[
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*.{py,pyi,c,cpp,h,rst,md,yml,yaml,json,test}]\ntrim_trailing_whitespace = true\ninsert_final_newline = true\nindent_style = space\n\n[*.{py,pyi,c,h,json,test}]\nindent_size = 4\n\n[*.{yml,yaml}]\nindent_size = 2\n"
  },
  {
    "path": ".git-blame-ignore-revs",
    "content": "# Adopt black and isort\n97c5ee99bc98dc475512e549b252b23a6e7e0997\n# Use builtin generics and PEP 604 for type annotations wherever possible (#13427)\n23ee1e7aff357e656e3102435ad0fe3b5074571e\n# Use variable annotations (#10723)\nf98f78216ba9d6ab68c8e69c19e9f3c7926c5efe\n# run pyupgrade (#12711)\nfc335cb16315964b923eb1927e3aad1516891c28\n# update black to 23.3.0 (#15059)\n4276308be01ea498d946a79554b4a10b1cf13ccb\n# Update black to 24.1.1 (#16847)\n8107e53158d83d30bb04d290ac10d8d3ccd344f8\n"
  },
  {
    "path": ".gitattributes",
    "content": "# We vendor typeshed from https://github.com/python/typeshed\nmypy/typeshed/** linguist-vendored\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/bug.md",
    "content": "---\nname: Bug Report\nabout: Submit a bug report\nlabels: \"bug\"\n---\n\n<!--\nIf you're not sure whether what you're experiencing is a mypy bug, please see the \"Question and Help\" form instead.\nPlease consider:\n\n- checking our common issues page: https://mypy.readthedocs.io/en/stable/common_issues.html\n- searching our issue tracker: https://github.com/python/mypy/issues to see if it's already been reported\n- asking on gitter chat: https://gitter.im/python/typing\n-->\n\n**Bug Report**\n\n<!--\nIf you're reporting a problem with a specific library function, the typeshed tracker is better suited for this report: https://github.com/python/typeshed/issues\n\nIf the project you encountered the issue in is open source, please provide a link to the project.\n-->\n\n(A clear and concise description of what the bug is.)\n\n**To Reproduce**\n\n```python\n# Ideally, a small sample program that demonstrates the problem.\n# Or even better, a reproducible playground link https://mypy-play.net/ (use the \"Gist\" button)\n```\n\n**Expected Behavior**\n\n<!--\nHow did you expect mypy to behave? It’s fine if you’re not sure your understanding is correct.\nWrite down what you thought would happen. If you expected no errors, delete this section.\n-->\n\n**Actual Behavior**\n\n<!-- What went wrong? Paste mypy's output. -->\n\n**Your Environment**\n\n<!-- Include as many relevant details about the environment you experienced the bug in -->\n\n- Mypy version used:\n- Mypy command-line flags:\n- Mypy configuration options from `mypy.ini` (and other config files):\n- Python version used:\n\n<!-- You can freely edit this text, please remove all the lines you believe are unnecessary. -->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/config.yml",
    "content": "contact_links:\n  - about: \"Please check the linked documentation page before filing new issues.\"\n    name: \"Common issues and solutions\"\n    url: \"https://mypy.readthedocs.io/en/stable/common_issues.html\"\n  - about: \"Please ask and answer any questions on the python/typing Gitter.\"\n    name: \"Questions or Chat\"\n    url: \"https://gitter.im/python/typing\"\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/crash.md",
    "content": "---\nname: Crash Report\nabout: Crash (traceback or \"INTERNAL ERROR\")\nlabels: \"crash\"\n---\n\n<!--\n  Use this form only if mypy reports an \"INTERNAL ERROR\" and/or gives a traceback.\n  Please include the traceback and all other messages below (use `mypy --show-traceback`).\n-->\n\n**Crash Report**\n\n(Tell us what happened.)\n\n**Traceback**\n\n```python-traceback\n(Insert traceback and other messages from mypy here -- use `--show-traceback`.)\n```\n\n**To Reproduce**\n\n(Write what you did to reproduce the crash.  Full source code is\nappreciated.  We also very much appreciate it if you try to narrow the\nsource down to a small stand-alone example.)\n\n```python\n# Ideally, a small sample program that demonstrates the problem.\n# Or even better, a reproducible playground link https://mypy-play.net/ (use the \"Gist\" button)\n```\n\n**Your Environment**\n\n<!-- Include as many relevant details about the environment you experienced the bug in -->\n\n- Mypy version used:\n- Mypy command-line flags:\n- Mypy configuration options from `mypy.ini` (and other config files):\n- Python version used:\n- Operating system and version:\n\n<!--\nYou can freely edit this text, please remove all the lines\nyou believe are unnecessary.\n-->\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/documentation.md",
    "content": "---\nname: Documentation\nabout: Report a problem with the documentation\nlabels: \"documentation\"\n---\n\n**Documentation**\n\n(A clear and concise description of the issue.)\n"
  },
  {
    "path": ".github/ISSUE_TEMPLATE/feature.md",
    "content": "---\nname: Feature\nabout: Submit a proposal for a new mypy feature\nlabels: \"feature\"\n---\n\n**Feature**\n\n<!-- Enter a clear and concise description of your feature proposal here. -->\n\n**Pitch**\n\n<!-- Please explain why this feature should be implemented and how it would be used. Add examples, if applicable. -->\n"
  },
  {
    "path": ".github/PULL_REQUEST_TEMPLATE.md",
    "content": "<!-- If this pull request fixes an issue, add \"Fixes #NNN\" with the issue number. -->\n\n(Explain how this PR changes mypy.)\n\n<!--\nChecklist:\n- Read the [Contributing Guidelines](https://github.com/python/mypy/blob/master/CONTRIBUTING.md)\n- Add tests for all changed behaviour.\n- If you can't add a test, please explain why and how you verified your changes work.\n- Make sure CI passes.\n- Please do not force push to the PR once it has been reviewed.\n-->\n"
  },
  {
    "path": ".github/workflows/build_wheels.yml",
    "content": "name: Trigger wheel build\n\non:\n  push:\n    branches: [main, master, 'release*']\n    tags: ['*']\n\npermissions:\n  contents: read\n\njobs:\n  build-wheels:\n    if: github.repository == 'python/mypy'\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          persist-credentials: false\n      - uses: actions/setup-python@v5\n        with:\n          python-version: '3.11'\n      - name: Trigger script\n        env:\n          WHEELS_PUSH_TOKEN: ${{ secrets.WHEELS_PUSH_TOKEN }}\n        run: ./misc/trigger_wheel_build.sh\n"
  },
  {
    "path": ".github/workflows/docs.yml",
    "content": "name: Check documentation build\n\non:\n  workflow_dispatch:\n  push:\n    branches: [main, master, 'release*']\n    tags: ['*']\n  pull_request:\n    paths:\n    - 'docs/**'\n    # We now have a docs check that fails if any error codes don't have documentation,\n    # so it's important to do the docs build on all PRs touching mypy/errorcodes.py\n    # in case somebody's adding a new error code without any docs\n    - 'mypy/errorcodes.py'\n    # Part of the documentation is automatically generated from the options\n    # definitions in mypy/main.py\n    - 'mypy/main.py'\n    - 'mypyc/doc/**'\n    - '**/*.rst'\n    - '**/*.md'\n    - CREDITS\n    - LICENSE\n\npermissions:\n  contents: read\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}\n  cancel-in-progress: true\n\njobs:\n  docs:\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    env:\n      TOXENV: docs\n      TOX_SKIP_MISSING_INTERPRETERS: False\n      VERIFY_MYPY_ERROR_CODES: 1\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          persist-credentials: false\n      - uses: actions/setup-python@v5\n        with:\n          python-version: '3.12'\n      - name: Install tox\n        run: pip install tox==4.26.0\n      - name: Setup tox environment\n        run: tox run -e ${{ env.TOXENV }} --notest\n      - name: Test\n        run: tox run -e ${{ env.TOXENV }} --skip-pkg-install\n"
  },
  {
    "path": ".github/workflows/mypy_primer.yml",
    "content": "name: Run mypy_primer\n\non:\n  # Only run on PR, since we diff against master\n  pull_request:\n    paths-ignore:\n    - 'docs/**'\n    - '**/*.rst'\n    - '**/*.md'\n    - 'misc/**'\n    - 'mypyc/**'\n    - 'mypy/stubtest.py'\n    - 'mypy/stubgen.py'\n    - 'mypy/stubgenc.py'\n    - 'mypy/test/**'\n    - 'test-data/**'\n\npermissions:\n  contents: read\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}\n  cancel-in-progress: true\n\njobs:\n  mypy_primer:\n    name: Run mypy_primer\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        shard-index: [0, 1, 2, 3, 4, 5]\n      fail-fast: false\n    timeout-minutes: 60\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          path: mypy_to_test\n          fetch-depth: 0\n          persist-credentials: false\n      - uses: actions/setup-python@v5\n        with:\n          python-version: \"3.14\"\n      - name: Install dependencies\n        run: |\n          python -m pip install -U pip\n          pip install git+https://github.com/hauntsaninja/mypy_primer.git\n      - name: Run mypy_primer\n        shell: bash\n        run: |\n          cd mypy_to_test\n          echo \"new commit\"\n          git rev-list --format=%s --max-count=1 $GITHUB_SHA\n\n          MERGE_BASE=$(git merge-base $GITHUB_SHA origin/$GITHUB_BASE_REF)\n          git checkout -b base_commit $MERGE_BASE\n          echo \"base commit\"\n          git rev-list --format=%s --max-count=1 base_commit\n\n          echo ''\n          cd ..\n          # fail action if exit code isn't zero or one\n          (\n            mypy_primer \\\n            --repo mypy_to_test \\\n            --new $GITHUB_SHA --old base_commit \\\n            --num-shards 6 --shard-index ${{ matrix.shard-index }} \\\n            --debug \\\n            --additional-flags=\"--debug-serialize\" \\\n            --output concise \\\n            --mypy-install-librt \\\n            | tee diff_${{ matrix.shard-index }}.txt\n          ) || [ $? -eq 1 ]\n      - if: ${{ matrix.shard-index == 0 }}\n        name: Save PR number\n        run: |\n          echo ${{ github.event.pull_request.number }} | tee pr_number.txt\n      - name: Upload mypy_primer diff + PR number\n        uses: actions/upload-artifact@v4\n        if: ${{ matrix.shard-index == 0 }}\n        with:\n          name: mypy_primer_diffs-${{ matrix.shard-index }}\n          path: |\n            diff_${{ matrix.shard-index }}.txt\n            pr_number.txt\n      - name: Upload mypy_primer diff\n        uses: actions/upload-artifact@v4\n        if: ${{ matrix.shard-index != 0 }}\n        with:\n          name: mypy_primer_diffs-${{ matrix.shard-index }}\n          path: diff_${{ matrix.shard-index }}.txt\n\n  join_artifacts:\n    name: Join artifacts\n    runs-on: ubuntu-latest\n    needs: [mypy_primer]\n    steps:\n      - name: Merge artifacts\n        uses: actions/upload-artifact/merge@v4\n        with:\n          name: mypy_primer_diffs\n          pattern: mypy_primer_diffs-*\n          delete-merged: true\n"
  },
  {
    "path": ".github/workflows/mypy_primer_comment.yml",
    "content": "name: Comment with mypy_primer diff\n\non:  # zizmor: ignore[dangerous-triggers]\n  workflow_run:\n    workflows:\n      - Run mypy_primer\n    types:\n      - completed\n\npermissions: {}\n\njobs:\n  comment:\n    name: Comment PR from mypy_primer\n    runs-on: ubuntu-latest\n    permissions:\n      contents: read\n      pull-requests: write\n    if: ${{ github.event.workflow_run.conclusion == 'success' }}\n    steps:\n      - name: Download diffs\n        uses: actions/github-script@v7\n        with:\n          script: |\n            const fs = require('fs');\n            const artifacts = await github.rest.actions.listWorkflowRunArtifacts({\n               owner: context.repo.owner,\n               repo: context.repo.repo,\n               run_id: ${{ github.event.workflow_run.id }},\n            });\n            const [matchArtifact] = artifacts.data.artifacts.filter((artifact) =>\n              artifact.name == \"mypy_primer_diffs\");\n\n            const download = await github.rest.actions.downloadArtifact({\n               owner: context.repo.owner,\n               repo: context.repo.repo,\n               artifact_id: matchArtifact.id,\n               archive_format: \"zip\",\n            });\n            fs.writeFileSync(\"diff.zip\", Buffer.from(download.data));\n\n      - run: unzip diff.zip\n      - run: |\n          cat diff_*.txt | tee fulldiff.txt\n\n      - name: Post comment\n        id: post-comment\n        uses: actions/github-script@v7\n        with:\n          github-token: ${{ secrets.GITHUB_TOKEN }}\n          script: |\n            const MAX_CHARACTERS = 50000\n            const MAX_CHARACTERS_PER_PROJECT = MAX_CHARACTERS / 3\n\n            const fs = require('fs')\n            let data = fs.readFileSync('fulldiff.txt', { encoding: 'utf8' })\n\n            function truncateIfNeeded(original, maxLength) {\n              if (original.length <= maxLength) {\n                return original\n              }\n              let truncated = original.substring(0, maxLength)\n              // further, remove last line that might be truncated\n              truncated = truncated.substring(0, truncated.lastIndexOf('\\n'))\n              let lines_truncated = original.split('\\n').length - truncated.split('\\n').length\n              return `${truncated}\\n\\n... (truncated ${lines_truncated} lines) ...`\n            }\n\n            const projects = data.split('\\n\\n')\n            // don't let one project dominate\n            data = projects.map(project => truncateIfNeeded(project, MAX_CHARACTERS_PER_PROJECT)).join('\\n\\n')\n            // posting comment fails if too long, so truncate\n            data = truncateIfNeeded(data, MAX_CHARACTERS)\n\n            console.log(\"Diff from mypy_primer:\")\n            console.log(data)\n\n            let body\n            if (data.trim()) {\n              body = 'Diff from [mypy_primer](https://github.com/hauntsaninja/mypy_primer), showing the effect of this PR on open source code:\\n```diff\\n' + data + '```'\n            } else {\n              body = \"According to [mypy_primer](https://github.com/hauntsaninja/mypy_primer), this change doesn't affect type check results on a corpus of open source code. ✅\"\n            }\n            const prNumber = parseInt(fs.readFileSync(\"pr_number.txt\", { encoding: \"utf8\" }))\n            await github.rest.issues.createComment({\n              issue_number: prNumber,\n              owner: context.repo.owner,\n              repo: context.repo.repo,\n              body\n            })\n            return prNumber\n\n      - name: Hide old comments\n        # v0.4.0\n        uses: kanga333/comment-hider@c12bb20b48aeb8fc098e35967de8d4f8018fffdf\n        with:\n          github_token: ${{ secrets.GITHUB_TOKEN }}\n          leave_visible: 1\n          issue_number: ${{ steps.post-comment.outputs.result }}\n"
  },
  {
    "path": ".github/workflows/sync_typeshed.yml",
    "content": "name: Sync typeshed\n\non:\n  workflow_dispatch:\n  schedule:\n    - cron: \"0 0 1,15 * *\"\n\npermissions: {}\n\njobs:\n  sync_typeshed:\n    name: Sync typeshed\n    if: github.repository == 'python/mypy'\n    runs-on: ubuntu-latest\n    permissions:\n      contents: write\n      pull-requests: write\n    timeout-minutes: 10\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          fetch-depth: 0\n          persist-credentials: true  # needed to `git push` the PR branch\n        # TODO: use whatever solution ends up working for\n        # https://github.com/python/typeshed/issues/8434\n      - uses: actions/setup-python@v5\n        with:\n          python-version: \"3.10\"\n      - name: git config\n        run: |\n          git config --global user.name mypybot\n          git config --global user.email '<>'\n      - name: Sync typeshed\n        run: |\n          python -m pip install requests==2.28.1\n          GITHUB_TOKEN=${{ secrets.GITHUB_TOKEN }} python misc/sync-typeshed.py --make-pr\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: Tests\n\non:\n  workflow_dispatch:\n  push:\n    branches: [main, master, 'release*']\n    tags: ['*']\n  pull_request:\n    paths-ignore:\n    - 'docs/**'\n    - 'mypyc/doc/**'\n    - '**/*.rst'\n    - '**/*.md'\n    - .gitignore\n    - CREDITS\n    - LICENSE\n\npermissions:\n  contents: read\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}\n  cancel-in-progress: true\n\njobs:\n  main:\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        include:\n        # Make sure to run mypyc compiled unit tests for both\n        # the oldest and newest supported Python versions\n        - name: Test suite with py310-ubuntu, mypyc-compiled\n          python: '3.10'\n          os: ubuntu-24.04-arm\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n          test_mypyc: true\n        - name: Test suite with py311-ubuntu\n          python: '3.11'\n          os: ubuntu-24.04-arm\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n        - name: Test suite with py312-ubuntu\n          python: '3.12'\n          os: ubuntu-24.04-arm\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n        - name: Test suite with py313-ubuntu, mypyc-compiled\n          python: '3.13'\n          os: ubuntu-24.04-arm\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n          test_mypyc: true\n        - name: Test suite with py314-ubuntu, mypyc-compiled\n          python: '3.14'\n          os: ubuntu-24.04-arm\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n          test_mypyc: true\n        - name: Test suite with py314t-ubuntu, mypyc-compiled\n          python: '3.14t'\n          os: ubuntu-24.04-arm\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n          test_mypyc: true\n        - name: Test suite with py314-windows-64\n          python: '3.14'\n          os: windows-latest\n          toxenv: py\n          tox_extra_args: \"-n 4\"\n\n        # - name: Test suite with py315-dev-ubuntu\n        #   python: '3.15-dev'\n        #   os: ubuntu-24.04-arm\n        #   toxenv: py\n        #   tox_extra_args: \"-n 4\"\n        #   # allow_failure: true\n        #   test_mypyc: true\n\n        - name: mypyc runtime tests with py313-macos\n          python: '3.13'\n          os: macos-latest\n          toxenv: py\n          tox_extra_args: \"-n 3 mypyc/test/test_run.py mypyc/test/test_external.py\"\n\n        - name: mypyc runtime tests with py310-ubuntu\n          python: '3.10'\n          os: ubuntu-latest\n          toxenv: py\n          tox_extra_args: \"-n 3 mypyc/test/test_run.py mypyc/test/test_external.py\"\n\n        # This is broken. See\n        # - https://github.com/python/mypy/issues/17819\n        # - https://github.com/python/mypy/pull/17822\n        # - name: mypyc runtime tests with py310-debug-build-ubuntu\n        #   python: '3.10'\n        #   os: ubuntu-latest\n        #   toxenv: py\n        #   tox_extra_args: \"-n 4 mypyc/test/test_run.py mypyc/test/test_external.py\"\n        #   debug_build: true\n\n        - name: Parallel tests with py314-ubuntu, interpreted\n          python: '3.14'\n          os: ubuntu-24.04-arm\n          toxenv: py\n          tox_extra_args: \"-n 4 --mypy-num-workers=4 mypy/test/testcheck.py\"\n        - name: Parallel tests with py314-ubuntu, mypyc-compiled\n          python: '3.14'\n          os: ubuntu-24.04-arm\n          toxenv: py\n          tox_extra_args: \"-n 4 --mypy-num-workers=4 mypy/test/testcheck.py\"\n          test_mypyc: true\n        - name: Parallel tests with py314-windows-64, interpreted\n          python: '3.14'\n          os: windows-latest\n          toxenv: py\n          tox_extra_args: \"-n 2 --mypy-num-workers=2 mypy/test/testcheck.py -k 'incremental or modules or classes'\"\n\n        - name: Type check our own code (py310-ubuntu)\n          python: '3.10'\n          os: ubuntu-latest\n          toxenv: type\n        - name: Type check our own code (py310-windows-64)\n          python: '3.10'\n          os: windows-latest\n          toxenv: type\n\n          # We also run these checks with pre-commit in CI,\n          # but it's useful to run them with tox too,\n          # to ensure the tox env works as expected\n        - name: Formatting and code style with Black + ruff\n          python: '3.10'\n          os: ubuntu-latest\n          toxenv: lint\n\n    name: ${{ matrix.name }}\n    timeout-minutes: 60\n    env:\n      TOX_SKIP_MISSING_INTERPRETERS: False\n      # Rich (pip) -- Disable color for windows + pytest\n      FORCE_COLOR: ${{ !(startsWith(matrix.os, 'windows-') && startsWith(matrix.toxenv, 'py')) && 1 || 0 }}\n      # Tox\n      PY_COLORS: 1\n      # Python -- Disable argparse help colors (3.14+)\n      PYTHON_COLORS: 0\n      # Mypy (see https://github.com/python/mypy/issues/7771)\n      TERM: xterm-color\n      MYPY_FORCE_COLOR: 1\n      MYPY_FORCE_TERMINAL_WIDTH: 200\n      # Pytest\n      PYTEST_ADDOPTS: --color=yes\n\n    steps:\n    - uses: actions/checkout@v4\n      with:\n        persist-credentials: false\n\n    - name: Latest dev build\n      if: ${{ endsWith(matrix.python, '-dev') }}\n      run: |\n          git clone --depth 1 https://github.com/python/cpython.git /tmp/cpython --branch $( echo ${{ matrix.python }} | sed 's/-dev//' )\n          cd /tmp/cpython\n          echo git rev-parse HEAD; git rev-parse HEAD\n          git show --no-patch\n          sudo apt-get update -q\n          sudo apt-get install -q -y --no-install-recommends \\\n            build-essential gdb lcov libbz2-dev libffi-dev libgdbm-dev liblzma-dev libncurses5-dev \\\n            libreadline6-dev libsqlite3-dev libssl-dev lzma lzma-dev tk-dev uuid-dev zlib1g-dev\n          ./configure --prefix=/opt/pythondev\n          make -j$(nproc)\n          sudo make install\n          sudo ln -s /opt/pythondev/bin/python3 /opt/pythondev/bin/python\n          sudo ln -s /opt/pythondev/bin/pip3 /opt/pythondev/bin/pip\n          echo \"/opt/pythondev/bin\" >> $GITHUB_PATH\n    - name: Debug build\n      if: ${{ matrix.debug_build }}\n      run: |\n          git clone --depth 1 https://github.com/python/cpython.git /tmp/cpython --branch ${{ matrix.python }}\n          cd /tmp/cpython\n          echo git rev-parse HEAD; git rev-parse HEAD\n          git show --no-patch\n          sudo apt-get update -q\n          sudo apt-get install -q -y --no-install-recommends \\\n            build-essential gdb lcov libbz2-dev libffi-dev libgdbm-dev liblzma-dev libncurses5-dev \\\n            libreadline6-dev libsqlite3-dev libssl-dev lzma lzma-dev tk-dev uuid-dev zlib1g-dev\n          ./configure CFLAGS=\"-DPy_DEBUG -DPy_TRACE_REFS -DPYMALLOC_DEBUG\" --with-pydebug -with-trace-refs --prefix=/opt/pythondev\n          make -j$(nproc)\n          sudo make install\n          sudo ln -s /opt/pythondev/bin/python3 /opt/pythondev/bin/python\n          sudo ln -s /opt/pythondev/bin/pip3 /opt/pythondev/bin/pip\n          echo \"/opt/pythondev/bin\" >> $GITHUB_PATH\n    - uses: actions/setup-python@v5\n      if: ${{ !(matrix.debug_build || endsWith(matrix.python, '-dev')) }}\n      with:\n        python-version: ${{ matrix.python }}\n\n    - name: Install tox\n      run: |\n        echo PATH; echo $PATH\n        echo which python; which python\n        echo which pip; which pip\n        echo python version; python -c 'import sys; print(sys.version)'\n        echo debug build; python -c 'import sysconfig; print(bool(sysconfig.get_config_var(\"Py_DEBUG\")))'\n        echo os.cpu_count; python -c 'import os; print(os.cpu_count())'\n        echo os.sched_getaffinity; python -c 'import os; print(len(getattr(os, \"sched_getaffinity\", lambda *args: [])(0)))'\n        pip install tox==4.26.0\n\n    - name: Compiled with mypyc\n      if: ${{ matrix.test_mypyc }}\n      run: |\n        pip install -r test-requirements.txt\n        CC=clang MYPYC_OPT_LEVEL=0 MYPY_USE_MYPYC=1 pip install -e .\n\n    - name: Setup tox environment\n      run: |\n        tox run -e ${{ matrix.toxenv }} --notest\n    - name: Test\n      run: tox run -e ${{ matrix.toxenv }} --skip-pkg-install -- ${{ matrix.tox_extra_args }}\n      continue-on-error: ${{ matrix.allow_failure == 'true' }}\n\n    - name: Mark as success (check failures manually)\n      if: ${{ matrix.allow_failure == 'true' }}\n      run: exit 0\n\n  python_32bits:\n    runs-on: ubuntu-latest\n    name: Test mypyc suite with 32-bit Python\n    timeout-minutes: 60\n    env:\n      TOX_SKIP_MISSING_INTERPRETERS: False\n      # Rich (pip)\n      FORCE_COLOR: 1\n      # Tox\n      PY_COLORS: 1\n      # Mypy (see https://github.com/python/mypy/issues/7771)\n      TERM: xterm-color\n      MYPY_FORCE_COLOR: 1\n      MYPY_FORCE_TERMINAL_WIDTH: 200\n      # Pytest\n      PYTEST_ADDOPTS: --color=yes\n      CXX: i686-linux-gnu-g++\n      CC: i686-linux-gnu-gcc\n    steps:\n      - uses: actions/checkout@v4\n        with:\n          persist-credentials: false\n      - name: Install 32-bit build dependencies\n        run: |\n          sudo dpkg --add-architecture i386 && \\\n          sudo apt-get update && sudo apt-get install -y \\\n            zlib1g-dev:i386 \\\n            libgcc-s1:i386 \\\n            g++-i686-linux-gnu \\\n            gcc-i686-linux-gnu \\\n            libffi-dev:i386 \\\n            libssl-dev:i386 \\\n            libbz2-dev:i386 \\\n            libncurses-dev:i386 \\\n            libreadline-dev:i386 \\\n            libsqlite3-dev:i386 \\\n            liblzma-dev:i386 \\\n            uuid-dev:i386\n      - name: Compile, install, and activate 32-bit Python\n        uses: gabrielfalcao/pyenv-action@v13\n        with:\n          default: 3.11.1\n          command: python -c \"import platform; print(f'{platform.architecture()=} {platform.machine()=}');\"\n      - name: Install tox\n        run: pip install tox==4.26.0\n      - name: Setup tox environment\n        run: tox run -e py --notest\n      - name: Test\n        run: tox run -e py --skip-pkg-install -- -n 4 mypyc/test/\n"
  },
  {
    "path": ".github/workflows/test_stubgenc.yml",
    "content": "name: Test stubgenc on pybind11_fixtures\n\non:\n  workflow_dispatch:\n  push:\n    branches: [main, master, 'release*']\n    tags: ['*']\n  pull_request:\n    paths:\n    - 'misc/test-stubgenc.sh'\n    - 'mypy/stubgenc.py'\n    - 'mypy/stubdoc.py'\n    - 'mypy/stubutil.py'\n    - 'test-data/pybind11_fixtures/**'\n\npermissions:\n  contents: read\n\nconcurrency:\n  group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }}\n  cancel-in-progress: true\n\njobs:\n  stubgenc:\n    # Check stub file generation for a small pybind11 project\n    # (full text match is required to pass)\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    steps:\n\n    - uses: actions/checkout@v4\n      with:\n        persist-credentials: false\n\n    - name: Setup 🐍 3.10\n      uses: actions/setup-python@v5\n      with:\n        python-version: '3.10'\n\n    - name: Test stubgenc\n      run: misc/test-stubgenc.sh\n"
  },
  {
    "path": ".gitignore",
    "content": "build/\n__pycache__\n*.py[cod]\n*~\n/build\n/env*/\ndocs/build/\ndocs/source/_build\nmypyc/doc/_build\n*.iml\n/out/\n.venv*\nvenv/\n.mypy_cache/\n.incremental_checker_cache.json\n.cache\ntest-data/packages/.pip_lock\ndmypy.json\n.dmypy.json\n/.mypyc_test_output\n\n# Packages\n*.egg\n*.egg-info\n*.eggs\n\n# IDEs\n.idea\n.vscode\n\n# vim temporary files\n.*.sw?\n*.sw?\n\n# Operating Systems\n.DS_Store\n\n# Coverage Files\nhtmlcov\n.coverage*\n\n# pytest cache\n.pytest_cache/\n\n# virtualenv\n.Python\nbin/\nlib/\ninclude/\n.python-version\npyvenv.cfg\n\n.tox\npip-wheel-metadata\n\n\ntest_capi\n*.o\n*.a\ntest_capi\n/mypyc/lib-rt/build/\n/mypyc/lib-rt/*.so\n"
  },
  {
    "path": ".pre-commit-config.yaml",
    "content": "exclude: '^(mypyc/external/)|(mypy/typeshed/)|misc/typeshed_patches'  # Exclude all vendored code from lints\nrepos:\n  - repo: https://github.com/pre-commit/pre-commit-hooks\n    rev: v5.0.0\n    hooks:\n      - id: trailing-whitespace\n      - id: end-of-file-fixer\n  - repo: https://github.com/psf/black-pre-commit-mirror\n    rev: 26.1.0\n    hooks:\n      - id: black\n        exclude: '^(test-data/)'\n  - repo: https://github.com/astral-sh/ruff-pre-commit\n    rev: v0.14.3\n    hooks:\n      - id: ruff-check\n        args: [--exit-non-zero-on-fix]\n  - repo: https://github.com/python-jsonschema/check-jsonschema\n    rev: 0.32.1\n    hooks:\n      - id: check-github-workflows\n      - id: check-github-actions\n      - id: check-readthedocs\n  - repo: https://github.com/codespell-project/codespell\n    rev: v2.4.1\n    hooks:\n      - id: codespell\n        args:\n          - --ignore-words-list=HAX,ccompiler,ot,statics,whet,zar\n        exclude: ^(mypy/test/|mypy/typeshed/|mypyc/test-data/|test-data/).+$\n  - repo: https://github.com/rhysd/actionlint\n    rev: v1.7.7\n    hooks:\n      - id: actionlint\n        args: [\n          -ignore=property \"debug_build\" is not defined,\n          -ignore=property \"allow_failure\" is not defined,\n          -ignore=SC2(046|086),\n        ]\n        additional_dependencies:\n          # actionlint has a shellcheck integration which extracts shell scripts in `run:` steps from GitHub Actions\n          # and checks these with shellcheck. This is arguably its most useful feature,\n          # but the integration only works if shellcheck is installed\n          - \"github.com/wasilibs/go-shellcheck/cmd/shellcheck@v0.11.1\"\n  - repo: https://github.com/woodruffw/zizmor-pre-commit\n    rev: v1.5.2\n    hooks:\n      - id: zizmor\n  - repo: local\n    hooks:\n      - id: bad-pr-link\n        name: Bad PR link\n        description: Detect PR links text that don't match their URL\n        language: pygrep\n        entry: '\\[(\\d+)\\]\\(https://github.com/python/mypy/pull/(?!\\1/?\\))\\d+/?\\)'\n        files: CHANGELOG.md\n  # Should be the last one:\n  - repo: meta\n    hooks:\n      - id: check-hooks-apply\n      - id: check-useless-excludes\n\nci:\n  autoupdate_schedule: quarterly\n"
  },
  {
    "path": ".readthedocs.yaml",
    "content": "# Read the Docs configuration file\n# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details\n\nversion: 2\n\nbuild:\n  os: ubuntu-22.04\n  tools:\n    python: \"3.11\"\n\nsphinx:\n   configuration: docs/source/conf.py\n\nformats: [pdf, htmlzip, epub]\n\npython:\n   install:\n   - requirements: docs/requirements-docs.txt\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Mypy Release Notes\r\n\r\n## Next Release\r\n\r\n### Better narrowing\r\n\r\nMypy's implementation of narrowing has been substantially reworked. Mypy will now narrow more\r\naggressively, more consistently, and more correctly. In particular, you are likely to notice new\r\nnarrowing behavior in equality expressions (`==`), containment expressions (`in`),\r\nmatch statements, and additional expressions providing type guards.\r\n\r\nNote that mypy (and other Python type checkers) do not model the potential for various non-local\r\noperations to invalidate narrowing assumptions. This means mypy may conclude that some of your code\r\nis [unreachable](https://mypy.readthedocs.io/en/stable/common_issues.html#unreachable-code) and\r\navoid further checking of it. The `--warn-unreachable` flag is useful for highlighting these cases.\r\nTo reset narrowing, you can insert dummy reassignments, for instance `var = var` will reset\r\nall narrowing of `var.attr`.\r\n\r\nFuture work includes better narrowing on initial assignments, more narrowing to `Literal` types,\r\nand better checking of unreachable code.\r\n\r\nContributed by Shantanu Jain.\r\n\r\n- Rework narrowing logic for equality and identity (Shantanu, PR [20492](https://github.com/python/mypy/pull/20492))\r\n- Refactor equality and identity narrowing for clarity (Shantanu, PR [20595](https://github.com/python/mypy/pull/20595))\r\n- Treat NotImplemented as a singleton type (Shantanu, PR [20601](https://github.com/python/mypy/pull/20601))\r\n- Improve narrowing logic for Enum int and str subclasses (Shantanu, PR [20609](https://github.com/python/mypy/pull/20609))\r\n- Narrow types based on collection containment (Shantanu, PR [20602](https://github.com/python/mypy/pull/20602))\r\n- Refactor and improve narrowing for type(x) == t checks (Shantanu, PR [20634](https://github.com/python/mypy/pull/20634))\r\n- Narrow for type expr comparisons to type exprs (Shantanu, PR [20639](https://github.com/python/mypy/pull/20639))\r\n- Narrowing for comparisons against `x.__class__` (Shantanu, PR [20642](https://github.com/python/mypy/pull/20642))\r\n- Better narrowing with custom equality (Shantanu, PR [20643](https://github.com/python/mypy/pull/20643))\r\n- Use a single pass for core narrowing logic, add comments (Shantanu, PR [20659](https://github.com/python/mypy/pull/20659))\r\n- Narrowing for final type objects (Shantanu, PR [20661](https://github.com/python/mypy/pull/20661))\r\n- Avoid narrowing type[T] (Shantanu, PR [20662](https://github.com/python/mypy/pull/20662))\r\n- Avoid widening to Any for checks like `type(x) is type(y: Any)` (Shantanu, PR [20663](https://github.com/python/mypy/pull/20663))\r\n- Preserve some lost narrowing, cleanup (Shantanu, PR [20674](https://github.com/python/mypy/pull/20674))\r\n- Fix narrowing related code for types with overloaded `__new__` (Shantanu, PR [20676](https://github.com/python/mypy/pull/20676))\r\n- Fix isinstance with unions of tuples (Shantanu, PR [20677](https://github.com/python/mypy/pull/20677))\r\n- Fix regression to chained containment (Shantanu, PR [20688](https://github.com/python/mypy/pull/20688))\r\n- Improve else handling with custom equality (Shantanu, PR [20692](https://github.com/python/mypy/pull/20692))\r\n- Better model runtime in isinstance and type checks (Shantanu, PR [20675](https://github.com/python/mypy/pull/20675))\r\n- Use --warn-unreachable and --strict-equality in more tests (Shantanu, PR [20707](https://github.com/python/mypy/pull/20707))\r\n- Model exact narrowing with type(x) checks (Shantanu, PR [20703](https://github.com/python/mypy/pull/20703))\r\n- Short term fix for bytes narrowing (Shantanu, PR [20704](https://github.com/python/mypy/pull/20704))\r\n- Preserve narrowing in unreachable code (Shantanu, PR [20710](https://github.com/python/mypy/pull/20710))\r\n- Fix bug when narrowing union containing custom eq against custom eq (Shantanu, PR [20754](https://github.com/python/mypy/pull/20754))\r\n- Fix narrowing for unions (Shantanu, PR [20728](https://github.com/python/mypy/pull/20728))\r\n- Unsoundly narrow away from None with custom eq (Shantanu, PR [20756](https://github.com/python/mypy/pull/20756))\r\n- Improve narrowing with numeric types (Shantanu, PR [20727](https://github.com/python/mypy/pull/20727))\r\n- Fix narrowing with final type objects (Shantanu, PR [20743](https://github.com/python/mypy/pull/20743))\r\n- Further improve match statement narrowing against unions (Shantanu, PR [20744](https://github.com/python/mypy/pull/20744))\r\n- Avoid narrowing to NewType (Shantanu, PR [20766](https://github.com/python/mypy/pull/20766))\r\n- Better match narrowing for irrefutable sequence patterns (Shantanu, PR [20782](https://github.com/python/mypy/pull/20782))\r\n- Remove prohibit_none_typevar_overlap (Shantanu, PR [20864](https://github.com/python/mypy/pull/20864))\r\n- Fix match statement narrowing reachability for tuples (Shantanu, PR [20896](https://github.com/python/mypy/pull/20896))\r\n- Better handling of generics when narrowing (Shantanu, PR [20863](https://github.com/python/mypy/pull/20863))\r\n- Better match narrowing for type objects (Shantanu, PR [20872](https://github.com/python/mypy/pull/20872))\r\n- Narrow Callable generic return types (Shantanu, PR [20868](https://github.com/python/mypy/pull/20868))\r\n- Better match narrowing for unions of type objects (Shantanu, PR [20905](https://github.com/python/mypy/pull/20905))\r\n- Improve reachability in narrowing logic (Shantanu, PR [20660](https://github.com/python/mypy/pull/20660))\r\n- Better match narrowing for irrefutable mapping patterns (Shantanu, PR [20906](https://github.com/python/mypy/pull/20906))\r\n- Fix match statement semantic reachability (Shantanu, PR [20968](https://github.com/python/mypy/pull/20968))\r\n- Add some additional narrowing test cases (Shantanu, PR [20598](https://github.com/python/mypy/pull/20598))\r\n- Move tests to check-narrowing , improve them slightly (Shantanu, PR [20637](https://github.com/python/mypy/pull/20637))\r\n- Add more tests for narrowing logic (Shantanu, PR [20672](https://github.com/python/mypy/pull/20672))\r\n- More testing related improvements and updates (Shantanu, PR [20709](https://github.com/python/mypy/pull/20709))\r\n- Add --warn-unreachable to more tests (Shantanu, PR [20977](https://github.com/python/mypy/pull/20977))\r\n\r\n### Drop Support for Python 3.9\r\n\r\nMypy no longer supports running with Python 3.9, which has reached end-of-life.\r\nWhen running mypy with Python 3.10+, it is still possible to type check code\r\nthat needs to support Python 3.9 with the `--python-version 3.9` argument.\r\nSupport for this will be dropped in the first half of 2026!\r\n\r\nContributed by Marc Mueller (PR [20156](https://github.com/python/mypy/pull/20156)).\r\n\r\n### Mypyc Accelerated Mypy Wheels for ARM Windows and Free Threading\r\n\r\nFor best performance, mypy can be compiled to C extension modules using mypyc. This makes\r\nmypy 3-5x faster than when interpreted with pure Python. We now build and upload mypyc\r\naccelerated mypy wheels for `win_arm64` and `cp314t-...` to PyPI, making it easy for Windows\r\nusers on ARM and those using the free theading builds for Python 3.14 to realise this speedup\r\n-- just `pip install` the latest mypy.\r\n\r\nContributed by Marc Mueller\r\n(PR [mypy_mypyc-wheels#106](https://github.com/mypyc/mypy_mypyc-wheels/pull/106),\r\nPR [mypy_mypyc-wheels#110](https://github.com/mypyc/mypy_mypyc-wheels/pull/110)).\r\n\r\n### Removed flags `--force-uppercase-builtins` and `--force-union-syntax`\r\n\r\nThe `--force-uppercase-builtins` flag was deprecated and has been a no-op since mypy 1.17.0.\r\nSince mypy has dropped support for Python 3.9, the `--force-union-syntax` flag is no longer\r\nnecessary.\r\n\r\nContributed by Marc Mueller (PR [20410](https://github.com/python/mypy/pull/20410))\r\nand (PR [20405](https://github.com/python/mypy/pull/20405)).\r\n\r\n## Mypy 1.19\r\n\r\nWe’ve just uploaded mypy 1.19.0 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)).\r\nMypy is a static type checker for Python. This release includes new features, performance\r\nimprovements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Python 3.9 Support Ending Soon\r\n\r\nThis is the last mypy feature release that supports Python 3.9, which reached\r\nend of life in October 2025.\r\n\r\n### Performance Improvements\r\n- Switch to a more dynamic SCC processing logic (Ivan Levkivskyi, PR [20053](https://github.com/python/mypy/pull/20053))\r\n- Speed up type aliases (Ivan Levkivskyi, PR [19810](https://github.com/python/mypy/pull/19810))\r\n\r\n### Fixed‑Format Cache Improvements\r\n\r\nMypy uses a cache by default to speed up incremental runs by reusing partial results\r\nfrom earlier runs. Mypy 1.18 added a new binary fixed-format cache representation as\r\nan experimental feature. The feature is no longer experimental, and we are planning\r\nto enable it by default in a future mypy release (possibly 1.20), since it's faster\r\nand uses less space than the original, JSON-based cache format. Use\r\n`--fixed-format-cache` to enable the fixed-format cache.\r\n\r\nMypy now has an extra dependency on the `librt` PyPI package, as it's needed for\r\ncache serialization and deserialization.\r\n\r\nMypy ships with a tool to convert fixed-format cache files to the old JSON format.\r\nExample of how to use this:\r\n```\r\n$ python -m mypy.exportjson .mypy_cache/.../my_module.data.ff\r\n```\r\n\r\nThis way existing use cases that parse JSON cache files can be supported when using\r\nthe new format, though an extra conversion step is needed.\r\n\r\nThis release includes these improvements:\r\n\r\n- Force-discard cache if cache format changed (Ivan Levkivskyi, PR [20152](https://github.com/python/mypy/pull/20152))\r\n- Add tool to convert binary cache files to JSON (Jukka Lehtosalo, PR [20071](https://github.com/python/mypy/pull/20071))\r\n- Use more efficient serialization format for long integers in cache files (Jukka Lehtosalo, PR [20151](https://github.com/python/mypy/pull/20151))\r\n- More robust packing of floats in fixed-format cache (Ivan Levkivskyi, PR [20150](https://github.com/python/mypy/pull/20150))\r\n- Use self-descriptive cache with type tags (Ivan Levkivskyi, PR [20137](https://github.com/python/mypy/pull/20137))\r\n- Use fixed format for cache metas (Ivan Levkivskyi, PR [20088](https://github.com/python/mypy/pull/20088))\r\n- Make metas more compact; fix indirect suppression (Ivan Levkivskyi, PR [20075](https://github.com/python/mypy/pull/20075))\r\n- Use dedicated tags for most common cached instances (Ivan Levkivskyi, PR [19762](https://github.com/python/mypy/pull/19762))\r\n\r\n### PEP 747: Annotating Type Forms\r\n\r\nMypy now recognizes `TypeForm[T]` as a type and implements\r\n[PEP 747](https://peps.python.org/pep-0747/). The feature is still experimental,\r\nand it's disabled by default. Use `--enable-incomplete-feature=TypeForm` to\r\nenable type forms. A type form object captures the type information provided by a\r\nruntime type expression. Example:\r\n\r\n```python\r\nfrom typing_extensions import TypeForm\r\n\r\ndef trycast[T](typx: TypeForm[T], value: object) -> T | None: ...\r\n\r\ndef example(o: object) -> None:\r\n    # 'int | str' below is an expression that represents a type.\r\n    # Unlike type[T], TypeForm[T] can be used with all kinds of types,\r\n    # including union types.\r\n    x = trycast(int | str, o)\r\n    if x is not None:\r\n        # Type of 'x' is 'int | str' here\r\n        ...\r\n```\r\n\r\nThis feature was contributed by David Foster (PR [19596](https://github.com/python/mypy/pull/19596)).\r\n\r\n### Fixes to Crashes\r\n- Do not push partial types to the binder (Stanislav Terliakov, PR [20202](https://github.com/python/mypy/pull/20202))\r\n- Fix crash on recursive tuple with Hashable (Ivan Levkivskyi, PR [20232](https://github.com/python/mypy/pull/20232))\r\n- Fix crash related to decorated functions (Stanislav Terliakov, PR [20203](https://github.com/python/mypy/pull/20203))\r\n- Do not abort constructing TypeAlias if only type parameters hold us back (Stanislav Terliakov, PR [20162](https://github.com/python/mypy/pull/20162))\r\n- Use the fallback for `ModuleSpec` early if it can never be resolved (Stanislav Terliakov, PR [20167](https://github.com/python/mypy/pull/20167))\r\n- Do not store deferred NamedTuple fields as redefinitions (Stanislav Terliakov, PR [20147](https://github.com/python/mypy/pull/20147))\r\n- Discard partial types remaining after inference failure (Stanislav Terliakov, PR [20126](https://github.com/python/mypy/pull/20126))\r\n- Fix an infinite recursion bug (Stanislav Terliakov, PR [20127](https://github.com/python/mypy/pull/20127))\r\n- Fix IsADirectoryError for namespace packages when using --linecoverage-report (wyattscarpenter, PR [20109](https://github.com/python/mypy/pull/20109))\r\n- Fix an internal error when creating cobertura output for namespace package (wyattscarpenter, PR [20112](https://github.com/python/mypy/pull/20112))\r\n- Allow type parameters reusing the name missing from current module (Stanislav Terliakov, PR [20081](https://github.com/python/mypy/pull/20081))\r\n- Prevent TypeGuardedType leak from narrowing declared type as part of type variable bound (Stanislav Terliakov, PR [20046](https://github.com/python/mypy/pull/20046))\r\n- Fix crash on invalid unpack in base class (Ivan Levkivskyi, PR [19962](https://github.com/python/mypy/pull/19962))\r\n- Traverse ParamSpec prefix where we should (Ivan Levkivskyi, PR [19800](https://github.com/python/mypy/pull/19800))\r\n- Fix daemon crash related to imports (Ivan Levkivskyi, PR [20271](https://github.com/python/mypy/pull/20271))\r\n\r\n### Mypyc: Support for `__getattr__`, `__setattr__`, and `__delattr__`\r\n\r\nMypyc now has partial support for `__getattr__`, `__setattr__` and\r\n`__delattr__` methods in native classes.\r\n\r\nNote that native attributes are not stored using `__dict__`. Setting attributes\r\ndirectly while bypassing `__setattr__` is possible by using\r\n`super().__setattr__(...)` or `object.__setattr__(...)`, but not via `__dict__`.\r\n\r\nExample:\r\n```python\r\nclass Demo:\r\n    _data: dict[str, str]\r\n\r\n    def __init__(self) -> None:\r\n        # Initialize data dict without calling our __setattr__\r\n        super().__setattr__(\"_data\", {})\r\n\r\n    def __setattr__(self, name: str, value: str) -> None:\r\n        print(f\"Setting {name} = {value!r}\")\r\n\r\n        if name == \"_data\":\r\n            raise AttributeError(\"'_data' cannot be set\")\r\n\r\n        self._data[name] = value\r\n\r\n    def __getattr__(self, name: str) -> str:\r\n        print(f\"Getting {name}\")\r\n\r\n        try:\r\n            return self._data[name]\r\n        except KeyError:\r\n            raise AttributeError(name)\r\n\r\nd = Demo()\r\nd.x = \"hello\"\r\nd.y = \"world\"\r\n\r\nprint(d.x)\r\nprint(d.y)\r\n```\r\n\r\nRelated PRs:\r\n- Generate `__setattr__` wrapper (Piotr Sawicki, PR [19937](https://github.com/python/mypy/pull/19937))\r\n- Generate `__getattr__` wrapper (Piotr Sawicki, PR [19909](https://github.com/python/mypy/pull/19909))\r\n- Support deleting attributes in `__setattr__` wrapper (Piotr Sawicki, PR [19997](https://github.com/python/mypy/pull/19997))\r\n\r\n### Miscellaneous Mypyc Improvements\r\n- Fix `__new__` in native classes with inheritance (Piotr Sawicki, PR [20302](https://github.com/python/mypy/pull/20302))\r\n- Fix crash on `super` in generator (Ivan Levkivskyi, PR [20291](https://github.com/python/mypy/pull/20291))\r\n- Fix calling base class async method using `super()` (Jukka Lehtosalo, PR [20254](https://github.com/python/mypy/pull/20254))\r\n- Fix async or generator methods in traits (Jukka Lehtosalo, PR [20246](https://github.com/python/mypy/pull/20246))\r\n- Optimize equality check with string literals (BobTheBuidler, PR [19883](https://github.com/python/mypy/pull/19883))\r\n- Fix inheritance of async defs (Jukka Lehtosalo, PR [20044](https://github.com/python/mypy/pull/20044))\r\n- Reject invalid `mypyc_attr` args (BobTheBuidler, PR [19963](https://github.com/python/mypy/pull/19963))\r\n- Optimize `isinstance` with tuple of primitive types (BobTheBuidler, PR [19949](https://github.com/python/mypy/pull/19949))\r\n- Optimize away first index check in for loops if length > 1 (BobTheBuidler, PR [19933](https://github.com/python/mypy/pull/19933))\r\n- Fix broken exception/cancellation handling in async def (Jukka Lehtosalo, PR [19951](https://github.com/python/mypy/pull/19951))\r\n- Transform `object.__new__` inside `__new__` (Piotr Sawicki, PR [19866](https://github.com/python/mypy/pull/19866))\r\n- Fix crash with NewType and other non-class types in incremental builds (Jukka Lehtosalo, PR [19837](https://github.com/python/mypy/pull/19837))\r\n- Optimize container creation from expressions with length known at compile time (BobTheBuidler, PR [19503](https://github.com/python/mypy/pull/19503))\r\n- Allow per-class free list to be used with inheritance (Jukka Lehtosalo, PR [19790](https://github.com/python/mypy/pull/19790))\r\n- Fix object finalization (Marc Mueller, PR [19749](https://github.com/python/mypy/pull/19749))\r\n- Allow defining a single-item free \"list\" for a native class (Jukka Lehtosalo, PR [19785](https://github.com/python/mypy/pull/19785))\r\n- Speed up unary \"not\" (Jukka Lehtosalo, PR [19774](https://github.com/python/mypy/pull/19774))\r\n\r\n### Stubtest Improvements\r\n- Check `_value_` for ellipsis-valued stub enum members (Stanislav Terliakov, PR [19760](https://github.com/python/mypy/pull/19760))\r\n- Include function name in overload assertion messages (Joren Hammudoglu, PR [20063](https://github.com/python/mypy/pull/20063))\r\n- Fix special case in analyzing function signature (iap, PR [19822](https://github.com/python/mypy/pull/19822))\r\n- Improve `allowlist` docs with better example (sobolevn, PR [20007](https://github.com/python/mypy/pull/20007))\r\n\r\n### Documentation Updates\r\n- Update duck type compatibility: mention strict-bytes and mypy 2.0 (wyattscarpenter, PR [20121](https://github.com/python/mypy/pull/20121))\r\n- Document `--enable-incomplete-feature TypeForm` (wyattscarpenter, PR [20173](https://github.com/python/mypy/pull/20173))\r\n- Change the inline TypedDict example (wyattscarpenter, PR [20172](https://github.com/python/mypy/pull/20172))\r\n- Replace `List` with built‑in `list` (PEP 585) (Thiago J. Barbalho, PR [20000](https://github.com/python/mypy/pull/20000))\r\n- Improve junit documentation (wyattscarpenter, PR [19867](https://github.com/python/mypy/pull/19867))\r\n\r\n### Other Notable Fixes and Improvements\r\n- Fix annotated with function as type keyword list parameter (KarelKenens, PR [20094](https://github.com/python/mypy/pull/20094))\r\n- Fix errors for raise NotImplemented (Shantanu, PR [20168](https://github.com/python/mypy/pull/20168))\r\n- Don't let help formatter line-wrap URLs (Frank Dana, PR [19825](https://github.com/python/mypy/pull/19825))\r\n- Do not cache fast container types inside lambdas (Stanislav Terliakov, PR [20166](https://github.com/python/mypy/pull/20166))\r\n- Respect force-union-syntax flag in error hint (Marc Mueller, PR [20165](https://github.com/python/mypy/pull/20165))\r\n- Fix type checking of dict type aliases (Shantanu, PR [20170](https://github.com/python/mypy/pull/20170))\r\n- Use pretty callable formatting more often for callable expressions (Theodore Ando, PR [20128](https://github.com/python/mypy/pull/20128))\r\n- Use dummy concrete type instead of `Any` when checking protocol variance (bzoracler, PR [20110](https://github.com/python/mypy/pull/20110))\r\n- PEP 696: Fix swapping TypeVars with defaults (Randolf Scholz, PR [19449](https://github.com/python/mypy/pull/19449))\r\n- Fix narrowing of class pattern with union type (Randolf Scholz, PR [19517](https://github.com/python/mypy/pull/19517))\r\n- Do not emit unreachable warnings for lines that return `NotImplemented` (Christoph Tyralla, PR [20083](https://github.com/python/mypy/pull/20083))\r\n- Fix matching against `typing.Callable` and `Protocol` types (Randolf Scholz, PR [19471](https://github.com/python/mypy/pull/19471))\r\n- Make `--pretty` work better on multi-line issues (A5rocks, PR [20056](https://github.com/python/mypy/pull/20056))\r\n- More precise return types for `TypedDict.get` (Randolf Scholz, PR [19897](https://github.com/python/mypy/pull/19897))\r\n- Prevent false unreachable warnings for `@final` instances that occur when strict optional checking is disabled (Christoph Tyralla, PR [20045](https://github.com/python/mypy/pull/20045))\r\n- Check class references to catch non-existent classes in match cases (A5rocks, PR [20042](https://github.com/python/mypy/pull/20042))\r\n- Do not sort unused error codes in unused error codes warning (wyattscarpenter, PR [20036](https://github.com/python/mypy/pull/20036))\r\n- Fix `[name-defined]` false positive in `class A[X, Y=X]:` case (sobolevn, PR [20021](https://github.com/python/mypy/pull/20021))\r\n- Filter SyntaxWarnings during AST parsing (Marc Mueller, PR [20023](https://github.com/python/mypy/pull/20023))\r\n- Make untyped decorator its own error code (wyattscarpenter, PR [19911](https://github.com/python/mypy/pull/19911))\r\n- Support error codes from plugins in options (Sigve Sebastian Farstad, PR [19719](https://github.com/python/mypy/pull/19719))\r\n- Allow returning Literals in `__new__` (James Hilton-Balfe, PR [15687](https://github.com/python/mypy/pull/15687))\r\n- Inverse interface freshness logic (Ivan Levkivskyi, PR [19809](https://github.com/python/mypy/pull/19809))\r\n- Do not report exhaustive-match after deferral (Stanislav Terliakov, PR [19804](https://github.com/python/mypy/pull/19804))\r\n- Make `untyped_calls_exclude` invalidate cache (Ivan Levkivskyi, PR [19801](https://github.com/python/mypy/pull/19801))\r\n- Add await to empty context hack (Stanislav Terliakov, PR [19777](https://github.com/python/mypy/pull/19777))\r\n- Consider non-empty enums assignable to Self (Stanislav Terliakov, PR [19779](https://github.com/python/mypy/pull/19779))\r\n\r\n### Typeshed updates\r\n\r\nPlease see [git log](https://github.com/python/typeshed/commits/main?after=ebce8d766b41fbf4d83cf47c1297563a9508ff60+0&branch=main&path=stdlib) for full list of standard library typeshed stub changes.\r\n\r\n### Mypy 1.19.1\r\n\r\n- Fix noncommutative joins with bounded TypeVars (Shantanu, PR [20345](https://github.com/python/mypy/pull/20345))\r\n- Respect output format for cached runs by serializing raw errors in cache metas (Ivan Levkivskyi, PR [20372](https://github.com/python/mypy/pull/20372))\r\n- Allow `types.NoneType` in match cases (A5rocks, PR [20383](https://github.com/python/mypy/pull/20383))\r\n- Fix mypyc generator regression with empty tuple (BobTheBuidler, PR [20371](https://github.com/python/mypy/pull/20371))\r\n- Fix crash involving Unpack-ed TypeVarTuple (Shantanu, PR [20323](https://github.com/python/mypy/pull/20323))\r\n- Fix crash on star import of redefinition (Ivan Levkivskyi, PR [20333](https://github.com/python/mypy/pull/20333))\r\n- Fix crash on typevar with forward ref used in other module (Ivan Levkivskyi, PR [20334](https://github.com/python/mypy/pull/20334))\r\n- Fail with an explicit error on PyPy (Ivan Levkivskyi, PR [20389](https://github.com/python/mypy/pull/20389))\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n- A5rocks\r\n- BobTheBuidler\r\n- bzoracler\r\n- Chainfire\r\n- Christoph Tyralla\r\n- David Foster\r\n- Frank Dana\r\n- Guo Ci\r\n- iap\r\n- Ivan Levkivskyi\r\n- James Hilton-Balfe\r\n- jhance\r\n- Joren Hammudoglu\r\n- Jukka Lehtosalo\r\n- KarelKenens\r\n- Kevin Kannammalil\r\n- Marc Mueller\r\n- Michael Carlstrom\r\n- Michael J. Sullivan\r\n- Piotr Sawicki\r\n- Randolf Scholz\r\n- Shantanu\r\n- Sigve Sebastian Farstad\r\n- sobolevn\r\n- Stanislav Terliakov\r\n- Stephen Morton\r\n- Theodore Ando\r\n- Thiago J. Barbalho\r\n- wyattscarpenter\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\n## Mypy 1.18\r\n\r\nWe’ve just uploaded mypy 1.18.1 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)).\r\nMypy is a static type checker for Python. This release includes new features, performance\r\nimprovements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Mypy Performance Improvements\r\n\r\nMypy 1.18.1 includes numerous performance improvements, resulting in about 40% speedup\r\ncompared to 1.17 when type checking mypy itself. In extreme cases, the improvement\r\ncan be 10x or higher. The list below is an overview of the various mypy optimizations.\r\nMany mypyc improvements (discussed in a separate section below) also improve performance.\r\n\r\nType caching optimizations have a small risk of causing regressions. When\r\nreporting issues with unexpected inferred types, please also check if\r\n`--disable-expression-cache` will work around the issue, as it turns off some of\r\nthese optimizations.\r\n\r\n- Improve self check performance by 1.8% (Jukka Lehtosalo, PR [19768](https://github.com/python/mypy/pull/19768), [19769](https://github.com/python/mypy/pull/19769), [19770](https://github.com/python/mypy/pull/19770))\r\n- Optimize fixed-format deserialization (Ivan Levkivskyi, PR [19765](https://github.com/python/mypy/pull/19765))\r\n- Use macros to optimize fixed-format deserialization (Ivan Levkivskyi, PR [19757](https://github.com/python/mypy/pull/19757))\r\n- Two additional micro‑optimizations (Ivan Levkivskyi, PR [19627](https://github.com/python/mypy/pull/19627))\r\n- Another set of micro‑optimizations (Ivan Levkivskyi, PR [19633](https://github.com/python/mypy/pull/19633))\r\n- Cache common types (Ivan Levkivskyi, PR [19621](https://github.com/python/mypy/pull/19621))\r\n- Skip more method bodies in third‑party libraries for speed (Ivan Levkivskyi, PR [19586](https://github.com/python/mypy/pull/19586))\r\n- Simplify the representation of callable types (Ivan Levkivskyi, PR [19580](https://github.com/python/mypy/pull/19580))\r\n- Add cache for types of some expressions (Ivan Levkivskyi, PR [19505](https://github.com/python/mypy/pull/19505))\r\n- Use cache for dictionary expressions (Ivan Levkivskyi, PR [19536](https://github.com/python/mypy/pull/19536))\r\n- Use cache for binary operations (Ivan Levkivskyi, PR [19523](https://github.com/python/mypy/pull/19523))\r\n- Cache types of type objects (Ivan Levkivskyi, PR [19514](https://github.com/python/mypy/pull/19514))\r\n- Avoid duplicate work when checking boolean operations (Ivan Levkivskyi, PR [19515](https://github.com/python/mypy/pull/19515))\r\n- Optimize generic inference passes (Ivan Levkivskyi, PR [19501](https://github.com/python/mypy/pull/19501))\r\n- Speed up the default plugin (Jukka Lehtosalo, PRs [19385](https://github.com/python/mypy/pull/19385) and [19462](https://github.com/python/mypy/pull/19462))\r\n- Remove nested imports from the default plugin (Ivan Levkivskyi, PR [19388](https://github.com/python/mypy/pull/19388))\r\n- Micro‑optimize type expansion (Jukka Lehtosalo, PR [19461](https://github.com/python/mypy/pull/19461))\r\n- Micro‑optimize type indirection (Jukka Lehtosalo, PR [19460](https://github.com/python/mypy/pull/19460))\r\n- Micro‑optimize the plugin framework (Jukka Lehtosalo, PR [19464](https://github.com/python/mypy/pull/19464))\r\n- Avoid temporary set creation in subtype checking (Jukka Lehtosalo, PR [19463](https://github.com/python/mypy/pull/19463))\r\n- Subtype checking micro‑optimization (Jukka Lehtosalo, PR [19384](https://github.com/python/mypy/pull/19384))\r\n- Return early where possible in subtype check (Stanislav Terliakov, PR [19400](https://github.com/python/mypy/pull/19400))\r\n- Deduplicate some types before joining (Stanislav Terliakov, PR [19409](https://github.com/python/mypy/pull/19409))\r\n- Speed up type checking by caching argument inference context (Jukka Lehtosalo, PR [19323](https://github.com/python/mypy/pull/19323))\r\n- Optimize binding method self argument type and deprecation checks (Ivan Levkivskyi, PR [19556](https://github.com/python/mypy/pull/19556))\r\n- Keep trivial instance types/aliases during expansion (Ivan Levkivskyi, PR [19543](https://github.com/python/mypy/pull/19543))\r\n\r\n### Fixed‑Format Cache (Experimental)\r\n\r\nMypy now supports a new cache format used for faster incremental builds. It makes\r\nincremental builds up to twice as fast. The feature is experimental and\r\ncurrently only supported when using a compiled version of mypy. Use `--fixed-format-cache`\r\nto enable the new format, or `fixed_format_cache = True` in a configuration file.\r\n\r\nWe plan to enable this by default in a future mypy release, and we'll eventually\r\ndeprecate and remove support for the original JSON-based format.\r\n\r\nUnlike the JSON-based cache format, the new binary format is currently\r\nnot easy to parse and inspect by mypy users. We are planning to provide a tool to\r\nconvert fixed-format cache files to JSON, but details of the output JSON may be\r\ndifferent from the current JSON format. If you rely on being able to inspect\r\nmypy cache files, we recommend creating a GitHub issue and explaining your use\r\ncase, so that we can more likely provide support for it. (Using\r\n`MypyFile.read(binary_data)` to inspect cache data may be sufficient to support\r\nsome use cases.)\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [19668](https://github.com/python/mypy/pull/19668), [19735](https://github.com/python/mypy/pull/19735), [19750](https://github.com/python/mypy/pull/19750), [19681](https://github.com/python/mypy/pull/19681), [19752](https://github.com/python/mypy/pull/19752), [19815](https://github.com/python/mypy/pull/19815)).\r\n\r\n### Flexible Variable Definitions: Update\r\n\r\nMypy 1.16.0 introduced `--allow-redefinition-new`, which allows redefining variables\r\nwith different types, and inferring union types for variables from multiple assignments.\r\nThe feature is now documented in the `--help` output, but the feature is still experimental.\r\n\r\nWe are planning to enable this by default in mypy 2.0, and we will also deprecate the\r\nolder `--allow-redefinition` flag. Since the new behavior differs significantly from\r\nthe older flag, we encourage users of `--allow-redefinition` to experiment with\r\n`--allow-redefinition-new` and create a GitHub issue if the new functionality doesn't\r\nsupport some important use cases.\r\n\r\nThis feature was contributed by Jukka Lehtosalo.\r\n\r\n### Inferred Type for Bare ClassVar\r\n\r\nA ClassVar without an explicit type annotation now causes the type of the variable\r\nto be inferred from the initializer:\r\n\r\n\r\n```python\r\nfrom typing import ClassVar\r\n\r\nclass Item:\r\n    # Type of 'next_id' is now 'int' (it was 'Any')\r\n    next_id: ClassVar = 1\r\n\r\n    ...\r\n```\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [19573](https://github.com/python/mypy/pull/19573)).\r\n\r\n### Disjoint Base Classes (@disjoint_base, PEP 800)\r\n\r\nMypy now understands disjoint bases (PEP 800): it recognizes the `@disjoint_base`\r\ndecorator, and rejects class definitions that combine mutually incompatible base classes,\r\nand takes advantage of the fact that such classes cannot exist in reachability and\r\nnarrowing logic.\r\n\r\nThis class definition will now generate an error:\r\n\r\n```python\r\n# Error: Class \"Bad\" has incompatible disjoint bases\r\nclass Bad(str, Exception):\r\n    ...\r\n```\r\n\r\nThis feature was contributed by Jelle Zijlstra (PR [19678](https://github.com/python/mypy/pull/19678)).\r\n\r\n### Miscellaneous New Mypy Features\r\n\r\n- Add `--strict-equality-for-none` to flag non-overlapping comparisons involving None (Christoph Tyralla, PR [19718](https://github.com/python/mypy/pull/19718))\r\n- Don’t show import‑related errors after a module‑level assert such as `assert sys.platform == \"linux\"` that is always false (Stanislav Terliakov, PR [19347](https://github.com/python/mypy/pull/19347))\r\n\r\n### Improvements to Match Statements\r\n\r\n- Add temporary named expressions for match subjects (Stanislav Terliakov, PR [18446](https://github.com/python/mypy/pull/18446))\r\n- Fix unwrapping of assignment expressions in match subject (Marc Mueller, PR [19742](https://github.com/python/mypy/pull/19742))\r\n- Omit errors for class patterns against object (Marc Mueller, PR [19709](https://github.com/python/mypy/pull/19709))\r\n- Remove unnecessary error for certain match class patterns (Marc Mueller, PR [19708](https://github.com/python/mypy/pull/19708))\r\n- Use union type for captured vars in or pattern (Marc Mueller, PR [19710](https://github.com/python/mypy/pull/19710))\r\n- Prevent final reassignment inside match case (Omer Hadari, PR [19496](https://github.com/python/mypy/pull/19496))\r\n\r\n### Fixes to Crashes\r\n\r\n- Fix crash with variadic tuple arguments to a generic type (Randolf Scholz, PR [19705](https://github.com/python/mypy/pull/19705))\r\n- Fix crash when enable_error_code in pyproject.toml has wrong type (wyattscarpenter, PR [19494](https://github.com/python/mypy/pull/19494))\r\n- Prevent crash for dataclass with PEP 695 TypeVarTuple on Python 3.13+ (Stanislav Terliakov, PR [19565](https://github.com/python/mypy/pull/19565))\r\n- Fix crash on settable property alias (Ivan Levkivskyi, PR [19615](https://github.com/python/mypy/pull/19615))\r\n\r\n### Experimental Free-threading Support for Mypyc\r\n\r\nAll mypyc tests now pass on free-threading Python 3.14 release candidate builds. The performance\r\nof various micro-benchmarks scale well across multiple threads.\r\n\r\nFree-threading support is still experimental. Note that native attribute access\r\n(get and set), list item access and certain other operations are still\r\nunsafe when there are race conditions. This will likely change in the future.\r\nYou can follow the\r\n[area-free-threading label](https://github.com/mypyc/mypyc/issues?q=is%3Aissue%20state%3Aopen%20label%3Aarea-free-threading)\r\nin the mypyc issues tracker to follow progress.\r\n\r\nRelated PRs:\r\n- Enable free‑threading when compiling multiple modules (Jukka Lehtosalo, PR [19541](https://github.com/python/mypy/pull/19541))\r\n- Fix `list.pop` on free‑threaded builds (Jukka Lehtosalo, PR [19522](https://github.com/python/mypy/pull/19522))\r\n- Make type objects immortal under free‑threading (Jukka Lehtosalo, PR [19538](https://github.com/python/mypy/pull/19538))\r\n\r\n### Mypyc: Support `__new__`\r\n\r\nMypyc now has rudimentary support for user-defined `__new__` methods.\r\n\r\nThis feature was contributed by Piotr Sawicki (PR [19739](https://github.com/python/mypy/pull/19739)).\r\n\r\n### Mypyc: Faster Generators and Async Functions\r\n\r\nGenerators and calls of async functions are now faster, sometimes by 2x or more.\r\n\r\nRelated PRs:\r\n- Speed up for loops over native generators (Jukka Lehtosalo, PR [19415](https://github.com/python/mypy/pull/19415))\r\n- Speed up native‑to‑native calls using await (Jukka Lehtosalo, PR [19398](https://github.com/python/mypy/pull/19398))\r\n- Call generator helper directly in await expressions (Jukka Lehtosalo, PR [19376](https://github.com/python/mypy/pull/19376))\r\n- Speed up generator allocation with per‑type freelists (Jukka Lehtosalo, PR [19316](https://github.com/python/mypy/pull/19316))\r\n\r\n### Miscellaneous Mypyc Improvements\r\n\r\n- Special‑case certain Enum method calls for speed (Ivan Levkivskyi, PR [19634](https://github.com/python/mypy/pull/19634))\r\n- Fix issues related to subclassing and undefined attribute tracking (Chainfire, PR [19787](https://github.com/python/mypy/pull/19787))\r\n- Fix invalid C function signature (Jukka Lehtosalo, PR [19773](https://github.com/python/mypy/pull/19773))\r\n- Speed up implicit `__ne__` (Jukka Lehtosalo, PR [19759](https://github.com/python/mypy/pull/19759))\r\n- Speed up equality with optional str/bytes types (Jukka Lehtosalo, PR [19758](https://github.com/python/mypy/pull/19758))\r\n- Speed up access to empty tuples (BobTheBuidler, PR [19654](https://github.com/python/mypy/pull/19654))\r\n- Speed up calls with `*args` (BobTheBuidler, PRs [19623](https://github.com/python/mypy/pull/19623) and [19631](https://github.com/python/mypy/pull/19631))\r\n- Speed up calls with `**kwargs` (BobTheBuidler, PR [19630](https://github.com/python/mypy/pull/19630))\r\n- Optimize `type(x)`, `x.__class__`, and `<type>.__name__` (Jukka Lehtosalo, PR [19691](https://github.com/python/mypy/pull/19691), [19683](https://github.com/python/mypy/pull/19683))\r\n- Specialize `bytes.decode` for common encodings (Jukka Lehtosalo, PR [19688](https://github.com/python/mypy/pull/19688))\r\n- Speed up `in` operations using final fixed‑length tuples (Jukka Lehtosalo, PR [19682](https://github.com/python/mypy/pull/19682))\r\n- Optimize f‑string building from final values (BobTheBuidler, PR [19611](https://github.com/python/mypy/pull/19611))\r\n- Add dictionary set item for exact dict instances (BobTheBuidler, PR [19657](https://github.com/python/mypy/pull/19657))\r\n- Cache length when iterating over immutable types (BobTheBuidler, PR [19656](https://github.com/python/mypy/pull/19656))\r\n- Fix name conflict related to attributes of generator classes (Piotr Sawicki, PR [19535](https://github.com/python/mypy/pull/19535))\r\n- Fix segfault from heap type objects with a static docstring (Brian Schubert, PR [19636](https://github.com/python/mypy/pull/19636))\r\n- Unwrap NewType to its base type for additional optimizations (BobTheBuidler, PR [19497](https://github.com/python/mypy/pull/19497))\r\n- Generate an export table only for separate compilation (Jukka Lehtosalo, PR [19521](https://github.com/python/mypy/pull/19521))\r\n- Speed up `isinstance` with built‑in types (Piotr Sawicki, PR [19435](https://github.com/python/mypy/pull/19435))\r\n- Use native integers for some sequence indexing (Jukka Lehtosalo, PR [19426](https://github.com/python/mypy/pull/19426))\r\n- Speed up `isinstance(obj, list)` (Piotr Sawicki, PR [19416](https://github.com/python/mypy/pull/19416))\r\n- Report error on reserved method names (Piotr Sawicki, PR [19407](https://github.com/python/mypy/pull/19407))\r\n- Speed up string equality (Jukka Lehtosalo, PR [19402](https://github.com/python/mypy/pull/19402))\r\n- Raise `NameError` on undefined names (Piotr Sawicki, PR [19395](https://github.com/python/mypy/pull/19395))\r\n- Use per‑type freelists for nested functions (Jukka Lehtosalo, PR [19390](https://github.com/python/mypy/pull/19390))\r\n- Simplify comparison of tuple elements (Piotr Sawicki, PR [19396](https://github.com/python/mypy/pull/19396))\r\n- Generate introspection signatures for compiled functions (Brian Schubert, PR [19307](https://github.com/python/mypy/pull/19307))\r\n- Fix undefined attribute checking special case (Jukka Lehtosalo, PR [19378](https://github.com/python/mypy/pull/19378))\r\n- Fix comparison of tuples with different lengths (Piotr Sawicki, PR [19372](https://github.com/python/mypy/pull/19372))\r\n- Speed up `list.clear` (Jahongir Qurbonov, PR [19344](https://github.com/python/mypy/pull/19344))\r\n- Speed up `weakref.proxy` (BobTheBuidler, PR [19217](https://github.com/python/mypy/pull/19217))\r\n- Speed up `weakref.ref` (BobTheBuidler, PR [19099](https://github.com/python/mypy/pull/19099))\r\n- Speed up `str.count` (BobTheBuidler, PR [19264](https://github.com/python/mypy/pull/19264))\r\n\r\n### Stubtest Improvements\r\n- Add temporary `--ignore-disjoint-bases` flag to ease PEP 800 migration (Joren Hammudoglu, PR [19740](https://github.com/python/mypy/pull/19740))\r\n- Flag redundant uses of `@disjoint_base` (Jelle Zijlstra, PR [19715](https://github.com/python/mypy/pull/19715))\r\n- Improve signatures for `__init__` of C extension classes (Stephen Morton, PR [18259](https://github.com/python/mypy/pull/18259))\r\n- Handle overloads with mixed positional‑only parameters (Stephen Morton, PR [18287](https://github.com/python/mypy/pull/18287))\r\n- Use “parameter” (not “argument”) in error messages (PrinceNaroliya, PR [19707](https://github.com/python/mypy/pull/19707))\r\n- Don’t require `@disjoint_base` when `__slots__` imply finality (Jelle Zijlstra, PR [19701](https://github.com/python/mypy/pull/19701))\r\n- Allow runtime‑existing aliases of `@type_check_only` types (Brian Schubert, PR [19568](https://github.com/python/mypy/pull/19568))\r\n- More detailed checking of type objects in stubtest (Stephen Morton, PR [18251](https://github.com/python/mypy/pull/18251))\r\n- Support running stubtest in non-UTF8 terminals (Stanislav Terliakov, PR [19085](https://github.com/python/mypy/pull/19085))\r\n\r\n### Documentation Updates\r\n\r\n- Add idlemypyextension to IDE integrations (CoolCat467, PR [18615](https://github.com/python/mypy/pull/18615))\r\n- Document that `object` is often preferable to `Any` in APIs (wyattscarpenter, PR [19103](https://github.com/python/mypy/pull/19103))\r\n- Include a detailed listing of flags enabled by `--strict` (wyattscarpenter, PR [19062](https://github.com/python/mypy/pull/19062))\r\n- Update “common issues” (reveal_type/reveal_locals; note on orjson) (wyattscarpenter, PR [19059](https://github.com/python/mypy/pull/19059), [19058](https://github.com/python/mypy/pull/19058))\r\n\r\n### Other Notable Fixes and Improvements\r\n\r\n- Remove deprecated `--new-type-inference` flag (the new algorithm has long been default) (Ivan Levkivskyi, PR [19570](https://github.com/python/mypy/pull/19570))\r\n- Use empty context as a fallback for return expressions when outer context misleads inference (Ivan Levkivskyi, PR [19767](https://github.com/python/mypy/pull/19767))\r\n- Fix forward references in type parameters of over‑parameterized PEP 695 aliases (Brian Schubert, PR [19725](https://github.com/python/mypy/pull/19725))\r\n- Don’t expand PEP 695 aliases when checking node fullnames (Brian Schubert, PR [19699](https://github.com/python/mypy/pull/19699))\r\n- Don’t use outer context for 'or' expression inference when LHS is Any (Stanislav Terliakov, PR [19748](https://github.com/python/mypy/pull/19748))\r\n- Recognize buffer protocol special methods (Brian Schubert, PR [19581](https://github.com/python/mypy/pull/19581))\r\n- Support attribute access on enum members correctly (Stanislav Terliakov, PR [19422](https://github.com/python/mypy/pull/19422))\r\n- Check `__slots__` assignments on self types (Stanislav Terliakov, PR [19332](https://github.com/python/mypy/pull/19332))\r\n- Move self‑argument checks after decorator application (Stanislav Terliakov, PR [19490](https://github.com/python/mypy/pull/19490))\r\n- Infer empty list for `__slots__` and module `__all__` (Stanislav Terliakov, PR [19348](https://github.com/python/mypy/pull/19348))\r\n- Use normalized tuples for fallback calculation (Stanislav Terliakov, PR [19111](https://github.com/python/mypy/pull/19111))\r\n- Preserve literals when joining similar types (Stanislav Terliakov, PR [19279](https://github.com/python/mypy/pull/19279))\r\n- Allow adjacent conditionally‑defined overloads (Stanislav Terliakov, PR [19042](https://github.com/python/mypy/pull/19042))\r\n- Check property decorators more strictly (Stanislav Terliakov, PR [19313](https://github.com/python/mypy/pull/19313))\r\n- Support properties with generic setters (Ivan Levkivskyi, PR [19298](https://github.com/python/mypy/pull/19298))\r\n- Generalize class/static method and property alias support (Ivan Levkivskyi, PR [19297](https://github.com/python/mypy/pull/19297))\r\n- Re‑widen custom properties after narrowing (Ivan Levkivskyi, PR [19296](https://github.com/python/mypy/pull/19296))\r\n- Avoid erasing type objects when checking runtime cover (Shantanu, PR [19320](https://github.com/python/mypy/pull/19320))\r\n- Include tuple fallback in constraints built from tuple types (Stanislav Terliakov, PR [19100](https://github.com/python/mypy/pull/19100))\r\n- Somewhat better isinstance support on old‑style unions (Shantanu, PR [19714](https://github.com/python/mypy/pull/19714))\r\n- Improve promotions inside unions (Christoph Tyralla, PR [19245](https://github.com/python/mypy/pull/19245))\r\n- Treat uninhabited types as having all attributes (Ivan Levkivskyi, PR [19300](https://github.com/python/mypy/pull/19300))\r\n- Improve metaclass conflict checks (Robsdedude, PR [17682](https://github.com/python/mypy/pull/17682))\r\n- Fixes to metaclass resolution algorithm (Robsdedude, PR [17713](https://github.com/python/mypy/pull/17713))\r\n- PEP 702 @deprecated: handle “combined” overloads (Christoph Tyralla, PR [19626](https://github.com/python/mypy/pull/19626))\r\n- PEP 702 @deprecated: include overloads in snapshot descriptions (Christoph Tyralla, PR [19613](https://github.com/python/mypy/pull/19613))\r\n- Ignore overload implementation when checking `__OP__` / `__rOP__` compatibility (Stanislav Terliakov, PR [18502](https://github.com/python/mypy/pull/18502))\r\n- Support `_value_` as a fallback for ellipsis Enum members (Stanislav Terliakov, PR [19352](https://github.com/python/mypy/pull/19352))\r\n- Sort arguments in TypedDict overlap messages (Marc Mueller, PR [19666](https://github.com/python/mypy/pull/19666))\r\n- Fix handling of implicit return in lambda (Stanislav Terliakov, PR [19642](https://github.com/python/mypy/pull/19642))\r\n- Improve behavior of uninhabited types (Stanislav Terliakov, PR [19648](https://github.com/python/mypy/pull/19648))\r\n- Fix overload diagnostics when `*args` and `**kwargs` both match (Shantanu, PR [19614](https://github.com/python/mypy/pull/19614))\r\n- Further fix overload diagnostics for `*args`/`**kwargs` (Shantanu, PR [19619](https://github.com/python/mypy/pull/19619))\r\n- Show type variable name in \"Cannot infer type argument\" (Brian Schubert, PR [19290](https://github.com/python/mypy/pull/19290))\r\n- Fail gracefully on unsupported template strings (PEP 750) (Brian Schubert, PR [19700](https://github.com/python/mypy/pull/19700))\r\n- Revert colored argparse help for Python 3.14 (Marc Mueller, PR [19721](https://github.com/python/mypy/pull/19721))\r\n- Update stubinfo for latest typeshed (Shantanu, PR [19771](https://github.com/python/mypy/pull/19771))\r\n- Fix dict assignment when an incompatible same‑shape TypedDict exists (Stanislav Terliakov, PR [19592](https://github.com/python/mypy/pull/19592))\r\n- Fix constructor type for subclasses of Any (Ivan Levkivskyi, PR [19295](https://github.com/python/mypy/pull/19295))\r\n- Fix TypeGuard/TypeIs being forgotten in some cases (Brian Schubert, PR [19325](https://github.com/python/mypy/pull/19325))\r\n- Fix TypeIs negative narrowing for unions of generics (Brian Schubert, PR [18193](https://github.com/python/mypy/pull/18193))\r\n- dmypy suggest: Fix incorrect signature suggestion when a type matches a module name (Brian Schubert, PR [18937](https://github.com/python/mypy/pull/18937))\r\n- dmypy suggest: Fix interaction with `__new__` (Stanislav Terliakov, PR [18966](https://github.com/python/mypy/pull/18966))\r\n- dmypy suggest: Support Callable / callable Protocols in decorator unwrapping (Anthony Sottile, PR [19072](https://github.com/python/mypy/pull/19072))\r\n- Fix missing error when redeclaring a type variable in a nested generic class (Brian Schubert, PR [18883](https://github.com/python/mypy/pull/18883))\r\n- Fix for overloaded type object erasure (Shantanu, PR [19338](https://github.com/python/mypy/pull/19338))\r\n- Fix TypeGuard with call on temporary object (Saul Shanabrook, PR [19577](https://github.com/python/mypy/pull/19577))\r\n\r\n### Typeshed Updates\r\n\r\nPlease see [git log](https://github.com/python/typeshed/commits/main?after=2480d7e7c74493a024eaf254c5d2c6f452c80ee2+0&branch=main&path=stdlib) for full list of standard library typeshed stub changes.\r\n\r\n### Mypy 1.18.2\r\n\r\n- Fix crash on recursive alias (Ivan Levkivskyi, PR [19845](https://github.com/python/mypy/pull/19845))\r\n- Add additional guidance for stubtest errors when runtime is `object.__init__` (Stephen Morton, PR [19733](https://github.com/python/mypy/pull/19733))\r\n- Fix handling of None values in f-string expressions in mypyc (BobTheBuidler, PR [19846](https://github.com/python/mypy/pull/19846))\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n- Ali Hamdan\r\n- Anthony Sottile\r\n- BobTheBuidler\r\n- Brian Schubert\r\n- Chainfire\r\n- Charlie Denton\r\n- Christoph Tyralla\r\n- CoolCat467\r\n- Daniel Hnyk\r\n- Emily\r\n- Emma Smith\r\n- Ethan Sarp\r\n- Ivan Levkivskyi\r\n- Jahongir Qurbonov\r\n- Jelle Zijlstra\r\n- Joren Hammudoglu\r\n- Jukka Lehtosalo\r\n- Marc Mueller\r\n- Omer Hadari\r\n- Piotr Sawicki\r\n- PrinceNaroliya\r\n- Randolf Scholz\r\n- Robsdedude\r\n- Saul Shanabrook\r\n- Shantanu\r\n- Stanislav Terliakov\r\n- Stephen Morton\r\n- wyattscarpenter\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\n## Mypy 1.17\r\n\r\nWe’ve just uploaded mypy 1.17 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)).\r\nMypy is a static type checker for Python. This release includes new features and bug fixes.\r\nYou can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Optionally Check That Match Is Exhaustive\r\n\r\nMypy can now optionally generate an error if a match statement does not\r\nmatch exhaustively, without having to use `assert_never(...)`. Enable\r\nthis by using `--enable-error-code exhaustive-match`.\r\n\r\nExample:\r\n\r\n```python\r\n# mypy: enable-error-code=exhaustive-match\r\n\r\nimport enum\r\n\r\nclass Color(enum.Enum):\r\n    RED = 1\r\n    BLUE = 2\r\n\r\ndef show_color(val: Color) -> None:\r\n    # error: Unhandled case for values of type \"Literal[Color.BLUE]\"\r\n    match val:\r\n        case Color.RED:\r\n            print(\"red\")\r\n```\r\n\r\nThis feature was contributed by Donal Burns (PR [19144](https://github.com/python/mypy/pull/19144)).\r\n\r\n### Further Improvements to Attribute Resolution\r\n\r\nThis release includes additional improvements to how attribute types\r\nand kinds are resolved. These fix many bugs and overall improve consistency.\r\n\r\n* Handle corner case: protocol/class variable/descriptor (Ivan Levkivskyi, PR [19277](https://github.com/python/mypy/pull/19277))\r\n* Fix a few inconsistencies in protocol/type object interactions (Ivan Levkivskyi, PR [19267](https://github.com/python/mypy/pull/19267))\r\n* Refactor/unify access to static attributes (Ivan Levkivskyi, PR [19254](https://github.com/python/mypy/pull/19254))\r\n* Remove inconsistencies in operator handling (Ivan Levkivskyi, PR [19250](https://github.com/python/mypy/pull/19250))\r\n* Make protocol subtyping more consistent (Ivan Levkivskyi, PR [18943](https://github.com/python/mypy/pull/18943))\r\n\r\n### Fixes to Nondeterministic Type Checking\r\n\r\nPrevious mypy versions could infer different types for certain expressions\r\nacross different runs (typically depending on which order certain types\r\nwere processed, and this order was nondeterministic). This release includes\r\nfixes to several such issues.\r\n\r\n* Fix nondeterministic type checking by making join with explicit Protocol and type promotion commute (Shantanu, PR [18402](https://github.com/python/mypy/pull/18402))\r\n* Fix nondeterministic type checking caused by nonassociative of None joins (Shantanu, PR [19158](https://github.com/python/mypy/pull/19158))\r\n* Fix nondeterministic type checking caused by nonassociativity of joins (Shantanu, PR [19147](https://github.com/python/mypy/pull/19147))\r\n* Fix nondeterministic type checking by making join between `type` and TypeVar commute (Shantanu, PR [19149](https://github.com/python/mypy/pull/19149))\r\n\r\n### Remove Support for Targeting Python 3.8\r\n\r\nMypy now requires `--python-version 3.9` or greater. Support for targeting Python 3.8 is\r\nfully removed now. Since 3.8 is an unsupported version, mypy will default to the oldest\r\nsupported version (currently 3.9) if you still try to target 3.8.\r\n\r\nThis change is necessary because typeshed stopped supporting Python 3.8 after it\r\nreached its End of Life in October 2024.\r\n\r\nContributed by Marc Mueller\r\n(PR [19157](https://github.com/python/mypy/pull/19157), PR [19162](https://github.com/python/mypy/pull/19162)).\r\n\r\n### Initial Support for Python 3.14\r\n\r\nMypy is now tested on 3.14 and mypyc works with 3.14.0b3 and later.\r\nBinary wheels compiled with mypyc for mypy itself will be available for 3.14\r\nsome time after 3.14.0rc1 has been released.\r\n\r\nNote that not all features are supported just yet.\r\n\r\nContributed by Marc Mueller (PR [19164](https://github.com/python/mypy/pull/19164))\r\n\r\n### Deprecated Flag: `--force-uppercase-builtins`\r\n\r\nMypy only supports Python 3.9+. The `--force-uppercase-builtins` flag is now\r\ndeprecated as unnecessary, and a no-op. It will be removed in a future version.\r\n\r\nContributed by Marc Mueller (PR [19176](https://github.com/python/mypy/pull/19176))\r\n\r\n### Mypyc: Improvements to Generators and Async Functions\r\n\r\nThis release includes both performance improvements and bug fixes related\r\nto generators and async functions (these share many implementation details).\r\n\r\n* Fix exception swallowing in async try/finally blocks with await (Chainfire, PR [19353](https://github.com/python/mypy/pull/19353))\r\n* Fix AttributeError in async try/finally with mixed return paths (Chainfire, PR [19361](https://github.com/python/mypy/pull/19361))\r\n* Make generated generator helper method internal (Jukka Lehtosalo, PR [19268](https://github.com/python/mypy/pull/19268))\r\n* Free coroutine after await encounters StopIteration (Jukka Lehtosalo, PR [19231](https://github.com/python/mypy/pull/19231))\r\n* Use non-tagged integer for generator label (Jukka Lehtosalo, PR [19218](https://github.com/python/mypy/pull/19218))\r\n* Merge generator and environment classes in simple cases (Jukka Lehtosalo, PR [19207](https://github.com/python/mypy/pull/19207))\r\n\r\n### Mypyc: Partial, Unsafe Support for Free Threading\r\n\r\nMypyc has minimal, quite memory-unsafe support for the free threaded\r\nbuilds of 3.14. It is also only lightly tested. Bug reports and experience\r\nreports are welcome!\r\n\r\nHere are some of the major limitations:\r\n* Free threading only works when compiling a single module at a time.\r\n* If there is concurrent access to an object while another thread is mutating the same\r\n  object, it's possible to encounter segfaults and memory corruption.\r\n* There are no efficient native primitives for thread synthronization, though the\r\n  regular `threading` module can be used.\r\n* Some workloads don't scale well to multiple threads for no clear reason.\r\n\r\nRelated PRs:\r\n\r\n* Enable partial, unsafe support for free-threading (Jukka Lehtosalo, PR [19167](https://github.com/python/mypy/pull/19167))\r\n* Fix incref/decref on free-threaded builds (Jukka Lehtosalo, PR [19127](https://github.com/python/mypy/pull/19127))\r\n\r\n### Other Mypyc Fixes and Improvements\r\n\r\n* Derive .c file name from full module name if using multi_file (Jukka Lehtosalo, PR [19278](https://github.com/python/mypy/pull/19278))\r\n* Support overriding the group name used in output files (Jukka Lehtosalo, PR [19272](https://github.com/python/mypy/pull/19272))\r\n* Add note about using non-native class to subclass built-in types (Jukka Lehtosalo, PR [19236](https://github.com/python/mypy/pull/19236))\r\n* Make some generated classes implicitly final (Jukka Lehtosalo, PR [19235](https://github.com/python/mypy/pull/19235))\r\n* Don't simplify module prefixes if using separate compilation (Jukka Lehtosalo, PR [19206](https://github.com/python/mypy/pull/19206))\r\n\r\n### Stubgen Improvements\r\n\r\n* Add import for `types` in `__exit__` method signature (Alexey Makridenko, PR [19120](https://github.com/python/mypy/pull/19120))\r\n* Add support for including class and property docstrings (Chad Dombrova, PR [17964](https://github.com/python/mypy/pull/17964))\r\n* Don't generate `Incomplete | None = None` argument annotation (Sebastian Rittau, PR [19097](https://github.com/python/mypy/pull/19097))\r\n* Support several more constructs in stubgen's alias printer (Stanislav Terliakov, PR [18888](https://github.com/python/mypy/pull/18888))\r\n\r\n### Miscellaneous Fixes and Improvements\r\n\r\n* Combine the revealed types of multiple iteration steps in a more robust manner (Christoph Tyralla, PR [19324](https://github.com/python/mypy/pull/19324))\r\n* Improve the handling of \"iteration dependent\" errors and notes in finally clauses (Christoph Tyralla, PR [19270](https://github.com/python/mypy/pull/19270))\r\n* Lessen dmypy suggest path limitations for Windows machines (CoolCat467, PR [19337](https://github.com/python/mypy/pull/19337))\r\n* Fix type ignore comments erroneously marked as unused by dmypy (Charlie Denton, PR [15043](https://github.com/python/mypy/pull/15043))\r\n* Fix misspelled `exhaustive-match` error code (johnthagen, PR [19276](https://github.com/python/mypy/pull/19276))\r\n* Fix missing error context for unpacking assignment involving star expression (Brian Schubert, PR [19258](https://github.com/python/mypy/pull/19258))\r\n* Fix and simplify error de-duplication (Ivan Levkivskyi, PR [19247](https://github.com/python/mypy/pull/19247))\r\n* Disallow `ClassVar` in type aliases (Brian Schubert, PR [19263](https://github.com/python/mypy/pull/19263))\r\n* Add script that prints list of compiled files when compiling mypy (Jukka Lehtosalo, PR [19260](https://github.com/python/mypy/pull/19260))\r\n* Fix help message url for \"None and Optional handling\" section (Guy Wilson, PR [19252](https://github.com/python/mypy/pull/19252))\r\n* Display fully qualified name of imported base classes in errors about incompatible overrides (Mikhail Golubev, PR [19115](https://github.com/python/mypy/pull/19115))\r\n* Avoid false `unreachable`, `redundant-expr`, and `redundant-casts` warnings in loops more robustly and efficiently, and avoid multiple `revealed type` notes for the same line (Christoph Tyralla, PR [19118](https://github.com/python/mypy/pull/19118))\r\n* Fix type extraction from `isinstance` checks (Stanislav Terliakov, PR [19223](https://github.com/python/mypy/pull/19223))\r\n* Erase stray type variables in `functools.partial` (Stanislav Terliakov, PR [18954](https://github.com/python/mypy/pull/18954))\r\n* Make inferring condition value recognize the whole truth table (Stanislav Terliakov, PR [18944](https://github.com/python/mypy/pull/18944))\r\n* Support type aliases, `NamedTuple` and `TypedDict` in constrained TypeVar defaults (Stanislav Terliakov, PR [18884](https://github.com/python/mypy/pull/18884))\r\n* Move dataclass `kw_only` fields to the end of the signature (Stanislav Terliakov, PR [19018](https://github.com/python/mypy/pull/19018))\r\n* Provide a better fallback value for the `python_version` option (Marc Mueller, PR [19162](https://github.com/python/mypy/pull/19162))\r\n* Avoid spurious non-overlapping equality error with metaclass with `__eq__` (Michael J. Sullivan, PR [19220](https://github.com/python/mypy/pull/19220))\r\n* Narrow type variable bounds (Ivan Levkivskyi, PR [19183](https://github.com/python/mypy/pull/19183))\r\n* Add classifier for Python 3.14 (Marc Mueller, PR [19199](https://github.com/python/mypy/pull/19199))\r\n* Capitalize syntax error messages (Charulata, PR [19114](https://github.com/python/mypy/pull/19114))\r\n* Infer constraints eagerly if actual is Any (Ivan Levkivskyi, PR [19190](https://github.com/python/mypy/pull/19190))\r\n* Include walrus assignments in conditional inference (Stanislav Terliakov, PR [19038](https://github.com/python/mypy/pull/19038))\r\n* Use PEP 604 syntax when converting types to strings (Marc Mueller, PR [19179](https://github.com/python/mypy/pull/19179))\r\n* Use more lower-case builtin types in error messages (Marc Mueller, PR [19177](https://github.com/python/mypy/pull/19177))\r\n* Fix example to use correct method of Stack (Łukasz Kwieciński, PR [19123](https://github.com/python/mypy/pull/19123))\r\n* Forbid `.pop` of `Readonly` `NotRequired` TypedDict items (Stanislav Terliakov, PR [19133](https://github.com/python/mypy/pull/19133))\r\n* Emit a friendlier warning on invalid exclude regex, instead of a stacktrace (wyattscarpenter, PR [19102](https://github.com/python/mypy/pull/19102))\r\n* Enable ANSI color codes for dmypy client in Windows (wyattscarpenter, PR [19088](https://github.com/python/mypy/pull/19088))\r\n* Extend special case for context-based type variable inference to unions in return position (Stanislav Terliakov, PR [18976](https://github.com/python/mypy/pull/18976))\r\n\r\n### Mypy 1.17.1\r\n* Retain `None` as constraints bottom if no bottoms were provided (Stanislav Terliakov, PR [19485](https://github.com/python/mypy/pull/19485))\r\n* Fix \"ignored exception in `hasattr`\" in dmypy (Stanislav Terliakov, PR [19428](https://github.com/python/mypy/pull/19428))\r\n* Prevent a crash when InitVar is redefined with a method in a subclass (Stanislav Terliakov, PR [19453](https://github.com/python/mypy/pull/19453))\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n* Alexey Makridenko\r\n* Brian Schubert\r\n* Chad Dombrova\r\n* Chainfire\r\n* Charlie Denton\r\n* Charulata\r\n* Christoph Tyralla\r\n* CoolCat467\r\n* Donal Burns\r\n* Guy Wilson\r\n* Ivan Levkivskyi\r\n* johnthagen\r\n* Jukka Lehtosalo\r\n* Łukasz Kwieciński\r\n* Marc Mueller\r\n* Michael J. Sullivan\r\n* Mikhail Golubev\r\n* Sebastian Rittau\r\n* Shantanu\r\n* Stanislav Terliakov\r\n* wyattscarpenter\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\n## Mypy 1.16\r\n\r\nWe’ve just uploaded mypy 1.16 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)).\r\nMypy is a static type checker for Python. This release includes new features and bug fixes.\r\nYou can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Different Property Getter and Setter Types\r\n\r\nMypy now supports using different types for a property getter and setter:\r\n\r\n```python\r\nclass A:\r\n    _value: int\r\n\r\n    @property\r\n    def foo(self) -> int:\r\n        return self._value\r\n\r\n    @foo.setter\r\n    def foo(self, x: str | int) -> None:\r\n        try:\r\n            self._value = int(x)\r\n        except ValueError:\r\n            raise Exception(f\"'{x}' is not a valid value for 'foo'\")\r\n```\r\nThis was contributed by Ivan Levkivskyi (PR [18510](https://github.com/python/mypy/pull/18510)).\r\n\r\n### Flexible Variable Redefinitions (Experimental)\r\n\r\nMypy now allows unannotated variables to be freely redefined with\r\ndifferent types when using the experimental `--allow-redefinition-new`\r\nflag. You will also need to enable `--local-partial-types`. Mypy will\r\nnow infer a union type when different types are assigned to a\r\nvariable:\r\n\r\n```py\r\n# mypy: allow-redefinition-new, local-partial-types\r\n\r\ndef f(n: int, b: bool) -> int | str:\r\n    if b:\r\n        x = n\r\n    else:\r\n        x = str(n)\r\n    # Type of 'x' is int | str here.\r\n    return x\r\n```\r\n\r\nWithout the new flag, mypy only supports inferring optional types (`X\r\n| None`) from multiple assignments, but now mypy can infer arbitrary\r\nunion types.\r\n\r\nAn unannotated variable can now also have different types in different\r\ncode locations:\r\n\r\n```py\r\n# mypy: allow-redefinition-new, local-partial-types\r\n...\r\n\r\nif cond():\r\n    for x in range(n):\r\n        # Type of 'x' is 'int' here\r\n        ...\r\nelse:\r\n    for x in ['a', 'b']:\r\n        # Type of 'x' is 'str' here\r\n        ...\r\n```\r\n\r\nWe are planning to turn this flag on by default in mypy 2.0, along\r\nwith `--local-partial-types`. The feature is still experimental and\r\nhas known issues, and the semantics may still change in the\r\nfuture. You may need to update or add type annotations when switching\r\nto the new behavior, but if you encounter anything unexpected, please\r\ncreate a GitHub issue.\r\n\r\nThis was contributed by Jukka Lehtosalo\r\n(PR [18727](https://github.com/python/mypy/pull/18727), PR [19153](https://github.com/python/mypy/pull/19153)).\r\n\r\n### Stricter Type Checking with Imprecise Types\r\n\r\nMypy can now detect additional errors in code that uses `Any` types or has missing function annotations.\r\n\r\nWhen calling `dict.get(x, None)` on an object of type `dict[str, Any]`, this\r\nnow results in an optional type (in the past it was `Any`):\r\n\r\n```python\r\ndef f(d: dict[str, Any]) -> int:\r\n    # Error: Return value has type \"Any | None\" but expected \"int\"\r\n    return d.get(\"x\", None)\r\n```\r\n\r\nType narrowing using assignments can result in more precise types in\r\nthe presence of `Any` types:\r\n\r\n```python\r\ndef foo(): ...\r\n\r\ndef bar(n: int) -> None:\r\n    x = foo()\r\n    # Type of 'x' is 'Any' here\r\n    if n > 5:\r\n        x = str(n)\r\n        # Type of 'x' is 'str' here\r\n```\r\n\r\nWhen using `--check-untyped-defs`, unannotated overrides are now\r\nchecked more strictly against superclass definitions.\r\n\r\nRelated PRs:\r\n\r\n * Use union types instead of join in binder (Ivan Levkivskyi, PR [18538](https://github.com/python/mypy/pull/18538))\r\n * Check superclass compatibility of untyped methods if `--check-untyped-defs` is set (Stanislav Terliakov, PR [18970](https://github.com/python/mypy/pull/18970))\r\n\r\n### Improvements to Attribute Resolution\r\n\r\nThis release includes several fixes to inconsistent resolution of attribute, method and descriptor types.\r\n\r\n * Consolidate descriptor handling (Ivan Levkivskyi, PR [18831](https://github.com/python/mypy/pull/18831))\r\n * Make multiple inheritance checking use common semantics (Ivan Levkivskyi, PR [18876](https://github.com/python/mypy/pull/18876))\r\n * Make method override checking use common semantics  (Ivan Levkivskyi, PR [18870](https://github.com/python/mypy/pull/18870))\r\n * Fix descriptor overload selection (Ivan Levkivskyi, PR [18868](https://github.com/python/mypy/pull/18868))\r\n * Handle union types when binding `self` (Ivan Levkivskyi, PR [18867](https://github.com/python/mypy/pull/18867))\r\n * Make variable override checking use common semantics (Ivan Levkivskyi, PR [18847](https://github.com/python/mypy/pull/18847))\r\n * Make descriptor handling behave consistently (Ivan Levkivskyi, PR [18831](https://github.com/python/mypy/pull/18831))\r\n\r\n### Make Implementation for Abstract Overloads Optional\r\n\r\nThe implementation can now be omitted for abstract overloaded methods,\r\neven outside stubs:\r\n\r\n```py\r\nfrom abc import abstractmethod\r\nfrom typing import overload\r\n\r\nclass C:\r\n    @abstractmethod\r\n    @overload\r\n    def foo(self, x: int) -> int: ...\r\n\r\n    @abstractmethod\r\n    @overload\r\n    def foo(self, x: str) -> str: ...\r\n\r\n    # No implementation required for \"foo\"\r\n```\r\n\r\nThis was contributed by Ivan Levkivskyi (PR [18882](https://github.com/python/mypy/pull/18882)).\r\n\r\n### Option to Exclude Everything in .gitignore\r\n\r\nYou can now use `--exclude-gitignore` to exclude everything in a\r\n`.gitignore` file from the mypy build. This behaves similar to\r\nexcluding the paths using `--exclude`. We might enable this by default\r\nin a future mypy release.\r\n\r\nThis was contributed by Ivan Levkivskyi (PR [18696](https://github.com/python/mypy/pull/18696)).\r\n\r\n### Selectively Disable Deprecated Warnings\r\n\r\nIt's now possible to selectively disable warnings generated from\r\n[`warnings.deprecated`](https://docs.python.org/3/library/warnings.html#warnings.deprecated)\r\nusing the [`--deprecated-calls-exclude`](https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-deprecated-calls-exclude)\r\noption:\r\n\r\n```python\r\n# mypy --enable-error-code deprecated\r\n#      --deprecated-calls-exclude=foo.A\r\nimport foo\r\n\r\nfoo.A().func()  # OK, the deprecated warning is ignored\r\n```\r\n\r\n```python\r\n# file foo.py\r\n\r\nfrom typing_extensions import deprecated\r\n\r\nclass A:\r\n    @deprecated(\"Use A.func2 instead\")\r\n    def func(self): pass\r\n\r\n    ...\r\n```\r\n\r\nContributed by Marc Mueller (PR [18641](https://github.com/python/mypy/pull/18641))\r\n\r\n### Annotating Native/Non-Native Classes in Mypyc\r\n\r\nYou can now declare a class as a non-native class when compiling with\r\nmypyc. Unlike native classes, which are extension classes and have an\r\nimmutable structure, non-native classes are normal Python classes at\r\nruntime and are fully dynamic.  Example:\r\n\r\n```python\r\nfrom mypy_extensions import mypyc_attr\r\n\r\n@mypyc_attr(native_class=False)\r\nclass NonNativeClass:\r\n    ...\r\n\r\no = NonNativeClass()\r\n\r\n# Ok, even if attribute \"foo\" not declared in class body\r\nsetattr(o, \"foo\", 1)\r\n```\r\n\r\nClasses are native by default in compiled modules, but classes that\r\nuse certain features (such as most metaclasses) are implicitly\r\nnon-native.\r\n\r\nYou can also explicitly declare a class as native. In this case mypyc\r\nwill generate an error if it can't compile the class as a native\r\nclass, instead of falling back to a non-native class:\r\n\r\n```python\r\nfrom mypy_extensions import mypyc_attr\r\nfrom foo import MyMeta\r\n\r\n# Error: Unsupported metaclass for a native class\r\n@mypyc_attr(native_class=True)\r\nclass C(metaclass=MyMeta):\r\n    ...\r\n```\r\n\r\nSince native classes are significantly more efficient that non-native\r\nclasses, you may want to ensure that certain classes always compiled\r\nas native classes.\r\n\r\nThis feature was contributed by Valentin Stanciu (PR [18802](https://github.com/python/mypy/pull/18802)).\r\n\r\n### Mypyc Fixes and Improvements\r\n\r\n * Improve documentation of native and non-native classes (Jukka Lehtosalo, PR [19154](https://github.com/python/mypy/pull/19154))\r\n * Fix compilation when using Python 3.13 debug build (Valentin Stanciu, PR [19045](https://github.com/python/mypy/pull/19045))\r\n * Show the reason why a class can't be a native class (Valentin Stanciu, PR [19016](https://github.com/python/mypy/pull/19016))\r\n * Support await/yield while temporary values are live (Michael J. Sullivan, PR [16305](https://github.com/python/mypy/pull/16305))\r\n * Fix spilling values with overlapping error values (Jukka Lehtosalo, PR [18961](https://github.com/python/mypy/pull/18961))\r\n * Fix reference count of spilled register in async def (Jukka Lehtosalo, PR [18957](https://github.com/python/mypy/pull/18957))\r\n * Add basic optimization for `sorted` (Marc Mueller, PR [18902](https://github.com/python/mypy/pull/18902))\r\n * Fix access of class object in a type annotation (Advait Dixit, PR [18874](https://github.com/python/mypy/pull/18874))\r\n * Optimize `list.__imul__` and `tuple.__mul__ `(Marc Mueller, PR [18887](https://github.com/python/mypy/pull/18887))\r\n * Optimize `list.__add__`, `list.__iadd__` and `tuple.__add__` (Marc Mueller, PR [18845](https://github.com/python/mypy/pull/18845))\r\n * Add and implement primitive `list.copy()` (exertustfm, PR [18771](https://github.com/python/mypy/pull/18771))\r\n * Optimize `builtins.repr` (Marc Mueller, PR [18844](https://github.com/python/mypy/pull/18844))\r\n * Support iterating over keys/values/items of dict-bound TypeVar and ParamSpec.kwargs (Stanislav Terliakov, PR [18789](https://github.com/python/mypy/pull/18789))\r\n * Add efficient primitives for `str.strip()` etc. (Advait Dixit, PR [18742](https://github.com/python/mypy/pull/18742))\r\n * Document that `strip()` etc. are optimized (Jukka Lehtosalo, PR [18793](https://github.com/python/mypy/pull/18793))\r\n * Fix mypyc crash with enum type aliases (Valentin Stanciu, PR [18725](https://github.com/python/mypy/pull/18725))\r\n * Optimize `str.find` and `str.rfind` (Marc Mueller, PR [18709](https://github.com/python/mypy/pull/18709))\r\n * Optimize `str.__contains__` (Marc Mueller, PR [18705](https://github.com/python/mypy/pull/18705))\r\n * Fix order of steal/unborrow in tuple unpacking (Ivan Levkivskyi, PR [18732](https://github.com/python/mypy/pull/18732))\r\n * Optimize `str.partition` and `str.rpartition` (Marc Mueller, PR [18702](https://github.com/python/mypy/pull/18702))\r\n * Optimize `str.startswith` and `str.endswith` with tuple argument (Marc Mueller, PR [18678](https://github.com/python/mypy/pull/18678))\r\n * Improve `str.startswith` and `str.endswith` with tuple argument (Marc Mueller, PR [18703](https://github.com/python/mypy/pull/18703))\r\n * `pythoncapi_compat`: don't define Py_NULL if it is already defined (Michael R. Crusoe, PR [18699](https://github.com/python/mypy/pull/18699))\r\n * Optimize `str.splitlines` (Marc Mueller, PR [18677](https://github.com/python/mypy/pull/18677))\r\n * Mark `dict.setdefault` as optimized (Marc Mueller, PR [18685](https://github.com/python/mypy/pull/18685))\r\n * Support `__del__` methods (Advait Dixit, PR [18519](https://github.com/python/mypy/pull/18519))\r\n * Optimize `str.rsplit` (Marc Mueller, PR [18673](https://github.com/python/mypy/pull/18673))\r\n * Optimize `str.removeprefix` and `str.removesuffix` (Marc Mueller, PR [18672](https://github.com/python/mypy/pull/18672))\r\n * Recognize literal types in `__match_args__` (Stanislav Terliakov, PR [18636](https://github.com/python/mypy/pull/18636))\r\n * Fix non extension classes with attribute annotations using forward references (Valentin Stanciu, PR [18577](https://github.com/python/mypy/pull/18577))\r\n * Use lower-case generic types such as `list[t]` in documentation (Jukka Lehtosalo, PR [18576](https://github.com/python/mypy/pull/18576))\r\n * Improve support for `frozenset` (Marc Mueller, PR [18571](https://github.com/python/mypy/pull/18571))\r\n * Fix wheel build for cp313-win (Marc Mueller, PR [18560](https://github.com/python/mypy/pull/18560))\r\n * Reduce impact of immortality (introduced in Python 3.12) on reference counting performance (Jukka Lehtosalo, PR [18459](https://github.com/python/mypy/pull/18459))\r\n * Update math error messages for 3.14 (Marc Mueller, PR [18534](https://github.com/python/mypy/pull/18534))\r\n * Update math error messages for 3.14 (2) (Marc Mueller, PR [18949](https://github.com/python/mypy/pull/18949))\r\n * Replace deprecated `_PyLong_new` with `PyLongWriter` API (Marc Mueller, PR [18532](https://github.com/python/mypy/pull/18532))\r\n\r\n### Fixes to Crashes\r\n\r\n * Traverse module ancestors when traversing reachable graph nodes during dmypy update (Stanislav Terliakov, PR [18906](https://github.com/python/mypy/pull/18906))\r\n * Fix crash on multiple unpacks in a bare type application (Stanislav Terliakov, PR [18857](https://github.com/python/mypy/pull/18857))\r\n * Prevent crash when enum/TypedDict call is stored as a class attribute (Stanislav Terliakov, PR [18861](https://github.com/python/mypy/pull/18861))\r\n * Fix crash on multiple unpacks in a bare type application (Stanislav Terliakov, PR [18857](https://github.com/python/mypy/pull/18857))\r\n * Fix crash on type inference against non-normal callables (Ivan Levkivskyi, PR [18858](https://github.com/python/mypy/pull/18858))\r\n * Fix crash on decorated getter in settable property (Ivan Levkivskyi, PR [18787](https://github.com/python/mypy/pull/18787))\r\n * Fix crash on callable with `*args` and suffix against Any (Ivan Levkivskyi, PR [18781](https://github.com/python/mypy/pull/18781))\r\n * Fix crash on deferred supertype and setter override (Ivan Levkivskyi, PR [18649](https://github.com/python/mypy/pull/18649))\r\n * Fix crashes on incorrectly detected recursive aliases (Ivan Levkivskyi, PR [18625](https://github.com/python/mypy/pull/18625))\r\n * Report that `NamedTuple` and `dataclass` are incompatile instead of crashing (Christoph Tyralla, PR [18633](https://github.com/python/mypy/pull/18633))\r\n * Fix mypy daemon crash (Valentin Stanciu, PR [19087](https://github.com/python/mypy/pull/19087))\r\n\r\n### Performance Improvements\r\n\r\nThese are specific to mypy. Mypyc-related performance improvements are discussed elsewhere.\r\n\r\n * Speed up binding `self` in trivial cases (Ivan Levkivskyi, PR [19024](https://github.com/python/mypy/pull/19024))\r\n * Small constraint solver optimization (Aaron Gokaslan, PR [18688](https://github.com/python/mypy/pull/18688))\r\n\r\n### Documentation Updates\r\n\r\n * Improve documentation of `--strict` (lenayoung8, PR [18903](https://github.com/python/mypy/pull/18903))\r\n * Remove a note about `from __future__ import annotations` (Ageev Maxim, PR [18915](https://github.com/python/mypy/pull/18915))\r\n * Improve documentation on type narrowing (Tim Hoffmann, PR [18767](https://github.com/python/mypy/pull/18767))\r\n * Fix metaclass usage example (Georg, PR [18686](https://github.com/python/mypy/pull/18686))\r\n * Update documentation on `extra_checks` flag (Ivan Levkivskyi, PR [18537](https://github.com/python/mypy/pull/18537))\r\n\r\n### Stubgen Improvements\r\n\r\n * Fix `TypeAlias` handling (Alexey Makridenko, PR [18960](https://github.com/python/mypy/pull/18960))\r\n * Handle `arg=None` in C extension modules (Anthony Sottile, PR [18768](https://github.com/python/mypy/pull/18768))\r\n * Fix valid type detection to allow pipe unions (Chad Dombrova, PR [18726](https://github.com/python/mypy/pull/18726))\r\n * Include simple decorators in stub files (Marc Mueller, PR [18489](https://github.com/python/mypy/pull/18489))\r\n * Support positional and keyword-only arguments in stubdoc (Paul Ganssle, PR [18762](https://github.com/python/mypy/pull/18762))\r\n * Fall back to `Incomplete` if we are unable to determine the module name (Stanislav Terliakov, PR [19084](https://github.com/python/mypy/pull/19084))\r\n\r\n### Stubtest Improvements\r\n\r\n * Make stubtest ignore `__slotnames__` (Nick Pope, PR [19077](https://github.com/python/mypy/pull/19077))\r\n * Fix stubtest tests on 3.14 (Jelle Zijlstra, PR [19074](https://github.com/python/mypy/pull/19074))\r\n * Support for `strict_bytes` in stubtest (Joren Hammudoglu, PR [19002](https://github.com/python/mypy/pull/19002))\r\n * Understand override (Shantanu, PR [18815](https://github.com/python/mypy/pull/18815))\r\n * Better checking of runtime arguments with dunder names (Shantanu, PR [18756](https://github.com/python/mypy/pull/18756))\r\n * Ignore setattr and delattr inherited from object (Stephen Morton, PR [18325](https://github.com/python/mypy/pull/18325))\r\n\r\n### Miscellaneous Fixes and Improvements\r\n\r\n * Add `--strict-bytes` to `--strict` (wyattscarpenter, PR [19049](https://github.com/python/mypy/pull/19049))\r\n * Admit that Final variables are never redefined (Stanislav Terliakov, PR [19083](https://github.com/python/mypy/pull/19083))\r\n * Add special support for `@django.cached_property` needed in `django-stubs` (sobolevn, PR [18959](https://github.com/python/mypy/pull/18959))\r\n * Do not narrow types to `Never` with binder (Ivan Levkivskyi, PR [18972](https://github.com/python/mypy/pull/18972))\r\n * Local forward references should precede global forward references (Ivan Levkivskyi, PR [19000](https://github.com/python/mypy/pull/19000))\r\n * Do not cache module lookup results in incremental mode that may become invalid (Stanislav Terliakov, PR [19044](https://github.com/python/mypy/pull/19044))\r\n * Only consider meta variables in ambiguous \"any of\" constraints (Stanislav Terliakov, PR [18986](https://github.com/python/mypy/pull/18986))\r\n * Allow accessing `__init__` on final classes and when `__init__` is final (Stanislav Terliakov, PR [19035](https://github.com/python/mypy/pull/19035))\r\n * Treat varargs as positional-only (A5rocks, PR [19022](https://github.com/python/mypy/pull/19022))\r\n * Enable colored output for argparse help in Python 3.14 (Marc Mueller, PR [19021](https://github.com/python/mypy/pull/19021))\r\n * Fix argparse for Python 3.14 (Marc Mueller, PR [19020](https://github.com/python/mypy/pull/19020))\r\n * `dmypy suggest` can now suggest through contextmanager-based decorators (Anthony Sottile, PR [18948](https://github.com/python/mypy/pull/18948))\r\n * Fix `__r<magic_methods>__` being used under the same `__<magic_method>__` hook (Arnav Jain, PR [18995](https://github.com/python/mypy/pull/18995))\r\n * Prioritize `.pyi` from `-stubs` packages over bundled `.pyi` (Joren Hammudoglu, PR [19001](https://github.com/python/mypy/pull/19001))\r\n * Fix missing subtype check case for `type[T]` (Stanislav Terliakov, PR [18975](https://github.com/python/mypy/pull/18975))\r\n * Fixes to the detection of redundant casts (Anthony Sottile, PR [18588](https://github.com/python/mypy/pull/18588))\r\n * Make some parse errors non-blocking (Shantanu, PR [18941](https://github.com/python/mypy/pull/18941))\r\n * Fix PEP 695 type alias with a mix of type arguments (PEP 696) (Marc Mueller, PR [18919](https://github.com/python/mypy/pull/18919))\r\n * Allow deeper recursion in mypy daemon, better error reporting (Carter Dodd, PR [17707](https://github.com/python/mypy/pull/17707))\r\n * Fix swapped errors for frozen/non-frozen dataclass inheritance (Nazrawi Demeke, PR [18918](https://github.com/python/mypy/pull/18918))\r\n * Fix incremental issue with namespace packages (Shantanu, PR [18907](https://github.com/python/mypy/pull/18907))\r\n * Exclude irrelevant members when narrowing union overlapping with enum (Stanislav Terliakov, PR [18897](https://github.com/python/mypy/pull/18897))\r\n * Flatten union before contracting literals when checking subtyping (Stanislav Terliakov, PR [18898](https://github.com/python/mypy/pull/18898))\r\n * Do not add `kw_only` dataclass fields to `__match_args__` (sobolevn, PR [18892](https://github.com/python/mypy/pull/18892))\r\n * Fix error message when returning long tuple with type mismatch (Thomas Mattone, PR [18881](https://github.com/python/mypy/pull/18881))\r\n * Treat `TypedDict` (old-style) aliases as regular `TypedDict`s (Stanislav Terliakov, PR [18852](https://github.com/python/mypy/pull/18852))\r\n * Warn about unused `type: ignore` comments when error code is disabled (Brian Schubert, PR [18849](https://github.com/python/mypy/pull/18849))\r\n * Reject duplicate `ParamSpec.{args,kwargs}` at call site (Stanislav Terliakov, PR [18854](https://github.com/python/mypy/pull/18854))\r\n * Make detection of enum members more consistent (sobolevn, PR [18675](https://github.com/python/mypy/pull/18675))\r\n * Admit that `**kwargs` mapping subtypes may have no direct type parameters (Stanislav Terliakov, PR [18850](https://github.com/python/mypy/pull/18850))\r\n * Don't suggest `types-setuptools` for `pkg_resources` (Shantanu, PR [18840](https://github.com/python/mypy/pull/18840))\r\n * Suggest `scipy-stubs` for `scipy` as non-typeshed stub package (Joren Hammudoglu, PR [18832](https://github.com/python/mypy/pull/18832))\r\n * Narrow tagged unions in match statements (Gene Parmesan Thomas, PR [18791](https://github.com/python/mypy/pull/18791))\r\n * Consistently store settable property type (Ivan Levkivskyi, PR [18774](https://github.com/python/mypy/pull/18774))\r\n * Do not blindly undefer on leaving function (Ivan Levkivskyi, PR [18674](https://github.com/python/mypy/pull/18674))\r\n * Process superclass methods before subclass methods in semanal (Ivan Levkivskyi, PR [18723](https://github.com/python/mypy/pull/18723))\r\n * Only defer top-level functions (Ivan Levkivskyi, PR [18718](https://github.com/python/mypy/pull/18718))\r\n * Add one more type-checking pass (Ivan Levkivskyi, PR [18717](https://github.com/python/mypy/pull/18717))\r\n * Properly account for `member` and `nonmember` in enums (sobolevn, PR [18559](https://github.com/python/mypy/pull/18559))\r\n * Fix instance vs tuple subtyping edge case (Ivan Levkivskyi, PR [18664](https://github.com/python/mypy/pull/18664))\r\n * Improve handling of Any/object in variadic generics (Ivan Levkivskyi, PR [18643](https://github.com/python/mypy/pull/18643))\r\n * Fix handling of named tuples in class match pattern (Ivan Levkivskyi, PR [18663](https://github.com/python/mypy/pull/18663))\r\n * Fix regression for user config files (Shantanu, PR [18656](https://github.com/python/mypy/pull/18656))\r\n * Fix dmypy socket issue on GNU/Hurd (Mattias Ellert, PR [18630](https://github.com/python/mypy/pull/18630))\r\n * Don't assume that for loop body index variable is always set (Jukka Lehtosalo, PR [18631](https://github.com/python/mypy/pull/18631))\r\n * Fix overlap check for variadic generics (Ivan Levkivskyi, PR [18638](https://github.com/python/mypy/pull/18638))\r\n * Improve support for `functools.partial` of overloaded callable protocol (Shantanu, PR [18639](https://github.com/python/mypy/pull/18639))\r\n * Allow lambdas in `except*` clauses (Stanislav Terliakov, PR [18620](https://github.com/python/mypy/pull/18620))\r\n * Fix trailing commas in many multiline string options in `pyproject.toml` (sobolevn, PR [18624](https://github.com/python/mypy/pull/18624))\r\n * Allow trailing commas for `files` setting in `mypy.ini` and `setup.ini` (sobolevn, PR [18621](https://github.com/python/mypy/pull/18621))\r\n * Fix \"not callable\" issue for `@dataclass(frozen=True)` with `Final` attr (sobolevn, PR [18572](https://github.com/python/mypy/pull/18572))\r\n * Add missing TypedDict special case when checking member access (Stanislav Terliakov, PR [18604](https://github.com/python/mypy/pull/18604))\r\n * Use lower case `list` and `dict` in invariance notes (Jukka Lehtosalo, PR [18594](https://github.com/python/mypy/pull/18594))\r\n * Fix inference when class and instance match protocol (Ivan Levkivskyi, PR [18587](https://github.com/python/mypy/pull/18587))\r\n * Remove support for `builtins.Any` (Marc Mueller, PR [18578](https://github.com/python/mypy/pull/18578))\r\n * Update the overlapping check for tuples to account for NamedTuples (A5rocks, PR [18564](https://github.com/python/mypy/pull/18564))\r\n * Fix `@deprecated` (PEP 702) with normal overloaded methods (Christoph Tyralla, PR [18477](https://github.com/python/mypy/pull/18477))\r\n * Start propagating end columns/lines for `type-arg` errors (A5rocks, PR [18533](https://github.com/python/mypy/pull/18533))\r\n * Improve handling of `type(x) is Foo` checks (Stanislav Terliakov, PR [18486](https://github.com/python/mypy/pull/18486))\r\n * Suggest `typing.Literal` for exit-return error messages (Marc Mueller, PR [18541](https://github.com/python/mypy/pull/18541))\r\n * Allow redefinitions in except/else/finally (Stanislav Terliakov, PR [18515](https://github.com/python/mypy/pull/18515))\r\n * Disallow setting Python version using inline config (Shantanu, PR [18497](https://github.com/python/mypy/pull/18497))\r\n * Improve type inference in tuple multiplication plugin (Shantanu, PR [18521](https://github.com/python/mypy/pull/18521))\r\n * Add missing line number to `yield from` with wrong type (Stanislav Terliakov, PR [18518](https://github.com/python/mypy/pull/18518))\r\n * Hint at argument names when formatting callables with compatible return types in error messages (Stanislav Terliakov, PR [18495](https://github.com/python/mypy/pull/18495))\r\n * Add better naming and improve compatibility for ad hoc intersections of instances (Christoph Tyralla, PR [18506](https://github.com/python/mypy/pull/18506))\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n- A5rocks\r\n- Aaron Gokaslan\r\n- Advait Dixit\r\n- Ageev Maxim\r\n- Alexey Makridenko\r\n- Ali Hamdan\r\n- Anthony Sottile\r\n- Arnav Jain\r\n- Brian Schubert\r\n- bzoracler\r\n- Carter Dodd\r\n- Chad Dombrova\r\n- Christoph Tyralla\r\n- Dimitri Papadopoulos Orfanos\r\n- Emma Smith\r\n- exertustfm\r\n- Gene Parmesan Thomas\r\n- Georg\r\n- Ivan Levkivskyi\r\n- Jared Hance\r\n- Jelle Zijlstra\r\n- Joren Hammudoglu\r\n- lenayoung8\r\n- Marc Mueller\r\n- Mattias Ellert\r\n- Michael J. Sullivan\r\n- Michael R. Crusoe\r\n- Nazrawi Demeke\r\n- Nick Pope\r\n- Paul Ganssle\r\n- Shantanu\r\n- sobolevn\r\n- Stanislav Terliakov\r\n- Stephen Morton\r\n- Thomas Mattone\r\n- Tim Hoffmann\r\n- Tim Ruffing\r\n- Valentin Stanciu\r\n- Wesley Collin Wright\r\n- wyattscarpenter\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\n## Mypy 1.15\r\n\r\nWe’ve just uploaded mypy 1.15 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)).\r\nMypy is a static type checker for Python. This release includes new features, performance\r\nimprovements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Performance Improvements\r\n\r\nMypy is up to 40% faster in some use cases. This improvement comes largely from tuning the performance\r\nof the garbage collector. Additionally, the release includes several micro-optimizations that may\r\nbe impactful for large projects.\r\n\r\nContributed by Jukka Lehtosalo\r\n- PR [18306](https://github.com/python/mypy/pull/18306)\r\n- PR [18302](https://github.com/python/mypy/pull/18302)\r\n- PR [18298](https://github.com/python/mypy/pull/18298)\r\n- PR [18299](https://github.com/python/mypy/pull/18299)\r\n\r\n### Mypyc Accelerated Mypy Wheels for ARM Linux\r\n\r\nFor best performance, mypy can be compiled to C extension modules using mypyc. This makes\r\nmypy 3-5x faster than when interpreted with pure Python. We now build and upload mypyc\r\naccelerated mypy wheels for `manylinux_aarch64` to PyPI, making it easy for Linux users on\r\nARM platforms to realise this speedup -- just `pip install` the latest mypy.\r\n\r\nContributed by Christian Bundy and Marc Mueller\r\n(PR [mypy_mypyc-wheels#76](https://github.com/mypyc/mypy_mypyc-wheels/pull/76),\r\nPR [mypy_mypyc-wheels#89](https://github.com/mypyc/mypy_mypyc-wheels/pull/89)).\r\n\r\n### `--strict-bytes`\r\n\r\nBy default, mypy treats `bytearray` and `memoryview` values as assignable to the `bytes`\r\ntype, for historical reasons. Use the `--strict-bytes` flag to disable this\r\nbehavior. [PEP 688](https://peps.python.org/pep-0688) specified the removal of this\r\nspecial case. The flag will be enabled by default in **mypy 2.0**.\r\n\r\nContributed by Ali Hamdan (PR [18263](https://github.com/python/mypy/pull/18263)) and\r\nShantanu Jain (PR [13952](https://github.com/python/mypy/pull/13952)).\r\n\r\n### Improvements to Reachability Analysis and Partial Type Handling in Loops\r\n\r\nThis change results in mypy better modelling control flow within loops and hence detecting\r\nseveral previously ignored issues. In some cases, this change may require additional\r\nexplicit variable annotations.\r\n\r\nContributed by Christoph Tyralla (PR [18180](https://github.com/python/mypy/pull/18180),\r\nPR [18433](https://github.com/python/mypy/pull/18433)).\r\n\r\n(Speaking of partial types, remember that we plan to enable `--local-partial-types`\r\nby default in **mypy 2.0**.)\r\n\r\n### Better Discovery of Configuration Files\r\n\r\nMypy will now walk up the filesystem (up until a repository or file system root) to discover\r\nconfiguration files. See the\r\n[mypy configuration file documentation](https://mypy.readthedocs.io/en/stable/config_file.html)\r\nfor more details.\r\n\r\nContributed by Mikhail Shiryaev and Shantanu Jain\r\n(PR [16965](https://github.com/python/mypy/pull/16965), PR [18482](https://github.com/python/mypy/pull/18482))\r\n\r\n### Better Line Numbers for Decorators and Slice Expressions\r\n\r\nMypy now uses more correct line numbers for decorators and slice expressions. In some cases,\r\nyou may have to change the location of a `# type: ignore` comment.\r\n\r\nContributed by Shantanu Jain (PR [18392](https://github.com/python/mypy/pull/18392),\r\nPR [18397](https://github.com/python/mypy/pull/18397)).\r\n\r\n### Drop Support for Python 3.8\r\n\r\nMypy no longer supports running with Python 3.8, which has reached end-of-life.\r\nWhen running mypy with Python 3.9+, it is still possible to type check code\r\nthat needs to support Python 3.8 with the `--python-version 3.8` argument.\r\nSupport for this will be dropped in the first half of 2025!\r\n\r\nContributed by Marc Mueller (PR [17492](https://github.com/python/mypy/pull/17492)).\r\n\r\n### Mypyc Improvements\r\n\r\n * Fix `__init__` for classes with `@attr.s(slots=True)` (Advait Dixit, PR [18447](https://github.com/python/mypy/pull/18447))\r\n * Report error for nested class instead of crashing (Valentin Stanciu, PR [18460](https://github.com/python/mypy/pull/18460))\r\n * Fix `InitVar` for dataclasses (Advait Dixit, PR [18319](https://github.com/python/mypy/pull/18319))\r\n * Remove unnecessary mypyc files from wheels (Marc Mueller, PR [18416](https://github.com/python/mypy/pull/18416))\r\n * Fix issues with relative imports (Advait Dixit, PR [18286](https://github.com/python/mypy/pull/18286))\r\n * Add faster primitive for some list get item operations (Jukka Lehtosalo, PR [18136](https://github.com/python/mypy/pull/18136))\r\n * Fix iteration over `NamedTuple` objects (Advait Dixit, PR [18254](https://github.com/python/mypy/pull/18254))\r\n * Mark mypyc package with `py.typed` (bzoracler, PR [18253](https://github.com/python/mypy/pull/18253))\r\n * Fix list index while checking for `Enum` class (Advait Dixit, PR [18426](https://github.com/python/mypy/pull/18426))\r\n\r\n### Stubgen Improvements\r\n\r\n * Improve dataclass init signatures (Marc Mueller, PR [18430](https://github.com/python/mypy/pull/18430))\r\n * Preserve `dataclass_transform` decorator (Marc Mueller, PR [18418](https://github.com/python/mypy/pull/18418))\r\n * Fix `UnpackType` for 3.11+ (Marc Mueller, PR [18421](https://github.com/python/mypy/pull/18421))\r\n * Improve `self` annotations (Marc Mueller, PR [18420](https://github.com/python/mypy/pull/18420))\r\n * Print `InspectError` traceback in stubgen `walk_packages` when verbose is specified (Gareth, PR [18224](https://github.com/python/mypy/pull/18224))\r\n\r\n### Stubtest Improvements\r\n\r\n * Fix crash with numpy array default values (Ali Hamdan, PR [18353](https://github.com/python/mypy/pull/18353))\r\n * Distinguish metaclass attributes from class attributes (Stephen Morton, PR [18314](https://github.com/python/mypy/pull/18314))\r\n\r\n### Fixes to Crashes\r\n\r\n * Prevent crash with `Unpack` of a fixed tuple in PEP695 type alias (Stanislav Terliakov, PR [18451](https://github.com/python/mypy/pull/18451))\r\n * Fix crash with `--cache-fine-grained --cache-dir=/dev/null` (Shantanu, PR [18457](https://github.com/python/mypy/pull/18457))\r\n * Prevent crashing when `match` arms use name of existing callable (Stanislav Terliakov, PR [18449](https://github.com/python/mypy/pull/18449))\r\n * Gracefully handle encoding errors when writing to stdout (Brian Schubert, PR [18292](https://github.com/python/mypy/pull/18292))\r\n * Prevent crash on generic NamedTuple with unresolved typevar bound (Stanislav Terliakov, PR [18585](https://github.com/python/mypy/pull/18585))\r\n\r\n### Documentation Updates\r\n\r\n * Add inline tabs to documentation (Marc Mueller, PR [18262](https://github.com/python/mypy/pull/18262))\r\n * Document any `TYPE_CHECKING` name works (Shantanu, PR [18443](https://github.com/python/mypy/pull/18443))\r\n * Update documentation to not mention 3.8 where possible (sobolevn, PR [18455](https://github.com/python/mypy/pull/18455))\r\n * Mention `ignore_errors` in exclude documentation (Shantanu, PR [18412](https://github.com/python/mypy/pull/18412))\r\n * Add `Self` misuse to common issues (Shantanu, PR [18261](https://github.com/python/mypy/pull/18261))\r\n\r\n### Other Notable Fixes and Improvements\r\n\r\n * Fix literal context for ternary expressions (Ivan Levkivskyi, PR [18545](https://github.com/python/mypy/pull/18545))\r\n * Ignore `dataclass.__replace__` LSP violations (Marc Mueller, PR [18464](https://github.com/python/mypy/pull/18464))\r\n * Bind `self` to the class being defined when checking multiple inheritance (Stanislav Terliakov, PR [18465](https://github.com/python/mypy/pull/18465))\r\n * Fix attribute type resolution with multiple inheritance (Stanislav Terliakov, PR [18415](https://github.com/python/mypy/pull/18415))\r\n * Improve security of our GitHub Actions (sobolevn, PR [18413](https://github.com/python/mypy/pull/18413))\r\n * Unwrap `type[Union[...]]` when solving type variable constraints (Stanislav Terliakov, PR [18266](https://github.com/python/mypy/pull/18266))\r\n * Allow `Any` to match sequence patterns in match/case (Stanislav Terliakov, PR [18448](https://github.com/python/mypy/pull/18448))\r\n * Fix parent generics mapping when overriding generic attribute with property (Stanislav Terliakov, PR [18441](https://github.com/python/mypy/pull/18441))\r\n * Add dedicated error code for explicit `Any` (Shantanu, PR [18398](https://github.com/python/mypy/pull/18398))\r\n * Reject invalid `ParamSpec` locations (Stanislav Terliakov, PR [18278](https://github.com/python/mypy/pull/18278))\r\n * Stop suggesting stubs that have been removed from typeshed (Shantanu, PR [18373](https://github.com/python/mypy/pull/18373))\r\n * Allow inverting `--local-partial-types` (Shantanu, PR [18377](https://github.com/python/mypy/pull/18377))\r\n * Allow to use `Final` and `ClassVar` after Python 3.13 (정승원, PR [18358](https://github.com/python/mypy/pull/18358))\r\n * Update suggestions to include latest stubs in typeshed (Shantanu, PR [18366](https://github.com/python/mypy/pull/18366))\r\n * Fix `--install-types` masking failure details (wyattscarpenter, PR [17485](https://github.com/python/mypy/pull/17485))\r\n * Reject promotions when checking against protocols (Christoph Tyralla, PR [18360](https://github.com/python/mypy/pull/18360))\r\n * Don't erase type object arguments in diagnostics (Shantanu, PR [18352](https://github.com/python/mypy/pull/18352))\r\n * Clarify status in `dmypy status` output (Kcornw, PR [18331](https://github.com/python/mypy/pull/18331))\r\n * Disallow no-argument generic aliases when using PEP 613 explicit aliases (Brian Schubert, PR [18173](https://github.com/python/mypy/pull/18173))\r\n * Suppress errors for unreachable branches in conditional expressions (Brian Schubert, PR [18295](https://github.com/python/mypy/pull/18295))\r\n * Do not allow `ClassVar` and `Final` in `TypedDict` and `NamedTuple` (sobolevn, PR [18281](https://github.com/python/mypy/pull/18281))\r\n * Report error if not enough or too many types provided to `TypeAliasType` (bzoracler, PR [18308](https://github.com/python/mypy/pull/18308))\r\n * Use more precise context for `TypedDict` plugin errors (Brian Schubert, PR [18293](https://github.com/python/mypy/pull/18293))\r\n * Use more precise context for invalid type argument errors (Brian Schubert, PR [18290](https://github.com/python/mypy/pull/18290))\r\n * Do not allow `type[]` to contain `Literal` types (sobolevn, PR [18276](https://github.com/python/mypy/pull/18276))\r\n * Allow bytearray/bytes comparisons with `--strict-bytes` (Jukka Lehtosalo, PR [18255](https://github.com/python/mypy/pull/18255))\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n- Advait Dixit\r\n- Ali Hamdan\r\n- Brian Schubert\r\n- bzoracler\r\n- Cameron Matsui\r\n- Christoph Tyralla\r\n- Gareth\r\n- Ivan Levkivskyi\r\n- Jukka Lehtosalo\r\n- Kcornw\r\n- Marc Mueller\r\n- Mikhail f. Shiryaev\r\n- Shantanu\r\n- sobolevn\r\n- Stanislav Terliakov\r\n- Stephen Morton\r\n- Valentin Stanciu\r\n- Viktor Szépe\r\n- wyattscarpenter\r\n- 정승원\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\n## Mypy 1.14\r\n\r\nWe’ve just uploaded mypy 1.14 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)).\r\nMypy is a static type checker for Python. This release includes new features and bug fixes.\r\nYou can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Change to Enum Membership Semantics\r\n\r\nAs per the updated [typing specification for enums](https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members),\r\nenum members must be left unannotated.\r\n\r\n```python\r\nclass Pet(Enum):\r\n    CAT = 1  # Member attribute\r\n    DOG = 2  # Member attribute\r\n\r\n    # New error: Enum members must be left unannotated\r\n    WOLF: int = 3\r\n\r\n    species: str  # Considered a non-member attribute\r\n```\r\n\r\nIn particular, the specification change can result in issues in type stubs (`.pyi` files), since\r\nhistorically it was common to leave the value absent:\r\n\r\n```python\r\n# In a type stub (.pyi file)\r\n\r\nclass Pet(Enum):\r\n    # Change in semantics: previously considered members,\r\n    # now non-member attributes\r\n    CAT: int\r\n    DOG: int\r\n\r\n    # Mypy will now issue a warning if it detects this\r\n    # situation in type stubs:\r\n    # > Detected enum \"Pet\" in a type stub with zero\r\n    # > members. There is a chance this is due to a recent\r\n    # > change in the semantics of enum membership. If so,\r\n    # > use `member = value` to mark an enum member,\r\n    # > instead of `member: type`\r\n\r\nclass Pet(Enum):\r\n    # As per the specification, you should now do one of\r\n    # the following:\r\n    DOG = 1  # Member attribute with value 1 and known type\r\n    WOLF = cast(int, ...)  # Member attribute with unknown\r\n                           # value but known type\r\n    LION = ...  # Member attribute with unknown value and\r\n                # # unknown type\r\n```\r\n\r\nContributed by Terence Honles (PR [17207](https://github.com/python/mypy/pull/17207)) and\r\nShantanu Jain (PR [18068](https://github.com/python/mypy/pull/18068)).\r\n\r\n### Support for @deprecated Decorator (PEP 702)\r\n\r\nMypy can now issue errors or notes when code imports a deprecated feature\r\nexplicitly with a `from mod import depr` statement, or uses a deprecated feature\r\nimported otherwise or defined locally. Features are considered deprecated when\r\ndecorated with `warnings.deprecated`, as specified in [PEP 702](https://peps.python.org/pep-0702).\r\n\r\nYou can enable the error code via `--enable-error-code=deprecated` on the mypy\r\ncommand line or `enable_error_code = deprecated` in the mypy config file.\r\nUse the command line flag `--report-deprecated-as-note` or config file option\r\n`report_deprecated_as_note=True` to turn all such errors into notes.\r\n\r\nDeprecation errors will be enabled by default in a future mypy version.\r\n\r\nThis feature was contributed by Christoph Tyralla.\r\n\r\nList of changes:\r\n\r\n * Add basic support for PEP 702 (`@deprecated`) (Christoph Tyralla, PR [17476](https://github.com/python/mypy/pull/17476))\r\n * Support descriptors with `@deprecated` (Christoph Tyralla, PR [18090](https://github.com/python/mypy/pull/18090))\r\n * Make \"deprecated\" note an error, disabled by default (Valentin Stanciu, PR [18192](https://github.com/python/mypy/pull/18192))\r\n * Consider all possible type positions with `@deprecated` (Christoph Tyralla, PR [17926](https://github.com/python/mypy/pull/17926))\r\n * Improve the handling of explicit type annotations in assignment statements with `@deprecated` (Christoph Tyralla, PR [17899](https://github.com/python/mypy/pull/17899))\r\n\r\n### Optionally Analyzing Untyped Modules\r\n\r\nMypy normally doesn't analyze imports from third-party modules (installed using pip, for example)\r\nif there are no stubs or a py.typed marker file. To force mypy to analyze these imports, you\r\ncan now use the `--follow-untyped-imports` flag or set the `follow_untyped_imports`\r\nconfig file option to True. This can be set either in the global section of your mypy config\r\nfile, or individually on a per-module basis.\r\n\r\nThis feature was contributed by Jannick Kremer.\r\n\r\nList of changes:\r\n\r\n * Implement flag to allow type checking of untyped modules (Jannick Kremer, PR [17712](https://github.com/python/mypy/pull/17712))\r\n * Warn about `--follow-untyped-imports` (Shantanu, PR [18249](https://github.com/python/mypy/pull/18249))\r\n\r\n### Support New Style Type Variable Defaults (PEP 696)\r\n\r\nMypy now supports type variable defaults using the new syntax described in PEP 696, which\r\nwas introduced in Python 3.13. Example:\r\n\r\n```python\r\n@dataclass\r\nclass Box[T = int]:  # Set default for \"T\"\r\n    value: T | None = None\r\n\r\nreveal_type(Box())                      # type is Box[int], since it's the default\r\nreveal_type(Box(value=\"Hello World!\"))  # type is Box[str]\r\n```\r\n\r\nThis feature was contributed by Marc Mueller (PR [17985](https://github.com/python/mypy/pull/17985)).\r\n\r\n### Improved For Loop Index Variable Type Narrowing\r\n\r\nMypy now preserves the literal type of for loop index variables, to support `TypedDict`\r\nlookups. Example:\r\n\r\n```python\r\nfrom typing import TypedDict\r\n\r\nclass X(TypedDict):\r\n    hourly: int\r\n    daily: int\r\n\r\ndef func(x: X) -> int:\r\n    s = 0\r\n    for var in (\"hourly\", \"daily\"):\r\n        # \"Union[Literal['hourly']?, Literal['daily']?]\"\r\n        reveal_type(var)\r\n\r\n        # x[var] no longer triggers a literal-required error\r\n        s += x[var]\r\n    return s\r\n```\r\n\r\nThis was contributed by Marc Mueller (PR [18014](https://github.com/python/mypy/pull/18014)).\r\n\r\n### Mypyc Improvements\r\n\r\n * Document optimized bytes operations and additional str operations (Jukka Lehtosalo, PR [18242](https://github.com/python/mypy/pull/18242))\r\n * Add primitives and specialization for `ord()` (Jukka Lehtosalo, PR [18240](https://github.com/python/mypy/pull/18240))\r\n * Optimize `str.encode` with specializations for common used encodings (Valentin Stanciu, PR [18232](https://github.com/python/mypy/pull/18232))\r\n * Fix fall back to generic operation for staticmethod and classmethod (Advait Dixit, PR [18228](https://github.com/python/mypy/pull/18228))\r\n * Support unicode surrogates in string literals (Jukka Lehtosalo, PR [18209](https://github.com/python/mypy/pull/18209))\r\n * Fix index variable in for loop with `builtins.enumerate` (Advait Dixit, PR [18202](https://github.com/python/mypy/pull/18202))\r\n * Fix check for enum classes (Advait Dixit, PR [18178](https://github.com/python/mypy/pull/18178))\r\n * Fix loading type from imported modules (Advait Dixit, PR [18158](https://github.com/python/mypy/pull/18158))\r\n * Fix initializers of final attributes in class body (Jared Hance, PR [18031](https://github.com/python/mypy/pull/18031))\r\n * Fix name generation for modules with similar full names (aatle, PR [18001](https://github.com/python/mypy/pull/18001))\r\n * Fix relative imports in `__init__.py` (Shantanu, PR [17979](https://github.com/python/mypy/pull/17979))\r\n * Optimize dunder methods (jairov4, PR [17934](https://github.com/python/mypy/pull/17934))\r\n * Replace deprecated `_PyDict_GetItemStringWithError` (Marc Mueller, PR [17930](https://github.com/python/mypy/pull/17930))\r\n * Fix wheel build for cp313-win (Marc Mueller, PR [17941](https://github.com/python/mypy/pull/17941))\r\n * Use public PyGen_GetCode instead of vendored implementation (Marc Mueller, PR [17931](https://github.com/python/mypy/pull/17931))\r\n * Optimize calls to final classes (jairov4, PR [17886](https://github.com/python/mypy/pull/17886))\r\n * Support ellipsis (`...`) expressions in class bodies (Newbyte, PR [17923](https://github.com/python/mypy/pull/17923))\r\n * Sync `pythoncapi_compat.h` (Marc Mueller, PR [17929](https://github.com/python/mypy/pull/17929))\r\n * Add `runtests.py mypyc-fast` for running fast mypyc tests (Jukka Lehtosalo, PR [17906](https://github.com/python/mypy/pull/17906))\r\n\r\n### Stubgen Improvements\r\n\r\n * Do not include mypy generated symbols (Ali Hamdan, PR [18137](https://github.com/python/mypy/pull/18137))\r\n * Fix `FunctionContext.fullname` for nested classes (Chad Dombrova, PR [17963](https://github.com/python/mypy/pull/17963))\r\n * Add flagfile support (Ruslan Sayfutdinov, PR [18061](https://github.com/python/mypy/pull/18061))\r\n * Add support for PEP 695 and PEP 696 syntax (Ali Hamdan, PR [18054](https://github.com/python/mypy/pull/18054))\r\n\r\n### Stubtest Improvements\r\n\r\n * Allow the use of `--show-traceback` and `--pdb` with stubtest (Stephen Morton, PR [18037](https://github.com/python/mypy/pull/18037))\r\n * Verify `__all__` exists in stub (Sebastian Rittau, PR [18005](https://github.com/python/mypy/pull/18005))\r\n * Stop telling people to use double underscores (Jelle Zijlstra, PR [17897](https://github.com/python/mypy/pull/17897))\r\n\r\n### Documentation Updates\r\n\r\n * Update config file documentation (sobolevn, PR [18103](https://github.com/python/mypy/pull/18103))\r\n * Improve contributor documentation for Windows (ag-tafe, PR [18097](https://github.com/python/mypy/pull/18097))\r\n * Correct note about `--disallow-any-generics` flag in documentation (Abel Sen, PR [18055](https://github.com/python/mypy/pull/18055))\r\n * Further caution against `--follow-imports=skip` (Shantanu, PR [18048](https://github.com/python/mypy/pull/18048))\r\n * Fix the edit page button link in documentation (Kanishk Pachauri, PR [17933](https://github.com/python/mypy/pull/17933))\r\n\r\n### Other Notables Fixes and Improvements\r\n\r\n * Allow enum members to have type objects as values (Jukka Lehtosalo, PR [19160](https://github.com/python/mypy/pull/19160))\r\n * Show `Protocol` `__call__` for arguments with incompatible types (MechanicalConstruct, PR [18214](https://github.com/python/mypy/pull/18214))\r\n * Make join and meet symmetric with `strict_optional` (MechanicalConstruct, PR [18227](https://github.com/python/mypy/pull/18227))\r\n * Preserve block unreachablility when checking function definitions with constrained TypeVars (Brian Schubert, PR [18217](https://github.com/python/mypy/pull/18217))\r\n * Do not include non-init fields in the synthesized `__replace__` method for dataclasses (Victorien, PR [18221](https://github.com/python/mypy/pull/18221))\r\n * Disallow `TypeVar` constraints parameterized by type variables (Brian Schubert, PR [18186](https://github.com/python/mypy/pull/18186))\r\n * Always complain about invalid varargs and varkwargs (Shantanu, PR [18207](https://github.com/python/mypy/pull/18207))\r\n * Set default strict_optional state to True (Shantanu, PR [18198](https://github.com/python/mypy/pull/18198))\r\n * Preserve type variable default None in type alias (Sukhorosov Aleksey, PR [18197](https://github.com/python/mypy/pull/18197))\r\n * Add checks for invalid usage of continue/break/return in `except*` block (coldwolverine, PR [18132](https://github.com/python/mypy/pull/18132))\r\n * Do not consider bare TypeVar not overlapping with None for reachability analysis (Stanislav Terliakov, PR [18138](https://github.com/python/mypy/pull/18138))\r\n * Special case `types.DynamicClassAttribute` as property-like (Stephen Morton, PR [18150](https://github.com/python/mypy/pull/18150))\r\n * Disallow bare `ParamSpec` in type aliases (Brian Schubert, PR [18174](https://github.com/python/mypy/pull/18174))\r\n * Move long_description metadata to pyproject.toml (Marc Mueller, PR [18172](https://github.com/python/mypy/pull/18172))\r\n * Support `==`-based narrowing of Optional (Christoph Tyralla, PR [18163](https://github.com/python/mypy/pull/18163))\r\n * Allow TypedDict assignment of Required item to NotRequired ReadOnly item (Brian Schubert, PR [18164](https://github.com/python/mypy/pull/18164))\r\n * Allow nesting of Annotated with TypedDict special forms inside TypedDicts (Brian Schubert, PR [18165](https://github.com/python/mypy/pull/18165))\r\n * Infer generic type arguments for slice expressions (Brian Schubert, PR [18160](https://github.com/python/mypy/pull/18160))\r\n * Fix checking of match sequence pattern against bounded type variables (Brian Schubert, PR [18091](https://github.com/python/mypy/pull/18091))\r\n * Fix incorrect truthyness for Enum types and literals (David Salvisberg, PR [17337](https://github.com/python/mypy/pull/17337))\r\n * Move static project metadata to pyproject.toml (Marc Mueller, PR [18146](https://github.com/python/mypy/pull/18146))\r\n * Fallback to stdlib json if integer exceeds 64-bit range (q0w, PR [18148](https://github.com/python/mypy/pull/18148))\r\n * Fix 'or' pattern structural matching exhaustiveness (yihong, PR [18119](https://github.com/python/mypy/pull/18119))\r\n * Fix type inference of positional parameter in class pattern involving builtin subtype (Brian Schubert, PR [18141](https://github.com/python/mypy/pull/18141))\r\n * Fix `[override]` error with no line number when argument node has no line number (Brian Schubert, PR [18122](https://github.com/python/mypy/pull/18122))\r\n * Fix some dmypy crashes (Ivan Levkivskyi, PR [18098](https://github.com/python/mypy/pull/18098))\r\n * Fix subtyping between instance type and overloaded (Shantanu, PR [18102](https://github.com/python/mypy/pull/18102))\r\n * Clean up new_semantic_analyzer config (Shantanu, PR [18071](https://github.com/python/mypy/pull/18071))\r\n * Issue warning for enum with no members in stub (Shantanu, PR [18068](https://github.com/python/mypy/pull/18068))\r\n * Fix enum attributes are not members (Terence Honles, PR [17207](https://github.com/python/mypy/pull/17207))\r\n * Fix crash when checking slice expression with step 0 in tuple index (Brian Schubert, PR [18063](https://github.com/python/mypy/pull/18063))\r\n * Allow union-with-callable attributes to be overridden by methods (Brian Schubert, PR [18018](https://github.com/python/mypy/pull/18018))\r\n * Emit `[mutable-override]` for covariant override of attribute with method (Brian Schubert, PR [18058](https://github.com/python/mypy/pull/18058))\r\n * Support ParamSpec mapping with `functools.partial` (Stanislav Terliakov, PR [17355](https://github.com/python/mypy/pull/17355))\r\n * Fix approved stub ignore, remove normpath (Shantanu, PR [18045](https://github.com/python/mypy/pull/18045))\r\n * Make `disallow-any-unimported` flag invertible (Séamus Ó Ceanainn, PR [18030](https://github.com/python/mypy/pull/18030))\r\n * Filter to possible package paths before trying to resolve a module (falsedrow, PR [18038](https://github.com/python/mypy/pull/18038))\r\n * Fix overlap check for ParamSpec types (Jukka Lehtosalo, PR [18040](https://github.com/python/mypy/pull/18040))\r\n * Do not prioritize ParamSpec signatures during overload resolution (Stanislav Terliakov, PR [18033](https://github.com/python/mypy/pull/18033))\r\n * Fix ternary union for literals (Ivan Levkivskyi, PR [18023](https://github.com/python/mypy/pull/18023))\r\n * Fix compatibility checks for conditional function definitions using decorators (Brian Schubert, PR [18020](https://github.com/python/mypy/pull/18020))\r\n * TypeGuard should be bool not Any when matching TypeVar (Evgeniy Slobodkin, PR [17145](https://github.com/python/mypy/pull/17145))\r\n * Fix convert-cache tool (Shantanu, PR [17974](https://github.com/python/mypy/pull/17974))\r\n * Fix generator comprehension with mypyc (Shantanu, PR [17969](https://github.com/python/mypy/pull/17969))\r\n * Fix crash issue when using shadowfile with pretty (Max Chang, PR [17894](https://github.com/python/mypy/pull/17894))\r\n * Fix multiple nested classes with new generics syntax (Max Chang, PR [17820](https://github.com/python/mypy/pull/17820))\r\n * Better error for `mypy -p package` without py.typed (Joe Gordon, PR [17908](https://github.com/python/mypy/pull/17908))\r\n * Emit error for `raise NotImplemented` (Brian Schubert, PR [17890](https://github.com/python/mypy/pull/17890))\r\n * Add `is_lvalue` attribute to AttributeContext (Brian Schubert, PR [17881](https://github.com/python/mypy/pull/17881))\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n- aatle\r\n- Abel Sen\r\n- Advait Dixit\r\n- ag-tafe\r\n- Alex Waygood\r\n- Ali Hamdan\r\n- Brian Schubert\r\n- Carlton Gibson\r\n- Chad Dombrova\r\n- Chelsea Durazo\r\n- chiri\r\n- Christoph Tyralla\r\n- coldwolverine\r\n- David Salvisberg\r\n- Ekin Dursun\r\n- Evgeniy Slobodkin\r\n- falsedrow\r\n- Gaurav Giri\r\n- Ihor\r\n- Ivan Levkivskyi\r\n- jairov4\r\n- Jannick Kremer\r\n- Jared Hance\r\n- Jelle Zijlstra\r\n- jianghuyiyuan\r\n- Joe Gordon\r\n- John Doknjas\r\n- Jukka Lehtosalo\r\n- Kanishk Pachauri\r\n- Marc Mueller\r\n- Max Chang\r\n- MechanicalConstruct\r\n- Newbyte\r\n- q0w\r\n- Ruslan Sayfutdinov\r\n- Sebastian Rittau\r\n- Shantanu\r\n- sobolevn\r\n- Stanislav Terliakov\r\n- Stephen Morton\r\n- Sukhorosov Aleksey\r\n- Séamus Ó Ceanainn\r\n- Terence Honles\r\n- Valentin Stanciu\r\n- vasiliy\r\n- Victorien\r\n- yihong\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\n\r\n## Mypy 1.13\r\n\r\nWe’ve just uploaded mypy 1.13 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)).\r\nMypy is a static type checker for Python. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\nNote that unlike typical releases, Mypy 1.13 does not have any changes to type checking semantics\r\nfrom 1.12.1.\r\n\r\n### Improved Performance\r\n\r\nMypy 1.13 contains several performance improvements. Users can expect mypy to be 5-20% faster.\r\nIn environments with long search paths (such as environments using many editable installs), mypy\r\ncan be significantly faster, e.g. 2.2x faster in the use case targeted by these improvements.\r\n\r\nMypy 1.13 allows use of the `orjson` library for handling the cache instead of the stdlib `json`,\r\nfor improved performance. You can ensure the presence of `orjson` using the `faster-cache` extra:\r\n\r\n    python3 -m pip install -U mypy[faster-cache]\r\n\r\nMypy may depend on `orjson` by default in the future.\r\n\r\nThese improvements were contributed by Shantanu.\r\n\r\nList of changes:\r\n* Significantly speed up file handling error paths (Shantanu, PR [17920](https://github.com/python/mypy/pull/17920))\r\n* Use fast path in modulefinder more often (Shantanu, PR [17950](https://github.com/python/mypy/pull/17950))\r\n* Let mypyc optimise os.path.join (Shantanu, PR [17949](https://github.com/python/mypy/pull/17949))\r\n* Make is_sub_path faster (Shantanu, PR [17962](https://github.com/python/mypy/pull/17962))\r\n* Speed up stubs suggestions (Shantanu, PR [17965](https://github.com/python/mypy/pull/17965))\r\n* Use sha1 for hashing (Shantanu, PR [17953](https://github.com/python/mypy/pull/17953))\r\n* Use orjson instead of json, when available (Shantanu, PR [17955](https://github.com/python/mypy/pull/17955))\r\n* Add faster-cache extra, test in CI (Shantanu, PR [17978](https://github.com/python/mypy/pull/17978))\r\n\r\n### Acknowledgements\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n- Shantanu Jain\r\n- Jukka Lehtosalo\r\n\r\n## Mypy 1.12\r\n\r\nWe’ve just uploaded mypy 1.12 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type\r\nchecker for Python. This release includes new features, performance improvements and bug fixes.\r\nYou can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Support Python 3.12 Syntax for Generics (PEP 695)\r\n\r\nSupport for the new type parameter syntax introduced in Python 3.12 is now enabled by default,\r\ndocumented, and no longer experimental. It was available through a feature flag in\r\nmypy 1.11 as an experimental feature.\r\n\r\nThis example demonstrates the new syntax:\r\n\r\n```python\r\n# Generic function\r\ndef f[T](x: T) -> T: ...\r\n\r\nreveal_type(f(1))  # Revealed type is 'int'\r\n\r\n# Generic class\r\nclass C[T]:\r\n    def __init__(self, x: T) -> None:\r\n       self.x = x\r\n\r\nc = C('a')\r\nreveal_type(c.x)  # Revealed type is 'str'\r\n\r\n# Type alias\r\ntype A[T] = C[list[T]]\r\n```\r\n\r\nFor more information, refer to the [documentation](https://mypy.readthedocs.io/en/latest/generics.html).\r\n\r\nThese improvements are included:\r\n\r\n * Document Python 3.12 type parameter syntax (Jukka Lehtosalo, PR [17816](https://github.com/python/mypy/pull/17816))\r\n * Further documentation updates (Jukka Lehtosalo, PR [17826](https://github.com/python/mypy/pull/17826))\r\n * Allow Self return types with contravariance (Jukka Lehtosalo, PR [17786](https://github.com/python/mypy/pull/17786))\r\n * Enable new type parameter syntax by default (Jukka Lehtosalo, PR [17798](https://github.com/python/mypy/pull/17798))\r\n * Generate error if new-style type alias used as base class (Jukka Lehtosalo, PR [17789](https://github.com/python/mypy/pull/17789))\r\n * Inherit variance if base class has explicit variance (Jukka Lehtosalo, PR [17787](https://github.com/python/mypy/pull/17787))\r\n * Fix crash on invalid type var reference (Jukka Lehtosalo, PR [17788](https://github.com/python/mypy/pull/17788))\r\n * Fix covariance of frozen dataclasses (Jukka Lehtosalo, PR [17783](https://github.com/python/mypy/pull/17783))\r\n * Allow covariance with attribute that has \"`_`\" name prefix (Jukka Lehtosalo, PR [17782](https://github.com/python/mypy/pull/17782))\r\n * Support `Annotated[...]` in new-style type aliases (Jukka Lehtosalo, PR [17777](https://github.com/python/mypy/pull/17777))\r\n * Fix nested generic classes (Jukka Lehtosalo, PR [17776](https://github.com/python/mypy/pull/17776))\r\n * Add detection and error reporting for the use of incorrect expressions within the scope of a type parameter and a type alias (Kirill Podoprigora, PR [17560](https://github.com/python/mypy/pull/17560))\r\n\r\n### Basic Support for Python 3.13\r\n\r\nThis release adds partial support for Python 3.13 features and compiled binaries for\r\nPython 3.13. Mypyc now also supports Python 3.13.\r\n\r\nIn particular, these features are supported:\r\n * Various new stdlib features and changes (through typeshed stub improvements)\r\n * `typing.ReadOnly` (see below for more)\r\n * `typing.TypeIs` (added in mypy 1.10, [PEP 742](https://peps.python.org/pep-0742/))\r\n * Type parameter defaults when using the legacy syntax ([PEP 696](https://peps.python.org/pep-0696/))\r\n\r\nThese features are not supported yet:\r\n * `warnings.deprecated` ([PEP 702](https://peps.python.org/pep-0702/))\r\n * Type parameter defaults when using Python 3.12 type parameter syntax\r\n\r\n### Mypyc Support for Python 3.13\r\n\r\nMypyc now supports Python 3.13. This was contributed by Marc Mueller, with additional\r\nfixes by Jukka Lehtosalo. Free threaded Python 3.13 builds are not supported yet.\r\n\r\nList of changes:\r\n\r\n * Add additional includes for Python 3.13 (Marc Mueller, PR [17506](https://github.com/python/mypy/pull/17506))\r\n * Add another include for Python 3.13 (Marc Mueller, PR [17509](https://github.com/python/mypy/pull/17509))\r\n * Fix ManagedDict functions for Python 3.13 (Marc Mueller, PR [17507](https://github.com/python/mypy/pull/17507))\r\n * Update mypyc test output for Python 3.13 (Marc Mueller, PR [17508](https://github.com/python/mypy/pull/17508))\r\n * Fix `PyUnicode` functions for Python 3.13 (Marc Mueller, PR [17504](https://github.com/python/mypy/pull/17504))\r\n * Fix `_PyObject_LookupAttrId` for Python 3.13 (Marc Mueller, PR [17505](https://github.com/python/mypy/pull/17505))\r\n * Fix `_PyList_Extend` for Python 3.13 (Marc Mueller, PR [17503](https://github.com/python/mypy/pull/17503))\r\n * Fix `gen_is_coroutine` for Python 3.13 (Marc Mueller, PR [17501](https://github.com/python/mypy/pull/17501))\r\n * Fix `_PyObject_FastCall` for Python 3.13 (Marc Mueller, PR [17502](https://github.com/python/mypy/pull/17502))\r\n * Avoid uses of `_PyObject_CallMethodOneArg` on 3.13 (Jukka Lehtosalo, PR [17526](https://github.com/python/mypy/pull/17526))\r\n * Don't rely on `_PyType_CalculateMetaclass` on 3.13 (Jukka Lehtosalo, PR [17525](https://github.com/python/mypy/pull/17525))\r\n * Don't use `_PyUnicode_FastCopyCharacters` on 3.13 (Jukka Lehtosalo, PR [17524](https://github.com/python/mypy/pull/17524))\r\n * Don't use `_PyUnicode_EQ` on 3.13, as it's no longer exported (Jukka Lehtosalo, PR [17523](https://github.com/python/mypy/pull/17523))\r\n\r\n### Inferring Unions for Conditional Expressions\r\n\r\nMypy now always tries to infer a union type for a conditional expression if left and right\r\noperand types are different. This results in more precise inferred types and lets mypy detect\r\nmore issues. Example:\r\n\r\n```python\r\ns = \"foo\" if cond() else 1\r\n# Type of \"s\" is now \"str | int\" (it used to be \"object\")\r\n```\r\n\r\nNotably, if one of the operands has type `Any`, the type of a conditional expression is\r\nnow `<type> | Any`. Previously the inferred type was just `Any`. The new type essentially\r\nindicates that the value can be of type `<type>`, and potentially of some (unknown) type.\r\nMost operations performed on the result must also be valid for `<type>`.\r\nExample where this is relevant:\r\n\r\n```python\r\nfrom typing import Any\r\n\r\ndef func(a: Any, b: bool) -> None:\r\n    x = a if b else None\r\n    # Type of x is \"Any | None\"\r\n    print(x.y)  # Error: None has no attribute \"y\"\r\n```\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [17427](https://github.com/python/mypy/pull/17427)).\r\n\r\n### ReadOnly Support for TypedDict (PEP 705)\r\n\r\nYou can now use `typing.ReadOnly` to specity TypedDict items as\r\nread-only ([PEP 705](https://peps.python.org/pep-0705/)):\r\n\r\n```python\r\nfrom typing import TypedDict\r\n\r\n# Or \"from typing ...\" on Python 3.13\r\nfrom typing_extensions import ReadOnly\r\n\r\nclass TD(TypedDict):\r\n    a: int\r\n    b: ReadOnly[int]\r\n\r\nd: TD = {\"a\": 1, \"b\": 2}\r\nd[\"a\"] = 3  # OK\r\nd[\"b\"] = 5  # Error: \"b\" is ReadOnly\r\n```\r\n\r\nThis feature was contributed by Nikita Sobolev (PR [17644](https://github.com/python/mypy/pull/17644)).\r\n\r\n### Python 3.8 End of Life Approaching\r\n\r\nWe are planning to drop support for Python 3.8 in the next mypy feature release or the\r\none after that. Python 3.8 reaches end of life in October 2024.\r\n\r\n### Planned Changes to Defaults\r\n\r\nWe are planning to enable `--local-partial-types` by default in mypy 2.0. This will\r\noften require at least minor code changes. This option is implicitly enabled by mypy\r\ndaemon, so this makes the behavior of daemon and non-daemon modes consistent.\r\n\r\nWe recommend that mypy users start using local partial types soon (or to explicitly disable\r\nthem) to prepare for the change.\r\n\r\nThis can also be configured in a mypy configuration file:\r\n\r\n```\r\nlocal_partial_types = True\r\n```\r\n\r\nFor more information, refer to the\r\n[documentation](https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-local-partial-types).\r\n\r\n### Documentation Updates\r\n\r\nMypy documentation now uses modern syntax variants and imports in many examples. Some\r\nexamples no longer work on Python 3.8, which is the earliest Python version that mypy supports.\r\n\r\nNotably, `Iterable` and other protocols/ABCs are imported from `collections.abc` instead of\r\n`typing`:\r\n```python\r\nfrom collections.abc import Iterable, Callable\r\n```\r\n\r\nExamples also avoid the upper-case aliases to built-in types: `list[str]` is used instead\r\nof `List[str]`. The `X | Y` union type syntax introduced in Python 3.10 is also now prevalent.\r\n\r\nList of documentation updates:\r\n\r\n * Document `--output=json` CLI option (Edgar Ramírez Mondragón, PR [17611](https://github.com/python/mypy/pull/17611))\r\n * Update various references to deprecated type aliases in docs (Jukka Lehtosalo, PR [17829](https://github.com/python/mypy/pull/17829))\r\n * Make \"X | Y\" union syntax more prominent in documentation (Jukka Lehtosalo, PR [17835](https://github.com/python/mypy/pull/17835))\r\n * Discuss upper bounds before self types in documentation (Jukka Lehtosalo, PR [17827](https://github.com/python/mypy/pull/17827))\r\n * Make changelog visible in mypy documentation (quinn-sasha, PR [17742](https://github.com/python/mypy/pull/17742))\r\n * List all incomplete features in `--enable-incomplete-feature` docs (sobolevn, PR [17633](https://github.com/python/mypy/pull/17633))\r\n * Remove the explicit setting of a pygments theme (Pradyun Gedam, PR [17571](https://github.com/python/mypy/pull/17571))\r\n * Document ReadOnly with TypedDict (Jukka Lehtosalo, PR [17905](https://github.com/python/mypy/pull/17905))\r\n * Document TypeIs (Chelsea Durazo, PR [17821](https://github.com/python/mypy/pull/17821))\r\n\r\n### Experimental Inline TypedDict Syntax\r\n\r\nMypy now supports a non-standard, experimental syntax for defining anonymous TypedDicts.\r\nExample:\r\n\r\n```python\r\ndef func(n: str, y: int) -> {\"name\": str, \"year\": int}:\r\n    return {\"name\": n, \"year\": y}\r\n```\r\n\r\nThe feature is disabled by default. Use `--enable-incomplete-feature=InlineTypedDict` to\r\nenable it. *We might remove this feature in a future release.*\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [17457](https://github.com/python/mypy/pull/17457)).\r\n\r\n### Stubgen Improvements\r\n\r\n * Fix crash on literal class-level keywords (sobolevn, PR [17663](https://github.com/python/mypy/pull/17663))\r\n * Stubgen add `--version` (sobolevn, PR [17662](https://github.com/python/mypy/pull/17662))\r\n * Fix `stubgen --no-analysis/--parse-only` docs (sobolevn, PR [17632](https://github.com/python/mypy/pull/17632))\r\n * Include keyword only args when generating signatures in stubgenc (Eric Mark Martin, PR [17448](https://github.com/python/mypy/pull/17448))\r\n * Add support for detecting `Literal` types when extracting types from docstrings (Michael Carlstrom, PR [17441](https://github.com/python/mypy/pull/17441))\r\n * Use `Generator` type var defaults (Sebastian Rittau, PR [17670](https://github.com/python/mypy/pull/17670))\r\n\r\n### Stubtest Improvements\r\n * Add support for `cached_property` (Ali Hamdan, PR [17626](https://github.com/python/mypy/pull/17626))\r\n * Add `enable_incomplete_feature` validation to `stubtest` (sobolevn, PR [17635](https://github.com/python/mypy/pull/17635))\r\n * Fix error code handling in `stubtest` with `--mypy-config-file` (sobolevn, PR [17629](https://github.com/python/mypy/pull/17629))\r\n\r\n### Other Notables Fixes and Improvements\r\n\r\n * Report error if using unsupported type parameter defaults (Jukka Lehtosalo, PR [17876](https://github.com/python/mypy/pull/17876))\r\n * Fix re-processing cross-reference in mypy daemon when node kind changes (Ivan Levkivskyi, PR [17883](https://github.com/python/mypy/pull/17883))\r\n * Don't use equality to narrow when value is IntEnum/StrEnum (Jukka Lehtosalo, PR [17866](https://github.com/python/mypy/pull/17866))\r\n * Don't consider None vs IntEnum comparison ambiguous (Jukka Lehtosalo, PR [17877](https://github.com/python/mypy/pull/17877))\r\n * Fix narrowing of IntEnum and StrEnum types (Jukka Lehtosalo, PR [17874](https://github.com/python/mypy/pull/17874))\r\n * Filter overload items based on self type during type inference (Jukka Lehtosalo, PR [17873](https://github.com/python/mypy/pull/17873))\r\n * Enable negative narrowing of union TypeVar upper bounds (Brian Schubert, PR [17850](https://github.com/python/mypy/pull/17850))\r\n * Fix issue with member expression formatting (Brian Schubert, PR [17848](https://github.com/python/mypy/pull/17848))\r\n * Avoid type size explosion when expanding types (Jukka Lehtosalo, PR [17842](https://github.com/python/mypy/pull/17842))\r\n * Fix negative narrowing of tuples in match statement (Brian Schubert, PR [17817](https://github.com/python/mypy/pull/17817))\r\n * Narrow falsey str/bytes/int to literal type (Brian Schubert, PR [17818](https://github.com/python/mypy/pull/17818))\r\n * Test against latest Python 3.13, make testing 3.14 easy (Shantanu, PR [17812](https://github.com/python/mypy/pull/17812))\r\n * Reject ParamSpec-typed callables calls with insufficient arguments (Stanislav Terliakov, PR [17323](https://github.com/python/mypy/pull/17323))\r\n * Fix crash when passing too many type arguments to generic base class accepting single ParamSpec (Brian Schubert, PR [17770](https://github.com/python/mypy/pull/17770))\r\n * Fix TypeVar upper bounds sometimes not being displayed in pretty callables (Brian Schubert, PR [17802](https://github.com/python/mypy/pull/17802))\r\n * Added error code for overlapping function signatures (Katrina Connors, PR [17597](https://github.com/python/mypy/pull/17597))\r\n * Check for `truthy-bool` in `not ...` unary expressions (sobolevn, PR [17773](https://github.com/python/mypy/pull/17773))\r\n * Add missing lines-covered and lines-valid attributes (Soubhik Kumar Mitra, PR [17738](https://github.com/python/mypy/pull/17738))\r\n * Fix another crash scenario with recursive tuple types (Ivan Levkivskyi, PR [17708](https://github.com/python/mypy/pull/17708))\r\n * Resolve TypeVar upper bounds in `functools.partial` (Shantanu, PR [17660](https://github.com/python/mypy/pull/17660))\r\n * Always reset binder when checking deferred nodes (Ivan Levkivskyi, PR [17643](https://github.com/python/mypy/pull/17643))\r\n * Fix crash on a callable attribute with single unpack (Ivan Levkivskyi, PR [17641](https://github.com/python/mypy/pull/17641))\r\n * Fix mismatched signature between checker plugin API and implementation (bzoracler, PR [17343](https://github.com/python/mypy/pull/17343))\r\n * Indexing a type also produces a GenericAlias (Shantanu, PR [17546](https://github.com/python/mypy/pull/17546))\r\n * Fix crash on self-type in callable protocol (Ivan Levkivskyi, PR [17499](https://github.com/python/mypy/pull/17499))\r\n * Fix crash on NamedTuple with method and error in function (Ivan Levkivskyi, PR [17498](https://github.com/python/mypy/pull/17498))\r\n * Add `__replace__` for dataclasses in 3.13 (Max Muoto, PR [17469](https://github.com/python/mypy/pull/17469))\r\n * Fix help message for `--no-namespace-packages` (Raphael Krupinski, PR [17472](https://github.com/python/mypy/pull/17472))\r\n * Fix typechecking for async generators (Danny Yang, PR [17452](https://github.com/python/mypy/pull/17452))\r\n * Fix strict optional handling in attrs plugin (Ivan Levkivskyi, PR [17451](https://github.com/python/mypy/pull/17451))\r\n * Allow mixing ParamSpec and TypeVarTuple in Generic (Ivan Levkivskyi, PR [17450](https://github.com/python/mypy/pull/17450))\r\n * Improvements to `functools.partial` of types (Shantanu, PR [17898](https://github.com/python/mypy/pull/17898))\r\n * Make ReadOnly TypedDict items covariant (Jukka Lehtosalo, PR [17904](https://github.com/python/mypy/pull/17904))\r\n * Fix union callees with `functools.partial` (Jukka Lehtosalo, PR [17903](https://github.com/python/mypy/pull/17903))\r\n * Improve handling of generic functions with `functools.partial` (Ivan Levkivskyi, PR [17925](https://github.com/python/mypy/pull/17925))\r\n\r\n### Typeshed Updates\r\n\r\nPlease see [git log](https://github.com/python/typeshed/commits/main?after=91a58b07cdd807b1d965e04ba85af2adab8bf924+0&branch=main&path=stdlib) for full list of standard library typeshed stub changes.\r\n\r\n### Mypy 1.12.1\r\n * Fix crash when showing partially analyzed type in error message (Ivan Levkivskyi, PR [17961](https://github.com/python/mypy/pull/17961))\r\n * Fix iteration over union (when self type is involved) (Shantanu, PR [17976](https://github.com/python/mypy/pull/17976))\r\n * Fix type object with type var default in union context (Jukka Lehtosalo, PR [17991](https://github.com/python/mypy/pull/17991))\r\n * Revert change to `os.path` stubs affecting use of `os.PathLike[Any]` (Shantanu, PR [17995](https://github.com/python/mypy/pull/17995))\r\n\r\n### Acknowledgements\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n- Ali Hamdan\r\n- Anders Kaseorg\r\n- Bénédikt Tran\r\n- Brian Schubert\r\n- bzoracler\r\n- Chelsea Durazo\r\n- Danny Yang\r\n- Edgar Ramírez Mondragón\r\n- Eric Mark Martin\r\n- InSync\r\n- Ivan Levkivskyi\r\n- Jordandev678\r\n- Katrina Connors\r\n- Kirill Podoprigora\r\n- Marc Mueller\r\n- Max Muoto\r\n- Max Murin\r\n- Michael Carlstrom\r\n- Michael I Chen\r\n- Pradyun Gedam\r\n- quinn-sasha\r\n- Raphael Krupinski\r\n- Sebastian Rittau\r\n- Shantanu\r\n- sobolevn\r\n- Soubhik Kumar Mitra\r\n- Stanislav Terliakov\r\n- wyattscarpenter\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\n\r\n## Mypy 1.11\r\n\r\nWe’ve just uploaded mypy 1.11 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Support Python 3.12 Syntax for Generics (PEP 695)\r\n\r\nMypy now supports the new type parameter syntax introduced in Python 3.12 ([PEP 695](https://peps.python.org/pep-0695/)).\r\nThis feature is still experimental and must be enabled with the `--enable-incomplete-feature=NewGenericSyntax` flag, or with `enable_incomplete_feature = NewGenericSyntax` in the mypy configuration file.\r\nWe plan to enable this by default in the next mypy feature release.\r\n\r\nThis example demonstrates the new syntax:\r\n\r\n```python\r\n# Generic function\r\ndef f[T](x: T) -> T: ...\r\n\r\nreveal_type(f(1))  # Revealed type is 'int'\r\n\r\n# Generic class\r\nclass C[T]:\r\n    def __init__(self, x: T) -> None:\r\n       self.x = x\r\n\r\nc = C('a')\r\nreveal_type(c.x)  # Revealed type is 'str'\r\n\r\n# Type alias\r\ntype A[T] = C[list[T]]\r\n```\r\n\r\nThis feature was contributed by Jukka Lehtosalo.\r\n\r\n\r\n### Support for `functools.partial`\r\n\r\nMypy now type checks uses of `functools.partial`. Previously mypy would accept arbitrary arguments.\r\n\r\nThis example will now produce an error:\r\n\r\n```python\r\nfrom functools import partial\r\n\r\ndef f(a: int, b: str) -> None: ...\r\n\r\ng = partial(f, 1)\r\n\r\n# Argument has incompatible type \"int\"; expected \"str\"\r\ng(11)\r\n```\r\n\r\nThis feature was contributed by Shantanu (PR [16939](https://github.com/python/mypy/pull/16939)).\r\n\r\n\r\n### Stricter Checks for Untyped Overrides\r\n\r\nPast mypy versions didn't check if untyped methods were compatible with overridden methods. This would result in false negatives. Now mypy performs these checks when using `--check-untyped-defs`.\r\n\r\nFor example, this now generates an error if using `--check-untyped-defs`:\r\n\r\n```python\r\nclass Base:\r\n    def f(self, x: int = 0) -> None: ...\r\n\r\nclass Derived(Base):\r\n    # Signature incompatible with \"Base\"\r\n    def f(self): ...\r\n```\r\n\r\nThis feature was contributed by Steven Troxler (PR [17276](https://github.com/python/mypy/pull/17276)).\r\n\r\n\r\n### Type Inference Improvements\r\n\r\nThe new polymorphic inference algorithm introduced in mypy 1.5 is now used in more situations. This improves type inference involving generic higher-order functions, in particular.\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [17348](https://github.com/python/mypy/pull/17348)).\r\n\r\nMypy now uses unions of tuple item types in certain contexts to enable more precise inferred types. Example:\r\n\r\n```python\r\nfor x in (1, 'x'):\r\n    # Previously inferred as 'object'\r\n    reveal_type(x)  # Revealed type is 'int | str'\r\n```\r\n\r\nThis was also contributed by Ivan Levkivskyi (PR [17408](https://github.com/python/mypy/pull/17408)).\r\n\r\n\r\n### Improvements to Detection of Overlapping Overloads\r\n\r\nThe details of how mypy checks if two `@overload` signatures are unsafely overlapping were overhauled. This both fixes some false positives, and allows mypy to detect additional unsafe signatures.\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [17392](https://github.com/python/mypy/pull/17392)).\r\n\r\n\r\n### Better Support for Type Hints in Expressions\r\n\r\nMypy now allows more expressions that evaluate to valid type annotations in all expression contexts. The inferred types of these expressions are also sometimes more precise. Previously they were often `object`.\r\n\r\nThis example uses a union type that includes a callable type as an expression, and it no longer generates an error:\r\n\r\n```python\r\nfrom typing import Callable\r\n\r\nprint(Callable[[], int] | None)  # No error\r\n```\r\n\r\nThis feature was contributed by Jukka Lehtosalo (PR [17404](https://github.com/python/mypy/pull/17404)).\r\n\r\n\r\n### Mypyc Improvements\r\n\r\nMypyc now supports the new syntax for generics introduced in Python 3.12 (see above). Another notable improvement is significantly faster basic operations on `int` values.\r\n\r\n * Support Python 3.12 syntax for generic functions and classes (Jukka Lehtosalo, PR [17357](https://github.com/python/mypy/pull/17357))\r\n * Support Python 3.12 type alias syntax (Jukka Lehtosalo, PR [17384](https://github.com/python/mypy/pull/17384))\r\n * Fix ParamSpec (Shantanu, PR [17309](https://github.com/python/mypy/pull/17309))\r\n * Inline fast paths of integer unboxing operations (Jukka Lehtosalo, PR [17266](https://github.com/python/mypy/pull/17266))\r\n * Inline tagged integer arithmetic and bitwise operations (Jukka Lehtosalo, PR [17265](https://github.com/python/mypy/pull/17265))\r\n * Allow specifying primitives as pure (Jukka Lehtosalo, PR [17263](https://github.com/python/mypy/pull/17263))\r\n\r\n\r\n### Changes to Stubtest\r\n * Ignore `_ios_support` (Alex Waygood, PR [17270](https://github.com/python/mypy/pull/17270))\r\n * Improve support for Python 3.13 (Shantanu, PR [17261](https://github.com/python/mypy/pull/17261))\r\n\r\n\r\n### Changes to Stubgen\r\n * Gracefully handle invalid `Optional` and recognize aliases to PEP 604 unions (Ali Hamdan, PR [17386](https://github.com/python/mypy/pull/17386))\r\n * Fix for Python 3.13 (Jelle Zijlstra, PR [17290](https://github.com/python/mypy/pull/17290))\r\n * Preserve enum value initialisers (Shantanu, PR [17125](https://github.com/python/mypy/pull/17125))\r\n\r\n\r\n### Miscellaneous New Features\r\n * Add error format support and JSON output option via `--output json` (Tushar Sadhwani, PR [11396](https://github.com/python/mypy/pull/11396))\r\n * Support `enum.member` in Python 3.11+ (Nikita Sobolev, PR [17382](https://github.com/python/mypy/pull/17382))\r\n * Support `enum.nonmember` in Python 3.11+ (Nikita Sobolev, PR [17376](https://github.com/python/mypy/pull/17376))\r\n * Support `namedtuple.__replace__` in Python 3.13 (Shantanu, PR [17259](https://github.com/python/mypy/pull/17259))\r\n * Support `rename=True` in collections.namedtuple (Jelle Zijlstra, PR [17247](https://github.com/python/mypy/pull/17247))\r\n * Add support for `__spec__` (Shantanu, PR [14739](https://github.com/python/mypy/pull/14739))\r\n\r\n\r\n### Changes to Error Reporting\r\n * Mention `--enable-incomplete-feature=NewGenericSyntax` in messages (Shantanu, PR [17462](https://github.com/python/mypy/pull/17462))\r\n * Do not report plugin-generated methods with `explicit-override` (sobolevn, PR [17433](https://github.com/python/mypy/pull/17433))\r\n * Use and display namespaces for function type variables (Ivan Levkivskyi, PR [17311](https://github.com/python/mypy/pull/17311))\r\n * Fix false positive for Final local scope variable in Protocol (GiorgosPapoutsakis, PR [17308](https://github.com/python/mypy/pull/17308))\r\n * Use Never in more messages, use ambiguous in join (Shantanu, PR [17304](https://github.com/python/mypy/pull/17304))\r\n * Log full path to config file in verbose output (dexterkennedy, PR [17180](https://github.com/python/mypy/pull/17180))\r\n * Added `[prop-decorator]` code for unsupported property decorators (#14461) (Christopher Barber, PR [16571](https://github.com/python/mypy/pull/16571))\r\n * Suppress second error message with `:=` and `[truthy-bool]` (Nikita Sobolev, PR [15941](https://github.com/python/mypy/pull/15941))\r\n * Generate error for assignment of functional Enum to variable of different name (Shantanu, PR [16805](https://github.com/python/mypy/pull/16805))\r\n * Fix error reporting on cached run after uninstallation of third party library (Shantanu, PR [17420](https://github.com/python/mypy/pull/17420))\r\n\r\n\r\n### Fixes for Crashes\r\n * Fix daemon crash on invalid type in TypedDict (Ivan Levkivskyi, PR [17495](https://github.com/python/mypy/pull/17495))\r\n * Fix crash and bugs related to `partial()` (Ivan Levkivskyi, PR [17423](https://github.com/python/mypy/pull/17423))\r\n * Fix crash when overriding with unpacked TypedDict (Ivan Levkivskyi, PR [17359](https://github.com/python/mypy/pull/17359))\r\n * Fix crash on TypedDict unpacking for ParamSpec (Ivan Levkivskyi, PR [17358](https://github.com/python/mypy/pull/17358))\r\n * Fix crash involving recursive union of tuples (Ivan Levkivskyi, PR [17353](https://github.com/python/mypy/pull/17353))\r\n * Fix crash on invalid callable property override (Ivan Levkivskyi, PR [17352](https://github.com/python/mypy/pull/17352))\r\n * Fix crash on unpacking self in NamedTuple (Ivan Levkivskyi, PR [17351](https://github.com/python/mypy/pull/17351))\r\n * Fix crash on recursive alias with an optional type (Ivan Levkivskyi, PR [17350](https://github.com/python/mypy/pull/17350))\r\n * Fix crash on type comment inside generic definitions (Bénédikt Tran, PR [16849](https://github.com/python/mypy/pull/16849))\r\n\r\n\r\n### Changes to Documentation\r\n * Use inline config in documentation for optional error codes (Shantanu, PR [17374](https://github.com/python/mypy/pull/17374))\r\n * Use lower-case generics in documentation (Seo Sanghyeon, PR [17176](https://github.com/python/mypy/pull/17176))\r\n * Add documentation for show-error-code-links (GiorgosPapoutsakis, PR [17144](https://github.com/python/mypy/pull/17144))\r\n * Update CONTRIBUTING.md to include commands for Windows (GiorgosPapoutsakis, PR [17142](https://github.com/python/mypy/pull/17142))\r\n\r\n\r\n### Other Notable Improvements and Fixes\r\n * Fix ParamSpec inference against TypeVarTuple (Ivan Levkivskyi, PR [17431](https://github.com/python/mypy/pull/17431))\r\n * Fix explicit type for `partial` (Ivan Levkivskyi, PR [17424](https://github.com/python/mypy/pull/17424))\r\n * Always allow lambda calls (Ivan Levkivskyi, PR [17430](https://github.com/python/mypy/pull/17430))\r\n * Fix isinstance checks with PEP 604 unions containing None (Shantanu, PR [17415](https://github.com/python/mypy/pull/17415))\r\n * Fix self-referential upper bound in new-style type variables (Ivan Levkivskyi, PR [17407](https://github.com/python/mypy/pull/17407))\r\n * Consider overlap between instances and callables (Ivan Levkivskyi, PR [17389](https://github.com/python/mypy/pull/17389))\r\n * Allow new-style self-types in classmethods (Ivan Levkivskyi, PR [17381](https://github.com/python/mypy/pull/17381))\r\n * Fix isinstance with type aliases to PEP 604 unions (Shantanu, PR [17371](https://github.com/python/mypy/pull/17371))\r\n * Properly handle unpacks in overlap checks (Ivan Levkivskyi, PR [17356](https://github.com/python/mypy/pull/17356))\r\n * Fix type application for classes with generic constructors (Ivan Levkivskyi, PR [17354](https://github.com/python/mypy/pull/17354))\r\n * Update `typing_extensions` to >=4.6.0 to fix Python 3.12 error (Ben Brown, PR [17312](https://github.com/python/mypy/pull/17312))\r\n * Avoid \"does not return\" error in lambda (Shantanu, PR [17294](https://github.com/python/mypy/pull/17294))\r\n * Fix bug with descriptors in non-strict-optional mode (Max Murin, PR [17293](https://github.com/python/mypy/pull/17293))\r\n * Don’t leak unreachability from lambda body to surrounding scope (Anders Kaseorg, PR [17287](https://github.com/python/mypy/pull/17287))\r\n * Fix issues with non-ASCII characters on Windows (Alexander Leopold Shon, PR [17275](https://github.com/python/mypy/pull/17275))\r\n * Fix for type narrowing of negative integer literals (gilesgc, PR [17256](https://github.com/python/mypy/pull/17256))\r\n * Fix confusion between .py and .pyi files in mypy daemon (Valentin Stanciu, PR [17245](https://github.com/python/mypy/pull/17245))\r\n * Fix type of `tuple[X, Y]` expression (urnest, PR [17235](https://github.com/python/mypy/pull/17235))\r\n * Don't forget that a `TypedDict` was wrapped in `Unpack` after a `name-defined` error occurred (Christoph Tyralla, PR [17226](https://github.com/python/mypy/pull/17226))\r\n * Mark annotated argument as having an explicit, not inferred type (bzoracler, PR [17217](https://github.com/python/mypy/pull/17217))\r\n * Don't consider Enum private attributes as enum members (Ali Hamdan, PR [17182](https://github.com/python/mypy/pull/17182))\r\n * Fix Literal strings containing pipe characters (Jelle Zijlstra, PR [17148](https://github.com/python/mypy/pull/17148))\r\n\r\n\r\n### Typeshed Updates\r\n\r\nPlease see [git log](https://github.com/python/typeshed/commits/main?after=6dda799d8ad1d89e0f8aad7ac41d2d34bd838ace+0&branch=main&path=stdlib) for full list of standard library typeshed stub changes.\r\n\r\n### Mypy 1.11.1\r\n * Fix `RawExpressionType.accept` crash with `--cache-fine-grained` (Anders Kaseorg, PR [17588](https://github.com/python/mypy/pull/17588))\r\n * Fix PEP 604 isinstance caching (Shantanu, PR [17563](https://github.com/python/mypy/pull/17563))\r\n * Fix `typing.TypeAliasType` being undefined on python < 3.12 (Nikita Sobolev, PR [17558](https://github.com/python/mypy/pull/17558))\r\n * Fix `types.GenericAlias` lookup crash (Shantanu, PR [17543](https://github.com/python/mypy/pull/17543))\r\n\r\n### Mypy 1.11.2\r\n * Alternative fix for a union-like literal string (Ivan Levkivskyi, PR [17639](https://github.com/python/mypy/pull/17639))\r\n * Unwrap `TypedDict` item types before storing (Ivan Levkivskyi, PR [17640](https://github.com/python/mypy/pull/17640))\r\n\r\n### Acknowledgements\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n- Alex Waygood\r\n- Alexander Leopold Shon\r\n- Ali Hamdan\r\n- Anders Kaseorg\r\n- Ben Brown\r\n- Bénédikt Tran\r\n- bzoracler\r\n- Christoph Tyralla\r\n- Christopher Barber\r\n- dexterkennedy\r\n- gilesgc\r\n- GiorgosPapoutsakis\r\n- Ivan Levkivskyi\r\n- Jelle Zijlstra\r\n- Jukka Lehtosalo\r\n- Marc Mueller\r\n- Matthieu Devlin\r\n- Michael R. Crusoe\r\n- Nikita Sobolev\r\n- Seo Sanghyeon\r\n- Shantanu\r\n- sobolevn\r\n- Steven Troxler\r\n- Tadeu Manoel\r\n- Tamir Duberstein\r\n- Tushar Sadhwani\r\n- urnest\r\n- Valentin Stanciu\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\n\r\n## Mypy 1.10\r\n\r\nWe’ve just uploaded mypy 1.10 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Support TypeIs (PEP 742)\r\n\r\nMypy now supports `TypeIs` ([PEP 742](https://peps.python.org/pep-0742/)), which allows\r\nfunctions to narrow the type of a value, similar to `isinstance()`. Unlike `TypeGuard`,\r\n`TypeIs` can narrow in both the `if` and `else` branches of an if statement:\r\n\r\n```python\r\nfrom typing_extensions import TypeIs\r\n\r\ndef is_str(s: object) -> TypeIs[str]:\r\n    return isinstance(s, str)\r\n\r\ndef f(o: str | int) -> None:\r\n    if is_str(o):\r\n        # Type of o is 'str'\r\n        ...\r\n    else:\r\n        # Type of o is 'int'\r\n        ...\r\n```\r\n\r\n`TypeIs` will be added to the `typing` module in Python 3.13, but it\r\ncan be used on earlier Python versions by importing it from\r\n`typing_extensions`.\r\n\r\nThis feature was contributed by Jelle Zijlstra (PR [16898](https://github.com/python/mypy/pull/16898)).\r\n\r\n### Support TypeVar Defaults (PEP 696)\r\n\r\n[PEP 696](https://peps.python.org/pep-0696/) adds support for type parameter defaults.\r\nExample:\r\n\r\n```python\r\nfrom typing import Generic\r\nfrom typing_extensions import TypeVar\r\n\r\nT = TypeVar(\"T\", default=int)\r\n\r\nclass C(Generic[T]):\r\n   ...\r\n\r\nx: C = ...\r\ny: C[str] = ...\r\nreveal_type(x)  # C[int], because of the default\r\nreveal_type(y)  # C[str]\r\n```\r\n\r\nTypeVar defaults will be added to the `typing` module in Python 3.13, but they\r\ncan be used with earlier Python releases by importing `TypeVar` from\r\n`typing_extensions`.\r\n\r\nThis feature was contributed by Marc Mueller (PR [16878](https://github.com/python/mypy/pull/16878)\r\nand PR [16925](https://github.com/python/mypy/pull/16925)).\r\n\r\n### Support TypeAliasType (PEP 695)\r\nAs part of the initial steps towards implementing [PEP 695](https://peps.python.org/pep-0695/), mypy now supports `TypeAliasType`.\r\n`TypeAliasType` provides a backport of the new `type` statement in Python 3.12.\r\n\r\n```python\r\ntype ListOrSet[T] = list[T] | set[T]\r\n```\r\n\r\nis equivalent to:\r\n\r\n```python\r\nT = TypeVar(\"T\")\r\nListOrSet = TypeAliasType(\"ListOrSet\", list[T] | set[T], type_params=(T,))\r\n```\r\n\r\nExample of use in mypy:\r\n\r\n```python\r\nfrom typing_extensions import TypeAliasType, TypeVar\r\n\r\nNewUnionType = TypeAliasType(\"NewUnionType\", int | str)\r\nx: NewUnionType = 42\r\ny: NewUnionType = 'a'\r\nz: NewUnionType = object()  # error: Incompatible types in assignment (expression has type \"object\", variable has type \"int | str\")  [assignment]\r\n\r\nT = TypeVar(\"T\")\r\nListOrSet = TypeAliasType(\"ListOrSet\", list[T] | set[T], type_params=(T,))\r\na: ListOrSet[int] = [1, 2]\r\nb: ListOrSet[str] = {'a', 'b'}\r\nc: ListOrSet[str] = 'test'  # error: Incompatible types in assignment (expression has type \"str\", variable has type \"list[str] | set[str]\")  [assignment]\r\n```\r\n\r\n`TypeAliasType` was added to the `typing` module in Python 3.12, but it can be used with earlier Python releases by importing from `typing_extensions`.\r\n\r\nThis feature was contributed by Ali Hamdan (PR [16926](https://github.com/python/mypy/pull/16926), PR [17038](https://github.com/python/mypy/pull/17038) and PR [17053](https://github.com/python/mypy/pull/17053))\r\n\r\n### Detect Additional Unsafe Uses of super()\r\n\r\nMypy will reject unsafe uses of `super()` more consistently, when the target has a\r\ntrivial (empty) body. Example:\r\n\r\n```python\r\nclass Proto(Protocol):\r\n    def method(self) -> int: ...\r\n\r\nclass Sub(Proto):\r\n    def method(self) -> int:\r\n        return super().meth()  # Error (unsafe)\r\n```\r\n\r\nThis feature was contributed by Shantanu (PR [16756](https://github.com/python/mypy/pull/16756)).\r\n\r\n### Stubgen Improvements\r\n- Preserve empty tuple annotation (Ali Hamdan, PR [16907](https://github.com/python/mypy/pull/16907))\r\n- Add support for PEP 570 positional-only parameters (Ali Hamdan, PR [16904](https://github.com/python/mypy/pull/16904))\r\n- Replace obsolete typing aliases with builtin containers (Ali Hamdan, PR [16780](https://github.com/python/mypy/pull/16780))\r\n- Fix generated dataclass `__init__` signature (Ali Hamdan, PR [16906](https://github.com/python/mypy/pull/16906))\r\n\r\n### Mypyc Improvements\r\n\r\n- Provide an easier way to define IR-to-IR transforms (Jukka Lehtosalo, PR [16998](https://github.com/python/mypy/pull/16998))\r\n- Implement lowering pass and add primitives for int (in)equality (Jukka Lehtosalo, PR [17027](https://github.com/python/mypy/pull/17027))\r\n- Implement lowering for remaining tagged integer comparisons (Jukka Lehtosalo, PR [17040](https://github.com/python/mypy/pull/17040))\r\n- Optimize away some bool/bit registers (Jukka Lehtosalo, PR [17022](https://github.com/python/mypy/pull/17022))\r\n- Remangle redefined names produced by async with (Richard Si, PR [16408](https://github.com/python/mypy/pull/16408))\r\n- Optimize TYPE_CHECKING to False at Runtime (Srinivas Lade, PR [16263](https://github.com/python/mypy/pull/16263))\r\n- Fix compilation of unreachable comprehensions (Richard Si, PR [15721](https://github.com/python/mypy/pull/15721))\r\n- Don't crash on non-inlinable final local reads (Richard Si, PR [15719](https://github.com/python/mypy/pull/15719))\r\n\r\n### Documentation Improvements\r\n- Import `TypedDict` from `typing` instead of `typing_extensions` (Riccardo Di Maio, PR [16958](https://github.com/python/mypy/pull/16958))\r\n- Add missing `mutable-override` to section title (James Braza, PR [16886](https://github.com/python/mypy/pull/16886))\r\n\r\n### Error Reporting Improvements\r\n\r\n- Use lower-case generics more consistently in error messages (Jukka Lehtosalo, PR [17035](https://github.com/python/mypy/pull/17035))\r\n\r\n### Other Notable Changes and Fixes\r\n- Fix incorrect inferred type when accessing descriptor on union type (Matthieu Devlin, PR [16604](https://github.com/python/mypy/pull/16604))\r\n- Fix crash when expanding invalid `Unpack` in a `Callable` alias (Ali Hamdan, PR [17028](https://github.com/python/mypy/pull/17028))\r\n- Fix false positive when string formatting with string enum (roberfi, PR [16555](https://github.com/python/mypy/pull/16555))\r\n- Narrow individual items when matching a tuple to a sequence pattern (Loïc Simon, PR [16905](https://github.com/python/mypy/pull/16905))\r\n- Fix false positive from type variable within TypeGuard or TypeIs (Evgeniy Slobodkin, PR [17071](https://github.com/python/mypy/pull/17071))\r\n- Improve `yield from` inference for unions of generators (Shantanu, PR [16717](https://github.com/python/mypy/pull/16717))\r\n- Fix emulating hash method logic in `attrs` classes (Hashem, PR [17016](https://github.com/python/mypy/pull/17016))\r\n- Add reverted typeshed commit that uses `ParamSpec` for `functools.wraps` (Tamir Duberstein, PR [16942](https://github.com/python/mypy/pull/16942))\r\n- Fix type narrowing for `types.EllipsisType` (Shantanu, PR [17003](https://github.com/python/mypy/pull/17003))\r\n- Fix single item enum match type exhaustion (Oskari Lehto, PR [16966](https://github.com/python/mypy/pull/16966))\r\n- Improve type inference with empty collections (Marc Mueller, PR [16994](https://github.com/python/mypy/pull/16994))\r\n- Fix override checking for decorated property (Shantanu, PR [16856](https://github.com/python/mypy/pull/16856))\r\n- Fix narrowing on match with function subject (Edward Paget, PR [16503](https://github.com/python/mypy/pull/16503))\r\n- Allow `+N` within `Literal[...]` (Spencer Brown, PR [16910](https://github.com/python/mypy/pull/16910))\r\n- Experimental: Support TypedDict within `type[...]` (Marc Mueller, PR [16963](https://github.com/python/mypy/pull/16963))\r\n- Experimtental: Fix issue with TypedDict with optional keys in `type[...]` (Marc Mueller, PR [17068](https://github.com/python/mypy/pull/17068))\r\n\r\n### Typeshed Updates\r\n\r\nPlease see [git log](https://github.com/python/typeshed/commits/main?after=6dda799d8ad1d89e0f8aad7ac41d2d34bd838ace+0&branch=main&path=stdlib) for full list of standard library typeshed stub changes.\r\n\r\n### Mypy 1.10.1\r\n\r\n- Fix error reporting on cached run after uninstallation of third party library (Shantanu, PR [17420](https://github.com/python/mypy/pull/17420))\r\n\r\n### Acknowledgements\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n- Alex Waygood\r\n- Ali Hamdan\r\n- Edward Paget\r\n- Evgeniy Slobodkin\r\n- Hashem\r\n- hesam\r\n- Hugo van Kemenade\r\n- Ihor\r\n- James Braza\r\n- Jelle Zijlstra\r\n- jhance\r\n- Jukka Lehtosalo\r\n- Loïc Simon\r\n- Marc Mueller\r\n- Matthieu Devlin\r\n- Michael R. Crusoe\r\n- Nikita Sobolev\r\n- Oskari Lehto\r\n- Riccardo Di Maio\r\n- Richard Si\r\n- roberfi\r\n- Roman Solomatin\r\n- Sam Xifaras\r\n- Shantanu\r\n- Spencer Brown\r\n- Srinivas Lade\r\n- Tamir Duberstein\r\n- youkaichao\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\n\r\n## Mypy 1.9\r\n\r\nWe’ve just uploaded mypy 1.9 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Breaking Changes\r\n\r\nBecause the version of typeshed we use in mypy 1.9 doesn't support 3.7, neither does mypy 1.9. (Jared Hance, PR [16883](https://github.com/python/mypy/pull/16883))\r\n\r\nWe are planning to enable\r\n[local partial types](https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-local-partial-types) (enabled via the\r\n`--local-partial-types` flag) later this year by default. This change\r\nwas announced years ago, but now it's finally happening. This is a\r\nmajor backward-incompatible change, so we'll probably include it as\r\npart of the upcoming mypy 2.0 release. This makes daemon and\r\nnon-daemon mypy runs have the same behavior by default.\r\n\r\nLocal partial types can also be enabled in the mypy config file:\r\n```\r\nlocal_partial_types = True\r\n```\r\n\r\nWe are looking at providing a tool to make it easier to migrate\r\nprojects to use `--local-partial-types`, but it's not yet clear whether\r\nthis is practical. The migration usually involves adding some\r\nexplicit type annotations to module-level and class-level variables.\r\n\r\n### Basic Support for Type Parameter Defaults (PEP 696)\r\n\r\nThis release contains new experimental support for type parameter\r\ndefaults ([PEP 696](https://peps.python.org/pep-0696)). Please try it\r\nout! This feature was contributed by Marc Mueller.\r\n\r\nSince this feature will be officially introduced in the next Python\r\nfeature release (3.13), you will need to import `TypeVar`, `ParamSpec`\r\nor `TypeVarTuple` from `typing_extensions` to use defaults for now.\r\n\r\nThis example adapted from the PEP defines a default for `BotT`:\r\n```python\r\nfrom typing import Generic\r\nfrom typing_extensions import TypeVar\r\n\r\nclass Bot: ...\r\n\r\nBotT = TypeVar(\"BotT\", bound=Bot, default=Bot)\r\n\r\nclass Context(Generic[BotT]):\r\n    bot: BotT\r\n\r\nclass MyBot(Bot): ...\r\n\r\n# type is Bot (the default)\r\nreveal_type(Context().bot)\r\n# type is MyBot\r\nreveal_type(Context[MyBot]().bot)\r\n```\r\n\r\n### Type-checking Improvements\r\n * Fix missing type store for overloads (Marc Mueller, PR [16803](https://github.com/python/mypy/pull/16803))\r\n * Fix `'WriteToConn' object has no attribute 'flush'` (Charlie Denton, PR [16801](https://github.com/python/mypy/pull/16801))\r\n * Improve TypeAlias error messages (Marc Mueller, PR [16831](https://github.com/python/mypy/pull/16831))\r\n * Support narrowing unions that include `type[None]` (Christoph Tyralla, PR [16315](https://github.com/python/mypy/pull/16315))\r\n * Support TypedDict functional syntax as class base type (anniel-stripe, PR [16703](https://github.com/python/mypy/pull/16703))\r\n * Accept multiline quoted annotations (Shantanu, PR [16765](https://github.com/python/mypy/pull/16765))\r\n * Allow unary + in `Literal` (Jelle Zijlstra, PR [16729](https://github.com/python/mypy/pull/16729))\r\n * Substitute type variables in return type of static methods (Kouroche Bouchiat, PR [16670](https://github.com/python/mypy/pull/16670))\r\n * Consider TypeVarTuple to be invariant (Marc Mueller, PR [16759](https://github.com/python/mypy/pull/16759))\r\n * Add `alias` support to `field()` in `attrs` plugin (Nikita Sobolev, PR [16610](https://github.com/python/mypy/pull/16610))\r\n * Improve attrs hashability detection (Tin Tvrtković, PR [16556](https://github.com/python/mypy/pull/16556))\r\n\r\n### Performance Improvements\r\n\r\n * Speed up finding function type variables (Jukka Lehtosalo, PR [16562](https://github.com/python/mypy/pull/16562))\r\n\r\n### Documentation Updates\r\n\r\n * Document supported values for `--enable-incomplete-feature` in \"mypy --help\" (Froger David, PR [16661](https://github.com/python/mypy/pull/16661))\r\n * Update new type system discussion links (thomaswhaley, PR [16841](https://github.com/python/mypy/pull/16841))\r\n * Add missing class instantiation to cheat sheet (Aleksi Tarvainen, PR [16817](https://github.com/python/mypy/pull/16817))\r\n * Document how evil `--no-strict-optional` is (Shantanu, PR [16731](https://github.com/python/mypy/pull/16731))\r\n * Improve mypy daemon documentation note about local partial types (Makonnen Makonnen, PR [16782](https://github.com/python/mypy/pull/16782))\r\n * Fix numbering error (Stefanie Molin, PR [16838](https://github.com/python/mypy/pull/16838))\r\n * Various documentation improvements (Shantanu, PR [16836](https://github.com/python/mypy/pull/16836))\r\n\r\n### Stubtest Improvements\r\n * Ignore private function/method parameters when they are missing from the stub (private parameter names start with a single underscore and have a default) (PR [16507](https://github.com/python/mypy/pull/16507))\r\n * Ignore a new protocol dunder (Alex Waygood, PR [16895](https://github.com/python/mypy/pull/16895))\r\n * Private parameters can be omitted (Sebastian Rittau, PR [16507](https://github.com/python/mypy/pull/16507))\r\n * Add support for setting enum members to \"...\" (Jelle Zijlstra, PR [16807](https://github.com/python/mypy/pull/16807))\r\n * Adjust symbol table logic (Shantanu, PR [16823](https://github.com/python/mypy/pull/16823))\r\n * Fix posisitional-only handling in overload resolution (Shantanu, PR [16750](https://github.com/python/mypy/pull/16750))\r\n\r\n### Stubgen Improvements\r\n * Fix crash on star unpack of TypeVarTuple (Ali Hamdan, PR [16869](https://github.com/python/mypy/pull/16869))\r\n * Use PEP 604 unions everywhere (Ali Hamdan, PR [16519](https://github.com/python/mypy/pull/16519))\r\n * Do not ignore property deleter (Ali Hamdan, PR [16781](https://github.com/python/mypy/pull/16781))\r\n * Support type stub generation for `staticmethod` (WeilerMarcel, PR [14934](https://github.com/python/mypy/pull/14934))\r\n\r\n### Acknowledgements\r\n\r\n​Thanks to all mypy contributors who contributed to this release:\r\n\r\n- Aleksi Tarvainen\r\n- Alex Waygood\r\n- Ali Hamdan\r\n- anniel-stripe\r\n- Charlie Denton\r\n- Christoph Tyralla\r\n- Dheeraj\r\n- Fabian Keller\r\n- Fabian Lewis\r\n- Froger David\r\n- Ihor\r\n- Jared Hance\r\n- Jelle Zijlstra\r\n- Jukka Lehtosalo\r\n- Kouroche Bouchiat\r\n- Lukas Geiger\r\n- Maarten Huijsmans\r\n- Makonnen Makonnen\r\n- Marc Mueller\r\n- Nikita Sobolev\r\n- Sebastian Rittau\r\n- Shantanu\r\n- Stefanie Molin\r\n- Stephen Morton\r\n- thomaswhaley\r\n- Tin Tvrtković\r\n- WeilerMarcel\r\n- Wesley Collin Wright\r\n- zipperer\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\n## Mypy 1.8\r\n\r\nWe’ve just uploaded mypy 1.8 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Type-checking Improvements\r\n * Do not intersect types in isinstance checks if at least one is final (Christoph Tyralla, PR [16330](https://github.com/python/mypy/pull/16330))\r\n * Detect that `@final` class without `__bool__` cannot have falsey instances (Ilya Priven, PR [16566](https://github.com/python/mypy/pull/16566))\r\n * Do not allow `TypedDict` classes with extra keywords (Nikita Sobolev, PR [16438](https://github.com/python/mypy/pull/16438))\r\n * Do not allow class-level keywords for `NamedTuple` (Nikita Sobolev, PR [16526](https://github.com/python/mypy/pull/16526))\r\n * Make imprecise constraints handling more robust (Ivan Levkivskyi, PR [16502](https://github.com/python/mypy/pull/16502))\r\n * Fix strict-optional in extending generic TypedDict (Ivan Levkivskyi, PR [16398](https://github.com/python/mypy/pull/16398))\r\n * Allow type ignores of PEP 695 constructs (Shantanu, PR [16608](https://github.com/python/mypy/pull/16608))\r\n * Enable `type_check_only` support for `TypedDict` and `NamedTuple` (Nikita Sobolev, PR [16469](https://github.com/python/mypy/pull/16469))\r\n\r\n### Performance Improvements\r\n * Add fast path to analyzing special form assignments (Jukka Lehtosalo, PR [16561](https://github.com/python/mypy/pull/16561))\r\n\r\n### Improvements to Error Reporting\r\n * Don't show documentation links for plugin error codes (Ivan Levkivskyi, PR [16383](https://github.com/python/mypy/pull/16383))\r\n * Improve error messages for `super` checks and add more tests (Nikita Sobolev, PR [16393](https://github.com/python/mypy/pull/16393))\r\n * Add error code for mutable covariant override (Ivan Levkivskyi, PR [16399](https://github.com/python/mypy/pull/16399))\r\n\r\n### Stubgen Improvements\r\n * Preserve simple defaults in function signatures (Ali Hamdan, PR [15355](https://github.com/python/mypy/pull/15355))\r\n * Include `__all__` in output (Jelle Zijlstra, PR [16356](https://github.com/python/mypy/pull/16356))\r\n * Fix stubgen regressions with pybind11 and mypy 1.7 (Chad Dombrova, PR [16504](https://github.com/python/mypy/pull/16504))\r\n\r\n### Stubtest Improvements\r\n * Improve handling of unrepresentable defaults (Jelle Zijlstra, PR [16433](https://github.com/python/mypy/pull/16433))\r\n * Print more helpful errors if a function is missing from stub (Alex Waygood, PR [16517](https://github.com/python/mypy/pull/16517))\r\n * Support `@type_check_only` decorator (Nikita Sobolev, PR [16422](https://github.com/python/mypy/pull/16422))\r\n * Warn about missing `__del__` (Shantanu, PR [16456](https://github.com/python/mypy/pull/16456))\r\n * Fix crashes with some uses of `final` and `deprecated` (Shantanu, PR [16457](https://github.com/python/mypy/pull/16457))\r\n\r\n### Fixes to Crashes\r\n * Fix crash with type alias to `Callable[[Unpack[Tuple[Any, ...]]], Any]` (Alex Waygood, PR [16541](https://github.com/python/mypy/pull/16541))\r\n * Fix crash on TypeGuard in `__call__` (Ivan Levkivskyi, PR [16516](https://github.com/python/mypy/pull/16516))\r\n * Fix crash on invalid enum in method (Ivan Levkivskyi, PR [16511](https://github.com/python/mypy/pull/16511))\r\n * Fix crash on unimported Any in TypedDict (Ivan Levkivskyi, PR [16510](https://github.com/python/mypy/pull/16510))\r\n\r\n### Documentation Updates\r\n * Update soft-error-limit default value to -1 (Sveinung Gundersen, PR [16542](https://github.com/python/mypy/pull/16542))\r\n * Support Sphinx 7.x (Michael R. Crusoe, PR [16460](https://github.com/python/mypy/pull/16460))\r\n\r\n### Other Notable Changes and Fixes\r\n * Allow mypy to output a junit file with per-file results (Matthew Wright, PR [16388](https://github.com/python/mypy/pull/16388))\r\n\r\n### Typeshed Updates\r\n\r\nPlease see [git log](https://github.com/python/typeshed/commits/main?after=4a854366e03dee700109f8e758a08b2457ea2f51+0&branch=main&path=stdlib) for full list of standard library typeshed stub changes.\r\n\r\n### Acknowledgements\r\n\r\n​Thanks to all mypy contributors who contributed to this release:\r\n\r\n- Alex Waygood\r\n- Ali Hamdan\r\n- Chad Dombrova\r\n- Christoph Tyralla\r\n- Ilya Priven\r\n- Ivan Levkivskyi\r\n- Jelle Zijlstra\r\n- Jukka Lehtosalo\r\n- Marcel Telka\r\n- Matthew Wright\r\n- Michael R. Crusoe\r\n- Nikita Sobolev\r\n- Ole Peder Brandtzæg\r\n- robjhornby\r\n- Shantanu\r\n- Sveinung Gundersen\r\n- Valentin Stanciu\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\nPosted by Wesley Collin Wright\r\n\r\n## Mypy 1.7\r\n\r\nWe’ve just uploaded mypy 1.7 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Using TypedDict for `**kwargs` Typing\r\n\r\nMypy now has support for using `Unpack[...]` with a TypedDict type to annotate `**kwargs` arguments enabled by default. Example:\r\n\r\n```python\r\n# Or 'from typing_extensions import ...'\r\nfrom typing import TypedDict, Unpack\r\n\r\nclass Person(TypedDict):\r\n    name: str\r\n    age: int\r\n\r\ndef foo(**kwargs: Unpack[Person]) -> None:\r\n    ...\r\n\r\nfoo(name=\"x\", age=1)  # Ok\r\nfoo(name=1)  # Error\r\n```\r\n\r\nThe definition of `foo` above is equivalent to the one below, with keyword-only arguments `name` and `age`:\r\n\r\n```python\r\ndef foo(*, name: str, age: int) -> None:\r\n    ...\r\n```\r\n\r\nRefer to [PEP 692](https://peps.python.org/pep-0692/) for more information. Note that unlike in the current version of the PEP, mypy always treats signatures with `Unpack[SomeTypedDict]` as equivalent to their expanded forms with explicit keyword arguments, and there aren't special type checking rules for TypedDict arguments.\r\n\r\nThis was contributed by Ivan Levkivskyi back in 2022 (PR [13471](https://github.com/python/mypy/pull/13471)).\r\n\r\n### TypeVarTuple Support Enabled (Experimental)\r\n\r\nMypy now has support for variadic generics (TypeVarTuple) enabled by default, as an experimental feature. Refer to [PEP 646](https://peps.python.org/pep-0646/) for the details.\r\n\r\nTypeVarTuple was implemented by Jared Hance and Ivan Levkivskyi over several mypy releases, with help from Jukka Lehtosalo.\r\n\r\nChanges included in this release:\r\n\r\n * Fix handling of tuple type context with unpacks (Ivan Levkivskyi, PR [16444](https://github.com/python/mypy/pull/16444))\r\n * Handle TypeVarTuples when checking overload constraints (robjhornby, PR [16428](https://github.com/python/mypy/pull/16428))\r\n * Enable Unpack/TypeVarTuple support (Ivan Levkivskyi, PR [16354](https://github.com/python/mypy/pull/16354))\r\n * Fix crash on unpack call special-casing (Ivan Levkivskyi, PR [16381](https://github.com/python/mypy/pull/16381))\r\n * Some final touches for variadic types support (Ivan Levkivskyi, PR [16334](https://github.com/python/mypy/pull/16334))\r\n * Support PEP-646 and PEP-692 in the same callable (Ivan Levkivskyi, PR [16294](https://github.com/python/mypy/pull/16294))\r\n * Support new `*` syntax for variadic types (Ivan Levkivskyi, PR [16242](https://github.com/python/mypy/pull/16242))\r\n * Correctly handle variadic instances with empty arguments (Ivan Levkivskyi, PR [16238](https://github.com/python/mypy/pull/16238))\r\n * Correctly handle runtime type applications of variadic types (Ivan Levkivskyi, PR [16240](https://github.com/python/mypy/pull/16240))\r\n * Support variadic tuple packing/unpacking (Ivan Levkivskyi, PR [16205](https://github.com/python/mypy/pull/16205))\r\n * Better support for variadic calls and indexing (Ivan Levkivskyi, PR [16131](https://github.com/python/mypy/pull/16131))\r\n * Subtyping and inference of user-defined variadic types (Ivan Levkivskyi, PR [16076](https://github.com/python/mypy/pull/16076))\r\n * Complete type analysis of variadic types (Ivan Levkivskyi, PR [15991](https://github.com/python/mypy/pull/15991))\r\n\r\n### New Way of Installing Mypyc Dependencies\r\n\r\nIf you want to install package dependencies needed by mypyc (not just mypy), you should now install `mypy[mypyc]` instead of just `mypy`:\r\n\r\n```\r\npython3 -m pip install -U 'mypy[mypyc]'\r\n```\r\n\r\nMypy has many more users than mypyc, so always installing mypyc dependencies would often bring unnecessary dependencies.\r\n\r\nThis change was contributed by Shantanu (PR [16229](https://github.com/python/mypy/pull/16229)).\r\n\r\n### New Rules for Re-exports\r\n\r\nMypy no longer considers an import such as `import a.b as b` as an explicit re-export. The old behavior was arguably inconsistent and surprising. This may impact some stub packages, such as older versions of `types-six`. You can change the import to `from a import b as b`, if treating the import as a re-export was intentional.\r\n\r\nThis change was contributed by Anders Kaseorg (PR [14086](https://github.com/python/mypy/pull/14086)).\r\n\r\n### Improved Type Inference\r\n\r\nThe new type inference algorithm that was recently introduced to mypy (but was not enabled by default) is now enabled by default. It improves type inference of calls to generic callables where an argument is also a generic callable, in particular. You can use `--old-type-inference` to disable the new behavior.\r\n\r\nThe new algorithm can (rarely) produce different error messages, different error codes, or errors reported on different lines. This is more likely in cases where generic types were used incorrectly.\r\n\r\nThe new type inference algorithm was contributed by Ivan Levkivskyi. PR [16345](https://github.com/python/mypy/pull/16345) enabled it by default.\r\n\r\n### Narrowing Tuple Types Using len()\r\n\r\nMypy now can narrow tuple types using `len()` checks. Example:\r\n\r\n```python\r\ndef f(t: tuple[int, int] | tuple[int, int, int]) -> None:\r\n    if len(t) == 2:\r\n        a, b = t   # Ok\r\n    ...\r\n```\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [16237](https://github.com/python/mypy/pull/16237)).\r\n\r\n### More Precise Tuple Lengths (Experimental)\r\n\r\nMypy supports experimental, more precise checking of tuple type lengths through `--enable-incomplete-feature=PreciseTupleTypes`. Refer to the [documentation](https://mypy.readthedocs.io/en/latest/command_line.html#enabling-incomplete-experimental-features) for more information.\r\n\r\nMore generally, we are planning to use `--enable-incomplete-feature` to introduce experimental features that would benefit from community feedback.\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [16237](https://github.com/python/mypy/pull/16237)).\r\n\r\n### Mypy Changelog\r\n\r\nWe now maintain a [changelog](https://github.com/python/mypy/blob/master/CHANGELOG.md) in the mypy Git repository. It mirrors the contents of [mypy release blog posts](https://mypy-lang.blogspot.com/). We will continue to also publish release blog posts. In the future, release blog posts will be created based on the changelog near a release date.\r\n\r\nThis was contributed by Shantanu (PR [16280](https://github.com/python/mypy/pull/16280)).\r\n\r\n### Mypy Daemon Improvements\r\n\r\n * Fix daemon crash caused by deleted submodule (Jukka Lehtosalo, PR [16370](https://github.com/python/mypy/pull/16370))\r\n * Fix file reloading in dmypy with --export-types (Ivan Levkivskyi, PR [16359](https://github.com/python/mypy/pull/16359))\r\n * Fix dmypy inspect on Windows (Ivan Levkivskyi, PR [16355](https://github.com/python/mypy/pull/16355))\r\n * Fix dmypy inspect for namespace packages (Ivan Levkivskyi, PR [16357](https://github.com/python/mypy/pull/16357))\r\n * Fix return type change to optional in generic function (Jukka Lehtosalo, PR [16342](https://github.com/python/mypy/pull/16342))\r\n * Fix daemon false positives related to module-level `__getattr__` (Jukka Lehtosalo, PR [16292](https://github.com/python/mypy/pull/16292))\r\n * Fix daemon crash related to ABCs (Jukka Lehtosalo, PR [16275](https://github.com/python/mypy/pull/16275))\r\n * Stream dmypy output instead of dumping everything at the end (Valentin Stanciu, PR [16252](https://github.com/python/mypy/pull/16252))\r\n * Make sure all dmypy errors are shown (Valentin Stanciu, PR [16250](https://github.com/python/mypy/pull/16250))\r\n\r\n### Mypyc Improvements\r\n\r\n * Generate error on duplicate function definitions (Jukka Lehtosalo, PR [16309](https://github.com/python/mypy/pull/16309))\r\n * Don't crash on unreachable statements (Jukka Lehtosalo, PR [16311](https://github.com/python/mypy/pull/16311))\r\n * Avoid cyclic reference in nested functions (Jukka Lehtosalo, PR [16268](https://github.com/python/mypy/pull/16268))\r\n * Fix direct `__dict__` access on inner functions in new Python (Shantanu, PR [16084](https://github.com/python/mypy/pull/16084))\r\n * Make tuple packing and unpacking more efficient (Jukka Lehtosalo, PR [16022](https://github.com/python/mypy/pull/16022))\r\n\r\n### Improvements to Error Reporting\r\n\r\n * Update starred expression error message to match CPython (Cibin Mathew, PR [16304](https://github.com/python/mypy/pull/16304))\r\n * Fix error code of \"Maybe you forgot to use await\" note (Jelle Zijlstra, PR [16203](https://github.com/python/mypy/pull/16203))\r\n * Use error code `[unsafe-overload]` for unsafe overloads, instead of `[misc]` (Randolf Scholz, PR [16061](https://github.com/python/mypy/pull/16061))\r\n * Reword the error message related to void functions (Albert Tugushev, PR [15876](https://github.com/python/mypy/pull/15876))\r\n * Represent bottom type as Never in messages (Shantanu, PR [15996](https://github.com/python/mypy/pull/15996))\r\n * Add hint for AsyncIterator incompatible return type (Ilya Priven, PR [15883](https://github.com/python/mypy/pull/15883))\r\n * Don't suggest stubs packages where the runtime package now ships with types (Alex Waygood, PR [16226](https://github.com/python/mypy/pull/16226))\r\n\r\n### Performance Improvements\r\n\r\n * Speed up type argument checking (Jukka Lehtosalo, PR [16353](https://github.com/python/mypy/pull/16353))\r\n * Add fast path for checking self types (Jukka Lehtosalo, PR [16352](https://github.com/python/mypy/pull/16352))\r\n * Cache information about whether file is typeshed file (Jukka Lehtosalo, PR [16351](https://github.com/python/mypy/pull/16351))\r\n * Skip expensive `repr()` in logging call when not needed (Jukka Lehtosalo, PR [16350](https://github.com/python/mypy/pull/16350))\r\n\r\n### Attrs and Dataclass Improvements\r\n\r\n * `dataclass.replace`: Allow transformed classes (Ilya Priven, PR [15915](https://github.com/python/mypy/pull/15915))\r\n * `dataclass.replace`: Fall through to typeshed signature (Ilya Priven, PR [15962](https://github.com/python/mypy/pull/15962))\r\n * Document `dataclass_transform` behavior (Ilya Priven, PR [16017](https://github.com/python/mypy/pull/16017))\r\n * `attrs`: Remove fields type check (Ilya Priven, PR [15983](https://github.com/python/mypy/pull/15983))\r\n * `attrs`, `dataclasses`: Don't enforce slots when base class doesn't (Ilya Priven, PR [15976](https://github.com/python/mypy/pull/15976))\r\n * Fix crash on dataclass field / property collision (Nikita Sobolev, PR [16147](https://github.com/python/mypy/pull/16147))\r\n\r\n### Stubgen Improvements\r\n\r\n * Write stubs with utf-8 encoding (Jørgen Lind, PR [16329](https://github.com/python/mypy/pull/16329))\r\n * Fix missing property setter in semantic analysis mode (Ali Hamdan, PR [16303](https://github.com/python/mypy/pull/16303))\r\n * Unify C extension and pure python stub generators with object oriented design (Chad Dombrova, PR [15770](https://github.com/python/mypy/pull/15770))\r\n * Multiple fixes to the generated imports (Ali Hamdan, PR [15624](https://github.com/python/mypy/pull/15624))\r\n * Generate valid dataclass stubs (Ali Hamdan, PR [15625](https://github.com/python/mypy/pull/15625))\r\n\r\n### Fixes to Crashes\r\n\r\n * Fix incremental mode crash on TypedDict in method (Ivan Levkivskyi, PR [16364](https://github.com/python/mypy/pull/16364))\r\n * Fix crash on star unpack in TypedDict (Ivan Levkivskyi, PR [16116](https://github.com/python/mypy/pull/16116))\r\n * Fix crash on malformed TypedDict in incremental mode (Ivan Levkivskyi, PR [16115](https://github.com/python/mypy/pull/16115))\r\n * Fix crash with report generation on namespace packages (Shantanu, PR [16019](https://github.com/python/mypy/pull/16019))\r\n * Fix crash when parsing error code config with typo (Shantanu, PR [16005](https://github.com/python/mypy/pull/16005))\r\n * Fix `__post_init__()` internal error (Ilya Priven, PR [16080](https://github.com/python/mypy/pull/16080))\r\n\r\n### Documentation Updates\r\n\r\n * Make it easier to copy commands from README (Hamir Mahal, PR [16133](https://github.com/python/mypy/pull/16133))\r\n * Document and rename `[overload-overlap]` error code (Shantanu, PR [16074](https://github.com/python/mypy/pull/16074))\r\n * Document `--force-uppercase-builtins` and `--force-union-syntax` (Nikita Sobolev, PR [16049](https://github.com/python/mypy/pull/16049))\r\n * Document `force_union_syntax` and `force_uppercase_builtins` (Nikita Sobolev, PR [16048](https://github.com/python/mypy/pull/16048))\r\n * Document we're not tracking relationships between symbols (Ilya Priven, PR [16018](https://github.com/python/mypy/pull/16018))\r\n\r\n### Other Notable Changes and Fixes\r\n\r\n * Propagate narrowed types to lambda expressions (Ivan Levkivskyi, PR [16407](https://github.com/python/mypy/pull/16407))\r\n * Avoid importing from `setuptools._distutils` (Shantanu, PR [16348](https://github.com/python/mypy/pull/16348))\r\n * Delete recursive aliases flags (Ivan Levkivskyi, PR [16346](https://github.com/python/mypy/pull/16346))\r\n * Properly use proper subtyping for callables (Ivan Levkivskyi, PR [16343](https://github.com/python/mypy/pull/16343))\r\n * Use upper bound as inference fallback more consistently (Ivan Levkivskyi, PR [16344](https://github.com/python/mypy/pull/16344))\r\n * Add `[unimported-reveal]` error code (Nikita Sobolev, PR [16271](https://github.com/python/mypy/pull/16271))\r\n * Add `|=` and `|` operators support for `TypedDict` (Nikita Sobolev, PR [16249](https://github.com/python/mypy/pull/16249))\r\n * Clarify variance convention for Parameters (Ivan Levkivskyi, PR [16302](https://github.com/python/mypy/pull/16302))\r\n * Correctly recognize `typing_extensions.NewType` (Ganden Schaffner, PR [16298](https://github.com/python/mypy/pull/16298))\r\n * Fix partially defined in the case of missing type maps (Shantanu, PR [15995](https://github.com/python/mypy/pull/15995))\r\n * Use SPDX license identifier (Nikita Sobolev, PR [16230](https://github.com/python/mypy/pull/16230))\r\n * Make `__qualname__` and `__module__` available in class bodies (Anthony Sottile, PR [16215](https://github.com/python/mypy/pull/16215))\r\n * stubtest: Hint when args in stub need to be keyword-only (Alex Waygood, PR [16210](https://github.com/python/mypy/pull/16210))\r\n * Tuple slice should not propagate fallback (Thomas Grainger, PR [16154](https://github.com/python/mypy/pull/16154))\r\n * Fix cases of type object handling for overloads (Shantanu, PR [16168](https://github.com/python/mypy/pull/16168))\r\n * Fix walrus interaction with empty collections (Ivan Levkivskyi, PR [16197](https://github.com/python/mypy/pull/16197))\r\n * Use type variable bound when it appears as actual during inference (Ivan Levkivskyi, PR [16178](https://github.com/python/mypy/pull/16178))\r\n * Use upper bounds as fallback solutions for inference (Ivan Levkivskyi, PR [16184](https://github.com/python/mypy/pull/16184))\r\n * Special-case type inference of empty collections (Ivan Levkivskyi, PR [16122](https://github.com/python/mypy/pull/16122))\r\n * Allow TypedDict unpacking in Callable types (Ivan Levkivskyi, PR [16083](https://github.com/python/mypy/pull/16083))\r\n * Fix inference for overloaded `__call__` with generic self (Shantanu, PR [16053](https://github.com/python/mypy/pull/16053))\r\n * Call dynamic class hook on generic classes (Petter Friberg, PR [16052](https://github.com/python/mypy/pull/16052))\r\n * Preserve implicitly exported types via attribute access (Shantanu, PR [16129](https://github.com/python/mypy/pull/16129))\r\n * Fix a stubtest bug (Alex Waygood)\r\n * Fix `tuple[Any, ...]` subtyping (Shantanu, PR [16108](https://github.com/python/mypy/pull/16108))\r\n * Lenient handling of trivial Callable suffixes (Ivan Levkivskyi, PR [15913](https://github.com/python/mypy/pull/15913))\r\n * Add `add_overloaded_method_to_class` helper for plugins (Nikita Sobolev, PR [16038](https://github.com/python/mypy/pull/16038))\r\n * Bundle `misc/proper_plugin.py` as a part of `mypy` (Nikita Sobolev, PR [16036](https://github.com/python/mypy/pull/16036))\r\n * Fix `case Any()` in match statement (DS/Charlie, PR [14479](https://github.com/python/mypy/pull/14479))\r\n * Make iterable logic more consistent (Shantanu, PR [16006](https://github.com/python/mypy/pull/16006))\r\n * Fix inference for properties with `__call__` (Shantanu, PR [15926](https://github.com/python/mypy/pull/15926))\r\n\r\n### Typeshed Updates\r\n\r\nPlease see [git log](https://github.com/python/typeshed/commits/main?after=4a854366e03dee700109f8e758a08b2457ea2f51+0&branch=main&path=stdlib) for full list of standard library typeshed stub changes.\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n* Albert Tugushev\r\n* Alex Waygood\r\n* Ali Hamdan\r\n* Anders Kaseorg\r\n* Anthony Sottile\r\n* Chad Dombrova\r\n* Cibin Mathew\r\n* dinaldoap\r\n* DS/Charlie\r\n* Eli Schwartz\r\n* Ganden Schaffner\r\n* Hamir Mahal\r\n* Ihor\r\n* Ikko Eltociear Ashimine\r\n* Ilya Priven\r\n* Ivan Levkivskyi\r\n* Jelle Zijlstra\r\n* Jukka Lehtosalo\r\n* Jørgen Lind\r\n* KotlinIsland\r\n* Matt Bogosian\r\n* Nikita Sobolev\r\n* Petter Friberg\r\n* Randolf Scholz\r\n* Shantanu\r\n* Thomas Grainger\r\n* Valentin Stanciu\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\nPosted by Jukka Lehtosalo\r\n\r\n## Mypy 1.6\r\n\r\n[Tuesday, 10 October 2023](https://mypy-lang.blogspot.com/2023/10/mypy-16-released.html)\r\n\r\nWe’ve just uploaded mypy 1.6 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Introduce Error Subcodes for Import Errors\r\n\r\nMypy now uses the error code import-untyped if an import targets an installed library that doesn’t support static type checking, and no stub files are available. Other invalid imports produce the import-not-found error code. They both are subcodes of the import error code, which was previously used for both kinds of import-related errors.\r\n\r\nUse \\--disable-error-code=import-untyped to only ignore import errors about installed libraries without stubs. This way mypy will still report errors about typos in import statements, for example.\r\n\r\nIf you use \\--warn-unused-ignore or \\--strict, mypy will complain if you use \\# type: ignore\\[import\\] to ignore an import error. You are expected to use one of the more specific error codes instead. Otherwise, ignoring the import error code continues to silence both errors.\r\n\r\nThis feature was contributed by Shantanu (PR [15840](https://github.com/python/mypy/pull/15840), PR [14740](https://github.com/python/mypy/pull/14740)).\r\n\r\n### Remove Support for Targeting Python 3.6 and Earlier\r\n\r\nRunning mypy with \\--python-version 3.6, for example, is no longer supported. Python 3.6 hasn’t been properly supported by mypy for some time now, and this makes it explicit. This was contributed by Nikita Sobolev (PR [15668](https://github.com/python/mypy/pull/15668)).\r\n\r\n### Selective Filtering of \\--disallow-untyped-calls Targets\r\n\r\nUsing \\--disallow-untyped-calls could be annoying when using libraries with missing type information, as mypy would generate many errors about code that uses the library. Now you can use \\--untyped-calls-exclude=acme, for example, to disable these errors about calls targeting functions defined in the acme package. Refer to the [documentation](https://mypy.readthedocs.io/en/latest/command_line.html#cmdoption-mypy-untyped-calls-exclude) for more information.\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [15845](https://github.com/python/mypy/pull/15845)).\r\n\r\n### Improved Type Inference between Callable Types\r\n\r\nMypy now does a better job inferring type variables inside arguments of callable types. For example, this code fragment now type checks correctly:\r\n\r\n```python\r\ndef f(c: Callable[[T, S], None]) -> Callable[[str, T, S], None]: ...\r\ndef g(*x: int) -> None: ...\r\n\r\nreveal_type(f(g))  # Callable[[str, int, int], None]\r\n```\r\n\r\nThis was contributed by Ivan Levkivskyi (PR [15910](https://github.com/python/mypy/pull/15910)).\r\n\r\n### Don’t Consider None and TypeVar to Overlap in Overloads\r\n\r\nMypy now doesn’t consider an overload item with an argument type None to overlap with a type variable:\r\n\r\n```python\r\n@overload\r\ndef f(x: None) -> None: ..\r\n@overload\r\ndef f(x: T) -> Foo[T]: ...\r\n...\r\n```\r\n\r\nPreviously mypy would generate an error about the definition of f above. This is slightly unsafe if the upper bound of T is object, since the value of the type variable could be None. We relaxed the rules a little, since this solves a common issue.\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [15846](https://github.com/python/mypy/pull/15846)).\r\n\r\n### Improvements to \\--new-type-inference\r\n\r\nThe experimental new type inference algorithm (polymorphic inference) introduced as an opt-in feature in mypy 1.5 has several improvements:\r\n\r\n*   Improve transitive closure computation during constraint solving (Ivan Levkivskyi, PR [15754](https://github.com/python/mypy/pull/15754))\r\n*   Add support for upper bounds and values with \\--new-type-inference (Ivan Levkivskyi, PR [15813](https://github.com/python/mypy/pull/15813))\r\n*   Basic support for variadic types with \\--new-type-inference (Ivan Levkivskyi, PR [15879](https://github.com/python/mypy/pull/15879))\r\n*   Polymorphic inference: support for parameter specifications and lambdas (Ivan Levkivskyi, PR [15837](https://github.com/python/mypy/pull/15837))\r\n*   Invalidate cache when adding \\--new-type-inference (Marc Mueller, PR [16059](https://github.com/python/mypy/pull/16059))\r\n\r\n**Note:** We are planning to enable \\--new-type-inference by default in mypy 1.7. Please try this out and let us know if you encounter any issues.\r\n\r\n### ParamSpec Improvements\r\n\r\n*   Support self-types containing ParamSpec (Ivan Levkivskyi, PR [15903](https://github.com/python/mypy/pull/15903))\r\n*   Allow “…” in Concatenate, and clean up ParamSpec literals (Ivan Levkivskyi, PR [15905](https://github.com/python/mypy/pull/15905))\r\n*   Fix ParamSpec inference for callback protocols (Ivan Levkivskyi, PR [15986](https://github.com/python/mypy/pull/15986))\r\n*   Infer ParamSpec constraint from arguments (Ivan Levkivskyi, PR [15896](https://github.com/python/mypy/pull/15896))\r\n*   Fix crash on invalid type variable with ParamSpec (Ivan Levkivskyi, PR [15953](https://github.com/python/mypy/pull/15953))\r\n*   Fix subtyping between ParamSpecs (Ivan Levkivskyi, PR [15892](https://github.com/python/mypy/pull/15892))\r\n\r\n### Stubgen Improvements\r\n\r\n*   Add option to include docstrings with stubgen (chylek, PR [13284](https://github.com/python/mypy/pull/13284))\r\n*   Add required ... initializer to NamedTuple fields with default values (Nikita Sobolev, PR [15680](https://github.com/python/mypy/pull/15680))\r\n\r\n### Stubtest Improvements\r\n\r\n*   Fix \\_\\_mypy-replace false positives (Alex Waygood, PR [15689](https://github.com/python/mypy/pull/15689))\r\n*   Fix edge case for bytes enum subclasses (Alex Waygood, PR [15943](https://github.com/python/mypy/pull/15943))\r\n*   Generate error if typeshed is missing modules from the stdlib (Alex Waygood, PR [15729](https://github.com/python/mypy/pull/15729))\r\n*   Fixes to new check for missing stdlib modules (Alex Waygood, PR [15960](https://github.com/python/mypy/pull/15960))\r\n*   Fix stubtest enum.Flag edge case (Alex Waygood, PR [15933](https://github.com/python/mypy/pull/15933))\r\n\r\n### Documentation Improvements\r\n\r\n*   Do not advertise to create your own assert\\_never helper (Nikita Sobolev, PR [15947](https://github.com/python/mypy/pull/15947))\r\n*   Fix all the missing references found within the docs (Albert Tugushev, PR [15875](https://github.com/python/mypy/pull/15875))\r\n*   Document await-not-async error code (Shantanu, PR [15858](https://github.com/python/mypy/pull/15858))\r\n*   Improve documentation of disabling error codes (Shantanu, PR [15841](https://github.com/python/mypy/pull/15841))\r\n\r\n### Other Notable Changes and Fixes\r\n\r\n*   Make unsupported PEP 695 features (introduced in Python 3.12) give a reasonable error message (Shantanu, PR [16013](https://github.com/python/mypy/pull/16013))\r\n*   Remove the \\--py2 command-line argument (Marc Mueller, PR [15670](https://github.com/python/mypy/pull/15670))\r\n*   Change empty tuple from tuple\\[\\] to tuple\\[()\\] in error messages (Nikita Sobolev, PR [15783](https://github.com/python/mypy/pull/15783))\r\n*   Fix assert\\_type failures when some nodes are deferred (Nikita Sobolev, PR [15920](https://github.com/python/mypy/pull/15920))\r\n*   Generate error on unbound TypeVar with values (Nikita Sobolev, PR [15732](https://github.com/python/mypy/pull/15732))\r\n*   Fix over-eager types-google-cloud-ndb suggestion (Shantanu, PR [15347](https://github.com/python/mypy/pull/15347))\r\n*   Fix type narrowing of \\== None and in (None,) conditions (Marti Raudsepp, PR [15760](https://github.com/python/mypy/pull/15760))\r\n*   Fix inference for attrs.fields (Shantanu, PR [15688](https://github.com/python/mypy/pull/15688))\r\n*   Make “await in non-async function” a non-blocking error and give it an error code (Gregory Santosa, PR [15384](https://github.com/python/mypy/pull/15384))\r\n*   Add basic support for decorated overloads (Ivan Levkivskyi, PR [15898](https://github.com/python/mypy/pull/15898))\r\n*   Fix TypeVar regression with self types (Ivan Levkivskyi, PR [15945](https://github.com/python/mypy/pull/15945))\r\n*   Add \\_\\_match\\_args\\_\\_ to dataclasses with no fields (Ali Hamdan, PR [15749](https://github.com/python/mypy/pull/15749))\r\n*   Include stdout and stderr in dmypy verbose output (Valentin Stanciu, PR [15881](https://github.com/python/mypy/pull/15881))\r\n*   Improve match narrowing and reachability analysis (Shantanu, PR [15882](https://github.com/python/mypy/pull/15882))\r\n*   Support \\_\\_bool\\_\\_ with Literal in \\--warn-unreachable (Jannic Warken, PR [15645](https://github.com/python/mypy/pull/15645))\r\n*   Fix inheriting from generic @frozen attrs class (Ilya Priven, PR [15700](https://github.com/python/mypy/pull/15700))\r\n*   Correctly narrow types for tuple\\[type\\[X\\], ...\\] (Nikita Sobolev, PR [15691](https://github.com/python/mypy/pull/15691))\r\n*   Don't flag intentionally empty generators unreachable (Ilya Priven, PR [15722](https://github.com/python/mypy/pull/15722))\r\n*   Add tox.ini to mypy sdist (Marcel Telka, PR [15853](https://github.com/python/mypy/pull/15853))\r\n*   Fix mypyc regression with pretty (Shantanu, PR [16124](https://github.com/python/mypy/pull/16124))\r\n\r\n### Typeshed Updates\r\n\r\nTypeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please see [git log](https://github.com/python/typeshed/commits/main?after=6a8d653a671925b0a3af61729ff8cf3f90c9c662+0&branch=main&path=stdlib) for full list of typeshed changes.\r\n\r\n### Acknowledgements\r\n\r\nThanks to Max Murin, who did most of the release manager work for this release (I just did the final steps).\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n*   Albert Tugushev\r\n*   Alex Waygood\r\n*   Ali Hamdan\r\n*   chylek\r\n*   EXPLOSION\r\n*   Gregory Santosa\r\n*   Ilya Priven\r\n*   Ivan Levkivskyi\r\n*   Jannic Warken\r\n*   KotlinIsland\r\n*   Marc Mueller\r\n*   Marcel Johannesmann\r\n*   Marcel Telka\r\n*   Mark Byrne\r\n*   Marti Raudsepp\r\n*   Max Murin\r\n*   Nikita Sobolev\r\n*   Shantanu\r\n*   Valentin Stanciu\r\n\r\nPosted by Jukka Lehtosalo\r\n\r\n\r\n## Mypy 1.5\r\n\r\n[Thursday, 10 August 2023](https://mypy-lang.blogspot.com/2023/08/mypy-15-released.html)\r\n\r\nWe’ve just uploaded mypy 1.5 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, deprecations and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Drop Support for Python 3.7\r\n\r\nMypy no longer supports running with Python 3.7, which has reached end-of-life. This was contributed by Shantanu (PR [15566](https://github.com/python/mypy/pull/15566)).\r\n\r\n### Optional Check to Require Explicit @override\r\n\r\nIf you enable the explicit-override error code, mypy will generate an error if a method override doesn’t use the @typing.override decorator (as discussed in [PEP 698](https://peps.python.org/pep-0698/#strict-enforcement-per-project)). This way mypy will detect accidentally introduced overrides. Example:\r\n\r\n```python\r\n# mypy: enable-error-code=\"explicit-override\"\r\n\r\nfrom typing_extensions import override\r\n\r\nclass C:\r\n    def foo(self) -> None: pass\r\n    def bar(self) -> None: pass\r\n\r\nclass D(C):\r\n    # Error: Method \"foo\" is not using @override but is\r\n    # overriding a method\r\n    def foo(self) -> None:\r\n        ...\r\n\r\n    @override\r\n    def bar(self) -> None:  # OK\r\n        ...\r\n```\r\n\r\nYou can enable the error code via \\--enable-error-code=explicit-override on the mypy command line or enable\\_error\\_code = explicit-override in the mypy config file.\r\n\r\nThe override decorator will be available in typing in Python 3.12, but you can also use the backport from a recent version of `typing_extensions` on all supported Python versions.\r\n\r\nThis feature was contributed by Marc Mueller(PR [15512](https://github.com/python/mypy/pull/15512)).\r\n\r\n### More Flexible TypedDict Creation and Update\r\n\r\nMypy was previously overly strict when type checking TypedDict creation and update operations. Though these checks were often technically correct, they sometimes triggered for apparently valid code. These checks have now been relaxed by default. You can enable stricter checking by using the new \\--extra-checks flag.\r\n\r\nConstruction using the `**` syntax is now more flexible:\r\n\r\n```python\r\nfrom typing import TypedDict\r\n\r\nclass A(TypedDict):\r\n    foo: int\r\n    bar: int\r\n\r\nclass B(TypedDict):\r\n    foo: int\r\n\r\na: A = {\"foo\": 1, \"bar\": 2}\r\nb: B = {\"foo\": 3}\r\na2: A = { **a, **b}  # OK (previously an error)\r\n```\r\n\r\nYou can also call update() with a TypedDict argument that contains a subset of the keys in the updated TypedDict:\r\n```python\r\na.update(b)  # OK (previously an error)\r\n```\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [15425](https://github.com/python/mypy/pull/15425)).\r\n\r\n### Deprecated Flag: \\--strict-concatenate\r\n\r\nThe behavior of \\--strict-concatenate is now included in the new \\--extra-checks flag, and the old flag is deprecated.\r\n\r\n### Optionally Show Links to Error Code Documentation\r\n\r\nIf you use \\--show-error-code-links, mypy will add documentation links to (many) reported errors. The links are not shown for error messages that are sufficiently obvious, and they are shown once per error code only.\r\n\r\nExample output:\r\n```\r\na.py:1: error: Need type annotation for \"foo\" (hint: \"x: List[<type>] = ...\")  [var-annotated]\r\na.py:1: note: See https://mypy.rtfd.io/en/stable/_refs.html#code-var-annotated for more info\r\n```\r\nThis was contributed by Ivan Levkivskyi (PR [15449](https://github.com/python/mypy/pull/15449)).\r\n\r\n### Consistently Avoid Type Checking Unreachable Code\r\n\r\nIf a module top level has unreachable code, mypy won’t type check the unreachable statements. This is consistent with how functions behave. The behavior of \\--warn-unreachable is also more consistent now.\r\n\r\nThis was contributed by Ilya Priven (PR [15386](https://github.com/python/mypy/pull/15386)).\r\n\r\n### Experimental Improved Type Inference for Generic Functions\r\n\r\nYou can use \\--new-type-inference to opt into an experimental new type inference algorithm. It fixes issues when calling a generic functions with an argument that is also a generic function, in particular. This current implementation is still incomplete, but we encourage trying it out and reporting bugs if you encounter regressions. We are planning to enable the new algorithm by default in a future mypy release.\r\n\r\nThis feature was contributed by Ivan Levkivskyi (PR [15287](https://github.com/python/mypy/pull/15287)).\r\n\r\n### Partial Support for Python 3.12\r\n\r\nMypy and mypyc now support running on recent Python 3.12 development versions. Not all new Python 3.12 features are supported, and we don’t ship compiled wheels for Python 3.12 yet.\r\n\r\n*   Fix ast warnings for Python 3.12 (Nikita Sobolev, PR [15558](https://github.com/python/mypy/pull/15558))\r\n*   mypyc: Fix multiple inheritance with a protocol on Python 3.12 (Jukka Lehtosalo, PR [15572](https://github.com/python/mypy/pull/15572))\r\n*   mypyc: Fix self-compilation on Python 3.12 (Jukka Lehtosalo, PR [15582](https://github.com/python/mypy/pull/15582))\r\n*   mypyc: Fix 3.12 issue with pickling of instances with \\_\\_dict\\_\\_ (Jukka Lehtosalo, PR [15574](https://github.com/python/mypy/pull/15574))\r\n*   mypyc: Fix i16 on Python 3.12 (Jukka Lehtosalo, PR [15510](https://github.com/python/mypy/pull/15510))\r\n*   mypyc: Fix int operations on Python 3.12 (Jukka Lehtosalo, PR [15470](https://github.com/python/mypy/pull/15470))\r\n*   mypyc: Fix generators on Python 3.12 (Jukka Lehtosalo, PR [15472](https://github.com/python/mypy/pull/15472))\r\n*   mypyc: Fix classes with \\_\\_dict\\_\\_ on 3.12 (Jukka Lehtosalo, PR [15471](https://github.com/python/mypy/pull/15471))\r\n*   mypyc: Fix coroutines on Python 3.12 (Jukka Lehtosalo, PR [15469](https://github.com/python/mypy/pull/15469))\r\n*   mypyc: Don't use \\_PyErr\\_ChainExceptions on 3.12, since it's deprecated (Jukka Lehtosalo, PR [15468](https://github.com/python/mypy/pull/15468))\r\n*   mypyc: Add Python 3.12 feature macro (Jukka Lehtosalo, PR [15465](https://github.com/python/mypy/pull/15465))\r\n\r\n### Improvements to Dataclasses\r\n\r\n*   Improve signature of dataclasses.replace (Ilya Priven, PR [14849](https://github.com/python/mypy/pull/14849))\r\n*   Fix dataclass/protocol crash on joining types (Ilya Priven, PR [15629](https://github.com/python/mypy/pull/15629))\r\n*   Fix strict optional handling in dataclasses (Ivan Levkivskyi, PR [15571](https://github.com/python/mypy/pull/15571))\r\n*   Support optional types for custom dataclass descriptors (Marc Mueller, PR [15628](https://github.com/python/mypy/pull/15628))\r\n*   Add `__slots__` attribute to dataclasses (Nikita Sobolev, PR [15649](https://github.com/python/mypy/pull/15649))\r\n*   Support better \\_\\_post\\_init\\_\\_ method signature for dataclasses (Nikita Sobolev, PR [15503](https://github.com/python/mypy/pull/15503))\r\n\r\n### Mypyc Improvements\r\n\r\n*   Support unsigned 8-bit native integer type: mypy\\_extensions.u8 (Jukka Lehtosalo, PR [15564](https://github.com/python/mypy/pull/15564))\r\n*   Support signed 16-bit native integer type: mypy\\_extensions.i16 (Jukka Lehtosalo, PR [15464](https://github.com/python/mypy/pull/15464))\r\n*   Define mypy\\_extensions.i16 in stubs (Jukka Lehtosalo, PR [15562](https://github.com/python/mypy/pull/15562))\r\n*   Document more unsupported features and update supported features (Richard Si, PR [15524](https://github.com/python/mypy/pull/15524))\r\n*   Fix final NamedTuple classes (Richard Si, PR [15513](https://github.com/python/mypy/pull/15513))\r\n*   Use C99 compound literals for undefined tuple values (Jukka Lehtosalo, PR [15453](https://github.com/python/mypy/pull/15453))\r\n*   Don't explicitly assign NULL values in setup functions (Logan Hunt, PR [15379](https://github.com/python/mypy/pull/15379))\r\n\r\n### Stubgen Improvements\r\n\r\n*   Teach stubgen to work with complex and unary expressions (Nikita Sobolev, PR [15661](https://github.com/python/mypy/pull/15661))\r\n*   Support ParamSpec and TypeVarTuple (Ali Hamdan, PR [15626](https://github.com/python/mypy/pull/15626))\r\n*   Fix crash on non-str docstring (Ali Hamdan, PR [15623](https://github.com/python/mypy/pull/15623))\r\n\r\n### Documentation Updates\r\n\r\n*   Add documentation for additional error codes (Ivan Levkivskyi, PR [15539](https://github.com/python/mypy/pull/15539))\r\n*   Improve documentation of type narrowing (Ilya Priven, PR [15652](https://github.com/python/mypy/pull/15652))\r\n*   Small improvements to protocol documentation (Shantanu, PR [15460](https://github.com/python/mypy/pull/15460))\r\n*   Remove confusing instance variable example in cheat sheet (Adel Atallah, PR [15441](https://github.com/python/mypy/pull/15441))\r\n\r\n### Other Notable Fixes and Improvements\r\n\r\n*   Constant fold additional unary and binary expressions (Richard Si, PR [15202](https://github.com/python/mypy/pull/15202))\r\n*   Exclude the same special attributes from Protocol as CPython (Kyle Benesch, PR [15490](https://github.com/python/mypy/pull/15490))\r\n*   Change the default value of the slots argument of attrs.define to True, to match runtime behavior (Ilya Priven, PR [15642](https://github.com/python/mypy/pull/15642))\r\n*   Fix type of class attribute if attribute is defined in both class and metaclass (Alex Waygood, PR [14988](https://github.com/python/mypy/pull/14988))\r\n*   Handle type the same as typing.Type in the first argument of classmethods (Erik Kemperman, PR [15297](https://github.com/python/mypy/pull/15297))\r\n*   Fix \\--find-occurrences flag (Shantanu, PR [15528](https://github.com/python/mypy/pull/15528))\r\n*   Fix error location for class patterns (Nikita Sobolev, PR [15506](https://github.com/python/mypy/pull/15506))\r\n*   Fix re-added file with errors in mypy daemon (Ivan Levkivskyi, PR [15440](https://github.com/python/mypy/pull/15440))\r\n*   Fix dmypy run on Windows (Ivan Levkivskyi, PR [15429](https://github.com/python/mypy/pull/15429))\r\n*   Fix abstract and non-abstract variant error for property deleter (Shantanu, PR [15395](https://github.com/python/mypy/pull/15395))\r\n*   Remove special casing for \"cannot\" in error messages (Ilya Priven, PR [15428](https://github.com/python/mypy/pull/15428))\r\n*   Add runtime `__slots__` attribute to attrs classes (Nikita Sobolev, PR [15651](https://github.com/python/mypy/pull/15651))\r\n*   Add get\\_expression\\_type to CheckerPluginInterface (Ilya Priven, PR [15369](https://github.com/python/mypy/pull/15369))\r\n*   Remove parameters that no longer exist from NamedTuple.\\_make() (Alex Waygood, PR [15578](https://github.com/python/mypy/pull/15578))\r\n*   Allow using typing.Self in `__all__` with an explicit @staticmethod decorator (Erik Kemperman, PR [15353](https://github.com/python/mypy/pull/15353))\r\n*   Fix self types in subclass methods without Self annotation (Ivan Levkivskyi, PR [15541](https://github.com/python/mypy/pull/15541))\r\n*   Check for abstract class objects in tuples (Nikita Sobolev, PR [15366](https://github.com/python/mypy/pull/15366))\r\n\r\n### Typeshed Updates\r\n\r\nTypeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please see [git log](https://github.com/python/typeshed/commits/main?after=fc7d4722eaa54803926cee5730e1f784979c0531+0&branch=main&path=stdlib) for full list of typeshed changes.\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n*   Adel Atallah\r\n*   Alex Waygood\r\n*   Ali Hamdan\r\n*   Erik Kemperman\r\n*   Federico Padua\r\n*   Ilya Priven\r\n*   Ivan Levkivskyi\r\n*   Jelle Zijlstra\r\n*   Jared Hance\r\n*   Jukka Lehtosalo\r\n*   Kyle Benesch\r\n*   Logan Hunt\r\n*   Marc Mueller\r\n*   Nikita Sobolev\r\n*   Richard Si\r\n*   Shantanu\r\n*   Stavros Ntentos\r\n*   Valentin Stanciu\r\n\r\nPosted by Valentin Stanciu\r\n\r\n\r\n## Mypy 1.4\r\n\r\n[Tuesday, 20 June 2023](https://mypy-lang.blogspot.com/2023/06/mypy-140-released.html)\r\n\r\nWe’ve just uploaded mypy 1.4 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### The Override Decorator\r\n\r\nMypy can now ensure that when renaming a method, overrides are also renamed. You can explicitly mark a method as overriding a base class method by using the @typing.override decorator ([PEP 698](https://peps.python.org/pep-0698/)). If the method is then renamed in the base class while the method override is not, mypy will generate an error. The decorator will be available in typing in Python 3.12, but you can also use the backport from a recent version of `typing_extensions` on all supported Python versions.\r\n\r\nThis feature was contributed byThomas M Kehrenberg (PR [14609](https://github.com/python/mypy/pull/14609)).\r\n\r\n### Propagating Type Narrowing to Nested Functions\r\n\r\nPreviously, type narrowing was not propagated to nested functions because it would not be sound if the narrowed variable changed between the definition of the nested function and the call site. Mypy will now propagate the narrowed type if the variable is not assigned to after the definition of the nested function:\r\n\r\n```python\r\ndef outer(x: str | None = None) -> None:\r\n    if x is None:\r\n        x = calculate_default()\r\n    reveal_type(x)  # \"str\" (narrowed)\r\n\r\n    def nested() -> None:\r\n        reveal_type(x)  # Now \"str\" (used to be \"str | None\")\r\n\r\n    nested()\r\n```\r\n\r\nThis may generate some new errors because asserts that were previously necessary may become tautological or no-ops.\r\n\r\nThis was contributed by Jukka Lehtosalo (PR [15133](https://github.com/python/mypy/pull/15133)).\r\n\r\n### Narrowing Enum Values Using “==”\r\n\r\nMypy now allows narrowing enum types using the \\== operator. Previously this was only supported when using the is operator. This makes exhaustiveness checking with enum types more usable, as the requirement to use the is operator was not very intuitive. In this example mypy can detect that the developer forgot to handle the value MyEnum.C in example\r\n\r\n```python\r\nfrom enum import Enum\r\n\r\nclass MyEnum(Enum):\r\n    A = 0\r\n    B = 1\r\n    C = 2\r\n\r\ndef example(e: MyEnum) -> str:  # Error: Missing return statement\r\n    if e == MyEnum.A:\r\n        return 'x'\r\n    elif e == MyEnum.B:\r\n        return 'y'\r\n```\r\n\r\nAdding an extra elif case resolves the error:\r\n\r\n```python\r\n...\r\ndef example(e: MyEnum) -> str:  # No error -- all values covered\r\n    if e == MyEnum.A:\r\n        return 'x'\r\n    elif e == MyEnum.B:\r\n        return 'y'\r\n    elif e == MyEnum.C:\r\n        return 'z'\r\n```\r\n\r\nThis change can cause false positives in test cases that have assert statements like assert o.x == SomeEnum.X when using \\--strict-equality. Example:\r\n\r\n```python\r\n# mypy: strict-equality\r\n\r\nfrom enum import Enum\r\n\r\nclass MyEnum(Enum):\r\n    A = 0\r\n    B = 1\r\n\r\nclass C:\r\n    x: MyEnum\r\n    ...\r\n\r\ndef test_something() -> None:\r\n    c = C(...)\r\n    assert c.x == MyEnum.A\r\n    c.do_something_that_changes_x()\r\n    assert c.x == MyEnum.B  # Error: Non-overlapping equality check\r\n```\r\n\r\nThese errors can be ignored using \\# type: ignore\\[comparison-overlap\\], or you can perform the assertion using a temporary variable as a workaround:\r\n\r\n```python\r\n...\r\ndef test_something() -> None:\r\n    ...\r\n    x = c.x\r\n    assert x == MyEnum.A  # Does not narrow c.x\r\n    c.do_something_that_changes_x()\r\n    x = c.x\r\n    assert x == MyEnum.B  # OK\r\n```\r\n\r\nThis feature was contributed by Shantanu (PR [11521](https://github.com/python/mypy/pull/11521)).\r\n\r\n### Performance Improvements\r\n\r\n*   Speed up simplification of large union types and also fix a recursive tuple crash (Shantanu, PR [15128](https://github.com/python/mypy/pull/15128))\r\n*   Speed up union subtyping (Shantanu, PR [15104](https://github.com/python/mypy/pull/15104))\r\n*   Don't type check most function bodies when type checking third-party library code, or generally when ignoring errors (Jukka Lehtosalo, PR [14150](https://github.com/python/mypy/pull/14150))\r\n\r\n### Improvements to Plugins\r\n\r\n*   attrs.evolve: Support generics and unions (Ilya Konstantinov, PR [15050](https://github.com/python/mypy/pull/15050))\r\n*   Fix ctypes plugin (Alex Waygood)\r\n\r\n### Fixes to Crashes\r\n\r\n*   Fix a crash when function-scope recursive alias appears as upper bound (Ivan Levkivskyi, PR [15159](https://github.com/python/mypy/pull/15159))\r\n*   Fix crash on follow\\_imports\\_for\\_stubs (Ivan Levkivskyi, PR [15407](https://github.com/python/mypy/pull/15407))\r\n*   Fix stubtest crash in explicit init subclass (Shantanu, PR [15399](https://github.com/python/mypy/pull/15399))\r\n*   Fix crash when indexing TypedDict with empty key (Shantanu, PR [15392](https://github.com/python/mypy/pull/15392))\r\n*   Fix crash on NamedTuple as attribute (Ivan Levkivskyi, PR [15404](https://github.com/python/mypy/pull/15404))\r\n*   Correctly track loop depth for nested functions/classes (Ivan Levkivskyi, PR [15403](https://github.com/python/mypy/pull/15403))\r\n*   Fix crash on joins with recursive tuples (Ivan Levkivskyi, PR [15402](https://github.com/python/mypy/pull/15402))\r\n*   Fix crash with custom ErrorCode subclasses (Marc Mueller, PR [15327](https://github.com/python/mypy/pull/15327))\r\n*   Fix crash in dataclass protocol with self attribute assignment (Ivan Levkivskyi, PR [15157](https://github.com/python/mypy/pull/15157))\r\n*   Fix crash on lambda in generic context with generic method in body (Ivan Levkivskyi, PR [15155](https://github.com/python/mypy/pull/15155))\r\n*   Fix recursive type alias crash in make\\_simplified\\_union (Ivan Levkivskyi, PR [15216](https://github.com/python/mypy/pull/15216))\r\n\r\n### Improvements to Error Messages\r\n\r\n*   Use lower-case built-in collection types such as list\\[…\\] instead of List\\[…\\] in errors when targeting Python 3.9+ (Max Murin, PR [15070](https://github.com/python/mypy/pull/15070))\r\n*   Use X | Y union syntax in error messages when targeting Python 3.10+ (Omar Silva, PR [15102](https://github.com/python/mypy/pull/15102))\r\n*   Use type instead of Type in errors when targeting Python 3.9+ (Rohit Sanjay, PR [15139](https://github.com/python/mypy/pull/15139))\r\n*   Do not show unused-ignore errors in unreachable code, and make it a real error code (Ivan Levkivskyi, PR [15164](https://github.com/python/mypy/pull/15164))\r\n*   Don’t limit the number of errors shown by default (Rohit Sanjay, PR [15138](https://github.com/python/mypy/pull/15138))\r\n*   Improver message for truthy functions (madt2709, PR [15193](https://github.com/python/mypy/pull/15193))\r\n*   Output distinct types when type names are ambiguous (teresa0605, PR [15184](https://github.com/python/mypy/pull/15184))\r\n*   Update message about invalid exception type in try (AJ Rasmussen, PR [15131](https://github.com/python/mypy/pull/15131))\r\n*   Add explanation if argument type is incompatible because of an unsupported numbers type (Jukka Lehtosalo, PR [15137](https://github.com/python/mypy/pull/15137))\r\n*   Add more detail to 'signature incompatible with supertype' messages for non-callables (Ilya Priven, PR [15263](https://github.com/python/mypy/pull/15263))\r\n\r\n### Documentation Updates\r\n\r\n*   Add \\--local-partial-types note to dmypy docs (Alan Du, PR [15259](https://github.com/python/mypy/pull/15259))\r\n*   Update getting started docs for mypyc for Windows (Valentin Stanciu, PR [15233](https://github.com/python/mypy/pull/15233))\r\n*   Clarify usage of callables regarding type object in docs (Viicos, PR [15079](https://github.com/python/mypy/pull/15079))\r\n*   Clarify difference between disallow\\_untyped\\_defs and disallow\\_incomplete\\_defs (Ilya Priven, PR [15247](https://github.com/python/mypy/pull/15247))\r\n*   Use attrs and @attrs.define in documentation and tests (Ilya Priven, PR [15152](https://github.com/python/mypy/pull/15152))\r\n\r\n### Mypyc Improvements\r\n\r\n*   Fix unexpected TypeError for certain variables with an inferred optional type (Richard Si, PR [15206](https://github.com/python/mypy/pull/15206))\r\n*   Inline math literals (Logan Hunt, PR [15324](https://github.com/python/mypy/pull/15324))\r\n*   Support unpacking mappings in dict display (Richard Si, PR [15203](https://github.com/python/mypy/pull/15203))\r\n\r\n### Changes to Stubgen\r\n\r\n*   Do not remove Generic from base classes (Ali Hamdan, PR [15316](https://github.com/python/mypy/pull/15316))\r\n*   Support yield from statements (Ali Hamdan, PR [15271](https://github.com/python/mypy/pull/15271))\r\n*   Fix missing total from TypedDict class (Ali Hamdan, PR [15208](https://github.com/python/mypy/pull/15208))\r\n*   Fix call-based namedtuple omitted from class bases (Ali Hamdan, PR [14680](https://github.com/python/mypy/pull/14680))\r\n*   Support TypedDict alternative syntax (Ali Hamdan, PR [14682](https://github.com/python/mypy/pull/14682))\r\n*   Make stubgen respect MYPY\\_CACHE\\_DIR (Henrik Bäärnhielm, PR [14722](https://github.com/python/mypy/pull/14722))\r\n*   Fixes and simplifications (Ali Hamdan, PR [15232](https://github.com/python/mypy/pull/15232))\r\n\r\n### Other Notable Fixes and Improvements\r\n\r\n*   Fix nested async functions when using TypeVar value restriction (Jukka Lehtosalo, PR [14705](https://github.com/python/mypy/pull/14705))\r\n*   Always allow returning Any from lambda (Ivan Levkivskyi, PR [15413](https://github.com/python/mypy/pull/15413))\r\n*   Add foundation for TypeVar defaults (PEP 696) (Marc Mueller, PR [14872](https://github.com/python/mypy/pull/14872))\r\n*   Update semantic analyzer for TypeVar defaults (PEP 696) (Marc Mueller, PR [14873](https://github.com/python/mypy/pull/14873))\r\n*   Make dict expression inference more consistent (Ivan Levkivskyi, PR [15174](https://github.com/python/mypy/pull/15174))\r\n*   Do not block on duplicate base classes (Nikita Sobolev, PR [15367](https://github.com/python/mypy/pull/15367))\r\n*   Generate an error when both staticmethod and classmethod decorators are used (Juhi Chandalia, PR [15118](https://github.com/python/mypy/pull/15118))\r\n*   Fix assert\\_type behaviour with literals (Carl Karsten, PR [15123](https://github.com/python/mypy/pull/15123))\r\n*   Fix match subject ignoring redefinitions (Vincent Vanlaer, PR [15306](https://github.com/python/mypy/pull/15306))\r\n*   Support `__all__`.remove (Shantanu, PR [15279](https://github.com/python/mypy/pull/15279))\r\n\r\n### Typeshed Updates\r\n\r\nTypeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please see [git log](https://github.com/python/typeshed/commits/main?after=877e06ad1cfd9fd9967c0b0340a86d0c23ea89ce+0&branch=main&path=stdlib) for full list of typeshed changes.\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n*   Adrian Garcia Badaracco\r\n*   AJ Rasmussen\r\n*   Alan Du\r\n*   Alex Waygood\r\n*   Ali Hamdan\r\n*   Carl Karsten\r\n*   dosisod\r\n*   Ethan Smith\r\n*   Gregory Santosa\r\n*   Heather White\r\n*   Henrik Bäärnhielm\r\n*   Ilya Konstantinov\r\n*   Ilya Priven\r\n*   Ivan Levkivskyi\r\n*   Juhi Chandalia\r\n*   Jukka Lehtosalo\r\n*   Logan Hunt\r\n*   madt2709\r\n*   Marc Mueller\r\n*   Max Murin\r\n*   Nikita Sobolev\r\n*   Omar Silva\r\n*   Özgür\r\n*   Richard Si\r\n*   Rohit Sanjay\r\n*   Shantanu\r\n*   teresa0605\r\n*   Thomas M Kehrenberg\r\n*   Tin Tvrtković\r\n*   Tushar Sadhwani\r\n*   Valentin Stanciu\r\n*   Viicos\r\n*   Vincent Vanlaer\r\n*   Wesley Collin Wright\r\n*   William Santosa\r\n*   yaegassy\r\n\r\nI’d also like to thank my employer, Dropbox, for supporting mypy development.\r\n\r\nPosted by Jared Hance\r\n\r\n\r\n## Mypy 1.3\r\n\r\n[Wednesday, 10 May 2023](https://mypy-lang.blogspot.com/2023/05/mypy-13-released.html)\r\n\r\n We’ve just uploaded mypy 1.3 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Performance Improvements\r\n\r\n*   Improve performance of union subtyping (Shantanu, PR [15104](https://github.com/python/mypy/pull/15104))\r\n*   Add negative subtype caches (Ivan Levkivskyi, PR [14884](https://github.com/python/mypy/pull/14884))\r\n\r\n### Stub Tooling Improvements\r\n\r\n*   Stubtest: Check that the stub is abstract if the runtime is, even when the stub is an overloaded method (Alex Waygood, PR [14955](https://github.com/python/mypy/pull/14955))\r\n*   Stubtest: Verify stub methods or properties are decorated with @final if they are decorated with @final at runtime (Alex Waygood, PR [14951](https://github.com/python/mypy/pull/14951))\r\n*   Stubtest: Fix stubtest false positives with TypedDicts at runtime (Alex Waygood, PR [14984](https://github.com/python/mypy/pull/14984))\r\n*   Stubgen: Support @functools.cached\\_property (Nikita Sobolev, PR [14981](https://github.com/python/mypy/pull/14981))\r\n*   Improvements to stubgenc (Chad Dombrova, PR [14564](https://github.com/python/mypy/pull/14564))\r\n\r\n### Improvements to attrs\r\n\r\n*   Add support for converters with TypeVars on generic attrs classes (Chad Dombrova, PR [14908](https://github.com/python/mypy/pull/14908))\r\n*   Fix attrs.evolve on bound TypeVar (Ilya Konstantinov, PR [15022](https://github.com/python/mypy/pull/15022))\r\n\r\n### Documentation Updates\r\n\r\n*   Improve async documentation (Shantanu, PR [14973](https://github.com/python/mypy/pull/14973))\r\n*   Improvements to cheat sheet (Shantanu, PR [14972](https://github.com/python/mypy/pull/14972))\r\n*   Add documentation for bytes formatting error code (Shantanu, PR [14971](https://github.com/python/mypy/pull/14971))\r\n*   Convert insecure links to use HTTPS (Marti Raudsepp, PR [14974](https://github.com/python/mypy/pull/14974))\r\n*   Also mention overloads in async iterator documentation (Shantanu, PR [14998](https://github.com/python/mypy/pull/14998))\r\n*   stubtest: Improve allowlist documentation (Shantanu, PR [15008](https://github.com/python/mypy/pull/15008))\r\n*   Clarify \"Using types... but not at runtime\" (Jon Shea, PR [15029](https://github.com/python/mypy/pull/15029))\r\n*   Fix alignment of cheat sheet example (Ondřej Cvacho, PR [15039](https://github.com/python/mypy/pull/15039))\r\n*   Fix error for callback protocol matching against callable type object (Shantanu, PR [15042](https://github.com/python/mypy/pull/15042))\r\n\r\n### Error Reporting Improvements\r\n\r\n*   Improve bytes formatting error (Shantanu, PR [14959](https://github.com/python/mypy/pull/14959))\r\n\r\n### Mypyc Improvements\r\n\r\n*   Fix unions of bools and ints (Tomer Chachamu, PR [15066](https://github.com/python/mypy/pull/15066))\r\n\r\n### Other Fixes and Improvements\r\n\r\n*   Fix narrowing union types that include Self with isinstance (Christoph Tyralla, PR [14923](https://github.com/python/mypy/pull/14923))\r\n*   Allow objects matching SupportsKeysAndGetItem to be unpacked (Bryan Forbes, PR [14990](https://github.com/python/mypy/pull/14990))\r\n*   Check type guard validity for staticmethods (EXPLOSION, PR [14953](https://github.com/python/mypy/pull/14953))\r\n*   Fix sys.platform when cross-compiling with emscripten (Ethan Smith, PR [14888](https://github.com/python/mypy/pull/14888))\r\n\r\n### Typeshed Updates\r\n\r\nTypeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please see [git log](https://github.com/python/typeshed/commits/main?after=b0ed50e9392a23e52445b630a808153e0e256976+0&branch=main&path=stdlib) for full list of typeshed changes.\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n*   Alex Waygood\r\n*   Amin Alaee\r\n*   Bryan Forbes\r\n*   Chad Dombrova\r\n*   Charlie Denton\r\n*   Christoph Tyralla\r\n*   dosisod\r\n*   Ethan Smith\r\n*   EXPLOSION\r\n*   Ilya Konstantinov\r\n*   Ivan Levkivskyi\r\n*   Jon Shea\r\n*   Jukka Lehtosalo\r\n*   KotlinIsland\r\n*   Marti Raudsepp\r\n*   Nikita Sobolev\r\n*   Ondřej Cvacho\r\n*   Shantanu\r\n*   sobolevn\r\n*   Tomer Chachamu\r\n*   Yaroslav Halchenko\r\n\r\nPosted by Wesley Collin Wright.\r\n\r\n\r\n## Mypy 1.2\r\n\r\n[Thursday, 6 April 2023](https://mypy-lang.blogspot.com/2023/04/mypy-12-released.html)\r\n\r\nWe’ve just uploaded mypy 1.2 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Improvements to Dataclass Transforms\r\n\r\n*   Support implicit default for \"init\" parameter in field specifiers (Wesley Collin Wright and Jukka Lehtosalo, PR [15010](https://github.com/python/mypy/pull/15010))\r\n*   Support descriptors in dataclass transform (Jukka Lehtosalo, PR [15006](https://github.com/python/mypy/pull/15006))\r\n*   Fix frozen\\_default in incremental mode (Wesley Collin Wright)\r\n*   Fix frozen behavior for base classes with direct metaclasses (Wesley Collin Wright, PR [14878](https://github.com/python/mypy/pull/14878))\r\n\r\n### Mypyc: Native Floats\r\n\r\nMypyc now uses a native, unboxed representation for values of type float. Previously these were heap-allocated Python objects. Native floats are faster and use less memory. Code that uses floating-point operations heavily can be several times faster when using native floats.\r\n\r\nVarious float operations and math functions also now have optimized implementations. Refer to the [documentation](https://mypyc.readthedocs.io/en/latest/float_operations.html) for a full list.\r\n\r\nThis can change the behavior of existing code that uses subclasses of float. When assigning an instance of a subclass of float to a variable with the float type, it gets implicitly converted to a float instance when compiled:\r\n\r\n```python\r\nfrom lib import MyFloat  # MyFloat ia a subclass of \"float\"\r\n\r\ndef example() -> None:\r\n    x = MyFloat(1.5)\r\n    y: float = x  # Implicit conversion from MyFloat to float\r\n    print(type(y))  # float, not MyFloat\r\n```\r\n\r\nPreviously, implicit conversions were applied to int subclasses but not float subclasses.\r\n\r\nAlso, int values can no longer be assigned to a variable with type float in compiled code, since these types now have incompatible representations. An explicit conversion is required:\r\n\r\n```python\r\ndef example(n: int) -> None:\r\n    a: float = 1  # Error: cannot assign \"int\" to \"float\"\r\n    b: float = 1.0  # OK\r\n    c: float = n  # Error\r\n    d: float = float(n)  # OK\r\n```\r\n\r\nThis restriction only applies to assignments, since they could otherwise narrow down the type of a variable from float to int. int values can still be implicitly converted to float when passed as arguments to functions that expect float values.\r\n\r\nNote that mypyc still doesn’t support arrays of unboxed float values. Using list\\[float\\] involves heap-allocated float objects, since list can only store boxed values. Support for efficient floating point arrays is one of the next major planned mypyc features.\r\n\r\nRelated changes:\r\n\r\n*   Use a native unboxed representation for floats (Jukka Lehtosalo, PR [14880](https://github.com/python/mypy/pull/14880))\r\n*   Document native floats and integers (Jukka Lehtosalo, PR [14927](https://github.com/python/mypy/pull/14927))\r\n*   Fixes to float to int conversion (Jukka Lehtosalo, PR [14936](https://github.com/python/mypy/pull/14936))\r\n\r\n### Mypyc: Native Integers\r\n\r\nMypyc now supports signed 32-bit and 64-bit integer types in addition to the arbitrary-precision int type. You can use the types mypy\\_extensions.i32 and mypy\\_extensions.i64 to speed up code that uses integer operations heavily.\r\n\r\nSimple example:\r\n```python\r\nfrom mypy_extensions import i64\r\n\r\ndef inc(x: i64) -> i64:\r\n    return x + 1\r\n```\r\n\r\nRefer to the [documentation](https://mypyc.readthedocs.io/en/latest/using_type_annotations.html#native-integer-types) for more information. This feature was contributed by Jukka Lehtosalo.\r\n\r\n### Other Mypyc Fixes and Improvements\r\n\r\n*   Support iterating over a TypedDict (Richard Si, PR [14747](https://github.com/python/mypy/pull/14747))\r\n*   Faster coercions between different tuple types (Jukka Lehtosalo, PR [14899](https://github.com/python/mypy/pull/14899))\r\n*   Faster calls via type aliases (Jukka Lehtosalo, PR [14784](https://github.com/python/mypy/pull/14784))\r\n*   Faster classmethod calls via cls (Jukka Lehtosalo, PR [14789](https://github.com/python/mypy/pull/14789))\r\n\r\n### Fixes to Crashes\r\n\r\n*   Fix crash on class-level import in protocol definition (Ivan Levkivskyi, PR [14926](https://github.com/python/mypy/pull/14926))\r\n*   Fix crash on single item union of alias (Ivan Levkivskyi, PR [14876](https://github.com/python/mypy/pull/14876))\r\n*   Fix crash on ParamSpec in incremental mode (Ivan Levkivskyi, PR [14885](https://github.com/python/mypy/pull/14885))\r\n\r\n### Documentation Updates\r\n\r\n*   Update adopting \\--strict documentation for 1.0 (Shantanu, PR [14865](https://github.com/python/mypy/pull/14865))\r\n*   Some minor documentation tweaks (Jukka Lehtosalo, PR [14847](https://github.com/python/mypy/pull/14847))\r\n*   Improve documentation of top level mypy: disable-error-code comment (Nikita Sobolev, PR [14810](https://github.com/python/mypy/pull/14810))\r\n\r\n### Error Reporting Improvements\r\n\r\n*   Add error code to `typing_extensions` suggestion (Shantanu, PR [14881](https://github.com/python/mypy/pull/14881))\r\n*   Add a separate error code for top-level await (Nikita Sobolev, PR [14801](https://github.com/python/mypy/pull/14801))\r\n*   Don’t suggest two obsolete stub packages (Jelle Zijlstra, PR [14842](https://github.com/python/mypy/pull/14842))\r\n*   Add suggestions for pandas-stubs and lxml-stubs (Shantanu, PR [14737](https://github.com/python/mypy/pull/14737))\r\n\r\n### Other Fixes and Improvements\r\n\r\n*   Multiple inheritance considers callable objects as subtypes of functions (Christoph Tyralla, PR [14855](https://github.com/python/mypy/pull/14855))\r\n*   stubtest: Respect @final runtime decorator and enforce it in stubs (Nikita Sobolev, PR [14922](https://github.com/python/mypy/pull/14922))\r\n*   Fix false positives related to type\\[<type-var>\\] (sterliakov, PR [14756](https://github.com/python/mypy/pull/14756))\r\n*   Fix duplication of ParamSpec prefixes and properly substitute ParamSpecs (EXPLOSION, PR [14677](https://github.com/python/mypy/pull/14677))\r\n*   Fix line number if `__iter__` is incorrectly reported as missing (Jukka Lehtosalo, PR [14893](https://github.com/python/mypy/pull/14893))\r\n*   Fix incompatible overrides of overloaded generics with self types (Shantanu, PR [14882](https://github.com/python/mypy/pull/14882))\r\n*   Allow SupportsIndex in slice expressions (Shantanu, PR [14738](https://github.com/python/mypy/pull/14738))\r\n*   Support if statements in bodies of dataclasses and classes that use dataclass\\_transform (Jacek Chałupka, PR [14854](https://github.com/python/mypy/pull/14854))\r\n*   Allow iterable class objects to be unpacked (including enums) (Alex Waygood, PR [14827](https://github.com/python/mypy/pull/14827))\r\n*   Fix narrowing for walrus expressions used in match statements (Shantanu, PR [14844](https://github.com/python/mypy/pull/14844))\r\n*   Add signature for attr.evolve (Ilya Konstantinov, PR [14526](https://github.com/python/mypy/pull/14526))\r\n*   Fix Any inference when unpacking iterators that don't directly inherit from typing.Iterator (Alex Waygood, PR [14821](https://github.com/python/mypy/pull/14821))\r\n*   Fix unpack with overloaded `__iter__` method (Nikita Sobolev, PR [14817](https://github.com/python/mypy/pull/14817))\r\n*   Reduce size of JSON data in mypy cache (dosisod, PR [14808](https://github.com/python/mypy/pull/14808))\r\n*   Improve “used before definition” checks when a local definition has the same name as a global definition (Stas Ilinskiy, PR [14517](https://github.com/python/mypy/pull/14517))\r\n*   Honor NoReturn as \\_\\_setitem\\_\\_ return type to mark unreachable code (sterliakov, PR [12572](https://github.com/python/mypy/pull/12572))\r\n\r\n### Typeshed Updates\r\n\r\nTypeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please see [git log](https://github.com/python/typeshed/commits/main?after=a544b75320e97424d2d927605316383c755cdac0+0&branch=main&path=stdlib) for full list of typeshed changes.\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n*   Alex Waygood\r\n*   Avasam\r\n*   Christoph Tyralla\r\n*   dosisod\r\n*   EXPLOSION\r\n*   Ilya Konstantinov\r\n*   Ivan Levkivskyi\r\n*   Jacek Chałupka\r\n*   Jelle Zijlstra\r\n*   Jukka Lehtosalo\r\n*   Marc Mueller\r\n*   Max Murin\r\n*   Nikita Sobolev\r\n*   Richard Si\r\n*   Shantanu\r\n*   Stas Ilinskiy\r\n*   sterliakov\r\n*   Wesley Collin Wright\r\n\r\nPosted by Jukka Lehtosalo\r\n\r\n\r\n## Mypy 1.1.1\r\n\r\n[Monday, 6 March 2023](https://mypy-lang.blogspot.com/2023/03/mypy-111-released.html)\r\n\r\n We’ve just uploaded mypy 1.1.1 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### Support for `dataclass_transform``\r\n\r\nThis release adds full support for the dataclass\\_transform decorator defined in [PEP 681](https://peps.python.org/pep-0681/#decorator-function-example). This allows decorators, base classes, and metaclasses that generate a \\_\\_init\\_\\_ method or other methods based on the properties of that class (similar to dataclasses) to have those methods recognized by mypy.\r\n\r\nThis was contributed by Wesley Collin Wright.\r\n\r\n### Dedicated Error Code for Method Assignments\r\n\r\nMypy can’t safely check all assignments to methods (a form of monkey patching), so mypy generates an error by default. To make it easier to ignore this error, mypy now uses the new error code method-assign for this. By disabling this error code in a file or globally, mypy will no longer complain about assignments to methods if the signatures are compatible.\r\n\r\nMypy also supports the old error code assignment for these assignments to prevent a backward compatibility break. More generally, we can use this mechanism in the future if we wish to split or rename another existing error code without causing backward compatibility issues.\r\n\r\nThis was contributed by Ivan Levkivskyi (PR [14570](https://github.com/python/mypy/pull/14570)).\r\n\r\n### Fixes to Crashes\r\n\r\n*   Fix a crash on walrus in comprehension at class scope (Ivan Levkivskyi, PR [14556](https://github.com/python/mypy/pull/14556))\r\n*   Fix crash related to value-constrained TypeVar (Shantanu, PR [14642](https://github.com/python/mypy/pull/14642))\r\n\r\n### Fixes to Cache Corruption\r\n\r\n*   Fix generic TypedDict/NamedTuple caching (Ivan Levkivskyi, PR [14675](https://github.com/python/mypy/pull/14675))\r\n\r\n### Mypyc Fixes and Improvements\r\n\r\n*   Raise \"non-trait base must be first...\" error less frequently (Richard Si, PR [14468](https://github.com/python/mypy/pull/14468))\r\n*   Generate faster code for bool comparisons and arithmetic (Jukka Lehtosalo, PR [14489](https://github.com/python/mypy/pull/14489))\r\n*   Optimize \\_\\_(a)enter\\_\\_/\\_\\_(a)exit\\_\\_ for native classes (Jared Hance, PR [14530](https://github.com/python/mypy/pull/14530))\r\n*   Detect if attribute definition conflicts with base class/trait (Jukka Lehtosalo, PR [14535](https://github.com/python/mypy/pull/14535))\r\n*   Support \\_\\_(r)divmod\\_\\_ dunders (Richard Si, PR [14613](https://github.com/python/mypy/pull/14613))\r\n*   Support \\_\\_pow\\_\\_, \\_\\_rpow\\_\\_, and \\_\\_ipow\\_\\_ dunders (Richard Si, PR [14616](https://github.com/python/mypy/pull/14616))\r\n*   Fix crash on star unpacking to underscore (Ivan Levkivskyi, PR [14624](https://github.com/python/mypy/pull/14624))\r\n*   Fix iterating over a union of dicts (Richard Si, PR [14713](https://github.com/python/mypy/pull/14713))\r\n\r\n### Fixes to Detecting Undefined Names (used-before-def)\r\n\r\n*   Correctly handle walrus operator (Stas Ilinskiy, PR [14646](https://github.com/python/mypy/pull/14646))\r\n*   Handle walrus declaration in match subject correctly (Stas Ilinskiy, PR [14665](https://github.com/python/mypy/pull/14665))\r\n\r\n### Stubgen Improvements\r\n\r\nStubgen is a tool for automatically generating draft stubs for libraries.\r\n\r\n*   Allow aliases below the top level (Chad Dombrova, PR [14388](https://github.com/python/mypy/pull/14388))\r\n*   Fix crash with PEP 604 union in type variable bound (Shantanu, PR [14557](https://github.com/python/mypy/pull/14557))\r\n*   Preserve PEP 604 unions in generated .pyi files (hamdanal, PR [14601](https://github.com/python/mypy/pull/14601))\r\n\r\n### Stubtest Improvements\r\n\r\nStubtest is a tool for testing that stubs conform to the implementations.\r\n\r\n*   Update message format so that it’s easier to go to error location (Avasam, PR [14437](https://github.com/python/mypy/pull/14437))\r\n*   Handle name-mangling edge cases better (Alex Waygood, PR [14596](https://github.com/python/mypy/pull/14596))\r\n\r\n### Changes to Error Reporting and Messages\r\n\r\n*   Add new TypedDict error code typeddict-unknown-key (JoaquimEsteves, PR [14225](https://github.com/python/mypy/pull/14225))\r\n*   Give arguments a more reasonable location in error messages (Max Murin, PR [14562](https://github.com/python/mypy/pull/14562))\r\n*   In error messages, quote just the module's name (Ilya Konstantinov, PR [14567](https://github.com/python/mypy/pull/14567))\r\n*   Improve misleading message about Enum() (Rodrigo Silva, PR [14590](https://github.com/python/mypy/pull/14590))\r\n*   Suggest importing from `typing_extensions` if definition is not in typing (Shantanu, PR [14591](https://github.com/python/mypy/pull/14591))\r\n*   Consistently use type-abstract error code (Ivan Levkivskyi, PR [14619](https://github.com/python/mypy/pull/14619))\r\n*   Consistently use literal-required error code for TypedDicts (Ivan Levkivskyi, PR [14621](https://github.com/python/mypy/pull/14621))\r\n*   Adjust inconsistent dataclasses plugin error messages (Wesley Collin Wright, PR [14637](https://github.com/python/mypy/pull/14637))\r\n*   Consolidate literal bool argument error messages (Wesley Collin Wright, PR [14693](https://github.com/python/mypy/pull/14693))\r\n\r\n### Other Fixes and Improvements\r\n\r\n*   Check that type guards accept a positional argument (EXPLOSION, PR [14238](https://github.com/python/mypy/pull/14238))\r\n*   Fix bug with in operator used with a union of Container and Iterable (Max Murin, PR [14384](https://github.com/python/mypy/pull/14384))\r\n*   Support protocol inference for type\\[T\\] via metaclass (Ivan Levkivskyi, PR [14554](https://github.com/python/mypy/pull/14554))\r\n*   Allow overlapping comparisons between bytes-like types (Shantanu, PR [14658](https://github.com/python/mypy/pull/14658))\r\n*   Fix mypy daemon documentation link in README (Ivan Levkivskyi, PR [14644](https://github.com/python/mypy/pull/14644))\r\n\r\n### Typeshed Updates\r\n\r\nTypeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please see [git log](https://github.com/python/typeshed/commits/main?after=5ebf892d0710a6e87925b8d138dfa597e7bb11cc+0&branch=main&path=stdlib) for full list of typeshed changes.\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n*   Alex Waygood\r\n*   Avasam\r\n*   Chad Dombrova\r\n*   dosisod\r\n*   EXPLOSION\r\n*   hamdanal\r\n*   Ilya Konstantinov\r\n*   Ivan Levkivskyi\r\n*   Jared Hance\r\n*   JoaquimEsteves\r\n*   Jukka Lehtosalo\r\n*   Marc Mueller\r\n*   Max Murin\r\n*   Michael Lee\r\n*   Michael R. Crusoe\r\n*   Richard Si\r\n*   Rodrigo Silva\r\n*   Shantanu\r\n*   Stas Ilinskiy\r\n*   Wesley Collin Wright\r\n*   Yilei \"Dolee\" Yang\r\n*   Yurii Karabas\r\n\r\nWe’d also like to thank our employer, Dropbox, for funding the mypy core team.\r\n\r\nPosted by Max Murin\r\n\r\n\r\n## Mypy 1.0\r\n\r\n[Monday, 6 February 2023](https://mypy-lang.blogspot.com/2023/02/mypy-10-released.html)\r\n\r\nWe’ve just uploaded mypy 1.0 to the Python Package Index ([PyPI](https://pypi.org/project/mypy/)). Mypy is a static type checker for Python. This release includes new features, performance improvements and bug fixes. You can install it as follows:\r\n\r\n    python3 -m pip install -U mypy\r\n\r\nYou can read the full documentation for this release on [Read the Docs](http://mypy.readthedocs.io).\r\n\r\n### New Release Versioning Scheme\r\n\r\nNow that mypy reached 1.0, we’ll switch to a new versioning scheme. Mypy version numbers will be of form x.y.z.\r\n\r\nRules:\r\n\r\n*   The major release number (x) is incremented if a feature release includes a significant backward incompatible change that affects a significant fraction of users.\r\n*   The minor release number (y) is incremented on each feature release. Minor releases include updated stdlib stubs from typeshed.\r\n*   The point release number (z) is incremented when there are fixes only.\r\n\r\nMypy doesn't use SemVer, since most minor releases have at least minor backward incompatible changes in typeshed, at the very least. Also, many type checking features find new legitimate issues in code. These are not considered backward incompatible changes, unless the number of new errors is very high.\r\n\r\nAny significant backward incompatible change must be announced in the blog post for the previous feature release, before making the change. The previous release must also provide a flag to explicitly enable or disable the new behavior (whenever practical), so that users will be able to prepare for the changes and report issues. We should keep the feature flag for at least a few releases after we've switched the default.\r\n\r\nSee [”Release Process” in the mypy wiki](https://github.com/python/mypy/wiki/Release-Process) for more details and for the most up-to-date version of the versioning scheme.\r\n\r\n### Performance Improvements\r\n\r\nMypy 1.0 is up to 40% faster than mypy 0.991 when type checking the Dropbox internal codebase. We also set up a daily job to measure the performance of the most recent development version of mypy to make it easier to track changes in performance.\r\n\r\nMany optimizations contributed to this improvement:\r\n\r\n*   Improve performance for errors on class with many attributes (Shantanu, PR [14379](https://github.com/python/mypy/pull/14379))\r\n*   Speed up make\\_simplified\\_union (Jukka Lehtosalo, PR [14370](https://github.com/python/mypy/pull/14370))\r\n*   Micro-optimize get\\_proper\\_type(s) (Jukka Lehtosalo, PR [14369](https://github.com/python/mypy/pull/14369))\r\n*   Micro-optimize flatten\\_nested\\_unions (Jukka Lehtosalo, PR [14368](https://github.com/python/mypy/pull/14368))\r\n*   Some semantic analyzer micro-optimizations (Jukka Lehtosalo, PR [14367](https://github.com/python/mypy/pull/14367))\r\n*   A few miscellaneous micro-optimizations (Jukka Lehtosalo, PR [14366](https://github.com/python/mypy/pull/14366))\r\n*   Optimization: Avoid a few uses of contextmanagers in semantic analyzer (Jukka Lehtosalo, PR [14360](https://github.com/python/mypy/pull/14360))\r\n*   Optimization: Enable always defined attributes in Type subclasses (Jukka Lehtosalo, PR [14356](https://github.com/python/mypy/pull/14356))\r\n*   Optimization: Remove expensive context manager in type analyzer (Jukka Lehtosalo, PR [14357](https://github.com/python/mypy/pull/14357))\r\n*   subtypes: fast path for Union/Union subtype check (Hugues, PR [14277](https://github.com/python/mypy/pull/14277))\r\n*   Micro-optimization: avoid Bogus\\[int\\] types that cause needless boxing (Jukka Lehtosalo, PR [14354](https://github.com/python/mypy/pull/14354))\r\n*   Avoid slow error message logic if errors not shown to user (Jukka Lehtosalo, PR [14336](https://github.com/python/mypy/pull/14336))\r\n*   Speed up the implementation of hasattr() checks (Jukka Lehtosalo, PR [14333](https://github.com/python/mypy/pull/14333))\r\n*   Avoid the use of a context manager in hot code path (Jukka Lehtosalo, PR [14331](https://github.com/python/mypy/pull/14331))\r\n*   Change various type queries into faster bool type queries (Jukka Lehtosalo, PR [14330](https://github.com/python/mypy/pull/14330))\r\n*   Speed up recursive type check (Jukka Lehtosalo, PR [14326](https://github.com/python/mypy/pull/14326))\r\n*   Optimize subtype checking by avoiding a nested function (Jukka Lehtosalo, PR [14325](https://github.com/python/mypy/pull/14325))\r\n*   Optimize type parameter checks in subtype checking (Jukka Lehtosalo, PR [14324](https://github.com/python/mypy/pull/14324))\r\n*   Speed up freshening type variables (Jukka Lehtosalo, PR [14323](https://github.com/python/mypy/pull/14323))\r\n*   Optimize implementation of TypedDict types for \\*\\*kwds (Jukka Lehtosalo, PR [14316](https://github.com/python/mypy/pull/14316))\r\n\r\n### Warn About Variables Used Before Definition\r\n\r\nMypy will now generate an error if you use a variable before it’s defined. This feature is enabled by default. By default mypy reports an error when it infers that a variable is always undefined.\r\n```python\r\ny = x  # E: Name \"x\" is used before definition [used-before-def]\r\nx = 0\r\n```\r\nThis feature was contributed by Stas Ilinskiy.\r\n\r\n### Detect Possibly Undefined Variables (Experimental)\r\n\r\nA new experimental possibly-undefined error code is now available that will detect variables that may be undefined:\r\n```python\r\n    if b:\r\n        x = 0\r\n    print(x)  # Error: Name \"x\" may be undefined [possibly-undefined]\r\n```\r\nThe error code is disabled be default, since it can generate false positives.\r\n\r\nThis feature was contributed by Stas Ilinskiy.\r\n\r\n### Support the “Self” Type\r\n\r\nThere is now a simpler syntax for declaring [generic self types](https://mypy.readthedocs.io/en/stable/generics.html#generic-methods-and-generic-self) introduced in [PEP 673](https://peps.python.org/pep-0673/): the Self type. You no longer have to define a type variable to use “self types”, and you can use them with attributes. Example from mypy documentation:\r\n```python\r\nfrom typing import Self\r\n\r\nclass Friend:\r\n    other: Self | None = None\r\n\r\n    @classmethod\r\n    def make_pair(cls) -> tuple[Self, Self]:\r\n        a, b = cls(), cls()\r\n        a.other = b\r\n        b.other = a\r\n        return a, b\r\n\r\nclass SuperFriend(Friend):\r\n    pass\r\n\r\n# a and b have the inferred type \"SuperFriend\", not \"Friend\"\r\na, b = SuperFriend.make_pair()\r\n```\r\nThe feature was introduced in Python 3.11. In earlier Python versions a backport of Self is available in `typing_extensions`.\r\n\r\nThis was contributed by Ivan Levkivskyi (PR [14041](https://github.com/python/mypy/pull/14041)).\r\n\r\n### Support ParamSpec in Type Aliases\r\n\r\nParamSpec and Concatenate can now be used in type aliases. Example:\r\n```python\r\nfrom typing import ParamSpec, Callable\r\n\r\nP = ParamSpec(\"P\")\r\nA = Callable[P, None]\r\n\r\ndef f(c: A[int, str]) -> None:\r\n    c(1, \"x\")\r\n```\r\nThis feature was contributed by Ivan Levkivskyi (PR [14159](https://github.com/python/mypy/pull/14159)).\r\n\r\n### ParamSpec and Generic Self Types No Longer Experimental\r\n\r\nSupport for ParamSpec ([PEP 612](https://www.python.org/dev/peps/pep-0612/)) and generic self types are no longer considered experimental.\r\n\r\n### Miscellaneous New Features\r\n\r\n*   Minimal, partial implementation of dataclass\\_transform ([PEP 681](https://peps.python.org/pep-0681/)) (Wesley Collin Wright, PR [14523](https://github.com/python/mypy/pull/14523))\r\n*   Add basic support for `typing_extensions`.TypeVar (Marc Mueller, PR [14313](https://github.com/python/mypy/pull/14313))\r\n*   Add \\--debug-serialize option (Marc Mueller, PR [14155](https://github.com/python/mypy/pull/14155))\r\n*   Constant fold initializers of final variables (Jukka Lehtosalo, PR [14283](https://github.com/python/mypy/pull/14283))\r\n*   Enable Final instance attributes for attrs (Tin Tvrtković, PR [14232](https://github.com/python/mypy/pull/14232))\r\n*   Allow function arguments as base classes (Ivan Levkivskyi, PR [14135](https://github.com/python/mypy/pull/14135))\r\n*   Allow super() with mixin protocols (Ivan Levkivskyi, PR [14082](https://github.com/python/mypy/pull/14082))\r\n*   Add type inference for dict.keys membership (Matthew Hughes, PR [13372](https://github.com/python/mypy/pull/13372))\r\n*   Generate error for class attribute access if attribute is defined with `__slots__` (Harrison McCarty, PR [14125](https://github.com/python/mypy/pull/14125))\r\n*   Support additional attributes in callback protocols (Ivan Levkivskyi, PR [14084](https://github.com/python/mypy/pull/14084))\r\n\r\n### Fixes to Crashes\r\n\r\n*   Fix crash on prefixed ParamSpec with forward reference (Ivan Levkivskyi, PR [14569](https://github.com/python/mypy/pull/14569))\r\n*   Fix internal crash when resolving the same partial type twice (Shantanu, PR [14552](https://github.com/python/mypy/pull/14552))\r\n*   Fix crash in daemon mode on new import cycle (Ivan Levkivskyi, PR [14508](https://github.com/python/mypy/pull/14508))\r\n*   Fix crash in mypy daemon (Ivan Levkivskyi, PR [14497](https://github.com/python/mypy/pull/14497))\r\n*   Fix crash on Any metaclass in incremental mode (Ivan Levkivskyi, PR [14495](https://github.com/python/mypy/pull/14495))\r\n*   Fix crash in await inside comprehension outside function (Ivan Levkivskyi, PR [14486](https://github.com/python/mypy/pull/14486))\r\n*   Fix crash in Self type on forward reference in upper bound (Ivan Levkivskyi, PR [14206](https://github.com/python/mypy/pull/14206))\r\n*   Fix a crash when incorrect super() is used outside a method (Ivan Levkivskyi, PR [14208](https://github.com/python/mypy/pull/14208))\r\n*   Fix crash on overriding with frozen attrs (Ivan Levkivskyi, PR [14186](https://github.com/python/mypy/pull/14186))\r\n*   Fix incremental mode crash on generic function appearing in nested position (Ivan Levkivskyi, PR [14148](https://github.com/python/mypy/pull/14148))\r\n*   Fix daemon crash on malformed NamedTuple (Ivan Levkivskyi, PR [14119](https://github.com/python/mypy/pull/14119))\r\n*   Fix crash during ParamSpec inference (Ivan Levkivskyi, PR [14118](https://github.com/python/mypy/pull/14118))\r\n*   Fix crash on nested generic callable (Ivan Levkivskyi, PR [14093](https://github.com/python/mypy/pull/14093))\r\n*   Fix crashes with unpacking SyntaxError (Shantanu, PR [11499](https://github.com/python/mypy/pull/11499))\r\n*   Fix crash on partial type inference within a lambda (Ivan Levkivskyi, PR [14087](https://github.com/python/mypy/pull/14087))\r\n*   Fix crash with enums (Michael Lee, PR [14021](https://github.com/python/mypy/pull/14021))\r\n*   Fix crash with malformed TypedDicts and disllow-any-expr (Michael Lee, PR [13963](https://github.com/python/mypy/pull/13963))\r\n\r\n### Error Reporting Improvements\r\n\r\n*   More helpful error for missing self (Shantanu, PR [14386](https://github.com/python/mypy/pull/14386))\r\n*   Add error-code truthy-iterable (Marc Mueller, PR [13762](https://github.com/python/mypy/pull/13762))\r\n*   Fix pluralization in error messages (KotlinIsland, PR [14411](https://github.com/python/mypy/pull/14411))\r\n\r\n### Mypyc: Support Match Statement\r\n\r\nMypyc can now compile Python 3.10 match statements.\r\n\r\nThis was contributed by dosisod (PR [13953](https://github.com/python/mypy/pull/13953)).\r\n\r\n### Other Mypyc Fixes and Improvements\r\n\r\n*   Optimize int(x)/float(x)/complex(x) on instances of native classes (Richard Si, PR [14450](https://github.com/python/mypy/pull/14450))\r\n*   Always emit warnings (Richard Si, PR [14451](https://github.com/python/mypy/pull/14451))\r\n*   Faster bool and integer conversions (Jukka Lehtosalo, PR [14422](https://github.com/python/mypy/pull/14422))\r\n*   Support attributes that override properties (Jukka Lehtosalo, PR [14377](https://github.com/python/mypy/pull/14377))\r\n*   Precompute set literals for \"in\" operations and iteration (Richard Si, PR [14409](https://github.com/python/mypy/pull/14409))\r\n*   Don't load targets with forward references while setting up non-extension class `__all__` (Richard Si, PR [14401](https://github.com/python/mypy/pull/14401))\r\n*   Compile away NewType type calls (Richard Si, PR [14398](https://github.com/python/mypy/pull/14398))\r\n*   Improve error message for multiple inheritance (Joshua Bronson, PR [14344](https://github.com/python/mypy/pull/14344))\r\n*   Simplify union types (Jukka Lehtosalo, PR [14363](https://github.com/python/mypy/pull/14363))\r\n*   Fixes to union simplification (Jukka Lehtosalo, PR [14364](https://github.com/python/mypy/pull/14364))\r\n*   Fix for typeshed changes to Collection (Shantanu, PR [13994](https://github.com/python/mypy/pull/13994))\r\n*   Allow use of enum.Enum (Shantanu, PR [13995](https://github.com/python/mypy/pull/13995))\r\n*   Fix compiling on Arch Linux (dosisod, PR [13978](https://github.com/python/mypy/pull/13978))\r\n\r\n### Documentation Improvements\r\n\r\n*   Various documentation and error message tweaks (Jukka Lehtosalo, PR [14574](https://github.com/python/mypy/pull/14574))\r\n*   Improve Generics documentation (Shantanu, PR [14587](https://github.com/python/mypy/pull/14587))\r\n*   Improve protocols documentation (Shantanu, PR [14577](https://github.com/python/mypy/pull/14577))\r\n*   Improve dynamic typing documentation (Shantanu, PR [14576](https://github.com/python/mypy/pull/14576))\r\n*   Improve the Common Issues page (Shantanu, PR [14581](https://github.com/python/mypy/pull/14581))\r\n*   Add a top-level TypedDict page (Shantanu, PR [14584](https://github.com/python/mypy/pull/14584))\r\n*   More improvements to getting started documentation (Shantanu, PR [14572](https://github.com/python/mypy/pull/14572))\r\n*   Move truthy-function documentation from “optional checks” to “enabled by default” (Anders Kaseorg, PR [14380](https://github.com/python/mypy/pull/14380))\r\n*   Avoid use of implicit optional in decorator factory documentation (Tom Schraitle, PR [14156](https://github.com/python/mypy/pull/14156))\r\n*   Clarify documentation surrounding install-types (Shantanu, PR [14003](https://github.com/python/mypy/pull/14003))\r\n*   Improve searchability for module level type ignore errors (Shantanu, PR [14342](https://github.com/python/mypy/pull/14342))\r\n*   Advertise mypy daemon in README (Ivan Levkivskyi, PR [14248](https://github.com/python/mypy/pull/14248))\r\n*   Add link to error codes in README (Ivan Levkivskyi, PR [14249](https://github.com/python/mypy/pull/14249))\r\n*   Document that report generation disables cache (Ilya Konstantinov, PR [14402](https://github.com/python/mypy/pull/14402))\r\n*   Stop saying mypy is beta software (Ivan Levkivskyi, PR [14251](https://github.com/python/mypy/pull/14251))\r\n*   Flycheck-mypy is deprecated, since its functionality was merged to Flycheck (Ivan Levkivskyi, PR [14247](https://github.com/python/mypy/pull/14247))\r\n*   Update code example in \"Declaring decorators\" (ChristianWitzler, PR [14131](https://github.com/python/mypy/pull/14131))\r\n\r\n### Stubtest Improvements\r\n\r\nStubtest is a tool for testing that stubs conform to the implementations.\r\n\r\n*   Improve error message for `__all__`\\-related errors (Alex Waygood, PR [14362](https://github.com/python/mypy/pull/14362))\r\n*   Improve heuristics for determining whether global-namespace names are imported (Alex Waygood, PR [14270](https://github.com/python/mypy/pull/14270))\r\n*   Catch BaseException on module imports (Shantanu, PR [14284](https://github.com/python/mypy/pull/14284))\r\n*   Associate exported symbol error with `__all__` object\\_path (Nikita Sobolev, PR [14217](https://github.com/python/mypy/pull/14217))\r\n*   Add \\_\\_warningregistry\\_\\_ to the list of ignored module dunders (Nikita Sobolev, PR [14218](https://github.com/python/mypy/pull/14218))\r\n*   If a default is present in the stub, check that it is correct (Jelle Zijlstra, PR [14085](https://github.com/python/mypy/pull/14085))\r\n\r\n### Stubgen Improvements\r\n\r\nStubgen is a tool for automatically generating draft stubs for libraries.\r\n\r\n*   Treat dlls as C modules (Shantanu, PR [14503](https://github.com/python/mypy/pull/14503))\r\n\r\n### Other Notable Fixes and Improvements\r\n\r\n*   Update stub suggestions based on recent typeshed changes (Alex Waygood, PR [14265](https://github.com/python/mypy/pull/14265))\r\n*   Fix attrs protocol check with cache (Marc Mueller, PR [14558](https://github.com/python/mypy/pull/14558))\r\n*   Fix strict equality check if operand item type has custom \\_\\_eq\\_\\_ (Jukka Lehtosalo, PR [14513](https://github.com/python/mypy/pull/14513))\r\n*   Don't consider object always truthy (Jukka Lehtosalo, PR [14510](https://github.com/python/mypy/pull/14510))\r\n*   Properly support union of TypedDicts as dict literal context (Ivan Levkivskyi, PR [14505](https://github.com/python/mypy/pull/14505))\r\n*   Properly expand type in generic class with Self and TypeVar with values (Ivan Levkivskyi, PR [14491](https://github.com/python/mypy/pull/14491))\r\n*   Fix recursive TypedDicts/NamedTuples defined with call syntax (Ivan Levkivskyi, PR [14488](https://github.com/python/mypy/pull/14488))\r\n*   Fix type inference issue when a class inherits from Any (Shantanu, PR [14404](https://github.com/python/mypy/pull/14404))\r\n*   Fix false positive on generic base class with six (Ivan Levkivskyi, PR [14478](https://github.com/python/mypy/pull/14478))\r\n*   Don't read scripts without extensions as modules in namespace mode (Tim Geypens, PR [14335](https://github.com/python/mypy/pull/14335))\r\n*   Fix inference for constrained type variables within unions (Christoph Tyralla, PR [14396](https://github.com/python/mypy/pull/14396))\r\n*   Fix Unpack imported from typing (Marc Mueller, PR [14378](https://github.com/python/mypy/pull/14378))\r\n*   Allow trailing commas in ini configuration of multiline values (Nikita Sobolev, PR [14240](https://github.com/python/mypy/pull/14240))\r\n*   Fix false negatives involving Unions and generators or coroutines (Shantanu, PR [14224](https://github.com/python/mypy/pull/14224))\r\n*   Fix ParamSpec constraint for types as callable (Vincent Vanlaer, PR [14153](https://github.com/python/mypy/pull/14153))\r\n*   Fix type aliases with fixed-length tuples (Jukka Lehtosalo, PR [14184](https://github.com/python/mypy/pull/14184))\r\n*   Fix issues with type aliases and new style unions (Jukka Lehtosalo, PR [14181](https://github.com/python/mypy/pull/14181))\r\n*   Simplify unions less aggressively (Ivan Levkivskyi, PR [14178](https://github.com/python/mypy/pull/14178))\r\n*   Simplify callable overlap logic (Ivan Levkivskyi, PR [14174](https://github.com/python/mypy/pull/14174))\r\n*   Try empty context when assigning to union typed variables (Ivan Levkivskyi, PR [14151](https://github.com/python/mypy/pull/14151))\r\n*   Improvements to recursive types (Ivan Levkivskyi, PR [14147](https://github.com/python/mypy/pull/14147))\r\n*   Make non-numeric non-empty FORCE\\_COLOR truthy (Shantanu, PR [14140](https://github.com/python/mypy/pull/14140))\r\n*   Fix to recursive type aliases (Ivan Levkivskyi, PR [14136](https://github.com/python/mypy/pull/14136))\r\n*   Correctly handle Enum name on Python 3.11 (Ivan Levkivskyi, PR [14133](https://github.com/python/mypy/pull/14133))\r\n*   Fix class objects falling back to metaclass for callback protocol (Ivan Levkivskyi, PR [14121](https://github.com/python/mypy/pull/14121))\r\n*   Correctly support self types in callable ClassVar (Ivan Levkivskyi, PR [14115](https://github.com/python/mypy/pull/14115))\r\n*   Fix type variable clash in nested positions and in attributes (Ivan Levkivskyi, PR [14095](https://github.com/python/mypy/pull/14095))\r\n*   Allow class variable as implementation for read only attribute (Ivan Levkivskyi, PR [14081](https://github.com/python/mypy/pull/14081))\r\n*   Prevent warnings from causing dmypy to fail (Andrzej Bartosiński, PR [14102](https://github.com/python/mypy/pull/14102))\r\n*   Correctly process nested definitions in mypy daemon (Ivan Levkivskyi, PR [14104](https://github.com/python/mypy/pull/14104))\r\n*   Don't consider a branch unreachable if there is a possible promotion (Ivan Levkivskyi, PR [14077](https://github.com/python/mypy/pull/14077))\r\n*   Fix incompatible overrides of overloaded methods in concrete subclasses (Shantanu, PR [14017](https://github.com/python/mypy/pull/14017))\r\n*   Fix new style union syntax in type aliases (Jukka Lehtosalo, PR [14008](https://github.com/python/mypy/pull/14008))\r\n*   Fix and optimise overload compatibility checking (Shantanu, PR [14018](https://github.com/python/mypy/pull/14018))\r\n*   Improve handling of redefinitions through imports (Shantanu, PR [13969](https://github.com/python/mypy/pull/13969))\r\n*   Preserve (some) implicitly exported types (Shantanu, PR [13967](https://github.com/python/mypy/pull/13967))\r\n\r\n### Typeshed Updates\r\n\r\nTypeshed is now modular and distributed as separate PyPI packages for everything except the standard library stubs. Please see [git log](https://github.com/python/typeshed/commits/main?after=ea0ae2155e8a04c9837903c3aff8dd5ad5f36ebc+0&branch=main&path=stdlib) for full list of typeshed changes.\r\n\r\n### Acknowledgements\r\n\r\nThanks to all mypy contributors who contributed to this release:\r\n\r\n*   Alessio Izzo\r\n*   Alex Waygood\r\n*   Anders Kaseorg\r\n*   Andrzej Bartosiński\r\n*   Avasam\r\n*   ChristianWitzler\r\n*   Christoph Tyralla\r\n*   dosisod\r\n*   Harrison McCarty\r\n*   Hugo van Kemenade\r\n*   Hugues\r\n*   Ilya Konstantinov\r\n*   Ivan Levkivskyi\r\n*   Jelle Zijlstra\r\n*   jhance\r\n*   johnthagen\r\n*   Jonathan Daniel\r\n*   Joshua Bronson\r\n*   Jukka Lehtosalo\r\n*   KotlinIsland\r\n*   Lakshay Bisht\r\n*   Lefteris Karapetsas\r\n*   Marc Mueller\r\n*   Matthew Hughes\r\n*   Michael Lee\r\n*   Nick Drozd\r\n*   Nikita Sobolev\r\n*   Richard Si\r\n*   Shantanu\r\n*   Stas Ilinskiy\r\n*   Tim Geypens\r\n*   Tin Tvrtković\r\n*   Tom Schraitle\r\n*   Valentin Stanciu\r\n*   Vincent Vanlaer\r\n\r\nWe’d also like to thank our employer, Dropbox, for funding the mypy core team.\r\n\r\nPosted by Stas Ilinskiy\r\n\r\n## Previous releases\r\n\r\nFor information about previous releases, refer to the posts at https://mypy-lang.blogspot.com/\r\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing to Mypy\n\nWelcome!  Mypy is a community project that aims to work for a wide\nrange of Python users and Python codebases.  If you're trying mypy on\nyour Python code, your experience and what you can contribute are\nimportant to the project's success.\n\n## Code of Conduct\n\nEveryone participating in the Mypy community, and in particular in our\nissue tracker, pull requests, and chat, is expected to treat\nother people with respect and more generally to follow the guidelines\narticulated in the [Python Community Code of Conduct](https://www.python.org/psf/codeofconduct/).\n\n## Getting started with development\n\n### Setup\n\n#### (1) Fork the mypy repository\n\nWithin GitHub, navigate to <https://github.com/python/mypy> and fork the repository.\n\n#### (2) Clone the mypy repository and enter into it\n\n```bash\ngit clone git@github.com:<your_username>/mypy.git\ncd mypy\n```\n\n#### (3) Create then activate a virtual environment\n\n```bash\npython3 -m venv venv\nsource venv/bin/activate\n```\n\n```bash\n# For Windows use\npython -m venv venv\n. venv/Scripts/activate\n\n# For more details, see https://docs.python.org/3/library/venv.html#creating-virtual-environments\n```\n\n#### (4) Install the test requirements and the project\n\n```bash\npython -m pip install -r test-requirements.txt\npython -m pip install -e .\nhash -r  # This resets shell PATH cache, not necessary on Windows\n```\n\n> **Note**\n> You'll need Python 3.10 or higher to install all requirements listed in\n> test-requirements.txt\n\n### Running tests\n\nRunning the full test suite can take a while, and usually isn't necessary when\npreparing a PR. Once you file a PR, the full test suite will run on GitHub.\nYou'll then be able to see any test failures, and make any necessary changes to\nyour PR.\n\nHowever, if you wish to do so, you can run the full test suite\nlike this:\n\n```bash\npython runtests.py\n```\n\nSome useful commands for running specific tests include:\n\n```bash\n# Use mypy to check mypy's own code\npython runtests.py self\n# or equivalently:\npython -m mypy --config-file mypy_self_check.ini -p mypy\n\n# Run a single test from the test suite (uses pytest substring expression matching)\npython runtests.py test_name\n# or equivalently:\npytest -n0 -k test_name\n\n# Run all test cases in the \"test-data/unit/check-dataclasses.test\" file\npython runtests.py check-dataclasses.test\n# or equivalently:\npytest mypy/test/testcheck.py::TypeCheckSuite::check-dataclasses.test\n\n# Run the formatters and linters\npython runtests.py lint\n```\n\nFor an in-depth guide on running and writing tests,\nsee [the README in the test-data directory](test-data/unit/README.md).\n\n#### Using `tox`\n\nYou can also use [`tox`](https://tox.wiki/en/latest/) to run tests and other commands.\n`tox` handles setting up test environments for you.\n\n```bash\n# Run tests\ntox run -e py\n\n# Run tests using some specific Python version\ntox run -e py311\n\n# Run a specific command\ntox run -e lint\n\n# Run a single test from the test suite\ntox run -e py -- -n0 -k 'test_name'\n\n# Run all test cases in the \"test-data/unit/check-dataclasses.test\" file using\n# Python 3.11 specifically\ntox run -e py311 -- mypy/test/testcheck.py::TypeCheckSuite::check-dataclasses.test\n\n# Set up a development environment with all the project libraries and run a command\ntox -e dev -- mypy --verbose test_case.py\ntox -e dev --override testenv:dev.allowlist_externals+=env -- env  # inspect the environment\n```\n\nIf you don't already have `tox` installed, you can use a virtual environment as\ndescribed above to install `tox` via `pip` (e.g., ``python -m pip install tox``).\n\n## First time contributors\n\nIf you're looking for things to help with, browse our [issue tracker](https://github.com/python/mypy/issues)!\n\nIn particular, look for:\n\n- [good first issues](https://github.com/python/mypy/labels/good-first-issue)\n- [good second issues](https://github.com/python/mypy/labels/good-second-issue)\n- [documentation issues](https://github.com/python/mypy/labels/documentation)\n\nYou do not need to ask for permission to work on any of these issues.\nJust fix the issue yourself, [try to add a unit test](#running-tests) and\n[open a pull request](#submitting-changes).\n\nTo get help fixing a specific issue, it's often best to comment on the issue\nitself. You're much more likely to get help if you provide details about what\nyou've tried and where you've looked (maintainers tend to help those who help\nthemselves). [gitter](https://gitter.im/python/typing) can also be a good place\nto ask for help.\n\nInteractive debuggers like `pdb` and `ipdb` are really useful for getting\nstarted with the mypy codebase. This is a\n[useful tutorial](https://realpython.com/python-debugging-pdb/).\n\nIt's also extremely easy to get started contributing to our sister project\n[typeshed](https://github.com/python/typeshed/issues) that provides type stubs\nfor libraries. This is a great way to become familiar with type syntax.\n\n## Submitting changes\n\nEven more excellent than a good bug report is a fix for a bug, or the\nimplementation of a much-needed new feature. We'd love to have\nyour contributions.\n\nWe use the usual GitHub pull-request flow, which may be familiar to\nyou if you've contributed to other projects on GitHub.  For the mechanics,\nsee [our git and GitHub workflow help page](https://github.com/python/mypy/wiki/Using-Git-And-GitHub),\nor [GitHub's own documentation](https://help.github.com/articles/using-pull-requests/).\n\nAnyone interested in Mypy may review your code.  One of the Mypy core\ndevelopers will merge your pull request when they think it's ready.\n\nIf your change will be a significant amount of work\nto write, we highly recommend starting by opening an issue laying out\nwhat you want to do.  That lets a conversation happen early in case\nother contributors disagree with what you'd like to do or have ideas\nthat will help you do it.\n\nThe best pull requests are focused, clearly describe what they're for\nand why they're correct, and contain tests for whatever changes they\nmake to the code's behavior.  As a bonus these are easiest for someone\nto review, which helps your pull request get merged quickly!  Standard\nadvice about good pull requests for open-source projects applies; we\nhave [our own writeup](https://github.com/python/mypy/wiki/Good-Pull-Request)\nof this advice.\n\nAlso, do not squash your commits after you have submitted a pull request, as this\nerases context during review. We will squash commits when the pull request is merged.\n\nYou may also find other pages in the\n[Mypy developer guide](https://github.com/python/mypy/wiki/Developer-Guides)\nhelpful in developing your change.\n\n## Core developer guidelines\n\nCore developers should follow these rules when processing pull requests:\n\n- Always wait for tests to pass before merging PRs.\n- Use \"[Squash and merge](https://github.com/blog/2141-squash-your-commits)\"\n  to merge PRs.\n- Delete branches for merged PRs (by core devs pushing to the main repo).\n- Edit the final commit message before merging to conform to the following\n  style (we wish to have a clean `git log` output):\n  - When merging a multi-commit PR make sure that the commit message doesn't\n    contain the local history from the committer and the review history from\n    the PR. Edit the message to only describe the end state of the PR.\n  - Make sure there is a *single* newline at the end of the commit message.\n    This way there is a single empty line between commits in `git log`\n    output.\n  - Split lines as needed so that the maximum line length of the commit\n    message is under 80 characters, including the subject line.\n  - Capitalize the subject and each paragraph.\n  - Make sure that the subject of the commit message has no trailing dot.\n  - Use the imperative mood in the subject line (e.g. \"Fix typo in README\").\n  - If the PR fixes an issue, make sure something like \"Fixes #xxx.\" occurs\n    in the body of the message (not in the subject).\n  - Use Markdown for formatting.\n"
  },
  {
    "path": "CREDITS",
    "content": "Credits\n-------\n\nFor a full list of contributors you can mine the commit history:\nhttps://github.com/python/mypy/commits/master\n\nFor lists of contributors per mypy release (including typeshed) see\nthe release blog posts at https://mypy-lang.blogspot.com/.\n\nDropbox core team:\n\n  Jukka Lehtosalo <jukka.lehtosalo@iki.fi>\n  Ivan Levkivskyi <levkivskyi@gmail.com>\n  Jared Hance\n\nNon-Dropbox core team members:\n\n  Emma Harper Smith <emma@python.org>\n  Guido van Rossum <guido@python.org>\n  Jelle Zijlstra <jelle.zijlstra@gmail.com>\n  Michael J. Sullivan <sully@msully.net>\n  Shantanu Jain\n  Xuanda Yang <th3charlie@gmail.com>\n  Jingchen Ye <97littleleaf11@gmail.com>\n  Nikita Sobolev <mail@sobolevn.me>\n\nPast Dropbox core team members:\n\n  David Fisher\n  Svyatoslav Ilinskiy\n  Greg Price\n  Naomi Seyfer\n  Michael Lee\n  Reid Barton\n\nAdditional thanks to:\n\n  Alex Allain\n  Max Bolingbroke\n  Peter Calvert\n  Kannan Goundan\n  Kathy Gray\n  David J Greaves\n  Riitta Ikonen\n  Terho Ikonen\n  Stephen Kell\n  Łukasz Langa\n  Laura Lehtosalo\n  Peter Ludemann\n  Seppo Mattila\n  Robin Message\n  Alan Mycroft\n  Dominic Orchard\n  Pekka Rapinoja\n  Matt Robben\n  Satnam Singh\n  Juha Sorva\n  Clay Sweetser\n  Jorma Tarhio\n  Jussi Tuovila\n  Andrey Vlasovskikh\n"
  },
  {
    "path": "LICENSE",
    "content": "Mypy (and mypyc) are licensed under the terms of the MIT license, reproduced below.\n\n= = = = =\n\nThe MIT License\n\nCopyright (c) 2012-2023 Jukka Lehtosalo and contributors\nCopyright (c) 2015-2023 Dropbox, Inc.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\n= = = = =\n\nPortions of mypy and mypyc are licensed under different licenses.\nThe files\nmypyc/lib-rt/pythonsupport.h, mypyc/lib-rt/getargs.c and\nmypyc/lib-rt/getargsfast.c are licensed under the PSF 2 License, reproduced\nbelow.\n\n= = = = =\n\nPYTHON SOFTWARE FOUNDATION LICENSE VERSION 2\n--------------------------------------------\n\n1. This LICENSE AGREEMENT is between the Python Software Foundation\n(\"PSF\"), and the Individual or Organization (\"Licensee\") accessing and\notherwise using this software (\"Python\") in source or binary form and\nits associated documentation.\n\n2. Subject to the terms and conditions of this License Agreement, PSF hereby\ngrants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,\nanalyze, test, perform and/or display publicly, prepare derivative works,\ndistribute, and otherwise use Python alone or in any derivative version,\nprovided, however, that PSF's License Agreement and PSF's notice of copyright,\ni.e., \"Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010,\n2011, 2012 Python Software Foundation; All Rights Reserved\" are retained in Python\nalone or in any derivative version prepared by Licensee.\n\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python.\n\n4. PSF is making Python available to Licensee on an \"AS IS\"\nbasis.  PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n\n5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\nFOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n\n7. Nothing in this License Agreement shall be deemed to create any\nrelationship of agency, partnership, or joint venture between PSF and\nLicensee.  This License Agreement does not grant permission to use PSF\ntrademarks or trade name in a trademark sense to endorse or promote\nproducts or services of Licensee, or any third party.\n\n8. By copying, installing or otherwise using Python, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\n\n\nBEOPEN.COM LICENSE AGREEMENT FOR PYTHON 2.0\n-------------------------------------------\n\nBEOPEN PYTHON OPEN SOURCE LICENSE AGREEMENT VERSION 1\n\n1. This LICENSE AGREEMENT is between BeOpen.com (\"BeOpen\"), having an\noffice at 160 Saratoga Avenue, Santa Clara, CA 95051, and the\nIndividual or Organization (\"Licensee\") accessing and otherwise using\nthis software in source or binary form and its associated\ndocumentation (\"the Software\").\n\n2. Subject to the terms and conditions of this BeOpen Python License\nAgreement, BeOpen hereby grants Licensee a non-exclusive,\nroyalty-free, world-wide license to reproduce, analyze, test, perform\nand/or display publicly, prepare derivative works, distribute, and\notherwise use the Software alone or in any derivative version,\nprovided, however, that the BeOpen Python License is retained in the\nSoftware, alone or in any derivative version prepared by Licensee.\n\n3. BeOpen is making the Software available to Licensee on an \"AS IS\"\nbasis.  BEOPEN MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, BEOPEN MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF THE SOFTWARE WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n\n4. BEOPEN SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF THE\nSOFTWARE FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS\nAS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE, OR ANY\nDERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n\n5. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n\n6. This License Agreement shall be governed by and interpreted in all\nrespects by the law of the State of California, excluding conflict of\nlaw provisions.  Nothing in this License Agreement shall be deemed to\ncreate any relationship of agency, partnership, or joint venture\nbetween BeOpen and Licensee.  This License Agreement does not grant\npermission to use BeOpen trademarks or trade names in a trademark\nsense to endorse or promote products or services of Licensee, or any\nthird party.  As an exception, the \"BeOpen Python\" logos available at\nhttp://www.pythonlabs.com/logos.html may be used according to the\npermissions granted on that web page.\n\n7. By copying, installing or otherwise using the software, Licensee\nagrees to be bound by the terms and conditions of this License\nAgreement.\n\n\nCNRI LICENSE AGREEMENT FOR PYTHON 1.6.1\n---------------------------------------\n\n1. This LICENSE AGREEMENT is between the Corporation for National\nResearch Initiatives, having an office at 1895 Preston White Drive,\nReston, VA 20191 (\"CNRI\"), and the Individual or Organization\n(\"Licensee\") accessing and otherwise using Python 1.6.1 software in\nsource or binary form and its associated documentation.\n\n2. Subject to the terms and conditions of this License Agreement, CNRI\nhereby grants Licensee a nonexclusive, royalty-free, world-wide\nlicense to reproduce, analyze, test, perform and/or display publicly,\nprepare derivative works, distribute, and otherwise use Python 1.6.1\nalone or in any derivative version, provided, however, that CNRI's\nLicense Agreement and CNRI's notice of copyright, i.e., \"Copyright (c)\n1995-2001 Corporation for National Research Initiatives; All Rights\nReserved\" are retained in Python 1.6.1 alone or in any derivative\nversion prepared by Licensee.  Alternately, in lieu of CNRI's License\nAgreement, Licensee may substitute the following text (omitting the\nquotes): \"Python 1.6.1 is made available subject to the terms and\nconditions in CNRI's License Agreement.  This Agreement together with\nPython 1.6.1 may be located on the Internet using the following\nunique, persistent identifier (known as a handle): 1895.22/1013.  This\nAgreement may also be obtained from a proxy server on the Internet\nusing the following URL: http://hdl.handle.net/1895.22/1013\".\n\n3. In the event Licensee prepares a derivative work that is based on\nor incorporates Python 1.6.1 or any part thereof, and wants to make\nthe derivative work available to others as provided herein, then\nLicensee hereby agrees to include in any such work a brief summary of\nthe changes made to Python 1.6.1.\n\n4. CNRI is making Python 1.6.1 available to Licensee on an \"AS IS\"\nbasis.  CNRI MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR\nIMPLIED.  BY WAY OF EXAMPLE, BUT NOT LIMITATION, CNRI MAKES NO AND\nDISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS\nFOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON 1.6.1 WILL NOT\nINFRINGE ANY THIRD PARTY RIGHTS.\n\n5. CNRI SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON\n1.6.1 FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS\nA RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON 1.6.1,\nOR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.\n\n6. This License Agreement will automatically terminate upon a material\nbreach of its terms and conditions.\n\n7. This License Agreement shall be governed by the federal\nintellectual property law of the United States, including without\nlimitation the federal copyright law, and, to the extent such\nU.S. federal law does not apply, by the law of the Commonwealth of\nVirginia, excluding Virginia's conflict of law provisions.\nNotwithstanding the foregoing, with regard to derivative works based\non Python 1.6.1 that incorporate non-separable material that was\npreviously distributed under the GNU General Public License (GPL), the\nlaw of the Commonwealth of Virginia shall govern this License\nAgreement only as to issues arising under or with respect to\nParagraphs 4, 5, and 7 of this License Agreement.  Nothing in this\nLicense Agreement shall be deemed to create any relationship of\nagency, partnership, or joint venture between CNRI and Licensee.  This\nLicense Agreement does not grant permission to use CNRI trademarks or\ntrade name in a trademark sense to endorse or promote products or\nservices of Licensee, or any third party.\n\n8. By clicking on the \"ACCEPT\" button where indicated, or by copying,\ninstalling or otherwise using Python 1.6.1, Licensee agrees to be\nbound by the terms and conditions of this License Agreement.\n\n        ACCEPT\n\n\nCWI LICENSE AGREEMENT FOR PYTHON 0.9.0 THROUGH 1.2\n--------------------------------------------------\n\nCopyright (c) 1991 - 1995, Stichting Mathematisch Centrum Amsterdam,\nThe Netherlands.  All rights reserved.\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for any purpose and without fee is hereby granted,\nprovided that the above copyright notice appear in all copies and that\nboth that copyright notice and this permission notice appear in\nsupporting documentation, and that the name of Stichting Mathematisch\nCentrum or CWI not be used in advertising or publicity pertaining to\ndistribution of the software without specific, written prior\npermission.\n\nSTICHTING MATHEMATISCH CENTRUM DISCLAIMS ALL WARRANTIES WITH REGARD TO\nTHIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\nFITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM BE LIABLE\nFOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\nWHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\nACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT\nOF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n\n= = = = =\n\nFiles under lib-rt/base64 are licensed under the following license.\n\n= = = = =\n\nCopyright (c) 2005-2007, Nick Galbreath\nCopyright (c) 2015-2018, Wojciech Muła\nCopyright (c) 2016-2017, Matthieu Darbois\nCopyright (c) 2013-2022, Alfred Klomp\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n- Redistributions of source code must retain the above copyright notice,\n  this list of conditions and the following disclaimer.\n\n- Redistributions in binary form must reproduce the above copyright\n  notice, this list of conditions and the following disclaimer in the\n  documentation and/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\nIS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\nTO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nHOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\nTO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\nPROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\nLIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\nNEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "MANIFEST.in",
    "content": "# some of the prunes here are so that check-manifest doesn't complain about their exclusion\n# as such, be judicious in your use of prune\n\n# stubs\nprune mypy/typeshed\ninclude mypy/typeshed/LICENSE\ninclude mypy/typeshed/stdlib/VERSIONS\nrecursive-include mypy/typeshed *.pyi\n\n# mypy and mypyc\ninclude mypy/py.typed\ninclude mypyc/py.typed\nrecursive-include mypy *.py\nrecursive-include mypyc *.py\n\n# random\ninclude mypy_bootstrap.ini\ngraft mypy/xml\ngraft scripts\n\n# docs\ngraft docs\nprune docs/build\nprune docs/source/_build\n\n# assorted mypyc requirements\ngraft mypyc/external\ngraft mypyc/lib-rt\ngraft mypyc/test\ngraft mypyc/test-data\ngraft mypyc/doc\nprune mypyc/doc/build\n\n# files necessary for testing sdist\ninclude mypy-requirements.txt\ninclude build-requirements.txt\ninclude test-requirements.in\ninclude test-requirements.txt\ninclude mypy_self_check.ini\nprune misc\ngraft test-data\ngraft mypy/test\ninclude conftest.py\ninclude runtests.py\ninclude tox.ini\n\ninclude LICENSE mypyc/README.md CHANGELOG.md\nexclude .gitmodules CONTRIBUTING.md CREDITS ROADMAP.md action.yml .editorconfig\nexclude .git-blame-ignore-revs .pre-commit-config.yaml\n\nglobal-exclude *.py[cod]\nglobal-exclude .DS_Store\n"
  },
  {
    "path": "README.md",
    "content": "<img src=\"docs/source/mypy_light.svg\" alt=\"mypy logo\" width=\"300px\"/>\n\nMypy: Static Typing for Python\n=======================================\n\n[![Stable Version](https://img.shields.io/pypi/v/mypy?color=blue)](https://pypi.org/project/mypy/)\n[![Downloads](https://img.shields.io/pypi/dm/mypy)](https://pypistats.org/packages/mypy)\n[![Build Status](https://github.com/python/mypy/actions/workflows/test.yml/badge.svg)](https://github.com/python/mypy/actions)\n[![Documentation Status](https://readthedocs.org/projects/mypy/badge/?version=latest)](https://mypy.readthedocs.io/en/latest/?badge=latest)\n[![Chat at https://gitter.im/python/typing](https://badges.gitter.im/python/typing.svg)](https://gitter.im/python/typing?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n[![Checked with mypy](https://www.mypy-lang.org/static/mypy_badge.svg)](https://mypy-lang.org/)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![Linting: Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/charliermarsh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n\nGot a question?\n---------------\n\nWe are always happy to answer questions! Here are some good places to ask them:\n\n- for general questions about Python typing, try [typing discussions](https://github.com/python/typing/discussions)\n- for anything you're curious about, try [gitter chat](https://gitter.im/python/typing)\n\nIf you're just getting started,\n[the documentation](https://mypy.readthedocs.io/en/stable/index.html)\nand [type hints cheat sheet](https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html)\ncan also help answer questions.\n\nIf you think you've found a bug:\n\n- check our [common issues page](https://mypy.readthedocs.io/en/stable/common_issues.html)\n- search our [issue tracker](https://github.com/python/mypy/issues) to see if\n  it's already been reported\n\nTo report a bug or request an enhancement:\n\n- report at [our issue tracker](https://github.com/python/mypy/issues)\n- if the issue is with a specific library or function, consider reporting it at\n  [typeshed tracker](https://github.com/python/typeshed/issues) or the issue\n  tracker for that library\n\nTo discuss a new type system feature:\n\n- discuss at [discuss.python.org](https://discuss.python.org/c/typing/32)\n- there is also some historical discussion at the [typing-sig mailing list](https://mail.python.org/archives/list/typing-sig@python.org/) and the [python/typing repo](https://github.com/python/typing/issues)\n\nWhat is mypy?\n-------------\n\nMypy is a static type checker for Python.\n\nType checkers help ensure that you're using variables and functions in your code\ncorrectly. With mypy, add type hints ([PEP 484](https://www.python.org/dev/peps/pep-0484/))\nto your Python programs, and mypy will warn you when you use those types\nincorrectly.\n\nPython is a dynamic language, so usually you'll only see errors in your code\nwhen you attempt to run it. Mypy is a *static* checker, so it finds bugs\nin your programs without even running them!\n\nHere is a small example to whet your appetite:\n\n```python\nnumber = input(\"What is your favourite number?\")\nprint(\"It is\", number + 1)  # error: Unsupported operand types for + (\"str\" and \"int\")\n```\n\nAdding type hints for mypy does not interfere with the way your program would\notherwise run. Think of type hints as similar to comments! You can always use\nthe Python interpreter to run your code, even if mypy reports errors.\n\nMypy is designed with gradual typing in mind. This means you can add type\nhints to your code base slowly and that you can always fall back to dynamic\ntyping when static typing is not convenient.\n\nMypy has a powerful and easy-to-use type system, supporting features such as\ntype inference, generics, callable types, tuple types, union types,\nstructural subtyping and more. Using mypy will make your programs easier to\nunderstand, debug, and maintain.\n\nSee [the documentation](https://mypy.readthedocs.io/en/stable/index.html) for\nmore examples and information.\n\nIn particular, see:\n\n- [type hints cheat sheet](https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html)\n- [getting started](https://mypy.readthedocs.io/en/stable/getting_started.html)\n- [list of error codes](https://mypy.readthedocs.io/en/stable/error_code_list.html)\n\nQuick start\n-----------\n\nMypy can be installed using pip:\n\n```bash\npython3 -m pip install -U mypy\n```\n\nIf you want to run the latest version of the code, you can install from the\nrepo directly:\n\n```bash\npython3 -m pip install -U git+https://github.com/python/mypy.git\n```\n\nNow you can type-check the [statically typed parts] of a program like this:\n\n```bash\nmypy PROGRAM\n```\n\nYou can always use the Python interpreter to run your statically typed\nprograms, even if mypy reports type errors:\n\n```bash\npython3 PROGRAM\n```\n\nIf you are working with large code bases, you can run mypy in\n[daemon mode], that will give much faster (often sub-second) incremental updates:\n\n```bash\ndmypy run -- PROGRAM\n```\n\nYou can also try mypy in an [online playground](https://mypy-play.net/) (developed by\nYusuke Miyazaki).\n\n[statically typed parts]: https://mypy.readthedocs.io/en/latest/getting_started.html#function-signatures-and-dynamic-vs-static-typing\n[daemon mode]: https://mypy.readthedocs.io/en/stable/mypy_daemon.html\n\nIntegrations\n------------\n\nMypy can be integrated into popular IDEs:\n\n- VS Code: provides [basic integration](https://code.visualstudio.com/docs/python/linting#_mypy) with mypy.\n- Vim:\n  - Using [Syntastic](https://github.com/vim-syntastic/syntastic): in `~/.vimrc` add\n    `let g:syntastic_python_checkers=['mypy']`\n  - Using [ALE](https://github.com/dense-analysis/ale): should be enabled by default when `mypy` is installed,\n    or can be explicitly enabled by adding `let b:ale_linters = ['mypy']` in `~/vim/ftplugin/python.vim`\n- Emacs: using [Flycheck](https://github.com/flycheck/)\n- Sublime Text: [SublimeLinter-contrib-mypy](https://github.com/fredcallaway/SublimeLinter-contrib-mypy)\n- PyCharm: [mypy plugin](https://github.com/dropbox/mypy-PyCharm-plugin)\n- IDLE: [idlemypyextension](https://github.com/CoolCat467/idlemypyextension)\n- pre-commit: use [pre-commit mirrors-mypy](https://github.com/pre-commit/mirrors-mypy), although\n  note by default this will limit mypy's ability to analyse your third party dependencies.\n\nWeb site and documentation\n--------------------------\n\nAdditional information is available at the web site:\n\n  <https://www.mypy-lang.org/>\n\nJump straight to the documentation:\n\n  <https://mypy.readthedocs.io/>\n\nFollow along our changelog at:\n\n  <https://mypy-lang.blogspot.com/>\n\nContributing\n------------\n\nHelp in testing, development, documentation and other tasks is\nhighly appreciated and useful to the project. There are tasks for\ncontributors of all experience levels.\n\nTo get started with developing mypy, see [CONTRIBUTING.md](CONTRIBUTING.md).\n\nMypyc and compiled version of mypy\n----------------------------------\n\n[Mypyc](https://github.com/mypyc/mypyc) uses Python type hints to compile Python\nmodules to faster C extensions. Mypy is itself compiled using mypyc: this makes\nmypy approximately 4 times faster than if interpreted!\n\nTo install an interpreted mypy instead, use:\n\n```bash\npython3 -m pip install --no-binary mypy -U mypy\n```\n\nTo use a compiled version of a development\nversion of mypy, directly install a binary from\n<https://github.com/mypyc/mypy_mypyc-wheels/releases/latest>.\n\nTo contribute to the mypyc project, check out the issue tracker at <https://github.com/mypyc/mypyc>\n"
  },
  {
    "path": "action.yml",
    "content": "name: \"Mypy\"\ndescription: \"Optional Static Typing for Python.\"\nauthor: \"Jukka Lehtosalo and contributors\"\ninputs:\n  options:\n    description: >\n      Options passed to mypy. Use `mypy --help` to see available options.\n    required: false\n  paths:\n    description: >\n      Explicit paths to run mypy on. Defaults to the current directory.\n    required: false\n    default: \".\"\n  version:\n    description: >\n      Mypy version to use (PEP440) - e.g. \"0.910\"\n    required: false\n    default: \"\"\n  install_types:\n    description: >\n      Whether to automatically install missing library stub packages.\n      ('yes'|'no', default: 'yes')\n    default: \"yes\"\n  install_project_dependencies:\n    description: >\n      Whether to attempt to install project dependencies into mypy\n      environment. ('yes'|'no', default: 'yes')\n    default: \"yes\"\nbranding:\n  color: \"blue\"\n  icon: \"check-circle\"\nruns:\n  using: composite\n  steps:\n    - name: mypy setup  # zizmor: ignore[template-injection]\n      shell: bash\n      run: |\n        echo ::group::Installing mypy...\n        export PIP_DISABLE_PIP_VERSION_CHECK=1\n\n        if [ \"$RUNNER_OS\" == \"Windows\" ]; then\n          HOST_PYTHON=python\n        else\n          HOST_PYTHON=python3\n        fi\n\n        venv_script=\"import os.path; import venv; import sys;\n        path = os.path.join(r'${{ github.action_path }}', '.mypy-venv');\n        venv.main([path]);\n        bin_subdir = 'Scripts' if sys.platform == 'win32' else 'bin';\n        print(os.path.join(path, bin_subdir, 'python'));\n        \"\n\n        VENV_PYTHON=$(echo $venv_script | \"$HOST_PYTHON\")\n        mypy_spec=\"mypy\"\n\n        if [ -n \"${{ inputs.version }}\" ]; then\n          mypy_spec+=\"==${{ inputs.version }}\"\n        fi\n\n        if ! \"$VENV_PYTHON\" -m pip install \"$mypy_spec\"; then\n          echo \"::error::Could not install mypy.\"\n          exit 1\n        fi\n        echo ::endgroup::\n\n        if [ \"${{ inputs.install_project_dependencies }}\" == \"yes\" ]; then\n          VENV=$(\"$VENV_PYTHON\" -c 'import sys;print(sys.prefix)')\n          echo ::group::Installing project dependencies...\n          \"$VENV_PYTHON\" -m pip download --dest=\"$VENV\"/deps .\n          \"$VENV_PYTHON\" -m pip install -U --find-links=\"$VENV\"/deps \"$VENV\"/deps/*\n          echo ::endgroup::\n        fi\n\n        echo ::group::Running mypy...\n        mypy_opts=\"\"\n        if [ \"${{ inputs.install_types }}\" == \"yes\" ]; then\n          mypy_opts+=\"--install-types --non-interactive\"\n        fi\n\n        echo \"mypy $mypy_opts ${{ inputs.options }} ${{ inputs.paths }}\"\n        \"$VENV_PYTHON\" -m mypy $mypy_opts ${{ inputs.options }} ${{ inputs.paths }}\n        echo ::endgroup::\n"
  },
  {
    "path": "build-requirements.txt",
    "content": "# NOTE: this needs to be kept in sync with the \"requires\" list in pyproject.toml\n-r mypy-requirements.txt\ntypes-psutil\ntypes-setuptools\n"
  },
  {
    "path": "conftest.py",
    "content": "from __future__ import annotations\n\nimport os.path\n\npytest_plugins = [\"mypy.test.data\"]\n\n\ndef pytest_configure(config):\n    mypy_source_root = os.path.dirname(os.path.abspath(__file__))\n    if os.getcwd() != mypy_source_root:\n        os.chdir(mypy_source_root)\n\n\n# This function name is special to pytest.  See\n# https://doc.pytest.org/en/latest/how-to/writing_plugins.html#initialization-command-line-and-configuration-hooks\ndef pytest_addoption(parser) -> None:\n    parser.addoption(\n        \"--bench\", action=\"store_true\", default=False, help=\"Enable the benchmark test runs\"\n    )\n"
  },
  {
    "path": "docs/Makefile",
    "content": "# Makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line.\nSPHINXOPTS    =\nSPHINXBUILD   = sphinx-build\nPAPER         =\nBUILDDIR      = build\n\n# User-friendly check for sphinx-build\nifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)\n$(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from https://www.sphinx-doc.org/)\nendif\n\n# Internal variables.\nPAPEROPT_a4     = -D latex_paper_size=a4\nPAPEROPT_letter = -D latex_paper_size=letter\nALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source\n# the i18n builder cannot share the environment and doctrees with the others\nI18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source\n\n.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext\n\nhelp:\n\t@echo \"Please use \\`make <target>' where <target> is one of\"\n\t@echo \"  html       to make standalone HTML files\"\n\t@echo \"  dirhtml    to make HTML files named index.html in directories\"\n\t@echo \"  singlehtml to make a single large HTML file\"\n\t@echo \"  pickle     to make pickle files\"\n\t@echo \"  json       to make JSON files\"\n\t@echo \"  htmlhelp   to make HTML files and a HTML help project\"\n\t@echo \"  qthelp     to make HTML files and a qthelp project\"\n\t@echo \"  devhelp    to make HTML files and a Devhelp project\"\n\t@echo \"  epub       to make an epub\"\n\t@echo \"  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter\"\n\t@echo \"  latexpdf   to make LaTeX files and run them through pdflatex\"\n\t@echo \"  latexpdfja to make LaTeX files and run them through platex/dvipdfmx\"\n\t@echo \"  text       to make text files\"\n\t@echo \"  man        to make manual pages\"\n\t@echo \"  texinfo    to make Texinfo files\"\n\t@echo \"  info       to make Texinfo files and run them through makeinfo\"\n\t@echo \"  gettext    to make PO message catalogs\"\n\t@echo \"  changes    to make an overview of all changed/added/deprecated items\"\n\t@echo \"  xml        to make Docutils-native XML files\"\n\t@echo \"  pseudoxml  to make pseudoxml-XML files for display purposes\"\n\t@echo \"  linkcheck  to check all external links for integrity\"\n\t@echo \"  doctest    to run all doctests embedded in the documentation (if enabled)\"\n\nclean:\n\trm -rf $(BUILDDIR)/*\n\nhtml:\n\t$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/html.\"\n\ndirhtml:\n\t$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml\n\t@echo\n\t@echo \"Build finished. The HTML pages are in $(BUILDDIR)/dirhtml.\"\n\nsinglehtml:\n\t$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml\n\t@echo\n\t@echo \"Build finished. The HTML page is in $(BUILDDIR)/singlehtml.\"\n\npickle:\n\t$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle\n\t@echo\n\t@echo \"Build finished; now you can process the pickle files.\"\n\njson:\n\t$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json\n\t@echo\n\t@echo \"Build finished; now you can process the JSON files.\"\n\nhtmlhelp:\n\t$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp\n\t@echo\n\t@echo \"Build finished; now you can run HTML Help Workshop with the\" \\\n\t      \".hhp project file in $(BUILDDIR)/htmlhelp.\"\n\nqthelp:\n\t$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp\n\t@echo\n\t@echo \"Build finished; now you can run \"qcollectiongenerator\" with the\" \\\n\t      \".qhcp project file in $(BUILDDIR)/qthelp, like this:\"\n\t@echo \"# qcollectiongenerator $(BUILDDIR)/qthelp/Mypy.qhcp\"\n\t@echo \"To view the help file:\"\n\t@echo \"# assistant -collectionFile $(BUILDDIR)/qthelp/Mypy.qhc\"\n\ndevhelp:\n\t$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp\n\t@echo\n\t@echo \"Build finished.\"\n\t@echo \"To view the help file:\"\n\t@echo \"# mkdir -p $$HOME/.local/share/devhelp/Mypy\"\n\t@echo \"# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Mypy\"\n\t@echo \"# devhelp\"\n\nepub:\n\t$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub\n\t@echo\n\t@echo \"Build finished. The epub file is in $(BUILDDIR)/epub.\"\n\nlatex:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo\n\t@echo \"Build finished; the LaTeX files are in $(BUILDDIR)/latex.\"\n\t@echo \"Run \\`make' in that directory to run these through (pdf)latex\" \\\n\t      \"(use \\`make latexpdf' here to do that automatically).\"\n\nlatexpdf:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through pdflatex...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\nlatexpdfja:\n\t$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex\n\t@echo \"Running LaTeX files through platex and dvipdfmx...\"\n\t$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja\n\t@echo \"pdflatex finished; the PDF files are in $(BUILDDIR)/latex.\"\n\ntext:\n\t$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text\n\t@echo\n\t@echo \"Build finished. The text files are in $(BUILDDIR)/text.\"\n\nman:\n\t$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man\n\t@echo\n\t@echo \"Build finished. The manual pages are in $(BUILDDIR)/man.\"\n\ntexinfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo\n\t@echo \"Build finished. The Texinfo files are in $(BUILDDIR)/texinfo.\"\n\t@echo \"Run \\`make' in that directory to run these through makeinfo\" \\\n\t      \"(use \\`make info' here to do that automatically).\"\n\ninfo:\n\t$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo\n\t@echo \"Running Texinfo files through makeinfo...\"\n\tmake -C $(BUILDDIR)/texinfo info\n\t@echo \"makeinfo finished; the Info files are in $(BUILDDIR)/texinfo.\"\n\ngettext:\n\t$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale\n\t@echo\n\t@echo \"Build finished. The message catalogs are in $(BUILDDIR)/locale.\"\n\nchanges:\n\t$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes\n\t@echo\n\t@echo \"The overview file is in $(BUILDDIR)/changes.\"\n\nlinkcheck:\n\t$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck\n\t@echo\n\t@echo \"Link check complete; look for any errors in the above output \" \\\n\t      \"or in $(BUILDDIR)/linkcheck/output.txt.\"\n\ndoctest:\n\t$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest\n\t@echo \"Testing of doctests in the sources finished, look at the \" \\\n\t      \"results in $(BUILDDIR)/doctest/output.txt.\"\n\nxml:\n\t$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml\n\t@echo\n\t@echo \"Build finished. The XML files are in $(BUILDDIR)/xml.\"\n\npseudoxml:\n\t$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml\n\t@echo\n\t@echo \"Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml.\"\n"
  },
  {
    "path": "docs/README.md",
    "content": "Mypy Documentation\n==================\n\nWhat's this?\n------------\n\nThis directory contains the source code for Mypy documentation (under `source/`)\nand build scripts. The documentation uses Sphinx and reStructuredText. We use\n`furo` as the documentation theme.\n\nBuilding the documentation\n--------------------------\n\nInstall Sphinx and other dependencies (i.e. theme) needed for the documentation.\nFrom the `docs` directory, use `pip`:\n\n```\npip install -r requirements-docs.txt\n```\n\nBuild the documentation like this:\n\n```\nmake html\n```\n\nThe built documentation will be placed in the `docs/build` directory. Open\n`docs/build/index.html` to view the documentation.\n\nHelpful documentation build commands\n------------------------------------\n\nClean the documentation build:\n\n```\nmake clean\n```\n\nTest and check the links found in the documentation:\n\n```\nmake linkcheck\n```\n\nDocumentation on Read The Docs\n------------------------------\n\nThe mypy documentation is hosted on Read The Docs, and the latest version\ncan be found at https://mypy.readthedocs.io/en/latest.\n"
  },
  {
    "path": "docs/make.bat",
    "content": "@ECHO OFF\r\n\r\nREM Command file for Sphinx documentation\r\n\r\nif \"%SPHINXBUILD%\" == \"\" (\r\n\tset SPHINXBUILD=sphinx-build\r\n)\r\nset BUILDDIR=build\r\nset ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% source\r\nset I18NSPHINXOPTS=%SPHINXOPTS% source\r\nif NOT \"%PAPER%\" == \"\" (\r\n\tset ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%\r\n\tset I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%\r\n)\r\n\r\nif \"%1\" == \"\" goto help\r\n\r\nif \"%1\" == \"help\" (\r\n\t:help\r\n\techo.Please use `make ^<target^>` where ^<target^> is one of\r\n\techo.  html       to make standalone HTML files\r\n\techo.  dirhtml    to make HTML files named index.html in directories\r\n\techo.  singlehtml to make a single large HTML file\r\n\techo.  pickle     to make pickle files\r\n\techo.  json       to make JSON files\r\n\techo.  htmlhelp   to make HTML files and a HTML help project\r\n\techo.  qthelp     to make HTML files and a qthelp project\r\n\techo.  devhelp    to make HTML files and a Devhelp project\r\n\techo.  epub       to make an epub\r\n\techo.  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter\r\n\techo.  text       to make text files\r\n\techo.  man        to make manual pages\r\n\techo.  texinfo    to make Texinfo files\r\n\techo.  gettext    to make PO message catalogs\r\n\techo.  changes    to make an overview over all changed/added/deprecated items\r\n\techo.  xml        to make Docutils-native XML files\r\n\techo.  pseudoxml  to make pseudoxml-XML files for display purposes\r\n\techo.  linkcheck  to check all external links for integrity\r\n\techo.  doctest    to run all doctests embedded in the documentation if enabled\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"clean\" (\r\n\tfor /d %%i in (%BUILDDIR%\\*) do rmdir /q /s %%i\r\n\tdel /q /s %BUILDDIR%\\*\r\n\tgoto end\r\n)\r\n\r\n\r\n%SPHINXBUILD% 2> nul\r\nif errorlevel 9009 (\r\n\techo.\r\n\techo.The 'sphinx-build' command was not found. Make sure you have Sphinx\r\n\techo.installed, then set the SPHINXBUILD environment variable to point\r\n\techo.to the full path of the 'sphinx-build' executable. Alternatively you\r\n\techo.may add the Sphinx directory to PATH.\r\n\techo.\r\n\techo.If you don't have Sphinx installed, grab it from\r\n\techo.https://www.sphinx-doc.org/\r\n\texit /b 1\r\n)\r\n\r\nif \"%1\" == \"html\" (\r\n\t%SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The HTML pages are in %BUILDDIR%/html.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"dirhtml\" (\r\n\t%SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"singlehtml\" (\r\n\t%SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"pickle\" (\r\n\t%SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished; now you can process the pickle files.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"json\" (\r\n\t%SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished; now you can process the JSON files.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"htmlhelp\" (\r\n\t%SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished; now you can run HTML Help Workshop with the ^\r\n.hhp project file in %BUILDDIR%/htmlhelp.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"qthelp\" (\r\n\t%SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished; now you can run \"qcollectiongenerator\" with the ^\r\n.qhcp project file in %BUILDDIR%/qthelp, like this:\r\n\techo.^> qcollectiongenerator %BUILDDIR%\\qthelp\\Mypy.qhcp\r\n\techo.To view the help file:\r\n\techo.^> assistant -collectionFile %BUILDDIR%\\qthelp\\Mypy.ghc\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"devhelp\" (\r\n\t%SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"epub\" (\r\n\t%SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The epub file is in %BUILDDIR%/epub.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"latex\" (\r\n\t%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished; the LaTeX files are in %BUILDDIR%/latex.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"latexpdf\" (\r\n\t%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex\r\n\tcd %BUILDDIR%/latex\r\n\tmake all-pdf\r\n\tcd %BUILDDIR%/..\r\n\techo.\r\n\techo.Build finished; the PDF files are in %BUILDDIR%/latex.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"latexpdfja\" (\r\n\t%SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex\r\n\tcd %BUILDDIR%/latex\r\n\tmake all-pdf-ja\r\n\tcd %BUILDDIR%/..\r\n\techo.\r\n\techo.Build finished; the PDF files are in %BUILDDIR%/latex.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"text\" (\r\n\t%SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The text files are in %BUILDDIR%/text.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"man\" (\r\n\t%SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The manual pages are in %BUILDDIR%/man.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"texinfo\" (\r\n\t%SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"gettext\" (\r\n\t%SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The message catalogs are in %BUILDDIR%/locale.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"changes\" (\r\n\t%SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.The overview file is in %BUILDDIR%/changes.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"linkcheck\" (\r\n\t%SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Link check complete; look for any errors in the above output ^\r\nor in %BUILDDIR%/linkcheck/output.txt.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"doctest\" (\r\n\t%SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Testing of doctests in the sources finished, look at the ^\r\nresults in %BUILDDIR%/doctest/output.txt.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"xml\" (\r\n\t%SPHINXBUILD% -b xml %ALLSPHINXOPTS% %BUILDDIR%/xml\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The XML files are in %BUILDDIR%/xml.\r\n\tgoto end\r\n)\r\n\r\nif \"%1\" == \"pseudoxml\" (\r\n\t%SPHINXBUILD% -b pseudoxml %ALLSPHINXOPTS% %BUILDDIR%/pseudoxml\r\n\tif errorlevel 1 exit /b 1\r\n\techo.\r\n\techo.Build finished. The pseudo-XML files are in %BUILDDIR%/pseudoxml.\r\n\tgoto end\r\n)\r\n\r\n:end\r\n"
  },
  {
    "path": "docs/requirements-docs.txt",
    "content": "-r ../mypy-requirements.txt\nsphinx>=8.1.0\nfuro>=2022.3.4\nmyst-parser>=4.0.0\nsphinx_inline_tabs>=2023.04.21\n"
  },
  {
    "path": "docs/source/additional_features.rst",
    "content": "Additional features\n-------------------\n\nThis section discusses various features that did not fit in naturally in one\nof the previous sections.\n\n.. _dataclasses_support:\n\nDataclasses\n***********\n\nThe :py:mod:`dataclasses` module allows defining and customizing simple\nboilerplate-free classes. They can be defined using the\n:py:func:`@dataclasses.dataclass <python:dataclasses.dataclass>` decorator:\n\n.. code-block:: python\n\n    from dataclasses import dataclass, field\n\n    @dataclass\n    class Application:\n        name: str\n        plugins: list[str] = field(default_factory=list)\n\n    test = Application(\"Testing...\")  # OK\n    bad = Application(\"Testing...\", \"with plugin\")  # Error: list[str] expected\n\nMypy will detect special methods (such as :py:meth:`__lt__ <object.__lt__>`) depending on the flags used to\ndefine dataclasses. For example:\n\n.. code-block:: python\n\n    from dataclasses import dataclass\n\n    @dataclass(order=True)\n    class OrderedPoint:\n        x: int\n        y: int\n\n    @dataclass(order=False)\n    class UnorderedPoint:\n        x: int\n        y: int\n\n    OrderedPoint(1, 2) < OrderedPoint(3, 4)  # OK\n    UnorderedPoint(1, 2) < UnorderedPoint(3, 4)  # Error: Unsupported operand types\n\nDataclasses can be generic and can be used in any other way a normal\nclass can be used (Python 3.12 syntax):\n\n.. code-block:: python\n\n    from dataclasses import dataclass\n\n    @dataclass\n    class BoxedData[T]:\n        data: T\n        label: str\n\n    def unbox[T](bd: BoxedData[T]) -> T:\n        ...\n\n    val = unbox(BoxedData(42, \"<important>\"))  # OK, inferred type is int\n\nFor more information see :doc:`official docs <python:library/dataclasses>`\nand :pep:`557`.\n\nCaveats/Known Issues\n====================\n\nSome functions in the :py:mod:`dataclasses` module, such as :py:func:`~dataclasses.asdict`,\nhave imprecise (too permissive) types. This will be fixed in future releases.\n\nMypy does not yet recognize aliases of :py:func:`dataclasses.dataclass <dataclasses.dataclass>`, and will\nprobably never recognize dynamically computed decorators. The following example\ndoes **not** work:\n\n.. code-block:: python\n\n    from dataclasses import dataclass\n\n    dataclass_alias = dataclass\n    def dataclass_wrapper(cls):\n      return dataclass(cls)\n\n    @dataclass_alias\n    class AliasDecorated:\n      \"\"\"\n      Mypy doesn't recognize this as a dataclass because it is decorated by an\n      alias of `dataclass` rather than by `dataclass` itself.\n      \"\"\"\n      attribute: int\n\n    AliasDecorated(attribute=1) # error: Unexpected keyword argument\n\n\nTo have Mypy recognize a wrapper of :py:func:`dataclasses.dataclass <dataclasses.dataclass>`\nas a dataclass decorator, consider using the :py:func:`~typing.dataclass_transform`\ndecorator (example uses Python 3.12 syntax):\n\n.. code-block:: python\n\n    from dataclasses import dataclass, Field\n    from typing import dataclass_transform\n\n    @dataclass_transform(field_specifiers=(Field,))\n    def my_dataclass[T](cls: type[T]) -> type[T]:\n        ...\n        return dataclass(cls)\n\n\nData Class Transforms\n*********************\n\nMypy supports the :py:func:`~typing.dataclass_transform` decorator as described in\n`PEP 681 <https://www.python.org/dev/peps/pep-0681/#the-dataclass-transform-decorator>`_.\n\n.. note::\n\n    Pragmatically, mypy will assume such classes have the internal attribute :code:`__dataclass_fields__`\n    (even though they might lack it in runtime) and will assume functions such as :py:func:`dataclasses.is_dataclass`\n    and :py:func:`dataclasses.fields` treat them as if they were dataclasses\n    (even though they may fail at runtime).\n\n.. _attrs_package:\n\nThe attrs package\n*****************\n\n:doc:`attrs <attrs:index>` is a package that lets you define\nclasses without writing boilerplate code. Mypy can detect uses of the\npackage and will generate the necessary method definitions for decorated\nclasses using the type annotations it finds.\nType annotations can be added as follows:\n\n.. code-block:: python\n\n    import attrs\n\n    @attrs.define\n    class A:\n        one: int\n        two: int = 7\n        three: int = attrs.field(8)\n\nIf you're using ``auto_attribs=False`` you must use ``attrs.field``:\n\n.. code-block:: python\n\n    import attrs\n\n    @attrs.define\n    class A:\n        one: int = attrs.field()          # Variable annotation (Python 3.6+)\n        two = attrs.field()  # type: int  # Type comment\n        three = attrs.field(type=int)     # type= argument\n\nTypeshed has a couple of \"white lie\" annotations to make type checking\neasier. :py:func:`attrs.field` and :py:class:`attrs.Factory` actually return objects, but the\nannotation says these return the types that they expect to be assigned to.\nThat enables this to work:\n\n.. code-block:: python\n\n    import attrs\n\n    @attrs.define\n    class A:\n        one: int = attrs.field(8)\n        two: dict[str, str] = attrs.Factory(dict)\n        bad: str = attrs.field(16)   # Error: can't assign int to str\n\nCaveats/Known Issues\n====================\n\n* The detection of attr classes and attributes works by function name only.\n  This means that if you have your own helper functions that, for example,\n  ``return attrs.field()`` mypy will not see them.\n\n* All boolean arguments that mypy cares about must be literal ``True`` or ``False``.\n  e.g the following will not work:\n\n  .. code-block:: python\n\n      import attrs\n      YES = True\n      @attrs.define(init=YES)\n      class A:\n          ...\n\n* Currently, ``converter`` only supports named functions.  If mypy finds something else it\n  will complain about not understanding the argument and the type annotation in\n  :py:meth:`__init__ <object.__init__>` will be replaced by ``Any``.\n\n* :ref:`Validator decorators <attrs:examples-validators>`\n  and `default decorators <https://www.attrs.org/en/stable/examples.html#defaults>`_\n  are not type-checked against the attribute they are setting/validating.\n\n* Method definitions added by mypy currently overwrite any existing method\n  definitions.\n\n.. _remote-cache:\n\nUsing a remote cache to speed up mypy runs\n******************************************\n\nMypy performs type checking *incrementally*, reusing results from\nprevious runs to speed up successive runs. If you are type checking a\nlarge codebase, mypy can still be sometimes slower than desirable. For\nexample, if you create a new branch based on a much more recent commit\nthan the target of the previous mypy run, mypy may have to\nprocess almost every file, as a large fraction of source files may\nhave changed. This can also happen after you've rebased a local\nbranch.\n\nMypy supports using a *remote cache* to improve performance in cases\nsuch as the above.  In a large codebase, remote caching can sometimes\nspeed up mypy runs by a factor of 10, or more.\n\nMypy doesn't include all components needed to set\nthis up -- generally you will have to perform some simple integration\nwith your Continuous Integration (CI) or build system to configure\nmypy to use a remote cache. This discussion assumes you have a CI\nsystem set up for the mypy build you want to speed up, and that you\nare using a central git repository. Generalizing to different\nenvironments should not be difficult.\n\nHere are the main components needed:\n\n* A shared repository for storing mypy cache files for all landed commits.\n\n* CI build that uploads mypy incremental cache files to the shared repository for\n  each commit for which the CI build runs.\n\n* A wrapper script around mypy that developers use to run mypy with remote\n  caching enabled.\n\nBelow we discuss each of these components in some detail.\n\nShared repository for cache files\n=================================\n\nYou need a repository that allows you to upload mypy cache files from\nyour CI build and make the cache files available for download based on\na commit id.  A simple approach would be to produce an archive of the\n``.mypy_cache`` directory (which contains the mypy cache data) as a\ndownloadable *build artifact* from your CI build (depending on the\ncapabilities of your CI system).  Alternatively, you could upload the\ndata to a web server or to S3, for example.\n\nContinuous Integration build\n============================\n\nThe CI build would run a regular mypy build and create an archive containing\nthe ``.mypy_cache`` directory produced by the build. Finally, it will produce\nthe cache as a build artifact or upload it to a repository where it is\naccessible by the mypy wrapper script.\n\nYour CI script might work like this:\n\n* Run mypy normally. This will generate cache data under the\n  ``.mypy_cache`` directory.\n\n* Create a tarball from the ``.mypy_cache`` directory.\n\n* Determine the current git master branch commit id (say, using\n  ``git rev-parse HEAD``).\n\n* Upload the tarball to the shared repository with a name derived from the\n  commit id.\n\nMypy wrapper script\n===================\n\nThe wrapper script is used by developers to run mypy locally during\ndevelopment instead of invoking mypy directly.  The wrapper first\npopulates the local ``.mypy_cache`` directory from the shared\nrepository and then runs a normal incremental build.\n\nThe wrapper script needs some logic to determine the most recent\ncentral repository commit (by convention, the ``origin/master`` branch\nfor git) the local development branch is based on. In a typical git\nsetup you can do it like this:\n\n.. code::\n\n    git merge-base HEAD origin/master\n\nThe next step is to download the cache data (contents of the\n``.mypy_cache`` directory) from the shared repository based on the\ncommit id of the merge base produced by the git command above. The\nscript will decompress the data so that mypy will start with a fresh\n``.mypy_cache``. Finally, the script runs mypy normally. And that's all!\n\nCaching with mypy daemon\n========================\n\nYou can also use remote caching with the :ref:`mypy daemon <mypy_daemon>`.\nThe remote cache will significantly speed up the first ``dmypy check``\nrun after starting or restarting the daemon.\n\nThe mypy daemon requires extra fine-grained dependency data in\nthe cache files which aren't included by default. To use caching with\nthe mypy daemon, use the :option:`--cache-fine-grained <mypy --cache-fine-grained>` option in your CI\nbuild::\n\n    $ mypy --cache-fine-grained <args...>\n\nThis flag adds extra information for the daemon to the cache. In\norder to use this extra information, you will also need to use the\n``--use-fine-grained-cache`` option with ``dmypy start`` or\n``dmypy restart``. Example::\n\n    $ dmypy start -- --use-fine-grained-cache <options...>\n\nNow your first ``dmypy check`` run should be much faster, as it can use\ncache information to avoid processing the whole program.\n\nRefinements\n===========\n\nThere are several optional refinements that may improve things further,\nat least if your codebase is hundreds of thousands of lines or more:\n\n* If the wrapper script determines that the merge base hasn't changed\n  from a previous run, there's no need to download the cache data and\n  it's better to instead reuse the existing local cache data.\n\n* If you use the mypy daemon, you may want to restart the daemon each time\n  after the merge base or local branch has changed to avoid processing a\n  potentially large number of changes in an incremental build, as this can\n  be much slower than downloading cache data and restarting the daemon.\n\n* If the current local branch is based on a very recent master commit,\n  the remote cache data may not yet be available for that commit, as\n  there will necessarily be some latency to build the cache files. It\n  may be a good idea to look for cache data for, say, the 5 latest\n  master commits and use the most recent data that is available.\n\n* If the remote cache is not accessible for some reason (say, from a public\n  network), the script can still fall back to a normal incremental build.\n\n* You can have multiple local cache directories for different local branches\n  using the :option:`--cache-dir <mypy --cache-dir>` option. If the user switches to an existing\n  branch where downloaded cache data is already available, you can continue\n  to use the existing cache data instead of redownloading the data.\n\n* You can set up your CI build to use a remote cache to speed up the\n  CI build. This would be particularly useful if each CI build starts\n  from a fresh state without access to cache files from previous\n  builds. It's still recommended to run a full, non-incremental\n  mypy build to create the cache data, as repeatedly updating cache\n  data incrementally could result in drift over a long time period (due\n  to a mypy caching issue, perhaps).\n\n.. _extended_callable:\n\nExtended Callable types\n***********************\n\n.. note::\n\n   This feature is deprecated.  You can use\n   :ref:`callback protocols <callback_protocols>` as a replacement.\n\nAs an experimental mypy extension, you can specify :py:class:`~collections.abc.Callable` types\nthat support keyword arguments, optional arguments, and more.  When\nyou specify the arguments of a :py:class:`~collections.abc.Callable`, you can choose to supply just\nthe type of a nameless positional argument, or an \"argument specifier\"\nrepresenting a more complicated form of argument.  This allows one to\nmore closely emulate the full range of possibilities given by the\n``def`` statement in Python.\n\nAs an example, here's a complicated function definition and the\ncorresponding :py:class:`~collections.abc.Callable`:\n\n.. code-block:: python\n\n   from collections.abc import Callable\n   from mypy_extensions import (Arg, DefaultArg, NamedArg,\n                                DefaultNamedArg, VarArg, KwArg)\n\n   def func(__a: int,  # This convention is for nameless arguments\n            b: int,\n            c: int = 0,\n            *args: int,\n            d: int,\n            e: int = 0,\n            **kwargs: int) -> int:\n       ...\n\n   F = Callable[[int,  # Or Arg(int)\n                 Arg(int, 'b'),\n                 DefaultArg(int, 'c'),\n                 VarArg(int),\n                 NamedArg(int, 'd'),\n                 DefaultNamedArg(int, 'e'),\n                 KwArg(int)],\n                int]\n\n   f: F = func\n\nArgument specifiers are special function calls that can specify the\nfollowing aspects of an argument:\n\n- its type (the only thing that the basic format supports)\n\n- its name (if it has one)\n\n- whether it may be omitted\n\n- whether it may or must be passed using a keyword\n\n- whether it is a ``*args`` argument (representing the remaining\n  positional arguments)\n\n- whether it is a ``**kwargs`` argument (representing the remaining\n  keyword arguments)\n\nThe following functions are available in ``mypy_extensions`` for this\npurpose:\n\n.. code-block:: python\n\n   def Arg(type=Any, name=None):\n       # A normal, mandatory, positional argument.\n       # If the name is specified it may be passed as a keyword.\n\n   def DefaultArg(type=Any, name=None):\n       # An optional positional argument (i.e. with a default value).\n       # If the name is specified it may be passed as a keyword.\n\n   def NamedArg(type=Any, name=None):\n       # A mandatory keyword-only argument.\n\n   def DefaultNamedArg(type=Any, name=None):\n       # An optional keyword-only argument (i.e. with a default value).\n\n   def VarArg(type=Any):\n       # A *args-style variadic positional argument.\n       # A single VarArg() specifier represents all remaining\n       # positional arguments.\n\n   def KwArg(type=Any):\n       # A **kwargs-style variadic keyword argument.\n       # A single KwArg() specifier represents all remaining\n       # keyword arguments.\n\nIn all cases, the ``type`` argument defaults to ``Any``, and if the\n``name`` argument is omitted the argument has no name (the name is\nrequired for ``NamedArg`` and ``DefaultNamedArg``).  A basic\n:py:class:`~collections.abc.Callable` such as\n\n.. code-block:: python\n\n   MyFunc = Callable[[int, str, int], float]\n\nis equivalent to the following:\n\n.. code-block:: python\n\n   MyFunc = Callable[[Arg(int), Arg(str), Arg(int)], float]\n\nA :py:class:`~collections.abc.Callable` with unspecified argument types, such as\n\n.. code-block:: python\n\n   MyOtherFunc = Callable[..., int]\n\nis (roughly) equivalent to\n\n.. code-block:: python\n\n   MyOtherFunc = Callable[[VarArg(), KwArg()], int]\n\n.. note::\n\n   Each of the functions above currently just returns its ``type``\n   argument at runtime, so the information contained in the argument\n   specifiers is not available at runtime.  This limitation is\n   necessary for backwards compatibility with the existing\n   ``typing.py`` module as present in the Python 3.5+ standard library\n   and distributed via PyPI.\n"
  },
  {
    "path": "docs/source/builtin_types.rst",
    "content": "Built-in types\n==============\n\nThis chapter introduces some commonly used built-in types. We will\ncover many other kinds of types later.\n\nSimple types\n............\n\nHere are examples of some common built-in types:\n\n====================== ===============================\nType                   Description\n====================== ===============================\n``int``                integer\n``float``              floating point number\n``bool``               boolean value (subclass of ``int``)\n``str``                text, sequence of unicode codepoints\n``bytes``              8-bit string, sequence of byte values\n``object``             an arbitrary object (``object`` is the common base class)\n====================== ===============================\n\nAll built-in classes can be used as types.\n\nAny type\n........\n\nIf you can't find a good type for some value, you can always fall back\nto ``Any``:\n\n====================== ===============================\nType                   Description\n====================== ===============================\n``Any``                dynamically typed value with an arbitrary type\n====================== ===============================\n\nThe type ``Any`` is defined in the :py:mod:`typing` module.\nSee :ref:`dynamic-typing` for more details.\n\nGeneric types\n.............\n\nIn Python 3.9 and later, built-in collection type objects support\nindexing:\n\n====================== ===============================\nType                   Description\n====================== ===============================\n``list[str]``          list of ``str`` objects\n``tuple[int, int]``    tuple of two ``int`` objects (``tuple[()]`` is the empty tuple)\n``tuple[int, ...]``    tuple of an arbitrary number of ``int`` objects\n``dict[str, int]``     dictionary from ``str`` keys to ``int`` values\n``Iterable[int]``      iterable object containing ints\n``Sequence[bool]``     sequence of booleans (read-only)\n``Mapping[str, int]``  mapping from ``str`` keys to ``int`` values (read-only)\n``type[C]``            type object of ``C`` (``C`` is a class/type variable/union of types)\n====================== ===============================\n\nThe type ``dict`` is a *generic* class, signified by type arguments within\n``[...]``. For example, ``dict[int, str]`` is a dictionary from integers to\nstrings and ``dict[Any, Any]`` is a dictionary of dynamically typed\n(arbitrary) values and keys. ``list`` is another generic class.\n\n``Iterable``, ``Sequence``, and ``Mapping`` are generic types that correspond to\nPython protocols. For example, a ``str`` object or a ``list[str]`` object is\nvalid when ``Iterable[str]`` or ``Sequence[str]`` is expected.\nYou can import them from :py:mod:`collections.abc` instead of importing from\n:py:mod:`typing` in Python 3.9.\n\nSee :ref:`generic-builtins` for more details, including how you can\nuse these in annotations also in Python 3.7 and 3.8.\n\nThese legacy types defined in :py:mod:`typing` are needed if you need to support\nPython 3.8 and earlier:\n\n====================== ===============================\nType                   Description\n====================== ===============================\n``List[str]``          list of ``str`` objects\n``Tuple[int, int]``    tuple of two ``int`` objects (``Tuple[()]`` is the empty tuple)\n``Tuple[int, ...]``    tuple of an arbitrary number of ``int`` objects\n``Dict[str, int]``     dictionary from ``str`` keys to ``int`` values\n``Iterable[int]``      iterable object containing ints\n``Sequence[bool]``     sequence of booleans (read-only)\n``Mapping[str, int]``  mapping from ``str`` keys to ``int`` values (read-only)\n``Type[C]``            type object of ``C`` (``C`` is a class/type variable/union of types)\n====================== ===============================\n\n``List`` is an alias for the built-in type ``list`` that supports\nindexing (and similarly for ``dict``/``Dict`` and\n``tuple``/``Tuple``).\n\nNote that even though ``Iterable``, ``Sequence`` and ``Mapping`` look\nsimilar to abstract base classes defined in :py:mod:`collections.abc`\n(formerly ``collections``), they are not identical, since the latter\ndon't support indexing prior to Python 3.9.\n"
  },
  {
    "path": "docs/source/changelog.md",
    "content": "<!-- This file includes mypy/CHANGELOG.md into mypy documentation -->\n```{include} ../../CHANGELOG.md\n```\n"
  },
  {
    "path": "docs/source/cheat_sheet_py3.rst",
    "content": ".. _cheat-sheet-py3:\n\nType hints cheat sheet\n======================\n\nThis document is a quick cheat sheet showing how to use type\nannotations for various common types in Python.\n\nVariables\n*********\n\nTechnically many of the type annotations shown below are redundant,\nsince mypy can usually infer the type of a variable from its value.\nSee :ref:`type-inference-and-annotations` for more details.\n\n.. code-block:: python\n\n   # This is how you declare the type of a variable\n   age: int = 1\n\n   # You don't need to initialize a variable to annotate it\n   a: int  # Ok (no value at runtime until assigned)\n\n   # Doing so can be useful in conditional branches\n   child: bool\n   if age < 18:\n       child = True\n   else:\n       child = False\n\n\nUseful built-in types\n*********************\n\n.. code-block:: python\n\n   # For most types, just use the name of the type in the annotation\n   # Note that mypy can usually infer the type of a variable from its value,\n   # so technically these annotations are redundant\n   x: int = 1\n   x: float = 1.0\n   x: bool = True\n   x: str = \"test\"\n   x: bytes = b\"test\"\n\n   # For collections on Python 3.9+, the type of the collection item is in brackets\n   x: list[int] = [1]\n   x: set[int] = {6, 7}\n\n   # For mappings, we need the types of both keys and values\n   x: dict[str, float] = {\"field\": 2.0}  # Python 3.9+\n\n   # For tuples of fixed size, we specify the types of all the elements\n   x: tuple[int, str, float] = (3, \"yes\", 7.5)  # Python 3.9+\n\n   # For tuples of variable size, we use one type and ellipsis\n   x: tuple[int, ...] = (1, 2, 3)  # Python 3.9+\n\n   # On Python 3.8 and earlier, the name of the collection type is\n   # capitalized, and the type is imported from the 'typing' module\n   from typing import List, Set, Dict, Tuple\n   x: List[int] = [1]\n   x: Set[int] = {6, 7}\n   x: Dict[str, float] = {\"field\": 2.0}\n   x: Tuple[int, str, float] = (3, \"yes\", 7.5)\n   x: Tuple[int, ...] = (1, 2, 3)\n\n   from typing import Union, Optional\n\n   # On Python 3.10+, use the | operator when something could be one of a few types\n   x: list[int | str] = [3, 5, \"test\", \"fun\"]  # Python 3.10+\n   # On earlier versions, use Union\n   x: list[Union[int, str]] = [3, 5, \"test\", \"fun\"]\n\n   # Use X | None for a value that could be None on Python 3.10+\n   # Use Optional[X] on 3.9 and earlier; Optional[X] is the same as 'X | None'\n   x: str | None = \"something\" if some_condition() else None\n   if x is not None:\n       # Mypy understands x won't be None here because of the if-statement\n       print(x.upper())\n   # If you know a value can never be None due to some logic that mypy doesn't\n   # understand, use an assert\n   assert x is not None\n   print(x.upper())\n\nFunctions\n*********\n\n.. code-block:: python\n\n   from collections.abc import Iterator, Callable\n   from typing import Union, Optional\n\n   # This is how you annotate a function definition\n   def stringify(num: int) -> str:\n       return str(num)\n\n   # And here's how you specify multiple arguments\n   def plus(num1: int, num2: int) -> int:\n       return num1 + num2\n\n   # If a function does not return a value, use None as the return type\n   # Default value for an argument goes after the type annotation\n   def show(value: str, excitement: int = 10) -> None:\n       print(value + \"!\" * excitement)\n\n   # Note that arguments without a type are dynamically typed (treated as Any)\n   # and that functions without any annotations are not checked\n   def untyped(x):\n       x.anything() + 1 + \"string\"  # no errors\n\n   # This is how you annotate a callable (function) value\n   x: Callable[[int, float], float] = f\n   def register(callback: Callable[[str], int]) -> None: ...\n\n   # A generator function that yields ints is secretly just a function that\n   # returns an iterator of ints, so that's how we annotate it\n   def gen(n: int) -> Iterator[int]:\n       i = 0\n       while i < n:\n           yield i\n           i += 1\n\n   # You can of course split a function annotation over multiple lines\n   def send_email(\n       address: str | list[str],\n       sender: str,\n       cc: list[str] | None,\n       bcc: list[str] | None,\n       subject: str = '',\n       body: list[str] | None = None,\n   ) -> bool:\n       ...\n\n   # Mypy understands positional-only and keyword-only arguments\n   # Positional-only arguments can also be marked by using a name starting with\n   # two underscores\n   def quux(x: int, /, *, y: int) -> None:\n       pass\n\n   quux(3, y=5)  # Ok\n   quux(3, 5)  # error: Too many positional arguments for \"quux\"\n   quux(x=3, y=5)  # error: Unexpected keyword argument \"x\" for \"quux\"\n\n   # This says each positional arg and each keyword arg is a \"str\"\n   def call(self, *args: str, **kwargs: str) -> str:\n       reveal_type(args)  # Revealed type is \"tuple[str, ...]\"\n       reveal_type(kwargs)  # Revealed type is \"dict[str, str]\"\n       request = make_request(*args, **kwargs)\n       return self.do_api_query(request)\n\nClasses\n*******\n\n.. code-block:: python\n\n   from typing import ClassVar\n\n   class BankAccount:\n       # The \"__init__\" method doesn't return anything, so it gets return\n       # type \"None\" just like any other method that doesn't return anything\n       def __init__(self, account_name: str, initial_balance: int = 0) -> None:\n           # mypy will infer the correct types for these instance variables\n           # based on the types of the parameters.\n           self.account_name = account_name\n           self.balance = initial_balance\n\n       # For instance methods, omit type for \"self\"\n       def deposit(self, amount: int) -> None:\n           self.balance += amount\n\n       def withdraw(self, amount: int) -> None:\n           self.balance -= amount\n\n   # User-defined classes are valid as types in annotations\n   account: BankAccount = BankAccount(\"Alice\", 400)\n   def transfer(src: BankAccount, dst: BankAccount, amount: int) -> None:\n       src.withdraw(amount)\n       dst.deposit(amount)\n\n   # Functions that accept BankAccount also accept any subclass of BankAccount!\n   class AuditedBankAccount(BankAccount):\n       # You can optionally declare instance variables in the class body\n       audit_log: list[str]\n\n       def __init__(self, account_name: str, initial_balance: int = 0) -> None:\n           super().__init__(account_name, initial_balance)\n           self.audit_log: list[str] = []\n\n       def deposit(self, amount: int) -> None:\n           self.audit_log.append(f\"Deposited {amount}\")\n           self.balance += amount\n\n       def withdraw(self, amount: int) -> None:\n           self.audit_log.append(f\"Withdrew {amount}\")\n           self.balance -= amount\n\n   audited = AuditedBankAccount(\"Bob\", 300)\n   transfer(audited, account, 100)  # type checks!\n\n   # You can use the ClassVar annotation to declare a class variable\n   class Car:\n       seats: ClassVar[int] = 4\n       passengers: ClassVar[list[str]]\n\n   # If you want dynamic attributes on your class, have it\n   # override \"__setattr__\" or \"__getattr__\"\n   class A:\n       # This will allow assignment to any A.x, if x is the same type as \"value\"\n       # (use \"value: Any\" to allow arbitrary types)\n       def __setattr__(self, name: str, value: int) -> None: ...\n\n       # This will allow access to any A.x, if x is compatible with the return type\n       def __getattr__(self, name: str) -> int: ...\n\n   a = A()\n   a.foo = 42  # Works\n   a.bar = 'Ex-parrot'  # Fails type checking\n\nWhen you're puzzled or when things are complicated\n**************************************************\n\n.. code-block:: python\n\n   from typing import Union, Any, Optional, TYPE_CHECKING, cast\n\n   # To find out what type mypy infers for an expression anywhere in\n   # your program, wrap it in reveal_type().  Mypy will print an error\n   # message with the type; remove it again before running the code.\n   reveal_type(1)  # Revealed type is \"builtins.int\"\n\n   # If you initialize a variable with an empty container or \"None\"\n   # you may have to help mypy a bit by providing an explicit type annotation\n   x: list[str] = []\n   x: str | None = None\n\n   # Use Any if you don't know the type of something or it's too\n   # dynamic to write a type for\n   x: Any = mystery_function()\n   # Mypy will let you do anything with x!\n   x.whatever() * x[\"you\"] + x(\"want\") - any(x) and all(x) is super  # no errors\n\n   # Use a \"type: ignore\" comment to suppress errors on a given line,\n   # when your code confuses mypy or runs into an outright bug in mypy.\n   # Good practice is to add a comment explaining the issue.\n   x = confusing_function()  # type: ignore  # confusing_function won't return None here because ...\n\n   # \"cast\" is a helper function that lets you override the inferred\n   # type of an expression. It's only for mypy -- there's no runtime check.\n   a = [4]\n   b = cast(list[int], a)  # Passes fine\n   c = cast(list[str], a)  # Passes fine despite being a lie (no runtime check)\n   reveal_type(c)  # Revealed type is \"builtins.list[builtins.str]\"\n   print(c)  # Still prints [4] ... the object is not changed or casted at runtime\n\n   # Use \"TYPE_CHECKING\" if you want to have code that mypy can see but will not\n   # be executed at runtime (or to have code that mypy can't see)\n   if TYPE_CHECKING:\n       import json\n   else:\n       import orjson as json  # mypy is unaware of this\n\nIn some cases type annotations can cause issues at runtime, see\n:ref:`runtime_troubles` for dealing with this.\n\nSee :ref:`silencing-type-errors` for details on how to silence errors.\n\nStandard \"duck types\"\n*********************\n\nIn typical Python code, many functions that can take a list or a dict\nas an argument only need their argument to be somehow \"list-like\" or\n\"dict-like\".  A specific meaning of \"list-like\" or \"dict-like\" (or\nsomething-else-like) is called a \"duck type\", and several duck types\nthat are common in idiomatic Python are standardized.\n\n.. code-block:: python\n\n   from collections.abc import Mapping, MutableMapping, Sequence, Iterable\n   # or 'from typing import ...' (required in Python 3.8)\n\n   # Use Iterable for generic iterables (anything usable in \"for\"),\n   # and Sequence where a sequence (supporting \"len\" and \"__getitem__\") is\n   # required\n   def f(ints: Iterable[int]) -> list[str]:\n       return [str(x) for x in ints]\n\n   f(range(1, 3))\n\n   # Mapping describes a dict-like object (with \"__getitem__\") that we won't\n   # mutate, and MutableMapping one (with \"__setitem__\") that we might\n   def f(my_mapping: Mapping[int, str]) -> list[int]:\n       my_mapping[5] = 'maybe'  # mypy will complain about this line...\n       return list(my_mapping.keys())\n\n   f({3: 'yes', 4: 'no'})\n\n   def f(my_mapping: MutableMapping[int, str]) -> set[str]:\n       my_mapping[5] = 'maybe'  # ...but mypy is OK with this.\n       return set(my_mapping.values())\n\n   f({3: 'yes', 4: 'no'})\n\n   import sys\n   from typing import IO\n\n   # Use IO[str] or IO[bytes] for functions that should accept or return\n   # objects that come from an open() call (note that IO does not\n   # distinguish between reading, writing or other modes)\n   def get_sys_IO(mode: str = 'w') -> IO[str]:\n       if mode == 'w':\n           return sys.stdout\n       elif mode == 'r':\n           return sys.stdin\n       else:\n           return sys.stdout\n\n\nYou can even make your own duck types using :ref:`protocol-types`.\n\nForward references\n******************\n\n.. code-block:: python\n\n   # You may want to reference a class before it is defined.\n   # This is known as a \"forward reference\".\n   def f(foo: A) -> int:  # This will fail at runtime with 'A' is not defined\n       ...\n\n   # However, if you add the following special import:\n   from __future__ import annotations\n   # It will work at runtime and type checking will succeed as long as there\n   # is a class of that name later on in the file\n   def f(foo: A) -> int:  # Ok\n       ...\n\n   # Another option is to just put the type in quotes\n   def f(foo: 'A') -> int:  # Also ok\n       ...\n\n   class A:\n       # This can also come up if you need to reference a class in a type\n       # annotation inside the definition of that class\n       @classmethod\n       def create(cls) -> A:\n           ...\n\nSee :ref:`forward-references` for more details.\n\nDecorators\n**********\n\nDecorator functions can be expressed via generics. See\n:ref:`declaring-decorators` for more details. Example using Python 3.12\nsyntax:\n\n.. code-block:: python\n\n    from collections.abc import Callable\n    from typing import Any\n\n    def bare_decorator[F: Callable[..., Any]](func: F) -> F:\n        ...\n\n    def decorator_args[F: Callable[..., Any]](url: str) -> Callable[[F], F]:\n        ...\n\nThe same example using pre-3.12 syntax:\n\n.. code-block:: python\n\n    from collections.abc import Callable\n    from typing import Any, TypeVar\n\n    F = TypeVar('F', bound=Callable[..., Any])\n\n    def bare_decorator(func: F) -> F:\n        ...\n\n    def decorator_args(url: str) -> Callable[[F], F]:\n        ...\n\nCoroutines and asyncio\n**********************\n\nSee :ref:`async-and-await` for the full detail on typing coroutines and asynchronous code.\n\n.. code-block:: python\n\n   import asyncio\n\n   # A coroutine is typed like a normal function\n   async def countdown(tag: str, count: int) -> str:\n       while count > 0:\n           print(f'T-minus {count} ({tag})')\n           await asyncio.sleep(0.1)\n           count -= 1\n       return \"Blastoff!\"\n"
  },
  {
    "path": "docs/source/class_basics.rst",
    "content": ".. _class-basics:\n\nClass basics\n============\n\nThis section will help get you started annotating your\nclasses. Built-in classes such as ``int`` also follow these same\nrules.\n\nInstance and class attributes\n*****************************\n\nThe mypy type checker detects if you are trying to access a missing\nattribute, which is a very common programming error. For this to work\ncorrectly, instance and class attributes must be defined or\ninitialized within the class. Mypy infers the types of attributes:\n\n.. code-block:: python\n\n   class A:\n       def __init__(self, x: int) -> None:\n           self.x = x  # Aha, attribute 'x' of type 'int'\n\n   a = A(1)\n   a.x = 2  # OK!\n   a.y = 3  # Error: \"A\" has no attribute \"y\"\n\nThis is a bit like each class having an implicitly defined\n:py:data:`__slots__ <object.__slots__>` attribute. This is only enforced during type\nchecking and not when your program is running.\n\nYou can declare types of variables in the class body explicitly using\na type annotation:\n\n.. code-block:: python\n\n   class A:\n       x: list[int]  # Declare attribute 'x' of type list[int]\n\n   a = A()\n   a.x = [1]     # OK\n\nAs in Python generally, a variable defined in the class body can be used\nas a class or an instance variable. (As discussed in the next section, you\ncan override this with a :py:data:`~typing.ClassVar` annotation.)\n\nSimilarly, you can give explicit types to instance variables defined\nin a method:\n\n.. code-block:: python\n\n   class A:\n       def __init__(self) -> None:\n           self.x: list[int] = []\n\n       def f(self) -> None:\n           self.y: Any = 0\n\nYou can only define an instance variable within a method if you assign\nto it explicitly using ``self``:\n\n.. code-block:: python\n\n   class A:\n       def __init__(self) -> None:\n           self.y = 1   # Define 'y'\n           a = self\n           a.x = 1      # Error: 'x' not defined\n\nAnnotating __init__ methods\n***************************\n\nThe :py:meth:`__init__ <object.__init__>` method is somewhat special -- it doesn't return a\nvalue.  This is best expressed as ``-> None``.  However, since many feel\nthis is redundant, it is allowed to omit the return type declaration\non :py:meth:`__init__ <object.__init__>` methods **if at least one argument is annotated**.  For\nexample, in the following classes :py:meth:`__init__ <object.__init__>` is considered fully\nannotated:\n\n.. code-block:: python\n\n   class C1:\n       def __init__(self) -> None:\n           self.var = 42\n\n   class C2:\n       def __init__(self, arg: int):\n           self.var = arg\n\nHowever, if :py:meth:`__init__ <object.__init__>` has no annotated arguments and no return type\nannotation, it is considered an untyped method:\n\n.. code-block:: python\n\n   class C3:\n       def __init__(self):\n           # This body is not type checked\n           self.var = 42 + 'abc'\n\nClass attribute annotations\n***************************\n\nYou can use a :py:data:`ClassVar[t] <typing.ClassVar>` annotation to explicitly declare that a\nparticular attribute should not be set on instances:\n\n.. code-block:: python\n\n  from typing import ClassVar\n\n  class A:\n      x: ClassVar[int] = 0  # Class variable only\n\n  A.x += 1  # OK\n\n  a = A()\n  a.x = 1  # Error: Cannot assign to class variable \"x\" via instance\n  print(a.x)  # OK -- can be read through an instance\n\nIt's not necessary to annotate all class variables using\n:py:data:`~typing.ClassVar`. An attribute without the :py:data:`~typing.ClassVar` annotation can\nstill be used as a class variable. However, mypy won't prevent it from\nbeing used as an instance variable, as discussed previously:\n\n.. code-block:: python\n\n  class A:\n      x = 0  # Can be used as a class or instance variable\n\n  A.x += 1  # OK\n\n  a = A()\n  a.x = 1  # Also OK\n\nNote that :py:data:`~typing.ClassVar` is not a class, and you can't use it with\n:py:func:`isinstance` or :py:func:`issubclass`. It does not change Python\nruntime behavior -- it's only for type checkers such as mypy (and\nalso helpful for human readers).\n\nYou can also omit the square brackets and the variable type in\na :py:data:`~typing.ClassVar` annotation, but this might not do what you'd expect:\n\n.. code-block:: python\n\n   class A:\n       y: ClassVar = 0  # Type implicitly Any!\n\nIn this case the type of the attribute will be implicitly ``Any``.\nThis behavior will change in the future, since it's surprising.\n\nAn explicit :py:data:`~typing.ClassVar` may be particularly handy to distinguish\nbetween class and instance variables with callable types. For example:\n\n.. code-block:: python\n\n   from collections.abc import Callable\n   from typing import ClassVar\n\n   class A:\n       foo: Callable[[int], None]\n       bar: ClassVar[Callable[[A, int], None]]\n       bad: Callable[[A], None]\n\n   A().foo(42)  # OK\n   A().bar(42)  # OK\n   A().bad()  # Error: Too few arguments\n\n.. note::\n   A :py:data:`~typing.ClassVar` type parameter cannot include type variables:\n   ``ClassVar[T]`` and ``ClassVar[list[T]]``\n   are both invalid if ``T`` is a type variable (see :ref:`generic-classes`\n   for more about type variables).\n\nOverriding statically typed methods\n***********************************\n\nWhen overriding a statically typed method, mypy checks that the\noverride has a compatible signature:\n\n.. code-block:: python\n\n   class Base:\n       def f(self, x: int) -> None:\n           ...\n\n   class Derived1(Base):\n       def f(self, x: str) -> None:   # Error: type of 'x' incompatible\n           ...\n\n   class Derived2(Base):\n       def f(self, x: int, y: int) -> None:  # Error: too many arguments\n           ...\n\n   class Derived3(Base):\n       def f(self, x: int) -> None:   # OK\n           ...\n\n   class Derived4(Base):\n       def f(self, x: float) -> None:   # OK: mypy treats int as a subtype of float\n           ...\n\n   class Derived5(Base):\n       def f(self, x: int, y: int = 0) -> None:   # OK: accepts more than the base\n           ...                                    #     class method\n\n.. note::\n\n   You can also vary return types **covariantly** in overriding. For\n   example, you could override the return type ``Iterable[int]`` with a\n   subtype such as ``list[int]``. Similarly, you can vary argument types\n   **contravariantly** -- subclasses can have more general argument types.\n\nIn order to ensure that your code remains correct when renaming methods,\nit can be helpful to explicitly mark a method as overriding a base\nmethod. This can be done with the ``@override`` decorator. ``@override``\ncan be imported from ``typing`` starting with Python 3.12 or from\n``typing_extensions`` for use with older Python versions. If the base\nmethod is then renamed while the overriding method is not, mypy will\nshow an error:\n\n.. code-block:: python\n\n   from typing import override\n\n   class Base:\n       def f(self, x: int) -> None:\n           ...\n       def g_renamed(self, y: str) -> None:\n           ...\n\n   class Derived1(Base):\n       @override\n       def f(self, x: int) -> None:   # OK\n           ...\n\n       @override\n       def g(self, y: str) -> None:   # Error: no corresponding base method found\n           ...\n\n.. note::\n\n   Use :ref:`--enable-error-code explicit-override <code-explicit-override>` to require\n   that method overrides use the ``@override`` decorator. Emit an error if it is missing.\n\nYou can also override a statically typed method with a dynamically\ntyped one. This allows dynamically typed code to override methods\ndefined in library classes without worrying about their type\nsignatures.\n\nAs always, relying on dynamically typed code can be unsafe. There is no\nruntime enforcement that the method override returns a value that is\ncompatible with the original return type, since annotations have no\neffect at runtime:\n\n.. code-block:: python\n\n   class Base:\n       def inc(self, x: int) -> int:\n           return x + 1\n\n   class Derived(Base):\n       def inc(self, x):   # Override, dynamically typed\n           return 'hello'  # Incompatible with 'Base', but no mypy error\n\nAbstract base classes and multiple inheritance\n**********************************************\n\nMypy supports Python :doc:`abstract base classes <python:library/abc>` (ABCs). Abstract classes\nhave at least one abstract method or property that must be implemented\nby any *concrete* (non-abstract) subclass. You can define abstract base\nclasses using the :py:class:`abc.ABCMeta` metaclass and the :py:func:`@abc.abstractmethod <abc.abstractmethod>`\nfunction decorator. Example:\n\n.. code-block:: python\n\n   from abc import ABCMeta, abstractmethod\n\n   class Animal(metaclass=ABCMeta):\n       @abstractmethod\n       def eat(self, food: str) -> None: pass\n\n       @property\n       @abstractmethod\n       def can_walk(self) -> bool: pass\n\n   class Cat(Animal):\n       def eat(self, food: str) -> None:\n           ...  # Body omitted\n\n       @property\n       def can_walk(self) -> bool:\n           return True\n\n   x = Animal()  # Error: 'Animal' is abstract due to 'eat' and 'can_walk'\n   y = Cat()     # OK\n\nNote that mypy performs checking for unimplemented abstract methods\neven if you omit the :py:class:`~abc.ABCMeta` metaclass. This can be useful if the\nmetaclass would cause runtime metaclass conflicts.\n\nSince you can't create instances of ABCs, they are most commonly used in\ntype annotations. For example, this method accepts arbitrary iterables\ncontaining arbitrary animals (instances of concrete ``Animal``\nsubclasses):\n\n.. code-block:: python\n\n   def feed_all(animals: Iterable[Animal], food: str) -> None:\n       for animal in animals:\n           animal.eat(food)\n\nThere is one important peculiarity about how ABCs work in Python --\nwhether a particular class is abstract or not is somewhat implicit.\nIn the example below, ``Derived`` is treated as an abstract base class\nsince ``Derived`` inherits an abstract ``f`` method from ``Base`` and\ndoesn't explicitly implement it. The definition of ``Derived``\ngenerates no errors from mypy, since it's a valid ABC:\n\n.. code-block:: python\n\n   from abc import ABCMeta, abstractmethod\n\n   class Base(metaclass=ABCMeta):\n       @abstractmethod\n       def f(self, x: int) -> None: pass\n\n   class Derived(Base):  # No error -- Derived is implicitly abstract\n       def g(self) -> None:\n           ...\n\nAttempting to create an instance of ``Derived`` will be rejected,\nhowever:\n\n.. code-block:: python\n\n   d = Derived()  # Error: 'Derived' is abstract\n\n.. note::\n\n   It's a common error to forget to implement an abstract method.\n   As shown above, the class definition will not generate an error\n   in this case, but any attempt to construct an instance will be\n   flagged as an error.\n\nMypy allows you to omit the body for an abstract method, but if you do so,\nit is unsafe to call such method via ``super()``. For example:\n\n.. code-block:: python\n\n   from abc import abstractmethod\n   class Base:\n       @abstractmethod\n       def foo(self) -> int: pass\n       @abstractmethod\n       def bar(self) -> int:\n           return 0\n   class Sub(Base):\n       def foo(self) -> int:\n           return super().foo() + 1  # error: Call to abstract method \"foo\" of \"Base\"\n                                     # with trivial body via super() is unsafe\n       @abstractmethod\n       def bar(self) -> int:\n           return super().bar() + 1  # This is OK however.\n\nA class can inherit any number of classes, both abstract and\nconcrete. As with normal overrides, a dynamically typed method can\noverride or implement a statically typed method defined in any base\nclass, including an abstract method defined in an abstract base class.\n\nYou can implement an abstract property using either a normal\nproperty or an instance variable.\n\nSlots\n*****\n\nWhen a class has explicitly defined :std:term:`__slots__`,\nmypy will check that all attributes assigned to are members of ``__slots__``:\n\n.. code-block:: python\n\n  class Album:\n      __slots__ = ('name', 'year')\n\n      def __init__(self, name: str, year: int) -> None:\n         self.name = name\n         self.year = year\n         # Error: Trying to assign name \"released\" that is not in \"__slots__\" of type \"Album\"\n         self.released = True\n\n  my_album = Album('Songs about Python', 2021)\n\nMypy will only check attribute assignments against ``__slots__`` when\nthe following conditions hold:\n\n1. All base classes (except builtin ones) must have explicit\n   ``__slots__`` defined (this mirrors Python semantics).\n\n2. ``__slots__`` does not include ``__dict__``. If ``__slots__``\n   includes ``__dict__``, arbitrary attributes can be set, similar to\n   when ``__slots__`` is not defined (this mirrors Python semantics).\n\n3. All values in ``__slots__`` must be string literals.\n"
  },
  {
    "path": "docs/source/command_line.rst",
    "content": ".. _command-line:\n\n.. program:: mypy\n\nThe mypy command line\n=====================\n\nThis section documents mypy's command line interface. You can view\na quick summary of the available flags by running :option:`mypy --help`.\n\n.. note::\n\n   Command line flags are liable to change between releases.\n\n\nSpecifying what to type check\n*****************************\n\nBy default, you can specify what code you want mypy to type check\nby passing in the paths to what you want to have type checked::\n\n    $ mypy foo.py bar.py some_directory\n\nNote that directories are checked recursively.\n\nMypy also lets you specify what code to type check in several other\nways. A short summary of the relevant flags is included below:\nfor full details, see :ref:`running-mypy`.\n\n.. option:: -m MODULE, --module MODULE\n\n    Asks mypy to type check the provided module. This flag may be\n    repeated multiple times.\n\n    Mypy *will not* recursively type check any submodules of the provided\n    module.\n\n.. option:: -p PACKAGE, --package PACKAGE\n\n    Asks mypy to type check the provided package. This flag may be\n    repeated multiple times.\n\n    Mypy *will* recursively type check any submodules of the provided\n    package. This flag is identical to :option:`--module` apart from this\n    behavior.\n\n.. option:: -c PROGRAM_TEXT, --command PROGRAM_TEXT\n\n    Asks mypy to type check the provided string as a program.\n\n\n.. option:: --exclude\n\n    A regular expression that matches file names, directory names and paths\n    which mypy should ignore while recursively discovering files to check.\n    Use forward slashes on all platforms.\n\n    For instance, to avoid discovering any files named `setup.py` you could\n    pass ``--exclude '/setup\\.py$'``. Similarly, you can ignore discovering\n    directories with a given name by e.g. ``--exclude /build/`` or\n    those matching a subpath with ``--exclude /project/vendor/``. To ignore\n    multiple files / directories / paths, you can provide the --exclude\n    flag more than once, e.g ``--exclude '/setup\\.py$' --exclude '/build/'``.\n\n    Note that this flag only affects recursive directory tree discovery, that\n    is, when mypy is discovering files within a directory tree or submodules of\n    a package to check. If you pass a file or module explicitly it will still be\n    checked. For instance, ``mypy --exclude '/setup.py$'\n    but_still_check/setup.py``.\n\n    In particular, ``--exclude`` does not affect mypy's discovery of files\n    via :ref:`import following <follow-imports>`. You can use a per-module\n    :confval:`ignore_errors` config option to silence errors from a given module,\n    or a per-module :confval:`follow_imports` config option to additionally avoid\n    mypy from following imports and checking code you do not wish to be checked.\n\n    Note that mypy will never recursively discover files and directories named\n    \"site-packages\", \"node_modules\" or \"__pycache__\", or those whose name starts\n    with a period, exactly as ``--exclude\n    '/(site-packages|node_modules|__pycache__|\\..*)/$'`` would. Mypy will also\n    never recursively discover files with extensions other than ``.py`` or\n    ``.pyi``.\n\n.. option:: --exclude-gitignore\n\n    This flag will add everything that matches ``.gitignore`` file(s) to :option:`--exclude`.\n\n\nOptional arguments\n******************\n\n.. option:: -h, --help\n\n    Show help message and exit.\n\n.. option:: -v, --verbose\n\n    More verbose messages.\n\n.. option:: -V, --version\n\n    Show program's version number and exit.\n\n.. option:: -O FORMAT, --output FORMAT {json}\n\n    Set a custom output format.\n\n.. _config-file-flag:\n\nConfig file\n***********\n\n.. option:: --config-file CONFIG_FILE\n\n    This flag makes mypy read configuration settings from the given file.\n\n    By default settings are read from ``mypy.ini``, ``.mypy.ini``, ``pyproject.toml``, or ``setup.cfg``\n    in the current directory. Settings override mypy's built-in defaults and\n    command line flags can override settings.\n\n    Specifying :option:`--config-file= <--config-file>` (with no filename) will ignore *all*\n    config files.\n\n    See :ref:`config-file` for the syntax of configuration files.\n\n.. option:: --warn-unused-configs\n\n    This flag makes mypy warn about unused ``[mypy-<pattern>]`` config\n    file sections.\n    (This requires turning off incremental mode using :option:`--no-incremental`.)\n\n\n.. _import-discovery:\n\nImport discovery\n****************\n\nThe following flags customize how exactly mypy discovers and follows\nimports.\n\n.. option:: --explicit-package-bases\n\n    This flag tells mypy that top-level packages will be based in either the\n    current directory, or a member of the ``MYPYPATH`` environment variable or\n    :confval:`mypy_path` config option. This option is only useful\n    in the absence of `__init__.py`. See :ref:`Mapping file\n    paths to modules <mapping-paths-to-modules>` for details.\n\n.. option:: --ignore-missing-imports\n\n    This flag makes mypy ignore all missing imports. It is equivalent\n    to adding ``# type: ignore`` comments to all unresolved imports\n    within your codebase.\n\n    Note that this flag does *not* suppress errors about missing names\n    in successfully resolved modules. For example, if one has the\n    following files::\n\n        package/__init__.py\n        package/mod.py\n\n    Then mypy will generate the following errors with :option:`--ignore-missing-imports`:\n\n    .. code-block:: python\n\n        import package.unknown      # No error, ignored\n        x = package.unknown.func()  # OK. 'func' is assumed to be of type 'Any'\n\n        from package import unknown          # No error, ignored\n        from package.mod import NonExisting  # Error: Module has no attribute 'NonExisting'\n\n    For more details, see :ref:`ignore-missing-imports`.\n\n.. option:: --follow-untyped-imports\n\n    This flag makes mypy analyze imports from installed packages even if\n    missing a :ref:`py.typed marker or stubs <installed-packages>`.\n\n    .. warning::\n\n        Note that analyzing all unannotated modules might result in issues\n        when analyzing code not designed to be type checked and may significantly\n        increase how long mypy takes to run.\n\n.. option:: --follow-imports {normal,silent,skip,error}\n\n    This flag adjusts how mypy follows imported modules that were not\n    explicitly passed in via the command line.\n\n    The default option is ``normal``: mypy will follow and type check\n    all modules. For more information on what the other options do,\n    see :ref:`Following imports <follow-imports>`.\n\n.. option:: --python-executable EXECUTABLE\n\n    This flag will have mypy collect type information from :pep:`561`\n    compliant packages installed for the Python executable ``EXECUTABLE``.\n    If not provided, mypy will use PEP 561 compliant packages installed for\n    the Python executable running mypy.\n\n    See :ref:`installed-packages` for more on making PEP 561 compliant packages.\n\n.. option:: --no-site-packages\n\n    This flag will disable searching for :pep:`561` compliant packages. This\n    will also disable searching for a usable Python executable.\n\n    Use this  flag if mypy cannot find a Python executable for the version of\n    Python being checked, and you don't need to use PEP 561 typed packages.\n    Otherwise, use :option:`--python-executable`.\n\n.. option:: --no-silence-site-packages\n\n    By default, mypy will suppress any error messages generated within :pep:`561`\n    compliant packages. Adding this flag will disable this behavior.\n\n.. option:: --fast-module-lookup\n\n    The default logic used to scan through search paths to resolve imports has a\n    quadratic worse-case behavior in some cases, which is for instance triggered\n    by a large number of folders sharing a top-level namespace as in::\n\n        foo/\n            company/\n                foo/\n                    a.py\n        bar/\n            company/\n                bar/\n                    b.py\n        baz/\n            company/\n                baz/\n                    c.py\n        ...\n\n    If you are in this situation, you can enable an experimental fast path by\n    setting the :option:`--fast-module-lookup` option.\n\n\n.. option:: --no-namespace-packages\n\n    This flag disables import discovery of namespace packages (see :pep:`420`).\n    In particular, this prevents discovery of packages that don't have an\n    ``__init__.py`` (or ``__init__.pyi``) file.\n\n    This flag affects how mypy finds modules and packages explicitly passed on\n    the command line. It also affects how mypy determines fully qualified module\n    names for files passed on the command line. See :ref:`Mapping file paths to\n    modules <mapping-paths-to-modules>` for details.\n\n\n.. _platform-configuration:\n\nPlatform configuration\n**********************\n\nBy default, mypy will assume that you intend to run your code using the same\noperating system and Python version you are using to run mypy itself. The\nfollowing flags let you modify this behavior.\n\nFor more information on how to use these flags, see :ref:`version_and_platform_checks`.\n\n.. option:: --python-version X.Y\n\n    This flag will make mypy type check your code as if it were\n    run under Python version X.Y. Without this option, mypy will default to using\n    whatever version of Python is running mypy.\n\n    This flag will attempt to find a Python executable of the corresponding\n    version to search for :pep:`561` compliant packages. If you'd like to\n    disable this, use the :option:`--no-site-packages` flag (see\n    :ref:`import-discovery` for more details).\n\n.. option:: --platform PLATFORM\n\n    This flag will make mypy type check your code as if it were\n    run under the given operating system. Without this option, mypy will\n    default to using whatever operating system you are currently using.\n\n    The ``PLATFORM`` parameter may be any string supported by\n    :py:data:`sys.platform`.\n\n.. _always-true:\n\n.. option:: --always-true NAME\n\n    This flag will treat all variables named ``NAME`` as\n    compile-time constants that are always true.  This flag may\n    be repeated.\n\n.. option:: --always-false NAME\n\n    This flag will treat all variables named ``NAME`` as\n    compile-time constants that are always false.  This flag may\n    be repeated.\n\n\n.. _disallow-dynamic-typing:\n\nDisallow dynamic typing\n***********************\n\nThe ``Any`` type is used to represent a value that has a :ref:`dynamic type <dynamic-typing>`.\nThe ``--disallow-any`` family of flags will disallow various uses of the ``Any`` type in\na module -- this lets us strategically disallow the use of dynamic typing in a controlled way.\n\nThe following options are available:\n\n.. option:: --disallow-any-unimported\n\n    This flag disallows usage of types that come from unfollowed imports\n    (such types become aliases for ``Any``). Unfollowed imports occur either\n    when the imported module does not exist or when :option:`--follow-imports=skip <--follow-imports>`\n    is set.\n\n.. option:: --disallow-any-expr\n\n    This flag disallows all expressions in the module that have type ``Any``.\n    If an expression of type ``Any`` appears anywhere in the module\n    mypy will output an error unless the expression is immediately\n    used as an argument to :py:func:`~typing.cast` or assigned to a variable with an\n    explicit type annotation.\n\n    In addition, declaring a variable of type ``Any``\n    or casting to type ``Any`` is not allowed. Note that calling functions\n    that take parameters of type ``Any`` is still allowed.\n\n.. option:: --disallow-any-decorated\n\n    This flag disallows functions that have ``Any`` in their signature\n    after decorator transformation.\n\n.. option:: --disallow-any-explicit\n\n    This flag disallows explicit ``Any`` in type positions such as type\n    annotations and generic type parameters.\n\n.. option:: --disallow-any-generics\n\n    This flag disallows usage of generic types that do not specify explicit\n    type parameters. For example, you can't use a bare ``x: list``. Instead, you\n    must always write something like ``x: list[int]``.\n\n.. option:: --disallow-subclassing-any\n\n    This flag reports an error whenever a class subclasses a value of\n    type ``Any``.  This may occur when the base class is imported from\n    a module that doesn't exist (when using\n    :option:`--ignore-missing-imports`) or is\n    ignored due to :option:`--follow-imports=skip <--follow-imports>` or a\n    ``# type: ignore`` comment on the ``import`` statement.\n\n    Since the module is silenced, the imported class is given a type of ``Any``.\n    By default mypy will assume that the subclass correctly inherited\n    the base class even though that may not actually be the case.  This\n    flag makes mypy raise an error instead.\n\n\n.. _untyped-definitions-and-calls:\n\nUntyped definitions and calls\n*****************************\n\nThe following flags configure how mypy handles untyped function\ndefinitions or calls.\n\n.. option:: --disallow-untyped-calls\n\n    This flag reports an error whenever a function with type annotations\n    calls a function defined without annotations.\n\n.. option:: --untyped-calls-exclude\n\n    This flag allows one to selectively disable :option:`--disallow-untyped-calls`\n    for functions and methods defined in specific packages, modules, or classes.\n    Note that each exclude entry acts as a prefix. For example (assuming there\n    are no type annotations for ``third_party_lib`` available):\n\n    .. code-block:: python\n\n        # mypy --disallow-untyped-calls\n        #      --untyped-calls-exclude=third_party_lib.module_a\n        #      --untyped-calls-exclude=foo.A\n        from third_party_lib.module_a import some_func\n        from third_party_lib.module_b import other_func\n        import foo\n\n        some_func()  # OK, function comes from module `third_party_lib.module_a`\n        other_func()  # E: Call to untyped function \"other_func\" in typed context\n\n        foo.A().meth()  # OK, method was defined in class `foo.A`\n        foo.B().meth()  # E: Call to untyped function \"meth\" in typed context\n\n        # file foo.py\n        class A:\n            def meth(self): pass\n        class B:\n            def meth(self): pass\n\n.. option:: --disallow-untyped-defs\n\n    This flag reports an error whenever it encounters a function definition\n    without type annotations or with incomplete type annotations.\n    (a superset of :option:`--disallow-incomplete-defs`).\n\n    For example, it would report an error for :code:`def f(a, b)` and :code:`def f(a: int, b)`.\n\n.. option:: --disallow-incomplete-defs\n\n    This flag reports an error whenever it encounters a partly annotated\n    function definition, while still allowing entirely unannotated definitions.\n\n    For example, it would report an error for :code:`def f(a: int, b)` but not :code:`def f(a, b)`.\n\n.. option:: --check-untyped-defs\n\n    This flag is less severe than the previous two options -- it type checks\n    the body of every function, regardless of whether it has type annotations.\n    (By default the bodies of functions without annotations are not type\n    checked.)\n\n    It will assume all arguments have type ``Any`` and always infer ``Any``\n    as the return type.\n\n.. option:: --disallow-untyped-decorators\n\n    This flag reports an error whenever a function with type annotations\n    is decorated with a decorator without annotations.\n\n\n.. _none-and-optional-handling:\n\nNone and Optional handling\n**************************\n\nThe following flags adjust how mypy handles values of type ``None``.\n\n.. _implicit-optional:\n\n.. option:: --implicit-optional\n\n    This flag causes mypy to treat parameters with a ``None``\n    default value as having an implicit optional type (``T | None``).\n\n    For example, if this flag is set, mypy would assume that the ``x``\n    parameter is actually of type ``int | None`` in the code snippet below,\n    since the default parameter is ``None``:\n\n    .. code-block:: python\n\n        def foo(x: int = None) -> None:\n            print(x)\n\n    **Note:** This was disabled by default starting in mypy 0.980.\n\n.. _no_strict_optional:\n\n.. option:: --no-strict-optional\n\n    This flag effectively disables checking of optional\n    types and ``None`` values. With this option, mypy doesn't\n    generally check the use of ``None`` values -- it is treated\n    as compatible with every type.\n\n    .. warning::\n\n        ``--no-strict-optional`` is evil. Avoid using it and definitely do\n        not use it without understanding what it does.\n\n\n.. _configuring-warnings:\n\nConfiguring warnings\n********************\n\nThe following flags enable warnings for code that is sound but is\npotentially problematic or redundant in some way.\n\n.. option:: --warn-redundant-casts\n\n    This flag will make mypy report an error whenever your code uses\n    an unnecessary cast that can safely be removed.\n\n.. option:: --warn-unused-ignores\n\n    This flag will make mypy report an error whenever your code uses\n    a ``# type: ignore`` comment on a line that is not actually\n    generating an error message.\n\n    This flag, along with the :option:`--warn-redundant-casts` flag, are both\n    particularly useful when you are upgrading mypy. Previously,\n    you may have needed to add casts or ``# type: ignore`` annotations\n    to work around bugs in mypy or missing stubs for 3rd party libraries.\n\n    These two flags let you discover cases where either workarounds are\n    no longer necessary.\n\n.. option:: --no-warn-no-return\n\n    By default, mypy will generate errors when a function is missing\n    return statements in some execution paths. The only exceptions\n    are when:\n\n    -   The function has a ``None`` or ``Any`` return type\n    -   The function has an empty body and is marked as an abstract method,\n        is in a protocol class, or is in a stub file\n    -  The execution path can never return; for example, if an exception\n        is always raised\n\n    Passing in :option:`--no-warn-no-return` will disable these error\n    messages in all cases.\n\n.. option:: --warn-return-any\n\n    This flag causes mypy to generate a warning when returning a value\n    with type ``Any`` from a function declared with a non-``Any`` return type.\n\n.. option:: --warn-unreachable\n\n    This flag will make mypy report an error whenever it encounters\n    code determined to be unreachable or redundant after performing type analysis.\n    This can be a helpful way of detecting certain kinds of bugs in your code.\n\n    For example, enabling this flag will make mypy report that the ``x > 7``\n    check is redundant and that the ``else`` block below is unreachable.\n\n    .. code-block:: python\n\n        def process(x: int) -> None:\n            # Error: Right operand of \"or\" is never evaluated\n            if isinstance(x, int) or x > 7:\n                # Error: Unsupported operand types for + (\"int\" and \"str\")\n                print(x + \"bad\")\n            else:\n                # Error: 'Statement is unreachable' error\n                print(x + \"bad\")\n\n    To help prevent mypy from generating spurious warnings, the \"Statement is\n    unreachable\" warning will be silenced in exactly three cases:\n\n    1.  When the unreachable statement is a ``raise`` statement, is an\n        ``assert False`` statement, or calls a function that has the :py:data:`~typing.NoReturn`\n        return type hint. In other words, when the unreachable statement\n        throws an error or terminates the program in some way.\n    2.  When the unreachable statement is ``return NotImplemented``. This\n        is allowed by mypy due to its use in operator overloading.\n    3.  When the unreachable statement was *intentionally* marked as unreachable\n        using :ref:`version_and_platform_checks`.\n\n    .. note::\n\n        Mypy currently cannot detect and report unreachable or redundant code\n        inside any functions using :ref:`type-variable-value-restriction`.\n\n        This limitation will be removed in future releases of mypy.\n\n.. option:: --report-deprecated-as-note\n\n    If error code ``deprecated`` is enabled, mypy emits errors if your code\n    imports or uses deprecated features. This flag converts such errors to\n    notes, causing mypy to eventually finish with a zero exit code. Features\n    are considered deprecated when decorated with ``warnings.deprecated``.\n\n.. option:: --deprecated-calls-exclude\n\n    This flag allows one to selectively disable :ref:`deprecated<code-deprecated>` warnings\n    for functions and methods defined in specific packages, modules, or classes.\n    Note that each exclude entry acts as a prefix. For example (assuming ``foo.A.func`` is deprecated):\n\n    .. code-block:: python\n\n        # mypy --enable-error-code deprecated\n        #      --deprecated-calls-exclude=foo.A\n        import foo\n\n        foo.A().func()  # OK, the deprecated warning is ignored\n\n        # file foo.py\n        from typing_extensions import deprecated\n        class A:\n            @deprecated(\"Use A.func2 instead\")\n            def func(self): pass\n\n.. _miscellaneous-strictness-flags:\n\nMiscellaneous strictness flags\n******************************\n\nThis section documents any other flags that do not neatly fall under any\nof the above sections.\n\n.. option:: --allow-untyped-globals\n\n    This flag causes mypy to suppress errors caused by not being able to fully\n    infer the types of global and class variables.\n\n.. option:: --allow-redefinition-new\n\n    By default, mypy won't allow a variable to be redefined with an\n    unrelated type. This flag enables the redefinition of unannotated\n    variables with an arbitrary type. You will also need to enable\n    :option:`--local-partial-types <mypy --local-partial-types>`.\n    Example:\n\n    .. code-block:: python\n\n        def maybe_convert(n: int, b: bool) -> int | str:\n            if b:\n                x = str(n)  # Assign \"str\"\n            else:\n                x = n       # Assign \"int\"\n            # Type of \"x\" is \"int | str\" here.\n            return x\n\n    Without the new flag, mypy only supports inferring optional types\n    (``X | None``) from multiple assignments. With this option enabled,\n    mypy can infer arbitrary union types.\n\n    This also enables an unannotated variable to have different types in different\n    code locations:\n\n    .. code-block:: python\n\n        if check():\n            for x in range(n):\n                # Type of \"x\" is \"int\" here.\n                ...\n        else:\n            for x in ['a', 'b']:\n                # Type of \"x\" is \"str\" here.\n                ...\n\n    Function arguments are special, changing their type within function body\n    is allowed even if they are annotated, but that annotation is used to infer\n    types of r.h.s. of all subsequent assignments. Such middle-ground semantics\n    provides good balance for majority of common use cases. For example:\n\n    .. code-block:: python\n\n        def process(values: list[float]) -> None:\n            if not values:\n                values = [0, 0, 0]\n            reveal_type(values)  # Revealed type is list[float]\n\n    Note: We are planning to turn this flag on by default in a future mypy\n    release, along with :option:`--local-partial-types <mypy --local-partial-types>`.\n    The feature is still experimental, and the semantics may still change.\n\n.. option:: --allow-redefinition\n\n    This is an alias to :option:`--allow-redefinition-old <mypy --allow-redefinition-old>`.\n    In mypy v2.0 this will point to\n    :option:`--allow-redefinition-new <mypy --allow-redefinition-new>`, and will\n    eventually became the default.\n\n.. option:: --allow-redefinition-old\n\n    This is an older variant of\n    :option:`--allow-redefinition-new <mypy --allow-redefinition-new>`.\n    This flag enables redefinition of a variable with an\n    arbitrary type *in some contexts*: only redefinitions within the\n    same block and nesting depth as the original definition are allowed.\n\n    We have no plans to remove this flag, but we expect that\n    :option:`--allow-redefinition-new <mypy --allow-redefinition-new>`\n    will replace this flag for new use cases eventually.\n\n    Example where this can be useful:\n\n    .. code-block:: python\n\n       def process(items: list[str]) -> None:\n           # 'items' has type list[str]\n           items = [item.split() for item in items]\n           # 'items' now has type list[list[str]]\n\n    The variable must be used before it can be redefined:\n\n    .. code-block:: python\n\n        def process(items: list[str]) -> None:\n           items = \"mypy\"  # invalid redefinition to str because the variable hasn't been used yet\n           print(items)\n           items = \"100\"  # valid, items now has type str\n           items = int(items)  # valid, items now has type int\n\n.. option:: --local-partial-types\n\n    In mypy, the most common cases for partial types are variables initialized using ``None``,\n    but without explicit ``X | None`` annotations. By default, mypy won't check partial types\n    spanning module top level or class top level. This flag changes the behavior to only allow\n    partial types at local level, therefore it disallows inferring variable type for ``None``\n    from two assignments in different scopes. For example:\n\n    .. code-block:: python\n\n        a = None  # Need type annotation here if using --local-partial-types\n        b: int | None = None\n\n        class Foo:\n            bar = None  # Need type annotation here if using --local-partial-types\n            baz: int | None = None\n\n            def __init__(self) -> None:\n                self.bar = 1\n\n        reveal_type(Foo().bar)  # 'int | None' without --local-partial-types\n\n    Note: this option is always implicitly enabled in mypy daemon and will become\n    enabled by default in mypy v2.0 release.\n\n.. option:: --no-implicit-reexport\n\n    By default, imported values to a module are treated as exported and mypy allows\n    other modules to import them. This flag changes the behavior to not re-export unless\n    the item is imported using from-as or is included in ``__all__``. Note this is\n    always treated as enabled for stub files. For example:\n\n    .. code-block:: python\n\n       # This won't re-export the value\n       from foo import bar\n\n       # Neither will this\n       from foo import bar as bang\n\n       # This will re-export it as bar and allow other modules to import it\n       from foo import bar as bar\n\n       # This will also re-export bar\n       from foo import bar\n       __all__ = ['bar']\n\n\n.. option:: --strict-equality\n\n    By default, mypy allows always-false comparisons like ``42 == 'no'``.\n    Use this flag to prohibit such comparisons of non-overlapping types, and\n    similar identity and container checks:\n\n    .. code-block:: python\n\n       items: list[int]\n       if 'some string' in items:  # Error: non-overlapping container check!\n           ...\n\n       text: str\n       if text != b'other bytes':  # Error: non-overlapping equality check!\n           ...\n\n       assert text is not None  # OK, check against None is allowed\n\n\n.. option:: --strict-equality-for-none\n\n    This flag extends :option:`--strict-equality <mypy --strict-equality>` for checks\n    against ``None``:\n\n    .. code-block:: python\n\n       text: str\n       assert text is not None  # Error: non-overlapping identity check!\n\n    Note that :option:`--strict-equality-for-none <mypy --strict-equality-for-none>`\n    only works in combination with :option:`--strict-equality <mypy --strict-equality>`.\n\n.. option:: --strict-bytes\n\n    By default, mypy treats ``bytearray`` and ``memoryview`` as subtypes of ``bytes`` which\n    is not true at runtime. Use this flag to disable this behavior. ``--strict-bytes`` will\n    be enabled by default in *mypy 2.0*.\n\n    .. code-block:: python\n\n       def f(buf: bytes) -> None:\n           assert isinstance(buf, bytes)  # Raises runtime AssertionError with bytearray/memoryview\n           with open(\"binary_file\", \"wb\") as fp:\n               fp.write(buf)\n\n       f(bytearray(b\"\"))  # error: Argument 1 to \"f\" has incompatible type \"bytearray\"; expected \"bytes\"\n       f(memoryview(b\"\"))  # error: Argument 1 to \"f\" has incompatible type \"memoryview\"; expected \"bytes\"\n\n       # If `f` accepts any object that implements the buffer protocol, consider using:\n       from collections.abc import Buffer  # \"from typing_extensions\" in Python 3.11 and earlier\n\n       def f(buf: Buffer) -> None:\n           with open(\"binary_file\", \"wb\") as fp:\n               fp.write(buf)\n\n       f(b\"\")  # Ok\n       f(bytearray(b\"\"))  # Ok\n       f(memoryview(b\"\"))  # Ok\n\n\n.. option:: --extra-checks\n\n    This flag enables additional checks that are technically correct but may be\n    impractical. In particular, it prohibits partial overlap in ``TypedDict`` updates,\n    and makes arguments prepended via ``Concatenate`` positional-only. For example:\n\n    .. code-block:: python\n\n       from typing import TypedDict\n\n       class Foo(TypedDict):\n           a: int\n\n       class Bar(TypedDict):\n           a: int\n           b: int\n\n       def test(foo: Foo, bar: Bar) -> None:\n           # This is technically unsafe since foo can have a subtype of Foo at\n           # runtime, where type of key \"b\" is incompatible with int, see below\n           bar.update(foo)\n\n       class Bad(Foo):\n           b: str\n       bad: Bad = {\"a\": 0, \"b\": \"no\"}\n       test(bad, bar)\n\n    In future more checks may be added to this flag if:\n\n    * The corresponding use cases are rare, thus not justifying a dedicated\n      strictness flag.\n\n    * The new check cannot be supported as an opt-in error code.\n\n.. option:: --strict\n\n    This flag mode enables a defined subset of optional error-checking flags.\n    This subset primarily includes checks for inadvertent type unsoundness (i.e\n    strict will catch type errors as long as intentional methods like type ignore\n    or casting were not used.)\n\n    Note: the :option:`--warn-unreachable` flag\n    is not automatically enabled by the strict flag.\n\n    The strict flag does not take precedence over other strict-related flags.\n    Directly specifying a flag of alternate behavior will override the\n    behavior of strict, regardless of the order in which they are passed.\n    You can see the list of flags enabled by strict mode in the full\n    :option:`mypy --help` output.\n\n    Note: the exact list of flags enabled by running :option:`--strict` may change\n    over time.\n\n    .. include:: strict_list.rst\n    ..\n        The above file is autogenerated and included during html generation.\n        (That's an include directive, and this is a comment.)\n        It would be fine to generate it at some other time instead,\n        theoretically, but we already had a convenient hook during html gen.\n\n\n.. option:: --disable-error-code\n\n    This flag allows disabling one or multiple error codes globally.\n    See :ref:`error-codes` for more information.\n\n    .. code-block:: python\n\n        # no flag\n        x = 'a string'\n        x.trim()  # error: \"str\" has no attribute \"trim\"  [attr-defined]\n\n        # When using --disable-error-code attr-defined\n        x = 'a string'\n        x.trim()\n\n.. option:: --enable-error-code\n\n    This flag allows enabling one or multiple error codes globally.\n    See :ref:`error-codes` for more information.\n\n    Note: This flag will override disabled error codes from the\n    :option:`--disable-error-code <mypy --disable-error-code>` flag.\n\n    .. code-block:: python\n\n        # When using --disable-error-code attr-defined\n        x = 'a string'\n        x.trim()\n\n        # --disable-error-code attr-defined --enable-error-code attr-defined\n        x = 'a string'\n        x.trim()  # error: \"str\" has no attribute \"trim\"  [attr-defined]\n\n\n.. _configuring-error-messages:\n\nConfiguring error messages\n**************************\n\nThe following flags let you adjust how much detail mypy displays\nin error messages.\n\n.. option:: --show-error-context\n\n    This flag will precede all errors with \"note\" messages explaining the\n    context of the error. For example, consider the following program:\n\n    .. code-block:: python\n\n        class Test:\n            def foo(self, x: int) -> int:\n                return x + \"bar\"\n\n    Mypy normally displays an error message that looks like this::\n\n        main.py:3: error: Unsupported operand types for + (\"int\" and \"str\")\n\n    If we enable this flag, the error message now looks like this::\n\n        main.py: note: In member \"foo\" of class \"Test\":\n        main.py:3: error: Unsupported operand types for + (\"int\" and \"str\")\n\n.. option:: --show-column-numbers\n\n    This flag will add column offsets to error messages.\n    For example, the following indicates an error in line 12, column 9\n    (note that column offsets are 0-based)::\n\n        main.py:12:9: error: Unsupported operand types for / (\"int\" and \"str\")\n\n.. option:: --show-error-code-links\n\n    This flag will also display a link to error code documentation, anchored to the error code reported by mypy.\n    The corresponding error code will be highlighted within the documentation page.\n    If we enable this flag, the error message now looks like this::\n\n        main.py:3: error: Unsupported operand types for - (\"int\" and \"str\")  [operator]\n        main.py:3: note: See 'https://mypy.rtfd.io/en/stable/_refs.html#code-operator' for more info\n\n\n\n.. option:: --show-error-end\n\n    This flag will make mypy show not just that start position where\n    an error was detected, but also the end position of the relevant expression.\n    This way various tools can easily highlight the whole error span. The format is\n    ``file:line:column:end_line:end_column``. This option implies\n    ``--show-column-numbers``.\n\n.. option:: --hide-error-codes\n\n    This flag will hide the error code ``[<code>]`` from error messages. By default, the error\n    code is shown after each error message::\n\n        prog.py:1: error: \"str\" has no attribute \"trim\"  [attr-defined]\n\n    See :ref:`error-codes` for more information.\n\n.. option:: --pretty\n\n    Use visually nicer output in error messages: use soft word wrap,\n    show source code snippets, and show error location markers.\n\n.. option:: --no-color-output\n\n    This flag will disable color output in error messages, enabled by default.\n\n.. option:: --no-error-summary\n\n    This flag will disable error summary. By default mypy shows a summary line\n    including total number of errors, number of files with errors, and number\n    of files checked.\n\n.. option:: --show-absolute-path\n\n    Show absolute paths to files.\n\n.. option:: --soft-error-limit N\n\n    This flag will adjust the limit after which mypy will (sometimes)\n    disable reporting most additional errors. The limit only applies\n    if it seems likely that most of the remaining errors will not be\n    useful or they may be overly noisy. If ``N`` is negative, there is\n    no limit. The default limit is -1.\n\n\n.. _incremental:\n\nIncremental mode\n****************\n\nBy default, mypy will store type information into a cache. Mypy\nwill use this information to avoid unnecessary recomputation when\nit type checks your code again.  This can help speed up the type\nchecking process, especially when most parts of your program have\nnot changed since the previous mypy run.\n\nIf you want to speed up how long it takes to recheck your code\nbeyond what incremental mode can offer, try running mypy in\n:ref:`daemon mode <mypy_daemon>`.\n\n.. option:: --no-incremental\n\n    This flag disables incremental mode: mypy will no longer reference\n    the cache when re-run.\n\n    Note that mypy will still write out to the cache even when\n    incremental mode is disabled: see the :option:`--cache-dir` flag below\n    for more details.\n\n.. option:: --cache-dir DIR\n\n    By default, mypy stores all cache data inside of a folder named\n    ``.mypy_cache`` in the current directory. This flag lets you\n    change this folder. This flag can also be useful for controlling\n    cache use when using :ref:`remote caching <remote-cache>`.\n\n    This setting will override the ``MYPY_CACHE_DIR`` environment\n    variable if it is set.\n\n    Mypy will also always write to the cache even when incremental\n    mode is disabled so it can \"warm up\" the cache. To disable\n    writing to the cache, use ``--cache-dir=/dev/null`` (UNIX)\n    or ``--cache-dir=nul`` (Windows).\n\n.. option:: --no-sqlite-cache\n\n    Avoid using `SQLite`_ database to store the cache, instead write cache data\n    out to individual files.\n\n.. option:: --cache-fine-grained\n\n    Include fine-grained dependency information in the cache for the mypy daemon.\n\n.. option:: --skip-version-check\n\n    By default, mypy will ignore cache data generated by a different\n    version of mypy. This flag disables that behavior.\n\n.. option:: --skip-cache-mtime-checks\n\n    Skip cache internal consistency checks based on mtime.\n\n\nAdvanced options\n****************\n\nThe following flags are useful mostly for people who are interested\nin developing or debugging mypy internals.\n\n.. option:: --pdb\n\n    This flag will invoke the Python debugger when mypy encounters\n    a fatal error.\n\n.. option:: --show-traceback, --tb\n\n    If set, this flag will display a full traceback when mypy\n    encounters a fatal error.\n\n.. option:: --raise-exceptions\n\n    Raise exception on fatal error.\n\n.. option:: --custom-typing-module MODULE\n\n    This flag lets you use a custom module as a substitute for the\n    :py:mod:`typing` module.\n\n.. option:: --custom-typeshed-dir DIR\n\n    This flag specifies the directory where mypy looks for standard library typeshed\n    stubs, instead of the typeshed that ships with mypy.  This is\n    primarily intended to make it easier to test typeshed changes before\n    submitting them upstream, but also allows you to use a forked version of\n    typeshed.\n\n    Note that this doesn't affect third-party library stubs. To test third-party stubs,\n    for example try ``MYPYPATH=stubs/six mypy ...``.\n\n.. _warn-incomplete-stub:\n\n.. option:: --warn-incomplete-stub\n\n    This flag modifies both the :option:`--disallow-untyped-defs` and\n    :option:`--disallow-incomplete-defs` flags so they also report errors\n    if stubs in typeshed are missing type annotations or has incomplete\n    annotations. If both flags are missing, :option:`--warn-incomplete-stub`\n    also does nothing.\n\n    This flag is mainly intended to be used by people who want contribute\n    to typeshed and would like a convenient way to find gaps and omissions.\n\n    If you want mypy to report an error when your codebase *uses* an untyped\n    function, whether that function is defined in typeshed or not, use the\n    :option:`--disallow-untyped-calls` flag. See :ref:`untyped-definitions-and-calls`\n    for more details.\n\n.. _shadow-file:\n\n.. option:: --shadow-file SOURCE_FILE SHADOW_FILE\n\n    When mypy is asked to type check ``SOURCE_FILE``, this flag makes mypy\n    read from and type check the contents of ``SHADOW_FILE`` instead. However,\n    diagnostics will continue to refer to ``SOURCE_FILE``.\n\n    Specifying this argument multiple times (``--shadow-file X1 Y1 --shadow-file X2 Y2``)\n    will allow mypy to perform multiple substitutions.\n\n    This allows tooling to create temporary files with helpful modifications\n    without having to change the source file in place. For example, suppose we\n    have a pipeline that adds ``reveal_type`` for certain variables.\n    This pipeline is run on ``original.py`` to produce ``temp.py``.\n    Running ``mypy --shadow-file original.py temp.py original.py`` will then\n    cause mypy to type check the contents of ``temp.py`` instead of  ``original.py``,\n    but error messages will still reference ``original.py``.\n\n\nReport generation\n*****************\n\nIf these flags are set, mypy will generate a report in the specified\nformat into the specified directory.\n\n.. option:: --any-exprs-report DIR\n\n    Causes mypy to generate a text file report documenting how many\n    expressions of type ``Any`` are present within your codebase.\n\n.. option:: --cobertura-xml-report DIR\n\n    Causes mypy to generate a Cobertura XML type checking coverage report.\n\n    To generate this report, you must either manually install the `lxml`_\n    library or specify mypy installation with the setuptools extra\n    ``mypy[reports]``.\n\n.. option:: --html-report / --xslt-html-report DIR\n\n    Causes mypy to generate an HTML type checking coverage report.\n\n    To generate this report, you must either manually install the `lxml`_\n    library or specify mypy installation with the setuptools extra\n    ``mypy[reports]``.\n\n.. option:: --linecount-report DIR\n\n    Causes mypy to generate a text file report documenting the functions\n    and lines that are typed and untyped within your codebase.\n\n.. option:: --linecoverage-report DIR\n\n    Causes mypy to generate a JSON file that maps each source file's\n    absolute filename to a list of line numbers that belong to typed\n    functions in that file.\n\n.. option:: --lineprecision-report DIR\n\n    Causes mypy to generate a flat text file report with per-module\n    statistics of how many lines are typechecked etc.\n\n.. option:: --txt-report / --xslt-txt-report DIR\n\n    Causes mypy to generate a text file type checking coverage report.\n\n    To generate this report, you must either manually install the `lxml`_\n    library or specify mypy installation with the setuptools extra\n    ``mypy[reports]``.\n\n.. option:: --xml-report DIR\n\n    Causes mypy to generate an XML type checking coverage report.\n\n    To generate this report, you must either manually install the `lxml`_\n    library or specify mypy installation with the setuptools extra\n    ``mypy[reports]``.\n\n\nEnabling incomplete/experimental features\n*****************************************\n\n.. option:: --enable-incomplete-feature {PreciseTupleTypes,InlineTypedDict,TypeForm}\n\n    Some features may require several mypy releases to implement, for example\n    due to their complexity, potential for backwards incompatibility, or\n    ambiguous semantics that would benefit from feedback from the community.\n    You can enable such features for early preview using this flag. Note that\n    it is not guaranteed that all features will be ultimately enabled by\n    default. In *rare cases* we may decide to not go ahead with certain\n    features.\n\nList of currently incomplete/experimental features:\n\n* ``PreciseTupleTypes``: this feature will infer more precise tuple types in\n  various scenarios. Before variadic types were added to the Python type system\n  by :pep:`646`, it was impossible to express a type like \"a tuple with\n  at least two integers\". The best type available was ``tuple[int, ...]``.\n  Therefore, mypy applied very lenient checking for variable-length tuples.\n  Now this type can be expressed as ``tuple[int, int, *tuple[int, ...]]``.\n  For such more precise types (when explicitly *defined* by a user) mypy,\n  for example, warns about unsafe index access, and generally handles them\n  in a type-safe manner. However, to avoid problems in existing code, mypy\n  does not *infer* these precise types when it technically can. Here are\n  notable examples where ``PreciseTupleTypes`` infers more precise types:\n\n  .. code-block:: python\n\n     numbers: tuple[int, ...]\n\n     more_numbers = (1, *numbers, 1)\n     reveal_type(more_numbers)\n     # Without PreciseTupleTypes: tuple[int, ...]\n     # With PreciseTupleTypes: tuple[int, *tuple[int, ...], int]\n\n     other_numbers = (1, 1) + numbers\n     reveal_type(other_numbers)\n     # Without PreciseTupleTypes: tuple[int, ...]\n     # With PreciseTupleTypes: tuple[int, int, *tuple[int, ...]]\n\n     if len(numbers) > 2:\n         reveal_type(numbers)\n         # Without PreciseTupleTypes: tuple[int, ...]\n         # With PreciseTupleTypes: tuple[int, int, int, *tuple[int, ...]]\n     else:\n         reveal_type(numbers)\n         # Without PreciseTupleTypes: tuple[int, ...]\n         # With PreciseTupleTypes: tuple[()] | tuple[int] | tuple[int, int]\n\n* ``InlineTypedDict``: this feature enables non-standard syntax for inline\n  :ref:`TypedDicts <typeddict>`, for example:\n\n  .. code-block:: python\n\n     def test_values() -> {\"width\": int, \"description\": str}:\n         return {\"width\": 42, \"description\": \"test\"}\n\n* ``TypeForm``: this feature enables ``TypeForm``, as described in\n  `PEP 747 – Annotating Type Forms <https://peps.python.org/pep-0747/>_`.\n\n\nMiscellaneous\n*************\n\n.. option:: --install-types\n\n    This flag causes mypy to install known missing stub packages for\n    third-party libraries using pip.  It will display the pip command\n    that will be run, and expects a confirmation before installing\n    anything. For security reasons, these stubs are limited to only a\n    small subset of manually selected packages that have been\n    verified by the typeshed team. These packages include only stub\n    files and no executable code.\n\n    If you use this option without providing any files or modules to\n    type check, mypy will install stub packages suggested during the\n    previous mypy run. If there are files or modules to type check,\n    mypy first type checks those, and proposes to install missing\n    stubs at the end of the run, but only if any missing modules were\n    detected.\n\n    .. note::\n\n        This is new in mypy 0.900. Previous mypy versions included a\n        selection of third-party package stubs, instead of having\n        them installed separately.\n\n.. option:: --non-interactive\n\n   When used together with :option:`--install-types <mypy\n   --install-types>`, this causes mypy to install all suggested stub\n   packages using pip without asking for confirmation, and then\n   continues to perform type checking using the installed stubs, if\n   some files or modules are provided to type check.\n\n   This is implemented as up to two mypy runs internally. The first run\n   is used to find missing stub packages, and output is shown from\n   this run only if no missing stub packages were found. If missing\n   stub packages were found, they are installed and then another run\n   is performed.\n\n.. option:: --junit-xml JUNIT_XML_OUTPUT_FILE\n\n    Causes mypy to generate a JUnit XML test result document with\n    type checking results. This can make it easier to integrate mypy\n    with continuous integration (CI) tools.\n\n.. option:: --junit-format {global,per_file}\n\n    If --junit-xml is set, specifies format.\n    global (default): single test with all errors;\n    per_file: one test entry per file with failures.\n\n.. option:: --find-occurrences CLASS.MEMBER\n\n    This flag will make mypy print out all usages of a class member\n    based on static type information. This feature is experimental.\n\n.. option:: --scripts-are-modules\n\n    This flag will give command line arguments that appear to be\n    scripts (i.e. files whose name does not end in ``.py``)\n    a module name derived from the script name rather than the fixed\n    name :py:mod:`__main__`.\n\n    This lets you check more than one script in a single mypy invocation.\n    (The default :py:mod:`__main__` is technically more correct, but if you\n    have many scripts that import a large package, the behavior enabled\n    by this flag is often more convenient.)\n\n.. _lxml: https://pypi.org/project/lxml/\n.. _SQLite: https://www.sqlite.org/\n"
  },
  {
    "path": "docs/source/common_issues.rst",
    "content": ".. _common_issues:\n\nCommon issues and solutions\n===========================\n\nThis section has examples of cases when you need to update your code\nto use static typing, and ideas for working around issues if mypy\ndoesn't work as expected. Statically typed code is often identical to\nnormal Python code (except for type annotations), but sometimes you need\nto do things slightly differently.\n\n.. _annotations_needed:\n\nNo errors reported for obviously wrong code\n-------------------------------------------\n\nThere are several common reasons why obviously wrong code is not\nflagged as an error.\n\n**The function containing the error is not annotated.**\n\nFunctions that\ndo not have any annotations (neither for any argument nor for the\nreturn type) are not type-checked, and even the most blatant type\nerrors (e.g. ``2 + 'a'``) pass silently.  The solution is to add\nannotations. Where that isn't possible, functions without annotations\ncan be checked using :option:`--check-untyped-defs <mypy --check-untyped-defs>`.\n\nExample:\n\n.. code-block:: python\n\n    def foo(a):\n        return '(' + a.split() + ')'  # No error!\n\nThis gives no error even though ``a.split()`` is \"obviously\" a list\n(the author probably meant ``a.strip()``).  The error is reported\nonce you add annotations:\n\n.. code-block:: python\n\n    def foo(a: str) -> str:\n        return '(' + a.split() + ')'\n    # error: Unsupported operand types for + (\"str\" and \"list[str]\")\n\nIf you don't know what types to add, you can use ``Any``, but beware:\n\n**One of the values involved has type 'Any'.**\n\nExtending the above\nexample, if we were to leave out the annotation for ``a``, we'd get\nno error:\n\n.. code-block:: python\n\n    def foo(a) -> str:\n        return '(' + a.split() + ')'  # No error!\n\nThe reason is that if the type of ``a`` is unknown, the type of\n``a.split()`` is also unknown, so it is inferred as having type\n``Any``, and it is no error to add a string to an ``Any``.\n\nIf you're having trouble debugging such situations,\n:ref:`reveal_type() <reveal-type>` might come in handy.\n\nNote that sometimes library stubs with imprecise type information\ncan be a source of ``Any`` values.\n\n:py:meth:`__init__ <object.__init__>` **method has no annotated\narguments and no return type annotation.**\n\nThis is basically a combination of the two cases above, in that ``__init__``\nwithout annotations can cause ``Any`` types leak into instance variables:\n\n.. code-block:: python\n\n    class Bad:\n        def __init__(self):\n            self.value = \"asdf\"\n            1 + \"asdf\"  # No error!\n\n    bad = Bad()\n    bad.value + 1           # No error!\n    reveal_type(bad)        # Revealed type is \"__main__.Bad\"\n    reveal_type(bad.value)  # Revealed type is \"Any\"\n\n    class Good:\n        def __init__(self) -> None:  # Explicitly return None\n            self.value = value\n\n\n**Some imports may be silently ignored**.\n\nA common source of unexpected ``Any`` values is the\n:option:`--ignore-missing-imports <mypy --ignore-missing-imports>` flag.\n\nWhen you use :option:`--ignore-missing-imports <mypy --ignore-missing-imports>`,\nany imported module that cannot be found is silently replaced with ``Any``.\n\nTo help debug this, simply leave out\n:option:`--ignore-missing-imports <mypy --ignore-missing-imports>`.\nAs mentioned in :ref:`fix-missing-imports`, setting ``ignore_missing_imports=True``\non a per-module basis will make bad surprises less likely and is highly encouraged.\n\nUse of the :option:`--follow-imports=skip <mypy --follow-imports>` flags can also\ncause problems. Use of these flags is strongly discouraged and only required in\nrelatively niche situations. See :ref:`follow-imports` for more information.\n\n**mypy considers some of your code unreachable**.\n\nSee :ref:`unreachable` for more information.\n\n**A function annotated as returning a non-optional type returns 'None'\nand mypy doesn't complain**.\n\n.. code-block:: python\n\n    def foo() -> str:\n        return None  # No error!\n\nYou may have disabled strict optional checking (see\n:ref:`--no-strict-optional <no_strict_optional>` for more).\n\n.. _silencing_checker:\n\nSpurious errors and locally silencing the checker\n-------------------------------------------------\n\nYou can use a ``# type: ignore`` comment to silence the type checker\non a particular line. For example, let's say our code is using\nthe C extension module ``frobnicate``, and there's no stub available.\nMypy will complain about this, as it has no information about the\nmodule:\n\n.. code-block:: python\n\n    import frobnicate  # Error: No module \"frobnicate\"\n    frobnicate.start()\n\nYou can add a ``# type: ignore`` comment to tell mypy to ignore this\nerror:\n\n.. code-block:: python\n\n    import frobnicate  # type: ignore\n    frobnicate.start()  # Okay!\n\nThe second line is now fine, since the ignore comment causes the name\n``frobnicate`` to get an implicit ``Any`` type.\n\nThe type ignore comment must be at the start of the comments on a line.\nThis type ignore will not take effect:\n\n.. code-block:: python\n\n    import frobnicate  #example other comment # type: ignore\n    frobnicate.start()\n\n.. note::\n\n    You can use the form ``# type: ignore[<code>]`` to only ignore\n    specific errors on the line. This way you are less likely to\n    silence unexpected errors that are not safe to ignore, and this\n    will also document what the purpose of the comment is.  See\n    :ref:`error-codes` for more information.\n\n.. note::\n\n    The ``# type: ignore`` comment will only assign the implicit ``Any``\n    type if mypy cannot find information about that particular module. So,\n    if we did have a stub available for ``frobnicate`` then mypy would\n    ignore the ``# type: ignore`` comment and typecheck the stub as usual.\n\nAnother option is to explicitly annotate values with type ``Any`` --\nmypy will let you perform arbitrary operations on ``Any``\nvalues. Sometimes there is no more precise type you can use for a\nparticular value, especially if you use dynamic Python features\nsuch as :py:meth:`__getattr__ <object.__getattr__>`:\n\n.. code-block:: python\n\n   class Wrapper:\n       ...\n       def __getattr__(self, a: str) -> Any:\n           return getattr(self._wrapped, a)\n\nFinally, you can create a stub file (``.pyi``) for a file that\ngenerates spurious errors. Mypy will only look at the stub file\nand ignore the implementation, since stub files take precedence\nover ``.py`` files.\n\nIgnoring a whole file\n---------------------\n\n* To only ignore errors, use a top-level ``# mypy: ignore-errors`` comment instead.\n* To only ignore errors with a specific error code, use a top-level\n  ``# mypy: disable-error-code=\"...\"`` comment. Example: ``# mypy: disable-error-code=\"truthy-bool, ignore-without-code\"``\n* To replace the contents of a module with ``Any``, use a per-module ``follow_imports = skip``.\n  See :ref:`Following imports <follow-imports>` for details.\n\nNote that a ``# type: ignore`` comment at the top of a module (before any statements,\nincluding imports or docstrings) has the effect of ignoring the entire contents of the module.\nThis behaviour can be surprising and result in\n\"Module ... has no attribute ... [attr-defined]\" errors.\n\nIssues with code at runtime\n---------------------------\n\nIdiomatic use of type annotations can sometimes run up against what a given\nversion of Python considers legal code. These can result in some of the\nfollowing errors when trying to run your code:\n\n* ``ImportError`` from circular imports\n* ``NameError: name \"X\" is not defined`` from forward references\n* ``TypeError: 'type' object is not subscriptable`` from types that are not generic at runtime\n* ``ImportError`` or ``ModuleNotFoundError`` from use of stub definitions not available at runtime\n* ``TypeError: unsupported operand type(s) for |: 'type' and 'type'`` from use of new syntax\n\nFor dealing with these, see :ref:`runtime_troubles`.\n\nMypy runs are slow\n------------------\n\nIf your mypy runs feel slow, you should probably use the :ref:`mypy\ndaemon <mypy_daemon>`, which can speed up incremental mypy runtimes by\na factor of 10 or more. :ref:`Remote caching <remote-cache>` can\nmake cold mypy runs several times faster.\n\nFurthermore: as of `mypy 1.13 <https://mypy-lang.blogspot.com/2024/10/mypy-113-released.html>`_,\nmypy allows use of the orjson library for handling the cache instead of the stdlib json, for\nimproved performance. You can ensure the presence of orjson using the ``faster-cache`` extra:\n\n    python3 -m pip install -U mypy[faster-cache]\n\nMypy may depend on orjson by default in the future. To use faster, native parser, use the\n``native-parse`` extra. Native parser will be default in near future.\n\nTypes of empty collections\n--------------------------\n\nYou often need to specify the type when you assign an empty list or\ndict to a new variable, as mentioned earlier:\n\n.. code-block:: python\n\n   a: list[int] = []\n\nWithout the annotation mypy can't always figure out the\nprecise type of ``a``.\n\nYou can use a simple empty list literal in a dynamically typed function (as the\ntype of ``a`` would be implicitly ``Any`` and need not be inferred), if type\nof the variable has been declared or inferred before, or if you perform a simple\nmodification operation in the same scope (such as ``append`` for a list):\n\n.. code-block:: python\n\n   a = []  # Okay because followed by append, inferred type list[int]\n   for i in range(n):\n       a.append(i * i)\n\nHowever, in more complex cases an explicit type annotation can be\nrequired (mypy will tell you this). Often the annotation can\nmake your code easier to understand, so it doesn't only help mypy but\neverybody who is reading the code!\n\nRedefinitions with incompatible types\n-------------------------------------\n\nEach name within a function only has a single 'declared' type. You can\nreuse for loop indices etc., but if you want to use a variable with\nmultiple types within a single function, you may need to instead use\nmultiple variables (or maybe declare the variable with an ``Any`` type).\n\n.. code-block:: python\n\n   def f() -> None:\n       n = 1\n       ...\n       n = 'x'  # error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n.. note::\n\n   Using the :option:`--allow-redefinition <mypy --allow-redefinition>`\n   flag can suppress this error in several cases.\n\nNote that you can redefine a variable with a more *precise* or a more\nconcrete type. For example, you can redefine a sequence (which does\nnot support ``sort()``) as a list and sort it in-place:\n\n.. code-block:: python\n\n    def f(x: Sequence[int]) -> None:\n        # Type of x is Sequence[int] here; we don't know the concrete type.\n        x = list(x)\n        # Type of x is list[int] here.\n        x.sort()  # Okay!\n\nSee :ref:`type-narrowing` for more information.\n\n.. _variance:\n\nInvariance vs covariance\n------------------------\n\nMost mutable generic collections are invariant, and mypy considers all\nuser-defined generic classes invariant by default\n(see :ref:`variance-of-generics` for motivation). This could lead to some\nunexpected errors when combined with type inference. For example:\n\n.. code-block:: python\n\n   class A: ...\n   class B(A): ...\n\n   lst = [A(), A()]  # Inferred type is list[A]\n   new_lst = [B(), B()]  # inferred type is list[B]\n   lst = new_lst  # mypy will complain about this, because List is invariant\n\nPossible strategies in such situations are:\n\n* Use an explicit type annotation:\n\n  .. code-block:: python\n\n     new_lst: list[A] = [B(), B()]\n     lst = new_lst  # OK\n\n* Make a copy of the right hand side:\n\n  .. code-block:: python\n\n     lst = list(new_lst) # Also OK\n\n* Use immutable collections as annotations whenever possible:\n\n  .. code-block:: python\n\n     def f_bad(x: list[A]) -> A:\n         return x[0]\n     f_bad(new_lst) # Fails\n\n     def f_good(x: Sequence[A]) -> A:\n         return x[0]\n     f_good(new_lst) # OK\n\nDeclaring a supertype as variable type\n--------------------------------------\n\nSometimes the inferred type is a subtype (subclass) of the desired\ntype. The type inference uses the first assignment to infer the type\nof a name:\n\n.. code-block:: python\n\n   class Shape: ...\n   class Circle(Shape): ...\n   class Triangle(Shape): ...\n\n   shape = Circle()    # mypy infers the type of shape to be Circle\n   shape = Triangle()  # error: Incompatible types in assignment (expression has type \"Triangle\", variable has type \"Circle\")\n\nYou can just give an explicit type for the variable in cases such the\nabove example:\n\n.. code-block:: python\n\n   shape: Shape = Circle()  # The variable s can be any Shape, not just Circle\n   shape = Triangle()       # OK\n\nComplex type tests\n------------------\n\nMypy can usually infer the types correctly when using :py:func:`isinstance <isinstance>`,\n:py:func:`issubclass <issubclass>`,\nor ``type(obj) is some_class`` type tests,\nand even :ref:`user-defined type guards <type-guards>`,\nbut for other kinds of checks you may need to add an\nexplicit type cast:\n\n.. code-block:: python\n\n  from collections.abc import Sequence\n  from typing import cast\n\n  def find_first_str(a: Sequence[object]) -> str:\n      index = next((i for i, s in enumerate(a) if isinstance(s, str)), -1)\n      if index < 0:\n          raise ValueError('No str found')\n\n      found = a[index]  # Has type \"object\", despite the fact that we know it is \"str\"\n      return cast(str, found)  # We need an explicit cast to make mypy happy\n\nAlternatively, you can use an ``assert`` statement together with some\nof the supported type inference techniques:\n\n.. code-block:: python\n\n  def find_first_str(a: Sequence[object]) -> str:\n      index = next((i for i, s in enumerate(a) if isinstance(s, str)), -1)\n      if index < 0:\n          raise ValueError('No str found')\n\n      found = a[index]  # Has type \"object\", despite the fact that we know it is \"str\"\n      assert isinstance(found, str)  # Now, \"found\" will be narrowed to \"str\"\n      return found  # No need for the explicit \"cast()\" anymore\n\n.. note::\n\n    Note that the :py:class:`object` type used in the above example is similar\n    to ``Object`` in Java: it only supports operations defined for *all*\n    objects, such as equality and :py:func:`isinstance`. The type ``Any``,\n    in contrast, supports all operations, even if they may fail at\n    runtime. The cast above would have been unnecessary if the type of\n    ``o`` was ``Any``.\n\n.. note::\n\n   You can read more about type narrowing techniques :ref:`here <type-narrowing>`.\n\nType inference in Mypy is designed to work well in common cases, to be\npredictable and to let the type checker give useful error\nmessages. More powerful type inference strategies often have complex\nand difficult-to-predict failure modes and could result in very\nconfusing error messages. The tradeoff is that you as a programmer\nsometimes have to give the type checker a little help.\n\n.. _version_and_platform_checks:\n\nPython version and system platform checks\n-----------------------------------------\n\nMypy supports the ability to perform Python version checks and platform\nchecks (e.g. Windows vs Posix), ignoring code paths that won't be run on\nthe targeted Python version or platform. This allows you to more effectively\ntypecheck code that supports multiple versions of Python or multiple operating\nsystems.\n\nMore specifically, mypy will understand the use of :py:data:`sys.version_info` and\n:py:data:`sys.platform` checks within ``if/elif/else`` statements. For example:\n\n.. code-block:: python\n\n   import sys\n\n   # Distinguishing between different versions of Python:\n   if sys.version_info >= (3, 13):\n       # Python 3.13+ specific definitions and imports\n   else:\n       # Other definitions and imports\n\n   # Distinguishing between different operating systems:\n   if sys.platform.startswith(\"linux\"):\n       # Linux-specific code\n   elif sys.platform == \"darwin\":\n       # Mac-specific code\n   elif sys.platform == \"win32\":\n       # Windows-specific code\n   else:\n       # Other systems\n\nAs a special case, you can also use one of these checks in a top-level\n(unindented) ``assert``; this makes mypy skip the rest of the file.\nExample:\n\n.. code-block:: python\n\n   import sys\n\n   assert sys.platform != 'win32'\n\n   # The rest of this file doesn't apply to Windows.\n\nSome other expressions exhibit similar behavior; in particular,\n:py:data:`~typing.TYPE_CHECKING`, variables named ``MYPY`` or ``TYPE_CHECKING``, and any variable\nwhose name is passed to :option:`--always-true <mypy --always-true>` or :option:`--always-false <mypy --always-false>`.\n(However, ``True`` and ``False`` are not treated specially!)\n\n.. note::\n\n   Mypy currently does not support more complex checks, and does not assign\n   any special meaning when assigning a :py:data:`sys.version_info` or :py:data:`sys.platform`\n   check to a variable. This may change in future versions of mypy.\n\nBy default, mypy will use your current version of Python and your current\noperating system as default values for :py:data:`sys.version_info` and\n:py:data:`sys.platform`.\n\nTo target a different Python version, use the :option:`--python-version X.Y <mypy --python-version>` flag.\nFor example, to verify your code typechecks if were run using Python 3.8, pass\nin :option:`--python-version 3.8 <mypy --python-version>` from the command line. Note that you do not need\nto have Python 3.8 installed to perform this check.\n\nTo target a different operating system, use the :option:`--platform PLATFORM <mypy --platform>` flag.\nFor example, to verify your code typechecks if it were run in Windows, pass\nin :option:`--platform win32 <mypy --platform>`. See the documentation for :py:data:`sys.platform`\nfor examples of valid platform parameters.\n\n.. _reveal-type:\n\nDisplaying the type of an expression\n------------------------------------\n\nYou can use ``reveal_type(expr)`` to ask mypy to display the inferred\nstatic type of an expression. This can be useful when you don't quite\nunderstand how mypy handles a particular piece of code. Example:\n\n.. code-block:: python\n\n   reveal_type((1, 'hello'))  # Revealed type is \"tuple[builtins.int, builtins.str]\"\n\nYou can also use ``reveal_locals()`` at any line in a file\nto see the types of all local variables at once. Example:\n\n.. code-block:: python\n\n   a = 1\n   b = 'one'\n   reveal_locals()\n   # Revealed local types are:\n   #     a: builtins.int\n   #     b: builtins.str\n.. note::\n\n    ``reveal_type`` and ``reveal_locals`` are handled specially by mypy during\n    type checking, and don't have to be defined or imported.\n\n    However, if you want to run your code,\n    you'll have to remove any ``reveal_type`` and ``reveal_locals``\n    calls from your program or else Python will give you an error at runtime.\n\n    Alternatively, you can import ``reveal_type`` from ``typing_extensions``\n    or ``typing`` (on Python 3.11 and newer)\n\n.. _silencing-linters:\n\nSilencing linters\n-----------------\n\nIn some cases, linters will complain about unused imports or code. In\nthese cases, you can silence them with a comment after type comments, or on\nthe same line as the import:\n\n.. code-block:: python\n\n   # to silence complaints about unused imports\n   from typing import List  # noqa\n   a = None  # type: List[int]\n\n\nTo silence the linter on the same line as a type comment\nput the linter comment *after* the type comment:\n\n.. code-block:: python\n\n    a = some_complex_thing()  # type: ignore  # noqa\n\nCovariant subtyping of mutable protocol members is rejected\n-----------------------------------------------------------\n\nMypy rejects this because this is potentially unsafe.\nConsider this example:\n\n.. code-block:: python\n\n   from typing import Protocol\n\n   class P(Protocol):\n       x: float\n\n   def fun(arg: P) -> None:\n       arg.x = 3.14\n\n   class C:\n       x = 42\n   c = C()\n   fun(c)  # This is not safe\n   c.x << 5  # Since this will fail!\n\nTo work around this problem consider whether \"mutating\" is actually part\nof a protocol. If not, then one can use a :py:class:`@property <property>` in\nthe protocol definition:\n\n.. code-block:: python\n\n   from typing import Protocol\n\n   class P(Protocol):\n       @property\n       def x(self) -> float:\n          pass\n\n   def fun(arg: P) -> None:\n       ...\n\n   class C:\n       x = 42\n   fun(C())  # OK\n\nDealing with conflicting names\n------------------------------\n\nSuppose you have a class with a method whose name is the same as an\nimported (or built-in) type, and you want to use the type in another\nmethod signature.  E.g.:\n\n.. code-block:: python\n\n   class Message:\n       def bytes(self):\n           ...\n       def register(self, path: bytes):  # error: Invalid type \"mod.Message.bytes\"\n           ...\n\nThe third line elicits an error because mypy sees the argument type\n``bytes`` as a reference to the method by that name.  Other than\nrenaming the method, a workaround is to use an alias:\n\n.. code-block:: python\n\n   bytes_ = bytes\n   class Message:\n       def bytes(self):\n           ...\n       def register(self, path: bytes_):\n           ...\n\nUsing a development mypy build\n------------------------------\n\nYou can install the latest development version of mypy from source. Clone the\n`mypy repository on GitHub <https://github.com/python/mypy>`_, and then run\n``pip install`` locally:\n\n.. code-block:: text\n\n    git clone https://github.com/python/mypy.git\n    cd mypy\n    python3 -m pip install --upgrade .\n\nTo install a development version of mypy that is mypyc-compiled, see the\ninstructions at the `mypyc wheels repo <https://github.com/mypyc/mypy_mypyc-wheels>`_.\n\nVariables vs type aliases\n-------------------------\n\nMypy has both *type aliases* and variables with types like ``type[...]``. These are\nsubtly different, and it's important to understand how they differ to avoid pitfalls.\n\n1. A variable with type ``type[...]`` is defined using an assignment with an\n   explicit type annotation:\n\n   .. code-block:: python\n\n     class A: ...\n     tp: type[A] = A\n\n2. You can define a type alias using an assignment without an explicit type annotation\n   at the top level of a module:\n\n   .. code-block:: python\n\n     class A: ...\n     Alias = A\n\n   You can also use ``TypeAlias`` (:pep:`613`) to define an *explicit type alias*:\n\n   .. code-block:: python\n\n     from typing import TypeAlias  # \"from typing_extensions\" in Python 3.9 and earlier\n\n     class A: ...\n     Alias: TypeAlias = A\n\n   You should always use ``TypeAlias`` to define a type alias in a class body or\n   inside a function.\n\nThe main difference is that the target of an alias is precisely known statically, and this\nmeans that they can be used in type annotations and other *type contexts*. Type aliases\ncan't be defined conditionally (unless using\n:ref:`supported Python version and platform checks <version_and_platform_checks>`):\n\n   .. code-block:: python\n\n     class A: ...\n     class B: ...\n\n     if random() > 0.5:\n         Alias = A\n     else:\n         # error: Cannot assign multiple types to name \"Alias\" without an\n         # explicit \"Type[...]\" annotation\n         Alias = B\n\n     tp: type[object]  # \"tp\" is a variable with a type object value\n     if random() > 0.5:\n         tp = A\n     else:\n         tp = B  # This is OK\n\n     def fun1(x: Alias) -> None: ...  # OK\n     def fun2(x: tp) -> None: ...  # Error: \"tp\" is not valid as a type\n\nIncompatible overrides\n----------------------\n\nIt's unsafe to override a method with a more specific argument type,\nas it violates the `Liskov substitution principle\n<https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle>`_.\nFor return types, it's unsafe to override a method with a more general\nreturn type.\n\nOther incompatible signature changes in method overrides, such as\nadding an extra required parameter, or removing an optional parameter,\nwill also generate errors. The signature of a method in a subclass\nshould accept all valid calls to the base class method. Mypy\ntreats a subclass as a subtype of the base class. An instance of a\nsubclass is valid everywhere where an instance of the base class is\nvalid.\n\nThis example demonstrates both safe and unsafe overrides:\n\n.. code-block:: python\n\n    from collections.abc import Sequence, Iterable\n\n    class A:\n        def test(self, t: Sequence[int]) -> Sequence[str]:\n            ...\n\n    class GeneralizedArgument(A):\n        # A more general argument type is okay\n        def test(self, t: Iterable[int]) -> Sequence[str]:  # OK\n            ...\n\n    class NarrowerArgument(A):\n        # A more specific argument type isn't accepted\n        def test(self, t: list[int]) -> Sequence[str]:  # Error\n            ...\n\n    class NarrowerReturn(A):\n        # A more specific return type is fine\n        def test(self, t: Sequence[int]) -> list[str]:  # OK\n            ...\n\n    class GeneralizedReturn(A):\n        # A more general return type is an error\n        def test(self, t: Sequence[int]) -> Iterable[str]:  # Error\n            ...\n\nYou can use ``# type: ignore[override]`` to silence the error. Add it\nto the line that generates the error, if you decide that type safety is\nnot necessary:\n\n.. code-block:: python\n\n    class NarrowerArgument(A):\n        def test(self, t: list[int]) -> Sequence[str]:  # type: ignore[override]\n            ...\n\n.. _unreachable:\n\nUnreachable code\n----------------\n\nMypy may consider some code as *unreachable*, even if it might not be\nimmediately obvious why.  It's important to note that mypy will *not*\ntype check such code. Consider this example:\n\n.. code-block:: python\n\n    class Foo:\n        bar: str = ''\n\n    def bar() -> None:\n        foo: Foo = Foo()\n        return\n        x: int = 'abc'  # Unreachable -- no error\n\nIt's easy to see that any statement after ``return`` is unreachable,\nand hence mypy will not complain about the mistyped code below\nit. For a more subtle example, consider this code:\n\n.. code-block:: python\n\n    class Foo:\n        bar: str = ''\n\n    def bar() -> None:\n        foo: Foo = Foo()\n        assert foo.bar is None\n        x: int = 'abc'  # Unreachable -- no error\n\nAgain, mypy will not report any errors. The type of ``foo.bar`` is\n``str``, and mypy reasons that it can never be ``None``.  Hence the\n``assert`` statement will always fail and the statement below will\nnever be executed.  (Note that in Python, ``None`` is not an empty\nreference but an object of type ``None``.)\n\nIn this example mypy will go on to check the last line and report an\nerror, since mypy thinks that the condition could be either True or\nFalse:\n\n.. code-block:: python\n\n    class Foo:\n        bar: str = ''\n\n    def bar() -> None:\n        foo: Foo = Foo()\n        if not foo.bar:\n            return\n        x: int = 'abc'  # Reachable -- error\n\nIf you use the :option:`--warn-unreachable <mypy --warn-unreachable>` flag, mypy will generate\nan error about each unreachable code block.\n\nNarrowing and inner functions\n-----------------------------\n\nBecause closures in Python are late-binding (https://docs.python-guide.org/writing/gotchas/#late-binding-closures),\nmypy will not narrow the type of a captured variable in an inner function.\nThis is best understood via an example:\n\n.. code-block:: python\n\n    def foo(x: int | None) -> Callable[[], int]:\n        if x is None:\n            x = 5\n        print(x + 1)  # mypy correctly deduces x must be an int here\n        def inner() -> int:\n            return x + 1  # but (correctly) complains about this line\n\n        x = None  # because x could later be assigned None\n        return inner\n\n    inner = foo(5)\n    inner()  # this will raise an error when called\n\nTo get this code to type check, you could assign ``y = x`` after ``x`` has been\nnarrowed, and use ``y`` in the inner function, or add an assert in the inner\nfunction.\n\n.. _incorrect-self:\n\nIncorrect use of ``Self``\n-------------------------\n\n``Self`` is not the type of the current class; it's a type variable with upper\nbound of the current class. That is, it represents the type of the current class\nor of potential subclasses.\n\n.. code-block:: python\n\n    from typing import Self\n\n    class Foo:\n        @classmethod\n        def constructor(cls) -> Self:\n            # Instead, either call cls() or change the annotation to -> Foo\n            return Foo()  # error: Incompatible return value type (got \"Foo\", expected \"Self\")\n\n    class Bar(Foo):\n        ...\n\n    reveal_type(Foo.constructor())  # note: Revealed type is \"Foo\"\n    # In the context of the subclass Bar, the Self return type promises\n    # that the return value will be Bar\n    reveal_type(Bar.constructor())  # note: Revealed type is \"Bar\"\n"
  },
  {
    "path": "docs/source/conf.py",
    "content": "# -*- coding: utf-8 -*-\n#\n# Mypy documentation build configuration file, created by\n# sphinx-quickstart on Sun Sep 14 19:50:35 2014.\n#\n# This file is execfile()d with the current directory set to its\n# containing dir.\n#\n# Note that not all possible configuration values are present in this\n# autogenerated file.\n#\n# All configuration values have a default; values that are commented out\n# serve to show the default.\n\nfrom __future__ import annotations\n\nimport os\nimport sys\n\nfrom sphinx.application import Sphinx\nfrom sphinx.util.docfields import Field\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\nsys.path.insert(0, os.path.abspath(\"../..\"))\n\nfrom mypy.version import __version__ as mypy_version\n\n# -- General configuration ------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n    \"sphinx.ext.intersphinx\",\n    \"sphinx_inline_tabs\",\n    \"docs.source.html_builder\",\n    \"myst_parser\",\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\n\n# The suffix of source filenames.\nsource_suffix = \".rst\"\n\n# The encoding of source files.\n# source_encoding = 'utf-8-sig'\n\n# The master toctree document.\nmaster_doc = \"index\"\n\n# General information about the project.\nproject = \"mypy\"\ncopyright = \"2012-%Y Jukka Lehtosalo and mypy contributors\"\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = mypy_version.split(\"-\")[0]\n# The full version, including alpha/beta/rc tags.\nrelease = mypy_version\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n# language = None\n\n# There are two options for replacing |today|: either, you set today to some\n# non-false value, then it is used:\n# today = ''\n# Else, today_fmt is used as the format for a strftime call.\n# today_fmt = '%B %d, %Y'\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\nexclude_patterns = []\n\n# The reST default role (used for this markup: `text`) to use for all\n# documents.\n# default_role = None\n\n# If true, '()' will be appended to :func: etc. cross-reference text.\n# add_function_parentheses = True\n\n# If true, the current module name will be prepended to all description\n# unit titles (such as .. function::).\n# add_module_names = True\n\n# If true, sectionauthor and moduleauthor directives will be shown in the\n# output. They are ignored by default.\n# show_authors = False\n\n# The name of the Pygments (syntax highlighting) style to use.\n# pygments_style = \"sphinx\"\n\n# A list of ignored prefixes for module index sorting.\n# modindex_common_prefix = []\n\n# If true, keep warnings as \"system message\" paragraphs in the built documents.\n# keep_warnings = False\n\n\n# -- Options for HTML output ----------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\nhtml_theme = \"furo\"\n\nhtml_theme_options = {\n    \"source_repository\": \"https://github.com/python/mypy\",\n    \"source_branch\": \"master\",\n    \"source_directory\": \"docs/source\",\n}\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n# html_theme_options = {}\n\n# Add any paths that contain custom themes here, relative to this directory.\n# html_theme_path = []\n\n# The name for this set of Sphinx documents.  If None, it defaults to\n# \"<project> v<release> documentation\".\n# html_title = None\n\n# A shorter title for the navigation bar.  Default is the same as html_title.\n# html_short_title = None\n\n# The name of an image file (relative to this directory) to place at the top\n# of the sidebar.\nhtml_logo = \"mypy_light.svg\"\n\n# The name of an image file (within the static path) to use as favicon of the\n# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32\n# pixels large.\n# html_favicon = None\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\n# html_static_path = ['_static']\n\n# Add any extra paths that contain custom files (such as robots.txt or\n# .htaccess) here, relative to this directory. These files are copied\n# directly to the root of the documentation.\n# html_extra_path = []\n\n# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,\n# using the given strftime format.\n# html_last_updated_fmt = '%b %d, %Y'\n\n# If true, SmartyPants will be used to convert quotes and dashes to\n# typographically correct entities.\n# html_use_smartypants = True\n\n# Custom sidebar templates, maps document names to template names.\n# html_sidebars = {}\n\n# Additional templates that should be rendered to pages, maps page names to\n# template names.\n# html_additional_pages = {}\n\n# If false, no module index is generated.\n# html_domain_indices = True\n\n# If false, no index is generated.\n# html_use_index = True\n\n# If true, the index is split into individual pages for each letter.\n# html_split_index = False\n\n# If true, links to the reST sources are added to the pages.\n# html_show_sourcelink = True\n\n# If true, \"Created using Sphinx\" is shown in the HTML footer. Default is True.\n# html_show_sphinx = True\n\n# If true, \"(C) Copyright ...\" is shown in the HTML footer. Default is True.\n# html_show_copyright = True\n\n# If true, an OpenSearch description file will be output, and all pages will\n# contain a <link> tag referring to it.  The value of this option must be the\n# base URL from which the finished HTML is served.\n# html_use_opensearch = ''\n\n# This is the file name suffix for HTML files (e.g. \".xhtml\").\n# html_file_suffix = None\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = \"mypydoc\"\n\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n    # The paper size ('letterpaper' or 'a4paper').\n    #'papersize': 'letterpaper',\n    # The font size ('10pt', '11pt' or '12pt').\n    #'pointsize': '10pt',\n    # Additional stuff for the LaTeX preamble.\n    #'preamble': '',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n#  author, documentclass [howto, manual, or own class]).\nlatex_documents = [(\"index\", \"Mypy.tex\", \"Mypy Documentation\", \"Jukka\", \"manual\")]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n# latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n# latex_use_parts = False\n\n# If true, show page references after internal links.\n# latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n# latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n# latex_appendices = []\n\n# If false, no module index is generated.\n# latex_domain_indices = True\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [(\"index\", \"mypy\", \"Mypy Documentation\", [\"Jukka Lehtosalo\"], 1)]\n\n# If true, show URL addresses after external links.\n# man_show_urls = False\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\ntexinfo_documents = [\n    (\n        \"index\",\n        \"Mypy\",\n        \"Mypy Documentation\",\n        \"Jukka\",\n        \"Mypy\",\n        \"One line description of project.\",\n        \"Miscellaneous\",\n    )\n]\n\n# Documents to append as an appendix to all manuals.\n# texinfo_appendices = []\n\n# If false, no module index is generated.\n# texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n# texinfo_show_urls = 'footnote'\n\n# If true, do not generate a @detailmenu in the \"Top\" node's menu.\n# texinfo_no_detailmenu = False\n\nrst_prolog = \".. |...| unicode:: U+2026   .. ellipsis\\n\"\n\nintersphinx_mapping = {\n    \"python\": (\"https://docs.python.org/3\", None),\n    \"attrs\": (\"https://www.attrs.org/en/stable/\", None),\n    \"cython\": (\"https://cython.readthedocs.io/en/stable\", None),\n    \"monkeytype\": (\"https://monkeytype.readthedocs.io/en/latest\", None),\n    \"setuptools\": (\"https://setuptools.pypa.io/en/latest\", None),\n}\n\n\ndef setup(app: Sphinx) -> None:\n    app.add_object_type(\n        \"confval\",\n        \"confval\",\n        objname=\"configuration value\",\n        indextemplate=\"pair: %s; configuration value\",\n        doc_field_types=[\n            Field(\"type\", label=\"Type\", has_arg=False, names=(\"type\",)),\n            Field(\"default\", label=\"Default\", has_arg=False, names=(\"default\",)),\n        ],\n    )\n"
  },
  {
    "path": "docs/source/config_file.rst",
    "content": ".. _config-file:\n\nThe mypy configuration file\n===========================\n\nMypy is very configurable. This is most useful when introducing typing to\nan existing codebase. See :ref:`existing-code` for concrete advice for\nthat situation.\n\nMypy supports reading configuration settings from a file. By default, mypy will\ndiscover configuration files by walking up the file system (up until the root of\na repository or the root of the filesystem). In each directory, it will look for\nthe following configuration files (in this order):\n\n    1. ``mypy.ini``\n    2. ``.mypy.ini``\n    3. ``pyproject.toml`` (containing a ``[tool.mypy]`` section)\n    4. ``setup.cfg`` (containing a ``[mypy]`` section)\n\nIf no configuration file is found by this method, mypy will then look for\nconfiguration files in the following locations (in this order):\n\n    1. ``$XDG_CONFIG_HOME/mypy/config``\n    2. ``~/.config/mypy/config``\n    3. ``~/.mypy.ini``\n\nThe :option:`--config-file <mypy --config-file>` command-line flag has the\nhighest precedence and must point towards a valid configuration file;\notherwise mypy will report an error and exit. Without the command line option,\nmypy will look for configuration files in the precedence order above.\n\nIt is important to understand that there is no merging of configuration\nfiles, as it would lead to ambiguity.\n\nMost flags correspond closely to :ref:`command-line flags\n<command-line>` but there are some differences in flag names and some\nflags may take a different value based on the module being processed.\n\nSome flags support user home directory and environment variable expansion.\nTo refer to the user home directory, use ``~`` at the beginning of the path.\nTo expand environment variables use ``$VARNAME`` or ``${VARNAME}``.\n\n\nConfig file format\n******************\n\nThe configuration file format is the usual\n:doc:`ini file <python:library/configparser>` format. It should contain\nsection names in square brackets and flag settings of the form\n`NAME = VALUE`. Comments start with ``#`` characters.\n\n- A section named ``[mypy]`` must be present.  This specifies\n  the global flags.\n\n- Additional sections named ``[mypy-PATTERN1,PATTERN2,...]`` may be\n  present, where ``PATTERN1``, ``PATTERN2``, etc., are comma-separated\n  patterns of fully-qualified module names, with some components optionally\n  replaced by the '*' character (e.g. ``foo.bar``, ``foo.bar.*``, ``foo.*.baz``).\n  These sections specify additional flags that only apply to *modules*\n  whose name matches at least one of the patterns.\n\n  A pattern of the form ``qualified_module_name`` matches only the named module,\n  while ``dotted_module_name.*`` matches ``dotted_module_name`` and any\n  submodules (so ``foo.bar.*`` would match all of ``foo.bar``,\n  ``foo.bar.baz``, and ``foo.bar.baz.quux``).\n\n  Patterns may also be \"unstructured\" wildcards, in which stars may\n  appear in the middle of a name (e.g\n  ``site.*.migrations.*``). Stars match zero or more module\n  components (so ``site.*.migrations.*`` can match ``site.migrations``).\n\n  .. _config-precedence:\n\n  When options conflict, the precedence order for configuration is:\n\n    1. :ref:`Inline configuration <inline-config>` in the source file\n    2. Sections with concrete module names (``foo.bar``)\n    3. Sections with \"unstructured\" wildcard patterns (``foo.*.baz``),\n       with sections later in the configuration file overriding\n       sections earlier.\n    4. Sections with \"well-structured\" wildcard patterns\n       (``foo.bar.*``), with more specific overriding more general.\n    5. Command line options.\n    6. Top-level configuration file options.\n\nThe difference in precedence order between \"structured\" patterns (by\nspecificity) and \"unstructured\" patterns (by order in the file) is\nunfortunate, and is subject to change in future versions.\n\n.. note::\n\n   The :confval:`warn_unused_configs` flag may be useful to debug misspelled\n   section names.\n\n.. note::\n\n   Configuration flags are liable to change between releases.\n\n\nPer-module and global options\n*****************************\n\nSome of the config options may be set either globally (in the ``[mypy]`` section)\nor on a per-module basis (in sections like ``[mypy-foo.bar]``).\n\nIf you set an option both globally and for a specific module, the module configuration\noptions take precedence. This lets you set global defaults and override them on a\nmodule-by-module basis. If multiple pattern sections match a module, :ref:`the options from the\nmost specific section are used where they disagree <config-precedence>`.\n\nSome other options, as specified in their description,\nmay only be set in the global section (``[mypy]``).\n\n\nInverting option values\n***********************\n\nOptions that take a boolean value may be inverted by adding ``no_`` to\ntheir name or by (when applicable) swapping their prefix from\n``disallow`` to ``allow`` (and vice versa).\n\n\nExample ``mypy.ini``\n********************\n\nHere is an example of a ``mypy.ini`` file. To use this config file, place it at the root\nof your repo and run mypy.\n\n.. code-block:: ini\n\n    # Global options:\n\n    [mypy]\n    warn_return_any = True\n    warn_unused_configs = True\n\n    # Per-module options:\n\n    [mypy-mycode.foo.*]\n    disallow_untyped_defs = True\n\n    [mypy-mycode.bar]\n    warn_return_any = False\n\n    [mypy-somelibrary]\n    ignore_missing_imports = True\n\nThis config file specifies two global options in the ``[mypy]`` section. These two\noptions will:\n\n1.  Report an error whenever a function returns a value that is inferred\n    to have type ``Any``.\n\n2.  Report any config options that are unused by mypy. (This will help us catch typos\n    when making changes to our config file).\n\nNext, this module specifies three per-module options. The first two options change how mypy\ntype checks code in ``mycode.foo.*`` and ``mycode.bar``, which we assume here are two modules\nthat you wrote. The final config option changes how mypy type checks ``somelibrary``, which we\nassume here is some 3rd party library you've installed and are importing. These options will:\n\n1.  Selectively disallow untyped function definitions only within the ``mycode.foo``\n    package -- that is, only for function definitions defined in the\n    ``mycode/foo`` directory.\n\n2.  Selectively *disable* the \"function is returning any\" warnings within\n    ``mycode.bar`` only. This overrides the global default we set earlier.\n\n3.  Suppress any error messages generated when your codebase tries importing the\n    module ``somelibrary``. This is useful if ``somelibrary`` is some 3rd party library\n    missing type hints.\n\n\n.. _config-file-import-discovery:\n\nImport discovery\n****************\n\nFor more information, see the :ref:`Import discovery <import-discovery>`\nsection of the command line docs.\n\n.. confval:: mypy_path\n\n    :type: string\n\n    Specifies the paths to use, after trying the paths from ``MYPYPATH`` environment\n    variable.  Useful if you'd like to keep stubs in your repo, along with the config file.\n    Multiple paths are always separated with a ``:`` or ``,`` regardless of the platform.\n    User home directory and environment variables will be expanded.\n\n    Relative paths are treated relative to the working directory of the mypy command,\n    not the config file.\n    Use the ``MYPY_CONFIG_FILE_DIR`` environment variable to refer to paths relative to\n    the config file (e.g. ``mypy_path = $MYPY_CONFIG_FILE_DIR/src``).\n\n    This option may only be set in the global section (``[mypy]``).\n\n    **Note:** On Windows, use UNC paths to avoid using ``:`` (e.g. ``\\\\127.0.0.1\\X$\\MyDir`` where ``X`` is the drive letter).\n\n.. confval:: files\n\n    :type: comma-separated list of strings\n\n    A comma-separated list of paths which should be checked by mypy if none are given on the command\n    line. Supports recursive file globbing using :py:mod:`glob`, where ``*`` (e.g. ``*.py``) matches\n    files in the current directory and ``**/`` (e.g. ``**/*.py``) matches files in any directories below\n    the current one. User home directory and environment variables will be expanded.\n\n    This option may only be set in the global section (``[mypy]``).\n\n.. confval:: modules\n\n    :type: comma-separated list of strings\n\n    A comma-separated list of packages which should be checked by mypy if none are given on the command\n    line. Mypy *will not* recursively type check any submodules of the provided\n    module.\n\n    This option may only be set in the global section (``[mypy]``).\n\n\n.. confval:: packages\n\n    :type: comma-separated list of strings\n\n    A comma-separated list of packages which should be checked by mypy if none are given on the command\n    line.  Mypy *will* recursively type check any submodules of the provided\n    package. This flag is identical to :confval:`modules` apart from this\n    behavior.\n\n    This option may only be set in the global section (``[mypy]``).\n\n.. confval:: exclude\n\n    :type: regular expression\n\n    A regular expression that matches file names, directory names and paths\n    which mypy should ignore while recursively discovering files to check.\n    Use forward slashes (``/``) as directory separators on all platforms.\n\n    .. code-block:: ini\n\n      [mypy]\n      exclude = (?x)(\n          ^one\\.py$    # files named \"one.py\"\n          | two\\.pyi$  # or files ending with \"two.pyi\"\n          | ^three\\.   # or files starting with \"three.\"\n        )\n\n    Crafting a single regular expression that excludes multiple files while remaining\n    human-readable can be a challenge. The above example demonstrates one approach.\n    ``(?x)`` enables the ``VERBOSE`` flag for the subsequent regular expression, which\n    :py:data:`ignores most whitespace and supports comments <re.VERBOSE>`.\n    The above is equivalent to: ``(^one\\.py$|two\\.pyi$|^three\\.)``.\n\n    For more details, see :option:`--exclude <mypy --exclude>`.\n\n    This option may only be set in the global section (``[mypy]``).\n\n    .. note::\n\n       Note that the TOML equivalent differs slightly. It can be either a single string\n       (including a multi-line string) -- which is treated as a single regular\n       expression -- or an array of such strings. The following TOML examples are\n       equivalent to the above INI example.\n\n       Array of strings:\n\n       .. code-block:: toml\n\n          [tool.mypy]\n          exclude = [\n              \"^one\\\\.py$\",  # TOML's double-quoted strings require escaping backslashes\n              'two\\.pyi$',  # but TOML's single-quoted strings do not\n              '^three\\.',\n          ]\n\n       A single, multi-line string:\n\n       .. code-block:: toml\n\n          [tool.mypy]\n          exclude = '''(?x)(\n              ^one\\.py$    # files named \"one.py\"\n              | two\\.pyi$  # or files ending with \"two.pyi\"\n              | ^three\\.   # or files starting with \"three.\"\n          )'''  # TOML's single-quoted strings do not require escaping backslashes\n\n       See :ref:`using-a-pyproject-toml`.\n\n.. confval:: exclude_gitignore\n\n    :type: boolean\n    :default: False\n\n    This flag will add everything that matches ``.gitignore`` file(s) to :confval:`exclude`.\n    This option may only be set in the global section (``[mypy]``).\n\n.. confval:: namespace_packages\n\n    :type: boolean\n    :default: True\n\n    Enables :pep:`420` style namespace packages.  See the\n    corresponding flag :option:`--no-namespace-packages <mypy --no-namespace-packages>`\n    for more information.\n\n    This option may only be set in the global section (``[mypy]``).\n\n.. confval:: explicit_package_bases\n\n    :type: boolean\n    :default: False\n\n    This flag tells mypy that top-level packages will be based in either the\n    current directory, or a member of the ``MYPYPATH`` environment variable or\n    :confval:`mypy_path` config option. This option is only useful in\n    the absence of `__init__.py`. See :ref:`Mapping file\n    paths to modules <mapping-paths-to-modules>` for details.\n\n    This option may only be set in the global section (``[mypy]``).\n\n.. confval:: ignore_missing_imports\n\n    :type: boolean\n    :default: False\n\n    Suppresses error messages about imports that cannot be resolved.\n\n    If this option is used in a per-module section, the module name should\n    match the name of the *imported* module, not the module containing the\n    import statement.\n\n.. confval:: follow_untyped_imports\n\n    :type: boolean\n    :default: False\n\n    Makes mypy analyze imports from installed packages even if missing a\n    :ref:`py.typed marker or stubs <installed-packages>`.\n\n    If this option is used in a per-module section, the module name should\n    match the name of the *imported* module, not the module containing the\n    import statement.\n\n    .. warning::\n\n        Note that analyzing all unannotated modules might result in issues\n        when analyzing code not designed to be type checked and may significantly\n        increase how long mypy takes to run.\n\n.. confval:: follow_imports\n\n    :type: string\n    :default: ``normal``\n\n    Directs what to do with imports when the imported module is found\n    as a ``.py`` file and not part of the files, modules and packages\n    provided on the command line.\n\n    The four possible values are ``normal``, ``silent``, ``skip`` and\n    ``error``.  For explanations see the discussion for the\n    :option:`--follow-imports <mypy --follow-imports>` command line flag.\n\n    Using this option in a per-module section (potentially with a wildcard,\n    as described at the top of this page) is a good way to prevent mypy from\n    checking portions of your code.\n\n    If this option is used in a per-module section, the module name should\n    match the name of the *imported* module, not the module containing the\n    import statement.\n\n.. confval:: follow_imports_for_stubs\n\n    :type: boolean\n    :default: False\n\n    Determines whether to respect the :confval:`follow_imports` setting even for\n    stub (``.pyi``) files.\n\n    Used in conjunction with :confval:`follow_imports=skip <follow_imports>`, this can be used\n    to suppress the import of a module from ``typeshed``, replacing it\n    with ``Any``.\n\n    Used in conjunction with :confval:`follow_imports=error <follow_imports>`, this can be used\n    to make any use of a particular ``typeshed`` module an error.\n\n    .. note::\n\n         This is not supported by the mypy daemon.\n\n.. confval:: python_executable\n\n    :type: string\n\n    Specifies the path to the Python executable to inspect to collect\n    a list of available :ref:`PEP 561 packages <installed-packages>`. User\n    home directory and environment variables will be expanded. Defaults to\n    the executable used to run mypy.\n\n    This option may only be set in the global section (``[mypy]``).\n\n.. confval:: no_site_packages\n\n    :type: boolean\n    :default: False\n\n    Disables using type information in installed packages (see :pep:`561`).\n    This will also disable searching for a usable Python executable. This acts\n    the same as :option:`--no-site-packages <mypy --no-site-packages>` command\n    line flag.\n\n.. confval:: no_silence_site_packages\n\n    :type: boolean\n    :default: False\n\n    Enables reporting error messages generated within installed packages (see\n    :pep:`561` for more details on distributing type information). Those error\n    messages are suppressed by default, since you are usually not able to\n    control errors in 3rd party code.\n\n    This option may only be set in the global section (``[mypy]``).\n\n\nPlatform configuration\n**********************\n\n.. confval:: python_version\n\n    :type: string\n\n    Specifies the Python version used to parse and check the target\n    program.  The string should be in the format ``MAJOR.MINOR`` --\n    for example ``3.9``.  The default is the version of the Python\n    interpreter used to run mypy.\n\n    This option may only be set in the global section (``[mypy]``).\n\n.. confval:: platform\n\n    :type: string\n\n    Specifies the OS platform for the target program, for example\n    ``darwin`` or ``win32`` (meaning OS X or Windows, respectively).\n    The default is the current platform as revealed by Python's\n    :py:data:`sys.platform` variable.\n\n    This option may only be set in the global section (``[mypy]``).\n\n.. confval:: always_true\n\n    :type: comma-separated list of strings\n\n    Specifies a list of variables that mypy will treat as\n    compile-time constants that are always true.\n\n.. confval:: always_false\n\n    :type: comma-separated list of strings\n\n    Specifies a list of variables that mypy will treat as\n    compile-time constants that are always false.\n\n\nDisallow dynamic typing\n***********************\n\nFor more information, see the :ref:`Disallow dynamic typing <disallow-dynamic-typing>`\nsection of the command line docs.\n\n.. confval:: disallow_any_unimported\n\n    :type: boolean\n    :default: False\n\n    Disallows usage of types that come from unfollowed imports (anything imported from\n    an unfollowed import is automatically given a type of ``Any``).\n\n.. confval:: disallow_any_expr\n\n    :type: boolean\n    :default: False\n\n    Disallows all expressions in the module that have type ``Any``.\n\n.. confval:: disallow_any_decorated\n\n    :type: boolean\n    :default: False\n\n    Disallows functions that have ``Any`` in their signature after decorator transformation.\n\n.. confval:: disallow_any_explicit\n\n    :type: boolean\n    :default: False\n\n    Disallows explicit ``Any`` in type positions such as type annotations and generic\n    type parameters.\n\n.. confval:: disallow_any_generics\n\n    :type: boolean\n    :default: False\n\n    Disallows usage of generic types that do not specify explicit type parameters.\n\n.. confval:: disallow_subclassing_any\n\n    :type: boolean\n    :default: False\n\n    Disallows subclassing a value of type ``Any``.\n\n\nUntyped definitions and calls\n*****************************\n\nFor more information, see the :ref:`Untyped definitions and calls <untyped-definitions-and-calls>`\nsection of the command line docs.\n\n.. confval:: disallow_untyped_calls\n\n    :type: boolean\n    :default: False\n\n    Disallows calling functions without type annotations from functions with type\n    annotations. Note that when used in per-module options, it enables/disables\n    this check **inside** the module(s) specified, not for functions that come\n    from that module(s), for example config like this:\n\n    .. code-block:: ini\n\n        [mypy]\n        disallow_untyped_calls = True\n\n        [mypy-some.library.*]\n        disallow_untyped_calls = False\n\n    will disable this check inside ``some.library``, not for your code that\n    imports ``some.library``. If you want to selectively disable this check for\n    all your code that imports ``some.library`` you should instead use\n    :confval:`untyped_calls_exclude`, for example:\n\n    .. code-block:: ini\n\n        [mypy]\n        disallow_untyped_calls = True\n        untyped_calls_exclude = some.library\n\n.. confval:: untyped_calls_exclude\n\n    :type: comma-separated list of strings\n\n    Selectively excludes functions and methods defined in specific packages,\n    modules, and classes from action of :confval:`disallow_untyped_calls`.\n    This also applies to all submodules of packages (i.e. everything inside\n    a given prefix). Note, this option does not support per-file configuration,\n    the exclusions list is defined globally for all your code.\n\n.. confval:: disallow_untyped_defs\n\n    :type: boolean\n    :default: False\n\n    Disallows defining functions without type annotations or with incomplete type\n    annotations (a superset of :confval:`disallow_incomplete_defs`).\n\n    For example, it would report an error for :code:`def f(a, b)` and :code:`def f(a: int, b)`.\n\n.. confval:: disallow_incomplete_defs\n\n    :type: boolean\n    :default: False\n\n    Disallows defining functions with incomplete type annotations, while still\n    allowing entirely unannotated definitions.\n\n    For example, it would report an error for :code:`def f(a: int, b)` but not :code:`def f(a, b)`.\n\n.. confval:: check_untyped_defs\n\n    :type: boolean\n    :default: False\n\n    Type-checks the interior of functions without type annotations.\n\n.. confval:: disallow_untyped_decorators\n\n    :type: boolean\n    :default: False\n\n    Reports an error whenever a function with type annotations is decorated with a\n    decorator without annotations.\n\n\n.. _config-file-none-and-optional-handling:\n\nNone and Optional handling\n**************************\n\nFor more information, see the :ref:`None and Optional handling <none-and-optional-handling>`\nsection of the command line docs.\n\n.. confval:: implicit_optional\n\n    :type: boolean\n    :default: False\n\n    Causes mypy to treat parameters with a ``None``\n    default value as having an implicit optional type (``T | None``).\n\n    **Note:** This was True by default in mypy versions 0.980 and earlier.\n\n.. confval:: strict_optional\n\n    :type: boolean\n    :default: True\n\n    Effectively disables checking of optional\n    types and ``None`` values. With this option, mypy doesn't\n    generally check the use of ``None`` values -- it is treated\n    as compatible with every type.\n\n    .. warning::\n\n        ``strict_optional = false`` is evil. Avoid using it and definitely do\n        not use it without understanding what it does.\n\n\nConfiguring warnings\n********************\n\nFor more information, see the :ref:`Configuring warnings <configuring-warnings>`\nsection of the command line docs.\n\n.. confval:: warn_redundant_casts\n\n    :type: boolean\n    :default: False\n\n    Warns about casting an expression to its inferred type.\n\n    This option may only be set in the global section (``[mypy]``).\n\n.. confval:: warn_unused_ignores\n\n    :type: boolean\n    :default: False\n\n    Warns about unneeded ``# type: ignore`` comments.\n\n.. confval:: warn_no_return\n\n    :type: boolean\n    :default: True\n\n    Shows errors for missing return statements on some execution paths.\n\n.. confval:: warn_return_any\n\n    :type: boolean\n    :default: False\n\n    Shows a warning when returning a value with type ``Any`` from a function\n    declared with a non- ``Any`` return type.\n\n.. confval:: warn_unreachable\n\n    :type: boolean\n    :default: False\n\n    Shows a warning when encountering any code inferred to be unreachable or\n    redundant after performing type analysis.\n\n.. confval:: deprecated_calls_exclude\n\n    :type: comma-separated list of strings\n\n    Selectively excludes functions and methods defined in specific packages,\n    modules, and classes from the :ref:`deprecated<code-deprecated>` error code.\n    This also applies to all submodules of packages (i.e. everything inside\n    a given prefix). Note, this option does not support per-file configuration,\n    the exclusions list is defined globally for all your code.\n\n\nSuppressing errors\n******************\n\nNote: these configuration options are available in the config file only. There is\nno analog available via the command line options.\n\n.. confval:: ignore_errors\n\n    :type: boolean\n    :default: False\n\n    Ignores all non-fatal errors.\n\n\nMiscellaneous strictness flags\n******************************\n\nFor more information, see the :ref:`Miscellaneous strictness flags <miscellaneous-strictness-flags>`\nsection of the command line docs.\n\n.. confval:: allow_untyped_globals\n\n    :type: boolean\n    :default: False\n\n    Causes mypy to suppress errors caused by not being able to fully\n    infer the types of global and class variables.\n\n.. confval:: allow_redefinition_new\n\n    :type: boolean\n    :default: False\n\n    By default, mypy won't allow a variable to be redefined with an\n    unrelated type. This flag enables the redefinition of unannotated\n    variables with an arbitrary type. You will also need to enable\n    :confval:`local_partial_types`.\n    Example:\n\n    .. code-block:: python\n\n        def maybe_convert(n: int, b: bool) -> int | str:\n            if b:\n                x = str(n)  # Assign \"str\"\n            else:\n                x = n       # Assign \"int\"\n            # Type of \"x\" is \"int | str\" here.\n            return x\n\n    This also enables an unannotated variable to have different types in different\n    code locations:\n\n    .. code-block:: python\n\n        if check():\n            for x in range(n):\n                # Type of \"x\" is \"int\" here.\n                ...\n        else:\n            for x in ['a', 'b']:\n                # Type of \"x\" is \"str\" here.\n                ...\n\n    Function arguments are special, changing their type within function body\n    is allowed even if they are annotated, but that annotation is used to infer\n    types of r.h.s. of all subsequent assignments. Such middle-ground semantics\n    provides good balance for majority of common use cases. For example:\n\n    .. code-block:: python\n\n        def process(values: list[float]) -> None:\n            if not values:\n                values = [0, 0, 0]\n            reveal_type(values)  # Revealed type is list[float]\n\n    Note: We are planning to turn this flag on by default in a future mypy\n    release, along with :confval:`local_partial_types`.\n\n.. confval:: allow_redefinition_old\n\n    :type: boolean\n    :default: False\n\n    Allows variables to be redefined with an arbitrary type, as long as the redefinition\n    is in the same block and nesting level as the original definition.\n    Example where this can be useful:\n\n    .. code-block:: python\n\n       def process(items: list[str]) -> None:\n           # 'items' has type list[str]\n           items = [item.split() for item in items]\n           # 'items' now has type list[list[str]]\n\n    The variable must be used before it can be redefined:\n\n    .. code-block:: python\n\n        def process(items: list[str]) -> None:\n           items = \"mypy\"  # invalid redefinition to str because the variable hasn't been used yet\n           print(items)\n           items = \"100\"  # valid, items now has type str\n           items = int(items)  # valid, items now has type int\n\n.. confval:: allow_redefinition\n\n    :type: boolean\n    :default: False\n\n    An alias to :confval:`allow_redefinition_old`, in mypy v2.0 this will point to\n    :confval:`allow_redefinition_new`, and will eventually became the default.\n\n.. confval:: local_partial_types\n\n    :type: boolean\n    :default: False\n\n    Disallows inferring variable type for ``None`` from two assignments in different scopes.\n    This is always implicitly enabled when using the :ref:`mypy daemon <mypy_daemon>`.\n    This will be enabled by default in mypy v2.0 release.\n\n.. confval:: disable_error_code\n\n    :type: comma-separated list of strings\n\n    Allows disabling one or multiple error codes globally.\n\n.. confval:: enable_error_code\n\n    :type: comma-separated list of strings\n\n    Allows enabling one or multiple error codes globally.\n\n    Note: This option will override disabled error codes from the disable_error_code option.\n\n.. confval:: extra_checks\n\n   :type: boolean\n   :default: False\n\n   This flag enables additional checks that are technically correct but may be impractical.\n   See :option:`mypy --extra-checks` for more info.\n\n.. confval:: implicit_reexport\n\n    :type: boolean\n    :default: True\n\n    By default, imported values to a module are treated as exported and mypy allows\n    other modules to import them. When false, mypy will not re-export unless\n    the item is imported using from-as or is included in ``__all__``. Note that mypy\n    treats stub files as if this is always disabled. For example:\n\n    .. code-block:: python\n\n       # This won't re-export the value\n       from foo import bar\n       # This will re-export it as bar and allow other modules to import it\n       from foo import bar as bar\n       # This will also re-export bar\n       from foo import bar\n       __all__ = ['bar']\n\n.. confval:: strict_equality\n\n   :type: boolean\n   :default: False\n\n   Prohibit equality checks, identity checks, and container checks between\n   non-overlapping types (except ``None``).\n\n.. confval:: strict_equality_for_none\n\n   :type: boolean\n   :default: False\n\n   Include ``None`` in strict equality checks (requires :confval:`strict_equality`\n   to be activated).\n\n.. confval:: strict_bytes\n\n   :type: boolean\n   :default: False\n\n   Disable treating ``bytearray`` and ``memoryview`` as subtypes of ``bytes``.\n   This will be enabled by default in *mypy 2.0*.\n\n.. confval:: strict\n\n   :type: boolean\n   :default: False\n\n   Enable all optional error checking flags.  You can see the list of\n   flags enabled by strict mode in the full :option:`mypy --help`\n   output.\n\n   Note: the exact list of flags enabled by :confval:`strict` may\n   change over time.\n\n\nConfiguring error messages\n**************************\n\nFor more information, see the :ref:`Configuring error messages <configuring-error-messages>`\nsection of the command line docs.\n\nThese options may only be set in the global section (``[mypy]``).\n\n.. confval:: show_error_context\n\n    :type: boolean\n    :default: False\n\n    Prefixes each error with the relevant context.\n\n.. confval:: show_column_numbers\n\n    :type: boolean\n    :default: False\n\n    Shows column numbers in error messages.\n\n.. confval:: show_error_code_links\n\n    :type: boolean\n    :default: False\n\n    Shows documentation link to corresponding error code.\n\n.. confval:: hide_error_codes\n\n    :type: boolean\n    :default: False\n\n    Hides error codes in error messages. See :ref:`error-codes` for more information.\n\n.. confval:: pretty\n\n    :type: boolean\n    :default: False\n\n    Use visually nicer output in error messages: use soft word wrap,\n    show source code snippets, and show error location markers.\n\n.. confval:: color_output\n\n    :type: boolean\n    :default: True\n\n    Shows error messages with color enabled.\n\n.. confval:: error_summary\n\n    :type: boolean\n    :default: True\n\n    Shows a short summary line after error messages.\n\n.. confval:: show_absolute_path\n\n    :type: boolean\n    :default: False\n\n    Show absolute paths to files.\n\nIncremental mode\n****************\n\nThese options may only be set in the global section (``[mypy]``).\n\n.. confval:: incremental\n\n    :type: boolean\n    :default: True\n\n    Enables :ref:`incremental mode <incremental>`.\n\n.. confval:: cache_dir\n\n    :type: string\n    :default: ``.mypy_cache``\n\n    Specifies the location where mypy stores incremental cache info.\n    User home directory and environment variables will be expanded.\n    This setting will be overridden by the ``MYPY_CACHE_DIR`` environment\n    variable.\n\n    Note that the cache is only read when incremental mode is enabled\n    but is always written to, unless the value is set to ``/dev/null``\n    (UNIX) or ``nul`` (Windows).\n\n.. confval:: sqlite_cache\n\n    :type: boolean\n    :default: True\n\n    Use an `SQLite`_ database to store the cache.\n\n.. confval:: cache_fine_grained\n\n    :type: boolean\n    :default: False\n\n    Include fine-grained dependency information in the cache for the mypy daemon.\n\n.. confval:: skip_version_check\n\n    :type: boolean\n    :default: False\n\n    Makes mypy use incremental cache data even if it was generated by a\n    different version of mypy. (By default, mypy will perform a version\n    check and regenerate the cache if it was written by older versions of mypy.)\n\n.. confval:: skip_cache_mtime_checks\n\n    :type: boolean\n    :default: False\n\n    Skip cache internal consistency checks based on mtime.\n\n\nAdvanced options\n****************\n\nThese options may only be set in the global section (``[mypy]``).\n\n.. confval:: plugins\n\n    :type: comma-separated list of strings\n\n    A comma-separated list of mypy plugins. See :ref:`extending-mypy-using-plugins`.\n\n.. confval:: pdb\n\n    :type: boolean\n    :default: False\n\n    Invokes :mod:`pdb` on fatal error.\n\n.. confval:: show_traceback\n\n    :type: boolean\n    :default: False\n\n    Shows traceback on fatal error.\n\n.. confval:: raise_exceptions\n\n    :type: boolean\n    :default: False\n\n    Raise exception on fatal error.\n\n.. confval:: custom_typing_module\n\n    :type: string\n\n    Specifies a custom module to use as a substitute for the :py:mod:`typing` module.\n\n.. confval:: custom_typeshed_dir\n\n    :type: string\n\n    This specifies the directory where mypy looks for standard library typeshed\n    stubs, instead of the typeshed that ships with mypy.  This is\n    primarily intended to make it easier to test typeshed changes before\n    submitting them upstream, but also allows you to use a forked version of\n    typeshed.\n\n    User home directory and environment variables will be expanded.\n\n    Note that this doesn't affect third-party library stubs. To test third-party stubs,\n    for example try ``MYPYPATH=stubs/six mypy ...``.\n\n.. confval:: warn_incomplete_stub\n\n    :type: boolean\n    :default: False\n\n    Warns about missing type annotations in typeshed.  This is only relevant\n    in combination with :confval:`disallow_untyped_defs` or :confval:`disallow_incomplete_defs`.\n\n\nReport generation\n*****************\n\nIf these options are set, mypy will generate a report in the specified\nformat into the specified directory.\n\n.. warning::\n\n  Generating reports disables incremental mode and can significantly slow down\n  your workflow. It is recommended to enable reporting only for specific runs\n  (e.g. in CI).\n\n.. confval:: any_exprs_report\n\n    :type: string\n\n    Causes mypy to generate a text file report documenting how many\n    expressions of type ``Any`` are present within your codebase.\n\n.. confval:: cobertura_xml_report\n\n    :type: string\n\n    Causes mypy to generate a Cobertura XML type checking coverage report.\n\n    To generate this report, you must either manually install the `lxml`_\n    library or specify mypy installation with the setuptools extra\n    ``mypy[reports]``.\n\n.. confval:: html_report / xslt_html_report\n\n    :type: string\n\n    Causes mypy to generate an HTML type checking coverage report.\n\n    To generate this report, you must either manually install the `lxml`_\n    library or specify mypy installation with the setuptools extra\n    ``mypy[reports]``.\n\n.. confval:: linecount_report\n\n    :type: string\n\n    Causes mypy to generate a text file report documenting the functions\n    and lines that are typed and untyped within your codebase.\n\n.. confval:: linecoverage_report\n\n    :type: string\n\n    Causes mypy to generate a JSON file that maps each source file's\n    absolute filename to a list of line numbers that belong to typed\n    functions in that file.\n\n.. confval:: lineprecision_report\n\n    :type: string\n\n    Causes mypy to generate a flat text file report with per-module\n    statistics of how many lines are typechecked etc.\n\n.. confval:: txt_report / xslt_txt_report\n\n    :type: string\n\n    Causes mypy to generate a text file type checking coverage report.\n\n    To generate this report, you must either manually install the `lxml`_\n    library or specify mypy installation with the setuptools extra\n    ``mypy[reports]``.\n\n.. confval:: xml_report\n\n    :type: string\n\n    Causes mypy to generate an XML type checking coverage report.\n\n    To generate this report, you must either manually install the `lxml`_\n    library or specify mypy installation with the setuptools extra\n    ``mypy[reports]``.\n\n\nMiscellaneous\n*************\n\nThese options may only be set in the global section (``[mypy]``).\n\n.. confval:: junit_xml\n\n    :type: string\n\n    Causes mypy to generate a JUnit XML test result document with\n    type checking results. This can make it easier to integrate mypy\n    with continuous integration (CI) tools.\n\n.. confval:: junit_format\n\n    :type: string\n    :default: ``global``\n\n    If junit_xml is set, specifies format.\n    global (default): single test with all errors;\n    per_file: one test entry per file with failures.\n\n.. confval:: scripts_are_modules\n\n    :type: boolean\n    :default: False\n\n    Makes script ``x`` become module ``x`` instead of ``__main__``.  This is\n    useful when checking multiple scripts in a single run.\n\n.. confval:: warn_unused_configs\n\n    :type: boolean\n    :default: False\n\n    Warns about per-module sections in the config file that do not\n    match any files processed when invoking mypy.\n    (This requires turning off incremental mode using :confval:`incremental = False <incremental>`.)\n\n.. confval:: verbosity\n\n    :type: integer\n    :default: 0\n\n    Controls how much debug output will be generated.  Higher numbers are more verbose.\n\n\n.. _using-a-pyproject-toml:\n\nUsing a pyproject.toml file\n***************************\n\nInstead of using a ``mypy.ini`` file, a ``pyproject.toml`` file (as specified by\n`PEP 518`_) may be used instead. A few notes on doing so:\n\n* The ``[mypy]`` section should have ``tool.`` prepended to its name:\n\n  * I.e., ``[mypy]`` would become ``[tool.mypy]``\n\n* The module specific sections should be moved into ``[[tool.mypy.overrides]]`` sections:\n\n  * For example, ``[mypy-packagename]`` would become:\n\n.. code-block:: toml\n\n  [[tool.mypy.overrides]]\n  module = 'packagename'\n  ...\n\n* Multi-module specific sections can be moved into a single ``[[tool.mypy.overrides]]`` section with a\n  module property set to an array of modules:\n\n  * For example, ``[mypy-packagename,packagename2]`` would become:\n\n.. code-block:: toml\n\n  [[tool.mypy.overrides]]\n  module = [\n      'packagename',\n      'packagename2'\n  ]\n  ...\n\n* The following care should be given to values in the ``pyproject.toml`` files as compared to ``ini`` files:\n\n  * Strings must be wrapped in double quotes, or single quotes if the string contains special characters\n\n  * Boolean values should be all lower case\n\nPlease see the `TOML Documentation`_ for more details and information on\nwhat is allowed in a ``toml`` file. See `PEP 518`_ for more information on the layout\nand structure of the ``pyproject.toml`` file.\n\nExample ``pyproject.toml``\n**************************\n\nHere is an example of a ``pyproject.toml`` file. To use this config file, place it at the root\nof your repo (or append it to the end of an existing ``pyproject.toml`` file) and run mypy.\n\n.. code-block:: toml\n\n    # mypy global options:\n\n    [tool.mypy]\n    python_version = \"3.9\"\n    warn_return_any = true\n    warn_unused_configs = true\n    exclude = [\n        '^file1\\.py$',  # TOML literal string (single-quotes, no escaping necessary)\n        \"^file2\\\\.py$\",  # TOML basic string (double-quotes, backslash and other characters need escaping)\n    ]\n\n    # mypy per-module options:\n\n    [[tool.mypy.overrides]]\n    module = \"mycode.foo.*\"\n    disallow_untyped_defs = true\n\n    [[tool.mypy.overrides]]\n    module = \"mycode.bar\"\n    warn_return_any = false\n\n    [[tool.mypy.overrides]]\n    module = [\n        \"somelibrary\",\n        \"some_other_library\"\n    ]\n    ignore_missing_imports = true\n\n.. _lxml: https://pypi.org/project/lxml/\n.. _SQLite: https://www.sqlite.org/\n.. _PEP 518: https://www.python.org/dev/peps/pep-0518/\n.. _TOML Documentation: https://toml.io/\n"
  },
  {
    "path": "docs/source/duck_type_compatibility.rst",
    "content": "Duck type compatibility\n-----------------------\n\nIn Python, certain types are compatible even though they aren't subclasses of\neach other. For example, ``int`` objects are valid whenever ``float`` objects\nare expected. Mypy supports this idiom via *duck type compatibility*. This is\nsupported for a small set of built-in types:\n\n* ``int`` is duck type compatible with ``float`` and ``complex``.\n* ``float`` is duck type compatible with ``complex``.\n* ``bytearray`` and ``memoryview`` are duck type compatible with ``bytes``.\n  (this will be disabled by default in **mypy 2.0**, and currently can be\n  disabled with :option:`--strict-bytes <mypy --strict-bytes>`.)\n\nFor example, mypy considers an ``int`` object to be valid whenever a\n``float`` object is expected.  Thus code like this is nice and clean\nand also behaves as expected:\n\n.. code-block:: python\n\n   import math\n\n   def degrees_to_radians(degrees: float) -> float:\n       return math.pi * degrees / 180\n\n   n = 90  # Inferred type 'int'\n   print(degrees_to_radians(n))  # Okay!\n\nYou can also often use :ref:`protocol-types` to achieve a similar effect in\na more principled and extensible fashion. Protocols don't apply to\ncases like ``int`` being compatible with ``float``, since ``float`` is not\na protocol class but a regular, concrete class, and many standard library\nfunctions expect concrete instances of ``float`` (or ``int``).\n"
  },
  {
    "path": "docs/source/dynamic_typing.rst",
    "content": ".. _dynamic-typing:\n\nDynamically typed code\n======================\n\nIn :ref:`getting-started-dynamic-vs-static`, we discussed how bodies of functions\nthat don't have any explicit type annotations in their function are \"dynamically typed\"\nand that mypy will not check them. In this section, we'll talk a little bit more\nabout what that means and how you can enable dynamic typing on a more fine grained basis.\n\nIn cases where your code is too magical for mypy to understand, you can make a\nvariable or parameter dynamically typed by explicitly giving it the type\n``Any``. Mypy will let you do basically anything with a value of type ``Any``,\nincluding assigning a value of type ``Any`` to a variable of any type (or vice\nversa).\n\n.. code-block:: python\n\n   from typing import Any\n\n   num = 1         # Statically typed (inferred to be int)\n   num = 'x'       # error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n   dyn: Any = 1    # Dynamically typed (type Any)\n   dyn = 'x'       # OK\n\n   num = dyn       # No error, mypy will let you assign a value of type Any to any variable\n   num += 1        # Oops, mypy still thinks num is an int\n\nYou can think of ``Any`` as a way to locally disable type checking.\nSee :ref:`silencing-type-errors` for other ways you can shut up\nthe type checker.\n\nOperations on Any values\n------------------------\n\nYou can do anything using a value with type ``Any``, and the type checker\nwill not complain:\n\n.. code-block:: python\n\n    def f(x: Any) -> int:\n        # All of these are valid!\n        x.foobar(1, y=2)\n        print(x[3] + 'f')\n        if x:\n            x.z = x(2)\n        open(x).read()\n        return x\n\nValues derived from an ``Any`` value also usually have the type ``Any``\nimplicitly, as mypy can't infer a more precise result type. For\nexample, if you get the attribute of an ``Any`` value or call a\n``Any`` value the result is ``Any``:\n\n.. code-block:: python\n\n    def f(x: Any) -> None:\n        y = x.foo()\n        reveal_type(y)  # Revealed type is \"Any\"\n        z = y.bar(\"mypy will let you do anything to y\")\n        reveal_type(z)  # Revealed type is \"Any\"\n\n``Any`` types may propagate through your program, making type checking\nless effective, unless you are careful.\n\nFunction parameters without annotations are also implicitly ``Any``:\n\n.. code-block:: python\n\n    def f(x) -> None:\n        reveal_type(x)  # Revealed type is \"Any\"\n        x.can.do[\"anything\", x](\"wants\", 2)\n\nYou can make mypy warn you about untyped function parameters using the\n:option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>` flag.\n\nGeneric types missing type parameters will have those parameters implicitly\ntreated as ``Any``:\n\n.. code-block:: python\n\n    def f(x: list) -> None:\n        reveal_type(x)        # Revealed type is \"builtins.list[Any]\"\n        reveal_type(x[0])     # Revealed type is \"Any\"\n        x[0].anything_goes()  # OK\n\nYou can make mypy warn you about missing generic parameters using the\n:option:`--disallow-any-generics <mypy --disallow-any-generics>` flag.\n\nFinally, another major source of ``Any`` types leaking into your program is from\nthird party libraries that mypy does not know about. This is particularly the case\nwhen using the :option:`--ignore-missing-imports <mypy --ignore-missing-imports>`\nflag. See :ref:`fix-missing-imports` for more information about this.\n\n.. _any-vs-object:\n\nAny vs. object\n--------------\n\nThe type :py:class:`object` is another type that can have an instance of arbitrary\ntype as a value. Unlike ``Any``, :py:class:`object` is an ordinary static type (it\nis similar to ``Object`` in Java), and only operations valid for *all*\ntypes are accepted for :py:class:`object` values. These are all valid:\n\n.. code-block:: python\n\n    def f(o: object) -> None:\n        if o:\n            print(o)\n        print(isinstance(o, int))\n        o = 2\n        o = 'foo'\n\nThese are, however, flagged as errors, since not all objects support these\noperations:\n\n.. code-block:: python\n\n    def f(o: object) -> None:\n        o.foo()       # Error!\n        o + 2         # Error!\n        open(o)       # Error!\n        n: int = 1\n        n = o         # Error!\n\n\nIf you're not sure whether you need to use :py:class:`object` or ``Any``, use\n:py:class:`object` -- only switch to using ``Any`` if you get a type checker\ncomplaint.\n\nYou can use different :ref:`type narrowing <type-narrowing>`\ntechniques to narrow :py:class:`object` to a more specific\ntype (subtype) such as ``int``. Type narrowing is not needed with\ndynamically typed values (values with type ``Any``).\n"
  },
  {
    "path": "docs/source/error_code_list.rst",
    "content": ".. _error-code-list:\n\nError codes enabled by default\n==============================\n\nThis section documents various errors codes that mypy can generate\nwith default options. See :ref:`error-codes` for general documentation\nabout error codes. :ref:`error-codes-optional` documents additional\nerror codes that you can enable.\n\n.. _code-attr-defined:\n\nCheck that attribute exists [attr-defined]\n------------------------------------------\n\nMypy checks that an attribute is defined in the target class or module\nwhen using the dot operator. This applies to both getting and setting\nan attribute. New attributes are defined by assignments in the class\nbody, or assignments to ``self.x`` in methods. These assignments don't\ngenerate ``attr-defined`` errors.\n\nExample:\n\n.. code-block:: python\n\n   class Resource:\n       def __init__(self, name: str) -> None:\n           self.name = name\n\n   r = Resource('x')\n   print(r.name)  # OK\n   print(r.id)  # Error: \"Resource\" has no attribute \"id\"  [attr-defined]\n   r.id = 5  # Error: \"Resource\" has no attribute \"id\"  [attr-defined]\n\nThis error code is also generated if an imported name is not defined\nin the module in a ``from ... import`` statement (as long as the\ntarget module can be found):\n\n.. code-block:: python\n\n    # Error: Module \"os\" has no attribute \"non_existent\"  [attr-defined]\n    from os import non_existent\n\nA reference to a missing attribute is given the ``Any`` type. In the\nabove example, the type of ``non_existent`` will be ``Any``, which can\nbe important if you silence the error.\n\n.. _code-union-attr:\n\nCheck that attribute exists in each union item [union-attr]\n-----------------------------------------------------------\n\nIf you access the attribute of a value with a union type, mypy checks\nthat the attribute is defined for *every* type in that\nunion. Otherwise the operation can fail at runtime. This also applies\nto optional types.\n\nExample:\n\n.. code-block:: python\n\n   class Cat:\n       def sleep(self) -> None: ...\n       def miaow(self) -> None: ...\n\n   class Dog:\n       def sleep(self) -> None: ...\n       def follow_me(self) -> None: ...\n\n   def func(animal: Cat | Dog) -> None:\n       # OK: 'sleep' is defined for both Cat and Dog\n       animal.sleep()\n       # Error: Item \"Cat\" of \"Cat | Dog\" has no attribute \"follow_me\"  [union-attr]\n       animal.follow_me()\n\nYou can often work around these errors by using ``assert isinstance(obj, ClassName)``\nor ``assert obj is not None`` to tell mypy that you know that the type is more specific\nthan what mypy thinks.\n\n.. _code-name-defined:\n\nCheck that name is defined [name-defined]\n-----------------------------------------\n\nMypy expects that all references to names have a corresponding\ndefinition in an active scope, such as an assignment, function\ndefinition or an import. This can catch missing definitions, missing\nimports, and typos.\n\nThis example accidentally calls ``sort()`` instead of :py:func:`sorted`:\n\n.. code-block:: python\n\n    x = sort([3, 2, 4])  # Error: Name \"sort\" is not defined  [name-defined]\n\n.. _code-used-before-def:\n\nCheck that a variable is not used before it's defined [used-before-def]\n-----------------------------------------------------------------------\n\nMypy will generate an error if a name is used before it's defined.\nWhile the name-defined check will catch issues with names that are undefined,\nit will not flag if a variable is used and then defined later in the scope.\nused-before-def check will catch such cases.\n\nExample:\n\n.. code-block:: python\n\n    print(x)  # Error: Name \"x\" is used before definition [used-before-def]\n    x = 123\n\n.. _code-call-arg:\n\nCheck arguments in calls [call-arg]\n-----------------------------------\n\nMypy expects that the number and names of arguments match the called function.\nNote that argument type checks have a separate error code ``arg-type``.\n\nExample:\n\n.. code-block:: python\n\n    def greet(name: str) -> None:\n         print('hello', name)\n\n    greet('jack')  # OK\n    greet('jill', 'jack')  # Error: Too many arguments for \"greet\"  [call-arg]\n\n.. _code-arg-type:\n\nCheck argument types [arg-type]\n-------------------------------\n\nMypy checks that argument types in a call match the declared argument\ntypes in the signature of the called function (if one exists).\n\nExample:\n\n.. code-block:: python\n\n    def first(x: list[int]) -> int:\n        return x[0] if x else 0\n\n    t = (5, 4)\n    # Error: Argument 1 to \"first\" has incompatible type \"tuple[int, int]\";\n    #        expected \"list[int]\"  [arg-type]\n    print(first(t))\n\n.. _code-call-overload:\n\nCheck calls to overloaded functions [call-overload]\n---------------------------------------------------\n\nWhen you call an overloaded function, mypy checks that at least one of\nthe signatures of the overload items match the argument types in the\ncall.\n\nExample:\n\n.. code-block:: python\n\n   from typing import overload\n\n   @overload\n   def inc_maybe(x: None) -> None: ...\n\n   @overload\n   def inc_maybe(x: int) -> int: ...\n\n   def inc_maybe(x: int | None) -> int | None:\n        if x is None:\n            return None\n        else:\n            return x + 1\n\n   inc_maybe(None)  # OK\n   inc_maybe(5)  # OK\n\n   # Error: No overload variant of \"inc_maybe\" matches argument type \"float\"  [call-overload]\n   inc_maybe(1.2)\n\n.. _code-valid-type:\n\nCheck validity of types [valid-type]\n------------------------------------\n\nMypy checks that each type annotation and any expression that\nrepresents a type is a valid type. Examples of valid types include\nclasses, union types, callable types, type aliases, and literal types.\nExamples of invalid types include bare integer literals, functions,\nvariables, and modules.\n\nThis example incorrectly uses the function ``log`` as a type:\n\n.. code-block:: python\n\n    def log(x: object) -> None:\n        print('log:', repr(x))\n\n    # Error: Function \"t.log\" is not valid as a type  [valid-type]\n    def log_all(objs: list[object], f: log) -> None:\n        for x in objs:\n            f(x)\n\nYou can use :py:class:`~collections.abc.Callable` as the type for callable objects:\n\n.. code-block:: python\n\n    from collections.abc import Callable\n\n    # OK\n    def log_all(objs: list[object], f: Callable[[object], None]) -> None:\n        for x in objs:\n            f(x)\n\n.. _code-nonetype-type:\n\nCheck that NoneType is not used as a type (annotation) [nonetype-type]\n----------------------------------------------------------------------\n\nThe preferred way to annotate the type of `None` is `None`.\n`NoneType` is equivalent, but mypy won't allow it by default.\n\n.. code-block:: python\n\n    from types import NoneType\n    def f(x: None) -> None:\n        reveal_type(x) # note: Revealed type is \"None\"\n\n    # error: NoneType should not be used as a type, please use None instead  [nonetype-type]\n    def g(x: NoneType) -> None:\n        reveal_type(x) # note: Revealed type is \"None\"\n\n    # error: NoneType should not be used as a type, please use None instead  [nonetype-type]\n    x1: NoneType = None\n    x2: None = None # OK\n\n.. _code-metaclass:\n\nCheck the validity of a class's metaclass [metaclass]\n-----------------------------------------------------\n\nMypy checks whether the metaclass of a class is valid. The metaclass\nmust be a subclass of ``type``. Further, the class hierarchy must yield\na consistent metaclass. For more details, see the\n`Python documentation <https://docs.python.org/3.13/reference/datamodel.html#determining-the-appropriate-metaclass>`_\n\nNote that mypy's metaclass checking is limited and may produce false-positives.\nSee also :ref:`limitations`.\n\nExample with an error:\n\n.. code-block:: python\n\n    class GoodMeta(type):\n        pass\n\n    class BadMeta:\n        pass\n\n    class A1(metaclass=GoodMeta):  # OK\n        pass\n\n    class A2(metaclass=BadMeta):  # Error:  Metaclasses not inheriting from \"type\" are not supported  [metaclass]\n        pass\n\n.. _code-var-annotated:\n\nRequire annotation if variable type is unclear [var-annotated]\n--------------------------------------------------------------\n\nIn some cases mypy can't infer the type of a variable without an\nexplicit annotation. Mypy treats this as an error. This typically\nhappens when you initialize a variable with an empty collection or\n``None``.  If mypy can't infer the collection item type, mypy replaces\nany parts of the type it couldn't infer with ``Any`` and generates an\nerror.\n\nExample with an error:\n\n.. code-block:: python\n\n    class Bundle:\n        def __init__(self) -> None:\n            # Error: Need type annotation for \"items\"\n            #        (hint: \"items: list[<type>] = ...\")  [var-annotated]\n            self.items = []\n\n    reveal_type(Bundle().items)  # list[Any]\n\nTo address this, we add an explicit annotation:\n\n.. code-block:: python\n\n    class Bundle:\n        def __init__(self) -> None:\n            self.items: list[str] = []  # OK\n\n   reveal_type(Bundle().items)  # list[str]\n\n.. _code-override:\n\nCheck validity of overrides [override]\n--------------------------------------\n\nMypy checks that an overridden method or attribute is compatible with\nthe base class.  A method in a subclass must accept all arguments\nthat the base class method accepts, and the return type must conform\nto the return type in the base class (Liskov substitution principle).\n\nArgument types can be more general is a subclass (i.e., they can vary\ncontravariantly).  The return type can be narrowed in a subclass\n(i.e., it can vary covariantly).  It's okay to define additional\narguments in a subclass method, as long all extra arguments have default\nvalues or can be left out (``*args``, for example).\n\nExample:\n\n.. code-block:: python\n\n   class Base:\n       def method(self,\n                  arg: int) -> int | None:\n           ...\n\n   class Derived(Base):\n       def method(self,\n                  arg: int | str) -> int:  # OK\n           ...\n\n   class DerivedBad(Base):\n       # Error: Argument 1 of \"method\" is incompatible with \"Base\"  [override]\n       def method(self,\n                  arg: bool) -> int:\n           ...\n\n.. _code-return:\n\nCheck that function returns a value [return]\n--------------------------------------------\n\nIf a function has a non-``None`` return type, mypy expects that the\nfunction always explicitly returns a value (or raises an exception).\nThe function should not fall off the end of the function, since this\nis often a bug.\n\nExample:\n\n.. code-block:: python\n\n    # Error: Missing return statement  [return]\n    def show(x: int) -> int:\n        print(x)\n\n    # Error: Missing return statement  [return]\n    def pred1(x: int) -> int:\n        if x > 0:\n            return x - 1\n\n    # OK\n    def pred2(x: int) -> int:\n        if x > 0:\n            return x - 1\n        else:\n            raise ValueError('not defined for zero')\n\n.. _code-empty-body:\n\nCheck that functions don't have empty bodies outside stubs [empty-body]\n-----------------------------------------------------------------------\n\nThis error code is similar to the ``[return]`` code but is emitted specifically\nfor functions and methods with empty bodies (if they are annotated with\nnon-trivial return type). Such a distinction exists because in some contexts\nan empty body can be valid, for example for an abstract method or in a stub\nfile. Also old versions of mypy used to unconditionally allow functions with\nempty bodies, so having a dedicated error code simplifies cross-version\ncompatibility.\n\nNote that empty bodies are allowed for methods in *protocols*, and such methods\nare considered implicitly abstract:\n\n.. code-block:: python\n\n   from abc import abstractmethod\n   from typing import Protocol\n\n   class RegularABC:\n       @abstractmethod\n       def foo(self) -> int:\n           pass  # OK\n       def bar(self) -> int:\n           pass  # Error: Missing return statement  [empty-body]\n\n   class Proto(Protocol):\n       def bar(self) -> int:\n           pass  # OK\n\n.. _code-return-value:\n\nCheck that return value is compatible [return-value]\n----------------------------------------------------\n\nMypy checks that the returned value is compatible with the type\nsignature of the function.\n\nExample:\n\n.. code-block:: python\n\n   def func(x: int) -> str:\n       # Error: Incompatible return value type (got \"int\", expected \"str\")  [return-value]\n       return x + 1\n\n.. _code-assignment:\n\nCheck types in assignment statement [assignment]\n------------------------------------------------\n\nMypy checks that the assigned expression is compatible with the\nassignment target (or targets).\n\nExample:\n\n.. code-block:: python\n\n    class Resource:\n        def __init__(self, name: str) -> None:\n            self.name = name\n\n    r = Resource('A')\n\n    r.name = 'B'  # OK\n\n    # Error: Incompatible types in assignment (expression has type \"int\",\n    #        variable has type \"str\")  [assignment]\n    r.name = 5\n\n.. _code-method-assign:\n\nCheck that assignment target is not a method [method-assign]\n------------------------------------------------------------\n\nIn general, assigning to a method on class object or instance (a.k.a.\nmonkey-patching) is ambiguous in terms of types, since Python's static type\nsystem cannot express the difference between bound and unbound callable types.\nConsider this example:\n\n.. code-block:: python\n\n   class A:\n       def f(self) -> None: pass\n       def g(self) -> None: pass\n\n   def h(self: A) -> None: pass\n\n   A.f = h  # Type of h is Callable[[A], None]\n   A().f()  # This works\n   A.f = A().g  # Type of A().g is Callable[[], None]\n   A().f()  # ...but this also works at runtime\n\nTo prevent the ambiguity, mypy will flag both assignments by default. If this\nerror code is disabled, mypy will treat the assigned value in all method assignments as unbound,\nso only the second assignment will still generate an error.\n\n.. note::\n\n    This error code is a subcode of the more general ``[assignment]`` code.\n\n.. _code-type-var:\n\nCheck type variable values [type-var]\n-------------------------------------\n\nMypy checks that value of a type variable is compatible with a value\nrestriction or the upper bound type.\n\nExample (Python 3.12 syntax):\n\n.. code-block:: python\n\n    def add[T1: (int, float)](x: T1, y: T1) -> T1:\n        return x + y\n\n    add(4, 5.5)  # OK\n\n    # Error: Value of type variable \"T1\" of \"add\" cannot be \"str\"  [type-var]\n    add('x', 'y')\n\n.. _code-operator:\n\nCheck uses of various operators [operator]\n------------------------------------------\n\nMypy checks that operands support a binary or unary operation, such as\n``+`` or ``~``. Indexing operations are so common that they have their\nown error code ``index`` (see below).\n\nExample:\n\n.. code-block:: python\n\n   # Error: Unsupported operand types for + (\"int\" and \"str\")  [operator]\n   1 + 'x'\n\n.. _code-index:\n\nCheck indexing operations [index]\n---------------------------------\n\nMypy checks that the indexed value in indexing operation such as\n``x[y]`` supports indexing, and that the index expression has a valid\ntype.\n\nExample:\n\n.. code-block:: python\n\n   a = {'x': 1, 'y': 2}\n\n   a['x']  # OK\n\n   # Error: Invalid index type \"int\" for \"dict[str, int]\"; expected type \"str\"  [index]\n   print(a[1])\n\n   # Error: Invalid index type \"bytes\" for \"dict[str, int]\"; expected type \"str\"  [index]\n   a[b'x'] = 4\n\n.. _code-list-item:\n\nCheck list items [list-item]\n----------------------------\n\nWhen constructing a list using ``[item, ...]``, mypy checks that each item\nis compatible with the list type that is inferred from the surrounding\ncontext.\n\nExample:\n\n.. code-block:: python\n\n    # Error: List item 0 has incompatible type \"int\"; expected \"str\"  [list-item]\n    a: list[str] = [0]\n\n.. _code-dict-item:\n\nCheck dict items [dict-item]\n----------------------------\n\nWhen constructing a dictionary using ``{key: value, ...}`` or ``dict(key=value, ...)``,\nmypy checks that each key and value is compatible with the dictionary type that is\ninferred from the surrounding context.\n\nExample:\n\n.. code-block:: python\n\n    # Error: Dict entry 0 has incompatible type \"str\": \"str\"; expected \"str\": \"int\"  [dict-item]\n    d: dict[str, int] = {'key': 'value'}\n\n.. _code-typeddict-item:\n\nCheck TypedDict items [typeddict-item]\n--------------------------------------\n\nWhen constructing a TypedDict object, mypy checks that each key and value is compatible\nwith the TypedDict type that is inferred from the surrounding context.\n\nWhen getting a TypedDict item, mypy checks that the key\nexists. When assigning to a TypedDict, mypy checks that both the\nkey and the value are valid.\n\nExample:\n\n.. code-block:: python\n\n    from typing import TypedDict\n\n    class Point(TypedDict):\n        x: int\n        y: int\n\n    # Error: Incompatible types (expression has type \"float\",\n    #        TypedDict item \"x\" has type \"int\")  [typeddict-item]\n    p: Point = {'x': 1.2, 'y': 4}\n\n.. _code-typeddict-unknown-key:\n\nCheck TypedDict Keys [typeddict-unknown-key]\n--------------------------------------------\n\nWhen constructing a TypedDict object, mypy checks whether the\ndefinition contains unknown keys, to catch invalid keys and\nmisspellings. On the other hand, mypy will not generate an error when\na previously constructed TypedDict value with extra keys is passed\nto a function as an argument, since TypedDict values support\nstructural subtyping (\"static duck typing\") and the keys are assumed\nto have been validated at the point of construction. Example:\n\n.. code-block:: python\n\n    from typing import TypedDict\n\n    class Point(TypedDict):\n        x: int\n        y: int\n\n    class Point3D(Point):\n        z: int\n\n    def add_x_coordinates(a: Point, b: Point) -> int:\n        return a[\"x\"] + b[\"x\"]\n\n    a: Point = {\"x\": 1, \"y\": 4}\n    b: Point3D = {\"x\": 2, \"y\": 5, \"z\": 6}\n\n    add_x_coordinates(a, b)  # OK\n\n    # Error: Extra key \"z\" for TypedDict \"Point\"  [typeddict-unknown-key]\n    add_x_coordinates(a, {\"x\": 1, \"y\": 4, \"z\": 5})\n\nSetting a TypedDict item using an unknown key will also generate this\nerror, since it could be a misspelling:\n\n.. code-block:: python\n\n    a: Point = {\"x\": 1, \"y\": 2}\n    # Error: Extra key \"z\" for TypedDict \"Point\"  [typeddict-unknown-key]\n    a[\"z\"] = 3\n\nReading an unknown key will generate the more general (and serious)\n``typeddict-item`` error, which is likely to result in an exception at\nruntime:\n\n.. code-block:: python\n\n    a: Point = {\"x\": 1, \"y\": 2}\n    # Error: TypedDict \"Point\" has no key \"z\"  [typeddict-item]\n    _ = a[\"z\"]\n\n.. note::\n\n    This error code is a subcode of the wider ``[typeddict-item]`` code.\n\n.. _code-has-type:\n\nCheck that type of target is known [has-type]\n---------------------------------------------\n\nMypy sometimes generates an error when it hasn't inferred any type for\na variable being referenced. This can happen for references to\nvariables that are initialized later in the source file, and for\nreferences across modules that form an import cycle. When this\nhappens, the reference gets an implicit ``Any`` type.\n\nIn this example the definitions of ``x`` and ``y`` are circular:\n\n.. code-block:: python\n\n   class Problem:\n       def set_x(self) -> None:\n           # Error: Cannot determine type of \"y\"  [has-type]\n           self.x = self.y\n\n       def set_y(self) -> None:\n           self.y = self.x\n\nTo work around this error, you can add an explicit type annotation to\nthe target variable or attribute. Sometimes you can also reorganize\nthe code so that the definition of the variable is placed earlier than\nthe reference to the variable in a source file. Untangling cyclic\nimports may also help.\n\nWe add an explicit annotation to the ``y`` attribute to work around\nthe issue:\n\n.. code-block:: python\n\n   class Problem:\n       def set_x(self) -> None:\n           self.x = self.y  # OK\n\n       def set_y(self) -> None:\n           self.y: int = self.x  # Added annotation here\n\n.. _code-import:\n\nCheck for an issue with imports [import]\n----------------------------------------\n\nMypy generates an error if it can't resolve an `import` statement.\nThis is a parent error code of `import-not-found` and `import-untyped`\n\nSee :ref:`ignore-missing-imports` for how to work around these errors.\n\n.. _code-import-not-found:\n\nCheck that import target can be found [import-not-found]\n--------------------------------------------------------\n\nMypy generates an error if it can't find the source code or a stub file\nfor an imported module.\n\nExample:\n\n.. code-block:: python\n\n    # Error: Cannot find implementation or library stub for module named \"m0dule_with_typo\"  [import-not-found]\n    import m0dule_with_typo\n\nSee :ref:`ignore-missing-imports` for how to work around these errors.\n\n.. _code-import-untyped:\n\nCheck that import target can be found [import-untyped]\n--------------------------------------------------------\n\nMypy generates an error if it can find the source code for an imported module,\nbut that module does not provide type annotations (via :ref:`PEP 561 <installed-packages>`).\n\nExample:\n\n.. code-block:: python\n\n    # Error: Library stubs not installed for \"bs4\"  [import-untyped]\n    import bs4\n    # Error: Skipping analyzing \"no_py_typed\": module is installed, but missing library stubs or py.typed marker  [import-untyped]\n    import no_py_typed\n\nIn some cases, these errors can be fixed by installing an appropriate\nstub package. See :ref:`ignore-missing-imports` for more details.\n\n.. _code-no-redef:\n\nCheck that each name is defined once [no-redef]\n-----------------------------------------------\n\nMypy may generate an error if you have multiple definitions for a name\nin the same namespace.  The reason is that this is often an error, as\nthe second definition may overwrite the first one. Also, mypy often\ncan't be able to determine whether references point to the first or\nthe second definition, which would compromise type checking.\n\nIf you silence this error, all references to the defined name refer to\nthe *first* definition.\n\nExample:\n\n.. code-block:: python\n\n   class A:\n       def __init__(self, x: int) -> None: ...\n\n   class A:  # Error: Name \"A\" already defined on line 1  [no-redef]\n       def __init__(self, x: str) -> None: ...\n\n   # Error: Argument 1 to \"A\" has incompatible type \"str\"; expected \"int\"\n   #        (the first definition wins!)\n   A('x')\n\n.. _code-func-returns-value:\n\nCheck that called function returns a value [func-returns-value]\n---------------------------------------------------------------\n\nMypy reports an error if you call a function with a ``None``\nreturn type and don't ignore the return value, as this is\nusually (but not always) a programming error.\n\nIn this example, the ``if f()`` check is always false since ``f``\nreturns ``None``:\n\n.. code-block:: python\n\n   def f() -> None:\n       ...\n\n   # OK: we don't do anything with the return value\n   f()\n\n   # Error: \"f\" does not return a value (it only ever returns None)  [func-returns-value]\n   if f():\n        print(\"not false\")\n\n.. _code-abstract:\n\nCheck instantiation of abstract classes [abstract]\n--------------------------------------------------\n\nMypy generates an error if you try to instantiate an abstract base\nclass (ABC). An abstract base class is a class with at least one\nabstract method or attribute. (See also :py:mod:`abc` module documentation)\n\nSometimes a class is made accidentally abstract, often due to an\nunimplemented abstract method. In a case like this you need to provide\nan implementation for the method to make the class concrete\n(non-abstract).\n\nExample:\n\n.. code-block:: python\n\n    from abc import ABCMeta, abstractmethod\n\n    class Persistent(metaclass=ABCMeta):\n        @abstractmethod\n        def save(self) -> None: ...\n\n    class Thing(Persistent):\n        def __init__(self) -> None:\n            ...\n\n        ...  # No \"save\" method\n\n    # Error: Cannot instantiate abstract class \"Thing\" with abstract attribute \"save\"  [abstract]\n    t = Thing()\n\n.. _code-type-abstract:\n\nSafe handling of abstract type object types [type-abstract]\n-----------------------------------------------------------\n\nMypy always allows instantiating (calling) type objects typed as ``type[t]``,\neven if it is not known that ``t`` is non-abstract, since it is a common\npattern to create functions that act as object factories (custom constructors).\nTherefore, to prevent issues described in the above section, when an abstract\ntype object is passed where ``type[t]`` is expected, mypy will give an error.\nExample (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from abc import ABCMeta, abstractmethod\n\n   class Config(metaclass=ABCMeta):\n       @abstractmethod\n       def get_value(self, attr: str) -> str: ...\n\n   def make_many[T](typ: type[T], n: int) -> list[T]:\n       return [typ() for _ in range(n)]  # This will raise if typ is abstract\n\n   # Error: Only concrete class can be given where \"type[Config]\" is expected [type-abstract]\n   make_many(Config, 5)\n\n.. _code-safe-super:\n\nCheck that call to an abstract method via super is valid [safe-super]\n---------------------------------------------------------------------\n\nAbstract methods often don't have any default implementation, i.e. their\nbodies are just empty. Calling such methods in subclasses via ``super()``\nwill cause runtime errors, so mypy prevents you from doing so:\n\n.. code-block:: python\n\n   from abc import abstractmethod\n   class Base:\n       @abstractmethod\n       def foo(self) -> int: ...\n   class Sub(Base):\n       def foo(self) -> int:\n           return super().foo() + 1  # error: Call to abstract method \"foo\" of \"Base\" with\n                                     # trivial body via super() is unsafe  [safe-super]\n   Sub().foo()  # This will crash at runtime.\n\nMypy considers the following as trivial bodies: a ``pass`` statement, a literal\nellipsis ``...``, a docstring, and a ``raise NotImplementedError`` statement.\n\n.. _code-valid-newtype:\n\nCheck the target of NewType [valid-newtype]\n-------------------------------------------\n\nThe target of a :py:class:`~typing.NewType` definition must be a class type. It can't\nbe a union type, ``Any``, or various other special types.\n\nYou can also get this error if the target has been imported from a\nmodule whose source mypy cannot find, since any such definitions are\ntreated by mypy as values with ``Any`` types. Example:\n\n.. code-block:: python\n\n   from typing import NewType\n\n   # The source for \"acme\" is not available for mypy\n   from acme import Entity  # type: ignore\n\n   # Error: Argument 2 to NewType(...) must be subclassable (got \"Any\")  [valid-newtype]\n   UserEntity = NewType('UserEntity', Entity)\n\nTo work around the issue, you can either give mypy access to the sources\nfor ``acme`` or create a stub file for the module.  See :ref:`ignore-missing-imports`\nfor more information.\n\n.. _code-exit-return:\n\nCheck the return type of __exit__ [exit-return]\n-----------------------------------------------\n\nIf mypy can determine that :py:meth:`__exit__ <object.__exit__>` always returns ``False``, mypy\nchecks that the return type is *not* ``bool``.  The boolean value of\nthe return type affects which lines mypy thinks are reachable after a\n``with`` statement, since any :py:meth:`__exit__ <object.__exit__>` method that can return\n``True`` may swallow exceptions. An imprecise return type can result\nin mysterious errors reported near ``with`` statements.\n\nTo fix this, use either ``typing.Literal[False]`` or\n``None`` as the return type. Returning ``None`` is equivalent to\nreturning ``False`` in this context, since both are treated as false\nvalues.\n\nExample:\n\n.. code-block:: python\n\n   class MyContext:\n       ...\n       def __exit__(self, exc, value, tb) -> bool:  # Error\n           print('exit')\n           return False\n\nThis produces the following output from mypy:\n\n.. code-block:: text\n\n   example.py:3: error: \"bool\" is invalid as return type for \"__exit__\" that always returns False\n   example.py:3: note: Use \"typing_extensions.Literal[False]\" as the return type or change it to\n       \"None\"\n   example.py:3: note: If return type of \"__exit__\" implies that it may return True, the context\n       manager may swallow exceptions\n\nYou can use ``Literal[False]`` to fix the error:\n\n.. code-block:: python\n\n   from typing import Literal\n\n   class MyContext:\n       ...\n       def __exit__(self, exc, value, tb) -> Literal[False]:  # OK\n           print('exit')\n           return False\n\nYou can also use ``None``:\n\n.. code-block:: python\n\n   class MyContext:\n       ...\n       def __exit__(self, exc, value, tb) -> None:  # Also OK\n           print('exit')\n\n.. _code-name-match:\n\nCheck that naming is consistent [name-match]\n--------------------------------------------\n\nThe definition of a named tuple or a TypedDict must be named\nconsistently when using the call-based syntax. Example:\n\n.. code-block:: python\n\n    from typing import NamedTuple\n\n    # Error: First argument to namedtuple() should be \"Point2D\", not \"Point\"\n    Point2D = NamedTuple(\"Point\", [(\"x\", int), (\"y\", int)])\n\n.. _code-literal-required:\n\nCheck that literal is used where expected [literal-required]\n------------------------------------------------------------\n\nThere are some places where only a (string) literal value is expected for\nthe purposes of static type checking, for example a ``TypedDict`` key, or\na ``__match_args__`` item. Providing a ``str``-valued variable in such contexts\nwill result in an error. Note that in many cases you can also use ``Final``\nor ``Literal`` variables. Example:\n\n.. code-block:: python\n\n   from typing import Final, Literal, TypedDict\n\n   class Point(TypedDict):\n       x: int\n       y: int\n\n   def test(p: Point) -> None:\n       X: Final = \"x\"\n       p[X]  # OK\n\n       Y: Literal[\"y\"] = \"y\"\n       p[Y]  # OK\n\n       key = \"x\"  # Inferred type of key is `str`\n       # Error: TypedDict key must be a string literal;\n       #   expected one of (\"x\", \"y\")  [literal-required]\n       p[key]\n\n.. _code-no-overload-impl:\n\nCheck that overloaded functions have an implementation [no-overload-impl]\n-------------------------------------------------------------------------\n\nOverloaded functions outside of stub files must be followed by a non overloaded\nimplementation.\n\n.. code-block:: python\n\n   from typing import overload\n\n   @overload\n   def func(value: int) -> int:\n       ...\n\n   @overload\n   def func(value: str) -> str:\n       ...\n\n   # presence of required function below is checked\n   def func(value):\n       pass  # actual implementation\n\n.. _code-unused-coroutine:\n\nCheck that coroutine return value is used [unused-coroutine]\n------------------------------------------------------------\n\nMypy ensures that return values of async def functions are not\nignored, as this is usually a programming error, as the coroutine\nwon't be executed at the call site.\n\n.. code-block:: python\n\n   async def f() -> None:\n       ...\n\n   async def g() -> None:\n       f()  # Error: missing await\n       await f()  # OK\n\nYou can work around this error by assigning the result to a temporary,\notherwise unused variable:\n\n.. code-block:: python\n\n       _ = f()  # No error\n\n.. _code-top-level-await:\n\nWarn about top level await expressions [top-level-await]\n--------------------------------------------------------\n\nThis error code is separate from the general ``[syntax]`` errors, because in\nsome environments (e.g. IPython) a top level ``await`` is allowed. In such\nenvironments a user may want to use ``--disable-error-code=top-level-await``,\nwhich allows one to still have errors for other improper uses of ``await``,\nfor example:\n\n.. code-block:: python\n\n   async def f() -> None:\n       ...\n\n   top = await f()  # Error: \"await\" outside function  [top-level-await]\n\n.. _code-await-not-async:\n\nWarn about await expressions used outside of coroutines [await-not-async]\n-------------------------------------------------------------------------\n\n``await`` must be used inside a coroutine.\n\n.. code-block:: python\n\n   async def f() -> None:\n       ...\n\n   def g() -> None:\n       await f()  # Error: \"await\" outside coroutine (\"async def\")  [await-not-async]\n\n.. _code-assert-type:\n\nCheck types in assert_type [assert-type]\n----------------------------------------\n\nThe inferred type for an expression passed to ``assert_type`` must match\nthe provided type.\n\n.. code-block:: python\n\n   from typing_extensions import assert_type\n\n   assert_type([1], list[int])  # OK\n\n   assert_type([1], list[str])  # Error\n\n.. _code-truthy-function:\n\nCheck that function isn't used in boolean context [truthy-function]\n-------------------------------------------------------------------\n\nFunctions will always evaluate to true in boolean contexts.\n\n.. code-block:: python\n\n    def f():\n        ...\n\n    if f:  # Error: Function \"Callable[[], Any]\" could always be true in boolean context  [truthy-function]\n        pass\n\n.. _code-str-format:\n\nCheck that string formatting/interpolation is type-safe [str-format]\n--------------------------------------------------------------------\n\nMypy will check that f-strings, ``str.format()`` calls, and ``%`` interpolations\nare valid (when corresponding template is a literal string). This includes\nchecking number and types of replacements, for example:\n\n.. code-block:: python\n\n    # Error: Cannot find replacement for positional format specifier 1 [str-format]\n    \"{} and {}\".format(\"spam\")\n    \"{} and {}\".format(\"spam\", \"eggs\")  # OK\n    # Error: Not all arguments converted during string formatting [str-format]\n    \"{} and {}\".format(\"spam\", \"eggs\", \"cheese\")\n\n    # Error: Incompatible types in string interpolation\n    # (expression has type \"float\", placeholder has type \"int\") [str-format]\n    \"{:d}\".format(3.14)\n\n.. _code-str-bytes-safe:\n\nCheck for implicit bytes coercions [str-bytes-safe]\n-------------------------------------------------------------------\n\nWarn about cases where a bytes object may be converted to a string in an unexpected manner.\n\n.. code-block:: python\n\n    b = b\"abc\"\n\n    # Error: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\".\n    # If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x).\n    # Otherwise, decode the bytes [str-bytes-safe]\n    print(f\"The alphabet starts with {b}\")\n\n    # Okay\n    print(f\"The alphabet starts with {b!r}\")  # The alphabet starts with b'abc'\n    print(f\"The alphabet starts with {b.decode('utf-8')}\")  # The alphabet starts with abc\n\n.. _code-str-unpack:\n\nCheck that ``str`` is not unpacked [str-unpack]\n---------------------------------------------------------\n\nIt can sometimes be surprising that ``str`` is iterable, especially when unpacking\nin an assignment.\n\nExample:\n\n.. code-block:: python\n\n    def print_dict(d: dict[str, str]) -> int:\n        # We meant to do d.items(), but instead we're unpacking the str keys of d\n\n        # Error: Unpacking a string is disallowed\n        for k, v in d:\n            print(k, v)\n\n.. _code-overload-overlap:\n\nCheck that overloaded functions don't overlap [overload-overlap]\n----------------------------------------------------------------\n\nWarn if multiple ``@overload`` variants overlap in potentially unsafe ways.\nThis guards against the following situation:\n\n.. code-block:: python\n\n    from typing import overload\n\n    class A: ...\n    class B(A): ...\n\n    @overload\n    def foo(x: B) -> int: ...  # Error: Overloaded function signatures 1 and 2 overlap with incompatible return types  [overload-overlap]\n    @overload\n    def foo(x: A) -> str: ...\n    def foo(x): ...\n\n    def takes_a(a: A) -> str:\n        return foo(a)\n\n    a: A = B()\n    value = takes_a(a)\n    # mypy will think that value is a str, but it could actually be an int\n    reveal_type(value) # Revealed type is \"builtins.str\"\n\n\nNote that in cases where you ignore this error, mypy will usually still infer the\ntypes you expect.\n\nSee :ref:`overloading <function-overloading>` for more explanation.\n\n\n.. _code-overload-cannot-match:\n\nCheck for overload signatures that cannot match [overload-cannot-match]\n--------------------------------------------------------------------------\n\nWarn if an ``@overload`` variant can never be matched, because an earlier\noverload has a wider signature. For example, this can happen if the two\noverloads accept the same parameters and each parameter on the first overload\nhas the same type or a wider type than the corresponding parameter on the second\noverload.\n\nExample:\n\n.. code-block:: python\n\n    from typing import overload, Union\n\n    @overload\n    def process(response1: object, response2: object) -> object:\n        ...\n    @overload\n    def process(response1: int, response2: int) -> int: # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader  [overload-cannot-match]\n        ...\n\n    def process(response1: object, response2: object) -> object:\n        return response1 + response2\n\n.. _code-annotation-unchecked:\n\nNotify about an annotation in an unchecked function [annotation-unchecked]\n--------------------------------------------------------------------------\n\nSometimes a user may accidentally omit an annotation for a function, and mypy\nwill not check the body of this function (unless one uses\n:option:`--check-untyped-defs <mypy --check-untyped-defs>` or\n:option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>`). To avoid\nsuch situations go unnoticed, mypy will show a note, if there are any type\nannotations in an unchecked function:\n\n.. code-block:: python\n\n    def test_assignment():  # \"-> None\" return annotation is missing\n        # Note: By default the bodies of untyped functions are not checked,\n        # consider using --check-untyped-defs [annotation-unchecked]\n        x: int = \"no way\"\n\nNote that mypy will still exit with return code ``0``, since such behaviour is\nspecified by :pep:`484`.\n\n.. _code-prop-decorator:\n\nDecorator preceding property not supported [prop-decorator]\n-----------------------------------------------------------\n\nMypy does not yet support analysis of decorators that precede the property\ndecorator. If the decorator does not preserve the declared type of the property,\nmypy will not infer the correct type for the declaration. If the decorator cannot\nbe moved after the ``@property`` decorator, then you must use a type ignore\ncomment:\n\n.. code-block:: python\n\n    class MyClass:\n        @special  # type: ignore[prop-decorator]\n        @property\n        def magic(self) -> str:\n            return \"xyzzy\"\n\n.. note::\n\n    For backward compatibility, this error code is a subcode of the generic ``[misc]`` code.\n\n.. _code-syntax:\n\nReport syntax errors [syntax]\n-----------------------------\n\nIf the code being checked is not syntactically valid, mypy issues a\nsyntax error. Most, but not all, syntax errors are *blocking errors*:\nthey can't be ignored with a ``# type: ignore`` comment.\n\n.. _code-typeddict-readonly-mutated:\n\nReadOnly key of a TypedDict is mutated [typeddict-readonly-mutated]\n-------------------------------------------------------------------\n\nConsider this example:\n\n.. code-block:: python\n\n    from datetime import datetime\n    from typing import TypedDict\n    from typing_extensions import ReadOnly\n\n    class User(TypedDict):\n        username: ReadOnly[str]\n        last_active: datetime\n\n    user: User = {'username': 'foobar', 'last_active': datetime.now()}\n    user['last_active'] = datetime.now()  # ok\n    user['username'] = 'other'  # error: ReadOnly TypedDict key \"key\" TypedDict is mutated  [typeddict-readonly-mutated]\n\n`PEP 705 <https://peps.python.org/pep-0705>`_ specifies\nhow ``ReadOnly`` special form works for ``TypedDict`` objects.\n\n.. _code-narrowed-type-not-subtype:\n\nCheck that ``TypeIs`` narrows types [narrowed-type-not-subtype]\n---------------------------------------------------------------\n\n:pep:`742` requires that when ``TypeIs`` is used, the narrowed\ntype must be a subtype of the original type::\n\n    from typing_extensions import TypeIs\n\n    def f(x: int) -> TypeIs[str]:  # Error, str is not a subtype of int\n        ...\n\n    def g(x: object) -> TypeIs[str]:  # OK\n        ...\n\n.. _code-maybe-unrecognized-str-typeform:\n\nString appears in a context which expects a TypeForm [maybe-unrecognized-str-typeform]\n--------------------------------------------------------------------------------------\n\nTypeForm literals may contain string annotations:\n\n.. code-block:: python\n\n   typx1: TypeForm = str | None\n   typx2: TypeForm = 'str | None'  # OK\n   typx3: TypeForm = 'str' | None  # OK\n\nHowever TypeForm literals containing a string annotation can only be recognized\nby mypy in the following locations:\n\n.. code-block:: python\n\n   typx_var: TypeForm = 'str | None'  # assignment r-value\n\n   def func(typx_param: TypeForm) -> TypeForm:\n       return 'str | None'  # returned expression\n\n   func('str | None')  # callable's argument\n\nIf you try to use a string annotation in some other location\nwhich expects a TypeForm, the string value will always be treated as a ``str``\neven if a ``TypeForm`` would be more appropriate and this error code\nwill be generated:\n\n.. code-block:: python\n\n   # Error: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize.  [maybe-unrecognized-str-typeform]\n   # Error: List item 0 has incompatible type \"str\"; expected \"TypeForm[Any]\"  [list-item]\n   list_of_typx: list[TypeForm] = ['str | None', float]\n\nFix the error by surrounding the entire type with ``TypeForm(...)``:\n\n.. code-block:: python\n\n   list_of_typx: list[TypeForm] = [TypeForm('str | None'), float]  # OK\n\nSimilarly, if you try to use a string literal in a location which expects a\nTypeForm, this error code will be generated:\n\n.. code-block:: python\n\n   dict_of_typx = {'str_or_none': TypeForm(str | None)}\n   # Error: TypeForm containing a string annotation cannot be recognized here. Surround with TypeForm(...) to recognize.  [maybe-unrecognized-str-typeform]\n   list_of_typx: list[TypeForm] = [dict_of_typx['str_or_none']]\n\nFix the error by adding ``# type: ignore[maybe-unrecognized-str-typeform]``\nto the line with the string literal:\n\n.. code-block:: python\n\n   dict_of_typx = {'str_or_none': TypeForm(str | None)}\n   list_of_typx: list[TypeForm] = [dict_of_typx['str_or_none']]  # type: ignore[maybe-unrecognized-str-typeform]\n\n.. _code-misc:\n\nMiscellaneous checks [misc]\n---------------------------\n\nMypy performs numerous other, less commonly failing checks that don't\nhave specific error codes. These use the ``misc`` error code. Other\nthan being used for multiple unrelated errors, the ``misc`` error code\nis not special. For example, you can ignore all errors in this\ncategory by using ``# type: ignore[misc]`` comment. Since these errors\nare not expected to be common, it's unlikely that you'll see two\n*different* errors with the ``misc`` code on a single line -- though\nthis can certainly happen once in a while.\n\n.. note::\n\n    Future mypy versions will likely add new error codes for some errors\n    that currently use the ``misc`` error code.\n"
  },
  {
    "path": "docs/source/error_code_list2.rst",
    "content": ".. _error-codes-optional:\n\nError codes for optional checks\n===============================\n\nThis section documents various errors codes that mypy generates only\nif you enable certain options. See :ref:`error-codes` for general\ndocumentation about error codes and their configuration.\n:ref:`error-code-list` documents error codes that are enabled by default.\n\n.. note::\n\n   The examples in this section use :ref:`inline configuration\n   <inline-config>` to specify mypy options. You can also set the same\n   options by using a :ref:`configuration file <config-file>` or\n   :ref:`command-line options <command-line>`.\n\n.. _code-type-arg:\n\nCheck that type arguments exist [type-arg]\n------------------------------------------\n\nIf you use :option:`--disallow-any-generics <mypy --disallow-any-generics>`, mypy requires that each generic\ntype has values for each type argument. For example, the types ``list`` or\n``dict`` would be rejected. You should instead use types like ``list[int]`` or\n``dict[str, int]``. Any omitted generic type arguments get implicit ``Any``\nvalues. The type ``list`` is equivalent to ``list[Any]``, and so on.\n\nExample:\n\n.. code-block:: python\n\n    # mypy: disallow-any-generics\n\n    # Error: Missing type arguments for generic type \"list\"  [type-arg]\n    def remove_dups(items: list) -> list:\n        ...\n\n.. _code-no-untyped-def:\n\nCheck that every function has an annotation [no-untyped-def]\n------------------------------------------------------------\n\nIf you use :option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>`, mypy requires that all functions\nhave annotations (either a Python 3 annotation or a type comment).\n\nExample:\n\n.. code-block:: python\n\n    # mypy: disallow-untyped-defs\n\n    def inc(x):  # Error: Function is missing a type annotation  [no-untyped-def]\n        return x + 1\n\n    def inc_ok(x: int) -> int:  # OK\n        return x + 1\n\n    class Counter:\n         # Error: Function is missing a type annotation  [no-untyped-def]\n         def __init__(self):\n             self.value = 0\n\n    class CounterOk:\n         # OK: An explicit \"-> None\" is needed if \"__init__\" takes no arguments\n         def __init__(self) -> None:\n             self.value = 0\n\n.. _code-redundant-cast:\n\nCheck that cast is not redundant [redundant-cast]\n-------------------------------------------------\n\nIf you use :option:`--warn-redundant-casts <mypy --warn-redundant-casts>`, mypy will generate an error if the source\ntype of a cast is the same as the target type.\n\nExample:\n\n.. code-block:: python\n\n    # mypy: warn-redundant-casts\n\n    from typing import cast\n\n    Count = int\n\n    def example(x: Count) -> int:\n        # Error: Redundant cast to \"int\"  [redundant-cast]\n        return cast(int, x)\n\n.. _code-redundant-self:\n\nCheck that methods do not have redundant Self annotations [redundant-self]\n--------------------------------------------------------------------------\n\nIf a method uses the ``Self`` type in the return type or the type of a\nnon-self argument, there is no need to annotate the ``self`` argument\nexplicitly. Such annotations are allowed by :pep:`673` but are\nredundant. If you enable this error code, mypy will generate an error if\nthere is a redundant ``Self`` type.\n\nExample:\n\n.. code-block:: python\n\n   # mypy: enable-error-code=\"redundant-self\"\n\n   from typing import Self\n\n   class C:\n       # Error: Redundant \"Self\" annotation for the first method argument\n       def copy(self: Self) -> Self:\n           return type(self)()\n\n.. _code-comparison-overlap:\n\nCheck that comparisons are overlapping [comparison-overlap]\n-----------------------------------------------------------\n\nIf you use :option:`--strict-equality <mypy --strict-equality>`, mypy will generate an error if it\nthinks that a comparison operation is always true or false. These are\noften bugs. Sometimes mypy is too picky and the comparison can\nactually be useful. Instead of disabling strict equality checking\neverywhere, you can use ``# type: ignore[comparison-overlap]`` to\nignore the issue on a particular line only.\n\nExample:\n\n.. code-block:: python\n\n    # mypy: strict-equality\n\n    def is_magic(x: bytes) -> bool:\n        # Error: Non-overlapping equality check (left operand type: \"bytes\",\n        #        right operand type: \"str\")  [comparison-overlap]\n        return x == 'magic'\n\nWe can fix the error by changing the string literal to a bytes\nliteral:\n\n.. code-block:: python\n\n    # mypy: strict-equality\n\n    def is_magic(x: bytes) -> bool:\n        return x == b'magic'  # OK\n\n:option:`--strict-equality <mypy --strict-equality>` does not include comparisons with\n``None``:\n\n.. code-block:: python\n\n    # mypy: strict-equality\n\n    def is_none(x: str) -> bool:\n        return x is None  # OK\n\nIf you want such checks, you must also activate\n:option:`--strict-equality-for-none <mypy --strict-equality-for-none>` (we might merge\nthese two options later).\n\n.. code-block:: python\n\n    # mypy: strict-equality strict-equality-for-none\n\n    def is_none(x: str) -> bool:\n        # Error: Non-overlapping identity check\n        #        (left operand type: \"str\", right operand type: \"None\")\n        return x is None\n\n.. _code-no-untyped-call:\n\nCheck that no untyped functions are called [no-untyped-call]\n------------------------------------------------------------\n\nIf you use :option:`--disallow-untyped-calls <mypy --disallow-untyped-calls>`, mypy generates an error when you\ncall an unannotated function in an annotated function.\n\nExample:\n\n.. code-block:: python\n\n    # mypy: disallow-untyped-calls\n\n    def do_it() -> None:\n        # Error: Call to untyped function \"bad\" in typed context  [no-untyped-call]\n        bad()\n\n    def bad():\n        ...\n\n.. _code-no-any-return:\n\nCheck that function does not return Any value [no-any-return]\n-------------------------------------------------------------\n\nIf you use :option:`--warn-return-any <mypy --warn-return-any>`, mypy generates an error if you return a\nvalue with an ``Any`` type in a function that is annotated to return a\nnon-``Any`` value.\n\nExample:\n\n.. code-block:: python\n\n    # mypy: warn-return-any\n\n    def fields(s):\n         return s.split(',')\n\n    def first_field(x: str) -> str:\n        # Error: Returning Any from function declared to return \"str\"  [no-any-return]\n        return fields(x)[0]\n\n.. _code-no-any-unimported:\n\nCheck that types have no Any components due to missing imports [no-any-unimported]\n----------------------------------------------------------------------------------\n\nIf you use :option:`--disallow-any-unimported <mypy --disallow-any-unimported>`, mypy generates an error if a component of\na type becomes ``Any`` because mypy couldn't resolve an import. These \"stealth\"\n``Any`` types can be surprising and accidentally cause imprecise type checking.\n\nIn this example, we assume that mypy can't find the module ``animals``, which means\nthat ``Cat`` falls back to ``Any`` in a type annotation:\n\n.. code-block:: python\n\n    # mypy: disallow-any-unimported\n\n    from animals import Cat  # type: ignore\n\n    # Error: Argument 1 to \"feed\" becomes \"Any\" due to an unfollowed import  [no-any-unimported]\n    def feed(cat: Cat) -> None:\n        ...\n\n.. _code-unreachable:\n\nCheck that statement or expression is unreachable [unreachable]\n---------------------------------------------------------------\n\nIf you use :option:`--warn-unreachable <mypy --warn-unreachable>`, mypy generates an error if it\nthinks that a statement or expression will never be executed. In most cases, this is due to\nincorrect control flow or conditional checks that are accidentally always true or false.\n\n.. code-block:: python\n\n    # mypy: warn-unreachable\n\n    def example(x: int) -> None:\n        # Error: Right operand of \"or\" is never evaluated  [unreachable]\n        assert isinstance(x, int) or x == 'unused'\n\n        return\n        # Error: Statement is unreachable  [unreachable]\n        print('unreachable')\n\n.. _code-deprecated:\n\nCheck that imported or used feature is deprecated [deprecated]\n--------------------------------------------------------------\n\nIf you use :option:`--enable-error-code deprecated <mypy --enable-error-code>`,\nmypy generates an error if your code imports a deprecated feature explicitly with a\n``from mod import depr`` statement or uses a deprecated feature imported otherwise or defined\nlocally.  Features are considered deprecated when decorated with ``warnings.deprecated``, as\nspecified in `PEP 702 <https://peps.python.org/pep-0702>`_.\nUse the :option:`--report-deprecated-as-note <mypy --report-deprecated-as-note>` option to\nturn all such errors into notes.\nUse :option:`--deprecated-calls-exclude <mypy --deprecated-calls-exclude>` to hide warnings\nfor specific functions, classes and packages.\n\n.. note::\n\n    The ``warnings`` module provides the ``@deprecated`` decorator since Python 3.13.\n    To use it with older Python versions, import it from ``typing_extensions`` instead.\n\nExamples:\n\n.. code-block:: python\n\n    # mypy: report-deprecated-as-error\n\n    # Error: abc.abstractproperty is deprecated: Deprecated, use 'property' with 'abstractmethod' instead\n    from abc import abstractproperty\n\n    from typing_extensions import deprecated\n\n    @deprecated(\"use new_function\")\n    def old_function() -> None:\n        print(\"I am old\")\n\n    # Error: __main__.old_function is deprecated: use new_function\n    old_function()\n    old_function()  # type: ignore[deprecated]\n\n\n.. _code-redundant-expr:\n\nCheck that expression is redundant [redundant-expr]\n---------------------------------------------------\n\nIf you use :option:`--enable-error-code redundant-expr <mypy --enable-error-code>`,\nmypy generates an error if it thinks that an expression is redundant.\n\n.. code-block:: python\n\n    # mypy: enable-error-code=\"redundant-expr\"\n\n    def example(x: int) -> None:\n        # Error: Left operand of \"and\" is always true  [redundant-expr]\n        if isinstance(x, int) and x > 0:\n            pass\n\n        # Error: If condition is always true  [redundant-expr]\n        1 if isinstance(x, int) else 0\n\n        # Error: If condition in comprehension is always true  [redundant-expr]\n        [i for i in range(x) if isinstance(i, int)]\n\n\n.. _code-possibly-undefined:\n\nWarn about variables that are defined only in some execution paths [possibly-undefined]\n---------------------------------------------------------------------------------------\n\nIf you use :option:`--enable-error-code possibly-undefined <mypy --enable-error-code>`,\nmypy generates an error if it cannot verify that a variable will be defined in\nall execution paths. This includes situations when a variable definition\nappears in a loop, in a conditional branch, in an except handler, etc. For\nexample:\n\n.. code-block:: python\n\n    # mypy: enable-error-code=\"possibly-undefined\"\n\n    from collections.abc import Iterable\n\n    def test(values: Iterable[int], flag: bool) -> None:\n        if flag:\n            a = 1\n        z = a + 1  # Error: Name \"a\" may be undefined [possibly-undefined]\n\n        for v in values:\n            b = v\n        z = b + 1  # Error: Name \"b\" may be undefined [possibly-undefined]\n\n.. _code-truthy-bool:\n\nCheck that expression is not implicitly true in boolean context [truthy-bool]\n-----------------------------------------------------------------------------\n\nWarn when the type of an expression in a boolean context does not\nimplement ``__bool__`` or ``__len__``. Unless one of these is\nimplemented by a subtype, the expression will always be considered\ntrue, and there may be a bug in the condition.\n\nAs an exception, the ``object`` type is allowed in a boolean context.\nUsing an iterable value in a boolean context has a separate error code\n(see below).\n\n.. code-block:: python\n\n    # mypy: enable-error-code=\"truthy-bool\"\n\n    class Foo:\n        pass\n    foo = Foo()\n    # Error: \"foo\" has type \"Foo\" which does not implement __bool__ or __len__ so it could always be true in boolean context\n    if foo:\n         ...\n\n.. _code-truthy-iterable:\n\nCheck that iterable is not implicitly true in boolean context [truthy-iterable]\n-------------------------------------------------------------------------------\n\nGenerate an error if a value of type ``Iterable`` is used as a boolean\ncondition, since ``Iterable`` does not implement ``__len__`` or ``__bool__``.\n\nExample:\n\n.. code-block:: python\n\n    from collections.abc import Iterable\n\n    def transform(items: Iterable[int]) -> list[int]:\n        # Error: \"items\" has type \"Iterable[int]\" which can always be true in boolean context. Consider using \"Collection[int]\" instead.  [truthy-iterable]\n        if not items:\n            return [42]\n        return [x + 1 for x in items]\n\nIf ``transform`` is called with a ``Generator`` argument, such as\n``int(x) for x in []``, this function would not return ``[42]`` unlike\nwhat might be intended. Of course, it's possible that ``transform`` is\nonly called with ``list`` or other container objects, and the ``if not\nitems`` check is actually valid. If that is the case, it is\nrecommended to annotate ``items`` as ``Collection[int]`` instead of\n``Iterable[int]``.\n\n.. _code-ignore-without-code:\n\nCheck that ``# type: ignore`` include an error code [ignore-without-code]\n-------------------------------------------------------------------------\n\nWarn when a ``# type: ignore`` comment does not specify any error codes.\nThis clarifies the intent of the ignore and ensures that only the\nexpected errors are silenced.\n\nExample:\n\n.. code-block:: python\n\n    # mypy: enable-error-code=\"ignore-without-code\"\n\n    class Foo:\n        def __init__(self, name: str) -> None:\n            self.name = name\n\n    f = Foo('foo')\n\n    # This line has a typo that mypy can't help with as both:\n    # - the expected error 'assignment', and\n    # - the unexpected error 'attr-defined'\n    # are silenced.\n    # Error: \"type: ignore\" comment without error code (consider \"type: ignore[attr-defined]\" instead)\n    f.nme = 42  # type: ignore\n\n    # This line warns correctly about the typo in the attribute name\n    # Error: \"Foo\" has no attribute \"nme\"; maybe \"name\"?\n    f.nme = 42  # type: ignore[assignment]\n\n.. _code-unused-awaitable:\n\nCheck that awaitable return value is used [unused-awaitable]\n------------------------------------------------------------\n\nIf you use :option:`--enable-error-code unused-awaitable <mypy --enable-error-code>`,\nmypy generates an error if you don't use a returned value that defines ``__await__``.\n\nExample:\n\n.. code-block:: python\n\n    # mypy: enable-error-code=\"unused-awaitable\"\n\n    import asyncio\n\n    async def f() -> int: ...\n\n    async def g() -> None:\n        # Error: Value of type \"Task[int]\" must be used\n        #        Are you missing an await?\n        asyncio.create_task(f())\n\nYou can assign the value to a temporary, otherwise unused variable to\nsilence the error:\n\n.. code-block:: python\n\n    async def g() -> None:\n        _ = asyncio.create_task(f())  # No error\n\n.. _code-unused-ignore:\n\nCheck that ``# type: ignore`` comment is used [unused-ignore]\n-------------------------------------------------------------\n\nIf you use :option:`--enable-error-code unused-ignore <mypy --enable-error-code>`,\nor :option:`--warn-unused-ignores <mypy --warn-unused-ignores>`\nmypy generates an error if you don't use a ``# type: ignore`` comment, i.e. if\nthere is a comment, but there would be no error generated by mypy on this line\nanyway.\n\nExample:\n\n.. code-block:: python\n\n    # Use \"mypy --warn-unused-ignores ...\"\n\n    def add(a: int, b: int) -> int:\n        # Error: unused \"type: ignore\" comment\n        return a + b  # type: ignore\n\nNote that due to a specific nature of this comment, the only way to selectively\nsilence it, is to include the error code explicitly. Also note that this error is\nnot shown if the ``# type: ignore`` is not used due to code being statically\nunreachable (e.g. due to platform or version checks).\n\nExample:\n\n.. code-block:: python\n\n    # Use \"mypy --warn-unused-ignores ...\"\n\n    import sys\n\n    try:\n        # The \"[unused-ignore]\" is needed to get a clean mypy run\n        # on both Python 3.8, and 3.9 where this module was added\n        import graphlib  # type: ignore[import,unused-ignore]\n    except ImportError:\n        pass\n\n    if sys.version_info >= (3, 9):\n        # The following will not generate an error on either\n        # Python 3.8, or Python 3.9\n        42 + \"testing...\"  # type: ignore\n\n.. _code-explicit-override:\n\nCheck that ``@override`` is used when overriding a base class method [explicit-override]\n----------------------------------------------------------------------------------------\n\nIf you use :option:`--enable-error-code explicit-override <mypy --enable-error-code>`\nmypy generates an error if you override a base class method without using the\n``@override`` decorator. An error will not be emitted for overrides of ``__init__``\nor ``__new__``. See `PEP 698 <https://peps.python.org/pep-0698/#strict-enforcement-per-project>`_.\n\n.. note::\n\n    Starting with Python 3.12, the ``@override`` decorator can be imported from ``typing``.\n    To use it with older Python versions, import it from ``typing_extensions`` instead.\n\nExample:\n\n.. code-block:: python\n\n    # mypy: enable-error-code=\"explicit-override\"\n\n    from typing import override\n\n    class Parent:\n        def f(self, x: int) -> None:\n            pass\n\n        def g(self, y: int) -> None:\n            pass\n\n\n    class Child(Parent):\n        def f(self, x: int) -> None:  # Error: Missing @override decorator\n            pass\n\n        @override\n        def g(self, y: int) -> None:\n            pass\n\n.. _code-mutable-override:\n\nCheck that overrides of mutable attributes are safe [mutable-override]\n----------------------------------------------------------------------\n\n`mutable-override` will enable the check for unsafe overrides of mutable attributes.\nFor historical reasons, and because this is a relatively common pattern in Python,\nthis check is not enabled by default. The example below is unsafe, and will be\nflagged when this error code is enabled:\n\n.. code-block:: python\n\n    from typing import Any\n\n    class C:\n        x: float\n        y: float\n        z: float\n\n    class D(C):\n        x: int  # Error: Covariant override of a mutable attribute\n                # (base class \"C\" defined the type as \"float\",\n                # expression has type \"int\")  [mutable-override]\n        y: float  # OK\n        z: Any  # OK\n\n    def f(c: C) -> None:\n        c.x = 1.1\n    d = D()\n    f(d)\n    d.x >> 1  # This will crash at runtime, because d.x is now float, not an int\n\n.. _code-unimported-reveal:\n\nCheck that ``reveal_type`` is imported from typing or typing_extensions [unimported-reveal]\n-------------------------------------------------------------------------------------------\n\nMypy used to have ``reveal_type`` as a special builtin\nthat only existed during type-checking.\nIn runtime it fails with expected ``NameError``,\nwhich can cause real problem in production, hidden from mypy.\n\nBut, in Python3.11 :py:func:`typing.reveal_type` was added.\n``typing_extensions`` ported this helper to all supported Python versions.\n\nNow users can actually import ``reveal_type`` to make the runtime code safe.\n\n.. note::\n\n    Starting with Python 3.11, the ``reveal_type`` function can be imported from ``typing``.\n    To use it with older Python versions, import it from ``typing_extensions`` instead.\n\n.. code-block:: python\n\n    # mypy: enable-error-code=\"unimported-reveal\"\n\n    x = 1\n    reveal_type(x)  # Note: Revealed type is \"builtins.int\" \\\n                    # Error: Name \"reveal_type\" is not defined\n\nCorrect usage:\n\n.. code-block:: python\n\n    # mypy: enable-error-code=\"unimported-reveal\"\n    from typing import reveal_type   # or `typing_extensions`\n\n    x = 1\n    # This won't raise an error:\n    reveal_type(x)  # Note: Revealed type is \"builtins.int\"\n\nWhen this code is enabled, using ``reveal_locals`` is always an error,\nbecause there's no way one can import it.\n\n\n.. _code-explicit-any:\n\nCheck that explicit Any type annotations are not allowed [explicit-any]\n-----------------------------------------------------------------------\n\nIf you use :option:`--disallow-any-explicit <mypy --disallow-any-explicit>`, mypy generates an error\nif you use an explicit ``Any`` type annotation.\n\nExample:\n\n.. code-block:: python\n\n    # mypy: disallow-any-explicit\n    from typing import Any\n    x: Any = 1  # Error: Explicit \"Any\" type annotation  [explicit-any]\n\n\n.. _code-exhaustive-match:\n\nCheck that match statements match exhaustively [exhaustive-match]\n-----------------------------------------------------------------------\n\nIf enabled with :option:`--enable-error-code exhaustive-match <mypy --enable-error-code>`,\nmypy generates an error if a match statement does not match all possible cases/types.\n\n\nExample:\n\n.. code-block:: python\n\n        import enum\n\n\n        class Color(enum.Enum):\n            RED = 1\n            BLUE = 2\n\n        val: Color = Color.RED\n\n        # OK without --enable-error-code exhaustive-match\n        match val:\n            case Color.RED:\n                print(\"red\")\n\n        # With --enable-error-code exhaustive-match\n        # Error: Match statement has unhandled case for values of type \"Literal[Color.BLUE]\"\n        match val:\n            case Color.RED:\n                print(\"red\")\n\n        # OK with or without --enable-error-code exhaustive-match, since all cases are handled\n        match val:\n            case Color.RED:\n                print(\"red\")\n            case _:\n                print(\"other\")\n\n.. _code-untyped-decorator:\n\nError if an untyped decorator makes a typed function effectively untyped [untyped-decorator]\n--------------------------------------------------------------------------------------------\n\nIf enabled with :option:`--disallow-untyped-decorators <mypy --disallow-untyped-decorators>`\nmypy generates an error if a typed function is wrapped by an untyped decorator\n(as this would effectively remove the benefits of typing the function).\n\nExample:\n\n.. code-block:: python\n\n        def printing_decorator(func):\n            def wrapper(*args, **kwds):\n                print(\"Calling\", func)\n                return func(*args, **kwds)\n            return wrapper\n        # A decorated function.\n        @printing_decorator  # E: Untyped decorator makes function \"add_forty_two\" untyped  [untyped-decorator]\n        def add_forty_two(value: int) -> int:\n            return value + 42\n"
  },
  {
    "path": "docs/source/error_codes.rst",
    "content": ".. _error-codes:\n\nError codes\n===========\n\nMypy can optionally display an error code such as ``[attr-defined]``\nafter each error message. Error codes serve two purposes:\n\n1. It's possible to silence specific error codes on a line using ``#\n   type: ignore[code]``. This way you won't accidentally ignore other,\n   potentially more serious errors.\n\n2. The error code can be used to find documentation about the error.\n   The next two topics (:ref:`error-code-list` and\n   :ref:`error-codes-optional`) document the various error codes\n   mypy can report.\n\nMost error codes are shared between multiple related error messages.\nError codes may change in future mypy releases.\n\n\n.. _silence-error-codes:\n\nSilencing errors based on error codes\n-------------------------------------\n\nYou can use a special comment ``# type: ignore[code, ...]`` to only\nignore errors with a specific error code (or codes) on a particular\nline.  This can be used even if you have not configured mypy to show\nerror codes.\n\nThis example shows how to ignore an error about an imported name mypy\nthinks is undefined:\n\n.. code-block:: python\n\n   # 'foo' is defined in 'foolib', even though mypy can't see the\n   # definition.\n   from foolib import foo  # type: ignore[attr-defined]\n\nEnabling/disabling specific error codes globally\n------------------------------------------------\n\nThere are command-line flags and config file settings for enabling\ncertain optional error codes, such as :option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>`,\nwhich enables the ``no-untyped-def`` error code.\n\nYou can use :option:`--enable-error-code <mypy --enable-error-code>`\nand :option:`--disable-error-code <mypy --disable-error-code>`\nto enable or disable specific error codes that don't have a dedicated\ncommand-line flag or config file setting.\n\nPer-module enabling/disabling error codes\n-----------------------------------------\n\nYou can use :ref:`configuration file <config-file>` sections to enable or\ndisable specific error codes only in some modules. For example, this ``mypy.ini``\nconfig will enable non-annotated empty containers in tests, while keeping\nother parts of code checked in strict mode:\n\n.. code-block:: ini\n\n   [mypy]\n   strict = True\n\n   [mypy-tests.*]\n   allow_untyped_defs = True\n   allow_untyped_calls = True\n   disable_error_code = var-annotated, has-type\n\nNote that per-module enabling/disabling acts as override over the global\noptions. So that you don't need to repeat the error code lists for each\nmodule if you have them in global config section. For example:\n\n.. code-block:: ini\n\n   [mypy]\n   enable_error_code = truthy-bool, ignore-without-code, unused-awaitable\n\n   [mypy-extensions.*]\n   disable_error_code = unused-awaitable\n\nThe above config will allow unused awaitables in extension modules, but will\nstill keep the other two error codes enabled. The overall logic is following:\n\n* Command line and/or config main section set global error codes\n\n* Individual config sections *adjust* them per glob/module\n\n* Inline ``# mypy: disable-error-code=\"...\"`` and ``# mypy: enable-error-code=\"...\"``\n  comments can further *adjust* them for a specific file.\n  For example:\n\n.. code-block:: python\n\n  # mypy: enable-error-code=\"truthy-bool, ignore-without-code\"\n\nSo one can e.g. enable some code globally, disable it for all tests in\nthe corresponding config section, and then re-enable it with an inline\ncomment in some specific test.\n\nSubcodes of error codes\n-----------------------\n\nIn some cases, mostly for backwards compatibility reasons, an error\ncode may be covered also by another, wider error code. For example, an error with\ncode ``[method-assign]`` can be ignored by ``# type: ignore[assignment]``.\nSimilar logic works for disabling error codes globally. If a given error code\nis a subcode of another one, it will be mentioned in the documentation for the narrower\ncode. This hierarchy is not nested: there cannot be subcodes of other\nsubcodes.\n\n\nRequiring error codes\n---------------------\n\nIt's possible to require error codes be specified in ``type: ignore`` comments.\nSee :ref:`ignore-without-code<code-ignore-without-code>` for more information.\n"
  },
  {
    "path": "docs/source/existing_code.rst",
    "content": ".. _existing-code:\n\nUsing mypy with an existing codebase\n====================================\n\nThis section explains how to get started using mypy with an existing,\nsignificant codebase that has little or no type annotations. If you are\na beginner, you can skip this section.\n\nStart small\n-----------\n\nIf your codebase is large, pick a subset of your codebase (say, 5,000 to 50,000\nlines) and get mypy to run successfully only on this subset at first, *before\nadding annotations*. This should be doable in a day or two. The sooner you get\nsome form of mypy passing on your codebase, the sooner you benefit.\n\nYou'll likely need to fix some mypy errors, either by inserting\nannotations requested by mypy or by adding ``# type: ignore``\ncomments to silence errors you don't want to fix now.\n\nWe'll mention some tips for getting mypy passing on your codebase in various\nsections below.\n\nRun mypy consistently and prevent regressions\n---------------------------------------------\n\nMake sure all developers on your codebase run mypy the same way.\nOne way to ensure this is adding a small script with your mypy\ninvocation to your codebase, or adding your mypy invocation to\nexisting tools you use to run tests, like ``tox``.\n\n* Make sure everyone runs mypy with the same options. Checking a mypy\n  :ref:`configuration file <config-file>` into your codebase is the\n  easiest way to do this.\n\n* Make sure everyone type checks the same set of files. See\n  :ref:`specifying-code-to-be-checked` for details.\n\n* Make sure everyone runs mypy with the same version of mypy, for instance\n  by pinning mypy with the rest of your dev requirements.\n\nIn particular, you'll want to make sure to run mypy as part of your\nContinuous Integration (CI) system as soon as possible. This will\nprevent new type errors from being introduced into your codebase.\n\nA simple CI script could look something like this:\n\n.. code-block:: text\n\n    python3 -m pip install mypy==1.8\n    # Run your standardised mypy invocation, e.g.\n    mypy my_project\n    # This could also look like `scripts/run_mypy.sh`, `tox run -e mypy`, `make mypy`, etc\n\nIgnoring errors from certain modules\n------------------------------------\n\nBy default mypy will follow imports in your code and try to check everything.\nThis means even if you only pass in a few files to mypy, it may still process a\nlarge number of imported files. This could potentially result in lots of errors\nyou don't want to deal with at the moment.\n\nOne way to deal with this is to ignore errors in modules you aren't yet ready to\ntype check. The :confval:`ignore_errors` option is useful for this, for instance,\nif you aren't yet ready to deal with errors from ``package_to_fix_later``:\n\n.. code-block:: text\n\n   [mypy-package_to_fix_later.*]\n   ignore_errors = True\n\nYou could even invert this, by setting ``ignore_errors = True`` in your global\nconfig section and only enabling error reporting with ``ignore_errors = False``\nfor the set of modules you are ready to type check.\n\nThe per-module configuration that mypy's configuration file allows can be\nextremely useful. Many configuration options can be enabled or disabled\nonly for specific modules. In particular, you can also enable or disable\nvarious error codes on a per-module basis, see :ref:`error-codes`.\n\nFixing errors related to imports\n--------------------------------\n\nA common class of error you will encounter is errors from mypy about modules\nthat it can't find, that don't have types, or don't have stub files:\n\n.. code-block:: text\n\n    core/config.py:7: error: Cannot find implementation or library stub for module named 'frobnicate'\n    core/model.py:9: error: Cannot find implementation or library stub for module named 'acme'\n    ...\n\nSometimes these can be fixed by installing the relevant packages or\nstub libraries in the environment you're running ``mypy`` in.\n\nSee :ref:`fix-missing-imports` for a complete reference on these errors\nand the ways in which you can fix them.\n\nYou'll likely find that you want to suppress all errors from importing\na given module that doesn't have types. If you only import that module\nin one or two places, you can use ``# type: ignore`` comments. For example,\nhere we ignore an error about a third-party module ``frobnicate`` that\ndoesn't have stubs using ``# type: ignore``:\n\n.. code-block:: python\n\n   import frobnicate  # type: ignore\n   ...\n   frobnicate.initialize()  # OK (but not checked)\n\nBut if you import the module in many places, this becomes unwieldy. In this\ncase, we recommend using a :ref:`configuration file <config-file>`. For example,\nto disable errors about importing ``frobnicate`` and ``acme`` everywhere in your\ncodebase, use a config like this:\n\n.. code-block:: text\n\n   [mypy-frobnicate.*]\n   ignore_missing_imports = True\n\n   [mypy-acme.*]\n   ignore_missing_imports = True\n\nIf you get a large number of errors, you may want to ignore all errors\nabout missing imports, for instance by setting\n:option:`--disable-error-code=import-untyped <mypy --ignore-missing-imports>`.\nor setting :confval:`ignore_missing_imports` to true globally.\nThis can hide errors later on, so we recommend avoiding this\nif possible.\n\nFinally, mypy allows fine-grained control over specific import following\nbehaviour. It's very easy to silently shoot yourself in the foot when playing\naround with these, so this should be a last resort. For more\ndetails, look :ref:`here <follow-imports>`.\n\nPrioritise annotating widely imported modules\n---------------------------------------------\n\nMost projects have some widely imported modules, such as utilities or\nmodel classes. It's a good idea to annotate these pretty early on,\nsince this allows code using these modules to be type checked more\neffectively.\n\nMypy is designed to support gradual typing, i.e. letting you add annotations at\nyour own pace, so it's okay to leave some of these modules unannotated. The more\nyou annotate, the more useful mypy will be, but even a little annotation\ncoverage is useful.\n\nWrite annotations as you go\n---------------------------\n\nConsider adding something like these in your code style\nconventions:\n\n1. Developers should add annotations for any new code.\n2. It's also encouraged to write annotations when you modify existing code.\n\nThis way you'll gradually increase annotation coverage in your\ncodebase without much effort.\n\nAutomate annotation of legacy code\n----------------------------------\n\nThere are tools for automatically adding draft annotations based on simple\nstatic analysis or on type profiles collected at runtime.  Tools include\n:doc:`monkeytype:index`, `autotyping`_ and `PyAnnotate`_.\n\nA simple approach is to collect types from test runs. This may work\nwell if your test coverage is good (and if your tests aren't very\nslow).\n\nAnother approach is to enable type collection for a small, random\nfraction of production network requests.  This clearly requires more\ncare, as type collection could impact the reliability or the\nperformance of your service.\n\n.. _getting-to-strict:\n\nIntroduce stricter options\n--------------------------\n\nMypy is very configurable. Once you get started with static typing, you may want\nto explore the various strictness options mypy provides to catch more bugs. For\nexample, you can ask mypy to require annotations for all functions in certain\nmodules to avoid accidentally introducing code that won't be type checked using\n:confval:`disallow_untyped_defs`. Refer to :ref:`config-file` for the details.\n\nAn excellent goal to aim for is to have your codebase pass when run against ``mypy --strict``.\nThis basically ensures that you will never have a type related error without an explicit\ncircumvention somewhere (such as a ``# type: ignore`` comment).\n\nThe following config is equivalent to ``--strict`` (as of mypy 1.0):\n\n.. code-block:: text\n\n   # Start off with these\n   warn_unused_configs = True\n   warn_redundant_casts = True\n   warn_unused_ignores = True\n\n   # Getting this passing should be easy\n   strict_equality = True\n\n   # Strongly recommend enabling this one as soon as you can\n   check_untyped_defs = True\n\n   # These shouldn't be too much additional work, but may be tricky to\n   # get passing if you use a lot of untyped libraries\n   disallow_subclassing_any = True\n   disallow_untyped_decorators = True\n   disallow_any_generics = True\n\n   # These next few are various gradations of forcing use of type annotations\n   disallow_untyped_calls = True\n   disallow_incomplete_defs = True\n   disallow_untyped_defs = True\n\n   # This one isn't too hard to get passing, but return on investment is lower\n   no_implicit_reexport = True\n\n   # This one can be tricky to get passing if you use a lot of untyped libraries\n   warn_return_any = True\n\n   # This one is a catch-all flag for the rest of strict checks that are technically\n   # correct but may not be practical\n   extra_checks = True\n\nNote that you can also start with ``--strict`` and subtract, for instance:\n\n.. code-block:: text\n\n   strict = True\n   warn_return_any = False\n\nRemember that many of these options can be enabled on a per-module basis. For instance,\nyou may want to enable ``disallow_untyped_defs`` for modules which you've completed\nannotations for, in order to prevent new code from being added without annotations.\n\nAnd if you want, it doesn't stop at ``--strict``. Mypy has additional checks\nthat are not part of ``--strict`` that can be useful. See the complete\n:ref:`command-line` reference and :ref:`error-codes-optional`.\n\nSpeed up mypy runs\n------------------\n\nYou can use :ref:`mypy daemon <mypy_daemon>` to get much faster\nincremental mypy runs. The larger your project is, the more useful\nthis will be.  If your project has at least 100,000 lines of code or\nso, you may also want to set up :ref:`remote caching <remote-cache>`\nfor further speedups.\n\n.. _PyAnnotate: https://github.com/dropbox/pyannotate\n.. _autotyping: https://github.com/JelleZijlstra/autotyping\n"
  },
  {
    "path": "docs/source/extending_mypy.rst",
    "content": ".. _extending-mypy:\n\nExtending and integrating mypy\n==============================\n\n.. _integrating-mypy:\n\nIntegrating mypy into another Python application\n************************************************\n\nIt is possible to integrate mypy into another Python 3 application by\nimporting ``mypy.api`` and calling the ``run`` function with a parameter of type ``list[str]``, containing\nwhat normally would have been the command line arguments to mypy.\n\nFunction ``run`` returns a ``tuple[str, str, int]``, namely\n``(<normal_report>, <error_report>, <exit_status>)``, in which ``<normal_report>``\nis what mypy normally writes to :py:data:`sys.stdout`, ``<error_report>`` is what mypy\nnormally writes to :py:data:`sys.stderr` and ``exit_status`` is the exit status mypy normally\nreturns to the operating system.\n\nA trivial example of using the api is the following\n\n.. code-block:: python\n\n    import sys\n    from mypy import api\n\n    result = api.run(sys.argv[1:])\n\n    if result[0]:\n        print('\\nType checking report:\\n')\n        print(result[0])  # stdout\n\n    if result[1]:\n        print('\\nError report:\\n')\n        print(result[1])  # stderr\n\n    print('\\nExit status:', result[2])\n\n\n.. _extending-mypy-using-plugins:\n\nExtending mypy using plugins\n****************************\n\nPython is a highly dynamic language and has extensive metaprogramming\ncapabilities. Many popular libraries use these to create APIs that may\nbe more flexible and/or natural for humans, but are hard to express using\nstatic types. Extending the :pep:`484` type system to accommodate all existing\ndynamic patterns is impractical and often just impossible.\n\nMypy supports a plugin system that lets you customize the way mypy type checks\ncode. This can be useful if you want to extend mypy so it can type check code\nthat uses a library that is difficult to express using just :pep:`484` types.\n\nThe plugin system is focused on improving mypy's understanding\nof *semantics* of third party frameworks. There is currently no way to define\nnew first class kinds of types.\n\n.. note::\n\n   The plugin system is experimental and prone to change. If you want to write\n   a mypy plugin, we recommend you start by contacting the mypy core developers\n   on `gitter <https://gitter.im/python/typing>`_. In particular, there are\n   no guarantees about backwards compatibility.\n\n   Backwards incompatible changes may be made without a deprecation period,\n   but we will announce them in\n   `the plugin API changes announcement issue <https://github.com/python/mypy/issues/6617>`_.\n\nConfiguring mypy to use plugins\n*******************************\n\nPlugins are Python files that can be specified in a mypy\n:ref:`config file <config-file>` using the :confval:`plugins` option and one of the two formats: relative or\nabsolute path to the plugin file, or a module name (if the plugin\nis installed using ``pip install`` in the same virtual environment where mypy\nis running). The two formats can be mixed, for example:\n\n.. code-block:: ini\n\n    [mypy]\n    plugins = /one/plugin.py, other.plugin\n\nMypy will try to import the plugins and will look for an entry point function\nnamed ``plugin``. If the plugin entry point function has a different name, it\ncan be specified after colon:\n\n.. code-block:: ini\n\n    [mypy]\n    plugins = custom_plugin:custom_entry_point\n\nIn the following sections we describe the basics of the plugin system with\nsome examples. For more technical details, please read the docstrings in\n`mypy/plugin.py <https://github.com/python/mypy/blob/master/mypy/plugin.py>`_\nin mypy source code. Also you can find good examples in the bundled plugins\nlocated in `mypy/plugins <https://github.com/python/mypy/tree/master/mypy/plugins>`_.\n\nHigh-level overview\n*******************\n\nEvery entry point function should accept a single string argument\nthat is a full mypy version and return a subclass of ``mypy.plugin.Plugin``:\n\n.. code-block:: python\n\n   from mypy.plugin import Plugin\n\n   class CustomPlugin(Plugin):\n       def get_type_analyze_hook(self, fullname: str):\n           # see explanation below\n           ...\n\n   def plugin(version: str):\n       # ignore version argument if the plugin works with all mypy versions.\n       return CustomPlugin\n\nDuring different phases of analyzing the code (first in semantic analysis,\nand then in type checking) mypy calls plugin methods such as\n``get_type_analyze_hook()`` on user plugins. This particular method, for example,\ncan return a callback that mypy will use to analyze unbound types with the given\nfull name. See the full plugin hook method list :ref:`below <plugin_hooks>`.\n\nMypy maintains a list of plugins it gets from the config file plus the default\n(built-in) plugin that is always enabled. Mypy calls a method once for each\nplugin in the list until one of the methods returns a non-``None`` value.\nThis callback will be then used to customize the corresponding aspect of\nanalyzing/checking the current abstract syntax tree node.\n\nThe callback returned by the ``get_xxx`` method will be given a detailed\ncurrent context and an API to create new nodes, new types, emit error messages,\netc., and the result will be used for further processing.\n\nPlugin developers should ensure that their plugins work well in incremental and\ndaemon modes. In particular, plugins should not hold global state due to caching\nof plugin hook results.\n\n.. _plugin_hooks:\n\nCurrent list of plugin hooks\n****************************\n\n**get_type_analyze_hook()** customizes behaviour of the type analyzer.\nFor example, :pep:`484` doesn't support defining variadic generic types:\n\n.. code-block:: python\n\n   from lib import Vector\n\n   a: Vector[int, int]\n   b: Vector[int, int, int]\n\nWhen analyzing this code, mypy will call ``get_type_analyze_hook(\"lib.Vector\")``,\nso the plugin can return some valid type for each variable.\n\n**get_function_hook()** is used to adjust the return type of a function call.\nThis hook will be also called for instantiation of classes.\nThis is a good choice if the return type is too complex\nto be expressed by regular python typing.\n\n**get_function_signature_hook()** is used to adjust the signature of a function.\n\n**get_method_hook()** is the same as ``get_function_hook()`` but for methods\ninstead of module level functions.\n\n**get_method_signature_hook()** is used to adjust the signature of a method.\nThis includes special Python methods except :py:meth:`~object.__init__` and :py:meth:`~object.__new__`.\nFor example in this code:\n\n.. code-block:: python\n\n   from ctypes import Array, c_int\n\n   x: Array[c_int]\n   x[0] = 42\n\nmypy will call ``get_method_signature_hook(\"ctypes.Array.__setitem__\")``\nso that the plugin can mimic the :py:mod:`ctypes` auto-convert behavior.\n\n**get_attribute_hook()** overrides instance member field lookups and property\naccess (not method calls). This hook is only called for\nfields which already exist on the class. *Exception:* if :py:meth:`__getattr__ <object.__getattr__>` or\n:py:meth:`__getattribute__ <object.__getattribute__>` is a method on the class, the hook is called for all\nfields which do not refer to methods.\n\n**get_class_attribute_hook()** is similar to above, but for attributes on classes rather than instances.\nUnlike above, this does not have special casing for :py:meth:`__getattr__ <object.__getattr__>` or\n:py:meth:`__getattribute__ <object.__getattribute__>`.\n\n**get_class_decorator_hook()** can be used to update class definition for\ngiven class decorators. For example, you can add some attributes to the class\nto match runtime behaviour:\n\n.. code-block:: python\n\n   from dataclasses import dataclass\n\n   @dataclass  # built-in plugin adds `__init__` method here\n   class User:\n       name: str\n\n   user = User(name='example')  # mypy can understand this using a plugin\n\n**get_metaclass_hook()** is similar to above, but for metaclasses.\n\n**get_base_class_hook()** is similar to above, but for base classes.\n\n**get_dynamic_class_hook()** can be used to allow dynamic class definitions\nin mypy. This plugin hook is called for every assignment to a simple name\nwhere right hand side is a function call:\n\n.. code-block:: python\n\n   from lib import dynamic_class\n\n   X = dynamic_class('X', [])\n\nFor such definition, mypy will call ``get_dynamic_class_hook(\"lib.dynamic_class\")``.\nThe plugin should create the corresponding ``mypy.nodes.TypeInfo`` object, and\nplace it into a relevant symbol table. (Instances of this class represent\nclasses in mypy and hold essential information such as qualified name,\nmethod resolution order, etc.)\n\n**get_customize_class_mro_hook()** can be used to modify class MRO (for example\ninsert some entries there) before the class body is analyzed.\n\n**get_additional_deps()** can be used to add new dependencies for a\nmodule. It is called before semantic analysis. For example, this can\nbe used if a library has dependencies that are dynamically loaded\nbased on configuration information.\n\n**report_config_data()** can be used if the plugin has some sort of\nper-module configuration that can affect typechecking. In that case,\nwhen the configuration for a module changes, we want to invalidate\nmypy's cache for that module so that it can be rechecked. This hook\nshould be used to report to mypy any relevant configuration data,\nso that mypy knows to recheck the module if the configuration changes.\nThe hooks should return data encodable as JSON.\n\nUseful tools\n************\n\nMypy ships ``mypy.plugins.proper_plugin`` plugin which can be useful\nfor plugin authors, since it finds missing ``get_proper_type()`` calls,\nwhich is a pretty common mistake.\n\nIt is recommended to enable it as a part of your plugin's CI.\n"
  },
  {
    "path": "docs/source/faq.rst",
    "content": "Frequently Asked Questions\n==========================\n\nWhy have both dynamic and static typing?\n****************************************\n\nDynamic typing can be flexible, powerful, convenient and easy. But\nit's not always the best approach; there are good reasons why many\ndevelopers choose to use statically typed languages or static typing\nfor Python.\n\nHere are some potential benefits of mypy-style static typing:\n\n- Static typing can make programs easier to understand and\n  maintain. Type declarations can serve as machine-checked\n  documentation. This is important as code is typically read much more\n  often than modified, and this is especially important for large and\n  complex programs.\n\n- Static typing can help you find bugs earlier and with less testing\n  and debugging. Especially in large and complex projects this can be\n  a major time-saver.\n\n- Static typing can help you find difficult-to-find bugs before your\n  code goes into production. This can improve reliability and reduce\n  the number of security issues.\n\n- Static typing makes it practical to build very useful development\n  tools that can improve programming productivity or software quality,\n  including IDEs with precise and reliable code completion, static\n  analysis tools, etc.\n\n- You can get the benefits of both dynamic and static typing in a\n  single language. Dynamic typing can be perfect for a small project\n  or for writing the UI of your program, for example. As your program\n  grows, you can adapt tricky application logic to static typing to\n  help maintenance.\n\nSee also the `front page <https://www.mypy-lang.org>`_ of the mypy web\nsite.\n\nWould my project benefit from static typing?\n********************************************\n\nFor many projects dynamic typing is perfectly fine (we think that\nPython is a great language). But sometimes your projects demand bigger\nguns, and that's when mypy may come in handy.\n\nIf some of these ring true for your projects, mypy (and static typing)\nmay be useful:\n\n- Your project is large or complex.\n\n- Your codebase must be maintained for a long time.\n\n- Multiple developers are working on the same code.\n\n- Running tests takes a lot of time or work (type checking helps\n  you find errors quickly early in development, reducing the number of\n  testing iterations).\n\n- Some project members (devs or management) don't like dynamic typing,\n  but others prefer dynamic typing and Python syntax. Mypy could be a\n  solution that everybody finds easy to accept.\n\n- You want to future-proof your project even if currently none of the\n  above really apply. The earlier you start, the easier it will be to\n  adopt static typing.\n\nCan I use mypy to type check my existing Python code?\n*****************************************************\n\nMypy supports most Python features and idioms, and many large Python\nprojects are using mypy successfully. Code that uses complex\nintrospection or metaprogramming may be impractical to type check, but\nit should still be possible to use static typing in other parts of a\ncodebase that are less dynamic.\n\nWill static typing make my programs run faster?\n***********************************************\n\nMypy only does static type checking and it does not improve\nperformance. It has a minimal performance impact. In the future, there\ncould be other tools that can compile statically typed mypy code to C\nmodules or to efficient JVM bytecode, for example, but this is outside\nthe scope of the mypy project.\n\nIs mypy free?\n*************\n\nYes. Mypy is free software, and it can also be used for commercial and\nproprietary projects. Mypy is available under the MIT license.\n\nCan I use duck typing with mypy?\n********************************\n\nMypy provides support for both `nominal subtyping\n<https://en.wikipedia.org/wiki/Nominative_type_system>`_ and\n`structural subtyping\n<https://en.wikipedia.org/wiki/Structural_type_system>`_.\nStructural subtyping can be thought of as \"static duck typing\".\nSome argue that structural subtyping is better suited for languages with duck\ntyping such as Python. Mypy however primarily uses nominal subtyping,\nleaving structural subtyping mostly opt-in (except for built-in protocols\nsuch as :py:class:`~collections.abc.Iterable` that always support structural\nsubtyping). Here are some reasons why:\n\n1. It is easy to generate short and informative error messages when\n   using a nominal type system. This is especially important when\n   using type inference.\n\n2. Python provides built-in support for nominal :py:func:`isinstance` tests and\n   they are widely used in programs. Only limited support for structural\n   :py:func:`isinstance` is available, and it's less type safe than nominal type tests.\n\n3. Many programmers are already familiar with static, nominal subtyping and it\n   has been successfully used in languages such as Java, C++ and\n   C#. Fewer languages use structural subtyping.\n\nHowever, structural subtyping can also be useful. For example, a \"public API\"\nmay be more flexible if it is typed with protocols. Also, using protocol types\nremoves the necessity to explicitly declare implementations of ABCs.\nAs a rule of thumb, we recommend using nominal classes where possible, and\nprotocols where necessary. For more details about protocol types and structural\nsubtyping see :ref:`protocol-types` and :pep:`544`.\n\nI like Python and I have no need for static typing\n**************************************************\n\nThe aim of mypy is not to convince everybody to write statically typed\nPython -- static typing is entirely optional, now and in the\nfuture. The goal is to give more options for Python programmers, to\nmake Python a more competitive alternative to other statically typed\nlanguages in large projects, to improve programmer productivity, and\nto improve software quality.\n\nHow are mypy programs different from normal Python?\n***************************************************\n\nSince you use a vanilla Python implementation to run mypy programs,\nmypy programs are also Python programs. The type checker may give\nwarnings for some valid Python code, but the code is still always\nrunnable. Also, a few Python features are still not\nsupported by mypy, but this is gradually improving.\n\nThe obvious difference is the availability of static type\nchecking. The section :ref:`common_issues` mentions some\nmodifications to Python code that may be required to make code type\ncheck without errors. Also, your code must make defined\nattributes explicit.\n\nMypy supports modular, efficient type checking, and this seems to\nrule out type checking some language features, such as arbitrary\nmonkey patching of methods.\n\nHow is mypy different from Cython?\n**********************************\n\n:doc:`Cython <cython:index>` is a variant of Python that supports\ncompilation to CPython C modules. It can give major speedups to\ncertain classes of programs compared to CPython, and it provides\nstatic typing (though this is different from mypy). Mypy differs in\nthe following aspects, among others:\n\n- Cython is much more focused on performance than mypy. Mypy is only\n  about static type checking, and increasing performance is not a\n  direct goal.\n\n- The mypy syntax is arguably simpler and more \"Pythonic\" (no cdef/cpdef, etc.) for statically typed code.\n\n- The mypy syntax is compatible with Python. Mypy programs are normal\n  Python programs that can be run using any Python\n  implementation. Cython has many incompatible extensions to Python\n  syntax, and Cython programs generally cannot be run without first\n  compiling them to CPython extension modules via C. Cython also has a\n  pure Python mode, but it seems to support only a subset of Cython\n  functionality, and the syntax is quite verbose.\n\n- Mypy has a different set of type system features. For example, mypy\n  has genericity (parametric polymorphism), function types and\n  bidirectional type inference, which are not supported by\n  Cython. (Cython has fused types that are different but related to\n  mypy generics. Mypy also has a similar feature as an extension of\n  generics.)\n\n- The mypy type checker knows about the static types of many Python\n  stdlib modules and can effectively type check code that uses them.\n\n- Cython supports accessing C functions directly and many features are\n  defined in terms of translating them to C or C++. Mypy just uses\n  Python semantics, and mypy does not deal with accessing C library\n  functionality.\n\nDoes it run on PyPy?\n*********************\n\nSomewhat. With PyPy 3.8, mypy is at least able to type check itself.\nWith older versions of PyPy, mypy relies on `typed-ast\n<https://github.com/python/typed_ast>`_, which uses several APIs that\nPyPy does not support (including some internal CPython APIs).\n\nMypy is a cool project. Can I help?\n***********************************\n\nAny help is much appreciated! `Contact\n<https://www.mypy-lang.org/contact.html>`_ the developers if you would\nlike to contribute. Any help related to development, design,\npublicity, documentation, testing, web site maintenance, financing,\netc. can be helpful. You can learn a lot by contributing, and anybody\ncan help, even beginners! However, some knowledge of compilers and/or\ntype systems is essential if you want to work on mypy internals.\n"
  },
  {
    "path": "docs/source/final_attrs.rst",
    "content": ".. _final_attrs:\n\nFinal names, methods and classes\n================================\n\nThis section introduces these related features:\n\n1. *Final names* are variables or attributes that should not be reassigned after\n   initialization. They are useful for declaring constants.\n2. *Final methods* should not be overridden in a subclass.\n3. *Final classes* should not be subclassed.\n\nAll of these are only enforced by mypy, and only in annotated code.\nThere is no runtime enforcement by the Python runtime.\n\n.. note::\n\n    The examples in this page import ``Final`` and ``final`` from the\n    ``typing`` module. These types were added to ``typing`` in Python 3.8,\n    but are also available for use in Python 3.4 - 3.7 via the\n    ``typing_extensions`` package.\n\nFinal names\n-----------\n\nYou can use the ``typing.Final`` qualifier to indicate that\na name or attribute should not be reassigned, redefined, or\noverridden. This is often useful for module and class-level\nconstants to prevent unintended modification. Mypy will prevent\nfurther assignments to final names in type-checked code:\n\n.. code-block:: python\n\n   from typing import Final\n\n   RATE: Final = 3_000\n\n   class Base:\n       DEFAULT_ID: Final = 0\n\n   RATE = 300  # Error: can't assign to final attribute\n   Base.DEFAULT_ID = 1  # Error: can't override a final attribute\n\nAnother use case for final attributes is to protect certain attributes\nfrom being overridden in a subclass:\n\n.. code-block:: python\n\n   from typing import Final\n\n   class Window:\n       BORDER_WIDTH: Final = 2.5\n       ...\n\n   class ListView(Window):\n       BORDER_WIDTH = 3  # Error: can't override a final attribute\n\nYou can use :py:class:`@property <property>` to make an attribute read-only, but unlike ``Final``,\nit doesn't work with module attributes, and it doesn't prevent overriding in\nsubclasses.\n\nSyntax variants\n***************\n\nYou can use ``Final`` in one of these forms:\n\n* You can provide an explicit type using the syntax ``Final[<type>]``. Example:\n\n  .. code-block:: python\n\n     ID: Final[int] = 1\n\n  Here, mypy will infer type ``int`` for ``ID``.\n\n* You can omit the type:\n\n  .. code-block:: python\n\n     ID: Final = 1\n\n  Here, mypy will infer type ``Literal[1]`` for ``ID``. Note that unlike for\n  generic classes, this is *not* the same as ``Final[Any]``.\n\n* In class bodies and stub files, you can omit the right-hand side and just write\n  ``ID: Final[int]``.\n\n* Finally, you can write ``self.id: Final = 1`` (also optionally with\n  a type in square brackets). This is allowed *only* in\n  :py:meth:`__init__ <object.__init__>` methods so the final instance attribute is\n  assigned only once when an instance is created.\n\nDetails of using ``Final``\n**************************\n\nThese are the two main rules for defining a final name:\n\n* There can be *at most one* final declaration per module or class for\n  a given attribute. There can't be separate class-level and instance-level\n  constants with the same name.\n\n* There must be *exactly one* assignment to a final name.\n\nA final attribute declared in a class body without an initializer must\nbe initialized in the :py:meth:`__init__ <object.__init__>` method (you can skip the\ninitializer in stub files):\n\n.. code-block:: python\n\n   class ImmutablePoint:\n       x: Final[int]\n       y: Final[int]  # Error: final attribute without an initializer\n\n       def __init__(self) -> None:\n           self.x = 1  # Good\n\n``Final`` can only be used as the outermost type in assignments or variable\nannotations. Using it in any other position is an error. In particular,\n``Final`` can't be used in annotations for function arguments:\n\n.. code-block:: python\n\n   x: list[Final[int]] = []  # Error!\n\n   def fun(x: Final[list[int]]) ->  None:  # Error!\n       ...\n\n``Final`` and :py:data:`~typing.ClassVar` should not be used together. Mypy will infer\nthe scope of a final declaration automatically depending on whether it was\ninitialized in the class body or in :py:meth:`__init__ <object.__init__>`.\n\nA final attribute can't be overridden by a subclass (even with another\nexplicit final declaration). Note, however, that a final attribute can\noverride a read-only property:\n\n.. code-block:: python\n\n   class Base:\n       @property\n       def ID(self) -> int: ...\n\n   class Derived(Base):\n       ID: Final = 1  # OK\n\nDeclaring a name as final only guarantees that the name will not be re-bound\nto another value. It doesn't make the value immutable. You can use immutable ABCs\nand containers to prevent mutating such values:\n\n.. code-block:: python\n\n   x: Final = ['a', 'b']\n   x.append('c')  # OK\n\n   y: Final[Sequence[str]] = ['a', 'b']\n   y.append('x')  # Error: Sequence is immutable\n   z: Final = ('a', 'b')  # Also an option\n\nFinal methods\n-------------\n\nLike with attributes, sometimes it is useful to protect a method from\noverriding. You can use the ``typing.final`` decorator for this purpose:\n\n.. code-block:: python\n\n   from typing import final\n\n   class Base:\n       @final\n       def common_name(self) -> None:\n           ...\n\n   class Derived(Base):\n       def common_name(self) -> None:  # Error: cannot override a final method\n           ...\n\nThis ``@final`` decorator can be used with instance methods, class methods,\nstatic methods, and properties.\n\nFor overloaded methods, you should add ``@final`` on the implementation\nto make it final (or on the first overload in stubs):\n\n.. code-block:: python\n\n   from typing import final, overload\n\n   class Base:\n       @overload\n       def method(self) -> None: ...\n       @overload\n       def method(self, arg: int) -> int: ...\n       @final\n       def method(self, x=None):\n           ...\n\nFinal classes\n-------------\n\nYou can apply the ``typing.final`` decorator to a class to indicate\nto mypy that it should not be subclassed:\n\n.. code-block:: python\n\n   from typing import final\n\n   @final\n   class Leaf:\n       ...\n\n   class MyLeaf(Leaf):  # Error: Leaf can't be subclassed\n       ...\n\nThe decorator acts as a declaration for mypy (and as documentation for\nhumans), but it doesn't actually prevent subclassing at runtime.\n\nHere are some situations where using a final class may be useful:\n\n* A class wasn't designed to be subclassed. Perhaps subclassing would not\n  work as expected, or subclassing would be error-prone.\n* Subclassing would make code harder to understand or maintain.\n  For example, you may want to prevent unnecessarily tight coupling between\n  base classes and subclasses.\n* You want to retain the freedom to arbitrarily change the class implementation\n  in the future, and these changes might break subclasses.\n\nAn abstract class that defines at least one abstract method or\nproperty and has ``@final`` decorator will generate an error from\nmypy since those attributes could never be implemented.\n\n.. code-block:: python\n\n    from abc import ABCMeta, abstractmethod\n    from typing import final\n\n    @final\n    class A(metaclass=ABCMeta):  # error: Final class A has abstract attributes \"f\"\n        @abstractmethod\n        def f(self, x: int) -> None: pass\n"
  },
  {
    "path": "docs/source/generics.rst",
    "content": "Generics\n========\n\nThis section explains how you can define your own generic classes that take\none or more type arguments, similar to built-in types such as ``list[T]``.\nUser-defined generics are a moderately advanced feature and you can get far\nwithout ever using them -- feel free to skip this section and come back later.\n\n.. _generic-classes:\n\nDefining generic classes\n************************\n\nThe built-in collection classes are generic classes. Generic types\naccept one or more type arguments within ``[...]``, which can be\narbitrary types. For example, the type ``dict[int, str]`` has the\ntype arguments ``int`` and ``str``, and ``list[int]`` has the type\nargument ``int``.\n\nPrograms can also define new generic classes. Here is a very simple\ngeneric class that represents a stack (using the syntax introduced in\nPython 3.12):\n\n.. code-block:: python\n\n   class Stack[T]:\n       def __init__(self) -> None:\n           # Create an empty list with items of type T\n           self.items: list[T] = []\n\n       def push(self, item: T) -> None:\n           self.items.append(item)\n\n       def pop(self) -> T:\n           return self.items.pop()\n\n       def empty(self) -> bool:\n           return not self.items\n\nThere are two syntax variants for defining generic classes in Python.\nPython 3.12 introduced a\n`new dedicated syntax <https://docs.python.org/3/whatsnew/3.12.html#pep-695-type-parameter-syntax>`_\nfor defining generic classes (and also functions and type aliases, which\nwe will discuss later). The above example used the new syntax. Most examples are\ngiven using both the new and the old (or legacy) syntax variants.\nUnless mentioned otherwise, they work the same -- but the new syntax\nis more readable and more convenient.\n\nHere is the same example using the old syntax (required for Python 3.11\nand earlier, but also supported on newer Python versions):\n\n.. code-block:: python\n\n   from typing import TypeVar, Generic\n\n   T = TypeVar('T')  # Define type variable \"T\"\n\n   class Stack(Generic[T]):\n       def __init__(self) -> None:\n           # Create an empty list with items of type T\n           self.items: list[T] = []\n\n       def push(self, item: T) -> None:\n           self.items.append(item)\n\n       def pop(self) -> T:\n           return self.items.pop()\n\n       def empty(self) -> bool:\n           return not self.items\n\n.. note::\n\n    There are currently no plans to deprecate the legacy syntax.\n    You can freely mix code using the new and old syntax variants,\n    even within a single file (but *not* within a single class).\n\nThe ``Stack`` class can be used to represent a stack of any type:\n``Stack[int]``, ``Stack[tuple[int, str]]``, etc. You can think of\n``Stack[int]`` as referring to the definition of ``Stack`` above,\nbut with all instances of ``T`` replaced with ``int``.\n\nUsing ``Stack`` is similar to built-in container types:\n\n.. code-block:: python\n\n   # Construct an empty Stack[int] instance\n   stack = Stack[int]()\n   stack.push(2)\n   stack.pop()\n\n   # error: Argument 1 to \"push\" of \"Stack\" has incompatible type \"str\"; expected \"int\"\n   stack.push('x')\n\n   stack2: Stack[str] = Stack()\n   stack2.push('x')\n\nConstruction of instances of generic types is type checked (Python 3.12 syntax):\n\n.. code-block:: python\n\n   class Box[T]:\n       def __init__(self, content: T) -> None:\n           self.content = content\n\n   Box(1)       # OK, inferred type is Box[int]\n   Box[int](1)  # Also OK\n\n   # error: Argument 1 to \"Box\" has incompatible type \"str\"; expected \"int\"\n   Box[int]('some string')\n\nHere is the definition of ``Box`` using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n   from typing import TypeVar, Generic\n\n   T = TypeVar('T')\n\n   class Box(Generic[T]):\n       def __init__(self, content: T) -> None:\n           self.content = content\n\n.. note::\n\n    Before moving on, let's clarify some terminology.\n    The name ``T`` in ``class Stack[T]`` or ``class Stack(Generic[T])``\n    declares a *type parameter* ``T`` (of class ``Stack``).\n    ``T`` is also called a *type variable*, especially in a type annotation,\n    such as in the signature of ``push`` above.\n    When the type ``Stack[...]`` is used in a type annotation, the type\n    within square brackets is called a *type argument*.\n    This is similar to the distinction between function parameters and arguments.\n\n.. _generic-subclasses:\n\nDefining subclasses of generic classes\n**************************************\n\nUser-defined generic classes and generic classes defined in :py:mod:`typing`\ncan be used as a base class for another class (generic or non-generic). For\nexample (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from typing import Mapping, Iterator\n\n   # This is a generic subclass of Mapping\n   class MyMap[KT, VT](Mapping[KT, VT]):\n       def __getitem__(self, k: KT) -> VT: ...\n       def __iter__(self) -> Iterator[KT]: ...\n       def __len__(self) -> int: ...\n\n   items: MyMap[str, int]  # OK\n\n   # This is a non-generic subclass of dict\n   class StrDict(dict[str, str]):\n       def __str__(self) -> str:\n           return f'StrDict({super().__str__()})'\n\n   data: StrDict[int, int]  # Error! StrDict is not generic\n   data2: StrDict  # OK\n\n   # This is a user-defined generic class\n   class Receiver[T]:\n       def accept(self, value: T) -> None: ...\n\n   # This is a generic subclass of Receiver\n   class AdvancedReceiver[T](Receiver[T]): ...\n\nHere is the above example using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n   from typing import Generic, TypeVar, Mapping, Iterator\n\n   KT = TypeVar('KT')\n   VT = TypeVar('VT')\n\n   # This is a generic subclass of Mapping\n   class MyMap(Mapping[KT, VT]):\n       def __getitem__(self, k: KT) -> VT: ...\n       def __iter__(self) -> Iterator[KT]: ...\n       def __len__(self) -> int: ...\n\n   items: MyMap[str, int]  # OK\n\n   # This is a non-generic subclass of dict\n   class StrDict(dict[str, str]):\n       def __str__(self) -> str:\n           return f'StrDict({super().__str__()})'\n\n   data: StrDict[int, int]  # Error! StrDict is not generic\n   data2: StrDict  # OK\n\n   # This is a user-defined generic class\n   class Receiver(Generic[T]):\n       def accept(self, value: T) -> None: ...\n\n   # This is a generic subclass of Receiver\n   class AdvancedReceiver(Receiver[T]): ...\n\n.. note::\n\n    You have to add an explicit :py:class:`~collections.abc.Mapping` base class\n    if you want mypy to consider a user-defined class as a mapping (and\n    :py:class:`~collections.abc.Sequence` for sequences, etc.). This is because\n    mypy doesn't use *structural subtyping* for these ABCs, unlike simpler protocols\n    like :py:class:`~collections.abc.Iterable`, which use\n    :ref:`structural subtyping <protocol-types>`.\n\nWhen using the legacy syntax, :py:class:`Generic <typing.Generic>` can be omitted\nfrom bases if there are\nother base classes that include type variables, such as ``Mapping[KT, VT]``\nin the above example. If you include ``Generic[...]`` in bases, then\nit should list all type variables present in other bases (or more,\nif needed). The order of type parameters is defined by the following\nrules:\n\n* If ``Generic[...]`` is present, then the order of parameters is\n  always determined by their order in ``Generic[...]``.\n* If there are no ``Generic[...]`` in bases, then all type parameters\n  are collected in the lexicographic order (i.e. by first appearance).\n\nExample:\n\n.. code-block:: python\n\n   from typing import Generic, TypeVar, Any\n\n   T = TypeVar('T')\n   S = TypeVar('S')\n   U = TypeVar('U')\n\n   class One(Generic[T]): ...\n   class Another(Generic[T]): ...\n\n   class First(One[T], Another[S]): ...\n   class Second(One[T], Another[S], Generic[S, U, T]): ...\n\n   x: First[int, str]        # Here T is bound to int, S is bound to str\n   y: Second[int, str, Any]  # Here T is Any, S is int, and U is str\n\nWhen using the Python 3.12 syntax, all type parameters must always be\nexplicitly defined immediately after the class name within ``[...]``, and the\n``Generic[...]`` base class is never used.\n\n.. _generic-functions:\n\nGeneric functions\n*****************\n\nFunctions can also be generic, i.e. they can have type parameters (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from collections.abc import Sequence\n\n   # A generic function!\n   def first[T](seq: Sequence[T]) -> T:\n       return seq[0]\n\nHere is the same example using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n   from typing import TypeVar, Sequence\n\n   T = TypeVar('T')\n\n   # A generic function!\n   def first(seq: Sequence[T]) -> T:\n       return seq[0]\n\nAs with generic classes, the type parameter ``T`` can be replaced with any\ntype. That means ``first`` can be passed an argument with any sequence type,\nand the return type is derived from the sequence item type. Example:\n\n.. code-block:: python\n\n   reveal_type(first([1, 2, 3]))   # Revealed type is \"builtins.int\"\n   reveal_type(first(('a', 'b')))  # Revealed type is \"builtins.str\"\n\nWhen using the legacy syntax, a single definition of a type variable\n(such as ``T`` above) can be used in multiple generic functions or\nclasses. In this example we use the same type variable in two generic\nfunctions to declare type parameters:\n\n.. code-block:: python\n\n   from typing import TypeVar, Sequence\n\n   T = TypeVar('T')      # Define type variable\n\n   def first(seq: Sequence[T]) -> T:\n       return seq[0]\n\n   def last(seq: Sequence[T]) -> T:\n       return seq[-1]\n\nSince the Python 3.12 syntax is more concise, it doesn't need (or have)\nan equivalent way of sharing type parameter definitions.\n\nA variable cannot have a type variable in its type unless the type\nvariable is bound in a containing generic class or function.\n\nWhen calling a generic function, you can't explicitly pass the values of\ntype parameters as type arguments. The values of type parameters are always\ninferred by mypy. This is not valid:\n\n.. code-block:: python\n\n    first[int]([1, 2])  # Error: can't use [...] with generic function\n\nIf you really need this, you can define a generic class with a ``__call__``\nmethod.\n\n.. _type-variable-upper-bound:\n\nType variables with upper bounds\n********************************\n\nA type variable can also be restricted to having values that are\nsubtypes of a specific type. This type is called the upper bound of\nthe type variable, and it is specified using ``T: <bound>`` when using the\nPython 3.12 syntax. In the definition of a generic function or a generic\nclass that uses such a type variable ``T``, the type represented by ``T``\nis assumed to be a subtype of its upper bound, so you can use methods\nof the upper bound on values of type ``T`` (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from typing import SupportsAbs\n\n   def max_by_abs[T: SupportsAbs[float]](*xs: T) -> T:\n       # We can use abs(), because T is a subtype of SupportsAbs[float].\n       return max(xs, key=abs)\n\nAn upper bound can also be specified with the ``bound=...`` keyword\nargument to :py:class:`~typing.TypeVar`.\nHere is the example using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n   from typing import TypeVar, SupportsAbs\n\n   T = TypeVar('T', bound=SupportsAbs[float])\n\n   def max_by_abs(*xs: T) -> T:\n       return max(xs, key=abs)\n\nIn a call to such a function, the type ``T`` must be replaced by a\ntype that is a subtype of its upper bound. Continuing the example\nabove:\n\n.. code-block:: python\n\n   max_by_abs(-3.5, 2)   # Okay, has type 'float'\n   max_by_abs(5+6j, 7)   # Okay, has type 'complex'\n   max_by_abs('a', 'b')  # Error: 'str' is not a subtype of SupportsAbs[float]\n\nType parameters of generic classes may also have upper bounds, which\nrestrict the valid values for the type parameter in the same way.\n\n.. _generic-methods-and-generic-self:\n\nGeneric methods and generic self\n********************************\n\nYou can also define generic methods. In\nparticular, the ``self`` parameter may also be generic, allowing a\nmethod to return the most precise type known at the point of access.\nIn this way, for example, you can type check a chain of setter\nmethods (Python 3.12 syntax):\n\n.. code-block:: python\n\n   class Shape:\n       def set_scale[T: Shape](self: T, scale: float) -> T:\n           self.scale = scale\n           return self\n\n   class Circle(Shape):\n       def set_radius(self, r: float) -> 'Circle':\n           self.radius = r\n           return self\n\n   class Square(Shape):\n       def set_width(self, w: float) -> 'Square':\n           self.width = w\n           return self\n\n   circle: Circle = Circle().set_scale(0.5).set_radius(2.7)\n   square: Square = Square().set_scale(0.5).set_width(3.2)\n\nWithout using generic ``self``, the last two lines could not be type\nchecked properly, since the return type of ``set_scale`` would be\n``Shape``, which doesn't define ``set_radius`` or ``set_width``.\n\nWhen using the legacy syntax, just use a type variable in the\nmethod signature that is different from class type parameters (if any\nare defined). Here is the above example using the legacy\nsyntax (3.11 and earlier):\n\n.. code-block:: python\n\n   from typing import TypeVar\n\n   T = TypeVar('T', bound='Shape')\n\n   class Shape:\n       def set_scale(self: T, scale: float) -> T:\n           self.scale = scale\n           return self\n\n   class Circle(Shape):\n       def set_radius(self, r: float) -> 'Circle':\n           self.radius = r\n           return self\n\n   class Square(Shape):\n       def set_width(self, w: float) -> 'Square':\n           self.width = w\n           return self\n\n   circle: Circle = Circle().set_scale(0.5).set_radius(2.7)\n   square: Square = Square().set_scale(0.5).set_width(3.2)\n\nOther uses include factory methods, such as copy and deserialization methods.\nFor class methods, you can also define generic ``cls``, using ``type[T]``\nor :py:class:`Type[T] <typing.Type>` (Python 3.12 syntax):\n\n.. code-block:: python\n\n   class Friend:\n       other: \"Friend | None\" = None\n\n       @classmethod\n       def make_pair[T: Friend](cls: type[T]) -> tuple[T, T]:\n           a, b = cls(), cls()\n           a.other = b\n           b.other = a\n           return a, b\n\n   class SuperFriend(Friend):\n       pass\n\n   a, b = SuperFriend.make_pair()\n\nHere is the same example using the legacy syntax (3.11 and earlier):\n\n.. code-block:: python\n\n   from typing import TypeVar\n\n   T = TypeVar('T', bound='Friend')\n\n   class Friend:\n       other: \"Friend | None\" = None\n\n       @classmethod\n       def make_pair(cls: type[T]) -> tuple[T, T]:\n           a, b = cls(), cls()\n           a.other = b\n           b.other = a\n           return a, b\n\n   class SuperFriend(Friend):\n       pass\n\n   a, b = SuperFriend.make_pair()\n\nNote that when overriding a method with generic ``self``, you must either\nreturn a generic ``self`` too, or return an instance of the current class.\nIn the latter case, you must implement this method in all future subclasses.\n\nNote also that mypy cannot always verify that the implementation of a copy\nor a deserialization method returns the actual type of self. Therefore\nyou may need to silence mypy inside these methods (but not at the call site),\npossibly by making use of the ``Any`` type or a ``# type: ignore`` comment.\n\nMypy lets you use generic self types in certain unsafe ways\nin order to support common idioms. For example, using a generic\nself type in an argument type is accepted even though it's unsafe (Python 3.12\nsyntax):\n\n.. code-block:: python\n\n   class Base:\n       def compare[T: Base](self: T, other: T) -> bool:\n           return False\n\n   class Sub(Base):\n       def __init__(self, x: int) -> None:\n           self.x = x\n\n       # This is unsafe (see below) but allowed because it's\n       # a common pattern and rarely causes issues in practice.\n       def compare(self, other: 'Sub') -> bool:\n           return self.x > other.x\n\n   b: Base = Sub(42)\n   b.compare(Base())  # Runtime error here: 'Base' object has no attribute 'x'\n\nFor some advanced uses of self types, see :ref:`additional examples <advanced_self>`.\n\nAutomatic self types using typing.Self\n**************************************\n\nSince the patterns described above are quite common, mypy supports a\nsimpler syntax, introduced in :pep:`673`, to make them easier to use.\nInstead of introducing a type parameter and using an explicit annotation\nfor ``self``, you can import the special type ``typing.Self`` that is\nautomatically transformed into a method-level type parameter with the\ncurrent class as the upper bound, and you don't need an annotation for\n``self`` (or ``cls`` in class methods). The example from the previous\nsection can be made simpler by using ``Self``:\n\n.. code-block:: python\n\n   from typing import Self\n\n   class Friend:\n       other: Self | None = None\n\n       @classmethod\n       def make_pair(cls) -> tuple[Self, Self]:\n           a, b = cls(), cls()\n           a.other = b\n           b.other = a\n           return a, b\n\n   class SuperFriend(Friend):\n       pass\n\n   a, b = SuperFriend.make_pair()\n\nThis is more compact than using explicit type parameters. Also, you can\nuse ``Self`` in attribute annotations in addition to methods.\n\n.. note::\n\n   To use this feature on Python versions earlier than 3.11, you will need to\n   import ``Self`` from ``typing_extensions`` (version 4.0 or newer).\n\n.. _variance-of-generics:\n\nVariance of generic types\n*************************\n\nThere are three main kinds of generic types with respect to subtype\nrelations between them: invariant, covariant, and contravariant.\nAssuming that we have a pair of types ``A`` and ``B``, and ``B`` is\na subtype of ``A``, these are defined as follows:\n\n* A generic class ``MyCovGen[T]`` is called covariant in type variable\n  ``T`` if ``MyCovGen[B]`` is always a subtype of ``MyCovGen[A]``.\n* A generic class ``MyContraGen[T]`` is called contravariant in type\n  variable ``T`` if ``MyContraGen[A]`` is always a subtype of\n  ``MyContraGen[B]``.\n* A generic class ``MyInvGen[T]`` is called invariant in ``T`` if neither\n  of the above is true.\n\nLet us illustrate this by few simple examples:\n\n.. code-block:: python\n\n    # We'll use these classes in the examples below\n    class Shape: ...\n    class Triangle(Shape): ...\n    class Square(Shape): ...\n\n* Most immutable container types, such as :py:class:`~collections.abc.Sequence`\n  and :py:class:`~frozenset` are covariant. Union types are\n  also covariant in all union items: ``Triangle | int`` is\n  a subtype of ``Shape | int``.\n\n  .. code-block:: python\n\n    def count_lines(shapes: Sequence[Shape]) -> int:\n        return sum(shape.num_sides for shape in shapes)\n\n    triangles: Sequence[Triangle]\n    count_lines(triangles)  # OK\n\n    def foo(triangle: Triangle, num: int) -> None:\n        shape_or_number: Union[Shape, int]\n        # a Triangle is a Shape, and a Shape is a valid Union[Shape, int]\n        shape_or_number = triangle\n\n  Covariance should feel relatively intuitive, but contravariance and invariance\n  can be harder to reason about.\n\n* :py:class:`~collections.abc.Callable` is an example of type that behaves contravariant\n  in types of arguments. That is, ``Callable[[Shape], int]`` is a subtype of\n  ``Callable[[Triangle], int]``, despite ``Shape`` being a supertype of\n  ``Triangle``. To understand this, consider:\n\n  .. code-block:: python\n\n    def cost_of_paint_required(\n        triangle: Triangle,\n        area_calculator: Callable[[Triangle], float]\n    ) -> float:\n        return area_calculator(triangle) * DOLLAR_PER_SQ_FT\n\n    # This straightforwardly works\n    def area_of_triangle(triangle: Triangle) -> float: ...\n    cost_of_paint_required(triangle, area_of_triangle)  # OK\n\n    # But this works as well!\n    def area_of_any_shape(shape: Shape) -> float: ...\n    cost_of_paint_required(triangle, area_of_any_shape)  # OK\n\n  ``cost_of_paint_required`` needs a callable that can calculate the area of a\n  triangle. If we give it a callable that can calculate the area of an\n  arbitrary shape (not just triangles), everything still works.\n\n* ``list`` is an invariant generic type. Naively, one would think\n  that it is covariant, like :py:class:`~collections.abc.Sequence` above, but consider this code:\n\n  .. code-block:: python\n\n     class Circle(Shape):\n         # The rotate method is only defined on Circle, not on Shape\n         def rotate(self): ...\n\n     def add_one(things: list[Shape]) -> None:\n         things.append(Shape())\n\n     my_circles: list[Circle] = []\n     add_one(my_circles)     # This may appear safe, but...\n     my_circles[0].rotate()  # ...this will fail, since my_circles[0] is now a Shape, not a Circle\n\n  Another example of invariant type is ``dict``. Most mutable containers\n  are invariant.\n\nWhen using the Python 3.12 syntax for generics, mypy will automatically\ninfer the most flexible variance for each class type variable. Here\n``Box`` will be inferred as covariant:\n\n.. code-block:: python\n\n   class Box[T]:  # this type is implicitly covariant\n       def __init__(self, content: T) -> None:\n           self._content = content\n\n       def get_content(self) -> T:\n           return self._content\n\n   def look_into(box: Box[Shape]): ...\n\n   my_box = Box(Square())\n   look_into(my_box)  # OK, but mypy would complain here for an invariant type\n\nHere the underscore prefix for ``_content`` is significant. Without an\nunderscore prefix, the class would be invariant, as the attribute would\nbe understood as a public, mutable attribute (a single underscore prefix\nhas no special significance for mypy in most other contexts). By declaring\nthe attribute as ``Final``, the class could still be made covariant:\n\n.. code-block:: python\n\n   from typing import Final\n\n   class Box[T]:  # this type is implicitly covariant\n       def __init__(self, content: T) -> None:\n           self.content: Final = content\n\n       def get_content(self) -> T:\n           return self.content\n\nWhen using the legacy syntax, mypy assumes that all user-defined generics\nare invariant by default. To declare a given generic class as covariant or\ncontravariant, use type variables defined with special keyword arguments\n``covariant`` or ``contravariant``. For example (Python 3.11 or earlier):\n\n.. code-block:: python\n\n   from typing import Generic, TypeVar\n\n   T_co = TypeVar('T_co', covariant=True)\n\n   class Box(Generic[T_co]):  # this type is declared covariant\n       def __init__(self, content: T_co) -> None:\n           self._content = content\n\n       def get_content(self) -> T_co:\n           return self._content\n\n   def look_into(box: Box[Shape]): ...\n\n   my_box = Box(Square())\n   look_into(my_box)  # OK, but mypy would complain here for an invariant type\n\n.. _type-variable-value-restriction:\n\nType variables with value restriction\n*************************************\n\nBy default, a type variable can be replaced with any type -- or any type that\nis a subtype of the upper bound, which defaults to ``object``. However, sometimes\nit's useful to have a type variable that can only have some specific types\nas its value. A typical example is a type variable that can only have values\n``str`` and ``bytes``. This lets us define a function that can concatenate\ntwo strings or bytes objects, but it can't be called with other argument\ntypes (Python 3.12 syntax):\n\n.. code-block:: python\n\n   def concat[S: (str, bytes)](x: S, y: S) -> S:\n       return x + y\n\n   concat('a', 'b')    # Okay\n   concat(b'a', b'b')  # Okay\n   concat(1, 2)        # Error!\n\n\nThe same thing is also possibly using the legacy syntax (Python 3.11 or earlier):\n\n.. code-block:: python\n\n   from typing import TypeVar\n\n   AnyStr = TypeVar('AnyStr', str, bytes)\n\n   def concat(x: AnyStr, y: AnyStr) -> AnyStr:\n       return x + y\n\nNo matter which syntax you use, such a type variable is called a type variable\nwith a value restriction. Importantly, this is different from a union type,\nsince combinations of ``str`` and ``bytes`` are not accepted:\n\n.. code-block:: python\n\n   concat('string', b'bytes')   # Error!\n\nIn this case, this is exactly what we want, since it's not possible\nto concatenate a string and a bytes object! If we tried to use\na union type, the type checker would complain about this possibility:\n\n.. code-block:: python\n\n   def union_concat(x: str | bytes, y: str | bytes) -> str | bytes:\n       return x + y  # Error: can't concatenate str and bytes\n\nAnother interesting special case is calling ``concat()`` with a\nsubtype of ``str``:\n\n.. code-block:: python\n\n    class S(str): pass\n\n    ss = concat(S('foo'), S('bar'))\n    reveal_type(ss)  # Revealed type is \"builtins.str\"\n\nYou may expect that the type of ``ss`` is ``S``, but the type is\nactually ``str``: a subtype gets promoted to one of the valid values\nfor the type variable, which in this case is ``str``.\n\nThis is thus subtly different from using ``str | bytes`` as an upper bound,\nwhere the return type would be ``S`` (see :ref:`type-variable-upper-bound`).\nUsing a value restriction is correct for ``concat``, since ``concat``\nactually returns a ``str`` instance in the above example:\n\n.. code-block:: python\n\n    >>> print(type(ss))\n    <class 'str'>\n\nYou can also use type variables with a restricted set of possible\nvalues when defining a generic class. For example, the type\n:py:class:`Pattern[S] <typing.Pattern>` is used for the return\nvalue of :py:func:`re.compile`, where ``S`` can be either ``str``\nor ``bytes``. Regular expressions can be based on a string or a\nbytes pattern.\n\nA type variable may not have both a value restriction and an upper bound.\n\nNote that you may come across :py:data:`~typing.AnyStr` imported from\n:py:mod:`typing`. This feature is now deprecated, but it means the same\nas our definition of ``AnyStr`` above.\n\n.. _declaring-decorators:\n\nDeclaring decorators\n********************\n\nDecorators are typically functions that take a function as an argument and\nreturn another function. Describing this behaviour in terms of types can\nbe a little tricky; we'll show how you can use type variables and a special\nkind of type variable called a *parameter specification* to do so.\n\nSuppose we have the following decorator, not type annotated yet,\nthat preserves the original function's signature and merely prints the decorated\nfunction's name:\n\n.. code-block:: python\n\n   def printing_decorator(func):\n       def wrapper(*args, **kwds):\n           print(\"Calling\", func)\n           return func(*args, **kwds)\n       return wrapper\n\nWe can use it to decorate function ``add_forty_two``:\n\n.. code-block:: python\n\n   # A decorated function.\n   @printing_decorator\n   def add_forty_two(value: int) -> int:\n       return value + 42\n\n   a = add_forty_two(3)\n\nSince ``printing_decorator`` is not type-annotated, the following won't get type checked:\n\n.. code-block:: python\n\n   reveal_type(a)        # Revealed type is \"Any\"\n   add_forty_two('foo')  # No type checker error :(\n\nThis is a sorry state of affairs! If you run with ``--strict``, mypy will\neven alert you to this fact:\n``Untyped decorator makes function \"add_forty_two\" untyped``\n\nNote that class decorators are handled differently than function decorators in\nmypy: decorating a class does not erase its type, even if the decorator has\nincomplete type annotations.\n\nHere's how one could annotate the decorator (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from collections.abc import Callable\n   from typing import Any, cast\n\n   # A decorator that preserves the signature.\n   def printing_decorator[F: Callable[..., Any]](func: F) -> F:\n       def wrapper(*args, **kwds):\n           print(\"Calling\", func)\n           return func(*args, **kwds)\n       return cast(F, wrapper)\n\n   @printing_decorator\n   def add_forty_two(value: int) -> int:\n       return value + 42\n\n   a = add_forty_two(3)\n   reveal_type(a)      # Revealed type is \"builtins.int\"\n   add_forty_two('x')  # Argument 1 to \"add_forty_two\" has incompatible type \"str\"; expected \"int\"\n\nHere is the example using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n   from collections.abc import Callable\n   from typing import Any, TypeVar, cast\n\n   F = TypeVar('F', bound=Callable[..., Any])\n\n   # A decorator that preserves the signature.\n   def printing_decorator(func: F) -> F:\n       def wrapper(*args, **kwds):\n           print(\"Calling\", func)\n           return func(*args, **kwds)\n       return cast(F, wrapper)\n\n   @printing_decorator\n   def add_forty_two(value: int) -> int:\n       return value + 42\n\n   a = add_forty_two(3)\n   reveal_type(a)      # Revealed type is \"builtins.int\"\n   add_forty_two('x')  # Argument 1 to \"add_forty_two\" has incompatible type \"str\"; expected \"int\"\n\nThis still has some shortcomings. First, we need to use the unsafe\n:py:func:`~typing.cast` to convince mypy that ``wrapper()`` has the same\nsignature as ``func`` (see :ref:`casts <casts>`).\n\nSecond, the ``wrapper()`` function is not tightly type checked, although\nwrapper functions are typically small enough that this is not a big\nproblem. This is also the reason for the :py:func:`~typing.cast` call in the\n``return`` statement in ``printing_decorator()``.\n\nHowever, we can use a parameter specification, introduced using ``**P``,\nfor a more faithful type annotation (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from collections.abc import Callable\n\n   def printing_decorator[**P, T](func: Callable[P, T]) -> Callable[P, T]:\n       def wrapper(*args: P.args, **kwds: P.kwargs) -> T:\n           print(\"Calling\", func)\n           return func(*args, **kwds)\n       return wrapper\n\nThe same is possible using the legacy syntax with :py:class:`~typing.ParamSpec`\n(Python 3.11 and earlier):\n\n.. code-block:: python\n\n   from collections.abc import Callable\n   from typing import TypeVar\n   from typing_extensions import ParamSpec\n\n   P = ParamSpec('P')\n   T = TypeVar('T')\n\n   def printing_decorator(func: Callable[P, T]) -> Callable[P, T]:\n       def wrapper(*args: P.args, **kwds: P.kwargs) -> T:\n           print(\"Calling\", func)\n           return func(*args, **kwds)\n       return wrapper\n\nParameter specifications also allow you to describe decorators that\nalter the signature of the input function (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from collections.abc import Callable\n\n   # We reuse 'P' in the return type, but replace 'T' with 'str'\n   def stringify[**P, T](func: Callable[P, T]) -> Callable[P, str]:\n       def wrapper(*args: P.args, **kwds: P.kwargs) -> str:\n           return str(func(*args, **kwds))\n       return wrapper\n\n    @stringify\n    def add_forty_two(value: int) -> int:\n        return value + 42\n\n    a = add_forty_two(3)\n    reveal_type(a)      # Revealed type is \"builtins.str\"\n    add_forty_two('x')  # error: Argument 1 to \"add_forty_two\" has incompatible type \"str\"; expected \"int\"\n\nHere is the above example using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n   from collections.abc import Callable\n   from typing import TypeVar\n   from typing_extensions import ParamSpec\n\n   P = ParamSpec('P')\n   T = TypeVar('T')\n\n   # We reuse 'P' in the return type, but replace 'T' with 'str'\n   def stringify(func: Callable[P, T]) -> Callable[P, str]:\n       def wrapper(*args: P.args, **kwds: P.kwargs) -> str:\n           return str(func(*args, **kwds))\n       return wrapper\n\nYou can also insert an argument in a decorator (Python 3.12 syntax):\n\n.. code-block:: python\n\n    from collections.abc import Callable\n    from typing import Concatenate\n\n    def printing_decorator[**P, T](func: Callable[P, T]) -> Callable[Concatenate[str, P], T]:\n        def wrapper(msg: str, /, *args: P.args, **kwds: P.kwargs) -> T:\n            print(\"Calling\", func, \"with\", msg)\n            return func(*args, **kwds)\n        return wrapper\n\n    @printing_decorator\n    def add_forty_two(value: int) -> int:\n        return value + 42\n\n    a = add_forty_two('three', 3)\n\nHere is the same function using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n    from collections.abc import Callable\n    from typing import TypeVar\n    from typing_extensions import Concatenate, ParamSpec\n\n    P = ParamSpec('P')\n    T = TypeVar('T')\n\n    def printing_decorator(func: Callable[P, T]) -> Callable[Concatenate[str, P], T]:\n        def wrapper(msg: str, /, *args: P.args, **kwds: P.kwargs) -> T:\n            print(\"Calling\", func, \"with\", msg)\n            return func(*args, **kwds)\n        return wrapper\n\n.. _decorator-factories:\n\nDecorator factories\n-------------------\n\nFunctions that take arguments and return a decorator (also called second-order decorators), are\nsimilarly supported via generics (Python 3.12 syntax):\n\n.. code-block:: python\n\n    from collections.abc import Callable\n    from typing import Any\n\n    def route[F: Callable[..., Any]](url: str) -> Callable[[F], F]:\n        ...\n\n    @route(url='/')\n    def index(request: Any) -> str:\n        return 'Hello world'\n\nNote that mypy infers that ``F`` is used to make the ``Callable`` return value\nof ``route`` generic, instead of making ``route`` itself generic, since ``F`` is\nonly used in the return type. Python has no explicit syntax to mark that ``F``\nis only bound in the return value.\n\nHere is the example using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n    from collections.abc import Callable\n    from typing import Any, TypeVar\n\n    F = TypeVar('F', bound=Callable[..., Any])\n\n    def route(url: str) -> Callable[[F], F]:\n        ...\n\n    @route(url='/')\n    def index(request: Any) -> str:\n        return 'Hello world'\n\nSometimes the same decorator supports both bare calls and calls with arguments. This can be\nachieved by combining with :py:func:`@overload <typing.overload>` (Python 3.12 syntax):\n\n.. code-block:: python\n\n    from collections.abc import Callable\n    from typing import Any, overload\n\n    # Bare decorator usage\n    @overload\n    def atomic[F: Callable[..., Any]](func: F, /) -> F: ...\n    # Decorator with arguments\n    @overload\n    def atomic[F: Callable[..., Any]](*, savepoint: bool = True) -> Callable[[F], F]: ...\n\n    # Implementation\n    def atomic(func: Callable[..., Any] | None = None, /, *, savepoint: bool = True):\n        def decorator(func: Callable[..., Any]):\n            ...  # Code goes here\n        if __func is not None:\n            return decorator(__func)\n        else:\n            return decorator\n\n    # Usage\n    @atomic\n    def func1() -> None: ...\n\n    @atomic(savepoint=False)\n    def func2() -> None: ...\n\nHere is the decorator from the example using the legacy syntax\n(Python 3.11 and earlier):\n\n.. code-block:: python\n\n    from collections.abc import Callable\n    from typing import Any, Optional, TypeVar, overload\n\n    F = TypeVar('F', bound=Callable[..., Any])\n\n    # Bare decorator usage\n    @overload\n    def atomic(func: F, /) -> F: ...\n    # Decorator with arguments\n    @overload\n    def atomic(*, savepoint: bool = True) -> Callable[[F], F]: ...\n\n    # Implementation\n    def atomic(func: Optional[Callable[..., Any]] = None, /, *, savepoint: bool = True):\n        ...  # Same as above\n\nGeneric protocols\n*****************\n\nMypy supports generic protocols (see also :ref:`protocol-types`). Several\n:ref:`predefined protocols <predefined_protocols>` are generic, such as\n:py:class:`Iterable[T] <collections.abc.Iterable>`, and you can define additional\ngeneric protocols. Generic protocols mostly follow the normal rules for\ngeneric classes. Example (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from typing import Protocol\n\n   class Box[T](Protocol):\n       content: T\n\n   def do_stuff(one: Box[str], other: Box[bytes]) -> None:\n       ...\n\n   class StringWrapper:\n       def __init__(self, content: str) -> None:\n           self.content = content\n\n   class BytesWrapper:\n       def __init__(self, content: bytes) -> None:\n           self.content = content\n\n   do_stuff(StringWrapper('one'), BytesWrapper(b'other'))  # OK\n\n   x: Box[float] = ...\n   y: Box[int] = ...\n   x = y  # Error -- Box is invariant\n\nHere is the definition of ``Box`` from the above example using the legacy\nsyntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n   from typing import Protocol, TypeVar\n\n   T = TypeVar('T')\n\n   class Box(Protocol[T]):\n       content: T\n\nNote that ``class ClassName(Protocol[T])`` is allowed as a shorthand for\n``class ClassName(Protocol, Generic[T])`` when using the legacy syntax,\nas per :pep:`PEP 544: Generic protocols <544#generic-protocols>`.\nThis form is only valid when using the legacy syntax.\n\nWhen using the legacy syntax, there is an important difference between\ngeneric protocols and ordinary generic classes: mypy checks that the\ndeclared variances of generic type variables in a protocol match how\nthey are used in the protocol definition.  The protocol in this example\nis rejected, since the type variable ``T`` is used covariantly as\na return type, but the type variable is invariant:\n\n.. code-block:: python\n\n   from typing import Protocol, TypeVar\n\n   T = TypeVar('T')\n\n   class ReadOnlyBox(Protocol[T]):  # error: Invariant type variable \"T\" used in protocol where covariant one is expected\n       def content(self) -> T: ...\n\nThis example correctly uses a covariant type variable:\n\n.. code-block:: python\n\n   from typing import Protocol, TypeVar\n\n   T_co = TypeVar('T_co', covariant=True)\n\n   class ReadOnlyBox(Protocol[T_co]):  # OK\n       def content(self) -> T_co: ...\n\n   ax: ReadOnlyBox[float] = ...\n   ay: ReadOnlyBox[int] = ...\n   ax = ay  # OK -- ReadOnlyBox is covariant\n\nSee :ref:`variance-of-generics` for more about variance.\n\nGeneric protocols can also be recursive. Example (Python 3.12 syntax):\n\n.. code-block:: python\n\n   class Linked[T](Protocol):\n       val: T\n       def next(self) -> 'Linked[T]': ...\n\n   class L:\n       val: int\n       def next(self) -> 'L': ...\n\n   def last(seq: Linked[T]) -> T: ...\n\n   result = last(L())\n   reveal_type(result)  # Revealed type is \"builtins.int\"\n\nHere is the definition of ``Linked`` using the legacy syntax\n(Python 3.11 and earlier):\n\n.. code-block:: python\n\n   from typing import TypeVar\n\n   T = TypeVar('T')\n\n   class Linked(Protocol[T]):\n       val: T\n       def next(self) -> 'Linked[T]': ...\n\n.. _generic-type-aliases:\n\nGeneric type aliases\n********************\n\nType aliases can be generic. In this case they can be used in two ways.\nFirst, subscripted aliases are equivalent to original types with substituted type\nvariables. Second, unsubscripted aliases are treated as original types with type\nparameters replaced with ``Any``.\n\nThe ``type`` statement introduced in Python 3.12 is used to define generic\ntype aliases (it also supports non-generic type aliases):\n\n.. code-block:: python\n\n    from collections.abc import Callable, Iterable\n\n    type TInt[S] = tuple[int, S]\n    type UInt[S] = S | int\n    type CBack[S] = Callable[..., S]\n\n    def response(query: str) -> UInt[str]:  # Same as str | int\n        ...\n    def activate[S](cb: CBack[S]) -> S:        # Same as Callable[..., S]\n        ...\n    table_entry: TInt  # Same as tuple[int, Any]\n\n    type Vec[T: (int, float, complex)] = Iterable[tuple[T, T]]\n\n    def inproduct[T: (int, float, complex)](v: Vec[T]) -> T:\n        return sum(x*y for x, y in v)\n\n    def dilate[T: (int, float, complex)](v: Vec[T], scale: T) -> Vec[T]:\n        return ((x * scale, y * scale) for x, y in v)\n\n    v1: Vec[int] = []      # Same as Iterable[tuple[int, int]]\n    v2: Vec = []           # Same as Iterable[tuple[Any, Any]]\n    v3: Vec[int, int] = [] # Error: Invalid alias, too many type arguments!\n\nThere is also a legacy syntax that relies on ``TypeVar``.\nHere the number of type arguments must match the number of free type variables\nin the generic type alias definition. A type variables is free if it's not\na type parameter of a surrounding class or function. Example (following\n:pep:`PEP 484: Type aliases <484#type-aliases>`, Python 3.11 and earlier):\n\n.. code-block:: python\n\n    from typing import TypeVar, Iterable, Union, Callable\n\n    S = TypeVar('S')\n\n    TInt = tuple[int, S]  # 1 type parameter, since only S is free\n    UInt = Union[S, int]\n    CBack = Callable[..., S]\n\n    def response(query: str) -> UInt[str]:  # Same as Union[str, int]\n        ...\n    def activate(cb: CBack[S]) -> S:        # Same as Callable[..., S]\n        ...\n    table_entry: TInt  # Same as tuple[int, Any]\n\n    T = TypeVar('T', int, float, complex)\n\n    Vec = Iterable[tuple[T, T]]\n\n    def inproduct(v: Vec[T]) -> T:\n        return sum(x*y for x, y in v)\n\n    def dilate(v: Vec[T], scale: T) -> Vec[T]:\n        return ((x * scale, y * scale) for x, y in v)\n\n    v1: Vec[int] = []      # Same as Iterable[tuple[int, int]]\n    v2: Vec = []           # Same as Iterable[tuple[Any, Any]]\n    v3: Vec[int, int] = [] # Error: Invalid alias, too many type arguments!\n\nType aliases can be imported from modules just like other names. An\nalias can also target another alias, although building complex chains\nof aliases is not recommended -- this impedes code readability, thus\ndefeating the purpose of using aliases.  Example (Python 3.12 syntax):\n\n.. code-block:: python\n\n    from example1 import AliasType\n    from example2 import Vec\n\n    # AliasType and Vec are type aliases (Vec as defined above)\n\n    def fun() -> AliasType:\n        ...\n\n    type OIntVec = Vec[int] | None\n\nType aliases defined using the ``type`` statement are not valid as\nbase classes, and they can't be used to construct instances:\n\n.. code-block:: python\n\n    from example1 import AliasType\n    from example2 import Vec\n\n    # AliasType and Vec are type aliases (Vec as defined above)\n\n    class NewVec[T](Vec[T]):  # Error: not valid as base class\n        ...\n\n    x = AliasType()  # Error: can't be used to create instances\n\nHere are examples using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n    from typing import TypeVar, Generic, Optional\n    from example1 import AliasType\n    from example2 import Vec\n\n    # AliasType and Vec are type aliases (Vec as defined above)\n\n    def fun() -> AliasType:\n        ...\n\n    OIntVec = Optional[Vec[int]]\n\n    T = TypeVar('T')\n\n    # Old-style type aliases can be used as base classes and you can\n    # construct instances using them\n\n    class NewVec(Vec[T]):\n        ...\n\n    x = AliasType()\n\n    for i, j in NewVec[int]():\n        ...\n\nUsing type variable bounds or value restriction in generic aliases has\nthe same effect as in generic classes and functions.\n\n\nDifferences between the new and old syntax\n******************************************\n\nThere are a few notable differences between the new (Python 3.12 and later)\nand the old syntax for generic classes, functions and type aliases, beyond\nthe obvious syntactic differences:\n\n * Type variables defined using the old syntax create definitions at runtime\n   in the surrounding namespace, whereas the type variables defined using the\n   new syntax are only defined within the class, function or type variable\n   that uses them.\n * Type variable definitions can be shared when using the old syntax, but\n   the new syntax doesn't support this.\n * When using the new syntax, the variance of class type variables is always\n   inferred.\n * Type aliases defined using the new syntax can contain forward references\n   and recursive references without using string literal escaping. The\n   same is true for the bounds and constraints of type variables.\n * The new syntax lets you define a generic alias where the definition doesn't\n   contain a reference to a type parameter. This is occasionally useful, at\n   least when conditionally defining type aliases.\n * Type aliases defined using the new syntax can't be used as base classes\n   and can't be used to construct instances, unlike aliases defined using the\n   old syntax.\n\n\nGeneric class internals\n***********************\n\nYou may wonder what happens at runtime when you index a generic class.\nIndexing returns a *generic alias* to the original class that returns instances\nof the original class on instantiation (Python 3.12 syntax):\n\n.. code-block:: python\n\n   >>> class Stack[T]: ...\n   >>> Stack\n   __main__.Stack\n   >>> Stack[int]\n   __main__.Stack[int]\n   >>> instance = Stack[int]()\n   >>> instance.__class__\n   __main__.Stack\n\nHere is the same example using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n   >>> from typing import TypeVar, Generic\n   >>> T = TypeVar('T')\n   >>> class Stack(Generic[T]): ...\n   >>> Stack\n   __main__.Stack\n   >>> Stack[int]\n   __main__.Stack[int]\n   >>> instance = Stack[int]()\n   >>> instance.__class__\n   __main__.Stack\n\nGeneric aliases can be instantiated or subclassed, similar to real\nclasses, but the above examples illustrate that type variables are\nerased at runtime. Generic ``Stack`` instances are just ordinary\nPython objects, and they have no extra runtime overhead or magic due\nto being generic, other than the ``Generic`` base class that overloads\nthe indexing operator using ``__class_getitem__``. ``typing.Generic``\nis included as an implicit base class even when using the new syntax:\n\n.. code-block:: python\n\n   >>> class Stack[T]: ...\n   >>> Stack.mro()\n   [<class '__main__.Stack'>, <class 'typing.Generic'>, <class 'object'>]\n\nNote that in Python 3.8 and earlier, the built-in types\n:py:class:`list`, :py:class:`dict` and others do not support indexing.\nThis is why we have the aliases :py:class:`~typing.List`,\n:py:class:`~typing.Dict` and so on in the :py:mod:`typing`\nmodule. Indexing these aliases gives you a generic alias that\nresembles generic aliases constructed by directly indexing the target\nclass in more recent versions of Python:\n\n.. code-block:: python\n\n   >>> # Only relevant for Python 3.8 and below\n   >>> # If using Python 3.9 or newer, prefer the 'list[int]' syntax\n   >>> from typing import List\n   >>> List[int]\n   typing.List[int]\n\nNote that the generic aliases in ``typing`` don't support constructing\ninstances, unlike the corresponding built-in classes:\n\n.. code-block:: python\n\n   >>> list[int]()\n   []\n   >>> from typing import List\n   >>> List[int]()\n   Traceback (most recent call last):\n   ...\n   TypeError: Type List cannot be instantiated; use list() instead\n"
  },
  {
    "path": "docs/source/getting_started.rst",
    "content": ".. _getting-started:\n\nGetting started\n===============\n\nThis chapter introduces some core concepts of mypy, including function\nannotations, the :py:mod:`typing` module, stub files, and more.\n\nIf you're looking for a quick intro, see the\n:ref:`mypy cheatsheet <cheat-sheet-py3>`.\n\nIf you're unfamiliar with the concepts of static and dynamic type checking,\nbe sure to read this chapter carefully, as the rest of the documentation\nmay not make much sense otherwise.\n\nInstalling and running mypy\n***************************\n\nMypy requires Python 3.10 or later to run.  You can install mypy using pip:\n\n.. code-block:: shell\n\n    $ python3 -m pip install mypy\n\nOnce mypy is installed, run it by using the ``mypy`` tool:\n\n.. code-block:: shell\n\n    $ mypy program.py\n\nThis command makes mypy *type check* your ``program.py`` file and print\nout any errors it finds. Mypy will type check your code *statically*: this\nmeans that it will check for errors without ever running your code, just\nlike a linter.\n\nThis also means that you are always free to ignore the errors mypy reports,\nif you so wish. You can always use the Python interpreter to run your code,\neven if mypy reports errors.\n\nHowever, if you try directly running mypy on your existing Python code, it\nwill most likely report little to no errors. This is a feature! It makes it\neasy to adopt mypy incrementally.\n\nIn order to get useful diagnostics from mypy, you must add *type annotations*\nto your code. See the section below for details.\n\n.. _getting-started-dynamic-vs-static:\n\nDynamic vs static typing\n************************\n\nA function without type annotations is considered to be *dynamically typed* by mypy:\n\n.. code-block:: python\n\n   def greeting(name):\n       return 'Hello ' + name\n\nBy default, mypy will **not** type check dynamically typed functions. This means\nthat with a few exceptions, mypy will not report any errors with regular unannotated Python.\n\nThis is the case even if you misuse the function!\n\n.. code-block:: python\n\n   def greeting(name):\n       return 'Hello ' + name\n\n   # These calls will fail when the program runs, but mypy does not report an error\n   # because \"greeting\" does not have type annotations.\n   greeting(123)\n   greeting(b\"Alice\")\n\nWe can get mypy to detect these kinds of bugs by adding *type annotations* (also\nknown as *type hints*). For example, you can tell mypy that ``greeting`` both accepts\nand returns a string like so:\n\n.. code-block:: python\n\n   # The \"name: str\" annotation says that the \"name\" argument should be a string\n   # The \"-> str\" annotation says that \"greeting\" will return a string\n   def greeting(name: str) -> str:\n       return 'Hello ' + name\n\nThis function is now *statically typed*: mypy will use the provided type hints\nto detect incorrect use of the ``greeting`` function and incorrect use of\nvariables within the ``greeting`` function. For example:\n\n.. code-block:: python\n\n   def greeting(name: str) -> str:\n       return 'Hello ' + name\n\n   greeting(3)         # Argument 1 to \"greeting\" has incompatible type \"int\"; expected \"str\"\n   greeting(b'Alice')  # Argument 1 to \"greeting\" has incompatible type \"bytes\"; expected \"str\"\n   greeting(\"World!\")  # No error\n\n   def bad_greeting(name: str) -> str:\n       return 'Hello ' * name  # Unsupported operand types for * (\"str\" and \"str\")\n\nBeing able to pick whether you want a function to be dynamically or statically\ntyped can be very helpful. For example, if you are migrating an existing\nPython codebase to use static types, it's usually easier to migrate by incrementally\nadding type hints to your code rather than adding them all at once. Similarly,\nwhen you are prototyping a new feature, it may be convenient to initially implement\nthe code using dynamic typing and only add type hints later once the code is more stable.\n\nOnce you are finished migrating or prototyping your code, you can make mypy warn you\nif you add a dynamic function by mistake by using the :option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>`\nflag. You can also get mypy to provide some limited checking of dynamically typed\nfunctions by using the :option:`--check-untyped-defs <mypy --check-untyped-defs>` flag.\nSee :ref:`command-line` for more information on configuring mypy.\n\nStrict mode and configuration\n*****************************\n\nMypy has a *strict mode* that enables a number of additional checks,\nlike :option:`--disallow-untyped-defs <mypy --disallow-untyped-defs>`.\n\nIf you run mypy with the :option:`--strict <mypy --strict>` flag, you\nwill basically never get a type related error at runtime without a corresponding\nmypy error, unless you explicitly circumvent mypy somehow.\n\nHowever, this flag will probably be too aggressive if you are trying\nto add static types to a large, existing codebase. See :ref:`existing-code`\nfor suggestions on how to handle that case.\n\nMypy is very configurable, so you can start with using ``--strict``\nand toggle off individual checks. For instance, if you use many third\nparty libraries that do not have types,\n:option:`--ignore-missing-imports <mypy --ignore-missing-imports>`\nmay be useful. See :ref:`getting-to-strict` for how to build up to ``--strict``.\n\nSee :ref:`command-line` and :ref:`config-file` for a complete reference on\nconfiguration options.\n\nMore complex types\n******************\n\nSo far, we've added type hints that use only basic concrete types like\n``str`` and ``float``. What if we want to express more complex types,\nsuch as \"a list of strings\" or \"an iterable of ints\"?\n\nFor example, to indicate that some function can accept a list of\nstrings, use the ``list[str]`` type (Python 3.9 and later):\n\n.. code-block:: python\n\n   def greet_all(names: list[str]) -> None:\n       for name in names:\n           print('Hello ' + name)\n\n   names = [\"Alice\", \"Bob\", \"Charlie\"]\n   ages = [10, 20, 30]\n\n   greet_all(names)   # Ok!\n   greet_all(ages)    # Error due to incompatible types\n\nThe :py:class:`list` type is an example of something called a *generic type*: it can\naccept one or more *type parameters*. In this case, we *parameterized* :py:class:`list`\nby writing ``list[str]``. This lets mypy know that ``greet_all`` accepts specifically\nlists containing strings, and not lists containing ints or any other type.\n\nIn the above examples, the type signature is perhaps a little too rigid.\nAfter all, there's no reason why this function must accept *specifically* a list --\nit would run just fine if you were to pass in a tuple, a set, or any other custom iterable.\n\nYou can express this idea using :py:class:`collections.abc.Iterable`:\n\n.. code-block:: python\n\n   from collections.abc import Iterable  # or \"from typing import Iterable\"\n\n   def greet_all(names: Iterable[str]) -> None:\n       for name in names:\n           print('Hello ' + name)\n\nThis behavior is actually a fundamental aspect of the PEP 484 type system: when\nwe annotate some variable with a type ``T``, we are actually telling mypy that\nvariable can be assigned an instance of ``T``, or an instance of a *subtype* of ``T``.\nThat is, ``list[str]`` is a subtype of ``Iterable[str]``.\n\nThis also applies to inheritance, so if you have a class ``Child`` that inherits from\n``Parent``, then a value of type ``Child`` can be assigned to a variable of type ``Parent``.\nFor example, a ``RuntimeError`` instance can be passed to a function that is annotated\nas taking an ``Exception``.\n\nAs another example, suppose you want to write a function that can accept *either*\nints or strings, but no other types. You can express this using a\nunion type. For example, ``int`` is a subtype of ``int | str``:\n\n.. code-block:: python\n\n   def normalize_id(user_id: int | str) -> str:\n       if isinstance(user_id, int):\n           return f'user-{100_000 + user_id}'\n       else:\n           return user_id\n\n.. note::\n\n    If using Python 3.9 or earlier, use ``typing.Union[int, str]`` instead of\n    ``int | str``, or use ``from __future__ import annotations`` at the top of\n    the file (see :ref:`runtime_troubles`).\n\nThe :py:mod:`typing` module contains many other useful types.\n\nFor a quick overview, look through the :ref:`mypy cheatsheet <cheat-sheet-py3>`.\n\nFor a detailed overview (including information on how to make your own\ngeneric types or your own type aliases), look through the\n:ref:`type system reference <overview-type-system-reference>`.\n\n.. note::\n\n   When adding types, the convention is to import types\n   using the form ``from typing import <name>`` (as opposed to doing\n   just ``import typing`` or ``import typing as t`` or ``from typing import *``).\n\n   For brevity, we often omit imports from :py:mod:`typing` or :py:mod:`collections.abc`\n   in code examples, but mypy will give an error if you use types such as\n   :py:class:`~collections.abc.Iterable` without first importing them.\n\n.. note::\n\n   In some examples we use capitalized variants of types, such as\n   ``List``, and sometimes we use plain ``list``. They are equivalent,\n   but the prior variant is needed if you are using Python 3.8 or earlier.\n\nLocal type inference\n********************\n\nOnce you have added type hints to a function (i.e. made it statically typed),\nmypy will automatically type check that function's body. While doing so,\nmypy will try and *infer* as many details as possible.\n\nWe saw an example of this in the ``normalize_id`` function above -- mypy understands\nbasic :py:func:`isinstance <isinstance>` checks and so can infer that the ``user_id`` variable was of\ntype ``int`` in the if-branch and of type ``str`` in the else-branch.\n\nAs another example, consider the following function. Mypy can type check this function\nwithout a problem: it will use the available context and deduce that ``output`` must be\nof type ``list[float]`` and that ``num`` must be of type ``float``:\n\n.. code-block:: python\n\n   def nums_below(numbers: Iterable[float], limit: float) -> list[float]:\n       output = []\n       for num in numbers:\n           if num < limit:\n               output.append(num)\n       return output\n\nFor more details, see :ref:`type-inference-and-annotations`.\n\nTypes from libraries\n********************\n\nMypy can also understand how to work with types from libraries that you use.\n\nFor instance, mypy comes out of the box with an intimate knowledge of the\nPython standard library. For example, here is a function which uses the\n``Path`` object from the :doc:`pathlib standard library module <python:library/pathlib>`:\n\n.. code-block:: python\n\n    from pathlib import Path\n\n    def load_template(template_path: Path, name: str) -> str:\n        # Mypy knows that `template_path` has a `read_text` method that returns a str\n        template = template_path.read_text()\n        # ...so it understands this line type checks\n        return template.replace('USERNAME', name)\n\nIf a third party library you use :ref:`declares support for type checking <installed-packages>`,\nmypy will type check your use of that library based on the type hints\nit contains.\n\nHowever, if the third party library does not have type hints, mypy will\ncomplain about missing type information.\n\n.. code-block:: text\n\n  prog.py:1: error: Library stubs not installed for \"yaml\"\n  prog.py:1: note: Hint: \"python3 -m pip install types-PyYAML\"\n  prog.py:2: error: Library stubs not installed for \"requests\"\n  prog.py:2: note: Hint: \"python3 -m pip install types-requests\"\n  ...\n\nIn this case, you can provide mypy a different source of type information,\nby installing a *stub* package. A stub package is a package that contains\ntype hints for another library, but no actual code.\n\n.. code-block:: shell\n\n  $ python3 -m pip install types-PyYAML types-requests\n\nStubs packages for a distribution are often named ``types-<distribution>``.\nNote that a distribution name may be different from the name of the package that\nyou import. For example, ``types-PyYAML`` contains stubs for the ``yaml``\npackage.\n\nFor more discussion on strategies for handling errors about libraries without\ntype information, refer to :ref:`fix-missing-imports`.\n\nFor more information about stubs, see :ref:`stub-files`.\n\nNext steps\n**********\n\nIf you are in a hurry and don't want to read lots of documentation\nbefore getting started, here are some pointers to quick learning\nresources:\n\n* Read the :ref:`mypy cheatsheet <cheat-sheet-py3>`.\n\n* Read :ref:`existing-code` if you have a significant existing\n  codebase without many type annotations.\n\n* Read the `blog post <https://blog.zulip.org/2016/10/13/static-types-in-python-oh-mypy/>`_\n  about the Zulip project's experiences with adopting mypy.\n\n* If you prefer watching talks instead of reading, here are\n  some ideas:\n\n  * Carl Meyer:\n    `Type Checked Python in the Real World <https://www.youtube.com/watch?v=pMgmKJyWKn8>`_\n    (PyCon 2018)\n\n  * Greg Price:\n    `Clearer Code at Scale: Static Types at Zulip and Dropbox <https://www.youtube.com/watch?v=0c46YHS3RY8>`_\n    (PyCon 2018)\n\n* Look at :ref:`solutions to common issues <common_issues>` with mypy if\n  you encounter problems.\n\n* You can ask questions about mypy in the\n  `mypy issue tracker <https://github.com/python/mypy/issues>`_ and\n  typing `Gitter chat <https://gitter.im/python/typing>`_.\n\n* For general questions about Python typing, try posting at\n  `typing discussions <https://github.com/python/typing/discussions>`_.\n\nYou can also continue reading this document and skip sections that\naren't relevant for you. You don't need to read sections in order.\n"
  },
  {
    "path": "docs/source/html_builder.py",
    "content": "from __future__ import annotations\n\nimport json\nimport os\nimport textwrap\nfrom pathlib import Path\nfrom typing import Any\n\nfrom sphinx.addnodes import document\nfrom sphinx.application import Sphinx\nfrom sphinx.builders.html import StandaloneHTMLBuilder\nfrom sphinx.environment import BuildEnvironment\n\nfrom mypy.main import define_options\n\n\nclass MypyHTMLBuilder(StandaloneHTMLBuilder):\n    strict_file: Path\n\n    def __init__(self, app: Sphinx, env: BuildEnvironment) -> None:\n        super().__init__(app, env)\n        self._ref_to_doc = {}\n        self.strict_file = Path(self.srcdir) / \"strict_list.rst\"\n        self._add_strict_list()\n\n    def write_doc(self, docname: str, doctree: document) -> None:\n        super().write_doc(docname, doctree)\n        self._ref_to_doc.update({_id: docname for _id in doctree.ids})\n\n    def _add_strict_list(self) -> None:\n        strict_flags: list[str]\n        _, strict_flags, _ = define_options()\n        strict_part = \", \".join(f\":option:`{s} <mypy {s}>`\" for s in strict_flags)\n        if (\n            not strict_part\n            or strict_part.isspace()\n            or len(strict_part) < 20\n            or len(strict_part) > 2000\n        ):\n            raise ValueError(f\"{strict_part=}, which doesn't look right (by a simple heuristic).\")\n        self.strict_file.write_text(\n            \"For this version of mypy, the list of flags enabled by strict is: \" + strict_part\n        )\n\n    def _verify_error_codes(self) -> None:\n        from mypy.errorcodes import error_codes\n\n        missing_error_codes = {c for c in error_codes if f\"code-{c}\" not in self._ref_to_doc}\n        if missing_error_codes:\n            raise ValueError(\n                f\"Some error codes are not documented: {', '.join(sorted(missing_error_codes))}\"\n            )\n\n    def _write_ref_redirector(self) -> None:\n        if os.getenv(\"VERIFY_MYPY_ERROR_CODES\"):\n            self._verify_error_codes()\n        p = Path(self.outdir) / \"_refs.html\"\n        data = f\"\"\"\n        <html>\n        <body>\n        <script>\n        const ref_to_doc = {json.dumps(self._ref_to_doc)};\n        const hash = window.location.hash.substring(1);\n        const doc = ref_to_doc[hash];\n        if (doc) {{\n            window.location.href = doc + '.html' + '#' + hash;\n        }} else {{\n            window.document.innerText = 'Unknown reference: ' + hash;\n        }}\n        </script>\n        </body>\n        </html>\n        \"\"\"\n        p.write_text(textwrap.dedent(data))\n\n    def finish(self) -> None:\n        super().finish()\n        self._write_ref_redirector()\n        self.strict_file.unlink()\n\n\ndef setup(app: Sphinx) -> dict[str, Any]:\n    app.add_builder(MypyHTMLBuilder, override=True)\n\n    return {\"version\": \"0.1\", \"parallel_read_safe\": True, \"parallel_write_safe\": True}\n"
  },
  {
    "path": "docs/source/index.rst",
    "content": ".. Mypy documentation master file, created by\n   sphinx-quickstart on Sun Sep 14 19:50:35 2014.\n   You can adapt this file completely to your liking, but it should at least\n   contain the root `toctree` directive.\n\nWelcome to mypy documentation!\n==============================\n\nMypy is a static type checker for Python.\n\nType checkers help ensure that you're using variables and functions in your code\ncorrectly. With mypy, add type hints (:pep:`484`)\nto your Python programs, and mypy will warn you when you use those types\nincorrectly.\n\nPython is a dynamic language, so usually you'll only see errors in your code\nwhen you attempt to run it. Mypy is a *static* checker, so it finds bugs\nin your programs without even running them!\n\nHere is a small example to whet your appetite:\n\n.. code-block:: python\n\n   number = input(\"What is your favourite number?\")\n   print(\"It is\", number + 1)  # error: Unsupported operand types for + (\"str\" and \"int\")\n\nAdding type hints for mypy does not interfere with the way your program would\notherwise run. Think of type hints as similar to comments! You can always use\nthe Python interpreter to run your code, even if mypy reports errors.\n\nMypy is designed with gradual typing in mind. This means you can add type\nhints to your code base slowly and that you can always fall back to dynamic\ntyping when static typing is not convenient.\n\nMypy has a powerful and easy-to-use type system, supporting features such as\ntype inference, generics, callable types, tuple types, union types,\nstructural subtyping and more. Using mypy will make your programs easier to\nunderstand, debug, and maintain.\n\n.. note::\n\n   Although mypy is production ready, there may be occasional changes\n   that break backward compatibility. The mypy development team tries to\n   minimize the impact of changes to user code. In case of a major breaking\n   change, mypy's major version will be bumped.\n\nContents\n--------\n\n.. toctree::\n   :maxdepth: 2\n   :caption: First steps\n\n   getting_started\n   cheat_sheet_py3\n   existing_code\n\n.. _overview-type-system-reference:\n\n.. toctree::\n   :maxdepth: 2\n   :caption: Type system reference\n\n   builtin_types\n   type_inference_and_annotations\n   kinds_of_types\n   class_basics\n   runtime_troubles\n   protocols\n   dynamic_typing\n   type_narrowing\n   duck_type_compatibility\n   stubs\n   generics\n   more_types\n   literal_types\n   typed_dict\n   final_attrs\n   metaclasses\n\n.. toctree::\n   :maxdepth: 2\n   :caption: Configuring and running mypy\n\n   running_mypy\n   command_line\n   config_file\n   inline_config\n   mypy_daemon\n   installed_packages\n   extending_mypy\n   stubgen\n   stubtest\n\n.. toctree::\n   :maxdepth: 2\n   :caption: Miscellaneous\n\n   common_issues\n   supported_python_features\n   error_codes\n   error_code_list\n   error_code_list2\n   additional_features\n   faq\n   changelog\n\n.. toctree::\n   :hidden:\n   :caption: Project Links\n\n   GitHub <https://github.com/python/mypy>\n   Website <https://mypy-lang.org/>\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`search`\n"
  },
  {
    "path": "docs/source/inline_config.rst",
    "content": ".. _inline-config:\n\nInline configuration\n====================\n\nMypy supports setting per-file configuration options inside files themselves\nusing ``# mypy:`` comments. For example:\n\n.. code-block:: python\n\n  # mypy: disallow-any-generics\n\nInline configuration comments take precedence over all other\nconfiguration mechanisms.\n\nConfiguration comment format\n****************************\n\nFlags correspond to :ref:`config file flags <config-file>` but allow\nhyphens to be substituted for underscores.\n\nValues are specified using ``=``, but ``= True`` may be omitted:\n\n.. code-block:: python\n\n  # mypy: disallow-any-generics\n  # mypy: always-true=FOO\n\nMultiple flags can be separated by commas or placed on separate\nlines. To include a comma as part of an option's value, place the\nvalue inside quotes:\n\n.. code-block:: python\n\n  # mypy: disallow-untyped-defs, always-false=\"FOO,BAR\"\n\nLike in the configuration file, options that take a boolean value may be\ninverted by adding ``no-`` to their name or by (when applicable)\nswapping their prefix from ``disallow`` to ``allow`` (and vice versa):\n\n.. code-block:: python\n\n  # mypy: allow-untyped-defs, no-strict-optional\n"
  },
  {
    "path": "docs/source/installed_packages.rst",
    "content": ".. _installed-packages:\n\nUsing installed packages\n========================\n\nPackages installed with pip can declare that they support type\nchecking. For example, the `aiohttp\n<https://docs.aiohttp.org/en/stable/>`_ package has built-in support\nfor type checking.\n\nPackages can also provide stubs for a library. For example,\n``types-requests`` is a stub-only package that provides stubs for the\n`requests <https://requests.readthedocs.io/en/master/>`_ package.\nStub packages are usually published from `typeshed\n<https://github.com/python/typeshed>`_, a shared repository for Python\nlibrary stubs, and have a name of form ``types-<library>``. Note that\nmany stub packages are not maintained by the original maintainers of\nthe package.\n\nThe sections below explain how mypy can use these packages, and how\nyou can create such packages.\n\n.. note::\n\n   :pep:`561` specifies how a package can declare that it supports\n   type checking.\n\n.. note::\n\n   New versions of stub packages often use type system features not\n   supported by older, and even fairly recent mypy versions. If you\n   pin to an older version of mypy (using ``requirements.txt``, for\n   example), it is recommended that you also pin the versions of all\n   your stub package dependencies.\n\n.. note::\n\n   Starting in mypy 0.900, most third-party package stubs must be\n   installed explicitly. This decouples mypy and stub versioning,\n   allowing stubs to updated without updating mypy. This also allows\n   stubs not originally included with mypy to be installed. Earlier\n   mypy versions included a fixed set of stubs for third-party\n   packages.\n\nUsing installed packages with mypy (PEP 561)\n********************************************\n\nTypically mypy will automatically find and use installed packages that\nsupport type checking or provide stubs. This requires that you install\nthe packages in the Python environment that you use to run mypy.  As\nmany packages don't support type checking yet, you may also have to\ninstall a separate stub package, usually named\n``types-<library>``. (See :ref:`fix-missing-imports` for how to deal\nwith libraries that don't support type checking and are also missing\nstubs.)\n\nIf you have installed typed packages in another Python installation or\nenvironment, mypy won't automatically find them. One option is to\ninstall another copy of those packages in the environment in which you\ninstalled mypy. Alternatively, you can use the\n:option:`--python-executable <mypy --python-executable>` flag to point\nto the Python executable for another environment, and mypy will find\npackages installed for that Python executable.\n\nNote that mypy does not support some more advanced import features,\nsuch as zip imports and custom import hooks.\n\nIf you don't want to use installed packages that provide type\ninformation at all, use the :option:`--no-site-packages <mypy\n--no-site-packages>` flag to disable searching for installed packages.\n\nNote that stub-only packages cannot be used with ``MYPYPATH``. If you\nwant mypy to find the package, it must be installed. For a package\n``foo``, the name of the stub-only package (``foo-stubs``) is not a\nlegal package name, so mypy will not find it, unless it is installed\n(see :pep:`PEP 561: Stub-only Packages <561#stub-only-packages>` for\nmore information).\n\nCreating PEP 561 compatible packages\n************************************\n\n.. note::\n\n  You can generally ignore this section unless you maintain a package on\n  PyPI, or want to publish type information for an existing PyPI\n  package.\n\n:pep:`561` describes three main ways to distribute type\ninformation:\n\n1. A package has inline type annotations in the Python implementation.\n\n2. A package ships :ref:`stub files <stub-files>` with type\n   information alongside the Python implementation.\n\n3. A package ships type information for another package separately as\n   stub files (also known as a \"stub-only package\").\n\nIf you want to create a stub-only package for an existing library, the\nsimplest way is to contribute stubs to the `typeshed\n<https://github.com/python/typeshed>`_ repository, and a stub package\nwill automatically be uploaded to PyPI.\n\nIf you would like to publish a library package to a package repository\nyourself (e.g. on PyPI) for either internal or external use in type\nchecking, packages that supply type information via type comments or\nannotations in the code should put a ``py.typed`` file in their\npackage directory. For example, here is a typical directory structure:\n\n.. code-block:: text\n\n    setup.py\n    package_a/\n        __init__.py\n        lib.py\n        py.typed\n\nThe ``setup.py`` file could look like this:\n\n.. code-block:: python\n\n    from setuptools import setup\n\n    setup(\n        name=\"SuperPackageA\",\n        author=\"Me\",\n        version=\"0.1\",\n        package_data={\"package_a\": [\"py.typed\"]},\n        packages=[\"package_a\"]\n    )\n\nSome packages have a mix of stub files and runtime files. These packages also\nrequire a ``py.typed`` file. An example can be seen below:\n\n.. code-block:: text\n\n    setup.py\n    package_b/\n        __init__.py\n        lib.py\n        lib.pyi\n        py.typed\n\nThe ``setup.py`` file might look like this:\n\n.. code-block:: python\n\n    from setuptools import setup\n\n    setup(\n        name=\"SuperPackageB\",\n        author=\"Me\",\n        version=\"0.1\",\n        package_data={\"package_b\": [\"py.typed\", \"lib.pyi\"]},\n        packages=[\"package_b\"]\n    )\n\nIn this example, both ``lib.py`` and the ``lib.pyi`` stub file exist. At\nruntime, the Python interpreter will use ``lib.py``, but mypy will use\n``lib.pyi`` instead.\n\nIf the package is stub-only (not imported at runtime), the package should have\na prefix of the runtime package name and a suffix of ``-stubs``.\nA ``py.typed`` file is not needed for stub-only packages. For example, if we\nhad stubs for ``package_c``, we might do the following:\n\n.. code-block:: text\n\n    setup.py\n    package_c-stubs/\n        __init__.pyi\n        lib.pyi\n\nThe ``setup.py`` might look like this:\n\n.. code-block:: python\n\n    from setuptools import setup\n\n    setup(\n        name=\"SuperPackageC\",\n        author=\"Me\",\n        version=\"0.1\",\n        package_data={\"package_c-stubs\": [\"__init__.pyi\", \"lib.pyi\"]},\n        packages=[\"package_c-stubs\"]\n    )\n\nThe instructions above are enough to ensure that the built wheels\ncontain the appropriate files. However, to ensure inclusion inside the\n``sdist`` (``.tar.gz`` archive), you may also need to modify the\ninclusion rules in your ``MANIFEST.in``:\n\n.. code-block:: text\n\n    global-include *.pyi\n    global-include *.typed\n"
  },
  {
    "path": "docs/source/kinds_of_types.rst",
    "content": "Kinds of types\n==============\n\nWe've mostly restricted ourselves to built-in types until now. This\nsection introduces several additional kinds of types. You are likely\nto need at least some of them to type check any non-trivial programs.\n\nClass types\n***********\n\nEvery class is also a valid type. Any instance of a subclass is also\ncompatible with all superclasses -- it follows that every value is compatible\nwith the :py:class:`object` type (and incidentally also the ``Any`` type, discussed\nbelow). Mypy analyzes the bodies of classes to determine which methods and\nattributes are available in instances. This example uses subclassing:\n\n.. code-block:: python\n\n   class A:\n       def f(self) -> int:  # Type of self inferred (A)\n           return 2\n\n   class B(A):\n       def f(self) -> int:\n            return 3\n       def g(self) -> int:\n           return 4\n\n   def foo(a: A) -> None:\n       print(a.f())  # 3\n       a.g()         # Error: \"A\" has no attribute \"g\"\n\n   foo(B())  # OK (B is a subclass of A)\n\nThe Any type\n************\n\nA value with the ``Any`` type is dynamically typed. Mypy doesn't know\nanything about the possible runtime types of such value. Any\noperations are permitted on the value, and the operations are only checked\nat runtime. You can use ``Any`` as an \"escape hatch\" when you can't use\na more precise type for some reason.\n\nThis should not be confused with the\n:py:class:`object` type, which represents the set of all values.\nUnlike ``object``, ``Any`` introduces type unsafety — see\n:ref:`any-vs-object` for more.\n\n``Any`` is compatible with every other type, and vice versa. You can freely\nassign a value of type ``Any`` to a variable with a more precise type:\n\n.. code-block:: python\n\n   a: Any = None\n   s: str = ''\n   a = 2     # OK (assign \"int\" to \"Any\")\n   s = a     # OK (assign \"Any\" to \"str\")\n\nDeclared (and inferred) types are ignored (or *erased*) at runtime. They are\nbasically treated as comments, and thus the above code does not\ngenerate a runtime error, even though ``s`` gets an ``int`` value when\nthe program is run, while the declared type of ``s`` is actually\n``str``! You need to be careful with ``Any`` types, since they let you\nlie to mypy, and this could easily hide bugs.\n\nIf you do not define a function return value or argument types, these\ndefault to ``Any``:\n\n.. code-block:: python\n\n   def show_heading(s) -> None:\n       print('=== ' + s + ' ===')  # No static type checking, as s has type Any\n\n   show_heading(1)  # OK (runtime error only; mypy won't generate an error)\n\nYou should give a statically typed function an explicit ``None``\nreturn type even if it doesn't return a value, as this lets mypy catch\nadditional type errors:\n\n.. code-block:: python\n\n   def wait(t: float):  # Implicit Any return value\n       print('Waiting...')\n       time.sleep(t)\n\n   if wait(2) > 1:   # Mypy doesn't catch this error!\n       ...\n\nIf we had used an explicit ``None`` return type, mypy would have caught\nthe error:\n\n.. code-block:: python\n\n   def wait(t: float) -> None:\n       print('Waiting...')\n       time.sleep(t)\n\n   if wait(2) > 1:   # Error: can't compare None and int\n       ...\n\nThe ``Any`` type is discussed in more detail in section :ref:`dynamic-typing`.\n\n.. note::\n\n  A function without any types in the signature is dynamically\n  typed. The body of a dynamically typed function is not checked\n  statically, and local variables have implicit ``Any`` types.\n  This makes it easier to migrate legacy Python code to mypy, as\n  mypy won't complain about dynamically typed functions.\n\n.. _tuple-types:\n\nTuple types\n***********\n\nThe type ``tuple[T1, ..., Tn]`` represents a tuple with the item types ``T1``, ..., ``Tn``:\n\n.. code-block:: python\n\n   # Use `typing.Tuple` in Python 3.8 and earlier\n   def f(t: tuple[int, str]) -> None:\n       t = 1, 'foo'    # OK\n       t = 'foo', 1    # Type check error\n\nA tuple type of this kind has exactly a specific number of items (2 in\nthe above example). Tuples can also be used as immutable,\nvarying-length sequences. You can use the type ``tuple[T, ...]`` (with\na literal ``...`` -- it's part of the syntax) for this\npurpose. Example:\n\n.. code-block:: python\n\n    def print_squared(t: tuple[int, ...]) -> None:\n        for n in t:\n            print(n, n ** 2)\n\n    print_squared(())           # OK\n    print_squared((1, 3, 5))    # OK\n    print_squared([1, 2])       # Error: only a tuple is valid\n\n.. note::\n\n   Usually it's a better idea to use ``Sequence[T]`` instead of ``tuple[T, ...]``, as\n   :py:class:`~collections.abc.Sequence` is also compatible with lists and other non-tuple sequences.\n\n.. note::\n\n   ``tuple[...]`` is valid as a base class in Python 3.6 and later, and\n   always in stub files. In earlier Python versions you can sometimes work around this\n   limitation by using a named tuple as a base class (see section :ref:`named-tuples`).\n\n.. _callable-types:\n\nCallable types (and lambdas)\n****************************\n\nYou can pass around function objects and bound methods in statically\ntyped code. The type of a function that accepts arguments ``A1``, ..., ``An``\nand returns ``Rt`` is ``Callable[[A1, ..., An], Rt]``. Example:\n\n.. code-block:: python\n\n   from collections.abc import Callable\n\n   def twice(i: int, next: Callable[[int], int]) -> int:\n       return next(next(i))\n\n   def add(i: int) -> int:\n       return i + 1\n\n   print(twice(3, add))   # 5\n\n.. note::\n\n    Import :py:data:`Callable[...] <typing.Callable>` from ``typing`` instead\n    of ``collections.abc`` if you use Python 3.8 or earlier.\n\nYou can only have positional arguments, and only ones without default\nvalues, in callable types. These cover the vast majority of uses of\ncallable types, but sometimes this isn't quite enough. Mypy recognizes\na special form ``Callable[..., T]`` (with a literal ``...``) which can\nbe used in less typical cases. It is compatible with arbitrary\ncallable objects that return a type compatible with ``T``, independent\nof the number, types or kinds of arguments. Mypy lets you call such\ncallable values with arbitrary arguments, without any checking -- in\nthis respect they are treated similar to a ``(*args: Any, **kwargs:\nAny)`` function signature. Example:\n\n.. code-block:: python\n\n   from collections.abc import Callable\n\n   def arbitrary_call(f: Callable[..., int]) -> int:\n       return f('x') + f(y=2)  # OK\n\n   arbitrary_call(ord)   # No static error, but fails at runtime\n   arbitrary_call(open)  # Error: does not return an int\n   arbitrary_call(1)     # Error: 'int' is not callable\n\nIn situations where more precise or complex types of callbacks are\nnecessary one can use flexible :ref:`callback protocols <callback_protocols>`.\nLambdas are also supported. The lambda argument and return value types\ncannot be given explicitly; they are always inferred based on context\nusing bidirectional type inference:\n\n.. code-block:: python\n\n   l = map(lambda x: x + 1, [1, 2, 3])   # Infer x as int and l as list[int]\n\nIf you want to give the argument or return value types explicitly, use\nan ordinary, perhaps nested function definition.\n\nCallables can also be used against type objects, matching their\n``__init__`` or ``__new__`` signature:\n\n.. code-block:: python\n\n    from collections.abc import Callable\n\n    class C:\n        def __init__(self, app: str) -> None:\n            pass\n\n    CallableType = Callable[[str], C]\n\n    def class_or_callable(arg: CallableType) -> None:\n        inst = arg(\"my_app\")\n        reveal_type(inst)  # Revealed type is \"C\"\n\nThis is useful if you want ``arg`` to be either a ``Callable`` returning an\ninstance of ``C`` or the type of ``C`` itself. This also works with\n:ref:`callback protocols <callback_protocols>`.\n\n\n.. _union-types:\n.. _alternative_union_syntax:\n\nUnion types\n***********\n\nPython functions often accept values of two or more different\ntypes. You can use :ref:`overloading <function-overloading>` to\nrepresent this, but union types are often more convenient.\n\nUse ``T1 | ... | Tn`` to construct a union\ntype. For example, if an argument has type ``int | str``, both\nintegers and strings are valid argument values.\n\nYou can use an :py:func:`isinstance` check to narrow down a union type to a\nmore specific type:\n\n.. code-block:: python\n\n   def f(x: int | str) -> None:\n       x + 1     # Error: str + int is not valid\n       if isinstance(x, int):\n           # Here type of x is int.\n           x + 1      # OK\n       else:\n           # Here type of x is str.\n           x + 'a'    # OK\n\n   f(1)    # OK\n   f('x')  # OK\n   f(1.1)  # Error\n\n.. note::\n\n    Operations are valid for union types only if they are valid for *every*\n    union item. This is why it's often necessary to use an :py:func:`isinstance`\n    check to first narrow down a union type to a non-union type. This also\n    means that it's recommended to avoid union types as function return types,\n    since the caller may have to use :py:func:`isinstance` before doing anything\n    interesting with the value.\n\nPython 3.9 and older only partially support this syntax. Instead, you can\nuse the legacy ``Union[T1, ..., Tn]`` type constructor. Example:\n\n.. code-block:: python\n\n   from typing import Union\n\n   def f(x: Union[int, str]) -> None:\n       ...\n\nIt is also possible to use the new syntax with versions of Python where it\nisn't supported by the runtime with some limitations, if you use\n``from __future__ import annotations`` (see :ref:`runtime_troubles`):\n\n.. code-block:: python\n\n   from __future__ import annotations\n\n   def f(x: int | str) -> None:   # OK on Python 3.7 and later\n       ...\n\n.. _no-strict-optional:\n.. _strict_optional:\n\nOptional types and the None type\n********************************\n\nYou can use ``T | None`` to define a type variant that allows ``None`` values,\nsuch as ``int | None``. This is called an *optional type*:\n\n.. code-block:: python\n\n   def strlen(s: str) -> int | None:\n       if not s:\n           return None  # OK\n       return len(s)\n\n   def strlen_invalid(s: str) -> int:\n       if not s:\n           return None  # Error: None not compatible with int\n       return len(s)\n\nTo support Python 3.9 and earlier, you can use the :py:data:`~typing.Optional`\ntype modifier instead, such as ``Optional[int]`` (``Optional[X]`` is\nthe preferred shorthand for ``Union[X, None]``):\n\n.. code-block:: python\n\n   from typing import Optional\n\n   def strlen(s: str) -> Optional[int]:\n       ...\n\nMost operations will not be allowed on unguarded ``None`` or *optional* values\n(values with an optional type):\n\n.. code-block:: python\n\n   def my_inc(x: int | None) -> int:\n       return x + 1  # Error: Cannot add None and int\n\nInstead, an explicit ``None`` check is required. Mypy has\npowerful type inference that lets you use regular Python\nidioms to guard against ``None`` values. For example, mypy\nrecognizes ``is None`` checks:\n\n.. code-block:: python\n\n   def my_inc(x: int | None) -> int:\n       if x is None:\n           return 0\n       else:\n           # The inferred type of x is just int here.\n           return x + 1\n\nMypy will infer the type of ``x`` to be ``int`` in the else block due to the\ncheck against ``None`` in the if condition.\n\nOther supported checks for guarding against a ``None`` value include\n``if x is not None``, ``if x`` and ``if not x``. Additionally, mypy understands\n``None`` checks within logical expressions:\n\n.. code-block:: python\n\n   def concat(x: str | None, y: str | None) -> str | None:\n       if x is not None and y is not None:\n           # Both x and y are not None here\n           return x + y\n       else:\n           return None\n\nSometimes mypy doesn't realize that a value is never ``None``. This notably\nhappens when a class instance can exist in a partially defined state,\nwhere some attribute is initialized to ``None`` during object\nconstruction, but a method assumes that the attribute is no longer ``None``. Mypy\nwill complain about the possible ``None`` value. You can use\n``assert x is not None`` to work around this in the method:\n\n.. code-block:: python\n\n   class Resource:\n       path: str | None = None\n\n       def initialize(self, path: str) -> None:\n           self.path = path\n\n       def read(self) -> str:\n           # We require that the object has been initialized.\n           assert self.path is not None\n           with open(self.path) as f:  # OK\n              return f.read()\n\n   r = Resource()\n   r.initialize('/foo/bar')\n   r.read()\n\nWhen initializing a variable as ``None``, ``None`` is usually an\nempty place-holder value, and the actual value has a different type.\nThis is why you need to annotate an attribute in cases like the class\n``Resource`` above:\n\n.. code-block:: python\n\n    class Resource:\n        path: str | None = None\n        ...\n\nThis also works for attributes defined within methods:\n\n.. code-block:: python\n\n    class Counter:\n        def __init__(self) -> None:\n            self.count: int | None = None\n\nOften it's easier to not use any initial value for an attribute.\nThis way you don't need to use an optional type and can avoid ``assert ... is not None``\nchecks. No initial value is needed if you annotate an attribute in the class body:\n\n.. code-block:: python\n\n   class Container:\n       items: list[str]  # No initial value\n\nMypy generally uses the first assignment to a variable to\ninfer the type of the variable. However, if you assign both a ``None``\nvalue and a non-``None`` value in the same scope, mypy can usually do\nthe right thing without an annotation:\n\n.. code-block:: python\n\n   def f(i: int) -> None:\n       n = None  # Inferred type 'int | None' because of the assignment below\n       if i > 0:\n            n = i\n       ...\n\nSometimes you may get the error \"Cannot determine type of <something>\". In this\ncase you should add an explicit ``... | None`` annotation.\n\n.. note::\n\n   ``None`` is a type with only one value, ``None``. ``None`` is also used\n   as the return type for functions that don't return a value, i.e. functions\n   that implicitly return ``None``.\n\n.. note::\n\n   The Python interpreter internally uses the name ``NoneType`` for\n   the type of ``None``, but ``None`` is always used in type\n   annotations. The latter is shorter and reads better. (``NoneType``\n   is available as :py:data:`types.NoneType` on Python 3.10+, but is\n   not exposed at all on earlier versions of Python.)\n\n.. note::\n\n    The type ``Optional[T]`` *does not* mean a function parameter with a default value.\n    It simply means that ``None`` is a valid argument value. This is\n    a common confusion because ``None`` is a common default value for parameters,\n    and parameters with default values are sometimes called *optional* parameters\n    (or arguments).\n\n.. _type-aliases:\n\nType aliases\n************\n\nIn certain situations, type names may end up being long and painful to type,\nespecially if they are used frequently:\n\n.. code-block:: python\n\n   def f() -> list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]]:\n       ...\n\nWhen cases like this arise, you can define a type alias by simply\nassigning the type to a variable (this is an *implicit type alias*):\n\n.. code-block:: python\n\n   AliasType = list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]]\n\n   # Now we can use AliasType in place of the full name:\n\n   def f() -> AliasType:\n       ...\n\n.. note::\n\n    A type alias does not create a new type. It's just a shorthand notation for\n    another type -- it's equivalent to the target type except for\n    :ref:`generic aliases <generic-type-aliases>`.\n\nPython 3.12 introduced the ``type`` statement for defining *explicit type aliases*.\nExplicit type aliases are unambiguous and can also improve readability by\nmaking the intent clear:\n\n.. code-block:: python\n\n   type AliasType = list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]]\n\n   # Now we can use AliasType in place of the full name:\n\n   def f() -> AliasType:\n       ...\n\nThere can be confusion about exactly when an assignment defines an implicit type alias --\nfor example, when the alias contains forward references, invalid types, or violates some other\nrestrictions on type alias declarations.  Because the\ndistinction between an unannotated variable and a type alias is implicit,\nambiguous or incorrect type alias declarations default to defining\na normal variable instead of a type alias.\n\nAliases defined using the ``type`` statement have these properties, which\ndistinguish them from implicit type aliases:\n\n* The definition may contain forward references without having to use string\n  literal escaping, since it is evaluated lazily.\n* The alias can be used in type annotations, type arguments, and casts, but\n  it can't be used in contexts which require a class object. For example, it's\n  not valid as a base class and it can't be used to construct instances.\n\nThere is also use an older syntax for defining explicit type aliases, which was\nintroduced in Python 3.10 (:pep:`613`):\n\n.. code-block:: python\n\n   from typing import TypeAlias  # \"from typing_extensions\" in Python 3.9 and earlier\n\n   AliasType: TypeAlias = list[dict[tuple[int, str], set[int]]] | tuple[str, list[str]]\n\n.. _named-tuples:\n\nNamed tuples\n************\n\nMypy recognizes named tuples and can type check code that defines or\nuses them.  In this example, we can detect code trying to access a\nmissing attribute:\n\n.. code-block:: python\n\n    Point = namedtuple('Point', ['x', 'y'])\n    p = Point(x=1, y=2)\n    print(p.z)  # Error: Point has no attribute 'z'\n\nIf you use :py:func:`namedtuple <collections.namedtuple>` to define your named tuple, all the items\nare assumed to have ``Any`` types. That is, mypy doesn't know anything\nabout item types. You can use :py:class:`~typing.NamedTuple` to also define\nitem types:\n\n.. code-block:: python\n\n    from typing import NamedTuple\n\n    Point = NamedTuple('Point', [('x', int),\n                                 ('y', int)])\n    p = Point(x=1, y='x')  # Argument has incompatible type \"str\"; expected \"int\"\n\nPython 3.6 introduced an alternative, class-based syntax for named tuples with types:\n\n.. code-block:: python\n\n    from typing import NamedTuple\n\n    class Point(NamedTuple):\n        x: int\n        y: int\n\n    p = Point(x=1, y='x')  # Argument has incompatible type \"str\"; expected \"int\"\n\n.. note::\n\n  You can use the raw ``NamedTuple`` \"pseudo-class\" in type annotations\n  if any ``NamedTuple`` object is valid.\n\n  For example, it can be useful for deserialization:\n\n  .. code-block:: python\n\n    def deserialize_named_tuple(arg: NamedTuple) -> Dict[str, Any]:\n        return arg._asdict()\n\n    Point = namedtuple('Point', ['x', 'y'])\n    Person = NamedTuple('Person', [('name', str), ('age', int)])\n\n    deserialize_named_tuple(Point(x=1, y=2))  # ok\n    deserialize_named_tuple(Person(name='Nikita', age=18))  # ok\n\n    # Error: Argument 1 to \"deserialize_named_tuple\" has incompatible type\n    # \"Tuple[int, int]\"; expected \"NamedTuple\"\n    deserialize_named_tuple((1, 2))\n\n  Note that this behavior is highly experimental, non-standard,\n  and may not be supported by other type checkers and IDEs.\n\n.. _type-of-class:\n\nThe type of class objects\n*************************\n\n(Freely after :pep:`PEP 484: The type of class objects\n<484#the-type-of-class-objects>`.)\n\nSometimes you want to talk about class objects that inherit from a\ngiven class.  This can be spelled as ``type[C]`` (or, on Python 3.8 and lower,\n:py:class:`typing.Type[C] <typing.Type>`) where ``C`` is a\nclass.  In other words, when ``C`` is the name of a class, using ``C``\nto annotate an argument declares that the argument is an instance of\n``C`` (or of a subclass of ``C``), but using ``type[C]`` as an\nargument annotation declares that the argument is a class object\nderiving from ``C`` (or ``C`` itself).\n\nFor example, assume the following classes:\n\n.. code-block:: python\n\n   class User:\n       # Defines fields like name, email\n\n   class BasicUser(User):\n       def upgrade(self):\n           \"\"\"Upgrade to Pro\"\"\"\n\n   class ProUser(User):\n       def pay(self):\n           \"\"\"Pay bill\"\"\"\n\nNote that ``ProUser`` doesn't inherit from ``BasicUser``.\n\nHere's a function that creates an instance of one of these classes if\nyou pass it the right class object:\n\n.. code-block:: python\n\n   def new_user(user_class):\n       user = user_class()\n       # (Here we could write the user object to a database)\n       return user\n\nHow would we annotate this function?  Without the ability to parameterize ``type``, the best we\ncould do would be:\n\n.. code-block:: python\n\n   def new_user(user_class: type) -> User:\n       # Same  implementation as before\n\nThis seems reasonable, except that in the following example, mypy\ndoesn't see that the ``buyer`` variable has type ``ProUser``:\n\n.. code-block:: python\n\n   buyer = new_user(ProUser)\n   buyer.pay()  # Rejected, not a method on User\n\nHowever, using the ``type[C]`` syntax and a type variable with an upper bound (see\n:ref:`type-variable-upper-bound`) we can do better (Python 3.12 syntax):\n\n.. code-block:: python\n\n   def new_user[U: User](user_class: type[U]) -> U:\n       # Same implementation as before\n\nHere is the example using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n   U = TypeVar('U', bound=User)\n\n   def new_user(user_class: type[U]) -> U:\n       # Same implementation as before\n\nNow mypy will infer the correct type of the result when we call\n``new_user()`` with a specific subclass of ``User``:\n\n.. code-block:: python\n\n   beginner = new_user(BasicUser)  # Inferred type is BasicUser\n   beginner.upgrade()  # OK\n\n.. note::\n\n   The value corresponding to ``type[C]`` must be an actual class\n   object that's a subtype of ``C``.  Its constructor must be\n   compatible with the constructor of ``C``.  If ``C`` is a type\n   variable, its upper bound must be a class object.\n\nFor more details about ``type[]`` and :py:class:`typing.Type[] <typing.Type>`, see :pep:`PEP 484: The type of\nclass objects <484#the-type-of-class-objects>`.\n\n.. _generators:\n\nGenerators\n**********\n\nA basic generator that only yields values can be succinctly annotated as having a return\ntype of either :py:class:`Iterator[YieldType] <typing.Iterator>` or :py:class:`Iterable[YieldType] <typing.Iterable>`. For example:\n\n.. code-block:: python\n\n   def squares(n: int) -> Iterator[int]:\n       for i in range(n):\n           yield i * i\n\nA good rule of thumb is to annotate functions with the most specific return\ntype possible. However, you should also take care to avoid leaking implementation\ndetails into a function's public API. In keeping with these two principles, prefer\n:py:class:`Iterator[YieldType] <typing.Iterator>` over\n:py:class:`Iterable[YieldType] <typing.Iterable>` as the return-type annotation for a\ngenerator function, as it lets mypy know that users are able to call :py:func:`next` on\nthe object returned by the function. Nonetheless, bear in mind that ``Iterable`` may\nsometimes be the better option, if you consider it an implementation detail that\n``next()`` can be called on the object returned by your function.\n\nIf you want your generator to accept values via the :py:meth:`~generator.send` method or return\na value, on the other hand, you should use the\n:py:class:`Generator[YieldType, SendType, ReturnType] <typing.Generator>` generic type instead of\neither ``Iterator`` or ``Iterable``. For example:\n\n.. code-block:: python\n\n   def echo_round() -> Generator[int, float, str]:\n       sent = yield 0\n       while sent >= 0:\n           sent = yield round(sent)\n       return 'Done'\n\nNote that unlike many other generics in the typing module, the ``SendType`` of\n:py:class:`~typing.Generator` behaves contravariantly, not covariantly or invariantly.\n\nIf you do not plan on receiving or returning values, then set the ``SendType``\nor ``ReturnType`` to ``None``, as appropriate. For example, we could have\nannotated the first example as the following:\n\n.. code-block:: python\n\n   def squares(n: int) -> Generator[int, None, None]:\n       for i in range(n):\n           yield i * i\n\nThis is slightly different from using ``Iterator[int]`` or ``Iterable[int]``,\nsince generators have :py:meth:`~generator.close`, :py:meth:`~generator.send`, and :py:meth:`~generator.throw` methods that\ngeneric iterators and iterables don't. If you plan to call these methods on the returned\ngenerator, use the :py:class:`~typing.Generator` type instead of :py:class:`~typing.Iterator` or :py:class:`~typing.Iterable`.\n"
  },
  {
    "path": "docs/source/literal_types.rst",
    "content": "Literal types and Enums\n=======================\n\n.. _literal_types:\n\nLiteral types\n-------------\n\nLiteral types let you indicate that an expression is equal to some specific\nprimitive value. For example, if we annotate a variable with type ``Literal[\"foo\"]``,\nmypy will understand that variable is not only of type ``str``, but is also\nequal to specifically the string ``\"foo\"``.\n\nThis feature is primarily useful when annotating functions that behave\ndifferently based on the exact value the caller provides. For example,\nsuppose we have a function ``fetch_data(...)`` that returns ``bytes`` if the\nfirst argument is ``True``, and ``str`` if it's ``False``. We can construct a\nprecise type signature for this function using ``Literal[...]`` and overloads:\n\n.. code-block:: python\n\n    from typing import overload, Union, Literal\n\n    # The first two overloads use Literal[...] so we can\n    # have precise return types:\n\n    @overload\n    def fetch_data(raw: Literal[True]) -> bytes: ...\n    @overload\n    def fetch_data(raw: Literal[False]) -> str: ...\n\n    # The last overload is a fallback in case the caller\n    # provides a regular bool:\n\n    @overload\n    def fetch_data(raw: bool) -> Union[bytes, str]: ...\n\n    def fetch_data(raw: bool) -> Union[bytes, str]:\n        # Implementation is omitted\n        ...\n\n    reveal_type(fetch_data(True))        # Revealed type is \"bytes\"\n    reveal_type(fetch_data(False))       # Revealed type is \"str\"\n\n    # Variables declared without annotations will continue to have an\n    # inferred type of 'bool'.\n\n    variable = True\n    reveal_type(fetch_data(variable))    # Revealed type is \"Union[bytes, str]\"\n\n.. note::\n\n    The examples in this page import ``Literal`` as well as ``Final`` and\n    ``TypedDict`` from the ``typing`` module. These types were added to\n    ``typing`` in Python 3.8, but are also available for use in Python\n    3.4 - 3.7 via the ``typing_extensions`` package.\n\nParameterizing Literals\n***********************\n\nLiteral types may contain one or more literal bools, ints, strs, bytes, and\nenum values. However, literal types **cannot** contain arbitrary expressions:\ntypes like ``Literal[my_string.trim()]``, ``Literal[x > 3]``, or ``Literal[3j + 4]``\nare all illegal.\n\nLiterals containing two or more values are equivalent to the union of those values.\nSo, ``Literal[-3, b\"foo\", MyEnum.A]`` is equivalent to\n``Union[Literal[-3], Literal[b\"foo\"], Literal[MyEnum.A]]``. This makes writing more\ncomplex types involving literals a little more convenient.\n\nLiteral types may also contain ``None``. Mypy will treat ``Literal[None]`` as being\nequivalent to just ``None``. This means that ``Literal[4, None]``,\n``Literal[4] | None``, and ``Optional[Literal[4]]`` are all equivalent.\n\nLiterals may also contain aliases to other literal types. For example, the\nfollowing program is legal:\n\n.. code-block:: python\n\n    PrimaryColors = Literal[\"red\", \"blue\", \"yellow\"]\n    SecondaryColors = Literal[\"purple\", \"green\", \"orange\"]\n    AllowedColors = Literal[PrimaryColors, SecondaryColors]\n\n    def paint(color: AllowedColors) -> None: ...\n\n    paint(\"red\")        # Type checks!\n    paint(\"turquoise\")  # Does not type check\n\nLiterals may not contain any other kind of type or expression. This means doing\n``Literal[my_instance]``, ``Literal[Any]``, ``Literal[3.14]``, or\n``Literal[{\"foo\": 2, \"bar\": 5}]`` are all illegal.\n\nDeclaring literal variables\n***************************\n\nYou must explicitly add an annotation to a variable to declare that it has\na literal type:\n\n.. code-block:: python\n\n    a: Literal[19] = 19\n    reveal_type(a)          # Revealed type is \"Literal[19]\"\n\nIn order to preserve backwards-compatibility, variables without this annotation\nare **not** assumed to be literals:\n\n.. code-block:: python\n\n    b = 19\n    reveal_type(b)          # Revealed type is \"int\"\n\nIf you find repeating the value of the variable in the type hint to be tedious,\nyou can instead change the variable to be ``Final`` (see :ref:`final_attrs`):\n\n.. code-block:: python\n\n    from typing import Final, Literal\n\n    def expects_literal(x: Literal[19]) -> None: pass\n\n    c: Final = 19\n\n    reveal_type(c)          # Revealed type is \"Literal[19]?\"\n    expects_literal(c)      # ...and this type checks!\n\nIf you do not provide an explicit type in the ``Final``, the type of ``c`` becomes\n*context-sensitive*: mypy will basically try \"substituting\" the original assigned\nvalue whenever it's used before performing type checking. This is why the revealed\ntype of ``c`` is ``Literal[19]?``: the question mark at the end reflects this\ncontext-sensitive nature.\n\nFor example, mypy will type check the above program almost as if it were written like so:\n\n.. code-block:: python\n\n    from typing import Final, Literal\n\n    def expects_literal(x: Literal[19]) -> None: pass\n\n    reveal_type(19)\n    expects_literal(19)\n\nThis means that while changing a variable to be ``Final`` is not quite the same thing\nas adding an explicit ``Literal[...]`` annotation, it often leads to the same effect\nin practice.\n\nThe main cases where the behavior of context-sensitive vs true literal types differ are\nwhen you try using those types in places that are not explicitly expecting a ``Literal[...]``.\nFor example, compare and contrast what happens when you try appending these types to a list:\n\n.. code-block:: python\n\n    from typing import Final, Literal\n\n    a: Final = 19\n    b: Literal[19] = 19\n\n    # Mypy will choose to infer list[int] here.\n    list_of_ints = []\n    list_of_ints.append(a)\n    reveal_type(list_of_ints)  # Revealed type is \"list[int]\"\n\n    # But if the variable you're appending is an explicit Literal, mypy\n    # will infer list[Literal[19]].\n    list_of_lits = []\n    list_of_lits.append(b)\n    reveal_type(list_of_lits)  # Revealed type is \"list[Literal[19]]\"\n\n\nIntelligent indexing\n********************\n\nWe can use Literal types to more precisely index into structured heterogeneous\ntypes such as tuples, NamedTuples, and TypedDicts. This feature is known as\n*intelligent indexing*.\n\nFor example, when we index into a tuple using some int, the inferred type is\nnormally the union of the tuple item types. However, if we want just the type\ncorresponding to some particular index, we can use Literal types like so:\n\n.. code-block:: python\n\n    from typing import TypedDict\n\n    tup = (\"foo\", 3.4)\n\n    # Indexing with an int literal gives us the exact type for that index\n    reveal_type(tup[0])  # Revealed type is \"str\"\n\n    # But what if we want the index to be a variable? Normally mypy won't\n    # know exactly what the index is and so will return a less precise type:\n    int_index = 0\n    reveal_type(tup[int_index])  # Revealed type is \"Union[str, float]\"\n\n    # But if we use either Literal types or a Final int, we can gain back\n    # the precision we originally had:\n    lit_index: Literal[0] = 0\n    fin_index: Final = 0\n    reveal_type(tup[lit_index])  # Revealed type is \"str\"\n    reveal_type(tup[fin_index])  # Revealed type is \"str\"\n\n    # We can do the same thing with with TypedDict and str keys:\n    class MyDict(TypedDict):\n        name: str\n        main_id: int\n        backup_id: int\n\n    d: MyDict = {\"name\": \"Saanvi\", \"main_id\": 111, \"backup_id\": 222}\n    name_key: Final = \"name\"\n    reveal_type(d[name_key])  # Revealed type is \"str\"\n\n    # You can also index using unions of literals\n    id_key: Literal[\"main_id\", \"backup_id\"]\n    reveal_type(d[id_key])    # Revealed type is \"int\"\n\n.. _tagged_unions:\n\nTagged unions\n*************\n\nWhen you have a union of types, you can normally discriminate between each type\nin the union by using ``isinstance`` checks. For example, if you had a variable ``x`` of\ntype ``Union[int, str]``, you could write some code that runs only if ``x`` is an int\nby doing ``if isinstance(x, int): ...``.\n\nHowever, it is not always possible or convenient to do this. For example, it is not\npossible to use ``isinstance`` to distinguish between two different TypedDicts since\nat runtime, your variable will simply be just a dict.\n\nInstead, what you can do is *label* or *tag* your TypedDicts with a distinct Literal\ntype. Then, you can discriminate between each kind of TypedDict by checking the label:\n\n.. code-block:: python\n\n    from typing import Literal, TypedDict, Union\n\n    class NewJobEvent(TypedDict):\n        tag: Literal[\"new-job\"]\n        job_name: str\n        config_file_path: str\n\n    class CancelJobEvent(TypedDict):\n        tag: Literal[\"cancel-job\"]\n        job_id: int\n\n    Event = Union[NewJobEvent, CancelJobEvent]\n\n    def process_event(event: Event) -> None:\n        # Since we made sure both TypedDicts have a key named 'tag', it's\n        # safe to do 'event[\"tag\"]'. This expression normally has the type\n        # Literal[\"new-job\", \"cancel-job\"], but the check below will narrow\n        # the type to either Literal[\"new-job\"] or Literal[\"cancel-job\"].\n        #\n        # This in turns narrows the type of 'event' to either NewJobEvent\n        # or CancelJobEvent.\n        if event[\"tag\"] == \"new-job\":\n            print(event[\"job_name\"])\n        else:\n            print(event[\"job_id\"])\n\nWhile this feature is mostly useful when working with TypedDicts, you can also\nuse the same technique with regular objects, tuples, or namedtuples.\n\nSimilarly, tags do not need to be specifically str Literals: they can be any type\nyou can normally narrow within ``if`` statements and the like. For example, you\ncould have your tags be int or Enum Literals or even regular classes you narrow\nusing ``isinstance()`` (Python 3.12 syntax):\n\n.. code-block:: python\n\n    class Wrapper[T]:\n        def __init__(self, inner: T) -> None:\n            self.inner = inner\n\n    def process(w: Wrapper[int] | Wrapper[str]) -> None:\n        # Doing `if isinstance(w, Wrapper[int])` does not work: isinstance requires\n        # that the second argument always be an *erased* type, with no generics.\n        # This is because generics are a typing-only concept and do not exist at\n        # runtime in a way `isinstance` can always check.\n        #\n        # However, we can side-step this by checking the type of `w.inner` to\n        # narrow `w` itself:\n        if isinstance(w.inner, int):\n            reveal_type(w)  # Revealed type is \"Wrapper[int]\"\n        else:\n            reveal_type(w)  # Revealed type is \"Wrapper[str]\"\n\nThis feature is sometimes called \"sum types\" or \"discriminated union types\"\nin other programming languages.\n\nExhaustiveness checking\n***********************\n\nYou may want to check that some code covers all possible\n``Literal`` or ``Enum`` cases. Example:\n\n.. code-block:: python\n\n  from typing import Literal\n\n  PossibleValues = Literal['one', 'two']\n\n  def validate(x: PossibleValues) -> bool:\n      if x == 'one':\n          return True\n      elif x == 'two':\n          return False\n      raise ValueError(f'Invalid value: {x}')\n\n  assert validate('one') is True\n  assert validate('two') is False\n\nIn the code above, it's easy to make a mistake. You can\nadd a new literal value to ``PossibleValues`` but forget\nto handle it in the ``validate`` function:\n\n.. code-block:: python\n\n  PossibleValues = Literal['one', 'two', 'three']\n\nMypy won't catch that ``'three'`` is not covered.  If you want mypy to\nperform an exhaustiveness check, you need to update your code to use an\n``assert_never()`` check:\n\n.. code-block:: python\n\n  from typing import Literal, NoReturn\n  from typing_extensions import assert_never\n\n  PossibleValues = Literal['one', 'two']\n\n  def validate(x: PossibleValues) -> bool:\n      if x == 'one':\n          return True\n      elif x == 'two':\n          return False\n      assert_never(x)\n\nNow if you add a new value to ``PossibleValues`` but don't update ``validate``,\nmypy will spot the error:\n\n.. code-block:: python\n\n  PossibleValues = Literal['one', 'two', 'three']\n\n  def validate(x: PossibleValues) -> bool:\n      if x == 'one':\n          return True\n      elif x == 'two':\n          return False\n      # Error: Argument 1 to \"assert_never\" has incompatible type \"Literal['three']\";\n      # expected \"NoReturn\"\n      assert_never(x)\n\nIf runtime checking against unexpected values is not needed, you can\nleave out the ``assert_never`` call in the above example, and mypy\nwill still generate an error about function ``validate`` returning\nwithout a value:\n\n.. code-block:: python\n\n  PossibleValues = Literal['one', 'two', 'three']\n\n  # Error: Missing return statement\n  def validate(x: PossibleValues) -> bool:\n      if x == 'one':\n          return True\n      elif x == 'two':\n          return False\n\nExhaustiveness checking is also supported for match statements (Python 3.10 and later):\n\n.. code-block:: python\n\n  def validate(x: PossibleValues) -> bool:\n      match x:\n          case 'one':\n              return True\n          case 'two':\n              return False\n      assert_never(x)\n\n\nLimitations\n***********\n\nMypy will not understand expressions that use variables of type ``Literal[..]``\non a deep level. For example, if you have a variable ``a`` of type ``Literal[3]``\nand another variable ``b`` of type ``Literal[5]``, mypy will infer that\n``a + b`` has type ``int``, **not** type ``Literal[8]``.\n\nThe basic rule is that literal types are treated as just regular subtypes of\nwhatever type the parameter has. For example, ``Literal[3]`` is treated as a\nsubtype of ``int`` and so will inherit all of ``int``'s methods directly. This\nmeans that ``Literal[3].__add__`` accepts the same arguments and has the same\nreturn type as ``int.__add__``.\n\n\nEnums\n-----\n\nMypy has special support for :py:class:`enum.Enum` and its subclasses:\n:py:class:`enum.IntEnum`, :py:class:`enum.Flag`, :py:class:`enum.IntFlag`,\nand :py:class:`enum.StrEnum`.\n\n.. code-block:: python\n\n  from enum import Enum\n\n  class Direction(Enum):\n      up = 'up'\n      down = 'down'\n\n  reveal_type(Direction.up)  # Revealed type is \"Literal[Direction.up]?\"\n  reveal_type(Direction.down)  # Revealed type is \"Literal[Direction.down]?\"\n\nYou can use enums to annotate types as you would expect:\n\n.. code-block:: python\n\n  class Movement:\n      def __init__(self, direction: Direction, speed: float) -> None:\n          self.direction = direction\n          self.speed = speed\n\n  Movement(Direction.up, 5.0)  # ok\n  Movement('up', 5.0)  # E: Argument 1 to \"Movement\" has incompatible type \"str\"; expected \"Direction\"\n\nExhaustiveness checking\n***********************\n\nSimilar to ``Literal`` types, ``Enum`` supports exhaustiveness checking.\nLet's start with a definition:\n\n.. code-block:: python\n\n  from enum import Enum\n  from typing import NoReturn\n  from typing_extensions import assert_never\n\n  class Direction(Enum):\n      up = 'up'\n      down = 'down'\n\nNow, let's use an exhaustiveness check:\n\n.. code-block:: python\n\n  def choose_direction(direction: Direction) -> None:\n      if direction is Direction.up:\n          reveal_type(direction)  # N: Revealed type is \"Literal[Direction.up]\"\n          print('Going up!')\n          return\n      elif direction is Direction.down:\n          print('Down')\n          return\n      # This line is never reached\n      assert_never(direction)\n\nIf we forget to handle one of the cases, mypy will generate an error:\n\n.. code-block:: python\n\n  def choose_direction(direction: Direction) -> None:\n      if direction == Direction.up:\n          print('Going up!')\n          return\n      assert_never(direction)  # E: Argument 1 to \"assert_never\" has incompatible type \"Direction\"; expected \"NoReturn\"\n\nExhaustiveness checking is also supported for match statements (Python 3.10 and later).\nFor match statements specifically, inexhaustive matches can be caught\nwithout needing to use ``assert_never`` by using\n:option:`--enable-error-code exhaustive-match <mypy --enable-error-code>`.\n\n\nExtra Enum checks\n*****************\n\nMypy also tries to support special features of ``Enum``\nthe same way Python's runtime does:\n\n- Any ``Enum`` class with values is implicitly :ref:`final <final_attrs>`.\n  This is what happens in CPython:\n\n  .. code-block:: python\n\n    >>> class AllDirection(Direction):\n    ...     left = 'left'\n    ...     right = 'right'\n    Traceback (most recent call last):\n      ...\n    TypeError: AllDirection: cannot extend enumeration 'Direction'\n\n  Mypy also catches this error:\n\n  .. code-block:: python\n\n    class AllDirection(Direction):  # E: Cannot inherit from final class \"Direction\"\n        left = 'left'\n        right = 'right'\n\n- All ``Enum`` fields are implicitly ``final`` as well.\n\n  .. code-block:: python\n\n    Direction.up = '^'  # E: Cannot assign to final attribute \"up\"\n\n- All field names are checked to be unique.\n\n  .. code-block:: python\n\n     class Some(Enum):\n        x = 1\n        x = 2  # E: Attempted to reuse member name \"x\" in Enum definition \"Some\"\n\n- Base classes have no conflicts and mixin types are correct.\n\n  .. code-block:: python\n\n    class WrongEnum(str, int, enum.Enum):\n        # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"int\"\n        ...\n\n    class MixinAfterEnum(enum.Enum, Mixin): # E: No base classes are allowed after \"enum.Enum\"\n        ...\n"
  },
  {
    "path": "docs/source/metaclasses.rst",
    "content": ".. _metaclasses:\n\nMetaclasses\n===========\n\nA :ref:`metaclass <python:metaclasses>` is a class that describes\nthe construction and behavior of other classes, similarly to how classes\ndescribe the construction and behavior of objects.\nThe default metaclass is :py:class:`type`, but it's possible to use other metaclasses.\nMetaclasses allows one to create \"a different kind of class\", such as\n:py:class:`~enum.Enum`\\s, :py:class:`~typing.NamedTuple`\\s and singletons.\n\nMypy has some special understanding of :py:class:`~abc.ABCMeta` and ``EnumMeta``.\n\n.. _defining:\n\nDefining a metaclass\n********************\n\n.. code-block:: python\n\n    class M(type):\n        pass\n\n    class A(metaclass=M):\n        pass\n\n.. _examples:\n\nMetaclass usage example\n***********************\n\nMypy supports the lookup of attributes in the metaclass:\n\n.. code-block:: python\n\n    from typing import ClassVar, TypeVar\n\n    S = TypeVar(\"S\")\n\n    class M(type):\n        count: ClassVar[int] = 0\n\n        def make(cls: type[S]) -> S:\n            M.count += 1\n            return cls()\n\n    class A(metaclass=M):\n        pass\n\n    a: A = A.make()  # make() is looked up at M; the result is an object of type A\n    print(A.count)\n\n    class B(A):\n        pass\n\n    b: B = B.make()  # metaclasses are inherited\n    print(B.count + \" objects were created\")  # Error: Unsupported operand types for + (\"int\" and \"str\")\n\n.. _limitations:\n\nGotchas and limitations of metaclass support\n********************************************\n\nNote that metaclasses pose some requirements on the inheritance structure,\nso it's better not to combine metaclasses and class hierarchies:\n\n.. code-block:: python\n\n    class M1(type): pass\n    class M2(type): pass\n\n    class A1(metaclass=M1): pass\n    class A2(metaclass=M2): pass\n\n    class B1(A1, metaclass=M2): pass  # Mypy Error: metaclass conflict\n    # At runtime the above definition raises an exception\n    # TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases\n\n    class B12(A1, A2): pass  # Mypy Error: metaclass conflict\n\n    # This can be solved via a common metaclass subtype:\n    class CorrectMeta(M1, M2): pass\n    class B2(A1, A2, metaclass=CorrectMeta): pass  # OK, runtime is also OK\n\n* Mypy does not understand dynamically-computed metaclasses,\n  such as ``class A(metaclass=f()): ...``\n* Mypy does not and cannot understand arbitrary metaclass code.\n* Mypy only recognizes subclasses of :py:class:`type` as potential metaclasses.\n* ``Self`` is not allowed as annotation in metaclasses as per `PEP 673`_.\n\n.. _PEP 673: https://peps.python.org/pep-0673/#valid-locations-for-self\n\nFor some builtin types, mypy may think their metaclass is :py:class:`abc.ABCMeta`\neven if it is :py:class:`type` at runtime. In those cases, you can either:\n\n* use :py:class:`abc.ABCMeta` instead of :py:class:`type` as the\n  superclass of your metaclass if that works in your use-case\n* mute the error with ``# type: ignore[metaclass]``\n\n.. code-block:: python\n\n    import abc\n\n    assert type(tuple) is type  # metaclass of tuple is type at runtime\n\n    # The problem:\n    class M0(type): pass\n    class A0(tuple, metaclass=M0): pass  # Mypy Error: metaclass conflict\n\n    # Option 1: use ABCMeta instead of type\n    class M1(abc.ABCMeta): pass\n    class A1(tuple, metaclass=M1): pass\n\n    # Option 2: mute the error\n    class M2(type): pass\n    class A2(tuple, metaclass=M2): pass  # type: ignore[metaclass]\n"
  },
  {
    "path": "docs/source/more_types.rst",
    "content": "More types\n==========\n\nThis section introduces a few additional kinds of types, including :py:data:`~typing.NoReturn`,\n:py:class:`~typing.NewType`, and types for async code. It also discusses\nhow to give functions more precise types using overloads. All of these are only\nsituationally useful, so feel free to skip this section and come back when you\nhave a need for some of them.\n\nHere's a quick summary of what's covered here:\n\n* :py:data:`~typing.NoReturn` lets you tell mypy that a function never returns normally.\n\n* :py:class:`~typing.NewType` lets you define a variant of a type that is treated as a\n  separate type by mypy but is identical to the original type at runtime.\n  For example, you can have ``UserId`` as a variant of ``int`` that is\n  just an ``int`` at runtime.\n\n* :py:func:`@overload <typing.overload>` lets you define a function that can accept multiple distinct\n  signatures. This is useful if you need to encode a relationship between the\n  arguments and the return type that would be difficult to express normally.\n\n* Async types let you type check programs using ``async`` and ``await``.\n\n.. _noreturn:\n\nThe NoReturn type\n*****************\n\nMypy provides support for functions that never return. For\nexample, a function that unconditionally raises an exception:\n\n.. code-block:: python\n\n   from typing import NoReturn\n\n   def stop() -> NoReturn:\n       raise Exception('no way')\n\nMypy will ensure that functions annotated as returning :py:data:`~typing.NoReturn`\ntruly never return, either implicitly or explicitly. Mypy will also\nrecognize that the code after calls to such functions is unreachable\nand will behave accordingly:\n\n.. code-block:: python\n\n   def f(x: int) -> int:\n       if x == 0:\n           return x\n       stop()\n       return 'whatever works'  # No error in an unreachable block\n\nIn earlier Python versions you need to install ``typing_extensions`` using\npip to use :py:data:`~typing.NoReturn` in your code. Python 3 command line:\n\n.. code-block:: text\n\n    python3 -m pip install --upgrade typing-extensions\n\n.. _newtypes:\n\nNewTypes\n********\n\nThere are situations where you may want to avoid programming errors by\ncreating simple derived classes that are only used to distinguish\ncertain values from base class instances. Example:\n\n.. code-block:: python\n\n    class UserId(int):\n        pass\n\n    def get_by_user_id(user_id: UserId):\n        ...\n\nHowever, this approach introduces some runtime overhead. To avoid this, the typing\nmodule provides a helper object :py:class:`~typing.NewType` that creates simple unique types with\nalmost zero runtime overhead. Mypy will treat the statement\n``Derived = NewType('Derived', Base)`` as being roughly equivalent to the following\ndefinition:\n\n.. code-block:: python\n\n    class Derived(Base):\n        def __init__(self, _x: Base) -> None:\n            ...\n\nHowever, at runtime, ``NewType('Derived', Base)`` will return a dummy callable that\nsimply returns its argument:\n\n.. code-block:: python\n\n    def Derived(_x):\n        return _x\n\nMypy will require explicit casts from ``int`` where ``UserId`` is expected, while\nimplicitly casting from ``UserId`` where ``int`` is expected. Examples:\n\n.. code-block:: python\n\n    from typing import NewType\n\n    UserId = NewType('UserId', int)\n\n    def name_by_id(user_id: UserId) -> str:\n        ...\n\n    UserId('user')          # Fails type check\n\n    name_by_id(42)          # Fails type check\n    name_by_id(UserId(42))  # OK\n\n    num: int = UserId(5) + 1\n\n:py:class:`~typing.NewType` accepts exactly two arguments. The first argument must be a string literal\ncontaining the name of the new type and must equal the name of the variable to which the new\ntype is assigned. The second argument must be a properly subclassable class, i.e.,\nnot a type construct like a :ref:`union type <union-types>`, etc.\n\nThe callable returned by :py:class:`~typing.NewType` accepts only one argument; this is equivalent to\nsupporting only one constructor accepting an instance of the base class (see above).\nExample:\n\n.. code-block:: python\n\n    from typing import NewType\n\n    class PacketId:\n        def __init__(self, major: int, minor: int) -> None:\n            self._major = major\n            self._minor = minor\n\n    TcpPacketId = NewType('TcpPacketId', PacketId)\n\n    packet = PacketId(100, 100)\n    tcp_packet = TcpPacketId(packet)  # OK\n\n    tcp_packet = TcpPacketId(127, 0)  # Fails in type checker and at runtime\n\nYou cannot use :py:func:`isinstance` or :py:func:`issubclass` on the object returned by\n:py:class:`~typing.NewType`, nor can you subclass an object returned by :py:class:`~typing.NewType`.\n\n.. note::\n\n    Unlike type aliases, :py:class:`~typing.NewType` will create an entirely new and\n    unique type when used. The intended purpose of :py:class:`~typing.NewType` is to help you\n    detect cases where you accidentally mixed together the old base type and the\n    new derived type.\n\n    For example, the following will successfully typecheck when using type\n    aliases:\n\n    .. code-block:: python\n\n        UserId = int\n\n        def name_by_id(user_id: UserId) -> str:\n            ...\n\n        name_by_id(3)  # ints and UserId are synonymous\n\n    But a similar example using :py:class:`~typing.NewType` will not typecheck:\n\n    .. code-block:: python\n\n        from typing import NewType\n\n        UserId = NewType('UserId', int)\n\n        def name_by_id(user_id: UserId) -> str:\n            ...\n\n        name_by_id(3)  # int is not the same as UserId\n\n.. _function-overloading:\n\nFunction overloading\n********************\n\nSometimes the arguments and types in a function depend on each other\nin ways that can't be captured with a :ref:`union types <union-types>`. For example, suppose\nwe want to write a function that can accept x-y coordinates. If we pass\nin just a single x-y coordinate, we return a ``ClickEvent`` object. However,\nif we pass in two x-y coordinates, we return a ``DragEvent`` object.\n\nOur first attempt at writing this function might look like this:\n\n.. code-block:: python\n\n    def mouse_event(x1: int,\n                    y1: int,\n                    x2: int | None = None,\n                    y2: int | None = None) -> ClickEvent | DragEvent:\n        if x2 is None and y2 is None:\n            return ClickEvent(x1, y1)\n        elif x2 is not None and y2 is not None:\n            return DragEvent(x1, y1, x2, y2)\n        else:\n            raise TypeError(\"Bad arguments\")\n\nWhile this function signature works, it's too loose: it implies ``mouse_event``\ncould return either object regardless of the number of arguments\nwe pass in. It also does not prohibit a caller from passing in the wrong\nnumber of ints: mypy would treat calls like ``mouse_event(1, 2, 20)`` as being\nvalid, for example.\n\nWe can do better by using :pep:`overloading <484#function-method-overloading>`\nwhich lets us give the same function multiple type annotations (signatures)\nto more accurately describe the function's behavior:\n\n.. code-block:: python\n\n    from typing import overload\n\n    # Overload *variants* for 'mouse_event'.\n    # These variants give extra information to the type checker.\n    # They are ignored at runtime.\n\n    @overload\n    def mouse_event(x1: int, y1: int) -> ClickEvent: ...\n    @overload\n    def mouse_event(x1: int, y1: int, x2: int, y2: int) -> DragEvent: ...\n\n    # The actual *implementation* of 'mouse_event'.\n    # The implementation contains the actual runtime logic.\n    #\n    # It may or may not have type hints. If it does, mypy\n    # will check the body of the implementation against the\n    # type hints.\n    #\n    # Mypy will also check and make sure the signature is\n    # consistent with the provided variants.\n\n    def mouse_event(x1: int,\n                    y1: int,\n                    x2: int | None = None,\n                    y2: int | None = None) -> ClickEvent | DragEvent:\n        if x2 is None and y2 is None:\n            return ClickEvent(x1, y1)\n        elif x2 is not None and y2 is not None:\n            return DragEvent(x1, y1, x2, y2)\n        else:\n            raise TypeError(\"Bad arguments\")\n\nThis allows mypy to understand calls to ``mouse_event`` much more precisely.\nFor example, mypy will understand that ``mouse_event(5, 25)`` will\nalways have a return type of ``ClickEvent`` and will report errors for\ncalls like ``mouse_event(5, 25, 2)``.\n\nAs another example, suppose we want to write a custom container class that\nimplements the :py:meth:`__getitem__ <object.__getitem__>` method (``[]`` bracket indexing). If this\nmethod receives an integer we return a single item. If it receives a\n``slice``, we return a :py:class:`~collections.abc.Sequence` of items.\n\nWe can precisely encode this relationship between the argument and the\nreturn type by using overloads like so (Python 3.12 syntax):\n\n.. code-block:: python\n\n    from collections.abc import Sequence\n    from typing import overload\n\n    class MyList[T](Sequence[T]):\n        @overload\n        def __getitem__(self, index: int) -> T: ...\n\n        @overload\n        def __getitem__(self, index: slice) -> Sequence[T]: ...\n\n        def __getitem__(self, index: int | slice) -> T | Sequence[T]:\n            if isinstance(index, int):\n                # Return a T here\n            elif isinstance(index, slice):\n                # Return a sequence of Ts here\n            else:\n                raise TypeError(...)\n\nHere is the same example using the legacy syntax (Python 3.11 and earlier):\n\n.. code-block:: python\n\n    from collections.abc import Sequence\n    from typing import TypeVar, overload\n\n    T = TypeVar('T')\n\n    class MyList(Sequence[T]):\n        @overload\n        def __getitem__(self, index: int) -> T: ...\n\n        @overload\n        def __getitem__(self, index: slice) -> Sequence[T]: ...\n\n        def __getitem__(self, index: int | slice) -> T | Sequence[T]:\n            if isinstance(index, int):\n                # Return a T here\n            elif isinstance(index, slice):\n                # Return a sequence of Ts here\n            else:\n                raise TypeError(...)\n\n.. note::\n\n   If you just need to constrain a type variable to certain types or\n   subtypes, you can use a :ref:`value restriction\n   <type-variable-value-restriction>`.\n\nThe default values of a function's arguments don't affect its signature -- only\nthe absence or presence of a default value does. So in order to reduce\nredundancy, it's possible to replace default values in overload definitions with\n``...`` as a placeholder:\n\n.. code-block:: python\n\n    from typing import overload\n\n    class M: ...\n\n    @overload\n    def get_model(model_or_pk: M, flag: bool = ...) -> M: ...\n    @overload\n    def get_model(model_or_pk: int, flag: bool = ...) -> M | None: ...\n\n    def get_model(model_or_pk: int | M, flag: bool = True) -> M | None:\n        ...\n\n\nRuntime behavior\n----------------\n\nAn overloaded function must consist of two or more overload *variants*\nfollowed by an *implementation*. The variants and the implementations\nmust be adjacent in the code: think of them as one indivisible unit.\n\nThe variant bodies must all be empty; only the implementation is allowed\nto contain code. This is because at runtime, the variants are completely\nignored: they're overridden by the final implementation function.\n\nThis means that an overloaded function is still an ordinary Python\nfunction! There is no automatic dispatch handling and you must manually\nhandle the different types in the implementation (e.g. by using\n``if`` statements and :py:func:`isinstance <isinstance>` checks).\n\nIf you are adding an overload within a stub file, the implementation\nfunction should be omitted: stubs do not contain runtime logic.\n\n.. note::\n\n   While we can leave the variant body empty using the ``pass`` keyword,\n   the more common convention is to instead use the ellipsis (``...``) literal.\n\nType checking calls to overloads\n--------------------------------\n\nWhen you call an overloaded function, mypy will infer the correct return\ntype by picking the best matching variant, after taking into consideration\nboth the argument types and arity. However, a call is never type\nchecked against the implementation. This is why mypy will report calls\nlike ``mouse_event(5, 25, 3)`` as being invalid even though it matches the\nimplementation signature.\n\nIf there are multiple equally good matching variants, mypy will select\nthe variant that was defined first. For example, consider the following\nprogram:\n\n.. code-block:: python\n\n    # For Python 3.8 and below you must use `typing.List` instead of `list`. e.g.\n    # from typing import List\n    from typing import overload\n\n    @overload\n    def summarize(data: list[int]) -> float: ...\n\n    @overload\n    def summarize(data: list[str]) -> str: ...\n\n    def summarize(data):\n        if not data:\n            return 0.0\n        elif isinstance(data[0], int):\n            # Do int specific code\n        else:\n            # Do str-specific code\n\n    # What is the type of 'output'? float or str?\n    output = summarize([])\n\nThe ``summarize([])`` call matches both variants: an empty list could\nbe either a ``list[int]`` or a ``list[str]``. In this case, mypy\nwill break the tie by picking the first matching variant: ``output``\nwill have an inferred type of ``float``. The implementer is responsible\nfor making sure ``summarize`` breaks ties in the same way at runtime.\n\nHowever, there are two exceptions to the \"pick the first match\" rule.\nFirst, if multiple variants match due to an argument being of type\n``Any``, mypy will make the inferred type also be ``Any``:\n\n.. code-block:: python\n\n    dynamic_var: Any = some_dynamic_function()\n\n    # output2 is of type 'Any'\n    output2 = summarize(dynamic_var)\n\nSecond, if multiple variants match due to one or more of the arguments\nbeing a union, mypy will make the inferred type be the union of the\nmatching variant returns:\n\n.. code-block:: python\n\n    some_list: list[int] | list[str]\n\n    # output3 is of type 'float | str'\n    output3 = summarize(some_list)\n\n.. note::\n\n   Due to the \"pick the first match\" rule, changing the order of your\n   overload variants can change how mypy type checks your program.\n\n   To minimize potential issues, we recommend that you:\n\n   1. Make sure your overload variants are listed in the same order as\n      the runtime checks (e.g. :py:func:`isinstance <isinstance>` checks) in your implementation.\n   2. Order your variants and runtime checks from most to least specific.\n      (See the following section for an example).\n\nType checking the variants\n--------------------------\n\nMypy will perform several checks on your overload variant definitions\nto ensure they behave as expected. First, mypy will check and make sure\nthat no overload variant is shadowing a subsequent one. For example,\nconsider the following function which adds together two ``Expression``\nobjects, and contains a special-case to handle receiving two ``Literal``\ntypes:\n\n.. code-block:: python\n\n    from typing import overload\n\n    class Expression:\n        # ...snip...\n\n    class Literal(Expression):\n        # ...snip...\n\n    # Warning -- the first overload variant shadows the second!\n\n    @overload\n    def add(left: Expression, right: Expression) -> Expression: ...\n\n    @overload\n    def add(left: Literal, right: Literal) -> Literal: ...\n\n    def add(left: Expression, right: Expression) -> Expression:\n        # ...snip...\n\nWhile this code snippet is technically type-safe, it does contain an\nanti-pattern: the second variant will never be selected! If we try calling\n``add(Literal(3), Literal(4))``, mypy will always pick the first variant\nand evaluate the function call to be of type ``Expression``, not ``Literal``.\nThis is because ``Literal`` is a subtype of ``Expression``, which means\nthe \"pick the first match\" rule will always halt after considering the\nfirst overload.\n\nBecause having an overload variant that can never be matched is almost\ncertainly a mistake, mypy will report an error. To fix the error, we can\neither 1) delete the second overload or 2) swap the order of the overloads:\n\n.. code-block:: python\n\n    # Everything is ok now -- the variants are correctly ordered\n    # from most to least specific.\n\n    @overload\n    def add(left: Literal, right: Literal) -> Literal: ...\n\n    @overload\n    def add(left: Expression, right: Expression) -> Expression: ...\n\n    def add(left: Expression, right: Expression) -> Expression:\n        # ...snip...\n\nMypy will also type check the different variants and flag any overloads\nthat have inherently unsafely overlapping variants. For example, consider\nthe following unsafe overload definition:\n\n.. code-block:: python\n\n    from typing import overload\n\n    @overload\n    def unsafe_func(x: int) -> int: ...\n\n    @overload\n    def unsafe_func(x: object) -> str: ...\n\n    def unsafe_func(x: object) -> int | str:\n        if isinstance(x, int):\n            return 42\n        else:\n            return \"some string\"\n\nOn the surface, this function definition appears to be fine. However, it will\nresult in a discrepancy between the inferred type and the actual runtime type\nwhen we try using it like so:\n\n.. code-block:: python\n\n    some_obj: object = 42\n    unsafe_func(some_obj) + \" danger danger\"  # Type checks, yet crashes at runtime!\n\nSince ``some_obj`` is of type :py:class:`object`, mypy will decide that ``unsafe_func``\nmust return something of type ``str`` and concludes the above will type check.\nBut in reality, ``unsafe_func`` will return an int, causing the code to crash\nat runtime!\n\nTo prevent these kinds of issues, mypy will detect and prohibit inherently unsafely\noverlapping overloads on a best-effort basis. Two variants are considered unsafely\noverlapping when both of the following are true:\n\n1. All of the arguments of the first variant are potentially compatible with the second.\n2. The return type of the first variant is *not* compatible with (e.g. is not a\n   subtype of) the second.\n\nSo in this example, the ``int`` argument in the first variant is a subtype of\nthe ``object`` argument in the second, yet the ``int`` return type is not a subtype of\n``str``. Both conditions are true, so mypy will correctly flag ``unsafe_func`` as\nbeing unsafe.\n\nNote that in cases where you ignore the overlapping overload error, mypy will usually\nstill infer the types you expect at callsites.\n\nHowever, mypy will not detect *all* unsafe uses of overloads. For example,\nsuppose we modify the above snippet so it calls ``summarize`` instead of\n``unsafe_func``:\n\n.. code-block:: python\n\n    some_list: list[str] = []\n    summarize(some_list) + \"danger danger\"  # Type safe, yet crashes at runtime!\n\nWe run into a similar issue here. This program type checks if we look just at the\nannotations on the overloads. But since ``summarize(...)`` is designed to be biased\ntowards returning a float when it receives an empty list, this program will actually\ncrash during runtime.\n\nThe reason mypy does not flag definitions like ``summarize`` as being potentially\nunsafe is because if it did, it would be extremely difficult to write a safe\noverload. For example, suppose we define an overload with two variants that accept\ntypes ``A`` and ``B`` respectively. Even if those two types were completely unrelated,\nthe user could still potentially trigger a runtime error similar to the ones above by\npassing in a value of some third type ``C`` that inherits from both ``A`` and ``B``.\n\nThankfully, these types of situations are relatively rare. What this does mean,\nhowever, is that you should exercise caution when designing or using an overloaded\nfunction that can potentially receive values that are an instance of two seemingly\nunrelated types.\n\n\nType checking the implementation\n--------------------------------\n\nThe body of an implementation is type-checked against the\ntype hints provided on the implementation. For example, in the\n``MyList`` example up above, the code in the body is checked with\nargument list ``index: int | slice`` and a return type of\n``T | Sequence[T]``. If there are no annotations on the\nimplementation, then the body is not type checked. If you want to\nforce mypy to check the body anyways, use the :option:`--check-untyped-defs <mypy --check-untyped-defs>`\nflag (:ref:`more details here <untyped-definitions-and-calls>`).\n\nThe variants must also also be compatible with the implementation\ntype hints. In the ``MyList`` example, mypy will check that the\nparameter type ``int`` and the return type ``T`` are compatible with\n``int | slice`` and ``T | Sequence`` for the\nfirst variant. For the second variant it verifies the parameter\ntype ``slice`` and the return type ``Sequence[T]`` are compatible\nwith ``int | slice`` and ``T | Sequence``.\n\n.. note::\n\n   The overload semantics documented above are new as of mypy 0.620.\n\n   Previously, mypy used to perform type erasure on all overload variants. For\n   example, the ``summarize`` example from the previous section used to be\n   illegal because ``list[str]`` and ``list[int]`` both erased to just ``list[Any]``.\n   This restriction was removed in mypy 0.620.\n\n   Mypy also previously used to select the best matching variant using a different\n   algorithm. If this algorithm failed to find a match, it would default to returning\n   ``Any``. The new algorithm uses the \"pick the first match\" rule and will fall back\n   to returning ``Any`` only if the input arguments also contain ``Any``.\n\n\nConditional overloads\n---------------------\n\nSometimes it is useful to define overloads conditionally.\nCommon use cases include types that are unavailable at runtime or that\nonly exist in a certain Python version. All existing overload rules still apply.\nFor example, there must be at least two overloads.\n\n.. note::\n\n    Mypy can only infer a limited number of conditions.\n    Supported ones currently include :py:data:`~typing.TYPE_CHECKING`, ``MYPY``,\n    :ref:`version_and_platform_checks`, :option:`--always-true <mypy --always-true>`,\n    and :option:`--always-false <mypy --always-false>` values.\n\n.. code-block:: python\n\n    from typing import TYPE_CHECKING, Any, overload\n\n    if TYPE_CHECKING:\n        class A: ...\n        class B: ...\n\n\n    if TYPE_CHECKING:\n        @overload\n        def func(var: A) -> A: ...\n\n        @overload\n        def func(var: B) -> B: ...\n\n    def func(var: Any) -> Any:\n        return var\n\n\n    reveal_type(func(A()))  # Revealed type is \"A\"\n\n.. code-block:: python\n\n    # flags: --python-version 3.10\n    import sys\n    from typing import Any, overload\n\n    class A: ...\n    class B: ...\n    class C: ...\n    class D: ...\n\n\n    if sys.version_info < (3, 7):\n        @overload\n        def func(var: A) -> A: ...\n\n    elif sys.version_info >= (3, 10):\n        @overload\n        def func(var: B) -> B: ...\n\n    else:\n        @overload\n        def func(var: C) -> C: ...\n\n    @overload\n    def func(var: D) -> D: ...\n\n    def func(var: Any) -> Any:\n        return var\n\n\n    reveal_type(func(B()))  # Revealed type is \"B\"\n    reveal_type(func(C()))  # No overload variant of \"func\" matches argument type \"C\"\n        # Possible overload variants:\n        #     def func(var: B) -> B\n        #     def func(var: D) -> D\n        # Revealed type is \"Any\"\n\n\n.. note::\n\n    In the last example, mypy is executed with\n    :option:`--python-version 3.10 <mypy --python-version>`.\n    Therefore, the condition ``sys.version_info >= (3, 10)`` will match and\n    the overload for ``B`` will be added.\n    The overloads for ``A`` and ``C`` are ignored!\n    The overload for ``D`` is not defined conditionally and thus is also added.\n\nWhen mypy cannot infer a condition to be always ``True`` or always ``False``,\nan error is emitted.\n\n.. code-block:: python\n\n    from typing import Any, overload\n\n    class A: ...\n    class B: ...\n\n\n    def g(bool_var: bool) -> None:\n        if bool_var:  # Condition can't be inferred, unable to merge overloads\n            @overload\n            def func(var: A) -> A: ...\n\n            @overload\n            def func(var: B) -> B: ...\n\n        def func(var: Any) -> Any: ...\n\n        reveal_type(func(A()))  # Revealed type is \"Any\"\n\n\n.. _advanced_self:\n\nAdvanced uses of self-types\n***************************\n\nNormally, mypy doesn't require annotations for the first arguments of instance and\nclass methods. However, they may be needed to have more precise static typing\nfor certain programming patterns.\n\nRestricted methods in generic classes\n-------------------------------------\n\nIn generic classes some methods may be allowed to be called only\nfor certain values of type arguments (Python 3.12 syntax):\n\n.. code-block:: python\n\n   class Tag[T]:\n       item: T\n\n       def uppercase_item(self: Tag[str]) -> str:\n           return self.item.upper()\n\n   def label(ti: Tag[int], ts: Tag[str]) -> None:\n       ti.uppercase_item()  # E: Invalid self argument \"Tag[int]\" to attribute function\n                            # \"uppercase_item\" with type \"Callable[[Tag[str]], str]\"\n       ts.uppercase_item()  # This is OK\n\nThis pattern also allows matching on nested types in situations where the type\nargument is itself generic (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from collections.abc import Sequence\n\n   class Storage[T]:\n       def __init__(self, content: T) -> None:\n           self._content = content\n\n       def first_chunk[S](self: Storage[Sequence[S]]) -> S:\n           return self._content[0]\n\n   page: Storage[list[str]]\n   page.first_chunk()  # OK, type is \"str\"\n\n   Storage(0).first_chunk()  # Error: Invalid self argument \"Storage[int]\" to attribute function\n                             # \"first_chunk\" with type \"Callable[[Storage[Sequence[S]]], S]\"\n\nFinally, one can use overloads on self-type to express precise types of\nsome tricky methods (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from collections.abc import Callable\n   from typing import overload\n\n   class Tag[T]:\n       @overload\n       def export(self: Tag[str]) -> str: ...\n       @overload\n       def export(self, converter: Callable[[T], str]) -> str: ...\n\n       def export(self, converter=None):\n           if isinstance(self.item, str):\n               return self.item\n           return converter(self.item)\n\nIn particular, an :py:meth:`~object.__init__` method overloaded on self-type\nmay be useful to annotate generic class constructors where type arguments\ndepend on constructor parameters in a non-trivial way, see e.g. :py:class:`~subprocess.Popen`.\n\nMixin classes\n-------------\n\nUsing host class protocol as a self-type in mixin methods allows\nmore code re-usability for static typing of mixin classes. For example,\none can define a protocol that defines common functionality for\nhost classes instead of adding required abstract methods to every mixin:\n\n.. code-block:: python\n\n   class Lockable(Protocol):\n       @property\n       def lock(self) -> Lock: ...\n\n   class AtomicCloseMixin:\n       def atomic_close(self: Lockable) -> int:\n           with self.lock:\n               # perform actions\n\n   class AtomicOpenMixin:\n       def atomic_open(self: Lockable) -> int:\n           with self.lock:\n               # perform actions\n\n   class File(AtomicCloseMixin, AtomicOpenMixin):\n       def __init__(self) -> None:\n           self.lock = Lock()\n\n   class Bad(AtomicCloseMixin):\n       pass\n\n   f = File()\n   b: Bad\n   f.atomic_close()  # OK\n   b.atomic_close()  # Error: Invalid self type for \"atomic_close\"\n\nNote that the explicit self-type is *required* to be a protocol whenever it\nis not a supertype of the current class. In this case mypy will check the validity\nof the self-type only at the call site.\n\nPrecise typing of alternative constructors\n------------------------------------------\n\nSome classes may define alternative constructors. If these\nclasses are generic, self-type allows giving them precise\nsignatures (Python 3.12 syntax):\n\n.. code-block:: python\n\n   from typing import Self\n\n   class Base[T]:\n       def __init__(self, item: T) -> None:\n           self.item = item\n\n       @classmethod\n       def make_pair(cls, item: T) -> tuple[Self, Self]:\n           return cls(item), cls(item)\n\n   class Sub[T](Base[T]):\n       ...\n\n   pair = Sub.make_pair('yes')  # Type is \"tuple[Sub[str], Sub[str]]\"\n   bad = Sub[int].make_pair('no')  # Error: Argument 1 to \"make_pair\" of \"Base\"\n                                   # has incompatible type \"str\"; expected \"int\"\n\n.. _async-and-await:\n\nTyping async/await\n******************\n\nMypy lets you type coroutines that use the ``async/await`` syntax.\nFor more information regarding coroutines, see :pep:`492` and the\n`asyncio documentation <python:library/asyncio>`_.\n\nFunctions defined using ``async def`` are typed similar to normal functions.\nThe return type annotation should be the same as the type of the value you\nexpect to get back when ``await``-ing the coroutine.\n\n.. code-block:: python\n\n   import asyncio\n\n   async def format_string(tag: str, count: int) -> str:\n       return f'T-minus {count} ({tag})'\n\n   async def countdown(tag: str, count: int) -> str:\n       while count > 0:\n           my_str = await format_string(tag, count)  # type is inferred to be str\n           print(my_str)\n           await asyncio.sleep(0.1)\n           count -= 1\n       return \"Blastoff!\"\n\n   asyncio.run(countdown(\"Millennium Falcon\", 5))\n\nThe result of calling an ``async def`` function *without awaiting* will\nautomatically be inferred to be a value of type\n:py:class:`Coroutine[Any, Any, T] <collections.abc.Coroutine>`, which is a subtype of\n:py:class:`Awaitable[T] <collections.abc.Awaitable>`:\n\n.. code-block:: python\n\n   my_coroutine = countdown(\"Millennium Falcon\", 5)\n   reveal_type(my_coroutine)  # Revealed type is \"typing.Coroutine[Any, Any, builtins.str]\"\n\n.. _async-iterators:\n\nAsynchronous iterators\n----------------------\n\nIf you have an asynchronous iterator, you can use the\n:py:class:`~collections.abc.AsyncIterator` type in your annotations:\n\n.. code-block:: python\n\n   from collections.abc import AsyncIterator\n   from typing import Optional\n   import asyncio\n\n   class arange:\n       def __init__(self, start: int, stop: int, step: int) -> None:\n           self.start = start\n           self.stop = stop\n           self.step = step\n           self.count = start - step\n\n       def __aiter__(self) -> AsyncIterator[int]:\n           return self\n\n       async def __anext__(self) -> int:\n           self.count += self.step\n           if self.count == self.stop:\n               raise StopAsyncIteration\n           else:\n               return self.count\n\n   async def run_countdown(tag: str, countdown: AsyncIterator[int]) -> str:\n       async for i in countdown:\n           print(f'T-minus {i} ({tag})')\n           await asyncio.sleep(0.1)\n       return \"Blastoff!\"\n\n   asyncio.run(run_countdown(\"Serenity\", arange(5, 0, -1)))\n\nAsync generators (introduced in :pep:`525`) are an easy way to create\nasync iterators:\n\n.. code-block:: python\n\n   from collections.abc import AsyncGenerator\n   from typing import Optional\n   import asyncio\n\n   # Could also type this as returning AsyncIterator[int]\n   async def arange(start: int, stop: int, step: int) -> AsyncGenerator[int, None]:\n       current = start\n       while (step > 0 and current < stop) or (step < 0 and current > stop):\n           yield current\n           current += step\n\n   asyncio.run(run_countdown(\"Battlestar Galactica\", arange(5, 0, -1)))\n\nOne common confusion is that the presence of a ``yield`` statement in an\n``async def`` function has an effect on the type of the function:\n\n.. code-block:: python\n\n   from collections.abc import AsyncIterator\n\n   async def arange(stop: int) -> AsyncIterator[int]:\n       # When called, arange gives you an async iterator\n       # Equivalent to Callable[[int], AsyncIterator[int]]\n       i = 0\n       while i < stop:\n           yield i\n           i += 1\n\n   async def coroutine(stop: int) -> AsyncIterator[int]:\n       # When called, coroutine gives you something you can await to get an async iterator\n       # Equivalent to Callable[[int], Coroutine[Any, Any, AsyncIterator[int]]]\n       return arange(stop)\n\n   async def main() -> None:\n       reveal_type(arange(5))  # Revealed type is \"typing.AsyncIterator[builtins.int]\"\n       reveal_type(coroutine(5))  # Revealed type is \"typing.Coroutine[Any, Any, typing.AsyncIterator[builtins.int]]\"\n\n       await arange(5)  # Error: Incompatible types in \"await\" (actual type \"AsyncIterator[int]\", expected type \"Awaitable[Any]\")\n       reveal_type(await coroutine(5))  # Revealed type is \"typing.AsyncIterator[builtins.int]\"\n\nThis can sometimes come up when trying to define base classes, Protocols or overloads:\n\n.. code-block:: python\n\n    from collections.abc import AsyncIterator\n    from typing import Protocol, overload\n\n    class LauncherIncorrect(Protocol):\n        # Because launch does not have yield, this has type\n        # Callable[[], Coroutine[Any, Any, AsyncIterator[int]]]\n        # instead of\n        # Callable[[], AsyncIterator[int]]\n        async def launch(self) -> AsyncIterator[int]:\n            raise NotImplementedError\n\n    class LauncherCorrect(Protocol):\n        def launch(self) -> AsyncIterator[int]:\n            raise NotImplementedError\n\n    class LauncherAlsoCorrect(Protocol):\n        async def launch(self) -> AsyncIterator[int]:\n            raise NotImplementedError\n            if False:\n                yield 0\n\n    # The type of the overloads is independent of the implementation.\n    # In particular, their type is not affected by whether or not the\n    # implementation contains a `yield`.\n    # Use of `def`` makes it clear the type is Callable[..., AsyncIterator[int]],\n    # whereas with `async def` it would be Callable[..., Coroutine[Any, Any, AsyncIterator[int]]]\n    @overload\n    def launch(*, count: int = ...) -> AsyncIterator[int]: ...\n    @overload\n    def launch(*, time: float = ...) -> AsyncIterator[int]: ...\n\n    async def launch(*, count: int = 0, time: float = 0) -> AsyncIterator[int]:\n        # The implementation of launch is an async generator and contains a yield\n        yield 0\n"
  },
  {
    "path": "docs/source/mypy_daemon.rst",
    "content": ".. _mypy_daemon:\n\n.. program:: dmypy\n\nMypy daemon (mypy server)\n=========================\n\nInstead of running mypy as a command-line tool, you can also run it as\na long-running daemon (server) process and use a command-line client to\nsend type-checking requests to the server.  This way mypy can perform type\nchecking much faster, since program state cached from previous runs is kept\nin memory and doesn't have to be read from the file system on each run.\nThe server also uses finer-grained dependency tracking to reduce the amount\nof work that needs to be done.\n\nIf you have a large codebase to check, running mypy using the mypy\ndaemon can be *10 or more times faster* than the regular command-line\n``mypy`` tool, especially if your workflow involves running mypy\nrepeatedly after small edits -- which is often a good idea, as this way\nyou'll find errors sooner.\n\n.. note::\n\n    The command-line interface of mypy daemon may change in future mypy\n    releases.\n\n.. note::\n\n    Each mypy daemon process supports one user and one set of source files,\n    and it can only process one type checking request at a time. You can\n    run multiple mypy daemon processes to type check multiple repositories.\n\n\nBasic usage\n***********\n\nThe client utility ``dmypy`` is used to control the mypy daemon.\nUse ``dmypy run -- <flags> <files>`` to type check a set of files\n(or directories). This will launch the daemon if it is not running.\nYou can use almost arbitrary mypy flags after ``--``.  The daemon\nwill always run on the current host. Example::\n\n    dmypy run -- prog.py pkg/*.py\n\n``dmypy run`` will automatically restart the daemon if the\nconfiguration or mypy version changes.\n\nThe initial run will process all the code and may take a while to\nfinish, but subsequent runs will be quick, especially if you've only\nchanged a few files. (You can use :ref:`remote caching <remote-cache>`\nto speed up the initial run. The speedup can be significant if\nyou have a large codebase.)\n\n.. note::\n\n   Mypy 0.780 added support for following imports in dmypy (enabled by\n   default). This functionality is still experimental. You can use\n   ``--follow-imports=skip`` or ``--follow-imports=error`` to fall\n   back to the stable functionality.  See :ref:`follow-imports` for\n   details on how these work.\n\n.. note::\n\n    The mypy daemon requires ``--local-partial-types`` and automatically enables it.\n\n\nDaemon client commands\n**********************\n\nWhile ``dmypy run`` is sufficient for most uses, some workflows\n(ones using :ref:`remote caching <remote-cache>`, perhaps),\nrequire more precise control over the lifetime of the daemon process:\n\n* ``dmypy stop`` stops the daemon.\n\n* ``dmypy start -- <flags>`` starts the daemon but does not check any files.\n  You can use almost arbitrary mypy flags after ``--``.\n\n* ``dmypy restart -- <flags>`` restarts the daemon. The flags are the same\n  as with ``dmypy start``. This is equivalent to a stop command followed\n  by a start.\n\n* Use ``dmypy run --timeout SECONDS -- <flags>`` (or\n  ``start`` or ``restart``) to automatically\n  shut down the daemon after inactivity. By default, the daemon runs\n  until it's explicitly stopped.\n\n* ``dmypy check <files>`` checks a set of files using an already\n  running daemon.\n\n* ``dmypy recheck`` checks the same set of files as the most recent\n  ``check`` or ``recheck`` command. (You can also use the :option:`--update`\n  and :option:`--remove` options to alter the set of files, and to define\n  which files should be processed.)\n\n* ``dmypy status`` checks whether a daemon is running. It prints a\n  diagnostic and exits with ``0`` if there is a running daemon.\n\nUse ``dmypy --help`` for help on additional commands and command-line\noptions not discussed here, and ``dmypy <command> --help`` for help on\ncommand-specific options.\n\nAdditional daemon flags\n***********************\n\n.. option:: --status-file FILE\n\n   Use ``FILE`` as the status file for storing daemon runtime state. This is\n   normally a JSON file that contains information about daemon process and\n   connection. The default path is ``.dmypy.json`` in the current working\n   directory.\n\n.. option:: --log-file FILE\n\n   Direct daemon stdout/stderr to ``FILE``. This is useful for debugging daemon\n   crashes, since the server traceback is not always printed by the client.\n   This is available for the ``start``, ``restart``, and ``run`` commands.\n\n.. option:: --timeout TIMEOUT\n\n   Automatically shut down server after ``TIMEOUT`` seconds of inactivity.\n   This is available for the ``start``, ``restart``, and ``run`` commands.\n\n.. option:: --update FILE\n\n   Re-check ``FILE``, or add it to the set of files being\n   checked (and check it). This option may be repeated, and it's only available for\n   the ``recheck`` command.  By default, mypy finds and checks all files changed\n   since the previous run and files that depend on them.  However, if you use this option\n   (and/or :option:`--remove`), mypy assumes that only the explicitly\n   specified files have changed. This is only useful to\n   speed up mypy if you type check a very large number of files, and use an\n   external, fast file system watcher, such as `watchman`_ or\n   `watchdog`_, to determine which files got edited or deleted.\n   *Note:* This option is never required and is only available for\n   performance tuning.\n\n.. option:: --remove FILE\n\n   Remove ``FILE`` from the set of files being checked. This option may be\n   repeated. This is only available for the\n   ``recheck`` command. See :option:`--update` above for when this may be useful.\n   *Note:* This option is never required and is only available for performance\n   tuning.\n\n.. option:: --fswatcher-dump-file FILE\n\n   Collect information about the current internal file state. This is\n   only available for the ``status`` command. This will dump JSON to\n   ``FILE`` in the format ``{path: [modification_time, size,\n   content_hash]}``. This is useful for debugging the built-in file\n   system watcher. *Note:* This is an internal flag and the format may\n   change.\n\n.. option:: --perf-stats-file FILE\n\n   Write performance profiling information to ``FILE``. This is only available\n   for the ``check``, ``recheck``, and ``run`` commands.\n\n.. option:: --export-types\n\n   Store all expression types in memory for future use. This is useful to speed\n   up future calls to ``dmypy inspect`` (but uses more memory). Only valid for\n   ``check``, ``recheck``, and ``run`` command.\n\nStatic inference of annotations\n*******************************\n\nThe mypy daemon supports (as an experimental feature) statically inferring\ndraft function and method type annotations. Use ``dmypy suggest FUNCTION`` to\ngenerate a draft signature in the format\n``(param_type_1, param_type_2, ...) -> ret_type`` (types are included for all\narguments, including keyword-only arguments, ``*args`` and ``**kwargs``).\n\nThis is a low-level feature intended to be used by editor integrations,\nIDEs, and other tools (for example, the `mypy plugin for PyCharm`_),\nto automatically add annotations to source files, or to propose function\nsignatures.\n\nIn this example, the function ``format_id()`` has no annotation:\n\n.. code-block:: python\n\n   def format_id(user):\n       return f\"User: {user}\"\n\n   root = format_id(0)\n\n``dmypy suggest`` uses call sites, return statements, and other heuristics (such as\nlooking for signatures in base classes) to infer that ``format_id()`` accepts\nan ``int`` argument and returns a ``str``. Use ``dmypy suggest module.format_id`` to\nprint the suggested signature for the function.\n\nMore generally, the target function may be specified in two ways:\n\n* By its fully qualified name, i.e. ``[package.]module.[class.]function``.\n\n* By its location in a source file, i.e. ``/path/to/file.py:line``. The path can be\n  absolute or relative, and ``line`` can refer to any line number within\n  the function body.\n\nThis command can also be used to find a more precise alternative for an existing,\nimprecise annotation with some ``Any`` types.\n\nThe following flags customize various aspects of the ``dmypy suggest``\ncommand.\n\n.. option:: --json\n\n   Output the signature as JSON, so that `PyAnnotate`_ can read it and add\n   the signature to the source file. Here is what the JSON looks like:\n\n   .. code-block:: python\n\n      [{\"func_name\": \"example.format_id\",\n        \"line\": 1,\n        \"path\": \"/absolute/path/to/example.py\",\n        \"samples\": 0,\n        \"signature\": {\"arg_types\": [\"int\"], \"return_type\": \"str\"}}]\n\n.. option:: --no-errors\n\n   Only produce suggestions that cause no errors in the checked code. By default,\n   mypy will try to find the most precise type, even if it causes some type errors.\n\n.. option:: --no-any\n\n   Only produce suggestions that don't contain ``Any`` types. By default mypy\n   proposes the most precise signature found, even if it contains ``Any`` types.\n\n.. option:: --flex-any FRACTION\n\n   Only allow some fraction of types in the suggested signature to be ``Any`` types.\n   The fraction ranges from ``0`` (same as ``--no-any``) to ``1``.\n\n.. option:: --callsites\n\n   Only find call sites for a given function instead of suggesting a type.\n   This will produce a list with line numbers and types of actual\n   arguments for each call: ``/path/to/file.py:line: (arg_type_1, arg_type_2, ...)``.\n\n.. option:: --use-fixme NAME\n\n   Use a dummy name instead of plain ``Any`` for types that cannot\n   be inferred. This may be useful to emphasize to a user that a given type\n   couldn't be inferred and needs to be entered manually.\n\n.. option:: --max-guesses NUMBER\n\n   Set the maximum number of types to try for a function (default: ``64``).\n\nStatically inspect expressions\n******************************\n\nThe daemon allows one to get the declared or inferred type of an expression (or other\ninformation about an expression, such as known attributes or definition location)\nusing the ``dmypy inspect LOCATION`` command. The location of the expression should be\nspecified in the format ``path/to/file.py:line:column[:end_line:end_column]``.\nBoth line and column are 1-based. Both start and end position are inclusive.\nThese rules match how mypy prints the error location in error messages.\n\nIf a span is given (i.e. all 4 numbers), then only an exactly matching expression\nis inspected. If only a position is given (i.e. 2 numbers, line and column), mypy\nwill inspect all expressions that include this position, starting from the\ninnermost one.\n\nConsider this Python code snippet:\n\n.. code-block:: python\n\n   def foo(x: int, longer_name: str) -> None:\n       x\n       longer_name\n\nHere to find the type of ``x`` one needs to call ``dmypy inspect src.py:2:5:2:5``\nor ``dmypy inspect src.py:2:5``. While for ``longer_name`` one needs to call\n``dmypy inspect src.py:3:5:3:15`` or, for example, ``dmypy inspect src.py:3:10``.\nPlease note that this command is only valid after daemon had a successful type\ncheck (without parse errors), so that types are populated, e.g. using\n``dmypy check``. In case where multiple expressions match the provided location,\ntheir types are returned separated by a newline.\n\nImportant note: it is recommended to check files with :option:`--export-types`\nsince otherwise most inspections will not work without :option:`--force-reload`.\n\n.. option:: --show INSPECTION\n\n   What kind of inspection to run for expression(s) found. Currently the supported\n   inspections are:\n\n   * ``type`` (default): Show the best known type of a given expression.\n   * ``attrs``: Show which attributes are valid for an expression (e.g. for\n     auto-completion). Format is ``{\"Base1\": [\"name_1\", \"name_2\", ...]; \"Base2\": ...}``.\n     Names are sorted by method resolution order. If expression refers to a module,\n     then module attributes will be under key like ``\"<full.module.name>\"``.\n   * ``definition`` (experimental): Show the definition location for a name\n     expression or member expression. Format is ``path/to/file.py:line:column:Symbol``.\n     If multiple definitions are found (e.g. for a Union attribute), they are\n     separated by comma.\n\n.. option:: --verbose\n\n   Increase verbosity of types string representation (can be repeated).\n   For example, this will print fully qualified names of instance types (like\n   ``\"builtins.str\"``), instead of just a short name (like ``\"str\"``).\n\n.. option:: --limit NUM\n\n   If the location is given as ``line:column``, this will cause daemon to\n   return only at most ``NUM`` inspections of innermost expressions.\n   Value of 0 means no limit (this is the default). For example, if one calls\n   ``dmypy inspect src.py:4:10 --limit=1`` with this code\n\n   .. code-block:: python\n\n      def foo(x: int) -> str: ..\n      def bar(x: str) -> None: ...\n      baz: int\n      bar(foo(baz))\n\n   This will output just one type ``\"int\"`` (for ``baz`` name expression).\n   While without the limit option, it would output all three types: ``\"int\"``,\n   ``\"str\"``, and ``\"None\"``.\n\n.. option:: --include-span\n\n   With this option on, the daemon will prepend each inspection result with\n   the full span of corresponding expression, formatted as ``1:2:1:4 -> \"int\"``.\n   This may be useful in case multiple expressions match a location.\n\n.. option:: --include-kind\n\n   With this option on, the daemon will prepend each inspection result with\n   the kind of corresponding expression, formatted as ``NameExpr -> \"int\"``.\n   If both this option and :option:`--include-span` are on, the kind will\n   appear first, for example ``NameExpr:1:2:1:4 -> \"int\"``.\n\n.. option:: --include-object-attrs\n\n   This will make the daemon include attributes of ``object`` (excluded by\n   default) in case of an ``atts`` inspection.\n\n.. option:: --union-attrs\n\n   Include attributes valid for some of possible expression types (by default\n   an intersection is returned). This is useful for union types of type variables\n   with values. For example, with this code:\n\n   .. code-block:: python\n\n      from typing import Union\n\n      class A:\n          x: int\n          z: int\n      class B:\n          y: int\n          z: int\n      var: Union[A, B]\n      var\n\n   The command ``dmypy inspect --show attrs src.py:10:1`` will return\n   ``{\"A\": [\"z\"], \"B\": [\"z\"]}``, while with ``--union-attrs`` it will return\n   ``{\"A\": [\"x\", \"z\"], \"B\": [\"y\", \"z\"]}``.\n\n.. option:: --force-reload\n\n   Force re-parsing and re-type-checking file before inspection. By default\n   this is done only when needed (for example file was not loaded from cache\n   or daemon was initially run without ``--export-types`` mypy option),\n   since reloading may be slow (up to few seconds for very large files).\n\n.. TODO: Add similar section about find usages when added, and then move\n   this to a separate file.\n\n\n.. _watchman: https://facebook.github.io/watchman/\n.. _watchdog: https://pypi.org/project/watchdog/\n.. _PyAnnotate: https://github.com/dropbox/pyannotate\n.. _mypy plugin for PyCharm: https://github.com/dropbox/mypy-PyCharm-plugin\n"
  },
  {
    "path": "docs/source/protocols.rst",
    "content": ".. _protocol-types:\n\nProtocols and structural subtyping\n==================================\n\nThe Python type system supports two ways of deciding whether two objects are\ncompatible as types: nominal subtyping and structural subtyping.\n\n*Nominal* subtyping is strictly based on the class hierarchy. If class ``Dog``\ninherits class ``Animal``, it's a subtype of ``Animal``. Instances of ``Dog``\ncan be used when ``Animal`` instances are expected. This form of subtyping\nis what Python's type system predominantly uses: it's easy to\nunderstand and produces clear and concise error messages, and matches how the\nnative :py:func:`isinstance <isinstance>` check works -- based on class\nhierarchy.\n\n*Structural* subtyping is based on the operations that can be performed with an\nobject. Class ``Dog`` is a structural subtype of class ``Animal`` if the former\nhas all attributes and methods of the latter, and with compatible types.\n\nStructural subtyping can be seen as a static equivalent of duck typing, which is\nwell known to Python programmers. See :pep:`544` for the detailed specification\nof protocols and structural subtyping in Python.\n\n.. _predefined_protocols:\n\nPredefined protocols\n********************\n\nThe :py:mod:`collections.abc`, :py:mod:`typing` and other stdlib modules define\nvarious protocol classes that correspond to common Python protocols, such as\n:py:class:`Iterable[T] <collections.abc.Iterable>`. If a class\ndefines a suitable :py:meth:`__iter__ <object.__iter__>` method, mypy understands that it\nimplements the iterable protocol and is compatible with :py:class:`Iterable[T] <collections.abc.Iterable>`.\nFor example, ``IntList`` below is iterable, over ``int`` values:\n\n.. code-block:: python\n\n   from __future__ import annotations\n\n   from collections.abc import Iterator, Iterable\n\n   class IntList:\n       def __init__(self, value: int, next: IntList | None) -> None:\n           self.value = value\n           self.next = next\n\n       def __iter__(self) -> Iterator[int]:\n           current = self\n           while current:\n               yield current.value\n               current = current.next\n\n   def print_numbered(items: Iterable[int]) -> None:\n       for n, x in enumerate(items):\n           print(n + 1, x)\n\n   x = IntList(3, IntList(5, None))\n   print_numbered(x)  # OK\n   print_numbered([4, 5])  # Also OK\n\n:ref:`predefined_protocols_reference` lists various protocols defined in\n:py:mod:`collections.abc` and :py:mod:`typing` and the signatures of the corresponding methods\nyou need to define to implement each protocol.\n\n.. note::\n    ``typing`` also contains deprecated aliases to protocols and ABCs defined in\n    :py:mod:`collections.abc`, such as :py:class:`Iterable[T] <typing.Iterable>`.\n    These are only necessary in Python 3.8 and earlier, since the protocols in\n    ``collections.abc`` didn't yet support subscripting (``[]``) in Python 3.8,\n    but the aliases in ``typing`` have always supported\n    subscripting. In Python 3.9 and later, the aliases in ``typing`` don't provide\n    any extra functionality.\n\nSimple user-defined protocols\n*****************************\n\nYou can define your own protocol class by inheriting the special ``Protocol``\nclass:\n\n.. code-block:: python\n\n   from collections.abc import Iterable\n   from typing import Protocol\n\n   class SupportsClose(Protocol):\n       # Empty method body (explicit '...')\n       def close(self) -> None: ...\n\n   class Resource:  # No SupportsClose base class!\n\n       def close(self) -> None:\n          self.resource.release()\n\n       # ... other methods ...\n\n   def close_all(items: Iterable[SupportsClose]) -> None:\n       for item in items:\n           item.close()\n\n   close_all([Resource(), open('some/file')])  # OK\n\n``Resource`` is a subtype of the ``SupportsClose`` protocol since it defines\na compatible ``close`` method. Regular file objects returned by :py:func:`open` are\nsimilarly compatible with the protocol, as they support ``close()``.\n\nDefining subprotocols and subclassing protocols\n***********************************************\n\nYou can also define subprotocols. Existing protocols can be extended\nand merged using multiple inheritance. Example:\n\n.. code-block:: python\n\n   # ... continuing from the previous example\n\n   class SupportsRead(Protocol):\n       def read(self, amount: int) -> bytes: ...\n\n   class TaggedReadableResource(SupportsClose, SupportsRead, Protocol):\n       label: str\n\n   class AdvancedResource(Resource):\n       def __init__(self, label: str) -> None:\n           self.label = label\n\n       def read(self, amount: int) -> bytes:\n           # some implementation\n           ...\n\n   resource: TaggedReadableResource\n   resource = AdvancedResource('handle with care')  # OK\n\nNote that inheriting from an existing protocol does not automatically\nturn the subclass into a protocol -- it just creates a regular\n(non-protocol) class or ABC that implements the given protocol (or\nprotocols). The ``Protocol`` base class must always be explicitly\npresent if you are defining a protocol:\n\n.. code-block:: python\n\n   class NotAProtocol(SupportsClose):  # This is NOT a protocol\n       new_attr: int\n\n   class Concrete:\n      new_attr: int = 0\n\n      def close(self) -> None:\n          ...\n\n   # Error: nominal subtyping used by default\n   x: NotAProtocol = Concrete()  # Error!\n\nYou can also include default implementations of methods in\nprotocols. If you explicitly subclass these protocols you can inherit\nthese default implementations.\n\nExplicitly including a protocol as a\nbase class is also a way of documenting that your class implements a\nparticular protocol, and it forces mypy to verify that your class\nimplementation is actually compatible with the protocol. In particular,\nomitting a value for an attribute or a method body will make it implicitly\nabstract:\n\n.. code-block:: python\n\n   class SomeProto(Protocol):\n       attr: int  # Note, no right hand side\n       def method(self) -> str: ...  # Literally just ... here\n\n   class ExplicitSubclass(SomeProto):\n       pass\n\n   ExplicitSubclass()  # error: Cannot instantiate abstract class 'ExplicitSubclass'\n                       # with abstract attributes 'attr' and 'method'\n\nSimilarly, explicitly assigning to a protocol instance can be a way to ask the\ntype checker to verify that your class implements a protocol:\n\n.. code-block:: python\n\n   _proto: SomeProto = cast(ExplicitSubclass, None)\n\nInvariance of protocol attributes\n*********************************\n\nA common issue with protocols is that protocol attributes are invariant.\nFor example:\n\n.. code-block:: python\n\n   class Box(Protocol):\n         content: object\n\n   class IntBox:\n         content: int\n\n   def takes_box(box: Box) -> None: ...\n\n   takes_box(IntBox())  # error: Argument 1 to \"takes_box\" has incompatible type \"IntBox\"; expected \"Box\"\n                        # note:  Following member(s) of \"IntBox\" have conflicts:\n                        # note:      content: expected \"object\", got \"int\"\n\nThis is because ``Box`` defines ``content`` as a mutable attribute.\nHere's why this is problematic:\n\n.. code-block:: python\n\n   def takes_box_evil(box: Box) -> None:\n       box.content = \"asdf\"  # This is bad, since box.content is supposed to be an object\n\n   my_int_box = IntBox()\n   takes_box_evil(my_int_box)\n   my_int_box.content + 1  # Oops, TypeError!\n\nThis can be fixed by declaring ``content`` to be read-only in the ``Box``\nprotocol using ``@property``:\n\n.. code-block:: python\n\n   class Box(Protocol):\n       @property\n       def content(self) -> object: ...\n\n   class IntBox:\n       content: int\n\n   def takes_box(box: Box) -> None: ...\n\n   takes_box(IntBox(42))  # OK\n\nRecursive protocols\n*******************\n\nProtocols can be recursive (self-referential) and mutually\nrecursive. This is useful for declaring abstract recursive collections\nsuch as trees and linked lists:\n\n.. code-block:: python\n\n   from __future__ import annotations\n\n   from typing import Protocol\n\n   class TreeLike(Protocol):\n       value: int\n\n       @property\n       def left(self) -> TreeLike | None: ...\n\n       @property\n       def right(self) -> TreeLike | None: ...\n\n   class SimpleTree:\n       def __init__(self, value: int) -> None:\n           self.value = value\n           self.left: SimpleTree | None = None\n           self.right: SimpleTree | None = None\n\n   root: TreeLike = SimpleTree(0)  # OK\n\nUsing isinstance() with protocols\n*********************************\n\nYou can use a protocol class with :py:func:`isinstance` if you decorate it\nwith the ``@runtime_checkable`` class decorator. The decorator adds\nrudimentary support for runtime structural checks:\n\n.. code-block:: python\n\n   from typing import Protocol, runtime_checkable\n\n   @runtime_checkable\n   class Portable(Protocol):\n       handles: int\n\n   class Mug:\n       def __init__(self) -> None:\n           self.handles = 1\n\n   def use(handles: int) -> None: ...\n\n   mug = Mug()\n   if isinstance(mug, Portable):  # Works at runtime!\n      use(mug.handles)\n\n:py:func:`isinstance` also works with the :ref:`predefined protocols <predefined_protocols>`\nin :py:mod:`typing` such as :py:class:`~typing.Iterable`.\n\n.. warning::\n   :py:func:`isinstance` with protocols is not completely safe at runtime.\n   For example, signatures of methods are not checked. The runtime\n   implementation only checks that all protocol members exist,\n   not that they have the correct type. :py:func:`issubclass` with protocols\n   will only check for the existence of methods.\n\n.. note::\n   :py:func:`isinstance` with protocols can also be surprisingly slow.\n   In many cases, you're better served by using :py:func:`hasattr` to\n   check for the presence of attributes.\n\n.. _callback_protocols:\n\nCallback protocols\n******************\n\nProtocols can be used to define flexible callback types that are hard\n(or even impossible) to express using the\n:py:class:`Callable[...] <collections.abc.Callable>` syntax,\nsuch as variadic, overloaded, and complex generic callbacks. They are defined with a\nspecial :py:meth:`__call__ <object.__call__>` member:\n\n.. code-block:: python\n\n   from collections.abc import Iterable\n   from typing import Optional, Protocol\n\n   class Combiner(Protocol):\n       def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...\n\n   def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:\n       for item in data:\n           ...\n\n   def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:\n       ...\n   def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:\n       ...\n\n   batch_proc([], good_cb)  # OK\n   batch_proc([], bad_cb)   # Error! Argument 2 has incompatible type because of\n                            # different name and kind in the callback\n\nCallback protocols and :py:class:`~collections.abc.Callable` types can be used mostly interchangeably.\nParameter names in :py:meth:`__call__ <object.__call__>` methods must be identical, unless\nthe parameters are positional-only. Example (using the legacy syntax for generic functions):\n\n.. code-block:: python\n\n   from collections.abc import Callable\n   from typing import Protocol, TypeVar\n\n   T = TypeVar('T')\n\n   class Copy(Protocol):\n       # '/' marks the end of positional-only parameters\n       def __call__(self, origin: T, /) -> T: ...\n\n   copy_a: Callable[[T], T]\n   copy_b: Copy\n\n   copy_a = copy_b  # OK\n   copy_b = copy_a  # Also OK\n\nBinding of types in protocol attributes\n***************************************\n\nAll protocol attributes annotations are treated as externally visible types\nof those attributes. This means that for example callables are not bound,\nand descriptors are not invoked:\n\n.. code-block:: python\n\n   from typing import Callable, Protocol, overload\n\n   class Integer:\n       @overload\n       def __get__(self, instance: None, owner: object) -> Integer: ...\n       @overload\n       def __get__(self, instance: object, owner: object) -> int: ...\n       # <some implementation>\n\n   class Example(Protocol):\n       foo: Callable[[object], int]\n       bar: Integer\n\n   ex: Example\n   reveal_type(ex.foo)  # Revealed type is Callable[[object], int]\n   reveal_type(ex.bar)  # Revealed type is Integer\n\nIn other words, protocol attribute types are handled as they would appear in a\n``self`` attribute annotation in a regular class. If you want some protocol\nattributes to be handled as though they were defined at class level, you should\ndeclare them explicitly using ``ClassVar[...]``. Continuing previous example:\n\n.. code-block:: python\n\n   from typing import ClassVar\n\n   class OtherExample(Protocol):\n       # This style is *not recommended*, but may be needed to reuse\n       # some complex callable types. Otherwise use regular methods.\n       foo: ClassVar[Callable[[object], int]]\n       # This may be needed to mimic descriptor access on Type[...] types,\n       # otherwise use a plain \"bar: int\" style.\n       bar: ClassVar[Integer]\n\n   ex2: OtherExample\n   reveal_type(ex2.foo)  # Revealed type is Callable[[], int]\n   reveal_type(ex2.bar)  # Revealed type is int\n\n.. _predefined_protocols_reference:\n\nPredefined protocol reference\n*****************************\n\nIteration protocols\n...................\n\nThe iteration protocols are useful in many contexts. For example, they allow\niteration of objects in for loops.\n\ncollections.abc.Iterable[T]\n---------------------------\n\nThe :ref:`example above <predefined_protocols>` has a simple implementation of an\n:py:meth:`__iter__ <object.__iter__>` method.\n\n.. code-block:: python\n\n   def __iter__(self) -> Iterator[T]\n\nSee also :py:class:`~collections.abc.Iterable`.\n\ncollections.abc.Iterator[T]\n---------------------------\n\n.. code-block:: python\n\n   def __next__(self) -> T\n   def __iter__(self) -> Iterator[T]\n\nSee also :py:class:`~collections.abc.Iterator`.\n\nCollection protocols\n....................\n\nMany of these are implemented by built-in container types such as\n:py:class:`list` and :py:class:`dict`, and these are also useful for user-defined\ncollection objects.\n\ncollections.abc.Sized\n---------------------\n\nThis is a type for objects that support :py:func:`len(x) <len>`.\n\n.. code-block:: python\n\n   def __len__(self) -> int\n\nSee also :py:class:`~collections.abc.Sized`.\n\ncollections.abc.Container[T]\n----------------------------\n\nThis is a type for objects that support the ``in`` operator.\n\n.. code-block:: python\n\n   def __contains__(self, x: object) -> bool\n\nSee also :py:class:`~collections.abc.Container`.\n\ncollections.abc.Collection[T]\n-----------------------------\n\n.. code-block:: python\n\n   def __len__(self) -> int\n   def __iter__(self) -> Iterator[T]\n   def __contains__(self, x: object) -> bool\n\nSee also :py:class:`~collections.abc.Collection`.\n\nOne-off protocols\n.................\n\nThese protocols are typically only useful with a single standard\nlibrary function or class.\n\ncollections.abc.Reversible[T]\n-----------------------------\n\nThis is a type for objects that support :py:func:`reversed(x) <reversed>`.\n\n.. code-block:: python\n\n   def __reversed__(self) -> Iterator[T]\n\nSee also :py:class:`~collections.abc.Reversible`.\n\ntyping.SupportsAbs[T]\n---------------------\n\nThis is a type for objects that support :py:func:`abs(x) <abs>`. ``T`` is the type of\nvalue returned by :py:func:`abs(x) <abs>`.\n\n.. code-block:: python\n\n   def __abs__(self) -> T\n\nSee also :py:class:`~typing.SupportsAbs`.\n\ntyping.SupportsBytes\n--------------------\n\nThis is a type for objects that support :py:class:`bytes(x) <bytes>`.\n\n.. code-block:: python\n\n   def __bytes__(self) -> bytes\n\nSee also :py:class:`~typing.SupportsBytes`.\n\n.. _supports-int-etc:\n\ntyping.SupportsComplex\n----------------------\n\nThis is a type for objects that support :py:class:`complex(x) <complex>`. Note that no arithmetic operations\nare supported.\n\n.. code-block:: python\n\n   def __complex__(self) -> complex\n\nSee also :py:class:`~typing.SupportsComplex`.\n\ntyping.SupportsFloat\n--------------------\n\nThis is a type for objects that support :py:class:`float(x) <float>`. Note that no arithmetic operations\nare supported.\n\n.. code-block:: python\n\n   def __float__(self) -> float\n\nSee also :py:class:`~typing.SupportsFloat`.\n\ntyping.SupportsInt\n------------------\n\nThis is a type for objects that support :py:class:`int(x) <int>`. Note that no arithmetic operations\nare supported.\n\n.. code-block:: python\n\n   def __int__(self) -> int\n\nSee also :py:class:`~typing.SupportsInt`.\n\ntyping.SupportsRound[T]\n-----------------------\n\nThis is a type for objects that support :py:func:`round(x) <round>`.\n\n.. code-block:: python\n\n   def __round__(self) -> T\n\nSee also :py:class:`~typing.SupportsRound`.\n\nAsync protocols\n...............\n\nThese protocols can be useful in async code. See :ref:`async-and-await`\nfor more information.\n\ncollections.abc.Awaitable[T]\n----------------------------\n\n.. code-block:: python\n\n   def __await__(self) -> Generator[Any, None, T]\n\nSee also :py:class:`~collections.abc.Awaitable`.\n\ncollections.abc.AsyncIterable[T]\n--------------------------------\n\n.. code-block:: python\n\n   def __aiter__(self) -> AsyncIterator[T]\n\nSee also :py:class:`~collections.abc.AsyncIterable`.\n\ncollections.abc.AsyncIterator[T]\n--------------------------------\n\n.. code-block:: python\n\n   def __anext__(self) -> Awaitable[T]\n   def __aiter__(self) -> AsyncIterator[T]\n\nSee also :py:class:`~collections.abc.AsyncIterator`.\n\nContext manager protocols\n.........................\n\nThere are two protocols for context managers -- one for regular context\nmanagers and one for async ones. These allow defining objects that can\nbe used in ``with`` and ``async with`` statements.\n\ncontextlib.AbstractContextManager[T]\n------------------------------------\n\n.. code-block:: python\n\n   def __enter__(self) -> T\n   def __exit__(self,\n                exc_type: type[BaseException] | None,\n                exc_value: BaseException | None,\n                traceback: TracebackType | None) -> bool | None\n\nSee also :py:class:`~contextlib.AbstractContextManager`.\n\ncontextlib.AbstractAsyncContextManager[T]\n-----------------------------------------\n\n.. code-block:: python\n\n   def __aenter__(self) -> Awaitable[T]\n   def __aexit__(self,\n                 exc_type: type[BaseException] | None,\n                 exc_value: BaseException | None,\n                 traceback: TracebackType | None) -> Awaitable[bool | None]\n\nSee also :py:class:`~contextlib.AbstractAsyncContextManager`.\n"
  },
  {
    "path": "docs/source/running_mypy.rst",
    "content": ".. _running-mypy:\n\nRunning mypy and managing imports\n=================================\n\nThe :ref:`getting-started` page should have already introduced you\nto the basics of how to run mypy -- pass in the files and directories\nyou want to type check via the command line::\n\n    $ mypy foo.py bar.py some_directory\n\nThis page discusses in more detail how exactly to specify what files\nyou want mypy to type check, how mypy discovers imported modules,\nand recommendations on how to handle any issues you may encounter\nalong the way.\n\nIf you are interested in learning about how to configure the\nactual way mypy type checks your code, see our\n:ref:`command-line` guide.\n\n\n.. _specifying-code-to-be-checked:\n\nSpecifying code to be checked\n*****************************\n\nMypy lets you specify what files it should type check in several different ways.\n\n1.  First, you can pass in paths to Python files and directories you\n    want to type check. For example::\n\n        $ mypy file_1.py foo/file_2.py file_3.pyi some/directory\n\n    The above command tells mypy it should type check all of the provided\n    files together. In addition, mypy will recursively type check the\n    entire contents of any provided directories.\n\n    For more details about how exactly this is done, see\n    :ref:`Mapping file paths to modules <mapping-paths-to-modules>`.\n\n2.  Second, you can use the :option:`-m <mypy -m>` flag (long form: :option:`--module <mypy --module>`) to\n    specify a module name to be type checked. The name of a module\n    is identical to the name you would use to import that module\n    within a Python program. For example, running::\n\n        $ mypy -m html.parser\n\n    ...will type check the module ``html.parser`` (this happens to be\n    a library stub).\n\n    Mypy will use an algorithm very similar to the one Python uses to\n    find where modules and imports are located on the file system.\n    For more details, see :ref:`finding-imports`.\n\n3.  Third, you can use the :option:`-p <mypy -p>` (long form: :option:`--package <mypy --package>`) flag to\n    specify a package to be (recursively) type checked. This flag\n    is almost identical to the :option:`-m <mypy -m>` flag except that if you give it\n    a package name, mypy will recursively type check all submodules\n    and subpackages of that package. For example, running::\n\n        $ mypy -p html\n\n    ...will type check the entire ``html`` package (of library stubs).\n    In contrast, if we had used the :option:`-m <mypy -m>` flag, mypy would have type\n    checked just ``html``'s ``__init__.py`` file and anything imported\n    from there.\n\n    Note that we can specify multiple packages and modules on the\n    command line. For example::\n\n      $ mypy --package p.a --package p.b --module c\n\n4.  Fourth, you can also instruct mypy to directly type check small\n    strings as programs by using the :option:`-c <mypy -c>` (long form: :option:`--command <mypy --command>`)\n    flag. For example::\n\n        $ mypy -c 'x = [1, 2]; print(x())'\n\n    ...will type check the above string as a mini-program (and in this case,\n    will report that ``list[int]`` is not callable).\n\nYou can also use the :confval:`files` option in your :file:`mypy.ini` file to specify which\nfiles to check, in which case you can simply run ``mypy`` with no arguments.\n\n\nReading a list of files from a file\n***********************************\n\nFinally, any command-line argument starting with ``@`` reads additional\ncommand-line arguments from the file following the ``@`` character.\nThis is primarily useful if you have a file containing a list of files\nthat you want to be type-checked: instead of using shell syntax like::\n\n    $ mypy $(cat file_of_files.txt)\n\nyou can use this instead::\n\n    $ mypy @file_of_files.txt\n\nThis file can technically also contain any command line flag, not\njust file paths. However, if you want to configure many different\nflags, the recommended approach is to use a\n:ref:`configuration file <config-file>` instead.\n\n\n.. _mapping-paths-to-modules:\n\nMapping file paths to modules\n*****************************\n\nOne of the main ways you can tell mypy what to type check\nis by providing mypy a list of paths. For example::\n\n    $ mypy file_1.py foo/file_2.py file_3.pyi some/directory\n\nThis section describes how exactly mypy maps the provided paths\nto modules to type check.\n\n- Mypy will check all paths provided that correspond to files.\n\n- Mypy will recursively discover and check all files ending in ``.py`` or\n  ``.pyi`` in directory paths provided, after accounting for\n  :option:`--exclude <mypy --exclude>`.\n\n- For each file to be checked, mypy will attempt to associate the file (e.g.\n  ``project/foo/bar/baz.py``) with a fully qualified module name (e.g.\n  ``foo.bar.baz``). The directory the package is in (``project``) is then\n  added to mypy's module search paths.\n\nHow mypy determines fully qualified module names depends on if the options\n:option:`--no-namespace-packages <mypy --no-namespace-packages>` and\n:option:`--explicit-package-bases <mypy --explicit-package-bases>` are set.\n\n1. If :option:`--no-namespace-packages <mypy --no-namespace-packages>` is set,\n   mypy will rely solely upon the presence of ``__init__.py[i]`` files to\n   determine the fully qualified module name. That is, mypy will crawl up the\n   directory tree for as long as it continues to find ``__init__.py`` (or\n   ``__init__.pyi``) files.\n\n   For example, if your directory tree consists of ``pkg/subpkg/mod.py``, mypy\n   would require ``pkg/__init__.py`` and ``pkg/subpkg/__init__.py`` to exist in\n   order correctly associate ``mod.py`` with ``pkg.subpkg.mod``\n\n2. The default case. If :option:`--namespace-packages <mypy\n   --no-namespace-packages>` is on, but :option:`--explicit-package-bases <mypy\n   --explicit-package-bases>` is off, mypy will allow for the possibility that\n   directories without ``__init__.py[i]`` are packages. Specifically, mypy will\n   look at all parent directories of the file and use the location of the\n   highest ``__init__.py[i]`` in the directory tree to determine the top-level\n   package.\n\n   For example, say your directory tree consists solely of ``pkg/__init__.py``\n   and ``pkg/a/b/c/d/mod.py``. When determining ``mod.py``'s fully qualified\n   module name, mypy will look at ``pkg/__init__.py`` and conclude that the\n   associated module name is ``pkg.a.b.c.d.mod``.\n\n3. You'll notice that the above case still relies on ``__init__.py``. If\n   you can't put an ``__init__.py`` in your top-level package, but still wish to\n   pass paths (as opposed to packages or modules using the ``-p`` or ``-m``\n   flags), :option:`--explicit-package-bases <mypy --explicit-package-bases>`\n   provides a solution.\n\n   With :option:`--explicit-package-bases <mypy --explicit-package-bases>`, mypy\n   will locate the nearest parent directory that is a member of the ``MYPYPATH``\n   environment variable, the :confval:`mypy_path` config or is the current\n   working directory. Mypy will then use the relative path to determine the\n   fully qualified module name.\n\n   For example, say your directory tree consists solely of\n   ``src/namespace_pkg/mod.py``. If you run the following command, mypy\n   will correctly associate ``mod.py`` with ``namespace_pkg.mod``::\n\n       $ MYPYPATH=src mypy --namespace-packages --explicit-package-bases .\n\nIf you pass a file not ending in ``.py[i]``, the module name assumed is\n``__main__`` (matching the behavior of the Python interpreter), unless\n:option:`--scripts-are-modules <mypy --scripts-are-modules>` is passed.\n\nPassing :option:`-v <mypy -v>` will show you the files and associated module\nnames that mypy will check.\n\n\nHow mypy handles imports\n************************\n\nWhen mypy encounters an ``import`` statement, it will first\n:ref:`attempt to locate <finding-imports>` that module\nor type stubs for that module in the file system. Mypy will then\ntype check the imported module. There are three different outcomes\nof this process:\n\n1.  Mypy is unable to follow the import: the module either does not\n    exist, or is a third party library that does not use type hints.\n\n2.  Mypy is able to follow and type check the import, but you did\n    not want mypy to type check that module at all.\n\n3.  Mypy is able to successfully both follow and type check the\n    module, and you want mypy to type check that module.\n\nThe third outcome is what mypy will do in the ideal case. The following\nsections will discuss what to do in the other two cases.\n\n.. _ignore-missing-imports:\n.. _fix-missing-imports:\n\nMissing imports\n***************\n\nWhen you import a module, mypy may report that it is unable to follow\nthe import. This can cause errors that look like the following:\n\n.. code-block:: text\n\n    main.py:1: error: Skipping analyzing 'django': module is installed, but missing library stubs or py.typed marker\n    main.py:2: error: Library stubs not installed for \"requests\"\n    main.py:3: error: Cannot find implementation or library stub for module named \"this_module_does_not_exist\"\n\nIf you get any of these errors on an import, mypy will assume the type of that\nmodule is ``Any``, the dynamic type. This means attempting to access any\nattribute of the module will automatically succeed:\n\n.. code-block:: python\n\n    # Error: Cannot find implementation or library stub for module named 'does_not_exist'\n    import does_not_exist\n\n    # But this type checks, and x will have type 'Any'\n    x = does_not_exist.foobar()\n\nThis can result in mypy failing to warn you about errors in your code. Since\noperations on ``Any`` result in ``Any``, these dynamic types can propagate\nthrough your code, making type checking less effective. See\n:ref:`dynamic-typing` for more information.\n\nThe next sections describe what each of these errors means and recommended next steps; scroll to\nthe section that matches your error.\n\n\nMissing library stubs or py.typed marker\n----------------------------------------\n\nIf you are getting a ``Skipping analyzing X: module is installed, but missing library stubs or py.typed marker``,\nerror, this means mypy was able to find the module you were importing, but no\ncorresponding type hints.\n\nMypy will not try inferring the types of any 3rd party libraries you have installed\nunless they either have declared themselves to be\n:ref:`PEP 561 compliant stub package <installed-packages>` (e.g. with a ``py.typed`` file) or have registered\nthemselves on `typeshed <https://github.com/python/typeshed>`_, the repository\nof types for the standard library and some 3rd party libraries.\n\nIf you are getting this error, try to obtain type hints for the library you're using:\n\n1.  Upgrading the version of the library you're using, in case a newer version\n    has started to include type hints.\n\n2.  Searching to see if there is a :ref:`PEP 561 compliant stub package <installed-packages>`\n    corresponding to your third party library. Stub packages let you install\n    type hints independently from the library itself.\n\n    For example, if you want type hints for the ``django`` library, you can\n    install the `django-stubs <https://pypi.org/project/django-stubs/>`_ package.\n\n3.  :ref:`Writing your own stub files <stub-files>` containing type hints for\n    the library. You can point mypy at your type hints either by passing\n    them in via the command line, by using the  :confval:`files` or :confval:`mypy_path`\n    config file options, or by\n    adding the location to the ``MYPYPATH`` environment variable.\n\n    These stub files do not need to be complete! A good strategy is to use\n    :ref:`stubgen <stubgen>`, a program that comes bundled with mypy, to generate a first\n    rough draft of the stubs. You can then iterate on just the parts of the\n    library you need.\n\n    If you want to share your work, you can try contributing your stubs back\n    to the library -- see our documentation on creating\n    :ref:`PEP 561 compliant packages <installed-packages>`.\n\n4.  Force mypy to analyze the library as best as it can (as if the library provided\n    a ``py.typed`` file), despite it likely missing any type annotations. In general,\n    the quality of type checking will be poor and mypy may have issues when\n    analyzing code not designed to be type checked.\n\n    You can do this via setting the\n    :option:`--follow-untyped-imports <mypy --follow-untyped-imports>`\n    command line flag or :confval:`follow_untyped_imports` config file option to True.\n    This option can be specified on a per-module basis as well:\n\n    .. tab:: mypy.ini\n\n        .. code-block:: ini\n\n            [mypy-untyped_package.*]\n            follow_untyped_imports = True\n\n    .. tab:: pyproject.toml\n\n        .. code-block:: toml\n\n            [[tool.mypy.overrides]]\n            module = [\"untyped_package.*\"]\n            follow_untyped_imports = true\n\nIf you are unable to find any existing type hints nor have time to write your\nown, you can instead *suppress* the errors.\n\nAll this will do is make mypy stop reporting an error on the line containing the\nimport: the imported module will continue to be of type ``Any``, and mypy may\nnot catch errors in its use.\n\n1.  To suppress a *single* missing import error, add a ``# type: ignore`` at the end of the\n    line containing the import.\n\n2.  To suppress *all* missing import errors from a single library, add\n    a per-module section to your :ref:`mypy config file <config-file>` setting\n    :confval:`ignore_missing_imports` to True for that library. For example,\n    suppose your codebase\n    makes heavy use of an (untyped) library named ``foobar``. You can silence\n    all import errors associated with that library and that library alone by\n    adding the following section to your config file:\n\n    .. tab:: mypy.ini\n\n        .. code-block:: ini\n\n            [mypy-foobar.*]\n            ignore_missing_imports = True\n\n    .. tab:: pyproject.toml\n\n        .. code-block:: toml\n\n            [[tool.mypy.overrides]]\n            module = [\"foobar.*\"]\n            ignore_missing_imports = true\n\n    Note: this option is equivalent to adding a ``# type: ignore`` to every\n    import of ``foobar`` in your codebase. For more information, see the\n    documentation about configuring\n    :ref:`import discovery <config-file-import-discovery>` in config files.\n    The ``.*`` after ``foobar`` will ignore imports of ``foobar`` modules\n    and subpackages in addition to the ``foobar`` top-level package namespace.\n\n3.  To suppress *all* missing import errors for *all* untyped libraries\n    in your codebase, use :option:`--disable-error-code=import-untyped <mypy --ignore-missing-imports>`.\n    See :ref:`code-import-untyped` for more details on this error code.\n\n    You can also set :confval:`disable_error_code`, like so:\n\n    .. tab:: mypy.ini\n\n        .. code-block:: ini\n\n            [mypy]\n            disable_error_code = import-untyped\n\n    .. tab:: pyproject.toml\n\n        .. code-block:: ini\n\n            [tool.mypy]\n            disable_error_code = [\"import-untyped\"]\n\n    You can also set the :option:`--ignore-missing-imports <mypy --ignore-missing-imports>`\n    command line flag or set the :confval:`ignore_missing_imports` config file\n    option to True in the *global* section of your mypy config file. We\n    recommend avoiding ``--ignore-missing-imports`` if possible: it's equivalent\n    to adding a ``# type: ignore`` to all unresolved imports in your codebase.\n\n\nLibrary stubs not installed\n---------------------------\n\nIf mypy can't find stubs for a third-party library, and it knows that stubs exist for\nthe library, you will get a message like this:\n\n.. code-block:: text\n\n    main.py:1: error: Library stubs not installed for \"yaml\"\n    main.py:1: note: Hint: \"python3 -m pip install types-PyYAML\"\n    main.py:1: note: (or run \"mypy --install-types\" to install all missing stub packages)\n\nYou can resolve the issue by running the suggested pip commands.\nIf you're running mypy in CI, you can ensure the presence of any stub packages\nyou need the same as you would any other test dependency, e.g. by adding them to\nthe appropriate ``requirements.txt`` file.\n\nAlternatively, add the :option:`--install-types <mypy --install-types>`\nto your mypy command to install all known missing stubs:\n\n.. code-block:: text\n\n    mypy --install-types\n\nThis is slower than explicitly installing stubs, since it effectively\nruns mypy twice -- the first time to find the missing stubs, and\nthe second time to type check your code properly after mypy has\ninstalled the stubs. It also can make controlling stub versions harder,\nresulting in less reproducible type checking.\n\nBy default, :option:`--install-types <mypy --install-types>` shows a confirmation prompt.\nUse :option:`--non-interactive <mypy --non-interactive>` to install all suggested\nstub packages without asking for confirmation *and* type check your code:\n\nIf you've already installed the relevant third-party libraries in an environment\nother than the one mypy is running in, you can use :option:`--python-executable\n<mypy --python-executable>` flag to point to the Python executable for that\nenvironment, and mypy will find packages installed for that Python executable.\n\nIf you've installed the relevant stub packages and are still getting this error,\nsee the :ref:`section below <missing-type-hints-for-third-party-library>`.\n\n.. _missing-type-hints-for-third-party-library:\n\nCannot find implementation or library stub\n------------------------------------------\n\nIf you are getting a ``Cannot find implementation or library stub for module``\nerror, this means mypy was not able to find the module you are trying to\nimport, whether it comes bundled with type hints or not. If you are getting\nthis error, try:\n\n1.  Making sure your import does not contain a typo.\n\n2.  If the module is a third party library, making sure that mypy is able\n    to find the interpreter containing the installed library.\n\n    For example, if you are running your code in a virtualenv, make sure\n    to install and use mypy within the virtualenv. Alternatively, if you\n    want to use a globally installed mypy, set the\n    :option:`--python-executable <mypy --python-executable>` command\n    line flag to point the Python interpreter containing your installed\n    third party packages.\n\n    You can confirm that you are running mypy from the environment you expect\n    by running it like ``python -m mypy ...``. You can confirm that you are\n    installing into the environment you expect by running pip like\n    ``python -m pip ...``.\n\n3.  Reading the :ref:`finding-imports` section below to make sure you\n    understand how exactly mypy searches for and finds modules and modify\n    how you're invoking mypy accordingly.\n\n4.  Directly specifying the directory containing the module you want to\n    type check from the command line, by using the :confval:`mypy_path`\n    or :confval:`files` config file options,\n    or by using the ``MYPYPATH`` environment variable.\n\n    Note: if the module you are trying to import is actually a *submodule* of\n    some package, you should specify the directory containing the *entire* package.\n    For example, suppose you are trying to add the module ``foo.bar.baz``\n    which is located at ``~/foo-project/src/foo/bar/baz.py``. In this case,\n    you must run ``mypy ~/foo-project/src`` (or set the ``MYPYPATH`` to\n    ``~/foo-project/src``).\n\n.. _finding-imports:\n\nHow imports are found\n*********************\n\nWhen mypy encounters an ``import`` statement or receives module\nnames from the command line via the :option:`--module <mypy --module>` or :option:`--package <mypy --package>`\nflags, mypy tries to find the module on the file system similar\nto the way Python finds it. However, there are some differences.\n\nFirst, mypy has its own search path.\nThis is computed from the following items:\n\n- The ``MYPYPATH`` environment variable\n  (a list of directories, colon-separated on UNIX systems, semicolon-separated on Windows).\n- The :confval:`mypy_path` config file option.\n- The directories containing the sources given on the command line\n  (see :ref:`Mapping file paths to modules <mapping-paths-to-modules>`).\n- The installed packages marked as safe for type checking (see\n  :ref:`PEP 561 support <installed-packages>`)\n- The relevant directories of the\n  `typeshed <https://github.com/python/typeshed>`_ repo.\n\n.. note::\n\n    You cannot point to a stub-only package (:pep:`561`) via the ``MYPYPATH``, it must be\n    installed (see :ref:`PEP 561 support <installed-packages>`)\n\nSecond, mypy searches for stub files in addition to regular Python files\nand packages.\nThe rules for searching for a module ``foo`` are as follows:\n\n- The search looks in each of the directories in the search path\n  (see above) until a match is found.\n- If a package named ``foo`` is found (i.e. a directory\n  ``foo`` containing an ``__init__.py`` or ``__init__.pyi`` file)\n  that's a match.\n- If a stub file named ``foo.pyi`` is found, that's a match.\n- If a Python module named ``foo.py`` is found, that's a match.\n\nThese matches are tried in order, so that if multiple matches are found\nin the same directory on the search path\n(e.g. a package and a Python file, or a stub file and a Python file)\nthe first one in the above list wins.\n\nIn particular, if a Python file and a stub file are both present in the\nsame directory on the search path, only the stub file is used.\n(However, if the files are in different directories, the one found\nin the earlier directory is used.)\n\nSetting :confval:`mypy_path`/``MYPYPATH`` is mostly useful in the case\nwhere you want to try running mypy against multiple distinct\nsets of files that happen to share some common dependencies.\n\nFor example, if you have multiple projects that happen to be\nusing the same set of work-in-progress stubs, it could be\nconvenient to just have your ``MYPYPATH`` point to a single\ndirectory containing the stubs.\n\n.. _follow-imports:\n\nFollowing imports\n*****************\n\nMypy is designed to :ref:`doggedly follow all imports <finding-imports>`,\neven if the imported module is not a file you explicitly wanted mypy to check.\n\nFor example, suppose we have two modules ``mycode.foo`` and ``mycode.bar``:\nthe former has type hints and the latter does not. We run\n:option:`mypy -m mycode.foo <mypy -m>` and mypy discovers that ``mycode.foo`` imports\n``mycode.bar``.\n\nHow do we want mypy to type check ``mycode.bar``? Mypy's behaviour here is\nconfigurable -- although we **strongly recommend** using the default --\nby using the :option:`--follow-imports <mypy --follow-imports>` flag. This flag\naccepts one of four string values:\n\n-   ``normal`` (the default, recommended) follows all imports normally and\n    type checks all top level code (as well as the bodies of all\n    functions and methods with at least one type annotation in\n    the signature).\n\n-   ``silent`` behaves in the same way as ``normal`` but will\n    additionally *suppress* any error messages.\n\n-   ``skip`` will *not* follow imports and instead will silently\n    replace the module (and *anything imported from it*) with an\n    object of type ``Any``.\n\n-   ``error`` behaves in the same way as ``skip`` but is not quite as\n    silent -- it will flag the import as an error, like this::\n\n        main.py:1: note: Import of \"mycode.bar\" ignored\n        main.py:1: note: (Using --follow-imports=error, module not passed on command line)\n\nIf you are starting a new codebase and plan on using type hints from\nthe start, we **recommend** you use either :option:`--follow-imports=normal <mypy --follow-imports>`\n(the default) or :option:`--follow-imports=error <mypy --follow-imports>`. Either option will help\nmake sure you are not skipping checking any part of your codebase by\naccident.\n\nIf you are planning on adding type hints to a large, existing code base,\nwe recommend you start by trying to make your entire codebase (including\nfiles that do not use type hints) pass under :option:`--follow-imports=normal <mypy --follow-imports>`.\nThis is usually not too difficult to do: mypy is designed to report as\nfew error messages as possible when it is looking at unannotated code.\n\nOnly if doing this is intractable, try passing mypy just the files\nyou want to type check and using :option:`--follow-imports=silent <mypy --follow-imports>`.\nEven if mypy is unable to perfectly type check a file, it can still glean some\nuseful information by parsing it (for example, understanding what methods\na given object has). See :ref:`existing-code` for more recommendations.\n\nAdjusting import following behaviour is often most useful when restricted to\nspecific modules. This can be accomplished by setting a per-module\n:confval:`follow_imports` config option.\n\n.. warning::\n\n    We do not recommend using ``follow_imports=skip`` unless you're really sure\n    you know what you are doing. This option greatly restricts the analysis mypy\n    can perform and you will lose a lot of the benefits of type checking.\n\n    This is especially true at the global level. Setting a per-module\n    ``follow_imports=skip`` for a specific problematic module can be\n    useful without causing too much harm.\n\n.. note::\n\n    If you're looking to resolve import errors related to libraries, try following\n    the advice in :ref:`fix-missing-imports` before messing with ``follow_imports``.\n"
  },
  {
    "path": "docs/source/runtime_troubles.rst",
    "content": ".. _runtime_troubles:\n\nAnnotation issues at runtime\n============================\n\nIdiomatic use of type annotations can sometimes run up against what a given\nversion of Python considers legal code. This section describes these scenarios\nand explains how to get your code running again. Generally speaking, we have\nthree tools at our disposal:\n\n* Use of string literal types or type comments\n* Use of ``typing.TYPE_CHECKING``\n* Use of ``from __future__ import annotations`` (:pep:`563`)\n\nWe provide a description of these before moving onto discussion of specific\nproblems you may encounter.\n\n.. _string-literal-types:\n\nString literal types and type comments\n--------------------------------------\n\nMypy lets you add type annotations using the (now deprecated) ``# type:``\ntype comment syntax. These were required with Python versions older than 3.6,\nsince they didn't support type annotations on variables. Example:\n\n.. code-block:: python\n\n   a = 1  # type: int\n\n   def f(x):  # type: (int) -> int\n       return x + 1\n\n   # Alternative type comment syntax for functions with many arguments\n   def send_email(\n        address,     # type: Union[str, List[str]]\n        sender,      # type: str\n        cc,          # type: Optional[List[str]]\n        subject='',\n        body=None    # type: List[str]\n   ):\n       # type: (...) -> bool\n\nType comments can't cause runtime errors because comments are not evaluated by\nPython.\n\nIn a similar way, using string literal types sidesteps the problem of\nannotations that would cause runtime errors.\n\nAny type can be entered as a string literal, and you can combine\nstring-literal types with non-string-literal types freely:\n\n.. code-block:: python\n\n   def f(a: list['A']) -> None: ...  # OK, prevents NameError since A is defined later\n   def g(n: 'int') -> None: ...      # Also OK, though not useful\n\n   class A: pass\n\nString literal types are never needed in ``# type:`` comments and :ref:`stub files <stub-files>`.\n\nString literal types must be defined (or imported) later *in the same module*.\nThey cannot be used to leave cross-module references unresolved.  (For dealing\nwith import cycles, see :ref:`import-cycles`.)\n\n.. _future-annotations:\n\nFuture annotations import (PEP 563)\n-----------------------------------\n\nMany of the issues described here are caused by Python trying to evaluate\nannotations. Future Python versions (potentially Python 3.14) will by default no\nlonger attempt to evaluate function and variable annotations. This behaviour is\nmade available in Python 3.7 and later through the use of\n``from __future__ import annotations``.\n\nThis can be thought of as automatic string literal-ification of all function and\nvariable annotations. Note that function and variable annotations are still\nrequired to be valid Python syntax. For more details, see :pep:`563`.\n\n.. note::\n\n    Even with the ``__future__`` import, there are some scenarios that could\n    still require string literals or result in errors, typically involving use\n    of forward references or generics in:\n\n    * :ref:`type aliases <type-aliases>` not defined using the ``type`` statement;\n    * :ref:`type narrowing <type-narrowing>`;\n    * type definitions (see :py:class:`~typing.TypeVar`, :py:class:`~typing.NewType`, :py:class:`~typing.NamedTuple`);\n    * base classes.\n\n    .. code-block:: python\n\n        # base class example\n        from __future__ import annotations\n\n        class A(tuple['B', 'C']): ... # String literal types needed here\n        class B: ...\n        class C: ...\n\n.. warning::\n\n    Some libraries may have use cases for dynamic evaluation of annotations, for\n    instance, through use of ``typing.get_type_hints`` or ``eval``. If your\n    annotation would raise an error when evaluated (say by using :pep:`604`\n    syntax with Python 3.9), you may need to be careful when using such\n    libraries.\n\n.. _typing-type-checking:\n\ntyping.TYPE_CHECKING\n--------------------\n\nThe :py:mod:`typing` module defines a :py:data:`~typing.TYPE_CHECKING` constant\nthat is ``False`` at runtime but treated as ``True`` while type checking.\n\nSince code inside ``if TYPE_CHECKING:`` is not executed at runtime, it provides\na convenient way to tell mypy something without the code being evaluated at\nruntime. This is most useful for resolving :ref:`import cycles <import-cycles>`.\n\n.. _forward-references:\n\nClass name forward references\n-----------------------------\n\nPython does not allow references to a class object before the class is\ndefined (aka forward reference). Thus this code does not work as expected:\n\n.. code-block:: python\n\n   def f(x: A) -> None: ...  # NameError: name \"A\" is not defined\n   class A: ...\n\nStarting from Python 3.7, you can add ``from __future__ import annotations`` to\nresolve this, as discussed earlier:\n\n.. code-block:: python\n\n   from __future__ import annotations\n\n   def f(x: A) -> None: ...  # OK\n   class A: ...\n\nFor Python 3.6 and below, you can enter the type as a string literal or type comment:\n\n.. code-block:: python\n\n   def f(x: 'A') -> None: ...  # OK\n\n   # Also OK\n   def g(x):  # type: (A) -> None\n       ...\n\n   class A: ...\n\nOf course, instead of using future annotations import or string literal types,\nyou could move the function definition after the class definition. This is not\nalways desirable or even possible, though.\n\n.. _import-cycles:\n\nImport cycles\n-------------\n\nAn import cycle occurs where module A imports module B and module B\nimports module A (perhaps indirectly, e.g. ``A -> B -> C -> A``).\nSometimes in order to add type annotations you have to add extra\nimports to a module and those imports cause cycles that didn't exist\nbefore. This can lead to errors at runtime like:\n\n.. code-block:: text\n\n   ImportError: cannot import name 'b' from partially initialized module 'A' (most likely due to a circular import)\n\nIf those cycles do become a problem when running your program, there's a trick:\nif the import is only needed for type annotations and you're using a) the\n:ref:`future annotations import<future-annotations>`, or b) string literals or type\ncomments for the relevant annotations, you can write the imports inside ``if\nTYPE_CHECKING:`` so that they are not executed at runtime. Example:\n\nFile ``foo.py``:\n\n.. code-block:: python\n\n   from typing import TYPE_CHECKING\n\n   if TYPE_CHECKING:\n       import bar\n\n   def listify(arg: 'bar.BarClass') -> 'list[bar.BarClass]':\n       return [arg]\n\nFile ``bar.py``:\n\n.. code-block:: python\n\n   from foo import listify\n\n   class BarClass:\n       def listifyme(self) -> 'list[BarClass]':\n           return listify(self)\n\n.. _not-generic-runtime:\n\nUsing classes that are generic in stubs but not at runtime\n----------------------------------------------------------\n\nSome classes are declared as :ref:`generic<generic-classes>` in stubs, but not\nat runtime.\n\nIn Python 3.8 and earlier, there are several examples within the standard library,\nfor instance, :py:class:`os.PathLike` and :py:class:`queue.Queue`. Subscripting\nsuch a class will result in a runtime error:\n\n.. code-block:: python\n\n   from queue import Queue\n\n   class Tasks(Queue[str]):  # TypeError: 'type' object is not subscriptable\n       ...\n\n   results: Queue[int] = Queue()  # TypeError: 'type' object is not subscriptable\n\nTo avoid errors from use of these generics in annotations, just use the\n:ref:`future annotations import<future-annotations>` (or string literals or type\ncomments for Python 3.6 and below).\n\nTo avoid errors when inheriting from these classes, things are a little more\ncomplicated and you need to use :ref:`typing.TYPE_CHECKING\n<typing-type-checking>`:\n\n.. code-block:: python\n\n   from typing import TYPE_CHECKING\n   from queue import Queue\n\n   if TYPE_CHECKING:\n       BaseQueue = Queue[str]  # this is only processed by mypy\n   else:\n       BaseQueue = Queue  # this is not seen by mypy but will be executed at runtime\n\n   class Tasks(BaseQueue):  # OK\n       ...\n\n   task_queue: Tasks\n   reveal_type(task_queue.get())  # Reveals str\n\nIf your subclass is also generic, you can use the following (using the\nlegacy syntax for generic classes):\n\n.. code-block:: python\n\n   from typing import TYPE_CHECKING, TypeVar, Generic\n   from queue import Queue\n\n   _T = TypeVar(\"_T\")\n   if TYPE_CHECKING:\n       class _MyQueueBase(Queue[_T]): pass\n   else:\n       class _MyQueueBase(Generic[_T], Queue): pass\n\n   class MyQueue(_MyQueueBase[_T]): pass\n\n   task_queue: MyQueue[str]\n   reveal_type(task_queue.get())  # Reveals str\n\nIn Python 3.9 and later, we can just inherit directly from ``Queue[str]`` or ``Queue[T]``\nsince its :py:class:`queue.Queue` implements :py:meth:`~object.__class_getitem__`, so\nthe class object can be subscripted at runtime. You may still encounter issues (even if\nyou use a recent Python version) when subclassing generic classes defined in third-party\nlibraries if types are generic only in stubs.\n\nUsing types defined in stubs but not at runtime\n-----------------------------------------------\n\nSometimes stubs that you're using may define types you wish to reuse that do\nnot exist at runtime. Importing these types naively will cause your code to fail\nat runtime with ``ImportError`` or ``ModuleNotFoundError``. Similar to previous\nsections, these can be dealt with by using :ref:`typing.TYPE_CHECKING\n<typing-type-checking>`:\n\n.. code-block:: python\n\n   from __future__ import annotations\n   from typing import TYPE_CHECKING\n   if TYPE_CHECKING:\n       from _typeshed import SupportsRichComparison\n\n    def f(x: SupportsRichComparison) -> None\n\nThe ``from __future__ import annotations`` is required to avoid\na ``NameError`` when using the imported symbol.\nFor more information and caveats, see the section on\n:ref:`future annotations <future-annotations>`.\n\n.. _generic-builtins:\n\nUsing generic builtins\n----------------------\n\nStarting with Python 3.9 (:pep:`585`), the type objects of many collections in\nthe standard library support subscription at runtime. This means that you no\nlonger have to import the equivalents from :py:mod:`typing`; you can simply use\nthe built-in collections or those from :py:mod:`collections.abc`:\n\n.. code-block:: python\n\n   from collections.abc import Sequence\n   x: list[str]\n   y: dict[int, str]\n   z: Sequence[str] = x\n\nThere is limited support for using this syntax in Python 3.7 and later as well:\nif you use ``from __future__ import annotations``, mypy will understand this\nsyntax in annotations. However, since this will not be supported by the Python\ninterpreter at runtime, make sure you're aware of the caveats mentioned in the\nnotes at :ref:`future annotations import<future-annotations>`.\n\nUsing X | Y syntax for Unions\n-----------------------------\n\nStarting with Python 3.10 (:pep:`604`), you can spell union types as\n``x: int | str``, instead of ``x: typing.Union[int, str]``.\n\nThere is limited support for using this syntax in Python 3.7 and later as well:\nif you use ``from __future__ import annotations``, mypy will understand this\nsyntax in annotations, string literal types, type comments and stub files.\nHowever, since this will not be supported by the Python interpreter at runtime\n(if evaluated, ``int | str`` will raise ``TypeError: unsupported operand type(s)\nfor |: 'type' and 'type'``), make sure you're aware of the caveats mentioned in\nthe notes at :ref:`future annotations import<future-annotations>`.\n\nUsing new additions to the typing module\n----------------------------------------\n\nYou may find yourself wanting to use features added to the :py:mod:`typing`\nmodule in earlier versions of Python than the addition.\n\nThe easiest way to do this is to install and use the ``typing_extensions``\npackage from PyPI for the relevant imports, for example:\n\n.. code-block:: python\n\n   from typing_extensions import TypeIs\n\nIf you don't want to rely on ``typing_extensions`` being installed on newer\nPythons, you could alternatively use:\n\n.. code-block:: python\n\n   import sys\n   if sys.version_info >= (3, 13):\n       from typing import TypeIs\n   else:\n       from typing_extensions import TypeIs\n\nThis plays nicely well with following :pep:`508` dependency specification:\n``typing_extensions; python_version<\"3.13\"``\n"
  },
  {
    "path": "docs/source/stubgen.rst",
    "content": ".. _stubgen:\n\n.. program:: stubgen\n\nAutomatic stub generation (stubgen)\n===================================\n\nA stub file (see :pep:`484`) contains only type hints for the public\ninterface of a module, with empty function bodies. Mypy can use a stub\nfile instead of the real implementation to provide type information\nfor the module. They are useful for third-party modules whose authors\nhave not yet added type hints (and when no stubs are available in\ntypeshed) and C extension modules (which mypy can't directly process).\n\nMypy includes the ``stubgen`` tool that can automatically generate\nstub files (``.pyi`` files) for Python modules and C extension modules.\nFor example, consider this source file:\n\n.. code-block:: python\n\n   from other_module import dynamic\n\n   BORDER_WIDTH = 15\n\n   class Window:\n       parent = dynamic()\n       def __init__(self, width, height):\n           self.width = width\n           self.height = height\n\n   def create_empty() -> Window:\n       return Window(0, 0)\n\nStubgen can generate this stub file based on the above file:\n\n.. code-block:: python\n\n   from typing import Any\n\n   BORDER_WIDTH: int = ...\n\n   class Window:\n       parent: Any = ...\n       width: Any = ...\n       height: Any = ...\n       def __init__(self, width, height) -> None: ...\n\n   def create_empty() -> Window: ...\n\nStubgen generates *draft* stubs. The auto-generated stub files often\nrequire some manual updates, and most types will default to ``Any``.\nThe stubs will be much more useful if you add more precise type annotations,\nat least for the most commonly used functionality.\n\nThe rest of this section documents the command line interface of stubgen.\nRun :option:`stubgen --help` for a quick summary of options.\n\n.. note::\n\n  The command-line flags may change between releases.\n\nSpecifying what to stub\n***********************\n\nYou can give stubgen paths of the source files for which you want to\ngenerate stubs::\n\n    $ stubgen foo.py bar.py\n\nThis generates stubs ``out/foo.pyi`` and ``out/bar.pyi``. The default\noutput directory ``out`` can be overridden with :option:`-o DIR <-o>`.\n\nYou can also pass directories, and stubgen will recursively search\nthem for any ``.py`` files and generate stubs for all of them::\n\n    $ stubgen my_pkg_dir\n\nAlternatively, you can give module or package names using the\n:option:`-m` or :option:`-p` options::\n\n    $ stubgen -m foo -m bar -p my_pkg_dir\n\nDetails of the options:\n\n.. option:: -m MODULE, --module MODULE\n\n    Generate a stub file for the given module. This flag may be repeated\n    multiple times.\n\n    Stubgen *will not* recursively generate stubs for any submodules of\n    the provided module.\n\n.. option:: -p PACKAGE, --package PACKAGE\n\n    Generate stubs for the given package. This flag maybe repeated\n    multiple times.\n\n    Stubgen *will* recursively generate stubs for all submodules of\n    the provided package. This flag is identical to :option:`--module` apart from\n    this behavior.\n\n.. note::\n\n   You can't mix paths and :option:`-m`/:option:`-p` options in the same stubgen\n   invocation.\n\nStubgen applies heuristics to avoid generating stubs for submodules\nthat include tests or vendored third-party packages.\n\nSpecifying how to generate stubs\n********************************\n\nBy default stubgen will try to import the target modules and packages.\nThis allows stubgen to use runtime introspection to generate stubs for C\nextension modules and to improve the quality of the generated\nstubs. By default, stubgen will also use mypy to perform light-weight\nsemantic analysis of any Python modules. Use the following flags to\nalter the default behavior:\n\n.. option:: --no-import\n\n    Don't try to import modules. Instead only use mypy's normal search mechanism to find\n    sources. This does not support C extension modules. This flag also disables\n    runtime introspection functionality, which mypy uses to find the value of\n    ``__all__``. As result the set of exported imported names in stubs may be\n    incomplete. This flag is generally only useful when importing a module causes\n    unwanted side effects, such as the running of tests. Stubgen tries to skip test\n    modules even without this option, but this does not always work.\n\n.. option:: --no-analysis\n\n    Don't perform semantic analysis of source files. This may generate\n    worse stubs -- in particular, some module, class, and function aliases may\n    be represented as variables with the ``Any`` type. This is generally only\n    useful if semantic analysis causes a critical mypy error.  Does not apply to\n    C extension modules.  Incompatible with :option:`--inspect-mode`.\n\n.. option:: --inspect-mode\n\n    Import and inspect modules instead of parsing source code. This is the default\n    behavior for C modules and pyc-only packages.  The flag is useful to force\n    inspection for pure Python modules that make use of dynamically generated\n    members that would otherwise be omitted when using the default behavior of\n    code parsing.  Implies :option:`--no-analysis` as analysis requires source\n    code.\n\n.. option:: --doc-dir PATH\n\n    Try to infer better signatures by parsing .rst documentation in ``PATH``.\n    This may result in better stubs, but currently it only works for C extension\n    modules.\n\nAdditional flags\n****************\n\n.. option:: -h, --help\n\n    Show help message and exit.\n\n.. option:: --ignore-errors\n\n    If an exception was raised during stub generation, continue to process any\n    remaining modules instead of immediately failing with an error.\n\n.. option:: --include-private\n\n    Include definitions that are considered private in stubs (with names such\n    as ``_foo`` with single leading underscore and no trailing underscores).\n\n.. option:: --export-less\n\n    Don't export all names imported from other modules within the same package.\n    Instead, only export imported names that are not referenced in the module\n    that contains the import.\n\n.. option:: --include-docstrings\n\n    Include docstrings in stubs. This will add docstrings to Python function and\n    classes stubs and to C extension function stubs.\n\n.. option:: --search-path PATH\n\n    Specify module search directories, separated by colons (only used if\n    :option:`--no-import` is given).\n\n.. option:: -o PATH, --output PATH\n\n    Change the output directory. By default the stubs are written in the\n    ``./out`` directory. The output directory will be created if it doesn't\n    exist. Existing stubs in the output directory will be overwritten without\n    warning.\n\n.. option:: -v, --verbose\n\n    Produce more verbose output.\n\n.. option:: -q, --quiet\n\n    Produce less verbose output.\n"
  },
  {
    "path": "docs/source/stubs.rst",
    "content": ".. _stub-files:\n\nStub files\n==========\n\nA *stub file* is a file containing a skeleton of the public interface\nof that Python module, including classes, variables, functions -- and\nmost importantly, their types.\n\nMypy uses stub files stored in the\n`typeshed <https://github.com/python/typeshed>`_ repository to determine\nthe types of standard library and third-party library functions, classes,\nand other definitions. You can also create your own stubs that will be\nused to type check your code.\n\nCreating a stub\n***************\n\nHere is an overview of how to create a stub file:\n\n* Write a stub file for the library (or an arbitrary module) and store it as\n  a ``.pyi`` file in the same directory as the library module.\n* Alternatively, put your stubs (``.pyi`` files) in a directory\n  reserved for stubs (e.g., :file:`myproject/stubs`). In this case you\n  have to set the environment variable ``MYPYPATH`` to refer to the\n  directory.  For example::\n\n    $ export MYPYPATH=~/work/myproject/stubs\n\nUse the normal Python file name conventions for modules, e.g. :file:`csv.pyi`\nfor module ``csv``. Use a subdirectory with :file:`__init__.pyi` for packages. Note\nthat :pep:`561` stub-only packages must be installed, and may not be pointed\nat through the ``MYPYPATH`` (see :ref:`PEP 561 support <installed-packages>`).\n\nIf a directory contains both a ``.py`` and a ``.pyi`` file for the\nsame module, the ``.pyi`` file takes precedence. This way you can\neasily add annotations for a module even if you don't want to modify\nthe source code. This can be useful, for example, if you use 3rd party\nopen source libraries in your program (and there are no stubs in\ntypeshed yet).\n\nThat's it!\n\nNow you can access the module in mypy programs and type check\ncode that uses the library. If you write a stub for a library module,\nconsider making it available for other programmers that use mypy\nby contributing it back to the typeshed repo.\n\nMypy also ships with two tools for making it easier to create and maintain\nstubs: :ref:`stubgen` and :ref:`stubtest`.\n\nThe following sections explain the kinds of type annotations you can use\nin your programs and stub files.\n\n.. note::\n\n   You may be tempted to point ``MYPYPATH`` to the standard library or\n   to the :file:`site-packages` directory where your 3rd party packages\n   are installed. This is almost always a bad idea -- you will likely\n   get tons of error messages about code you didn't write and that\n   mypy can't analyze all that well yet, and in the worst case\n   scenario mypy may crash due to some construct in a 3rd party\n   package that it didn't expect.\n\nStub file syntax\n****************\n\nStub files are written in normal Python syntax, but generally\nleaving out runtime logic like variable initializers, function bodies,\nand default arguments.\n\nIf it is not possible to completely leave out some piece of runtime\nlogic, the recommended convention is to replace or elide them with ellipsis\nexpressions (``...``). Each ellipsis below is literally written in the\nstub file as three dots:\n\n.. code-block:: python\n\n    # Variables with annotations do not need to be assigned a value.\n    # So by convention, we omit them in the stub file.\n    x: int\n\n    # Function bodies cannot be completely removed. By convention,\n    # we replace them with `...` instead of the `pass` statement.\n    def func_1(code: str) -> int: ...\n\n    # We can do the same with default arguments.\n    def func_2(a: int, b: int = ...) -> int: ...\n\n.. note::\n\n    The ellipsis ``...`` is also used with a different meaning in\n    :ref:`callable types <callable-types>` and :ref:`tuple types\n    <tuple-types>`.\n\nUsing stub file syntax at runtime\n*********************************\n\nYou may also occasionally need to elide actual logic in regular\nPython code -- for example, when writing methods in\n:ref:`overload variants <function-overloading>` or\n:ref:`custom protocols <protocol-types>`.\n\nThe recommended style is to use ellipses to do so, just like in\nstub files. It is also considered stylistically acceptable to\nthrow a :py:exc:`NotImplementedError` in cases where the user of the\ncode may accidentally call functions with no actual logic.\n\nYou can also elide default arguments as long as the function body\nalso contains no runtime logic: the function body only contains\na single ellipsis, the pass statement, or a ``raise NotImplementedError()``.\nIt is also acceptable for the function body to contain a docstring.\nFor example:\n\n.. code-block:: python\n\n    from typing import Protocol\n\n    class Resource(Protocol):\n        def ok_1(self, foo: list[str] = ...) -> None: ...\n\n        def ok_2(self, foo: list[str] = ...) -> None:\n            raise NotImplementedError()\n\n        def ok_3(self, foo: list[str] = ...) -> None:\n            \"\"\"Some docstring\"\"\"\n            pass\n\n        # Error: Incompatible default for parameter \"foo\" (default has\n        # type \"ellipsis\", parameter has type \"list[str]\")\n        def not_ok(self, foo: list[str] = ...) -> None:\n            print(foo)\n"
  },
  {
    "path": "docs/source/stubtest.rst",
    "content": ".. _stubtest:\n\n.. program:: stubtest\n\nAutomatic stub testing (stubtest)\n=================================\n\nStub files are files containing type annotations. See\n`PEP 484 <https://www.python.org/dev/peps/pep-0484/#stub-files>`_\nfor more motivation and details.\n\nA common problem with stub files is that they tend to diverge from the\nactual implementation. Mypy includes the ``stubtest`` tool that can\nautomatically check for discrepancies between the stubs and the\nimplementation at runtime.\n\nWhat stubtest does and does not do\n**********************************\n\nStubtest will import your code and introspect your code objects at runtime, for\nexample, by using the capabilities of the :py:mod:`inspect` module. Stubtest\nwill then analyse the stub files, and compare the two, pointing out things that\ndiffer between stubs and the implementation at runtime.\n\nIt's important to be aware of the limitations of this comparison. Stubtest will\nnot make any attempt to statically analyse your actual code and relies only on\ndynamic runtime introspection (in particular, this approach means stubtest works\nwell with extension modules). However, this means that stubtest has limited\nvisibility; for instance, it cannot tell if a return type of a function is\naccurately typed in the stubs.\n\nFor clarity, here are some additional things stubtest can't do:\n\n* Type check your code -- use ``mypy`` instead\n* Generate stubs -- use ``stubgen`` or ``pyright --createstub`` instead\n* Generate stubs based on running your application or test suite -- use ``monkeytype`` instead\n* Apply stubs to code to produce inline types -- use ``retype`` or ``libcst`` instead\n\nIn summary, stubtest works very well for ensuring basic consistency between\nstubs and implementation or to check for stub completeness. It's used to\ntest Python's official collection of library stubs,\n`typeshed <https://github.com/python/typeshed>`_.\n\n.. warning::\n\n    stubtest will import and execute Python code from the packages it checks.\n\nExample\n*******\n\nHere's a quick example of what stubtest can do:\n\n.. code-block:: shell\n\n    $ python3 -m pip install mypy\n\n    $ cat library.py\n    x = \"hello, stubtest\"\n\n    def foo(x=None):\n        print(x)\n\n    $ cat library.pyi\n    x: int\n\n    def foo(x: int) -> None: ...\n\n    $ python3 -m mypy.stubtest library\n    error: library.foo is inconsistent, runtime argument \"x\" has a default value but stub argument does not\n    Stub: at line 3\n    def (x: builtins.int)\n    Runtime: in file ~/library.py:3\n    def (x=None)\n\n    error: library.x variable differs from runtime type Literal['hello, stubtest']\n    Stub: at line 1\n    builtins.int\n    Runtime:\n    'hello, stubtest'\n\n\nUsage\n*****\n\nRunning stubtest can be as simple as ``stubtest module_to_check``.\nRun :option:`stubtest --help` for a quick summary of options.\n\nStubtest must be able to import the code to be checked, so make sure that mypy\nis installed in the same environment as the library to be tested. In some\ncases, setting ``PYTHONPATH`` can help stubtest find the code to import.\n\nSimilarly, stubtest must be able to find the stubs to be checked. Stubtest\nrespects the ``MYPYPATH`` environment variable -- consider using this if you\nreceive a complaint along the lines of \"failed to find stubs\".\n\nNote that stubtest requires mypy to be able to analyse stubs. If mypy is unable\nto analyse stubs, you may get an error on the lines of \"not checking stubs due\nto mypy build errors\". In this case, you will need to mitigate those errors\nbefore stubtest will run. Despite potential overlap in errors here, stubtest is\nnot intended as a substitute for running mypy directly.\n\nAllowlist\n*********\n\nIf you wish to ignore some of stubtest's complaints, stubtest supports a\npretty handy :option:`--allowlist` system.\n\nLet's say that you have this python module called ``ex``:\n\n.. code-block:: python\n\n   try:\n       import optional_expensive_dep\n   except ImportError:\n       optional_expensive_dep = None\n\n   first = 1\n   if optional_expensive_dep:\n       second = 2\n\nLet's say that you can't install ``optional_expensive_dep`` in CI for some reason,\nbut you still want to include ``second: int`` in the stub file:\n\n.. code-block:: python\n\n    first: int\n    second: int\n\nIn this case stubtest will correctly complain:\n\n.. code-block:: shell\n\n   error: ex.second is not present at runtime\n   Stub: in file /.../ex.pyi:2\n   builtins.int\n   Runtime:\n   MISSING\n\n   Found 1 error (checked 1 module)\n\nTo fix this, you can add an ``allowlist`` entry:\n\n.. code-block:: ini\n\n   # Allowlist entries in `allowlist.txt` file:\n\n   # Does not exist if `optional_expensive_dep` is not installed:\n   ex.second\n\nAnd now when running stubtest with ``--allowlist=allowlist.txt``,\nno errors will be generated anymore.\n\nAllowlists also support regular expressions,\nwhich can be useful to ignore many similar errors at once.\nThey can also be useful for suppressing stubtest errors that occur sometimes,\nbut not on every CI run. For example, if some CI workers have\n``optional_expensive_dep`` installed, stubtest might complain with this message\non those workers if you had the ``ex.second`` allowlist entry:\n\n.. code-block:: ini\n\n   note: unused allowlist entry ex.second\n   Found 1 error (checked 1 module)\n\nChanging ``ex.second`` to be ``(ex\\.second)?`` will make this error optional,\nmeaning that stubtest will pass whether or not a CI runner\nhas``optional_expensive_dep`` installed.\n\nCLI\n***\n\nThe rest of this section documents the command line interface of stubtest.\n\n.. option:: --concise\n\n    Makes stubtest's output more concise, one line per error\n\n.. option:: --ignore-missing-stub\n\n    Ignore errors for stub missing things that are present at runtime\n\n.. option:: --ignore-positional-only\n\n    Ignore errors for whether an argument should or shouldn't be positional-only\n\n.. option:: --allowlist FILE\n\n    Use file as an allowlist. Can be passed multiple times to combine multiple\n    allowlists. Allowlists can be created with :option:`--generate-allowlist`.\n    Allowlists support regular expressions.\n\n    The presence of an entry in the allowlist means stubtest will not generate\n    any errors for the corresponding definition.\n\n.. option:: --generate-allowlist\n\n    Print an allowlist (to stdout) to be used with :option:`--allowlist`.\n\n    When introducing stubtest to an existing project, this is an easy way to\n    silence all existing errors.\n\n.. option:: --ignore-unused-allowlist\n\n    Ignore unused allowlist entries\n\n    Without this option enabled, the default is for stubtest to complain if an\n    allowlist entry is not necessary for stubtest to pass successfully.\n\n    Note if an allowlist entry is a regex that matches the empty string,\n    stubtest will never consider it unused. For example, to get\n    ``--ignore-unused-allowlist`` behaviour for a single allowlist entry like\n    ``foo.bar`` you could add an allowlist entry ``(foo\\.bar)?``.\n    This can be useful when an error only occurs on a specific platform.\n\n.. option:: --mypy-config-file FILE\n\n    Use specified mypy config *file* to determine mypy plugins and mypy path\n\n.. option:: --custom-typeshed-dir DIR\n\n    Use the custom typeshed in *DIR*\n\n.. option:: --check-typeshed\n\n    Check all stdlib modules in typeshed\n\n.. option:: --help\n\n    Show a help message :-)\n"
  },
  {
    "path": "docs/source/supported_python_features.rst",
    "content": "Supported Python features\n=========================\n\nA list of unsupported Python features is maintained in the mypy wiki:\n\n- `Unsupported Python features <https://github.com/python/mypy/wiki/Unsupported-Python-Features>`_\n\nRuntime definition of methods and functions\n*******************************************\n\nBy default, mypy will complain if you add a function to a class\nor module outside its definition -- but only if this is visible to the\ntype checker. This only affects static checking, as mypy performs no\nadditional type checking at runtime. You can easily work around\nthis. For example, you can use dynamically typed code or values with\n``Any`` types, or you can use :py:func:`setattr` or other introspection\nfeatures. However, you need to be careful if you decide to do this. If\nused indiscriminately, you may have difficulty using static typing\neffectively, since the type checker cannot see functions defined at\nruntime.\n"
  },
  {
    "path": "docs/source/type_inference_and_annotations.rst",
    "content": ".. _type-inference-and-annotations:\n\nType inference and type annotations\n===================================\n\nType inference\n**************\n\nFor most variables, if you do not explicitly specify its type, mypy will\ninfer the correct type based on what is initially assigned to the variable.\n\n.. code-block:: python\n\n    # Mypy will infer the type of these variables, despite no annotations\n    i = 1\n    reveal_type(i)  # Revealed type is \"builtins.int\"\n    l = [1, 2]\n    reveal_type(l)  # Revealed type is \"builtins.list[builtins.int]\"\n\n\n.. note::\n\n    Note that mypy will not use type inference in dynamically typed functions\n    (those without a function type annotation) — every local variable type\n    defaults to ``Any`` in such functions. For more details, see :ref:`dynamic-typing`.\n\n    .. code-block:: python\n\n        def untyped_function():\n            i = 1\n            reveal_type(i) # Revealed type is \"Any\"\n                           # 'reveal_type' always outputs 'Any' in unchecked functions\n\n.. _explicit-var-types:\n\nExplicit types for variables\n****************************\n\nYou can override the inferred type of a variable by using a\nvariable type annotation:\n\n.. code-block:: python\n\n   x: int | str = 1\n\nWithout the type annotation, the type of ``x`` would be just ``int``. We\nuse an annotation to give it a more general type ``int | str`` (this\ntype means that the value can be either an ``int`` or a ``str``).\n\nThe best way to think about this is that the type annotation sets the type of\nthe variable, not the type of the expression. For instance, mypy will complain\nabout the following code:\n\n.. code-block:: python\n\n   x: int | str = 1.1  # error: Incompatible types in assignment\n                       # (expression has type \"float\", variable has type \"int | str\")\n\n.. note::\n\n   To explicitly override the type of an expression you can use\n   :py:func:`cast(\\<type\\>, \\<expression\\>) <typing.cast>`.\n   See :ref:`casts` for details.\n\nNote that you can explicitly declare the type of a variable without\ngiving it an initial value:\n\n.. code-block:: python\n\n   # We only unpack two values, so there's no right-hand side value\n   # for mypy to infer the type of \"cs\" from:\n   a, b, *cs = 1, 2  # error: Need type annotation for \"cs\"\n\n   rs: list[int]  # no assignment!\n   p, q, *rs = 1, 2  # OK\n\nExplicit types for collections\n******************************\n\nThe type checker cannot always infer the type of a list or a\ndictionary. This often arises when creating an empty list or\ndictionary and assigning it to a new variable that doesn't have an explicit\nvariable type. Here is an example where mypy can't infer the type\nwithout some help:\n\n.. code-block:: python\n\n   l = []  # Error: Need type annotation for \"l\"\n\nIn these cases you can give the type explicitly using a type annotation:\n\n.. code-block:: python\n\n   l: list[int] = []       # Create empty list of int\n   d: dict[str, int] = {}  # Create empty dictionary (str -> int)\n\n.. note::\n\n   Using type arguments (e.g. ``list[int]``) on builtin collections like\n   :py:class:`list`,  :py:class:`dict`, :py:class:`tuple`, and  :py:class:`set`\n   only works in Python 3.9 and later. For Python 3.8 and earlier, you must use\n   :py:class:`~typing.List` (e.g. ``List[int]``), :py:class:`~typing.Dict`, and\n   so on.\n\n\nCompatibility of container types\n********************************\n\nA quick note: container types can sometimes be unintuitive. We'll discuss this\nmore in :ref:`variance`. For example, the following program generates a mypy error,\nbecause mypy treats ``list[int]`` as incompatible with ``list[object]``:\n\n.. code-block:: python\n\n   def f(l: list[object], k: list[int]) -> None:\n       l = k  # error: Incompatible types in assignment\n\nThe reason why the above assignment is disallowed is that allowing the\nassignment could result in non-int values stored in a list of ``int``:\n\n.. code-block:: python\n\n   def f(l: list[object], k: list[int]) -> None:\n       l = k\n       l.append('x')\n       print(k[-1])  # Ouch; a string in list[int]\n\nOther container types like :py:class:`dict` and :py:class:`set` behave similarly.\n\nYou can still run the above program; it prints ``x``. This illustrates the fact\nthat static types do not affect the runtime behavior of programs. You can run\nprograms with type check failures, which is often very handy when performing a\nlarge refactoring. Thus you can always 'work around' the type system, and it\ndoesn't really limit what you can do in your program.\n\nContext in type inference\n*************************\n\nType inference is *bidirectional* and takes context into account.\n\nMypy will take into account the type of the variable on the left-hand side\nof an assignment when inferring the type of the expression on the right-hand\nside. For example, the following will type check:\n\n.. code-block:: python\n\n   def f(l: list[object]) -> None:\n       l = [1, 2]  # Infer type list[object] for [1, 2], not list[int]\n\n\nThe value expression ``[1, 2]`` is type checked with the additional\ncontext that it is being assigned to a variable of type ``list[object]``.\nThis is used to infer the type of the *expression* as ``list[object]``.\n\nDeclared argument types are also used for type context. In this program\nmypy knows that the empty list ``[]`` should have type ``list[int]`` based\non the declared type of ``arg`` in ``foo``:\n\n.. code-block:: python\n\n    def foo(arg: list[int]) -> None:\n        print('Items:', ', '.join(str(a) for a in arg))\n\n    foo([])  # OK\n\nHowever, context only works within a single statement. Here mypy requires\nan annotation for the empty list, since the context would only be available\nin the following statement:\n\n.. code-block:: python\n\n    def foo(arg: list[int]) -> None:\n        print('Items:', ', '.join(str(a) for a in arg))\n\n    a = []  # Error: Need type annotation for \"a\"\n    foo(a)\n\nWorking around the issue is easy by adding a type annotation:\n\n.. code-block:: Python\n\n    ...\n    a: list[int] = []  # OK\n    foo(a)\n\n.. _silencing-type-errors:\n\nSilencing type errors\n*********************\n\nYou might want to disable type checking on specific lines, or within specific\nfiles in your codebase. To do that, you can use a ``# type: ignore`` comment.\n\nFor example, say in its latest update, the web framework you use can now take an\ninteger argument to ``run()``, which starts it on localhost on that port.\nLike so:\n\n.. code-block:: python\n\n    # Starting app on http://localhost:8000\n    app.run(8000)\n\nHowever, the devs forgot to update their type annotations for\n``run``, so mypy still thinks ``run`` only expects ``str`` types.\nThis would give you the following error:\n\n.. code-block:: text\n\n    error: Argument 1 to \"run\" of \"A\" has incompatible type \"int\"; expected \"str\"\n\nIf you cannot directly fix the web framework yourself, you can temporarily\ndisable type checking on that line, by adding a ``# type: ignore``:\n\n.. code-block:: python\n\n    # Starting app on http://localhost:8000\n    app.run(8000)  # type: ignore\n\nThis will suppress any mypy errors that would have raised on that specific line.\n\nYou should probably add some more information on the ``# type: ignore`` comment,\nto explain why the ignore was added in the first place. This could be a link to\nan issue on the repository responsible for the type stubs, or it could be a\nshort explanation of the bug. To do that, use this format:\n\n.. code-block:: python\n\n    # Starting app on http://localhost:8000\n    app.run(8000)  # type: ignore  # `run()` in v2.0 accepts an `int`, as a port\n\nType ignore error codes\n-----------------------\n\nBy default, mypy displays an error code for each error:\n\n.. code-block:: text\n\n   error: \"str\" has no attribute \"trim\"  [attr-defined]\n\n\nIt is possible to add a specific error-code in your ignore comment (e.g.\n``# type: ignore[attr-defined]``) to clarify what's being silenced. You can\nfind more information about error codes :ref:`here <silence-error-codes>`.\n\nOther ways to silence errors\n----------------------------\n\nYou can get mypy to silence errors about a specific variable by dynamically\ntyping it with ``Any``. See :ref:`dynamic-typing` for more information.\n\n.. code-block:: python\n\n    from typing import Any\n\n    def f(x: Any, y: str) -> None:\n        x = 'hello'\n        x += 1  # OK\n\nYou can ignore all mypy errors in a file by adding a\n``# mypy: ignore-errors`` at the top of the file:\n\n.. code-block:: python\n\n    # mypy: ignore-errors\n    # This is a test file, skipping type checking in it.\n    import unittest\n    ...\n\nYou can also specify per-module configuration options in your :ref:`config-file`.\nFor example:\n\n.. code-block:: ini\n\n    # Don't report errors in the 'package_to_fix_later' package\n    [mypy-package_to_fix_later.*]\n    ignore_errors = True\n\n    # Disable specific error codes in the 'tests' package\n    # Also don't require type annotations\n    [mypy-tests.*]\n    disable_error_code = var-annotated, has-type\n    allow_untyped_defs = True\n\n    # Silence import errors from the 'library_missing_types' package\n    [mypy-library_missing_types.*]\n    ignore_missing_imports = True\n\nFinally, adding a ``@typing.no_type_check`` decorator to a class, method or\nfunction causes mypy to avoid type checking that class, method or function\nand to treat it as not having any type annotations.\n\n.. code-block:: python\n\n    @typing.no_type_check\n    def foo() -> str:\n       return 12345  # No error!\n"
  },
  {
    "path": "docs/source/type_narrowing.rst",
    "content": ".. _type-narrowing:\n\nType narrowing\n==============\n\nThis section is dedicated to several type narrowing\ntechniques which are supported by mypy.\n\nType narrowing is when you convince a type checker that a broader type is actually more specific, for instance, that an object of type ``Shape`` is actually of the narrower type ``Square``.\n\nThe following type narrowing techniques are available:\n\n- :ref:`type-narrowing-expressions`\n- :ref:`casts`\n- :ref:`type-guards`\n- :ref:`typeis`\n\n\n.. _type-narrowing-expressions:\n\nType narrowing expressions\n--------------------------\n\nThe simplest way to narrow a type is to use one of the supported expressions:\n\n- :py:func:`isinstance` like in :code:`isinstance(obj, float)` will narrow ``obj`` to have ``float`` type\n- :py:func:`issubclass` like in :code:`issubclass(cls, MyClass)` will narrow ``cls`` to be ``Type[MyClass]``\n- :py:class:`type` like in :code:`type(obj) is int` will narrow ``obj`` to have ``int`` type\n- :py:func:`callable` like in :code:`callable(obj)` will narrow object to callable type\n- :code:`obj is not None` will narrow object to its :ref:`non-optional form <strict_optional>`\n\nType narrowing is contextual. For example, based on the condition, mypy will narrow an expression only within an ``if`` branch:\n\n.. code-block:: python\n\n  def function(arg: object):\n      if isinstance(arg, int):\n          # Type is narrowed within the ``if`` branch only\n          reveal_type(arg)  # Revealed type: \"builtins.int\"\n      elif isinstance(arg, str) or isinstance(arg, bool):\n          # Type is narrowed differently within this ``elif`` branch:\n          reveal_type(arg)  # Revealed type: \"builtins.str | builtins.bool\"\n\n          # Subsequent narrowing operations will narrow the type further\n          if isinstance(arg, bool):\n              reveal_type(arg)  # Revealed type: \"builtins.bool\"\n\n      # Back outside of the ``if`` statement, the type isn't narrowed:\n      reveal_type(arg)  # Revealed type: \"builtins.object\"\n\nMypy understands the implications ``return`` or exception raising can have\nfor what type an object could be:\n\n.. code-block:: python\n\n  def function(arg: int | str):\n      if isinstance(arg, int):\n          return\n\n      # `arg` can't be `int` at this point:\n      reveal_type(arg)  # Revealed type: \"builtins.str\"\n\nWe can also use ``assert`` to narrow types in the same context:\n\n.. code-block:: python\n\n  def function(arg: Any):\n      assert isinstance(arg, int)\n      reveal_type(arg)  # Revealed type: \"builtins.int\"\n\n.. note::\n\n  With :option:`--warn-unreachable <mypy --warn-unreachable>`\n  narrowing types to some impossible state will be treated as an error.\n\n  .. code-block:: python\n\n     def function(arg: int):\n         # error: Subclass of \"int\" and \"str\" cannot exist:\n         # would have incompatible method signatures\n         assert isinstance(arg, str)\n\n         # error: Statement is unreachable\n         print(\"so mypy concludes the assert will always trigger\")\n\n  Without ``--warn-unreachable`` mypy will simply not check code it deems to be\n  unreachable. See :ref:`unreachable` for more information.\n\n  .. code-block:: python\n\n     x: int = 1\n     assert isinstance(x, str)\n     reveal_type(x)  # Revealed type is \"builtins.int\"\n     print(x + '!')  # Typechecks with `mypy`, but fails in runtime.\n\n\nissubclass\n~~~~~~~~~~\n\nMypy can also use :py:func:`issubclass`\nfor better type inference when working with types and metaclasses:\n\n.. code-block:: python\n\n   class MyCalcMeta(type):\n       @classmethod\n       def calc(cls) -> int:\n           ...\n\n   def f(o: object) -> None:\n       t = type(o)  # We must use a variable here\n       reveal_type(t)  # Revealed type is \"builtins.type\"\n\n       if issubclass(t, MyCalcMeta):  # `issubclass(type(o), MyCalcMeta)` won't work\n           reveal_type(t)  # Revealed type is \"Type[MyCalcMeta]\"\n           t.calc()  # Okay\n\ncallable\n~~~~~~~~\n\nMypy knows what types are callable and which ones are not during type checking.\nSo, we know what ``callable()`` will return. For example:\n\n.. code-block:: python\n\n  from collections.abc import Callable\n\n  x: Callable[[], int]\n\n  if callable(x):\n      reveal_type(x)  # N: Revealed type is \"def () -> builtins.int\"\n  else:\n      ...  # Will never be executed and will raise error with `--warn-unreachable`\n\nThe ``callable`` function can even split union types into\ncallable and non-callable parts:\n\n.. code-block:: python\n\n  from collections.abc import Callable\n\n  x: int | Callable[[], int]\n\n  if callable(x):\n      reveal_type(x)  # N: Revealed type is \"def () -> builtins.int\"\n  else:\n      reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n.. _casts:\n\nCasts\n-----\n\nMypy supports type casts that are usually used to coerce a statically\ntyped value to a subtype. Unlike languages such as Java or C#,\nhowever, mypy casts are only used as hints for the type checker, and they\ndon't perform a runtime type check. Use the function :py:func:`~typing.cast`\nto perform a cast:\n\n.. code-block:: python\n\n   from typing import cast\n\n   o: object = [1]\n   x = cast(list[int], o)  # OK\n   y = cast(list[str], o)  # OK (cast performs no actual runtime check)\n\nTo support runtime checking of casts such as the above, we'd have to check\nthe types of all list items, which would be very inefficient for large lists.\nCasts are used to silence spurious\ntype checker warnings and give the type checker a little help when it can't\nquite understand what is going on.\n\n.. note::\n\n   You can use an assertion if you want to perform an actual runtime check:\n\n   .. code-block:: python\n\n      def foo(o: object) -> None:\n          print(o + 5)  # Error: can't add 'object' and 'int'\n          assert isinstance(o, int)\n          print(o + 5)  # OK: type of 'o' is 'int' here\n\nYou don't need a cast for expressions with type ``Any``, or when\nassigning to a variable with type ``Any``, as was explained earlier.\nYou can also use ``Any`` as the cast target type -- this lets you perform\nany operations on the result. For example:\n\n.. code-block:: python\n\n    from typing import cast, Any\n\n    x = 1\n    x.whatever()  # Type check error\n    y = cast(Any, x)\n    y.whatever()  # Type check OK (runtime error)\n\n\n.. _type-guards:\n\nUser-Defined Type Guards\n------------------------\n\nMypy supports User-Defined Type Guards (:pep:`647`).\n\nA type guard is a way for programs to influence conditional\ntype narrowing employed by a type checker based on runtime checks.\n\nBasically, a ``TypeGuard`` is a \"smart\" alias for a ``bool`` type.\nLet's have a look at the regular ``bool`` example:\n\n.. code-block:: python\n\n  def is_str_list(val: list[object]) -> bool:\n    \"\"\"Determines whether all objects in the list are strings\"\"\"\n    return all(isinstance(x, str) for x in val)\n\n  def func1(val: list[object]) -> None:\n      if is_str_list(val):\n          reveal_type(val)  # Reveals list[object]\n          print(\" \".join(val)) # Error: incompatible type\n\nThe same example with ``TypeGuard``:\n\n.. code-block:: python\n\n  from typing import TypeGuard  # use `typing_extensions` for Python 3.9 and below\n\n  def is_str_list(val: list[object]) -> TypeGuard[list[str]]:\n      \"\"\"Determines whether all objects in the list are strings\"\"\"\n      return all(isinstance(x, str) for x in val)\n\n  def func1(val: list[object]) -> None:\n      if is_str_list(val):\n          reveal_type(val)  # list[str]\n          print(\" \".join(val)) # ok\n\nHow does it work? ``TypeGuard`` narrows the first function argument (``val``)\nto the type specified as the first type parameter (``list[str]``).\n\n.. note::\n\n  Narrowing is\n  `not strict <https://www.python.org/dev/peps/pep-0647/#enforcing-strict-narrowing>`_.\n  For example, you can narrow ``str`` to ``int``:\n\n  .. code-block:: python\n\n    def f(value: str) -> TypeGuard[int]:\n        return True\n\n  Note: since strict narrowing is not enforced, it's easy\n  to break type safety.\n\n  However, there are many ways a determined or uninformed developer can\n  subvert type safety -- most commonly by using cast or Any.\n  If a Python developer takes the time to learn about and implement\n  user-defined type guards within their code,\n  it is safe to assume that they are interested in type safety\n  and will not write their type guard functions in a way\n  that will undermine type safety or produce nonsensical results.\n\nGeneric TypeGuards\n~~~~~~~~~~~~~~~~~~\n\n``TypeGuard`` can also work with generic types (Python 3.12 syntax):\n\n.. code-block:: python\n\n  from typing import TypeGuard  # use `typing_extensions` for `python<3.10`\n\n  def is_two_element_tuple[T](val: tuple[T, ...]) -> TypeGuard[tuple[T, T]]:\n      return len(val) == 2\n\n  def func(names: tuple[str, ...]):\n      if is_two_element_tuple(names):\n          reveal_type(names)  # tuple[str, str]\n      else:\n          reveal_type(names)  # tuple[str, ...]\n\nTypeGuards with parameters\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nType guard functions can accept extra arguments (Python 3.12 syntax):\n\n.. code-block:: python\n\n  from typing import TypeGuard  # use `typing_extensions` for `python<3.10`\n\n  def is_set_of[T](val: set[Any], type: type[T]) -> TypeGuard[set[T]]:\n      return all(isinstance(x, type) for x in val)\n\n  items: set[Any]\n  if is_set_of(items, str):\n      reveal_type(items)  # set[str]\n\nTypeGuards as methods\n~~~~~~~~~~~~~~~~~~~~~\n\nA method can also serve as a ``TypeGuard``:\n\n.. code-block:: python\n\n  class StrValidator:\n      def is_valid(self, instance: object) -> TypeGuard[str]:\n          return isinstance(instance, str)\n\n  def func(to_validate: object) -> None:\n      if StrValidator().is_valid(to_validate):\n          reveal_type(to_validate)  # Revealed type is \"builtins.str\"\n\n.. note::\n\n  Note, that ``TypeGuard``\n  `does not narrow <https://www.python.org/dev/peps/pep-0647/#narrowing-of-implicit-self-and-cls-parameters>`_\n  types of ``self`` or ``cls`` implicit arguments.\n\n  If narrowing of ``self`` or ``cls`` is required,\n  the value can be passed as an explicit argument to a type guard function:\n\n  .. code-block:: python\n\n    class Parent:\n        def method(self) -> None:\n            reveal_type(self)  # Revealed type is \"Parent\"\n            if is_child(self):\n                reveal_type(self)  # Revealed type is \"Child\"\n\n    class Child(Parent):\n        ...\n\n    def is_child(instance: Parent) -> TypeGuard[Child]:\n        return isinstance(instance, Child)\n\nAssignment expressions as TypeGuards\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSometimes you might need to create a new variable and narrow it\nto some specific type at the same time.\nThis can be achieved by using ``TypeGuard`` together\nwith `:= operator <https://docs.python.org/3/whatsnew/3.8.html#assignment-expressions>`_.\n\n.. code-block:: python\n\n  from typing import TypeGuard  # use `typing_extensions` for `python<3.10`\n\n  def is_float(a: object) -> TypeGuard[float]:\n      return isinstance(a, float)\n\n  def main(a: object) -> None:\n      if is_float(x := a):\n          reveal_type(x)  # N: Revealed type is 'builtins.float'\n          reveal_type(a)  # N: Revealed type is 'builtins.object'\n      reveal_type(x)  # N: Revealed type is 'builtins.object'\n      reveal_type(a)  # N: Revealed type is 'builtins.object'\n\nWhat happens here?\n\n1. We create a new variable ``x`` and assign a value of ``a`` to it\n2. We run ``is_float()`` type guard on ``x``\n3. It narrows ``x`` to be ``float`` in the ``if`` context and does not touch ``a``\n\n.. note::\n\n  The same will work with ``isinstance(x := a, float)`` as well.\n\n\n.. _typeis:\n\nTypeIs\n------\n\nMypy supports TypeIs (:pep:`742`).\n\nA `TypeIs narrowing function <https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeis>`_\nallows you to define custom type checks that can narrow the type of a variable\nin `both the if and else <https://docs.python.org/3.13/library/typing.html#typing.TypeIs>`_\nbranches of a conditional, similar to how the built-in isinstance() function works.\n\nTypeIs is new in Python 3.13 — for use in older Python versions, use the backport\nfrom `typing_extensions <https://typing-extensions.readthedocs.io/en/latest/>`_\n\nConsider the following example using TypeIs:\n\n.. code-block:: python\n\n    from typing import TypeIs\n\n    def is_str(x: object) -> TypeIs[str]:\n        return isinstance(x, str)\n\n    def process(x: int | str) -> None:\n        if is_str(x):\n            reveal_type(x)  # Revealed type is 'str'\n            print(x.upper())  # Valid: x is str\n        else:\n            reveal_type(x)  # Revealed type is 'int'\n            print(x + 1)  # Valid: x is int\n\nIn this example, the function is_str is a type narrowing function\nthat returns TypeIs[str]. When used in an if statement, x is narrowed\nto str in the if branch and to int in the else branch.\n\nKey points:\n\n\n- The function must accept at least one positional argument.\n\n- The return type is annotated as ``TypeIs[T]``, where ``T`` is the type you\n  want to narrow to.\n\n- The function must return a ``bool`` value.\n\n- In the ``if`` branch (when the function returns ``True``), the type of the\n  argument is narrowed to the intersection of its original type and ``T``.\n\n- In the ``else`` branch (when the function returns ``False``), the type of\n  the argument is narrowed to the intersection of its original type and the\n  complement of ``T``.\n\n\nTypeIs vs TypeGuard\n~~~~~~~~~~~~~~~~~~~\n\nWhile both TypeIs and TypeGuard allow you to define custom type narrowing\nfunctions, they differ in important ways:\n\n- **Type narrowing behavior**: TypeIs narrows the type in both the if and else branches,\n  whereas TypeGuard narrows only in the if branch.\n\n- **Compatibility requirement**: TypeIs requires that the narrowed type T be\n  compatible with the input type of the function. TypeGuard does not have this restriction.\n\n- **Type inference**: With TypeIs, the type checker may infer a more precise type by\n  combining existing type information with T.\n\nHere's an example demonstrating the behavior with TypeGuard:\n\n.. code-block:: python\n\n    from typing import TypeGuard, reveal_type\n\n    def is_str(x: object) -> TypeGuard[str]:\n        return isinstance(x, str)\n\n    def process(x: int | str) -> None:\n        if is_str(x):\n            reveal_type(x)  # Revealed type is \"builtins.str\"\n            print(x.upper())  # ok: x is str\n        else:\n            reveal_type(x)  # Revealed type is \"Union[builtins.int, builtins.str]\"\n            print(x + 1)  # ERROR: Unsupported operand types for + (\"str\" and \"int\")  [operator]\n\nGeneric TypeIs\n~~~~~~~~~~~~~~\n\n``TypeIs`` functions can also work with generic types:\n\n.. code-block:: python\n\n    from typing import TypeVar, TypeIs\n\n    T = TypeVar('T')\n\n    def is_two_element_tuple(val: tuple[T, ...]) -> TypeIs[tuple[T, T]]:\n        return len(val) == 2\n\n    def process(names: tuple[str, ...]) -> None:\n        if is_two_element_tuple(names):\n            reveal_type(names)  # Revealed type is 'tuple[str, str]'\n        else:\n            reveal_type(names)  # Revealed type is 'tuple[str, ...]'\n\n\nTypeIs with Additional Parameters\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nTypeIs functions can accept additional parameters beyond the first.\nThe type narrowing applies only to the first argument.\n\n.. code-block:: python\n\n    from typing import Any, TypeVar, reveal_type, TypeIs\n\n    T = TypeVar('T')\n\n    def is_instance_of(val: Any, typ: type[T]) -> TypeIs[T]:\n        return isinstance(val, typ)\n\n    def process(x: Any) -> None:\n        if is_instance_of(x, int):\n            reveal_type(x)  # Revealed type is 'int'\n            print(x + 1)  # ok\n        else:\n            reveal_type(x)  # Revealed type is 'Any'\n\nTypeIs in Methods\n~~~~~~~~~~~~~~~~~\n\nA method can also serve as a ``TypeIs`` function. Note that in instance or\nclass methods, the type narrowing applies to the second parameter\n(after ``self`` or ``cls``).\n\n.. code-block:: python\n\n    class Validator:\n        def is_valid(self, instance: object) -> TypeIs[str]:\n            return isinstance(instance, str)\n\n        def process(self, to_validate: object) -> None:\n            if Validator().is_valid(to_validate):\n                reveal_type(to_validate)  # Revealed type is 'str'\n                print(to_validate.upper())  # ok: to_validate is str\n\n\nAssignment Expressions with TypeIs\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nYou can use the assignment expression operator ``:=`` with ``TypeIs`` to create a new variable and narrow its type simultaneously.\n\n.. code-block:: python\n\n    from typing import TypeIs, reveal_type\n\n    def is_float(x: object) -> TypeIs[float]:\n        return isinstance(x, float)\n\n    def main(a: object) -> None:\n        if is_float(x := a):\n            reveal_type(x)  # Revealed type is 'float'\n            # x is narrowed to float in this block\n            print(x + 1.0)\n\n\nLimitations\n-----------\n\nMypy's analysis is limited to individual symbols and it will not track\nrelationships between symbols. For example, in the following code\nit's easy to deduce that if :code:`a` is None then :code:`b` must not be,\ntherefore :code:`a or b` will always be an instance of :code:`C`,\nbut Mypy will not be able to tell that:\n\n.. code-block:: python\n\n    class C:\n        pass\n\n    def f(a: C | None, b: C | None) -> C:\n        if a is not None or b is not None:\n            return a or b  # Incompatible return value type (got \"C | None\", expected \"C\")\n        return C()\n\nTracking these sort of cross-variable conditions in a type checker would add significant complexity\nand performance overhead.\n\nYou can use an ``assert`` to convince the type checker, override it with a :ref:`cast <casts>`\nor rewrite the function to be slightly more verbose:\n\n.. code-block:: python\n\n    def f(a: C | None, b: C | None) -> C:\n        if a is not None:\n            return a\n        elif b is not None:\n            return b\n        return C()\n"
  },
  {
    "path": "docs/source/typed_dict.rst",
    "content": ".. _typeddict:\n\nTypedDict\n*********\n\nPython programs often use dictionaries with string keys to represent objects.\n``TypedDict`` lets you give precise types for dictionaries that represent\nobjects with a fixed schema, such as ``{'id': 1, 'items': ['x']}``.\n\nHere is a typical example:\n\n.. code-block:: python\n\n   movie = {'name': 'Blade Runner', 'year': 1982}\n\nOnly a fixed set of string keys is expected (``'name'`` and\n``'year'`` above), and each key has an independent value type (``str``\nfor ``'name'`` and ``int`` for ``'year'`` above). We've previously\nseen the ``dict[K, V]`` type, which lets you declare uniform\ndictionary types, where every value has the same type, and arbitrary keys\nare supported. This is clearly not a good fit for\n``movie`` above. Instead, you can use a ``TypedDict`` to give a precise\ntype for objects like ``movie``, where the type of each\ndictionary value depends on the key:\n\n.. code-block:: python\n\n   from typing import TypedDict\n\n   Movie = TypedDict('Movie', {'name': str, 'year': int})\n\n   movie: Movie = {'name': 'Blade Runner', 'year': 1982}\n\n``Movie`` is a ``TypedDict`` type with two items: ``'name'`` (with type ``str``)\nand ``'year'`` (with type ``int``). Note that we used an explicit type\nannotation for the ``movie`` variable. This type annotation is\nimportant -- without it, mypy will try to infer a regular, uniform\n:py:class:`dict` type for ``movie``, which is not what we want here.\n\n.. note::\n\n   If you pass a ``TypedDict`` object as an argument to a function, no\n   type annotation is usually necessary since mypy can infer the\n   desired type based on the declared argument type. Also, if an\n   assignment target has been previously defined, and it has a\n   ``TypedDict`` type, mypy will treat the assigned value as a ``TypedDict``,\n   not :py:class:`dict`.\n\nNow mypy will recognize these as valid:\n\n.. code-block:: python\n\n   name = movie['name']  # Okay; type of name is str\n   year = movie['year']  # Okay; type of year is int\n\nMypy will detect an invalid key as an error:\n\n.. code-block:: python\n\n   director = movie['director']  # Error: 'director' is not a valid key\n\nMypy will also reject a runtime-computed expression as a key, as\nit can't verify that it's a valid key. You can only use string\nliterals as ``TypedDict`` keys.\n\nThe ``TypedDict`` type object can also act as a constructor. It\nreturns a normal :py:class:`dict` object at runtime -- a ``TypedDict`` does\nnot define a new runtime type:\n\n.. code-block:: python\n\n   toy_story = Movie(name='Toy Story', year=1995)\n\nThis is equivalent to just constructing a dictionary directly using\n``{ ... }`` or ``dict(key=value, ...)``. The constructor form is\nsometimes convenient, since it can be used without a type annotation,\nand it also makes the type of the object explicit.\n\nLike all types, ``TypedDict``\\s can be used as components to build\narbitrarily complex types. For example, you can define nested\n``TypedDict``\\s and containers with ``TypedDict`` items.\nUnlike most other types, mypy uses structural compatibility checking\n(or structural subtyping) with ``TypedDict``\\s. A ``TypedDict`` object with\nextra items is compatible with (a subtype of) a narrower\n``TypedDict``, assuming item types are compatible (*totality* also affects\nsubtyping, as discussed below).\n\nA ``TypedDict`` object is not a subtype of the regular ``dict[...]``\ntype (and vice versa), since :py:class:`dict` allows arbitrary keys to be\nadded and removed, unlike ``TypedDict``. However, any ``TypedDict`` object is\na subtype of (that is, compatible with) ``Mapping[str, object]``, since\n:py:class:`~collections.abc.Mapping` only provides read-only access to the dictionary items:\n\n.. code-block:: python\n\n   def print_typed_dict(obj: Mapping[str, object]) -> None:\n       for key, value in obj.items():\n           print(f'{key}: {value}')\n\n   print_typed_dict(Movie(name='Toy Story', year=1995))  # OK\n\n.. note::\n\n   Unless you are on Python 3.8 or newer (where ``TypedDict`` is available in\n   standard library :py:mod:`typing` module) you need to install ``typing_extensions``\n   using pip to use ``TypedDict``:\n\n   .. code-block:: text\n\n      python3 -m pip install --upgrade typing-extensions\n\nTotality\n--------\n\nBy default mypy ensures that a ``TypedDict`` object has all the specified\nkeys. This will be flagged as an error:\n\n.. code-block:: python\n\n   # Error: 'year' missing\n   toy_story: Movie = {'name': 'Toy Story'}\n\nSometimes you want to allow keys to be left out when creating a\n``TypedDict`` object. You can provide the ``total=False`` argument to\n``TypedDict(...)`` to achieve this:\n\n.. code-block:: python\n\n   GuiOptions = TypedDict(\n       'GuiOptions', {'language': str, 'color': str}, total=False)\n   options: GuiOptions = {}  # Okay\n   options['language'] = 'en'\n\nYou may need to use :py:meth:`~dict.get` to access items of a partial (non-total)\n``TypedDict``, since indexing using ``[]`` could fail at runtime.\nHowever, mypy still lets use ``[]`` with a partial ``TypedDict`` -- you\njust need to be careful with it, as it could result in a :py:exc:`KeyError`.\nRequiring :py:meth:`~dict.get` everywhere would be too cumbersome. (Note that you\nare free to use :py:meth:`~dict.get` with total ``TypedDict``\\s as well.)\n\nKeys that aren't required are shown with a ``?`` in error messages:\n\n.. code-block:: python\n\n   # Revealed type is \"TypedDict('GuiOptions', {'language'?: builtins.str,\n   #                                            'color'?: builtins.str})\"\n   reveal_type(options)\n\nTotality also affects structural compatibility. You can't use a partial\n``TypedDict`` when a total one is expected. Also, a total ``TypedDict`` is not\nvalid when a partial one is expected.\n\nSupported operations\n--------------------\n\n``TypedDict`` objects support a subset of dictionary operations and methods.\nYou must use string literals as keys when calling most of the methods,\nas otherwise mypy won't be able to check that the key is valid. List\nof supported operations:\n\n* Anything included in :py:class:`~collections.abc.Mapping`:\n\n  * ``d[key]``\n  * ``key in d``\n  * ``len(d)``\n  * ``for key in d`` (iteration)\n  * :py:meth:`d.get(key[, default]) <dict.get>`\n  * :py:meth:`d.keys() <dict.keys>`\n  * :py:meth:`d.values() <dict.values>`\n  * :py:meth:`d.items() <dict.items>`\n\n* :py:meth:`d.copy() <dict.copy>`\n* :py:meth:`d.setdefault(key, default) <dict.setdefault>`\n* :py:meth:`d1.update(d2) <dict.update>`\n* :py:meth:`d.pop(key[, default]) <dict.pop>` (partial ``TypedDict``\\s only)\n* ``del d[key]`` (partial ``TypedDict``\\s only)\n\n.. note::\n\n   :py:meth:`~dict.clear` and :py:meth:`~dict.popitem` are not supported since they are unsafe\n   -- they could delete required ``TypedDict`` items that are not visible to\n   mypy because of structural subtyping.\n\nClass-based syntax\n------------------\n\nAn alternative, class-based syntax to define a ``TypedDict`` is supported\nin Python 3.6 and later:\n\n.. code-block:: python\n\n   from typing import TypedDict  # \"from typing_extensions\" in Python 3.7 and earlier\n\n   class Movie(TypedDict):\n       name: str\n       year: int\n\nThe above definition is equivalent to the original ``Movie``\ndefinition. It doesn't actually define a real class. This syntax also\nsupports a form of inheritance -- subclasses can define additional\nitems. However, this is primarily a notational shortcut. Since mypy\nuses structural compatibility with ``TypedDict``\\s, inheritance is not\nrequired for compatibility. Here is an example of inheritance:\n\n.. code-block:: python\n\n   class Movie(TypedDict):\n       name: str\n       year: int\n\n   class BookBasedMovie(Movie):\n       based_on: str\n\nNow ``BookBasedMovie`` has keys ``name``, ``year`` and ``based_on``.\n\nMixing required and non-required items\n--------------------------------------\n\nIn addition to allowing reuse across ``TypedDict`` types, inheritance also allows\nyou to mix required and non-required (using ``total=False``) items\nin a single ``TypedDict``. Example:\n\n.. code-block:: python\n\n   class MovieBase(TypedDict):\n       name: str\n       year: int\n\n   class Movie(MovieBase, total=False):\n       based_on: str\n\nNow ``Movie`` has required keys ``name`` and ``year``, while ``based_on``\ncan be left out when constructing an object. A ``TypedDict`` with a mix of required\nand non-required keys, such as ``Movie`` above, will only be compatible with\nanother ``TypedDict`` if all required keys in the other ``TypedDict`` are required keys in the\nfirst ``TypedDict``, and all non-required keys of the other ``TypedDict`` are also non-required keys\nin the first ``TypedDict``.\n\nRead-only items\n---------------\n\nYou can use ``typing.ReadOnly``, introduced in Python 3.13, or\n``typing_extensions.ReadOnly`` to mark TypedDict items as read-only (:pep:`705`):\n\n.. code-block:: python\n\n    from typing import TypedDict\n\n    # Or \"from typing ...\" on Python 3.13+\n    from typing_extensions import ReadOnly\n\n    class Movie(TypedDict):\n        name: ReadOnly[str]\n        num_watched: int\n\n    m: Movie = {\"name\": \"Jaws\", \"num_watched\": 1}\n    m[\"name\"] = \"The Godfather\"  # Error: \"name\" is read-only\n    m[\"num_watched\"] += 1  # OK\n\nA TypedDict with a mutable item can be assigned to a TypedDict\nwith a corresponding read-only item, and the type of the item can\nvary :ref:`covariantly <variance-of-generics>`:\n\n.. code-block:: python\n\n    class Entry(TypedDict):\n        name: ReadOnly[str | None]\n        year: ReadOnly[int]\n\n    class Movie(TypedDict):\n        name: str\n        year: int\n\n    def process_entry(i: Entry) -> None: ...\n\n    m: Movie = {\"name\": \"Jaws\", \"year\": 1975}\n    process_entry(m)  # OK\n\nUnions of TypedDicts\n--------------------\n\nSince TypedDicts are really just regular dicts at runtime, it is not possible to\nuse ``isinstance`` checks to distinguish between different variants of a Union of\nTypedDict in the same way you can with regular objects.\n\nInstead, you can use the :ref:`tagged union pattern <tagged_unions>`. The referenced\nsection of the docs has a full description with an example, but in short, you will\nneed to give each TypedDict the same key where each value has a unique\n:ref:`Literal type <literal_types>`. Then, check that key to distinguish\nbetween your TypedDicts.\n\nInline TypedDict types\n----------------------\n\n.. note::\n\n    This is an experimental (non-standard) feature. Use\n    ``--enable-incomplete-feature=InlineTypedDict`` to enable.\n\nSometimes you may want to define a complex nested JSON schema, or annotate\na one-off function that returns a TypedDict. In such cases it may be convenient\nto use inline TypedDict syntax. For example:\n\n.. code-block:: python\n\n    def test_values() -> {\"width\": int, \"description\": str}:\n        return {\"width\": 42, \"description\": \"test\"}\n\n    class Response(TypedDict):\n        status: int\n        msg: str\n        # Using inline syntax here avoids defining two additional TypedDicts.\n        content: {\"items\": list[{\"key\": str, \"value\": str}]}\n\nInline TypedDicts can also by used as targets of type aliases, but due to\nambiguity with a regular variables it is only allowed for (newer) explicit\ntype alias forms:\n\n.. code-block:: python\n\n    from typing import TypeAlias\n\n    X = {\"a\": int, \"b\": int}  # creates a variable with type dict[str, type[int]]\n    Y: TypeAlias = {\"a\": int, \"b\": int}  # creates a type alias\n    type Z = {\"a\": int, \"b\": int}  # same as above (Python 3.12+ only)\n\nAlso, due to incompatibility with runtime type-checking it is strongly recommended\nto *not* use inline syntax in union types.\n"
  },
  {
    "path": "misc/analyze_cache.py",
    "content": "#!/usr/bin/env python\n\nfrom __future__ import annotations\n\nimport json\nimport os\nimport os.path\nfrom collections import Counter\nfrom collections.abc import Iterable\nfrom typing import Any, Final, TypeAlias as _TypeAlias\n\nROOT: Final = \".mypy_cache/3.5\"\n\nJsonDict: _TypeAlias = dict[str, Any]\n\n\nclass CacheData:\n    def __init__(\n        self,\n        filename: str,\n        data_json: JsonDict,\n        meta_json: JsonDict,\n        data_size: int,\n        meta_size: int,\n    ) -> None:\n        self.filename = filename\n        self.data = data_json\n        self.meta = meta_json\n        self.data_size = data_size\n        self.meta_size = meta_size\n\n    @property\n    def total_size(self) -> int:\n        return self.data_size + self.meta_size\n\n\ndef extract_classes(chunks: Iterable[CacheData]) -> Iterable[JsonDict]:\n    def extract(chunks: Iterable[JsonDict]) -> Iterable[JsonDict]:\n        for chunk in chunks:\n            if isinstance(chunk, dict):\n                yield chunk\n                yield from extract(chunk.values())\n            elif isinstance(chunk, list):  # type: ignore[unreachable] #TODO: is this actually unreachable, or are our types wrong?\n                yield from extract(chunk)\n\n    yield from extract([chunk.data for chunk in chunks])\n\n\ndef load_json(data_path: str, meta_path: str) -> CacheData:\n    with open(data_path) as ds:\n        data_json = json.load(ds)\n\n    with open(meta_path) as ms:\n        meta_json = json.load(ms)\n\n    data_size = os.path.getsize(data_path)\n    meta_size = os.path.getsize(meta_path)\n\n    return CacheData(\n        data_path.replace(\".data.json\", \".*.json\"), data_json, meta_json, data_size, meta_size\n    )\n\n\ndef get_files(root: str) -> Iterable[CacheData]:\n    for dirpath, dirnames, filenames in os.walk(root):\n        for filename in filenames:\n            if filename.endswith(\".data.json\"):\n                meta_filename = filename.replace(\".data.json\", \".meta.json\")\n                yield load_json(\n                    os.path.join(dirpath, filename), os.path.join(dirpath, meta_filename)\n                )\n\n\ndef pluck(name: str, chunks: Iterable[JsonDict]) -> Iterable[JsonDict]:\n    return (chunk for chunk in chunks if chunk[\".class\"] == name)\n\n\ndef report_counter(counter: Counter[str], amount: int | None = None) -> None:\n    for name, count in counter.most_common(amount):\n        print(f\"    {count: <8} {name}\")\n    print()\n\n\ndef report_most_common(chunks: list[JsonDict], amount: int | None = None) -> None:\n    report_counter(Counter(str(chunk) for chunk in chunks), amount)\n\n\ndef compress(chunk: JsonDict) -> JsonDict:\n    cache: dict[int, JsonDict] = {}\n    counter = 0\n\n    def helper(chunk: JsonDict) -> JsonDict:\n        nonlocal counter\n        if not isinstance(chunk, dict):\n            return chunk  # type: ignore[unreachable] #TODO: is this actually unreachable, or are our types wrong?\n\n        if len(chunk) <= 2:\n            return chunk\n        id = hash(str(chunk))\n\n        if id in cache:\n            return cache[id]\n        else:\n            cache[id] = {\".id\": counter}\n            chunk[\".cache_id\"] = counter\n            counter += 1\n\n        for name in sorted(chunk.keys()):\n            value = chunk[name]\n            if isinstance(value, list):\n                chunk[name] = [helper(child) for child in value]\n            elif isinstance(value, dict):\n                chunk[name] = helper(value)\n\n        return chunk\n\n    out = helper(chunk)\n    return out\n\n\ndef decompress(chunk: JsonDict) -> JsonDict:\n    cache: dict[int, JsonDict] = {}\n\n    def helper(chunk: JsonDict) -> JsonDict:\n        if not isinstance(chunk, dict):\n            return chunk  # type: ignore[unreachable] #TODO: is this actually unreachable, or are our types wrong?\n        if \".id\" in chunk:\n            return cache[chunk[\".id\"]]\n\n        counter = None\n        if \".cache_id\" in chunk:\n            counter = chunk[\".cache_id\"]\n            del chunk[\".cache_id\"]\n\n        for name in sorted(chunk.keys()):\n            value = chunk[name]\n            if isinstance(value, list):\n                chunk[name] = [helper(child) for child in value]\n            elif isinstance(value, dict):\n                chunk[name] = helper(value)\n\n        if counter is not None:\n            cache[counter] = chunk\n\n        return chunk\n\n    return helper(chunk)\n\n\ndef main() -> None:\n    json_chunks = list(get_files(ROOT))\n    class_chunks = list(extract_classes(json_chunks))\n\n    total_size = sum(chunk.total_size for chunk in json_chunks)\n    print(f\"Total cache size: {total_size / (1024 * 1024):.3f} megabytes\")\n    print()\n\n    class_name_counter = Counter(chunk[\".class\"] for chunk in class_chunks)\n    print(\"Most commonly used classes:\")\n    report_counter(class_name_counter)\n\n    print(\"Most common literal chunks:\")\n    report_most_common(class_chunks, 15)\n\n    build = None\n    for chunk in json_chunks:\n        if \"build.*.json\" in chunk.filename:\n            build = chunk\n            break\n    assert build is not None\n    original = json.dumps(build.data, sort_keys=True)\n    print(f\"Size of build.data.json, in kilobytes: {len(original) / 1024:.3f}\")\n\n    build.data = compress(build.data)\n    compressed = json.dumps(build.data, sort_keys=True)\n    print(f\"Size of compressed build.data.json, in kilobytes: {len(compressed) / 1024:.3f}\")\n\n    build.data = decompress(build.data)\n    decompressed = json.dumps(build.data, sort_keys=True)\n    print(f\"Size of decompressed build.data.json, in kilobytes: {len(decompressed) / 1024:.3f}\")\n\n    print(\"Lossless conversion back\", original == decompressed)\n\n    \"\"\"var_chunks = list(pluck(\"Var\", class_chunks))\n    report_most_common(var_chunks, 20)\n    print()\n\n    #for var in var_chunks:\n    #    if var['fullname'] == 'self' and not (isinstance(var['type'], dict) and var['type']['.class'] == 'AnyType'):\n    #        print(var)\n    #argument_chunks = list(pluck(\"Argument\", class_chunks))\n\n    symbol_table_node_chunks = list(pluck(\"SymbolTableNode\", class_chunks))\n    report_most_common(symbol_table_node_chunks, 20)\n\n    print()\n    print(\"Most common\")\n    report_most_common(class_chunks, 20)\n    print()\"\"\"\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/analyze_typeform_stats.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nAnalyze TypeForm parsing efficiency from mypy build stats.\n\nUsage:\n    python3 analyze_typeform_stats.py '<mypy_output_with_stats>'\n    python3 -m mypy --dump-build-stats file.py 2>&1 | python3 analyze_typeform_stats.py\n\nExample output:\n    TypeForm Expression Parsing Statistics:\n    ==================================================\n    Total calls to SA.try_parse_as_type_expression: 14,555\n    Quick rejections (no full parse): 14,255\n    Full parses attempted: 300\n    - Successful: 248\n    - Failed: 52\n\n    Efficiency Metrics:\n    - Quick rejection rate: 97.9%\n    - Full parse rate: 2.1%\n    - Full parse success rate: 82.7%\n    - Overall success rate: 1.7%\n\n    Performance Implications:\n    - Expensive failed full parses: 52 (0.4% of all calls)\n\nSee also:\n    - mypy/semanal.py: SemanticAnalyzer.try_parse_as_type_expression()\n    - mypy/semanal.py: DEBUG_TYPE_EXPRESSION_FULL_PARSE_FAILURES\n\"\"\"\n\nimport re\nimport sys\n\n\ndef analyze_stats(output: str) -> None:\n    \"\"\"Parse mypy stats output and calculate TypeForm parsing efficiency.\"\"\"\n\n    # Extract the three counters\n    total_match = re.search(r\"type_expression_parse_count:\\s*(\\d+)\", output)\n    success_match = re.search(r\"type_expression_full_parse_success_count:\\s*(\\d+)\", output)\n    failure_match = re.search(r\"type_expression_full_parse_failure_count:\\s*(\\d+)\", output)\n\n    if not (total_match and success_match and failure_match):\n        print(\"Error: Could not find all required counters in output\")\n        return\n\n    total = int(total_match.group(1))\n    successes = int(success_match.group(1))\n    failures = int(failure_match.group(1))\n\n    full_parses = successes + failures\n\n    print(\"TypeForm Expression Parsing Statistics:\")\n    print(\"=\" * 50)\n    print(f\"Total calls to SA.try_parse_as_type_expression: {total:,}\")\n    print(f\"Quick rejections (no full parse): {total - full_parses:,}\")\n    print(f\"Full parses attempted: {full_parses:,}\")\n    print(f\"  - Successful: {successes:,}\")\n    print(f\"  - Failed: {failures:,}\")\n    if total > 0:\n        print()\n        print(\"Efficiency Metrics:\")\n        print(f\"  - Quick rejection rate: {((total - full_parses) / total * 100):.1f}%\")\n        print(f\"  - Full parse rate: {(full_parses / total * 100):.1f}%\")\n        print(f\"  - Full parse success rate: {(successes / full_parses * 100):.1f}%\")\n        print(f\"  - Overall success rate: {(successes / total * 100):.1f}%\")\n        print()\n        print(\"Performance Implications:\")\n        print(\n            f\"  - Expensive failed full parses: {failures:,} ({(failures / total * 100):.1f}% of all calls)\"\n        )\n\n\nif __name__ == \"__main__\":\n    if len(sys.argv) == 1:\n        # Read from stdin\n        output = sys.stdin.read()\n    elif len(sys.argv) == 2:\n        # Read from command line argument\n        output = sys.argv[1]\n    else:\n        print(\"Usage: python3 analyze_typeform_stats.py [mypy_output_with_stats]\")\n        print(\"Examples:\")\n        print(\n            \"  python3 -m mypy --dump-build-stats file.py 2>&1 | python3 analyze_typeform_stats.py\"\n        )\n        print(\"  python3 analyze_typeform_stats.py 'output_string'\")\n        sys.exit(1)\n\n    analyze_stats(output)\n"
  },
  {
    "path": "misc/apply-cache-diff.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Script for applying a cache diff.\n\nWith some infrastructure, this can allow for distributing small cache diffs to users in\nmany cases instead of full cache artifacts.\n\nUse diff-cache.py to generate a cache diff.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport os\nimport sys\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom librt import base64\nfrom librt.internal import ReadBuffer\n\nfrom mypy.cache import CacheMeta\nfrom mypy.metastore import FilesystemMetadataStore, MetadataStore, SqliteMetadataStore\nfrom mypy.util import json_dumps, json_loads\n\n\ndef make_cache(input_dir: str, sqlite: bool) -> MetadataStore:\n    if sqlite:\n        return SqliteMetadataStore(input_dir)\n    else:\n        return FilesystemMetadataStore(input_dir)\n\n\ndef apply_diff(cache_dir: str, diff_file: str, sqlite: bool = False) -> None:\n    cache = make_cache(cache_dir, sqlite)\n    with open(diff_file, \"rb\") as f:\n        diff = json_loads(f.read())\n\n    old_deps = json_loads(cache.read(\"@deps.meta.json\"))\n\n    for file, data in diff.items():\n        if data is None:\n            cache.remove(file)\n        else:\n            if file.endswith(\".ff\"):\n                data_bytes = base64.b64decode(data)\n            else:\n                data_bytes = data.encode() if isinstance(data, str) else data\n            cache.write(file, data_bytes)\n            if file.endswith(\".meta.ff\") and \"@deps\" not in file:\n                buf = ReadBuffer(data_bytes[2:])\n                meta = CacheMeta.read(buf, data_file=\"\")\n                assert meta is not None\n                old_deps[\"snapshot\"][meta.id] = meta.hash\n            elif file.endswith(\".meta.json\") and \"@deps\" not in file:\n                meta_dict = json_loads(data_bytes)\n                old_deps[\"snapshot\"][meta_dict[\"id\"]] = meta_dict[\"hash\"]\n\n    cache.write(\"@deps.meta.json\", json_dumps(old_deps))\n\n    cache.commit()\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--sqlite\", action=\"store_true\", default=False, help=\"Use a sqlite cache\")\n    parser.add_argument(\"cache_dir\", help=\"Directory for the cache\")\n    parser.add_argument(\"diff\", help=\"Cache diff file\")\n    args = parser.parse_args()\n\n    apply_diff(args.cache_dir, args.diff, args.sqlite)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/build-debug-python.sh",
    "content": "#!/bin/bash -eux\n\n# Build a debug build of python, install it, and create a venv for it\n# This is mainly intended for use in our github actions builds but it can work\n# locally. (Though it unfortunately uses brew on OS X to deal with openssl\n# nonsense.)\n# Usage: build-debug-python.sh <version> <install prefix> <venv location>\n#\n# Running it locally might look something like: mkdir -p ~/tmp/cpython-debug && cd ~/tmp/cpython-debug && ~/src/mypy/misc/build-debug-python.sh 3.6.6 ~/tmp/cpython-debug ~/src/mypy/env-debug\n\nVERSION=$1\nPREFIX=$2\nVENV=$3\nif [[ -f $PREFIX/bin/python3 ]]; then\n    exit\nfi\n\nCPPFLAGS=\"\"\nLDFLAGS=\"\"\nif [[ $(uname) == Darwin ]]; then\n    brew install openssl xz\n    CPPFLAGS=\"-I$(brew --prefix openssl)/include\"\n    LDFLAGS=\"-L$(brew --prefix openssl)/lib\"\nfi\n\ncurl -O https://www.python.org/ftp/python/$VERSION/Python-$VERSION.tgz\ntar zxf Python-$VERSION.tgz\ncd Python-$VERSION\nCPPFLAGS=\"$CPPFLAGS\" LDFLAGS=\"$LDFLAGS\" ./configure CFLAGS=\"-DPy_DEBUG -DPy_TRACE_REFS -DPYMALLOC_DEBUG\" --with-pydebug --prefix=$PREFIX --with-trace-refs\nmake -j4\nmake install\n$PREFIX/bin/python3 -m pip install virtualenv\n$PREFIX/bin/python3 -m virtualenv $VENV\nln -s python3-config $PREFIX/bin/python-config\n"
  },
  {
    "path": "misc/build_wheel.py",
    "content": "\"\"\"\nThe main GitHub workflow where wheels are built:\nhttps://github.com/mypyc/mypy_mypyc-wheels/blob/master/.github/workflows/build.yml\n\nThe script that builds wheels:\nhttps://github.com/mypyc/mypy_mypyc-wheels/blob/master/build_wheel.py\n\nThat script is a light wrapper around cibuildwheel. Now that cibuildwheel has native configuration\nand better support for local builds, we could probably replace the script.\n\"\"\"\n\nraise ImportError(\"This script has been moved back to https://github.com/mypyc/mypy_mypyc-wheels\")\n"
  },
  {
    "path": "misc/cherry-pick-typeshed.py",
    "content": "\"\"\"Cherry-pick a commit from typeshed.\n\nUsage:\n\n  python3 misc/cherry-pick-typeshed.py --typeshed-dir dir hash\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport os.path\nimport re\nimport subprocess\nimport sys\nimport tempfile\n\n\ndef parse_commit_title(diff: str) -> str:\n    m = re.search(\"\\n    ([^ ].*)\", diff)\n    assert m is not None, \"Could not parse diff\"\n    return m.group(1)\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--typeshed-dir\", help=\"location of typeshed\", metavar=\"dir\", required=True\n    )\n    parser.add_argument(\"commit\", help=\"typeshed commit hash to cherry-pick\")\n    args = parser.parse_args()\n    typeshed_dir = args.typeshed_dir\n    commit = args.commit\n\n    if not os.path.isdir(typeshed_dir):\n        sys.exit(f\"error: {typeshed_dir} does not exist\")\n    if not re.match(\"[0-9a-fA-F]+$\", commit):\n        sys.exit(f\"error: Invalid commit {commit!r}\")\n\n    if not os.path.exists(\"mypy\") or not os.path.exists(\"mypyc\"):\n        sys.exit(\"error: This script must be run at the mypy repository root directory\")\n\n    with tempfile.TemporaryDirectory() as d:\n        diff_file = os.path.join(d, \"diff\")\n        out = subprocess.run(\n            [\"git\", \"show\", commit], capture_output=True, text=True, check=True, cwd=typeshed_dir\n        )\n        with open(diff_file, \"w\") as f:\n            f.write(out.stdout)\n        subprocess.run(\n            [\n                \"git\",\n                \"apply\",\n                \"--index\",\n                \"--directory=mypy/typeshed\",\n                \"--exclude=**/tests/**\",\n                \"--exclude=**/test_cases/**\",\n                diff_file,\n            ],\n            check=True,\n        )\n\n        title = parse_commit_title(out.stdout)\n        subprocess.run([\"git\", \"commit\", \"-m\", f\"Typeshed cherry-pick: {title}\"], check=True)\n\n    print()\n    print(f\"Cherry-picked commit {commit} from {typeshed_dir}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/clean-mypyc.sh",
    "content": "#!/bin/bash\necho \"Cleaning C/C++ build artifacts...\"\n(cd mypyc/lib-rt; make clean)\n(cd mypyc/external/googletest/make; make clean)\n"
  },
  {
    "path": "misc/convert-cache.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Script for converting between cache formats.\n\nWe support a filesystem tree based cache and a sqlite based cache.\nSee mypy/metastore.py for details.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport re\nimport sys\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nimport argparse\n\nfrom mypy.metastore import FilesystemMetadataStore, MetadataStore, SqliteMetadataStore\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--to-sqlite\",\n        action=\"store_true\",\n        default=False,\n        help=\"Convert to a sqlite cache (default: convert from)\",\n    )\n    parser.add_argument(\n        \"--output_dir\",\n        action=\"store\",\n        default=None,\n        help=\"Output cache location (default: same as input)\",\n    )\n    parser.add_argument(\"input_dir\", help=\"Input directory for the cache\")\n    args = parser.parse_args()\n\n    input_dir = args.input_dir\n    output_dir = args.output_dir or input_dir\n    assert os.path.isdir(output_dir), f\"{output_dir} is not a directory\"\n    if args.to_sqlite:\n        input: MetadataStore = FilesystemMetadataStore(input_dir)\n        output: MetadataStore = SqliteMetadataStore(output_dir)\n    else:\n        fnam = os.path.join(input_dir, \"cache.db\")\n        msg = f\"{fnam} does not exist\"\n        if not re.match(r\"[0-9]+\\.[0-9]+$\", os.path.basename(input_dir)):\n            msg += f\" (are you missing Python version at the end, e.g. {input_dir}/3.11)\"\n        assert os.path.isfile(fnam), msg\n        input, output = SqliteMetadataStore(input_dir), FilesystemMetadataStore(output_dir)\n\n    for s in input.list_all():\n        if s.endswith((\".json\", \".ff\")):\n            assert output.write(\n                s, input.read(s), input.getmtime(s)\n            ), f\"Failed to write cache file {s}!\"\n    output.commit()\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/diff-cache.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Produce a diff between mypy caches.\n\nWith some infrastructure, this can allow for distributing small cache diffs to users in\nmany cases instead of full cache artifacts.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport os\nimport sys\nfrom collections import defaultdict\nfrom typing import Any\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom librt import base64\nfrom librt.internal import ReadBuffer, WriteBuffer\n\nfrom mypy.cache import CacheMeta\nfrom mypy.metastore import FilesystemMetadataStore, MetadataStore, SqliteMetadataStore\nfrom mypy.util import json_dumps, json_loads\n\n\ndef make_cache(input_dir: str, sqlite: bool) -> MetadataStore:\n    if sqlite:\n        return SqliteMetadataStore(input_dir)\n    else:\n        return FilesystemMetadataStore(input_dir)\n\n\ndef merge_deps(all: dict[str, set[str]], new: dict[str, set[str]]) -> None:\n    for k, v in new.items():\n        all.setdefault(k, set()).update(v)\n\n\ndef sort_deps(\n    dependencies: list[str], suppressed: list[str], dep_prios: list[int], dep_lines: list[int]\n) -> tuple[list[str], list[str], list[int], list[int]]:\n    \"\"\"Sort dependencies and suppressed independently, keeping prios/lines aligned.\"\"\"\n    all_deps = list(zip(dependencies + suppressed, dep_prios, dep_lines))\n    num_deps = len(dependencies)\n    sorted_deps = sorted(all_deps[:num_deps])\n    sorted_supp = sorted(all_deps[num_deps:])\n    if sorted_deps:\n        deps_t, prios1_t, lines1_t = zip(*sorted_deps)\n        deps_out = list(deps_t)\n        prios1 = list(prios1_t)\n        lines1 = list(lines1_t)\n    else:\n        deps_out = []\n        prios1 = []\n        lines1 = []\n    if sorted_supp:\n        supp_t, prios2_t, lines2_t = zip(*sorted_supp)\n        supp_out = list(supp_t)\n        prios2 = list(prios2_t)\n        lines2 = list(lines2_t)\n    else:\n        supp_out = []\n        prios2 = []\n        lines2 = []\n    return deps_out, supp_out, prios1 + prios2, lines1 + lines2\n\n\ndef normalize_meta(meta: CacheMeta) -> None:\n    \"\"\"Normalize a CacheMeta instance to avoid spurious diffs.\n\n    Zero out mtimes and sort dependencies deterministically.\n    \"\"\"\n    meta.mtime = 0\n    meta.data_mtime = 0\n    meta.dependencies, meta.suppressed, meta.dep_prios, meta.dep_lines = sort_deps(\n        meta.dependencies, meta.suppressed, meta.dep_prios, meta.dep_lines\n    )\n\n\ndef serialize_meta_ff(meta: CacheMeta, version_prefix: bytes) -> bytes:\n    \"\"\"Serialize a CacheMeta instance back to fixed format binary.\"\"\"\n    buf = WriteBuffer()\n    meta.write(buf)\n    return version_prefix + buf.getvalue()\n\n\ndef normalize_json_meta(obj: dict[str, Any]) -> None:\n    \"\"\"Normalize a JSON meta dict to avoid spurious diffs.\n\n    Zero out mtimes and sort dependencies deterministically.\n    \"\"\"\n    obj[\"mtime\"] = 0\n    obj[\"data_mtime\"] = 0\n    if \"dependencies\" in obj:\n        obj[\"dependencies\"], obj[\"suppressed\"], obj[\"dep_prios\"], obj[\"dep_lines\"] = sort_deps(\n            obj[\"dependencies\"], obj[\"suppressed\"], obj[\"dep_prios\"], obj[\"dep_lines\"]\n        )\n\n\ndef load(cache: MetadataStore, s: str) -> Any:\n    \"\"\"Load and normalize a cache entry.\n\n    Returns:\n      - For .meta.ff: normalized binary bytes (with version prefix)\n      - For .data.ff: raw binary bytes\n      - For .meta.json/.data.json/.deps.json: parsed and normalized dict/list\n    \"\"\"\n    data = cache.read(s)\n    if s.endswith(\".meta.ff\"):\n        version_prefix = data[:2]\n        buf = ReadBuffer(data[2:])\n        meta = CacheMeta.read(buf, data_file=\"\")\n        if meta is None:\n            # Can't deserialize (e.g. different mypy version). Fall back to\n            # raw bytes -- we lose mtime normalization but the diff stays correct.\n            return data\n        normalize_meta(meta)\n        return serialize_meta_ff(meta, version_prefix)\n    if s.endswith((\".data.ff\", \".err.ff\")):\n        return data\n    obj = json_loads(data)\n    if s.endswith(\".meta.json\"):\n        normalize_json_meta(obj)\n    if s.endswith(\".deps.json\"):\n        # For deps files, sort the deps to avoid spurious mismatches\n        for v in obj.values():\n            v.sort()\n    return obj\n\n\ndef encode_for_diff(s: str, obj: object) -> str:\n    \"\"\"Encode a cache entry value for inclusion in the JSON diff.\n\n    Fixed format binary entries are base64-encoded, JSON entries are\n    re-serialized as JSON strings.\n    \"\"\"\n    if isinstance(obj, bytes):\n        return base64.b64encode(obj).decode()\n    return json_dumps(obj).decode()\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--verbose\", action=\"store_true\", default=False, help=\"Increase verbosity\")\n    parser.add_argument(\"--sqlite\", action=\"store_true\", default=False, help=\"Use a sqlite cache\")\n    parser.add_argument(\"input_dir1\", help=\"Input directory for the original cache\")\n    parser.add_argument(\"input_dir2\", help=\"Input directory for the target cache\")\n    parser.add_argument(\"output\", help=\"Output file with the diff from original cache\")\n    args = parser.parse_args()\n\n    cache1 = make_cache(args.input_dir1, args.sqlite)\n    cache2 = make_cache(args.input_dir2, args.sqlite)\n\n    type_misses: dict[str, int] = defaultdict(int)\n    type_hits: dict[str, int] = defaultdict(int)\n\n    updates: dict[str, str | None] = {}\n\n    deps1: dict[str, set[str]] = {}\n    deps2: dict[str, set[str]] = {}\n\n    misses = hits = 0\n    cache1_all = list(cache1.list_all())\n    for s in cache1_all:\n        obj1 = load(cache1, s)\n        try:\n            obj2 = load(cache2, s)\n        except FileNotFoundError:\n            obj2 = None\n\n        typ = s.split(\".\")[-2]\n        if obj1 != obj2:\n            misses += 1\n            type_misses[typ] += 1\n\n            # Collect the dependencies instead of including them directly in the diff\n            # so we can produce a much smaller direct diff of them.\n            if \".deps.\" not in s:\n                if obj2 is not None:\n                    updates[s] = encode_for_diff(s, obj2)\n                else:\n                    updates[s] = None\n            elif obj2:\n                # This is a deps file, with json data\n                assert \".deps.\" in s\n                merge_deps(deps1, obj1)\n                merge_deps(deps2, obj2)\n        else:\n            hits += 1\n            type_hits[typ] += 1\n\n    cache1_all_set = set(cache1_all)\n    for s in cache2.list_all():\n        if s not in cache1_all_set:\n            raw = cache2.read(s)\n            if s.endswith(\".ff\"):\n                updates[s] = base64.b64encode(raw).decode()\n            else:\n                updates[s] = raw.decode()\n\n    # Compute what deps have been added and merge them all into the\n    # @root deps file.\n    new_deps = {k: deps2.get(k, set()) - deps1.get(k, set()) for k in deps2}\n    new_deps = {k: v for k, v in new_deps.items() if v}\n    try:\n        root_deps = load(cache1, \"@root.deps.json\")\n    except FileNotFoundError:\n        root_deps = {}\n    merge_deps(new_deps, root_deps)\n\n    new_deps_json = {k: list(v) for k, v in new_deps.items() if v}\n    updates[\"@root.deps.json\"] = json_dumps(new_deps_json).decode()\n\n    # Drop updates to deps.meta.json for size reasons. The diff\n    # applier will manually fix it up.\n    updates.pop(\"./@deps.meta.json\", None)\n    updates.pop(\"@deps.meta.json\", None)\n\n    ###\n\n    print(\"Generated incremental cache:\", hits, \"hits,\", misses, \"misses\")\n    if args.verbose:\n        print(\"hits\", type_hits)\n        print(\"misses\", type_misses)\n\n    with open(args.output, \"wb\") as f:\n        f.write(json_dumps(updates))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/docker/Dockerfile",
    "content": "FROM ubuntu:latest\n\nWORKDIR /mypy\n\nRUN apt-get update\nRUN apt-get install -y python3 python3-pip clang\n\nCOPY mypy-requirements.txt .\nCOPY test-requirements.txt .\nCOPY build-requirements.txt .\n\nRUN pip3 install -r test-requirements.txt\n"
  },
  {
    "path": "misc/docker/README.md",
    "content": "Running mypy and mypyc tests in a Docker container\n==================================================\n\nThis directory contains scripts for running mypy and mypyc tests in a\nLinux Docker container. This allows running Linux tests on a different\noperating system that supports Docker, or running tests in an\nisolated, predictable environment on a Linux host operating system.\n\nWhy use Docker?\n---------------\n\nMypyc tests can be significantly faster in a Docker container than\nrunning natively on macOS.\n\nAlso, if it's inconvenient to install the necessary dependencies on the\nhost operating system, or there are issues getting some tests to pass\non the host operating system, using a container can be an easy\nworkaround.\n\nPrerequisites\n-------------\n\nFirst install Docker. On macOS, both Docker Desktop (proprietary, but\nwith a free of charge subscription for some use cases) and Colima (MIT\nlicense) should work as runtimes.\n\nYou may have to explicitly start the runtime first. Colima example\n(replace '8' with the number of CPU cores you have):\n\n```\n$ colima start -c 8\n\n```\n\nHow to run tests\n----------------\n\nYou need to build the container with all necessary dependencies before\nyou can run tests:\n\n```\n$ python3 misc/docker/build.py\n```\n\nThis creates a `mypy-test` Docker container that you can use to run\ntests.\n\nYou may need to run the script as root:\n\n```\n$ sudo python3 misc/docker/build.py\n```\n\nIf you have a stale container which isn't up-to-date, use `--no-cache`\n`--pull` to force rebuilding everything:\n\n```\n$ python3 misc/docker/build.py --no-cache --pull\n```\n\nNow you can run tests by using the `misc/docker/run.sh` script. Give\nit the pytest command line you want to run as arguments. For example,\nyou can run mypyc tests like this:\n\n```\n$ misc/docker/run.sh pytest mypyc\n```\n\nYou can also use `-k <filter>`, `-n0`, `-q`, etc.\n\nAgain, you may need to run `run.sh` as root:\n\n```\n$ sudo misc/docker/run.sh pytest mypyc\n```\n\nYou can also use `runtests.py` in the container. Example:\n\n```\n$ misc/docker/run.sh ./runtests.py self lint\n```\n\nNotes\n-----\n\nFile system changes within the container are not visible to the host\nsystem. You can't use the container to format code using Black, for\nexample.\n\nOn a mac, you may want to give additional CPU to the VM used to run\nthe container. The default allocation may be way too low (e.g. 2 CPU\ncores). For example, use the `-c` option when starting the VM if you\nuse Colima:\n\n```\n$ colima start -c 8\n```\n\nGiving access to all available CPUs to the Linux VM tends to provide\nthe best performance. This is not needed on a Linux host, since the\ncontainer is not run in a VM.\n"
  },
  {
    "path": "misc/docker/build.py",
    "content": "\"\"\"Build a \"mypy-test\" Linux Docker container for running mypy/mypyc tests.\n\nThis allows running Linux tests under a non-Linux operating system. Mypyc\ntests can also run much faster under Linux that the host OS.\n\nNOTE: You may need to run this as root (using sudo).\n\nRun with \"--no-cache\" to force reinstallation of mypy dependencies.\nRun with \"--pull\" to force update of the Linux (Ubuntu) base image.\n\nAfter you've built the container, use \"run.sh\" to run tests. Example:\n\n  misc/docker/run.sh pytest mypyc/\n\"\"\"\n\nimport argparse\nimport os\nimport subprocess\nimport sys\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser(\n        description=\"\"\"Build a 'mypy-test' Docker container for running mypy/mypyc tests. You may\n                       need to run this as root (using sudo).\"\"\"\n    )\n    parser.add_argument(\"--no-cache\", action=\"store_true\", help=\"Force rebuilding\")\n    parser.add_argument(\"--pull\", action=\"store_true\", help=\"Force pulling fresh Linux base image\")\n    args = parser.parse_args()\n\n    dockerdir = os.path.dirname(os.path.abspath(__file__))\n    dockerfile = os.path.join(dockerdir, \"Dockerfile\")\n    rootdir = os.path.join(dockerdir, \"..\", \"..\")\n\n    cmdline = [\"docker\", \"build\", \"-t\", \"mypy-test\", \"-f\", dockerfile]\n    if args.no_cache:\n        cmdline.append(\"--no-cache\")\n    if args.pull:\n        cmdline.append(\"--pull\")\n    cmdline.append(rootdir)\n    result = subprocess.run(cmdline)\n    sys.exit(result.returncode)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/docker/run-wrapper.sh",
    "content": "#!/bin/bash\n# Internal wrapper script used to run commands in a container\n\n# Copy all the files we need from the mypy repo directory shared with\n# the host to a local directory. Accessing files using a shared\n# directory on a mac can be *very* slow.\necho \"copying files to the container...\"\ncp -R /repo/{mypy,mypyc,test-data,misc} .\ncp /repo/{pytest.ini,conftest.py,runtests.py,pyproject.toml,setup.cfg} .\ncp /repo/{mypy_self_check.ini,mypy_bootstrap.ini} .\n\n# Run the wrapped command\n\"$@\"\n"
  },
  {
    "path": "misc/docker/run.sh",
    "content": "#!/bin/bash\n# Run mypy or mypyc tests in a Docker container that was built using misc/docker/build.py.\n#\n# Usage: misc/docker/run.sh <command> <arg>...\n#\n# For example, run mypyc tests like this:\n#\n#   misc/docker/run.sh pytest mypyc\n#\n# NOTE: You may need to run this as root (using sudo).\n\nSCRIPT_DIR=$(cd -- \"$( dirname -- \"${BASH_SOURCE[0]}\" )\" &> /dev/null && pwd)\nMYPY_DIR=\"$SCRIPT_DIR/../..\"\n\ndocker run -ti --rm -v \"$MYPY_DIR:/repo\" mypy-test /repo/misc/docker/run-wrapper.sh \"$@\"\n"
  },
  {
    "path": "misc/dump-ast.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nParse source files and print the abstract syntax trees.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport sys\n\nfrom mypy import defaults\nfrom mypy.errors import CompileError, Errors\nfrom mypy.options import Options\nfrom mypy.parse import parse\n\n\ndef dump(fname: str, python_version: tuple[int, int], quiet: bool = False) -> None:\n    options = Options()\n    options.python_version = python_version\n    with open(fname, \"rb\") as f:\n        s = f.read()\n        tree = parse(s, fname, None, errors=Errors(options), options=options)\n        if not quiet:\n            print(tree)\n\n\ndef main() -> None:\n    # Parse a file and dump the AST (or display errors).\n    parser = argparse.ArgumentParser(\n        description=\"Parse source files and print the abstract syntax tree (AST).\"\n    )\n    parser.add_argument(\"--quiet\", action=\"store_true\", help=\"do not print AST\")\n    parser.add_argument(\"FILE\", nargs=\"*\", help=\"files to parse\")\n    args = parser.parse_args()\n\n    status = 0\n    for fname in args.FILE:\n        try:\n            dump(fname, defaults.PYTHON3_VERSION, args.quiet)\n        except CompileError as e:\n            for msg in e.messages:\n                sys.stderr.write(\"%s\\n\" % msg)\n            status = 1\n    sys.exit(status)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/find_type.py",
    "content": "#!/usr/bin/env python3\n# Usage: find_type.py FILENAME START_LINE START_COL END_LINE END_COL MYPY_AND_ARGS\n# Prints out the type of the expression in the given location if the mypy run\n# succeeds cleanly.  Otherwise, prints out the errors encountered.\n# Note: this only works on expressions, and not assignment targets.\n# Note: MYPY_AND_ARGS is should be the remainder of argv, not a single\n# spaces-included argument.\n# NOTE: Line numbers are 1-based; column numbers are 0-based.\n#\n#\n# Example vim usage:\n# function RevealType()\n#   \" Set this to the command you use to run mypy on your project.  Include the mypy invocation.\n#   let mypycmd = 'python3 -m mypy mypy --incremental'\n#   let [startline, startcol] = getpos(\"'<\")[1:2]\n#   let [endline, endcol] = getpos(\"'>\")[1:2]\n#   \" Convert to 0-based column offsets\n#   let startcol = startcol - 1\n#   \" Change this line to point to the find_type.py script.\n#   execute '!python3 /path/to/mypy/misc/find_type.py % ' . startline . ' ' . startcol . ' ' . endline . ' ' . endcol . ' ' . mypycmd\n# endfunction\n# vnoremap <Leader>t :call RevealType()<CR>\n#\n# For an Emacs example, see misc/macs.el.\n\nfrom __future__ import annotations\n\nimport os.path\nimport re\nimport subprocess\nimport sys\nimport tempfile\n\nREVEAL_TYPE_START = \"reveal_type(\"\nREVEAL_TYPE_END = \")\"\n\n\ndef update_line(line: str, s: str, pos: int) -> str:\n    return line[:pos] + s + line[pos:]\n\n\ndef run_mypy(mypy_and_args: list[str], filename: str, tmp_name: str) -> str:\n    proc = subprocess.run(\n        mypy_and_args + [\"--shadow-file\", filename, tmp_name], stdout=subprocess.PIPE\n    )\n    assert isinstance(\n        proc.stdout, bytes\n    )  # Guaranteed to be true because we called run with universal_newlines=False\n    return proc.stdout.decode(encoding=\"utf-8\")\n\n\ndef get_revealed_type(line: str, relevant_file: str, relevant_line: int) -> str | None:\n    m = re.match(r'(.+?):(\\d+): note: Revealed type is \"(.*)\"$', line)\n    if m and int(m.group(2)) == relevant_line and os.path.samefile(relevant_file, m.group(1)):\n        return m.group(3)\n    else:\n        return None\n\n\ndef process_output(output: str, filename: str, start_line: int) -> tuple[str | None, bool]:\n    error_found = False\n    for line in output.splitlines():\n        t = get_revealed_type(line, filename, start_line)\n        if t:\n            return t, error_found\n        elif \"error:\" in line:\n            error_found = True\n    return None, True  # finding no reveal_type is an error\n\n\ndef main() -> None:\n    filename, start_line_str, start_col_str, end_line_str, end_col_str, *mypy_and_args = sys.argv[\n        1:\n    ]\n    start_line = int(start_line_str)\n    start_col = int(start_col_str)\n    end_line = int(end_line_str)\n    end_col = int(end_col_str)\n    with open(filename) as f:\n        lines = f.readlines()\n        lines[end_line - 1] = update_line(\n            lines[end_line - 1], REVEAL_TYPE_END, end_col\n        )  # insert after end_col\n        lines[start_line - 1] = update_line(lines[start_line - 1], REVEAL_TYPE_START, start_col)\n        with tempfile.NamedTemporaryFile(mode=\"w\", prefix=\"mypy\") as tmp_f:\n            tmp_f.writelines(lines)\n            tmp_f.flush()\n\n            output = run_mypy(mypy_and_args, filename, tmp_f.name)\n            revealed_type, error = process_output(output, filename, start_line)\n            if revealed_type:\n                print(revealed_type)\n            if error:\n                print(output)\n            exit(int(error))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/gen_blog_post_html.py",
    "content": "\"\"\"Converter from CHANGELOG.md (Markdown) to HTML suitable for a mypy blog post.\n\nHow to use:\n\n1. Write release notes in CHANGELOG.md.\n2. Make sure the heading for the next release is of form `## Mypy X.Y`.\n2. Run `misc/gen_blog_post_html.py X.Y > target.html`.\n4. Manually inspect and tweak the result.\n\nNotes:\n\n* There are some fragile assumptions. Double check the output.\n\"\"\"\n\nimport argparse\nimport html\nimport os\nimport re\nimport sys\n\n\ndef format_lists(h: str) -> str:\n    a = h.splitlines()\n    r = []\n    i = 0\n    bullets = (\"- \", \"* \", \" * \")\n    while i < len(a):\n        if a[i].startswith(bullets):\n            r.append(\"<p><ul>\")\n            while i < len(a) and a[i].startswith(bullets):\n                r.append(\"<li>%s\" % a[i][2:].lstrip())\n                i += 1\n            r.append(\"</ul>\")\n        else:\n            r.append(a[i])\n            i += 1\n    return \"\\n\".join(r)\n\n\ndef format_code(h: str) -> str:\n    a = h.splitlines()\n    r = []\n    i = 0\n    while i < len(a):\n        if a[i].startswith(\"    \") or a[i].startswith(\"```\"):\n            indent = a[i].startswith(\"    \")\n            language: str = \"\"\n            if not indent:\n                language = a[i][3:]\n                i += 1\n            if language:\n                r.append(f'<pre><code class=\"language-{language}\">')\n            else:\n                r.append(\"<pre><code>\")\n            while i < len(a) and (\n                (indent and a[i].startswith(\"    \")) or (not indent and not a[i].startswith(\"```\"))\n            ):\n                # Undo &gt; and &lt;\n                line = a[i].replace(\"&gt;\", \">\").replace(\"&lt;\", \"<\")\n                if indent:\n                    # Undo this extra level of indentation so it looks nice with\n                    # syntax highlighting CSS.\n                    line = line[4:]\n                r.append(html.escape(line))\n                i += 1\n            r.append(\"</code></pre>\")\n            if not indent and a[i].startswith(\"```\"):\n                i += 1\n        else:\n            r.append(a[i])\n            i += 1\n    formatted = \"\\n\".join(r)\n    # remove empty first line for code blocks\n    return re.sub(r\"<code([^\\>]*)>\\n\", r\"<code\\1>\", formatted)\n\n\ndef convert(src: str) -> str:\n    h = src\n\n    # Replace < and >.\n    h = re.sub(r\"<\", \"&lt;\", h)\n    h = re.sub(r\">\", \"&gt;\", h)\n\n    # Title\n    h = re.sub(r\"^## (Mypy [0-9.]+)\", r\"<h1>\\1 Released</h1>\", h, flags=re.MULTILINE)\n\n    # Subheadings\n    h = re.sub(r\"\\n### ([A-Z`].*)\\n\", r\"\\n<h2>\\1</h2>\\n\", h)\n\n    # Sub-subheadings\n    h = re.sub(r\"\\n\\*\\*([A-Z_`].*)\\*\\*\\n\", r\"\\n<h3>\\1</h3>\\n\", h)\n    h = re.sub(r\"\\n`\\*\\*([A-Z_`].*)\\*\\*\\n\", r\"\\n<h3>`\\1</h3>\\n\", h)\n\n    # Translate `**`\n    h = re.sub(r\"`\\*\\*`\", \"<tt>**</tt>\", h)\n\n    # Paragraphs\n    h = re.sub(r\"\\n\\n([A-Z])\", r\"\\n\\n<p>\\1\", h)\n\n    # Bullet lists\n    h = format_lists(h)\n\n    # Code blocks\n    h = format_code(h)\n\n    # Code fragments\n    h = re.sub(r\"``([^`]+)``\", r\"<tt>\\1</tt>\", h)\n    h = re.sub(r\"`([^`]+)`\", r\"<tt>\\1</tt>\", h)\n\n    # Remove **** noise\n    h = re.sub(r\"\\*\\*\\*\\*\", \"\", h)\n\n    # Bold text\n    h = re.sub(r\"\\*\\*([A-Za-z].*?)\\*\\*\", r\" <b>\\1</b>\", h)\n\n    # Emphasized text\n    h = re.sub(r\" \\*([A-Za-z].*?)\\*\", r\" <i>\\1</i>\", h)\n\n    # Remove redundant PR links to avoid double links (they will be generated below)\n    h = re.sub(r\"\\[(#[0-9]+)\\]\\(https://github.com/python/mypy/pull/[0-9]+/?\\)\", r\"\\1\", h)\n\n    # Issue and PR links\n    h = re.sub(r\"\\((#[0-9]+)\\) +\\(([^)]+)\\)\", r\"(\\2, \\1)\", h)\n    h = re.sub(\n        r\"fixes #([0-9]+)\",\n        r'fixes issue <a href=\"https://github.com/python/mypy/issues/\\1\">\\1</a>',\n        h,\n    )\n    # Note the leading space to avoid stomping on strings that contain #\\d in the middle (such as\n    # links to PRs in other repos)\n    h = re.sub(r\" #([0-9]+)\", r' PR <a href=\"https://github.com/python/mypy/pull/\\1\">\\1</a>', h)\n    h = re.sub(r\"\\) \\(PR\", \", PR\", h)\n\n    # Markdown links\n    h = re.sub(r\"\\[([^]]*)\\]\\(([^)]*)\\)\", r'<a href=\"\\2\">\\1</a>', h)\n\n    # Add random links in case they are missing\n    h = re.sub(\n        r\"contributors to typeshed:\",\n        'contributors to <a href=\"https://github.com/python/typeshed\">typeshed</a>:',\n        h,\n    )\n\n    # Add top-level HTML tags and headers for syntax highlighting css/js.\n    # We're configuring hljs to highlight python and bash code. We can remove\n    # this configure call to make it try all the languages it supports.\n    h = f\"\"\"<html>\n<meta charset=\"utf-8\" />\n<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/a11y-light.min.css\">\n<script src=\"https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js\"></script>\n<script>hljs.configure({{languages:[\"python\",\"bash\"]}});hljs.highlightAll();</script>\n<body>\n{h}\n</body>\n</html>\"\"\"\n\n    return h\n\n\ndef extract_version(src: str, version: str) -> str:\n    a = src.splitlines()\n    i = 0\n    heading = f\"## Mypy {version}\"\n    while i < len(a):\n        if a[i].strip() == heading:\n            break\n        i += 1\n    else:\n        raise RuntimeError(f\"Can't find heading {heading!r}\")\n    j = i + 1\n    while not a[j].startswith(\"## \"):\n        j += 1\n    return \"\\n\".join(a[i:j])\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser(\n        description=\"Generate HTML release blog post based on CHANGELOG.md and write to stdout.\"\n    )\n    parser.add_argument(\"version\", help=\"mypy version, in form X.Y or X.Y.Z\")\n    args = parser.parse_args()\n    version: str = args.version\n    if not re.match(r\"[0-9]+(\\.[0-9]+)+$\", version):\n        sys.exit(f\"error: Version must be of form X.Y or X.Y.Z, not {version!r}\")\n    changelog_path = os.path.join(os.path.dirname(__file__), os.path.pardir, \"CHANGELOG.md\")\n    src = open(changelog_path).read()\n    src = extract_version(src, version)\n    dst = convert(src)\n    sys.stdout.write(dst)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/generate_changelog.py",
    "content": "\"\"\"Generate the changelog for a mypy release.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport re\nimport subprocess\nimport sys\nfrom dataclasses import dataclass\n\n\ndef find_all_release_branches() -> list[tuple[int, int]]:\n    result = subprocess.run([\"git\", \"branch\", \"-r\"], text=True, capture_output=True, check=True)\n    versions = []\n    for line in result.stdout.splitlines():\n        line = line.strip()\n        if m := re.match(r\"origin/release-([0-9]+)\\.([0-9]+)$\", line):\n            major = int(m.group(1))\n            minor = int(m.group(2))\n            versions.append((major, minor))\n    return versions\n\n\ndef git_merge_base(rev1: str, rev2: str) -> str:\n    result = subprocess.run(\n        [\"git\", \"merge-base\", rev1, rev2], text=True, capture_output=True, check=True\n    )\n    return result.stdout.strip()\n\n\n@dataclass\nclass CommitInfo:\n    commit: str\n    author: str\n    title: str\n    pr_number: int | None\n\n\ndef normalize_author(author: str) -> str:\n    # Some ad-hoc rules to get more consistent author names.\n    if author == \"AlexWaygood\":\n        return \"Alex Waygood\"\n    elif author == \"jhance\":\n        return \"Jared Hance\"\n    return author\n\n\ndef git_commit_log(rev1: str, rev2: str) -> list[CommitInfo]:\n    result = subprocess.run(\n        [\"git\", \"log\", \"--pretty=%H\\t%an\\t%s\", f\"{rev1}..{rev2}\"],\n        text=True,\n        capture_output=True,\n        check=True,\n    )\n    commits = []\n    for line in result.stdout.splitlines():\n        commit, author, title = line.strip().split(\"\\t\", 2)\n        pr_number = None\n        if m := re.match(r\".*\\(#([0-9]+)\\) *$\", title):\n            pr_number = int(m.group(1))\n            title = re.sub(r\" *\\(#[0-9]+\\) *$\", \"\", title)\n\n        author = normalize_author(author)\n        entry = CommitInfo(commit, author, title, pr_number)\n        commits.append(entry)\n    return commits\n\n\ndef filter_omitted_commits(commits: list[CommitInfo]) -> list[CommitInfo]:\n    result = []\n    for c in commits:\n        title = c.title\n        keep = True\n        if title.startswith(\"Sync typeshed\"):\n            # Typeshed syncs aren't mentioned in release notes\n            keep = False\n        if title.startswith(\n            (\n                \"Revert sum literal integer change\",\n                \"Remove use of LiteralString in builtins\",\n                \"Revert typeshed ctypes change\",\n            )\n        ):\n            # These are generated by a typeshed sync.\n            keep = False\n        if re.search(r\"(bump|update).*version\", title.lower()):\n            # Version number updates aren't mentioned\n            keep = False\n        if \"pre-commit autoupdate\" in title:\n            keep = False\n        if title.startswith((\"Update commit hashes\", \"Update hashes\")):\n            # Internal tool change\n            keep = False\n        if keep:\n            result.append(c)\n    return result\n\n\ndef normalize_title(title: str) -> str:\n    # We sometimes add a title prefix when cherry-picking commits to a\n    # release branch. Attempt to remove these prefixes so that we can\n    # match them to the corresponding master branch.\n    if m := re.match(r\"\\[release [0-9.]+\\] *\", title, flags=re.I):\n        title = title.replace(m.group(0), \"\")\n    return title\n\n\ndef filter_out_commits_from_old_release_branch(\n    new_commits: list[CommitInfo], old_commits: list[CommitInfo]\n) -> list[CommitInfo]:\n    old_titles = {normalize_title(commit.title) for commit in old_commits}\n    result = []\n    for commit in new_commits:\n        drop = False\n        if normalize_title(commit.title) in old_titles:\n            drop = True\n        if normalize_title(f\"{commit.title} (#{commit.pr_number})\") in old_titles:\n            drop = True\n        if not drop:\n            result.append(commit)\n        else:\n            print(f'NOTE: Drop \"{commit.title}\", since it was in previous release branch')\n    return result\n\n\ndef find_changes_between_releases(old_branch: str, new_branch: str) -> list[CommitInfo]:\n    merge_base = git_merge_base(old_branch, new_branch)\n    print(f\"Merge base: {merge_base}\")\n    new_commits = git_commit_log(merge_base, new_branch)\n    old_commits = git_commit_log(merge_base, old_branch)\n\n    # Filter out some commits that won't be mentioned in release notes.\n    new_commits = filter_omitted_commits(new_commits)\n\n    # Filter out commits cherry-picked to old branch.\n    new_commits = filter_out_commits_from_old_release_branch(new_commits, old_commits)\n\n    return new_commits\n\n\ndef format_changelog_entry(c: CommitInfo) -> str:\n    \"\"\"\n    s = f\" * {c.commit[:9]} - {c.title}\"\n    if c.pr_number:\n        s += f\" (#{c.pr_number})\"\n    s += f\" ({c.author})\"\n    \"\"\"\n    title = c.title.removesuffix(\".\")\n    s = f\" * {title} ({c.author}\"\n    if c.pr_number:\n        s += f\", PR [{c.pr_number}](https://github.com/python/mypy/pull/{c.pr_number})\"\n    s += \")\"\n\n    return s\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser(\n        description=\"Generate draft .md changelog for a mypy public release and print it to stdout.\"\n    )\n    parser.add_argument(\"version\", help=\"target mypy version (form X.Y)\")\n    parser.add_argument(\n        \"--local\", action=\"store_true\", help=\"use local release branch, not origin\"\n    )\n    args = parser.parse_args()\n    version: str = args.version\n    local: bool = args.local\n\n    version = version.removeprefix(\"v\")\n\n    if not re.match(r\"[0-9]+\\.[0-9]+$\", version):\n        sys.exit(f\"error: Release must be of form X.Y (not {version!r})\")\n    major, minor = (int(component) for component in version.split(\".\"))\n\n    if not local:\n        print(\"Running 'git fetch' to fetch all release branches...\")\n        subprocess.run([\"git\", \"fetch\"], check=True)\n\n    if minor > 0:\n        prev_major = major\n        prev_minor = minor - 1\n    else:\n        # For a x.0 release, the previous release is the most recent (x-1).y release.\n        all_releases = sorted(find_all_release_branches())\n        if (major, minor) not in all_releases:\n            sys.exit(f\"error: Can't find release branch for {major}.{minor} at origin\")\n        for i in reversed(range(len(all_releases))):\n            if all_releases[i][0] == major - 1:\n                prev_major, prev_minor = all_releases[i]\n                break\n        else:\n            sys.exit(\"error: Could not determine previous release\")\n    print(f\"Generating changelog for {major}.{minor}\")\n    print(f\"Previous release was     {prev_major}.{prev_minor}\")\n\n    if local:\n        new_branch = f\"release-{major}.{minor}\"\n    else:\n        new_branch = f\"origin/release-{major}.{minor}\"\n    old_branch = f\"origin/release-{prev_major}.{prev_minor}\"\n\n    changes = find_changes_between_releases(old_branch, new_branch)\n\n    print()\n    for c in changes:\n        print(format_changelog_entry(c))\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/incremental_checker.py",
    "content": "#!/usr/bin/env python3\n\"\"\"\nThis file compares the output and runtime of running normal vs incremental mode\non the history of any arbitrary git repo as a way of performing a sanity check\nto make sure incremental mode is working correctly and efficiently.\n\nIt does so by first running mypy without incremental mode on the specified range\nof commits to find the expected result, then rewinds back to the first commit and\nre-runs mypy on the commits with incremental mode enabled to make sure it returns\nthe same results.\n\nThis script will download and test the official mypy repo by default. Running:\n\n    python3 misc/incremental_checker.py last 30\n\nis equivalent to running\n\n    python3 misc/incremental_checker.py last 30 \\\\\n            --repo_url https://github.com/python/mypy.git \\\\\n            --file-path mypy\n\nYou can chose to run this script against a specific commit id or against the\nlast n commits.\n\nTo run this script against the last 30 commits:\n\n    python3 misc/incremental_checker.py last 30\n\nTo run this script starting from the commit id 2a432b:\n\n    python3 misc/incremental_checker.py commit 2a432b\n\"\"\"\n\nfrom __future__ import annotations\n\nimport base64\nimport json\nimport os\nimport random\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport textwrap\nimport time\nfrom argparse import ArgumentParser, Namespace, RawDescriptionHelpFormatter\nfrom typing import Any, Final, TypeAlias as _TypeAlias\n\nCACHE_PATH: Final = \".incremental_checker_cache.json\"\nMYPY_REPO_URL: Final = \"https://github.com/python/mypy.git\"\nMYPY_TARGET_FILE: Final = \"mypy\"\nDAEMON_CMD: Final = [\"python3\", \"-m\", \"mypy.dmypy\"]\n\nJsonDict: _TypeAlias = dict[str, Any]\n\n\ndef print_offset(text: str, indent_length: int = 4) -> None:\n    print()\n    print(textwrap.indent(text, \" \" * indent_length))\n    print()\n\n\ndef delete_folder(folder_path: str) -> None:\n    if os.path.exists(folder_path):\n        shutil.rmtree(folder_path)\n\n\ndef execute(command: list[str], fail_on_error: bool = True) -> tuple[str, str, int]:\n    proc = subprocess.Popen(\n        \" \".join(command), stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True\n    )\n    stdout_bytes, stderr_bytes = proc.communicate()\n    stdout, stderr = stdout_bytes.decode(\"utf-8\"), stderr_bytes.decode(\"utf-8\")\n    if fail_on_error and proc.returncode != 0:\n        print(\"EXECUTED COMMAND:\", repr(command))\n        print(\"RETURN CODE:\", proc.returncode)\n        print()\n        print(\"STDOUT:\")\n        print_offset(stdout)\n        print(\"STDERR:\")\n        print_offset(stderr)\n        raise RuntimeError(\"Unexpected error from external tool.\")\n    return stdout, stderr, proc.returncode\n\n\ndef ensure_environment_is_ready(mypy_path: str, temp_repo_path: str, mypy_cache_path: str) -> None:\n    os.chdir(mypy_path)\n    delete_folder(temp_repo_path)\n    delete_folder(mypy_cache_path)\n\n\ndef initialize_repo(repo_url: str, temp_repo_path: str, branch: str) -> None:\n    print(f\"Cloning repo {repo_url} to {temp_repo_path}\")\n    execute([\"git\", \"clone\", repo_url, temp_repo_path])\n    if branch is not None:\n        print(f\"Checking out branch {branch}\")\n        execute([\"git\", \"-C\", temp_repo_path, \"checkout\", branch])\n\n\ndef get_commits(repo_folder_path: str, commit_range: str) -> list[tuple[str, str]]:\n    raw_data, _stderr, _errcode = execute(\n        [\"git\", \"-C\", repo_folder_path, \"log\", \"--reverse\", \"--oneline\", commit_range]\n    )\n    output = []\n    for line in raw_data.strip().split(\"\\n\"):\n        commit_id, _, message = line.partition(\" \")\n        output.append((commit_id, message))\n    return output\n\n\ndef get_commits_starting_at(repo_folder_path: str, start_commit: str) -> list[tuple[str, str]]:\n    print(f\"Fetching commits starting at {start_commit}\")\n    return get_commits(repo_folder_path, f\"{start_commit}^..HEAD\")\n\n\ndef get_nth_commit(repo_folder_path: str, n: int) -> tuple[str, str]:\n    print(f\"Fetching last {n} commits (or all, if there are fewer commits than n)\")\n    return get_commits(repo_folder_path, f\"-{n}\")[0]\n\n\ndef run_mypy(\n    target_file_path: str | None,\n    mypy_cache_path: str,\n    mypy_script: str | None,\n    *,\n    incremental: bool = False,\n    daemon: bool = False,\n    verbose: bool = False,\n) -> tuple[float, str, dict[str, Any]]:\n    \"\"\"Runs mypy against `target_file_path` and returns what mypy prints to stdout as a string.\n\n    If `incremental` is set to True, this function will use store and retrieve all caching data\n    inside `mypy_cache_path`. If `verbose` is set to True, this function will pass the \"-v -v\"\n    flags to mypy to make it output debugging information.\n\n    If `daemon` is True, we use daemon mode; the daemon must be started and stopped by the caller.\n    \"\"\"\n    stats: dict[str, Any] = {}\n    if daemon:\n        command = DAEMON_CMD + [\"check\", \"-v\"]\n    else:\n        if mypy_script is None:\n            command = [\"python3\", \"-m\", \"mypy\"]\n        else:\n            command = [mypy_script]\n        command.extend([\"--cache-dir\", mypy_cache_path])\n        if incremental:\n            command.append(\"--incremental\")\n        if verbose:\n            command.extend([\"-v\", \"-v\"])\n    if target_file_path is not None:\n        command.append(target_file_path)\n    start = time.time()\n    output, stderr, _ = execute(command, False)\n    if stderr != \"\":\n        output = stderr\n    else:\n        if daemon:\n            output, stats = filter_daemon_stats(output)\n    runtime = time.time() - start\n    return runtime, output, stats\n\n\ndef filter_daemon_stats(output: str) -> tuple[str, dict[str, Any]]:\n    stats: dict[str, Any] = {}\n    lines = output.splitlines()\n    output_lines = []\n    for line in lines:\n        m = re.match(r\"(\\w+)\\s+:\\s+(.*)\", line)\n        if m:\n            key, value = m.groups()\n            stats[key] = value\n        else:\n            output_lines.append(line)\n    if output_lines:\n        output_lines.append(\"\\n\")\n    return \"\\n\".join(output_lines), stats\n\n\ndef start_daemon(mypy_cache_path: str) -> None:\n    cmd = DAEMON_CMD + [\n        \"restart\",\n        \"--log-file\",\n        \"./@incr-chk-logs\",\n        \"--\",\n        \"--cache-dir\",\n        mypy_cache_path,\n    ]\n    execute(cmd)\n\n\ndef stop_daemon() -> None:\n    execute(DAEMON_CMD + [\"stop\"])\n\n\ndef load_cache(incremental_cache_path: str = CACHE_PATH) -> JsonDict:\n    if os.path.exists(incremental_cache_path):\n        with open(incremental_cache_path) as stream:\n            cache = json.load(stream)\n            assert isinstance(cache, dict)\n            return cache\n    else:\n        return {}\n\n\ndef save_cache(cache: JsonDict, incremental_cache_path: str = CACHE_PATH) -> None:\n    with open(incremental_cache_path, \"w\") as stream:\n        json.dump(cache, stream, indent=2)\n\n\ndef set_expected(\n    commits: list[tuple[str, str]],\n    cache: JsonDict,\n    temp_repo_path: str,\n    target_file_path: str | None,\n    mypy_cache_path: str,\n    mypy_script: str | None,\n) -> None:\n    \"\"\"Populates the given `cache` with the expected results for all of the given `commits`.\n\n    This function runs mypy on the `target_file_path` inside the `temp_repo_path`, and stores\n    the result in the `cache`.\n\n    If `cache` already contains results for a particular commit, this function will\n    skip evaluating that commit and move on to the next.\"\"\"\n    for commit_id, message in commits:\n        if commit_id in cache:\n            print(f'Skipping commit (already cached): {commit_id}: \"{message}\"')\n        else:\n            print(f'Caching expected output for commit {commit_id}: \"{message}\"')\n            execute([\"git\", \"-C\", temp_repo_path, \"checkout\", commit_id])\n            runtime, output, stats = run_mypy(\n                target_file_path, mypy_cache_path, mypy_script, incremental=False\n            )\n            cache[commit_id] = {\"runtime\": runtime, \"output\": output}\n            if output == \"\":\n                print(f\"    Clean output ({runtime:.3f} sec)\")\n            else:\n                print(f\"    Output ({runtime:.3f} sec)\")\n                print_offset(output, 8)\n    print()\n\n\ndef test_incremental(\n    commits: list[tuple[str, str]],\n    cache: JsonDict,\n    temp_repo_path: str,\n    target_file_path: str | None,\n    mypy_cache_path: str,\n    *,\n    mypy_script: str | None = None,\n    daemon: bool = False,\n    exit_on_error: bool = False,\n) -> None:\n    \"\"\"Runs incremental mode on all `commits` to verify the output matches the expected output.\n\n    This function runs mypy on the `target_file_path` inside the `temp_repo_path`. The\n    expected output must be stored inside of the given `cache`.\n    \"\"\"\n    print(\"Note: first commit is evaluated twice to warm up cache\")\n    commits = [commits[0]] + commits\n    overall_stats: dict[str, float] = {}\n    for commit_id, message in commits:\n        print(f'Now testing commit {commit_id}: \"{message}\"')\n        execute([\"git\", \"-C\", temp_repo_path, \"checkout\", commit_id])\n        runtime, output, stats = run_mypy(\n            target_file_path, mypy_cache_path, mypy_script, incremental=True, daemon=daemon\n        )\n        relevant_stats = combine_stats(overall_stats, stats)\n        expected_runtime: float = cache[commit_id][\"runtime\"]\n        expected_output: str = cache[commit_id][\"output\"]\n        if output != expected_output:\n            print(\"    Output does not match expected result!\")\n            print(f\"    Expected output ({expected_runtime:.3f} sec):\")\n            print_offset(expected_output, 8)\n            print(f\"    Actual output: ({runtime:.3f} sec):\")\n            print_offset(output, 8)\n            if exit_on_error:\n                break\n        else:\n            print(\"    Output matches expected result!\")\n            print(f\"    Incremental: {runtime:.3f} sec\")\n            print(f\"    Original:    {expected_runtime:.3f} sec\")\n            if relevant_stats:\n                print(f\"    Stats:       {relevant_stats}\")\n    if overall_stats:\n        print(\"Overall stats:\", overall_stats)\n\n\ndef combine_stats(overall_stats: dict[str, float], new_stats: dict[str, Any]) -> dict[str, float]:\n    INTERESTING_KEYS = [\"build_time\", \"gc_time\"]\n    # For now, we only support float keys\n    relevant_stats: dict[str, float] = {}\n    for key in INTERESTING_KEYS:\n        if key in new_stats:\n            value = float(new_stats[key])\n            relevant_stats[key] = value\n            overall_stats[key] = overall_stats.get(key, 0.0) + value\n    return relevant_stats\n\n\ndef cleanup(temp_repo_path: str, mypy_cache_path: str) -> None:\n    delete_folder(temp_repo_path)\n    delete_folder(mypy_cache_path)\n\n\ndef test_repo(\n    target_repo_url: str,\n    temp_repo_path: str,\n    target_file_path: str | None,\n    mypy_path: str,\n    incremental_cache_path: str,\n    mypy_cache_path: str,\n    range_type: str,\n    range_start: str,\n    branch: str,\n    params: Namespace,\n) -> None:\n    \"\"\"Tests incremental mode against the repo specified in `target_repo_url`.\n\n    This algorithm runs in five main stages:\n\n    1.  Clones `target_repo_url` into the `temp_repo_path` folder locally,\n        checking out the specified `branch` if applicable.\n    2.  Examines the repo's history to get the list of all commits to\n        to test incremental mode on.\n    3.  Runs mypy WITHOUT incremental mode against the `target_file_path` (which is\n        assumed to be located inside the `temp_repo_path`), testing each commit\n        discovered in stage two.\n        -   If the results of running mypy WITHOUT incremental mode on a\n            particular commit are already cached inside the `incremental_cache_path`,\n            skip that commit to save time.\n        -   Cache the results after finishing.\n    4.  Rewind back to the first commit, and run mypy WITH incremental mode\n        against the `target_file_path` commit-by-commit, and compare to the expected\n        results found in stage 3.\n    5.  Delete all unnecessary temp files.\n    \"\"\"\n    # Stage 1: Clone repo and get ready to being testing\n    ensure_environment_is_ready(mypy_path, temp_repo_path, mypy_cache_path)\n    initialize_repo(target_repo_url, temp_repo_path, branch)\n\n    # Stage 2: Get all commits we want to test\n    if range_type == \"last\":\n        start_commit = get_nth_commit(temp_repo_path, int(range_start))[0]\n    elif range_type == \"commit\":\n        start_commit = range_start\n    else:\n        raise RuntimeError(f\"Invalid option: {range_type}\")\n    commits = get_commits_starting_at(temp_repo_path, start_commit)\n    if params.limit:\n        commits = commits[: params.limit]\n    if params.sample:\n        seed = params.seed or base64.urlsafe_b64encode(os.urandom(15)).decode(\"ascii\")\n        random.seed(seed)\n        commits = random.sample(commits, params.sample)\n        print(\"Sampled down to %d commits using random seed %s\" % (len(commits), seed))\n\n    # Stage 3: Find and cache expected results for each commit (without incremental mode)\n    cache = load_cache(incremental_cache_path)\n    set_expected(\n        commits,\n        cache,\n        temp_repo_path,\n        target_file_path,\n        mypy_cache_path,\n        mypy_script=params.mypy_script,\n    )\n    save_cache(cache, incremental_cache_path)\n\n    # Stage 4: Rewind and re-run mypy (with incremental mode enabled)\n    if params.daemon:\n        print(\"Starting daemon\")\n        start_daemon(mypy_cache_path)\n    test_incremental(\n        commits,\n        cache,\n        temp_repo_path,\n        target_file_path,\n        mypy_cache_path,\n        mypy_script=params.mypy_script,\n        daemon=params.daemon,\n        exit_on_error=params.exit_on_error,\n    )\n\n    # Stage 5: Remove temp files, stop daemon\n    if not params.keep_temporary_files:\n        cleanup(temp_repo_path, mypy_cache_path)\n    if params.daemon:\n        print(\"Stopping daemon\")\n        stop_daemon()\n\n\ndef main() -> None:\n    help_factory: Any = lambda prog: RawDescriptionHelpFormatter(prog=prog, max_help_position=32)\n    parser = ArgumentParser(\n        prog=\"incremental_checker\", description=__doc__, formatter_class=help_factory\n    )\n\n    parser.add_argument(\n        \"range_type\",\n        metavar=\"START_TYPE\",\n        choices=[\"last\", \"commit\"],\n        help=\"must be one of 'last' or 'commit'\",\n    )\n    parser.add_argument(\n        \"range_start\",\n        metavar=\"COMMIT_ID_OR_NUMBER\",\n        help=\"the commit id to start from, or the number of commits to move back (see above)\",\n    )\n    parser.add_argument(\n        \"-r\",\n        \"--repo_url\",\n        default=MYPY_REPO_URL,\n        metavar=\"URL\",\n        help=\"the repo to clone and run tests on\",\n    )\n    parser.add_argument(\n        \"-f\",\n        \"--file-path\",\n        default=MYPY_TARGET_FILE,\n        metavar=\"FILE\",\n        help=\"the name of the file or directory to typecheck\",\n    )\n    parser.add_argument(\n        \"-x\", \"--exit-on-error\", action=\"store_true\", help=\"Exits as soon as an error occurs\"\n    )\n    parser.add_argument(\n        \"--keep-temporary-files\", action=\"store_true\", help=\"Keep temporary files on exit\"\n    )\n    parser.add_argument(\n        \"--cache-path\",\n        default=CACHE_PATH,\n        metavar=\"DIR\",\n        help=\"sets a custom location to store cache data\",\n    )\n    parser.add_argument(\n        \"--branch\",\n        default=None,\n        metavar=\"NAME\",\n        help=\"check out and test a custom branch uses the default if not specified\",\n    )\n    parser.add_argument(\"--sample\", type=int, help=\"use a random sample of size SAMPLE\")\n    parser.add_argument(\"--seed\", type=str, help=\"random seed\")\n    parser.add_argument(\n        \"--limit\", type=int, help=\"maximum number of commits to use (default until end)\"\n    )\n    parser.add_argument(\"--mypy-script\", type=str, help=\"alternate mypy script to run\")\n    parser.add_argument(\n        \"--daemon\",\n        action=\"store_true\",\n        help=\"use mypy daemon instead of incremental (highly experimental)\",\n    )\n\n    if len(sys.argv[1:]) == 0:\n        parser.print_help()\n        parser.exit()\n\n    params = parser.parse_args(sys.argv[1:])\n\n    # Make all paths absolute so we avoid having to worry about being in the right folder\n\n    # The path to this specific script (incremental_checker.py).\n    script_path = os.path.abspath(sys.argv[0])\n\n    # The path to the mypy repo.\n    mypy_path = os.path.abspath(os.path.dirname(os.path.dirname(script_path)))\n\n    # The folder the cloned repo will reside in.\n    temp_repo_path = os.path.abspath(os.path.join(mypy_path, \"tmp_repo\"))\n\n    # The particular file or package to typecheck inside the repo.\n    if params.file_path:\n        target_file_path = os.path.abspath(os.path.join(temp_repo_path, params.file_path))\n    else:\n        # Allow `-f ''` to clear target_file_path.\n        target_file_path = None\n\n    # The path to where the incremental checker cache data is stored.\n    incremental_cache_path = os.path.abspath(params.cache_path)\n\n    # The path to store the mypy incremental mode cache data\n    mypy_cache_path = os.path.abspath(os.path.join(mypy_path, \"misc\", \".mypy_cache\"))\n\n    print(f\"Assuming mypy is located at {mypy_path}\")\n    print(f\"Temp repo will be cloned at {temp_repo_path}\")\n    print(f\"Testing file/dir located at {target_file_path}\")\n    print(f\"Using cache data located at {incremental_cache_path}\")\n    print()\n\n    test_repo(\n        params.repo_url,\n        temp_repo_path,\n        target_file_path,\n        mypy_path,\n        incremental_cache_path,\n        mypy_cache_path,\n        params.range_type,\n        params.range_start,\n        params.branch,\n        params,\n    )\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/log_trace_check.py",
    "content": "\"\"\"Compile mypy using mypyc with trace logging enabled, and collect a trace.\n\nThe trace log can be used to analyze low-level performance bottlenecks.\n\nBy default does a self check as the workload.\n\nThis works on all supported platforms, unlike some of our other performance tools.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport glob\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport time\n\nfrom perf_compare import build_mypy, clone\n\n# Generated files, including binaries, go under this directory to avoid overwriting user state.\nTARGET_DIR = \"mypy.log_trace.tmpdir\"\n\n\ndef perform_type_check(target_dir: str, code: str | None) -> None:\n    cache_dir = os.path.join(target_dir, \".mypy_cache\")\n    if os.path.exists(cache_dir):\n        shutil.rmtree(cache_dir)\n    args = []\n    if code is None:\n        args.extend([\"--config-file\", \"mypy_self_check.ini\"])\n        for pat in \"mypy/*.py\", \"mypy/*/*.py\", \"mypyc/*.py\", \"mypyc/test/*.py\":\n            args.extend(glob.glob(pat))\n    else:\n        args.extend([\"-c\", code])\n    check_cmd = [\"python\", \"-m\", \"mypy\"] + args\n    t0 = time.time()\n    subprocess.run(check_cmd, cwd=target_dir, check=True)\n    elapsed = time.time() - t0\n    print(f\"{elapsed:.2f}s elapsed\")\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser(\n        description=\"Compile mypy and collect a trace log while type checking (by default, self check).\"\n    )\n    parser.add_argument(\n        \"--multi-file\",\n        action=\"store_true\",\n        help=\"compile mypy into one C file per module (to reduce RAM use during compilation)\",\n    )\n    parser.add_argument(\n        \"--skip-compile\", action=\"store_true\", help=\"use compiled mypy from previous run\"\n    )\n    parser.add_argument(\n        \"-c\",\n        metavar=\"CODE\",\n        default=None,\n        type=str,\n        help=\"type check Python code fragment instead of mypy self-check\",\n    )\n    args = parser.parse_args()\n    multi_file: bool = args.multi_file\n    skip_compile: bool = args.skip_compile\n    code: str | None = args.c\n\n    target_dir = TARGET_DIR\n\n    if not skip_compile:\n        clone(target_dir, \"HEAD\")\n\n        print(f\"Building mypy in {target_dir} with trace logging enabled...\")\n        build_mypy(target_dir, multi_file, log_trace=True, opt_level=\"0\")\n    elif not os.path.isdir(target_dir):\n        sys.exit(\"error: Can't find compile mypy from previous run -- can't use --skip-compile\")\n\n    perform_type_check(target_dir, code)\n\n    trace_fnam = os.path.join(target_dir, \"mypyc_trace.txt\")\n    print(f\"Generated event trace log in {trace_fnam}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/macs.el",
    "content": "; Example Emacs integration; shows type of expression in region.\n\n(defun mypy-show-region ()\n  \"Show type of variable at point.\"\n  (interactive)\n  (let ((here (region-beginning))\n        (there (region-end))\n        (filename (buffer-file-name)))\n    (let ((hereline (line-number-at-pos here))\n          (herecol (save-excursion (goto-char here) (current-column)))\n          (thereline (line-number-at-pos there))\n          (therecol (save-excursion (goto-char there) (current-column))))\n      (shell-command\n       (format \"cd ~/src/mypy; python3 ./misc/find_type.py %s %s %s %s %s python3 -m mypy -i mypy\"\n               filename hereline herecol thereline therecol)\n       )\n      )\n    )\n  )\n\n; I like to bind this to ^X-t.\n(global-set-key \"\\C-xt\" 'mypy-show-region)\n"
  },
  {
    "path": "misc/perf_checker.py",
    "content": "#!/usr/bin/env python3\n\nfrom __future__ import annotations\n\nimport os\nimport shutil\nimport statistics\nimport subprocess\nimport textwrap\nimport time\nfrom collections.abc import Callable\n\n\nclass Command:\n    def __init__(self, setup: Callable[[], None], command: Callable[[], None]) -> None:\n        self.setup = setup\n        self.command = command\n\n\ndef print_offset(text: str, indent_length: int = 4) -> None:\n    print()\n    print(textwrap.indent(text, \" \" * indent_length))\n    print()\n\n\ndef delete_folder(folder_path: str) -> None:\n    if os.path.exists(folder_path):\n        shutil.rmtree(folder_path)\n\n\ndef execute(command: list[str]) -> None:\n    proc = subprocess.Popen(\n        \" \".join(command), stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True\n    )\n    stdout_bytes, stderr_bytes = proc.communicate()\n    stdout, stderr = stdout_bytes.decode(\"utf-8\"), stderr_bytes.decode(\"utf-8\")\n    if proc.returncode != 0:\n        print(\"EXECUTED COMMAND:\", repr(command))\n        print(\"RETURN CODE:\", proc.returncode)\n        print()\n        print(\"STDOUT:\")\n        print_offset(stdout)\n        print(\"STDERR:\")\n        print_offset(stderr)\n        raise RuntimeError(\"Unexpected error from external tool.\")\n\n\ndef trial(num_trials: int, command: Command) -> list[float]:\n    trials = []\n    for i in range(num_trials):\n        command.setup()\n        start = time.time()\n        command.command()\n        delta = time.time() - start\n        trials.append(delta)\n    return trials\n\n\ndef report(name: str, times: list[float]) -> None:\n    print(f\"{name}:\")\n    print(f\"  Times: {times}\")\n    print(f\"  Mean:  {statistics.mean(times)}\")\n    print(f\"  Stdev: {statistics.stdev(times)}\")\n    print()\n\n\ndef main() -> None:\n    trials = 3\n\n    print(\"Testing baseline\")\n    baseline = trial(\n        trials, Command(lambda: None, lambda: execute([\"python3\", \"-m\", \"mypy\", \"mypy\"]))\n    )\n    report(\"Baseline\", baseline)\n\n    print(\"Testing cold cache\")\n    cold_cache = trial(\n        trials,\n        Command(\n            lambda: delete_folder(\".mypy_cache\"),\n            lambda: execute([\"python3\", \"-m\", \"mypy\", \"-i\", \"mypy\"]),\n        ),\n    )\n    report(\"Cold cache\", cold_cache)\n\n    print(\"Testing warm cache\")\n    execute([\"python3\", \"-m\", \"mypy\", \"-i\", \"mypy\"])\n    warm_cache = trial(\n        trials, Command(lambda: None, lambda: execute([\"python3\", \"-m\", \"mypy\", \"-i\", \"mypy\"]))\n    )\n    report(\"Warm cache\", warm_cache)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/perf_compare.py",
    "content": "#! /usr/bin/env python\n\n\"\"\"Compare performance of mypyc-compiled mypy between one or more commits/branches.\n\nSimple usage:\n\n  python misc/perf_compare.py master my-branch ...\n\nWhat this does:\n\n * Create a temp clone of the mypy repo for each target commit to measure\n * Checkout a target commit in each of the clones\n * Compile mypyc in each of the clones *in parallel*\n * Create another temp clone of the first provided revision (or, with -r, a foreign repo) as the code to check\n * Self check with each of the compiled mypys N times\n * Report the average runtimes and relative performance\n * Remove the temp clones\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport glob\nimport os\nimport random\nimport shutil\nimport statistics\nimport subprocess\nimport sys\nimport time\nfrom concurrent.futures import ThreadPoolExecutor, as_completed\n\n\ndef heading(s: str) -> None:\n    print()\n    print(f\"=== {s} ===\")\n    print()\n\n\ndef build_mypy(\n    target_dir: str,\n    multi_file: bool,\n    *,\n    cflags: str | None = None,\n    log_trace: bool = False,\n    opt_level: str = \"2\",\n) -> None:\n    env = os.environ.copy()\n    env[\"CC\"] = \"clang\"\n    env[\"MYPYC_OPT_LEVEL\"] = opt_level\n    env[\"PYTHONHASHSEED\"] = \"1\"\n    if multi_file:\n        env[\"MYPYC_MULTI_FILE\"] = \"1\"\n    if log_trace:\n        env[\"MYPYC_LOG_TRACE\"] = \"1\"\n    if cflags is not None:\n        env[\"CFLAGS\"] = cflags\n    cmd = [sys.executable, \"setup.py\", \"--use-mypyc\", \"build_ext\", \"--inplace\"]\n    subprocess.run(cmd, env=env, check=True, cwd=target_dir)\n\n\ndef clone(target_dir: str, commit: str | None, repo_source: str | None = None) -> None:\n    source_name = repo_source or \"mypy\"\n    heading(f\"Cloning {source_name} to {target_dir}\")\n    if repo_source is None:\n        repo_source = os.getcwd()\n    if os.path.isdir(target_dir):\n        print(f\"{target_dir} exists: deleting\")\n        shutil.rmtree(target_dir)\n    subprocess.run([\"git\", \"clone\", repo_source, target_dir], check=True)\n    if commit:\n        subprocess.run([\"git\", \"checkout\", commit], check=True, cwd=target_dir)\n\n\ndef edit_python_file(fnam: str) -> None:\n    with open(fnam) as f:\n        data = f.read()\n    data += \"\\n#\"\n    with open(fnam, \"w\") as f:\n        f.write(data)\n\n\ndef run_benchmark(\n    compiled_dir: str, check_dir: str, *, incremental: bool, code: str | None, foreign: bool | None\n) -> float:\n    cache_dir = os.path.join(compiled_dir, \".mypy_cache\")\n    if os.path.isdir(cache_dir) and not incremental:\n        shutil.rmtree(cache_dir)\n    env = os.environ.copy()\n    env[\"PYTHONPATH\"] = os.path.abspath(compiled_dir)\n    env[\"PYTHONHASHSEED\"] = \"1\"\n    abschk = os.path.abspath(check_dir)\n    cmd = [sys.executable, \"-m\", \"mypy\"]\n    if code:\n        cmd += [\"-c\", code]\n    elif foreign:\n        pass\n    else:\n        cmd += [\"--config-file\", os.path.join(abschk, \"mypy_self_check.ini\")]\n        cmd += glob.glob(os.path.join(abschk, \"mypy/*.py\"))\n        cmd += glob.glob(os.path.join(abschk, \"mypy/*/*.py\"))\n        if incremental:\n            # Update a few files to force non-trivial incremental run\n            edit_python_file(os.path.join(abschk, \"mypy/__main__.py\"))\n            edit_python_file(os.path.join(abschk, \"mypy/test/testcheck.py\"))\n    t0 = time.time()\n    # Ignore errors, since some commits being measured may generate additional errors.\n    if foreign:\n        subprocess.run(cmd, cwd=check_dir, env=env)\n    else:\n        subprocess.run(cmd, cwd=compiled_dir, env=env)\n    return time.time() - t0\n\n\ndef main() -> None:\n    whole_program_time_0 = time.time()\n    parser = argparse.ArgumentParser(\n        formatter_class=argparse.RawDescriptionHelpFormatter,\n        description=__doc__,\n        epilog=\"Remember: you usually want the first argument to this command to be 'master'.\",\n    )\n    parser.add_argument(\n        \"--incremental\",\n        default=False,\n        action=\"store_true\",\n        help=\"measure incremental run (fully cached)\",\n    )\n    parser.add_argument(\n        \"--multi-file\",\n        default=False,\n        action=\"store_true\",\n        help=\"compile each mypy module to a separate C file (reduces RAM use)\",\n    )\n    parser.add_argument(\n        \"--dont-setup\",\n        default=False,\n        action=\"store_true\",\n        help=\"don't make the clones or compile mypy, just run the performance measurement benchmark \"\n        + \"(this will fail unless the clones already exist, such as from a previous run that was canceled before it deleted them)\",\n    )\n    parser.add_argument(\n        \"--num-runs\",\n        metavar=\"N\",\n        default=15,\n        type=int,\n        help=\"set number of measurements to perform (default=15)\",\n    )\n    parser.add_argument(\n        \"-j\",\n        metavar=\"N\",\n        default=4,\n        type=int,\n        help=\"set maximum number of parallel builds (default=4) -- high numbers require a lot of RAM!\",\n    )\n    parser.add_argument(\n        \"-r\",\n        metavar=\"FOREIGN_REPOSITORY\",\n        default=None,\n        type=str,\n        help=\"measure time to typecheck the project at FOREIGN_REPOSITORY instead of mypy self-check; \"\n        + \"the provided value must be the URL or path of a git repo \"\n        + \"(note that this script will take no special steps to *install* the foreign repo, so you will probably get a lot of missing import errors)\",\n    )\n    parser.add_argument(\n        \"-c\",\n        metavar=\"CODE\",\n        default=None,\n        type=str,\n        help=\"measure time to type check Python code fragment instead of mypy self-check\",\n    )\n    parser.add_argument(\n        \"commit\",\n        nargs=\"+\",\n        help=\"git revision(s), e.g. branch name or commit id, to measure the performance of\",\n    )\n    args = parser.parse_args()\n    incremental: bool = args.incremental\n    dont_setup: bool = args.dont_setup\n    multi_file: bool = args.multi_file\n    commits = args.commit\n    num_runs: int = args.num_runs + 1\n    max_workers: int = args.j\n    code: str | None = args.c\n    foreign_repo: str | None = args.r\n\n    if not (os.path.isdir(\".git\") and os.path.isdir(\"mypyc\")):\n        sys.exit(\"error: You must run this script from the mypy repo root\")\n\n    target_dirs = []\n    for i, commit in enumerate(commits):\n        target_dir = f\"mypy.{i}.tmpdir\"\n        target_dirs.append(target_dir)\n        if not dont_setup:\n            clone(target_dir, commit)\n\n    if foreign_repo:\n        check_dir = \"mypy.foreign.tmpdir\"\n        if not dont_setup:\n            clone(check_dir, None, foreign_repo)\n    else:\n        check_dir = \"mypy.self.tmpdir\"\n        if not dont_setup:\n            clone(check_dir, commits[0])\n\n    if not dont_setup:\n        heading(\"Compiling mypy\")\n        print(\"(This will take a while...)\")\n\n        with ThreadPoolExecutor(max_workers=max_workers) as executor:\n            futures = [\n                executor.submit(build_mypy, target_dir, multi_file) for target_dir in target_dirs\n            ]\n            for future in as_completed(futures):\n                future.result()\n\n        print(f\"Finished compiling mypy ({len(commits)} builds)\")\n\n    heading(\"Performing measurements\")\n\n    results: dict[str, list[float]] = {}\n    for n in range(num_runs):\n        if n == 0:\n            print(\"Warmup...\")\n        else:\n            print(f\"Run {n}/{num_runs - 1}...\")\n        items = list(enumerate(commits))\n        random.shuffle(items)\n        for i, commit in items:\n            tt = run_benchmark(\n                target_dirs[i],\n                check_dir,\n                incremental=incremental,\n                code=code,\n                foreign=bool(foreign_repo),\n            )\n            # Don't record the first warm-up run\n            if n > 0:\n                print(f\"{commit}: t={tt:.3f}s\")\n                results.setdefault(commit, []).append(tt)\n\n    print()\n    heading(\"Results\")\n    first = -1.0\n    for commit in commits:\n        tt = statistics.mean(results[commit])\n        # pstdev (instead of stdev) is used here primarily to accommodate the case where num_runs=1\n        s = statistics.pstdev(results[commit]) if len(results[commit]) > 1 else 0\n        if first < 0:\n            delta = \"0.0%\"\n            first = tt\n        else:\n            d = (tt / first) - 1\n            delta = f\"{d:+.1%}\"\n        print(f\"{commit:<25} {tt:.3f}s ({delta}) | stdev {s:.3f}s \")\n\n    t = int(time.time() - whole_program_time_0)\n    total_time_taken_formatted = \", \".join(\n        f\"{v} {n if v==1 else n+'s'}\"\n        for v, n in ((t // 3600, \"hour\"), (t // 60 % 60, \"minute\"), (t % 60, \"second\"))\n        if v\n    )\n    print(\n        \"Total time taken by the whole benchmarking program (including any setup):\",\n        total_time_taken_formatted,\n    )\n\n    shutil.rmtree(check_dir)\n    for target_dir in target_dirs:\n        shutil.rmtree(target_dir)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/profile_check.py",
    "content": "\"\"\"Compile mypy using mypyc and profile type checking using perf.\n\nBy default does a self check.\n\nNotes:\n - Only Linux is supported for now (TODO: add support for other profilers)\n - The profile is collected at C level\n   - It includes C functions compiled by mypyc and CPython runtime functions\n - The names of mypy functions are mangled to C names, but usually it's clear what they mean\n   - Generally CPyDef_ prefix for native functions and CPyPy_ prefix for wrapper functions\n - It's important to compile CPython using special flags (see below) to get good results\n - Generally use the latest Python feature release (or the most recent beta if supported by mypyc)\n - The tool prints a command that can be used to analyze the profile afterwards\n\nYou may need to adjust kernel parameters temporarily, e.g. this (note that this has security\nimplications):\n\n  sudo sysctl kernel.perf_event_paranoid=-1\n\nThis is the recommended way to configure CPython for profiling:\n\n  ./configure \\\n      --enable-optimizations \\\n      --with-lto \\\n      CFLAGS=\"-O2 -g -fno-omit-frame-pointer\"\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport glob\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport time\n\nfrom perf_compare import build_mypy, clone\n\n# Use these C compiler flags when compiling mypy (important). Note that it's strongly recommended\n# to also compile CPython using similar flags, but we don't enforce it in this script.\nCFLAGS = \"-O2 -fno-omit-frame-pointer -g\"\n\n# Generated files, including binaries, go under this directory to avoid overwriting user state.\nTARGET_DIR = \"mypy.profile.tmpdir\"\n\n\ndef _profile_type_check(target_dir: str, code: str | None) -> None:\n    cache_dir = os.path.join(target_dir, \".mypy_cache\")\n    if os.path.exists(cache_dir):\n        shutil.rmtree(cache_dir)\n    args = []\n    if code is None:\n        args.extend([\"--config-file\", \"mypy_self_check.ini\"])\n        for pat in \"mypy/*.py\", \"mypy/*/*.py\", \"mypyc/*.py\", \"mypyc/test/*.py\":\n            args.extend(glob.glob(pat))\n    else:\n        args.extend([\"-c\", code])\n    check_cmd = [\"python\", \"-m\", \"mypy\"] + args\n    cmdline = [\"perf\", \"record\", \"-g\"] + check_cmd\n    t0 = time.time()\n    subprocess.run(cmdline, cwd=target_dir, check=True)\n    elapsed = time.time() - t0\n    print(f\"{elapsed:.2f}s elapsed\")\n\n\ndef profile_type_check(target_dir: str, code: str | None) -> None:\n    try:\n        _profile_type_check(target_dir, code)\n    except subprocess.CalledProcessError:\n        print(\"\\nProfiling failed! You may missing some permissions.\")\n        print(\"\\nThis may help (note that it has security implications):\")\n        print(\"  sudo sysctl kernel.perf_event_paranoid=-1\")\n        sys.exit(1)\n\n\ndef check_requirements() -> None:\n    if sys.platform != \"linux\":\n        # TODO: How to make this work on other platforms?\n        sys.exit(\"error: Only Linux is supported\")\n    else:  # fun fact/todo: we have to use else here, because of https://github.com/python/mypy/issues/10773\n        try:\n            subprocess.run([\"perf\", \"-h\"], capture_output=True)\n        except (subprocess.CalledProcessError, FileNotFoundError):\n            print(\"error: The 'perf' profiler is not installed\")\n            sys.exit(1)\n\n        try:\n            subprocess.run([\"clang\", \"--version\"], capture_output=True)\n        except (subprocess.CalledProcessError, FileNotFoundError):\n            print(\"error: The clang compiler is not installed\")\n            sys.exit(1)\n\n        if not os.path.isfile(\"mypy_self_check.ini\"):\n            print(\"error: Run this in the mypy repository root\")\n            sys.exit(1)\n\n\ndef main() -> None:\n    check_requirements()\n\n    parser = argparse.ArgumentParser(\n        description=\"Compile mypy and profile type checking using 'perf' (by default, self check).\"\n    )\n    parser.add_argument(\n        \"--multi-file\",\n        action=\"store_true\",\n        help=\"compile mypy into one C file per module (to reduce RAM use during compilation)\",\n    )\n    parser.add_argument(\n        \"--skip-compile\", action=\"store_true\", help=\"use compiled mypy from previous run\"\n    )\n    parser.add_argument(\n        \"-c\",\n        metavar=\"CODE\",\n        default=None,\n        type=str,\n        help=\"profile type checking Python code fragment instead of mypy self-check\",\n    )\n    args = parser.parse_args()\n    multi_file: bool = args.multi_file\n    skip_compile: bool = args.skip_compile\n    code: str | None = args.c\n\n    target_dir = TARGET_DIR\n\n    if not skip_compile:\n        clone(target_dir, \"HEAD\")\n\n        print(f\"Building mypy in {target_dir}...\")\n        build_mypy(target_dir, multi_file, cflags=CFLAGS)\n    elif not os.path.isdir(target_dir):\n        sys.exit(\"error: Can't find compile mypy from previous run -- can't use --skip-compile\")\n\n    profile_type_check(target_dir, code)\n\n    print()\n    print('NOTE: Compile CPython using CFLAGS=\"-O2 -g -fno-omit-frame-pointer\" for good results')\n    print()\n    print(\"CPU profile collected. You can now analyze the profile:\")\n    print(f\"  perf report -i {target_dir}/perf.data \")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/self_compile_info.py",
    "content": "\"\"\"Print list of files compiled when compiling self (mypy and mypyc).\"\"\"\n\nimport argparse\nimport sys\nfrom typing import Any\n\nimport setuptools\n\nimport mypyc.build\n\n\nclass FakeExtension:\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        pass\n\n\ndef fake_mypycify(args: list[str], **kwargs: Any) -> list[FakeExtension]:\n    for target in sorted(args):\n        if not target.startswith(\"-\"):\n            print(target)\n    return [FakeExtension()]\n\n\ndef fake_setup(*args: Any, **kwargs: Any) -> Any:\n    pass\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser(\n        description=\"Print list of files compiled when compiling self. Run in repository root.\"\n    )\n    parser.parse_args()\n\n    # Prepare fake state for running setup.py.\n    mypyc.build.mypycify = fake_mypycify  # type: ignore[assignment]\n    setuptools.Extension = FakeExtension  # type: ignore[misc, assignment]\n    setuptools.setup = fake_setup\n    sys.argv = [sys.argv[0], \"--use-mypyc\"]\n\n    # Run setup.py at the root of the repository.\n    import setup  # noqa: F401\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/sync-typeshed.py",
    "content": "\"\"\"Sync stdlib stubs (and a few other files) from typeshed.\n\nUsage:\n\n  python3 misc/sync-typeshed.py [--commit hash] [--typeshed-dir dir]\n\nBy default, sync to the latest typeshed commit.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport functools\nimport glob\nimport os\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport textwrap\nfrom collections.abc import Mapping\n\nimport requests\n\n\ndef check_state() -> None:\n    if not os.path.isfile(\"pyproject.toml\") or not os.path.isdir(\"mypy\"):\n        sys.exit(\"error: The current working directory must be the mypy repository root\")\n    out = subprocess.check_output([\"git\", \"status\", \"-s\", os.path.join(\"mypy\", \"typeshed\")])\n    if out:\n        # If there are local changes under mypy/typeshed, they would be lost.\n        sys.exit('error: Output of \"git status -s mypy/typeshed\" must be empty')\n\n\ndef update_typeshed(typeshed_dir: str, commit: str | None) -> str:\n    \"\"\"Update contents of local typeshed copy.\n\n    We maintain our own separate mypy_extensions stubs, since it's\n    treated specially by mypy and we make assumptions about what's there.\n    We don't sync mypy_extensions stubs here -- this is done manually.\n\n    Return the normalized typeshed commit hash.\n    \"\"\"\n    assert os.path.isdir(os.path.join(typeshed_dir, \"stdlib\"))\n    if commit:\n        subprocess.run([\"git\", \"checkout\", commit], check=True, cwd=typeshed_dir)\n    commit = git_head_commit(typeshed_dir)\n\n    stdlib_dir = os.path.join(\"mypy\", \"typeshed\", \"stdlib\")\n    # Remove existing stubs.\n    shutil.rmtree(stdlib_dir)\n    # Copy new stdlib stubs.\n    shutil.copytree(\n        os.path.join(typeshed_dir, \"stdlib\"), stdlib_dir, ignore=shutil.ignore_patterns(\"@tests\")\n    )\n    shutil.copy(os.path.join(typeshed_dir, \"LICENSE\"), os.path.join(\"mypy\", \"typeshed\"))\n    return commit\n\n\ndef git_head_commit(repo: str) -> str:\n    commit = subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=repo).decode(\"ascii\")\n    return commit.strip()\n\n\n@functools.cache\ndef get_github_api_headers() -> Mapping[str, str]:\n    headers = {\"Accept\": \"application/vnd.github.v3+json\"}\n    secret = os.environ.get(\"GITHUB_TOKEN\")\n    if secret is not None:\n        headers[\"Authorization\"] = (\n            f\"token {secret}\" if secret.startswith(\"ghp\") else f\"Bearer {secret}\"\n        )\n    return headers\n\n\n@functools.cache\ndef get_origin_owner() -> str:\n    output = subprocess.check_output([\"git\", \"remote\", \"get-url\", \"origin\"], text=True).strip()\n    match = re.match(\n        r\"(git@github.com:|https://github.com/)(?P<owner>[^/]+)/(?P<repo>[^/\\s]+)\", output\n    )\n    assert match is not None, f\"Couldn't identify origin's owner: {output!r}\"\n    assert (\n        match.group(\"repo\").removesuffix(\".git\") == \"mypy\"\n    ), f'Unexpected repo: {match.group(\"repo\")!r}'\n    return match.group(\"owner\")\n\n\ndef create_or_update_pull_request(*, title: str, body: str, branch_name: str) -> None:\n    fork_owner = get_origin_owner()\n\n    with requests.post(\n        \"https://api.github.com/repos/python/mypy/pulls\",\n        json={\n            \"title\": title,\n            \"body\": body,\n            \"head\": f\"{fork_owner}:{branch_name}\",\n            \"base\": \"master\",\n        },\n        headers=get_github_api_headers(),\n    ) as response:\n        resp_json = response.json()\n        if response.status_code == 422 and any(\n            \"A pull request already exists\" in e.get(\"message\", \"\")\n            for e in resp_json.get(\"errors\", [])\n        ):\n            # Find the existing PR\n            with requests.get(\n                \"https://api.github.com/repos/python/mypy/pulls\",\n                params={\"state\": \"open\", \"head\": f\"{fork_owner}:{branch_name}\", \"base\": \"master\"},\n                headers=get_github_api_headers(),\n            ) as response:\n                response.raise_for_status()\n                resp_json = response.json()\n                assert len(resp_json) >= 1\n                pr_number = resp_json[0][\"number\"]\n            # Update the PR's title and body\n            with requests.patch(\n                f\"https://api.github.com/repos/python/mypy/pulls/{pr_number}\",\n                json={\"title\": title, \"body\": body},\n                headers=get_github_api_headers(),\n            ) as response:\n                response.raise_for_status()\n            return\n        response.raise_for_status()\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\n        \"--commit\",\n        default=None,\n        help=\"Typeshed commit (default to latest main if using a repository clone)\",\n    )\n    parser.add_argument(\n        \"--typeshed-dir\",\n        default=None,\n        help=\"Location of typeshed (default to a temporary repository clone)\",\n    )\n    parser.add_argument(\n        \"--make-pr\",\n        action=\"store_true\",\n        help=\"Whether to make a PR with the changes (default to no)\",\n    )\n    parser.add_argument(\"--no-branch\", action=\"store_true\", help=\"Skip creating a new branch\")\n    args = parser.parse_args()\n\n    check_state()\n\n    if args.make_pr:\n        if os.environ.get(\"GITHUB_TOKEN\") is None:\n            raise ValueError(\"GITHUB_TOKEN environment variable must be set\")\n\n    with tempfile.TemporaryDirectory() as tmpdir:\n        # Stash patches before checking out a new branch\n        typeshed_patches = os.path.join(\"misc\", \"typeshed_patches\")\n        tmp_patches = os.path.join(tmpdir, \"typeshed_patches\")\n        shutil.copytree(typeshed_patches, tmp_patches)\n\n        branch_name = \"mypybot/sync-typeshed\"\n        if not args.no_branch:\n            subprocess.run([\"git\", \"checkout\", \"-B\", branch_name, \"origin/master\"], check=True)\n\n        # Copy the stashed patches back\n        shutil.rmtree(typeshed_patches, ignore_errors=True)\n        shutil.copytree(tmp_patches, typeshed_patches)\n        if subprocess.run([\"git\", \"diff\", \"--quiet\", \"--exit-code\"], check=False).returncode != 0:\n            subprocess.run([\"git\", \"commit\", \"-am\", \"Update typeshed patches\"], check=True)\n\n        if not args.typeshed_dir:\n            tmp_typeshed = os.path.join(tmpdir, \"typeshed\")\n            os.makedirs(tmp_typeshed)\n            # Clone typeshed repo if no directory given.\n            print(f\"Cloning typeshed in {tmp_typeshed}...\")\n            subprocess.run(\n                [\"git\", \"clone\", \"https://github.com/python/typeshed.git\"],\n                check=True,\n                cwd=tmp_typeshed,\n            )\n            repo = os.path.join(tmp_typeshed, \"typeshed\")\n            commit = update_typeshed(repo, args.commit)\n        else:\n            commit = update_typeshed(args.typeshed_dir, args.commit)\n\n        assert commit\n\n        # Create a commit\n        message = textwrap.dedent(f\"\"\"\\\n            Sync typeshed\n\n            Source commit:\n            https://github.com/python/typeshed/commit/{commit}\n            \"\"\")\n        subprocess.run([\"git\", \"add\", \"--all\", os.path.join(\"mypy\", \"typeshed\")], check=True)\n        subprocess.run([\"git\", \"commit\", \"-m\", message], check=True)\n        print(\"Created typeshed sync commit.\")\n\n        patches = sorted(glob.glob(os.path.join(typeshed_patches, \"*.patch\")))\n        for patch in patches:\n            cmd = [\"git\", \"am\", \"--3way\", patch]\n            try:\n                subprocess.run(cmd, check=True)\n            except subprocess.CalledProcessError as e:\n                raise RuntimeError(\n                    f\"\\n\\nFailed to apply patch {patch}\\n\"\n                    \"1. Resolve the conflict, `git add --update`, then run `git am --continue`\\n\"\n                    \"2. Run `git format-patch -1 -o misc/typeshed_patches <new_commit_sha>` \"\n                    \"to update the patch file.\\n\"\n                    \"3. Re-run sync-typeshed.py\"\n                ) from e\n\n            print(f\"Applied patch {patch}\")\n\n    if args.make_pr:\n        subprocess.run([\"git\", \"push\", \"--force\", \"origin\", branch_name], check=True)\n        print(\"Pushed commit.\")\n\n        warning = \"Note that you will need to close and re-open the PR in order to trigger CI.\"\n\n        create_or_update_pull_request(\n            title=\"Sync typeshed\", body=message + \"\\n\" + warning, branch_name=branch_name\n        )\n        print(\"Created PR.\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/test-stubgenc.sh",
    "content": "#!/bin/bash\n\nset -e\nset -x\n\ncd \"$(dirname \"$0\")/..\"\n\n# Install dependencies, demo project and mypy\npython -m pip install -r test-requirements.txt\npython -m pip install ./test-data/pybind11_fixtures\npython -m pip install .\n\nEXIT=0\n\n# performs the stubgenc test\n# first argument is the test result folder\n# everything else is passed to stubgen as its arguments\nfunction stubgenc_test() {\n    # Remove expected stubs and generate new inplace\n    STUBGEN_OUTPUT_FOLDER=./test-data/pybind11_fixtures/$1\n    rm -rf \"${STUBGEN_OUTPUT_FOLDER:?}\"\n\n    stubgen -o \"$STUBGEN_OUTPUT_FOLDER\" \"${@:2}\"\n\n    # Check if generated stubs can actually be type checked by mypy\n    if ! mypy \"$STUBGEN_OUTPUT_FOLDER\";\n    then\n        echo \"Stubgen test failed, because generated stubs failed to type check.\"\n        EXIT=1\n    fi\n\n    # Compare generated stubs to expected ones\n    if ! git diff --exit-code \"$STUBGEN_OUTPUT_FOLDER\";\n    then\n        echo \"Stubgen test failed, because generated stubs differ from expected outputs.\"\n        EXIT=1\n    fi\n}\n\n# create stubs without docstrings\nstubgenc_test expected_stubs_no_docs -p pybind11_fixtures\n# create stubs with docstrings\nstubgenc_test expected_stubs_with_docs -p pybind11_fixtures --include-docstrings\n\nexit $EXIT\n"
  },
  {
    "path": "misc/trigger_wheel_build.sh",
    "content": "#!/bin/bash -eux\n\n# Trigger a build of mypyc compiled mypy wheels by updating the mypy\n# submodule in the git repo that drives those builds.\n\n# $WHEELS_PUSH_TOKEN is stored in GitHub Settings and is an API token\n# for the mypy-build-bot account.\n\ngit config --global user.email \"nobody\"\ngit config --global user.name \"mypy wheels autopush\"\n\nCOMMIT=$(git rev-parse HEAD)\npip install -r mypy-requirements.txt\nV=$(python3 -m mypy --version)\nV=$(echo \"$V\" | cut -d\" \" -f2)\n\ngit clone --depth 1 https://${WHEELS_PUSH_TOKEN}@github.com/mypyc/mypy_mypyc-wheels.git build\ncd build\necho $COMMIT > mypy_commit\ngit commit -am \"Build wheels for mypy $V\"\ngit tag v$V\n# Push a tag, but no need to push the change to master\ngit push --tags\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Adjust-stubs-to-fix-mypy-lookup-error-due-to-circula.patch",
    "content": "From 5c922a2484f2e18c7f901e62bb499b6414cf1090 Mon Sep 17 00:00:00 2001\nFrom: Marc Mueller <30130371+cdce8p@users.noreply.github.com>\nDate: Wed, 18 Feb 2026 13:11:02 +0100\nSubject: [PATCH] Adjust stubs to fix mypy lookup error due to circular\n dependencies in stubs\n\n---\n mypy/typeshed/stdlib/time.pyi | 6 +++---\n 1 file changed, 3 insertions(+), 3 deletions(-)\n\ndiff --git a/mypy/typeshed/stdlib/time.pyi b/mypy/typeshed/stdlib/time.pyi\nindex 64a009318..d0853792b 100644\n--- a/mypy/typeshed/stdlib/time.pyi\n+++ b/mypy/typeshed/stdlib/time.pyi\n@@ -1,16 +1,16 @@\n import sys\n from _typeshed import structseq\n-from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, final, type_check_only\n+from typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, Union, final, type_check_only\n from typing_extensions import TypeAlias\n \n _TimeTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int]\n \n if sys.version_info >= (3, 15):\n     # anticipate on https://github.com/python/cpython/pull/139224\n-    _SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex\n+    _SupportsFloatOrIndex: TypeAlias = Union[SupportsFloat, SupportsIndex]\n else:\n     # before, time functions only accept (subclass of) float, *not* SupportsFloat\n-    _SupportsFloatOrIndex: TypeAlias = float | SupportsIndex\n+    _SupportsFloatOrIndex: TypeAlias = Union[float, SupportsIndex]\n \n altzone: int\n daylight: int\n-- \n2.53.0\n\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Partially-revert-Clean-up-argparse-hacks.patch",
    "content": "From b6d495c10e79fb56ff64f8fb90c87894090f9cbe Mon Sep 17 00:00:00 2001\nFrom: Marc Mueller <30130371+cdce8p@users.noreply.github.com>\nDate: Sat, 15 Feb 2025 20:11:06 +0100\nSubject: [PATCH] Partially revert Clean up argparse hacks\n\n---\n mypy/typeshed/stdlib/argparse.pyi | 8 +++++---\n 1 file changed, 5 insertions(+), 3 deletions(-)\n\ndiff --git a/mypy/typeshed/stdlib/argparse.pyi b/mypy/typeshed/stdlib/argparse.pyi\nindex ae99eb036..c87b8f4fc 100644\n--- a/mypy/typeshed/stdlib/argparse.pyi\n+++ b/mypy/typeshed/stdlib/argparse.pyi\n@@ -2,7 +2,7 @@ import sys\n from _typeshed import SupportsWrite, sentinel\n from collections.abc import Callable, Generator, Iterable, Sequence\n from re import Pattern\n-from typing import IO, Any, ClassVar, Final, Generic, NoReturn, Protocol, TypeVar, overload, type_check_only\n+from typing import IO, Any, ClassVar, Final, Generic, NewType, NoReturn, Protocol, TypeVar, overload, type_check_only\n from typing_extensions import Self, TypeAlias, deprecated\n \n __all__ = [\n@@ -36,7 +36,9 @@ ONE_OR_MORE: Final = \"+\"\n OPTIONAL: Final = \"?\"\n PARSER: Final = \"A...\"\n REMAINDER: Final = \"...\"\n-SUPPRESS: Final = \"==SUPPRESS==\"\n+_SUPPRESS_T = NewType(\"_SUPPRESS_T\", str)\n+SUPPRESS: _SUPPRESS_T | str  # not using Literal because argparse sometimes compares SUPPRESS with is\n+# the | str is there so that foo = argparse.SUPPRESS; foo = \"test\" checks out in mypy\n ZERO_OR_MORE: Final = \"*\"\n _UNRECOGNIZED_ARGS_ATTR: Final = \"_unrecognized_args\"  # undocumented\n \n@@ -79,7 +81,7 @@ class _ActionsContainer:\n         # more precisely, Literal[\"?\", \"*\", \"+\", \"...\", \"A...\", \"==SUPPRESS==\"],\n         # but using this would make it hard to annotate callers that don't use a\n         # literal argument and for subclasses to override this method.\n-        nargs: int | str | None = None,\n+        nargs: int | str | _SUPPRESS_T | None = None,\n         const: Any = ...,\n         default: Any = ...,\n         type: _ActionType = ...,\n-- \n2.52.0\n\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Remove-use-of-LiteralString-in-builtins-13743.patch",
    "content": "From b3021cdc4b4c2cf547c5bc2d1d21a5a00ffea001 Mon Sep 17 00:00:00 2001\nFrom: Shantanu <12621235+hauntsaninja@users.noreply.github.com>\nDate: Mon, 26 Sep 2022 12:55:07 -0700\nSubject: [PATCH] Remove use of LiteralString in builtins (#13743)\n\n---\n mypy/typeshed/stdlib/builtins.pyi | 98 -------------------------------\n 1 file changed, 98 deletions(-)\n\ndiff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi\nindex efc51fe25..8600a372b 100644\n--- a/mypy/typeshed/stdlib/builtins.pyi\n+++ b/mypy/typeshed/stdlib/builtins.pyi\n@@ -64,7 +64,6 @@ from typing import (  # noqa: Y022,UP035\n from typing_extensions import (  # noqa: Y023\n     Concatenate,\n     Literal,\n-    LiteralString,\n     ParamSpec,\n     Self,\n     TypeAlias,\n@@ -482,31 +481,16 @@ class str(Sequence[str]):\n     def __new__(cls, object: object = \"\") -> Self: ...\n     @overload\n     def __new__(cls, object: ReadableBuffer, encoding: str = \"utf-8\", errors: str = \"strict\") -> Self: ...\n-    @overload\n-    def capitalize(self: LiteralString) -> LiteralString: ...\n-    @overload\n     def capitalize(self) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def casefold(self: LiteralString) -> LiteralString: ...\n-    @overload\n     def casefold(self) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def center(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = \" \", /) -> LiteralString: ...\n-    @overload\n     def center(self, width: SupportsIndex, fillchar: str = \" \", /) -> str: ...  # type: ignore[misc]\n     def count(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ...\n     def encode(self, encoding: str = \"utf-8\", errors: str = \"strict\") -> bytes: ...\n     def endswith(\n         self, suffix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n     ) -> bool: ...\n-    @overload\n-    def expandtabs(self: LiteralString, tabsize: SupportsIndex = 8) -> LiteralString: ...\n-    @overload\n     def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ...  # type: ignore[misc]\n     def find(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ...\n-    @overload\n-    def format(self: LiteralString, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ...\n-    @overload\n     def format(self, *args: object, **kwargs: object) -> str: ...\n     def format_map(self, mapping: _FormatMapMapping, /) -> str: ...\n     def index(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ...\n@@ -522,98 +506,34 @@ class str(Sequence[str]):\n     def isspace(self) -> bool: ...\n     def istitle(self) -> bool: ...\n     def isupper(self) -> bool: ...\n-    @overload\n-    def join(self: LiteralString, iterable: Iterable[LiteralString], /) -> LiteralString: ...\n-    @overload\n     def join(self, iterable: Iterable[str], /) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def ljust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = \" \", /) -> LiteralString: ...\n-    @overload\n     def ljust(self, width: SupportsIndex, fillchar: str = \" \", /) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def lower(self: LiteralString) -> LiteralString: ...\n-    @overload\n     def lower(self) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def lstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ...\n-    @overload\n     def lstrip(self, chars: str | None = None, /) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def partition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ...\n-    @overload\n     def partition(self, sep: str, /) -> tuple[str, str, str]: ...  # type: ignore[misc]\n     if sys.version_info >= (3, 13):\n-        @overload\n-        def replace(\n-            self: LiteralString, old: LiteralString, new: LiteralString, /, count: SupportsIndex = -1\n-        ) -> LiteralString: ...\n-        @overload\n         def replace(self, old: str, new: str, /, count: SupportsIndex = -1) -> str: ...  # type: ignore[misc]\n     else:\n-        @overload\n-        def replace(\n-            self: LiteralString, old: LiteralString, new: LiteralString, count: SupportsIndex = -1, /\n-        ) -> LiteralString: ...\n-        @overload\n         def replace(self, old: str, new: str, count: SupportsIndex = -1, /) -> str: ...  # type: ignore[misc]\n \n-    @overload\n-    def removeprefix(self: LiteralString, prefix: LiteralString, /) -> LiteralString: ...\n-    @overload\n     def removeprefix(self, prefix: str, /) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def removesuffix(self: LiteralString, suffix: LiteralString, /) -> LiteralString: ...\n-    @overload\n     def removesuffix(self, suffix: str, /) -> str: ...  # type: ignore[misc]\n     def rfind(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ...\n     def rindex(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ...\n-    @overload\n-    def rjust(self: LiteralString, width: SupportsIndex, fillchar: LiteralString = \" \", /) -> LiteralString: ...\n-    @overload\n     def rjust(self, width: SupportsIndex, fillchar: str = \" \", /) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def rpartition(self: LiteralString, sep: LiteralString, /) -> tuple[LiteralString, LiteralString, LiteralString]: ...\n-    @overload\n     def rpartition(self, sep: str, /) -> tuple[str, str, str]: ...  # type: ignore[misc]\n-    @overload\n-    def rsplit(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ...\n-    @overload\n     def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ...  # type: ignore[misc]\n-    @overload\n-    def rstrip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ...\n-    @overload\n     def rstrip(self, chars: str | None = None, /) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def split(self: LiteralString, sep: LiteralString | None = None, maxsplit: SupportsIndex = -1) -> list[LiteralString]: ...\n-    @overload\n     def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ...  # type: ignore[misc]\n-    @overload\n-    def splitlines(self: LiteralString, keepends: bool = False) -> list[LiteralString]: ...\n-    @overload\n     def splitlines(self, keepends: bool = False) -> list[str]: ...  # type: ignore[misc]\n     def startswith(\n         self, prefix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n     ) -> bool: ...\n-    @overload\n-    def strip(self: LiteralString, chars: LiteralString | None = None, /) -> LiteralString: ...\n-    @overload\n     def strip(self, chars: str | None = None, /) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def swapcase(self: LiteralString) -> LiteralString: ...\n-    @overload\n     def swapcase(self) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def title(self: LiteralString) -> LiteralString: ...\n-    @overload\n     def title(self) -> str: ...  # type: ignore[misc]\n     def translate(self, table: _TranslateTable, /) -> str: ...\n-    @overload\n-    def upper(self: LiteralString) -> LiteralString: ...\n-    @overload\n     def upper(self) -> str: ...  # type: ignore[misc]\n-    @overload\n-    def zfill(self: LiteralString, width: SupportsIndex, /) -> LiteralString: ...\n-    @overload\n     def zfill(self, width: SupportsIndex, /) -> str: ...  # type: ignore[misc]\n     @staticmethod\n     @overload\n@@ -624,39 +544,21 @@ class str(Sequence[str]):\n     @staticmethod\n     @overload\n     def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ...\n-    @overload\n-    def __add__(self: LiteralString, value: LiteralString, /) -> LiteralString: ...\n-    @overload\n     def __add__(self, value: str, /) -> str: ...  # type: ignore[misc]\n     # Incompatible with Sequence.__contains__\n     def __contains__(self, key: str, /) -> bool: ...  # type: ignore[override]\n     def __eq__(self, value: object, /) -> bool: ...\n     def __ge__(self, value: str, /) -> bool: ...\n-    @overload\n-    def __getitem__(self: LiteralString, key: SupportsIndex | slice[SupportsIndex | None], /) -> LiteralString: ...\n-    @overload\n     def __getitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> str: ...  # type: ignore[misc]\n     def __gt__(self, value: str, /) -> bool: ...\n     def __hash__(self) -> int: ...\n-    @overload\n-    def __iter__(self: LiteralString) -> Iterator[LiteralString]: ...\n-    @overload\n     def __iter__(self) -> Iterator[str]: ...  # type: ignore[misc]\n     def __le__(self, value: str, /) -> bool: ...\n     def __len__(self) -> int: ...\n     def __lt__(self, value: str, /) -> bool: ...\n-    @overload\n-    def __mod__(self: LiteralString, value: LiteralString | tuple[LiteralString, ...], /) -> LiteralString: ...\n-    @overload\n     def __mod__(self, value: Any, /) -> str: ...\n-    @overload\n-    def __mul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ...\n-    @overload\n     def __mul__(self, value: SupportsIndex, /) -> str: ...  # type: ignore[misc]\n     def __ne__(self, value: object, /) -> bool: ...\n-    @overload\n-    def __rmul__(self: LiteralString, value: SupportsIndex, /) -> LiteralString: ...\n-    @overload\n     def __rmul__(self, value: SupportsIndex, /) -> str: ...  # type: ignore[misc]\n     def __getnewargs__(self) -> tuple[str]: ...\n     def __format__(self, format_spec: str, /) -> str: ...\n-- \n2.52.0\n\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Revert-Remove-redundant-inheritances-from-Iterator.patch",
    "content": "From 69791281c2c5e919cea9a77c4a771f79d9e70384 Mon Sep 17 00:00:00 2001\nFrom: Marc Mueller <30130371+cdce8p@users.noreply.github.com>\nDate: Sat, 21 Dec 2024 22:36:38 +0100\nSubject: [PATCH] Revert Remove redundant inheritances from Iterator in\n builtins\n\n---\n mypy/typeshed/stdlib/_asyncio.pyi             |  4 +-\n mypy/typeshed/stdlib/builtins.pyi             | 10 ++---\n mypy/typeshed/stdlib/csv.pyi                  |  4 +-\n mypy/typeshed/stdlib/fileinput.pyi            |  6 +--\n mypy/typeshed/stdlib/itertools.pyi            | 38 +++++++++----------\n mypy/typeshed/stdlib/multiprocessing/pool.pyi |  4 +-\n mypy/typeshed/stdlib/sqlite3/__init__.pyi     |  2 +-\n 7 files changed, 34 insertions(+), 34 deletions(-)\n\ndiff --git a/mypy/typeshed/stdlib/_asyncio.pyi b/mypy/typeshed/stdlib/_asyncio.pyi\nindex d663f5d93..f43178e4d 100644\n--- a/mypy/typeshed/stdlib/_asyncio.pyi\n+++ b/mypy/typeshed/stdlib/_asyncio.pyi\n@@ -1,6 +1,6 @@\n import sys\n from asyncio.events import AbstractEventLoop\n-from collections.abc import Awaitable, Callable, Coroutine, Generator\n+from collections.abc import Awaitable, Callable, Coroutine, Generator, Iterable\n from contextvars import Context\n from types import FrameType, GenericAlias\n from typing import Any, Literal, TextIO, TypeVar\n@@ -11,7 +11,7 @@ _T_co = TypeVar(\"_T_co\", covariant=True)\n _TaskYieldType: TypeAlias = Future[object] | None\n \n @disjoint_base\n-class Future(Awaitable[_T]):\n+class Future(Awaitable[_T], Iterable[_T]):\n     _state: str\n     @property\n     def _exception(self) -> BaseException | None: ...\ndiff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi\nindex 8acdeadff..5a3bb5908 100644\n--- a/mypy/typeshed/stdlib/builtins.pyi\n+++ b/mypy/typeshed/stdlib/builtins.pyi\n@@ -1226,7 +1226,7 @@ class frozenset(AbstractSet[_T_co]):\n     def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n \n @disjoint_base\n-class enumerate(Generic[_T]):\n+class enumerate(Iterator[tuple[int, _T]]):\n     def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ...\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> tuple[int, _T]: ...\n@@ -1413,7 +1413,7 @@ else:\n exit: _sitebuiltins.Quitter\n \n @disjoint_base\n-class filter(Generic[_T]):\n+class filter(Iterator[_T]):\n     @overload\n     def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ...\n     @overload\n@@ -1477,7 +1477,7 @@ license: _sitebuiltins._Printer\n \n def locals() -> dict[str, Any]: ...\n @disjoint_base\n-class map(Generic[_S]):\n+class map(Iterator[_S]):\n     # 3.14 adds `strict` argument.\n     if sys.version_info >= (3, 14):\n         @overload\n@@ -1784,7 +1784,7 @@ def pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex\n quit: _sitebuiltins.Quitter\n \n @disjoint_base\n-class reversed(Generic[_T]):\n+class reversed(Iterator[_T]):\n     @overload\n     def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ...  # type: ignore[misc]\n     @overload\n@@ -1848,7 +1848,7 @@ def vars(object: type, /) -> types.MappingProxyType[str, Any]: ...\n @overload\n def vars(object: Any = ..., /) -> dict[str, Any]: ...\n @disjoint_base\n-class zip(Generic[_T_co]):\n+class zip(Iterator[_T_co]):\n     if sys.version_info >= (3, 10):\n         @overload\n         def __new__(cls, *, strict: bool = False) -> zip[Any]: ...\ndiff --git a/mypy/typeshed/stdlib/csv.pyi b/mypy/typeshed/stdlib/csv.pyi\nindex 2c8e7109c..4ed0ab1d8 100644\n--- a/mypy/typeshed/stdlib/csv.pyi\n+++ b/mypy/typeshed/stdlib/csv.pyi\n@@ -25,7 +25,7 @@ else:\n     from _csv import _reader as Reader, _writer as Writer\n \n from _typeshed import SupportsWrite\n-from collections.abc import Collection, Iterable, Mapping, Sequence\n+from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence\n from types import GenericAlias\n from typing import Any, Generic, Literal, TypeVar, overload\n from typing_extensions import Self\n@@ -73,7 +73,7 @@ class excel(Dialect): ...\n class excel_tab(excel): ...\n class unix_dialect(Dialect): ...\n \n-class DictReader(Generic[_T]):\n+class DictReader(Iterator[dict[_T | Any, str | Any]], Generic[_T]):\n     fieldnames: Sequence[_T] | None\n     restkey: _T | None\n     restval: str | Any | None\ndiff --git a/mypy/typeshed/stdlib/fileinput.pyi b/mypy/typeshed/stdlib/fileinput.pyi\nindex 6778b7648..95164de2f 100644\n--- a/mypy/typeshed/stdlib/fileinput.pyi\n+++ b/mypy/typeshed/stdlib/fileinput.pyi\n@@ -1,8 +1,8 @@\n import sys\n from _typeshed import AnyStr_co, StrOrBytesPath\n-from collections.abc import Callable, Iterable\n+from collections.abc import Callable, Iterable, Iterator\n from types import GenericAlias, TracebackType\n-from typing import IO, Any, AnyStr, Generic, Literal, Protocol, overload, type_check_only\n+from typing import IO, Any, AnyStr, Literal, Protocol, overload, type_check_only\n from typing_extensions import Self, TypeAlias, deprecated\n \n __all__ = [\n@@ -105,7 +105,7 @@ def fileno() -> int: ...\n def isfirstline() -> bool: ...\n def isstdin() -> bool: ...\n \n-class FileInput(Generic[AnyStr]):\n+class FileInput(Iterator[AnyStr]):\n     if sys.version_info >= (3, 10):\n         # encoding and errors are added\n         @overload\ndiff --git a/mypy/typeshed/stdlib/itertools.pyi b/mypy/typeshed/stdlib/itertools.pyi\nindex 8a924ad8b..5c2bf7f83 100644\n--- a/mypy/typeshed/stdlib/itertools.pyi\n+++ b/mypy/typeshed/stdlib/itertools.pyi\n@@ -28,7 +28,7 @@ _Predicate: TypeAlias = Callable[[_T], object]\n # Technically count can take anything that implements a number protocol and has an add method\n # but we can't enforce the add method\n @disjoint_base\n-class count(Generic[_N]):\n+class count(Iterator[_N]):\n     @overload\n     def __new__(cls) -> count[int]: ...\n     @overload\n@@ -39,13 +39,13 @@ class count(Generic[_N]):\n     def __iter__(self) -> Self: ...\n \n @disjoint_base\n-class cycle(Generic[_T]):\n+class cycle(Iterator[_T]):\n     def __new__(cls, iterable: Iterable[_T], /) -> Self: ...\n     def __next__(self) -> _T: ...\n     def __iter__(self) -> Self: ...\n \n @disjoint_base\n-class repeat(Generic[_T]):\n+class repeat(Iterator[_T]):\n     @overload\n     def __new__(cls, object: _T) -> Self: ...\n     @overload\n@@ -55,7 +55,7 @@ class repeat(Generic[_T]):\n     def __length_hint__(self) -> int: ...\n \n @disjoint_base\n-class accumulate(Generic[_T]):\n+class accumulate(Iterator[_T]):\n     @overload\n     def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = None) -> Self: ...\n     @overload\n@@ -64,7 +64,7 @@ class accumulate(Generic[_T]):\n     def __next__(self) -> _T: ...\n \n @disjoint_base\n-class chain(Generic[_T]):\n+class chain(Iterator[_T]):\n     def __new__(cls, *iterables: Iterable[_T]) -> Self: ...\n     def __next__(self) -> _T: ...\n     def __iter__(self) -> Self: ...\n@@ -74,25 +74,25 @@ class chain(Generic[_T]):\n     def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n \n @disjoint_base\n-class compress(Generic[_T]):\n+class compress(Iterator[_T]):\n     def __new__(cls, data: Iterable[_T], selectors: Iterable[Any]) -> Self: ...\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T: ...\n \n @disjoint_base\n-class dropwhile(Generic[_T]):\n+class dropwhile(Iterator[_T]):\n     def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ...\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T: ...\n \n @disjoint_base\n-class filterfalse(Generic[_T]):\n+class filterfalse(Iterator[_T]):\n     def __new__(cls, function: _Predicate[_T] | None, iterable: Iterable[_T], /) -> Self: ...\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T: ...\n \n @disjoint_base\n-class groupby(Generic[_T_co, _S_co]):\n+class groupby(Iterator[tuple[_T_co, Iterator[_S_co]]], Generic[_T_co, _S_co]):\n     @overload\n     def __new__(cls, iterable: Iterable[_T1], key: None = None) -> groupby[_T1, _T1]: ...\n     @overload\n@@ -101,7 +101,7 @@ class groupby(Generic[_T_co, _S_co]):\n     def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: ...\n \n @disjoint_base\n-class islice(Generic[_T]):\n+class islice(Iterator[_T]):\n     @overload\n     def __new__(cls, iterable: Iterable[_T], stop: int | None, /) -> Self: ...\n     @overload\n@@ -110,20 +110,20 @@ class islice(Generic[_T]):\n     def __next__(self) -> _T: ...\n \n @disjoint_base\n-class starmap(Generic[_T_co]):\n+class starmap(Iterator[_T_co]):\n     def __new__(cls, function: Callable[..., _T], iterable: Iterable[Iterable[Any]], /) -> starmap[_T]: ...\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T_co: ...\n \n @disjoint_base\n-class takewhile(Generic[_T]):\n+class takewhile(Iterator[_T]):\n     def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ...\n     def __iter__(self) -> Self: ...\n     def __next__(self) -> _T: ...\n \n def tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: ...\n @disjoint_base\n-class zip_longest(Generic[_T_co]):\n+class zip_longest(Iterator[_T_co]):\n     # one iterable (fillvalue doesn't matter)\n     @overload\n     def __new__(cls, iter1: Iterable[_T1], /, *, fillvalue: object = None) -> zip_longest[tuple[_T1]]: ...\n@@ -202,7 +202,7 @@ class zip_longest(Generic[_T_co]):\n     def __next__(self) -> _T_co: ...\n \n @disjoint_base\n-class product(Generic[_T_co]):\n+class product(Iterator[_T_co]):\n     @overload\n     def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ...\n     @overload\n@@ -288,7 +288,7 @@ class product(Generic[_T_co]):\n     def __next__(self) -> _T_co: ...\n \n @disjoint_base\n-class permutations(Generic[_T_co]):\n+class permutations(Iterator[_T_co]):\n     @overload\n     def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> permutations[tuple[_T, _T]]: ...\n     @overload\n@@ -303,7 +303,7 @@ class permutations(Generic[_T_co]):\n     def __next__(self) -> _T_co: ...\n \n @disjoint_base\n-class combinations(Generic[_T_co]):\n+class combinations(Iterator[_T_co]):\n     @overload\n     def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations[tuple[_T, _T]]: ...\n     @overload\n@@ -318,7 +318,7 @@ class combinations(Generic[_T_co]):\n     def __next__(self) -> _T_co: ...\n \n @disjoint_base\n-class combinations_with_replacement(Generic[_T_co]):\n+class combinations_with_replacement(Iterator[_T_co]):\n     @overload\n     def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations_with_replacement[tuple[_T, _T]]: ...\n     @overload\n@@ -334,14 +334,14 @@ class combinations_with_replacement(Generic[_T_co]):\n \n if sys.version_info >= (3, 10):\n     @disjoint_base\n-    class pairwise(Generic[_T_co]):\n+    class pairwise(Iterator[_T_co]):\n         def __new__(cls, iterable: Iterable[_T], /) -> pairwise[tuple[_T, _T]]: ...\n         def __iter__(self) -> Self: ...\n         def __next__(self) -> _T_co: ...\n \n if sys.version_info >= (3, 12):\n     @disjoint_base\n-    class batched(Generic[_T_co]):\n+    class batched(Iterator[_T_co], Generic[_T_co]):\n         if sys.version_info >= (3, 13):\n             @overload\n             def __new__(cls, iterable: Iterable[_T], n: Literal[1], *, strict: Literal[True]) -> batched[tuple[_T]]: ...\ndiff --git a/mypy/typeshed/stdlib/multiprocessing/pool.pyi b/mypy/typeshed/stdlib/multiprocessing/pool.pyi\nindex b79f9e773..f276372d0 100644\n--- a/mypy/typeshed/stdlib/multiprocessing/pool.pyi\n+++ b/mypy/typeshed/stdlib/multiprocessing/pool.pyi\n@@ -1,4 +1,4 @@\n-from collections.abc import Callable, Iterable, Mapping\n+from collections.abc import Callable, Iterable, Iterator, Mapping\n from multiprocessing.context import DefaultContext, Process\n from types import GenericAlias, TracebackType\n from typing import Any, Final, Generic, TypeVar\n@@ -32,7 +32,7 @@ class MapResult(ApplyResult[list[_T]]):\n         error_callback: Callable[[BaseException], object] | None,\n     ) -> None: ...\n \n-class IMapIterator(Generic[_T]):\n+class IMapIterator(Iterator[_T]):\n     def __init__(self, pool: Pool) -> None: ...\n     def __iter__(self) -> Self: ...\n     def next(self, timeout: float | None = None) -> _T: ...\ndiff --git a/mypy/typeshed/stdlib/sqlite3/__init__.pyi b/mypy/typeshed/stdlib/sqlite3/__init__.pyi\nindex 04b978b1b..e4604144f 100644\n--- a/mypy/typeshed/stdlib/sqlite3/__init__.pyi\n+++ b/mypy/typeshed/stdlib/sqlite3/__init__.pyi\n@@ -408,7 +408,7 @@ class Connection:\n     ) -> Literal[False]: ...\n \n @disjoint_base\n-class Cursor:\n+class Cursor(Iterator[Any]):\n     arraysize: int\n     @property\n     def connection(self) -> Connection: ...\n-- \n2.52.0\n\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Revert-Use-contravariant-type-variable-in-Container.patch",
    "content": "From 274a77fe74d961e9885036ed31e5ed46f8d91daa Mon Sep 17 00:00:00 2001\nFrom: Marc Mueller <30130371+cdce8p@users.noreply.github.com>\nDate: Mon, 23 Feb 2026 12:00:18 +0100\nSubject: [PATCH] Revert Use contravariant type variable in Container\n\n---\n mypy/typeshed/stdlib/typing.pyi | 9 +++------\n 1 file changed, 3 insertions(+), 6 deletions(-)\n\ndiff --git a/mypy/typeshed/stdlib/typing.pyi b/mypy/typeshed/stdlib/typing.pyi\nindex 83e114aac..e9f67877c 100644\n--- a/mypy/typeshed/stdlib/typing.pyi\n+++ b/mypy/typeshed/stdlib/typing.pyi\n@@ -640,17 +640,14 @@ class AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_cont\n     ) -> Coroutine[Any, Any, _YieldT_co]: ...\n     def aclose(self) -> Coroutine[Any, Any, None]: ...\n \n-_ContainerT_contra = TypeVar(\"_ContainerT_contra\", contravariant=True, default=Any)\n-\n @runtime_checkable\n-class Container(Protocol[_ContainerT_contra]):\n+class Container(Protocol[_T_co]):\n     # This is generic more on vibes than anything else\n     @abstractmethod\n-    def __contains__(self, x: _ContainerT_contra, /) -> bool: ...\n+    def __contains__(self, x: object, /) -> bool: ...\n \n @runtime_checkable\n-class Collection(Iterable[_T_co], Container[Any], Protocol[_T_co]):\n-    # Note: need to use Container[Any] instead of Container[_T_co] to ensure covariance.\n+class Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]):\n     # Implement Sized (but don't have it as a base class).\n     @abstractmethod\n     def __len__(self) -> int: ...\n-- \n2.53.0\n\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Revert-sum-literal-integer-change-13961.patch",
    "content": "From 0e30b762e8335f02e19977c055ac7b98e707991c Mon Sep 17 00:00:00 2001\nFrom: Shantanu <12621235+hauntsaninja@users.noreply.github.com>\nDate: Sat, 29 Oct 2022 12:47:21 -0700\nSubject: [PATCH] Revert sum literal integer change (#13961)\n\nThis is allegedly causing large performance problems, see 13821\n\ntypeshed/8231 had zero hits on mypy_primer, so it's not the worst thing\nto undo. Patching this in typeshed also feels weird, since there's a\nmore general soundness issue. If a typevar has a bound or constraint, we\nmight not want to solve it to a Literal.\n\nIf we can confirm the performance regression or fix the unsoundness\nwithin mypy, I might pursue upstreaming this in typeshed.\n\n(Reminder: add this to the sync_typeshed script once merged)\n---\n mypy/typeshed/stdlib/builtins.pyi | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)\n\ndiff --git a/mypy/typeshed/stdlib/builtins.pyi b/mypy/typeshed/stdlib/builtins.pyi\nindex 5a3bb5908..0f2196070 100644\n--- a/mypy/typeshed/stdlib/builtins.pyi\n+++ b/mypy/typeshed/stdlib/builtins.pyi\n@@ -1835,7 +1835,7 @@ _SupportsSumNoDefaultT = TypeVar(\"_SupportsSumNoDefaultT\", bound=_SupportsSumWit\n # without creating many false-positive errors (see #7578).\n # Instead, we special-case the most common examples of this: bool and literal integers.\n @overload\n-def sum(iterable: Iterable[bool | _LiteralInteger], /, start: int = 0) -> int: ...\n+def sum(iterable: Iterable[bool], /, start: int = 0) -> int: ...\n @overload\n def sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ...\n @overload\n-- \n2.52.0\n\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Revert-typeshed-ctypes-change.patch",
    "content": "From 80a710e0e2c09612c6fc30c644f2052450e69ccd Mon Sep 17 00:00:00 2001\nFrom: AlexWaygood <alex.waygood@gmail.com>\nDate: Mon, 1 May 2023 20:34:55 +0100\nSubject: [PATCH] Revert typeshed ctypes change\n\nThe plugin provides superior type checking:\nhttps://github.com/python/mypy/pull/13987#issuecomment-1310863427\nA manual cherry-pick of e437cdf.\n---\n mypy/typeshed/stdlib/_ctypes.pyi | 6 +-----\n 1 file changed, 1 insertion(+), 5 deletions(-)\n\ndiff --git a/mypy/typeshed/stdlib/_ctypes.pyi b/mypy/typeshed/stdlib/_ctypes.pyi\nindex be7792818..b7a3fb104 100644\n--- a/mypy/typeshed/stdlib/_ctypes.pyi\n+++ b/mypy/typeshed/stdlib/_ctypes.pyi\n@@ -320,11 +320,7 @@ class Array(_CData, Generic[_CT], metaclass=_PyCArrayType):\n     def _type_(self) -> type[_CT]: ...\n     @_type_.setter\n     def _type_(self, value: type[_CT]) -> None: ...\n-    # Note: only available if _CT == c_char\n-    @property\n-    def raw(self) -> bytes: ...\n-    @raw.setter\n-    def raw(self, value: ReadableBuffer) -> None: ...\n+    raw: bytes  # Note: only available if _CT == c_char\n     value: Any  # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise\n     # TODO: These methods cannot be annotated correctly at the moment.\n     # All of these \"Any\"s stand for the array's element type, but it's not possible to use _CT\n-- \n2.52.0\n\n"
  },
  {
    "path": "misc/typeshed_patches/0001-Temporarily-revert-contextlib-deprecation.patch",
    "content": "From ae45edc46f2ca9c939e317648b44ed3372487798 Mon Sep 17 00:00:00 2001\nFrom: Shantanu Jain <hauntsaninja@gmail.com>\nDate: Sun, 22 Feb 2026 20:37:48 -0800\nSubject: [PATCH] Temporarily revert contextlib deprecation\n\n---\n mypy/typeshed/stdlib/contextlib.pyi | 15 +--------------\n 1 file changed, 1 insertion(+), 14 deletions(-)\n\ndiff --git a/mypy/typeshed/stdlib/contextlib.pyi b/mypy/typeshed/stdlib/contextlib.pyi\nindex 8d5902c46..221102ee2 100644\n--- a/mypy/typeshed/stdlib/contextlib.pyi\n+++ b/mypy/typeshed/stdlib/contextlib.pyi\n@@ -5,7 +5,7 @@ from abc import ABC, abstractmethod\n from collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator\n from types import TracebackType\n from typing import Any, Generic, Protocol, TypeVar, overload, runtime_checkable, type_check_only\n-from typing_extensions import ParamSpec, Self, TypeAlias, deprecated\n+from typing_extensions import ParamSpec, Self, TypeAlias\n \n __all__ = [\n     \"contextmanager\",\n@@ -86,12 +86,6 @@ class _GeneratorContextManager(\n         self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n     ) -> bool | None: ...\n \n-@overload\n-def contextmanager(func: Callable[_P, Generator[_T_co, None, object]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ...\n-@overload\n-@deprecated(\n-    \"Annotating the return type as `-> Iterator[Foo]` with `@contextmanager` is deprecated. Use `-> Generator[Foo]` instead.\"\n-)\n def contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ...\n \n if sys.version_info >= (3, 10):\n@@ -118,13 +112,6 @@ else:\n             self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n         ) -> bool | None: ...\n \n-@overload\n-def asynccontextmanager(func: Callable[_P, AsyncGenerator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ...\n-@overload\n-@deprecated(\n-    \"Annotating the return type as `-> AsyncIterator[Foo]` with `@asynccontextmanager` is deprecated. \"\n-    \"Use `-> AsyncGenerator[Foo]` instead.\"\n-)\n def asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ...\n @type_check_only\n class _SupportsClose(Protocol):\n-- \n2.53.0\n\n"
  },
  {
    "path": "misc/update-stubinfo.py",
    "content": "import argparse\nfrom pathlib import Path\n\nimport tomli as tomllib\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser()\n    parser.add_argument(\"--typeshed\", type=Path, required=True)\n    args = parser.parse_args()\n\n    typeshed_p_to_d = {}\n    for stub in (args.typeshed / \"stubs\").iterdir():\n        if not stub.is_dir():\n            continue\n        try:\n            metadata = tomllib.loads((stub / \"METADATA.toml\").read_text())\n        except FileNotFoundError:\n            continue\n        d = metadata.get(\"stub_distribution\", f\"types-{stub.name}\")\n        for p in stub.iterdir():\n            if not p.stem.isidentifier():\n                continue\n            if p.is_dir() and not any(f.suffix == \".pyi\" for f in p.iterdir()):\n                # ignore namespace packages\n                continue\n            if p.is_file() and p.suffix != \".pyi\":\n                continue\n            typeshed_p_to_d[p.stem] = d\n\n    import mypy.stubinfo\n\n    mypy_p = set(mypy.stubinfo.non_bundled_packages_flat) | set(\n        mypy.stubinfo.legacy_bundled_packages\n    )\n\n    for p in typeshed_p_to_d.keys() & mypy_p:\n        mypy_d = mypy.stubinfo.non_bundled_packages_flat.get(p)\n        mypy_d = mypy_d or mypy.stubinfo.legacy_bundled_packages.get(p)\n        if mypy_d != typeshed_p_to_d[p]:\n            raise ValueError(\n                f\"stub_distribution mismatch for {p}: {mypy_d} != {typeshed_p_to_d[p]}\"\n            )\n\n    print(\"=\" * 40)\n    print(\"Add the following to non_bundled_packages_flat:\")\n    print(\"=\" * 40)\n    for p in sorted(typeshed_p_to_d.keys() - mypy_p):\n        if p in {\n            \"pika\",  # see comment in stubinfo.py\n            \"distutils\",  # don't recommend types-setuptools here\n        }:\n            continue\n        print(f'\"{p}\": \"{typeshed_p_to_d[p]}\",')\n    print()\n\n    print(\"=\" * 40)\n    print(\"Consider removing the following packages no longer in typeshed:\")\n    print(\"=\" * 40)\n    for p in sorted(mypy_p - typeshed_p_to_d.keys()):\n        if p in {\"lxml\", \"pandas\", \"scipy\"}:  # never in typeshed\n            continue\n        print(p)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "misc/upload-pypi.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Upload mypy packages to PyPI.\n\nYou must first tag the release, use `git push --tags` and wait for the wheel build in CI to complete.\n\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport contextlib\nimport json\nimport re\nimport shutil\nimport subprocess\nimport tarfile\nimport tempfile\nimport venv\nfrom collections.abc import Iterator\nfrom concurrent.futures import ThreadPoolExecutor\nfrom pathlib import Path\nfrom typing import Any\nfrom urllib.request import urlopen\n\nBASE = \"https://api.github.com/repos\"\nREPO = \"mypyc/mypy_mypyc-wheels\"\n\n\ndef is_whl_or_tar(name: str) -> bool:\n    return name.endswith((\".tar.gz\", \".whl\"))\n\n\ndef item_ok_for_pypi(name: str) -> bool:\n    if not is_whl_or_tar(name):\n        return False\n\n    name = name.removesuffix(\".tar.gz\")\n    name = name.removesuffix(\".whl\")\n\n    if name.endswith(\"wasm32\"):\n        return False\n\n    return True\n\n\ndef get_release_for_tag(tag: str) -> dict[str, Any]:\n    with urlopen(f\"{BASE}/{REPO}/releases/tags/{tag}\") as f:\n        data = json.load(f)\n    assert isinstance(data, dict)\n    assert data[\"tag_name\"] == tag\n    return data\n\n\ndef download_asset(asset: dict[str, Any], dst: Path) -> Path:\n    name = asset[\"name\"]\n    assert isinstance(name, str)\n    download_url = asset[\"browser_download_url\"]\n    assert is_whl_or_tar(name)\n    with urlopen(download_url) as src_file:\n        with open(dst / name, \"wb\") as dst_file:\n            shutil.copyfileobj(src_file, dst_file)\n    return dst / name\n\n\ndef download_all_release_assets(release: dict[str, Any], dst: Path) -> None:\n    print(\"Downloading assets...\")\n    with ThreadPoolExecutor() as e:\n        for asset in e.map(lambda asset: download_asset(asset, dst), release[\"assets\"]):\n            print(f\"Downloaded {asset}\")\n\n\ndef check_sdist(dist: Path, version: str) -> None:\n    tarfiles = list(dist.glob(\"*.tar.gz\"))\n    assert len(tarfiles) == 1\n    sdist = tarfiles[0]\n    assert version in sdist.name\n    with tarfile.open(sdist) as f:\n        version_py = f.extractfile(f\"{sdist.name[:-len('.tar.gz')]}/mypy/version.py\")\n        assert version_py is not None\n        version_py_contents = version_py.read().decode(\"utf-8\")\n\n        # strip a git hash from our version, if necessary, since that's not present in version.py\n        match = re.match(r\"(.*\\+dev).*$\", version)\n        hashless_version = match.group(1) if match else version\n\n        assert (\n            f'\"{hashless_version}\"' in version_py_contents\n        ), \"Version does not match version.py in sdist\"\n\n\ndef spot_check_dist(dist: Path, version: str) -> None:\n    items = [item for item in dist.iterdir() if item_ok_for_pypi(item.name)]\n    assert len(items) > 10\n    assert all(version in item.name for item in items)\n    assert any(item.name.endswith(\"py3-none-any.whl\") for item in items)\n\n\n@contextlib.contextmanager\ndef tmp_twine() -> Iterator[Path]:\n    with tempfile.TemporaryDirectory() as tmp_dir:\n        tmp_venv_dir = Path(tmp_dir) / \"venv\"\n        venv.create(tmp_venv_dir, with_pip=True)\n        pip_exe = tmp_venv_dir / \"bin\" / \"pip\"\n        subprocess.check_call([pip_exe, \"install\", \"twine\"])\n        yield tmp_venv_dir / \"bin\" / \"twine\"\n\n\ndef upload_dist(dist: Path, dry_run: bool = True) -> None:\n    with tmp_twine() as twine:\n        files = [item for item in dist.iterdir() if item_ok_for_pypi(item.name)]\n        cmd: list[Any] = [twine, \"upload\", \"--skip-existing\"]\n        cmd += files\n        if dry_run:\n            print(\"[dry run] \" + \" \".join(map(str, cmd)))\n        else:\n            print(\" \".join(map(str, cmd)))\n            subprocess.check_call(cmd)\n\n\ndef upload_to_pypi(version: str, dry_run: bool = True) -> None:\n    assert re.match(r\"v?[1-9]\\.[0-9]+\\.[0-9](\\+\\S+)?$\", version)\n    if \"dev\" in version:\n        assert dry_run, \"Must use --dry-run with dev versions of mypy\"\n    version = version.removeprefix(\"v\")\n\n    target_dir = tempfile.mkdtemp()\n    dist = Path(target_dir) / \"dist\"\n    dist.mkdir()\n    print(f\"Temporary target directory: {target_dir}\")\n\n    release = get_release_for_tag(f\"v{version}\")\n    download_all_release_assets(release, dist)\n\n    spot_check_dist(dist, version)\n    check_sdist(dist, version)\n    upload_dist(dist, dry_run)\n    print(\"<< All done! >>\")\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser(description=\"PyPI mypy package uploader\")\n    parser.add_argument(\n        \"--dry-run\", action=\"store_true\", default=False, help=\"Don't actually upload packages\"\n    )\n    parser.add_argument(\"version\", help=\"mypy version to release\")\n    args = parser.parse_args()\n\n    upload_to_pypi(args.version, args.dry_run)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "mypy/__init__.py",
    "content": "# This page intentionally left blank\n"
  },
  {
    "path": "mypy/__main__.py",
    "content": "\"\"\"Mypy type checker command line tool.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport sys\nimport traceback\n\nfrom mypy.main import main, process_options\nfrom mypy.util import FancyFormatter\n\n\ndef console_entry() -> None:\n    try:\n        main()\n        sys.stdout.flush()\n        sys.stderr.flush()\n    except BrokenPipeError:\n        # Python flushes standard streams on exit; redirect remaining output\n        # to devnull to avoid another BrokenPipeError at shutdown\n        devnull = os.open(os.devnull, os.O_WRONLY)\n        os.dup2(devnull, sys.stdout.fileno())\n        sys.exit(2)\n    except KeyboardInterrupt:\n        _, options = process_options(args=sys.argv[1:])\n        if options.show_traceback:\n            sys.stdout.write(traceback.format_exc())\n        formatter = FancyFormatter(sys.stdout, sys.stderr, False)\n        msg = \"Interrupted\\n\"\n        sys.stdout.write(formatter.style(msg, color=\"red\", bold=True))\n        sys.stdout.flush()\n        sys.stderr.flush()\n        sys.exit(2)\n    except Exception as e:\n        # Try reporting any uncaught error canonically, otherwise just flush the traceback.\n        try:\n            import mypy.errors\n\n            _, options = process_options(args=sys.argv[1:])\n            mypy.errors.report_internal_error(e, None, 0, None, options)\n        except Exception:\n            pass\n        sys.stdout.write(traceback.format_exc())\n        sys.stdout.flush()\n        sys.stderr.flush()\n        sys.exit(2)\n\n\nif __name__ == \"__main__\":\n    console_entry()\n"
  },
  {
    "path": "mypy/api.py",
    "content": "\"\"\"This module makes it possible to use mypy as part of a Python application.\n\nSince mypy still changes, the API was kept utterly simple and non-intrusive.\nIt just mimics command line activation without starting a new interpreter.\nSo the normal docs about the mypy command line apply.\nChanges in the command line version of mypy will be immediately usable.\n\nJust import this module and then call the 'run' function with a parameter of\ntype List[str], containing what normally would have been the command line\narguments to mypy.\n\nFunction 'run' returns a Tuple[str, str, int], namely\n(<normal_report>, <error_report>, <exit_status>),\nin which <normal_report> is what mypy normally writes to sys.stdout,\n<error_report> is what mypy normally writes to sys.stderr and exit_status is\nthe exit status mypy normally returns to the operating system.\n\nAny pretty formatting is left to the caller.\n\nThe 'run_dmypy' function is similar, but instead mimics invocation of\ndmypy. Note that run_dmypy is not thread-safe and modifies sys.stdout\nand sys.stderr during its invocation.\n\nNote that these APIs don't support incremental generation of error\nmessages.\n\nTrivial example of code using this module:\n\nimport sys\nfrom mypy import api\n\nresult = api.run(sys.argv[1:])\n\nif result[0]:\n    print('\\nType checking report:\\n')\n    print(result[0])  # stdout\n\nif result[1]:\n    print('\\nError report:\\n')\n    print(result[1])  # stderr\n\nprint('\\nExit status:', result[2])\n\n\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nfrom collections.abc import Callable\nfrom io import StringIO\nfrom typing import TextIO\n\n\ndef _run(main_wrapper: Callable[[TextIO, TextIO], None]) -> tuple[str, str, int]:\n    stdout = StringIO()\n    stderr = StringIO()\n\n    try:\n        main_wrapper(stdout, stderr)\n        exit_status = 0\n    except SystemExit as system_exit:\n        assert isinstance(system_exit.code, int)\n        exit_status = system_exit.code\n\n    return stdout.getvalue(), stderr.getvalue(), exit_status\n\n\ndef run(args: list[str]) -> tuple[str, str, int]:\n    # Lazy import to avoid needing to import all of mypy to call run_dmypy\n    from mypy.main import main\n\n    return _run(\n        lambda stdout, stderr: main(args=args, stdout=stdout, stderr=stderr, clean_exit=True)\n    )\n\n\ndef run_dmypy(args: list[str]) -> tuple[str, str, int]:\n    from mypy.dmypy.client import main\n\n    # A bunch of effort has been put into threading stdout and stderr\n    # through the main API to avoid the threadsafety problems of\n    # modifying sys.stdout/sys.stderr, but that hasn't been done for\n    # the dmypy client, so we just do the non-threadsafe thing.\n    def f(stdout: TextIO, stderr: TextIO) -> None:\n        old_stdout = sys.stdout\n        old_stderr = sys.stderr\n        try:\n            sys.stdout = stdout\n            sys.stderr = stderr\n            main(args)\n        finally:\n            sys.stdout = old_stdout\n            sys.stderr = old_stderr\n\n    return _run(f)\n"
  },
  {
    "path": "mypy/applytype.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Callable, Iterable, Sequence\n\nimport mypy.subtypes\nfrom mypy.erasetype import erase_typevars\nfrom mypy.expandtype import expand_type\nfrom mypy.nodes import Context, TypeInfo\nfrom mypy.type_visitor import TypeTranslator\nfrom mypy.typeops import get_all_type_vars\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    Parameters,\n    ParamSpecFlavor,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    Type,\n    TypeAliasType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UninhabitedType,\n    UnpackType,\n    get_proper_type,\n    remove_dups,\n)\n\n\ndef get_target_type(\n    tvar: TypeVarLikeType,\n    type: Type,\n    callable: CallableType,\n    report_incompatible_typevar_value: Callable[[CallableType, Type, str, Context], None],\n    context: Context,\n    skip_unsatisfied: bool,\n) -> Type | None:\n    p_type = get_proper_type(type)\n    if isinstance(p_type, UninhabitedType) and tvar.has_default():\n        return tvar.default\n    if isinstance(tvar, ParamSpecType):\n        return type\n    if isinstance(tvar, TypeVarTupleType):\n        return type\n    assert isinstance(tvar, TypeVarType)\n    values = tvar.values\n    if values:\n        if isinstance(p_type, AnyType):\n            return type\n        if isinstance(p_type, TypeVarType) and p_type.values:\n            # Allow substituting T1 for T if every allowed value of T1\n            # is also a legal value of T.\n            if all(any(mypy.subtypes.is_same_type(v, v1) for v in values) for v1 in p_type.values):\n                return type\n        matching = []\n        for value in values:\n            if mypy.subtypes.is_subtype(type, value):\n                matching.append(value)\n        if matching:\n            best = matching[0]\n            # If there are more than one matching value, we select the narrowest\n            for match in matching[1:]:\n                if mypy.subtypes.is_subtype(match, best):\n                    best = match\n            return best\n        if skip_unsatisfied:\n            return None\n        report_incompatible_typevar_value(callable, type, tvar.name, context)\n    else:\n        upper_bound = tvar.upper_bound\n        if tvar.name == \"Self\":\n            # Internally constructed Self-types contain class type variables in upper bound,\n            # so we need to erase them to avoid false positives. This is safe because we do\n            # not support type variables in upper bounds of user defined types.\n            upper_bound = erase_typevars(upper_bound)\n        if not mypy.subtypes.is_subtype(type, upper_bound):\n            if skip_unsatisfied:\n                return None\n            report_incompatible_typevar_value(callable, type, tvar.name, context)\n    return type\n\n\ndef apply_generic_arguments(\n    callable: CallableType,\n    orig_types: Sequence[Type | None],\n    report_incompatible_typevar_value: Callable[[CallableType, Type, str, Context], None],\n    context: Context,\n    skip_unsatisfied: bool = False,\n) -> CallableType:\n    \"\"\"Apply generic type arguments to a callable type.\n\n    For example, applying [int] to 'def [T] (T) -> T' results in\n    'def (int) -> int'.\n\n    Note that each type can be None; in this case, it will not be applied.\n\n    If `skip_unsatisfied` is True, then just skip the types that don't satisfy type variable\n    bound or constraints, instead of giving an error.\n    \"\"\"\n    tvars = callable.variables\n    assert len(orig_types) <= len(tvars)\n    # Check that inferred type variable values are compatible with allowed\n    # values and bounds.  Also, promote subtype values to allowed values.\n    # Create a map from type variable id to target type.\n    id_to_type: dict[TypeVarId, Type] = {}\n\n    for tvar, type in zip(tvars, orig_types):\n        assert not isinstance(type, PartialType), \"Internal error: must never apply partial type\"\n        if type is None:\n            continue\n\n        target_type = get_target_type(\n            tvar, type, callable, report_incompatible_typevar_value, context, skip_unsatisfied\n        )\n        if target_type is not None:\n            id_to_type[tvar.id] = target_type\n\n    # TODO: validate arg_kinds/arg_names for ParamSpec and TypeVarTuple replacements,\n    # not just type variable bounds above.\n    param_spec = callable.param_spec()\n    if param_spec is not None:\n        nt = id_to_type.get(param_spec.id)\n        if nt is not None:\n            # ParamSpec expansion is special-cased, so we need to always expand callable\n            # as a whole, not expanding arguments individually.\n            callable = expand_type(callable, id_to_type)\n            assert isinstance(callable, CallableType)\n            return callable.copy_modified(\n                variables=[tv for tv in tvars if tv.id not in id_to_type]\n            )\n\n    # Apply arguments to argument types.\n    var_arg = callable.var_arg()\n    if var_arg is not None and isinstance(var_arg.typ, UnpackType):\n        # Same as for ParamSpec, callable with variadic types needs to be expanded as a whole.\n        callable = expand_type(callable, id_to_type)\n        assert isinstance(callable, CallableType)\n        return callable.copy_modified(variables=[tv for tv in tvars if tv.id not in id_to_type])\n    else:\n        callable = callable.copy_modified(\n            arg_types=[expand_type(at, id_to_type) for at in callable.arg_types]\n        )\n\n    # Apply arguments to TypeGuard and TypeIs if any.\n    if callable.type_guard is not None:\n        type_guard = expand_type(callable.type_guard, id_to_type)\n    else:\n        type_guard = None\n    if callable.type_is is not None:\n        type_is = expand_type(callable.type_is, id_to_type)\n    else:\n        type_is = None\n\n    # The callable may retain some type vars if only some were applied.\n    # TODO: move apply_poly() logic here when new inference\n    # becomes universally used (i.e. in all passes + in unification).\n    # With this new logic we can actually *add* some new free variables.\n    remaining_tvars: list[TypeVarLikeType] = []\n    for tv in tvars:\n        if tv.id in id_to_type:\n            continue\n        if not tv.has_default():\n            remaining_tvars.append(tv)\n            continue\n        # TypeVarLike isn't in id_to_type mapping.\n        # Only expand the TypeVar default here.\n        typ = expand_type(tv, id_to_type)\n        assert isinstance(typ, TypeVarLikeType)\n        remaining_tvars.append(typ)\n\n    return callable.copy_modified(\n        ret_type=expand_type(callable.ret_type, id_to_type),\n        variables=remaining_tvars,\n        type_guard=type_guard,\n        type_is=type_is,\n    )\n\n\ndef apply_poly(tp: CallableType, poly_tvars: Sequence[TypeVarLikeType]) -> CallableType | None:\n    \"\"\"Make free type variables generic in the type if possible.\n\n    This will translate the type `tp` while trying to create valid bindings for\n    type variables `poly_tvars` while traversing the type. This follows the same rules\n    as we do during semantic analysis phase, examples:\n      * Callable[Callable[[T], T], T] -> def [T] (def (T) -> T) -> T\n      * Callable[[], Callable[[T], T]] -> def () -> def [T] (T -> T)\n      * List[T] -> None (not possible)\n    \"\"\"\n    try:\n        return tp.copy_modified(\n            arg_types=[t.accept(PolyTranslator(poly_tvars)) for t in tp.arg_types],\n            ret_type=tp.ret_type.accept(PolyTranslator(poly_tvars)),\n            variables=[],\n        )\n    except PolyTranslationError:\n        return None\n\n\nclass PolyTranslationError(Exception):\n    pass\n\n\nclass PolyTranslator(TypeTranslator):\n    \"\"\"Make free type variables generic in the type if possible.\n\n    See docstring for apply_poly() for details.\n    \"\"\"\n\n    def __init__(\n        self,\n        poly_tvars: Iterable[TypeVarLikeType],\n        bound_tvars: frozenset[TypeVarLikeType] = frozenset(),\n        seen_aliases: frozenset[TypeInfo] = frozenset(),\n    ) -> None:\n        super().__init__()\n        self.poly_tvars = set(poly_tvars)\n        # This is a simplified version of TypeVarScope used during semantic analysis.\n        self.bound_tvars = bound_tvars\n        self.seen_aliases = seen_aliases\n\n    def collect_vars(self, t: CallableType | Parameters) -> list[TypeVarLikeType]:\n        found_vars = []\n        for arg in t.arg_types:\n            for tv in get_all_type_vars(arg):\n                if isinstance(tv, ParamSpecType):\n                    normalized: TypeVarLikeType = tv.copy_modified(\n                        flavor=ParamSpecFlavor.BARE, prefix=Parameters([], [], [])\n                    )\n                else:\n                    normalized = tv\n                if normalized in self.poly_tvars and normalized not in self.bound_tvars:\n                    found_vars.append(normalized)\n        return remove_dups(found_vars)\n\n    def visit_callable_type(self, t: CallableType) -> Type:\n        found_vars = self.collect_vars(t)\n        self.bound_tvars |= set(found_vars)\n        result = super().visit_callable_type(t)\n        self.bound_tvars -= set(found_vars)\n\n        assert isinstance(result, ProperType) and isinstance(result, CallableType)\n        result.variables = result.variables + tuple(found_vars)\n        return result\n\n    def visit_type_var(self, t: TypeVarType) -> Type:\n        if t in self.poly_tvars and t not in self.bound_tvars:\n            raise PolyTranslationError()\n        return super().visit_type_var(t)\n\n    def visit_param_spec(self, t: ParamSpecType) -> Type:\n        if t in self.poly_tvars and t not in self.bound_tvars:\n            raise PolyTranslationError()\n        return super().visit_param_spec(t)\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type:\n        if t in self.poly_tvars and t not in self.bound_tvars:\n            raise PolyTranslationError()\n        return super().visit_type_var_tuple(t)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        if not t.args:\n            return t.copy_modified()\n        if not t.is_recursive:\n            return get_proper_type(t).accept(self)\n        # We can't handle polymorphic application for recursive generic aliases\n        # without risking an infinite recursion, just give up for now.\n        raise PolyTranslationError()\n\n    def visit_instance(self, t: Instance) -> Type:\n        if t.type.has_param_spec_type:\n            # We need this special-casing to preserve the possibility to store a\n            # generic function in an instance type. Things like\n            #     forall T . Foo[[x: T], T]\n            # are not really expressible in current type system, but this looks like\n            # a useful feature, so let's keep it.\n            param_spec_index = next(\n                i for (i, tv) in enumerate(t.type.defn.type_vars) if isinstance(tv, ParamSpecType)\n            )\n            p = get_proper_type(t.args[param_spec_index])\n            if isinstance(p, Parameters):\n                found_vars = self.collect_vars(p)\n                self.bound_tvars |= set(found_vars)\n                new_args = [a.accept(self) for a in t.args]\n                self.bound_tvars -= set(found_vars)\n\n                repl = new_args[param_spec_index]\n                assert isinstance(repl, ProperType) and isinstance(repl, Parameters)\n                repl.variables = list(repl.variables) + list(found_vars)\n                return t.copy_modified(args=new_args)\n        # There is the same problem with callback protocols as with aliases\n        # (callback protocols are essentially more flexible aliases to callables).\n        if t.args and t.type.is_protocol and t.type.protocol_members == [\"__call__\"]:\n            if t.type in self.seen_aliases:\n                raise PolyTranslationError()\n            call = mypy.subtypes.find_member(\"__call__\", t, t, is_operator=True)\n            assert call is not None\n            return call.accept(\n                PolyTranslator(self.poly_tvars, self.bound_tvars, self.seen_aliases | {t.type})\n            )\n        return super().visit_instance(t)\n"
  },
  {
    "path": "mypy/argmap.py",
    "content": "\"\"\"Utilities for mapping between actual and formal arguments (and their types).\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable, Sequence\nfrom typing import TYPE_CHECKING\n\nfrom mypy import nodes\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.types import (\n    AnyType,\n    Instance,\n    ParamSpecType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeOfAny,\n    TypeVarTupleType,\n    UnpackType,\n    get_proper_type,\n)\n\nif TYPE_CHECKING:\n    from mypy.infer import ArgumentInferContext\n\n\ndef map_actuals_to_formals(\n    actual_kinds: list[nodes.ArgKind],\n    actual_names: Sequence[str | None] | None,\n    formal_kinds: list[nodes.ArgKind],\n    formal_names: Sequence[str | None],\n    actual_arg_type: Callable[[int], Type],\n) -> list[list[int]]:\n    \"\"\"Calculate mapping between actual (caller) args and formals.\n\n    The result contains a list of caller argument indexes mapping to each\n    callee argument index, indexed by callee index.\n\n    The actual_arg_type argument should evaluate to the type of the actual\n    argument with the given index.\n    \"\"\"\n    nformals = len(formal_kinds)\n    formal_to_actual: list[list[int]] = [[] for i in range(nformals)]\n    ambiguous_actual_kwargs: list[int] = []\n    fi = 0\n    for ai, actual_kind in enumerate(actual_kinds):\n        if actual_kind == nodes.ARG_POS:\n            if fi < nformals:\n                if not formal_kinds[fi].is_star():\n                    formal_to_actual[fi].append(ai)\n                    fi += 1\n                elif formal_kinds[fi] == nodes.ARG_STAR:\n                    formal_to_actual[fi].append(ai)\n        elif actual_kind == nodes.ARG_STAR:\n            # We need to know the actual type to map varargs.\n            actualt = get_proper_type(actual_arg_type(ai))\n            if isinstance(actualt, TupleType):\n                # A tuple actual maps to a fixed number of formals.\n                for _ in range(len(actualt.items)):\n                    if fi < nformals:\n                        if formal_kinds[fi] != nodes.ARG_STAR2:\n                            formal_to_actual[fi].append(ai)\n                        else:\n                            break\n                        if formal_kinds[fi] != nodes.ARG_STAR:\n                            fi += 1\n            else:\n                # Assume that it is an iterable (if it isn't, there will be\n                # an error later).\n                while fi < nformals:\n                    if formal_kinds[fi].is_named(star=True):\n                        break\n                    else:\n                        formal_to_actual[fi].append(ai)\n                    if formal_kinds[fi] == nodes.ARG_STAR:\n                        break\n                    fi += 1\n        elif actual_kind.is_named():\n            assert actual_names is not None, \"Internal error: named kinds without names given\"\n            name = actual_names[ai]\n            if name in formal_names and formal_kinds[formal_names.index(name)] != nodes.ARG_STAR:\n                formal_to_actual[formal_names.index(name)].append(ai)\n            elif nodes.ARG_STAR2 in formal_kinds:\n                formal_to_actual[formal_kinds.index(nodes.ARG_STAR2)].append(ai)\n        else:\n            assert actual_kind == nodes.ARG_STAR2\n            actualt = get_proper_type(actual_arg_type(ai))\n            if isinstance(actualt, TypedDictType):\n                for name in actualt.items:\n                    if name in formal_names:\n                        formal_to_actual[formal_names.index(name)].append(ai)\n                    elif nodes.ARG_STAR2 in formal_kinds:\n                        formal_to_actual[formal_kinds.index(nodes.ARG_STAR2)].append(ai)\n            else:\n                # We don't exactly know which **kwargs are provided by the\n                # caller, so we'll defer until all the other unambiguous\n                # actuals have been processed\n                ambiguous_actual_kwargs.append(ai)\n\n    if ambiguous_actual_kwargs:\n        # Assume the ambiguous kwargs will fill the remaining arguments.\n        #\n        # TODO: If there are also tuple varargs, we might be missing some potential\n        #       matches if the tuple was short enough to not match everything.\n        unmatched_formals = [\n            fi\n            for fi in range(nformals)\n            if (\n                formal_names[fi]\n                and (\n                    not formal_to_actual[fi]\n                    or actual_kinds[formal_to_actual[fi][0]] == nodes.ARG_STAR\n                )\n                and formal_kinds[fi] != nodes.ARG_STAR\n            )\n            or formal_kinds[fi] == nodes.ARG_STAR2\n        ]\n        for ai in ambiguous_actual_kwargs:\n            for fi in unmatched_formals:\n                formal_to_actual[fi].append(ai)\n\n    return formal_to_actual\n\n\ndef map_formals_to_actuals(\n    actual_kinds: list[nodes.ArgKind],\n    actual_names: Sequence[str | None] | None,\n    formal_kinds: list[nodes.ArgKind],\n    formal_names: list[str | None],\n    actual_arg_type: Callable[[int], Type],\n) -> list[list[int]]:\n    \"\"\"Calculate the reverse mapping of map_actuals_to_formals.\"\"\"\n    formal_to_actual = map_actuals_to_formals(\n        actual_kinds, actual_names, formal_kinds, formal_names, actual_arg_type\n    )\n    # Now reverse the mapping.\n    actual_to_formal: list[list[int]] = [[] for _ in actual_kinds]\n    for formal, actuals in enumerate(formal_to_actual):\n        for actual in actuals:\n            actual_to_formal[actual].append(formal)\n    return actual_to_formal\n\n\nclass ArgTypeExpander:\n    \"\"\"Utility class for mapping actual argument types to formal arguments.\n\n    One of the main responsibilities is to expand caller tuple *args and TypedDict\n    **kwargs, and to keep track of which tuple/TypedDict items have already been\n    consumed.\n\n    Example:\n\n       def f(x: int, *args: str) -> None: ...\n       f(*(1, 'x', 1.1))\n\n    We'd call expand_actual_type three times:\n\n      1. The first call would provide 'int' as the actual type of 'x' (from '1').\n      2. The second call would provide 'str' as one of the actual types for '*args'.\n      2. The third call would provide 'float' as one of the actual types for '*args'.\n\n    A single instance can process all the arguments for a single call. Each call\n    needs a separate instance since instances have per-call state.\n    \"\"\"\n\n    def __init__(self, context: ArgumentInferContext) -> None:\n        # Next tuple *args index to use.\n        self.tuple_index = 0\n        # Keyword arguments in TypedDict **kwargs used.\n        self.kwargs_used: set[str] | None = None\n        # Type context for `*` and `**` arg kinds.\n        self.context = context\n\n    def expand_actual_type(\n        self,\n        actual_type: Type,\n        actual_kind: nodes.ArgKind,\n        formal_name: str | None,\n        formal_kind: nodes.ArgKind,\n        allow_unpack: bool = False,\n    ) -> Type:\n        \"\"\"Return the actual (caller) type(s) of a formal argument with the given kinds.\n\n        If the actual argument is a tuple *args, return the next individual tuple item that\n        maps to the formal arg.\n\n        If the actual argument is a TypedDict **kwargs, return the next matching typed dict\n        value type based on formal argument name and kind.\n\n        This is supposed to be called for each formal, in order. Call multiple times per\n        formal if multiple actuals map to a formal.\n        \"\"\"\n        original_actual = actual_type\n        actual_type = get_proper_type(actual_type)\n        if actual_kind == nodes.ARG_STAR:\n            if isinstance(actual_type, TypeVarTupleType):\n                # This code path is hit when *Ts is passed to a callable and various\n                # special-handling didn't catch this. The best thing we can do is to use\n                # the upper bound.\n                actual_type = get_proper_type(actual_type.upper_bound)\n            if isinstance(actual_type, Instance) and actual_type.args:\n                from mypy.subtypes import is_subtype\n\n                if is_subtype(actual_type, self.context.iterable_type):\n                    return map_instance_to_supertype(\n                        actual_type, self.context.iterable_type.type\n                    ).args[0]\n                else:\n                    # We cannot properly unpack anything other\n                    # than `Iterable` type with `*`.\n                    # Just return `Any`, other parts of code would raise\n                    # a different error for improper use.\n                    return AnyType(TypeOfAny.from_error)\n            elif isinstance(actual_type, TupleType):\n                # Get the next tuple item of a tuple *arg.\n                if self.tuple_index >= len(actual_type.items):\n                    # Exhausted a tuple -- continue to the next *args.\n                    self.tuple_index = 1\n                else:\n                    self.tuple_index += 1\n                item = actual_type.items[self.tuple_index - 1]\n                if isinstance(item, UnpackType) and not allow_unpack:\n                    # An unpack item that doesn't have special handling, use upper bound as above.\n                    unpacked = get_proper_type(item.type)\n                    if isinstance(unpacked, TypeVarTupleType):\n                        fallback = get_proper_type(unpacked.upper_bound)\n                    else:\n                        fallback = unpacked\n                    assert (\n                        isinstance(fallback, Instance)\n                        and fallback.type.fullname == \"builtins.tuple\"\n                    )\n                    item = fallback.args[0]\n                return item\n            elif isinstance(actual_type, ParamSpecType):\n                # ParamSpec is valid in *args but it can't be unpacked.\n                return actual_type\n            else:\n                return AnyType(TypeOfAny.from_error)\n        elif actual_kind == nodes.ARG_STAR2:\n            from mypy.subtypes import is_subtype\n\n            if isinstance(actual_type, TypedDictType):\n                if self.kwargs_used is None:\n                    self.kwargs_used = set()\n                if formal_kind != nodes.ARG_STAR2 and formal_name in actual_type.items:\n                    # Lookup type based on keyword argument name.\n                    assert formal_name is not None\n                else:\n                    # Pick an arbitrary item if no specified keyword is expected.\n                    formal_name = (set(actual_type.items.keys()) - self.kwargs_used).pop()\n                self.kwargs_used.add(formal_name)\n                return actual_type.items[formal_name]\n            elif isinstance(actual_type, Instance) and is_subtype(\n                actual_type, self.context.mapping_type\n            ):\n                # Only `Mapping` type can be unpacked with `**`.\n                # Other types will produce an error somewhere else.\n                return map_instance_to_supertype(actual_type, self.context.mapping_type.type).args[\n                    1\n                ]\n            elif isinstance(actual_type, ParamSpecType):\n                # ParamSpec is valid in **kwargs but it can't be unpacked.\n                return actual_type\n            else:\n                return AnyType(TypeOfAny.from_error)\n        else:\n            # No translation for other kinds -- 1:1 mapping.\n            return original_actual\n"
  },
  {
    "path": "mypy/binder.py",
    "content": "from __future__ import annotations\n\nfrom collections import defaultdict\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom typing import Literal, NamedTuple, TypeAlias as _TypeAlias\n\nfrom mypy.erasetype import remove_instance_last_known_values\nfrom mypy.literals import Key, extract_var_from_literal_hash, literal, literal_hash, subkeys\nfrom mypy.nodes import (\n    LITERAL_NO,\n    Expression,\n    IndexExpr,\n    MemberExpr,\n    NameExpr,\n    RefExpr,\n    TypeInfo,\n    Var,\n)\nfrom mypy.options import Options\nfrom mypy.subtypes import is_same_type, is_subtype\nfrom mypy.typeops import make_simplified_union\nfrom mypy.types import (\n    AnyType,\n    Instance,\n    NoneType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeType,\n    TypeVarType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    flatten_nested_unions,\n    get_proper_type,\n)\nfrom mypy.typevars import fill_typevars_with_any\n\nBindableExpression: _TypeAlias = IndexExpr | MemberExpr | NameExpr\n\n\nclass CurrentType(NamedTuple):\n    type: Type\n    from_assignment: bool\n\n\nclass Frame:\n    \"\"\"A Frame represents a specific point in the execution of a program.\n\n    It carries information about the current types of expressions at\n    that point, arising either from assignments to those expressions\n    or the result of isinstance checks and other type narrowing\n    operations. It also records whether it is possible to reach that\n    point at all.\n\n    We add a new frame wherenever there is a new scope or control flow\n    branching.\n\n    This information is not copied into a new Frame when it is pushed\n    onto the stack, so a given Frame only has information about types\n    that were assigned in that frame.\n\n    Expressions are stored in dicts using 'literal hashes' as keys (type\n    \"Key\"). These are hashable values derived from expression AST nodes\n    (only those that can be narrowed). literal_hash(expr) is used to\n    calculate the hashes. Note that this isn't directly related to literal\n    types -- the concept predates literal types.\n    \"\"\"\n\n    def __init__(self, id: int, conditional_frame: bool = False) -> None:\n        self.id = id\n        self.types: dict[Key, CurrentType] = {}\n        self.unreachable = False\n        self.conditional_frame = conditional_frame\n        self.suppress_unreachable_warnings = False\n\n    def __repr__(self) -> str:\n        return f\"Frame({self.id}, {self.types}, {self.unreachable}, {self.conditional_frame})\"\n\n\nAssigns = defaultdict[Expression, list[tuple[Type, Type | None]]]\n\n\nclass FrameContext:\n    \"\"\"Context manager pushing a Frame to ConditionalTypeBinder.\n\n    See frame_context() below for documentation on parameters. We use this class\n    instead of @contextmanager as a mypyc-specific performance optimization.\n    \"\"\"\n\n    def __init__(\n        self,\n        binder: ConditionalTypeBinder,\n        can_skip: bool,\n        fall_through: int,\n        break_frame: int,\n        continue_frame: int,\n        conditional_frame: bool,\n        try_frame: bool,\n        discard: bool,\n    ) -> None:\n        self.binder = binder\n        self.can_skip = can_skip\n        self.fall_through = fall_through\n        self.break_frame = break_frame\n        self.continue_frame = continue_frame\n        self.conditional_frame = conditional_frame\n        self.try_frame = try_frame\n        self.discard = discard\n\n    def __enter__(self) -> Frame:\n        assert len(self.binder.frames) > 1\n\n        if self.break_frame:\n            self.binder.break_frames.append(len(self.binder.frames) - self.break_frame)\n        if self.continue_frame:\n            self.binder.continue_frames.append(len(self.binder.frames) - self.continue_frame)\n        if self.try_frame:\n            self.binder.try_frames.add(len(self.binder.frames) - 1)\n\n        new_frame = self.binder.push_frame(self.conditional_frame)\n        if self.try_frame:\n            # An exception may occur immediately\n            self.binder.allow_jump(-1)\n        return new_frame\n\n    def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> Literal[False]:\n        self.binder.pop_frame(self.can_skip, self.fall_through, discard=self.discard)\n\n        if self.break_frame:\n            self.binder.break_frames.pop()\n        if self.continue_frame:\n            self.binder.continue_frames.pop()\n        if self.try_frame:\n            self.binder.try_frames.remove(len(self.binder.frames) - 1)\n        return False\n\n\nclass ConditionalTypeBinder:\n    \"\"\"Keep track of conditional types of variables.\n\n    NB: Variables are tracked by literal hashes of expressions, so it is\n    possible to confuse the binder when there is aliasing. Example:\n\n        class A:\n            a: int | str\n\n        x = A()\n        lst = [x]\n        reveal_type(x.a)      # int | str\n        x.a = 1\n        reveal_type(x.a)      # int\n        reveal_type(lst[0].a) # int | str\n        lst[0].a = 'a'\n        reveal_type(x.a)      # int\n        reveal_type(lst[0].a) # str\n    \"\"\"\n\n    # Stored assignments for situations with tuple/list lvalue and rvalue of union type.\n    # This maps an expression to a list of bound types for every item in the union type.\n    type_assignments: Assigns | None = None\n\n    def __init__(self, options: Options) -> None:\n        # Each frame gets an increasing, distinct id.\n        self.next_id = 1\n\n        # The stack of frames currently used.  These map\n        # literal_hash(expr) -- literals like 'foo.bar' --\n        # to types. The last element of this list is the\n        # top-most, current frame. Each earlier element\n        # records the state as of when that frame was last\n        # on top of the stack.\n        self.frames = [Frame(self._get_id())]\n\n        # For frames higher in the stack, we record the set of\n        # Frames that can escape there, either by falling off\n        # the end of the frame or by a loop control construct\n        # or raised exception. The last element of self.frames\n        # has no corresponding element in this list.\n        self.options_on_return: list[list[Frame]] = []\n\n        # Maps literal_hash(expr) to get_declaration(expr)\n        # for every expr stored in the binder\n        self.declarations: dict[Key, Type | None] = {}\n        # Set of other keys to invalidate if a key is changed, e.g. x -> {x.a, x[0]}\n        # Whenever a new key (e.g. x.a.b) is added, we update this\n        self.dependencies: dict[Key, set[Key]] = {}\n\n        # Whether the last pop changed the newly top frame on exit\n        self.last_pop_changed = False\n\n        # These are used to track control flow in try statements and loops.\n        self.try_frames: set[int] = set()\n        self.break_frames: list[int] = []\n        self.continue_frames: list[int] = []\n\n        # If True, initial assignment to a simple variable (e.g. \"x\", but not \"x.y\")\n        # is added to the binder. This allows more precise narrowing and more\n        # flexible inference of variable types (--allow-redefinition-new).\n        self.bind_all = options.allow_redefinition_new\n\n        # This tracks any externally visible changes in binder to invalidate\n        # expression caches when needed.\n        self.version = 0\n\n    def _get_id(self) -> int:\n        self.next_id += 1\n        return self.next_id\n\n    def _add_dependencies(self, key: Key, value: Key | None = None) -> None:\n        if value is None:\n            value = key\n        else:\n            self.dependencies.setdefault(key, set()).add(value)\n        for elt in subkeys(key):\n            self._add_dependencies(elt, value)\n\n    def push_frame(self, conditional_frame: bool = False) -> Frame:\n        \"\"\"Push a new frame into the binder.\"\"\"\n        f = Frame(self._get_id(), conditional_frame)\n        self.frames.append(f)\n        self.options_on_return.append([])\n        return f\n\n    def _put(self, key: Key, type: Type, from_assignment: bool, index: int = -1) -> None:\n        self.version += 1\n        self.frames[index].types[key] = CurrentType(type, from_assignment)\n\n    def _get(self, key: Key, index: int = -1) -> CurrentType | None:\n        if index < 0:\n            index += len(self.frames)\n        for i in range(index, -1, -1):\n            if key in self.frames[i].types:\n                return self.frames[i].types[key]\n        return None\n\n    @classmethod\n    def can_put_directly(cls, expr: Expression) -> bool:\n        \"\"\"Will `.put()` on this expression be successful?\n\n        This is inlined in `.put()` because the logic is rather hot and must be kept\n        in sync.\n        \"\"\"\n        return isinstance(expr, (IndexExpr, MemberExpr, NameExpr)) and literal(expr) > LITERAL_NO\n\n    def put(self, expr: Expression, typ: Type, *, from_assignment: bool = True) -> None:\n        \"\"\"Directly set the narrowed type of expression (if it supports it).\n\n        This is used for isinstance() etc. Assignments should go through assign_type().\n        \"\"\"\n        if not isinstance(expr, (IndexExpr, MemberExpr, NameExpr)):\n            return\n        if not literal(expr):\n            return\n        key = literal_hash(expr)\n        assert key is not None, \"Internal error: binder tried to put non-literal\"\n        if key not in self.declarations:\n            self.declarations[key] = get_declaration(expr)\n            self._add_dependencies(key)\n        self._put(key, typ, from_assignment)\n\n    def unreachable(self) -> None:\n        self.version += 1\n        self.frames[-1].unreachable = True\n\n    def suppress_unreachable_warnings(self) -> None:\n        self.frames[-1].suppress_unreachable_warnings = True\n\n    def get(self, expr: Expression) -> Type | None:\n        key = literal_hash(expr)\n        assert key is not None, \"Internal error: binder tried to get non-literal\"\n        found = self._get(key)\n        if found is None:\n            return None\n        return found.type\n\n    def is_unreachable(self) -> bool:\n        # TODO: Copy the value of unreachable into new frames to avoid\n        # this traversal on every statement?\n        return any(f.unreachable for f in self.frames)\n\n    def is_unreachable_warning_suppressed(self) -> bool:\n        return any(f.suppress_unreachable_warnings for f in self.frames)\n\n    def cleanse(self, expr: Expression) -> None:\n        \"\"\"Remove all references to a Node from the binder.\"\"\"\n        key = literal_hash(expr)\n        assert key is not None, \"Internal error: binder tried cleanse non-literal\"\n        self._cleanse_key(key)\n\n    def _cleanse_key(self, key: Key) -> None:\n        \"\"\"Remove all references to a key from the binder.\"\"\"\n        for frame in self.frames:\n            if key in frame.types:\n                del frame.types[key]\n\n    def update_from_options(self, frames: list[Frame]) -> bool:\n        \"\"\"Update the frame to reflect that each key will be updated\n        as in one of the frames.  Return whether any item changes.\n\n        If a key is declared as AnyType, only update it if all the\n        options are the same.\n        \"\"\"\n        all_reachable = all(not f.unreachable for f in frames)\n        if not all_reachable:\n            frames = [f for f in frames if not f.unreachable]\n        changed = False\n        keys = [key for f in frames for key in f.types]\n        if len(keys) > 1:\n            keys = list(set(keys))\n        for key in keys:\n            current_value = self._get(key)\n            resulting_values = [f.types.get(key, current_value) for f in frames]\n            # Keys can be narrowed using two different semantics. The new semantics\n            # is enabled for inferred variables when bind_all is true, and it allows\n            # variable types to be widened using subsequent assignments. This is\n            # not allowed for instance attributes and annotated variables.\n            var = extract_var_from_literal_hash(key)\n            old_semantics = (\n                not self.bind_all or var is None or not var.is_inferred and not var.is_argument\n            )\n            if old_semantics and any(x is None for x in resulting_values):\n                # We didn't know anything about key before\n                # (current_value must be None), and we still don't\n                # know anything about key in at least one possible frame.\n                continue\n\n            resulting_values = [x for x in resulting_values if x is not None]\n\n            if all_reachable and all(not x.from_assignment for x in resulting_values):\n                # Do not synthesize a new type if we encountered a conditional block\n                # (if, while or match-case) without assignments.\n                # See check-isinstance.test::testNoneCheckDoesNotMakeTypeVarOptional\n                # This is a safe assumption: the fact that we checked something with `is`\n                # or `isinstance` does not change the type of the value.\n                continue\n\n            # Remove exact duplicates to save pointless work later, this is\n            # a micro-optimization for --allow-redefinition-new.\n            seen_types = set()\n            resulting_types = []\n            for rv in resulting_values:\n                assert rv is not None\n                if rv.type in seen_types:\n                    continue\n                resulting_types.append(rv.type)\n                seen_types.add(rv.type)\n\n            type = resulting_types[0]\n            declaration_type = get_proper_type(self.declarations.get(key))\n            if isinstance(declaration_type, AnyType):\n                # At this point resulting values can't contain None, see continue above\n                if not all(is_same_type(type, t) for t in resulting_types[1:]):\n                    type = AnyType(TypeOfAny.from_another_any, source_any=declaration_type)\n            else:\n                possible_types = []\n                for t in resulting_types:\n                    assert t is not None\n                    possible_types.append(t)\n                if len(possible_types) == 1:\n                    # This is to avoid calling get_proper_type() unless needed, as this may\n                    # interfere with our (hacky) TypeGuard support.\n                    type = possible_types[0]\n                else:\n                    type = make_simplified_union(possible_types)\n                    # Legacy guard for corner case when the original type is TypeVarType.\n                    if isinstance(declaration_type, TypeVarType) and not is_subtype(\n                        type, declaration_type\n                    ):\n                        type = declaration_type\n                    # Try simplifying resulting type for unions involving variadic tuples.\n                    # Technically, everything is still valid without this step, but if we do\n                    # not do this, this may create long unions after exiting an if check like:\n                    #     x: tuple[int, ...]\n                    #     if len(x) < 10:\n                    #         ...\n                    # We want the type of x to be tuple[int, ...] after this block (if it is\n                    # still equivalent to such type).\n                    if isinstance(type, UnionType):\n                        type = collapse_variadic_union(type)\n                    if (\n                        old_semantics\n                        and isinstance(type, ProperType)\n                        and isinstance(type, UnionType)\n                    ):\n                        # Simplify away any extra Any's that were added to the declared\n                        # type when popping a frame.\n                        simplified = UnionType.make_union(\n                            [t for t in type.items if not isinstance(get_proper_type(t), AnyType)]\n                        )\n                        if simplified == self.declarations[key]:\n                            type = simplified\n            if (\n                current_value is None\n                or not is_same_type(type, current_value.type)\n                # Manually carry over any narrowing from hasattr() from inner frames. This is\n                # a bit ad-hoc, but our handling of hasattr() is on best effort basis anyway.\n                or isinstance(p_type := get_proper_type(type), Instance)\n                and p_type.extra_attrs\n            ):\n                self._put(key, type, from_assignment=True)\n                if current_value is not None or extract_var_from_literal_hash(key) is None:\n                    # We definitely learned something new\n                    changed = True\n                elif not changed:\n                    # If there is no current value compare with the declaration. This prevents\n                    # reporting false changes in cases like this:\n                    #     x: int\n                    #     if foo():\n                    #         x = 1\n                    #     else:\n                    #         x = 2\n                    # We check partial types and widening in accept_loop() separately, so\n                    # this should be safe.\n                    changed = declaration_type is not None and not is_same_type(\n                        type, declaration_type\n                    )\n\n        self.frames[-1].unreachable = not frames\n\n        return changed\n\n    def pop_frame(self, can_skip: bool, fall_through: int, *, discard: bool = False) -> Frame:\n        \"\"\"Pop a frame and return it.\n\n        See frame_context() for documentation of fall_through and discard.\n        \"\"\"\n\n        if fall_through > 0:\n            self.allow_jump(-fall_through)\n\n        result = self.frames.pop()\n        options = self.options_on_return.pop()\n\n        if discard:\n            self.last_pop_changed = False\n            return result\n\n        if can_skip:\n            options.insert(0, self.frames[-1])\n\n        self.last_pop_changed = self.update_from_options(options)\n\n        return result\n\n    @contextmanager\n    def accumulate_type_assignments(self) -> Iterator[Assigns]:\n        \"\"\"Push a new map to collect assigned types in multiassign from union.\n\n        If this map is not None, actual binding is deferred until all items in\n        the union are processed (a union of collected items is later bound\n        manually by the caller).\n        \"\"\"\n        old_assignments = None\n        if self.type_assignments is not None:\n            old_assignments = self.type_assignments\n        self.type_assignments = defaultdict(list)\n        yield self.type_assignments\n        self.type_assignments = old_assignments\n\n    def assign_type(self, expr: Expression, type: Type, declared_type: Type | None) -> None:\n        \"\"\"Narrow type of expression through an assignment.\n\n        Do nothing if the expression doesn't support narrowing.\n\n        When not narrowing though an assignment (isinstance() etc.), use put()\n        directly. This omits some special-casing logic for assignments.\n        \"\"\"\n        # We should erase last known value in binder, because if we are using it,\n        # it means that the target is not final, and therefore can't hold a literal.\n        type = remove_instance_last_known_values(type)\n\n        if self.type_assignments is not None:\n            # We are in a multiassign from union, defer the actual binding,\n            # just collect the types.\n            self.type_assignments[expr].append((type, declared_type))\n            return\n        if not isinstance(expr, (IndexExpr, MemberExpr, NameExpr)):\n            return\n        if not literal(expr):\n            return\n        self.invalidate_dependencies(expr)\n\n        if declared_type is None:\n            # Not sure why this happens.  It seems to mainly happen in\n            # member initialization.\n            return\n        if not is_subtype(type, declared_type):\n            # Pretty sure this is only happens when there's a type error.\n\n            # Ideally this function wouldn't be called if the\n            # expression has a type error, though -- do other kinds of\n            # errors cause this function to get called at invalid\n            # times?\n            return\n\n        p_declared = get_proper_type(declared_type)\n        p_type = get_proper_type(type)\n        if isinstance(p_type, AnyType):\n            # Any type requires some special casing, for both historical reasons,\n            # and to optimise user experience without sacrificing correctness too much.\n            if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_inferred:\n                # First case: a local/global variable without explicit annotation,\n                # in this case we just assign Any (essentially following the SSA logic).\n                self.put(expr, type)\n            elif isinstance(p_declared, UnionType):\n                all_items = flatten_nested_unions(p_declared.items)\n                if any(isinstance(get_proper_type(item), NoneType) for item in all_items):\n                    # Second case: explicit optional type, in this case we optimize for\n                    # a common pattern when an untyped value used as a fallback replacing None.\n                    new_items = [\n                        type if isinstance(get_proper_type(item), NoneType) else item\n                        for item in all_items\n                    ]\n                    self.put(expr, UnionType(new_items))\n                elif any(isinstance(get_proper_type(item), AnyType) for item in all_items):\n                    # Third case: a union already containing Any (most likely from\n                    # an un-imported name), in this case we allow assigning Any as well.\n                    self.put(expr, type)\n                else:\n                    # In all other cases we don't narrow to Any to minimize false negatives.\n                    self.put(expr, declared_type)\n            else:\n                self.put(expr, declared_type)\n        elif isinstance(p_declared, AnyType):\n            # Mirroring the first case above, we don't narrow to a precise type if the variable\n            # has an explicit `Any` type annotation.\n            if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_inferred:\n                self.put(expr, type)\n            else:\n                self.put(expr, declared_type)\n        else:\n            self.put(expr, type)\n\n        for i in self.try_frames:\n            # XXX This should probably not copy the entire frame, but\n            # just copy this variable into a single stored frame.\n            self.allow_jump(i)\n\n    def invalidate_dependencies(self, expr: BindableExpression) -> None:\n        \"\"\"Invalidate knowledge of types that include expr, but not expr itself.\n\n        For example, when expr is foo.bar, invalidate foo.bar.baz.\n\n        It is overly conservative: it invalidates globally, including\n        in code paths unreachable from here.\n        \"\"\"\n        key = literal_hash(expr)\n        assert key is not None\n        for dep in self.dependencies.get(key, set()):\n            self._cleanse_key(dep)\n\n    def allow_jump(self, index: int) -> None:\n        # self.frames and self.options_on_return have different lengths\n        # so make sure the index is positive\n        if index < 0:\n            index += len(self.options_on_return)\n        frame = Frame(self._get_id())\n        for f in self.frames[index + 1 :]:\n            frame.types.update(f.types)\n            if f.unreachable:\n                frame.unreachable = True\n        self.options_on_return[index].append(frame)\n\n    def handle_break(self) -> None:\n        self.allow_jump(self.break_frames[-1])\n        self.unreachable()\n\n    def handle_continue(self) -> None:\n        self.allow_jump(self.continue_frames[-1])\n        self.unreachable()\n\n    def frame_context(\n        self,\n        *,\n        can_skip: bool,\n        fall_through: int = 1,\n        break_frame: int = 0,\n        continue_frame: int = 0,\n        conditional_frame: bool = False,\n        try_frame: bool = False,\n        discard: bool = False,\n    ) -> FrameContext:\n        \"\"\"Return a context manager that pushes/pops frames on enter/exit.\n\n        If can_skip is True, control flow is allowed to bypass the\n        newly-created frame.\n\n        If fall_through > 0, then it will allow control flow that\n        falls off the end of the frame to escape to its ancestor\n        `fall_through` levels higher. Otherwise, control flow ends\n        at the end of the frame.\n\n        If break_frame > 0, then 'break' statements within this frame\n        will jump out to the frame break_frame levels higher than the\n        frame created by this call to frame_context. Similarly, for\n        continue_frame and 'continue' statements.\n\n        If try_frame is true, then execution is allowed to jump at any\n        point within the newly created frame (or its descendants) to\n        its parent (i.e., to the frame that was on top before this\n        call to frame_context).\n\n        If discard is True, then this is a temporary throw-away frame\n        (used e.g. for isolation) and its effect will be discarded on pop.\n\n        After the context manager exits, self.last_pop_changed indicates\n        whether any types changed in the newly-topmost frame as a result\n        of popping this frame.\n        \"\"\"\n        return FrameContext(\n            self,\n            can_skip=can_skip,\n            fall_through=fall_through,\n            break_frame=break_frame,\n            continue_frame=continue_frame,\n            conditional_frame=conditional_frame,\n            try_frame=try_frame,\n            discard=discard,\n        )\n\n    @contextmanager\n    def top_frame_context(self) -> Iterator[Frame]:\n        \"\"\"A variant of frame_context for use at the top level of\n        a namespace (module, function, or class).\n        \"\"\"\n        assert len(self.frames) == 1\n        yield self.push_frame()\n        self.pop_frame(True, 0)\n        assert len(self.frames) == 1\n\n\ndef get_declaration(expr: BindableExpression) -> Type | None:\n    \"\"\"Get the declared or inferred type of a RefExpr expression.\n\n    Return None if there is no type or the expression is not a RefExpr.\n    This can return None if the type hasn't been inferred yet.\n    \"\"\"\n    if isinstance(expr, RefExpr):\n        if isinstance(expr.node, Var):\n            type = expr.node.type\n            if not isinstance(get_proper_type(type), PartialType):\n                return type\n        elif isinstance(expr.node, TypeInfo):\n            return TypeType(fill_typevars_with_any(expr.node))\n    return None\n\n\ndef collapse_variadic_union(typ: UnionType) -> Type:\n    \"\"\"Simplify a union involving variadic tuple if possible.\n\n    This will collapse a type like e.g.\n        tuple[X, Z] | tuple[X, Y, Z] | tuple[X, Y, Y, *tuple[Y, ...], Z]\n    back to\n        tuple[X, *tuple[Y, ...], Z]\n    which is equivalent, but much simpler form of the same type.\n    \"\"\"\n    tuple_items = []\n    other_items = []\n    for t in typ.items:\n        p_t = get_proper_type(t)\n        if isinstance(p_t, TupleType):\n            tuple_items.append(p_t)\n        else:\n            other_items.append(t)\n    if len(tuple_items) <= 1:\n        # This type cannot be simplified further.\n        return typ\n    tuple_items = sorted(tuple_items, key=lambda t: len(t.items))\n    first = tuple_items[0]\n    last = tuple_items[-1]\n    unpack_index = find_unpack_in_list(last.items)\n    if unpack_index is None:\n        return typ\n    unpack = last.items[unpack_index]\n    assert isinstance(unpack, UnpackType)\n    unpacked = get_proper_type(unpack.type)\n    if not isinstance(unpacked, Instance):\n        return typ\n    assert unpacked.type.fullname == \"builtins.tuple\"\n    suffix = last.items[unpack_index + 1 :]\n\n    # Check that first item matches the expected pattern and infer prefix.\n    if len(first.items) < len(suffix):\n        return typ\n    if suffix and first.items[-len(suffix) :] != suffix:\n        return typ\n    if suffix:\n        prefix = first.items[: -len(suffix)]\n    else:\n        prefix = first.items\n\n    # Check that all middle types match the expected pattern as well.\n    arg = unpacked.args[0]\n    for i, it in enumerate(tuple_items[1:-1]):\n        if it.items != prefix + [arg] * (i + 1) + suffix:\n            return typ\n\n    # Check the last item (the one with unpack), and choose an appropriate simplified type.\n    if last.items != prefix + [arg] * (len(typ.items) - 1) + [unpack] + suffix:\n        return typ\n    if len(first.items) == 0:\n        simplified: Type = unpacked.copy_modified()\n    else:\n        simplified = TupleType(prefix + [unpack] + suffix, fallback=last.partial_fallback)\n    return UnionType.make_union([simplified] + other_items)\n"
  },
  {
    "path": "mypy/bogus_type.py",
    "content": "\"\"\"A Bogus[T] type alias for marking when we subvert the type system\n\nWe need this for compiling with mypyc, which inserts runtime\ntypechecks that cause problems when we subvert the type system. So\nwhen compiling with mypyc, we turn those places into Any, while\nkeeping the types around for normal typechecks.\n\nSince this causes the runtime types to be Any, this is best used\nin places where efficient access to properties is not important.\nFor those cases some other technique should be used.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Any, TypeVar\n\nfrom mypy_extensions import FlexibleAlias\n\nT = TypeVar(\"T\")\n\n# This won't ever be true at runtime, but we consider it true during\n# mypyc compilations.\nMYPYC = False\nif MYPYC:\n    Bogus = FlexibleAlias[T, Any]\nelse:\n    Bogus = FlexibleAlias[T, T]\n"
  },
  {
    "path": "mypy/build.py",
    "content": "\"\"\"Facilities to analyze entire programs, including imported modules.\n\nParse and analyze the source files of a program in the correct order\n(based on file dependencies), and collect the results.\n\nThis module only directs a build, which is performed in multiple passes per\nfile.  The individual passes are implemented in separate modules.\n\nThe function build() is the main interface to this module.\n\"\"\"\n\n# TODO: More consistent terminology, e.g. path/fnam, module/id, state/file\n\nfrom __future__ import annotations\n\nimport collections\nimport contextlib\nimport gc\nimport json\nimport os\nimport pickle\nimport platform\nimport re\nimport stat\nimport subprocess\nimport sys\nimport time\nimport types\nfrom collections.abc import Callable, Iterator, Mapping, Sequence, Set as AbstractSet\nfrom heapq import heappop, heappush\nfrom textwrap import dedent\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    ClassVar,\n    Final,\n    NoReturn,\n    TextIO,\n    TypeAlias as _TypeAlias,\n    TypedDict,\n    cast,\n    final,\n)\n\nfrom librt.base64 import b64encode\nfrom librt.internal import (\n    cache_version,\n    read_bool,\n    read_int as read_int_bare,\n    read_str as read_str_bare,\n    read_tag,\n    write_bool,\n    write_bytes as write_bytes_bare,\n    write_int as write_int_bare,\n    write_str as write_str_bare,\n    write_tag,\n)\n\nimport mypy.semanal_main\nfrom mypy.cache import (\n    CACHE_VERSION,\n    DICT_STR_GEN,\n    LIST_GEN,\n    LITERAL_NONE,\n    CacheMeta,\n    ErrorTuple,\n    JsonValue,\n    ReadBuffer,\n    Tag,\n    WriteBuffer,\n    read_bytes,\n    read_errors,\n    read_int,\n    read_int_list,\n    read_int_opt,\n    read_str,\n    read_str_list,\n    read_str_opt,\n    write_bytes,\n    write_errors,\n    write_int,\n    write_int_list,\n    write_int_opt,\n    write_json_value,\n    write_str,\n    write_str_list,\n    write_str_opt,\n)\nfrom mypy.checker import TypeChecker\nfrom mypy.defaults import (\n    WORKER_CONNECTION_TIMEOUT,\n    WORKER_DONE_TIMEOUT,\n    WORKER_START_INTERVAL,\n    WORKER_START_TIMEOUT,\n)\nfrom mypy.error_formatter import OUTPUT_CHOICES, ErrorFormatter\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.errors import CompileError, ErrorInfo, Errors, report_internal_error\nfrom mypy.graph_utils import prepare_sccs, strongly_connected_components, topsort\nfrom mypy.indirection import TypeIndirectionVisitor\nfrom mypy.ipc import (\n    BadStatus,\n    IPCClient,\n    IPCException,\n    IPCMessage,\n    read_status,\n    ready_to_read,\n    receive,\n    send,\n)\nfrom mypy.messages import MessageBuilder\nfrom mypy.nodes import (\n    FileRawData,\n    Import,\n    ImportAll,\n    ImportBase,\n    ImportFrom,\n    MypyFile,\n    SymbolTable,\n)\nfrom mypy.options import OPTIONS_AFFECTING_CACHE_NO_PLATFORM\nfrom mypy.partially_defined import PossiblyUndefinedVariableVisitor\nfrom mypy.semanal import SemanticAnalyzer\nfrom mypy.semanal_pass1 import SemanticAnalyzerPreAnalysis\nfrom mypy.util import (\n    DecodeError,\n    decode_python_encoding,\n    get_mypy_comments,\n    hash_digest,\n    hash_digest_bytes,\n    is_stub_package_file,\n    is_sub_path_normabs,\n    is_typeshed_file,\n    module_prefix,\n    os_path_join,\n    read_py_file,\n    time_ref,\n    time_spent_us,\n)\n\nif TYPE_CHECKING:\n    from mypy.report import Reports  # Avoid unconditional slow import\n\nfrom mypy import errorcodes as codes\nfrom mypy.config_parser import get_config_module_names, parse_mypy_comments\nfrom mypy.fixup import fixup_module\nfrom mypy.freetree import free_tree\nfrom mypy.fscache import FileSystemCache\nfrom mypy.metastore import FilesystemMetadataStore, MetadataStore, SqliteMetadataStore\nfrom mypy.modulefinder import (\n    BuildSource as BuildSource,\n    BuildSourceSet as BuildSourceSet,\n    FindModuleCache,\n    ModuleNotFoundReason,\n    ModuleSearchResult,\n    SearchPaths,\n    compute_search_paths,\n)\nfrom mypy.nodes import Expression\nfrom mypy.options import Options\nfrom mypy.parse import load_from_raw, parse\nfrom mypy.plugin import ChainedPlugin, Plugin, ReportConfigContext\nfrom mypy.plugins.default import DefaultPlugin\nfrom mypy.renaming import LimitedVariableRenameVisitor, VariableRenameVisitor\nfrom mypy.stats import dump_type_stats\nfrom mypy.stubinfo import is_module_from_legacy_bundled_package, stub_distribution_name\nfrom mypy.types import Type, instance_cache\nfrom mypy.typestate import reset_global_state, type_state\nfrom mypy.util import json_dumps, json_loads\nfrom mypy.version import __version__\n\n# Switch to True to produce debug output related to fine-grained incremental\n# mode only that is useful during development. This produces only a subset of\n# output compared to --verbose output. We use a global flag to enable this so\n# that it's easy to enable this when running tests.\nDEBUG_FINE_GRAINED: Final = False\n\n# These modules are special and should always come from typeshed.\nCORE_BUILTIN_MODULES: Final = {\n    \"builtins\",\n    \"typing\",\n    \"types\",\n    \"typing_extensions\",\n    \"mypy_extensions\",\n    \"_typeshed\",\n    \"_collections_abc\",\n    \"collections\",\n    \"collections.abc\",\n    \"sys\",\n    \"abc\",\n}\n\n# We are careful now, we can increase this in future if safe/useful.\nMAX_GC_FREEZE_CYCLES: Final = 1\n\n# We store status of initial GC freeze as a global variable to avoid memory\n# leaks in tests, where we keep creating new BuildManagers in the same process.\ninitial_gc_freeze_done = False\n\nGraph: _TypeAlias = dict[str, \"State\"]\n\nMODULE_RESOLUTION_URL: Final = (\n    \"https://mypy.readthedocs.io/en/stable/running_mypy.html#mapping-file-paths-to-modules\"\n)\n\n\nclass SCC:\n    \"\"\"A simple class that represents a strongly connected component (import cycle).\"\"\"\n\n    id_counter: ClassVar[int] = 0\n\n    def __init__(\n        self, ids: set[str], scc_id: int | None = None, deps: list[int] | None = None\n    ) -> None:\n        if scc_id is None:\n            self.id = SCC.id_counter\n            SCC.id_counter += 1\n        else:\n            self.id = scc_id\n        # Ids of modules in this cycle.\n        self.mod_ids = ids\n        # Direct dependencies, should be populated by the caller.\n        self.deps: set[int] = set(deps) if deps is not None else set()\n        # Direct dependencies that have not been processed yet.\n        # Should be populated by the caller. This set may change during graph\n        # processing, while the above stays constant.\n        self.not_ready_deps: set[int] = set()\n        # SCCs that (directly) depend on this SCC. Note this is a list to\n        # make processing order more predictable. Dependents will be notified\n        # that they may be ready in the order in this list.\n        self.direct_dependents: list[int] = []\n        # Rough estimate of how much time processing this SCC will take, this\n        # is used for more efficient scheduling across multiple build workers.\n        self.size_hint: int = 0\n\n\n# TODO: Get rid of BuildResult.  We might as well return a BuildManager.\nclass BuildResult:\n    \"\"\"The result of a successful build.\n\n    Attributes:\n      manager: The build manager.\n      files:   Dictionary from module name to related AST node.\n      types:   Dictionary from parse tree node to its inferred type.\n      used_cache: Whether the build took advantage of a pre-existing cache\n      errors:  List of error messages.\n    \"\"\"\n\n    def __init__(self, manager: BuildManager, graph: Graph) -> None:\n        self.manager = manager\n        self.graph = graph\n        self.files = manager.modules\n        self.types = manager.all_types  # Non-empty if export_types True in options\n        self.used_cache = manager.cache_enabled\n        self.errors: list[str] = []  # Filled in by build if desired\n\n\nclass WorkerClient:\n    \"\"\"A simple class that represents a mypy build worker.\"\"\"\n\n    conn: IPCClient\n\n    def __init__(self, status_file: str, options_data: str, env: Mapping[str, str]) -> None:\n        self.status_file = status_file\n        if os.path.isfile(status_file):\n            os.unlink(status_file)\n\n        command = [\n            sys.executable,\n            \"-m\",\n            \"mypy.build_worker\",\n            f\"--status-file={status_file}\",\n            f'--options-data=\"{options_data}\"',\n        ]\n        # Return early without waiting, caller must call connect() before using the client.\n        self.proc = subprocess.Popen(command, env=env)\n\n    def connect(self) -> None:\n        end_time = time.time() + WORKER_START_TIMEOUT\n        last_exception: Exception | None = None\n        while time.time() < end_time:\n            try:\n                data = read_status(self.status_file)\n            except BadStatus as exc:\n                last_exception = exc\n                time.sleep(WORKER_START_INTERVAL)\n                continue\n            try:\n                pid, connection_name = data[\"pid\"], data[\"connection_name\"]\n                assert isinstance(pid, int), f\"Bad PID: {pid}\"\n                assert isinstance(connection_name, str), f\"Bad connection name: {connection_name}\"\n                if sys.platform != \"win32\":\n                    # Windows uses \"wrapper processes\" to run Python, so we cannot\n                    # verify PIDs reliably.\n                    assert pid == self.proc.pid, f\"PID mismatch: {pid} vs {self.proc.pid}\"\n                self.conn = IPCClient(connection_name, WORKER_CONNECTION_TIMEOUT)\n                return\n            except Exception as exc:\n                last_exception = exc\n                break\n        print(\"Failed to establish connection with worker:\", last_exception)\n        sys.exit(2)\n\n    def close(self) -> None:\n        self.conn.close()\n        # Technically we don't need to wait, but otherwise we will get ResourceWarnings.\n        try:\n            self.proc.wait(timeout=1)\n        except subprocess.TimeoutExpired:\n            pass\n        if os.path.isfile(self.status_file):\n            os.unlink(self.status_file)\n\n\ndef build_error(msg: str) -> NoReturn:\n    raise CompileError([f\"mypy: error: {msg}\"])\n\n\ndef build(\n    sources: list[BuildSource],\n    options: Options,\n    alt_lib_path: str | None = None,\n    flush_errors: Callable[[str | None, list[str], bool], None] | None = None,\n    fscache: FileSystemCache | None = None,\n    stdout: TextIO | None = None,\n    stderr: TextIO | None = None,\n    extra_plugins: Sequence[Plugin] | None = None,\n    worker_env: Mapping[str, str] | None = None,\n) -> BuildResult:\n    \"\"\"Analyze a program.\n\n    A single call to build performs parsing, semantic analysis and optionally\n    type checking for the program *and* all imported modules, recursively.\n\n    Return BuildResult if successful or only non-blocking errors were found;\n    otherwise raise CompileError.\n\n    If a flush_errors callback is provided, all error messages will be\n    passed to it and the errors and messages fields of BuildResult and\n    CompileError (respectively) will be empty. Otherwise those fields will\n    report any error messages.\n\n    Args:\n      sources: list of sources to build\n      options: build options\n      alt_lib_path: an additional directory for looking up library modules\n        (takes precedence over other directories)\n      flush_errors: optional function to flush errors after a file is processed\n      fscache: optionally a file-system cacher\n      worker_env: An environment to start parallel build workers (used for tests)\n    \"\"\"\n    # If we were not given a flush_errors, we use one that will populate those\n    # fields for callers that want the traditional API.\n    messages = []\n\n    # This is mostly for the benefit of tests that use builtins fixtures.\n    instance_cache.reset()\n\n    def default_flush_errors(\n        filename: str | None, new_messages: list[str], is_serious: bool\n    ) -> None:\n        messages.extend(new_messages)\n\n    flush_errors = flush_errors or default_flush_errors\n    stdout = stdout or sys.stdout\n    stderr = stderr or sys.stderr\n    extra_plugins = extra_plugins or []\n\n    workers = []\n    if options.num_workers > 0:\n        # TODO: switch to something more efficient than pickle (also in the daemon).\n        pickled_options = pickle.dumps(options.snapshot())\n        options_data = b64encode(pickled_options).decode()\n        workers = [\n            WorkerClient(f\".mypy_worker.{idx}.json\", options_data, worker_env or os.environ)\n            for idx in range(options.num_workers)\n        ]\n        sources_message = SourcesDataMessage(sources=sources)\n        buf = WriteBuffer()\n        sources_message.write(buf)\n        sources_data = buf.getvalue()\n        for worker in workers:\n            # Start loading graph in each worker as soon as it is up.\n            worker.connect()\n            worker.conn.write_bytes(sources_data)\n\n    try:\n        result = build_inner(\n            sources,\n            options,\n            alt_lib_path,\n            flush_errors,\n            fscache,\n            stdout,\n            stderr,\n            extra_plugins,\n            workers,\n        )\n        result.errors = messages\n        return result\n    except CompileError as e:\n        # CompileErrors raised from an errors object carry all the\n        # messages that have not been reported out by error streaming.\n        # Patch it up to contain either none or all none of the messages,\n        # depending on whether we are flushing errors.\n        serious = not e.use_stdout\n        flush_errors(None, e.messages, serious)\n        e.messages = messages\n        raise\n    finally:\n        for worker in workers:\n            try:\n                send(worker.conn, SccRequestMessage(scc_id=None, import_errors={}, mod_data={}))\n            except (OSError, IPCException):\n                pass\n        for worker in workers:\n            worker.close()\n\n\ndef build_inner(\n    sources: list[BuildSource],\n    options: Options,\n    alt_lib_path: str | None,\n    flush_errors: Callable[[str | None, list[str], bool], None],\n    fscache: FileSystemCache | None,\n    stdout: TextIO,\n    stderr: TextIO,\n    extra_plugins: Sequence[Plugin],\n    workers: list[WorkerClient],\n) -> BuildResult:\n    if platform.python_implementation() == \"CPython\":\n        # Run gc less frequently, as otherwise we can spend a large fraction of\n        # cpu in gc. This seems the most reasonable place to tune garbage collection.\n        gc.set_threshold(200 * 1000, 30, 30)\n\n    data_dir = default_data_dir()\n    fscache = fscache or FileSystemCache()\n\n    search_paths = compute_search_paths(sources, options, data_dir, alt_lib_path)\n\n    reports = None\n    if options.report_dirs:\n        # Import lazily to avoid slowing down startup.\n        from mypy.report import Reports\n\n        reports = Reports(data_dir, options.report_dirs)\n\n    source_set = BuildSourceSet(sources)\n    cached_read = fscache.read\n    errors = Errors(options, read_source=lambda path: read_py_file(path, cached_read))\n    # Record import errors so that they can be replayed by the workers.\n    if workers:\n        errors.global_watcher = True\n    plugin, snapshot = load_plugins(options, errors, stdout, extra_plugins)\n\n    # Validate error codes after plugins are loaded.\n    options.process_error_codes(error_callback=build_error)\n\n    # Construct a build manager object to hold state during the build.\n    #\n    # Ignore current directory prefix in error messages.\n    manager = BuildManager(\n        data_dir,\n        search_paths,\n        ignore_prefix=os.getcwd(),\n        source_set=source_set,\n        reports=reports,\n        options=options,\n        version_id=__version__,\n        plugin=plugin,\n        plugins_snapshot=snapshot,\n        errors=errors,\n        error_formatter=None if options.output is None else OUTPUT_CHOICES.get(options.output),\n        flush_errors=flush_errors,\n        fscache=fscache,\n        stdout=stdout,\n        stderr=stderr,\n    )\n    manager.workers = workers\n    if manager.verbosity() >= 2:\n        manager.trace(repr(options))\n\n    reset_global_state()\n    try:\n        graph = dispatch(sources, manager, stdout)\n        if not options.fine_grained_incremental:\n            type_state.reset_all_subtype_caches()\n        if options.timing_stats is not None:\n            dump_timing_stats(options.timing_stats, graph)\n        if options.line_checking_stats is not None:\n            dump_line_checking_stats(options.line_checking_stats, graph)\n        warn_unused_configs(options, flush_errors)\n        return BuildResult(manager, graph)\n    finally:\n        t0 = time.time()\n        manager.metastore.commit()\n        manager.add_stats(cache_commit_time=time.time() - t0)\n        manager.log(\n            \"Build finished in %.3f seconds with %d modules, and %d errors\"\n            % (\n                time.time() - manager.start_time,\n                len(manager.modules),\n                manager.errors.num_messages(),\n            )\n        )\n        manager.dump_stats()\n        if reports is not None:\n            # Finish the HTML or XML reports even if CompileError was raised.\n            reports.finish()\n        if os.path.isdir(options.cache_dir):\n            add_catch_all_gitignore(options.cache_dir)\n            exclude_from_backups(options.cache_dir)\n        if os.path.isdir(options.cache_dir):\n            record_missing_stub_packages(options.cache_dir, manager.missing_stub_packages)\n\n\ndef warn_unused_configs(\n    options: Options, flush_errors: Callable[[str | None, list[str], bool], None]\n) -> None:\n    if options.warn_unused_configs and options.unused_configs and not options.non_interactive:\n        unused = get_config_module_names(\n            options.config_file,\n            [glob for glob in options.per_module_options.keys() if glob in options.unused_configs],\n        )\n        flush_errors(\n            None, [\"{}: note: unused section(s): {}\".format(options.config_file, unused)], False\n        )\n\n\ndef default_data_dir() -> str:\n    \"\"\"Returns directory containing typeshed directory.\"\"\"\n    return os.path.dirname(__file__)\n\n\ndef normpath(path: str, options: Options) -> str:\n    \"\"\"Convert path to absolute; but to relative in bazel mode.\n\n    (Bazel's distributed cache doesn't like filesystem metadata to\n    end up in output files.)\n    \"\"\"\n    # TODO: Could we always use relpath?  (A worry in non-bazel\n    # mode would be that a moved file may change its full module\n    # name without changing its size, mtime or hash.)\n    if options.bazel:\n        return os.path.relpath(path)\n    else:\n        return os.path.abspath(path)\n\n\n# NOTE: dependencies + suppressed == all reachable imports;\n# suppressed contains those reachable imports that were prevented by\n# silent mode or simply not found.\n\n\n# Metadata for the fine-grained dependencies file associated with a module.\nclass FgDepMeta(TypedDict):\n    path: str\n    mtime: int\n\n\n# Priorities used for imports.  (Here, top-level includes inside a class.)\n# These are used to determine a more predictable order in which the\n# nodes in an import cycle are processed.\nPRI_HIGH: Final = 5  # top-level \"from X import blah\"\nPRI_MED: Final = 10  # top-level \"import X\"\nPRI_LOW: Final = 20  # either form inside a function\nPRI_MYPY: Final = 25  # inside \"if MYPY\" or \"if TYPE_CHECKING\"\nPRI_INDIRECT: Final = 30  # an indirect dependency\nPRI_ALL: Final = 99  # include all priorities\n\n\ndef import_priority(imp: ImportBase, toplevel_priority: int) -> int:\n    \"\"\"Compute import priority from an import node.\"\"\"\n    if not imp.is_top_level:\n        # Inside a function\n        return PRI_LOW\n    if imp.is_mypy_only:\n        # Inside \"if MYPY\" or \"if typing.TYPE_CHECKING\"\n        return max(PRI_MYPY, toplevel_priority)\n    # A regular import; priority determined by argument.\n    return toplevel_priority\n\n\ndef load_plugins_from_config(\n    options: Options, errors: Errors, stdout: TextIO\n) -> tuple[list[Plugin], dict[str, str]]:\n    \"\"\"Load all configured plugins.\n\n    Return a list of all the loaded plugins from the config file.\n    The second return value is a snapshot of versions/hashes of loaded user\n    plugins (for cache validation).\n    \"\"\"\n    import importlib\n\n    snapshot: dict[str, str] = {}\n\n    if not options.config_file:\n        return [], snapshot\n\n    line = find_config_file_line_number(options.config_file, \"mypy\", \"plugins\")\n    if line == -1:\n        line = 1  # We need to pick some line number that doesn't look too confusing\n\n    def plugin_error(message: str) -> NoReturn:\n        errors.report(line, 0, message)\n        errors.raise_error(use_stdout=False)\n\n    custom_plugins: list[Plugin] = []\n    errors.set_file(options.config_file, None, options)\n    for plugin_path in options.plugins:\n        func_name = \"plugin\"\n        plugin_dir: str | None = None\n        if \":\" in os.path.basename(plugin_path):\n            plugin_path, func_name = plugin_path.rsplit(\":\", 1)\n        if plugin_path.endswith(\".py\"):\n            # Plugin paths can be relative to the config file location.\n            plugin_path = os_path_join(os.path.dirname(options.config_file), plugin_path)\n            if not os.path.isfile(plugin_path):\n                plugin_error(f'Can\\'t find plugin \"{plugin_path}\"')\n            # Use an absolute path to avoid populating the cache entry\n            # for 'tmp' during tests, since it will be different in\n            # different tests.\n            plugin_dir = os.path.abspath(os.path.dirname(plugin_path))\n            fnam = os.path.basename(plugin_path)\n            module_name = fnam[:-3]\n            sys.path.insert(0, plugin_dir)\n        elif re.search(r\"[\\\\/]\", plugin_path):\n            fnam = os.path.basename(plugin_path)\n            plugin_error(f'Plugin \"{fnam}\" does not have a .py extension')\n        else:\n            module_name = plugin_path\n\n        try:\n            module = importlib.import_module(module_name)\n        except Exception as exc:\n            plugin_error(f'Error importing plugin \"{plugin_path}\": {exc}')\n        finally:\n            if plugin_dir is not None:\n                assert sys.path[0] == plugin_dir\n                del sys.path[0]\n\n        if not hasattr(module, func_name):\n            plugin_error(\n                'Plugin \"{}\" does not define entry point function \"{}\"'.format(\n                    plugin_path, func_name\n                )\n            )\n\n        try:\n            plugin_type = getattr(module, func_name)(__version__)\n        except Exception:\n            print(f\"Error calling the plugin(version) entry point of {plugin_path}\\n\", file=stdout)\n            raise  # Propagate to display traceback\n\n        if not isinstance(plugin_type, type):\n            plugin_error(\n                'Type object expected as the return value of \"plugin\"; got {!r} (in {})'.format(\n                    plugin_type, plugin_path\n                )\n            )\n        if not issubclass(plugin_type, Plugin):\n            plugin_error(\n                'Return value of \"plugin\" must be a subclass of \"mypy.plugin.Plugin\" '\n                \"(in {})\".format(plugin_path)\n            )\n        try:\n            custom_plugins.append(plugin_type(options))\n            snapshot[module_name] = take_module_snapshot(module)\n        except Exception:\n            print(f\"Error constructing plugin instance of {plugin_type.__name__}\\n\", file=stdout)\n            raise  # Propagate to display traceback\n\n    return custom_plugins, snapshot\n\n\ndef load_plugins(\n    options: Options, errors: Errors, stdout: TextIO, extra_plugins: Sequence[Plugin]\n) -> tuple[Plugin, dict[str, str]]:\n    \"\"\"Load all configured plugins.\n\n    Return a plugin that encapsulates all plugins chained together. Always\n    at least include the default plugin (it's last in the chain).\n    The second return value is a snapshot of versions/hashes of loaded user\n    plugins (for cache validation).\n    \"\"\"\n    custom_plugins, snapshot = load_plugins_from_config(options, errors, stdout)\n\n    custom_plugins += extra_plugins\n\n    default_plugin: Plugin = DefaultPlugin(options)\n    if not custom_plugins:\n        return default_plugin, snapshot\n\n    # Custom plugins take precedence over the default plugin.\n    return ChainedPlugin(options, custom_plugins + [default_plugin]), snapshot\n\n\ndef take_module_snapshot(module: types.ModuleType) -> str:\n    \"\"\"Take plugin module snapshot by recording its version and hash.\n\n    We record _both_ hash and the version to detect more possible changes\n    (e.g. if there is a change in modules imported by a plugin).\n    \"\"\"\n    if hasattr(module, \"__file__\"):\n        assert module.__file__ is not None\n        with open(module.__file__, \"rb\") as f:\n            digest = hash_digest(f.read())\n    else:\n        digest = \"unknown\"\n    ver = getattr(module, \"__version__\", \"none\")\n    return f\"{ver}:{digest}\"\n\n\ndef find_config_file_line_number(path: str, section: str, setting_name: str) -> int:\n    \"\"\"Return the approximate location of setting_name within mypy config file.\n\n    Return -1 if can't determine the line unambiguously.\n    \"\"\"\n    in_desired_section = False\n    try:\n        results = []\n        with open(path, encoding=\"UTF-8\") as f:\n            for i, line in enumerate(f):\n                line = line.strip()\n                if line.startswith(\"[\") and line.endswith(\"]\"):\n                    current_section = line[1:-1].strip()\n                    in_desired_section = current_section == section\n                elif in_desired_section and re.match(rf\"{setting_name}\\s*=\", line):\n                    results.append(i + 1)\n        if len(results) == 1:\n            return results[0]\n    except OSError:\n        pass\n    return -1\n\n\nclass BuildManager:\n    \"\"\"This class holds shared state for building a mypy program.\n\n    It is used to coordinate parsing, import processing, semantic\n    analysis and type checking.  The actual build steps are carried\n    out by dispatch().\n\n    Attributes:\n      data_dir:        Mypy data directory (contains stubs)\n      search_paths:    SearchPaths instance indicating where to look for modules\n      modules:         Mapping of module ID to MypyFile (shared by the passes)\n      semantic_analyzer:\n                       Semantic analyzer, pass 2\n      all_types:       Map {Expression: Type} from all modules (enabled by export_types)\n      options:         Build options\n      missing_modules: Modules that could not be imported (or intentionally skipped)\n      stale_modules:   Set of modules that needed to be rechecked (only used by tests)\n      fg_deps_meta:    Metadata for fine-grained dependencies caches associated with modules\n      fg_deps:         A fine-grained dependency map\n      version_id:      The current mypy version (based on commit id when possible)\n      plugin:          Active mypy plugin(s)\n      plugins_snapshot:\n                       Snapshot of currently active user plugins (versions and hashes)\n      old_plugins_snapshot:\n                       Plugins snapshot from previous incremental run (or None in\n                       non-incremental mode and if cache was not found)\n      errors:          Used for reporting all errors\n      flush_errors:    A function for processing errors after each SCC\n      cache_enabled:   Whether cache is being read. This is set based on options,\n                       but is disabled if fine-grained cache loading fails\n                       and after an initial fine-grained load. This doesn't\n                       determine whether we write cache files or not.\n      quickstart_state:\n                       A cache of filename -> mtime/size/hash info used to avoid\n                       needing to hash source files when using a cache with mismatching mtimes\n      stats:           Dict with various instrumentation numbers, it is used\n                       not only for debugging, but also required for correctness,\n                       in particular to check consistency of the fine-grained dependency cache.\n      fscache:         A file system cacher\n      ast_cache:       AST cache to speed up mypy daemon\n    \"\"\"\n\n    def __init__(\n        self,\n        data_dir: str,\n        search_paths: SearchPaths,\n        ignore_prefix: str,\n        source_set: BuildSourceSet,\n        reports: Reports | None,\n        options: Options,\n        version_id: str,\n        plugin: Plugin,\n        plugins_snapshot: dict[str, str],\n        errors: Errors,\n        flush_errors: Callable[[str | None, list[str], bool], None],\n        fscache: FileSystemCache,\n        stdout: TextIO,\n        stderr: TextIO,\n        error_formatter: ErrorFormatter | None = None,\n        parallel_worker: bool = False,\n    ) -> None:\n        self.stats: dict[str, Any] = {}  # Values are ints or floats\n        self.stdout = stdout\n        self.stderr = stderr\n        self.start_time = time.time()\n        self.data_dir = data_dir\n        self.errors = errors\n        self.errors.set_ignore_prefix(ignore_prefix)\n        self.error_formatter = error_formatter\n        self.search_paths = search_paths\n        self.source_set = source_set\n        self.reports = reports\n        self.options = options\n        self.version_id = version_id\n        self.modules: dict[str, MypyFile] = {}\n        self.import_map: dict[str, set[str]] = {}\n        self.missing_modules: dict[str, int] = {}\n        self.fg_deps_meta: dict[str, FgDepMeta] = {}\n        # fg_deps holds the dependencies of every module that has been\n        # processed. We store this in BuildManager so that we can compute\n        # dependencies as we go, which allows us to free ASTs and type information,\n        # saving a ton of memory on net.\n        self.fg_deps: dict[str, set[str]] = {}\n        # Always convert the plugin to a ChainedPlugin so that it can be manipulated if needed\n        if not isinstance(plugin, ChainedPlugin):\n            plugin = ChainedPlugin(options, [plugin])\n        self.plugin = plugin\n        # These allow quickly skipping logging and stats collection calls. Note\n        # that some stats impact mypy behavior, so be careful when skipping stats\n        # collection calls.\n        self.stats_enabled = self.options.dump_build_stats\n        self.logging_enabled = self.options.verbosity >= 1\n        self.tracing_enabled = self.options.verbosity >= 2\n        # Set of namespaces (module or class) that are being populated during semantic\n        # analysis and may have missing definitions.\n        self.incomplete_namespaces: set[str] = set()\n        self.semantic_analyzer = SemanticAnalyzer(\n            self.modules,\n            self.missing_modules,\n            self.incomplete_namespaces,\n            self.errors,\n            self.plugin,\n            self.import_map,\n        )\n        self.all_types: dict[Expression, Type] = {}  # Enabled by export_types\n        self.indirection_detector = TypeIndirectionVisitor()\n        self.stale_modules: set[str] = set()\n        self.rechecked_modules: set[str] = set()\n        self.flush_errors = flush_errors\n        has_reporters = reports is not None and reports.reporters\n        self.cache_enabled = (\n            options.incremental\n            and (not options.fine_grained_incremental or options.use_fine_grained_cache)\n            and not has_reporters\n        )\n        self.fscache = fscache\n        self.cwd = os.getcwd()\n        self.find_module_cache = FindModuleCache(\n            self.search_paths, self.fscache, self.options, source_set=self.source_set\n        )\n        for module in CORE_BUILTIN_MODULES:\n            if options.use_builtins_fixtures:\n                continue\n            path = self.find_module_cache.find_module(module, fast_path=True)\n            if not isinstance(path, str):\n                raise CompileError(\n                    [f\"Failed to find builtin module {module}, perhaps typeshed is broken?\"]\n                )\n            if is_typeshed_file(options.abs_custom_typeshed_dir, path) or is_stub_package_file(\n                path\n            ):\n                continue\n\n            raise CompileError(\n                [\n                    f'mypy: \"{os.path.relpath(path)}\" shadows library module \"{module}\"',\n                    f'note: A user-defined top-level module with name \"{module}\" is not supported',\n                ]\n            )\n\n        self.metastore = create_metastore(options, parallel_worker)\n\n        # a mapping from source files to their corresponding shadow files\n        # for efficient lookup\n        self.shadow_map: dict[str, str] = {}\n        if self.options.shadow_file is not None:\n            self.shadow_map = dict(self.options.shadow_file)\n        # a mapping from each file being typechecked to its possible shadow file\n        self.shadow_equivalence_map: dict[str, str | None] = {}\n        self.plugin = plugin\n        self.plugins_snapshot = plugins_snapshot\n        self.old_plugins_snapshot = read_plugins_snapshot(self)\n        if self.verbosity() >= 2:\n            self.trace(f\"Plugins snapshot (fresh) {json.dumps(self.plugins_snapshot)}\")\n        self.quickstart_state = read_quickstart_file(options, self.stdout)\n        # Fine grained targets (module top levels and top level functions) processed by\n        # the semantic analyzer, used only for testing. Currently used only by the new\n        # semantic analyzer. Tuple of module and target name.\n        self.processed_targets: list[tuple[str, str]] = []\n        # Missing stub packages encountered.\n        self.missing_stub_packages: set[str] = set()\n        # Cache for mypy ASTs that have completed semantic analysis\n        # pass 1. When multiple files are added to the build in a\n        # single daemon increment, only one of the files gets added\n        # per step and the others are discarded. This gets repeated\n        # until all the files have been added. This means that a\n        # new file can be processed O(n**2) times. This cache\n        # avoids most of this redundant work.\n        self.ast_cache: dict[str, tuple[MypyFile, list[ErrorInfo]]] = {}\n        # Number of times we used GC optimization hack for fresh SCCs.\n        self.gc_freeze_cycles = 0\n        # Mapping from SCC id to corresponding SCC instance. This is populated\n        # in process_graph().\n        self.scc_by_id: dict[int, SCC] = {}\n        # Mapping from module id to the SCC it belongs to. This is populated\n        # in process_graph().\n        self.scc_by_mod_id: dict[str, SCC] = {}\n        # Global topological order for SCCs. This exists to make order of processing\n        # SCCs more predictable.\n        self.top_order: list[int] = []\n        # Stale SCCs that are queued for processing. Each tuple contains SCC size hint,\n        # SCC adding order (tie-breaker), and the SCC itself.\n        self.scc_queue: list[tuple[int, int, SCC]] = []\n        # SCCs that have been fully processed.\n        self.done_sccs: set[int] = set()\n        # Parallel build workers, list is empty for in-process type-checking.\n        self.workers: list[WorkerClient] = []\n        # We track which workers are currently free in the coordinator process.\n        # This is a tiny bit faster and conceptually simpler than check which ones\n        # are writeable each time we want to submit an SCC for processing.\n        self.free_workers: set[int] = set()\n        # A global adding order for SCC queue, see comment above.\n        self.queue_order: int = 0\n        # Is this an instance used by a parallel worker?\n        self.parallel_worker = parallel_worker\n        # Snapshot of import-related options per module. We record these even for\n        # suppressed imports, since they can affect errors in the callers. Bytes\n        # value is opaque but can be compared to detect changes in options.\n        self.import_options: dict[str, bytes] = {}\n        # Cache for transitive dependency check (expensive).\n        self.transitive_deps_cache: dict[tuple[int, int], bool] = {}\n        # Packages for which we know presence or absence of __getattr__().\n        self.known_partial_packages: dict[str, bool] = {}\n\n    def dump_stats(self) -> None:\n        if self.stats_enabled:\n            print(\"Stats:\")\n            for key, value in sorted(self.stats_summary().items()):\n                print(f\"{key + ':':24}{value}\")\n\n    def use_fine_grained_cache(self) -> bool:\n        return self.cache_enabled and self.options.use_fine_grained_cache\n\n    def maybe_swap_for_shadow_path(self, path: str) -> str:\n        if not self.shadow_map:\n            return path\n\n        path = normpath(path, self.options)\n\n        previously_checked = path in self.shadow_equivalence_map\n        if not previously_checked:\n            for source, shadow in self.shadow_map.items():\n                if self.fscache.samefile(path, source):\n                    self.shadow_equivalence_map[path] = shadow\n                    break\n                else:\n                    self.shadow_equivalence_map[path] = None\n\n        shadow_file = self.shadow_equivalence_map.get(path)\n        return shadow_file if shadow_file else path\n\n    def get_stat(self, path: str) -> os.stat_result | None:\n        return self.fscache.stat_or_none(self.maybe_swap_for_shadow_path(path))\n\n    def getmtime(self, path: str) -> int:\n        \"\"\"Return a file's mtime; but 0 in bazel mode.\n\n        (Bazel's distributed cache doesn't like filesystem metadata to\n        end up in output files.)\n        \"\"\"\n        if self.options.bazel:\n            return 0\n        else:\n            return int(self.metastore.getmtime(path))\n\n    def correct_rel_imp(self, file: MypyFile, imp: ImportFrom | ImportAll) -> str:\n        \"\"\"Function to correct for relative imports.\"\"\"\n        file_id = file.fullname\n        rel = imp.relative\n        if rel == 0:\n            return imp.id\n        if os.path.basename(file.path).startswith(\"__init__.\"):\n            rel -= 1\n        if rel != 0:\n            file_id = \".\".join(file_id.split(\".\")[:-rel])\n        new_id = file_id + \".\" + imp.id if imp.id else file_id\n\n        if not new_id:\n            self.errors.set_file(file.path, file.name, self.options)\n            self.error(\n                imp.line, \"No parent module -- cannot perform relative import\", blocker=True\n            )\n\n        return new_id\n\n    def all_imported_modules_in_file(self, file: MypyFile) -> list[tuple[int, str, int]]:\n        \"\"\"Find all reachable import statements in a file.\n\n        Return list of tuples (priority, module id, import line number)\n        for all modules imported in file; lower numbers == higher priority.\n\n        Can generate blocking errors on bogus relative imports.\n        \"\"\"\n        res: list[tuple[int, str, int]] = []\n        for imp in file.imports:\n            if not imp.is_unreachable:\n                if isinstance(imp, Import):\n                    pri = import_priority(imp, PRI_MED)\n                    ancestor_pri = import_priority(imp, PRI_LOW)\n                    for id, _ in imp.ids:\n                        res.append((pri, id, imp.line))\n                        ancestor_parts = id.split(\".\")[:-1]\n                        ancestors = []\n                        for part in ancestor_parts:\n                            ancestors.append(part)\n                            res.append((ancestor_pri, \".\".join(ancestors), imp.line))\n                elif isinstance(imp, ImportFrom):\n                    cur_id = self.correct_rel_imp(file, imp)\n                    all_are_submodules = True\n                    # Also add any imported names that are submodules.\n                    pri = import_priority(imp, PRI_MED)\n                    for name, __ in imp.names:\n                        sub_id = cur_id + \".\" + name\n                        if self.is_module(sub_id):\n                            res.append((pri, sub_id, imp.line))\n                        else:\n                            all_are_submodules = False\n                    # Add cur_id as a dependency, even if all the\n                    # imports are submodules. Processing import from will try\n                    # to look through cur_id, so we should depend on it.\n                    # As a workaround for some bugs in cycle handling (#4498),\n                    # if all the imports are submodules, do the import at a lower\n                    # priority.\n                    pri = import_priority(imp, PRI_HIGH if not all_are_submodules else PRI_LOW)\n                    res.append((pri, cur_id, imp.line))\n                elif isinstance(imp, ImportAll):\n                    pri = import_priority(imp, PRI_HIGH)\n                    res.append((pri, self.correct_rel_imp(file, imp), imp.line))\n\n        # Sort such that module (e.g. foo.bar.baz) comes before its ancestors (e.g. foo\n        # and foo.bar) so that, if FindModuleCache finds the target module in a\n        # package marked with py.typed underneath a namespace package installed in\n        # site-packages, (gasp), that cache's knowledge of the ancestors\n        # (aka FindModuleCache.ns_ancestors) can be primed when it is asked to find\n        # the parent.\n        res.sort(key=lambda x: -x[1].count(\".\"))\n        return res\n\n    def is_module(self, id: str) -> bool:\n        \"\"\"Is there a file in the file system corresponding to module id?\"\"\"\n        return find_module_simple(id, self) is not None\n\n    def parse_file(\n        self,\n        id: str,\n        path: str,\n        source: str,\n        ignore_errors: bool,\n        options: Options,\n        raw_data: FileRawData | None = None,\n    ) -> MypyFile:\n        \"\"\"Parse the source of a file with the given name.\n\n        Raise CompileError if there is a parse error.\n        \"\"\"\n        imports_only = False\n        if self.workers and self.fscache.exists(path):\n            # Currently, we can use the native parser only for actual files.\n            imports_only = True\n        t0 = time.time()\n        if ignore_errors:\n            self.errors.ignored_files.add(path)\n        if raw_data:\n            # If possible, deserialize from known binary data instead of parsing from scratch.\n            tree = load_from_raw(path, id, raw_data, self.errors, options)\n        else:\n            tree = parse(source, path, id, self.errors, options=options, imports_only=imports_only)\n        tree._fullname = id\n        self.add_stats(\n            files_parsed=1,\n            modules_parsed=int(not tree.is_stub),\n            stubs_parsed=int(tree.is_stub),\n            parse_time=time.time() - t0,\n        )\n\n        if self.errors.is_blockers():\n            self.log(\"Bailing due to parse errors\")\n            self.errors.raise_error()\n        return tree\n\n    def load_fine_grained_deps(self, id: str) -> dict[str, set[str]]:\n        t0 = time.time()\n        if id in self.fg_deps_meta:\n            # TODO: Assert deps file wasn't changed.\n            deps = json_loads(self.metastore.read(self.fg_deps_meta[id][\"path\"]))\n        else:\n            deps = {}\n        val = {k: set(v) for k, v in deps.items()}\n        self.add_stats(load_fg_deps_time=time.time() - t0)\n        return val\n\n    def report_file(\n        self, file: MypyFile, type_map: dict[Expression, Type], options: Options\n    ) -> None:\n        if self.reports is not None and self.source_set.is_source(file):\n            self.reports.file(file, self.modules, type_map, options)\n\n    def verbosity(self) -> int:\n        return self.options.verbosity\n\n    def log(self, *message: str) -> None:\n        if self.verbosity() >= 1:\n            if message:\n                print(\"LOG: \", *message, file=self.stderr)\n            else:\n                print(file=self.stderr)\n            self.stderr.flush()\n\n    def log_fine_grained(self, *message: str) -> None:\n        if self.verbosity() >= 1:\n            self.log(\"fine-grained:\", *message)\n        elif mypy.build.DEBUG_FINE_GRAINED:\n            # Output log in a simplified format that is quick to browse.\n            if message:\n                print(*message, file=self.stderr)\n            else:\n                print(file=self.stderr)\n            self.stderr.flush()\n\n    def trace(self, *message: str) -> None:\n        if self.verbosity() >= 2:\n            print(\"TRACE:\", *message, file=self.stderr)\n            self.stderr.flush()\n\n    def add_stats(self, **kwds: Any) -> None:\n        for key, value in kwds.items():\n            if key in self.stats:\n                self.stats[key] += value\n            else:\n                self.stats[key] = value\n\n    def stats_summary(self) -> Mapping[str, object]:\n        return self.stats\n\n    def submit(self, graph: Graph, sccs: list[SCC]) -> None:\n        \"\"\"Submit a stale SCC for processing in current process or parallel workers.\"\"\"\n        if self.workers:\n            self.submit_to_workers(graph, sccs)\n        else:\n            self.scc_queue.extend([(0, 0, scc) for scc in sccs])\n\n    def submit_to_workers(self, graph: Graph, sccs: list[SCC] | None = None) -> None:\n        if sccs is not None:\n            for scc in sccs:\n                heappush(self.scc_queue, (-scc.size_hint, self.queue_order, scc))\n                self.queue_order += 1\n        while self.scc_queue and self.free_workers:\n            idx = self.free_workers.pop()\n            _, _, scc = heappop(self.scc_queue)\n            import_errors = {\n                mod_id: self.errors.recorded[path]\n                for mod_id in scc.mod_ids\n                if (path := graph[mod_id].xpath) in self.errors.recorded\n            }\n            send(\n                self.workers[idx].conn,\n                SccRequestMessage(\n                    scc_id=scc.id,\n                    import_errors=import_errors,\n                    mod_data={\n                        mod_id: (\n                            # Although workers don't really need to know about details\n                            # of dependencies, they will write cache, so we need to pass\n                            # suppressed_deps_opts() as part of module data.\n                            graph[mod_id].suppressed_deps_opts(),\n                            tree.raw_data if (tree := graph[mod_id].tree) else None,\n                        )\n                        for mod_id in scc.mod_ids\n                    },\n                ),\n            )\n\n    def wait_for_done(\n        self, graph: Graph\n    ) -> tuple[list[SCC], bool, dict[str, tuple[str, list[str]]]]:\n        \"\"\"Wait for a stale SCC processing to finish.\n\n        Return a tuple three items:\n          * processed SCCs\n          * whether we have more in the queue\n          * new interface hash and list of errors for each module\n        The last item is only used for parallel processing.\n        \"\"\"\n        if self.workers:\n            return self.wait_for_done_workers(graph)\n        if not self.scc_queue:\n            return [], False, {}\n        _, _, next_scc = self.scc_queue.pop(0)\n        process_stale_scc(graph, next_scc, self)\n        return [next_scc], bool(self.scc_queue), {}\n\n    def wait_for_done_workers(\n        self, graph: Graph\n    ) -> tuple[list[SCC], bool, dict[str, tuple[str, list[str]]]]:\n        if not self.scc_queue and len(self.free_workers) == len(self.workers):\n            return [], False, {}\n\n        done_sccs = []\n        results = {}\n        for idx in ready_to_read([w.conn for w in self.workers], WORKER_DONE_TIMEOUT):\n            data = SccResponseMessage.read(receive(self.workers[idx].conn))\n            self.free_workers.add(idx)\n            scc_id = data.scc_id\n            if data.blocker is not None:\n                raise data.blocker\n            assert data.result is not None\n            results.update(data.result)\n            done_sccs.append(self.scc_by_id[scc_id])\n        self.submit_to_workers(graph)  # advance after some workers are free.\n        return (\n            done_sccs,\n            bool(self.scc_queue) or len(self.free_workers) < len(self.workers),\n            results,\n        )\n\n    def is_transitive_scc_dep(self, from_scc_id: int, to_scc_id: int) -> bool:\n        \"\"\"Check if one SCC is a (transitive) dependency of another.\"\"\"\n        edge = (from_scc_id, to_scc_id)\n        if (cached := self.transitive_deps_cache.get(edge)) is not None:\n            return cached\n        todo = self.scc_by_id[from_scc_id].deps\n        seen = set()\n        while todo:\n            more = set()\n            # Breadth-first search seems to be better here, because all\n            # \"lower-level\" SCCs are processed and some may be cached.\n            for dep in todo:\n                seen.add(dep)\n                if dep == to_scc_id:\n                    self.transitive_deps_cache[edge] = True\n                    return True\n                if cached := self.transitive_deps_cache.get((dep, to_scc_id)):\n                    self.transitive_deps_cache[edge] = True\n                    return True\n                elif cached is None:\n                    more |= self.scc_by_id[dep].deps\n            todo = more\n        self.transitive_deps_cache[edge] = False\n        for dep in seen:\n            # We negative-cache all intermediate lookups, thus\n            # trading time for space.\n            self.transitive_deps_cache[(dep, to_scc_id)] = False\n        return False\n\n    def error(\n        self,\n        line: int | None,\n        msg: str,\n        code: ErrorCode | None = None,\n        *,\n        blocker: bool = False,\n        only_once: bool = False,\n    ) -> None:\n        if line is None:\n            line = column = -1\n        else:\n            column = 0\n        self.errors.report(line, column, msg, code, blocker=blocker, only_once=only_once)\n\n    def note(\n        self, line: int | None, msg: str, code: ErrorCode | None = None, *, only_once: bool = False\n    ) -> None:\n        if line is None:\n            line = column = -1\n        else:\n            column = 0\n        self.errors.report(line, column, msg, code, severity=\"note\", only_once=only_once)\n\n    def note_multiline(\n        self, line: int | None, msg: str, code: ErrorCode | None = None, *, only_once: bool = False\n    ) -> None:\n        for msg_line in dedent(msg.lstrip(\"\\n\")).splitlines():\n            self.note(line, msg_line, code, only_once=only_once)\n\n\ndef deps_to_json(x: dict[str, set[str]]) -> bytes:\n    return json_dumps({k: list(v) for k, v in x.items()})\n\n\n# File for storing metadata about all the fine-grained dependency caches\nDEPS_META_FILE: Final = \"@deps.meta.json\"\n# File for storing fine-grained dependencies that didn't a parent in the build\nDEPS_ROOT_FILE: Final = \"@root.deps.json\"\n\n# The name of the fake module used to store fine-grained dependencies that\n# have no other place to go.\nFAKE_ROOT_MODULE: Final = \"@root\"\n\n\ndef write_deps_cache(\n    rdeps: dict[str, dict[str, set[str]]], manager: BuildManager, graph: Graph\n) -> None:\n    \"\"\"Write cache files for fine-grained dependencies.\n\n    Serialize fine-grained dependencies map for fine-grained mode.\n\n    Dependencies on some module 'm' is stored in the dependency cache\n    file m.deps.json.  This entails some spooky action at a distance:\n    if module 'n' depends on 'm', that produces entries in m.deps.json.\n    When there is a dependency on a module that does not exist in the\n    build, it is stored with its first existing parent module. If no\n    such module exists, it is stored with the fake module FAKE_ROOT_MODULE.\n\n    This means that the validity of the fine-grained dependency caches\n    are a global property, so we store validity checking information for\n    fine-grained dependencies in a global cache file:\n     * We take a snapshot of current sources to later check consistency\n       between the fine-grained dependency cache and module cache metadata\n     * We store the mtime of all the dependency files to verify they\n       haven't changed\n    \"\"\"\n    metastore = manager.metastore\n\n    error = False\n\n    fg_deps_meta = manager.fg_deps_meta.copy()\n\n    for id in rdeps:\n        if id != FAKE_ROOT_MODULE:\n            _, _, deps_json = get_cache_names(id, graph[id].xpath, manager.options)\n        else:\n            deps_json = DEPS_ROOT_FILE\n        assert deps_json\n        manager.log(\"Writing deps cache\", deps_json)\n        if not manager.metastore.write(deps_json, deps_to_json(rdeps[id])):\n            manager.log(f\"Error writing fine-grained deps JSON file {deps_json}\")\n            error = True\n        else:\n            fg_deps_meta[id] = {\"path\": deps_json, \"mtime\": manager.getmtime(deps_json)}\n\n    meta_snapshot: dict[str, str] = {}\n    for id, st in graph.items():\n        # If we didn't parse a file (so it doesn't have a\n        # source_hash), then it must be a module with a fresh cache,\n        # so use the hash from that.\n        if st.source_hash:\n            hash = st.source_hash\n        else:\n            if st.meta:\n                hash = st.meta.hash\n            else:\n                hash = \"\"\n        meta_snapshot[id] = hash\n\n    meta = {\"snapshot\": meta_snapshot, \"deps_meta\": fg_deps_meta}\n\n    if not metastore.write(DEPS_META_FILE, json_dumps(meta)):\n        manager.log(f\"Error writing fine-grained deps meta JSON file {DEPS_META_FILE}\")\n        error = True\n\n    if error:\n        manager.errors.set_file(_cache_dir_prefix(manager.options), None, manager.options)\n        manager.error(None, \"Error writing fine-grained dependencies cache\", blocker=True)\n\n\ndef invert_deps(deps: dict[str, set[str]], graph: Graph) -> dict[str, dict[str, set[str]]]:\n    \"\"\"Splits fine-grained dependencies based on the module of the trigger.\n\n    Returns a dictionary from module ids to all dependencies on that\n    module. Dependencies not associated with a module in the build will be\n    associated with the nearest parent module that is in the build, or the\n    fake module FAKE_ROOT_MODULE if none are.\n    \"\"\"\n    # Lazy import to speed up startup\n    from mypy.server.target import trigger_to_target\n\n    # Prepopulate the map for all the modules that have been processed,\n    # so that we always generate files for processed modules (even if\n    # there aren't any dependencies to them.)\n    rdeps: dict[str, dict[str, set[str]]] = {id: {} for id, st in graph.items() if st.tree}\n    for trigger, targets in deps.items():\n        module = module_prefix(graph, trigger_to_target(trigger))\n        if not module or not graph[module].tree:\n            module = FAKE_ROOT_MODULE\n\n        mod_rdeps = rdeps.setdefault(module, {})\n        mod_rdeps.setdefault(trigger, set()).update(targets)\n\n    return rdeps\n\n\ndef generate_deps_for_cache(manager: BuildManager, graph: Graph) -> dict[str, dict[str, set[str]]]:\n    \"\"\"Generate fine-grained dependencies into a form suitable for serializing.\n\n    This does a couple things:\n    1. Splits fine-grained deps based on the module of the trigger\n    2. For each module we generated fine-grained deps for, load any previous\n       deps and merge them in.\n\n    Returns a dictionary from module ids to all dependencies on that\n    module. Dependencies not associated with a module in the build will be\n    associated with the nearest parent module that is in the build, or the\n    fake module FAKE_ROOT_MODULE if none are.\n    \"\"\"\n    from mypy.server.deps import merge_dependencies  # Lazy import to speed up startup\n\n    # Split the dependencies out into based on the module that is depended on.\n    rdeps = invert_deps(manager.fg_deps, graph)\n\n    # We can't just clobber existing dependency information, so we\n    # load the deps for every module we've generated new dependencies\n    # to and merge the new deps into them.\n    for module, mdeps in rdeps.items():\n        old_deps = manager.load_fine_grained_deps(module)\n        merge_dependencies(old_deps, mdeps)\n\n    return rdeps\n\n\nPLUGIN_SNAPSHOT_FILE: Final = \"@plugins_snapshot.json\"\n\n\ndef write_plugins_snapshot(manager: BuildManager) -> None:\n    \"\"\"Write snapshot of versions and hashes of currently active plugins.\"\"\"\n    snapshot = json_dumps(manager.plugins_snapshot)\n    if (\n        not manager.metastore.write(PLUGIN_SNAPSHOT_FILE, snapshot)\n        and manager.options.cache_dir != os.devnull\n    ):\n        manager.errors.set_file(_cache_dir_prefix(manager.options), None, manager.options)\n        manager.error(None, \"Error writing plugins snapshot\", blocker=True)\n\n\ndef read_plugins_snapshot(manager: BuildManager) -> dict[str, str] | None:\n    \"\"\"Read cached snapshot of versions and hashes of plugins from previous run.\"\"\"\n    snapshot = _load_json_file(\n        PLUGIN_SNAPSHOT_FILE,\n        manager,\n        log_success=\"Plugins snapshot (cached) \",\n        log_error=\"Could not load plugins snapshot: \",\n    )\n    if snapshot is None:\n        return None\n    if not isinstance(snapshot, dict):\n        manager.log(f\"Could not load plugins snapshot: cache is not a dict: {type(snapshot)}\")  # type: ignore[unreachable]\n        return None\n    return snapshot\n\n\ndef read_quickstart_file(\n    options: Options, stdout: TextIO\n) -> dict[str, tuple[float, int, str]] | None:\n    quickstart: dict[str, tuple[float, int, str]] | None = None\n    if options.quickstart_file:\n        # This is very \"best effort\". If the file is missing or malformed,\n        # just ignore it.\n        raw_quickstart: dict[str, Any] = {}\n        try:\n            with open(options.quickstart_file, \"rb\") as f:\n                raw_quickstart = json_loads(f.read())\n\n            quickstart = {}\n            for file, (x, y, z) in raw_quickstart.items():\n                quickstart[file] = (x, y, z)\n        except Exception as e:\n            print(f\"Warning: Failed to load quickstart file: {str(e)}\\n\", file=stdout)\n    return quickstart\n\n\ndef read_deps_cache(manager: BuildManager, graph: Graph) -> dict[str, FgDepMeta] | None:\n    \"\"\"Read and validate the fine-grained dependencies cache.\n\n    See the write_deps_cache documentation for more information on\n    the details of the cache.\n\n    Returns None if the cache was invalid in some way.\n    \"\"\"\n    deps_meta = _load_json_file(\n        DEPS_META_FILE,\n        manager,\n        log_success=\"Deps meta \",\n        log_error=\"Could not load fine-grained dependency metadata: \",\n    )\n    if deps_meta is None:\n        return None\n    meta_snapshot = deps_meta[\"snapshot\"]\n    # Take a snapshot of the source hashes from all the metas we found.\n    # (Including the ones we rejected because they were out of date.)\n    # We use this to verify that they match up with the proto_deps.\n    current_meta_snapshot = {\n        id: st.meta_source_hash for id, st in graph.items() if st.meta_source_hash is not None\n    }\n\n    common = set(meta_snapshot.keys()) & set(current_meta_snapshot.keys())\n    if any(meta_snapshot[id] != current_meta_snapshot[id] for id in common):\n        # TODO: invalidate also if options changed (like --strict-optional)?\n        manager.log(\"Fine-grained dependencies cache inconsistent, ignoring\")\n        return None\n\n    module_deps_metas = deps_meta[\"deps_meta\"]\n    assert isinstance(module_deps_metas, dict)\n    if not manager.options.skip_cache_mtime_checks:\n        for meta in module_deps_metas.values():\n            try:\n                matched = manager.getmtime(meta[\"path\"]) == meta[\"mtime\"]\n            except FileNotFoundError:\n                matched = False\n            if not matched:\n                manager.log(f\"Invalid or missing fine-grained deps cache: {meta['path']}\")\n                return None\n\n    return module_deps_metas\n\n\ndef _load_ff_file(\n    file: str, manager: BuildManager, log_error_fmt: str, id: str | None\n) -> bytes | None:\n    if manager.stats_enabled:\n        t0 = time.time()\n    try:\n        data = manager.metastore.read(file)\n    except OSError:\n        if manager.logging_enabled:\n            if id:\n                message = log_error_fmt.format(id) + file\n            else:\n                message = log_error_fmt + file\n            manager.log(message)\n        return None\n    if manager.stats_enabled:\n        manager.add_stats(metastore_read_time=time.time() - t0)\n    return data\n\n\ndef _load_json_file(\n    file: str, manager: BuildManager, log_success: str, log_error: str\n) -> dict[str, Any] | None:\n    \"\"\"A simple helper to read a JSON file with logging.\"\"\"\n    t0 = time.time()\n    try:\n        data = manager.metastore.read(file)\n    except OSError:\n        manager.log(log_error + file)\n        return None\n    manager.add_stats(metastore_read_time=time.time() - t0)\n    # Only bother to compute the log message if we are logging it, since it could be big\n    if manager.verbosity() >= 2:\n        manager.trace(log_success + data.rstrip().decode())\n    try:\n        t1 = time.time()\n        result = json_loads(data)\n        manager.add_stats(data_file_load_time=time.time() - t1)\n    except json.JSONDecodeError:\n        manager.errors.set_file(file, None, manager.options)\n        manager.error(\n            None,\n            \"Error reading JSON file;\"\n            \" you likely have a bad cache.\\n\"\n            \"Try removing the {cache_dir} directory\"\n            \" and run mypy again.\".format(cache_dir=manager.options.cache_dir),\n            blocker=True,\n        )\n        return None\n    else:\n        assert isinstance(result, dict)\n        return result\n\n\ndef _cache_dir_prefix(options: Options) -> str:\n    \"\"\"Get current cache directory (or file if id is given).\"\"\"\n    if options.bazel:\n        # This is needed so the cache map works.\n        return os.curdir\n    cache_dir = options.cache_dir\n    pyversion = options.python_version\n    base = os_path_join(cache_dir, \"%d.%d\" % pyversion)\n    return base\n\n\ndef add_catch_all_gitignore(target_dir: str) -> None:\n    \"\"\"Add catch-all .gitignore to an existing directory.\n\n    No-op if the .gitignore already exists.\n    \"\"\"\n    gitignore = os_path_join(target_dir, \".gitignore\")\n    try:\n        with open(gitignore, \"x\") as f:\n            print(\"# Automatically created by mypy\", file=f)\n            print(\"*\", file=f)\n    except FileExistsError:\n        pass\n\n\ndef exclude_from_backups(target_dir: str) -> None:\n    \"\"\"Exclude the directory from various archives and backups supporting CACHEDIR.TAG.\n\n    If the CACHEDIR.TAG file exists the function is a no-op.\n    \"\"\"\n    cachedir_tag = os_path_join(target_dir, \"CACHEDIR.TAG\")\n    try:\n        with open(cachedir_tag, \"x\") as f:\n            f.write(\"\"\"Signature: 8a477f597d28d172789f06886806bc55\n# This file is a cache directory tag automatically created by mypy.\n# For information about cache directory tags see https://bford.info/cachedir/\n\"\"\")\n    except FileExistsError:\n        pass\n\n\ndef create_metastore(options: Options, parallel_worker: bool = False) -> MetadataStore:\n    \"\"\"Create the appropriate metadata store.\"\"\"\n    if options.sqlite_cache:\n        # We use this flag in both coordinator and workers to speed up commits,\n        # see mypy.metastore.connect_db() for details.\n        sync_off = options.num_workers > 0 or parallel_worker\n        mds: MetadataStore = SqliteMetadataStore(_cache_dir_prefix(options), sync_off=sync_off)\n    else:\n        mds = FilesystemMetadataStore(_cache_dir_prefix(options))\n    return mds\n\n\ndef get_errors_name(meta_name: str) -> str:\n    # Convert e.g. foo.bar.meta.ff to foo.bar.err.ff\n    parts = meta_name.rsplit(\".\", maxsplit=2)\n    parts[1] = \"err\"\n    return \".\".join(parts)\n\n\ndef get_cache_names(id: str, path: str, options: Options) -> tuple[str, str, str | None]:\n    \"\"\"Return the file names for the cache files.\n\n    Args:\n      id: module ID\n      path: module path\n      options: build options\n\n    Returns:\n      A tuple with the file names to be used for the meta file, the\n      data file, and the fine-grained deps JSON, respectively.\n    \"\"\"\n    if options.cache_map:\n        pair = options.cache_map.get(normpath(path, options))\n    else:\n        pair = None\n    if pair is not None:\n        # The cache map paths were specified relative to the base directory,\n        # but the filesystem metastore APIs operates relative to the cache\n        # prefix directory.\n        # Solve this by rewriting the paths as relative to the root dir.\n        # This only makes sense when using the filesystem backed cache.\n        root = _cache_dir_prefix(options)\n        return os.path.relpath(pair[0], root), os.path.relpath(pair[1], root), None\n    prefix = os.path.join(*id.split(\".\"))\n    is_package = os.path.basename(path).startswith(\"__init__.py\")\n    if is_package:\n        prefix = os_path_join(prefix, \"__init__\")\n\n    deps_json = None\n    if options.cache_fine_grained:\n        deps_json = prefix + \".deps.json\"\n    if options.fixed_format_cache:\n        data_suffix = \".data.ff\"\n        meta_suffix = \".meta.ff\"\n    else:\n        data_suffix = \".data.json\"\n        meta_suffix = \".meta.json\"\n    return prefix + meta_suffix, prefix + data_suffix, deps_json\n\n\ndef options_snapshot(id: str, manager: BuildManager) -> dict[str, object]:\n    \"\"\"Make compact snapshot of options for a module.\n\n    Separately store only the options we may compare individually, and take a hash\n    of everything else. If --debug-cache is specified, fall back to full snapshot.\n    \"\"\"\n    platform_opt, values = manager.options.clone_for_module(id).select_options_affecting_cache()\n    if manager.options.debug_cache:\n        # Build full options snapshot for debugging purposes.\n        result: dict[str, object] = {\"platform\": platform_opt}\n        for key, val in zip(OPTIONS_AFFECTING_CACHE_NO_PLATFORM, values):\n            result[key] = val\n        return result\n    # Process most options quickly, since this is performance critical.\n    buf = WriteBuffer()\n    write_json_value(buf, cast(JsonValue, values))\n    return {\"platform\": platform_opt, \"other_options\": hash_digest(buf.getvalue())}\n\n\ndef find_cache_meta(\n    id: str, path: str, manager: BuildManager, skip_validation: bool = False\n) -> tuple[CacheMeta | None, list[ErrorTuple]]:\n    \"\"\"Find cache data for a module.\n\n    Args:\n      id: module ID\n      path: module path\n      manager: the build manager (for pyversion, log/trace, and build options)\n      skip_validation: if True skip any validation steps (used for parallel checking)\n\n    Returns:\n      A CacheMeta instance if the cache data was found and appears\n      valid; otherwise None.\n    \"\"\"\n    # TODO: May need to take more build options into account\n    meta_file, data_file, _ = get_cache_names(id, path, manager.options)\n    if manager.tracing_enabled:\n        manager.trace(f\"Looking for {id} at {meta_file}\")\n    if manager.stats_enabled:\n        t0 = time.time()\n    if manager.options.fixed_format_cache:\n        meta = _load_ff_file(\n            meta_file, manager, log_error_fmt=\"Could not load cache for {}: \", id=id\n        )\n    else:\n        meta = _load_json_file(\n            meta_file,\n            manager,\n            log_success=f\"Meta {id} \",\n            log_error=f\"Could not load cache for {id}: \",\n        )\n    if meta is None:\n        return None, []\n    if manager.stats_enabled:\n        t1 = time.time()\n    if isinstance(meta, bytes):\n        # If either low-level buffer format or high-level cache layout changed, we\n        # cannot use the cache files, even with --skip-version-check.\n        # TODO: switch to something like librt.internal.read_byte() if this is slow.\n        if meta[0] != cache_version() or meta[1] != CACHE_VERSION:\n            manager.log(f\"Metadata abandoned for {id}: incompatible cache format\")\n            return None, []\n        data_io = ReadBuffer(meta[2:])\n        m = CacheMeta.read(data_io, data_file)\n    else:\n        m = CacheMeta.deserialize(meta, data_file)\n    if m is None:\n        manager.log(f\"Metadata abandoned for {id}: cannot deserialize data\")\n        return None, []\n    if manager.stats_enabled:\n        t2 = time.time()\n        manager.add_stats(\n            load_meta_time=t2 - t0, load_meta_load_time=t1 - t0, load_meta_from_dict_time=t2 - t1\n        )\n    if skip_validation:\n        return m, []\n\n    # Ignore cache if generated by an older mypy version.\n    if m.version_id != manager.version_id and not manager.options.skip_version_check:\n        manager.log(f\"Metadata abandoned for {id}: different mypy version\")\n        return None, []\n\n    total_deps = len(m.dependencies) + len(m.suppressed)\n    if len(m.dep_prios) != total_deps or len(m.dep_lines) != total_deps:\n        manager.log(f\"Metadata abandoned for {id}: broken dependencies\")\n        return None, []\n\n    # Ignore cache if (relevant) options aren't the same.\n    # Note that it's fine to mutilate cached_options since it's only used here.\n    cached_options = m.options\n    current_options = options_snapshot(id, manager)\n    if manager.options.skip_version_check:\n        # When we're lax about version we're also lax about platform.\n        cached_options[\"platform\"] = current_options[\"platform\"]\n    if \"debug_cache\" in cached_options:\n        # Older versions included debug_cache, but it's silly to compare it.\n        del cached_options[\"debug_cache\"]\n    if cached_options != current_options:\n        manager.log(f\"Metadata abandoned for {id}: options differ\")\n        if manager.options.verbosity >= 2:\n            for key in sorted(set(cached_options) | set(current_options)):\n                if cached_options.get(key) != current_options.get(key):\n                    manager.trace(\n                        \"    {}: {} != {}\".format(\n                            key, cached_options.get(key), current_options.get(key)\n                        )\n                    )\n        return None, []\n    if manager.old_plugins_snapshot and manager.plugins_snapshot:\n        # Check if plugins are still the same.\n        if manager.plugins_snapshot != manager.old_plugins_snapshot:\n            manager.log(f\"Metadata abandoned for {id}: plugins differ\")\n            return None, []\n    plugin_data = manager.plugin.report_config_data(ReportConfigContext(id, path, is_check=True))\n    if not manager.options.fixed_format_cache:\n        # So that plugins can return data with tuples in it without\n        # things silently always invalidating modules, we round-trip\n        # the config data. This isn't beautiful.\n        plugin_data = json_loads(json_dumps(plugin_data))\n    if m.plugin_data != plugin_data:\n        manager.log(f\"Metadata abandoned for {id}: plugin configuration differs\")\n        return None, []\n\n    # Load cached errors for this file, even if empty. This is needed to avoid\n    # invalid cache state after a crash/blocker/Ctrl+C etc.\n    errors_file = get_errors_name(meta_file)\n    if manager.options.fixed_format_cache:\n        errors = _load_ff_file(\n            errors_file, manager, log_error_fmt=\"Could not load errors for {}: \", id=id\n        )\n    else:\n        errors = _load_json_file(\n            errors_file,\n            manager,\n            log_success=f\"Errors {id} \",\n            log_error=f\"Could not load errors for {id}: \",\n        )\n    if errors is None:\n        return None, []\n    if isinstance(errors, bytes):\n        data_io = ReadBuffer(errors)\n        e = read_errors(data_io)\n    else:\n        e = [tuple(err) for err in errors[\"error_lines\"]]\n    manager.add_stats(fresh_metas=1)\n    return m, e\n\n\ndef validate_meta(\n    meta: CacheMeta | None, id: str, path: str | None, ignore_all: bool, manager: BuildManager\n) -> CacheMeta | None:\n    \"\"\"Checks whether the cached AST of this module can be used.\n\n    Returns:\n      None, if the cached AST is unusable.\n      Original meta, if mtime/size matched.\n      Meta with mtime updated to match source file, if hash/size matched but mtime/path didn't.\n    \"\"\"\n    # This requires two steps. The first one is obvious: we check that the module source file\n    # contents is the same as it was when the cache data file was created. The second one is not\n    # too obvious: we check that the cache data file mtime has not changed; it is needed because\n    # we use cache data file mtime to propagate information about changes in the dependencies.\n\n    if meta is None:\n        manager.log(f\"Metadata not found for {id}\")\n        return None\n\n    if meta.ignore_all and not ignore_all:\n        manager.log(f\"Metadata abandoned for {id}: errors were previously ignored\")\n        return None\n\n    if manager.stats_enabled:\n        t0 = time.time()\n    bazel = manager.options.bazel\n    assert path is not None, \"Internal error: meta was provided without a path\"\n    if not manager.options.skip_cache_mtime_checks:\n        # Check data_file; assume if its mtime matches it's good.\n        try:\n            data_mtime = manager.getmtime(meta.data_file)\n        except OSError:\n            manager.log(f\"Metadata abandoned for {id}: failed to stat data_file\")\n            return None\n        if data_mtime != meta.data_mtime:\n            manager.log(f\"Metadata abandoned for {id}: data cache is modified\")\n            return None\n\n    if bazel:\n        # Normalize path under bazel to make sure it isn't absolute\n        path = normpath(path, manager.options)\n\n    st = manager.get_stat(path)\n    if st is None:\n        return None\n    if not stat.S_ISDIR(st.st_mode) and not stat.S_ISREG(st.st_mode):\n        manager.log(f\"Metadata abandoned for {id}: file or directory {path} does not exist\")\n        return None\n\n    if manager.stats_enabled:\n        manager.add_stats(validate_stat_time=time.time() - t0)\n\n    # When we are using a fine-grained cache, we want our initial\n    # build() to load all of the cache information and then do a\n    # fine-grained incremental update to catch anything that has\n    # changed since the cache was generated. We *don't* want to do a\n    # coarse-grained incremental rebuild, so we accept the cache\n    # metadata even if it doesn't match the source file.\n    #\n    # We still *do* the mtime/hash checks, however, to enable\n    # fine-grained mode to take advantage of the mtime-updating\n    # optimization when mtimes differ but hashes match.  There is\n    # essentially no extra time cost to computing the hash here, since\n    # it will be cached and will be needed for finding changed files\n    # later anyways.\n    fine_grained_cache = manager.use_fine_grained_cache()\n\n    size = st.st_size\n    # Bazel ensures the cache is valid.\n    if size != meta.size and not bazel and not fine_grained_cache:\n        manager.log(f\"Metadata abandoned for {id}: file {path} has different size\")\n        return None\n\n    # Bazel ensures the cache is valid.\n    mtime = 0 if bazel else int(st.st_mtime)\n    if not bazel and (mtime != meta.mtime or path != meta.path):\n        if manager.quickstart_state and path in manager.quickstart_state:\n            # If the mtime and the size of the file recorded in the quickstart dump matches\n            # what we see on disk, we know (assume) that the hash matches the quickstart\n            # data as well. If that hash matches the hash in the metadata, then we know\n            # the file is up to date even though the mtime is wrong, without needing to hash it.\n            qmtime, qsize, qhash = manager.quickstart_state[path]\n            if int(qmtime) == mtime and qsize == size and qhash == meta.hash:\n                manager.log(f\"Metadata fresh (by quickstart) for {id}: file {path}\")\n                meta.mtime = mtime\n                meta.path = path\n                return meta\n\n        t0 = time.time()\n        try:\n            # dir means it is a namespace package\n            if stat.S_ISDIR(st.st_mode):\n                source_hash = \"\"\n            else:\n                source_hash = manager.fscache.hash_digest(path)\n        except (OSError, UnicodeDecodeError, DecodeError):\n            return None\n        manager.add_stats(validate_hash_time=time.time() - t0)\n        if source_hash != meta.hash:\n            if fine_grained_cache:\n                manager.log(f\"Using stale metadata for {id}: file {path}\")\n                return meta\n            else:\n                manager.log(f\"Metadata abandoned for {id}: file {path} has different hash\")\n                return None\n        else:\n            if manager.stats_enabled:\n                t0 = time.time()\n            # Optimization: update mtime and path (otherwise, this mismatch will reappear).\n            meta.mtime = mtime\n            meta.path = path\n            meta.size = size\n            meta.options = options_snapshot(id, manager)\n            meta_file, _, _ = get_cache_names(id, path, manager.options)\n            if manager.logging_enabled:\n                manager.log(\n                    \"Updating mtime for {}: file {}, meta {}, mtime {}\".format(\n                        id, path, meta_file, meta.mtime\n                    )\n                )\n            write_cache_meta(meta, manager, meta_file)\n            if manager.stats_enabled:\n                t1 = time.time()\n                manager.add_stats(\n                    validate_update_time=time.time() - t1, validate_munging_time=t1 - t0\n                )\n            return meta\n\n    # It's a match on (id, path, size, hash, mtime).\n    if manager.logging_enabled:\n        manager.log(f\"Metadata fresh for {id}: file {path}\")\n    return meta\n\n\ndef compute_hash(text: str) -> str:\n    # We use a crypto hash instead of the builtin hash(...) function\n    # because the output of hash(...)  can differ between runs due to\n    # hash randomization (enabled by default in Python 3.3).  See the\n    # note in\n    # https://docs.python.org/3/reference/datamodel.html#object.__hash__.\n    return hash_digest(text.encode(\"utf-8\"))\n\n\ndef write_cache(\n    id: str,\n    path: str,\n    tree: MypyFile,\n    dependencies: list[str],\n    suppressed: list[str],\n    suppressed_deps_opts: bytes,\n    imports_ignored: dict[int, list[str]],\n    dep_prios: list[int],\n    dep_lines: list[int],\n    old_interface_hash: bytes,\n    trans_dep_hash: bytes,\n    source_hash: str,\n    ignore_all: bool,\n    manager: BuildManager,\n) -> tuple[bytes, tuple[CacheMeta, str] | None]:\n    \"\"\"Write cache files for a module.\n\n    Note that this mypy's behavior is still correct when any given\n    write_cache() call is replaced with a no-op, so error handling\n    code that bails without writing anything is okay.\n\n    Args:\n      id: module ID\n      path: module path\n      tree: the fully checked module data\n      dependencies: module IDs on which this module depends\n      suppressed: module IDs which were suppressed as dependencies\n      dep_prios: priorities (parallel array to dependencies)\n      dep_lines: import line locations (parallel array to dependencies)\n      old_interface_hash: the hash from the previous version of the data cache file\n      source_hash: the hash of the source code\n      ignore_all: the ignore_all flag for this module\n      manager: the build manager (for pyversion, log/trace)\n\n    Returns:\n      A tuple containing the interface hash and inner tuple with CacheMeta\n      that should be written and path to cache file (inner tuple may be None,\n      if the cache data could not be written).\n    \"\"\"\n    metastore = manager.metastore\n    # For Bazel we use relative paths and zero mtimes.\n    bazel = manager.options.bazel\n\n    # Obtain file paths.\n    meta_file, data_file, _ = get_cache_names(id, path, manager.options)\n    manager.log(f\"Writing {id} {path} {meta_file} {data_file}\")\n\n    # Update tree.path so that in bazel mode it's made relative (since\n    # sometimes paths leak out).\n    if bazel:\n        tree.path = path\n\n    plugin_data = manager.plugin.report_config_data(ReportConfigContext(id, path, is_check=False))\n\n    # Serialize data and analyze interface\n    if manager.options.fixed_format_cache:\n        data_io = WriteBuffer()\n        tree.write(data_io)\n        data_bytes = data_io.getvalue()\n    else:\n        data = tree.serialize()\n        data_bytes = json_dumps(data, manager.options.debug_cache)\n    interface_hash = hash_digest_bytes(data_bytes + json_dumps(plugin_data))\n\n    # Obtain and set up metadata\n    st = manager.get_stat(path)\n    if st is None:\n        manager.log(f\"Cannot get stat for {path}\")\n        # Remove apparently-invalid cache files.\n        # (This is purely an optimization.)\n        for filename in [data_file, meta_file]:\n            try:\n                os.remove(filename)\n            except OSError:\n                pass\n        # Still return the interface hash we computed.\n        return interface_hash, None\n\n    # Write data cache file, if applicable\n    # Note that for Bazel we don't record the data file's mtime.\n    if old_interface_hash == interface_hash:\n        manager.trace(f\"Interface for {id} is unchanged\")\n    else:\n        manager.trace(f\"Interface for {id} has changed\")\n        if not metastore.write(data_file, data_bytes):\n            # Most likely the error is the replace() call\n            # (see https://github.com/python/mypy/issues/3215).\n            manager.log(f\"Error writing cache data file {data_file}\")\n            # Let's continue without writing the meta file.  Analysis:\n            # If the replace failed, we've changed nothing except left\n            # behind an extraneous temporary file; if the replace\n            # worked but the getmtime() call failed, the meta file\n            # will be considered invalid on the next run because the\n            # data_mtime field won't match the data file's mtime.\n            # Both have the effect of slowing down the next run a\n            # little bit due to an out-of-date cache file.\n            return interface_hash, None\n\n    try:\n        data_mtime = manager.getmtime(data_file)\n    except OSError:\n        manager.log(f\"Error in os.stat({data_file!r}), skipping cache write\")\n        return interface_hash, None\n\n    mtime = 0 if bazel else int(st.st_mtime)\n    size = st.st_size\n    # Note that the options we store in the cache are the options as\n    # specified by the command line/config file and *don't* reflect\n    # updates made by inline config directives in the file. This is\n    # important, or otherwise the options would never match when\n    # verifying the cache.\n    assert source_hash is not None\n    meta = CacheMeta(\n        id=id,\n        path=path,\n        mtime=mtime,\n        size=size,\n        hash=source_hash,\n        dependencies=dependencies,\n        data_mtime=data_mtime,\n        data_file=data_file,\n        suppressed=suppressed,\n        imports_ignored=imports_ignored,\n        options=options_snapshot(id, manager),\n        suppressed_deps_opts=suppressed_deps_opts,\n        dep_prios=dep_prios,\n        dep_lines=dep_lines,\n        interface_hash=interface_hash,\n        trans_dep_hash=trans_dep_hash,\n        version_id=manager.version_id,\n        ignore_all=ignore_all,\n        plugin_data=plugin_data,\n        # This one will be filled by the caller.\n        dep_hashes=[],\n    )\n    return interface_hash, (meta, meta_file)\n\n\ndef write_cache_meta(meta: CacheMeta, manager: BuildManager, meta_file: str) -> None:\n    # Write meta cache file\n    metastore = manager.metastore\n    if manager.options.fixed_format_cache:\n        data_io = WriteBuffer()\n        meta.write(data_io)\n        # Prefix with both low- and high-level cache format versions for future validation.\n        # TODO: switch to something like librt.internal.write_byte() if this is slow.\n        meta_bytes = bytes([cache_version(), CACHE_VERSION]) + data_io.getvalue()\n    else:\n        meta_dict = meta.serialize()\n        meta_bytes = json_dumps(meta_dict, manager.options.debug_cache)\n    if not metastore.write(meta_file, meta_bytes):\n        # Most likely the error is the replace() call\n        # (see https://github.com/python/mypy/issues/3215).\n        # The next run will simply find the cache entry out of date.\n        manager.log(f\"Error writing cache meta file {meta_file}\")\n\n\ndef write_errors_file(\n    meta_file: str, error_lines: list[ErrorTuple], manager: BuildManager\n) -> None:\n    # Write errors cache file\n    errors_file = get_errors_name(meta_file)\n    metastore = manager.metastore\n    if manager.options.fixed_format_cache:\n        data_io = WriteBuffer()\n        write_errors(data_io, error_lines)\n        meta_bytes = data_io.getvalue()\n    else:\n        # Some generic JSON helpers require top-level to be a dict.\n        meta_bytes = json_dumps({\"error_lines\": error_lines}, manager.options.debug_cache)\n    if not metastore.write(errors_file, meta_bytes):\n        manager.log(f\"Error writing errors file {errors_file}\")\n\n\n\"\"\"Dependency manager.\n\nDesign\n======\n\nIdeally\n-------\n\nA. Collapse cycles (each SCC -- strongly connected component --\n   becomes one \"supernode\").\n\nB. Topologically sort nodes based on dependencies.\n\nC. Process from leaves towards roots.\n\nWrinkles\n--------\n\na. Need to parse source modules to determine dependencies.\n\nb. Processing order for modules within an SCC.\n\nc. Must order mtimes of files to decide whether to re-process; depends\n   on clock never resetting.\n\nd. from P import M; checks filesystem whether module P.M exists in\n   filesystem.\n\ne. Race conditions, where somebody modifies a file while we're\n   processing. Solved by using a FileSystemCache.\n\n\nSteps\n-----\n\n1. For each explicitly given module find the source file location.\n\n2. For each such module load and check the cache metadata, and decide\n   whether it's valid.\n\n3. Now recursively (or iteratively) find dependencies and add those to\n   the graph:\n\n   - for cached nodes use the list of dependencies from the cache\n     metadata (this will be valid even if we later end up re-parsing\n     the same source);\n\n   - for uncached nodes parse the file and process all imports found,\n     taking care of (a) above.\n\nStep 3 should also address (d) above.\n\nOnce step 3 terminates we have the entire dependency graph, and for\neach module we've either loaded the cache metadata or parsed the\nsource code.  (However, we may still need to parse those modules for\nwhich we have cache metadata but that depend, directly or indirectly,\non at least one module for which the cache metadata is stale.)\n\nNow we can execute steps A-C from the first section.  Finding SCCs for\nstep A shouldn't be hard; there's a recipe here:\nhttps://code.activestate.com/recipes/578507/.  There's also a plethora\nof topsort recipes, e.g. https://code.activestate.com/recipes/577413/.\n\nFor single nodes, processing is simple.  If the node was cached, we\ndeserialize the cache data and fix up cross-references.  Otherwise, we\ndo semantic analysis followed by type checking.  Once we (re-)processed\nan SCC we check whether its interface (symbol table) is still fresh\n(matches previous cached value). If it is not, we consider dependent SCCs\nstale so that they need to be re-parsed as well.\n\nNote on indirect dependencies: normally dependencies are determined from\nimports, but since our interfaces are \"opaque\" (i.e. symbol tables can\ncontain cross-references as well as types identified by name), these are not\nenough.  We *must* also add \"indirect\" dependencies from symbols and types to\ntheir definitions.  For this purpose, we record all accessed symbols during\nsemantic analysis, and after we finished processing a module, we traverse its\ntype map, and for each type we find (transitively) on which named types it\ndepends.\n\nImport cycles\n-------------\n\nFinally we have to decide how to handle (b), import cycles.  Here\nwe'll need a modified version of the original state machine\n(build.py), but we only need to do this per SCC, and we won't have to\ndeal with changes to the list of nodes while we're processing it.\n\nIf all nodes in the SCC have valid cache metadata and all dependencies\noutside the SCC are still valid, we can proceed as follows:\n\n  1. Load cache data for all nodes in the SCC.\n\n  2. Fix up cross-references for all nodes in the SCC.\n\nOtherwise, the simplest (but potentially slow) way to proceed is to\ninvalidate all cache data in the SCC and re-parse all nodes in the SCC\nfrom source.  We can do this as follows:\n\n  1. Parse source for all nodes in the SCC.\n\n  2. Semantic analysis for all nodes in the SCC.\n\n  3. Type check all nodes in the SCC.\n\n(If there are more passes the process is the same -- each pass should\nbe done for all nodes before starting the next pass for any nodes in\nthe SCC.)\n\nWe could process the nodes in the SCC in any order.  For sentimental\nreasons, I've decided to process them in the reverse order in which we\nencountered them when originally constructing the graph.  That's how\nthe old build.py deals with cycles, and at least this reproduces the\nprevious implementation more accurately.\n\nCan we do better than re-parsing all nodes in the SCC when any of its\ndependencies are out of date?  It's doubtful.  The optimization\nmentioned at the end of the previous section would require re-parsing\nand type-checking a node and then comparing its symbol table to the\ncached data; but because the node is part of a cycle we can't\ntechnically type-check it until the semantic analysis of all other\nnodes in the cycle has completed.  (This is an important issue because\nDropbox has a very large cycle in production code.  But I'd like to\ndeal with it later.)\n\nAdditional wrinkles\n-------------------\n\nDuring implementation more wrinkles were found.\n\n- When a submodule of a package (e.g. x.y) is encountered, the parent\n  package (e.g. x) must also be loaded, but it is not strictly a\n  dependency.  See State.add_ancestors() below.\n\"\"\"\n\n\nclass SuppressionReason:\n    NOT_FOUND: Final = 1\n    SKIPPED: Final = 2\n\n\nclass ModuleNotFound(Exception):\n    \"\"\"Control flow exception to signal that a module was not found.\"\"\"\n\n    def __init__(self, reason: int = SuppressionReason.NOT_FOUND) -> None:\n        self.reason = reason\n\n\n@final\nclass State:\n    \"\"\"The state for a module.\n\n    The source is only used for the -c command line option; in that\n    case path is None.  Otherwise, source is None and path isn't.\n    \"\"\"\n\n    manager: BuildManager\n    order_counter: ClassVar[int] = 0\n    order: int  # Order in which modules were encountered\n    id: str  # Fully qualified module name\n    path: str | None = None  # Path to module source\n    abspath: str | None = None  # Absolute path to module source\n    xpath: str  # Path or '<string>'\n    source: str | None = None  # Module source code\n    source_hash: str | None = None  # Hash calculated based on the source code\n    meta_source_hash: str | None = None  # Hash of the source given in the meta, if any\n    meta: CacheMeta | None = None\n    tree: MypyFile | None = None\n    # We keep both a list and set of dependencies. A set because it makes it efficient to\n    # prevent duplicates and the list because I am afraid of changing the order of\n    # iteration over dependencies.\n    # They should be managed with add_dependency and suppress_dependency.\n    dependencies: list[str]  # Modules directly imported by the module\n    dependencies_set: set[str]  # The same but as a set for deduplication purposes\n    suppressed: list[str]  # Suppressed/missing dependencies\n    suppressed_set: set[str]  # Suppressed/missing dependencies\n    priorities: dict[str, int]\n\n    # Map each dependency to the line number where it is first imported\n    dep_line_map: dict[str, int]\n\n    # Map from dependency id to its last observed interface hash\n    dep_hashes: dict[str, bytes]\n\n    # List of errors reported for this file last time.\n    error_lines: list[ErrorTuple]\n\n    # Parent package, its parent, etc.\n    ancestors: list[str] | None = None\n\n    # List of (path, line number) tuples giving context for import\n    import_context: list[tuple[str, int]]\n\n    # If caller_state is set, the line number in the caller where the import occurred\n    caller_line = 0\n\n    # Contains a hash of the public interface in incremental mode\n    interface_hash: bytes = b\"\"\n\n    # Hash of import structure that this module depends on. It is not 1:1 with\n    # transitive dependencies set, but if two hashes are equal, transitive\n    # dependencies are guaranteed to be identical. Some expensive checks can be\n    # skipped if this value is unchanged for a module.\n    trans_dep_hash: bytes = b\"\"\n\n    # Options, specialized for this file\n    options: Options\n\n    # Whether to ignore all errors\n    ignore_all = False\n\n    # Errors reported before semantic analysis, to allow fine-grained\n    # mode to keep reporting them.\n    early_errors: list[ErrorInfo]\n\n    # Type checker used for checking this file.  Use type_checker() for\n    # access and to construct this on demand.\n    _type_checker: TypeChecker | None = None\n\n    fine_grained_deps_loaded = False\n\n    # Cumulative time spent on this file, in microseconds (for profiling stats)\n    time_spent_us: int = 0\n\n    # Per-line type-checking time (cumulative time spent type-checking expressions\n    # on a given source code line).\n    per_line_checking_time_ns: dict[int, int]\n\n    # Rough estimate of how much time it would take to process this file. Currently,\n    # we use file size as a proxy for complexity.\n    size_hint: int\n\n    # Mapping from line number to type ignore codes on this line (for imports only).\n    imports_ignored: dict[int, list[str]]\n\n    @staticmethod\n    def new_state(\n        id: str | None,\n        path: str | None,\n        source: str | None,\n        manager: BuildManager,\n        caller_state: State | None = None,\n        caller_line: int = 0,\n        ancestor_for: State | None = None,\n        root_source: bool = False,\n        # If `temporary` is True, this State is being created to just\n        # quickly parse/load the tree, without an intention to further\n        # process it. With this flag, any changes to external state as well\n        # as error reporting should be avoided.\n        temporary: bool = False,\n    ) -> State:\n        if not temporary:\n            assert id or path or source is not None, \"Neither id, path nor source given\"\n        State.order_counter += 1\n        if caller_state:\n            import_context = caller_state.import_context.copy()\n            import_context.append((caller_state.xpath, caller_line))\n        else:\n            import_context = []\n        id = id or \"__main__\"\n        options = manager.options.clone_for_module(id)\n        manager.import_options[id] = options.dep_import_options()\n\n        ignore_all = False\n        if not path and source is None:\n            assert id is not None\n            try:\n                path, follow_imports = find_module_and_diagnose(\n                    manager,\n                    id,\n                    options,\n                    caller_state,\n                    caller_line,\n                    ancestor_for,\n                    root_source,\n                    skip_diagnose=temporary,\n                )\n            except ModuleNotFound as exc:\n                if not temporary:\n                    manager.missing_modules[id] = exc.reason\n                raise\n            if follow_imports == \"silent\":\n                ignore_all = True\n        elif path and is_silent_import_module(manager, path) and not root_source:\n            ignore_all = True\n\n        meta = None\n        interface_hash = b\"\"\n        meta_source_hash = None\n        if path and source is None and manager.cache_enabled:\n            meta, error_lines = find_cache_meta(id, path, manager)\n            # TODO: Get mtime if not cached.\n            if meta is not None:\n                interface_hash = meta.interface_hash\n                meta_source_hash = meta.hash\n        if path and source is None and manager.fscache.isdir(path):\n            source = \"\"\n\n        if manager.stats_enabled:\n            t0 = time.time()\n        meta = validate_meta(meta, id, path, ignore_all, manager)\n        if manager.stats_enabled:\n            manager.add_stats(validate_meta_time=time.time() - t0)\n\n        if meta:\n            # Make copies, since we may modify these and want to\n            # compare them to the originals later.\n            dependencies = list(meta.dependencies)\n            suppressed = list(meta.suppressed)\n            all_deps = dependencies + suppressed\n            assert len(all_deps) == len(meta.dep_prios)\n            priorities = {id: pri for id, pri in zip(all_deps, meta.dep_prios)}\n            assert len(all_deps) == len(meta.dep_lines)\n            dep_line_map = {id: line for id, line in zip(all_deps, meta.dep_lines)}\n            assert len(meta.dep_hashes) == len(meta.dependencies)\n            dep_hashes = {k: v for (k, v) in zip(meta.dependencies, meta.dep_hashes)}\n            # Only copy `error_lines` if the module is not silently imported.\n            error_lines = [] if ignore_all else error_lines\n            imports_ignored = meta.imports_ignored\n        else:\n            dependencies = []\n            suppressed = []\n            priorities = {}\n            dep_line_map = {}\n            dep_hashes = {}\n            error_lines = []\n            imports_ignored = {}\n\n        state = State(\n            manager=manager,\n            order=State.order_counter,\n            id=id,\n            path=path,\n            source=source,\n            options=options,\n            ignore_all=ignore_all,\n            caller_line=caller_line,\n            import_context=import_context,\n            meta=meta,\n            interface_hash=interface_hash,\n            meta_source_hash=meta_source_hash,\n            dependencies=dependencies,\n            suppressed=suppressed,\n            priorities=priorities,\n            dep_line_map=dep_line_map,\n            dep_hashes=dep_hashes,\n            error_lines=error_lines,\n            imports_ignored=imports_ignored,\n        )\n\n        if meta:\n            if temporary:\n                state.load_tree(temporary=True)\n            if not manager.use_fine_grained_cache():\n                # Special case: if there were a previously missing package imported here,\n                # and it is not present, then we need to re-calculate dependencies.\n                # This is to support patterns like this:\n                #     from missing_package import missing_module  # type: ignore\n                # At first mypy doesn't know that `missing_module` is a module\n                # (it may be a variable, a class, or a function), so it is not added to\n                # suppressed dependencies. Therefore, when the package with module is added,\n                # we need to re-calculate dependencies.\n                # NOTE: see comment below for why we skip this in fine-grained mode.\n                if exist_added_packages(suppressed, manager):\n                    state.parse_file()  # This is safe because the cache is anyway stale.\n                    state.compute_dependencies()\n                # This is an inverse to the situation above. If we had an import like this:\n                #     from pkg import mod\n                # and then mod was deleted, we need to force recompute dependencies, to\n                # decide whether we should still depend on a missing pkg.mod. Otherwise,\n                # the above import is indistinguishable from something like this:\n                #     import pkg\n                #     import pkg.mod\n                if exist_removed_submodules(dependencies, manager):\n                    state.parse_file()  # Same as above, the current state is stale anyway.\n                    state.compute_dependencies()\n            state.size_hint = meta.size\n        else:\n            # When doing a fine-grained cache load, pretend we only\n            # know about modules that have cache information and defer\n            # handling new modules until the fine-grained update.\n            if manager.use_fine_grained_cache():\n                manager.log(f\"Deferring module to fine-grained update {path} ({id})\")\n                raise ModuleNotFound\n\n            # Parse the file (and then some) to get the dependencies.\n            state.parse_file(temporary=temporary)\n            state.compute_dependencies()\n            if manager.workers and state.tree:\n                # We don't need imports in coordinator process anymore, we parse only to\n                # compute dependencies.\n                state.tree.imports = []\n                del manager.ast_cache[id]\n\n        return state\n\n    def __init__(\n        self,\n        manager: BuildManager,\n        order: int,\n        id: str,\n        path: str | None,\n        source: str | None,\n        options: Options,\n        ignore_all: bool,\n        caller_line: int,\n        import_context: list[tuple[str, int]],\n        meta: CacheMeta | None,\n        interface_hash: bytes,\n        meta_source_hash: str | None,\n        dependencies: list[str],\n        suppressed: list[str],\n        priorities: dict[str, int],\n        dep_line_map: dict[str, int],\n        dep_hashes: dict[str, bytes],\n        error_lines: list[ErrorTuple],\n        imports_ignored: dict[int, list[str]],\n        size_hint: int = 0,\n    ) -> None:\n        self.manager = manager\n        self.order = order\n        self.id = id\n        self.path = path\n        if path:\n            # Avoid calling os.abspath, since it makes a getcwd() syscall, which is slow\n            if os.path.isabs(path):\n                self.abspath = path\n            else:\n                self.abspath = os.path.normpath(os_path_join(manager.cwd, path))\n        self.xpath = path or \"<string>\"\n        self.source = source\n        self.options = options\n        self.ignore_all = ignore_all\n        self.caller_line = caller_line\n        self.import_context = import_context\n        self.meta = meta\n        self.interface_hash = interface_hash\n        self.meta_source_hash = meta_source_hash\n        self.dependencies = dependencies\n        self.suppressed = suppressed\n        self.dependencies_set = set(dependencies)\n        self.suppressed_set = set(suppressed)\n        self.priorities = priorities\n        self.dep_line_map = dep_line_map\n        self.dep_hashes = dep_hashes\n        self.error_lines = error_lines\n        self.per_line_checking_time_ns = collections.defaultdict(int)\n        self.early_errors = []\n        self._type_checker = None\n        self.add_ancestors()\n        self.imports_ignored = imports_ignored\n        self.size_hint = size_hint\n        # Pre-computed opaque value of suppressed_deps_opts() used\n        # to minimize amount of data sent to parallel workers.\n        self.known_suppressed_deps_opts: bytes | None = None\n\n    def write(self, buf: WriteBuffer) -> None:\n        \"\"\"Serialize State for sending to build worker.\n\n        Note that unlike write() methods for most other classes, this one is\n        not idempotent. We erase some bulky values that should either be not needed\n        for processing by the worker, or can be re-created from other data relatively\n        quickly. These are:\n          * self.meta: workers will call self.reload_meta() anyway.\n          * self.options: can be restored with Options.clone_for_module().\n          * self.error_lines: fresh errors are handled by the coordinator.\n        \"\"\"\n        write_int(buf, self.order)\n        write_str(buf, self.id)\n        write_str_opt(buf, self.path)\n        write_str_opt(buf, self.source)  # mostly for mypy -c '<some code>'\n        write_bool(buf, self.ignore_all)\n        write_int(buf, self.caller_line)\n        write_tag(buf, LIST_GEN)\n        write_int_bare(buf, len(self.import_context))\n        for path, line in self.import_context:\n            write_str(buf, path)\n            write_int(buf, line)\n        write_bytes(buf, self.interface_hash)\n        write_str_opt(buf, self.meta_source_hash)\n        write_str_list(buf, self.dependencies)\n        write_str_list(buf, self.suppressed)\n        # TODO: we can possibly serialize these dictionaries in a more compact way.\n        # Most keys in the dictionaries should be the same, so we can write them once.\n        write_tag(buf, DICT_STR_GEN)\n        write_int_bare(buf, len(self.priorities))\n        for mod_id, prio in self.priorities.items():\n            write_str_bare(buf, mod_id)\n            write_int(buf, prio)\n        write_tag(buf, DICT_STR_GEN)\n        write_int_bare(buf, len(self.dep_line_map))\n        for mod_id, line in self.dep_line_map.items():\n            write_str_bare(buf, mod_id)\n            write_int(buf, line)\n        write_tag(buf, DICT_STR_GEN)\n        write_int_bare(buf, len(self.dep_hashes))\n        for mod_id, dep_hash in self.dep_hashes.items():\n            write_str_bare(buf, mod_id)\n            write_bytes(buf, dep_hash)\n        write_int(buf, self.size_hint)\n\n    @classmethod\n    def read(cls, buf: ReadBuffer, manager: BuildManager) -> State:\n        order = read_int(buf)\n        id = read_str(buf)\n        path = read_str_opt(buf)\n        source = read_str_opt(buf)\n        ignore_all = read_bool(buf)\n        caller_line = read_int(buf)\n        assert read_tag(buf) == LIST_GEN\n        import_context = [(read_str(buf), read_int(buf)) for _ in range(read_int_bare(buf))]\n        interface_hash = read_bytes(buf)\n        meta_source_hash = read_str_opt(buf)\n        dependencies = read_str_list(buf)\n        suppressed = read_str_list(buf)\n        assert read_tag(buf) == DICT_STR_GEN\n        priorities = {read_str_bare(buf): read_int(buf) for _ in range(read_int_bare(buf))}\n        assert read_tag(buf) == DICT_STR_GEN\n        dep_line_map = {read_str_bare(buf): read_int(buf) for _ in range(read_int_bare(buf))}\n        assert read_tag(buf) == DICT_STR_GEN\n        dep_hashes = {read_str_bare(buf): read_bytes(buf) for _ in range(read_int_bare(buf))}\n        return cls(\n            manager=manager,\n            order=order,\n            id=id,\n            path=path,\n            source=source,\n            # The caller must call clone_for_module().\n            options=manager.options,\n            ignore_all=ignore_all,\n            caller_line=caller_line,\n            import_context=import_context,\n            meta=None,\n            interface_hash=interface_hash,\n            meta_source_hash=meta_source_hash,\n            dependencies=dependencies,\n            suppressed=suppressed,\n            priorities=priorities,\n            dep_line_map=dep_line_map,\n            dep_hashes=dep_hashes,\n            error_lines=[],\n            imports_ignored={},\n            size_hint=read_int(buf),\n        )\n\n    def reload_meta(self) -> None:\n        \"\"\"Force reload of cache meta.\n\n        This is used by parallel checking workers to update shared information\n        that may have changed after initial graph loading. Currently, this is only\n        the interface hash.\n        \"\"\"\n        assert self.path is not None\n        self.meta, _ = find_cache_meta(self.id, self.path, self.manager, skip_validation=True)\n        assert self.meta is not None\n        self.interface_hash = self.meta.interface_hash\n\n    def add_ancestors(self) -> None:\n        if self.path is not None:\n            _, name = os.path.split(self.path)\n            base, _ = os.path.splitext(name)\n            if \".\" in base:\n                # This is just a weird filename, don't add anything\n                self.ancestors = []\n                return\n        # All parent packages are new ancestors.\n        ancestors = []\n        parent = self.id\n        while \".\" in parent:\n            parent, _ = parent.rsplit(\".\", 1)\n            ancestors.append(parent)\n        self.ancestors = ancestors\n\n    def is_fresh(self) -> bool:\n        \"\"\"Return whether the cache data for this file is fresh.\"\"\"\n        # NOTE: self.dependencies may differ from\n        # self.meta.dependencies when a dependency is dropped due to\n        # suppression by silent mode.  However, when a suppressed\n        # dependency is added back we find out later in the process.\n        # Additionally, we need to verify that import following options are\n        # same for suppressed dependencies, even if the first check is OK.\n        return (\n            self.meta is not None\n            and self.dependencies == self.meta.dependencies\n            and (\n                self.options.fine_grained_incremental\n                or self.meta.suppressed_deps_opts == self.suppressed_deps_opts()\n            )\n        )\n\n    def mark_as_rechecked(self) -> None:\n        \"\"\"Marks this module as having been fully re-analyzed by the type-checker.\"\"\"\n        self.manager.rechecked_modules.add(self.id)\n\n    def mark_interface_stale(self) -> None:\n        \"\"\"Marks this module as having a stale public interface, and discards the cache data.\"\"\"\n        self.manager.stale_modules.add(self.id)\n\n    def check_blockers(self) -> None:\n        \"\"\"Raise CompileError if a blocking error is detected.\"\"\"\n        if self.manager.errors.is_blockers():\n            self.manager.log(\"Bailing due to blocking errors\")\n            self.manager.errors.raise_error()\n\n    @contextlib.contextmanager\n    def wrap_context(self, check_blockers: bool = True) -> Iterator[None]:\n        \"\"\"Temporarily change the error import context to match this state.\n\n        Also report an internal error if an unexpected exception was raised\n        and raise an exception on a blocking error, unless\n        check_blockers is False. Skipping blocking error reporting is used\n        in the semantic analyzer so that we can report all blocking errors\n        for a file (across multiple targets) to maintain backward\n        compatibility.\n        \"\"\"\n        save_import_context = self.manager.errors.import_context()\n        self.manager.errors.set_import_context(self.import_context)\n        try:\n            yield\n        except CompileError:\n            raise\n        except Exception as err:\n            report_internal_error(\n                err,\n                self.path,\n                0,\n                self.manager.errors,\n                self.options,\n                self.manager.stdout,\n                self.manager.stderr,\n            )\n        self.manager.errors.set_import_context(save_import_context)\n        # TODO: Move this away once we've removed the old semantic analyzer?\n        if check_blockers:\n            self.check_blockers()\n\n    def load_fine_grained_deps(self) -> dict[str, set[str]]:\n        return self.manager.load_fine_grained_deps(self.id)\n\n    def load_tree(self, temporary: bool = False) -> None:\n        if self.manager.parallel_worker:\n            assert self.path is not None\n            _, data_file, _ = get_cache_names(self.id, self.path, self.manager.options)\n        else:\n            assert (\n                self.meta is not None\n            ), \"Internal error: this method must be called only for cached modules\"\n            data_file = self.meta.data_file\n\n        data: bytes | dict[str, Any] | None\n        if self.options.fixed_format_cache:\n            data = _load_ff_file(data_file, self.manager, \"Could not load tree: \", None)\n        else:\n            data = _load_json_file(data_file, self.manager, \"Load tree \", \"Could not load tree: \")\n        if data is None:\n            return\n\n        t0 = time.time()\n        # TODO: Assert data file wasn't changed.\n        if isinstance(data, bytes):\n            data_io = ReadBuffer(data)\n            self.tree = MypyFile.read(data_io)\n        else:\n            self.tree = MypyFile.deserialize(data)\n        t1 = time.time()\n        self.manager.add_stats(deserialize_time=t1 - t0)\n        if not temporary:\n            self.manager.modules[self.id] = self.tree\n            self.manager.add_stats(fresh_trees=1)\n\n    def fix_cross_refs(self) -> None:\n        assert self.tree is not None, \"Internal error: method must be called on parsed file only\"\n        # We need to set allow_missing when doing a fine-grained cache\n        # load because we need to gracefully handle missing modules.\n        fixup_module(self.tree, self.manager.modules, self.options.use_fine_grained_cache)\n\n    # Methods for processing modules from source code.\n\n    def parse_file(self, *, temporary: bool = False, raw_data: FileRawData | None = None) -> None:\n        \"\"\"Parse file and run first pass of semantic analysis.\n\n        Everything done here is local to the file. Don't depend on imported\n        modules in any way. Also record module dependencies based on imports.\n        \"\"\"\n        if self.tree is not None:\n            # The file was already parsed (in __init__()).\n            return\n\n        manager = self.manager\n\n        # Can we reuse a previously parsed AST? This avoids redundant work in daemon.\n        cached = self.id in manager.ast_cache\n        modules = manager.modules\n        if not cached:\n            manager.log(f\"Parsing {self.xpath} ({self.id})\")\n        else:\n            manager.log(f\"Using cached AST for {self.xpath} ({self.id})\")\n\n        t0 = time_ref()\n\n        with self.wrap_context():\n            source = self.source\n            if self.path and source is None:\n                try:\n                    path = manager.maybe_swap_for_shadow_path(self.path)\n                    source = decode_python_encoding(manager.fscache.read(path))\n                    self.source_hash = manager.fscache.hash_digest(path)\n                except OSError as ioerr:\n                    # ioerr.strerror differs for os.stat failures between Windows and\n                    # other systems, but os.strerror(ioerr.errno) does not, so we use that.\n                    # (We want the error messages to be platform-independent so that the\n                    # tests have predictable output.)\n                    assert ioerr.errno is not None\n                    raise CompileError(\n                        [\n                            \"mypy: error: cannot read file '{}': {}\".format(\n                                self.path.replace(os.getcwd() + os.sep, \"\"),\n                                os.strerror(ioerr.errno),\n                            )\n                        ],\n                        module_with_blocker=self.id,\n                    ) from ioerr\n                except (UnicodeDecodeError, DecodeError) as decodeerr:\n                    if self.path.endswith(\".pyd\"):\n                        err = f\"{self.path}: error: stubgen does not support .pyd files\"\n                    else:\n                        err = f\"{self.path}: error: cannot decode file: {str(decodeerr)}\"\n                    raise CompileError([err], module_with_blocker=self.id) from decodeerr\n            elif self.path and self.manager.fscache.isdir(self.path):\n                source = \"\"\n                self.source_hash = \"\"\n            else:\n                assert source is not None\n                self.source_hash = compute_hash(source)\n\n            self.parse_inline_configuration(source)\n            self.check_for_invalid_options()\n\n            self.size_hint = len(source)\n            if not cached:\n                ignore_errors = self.ignore_all or self.options.ignore_errors\n                self.tree = manager.parse_file(\n                    self.id,\n                    self.xpath,\n                    source,\n                    ignore_errors=ignore_errors,\n                    options=self.options,\n                    raw_data=raw_data,\n                )\n            else:\n                # Reuse a cached AST\n                self.tree = manager.ast_cache[self.id][0]\n\n        self.time_spent_us += time_spent_us(t0)\n\n        if not cached:\n            # Make a copy of any errors produced during parse time so that\n            # fine-grained mode can repeat them when the module is\n            # reprocessed.\n            self.early_errors = list(manager.errors.error_info_map.get(self.xpath, []))\n            self.semantic_analysis_pass1()\n        else:\n            self.early_errors = manager.ast_cache[self.id][1]\n\n        if not temporary:\n            modules[self.id] = self.tree\n            self.check_blockers()\n\n        manager.ast_cache[self.id] = (self.tree, self.early_errors)\n        self.setup_errors()\n\n    def setup_errors(self) -> None:\n        assert self.tree is not None\n        self.manager.errors.set_file_ignored_lines(\n            self.xpath, self.tree.ignored_lines, self.ignore_all or self.options.ignore_errors\n        )\n        self.manager.errors.set_skipped_lines(self.xpath, self.tree.skipped_lines)\n\n    def parse_inline_configuration(self, source: str) -> None:\n        \"\"\"Check for inline mypy: options directive and parse them.\"\"\"\n        flags = get_mypy_comments(source)\n        if flags:\n            changes, config_errors = parse_mypy_comments(flags, self.options)\n            self.options = self.options.apply_changes(changes)\n            self.manager.errors.set_file(self.xpath, self.id, self.options)\n            for lineno, error in config_errors:\n                self.manager.error(lineno, error)\n\n    def check_for_invalid_options(self) -> None:\n        if self.options.mypyc and not self.options.strict_bytes:\n            self.manager.errors.set_file(self.xpath, self.id, options=self.options)\n            self.manager.error(\n                None, \"Option --strict-bytes cannot be disabled when using mypyc\", blocker=True\n            )\n\n    def semantic_analysis_pass1(self) -> None:\n        \"\"\"Perform pass 1 of semantic analysis, which happens immediately after parsing.\n\n        This pass can't assume that any other modules have been processed yet.\n        \"\"\"\n        options = self.options\n        assert self.tree is not None\n\n        t0 = time_ref()\n\n        # Do the first pass of semantic analysis: analyze the reachability\n        # of blocks and import statements. We must do this before\n        # processing imports, since this may mark some import statements as\n        # unreachable.\n        #\n        # TODO: This should not be considered as a semantic analysis\n        #     pass -- it's an independent pass.\n        if not options.native_parser:\n            analyzer = SemanticAnalyzerPreAnalysis()\n            with self.wrap_context():\n                analyzer.visit_file(self.tree, self.xpath, self.id, options)\n        # TODO: Do this while constructing the AST?\n        self.tree.names = SymbolTable()\n        if not self.tree.is_stub:\n            if not self.options.allow_redefinition_new:\n                # Perform some low-key variable renaming when assignments can't\n                # widen inferred types\n                self.tree.accept(LimitedVariableRenameVisitor())\n            if options.allow_redefinition_old:\n                # Perform more renaming across the AST to allow variable redefinitions\n                self.tree.accept(VariableRenameVisitor())\n        self.time_spent_us += time_spent_us(t0)\n\n    def add_dependency(self, dep: str) -> None:\n        if dep not in self.dependencies_set:\n            self.dependencies.append(dep)\n            self.dependencies_set.add(dep)\n        if dep in self.suppressed_set:\n            self.suppressed.remove(dep)\n            self.suppressed_set.remove(dep)\n\n    def suppress_dependency(self, dep: str) -> None:\n        if dep in self.dependencies_set:\n            self.dependencies.remove(dep)\n            self.dependencies_set.remove(dep)\n        if dep not in self.suppressed_set:\n            self.suppressed.append(dep)\n            self.suppressed_set.add(dep)\n\n    def compute_dependencies(self) -> None:\n        \"\"\"Compute a module's dependencies after parsing it.\n\n        This is used when we parse a file that we didn't have\n        up-to-date cache information for. When we have an up-to-date\n        cache, we just use the cached info.\n        \"\"\"\n        manager = self.manager\n        assert self.tree is not None\n\n        # Compute (direct) dependencies.\n        # Add all direct imports (this is why we needed the first pass).\n        # Also keep track of each dependency's source line.\n        # Missing dependencies will be moved from dependencies to\n        # suppressed when they fail to be loaded in load_graph.\n\n        self.dependencies = []\n        self.dependencies_set = set()\n        self.suppressed = []\n        self.suppressed_set = set()\n        self.priorities = {}  # id -> priority\n        self.dep_line_map = {}  # id -> line\n        self.dep_hashes = {}\n        dep_entries = manager.all_imported_modules_in_file(\n            self.tree\n        ) + self.manager.plugin.get_additional_deps(self.tree)\n        for pri, id, line in dep_entries:\n            self.priorities[id] = min(pri, self.priorities.get(id, PRI_ALL))\n            if id == self.id:\n                continue\n            self.add_dependency(id)\n            if id not in self.dep_line_map:\n                self.dep_line_map[id] = line\n        import_lines = self.dep_line_map.values()\n        self.imports_ignored = {\n            line: codes for line, codes in self.tree.ignored_lines.items() if line in import_lines\n        }\n        # Every module implicitly depends on builtins.\n        if self.id != \"builtins\":\n            self.add_dependency(\"builtins\")\n        if self.tree.uses_template_strings:\n            self.add_dependency(\"string.templatelib\")\n\n        self.check_blockers()  # Can fail due to bogus relative imports\n\n    def type_check_first_pass(self) -> None:\n        if self.options.semantic_analysis_only:\n            return\n        t0 = time_ref()\n        with self.wrap_context():\n            self.type_checker().check_first_pass()\n        self.time_spent_us += time_spent_us(t0)\n\n    def type_checker(self) -> TypeChecker:\n        if not self._type_checker:\n            assert self.tree is not None, \"Internal error: must be called on parsed file only\"\n            manager = self.manager\n            self._type_checker = TypeChecker(\n                manager.errors,\n                manager.modules,\n                self.options,\n                self.tree,\n                self.xpath,\n                manager.plugin,\n                self.per_line_checking_time_ns,\n            )\n        return self._type_checker\n\n    def type_map(self) -> dict[Expression, Type]:\n        # We can extract the master type map directly since at this\n        # point no temporary type maps can be active.\n        assert len(self.type_checker()._type_maps) == 1\n        return self.type_checker()._type_maps[0]\n\n    def type_check_second_pass(self) -> bool:\n        if self.options.semantic_analysis_only:\n            return False\n        t0 = time_ref()\n        with self.wrap_context():\n            result = self.type_checker().check_second_pass()\n        self.time_spent_us += time_spent_us(t0)\n        return result\n\n    def detect_possibly_undefined_vars(self) -> None:\n        assert self.tree is not None, \"Internal error: method must be called on parsed file only\"\n        if self.tree.is_stub:\n            # We skip stub files because they aren't actually executed.\n            return\n        manager = self.manager\n        manager.errors.set_file(self.xpath, self.tree.fullname, options=self.options)\n        if manager.errors.is_error_code_enabled(\n            codes.POSSIBLY_UNDEFINED\n        ) or manager.errors.is_error_code_enabled(codes.USED_BEFORE_DEF):\n            self.tree.accept(\n                PossiblyUndefinedVariableVisitor(\n                    MessageBuilder(manager.errors, manager.modules),\n                    self.type_map(),\n                    self.options,\n                    self.tree.names,\n                )\n            )\n\n    def finish_passes(self) -> None:\n        assert self.tree is not None, \"Internal error: method must be called on parsed file only\"\n        manager = self.manager\n        if self.options.semantic_analysis_only:\n            return\n        t0 = time_ref()\n        with self.wrap_context():\n            # Some tests (and tools) want to look at the set of all types.\n            options = manager.options\n            if options.export_types:\n                manager.all_types.update(self.type_map())\n\n            # We should always patch indirect dependencies, even in full (non-incremental) builds,\n            # because the cache still may be written, and it must be correct.\n            self.patch_indirect_dependencies(\n                # Two possible sources of indirect dependencies:\n                # * Symbols not directly imported in this module but accessed via an attribute\n                #   or via a re-export (vast majority of these recorded in semantic analysis).\n                # * For each expression type we need to record definitions of type components\n                #   since \"meaning\" of the type may be updated when definitions are updated.\n                self.tree.module_refs | self.type_checker().module_refs,\n                set(self.type_map().values()),\n            )\n\n            if self.options.dump_inference_stats:\n                dump_type_stats(\n                    self.tree,\n                    self.xpath,\n                    modules=self.manager.modules,\n                    inferred=True,\n                    typemap=self.type_map(),\n                )\n            manager.report_file(self.tree, self.type_map(), self.options)\n\n            self.update_fine_grained_deps(self.manager.fg_deps)\n\n            if manager.options.export_ref_info:\n                write_undocumented_ref_info(\n                    self, manager.metastore, manager.options, self.type_map()\n                )\n\n            self.free_state()\n            if not manager.options.fine_grained_incremental and not manager.options.preserve_asts:\n                free_tree(self.tree)\n                self.tree.defs.clear()\n        self.time_spent_us += time_spent_us(t0)\n\n    def free_state(self) -> None:\n        if self._type_checker:\n            self._type_checker.reset()\n            self._type_checker = None\n\n    def patch_indirect_dependencies(self, module_refs: set[str], types: set[Type]) -> None:\n        assert self.ancestors is not None\n        existing_deps = set(self.dependencies + self.suppressed + self.ancestors)\n        existing_deps.add(self.id)\n\n        encountered = self.manager.indirection_detector.find_modules(types) | module_refs\n        for dep in sorted(encountered - existing_deps):\n            if dep not in self.manager.modules:\n                continue\n            self.add_dependency(dep)\n            self.priorities[dep] = PRI_INDIRECT\n\n    def compute_fine_grained_deps(self) -> dict[str, set[str]]:\n        assert self.tree is not None\n        if self.id in (\"builtins\", \"typing\", \"types\", \"sys\", \"_typeshed\"):\n            # We don't track changes to core parts of typeshed -- the\n            # assumption is that they are only changed as part of mypy\n            # updates, which will invalidate everything anyway. These\n            # will always be processed in the initial non-fine-grained\n            # build. Other modules may be brought in as a result of an\n            # fine-grained increment, and we may need these\n            # dependencies then to handle cyclic imports.\n            return {}\n        from mypy.server.deps import get_dependencies  # Lazy import to speed up startup\n\n        return get_dependencies(\n            target=self.tree,\n            type_map=self.type_map(),\n            python_version=self.options.python_version,\n            options=self.manager.options,\n        )\n\n    def update_fine_grained_deps(self, deps: dict[str, set[str]]) -> None:\n        options = self.manager.options\n        if options.cache_fine_grained or options.fine_grained_incremental:\n            from mypy.server.deps import merge_dependencies  # Lazy import to speed up startup\n\n            merge_dependencies(self.compute_fine_grained_deps(), deps)\n            type_state.update_protocol_deps(deps)\n\n    def suppressed_deps_opts(self) -> bytes:\n        if not self.suppressed:\n            return b\"\"\n        if self.known_suppressed_deps_opts:\n            return self.known_suppressed_deps_opts\n        buf = WriteBuffer()\n        import_options = self.manager.import_options\n        for dep in sorted(self.suppressed):\n            # Using .get() is a bit defensive, but just in case we have a bug elsewhere\n            # (e.g. in the daemon), it is better to get a stale cache than a crash.\n            reason = self.manager.missing_modules.get(dep, SuppressionReason.NOT_FOUND)\n            if self.priorities.get(dep) != PRI_INDIRECT:\n                write_str_bare(buf, dep)\n                write_bytes_bare(buf, import_options[dep])\n                write_int_bare(buf, reason)\n        return buf.getvalue()\n\n    def write_cache(self) -> tuple[CacheMeta, str] | None:\n        assert self.tree is not None, \"Internal error: method must be called on parsed file only\"\n        # We don't support writing cache files in fine-grained incremental mode.\n        if (\n            not self.path\n            or self.options.cache_dir == os.devnull\n            or self.options.fine_grained_incremental\n        ):\n            if self.options.debug_serialize:\n                try:\n                    if self.manager.options.fixed_format_cache:\n                        data = WriteBuffer()\n                        self.tree.write(data)\n                    else:\n                        self.tree.serialize()\n                except Exception:\n                    print(f\"Error serializing {self.id}\", file=self.manager.stdout)\n                    raise  # Propagate to display traceback\n            return None\n        dep_prios = self.dependency_priorities()\n        dep_lines = self.dependency_lines()\n        assert self.source_hash is not None\n        assert len(set(self.dependencies)) == len(\n            self.dependencies\n        ), f\"Duplicates in dependencies list for {self.id} ({self.dependencies})\"\n        new_interface_hash, meta_tuple = write_cache(\n            self.id,\n            self.path,\n            self.tree,\n            list(self.dependencies),\n            list(self.suppressed),\n            self.suppressed_deps_opts(),\n            self.imports_ignored,\n            dep_prios,\n            dep_lines,\n            self.interface_hash,\n            self.trans_dep_hash,\n            self.source_hash,\n            self.ignore_all,\n            self.manager,\n        )\n        if new_interface_hash == self.interface_hash:\n            self.manager.log(f\"Cached module {self.id} has same interface\")\n        else:\n            self.manager.log(f\"Cached module {self.id} has changed interface\")\n            self.mark_interface_stale()\n            self.interface_hash = new_interface_hash\n        return meta_tuple\n\n    def verify_dependencies(self, suppressed_only: bool = False) -> None:\n        \"\"\"Report errors for import targets in modules that don't exist.\n\n        If suppressed_only is set, only check suppressed dependencies.\n        \"\"\"\n        manager = self.manager\n        assert self.ancestors is not None\n        # Strip out indirect dependencies. See comment in build.load_graph().\n        if suppressed_only:\n            all_deps = [dep for dep in self.suppressed if self.priorities.get(dep) != PRI_INDIRECT]\n        else:\n            dependencies = [\n                dep\n                for dep in self.dependencies + self.suppressed\n                if self.priorities.get(dep) != PRI_INDIRECT\n            ]\n            all_deps = dependencies + self.ancestors\n        for dep in all_deps:\n            if dep in manager.modules:\n                continue\n            options = manager.options.clone_for_module(dep)\n            if options.ignore_missing_imports:\n                continue\n            line = self.dep_line_map.get(dep, 1)\n            try:\n                if dep in self.ancestors:\n                    state: State | None = None\n                    ancestor: State | None = self\n                else:\n                    state, ancestor = self, None\n                # Called just for its side effects of producing diagnostics.\n                find_module_and_diagnose(\n                    manager,\n                    dep,\n                    options,\n                    caller_state=state,\n                    caller_line=line,\n                    ancestor_for=ancestor,\n                )\n            except (ModuleNotFound, CompileError):\n                # Swallow up any ModuleNotFounds or CompilerErrors while generating\n                # a diagnostic. CompileErrors may get generated in\n                # fine-grained mode when an __init__.py is deleted, if a module\n                # that was in that package has targets reprocessed before\n                # it is renamed.\n                pass\n\n    def dependency_priorities(self) -> list[int]:\n        return [self.priorities.get(dep, PRI_HIGH) for dep in self.dependencies + self.suppressed]\n\n    def dependency_lines(self) -> list[int]:\n        return [self.dep_line_map.get(dep, 1) for dep in self.dependencies + self.suppressed]\n\n    def generate_unused_ignore_notes(self) -> None:\n        if (\n            self.options.warn_unused_ignores\n            or codes.UNUSED_IGNORE in self.options.enabled_error_codes\n        ) and codes.UNUSED_IGNORE not in self.options.disabled_error_codes:\n            # We only need this for the daemon, regular incremental does this unconditionally.\n            if self.meta and self.options.fine_grained_incremental:\n                self.verify_dependencies(suppressed_only=True)\n            is_typeshed = self.tree is not None and self.tree.is_typeshed_file(self.options)\n            self.manager.errors.generate_unused_ignore_errors(self.xpath, is_typeshed)\n\n    def generate_ignore_without_code_notes(self) -> None:\n        if self.manager.errors.is_error_code_enabled(codes.IGNORE_WITHOUT_CODE):\n            is_typeshed = self.tree is not None and self.tree.is_typeshed_file(self.options)\n            self.manager.errors.generate_ignore_without_code_errors(\n                self.xpath, self.options.warn_unused_ignores, is_typeshed\n            )\n\n\n# Module import and diagnostic glue\n\n\ndef find_module_and_diagnose(\n    manager: BuildManager,\n    id: str,\n    options: Options,\n    caller_state: State | None = None,\n    caller_line: int = 0,\n    ancestor_for: State | None = None,\n    root_source: bool = False,\n    skip_diagnose: bool = False,\n) -> tuple[str, str]:\n    \"\"\"Find a module by name, respecting follow_imports and producing diagnostics.\n\n    If the module is not found, then the ModuleNotFound exception is raised.\n\n    Args:\n      id: module to find\n      options: the options for the module being loaded\n      caller_state: the state of the importing module, if applicable\n      caller_line: the line number of the import\n      ancestor_for: the child module this is an ancestor of, if applicable\n      root_source: whether this source was specified on the command line\n      skip_diagnose: skip any error diagnosis and reporting (but ModuleNotFound is\n          still raised if the module is missing)\n\n    The specified value of follow_imports for a module can be overridden\n    if the module is specified on the command line or if it is a stub,\n    so we compute and return the \"effective\" follow_imports of the module.\n\n    Returns a tuple containing (file path, target's effective follow_imports setting)\n    \"\"\"\n    result = find_module_with_reason(id, manager)\n    if isinstance(result, str):\n        # For non-stubs, look at options.follow_imports:\n        # - normal (default) -> fully analyze\n        # - silent -> analyze but silence errors\n        # - skip -> don't analyze, make the type Any\n        follow_imports = options.follow_imports\n        if (\n            root_source  # Honor top-level modules\n            or (\n                result.endswith(\".pyi\")  # Stubs are always normal\n                and not options.follow_imports_for_stubs  # except when they aren't\n            )\n            or id in CORE_BUILTIN_MODULES  # core is always normal\n        ):\n            follow_imports = \"normal\"\n        if skip_diagnose:\n            pass\n        elif follow_imports == \"silent\":\n            # Still import it, but silence non-blocker errors.\n            manager.log(f\"Silencing {result} ({id})\")\n        elif follow_imports == \"skip\" or follow_imports == \"error\":\n            # In 'error' mode, produce special error messages.\n            if id not in manager.missing_modules:\n                manager.log(f\"Skipping {result} ({id})\")\n            if follow_imports == \"error\":\n                if ancestor_for:\n                    skipping_ancestor(manager, id, result, ancestor_for)\n                else:\n                    skipping_module(manager, caller_line, caller_state, id, result)\n            reason = SuppressionReason.SKIPPED\n            if options.ignore_missing_imports:\n                # Performance optimization: when we are ignoring imports, there is no\n                # difference for the caller between skipped import and actually missing one.\n                reason = SuppressionReason.NOT_FOUND\n            raise ModuleNotFound(reason=reason)\n        if is_silent_import_module(manager, result) and not root_source:\n            follow_imports = \"silent\"\n        return result, follow_imports\n    else:\n        # Could not find a module.  Typically, the reason is a\n        # misspelled module name, missing stub, module not in\n        # search path or the module has not been installed.\n\n        ignore_missing_imports = options.ignore_missing_imports\n\n        # Don't honor a global (not per-module) ignore_missing_imports\n        # setting for modules that used to have bundled stubs, as\n        # otherwise updating mypy can silently result in new false\n        # negatives. (Unless there are stubs, but they are incomplete.)\n        global_ignore_missing_imports = manager.options.ignore_missing_imports\n        if (\n            is_module_from_legacy_bundled_package(id)\n            and global_ignore_missing_imports\n            and not options.ignore_missing_imports_per_module\n            and result is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED\n        ):\n            ignore_missing_imports = False\n\n        if skip_diagnose:\n            raise ModuleNotFound\n        if caller_state:\n            if not (ignore_missing_imports or in_partial_package(id, manager)):\n                module_not_found(manager, caller_line, caller_state, id, result)\n            raise ModuleNotFound\n        elif root_source:\n            # If we can't find a root source it's always fatal.\n            # TODO: This might hide non-fatal errors from\n            # root sources processed earlier.\n            raise CompileError([f\"mypy: can't find module '{id}'\"])\n        else:\n            raise ModuleNotFound\n\n\ndef exist_added_packages(suppressed: list[str], manager: BuildManager) -> bool:\n    \"\"\"Find if there are any newly added packages that were previously suppressed.\n\n    Exclude everything not in build for follow-imports=skip.\n    \"\"\"\n    for dep in suppressed:\n        if dep in manager.source_set.source_modules:\n            # We don't need to add any special logic for this. If a module\n            # is added to build, importers will be invalidated by normal mechanism.\n            continue\n        path = find_module_simple(dep, manager)\n        if not path:\n            continue\n        options = manager.options.clone_for_module(dep)\n        # Technically this is not 100% correct, since we can have:\n        #     from pkg import mod\n        # with\n        #     [mypy-pkg]\n        #     follow-import = silent\n        #     [mypy-pkg.mod]\n        #     follow-imports = normal\n        # But such cases are extremely rare, and this allows us to avoid\n        # massive performance impact in much more common situations.\n        if options.follow_imports in (\"skip\", \"error\") and (\n            not path.endswith(\".pyi\") or options.follow_imports_for_stubs\n        ):\n            continue\n        if os.path.basename(path) in (\"__init__.py\", \"__init__.pyi\"):\n            return True\n    return False\n\n\ndef exist_removed_submodules(dependencies: list[str], manager: BuildManager) -> bool:\n    \"\"\"Find if there are any submodules of packages that are now missing.\n\n    This is conceptually an inverse of exist_added_packages().\n    \"\"\"\n    dependencies_set = set(dependencies)\n    for dep in dependencies:\n        if \".\" not in dep:\n            continue\n        if dep in manager.source_set.source_modules:\n            # We still know it is definitely a module.\n            continue\n        direct_ancestor, _ = dep.rsplit(\".\", maxsplit=1)\n        if direct_ancestor not in dependencies_set:\n            continue\n        if find_module_simple(dep, manager) is None:\n            return True\n    return False\n\n\ndef find_module_simple(id: str, manager: BuildManager) -> str | None:\n    \"\"\"Find a filesystem path for module `id` or `None` if not found.\"\"\"\n    if manager.stats_enabled:\n        t0 = time.time()\n    x = manager.find_module_cache.find_module(id, fast_path=True)\n    if manager.stats_enabled:\n        manager.add_stats(find_module_time=time.time() - t0, find_module_calls=1)\n    if isinstance(x, ModuleNotFoundReason):\n        return None\n    return x\n\n\ndef find_module_with_reason(id: str, manager: BuildManager) -> ModuleSearchResult:\n    \"\"\"Find a filesystem path for module `id` or the reason it can't be found.\"\"\"\n    if manager.stats_enabled:\n        t0 = time.time()\n    x = manager.find_module_cache.find_module(id, fast_path=False)\n    if manager.stats_enabled:\n        manager.add_stats(find_module_time=time.time() - t0, find_module_calls=1)\n    return x\n\n\ndef in_partial_package(id: str, manager: BuildManager) -> bool:\n    \"\"\"Check if a missing module can potentially be a part of a package.\n\n    This checks if there is any existing parent __init__.pyi stub that\n    defines a module-level __getattr__ (a.k.a. partial stub package).\n    \"\"\"\n    while \".\" in id:\n        ancestor, _ = id.rsplit(\".\", 1)\n        if ancestor in manager.known_partial_packages:\n            return manager.known_partial_packages[ancestor]\n        if ancestor in manager.modules:\n            ancestor_mod: MypyFile | None = manager.modules[ancestor]\n        else:\n            # Ancestor is not in build, try quickly if we can find it.\n            try:\n                ancestor_st = State.new_state(\n                    id=ancestor, path=None, source=None, manager=manager, temporary=True\n                )\n            except (ModuleNotFound, CompileError):\n                ancestor_mod = None\n            else:\n                ancestor_mod = ancestor_st.tree\n                # We will not need this anymore.\n                ancestor_st.tree = None\n        if ancestor_mod is not None:\n            # Bail out soon, complete subpackage found\n            manager.known_partial_packages[ancestor] = ancestor_mod.is_partial_stub_package\n            return ancestor_mod.is_partial_stub_package\n        id = ancestor\n    return False\n\n\ndef module_not_found(\n    manager: BuildManager,\n    line: int,\n    caller_state: State,\n    target: str,\n    reason: ModuleNotFoundReason,\n) -> None:\n    errors = manager.errors\n    save_import_context = errors.import_context()\n    errors.set_import_context(caller_state.import_context)\n    errors.set_file(caller_state.xpath, caller_state.id, caller_state.options)\n    errors.set_file_ignored_lines(\n        caller_state.xpath,\n        caller_state.tree.ignored_lines if caller_state.tree else caller_state.imports_ignored,\n        caller_state.ignore_all or caller_state.options.ignore_errors,\n    )\n    if target == \"builtins\":\n        manager.error(\n            line, \"Cannot find 'builtins' module. Typeshed appears broken!\", blocker=True\n        )\n        errors.raise_error()\n    else:\n        daemon = manager.options.fine_grained_incremental\n        msg, notes = reason.error_message_templates(daemon)\n        if reason == ModuleNotFoundReason.NOT_FOUND:\n            code = codes.IMPORT_NOT_FOUND\n        elif (\n            reason == ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS\n            or reason == ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED\n        ):\n            code = codes.IMPORT_UNTYPED\n        else:\n            code = codes.IMPORT\n        manager.error(line, msg.format(module=target), code=code)\n\n        dist = stub_distribution_name(target)\n        for note in notes:\n            if \"{stub_dist}\" in note:\n                assert dist is not None\n                note = note.format(stub_dist=dist)\n            manager.note(line, note, only_once=True, code=code)\n        if reason is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:\n            assert dist is not None\n            manager.missing_stub_packages.add(dist)\n    errors.set_import_context(save_import_context)\n\n\ndef skipping_module(\n    manager: BuildManager, line: int, caller_state: State | None, id: str, path: str\n) -> None:\n    \"\"\"Produce an error for an import ignored due to --follow_imports=error\"\"\"\n    assert caller_state, (id, path)\n    save_import_context = manager.errors.import_context()\n    manager.errors.set_import_context(caller_state.import_context)\n    manager.errors.set_file(caller_state.xpath, caller_state.id, manager.options)\n    manager.error(line, f'Import of \"{id}\" ignored')\n    manager.note(\n        line, \"(Using --follow-imports=error, module not passed on command line)\", only_once=True\n    )\n    manager.errors.set_import_context(save_import_context)\n\n\ndef skipping_ancestor(manager: BuildManager, id: str, path: str, ancestor_for: State) -> None:\n    \"\"\"Produce an error for an ancestor ignored due to --follow_imports=error\"\"\"\n    # TODO: Read the path (the __init__.py file) and return\n    # immediately if it's empty or only contains comments.\n    # But beware, some package may be the ancestor of many modules,\n    # so we'd need to cache the decision.\n    manager.errors.set_import_context([])\n    manager.errors.set_file(ancestor_for.xpath, ancestor_for.id, manager.options)\n    manager.error(None, f'Ancestor package \"{id}\" ignored', only_once=True)\n    manager.note(\n        None, \"(Using --follow-imports=error, submodule passed on command line)\", only_once=True\n    )\n\n\ndef log_configuration(manager: BuildManager, sources: list[BuildSource]) -> None:\n    \"\"\"Output useful configuration information to LOG and TRACE\"\"\"\n\n    if not manager.logging_enabled:\n        return\n\n    config_file = manager.options.config_file\n    if config_file:\n        config_file = os.path.abspath(config_file)\n\n    manager.log()\n    configuration_vars = [\n        (\"Mypy Version\", __version__),\n        (\"Config File\", (config_file or \"Default\")),\n        (\"Configured Executable\", manager.options.python_executable or \"None\"),\n        (\"Current Executable\", sys.executable),\n        (\"Cache Dir\", manager.options.cache_dir),\n        (\"Compiled\", str(not __file__.endswith(\".py\"))),\n        (\"Exclude\", manager.options.exclude),\n    ]\n\n    for conf_name, conf_value in configuration_vars:\n        manager.log(f\"{conf_name + ':':24}{conf_value}\")\n\n    for source in sources:\n        manager.log(f\"{'Found source:':24}{source}\")\n\n    # Complete list of searched paths can get very long, put them under TRACE\n    for path_type, paths in manager.search_paths.asdict().items():\n        if not paths:\n            manager.trace(f\"No {path_type}\")\n            continue\n\n        manager.trace(f\"{path_type}:\")\n\n        for pth in paths:\n            manager.trace(f\"    {pth}\")\n\n\n# The driver\n\n\ndef dispatch(sources: list[BuildSource], manager: BuildManager, stdout: TextIO) -> Graph:\n    log_configuration(manager, sources)\n\n    t0 = time.time()\n\n    # We disable GC while loading the graph as a performance optimization for\n    # cold-cache runs. The parsed ASTs are trees, and therefore should not have any\n    # reference cycles. This is an important optimization, since we create a lot of\n    # new objects while parsing files.\n    global initial_gc_freeze_done\n    if (\n        not manager.options.test_env\n        and platform.python_implementation() == \"CPython\"\n        and not initial_gc_freeze_done\n    ):\n        gc.disable()\n    graph = load_graph(sources, manager)\n\n    # This is a kind of unfortunate hack to work around some of fine-grained's\n    # fragility: if we have loaded less than 50% of the specified files from\n    # cache in fine-grained cache mode, load the graph again honestly.\n    # In this case, we just turn the cache off entirely, so we don't need\n    # to worry about some files being loaded and some from cache and so\n    # that fine-grained mode never *writes* to the cache.\n    if manager.use_fine_grained_cache() and len(graph) < 0.50 * len(sources):\n        manager.log(\"Redoing load_graph without cache because too much was missing\")\n        manager.cache_enabled = False\n        graph = load_graph(sources, manager)\n\n    if (\n        not manager.options.test_env\n        and platform.python_implementation() == \"CPython\"\n        and not initial_gc_freeze_done\n    ):\n        gc.freeze()\n        gc.unfreeze()\n        gc.enable()\n        initial_gc_freeze_done = True\n\n    for id in graph:\n        manager.import_map[id] = graph[id].dependencies_set\n\n    t1 = time.time()\n    manager.add_stats(\n        graph_size=len(graph),\n        stubs_found=sum(g.path is not None and g.path.endswith(\".pyi\") for g in graph.values()),\n        graph_load_time=(t1 - t0),\n        fm_cache_size=len(manager.find_module_cache.results),\n    )\n    if not graph:\n        print(\"Nothing to do?!\", file=stdout)\n        return graph\n    manager.log(f\"Loaded graph with {len(graph)} nodes ({t1 - t0:.3f} sec)\")\n    if manager.options.dump_graph:\n        dump_graph(graph, stdout)\n        return graph\n\n    # Fine grained dependencies that didn't have an associated module in the build\n    # are serialized separately, so we read them after we load the graph.\n    # We need to read them both for running in daemon mode and if we are generating\n    # a fine-grained cache (so that we can properly update them incrementally).\n    # The `read_deps_cache` will also validate\n    # the deps cache against the loaded individual cache files.\n    if manager.options.cache_fine_grained or manager.use_fine_grained_cache():\n        t2 = time.time()\n        fg_deps_meta = read_deps_cache(manager, graph)\n        manager.add_stats(load_fg_deps_time=time.time() - t2)\n        if fg_deps_meta is not None:\n            manager.fg_deps_meta = fg_deps_meta\n        elif manager.stats.get(\"fresh_metas\", 0) > 0:\n            # Clear the stats so we don't infinite loop because of positive fresh_metas\n            manager.stats.clear()\n            # There were some cache files read, but no fine-grained dependencies loaded.\n            manager.log(\"Error reading fine-grained dependencies cache -- aborting cache load\")\n            manager.cache_enabled = False\n            manager.log(\"Falling back to full run -- reloading graph...\")\n            return dispatch(sources, manager, stdout)\n\n    # If we are loading a fine-grained incremental mode cache, we\n    # don't want to do a real incremental reprocess of the\n    # graph---we'll handle it all later.\n    if not manager.use_fine_grained_cache():\n        process_graph(graph, manager)\n        # Update plugins snapshot.\n        write_plugins_snapshot(manager)\n        manager.old_plugins_snapshot = manager.plugins_snapshot\n        if manager.options.cache_fine_grained or manager.options.fine_grained_incremental:\n            # If we are running a daemon or are going to write cache for further fine grained use,\n            # then we need to collect fine grained protocol dependencies.\n            # Since these are a global property of the program, they are calculated after we\n            # processed the whole graph.\n            type_state.add_all_protocol_deps(manager.fg_deps)\n            if not manager.options.fine_grained_incremental:\n                rdeps = generate_deps_for_cache(manager, graph)\n                write_deps_cache(rdeps, manager, graph)\n\n    if manager.options.dump_deps:\n        # This speeds up startup a little when not using the daemon mode.\n        from mypy.server.deps import dump_all_dependencies\n\n        dump_all_dependencies(\n            manager.modules, manager.all_types, manager.options.python_version, manager.options\n        )\n\n    return graph\n\n\nclass NodeInfo:\n    \"\"\"Some info about a node in the graph of SCCs.\"\"\"\n\n    def __init__(self, index: int, scc: list[str]) -> None:\n        self.node_id = \"n%d\" % index\n        self.scc = scc\n        self.sizes: dict[str, int] = {}  # mod -> size in bytes\n        self.deps: dict[str, int] = {}  # node_id -> pri\n\n    def dumps(self) -> str:\n        \"\"\"Convert to JSON string.\"\"\"\n        total_size = sum(self.sizes.values())\n        return \"[{}, {}, {},\\n     {},\\n     {}]\".format(\n            json.dumps(self.node_id),\n            json.dumps(total_size),\n            json.dumps(self.scc),\n            json.dumps(self.sizes),\n            json.dumps(self.deps),\n        )\n\n\ndef dump_timing_stats(path: str, graph: Graph) -> None:\n    \"\"\"Dump timing stats for each file in the given graph.\"\"\"\n    with open(path, \"w\") as f:\n        for id in sorted(graph):\n            f.write(f\"{id} {graph[id].time_spent_us}\\n\")\n\n\ndef dump_line_checking_stats(path: str, graph: Graph) -> None:\n    \"\"\"Dump per-line expression type checking stats.\"\"\"\n    with open(path, \"w\") as f:\n        for id in sorted(graph):\n            if not graph[id].per_line_checking_time_ns:\n                continue\n            f.write(f\"{id}:\\n\")\n            for line in sorted(graph[id].per_line_checking_time_ns):\n                line_time = graph[id].per_line_checking_time_ns[line]\n                f.write(f\"{line:>5} {line_time/1000:8.1f}\\n\")\n\n\ndef dump_graph(graph: Graph, stdout: TextIO | None = None) -> None:\n    \"\"\"Dump the graph as a JSON string to stdout.\n\n    This copies some of the work by process_graph()\n    (sorted_components() and order_ascc()).\n    \"\"\"\n    stdout = stdout or sys.stdout\n    nodes = []\n    sccs = sorted_components(graph)\n    for i, ascc in enumerate(sccs):\n        scc = order_ascc(graph, ascc.mod_ids)\n        node = NodeInfo(i, scc)\n        nodes.append(node)\n    inv_nodes = {}  # module -> node_id\n    for node in nodes:\n        for mod in node.scc:\n            inv_nodes[mod] = node.node_id\n    for node in nodes:\n        for mod in node.scc:\n            state = graph[mod]\n            size = 0\n            if state.path:\n                try:\n                    size = os.path.getsize(state.path)\n                except OSError:\n                    pass\n            node.sizes[mod] = size\n            for dep in state.dependencies:\n                if dep in state.priorities:\n                    pri = state.priorities[dep]\n                    if dep in inv_nodes:\n                        dep_id = inv_nodes[dep]\n                        if dep_id != node.node_id and (\n                            dep_id not in node.deps or pri < node.deps[dep_id]\n                        ):\n                            node.deps[dep_id] = pri\n    print(\"[\" + \",\\n \".join(node.dumps() for node in nodes) + \"\\n]\", file=stdout)\n\n\ndef load_graph(\n    sources: list[BuildSource],\n    manager: BuildManager,\n    old_graph: Graph | None = None,\n    new_modules: list[State] | None = None,\n) -> Graph:\n    \"\"\"Given some source files, load the full dependency graph.\n\n    If an old_graph is passed in, it is used as the starting point and\n    modified during graph loading.\n\n    If a new_modules is passed in, any modules that are loaded are\n    added to the list. This is an argument and not a return value\n    so that the caller can access it even if load_graph fails.\n\n    As this may need to parse files, this can raise CompileError in case\n    there are syntax errors.\n    \"\"\"\n\n    graph: Graph = old_graph if old_graph is not None else {}\n\n    # The deque is used to implement breadth-first traversal.\n    # TODO: Consider whether to go depth-first instead.  This may\n    # affect the order in which we process files within import cycles.\n    new = new_modules if new_modules is not None else []\n    entry_points: set[str] = set()\n    # Seed the graph with the initial root sources.\n    for bs in sources:\n        try:\n            st = State.new_state(\n                id=bs.module,\n                path=bs.path,\n                source=bs.text,\n                manager=manager,\n                root_source=not bs.followed,\n            )\n        except ModuleNotFound:\n            continue\n        if st.id in graph:\n            manager.errors.set_file(st.xpath, st.id, manager.options)\n            manager.error(\n                None,\n                f'Duplicate module named \"{st.id}\" (also at \"{graph[st.id].xpath}\")',\n                blocker=True,\n            )\n            resolution_note = f\"\"\"\n            See {MODULE_RESOLUTION_URL} for more info\n            Common resolutions include:\n                a) using `--exclude` to avoid checking one of them,\n                b) adding `__init__.py` somewhere,\n                c) using `--explicit-package-bases` or adjusting `MYPYPATH`\n            \"\"\"\n            manager.note_multiline(None, resolution_note)\n            manager.errors.raise_error()\n        graph[st.id] = st\n        new.append(st)\n        entry_points.add(bs.module)\n\n    # Note: Running this each time could be slow in the daemon. If it's a problem, we\n    # can do more work to maintain this incrementally.\n    seen_files = {st.abspath: st for st in graph.values() if st.path}\n\n    # Collect dependencies.  We go breadth-first.\n    # More nodes might get added to new as we go, but that's fine.\n    for st in new:\n        assert st.ancestors is not None\n        # Strip out indirect dependencies.  These will be dealt with\n        # when they show up as direct dependencies, and there's a\n        # scenario where they hurt:\n        # - Suppose A imports B and B imports C.\n        # - Suppose on the next round:\n        #   - C is deleted;\n        #   - B is updated to remove the dependency on C;\n        #   - A is unchanged.\n        # - In this case A's cached *direct* dependencies are still valid\n        #   (since direct dependencies reflect the imports found in the source)\n        #   but A's cached *indirect* dependency on C is wrong.\n        dependencies = [dep for dep in st.dependencies if st.priorities.get(dep) != PRI_INDIRECT]\n        if not manager.use_fine_grained_cache():\n            added = [dep for dep in st.suppressed if find_module_simple(dep, manager)]\n        else:\n            # During initial loading we don't care about newly added modules,\n            # they will be taken care of during fine-grained update. See also\n            # comment about this in `State.new_state()`.\n            added = []\n        for dep in st.ancestors + dependencies + st.suppressed:\n            ignored = dep in st.suppressed_set and dep not in entry_points\n            if ignored and dep not in added:\n                manager.missing_modules[dep] = SuppressionReason.NOT_FOUND\n                # TODO: for now we skip this in the daemon as a performance optimization.\n                # This however creates a correctness issue, see #7777 and State.is_fresh().\n                if not manager.use_fine_grained_cache() or manager.options.warn_unused_configs:\n                    manager.import_options[dep] = manager.options.clone_for_module(\n                        dep\n                    ).dep_import_options()\n            elif dep not in graph:\n                try:\n                    if dep in st.ancestors:\n                        # TODO: Why not 'if dep not in st.dependencies' ?\n                        # Ancestors don't have import context.\n                        newst = State.new_state(\n                            id=dep, path=None, source=None, manager=manager, ancestor_for=st\n                        )\n                    else:\n                        newst = State.new_state(\n                            id=dep,\n                            path=None,\n                            source=None,\n                            manager=manager,\n                            caller_state=st,\n                            caller_line=st.dep_line_map.get(dep, 1),\n                        )\n                except ModuleNotFound:\n                    if dep in st.dependencies_set:\n                        st.suppress_dependency(dep)\n                else:\n                    if newst.path:\n                        newst_path = newst.abspath\n\n                        if newst_path in seen_files:\n                            manager.error(\n                                None,\n                                \"Source file found twice under different module names: \"\n                                f'\"{seen_files[newst_path].id}\" and \"{newst.id}\"',\n                                blocker=True,\n                            )\n                            resolution_note = f\"\"\"\n                            See {MODULE_RESOLUTION_URL} for more info\n                            Common resolutions include:\n                                a) adding `__init__.py` somewhere,\n                                b) using `--explicit-package-bases` or adjusting `MYPYPATH`\n                            \"\"\"\n                            manager.note_multiline(None, resolution_note)\n                            manager.errors.raise_error()\n\n                        seen_files[newst_path] = newst\n\n                    assert newst.id not in graph, newst.id\n                    graph[newst.id] = newst\n                    new.append(newst)\n    # There are two things we need to do after the initial load loop. One is up-suppress\n    # modules that are back in graph. We need to do this after the loop to cover edge cases\n    # like where a namespace package ancestor is shared by a typed and an untyped package.\n    for st in graph.values():\n        for dep in st.suppressed.copy():\n            if dep in graph:\n                st.add_dependency(dep)\n                manager.missing_modules.pop(dep, None)\n    # Second, in the initial loop we skip indirect dependencies, so to make indirect dependencies\n    # behave more consistently with regular ones, we suppress them manually here (when needed).\n    for st in graph.values():\n        indirect = [dep for dep in st.dependencies if st.priorities.get(dep) == PRI_INDIRECT]\n        for dep in indirect:\n            if dep not in graph:\n                st.suppress_dependency(dep)\n    manager.plugin.set_modules(manager.modules)\n    manager.errors.global_watcher = False\n    return graph\n\n\ndef order_ascc_ex(graph: Graph, ascc: SCC) -> list[str]:\n    \"\"\"Apply extra heuristics on top of order_ascc().\n\n    This should be used only for actual SCCs, not for \"inner\" SCCs\n    we create recursively during ordering of the SCC. Currently, this\n    has only some special handling for builtin SCC.\n    \"\"\"\n    scc = order_ascc(graph, ascc.mod_ids)\n    # Make the order of the SCC that includes 'builtins' and 'typing',\n    # among other things, predictable. Various things may  break if\n    # the order changes.\n    if \"builtins\" in ascc.mod_ids:\n        scc = sorted(scc, reverse=True)\n        # If builtins is in the list, move it last.  (This is a bit of\n        # a hack, but it's necessary because the builtins module is\n        # part of a small cycle involving at least {builtins, abc,\n        # typing}.  Of these, builtins must be processed last or else\n        # some builtin objects will be incompletely processed.)\n        scc.remove(\"builtins\")\n        scc.append(\"builtins\")\n    return scc\n\n\ndef verify_transitive_deps(ascc: SCC, graph: Graph, manager: BuildManager) -> str | None:\n    \"\"\"Verify all indirect dependencies of this SCC are still reachable via direct ones.\n\n    Return first unreachable dependency id, or None.\n    \"\"\"\n    for id in ascc.mod_ids:\n        st = graph[id]\n        assert st.meta is not None, \"Must be called on fresh SCCs only\"\n        if st.trans_dep_hash == st.meta.trans_dep_hash:\n            # Import graph unchanged, skip this module.\n            continue\n        for dep in st.dependencies:\n            if st.priorities.get(dep) == PRI_INDIRECT:\n                dep_scc_id = manager.scc_by_mod_id[dep].id\n                if dep_scc_id == ascc.id:\n                    continue\n                if not manager.is_transitive_scc_dep(ascc.id, dep_scc_id):\n                    return dep\n    return None\n\n\ndef find_stale_sccs(\n    sccs: list[SCC], graph: Graph, manager: BuildManager\n) -> tuple[list[SCC], list[SCC]]:\n    \"\"\"Split a list of ready SCCs into stale and fresh.\n\n    Fresh SCCs are those where:\n    * We have valid cache files for all modules in the SCC.\n    * There are no changes in dependencies (files removed from/added to the build).\n    * The interface hashes of dependencies matches those recorded in the cache.\n    * All indirect dependencies are still reachable via direct ones.\n    The first and second conditions are verified by is_fresh().\n    \"\"\"\n    stale_sccs = []\n    fresh_sccs = []\n    for ascc in sccs:\n        stale_scc = {id for id in ascc.mod_ids if not graph[id].is_fresh()}\n        fresh = not stale_scc\n\n        # Verify that interfaces of dependencies still present in graph are up-to-date (fresh).\n        stale_deps = set()\n        for id in ascc.mod_ids:\n            for dep in graph[id].dep_hashes:\n                if dep in graph and graph[dep].interface_hash != graph[id].dep_hashes[dep]:\n                    stale_deps.add(dep)\n        fresh = fresh and not stale_deps\n\n        # Verify the invariant that indirect dependencies are a subset of transitive direct\n        # dependencies. Note: the case where indirect dependency is removed from the graph\n        # completely is already handled above.\n        stale_indirect = None\n        if fresh:\n            stale_indirect = verify_transitive_deps(ascc, graph, manager)\n            if stale_indirect is not None:\n                fresh = False\n\n        if manager.logging_enabled:\n            if fresh:\n                fresh_msg = \"fresh\"\n            elif stale_scc:\n                fresh_msg = \"inherently stale\"\n                if stale_scc != ascc.mod_ids:\n                    fresh_msg += f\" ({' '.join(sorted(stale_scc))})\"\n                if stale_deps:\n                    fresh_msg += f\" with stale deps ({' '.join(sorted(stale_deps))})\"\n            elif stale_deps:\n                fresh_msg = f\"stale due to deps ({' '.join(sorted(stale_deps))})\"\n            else:\n                assert stale_indirect is not None\n                fresh_msg = f\"stale due to stale indirect dep(s): first {stale_indirect}\"\n            scc_str = \" \".join(ascc.mod_ids)\n\n        if fresh:\n            if manager.tracing_enabled:\n                manager.trace(f\"Found {fresh_msg} SCC ({scc_str})\")\n            # If there is at most one file with errors we can skip the ordering to save time.\n            mods_with_errors = [id for id in ascc.mod_ids if graph[id].error_lines]\n            if len(mods_with_errors) <= 1:\n                scc = mods_with_errors\n            else:\n                # Use exactly the same order as for stale SCCs for stability.\n                scc = order_ascc_ex(graph, ascc)\n            for id in scc:\n                if graph[id].error_lines:\n                    path = manager.errors.simplify_path(graph[id].xpath)\n                    formatted = manager.errors.format_messages(\n                        path, graph[id].error_lines, formatter=manager.error_formatter\n                    )\n                    manager.flush_errors(path, formatted, False)\n            fresh_sccs.append(ascc)\n        else:\n            if manager.logging_enabled:\n                size = len(ascc.mod_ids)\n                if size == 1:\n                    manager.log(f\"Scheduling SCC singleton ({scc_str}) as {fresh_msg}\")\n                else:\n                    manager.log(\n                        \"Scheduling SCC of size %d (%s) as %s\" % (size, scc_str, fresh_msg)\n                    )\n            stale_sccs.append(ascc)\n    return stale_sccs, fresh_sccs\n\n\ndef process_graph(graph: Graph, manager: BuildManager) -> None:\n    \"\"\"Process everything in dependency order.\"\"\"\n    # Broadcast graph to workers before computing SCCs to save a bit of time.\n    # TODO: check if we can optimize by sending only part of the graph needed for given SCC.\n    # For example only send modules in the SCC and their dependencies.\n    graph_message = GraphMessage(graph=graph, missing_modules=manager.missing_modules)\n    buf = WriteBuffer()\n    graph_message.write(buf)\n    graph_data = buf.getvalue()\n    for worker in manager.workers:\n        AckMessage.read(receive(worker.conn))\n        worker.conn.write_bytes(graph_data)\n\n    sccs = sorted_components(graph)\n    manager.log(\n        \"Found %d SCCs; largest has %d nodes\" % (len(sccs), max(len(scc.mod_ids) for scc in sccs))\n    )\n    scc_by_id = {scc.id: scc for scc in sccs}\n    manager.scc_by_id = scc_by_id\n    manager.top_order = [scc.id for scc in sccs]\n    for scc in sccs:\n        for mod_id in scc.mod_ids:\n            manager.scc_by_mod_id[mod_id] = scc\n\n    # Broadcast SCC structure to the parallel workers, since they don't compute it.\n    sccs_message = SccsDataMessage(sccs=sccs)\n    buf = WriteBuffer()\n    sccs_message.write(buf)\n    sccs_data = buf.getvalue()\n    for worker in manager.workers:\n        AckMessage.read(receive(worker.conn))\n        worker.conn.write_bytes(sccs_data)\n    for worker in manager.workers:\n        AckMessage.read(receive(worker.conn))\n\n    manager.free_workers = set(range(manager.options.num_workers))\n\n    # Prime the ready list with leaf SCCs (that have no dependencies).\n    ready = []\n    not_ready = set()\n    for scc in sccs:\n        if not scc.deps:\n            ready.append(scc)\n        else:\n            not_ready.add(scc)\n\n    still_working = False\n    while ready or not_ready or still_working:\n        stale, fresh = find_stale_sccs(ready, graph, manager)\n        if stale:\n            for scc in stale:\n                for id in scc.mod_ids:\n                    graph[id].mark_as_rechecked()\n            manager.submit(graph, stale)\n            still_working = True\n        # We eagerly walk over fresh SCCs to reach as many stale SCCs as soon\n        # as possible. Only when there are no fresh SCCs, we wait on scheduled stale ones.\n        # This strategy, similar to a naive strategy in minesweeper game, will allow us\n        # to leverage parallelism as much as possible.\n        if fresh:\n            done = fresh\n        else:\n            done, still_working, results = manager.wait_for_done(graph)\n            # Expose the results of type-checking by workers. For in-process\n            # type-checking this is already done and results should be empty here.\n            if not manager.workers:\n                assert not results\n            for id, (interface_hash, errors) in results.items():\n                new_hash = bytes.fromhex(interface_hash)\n                if new_hash != graph[id].interface_hash:\n                    graph[id].mark_interface_stale()\n                    graph[id].interface_hash = new_hash\n                manager.flush_errors(manager.errors.simplify_path(graph[id].xpath), errors, False)\n        ready = []\n        for done_scc in done:\n            for dependent in done_scc.direct_dependents:\n                scc_by_id[dependent].not_ready_deps.discard(done_scc.id)\n                if not scc_by_id[dependent].not_ready_deps:\n                    not_ready.remove(scc_by_id[dependent])\n                    ready.append(scc_by_id[dependent])\n    manager.trace(f\"Transitive deps cache size: {sys.getsizeof(manager.transitive_deps_cache)}\")\n\n\ndef order_ascc(graph: Graph, ascc: AbstractSet[str], pri_max: int = PRI_INDIRECT) -> list[str]:\n    \"\"\"Come up with the ideal processing order within an SCC.\n\n    Using the priorities assigned by all_imported_modules_in_file(),\n    try to reduce the cycle to a DAG, by omitting arcs representing\n    dependencies of lower priority.\n\n    In the simplest case, if we have A <--> B where A has a top-level\n    \"import B\" (medium priority) but B only has the reverse \"import A\"\n    inside a function (low priority), we turn the cycle into a DAG by\n    dropping the B --> A arc, which leaves only A --> B.\n\n    If all arcs have the same priority, we fall back to sorting by\n    reverse global order (the order in which modules were first\n    encountered).\n\n    The algorithm is recursive, as follows: when as arcs of different\n    priorities are present, drop all arcs of the lowest priority,\n    identify SCCs in the resulting graph, and apply the algorithm to\n    each SCC thus found.  The recursion is bounded because at each\n    recursion the spread in priorities is (at least) one less.\n\n    In practice there are only a few priority levels (less than a\n    dozen) and in the worst case we just carry out the same algorithm\n    for finding SCCs N times.  Thus, the complexity is no worse than\n    the complexity of the original SCC-finding algorithm -- see\n    strongly_connected_components() below for a reference.\n    \"\"\"\n    if len(ascc) == 1:\n        return list(ascc)\n    pri_spread = set()\n    for id in ascc:\n        state = graph[id]\n        for dep in state.dependencies:\n            if dep in ascc:\n                pri = state.priorities.get(dep, PRI_HIGH)\n                if pri < pri_max:\n                    pri_spread.add(pri)\n    if len(pri_spread) == 1:\n        # Filtered dependencies are uniform -- order by global order.\n        return sorted(ascc, key=lambda id: -graph[id].order)\n    pri_max = max(pri_spread)\n    sccs = sorted_components_inner(graph, ascc, pri_max)\n    # The recursion is bounded by the len(pri_spread) check above.\n    return [s for ss in sccs for s in order_ascc(graph, ss, pri_max)]\n\n\ndef process_fresh_modules(graph: Graph, modules: list[str], manager: BuildManager) -> None:\n    \"\"\"Process the modules in one group of modules from their cached data.\n\n    This can be used to process an SCC of modules. This involves loading the tree (i.e.\n    module symbol tables) from cache file and then fixing cross-references in the symbols.\n    \"\"\"\n    t0 = time.time()\n    for id in modules:\n        graph[id].load_tree()\n    t1 = time.time()\n    for id in modules:\n        graph[id].fix_cross_refs()\n    t2 = time.time()\n    manager.add_stats(process_fresh_time=t2 - t0, load_tree_time=t1 - t0)\n\n\ndef process_stale_scc(\n    graph: Graph, ascc: SCC, manager: BuildManager, from_cache: set[str] | None = None\n) -> dict[str, tuple[str, list[str]]]:\n    \"\"\"Process the modules in one SCC from source code.\"\"\"\n    # First verify if all transitive dependencies are loaded in the current process.\n    t0 = time.time()\n    missing_sccs = set()\n    sccs_to_find = ascc.deps.copy()\n    while sccs_to_find:\n        dep_scc = sccs_to_find.pop()\n        if dep_scc in manager.done_sccs or dep_scc in missing_sccs:\n            continue\n        missing_sccs.add(dep_scc)\n        sccs_to_find.update(manager.scc_by_id[dep_scc].deps)\n\n    if missing_sccs:\n        # Load missing SCCs from cache.\n        # TODO: speed-up ordering if this causes problems for large builds.\n        fresh_sccs_to_load = [\n            manager.scc_by_id[sid] for sid in manager.top_order if sid in missing_sccs\n        ]\n\n        if manager.parallel_worker:\n            # Update cache metas as well, cache data is loaded below\n            # in process_fresh_modules().\n            for prev_scc in fresh_sccs_to_load:\n                for mod_id in prev_scc.mod_ids:\n                    graph[mod_id].reload_meta()\n\n        manager.log(f\"Processing {len(fresh_sccs_to_load)} fresh SCCs\")\n        if (\n            not manager.options.test_env\n            and platform.python_implementation() == \"CPython\"\n            # Parallel workers perform loading in many smaller \"pieces\", so we\n            # should repeat the GC hack multiple times to actually benefit from it.\n            and (manager.gc_freeze_cycles < MAX_GC_FREEZE_CYCLES or manager.parallel_worker)\n        ):\n            # When deserializing cache we create huge amount of new objects, so even\n            # with our generous GC thresholds, GC is still doing a lot of pointless\n            # work searching for garbage. So, we temporarily disable it when\n            # processing fresh SCCs, and then move all the new objects to the oldest\n            # generation with the freeze()/unfreeze() trick below. This is arguably\n            # a hack, but it gives huge performance wins for large third-party\n            # libraries, like torch.\n            gc.collect(generation=1)\n            gc.collect(generation=0)\n            gc.disable()\n        for prev_scc in fresh_sccs_to_load:\n            manager.done_sccs.add(prev_scc.id)\n            process_fresh_modules(graph, sorted(prev_scc.mod_ids), manager)\n        if (\n            not manager.options.test_env\n            and platform.python_implementation() == \"CPython\"\n            and (manager.gc_freeze_cycles < MAX_GC_FREEZE_CYCLES or manager.parallel_worker)\n        ):\n            manager.gc_freeze_cycles += 1\n            gc.freeze()\n            gc.unfreeze()\n            gc.enable()\n\n    t1 = time.time()\n    # Process the SCC in stable order.\n    scc = order_ascc_ex(graph, ascc)\n\n    t2 = time.time()\n    stale = scc\n    for id in stale:\n        # Re-generate import errors in case this module was loaded from the cache.\n        # Deserialized states all have meta=None, so the caller should specify\n        # explicitly which of them are from cache.\n        if graph[id].meta or from_cache and id in from_cache:\n            graph[id].verify_dependencies(suppressed_only=True)\n        # We may already have parsed the module, or not.\n        # If the former, parse_file() is a no-op.\n        graph[id].parse_file()\n    if \"typing\" in scc:\n        # For historical reasons we need to manually add typing aliases\n        # for built-in generic collections, see docstring of\n        # SemanticAnalyzerPass2.add_builtin_aliases for details.\n        typing_mod = graph[\"typing\"].tree\n        assert typing_mod, \"The typing module was not parsed\"\n    mypy.semanal_main.semantic_analysis_for_scc(graph, scc, manager.errors)\n\n    t3 = time.time()\n    # Track what modules aren't yet done, so we can finish them as soon\n    # as possible, saving memory.\n    unfinished_modules = set(stale)\n    for id in stale:\n        graph[id].type_check_first_pass()\n        if not graph[id].type_checker().deferred_nodes:\n            unfinished_modules.discard(id)\n            graph[id].detect_possibly_undefined_vars()\n            graph[id].finish_passes()\n\n    while unfinished_modules:\n        for id in stale:\n            if id not in unfinished_modules:\n                continue\n            if not graph[id].type_check_second_pass():\n                unfinished_modules.discard(id)\n                graph[id].detect_possibly_undefined_vars()\n                graph[id].finish_passes()\n    for id in stale:\n        graph[id].generate_unused_ignore_notes()\n        graph[id].generate_ignore_without_code_notes()\n\n    t4 = time.time()\n    # Flush errors, and write cache in two phases: first data files, then meta files.\n    meta_tuples = {}\n    errors_by_id = {}\n    formatted_by_id = {}\n    for id in stale:\n        if graph[id].xpath not in manager.errors.ignored_files:\n            errors = manager.errors.file_messages(graph[id].xpath)\n            formatted = manager.errors.format_messages(\n                graph[id].xpath, errors, formatter=manager.error_formatter\n            )\n            manager.flush_errors(manager.errors.simplify_path(graph[id].xpath), formatted, False)\n            errors_by_id[id] = errors\n            formatted_by_id[id] = formatted\n        meta_tuples[id] = graph[id].write_cache()\n    for id in stale:\n        meta_tuple = meta_tuples[id]\n        if meta_tuple is None:\n            continue\n        meta, meta_file = meta_tuple\n        meta.dep_hashes = [graph[dep].interface_hash for dep in graph[id].dependencies]\n        write_cache_meta(meta, manager, meta_file)\n        write_errors_file(meta_file, errors_by_id.get(id, []), manager)\n    manager.done_sccs.add(ascc.id)\n    manager.add_stats(\n        load_missing_time=t1 - t0,\n        order_scc_time=t2 - t1,\n        semanal_time=t3 - t2,\n        type_check_time=t4 - t3,\n        flush_and_cache_time=time.time() - t4,\n    )\n    scc_result = {}\n    for id in scc:\n        scc_result[id] = graph[id].interface_hash.hex(), formatted_by_id.get(id, [])\n    return scc_result\n\n\ndef prepare_sccs_full(\n    raw_sccs: Iterator[set[str]], edges: dict[str, list[str]]\n) -> dict[SCC, set[SCC]]:\n    \"\"\"Turn raw SCC sets into SCC objects and build dependency graph for SCCs.\"\"\"\n    sccs = [SCC(raw_scc) for raw_scc in raw_sccs]\n    scc_map = {}\n    for scc in sccs:\n        for id in scc.mod_ids:\n            scc_map[id] = scc\n    scc_deps_map: dict[SCC, set[SCC]] = {}\n    for scc in sccs:\n        for id in scc.mod_ids:\n            scc_deps_map.setdefault(scc, set()).update(scc_map[dep] for dep in edges[id])\n    for scc in sccs:\n        # Remove trivial dependency on itself.\n        scc_deps_map[scc].discard(scc)\n        for dep_scc in scc_deps_map[scc]:\n            scc.deps.add(dep_scc.id)\n            scc.not_ready_deps.add(dep_scc.id)\n    return scc_deps_map\n\n\ndef sorted_components(graph: Graph) -> list[SCC]:\n    \"\"\"Return the graph's SCCs, topologically sorted by dependencies.\n\n    The sort order is from leaves (nodes without dependencies) to\n    roots (nodes on which no other nodes depend).\n    \"\"\"\n    # Compute SCCs.\n    vertices = set(graph)\n    edges = {id: deps_filtered(graph, vertices, id, PRI_INDIRECT) for id in vertices}\n    scc_dep_map = prepare_sccs_full(strongly_connected_components(vertices, edges), edges)\n    # Topsort.\n    res = []\n    for ready in topsort(scc_dep_map):\n        # Sort the sets in ready by reversed smallest State.order.  Examples:\n        #\n        # - If ready is [{x}, {y}], x.order == 1, y.order == 2, we get\n        #   [{y}, {x}].\n        #\n        # - If ready is [{a, b}, {c, d}], a.order == 1, b.order == 3,\n        #   c.order == 2, d.order == 4, the sort keys become [1, 2]\n        #   and the result is [{c, d}, {a, b}].\n        sorted_ready = sorted(ready, key=lambda scc: -min(graph[id].order for id in scc.mod_ids))\n        for scc in sorted_ready:\n            scc.size_hint = sum(graph[mid].size_hint for mid in scc.mod_ids)\n            for dep in scc_dep_map[scc]:\n                dep.direct_dependents.append(scc.id)\n            # We compute dependencies hash here since we know no direct\n            # dependencies will be added or suppressed after this point.\n            trans_dep_hash = transitive_dep_hash(scc, graph)\n            for id in scc.mod_ids:\n                graph[id].trans_dep_hash = trans_dep_hash\n        res.extend(sorted_ready)\n    return res\n\n\ndef sorted_components_inner(\n    graph: Graph, vertices: AbstractSet[str], pri_max: int\n) -> list[AbstractSet[str]]:\n    \"\"\"Simplified version of sorted_components() to work with sub-graphs.\n\n    This doesn't create SCC objects, and operates with raw sets. This function\n    also allows filtering dependencies to take into account when building SCCs.\n    This is used for heuristic ordering of modules within actual SCCs.\n    \"\"\"\n    edges = {id: deps_filtered(graph, vertices, id, pri_max) for id in vertices}\n    sccs = list(strongly_connected_components(vertices, edges))\n    res = []\n    for ready in topsort(prepare_sccs(sccs, edges)):\n        res.extend(sorted(ready, key=lambda scc: -min(graph[id].order for id in scc)))\n    return res\n\n\ndef deps_filtered(graph: Graph, vertices: AbstractSet[str], id: str, pri_max: int) -> list[str]:\n    \"\"\"Filter dependencies for id with pri < pri_max.\"\"\"\n    if id not in vertices:\n        return []\n    state = graph[id]\n    return [\n        dep\n        for dep in state.dependencies\n        if dep in vertices and state.priorities.get(dep, PRI_HIGH) < pri_max\n    ]\n\n\ndef transitive_dep_hash(scc: SCC, graph: Graph) -> bytes:\n    \"\"\"Compute stable snapshot of transitive import structure for given SCC.\"\"\"\n    all_direct_deps = sorted(\n        {\n            dep\n            for id in scc.mod_ids\n            for dep in graph[id].dependencies\n            if graph[id].priorities.get(dep) != PRI_INDIRECT\n        }\n    )\n    buf = WriteBuffer()\n    for dep_id in all_direct_deps:\n        write_str_bare(buf, dep_id)\n        if dep_id not in scc.mod_ids:\n            write_bytes_bare(buf, graph[dep_id].trans_dep_hash)\n    return hash_digest_bytes(buf.getvalue())\n\n\ndef missing_stubs_file(cache_dir: str) -> str:\n    return os_path_join(cache_dir, \"missing_stubs\")\n\n\ndef record_missing_stub_packages(cache_dir: str, missing_stub_packages: set[str]) -> None:\n    \"\"\"Write a file containing missing stub packages.\n\n    This allows a subsequent \"mypy --install-types\" run (without other arguments)\n    to install missing stub packages.\n    \"\"\"\n    fnam = missing_stubs_file(cache_dir)\n    if missing_stub_packages:\n        with open(fnam, \"w\") as f:\n            for pkg in sorted(missing_stub_packages):\n                f.write(f\"{pkg}\\n\")\n    else:\n        if os.path.isfile(fnam):\n            os.remove(fnam)\n\n\ndef is_silent_import_module(manager: BuildManager, path: str) -> bool:\n    if manager.options.no_silence_site_packages:\n        return False\n    # Silence errors in site-package dirs and typeshed\n    if any(is_sub_path_normabs(path, dir) for dir in manager.search_paths.package_path):\n        return True\n    return any(is_sub_path_normabs(path, dir) for dir in manager.search_paths.typeshed_path)\n\n\ndef write_undocumented_ref_info(\n    state: State, metastore: MetadataStore, options: Options, type_map: dict[Expression, Type]\n) -> None:\n    # This exports some dependency information in a rather ad-hoc fashion, which\n    # can be helpful for some tools. This is all highly experimental and could be\n    # removed at any time.\n\n    from mypy.refinfo import get_undocumented_ref_info_json\n\n    if not state.tree:\n        # We need a full AST for this.\n        return\n\n    _, data_file, _ = get_cache_names(state.id, state.xpath, options)\n    ref_info_file = \".\".join(data_file.split(\".\")[:-2]) + \".refs.json\"\n    assert not ref_info_file.startswith(\".\")\n\n    deps_json = get_undocumented_ref_info_json(state.tree, type_map)\n    metastore.write(ref_info_file, json_dumps(deps_json))\n\n\n# The IPC message classes and tags for communication with build workers are\n# in this file to avoid import cycles.\n# Note that we use a more compact fixed serialization format than in cache.py.\n# This is because the messages don't need to read by a generic tool, nor there\n# is any need for backwards compatibility. We still reuse some elements from\n# cache.py for convenience, and also some conventions (like using bare ints\n# to specify object size).\n# Note that we can use tags overlapping with cache.py, since they should never\n# appear on the same context.\nACK_MESSAGE: Final[Tag] = 101\nSCC_REQUEST_MESSAGE: Final[Tag] = 102\nSCC_RESPONSE_MESSAGE: Final[Tag] = 103\nSOURCES_DATA_MESSAGE: Final[Tag] = 104\nSCCS_DATA_MESSAGE: Final[Tag] = 105\nGRAPH_MESSAGE: Final[Tag] = 106\n\n\nclass AckMessage(IPCMessage):\n    \"\"\"An empty message used primarily for synchronization.\"\"\"\n\n    @classmethod\n    def read(cls, buf: ReadBuffer) -> AckMessage:\n        assert read_tag(buf) == ACK_MESSAGE\n        return AckMessage()\n\n    def write(self, buf: WriteBuffer) -> None:\n        write_tag(buf, ACK_MESSAGE)\n\n\nclass SccRequestMessage(IPCMessage):\n    \"\"\"\n    A message representing a request to type check an SCC.\n\n    If scc_id is None, then it means that the coordinator requested a shutdown.\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        scc_id: int | None,\n        import_errors: dict[str, list[ErrorInfo]],\n        mod_data: dict[str, tuple[bytes, FileRawData | None]],\n    ) -> None:\n        self.scc_id = scc_id\n        self.import_errors = import_errors\n        self.mod_data = mod_data\n\n    @classmethod\n    def read(cls, buf: ReadBuffer) -> SccRequestMessage:\n        assert read_tag(buf) == SCC_REQUEST_MESSAGE\n        return SccRequestMessage(\n            scc_id=read_int_opt(buf),\n            import_errors={\n                read_str(buf): [ErrorInfo.read(buf) for _ in range(read_int_bare(buf))]\n                for _ in range(read_int_bare(buf))\n            },\n            mod_data={\n                read_str_bare(buf): (\n                    read_bytes(buf),\n                    FileRawData.read(buf) if read_bool(buf) else None,\n                )\n                for _ in range(read_int_bare(buf))\n            },\n        )\n\n    def write(self, buf: WriteBuffer) -> None:\n        write_tag(buf, SCC_REQUEST_MESSAGE)\n        write_int_opt(buf, self.scc_id)\n        write_int_bare(buf, len(self.import_errors))\n        for path, errors in self.import_errors.items():\n            write_str(buf, path)\n            write_int_bare(buf, len(errors))\n            for error in errors:\n                error.write(buf)\n        write_int_bare(buf, len(self.mod_data))\n        for mod, (suppressed_deps_opts, raw_data) in self.mod_data.items():\n            write_str_bare(buf, mod)\n            write_bytes(buf, suppressed_deps_opts)\n            if raw_data is None:\n                write_bool(buf, False)\n            else:\n                write_bool(buf, True)\n                raw_data.write(buf)\n\n\nclass SccResponseMessage(IPCMessage):\n    \"\"\"\n    A message representing a result of type checking an SCC.\n\n    Only one of `result` or `blocker` can be non-None. The latter means there was\n    a blocking error while type checking the SCC.\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        scc_id: int,\n        result: dict[str, tuple[str, list[str]]] | None = None,\n        blocker: CompileError | None = None,\n    ) -> None:\n        if result is not None:\n            assert blocker is None\n        if blocker is not None:\n            assert result is None\n        self.scc_id = scc_id\n        self.result = result\n        self.blocker = blocker\n\n    @classmethod\n    def read(cls, buf: ReadBuffer) -> SccResponseMessage:\n        assert read_tag(buf) == SCC_RESPONSE_MESSAGE\n        scc_id = read_int(buf)\n        tag = read_tag(buf)\n        if tag == LITERAL_NONE:\n            return SccResponseMessage(\n                scc_id=scc_id,\n                blocker=CompileError(read_str_list(buf), read_bool(buf), read_str_opt(buf)),\n            )\n        else:\n            assert tag == DICT_STR_GEN\n            return SccResponseMessage(\n                scc_id=scc_id,\n                result={\n                    read_str_bare(buf): (read_str(buf), read_str_list(buf))\n                    for _ in range(read_int_bare(buf))\n                },\n            )\n\n    def write(self, buf: WriteBuffer) -> None:\n        write_tag(buf, SCC_RESPONSE_MESSAGE)\n        write_int(buf, self.scc_id)\n        if self.result is None:\n            assert self.blocker is not None\n            write_tag(buf, LITERAL_NONE)\n            write_str_list(buf, self.blocker.messages)\n            write_bool(buf, self.blocker.use_stdout)\n            write_str_opt(buf, self.blocker.module_with_blocker)\n        else:\n            write_tag(buf, DICT_STR_GEN)\n            write_int_bare(buf, len(self.result))\n            for mod_id in sorted(self.result):\n                write_str_bare(buf, mod_id)\n                hex_hash, errs = self.result[mod_id]\n                write_str(buf, hex_hash)\n                write_str_list(buf, errs)\n\n\nclass SourcesDataMessage(IPCMessage):\n    \"\"\"A message wrapping a list of build sources.\"\"\"\n\n    def __init__(self, *, sources: list[BuildSource]) -> None:\n        self.sources = sources\n\n    @classmethod\n    def read(cls, buf: ReadBuffer) -> SourcesDataMessage:\n        assert read_tag(buf) == SOURCES_DATA_MESSAGE\n        sources = [\n            BuildSource(\n                read_str_opt(buf),\n                read_str_opt(buf),\n                read_str_opt(buf),\n                read_str_opt(buf),\n                read_bool(buf),\n            )\n            for _ in range(read_int_bare(buf))\n        ]\n        return SourcesDataMessage(sources=sources)\n\n    def write(self, buf: WriteBuffer) -> None:\n        write_tag(buf, SOURCES_DATA_MESSAGE)\n        write_int_bare(buf, len(self.sources))\n        for bs in self.sources:\n            write_str_opt(buf, bs.path)\n            write_str_opt(buf, bs.module)\n            write_str_opt(buf, bs.text)\n            write_str_opt(buf, bs.base_dir)\n            write_bool(buf, bs.followed)\n\n\nclass SccsDataMessage(IPCMessage):\n    \"\"\"A message wrapping the SCC structure computed by the coordinator.\"\"\"\n\n    def __init__(self, *, sccs: list[SCC]) -> None:\n        self.sccs = sccs\n\n    @classmethod\n    def read(cls, buf: ReadBuffer) -> SccsDataMessage:\n        assert read_tag(buf) == SCCS_DATA_MESSAGE\n        sccs = [\n            SCC(set(read_str_list(buf)), read_int(buf), read_int_list(buf))\n            for _ in range(read_int_bare(buf))\n        ]\n        return SccsDataMessage(sccs=sccs)\n\n    def write(self, buf: WriteBuffer) -> None:\n        write_tag(buf, SCCS_DATA_MESSAGE)\n        write_int_bare(buf, len(self.sccs))\n        for scc in self.sccs:\n            write_str_list(buf, sorted(scc.mod_ids))\n            write_int(buf, scc.id)\n            write_int_list(buf, sorted(scc.deps))\n\n\nclass GraphMessage(IPCMessage):\n    \"\"\"A message wrapping the build graph computed by the coordinator.\"\"\"\n\n    def __init__(self, *, graph: Graph, missing_modules: dict[str, int]) -> None:\n        self.graph = graph\n        self.missing_modules = missing_modules\n        # Send this data separately as it will be lost during state serialization.\n        self.from_cache = {mod_id for mod_id in graph if graph[mod_id].meta}\n\n    @classmethod\n    def read(cls, buf: ReadBuffer, manager: BuildManager | None = None) -> GraphMessage:\n        assert manager is not None\n        assert read_tag(buf) == GRAPH_MESSAGE\n        graph = {read_str_bare(buf): State.read(buf, manager) for _ in range(read_int_bare(buf))}\n        missing_modules = {read_str_bare(buf): read_int(buf) for _ in range(read_int_bare(buf))}\n        message = GraphMessage(graph=graph, missing_modules=missing_modules)\n        message.from_cache = {read_str_bare(buf) for _ in range(read_int_bare(buf))}\n        return message\n\n    def write(self, buf: WriteBuffer) -> None:\n        write_tag(buf, GRAPH_MESSAGE)\n        write_int_bare(buf, len(self.graph))\n        for mod_id, state in self.graph.items():\n            write_str_bare(buf, mod_id)\n            state.write(buf)\n        write_int_bare(buf, len(self.missing_modules))\n        for module, reason in self.missing_modules.items():\n            write_str_bare(buf, module)\n            write_int(buf, reason)\n        write_int_bare(buf, len(self.from_cache))\n        for module in self.from_cache:\n            write_str_bare(buf, module)\n"
  },
  {
    "path": "mypy/build_worker/__init__.py",
    "content": ""
  },
  {
    "path": "mypy/build_worker/__main__.py",
    "content": "from __future__ import annotations\n\nfrom mypy.build_worker.worker import console_entry\n\nif __name__ == \"__main__\":\n    console_entry()\n"
  },
  {
    "path": "mypy/build_worker/worker.py",
    "content": "\"\"\"\nMypy parallel build worker.\n\nThe protocol of communication with the coordinator is as following:\n* Read (pickled) build options from command line.\n* Populate status file with pid and socket address.\n* Receive build sources from coordinator.\n* Load graph using the sources, and send ack to coordinator.\n* Receive SCC structure from coordinator, and ack it.\n* Receive an SCC id from coordinator, process it, and send back the results.\n* When prompted by coordinator (with a scc_id=None message), cleanup and shutdown.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport gc\nimport json\nimport os\nimport pickle\nimport platform\nimport sys\nimport time\nfrom typing import NamedTuple\n\nfrom librt.base64 import b64decode\n\nfrom mypy import util\nfrom mypy.build import (\n    SCC,\n    AckMessage,\n    BuildManager,\n    Graph,\n    GraphMessage,\n    SccRequestMessage,\n    SccResponseMessage,\n    SccsDataMessage,\n    SourcesDataMessage,\n    load_plugins,\n    process_stale_scc,\n)\nfrom mypy.defaults import RECURSION_LIMIT, WORKER_CONNECTION_TIMEOUT\nfrom mypy.errors import CompileError, ErrorInfo, Errors, report_internal_error\nfrom mypy.fscache import FileSystemCache\nfrom mypy.ipc import IPCException, IPCServer, receive, send\nfrom mypy.modulefinder import BuildSource, BuildSourceSet, compute_search_paths\nfrom mypy.nodes import FileRawData\nfrom mypy.options import Options\nfrom mypy.util import read_py_file\nfrom mypy.version import __version__\n\nparser = argparse.ArgumentParser(prog=\"mypy_worker\", description=\"Mypy build worker\")\nparser.add_argument(\"--status-file\", help=\"status file to communicate worker details\")\nparser.add_argument(\"--options-data\", help=\"serialized mypy options\")\n\nCONNECTION_NAME = \"build_worker\"\n\n\nclass ServerContext(NamedTuple):\n    options: Options\n    disable_error_code: list[str]\n    enable_error_code: list[str]\n    errors: Errors\n    fscache: FileSystemCache\n\n\ndef main(argv: list[str]) -> None:\n    # Set recursion limit and GC thresholds consistent with mypy/main.py\n    sys.setrecursionlimit(RECURSION_LIMIT)\n    if platform.python_implementation() == \"CPython\":\n        gc.set_threshold(200 * 1000, 30, 30)\n\n    args = parser.parse_args(argv)\n\n    # This mimics how daemon receives the options. Note we need to postpone\n    # processing error codes after plugins are loaded, because plugins can add\n    # custom error codes.\n    options_dict = pickle.loads(b64decode(args.options_data))\n    options_obj = Options()\n    disable_error_code = options_dict.pop(\"disable_error_code\", [])\n    enable_error_code = options_dict.pop(\"enable_error_code\", [])\n    options = options_obj.apply_changes(options_dict)\n\n    status_file = args.status_file\n    server = IPCServer(CONNECTION_NAME, WORKER_CONNECTION_TIMEOUT)\n\n    try:\n        with open(status_file, \"w\") as f:\n            json.dump({\"pid\": os.getpid(), \"connection_name\": server.connection_name}, f)\n            f.write(\"\\n\")\n    except Exception as exc:\n        print(f\"Error writing status file {status_file}:\", exc)\n        raise\n\n    fscache = FileSystemCache()\n    cached_read = fscache.read\n    errors = Errors(options, read_source=lambda path: read_py_file(path, cached_read))\n\n    ctx = ServerContext(options, disable_error_code, enable_error_code, errors, fscache)\n    try:\n        with server:\n            serve(server, ctx)\n    except (OSError, IPCException) as exc:\n        if options.verbosity >= 1:\n            print(\"Error communicating with coordinator:\", exc)\n    except Exception as exc:\n        report_internal_error(exc, errors.file, 0, errors, options)\n    finally:\n        server.cleanup()\n\n    if options.fast_exit:\n        # Exit fast if allowed, since coordinator is waiting on us.\n        util.hard_exit(0)\n\n\ndef serve(server: IPCServer, ctx: ServerContext) -> None:\n    \"\"\"Main server loop of the worker.\n\n    Receive initial state from the coordinator, then process each\n    SCC checking request and reply to client (coordinator). See module\n    docstring for more details on the protocol.\n    \"\"\"\n    sources = SourcesDataMessage.read(receive(server)).sources\n    manager = setup_worker_manager(sources, ctx)\n    if manager is None:\n        return\n\n    # Notify coordinator we are done with setup.\n    send(server, AckMessage())\n    graph_data = GraphMessage.read(receive(server), manager)\n    # Update some manager data in-place as it has been passed to semantic analyzer.\n    manager.missing_modules |= graph_data.missing_modules\n    graph = graph_data.graph\n    for id in graph:\n        manager.import_map[id] = graph[id].dependencies_set\n    # Link modules dicts, so that plugins will get access to ASTs as we parse them.\n    manager.plugin.set_modules(manager.modules)\n\n    # Notify coordinator we are ready to receive computed graph SCC structure.\n    send(server, AckMessage())\n    sccs = SccsDataMessage.read(receive(server)).sccs\n    manager.scc_by_id = {scc.id: scc for scc in sccs}\n    manager.top_order = [scc.id for scc in sccs]\n\n    # Notify coordinator we are ready to start processing SCCs.\n    send(server, AckMessage())\n    while True:\n        scc_message = SccRequestMessage.read(receive(server))\n        scc_id = scc_message.scc_id\n        if scc_id is None:\n            manager.dump_stats()\n            break\n        scc = manager.scc_by_id[scc_id]\n        t0 = time.time()\n        try:\n            if platform.python_implementation() == \"CPython\":\n                # Since we are splitting the GC freeze hack into multiple smaller freezes,\n                # we should collect young generations to not accumulate accidental garbage.\n                gc.collect(generation=1)\n                gc.collect(generation=0)\n                gc.disable()\n            load_states(scc, graph, manager, scc_message.import_errors, scc_message.mod_data)\n            if platform.python_implementation() == \"CPython\":\n                gc.freeze()\n                gc.unfreeze()\n                gc.enable()\n            result = process_stale_scc(graph, scc, manager, from_cache=graph_data.from_cache)\n            # We must commit after each SCC, otherwise we break --sqlite-cache.\n            manager.metastore.commit()\n        except CompileError as blocker:\n            send(server, SccResponseMessage(scc_id=scc_id, blocker=blocker))\n        else:\n            send(server, SccResponseMessage(scc_id=scc_id, result=result))\n        manager.add_stats(total_process_stale_time=time.time() - t0, stale_sccs_processed=1)\n\n\ndef load_states(\n    scc: SCC,\n    graph: Graph,\n    manager: BuildManager,\n    import_errors: dict[str, list[ErrorInfo]],\n    mod_data: dict[str, tuple[bytes, FileRawData | None]],\n) -> None:\n    \"\"\"Re-create full state of an SCC as it would have been in coordinator.\"\"\"\n    for id in scc.mod_ids:\n        state = graph[id]\n        # Re-clone options since we don't send them, it is usually faster than deserializing.\n        state.options = state.options.clone_for_module(state.id)\n        suppressed_deps_opts, raw_data = mod_data[id]\n        state.parse_file(raw_data=raw_data)\n        # Set data that is needed to be written to cache meta.\n        state.known_suppressed_deps_opts = suppressed_deps_opts\n        assert state.tree is not None\n        import_lines = {imp.line for imp in state.tree.imports}\n        state.imports_ignored = {\n            line: codes for line, codes in state.tree.ignored_lines.items() if line in import_lines\n        }\n        # Replay original errors encountered during graph loading in coordinator.\n        if id in import_errors:\n            manager.errors.set_file(state.xpath, id, state.options)\n            for err_info in import_errors[id]:\n                manager.errors.add_error_info(err_info)\n\n\ndef setup_worker_manager(sources: list[BuildSource], ctx: ServerContext) -> BuildManager | None:\n    data_dir = os.path.dirname(os.path.dirname(__file__))\n    # This is used for testing only now.\n    alt_lib_path = os.environ.get(\"MYPY_ALT_LIB_PATH\")\n    search_paths = compute_search_paths(sources, ctx.options, data_dir, alt_lib_path)\n\n    source_set = BuildSourceSet(sources)\n    try:\n        plugin, snapshot = load_plugins(ctx.options, ctx.errors, sys.stdout, [])\n    except CompileError:\n        # CompileError while importing plugins will be reported by the coordinator.\n        return None\n\n    # Process the rest of the options when plugins are loaded.\n    options = ctx.options\n    options.disable_error_code = ctx.disable_error_code\n    options.enable_error_code = ctx.enable_error_code\n    options.process_error_codes(error_callback=lambda msg: None)\n\n    def flush_errors(filename: str | None, new_messages: list[str], is_serious: bool) -> None:\n        # We never flush errors in the worker, we send them back to coordinator.\n        pass\n\n    return BuildManager(\n        data_dir,\n        search_paths,\n        ignore_prefix=os.getcwd(),\n        source_set=source_set,\n        reports=None,\n        options=options,\n        version_id=__version__,\n        plugin=plugin,\n        plugins_snapshot=snapshot,\n        errors=ctx.errors,\n        error_formatter=None,\n        flush_errors=flush_errors,\n        fscache=ctx.fscache,\n        stdout=sys.stdout,\n        stderr=sys.stderr,\n        parallel_worker=True,\n    )\n\n\ndef console_entry() -> None:\n    main(sys.argv[1:])\n"
  },
  {
    "path": "mypy/cache.py",
    "content": "\"\"\"\nThis module contains high-level logic for fixed format serialization.\n\nLower-level parts are implemented in C in mypyc/lib-rt/internal/librt_internal.c\nShort summary of low-level functionality:\n* integers are automatically serialized as 1, 2, or 4 bytes, or arbitrary length.\n* str/bytes are serialized as size (1, 2, or 4 bytes) followed by bytes buffer.\n* floats are serialized as C doubles.\n\nAt high-level we add type tags as needed so that our format is self-descriptive.\nMore precisely:\n* False, True, and None are stored as just a tag: 0, 1, 2 correspondingly.\n* builtin primitives like int/str/bytes/float are stored as their type tag followed\n  by bare (low-level) representation of the value. Reserved tag range for primitives is\n  3 ... 19.\n* generic (heterogeneous) list are stored as tag, followed by bare size, followed by\n  sequence of tagged values.\n* homogeneous lists of primitives are stored as tag, followed by bare size, followed\n  by sequence of bare values.\n* reserved tag range for sequence-like builtins is 20 ... 29\n* currently we have only one mapping-like format: string-keyed dictionary with heterogeneous\n  values. It is stored as tag, followed by bare size, followed by sequence of pairs: bare\n  string key followed by tagged value.\n* reserved tag range for mapping-like builtins is 30 ... 39\n* there is an additional reserved tag range 40 ... 49 for any other builtin collections.\n* custom classes (like types, symbols etc.) are stored as tag, followed by a sequence of\n  tagged field values, followed by a special end tag 255. Names of class fields are\n  *not* stored, the caller should know the field names and order for the given class tag.\n* reserved tag range for symbols (TypeInfo, Var, etc) is 50 ... 79.\n* class Instance is the only exception from the above format (since it is the most common one).\n  It has two extra formats: few most common instances like \"builtins.object\" are stored as\n  instance tag followed by a secondary tag, other plain non-generic instances are stored as\n  instance tag followed by secondary tag followed by fullname as bare string. All generic\n  readers must handle these.\n* reserved tag range for Instance type formats is 80 ... 99, for other types it is 100 ... 149.\n* tag 254 is reserved for if we would ever need to extend the tag range to indicated second tag\n  page. Tags 150 ... 253 are free for everything else (e.g. AST nodes etc).\n\nGeneral convention is that custom classes implement write() and read() methods for FF\nserialization. The write method should write both class tag and end tag. The read method\nconventionally *does not* read the start tag (to simplify logic for unions). Known exceptions\nare MypyFile.read() and SymbolTableNode.read(), since those two never appear in a union.\n\nIf any of these details change, or if the structure of CacheMeta changes please\nbump CACHE_VERSION below.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Final, TypeAlias as _TypeAlias\n\nfrom librt.internal import (\n    ReadBuffer as ReadBuffer,\n    WriteBuffer as WriteBuffer,\n    read_bool as read_bool,\n    read_bytes as read_bytes_bare,\n    read_float as read_float_bare,\n    read_int as read_int_bare,\n    read_str as read_str_bare,\n    read_tag as read_tag,\n    write_bool as write_bool,\n    write_bytes as write_bytes_bare,\n    write_float as write_float_bare,\n    write_int as write_int_bare,\n    write_str as write_str_bare,\n    write_tag as write_tag,\n)\nfrom mypy_extensions import u8\n\n# High-level cache layout format\nCACHE_VERSION: Final = 7\n\n# Type used internally to represent errors:\n#   (path, line, column, end_line, end_column, severity, message, code)\nErrorTuple: _TypeAlias = tuple[str | None, int, int, int, int, str, str, str | None]\n\n\nclass CacheMeta:\n    \"\"\"Class representing cache metadata for a module.\"\"\"\n\n    def __init__(\n        self,\n        *,\n        id: str,\n        path: str,\n        mtime: int,\n        size: int,\n        hash: str,\n        dependencies: list[str],\n        data_mtime: int,\n        data_file: str,\n        suppressed: list[str],\n        imports_ignored: dict[int, list[str]],\n        options: dict[str, object],\n        suppressed_deps_opts: bytes,\n        dep_prios: list[int],\n        dep_lines: list[int],\n        dep_hashes: list[bytes],\n        interface_hash: bytes,\n        trans_dep_hash: bytes,\n        version_id: str,\n        ignore_all: bool,\n        plugin_data: Any,\n    ) -> None:\n        self.id = id\n        self.path = path\n        self.mtime = mtime  # source file mtime\n        self.size = size  # source file size\n        self.hash = hash  # source file hash (as a hex string for historical reasons)\n        self.dependencies = dependencies  # names of imported modules\n        self.data_mtime = data_mtime  # mtime of data_file\n        self.data_file = data_file  # path of <id>.data.json or <id>.data.ff\n        self.suppressed = suppressed  # dependencies that weren't imported\n        self.imports_ignored = imports_ignored  # type ignore codes by line\n        self.options = options  # build options snapshot\n        self.suppressed_deps_opts = suppressed_deps_opts  # hash of import-related options\n        # dep_prios and dep_lines are both aligned with dependencies + suppressed\n        self.dep_prios = dep_prios\n        self.dep_lines = dep_lines\n        # dep_hashes list is aligned with dependencies only\n        self.dep_hashes = dep_hashes  # list of interface_hash for dependencies\n        self.interface_hash = interface_hash  # hash representing the public interface\n        self.trans_dep_hash = trans_dep_hash  # hash of import structure (transitive)\n        self.version_id = version_id  # mypy version for cache invalidation\n        self.ignore_all = ignore_all  # if errors were ignored\n        self.plugin_data = plugin_data  # config data from plugins\n\n    def serialize(self) -> dict[str, Any]:\n        return {\n            \"id\": self.id,\n            \"path\": self.path,\n            \"mtime\": self.mtime,\n            \"size\": self.size,\n            \"hash\": self.hash,\n            \"data_mtime\": self.data_mtime,\n            \"dependencies\": self.dependencies,\n            \"suppressed\": self.suppressed,\n            \"imports_ignored\": {str(line): codes for line, codes in self.imports_ignored.items()},\n            \"options\": self.options,\n            \"suppressed_deps_opts\": self.suppressed_deps_opts.hex(),\n            \"dep_prios\": self.dep_prios,\n            \"dep_lines\": self.dep_lines,\n            \"dep_hashes\": [dep.hex() for dep in self.dep_hashes],\n            \"interface_hash\": self.interface_hash.hex(),\n            \"trans_dep_hash\": self.trans_dep_hash.hex(),\n            \"version_id\": self.version_id,\n            \"ignore_all\": self.ignore_all,\n            \"plugin_data\": self.plugin_data,\n        }\n\n    @classmethod\n    def deserialize(cls, meta: dict[str, Any], data_file: str) -> CacheMeta | None:\n        try:\n            return CacheMeta(\n                id=meta[\"id\"],\n                path=meta[\"path\"],\n                mtime=meta[\"mtime\"],\n                size=meta[\"size\"],\n                hash=meta[\"hash\"],\n                dependencies=meta[\"dependencies\"],\n                data_mtime=meta[\"data_mtime\"],\n                data_file=data_file,\n                suppressed=meta[\"suppressed\"],\n                imports_ignored={\n                    int(line): codes for line, codes in meta[\"imports_ignored\"].items()\n                },\n                options=meta[\"options\"],\n                suppressed_deps_opts=bytes.fromhex(meta[\"suppressed_deps_opts\"]),\n                dep_prios=meta[\"dep_prios\"],\n                dep_lines=meta[\"dep_lines\"],\n                dep_hashes=[bytes.fromhex(dep) for dep in meta[\"dep_hashes\"]],\n                interface_hash=bytes.fromhex(meta[\"interface_hash\"]),\n                trans_dep_hash=bytes.fromhex(meta[\"trans_dep_hash\"]),\n                version_id=meta[\"version_id\"],\n                ignore_all=meta[\"ignore_all\"],\n                plugin_data=meta[\"plugin_data\"],\n            )\n        except (KeyError, ValueError):\n            return None\n\n    def write(self, data: WriteBuffer) -> None:\n        write_str(data, self.id)\n        write_str(data, self.path)\n        write_int(data, self.mtime)\n        write_int(data, self.size)\n        write_str(data, self.hash)\n        write_str_list(data, self.dependencies)\n        write_int(data, self.data_mtime)\n        write_str_list(data, self.suppressed)\n        write_int_bare(data, len(self.imports_ignored))\n        for line, codes in self.imports_ignored.items():\n            write_int(data, line)\n            write_str_list(data, codes)\n        write_json(data, self.options)\n        write_bytes(data, self.suppressed_deps_opts)\n        write_int_list(data, self.dep_prios)\n        write_int_list(data, self.dep_lines)\n        write_bytes_list(data, self.dep_hashes)\n        write_bytes(data, self.interface_hash)\n        write_bytes(data, self.trans_dep_hash)\n        write_str(data, self.version_id)\n        write_bool(data, self.ignore_all)\n        # Plugin data may be not a dictionary, so we use\n        # a more generic write_json_value() here.\n        write_json_value(data, self.plugin_data)\n\n    @classmethod\n    def read(cls, data: ReadBuffer, data_file: str) -> CacheMeta | None:\n        try:\n            return CacheMeta(\n                id=read_str(data),\n                path=read_str(data),\n                mtime=read_int(data),\n                size=read_int(data),\n                hash=read_str(data),\n                dependencies=read_str_list(data),\n                data_mtime=read_int(data),\n                data_file=data_file,\n                suppressed=read_str_list(data),\n                imports_ignored={\n                    read_int(data): read_str_list(data) for _ in range(read_int_bare(data))\n                },\n                options=read_json(data),\n                suppressed_deps_opts=read_bytes(data),\n                dep_prios=read_int_list(data),\n                dep_lines=read_int_list(data),\n                dep_hashes=read_bytes_list(data),\n                interface_hash=read_bytes(data),\n                trans_dep_hash=read_bytes(data),\n                version_id=read_str(data),\n                ignore_all=read_bool(data),\n                plugin_data=read_json_value(data),\n            )\n        except (ValueError, AssertionError):\n            return None\n\n\n# Always use this type alias to refer to type tags.\nTag = u8\n\n# Primitives.\nLITERAL_FALSE: Final[Tag] = 0\nLITERAL_TRUE: Final[Tag] = 1\nLITERAL_NONE: Final[Tag] = 2\nLITERAL_INT: Final[Tag] = 3\nLITERAL_STR: Final[Tag] = 4\nLITERAL_BYTES: Final[Tag] = 5\nLITERAL_FLOAT: Final[Tag] = 6\nLITERAL_COMPLEX: Final[Tag] = 7\n\n# Collections.\nLIST_GEN: Final[Tag] = 20\nLIST_INT: Final[Tag] = 21\nLIST_STR: Final[Tag] = 22\nLIST_BYTES: Final[Tag] = 23\nTUPLE_GEN: Final[Tag] = 24\nDICT_STR_GEN: Final[Tag] = 30\nDICT_INT_GEN: Final[Tag] = 31\n\n# Misc classes.\nEXTRA_ATTRS: Final[Tag] = 150\nDT_SPEC: Final[Tag] = 151\n# Four integers representing source file (line, column) range.\nLOCATION: Final[Tag] = 152\n\nEND_TAG: Final[Tag] = 255\n\n\ndef read_literal(data: ReadBuffer, tag: Tag) -> int | str | bool | float:\n    if tag == LITERAL_INT:\n        return read_int_bare(data)\n    elif tag == LITERAL_STR:\n        return read_str_bare(data)\n    elif tag == LITERAL_FALSE:\n        return False\n    elif tag == LITERAL_TRUE:\n        return True\n    elif tag == LITERAL_FLOAT:\n        return read_float_bare(data)\n    assert False, f\"Unknown literal tag {tag}\"\n\n\n# There is an intentional asymmetry between read and write for literals because\n# None and/or complex values are only allowed in some contexts but not in others.\ndef write_literal(data: WriteBuffer, value: int | str | bool | float | complex | None) -> None:\n    if isinstance(value, bool):\n        write_bool(data, value)\n    elif isinstance(value, int):\n        write_tag(data, LITERAL_INT)\n        write_int_bare(data, value)\n    elif isinstance(value, str):\n        write_tag(data, LITERAL_STR)\n        write_str_bare(data, value)\n    elif isinstance(value, float):\n        write_tag(data, LITERAL_FLOAT)\n        write_float_bare(data, value)\n    elif isinstance(value, complex):\n        write_tag(data, LITERAL_COMPLEX)\n        write_float_bare(data, value.real)\n        write_float_bare(data, value.imag)\n    else:\n        write_tag(data, LITERAL_NONE)\n\n\ndef read_int(data: ReadBuffer) -> int:\n    assert read_tag(data) == LITERAL_INT\n    return read_int_bare(data)\n\n\ndef write_int(data: WriteBuffer, value: int) -> None:\n    write_tag(data, LITERAL_INT)\n    write_int_bare(data, value)\n\n\ndef read_str(data: ReadBuffer) -> str:\n    assert read_tag(data) == LITERAL_STR\n    return read_str_bare(data)\n\n\ndef write_str(data: WriteBuffer, value: str) -> None:\n    write_tag(data, LITERAL_STR)\n    write_str_bare(data, value)\n\n\ndef read_bytes(data: ReadBuffer) -> bytes:\n    assert read_tag(data) == LITERAL_BYTES\n    return read_bytes_bare(data)\n\n\ndef write_bytes(data: WriteBuffer, value: bytes) -> None:\n    write_tag(data, LITERAL_BYTES)\n    write_bytes_bare(data, value)\n\n\ndef read_int_opt(data: ReadBuffer) -> int | None:\n    tag = read_tag(data)\n    if tag == LITERAL_NONE:\n        return None\n    assert tag == LITERAL_INT\n    return read_int_bare(data)\n\n\ndef write_int_opt(data: WriteBuffer, value: int | None) -> None:\n    if value is not None:\n        write_tag(data, LITERAL_INT)\n        write_int_bare(data, value)\n    else:\n        write_tag(data, LITERAL_NONE)\n\n\ndef read_str_opt(data: ReadBuffer) -> str | None:\n    tag = read_tag(data)\n    if tag == LITERAL_NONE:\n        return None\n    assert tag == LITERAL_STR\n    return read_str_bare(data)\n\n\ndef write_str_opt(data: WriteBuffer, value: str | None) -> None:\n    if value is not None:\n        write_tag(data, LITERAL_STR)\n        write_str_bare(data, value)\n    else:\n        write_tag(data, LITERAL_NONE)\n\n\ndef read_int_list(data: ReadBuffer) -> list[int]:\n    assert read_tag(data) == LIST_INT\n    size = read_int_bare(data)\n    return [read_int_bare(data) for _ in range(size)]\n\n\ndef write_int_list(data: WriteBuffer, value: list[int]) -> None:\n    write_tag(data, LIST_INT)\n    write_int_bare(data, len(value))\n    for item in value:\n        write_int_bare(data, item)\n\n\ndef read_str_list(data: ReadBuffer) -> list[str]:\n    assert read_tag(data) == LIST_STR\n    size = read_int_bare(data)\n    return [read_str_bare(data) for _ in range(size)]\n\n\ndef write_str_list(data: WriteBuffer, value: Sequence[str]) -> None:\n    write_tag(data, LIST_STR)\n    write_int_bare(data, len(value))\n    for item in value:\n        write_str_bare(data, item)\n\n\ndef read_bytes_list(data: ReadBuffer) -> list[bytes]:\n    assert read_tag(data) == LIST_BYTES\n    size = read_int_bare(data)\n    return [read_bytes_bare(data) for _ in range(size)]\n\n\ndef write_bytes_list(data: WriteBuffer, value: Sequence[bytes]) -> None:\n    write_tag(data, LIST_BYTES)\n    write_int_bare(data, len(value))\n    for item in value:\n        write_bytes_bare(data, item)\n\n\ndef read_str_opt_list(data: ReadBuffer) -> list[str | None]:\n    assert read_tag(data) == LIST_GEN\n    size = read_int_bare(data)\n    return [read_str_opt(data) for _ in range(size)]\n\n\ndef write_str_opt_list(data: WriteBuffer, value: list[str | None]) -> None:\n    write_tag(data, LIST_GEN)\n    write_int_bare(data, len(value))\n    for item in value:\n        write_str_opt(data, item)\n\n\nValue: _TypeAlias = None | int | str | bool\n\n# Our JSON format is somewhat non-standard as we distinguish lists and tuples.\n# This is convenient for some internal things, like mypyc plugin and error serialization.\nJsonValue: _TypeAlias = (\n    Value | list[\"JsonValue\"] | dict[str, \"JsonValue\"] | tuple[\"JsonValue\", ...]\n)\n\n\ndef read_json_value(data: ReadBuffer) -> JsonValue:\n    tag = read_tag(data)\n    if tag == LITERAL_NONE:\n        return None\n    if tag == LITERAL_FALSE:\n        return False\n    if tag == LITERAL_TRUE:\n        return True\n    if tag == LITERAL_INT:\n        return read_int_bare(data)\n    if tag == LITERAL_STR:\n        return read_str_bare(data)\n    if tag == LIST_GEN:\n        size = read_int_bare(data)\n        return [read_json_value(data) for _ in range(size)]\n    if tag == TUPLE_GEN:\n        size = read_int_bare(data)\n        return tuple(read_json_value(data) for _ in range(size))\n    if tag == DICT_STR_GEN:\n        size = read_int_bare(data)\n        return {read_str_bare(data): read_json_value(data) for _ in range(size)}\n    assert False, f\"Invalid JSON tag: {tag}\"\n\n\ndef write_json_value(data: WriteBuffer, value: JsonValue) -> None:\n    if value is None:\n        write_tag(data, LITERAL_NONE)\n    elif isinstance(value, bool):\n        write_bool(data, value)\n    elif isinstance(value, int):\n        write_tag(data, LITERAL_INT)\n        write_int_bare(data, value)\n    elif isinstance(value, str):\n        write_tag(data, LITERAL_STR)\n        write_str_bare(data, value)\n    elif isinstance(value, list):\n        write_tag(data, LIST_GEN)\n        write_int_bare(data, len(value))\n        for val in value:\n            write_json_value(data, val)\n    elif isinstance(value, tuple):\n        write_tag(data, TUPLE_GEN)\n        write_int_bare(data, len(value))\n        for val in value:\n            write_json_value(data, val)\n    elif isinstance(value, dict):\n        write_tag(data, DICT_STR_GEN)\n        write_int_bare(data, len(value))\n        for key in sorted(value):\n            write_str_bare(data, key)\n            write_json_value(data, value[key])\n    else:\n        assert False, f\"Invalid JSON value: {value}\"\n\n\n# These are functions for JSON *dictionaries* specifically. Unfortunately, we\n# must use imprecise types here, because the callers use imprecise types.\ndef read_json(data: ReadBuffer) -> dict[str, Any]:\n    assert read_tag(data) == DICT_STR_GEN\n    size = read_int_bare(data)\n    return {read_str_bare(data): read_json_value(data) for _ in range(size)}\n\n\ndef write_json(data: WriteBuffer, value: dict[str, Any]) -> None:\n    write_tag(data, DICT_STR_GEN)\n    write_int_bare(data, len(value))\n    for key in sorted(value):\n        write_str_bare(data, key)\n        write_json_value(data, value[key])\n\n\ndef write_errors(data: WriteBuffer, errs: list[ErrorTuple]) -> None:\n    write_tag(data, LIST_GEN)\n    write_int_bare(data, len(errs))\n    for path, line, column, end_line, end_column, severity, message, code in errs:\n        write_tag(data, TUPLE_GEN)\n        write_str_opt(data, path)\n        write_int(data, line)\n        write_int(data, column)\n        write_int(data, end_line)\n        write_int(data, end_column)\n        write_str(data, severity)\n        write_str(data, message)\n        write_str_opt(data, code)\n\n\ndef read_errors(data: ReadBuffer) -> list[ErrorTuple]:\n    assert read_tag(data) == LIST_GEN\n    result = []\n    for _ in range(read_int_bare(data)):\n        assert read_tag(data) == TUPLE_GEN\n        result.append(\n            (\n                read_str_opt(data),\n                read_int(data),\n                read_int(data),\n                read_int(data),\n                read_int(data),\n                read_str(data),\n                read_str(data),\n                read_str_opt(data),\n            )\n        )\n    return result\n"
  },
  {
    "path": "mypy/checker.py",
    "content": "\"\"\"Mypy type checker.\"\"\"\n\nfrom __future__ import annotations\n\nimport itertools\nfrom collections import defaultdict\nfrom collections.abc import Callable, Iterable, Iterator, Mapping, Sequence, Set as AbstractSet\nfrom contextlib import ExitStack, contextmanager\nfrom typing import (\n    Final,\n    Generic,\n    Literal,\n    NamedTuple,\n    TypeAlias as _TypeAlias,\n    TypeGuard,\n    TypeVar,\n    cast,\n    overload,\n)\n\nimport mypy.checkexpr\nfrom mypy import errorcodes as codes, join, message_registry, nodes, operators\nfrom mypy.binder import ConditionalTypeBinder, Frame, get_declaration\nfrom mypy.checker_shared import CheckerScope, TypeCheckerSharedApi, TypeRange\nfrom mypy.checker_state import checker_state\nfrom mypy.checkmember import (\n    MemberContext,\n    analyze_class_attribute_access,\n    analyze_instance_member_access,\n    analyze_member_access,\n    is_instance_var,\n)\nfrom mypy.checkpattern import PatternChecker\nfrom mypy.constraints import SUPERTYPE_OF\nfrom mypy.erasetype import (\n    erase_type,\n    erase_typevars,\n    remove_instance_last_known_values,\n    shallow_erase_type_for_equality,\n)\nfrom mypy.errorcodes import TYPE_VAR, UNUSED_AWAITABLE, UNUSED_COROUTINE, ErrorCode\nfrom mypy.errors import (\n    ErrorInfo,\n    Errors,\n    ErrorWatcher,\n    IterationDependentErrors,\n    IterationErrorWatcher,\n    report_internal_error,\n)\nfrom mypy.expandtype import expand_type\nfrom mypy.literals import Key, extract_var_from_literal_hash, literal, literal_hash\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.meet import is_overlapping_erased_types, is_overlapping_types, meet_types\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.messages import (\n    SUGGESTED_TEST_FIXTURES,\n    MessageBuilder,\n    append_invariance_notes,\n    append_union_note,\n    format_type,\n    format_type_bare,\n    format_type_distinctly,\n    make_inferred_type_note,\n    pretty_seq,\n)\nfrom mypy.mro import MroError, calculate_mro\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    ARG_STAR,\n    CONTRAVARIANT,\n    COVARIANT,\n    FUNC_NO_INFO,\n    GDEF,\n    IMPLICITLY_ABSTRACT,\n    INVARIANT,\n    IS_ABSTRACT,\n    LDEF,\n    LITERAL_TYPE,\n    MDEF,\n    NOT_ABSTRACT,\n    SYMBOL_FUNCBASE_TYPES,\n    AssertStmt,\n    AssignmentExpr,\n    AssignmentStmt,\n    AwaitExpr,\n    Block,\n    BreakStmt,\n    BytesExpr,\n    CallExpr,\n    ClassDef,\n    ComparisonExpr,\n    Context,\n    ContinueStmt,\n    Decorator,\n    DelStmt,\n    DictExpr,\n    EllipsisExpr,\n    Expression,\n    ExpressionStmt,\n    FloatExpr,\n    ForStmt,\n    FuncBase,\n    FuncDef,\n    FuncItem,\n    GlobalDecl,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportBase,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListExpr,\n    Lvalue,\n    MatchStmt,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    Node,\n    NonlocalDecl,\n    OperatorAssignmentStmt,\n    OpExpr,\n    OverloadedFuncDef,\n    OverloadPart,\n    PassStmt,\n    PromoteExpr,\n    RaiseStmt,\n    RefExpr,\n    ReturnStmt,\n    SetExpr,\n    SplittingVisitor,\n    StarExpr,\n    Statement,\n    StrExpr,\n    SymbolNode,\n    SymbolTable,\n    SymbolTableNode,\n    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAlias,\n    TypeAliasStmt,\n    TypeInfo,\n    UnaryExpr,\n    Var,\n    WhileStmt,\n    WithStmt,\n    YieldExpr,\n    get_func_def,\n    is_final_node,\n)\nfrom mypy.operators import flip_ops, int_op_to_method, neg_ops\nfrom mypy.options import PRECISE_TUPLE_TYPES, Options\nfrom mypy.patterns import AsPattern, StarredPattern\nfrom mypy.plugin import Plugin\nfrom mypy.plugins import dataclasses as dataclasses_plugin\nfrom mypy.scope import Scope\nfrom mypy.semanal import is_trivial_body, refers_to_fullname, set_callable_name\nfrom mypy.semanal_enum import ENUM_BASES, ENUM_SPECIAL_PROPS\nfrom mypy.semanal_shared import SemanticAnalyzerCoreInterface\nfrom mypy.sharedparse import BINARY_MAGIC_METHODS\nfrom mypy.state import state\nfrom mypy.subtypes import (\n    find_member,\n    infer_class_variances,\n    is_callable_compatible,\n    is_equivalent,\n    is_more_precise,\n    is_proper_subtype,\n    is_same_type,\n    is_subtype,\n    restrict_subtype_away,\n    unify_generic_callable,\n)\nfrom mypy.traverser import TraverserVisitor, all_return_statements, has_return_statement\nfrom mypy.treetransform import TransformVisitor\nfrom mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type, make_optional_type\nfrom mypy.typeops import (\n    bind_self,\n    can_have_shared_disjoint_base,\n    coerce_to_literal,\n    custom_special_method,\n    erase_def_to_union_or_bound,\n    erase_to_bound,\n    erase_to_union_or_bound,\n    false_only,\n    fixup_partial_type,\n    function_type,\n    is_literal_type_like,\n    is_singleton_equality_type,\n    is_singleton_identity_type,\n    make_simplified_union,\n    true_only,\n    try_expanding_sum_type_to_union,\n    try_getting_int_literals_from_type,\n    try_getting_str_literals,\n    try_getting_str_literals_from_type,\n    tuple_fallback,\n    type_object_type,\n)\nfrom mypy.types import (\n    ANY_STRATEGY,\n    MYPYC_NATIVE_INT_NAMES,\n    NOT_IMPLEMENTED_TYPE_NAMES,\n    OVERLOAD_NAMES,\n    AnyType,\n    BoolTypeQuery,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeGuardedType,\n    TypeOfAny,\n    TypeTranslator,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    flatten_nested_unions,\n    get_proper_type,\n    get_proper_types,\n    instance_cache,\n    is_literal_type,\n    is_named_instance,\n)\nfrom mypy.types_utils import is_overlapping_none, remove_optional, store_argument_type, strip_type\nfrom mypy.typetraverser import TypeTraverserVisitor\nfrom mypy.typevars import fill_typevars, fill_typevars_with_any, has_no_typevars\nfrom mypy.util import is_dunder, is_sunder\nfrom mypy.visitor import NodeVisitor\n\nT = TypeVar(\"T\")\n\nDEFAULT_LAST_PASS: Final = 2  # Pass numbers start at 0\n\n# Maximum length of fixed tuple types inferred when narrowing from variadic tuples.\nMAX_PRECISE_TUPLE_SIZE: Final = 8\n\nDeferredNodeType: _TypeAlias = FuncDef | OverloadedFuncDef | Decorator\nFineGrainedDeferredNodeType: _TypeAlias = FuncDef | MypyFile | OverloadedFuncDef\n\n\n# A node which is postponed to be processed during the next pass.\n# In normal mode one can defer functions and methods (also decorated and/or overloaded)\n# but not lambda expressions. Nested functions can't be deferred -- only top-level functions\n# and methods of classes not defined within a function can be deferred.\nclass DeferredNode(NamedTuple):\n    node: DeferredNodeType\n    # And its TypeInfo (for semantic analysis self type handling)\n    active_typeinfo: TypeInfo | None\n\n\n# Same as above, but for fine-grained mode targets. Only top-level functions/methods\n# and module top levels are allowed as such.\nclass FineGrainedDeferredNode(NamedTuple):\n    node: FineGrainedDeferredNodeType\n    active_typeinfo: TypeInfo | None\n\n\n# Data structure returned by find_isinstance_check representing\n# information learned from the truth or falsehood of a condition.  The\n# dict maps nodes representing expressions like 'a[0].x' to their\n# refined types under the assumption that the condition has a\n# particular truth value. A value of None means that the condition can\n# never have that truth value.\n\n# NB: The keys of this dict are nodes in the original source program,\n# which are compared by reference equality--effectively, being *the\n# same* expression of the program, not just two identical expressions\n# (such as two references to the same variable). TODO: it would\n# probably be better to have the dict keyed by the nodes' literal_hash\n# field instead.\nTypeMap: _TypeAlias = dict[Expression, Type]\n\n\n# Keeps track of partial types in a single scope. In fine-grained incremental\n# mode partial types initially defined at the top level cannot be completed in\n# a function, and we use the 'is_function' attribute to enforce this.\nclass PartialTypeScope(NamedTuple):\n    map: dict[Var, Context]\n    is_function: bool\n    is_local: bool\n\n\nclass LocalTypeMap:\n    \"\"\"Store inferred types into a temporary type map (returned).\n\n    This can be used to perform type checking \"experiments\" without\n    affecting exported types (which are used by mypyc).\n    \"\"\"\n\n    def __init__(self, chk: TypeChecker) -> None:\n        self.chk = chk\n\n    def __enter__(self) -> dict[Expression, Type]:\n        temp_type_map: dict[Expression, Type] = {}\n        self.chk._type_maps.append(temp_type_map)\n        return temp_type_map\n\n    def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> Literal[False]:\n        self.chk._type_maps.pop()\n        return False\n\n\nclass TypeChecker(NodeVisitor[None], TypeCheckerSharedApi, SplittingVisitor):\n    \"\"\"Mypy type checker.\n\n    Type check mypy source files that have been semantically analyzed.\n\n    You must create a separate instance for each source file.\n    \"\"\"\n\n    # Are we type checking a stub?\n    is_stub = False\n    # Error message reporter\n    errors: Errors\n    # Utility for generating messages\n    msg: MessageBuilder\n    # Types of type checked nodes. The first item is the \"master\" type\n    # map that will store the final, exported types. Additional items\n    # are temporary type maps used during type inference, and these\n    # will be eventually popped and either discarded or merged into\n    # the master type map.\n    #\n    # Avoid accessing this directly, but prefer the lookup_type(),\n    # has_type() etc. helpers instead.\n    _type_maps: list[dict[Expression, Type]]\n\n    # Helper for managing conditional types\n    binder: ConditionalTypeBinder\n    # Helper for type checking expressions\n    _expr_checker: mypy.checkexpr.ExpressionChecker\n\n    pattern_checker: PatternChecker\n\n    tscope: Scope\n    scope: CheckerScope\n    # Innermost enclosing type\n    type: TypeInfo | None\n    # Stack of function return types\n    return_types: list[Type]\n    # Flags; true for dynamically typed functions\n    dynamic_funcs: list[bool]\n    # Stack of collections of variables with partial types\n    partial_types: list[PartialTypeScope]\n    # Vars for which partial type errors are already reported\n    # (to avoid logically duplicate errors with different error context).\n    partial_reported: set[Var]\n    # Short names of Var nodes whose previous inferred type has been widened via assignment.\n    # NOTE: The names might not be unique, they are only for debugging purposes.\n    widened_vars: list[str]\n    globals: SymbolTable\n    modules: dict[str, MypyFile]\n    # Nodes that couldn't be checked because some types weren't available. We'll run\n    # another pass and try these again.\n    deferred_nodes: list[DeferredNode]\n    # Type checking pass number (0 = first pass)\n    pass_num = 0\n    # Last pass number to take\n    last_pass = DEFAULT_LAST_PASS\n    # Have we deferred the current function? If yes, don't infer additional\n    # types during this pass within the function.\n    current_node_deferred = False\n    # Is this file a typeshed stub?\n    is_typeshed_stub = False\n    options: Options\n    # Used for collecting inferred attribute types so that they can be checked\n    # for consistency.\n    inferred_attribute_types: dict[Var, Type] | None = None\n    # Don't infer partial None types if we are processing assignment from Union\n    no_partial_types: bool = False\n    # Extra module references not detected during semantic analysis (these are rare cases\n    # e.g. access to class-level import via instance).\n    module_refs: set[str]\n    # A map from variable nodes to a snapshot of the frame ids of the\n    # frames that were active when the variable was declared. This can\n    # be used to determine nearest common ancestor frame of a variable's\n    # declaration and the current frame, which lets us determine if it\n    # was declared in a different branch of the same `if` statement\n    # (if that frame is a conditional_frame).\n    var_decl_frames: dict[Var, set[int]]\n\n    # Plugin that provides special type checking rules for specific library\n    # functions such as open(), etc.\n    plugin: Plugin\n\n    # A helper state to produce unique temporary names on demand.\n    _unique_id: int\n    # Fake concrete type used when checking variance\n    _variance_dummy_type: Instance | None\n\n    def __init__(\n        self,\n        errors: Errors,\n        modules: dict[str, MypyFile],\n        options: Options,\n        tree: MypyFile,\n        path: str,\n        plugin: Plugin,\n        per_line_checking_time_ns: dict[int, int],\n    ) -> None:\n        \"\"\"Construct a type checker.\n\n        Use errors to report type check errors.\n        \"\"\"\n        self.errors = errors\n        self.modules = modules\n        self.options = options\n        self.tree = tree\n        self.path = path\n        self.msg = MessageBuilder(errors, modules)\n        self.plugin = plugin\n        self.tscope = Scope()\n        self.scope = CheckerScope(tree)\n        self.binder = ConditionalTypeBinder(options)\n        self.globals = tree.names\n        self.type = None\n        self.return_types = []\n        self.dynamic_funcs = []\n        self.partial_types = []\n        self.partial_reported = set()\n        self.var_decl_frames = {}\n        self.deferred_nodes = []\n        self.widened_vars = []\n        self._type_maps = [{}]\n        self.module_refs = set()\n        self.pass_num = 0\n        self.current_node_deferred = False\n        self.is_stub = tree.is_stub\n        self.is_typeshed_stub = tree.is_typeshed_file(options)\n        self.inferred_attribute_types = None\n        self.allow_constructor_cache = True\n        self.local_type_map = LocalTypeMap(self)\n\n        self.can_skip_diagnostics: Final = (\n            self.options.ignore_errors\n            or self.path in self.msg.errors.ignored_files\n            or (self.options.test_env and self.is_typeshed_stub)\n        )\n        self.recurse_into_functions = True\n        # This internal flag is used to track whether we a currently type-checking\n        # a final declaration (assignment), so that some errors should be suppressed.\n        # Should not be set manually, use get_final_context/enter_final_context instead.\n        # NOTE: we use the context manager to avoid \"threading\" an additional `is_final_def`\n        # argument through various `checker` and `checkmember` functions.\n        self._is_final_def = False\n\n        # Track when we enter an overload implementation. Some checks should not be applied\n        # to the implementation signature when specific overloads are available.\n        # Use `enter_overload_impl` to modify.\n        self.overload_impl_stack: list[OverloadPart] = []\n\n        # This flag is set when we run type-check or attribute access check for the purpose\n        # of giving a note on possibly missing \"await\". It is used to avoid infinite recursion.\n        self.checking_missing_await = False\n\n        # While this is True, allow passing an abstract class where Type[T] is expected.\n        # although this is technically unsafe, this is desirable in some context, for\n        # example when type-checking class decorators.\n        self.allow_abstract_call = False\n\n        # Child checker objects for specific AST node types\n        self._expr_checker = mypy.checkexpr.ExpressionChecker(\n            self, self.msg, self.plugin, per_line_checking_time_ns\n        )\n\n        self.pattern_checker = PatternChecker(self, self.msg, self.plugin, options)\n        self._unique_id = 0\n        self._variance_dummy_type = None\n\n    @property\n    def expr_checker(self) -> mypy.checkexpr.ExpressionChecker:\n        return self._expr_checker\n\n    @property\n    def type_context(self) -> list[Type | None]:\n        return self._expr_checker.type_context\n\n    def reset(self) -> None:\n        \"\"\"Cleanup stale state that might be left over from a typechecking run.\n\n        This allows us to reuse TypeChecker objects in fine-grained\n        incremental mode.\n        \"\"\"\n        # TODO: verify this is still actually worth it over creating new checkers\n        self.partial_reported.clear()\n        self.module_refs.clear()\n        self.binder = ConditionalTypeBinder(self.options)\n        self._type_maps[1:] = []\n        self._type_maps[0].clear()\n        self.expr_checker.reset()\n        self.deferred_nodes = []\n        self.partial_types = []\n        self.inferred_attribute_types = None\n        self.scope = CheckerScope(self.tree)\n\n    def check_first_pass(self) -> None:\n        \"\"\"Type check the entire file, but defer functions with unresolved references.\n\n        Unresolved references are forward references to variables\n        whose types haven't been inferred yet.  They may occur later\n        in the same file or in a different file that's being processed\n        later (usually due to an import cycle).\n\n        Deferred functions will be processed by check_second_pass().\n        \"\"\"\n        self.recurse_into_functions = True\n        with state.strict_optional_set(self.options.strict_optional), checker_state.set(self):\n            self.errors.set_file(\n                self.path, self.tree.fullname, scope=self.tscope, options=self.options\n            )\n            with self.tscope.module_scope(self.tree.fullname):\n                with self.enter_partial_types(), self.binder.top_frame_context():\n                    for d in self.tree.defs:\n                        if self.binder.is_unreachable():\n                            if not self.should_report_unreachable_issues():\n                                break\n                            if not self.is_noop_for_reachability(d):\n                                self.msg.unreachable_statement(d)\n                                break\n                        else:\n                            self.accept(d)\n\n                assert not self.current_node_deferred\n\n                all_ = self.globals.get(\"__all__\")\n                if all_ is not None and all_.type is not None:\n                    all_node = all_.node\n                    assert all_node is not None\n                    seq_str = self.named_generic_type(\n                        \"typing.Sequence\", [self.named_type(\"builtins.str\")]\n                    )\n                    if not is_subtype(all_.type, seq_str):\n                        str_seq_s, all_s = format_type_distinctly(\n                            seq_str, all_.type, options=self.options\n                        )\n                        self.fail(\n                            message_registry.ALL_MUST_BE_SEQ_STR.format(str_seq_s, all_s), all_node\n                        )\n\n    def check_second_pass(\n        self,\n        todo: Sequence[DeferredNode | FineGrainedDeferredNode] | None = None,\n        *,\n        allow_constructor_cache: bool = True,\n    ) -> bool:\n        \"\"\"Run second or following pass of type checking.\n\n        This goes through deferred nodes, returning True if there were any.\n        \"\"\"\n        self.allow_constructor_cache = allow_constructor_cache\n        self.recurse_into_functions = True\n        with state.strict_optional_set(self.options.strict_optional), checker_state.set(self):\n            if not todo and not self.deferred_nodes:\n                return False\n            self.errors.set_file(\n                self.path, self.tree.fullname, scope=self.tscope, options=self.options\n            )\n            with self.tscope.module_scope(self.tree.fullname):\n                self.pass_num += 1\n                if not todo:\n                    todo = self.deferred_nodes\n                else:\n                    assert not self.deferred_nodes\n                self.deferred_nodes = []\n                done: set[DeferredNodeType | FineGrainedDeferredNodeType] = set()\n                for node, active_typeinfo in todo:\n                    if node in done:\n                        continue\n                    # This is useful for debugging:\n                    # print(\"XXX in pass %d, class %s, function %s\" %\n                    #       (self.pass_num, type_name, node.fullname or node.name))\n                    done.add(node)\n                    with ExitStack() as stack:\n                        if active_typeinfo:\n                            stack.enter_context(self.tscope.class_scope(active_typeinfo))\n                            stack.enter_context(self.scope.push_class(active_typeinfo))\n                        self.check_partial(node)\n            return True\n\n    def check_partial(self, node: DeferredNodeType | FineGrainedDeferredNodeType) -> None:\n        self.widened_vars = []\n        if isinstance(node, MypyFile):\n            self.check_top_level(node)\n        else:\n            self.recurse_into_functions = True\n            with self.binder.top_frame_context():\n                self.accept(node)\n\n    def check_top_level(self, node: MypyFile) -> None:\n        \"\"\"Check only the top-level of a module, skipping function definitions.\"\"\"\n        self.recurse_into_functions = False\n        with self.enter_partial_types():\n            with self.binder.top_frame_context():\n                for d in node.defs:\n                    d.accept(self)\n\n        assert not self.current_node_deferred\n        # TODO: Handle __all__\n\n    def defer_node(self, node: DeferredNodeType, enclosing_class: TypeInfo | None) -> None:\n        \"\"\"Defer a node for processing during next type-checking pass.\n\n        Args:\n            node: function/method being deferred\n            enclosing_class: for methods, the class where the method is defined\n        NOTE: this can't handle nested functions/methods.\n        \"\"\"\n        # We don't freeze the entire scope since only top-level functions and methods\n        # can be deferred. Only module/class level scope information is needed.\n        # Module-level scope information is preserved in the TypeChecker instance.\n        self.deferred_nodes.append(DeferredNode(node, enclosing_class))\n\n    def handle_cannot_determine_type(self, name: str, context: Context) -> None:\n        node = self.scope.top_level_function()\n        if self.pass_num < self.last_pass and isinstance(node, FuncDef):\n            # Don't report an error yet. Just defer. Note that we don't defer\n            # lambdas because they are coupled to the surrounding function\n            # through the binder and the inferred type of the lambda, so it\n            # would get messy.\n            enclosing_class = self.scope.enclosing_class(node)\n            self.defer_node(node, enclosing_class)\n            # Set a marker so that we won't infer additional types in this\n            # function. Any inferred types could be bogus, because there's at\n            # least one type that we don't know.\n            self.current_node_deferred = True\n        else:\n            self.msg.cannot_determine_type(name, context)\n\n    def accept(self, stmt: Statement) -> None:\n        \"\"\"Type check a node in the given type context.\"\"\"\n        try:\n            stmt.accept(self)\n        except Exception as err:\n            report_internal_error(err, self.errors.file, stmt.line, self.errors, self.options)\n\n    def accept_loop(\n        self,\n        body: Statement,\n        else_body: Statement | None = None,\n        *,\n        exit_condition: Expression | None = None,\n        on_enter_body: Callable[[], None] | None = None,\n    ) -> None:\n        \"\"\"Repeatedly type check a loop body until the frame doesn't change.\"\"\"\n\n        # The outer frame accumulates the results of all iterations:\n        with self.binder.frame_context(can_skip=False, conditional_frame=True):\n            # Check for potential decreases in the number of partial types so as not to stop the\n            # iteration too early:\n            partials_old = sum(len(pts.map) for pts in self.partial_types)\n            # Check if assignment widened the inferred type of a variable; in this case we\n            # need to iterate again (we only do one extra iteration, since this could go\n            # on without bound otherwise)\n            widened_old = len(self.widened_vars)\n\n            iter_errors = IterationDependentErrors()\n            iter = 1\n            while True:\n                with self.binder.frame_context(can_skip=True, break_frame=2, continue_frame=1):\n                    if on_enter_body is not None:\n                        on_enter_body()\n\n                    with IterationErrorWatcher(self.msg.errors, iter_errors):\n                        self.accept(body)\n\n                partials_new = sum(len(pts.map) for pts in self.partial_types)\n                widened_new = len(self.widened_vars)\n                # Perform multiple iterations if something changed that might affect\n                # inferred types. Also limit the number of iterations. The limits are\n                # somewhat arbitrary, but they were chosen to 1) avoid slowdown from\n                # multiple iterations in common cases and 2) support common, valid use\n                # cases. Limits are needed since otherwise we could infer infinitely\n                # complex types.\n                if (\n                    (partials_new == partials_old)\n                    and (not self.binder.last_pop_changed or iter > 3)\n                    and (widened_new == widened_old or iter > 1)\n                ):\n                    break\n                partials_old = partials_new\n                widened_old = widened_new\n                iter += 1\n                if iter == 20:\n                    raise RuntimeError(\"Too many iterations when checking a loop\")\n\n            self.msg.iteration_dependent_errors(iter_errors)\n\n            # If exit_condition is set, assume it must be False on exit from the loop:\n            if exit_condition:\n                _, else_map = self.find_isinstance_check(exit_condition)\n                self.push_type_map(else_map)\n\n            # Check the else body:\n            if else_body:\n                self.accept(else_body)\n\n    #\n    # Definitions\n    #\n\n    def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:\n        # If a function/method can infer variable types, it should be processed as part\n        # of the module top level (i.e. module interface).\n        if not self.recurse_into_functions and not defn.def_or_infer_vars:\n            return\n        with self.tscope.function_scope(defn), self.set_recurse_into_functions():\n            self._visit_overloaded_func_def(defn)\n\n    def _visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:\n        num_abstract = 0\n        if not defn.items:\n            # In this case we have already complained about none of these being\n            # valid overloads.\n            return\n        if len(defn.items) == 1:\n            self.fail(message_registry.MULTIPLE_OVERLOADS_REQUIRED, defn)\n\n        if defn.is_property:\n            # HACK: Infer the type of the property.\n            assert isinstance(defn.items[0], Decorator)\n            self.visit_decorator(defn.items[0])\n            if defn.items[0].var.is_settable_property:\n                # Perform a reduced visit just to infer the actual setter type.\n                self.visit_decorator_inner(defn.setter, skip_first_item=True)\n                setter_type = defn.setter.var.type\n                # Check if the setter can accept two positional arguments.\n                any_type = AnyType(TypeOfAny.special_form)\n                fallback_setter_type = CallableType(\n                    arg_types=[any_type, any_type],\n                    arg_kinds=[ARG_POS, ARG_POS],\n                    arg_names=[None, None],\n                    ret_type=any_type,\n                    fallback=self.named_type(\"builtins.function\"),\n                )\n                if setter_type and not is_subtype(setter_type, fallback_setter_type):\n                    self.fail(\"Invalid property setter signature\", defn.setter.func)\n                setter_type = self.extract_callable_type(setter_type, defn)\n                if not isinstance(setter_type, CallableType) or len(setter_type.arg_types) != 2:\n                    # TODO: keep precise type for callables with tricky but valid signatures.\n                    setter_type = fallback_setter_type\n                defn.items[0].var.setter_type = setter_type\n                if isinstance(defn.type, Overloaded):\n                    # Update legacy property type for decorated properties.\n                    getter_type = self.extract_callable_type(defn.items[0].var.type, defn)\n                    if getter_type is not None:\n                        getter_type.definition = defn.items[0]\n                        defn.type.items[0] = getter_type\n        for i, fdef in enumerate(defn.items):\n            assert isinstance(fdef, Decorator)\n            if defn.is_property:\n                assert isinstance(defn.items[0], Decorator)\n                settable = defn.items[0].var.is_settable_property\n                # Do not visit the second time the items we checked above.\n                if (settable and i > 1) or (not settable and i > 0):\n                    self.check_func_item(fdef.func, name=fdef.func.name, allow_empty=True)\n            else:\n                # Perform full check for real overloads to infer type of all decorated\n                # overload variants.\n                self.visit_decorator_inner(fdef, allow_empty=True)\n            if fdef.func.abstract_status in (IS_ABSTRACT, IMPLICITLY_ABSTRACT):\n                num_abstract += 1\n        if num_abstract not in (0, len(defn.items)):\n            self.fail(message_registry.INCONSISTENT_ABSTRACT_OVERLOAD, defn)\n        if defn.impl:\n            with self.enter_overload_impl(defn.impl):\n                defn.impl.accept(self)\n        if not defn.is_property:\n            self.check_overlapping_overloads(defn)\n            if defn.type is None:\n                item_types = []\n                for item in defn.items:\n                    assert isinstance(item, Decorator)\n                    item_type = self.extract_callable_type(item.var.type, item)\n                    if item_type is not None:\n                        item_type.definition = item\n                        item_types.append(item_type)\n                if item_types:\n                    defn.type = Overloaded(item_types)\n        elif defn.type is None:\n            # We store the getter type as an overall overload type, as some\n            # code paths are getting property type this way.\n            assert isinstance(defn.items[0], Decorator)\n            var_type = self.extract_callable_type(defn.items[0].var.type, defn)\n            if not isinstance(var_type, CallableType):\n                # Construct a fallback type, invalid types should be already reported.\n                any_type = AnyType(TypeOfAny.special_form)\n                var_type = CallableType(\n                    arg_types=[any_type],\n                    arg_kinds=[ARG_POS],\n                    arg_names=[None],\n                    ret_type=any_type,\n                    fallback=self.named_type(\"builtins.function\"),\n                )\n            defn.type = Overloaded([var_type])\n        # Check override validity after we analyzed current definition.\n        if not self.can_skip_diagnostics and defn.info:\n            found_method_base_classes = self.check_method_override(defn)\n            if (\n                defn.is_explicit_override\n                and not found_method_base_classes\n                and found_method_base_classes is not None\n                # If the class has Any fallback, we can't be certain that a method\n                # is really missing - it might come from unfollowed import.\n                and not defn.info.fallback_to_any\n            ):\n                self.msg.no_overridable_method(defn.name, defn)\n            self.check_explicit_override_decorator(defn, found_method_base_classes, defn.impl)\n            self.check_inplace_operator_method(defn)\n\n    @contextmanager\n    def enter_overload_impl(self, impl: OverloadPart) -> Iterator[None]:\n        self.overload_impl_stack.append(impl)\n        try:\n            yield\n        finally:\n            assert self.overload_impl_stack.pop() == impl\n\n    def extract_callable_type(self, inner_type: Type | None, ctx: Context) -> CallableType | None:\n        \"\"\"Get type as seen by an overload item caller.\"\"\"\n        inner_type = get_proper_type(inner_type)\n        outer_type: FunctionLike | None = None\n        if inner_type is None or isinstance(inner_type, AnyType):\n            return None\n        if isinstance(inner_type, TypeVarLikeType):\n            inner_type = get_proper_type(inner_type.upper_bound)\n        if isinstance(inner_type, TypeType):\n            inner_type = get_proper_type(\n                self.expr_checker.analyze_type_type_callee(inner_type.item, ctx)\n            )\n\n        if isinstance(inner_type, FunctionLike):\n            outer_type = inner_type\n        elif isinstance(inner_type, Instance):\n            inner_call = get_proper_type(\n                analyze_member_access(\n                    name=\"__call__\",\n                    typ=inner_type,\n                    context=ctx,\n                    is_lvalue=False,\n                    is_super=False,\n                    is_operator=True,\n                    original_type=inner_type,\n                    chk=self,\n                )\n            )\n            if isinstance(inner_call, FunctionLike):\n                outer_type = inner_call\n        elif isinstance(inner_type, UnionType):\n            union_type = make_simplified_union(inner_type.items)\n            if isinstance(union_type, UnionType):\n                items = []\n                for item in union_type.items:\n                    callable_item = self.extract_callable_type(item, ctx)\n                    if callable_item is None:\n                        break\n                    items.append(callable_item)\n                else:\n                    joined_type = get_proper_type(join.join_type_list(items))\n                    if isinstance(joined_type, FunctionLike):\n                        outer_type = joined_type\n            else:\n                return self.extract_callable_type(union_type, ctx)\n\n        if outer_type is None:\n            self.msg.not_callable(inner_type, ctx)\n            return None\n        if isinstance(outer_type, Overloaded):\n            return None\n\n        assert isinstance(outer_type, CallableType)\n        return outer_type\n\n    def check_overlapping_overloads(self, defn: OverloadedFuncDef) -> None:\n        # At this point we should have set the impl already, and all remaining\n        # items are decorators\n\n        if self.can_skip_diagnostics:\n            return\n\n        # Compute some info about the implementation (if it exists) for use below\n        impl_type: CallableType | None = None\n        if defn.impl:\n            if isinstance(defn.impl, FuncDef):\n                inner_type: Type | None = defn.impl.type\n            elif isinstance(defn.impl, Decorator):\n                inner_type = defn.impl.var.type\n            else:\n                assert False, \"Impl isn't the right type\"\n\n            # This can happen if we've got an overload with a different\n            # decorator or if the implementation is untyped -- we gave up on the types.\n            impl_type = self.extract_callable_type(inner_type, defn.impl)\n\n        is_descriptor_get = defn.info and defn.name == \"__get__\"\n        for i, item in enumerate(defn.items):\n            assert isinstance(item, Decorator)\n            sig1 = self.extract_callable_type(item.var.type, item)\n            if sig1 is None:\n                continue\n\n            for j, item2 in enumerate(defn.items[i + 1 :]):\n                assert isinstance(item2, Decorator)\n                sig2 = self.extract_callable_type(item2.var.type, item2)\n                if sig2 is None:\n                    continue\n\n                if not are_argument_counts_overlapping(sig1, sig2):\n                    continue\n\n                if overload_can_never_match(sig1, sig2):\n                    self.msg.overloaded_signature_will_never_match(i + 1, i + j + 2, item2.func)\n                elif not is_descriptor_get:\n                    # Note: we force mypy to check overload signatures in strict-optional mode\n                    # so we don't incorrectly report errors when a user tries typing an overload\n                    # that happens to have a 'if the argument is None' fallback.\n                    #\n                    # For example, the following is fine in strict-optional mode but would throw\n                    # the unsafe overlap error when strict-optional is disabled:\n                    #\n                    #     @overload\n                    #     def foo(x: None) -> int: ...\n                    #     @overload\n                    #     def foo(x: str) -> str: ...\n                    #\n                    # See Python 2's map function for a concrete example of this kind of overload.\n                    current_class = self.scope.active_class()\n                    type_vars = current_class.defn.type_vars if current_class else []\n                    with state.strict_optional_set(True):\n                        if is_unsafe_overlapping_overload_signatures(sig1, sig2, type_vars):\n                            flip_note = (\n                                j == 0\n                                and not is_unsafe_overlapping_overload_signatures(\n                                    sig2, sig1, type_vars\n                                )\n                                and not overload_can_never_match(sig2, sig1)\n                            )\n                            self.msg.overloaded_signatures_overlap(\n                                i + 1, i + j + 2, flip_note, item.func\n                            )\n\n            if impl_type is not None:\n                assert defn.impl is not None\n\n                # This is what we want from implementation, it should accept all arguments\n                # of an overload, but the return types should go the opposite way.\n                if is_callable_compatible(\n                    impl_type,\n                    sig1,\n                    is_compat=is_subtype,\n                    is_proper_subtype=False,\n                    is_compat_return=lambda l, r: is_subtype(r, l),\n                ):\n                    continue\n                # If the above check didn't work, we repeat some key steps in\n                # is_callable_compatible() to give a better error message.\n\n                # We perform a unification step that's very similar to what\n                # 'is_callable_compatible' does -- the only difference is that\n                # we check and see if the impl_type's return value is a\n                # *supertype* of the overload alternative, not a *subtype*.\n                #\n                # This is to match the direction the implementation's return\n                # needs to be compatible in.\n                if impl_type.variables:\n                    impl: CallableType | None = unify_generic_callable(\n                        # Normalize both before unifying\n                        impl_type.with_unpacked_kwargs(),\n                        sig1.with_unpacked_kwargs(),\n                        ignore_return=False,\n                        return_constraint_direction=SUPERTYPE_OF,\n                    )\n                    if impl is None:\n                        self.msg.overloaded_signatures_typevar_specific(i + 1, defn.impl)\n                        continue\n                else:\n                    impl = impl_type\n\n                # Prevent extra noise from inconsistent use of @classmethod by copying\n                # the first arg from the method being checked against.\n                if sig1.arg_types and defn.info:\n                    impl = impl.copy_modified(arg_types=[sig1.arg_types[0]] + impl.arg_types[1:])\n\n                # Is the overload alternative's arguments subtypes of the implementation's?\n                if not is_callable_compatible(\n                    impl, sig1, is_compat=is_subtype, is_proper_subtype=False, ignore_return=True\n                ):\n                    self.msg.overloaded_signatures_param_specific(i + 1, defn.impl)\n\n                # Is the overload alternative's return type a subtype of the implementation's?\n                if not (\n                    is_subtype(sig1.ret_type, impl.ret_type)\n                    or is_subtype(impl.ret_type, sig1.ret_type)\n                ):\n                    self.msg.overloaded_signatures_ret_specific(i + 1, defn.impl)\n\n    # Here's the scoop about generators and coroutines.\n    #\n    # There are two kinds of generators: classic generators (functions\n    # with `yield` or `yield from` in the body) and coroutines\n    # (functions declared with `async def`).  The latter are specified\n    # in PEP 492 and only available in Python >= 3.5.\n    #\n    # Classic generators can be parameterized with three types:\n    # - ty is the Yield type (the type of y in `yield y`)\n    # - tc is the type reCeived by yield (the type of c in `c = yield`).\n    # - tr is the Return type (the type of r in `return r`)\n    #\n    # A classic generator must define a return type that's either\n    # `Generator[ty, tc, tr]`, Iterator[ty], or Iterable[ty] (or\n    # object or Any).  If tc/tr are not given, both are None.\n    #\n    # A coroutine must define a return type corresponding to tr; the\n    # other two are unconstrained.  The \"external\" return type (seen\n    # by the caller) is Awaitable[tr].\n    #\n    # In addition, there's the synthetic type AwaitableGenerator: it\n    # inherits from both Awaitable and Generator and can be used both\n    # in `yield from` and in `await`.  This type is set automatically\n    # for functions decorated with `@types.coroutine` or\n    # `@asyncio.coroutine`.  Its single parameter corresponds to tr.\n    #\n    # PEP 525 adds a new type, the asynchronous generator, which was\n    # first released in Python 3.6. Async generators are `async def`\n    # functions that can also `yield` values. They can be parameterized\n    # with two types, ty and tc, because they cannot return a value.\n    #\n    # There are several useful methods, each taking a type t and a\n    # flag c indicating whether it's for a generator or coroutine:\n    #\n    # - is_generator_return_type(t, c) returns whether t is a Generator,\n    #   Iterator, Iterable (if not c), or Awaitable (if c), or\n    #   AwaitableGenerator (regardless of c).\n    # - is_async_generator_return_type(t) returns whether t is an\n    #   AsyncGenerator.\n    # - get_generator_yield_type(t, c) returns ty.\n    # - get_generator_receive_type(t, c) returns tc.\n    # - get_generator_return_type(t, c) returns tr.\n\n    def is_generator_return_type(self, typ: Type, is_coroutine: bool) -> bool:\n        \"\"\"Is `typ` a valid type for a generator/coroutine?\n\n        True if `typ` is a *supertype* of Generator or Awaitable.\n        Also true it it's *exactly* AwaitableGenerator (modulo type parameters).\n        \"\"\"\n        typ = get_proper_type(typ)\n        if is_coroutine:\n            # This means we're in Python 3.5 or later.\n            at = self.named_generic_type(\"typing.Awaitable\", [AnyType(TypeOfAny.special_form)])\n            if is_subtype(at, typ):\n                return True\n        else:\n            any_type = AnyType(TypeOfAny.special_form)\n            gt = self.named_generic_type(\"typing.Generator\", [any_type, any_type, any_type])\n            if is_subtype(gt, typ):\n                return True\n        return isinstance(typ, Instance) and typ.type.fullname == \"typing.AwaitableGenerator\"\n\n    def is_async_generator_return_type(self, typ: Type) -> bool:\n        \"\"\"Is `typ` a valid type for an async generator?\n\n        True if `typ` is a supertype of AsyncGenerator.\n        \"\"\"\n        try:\n            any_type = AnyType(TypeOfAny.special_form)\n            agt = self.named_generic_type(\"typing.AsyncGenerator\", [any_type, any_type])\n        except KeyError:\n            # we're running on a version of typing that doesn't have AsyncGenerator yet\n            return False\n        return is_subtype(agt, typ)\n\n    def get_generator_yield_type(self, return_type: Type, is_coroutine: bool) -> Type:\n        \"\"\"Given the declared return type of a generator (t), return the type it yields (ty).\"\"\"\n        return_type = get_proper_type(return_type)\n\n        if isinstance(return_type, AnyType):\n            return AnyType(TypeOfAny.from_another_any, source_any=return_type)\n        elif isinstance(return_type, UnionType):\n            return make_simplified_union(\n                [self.get_generator_yield_type(item, is_coroutine) for item in return_type.items]\n            )\n        elif not self.is_generator_return_type(\n            return_type, is_coroutine\n        ) and not self.is_async_generator_return_type(return_type):\n            # If the function doesn't have a proper Generator (or\n            # Awaitable) return type, anything is permissible.\n            return AnyType(TypeOfAny.from_error)\n        elif not isinstance(return_type, Instance):\n            # Same as above, but written as a separate branch so the typechecker can understand.\n            return AnyType(TypeOfAny.from_error)\n        elif return_type.type.fullname == \"typing.Awaitable\":\n            # Awaitable: ty is Any.\n            return AnyType(TypeOfAny.special_form)\n        elif return_type.args:\n            # AwaitableGenerator, Generator, AsyncGenerator, Iterator, or Iterable; ty is args[0].\n            ret_type = return_type.args[0]\n            # TODO not best fix, better have dedicated yield token\n            return ret_type\n        else:\n            # If the function's declared supertype of Generator has no type\n            # parameters (i.e. is `object`), then the yielded values can't\n            # be accessed so any type is acceptable.  IOW, ty is Any.\n            # (However, see https://github.com/python/mypy/issues/1933)\n            return AnyType(TypeOfAny.special_form)\n\n    def get_generator_receive_type(self, return_type: Type, is_coroutine: bool) -> Type:\n        \"\"\"Given a declared generator return type (t), return the type its yield receives (tc).\"\"\"\n        return_type = get_proper_type(return_type)\n\n        if isinstance(return_type, AnyType):\n            return AnyType(TypeOfAny.from_another_any, source_any=return_type)\n        elif isinstance(return_type, UnionType):\n            return make_simplified_union(\n                [self.get_generator_receive_type(item, is_coroutine) for item in return_type.items]\n            )\n        elif not self.is_generator_return_type(\n            return_type, is_coroutine\n        ) and not self.is_async_generator_return_type(return_type):\n            # If the function doesn't have a proper Generator (or\n            # Awaitable) return type, anything is permissible.\n            return AnyType(TypeOfAny.from_error)\n        elif not isinstance(return_type, Instance):\n            # Same as above, but written as a separate branch so the typechecker can understand.\n            return AnyType(TypeOfAny.from_error)\n        elif return_type.type.fullname == \"typing.Awaitable\":\n            # Awaitable, AwaitableGenerator: tc is Any.\n            return AnyType(TypeOfAny.special_form)\n        elif (\n            return_type.type.fullname in (\"typing.Generator\", \"typing.AwaitableGenerator\")\n            and len(return_type.args) >= 3\n        ):\n            # Generator: tc is args[1].\n            return return_type.args[1]\n        elif return_type.type.fullname == \"typing.AsyncGenerator\" and len(return_type.args) >= 2:\n            return return_type.args[1]\n        else:\n            # `return_type` is a supertype of Generator, so callers won't be able to send it\n            # values.  IOW, tc is None.\n            return NoneType()\n\n    def get_coroutine_return_type(self, return_type: Type) -> Type:\n        return_type = get_proper_type(return_type)\n        if isinstance(return_type, AnyType):\n            return AnyType(TypeOfAny.from_another_any, source_any=return_type)\n        assert isinstance(return_type, Instance), \"Should only be called on coroutine functions.\"\n        # Note: return type is the 3rd type parameter of Coroutine.\n        return return_type.args[2]\n\n    def get_generator_return_type(self, return_type: Type, is_coroutine: bool) -> Type:\n        \"\"\"Given the declared return type of a generator (t), return the type it returns (tr).\"\"\"\n        return_type = get_proper_type(return_type)\n\n        if isinstance(return_type, AnyType):\n            return AnyType(TypeOfAny.from_another_any, source_any=return_type)\n        elif isinstance(return_type, UnionType):\n            return make_simplified_union(\n                [self.get_generator_return_type(item, is_coroutine) for item in return_type.items]\n            )\n        elif not self.is_generator_return_type(return_type, is_coroutine):\n            # If the function doesn't have a proper Generator (or\n            # Awaitable) return type, anything is permissible.\n            return AnyType(TypeOfAny.from_error)\n        elif not isinstance(return_type, Instance):\n            # Same as above, but written as a separate branch so the typechecker can understand.\n            return AnyType(TypeOfAny.from_error)\n        elif return_type.type.fullname == \"typing.Awaitable\" and len(return_type.args) == 1:\n            # Awaitable: tr is args[0].\n            return return_type.args[0]\n        elif (\n            return_type.type.fullname in (\"typing.Generator\", \"typing.AwaitableGenerator\")\n            and len(return_type.args) >= 3\n        ):\n            # AwaitableGenerator, Generator: tr is args[2].\n            return return_type.args[2]\n        else:\n            # We have a supertype of Generator (Iterator, Iterable, object)\n            # Treat `Iterator[X]` as a shorthand for `Generator[X, Any, None]`.\n            return NoneType()\n\n    def visit_func_def(self, defn: FuncDef) -> None:\n        if not self.recurse_into_functions and not defn.def_or_infer_vars:\n            return\n        with self.tscope.function_scope(defn), self.set_recurse_into_functions():\n            self.check_func_item(defn, name=defn.name)\n            if not self.can_skip_diagnostics:\n                if defn.info:\n                    if not defn.is_overload and not defn.is_decorated:\n                        # If the definition is the implementation for an\n                        # overload, the legality of the override has already\n                        # been typechecked, and decorated methods will be\n                        # checked when the decorator is.\n                        found_method_base_classes = self.check_method_override(defn)\n                        self.check_explicit_override_decorator(defn, found_method_base_classes)\n                    self.check_inplace_operator_method(defn)\n            if defn.original_def:\n                # Override previous definition.\n                new_type = self.function_type(defn)\n                self.check_func_def_override(defn, new_type)\n\n    def check_func_item(\n        self,\n        defn: FuncItem,\n        type_override: CallableType | None = None,\n        name: str | None = None,\n        allow_empty: bool = False,\n    ) -> None:\n        \"\"\"Type check a function.\n\n        If type_override is provided, use it as the function type.\n        \"\"\"\n        self.dynamic_funcs.append(defn.is_dynamic() and not type_override)\n\n        enclosing_node_deferred = self.current_node_deferred\n        with self.enter_partial_types(is_function=True):\n            typ = self.function_type(defn)\n            if type_override:\n                typ = type_override.copy_modified(line=typ.line, column=typ.column)\n            if isinstance(typ, CallableType):\n                with self.enter_attribute_inference_context():\n                    self.check_func_def(defn, typ, name, allow_empty)\n            else:\n                raise RuntimeError(\"Not supported\")\n\n        self.dynamic_funcs.pop()\n        self.current_node_deferred = enclosing_node_deferred\n\n        if name == \"__exit__\":\n            self.check__exit__return_type(defn)\n        # TODO: the following logic should move to the dataclasses plugin\n        #  https://github.com/python/mypy/issues/15515\n        if name == \"__post_init__\":\n            if dataclasses_plugin.is_processed_dataclass(defn.info):\n                dataclasses_plugin.check_post_init(self, defn, defn.info)\n\n    def check_func_def_override(self, defn: FuncDef, new_type: FunctionLike) -> None:\n        assert defn.original_def is not None\n        if isinstance(defn.original_def, FuncDef):\n            # Function definition overrides function definition.\n            old_type = self.function_type(defn.original_def)\n            if not is_same_type(new_type, old_type):\n                self.msg.incompatible_conditional_function_def(defn, old_type, new_type)\n        else:\n            # Function definition overrides a variable initialized via assignment or a\n            # decorated function.\n            orig_type = defn.original_def.type\n            if orig_type is None:\n                # If other branch is unreachable, we don't type check it and so we might\n                # not have a type for the original definition\n                return\n            if isinstance(orig_type, PartialType):\n                if orig_type.type is None:\n                    # Ah this is a partial type. Give it the type of the function.\n                    orig_def = defn.original_def\n                    if isinstance(orig_def, Decorator):\n                        var = orig_def.var\n                    else:\n                        var = orig_def\n                    partial_types = self.find_partial_types(var)\n                    if partial_types is not None:\n                        var.type = new_type\n                        del partial_types[var]\n                else:\n                    # Trying to redefine something like partial empty list as function.\n                    self.fail(message_registry.INCOMPATIBLE_REDEFINITION, defn)\n            else:\n                name_expr = NameExpr(defn.name)\n                name_expr.node = defn.original_def\n                self.binder.assign_type(name_expr, new_type, orig_type)\n                self.check_subtype(\n                    new_type,\n                    orig_type,\n                    defn,\n                    message_registry.INCOMPATIBLE_REDEFINITION,\n                    \"redefinition with type\",\n                    \"original type\",\n                )\n\n    @contextmanager\n    def enter_attribute_inference_context(self) -> Iterator[None]:\n        old_types = self.inferred_attribute_types\n        self.inferred_attribute_types = {}\n        yield None\n        self.inferred_attribute_types = old_types\n\n    def check_func_def(\n        self, defn: FuncItem, typ: CallableType, name: str | None, allow_empty: bool = False\n    ) -> None:\n        \"\"\"Type check a function definition.\"\"\"\n        # Expand type variables with value restrictions to ordinary types.\n        self.check_typevar_defaults(typ.variables)\n        expanded = self.expand_typevars(defn, typ)\n        original_typ = typ\n        for item, typ in expanded:\n            old_binder = self.binder\n            self.binder = ConditionalTypeBinder(self.options)\n            with self.binder.top_frame_context():\n                defn.expanded.append(item)\n\n                # We may be checking a function definition or an anonymous\n                # function. In the first case, set up another reference with the\n                # precise type.\n                if not self.can_skip_diagnostics:\n                    self.check_funcdef_item(item, typ, name, defn=defn, original_typ=original_typ)\n\n                # Fix the type if decorated with `@types.coroutine` or `@asyncio.coroutine`.\n                if defn.is_awaitable_coroutine:\n                    # Update the return type to AwaitableGenerator.\n                    # (This doesn't exist in typing.py, only in typing.pyi.)\n                    t = typ.ret_type\n                    c = defn.is_coroutine\n                    ty = self.get_generator_yield_type(t, c)\n                    tc = self.get_generator_receive_type(t, c)\n                    if c:\n                        tr = self.get_coroutine_return_type(t)\n                    else:\n                        tr = self.get_generator_return_type(t, c)\n                    ret_type = self.named_generic_type(\n                        \"typing.AwaitableGenerator\", [ty, tc, tr, t]\n                    )\n                    typ = typ.copy_modified(ret_type=ret_type)\n                    defn.type = typ\n\n                # Push return type.\n                self.return_types.append(typ.ret_type)\n\n                with self.scope.push_function(defn):\n                    # We temporary push the definition to get the self type as\n                    # visible from *inside* of this function/method.\n                    ref_type: Type | None = self.scope.active_self_type()\n\n                if typ.type_is:\n                    arg_index = 0\n                    # For methods and classmethods, we want the second parameter\n                    if ref_type is not None and defn.has_self_or_cls_argument:\n                        arg_index = 1\n                    if arg_index < len(typ.arg_types) and not is_subtype(\n                        typ.type_is, typ.arg_types[arg_index]\n                    ):\n                        self.fail(\n                            message_registry.NARROWED_TYPE_NOT_SUBTYPE.format(\n                                format_type(typ.type_is, self.options),\n                                format_type(typ.arg_types[arg_index], self.options),\n                            ),\n                            item,\n                        )\n\n                # Store argument types.\n                found_self = False\n                if isinstance(defn, FuncDef) and not defn.is_decorated:\n                    found_self = self.require_correct_self_argument(typ, defn)\n                for i in range(len(typ.arg_types)):\n                    arg_type = typ.arg_types[i]\n                    if isinstance(arg_type, TypeVarType):\n                        # Refuse covariant parameter type variables\n                        # TODO: check recursively for inner type variables\n                        if (\n                            arg_type.variance == COVARIANT\n                            and defn.name not in (\"__init__\", \"__new__\", \"__post_init__\")\n                            and not is_private(defn.name)  # private methods are not inherited\n                            and (i != 0 or not found_self)\n                        ):\n                            ctx: Context = arg_type\n                            if ctx.line < 0:\n                                ctx = typ\n                            self.fail(message_registry.FUNCTION_PARAMETER_CANNOT_BE_COVARIANT, ctx)\n                    # Need to store arguments again for the expanded item.\n                    store_argument_type(item, i, typ, self.named_generic_type)\n\n                # Type check initialization expressions.\n                body_is_trivial = is_trivial_body(defn.body)\n                if not self.can_skip_diagnostics:\n                    self.check_default_params(item, body_is_trivial)\n\n            # Type check body in a new scope.\n            with self.binder.top_frame_context():\n                # Copy some type narrowings from an outer function when it seems safe enough\n                # (i.e. we can't find an assignment that might change the type of the\n                # variable afterwards).\n                new_frame: Frame | None = None\n                for frame in old_binder.frames:\n                    for key, narrowed_type in frame.types.items():\n                        key_var = extract_var_from_literal_hash(key)\n                        if key_var is not None and not self.is_var_redefined_in_outer_context(\n                            key_var, defn.line\n                        ):\n                            # It seems safe to propagate the type narrowing to a nested scope.\n                            if new_frame is None:\n                                new_frame = self.binder.push_frame()\n                            new_frame.types[key] = narrowed_type\n                            self.binder.declarations[key] = old_binder.declarations[key]\n\n                if self.options.allow_redefinition_new and not self.is_stub:\n                    # Add formal argument types to the binder.\n                    for arg in defn.arguments:\n                        # TODO: Add these directly using a fast path (possibly \"put\")\n                        v = arg.variable\n                        if v.type is not None:\n                            n = NameExpr(v.name)\n                            n.node = v\n                            self.binder.assign_type(n, v.type, v.type)\n\n                with self.scope.push_function(defn):\n                    # We suppress reachability warnings for empty generator functions\n                    # (return; yield) which have a \"yield\" that's unreachable by definition\n                    # since it's only there to promote the function into a generator function.\n                    #\n                    # We also suppress reachability warnings when we use TypeVars with value\n                    # restrictions: we only want to report a warning if a certain statement is\n                    # marked as being suppressed in *all* of the expansions, but we currently\n                    # have no good way of doing this.\n                    #\n                    # TODO: Find a way of working around this limitation\n                    if _is_empty_generator_function(item) or len(expanded) >= 2:\n                        self.binder.suppress_unreachable_warnings()\n                    # When checking a third-party library, we can skip function body,\n                    # if during semantic analysis we found that there are no attributes\n                    # defined via self here.\n                    if (\n                        not self.can_skip_diagnostics\n                        or self.options.preserve_asts\n                        or not isinstance(defn, FuncDef)\n                        or defn.def_or_infer_vars\n                    ):\n                        self.accept(item.body)\n                unreachable = self.binder.is_unreachable()\n                if new_frame is not None:\n                    self.binder.pop_frame(True, 0)\n\n            if not unreachable:\n                if defn.is_generator or is_named_instance(\n                    self.return_types[-1], \"typing.AwaitableGenerator\"\n                ):\n                    return_type = self.get_generator_return_type(\n                        self.return_types[-1], defn.is_coroutine\n                    )\n                elif defn.is_coroutine:\n                    return_type = self.get_coroutine_return_type(self.return_types[-1])\n                else:\n                    return_type = self.return_types[-1]\n                return_type = get_proper_type(return_type)\n\n                allow_empty = allow_empty or self.options.allow_empty_bodies\n\n                show_error = (\n                    not body_is_trivial\n                    or\n                    # Allow empty bodies for abstract methods, overloads, in tests and stubs.\n                    (\n                        not allow_empty\n                        and not (\n                            isinstance(defn, FuncDef) and defn.abstract_status != NOT_ABSTRACT\n                        )\n                        and not self.is_stub\n                    )\n                )\n\n                if (\n                    self.can_skip_diagnostics\n                    # Ignore plugin generated methods, these usually don't need any bodies.\n                    or (\n                        defn.info is not FUNC_NO_INFO\n                        and (\n                            defn.name not in defn.info.names\n                            or defn.info.names[defn.name].plugin_generated\n                        )\n                    )\n                    # Ignore also definitions that appear in `if TYPE_CHECKING: ...` blocks.\n                    # These can't be called at runtime anyway (similar to plugin-generated).\n                    or (isinstance(defn, FuncDef) and defn.is_mypy_only)\n                    # We want to minimize the fallout from checking empty bodies\n                    # that was absent in many mypy versions.\n                    or (body_is_trivial and is_subtype(NoneType(), return_type))\n                ):\n                    show_error = False\n\n                if show_error and not self.current_node_deferred:\n                    may_be_abstract = (\n                        body_is_trivial\n                        and defn.info is not FUNC_NO_INFO\n                        and defn.info.metaclass_type is not None\n                        and defn.info.metaclass_type.type.has_base(\"abc.ABCMeta\")\n                    )\n                    if self.options.warn_no_return:\n                        if not isinstance(return_type, (NoneType, AnyType)):\n                            # Control flow fell off the end of a function that was\n                            # declared to return a non-None type.\n                            if isinstance(return_type, UninhabitedType):\n                                # This is a NoReturn function\n                                msg = message_registry.INVALID_IMPLICIT_RETURN\n                            else:\n                                msg = message_registry.MISSING_RETURN_STATEMENT\n                            if body_is_trivial:\n                                msg = msg._replace(code=codes.EMPTY_BODY)\n                            self.fail(msg, defn)\n                            if may_be_abstract:\n                                self.note(message_registry.EMPTY_BODY_ABSTRACT, defn)\n                    else:\n                        msg = message_registry.INCOMPATIBLE_RETURN_VALUE_TYPE\n                        if body_is_trivial:\n                            msg = msg._replace(code=codes.EMPTY_BODY)\n                        # similar to code in check_return_stmt\n                        if (\n                            not self.check_subtype(\n                                subtype_label=\"implicitly returns\",\n                                subtype=NoneType(),\n                                supertype_label=\"expected\",\n                                supertype=return_type,\n                                context=defn,\n                                msg=msg,\n                            )\n                            and may_be_abstract\n                        ):\n                            self.note(message_registry.EMPTY_BODY_ABSTRACT, defn)\n\n            self.return_types.pop()\n\n            self.binder = old_binder\n\n    def check_funcdef_item(\n        self,\n        item: FuncItem,\n        typ: CallableType,\n        name: str | None,\n        *,\n        defn: FuncItem,\n        original_typ: CallableType,\n    ) -> None:\n        if isinstance(item, FuncDef):\n            fdef = item\n            # Check if __init__ has an invalid return type.\n            if (\n                fdef.info\n                and fdef.name in (\"__init__\", \"__init_subclass__\")\n                and not isinstance(get_proper_type(typ.ret_type), (NoneType, UninhabitedType))\n                and not self.dynamic_funcs[-1]\n            ):\n                self.fail(message_registry.MUST_HAVE_NONE_RETURN_TYPE.format(fdef.name), item)\n\n            # Check validity of __new__ signature\n            if fdef.info and fdef.name == \"__new__\":\n                self.check___new___signature(fdef, typ)\n\n            self.check_for_missing_annotations(fdef)\n            if self.options.disallow_any_unimported:\n                if fdef.type and isinstance(fdef.type, CallableType):\n                    ret_type = fdef.type.ret_type\n                    if has_any_from_unimported_type(ret_type):\n                        self.msg.unimported_type_becomes_any(\"Return type\", ret_type, fdef)\n                    for idx, arg_type in enumerate(fdef.type.arg_types):\n                        if has_any_from_unimported_type(arg_type):\n                            prefix = f'Argument {idx + 1} to \"{fdef.name}\"'\n                            self.msg.unimported_type_becomes_any(prefix, arg_type, fdef)\n            check_for_explicit_any(\n                fdef.type, self.options, self.is_typeshed_stub, self.msg, context=fdef\n            )\n\n        if name:  # Special method names\n            if (\n                defn.info\n                and self.is_reverse_op_method(name)\n                and defn not in self.overload_impl_stack\n            ):\n                self.check_reverse_op_method(item, typ, name, defn)\n            elif name in (\"__getattr__\", \"__getattribute__\"):\n                self.check_getattr_method(typ, defn, name)\n            elif name == \"__setattr__\":\n                self.check_setattr_method(typ, defn)\n\n        # Refuse contravariant return type variable\n        if isinstance(typ.ret_type, TypeVarType):\n            if typ.ret_type.variance == CONTRAVARIANT:\n                self.fail(message_registry.RETURN_TYPE_CANNOT_BE_CONTRAVARIANT, typ.ret_type)\n            self.check_unbound_return_typevar(typ)\n        elif isinstance(original_typ.ret_type, TypeVarType) and original_typ.ret_type.values:\n            # Since type vars with values are expanded, the return type is changed\n            # to a raw value. This is a hack to get it back.\n            self.check_unbound_return_typevar(original_typ)\n\n        # Check that Generator functions have the appropriate return type.\n        if defn.is_generator:\n            if defn.is_async_generator:\n                if not self.is_async_generator_return_type(typ.ret_type):\n                    self.fail(message_registry.INVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR, typ)\n            else:\n                if not self.is_generator_return_type(typ.ret_type, defn.is_coroutine):\n                    self.fail(message_registry.INVALID_RETURN_TYPE_FOR_GENERATOR, typ)\n\n    def require_correct_self_argument(self, func: Type, defn: FuncDef) -> bool:\n        func = get_proper_type(func)\n        if not isinstance(func, CallableType):\n            return False\n\n        # Do not report errors for untyped methods in classes nested in untyped funcs.\n        if not (\n            self.options.check_untyped_defs\n            or len(self.dynamic_funcs) < 2\n            or not self.dynamic_funcs[-2]\n            or not defn.is_dynamic()\n        ):\n            return bool(func.arg_types)\n\n        with self.scope.push_function(defn):\n            # We temporary push the definition to get the self type as\n            # visible from *inside* of this function/method.\n            ref_type: Type | None = self.scope.active_self_type()\n            if ref_type is None:\n                return False\n\n        if not defn.has_self_or_cls_argument or (\n            func.arg_kinds and func.arg_kinds[0] in [nodes.ARG_STAR, nodes.ARG_STAR2]\n        ):\n            return False\n\n        if not func.arg_types:\n            self.fail(\n                'Method must have at least one argument. Did you forget the \"self\" argument?', defn\n            )\n            return False\n\n        if self.can_skip_diagnostics:\n            return True\n\n        arg_type = func.arg_types[0]\n        if defn.is_class or defn.name == \"__new__\":\n            ref_type = mypy.types.TypeType.make_normalized(ref_type)\n        if is_same_type(arg_type, ref_type):\n            return True\n\n        # This level of erasure matches the one in checkmember.check_self_arg(),\n        # better keep these two checks consistent.\n        erased = get_proper_type(erase_typevars(erase_to_bound(arg_type)))\n        if not is_subtype(ref_type, erased, ignore_type_params=True):\n            if (\n                isinstance(erased, Instance)\n                and erased.type.is_protocol\n                or isinstance(erased, TypeType)\n                and isinstance(erased.item, Instance)\n                and erased.item.type.is_protocol\n            ):\n                # We allow the explicit self-type to be not a supertype of\n                # the current class if it is a protocol. For such cases\n                # the consistency check will be performed at call sites.\n                msg = None\n            elif func.arg_names[0] in {\"self\", \"cls\"}:\n                msg = message_registry.ERASED_SELF_TYPE_NOT_SUPERTYPE.format(\n                    erased.str_with_options(self.options), ref_type.str_with_options(self.options)\n                )\n            else:\n                msg = message_registry.MISSING_OR_INVALID_SELF_TYPE\n            if msg:\n                self.fail(msg, defn)\n        return True\n\n    def is_var_redefined_in_outer_context(self, v: Var, after_line: int) -> bool:\n        \"\"\"Can the variable be assigned to at module top level or outer function?\n\n        Note that this doesn't do a full CFG analysis but uses a line number based\n        heuristic that isn't correct in some (rare) cases.\n        \"\"\"\n        if v.is_final:\n            # Final vars are definitely never reassigned.\n            return False\n\n        outers = self.tscope.outer_functions()\n        if not outers:\n            # Top-level function -- outer context is top level, and we can't reason about\n            # globals\n            return True\n        for outer in outers:\n            if isinstance(outer, FuncDef):\n                if find_last_var_assignment_line(outer.body, v) >= after_line:\n                    return True\n        return False\n\n    def check_unbound_return_typevar(self, typ: CallableType) -> None:\n        \"\"\"Fails when the return typevar is not defined in arguments.\"\"\"\n        if isinstance(typ.ret_type, TypeVarType) and typ.ret_type in typ.variables:\n            arg_type_visitor = CollectArgTypeVarTypes()\n            for argtype in typ.arg_types:\n                argtype.accept(arg_type_visitor)\n\n            if typ.ret_type not in arg_type_visitor.arg_types:\n                self.fail(message_registry.UNBOUND_TYPEVAR, typ.ret_type, code=TYPE_VAR)\n                upper_bound = get_proper_type(typ.ret_type.upper_bound)\n                if not (\n                    isinstance(upper_bound, Instance)\n                    and upper_bound.type.fullname == \"builtins.object\"\n                ):\n                    self.note(\n                        \"Consider using the upper bound \"\n                        f\"{format_type(typ.ret_type.upper_bound, self.options)} instead\",\n                        context=typ.ret_type,\n                    )\n\n    def check_default_params(self, item: FuncItem, body_is_trivial: bool) -> None:\n        for param in item.arguments:\n            if param.initializer is None:\n                continue\n            if body_is_trivial and isinstance(param.initializer, EllipsisExpr):\n                continue\n            name = param.variable.name\n            msg = \"Incompatible default for \"\n            if name.startswith(\"__tuple_param_\"):\n                msg += f\"tuple parameter {name[12:]}\"\n            else:\n                msg += f'parameter \"{name}\"'\n            if (\n                not self.options.implicit_optional\n                and isinstance(param.initializer, NameExpr)\n                and param.initializer.fullname == \"builtins.None\"\n            ):\n                notes = [\n                    \"PEP 484 prohibits implicit Optional. \"\n                    \"Accordingly, mypy has changed its default to no_implicit_optional=True\",\n                    \"Use https://github.com/hauntsaninja/no_implicit_optional to automatically \"\n                    \"upgrade your codebase\",\n                ]\n            else:\n                notes = None\n            self.check_simple_assignment(\n                param.variable.type,\n                param.initializer,\n                context=param.initializer,\n                msg=ErrorMessage(msg, code=codes.ASSIGNMENT),\n                lvalue_name=\"parameter\",\n                rvalue_name=\"default\",\n                notes=notes,\n            )\n\n    def is_forward_op_method(self, method_name: str) -> bool:\n        return method_name in operators.reverse_op_methods\n\n    def is_reverse_op_method(self, method_name: str) -> bool:\n        return method_name in operators.reverse_op_method_set\n\n    def check_for_missing_annotations(self, fdef: FuncItem) -> None:\n        show_untyped = not self.is_typeshed_stub or self.options.warn_incomplete_stub\n        if not show_untyped:\n            return\n\n        # Check for functions with unspecified/not fully specified types.\n        def is_unannotated_any(t: Type) -> bool:\n            if not isinstance(t, ProperType):\n                return False\n            return isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated\n\n        has_explicit_annotation = isinstance(fdef.type, CallableType) and any(\n            not is_unannotated_any(t) for t in fdef.type.arg_types + [fdef.type.ret_type]\n        )\n\n        check_incomplete_defs = self.options.disallow_incomplete_defs and has_explicit_annotation\n        if self.options.disallow_untyped_defs or check_incomplete_defs:\n            if fdef.type is None and self.options.disallow_untyped_defs:\n                if not fdef.arguments or (\n                    len(fdef.arguments) == 1\n                    and (fdef.arg_names[0] == \"self\" or fdef.arg_names[0] == \"cls\")\n                ):\n                    self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)\n                    if not has_return_statement(fdef) and not fdef.is_generator:\n                        self.note(\n                            'Use \"-> None\" if function does not return a value',\n                            fdef,\n                            code=codes.NO_UNTYPED_DEF,\n                        )\n                else:\n                    self.fail(message_registry.FUNCTION_TYPE_EXPECTED, fdef)\n            elif isinstance(fdef.type, CallableType):\n                ret_type = get_proper_type(fdef.type.ret_type)\n                if is_unannotated_any(ret_type):\n                    self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)\n                elif fdef.is_generator:\n                    if is_unannotated_any(\n                        self.get_generator_return_type(ret_type, fdef.is_coroutine)\n                    ):\n                        self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)\n                elif fdef.is_coroutine and isinstance(ret_type, Instance):\n                    if is_unannotated_any(self.get_coroutine_return_type(ret_type)):\n                        self.fail(message_registry.RETURN_TYPE_EXPECTED, fdef)\n                if any(is_unannotated_any(t) for t in fdef.type.arg_types):\n                    self.fail(message_registry.PARAM_TYPE_EXPECTED, fdef)\n\n    def check___new___signature(self, fdef: FuncDef, typ: CallableType) -> None:\n        self_type = fill_typevars_with_any(fdef.info)\n        bound_type = bind_self(typ, self_type, is_classmethod=True)\n        # Check that __new__ (after binding cls) returns an instance\n        # type (or any).\n        if fdef.info.is_metaclass():\n            # This is a metaclass, so it must return a new unrelated type.\n            self.check_subtype(\n                bound_type.ret_type,\n                self.type_type(),\n                fdef,\n                message_registry.INVALID_NEW_TYPE,\n                \"returns\",\n                \"but must return a subtype of\",\n            )\n        elif not isinstance(\n            get_proper_type(bound_type.ret_type),\n            (AnyType, Instance, TupleType, UninhabitedType, LiteralType),\n        ):\n            self.fail(\n                message_registry.NON_INSTANCE_NEW_TYPE.format(\n                    format_type(bound_type.ret_type, self.options)\n                ),\n                fdef,\n            )\n        else:\n            # And that it returns a subtype of the class\n            self.check_subtype(\n                bound_type.ret_type,\n                self_type,\n                fdef,\n                message_registry.INVALID_NEW_TYPE,\n                \"returns\",\n                \"but must return a subtype of\",\n            )\n\n    def check_reverse_op_method(\n        self, defn: FuncItem, reverse_type: CallableType, reverse_name: str, context: Context\n    ) -> None:\n        \"\"\"Check a reverse operator method such as __radd__.\"\"\"\n        # Decides whether it's worth calling check_overlapping_op_methods().\n\n        # This used to check for some very obscure scenario.  It now\n        # just decides whether it's worth calling\n        # check_overlapping_op_methods().\n\n        assert defn.info\n\n        # First check for a valid signature\n        method_type = CallableType(\n            [AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form)],\n            [nodes.ARG_POS, nodes.ARG_POS],\n            [None, None],\n            AnyType(TypeOfAny.special_form),\n            self.named_type(\"builtins.function\"),\n        )\n        if not is_subtype(reverse_type, method_type):\n            self.msg.invalid_signature(reverse_type, context)\n            return\n\n        if reverse_name in (\"__eq__\", \"__ne__\"):\n            # These are defined for all objects => can't cause trouble.\n            return\n\n        # With 'Any' or 'object' return type we are happy, since any possible\n        # return value is valid.\n        ret_type = get_proper_type(reverse_type.ret_type)\n        if isinstance(ret_type, AnyType):\n            return\n        if isinstance(ret_type, Instance):\n            if ret_type.type.fullname == \"builtins.object\":\n                return\n        if reverse_type.arg_kinds[0] == ARG_STAR:\n            reverse_type = reverse_type.copy_modified(\n                arg_types=[reverse_type.arg_types[0]] * 2,\n                arg_kinds=[ARG_POS] * 2,\n                arg_names=[reverse_type.arg_names[0], \"_\"],\n            )\n        assert len(reverse_type.arg_types) >= 2\n\n        forward_name = operators.normal_from_reverse_op[reverse_name]\n        forward_inst = get_proper_type(reverse_type.arg_types[1])\n        if isinstance(forward_inst, TypeVarType):\n            forward_inst = get_proper_type(forward_inst.upper_bound)\n        elif isinstance(forward_inst, TupleType):\n            forward_inst = tuple_fallback(forward_inst)\n        elif isinstance(forward_inst, (FunctionLike, TypedDictType, LiteralType)):\n            forward_inst = forward_inst.fallback\n        if isinstance(forward_inst, TypeType):\n            item = forward_inst.item\n            if isinstance(item, Instance):\n                opt_meta = item.type.metaclass_type\n                if opt_meta is not None:\n                    forward_inst = opt_meta\n\n        def has_readable_member(typ: UnionType | Instance, name: str) -> bool:\n            # TODO: Deal with attributes of TupleType etc.\n            if isinstance(typ, Instance):\n                return typ.type.has_readable_member(name)\n            return all(\n                (isinstance(x, UnionType) and has_readable_member(x, name))\n                or (isinstance(x, Instance) and x.type.has_readable_member(name))\n                for x in get_proper_types(typ.relevant_items())\n            )\n\n        if not (\n            isinstance(forward_inst, (Instance, UnionType))\n            and has_readable_member(forward_inst, forward_name)\n        ):\n            return\n        forward_base = reverse_type.arg_types[1]\n        forward_type = self.expr_checker.analyze_external_member_access(\n            forward_name, forward_base, context=defn\n        )\n        self.check_overlapping_op_methods(\n            reverse_type,\n            reverse_name,\n            defn.info,\n            forward_type,\n            forward_name,\n            forward_base,\n            context=defn,\n        )\n\n    def check_overlapping_op_methods(\n        self,\n        reverse_type: CallableType,\n        reverse_name: str,\n        reverse_class: TypeInfo,\n        forward_type: Type,\n        forward_name: str,\n        forward_base: Type,\n        context: Context,\n    ) -> None:\n        \"\"\"Check for overlapping method and reverse method signatures.\n\n        This function assumes that:\n\n        -   The reverse method has valid argument count and kinds.\n        -   If the reverse operator method accepts some argument of type\n            X, the forward operator method also belong to class X.\n\n            For example, if we have the reverse operator `A.__radd__(B)`, then the\n            corresponding forward operator must have the type `B.__add__(...)`.\n        \"\"\"\n\n        # Note: Suppose we have two operator methods \"A.__rOP__(B) -> R1\" and\n        # \"B.__OP__(C) -> R2\". We check if these two methods are unsafely overlapping\n        # by using the following algorithm:\n        #\n        # 1. Rewrite \"B.__OP__(C) -> R1\"  to \"temp1(B, C) -> R1\"\n        #\n        # 2. Rewrite \"A.__rOP__(B) -> R2\" to \"temp2(B, A) -> R2\"\n        #\n        # 3. Treat temp1 and temp2 as if they were both variants in the same\n        #    overloaded function. (This mirrors how the Python runtime calls\n        #    operator methods: we first try __OP__, then __rOP__.)\n        #\n        #    If the first signature is unsafely overlapping with the second,\n        #    report an error.\n        #\n        # 4. However, if temp1 shadows temp2 (e.g. the __rOP__ method can never\n        #    be called), do NOT report an error.\n        #\n        #    This behavior deviates from how we handle overloads -- many of the\n        #    modules in typeshed seem to define __OP__ methods that shadow the\n        #    corresponding __rOP__ method.\n        #\n        # Note: we do not attempt to handle unsafe overlaps related to multiple\n        # inheritance. (This is consistent with how we handle overloads: we also\n        # do not try checking unsafe overlaps due to multiple inheritance there.)\n\n        for forward_item in flatten_nested_unions([forward_type]):\n            forward_item = get_proper_type(forward_item)\n            if isinstance(forward_item, CallableType):\n                if self.is_unsafe_overlapping_op(forward_item, forward_base, reverse_type):\n                    self.msg.operator_method_signatures_overlap(\n                        reverse_class, reverse_name, forward_base, forward_name, context\n                    )\n            elif isinstance(forward_item, Overloaded):\n                for item in forward_item.items:\n                    if self.is_unsafe_overlapping_op(item, forward_base, reverse_type):\n                        self.msg.operator_method_signatures_overlap(\n                            reverse_class, reverse_name, forward_base, forward_name, context\n                        )\n            elif not isinstance(forward_item, AnyType):\n                self.msg.forward_operator_not_callable(forward_name, context)\n\n    def is_unsafe_overlapping_op(\n        self, forward_item: CallableType, forward_base: Type, reverse_type: CallableType\n    ) -> bool:\n        # TODO: check argument kinds?\n        if len(forward_item.arg_types) < 1:\n            # Not a valid operator method -- can't succeed anyway.\n            return False\n\n        # Erase the type if necessary to make sure we don't have a single\n        # TypeVar in forward_tweaked. (Having a function signature containing\n        # just a single TypeVar can lead to unpredictable behavior.)\n        forward_base_erased = forward_base\n        if isinstance(forward_base, TypeVarType):\n            forward_base_erased = erase_to_bound(forward_base)\n\n        # Construct normalized function signatures corresponding to the\n        # operator methods. The first argument is the left operand and the\n        # second operand is the right argument -- we switch the order of\n        # the arguments of the reverse method.\n\n        # TODO: this manipulation is dangerous if callables are generic.\n        # Shuffling arguments between callables can create meaningless types.\n        forward_tweaked = forward_item.copy_modified(\n            arg_types=[forward_base_erased, forward_item.arg_types[0]],\n            arg_kinds=[nodes.ARG_POS] * 2,\n            arg_names=[None] * 2,\n        )\n        reverse_tweaked = reverse_type.copy_modified(\n            arg_types=[reverse_type.arg_types[1], reverse_type.arg_types[0]],\n            arg_kinds=[nodes.ARG_POS] * 2,\n            arg_names=[None] * 2,\n        )\n\n        reverse_base_erased = reverse_type.arg_types[0]\n        if isinstance(reverse_base_erased, TypeVarType):\n            reverse_base_erased = erase_to_bound(reverse_base_erased)\n\n        if is_same_type(reverse_base_erased, forward_base_erased):\n            return False\n        elif is_subtype(reverse_base_erased, forward_base_erased):\n            first = reverse_tweaked\n            second = forward_tweaked\n        else:\n            first = forward_tweaked\n            second = reverse_tweaked\n\n        current_class = self.scope.active_class()\n        type_vars = current_class.defn.type_vars if current_class else []\n        return is_unsafe_overlapping_overload_signatures(\n            first, second, type_vars, partial_only=False\n        )\n\n    def check_inplace_operator_method(self, defn: FuncBase) -> None:\n        \"\"\"Check an inplace operator method such as __iadd__.\n\n        They cannot arbitrarily overlap with __add__.\n        \"\"\"\n        method = defn.name\n        if method not in operators.inplace_operator_methods:\n            return\n        typ = bind_self(self.function_type(defn))\n        cls = defn.info\n        other_method = \"__\" + method[3:]\n        if cls.has_readable_member(other_method):\n            instance = fill_typevars(cls)\n            typ2 = get_proper_type(\n                self.expr_checker.analyze_external_member_access(other_method, instance, defn)\n            )\n            fail = False\n            if isinstance(typ2, FunctionLike):\n                if not is_more_general_arg_prefix(typ, typ2):\n                    fail = True\n            else:\n                # TODO overloads\n                fail = True\n            if fail:\n                self.msg.signatures_incompatible(method, other_method, defn)\n\n    def check_getattr_method(self, typ: Type, context: Context, name: str) -> None:\n        if len(self.scope.stack) == 1:\n            # module scope\n            if name == \"__getattribute__\":\n                self.fail(message_registry.MODULE_LEVEL_GETATTRIBUTE, context)\n                return\n            # __getattr__ is fine at the module level as of Python 3.7 (PEP 562). We could\n            # show an error for Python < 3.7, but that would be annoying in code that supports\n            # both 3.7 and older versions.\n            method_type = CallableType(\n                [self.named_type(\"builtins.str\")],\n                [nodes.ARG_POS],\n                [None],\n                AnyType(TypeOfAny.special_form),\n                self.named_type(\"builtins.function\"),\n            )\n        elif self.scope.active_class():\n            method_type = CallableType(\n                [AnyType(TypeOfAny.special_form), self.named_type(\"builtins.str\")],\n                [nodes.ARG_POS, nodes.ARG_POS],\n                [None, None],\n                AnyType(TypeOfAny.special_form),\n                self.named_type(\"builtins.function\"),\n            )\n        else:\n            return\n        if not is_subtype(typ, method_type):\n            self.msg.invalid_signature_for_special_method(typ, context, name)\n\n    def check_setattr_method(self, typ: Type, context: Context) -> None:\n        if not self.scope.active_class():\n            return\n        method_type = CallableType(\n            [\n                AnyType(TypeOfAny.special_form),\n                self.named_type(\"builtins.str\"),\n                AnyType(TypeOfAny.special_form),\n            ],\n            [nodes.ARG_POS, nodes.ARG_POS, nodes.ARG_POS],\n            [None, None, None],\n            NoneType(),\n            self.named_type(\"builtins.function\"),\n        )\n        if not is_subtype(typ, method_type):\n            self.msg.invalid_signature_for_special_method(typ, context, \"__setattr__\")\n\n    def check_slots_definition(self, typ: Type, context: Context) -> None:\n        \"\"\"Check the type of __slots__.\"\"\"\n        str_type = self.named_type(\"builtins.str\")\n        expected_type = UnionType(\n            [str_type, self.named_generic_type(\"typing.Iterable\", [str_type])]\n        )\n        self.check_subtype(\n            typ,\n            expected_type,\n            context,\n            message_registry.INVALID_TYPE_FOR_SLOTS,\n            \"actual type\",\n            \"expected type\",\n            code=codes.ASSIGNMENT,\n        )\n\n    def check_match_args(self, var: Var, typ: Type, context: Context) -> None:\n        \"\"\"Check that __match_args__ contains literal strings\"\"\"\n        if not self.scope.active_class():\n            return\n        typ = get_proper_type(typ)\n        if not isinstance(typ, TupleType) or not all(\n            is_string_literal(item) for item in typ.items\n        ):\n            self.msg.note(\n                \"__match_args__ must be a tuple containing string literals for checking \"\n                \"of match statements to work\",\n                context,\n                code=codes.LITERAL_REQ,\n            )\n\n    def expand_typevars(\n        self, defn: FuncItem, typ: CallableType\n    ) -> list[tuple[FuncItem, CallableType]]:\n        # TODO use generator\n        subst: list[list[tuple[TypeVarId, Type]]] = []\n        tvars = list(typ.variables) or []\n        if defn.info:\n            # Class type variables\n            tvars += defn.info.defn.type_vars or []\n        for tvar in tvars:\n            if isinstance(tvar, TypeVarType) and tvar.values:\n                subst.append([(tvar.id, value) for value in tvar.values])\n        # Make a copy of the function to check for each combination of\n        # value restricted type variables. (Except when running mypyc,\n        # where we need one canonical version of the function.)\n        if subst and not (self.options.mypyc or self.options.inspections):\n            result: list[tuple[FuncItem, CallableType]] = []\n            for substitutions in itertools.product(*subst):\n                mapping = dict(substitutions)\n                result.append((expand_func(defn, mapping), expand_type(typ, mapping)))\n            return result\n        else:\n            return [(defn, typ)]\n\n    def check_explicit_override_decorator(\n        self,\n        defn: FuncDef | OverloadedFuncDef,\n        found_method_base_classes: list[TypeInfo] | None,\n        context: Context | None = None,\n    ) -> None:\n        plugin_generated = False\n        if defn.info and (node := defn.info.get(defn.name)) and node.plugin_generated:\n            # Do not report issues for plugin generated nodes,\n            # they can't realistically use `@override` for their methods.\n            plugin_generated = True\n\n        if (\n            not plugin_generated\n            and found_method_base_classes\n            and not defn.is_explicit_override\n            and defn.name not in (\"__init__\", \"__new__\")\n            and not is_private(defn.name)\n        ):\n            self.msg.explicit_override_decorator_missing(\n                defn.name, found_method_base_classes[0].fullname, context or defn\n            )\n\n    def check_method_override(\n        self, defn: FuncDef | OverloadedFuncDef | Decorator\n    ) -> list[TypeInfo] | None:\n        \"\"\"Check if function definition is compatible with base classes.\n\n        This may defer the method if a signature is not available in at least one base class.\n        Return ``None`` if that happens.\n\n        Return a list of base classes which contain an attribute with the method name.\n        \"\"\"\n        if self.can_skip_diagnostics:\n            return None\n        # Check against definitions in base classes.\n        check_override_compatibility = (\n            defn.name not in (\"__init__\", \"__new__\", \"__init_subclass__\", \"__post_init__\")\n            and (self.options.check_untyped_defs or not defn.is_dynamic())\n            and (\n                # don't check override for synthesized __replace__ methods from dataclasses\n                defn.name != \"__replace__\"\n                or defn.info.metadata.get(\"dataclass_tag\") is None\n            )\n        )\n        found_method_base_classes: list[TypeInfo] = []\n        for base in defn.info.mro[1:]:\n            result = self.check_method_or_accessor_override_for_base(\n                defn, base, check_override_compatibility\n            )\n            if result is None:\n                # Node was deferred, we will have another attempt later.\n                return None\n            if result:\n                found_method_base_classes.append(base)\n        return found_method_base_classes\n\n    def check_method_or_accessor_override_for_base(\n        self,\n        defn: FuncDef | OverloadedFuncDef | Decorator,\n        base: TypeInfo,\n        check_override_compatibility: bool,\n    ) -> bool | None:\n        \"\"\"Check if method definition is compatible with a base class.\n\n        Return ``None`` if the node was deferred because one of the corresponding\n        superclass nodes is not ready.\n\n        Return ``True`` if an attribute with the method name was found in the base class.\n        \"\"\"\n        found_base_method = False\n        if base:\n            name = defn.name\n            base_attr = base.names.get(name)\n            if base_attr:\n                # First, check if we override a final (always an error, even with Any types).\n                if is_final_node(base_attr.node) and not is_private(name):\n                    self.msg.cant_override_final(name, base.name, defn)\n                # Second, final can't override anything writeable independently of types.\n                if defn.is_final:\n                    self.check_if_final_var_override_writable(name, base_attr.node, defn)\n                found_base_method = True\n            if check_override_compatibility:\n                # Check compatibility of the override signature\n                # (__init__, __new__, __init_subclass__ are special).\n                if self.check_method_override_for_base_with_name(defn, name, base):\n                    return None\n                if name in operators.inplace_operator_methods:\n                    # Figure out the name of the corresponding operator method.\n                    method = \"__\" + name[3:]\n                    # An inplace operator method such as __iadd__ might not be\n                    # always introduced safely if a base class defined __add__.\n                    # TODO can't come up with an example where this is\n                    #      necessary; now it's \"just in case\"\n                    if self.check_method_override_for_base_with_name(defn, method, base):\n                        return None\n        return found_base_method\n\n    def check_setter_type_override(self, defn: OverloadedFuncDef, base: TypeInfo) -> None:\n        \"\"\"Check override of a setter type of a mutable attribute.\n\n        Currently, this should be only called when either base node or the current node\n        is a custom settable property (i.e. where setter type is different from getter type).\n        Note that this check is contravariant.\n        \"\"\"\n        typ, _ = self.node_type_from_base(defn.name, defn.info, defn, setter_type=True)\n        original_type, _ = self.node_type_from_base(defn.name, base, defn, setter_type=True)\n        # The caller should handle deferrals.\n        assert typ is not None and original_type is not None\n\n        if not is_subtype(original_type, typ):\n            self.msg.incompatible_setter_override(defn.setter, typ, original_type, base)\n\n    def check_method_override_for_base_with_name(\n        self, defn: FuncDef | OverloadedFuncDef | Decorator, name: str, base: TypeInfo\n    ) -> bool:\n        \"\"\"Check if overriding an attribute `name` of `base` with `defn` is valid.\n\n        Return True if the supertype node was not analysed yet, and `defn` was deferred.\n        \"\"\"\n        base_attr = base.names.get(name)\n        if not base_attr:\n            return False\n        # The name of the method is defined in the base class.\n\n        # Point errors at the 'def' line (important for backward compatibility\n        # of type ignores).\n        if not isinstance(defn, Decorator):\n            context = defn\n        else:\n            context = defn.func\n\n        # Construct the type of the overriding method.\n        if isinstance(defn, (FuncDef, OverloadedFuncDef)):\n            override_class_or_static = defn.is_class or defn.is_static\n        else:\n            override_class_or_static = defn.func.is_class or defn.func.is_static\n        typ, _ = self.node_type_from_base(defn.name, defn.info, defn)\n        if typ is None:\n            # This may only happen if we're checking `x-redefinition` member\n            # and `x` itself is for some reason gone. Normally the node should\n            # be reachable from the containing class by its name.\n            # The redefinition is never removed, use this as a sanity check to verify\n            # the reasoning above.\n            assert f\"{defn.name}-redefinition\" in defn.info.names\n            return False\n\n        original_node = base_attr.node\n        # `original_type` can be partial if (e.g.) it is originally an\n        # instance variable from an `__init__` block that becomes deferred.\n        supertype_ready = True\n        original_type, _ = self.node_type_from_base(name, base, defn)\n        if original_type is None:\n            supertype_ready = False\n            if self.pass_num < self.last_pass:\n                # If there are passes left, defer this node until next pass,\n                # otherwise try reconstructing the method type from available information.\n                # For consistency, defer an enclosing top-level function (if any).\n                top_level = self.scope.top_level_function()\n                if isinstance(top_level, FuncDef):\n                    self.defer_node(top_level, self.scope.enclosing_class(top_level))\n                else:\n                    # Specify enclosing class explicitly, as we check type override before\n                    # entering e.g. decorators or overloads.\n                    self.defer_node(defn, defn.info)\n                return True\n            elif isinstance(original_node, (FuncDef, OverloadedFuncDef)):\n                original_type = self.function_type(original_node)\n            elif isinstance(original_node, Decorator):\n                original_type = self.function_type(original_node.func)\n            elif isinstance(original_node, Var):\n                # Super type can define method as an attribute.\n                # See https://github.com/python/mypy/issues/10134\n\n                # We also check that sometimes `original_node.type` is None.\n                # This is the case when we use something like `__hash__ = None`.\n                if original_node.type is not None:\n                    original_type = get_proper_type(original_node.type)\n                else:\n                    original_type = NoneType()\n            else:\n                # Will always fail to typecheck below, since we know the node is a method\n                original_type = NoneType()\n\n        always_allow_covariant = False\n        if is_settable_property(defn) and (\n            is_settable_property(original_node) or isinstance(original_node, Var)\n        ):\n            if is_custom_settable_property(defn) or (is_custom_settable_property(original_node)):\n                # Unlike with getter, where we try to construct some fallback type in case of\n                # deferral during last_pass, we can't make meaningful setter checks if the\n                # supertype is not known precisely.\n                if supertype_ready:\n                    always_allow_covariant = True\n                    self.check_setter_type_override(defn, base)\n\n        if isinstance(original_node, (FuncDef, OverloadedFuncDef)):\n            original_class_or_static = original_node.is_class or original_node.is_static\n        elif isinstance(original_node, Decorator):\n            fdef = original_node.func\n            original_class_or_static = fdef.is_class or fdef.is_static\n        else:\n            original_class_or_static = False  # a variable can't be class or static\n\n        typ = get_proper_type(typ)\n        original_type = get_proper_type(original_type)\n\n        if (\n            is_property(defn)\n            and isinstance(original_node, Var)\n            and not original_node.is_final\n            and (not original_node.is_property or original_node.is_settable_property)\n            and isinstance(defn, Decorator)\n        ):\n            # We only give an error where no other similar errors will be given.\n            if not isinstance(original_type, AnyType):\n                self.msg.fail(\n                    \"Cannot override writeable attribute with read-only property\",\n                    # Give an error on function line to match old behaviour.\n                    defn.func,\n                    code=codes.OVERRIDE,\n                )\n\n        if isinstance(original_type, AnyType) or isinstance(typ, AnyType):\n            pass\n        elif isinstance(original_type, FunctionLike) and isinstance(typ, FunctionLike):\n            # Check that the types are compatible.\n            ok = self.check_override(\n                typ,\n                original_type,\n                defn.name,\n                name,\n                base.name if base.module_name == self.tree.fullname else base.fullname,\n                original_class_or_static,\n                override_class_or_static,\n                context,\n            )\n            # Check if this override is covariant.\n            if (\n                ok\n                and original_node\n                and codes.MUTABLE_OVERRIDE in self.options.enabled_error_codes\n                and self.is_writable_attribute(original_node)\n                and not always_allow_covariant\n                and not is_subtype(original_type, typ, ignore_pos_arg_names=True)\n            ):\n                base_str, override_str = format_type_distinctly(\n                    original_type, typ, options=self.options\n                )\n                msg = message_registry.COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE.with_additional_msg(\n                    f' (base class \"{base.name}\" defined the type as {base_str},'\n                    f\" override has type {override_str})\"\n                )\n                self.fail(msg, context)\n        elif isinstance(original_type, UnionType) and any(\n            is_subtype(typ, orig_typ, ignore_pos_arg_names=True)\n            for orig_typ in original_type.items\n        ):\n            # This method is a subtype of at least one union variant.\n            if (\n                original_node\n                and codes.MUTABLE_OVERRIDE in self.options.enabled_error_codes\n                and self.is_writable_attribute(original_node)\n                and not always_allow_covariant\n            ):\n                # Covariant override of mutable attribute.\n                base_str, override_str = format_type_distinctly(\n                    original_type, typ, options=self.options\n                )\n                msg = message_registry.COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE.with_additional_msg(\n                    f' (base class \"{base.name}\" defined the type as {base_str},'\n                    f\" override has type {override_str})\"\n                )\n                self.fail(msg, context)\n        elif is_equivalent(original_type, typ):\n            # Assume invariance for a non-callable attribute here. Note\n            # that this doesn't affect read-only properties which can have\n            # covariant overrides.\n            pass\n        elif (\n            original_node\n            and (not self.is_writable_attribute(original_node) or always_allow_covariant)\n            and is_subtype(typ, original_type)\n        ):\n            # If the attribute is read-only, allow covariance\n            pass\n        else:\n            self.msg.signature_incompatible_with_supertype(\n                defn.name, name, base.name, context, original=original_type, override=typ\n            )\n        return False\n\n    def get_op_other_domain(self, tp: FunctionLike) -> Type | None:\n        if isinstance(tp, CallableType):\n            if tp.arg_kinds and tp.arg_kinds[0] == ARG_POS:\n                # For generic methods, domain comparison is tricky, as a first\n                # approximation erase all remaining type variables.\n                return erase_typevars(tp.arg_types[0], {v.id for v in tp.variables})\n            return None\n        elif isinstance(tp, Overloaded):\n            raw_items = [self.get_op_other_domain(it) for it in tp.items]\n            items = [it for it in raw_items if it]\n            if items:\n                return make_simplified_union(items)\n            return None\n        else:\n            assert False, \"Need to check all FunctionLike subtypes here\"\n\n    def check_override(\n        self,\n        override: FunctionLike,\n        original: FunctionLike,\n        name: str,\n        name_in_super: str,\n        supertype: str,\n        original_class_or_static: bool,\n        override_class_or_static: bool,\n        node: Context,\n    ) -> bool:\n        \"\"\"Check a method override with given signatures.\n\n        Arguments:\n          override:                 The signature of the overriding method.\n          original:                 The signature of the original supertype method.\n          name:                     The name of the overriding method.\n                                    Used primarily for generating error messages.\n          name_in_super:            The name of the overridden in the superclass.\n                                    Used for generating error messages only.\n          supertype:                The name of the supertype.\n          original_class_or_static: Indicates whether the original method (from the superclass)\n                                    is either a class method or a static method.\n          override_class_or_static: Indicates whether the overriding method (from the subclass)\n                                    is either a class method or a static method.\n          node:                     Context node.\n        \"\"\"\n        # Use boolean variable to clarify code.\n        fail = False\n        op_method_wider_note = False\n        if not is_subtype(override, original, ignore_pos_arg_names=True):\n            fail = True\n        elif isinstance(override, Overloaded) and self.is_forward_op_method(name):\n            # Operator method overrides cannot extend the domain, as\n            # this could be unsafe with reverse operator methods.\n            original_domain = self.get_op_other_domain(original)\n            override_domain = self.get_op_other_domain(override)\n            if (\n                original_domain\n                and override_domain\n                and not is_subtype(override_domain, original_domain)\n            ):\n                fail = True\n                op_method_wider_note = True\n        if isinstance(override, FunctionLike):\n            if original_class_or_static and not override_class_or_static:\n                fail = True\n            elif isinstance(original, CallableType) and isinstance(override, CallableType):\n                if original.type_guard is not None and override.type_guard is None:\n                    fail = True\n                if original.type_is is not None and override.type_is is None:\n                    fail = True\n\n        if is_private(name):\n            fail = False\n\n        if fail:\n            emitted_msg = False\n\n            offset_arguments = isinstance(override, CallableType) and override.unpack_kwargs\n            # Normalize signatures, so we get better diagnostics.\n            if isinstance(override, (CallableType, Overloaded)):\n                override = override.with_unpacked_kwargs()\n            if isinstance(original, (CallableType, Overloaded)):\n                original = original.with_unpacked_kwargs()\n\n            if (\n                isinstance(override, CallableType)\n                and isinstance(original, CallableType)\n                and len(override.arg_types) == len(original.arg_types)\n                and override.min_args == original.min_args\n            ):\n                # Give more detailed messages for the common case of both\n                # signatures having the same number of arguments and no\n                # overloads.\n\n                # override might have its own generic function type\n                # variables. If an argument or return type of override\n                # does not have the correct subtyping relationship\n                # with the original type even after these variables\n                # are erased, then it is definitely an incompatibility.\n\n                override_ids = override.type_var_ids()\n                type_name = None\n                definition = get_func_def(override)\n                if isinstance(definition, FuncDef):\n                    type_name = definition.info.name\n\n                def erase_override(t: Type) -> Type:\n                    return erase_typevars(t, ids_to_erase=override_ids)\n\n                for i, (sub_kind, super_kind) in enumerate(\n                    zip(override.arg_kinds, original.arg_kinds)\n                ):\n                    if sub_kind.is_positional() and super_kind.is_positional():\n                        override_arg_type = override.arg_types[i]\n                        original_arg_type = original.arg_types[i]\n                    elif sub_kind.is_named() and super_kind.is_named() and not offset_arguments:\n                        arg_name = override.arg_names[i]\n                        if arg_name in original.arg_names:\n                            override_arg_type = override.arg_types[i]\n                            original_i = original.arg_names.index(arg_name)\n                            original_arg_type = original.arg_types[original_i]\n                        else:\n                            continue\n                    else:\n                        continue\n                    if not is_subtype(original_arg_type, erase_override(override_arg_type)):\n                        context: Context = node\n                        if (\n                            isinstance(node, FuncDef)\n                            and not node.is_property\n                            and (\n                                not node.is_decorated  # fast path\n                                # allow trivial decorators like @classmethod and @override\n                                or not (sym := node.info.get(node.name))\n                                or not isinstance(sym.node, Decorator)\n                                or not sym.node.decorators\n                            )\n                        ):\n                            # If there's any decorator, we can no longer map arguments 1:1 reliably.\n                            arg_node = node.arguments[i + override.bound()]\n                            if arg_node.line != -1:\n                                context = arg_node\n                        self.msg.argument_incompatible_with_supertype(\n                            i + 1,\n                            name,\n                            type_name,\n                            name_in_super,\n                            original_arg_type,\n                            supertype,\n                            context,\n                            origin_context=node,\n                        )\n                        emitted_msg = True\n\n                if not is_subtype(erase_override(override.ret_type), original.ret_type):\n                    self.msg.return_type_incompatible_with_supertype(\n                        name, name_in_super, supertype, original.ret_type, override.ret_type, node\n                    )\n                    emitted_msg = True\n            elif isinstance(override, Overloaded) and isinstance(original, Overloaded):\n                # Give a more detailed message in the case where the user is trying to\n                # override an overload, and the subclass's overload is plausible, except\n                # that the order of the variants are wrong.\n                #\n                # For example, if the parent defines the overload f(int) -> int and f(str) -> str\n                # (in that order), and if the child swaps the two and does f(str) -> str and\n                # f(int) -> int\n                order = []\n                for child_variant in override.items:\n                    for i, parent_variant in enumerate(original.items):\n                        if is_subtype(child_variant, parent_variant):\n                            order.append(i)\n                            break\n\n                if len(order) == len(original.items) and order != sorted(order):\n                    self.msg.overload_signature_incompatible_with_supertype(\n                        name, name_in_super, supertype, node\n                    )\n                    emitted_msg = True\n\n            if not emitted_msg:\n                # Fall back to generic incompatibility message.\n                self.msg.signature_incompatible_with_supertype(\n                    name, name_in_super, supertype, node, original=original, override=override\n                )\n            if op_method_wider_note:\n                self.note(\n                    \"Overloaded operator methods can't have wider argument types in overrides\",\n                    node,\n                    code=codes.OVERRIDE,\n                )\n        return not fail\n\n    def check__exit__return_type(self, defn: FuncItem) -> None:\n        \"\"\"Generate error if the return type of __exit__ is problematic.\n\n        If __exit__ always returns False but the return type is declared\n        as bool, mypy thinks that a with statement may \"swallow\"\n        exceptions even though this is not the case, resulting in\n        invalid reachability inference.\n        \"\"\"\n        if not defn.type or not isinstance(defn.type, CallableType):\n            return\n\n        ret_type = get_proper_type(defn.type.ret_type)\n        if not has_bool_item(ret_type):\n            return\n\n        returns = all_return_statements(defn)\n        if not returns:\n            return\n\n        if all(\n            isinstance(ret.expr, NameExpr) and ret.expr.fullname == \"builtins.False\"\n            for ret in returns\n        ):\n            self.msg.incorrect__exit__return(defn)\n\n    def visit_class_def(self, defn: ClassDef) -> None:\n        \"\"\"Type check a class definition.\"\"\"\n        typ = defn.info\n        for base in typ.mro[1:]:\n            if base.is_final:\n                self.fail(message_registry.CANNOT_INHERIT_FROM_FINAL.format(base.name), defn)\n        if not can_have_shared_disjoint_base(typ.bases):\n            self.fail(message_registry.INCOMPATIBLE_DISJOINT_BASES.format(typ.name), defn)\n        with (\n            self.tscope.class_scope(defn.info),\n            self.enter_partial_types(is_class=True),\n            self.enter_class(defn.info),\n        ):\n            old_binder = self.binder\n            self.binder = ConditionalTypeBinder(self.options)\n            with self.binder.top_frame_context():\n                with self.scope.push_class(defn.info):\n                    self.accept(defn.defs)\n            self.binder = old_binder\n            if not self.can_skip_diagnostics:\n                if not (defn.info.typeddict_type or defn.info.tuple_type or defn.info.is_enum):\n                    # If it is not a normal class (not a special form) check class keywords.\n                    self.check_init_subclass(defn)\n                if not defn.has_incompatible_baseclass:\n                    # Otherwise we've already found errors; more errors are not useful\n                    self.check_multiple_inheritance(typ)\n                self.check_metaclass_compatibility(typ)\n                self.check_final_deletable(typ)\n\n            if defn.decorators:\n                sig: Type = type_object_type(defn.info, self.named_type)\n                # Decorators are applied in reverse order.\n                for decorator in reversed(defn.decorators):\n                    if isinstance(decorator, CallExpr) and isinstance(\n                        decorator.analyzed, PromoteExpr\n                    ):\n                        # _promote is a special type checking related construct.\n                        continue\n\n                    dec = self.expr_checker.accept(decorator)\n                    temp = self.temp_node(sig, context=decorator)\n                    fullname = None\n                    if isinstance(decorator, RefExpr):\n                        fullname = decorator.fullname or None\n\n                    # TODO: Figure out how to have clearer error messages.\n                    # (e.g. \"class decorator must be a function that accepts a type.\"\n                    old_allow_abstract_call = self.allow_abstract_call\n                    self.allow_abstract_call = True\n                    sig, _ = self.expr_checker.check_call(\n                        dec, [temp], [nodes.ARG_POS], defn, callable_name=fullname\n                    )\n                    self.allow_abstract_call = old_allow_abstract_call\n                # TODO: Apply the sig to the actual TypeInfo so we can handle decorators\n                # that completely swap out the type.  (e.g. Callable[[Type[A]], Type[B]])\n        if typ.defn.type_vars and typ.defn.type_args is None:\n            for base_inst in typ.bases:\n                for base_tvar, base_decl_tvar in zip(\n                    base_inst.args, base_inst.type.defn.type_vars\n                ):\n                    if (\n                        isinstance(base_tvar, TypeVarType)\n                        and base_tvar.variance != INVARIANT\n                        and isinstance(base_decl_tvar, TypeVarType)\n                        and base_decl_tvar.variance != base_tvar.variance\n                    ):\n                        self.fail(\n                            f'Variance of TypeVar \"{base_tvar.name}\" incompatible '\n                            \"with variance in parent type\",\n                            context=defn,\n                            code=codes.TYPE_VAR,\n                        )\n        if typ.defn.type_vars:\n            self.check_typevar_defaults(typ.defn.type_vars)\n\n        if typ.is_protocol and typ.defn.type_vars:\n            self.check_protocol_variance(defn)\n        if not defn.has_incompatible_baseclass and defn.info.is_enum:\n            self.check_enum(defn)\n        infer_class_variances(defn.info)\n\n    @contextmanager\n    def enter_class(self, type: TypeInfo) -> Iterator[None]:\n        original_type = self.type\n        self.type = type\n        try:\n            yield\n        finally:\n            self.type = original_type\n\n    def check_final_deletable(self, typ: TypeInfo) -> None:\n        # These checks are only for mypyc. Only perform some checks that are easier\n        # to implement here than in mypyc.\n        for attr in typ.deletable_attributes:\n            node = typ.names.get(attr)\n            if node and isinstance(node.node, Var) and node.node.is_final:\n                self.fail(message_registry.CANNOT_MAKE_DELETABLE_FINAL, node.node)\n\n    def check_init_subclass(self, defn: ClassDef) -> None:\n        \"\"\"Check that keywords in a class definition are valid arguments for __init_subclass__().\n\n        In this example:\n            1   class Base:\n            2       def __init_subclass__(cls, thing: int):\n            3           pass\n            4   class Child(Base, thing=5):\n            5       def __init_subclass__(cls):\n            6           pass\n            7   Child()\n\n        Base.__init_subclass__(thing=5) is called at line 4. This is what we simulate here.\n        Child.__init_subclass__ is never called.\n        \"\"\"\n        if defn.info.metaclass_type and defn.info.metaclass_type.type.fullname not in (\n            \"builtins.type\",\n            \"abc.ABCMeta\",\n        ):\n            # We can't safely check situations when both __init_subclass__ and a custom\n            # metaclass are present.\n            return\n        # At runtime, only Base.__init_subclass__ will be called, so\n        # we skip the current class itself.\n        for base in defn.info.mro[1:]:\n            if \"__init_subclass__\" not in base.names:\n                continue\n            name_expr = NameExpr(defn.name)\n            name_expr.node = base\n            callee = MemberExpr(name_expr, \"__init_subclass__\")\n            args = list(defn.keywords.values())\n            arg_names: list[str | None] = list(defn.keywords.keys())\n            # 'metaclass' keyword is consumed by the rest of the type machinery,\n            # and is never passed to __init_subclass__ implementations\n            if \"metaclass\" in arg_names:\n                idx = arg_names.index(\"metaclass\")\n                arg_names.pop(idx)\n                args.pop(idx)\n            arg_kinds = [ARG_NAMED] * len(args)\n            call_expr = CallExpr(callee, args, arg_kinds, arg_names)\n            call_expr.line = defn.line\n            call_expr.column = defn.column\n            call_expr.end_line = defn.end_line\n            self.expr_checker.accept(call_expr, allow_none_return=True, always_allow_any=True)\n            # We are only interested in the first Base having __init_subclass__,\n            # all other bases have already been checked.\n            break\n\n    def check_typevar_defaults(self, tvars: Sequence[TypeVarLikeType]) -> None:\n        for tv in tvars:\n            if not (isinstance(tv, TypeVarType) and tv.has_default()):\n                continue\n            if not is_subtype(tv.default, tv.upper_bound):\n                self.fail(\"TypeVar default must be a subtype of the bound type\", tv)\n            if tv.values and not any(is_same_type(tv.default, value) for value in tv.values):\n                self.fail(\"TypeVar default must be one of the constraint types\", tv)\n\n    def check_enum(self, defn: ClassDef) -> None:\n        assert defn.info.is_enum\n        if defn.info.fullname not in ENUM_BASES and \"__members__\" in defn.info.names:\n            sym = defn.info.names[\"__members__\"]\n            if isinstance(sym.node, Var) and sym.node.has_explicit_value:\n                # `__members__` will always be overwritten by `Enum` and is considered\n                # read-only so we disallow assigning a value to it\n                self.fail(message_registry.ENUM_MEMBERS_ATTR_WILL_BE_OVERRIDDEN, sym.node)\n        for base in defn.info.mro[1:-1]:  # we don't need self and `object`\n            if base.is_enum and base.fullname not in ENUM_BASES:\n                self.check_final_enum(defn, base)\n\n        if self.is_stub and self.tree.fullname not in {\"enum\", \"_typeshed\"}:\n            if not defn.info.enum_members:\n                self.fail(\n                    f'Detected enum \"{defn.info.fullname}\" in a type stub with zero members. '\n                    \"There is a chance this is due to a recent change in the semantics of \"\n                    \"enum membership. If so, use `member = value` to mark an enum member, \"\n                    \"instead of `member: type`\",\n                    defn,\n                )\n                self.note(\n                    \"See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members\",\n                    defn,\n                )\n\n        self.check_enum_bases(defn)\n        self.check_enum_new(defn)\n\n    def check_final_enum(self, defn: ClassDef, base: TypeInfo) -> None:\n        if base.enum_members:\n            self.fail(f'Cannot extend enum with existing members: \"{base.name}\"', defn)\n\n    def is_final_enum_value(self, sym: SymbolTableNode) -> bool:\n        if isinstance(sym.node, (FuncBase, Decorator)):\n            return False  # A method is fine\n        if not isinstance(sym.node, Var):\n            return True  # Can be a class or anything else\n\n        # Now, only `Var` is left, we need to check:\n        # 1. Private name like in `__prop = 1`\n        # 2. Dunder name like `__hash__ = some_hasher`\n        # 3. Sunder name like `_order_ = 'a, b, c'`\n        # 4. If it is a method / descriptor like in `method = classmethod(func)`\n        if (\n            is_private(sym.node.name)\n            or is_dunder(sym.node.name)\n            or is_sunder(sym.node.name)\n            # TODO: make sure that `x = @class/staticmethod(func)`\n            # and `x = property(prop)` both work correctly.\n            # Now they are incorrectly counted as enum members.\n            or isinstance(get_proper_type(sym.node.type), FunctionLike)\n        ):\n            return False\n\n        return self.is_stub or sym.node.has_explicit_value\n\n    def check_enum_bases(self, defn: ClassDef) -> None:\n        \"\"\"\n        Non-enum mixins cannot appear after enum bases; this is disallowed at runtime:\n\n            class Foo: ...\n            class Bar(enum.Enum, Foo): ...\n\n        But any number of enum mixins can appear in a class definition\n        (even if multiple enum bases define __new__). So this is fine:\n\n            class Foo(enum.Enum):\n                def __new__(cls, val): ...\n            class Bar(enum.Enum):\n                def __new__(cls, val): ...\n            class Baz(int, Foo, Bar, enum.Flag): ...\n        \"\"\"\n        enum_base: Instance | None = None\n        for base in defn.info.bases:\n            if enum_base is None and base.type.is_enum:\n                enum_base = base\n                continue\n            elif enum_base is not None and not base.type.is_enum:\n                self.fail(\n                    f'No non-enum mixin classes are allowed after \"{enum_base.str_with_options(self.options)}\"',\n                    defn,\n                )\n                break\n\n    def check_enum_new(self, defn: ClassDef) -> None:\n        def has_new_method(info: TypeInfo) -> bool:\n            new_method = info.get(\"__new__\")\n            return bool(\n                new_method\n                and new_method.node\n                and new_method.node.fullname != \"builtins.object.__new__\"\n            )\n\n        has_new = False\n        for base in defn.info.bases:\n            candidate = False\n\n            if base.type.is_enum:\n                # If we have an `Enum`, then we need to check all its bases.\n                candidate = any(not b.is_enum and has_new_method(b) for b in base.type.mro[1:-1])\n            else:\n                candidate = has_new_method(base.type)\n\n            if candidate and has_new:\n                self.fail(\n                    \"Only a single data type mixin is allowed for Enum subtypes, \"\n                    'found extra \"{}\"'.format(base.str_with_options(self.options)),\n                    defn,\n                )\n            elif candidate:\n                has_new = True\n\n    def check_protocol_variance(self, defn: ClassDef) -> None:\n        \"\"\"Check that protocol definition is compatible with declared\n        variances of type variables.\n\n        Note that we also prohibit declaring protocol classes as invariant\n        if they are actually covariant/contravariant, since this may break\n        transitivity of subtyping, see PEP 544.\n        \"\"\"\n        if self.can_skip_diagnostics:\n            return\n        if defn.type_args is not None:\n            # Using new-style syntax (PEP 695), so variance will be inferred\n            return\n        info = defn.info\n        object_type = Instance(info.mro[-1], [])\n        tvars = info.defn.type_vars\n        if self._variance_dummy_type is None:\n            _, dummy_info = self.make_fake_typeinfo(\"<dummy>\", \"Dummy\", \"Dummy\", [])\n            self._variance_dummy_type = Instance(dummy_info, [])\n        dummy = self._variance_dummy_type\n        for i, tvar in enumerate(tvars):\n            if not isinstance(tvar, TypeVarType):\n                # Variance of TypeVarTuple and ParamSpec is underspecified by PEPs.\n                continue\n            up_args: list[Type] = [\n                object_type if i == j else dummy.copy_modified() for j, _ in enumerate(tvars)\n            ]\n            down_args: list[Type] = [\n                UninhabitedType() if i == j else dummy.copy_modified() for j, _ in enumerate(tvars)\n            ]\n            up, down = Instance(info, up_args), Instance(info, down_args)\n            # TODO: add advanced variance checks for recursive protocols\n            if is_subtype(down, up, ignore_declared_variance=True):\n                expected = COVARIANT\n            elif is_subtype(up, down, ignore_declared_variance=True):\n                expected = CONTRAVARIANT\n            else:\n                expected = INVARIANT\n            if expected != tvar.variance:\n                self.msg.bad_proto_variance(tvar.variance, tvar.name, expected, defn)\n\n    def check_multiple_inheritance(self, typ: TypeInfo) -> None:\n        \"\"\"Check for multiple inheritance related errors.\"\"\"\n        if len(typ.bases) <= 1:\n            # No multiple inheritance.\n            return\n        # Verify that inherited attributes are compatible.\n        mro = typ.mro[1:]\n        all_names = {name for base in mro for name in base.names}\n        for name in sorted(all_names - typ.names.keys()):\n            # Sort for reproducible message order.\n            # Attributes defined in both the type and base are skipped.\n            # Normal checks for attribute compatibility should catch any problems elsewhere.\n            if is_private(name):\n                continue\n            # Compare the first base defining a name with the rest.\n            # Remaining bases may not be pairwise compatible as the first base provides\n            # the used definition.\n            i, base = next((i, base) for i, base in enumerate(mro) if name in base.names)\n            for base2 in mro[i + 1 :]:\n                if name in base2.names and base2 not in base.mro:\n                    self.check_compatibility(name, base, base2, typ)\n\n    def check_compatibility(\n        self, name: str, base1: TypeInfo, base2: TypeInfo, ctx: TypeInfo\n    ) -> None:\n        \"\"\"Check if attribute name in base1 is compatible with base2 in multiple inheritance.\n\n        Assume base1 comes before base2 in the MRO, and that base1 and base2 don't have\n        a direct subclass relationship (i.e., the compatibility requirement only derives from\n        multiple inheritance).\n\n        This check verifies that a definition taken from base1 (and mapped to the current\n        class ctx), is type compatible with the definition taken from base2 (also mapped), so\n        that unsafe subclassing like this can be detected:\n            class A(Generic[T]):\n                def foo(self, x: T) -> None: ...\n\n            class B:\n                def foo(self, x: str) -> None: ...\n\n            class C(B, A[int]): ...  # this is unsafe because...\n\n            x: A[int] = C()\n            x.foo  # ...runtime type is (str) -> None, while static type is (int) -> None\n        \"\"\"\n        if name in (\"__init__\", \"__new__\", \"__init_subclass__\"):\n            # __init__ and friends can be incompatible -- it's a special case.\n            return\n        first = base1.names[name]\n        second = base2.names[name]\n        # Specify current_class explicitly as this function is called after leaving the class.\n        first_type, _ = self.node_type_from_base(name, base1, ctx, current_class=ctx)\n        second_type, _ = self.node_type_from_base(name, base2, ctx, current_class=ctx)\n\n        # TODO: use more principled logic to decide is_subtype() vs is_equivalent().\n        # We should rely on mutability of superclass node, not on types being Callable.\n        # (in particular handle settable properties with setter type different from getter).\n\n        p_first_type = get_proper_type(first_type)\n        p_second_type = get_proper_type(second_type)\n        if isinstance(p_first_type, FunctionLike) and isinstance(p_second_type, FunctionLike):\n            if p_first_type.is_type_obj() and p_second_type.is_type_obj():\n                # For class objects only check the subtype relationship of the classes,\n                # since we allow incompatible overrides of '__init__'/'__new__'\n                ok = is_subtype(\n                    left=fill_typevars_with_any(p_first_type.type_object()),\n                    right=fill_typevars_with_any(p_second_type.type_object()),\n                )\n            else:\n                assert first_type and second_type\n                ok = is_subtype(first_type, second_type, ignore_pos_arg_names=True)\n        elif first_type and second_type:\n            if second.node is not None and not self.is_writable_attribute(second.node):\n                ok = is_subtype(first_type, second_type)\n            else:\n                ok = is_equivalent(first_type, second_type)\n            if ok:\n                if (\n                    first.node\n                    and second.node\n                    and self.is_writable_attribute(second.node)\n                    and is_property(first.node)\n                    and isinstance(first.node, Decorator)\n                    and not isinstance(p_second_type, AnyType)\n                ):\n                    self.msg.fail(\n                        f'Cannot override writeable attribute \"{name}\" in base \"{base2.name}\"'\n                        f' with read-only property in base \"{base1.name}\"',\n                        ctx,\n                        code=codes.OVERRIDE,\n                    )\n        else:\n            if first_type is None:\n                self.msg.cannot_determine_type_in_base(name, base1.name, ctx)\n            if second_type is None:\n                self.msg.cannot_determine_type_in_base(name, base2.name, ctx)\n            ok = True\n        # Final attributes can never be overridden, but can override\n        # non-final read-only attributes.\n        if is_final_node(second.node) and not is_private(name):\n            self.msg.cant_override_final(name, base2.name, ctx)\n        if is_final_node(first.node):\n            self.check_if_final_var_override_writable(name, second.node, ctx)\n        # Some attributes like __slots__ and __deletable__ are special, and the type can\n        # vary across class hierarchy.\n        if isinstance(second.node, Var) and second.node.allow_incompatible_override:\n            ok = True\n        if not ok:\n            self.msg.base_class_definitions_incompatible(name, base1, base2, ctx)\n\n    def check_metaclass_compatibility(self, typ: TypeInfo) -> None:\n        \"\"\"Ensures that metaclasses of all parent types are compatible.\"\"\"\n        if (\n            typ.is_metaclass()\n            or typ.is_protocol\n            or typ.is_named_tuple\n            or typ.is_enum\n            or typ.typeddict_type is not None\n        ):\n            return  # Reasonable exceptions from this check\n\n        if typ.metaclass_type is None and any(\n            base.type.metaclass_type is not None for base in typ.bases\n        ):\n            self.fail(\n                \"Metaclass conflict: the metaclass of a derived class must be \"\n                \"a (non-strict) subclass of the metaclasses of all its bases\",\n                typ,\n                code=codes.METACLASS,\n            )\n            explanation = typ.explain_metaclass_conflict()\n            if explanation:\n                self.note(explanation, typ, code=codes.METACLASS)\n\n    def visit_import_from(self, node: ImportFrom) -> None:\n        for name, _ in node.names:\n            if (sym := self.globals.get(name)) is not None:\n                self.warn_deprecated(sym.node, node)\n        self.check_import(node)\n\n    def visit_import_all(self, node: ImportAll) -> None:\n        self.check_import(node)\n\n    def visit_import(self, node: Import) -> None:\n        self.check_import(node)\n\n    def check_import(self, node: ImportBase) -> None:\n        for assign in node.assignments:\n            lvalue = assign.lvalues[0]\n            lvalue_type, _, __ = self.check_lvalue(lvalue)\n            if lvalue_type is None:\n                # TODO: This is broken.\n                lvalue_type = AnyType(TypeOfAny.special_form)\n            assert isinstance(assign.rvalue, NameExpr)\n            message = message_registry.INCOMPATIBLE_IMPORT_OF.format(assign.rvalue.name)\n            self.check_simple_assignment(\n                lvalue_type,\n                assign.rvalue,\n                node,\n                msg=message,\n                lvalue_name=\"local name\",\n                rvalue_name=\"imported name\",\n            )\n\n    #\n    # Statements\n    #\n\n    def visit_block(self, b: Block) -> None:\n        if b.is_unreachable:\n            # This block was marked as being unreachable during semantic analysis.\n            # It turns out any blocks marked in this way are *intentionally* marked\n            # as unreachable -- so we don't display an error.\n            self.binder.unreachable()\n            return\n        for s in b.body:\n            if self.binder.is_unreachable():\n                if not self.should_report_unreachable_issues():\n                    break\n                if not self.is_noop_for_reachability(s):\n                    self.msg.unreachable_statement(s)\n                    break\n            else:\n                self.accept(s)\n                # Clear expression cache after each statement to avoid unlimited growth.\n                self.expr_checker.expr_cache.clear()\n\n    def should_report_unreachable_issues(self) -> bool:\n        return (\n            self.in_checked_function()\n            and self.options.warn_unreachable\n            and not self.current_node_deferred\n            and not self.binder.is_unreachable_warning_suppressed()\n        )\n\n    def is_noop_for_reachability(self, s: Statement) -> bool:\n        \"\"\"Returns 'true' if the given statement either throws an error of some kind\n        or is a no-op.\n\n        We use this function while handling the '--warn-unreachable' flag. When\n        that flag is present, we normally report an error on any unreachable statement.\n        But if that statement is just something like a 'pass' or a just-in-case 'assert False',\n        reporting an error would be annoying.\n        \"\"\"\n        if isinstance(s, AssertStmt) and is_false_literal(s.expr):\n            return True\n        elif isinstance(s, ReturnStmt) and is_literal_not_implemented(s.expr):\n            return True\n        elif isinstance(s, RaiseStmt):\n            return True\n        elif isinstance(s, ExpressionStmt):\n            if isinstance(s.expr, CallExpr):\n                with self.expr_checker.msg.filter_errors(filter_revealed_type=True):\n                    typ = get_proper_type(\n                        self.expr_checker.accept(\n                            s.expr, allow_none_return=True, always_allow_any=True\n                        )\n                    )\n\n                if isinstance(typ, UninhabitedType):\n                    return True\n        return False\n\n    def visit_assignment_stmt(self, s: AssignmentStmt) -> None:\n        \"\"\"Type check an assignment statement.\n\n        Handle all kinds of assignment statements (simple, indexed, multiple).\n        \"\"\"\n\n        # Avoid type checking type aliases in stubs to avoid false\n        # positives about modern type syntax available in stubs such\n        # as X | Y.\n        if not (s.is_alias_def and self.is_stub):\n            with self.enter_final_context(s.is_final_def):\n                self.check_assignment(s.lvalues[-1], s.rvalue, s.type is None, s.new_syntax)\n\n        if s.is_alias_def:\n            self.check_type_alias_rvalue(s)\n\n        if (\n            s.type is not None\n            and self.options.disallow_any_unimported\n            and has_any_from_unimported_type(s.type)\n        ):\n            if isinstance(s.lvalues[-1], TupleExpr):\n                # This is a multiple assignment. Instead of figuring out which type is problematic,\n                # give a generic error message.\n                self.msg.unimported_type_becomes_any(\n                    \"A type on this line\", AnyType(TypeOfAny.special_form), s\n                )\n            else:\n                self.msg.unimported_type_becomes_any(\"Type of variable\", s.type, s)\n        check_for_explicit_any(s.type, self.options, self.is_typeshed_stub, self.msg, context=s)\n\n        if len(s.lvalues) > 1:\n            # Chained assignment (e.g. x = y = ...).\n            # Make sure that rvalue type will not be reinferred.\n            if not self.has_type(s.rvalue):\n                self.expr_checker.accept(s.rvalue)\n            rvalue = self.temp_node(self.lookup_type(s.rvalue), s)\n            for lv in s.lvalues[:-1]:\n                with self.enter_final_context(s.is_final_def):\n                    self.check_assignment(lv, rvalue, s.type is None)\n\n        self.check_final(s)\n        if (\n            s.is_final_def\n            and s.type\n            and not has_no_typevars(s.type)\n            and self.scope.active_class() is not None\n        ):\n            self.fail(message_registry.DEPENDENT_FINAL_IN_CLASS_BODY, s)\n\n        if s.unanalyzed_type and not self.in_checked_function():\n            self.msg.annotation_in_unchecked_function(context=s)\n\n    def check_type_alias_rvalue(self, s: AssignmentStmt) -> None:\n        with self.msg.filter_errors():\n            alias_type = self.expr_checker.accept(s.rvalue)\n        self.store_type(s.lvalues[-1], alias_type)\n\n    def check_assignment(\n        self,\n        lvalue: Lvalue,\n        rvalue: Expression,\n        infer_lvalue_type: bool = True,\n        new_syntax: bool = False,\n    ) -> None:\n        \"\"\"Type check a single assignment: lvalue = rvalue.\"\"\"\n        if isinstance(lvalue, (TupleExpr, ListExpr)):\n            self.check_assignment_to_multiple_lvalues(\n                lvalue.items, rvalue, rvalue, infer_lvalue_type\n            )\n        else:\n            self.try_infer_partial_generic_type_from_assignment(lvalue, rvalue, \"=\")\n            lvalue_type, index_lvalue, inferred = self.check_lvalue(lvalue, rvalue)\n            # If we're assigning to __getattr__ or similar methods, check that the signature is\n            # valid.\n            if isinstance(lvalue, NameExpr) and lvalue.node:\n                name = lvalue.node.name\n                if name in (\"__setattr__\", \"__getattribute__\", \"__getattr__\"):\n                    # If an explicit type is given, use that.\n                    if lvalue_type:\n                        signature = lvalue_type\n                    else:\n                        signature = self.expr_checker.accept(rvalue)\n                    if signature:\n                        if name == \"__setattr__\":\n                            self.check_setattr_method(signature, lvalue)\n                        else:\n                            self.check_getattr_method(signature, lvalue, name)\n\n                if name == \"__slots__\" and self.scope.active_class() is not None:\n                    typ = lvalue_type or self.expr_checker.accept(rvalue)\n                    self.check_slots_definition(typ, lvalue)\n                if name == \"__match_args__\" and inferred is not None:\n                    typ = self.expr_checker.accept(rvalue)\n                    self.check_match_args(inferred, typ, lvalue)\n                if name == \"__post_init__\":\n                    active_class = self.scope.active_class()\n                    if active_class and dataclasses_plugin.is_processed_dataclass(active_class):\n                        self.fail(message_registry.DATACLASS_POST_INIT_MUST_BE_A_FUNCTION, rvalue)\n\n            if isinstance(lvalue, MemberExpr) and lvalue.name == \"__match_args__\":\n                self.fail(message_registry.CANNOT_MODIFY_MATCH_ARGS, lvalue)\n\n            if lvalue_type:\n                if isinstance(lvalue_type, PartialType) and lvalue_type.type is None:\n                    # Try to infer a proper type for a variable with a partial None type.\n                    rvalue_type = self.expr_checker.accept(rvalue)\n                    if isinstance(get_proper_type(rvalue_type), NoneType):\n                        # This doesn't actually provide any additional information -- multiple\n                        # None initializers preserve the partial None type.\n                        return\n\n                    var = lvalue_type.var\n                    if is_valid_inferred_type(\n                        rvalue_type, self.options, is_lvalue_final=var.is_final\n                    ):\n                        partial_types = self.find_partial_types(var)\n                        if partial_types is not None:\n                            if not self.current_node_deferred:\n                                # Partial type can't be final, so strip any literal values.\n                                rvalue_type = remove_instance_last_known_values(rvalue_type)\n                                inferred_type = make_simplified_union([rvalue_type, NoneType()])\n                                self.set_inferred_type(var, lvalue, inferred_type)\n                            else:\n                                var.type = None\n                            del partial_types[var]\n                            lvalue_type = var.type\n                    else:\n                        # Try to infer a partial type.\n                        if not self.infer_partial_type(var, lvalue, rvalue_type):\n                            # If that also failed, give up and let the caller know that we\n                            # cannot read their mind. The definition site will be reported later.\n                            # Calling .put() directly because the newly inferred type is\n                            # not a subtype of None - we are not looking for narrowing\n                            fallback = self.inference_error_fallback_type(rvalue_type)\n                            self.binder.put(lvalue, fallback)\n                            # Same as self.set_inference_error_fallback_type but inlined\n                            # to avoid computing fallback twice.\n                            # We are replacing partial<None> now, so the variable type\n                            # should remain optional.\n                            self.set_inferred_type(var, lvalue, make_optional_type(fallback))\n                elif (\n                    is_literal_none(rvalue)\n                    and isinstance(lvalue, NameExpr)\n                    and isinstance(lvalue.node, Var)\n                    and lvalue.node.is_initialized_in_class\n                    and not new_syntax\n                ):\n                    # Allow None's to be assigned to class variables with non-Optional types.\n                    rvalue_type = lvalue_type\n                elif (\n                    isinstance(lvalue, MemberExpr) and lvalue.kind is None\n                ):  # Ignore member access to modules\n                    instance_type = self.expr_checker.accept(lvalue.expr)\n                    rvalue_type, lvalue_type, infer_lvalue_type = self.check_member_assignment(\n                        lvalue, instance_type, lvalue_type, rvalue, context=rvalue\n                    )\n                else:\n                    # Hacky special case for assigning a literal None\n                    # to a variable defined in a previous if\n                    # branch. When we detect this, we'll go back and\n                    # make the type optional. This is somewhat\n                    # unpleasant, and a generalization of this would\n                    # be an improvement!\n                    if (\n                        not self.options.allow_redefinition_new\n                        and is_literal_none(rvalue)\n                        and isinstance(lvalue, NameExpr)\n                        and lvalue.kind == LDEF\n                        and isinstance(lvalue.node, Var)\n                        and lvalue.node.type\n                        and lvalue.node in self.var_decl_frames\n                        and not isinstance(get_proper_type(lvalue_type), AnyType)\n                    ):\n                        decl_frame_map = self.var_decl_frames[lvalue.node]\n                        # Check if the nearest common ancestor frame for the definition site\n                        # and the current site is the enclosing frame of an if/elif/else block.\n                        has_if_ancestor = False\n                        for frame in reversed(self.binder.frames):\n                            if frame.id in decl_frame_map:\n                                has_if_ancestor = frame.conditional_frame\n                                break\n                        if has_if_ancestor:\n                            lvalue_type = make_optional_type(lvalue_type)\n                            self.set_inferred_type(lvalue.node, lvalue, lvalue_type)\n\n                    rvalue_type, lvalue_type = self.check_simple_assignment(\n                        lvalue_type, rvalue, context=rvalue, inferred=inferred, lvalue=lvalue\n                    )\n                    # The above call may update inferred variable type. Prevent further\n                    # inference.\n                    inferred = None\n\n                # Special case: only non-abstract non-protocol classes can be assigned to\n                # variables with explicit type `Type[A]`, where A is protocol or abstract.\n                p_rvalue_type = get_proper_type(rvalue_type)\n                p_lvalue_type = get_proper_type(lvalue_type)\n                if (\n                    isinstance(p_rvalue_type, FunctionLike)\n                    and p_rvalue_type.is_type_obj()\n                    and (\n                        p_rvalue_type.type_object().is_abstract\n                        or p_rvalue_type.type_object().is_protocol\n                    )\n                    and isinstance(p_lvalue_type, TypeType)\n                    and isinstance(p_lvalue_type.item, Instance)\n                    and (\n                        p_lvalue_type.item.type.is_abstract or p_lvalue_type.item.type.is_protocol\n                    )\n                ):\n                    self.msg.concrete_only_assign(p_lvalue_type, rvalue)\n                    return\n                if rvalue_type and infer_lvalue_type and not isinstance(lvalue_type, PartialType):\n                    # Don't use type binder for definitions of special forms, like named tuples.\n                    if not (isinstance(lvalue, NameExpr) and lvalue.is_special_form):\n                        self.binder.assign_type(lvalue, rvalue_type, lvalue_type)\n                        if (\n                            isinstance(lvalue, NameExpr)\n                            and isinstance(lvalue.node, Var)\n                            and lvalue.node.is_inferred\n                            and lvalue.node.is_index_var\n                            and lvalue_type is not None\n                        ):\n                            lvalue.node.type = remove_instance_last_known_values(lvalue_type)\n                elif (\n                    self.options.allow_redefinition_new\n                    and lvalue_type is not None\n                    and not isinstance(lvalue_type, PartialType)\n                    # Note that `inferred is not None` is not a reliable check here, because\n                    # simple assignments like x = \"a\" are inferred during semantic analysis.\n                    and isinstance(lvalue, NameExpr)\n                    and isinstance(lvalue.node, Var)\n                    and lvalue.node.is_inferred\n                ):\n                    # TODO: Can we use put() here?\n                    self.binder.assign_type(lvalue, lvalue_type, lvalue_type)\n\n            elif index_lvalue:\n                self.check_indexed_assignment(index_lvalue, rvalue, lvalue)\n\n            if inferred:\n                type_context = self.get_variable_type_context(inferred, rvalue)\n                rvalue_type = self.expr_checker.accept(rvalue, type_context=type_context)\n                if not (\n                    inferred.is_final\n                    or inferred.is_index_var\n                    or (isinstance(lvalue, NameExpr) and lvalue.name == \"__match_args__\")\n                ):\n                    rvalue_type = remove_instance_last_known_values(rvalue_type)\n                self.infer_variable_type(inferred, lvalue, rvalue_type, rvalue)\n            self.check_assignment_to_slots(lvalue)\n            if (\n                isinstance(lvalue, RefExpr)\n                and not (isinstance(lvalue, NameExpr) and lvalue.name == \"__match_args__\")\n                and not self.can_skip_diagnostics\n            ):\n                # We check override here at the end after storing the inferred type, since\n                # override check will try to access the current attribute via symbol tables\n                # (like a regular attribute access).\n                self.check_compatibility_all_supers(lvalue, rvalue)\n\n    # (type, operator) tuples for augmented assignments supported with partial types\n    partial_type_augmented_ops: Final = {(\"builtins.list\", \"+\"), (\"builtins.set\", \"|\")}\n\n    def get_variable_type_context(self, inferred: Var, rvalue: Expression) -> Type | None:\n        type_contexts = []\n        if inferred.info:\n            for base in inferred.info.mro[1:]:\n                if inferred.name not in base.names:\n                    continue\n                # For inference within class body, get supertype attribute as it would look on\n                # a class object for lambdas overriding methods, etc.\n                base_node = base.names[inferred.name].node\n                base_type, _ = self.node_type_from_base(\n                    inferred.name,\n                    base,\n                    inferred,\n                    is_class=is_method(base_node)\n                    or isinstance(base_node, Var)\n                    and not is_instance_var(base_node),\n                )\n                if (\n                    base_type\n                    and not (isinstance(base_node, Var) and base_node.invalid_partial_type)\n                    and not isinstance(base_type, PartialType)\n                ):\n                    type_contexts.append(base_type)\n        # Use most derived supertype as type context if available.\n        if not type_contexts:\n            if inferred.name == \"__slots__\" and self.scope.active_class() is not None:\n                str_type = self.named_type(\"builtins.str\")\n                return self.named_generic_type(\"typing.Iterable\", [str_type])\n            if inferred.name == \"__all__\" and self.scope.is_top_level():\n                str_type = self.named_type(\"builtins.str\")\n                return self.named_generic_type(\"typing.Sequence\", [str_type])\n            return None\n        candidate = type_contexts[0]\n        for other in type_contexts:\n            if is_proper_subtype(other, candidate):\n                candidate = other\n            elif not is_subtype(candidate, other):\n                # Multiple incompatible candidates, cannot use any of them as context.\n                return None\n        return candidate\n\n    def try_infer_partial_generic_type_from_assignment(\n        self, lvalue: Lvalue, rvalue: Expression, op: str\n    ) -> None:\n        \"\"\"Try to infer a precise type for partial generic type from assignment.\n\n        'op' is '=' for normal assignment and a binary operator ('+', ...) for\n        augmented assignment.\n\n        Example where this happens:\n\n            x = []\n            if foo():\n                x = [1]  # Infer List[int] as type of 'x'\n        \"\"\"\n        var = None\n        if (\n            isinstance(lvalue, NameExpr)\n            and isinstance(lvalue.node, Var)\n            and isinstance(lvalue.node.type, PartialType)\n        ):\n            var = lvalue.node\n        elif isinstance(lvalue, MemberExpr):\n            var = self.expr_checker.get_partial_self_var(lvalue)\n        if var is not None:\n            typ = var.type\n            assert isinstance(typ, PartialType)\n            if typ.type is None:\n                return\n            # Return if this is an unsupported augmented assignment.\n            if op != \"=\" and (typ.type.fullname, op) not in self.partial_type_augmented_ops:\n                return\n            # TODO: some logic here duplicates the None partial type counterpart\n            #       inlined in check_assignment(), see #8043.\n            partial_types = self.find_partial_types(var)\n            if partial_types is None:\n                return\n            rvalue_type = self.expr_checker.accept(rvalue)\n            rvalue_type = get_proper_type(rvalue_type)\n            if isinstance(rvalue_type, Instance):\n                if rvalue_type.type == typ.type and is_valid_inferred_type(\n                    rvalue_type, self.options\n                ):\n                    var.type = rvalue_type\n                    del partial_types[var]\n            elif isinstance(rvalue_type, AnyType):\n                var.type = fill_typevars_with_any(typ.type)\n                del partial_types[var]\n\n    def check_compatibility_all_supers(self, lvalue: RefExpr, rvalue: Expression) -> None:\n        lvalue_node = lvalue.node\n        # Check if we are a class variable with at least one base class\n        if (\n            isinstance(lvalue_node, Var)\n            # If we have explicit annotation, there is no point in checking the override\n            # for each assignment, so we check only for the first one.\n            # TODO: for some reason annotated attributes on self are stored as inferred vars.\n            and (\n                lvalue_node.line == lvalue.line\n                or lvalue_node.is_inferred\n                and not lvalue_node.explicit_self_type\n            )\n            and lvalue.kind in (MDEF, None)  # None for Vars defined via self\n            and len(lvalue_node.info.bases) > 0\n        ):\n            for base in lvalue_node.info.mro[1:]:\n                tnode = base.names.get(lvalue_node.name)\n                if tnode is not None:\n                    if not self.check_compatibility_classvar_super(lvalue_node, base, tnode.node):\n                        # Show only one error per variable\n                        break\n\n                    if not self.check_compatibility_final_super(lvalue_node, base, tnode.node):\n                        # Show only one error per variable\n                        break\n\n            direct_bases = lvalue_node.info.direct_base_classes()\n            last_immediate_base = direct_bases[-1] if direct_bases else None\n\n            # The historical behavior for inferred vars was to compare rvalue type against\n            # the type declared in a superclass. To preserve this behavior, we temporarily\n            # store the rvalue type on the variable.\n            actual_lvalue_type = None\n            if lvalue_node.is_inferred and not lvalue_node.explicit_self_type:\n                # Don't use partial types as context, similar to regular code path.\n                ctx = lvalue_node.type if not isinstance(lvalue_node.type, PartialType) else None\n                rvalue_type = self.expr_checker.accept(rvalue, ctx)\n                actual_lvalue_type = lvalue_node.type\n                lvalue_node.type = rvalue_type\n            lvalue_type, _ = self.node_type_from_base(lvalue_node.name, lvalue_node.info, lvalue)\n            if lvalue_node.is_inferred and not lvalue_node.explicit_self_type:\n                lvalue_node.type = actual_lvalue_type\n\n            if not lvalue_type:\n                return\n\n            for base in lvalue_node.info.mro[1:]:\n                # The type of \"__slots__\" and some other attributes usually doesn't need to\n                # be compatible with a base class. We'll still check the type of \"__slots__\"\n                # against \"object\" as an exception.\n                if lvalue_node.allow_incompatible_override and not (\n                    lvalue_node.name == \"__slots__\" and base.fullname == \"builtins.object\"\n                ):\n                    continue\n\n                if is_private(lvalue_node.name):\n                    continue\n\n                base_type, base_node = self.node_type_from_base(lvalue_node.name, base, lvalue)\n                # TODO: if the r.h.s. is a descriptor, we should check setter override as well.\n                custom_setter = is_custom_settable_property(base_node)\n                if isinstance(base_type, PartialType):\n                    base_type = None\n\n                if base_type:\n                    assert base_node is not None\n                    if not self.check_compatibility_super(\n                        lvalue_type,\n                        rvalue,\n                        base,\n                        base_type,\n                        base_node,\n                        always_allow_covariant=custom_setter,\n                    ):\n                        # Only show one error per variable; even if other\n                        # base classes are also incompatible\n                        return\n                    if lvalue_type and custom_setter:\n                        base_type, _ = self.node_type_from_base(\n                            lvalue_node.name, base, lvalue, setter_type=True\n                        )\n                        # Setter type for a custom property must be ready if\n                        # the getter type is ready.\n                        assert base_type is not None\n                        if not is_subtype(base_type, lvalue_type):\n                            self.msg.incompatible_setter_override(\n                                lvalue, lvalue_type, base_type, base\n                            )\n                            return\n                    if base is last_immediate_base:\n                        # At this point, the attribute was found to be compatible with all\n                        # immediate parents.\n                        break\n\n    def check_compatibility_super(\n        self,\n        compare_type: Type,\n        rvalue: Expression,\n        base: TypeInfo,\n        base_type: Type,\n        base_node: Node,\n        always_allow_covariant: bool,\n    ) -> bool:\n        # TODO: check __set__() type override for custom descriptors.\n        # TODO: for descriptors check also class object access override.\n        ok = self.check_subtype(\n            compare_type,\n            base_type,\n            rvalue,\n            message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT,\n            \"expression has type\",\n            f'base class \"{base.name}\" defined the type as',\n        )\n        if (\n            ok\n            and codes.MUTABLE_OVERRIDE in self.options.enabled_error_codes\n            and self.is_writable_attribute(base_node)\n            and not always_allow_covariant\n        ):\n            ok = self.check_subtype(\n                base_type,\n                compare_type,\n                rvalue,\n                message_registry.COVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE,\n                f'base class \"{base.name}\" defined the type as',\n                \"expression has type\",\n            )\n        return ok\n\n    def node_type_from_base(\n        self,\n        name: str,\n        base: TypeInfo,\n        context: Context,\n        *,\n        setter_type: bool = False,\n        is_class: bool = False,\n        current_class: TypeInfo | None = None,\n    ) -> tuple[Type | None, SymbolNode | None]:\n        \"\"\"Find a type for a name in base class.\n\n        Return the type found and the corresponding node defining the name or None\n        for both if the name is not defined in base or the node type is not known (yet).\n        The type returned is already properly mapped/bound to the subclass.\n        If setter_type is True, return setter types for settable properties (otherwise the\n        getter type is returned).\n        \"\"\"\n        base_node = base.names.get(name)\n\n        # TODO: defer current node if the superclass node is not ready.\n        if (\n            not base_node\n            or isinstance(base_node.node, (Var, Decorator))\n            and not base_node.type\n            or isinstance(base_node.type, PartialType)\n            and base_node.type.type is not None\n        ):\n            return None, None\n\n        if current_class is None:\n            self_type = self.scope.current_self_type()\n        else:\n            self_type = fill_typevars(current_class)\n        assert self_type is not None, \"Internal error: base lookup outside class\"\n        if isinstance(self_type, TupleType):\n            instance = tuple_fallback(self_type)\n        else:\n            instance = self_type\n\n        mx = MemberContext(\n            is_lvalue=setter_type,\n            is_super=False,\n            is_operator=mypy.checkexpr.is_operator_method(name),\n            original_type=self_type,\n            context=context,\n            chk=self,\n            suppress_errors=True,\n        )\n        # TODO: we should not filter \"cannot determine type\" errors here.\n        with self.msg.filter_errors(filter_deprecated=True):\n            if is_class:\n                fallback = instance.type.metaclass_type or mx.named_type(\"builtins.type\")\n                base_type = analyze_class_attribute_access(\n                    instance, name, mx, mcs_fallback=fallback, override_info=base\n                )\n            else:\n                base_type = analyze_instance_member_access(name, instance, mx, base)\n        return base_type, base_node.node\n\n    def check_compatibility_classvar_super(\n        self, node: Var, base: TypeInfo, base_node: Node | None\n    ) -> bool:\n        if not isinstance(base_node, Var):\n            return True\n        if node.is_classvar and not base_node.is_classvar:\n            self.fail(message_registry.CANNOT_OVERRIDE_INSTANCE_VAR.format(base.name), node)\n            return False\n        elif not node.is_classvar and base_node.is_classvar:\n            self.fail(message_registry.CANNOT_OVERRIDE_CLASS_VAR.format(base.name), node)\n            return False\n        return True\n\n    def check_compatibility_final_super(\n        self, node: Var, base: TypeInfo, base_node: Node | None\n    ) -> bool:\n        \"\"\"Check if an assignment overrides a final attribute in a base class.\n\n        This only checks situations where either a node in base class is not a variable\n        but a final method, or where override is explicitly declared as final.\n        In these cases we give a more detailed error message. In addition, we check that\n        a final variable doesn't override writeable attribute, which is not safe.\n\n        Other situations are checked in `check_final()`.\n        \"\"\"\n        if not isinstance(base_node, (Var, FuncBase, Decorator)):\n            return True\n        if is_private(node.name):\n            return True\n        if base_node.is_final and (node.is_final or not isinstance(base_node, Var)):\n            # Give this error only for explicit override attempt with `Final`, or\n            # if we are overriding a final method with variable.\n            # Other override attempts will be flagged as assignment to constant\n            # in `check_final()`.\n            self.msg.cant_override_final(node.name, base.name, node)\n            return False\n        if node.is_final:\n            if base.fullname in ENUM_BASES or node.name in ENUM_SPECIAL_PROPS:\n                return True\n            self.check_if_final_var_override_writable(node.name, base_node, node)\n        return True\n\n    def check_if_final_var_override_writable(\n        self, name: str, base_node: Node | None, ctx: Context\n    ) -> None:\n        \"\"\"Check that a final variable doesn't override writeable attribute.\n\n        This is done to prevent situations like this:\n            class C:\n                attr = 1\n            class D(C):\n                attr: Final = 2\n\n            x: C = D()\n            x.attr = 3  # Oops!\n        \"\"\"\n        writable = True\n        if base_node:\n            writable = self.is_writable_attribute(base_node)\n        if writable:\n            self.msg.final_cant_override_writable(name, ctx)\n\n    def get_final_context(self) -> bool:\n        \"\"\"Check whether we a currently checking a final declaration.\"\"\"\n        return self._is_final_def\n\n    @contextmanager\n    def enter_final_context(self, is_final_def: bool) -> Iterator[None]:\n        \"\"\"Store whether the current checked assignment is a final declaration.\"\"\"\n        old_ctx = self._is_final_def\n        self._is_final_def = is_final_def\n        try:\n            yield\n        finally:\n            self._is_final_def = old_ctx\n\n    def check_final(self, s: AssignmentStmt | OperatorAssignmentStmt | AssignmentExpr) -> None:\n        \"\"\"Check if this assignment does not assign to a final attribute.\n\n        This function performs the check only for name assignments at module\n        and class scope. The assignments to `obj.attr` and `Cls.attr` are checked\n        in checkmember.py.\n        \"\"\"\n        if isinstance(s, AssignmentStmt):\n            lvs = self.flatten_lvalues(s.lvalues)\n        elif isinstance(s, AssignmentExpr):\n            lvs = [s.target]\n        else:\n            lvs = [s.lvalue]\n        is_final_decl = s.is_final_def if isinstance(s, AssignmentStmt) else False\n        if is_final_decl and (active_class := self.scope.active_class()):\n            lv = lvs[0]\n            assert isinstance(lv, RefExpr)\n            if lv.node is not None:\n                assert isinstance(lv.node, Var)\n                if (\n                    lv.node.final_unset_in_class\n                    and not lv.node.final_set_in_init\n                    and not self.is_stub  # It is OK to skip initializer in stub files.\n                    and\n                    # Avoid extra error messages, if there is no type in Final[...],\n                    # then we already reported the error about missing r.h.s.\n                    isinstance(s, AssignmentStmt)\n                    and s.type is not None\n                    # Avoid extra error message for NamedTuples,\n                    # they were reported during semanal\n                    and not active_class.is_named_tuple\n                ):\n                    self.msg.final_without_value(s)\n        for lv in lvs:\n            if isinstance(lv, RefExpr) and isinstance(lv.node, Var):\n                name = lv.node.name\n                cls = self.scope.active_class()\n                if cls is not None:\n                    # These additional checks exist to give more error messages\n                    # even if the final attribute was overridden with a new symbol\n                    # (which is itself an error)...\n                    for base in cls.mro[1:]:\n                        sym = base.names.get(name)\n                        # We only give this error if base node is variable,\n                        # overriding final method will be caught in\n                        # `check_compatibility_final_super()`.\n                        if sym and isinstance(sym.node, Var):\n                            if sym.node.is_final and not is_final_decl:\n                                self.msg.cant_assign_to_final(name, sym.node.info is None, s)\n                                # ...but only once\n                                break\n                if lv.node.is_final and not is_final_decl:\n                    self.msg.cant_assign_to_final(name, lv.node.info is None, s)\n\n    def check_assignment_to_slots(self, lvalue: Lvalue) -> None:\n        if not isinstance(lvalue, MemberExpr):\n            return\n\n        inst = get_proper_type(self.expr_checker.accept(lvalue.expr))\n        if isinstance(inst, TypeVarType) and inst.id.is_self():\n            # Unwrap self type\n            inst = get_proper_type(inst.upper_bound)\n        if not isinstance(inst, Instance):\n            return\n        if inst.type.slots is None:\n            return  # Slots do not exist, we can allow any assignment\n        if lvalue.name in inst.type.slots:\n            return  # We are assigning to an existing slot\n        for base_info in inst.type.mro[:-1]:\n            if base_info.names.get(\"__setattr__\") is not None:\n                # When type has `__setattr__` defined,\n                # we can assign any dynamic value.\n                # We exclude object, because it always has `__setattr__`.\n                return\n\n        definition = inst.type.get(lvalue.name)\n        if definition is None:\n            # We don't want to duplicate\n            # `\"SomeType\" has no attribute \"some_attr\"`\n            # error twice.\n            return\n        if self.is_assignable_slot(lvalue, definition.type):\n            return\n\n        self.fail(\n            message_registry.NAME_NOT_IN_SLOTS.format(lvalue.name, inst.type.fullname), lvalue\n        )\n\n    def is_assignable_slot(self, lvalue: Lvalue, typ: Type | None) -> bool:\n        if getattr(lvalue, \"node\", None):\n            return False  # This is a definition\n\n        typ = get_proper_type(typ)\n        if typ is None or isinstance(typ, AnyType):\n            return True  # Any can be literally anything, like `@property`\n        if isinstance(typ, Instance):\n            # When working with instances, we need to know if they contain\n            # `__set__` special method. Like `@property` does.\n            # This makes assigning to properties possible,\n            # even without extra slot spec.\n            return typ.type.get(\"__set__\") is not None\n        if isinstance(typ, FunctionLike):\n            return True  # Can be a property, or some other magic\n        if isinstance(typ, UnionType):\n            return all(self.is_assignable_slot(lvalue, u) for u in typ.items)\n        return False\n\n    def flatten_rvalues(self, rvalues: list[Expression]) -> list[Expression]:\n        \"\"\"Flatten expression list by expanding those * items that have tuple type.\n\n        For each regular type item in the tuple type use a TempNode(), for an Unpack\n        item use a corresponding StarExpr(TempNode()).\n        \"\"\"\n        new_rvalues = []\n        for rv in rvalues:\n            if not isinstance(rv, StarExpr):\n                new_rvalues.append(rv)\n                continue\n            typ = get_proper_type(self.expr_checker.accept(rv.expr))\n            if not isinstance(typ, TupleType):\n                new_rvalues.append(rv)\n                continue\n            for t in typ.items:\n                if not isinstance(t, UnpackType):\n                    new_rvalues.append(TempNode(t))\n                else:\n                    unpacked = get_proper_type(t.type)\n                    if isinstance(unpacked, TypeVarTupleType):\n                        fallback = unpacked.upper_bound\n                    else:\n                        assert (\n                            isinstance(unpacked, Instance)\n                            and unpacked.type.fullname == \"builtins.tuple\"\n                        )\n                        fallback = unpacked\n                    new_rvalues.append(StarExpr(TempNode(fallback)))\n        return new_rvalues\n\n    def check_assignment_to_multiple_lvalues(\n        self,\n        lvalues: list[Lvalue],\n        rvalue: Expression,\n        context: Context,\n        infer_lvalue_type: bool = True,\n    ) -> None:\n        if isinstance(rvalue, (TupleExpr, ListExpr)):\n            # Recursively go into Tuple or List expression rhs instead of\n            # using the type of rhs, because this allows more fine-grained\n            # control in cases like: a, b = [int, str] where rhs would get\n            # type List[object]\n            rvalues: list[Expression] = []\n            iterable_type: Type | None = None\n            last_idx: int | None = None\n            for idx_rval, rval in enumerate(self.flatten_rvalues(rvalue.items)):\n                if isinstance(rval, StarExpr):\n                    typs = get_proper_type(self.expr_checker.accept(rval.expr))\n                    if self.type_is_iterable(typs) and isinstance(typs, Instance):\n                        if iterable_type is not None and iterable_type != self.iterable_item_type(\n                            typs, rvalue\n                        ):\n                            self.fail(message_registry.CONTIGUOUS_ITERABLE_EXPECTED, context)\n                        else:\n                            if last_idx is None or last_idx + 1 == idx_rval:\n                                rvalues.append(rval)\n                                last_idx = idx_rval\n                                iterable_type = self.iterable_item_type(typs, rvalue)\n                            else:\n                                self.fail(message_registry.CONTIGUOUS_ITERABLE_EXPECTED, context)\n                    else:\n                        self.fail(message_registry.ITERABLE_TYPE_EXPECTED.format(typs), context)\n                else:\n                    rvalues.append(rval)\n            iterable_start: int | None = None\n            iterable_end: int | None = None\n            for i, rval in enumerate(rvalues):\n                if isinstance(rval, StarExpr):\n                    typs = get_proper_type(self.expr_checker.accept(rval.expr))\n                    if self.type_is_iterable(typs) and isinstance(typs, Instance):\n                        if iterable_start is None:\n                            iterable_start = i\n                        iterable_end = i\n            if (\n                iterable_start is not None\n                and iterable_end is not None\n                and iterable_type is not None\n            ):\n                iterable_num = iterable_end - iterable_start + 1\n                rvalue_needed = len(lvalues) - (len(rvalues) - iterable_num)\n                if rvalue_needed > 0:\n                    rvalues = (\n                        rvalues[0:iterable_start]\n                        + [TempNode(iterable_type, context=rval) for _ in range(rvalue_needed)]\n                        + rvalues[iterable_end + 1 :]\n                    )\n\n            if self.check_rvalue_count_in_assignment(lvalues, len(rvalues), context):\n                star_index = next(\n                    (i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues)\n                )\n\n                left_lvs = lvalues[:star_index]\n                star_lv = (\n                    cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None\n                )\n                right_lvs = lvalues[star_index + 1 :]\n\n                left_rvs, star_rvs, right_rvs = self.split_around_star(\n                    rvalues, star_index, len(lvalues)\n                )\n\n                lr_pairs = list(zip(left_lvs, left_rvs))\n                if star_lv:\n                    rv_list = ListExpr(star_rvs)\n                    rv_list.set_line(rvalue)\n                    lr_pairs.append((star_lv.expr, rv_list))\n                lr_pairs.extend(zip(right_lvs, right_rvs))\n\n                for lv, rv in lr_pairs:\n                    self.check_assignment(lv, rv, infer_lvalue_type)\n        else:\n            self.check_multi_assignment(lvalues, rvalue, context, infer_lvalue_type)\n\n    def check_rvalue_count_in_assignment(\n        self,\n        lvalues: list[Lvalue],\n        rvalue_count: int,\n        context: Context,\n        rvalue_unpack: int | None = None,\n    ) -> bool:\n        if rvalue_unpack is not None:\n            if not any(isinstance(e, StarExpr) for e in lvalues):\n                self.fail(\"Variadic tuple unpacking requires a star target\", context)\n                return False\n            if len(lvalues) > rvalue_count:\n                self.fail(message_registry.TOO_MANY_TARGETS_FOR_VARIADIC_UNPACK, context)\n                return False\n            left_star_index = next(i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr))\n            left_prefix = left_star_index\n            left_suffix = len(lvalues) - left_star_index - 1\n            right_prefix = rvalue_unpack\n            right_suffix = rvalue_count - rvalue_unpack - 1\n            if left_suffix > right_suffix or left_prefix > right_prefix:\n                # Case of asymmetric unpack like:\n                #     rv: tuple[int, *Ts, int, int]\n                #     x, y, *xs, z = rv\n                # it is technically valid, but is tricky to reason about.\n                # TODO: support this (at least if the r.h.s. unpack is a homogeneous tuple).\n                self.fail(message_registry.TOO_MANY_TARGETS_FOR_VARIADIC_UNPACK, context)\n            return True\n        if any(isinstance(lvalue, StarExpr) for lvalue in lvalues):\n            if len(lvalues) - 1 > rvalue_count:\n                self.msg.wrong_number_values_to_unpack(rvalue_count, len(lvalues) - 1, context)\n                return False\n        elif rvalue_count != len(lvalues):\n            self.msg.wrong_number_values_to_unpack(rvalue_count, len(lvalues), context)\n            return False\n        return True\n\n    def check_multi_assignment(\n        self,\n        lvalues: list[Lvalue],\n        rvalue: Expression,\n        context: Context,\n        infer_lvalue_type: bool = True,\n        rv_type: Type | None = None,\n        undefined_rvalue: bool = False,\n    ) -> None:\n        \"\"\"Check the assignment of one rvalue to a number of lvalues.\"\"\"\n\n        # Infer the type of an ordinary rvalue expression.\n        # TODO: maybe elsewhere; redundant.\n        rvalue_type = get_proper_type(rv_type or self.expr_checker.accept(rvalue))\n\n        if isinstance(rvalue_type, TypeVarLikeType):\n            rvalue_type = get_proper_type(rvalue_type.upper_bound)\n\n        if isinstance(rvalue_type, UnionType):\n            # If this is an Optional type in non-strict Optional code, unwrap it.\n            relevant_items = rvalue_type.relevant_items()\n            if len(relevant_items) == 1:\n                rvalue_type = get_proper_type(relevant_items[0])\n\n        if (\n            isinstance(rvalue_type, TupleType)\n            and find_unpack_in_list(rvalue_type.items) is not None\n        ):\n            # Normalize for consistent handling with \"old-style\" homogeneous tuples.\n            rvalue_type = expand_type(rvalue_type, {})\n\n        if isinstance(rvalue_type, AnyType):\n            for lv in lvalues:\n                if isinstance(lv, StarExpr):\n                    lv = lv.expr\n                temp_node = self.temp_node(\n                    AnyType(TypeOfAny.from_another_any, source_any=rvalue_type), context\n                )\n                self.check_assignment(lv, temp_node, infer_lvalue_type)\n        elif isinstance(rvalue_type, TupleType):\n            self.check_multi_assignment_from_tuple(\n                lvalues, rvalue, rvalue_type, context, undefined_rvalue, infer_lvalue_type\n            )\n        elif isinstance(rvalue_type, UnionType):\n            self.check_multi_assignment_from_union(\n                lvalues, rvalue, rvalue_type, context, infer_lvalue_type\n            )\n        else:\n            rvalue_literal = rvalue_type\n            if isinstance(rvalue_type, Instance) and rvalue_type.type.fullname == \"builtins.str\":\n                if rvalue_type.last_known_value is None:\n                    self.msg.unpacking_strings_disallowed(context)\n                else:\n                    rvalue_literal = rvalue_type.last_known_value\n            if (\n                isinstance(rvalue_literal, LiteralType)\n                and isinstance(rvalue_literal.value, str)\n                and len(lvalues) != len(rvalue_literal.value)\n            ):\n                self.msg.unpacking_strings_disallowed(context)\n\n            self.check_multi_assignment_from_iterable(\n                lvalues, rvalue_type, context, infer_lvalue_type\n            )\n\n    def check_multi_assignment_from_union(\n        self,\n        lvalues: list[Expression],\n        rvalue: Expression,\n        rvalue_type: UnionType,\n        context: Context,\n        infer_lvalue_type: bool,\n    ) -> None:\n        \"\"\"Check assignment to multiple lvalue targets when rvalue type is a Union[...].\n        For example:\n\n            t: Union[Tuple[int, int], Tuple[str, str]]\n            x, y = t\n            reveal_type(x)  # Union[int, str]\n\n        The idea in this case is to process the assignment for every item of the union.\n        Important note: the types are collected in two places, 'union_types' contains\n        inferred types for first assignments, 'assignments' contains the narrowed types\n        for binder.\n        \"\"\"\n        self.no_partial_types = True\n        transposed: tuple[list[Type], ...] = tuple([] for _ in self.flatten_lvalues(lvalues))\n        # Notify binder that we want to defer bindings and instead collect types.\n        with self.binder.accumulate_type_assignments() as assignments:\n            for item in rvalue_type.items:\n                # Type check the assignment separately for each union item and collect\n                # the inferred lvalue types for each union item.\n                self.check_multi_assignment(\n                    lvalues,\n                    rvalue,\n                    context,\n                    infer_lvalue_type=infer_lvalue_type,\n                    rv_type=item,\n                    undefined_rvalue=True,\n                )\n                for t, lv in zip(transposed, self.flatten_lvalues(lvalues)):\n                    # We can access _type_maps directly since temporary type maps are\n                    # only created within expressions.\n                    t.append(self._type_maps[-1].pop(lv, AnyType(TypeOfAny.special_form)))\n        union_types = tuple(make_simplified_union(col) for col in transposed)\n        for expr, items in assignments.items():\n            # Bind a union of types collected in 'assignments' to every expression.\n            if isinstance(expr, StarExpr):\n                expr = expr.expr\n\n            # TODO: See comment in binder.py, ConditionalTypeBinder.assign_type\n            # It's unclear why the 'declared_type' param is sometimes 'None'\n            clean_items: list[tuple[Type, Type]] = []\n            for type, declared_type in items:\n                assert declared_type is not None\n                clean_items.append((type, declared_type))\n\n            types, declared_types = zip(*clean_items)\n            self.binder.assign_type(\n                expr,\n                make_simplified_union(list(types)),\n                make_simplified_union(list(declared_types)),\n            )\n        for union, lv in zip(union_types, self.flatten_lvalues(lvalues)):\n            # Properly store the inferred types.\n            _1, _2, inferred = self.check_lvalue(lv)\n            if inferred:\n                self.set_inferred_type(inferred, lv, union)\n            else:\n                self.store_type(lv, union)\n        self.no_partial_types = False\n\n    def flatten_lvalues(self, lvalues: list[Expression]) -> list[Expression]:\n        res: list[Expression] = []\n        for lv in lvalues:\n            if isinstance(lv, (TupleExpr, ListExpr)):\n                res.extend(self.flatten_lvalues(lv.items))\n            if isinstance(lv, StarExpr):\n                # Unwrap StarExpr, since it is unwrapped by other helpers.\n                lv = lv.expr\n            res.append(lv)\n        return res\n\n    def check_multi_assignment_from_tuple(\n        self,\n        lvalues: list[Lvalue],\n        rvalue: Expression,\n        rvalue_type: TupleType,\n        context: Context,\n        undefined_rvalue: bool,\n        infer_lvalue_type: bool = True,\n    ) -> None:\n        rvalue_unpack = find_unpack_in_list(rvalue_type.items)\n        if self.check_rvalue_count_in_assignment(\n            lvalues, len(rvalue_type.items), context, rvalue_unpack=rvalue_unpack\n        ):\n            star_index = next(\n                (i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues)\n            )\n\n            left_lvs = lvalues[:star_index]\n            star_lv = cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None\n            right_lvs = lvalues[star_index + 1 :]\n\n            if not undefined_rvalue:\n                # Infer rvalue again, now in the correct type context.\n                lvalue_type = self.lvalue_type_for_inference(lvalues, rvalue_type)\n                reinferred_rvalue_type = get_proper_type(\n                    self.expr_checker.accept(rvalue, lvalue_type)\n                )\n\n                if isinstance(reinferred_rvalue_type, TypeVarLikeType):\n                    reinferred_rvalue_type = get_proper_type(reinferred_rvalue_type.upper_bound)\n                if isinstance(reinferred_rvalue_type, UnionType):\n                    # If this is an Optional type in non-strict Optional code, unwrap it.\n                    relevant_items = reinferred_rvalue_type.relevant_items()\n                    if len(relevant_items) == 1:\n                        reinferred_rvalue_type = get_proper_type(relevant_items[0])\n                if isinstance(reinferred_rvalue_type, UnionType):\n                    self.check_multi_assignment_from_union(\n                        lvalues, rvalue, reinferred_rvalue_type, context, infer_lvalue_type\n                    )\n                    return\n                if isinstance(reinferred_rvalue_type, AnyType):\n                    # We can get Any if the current node is\n                    # deferred. Doing more inference in deferred nodes\n                    # is hard, so give up for now.  We can also get\n                    # here if reinferring types above changes the\n                    # inferred return type for an overloaded function\n                    # to be ambiguous.\n                    return\n                assert isinstance(reinferred_rvalue_type, TupleType)\n                rvalue_type = reinferred_rvalue_type\n\n            left_rv_types, star_rv_types, right_rv_types = self.split_around_star(\n                rvalue_type.items, star_index, len(lvalues)\n            )\n\n            for lv, rv_type in zip(left_lvs, left_rv_types):\n                self.check_assignment(lv, self.temp_node(rv_type, context), infer_lvalue_type)\n            if star_lv:\n                list_expr = ListExpr(\n                    [\n                        (\n                            self.temp_node(rv_type, context)\n                            if not isinstance(rv_type, UnpackType)\n                            else StarExpr(self.temp_node(rv_type.type, context))\n                        )\n                        for rv_type in star_rv_types\n                    ]\n                )\n                list_expr.set_line(context)\n                self.check_assignment(star_lv.expr, list_expr, infer_lvalue_type)\n            for lv, rv_type in zip(right_lvs, right_rv_types):\n                self.check_assignment(lv, self.temp_node(rv_type, context), infer_lvalue_type)\n        else:\n            # Store meaningful Any types for lvalues, errors are already given\n            # by check_rvalue_count_in_assignment()\n            if infer_lvalue_type:\n                for lv in lvalues:\n                    if (\n                        isinstance(lv, NameExpr)\n                        and isinstance(lv.node, Var)\n                        and lv.node.type is None\n                    ):\n                        lv.node.type = AnyType(TypeOfAny.from_error)\n                    elif isinstance(lv, StarExpr):\n                        if (\n                            isinstance(lv.expr, NameExpr)\n                            and isinstance(lv.expr.node, Var)\n                            and lv.expr.node.type is None\n                        ):\n                            lv.expr.node.type = self.named_generic_type(\n                                \"builtins.list\", [AnyType(TypeOfAny.from_error)]\n                            )\n\n    def lvalue_type_for_inference(self, lvalues: list[Lvalue], rvalue_type: TupleType) -> Type:\n        star_index = next(\n            (i for i, lv in enumerate(lvalues) if isinstance(lv, StarExpr)), len(lvalues)\n        )\n        left_lvs = lvalues[:star_index]\n        star_lv = cast(StarExpr, lvalues[star_index]) if star_index != len(lvalues) else None\n        right_lvs = lvalues[star_index + 1 :]\n        left_rv_types, star_rv_types, right_rv_types = self.split_around_star(\n            rvalue_type.items, star_index, len(lvalues)\n        )\n\n        type_parameters: list[Type] = []\n\n        def append_types_for_inference(lvs: list[Expression], rv_types: list[Type]) -> None:\n            for lv, rv_type in zip(lvs, rv_types):\n                sub_lvalue_type, index_expr, inferred = self.check_lvalue(lv)\n                if sub_lvalue_type and not isinstance(sub_lvalue_type, PartialType):\n                    type_parameters.append(sub_lvalue_type)\n                else:  # index lvalue\n                    # TODO Figure out more precise type context, probably\n                    #      based on the type signature of the _set method.\n                    type_parameters.append(rv_type)\n\n        append_types_for_inference(left_lvs, left_rv_types)\n\n        if star_lv:\n            sub_lvalue_type, index_expr, inferred = self.check_lvalue(star_lv.expr)\n            if sub_lvalue_type and not isinstance(sub_lvalue_type, PartialType):\n                type_parameters.extend([sub_lvalue_type] * len(star_rv_types))\n            else:  # index lvalue\n                # TODO Figure out more precise type context, probably\n                #      based on the type signature of the _set method.\n                type_parameters.extend(star_rv_types)\n\n        append_types_for_inference(right_lvs, right_rv_types)\n\n        return TupleType(type_parameters, self.named_type(\"builtins.tuple\"))\n\n    def split_around_star(\n        self, items: list[T], star_index: int, length: int\n    ) -> tuple[list[T], list[T], list[T]]:\n        \"\"\"Splits a list of items in three to match another list of length 'length'\n        that contains a starred expression at 'star_index' in the following way:\n\n        star_index = 2, length = 5 (i.e., [a,b,*,c,d]), items = [1,2,3,4,5,6,7]\n        returns in: ([1,2], [3,4,5], [6,7])\n        \"\"\"\n        nr_right_of_star = length - star_index - 1\n        right_index = -nr_right_of_star if nr_right_of_star != 0 else len(items)\n        left = items[:star_index]\n        star = items[star_index:right_index]\n        right = items[right_index:]\n        return left, star, right\n\n    def type_is_iterable(self, type: Type) -> bool:\n        type = get_proper_type(type)\n        if isinstance(type, FunctionLike) and type.is_type_obj():\n            type = type.fallback\n        return is_subtype(\n            type, self.named_generic_type(\"typing.Iterable\", [AnyType(TypeOfAny.special_form)])\n        )\n\n    def check_multi_assignment_from_iterable(\n        self,\n        lvalues: list[Lvalue],\n        rvalue_type: Type,\n        context: Context,\n        infer_lvalue_type: bool = True,\n    ) -> None:\n        rvalue_type = get_proper_type(rvalue_type)\n        if self.type_is_iterable(rvalue_type):\n            item_type = self.iterable_item_type(rvalue_type, context)\n            for lv in lvalues:\n                if isinstance(lv, StarExpr):\n                    items_type = self.named_generic_type(\"builtins.list\", [item_type])\n                    self.check_assignment(\n                        lv.expr, self.temp_node(items_type, context), infer_lvalue_type\n                    )\n                else:\n                    self.check_assignment(\n                        lv, self.temp_node(item_type, context), infer_lvalue_type\n                    )\n        else:\n            self.msg.type_not_iterable(rvalue_type, context)\n\n    def check_lvalue(\n        self, lvalue: Lvalue, rvalue: Expression | None = None\n    ) -> tuple[Type | None, IndexExpr | None, Var | None]:\n        lvalue_type = None\n        index_lvalue = None\n        inferred = None\n\n        # When revisiting the initial assignment (for example in a loop),\n        # treat is as regular if redefinitions are allowed.\n        skip_definition = (\n            self.options.allow_redefinition_new\n            and isinstance(lvalue, NameExpr)\n            and isinstance(lvalue.node, Var)\n            and lvalue.node.is_inferred\n            and lvalue.node.type is not None\n            and not isinstance(lvalue.node.type, PartialType)\n            # Indexes in for loops require special handling, we need to reset them to\n            # a literal value on each loop, but binder doesn't work well with literals.\n            and not lvalue.node.is_index_var\n        )\n\n        if (\n            self.is_definition(lvalue)\n            and (not isinstance(lvalue, NameExpr) or isinstance(lvalue.node, Var))\n            and not skip_definition\n        ):\n            if isinstance(lvalue, NameExpr):\n                assert isinstance(lvalue.node, Var)\n                inferred = lvalue.node\n            else:\n                assert isinstance(lvalue, MemberExpr)\n                self.expr_checker.accept(lvalue.expr)\n                inferred = lvalue.def_var\n        elif isinstance(lvalue, IndexExpr):\n            index_lvalue = lvalue\n        elif isinstance(lvalue, MemberExpr):\n            lvalue_type = self.expr_checker.analyze_ordinary_member_access(lvalue, True, rvalue)\n            self.store_type(lvalue, lvalue_type)\n        elif isinstance(lvalue, NameExpr):\n            lvalue_type = self.expr_checker.analyze_ref_expr(lvalue, lvalue=True)\n            if (\n                self.options.allow_redefinition_new\n                and isinstance(lvalue.node, Var)\n                # We allow redefinition for function arguments inside function body.\n                # Although we normally do this for variables without annotation, users\n                # don't have a choice to leave a function argument without annotation.\n                and (lvalue.node.is_inferred or lvalue.node.is_argument)\n            ):\n                inferred = lvalue.node\n            self.store_type(lvalue, lvalue_type)\n        elif isinstance(lvalue, (TupleExpr, ListExpr)):\n            types = [\n                self.check_lvalue(sub_expr)[0] or\n                # This type will be used as a context for further inference of rvalue,\n                # we put Uninhabited if there is no information available from lvalue.\n                UninhabitedType()\n                for sub_expr in lvalue.items\n            ]\n            lvalue_type = TupleType(types, self.named_type(\"builtins.tuple\"))\n        elif isinstance(lvalue, StarExpr):\n            lvalue_type, _, _ = self.check_lvalue(lvalue.expr)\n        else:\n            lvalue_type = self.expr_checker.accept(lvalue)\n\n        return lvalue_type, index_lvalue, inferred\n\n    def is_definition(self, s: Lvalue) -> bool:\n        if isinstance(s, NameExpr):\n            if s.is_inferred_def:\n                return True\n            # If the node type is not defined, this must the first assignment\n            # that we process => this is a definition, even though the semantic\n            # analyzer did not recognize this as such. This can arise in code\n            # that uses isinstance checks, if type checking of the primary\n            # definition is skipped due to an always False type check.\n            node = s.node\n            if isinstance(node, Var):\n                return node.type is None\n        elif isinstance(s, MemberExpr):\n            return s.is_inferred_def\n        return False\n\n    def infer_variable_type(\n        self, name: Var, lvalue: Lvalue, init_type: Type, context: Context\n    ) -> None:\n        \"\"\"Infer the type of initialized variables from initializer type.\"\"\"\n        if isinstance(init_type, DeletedType):\n            self.msg.deleted_as_rvalue(init_type, context)\n        elif (\n            not is_valid_inferred_type(\n                init_type,\n                self.options,\n                is_lvalue_final=name.is_final,\n                is_lvalue_member=isinstance(lvalue, MemberExpr),\n            )\n            and not (\n                # Trust None assignments to dunder methods\n                # This is a bit ad-hoc, but it improves protocol\n                # (non-)assignability, for instance `__hash__ = None`\n                self.scope.active_class()\n                and is_dunder(name.name)\n                and isinstance(get_proper_type(init_type), NoneType)\n            )\n            and not self.no_partial_types\n        ):\n            # We cannot use the type of the initialization expression for full type\n            # inference (it's not specific enough), but we might be able to give\n            # partial type which will be made more specific later. A partial type\n            # gets generated in assignment like 'x = []' where item type is not known.\n            if name.name != \"_\" and not self.infer_partial_type(name, lvalue, init_type):\n                self.msg.need_annotation_for_var(name, context, self.options)\n                self.set_inference_error_fallback_type(name, lvalue, init_type)\n        elif (\n            isinstance(lvalue, MemberExpr)\n            and self.inferred_attribute_types is not None\n            and lvalue.def_var\n            and lvalue.def_var in self.inferred_attribute_types\n            and not is_same_type(self.inferred_attribute_types[lvalue.def_var], init_type)\n        ):\n            # Multiple, inconsistent types inferred for an attribute.\n            self.msg.need_annotation_for_var(name, context, self.options)\n            name.type = AnyType(TypeOfAny.from_error)\n        else:\n            # Infer type of the target.\n\n            # Make the type more general (strip away function names etc.).\n            init_type = strip_type(init_type)\n\n            self.set_inferred_type(name, lvalue, init_type)\n            if self.options.allow_redefinition_new:\n                self.binder.assign_type(lvalue, init_type, init_type)\n\n    def infer_partial_type(self, name: Var, lvalue: Lvalue, init_type: Type) -> bool:\n        init_type = get_proper_type(init_type)\n        if isinstance(init_type, NoneType) and (\n            isinstance(lvalue, MemberExpr) or not self.options.allow_redefinition_new\n        ):\n            # When using --allow-redefinition-new, None types aren't special\n            # when inferring simple variable types.\n            partial_type = PartialType(None, name)\n        elif isinstance(init_type, Instance):\n            fullname = init_type.type.fullname\n            is_ref = isinstance(lvalue, RefExpr)\n            if (\n                is_ref\n                and (\n                    fullname == \"builtins.list\"\n                    or fullname == \"builtins.set\"\n                    or fullname == \"builtins.dict\"\n                    or fullname == \"collections.OrderedDict\"\n                )\n                and all(\n                    isinstance(t, (NoneType, UninhabitedType))\n                    for t in get_proper_types(init_type.args)\n                )\n            ):\n                partial_type = PartialType(init_type.type, name)\n            elif is_ref and fullname == \"collections.defaultdict\":\n                arg0 = get_proper_type(init_type.args[0])\n                arg1 = get_proper_type(init_type.args[1])\n                if isinstance(\n                    arg0, (NoneType, UninhabitedType)\n                ) and self.is_valid_defaultdict_partial_value_type(arg1):\n                    arg1 = erase_type(arg1)\n                    assert isinstance(arg1, Instance)\n                    partial_type = PartialType(init_type.type, name, arg1)\n                else:\n                    return False\n            else:\n                return False\n        else:\n            return False\n        self.set_inferred_type(name, lvalue, partial_type)\n        self.partial_types[-1].map[name] = lvalue\n        return True\n\n    def is_valid_defaultdict_partial_value_type(self, t: ProperType) -> bool:\n        \"\"\"Check if t can be used as the basis for a partial defaultdict value type.\n\n        Examples:\n\n          * t is 'int' --> True\n          * t is 'list[Never]' --> True\n          * t is 'dict[...]' --> False (only generic types with a single type\n            argument supported)\n        \"\"\"\n        if not isinstance(t, Instance):\n            return False\n        if len(t.args) == 0:\n            return True\n        if len(t.args) == 1:\n            arg = get_proper_type(t.args[0])\n            if self.options.old_type_inference:\n                # Allow leaked TypeVars for legacy inference logic.\n                allowed = isinstance(arg, (UninhabitedType, NoneType, TypeVarType))\n            else:\n                allowed = isinstance(arg, (UninhabitedType, NoneType))\n            if allowed:\n                return True\n        return False\n\n    def set_inferred_type(self, var: Var, lvalue: Lvalue, type: Type) -> None:\n        \"\"\"Store inferred variable type.\n\n        Store the type to both the variable node and the expression node that\n        refers to the variable (lvalue). If var is None, do nothing.\n        \"\"\"\n        if var and not self.current_node_deferred:\n            var.type = type\n            var.is_inferred = True\n            var.is_ready = True\n            if var not in self.var_decl_frames:\n                # Used for the hack to improve optional type inference in conditionals\n                self.var_decl_frames[var] = {frame.id for frame in self.binder.frames}\n            if isinstance(lvalue, MemberExpr) and self.inferred_attribute_types is not None:\n                # Store inferred attribute type so that we can check consistency afterwards.\n                if lvalue.def_var is not None:\n                    self.inferred_attribute_types[lvalue.def_var] = type\n            self.store_type(lvalue, type)\n            p_type = get_proper_type(type)\n            definition = None\n            if isinstance(p_type, CallableType):\n                definition = p_type.definition\n            elif isinstance(p_type, Overloaded):\n                # Randomly select first item, if items are different, there will\n                # be an error during semantic analysis.\n                definition = p_type.items[0].definition\n            if definition:\n                if is_node_static(definition):\n                    var.is_staticmethod = True\n                elif is_classmethod_node(definition):\n                    var.is_classmethod = True\n                elif is_property(definition):\n                    var.is_property = True\n                    if isinstance(p_type, Overloaded):\n                        # TODO: in theory we can have a property with a deleter only.\n                        var.is_settable_property = True\n                        assert isinstance(definition, Decorator), definition\n                        var.setter_type = definition.var.setter_type\n\n    def set_inference_error_fallback_type(self, var: Var, lvalue: Lvalue, type: Type) -> None:\n        \"\"\"Store best known type for variable if type inference failed.\n\n        If a program ignores error on type inference error, the variable should get some\n        inferred type so that it can be used later on in the program. Example:\n\n          x = []  # type: ignore\n          x.append(1)   # Should be ok!\n\n        We implement this here by giving x a valid type (replacing inferred Never with Any).\n        \"\"\"\n        fallback = self.inference_error_fallback_type(type)\n        self.set_inferred_type(var, lvalue, fallback)\n\n    def inference_error_fallback_type(self, type: Type) -> Type:\n        fallback = type.accept(SetNothingToAny())\n        # Type variables may leak from inference, see https://github.com/python/mypy/issues/5738,\n        # we therefore need to erase them.\n        return erase_typevars(fallback)\n\n    def simple_rvalue(self, rvalue: Expression) -> bool:\n        \"\"\"Returns True for expressions for which inferred type should not depend on context.\n\n        Note that this function can still return False for some expressions where inferred type\n        does not depend on context. It only exists for performance optimizations.\n        \"\"\"\n        if isinstance(rvalue, (IntExpr, StrExpr, BytesExpr, FloatExpr, RefExpr)):\n            return True\n        if isinstance(rvalue, CallExpr):\n            if isinstance(rvalue.callee, RefExpr) and isinstance(\n                rvalue.callee.node, SYMBOL_FUNCBASE_TYPES\n            ):\n                typ = rvalue.callee.node.type\n                if isinstance(typ, CallableType):\n                    return not typ.variables\n                elif isinstance(typ, Overloaded):\n                    return not any(item.variables for item in typ.items)\n        return False\n\n    def infer_rvalue_with_fallback_context(\n        self,\n        lvalue_type: Type | None,\n        rvalue: Expression,\n        preferred_context: Type | None,\n        fallback_context: Type | None,\n        inferred: Var | None,\n        always_allow_any: bool,\n    ) -> Type:\n        \"\"\"Infer rvalue type in two type context and select the best one.\n\n        See comments below for supported fallback scenarios.\n        \"\"\"\n        assert fallback_context is not preferred_context\n        # TODO: make assignment checking correct in presence of walrus in r.h.s.\n        # We may accept r.h.s. twice. In presence of walrus this can lead to weird\n        # false negatives and \"back action\". A proper solution would be to use\n        # binder.accumulate_type_assignments() and assign the types inferred for type\n        # context that is ultimately used. This is however tricky with redefinitions.\n        # For now we simply disable second accept in cases known to cause problems,\n        # see e.g. testAssignToOptionalTupleWalrus.\n        binder_version = self.binder.version\n\n        fallback_context_used = False\n        with (\n            self.msg.filter_errors(save_filtered_errors=True) as local_errors,\n            self.local_type_map as type_map,\n        ):\n            rvalue_type = self.expr_checker.accept(\n                rvalue, type_context=preferred_context, always_allow_any=always_allow_any\n            )\n\n        # There are two cases where we want to try re-inferring r.h.s. in a fallback\n        # type context. First case is when redefinitions are allowed, and we got\n        # invalid type when using the preferred (empty) type context.\n        redefinition_fallback = (\n            inferred is not None\n            and not inferred.is_argument\n            and not is_valid_inferred_type(rvalue_type, self.options)\n        )\n        # For function arguments the preference order is opposite, and we use errors\n        # during type-checking as the fallback trigger.\n        argument_redefinition_fallback = (\n            inferred is not None and inferred.is_argument and local_errors.has_new_errors()\n        )\n        # Try re-inferring r.h.s. in empty context for union with explicit annotation,\n        # and use it results in a narrower type. This helps with various practical\n        # examples, see e.g. testOptionalTypeNarrowedByGenericCall.\n        union_fallback = (\n            preferred_context is not None\n            and isinstance(get_proper_type(lvalue_type), UnionType)\n            and binder_version == self.binder.version\n        )\n\n        # Skip literal types, as they have special logic (for better errors).\n        try_fallback = redefinition_fallback or union_fallback or argument_redefinition_fallback\n        if try_fallback and not is_literal_type_like(rvalue_type):\n            with (\n                self.msg.filter_errors(save_filtered_errors=True) as alt_local_errors,\n                self.local_type_map as alt_type_map,\n            ):\n                alt_rvalue_type = self.expr_checker.accept(\n                    rvalue, fallback_context, always_allow_any=always_allow_any\n                )\n            if (\n                not alt_local_errors.has_new_errors()\n                and is_valid_inferred_type(alt_rvalue_type, self.options)\n                and (\n                    # For redefinition fallbacks we are fine getting not a subtype.\n                    redefinition_fallback\n                    or argument_redefinition_fallback\n                    # Skip Any type, since it is special cased in binder.\n                    or not isinstance(get_proper_type(alt_rvalue_type), AnyType)\n                    and is_proper_subtype(alt_rvalue_type, rvalue_type)\n                )\n            ):\n                fallback_context_used = True\n                rvalue_type = alt_rvalue_type\n                self.store_types(alt_type_map)\n\n        if not fallback_context_used:\n            self.msg.add_errors(local_errors.filtered_errors())\n            self.store_types(type_map)\n        return rvalue_type\n\n    def check_simple_assignment(\n        self,\n        lvalue_type: Type | None,\n        rvalue: Expression,\n        context: Context,\n        msg: ErrorMessage = message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT,\n        lvalue_name: str = \"variable\",\n        rvalue_name: str = \"expression\",\n        *,\n        notes: list[str] | None = None,\n        lvalue: Expression | None = None,\n        inferred: Var | None = None,\n    ) -> tuple[Type, Type | None]:\n        if self.is_stub and isinstance(rvalue, EllipsisExpr):\n            # '...' is always a valid initializer in a stub.\n            return AnyType(TypeOfAny.special_form), lvalue_type\n        else:\n            always_allow_any = lvalue_type is not None and not isinstance(\n                get_proper_type(lvalue_type), AnyType\n            )\n\n            # If redefinitions are allowed (i.e. we have --allow-redefinition-new\n            # and a variable without annotation) or if a variable has union type we\n            # try inferring r.h.s. twice with a fallback type context. The only exception\n            # is TypedDicts, they are often useless without context.\n            try_fallback = (\n                inferred is not None or isinstance(get_proper_type(lvalue_type), UnionType)\n            ) and not self.simple_rvalue(rvalue)\n\n            if not try_fallback or lvalue_type is None or is_typeddict_type_context(lvalue_type):\n                rvalue_type = self.expr_checker.accept(\n                    rvalue, type_context=lvalue_type, always_allow_any=always_allow_any\n                )\n            else:\n                # Prefer full type context for function arguments as this reduces\n                # false positives, see issue #19918 for discussion.\n                if inferred is not None and not inferred.is_argument:\n                    preferred = None\n                    fallback = lvalue_type\n                else:\n                    preferred = lvalue_type\n                    fallback = None\n\n                rvalue_type = self.infer_rvalue_with_fallback_context(\n                    lvalue_type, rvalue, preferred, fallback, inferred, always_allow_any\n                )\n\n            if (\n                inferred is not None\n                and not is_valid_inferred_type(rvalue_type, self.options)\n                and (\n                    not inferred.type\n                    or isinstance(inferred.type, PartialType)\n                    # This additional check is to give an error instead of inferring\n                    # a useless type like None | list[Never] in case of \"double-partial\"\n                    # types that are not supported yet, see issue #20257.\n                    or not is_subtype(rvalue_type, inferred.type)\n                )\n            ):\n                self.msg.need_annotation_for_var(inferred, inferred, self.options)\n                rvalue_type = rvalue_type.accept(SetNothingToAny())\n\n            if (\n                isinstance(lvalue, NameExpr)\n                and inferred is not None\n                and inferred.type is not None\n                and not inferred.is_final\n            ):\n                new_inferred = remove_instance_last_known_values(rvalue_type)\n                # Should we widen the inferred type or the lvalue? Variables defined\n                # at module level or class bodies can't be widened in functions, or\n                # in another module.\n                if (\n                    not self.refers_to_different_scope(lvalue)\n                    and not isinstance(inferred.type, PartialType)\n                    and not is_proper_subtype(new_inferred, inferred.type)\n                ):\n                    lvalue_type = make_simplified_union([inferred.type, new_inferred])\n                    # Widen the type to the union of original and new type.\n                    if not inferred.is_index_var:\n                        # Skip index variables as they are reset on each loop.\n                        self.widened_vars.append(inferred.name)\n                    self.set_inferred_type(inferred, lvalue, lvalue_type)\n                    self.binder.put(lvalue, rvalue_type)\n                    # TODO: A bit hacky, maybe add a binder method that does put and\n                    #       updates declaration?\n                    lit = literal_hash(lvalue)\n                    if lit is not None:\n                        self.binder.declarations[lit] = lvalue_type\n\n            if isinstance(rvalue_type, DeletedType):\n                self.msg.deleted_as_rvalue(rvalue_type, context)\n            if isinstance(lvalue_type, DeletedType):\n                self.msg.deleted_as_lvalue(lvalue_type, context)\n            elif lvalue_type:\n                self.check_subtype(\n                    # Preserve original aliases for error messages when possible.\n                    rvalue_type,\n                    lvalue_type,\n                    context,\n                    msg,\n                    f\"{rvalue_name} has type\",\n                    f\"{lvalue_name} has type\",\n                    notes=notes,\n                )\n            return rvalue_type, lvalue_type\n\n    def refers_to_different_scope(self, name: NameExpr) -> bool:\n        if name.kind == LDEF:\n            # TODO: Consider reference to outer function as a different scope?\n            return False\n        elif self.scope.top_level_function() is not None:\n            # A non-local reference from within a function must refer to a different scope\n            return True\n        elif name.kind == GDEF and name.fullname.rpartition(\".\")[0] != self.tree.fullname:\n            # Reference to global definition from another module\n            return True\n        return False\n\n    def check_member_assignment(\n        self,\n        lvalue: MemberExpr,\n        instance_type: Type,\n        set_lvalue_type: Type,\n        rvalue: Expression,\n        context: Context,\n    ) -> tuple[Type, Type, bool]:\n        \"\"\"Type member assignment.\n\n        This defers to check_simple_assignment, unless the member expression\n        is a descriptor, in which case this checks descriptor semantics as well.\n\n        Return the inferred rvalue_type, inferred lvalue_type, and whether to use the binder\n        for this assignment.\n        \"\"\"\n        instance_type = get_proper_type(instance_type)\n        # Descriptors don't participate in class-attribute access\n        if (isinstance(instance_type, FunctionLike) and instance_type.is_type_obj()) or isinstance(\n            instance_type, TypeType\n        ):\n            rvalue_type, _ = self.check_simple_assignment(set_lvalue_type, rvalue, context)\n            return rvalue_type, set_lvalue_type, True\n\n        with self.msg.filter_errors(filter_deprecated=True):\n            get_lvalue_type = self.expr_checker.analyze_ordinary_member_access(\n                lvalue, is_lvalue=False\n            )\n\n        # Special case: if the rvalue_type is a subtype of '__get__' type, and\n        # '__get__' type is narrower than '__set__', then we invoke the binder to narrow type\n        # by this assignment. Technically, this is not safe, but in practice this is\n        # what a user expects.\n        rvalue_type, _ = self.check_simple_assignment(set_lvalue_type, rvalue, context)\n        rvalue_type = rvalue_type if is_subtype(rvalue_type, get_lvalue_type) else get_lvalue_type\n        return rvalue_type, set_lvalue_type, is_subtype(get_lvalue_type, set_lvalue_type)\n\n    def check_indexed_assignment(\n        self, lvalue: IndexExpr, rvalue: Expression, context: Context\n    ) -> None:\n        \"\"\"Type check indexed assignment base[index] = rvalue.\n\n        The lvalue argument is the base[index] expression.\n        \"\"\"\n        self.try_infer_partial_type_from_indexed_assignment(lvalue, rvalue)\n        basetype = get_proper_type(self.expr_checker.accept(lvalue.base))\n        method_type = self.expr_checker.analyze_external_member_access(\n            \"__setitem__\", basetype, lvalue\n        )\n\n        lvalue.method_type = method_type\n        res_type, _ = self.expr_checker.check_method_call(\n            \"__setitem__\",\n            basetype,\n            method_type,\n            [lvalue.index, rvalue],\n            [nodes.ARG_POS, nodes.ARG_POS],\n            context,\n        )\n        res_type = get_proper_type(res_type)\n        if isinstance(res_type, UninhabitedType) and not res_type.ambiguous:\n            self.binder.unreachable()\n\n    def replace_partial_type(\n        self, var: Var, new_type: Type, partial_types: dict[Var, Context]\n    ) -> None:\n        \"\"\"Replace the partial type of var with a non-partial type.\"\"\"\n        var.type = new_type\n        # Updating a partial type should invalidate expression caches.\n        self.binder.version += 1\n        del partial_types[var]\n        if self.options.allow_redefinition_new:\n            # When using --allow-redefinition-new, binder tracks all types of\n            # simple variables.\n            n = NameExpr(var.name)\n            n.node = var\n            self.binder.assign_type(n, new_type, new_type)\n\n    def try_infer_partial_type_from_indexed_assignment(\n        self, lvalue: IndexExpr, rvalue: Expression\n    ) -> None:\n        # TODO: Should we share some of this with try_infer_partial_type?\n        var = None\n        if isinstance(lvalue.base, RefExpr) and isinstance(lvalue.base.node, Var):\n            var = lvalue.base.node\n        elif isinstance(lvalue.base, MemberExpr):\n            var = self.expr_checker.get_partial_self_var(lvalue.base)\n        if isinstance(var, Var):\n            if isinstance(var.type, PartialType):\n                type_type = var.type.type\n                if type_type is None:\n                    return  # The partial type is None.\n                partial_types = self.find_partial_types(var)\n                if partial_types is None:\n                    return\n                typename = type_type.fullname\n                if (\n                    typename == \"builtins.dict\"\n                    or typename == \"collections.OrderedDict\"\n                    or typename == \"collections.defaultdict\"\n                ):\n                    # TODO: Don't infer things twice.\n                    key_type = self.expr_checker.accept(lvalue.index)\n                    value_type = self.expr_checker.accept(rvalue)\n                    if (\n                        is_valid_inferred_type(key_type, self.options)\n                        and is_valid_inferred_type(value_type, self.options)\n                        and not self.current_node_deferred\n                        and not (\n                            typename == \"collections.defaultdict\"\n                            and var.type.value_type is not None\n                            and not is_equivalent(value_type, var.type.value_type)\n                        )\n                    ):\n                        new_type = self.named_generic_type(typename, [key_type, value_type])\n                        self.replace_partial_type(var, new_type, partial_types)\n\n    def type_requires_usage(self, typ: Type) -> tuple[str, ErrorCode] | None:\n        \"\"\"Some types require usage in all cases. The classic example is\n        an unused coroutine.\n\n        In the case that it does require usage, returns a note to attach\n        to the error message.\n        \"\"\"\n        proper_type = get_proper_type(typ)\n        if isinstance(proper_type, Instance):\n            # We use different error codes for generic awaitable vs coroutine.\n            # Coroutines are on by default, whereas generic awaitables are not.\n            if proper_type.type.fullname == \"typing.Coroutine\":\n                return (\"Are you missing an await?\", UNUSED_COROUTINE)\n            if proper_type.type.get(\"__await__\") is not None:\n                return (\"Are you missing an await?\", UNUSED_AWAITABLE)\n        return None\n\n    def visit_expression_stmt(self, s: ExpressionStmt) -> None:\n        expr_type = self.expr_checker.accept(s.expr, allow_none_return=True, always_allow_any=True)\n        error_note_and_code = self.type_requires_usage(expr_type)\n        if error_note_and_code:\n            error_note, code = error_note_and_code\n            self.fail(\n                message_registry.TYPE_MUST_BE_USED.format(format_type(expr_type, self.options)),\n                s,\n                code=code,\n            )\n            self.note(error_note, s, code=code)\n\n    def visit_return_stmt(self, s: ReturnStmt) -> None:\n        \"\"\"Type check a return statement.\"\"\"\n        self.check_return_stmt(s)\n        self.binder.unreachable()\n\n    def infer_context_dependent(\n        self, expr: Expression, type_ctx: Type, allow_none_func_call: bool\n    ) -> ProperType:\n        \"\"\"Infer type of expression with fallback to empty type context.\"\"\"\n        with self.msg.filter_errors(filter_deprecated=True, save_filtered_errors=True) as msg:\n            with (\n                self.local_type_map as type_map,\n                # Prevent any narrowing (e.g. from walrus) to have effect during second accept.\n                self.binder.frame_context(can_skip=False, discard=True),\n            ):\n                typ = get_proper_type(\n                    self.expr_checker.accept(\n                        expr, type_ctx, allow_none_return=allow_none_func_call\n                    )\n                )\n        if not msg.has_new_errors():\n            self.store_types(type_map)\n            return typ\n\n        # If there are errors with the original type context, try re-inferring in empty context.\n        original_messages = msg.filtered_errors()\n        original_type_map = type_map\n        with self.msg.filter_errors(filter_deprecated=True, save_filtered_errors=True) as msg:\n            with self.local_type_map as type_map:\n                alt_typ = get_proper_type(\n                    self.expr_checker.accept(expr, None, allow_none_return=allow_none_func_call)\n                )\n        if not msg.has_new_errors() and is_subtype(alt_typ, type_ctx):\n            self.store_types(type_map)\n            return alt_typ\n\n        # If empty fallback didn't work, use results from the original type context.\n        self.msg.add_errors(original_messages)\n        self.store_types(original_type_map)\n        return typ\n\n    def check_return_stmt(self, s: ReturnStmt) -> None:\n        defn = self.scope.current_function()\n        if defn is not None:\n            if defn.is_generator:\n                return_type = self.get_generator_return_type(\n                    self.return_types[-1], defn.is_coroutine\n                )\n            elif defn.is_coroutine:\n                return_type = self.get_coroutine_return_type(self.return_types[-1])\n            else:\n                return_type = self.return_types[-1]\n            return_type = get_proper_type(return_type)\n\n            is_lambda = isinstance(defn, LambdaExpr)\n            if isinstance(return_type, UninhabitedType):\n                # Avoid extra error messages for failed inference in lambdas\n                if not is_lambda and not return_type.ambiguous:\n                    self.fail(message_registry.NO_RETURN_EXPECTED, s)\n                    return\n\n            if s.expr:\n                declared_none_return = isinstance(return_type, NoneType)\n                declared_any_return = isinstance(return_type, AnyType)\n\n                # This controls whether or not we allow a function call that\n                # returns None as the expression of this return statement.\n                # E.g. `return f()` for some `f` that returns None.  We allow\n                # this only if we're in a lambda or in a function that returns\n                # `None` or `Any`.\n                allow_none_func_call = is_lambda or declared_none_return or declared_any_return\n\n                # Return with a value.\n                if (\n                    isinstance(s.expr, (CallExpr, ListExpr, TupleExpr, DictExpr, SetExpr, OpExpr))\n                    or isinstance(s.expr, AwaitExpr)\n                    and isinstance(s.expr.expr, CallExpr)\n                ):\n                    # For expressions that (strongly) depend on type context (i.e. those that\n                    # are handled like a function call), we allow fallback to empty type context\n                    # in case of errors, this improves user experience in some cases,\n                    # see e.g. testReturnFallbackInference.\n                    typ = self.infer_context_dependent(s.expr, return_type, allow_none_func_call)\n                else:\n                    typ = get_proper_type(\n                        self.expr_checker.accept(\n                            s.expr, return_type, allow_none_return=allow_none_func_call\n                        )\n                    )\n                # Treat NotImplemented as having type Any, consistent with its\n                # definition in typeshed prior to python/typeshed#4222.\n                if isinstance(typ, Instance) and typ.type.fullname in NOT_IMPLEMENTED_TYPE_NAMES:\n                    typ = AnyType(TypeOfAny.special_form)\n\n                if defn.is_async_generator:\n                    self.fail(message_registry.RETURN_IN_ASYNC_GENERATOR, s)\n                    return\n                # Returning a value of type Any is always fine.\n                if isinstance(typ, AnyType):\n                    # (Unless you asked to be warned in that case, and the\n                    # function is not declared to return Any)\n                    if (\n                        self.options.warn_return_any\n                        and not self.current_node_deferred\n                        and not is_proper_subtype(AnyType(TypeOfAny.special_form), return_type)\n                        and not (\n                            defn.name in BINARY_MAGIC_METHODS\n                            and is_literal_not_implemented(s.expr)\n                        )\n                        and not (\n                            isinstance(return_type, Instance)\n                            and return_type.type.fullname == \"builtins.object\"\n                        )\n                        and not is_lambda\n                    ):\n                        self.msg.incorrectly_returning_any(return_type, s)\n                    return\n\n                # Disallow return expressions in functions declared to return\n                # None, subject to two exceptions below.\n                if declared_none_return:\n                    # Lambdas are allowed to have None returns.\n                    # Functions returning a value of type None are allowed to have a None return.\n                    if is_lambda or isinstance(typ, NoneType):\n                        return\n                    self.fail(message_registry.NO_RETURN_VALUE_EXPECTED, s)\n                else:\n                    self.check_subtype(\n                        subtype_label=\"got\",\n                        subtype=typ,\n                        supertype_label=\"expected\",\n                        supertype=return_type,\n                        context=s.expr,\n                        outer_context=s,\n                        msg=message_registry.INCOMPATIBLE_RETURN_VALUE_TYPE,\n                    )\n            else:\n                # Empty returns are valid in Generators with Any typed returns, but not in\n                # coroutines.\n                if (\n                    defn.is_generator\n                    and not defn.is_coroutine\n                    and isinstance(return_type, AnyType)\n                ):\n                    return\n\n                if isinstance(return_type, (NoneType, AnyType)):\n                    return\n\n                if self.in_checked_function():\n                    self.fail(message_registry.RETURN_VALUE_EXPECTED, s)\n\n    def visit_if_stmt(self, s: IfStmt) -> None:\n        \"\"\"Type check an if statement.\"\"\"\n        # This frame records the knowledge from previous if/elif clauses not being taken.\n        # Fall-through to the original frame is handled explicitly in each block.\n        with self.binder.frame_context(can_skip=False, conditional_frame=True, fall_through=0):\n            for e, b in zip(s.expr, s.body):\n                t = get_proper_type(self.expr_checker.accept(e))\n\n                if isinstance(t, DeletedType):\n                    self.msg.deleted_as_rvalue(t, s)\n\n                if_map, else_map = self.find_isinstance_check(e)\n\n                s.unreachable_else = is_unreachable_map(else_map)\n\n                # XXX Issue a warning if condition is always False?\n                with self.binder.frame_context(can_skip=True, fall_through=2):\n                    self.push_type_map(if_map, from_assignment=False)\n                    self.accept(b)\n\n                # XXX Issue a warning if condition is always True?\n                self.push_type_map(else_map, from_assignment=False)\n\n            with self.binder.frame_context(can_skip=False, fall_through=2):\n                if s.else_body:\n                    self.accept(s.else_body)\n\n    def visit_while_stmt(self, s: WhileStmt) -> None:\n        \"\"\"Type check a while statement.\"\"\"\n        if_stmt = IfStmt([s.expr], [s.body], None)\n        if_stmt.set_line(s)\n        self.accept_loop(if_stmt, s.else_body, exit_condition=s.expr)\n\n    def visit_operator_assignment_stmt(self, s: OperatorAssignmentStmt) -> None:\n        \"\"\"Type check an operator assignment statement, e.g. x += 1.\"\"\"\n        self.try_infer_partial_generic_type_from_assignment(s.lvalue, s.rvalue, s.op)\n        if isinstance(s.lvalue, MemberExpr):\n            # Special case, some additional errors may be given for\n            # assignments to read-only or final attributes.\n            lvalue_type = self.expr_checker.visit_member_expr(s.lvalue, True)\n        else:\n            lvalue_type = self.expr_checker.accept(s.lvalue)\n        inplace, method = infer_operator_assignment_method(lvalue_type, s.op)\n        if inplace:\n            # There is __ifoo__, treat as x = x.__ifoo__(y)\n            rvalue_type, _ = self.expr_checker.check_op(method, lvalue_type, s.rvalue, s)\n            if not is_subtype(rvalue_type, lvalue_type):\n                self.msg.incompatible_operator_assignment(s.op, s)\n        else:\n            # There is no __ifoo__, treat as x = x <foo> y\n            expr = OpExpr(s.op, s.lvalue, s.rvalue)\n            expr.set_line(s)\n            self.check_assignment(\n                lvalue=s.lvalue, rvalue=expr, infer_lvalue_type=True, new_syntax=False\n            )\n        self.check_final(s)\n\n    def visit_assert_stmt(self, s: AssertStmt) -> None:\n        self.expr_checker.accept(s.expr)\n\n        if isinstance(s.expr, TupleExpr) and len(s.expr.items) > 0:\n            self.fail(message_registry.MALFORMED_ASSERT, s)\n\n        # If this is asserting some isinstance check, bind that type in the following code\n        true_map, else_map = self.find_isinstance_check(s.expr)\n        if s.msg is not None:\n            self.expr_checker.analyze_cond_branch(\n                else_map, s.msg, None, suppress_unreachable_errors=False\n            )\n        self.push_type_map(true_map)\n\n    def visit_raise_stmt(self, s: RaiseStmt) -> None:\n        \"\"\"Type check a raise statement.\"\"\"\n        if s.expr:\n            self.type_check_raise(s.expr, s)\n        if s.from_expr:\n            self.type_check_raise(s.from_expr, s, optional=True)\n        self.binder.unreachable()\n\n    def type_check_raise(self, e: Expression, s: RaiseStmt, optional: bool = False) -> None:\n        typ = get_proper_type(self.expr_checker.accept(e))\n        if isinstance(typ, DeletedType):\n            self.msg.deleted_as_rvalue(typ, e)\n            return\n\n        exc_type = self.named_type(\"builtins.BaseException\")\n        expected_type_items = [exc_type, TypeType(exc_type)]\n        if optional:\n            # This is used for `x` part in a case like `raise e from x`,\n            # where we allow `raise e from None`.\n            expected_type_items.append(NoneType())\n\n        self.check_subtype(\n            typ, UnionType.make_union(expected_type_items), s, message_registry.INVALID_EXCEPTION\n        )\n\n        if isinstance(typ, FunctionLike):\n            # https://github.com/python/mypy/issues/11089\n            self.expr_checker.check_call(typ, [], [], e)\n\n        if (isinstance(typ, Instance) and typ.type.fullname in NOT_IMPLEMENTED_TYPE_NAMES) or (\n            isinstance(e, CallExpr)\n            and isinstance(e.callee, RefExpr)\n            and e.callee.fullname == \"builtins.NotImplemented\"\n        ):\n            self.fail(\n                message_registry.INVALID_EXCEPTION.with_additional_msg(\n                    '; did you mean \"NotImplementedError\"?'\n                ),\n                s,\n            )\n\n    def visit_try_stmt(self, s: TryStmt) -> None:\n        \"\"\"Type check a try statement.\"\"\"\n\n        iter_errors = None\n\n        # Our enclosing frame will get the result if the try/except falls through.\n        # This one gets all possible states after the try block exited abnormally\n        # (by exception, return, break, etc.)\n        with self.binder.frame_context(can_skip=False, fall_through=0):\n            # Not only might the body of the try statement exit\n            # abnormally, but so might an exception handler or else\n            # clause. The finally clause runs in *all* cases, so we\n            # need an outer try frame to catch all intermediate states\n            # in case an exception is raised during an except or else\n            # clause. As an optimization, only create the outer try\n            # frame when there actually is a finally clause.\n            self.visit_try_without_finally(s, try_frame=bool(s.finally_body))\n            if s.finally_body:\n                # First we check finally_body is type safe on all abnormal exit paths\n                iter_errors = IterationDependentErrors()\n                with IterationErrorWatcher(self.msg.errors, iter_errors):\n                    self.accept(s.finally_body)\n\n        if s.finally_body:\n            # Then we try again for the more restricted set of options\n            # that can fall through. (Why do we need to check the\n            # finally clause twice? Depending on whether the finally\n            # clause was reached by the try clause falling off the end\n            # or exiting abnormally, after completing the finally clause\n            # either flow will continue to after the entire try statement\n            # or the exception/return/etc. will be processed and control\n            # flow will escape. We need to check that the finally clause\n            # type checks in both contexts, but only the resulting types\n            # from the latter context affect the type state in the code\n            # that follows the try statement.)\n            assert iter_errors is not None\n            if not self.binder.is_unreachable():\n                with IterationErrorWatcher(self.msg.errors, iter_errors):\n                    self.accept(s.finally_body)\n            self.msg.iteration_dependent_errors(iter_errors)\n\n    def visit_try_without_finally(self, s: TryStmt, try_frame: bool) -> None:\n        \"\"\"Type check a try statement, ignoring the finally block.\n\n        On entry, the top frame should receive all flow that exits the\n        try block abnormally (i.e., such that the else block does not\n        execute), and its parent should receive all flow that exits\n        the try block normally.\n        \"\"\"\n        # This frame will run the else block if the try fell through.\n        # In that case, control flow continues to the parent of what\n        # was the top frame on entry.\n        with self.binder.frame_context(can_skip=False, fall_through=2, try_frame=try_frame):\n            # This frame receives exit via exception, and runs exception handlers\n            with self.binder.frame_context(can_skip=False, conditional_frame=True, fall_through=2):\n                # Finally, the body of the try statement\n                with self.binder.frame_context(can_skip=False, fall_through=2, try_frame=True):\n                    self.accept(s.body)\n                for i in range(len(s.handlers)):\n                    with self.binder.frame_context(can_skip=True, fall_through=4):\n                        typ = s.types[i]\n                        if typ:\n                            t = self.check_except_handler_test(typ, s.is_star)\n                            var = s.vars[i]\n                            if var:\n                                # To support local variables, we make this a definition line,\n                                # causing assignment to set the variable's type.\n                                var.is_inferred_def = True\n                                self.check_assignment(var, self.temp_node(t, var))\n                        self.accept(s.handlers[i])\n                        var = s.vars[i]\n                        if var:\n                            # Exception variables are deleted.\n                            # Unfortunately, this doesn't let us detect usage before the\n                            # try/except block.\n                            source = var.name\n                            if isinstance(var.node, Var):\n                                new_type = DeletedType(source=source)\n                                var.node.type = new_type\n                                if self.options.allow_redefinition_new:\n                                    # TODO: Should we use put() here?\n                                    self.binder.assign_type(var, new_type, new_type)\n                            if not self.options.allow_redefinition_new:\n                                self.binder.cleanse(var)\n            if s.else_body:\n                self.accept(s.else_body)\n\n    def check_except_handler_test(self, n: Expression, is_star: bool) -> Type:\n        \"\"\"Type check an exception handler test clause.\"\"\"\n        typ = self.expr_checker.accept(n)\n\n        all_types: list[Type] = []\n        test_types = self.get_types_from_except_handler(typ, n)\n\n        for ttype in get_proper_types(test_types):\n            if isinstance(ttype, AnyType):\n                all_types.append(ttype)\n                continue\n\n            if isinstance(ttype, FunctionLike):\n                item = ttype.items[0]\n                if not item.is_type_obj():\n                    self.fail(message_registry.INVALID_EXCEPTION_TYPE, n)\n                    return self.default_exception_type(is_star)\n                exc_type = erase_typevars(item.ret_type)\n            elif isinstance(ttype, TypeType):\n                exc_type = ttype.item\n            else:\n                self.fail(message_registry.INVALID_EXCEPTION_TYPE, n)\n                return self.default_exception_type(is_star)\n\n            if not is_subtype(exc_type, self.named_type(\"builtins.BaseException\")):\n                self.fail(message_registry.INVALID_EXCEPTION_TYPE, n)\n                return self.default_exception_type(is_star)\n\n            all_types.append(exc_type)\n\n        if is_star:\n            new_all_types: list[Type] = []\n            for typ in all_types:\n                if is_proper_subtype(typ, self.named_type(\"builtins.BaseExceptionGroup\")):\n                    self.fail(message_registry.INVALID_EXCEPTION_GROUP, n)\n                    new_all_types.append(AnyType(TypeOfAny.from_error))\n                else:\n                    new_all_types.append(typ)\n            return self.wrap_exception_group(new_all_types)\n        return make_simplified_union(all_types)\n\n    def default_exception_type(self, is_star: bool) -> Type:\n        \"\"\"Exception type to return in case of a previous type error.\"\"\"\n        any_type = AnyType(TypeOfAny.from_error)\n        if is_star:\n            return self.named_generic_type(\"builtins.ExceptionGroup\", [any_type])\n        return any_type\n\n    def wrap_exception_group(self, types: Sequence[Type]) -> Type:\n        \"\"\"Transform except* variable type into an appropriate exception group.\"\"\"\n        arg = make_simplified_union(types)\n        if is_subtype(arg, self.named_type(\"builtins.Exception\")):\n            base = \"builtins.ExceptionGroup\"\n        else:\n            base = \"builtins.BaseExceptionGroup\"\n        return self.named_generic_type(base, [arg])\n\n    def get_types_from_except_handler(self, typ: Type, n: Expression) -> list[Type]:\n        \"\"\"Helper for check_except_handler_test to retrieve handler types.\"\"\"\n        typ = get_proper_type(typ)\n        if isinstance(typ, TupleType):\n            merged_type = make_simplified_union(typ.items)\n            if isinstance(merged_type, UnionType):\n                return merged_type.relevant_items()\n            return [merged_type]\n        elif is_named_instance(typ, \"builtins.tuple\"):\n            # variadic tuple\n            merged_type = make_simplified_union((typ.args[0],))\n            if isinstance(merged_type, UnionType):\n                return merged_type.relevant_items()\n            return [merged_type]\n        elif isinstance(typ, UnionType):\n            return [\n                union_typ\n                for item in typ.relevant_items()\n                for union_typ in self.get_types_from_except_handler(item, n)\n            ]\n        else:\n            return [typ]\n\n    def visit_for_stmt(self, s: ForStmt) -> None:\n        \"\"\"Type check a for statement.\"\"\"\n        if s.is_async:\n            iterator_type, item_type = self.analyze_async_iterable_item_type(s.expr)\n        else:\n            iterator_type, item_type = self.analyze_iterable_item_type(s.expr)\n        s.inferred_item_type = item_type\n        s.inferred_iterator_type = iterator_type\n\n        self.accept_loop(\n            s.body,\n            s.else_body,\n            on_enter_body=lambda: self.analyze_index_variables(\n                s.index, item_type, s.index_type is None, s\n            ),\n        )\n\n    def analyze_async_iterable_item_type(self, expr: Expression) -> tuple[Type, Type]:\n        \"\"\"Analyse async iterable expression and return iterator and iterator item types.\"\"\"\n        echk = self.expr_checker\n        iterable = echk.accept(expr)\n        iterator = echk.check_method_call_by_name(\"__aiter__\", iterable, [], [], expr)[0]\n        awaitable = echk.check_method_call_by_name(\"__anext__\", iterator, [], [], expr)[0]\n        item_type = echk.check_awaitable_expr(\n            awaitable, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_FOR\n        )\n        return iterator, item_type\n\n    def analyze_iterable_item_type(self, expr: Expression) -> tuple[Type, Type]:\n        \"\"\"Analyse iterable expression and return iterator and iterator item types.\"\"\"\n        iterator, iterable = self.analyze_iterable_item_type_without_expression(\n            self.expr_checker.accept(expr), context=expr\n        )\n        int_type = self.analyze_range_native_int_type(expr)\n        if int_type:\n            return iterator, int_type\n        return iterator, iterable\n\n    def analyze_iterable_item_type_without_expression(\n        self, type: Type, context: Context\n    ) -> tuple[Type, Type]:\n        \"\"\"Analyse iterable type and return iterator and iterator item types.\"\"\"\n        echk = self.expr_checker\n        iterable: Type\n        iterable = get_proper_type(type)\n        iterator = echk.check_method_call_by_name(\"__iter__\", iterable, [], [], context)[0]\n\n        if (\n            isinstance(iterable, TupleType)\n            and iterable.partial_fallback.type.fullname == \"builtins.tuple\"\n        ):\n            return iterator, tuple_fallback(iterable).args[0]\n        else:\n            # Non-tuple iterable.\n            iterable = echk.check_method_call_by_name(\"__next__\", iterator, [], [], context)[0]\n            return iterator, iterable\n\n    def analyze_range_native_int_type(self, expr: Expression) -> Type | None:\n        \"\"\"Try to infer native int item type from arguments to range(...).\n\n        For example, return i64 if the expression is \"range(0, i64(n))\".\n\n        Return None if unsuccessful.\n        \"\"\"\n        if (\n            isinstance(expr, CallExpr)\n            and isinstance(expr.callee, RefExpr)\n            and expr.callee.fullname == \"builtins.range\"\n            and 1 <= len(expr.args) <= 3\n            and all(kind == ARG_POS for kind in expr.arg_kinds)\n        ):\n            native_int: Type | None = None\n            ok = True\n            for arg in expr.args:\n                argt = get_proper_type(self.lookup_type(arg))\n                if isinstance(argt, Instance) and argt.type.fullname in MYPYC_NATIVE_INT_NAMES:\n                    if native_int is None:\n                        native_int = argt\n                    elif argt != native_int:\n                        ok = False\n            if ok and native_int:\n                return native_int\n        return None\n\n    def analyze_container_item_type(self, typ: Type) -> Type | None:\n        \"\"\"Check if a type is a nominal container of a union of such.\n\n        Return the corresponding container item type.\n        \"\"\"\n        typ = get_proper_type(typ)\n        if isinstance(typ, UnionType):\n            types: list[Type] = []\n            for item in typ.items:\n                c_type = self.analyze_container_item_type(item)\n                if c_type:\n                    types.append(c_type)\n            return UnionType.make_union(types)\n        if isinstance(typ, Instance) and typ.type.has_base(\"typing.Container\"):\n            supertype = self.named_type(\"typing.Container\").type\n            super_instance = map_instance_to_supertype(typ, supertype)\n            assert len(super_instance.args) == 1\n            return super_instance.args[0]\n        if isinstance(typ, TupleType):\n            return self.analyze_container_item_type(tuple_fallback(typ))\n        return None\n\n    def analyze_index_variables(\n        self, index: Expression, item_type: Type, infer_lvalue_type: bool, context: Context\n    ) -> None:\n        \"\"\"Type check or infer for loop or list comprehension index vars.\"\"\"\n        self.check_assignment(index, self.temp_node(item_type, context), infer_lvalue_type)\n\n    def visit_del_stmt(self, s: DelStmt) -> None:\n        if isinstance(s.expr, IndexExpr):\n            e = s.expr\n            m = MemberExpr(e.base, \"__delitem__\")\n            m.line = s.line\n            m.column = s.column\n            c = CallExpr(m, [e.index], [nodes.ARG_POS], [None])\n            c.line = s.line\n            c.column = s.column\n            self.expr_checker.accept(c, allow_none_return=True)\n        else:\n            s.expr.accept(self.expr_checker)\n            for elt in flatten(s.expr):\n                if isinstance(elt, NameExpr):\n                    self.binder.assign_type(\n                        elt, DeletedType(source=elt.name), get_declaration(elt)\n                    )\n\n    def visit_decorator(self, e: Decorator) -> None:\n        for d in e.decorators:\n            if isinstance(d, RefExpr):\n                if d.fullname == \"typing.no_type_check\":\n                    e.var.type = AnyType(TypeOfAny.special_form)\n                    e.var.is_ready = True\n                    return\n        self.visit_decorator_inner(e)\n\n    def visit_decorator_inner(\n        self, e: Decorator, allow_empty: bool = False, skip_first_item: bool = False\n    ) -> None:\n        if self.recurse_into_functions or e.func.def_or_infer_vars:\n            with self.tscope.function_scope(e.func), self.set_recurse_into_functions():\n                self.check_func_item(e.func, name=e.func.name, allow_empty=allow_empty)\n\n        # Process decorators from the inside out to determine decorated signature, which\n        # may be different from the declared signature.\n        sig: Type = self.function_type(e.func)\n        non_trivial_decorator = False\n        # For settable properties skip the first decorator (that is @foo.setter).\n        for d in reversed(e.decorators[1:] if skip_first_item else e.decorators):\n            if refers_to_fullname(d, \"abc.abstractmethod\"):\n                # This is a hack to avoid spurious errors because of incomplete type\n                # of @abstractmethod in the test fixtures.\n                continue\n            if refers_to_fullname(d, OVERLOAD_NAMES):\n                if not allow_empty:\n                    self.fail(message_registry.MULTIPLE_OVERLOADS_REQUIRED, e)\n                continue\n            non_trivial_decorator = True\n            dec = self.expr_checker.accept(d)\n            temp = self.temp_node(sig, context=d)\n            fullname = None\n            if isinstance(d, RefExpr):\n                fullname = d.fullname or None\n            # if this is an expression like @b.a where b is an object, get the type of b,\n            # so we can pass it the method hook in the plugins\n            object_type: Type | None = None\n            if fullname is None and isinstance(d, MemberExpr) and self.has_type(d.expr):\n                object_type = self.lookup_type(d.expr)\n                fullname = self.expr_checker.method_fullname(object_type, d.name)\n            self.check_for_untyped_decorator(e.func, dec, d)\n            sig, t2 = self.expr_checker.check_call(\n                dec, [temp], [nodes.ARG_POS], e, callable_name=fullname, object_type=object_type\n            )\n        if non_trivial_decorator:\n            self.check_untyped_after_decorator(sig, e.func)\n        self.require_correct_self_argument(sig, e.func)\n        sig = set_callable_name(sig, e.func)\n        if isinstance(sig, CallableType):\n            sig.definition = e\n        e.var.type = sig\n        e.var.is_ready = True\n        if e.func.is_property:\n            if isinstance(sig, CallableType):\n                if len([k for k in sig.arg_kinds if k.is_required()]) > 1:\n                    self.msg.fail(\"Too many arguments for property\", e)\n            self.check_incompatible_property_override(e)\n        # For overloaded functions/properties we already checked override for overload as a whole.\n        if allow_empty or skip_first_item:\n            return\n        if e.func.info and not e.is_overload:\n            found_method_base_classes = self.check_method_override(e)\n            if (\n                e.func.is_explicit_override\n                and not found_method_base_classes\n                and found_method_base_classes is not None\n                # If the class has Any fallback, we can't be certain that a method\n                # is really missing - it might come from unfollowed import.\n                and not e.func.info.fallback_to_any\n            ):\n                self.msg.no_overridable_method(e.func.name, e.func)\n            self.check_explicit_override_decorator(e.func, found_method_base_classes)\n\n        if e.func.info and e.func.name in (\"__init__\", \"__new__\"):\n            if e.type and not isinstance(get_proper_type(e.type), (FunctionLike, AnyType)):\n                self.fail(message_registry.BAD_CONSTRUCTOR_TYPE, e)\n\n        if e.func.original_def and isinstance(sig, FunctionLike):\n            # Function definition overrides function definition.\n            self.check_func_def_override(e.func, sig)\n\n    def check_for_untyped_decorator(\n        self, func: FuncDef, dec_type: Type, dec_expr: Expression\n    ) -> None:\n        if (\n            self.options.disallow_untyped_decorators\n            and is_typed_callable(func.type)\n            and is_untyped_decorator(dec_type)\n            and not self.current_node_deferred\n        ):\n            self.msg.typed_function_untyped_decorator(func.name, dec_expr)\n\n    def check_incompatible_property_override(self, e: Decorator) -> None:\n        if not e.var.is_settable_property and e.func.info:\n            name = e.func.name\n            for base in e.func.info.mro[1:]:\n                base_attr = base.names.get(name)\n                if not base_attr:\n                    continue\n                if (\n                    isinstance(base_attr.node, OverloadedFuncDef)\n                    and base_attr.node.is_property\n                    and cast(Decorator, base_attr.node.items[0]).var.is_settable_property\n                ):\n                    self.fail(message_registry.READ_ONLY_PROPERTY_OVERRIDES_READ_WRITE, e)\n\n    def visit_with_stmt(self, s: WithStmt) -> None:\n        exceptions_maybe_suppressed = False\n        for expr, target in zip(s.expr, s.target):\n            if s.is_async:\n                exit_ret_type = self.check_async_with_item(expr, target, s.unanalyzed_type is None)\n            else:\n                exit_ret_type = self.check_with_item(expr, target, s.unanalyzed_type is None)\n\n            # Based on the return type, determine if this context manager 'swallows'\n            # exceptions or not. We determine this using a heuristic based on the\n            # return type of the __exit__ method -- see the discussion in\n            # https://github.com/python/mypy/issues/7214 and the section about context managers\n            # in https://github.com/python/typeshed/blob/main/CONTRIBUTING.md#conventions\n            # for more details.\n\n            exit_ret_type = get_proper_type(exit_ret_type)\n            if is_literal_type(exit_ret_type, \"builtins.bool\", False):\n                continue\n\n            if is_literal_type(exit_ret_type, \"builtins.bool\", True) or (\n                isinstance(exit_ret_type, Instance)\n                and exit_ret_type.type.fullname == \"builtins.bool\"\n                and state.strict_optional\n            ):\n                # Note: if strict-optional is disabled, this bool instance\n                # could actually be an Optional[bool].\n                exceptions_maybe_suppressed = True\n\n        if exceptions_maybe_suppressed:\n            # Treat this 'with' block in the same way we'd treat a 'try: BODY; except: pass'\n            # block. This means control flow can continue after the 'with' even if the 'with'\n            # block immediately returns.\n            with self.binder.frame_context(can_skip=True, try_frame=True):\n                self.accept(s.body)\n        else:\n            self.accept(s.body)\n\n    def check_untyped_after_decorator(self, typ: Type, func: FuncDef) -> None:\n        if not self.options.disallow_any_decorated or self.is_stub or self.current_node_deferred:\n            return\n\n        if mypy.checkexpr.has_any_type(typ):\n            self.msg.untyped_decorated_function(typ, func)\n\n    def check_async_with_item(\n        self, expr: Expression, target: Expression | None, infer_lvalue_type: bool\n    ) -> Type:\n        echk = self.expr_checker\n        ctx = echk.accept(expr)\n        obj = echk.check_method_call_by_name(\"__aenter__\", ctx, [], [], expr)[0]\n        obj = echk.check_awaitable_expr(\n            obj, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER\n        )\n        if target:\n            self.check_assignment(target, self.temp_node(obj, expr), infer_lvalue_type)\n        arg = self.temp_node(AnyType(TypeOfAny.special_form), expr)\n        res, _ = echk.check_method_call_by_name(\n            \"__aexit__\", ctx, [arg] * 3, [nodes.ARG_POS] * 3, expr\n        )\n        return echk.check_awaitable_expr(\n            res, expr, message_registry.INCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT\n        )\n\n    def check_with_item(\n        self, expr: Expression, target: Expression | None, infer_lvalue_type: bool\n    ) -> Type:\n        echk = self.expr_checker\n        ctx = echk.accept(expr)\n        obj = echk.check_method_call_by_name(\"__enter__\", ctx, [], [], expr)[0]\n        if target:\n            self.check_assignment(target, self.temp_node(obj, expr), infer_lvalue_type)\n        arg = self.temp_node(AnyType(TypeOfAny.special_form), expr)\n        res, _ = echk.check_method_call_by_name(\n            \"__exit__\", ctx, [arg] * 3, [nodes.ARG_POS] * 3, expr\n        )\n        return res\n\n    def visit_break_stmt(self, s: BreakStmt) -> None:\n        self.binder.handle_break()\n\n    def visit_continue_stmt(self, s: ContinueStmt) -> None:\n        self.binder.handle_continue()\n        return\n\n    def visit_match_stmt(self, s: MatchStmt) -> None:\n        # In sync with similar actions elsewhere, narrow the target if\n        # we are matching an AssignmentExpr\n        unwrapped_subject = collapse_walrus(s.subject)\n        named_subject = self._make_named_statement_for_match(s, unwrapped_subject)\n        with self.binder.frame_context(can_skip=False, fall_through=0):\n            subject_type = get_proper_type(self.expr_checker.accept(s.subject))\n\n            if isinstance(subject_type, DeletedType):\n                self.msg.deleted_as_rvalue(subject_type, s)\n\n            # We infer types of patterns twice. The first pass is used\n            # to infer the types of capture variables. The type of a\n            # capture variable may depend on multiple patterns (it\n            # will be a union of all capture types). This pass ignores\n            # guard expressions.\n            pattern_types = [self.pattern_checker.accept(p, subject_type) for p in s.patterns]\n            type_maps: list[TypeMap] = [t.captures for t in pattern_types]\n            inferred_types = self.infer_variable_types_from_type_maps(type_maps)\n\n            # The second pass narrows down the types and type checks bodies.\n            unmatched_types: TypeMap = {s.subject: UninhabitedType()}\n            for p, g, b in zip(s.patterns, s.guards, s.bodies):\n                current_subject_type = self.expr_checker.narrow_type_from_binder(\n                    named_subject, subject_type\n                )\n                pattern_type = self.pattern_checker.accept(p, current_subject_type)\n                with self.binder.frame_context(can_skip=True, fall_through=2):\n                    pattern_map, else_map = conditional_types_to_typemaps(\n                        named_subject, pattern_type.type, pattern_type.rest_type\n                    )\n                    # Maybe the subject type can be inferred from constraints on\n                    # its attribute/item?\n                    if named_subject in pattern_map:\n                        pattern_map[unwrapped_subject] = pattern_map[named_subject]\n                    if named_subject in else_map:\n                        else_map[unwrapped_subject] = else_map[named_subject]\n                    pattern_map = self.propagate_up_typemap_info(pattern_map)\n                    else_map = self.propagate_up_typemap_info(else_map)\n                    self.remove_capture_conflicts(pattern_type.captures, inferred_types)\n                    self.push_type_map(pattern_map, from_assignment=False)\n                    if pattern_map:\n                        for expr, typ in pattern_map.items():\n                            self.push_type_map(\n                                self._get_recursive_sub_patterns_map(expr, typ),\n                                from_assignment=False,\n                            )\n                    self.push_type_map(pattern_type.captures, from_assignment=False)\n                    if g is not None:\n                        with self.binder.frame_context(can_skip=False, fall_through=3):\n                            gt = get_proper_type(self.expr_checker.accept(g))\n\n                            if isinstance(gt, DeletedType):\n                                self.msg.deleted_as_rvalue(gt, s)\n\n                            guard_map, guard_else_map = self.find_isinstance_check(g)\n                            else_map = or_conditional_maps(else_map, guard_else_map)\n\n                            # If the guard narrowed the subject, copy the narrowed types over\n                            if isinstance(p, AsPattern):\n                                case_target = p.pattern or p.name\n                                if isinstance(case_target, NameExpr):\n                                    for type_map in (guard_map, else_map):\n                                        for expr in list(type_map):\n                                            if not (\n                                                isinstance(expr, NameExpr)\n                                                and expr.fullname == case_target.fullname\n                                            ):\n                                                continue\n                                            type_map[named_subject] = type_map[expr]\n\n                            self.push_type_map(guard_map, from_assignment=False)\n                            self.accept(b)\n                    else:\n                        self.accept(b)\n                self.push_type_map(else_map, from_assignment=False)\n                unmatched_types = else_map\n\n            if not is_unreachable_map(unmatched_types) and not self.current_node_deferred:\n                for typ in unmatched_types.values():\n                    self.msg.match_statement_inexhaustive_match(typ, s)\n\n            # This is needed due to a quirk in frame_context. Without it types will stay narrowed\n            # after the match.\n            with self.binder.frame_context(can_skip=False, fall_through=2):\n                pass\n\n    def _make_named_statement_for_match(self, s: MatchStmt, subject: Expression) -> Expression:\n        \"\"\"Construct a fake NameExpr for inference if a match clause is complex.\"\"\"\n        if self.binder.can_put_directly(subject):\n            # Already named - we should infer type of it as given\n            return subject\n        elif s.subject_dummy is not None:\n            return s.subject_dummy\n        else:\n            # Create a dummy subject expression to handle cases where a match statement's subject\n            # is not a literal value. This lets us correctly narrow types and check exhaustivity\n            # This is hack!\n            name = self.new_unique_dummy_name(\"match\")\n            v = Var(name)\n            named_subject = NameExpr(name)\n            named_subject.node = v\n            s.subject_dummy = named_subject\n            return named_subject\n\n    def _get_recursive_sub_patterns_map(\n        self, expr: Expression, typ: Type\n    ) -> dict[Expression, Type]:\n        sub_patterns_map: dict[Expression, Type] = {}\n        typ_ = get_proper_type(typ)\n        if isinstance(expr, TupleExpr) and isinstance(typ_, TupleType):\n            # When matching a tuple expression with a sequence pattern, narrow individual tuple items\n            assert len(expr.items) == len(typ_.items)\n            for item_expr, item_typ in zip(expr.items, typ_.items):\n                sub_patterns_map[item_expr] = item_typ\n                sub_patterns_map.update(self._get_recursive_sub_patterns_map(item_expr, item_typ))\n\n        return sub_patterns_map\n\n    def infer_variable_types_from_type_maps(\n        self, type_maps: list[TypeMap]\n    ) -> dict[SymbolNode, Type]:\n        # Type maps may contain variables inherited from previous code which are not\n        # necessary `Var`s (e.g. a function defined earlier with the same name).\n        all_captures: dict[SymbolNode, list[tuple[NameExpr, Type]]] = defaultdict(list)\n        for tm in type_maps:\n            if not is_unreachable_map(tm):\n                for expr, typ in tm.items():\n                    if isinstance(expr, NameExpr):\n                        node = expr.node\n                        assert node is not None\n                        all_captures[node].append((expr, typ))\n\n        inferred_types: dict[SymbolNode, Type] = {}\n        for var, captures in all_captures.items():\n            already_exists = False\n            types: list[Type] = []\n            for expr, typ in captures:\n                types.append(typ)\n\n                previous_type, _, _ = self.check_lvalue(expr)\n                if previous_type is not None:\n                    already_exists = True\n                    if isinstance(expr.node, Var) and expr.node.is_final:\n                        self.msg.cant_assign_to_final(expr.name, False, expr)\n                    if self.check_subtype(\n                        typ,\n                        previous_type,\n                        expr,\n                        msg=message_registry.INCOMPATIBLE_TYPES_IN_CAPTURE,\n                        subtype_label=\"pattern captures type\",\n                        supertype_label=\"variable has type\",\n                    ):\n                        inferred_types[var] = previous_type\n\n            if not already_exists:\n                new_type = UnionType.make_union(types)\n                # Infer the union type at the first occurrence\n                first_occurrence, _ = captures[0]\n                # If it didn't exist before ``match``, it's a Var.\n                assert isinstance(var, Var)\n                inferred_types[var] = new_type\n                self.infer_variable_type(var, first_occurrence, new_type, first_occurrence)\n        return inferred_types\n\n    def remove_capture_conflicts(\n        self, type_map: TypeMap, inferred_types: dict[SymbolNode, Type]\n    ) -> None:\n        if not is_unreachable_map(type_map):\n            for expr, typ in list(type_map.items()):\n                if isinstance(expr, NameExpr):\n                    node = expr.node\n                    if node not in inferred_types or not is_subtype(typ, inferred_types[node]):\n                        del type_map[expr]\n\n    def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None:\n        if o.alias_node:\n            self.check_typevar_defaults(o.alias_node.alias_tvars)\n\n        with self.msg.filter_errors():\n            self.expr_checker.accept(o.value)\n\n    def make_fake_typeinfo(\n        self,\n        curr_module_fullname: str,\n        class_gen_name: str,\n        class_short_name: str,\n        bases: list[Instance],\n    ) -> tuple[ClassDef, TypeInfo]:\n        # Build the fake ClassDef and TypeInfo together.\n        # The ClassDef is full of lies and doesn't actually contain a body.\n        # Use format_bare to generate a nice name for error messages.\n        # We skip fully filling out a handful of TypeInfo fields because they\n        # should be irrelevant for a generated type like this:\n        # is_protocol, protocol_members, is_abstract\n        cdef = ClassDef(class_short_name, Block([]))\n        cdef.fullname = curr_module_fullname + \".\" + class_gen_name\n        info = TypeInfo(SymbolTable(), cdef, curr_module_fullname)\n        cdef.info = info\n        info.bases = bases\n        calculate_mro(info)\n        info.metaclass_type = info.calculate_metaclass_type()\n        return cdef, info\n\n    def intersect_instances(\n        self, instances: tuple[Instance, Instance], errors: list[tuple[str, str]]\n    ) -> Instance | None:\n        \"\"\"Try creating an ad-hoc intersection of the given instances.\n\n        Note that this function does *not* try and create a full-fledged\n        intersection type. Instead, it returns an instance of a new ad-hoc\n        subclass of the given instances.\n\n        This is mainly useful when you need a way of representing some\n        theoretical subclass of the instances the user may be trying to use\n        the generated intersection can serve as a placeholder.\n\n        This function will create a fresh subclass the first time you call it.\n        So this means calling `self.intersect_intersection([inst_1, inst_2], ctx)`\n        twice will return the same subclass of inst_1 and inst_2.\n\n        Returns None if creating the subclass is impossible (e.g. due to\n        MRO errors or incompatible signatures). If we do successfully create\n        a subclass, its TypeInfo will automatically be added to the global scope.\n        \"\"\"\n        curr_module = self.scope.stack[0]\n        assert isinstance(curr_module, MypyFile)\n\n        # First, retry narrowing while allowing promotions (they are disabled by default\n        # for isinstance() checks, etc). This way we will still type-check branches like\n        # x: complex = 1\n        # if isinstance(x, int):\n        #     ...\n        left, right = instances\n        if is_proper_subtype(left, right, ignore_promotions=False):\n            return left\n        if is_proper_subtype(right, left, ignore_promotions=False):\n            return right\n\n        def _get_base_classes(instances_: tuple[Instance, Instance]) -> list[Instance]:\n            base_classes_ = []\n            for inst in instances_:\n                if inst.type.is_intersection:\n                    expanded = inst.type.bases\n                else:\n                    expanded = [inst]\n\n                for expanded_inst in expanded:\n                    base_classes_.append(expanded_inst)\n            return base_classes_\n\n        def _make_fake_typeinfo_and_full_name(\n            base_classes_: list[Instance], curr_module_: MypyFile, options: Options\n        ) -> tuple[TypeInfo, str]:\n            names = [format_type_bare(x, options=options, verbosity=2) for x in base_classes_]\n            name = f\"<subclass of {pretty_seq(names, 'and')}>\"\n            if (symbol := curr_module_.names.get(name)) is not None:\n                assert isinstance(symbol.node, TypeInfo)\n                return symbol.node, name\n            cdef, info_ = self.make_fake_typeinfo(curr_module_.fullname, name, name, base_classes_)\n            return info_, name\n\n        base_classes = _get_base_classes(instances)\n        # We use the pretty_names_list for error messages but for the real name that goes\n        # into the symbol table because it is not specific enough.\n        pretty_names_list = pretty_seq(\n            format_type_distinctly(*base_classes, options=self.options, bare=True), \"and\"\n        )\n\n        if not can_have_shared_disjoint_base(base_classes):\n            errors.append((pretty_names_list, \"have distinct disjoint bases\"))\n            return None\n\n        new_errors = []\n        for base in base_classes:\n            if base.type.is_final:\n                new_errors.append((pretty_names_list, f'\"{base.type.name}\" is final'))\n        if new_errors:\n            errors.extend(new_errors)\n            return None\n\n        try:\n            info, full_name = _make_fake_typeinfo_and_full_name(\n                base_classes, curr_module, self.options\n            )\n            with self.msg.filter_errors() as local_errors:\n                self.check_multiple_inheritance(info)\n            if local_errors.has_new_errors():\n                # \"class A(B, C)\" unsafe, now check \"class A(C, B)\":\n                base_classes = _get_base_classes(instances[::-1])\n                info, full_name = _make_fake_typeinfo_and_full_name(\n                    base_classes, curr_module, self.options\n                )\n                with self.msg.filter_errors() as local_errors:\n                    self.check_multiple_inheritance(info)\n            info.is_intersection = True\n        except MroError:\n            errors.append((pretty_names_list, \"would have inconsistent method resolution order\"))\n            return None\n        if local_errors.has_new_errors():\n            errors.append((pretty_names_list, \"would have incompatible method signatures\"))\n            return None\n\n        curr_module.names[full_name] = SymbolTableNode(GDEF, info, False, module_hidden=True)\n        return Instance(info, [], extra_attrs=instances[0].extra_attrs or instances[1].extra_attrs)\n\n    def intersect_instance_callable(self, typ: Instance, callable_type: CallableType) -> Instance:\n        \"\"\"Creates a fake type that represents the intersection of an Instance and a CallableType.\n\n        It operates by creating a bare-minimum dummy TypeInfo that\n        subclasses type and adds a __call__ method matching callable_type.\n        \"\"\"\n\n        # In order for this to work in incremental mode, the type we generate needs to\n        # have a valid fullname and a corresponding entry in a symbol table. We generate\n        # a unique name inside the symbol table of the current module.\n        cur_module = self.scope.stack[0]\n        assert isinstance(cur_module, MypyFile)\n        gen_name = gen_unique_name(f\"<callable subtype of {typ.type.name}>\", cur_module.names)\n\n        # Synthesize a fake TypeInfo\n        short_name = format_type_bare(typ, self.options)\n        cdef, info = self.make_fake_typeinfo(cur_module.fullname, gen_name, short_name, [typ])\n\n        # Build up a fake FuncDef so we can populate the symbol table.\n        func_def = FuncDef(\"__call__\", [], Block([]), callable_type)\n        func_def._fullname = cdef.fullname + \".__call__\"\n        func_def.info = info\n        info.names[\"__call__\"] = SymbolTableNode(MDEF, func_def)\n\n        cur_module.names[gen_name] = SymbolTableNode(GDEF, info)\n\n        return Instance(info, [], extra_attrs=typ.extra_attrs)\n\n    def make_fake_callable(self, typ: Instance) -> Instance:\n        \"\"\"Produce a new type that makes type Callable with a generic callable type.\"\"\"\n\n        fallback = self.named_type(\"builtins.function\")\n        callable_type = CallableType(\n            [AnyType(TypeOfAny.explicit), AnyType(TypeOfAny.explicit)],\n            [nodes.ARG_STAR, nodes.ARG_STAR2],\n            [None, None],\n            ret_type=AnyType(TypeOfAny.explicit),\n            fallback=fallback,\n            is_ellipsis_args=True,\n        )\n\n        return self.intersect_instance_callable(typ, callable_type)\n\n    def partition_by_callable(\n        self, typ: Type, unsound_partition: bool\n    ) -> tuple[list[Type], list[Type]]:\n        \"\"\"Partitions a type into callable subtypes and uncallable subtypes.\n\n        Thus, given:\n        `callables, uncallables = partition_by_callable(type)`\n\n        If we assert `callable(type)` then `type` has type Union[*callables], and\n        If we assert `not callable(type)` then `type` has type Union[*uncallables]\n\n        If unsound_partition is set, assume that anything that is not\n        clearly callable is in fact not callable. Otherwise we generate a\n        new subtype that *is* callable.\n\n        Guaranteed to not return [], [].\n        \"\"\"\n        typ = get_proper_type(typ)\n\n        if isinstance(typ, (FunctionLike, TypeType)):\n            return [typ], []\n\n        if isinstance(typ, AnyType):\n            return [typ], [typ]\n\n        if isinstance(typ, NoneType):\n            return [], [typ]\n\n        if isinstance(typ, UnionType):\n            callables = []\n            uncallables: list[Type] = []\n            for subtype in typ.items:\n                # Use unsound_partition when handling unions in order to\n                # allow the expected type discrimination.\n                subcallables, subuncallables = self.partition_by_callable(\n                    subtype, unsound_partition=True\n                )\n                callables.extend(subcallables)\n                uncallables.extend(subuncallables)\n            return callables, uncallables\n\n        if isinstance(typ, TypeVarType):\n            # We could do better probably?\n            # Refine the type variable's bound as our type in the case that\n            # callable() is true. This unfortunately loses the information that\n            # the type is a type variable in that branch.\n            # This matches what is done for isinstance, but it may be possible to\n            # do better.\n            # If it is possible for the false branch to execute, return the original\n            # type to avoid losing type information.\n            callables, uncallables = self.partition_by_callable(\n                erase_to_union_or_bound(typ), unsound_partition\n            )\n            uncallables = [typ] if uncallables else []\n            return callables, uncallables\n\n        # A TupleType is callable if its fallback is, but needs special handling\n        # when we dummy up a new type.\n        ityp = typ\n        if isinstance(typ, TupleType):\n            ityp = tuple_fallback(typ)\n\n        if isinstance(ityp, Instance):\n            method = ityp.type.get_method(\"__call__\")\n            if method and method.type:\n                callables, uncallables = self.partition_by_callable(\n                    method.type, unsound_partition=False\n                )\n                if callables and not uncallables:\n                    # Only consider the type callable if its __call__ method is\n                    # definitely callable.\n                    return [typ], []\n\n            if not unsound_partition:\n                fake = self.make_fake_callable(ityp)\n                if isinstance(typ, TupleType):\n                    fake.type.tuple_type = TupleType(typ.items, fake)\n                    return [fake.type.tuple_type], [typ]\n                return [fake], [typ]\n\n        if unsound_partition:\n            return [], [typ]\n        else:\n            # We don't know how properly make the type callable.\n            return [typ], [typ]\n\n    def conditional_callable_type_map(\n        self, expr: Expression, current_type: Type | None\n    ) -> tuple[TypeMap, TypeMap]:\n        \"\"\"Takes in an expression and the current type of the expression.\n\n        Returns a 2-tuple: The first element is a map from the expression to\n        the restricted type if it were callable. The second element is a\n        map from the expression to the type it would hold if it weren't\n        callable.\n        \"\"\"\n        if not current_type:\n            return {}, {}\n\n        if isinstance(get_proper_type(current_type), AnyType):\n            return {}, {}\n\n        callables, uncallables = self.partition_by_callable(current_type, unsound_partition=False)\n\n        if callables and uncallables:\n            callable_map = {expr: UnionType.make_union(callables)}\n            uncallable_map = {expr: UnionType.make_union(uncallables)}\n            return callable_map, uncallable_map\n\n        elif callables:\n            return {}, {expr: UninhabitedType()}\n\n        return {expr: UninhabitedType()}, {}\n\n    def conditional_types_for_iterable(\n        self, item_type: Type, iterable_type: Type\n    ) -> tuple[Type, Type]:\n        \"\"\"\n        Narrows the type of `iterable_type` based on the type of `item_type`.\n        For now, we only support narrowing unions of TypedDicts based on left operand being literal string(s).\n        \"\"\"\n        if_types: list[Type] = []\n        else_types: list[Type] = []\n\n        iterable_type = get_proper_type(iterable_type)\n        if isinstance(iterable_type, UnionType):\n            possible_iterable_types = get_proper_types(iterable_type.relevant_items())\n        else:\n            possible_iterable_types = [iterable_type]\n\n        item_str_literals = try_getting_str_literals_from_type(item_type)\n\n        for possible_iterable_type in possible_iterable_types:\n            if item_str_literals and isinstance(possible_iterable_type, TypedDictType):\n                for key in item_str_literals:\n                    if key in possible_iterable_type.required_keys:\n                        if_types.append(possible_iterable_type)\n                    elif (\n                        key in possible_iterable_type.items or not possible_iterable_type.is_final\n                    ):\n                        if_types.append(possible_iterable_type)\n                        else_types.append(possible_iterable_type)\n                    else:\n                        else_types.append(possible_iterable_type)\n            else:\n                if_types.append(possible_iterable_type)\n                else_types.append(possible_iterable_type)\n\n        return UnionType.make_union(if_types), UnionType.make_union(else_types)\n\n    def _is_truthy_type(self, t: ProperType) -> bool:\n        return (\n            (\n                isinstance(t, Instance)\n                and bool(t.type)\n                and not t.type.has_readable_member(\"__bool__\")\n                and not t.type.has_readable_member(\"__len__\")\n                and t.type.fullname != \"builtins.object\"\n            )\n            or isinstance(t, FunctionLike)\n            or (\n                isinstance(t, UnionType)\n                and all(self._is_truthy_type(t) for t in get_proper_types(t.items))\n            )\n        )\n\n    def check_for_truthy_type(self, t: Type, expr: Expression) -> None:\n        \"\"\"\n        Check if a type can have a truthy value.\n\n        Used in checks like::\n\n            if x: # <---\n\n            not x  # <---\n        \"\"\"\n        if not state.strict_optional:\n            return  # if everything can be None, all bets are off\n\n        t = get_proper_type(t)\n        if not self._is_truthy_type(t):\n            return\n\n        def format_expr_type() -> str:\n            typ = format_type(t, self.options)\n            if isinstance(expr, MemberExpr):\n                return f'Member \"{expr.name}\" has type {typ}'\n            elif isinstance(expr, RefExpr) and expr.fullname:\n                return f'\"{expr.fullname}\" has type {typ}'\n            elif isinstance(expr, CallExpr):\n                if isinstance(expr.callee, MemberExpr):\n                    return f'\"{expr.callee.name}\" returns {typ}'\n                elif isinstance(expr.callee, RefExpr) and expr.callee.fullname:\n                    return f'\"{expr.callee.fullname}\" returns {typ}'\n                return f\"Call returns {typ}\"\n            else:\n                return f\"Expression has type {typ}\"\n\n        def get_expr_name() -> str:\n            if isinstance(expr, (NameExpr, MemberExpr)):\n                return f'\"{expr.name}\"'\n            else:\n                # return type if expr has no name\n                return format_type(t, self.options)\n\n        if isinstance(t, FunctionLike):\n            self.fail(message_registry.FUNCTION_ALWAYS_TRUE.format(get_expr_name()), expr)\n        elif isinstance(t, UnionType):\n            self.fail(message_registry.TYPE_ALWAYS_TRUE_UNIONTYPE.format(format_expr_type()), expr)\n        elif isinstance(t, Instance) and t.type.fullname == \"typing.Iterable\":\n            _, info = self.make_fake_typeinfo(\"typing\", \"Collection\", \"Collection\", [])\n            self.fail(\n                message_registry.ITERABLE_ALWAYS_TRUE.format(\n                    format_expr_type(), format_type(Instance(info, t.args), self.options)\n                ),\n                expr,\n            )\n        else:\n            self.fail(message_registry.TYPE_ALWAYS_TRUE.format(format_expr_type()), expr)\n\n    def find_isinstance_check(\n        self, node: Expression, *, in_boolean_context: bool = True\n    ) -> tuple[TypeMap, TypeMap]:\n        \"\"\"Find any isinstance checks (within a chain of ands).  Includes\n        implicit and explicit checks for None and calls to callable.\n        Also includes TypeGuard and TypeIs functions.\n\n        Return value is a map of variables to their types if the condition\n        is true and a map of variables to their types if the condition is false.\n\n        If either of the values in the tuple is None, then that particular\n        branch can never occur.\n\n        If `in_boolean_context=True` is passed, it means that we handle\n        a walrus expression. We treat rhs values\n        in expressions like `(a := A())` specially:\n        for example, some errors are suppressed.\n\n        May return {}, {}.\n        Can return None, None in situations involving NoReturn.\n        \"\"\"\n        if_map, else_map = self.find_isinstance_check_helper(\n            node, in_boolean_context=in_boolean_context\n        )\n        new_if_map = self.propagate_up_typemap_info(if_map)\n        new_else_map = self.propagate_up_typemap_info(else_map)\n        return new_if_map, new_else_map\n\n    def find_isinstance_check_helper(\n        self, node: Expression, *, in_boolean_context: bool = True\n    ) -> tuple[TypeMap, TypeMap]:\n        if is_true_literal(node):\n            return {}, {node: UninhabitedType()}\n        if is_false_literal(node):\n            return {node: UninhabitedType()}, {}\n\n        if isinstance(node, CallExpr) and len(node.args) != 0:\n            expr = collapse_walrus(node.args[0])\n            if refers_to_fullname(node.callee, \"builtins.isinstance\"):\n                if len(node.args) != 2:  # the error will be reported elsewhere\n                    return {}, {}\n                if literal(expr) == LITERAL_TYPE:\n                    return conditional_types_to_typemaps(\n                        expr,\n                        *self.conditional_types_with_intersection(\n                            self.lookup_type(expr), self.get_isinstance_type(node.args[1]), expr\n                        ),\n                    )\n            elif refers_to_fullname(node.callee, \"builtins.issubclass\"):\n                if len(node.args) != 2:  # the error will be reported elsewhere\n                    return {}, {}\n                if literal(expr) == LITERAL_TYPE:\n                    return self.infer_issubclass_maps(node, expr)\n            elif refers_to_fullname(node.callee, \"builtins.callable\"):\n                if len(node.args) != 1:  # the error will be reported elsewhere\n                    return {}, {}\n                if literal(expr) == LITERAL_TYPE:\n                    vartype = self.lookup_type(expr)\n                    return self.conditional_callable_type_map(expr, vartype)\n            elif refers_to_fullname(node.callee, \"builtins.hasattr\"):\n                if len(node.args) != 2:  # the error will be reported elsewhere\n                    return {}, {}\n                attr = try_getting_str_literals(node.args[1], self.lookup_type(node.args[1]))\n                if literal(expr) == LITERAL_TYPE and attr and len(attr) == 1:\n                    return self.hasattr_type_maps(expr, self.lookup_type(expr), attr[0])\n            else:\n                type_is, type_guard = None, None\n                called_type = self.lookup_type_or_none(node.callee)\n                if called_type is not None:\n                    called_type = get_proper_type(called_type)\n                    # TODO: there are some more cases in check_call() to handle.\n                    # If the callee is an instance, try to extract TypeGuard/TypeIs from its __call__ method.\n                    if isinstance(called_type, Instance):\n                        call = find_member(\"__call__\", called_type, called_type, is_operator=True)\n                        if call is not None:\n                            called_type = get_proper_type(call)\n                    if isinstance(called_type, CallableType):\n                        type_is, type_guard = called_type.type_is, called_type.type_guard\n\n                # If the callee is a RefExpr, extract TypeGuard/TypeIs directly.\n                if isinstance(node.callee, RefExpr):\n                    type_is, type_guard = node.callee.type_is, node.callee.type_guard\n                if type_guard is not None or type_is is not None:\n                    # TODO: Follow *args, **kwargs\n                    if node.arg_kinds[0] != nodes.ARG_POS:\n                        # *assuming* the overloaded function is correct, there's a couple cases:\n                        #  1) The first argument has different names, but is pos-only. We don't\n                        #     care about this case, the argument must be passed positionally.\n                        #  2) The first argument allows keyword reference, therefore must be the\n                        #     same between overloads.\n                        if isinstance(called_type, (CallableType, Overloaded)):\n                            name = called_type.items[0].arg_names[0]\n                            if name in node.arg_names:\n                                idx = node.arg_names.index(name)\n                                # we want the idx-th variable to be narrowed\n                                expr = collapse_walrus(node.args[idx])\n                            else:\n                                kind = \"guard\" if type_guard is not None else \"narrower\"\n                                self.fail(\n                                    message_registry.TYPE_GUARD_POS_ARG_REQUIRED.format(kind), node\n                                )\n                                return {}, {}\n                    if literal(expr) == LITERAL_TYPE:\n                        # Note: we wrap the target type, so that we can special case later.\n                        # Namely, for isinstance() we use a normal meet, while TypeGuard is\n                        # considered \"always right\" (i.e. even if the types are not overlapping).\n                        # Also note that a care must be taken to unwrap this back at read places\n                        # where we use this to narrow down declared type.\n                        if type_guard is not None:\n                            return {expr: TypeGuardedType(type_guard)}, {}\n                        else:\n                            assert type_is is not None\n                            return conditional_types_to_typemaps(\n                                expr,\n                                *self.conditional_types_with_intersection(\n                                    self.lookup_type(expr),\n                                    [TypeRange(type_is, is_upper_bound=False)],\n                                    expr,\n                                    consider_runtime_isinstance=False,\n                                ),\n                            )\n        elif isinstance(node, ComparisonExpr):\n            return self.comparison_type_narrowing_helper(node)\n        elif isinstance(node, AssignmentExpr):\n            if_map: TypeMap\n            else_map: TypeMap\n            if_map = {}\n            else_map = {}\n\n            if_assignment_map, else_assignment_map = self.find_isinstance_check(node.target)\n            if_map.update(if_assignment_map)\n            else_map.update(else_assignment_map)\n\n            if_condition_map, else_condition_map = self.find_isinstance_check(\n                node.value, in_boolean_context=False\n            )\n\n            if_map.update(if_condition_map)\n            else_map.update(else_condition_map)\n\n            return if_map, else_map\n        elif isinstance(node, OpExpr) and node.op == \"and\":\n            left_if_vars, left_else_vars = self.find_isinstance_check(node.left)\n            right_if_vars, right_else_vars = self.find_isinstance_check(node.right)\n\n            # (e1 and e2) is true if both e1 and e2 are true,\n            # and false if at least one of e1 and e2 is false.\n            return (\n                and_conditional_maps(left_if_vars, right_if_vars),\n                # Note that if left else type is Any, we can't add any additional\n                # types to it, since the right maps were computed assuming\n                # the left is True, which may be not the case in the else branch.\n                or_conditional_maps(left_else_vars, right_else_vars, coalesce_any=True),\n            )\n        elif isinstance(node, OpExpr) and node.op == \"or\":\n            left_if_vars, left_else_vars = self.find_isinstance_check(node.left)\n            right_if_vars, right_else_vars = self.find_isinstance_check(node.right)\n\n            # (e1 or e2) is true if at least one of e1 or e2 is true,\n            # and false if both e1 and e2 are false.\n            return (\n                or_conditional_maps(left_if_vars, right_if_vars),\n                and_conditional_maps(left_else_vars, right_else_vars),\n            )\n        elif isinstance(node, UnaryExpr) and node.op == \"not\":\n            left, right = self.find_isinstance_check(node.expr)\n            return right, left\n        elif (\n            literal(node) == LITERAL_TYPE\n            and self.has_type(node)\n            and self.can_be_narrowed_with_len(self.lookup_type(node))\n            # Only translate `if x` to `if len(x) > 0` when possible.\n            and not custom_special_method(self.lookup_type(node), \"__bool__\")\n            and self.options.strict_optional\n        ):\n            # Combine a `len(x) > 0` check with the default logic below.\n            yes_type, no_type = self.narrow_with_len(self.lookup_type(node), \">\", 0)\n            if_map = {node: true_only(yes_type)}\n            else_map = {node: false_only(no_type)}\n            return if_map, else_map\n\n        # Restrict the type of the variable to True-ish/False-ish in the if and else branches\n        # respectively\n        original_vartype = self.lookup_type(node)\n        if in_boolean_context:\n            # We don't check `:=` values in expressions like `(a := A())`,\n            # because they produce two error messages.\n            self.check_for_truthy_type(original_vartype, node)\n        vartype = try_expanding_sum_type_to_union(original_vartype, \"builtins.bool\")\n\n        if_map = {node: true_only(vartype)}\n        else_map = {node: false_only(vartype)}\n        return if_map, else_map\n\n    def comparison_type_narrowing_helper(self, node: ComparisonExpr) -> tuple[TypeMap, TypeMap]:\n        \"\"\"Infer type narrowing from a comparison expression.\"\"\"\n        # Step 1: Obtain the types of each operand and whether or not we can\n        # narrow their types. (For example, we shouldn't try narrowing the\n        # types of literal string or enum expressions).\n\n        operands = [collapse_walrus(x) for x in node.operands]\n        operand_types = []\n        narrowable_operand_index_to_hash = {}\n        for i, expr in enumerate(operands):\n            if not self.has_type(expr):\n                return {}, {}\n            expr_type = self.lookup_type(expr)\n            operand_types.append(expr_type)\n\n            if (\n                literal(expr) == LITERAL_TYPE\n                and not is_literal_none(expr)\n                and not is_literal_not_implemented(expr)\n                and not is_false_literal(expr)\n                and not is_true_literal(expr)\n                and not self.is_literal_enum(expr)\n                # CallableType type objects are usually already maximally specific\n                and not (\n                    isinstance(p_expr := get_proper_type(expr_type), FunctionLike)\n                    and p_expr.is_type_obj()\n                )\n                # This is a little ad hoc, in the absence of intersection types\n                and not (isinstance(p_expr, TypeType) and isinstance(p_expr.item, TypeVarType))\n            ):\n                h = literal_hash(expr)\n                if h is not None:\n                    narrowable_operand_index_to_hash[i] = h\n\n        # Step 2: Group operands chained by either the 'is' or '==' operands\n        # together. For all other operands, we keep them in groups of size 2.\n        # So the expression:\n        #\n        #   x0 == x1 == x2 < x3 < x4 is x5 is x6 is not x7 is not x8\n        #\n        # ...is converted into the simplified operator list:\n        #\n        #  [(\"==\", [0, 1, 2]), (\"<\", [2, 3]), (\"<\", [3, 4]),\n        #   (\"is\", [4, 5, 6]), (\"is not\", [6, 7]), (\"is not\", [7, 8])]\n        #\n        # We group identity/equality expressions so we can propagate information\n        # we discover about one operand across the entire chain. We don't bother\n        # handling 'is not' and '!=' chains in a special way: those are very rare\n        # in practice.\n\n        simplified_operator_list = group_comparison_operands(\n            node.pairwise(), narrowable_operand_index_to_hash, {\"==\", \"is\"}\n        )\n\n        # Step 3: Analyze each group and infer more precise type maps for each\n        # assignable operand, if possible. We combine these type maps together\n        # in the final step.\n\n        partial_type_maps = []\n        for operator, expr_indices in simplified_operator_list:\n            if_map: TypeMap\n            else_map: TypeMap\n\n            if operator in {\"is\", \"is not\", \"==\", \"!=\"}:\n                if_map, else_map = self.narrow_type_by_identity_equality(\n                    operator,\n                    operands,\n                    operand_types,\n                    expr_indices,\n                    narrowable_indices=narrowable_operand_index_to_hash.keys(),\n                )\n            elif operator in {\"in\", \"not in\"}:\n                assert len(expr_indices) == 2\n                left_index, right_index = expr_indices\n                item_type = operand_types[left_index]\n                iterable_type = operand_types[right_index]\n\n                if_map = {}\n                else_map = {}\n\n                if left_index in narrowable_operand_index_to_hash:\n                    collection_item_type = get_proper_type(builtin_item_type(iterable_type))\n                    if collection_item_type is not None:\n                        if_map, else_map = self.narrow_type_by_identity_equality(\n                            \"==\",\n                            operands=[operands[left_index], operands[right_index]],\n                            operand_types=[item_type, collection_item_type],\n                            expr_indices=[0, 1],\n                            narrowable_indices={0},\n                        )\n\n                        # TODO: This remove_optional code should no longer be needed. The only\n                        # thing it does is paper over a pre-existing deficiency in equality\n                        # narrowing w.r.t to enums.\n                        # We only try and narrow away 'None' for now\n                        if (\n                            not is_unreachable_map(if_map)\n                            and is_overlapping_none(item_type)\n                            and not is_overlapping_none(collection_item_type)\n                            and not (\n                                isinstance(collection_item_type, Instance)\n                                and collection_item_type.type.fullname == \"builtins.object\"\n                            )\n                            and is_overlapping_erased_types(item_type, collection_item_type)\n                        ):\n                            if_map[operands[left_index]] = remove_optional(item_type)\n\n                if right_index in narrowable_operand_index_to_hash:\n                    if_type, else_type = self.conditional_types_for_iterable(\n                        item_type, iterable_type\n                    )\n                    expr = operands[right_index]\n                    if_map[expr] = if_type\n                    else_map[expr] = else_type\n\n            else:\n                if_map = {}\n                else_map = {}\n\n            if operator in {\"is not\", \"!=\", \"not in\"}:\n                if_map, else_map = else_map, if_map\n\n            partial_type_maps.append((if_map, else_map))\n\n        # If we have found non-trivial restrictions from the regular comparisons,\n        # then return soon. Otherwise try to infer restrictions involving `len(x)`.\n        # TODO: support regular and len() narrowing in the same chain.\n        if any(m != ({}, {}) for m in partial_type_maps):\n            return reduce_conditional_maps(partial_type_maps)\n        else:\n            # Use meet for `and` maps to get correct results for chained checks\n            # like `if 1 < len(x) < 4: ...`\n            return reduce_conditional_maps(self.find_tuple_len_narrowing(node), use_meet=True)\n\n    def narrow_type_by_identity_equality(\n        self,\n        operator: str,\n        operands: list[Expression],\n        operand_types: list[Type],\n        expr_indices: list[int],\n        narrowable_indices: AbstractSet[int],\n    ) -> tuple[TypeMap, TypeMap]:\n        \"\"\"\n        Calculate type maps for '==', '!=', 'is' or 'is not' expression, ignoring `type(x)` checks.\n\n        The 'operands' and 'operand_types' lists should be the full list of operands used\n        in the overall comparison expression. The 'chain_indices' list is the list of indices\n        actually used within this identity comparison chain.\n\n        So if we have the expression:\n\n            a <= b is c is d <= e\n\n        ...then 'operands' and 'operand_types' would be lists of length 5 and 'chain_indices'\n        would be the list [1, 2, 3].\n\n        The 'narrowable_indices' parameter is the set of all indices we are allowed\n        to refine the types of: that is, all operands that will potentially be a part of\n        the output TypeMaps.\n\n        \"\"\"\n        # is_target_for_value_narrowing:\n        # If the operator returns True when compared to this target, do we narrow in else branch?\n        # E.g. if operator is \"==\", then:\n        # - is_target_for_value_narrowing(str) == False\n        # - is_target_for_value_narrowing(Literal[\"asdf\"]) == True\n        is_target_for_value_narrowing: Callable[[ProperType], bool]\n\n        # should_coerce_literals:\n        # Ideally, we should always attempt to have this set to True. Unfortunately, for now,\n        # performing this coercion can sometimes result in overly aggressive narrowing when taking\n        # in the context of other type checker behaviour.\n        should_coerce_literals: bool\n\n        # custom_eq_indices:\n        # Operands at these indices define a custom `__eq__`. These can do arbitrary things, so we\n        # have to be more careful about what narrowing we can conclude from a successful comparison\n        custom_eq_indices: set[int]\n\n        # enum_comparison_is_ambiguous:\n        # `if x is Fruits.APPLE` we know `x` is `Fruits.APPLE`, but `if x == Fruits.APPLE: ...`\n        # it could e.g. be an int or str if Fruits is an IntEnum or StrEnum.\n        # See ambiguous_enum_equality_keys for more details\n        enum_comparison_is_ambiguous: bool\n\n        if operator in {\"is\", \"is not\"}:\n            is_target_for_value_narrowing = is_singleton_identity_type\n            should_coerce_literals = True\n            custom_eq_indices = set()\n            enum_comparison_is_ambiguous = False\n\n        elif operator in {\"==\", \"!=\"}:\n            is_target_for_value_narrowing = is_singleton_equality_type\n\n            should_coerce_literals = False\n            for i in expr_indices:\n                typ = get_proper_type(operand_types[i])\n                if is_literal_type_like(typ) or (isinstance(typ, Instance) and typ.type.is_enum):\n                    should_coerce_literals = True\n                    break\n\n            custom_eq_indices = {i for i in expr_indices if has_custom_eq_checks(operand_types[i])}\n            enum_comparison_is_ambiguous = True\n        else:\n            raise AssertionError\n\n        all_if_maps: list[TypeMap] = []\n        all_else_maps: list[TypeMap] = []\n\n        # For each narrowable index, we see what we can narrow based on each relevant target\n        for i in expr_indices:\n            if i not in narrowable_indices:\n                continue\n            if i in custom_eq_indices:\n                # Handled later\n                continue\n\n            expr_type = operand_types[i]\n            expr_enum_keys = ambiguous_enum_equality_keys(expr_type)\n            expr_type = try_expanding_sum_type_to_union(coerce_to_literal(expr_type), None)\n            for j in expr_indices:\n                if i == j:\n                    continue\n                if j in custom_eq_indices:\n                    # We can't use types with custom __eq__ as targets for narrowing\n                    # E.g. if (x: int | None) == (y: CustomEq | None), we cannot narrow x to None\n                    continue\n                target_type = operand_types[j]\n                if should_coerce_literals:\n                    target_type = coerce_to_literal(target_type)\n\n                if (\n                    # See comments in ambiguous_enum_equality_keys\n                    enum_comparison_is_ambiguous\n                    and len(expr_enum_keys | ambiguous_enum_equality_keys(target_type)) > 1\n                ):\n                    continue\n\n                target = TypeRange(target_type, is_upper_bound=False)\n\n                if_map, else_map = conditional_types_to_typemaps(\n                    operands[i], *conditional_types(expr_type, [target], from_equality=True)\n                )\n                if is_target_for_value_narrowing(get_proper_type(target_type)):\n                    all_if_maps.append(if_map)\n                    all_else_maps.append(else_map)\n                else:\n                    # For value targets, it is safe to narrow in the negative case.\n                    # e.g. if (x: Literal[5] | None) != (y: Literal[5]), we can narrow x to None\n                    # However, for non-value targets, we cannot do this narrowing,\n                    # and so we ignore else_map\n                    # e.g. if (x: str | None) != (y: str), we cannot narrow x to None\n\n                    # It is correct to always narrow here. It improves behaviour on tests and\n                    # detects many inaccurate type annotations on primer.\n                    # However, because mypy does not currently check unreachable code, it feels\n                    # risky to narrow to unreachable without --warn-unreachable.\n                    # See also this specific primer comment, where I force primer to run with\n                    # --warn-unreachable to see what code we would stop checking:\n                    # https://github.com/python/mypy/pull/20660#issuecomment-3865794148\n                    if self.options.warn_unreachable or not is_unreachable_map(if_map):\n                        all_if_maps.append(if_map)\n\n        # Handle narrowing for operands with custom __eq__ methods specially\n        # In most cases, we won't be able to do any narrowing\n        for i in custom_eq_indices:\n            if i not in narrowable_indices:\n                continue\n            union_expr_type = get_proper_type(operand_types[i])\n            if not isinstance(union_expr_type, UnionType):\n                # Here we won't be able to do any positive narrowing, because we can't conclude\n                # anything from a custom __eq__ returning True.\n                # But we might be able to do some negative narrowing, since we can assume\n                # a custom __eq__ is reflexive. This should only apply to custom __eq__ enums,\n                # see testNarrowingEqualityCustomEqualityEnum\n                expr_type = operand_types[i]\n                for j in expr_indices:\n                    if j in custom_eq_indices:\n                        continue\n                    target_type = operand_types[j]\n                    if should_coerce_literals:\n                        target_type = coerce_to_literal(target_type)\n                    target = TypeRange(target_type, is_upper_bound=False)\n                    if is_target_for_value_narrowing(get_proper_type(target_type)):\n                        if_map, else_map = conditional_types_to_typemaps(\n                            operands[i],\n                            *conditional_types(expr_type, [target], from_equality=True),\n                        )\n                        all_else_maps.append(else_map)\n                continue\n\n            # If our operand with custom __eq__ is a union, where only some members of the union\n            # implement custom __eq__, then we can narrow down the other members as usual.\n            # This is basically the same logic as the main narrowing loop above.\n            or_if_maps: list[TypeMap] = []\n            or_else_maps: list[TypeMap] = []\n            for expr_type in union_expr_type.items:\n                if has_custom_eq_checks(expr_type):\n                    # Always include the union items with custom __eq__ in the type\n                    # we narrow to in the if_map\n                    or_if_maps.append({operands[i]: expr_type})\n\n                expr_type = coerce_to_literal(try_expanding_sum_type_to_union(expr_type, None))\n                for j in expr_indices:\n                    if j in custom_eq_indices:\n                        if i == j:\n                            continue\n                        # If we compare to a target with custom __eq__, we cannot narrow at all\n                        if is_overlapping_none(expr_type) and not is_overlapping_none(\n                            operand_types[j]\n                        ):\n                            # Narrow away from None. This is unsound, we're hoping that no one\n                            # has a custom __eq__ that returns True for None.\n                            or_if_maps.append({operands[i]: remove_optional(expr_type)})\n                        else:\n                            or_if_maps.append({operands[i]: expr_type})\n                        continue\n                    target_type = operand_types[j]\n                    if should_coerce_literals:\n                        target_type = coerce_to_literal(target_type)\n                    target = TypeRange(target_type, is_upper_bound=False)\n\n                    if_map, else_map = conditional_types_to_typemaps(\n                        operands[i],\n                        *conditional_types(\n                            expr_type, [target], default=expr_type, from_equality=True\n                        ),\n                    )\n                    or_if_maps.append(if_map)\n                    if is_target_for_value_narrowing(get_proper_type(target_type)):\n                        or_else_maps.append(else_map)\n\n            all_if_maps.append(reduce_or_conditional_type_maps(or_if_maps))\n            all_else_maps.append(reduce_or_conditional_type_maps(or_else_maps))\n\n        # Handle narrowing for comparisons that produce additional narrowing, like\n        # `type(x) == T` or `x.__class__ is T`\n        for i in expr_indices:\n            type_expr = operands[i]\n            if (\n                isinstance(type_expr, CallExpr)\n                and refers_to_fullname(type_expr.callee, \"builtins.type\")\n                and len(type_expr.args) == 1\n            ):\n                expr_in_type_expr = type_expr.args[0]\n            elif isinstance(type_expr, MemberExpr) and type_expr.name == \"__class__\":\n                expr_in_type_expr = type_expr.expr\n            else:\n                continue\n            for j in expr_indices:\n                if i == j:\n                    continue\n                expr = operands[j]\n\n                current_type_range = self.get_type_range_of_type(operand_types[j])\n                if current_type_range is None:\n                    continue\n                if isinstance(get_proper_type(current_type_range.item), AnyType):\n                    # Avoid widening to Any for checks like `type(x) is type(y: Any)`.\n                    # We patch this here because it is desirable to widen to any for cases like\n                    # isinstance(x, (y: Any))\n                    continue\n\n                arg_type = self.lookup_type(expr_in_type_expr)\n                if_type, else_type = self.conditional_types_with_intersection(\n                    arg_type, [current_type_range], expr_in_type_expr\n                )\n                if if_type is not None and (\n                    not current_type_range.is_upper_bound\n                    and not is_equivalent(if_type, current_type_range.item)\n                ):\n                    # type(x) and x.__class__ checks must exact match\n                    if_type = UninhabitedType()\n\n                if_map, else_map = conditional_types_to_typemaps(\n                    expr_in_type_expr, if_type, else_type\n                )\n\n                is_final = (\n                    expr.node.is_final\n                    if isinstance(expr, RefExpr) and isinstance(expr.node, TypeInfo)\n                    else False\n                )\n                all_if_maps.append(if_map)\n                if is_final:\n                    # We can only narrow `type(x) == T` in the negative case if T is final\n                    all_else_maps.append(else_map)\n\n        # We will not have duplicate entries in our type maps if we only have two operands,\n        # so we can skip running meets on the intersections\n        if_map = reduce_and_conditional_type_maps(all_if_maps, use_meet=len(operands) > 2)\n        else_map = reduce_or_conditional_type_maps(all_else_maps)\n        return if_map, else_map\n\n    def propagate_up_typemap_info(self, new_types: TypeMap) -> TypeMap:\n        \"\"\"Attempts refining parent expressions of any MemberExpr or IndexExprs in new_types.\n\n        Specifically, this function accepts two mappings of expression to original types:\n        the original mapping (existing_types), and a new mapping (new_types) intended to\n        update the original.\n\n        This function iterates through new_types and attempts to use the information to try\n        refining any parent types that happen to be unions.\n\n        For example, suppose there are two types \"A = Tuple[int, int]\" and \"B = Tuple[str, str]\".\n        Next, suppose that 'new_types' specifies the expression 'foo[0]' has a refined type\n        of 'int' and that 'foo' was previously deduced to be of type Union[A, B].\n\n        Then, this function will observe that since A[0] is an int and B[0] is not, the type of\n        'foo' can be further refined from Union[A, B] into just B.\n\n        We perform this kind of \"parent narrowing\" for member lookup expressions and indexing\n        expressions into tuples, namedtuples, and typeddicts. We repeat this narrowing\n        recursively if the parent is also a \"lookup expression\". So for example, if we have\n        the expression \"foo['bar'].baz[0]\", we'd potentially end up refining types for the\n        expressions \"foo\", \"foo['bar']\", and \"foo['bar'].baz\".\n\n        We return the newly refined map. This map is guaranteed to be a superset of 'new_types'.\n        \"\"\"\n        output_map = {}\n        for expr, expr_type in new_types.items():\n            # The original inferred type should always be present in the output map, of course\n            output_map[expr] = expr_type\n\n            # Next, try using this information to refine the parent types, if applicable.\n            new_mapping = self.refine_parent_types(expr, expr_type)\n            for parent_expr, proposed_parent_type in new_mapping.items():\n                # We don't try inferring anything if we've already inferred something for\n                # the parent expression.\n                # TODO: Consider picking the narrower type instead of always discarding this?\n                if parent_expr in new_types:\n                    continue\n                output_map[parent_expr] = proposed_parent_type\n        return output_map\n\n    def refine_parent_types(self, expr: Expression, expr_type: Type) -> Mapping[Expression, Type]:\n        \"\"\"Checks if the given expr is a 'lookup operation' into a union and iteratively refines\n        the parent types based on the 'expr_type'.\n\n        For example, if 'expr' is an expression like 'a.b.c.d', we'll potentially return refined\n        types for expressions 'a', 'a.b', and 'a.b.c'.\n\n        For more details about what a 'lookup operation' is and how we use the expr_type to refine\n        the parent types of lookup_expr, see the docstring in 'propagate_up_typemap_info'.\n        \"\"\"\n        output: dict[Expression, Type] = {}\n\n        # Note: parent_expr and parent_type are progressively refined as we crawl up the\n        # parent lookup chain.\n        while True:\n            # First, check if this expression is one that's attempting to\n            # \"lookup\" some key in the parent type. If so, save the parent type\n            # and create function that will try replaying the same lookup\n            # operation against arbitrary types.\n            if isinstance(expr, MemberExpr):\n                parent_expr = self._propagate_walrus_assignments(expr.expr, output)\n                parent_type = self.lookup_type_or_none(parent_expr)\n                member_name = expr.name\n\n                def replay_lookup(new_parent_type: ProperType) -> Type | None:\n                    with self.msg.filter_errors() as w:\n                        member_type = analyze_member_access(\n                            name=member_name,\n                            typ=new_parent_type,\n                            context=parent_expr,\n                            is_lvalue=False,\n                            is_super=False,\n                            is_operator=False,\n                            original_type=new_parent_type,\n                            chk=self,\n                            in_literal_context=False,\n                        )\n                    if w.has_new_errors():\n                        return None\n                    else:\n                        return member_type\n\n            elif isinstance(expr, IndexExpr):\n                parent_expr = self._propagate_walrus_assignments(expr.base, output)\n                parent_type = self.lookup_type_or_none(parent_expr)\n\n                self._propagate_walrus_assignments(expr.index, output)\n                index_type = self.lookup_type_or_none(expr.index)\n                if index_type is None:\n                    return output\n\n                str_literals = try_getting_str_literals_from_type(index_type)\n                if str_literals is not None:\n                    # Refactoring these two indexing replay functions is surprisingly\n                    # tricky -- see https://github.com/python/mypy/pull/7917, which\n                    # was blocked by https://github.com/mypyc/mypyc/issues/586\n                    def replay_lookup(new_parent_type: ProperType) -> Type | None:\n                        if not isinstance(new_parent_type, TypedDictType):\n                            return None\n                        try:\n                            assert str_literals is not None\n                            member_types = [new_parent_type.items[key] for key in str_literals]\n                        except KeyError:\n                            return None\n                        return make_simplified_union(member_types)\n\n                else:\n                    int_literals = try_getting_int_literals_from_type(index_type)\n                    if int_literals is not None:\n\n                        def replay_lookup(new_parent_type: ProperType) -> Type | None:\n                            if not isinstance(new_parent_type, TupleType):\n                                return None\n                            try:\n                                assert int_literals is not None\n                                member_types = [new_parent_type.items[key] for key in int_literals]\n                            except IndexError:\n                                return None\n                            return make_simplified_union(member_types)\n\n                    else:\n                        return output\n            else:\n                return output\n\n            # If we somehow didn't previously derive the parent type, abort completely\n            # with what we have so far: something went wrong at an earlier stage.\n            if parent_type is None:\n                return output\n\n            # We currently only try refining the parent type if it's a Union.\n            # If not, there's no point in trying to refine any further parents\n            # since we have no further information we can use to refine the lookup\n            # chain, so we end early as an optimization.\n            parent_type = get_proper_type(parent_type)\n            if not isinstance(parent_type, UnionType):\n                return output\n\n            # Take each element in the parent union and replay the original lookup procedure\n            # to figure out which parents are compatible.\n            new_parent_types = []\n            for item in flatten_nested_unions(parent_type.items):\n                member_type = replay_lookup(get_proper_type(item))\n                if member_type is None:\n                    # We were unable to obtain the member type. So, we give up on refining this\n                    # parent type entirely and abort.\n                    return output\n\n                if is_overlapping_types(member_type, expr_type):\n                    new_parent_types.append(item)\n\n            # If none of the parent types overlap (if we derived an empty union), something\n            # went wrong. We should never hit this case, but deriving the uninhabited type or\n            # reporting an error both seem unhelpful. So we abort.\n            if not new_parent_types:\n                return output\n\n            expr = parent_expr\n            expr_type = output[parent_expr] = make_simplified_union(new_parent_types)\n\n    def _propagate_walrus_assignments(\n        self, expr: Expression, type_map: dict[Expression, Type]\n    ) -> Expression:\n        \"\"\"Add assignments from walrus expressions to inferred types.\n\n        Only considers nested assignment exprs, does not recurse into other types.\n        This may be added later if necessary by implementing a dedicated visitor.\n        \"\"\"\n        if isinstance(expr, AssignmentExpr):\n            if isinstance(expr.value, AssignmentExpr):\n                self._propagate_walrus_assignments(expr.value, type_map)\n            assigned_type = self.lookup_type_or_none(expr.value)\n            parent_expr = collapse_walrus(expr)\n            if assigned_type is not None:\n                type_map[parent_expr] = assigned_type\n            return parent_expr\n        return expr\n\n    def is_len_of_tuple(self, expr: Expression) -> bool:\n        \"\"\"Is this expression a `len(x)` call where x is a tuple or union of tuples?\"\"\"\n        if not isinstance(expr, CallExpr):\n            return False\n        if not refers_to_fullname(expr.callee, \"builtins.len\"):\n            return False\n        if len(expr.args) != 1:\n            return False\n        expr = expr.args[0]\n        if literal(expr) != LITERAL_TYPE:\n            return False\n        if not self.has_type(expr):\n            return False\n        return self.can_be_narrowed_with_len(self.lookup_type(expr))\n\n    def can_be_narrowed_with_len(self, typ: Type) -> bool:\n        \"\"\"Is this a type that can benefit from length check type restrictions?\n\n        Currently supported types are TupleTypes, Instances of builtins.tuple, and\n        unions involving such types.\n        \"\"\"\n        if custom_special_method(typ, \"__len__\"):\n            # If user overrides builtin behavior, we can't do anything.\n            return False\n        p_typ = get_proper_type(typ)\n        # Note: we are conservative about tuple subclasses, because some code may rely on\n        # the fact that tuple_type of fallback TypeInfo matches the original TupleType.\n        if isinstance(p_typ, TupleType):\n            if any(isinstance(t, UnpackType) for t in p_typ.items):\n                return p_typ.partial_fallback.type.fullname == \"builtins.tuple\"\n            return True\n        if isinstance(p_typ, Instance):\n            return p_typ.type.has_base(\"builtins.tuple\")\n        if isinstance(p_typ, UnionType):\n            return any(self.can_be_narrowed_with_len(t) for t in p_typ.items)\n        return False\n\n    def literal_int_expr(self, expr: Expression) -> int | None:\n        \"\"\"Is this expression an int literal, or a reference to an int constant?\n\n        If yes, return the corresponding int value, otherwise return None.\n        \"\"\"\n        if not self.has_type(expr):\n            return None\n        expr_type = self.lookup_type(expr)\n        expr_type = coerce_to_literal(expr_type)\n        proper_type = get_proper_type(expr_type)\n        if not isinstance(proper_type, LiteralType):\n            return None\n        if not isinstance(proper_type.value, int):\n            return None\n        return proper_type.value\n\n    def find_tuple_len_narrowing(self, node: ComparisonExpr) -> list[tuple[TypeMap, TypeMap]]:\n        \"\"\"Top-level logic to find type restrictions from a length check on tuples.\n\n        We try to detect `if` checks like the following:\n            x: tuple[int, int] | tuple[int, int, int]\n            y: tuple[int, int] | tuple[int, int, int]\n            if len(x) == len(y) == 2:\n                a, b = x  # OK\n                c, d = y  # OK\n\n            z: tuple[int, ...]\n            if 1 < len(z) < 4:\n                x = z  # OK\n        and report corresponding type restrictions to the binder.\n        \"\"\"\n        # First step: group consecutive `is` and `==` comparisons together.\n        # This is essentially a simplified version of group_comparison_operands(),\n        # tuned to the len()-like checks. Note that we don't propagate indirect\n        # restrictions like e.g. `len(x) > foo() > 1` yet, since it is tricky.\n        # TODO: propagate indirect len() comparison restrictions.\n        chained = []\n        last_group = set()\n        for op, left, right in node.pairwise():\n            if isinstance(left, AssignmentExpr):\n                left = left.value\n            if isinstance(right, AssignmentExpr):\n                right = right.value\n            if op in (\"is\", \"==\"):\n                last_group.add(left)\n                last_group.add(right)\n            else:\n                if last_group:\n                    chained.append((\"==\", list(last_group)))\n                    last_group = set()\n                if op in {\"is not\", \"!=\", \"<\", \"<=\", \">\", \">=\"}:\n                    chained.append((op, [left, right]))\n        if last_group:\n            chained.append((\"==\", list(last_group)))\n\n        yes_map: TypeMap\n        no_map: TypeMap\n\n        # Second step: infer type restrictions from each group found above.\n        type_maps = []\n        for op, items in chained:\n            # TODO: support unions of literal types as len() comparison targets.\n            if not any(self.literal_int_expr(it) is not None for it in items):\n                continue\n            if not any(self.is_len_of_tuple(it) for it in items):\n                continue\n\n            # At this step we know there is at least one len(x) and one literal in the group.\n            if op in (\"is\", \"==\"):\n                literal_values = set()\n                tuples = []\n                for it in items:\n                    lit = self.literal_int_expr(it)\n                    if lit is not None:\n                        literal_values.add(lit)\n                        continue\n                    if self.is_len_of_tuple(it):\n                        assert isinstance(it, CallExpr)\n                        tuples.append(it.args[0])\n                if len(literal_values) > 1:\n                    # More than one different literal value found, like 1 == len(x) == 2,\n                    # so the corresponding branch is unreachable.\n                    yes_map = {tpl: UninhabitedType() for tpl in tuples}\n                    return [(yes_map, {})]\n                size = literal_values.pop()\n                if size > MAX_PRECISE_TUPLE_SIZE:\n                    # Avoid creating huge tuples from checks like if len(x) == 300.\n                    continue\n                for tpl in tuples:\n                    yes_type, no_type = self.narrow_with_len(self.lookup_type(tpl), op, size)\n                    yes_map = {tpl: yes_type}\n                    no_map = {tpl: no_type}\n                    type_maps.append((yes_map, no_map))\n            else:\n                left, right = items\n                if self.is_len_of_tuple(right):\n                    # Normalize `1 < len(x)` and similar as `len(x) > 1`.\n                    left, right = right, left\n                    op = flip_ops.get(op, op)\n                r_size = self.literal_int_expr(right)\n                assert r_size is not None\n                if r_size > MAX_PRECISE_TUPLE_SIZE:\n                    # Avoid creating huge unions from checks like if len(x) > 300.\n                    continue\n                assert isinstance(left, CallExpr)\n                yes_type, no_type = self.narrow_with_len(\n                    self.lookup_type(left.args[0]), op, r_size\n                )\n                yes_map = {left.args[0]: yes_type}\n                no_map = {left.args[0]: no_type}\n                type_maps.append((yes_map, no_map))\n        return type_maps\n\n    def narrow_with_len(self, typ: Type, op: str, size: int) -> tuple[Type, Type]:\n        \"\"\"Dispatch tuple type narrowing logic depending on the kind of type we got.\"\"\"\n        typ = get_proper_type(typ)\n        if isinstance(typ, TupleType):\n            return self.refine_tuple_type_with_len(typ, op, size)\n        elif isinstance(typ, Instance):\n            return self.refine_instance_type_with_len(typ, op, size)\n        elif isinstance(typ, UnionType):\n            yes_types = []\n            no_types = []\n            other_types = []\n            for t in typ.items:\n                if not self.can_be_narrowed_with_len(t):\n                    other_types.append(t)\n                    continue\n                yt, nt = self.narrow_with_len(t, op, size)\n                yes_types.append(yt)\n                no_types.append(nt)\n            yes_types += other_types\n            no_types += other_types\n            yes_type = make_simplified_union(yes_types)\n            no_type = make_simplified_union(no_types)\n            return yes_type, no_type\n        else:\n            assert False, \"Unsupported type for len narrowing\"\n\n    def refine_tuple_type_with_len(self, typ: TupleType, op: str, size: int) -> tuple[Type, Type]:\n        \"\"\"Narrow a TupleType using length restrictions.\"\"\"\n        unpack_index = find_unpack_in_list(typ.items)\n        if unpack_index is None:\n            # For fixed length tuple situation is trivial, it is either reachable or not,\n            # depending on the current length, expected length, and the comparison op.\n            method = int_op_to_method[op]\n            if method(typ.length(), size):\n                return typ, UninhabitedType()\n            return UninhabitedType(), typ\n        unpack = typ.items[unpack_index]\n        assert isinstance(unpack, UnpackType)\n        unpacked = get_proper_type(unpack.type)\n        if isinstance(unpacked, TypeVarTupleType):\n            # For tuples involving TypeVarTuple unpack we can't do much except\n            # inferring reachability, and recording the restrictions on TypeVarTuple\n            # for further \"manual\" use elsewhere.\n            min_len = typ.length() - 1 + unpacked.min_len\n            if op in (\"==\", \"is\"):\n                if min_len <= size:\n                    return typ, typ\n                return UninhabitedType(), typ\n            elif op in (\"<\", \"<=\"):\n                if op == \"<=\":\n                    size += 1\n                if min_len < size:\n                    prefix = typ.items[:unpack_index]\n                    suffix = typ.items[unpack_index + 1 :]\n                    # TODO: also record max_len to avoid false negatives?\n                    unpack = UnpackType(unpacked.copy_modified(min_len=size - typ.length() + 1))\n                    return typ, typ.copy_modified(items=prefix + [unpack] + suffix)\n                return UninhabitedType(), typ\n            else:\n                yes_type, no_type = self.refine_tuple_type_with_len(typ, neg_ops[op], size)\n                return no_type, yes_type\n        # Homogeneous variadic item is the case where we are most flexible. Essentially,\n        # we adjust the variadic item by \"eating away\" from it to satisfy the restriction.\n        assert isinstance(unpacked, Instance) and unpacked.type.fullname == \"builtins.tuple\"\n        min_len = typ.length() - 1\n        arg = unpacked.args[0]\n        prefix = typ.items[:unpack_index]\n        suffix = typ.items[unpack_index + 1 :]\n        if op in (\"==\", \"is\"):\n            if min_len <= size:\n                # TODO: return fixed union + prefixed variadic tuple for no_type?\n                return typ.copy_modified(items=prefix + [arg] * (size - min_len) + suffix), typ\n            return UninhabitedType(), typ\n        elif op in (\"<\", \"<=\"):\n            if op == \"<=\":\n                size += 1\n            if min_len < size:\n                # Note: there is some ambiguity w.r.t. to where to put the additional\n                # items: before or after the unpack. However, such types are equivalent,\n                # so we always put them before for consistency.\n                no_type = typ.copy_modified(\n                    items=prefix + [arg] * (size - min_len) + [unpack] + suffix\n                )\n                yes_items = []\n                for n in range(size - min_len):\n                    yes_items.append(typ.copy_modified(items=prefix + [arg] * n + suffix))\n                return UnionType.make_union(yes_items, typ.line, typ.column), no_type\n            return UninhabitedType(), typ\n        else:\n            yes_type, no_type = self.refine_tuple_type_with_len(typ, neg_ops[op], size)\n            return no_type, yes_type\n\n    def refine_instance_type_with_len(\n        self, typ: Instance, op: str, size: int\n    ) -> tuple[Type, Type]:\n        \"\"\"Narrow a homogeneous tuple using length restrictions.\"\"\"\n        base = map_instance_to_supertype(typ, self.lookup_typeinfo(\"builtins.tuple\"))\n        arg = base.args[0]\n        # Again, we are conservative about subclasses until we gain more confidence.\n        allow_precise = (\n            PRECISE_TUPLE_TYPES in self.options.enable_incomplete_feature\n        ) and typ.type.fullname == \"builtins.tuple\"\n        if op in (\"==\", \"is\"):\n            # TODO: return fixed union + prefixed variadic tuple for no_type?\n            return TupleType(items=[arg] * size, fallback=typ), typ\n        elif op in (\"<\", \"<=\"):\n            if op == \"<=\":\n                size += 1\n            if allow_precise:\n                unpack = UnpackType(self.named_generic_type(\"builtins.tuple\", [arg]))\n                no_type: Type = TupleType(items=[arg] * size + [unpack], fallback=typ)\n            else:\n                no_type = typ\n            if allow_precise:\n                items = []\n                for n in range(size):\n                    items.append(TupleType([arg] * n, fallback=typ))\n                yes_type: Type = UnionType.make_union(items, typ.line, typ.column)\n            else:\n                yes_type = typ\n            return yes_type, no_type\n        else:\n            yes_type, no_type = self.refine_instance_type_with_len(typ, neg_ops[op], size)\n            return no_type, yes_type\n\n    #\n    # Helpers\n    #\n    @overload\n    def check_subtype(\n        self,\n        subtype: Type,\n        supertype: Type,\n        context: Context,\n        msg: str,\n        subtype_label: str | None = None,\n        supertype_label: str | None = None,\n        *,\n        notes: list[str] | None = None,\n        code: ErrorCode | None = None,\n        outer_context: Context | None = None,\n    ) -> bool: ...\n\n    @overload\n    def check_subtype(\n        self,\n        subtype: Type,\n        supertype: Type,\n        context: Context,\n        msg: ErrorMessage,\n        subtype_label: str | None = None,\n        supertype_label: str | None = None,\n        *,\n        notes: list[str] | None = None,\n        outer_context: Context | None = None,\n    ) -> bool: ...\n\n    def check_subtype(\n        self,\n        subtype: Type,\n        supertype: Type,\n        context: Context,\n        msg: str | ErrorMessage,\n        subtype_label: str | None = None,\n        supertype_label: str | None = None,\n        *,\n        notes: list[str] | None = None,\n        code: ErrorCode | None = None,\n        outer_context: Context | None = None,\n    ) -> bool:\n        \"\"\"Generate an error if the subtype is not compatible with supertype.\"\"\"\n        if is_subtype(subtype, supertype, options=self.options):\n            return True\n\n        if isinstance(msg, str):\n            msg = ErrorMessage(msg, code=code)\n\n        if self.msg.prefer_simple_messages():\n            self.fail(msg, context)  # Fast path -- skip all fancy logic\n            return False\n\n        orig_subtype = subtype\n        subtype = get_proper_type(subtype)\n        orig_supertype = supertype\n        supertype = get_proper_type(supertype)\n        if self.msg.try_report_long_tuple_assignment_error(\n            subtype, supertype, context, msg, subtype_label, supertype_label\n        ):\n            return False\n        extra_info: list[str] = []\n        note_msg = \"\"\n        notes = notes or []\n        if subtype_label is not None or supertype_label is not None:\n            subtype_str, supertype_str = format_type_distinctly(\n                orig_subtype, orig_supertype, options=self.options\n            )\n            if subtype_label is not None:\n                extra_info.append(subtype_label + \" \" + subtype_str)\n            if supertype_label is not None:\n                extra_info.append(supertype_label + \" \" + supertype_str)\n            note_msg = make_inferred_type_note(\n                outer_context or context, subtype, supertype, supertype_str\n            )\n            if isinstance(subtype, Instance) and isinstance(supertype, Instance):\n                notes = append_invariance_notes(notes, subtype, supertype)\n            if isinstance(subtype, UnionType) and isinstance(supertype, UnionType):\n                notes = append_union_note(notes, subtype, supertype, self.options)\n        if extra_info:\n            msg = msg.with_additional_msg(\" (\" + \", \".join(extra_info) + \")\")\n\n        error = self.fail(msg, context)\n        for note in notes:\n            self.msg.note(note, context, code=msg.code)\n        if note_msg:\n            self.note(note_msg, context, code=msg.code)\n        self.msg.maybe_note_concatenate_pos_args(subtype, supertype, context, code=msg.code)\n        if (\n            isinstance(supertype, Instance)\n            and supertype.type.is_protocol\n            and isinstance(subtype, (CallableType, Instance, TupleType, TypedDictType, TypeType))\n        ):\n            self.msg.report_protocol_problems(subtype, supertype, context, parent_error=error)\n        if isinstance(supertype, CallableType) and isinstance(subtype, Instance):\n            call = find_member(\"__call__\", subtype, subtype, is_operator=True)\n            if call:\n                self.msg.note_call(subtype, call, context, code=msg.code)\n        if isinstance(subtype, (CallableType, Overloaded)) and isinstance(supertype, Instance):\n            if supertype.type.is_protocol and \"__call__\" in supertype.type.protocol_members:\n                call = find_member(\"__call__\", supertype, subtype, is_operator=True)\n                assert call is not None\n                if not is_subtype(subtype, call, options=self.options):\n                    self.msg.note_call(supertype, call, context, code=msg.code)\n        self.check_possible_missing_await(subtype, supertype, context, code=msg.code)\n        return False\n\n    def get_precise_awaitable_type(self, typ: Type, local_errors: ErrorWatcher) -> Type | None:\n        \"\"\"If type implements Awaitable[X] with non-Any X, return X.\n\n        In all other cases return None. This method must be called in context\n        of local_errors.\n        \"\"\"\n        if isinstance(get_proper_type(typ), PartialType):\n            # Partial types are special, ignore them here.\n            return None\n        try:\n            aw_type = self.expr_checker.check_awaitable_expr(\n                typ, Context(), \"\", ignore_binder=True\n            )\n        except KeyError:\n            # This is a hack to speed up tests by not including Awaitable in all typing stubs.\n            return None\n        if local_errors.has_new_errors():\n            return None\n        if isinstance(get_proper_type(aw_type), (AnyType, UnboundType)):\n            return None\n        return aw_type\n\n    @contextmanager\n    def checking_await_set(self) -> Iterator[None]:\n        self.checking_missing_await = True\n        try:\n            yield\n        finally:\n            self.checking_missing_await = False\n\n    def check_possible_missing_await(\n        self, subtype: Type, supertype: Type, context: Context, code: ErrorCode | None\n    ) -> None:\n        \"\"\"Check if the given type becomes a subtype when awaited.\"\"\"\n        if self.checking_missing_await:\n            # Avoid infinite recursion.\n            return\n        with self.checking_await_set(), self.msg.filter_errors() as local_errors:\n            aw_type = self.get_precise_awaitable_type(subtype, local_errors)\n            if aw_type is None:\n                return\n            if not self.check_subtype(\n                aw_type, supertype, context, msg=message_registry.INCOMPATIBLE_TYPES\n            ):\n                return\n        self.msg.possible_missing_await(context, code)\n\n    def named_type(self, name: str) -> Instance:\n        \"\"\"Return an instance type with given name and implicit Any type args.\n\n        For example, named_type('builtins.object') produces the 'object' type.\n        \"\"\"\n        if name == \"builtins.str\":\n            if instance_cache.str_type is None:\n                instance_cache.str_type = self._named_type(name)\n            return instance_cache.str_type\n        if name == \"builtins.function\":\n            if instance_cache.function_type is None:\n                instance_cache.function_type = self._named_type(name)\n            return instance_cache.function_type\n        if name == \"builtins.int\":\n            if instance_cache.int_type is None:\n                instance_cache.int_type = self._named_type(name)\n            return instance_cache.int_type\n        if name == \"builtins.bool\":\n            if instance_cache.bool_type is None:\n                instance_cache.bool_type = self._named_type(name)\n            return instance_cache.bool_type\n        if name == \"builtins.object\":\n            if instance_cache.object_type is None:\n                instance_cache.object_type = self._named_type(name)\n            return instance_cache.object_type\n        return self._named_type(name)\n\n    def _named_type(self, name: str) -> Instance:\n        # Assume that the name refers to a type.\n        sym = self.lookup_qualified(name)\n        node = sym.node\n        if isinstance(node, TypeAlias):\n            assert isinstance(node.target, Instance)  # type: ignore[misc]\n            node = node.target.type\n        assert isinstance(node, TypeInfo), node\n        any_type = AnyType(TypeOfAny.from_omitted_generics)\n        return Instance(node, [any_type] * len(node.defn.type_vars))\n\n    def named_generic_type(self, name: str, args: list[Type]) -> Instance:\n        \"\"\"Return an instance with the given name and type arguments.\n\n        Assume that the number of arguments is correct.  Assume that\n        the name refers to a compatible generic type.\n        \"\"\"\n        info = self.lookup_typeinfo(name)\n        args = [remove_instance_last_known_values(arg) for arg in args]\n        # TODO: assert len(args) == len(info.defn.type_vars)\n        return Instance(info, args)\n\n    def lookup_typeinfo(self, fullname: str) -> TypeInfo:\n        # Assume that the name refers to a class.\n        sym = self.lookup_qualified(fullname)\n        node = sym.node\n        assert isinstance(node, TypeInfo), node\n        return node\n\n    def type_type(self) -> Instance:\n        \"\"\"Return instance type 'type'.\"\"\"\n        return self.named_type(\"builtins.type\")\n\n    def str_type(self) -> Instance:\n        \"\"\"Return instance type 'str'.\"\"\"\n        return self.named_type(\"builtins.str\")\n\n    def store_type(self, node: Expression, typ: Type) -> None:\n        \"\"\"Store the type of a node in the type map.\"\"\"\n        self._type_maps[-1][node] = typ\n\n    def has_type(self, node: Expression) -> bool:\n        return any(node in m for m in reversed(self._type_maps))\n\n    def lookup_type_or_none(self, node: Expression) -> Type | None:\n        for m in reversed(self._type_maps):\n            if node in m:\n                return m[node]\n        return None\n\n    def lookup_type(self, node: Expression) -> Type:\n        for m in reversed(self._type_maps):\n            t = m.get(node)\n            if t is not None:\n                return t\n        raise KeyError(node)\n\n    def store_types(self, d: dict[Expression, Type]) -> None:\n        self._type_maps[-1].update(d)\n\n    def in_checked_function(self) -> bool:\n        \"\"\"Should we type-check the current function?\n\n        - Yes if --check-untyped-defs is set.\n        - Yes outside functions.\n        - Yes in annotated functions.\n        - No otherwise.\n        \"\"\"\n        return (\n            self.options.check_untyped_defs or not self.dynamic_funcs or not self.dynamic_funcs[-1]\n        )\n\n    def lookup(self, name: str) -> SymbolTableNode:\n        \"\"\"Look up a definition from the symbol table with the given name.\"\"\"\n        if name in self.globals:\n            return self.globals[name]\n        else:\n            b = self.globals.get(\"__builtins__\", None)\n            if b:\n                assert isinstance(b.node, MypyFile)\n                table = b.node.names\n                if name in table:\n                    return table[name]\n            raise KeyError(f\"Failed lookup: {name}\")\n\n    def lookup_qualified(self, name: str) -> SymbolTableNode:\n        if \".\" not in name:\n            return self.lookup(name)\n        else:\n            parts = name.split(\".\")\n            n = self.modules[parts[0]]\n            for i in range(1, len(parts) - 1):\n                sym = n.names.get(parts[i])\n                assert sym is not None, \"Internal error: attempted lookup of unknown name\"\n                assert isinstance(sym.node, MypyFile)\n                n = sym.node\n            last = parts[-1]\n            if last in n.names:\n                return n.names[last]\n            elif len(parts) == 2 and parts[0] in (\"builtins\", \"typing\"):\n                fullname = \".\".join(parts)\n                if fullname in SUGGESTED_TEST_FIXTURES:\n                    suggestion = \", e.g. add '[{} fixtures/{}]' to your test\".format(\n                        parts[0], SUGGESTED_TEST_FIXTURES[fullname]\n                    )\n                else:\n                    suggestion = \"\"\n                raise KeyError(\n                    \"Could not find builtin symbol '{}' (If you are running a \"\n                    \"test case, use a fixture that \"\n                    \"defines this symbol{})\".format(last, suggestion)\n                )\n            else:\n                msg = \"Failed qualified lookup: '{}' (fullname = '{}').\"\n                raise KeyError(msg.format(last, name))\n\n    @contextmanager\n    def enter_partial_types(\n        self, *, is_function: bool = False, is_class: bool = False\n    ) -> Iterator[None]:\n        \"\"\"Enter a new scope for collecting partial types.\n\n        Also report errors for (some) variables which still have partial\n        types, i.e. we couldn't infer a complete type.\n        \"\"\"\n        is_local = (self.partial_types and self.partial_types[-1].is_local) or is_function\n        self.partial_types.append(PartialTypeScope({}, is_function, is_local))\n        yield\n\n        # Don't complain about not being able to infer partials if it is\n        # at the toplevel (with allow_untyped_globals) or if it is in an\n        # untyped function being checked with check_untyped_defs.\n        permissive = (self.options.allow_untyped_globals and not is_local) or (\n            self.options.check_untyped_defs and self.dynamic_funcs and self.dynamic_funcs[-1]\n        )\n\n        partial_types, _, _ = self.partial_types.pop()\n        if not self.current_node_deferred:\n            for var, context in partial_types.items():\n                if isinstance(var.type, PartialType) and var.type.type is None and not permissive:\n                    var.type = NoneType()\n                else:\n                    if var not in self.partial_reported and not permissive:\n                        self.msg.need_annotation_for_var(var, context, self.options)\n                        self.partial_reported.add(var)\n                    if var.type:\n                        fixed = fixup_partial_type(var.type)\n                        var.invalid_partial_type = fixed != var.type\n                        var.type = fixed\n\n    def handle_partial_var_type(\n        self, typ: PartialType, is_lvalue: bool, node: Var, context: Context\n    ) -> Type:\n        \"\"\"Handle a reference to a partial type through a var.\n\n        (Used by checkexpr and checkmember.)\n        \"\"\"\n        in_scope, is_local, partial_types = self.find_partial_types_in_all_scopes(node)\n        if typ.type is None and in_scope:\n            # 'None' partial type. It has a well-defined type. In an lvalue context\n            # we want to preserve the knowledge of it being a partial type.\n            if not is_lvalue:\n                return NoneType()\n            else:\n                return typ\n        else:\n            if partial_types is not None and not self.current_node_deferred:\n                if in_scope:\n                    context = partial_types[node]\n                    if is_local or not self.options.allow_untyped_globals:\n                        self.msg.need_annotation_for_var(node, context, self.options)\n                        self.partial_reported.add(node)\n                else:\n                    # Defer the node -- we might get a better type in the outer scope\n                    self.handle_cannot_determine_type(node.name, context)\n            return fixup_partial_type(typ)\n\n    def is_defined_in_base_class(self, var: Var) -> bool:\n        if not var.info:\n            return False\n        return var.info.fallback_to_any or any(\n            base.get(var.name) is not None for base in var.info.mro[1:]\n        )\n\n    def find_partial_types(self, var: Var) -> dict[Var, Context] | None:\n        \"\"\"Look for an active partial type scope containing variable.\n\n        A scope is active if assignments in the current context can refine a partial\n        type originally defined in the scope. This is affected by the local_partial_types\n        configuration option.\n        \"\"\"\n        in_scope, _, partial_types = self.find_partial_types_in_all_scopes(var)\n        if in_scope:\n            return partial_types\n        return None\n\n    def find_partial_types_in_all_scopes(\n        self, var: Var\n    ) -> tuple[bool, bool, dict[Var, Context] | None]:\n        \"\"\"Look for partial type scope containing variable.\n\n        Return tuple (is the scope active, is the scope a local scope, scope).\n        \"\"\"\n        for scope in reversed(self.partial_types):\n            if var in scope.map:\n                # All scopes within the outermost function are active. Scopes out of\n                # the outermost function are inactive to allow local reasoning (important\n                # for fine-grained incremental mode).\n                disallow_other_scopes = self.options.local_partial_types\n\n                # There are two exceptions:\n                if isinstance(var.type, PartialType) and var.type.type is not None and var.info:\n                    # We always prohibit non-None partial types at class scope\n                    # for historical reasons.\n                    disallow_other_scopes = True\n                if isinstance(var.type, PartialType) and var.type.type is None:\n                    # We always allow None partial types, since this is a common use case.\n                    # It is special-cased in fine-grained incremental mode.\n                    disallow_other_scopes = False\n\n                scope_active = (\n                    not disallow_other_scopes or scope.is_local == self.partial_types[-1].is_local\n                )\n                return scope_active, scope.is_local, scope.map\n        return False, False, None\n\n    def temp_node(self, t: Type, context: Context | None = None) -> TempNode:\n        \"\"\"Create a temporary node with the given, fixed type.\"\"\"\n        return TempNode(t, context=context)\n\n    def fail(\n        self, msg: str | ErrorMessage, context: Context, *, code: ErrorCode | None = None\n    ) -> ErrorInfo:\n        \"\"\"Produce an error message.\"\"\"\n        if isinstance(msg, ErrorMessage):\n            return self.msg.fail(msg.value, context, code=msg.code)\n        return self.msg.fail(msg, context, code=code)\n\n    def note(\n        self,\n        msg: str | ErrorMessage,\n        context: Context,\n        offset: int = 0,\n        *,\n        code: ErrorCode | None = None,\n    ) -> None:\n        \"\"\"Produce a note.\"\"\"\n        if isinstance(msg, ErrorMessage):\n            self.msg.note(msg.value, context, code=msg.code)\n            return\n        self.msg.note(msg, context, offset=offset, code=code)\n\n    def iterable_item_type(self, it: ProperType, context: Context) -> Type:\n        if isinstance(it, Instance):\n            iterable = map_instance_to_supertype(it, self.lookup_typeinfo(\"typing.Iterable\"))\n            item_type = iterable.args[0]\n            if not isinstance(get_proper_type(item_type), AnyType):\n                # This relies on 'map_instance_to_supertype' returning 'Iterable[Any]'\n                # in case there is no explicit base class.\n                return item_type\n        # Try also structural typing.\n        return self.analyze_iterable_item_type_without_expression(it, context)[1]\n\n    def function_type(self, func: FuncBase) -> FunctionLike:\n        return function_type(func, self.named_type(\"builtins.function\"))\n\n    def push_type_map(self, type_map: TypeMap, *, from_assignment: bool = True) -> None:\n        if is_unreachable_map(type_map):\n            self.binder.unreachable()\n        else:\n            for expr, type in type_map.items():\n                self.binder.put(expr, type, from_assignment=from_assignment)\n\n    def infer_issubclass_maps(self, node: CallExpr, expr: Expression) -> tuple[TypeMap, TypeMap]:\n        \"\"\"Infer type restrictions for an expression in issubclass call.\"\"\"\n        vartype = self.lookup_type(expr)\n        type = self.get_isinstance_type(node.args[1])\n        if isinstance(vartype, TypeVarType):\n            vartype = vartype.upper_bound\n        vartype = get_proper_type(vartype)\n        if isinstance(vartype, UnionType):\n            union_list = []\n            for t in get_proper_types(vartype.items):\n                if isinstance(t, TypeType):\n                    union_list.append(t.item)\n                else:\n                    # This is an error that should be reported earlier\n                    # if we reach here, we refuse to do any type inference.\n                    return {}, {}\n            vartype = UnionType(union_list)\n        elif isinstance(vartype, TypeType):\n            vartype = vartype.item\n        elif isinstance(vartype, Instance) and vartype.type.is_metaclass():\n            vartype = self.named_type(\"builtins.object\")\n        else:\n            # Any other object whose type we don't know precisely\n            # for example, Any or a custom metaclass.\n            return {}, {}  # unknown type\n        yes_type, no_type = self.conditional_types_with_intersection(vartype, type, expr)\n        yes_map, no_map = conditional_types_to_typemaps(expr, yes_type, no_type)\n        yes_map, no_map = map(convert_to_typetype, (yes_map, no_map))\n        return yes_map, no_map\n\n    @overload\n    def conditional_types_with_intersection(\n        self,\n        expr_type: Type,\n        type_ranges: list[TypeRange] | None,\n        ctx: Context,\n        default: None = None,\n        *,\n        consider_runtime_isinstance: bool = True,\n    ) -> tuple[Type | None, Type | None]: ...\n\n    @overload\n    def conditional_types_with_intersection(\n        self,\n        expr_type: Type,\n        type_ranges: list[TypeRange] | None,\n        ctx: Context,\n        default: Type,\n        *,\n        consider_runtime_isinstance: bool = True,\n    ) -> tuple[Type, Type]: ...\n\n    def conditional_types_with_intersection(\n        self,\n        expr_type: Type,\n        type_ranges: list[TypeRange] | None,\n        ctx: Context,\n        default: Type | None = None,\n        *,\n        consider_runtime_isinstance: bool = True,\n    ) -> tuple[Type | None, Type | None]:\n        initial_types = conditional_types(\n            expr_type,\n            type_ranges,\n            default,\n            consider_runtime_isinstance=consider_runtime_isinstance,\n        )\n        # For some reason, doing \"yes_map, no_map = conditional_types_to_typemaps(...)\"\n        # doesn't work: mypyc will decide that 'yes_map' is of type None if we try.\n        yes_type: Type | None = initial_types[0]\n        no_type: Type | None = initial_types[1]\n\n        if not isinstance(get_proper_type(yes_type), UninhabitedType) or type_ranges is None:\n            return yes_type, no_type\n\n        # If conditional_types was unable to successfully narrow the expr_type\n        # using the type_ranges and concluded if-branch is unreachable, we try\n        # computing it again using a different algorithm that tries to generate\n        # an ad-hoc intersection between the expr_type and the type_ranges.\n        proper_type = get_proper_type(expr_type)\n        if isinstance(proper_type, UnionType):\n            possible_expr_types = get_proper_types(proper_type.relevant_items())\n        else:\n            possible_expr_types = [proper_type]\n\n        possible_target_types = []\n        for tr in type_ranges:\n            item = get_proper_type(tr.item)\n            if isinstance(item, (Instance, NoneType)):\n                possible_target_types.append(item)\n        if not possible_target_types:\n            return yes_type, no_type\n\n        out = []\n        errors: list[tuple[str, str]] = []\n        for v in possible_expr_types:\n            if not isinstance(v, Instance):\n                return yes_type, no_type\n            for t in possible_target_types:\n                if isinstance(t, NoneType):\n                    errors.append((f'\"{v.type.name}\" and \"NoneType\"', '\"NoneType\" is final'))\n                    continue\n                intersection = self.intersect_instances((v, t), errors)\n                if intersection is None:\n                    continue\n                out.append(intersection)\n        if not out:\n            # Only report errors if no element in the union worked.\n            if self.should_report_unreachable_issues():\n                for types, reason in errors:\n                    self.msg.impossible_intersection(types, reason, ctx)\n            return UninhabitedType(), expr_type\n        new_yes_type = make_simplified_union(out)\n        return new_yes_type, expr_type\n\n    def is_writable_attribute(self, node: Node) -> bool:\n        \"\"\"Check if an attribute is writable\"\"\"\n        if isinstance(node, Var):\n            if node.is_property and not node.is_settable_property:\n                return False\n            return True\n        elif isinstance(node, OverloadedFuncDef) and node.is_property:\n            first_item = node.items[0]\n            assert isinstance(first_item, Decorator)\n            return first_item.var.is_settable_property\n        return False\n\n    def get_isinstance_type(\n        self, expr: Expression, flatten_tuples: bool = True\n    ) -> list[TypeRange] | None:\n        \"\"\"Get the type(s) resulting from an isinstance check.\n\n        Returns an empty list for isinstance(x, ()).\n        \"\"\"\n        if isinstance(expr, OpExpr) and expr.op == \"|\":\n            left: list[TypeRange] | None\n            right: list[TypeRange] | None\n            if is_literal_none(expr.left):\n                left = [TypeRange(NoneType(), is_upper_bound=False)]\n            else:\n                left = self.get_isinstance_type(expr.left, flatten_tuples=False)\n            if is_literal_none(expr.right):\n                right = [TypeRange(NoneType(), is_upper_bound=False)]\n            else:\n                right = self.get_isinstance_type(expr.right, flatten_tuples=False)\n            if left is None or right is None:\n                return None\n            return left + right\n\n        if flatten_tuples:\n            type_ranges = []\n            for typ in flatten_types_if_tuple(self.lookup_type(expr)):\n                type_range = self.get_type_range_of_type(typ)\n                if type_range is None:\n                    return None\n                type_ranges.append(type_range)\n            return type_ranges\n\n        else:\n            type_range = self.get_type_range_of_type(self.lookup_type(expr))\n            if type_range is None:\n                return None\n            return [type_range]\n\n    def get_type_range_of_type(self, typ: Type) -> TypeRange | None:\n        typ = get_proper_type(typ)\n        if isinstance(typ, TypeVarType):\n            typ = get_proper_type(typ.upper_bound)\n\n        if isinstance(typ, UnionType):\n            type_ranges = [self.get_type_range_of_type(item) for item in typ.items]\n            item = make_simplified_union([t.item for t in type_ranges if t is not None])\n            return TypeRange(item, is_upper_bound=True)\n        if isinstance(typ, FunctionLike) and typ.is_type_obj():\n            # If a type is generic, `isinstance` can only narrow its variables to Any.\n            any_parameterized = fill_typevars_with_any(typ.type_object())\n            # Tuples may have unattended type variables among their items\n            if isinstance(any_parameterized, TupleType):\n                erased_type = erase_typevars(any_parameterized)\n            else:\n                erased_type = any_parameterized\n            return TypeRange(erased_type, is_upper_bound=False)\n        if isinstance(typ, TypeType):\n            # Type[A] means \"any type that is a subtype of A\" rather than \"precisely type A\"\n            # we indicate this by setting is_upper_bound flag\n            is_upper_bound = True\n            if isinstance(typ.item, NoneType):\n                # except for Type[None], because \"'NoneType' is not an acceptable base type\"\n                is_upper_bound = False\n            if isinstance(typ.item, Instance) and typ.item.type.is_final:\n                is_upper_bound = False\n            return TypeRange(typ.item, is_upper_bound=is_upper_bound)\n        if isinstance(typ, AnyType):\n            return TypeRange(typ, is_upper_bound=False)\n        if isinstance(typ, Instance) and typ.type.fullname == \"builtins.type\":\n            object_type = Instance(typ.type.mro[-1], [])\n            return TypeRange(object_type, is_upper_bound=True)\n        if isinstance(typ, Instance) and typ.type.fullname == \"types.UnionType\" and typ.args:\n            return TypeRange(UnionType(typ.args), is_upper_bound=False)\n        if isinstance(typ, Instance) and typ.type.fullname == \"typing._SpecialForm\":\n            # This is probably an alias to a Union object. We don't have the args here so we can't\n            # conclude anything\n            return None\n        if not is_subtype(self.named_type(\"builtins.type\"), typ):\n            # We saw something, but it couldn't possibly be valid\n            return TypeRange(UninhabitedType(), is_upper_bound=False)\n\n        # This is e.g. a variable of type object, so we can't conclude anything\n        return None\n\n    def is_literal_enum(self, n: Expression) -> bool:\n        \"\"\"Returns true if this expression (with the given type context) is an Enum literal.\n\n        For example, if we had an enum:\n\n            class Foo(Enum):\n                A = 1\n                B = 2\n\n        ...and if the expression 'Foo' referred to that enum within the current type context,\n        then the expression 'Foo.A' would be a literal enum. However, if we did 'a = Foo.A',\n        then the variable 'a' would *not* be a literal enum.\n\n        We occasionally special-case expressions like 'Foo.A' and treat them as a single primitive\n        unit for the same reasons we sometimes treat 'True', 'False', or 'None' as a single\n        primitive unit.\n        \"\"\"\n        if not isinstance(n, MemberExpr) or not isinstance(n.expr, NameExpr):\n            return False\n\n        parent_type = self.lookup_type_or_none(n.expr)\n        member_type = self.lookup_type_or_none(n)\n        if member_type is None or parent_type is None:\n            return False\n\n        parent_type = get_proper_type(parent_type)\n        member_type = get_proper_type(coerce_to_literal(member_type))\n        if not isinstance(parent_type, FunctionLike) or not isinstance(member_type, LiteralType):\n            return False\n\n        if not parent_type.is_type_obj():\n            return False\n\n        return (\n            member_type.is_enum_literal()\n            and member_type.fallback.type == parent_type.type_object()\n        )\n\n    def add_any_attribute_to_type(self, typ: Type, name: str) -> Type:\n        \"\"\"Inject an extra attribute with Any type using fallbacks.\"\"\"\n        orig_typ = typ\n        typ = get_proper_type(typ)\n        any_type = AnyType(TypeOfAny.unannotated)\n        if isinstance(typ, Instance):\n            result = typ.copy_with_extra_attr(name, any_type)\n            # For instances, we erase the possible module name, so that restrictions\n            # become anonymous types.ModuleType instances, allowing hasattr() to\n            # have effect on modules.\n            assert result.extra_attrs is not None\n            result.extra_attrs.mod_name = None\n            return result\n        if isinstance(typ, TupleType):\n            fallback = typ.partial_fallback.copy_with_extra_attr(name, any_type)\n            return typ.copy_modified(fallback=fallback)\n        if isinstance(typ, CallableType):\n            fallback = typ.fallback.copy_with_extra_attr(name, any_type)\n            return typ.copy_modified(fallback=fallback)\n        if isinstance(typ, TypeType) and isinstance(typ.item, Instance):\n            return TypeType.make_normalized(\n                self.add_any_attribute_to_type(typ.item, name), is_type_form=typ.is_type_form\n            )\n        if isinstance(typ, TypeVarType):\n            return typ.copy_modified(\n                upper_bound=self.add_any_attribute_to_type(typ.upper_bound, name),\n                values=[self.add_any_attribute_to_type(v, name) for v in typ.values],\n            )\n        if isinstance(typ, UnionType):\n            with_attr, without_attr = self.partition_union_by_attr(typ, name)\n            return make_simplified_union(\n                with_attr + [self.add_any_attribute_to_type(typ, name) for typ in without_attr]\n            )\n        return orig_typ\n\n    def hasattr_type_maps(\n        self, expr: Expression, source_type: Type, name: str\n    ) -> tuple[TypeMap, TypeMap]:\n        \"\"\"Simple support for hasattr() checks.\n\n        Essentially the logic is following:\n            * In the if branch, keep types that already has a valid attribute as is,\n              for other inject an attribute with `Any` type.\n            * In the else branch, remove types that already have a valid attribute,\n              while keeping the rest.\n        \"\"\"\n        if self.has_valid_attribute(source_type, name):\n            return {expr: source_type}, {}\n\n        source_type = get_proper_type(source_type)\n        if isinstance(source_type, UnionType):\n            _, without_attr = self.partition_union_by_attr(source_type, name)\n            yes_map = {expr: self.add_any_attribute_to_type(source_type, name)}\n            return yes_map, {expr: make_simplified_union(without_attr)}\n\n        type_with_attr = self.add_any_attribute_to_type(source_type, name)\n        if type_with_attr != source_type:\n            return {expr: type_with_attr}, {}\n        return {}, {}\n\n    def partition_union_by_attr(\n        self, source_type: UnionType, name: str\n    ) -> tuple[list[Type], list[Type]]:\n        with_attr = []\n        without_attr = []\n        for item in source_type.items:\n            if self.has_valid_attribute(item, name):\n                with_attr.append(item)\n            else:\n                without_attr.append(item)\n        return with_attr, without_attr\n\n    def has_valid_attribute(self, typ: Type, name: str) -> bool:\n        p_typ = get_proper_type(typ)\n        if isinstance(p_typ, AnyType):\n            return False\n        if isinstance(p_typ, Instance) and p_typ.extra_attrs and p_typ.extra_attrs.mod_name:\n            # Presence of module_symbol_table means this check will skip ModuleType.__getattr__\n            module_symbol_table = p_typ.type.names\n        else:\n            module_symbol_table = None\n        with self.msg.filter_errors() as watcher:\n            analyze_member_access(\n                name,\n                typ,\n                TempNode(AnyType(TypeOfAny.special_form)),\n                is_lvalue=False,\n                is_super=False,\n                is_operator=False,\n                original_type=typ,\n                chk=self,\n                # This is not a real attribute lookup so don't mess with deferring nodes.\n                no_deferral=True,\n                module_symbol_table=module_symbol_table,\n            )\n        return not watcher.has_new_errors()\n\n    def get_expression_type(self, node: Expression, type_context: Type | None = None) -> Type:\n        return self.expr_checker.accept(node, type_context=type_context)\n\n    def is_defined_in_stub(self, typ: Instance, /) -> bool:\n        return self.modules[typ.type.module_name].is_stub\n\n    def check_deprecated(self, node: Node | None, context: Context) -> None:\n        \"\"\"Warn if deprecated and not directly imported with a `from` statement.\"\"\"\n        if isinstance(node, Decorator):\n            node = node.func\n        if isinstance(node, (FuncDef, OverloadedFuncDef, TypeInfo)) and (\n            node.deprecated is not None\n        ):\n            for imp in self.tree.imports:\n                if isinstance(imp, ImportFrom) and any(node.name == n[0] for n in imp.names):\n                    break\n            else:\n                self.warn_deprecated(node, context)\n\n    def warn_deprecated(self, node: Node | None, context: Context) -> None:\n        \"\"\"Warn if deprecated.\"\"\"\n        if isinstance(node, Decorator):\n            node = node.func\n        if (\n            isinstance(node, (FuncDef, OverloadedFuncDef, TypeInfo))\n            and (deprecated := node.deprecated) is not None\n            and not self.is_typeshed_stub\n            and not any(\n                node.fullname == p or node.fullname.startswith(f\"{p}.\")\n                for p in self.options.deprecated_calls_exclude\n            )\n        ):\n            warn = self.msg.note if self.options.report_deprecated_as_note else self.msg.fail\n            warn(deprecated, context, code=codes.DEPRECATED)\n\n    def new_unique_dummy_name(self, namespace: str) -> str:\n        \"\"\"Generate a name that is guaranteed to be unique for this TypeChecker instance.\"\"\"\n        name = f\"dummy-{namespace}-{self._unique_id}\"\n        self._unique_id += 1\n        return name\n\n    # leafs\n\n    def visit_pass_stmt(self, o: PassStmt, /) -> None:\n        return None\n\n    def visit_nonlocal_decl(self, o: NonlocalDecl, /) -> None:\n        return None\n\n    def visit_global_decl(self, o: GlobalDecl, /) -> None:\n        return None\n\n\nclass TypeCheckerAsSemanticAnalyzer(SemanticAnalyzerCoreInterface):\n    \"\"\"\n    Adapts TypeChecker to the SemanticAnalyzerCoreInterface,\n    allowing most type expressions to be parsed during the TypeChecker pass.\n\n    See ExpressionChecker.try_parse_as_type_expression() to understand how this\n    class is used.\n    \"\"\"\n\n    _chk: TypeChecker\n    _names: dict[str, SymbolTableNode]\n    did_fail: bool\n\n    def __init__(self, chk: TypeChecker, names: dict[str, SymbolTableNode]) -> None:\n        self._chk = chk\n        self._names = names\n        self.did_fail = False\n\n    def lookup_qualified(\n        self, name: str, ctx: Context, suppress_errors: bool = False\n    ) -> SymbolTableNode | None:\n        sym = self._names.get(name)\n        # All names being looked up should have been previously gathered,\n        # even if the related SymbolTableNode does not refer to a valid SymbolNode\n        assert sym is not None, name\n        return sym\n\n    def lookup_fully_qualified(self, fullname: str, /) -> SymbolTableNode:\n        ret = self.lookup_fully_qualified_or_none(fullname)\n        assert ret is not None, fullname\n        return ret\n\n    def lookup_fully_qualified_or_none(self, fullname: str, /) -> SymbolTableNode | None:\n        try:\n            return self._chk.lookup_qualified(fullname)\n        except KeyError:\n            return None\n\n    def fail(\n        self,\n        msg: str,\n        ctx: Context,\n        serious: bool = False,\n        *,\n        blocker: bool = False,\n        code: ErrorCode | None = None,\n    ) -> None:\n        self.did_fail = True\n\n    def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:\n        pass\n\n    def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool:\n        if feature not in self._chk.options.enable_incomplete_feature:\n            self.fail(\"__ignored__\", ctx)\n            return False\n        return True\n\n    def record_incomplete_ref(self) -> None:\n        pass\n\n    def defer(self, debug_context: Context | None = None, force_progress: bool = False) -> None:\n        pass\n\n    def is_incomplete_namespace(self, fullname: str) -> bool:\n        return False\n\n    @property\n    def final_iteration(self) -> bool:\n        return True\n\n    def is_future_flag_set(self, flag: str) -> bool:\n        return self._chk.tree.is_future_flag_set(flag)\n\n    @property\n    def is_stub_file(self) -> bool:\n        return self._chk.tree.is_stub\n\n    def is_func_scope(self) -> bool:\n        # Return arbitrary value.\n        #\n        # This method is currently only used to decide whether to pair\n        # a fail() message with a note() message or not. Both of those\n        # message types are ignored.\n        return False\n\n    @property\n    def type(self) -> TypeInfo | None:\n        return self._chk.type\n\n\nclass CollectArgTypeVarTypes(TypeTraverserVisitor):\n    \"\"\"Collects the non-nested argument types in a set.\"\"\"\n\n    def __init__(self) -> None:\n        self.arg_types: set[TypeVarType] = set()\n\n    def visit_type_var(self, t: TypeVarType) -> None:\n        self.arg_types.add(t)\n\n\n@overload\ndef conditional_types(\n    current_type: Type,\n    proposed_type_ranges: list[TypeRange] | None,\n    default: None = None,\n    *,\n    consider_runtime_isinstance: bool = True,\n    from_equality: bool = False,\n) -> tuple[Type | None, Type | None]: ...\n\n\n@overload\ndef conditional_types(\n    current_type: Type,\n    proposed_type_ranges: list[TypeRange] | None,\n    default: Type,\n    *,\n    consider_runtime_isinstance: bool = True,\n    from_equality: bool = False,\n) -> tuple[Type, Type]: ...\n\n\ndef conditional_types(\n    current_type: Type,\n    proposed_type_ranges: list[TypeRange] | None,\n    default: Type | None = None,\n    *,\n    consider_runtime_isinstance: bool = True,\n    from_equality: bool = False,\n) -> tuple[Type | None, Type | None]:\n    \"\"\"Takes in the current type and a proposed type of an expression.\n\n    Returns a 2-tuple:\n        The first element is the proposed type, if the expression can be the proposed type.\n            (or default, if default is set and the expression is a subtype of the proposed type).\n        The second element is the type it would hold if it was not the proposed type, if any.\n            (or default, if default is set and the expression is not a subtype of the proposed type).\n\n        UninhabitedType means unreachable.\n        None means no new information can be inferred.\n    \"\"\"\n    if proposed_type_ranges is None:\n        # An isinstance check, but we don't understand the type\n        return current_type, default\n\n    if not proposed_type_ranges:\n        # This is the case for `if isinstance(x, ())` which always returns False.\n        return UninhabitedType(), default\n\n    if len(proposed_type_ranges) == 1:\n        # expand e.g. bool -> Literal[True] | Literal[False]\n        target = proposed_type_ranges[0].item\n        target = get_proper_type(target)\n        if isinstance(target, LiteralType) and (\n            target.is_enum_literal() or isinstance(target.value, bool)\n        ):\n            enum_name = target.fallback.type.fullname\n            current_type = try_expanding_sum_type_to_union(current_type, enum_name)\n\n    proposed_type: Type\n    remaining_type: Type\n\n    proper_type = get_proper_type(current_type)\n    # factorize over union types: isinstance(A|B, C) -> yes = A_yes | B_yes\n    if isinstance(proper_type, UnionType):\n        yes_items: list[Type] = []\n        no_items: list[Type] = []\n        for union_item in proper_type.items:\n            yes_type, no_type = conditional_types(\n                union_item,\n                proposed_type_ranges,\n                default=union_item,\n                consider_runtime_isinstance=consider_runtime_isinstance,\n                from_equality=from_equality,\n            )\n            yes_items.append(yes_type)\n            no_items.append(no_type)\n\n        proposed_type = make_simplified_union(yes_items)\n        remaining_type = make_simplified_union(no_items)\n        return proposed_type, remaining_type\n\n    proposed_type = make_simplified_union([type_range.item for type_range in proposed_type_ranges])\n    items = proposed_type.items if isinstance(proposed_type, UnionType) else [proposed_type]\n    for i in range(len(items)):\n        item = get_proper_type(items[i])\n        # Avoid ever narrowing to a NewType. The principle is values of NewType should only be\n        # produce by explicit wrapping\n        while isinstance(item, Instance) and item.type.is_newtype:\n            item = item.type.bases[0]\n        items[i] = item\n    proposed_type = get_proper_type(UnionType.make_union(items))\n\n    if isinstance(proper_type, AnyType):\n        return proposed_type, current_type\n    if isinstance(proposed_type, AnyType):\n        # We don't really know much about the proposed type, so we shouldn't\n        # attempt to narrow anything. Instead, we broaden the expr to Any to\n        # avoid false positives\n        return proposed_type, default\n    if not any(type_range.is_upper_bound for type_range in proposed_type_ranges):\n        # concrete subtype\n        if is_proper_subtype(current_type, proposed_type, ignore_promotions=True):\n            return default, UninhabitedType()\n\n        # structural subtypes\n        if (\n            isinstance(proposed_type, CallableType)\n            or (isinstance(proposed_type, Instance) and proposed_type.type.is_protocol)\n        ) and is_subtype(current_type, proposed_type, ignore_promotions=True):\n            # Note: It's possible that current_type=`Any | Proto` while proposed_type=`Proto`\n            #  so we cannot return `Never` for the else branch\n            remainder = restrict_subtype_away(\n                current_type,\n                default if default is not None else proposed_type,\n                consider_runtime_isinstance=consider_runtime_isinstance,\n            )\n            return default, remainder\n\n    if from_equality:\n        # We erase generic args because values with different generic types can compare equal\n        # For instance, cast(list[str], []) and cast(list[int], [])\n        proposed_type = shallow_erase_type_for_equality(proposed_type)\n        if not is_overlapping_types(current_type, proposed_type, ignore_promotions=False):\n            # Equality narrowing is one of the places at runtime where subtyping with promotion\n            # does happen to match runtime semantics\n            # Expression is never of any type in proposed_type_ranges\n            return UninhabitedType(), default\n        if not is_overlapping_types(current_type, proposed_type, ignore_promotions=True):\n            return default, default\n    else:\n        if not is_overlapping_types(current_type, proposed_type, ignore_promotions=True):\n            # Expression is never of any type in proposed_type_ranges\n            return UninhabitedType(), default\n\n    # we can only restrict when the type is precise, not bounded\n    proposed_precise_type = UnionType.make_union(\n        [type_range.item for type_range in proposed_type_ranges if not type_range.is_upper_bound]\n    )\n    remaining_type = restrict_subtype_away(\n        current_type,\n        proposed_precise_type,\n        consider_runtime_isinstance=consider_runtime_isinstance,\n    )\n    return proposed_type, remaining_type\n\n\ndef conditional_types_to_typemaps(\n    expr: Expression, yes_type: Type | None, no_type: Type | None\n) -> tuple[TypeMap, TypeMap]:\n    expr = collapse_walrus(expr)\n\n    yes_map = {} if yes_type is None else {expr: yes_type}\n    no_map = {} if no_type is None else {expr: no_type}\n    return yes_map, no_map\n\n\ndef gen_unique_name(base: str, table: SymbolTable) -> str:\n    \"\"\"Generate a name that does not appear in table by appending numbers to base.\"\"\"\n    if base not in table:\n        return base\n    i = 1\n    while base + str(i) in table:\n        i += 1\n    return base + str(i)\n\n\ndef is_true_literal(n: Expression) -> bool:\n    \"\"\"Returns true if this expression is the 'True' literal/keyword.\"\"\"\n    return refers_to_fullname(n, \"builtins.True\") or isinstance(n, IntExpr) and n.value != 0\n\n\ndef is_false_literal(n: Expression) -> bool:\n    \"\"\"Returns true if this expression is the 'False' literal/keyword.\"\"\"\n    return refers_to_fullname(n, \"builtins.False\") or isinstance(n, IntExpr) and n.value == 0\n\n\ndef is_literal_none(n: Expression) -> bool:\n    \"\"\"Returns true if this expression is the 'None' literal/keyword.\"\"\"\n    return isinstance(n, NameExpr) and n.fullname == \"builtins.None\"\n\n\ndef is_literal_not_implemented(n: Expression | None) -> bool:\n    return isinstance(n, NameExpr) and n.fullname == \"builtins.NotImplemented\"\n\n\ndef _is_empty_generator_function(func: FuncItem) -> bool:\n    \"\"\"\n    Checks whether a function's body is 'return; yield' (the yield being added only\n    to promote the function into a generator function).\n    \"\"\"\n    body = func.body.body\n    return (\n        len(body) == 2\n        and isinstance(ret_stmt := body[0], ReturnStmt)\n        and (ret_stmt.expr is None or is_literal_none(ret_stmt.expr))\n        and isinstance(expr_stmt := body[1], ExpressionStmt)\n        and isinstance(yield_expr := expr_stmt.expr, YieldExpr)\n        and (yield_expr.expr is None or is_literal_none(yield_expr.expr))\n    )\n\n\ndef builtin_item_type(tp: Type) -> Type | None:\n    \"\"\"Get the item type of a builtin container.\n\n    If 'tp' is not one of the built containers (these includes NamedTuple and TypedDict)\n    or if the container is not parameterized (like List or List[Any])\n    return None. This function is used to narrow optional types in situations like this:\n\n        x: Optional[int]\n        if x in (1, 2, 3):\n            x + 42  # OK\n\n    Note: this is only OK for built-in containers, where we know the behavior\n    of __contains__.\n    \"\"\"\n    tp = get_proper_type(tp)\n\n    if isinstance(tp, Instance):\n        if tp.type.fullname in [\n            \"builtins.list\",\n            \"builtins.tuple\",\n            \"builtins.dict\",\n            \"builtins.set\",\n            \"builtins.frozenset\",\n            \"_collections_abc.dict_keys\",\n            \"typing.KeysView\",\n        ]:\n            if not tp.args:\n                # TODO: fix tuple in lib-stub/builtins.pyi (it should be generic).\n                return None\n            if not isinstance(get_proper_type(tp.args[0]), AnyType):\n                return tp.args[0]\n    elif isinstance(tp, TupleType):\n        normalized_items = []\n        for it in tp.items:\n            # This use case is probably rare, but not handling unpacks here can cause crashes.\n            if isinstance(it, UnpackType):\n                unpacked = get_proper_type(it.type)\n                if isinstance(unpacked, TypeVarTupleType):\n                    unpacked = get_proper_type(unpacked.upper_bound)\n                assert (\n                    isinstance(unpacked, Instance) and unpacked.type.fullname == \"builtins.tuple\"\n                )\n                normalized_items.append(unpacked.args[0])\n            else:\n                normalized_items.append(it)\n        if all(not isinstance(it, AnyType) for it in get_proper_types(normalized_items)):\n            return make_simplified_union(normalized_items)  # this type is not externally visible\n    elif isinstance(tp, TypedDictType):\n        # TypedDict always has non-optional string keys. Find the key type from the Mapping\n        # base class.\n        for base in tp.fallback.type.mro:\n            if base.fullname == \"typing.Mapping\":\n                return map_instance_to_supertype(tp.fallback, base).args[0]\n        assert False, \"No Mapping base class found for TypedDict fallback\"\n    return None\n\n\ndef is_unreachable_map(map: TypeMap) -> bool:\n    return any(isinstance(get_proper_type(v), UninhabitedType) for v in map.values())\n\n\ndef and_conditional_maps(m1: TypeMap, m2: TypeMap, *, use_meet: bool = False) -> TypeMap:\n    \"\"\"Calculate what information we can learn from the truth of (e1 and e2)\n    in terms of the information that we can learn from the truth of e1 and\n    the truth of e2.\n    \"\"\"\n    # Both conditions can be true; combine the information. Anything\n    # we learn from either conditions' truth is valid. If the same\n    # expression's type is refined by both conditions, we somewhat\n    # arbitrarily give precedence to m2 unless m1 value is Any.\n    # In the future, we could use an intersection type or meet_types().\n    result = m2.copy()\n    m2_keys = {literal_hash(n2) for n2 in m2}\n    for n1 in m1:\n        if literal_hash(n1) not in m2_keys or isinstance(\n            get_proper_type(m1[n1]), (AnyType, UninhabitedType)\n        ):\n            result[n1] = m1[n1]\n    if use_meet:\n        # For now, meet common keys only if specifically requested.\n        # This is currently used for tuple types narrowing, where having\n        # a precise result is important.\n        for n1 in m1:\n            for n2 in m2:\n                if literal_hash(n1) == literal_hash(n2):\n                    result[n1] = meet_types(m1[n1], m2[n2])\n    return result\n\n\ndef or_conditional_maps(m1: TypeMap, m2: TypeMap, *, coalesce_any: bool = False) -> TypeMap:\n    \"\"\"Calculate what information we can learn from the truth of (e1 or e2)\n    in terms of the information that we can learn from the truth of e1 and\n    the truth of e2. If coalesce_any is True, consider Any a supertype when\n    joining restrictions.\n    \"\"\"\n\n    if is_unreachable_map(m1):\n        return m2\n    if is_unreachable_map(m2):\n        return m1\n    # Both conditions can be true. Combine information about\n    # expressions whose type is refined by both conditions. (We do not\n    # learn anything about expressions whose type is refined by only\n    # one condition.)\n    result: dict[Expression, Type] = {}\n    for n1 in m1:\n        for n2 in m2:\n            if literal_hash(n1) == literal_hash(n2):\n                if coalesce_any and isinstance(get_proper_type(m1[n1]), AnyType):\n                    result[n1] = m1[n1]\n                else:\n                    result[n1] = make_simplified_union([m1[n1], m2[n2]])\n    return result\n\n\ndef reduce_conditional_maps(\n    type_maps: list[tuple[TypeMap, TypeMap]], use_meet: bool = False\n) -> tuple[TypeMap, TypeMap]:\n    \"\"\"Reduces a list containing pairs of if/else TypeMaps into a single pair.\n\n    We \"and\" together all of the if TypeMaps and \"or\" together the else TypeMaps. So\n    for example, if we had the input:\n\n        [\n            ({x: TypeIfX, shared: TypeIfShared1}, {x: TypeElseX, shared: TypeElseShared1}),\n            ({y: TypeIfY, shared: TypeIfShared2}, {y: TypeElseY, shared: TypeElseShared2}),\n        ]\n\n    ...we'd return the output:\n\n        (\n            {x: TypeIfX,   y: TypeIfY,   shared: PseudoIntersection[TypeIfShared1, TypeIfShared2]},\n            {shared: Union[TypeElseShared1, TypeElseShared2]},\n        )\n\n    ...where \"PseudoIntersection[X, Y] == Y\" because mypy actually doesn't understand intersections\n    yet, so we settle for just arbitrarily picking the right expr's type.\n\n    We only retain the shared expression in the 'else' case because we don't actually know\n    whether x was refined or y was refined -- only just that one of the two was refined.\n    \"\"\"\n    if len(type_maps) == 0:\n        return {}, {}\n    elif len(type_maps) == 1:\n        return type_maps[0]\n    else:\n        final_if_map, final_else_map = type_maps[0]\n        for if_map, else_map in type_maps[1:]:\n            final_if_map = and_conditional_maps(final_if_map, if_map, use_meet=use_meet)\n            final_else_map = or_conditional_maps(final_else_map, else_map)\n\n        return final_if_map, final_else_map\n\n\ndef reduce_or_conditional_type_maps(ms: list[TypeMap]) -> TypeMap:\n    \"\"\"Reduces a list of TypeMaps into a single TypeMap by \"or\"-ing them together.\"\"\"\n    if len(ms) == 0:\n        return {}\n    if len(ms) == 1:\n        return ms[0]\n    result = ms[0]\n    for m in ms[1:]:\n        result = or_conditional_maps(result, m)\n    return result\n\n\ndef reduce_and_conditional_type_maps(ms: list[TypeMap], *, use_meet: bool) -> TypeMap:\n    \"\"\"Reduces a list of TypeMaps into a single TypeMap by \"and\"-ing them together.\"\"\"\n    if len(ms) == 0:\n        return {}\n    if len(ms) == 1:\n        return ms[0]\n    result = ms[0]\n    for m in ms[1:]:\n        result = and_conditional_maps(result, m, use_meet=use_meet)\n    return result\n\n\nBUILTINS_CUSTOM_EQ_CHECKS: Final = {\"builtins.bytearray\", \"builtins.memoryview\"}\n\n\ndef has_custom_eq_checks(t: Type) -> bool:\n    return (\n        custom_special_method(t, \"__eq__\", check_all=False)\n        or custom_special_method(t, \"__ne__\", check_all=False)\n        # custom_special_method has special casing for builtins.* and typing.* that make the\n        # above always return False. So here we return True if the a value of a builtin type\n        # will ever compare equal to value of another type, e.g. a bytes value can compare equal\n        # to a bytearray value. We also include builtins collections, see testNarrowingCollections\n        or (\n            isinstance(pt := get_proper_type(t), Instance)\n            and pt.type.fullname in BUILTINS_CUSTOM_EQ_CHECKS\n        )\n    )\n\n\ndef convert_to_typetype(type_map: TypeMap) -> TypeMap:\n    converted_type_map: dict[Expression, Type] = {}\n    for expr, typ in type_map.items():\n        t = typ\n        if isinstance(t, TypeVarType):\n            t = t.upper_bound\n        t = get_proper_type(t)\n\n        # TODO: should we only allow unions of instances as per PEP 484?\n        if isinstance(t, UninhabitedType):\n            converted_type_map[expr] = typ\n        elif isinstance(t, (UnionType, Instance, NoneType)):\n            converted_type_map[expr] = TypeType.make_normalized(typ)\n        else:\n            # unknown type; error was likely reported earlier\n            return {}\n    return converted_type_map\n\n\ndef flatten(t: Expression) -> list[Expression]:\n    \"\"\"Flatten a nested sequence of tuples/lists into one list of nodes.\"\"\"\n    if isinstance(t, (TupleExpr, ListExpr)):\n        return [b for a in t.items for b in flatten(a)]\n    elif isinstance(t, StarExpr):\n        return flatten(t.expr)\n    else:\n        return [t]\n\n\ndef flatten_types_if_tuple(t: Type) -> list[Type]:\n    \"\"\"Flatten a nested sequence of tuples into one list of nodes.\"\"\"\n    t = get_proper_type(t)\n    if isinstance(t, UnionType):\n        return [UnionType.make_union([b for a in t.items for b in flatten_types_if_tuple(a)])]\n    if isinstance(t, TupleType):\n        return [b for a in t.items for b in flatten_types_if_tuple(a)]\n    elif is_named_instance(t, \"builtins.tuple\"):\n        return [t.args[0]]\n    return [t]\n\n\ndef expand_func(defn: FuncItem, map: dict[TypeVarId, Type]) -> FuncItem:\n    visitor = TypeTransformVisitor(map)\n    ret = visitor.node(defn)\n    assert isinstance(ret, FuncItem)\n    return ret\n\n\nclass TypeTransformVisitor(TransformVisitor):\n    def __init__(self, map: dict[TypeVarId, Type]) -> None:\n        super().__init__()\n        self.map = map\n\n    def type(self, type: Type) -> Type:\n        return expand_type(type, self.map)\n\n\ndef are_argument_counts_overlapping(t: CallableType, s: CallableType) -> bool:\n    \"\"\"Can a single call match both t and s, based just on positional argument counts?\"\"\"\n    min_args = max(t.min_args, s.min_args)\n    max_args = min(t.max_possible_positional_args(), s.max_possible_positional_args())\n    return min_args <= max_args\n\n\ndef expand_callable_variants(c: CallableType) -> list[CallableType]:\n    \"\"\"Expand a generic callable using all combinations of type variables' values/bounds.\"\"\"\n    for tv in c.variables:\n        # We need to expand self-type before other variables, because this is the only\n        # type variable that can have other type variables in the upper bound.\n        if tv.id.is_self():\n            c = expand_type(c, {tv.id: tv.upper_bound}).copy_modified(\n                variables=[v for v in c.variables if not v.id.is_self()]\n            )\n            break\n\n    if not c.is_generic():\n        # Fast path.\n        return [c]\n\n    tvar_values = []\n    for tvar in c.variables:\n        if isinstance(tvar, TypeVarType) and tvar.values:\n            tvar_values.append(tvar.values)\n        else:\n            tvar_values.append([tvar.upper_bound])\n\n    variants = []\n    for combination in itertools.product(*tvar_values):\n        tvar_map = {tv.id: subst for (tv, subst) in zip(c.variables, combination)}\n        variants.append(expand_type(c, tvar_map).copy_modified(variables=[]))\n    return variants\n\n\ndef is_unsafe_overlapping_overload_signatures(\n    signature: CallableType,\n    other: CallableType,\n    class_type_vars: list[TypeVarLikeType],\n    partial_only: bool = True,\n) -> bool:\n    \"\"\"Check if two overloaded signatures are unsafely overlapping or partially overlapping.\n\n    We consider two functions 's' and 't' to be unsafely overlapping if three\n    conditions hold:\n\n    1.  s's parameters are partially overlapping with t's. i.e. there are calls that are\n        valid for both signatures.\n    2.  for these common calls, some of t's parameters types are wider that s's.\n    3.  s's return type is NOT a subset of t's.\n\n    Note that we use subset rather than subtype relationship in these checks because:\n    * Overload selection happens at runtime, not statically.\n    * This results in more lenient behavior.\n    This can cause false negatives (e.g. if overloaded function returns an externally\n    visible attribute with invariant type), but such situations are rare. In general,\n    overloads in Python are generally unsafe, so we intentionally try to avoid giving\n    non-actionable errors (see more details in comments below).\n\n    Assumes that 'signature' appears earlier in the list of overload\n    alternatives then 'other' and that their argument counts are overlapping.\n    \"\"\"\n    # Try detaching callables from the containing class so that all TypeVars\n    # are treated as being free, i.e. the signature is as seen from inside the class,\n    # where \"self\" is not yet bound to anything.\n    signature = detach_callable(signature, class_type_vars)\n    other = detach_callable(other, class_type_vars)\n\n    # Note: We repeat this check twice in both directions compensate for slight\n    # asymmetries in 'is_callable_compatible'.\n\n    other_expanded = expand_callable_variants(other)\n    for sig_variant in expand_callable_variants(signature):\n        for other_variant in other_expanded:\n            # Using only expanded callables may cause false negatives, we can add\n            # more variants (e.g. using inference between callables) in the future.\n            if is_subset_no_promote(sig_variant.ret_type, other_variant.ret_type):\n                continue\n            if not (\n                is_callable_compatible(\n                    sig_variant,\n                    other_variant,\n                    is_compat=is_overlapping_types_for_overload,\n                    check_args_covariantly=False,\n                    is_proper_subtype=False,\n                    is_compat_return=lambda l, r: not is_subset_no_promote(l, r),\n                    allow_partial_overlap=True,\n                )\n                or is_callable_compatible(\n                    other_variant,\n                    sig_variant,\n                    is_compat=is_overlapping_types_for_overload,\n                    check_args_covariantly=True,\n                    is_proper_subtype=False,\n                    is_compat_return=lambda l, r: not is_subset_no_promote(r, l),\n                    allow_partial_overlap=True,\n                )\n            ):\n                continue\n            # Using the same `allow_partial_overlap` flag as before, can cause false\n            # negatives in case where star argument is used in a catch-all fallback overload.\n            # But again, practicality beats purity here.\n            if not partial_only or not is_callable_compatible(\n                other_variant,\n                sig_variant,\n                is_compat=is_subset_no_promote,\n                check_args_covariantly=True,\n                is_proper_subtype=False,\n                ignore_return=True,\n                allow_partial_overlap=True,\n            ):\n                return True\n    return False\n\n\ndef detach_callable(typ: CallableType, class_type_vars: list[TypeVarLikeType]) -> CallableType:\n    \"\"\"Ensures that the callable's type variables are 'detached' and independent of the context.\n\n    A callable normally keeps track of the type variables it uses within its 'variables' field.\n    However, if the callable is from a method and that method is using a class type variable,\n    the callable will not keep track of that type variable since it belongs to the class.\n    \"\"\"\n    if not class_type_vars:\n        # Fast path, nothing to update.\n        return typ\n    return typ.copy_modified(variables=list(typ.variables) + class_type_vars)\n\n\ndef overload_can_never_match(signature: CallableType, other: CallableType) -> bool:\n    \"\"\"Check if the 'other' method can never be matched due to 'signature'.\n\n    This can happen if signature's parameters are all strictly broader then\n    other's parameters.\n\n    Assumes that both signatures have overlapping argument counts.\n    \"\"\"\n    # The extra erasure is needed to prevent spurious errors\n    # in situations where an `Any` overload is used as a fallback\n    # for an overload with type variables. The spurious error appears\n    # because the type variables turn into `Any` during unification in\n    # the below subtype check and (surprisingly?) `is_proper_subtype(Any, Any)`\n    # returns `True`.\n    # TODO: find a cleaner solution instead of this ad-hoc erasure.\n    exp_signature = expand_type(\n        signature, {tvar.id: erase_def_to_union_or_bound(tvar) for tvar in signature.variables}\n    )\n    return is_callable_compatible(\n        exp_signature, other, is_compat=is_more_precise, is_proper_subtype=True, ignore_return=True\n    )\n\n\ndef is_more_general_arg_prefix(t: FunctionLike, s: FunctionLike) -> bool:\n    \"\"\"Does t have wider arguments than s?\"\"\"\n    # TODO should an overload with additional items be allowed to be more\n    #      general than one with fewer items (or just one item)?\n    if isinstance(t, CallableType):\n        if isinstance(s, CallableType):\n            return is_callable_compatible(\n                t, s, is_compat=is_proper_subtype, is_proper_subtype=True, ignore_return=True\n            )\n    elif isinstance(t, FunctionLike):\n        if isinstance(s, FunctionLike):\n            if len(t.items) == len(s.items):\n                return all(\n                    is_same_arg_prefix(items, itemt) for items, itemt in zip(t.items, s.items)\n                )\n    return False\n\n\ndef is_same_arg_prefix(t: CallableType, s: CallableType) -> bool:\n    return is_callable_compatible(\n        t,\n        s,\n        is_compat=is_same_type,\n        is_proper_subtype=True,\n        ignore_return=True,\n        check_args_covariantly=True,\n        ignore_pos_arg_names=True,\n    )\n\n\ndef infer_operator_assignment_method(typ: Type, operator: str) -> tuple[bool, str]:\n    \"\"\"Determine if operator assignment on given value type is in-place, and the method name.\n\n    For example, if operator is '+', return (True, '__iadd__') or (False, '__add__')\n    depending on which method is supported by the type.\n    \"\"\"\n    typ = get_proper_type(typ)\n    method = operators.op_methods[operator]\n    existing_method = None\n    if isinstance(typ, Instance):\n        existing_method = _find_inplace_method(typ, method, operator)\n    elif isinstance(typ, TypedDictType):\n        existing_method = _find_inplace_method(typ.fallback, method, operator)\n\n    if existing_method is not None:\n        return True, existing_method\n    return False, method\n\n\ndef _find_inplace_method(inst: Instance, method: str, operator: str) -> str | None:\n    if operator in operators.ops_with_inplace_method:\n        inplace_method = \"__i\" + method[2:]\n        if inst.type.has_readable_member(inplace_method):\n            return inplace_method\n    return None\n\n\ndef is_valid_inferred_type(\n    typ: Type, options: Options, is_lvalue_final: bool = False, is_lvalue_member: bool = False\n) -> bool:\n    \"\"\"Is an inferred type valid and needs no further refinement?\n\n    Examples of invalid types include the None type (when we are not assigning\n    None to a final lvalue) or List[<uninhabited>].\n\n    When not doing strict Optional checking, all types containing None are\n    invalid.  When doing strict Optional checking, only None and types that are\n    incompletely defined (i.e. contain UninhabitedType) are invalid.\n    \"\"\"\n    proper_type = get_proper_type(typ)\n    if isinstance(proper_type, NoneType):\n        # If the lvalue is final, we may immediately infer NoneType when the\n        # initializer is None.\n        #\n        # If not, we want to defer making this decision. The final inferred\n        # type could either be NoneType or an Optional type, depending on\n        # the context. This resolution happens in leave_partial_types when\n        # we pop a partial types scope.\n        return is_lvalue_final or (not is_lvalue_member and options.allow_redefinition_new)\n    elif isinstance(proper_type, UninhabitedType):\n        return False\n    return not typ.accept(InvalidInferredTypes())\n\n\nclass InvalidInferredTypes(BoolTypeQuery):\n    \"\"\"Find type components that are not valid for an inferred type.\n\n    These include <Erased> type, and any uninhabited types resulting from failed\n    (ambiguous) type inference.\n    \"\"\"\n\n    def __init__(self) -> None:\n        super().__init__(ANY_STRATEGY)\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> bool:\n        return t.ambiguous\n\n    def visit_erased_type(self, t: ErasedType) -> bool:\n        # This can happen inside a lambda.\n        return True\n\n    def visit_type_var(self, t: TypeVarType) -> bool:\n        # This is needed to prevent leaking into partial types during\n        # multi-step type inference.\n        return t.id.is_meta_var()\n\n    def visit_tuple_type(self, t: TupleType, /) -> bool:\n        # Exclude fallback to avoid bogus \"need type annotation\" errors\n        return self.query_types(t.items)\n\n\nclass SetNothingToAny(TypeTranslator):\n    \"\"\"Replace all ambiguous Uninhabited types with Any (to avoid spurious extra errors).\"\"\"\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> Type:\n        if t.ambiguous:\n            return AnyType(TypeOfAny.from_error)\n        return t\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        # Target of the alias cannot be an ambiguous UninhabitedType, so we just\n        # replace the arguments.\n        return t.copy_modified(args=[a.accept(self) for a in t.args])\n\n\ndef is_classmethod_node(node: SymbolNode | None) -> bool | None:\n    \"\"\"Find out if a node describes a classmethod.\"\"\"\n    if isinstance(node, Decorator):\n        node = node.func\n    if isinstance(node, FuncDef):\n        return node.is_class\n    if isinstance(node, Var):\n        return node.is_classmethod\n    return None\n\n\ndef is_node_static(node: SymbolNode | None) -> bool | None:\n    \"\"\"Find out if a node describes a static function method.\"\"\"\n    if isinstance(node, Decorator):\n        node = node.func\n    if isinstance(node, FuncDef):\n        return node.is_static\n    if isinstance(node, Var):\n        return node.is_staticmethod\n    return None\n\n\nTKey = TypeVar(\"TKey\")\nTValue = TypeVar(\"TValue\")\n\n\nclass DisjointDict(Generic[TKey, TValue]):\n    \"\"\"An variation of the union-find algorithm/data structure where instead of keeping\n    track of just disjoint sets, we keep track of disjoint dicts -- keep track of multiple\n    Set[Key] -> Set[Value] mappings, where each mapping's keys are guaranteed to be disjoint.\n\n    This data structure is currently used exclusively by 'group_comparison_operands' below\n    to merge chains of '==' and 'is' comparisons when two or more chains use the same expression\n    in best-case O(n), where n is the number of operands.\n\n    Specifically, the `add_mapping()` function and `items()` functions will take on average\n    O(k + v) and O(n) respectively, where k and v are the number of keys and values we're adding\n    for a given chain. Note that k <= n and v <= n.\n\n    We hit these average/best-case scenarios for most user code: e.g. when the user has just\n    a single chain like 'a == b == c == d == ...' or multiple disjoint chains like\n    'a==b < c==d < e==f < ...'. (Note that a naive iterative merging would be O(n^2) for\n    the latter case).\n\n    In comparison, this data structure will make 'group_comparison_operands' have a worst-case\n    runtime of O(n*log(n)): 'add_mapping()' and 'items()' are worst-case O(k*log(n) + v) and\n    O(k*log(n)) respectively. This happens only in the rare case where the user keeps repeatedly\n    making disjoint mappings before merging them in a way that persistently dodges the path\n    compression optimization in '_lookup_root_id', which would end up constructing a single\n    tree of height log_2(n). This makes root lookups no longer amoritized constant time when we\n    finally call 'items()'.\n    \"\"\"\n\n    def __init__(self) -> None:\n        # Each key maps to a unique ID\n        self._key_to_id: dict[TKey, int] = {}\n\n        # Each id points to the parent id, forming a forest of upwards-pointing trees. If the\n        # current id already is the root, it points to itself. We gradually flatten these trees\n        # as we perform root lookups: eventually all nodes point directly to its root.\n        self._id_to_parent_id: dict[int, int] = {}\n\n        # Each root id in turn maps to the set of values.\n        self._root_id_to_values: dict[int, set[TValue]] = {}\n\n    def add_mapping(self, keys: set[TKey], values: set[TValue]) -> None:\n        \"\"\"Adds a 'Set[TKey] -> Set[TValue]' mapping. If there already exists a mapping\n        containing one or more of the given keys, we merge the input mapping with the old one.\n\n        Note that the given set of keys must be non-empty -- otherwise, nothing happens.\n        \"\"\"\n        if not keys:\n            return\n\n        subtree_roots = [self._lookup_or_make_root_id(key) for key in keys]\n        new_root = subtree_roots[0]\n\n        root_values = self._root_id_to_values[new_root]\n        root_values.update(values)\n        for subtree_root in subtree_roots[1:]:\n            if subtree_root == new_root or subtree_root not in self._root_id_to_values:\n                continue\n            self._id_to_parent_id[subtree_root] = new_root\n            root_values.update(self._root_id_to_values.pop(subtree_root))\n\n    def items(self) -> list[tuple[set[TKey], set[TValue]]]:\n        \"\"\"Returns all disjoint mappings in key-value pairs.\"\"\"\n        root_id_to_keys: dict[int, set[TKey]] = {}\n        for key in self._key_to_id:\n            root_id = self._lookup_root_id(key)\n            if root_id not in root_id_to_keys:\n                root_id_to_keys[root_id] = set()\n            root_id_to_keys[root_id].add(key)\n\n        output = []\n        for root_id, keys in root_id_to_keys.items():\n            output.append((keys, self._root_id_to_values[root_id]))\n\n        return output\n\n    def _lookup_or_make_root_id(self, key: TKey) -> int:\n        if key in self._key_to_id:\n            return self._lookup_root_id(key)\n        else:\n            new_id = len(self._key_to_id)\n            self._key_to_id[key] = new_id\n            self._id_to_parent_id[new_id] = new_id\n            self._root_id_to_values[new_id] = set()\n            return new_id\n\n    def _lookup_root_id(self, key: TKey) -> int:\n        i = self._key_to_id[key]\n        while i != self._id_to_parent_id[i]:\n            # Optimization: make keys directly point to their grandparents to speed up\n            # future traversals. This prevents degenerate trees of height n from forming.\n            new_parent = self._id_to_parent_id[self._id_to_parent_id[i]]\n            self._id_to_parent_id[i] = new_parent\n            i = new_parent\n        return i\n\n\ndef group_comparison_operands(\n    pairwise_comparisons: Iterable[tuple[str, Expression, Expression]],\n    operand_to_literal_hash: Mapping[int, Key],\n    operators_to_group: set[str],\n) -> list[tuple[str, list[int]]]:\n    \"\"\"Group a series of comparison operands together chained by any operand\n    in the 'operators_to_group' set. All other pairwise operands are kept in\n    groups of size 2.\n\n    For example, suppose we have the input comparison expression:\n\n        x0 == x1 == x2 < x3 < x4 is x5 is x6 is not x7 is not x8\n\n    If we get these expressions in a pairwise way (e.g. by calling ComparisonExpr's\n    'pairwise()' method), we get the following as input:\n\n        [('==', x0, x1), ('==', x1, x2), ('<', x2, x3), ('<', x3, x4),\n         ('is', x4, x5), ('is', x5, x6), ('is not', x6, x7), ('is not', x7, x8)]\n\n    If `operators_to_group` is the set {'==', 'is'}, this function will produce\n    the following \"simplified operator list\":\n\n       [(\"==\", [0, 1, 2]), (\"<\", [2, 3]), (\"<\", [3, 4]),\n        (\"is\", [4, 5, 6]), (\"is not\", [6, 7]), (\"is not\", [7, 8])]\n\n    Note that (a) we yield *indices* to the operands rather then the operand\n    expressions themselves and that (b) operands used in a consecutive chain\n    of '==' or 'is' are grouped together.\n\n    If two of these chains happen to contain operands with the same underlying\n    literal hash (e.g. are assignable and correspond to the same expression),\n    we combine those chains together. For example, if we had:\n\n        same == x < y == same\n\n    ...and if 'operand_to_literal_hash' contained the same values for the indices\n    0 and 3, we'd produce the following output:\n\n        [(\"==\", [0, 1, 2, 3]), (\"<\", [1, 2])]\n\n    But if the 'operand_to_literal_hash' did *not* contain an entry, we'd instead\n    default to returning:\n\n        [(\"==\", [0, 1]), (\"<\", [1, 2]), (\"==\", [2, 3])]\n\n    This function is currently only used to assist with type-narrowing refinements\n    and is extracted out to a helper function so we can unit test it.\n    \"\"\"\n    groups: dict[str, DisjointDict[Key, int]] = {op: DisjointDict() for op in operators_to_group}\n\n    simplified_operator_list: list[tuple[str, list[int]]] = []\n    last_operator: str | None = None\n    current_indices: set[int] = set()\n    current_hashes: set[Key] = set()\n    for i, (operator, left_expr, right_expr) in enumerate(pairwise_comparisons):\n        if last_operator is None:\n            last_operator = operator\n\n        if current_indices and (operator != last_operator or operator not in operators_to_group):\n            # If some of the operands in the chain are assignable, defer adding it: we might\n            # end up needing to merge it with other chains that appear later.\n            if not current_hashes:\n                simplified_operator_list.append((last_operator, sorted(current_indices)))\n            else:\n                groups[last_operator].add_mapping(current_hashes, current_indices)\n            last_operator = operator\n            current_indices = set()\n            current_hashes = set()\n\n        # Note: 'i' corresponds to the left operand index, so 'i + 1' is the\n        # right operand.\n        current_indices.add(i)\n        current_indices.add(i + 1)\n\n        # We only ever want to combine operands/combine chains for these operators\n        if operator in operators_to_group:\n            left_hash = operand_to_literal_hash.get(i)\n            if left_hash is not None:\n                current_hashes.add(left_hash)\n            right_hash = operand_to_literal_hash.get(i + 1)\n            if right_hash is not None:\n                current_hashes.add(right_hash)\n\n    if last_operator is not None:\n        if not current_hashes:\n            simplified_operator_list.append((last_operator, sorted(current_indices)))\n        else:\n            groups[last_operator].add_mapping(current_hashes, current_indices)\n\n    # Now that we know which chains happen to contain the same underlying expressions\n    # and can be merged together, add in this info back to the output.\n    for operator, disjoint_dict in groups.items():\n        for keys, indices in disjoint_dict.items():\n            simplified_operator_list.append((operator, sorted(indices)))\n\n    # For stability, reorder list by the first operand index to appear\n    simplified_operator_list.sort(key=lambda item: item[1][0])\n    return simplified_operator_list\n\n\ndef is_typed_callable(c: Type | None) -> bool:\n    c = get_proper_type(c)\n    if not c or not isinstance(c, CallableType):\n        return False\n    return not all(\n        isinstance(t, AnyType) and t.type_of_any == TypeOfAny.unannotated\n        for t in get_proper_types(c.arg_types + [c.ret_type])\n    )\n\n\ndef is_untyped_decorator(typ: Type | None) -> bool:\n    typ = get_proper_type(typ)\n    if not typ:\n        return True\n    elif isinstance(typ, CallableType):\n        return not is_typed_callable(typ)\n    elif isinstance(typ, Instance):\n        method = typ.type.get_method(\"__call__\")\n        if method:\n            if isinstance(method, Decorator):\n                return is_untyped_decorator(method.func.type) or is_untyped_decorator(\n                    method.var.type\n                )\n\n            if isinstance(method.type, Overloaded):\n                return any(is_untyped_decorator(item) for item in method.type.items)\n            else:\n                return not is_typed_callable(method.type)\n        else:\n            return False\n    elif isinstance(typ, Overloaded):\n        return any(is_untyped_decorator(item) for item in typ.items)\n    return True\n\n\ndef is_static(func: FuncBase | Decorator) -> bool:\n    if isinstance(func, Decorator):\n        return is_static(func.func)\n    elif isinstance(func, FuncBase):\n        return func.is_static\n    assert False, f\"Unexpected func type: {type(func)}\"\n\n\ndef is_property(defn: SymbolNode) -> bool:\n    if isinstance(defn, FuncDef):\n        return defn.is_property\n    if isinstance(defn, Decorator):\n        return defn.func.is_property\n    if isinstance(defn, OverloadedFuncDef):\n        if defn.items and isinstance(defn.items[0], Decorator):\n            return defn.items[0].func.is_property\n    return False\n\n\ndef is_settable_property(defn: SymbolNode | None) -> TypeGuard[OverloadedFuncDef]:\n    if isinstance(defn, OverloadedFuncDef):\n        if defn.items and isinstance(defn.items[0], Decorator):\n            return defn.items[0].func.is_property\n    return False\n\n\ndef is_custom_settable_property(defn: SymbolNode | None) -> bool:\n    \"\"\"Check if a node is a settable property with a non-trivial setter type.\n\n    By non-trivial here we mean that it is known (i.e. definition was already type\n    checked), it is not Any, and it is different from the property getter type.\n    \"\"\"\n    if defn is None:\n        return False\n    if not is_settable_property(defn):\n        return False\n    first_item = defn.items[0]\n    assert isinstance(first_item, Decorator)\n    if not first_item.var.is_settable_property:\n        return False\n    var = first_item.var\n    if var.type is None or var.setter_type is None or isinstance(var.type, PartialType):\n        # The caller should defer in case of partial types or not ready variables.\n        return False\n    setter_type = var.setter_type.arg_types[1]\n    if isinstance(get_proper_type(setter_type), AnyType):\n        return False\n    return not is_same_type(get_property_type(get_proper_type(var.type)), setter_type)\n\n\ndef get_property_type(t: ProperType) -> ProperType:\n    if isinstance(t, CallableType):\n        return get_proper_type(t.ret_type)\n    if isinstance(t, Overloaded):\n        return get_proper_type(t.items[0].ret_type)\n    return t\n\n\ndef is_subset_no_promote(left: Type, right: Type) -> bool:\n    return is_subtype(left, right, ignore_promotions=True, always_covariant=True)\n\n\ndef is_overlapping_types_for_overload(left: Type, right: Type) -> bool:\n    # Note that among other effects 'overlap_for_overloads' flag will effectively\n    # ignore possible overlap between type variables and None. This is technically\n    # unsafe, but unsafety is tiny and this prevents some common use cases like:\n    #     @overload\n    #     def foo(x: None) -> None: ..\n    #     @overload\n    #     def foo(x: T) -> Foo[T]: ...\n    return is_overlapping_types(left, right, ignore_promotions=True, overlap_for_overloads=True)\n\n\ndef is_private(node_name: str) -> bool:\n    \"\"\"Check if node is private to class definition.\"\"\"\n    return node_name.startswith(\"__\") and not node_name.endswith(\"__\")\n\n\ndef is_string_literal(typ: Type) -> bool:\n    strs = try_getting_str_literals_from_type(typ)\n    return strs is not None and len(strs) == 1\n\n\ndef has_bool_item(typ: ProperType) -> bool:\n    \"\"\"Return True if type is 'bool' or a union with a 'bool' item.\"\"\"\n    if is_named_instance(typ, \"builtins.bool\"):\n        return True\n    if isinstance(typ, UnionType):\n        return any(is_named_instance(item, \"builtins.bool\") for item in typ.items)\n    return False\n\n\ndef collapse_walrus(e: Expression) -> Expression:\n    \"\"\"If an expression is an AssignmentExpr, pull out the assignment target.\n\n    We don't make any attempt to pull out all the targets in code like `x := (y := z)`.\n    We could support narrowing those if that sort of code turns out to be common.\n    \"\"\"\n    if isinstance(e, AssignmentExpr):\n        return e.target\n    return e\n\n\ndef find_last_var_assignment_line(n: Node, v: Var) -> int:\n    \"\"\"Find the highest line number of a potential assignment to variable within node.\n\n    This supports local and global variables.\n\n    Return -1 if no assignment was found.\n    \"\"\"\n    visitor = VarAssignVisitor(v)\n    n.accept(visitor)\n    return visitor.last_line\n\n\nclass VarAssignVisitor(TraverserVisitor):\n    def __init__(self, v: Var) -> None:\n        self.last_line = -1\n        self.lvalue = False\n        self.var_node = v\n\n    def visit_assignment_stmt(self, s: AssignmentStmt) -> None:\n        self.lvalue = True\n        for lv in s.lvalues:\n            lv.accept(self)\n        self.lvalue = False\n\n    def visit_name_expr(self, e: NameExpr) -> None:\n        if self.lvalue and e.node is self.var_node:\n            self.last_line = max(self.last_line, e.line)\n\n    def visit_member_expr(self, e: MemberExpr) -> None:\n        old_lvalue = self.lvalue\n        self.lvalue = False\n        super().visit_member_expr(e)\n        self.lvalue = old_lvalue\n\n    def visit_index_expr(self, e: IndexExpr) -> None:\n        old_lvalue = self.lvalue\n        self.lvalue = False\n        super().visit_index_expr(e)\n        self.lvalue = old_lvalue\n\n    def visit_with_stmt(self, s: WithStmt) -> None:\n        self.lvalue = True\n        for lv in s.target:\n            if lv is not None:\n                lv.accept(self)\n        self.lvalue = False\n        s.body.accept(self)\n\n    def visit_for_stmt(self, s: ForStmt) -> None:\n        self.lvalue = True\n        s.index.accept(self)\n        self.lvalue = False\n        s.body.accept(self)\n        if s.else_body:\n            s.else_body.accept(self)\n\n    def visit_assignment_expr(self, e: AssignmentExpr) -> None:\n        self.lvalue = True\n        e.target.accept(self)\n        self.lvalue = False\n        e.value.accept(self)\n\n    def visit_as_pattern(self, p: AsPattern) -> None:\n        if p.pattern is not None:\n            p.pattern.accept(self)\n        if p.name is not None:\n            self.lvalue = True\n            p.name.accept(self)\n            self.lvalue = False\n\n    def visit_starred_pattern(self, p: StarredPattern) -> None:\n        if p.capture is not None:\n            self.lvalue = True\n            p.capture.accept(self)\n            self.lvalue = False\n\n\ndef ambiguous_enum_equality_keys(t: Type) -> set[str]:\n    \"\"\"\n    Used when narrowing types based on equality.\n\n    Certain kinds of enums can compare equal to values of other types, so doing type math\n    the way `conditional_types` does will be misleading if you expect it to correspond to\n    conditions based on equality comparisons.\n\n    For example, StrEnum classes can compare equal to str values. So if we see\n    `val: StrEnum; if val == \"foo\": ...` we currently avoid narrowing.\n    Note that we do wish to continue narrowing for `if val == StrEnum.MEMBER: ...`\n    \"\"\"\n    # We need these things for this to be ambiguous:\n    #  (1) an IntEnum or StrEnum type or enum subclass of int or str\n    #  (2) either a different IntEnum/StrEnum type or a non-enum type (\"<other>\")\n    result = set()\n    t = get_proper_type(t)\n    if isinstance(t, UnionType):\n        for item in t.items:\n            result.update(ambiguous_enum_equality_keys(item))\n    elif isinstance(t, Instance):\n        if t.last_known_value:\n            result.update(ambiguous_enum_equality_keys(t.last_known_value))\n        elif t.type.is_enum and any(\n            base.fullname in (\"enum.IntEnum\", \"enum.StrEnum\", \"builtins.str\", \"builtins.int\")\n            for base in t.type.mro\n        ):\n            result.add(t.type.fullname)\n        elif not t.type.is_enum:\n            # These might compare equal to IntEnum/StrEnum types (e.g. Decimal), so\n            # let's be conservative\n            result.add(\"<other>\")\n    elif isinstance(t, LiteralType):\n        result.update(ambiguous_enum_equality_keys(t.fallback))\n    elif isinstance(t, NoneType):\n        pass\n    else:\n        result.add(\"<other>\")\n    return result\n\n\ndef is_typeddict_type_context(lvalue_type: Type) -> bool:\n    lvalue_type = get_proper_type(lvalue_type)\n    if isinstance(lvalue_type, TypedDictType):\n        return True\n    if isinstance(lvalue_type, UnionType):\n        for item in lvalue_type.items:\n            if is_typeddict_type_context(item):\n                return True\n    return False\n\n\ndef is_method(node: SymbolNode | None) -> bool:\n    if isinstance(node, OverloadedFuncDef):\n        return not node.is_property\n    if isinstance(node, Decorator):\n        return not node.var.is_property\n    return isinstance(node, FuncDef)\n"
  },
  {
    "path": "mypy/checker_shared.py",
    "content": "\"\"\"Shared definitions used by different parts of type checker.\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections.abc import Iterator, Sequence, Set as AbstractSet\nfrom contextlib import contextmanager\nfrom typing import NamedTuple, overload\n\nfrom mypy_extensions import trait\n\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.errors import ErrorWatcher\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.nodes import (\n    ArgKind,\n    Context,\n    Expression,\n    FuncItem,\n    LambdaExpr,\n    MypyFile,\n    Node,\n    RefExpr,\n    SymbolNode,\n    TypeInfo,\n    Var,\n)\nfrom mypy.plugin import CheckerPluginInterface, Plugin\nfrom mypy.types import (\n    CallableType,\n    Instance,\n    LiteralValue,\n    Overloaded,\n    PartialType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeType,\n)\nfrom mypy.typevars import fill_typevars\n\n\n# An object that represents either a precise type or a type with an upper bound;\n# it is important for correct type inference with isinstance.\nclass TypeRange(NamedTuple):\n    item: Type\n    is_upper_bound: bool  # False => precise type\n\n\n@trait\nclass ExpressionCheckerSharedApi:\n    @abstractmethod\n    def accept(\n        self,\n        node: Expression,\n        type_context: Type | None = None,\n        allow_none_return: bool = False,\n        always_allow_any: bool = False,\n        is_callee: bool = False,\n    ) -> Type:\n        raise NotImplementedError\n\n    @abstractmethod\n    def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type:\n        raise NotImplementedError\n\n    @abstractmethod\n    def check_call(\n        self,\n        callee: Type,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n        arg_names: Sequence[str | None] | None = None,\n        callable_node: Expression | None = None,\n        callable_name: str | None = None,\n        object_type: Type | None = None,\n        original_type: Type | None = None,\n    ) -> tuple[Type, Type]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def transform_callee_type(\n        self,\n        callable_name: str | None,\n        callee: Type,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n        arg_names: Sequence[str | None] | None = None,\n        object_type: Type | None = None,\n    ) -> Type:\n        raise NotImplementedError\n\n    @abstractmethod\n    def method_fullname(self, object_type: Type, method_name: str) -> str | None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def check_method_call_by_name(\n        self,\n        method: str,\n        base_type: Type,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n        original_type: Type | None = None,\n    ) -> tuple[Type, Type]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_typeddict_index_expr(\n        self, td_type: TypedDictType, index: Expression, setitem: bool = False\n    ) -> tuple[Type, set[str]]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def infer_literal_expr_type(self, value: LiteralValue, fallback_name: str) -> Type:\n        raise NotImplementedError\n\n    @abstractmethod\n    def analyze_static_reference(\n        self,\n        node: SymbolNode,\n        ctx: Context,\n        is_lvalue: bool,\n        *,\n        include_modules: bool = True,\n        suppress_errors: bool = False,\n    ) -> Type:\n        raise NotImplementedError\n\n\n@trait\nclass TypeCheckerSharedApi(CheckerPluginInterface):\n    plugin: Plugin\n    module_refs: set[str]\n    scope: CheckerScope\n    checking_missing_await: bool\n    allow_constructor_cache: bool\n\n    @property\n    @abstractmethod\n    def expr_checker(self) -> ExpressionCheckerSharedApi:\n        raise NotImplementedError\n\n    @abstractmethod\n    def named_type(self, name: str) -> Instance:\n        raise NotImplementedError\n\n    @abstractmethod\n    def lookup_typeinfo(self, fullname: str) -> TypeInfo:\n        raise NotImplementedError\n\n    @abstractmethod\n    def lookup_type(self, node: Expression) -> Type:\n        raise NotImplementedError\n\n    @abstractmethod\n    def handle_cannot_determine_type(self, name: str, context: Context) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def handle_partial_var_type(\n        self, typ: PartialType, is_lvalue: bool, node: Var, context: Context\n    ) -> Type:\n        raise NotImplementedError\n\n    @overload\n    @abstractmethod\n    def check_subtype(\n        self,\n        subtype: Type,\n        supertype: Type,\n        context: Context,\n        msg: str,\n        subtype_label: str | None = None,\n        supertype_label: str | None = None,\n        *,\n        notes: list[str] | None = None,\n        code: ErrorCode | None = None,\n        outer_context: Context | None = None,\n    ) -> bool: ...\n\n    @overload\n    @abstractmethod\n    def check_subtype(\n        self,\n        subtype: Type,\n        supertype: Type,\n        context: Context,\n        msg: ErrorMessage,\n        subtype_label: str | None = None,\n        supertype_label: str | None = None,\n        *,\n        notes: list[str] | None = None,\n        outer_context: Context | None = None,\n    ) -> bool: ...\n\n    # Unfortunately, mypyc doesn't support abstract overloads yet.\n    @abstractmethod\n    def check_subtype(\n        self,\n        subtype: Type,\n        supertype: Type,\n        context: Context,\n        msg: str | ErrorMessage,\n        subtype_label: str | None = None,\n        supertype_label: str | None = None,\n        *,\n        notes: list[str] | None = None,\n        code: ErrorCode | None = None,\n        outer_context: Context | None = None,\n    ) -> bool:\n        raise NotImplementedError\n\n    @abstractmethod\n    def get_final_context(self) -> bool:\n        raise NotImplementedError\n\n    @overload\n    @abstractmethod\n    def conditional_types_with_intersection(\n        self,\n        expr_type: Type,\n        type_ranges: list[TypeRange] | None,\n        ctx: Context,\n        default: None = None,\n    ) -> tuple[Type | None, Type | None]: ...\n\n    @overload\n    @abstractmethod\n    def conditional_types_with_intersection(\n        self, expr_type: Type, type_ranges: list[TypeRange] | None, ctx: Context, default: Type\n    ) -> tuple[Type, Type]: ...\n\n    # Unfortunately, mypyc doesn't support abstract overloads yet.\n    @abstractmethod\n    def conditional_types_with_intersection(\n        self,\n        expr_type: Type,\n        type_ranges: list[TypeRange] | None,\n        ctx: Context,\n        default: Type | None = None,\n    ) -> tuple[Type | None, Type | None]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def narrow_type_by_identity_equality(\n        self,\n        operator: str,\n        operands: list[Expression],\n        operand_types: list[Type],\n        expr_indices: list[int],\n        narrowable_indices: AbstractSet[int],\n    ) -> tuple[dict[Expression, Type] | None, dict[Expression, Type] | None]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def check_deprecated(self, node: Node | None, context: Context) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def warn_deprecated(self, node: Node | None, context: Context) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def type_is_iterable(self, type: Type) -> bool:\n        raise NotImplementedError\n\n    @abstractmethod\n    def iterable_item_type(\n        self, it: Instance | CallableType | TypeType | Overloaded, context: Context\n    ) -> Type:\n        raise NotImplementedError\n\n    @abstractmethod\n    @contextmanager\n    def checking_await_set(self) -> Iterator[None]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def get_precise_awaitable_type(self, typ: Type, local_errors: ErrorWatcher) -> Type | None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def add_any_attribute_to_type(self, typ: Type, name: str) -> Type:\n        raise NotImplementedError\n\n    @abstractmethod\n    def is_defined_in_stub(self, typ: Instance, /) -> bool:\n        raise NotImplementedError\n\n\nclass CheckerScope:\n    # We keep two stacks combined, to maintain the relative order\n    stack: list[TypeInfo | FuncItem | MypyFile]\n\n    def __init__(self, module: MypyFile) -> None:\n        self.stack = [module]\n\n    def current_function(self) -> FuncItem | None:\n        for e in reversed(self.stack):\n            if isinstance(e, FuncItem):\n                return e\n        return None\n\n    def top_level_function(self) -> FuncItem | None:\n        \"\"\"Return top-level non-lambda function.\"\"\"\n        for e in self.stack:\n            if isinstance(e, FuncItem) and not isinstance(e, LambdaExpr):\n                return e\n        return None\n\n    def active_class(self) -> TypeInfo | None:\n        if isinstance(self.stack[-1], TypeInfo):\n            return self.stack[-1]\n        return None\n\n    def enclosing_class(self, func: FuncItem | None = None) -> TypeInfo | None:\n        \"\"\"Is there a class *directly* enclosing this function?\"\"\"\n        func = func or self.current_function()\n        assert func, \"This method must be called from inside a function\"\n        index = self.stack.index(func)\n        assert index, \"CheckerScope stack must always start with a module\"\n        enclosing = self.stack[index - 1]\n        if isinstance(enclosing, TypeInfo):\n            return enclosing\n        return None\n\n    def active_self_type(self) -> Instance | TupleType | None:\n        \"\"\"An instance or tuple type representing the current class.\n\n        This returns None unless we are in class body or in a method.\n        In particular, inside a function nested in method this returns None.\n        \"\"\"\n        info = self.active_class()\n        if not info and self.current_function():\n            info = self.enclosing_class()\n        if info:\n            return fill_typevars(info)\n        return None\n\n    def current_self_type(self) -> Instance | TupleType | None:\n        \"\"\"Same as active_self_type() but handle functions nested in methods.\"\"\"\n        for item in reversed(self.stack):\n            if isinstance(item, TypeInfo):\n                return fill_typevars(item)\n        return None\n\n    def is_top_level(self) -> bool:\n        \"\"\"Is current scope top-level (no classes or functions)?\"\"\"\n        return len(self.stack) == 1\n\n    @contextmanager\n    def push_function(self, item: FuncItem) -> Iterator[None]:\n        self.stack.append(item)\n        yield\n        self.stack.pop()\n\n    @contextmanager\n    def push_class(self, info: TypeInfo) -> Iterator[None]:\n        self.stack.append(info)\n        yield\n        self.stack.pop()\n"
  },
  {
    "path": "mypy/checker_state.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom typing import Final\n\nfrom mypy.checker_shared import TypeCheckerSharedApi\n\n# This is global mutable state. Don't add anything here unless there's a very\n# good reason.\n\n\nclass TypeCheckerState:\n    # Wrap this in a class since it's faster that using a module-level attribute.\n\n    def __init__(self, type_checker: TypeCheckerSharedApi | None) -> None:\n        # Value varies by file being processed\n        self.type_checker = type_checker\n\n    @contextmanager\n    def set(self, value: TypeCheckerSharedApi) -> Iterator[None]:\n        saved = self.type_checker\n        self.type_checker = value\n        try:\n            yield\n        finally:\n            self.type_checker = saved\n\n\nchecker_state: Final = TypeCheckerState(type_checker=None)\n"
  },
  {
    "path": "mypy/checkexpr.py",
    "content": "\"\"\"Expression type checker. This file is conceptually part of TypeChecker.\"\"\"\n\nfrom __future__ import annotations\n\nimport enum\nimport itertools\nimport time\nfrom collections import defaultdict\nfrom collections.abc import Callable, Iterable, Iterator, Sequence\nfrom contextlib import contextmanager, nullcontext\nfrom typing import ClassVar, Final, TypeAlias as _TypeAlias, cast, overload\nfrom typing_extensions import assert_never\n\nimport mypy.checker\nimport mypy.errorcodes as codes\nfrom mypy import applytype, erasetype, join, message_registry, nodes, operators, types\nfrom mypy.argmap import ArgTypeExpander, map_actuals_to_formals, map_formals_to_actuals\nfrom mypy.checker_shared import ExpressionCheckerSharedApi\nfrom mypy.checkmember import analyze_member_access, has_operator\nfrom mypy.checkstrformat import StringFormatterChecker\nfrom mypy.constant_fold import constant_fold_expr\nfrom mypy.erasetype import erase_type, remove_instance_last_known_values, replace_meta_vars\nfrom mypy.errors import ErrorInfo, ErrorWatcher, report_internal_error\nfrom mypy.expandtype import (\n    expand_type,\n    expand_type_by_instance,\n    freshen_all_functions_type_vars,\n    freshen_function_type_vars,\n)\nfrom mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type\nfrom mypy.infer import ArgumentInferContext, infer_function_type_arguments, infer_type_arguments\nfrom mypy.literals import literal\nfrom mypy.lookup import lookup_fully_qualified\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.meet import is_overlapping_types, narrow_declared_type\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.messages import MessageBuilder, format_type\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    IMPLICITLY_ABSTRACT,\n    LAMBDA_NAME,\n    LITERAL_TYPE,\n    REVEAL_LOCALS,\n    REVEAL_TYPE,\n    UNBOUND_IMPORTED,\n    ArgKind,\n    AssertTypeExpr,\n    AssignmentExpr,\n    AwaitExpr,\n    BytesExpr,\n    CallExpr,\n    CastExpr,\n    ComparisonExpr,\n    ComplexExpr,\n    ConditionalExpr,\n    Context,\n    Decorator,\n    DictExpr,\n    DictionaryComprehension,\n    EllipsisExpr,\n    EnumCallExpr,\n    Expression,\n    FloatExpr,\n    FuncDef,\n    GeneratorExpr,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    MaybeTypeExpression,\n    MemberExpr,\n    MypyFile,\n    NamedTupleExpr,\n    NameExpr,\n    NewTypeExpr,\n    NotParsed,\n    OpExpr,\n    OverloadedFuncDef,\n    ParamSpecExpr,\n    PlaceholderNode,\n    PromoteExpr,\n    RefExpr,\n    RevealExpr,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    StrExpr,\n    SuperExpr,\n    SymbolNode,\n    SymbolTableNode,\n    TemplateStrExpr,\n    TempNode,\n    TupleExpr,\n    TypeAlias,\n    TypeAliasExpr,\n    TypeApplication,\n    TypedDictExpr,\n    TypeFormExpr,\n    TypeInfo,\n    TypeVarExpr,\n    TypeVarLikeExpr,\n    TypeVarTupleExpr,\n    UnaryExpr,\n    Var,\n    YieldExpr,\n    YieldFromExpr,\n    get_member_expr_fullname,\n)\nfrom mypy.options import PRECISE_TUPLE_TYPES\nfrom mypy.plugin import (\n    FunctionContext,\n    FunctionSigContext,\n    MethodContext,\n    MethodSigContext,\n    Plugin,\n)\nfrom mypy.semanal_enum import ENUM_BASES\nfrom mypy.state import state\nfrom mypy.subtypes import (\n    covers_at_runtime,\n    find_member,\n    is_equivalent,\n    is_same_type,\n    is_subtype,\n    non_method_protocol_members,\n)\nfrom mypy.traverser import (\n    all_name_and_member_expressions,\n    has_await_expression,\n    has_str_expression,\n)\nfrom mypy.tvar_scope import TypeVarLikeScope\nfrom mypy.typeanal import (\n    TypeAnalyser,\n    check_for_explicit_any,\n    fix_instance,\n    has_any_from_unimported_type,\n    instantiate_type_alias,\n    make_optional_type,\n    set_any_tvars,\n    validate_instance,\n)\nfrom mypy.typeops import (\n    callable_type,\n    custom_special_method,\n    erase_to_union_or_bound,\n    false_only,\n    fixup_partial_type,\n    freeze_all_type_vars,\n    function_type,\n    get_all_type_vars,\n    get_type_vars,\n    is_literal_type_like,\n    make_simplified_union,\n    true_only,\n    try_expanding_sum_type_to_union,\n    try_getting_str_literals,\n    tuple_fallback,\n    type_object_type,\n)\nfrom mypy.types import (\n    LITERAL_TYPE_NAMES,\n    TUPLE_LIKE_INSTANCE_NAMES,\n    AnyType,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    ExtraAttrs,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    LiteralValue,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecFlavor,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    flatten_nested_tuples,\n    flatten_nested_unions,\n    get_proper_type,\n    get_proper_types,\n    has_recursive_types,\n    has_type_vars,\n    is_named_instance,\n    split_with_prefix_and_suffix,\n)\nfrom mypy.types_utils import (\n    is_generic_instance,\n    is_overlapping_none,\n    is_self_type_like,\n    remove_optional,\n)\nfrom mypy.typestate import type_state\nfrom mypy.typevars import fill_typevars\nfrom mypy.visitor import ExpressionVisitor\n\n# Type of callback user for checking individual function arguments. See\n# check_args() below for details.\nArgChecker: _TypeAlias = Callable[\n    [Type, Type, ArgKind, Type, int, int, CallableType, Type | None, Context, Context], None\n]\n\n# Maximum nesting level for math union in overloads, setting this to large values\n# may cause performance issues. The reason is that although union math algorithm we use\n# nicely captures most corner cases, its worst case complexity is exponential,\n# see https://github.com/python/mypy/pull/5255#discussion_r196896335 for discussion.\nMAX_UNIONS: Final = 5\n\n\n# Types considered safe for comparisons with --strict-equality due to known behaviour of __eq__.\n# NOTE: All these types are subtypes of AbstractSet.\nOVERLAPPING_TYPES_ALLOWLIST: Final = [\n    \"builtins.set\",\n    \"builtins.frozenset\",\n    \"typing.KeysView\",\n    \"typing.ItemsView\",\n    \"builtins._dict_keys\",\n    \"builtins._dict_items\",\n    \"_collections_abc.dict_keys\",\n    \"_collections_abc.dict_items\",\n]\nOVERLAPPING_BYTES_ALLOWLIST: Final = {\n    \"builtins.bytes\",\n    \"builtins.bytearray\",\n    \"builtins.memoryview\",\n}\n\n\nclass TooManyUnions(Exception):\n    \"\"\"Indicates that we need to stop splitting unions in an attempt\n    to match an overload in order to save performance.\n    \"\"\"\n\n\ndef allow_fast_container_literal(t: Type) -> bool:\n    if isinstance(t, TypeAliasType) and t.is_recursive:\n        return False\n    t = get_proper_type(t)\n    return isinstance(t, Instance) or (\n        isinstance(t, TupleType) and all(allow_fast_container_literal(it) for it in t.items)\n    )\n\n\nclass Finished(Exception):\n    \"\"\"Raised if we can terminate overload argument check early (no match).\"\"\"\n\n\n@enum.unique\nclass UseReverse(enum.Enum):\n    \"\"\"Used in `visit_op_expr` to enable or disable reverse method checks.\"\"\"\n\n    DEFAULT = 0\n    ALWAYS = 1\n    NEVER = 2\n\n\nUSE_REVERSE_DEFAULT: Final = UseReverse.DEFAULT\nUSE_REVERSE_ALWAYS: Final = UseReverse.ALWAYS\nUSE_REVERSE_NEVER: Final = UseReverse.NEVER\n\n\nclass ExpressionChecker(ExpressionVisitor[Type], ExpressionCheckerSharedApi):\n    \"\"\"Expression type checker.\n\n    This class works closely together with checker.TypeChecker.\n    \"\"\"\n\n    # Some services are provided by a TypeChecker instance.\n    chk: mypy.checker.TypeChecker\n    # This is shared with TypeChecker, but stored also here for convenience.\n    msg: MessageBuilder\n    # Type context for type inference\n    type_context: list[Type | None]\n\n    strfrm_checker: StringFormatterChecker\n    plugin: Plugin\n\n    _arg_infer_context_cache: ArgumentInferContext | None\n\n    def __init__(\n        self,\n        chk: mypy.checker.TypeChecker,\n        msg: MessageBuilder,\n        plugin: Plugin,\n        per_line_checking_time_ns: dict[int, int],\n    ) -> None:\n        \"\"\"Construct an expression type checker.\"\"\"\n        self.chk = chk\n        self.msg = msg\n        self.plugin = plugin\n        self.per_line_checking_time_ns = per_line_checking_time_ns\n        self.collect_line_checking_stats = chk.options.line_checking_stats is not None\n        # Are we already visiting some expression? This is used to avoid double counting\n        # time for nested expressions.\n        self.in_expression = False\n        self.type_context = [None]\n\n        # Temporary overrides for expression types. This is currently\n        # used by the union math in overloads.\n        # TODO: refactor this to use a pattern similar to one in\n        # multiassign_from_union, or maybe even combine the two?\n        self.type_overrides: dict[Expression, Type] = {}\n        self.strfrm_checker = StringFormatterChecker(self.chk, self.msg)\n\n        # Callee in a call expression is in some sense both runtime context and\n        # type context, because we support things like C[int](...). Store information\n        # on whether current expression is a callee, to give better error messages\n        # related to type context.\n        self.is_callee = False\n        type_state.infer_polymorphic = not self.chk.options.old_type_inference\n\n        self._arg_infer_context_cache = None\n        self.expr_cache: dict[\n            tuple[Expression, Type | None],\n            tuple[int, Type, list[ErrorInfo], dict[Expression, Type]],\n        ] = {}\n        self.in_lambda_expr = False\n\n        self._literal_true: Instance | None = None\n        self._literal_false: Instance | None = None\n\n    def reset(self) -> None:\n        self.expr_cache.clear()\n\n    def visit_name_expr(self, e: NameExpr) -> Type:\n        \"\"\"Type check a name expression.\n\n        It can be of any kind: local, member or global.\n        \"\"\"\n        result = self.analyze_ref_expr(e)\n        narrowed = self.narrow_type_from_binder(e, result)\n        self.chk.check_deprecated(e.node, e)\n        return narrowed\n\n    def analyze_ref_expr(self, e: RefExpr, lvalue: bool = False) -> Type:\n        result: Type | None = None\n        node = e.node\n\n        if isinstance(e, NameExpr) and e.is_special_form:\n            # A special form definition, nothing to check here.\n            return AnyType(TypeOfAny.special_form)\n\n        if isinstance(node, Var):\n            # Variable reference.\n            result = self.analyze_var_ref(node, e)\n            if isinstance(result, PartialType):\n                result = self.chk.handle_partial_var_type(result, lvalue, node, e)\n        elif isinstance(node, Decorator):\n            result = self.analyze_var_ref(node.var, e)\n        elif isinstance(node, OverloadedFuncDef):\n            if node.type is None:\n                if self.chk.in_checked_function() and node.items:\n                    self.chk.handle_cannot_determine_type(node.name, e)\n                result = AnyType(TypeOfAny.from_error)\n            else:\n                result = node.type\n        elif isinstance(node, (FuncDef, TypeInfo, TypeAlias, MypyFile, TypeVarLikeExpr)):\n            result = self.analyze_static_reference(node, e, e.is_alias_rvalue or lvalue)\n        else:\n            if isinstance(node, PlaceholderNode):\n                assert False, f\"PlaceholderNode {node.fullname!r} leaked to checker\"\n            # Unknown reference; use any type implicitly to avoid\n            # generating extra type errors.\n            result = AnyType(TypeOfAny.from_error)\n        if isinstance(node, TypeInfo):\n            if isinstance(result, CallableType) and isinstance(  # type: ignore[misc]\n                result.ret_type, Instance\n            ):\n                # We need to set correct line and column\n                # TODO: always do this in type_object_type by passing the original context\n                result.ret_type.line = e.line\n                result.ret_type.column = e.column\n            if is_type_type_context(self.type_context[-1]):\n                # This is the type in a type[] expression, so substitute type\n                # variables with Any.\n                result = erasetype.erase_typevars(result)\n        assert result is not None\n        return result\n\n    def analyze_static_reference(\n        self,\n        node: SymbolNode,\n        ctx: Context,\n        is_lvalue: bool,\n        *,\n        include_modules: bool = True,\n        suppress_errors: bool = False,\n    ) -> Type:\n        \"\"\"\n        This is the version of analyze_ref_expr() that doesn't do any deferrals.\n\n        This function can be used by member access to \"static\" attributes. For example,\n        when accessing module attributes in protocol checks, or accessing attributes of\n        special kinds (like TypeAlias, TypeInfo, etc.) on an instance or class object.\n        # TODO: merge with analyze_ref_expr() when we are confident about performance.\n        \"\"\"\n        if isinstance(node, (Var, Decorator, OverloadedFuncDef)):\n            return node.type or AnyType(TypeOfAny.special_form)\n        elif isinstance(node, FuncDef):\n            return function_type(node, self.named_type(\"builtins.function\"))\n        elif isinstance(node, TypeInfo):\n            # Reference to a type object.\n            if node.typeddict_type:\n                # We special-case TypedDict, because they don't define any constructor.\n                return self.typeddict_callable(node)\n            elif node.fullname == \"types.NoneType\":\n                # We special case NoneType, because its stub definition is not related to None.\n                return TypeType(NoneType())\n            else:\n                return type_object_type(node, self.named_type)\n        elif isinstance(node, TypeAlias):\n            # Something that refers to a type alias appears in runtime context.\n            # Note that we suppress bogus errors for alias redefinitions,\n            # they are already reported in semanal.py.\n            with self.msg.filter_errors() if suppress_errors else nullcontext():\n                return self.alias_type_in_runtime_context(\n                    node, ctx=ctx, alias_definition=is_lvalue\n                )\n        elif isinstance(node, TypeVarExpr):\n            return self.named_type(\"typing.TypeVar\")\n        elif isinstance(node, (ParamSpecExpr, TypeVarTupleExpr)):\n            return self.object_type()\n        elif isinstance(node, MypyFile):\n            # Reference to a module object.\n            return self.module_type(node) if include_modules else AnyType(TypeOfAny.special_form)\n        return AnyType(TypeOfAny.from_error)\n\n    def analyze_var_ref(self, var: Var, context: Context) -> Type:\n        if var.type:\n            var_type = get_proper_type(var.type)\n            if isinstance(var_type, Instance):\n                if var.fullname == \"typing.Any\":\n                    # The typeshed type is 'object'; give a more useful type in runtime context\n                    return self.named_type(\"typing._SpecialForm\")\n                if self.is_literal_context() and var_type.last_known_value is not None:\n                    return var_type.last_known_value\n                if var.name in {\"True\", \"False\"}:\n                    return self.infer_literal_expr_type(var.name == \"True\", \"builtins.bool\")\n            return var.type\n        else:\n            if not var.is_ready and self.chk.in_checked_function():\n                self.chk.handle_cannot_determine_type(var.name, context)\n            # Implicit 'Any' type.\n            return AnyType(TypeOfAny.special_form)\n\n    def module_type(self, node: MypyFile) -> Instance:\n        try:\n            result = self.named_type(\"types.ModuleType\")\n        except KeyError:\n            # In test cases might 'types' may not be available.\n            # Fall back to a dummy 'object' type instead to\n            # avoid a crash.\n            # Make a copy so that we don't set extra_attrs (below) on a shared instance.\n            result = self.named_type(\"builtins.object\").copy_modified()\n        module_attrs: dict[str, Type] = {}\n        immutable = set()\n        for name, n in node.names.items():\n            if not n.module_public:\n                continue\n            if isinstance(n.node, Var) and n.node.is_final:\n                immutable.add(name)\n            if n.node is None:\n                module_attrs[name] = AnyType(TypeOfAny.from_error)\n            else:\n                # TODO: what to do about nested module references?\n                # They are non-trivial because there may be import cycles.\n                module_attrs[name] = self.analyze_static_reference(\n                    n.node, n.node, False, include_modules=False, suppress_errors=True\n                )\n        result.extra_attrs = ExtraAttrs(module_attrs, immutable, node.fullname)\n        return result\n\n    def visit_call_expr(self, e: CallExpr, allow_none_return: bool = False) -> Type:\n        \"\"\"Type check a call expression.\"\"\"\n        if e.analyzed:\n            if isinstance(e.analyzed, NamedTupleExpr) and not e.analyzed.is_typed:\n                # Type check the arguments, but ignore the results. This relies\n                # on the typeshed stubs to type check the arguments.\n                self.visit_call_expr_inner(e)\n            # It's really a special form that only looks like a call.\n            return self.accept(e.analyzed, self.type_context[-1])\n        return self.visit_call_expr_inner(e, allow_none_return=allow_none_return)\n\n    def refers_to_typeddict(self, base: Expression) -> bool:\n        if not isinstance(base, RefExpr):\n            return False\n        if isinstance(base.node, TypeInfo) and base.node.typeddict_type is not None:\n            # Direct reference.\n            return True\n        return isinstance(base.node, TypeAlias) and isinstance(\n            get_proper_type(base.node.target), TypedDictType\n        )\n\n    def visit_call_expr_inner(self, e: CallExpr, allow_none_return: bool = False) -> Type:\n        if (\n            self.refers_to_typeddict(e.callee)\n            or isinstance(e.callee, IndexExpr)\n            and self.refers_to_typeddict(e.callee.base)\n        ):\n            typeddict_callable = get_proper_type(self.accept(e.callee, is_callee=True))\n            if isinstance(typeddict_callable, CallableType):\n                typeddict_type = get_proper_type(typeddict_callable.ret_type)\n                assert isinstance(typeddict_type, TypedDictType)\n                return self.check_typeddict_call(\n                    typeddict_type, e.arg_kinds, e.arg_names, e.args, e, typeddict_callable\n                )\n        if (\n            isinstance(e.callee, NameExpr)\n            and e.callee.name in (\"isinstance\", \"issubclass\")\n            and len(e.args) == 2\n        ):\n            for typ in mypy.checker.flatten(e.args[1]):\n                node = None\n                if isinstance(typ, NameExpr):\n                    try:\n                        node = self.chk.lookup_qualified(typ.name)\n                    except KeyError:\n                        # Undefined names should already be reported in semantic analysis.\n                        pass\n                if is_expr_literal_type(typ):\n                    self.msg.cannot_use_function_with_type(e.callee.name, \"Literal\", e)\n                    continue\n                if node and isinstance(node.node, TypeAlias):\n                    target = get_proper_type(node.node.target)\n                    if isinstance(target, AnyType):\n                        self.msg.cannot_use_function_with_type(e.callee.name, \"Any\", e)\n                        continue\n                    if isinstance(target, NoneType):\n                        continue\n                if (\n                    isinstance(typ, IndexExpr)\n                    and isinstance(typ.analyzed, (TypeApplication, TypeAliasExpr))\n                ) or (\n                    isinstance(typ, NameExpr)\n                    and node\n                    and isinstance(node.node, TypeAlias)\n                    and not node.node.no_args\n                    and not (\n                        isinstance(union_target := get_proper_type(node.node.target), UnionType)\n                        and (\n                            union_target.uses_pep604_syntax\n                            or self.chk.options.python_version >= (3, 10)\n                        )\n                    )\n                ):\n                    self.msg.type_arguments_not_allowed(e)\n                if isinstance(typ, RefExpr) and isinstance(typ.node, TypeInfo):\n                    if typ.node.typeddict_type:\n                        self.msg.cannot_use_function_with_type(e.callee.name, \"TypedDict\", e)\n                    elif typ.node.is_newtype:\n                        self.msg.cannot_use_function_with_type(e.callee.name, \"NewType\", e)\n        self.try_infer_partial_type(e)\n        type_context = None\n        if isinstance(e.callee, LambdaExpr):\n            formal_to_actual = map_actuals_to_formals(\n                e.arg_kinds,\n                e.arg_names,\n                e.callee.arg_kinds,\n                e.callee.arg_names,\n                lambda i: self.accept(e.args[i]),\n            )\n\n            arg_types = [\n                join.join_type_list([self.accept(e.args[j]) for j in formal_to_actual[i]])\n                for i in range(len(e.callee.arg_kinds))\n            ]\n            type_context = CallableType(\n                arg_types,\n                e.callee.arg_kinds,\n                e.callee.arg_names,\n                ret_type=self.object_type(),\n                fallback=self.named_type(\"builtins.function\"),\n            )\n        callee_type = get_proper_type(\n            self.accept(e.callee, type_context, always_allow_any=True, is_callee=True)\n        )\n\n        # Figure out the full name of the callee for plugin lookup.\n        object_type = None\n        member = None\n        fullname = None\n        if isinstance(e.callee, RefExpr):\n            # There are two special cases where plugins might act:\n            # * A \"static\" reference/alias to a class or function;\n            #   get_function_hook() will be invoked for these.\n            fullname = e.callee.fullname or None\n            if isinstance(e.callee.node, TypeAlias):\n                target = get_proper_type(e.callee.node.target)\n                if isinstance(target, Instance):\n                    fullname = target.type.fullname\n            # * Call to a method on object that has a full name (see\n            #   method_fullname() for details on supported objects);\n            #   get_method_hook() and get_method_signature_hook() will\n            #   be invoked for these.\n            if (\n                not fullname\n                and isinstance(e.callee, MemberExpr)\n                and self.chk.has_type(e.callee.expr)\n            ):\n                member = e.callee.name\n                object_type = self.chk.lookup_type(e.callee.expr)\n\n        if (\n            self.chk.options.disallow_untyped_calls\n            and self.chk.in_checked_function()\n            and isinstance(callee_type, CallableType)\n            and callee_type.implicit\n            and callee_type.name != LAMBDA_NAME\n        ):\n            if fullname is None and member is not None:\n                assert object_type is not None\n                fullname = self.method_fullname(object_type, member)\n            if not fullname or not any(\n                fullname == p or fullname.startswith(f\"{p}.\")\n                for p in self.chk.options.untyped_calls_exclude\n            ):\n                self.msg.untyped_function_call(callee_type, e)\n\n        ret_type = self.check_call_expr_with_callee_type(\n            callee_type, e, fullname, object_type, member\n        )\n        if isinstance(e.callee, RefExpr) and len(e.args) == 2:\n            if e.callee.fullname in (\"builtins.isinstance\", \"builtins.issubclass\"):\n                self.check_runtime_protocol_test(e)\n            if e.callee.fullname == \"builtins.issubclass\":\n                self.check_protocol_issubclass(e)\n        if isinstance(e.callee, MemberExpr) and e.callee.name == \"format\":\n            self.check_str_format_call(e)\n        ret_type = get_proper_type(ret_type)\n        if isinstance(ret_type, UnionType):\n            ret_type = make_simplified_union(ret_type.items)\n        if isinstance(ret_type, UninhabitedType) and not ret_type.ambiguous:\n            self.chk.binder.unreachable()\n        # Warn on calls to functions that always return None. The check\n        # of ret_type is both a common-case optimization and prevents reporting\n        # the error in dynamic functions (where it will be Any).\n        if (\n            not allow_none_return\n            and isinstance(ret_type, NoneType)\n            and self.always_returns_none(e.callee)\n        ):\n            self.chk.msg.does_not_return_value(callee_type, e)\n        return ret_type\n\n    def check_str_format_call(self, e: CallExpr) -> None:\n        \"\"\"More precise type checking for str.format() calls on literals and folded constants.\"\"\"\n        assert isinstance(e.callee, MemberExpr)\n        format_value = None\n        folded_callee_expr = constant_fold_expr(e.callee.expr, \"<unused>\")\n        if isinstance(folded_callee_expr, str):\n            format_value = folded_callee_expr\n        elif self.chk.has_type(e.callee.expr):\n            typ = get_proper_type(self.chk.lookup_type(e.callee.expr))\n            if (\n                isinstance(typ, Instance)\n                and typ.type.is_enum\n                and isinstance(typ.last_known_value, LiteralType)\n                and isinstance(typ.last_known_value.value, str)\n            ):\n                value_type = typ.type.names[typ.last_known_value.value].type\n                if isinstance(value_type, Type):\n                    typ = get_proper_type(value_type)\n            base_typ = try_getting_literal(typ)\n            if isinstance(base_typ, LiteralType) and isinstance(base_typ.value, str):\n                format_value = base_typ.value\n        if format_value is not None:\n            self.strfrm_checker.check_str_format_call(e, format_value)\n\n    def method_fullname(self, object_type: Type, method_name: str) -> str | None:\n        \"\"\"Convert a method name to a fully qualified name, based on the type of the object that\n        it is invoked on. Return `None` if the name of `object_type` cannot be determined.\n        \"\"\"\n        object_type = get_proper_type(object_type)\n\n        if isinstance(object_type, CallableType) and object_type.is_type_obj():\n            # For class method calls, object_type is a callable representing the class object.\n            # We \"unwrap\" it to a regular type, as the class/instance method difference doesn't\n            # affect the fully qualified name.\n            object_type = get_proper_type(object_type.ret_type)\n        elif isinstance(object_type, TypeType):\n            object_type = object_type.item\n\n        type_name = None\n        if isinstance(object_type, Instance):\n            type_name = object_type.type.fullname\n        elif isinstance(object_type, (TypedDictType, LiteralType)):\n            info = object_type.fallback.type.get_containing_type_info(method_name)\n            type_name = info.fullname if info is not None else None\n        elif isinstance(object_type, TupleType):\n            type_name = tuple_fallback(object_type).type.fullname\n\n        if type_name:\n            return f\"{type_name}.{method_name}\"\n        else:\n            return None\n\n    def always_returns_none(self, node: Expression) -> bool:\n        \"\"\"Check if `node` refers to something explicitly annotated as only returning None.\"\"\"\n        if isinstance(node, RefExpr):\n            if self.defn_returns_none(node.node):\n                return True\n        if isinstance(node, MemberExpr) and node.node is None:  # instance or class attribute\n            typ = get_proper_type(self.chk.lookup_type(node.expr))\n            if isinstance(typ, Instance):\n                info = typ.type\n            elif isinstance(typ, CallableType) and typ.is_type_obj():\n                ret_type = get_proper_type(typ.ret_type)\n                if isinstance(ret_type, Instance):\n                    info = ret_type.type\n                else:\n                    return False\n            else:\n                return False\n            sym = info.get(node.name)\n            if sym and self.defn_returns_none(sym.node):\n                return True\n        return False\n\n    def defn_returns_none(self, defn: SymbolNode | None) -> bool:\n        \"\"\"Check if `defn` can _only_ return None.\"\"\"\n        if isinstance(defn, FuncDef):\n            return isinstance(defn.type, CallableType) and isinstance(\n                get_proper_type(defn.type.ret_type), NoneType\n            )\n        if isinstance(defn, OverloadedFuncDef):\n            return all(self.defn_returns_none(item) for item in defn.items)\n        if isinstance(defn, Var):\n            typ = get_proper_type(defn.type)\n            if (\n                not defn.is_inferred\n                and isinstance(typ, CallableType)\n                and isinstance(get_proper_type(typ.ret_type), NoneType)\n            ):\n                return True\n            if isinstance(typ, Instance):\n                sym = typ.type.get(\"__call__\")\n                if sym and self.defn_returns_none(sym.node):\n                    return True\n        return False\n\n    def check_runtime_protocol_test(self, e: CallExpr) -> None:\n        for expr in mypy.checker.flatten(e.args[1]):\n            tp = get_proper_type(self.chk.lookup_type(expr))\n            if (\n                isinstance(tp, FunctionLike)\n                and tp.is_type_obj()\n                and tp.type_object().is_protocol\n                and not tp.type_object().runtime_protocol\n            ):\n                self.chk.fail(message_registry.RUNTIME_PROTOCOL_EXPECTED, e)\n\n    def check_protocol_issubclass(self, e: CallExpr) -> None:\n        for expr in mypy.checker.flatten(e.args[1]):\n            tp = get_proper_type(self.chk.lookup_type(expr))\n            if isinstance(tp, FunctionLike) and tp.is_type_obj() and tp.type_object().is_protocol:\n                attr_members = non_method_protocol_members(tp.type_object())\n                if attr_members:\n                    self.chk.msg.report_non_method_protocol(tp.type_object(), attr_members, e)\n\n    def check_typeddict_call(\n        self,\n        callee: TypedDictType,\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None],\n        args: list[Expression],\n        context: Context,\n        orig_callee: Type | None,\n    ) -> Type:\n        if args and all(ak in (ARG_NAMED, ARG_STAR2) for ak in arg_kinds):\n            # ex: Point(x=42, y=1337, **extras)\n            # This is a bit ugly, but this is a price for supporting all possible syntax\n            # variants for TypedDict constructors.\n            kwargs = zip([StrExpr(n) if n is not None else None for n in arg_names], args)\n            result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee)\n            if result is not None:\n                validated_kwargs, always_present_keys = result\n                return self.check_typeddict_call_with_kwargs(\n                    callee, validated_kwargs, context, orig_callee, always_present_keys\n                )\n            return AnyType(TypeOfAny.from_error)\n\n        if len(args) == 1 and arg_kinds[0] == ARG_POS:\n            unique_arg = args[0]\n            if isinstance(unique_arg, DictExpr):\n                # ex: Point({'x': 42, 'y': 1337, **extras})\n                return self.check_typeddict_call_with_dict(\n                    callee, unique_arg.items, context, orig_callee\n                )\n            if isinstance(unique_arg, CallExpr) and isinstance(unique_arg.analyzed, DictExpr):\n                # ex: Point(dict(x=42, y=1337, **extras))\n                return self.check_typeddict_call_with_dict(\n                    callee, unique_arg.analyzed.items, context, orig_callee\n                )\n\n        if not args:\n            # ex: EmptyDict()\n            return self.check_typeddict_call_with_kwargs(callee, {}, context, orig_callee, set())\n\n        self.chk.fail(message_registry.INVALID_TYPEDDICT_ARGS, context)\n        return AnyType(TypeOfAny.from_error)\n\n    def validate_typeddict_kwargs(\n        self, kwargs: Iterable[tuple[Expression | None, Expression]], callee: TypedDictType\n    ) -> tuple[dict[str, list[Expression]], set[str]] | None:\n        # All (actual or mapped from ** unpacks) expressions that can match given key.\n        result = defaultdict(list)\n        # Keys that are guaranteed to be present no matter what (e.g. for all items of a union)\n        always_present_keys = set()\n        # Indicates latest encountered ** unpack among items.\n        last_star_found = None\n\n        for item_name_expr, item_arg in kwargs:\n            if item_name_expr:\n                key_type = self.accept(item_name_expr)\n                values = try_getting_str_literals(item_name_expr, key_type)\n                literal_value = None\n                if values and len(values) == 1:\n                    literal_value = values[0]\n                if literal_value is None:\n                    key_context = item_name_expr or item_arg\n                    self.chk.fail(\n                        message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,\n                        key_context,\n                        code=codes.LITERAL_REQ,\n                    )\n                    return None\n                else:\n                    # A directly present key unconditionally shadows all previously found\n                    # values from ** items.\n                    # TODO: for duplicate keys, type-check all values.\n                    result[literal_value] = [item_arg]\n                    always_present_keys.add(literal_value)\n            else:\n                last_star_found = item_arg\n                if not self.validate_star_typeddict_item(\n                    item_arg, callee, result, always_present_keys\n                ):\n                    return None\n        if self.chk.options.extra_checks and last_star_found is not None:\n            absent_keys = []\n            for key in callee.items:\n                if key not in callee.required_keys and key not in result:\n                    absent_keys.append(key)\n            if absent_keys:\n                # Having an optional key not explicitly declared by a ** unpacked\n                # TypedDict is unsafe, it may be an (incompatible) subtype at runtime.\n                # TODO: catch the cases where a declared key is overridden by a subsequent\n                # ** item without it (and not again overridden with complete ** item).\n                self.msg.non_required_keys_absent_with_star(absent_keys, last_star_found)\n        return result, always_present_keys\n\n    def validate_star_typeddict_item(\n        self,\n        item_arg: Expression,\n        callee: TypedDictType,\n        result: dict[str, list[Expression]],\n        always_present_keys: set[str],\n    ) -> bool:\n        \"\"\"Update keys/expressions from a ** expression in TypedDict constructor.\n\n        Note `result` and `always_present_keys` are updated in place. Return true if the\n        expression `item_arg` may valid in `callee` TypedDict context.\n        \"\"\"\n        inferred = get_proper_type(self.accept(item_arg, type_context=callee))\n        possible_tds = []\n        if isinstance(inferred, TypedDictType):\n            possible_tds = [inferred]\n        elif isinstance(inferred, UnionType):\n            for item in get_proper_types(inferred.relevant_items()):\n                if isinstance(item, TypedDictType):\n                    possible_tds.append(item)\n                elif not self.valid_unpack_fallback_item(item):\n                    self.msg.unsupported_target_for_star_typeddict(item, item_arg)\n                    return False\n        elif not self.valid_unpack_fallback_item(inferred):\n            self.msg.unsupported_target_for_star_typeddict(inferred, item_arg)\n            return False\n        all_keys: set[str] = set()\n        for td in possible_tds:\n            all_keys |= td.items.keys()\n        for key in all_keys:\n            arg = TempNode(\n                UnionType.make_union([td.items[key] for td in possible_tds if key in td.items])\n            )\n            arg.set_line(item_arg)\n            if all(key in td.required_keys for td in possible_tds):\n                always_present_keys.add(key)\n                # Always present keys override previously found values. This is done\n                # to support use cases like `Config({**defaults, **overrides})`, where\n                # some `overrides` types are narrower that types in `defaults`, and\n                # former are too wide for `Config`.\n                if result[key]:\n                    first = result[key][0]\n                    if not isinstance(first, TempNode):\n                        # We must always preserve any non-synthetic values, so that\n                        # we will accept them even if they are shadowed.\n                        result[key] = [first, arg]\n                    else:\n                        result[key] = [arg]\n                else:\n                    result[key] = [arg]\n            else:\n                # If this key is not required at least in some item of a union\n                # it may not shadow previous item, so we need to type check both.\n                result[key].append(arg)\n        return True\n\n    def valid_unpack_fallback_item(self, typ: ProperType) -> bool:\n        if isinstance(typ, AnyType):\n            return True\n        if not isinstance(typ, Instance) or not typ.type.has_base(\"typing.Mapping\"):\n            return False\n        mapped = map_instance_to_supertype(typ, self.chk.lookup_typeinfo(\"typing.Mapping\"))\n        return all(isinstance(a, AnyType) for a in get_proper_types(mapped.args))\n\n    def match_typeddict_call_with_dict(\n        self,\n        callee: TypedDictType,\n        kwargs: list[tuple[Expression | None, Expression]],\n        context: Context,\n    ) -> bool:\n        result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee)\n        if result is not None:\n            validated_kwargs, _ = result\n            return callee.required_keys <= set(validated_kwargs.keys()) <= set(callee.items.keys())\n        else:\n            return False\n\n    def check_typeddict_call_with_dict(\n        self,\n        callee: TypedDictType,\n        kwargs: list[tuple[Expression | None, Expression]],\n        context: Context,\n        orig_callee: Type | None,\n    ) -> Type:\n        result = self.validate_typeddict_kwargs(kwargs=kwargs, callee=callee)\n        if result is not None:\n            validated_kwargs, always_present_keys = result\n            return self.check_typeddict_call_with_kwargs(\n                callee,\n                kwargs=validated_kwargs,\n                context=context,\n                orig_callee=orig_callee,\n                always_present_keys=always_present_keys,\n            )\n        else:\n            return AnyType(TypeOfAny.from_error)\n\n    def typeddict_callable(self, info: TypeInfo) -> CallableType:\n        \"\"\"Construct a reasonable type for a TypedDict type in runtime context.\n\n        If it appears as a callee, it will be special-cased anyway, e.g. it is\n        also allowed to accept a single positional argument if it is a dict literal.\n\n        Note it is not safe to move this to type_object_type() since it will crash\n        on plugin-generated TypedDicts, that may not have the special_alias.\n        \"\"\"\n        assert info.special_alias is not None\n        target = info.special_alias.target\n        assert isinstance(target, ProperType) and isinstance(target, TypedDictType)\n        return self.typeddict_callable_from_context(target, info.defn.type_vars)\n\n    def typeddict_callable_from_context(\n        self, callee: TypedDictType, variables: Sequence[TypeVarLikeType] | None = None\n    ) -> CallableType:\n        return CallableType(\n            list(callee.items.values()),\n            [\n                ArgKind.ARG_NAMED if name in callee.required_keys else ArgKind.ARG_NAMED_OPT\n                for name in callee.items\n            ],\n            list(callee.items.keys()),\n            callee,\n            self.named_type(\"builtins.type\"),\n            variables=variables,\n            is_bound=True,\n        )\n\n    def check_typeddict_call_with_kwargs(\n        self,\n        callee: TypedDictType,\n        kwargs: dict[str, list[Expression]],\n        context: Context,\n        orig_callee: Type | None,\n        always_present_keys: set[str],\n    ) -> Type:\n        actual_keys = kwargs.keys()\n        if callee.to_be_mutated:\n            assigned_readonly_keys = actual_keys & callee.readonly_keys\n            if assigned_readonly_keys:\n                self.msg.readonly_keys_mutated(assigned_readonly_keys, context=context)\n        if not (\n            callee.required_keys <= always_present_keys and actual_keys <= callee.items.keys()\n        ):\n            if not (actual_keys <= callee.items.keys()):\n                self.msg.unexpected_typeddict_keys(\n                    callee,\n                    expected_keys=[\n                        key\n                        for key in callee.items.keys()\n                        if key in callee.required_keys or key in actual_keys\n                    ],\n                    actual_keys=list(actual_keys),\n                    context=context,\n                )\n            if not (callee.required_keys <= always_present_keys):\n                self.msg.unexpected_typeddict_keys(\n                    callee,\n                    expected_keys=[\n                        key for key in callee.items.keys() if key in callee.required_keys\n                    ],\n                    actual_keys=[\n                        key for key in always_present_keys if key in callee.required_keys\n                    ],\n                    context=context,\n                )\n            if callee.required_keys > actual_keys:\n                # found_set is a sub-set of the required_keys\n                # This means we're missing some keys and as such, we can't\n                # properly type the object\n                return AnyType(TypeOfAny.from_error)\n\n        orig_callee = get_proper_type(orig_callee)\n        if isinstance(orig_callee, CallableType):\n            infer_callee = orig_callee\n        else:\n            # Try reconstructing from type context.\n            if callee.fallback.type.special_alias is not None:\n                infer_callee = self.typeddict_callable(callee.fallback.type)\n            else:\n                # Likely a TypedDict type generated by a plugin.\n                infer_callee = self.typeddict_callable_from_context(callee)\n\n        # We don't show any errors, just infer types in a generic TypedDict type,\n        # a custom error message will be given below, if there are errors.\n        with self.msg.filter_errors(), self.chk.local_type_map:\n            orig_ret_type, _ = self.check_callable_call(\n                infer_callee,\n                # We use first expression for each key to infer type variables of a generic\n                # TypedDict. This is a bit arbitrary, but in most cases will work better than\n                # trying to infer a union or a join.\n                [args[0] for args in kwargs.values()],\n                [ArgKind.ARG_NAMED] * len(kwargs),\n                context,\n                list(kwargs.keys()),\n                None,\n                None,\n                None,\n            )\n\n        ret_type = get_proper_type(orig_ret_type)\n        if not isinstance(ret_type, TypedDictType):\n            # If something went really wrong, type-check call with original type,\n            # this may give a better error message.\n            ret_type = callee\n\n        for item_name, item_expected_type in ret_type.items.items():\n            if item_name in kwargs:\n                item_values = kwargs[item_name]\n                for item_value in item_values:\n                    self.chk.check_simple_assignment(\n                        lvalue_type=item_expected_type,\n                        rvalue=item_value,\n                        context=item_value,\n                        msg=ErrorMessage(\n                            message_registry.INCOMPATIBLE_TYPES.value, code=codes.TYPEDDICT_ITEM\n                        ),\n                        lvalue_name=f'TypedDict item \"{item_name}\"',\n                        rvalue_name=\"expression\",\n                    )\n\n        return orig_ret_type\n\n    def get_partial_self_var(self, expr: MemberExpr) -> Var | None:\n        \"\"\"Get variable node for a partial self attribute.\n\n        If the expression is not a self attribute, or attribute is not variable,\n        or variable is not partial, return None.\n        \"\"\"\n        if not (\n            isinstance(expr.expr, NameExpr)\n            and isinstance(expr.expr.node, Var)\n            and expr.expr.node.is_self\n        ):\n            # Not a self.attr expression.\n            return None\n        info = self.chk.scope.enclosing_class()\n        if not info or expr.name not in info.names:\n            # Don't mess with partial types in superclasses.\n            return None\n        sym = info.names[expr.name]\n        if isinstance(sym.node, Var) and isinstance(sym.node.type, PartialType):\n            return sym.node\n        return None\n\n    # Types and methods that can be used to infer partial types.\n    item_args: ClassVar[dict[str, list[str]]] = {\n        \"builtins.list\": [\"append\"],\n        \"builtins.set\": [\"add\", \"discard\"],\n    }\n    container_args: ClassVar[dict[str, dict[str, list[str]]]] = {\n        \"builtins.list\": {\"extend\": [\"builtins.list\"]},\n        \"builtins.dict\": {\"update\": [\"builtins.dict\"]},\n        \"collections.OrderedDict\": {\"update\": [\"builtins.dict\"]},\n        \"builtins.set\": {\"update\": [\"builtins.set\", \"builtins.list\"]},\n    }\n\n    def try_infer_partial_type(self, e: CallExpr) -> None:\n        \"\"\"Try to make partial type precise from a call.\"\"\"\n        if not isinstance(e.callee, MemberExpr):\n            return\n        callee = e.callee\n        if isinstance(callee.expr, RefExpr):\n            # Call a method with a RefExpr callee, such as 'x.method(...)'.\n            ret = self.get_partial_var(callee.expr)\n            if ret is None:\n                return\n            var, partial_types = ret\n            typ = self.try_infer_partial_value_type_from_call(e, callee.name, var)\n            # Var may be deleted from partial_types in try_infer_partial_value_type_from_call\n            if typ is not None and var in partial_types:\n                self.chk.replace_partial_type(var, typ, partial_types)\n        elif isinstance(callee.expr, IndexExpr) and isinstance(callee.expr.base, RefExpr):\n            # Call 'x[y].method(...)'; may infer type of 'x' if it's a partial defaultdict.\n            if callee.expr.analyzed is not None:\n                return  # A special form\n            base = callee.expr.base\n            index = callee.expr.index\n            ret = self.get_partial_var(base)\n            if ret is None:\n                return\n            var, partial_types = ret\n            partial_type = get_partial_instance_type(var.type)\n            if partial_type is None or partial_type.value_type is None:\n                return\n            value_type = self.try_infer_partial_value_type_from_call(e, callee.name, var)\n            if value_type is not None:\n                # Infer key type.\n                key_type = self.accept(index)\n                if mypy.checker.is_valid_inferred_type(key_type, self.chk.options):\n                    # Store inferred partial type.\n                    assert partial_type.type is not None\n                    typename = partial_type.type.fullname\n                    new_type = self.chk.named_generic_type(typename, [key_type, value_type])\n                    self.chk.replace_partial_type(var, new_type, partial_types)\n\n    def get_partial_var(self, ref: RefExpr) -> tuple[Var, dict[Var, Context]] | None:\n        var = ref.node\n        if var is None and isinstance(ref, MemberExpr):\n            var = self.get_partial_self_var(ref)\n        if not isinstance(var, Var):\n            return None\n        partial_types = self.chk.find_partial_types(var)\n        if partial_types is None:\n            return None\n        return var, partial_types\n\n    def try_infer_partial_value_type_from_call(\n        self, e: CallExpr, methodname: str, var: Var\n    ) -> Instance | None:\n        \"\"\"Try to make partial type precise from a call such as 'x.append(y)'.\"\"\"\n        if self.chk.current_node_deferred:\n            return None\n        partial_type = get_partial_instance_type(var.type)\n        if partial_type is None:\n            return None\n        if partial_type.value_type:\n            typename = partial_type.value_type.type.fullname\n        else:\n            assert partial_type.type is not None\n            typename = partial_type.type.fullname\n        # Sometimes we can infer a full type for a partial List, Dict or Set type.\n        # TODO: Don't infer argument expression twice.\n        if (\n            typename in self.item_args\n            and methodname in self.item_args[typename]\n            and e.arg_kinds == [ARG_POS]\n        ):\n            item_type = self.accept(e.args[0])\n            if mypy.checker.is_valid_inferred_type(item_type, self.chk.options):\n                return self.chk.named_generic_type(typename, [item_type])\n        elif (\n            typename in self.container_args\n            and methodname in self.container_args[typename]\n            and e.arg_kinds == [ARG_POS]\n        ):\n            arg_type = get_proper_type(self.accept(e.args[0]))\n            if isinstance(arg_type, Instance):\n                arg_typename = arg_type.type.fullname\n                if arg_typename in self.container_args[typename][methodname]:\n                    if all(\n                        mypy.checker.is_valid_inferred_type(item_type, self.chk.options)\n                        for item_type in arg_type.args\n                    ):\n                        return self.chk.named_generic_type(typename, list(arg_type.args))\n            elif isinstance(arg_type, AnyType):\n                return self.chk.named_type(typename)\n\n        return None\n\n    def apply_function_plugin(\n        self,\n        callee: CallableType,\n        arg_kinds: list[ArgKind],\n        arg_types: list[Type],\n        arg_names: Sequence[str | None] | None,\n        formal_to_actual: list[list[int]],\n        args: list[Expression],\n        fullname: str,\n        object_type: Type | None,\n        context: Context,\n    ) -> Type:\n        \"\"\"Use special case logic to infer the return type of a specific named function/method.\n\n        Caller must ensure that a plugin hook exists. There are two different cases:\n\n        - If object_type is None, the caller must ensure that a function hook exists\n          for fullname.\n        - If object_type is not None, the caller must ensure that a method hook exists\n          for fullname.\n\n        Return the inferred return type.\n        \"\"\"\n        num_formals = len(callee.arg_types)\n        formal_arg_types: list[list[Type]] = [[] for _ in range(num_formals)]\n        formal_arg_exprs: list[list[Expression]] = [[] for _ in range(num_formals)]\n        formal_arg_names: list[list[str | None]] = [[] for _ in range(num_formals)]\n        formal_arg_kinds: list[list[ArgKind]] = [[] for _ in range(num_formals)]\n        for formal, actuals in enumerate(formal_to_actual):\n            for actual in actuals:\n                formal_arg_types[formal].append(arg_types[actual])\n                formal_arg_exprs[formal].append(args[actual])\n                if arg_names:\n                    formal_arg_names[formal].append(arg_names[actual])\n                else:\n                    formal_arg_names[formal].append(None)\n                formal_arg_kinds[formal].append(arg_kinds[actual])\n\n        if object_type is None:\n            # Apply function plugin\n            callback = self.plugin.get_function_hook(fullname)\n            assert callback is not None  # Assume that caller ensures this\n            return callback(\n                FunctionContext(\n                    arg_types=formal_arg_types,\n                    arg_kinds=formal_arg_kinds,\n                    callee_arg_names=callee.arg_names,\n                    arg_names=formal_arg_names,\n                    default_return_type=callee.ret_type,\n                    args=formal_arg_exprs,\n                    context=context,\n                    api=self.chk,\n                )\n            )\n        else:\n            # Apply method plugin\n            method_callback = self.plugin.get_method_hook(fullname)\n            assert method_callback is not None  # Assume that caller ensures this\n            object_type = get_proper_type(object_type)\n            return method_callback(\n                MethodContext(\n                    type=object_type,\n                    arg_types=formal_arg_types,\n                    arg_kinds=formal_arg_kinds,\n                    callee_arg_names=callee.arg_names,\n                    arg_names=formal_arg_names,\n                    default_return_type=callee.ret_type,\n                    args=formal_arg_exprs,\n                    context=context,\n                    api=self.chk,\n                )\n            )\n\n    def apply_signature_hook(\n        self,\n        callee: FunctionLike,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        hook: Callable[[list[list[Expression]], CallableType], FunctionLike],\n    ) -> FunctionLike:\n        \"\"\"Helper to apply a signature hook for either a function or method\"\"\"\n        if isinstance(callee, CallableType):\n            num_formals = len(callee.arg_kinds)\n            formal_to_actual = map_actuals_to_formals(\n                arg_kinds,\n                arg_names,\n                callee.arg_kinds,\n                callee.arg_names,\n                lambda i: self.accept(args[i]),\n            )\n            formal_arg_exprs: list[list[Expression]] = [[] for _ in range(num_formals)]\n            for formal, actuals in enumerate(formal_to_actual):\n                for actual in actuals:\n                    formal_arg_exprs[formal].append(args[actual])\n            return hook(formal_arg_exprs, callee)\n        else:\n            assert isinstance(callee, Overloaded)\n            items = []\n            for item in callee.items:\n                adjusted = self.apply_signature_hook(item, args, arg_kinds, arg_names, hook)\n                assert isinstance(adjusted, CallableType)\n                items.append(adjusted)\n            return Overloaded(items)\n\n    def apply_function_signature_hook(\n        self,\n        callee: FunctionLike,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n        arg_names: Sequence[str | None] | None,\n        signature_hook: Callable[[FunctionSigContext], FunctionLike],\n    ) -> FunctionLike:\n        \"\"\"Apply a plugin hook that may infer a more precise signature for a function.\"\"\"\n        return self.apply_signature_hook(\n            callee,\n            args,\n            arg_kinds,\n            arg_names,\n            (lambda args, sig: signature_hook(FunctionSigContext(args, sig, context, self.chk))),\n        )\n\n    def apply_method_signature_hook(\n        self,\n        callee: FunctionLike,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n        arg_names: Sequence[str | None] | None,\n        object_type: Type,\n        signature_hook: Callable[[MethodSigContext], FunctionLike],\n    ) -> FunctionLike:\n        \"\"\"Apply a plugin hook that may infer a more precise signature for a method.\"\"\"\n        pobject_type = get_proper_type(object_type)\n        return self.apply_signature_hook(\n            callee,\n            args,\n            arg_kinds,\n            arg_names,\n            (\n                lambda args, sig: signature_hook(\n                    MethodSigContext(pobject_type, args, sig, context, self.chk)\n                )\n            ),\n        )\n\n    def transform_callee_type(\n        self,\n        callable_name: str | None,\n        callee: Type,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n        arg_names: Sequence[str | None] | None = None,\n        object_type: Type | None = None,\n    ) -> Type:\n        \"\"\"Attempt to determine a more accurate signature for a method call.\n\n        This is done by looking up and applying a method signature hook (if one exists for the\n        given method name).\n\n        If no matching method signature hook is found, callee is returned unmodified. The same\n        happens if the arguments refer to a non-method callable (this is allowed so that the code\n        calling transform_callee_type needs to perform fewer boilerplate checks).\n\n        Note: this method is *not* called automatically as part of check_call, because in some\n        cases check_call is called multiple times while checking a single call (for example when\n        dealing with overloads). Instead, this method needs to be called explicitly\n        (if appropriate) before the signature is passed to check_call.\n        \"\"\"\n        callee = get_proper_type(callee)\n        if callable_name is not None and isinstance(callee, FunctionLike):\n            if object_type is not None:\n                method_sig_hook = self.plugin.get_method_signature_hook(callable_name)\n                if method_sig_hook:\n                    return self.apply_method_signature_hook(\n                        callee, args, arg_kinds, context, arg_names, object_type, method_sig_hook\n                    )\n            else:\n                function_sig_hook = self.plugin.get_function_signature_hook(callable_name)\n                if function_sig_hook:\n                    return self.apply_function_signature_hook(\n                        callee, args, arg_kinds, context, arg_names, function_sig_hook\n                    )\n\n        return callee\n\n    def is_generic_decorator_overload_call(\n        self, callee_type: CallableType, args: list[Expression]\n    ) -> Overloaded | None:\n        \"\"\"Check if this looks like an application of a generic function to overload argument.\"\"\"\n        assert callee_type.variables\n        if len(callee_type.arg_types) != 1 or len(args) != 1:\n            # TODO: can we handle more general cases?\n            return None\n        if not isinstance(get_proper_type(callee_type.arg_types[0]), CallableType):\n            return None\n        if not isinstance(get_proper_type(callee_type.ret_type), CallableType):\n            return None\n        with self.chk.local_type_map:\n            with self.msg.filter_errors():\n                arg_type = get_proper_type(self.accept(args[0], type_context=None))\n        if isinstance(arg_type, Overloaded):\n            return arg_type\n        return None\n\n    def handle_decorator_overload_call(\n        self, callee_type: CallableType, overloaded: Overloaded, ctx: Context\n    ) -> tuple[Type, Type] | None:\n        \"\"\"Type-check application of a generic callable to an overload.\n\n        We check call on each individual overload item, and then combine results into a new\n        overload. This function should be only used if callee_type takes and returns a Callable.\n        \"\"\"\n        result = []\n        inferred_args = []\n        for item in overloaded.items:\n            arg = TempNode(typ=item)\n            with self.msg.filter_errors() as err:\n                item_result, inferred_arg = self.check_call(callee_type, [arg], [ARG_POS], ctx)\n            if err.has_new_errors():\n                # This overload doesn't match.\n                continue\n            p_item_result = get_proper_type(item_result)\n            if not isinstance(p_item_result, CallableType):\n                continue\n            p_inferred_arg = get_proper_type(inferred_arg)\n            if not isinstance(p_inferred_arg, CallableType):\n                continue\n            inferred_args.append(p_inferred_arg)\n            result.append(p_item_result)\n        if not result or not inferred_args:\n            # None of the overload matched (or overload was initially malformed).\n            return None\n        return Overloaded(result), Overloaded(inferred_args)\n\n    def check_call_expr_with_callee_type(\n        self,\n        callee_type: Type,\n        e: CallExpr,\n        callable_name: str | None,\n        object_type: Type | None,\n        member: str | None = None,\n    ) -> Type:\n        \"\"\"Type check call expression.\n\n        The callee_type should be used as the type of callee expression. In particular,\n        in case of a union type this can be a particular item of the union, so that we can\n        apply plugin hooks to each item.\n\n        The 'member', 'callable_name' and 'object_type' are only used to call plugin hooks.\n        If 'callable_name' is None but 'member' is not None (member call), try constructing\n        'callable_name' using 'object_type' (the base type on which the method is called),\n        for example 'typing.Mapping.get'.\n        \"\"\"\n        if callable_name is None and member is not None:\n            assert object_type is not None\n            callable_name = self.method_fullname(object_type, member)\n        object_type = get_proper_type(object_type)\n        if callable_name:\n            # Try to refine the call signature using plugin hooks before checking the call.\n            callee_type = self.transform_callee_type(\n                callable_name, callee_type, e.args, e.arg_kinds, e, e.arg_names, object_type\n            )\n        # Unions are special-cased to allow plugins to act on each item in the union.\n        elif member is not None and isinstance(object_type, UnionType):\n            return self.check_union_call_expr(e, object_type, member)\n        ret_type, callee_type = self.check_call(\n            callee_type,\n            e.args,\n            e.arg_kinds,\n            e,\n            e.arg_names,\n            callable_node=e.callee,\n            callable_name=callable_name,\n            object_type=object_type,\n        )\n        proper_callee = get_proper_type(callee_type)\n        if isinstance(e.callee, RefExpr) and isinstance(proper_callee, CallableType):\n            # Cache it for find_isinstance_check()\n            if proper_callee.type_guard is not None:\n                e.callee.type_guard = proper_callee.type_guard\n            if proper_callee.type_is is not None:\n                e.callee.type_is = proper_callee.type_is\n        return ret_type\n\n    def check_union_call_expr(self, e: CallExpr, object_type: UnionType, member: str) -> Type:\n        \"\"\"Type check calling a member expression where the base type is a union.\"\"\"\n        res: list[Type] = []\n        for typ in flatten_nested_unions(object_type.relevant_items()):\n            # Member access errors are already reported when visiting the member expression.\n            with self.msg.filter_errors():\n                item = analyze_member_access(\n                    member,\n                    typ,\n                    e,\n                    is_lvalue=False,\n                    is_super=False,\n                    is_operator=False,\n                    original_type=object_type,\n                    chk=self.chk,\n                    in_literal_context=self.is_literal_context(),\n                    self_type=typ,\n                )\n            narrowed = self.narrow_type_from_binder(e.callee, item, skip_non_overlapping=True)\n            if narrowed is None:\n                continue\n            callable_name = self.method_fullname(typ, member)\n            item_object_type = typ if callable_name else None\n            res.append(\n                self.check_call_expr_with_callee_type(narrowed, e, callable_name, item_object_type)\n            )\n        return make_simplified_union(res)\n\n    def check_call(\n        self,\n        callee: Type,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n        arg_names: Sequence[str | None] | None = None,\n        callable_node: Expression | None = None,\n        callable_name: str | None = None,\n        object_type: Type | None = None,\n        original_type: Type | None = None,\n    ) -> tuple[Type, Type]:\n        \"\"\"Type check a call.\n\n        Also infer type arguments if the callee is a generic function.\n\n        Return (result type, inferred callee type).\n\n        Arguments:\n            callee: type of the called value\n            args: actual argument expressions\n            arg_kinds: contains nodes.ARG_* constant for each argument in args\n                 describing whether the argument is positional, *arg, etc.\n            context: current expression context, used for inference.\n            arg_names: names of arguments (optional)\n            callable_node: associate the inferred callable type to this node,\n                if specified\n            callable_name: Fully-qualified name of the function/method to call,\n                or None if unavailable (examples: 'builtins.open', 'typing.Mapping.get')\n            object_type: If callable_name refers to a method, the type of the object\n                on which the method is being called\n        \"\"\"\n        callee = get_proper_type(callee)\n\n        if isinstance(callee, CallableType):\n            if callee.variables:\n                overloaded = self.is_generic_decorator_overload_call(callee, args)\n                if overloaded is not None:\n                    # Special casing for inline application of generic callables to overloads.\n                    # Supporting general case would be tricky, but this should cover 95% of cases.\n                    overloaded_result = self.handle_decorator_overload_call(\n                        callee, overloaded, context\n                    )\n                    if overloaded_result is not None:\n                        return overloaded_result\n\n            return self.check_callable_call(\n                callee,\n                args,\n                arg_kinds,\n                context,\n                arg_names,\n                callable_node,\n                callable_name,\n                object_type,\n            )\n        elif isinstance(callee, Overloaded):\n            return self.check_overload_call(\n                callee, args, arg_kinds, arg_names, callable_name, object_type, context\n            )\n        elif isinstance(callee, AnyType) or not self.chk.in_checked_function():\n            return self.check_any_type_call(args, arg_kinds, callee, context)\n        elif isinstance(callee, UnionType):\n            return self.check_union_call(callee, args, arg_kinds, arg_names, context)\n        elif isinstance(callee, Instance):\n            call_function = analyze_member_access(\n                \"__call__\",\n                callee,\n                context,\n                is_lvalue=False,\n                is_super=False,\n                is_operator=True,\n                original_type=original_type or callee,\n                chk=self.chk,\n                in_literal_context=self.is_literal_context(),\n            )\n            callable_name = callee.type.fullname + \".__call__\"\n            # Apply method signature hook, if one exists\n            call_function = self.transform_callee_type(\n                callable_name, call_function, args, arg_kinds, context, arg_names, callee\n            )\n            result = self.check_call(\n                call_function,\n                args,\n                arg_kinds,\n                context,\n                arg_names,\n                callable_node,\n                callable_name,\n                callee,\n            )\n            if callable_node:\n                # check_call() stored \"call_function\" as the type, which is incorrect.\n                # Override the type.\n                self.chk.store_type(callable_node, callee)\n            return result\n        elif isinstance(callee, TypeVarType):\n            return self.check_call(\n                callee.upper_bound, args, arg_kinds, context, arg_names, callable_node\n            )\n        elif isinstance(callee, TypeType):\n            item = self.analyze_type_type_callee(callee.item, context)\n            return self.check_call(item, args, arg_kinds, context, arg_names, callable_node)\n        elif isinstance(callee, TupleType):\n            return self.check_call(\n                tuple_fallback(callee),\n                args,\n                arg_kinds,\n                context,\n                arg_names,\n                callable_node,\n                callable_name,\n                object_type,\n                original_type=callee,\n            )\n        elif isinstance(callee, UninhabitedType):\n            ret = UninhabitedType()\n            ret.ambiguous = callee.ambiguous\n            return callee, ret\n        else:\n            return self.msg.not_callable(callee, context), AnyType(TypeOfAny.from_error)\n\n    def check_callable_call(\n        self,\n        callee: CallableType,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n        arg_names: Sequence[str | None] | None,\n        callable_node: Expression | None,\n        callable_name: str | None,\n        object_type: Type | None,\n    ) -> tuple[Type, Type]:\n        \"\"\"Type check a call that targets a callable value.\n\n        See the docstring of check_call for more information.\n        \"\"\"\n        # Always unpack **kwargs before checking a call.\n        callee = callee.with_unpacked_kwargs().with_normalized_var_args()\n        if callable_name is None and callee.name:\n            callable_name = callee.name\n        ret_type = get_proper_type(callee.ret_type)\n        if callee.is_type_obj() and isinstance(ret_type, Instance):\n            callable_name = ret_type.type.fullname\n        if isinstance(callable_node, RefExpr) and callable_node.fullname in ENUM_BASES:\n            # An Enum() call that failed SemanticAnalyzerPass2.check_enum_call().\n            return callee.ret_type, callee\n\n        if (\n            callee.is_type_obj()\n            and callee.type_object().is_protocol\n            # Exception for Type[...]\n            and not callee.from_type_type\n        ):\n            self.chk.fail(\n                message_registry.CANNOT_INSTANTIATE_PROTOCOL.format(callee.type_object().name),\n                context,\n            )\n        elif (\n            callee.is_type_obj()\n            and callee.type_object().is_abstract\n            # Exception for Type[...]\n            and not callee.from_type_type\n            and not callee.type_object().fallback_to_any\n        ):\n            type = callee.type_object()\n            # Determine whether the implicitly abstract attributes are functions with\n            # None-compatible return types.\n            abstract_attributes: dict[str, bool] = {}\n            for attr_name, abstract_status in type.abstract_attributes:\n                if abstract_status == IMPLICITLY_ABSTRACT:\n                    abstract_attributes[attr_name] = self.can_return_none(type, attr_name)\n                else:\n                    abstract_attributes[attr_name] = False\n            self.msg.cannot_instantiate_abstract_class(\n                callee.type_object().name, abstract_attributes, context\n            )\n\n        var_arg = callee.var_arg()\n        if var_arg and isinstance(var_arg.typ, UnpackType):\n            # It is hard to support multiple variadic unpacks (except for old-style *args: int),\n            # fail gracefully to avoid crashes later.\n            seen_unpack = False\n            for arg, arg_kind in zip(args, arg_kinds):\n                if arg_kind != ARG_STAR:\n                    continue\n                arg_type = get_proper_type(self.accept(arg))\n                if not isinstance(arg_type, TupleType) or any(\n                    isinstance(t, UnpackType) for t in arg_type.items\n                ):\n                    if seen_unpack:\n                        self.msg.fail(\n                            \"Passing multiple variadic unpacks in a call is not supported\",\n                            context,\n                            code=codes.CALL_ARG,\n                        )\n                        return AnyType(TypeOfAny.from_error), callee\n                    seen_unpack = True\n\n        # This is tricky: return type may contain its own type variables, like in\n        # def [S] (S) -> def [T] (T) -> tuple[S, T], so we need to update their ids\n        # to avoid possible id clashes if this call itself appears in a generic\n        # function body.\n        ret_type = get_proper_type(callee.ret_type)\n        if isinstance(ret_type, CallableType) and ret_type.variables:\n            fresh_ret_type = freshen_all_functions_type_vars(callee.ret_type)\n            freeze_all_type_vars(fresh_ret_type)\n            callee = callee.copy_modified(ret_type=fresh_ret_type)\n\n        if callee.is_generic():\n            callee = freshen_function_type_vars(callee)\n            callee = self.infer_function_type_arguments_using_context(callee, context)\n\n        formal_to_actual = map_actuals_to_formals(\n            arg_kinds,\n            arg_names,\n            callee.arg_kinds,\n            callee.arg_names,\n            lambda i: self.accept(args[i]),\n        )\n\n        if callee.is_generic():\n            need_refresh = any(\n                isinstance(v, (ParamSpecType, TypeVarTupleType)) for v in callee.variables\n            )\n            callee = self.infer_function_type_arguments(\n                callee, args, arg_kinds, arg_names, formal_to_actual, need_refresh, context\n            )\n            if need_refresh:\n                # Argument kinds etc. may have changed due to\n                # ParamSpec or TypeVarTuple variables being replaced with an arbitrary\n                # number of arguments; recalculate actual-to-formal map\n                formal_to_actual = map_actuals_to_formals(\n                    arg_kinds,\n                    arg_names,\n                    callee.arg_kinds,\n                    callee.arg_names,\n                    lambda i: self.accept(args[i]),\n                )\n\n        param_spec = callee.param_spec()\n        if (\n            param_spec is not None\n            and arg_kinds == [ARG_STAR, ARG_STAR2]\n            and len(formal_to_actual) == 2\n        ):\n            arg1 = self.accept(args[0])\n            arg2 = self.accept(args[1])\n            if (\n                isinstance(arg1, ParamSpecType)\n                and isinstance(arg2, ParamSpecType)\n                and arg1.flavor == ParamSpecFlavor.ARGS\n                and arg2.flavor == ParamSpecFlavor.KWARGS\n                and arg1.id == arg2.id == param_spec.id\n            ):\n                return callee.ret_type, callee\n\n        arg_types = self.infer_arg_types_in_context(callee, args, arg_kinds, formal_to_actual)\n\n        self.check_argument_count(\n            callee,\n            arg_types,\n            arg_kinds,\n            arg_names,\n            formal_to_actual,\n            context,\n            object_type,\n            callable_name,\n        )\n\n        self.check_argument_types(\n            arg_types, arg_kinds, args, callee, formal_to_actual, context, object_type=object_type\n        )\n\n        if (\n            callee.is_type_obj()\n            and (len(arg_types) == 1)\n            and is_equivalent(callee.ret_type, self.named_type(\"builtins.type\"))\n        ):\n            callee = callee.copy_modified(ret_type=TypeType.make_normalized(arg_types[0]))\n\n        if callable_node:\n            # Store the inferred callable type.\n            self.chk.store_type(callable_node, callee)\n\n        if callable_name and (\n            (object_type is None and self.plugin.get_function_hook(callable_name))\n            or (object_type is not None and self.plugin.get_method_hook(callable_name))\n        ):\n            new_ret_type = self.apply_function_plugin(\n                callee,\n                arg_kinds,\n                arg_types,\n                arg_names,\n                formal_to_actual,\n                args,\n                callable_name,\n                object_type,\n                context,\n            )\n            callee = callee.copy_modified(ret_type=new_ret_type)\n        return callee.ret_type, callee\n\n    def can_return_none(self, type: TypeInfo, attr_name: str) -> bool:\n        \"\"\"Is the given attribute a method with a None-compatible return type?\n\n        Overloads are only checked if there is an implementation.\n        \"\"\"\n        if not state.strict_optional:\n            # If strict-optional is not set, is_subtype(NoneType(), T) is always True.\n            # So, we cannot do anything useful here in that case.\n            return False\n        for base in type.mro:\n            symnode = base.names.get(attr_name)\n            if symnode is None:\n                continue\n            node = symnode.node\n            if isinstance(node, OverloadedFuncDef):\n                node = node.impl\n            if isinstance(node, Decorator):\n                node = node.func\n            if isinstance(node, FuncDef):\n                if node.type is not None:\n                    assert isinstance(node.type, CallableType)\n                    return is_subtype(NoneType(), node.type.ret_type)\n        return False\n\n    def analyze_type_type_callee(self, item: ProperType, context: Context) -> Type:\n        \"\"\"Analyze the callee X in X(...) where X is Type[item].\n\n        Return a Y that we can pass to check_call(Y, ...).\n        \"\"\"\n        if isinstance(item, AnyType):\n            return AnyType(TypeOfAny.from_another_any, source_any=item)\n        if isinstance(item, Instance):\n            res = type_object_type(item.type, self.named_type)\n            if isinstance(res, CallableType):\n                res = res.copy_modified(from_type_type=True)\n            expanded = expand_type_by_instance(res, item)\n            if isinstance(expanded, CallableType):\n                # Callee of the form Type[...] should never be generic, only\n                # proper class objects can be.\n                expanded = expanded.copy_modified(variables=[])\n            return expanded\n        if isinstance(item, UnionType):\n            return UnionType(\n                [\n                    self.analyze_type_type_callee(get_proper_type(tp), context)\n                    for tp in item.relevant_items()\n                ],\n                item.line,\n            )\n        if isinstance(item, TypeVarType):\n            # Pretend we're calling the typevar's upper bound,\n            # i.e. its constructor (a poor approximation for reality,\n            # but better than AnyType...), but replace the return type\n            # with typevar.\n            callee = self.analyze_type_type_callee(get_proper_type(item.upper_bound), context)\n            callee = get_proper_type(callee)\n            if isinstance(callee, CallableType):\n                callee = callee.copy_modified(ret_type=item)\n            elif isinstance(callee, Overloaded):\n                callee = Overloaded([c.copy_modified(ret_type=item) for c in callee.items])\n            return callee\n        # We support Type of namedtuples but not of tuples in general\n        if isinstance(item, TupleType) and tuple_fallback(item).type.fullname != \"builtins.tuple\":\n            return self.analyze_type_type_callee(tuple_fallback(item), context)\n        if isinstance(item, TypedDictType):\n            return self.typeddict_callable_from_context(item)\n\n        self.msg.unsupported_type_type(item, context)\n        return AnyType(TypeOfAny.from_error)\n\n    def infer_arg_types_in_empty_context(self, args: list[Expression]) -> list[Type]:\n        \"\"\"Infer argument expression types in an empty context.\n\n        In short, we basically recurse on each argument without considering\n        in what context the argument was called.\n        \"\"\"\n        res: list[Type] = []\n\n        for arg in args:\n            arg_type = self.accept(arg)\n            if has_erased_component(arg_type):\n                res.append(NoneType())\n            else:\n                res.append(arg_type)\n        return res\n\n    def infer_more_unions_for_recursive_type(self, type_context: Type) -> bool:\n        \"\"\"Adjust type inference of unions if type context has a recursive type.\n\n        Return the old state. The caller must assign it to type_state.infer_unions\n        afterwards.\n\n        This is a hack to better support inference for recursive types.\n\n        Note: This is performance-sensitive and must not be a context manager\n        until mypyc supports them better.\n        \"\"\"\n        old = type_state.infer_unions\n        if has_recursive_types(type_context):\n            type_state.infer_unions = True\n        return old\n\n    def infer_arg_types_in_context(\n        self,\n        callee: CallableType,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        formal_to_actual: list[list[int]],\n    ) -> list[Type]:\n        \"\"\"Infer argument expression types using a callable type as context.\n\n        For example, if callee argument 2 has type List[int], infer the\n        argument expression with List[int] type context.\n\n        Returns the inferred types of *actual arguments*.\n        \"\"\"\n        # Precompute arg_context so that we type check argument expressions in evaluation order\n        arg_context: list[Type | None] = [None] * len(args)\n        for fi, actuals in enumerate(formal_to_actual):\n            for ai in actuals:\n                if arg_kinds[ai].is_star():\n                    continue\n                arg_context[ai] = callee.arg_types[fi]\n\n        res = []\n        for arg, ctx in zip(args, arg_context):\n            if ctx is not None:\n                # When the outer context for a function call is known to be recursive,\n                # we solve type constraints inferred from arguments using unions instead\n                # of joins. This is a bit arbitrary, but in practice it works for most\n                # cases. A cleaner alternative would be to switch to single bin type\n                # inference, but this is a lot of work.\n                old = self.infer_more_unions_for_recursive_type(ctx)\n                res.append(self.accept(arg, ctx))\n                # We need to manually restore union inference state, ugh.\n                type_state.infer_unions = old\n            else:\n                res.append(self.accept(arg))\n        return res\n\n    def infer_function_type_arguments_using_context(\n        self, callable: CallableType, error_context: Context\n    ) -> CallableType:\n        \"\"\"Unify callable return type to type context to infer type vars.\n\n        For example, if the return type is set[t] where 't' is a type variable\n        of callable, and if the context is set[int], return callable modified\n        by substituting 't' with 'int'.\n        \"\"\"\n        ctx = self.type_context[-1]\n        if not ctx:\n            return callable\n        # The return type may have references to type metavariables that\n        # we are inferring right now. We must consider them as indeterminate\n        # and they are not potential results; thus we replace them with the\n        # special ErasedType type. On the other hand, class type variables are\n        # valid results.\n        erased_ctx = replace_meta_vars(ctx, ErasedType())\n        ret_type = callable.ret_type\n        if is_overlapping_none(ret_type) and is_overlapping_none(ctx):\n            # If both the context and the return type are optional, unwrap the optional,\n            # since in 99% cases this is what a user expects. In other words, we replace\n            #     Optional[T] <: Optional[int]\n            # with\n            #     T <: int\n            # while the former would infer T <: Optional[int].\n            ret_type = remove_optional(ret_type)\n            erased_ctx = remove_optional(erased_ctx)\n            #\n            # TODO: Instead of this hack and the one below, we need to use outer and\n            # inner contexts at the same time. This is however not easy because of two\n            # reasons:\n            #   * We need to support constraints like [1 <: 2, 2 <: X], i.e. with variables\n            #     on both sides. (This is not too hard.)\n            #   * We need to update all the inference \"infrastructure\", so that all\n            #     variables in an expression are inferred at the same time.\n            #     (And this is hard, also we need to be careful with lambdas that require\n            #     two passes.)\n        proper_ret = get_proper_type(ret_type)\n        if (\n            isinstance(proper_ret, TypeVarType)\n            or isinstance(proper_ret, UnionType)\n            and all(isinstance(get_proper_type(u), TypeVarType) for u in proper_ret.items)\n        ):\n            # Another special case: the return type is a type variable. If it's unrestricted,\n            # we could infer a too general type for the type variable if we use context,\n            # and this could result in confusing and spurious type errors elsewhere.\n            #\n            # So we give up and just use function arguments for type inference, with just two\n            # exceptions:\n            #\n            # 1. If the context is a generic instance type, actually use it as context, as\n            #    this *seems* to usually be the reasonable thing to do.\n            #\n            #    See also github issues #462 and #360.\n            #\n            # 2. If the context is some literal type, we want to \"propagate\" that information\n            #    down so that we infer a more precise type for literal expressions. For example,\n            #    the expression `3` normally has an inferred type of `builtins.int`: but if it's\n            #    in a literal context like below, we want it to infer `Literal[3]` instead.\n            #\n            #        def expects_literal(x: Literal[3]) -> None: pass\n            #        def identity(x: T) -> T: return x\n            #\n            #        expects_literal(identity(3))  # Should type-check\n            # TODO: we may want to add similar exception if all arguments are lambdas, since\n            # in this case external context is almost everything we have.\n            if not is_generic_instance(ctx) and not is_literal_type_like(ctx):\n                return callable.copy_modified()\n        args = infer_type_arguments(\n            callable.variables, ret_type, erased_ctx, skip_unsatisfied=True\n        )\n        # Only substitute non-Uninhabited and non-erased types.\n        new_args: list[Type | None] = []\n        for arg in args:\n            if has_uninhabited_component(arg) or has_erased_component(arg):\n                new_args.append(None)\n            else:\n                new_args.append(arg)\n        # Don't show errors after we have only used the outer context for inference.\n        # We will use argument context to infer more variables.\n        return self.apply_generic_arguments(\n            callable, new_args, error_context, skip_unsatisfied=True\n        )\n\n    def infer_function_type_arguments(\n        self,\n        callee_type: CallableType,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        formal_to_actual: list[list[int]],\n        need_refresh: bool,\n        context: Context,\n    ) -> CallableType:\n        \"\"\"Infer the type arguments for a generic callee type.\n\n        Infer based on the types of arguments.\n\n        Return a derived callable type that has the arguments applied.\n        \"\"\"\n        if self.chk.in_checked_function():\n            # Disable type errors during type inference. There may be errors\n            # due to partial available context information at this time, but\n            # these errors can be safely ignored as the arguments will be\n            # inferred again later.\n            with self.msg.filter_errors():\n                arg_types = self.infer_arg_types_in_context(\n                    callee_type, args, arg_kinds, formal_to_actual\n                )\n\n            arg_pass_nums = self.get_arg_infer_passes(\n                callee_type, args, arg_types, formal_to_actual, len(args)\n            )\n\n            pass1_args: list[Type | None] = []\n            for i, arg in enumerate(arg_types):\n                if arg_pass_nums[i] > 1:\n                    pass1_args.append(None)\n                else:\n                    pass1_args.append(arg)\n\n            inferred_args, _ = infer_function_type_arguments(\n                callee_type,\n                pass1_args,\n                arg_kinds,\n                arg_names,\n                formal_to_actual,\n                context=self.argument_infer_context(),\n                strict=self.chk.in_checked_function(),\n            )\n\n            if 2 in arg_pass_nums:\n                # Second pass of type inference.\n                callee_type, inferred_args = self.infer_function_type_arguments_pass2(\n                    callee_type,\n                    args,\n                    arg_kinds,\n                    arg_names,\n                    formal_to_actual,\n                    inferred_args,\n                    need_refresh,\n                    context,\n                )\n\n            if (\n                callee_type.special_sig == \"dict\"\n                and len(inferred_args) == 2\n                and (ARG_NAMED in arg_kinds or ARG_STAR2 in arg_kinds)\n            ):\n                # HACK: Infer str key type for dict(...) with keyword args. The type system\n                #       can't represent this so we special case it, as this is a pretty common\n                #       thing. This doesn't quite work with all possible subclasses of dict\n                #       if they shuffle type variables around, as we assume that there is a 1-1\n                #       correspondence with dict type variables. This is a marginal issue and\n                #       a little tricky to fix so it's left unfixed for now.\n                first_arg = get_proper_type(inferred_args[0])\n                if isinstance(first_arg, (NoneType, UninhabitedType)):\n                    inferred_args[0] = self.named_type(\"builtins.str\")\n                elif not first_arg or not is_subtype(self.named_type(\"builtins.str\"), first_arg):\n                    self.chk.fail(message_registry.KEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE, context)\n\n            if not self.chk.options.old_type_inference and any(\n                a is None\n                or isinstance(get_proper_type(a), UninhabitedType)\n                or set(get_type_vars(a)) & set(callee_type.variables)\n                for a in inferred_args\n            ):\n                if need_refresh:\n                    # Technically we need to refresh formal_to_actual after *each* inference pass,\n                    # since each pass can expand ParamSpec or TypeVarTuple. Although such situations\n                    # are very rare, not doing this can cause crashes.\n                    formal_to_actual = map_actuals_to_formals(\n                        arg_kinds,\n                        arg_names,\n                        callee_type.arg_kinds,\n                        callee_type.arg_names,\n                        lambda a: self.accept(args[a]),\n                    )\n                # If the regular two-phase inference didn't work, try inferring type\n                # variables while allowing for polymorphic solutions, i.e. for solutions\n                # potentially involving free variables.\n                # TODO: support the similar inference for return type context.\n                poly_inferred_args, free_vars = infer_function_type_arguments(\n                    callee_type,\n                    arg_types,\n                    arg_kinds,\n                    arg_names,\n                    formal_to_actual,\n                    context=self.argument_infer_context(),\n                    strict=self.chk.in_checked_function(),\n                    allow_polymorphic=True,\n                )\n                poly_callee_type = self.apply_generic_arguments(\n                    callee_type, poly_inferred_args, context\n                )\n                # Try applying inferred polymorphic type if possible, e.g. Callable[[T], T] can\n                # be interpreted as def [T] (T) -> T, but dict[T, T] cannot be expressed.\n                applied = applytype.apply_poly(poly_callee_type, free_vars)\n                if applied is not None and all(\n                    a is not None and not isinstance(get_proper_type(a), UninhabitedType)\n                    for a in poly_inferred_args\n                ):\n                    freeze_all_type_vars(applied)\n                    return applied\n                # If it didn't work, erase free variables as uninhabited, to avoid confusing errors.\n                unknown = UninhabitedType()\n                unknown.ambiguous = True\n                inferred_args = [\n                    (\n                        expand_type(\n                            a, {v.id: unknown for v in list(callee_type.variables) + free_vars}\n                        )\n                        if a is not None\n                        else None\n                    )\n                    for a in poly_inferred_args\n                ]\n        else:\n            # In dynamically typed functions use implicit 'Any' types for\n            # type variables.\n            inferred_args = [AnyType(TypeOfAny.unannotated)] * len(callee_type.variables)\n        return self.apply_inferred_arguments(callee_type, inferred_args, context)\n\n    def infer_function_type_arguments_pass2(\n        self,\n        callee_type: CallableType,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        formal_to_actual: list[list[int]],\n        old_inferred_args: Sequence[Type | None],\n        need_refresh: bool,\n        context: Context,\n    ) -> tuple[CallableType, list[Type | None]]:\n        \"\"\"Perform second pass of generic function type argument inference.\n\n        The second pass is needed for arguments with types such as Callable[[T], S],\n        where both T and S are type variables, when the actual argument is a\n        lambda with inferred types.  The idea is to infer the type variable T\n        in the first pass (based on the types of other arguments).  This lets\n        us infer the argument and return type of the lambda expression and\n        thus also the type variable S in this second pass.\n\n        Return (the callee with type vars applied, inferred actual arg types).\n        \"\"\"\n        # None or erased types in inferred types mean that there was not enough\n        # information to infer the argument. Replace them with None values so\n        # that they are not applied yet below.\n        inferred_args = list(old_inferred_args)\n        for i, arg in enumerate(get_proper_types(inferred_args)):\n            if isinstance(arg, (NoneType, UninhabitedType)) or has_erased_component(arg):\n                inferred_args[i] = None\n        callee_type = self.apply_generic_arguments(callee_type, inferred_args, context)\n\n        if not callee_type.is_generic():\n            # Fast path, second pass can't give new information.\n            return callee_type, []\n\n        if need_refresh:\n            formal_to_actual = map_actuals_to_formals(\n                arg_kinds,\n                arg_names,\n                callee_type.arg_kinds,\n                callee_type.arg_names,\n                lambda a: self.accept(args[a]),\n            )\n\n        # Same as during first pass, disable type errors (we still have partial context).\n        with self.msg.filter_errors():\n            arg_types = self.infer_arg_types_in_context(\n                callee_type, args, arg_kinds, formal_to_actual\n            )\n\n        inferred_args, _ = infer_function_type_arguments(\n            callee_type,\n            arg_types,\n            arg_kinds,\n            arg_names,\n            formal_to_actual,\n            context=self.argument_infer_context(),\n        )\n\n        return callee_type, inferred_args\n\n    def argument_infer_context(self) -> ArgumentInferContext:\n        if self._arg_infer_context_cache is None:\n            self._arg_infer_context_cache = ArgumentInferContext(\n                self.chk.named_type(\"typing.Mapping\"), self.chk.named_type(\"typing.Iterable\")\n            )\n        return self._arg_infer_context_cache\n\n    def get_arg_infer_passes(\n        self,\n        callee: CallableType,\n        args: list[Expression],\n        arg_types: list[Type],\n        formal_to_actual: list[list[int]],\n        num_actuals: int,\n    ) -> list[int]:\n        \"\"\"Return pass numbers for args for two-pass argument type inference.\n\n        For each actual, the pass number is either 1 (first pass) or 2 (second\n        pass).\n\n        Two-pass argument type inference primarily lets us infer types of\n        lambdas more effectively.\n        \"\"\"\n        res = [1] * num_actuals\n        for i, arg in enumerate(callee.arg_types):\n            skip_param_spec = False\n            p_formal = get_proper_type(callee.arg_types[i])\n            if isinstance(p_formal, CallableType) and p_formal.param_spec():\n                for j in formal_to_actual[i]:\n                    p_actual = get_proper_type(arg_types[j])\n                    # This is an exception from the usual logic where we put generic Callable\n                    # arguments in the second pass. If we have a non-generic actual, it is\n                    # likely to infer good constraints, for example if we have:\n                    #   def run(Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n                    #   def test(x: int, y: int) -> int: ...\n                    #   run(test, 1, 2)\n                    # we will use `test` for inference, since it will allow to infer also\n                    # argument *names* for P <: [x: int, y: int].\n                    if isinstance(p_actual, Instance):\n                        call_method = find_member(\"__call__\", p_actual, p_actual, is_operator=True)\n                        if call_method is not None:\n                            p_actual = get_proper_type(call_method)\n                    if (\n                        isinstance(p_actual, CallableType)\n                        and not p_actual.variables\n                        and not isinstance(args[j], LambdaExpr)\n                    ):\n                        skip_param_spec = True\n                        break\n            if not skip_param_spec and arg.accept(ArgInferSecondPassQuery()):\n                for j in formal_to_actual[i]:\n                    res[j] = 2\n        return res\n\n    def apply_inferred_arguments(\n        self, callee_type: CallableType, inferred_args: Sequence[Type | None], context: Context\n    ) -> CallableType:\n        \"\"\"Apply inferred values of type arguments to a generic function.\n\n        Inferred_args contains the values of function type arguments.\n        \"\"\"\n        # Report error if some of the variables could not be solved. In that\n        # case assume that all variables have type Any to avoid extra\n        # bogus error messages.\n        for inferred_type, tv in zip(inferred_args, callee_type.variables):\n            if not inferred_type or has_erased_component(inferred_type):\n                # Could not infer a non-trivial type for a type variable.\n                self.msg.could_not_infer_type_arguments(callee_type, tv, context)\n                inferred_args = [AnyType(TypeOfAny.from_error)] * len(inferred_args)\n        # Apply the inferred types to the function type. In this case the\n        # return type must be CallableType, since we give the right number of type\n        # arguments.\n        return self.apply_generic_arguments(callee_type, inferred_args, context)\n\n    def check_argument_count(\n        self,\n        callee: CallableType,\n        actual_types: list[Type],\n        actual_kinds: list[ArgKind],\n        actual_names: Sequence[str | None] | None,\n        formal_to_actual: list[list[int]],\n        context: Context | None,\n        object_type: Type | None = None,\n        callable_name: str | None = None,\n    ) -> bool:\n        \"\"\"Check that there is a value for all required arguments to a function.\n\n        Also check that there are no duplicate values for arguments. Report found errors\n        using 'messages' if it's not None. If 'messages' is given, 'context' must also be given.\n\n        Return False if there were any errors. Otherwise return True\n        \"\"\"\n        if context is None:\n            # Avoid \"is None\" checks\n            context = TempNode(AnyType(TypeOfAny.special_form))\n\n        # TODO(jukka): We could return as soon as we find an error if messages is None.\n\n        # Collect dict of all actual arguments matched to formal arguments, with occurrence count\n        all_actuals: dict[int, int] = {}\n        for actuals in formal_to_actual:\n            for a in actuals:\n                all_actuals[a] = all_actuals.get(a, 0) + 1\n\n        ok, is_unexpected_arg_error = self.check_for_extra_actual_arguments(\n            callee, actual_types, actual_kinds, actual_names, all_actuals, context\n        )\n\n        # Check for too many or few values for formals.\n        for i, kind in enumerate(callee.arg_kinds):\n            mapped_args = formal_to_actual[i]\n            if kind.is_required() and not mapped_args and not is_unexpected_arg_error:\n                # No actual for a mandatory formal\n                if kind.is_positional():\n                    self.msg.too_few_arguments(callee, context, actual_names)\n                    if object_type and callable_name and \".\" in callable_name:\n                        self.missing_classvar_callable_note(object_type, callable_name, context)\n                else:\n                    argname = callee.arg_names[i] or \"?\"\n                    self.msg.missing_named_argument(callee, context, argname)\n                ok = False\n            elif not kind.is_star() and is_duplicate_mapping(\n                mapped_args, actual_types, actual_kinds\n            ):\n                if self.chk.in_checked_function() or isinstance(\n                    get_proper_type(actual_types[mapped_args[0]]), TupleType\n                ):\n                    self.msg.duplicate_argument_value(callee, i, context)\n                    ok = False\n            elif (\n                kind.is_named()\n                and mapped_args\n                and actual_kinds[mapped_args[0]] not in [nodes.ARG_NAMED, nodes.ARG_STAR2]\n            ):\n                # Positional argument when expecting a keyword argument.\n                self.msg.too_many_positional_arguments(callee, context)\n                ok = False\n            elif callee.param_spec() is not None:\n                if not mapped_args and callee.special_sig != \"partial\":\n                    self.msg.too_few_arguments(callee, context, actual_names)\n                    ok = False\n                elif len(mapped_args) > 1:\n                    paramspec_entries = sum(\n                        isinstance(get_proper_type(actual_types[k]), ParamSpecType)\n                        for k in mapped_args\n                    )\n                    if actual_kinds[mapped_args[0]] == nodes.ARG_STAR and paramspec_entries > 1:\n                        self.msg.fail(\"ParamSpec.args should only be passed once\", context)\n                        ok = False\n                    if actual_kinds[mapped_args[0]] == nodes.ARG_STAR2 and paramspec_entries > 1:\n                        self.msg.fail(\"ParamSpec.kwargs should only be passed once\", context)\n                        ok = False\n        return ok\n\n    def check_for_extra_actual_arguments(\n        self,\n        callee: CallableType,\n        actual_types: list[Type],\n        actual_kinds: list[ArgKind],\n        actual_names: Sequence[str | None] | None,\n        all_actuals: dict[int, int],\n        context: Context,\n    ) -> tuple[bool, bool]:\n        \"\"\"Check for extra actual arguments.\n\n        Return tuple (was everything ok,\n                      was there an extra keyword argument error [used to avoid duplicate errors]).\n        \"\"\"\n\n        is_unexpected_arg_error = False  # Keep track of errors to avoid duplicate errors\n        ok = True  # False if we've found any error\n\n        for i, kind in enumerate(actual_kinds):\n            if (\n                i not in all_actuals\n                and\n                # We accept the other iterables than tuple (including Any)\n                # as star arguments because they could be empty, resulting no arguments.\n                (kind != nodes.ARG_STAR or is_non_empty_tuple(actual_types[i]))\n                and\n                # Accept all types for double-starred arguments, because they could be empty\n                # dictionaries and we can't tell it from their types\n                kind != nodes.ARG_STAR2\n            ):\n                # Extra actual: not matched by a formal argument.\n                ok = False\n                if kind != nodes.ARG_NAMED:\n                    self.msg.too_many_arguments(callee, context)\n                else:\n                    assert actual_names, \"Internal error: named kinds without names given\"\n                    act_name = actual_names[i]\n                    assert act_name is not None\n                    act_type = actual_types[i]\n                    self.msg.unexpected_keyword_argument(callee, act_name, act_type, context)\n                    is_unexpected_arg_error = True\n            elif (\n                kind == nodes.ARG_STAR and nodes.ARG_STAR not in callee.arg_kinds\n            ) or kind == nodes.ARG_STAR2:\n                actual_type = get_proper_type(actual_types[i])\n                if isinstance(actual_type, (TupleType, TypedDictType)):\n                    if all_actuals.get(i, 0) < len(actual_type.items):\n                        # Too many tuple/dict items as some did not match.\n                        if kind != nodes.ARG_STAR2 or not isinstance(actual_type, TypedDictType):\n                            self.msg.too_many_arguments(callee, context)\n                        else:\n                            self.msg.too_many_arguments_from_typed_dict(\n                                callee, actual_type, context\n                            )\n                            is_unexpected_arg_error = True\n                        ok = False\n                # *args/**kwargs can be applied even if the function takes a fixed\n                # number of positional arguments. This may succeed at runtime.\n\n        return ok, is_unexpected_arg_error\n\n    def missing_classvar_callable_note(\n        self, object_type: Type, callable_name: str, context: Context\n    ) -> None:\n        if isinstance(object_type, ProperType) and isinstance(object_type, Instance):\n            _, var_name = callable_name.rsplit(\".\", maxsplit=1)\n            node = object_type.type.get(var_name)\n            if node is not None and isinstance(node.node, Var):\n                if not node.node.is_inferred and not node.node.is_classvar:\n                    self.msg.note(\n                        f'\"{var_name}\" is considered instance variable,'\n                        \" to make it class variable use ClassVar[...]\",\n                        context,\n                    )\n\n    def check_var_args_kwargs(\n        self, arg_types: list[Type], arg_kinds: list[ArgKind], context: Context\n    ) -> None:\n        for arg_type, arg_kind in zip(arg_types, arg_kinds):\n            arg_type = get_proper_type(arg_type)\n            if arg_kind == nodes.ARG_STAR and not self.is_valid_var_arg(arg_type):\n                self.msg.invalid_var_arg(arg_type, context)\n            if arg_kind == nodes.ARG_STAR2 and not self.is_valid_keyword_var_arg(arg_type):\n                is_mapping = is_subtype(\n                    arg_type, self.chk.named_type(\"_typeshed.SupportsKeysAndGetItem\")\n                )\n                self.msg.invalid_keyword_var_arg(arg_type, is_mapping, context)\n\n    def check_argument_types(\n        self,\n        arg_types: list[Type],\n        arg_kinds: list[ArgKind],\n        args: list[Expression],\n        callee: CallableType,\n        formal_to_actual: list[list[int]],\n        context: Context,\n        check_arg: ArgChecker | None = None,\n        object_type: Type | None = None,\n    ) -> None:\n        \"\"\"Check argument types against a callable type.\n\n        Report errors if the argument types are not compatible.\n\n        The check_call docstring describes some of the arguments.\n        \"\"\"\n        self.check_var_args_kwargs(arg_types, arg_kinds, context)\n\n        check_arg = check_arg or self.check_arg\n        # Keep track of consumed tuple *arg items.\n        mapper = ArgTypeExpander(self.argument_infer_context())\n\n        for i, actuals in enumerate(formal_to_actual):\n            orig_callee_arg_type = get_proper_type(callee.arg_types[i])\n\n            # Checking the case that we have more than one item but the first argument\n            # is an unpack, so this would be something like:\n            # [Tuple[Unpack[Ts]], int]\n            #\n            # In this case we have to check everything together, we do this by re-unifying\n            # the suffices to the tuple, e.g. a single actual like\n            # Tuple[Unpack[Ts], int]\n            expanded_tuple = False\n            actual_kinds = [arg_kinds[a] for a in actuals]\n            if len(actuals) > 1:\n                p_actual_type = get_proper_type(arg_types[actuals[0]])\n                if (\n                    isinstance(p_actual_type, TupleType)\n                    and len(p_actual_type.items) == 1\n                    and isinstance(p_actual_type.items[0], UnpackType)\n                    and actual_kinds == [nodes.ARG_STAR] + [nodes.ARG_POS] * (len(actuals) - 1)\n                ):\n                    actual_types = [p_actual_type.items[0]] + [arg_types[a] for a in actuals[1:]]\n                    if isinstance(orig_callee_arg_type, UnpackType):\n                        p_callee_type = get_proper_type(orig_callee_arg_type.type)\n                        if isinstance(p_callee_type, TupleType):\n                            assert p_callee_type.items\n                            callee_arg_types = p_callee_type.items\n                            callee_arg_kinds = [nodes.ARG_STAR] + [nodes.ARG_POS] * (\n                                len(p_callee_type.items) - 1\n                            )\n                            expanded_tuple = True\n\n            if not expanded_tuple:\n                actual_types = [arg_types[a] for a in actuals]\n                if isinstance(orig_callee_arg_type, UnpackType):\n                    unpacked_type = get_proper_type(orig_callee_arg_type.type)\n                    if isinstance(unpacked_type, TupleType):\n                        inner_unpack_index = find_unpack_in_list(unpacked_type.items)\n                        if inner_unpack_index is None:\n                            callee_arg_types = unpacked_type.items\n                            callee_arg_kinds = [ARG_POS] * len(actuals)\n                        else:\n                            inner_unpack = unpacked_type.items[inner_unpack_index]\n                            assert isinstance(inner_unpack, UnpackType)\n                            inner_unpacked_type = get_proper_type(inner_unpack.type)\n                            if isinstance(inner_unpacked_type, TypeVarTupleType):\n                                # This branch mimics the expanded_tuple case above but for\n                                # the case where caller passed a single * unpacked tuple argument.\n                                callee_arg_types = unpacked_type.items\n                                callee_arg_kinds = [\n                                    ARG_POS if i != inner_unpack_index else ARG_STAR\n                                    for i in range(len(unpacked_type.items))\n                                ]\n                            else:\n                                # We assume heterogeneous tuples are desugared earlier.\n                                assert isinstance(inner_unpacked_type, Instance)\n                                assert inner_unpacked_type.type.fullname == \"builtins.tuple\"\n                                callee_arg_types = (\n                                    unpacked_type.items[:inner_unpack_index]\n                                    + [inner_unpacked_type.args[0]]\n                                    * (len(actuals) - len(unpacked_type.items) + 1)\n                                    + unpacked_type.items[inner_unpack_index + 1 :]\n                                )\n                                callee_arg_kinds = [ARG_POS] * len(actuals)\n                    elif isinstance(unpacked_type, TypeVarTupleType):\n                        callee_arg_types = [orig_callee_arg_type]\n                        callee_arg_kinds = [ARG_STAR]\n                    else:\n                        assert isinstance(unpacked_type, Instance)\n                        assert unpacked_type.type.fullname == \"builtins.tuple\"\n                        callee_arg_types = [unpacked_type.args[0]] * len(actuals)\n                        callee_arg_kinds = [ARG_POS] * len(actuals)\n                else:\n                    callee_arg_types = [orig_callee_arg_type] * len(actuals)\n                    callee_arg_kinds = [callee.arg_kinds[i]] * len(actuals)\n\n            assert len(actual_types) == len(actuals) == len(actual_kinds)\n\n            if len(callee_arg_types) != len(actual_types):\n                if len(actual_types) > len(callee_arg_types):\n                    self.chk.msg.too_many_arguments(callee, context)\n                else:\n                    self.chk.msg.too_few_arguments(callee, context, None)\n                continue\n\n            assert len(callee_arg_types) == len(actual_types)\n            assert len(callee_arg_types) == len(callee_arg_kinds)\n            for actual, actual_type, actual_kind, callee_arg_type, callee_arg_kind in zip(\n                actuals, actual_types, actual_kinds, callee_arg_types, callee_arg_kinds\n            ):\n                # Check that a *arg is valid as varargs.\n                expanded_actual = mapper.expand_actual_type(\n                    actual_type,\n                    actual_kind,\n                    callee.arg_names[i],\n                    callee_arg_kind,\n                    allow_unpack=isinstance(callee_arg_type, UnpackType),\n                )\n                check_arg(\n                    expanded_actual,\n                    actual_type,\n                    actual_kind,\n                    callee_arg_type,\n                    actual + 1,\n                    i + 1,\n                    callee,\n                    object_type,\n                    args[actual],\n                    context,\n                )\n\n    def check_arg(\n        self,\n        caller_type: Type,\n        original_caller_type: Type,\n        caller_kind: ArgKind,\n        callee_type: Type,\n        n: int,\n        m: int,\n        callee: CallableType,\n        object_type: Type | None,\n        context: Context,\n        outer_context: Context,\n    ) -> None:\n        \"\"\"Check the type of a single argument in a call.\"\"\"\n        caller_type = get_proper_type(caller_type)\n        original_caller_type = get_proper_type(original_caller_type)\n        callee_type = get_proper_type(callee_type)\n\n        if isinstance(caller_type, DeletedType):\n            self.msg.deleted_as_rvalue(caller_type, context)\n        # Only non-abstract non-protocol class can be given where Type[...] is expected...\n        elif self.has_abstract_type_part(caller_type, callee_type):\n            self.msg.concrete_only_call(callee_type, context)\n        elif not is_subtype(caller_type, callee_type, options=self.chk.options):\n            error = self.msg.incompatible_argument(\n                n,\n                m,\n                callee,\n                original_caller_type,\n                caller_kind,\n                object_type=object_type,\n                context=context,\n                outer_context=outer_context,\n            )\n            if not caller_kind.is_star():\n                # For *args and **kwargs this note would be incorrect - we're comparing\n                # iterable/mapping type with union of relevant arg types.\n                self.msg.incompatible_argument_note(\n                    original_caller_type, callee_type, context, parent_error=error\n                )\n            if not self.msg.prefer_simple_messages():\n                self.chk.check_possible_missing_await(\n                    caller_type, callee_type, context, error.code\n                )\n\n    def check_overload_call(\n        self,\n        callee: Overloaded,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        callable_name: str | None,\n        object_type: Type | None,\n        context: Context,\n    ) -> tuple[Type, Type]:\n        \"\"\"Checks a call to an overloaded function.\"\"\"\n        # Normalize unpacked kwargs before checking the call.\n        callee = callee.with_unpacked_kwargs()\n        arg_types = self.infer_arg_types_in_empty_context(args)\n        # Step 1: Filter call targets to remove ones where the argument counts don't match\n        plausible_targets = self.plausible_overload_call_targets(\n            arg_types, arg_kinds, arg_names, callee\n        )\n\n        # Step 2: If the arguments contain a union, we try performing union math first,\n        #         instead of picking the first matching overload.\n        #         This is because picking the first overload often ends up being too greedy:\n        #         for example, when we have a fallback alternative that accepts an unrestricted\n        #         typevar. See https://github.com/python/mypy/issues/4063 for related discussion.\n        erased_targets: list[CallableType] | None = None\n        inferred_types: list[Type] | None = None\n        unioned_result: tuple[Type, Type] | None = None\n\n        # Determine whether we need to encourage union math. This should be generally safe,\n        # as union math infers better results in the vast majority of cases, but it is very\n        # computationally intensive.\n        none_type_var_overlap = self.possible_none_type_var_overlap(arg_types, plausible_targets)\n        union_interrupted = False  # did we try all union combinations?\n        if any(self.real_union(arg) for arg in arg_types):\n            try:\n                with self.msg.filter_errors():\n                    unioned_return = self.union_overload_result(\n                        plausible_targets,\n                        args,\n                        arg_types,\n                        arg_kinds,\n                        arg_names,\n                        callable_name,\n                        object_type,\n                        none_type_var_overlap,\n                        context,\n                    )\n            except TooManyUnions:\n                union_interrupted = True\n            else:\n                # Record if we succeeded. Next we need to see if maybe normal procedure\n                # gives a narrower type.\n                if unioned_return:\n                    returns = [u[0] for u in unioned_return]\n                    inferred_types = [u[1] for u in unioned_return]\n                    # Note that we use `combine_function_signatures` instead of just returning\n                    # a union of inferred callables because for example a call\n                    # Union[int -> int, str -> str](Union[int, str]) is invalid and\n                    # we don't want to introduce internal inconsistencies.\n                    unioned_result = (\n                        make_simplified_union(returns, context.line, context.column),\n                        self.combine_function_signatures(get_proper_types(inferred_types)),\n                    )\n\n        # Step 3: We try checking each branch one-by-one.\n        inferred_result = self.infer_overload_return_type(\n            plausible_targets,\n            args,\n            arg_types,\n            arg_kinds,\n            arg_names,\n            callable_name,\n            object_type,\n            context,\n        )\n        # If any of checks succeed, perform deprecation tests and stop early.\n        if inferred_result is not None and unioned_result is not None:\n            # Both unioned and direct checks succeeded, choose the more precise type.\n            if (\n                is_subtype(inferred_result[0], unioned_result[0])\n                and not isinstance(get_proper_type(inferred_result[0]), AnyType)\n                and not none_type_var_overlap\n            ):\n                unioned_result = None\n            else:\n                inferred_result = None\n        if unioned_result is not None:\n            if inferred_types is not None:\n                for inferred_type in inferred_types:\n                    if isinstance(c := get_proper_type(inferred_type), CallableType):\n                        self.chk.warn_deprecated(c.definition, context)\n            return unioned_result\n        if inferred_result is not None:\n            if isinstance(c := get_proper_type(inferred_result[1]), CallableType):\n                self.chk.warn_deprecated(c.definition, context)\n            return inferred_result\n\n        # Step 4: Failure. At this point, we know there is no match. We fall back to trying\n        #         to find a somewhat plausible overload target using the erased types\n        #         so we can produce a nice error message.\n        #\n        #         For example, suppose the user passes a value of type 'List[str]' into an\n        #         overload with signatures f(x: int) -> int and f(x: List[int]) -> List[int].\n        #\n        #         Neither alternative matches, but we can guess the user probably wants the\n        #         second one.\n        erased_targets = self.overload_erased_call_targets(\n            plausible_targets, arg_types, arg_kinds, arg_names, args, context\n        )\n\n        # Step 5: We try and infer a second-best alternative if possible. If not, fall back\n        #         to using 'Any'.\n        if len(erased_targets) > 0:\n            # Pick the first plausible erased target as the fallback\n            # TODO: Adjust the error message here to make it clear there was no match.\n            #       In order to do this, we need to find a clean way of associating\n            #       a note with whatever error message 'self.check_call' will generate.\n            #       In particular, the note's line and column numbers need to be the same\n            #       as the error's.\n            target: Type = erased_targets[0]\n        else:\n            # There was no plausible match: give up\n            target = AnyType(TypeOfAny.from_error)\n            if not is_operator_method(callable_name):\n                code = None\n            else:\n                code = codes.OPERATOR\n            self.msg.no_variant_matches_arguments(callee, arg_types, context, code=code)\n\n        result = self.check_call(\n            target,\n            args,\n            arg_kinds,\n            context,\n            arg_names,\n            callable_name=callable_name,\n            object_type=object_type,\n        )\n        # Do not show the extra error if the union math was forced.\n        if union_interrupted and not none_type_var_overlap:\n            self.chk.fail(message_registry.TOO_MANY_UNION_COMBINATIONS, context)\n        return result\n\n    def plausible_overload_call_targets(\n        self,\n        arg_types: list[Type],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        overload: Overloaded,\n    ) -> list[CallableType]:\n        \"\"\"Returns all overload call targets that having matching argument counts.\n\n        If the given args contains a star-arg (*arg or **kwarg argument, except for\n        ParamSpec), this method will ensure all star-arg overloads appear at the start\n        of the list, instead of their usual location.\n\n        The only exception is if the starred argument is something like a Tuple or a\n        NamedTuple, which has a definitive \"shape\". If so, we don't move the corresponding\n        alternative to the front since we can infer a more precise match using the original\n        order.\"\"\"\n\n        def has_shape(typ: Type) -> bool:\n            typ = get_proper_type(typ)\n            return isinstance(typ, (TupleType, TypedDictType)) or (\n                isinstance(typ, Instance) and typ.type.is_named_tuple\n            )\n\n        matches: list[CallableType] = []\n        star_matches: list[CallableType] = []\n\n        args_have_var_arg = False\n        args_have_kw_arg = False\n        for kind, typ in zip(arg_kinds, arg_types):\n            if kind == ARG_STAR and not has_shape(typ):\n                args_have_var_arg = True\n            if kind == ARG_STAR2 and not has_shape(typ):\n                args_have_kw_arg = True\n\n        for typ in overload.items:\n            formal_to_actual = map_actuals_to_formals(\n                arg_kinds, arg_names, typ.arg_kinds, typ.arg_names, lambda i: arg_types[i]\n            )\n            with self.msg.filter_errors():\n                if typ.param_spec() is not None:\n                    # ParamSpec can be expanded in a lot of different ways. We may try\n                    # to expand it here instead, but picking an impossible overload\n                    # is safe: it will be filtered out later.\n                    # Unlike other var-args signatures, ParamSpec produces essentially\n                    # a fixed signature, so there's no need to push them to the top.\n                    matches.append(typ)\n                elif self.check_argument_count(\n                    typ, arg_types, arg_kinds, arg_names, formal_to_actual, None\n                ):\n                    if args_have_var_arg and typ.is_var_arg:\n                        star_matches.append(typ)\n                    elif args_have_kw_arg and typ.is_kw_arg:\n                        star_matches.append(typ)\n                    else:\n                        matches.append(typ)\n\n        return star_matches + matches\n\n    def infer_overload_return_type(\n        self,\n        plausible_targets: list[CallableType],\n        args: list[Expression],\n        arg_types: list[Type],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        callable_name: str | None,\n        object_type: Type | None,\n        context: Context,\n    ) -> tuple[Type, Type] | None:\n        \"\"\"Attempts to find the first matching callable from the given list.\n\n        If a match is found, returns a tuple containing the result type and the inferred\n        callee type. (This tuple is meant to be eventually returned by check_call.)\n        If multiple targets match due to ambiguous Any parameters, returns (AnyType, AnyType).\n        If no targets match, returns None.\n\n        Assumes all of the given targets have argument counts compatible with the caller.\n        \"\"\"\n\n        matches: list[CallableType] = []\n        return_types: list[Type] = []\n        inferred_types: list[Type] = []\n        args_contain_any = any(map(has_any_type, arg_types))\n        type_maps: list[dict[Expression, Type]] = []\n\n        for typ in plausible_targets:\n            assert self.msg is self.chk.msg\n            with self.msg.filter_errors(filter_revealed_type=True) as w:\n                with self.chk.local_type_map as m:\n                    ret_type, infer_type = self.check_call(\n                        callee=typ,\n                        args=args,\n                        arg_kinds=arg_kinds,\n                        arg_names=arg_names,\n                        context=context,\n                        callable_name=callable_name,\n                        object_type=object_type,\n                    )\n            is_match = not w.has_new_errors()\n            if is_match:\n                # Return early if possible; otherwise record info, so we can\n                # check for ambiguity due to 'Any' below.\n                if not args_contain_any:\n                    self.chk.store_types(m)\n                    return ret_type, infer_type\n                p_infer_type = get_proper_type(infer_type)\n                if isinstance(p_infer_type, CallableType):\n                    # Prefer inferred types if possible, this will avoid false triggers for\n                    # Any-ambiguity caused by arguments with Any passed to generic overloads.\n                    matches.append(p_infer_type)\n                else:\n                    matches.append(typ)\n                return_types.append(ret_type)\n                inferred_types.append(infer_type)\n                type_maps.append(m)\n\n        if not matches:\n            return None\n        elif any_causes_overload_ambiguity(matches, return_types, arg_types, arg_kinds, arg_names):\n            # An argument of type or containing the type 'Any' caused ambiguity.\n            # We try returning a precise type if we can. If not, we give up and just return 'Any'.\n            if all_same_types(return_types):\n                self.chk.store_types(type_maps[0])\n                return return_types[0], inferred_types[0]\n            elif all_same_types([erase_type(typ) for typ in return_types]):\n                self.chk.store_types(type_maps[0])\n                return erase_type(return_types[0]), erase_type(inferred_types[0])\n            else:\n                return self.check_call(\n                    callee=AnyType(TypeOfAny.special_form),\n                    args=args,\n                    arg_kinds=arg_kinds,\n                    arg_names=arg_names,\n                    context=context,\n                    callable_name=callable_name,\n                    object_type=object_type,\n                )\n        else:\n            # Success! No ambiguity; return the first match.\n            self.chk.store_types(type_maps[0])\n            return return_types[0], inferred_types[0]\n\n    def overload_erased_call_targets(\n        self,\n        plausible_targets: list[CallableType],\n        arg_types: list[Type],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        args: list[Expression],\n        context: Context,\n    ) -> list[CallableType]:\n        \"\"\"Returns a list of all targets that match the caller after erasing types.\n\n        Assumes all of the given targets have argument counts compatible with the caller.\n        \"\"\"\n        matches: list[CallableType] = []\n        for typ in plausible_targets:\n            if self.erased_signature_similarity(\n                arg_types, arg_kinds, arg_names, args, typ, context\n            ):\n                matches.append(typ)\n        return matches\n\n    def possible_none_type_var_overlap(\n        self, arg_types: list[Type], plausible_targets: list[CallableType]\n    ) -> bool:\n        \"\"\"Heuristic to determine whether we need to try forcing union math.\n\n        This is needed to avoid greedy type variable match in situations like this:\n            @overload\n            def foo(x: None) -> None: ...\n            @overload\n            def foo(x: T) -> list[T]: ...\n\n            x: int | None\n            foo(x)\n        we want this call to infer list[int] | None, not list[int | None].\n        \"\"\"\n        if not plausible_targets or not arg_types:\n            return False\n        has_optional_arg = False\n        for arg_type in get_proper_types(arg_types):\n            if not isinstance(arg_type, UnionType):\n                continue\n            for item in get_proper_types(arg_type.items):\n                if isinstance(item, NoneType):\n                    has_optional_arg = True\n                    break\n        if not has_optional_arg:\n            return False\n\n        min_prefix = min(len(c.arg_types) for c in plausible_targets)\n        for i in range(min_prefix):\n            if any(\n                isinstance(get_proper_type(c.arg_types[i]), NoneType) for c in plausible_targets\n            ) and any(\n                isinstance(get_proper_type(c.arg_types[i]), TypeVarType) for c in plausible_targets\n            ):\n                return True\n        return False\n\n    def union_overload_result(\n        self,\n        plausible_targets: list[CallableType],\n        args: list[Expression],\n        arg_types: list[Type],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        callable_name: str | None,\n        object_type: Type | None,\n        none_type_var_overlap: bool,\n        context: Context,\n        level: int = 0,\n    ) -> list[tuple[Type, Type]] | None:\n        \"\"\"Accepts a list of overload signatures and attempts to match calls by destructuring\n        the first union.\n\n        Return a list of (<return type>, <inferred variant type>) if call succeeds for every\n        item of the desctructured union. Returns None if there is no match.\n        \"\"\"\n        # Step 1: If we are already too deep, then stop immediately. Otherwise mypy might\n        # hang for long time because of a weird overload call. The caller will get\n        # the exception and generate an appropriate note message, if needed.\n        if level >= MAX_UNIONS:\n            raise TooManyUnions\n\n        # Step 2: Find position of the first union in arguments. Return the normal inferred\n        # type if no more unions left.\n        for idx, typ in enumerate(arg_types):\n            if self.real_union(typ):\n                break\n        else:\n            # No unions in args, just fall back to normal inference\n            with self.type_overrides_set(args, arg_types):\n                res = self.infer_overload_return_type(\n                    plausible_targets,\n                    args,\n                    arg_types,\n                    arg_kinds,\n                    arg_names,\n                    callable_name,\n                    object_type,\n                    context,\n                )\n            if res is not None:\n                return [res]\n            return None\n\n        # Step 3: Try a direct match before splitting to avoid unnecessary union splits\n        # and save performance.\n        if not none_type_var_overlap:\n            with self.type_overrides_set(args, arg_types):\n                direct = self.infer_overload_return_type(\n                    plausible_targets,\n                    args,\n                    arg_types,\n                    arg_kinds,\n                    arg_names,\n                    callable_name,\n                    object_type,\n                    context,\n                )\n            if direct is not None and not isinstance(\n                get_proper_type(direct[0]), (UnionType, AnyType)\n            ):\n                # We only return non-unions soon, to avoid greedy match.\n                return [direct]\n\n        # Step 4: Split the first remaining union type in arguments into items and\n        # try to match each item individually (recursive).\n        first_union = get_proper_type(arg_types[idx])\n        assert isinstance(first_union, UnionType)\n        res_items = []\n        for item in first_union.relevant_items():\n            new_arg_types = arg_types.copy()\n            new_arg_types[idx] = item\n            sub_result = self.union_overload_result(\n                plausible_targets,\n                args,\n                new_arg_types,\n                arg_kinds,\n                arg_names,\n                callable_name,\n                object_type,\n                none_type_var_overlap,\n                context,\n                level + 1,\n            )\n            if sub_result is not None:\n                res_items.extend(sub_result)\n            else:\n                # Some item doesn't match, return soon.\n                return None\n\n        # Step 5: If splitting succeeded, then filter out duplicate items before returning.\n        seen: set[tuple[Type, Type]] = set()\n        result = []\n        for pair in res_items:\n            if pair not in seen:\n                seen.add(pair)\n                result.append(pair)\n        return result\n\n    def real_union(self, typ: Type) -> bool:\n        typ = get_proper_type(typ)\n        return isinstance(typ, UnionType) and len(typ.relevant_items()) > 1\n\n    @contextmanager\n    def type_overrides_set(\n        self, exprs: Sequence[Expression], overrides: Sequence[Type]\n    ) -> Iterator[None]:\n        \"\"\"Set _temporary_ type overrides for given expressions.\"\"\"\n        assert len(exprs) == len(overrides)\n        for expr, typ in zip(exprs, overrides):\n            self.type_overrides[expr] = typ\n        try:\n            yield\n        finally:\n            for expr in exprs:\n                del self.type_overrides[expr]\n\n    def combine_function_signatures(self, types: list[ProperType]) -> AnyType | CallableType:\n        \"\"\"Accepts a list of function signatures and attempts to combine them together into a\n        new CallableType consisting of the union of all of the given arguments and return types.\n\n        If there is at least one non-callable type, return Any (this can happen if there is\n        an ambiguity because of Any in arguments).\n        \"\"\"\n        assert types, \"Trying to merge no callables\"\n        if not all(isinstance(c, CallableType) for c in types):\n            return AnyType(TypeOfAny.special_form)\n        callables = cast(\"list[CallableType]\", types)\n        if len(callables) == 1:\n            return callables[0]\n\n        # Note: we are assuming here that if a user uses some TypeVar 'T' in\n        # two different functions, they meant for that TypeVar to mean the\n        # same thing.\n        #\n        # This function will make sure that all instances of that TypeVar 'T'\n        # refer to the same underlying TypeVarType objects to simplify the union-ing\n        # logic below.\n        #\n        # (If the user did *not* mean for 'T' to be consistently bound to the\n        # same type in their overloads, well, their code is probably too\n        # confusing and ought to be re-written anyways.)\n        callables, variables = merge_typevars_in_callables_by_name(callables)\n\n        new_args: list[list[Type]] = [[] for _ in range(len(callables[0].arg_types))]\n        new_kinds = list(callables[0].arg_kinds)\n        new_returns: list[Type] = []\n\n        too_complex = False\n        for target in callables:\n            # We fall back to Callable[..., Union[<returns>]] if the functions do not have\n            # the exact same signature. The only exception is if one arg is optional and\n            # the other is positional: in that case, we continue unioning (and expect a\n            # positional arg).\n            # TODO: Enhance the merging logic to handle a wider variety of signatures.\n            if len(new_kinds) != len(target.arg_kinds):\n                too_complex = True\n                break\n            for i, (new_kind, target_kind) in enumerate(zip(new_kinds, target.arg_kinds)):\n                if new_kind == target_kind:\n                    continue\n                elif new_kind.is_positional() and target_kind.is_positional():\n                    new_kinds[i] = ARG_POS\n                else:\n                    too_complex = True\n                    break\n\n            if too_complex:\n                break  # outer loop\n\n            for i, arg in enumerate(target.arg_types):\n                new_args[i].append(arg)\n            new_returns.append(target.ret_type)\n\n        union_return = make_simplified_union(new_returns)\n        if too_complex:\n            any = AnyType(TypeOfAny.special_form)\n            return callables[0].copy_modified(\n                arg_types=[any, any],\n                arg_kinds=[ARG_STAR, ARG_STAR2],\n                arg_names=[None, None],\n                ret_type=union_return,\n                variables=variables,\n                implicit=True,\n            )\n\n        final_args = []\n        for args_list in new_args:\n            new_type = make_simplified_union(args_list)\n            final_args.append(new_type)\n\n        return callables[0].copy_modified(\n            arg_types=final_args,\n            arg_kinds=new_kinds,\n            ret_type=union_return,\n            variables=variables,\n            implicit=True,\n        )\n\n    def erased_signature_similarity(\n        self,\n        arg_types: list[Type],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        args: list[Expression],\n        callee: CallableType,\n        context: Context,\n    ) -> bool:\n        \"\"\"Determine whether arguments could match the signature at runtime, after\n        erasing types.\"\"\"\n        formal_to_actual = map_actuals_to_formals(\n            arg_kinds, arg_names, callee.arg_kinds, callee.arg_names, lambda i: arg_types[i]\n        )\n\n        with self.msg.filter_errors():\n            if not self.check_argument_count(\n                callee, arg_types, arg_kinds, arg_names, formal_to_actual, None\n            ):\n                # Too few or many arguments -> no match.\n                return False\n\n        def check_arg(\n            caller_type: Type,\n            original_ccaller_type: Type,\n            caller_kind: ArgKind,\n            callee_type: Type,\n            n: int,\n            m: int,\n            callee: CallableType,\n            object_type: Type | None,\n            context: Context,\n            outer_context: Context,\n        ) -> None:\n            if not arg_approximate_similarity(caller_type, callee_type):\n                # No match -- exit early since none of the remaining work can change\n                # the result.\n                raise Finished\n\n        try:\n            self.check_argument_types(\n                arg_types,\n                arg_kinds,\n                args,\n                callee,\n                formal_to_actual,\n                context=context,\n                check_arg=check_arg,\n            )\n            return True\n        except Finished:\n            return False\n\n    def apply_generic_arguments(\n        self,\n        callable: CallableType,\n        types: Sequence[Type | None],\n        context: Context,\n        skip_unsatisfied: bool = False,\n    ) -> CallableType:\n        \"\"\"Simple wrapper around mypy.applytype.apply_generic_arguments.\"\"\"\n        return applytype.apply_generic_arguments(\n            callable,\n            types,\n            self.msg.incompatible_typevar_value,\n            context,\n            skip_unsatisfied=skip_unsatisfied,\n        )\n\n    def check_any_type_call(\n        self, args: list[Expression], arg_kinds: list[ArgKind], callee: Type, context: Context\n    ) -> tuple[Type, Type]:\n        arg_types = self.infer_arg_types_in_empty_context(args)\n        self.check_var_args_kwargs(arg_types, arg_kinds, context)\n\n        callee = get_proper_type(callee)\n        if isinstance(callee, AnyType):\n            return (\n                AnyType(TypeOfAny.from_another_any, source_any=callee),\n                AnyType(TypeOfAny.from_another_any, source_any=callee),\n            )\n        else:\n            return AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form)\n\n    def check_union_call(\n        self,\n        callee: UnionType,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None] | None,\n        context: Context,\n    ) -> tuple[Type, Type]:\n        with self.msg.disable_type_names():\n            results = [\n                self.check_call(subtype, args, arg_kinds, context, arg_names)\n                for subtype in callee.relevant_items()\n            ]\n\n        return (make_simplified_union([res[0] for res in results]), callee)\n\n    def visit_member_expr(self, e: MemberExpr, is_lvalue: bool = False) -> Type:\n        \"\"\"Visit member expression (of form e.id).\"\"\"\n        result = self.analyze_ordinary_member_access(e, is_lvalue)\n        narrowed = self.narrow_type_from_binder(e, result)\n        self.chk.warn_deprecated(e.node, e)\n        return narrowed\n\n    def analyze_ordinary_member_access(\n        self, e: MemberExpr, is_lvalue: bool, rvalue: Expression | None = None\n    ) -> Type:\n        \"\"\"Analyse member expression or member lvalue.\n\n        An rvalue can be provided optionally to infer better setter type when is_lvalue is True.\n        \"\"\"\n        if e.kind is not None:\n            # This is a reference to a module attribute.\n            return self.analyze_ref_expr(e)\n        else:\n            # This is a reference to a non-module attribute.\n            original_type = self.accept(e.expr, is_callee=self.is_callee)\n            base = e.expr\n            module_symbol_table = None\n\n            if isinstance(base, RefExpr) and isinstance(base.node, MypyFile):\n                module_symbol_table = base.node.names\n            if isinstance(base, RefExpr) and isinstance(base.node, Var):\n                # This is needed to special case self-types, so we don't need to track\n                # these flags separately in checkmember.py.\n                is_self = base.node.is_self or base.node.is_cls\n            else:\n                is_self = False\n\n            member_type = analyze_member_access(\n                e.name,\n                original_type,\n                e,\n                is_lvalue=is_lvalue,\n                is_super=False,\n                is_operator=False,\n                original_type=original_type,\n                chk=self.chk,\n                in_literal_context=self.is_literal_context(),\n                module_symbol_table=module_symbol_table,\n                is_self=is_self,\n                rvalue=rvalue,\n            )\n\n            return member_type\n\n    def analyze_external_member_access(\n        self, member: str, base_type: Type, context: Context\n    ) -> Type:\n        \"\"\"Analyse member access that is external, i.e. it cannot\n        refer to private definitions. Return the result type.\n        \"\"\"\n        # TODO remove; no private definitions in mypy\n        return analyze_member_access(\n            member,\n            base_type,\n            context,\n            is_lvalue=False,\n            is_super=False,\n            is_operator=False,\n            original_type=base_type,\n            chk=self.chk,\n            in_literal_context=self.is_literal_context(),\n        )\n\n    def is_literal_context(self) -> bool:\n        return is_literal_type_like(self.type_context[-1])\n\n    def infer_literal_expr_type(self, value: LiteralValue, fallback_name: str) -> Type:\n        \"\"\"Analyzes the given literal expression and determines if we should be\n        inferring an Instance type, a Literal[...] type, or an Instance that\n        remembers the original literal. We...\n\n        1. ...Infer a normal Instance in most circumstances.\n\n        2. ...Infer a Literal[...] if we're in a literal context. For example, if we\n           were analyzing the \"3\" in \"foo(3)\" where \"foo\" has a signature of\n           \"def foo(Literal[3]) -> None\", we'd want to infer that the \"3\" has a\n           type of Literal[3] instead of Instance.\n\n        3. ...Infer an Instance that remembers the original Literal if we're declaring\n           a Final variable with an inferred type -- for example, \"bar\" in \"bar: Final = 3\"\n           would be assigned an Instance that remembers it originated from a '3'. See\n           the comments in Instance's constructor for more details.\n        \"\"\"\n        typ = self.named_type(fallback_name)\n        if self.is_literal_context():\n            return LiteralType(value=value, fallback=typ)\n        else:\n            if value is True:\n                if self._literal_true is None:\n                    self._literal_true = typ.copy_modified(\n                        last_known_value=LiteralType(value=value, fallback=typ)\n                    )\n                return self._literal_true\n            if value is False:\n                if self._literal_false is None:\n                    self._literal_false = typ.copy_modified(\n                        last_known_value=LiteralType(value=value, fallback=typ)\n                    )\n                return self._literal_false\n            return typ.copy_modified(last_known_value=LiteralType(value=value, fallback=typ))\n\n    def concat_tuples(self, left: TupleType, right: TupleType) -> TupleType:\n        \"\"\"Concatenate two fixed length tuples.\"\"\"\n        assert not (find_unpack_in_list(left.items) and find_unpack_in_list(right.items))\n        return TupleType(\n            items=left.items + right.items, fallback=self.named_type(\"builtins.tuple\")\n        )\n\n    def visit_int_expr(self, e: IntExpr) -> Type:\n        \"\"\"Type check an integer literal (trivial).\"\"\"\n        return self.infer_literal_expr_type(e.value, \"builtins.int\")\n\n    def visit_str_expr(self, e: StrExpr) -> Type:\n        \"\"\"Type check a string literal (trivial).\"\"\"\n        return self.infer_literal_expr_type(e.value, \"builtins.str\")\n\n    def visit_bytes_expr(self, e: BytesExpr) -> Type:\n        \"\"\"Type check a bytes literal (trivial).\"\"\"\n        return self.infer_literal_expr_type(e.value, \"builtins.bytes\")\n\n    def visit_float_expr(self, e: FloatExpr) -> Type:\n        \"\"\"Type check a float literal (trivial).\"\"\"\n        return self.named_type(\"builtins.float\")\n\n    def visit_complex_expr(self, e: ComplexExpr) -> Type:\n        \"\"\"Type check a complex literal.\"\"\"\n        return self.named_type(\"builtins.complex\")\n\n    def visit_ellipsis(self, e: EllipsisExpr) -> Type:\n        \"\"\"Type check '...'.\"\"\"\n        return self.named_type(\"builtins.ellipsis\")\n\n    def visit_op_expr(self, e: OpExpr) -> Type:\n        \"\"\"Type check a binary operator expression.\"\"\"\n        if e.analyzed:\n            # It's actually a type expression X | Y.\n            return self.accept(e.analyzed)\n        if e.op == \"and\" or e.op == \"or\":\n            return self.check_boolean_op(e)\n        if e.op == \"*\" and isinstance(e.left, ListExpr):\n            # Expressions of form [...] * e get special type inference.\n            return self.check_list_multiply(e)\n        if e.op == \"%\":\n            if isinstance(e.left, BytesExpr):\n                return self.strfrm_checker.check_str_interpolation(e.left, e.right)\n            if isinstance(e.left, StrExpr):\n                return self.strfrm_checker.check_str_interpolation(e.left, e.right)\n        left_type = self.accept(e.left)\n\n        proper_left_type = get_proper_type(left_type)\n        if isinstance(proper_left_type, TupleType) and e.op == \"+\":\n            left_add_method = proper_left_type.partial_fallback.type.get(\"__add__\")\n            if left_add_method and left_add_method.fullname == \"builtins.tuple.__add__\":\n                proper_right_type = get_proper_type(self.accept(e.right))\n                if isinstance(proper_right_type, TupleType):\n                    right_radd_method = proper_right_type.partial_fallback.type.get(\"__radd__\")\n                    if right_radd_method is None:\n                        # One cannot have two variadic items in the same tuple.\n                        if (\n                            find_unpack_in_list(proper_left_type.items) is None\n                            or find_unpack_in_list(proper_right_type.items) is None\n                        ):\n                            return self.concat_tuples(proper_left_type, proper_right_type)\n                elif (\n                    PRECISE_TUPLE_TYPES in self.chk.options.enable_incomplete_feature\n                    and isinstance(proper_right_type, Instance)\n                    and self.chk.type_is_iterable(proper_right_type)\n                ):\n                    # Handle tuple[X, Y] + tuple[Z, ...] = tuple[X, Y, *tuple[Z, ...]].\n                    right_radd_method = proper_right_type.type.get(\"__radd__\")\n                    if (\n                        right_radd_method is None\n                        and proper_left_type.partial_fallback.type.fullname == \"builtins.tuple\"\n                        and find_unpack_in_list(proper_left_type.items) is None\n                    ):\n                        item_type = self.chk.iterable_item_type(proper_right_type, e)\n                        mapped = self.chk.named_generic_type(\"builtins.tuple\", [item_type])\n                        return proper_left_type.copy_modified(\n                            items=proper_left_type.items + [UnpackType(mapped)]\n                        )\n\n        use_reverse: UseReverse = USE_REVERSE_DEFAULT\n        if e.op == \"|\":\n            if is_named_instance(proper_left_type, \"builtins.dict\"):\n                # This is a special case for `dict | TypedDict`.\n                # 1. Find `dict | TypedDict` case\n                # 2. Switch `dict.__or__` to `TypedDict.__ror__` (the same from both runtime and typing perspective)\n                proper_right_type = get_proper_type(self.accept(e.right))\n                if isinstance(proper_right_type, TypedDictType):\n                    use_reverse = USE_REVERSE_ALWAYS\n            if isinstance(proper_left_type, TypedDictType):\n                # This is the reverse case: `TypedDict | dict`,\n                # simply do not allow the reverse checking:\n                # do not call `__dict__.__ror__`.\n                proper_right_type = get_proper_type(self.accept(e.right))\n                if is_named_instance(proper_right_type, \"builtins.dict\"):\n                    use_reverse = USE_REVERSE_NEVER\n\n        if PRECISE_TUPLE_TYPES in self.chk.options.enable_incomplete_feature:\n            # Handle tuple[X, ...] + tuple[Y, Z] = tuple[*tuple[X, ...], Y, Z].\n            if (\n                e.op == \"+\"\n                and isinstance(proper_left_type, Instance)\n                and proper_left_type.type.fullname == \"builtins.tuple\"\n            ):\n                proper_right_type = get_proper_type(self.accept(e.right))\n                if (\n                    isinstance(proper_right_type, TupleType)\n                    and proper_right_type.partial_fallback.type.fullname == \"builtins.tuple\"\n                    and find_unpack_in_list(proper_right_type.items) is None\n                ):\n                    return proper_right_type.copy_modified(\n                        items=[UnpackType(proper_left_type)] + proper_right_type.items\n                    )\n\n        if e.op in operators.op_methods:\n            method = operators.op_methods[e.op]\n            if use_reverse is UseReverse.DEFAULT or use_reverse is UseReverse.NEVER:\n                result, method_type = self.check_op(\n                    method,\n                    base_type=left_type,\n                    arg=e.right,\n                    context=e,\n                    allow_reverse=use_reverse is UseReverse.DEFAULT,\n                )\n            elif use_reverse is UseReverse.ALWAYS:\n                result, method_type = self.check_op(\n                    # The reverse operator here gives better error messages:\n                    operators.reverse_op_methods[method],\n                    base_type=self.accept(e.right),\n                    arg=e.left,\n                    context=e,\n                    allow_reverse=False,\n                )\n            else:\n                assert_never(use_reverse)\n            e.method_type = method_type\n            return result\n        else:\n            raise RuntimeError(f\"Unknown operator {e.op}\")\n\n    def visit_comparison_expr(self, e: ComparisonExpr) -> Type:\n        \"\"\"Type check a comparison expression.\n\n        Comparison expressions are type checked consecutive-pair-wise\n        That is, 'a < b > c == d' is check as 'a < b and b > c and c == d'\n        \"\"\"\n        result: Type | None = None\n        sub_result: Type\n\n        # Check each consecutive operand pair and their operator\n        for left, right, operator in zip(e.operands, e.operands[1:], e.operators):\n            left_type = self.accept(left)\n\n            if operator == \"in\" or operator == \"not in\":\n                # This case covers both iterables and containers, which have different meanings.\n                # For a container, the in operator calls the __contains__ method.\n                # For an iterable, the in operator iterates over the iterable, and compares each item one-by-one.\n                # We allow `in` for a union of containers and iterables as long as at least one of them matches the\n                # type of the left operand, as the operation will simply return False if the union's container/iterator\n                # type doesn't match the left operand.\n\n                # If the right operand has partial type, look it up without triggering\n                # a \"Need type annotation ...\" message, as it would be noise.\n                right_type = self.find_partial_type_ref_fast_path(right)\n                if right_type is None:\n                    right_type = self.accept(right)  # Validate the right operand\n\n                right_type = get_proper_type(right_type)\n                item_types: Sequence[Type] = [right_type]\n                if isinstance(right_type, UnionType):\n                    item_types = list(right_type.relevant_items())\n\n                sub_result = self.bool_type()\n\n                container_types: list[Type] = []\n                iterable_types: list[Type] = []\n                failed_out = False\n                encountered_partial_type = False\n\n                for item_type in item_types:\n                    # Keep track of whether we get type check errors (these won't be reported, they\n                    # are just to verify whether something is valid typing wise).\n                    with self.msg.filter_errors(save_filtered_errors=True) as container_errors:\n                        _, method_type = self.check_method_call_by_name(\n                            method=\"__contains__\",\n                            base_type=item_type,\n                            args=[left],\n                            arg_kinds=[ARG_POS],\n                            context=e,\n                            original_type=right_type,\n                        )\n                        # Container item type for strict type overlap checks. Note: we need to only\n                        # check for nominal type, because a usual \"Unsupported operands for in\"\n                        # will be reported for types incompatible with __contains__().\n                        # See testCustomContainsCheckStrictEquality for an example.\n                        cont_type = self.chk.analyze_container_item_type(item_type)\n\n                    if isinstance(item_type, PartialType):\n                        # We don't really know if this is an error or not, so just shut up.\n                        encountered_partial_type = True\n                        pass\n                    elif (\n                        container_errors.has_new_errors()\n                        and\n                        # is_valid_var_arg is True for any Iterable\n                        self.is_valid_var_arg(item_type)\n                    ):\n                        # it's not a container, but it is an iterable\n                        with self.msg.filter_errors(save_filtered_errors=True) as iterable_errors:\n                            _, itertype = self.chk.analyze_iterable_item_type_without_expression(\n                                item_type, e\n                            )\n                        if iterable_errors.has_new_errors():\n                            self.msg.add_errors(iterable_errors.filtered_errors())\n                            failed_out = True\n                        else:\n                            method_type = CallableType(\n                                [left_type],\n                                [nodes.ARG_POS],\n                                [None],\n                                self.bool_type(),\n                                self.named_type(\"builtins.function\"),\n                            )\n                            e.method_types.append(method_type)\n                            iterable_types.append(itertype)\n                    elif not container_errors.has_new_errors() and cont_type:\n                        container_types.append(cont_type)\n                        e.method_types.append(method_type)\n                    else:\n                        self.msg.add_errors(container_errors.filtered_errors())\n                        failed_out = True\n\n                if not encountered_partial_type and not failed_out:\n                    iterable_type = UnionType.make_union(iterable_types)\n                    if not is_subtype(left_type, iterable_type):\n                        if not container_types:\n                            self.msg.unsupported_operand_types(\"in\", left_type, right_type, e)\n                        else:\n                            container_type = UnionType.make_union(container_types)\n                            if not self.chk.can_skip_diagnostics and self.dangerous_comparison(\n                                left_type,\n                                container_type,\n                                original_container=right_type,\n                                prefer_literal=False,\n                            ):\n                                self.msg.dangerous_comparison(\n                                    left_type, container_type, \"container\", e\n                                )\n\n            elif operator in operators.op_methods:\n                method = operators.op_methods[operator]\n\n                with ErrorWatcher(self.msg.errors) as w:\n                    sub_result, method_type = self.check_op(\n                        method, left_type, right, e, allow_reverse=True\n                    )\n                    e.method_types.append(method_type)\n\n                # Only show dangerous overlap if there are no other errors. See\n                # testCustomEqCheckStrictEquality for an example.\n                if not w.has_new_errors() and operator in (\"==\", \"!=\"):\n                    right_type = self.accept(right)\n                    if not self.chk.can_skip_diagnostics and self.dangerous_comparison(\n                        left_type, right_type\n                    ):\n                        # Show the most specific literal types possible\n                        left_type = try_getting_literal(left_type)\n                        right_type = try_getting_literal(right_type)\n                        self.msg.dangerous_comparison(left_type, right_type, \"equality\", e)\n\n            elif operator == \"is\" or operator == \"is not\":\n                right_type = self.accept(right)  # validate the right operand\n                sub_result = self.bool_type()\n                if not self.chk.can_skip_diagnostics and self.dangerous_comparison(\n                    left_type, right_type, identity_check=True\n                ):\n                    # Show the most specific literal types possible\n                    left_type = try_getting_literal(left_type)\n                    right_type = try_getting_literal(right_type)\n                    self.msg.dangerous_comparison(left_type, right_type, \"identity\", e)\n                e.method_types.append(None)\n            else:\n                raise RuntimeError(f\"Unknown comparison operator {operator}\")\n\n            #  Determine type of boolean-and of result and sub_result\n            if result is None:\n                result = sub_result\n            else:\n                result = join.join_types(result, sub_result)\n\n        assert result is not None\n        return result\n\n    def find_partial_type_ref_fast_path(self, expr: Expression) -> Type | None:\n        \"\"\"If expression has a partial generic type, return it without additional checks.\n\n        In particular, this does not generate an error about a missing annotation.\n\n        Otherwise, return None.\n        \"\"\"\n        if not isinstance(expr, RefExpr):\n            return None\n        if isinstance(expr.node, Var):\n            result = self.analyze_var_ref(expr.node, expr)\n            if isinstance(result, PartialType) and result.type is not None:\n                self.chk.store_type(expr, fixup_partial_type(result))\n                return result\n        return None\n\n    def dangerous_comparison(\n        self,\n        left: Type,\n        right: Type,\n        *,\n        original_container: Type | None = None,\n        seen_types: set[tuple[Type, Type]] | None = None,\n        prefer_literal: bool = True,\n        identity_check: bool = False,\n    ) -> bool:\n        \"\"\"Check for dangerous non-overlapping comparisons like 42 == 'no'.\n\n        The original_container is the original container type for 'in' checks\n        (and None for equality checks).\n\n        Rules:\n            * X and None are overlapping even in strict-optional mode. This is to allow\n            'assert x is not None' for x defined as 'x = None  # type: str' in class body\n            (otherwise mypy itself would have couple dozen errors because of this).\n            * Optional[X] and Optional[Y] are non-overlapping if X and Y are\n            non-overlapping, although technically None is overlap, it is most\n            likely an error.\n            * Any overlaps with everything, i.e. always safe.\n            * Special case: b'abc' in b'cde' is safe.\n        \"\"\"\n        if not self.chk.options.strict_equality:\n            return False\n\n        if seen_types is None:\n            seen_types = set()\n        if (left, right) in seen_types:\n            return False\n        seen_types.add((left, right))\n\n        left, right = get_proper_types((left, right))\n\n        # We suppress the error for equality and container checks if there is a custom __eq__()\n        # method on either side. User defined (or even standard library) classes can define this\n        # to return True for comparisons between non-overlapping types.\n        if (\n            custom_special_method(left, \"__eq__\") or custom_special_method(right, \"__eq__\")\n        ) and not identity_check:\n            return False\n\n        if prefer_literal:\n            # Also flag non-overlapping literals in situations like:\n            #    x: Literal['a', 'b']\n            #    if x == 'c':\n            #        ...\n            left = try_getting_literal(left)\n            right = try_getting_literal(right)\n\n        if self.chk.binder.is_unreachable_warning_suppressed():\n            # We are inside a function that contains type variables with value restrictions in\n            # its signature. In this case we just suppress all strict-equality checks to avoid\n            # false positives for code like:\n            #\n            #     T = TypeVar('T', str, int)\n            #     def f(x: T) -> T:\n            #         if x == 0:\n            #             ...\n            #         return x\n            #\n            # TODO: find a way of disabling the check only for types resulted from the expansion.\n            return False\n        if self.chk.options.strict_equality_for_none:\n            if isinstance(left, NoneType) and isinstance(right, NoneType):\n                return False\n        elif isinstance(left, NoneType) or isinstance(right, NoneType):\n            return False\n        if isinstance(left, UnionType) and isinstance(right, UnionType):\n            left = remove_optional(left)\n            right = remove_optional(right)\n            left, right = get_proper_types((left, right))\n        if (\n            original_container\n            and has_bytes_component(original_container)\n            and has_bytes_component(left)\n        ):\n            # We need to special case bytes and bytearray, because 97 in b'abc', b'a' in b'abc',\n            # b'a' in bytearray(b'abc') etc. all return True (and we want to show the error only\n            # if the check can _never_ be True).\n            return False\n        if isinstance(left, Instance) and isinstance(right, Instance):\n            # Special case some builtin implementations of AbstractSet.\n            left_name = left.type.fullname\n            right_name = right.type.fullname\n            if (\n                left_name in OVERLAPPING_TYPES_ALLOWLIST\n                and right_name in OVERLAPPING_TYPES_ALLOWLIST\n            ):\n                abstract_set = self.chk.lookup_typeinfo(\"typing.AbstractSet\")\n                left = map_instance_to_supertype(left, abstract_set)\n                right = map_instance_to_supertype(right, abstract_set)\n                return self.dangerous_comparison(\n                    left.args[0], right.args[0], seen_types=seen_types\n                )\n            elif left.type.has_base(\"typing.Mapping\") and right.type.has_base(\"typing.Mapping\"):\n                # Similar to above: Mapping ignores the classes, it just compares items.\n                abstract_map = self.chk.lookup_typeinfo(\"typing.Mapping\")\n                left = map_instance_to_supertype(left, abstract_map)\n                right = map_instance_to_supertype(right, abstract_map)\n                return self.dangerous_comparison(\n                    left.args[0], right.args[0], seen_types=seen_types\n                ) or self.dangerous_comparison(left.args[1], right.args[1], seen_types=seen_types)\n            elif left_name in (\"builtins.list\", \"builtins.tuple\") and right_name == left_name:\n                return self.dangerous_comparison(\n                    left.args[0], right.args[0], seen_types=seen_types\n                )\n            elif left_name in OVERLAPPING_BYTES_ALLOWLIST and right_name in (\n                OVERLAPPING_BYTES_ALLOWLIST\n            ):\n                return False\n        if isinstance(left, LiteralType) and isinstance(right, LiteralType):\n            if isinstance(left.value, bool) and isinstance(right.value, bool):\n                # Comparing different booleans is not dangerous.\n                return False\n        if isinstance(left, LiteralType) and isinstance(right, Instance):\n            # bytes/bytearray comparisons are supported\n            if left.fallback.type.fullname == \"builtins.bytes\" and right.type.has_base(\n                \"builtins.bytearray\"\n            ):\n                return False\n        if isinstance(right, LiteralType) and isinstance(left, Instance):\n            # bytes/bytearray comparisons are supported\n            if right.fallback.type.fullname == \"builtins.bytes\" and left.type.has_base(\n                \"builtins.bytearray\"\n            ):\n                return False\n        return not is_overlapping_types(left, right, ignore_promotions=False)\n\n    def check_method_call_by_name(\n        self,\n        method: str,\n        base_type: Type,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n        original_type: Type | None = None,\n        self_type: Type | None = None,\n    ) -> tuple[Type, Type]:\n        \"\"\"Type check a call to a named method on an object.\n\n        Return tuple (result type, inferred method type). The 'original_type'\n        is used for error messages. The self_type is to bind self in methods\n        (see analyze_member_access for more details).\n        \"\"\"\n        original_type = original_type or base_type\n        self_type = self_type or base_type\n        # Unions are special-cased to allow plugins to act on each element of the union.\n        base_type = get_proper_type(base_type)\n        if isinstance(base_type, UnionType):\n            return self.check_union_method_call_by_name(\n                method, base_type, args, arg_kinds, context, original_type\n            )\n\n        method_type = analyze_member_access(\n            method,\n            base_type,\n            context,\n            is_lvalue=False,\n            is_super=False,\n            is_operator=True,\n            original_type=original_type,\n            self_type=self_type,\n            chk=self.chk,\n            in_literal_context=self.is_literal_context(),\n        )\n        return self.check_method_call(method, base_type, method_type, args, arg_kinds, context)\n\n    def check_union_method_call_by_name(\n        self,\n        method: str,\n        base_type: UnionType,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n        original_type: Type | None = None,\n    ) -> tuple[Type, Type]:\n        \"\"\"Type check a call to a named method on an object with union type.\n\n        This essentially checks the call using check_method_call_by_name() for each\n        union item and unions the result. We do this to allow plugins to act on\n        individual union items.\n        \"\"\"\n        res: list[Type] = []\n        meth_res: list[Type] = []\n        for typ in base_type.relevant_items():\n            # Format error messages consistently with\n            # mypy.checkmember.analyze_union_member_access().\n            with self.msg.disable_type_names():\n                item, meth_item = self.check_method_call_by_name(\n                    method, typ, args, arg_kinds, context, original_type\n                )\n            res.append(item)\n            meth_res.append(meth_item)\n        return make_simplified_union(res), make_simplified_union(meth_res)\n\n    def check_method_call(\n        self,\n        method_name: str,\n        base_type: Type,\n        method_type: Type,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        context: Context,\n    ) -> tuple[Type, Type]:\n        \"\"\"Type check a call to a method with the given name and type on an object.\n\n        Return tuple (result type, inferred method type).\n        \"\"\"\n        callable_name = self.method_fullname(base_type, method_name)\n        object_type = base_type if callable_name is not None else None\n\n        # Try to refine the method signature using plugin hooks before checking the call.\n        method_type = self.transform_callee_type(\n            callable_name, method_type, args, arg_kinds, context, object_type=object_type\n        )\n\n        return self.check_call(\n            method_type,\n            args,\n            arg_kinds,\n            context,\n            callable_name=callable_name,\n            object_type=base_type,\n        )\n\n    def check_op_reversible(\n        self,\n        op_name: str,\n        left_type: Type,\n        left_expr: Expression,\n        right_type: Type,\n        right_expr: Expression,\n        context: Context,\n    ) -> tuple[Type, Type]:\n        def lookup_operator(op_name: str, base_type: Type) -> Type | None:\n            \"\"\"Looks up the given operator and returns the corresponding type,\n            if it exists.\"\"\"\n\n            # This check is an important performance optimization.\n            if not has_operator(base_type, op_name, self.named_type):\n                return None\n\n            with self.msg.filter_errors() as w:\n                member = analyze_member_access(\n                    name=op_name,\n                    typ=base_type,\n                    is_lvalue=False,\n                    is_super=False,\n                    is_operator=True,\n                    original_type=base_type,\n                    context=context,\n                    chk=self.chk,\n                    in_literal_context=self.is_literal_context(),\n                )\n                return None if w.has_new_errors() else member\n\n        def lookup_definer(typ: Instance, attr_name: str) -> str | None:\n            \"\"\"Returns the name of the class that contains the actual definition of attr_name.\n\n            So if class A defines foo and class B subclasses A, running\n            'get_class_defined_in(B, \"foo\")` would return the full name of A.\n\n            However, if B were to override and redefine foo, that method call would\n            return the full name of B instead.\n\n            If the attr name is not present in the given class or its MRO, returns None.\n            \"\"\"\n            for cls in typ.type.mro:\n                if cls.names.get(attr_name):\n                    return cls.fullname\n            return None\n\n        left_type = get_proper_type(left_type)\n        right_type = get_proper_type(right_type)\n\n        # If either the LHS or the RHS are Any, we can't really concluding anything\n        # about the operation since the Any type may or may not define an\n        # __op__ or __rop__ method. So, we punt and return Any instead.\n\n        if isinstance(left_type, AnyType):\n            any_type = AnyType(TypeOfAny.from_another_any, source_any=left_type)\n            return any_type, any_type\n        if isinstance(right_type, AnyType):\n            any_type = AnyType(TypeOfAny.from_another_any, source_any=right_type)\n            return any_type, any_type\n\n        # STEP 1:\n        # We start by getting the __op__ and __rop__ methods, if they exist.\n\n        rev_op_name = operators.reverse_op_methods[op_name]\n\n        left_op = lookup_operator(op_name, left_type)\n        right_op = lookup_operator(rev_op_name, right_type)\n\n        # STEP 2a:\n        # We figure out in which order Python will call the operator methods. As it\n        # turns out, it's not as simple as just trying to call __op__ first and\n        # __rop__ second.\n        #\n        # We store the determined order inside the 'variants_raw' variable,\n        # which records tuples containing the method, base type, and the argument.\n\n        if op_name in operators.op_methods_that_shortcut and is_same_type(left_type, right_type):\n            # When we do \"A() + A()\", for example, Python will only call the __add__ method,\n            # never the __radd__ method.\n            #\n            # This is the case even if the __add__ method is completely missing and the __radd__\n            # method is defined.\n\n            variants_raw = [(op_name, left_op, left_type, right_expr)]\n        elif (\n            (\n                # Checking (A implies B) using the logically equivalent (not A or B), where\n                #    A: left and right are both `Instance` objects\n                #    B: right's __rop__ method is different from left's __op__ method\n                not (isinstance(left_type, Instance) and isinstance(right_type, Instance))\n                or (\n                    lookup_definer(left_type, op_name) != lookup_definer(right_type, rev_op_name)\n                    and (\n                        left_type.type.alt_promote is None\n                        or left_type.type.alt_promote.type is not right_type.type\n                    )\n                )\n            )\n            # Note: use `covers_at_runtime` instead of `is_subtype` (#19006)\n            and covers_at_runtime(right_type, left_type)\n        ):\n            # When we do \"A() + B()\" where B is a subclass of A, we'll actually try calling\n            # B's __radd__ method first, but ONLY if B explicitly defines or overrides the\n            # __radd__ method.\n            #\n            # This mechanism lets subclasses \"refine\" the expected outcome of the operation, even\n            # if they're located on the RHS.\n            #\n            # As a special case, the alt_promote check makes sure that we don't use the\n            # __radd__ method of int if the LHS is a native int type.\n\n            variants_raw = [\n                (rev_op_name, right_op, right_type, left_expr),\n                (op_name, left_op, left_type, right_expr),\n            ]\n        else:\n            # In all other cases, we do the usual thing and call __add__ first and\n            # __radd__ second when doing \"A() + B()\".\n\n            variants_raw = [\n                (op_name, left_op, left_type, right_expr),\n                (rev_op_name, right_op, right_type, left_expr),\n            ]\n\n        # STEP 3:\n        # We now filter out all non-existent operators. The 'variants' list contains\n        # all operator methods that are actually present, in the order that Python\n        # attempts to invoke them.\n\n        variants = [(na, op, obj, arg) for (na, op, obj, arg) in variants_raw if op is not None]\n\n        # STEP 4:\n        # We now try invoking each one. If an operation succeeds, end early and return\n        # the corresponding result. Otherwise, return the result and errors associated\n        # with the first entry.\n\n        errors = []\n        results = []\n        for name, method, obj, arg in variants:\n            with self.msg.filter_errors(save_filtered_errors=True) as local_errors:\n                result = self.check_method_call(name, obj, method, [arg], [ARG_POS], context)\n            if local_errors.has_new_errors():\n                errors.append(local_errors.filtered_errors())\n                results.append(result)\n            else:\n                return result\n\n        # We finish invoking above operators and no early return happens. Therefore,\n        # we check if either the LHS or the RHS is Instance and fallbacks to Any,\n        # if so, we also return Any\n        if (isinstance(left_type, Instance) and left_type.type.fallback_to_any) or (\n            isinstance(right_type, Instance) and right_type.type.fallback_to_any\n        ):\n            any_type = AnyType(TypeOfAny.special_form)\n            return any_type, any_type\n\n        # STEP 4b:\n        # Sometimes, the variants list is empty. In that case, we fall-back to attempting to\n        # call the __op__ method (even though it's missing).\n\n        if not variants:\n            with self.msg.filter_errors(save_filtered_errors=True) as local_errors:\n                result = self.check_method_call_by_name(\n                    op_name, left_type, [right_expr], [ARG_POS], context\n                )\n\n            if local_errors.has_new_errors():\n                errors.append(local_errors.filtered_errors())\n                results.append(result)\n            else:\n                # Although we should not need this case anymore, we keep it just in case, as\n                # otherwise we will get a crash if we introduce inconsistency in checkmember.py\n                return result\n\n        self.msg.add_errors(errors[0])\n        if len(results) == 1:\n            return results[0]\n        else:\n            error_any = AnyType(TypeOfAny.from_error)\n            result = error_any, error_any\n            return result\n\n    def check_op(\n        self,\n        method: str,\n        base_type: Type,\n        arg: Expression,\n        context: Context,\n        allow_reverse: bool = False,\n    ) -> tuple[Type, Type]:\n        \"\"\"Type check a binary operation which maps to a method call.\n\n        Return tuple (result type, inferred operator method type).\n        \"\"\"\n\n        if allow_reverse:\n            left_variants = [base_type]\n            base_type = get_proper_type(base_type)\n            if isinstance(base_type, UnionType):\n                left_variants = list(flatten_nested_unions(base_type.relevant_items()))\n            right_type = self.accept(arg)\n\n            # Step 1: We first try leaving the right arguments alone and destructure\n            # just the left ones. (Mypy can sometimes perform some more precise inference\n            # if we leave the right operands a union -- see testOperatorWithEmptyListAndSum.)\n            all_results = []\n            all_inferred = []\n\n            with self.msg.filter_errors() as local_errors:\n                for left_possible_type in left_variants:\n                    result, inferred = self.check_op_reversible(\n                        op_name=method,\n                        left_type=left_possible_type,\n                        left_expr=TempNode(left_possible_type, context=context),\n                        right_type=right_type,\n                        right_expr=arg,\n                        context=context,\n                    )\n                    all_results.append(result)\n                    all_inferred.append(inferred)\n\n            if not local_errors.has_new_errors():\n                results_final = make_simplified_union(all_results)\n                inferred_final = make_simplified_union(all_inferred)\n                return results_final, inferred_final\n\n            # Step 2: If that fails, we try again but also destructure the right argument.\n            # This is also necessary to make certain edge cases work -- see\n            # testOperatorDoubleUnionInterwovenUnionAdd, for example.\n\n            # Note: We want to pass in the original 'arg' for 'left_expr' and 'right_expr'\n            # whenever possible so that plugins and similar things can introspect on the original\n            # node if possible.\n            #\n            # We don't do the same for the base expression because it could lead to weird\n            # type inference errors -- e.g. see 'testOperatorDoubleUnionSum'.\n            # TODO: Can we use `type_overrides_set()` here?\n            right_variants = [(right_type, arg)]\n            right_type = get_proper_type(right_type)\n            if isinstance(right_type, UnionType):\n                right_variants = [\n                    (item, TempNode(item, context=context))\n                    for item in flatten_nested_unions(right_type.relevant_items())\n                ]\n\n            all_results = []\n            all_inferred = []\n\n            with self.msg.filter_errors(save_filtered_errors=True) as local_errors:\n                for left_possible_type in left_variants:\n                    for right_possible_type, right_expr in right_variants:\n                        result, inferred = self.check_op_reversible(\n                            op_name=method,\n                            left_type=left_possible_type,\n                            left_expr=TempNode(left_possible_type, context=context),\n                            right_type=right_possible_type,\n                            right_expr=right_expr,\n                            context=context,\n                        )\n                        all_results.append(result)\n                        all_inferred.append(inferred)\n\n            if local_errors.has_new_errors():\n                self.msg.add_errors(local_errors.filtered_errors())\n                # Point any notes to the same location as an existing message.\n                err = local_errors.filtered_errors()[-1]\n                recent_context = TempNode(NoneType())\n                recent_context.line = err.line\n                recent_context.column = err.column\n                if len(left_variants) >= 2 and len(right_variants) >= 2:\n                    self.msg.warn_both_operands_are_from_unions(recent_context)\n                elif len(left_variants) >= 2:\n                    self.msg.warn_operand_was_from_union(\"Left\", base_type, context=recent_context)\n                elif len(right_variants) >= 2:\n                    self.msg.warn_operand_was_from_union(\n                        \"Right\", right_type, context=recent_context\n                    )\n\n            # See the comment in 'check_overload_call' for more details on why\n            # we call 'combine_function_signature' instead of just unioning the inferred\n            # callable types.\n            results_final = make_simplified_union(all_results)\n            inferred_final = self.combine_function_signatures(get_proper_types(all_inferred))\n            return results_final, inferred_final\n        else:\n            return self.check_method_call_by_name(\n                method=method,\n                base_type=base_type,\n                args=[arg],\n                arg_kinds=[ARG_POS],\n                context=context,\n            )\n\n    def check_boolean_op(self, e: OpExpr) -> Type:\n        \"\"\"Type check a boolean operation ('and' or 'or').\"\"\"\n\n        # A boolean operation can evaluate to either of the operands.\n\n        # We use the current type context to guide the type inference of\n        # the left operand. We also use the left operand type to guide the type\n        # inference of the right operand so that expressions such as\n        # '[1] or []' are inferred correctly.\n        ctx = self.type_context[-1]\n        left_type = self.accept(e.left, ctx)\n        expanded_left_type = try_expanding_sum_type_to_union(left_type, \"builtins.bool\")\n\n        assert e.op in (\"and\", \"or\")  # Checked by visit_op_expr\n\n        left_map: mypy.checker.TypeMap\n        right_map: mypy.checker.TypeMap\n        if e.right_always:\n            left_map, right_map = {e.left: UninhabitedType()}, {}\n        elif e.right_unreachable:\n            left_map, right_map = {}, {e.right: UninhabitedType()}\n        elif e.op == \"and\":\n            right_map, left_map = self.chk.find_isinstance_check(e.left)\n        elif e.op == \"or\":\n            left_map, right_map = self.chk.find_isinstance_check(e.left)\n\n        # If left_map is unreachable then we know mypy considers the left expression\n        # to be redundant.\n        left_unreachable = mypy.checker.is_unreachable_map(left_map)\n        if (\n            codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes\n            and left_unreachable\n            # don't report an error if it's intentional\n            and not e.right_always\n        ):\n            self.msg.redundant_left_operand(e.op, e.left)\n\n        right_unreachable = mypy.checker.is_unreachable_map(right_map)\n        if (\n            self.chk.should_report_unreachable_issues()\n            and right_unreachable\n            # don't report an error if it's intentional\n            and not e.right_unreachable\n        ):\n            self.msg.unreachable_right_operand(e.op, e.right)\n\n        right_type = self.analyze_cond_branch(\n            right_map, e.right, self._combined_context(expanded_left_type)\n        )\n\n        if left_unreachable and right_unreachable:\n            return UninhabitedType()\n\n        if right_unreachable:\n            # The boolean expression is statically known to be the left value\n            return left_type\n        if left_unreachable:\n            # The boolean expression is statically known to be the right value\n            return right_type\n\n        if e.op == \"and\":\n            restricted_left_type = false_only(expanded_left_type)\n            result_is_left = not expanded_left_type.can_be_true\n        elif e.op == \"or\":\n            restricted_left_type = true_only(expanded_left_type)\n            result_is_left = not expanded_left_type.can_be_false\n\n        if isinstance(restricted_left_type, UninhabitedType):\n            # The left operand can never be the result\n            return right_type\n        elif result_is_left:\n            # The left operand is always the result\n            return left_type\n        else:\n            return make_simplified_union([restricted_left_type, right_type])\n\n    def check_list_multiply(self, e: OpExpr) -> Type:\n        \"\"\"Type check an expression of form '[...] * e'.\n\n        Type inference is special-cased for this common construct.\n        \"\"\"\n        right_type = self.accept(e.right)\n        if is_subtype(right_type, self.named_type(\"builtins.int\")):\n            # Special case: [...] * <int value>. Use the type context of the\n            # OpExpr, since the multiplication does not affect the type.\n            left_type = self.accept(e.left, type_context=self.type_context[-1])\n        else:\n            left_type = self.accept(e.left)\n        result, method_type = self.check_op(\"__mul__\", left_type, e.right, e)\n        e.method_type = method_type\n        return result\n\n    def visit_assignment_expr(self, e: AssignmentExpr) -> Type:\n        value = self.accept(e.value)\n        self.chk.check_assignment(e.target, e.value)\n        self.chk.check_final(e)\n        if not has_uninhabited_component(value):\n            # TODO: can we get rid of this extra store_type()?\n            # Usually, check_assignment() already stores the lvalue type correctly.\n            self.chk.store_type(e.target, value)\n        self.find_partial_type_ref_fast_path(e.target)\n        return value\n\n    def visit_unary_expr(self, e: UnaryExpr) -> Type:\n        \"\"\"Type check an unary operation ('not', '-', '+' or '~').\"\"\"\n        operand_type = self.accept(e.expr)\n        op = e.op\n        if op == \"not\":\n            result: Type = self.bool_type()\n            self.chk.check_for_truthy_type(operand_type, e.expr)\n        else:\n            method = operators.unary_op_methods[op]\n            result, method_type = self.check_method_call_by_name(method, operand_type, [], [], e)\n            e.method_type = method_type\n        return result\n\n    def visit_index_expr(self, e: IndexExpr) -> Type:\n        \"\"\"Type check an index expression (base[index]).\n\n        It may also represent type application.\n        \"\"\"\n        result = self.visit_index_expr_helper(e)\n        result = self.narrow_type_from_binder(e, result)\n        p_result = get_proper_type(result)\n        if (\n            self.is_literal_context()\n            and isinstance(p_result, Instance)\n            and p_result.last_known_value is not None\n        ):\n            result = p_result.last_known_value\n        return result\n\n    def visit_index_expr_helper(self, e: IndexExpr) -> Type:\n        if e.analyzed:\n            # It's actually a type application.\n            return self.accept(e.analyzed)\n        left_type = self.accept(e.base)\n        return self.visit_index_with_type(left_type, e)\n\n    def visit_index_with_type(\n        self,\n        left_type: Type,\n        e: IndexExpr,\n        original_type: ProperType | None = None,\n        self_type: Type | None = None,\n    ) -> Type:\n        \"\"\"Analyze type of an index expression for a given type of base expression.\n\n        The 'original_type' is used for error messages (currently used for union types). The\n        'self_type' is to bind self in methods (see analyze_member_access for more details).\n        \"\"\"\n        index = e.index\n        self_type = self_type or left_type\n        left_type = get_proper_type(left_type)\n\n        # Visit the index, just to make sure we have a type for it available\n        self.accept(index)\n\n        if isinstance(left_type, TupleType) and any(\n            isinstance(it, UnpackType) for it in left_type.items\n        ):\n            # Normalize variadic tuples for consistency.\n            left_type = expand_type(left_type, {})\n\n        if isinstance(left_type, UnionType):\n            original_type = original_type or left_type\n            # Don't combine literal types, since we may need them for type narrowing.\n            return make_simplified_union(\n                [\n                    self.visit_index_with_type(typ, e, original_type)\n                    for typ in left_type.relevant_items()\n                ],\n                contract_literals=False,\n            )\n        elif isinstance(left_type, TupleType) and self.chk.in_checked_function():\n            # Special case for tuples. They return a more specific type when\n            # indexed by an integer literal.\n            if isinstance(index, SliceExpr):\n                return self.visit_tuple_slice_helper(left_type, index)\n\n            ns = self.try_getting_int_literals(index)\n            if ns is not None:\n                out = []\n                for n in ns:\n                    item = self.visit_tuple_index_helper(left_type, n)\n                    if item is not None:\n                        out.append(item)\n                    else:\n                        self.chk.fail(message_registry.TUPLE_INDEX_OUT_OF_RANGE, e)\n                        if any(isinstance(t, UnpackType) for t in left_type.items):\n                            min_len = self.min_tuple_length(left_type)\n                            self.chk.note(f\"Variadic tuple can have length {min_len}\", e)\n                        return AnyType(TypeOfAny.from_error)\n                return make_simplified_union(out)\n            else:\n                return self.nonliteral_tuple_index_helper(left_type, index)\n        elif isinstance(left_type, TypedDictType):\n            return self.visit_typeddict_index_expr(left_type, e.index)[0]\n        elif isinstance(left_type, FunctionLike) and left_type.is_type_obj():\n            if left_type.type_object().is_enum:\n                return self.visit_enum_index_expr(left_type.type_object(), e.index, e)\n            elif (\n                left_type.type_object().type_vars\n                or left_type.type_object().fullname == \"builtins.type\"\n            ):\n                return self.named_type(\"types.GenericAlias\")\n\n        if isinstance(left_type, TypeVarType):\n            return self.visit_index_with_type(\n                left_type.values_or_bound(), e, original_type, left_type\n            )\n        elif isinstance(left_type, Instance) and left_type.type.fullname == \"typing._SpecialForm\":\n            # Allow special forms to be indexed and used to create union types\n            return self.named_type(\"typing._SpecialForm\")\n        else:\n            result, method_type = self.check_method_call_by_name(\n                \"__getitem__\",\n                left_type,\n                [e.index],\n                [ARG_POS],\n                e,\n                original_type=original_type,\n                self_type=self_type,\n            )\n            e.method_type = method_type\n            return result\n\n    def min_tuple_length(self, left: TupleType) -> int:\n        unpack_index = find_unpack_in_list(left.items)\n        if unpack_index is None:\n            return left.length()\n        unpack = left.items[unpack_index]\n        assert isinstance(unpack, UnpackType)\n        if isinstance(unpack.type, TypeVarTupleType):\n            return left.length() - 1 + unpack.type.min_len\n        return left.length() - 1\n\n    def visit_tuple_index_helper(self, left: TupleType, n: int) -> Type | None:\n        unpack_index = find_unpack_in_list(left.items)\n        if unpack_index is None:\n            if n < 0:\n                n += len(left.items)\n            if 0 <= n < len(left.items):\n                return left.items[n]\n            return None\n        unpack = left.items[unpack_index]\n        assert isinstance(unpack, UnpackType)\n        unpacked = get_proper_type(unpack.type)\n        if isinstance(unpacked, TypeVarTupleType):\n            # Usually we say that TypeVarTuple can't be split, be in case of\n            # indexing it seems benign to just return the upper bound item, similar\n            # to what we do when indexing a regular TypeVar.\n            bound = get_proper_type(unpacked.upper_bound)\n            assert isinstance(bound, Instance)\n            assert bound.type.fullname == \"builtins.tuple\"\n            middle = bound.args[0]\n        else:\n            assert isinstance(unpacked, Instance)\n            assert unpacked.type.fullname == \"builtins.tuple\"\n            middle = unpacked.args[0]\n\n        extra_items = self.min_tuple_length(left) - left.length() + 1\n        if n >= 0:\n            if n >= self.min_tuple_length(left):\n                # For tuple[int, *tuple[str, ...], int] we allow either index 0 or 1,\n                # since variadic item may have zero items.\n                return None\n            if n < unpack_index:\n                return left.items[n]\n            return UnionType.make_union(\n                [middle]\n                + left.items[unpack_index + 1 : max(n - extra_items + 2, unpack_index + 1)],\n                left.line,\n                left.column,\n            )\n        n += self.min_tuple_length(left)\n        if n < 0:\n            # Similar to above, we only allow -1, and -2 for tuple[int, *tuple[str, ...], int]\n            return None\n        if n >= unpack_index + extra_items:\n            return left.items[n - extra_items + 1]\n        return UnionType.make_union(\n            left.items[min(n, unpack_index) : unpack_index] + [middle], left.line, left.column\n        )\n\n    def visit_tuple_slice_helper(self, left_type: TupleType, slic: SliceExpr) -> Type:\n        begin: Sequence[int | None] = [None]\n        end: Sequence[int | None] = [None]\n        stride: Sequence[int | None] = [None]\n\n        if slic.begin_index:\n            begin_raw = self.try_getting_int_literals(slic.begin_index)\n            if begin_raw is None:\n                return self.nonliteral_tuple_index_helper(left_type, slic)\n            begin = begin_raw\n\n        if slic.end_index:\n            end_raw = self.try_getting_int_literals(slic.end_index)\n            if end_raw is None:\n                return self.nonliteral_tuple_index_helper(left_type, slic)\n            end = end_raw\n\n        if slic.stride:\n            stride_raw = self.try_getting_int_literals(slic.stride)\n            if stride_raw is None:\n                return self.nonliteral_tuple_index_helper(left_type, slic)\n            stride = stride_raw\n\n        items: list[Type] = []\n        for b, e, s in itertools.product(begin, end, stride):\n            item = left_type.slice(b, e, s, fallback=self.named_type(\"builtins.tuple\"))\n            if item is None:\n                self.chk.fail(message_registry.AMBIGUOUS_SLICE_OF_VARIADIC_TUPLE, slic)\n                return AnyType(TypeOfAny.from_error)\n            items.append(item)\n        return make_simplified_union(items)\n\n    def try_getting_int_literals(self, index: Expression) -> list[int] | None:\n        \"\"\"If the given expression or type corresponds to an int literal\n        or a union of int literals, returns a list of the underlying ints.\n        Otherwise, returns None.\n\n        Specifically, this function is guaranteed to return a list with\n        one or more ints if one the following is true:\n\n        1. 'expr' is a IntExpr or a UnaryExpr backed by an IntExpr\n        2. 'typ' is a LiteralType containing an int\n        3. 'typ' is a UnionType containing only LiteralType of ints\n        \"\"\"\n        if isinstance(index, IntExpr):\n            return [index.value]\n        elif isinstance(index, UnaryExpr):\n            if index.op == \"-\":\n                operand = index.expr\n                if isinstance(operand, IntExpr):\n                    return [-1 * operand.value]\n            if index.op == \"+\":\n                operand = index.expr\n                if isinstance(operand, IntExpr):\n                    return [operand.value]\n        typ = get_proper_type(self.accept(index))\n        if isinstance(typ, Instance) and typ.last_known_value is not None:\n            typ = typ.last_known_value\n        if isinstance(typ, LiteralType) and isinstance(typ.value, int):\n            return [typ.value]\n        if isinstance(typ, UnionType):\n            out = []\n            for item in get_proper_types(typ.items):\n                if isinstance(item, LiteralType) and isinstance(item.value, int):\n                    out.append(item.value)\n                else:\n                    return None\n            return out\n        return None\n\n    def nonliteral_tuple_index_helper(self, left_type: TupleType, index: Expression) -> Type:\n        self.check_method_call_by_name(\"__getitem__\", left_type, [index], [ARG_POS], context=index)\n        # We could return the return type from above, but unions are often better than the join\n        union = self.union_tuple_fallback_item(left_type)\n        if isinstance(index, SliceExpr):\n            return self.chk.named_generic_type(\"builtins.tuple\", [union])\n        return union\n\n    def union_tuple_fallback_item(self, left_type: TupleType) -> Type:\n        # TODO: this duplicates logic in typeops.tuple_fallback().\n        items = []\n        for item in left_type.items:\n            if isinstance(item, UnpackType):\n                unpacked_type = get_proper_type(item.type)\n                if isinstance(unpacked_type, TypeVarTupleType):\n                    unpacked_type = get_proper_type(unpacked_type.upper_bound)\n                if (\n                    isinstance(unpacked_type, Instance)\n                    and unpacked_type.type.fullname == \"builtins.tuple\"\n                ):\n                    items.append(unpacked_type.args[0])\n                else:\n                    raise NotImplementedError\n            else:\n                items.append(item)\n        return make_simplified_union(items)\n\n    def visit_typeddict_index_expr(\n        self, td_type: TypedDictType, index: Expression, setitem: bool = False\n    ) -> tuple[Type, set[str]]:\n        if isinstance(index, StrExpr):\n            key_names = [index.value]\n        else:\n            typ = get_proper_type(self.accept(index))\n            if isinstance(typ, UnionType):\n                key_types: list[Type] = list(typ.items)\n            else:\n                key_types = [typ]\n\n            key_names = []\n            for key_type in get_proper_types(key_types):\n                if isinstance(key_type, Instance) and key_type.last_known_value is not None:\n                    key_type = key_type.last_known_value\n\n                if (\n                    isinstance(key_type, LiteralType)\n                    and isinstance(key_type.value, str)\n                    and key_type.fallback.type.fullname != \"builtins.bytes\"\n                ):\n                    key_names.append(key_type.value)\n                else:\n                    self.msg.typeddict_key_must_be_string_literal(td_type, index)\n                    return AnyType(TypeOfAny.from_error), set()\n\n        value_types = []\n        for key_name in key_names:\n            value_type = td_type.items.get(key_name)\n            if value_type is None:\n                self.msg.typeddict_key_not_found(td_type, key_name, index, setitem)\n                return AnyType(TypeOfAny.from_error), set()\n            else:\n                value_types.append(value_type)\n        return make_simplified_union(value_types), set(key_names)\n\n    def visit_enum_index_expr(\n        self, enum_type: TypeInfo, index: Expression, context: Context\n    ) -> Type:\n        string_type: Type = self.named_type(\"builtins.str\")\n        self.chk.check_subtype(\n            self.accept(index),\n            string_type,\n            context,\n            \"Enum index should be a string\",\n            \"actual index type\",\n        )\n        return Instance(enum_type, [])\n\n    def visit_cast_expr(self, expr: CastExpr) -> Type:\n        \"\"\"Type check a cast expression.\"\"\"\n        source_type = self.accept(\n            expr.expr,\n            type_context=AnyType(TypeOfAny.special_form),\n            allow_none_return=True,\n            always_allow_any=True,\n        )\n        target_type = expr.type\n        options = self.chk.options\n        if (\n            options.warn_redundant_casts\n            and not is_same_type(target_type, AnyType(TypeOfAny.special_form))\n            and is_same_type(source_type, target_type)\n        ):\n            self.msg.redundant_cast(target_type, expr)\n        if options.disallow_any_unimported and has_any_from_unimported_type(target_type):\n            self.msg.unimported_type_becomes_any(\"Target type of cast\", target_type, expr)\n        check_for_explicit_any(\n            target_type, self.chk.options, self.chk.is_typeshed_stub, self.msg, context=expr\n        )\n        return target_type\n\n    def visit_type_form_expr(self, expr: TypeFormExpr) -> Type:\n        typ = expr.type\n        return TypeType.make_normalized(typ, line=typ.line, column=typ.column, is_type_form=True)\n\n    def visit_assert_type_expr(self, expr: AssertTypeExpr) -> Type:\n        source_type = self.accept(\n            expr.expr,\n            type_context=self.type_context[-1],\n            allow_none_return=True,\n            always_allow_any=True,\n        )\n        if self.chk.current_node_deferred:\n            return source_type\n\n        target_type = expr.type\n        proper_source_type = get_proper_type(source_type)\n        if (\n            isinstance(proper_source_type, mypy.types.Instance)\n            and proper_source_type.last_known_value is not None\n        ):\n            source_type = proper_source_type.last_known_value\n        if not is_same_type(source_type, target_type):\n            if not self.chk.in_checked_function():\n                self.msg.note(\n                    '\"assert_type\" expects everything to be \"Any\" in unchecked functions',\n                    expr.expr,\n                )\n            self.msg.assert_type_fail(source_type, target_type, expr)\n        return source_type\n\n    def visit_reveal_expr(self, expr: RevealExpr) -> Type:\n        \"\"\"Type check a reveal_type expression.\"\"\"\n        if expr.kind == REVEAL_TYPE:\n            assert expr.expr is not None\n            revealed_type = self.accept(\n                expr.expr, type_context=self.type_context[-1], allow_none_return=True\n            )\n            if not self.chk.current_node_deferred:\n                self.msg.reveal_type(revealed_type, expr.expr)\n                if not self.chk.in_checked_function():\n                    self.msg.note(\n                        \"'reveal_type' always outputs 'Any' in unchecked functions\", expr.expr\n                    )\n                self.check_reveal_imported(expr)\n            return revealed_type\n        else:\n            # REVEAL_LOCALS\n            if not self.chk.current_node_deferred:\n                # the RevealExpr contains a local_nodes attribute,\n                # calculated at semantic analysis time. Use it to pull out the\n                # corresponding subset of variables in self.chk.type_map\n                names_to_types = (\n                    {var_node.name: var_node.type for var_node in expr.local_nodes}\n                    if expr.local_nodes is not None\n                    else {}\n                )\n\n                self.msg.reveal_locals(names_to_types, expr)\n                self.check_reveal_imported(expr)\n            return NoneType()\n\n    def check_reveal_imported(self, expr: RevealExpr) -> None:\n        if codes.UNIMPORTED_REVEAL not in self.chk.options.enabled_error_codes:\n            return\n\n        name = \"\"\n        if expr.kind == REVEAL_LOCALS:\n            name = \"reveal_locals\"\n        elif expr.kind == REVEAL_TYPE and not expr.is_imported:\n            name = \"reveal_type\"\n        else:\n            return\n\n        self.chk.fail(f'Name \"{name}\" is not defined', expr, code=codes.UNIMPORTED_REVEAL)\n        if name == \"reveal_type\":\n            module = (\n                \"typing\" if self.chk.options.python_version >= (3, 11) else \"typing_extensions\"\n            )\n            hint = (\n                'Did you forget to import it from \"{module}\"?'\n                ' (Suggestion: \"from {module} import {name}\")'\n            ).format(module=module, name=name)\n            self.chk.note(hint, expr, code=codes.UNIMPORTED_REVEAL)\n\n    def visit_type_application(self, tapp: TypeApplication) -> Type:\n        \"\"\"Type check a type application (expr[type, ...]).\n\n        There are two different options here, depending on whether expr refers\n        to a type alias or directly to a generic class. In the first case we need\n        to use a dedicated function typeanal.instantiate_type_alias(). This\n        is due to slight differences in how type arguments are applied and checked.\n        \"\"\"\n        if isinstance(tapp.expr, RefExpr) and isinstance(tapp.expr.node, TypeAlias):\n            if tapp.expr.node.python_3_12_type_alias:\n                return self.type_alias_type_type()\n            # Subscription of a (generic) alias in runtime context, expand the alias.\n            item = instantiate_type_alias(\n                tapp.expr.node,\n                tapp.types,\n                self.chk.fail,\n                tapp.expr.node.no_args,\n                tapp,\n                self.chk.options,\n            )\n            item = get_proper_type(item)\n            if isinstance(item, Instance):\n                tp = type_object_type(item.type, self.named_type)\n                return self.apply_type_arguments_to_callable(tp, item.args, tapp)\n            elif isinstance(item, TupleType) and item.partial_fallback.type.is_named_tuple:\n                tp = type_object_type(item.partial_fallback.type, self.named_type)\n                return self.apply_type_arguments_to_callable(tp, item.partial_fallback.args, tapp)\n            elif isinstance(item, TypedDictType):\n                return self.typeddict_callable_from_context(item)\n            else:\n                self.chk.fail(message_registry.ONLY_CLASS_APPLICATION, tapp)\n                return AnyType(TypeOfAny.from_error)\n        # Type application of a normal generic class in runtime context.\n        # This is typically used as `x = G[int]()`.\n        tp = get_proper_type(self.accept(tapp.expr))\n        if isinstance(tp, (CallableType, Overloaded)):\n            if not tp.is_type_obj():\n                self.chk.fail(message_registry.ONLY_CLASS_APPLICATION, tapp)\n            return self.apply_type_arguments_to_callable(tp, tapp.types, tapp)\n        if isinstance(tp, AnyType):\n            return AnyType(TypeOfAny.from_another_any, source_any=tp)\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_type_alias_expr(self, alias: TypeAliasExpr) -> Type:\n        \"\"\"Right hand side of a type alias definition.\n\n        It has the same type as if the alias itself was used in a runtime context.\n        For example, here:\n\n            A = reveal_type(List[T])\n            reveal_type(A)\n\n        both `reveal_type` instances will reveal the same type `def (...) -> builtins.list[Any]`.\n        Note that type variables are implicitly substituted with `Any`.\n        \"\"\"\n        return self.alias_type_in_runtime_context(alias.node, ctx=alias, alias_definition=True)\n\n    def alias_type_in_runtime_context(\n        self, alias: TypeAlias, *, ctx: Context, alias_definition: bool = False\n    ) -> Type:\n        \"\"\"Get type of a type alias (could be generic) in a runtime expression.\n\n        Note that this function can be called only if the alias appears _not_\n        as a target of type application, which is treated separately in the\n        visit_type_application method. Some examples where this method is called are\n        casts and instantiation:\n\n            class LongName(Generic[T]): ...\n            A = LongName[int]\n\n            x = A()\n            y = cast(A, ...)\n        \"\"\"\n        if alias.python_3_12_type_alias:\n            return self.type_alias_type_type()\n        # If this is a generic alias, we set all variables to `Any`.\n        # For example:\n        #     A = List[Tuple[T, T]]\n        #     x = A() <- same as List[Tuple[Any, Any]], see PEP 484.\n        disallow_any = self.chk.options.disallow_any_generics and self.is_callee\n        item = get_proper_type(\n            set_any_tvars(\n                alias,\n                [],\n                ctx.line,\n                ctx.column,\n                self.chk.options,\n                disallow_any=disallow_any,\n                fail=self.msg.fail,\n            )\n        )\n        if isinstance(item, Instance):\n            # Normally we get a callable type (or overloaded) with .is_type_obj() true\n            # representing the class's constructor\n            tp = type_object_type(item.type, self.named_type)\n            if alias.no_args:\n                return tp\n            return self.apply_type_arguments_to_callable(tp, item.args, ctx)\n        elif (\n            isinstance(item, TupleType)\n            and\n            # Tuple[str, int]() fails at runtime, only named tuples and subclasses work.\n            tuple_fallback(item).type.fullname != \"builtins.tuple\"\n        ):\n            return type_object_type(tuple_fallback(item).type, self.named_type)\n        elif isinstance(item, TypedDictType):\n            return self.typeddict_callable_from_context(item)\n        elif isinstance(item, NoneType):\n            return TypeType(item, line=item.line, column=item.column)\n        elif isinstance(item, AnyType):\n            return AnyType(TypeOfAny.from_another_any, source_any=item)\n        elif (\n            isinstance(item, UnionType)\n            and item.uses_pep604_syntax\n            and self.chk.options.python_version >= (3, 10)\n        ):\n            return self.chk.named_generic_type(\"types.UnionType\", item.items)\n        else:\n            if alias_definition:\n                return AnyType(TypeOfAny.special_form)\n            # The _SpecialForm type can be used in some runtime contexts (e.g. it may have __or__).\n            return self.named_type(\"typing._SpecialForm\")\n\n    def split_for_callable(\n        self, t: CallableType, args: Sequence[Type], ctx: Context\n    ) -> list[Type]:\n        \"\"\"Handle directly applying type arguments to a variadic Callable.\n\n        This is needed in situations where e.g. variadic class object appears in\n        runtime context. For example:\n            class C(Generic[T, Unpack[Ts]]): ...\n            x = C[int, str]()\n\n        We simply group the arguments that need to go into Ts variable into a TupleType,\n        similar to how it is done in other places using split_with_prefix_and_suffix().\n        \"\"\"\n        if t.is_type_obj():\n            # Type arguments must map to class type variables, ignoring constructor vars.\n            vars = t.type_object().defn.type_vars\n        else:\n            vars = list(t.variables)\n        args = flatten_nested_tuples(args)\n\n        # TODO: this logic is duplicated with semanal_typeargs.\n        for tv, arg in zip(t.variables, args):\n            if isinstance(tv, ParamSpecType):\n                if not isinstance(\n                    get_proper_type(arg), (Parameters, ParamSpecType, AnyType, UnboundType)\n                ):\n                    self.chk.fail(\n                        \"Can only replace ParamSpec with a parameter types list or\"\n                        f\" another ParamSpec, got {format_type(arg, self.chk.options)}\",\n                        ctx,\n                    )\n                    return [AnyType(TypeOfAny.from_error)] * len(vars)\n\n        # TODO: in future we may want to support type application to variadic functions.\n        if (\n            not vars\n            or not any(isinstance(v, TypeVarTupleType) for v in vars)\n            or not t.is_type_obj()\n        ):\n            return list(args)\n        info = t.type_object()\n        # We reuse the logic from semanal phase to reduce code duplication.\n        fake = Instance(info, args, line=ctx.line, column=ctx.column)\n        # This code can be only called either from checking a type application, or from\n        # checking a type alias (after the caller handles no_args aliases), so we know it\n        # was initially an IndexExpr, and we allow empty tuple type arguments.\n        if not validate_instance(fake, self.chk.fail, indexed=True):\n            fix_instance(\n                fake, self.chk.fail, self.chk.note, disallow_any=False, options=self.chk.options\n            )\n            args = list(fake.args)\n\n        prefix = next(i for (i, v) in enumerate(vars) if isinstance(v, TypeVarTupleType))\n        suffix = len(vars) - prefix - 1\n        tvt = vars[prefix]\n        assert isinstance(tvt, TypeVarTupleType)\n        start, middle, end = split_with_prefix_and_suffix(tuple(args), prefix, suffix)\n        return list(start) + [TupleType(list(middle), tvt.tuple_fallback)] + list(end)\n\n    def apply_type_arguments_to_callable(\n        self, tp: Type, args: Sequence[Type], ctx: Context\n    ) -> Type:\n        \"\"\"Apply type arguments to a generic callable type coming from a type object.\n\n        This will first perform type arguments count checks, report the\n        error as needed, and return the correct kind of Any. As a special\n        case this returns Any for non-callable types, because if type object type\n        is not callable, then an error should be already reported.\n        \"\"\"\n        tp = get_proper_type(tp)\n\n        if isinstance(tp, CallableType):\n            if tp.is_type_obj():\n                # If we have a class object in runtime context, then the available type\n                # variables are those of the class, we don't include additional variables\n                # of the constructor. So that with\n                #     class C(Generic[T]):\n                #         def __init__(self, f: Callable[[S], T], x: S) -> None\n                # C[int] is valid\n                # C[int, str] is invalid (although C as a callable has 2 type variables)\n                # Note: various logic below and in applytype.py relies on the fact that\n                # class type variables appear *before* constructor variables.\n                type_vars = tp.type_object().defn.type_vars\n            else:\n                type_vars = list(tp.variables)\n            min_arg_count = sum(not v.has_default() for v in type_vars)\n            has_type_var_tuple = any(isinstance(v, TypeVarTupleType) for v in type_vars)\n            if (\n                len(args) < min_arg_count or len(args) > len(type_vars)\n            ) and not has_type_var_tuple:\n                if tp.is_type_obj() and tp.type_object().fullname == \"builtins.tuple\":\n                    # e.g. expression tuple[X, Y]\n                    # - want the type of the expression i.e. a function with that as its return type\n                    # - tp is type of tuple (note it won't have params as we are only called\n                    #   with generic callable type)\n                    # - tuple[X, Y]() takes a single arg that is a tuple containing an X and a Y\n                    return CallableType(\n                        [TupleType(list(args), self.chk.named_type(\"tuple\"))],\n                        [ARG_POS],\n                        [None],\n                        TupleType(list(args), self.chk.named_type(\"tuple\")),\n                        tp.fallback,\n                        name=\"tuple\",\n                        definition=tp.definition,\n                        is_bound=tp.is_bound,\n                    )\n                self.msg.incompatible_type_application(\n                    min_arg_count, len(type_vars), len(args), ctx\n                )\n                return AnyType(TypeOfAny.from_error)\n            return self.apply_generic_arguments(tp, self.split_for_callable(tp, args, ctx), ctx)\n        if isinstance(tp, Overloaded):\n            for it in tp.items:\n                if tp.is_type_obj():\n                    # Same as above.\n                    type_vars = tp.type_object().defn.type_vars\n                else:\n                    type_vars = list(it.variables)\n                min_arg_count = sum(not v.has_default() for v in type_vars)\n                has_type_var_tuple = any(isinstance(v, TypeVarTupleType) for v in type_vars)\n                if (\n                    len(args) < min_arg_count or len(args) > len(type_vars)\n                ) and not has_type_var_tuple:\n                    self.msg.incompatible_type_application(\n                        min_arg_count, len(type_vars), len(args), ctx\n                    )\n                    return AnyType(TypeOfAny.from_error)\n            return Overloaded(\n                [\n                    self.apply_generic_arguments(it, self.split_for_callable(it, args, ctx), ctx)\n                    for it in tp.items\n                ]\n            )\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_list_expr(self, e: ListExpr) -> Type:\n        \"\"\"Type check a list expression [...].\"\"\"\n        return self.check_lst_expr(e, \"builtins.list\", \"<list>\")\n\n    def visit_set_expr(self, e: SetExpr) -> Type:\n        return self.check_lst_expr(e, \"builtins.set\", \"<set>\")\n\n    def fast_container_type(\n        self, e: ListExpr | SetExpr | TupleExpr, container_fullname: str\n    ) -> Type | None:\n        \"\"\"\n        Fast path to determine the type of a list or set literal,\n        based on the list of entries. This mostly impacts large\n        module-level constant definitions.\n\n        Limitations:\n\n         - no active type context\n         - at least one item\n         - no star expressions\n         - not after deferral\n         - either exactly one distinct type inside,\n           or the joined type of all entries is an Instance or Tuple type,\n        \"\"\"\n        ctx = self.type_context[-1]\n        if ctx or not e.items:\n            return None\n        if self.chk.current_node_deferred:\n            # Guarantees that all items will be Any, we'll reject it anyway.\n            return None\n        values: list[Type] = []\n        # Preserve join order while avoiding O(n) lookups at every iteration\n        values_set: set[Type] = set()\n        for item in e.items:\n            if isinstance(item, StarExpr):\n                # fallback to slow path\n                return None\n\n            typ = self.accept(item)\n            if typ not in values_set:\n                values.append(typ)\n                values_set.add(typ)\n\n        vt = self._first_or_join_fast_item(values)\n        if vt is None:\n            return None\n        return self.chk.named_generic_type(container_fullname, [vt])\n\n    def _first_or_join_fast_item(self, items: list[Type]) -> Type | None:\n        if len(items) == 1 and not self.chk.current_node_deferred:\n            return items[0]\n        typ = join.join_type_list(items)\n        if not allow_fast_container_literal(typ):\n            # TODO: This is overly strict, many other types can be joined safely here.\n            # However, our join implementation isn't bug-free, and some joins may produce\n            # undesired `Any`s or even more surprising results.\n            return None\n        return typ\n\n    def check_lst_expr(self, e: ListExpr | SetExpr | TupleExpr, fullname: str, tag: str) -> Type:\n        # fast path\n        t = self.fast_container_type(e, fullname)\n        if t:\n            return t\n\n        # Translate into type checking a generic function call.\n        # Used for list and set expressions, as well as for tuples\n        # containing star expressions that don't refer to a\n        # Tuple. (Note: \"lst\" stands for list-set-tuple. :-)\n        tv = TypeVarType(\n            \"T\",\n            \"T\",\n            id=TypeVarId(-1, namespace=\"<lst>\"),\n            values=[],\n            upper_bound=self.object_type(),\n            default=AnyType(TypeOfAny.from_omitted_generics),\n        )\n        constructor = CallableType(\n            [tv],\n            [nodes.ARG_STAR],\n            [None],\n            self.chk.named_generic_type(fullname, [tv]),\n            self.named_type(\"builtins.function\"),\n            name=tag,\n            variables=[tv],\n        )\n        out = self.check_call(\n            constructor,\n            [(i.expr if isinstance(i, StarExpr) else i) for i in e.items],\n            [(nodes.ARG_STAR if isinstance(i, StarExpr) else nodes.ARG_POS) for i in e.items],\n            e,\n        )[0]\n        return remove_instance_last_known_values(out)\n\n    def tuple_context_matches(self, expr: TupleExpr, ctx: TupleType) -> bool:\n        ctx_unpack_index = find_unpack_in_list(ctx.items)\n        if ctx_unpack_index is None:\n            # For fixed tuples accept everything that can possibly match, even if this\n            # requires all star items to be empty.\n            return len([e for e in expr.items if not isinstance(e, StarExpr)]) <= len(ctx.items)\n        # For variadic context, the only easy case is when structure matches exactly.\n        # TODO: try using tuple type context in more cases.\n        if len([e for e in expr.items if isinstance(e, StarExpr)]) != 1:\n            return False\n        expr_star_index = next(i for i, lv in enumerate(expr.items) if isinstance(lv, StarExpr))\n        return len(expr.items) == len(ctx.items) and ctx_unpack_index == expr_star_index\n\n    def visit_tuple_expr(self, e: TupleExpr) -> Type:\n        \"\"\"Type check a tuple expression.\"\"\"\n        # Try to determine type context for type inference.\n        type_context = get_proper_type(self.type_context[-1])\n        type_context_items = None\n        if isinstance(type_context, UnionType):\n            tuples_in_context = [\n                t\n                for t in get_proper_types(type_context.items)\n                if (isinstance(t, TupleType) and self.tuple_context_matches(e, t))\n                or is_named_instance(t, TUPLE_LIKE_INSTANCE_NAMES)\n            ]\n            if len(tuples_in_context) == 1:\n                type_context = tuples_in_context[0]\n            else:\n                # There are either no relevant tuples in the Union, or there is\n                # more than one.  Either way, we can't decide on a context.\n                pass\n\n        if isinstance(type_context, TupleType) and self.tuple_context_matches(e, type_context):\n            type_context_items = type_context.items\n        elif type_context and is_named_instance(type_context, TUPLE_LIKE_INSTANCE_NAMES):\n            assert isinstance(type_context, Instance)\n            if type_context.args:\n                type_context_items = [type_context.args[0]] * len(e.items)\n        # NOTE: it's possible for the context to have a different\n        # number of items than e.  In that case we use those context\n        # items that match a position in e, and we'll worry about type\n        # mismatches later.\n\n        unpack_in_context = False\n        if type_context_items is not None:\n            unpack_in_context = find_unpack_in_list(type_context_items) is not None\n        seen_unpack_in_items = False\n        allow_precise_tuples = (\n            unpack_in_context or PRECISE_TUPLE_TYPES in self.chk.options.enable_incomplete_feature\n        )\n\n        # Infer item types.  Give up if there's a star expression\n        # that's not a Tuple.\n        items: list[Type] = []\n        j = 0  # Index into type_context_items; irrelevant if type_context_items is none\n        for i in range(len(e.items)):\n            item = e.items[i]\n            if isinstance(item, StarExpr):\n                # Special handling for star expressions.\n                # TODO: If there's a context, and item.expr is a\n                # TupleExpr, flatten it, so we can benefit from the\n                # context?  Counterargument: Why would anyone write\n                # (1, *(2, 3)) instead of (1, 2, 3) except in a test?\n                if unpack_in_context:\n                    # Note: this logic depends on full structure match in tuple_context_matches().\n                    assert type_context_items\n                    ctx_item = type_context_items[j]\n                    assert isinstance(ctx_item, UnpackType)\n                    ctx = ctx_item.type\n                else:\n                    ctx = None\n                tt = self.accept(item.expr, ctx)\n                tt = get_proper_type(tt)\n                if isinstance(tt, TupleType):\n                    if find_unpack_in_list(tt.items) is not None:\n                        if seen_unpack_in_items:\n                            # Multiple unpack items are not allowed in tuples,\n                            # fall back to instance type.\n                            return self.check_lst_expr(e, \"builtins.tuple\", \"<tuple>\")\n                        else:\n                            seen_unpack_in_items = True\n                    items.extend(tt.items)\n                    # Note: this logic depends on full structure match in tuple_context_matches().\n                    if unpack_in_context:\n                        j += 1\n                    else:\n                        # If there is an unpack in expressions, but not in context, this will\n                        # result in an error later, just do something predictable here.\n                        j += len(tt.items)\n                else:\n                    if allow_precise_tuples and not seen_unpack_in_items:\n                        # Handle (x, *y, z), where y is e.g. tuple[Y, ...].\n                        if isinstance(tt, Instance) and self.chk.type_is_iterable(tt):\n                            item_type = self.chk.iterable_item_type(tt, e)\n                            mapped = self.chk.named_generic_type(\"builtins.tuple\", [item_type])\n                            items.append(UnpackType(mapped))\n                            seen_unpack_in_items = True\n                            continue\n                    # A star expression that's not a Tuple.\n                    # Treat the whole thing as a variable-length tuple.\n                    return self.check_lst_expr(e, \"builtins.tuple\", \"<tuple>\")\n            else:\n                if not type_context_items or j >= len(type_context_items):\n                    tt = self.accept(item)\n                else:\n                    tt = self.accept(item, type_context_items[j])\n                    j += 1\n                items.append(tt)\n        # This is a partial fallback item type. A precise type will be calculated on demand.\n        fallback_item = AnyType(TypeOfAny.special_form)\n        result: ProperType = TupleType(\n            items, self.chk.named_generic_type(\"builtins.tuple\", [fallback_item])\n        )\n        if seen_unpack_in_items:\n            # Return already normalized tuple type just in case.\n            result = expand_type(result, {})\n        return result\n\n    def fast_dict_type(self, e: DictExpr) -> Type | None:\n        \"\"\"\n        Fast path to determine the type of a dict literal,\n        based on the list of entries. This mostly impacts large\n        module-level constant definitions.\n\n        Limitations:\n\n         - no active type context\n         - at least one item\n         - only supported star expressions are other dict instances\n         - either exactly one distinct type (keys and values separately) inside,\n           or the joined type of all entries is an Instance or Tuple type\n        \"\"\"\n        ctx = self.type_context[-1]\n        if ctx or not e.items:\n            return None\n\n        if self.chk.current_node_deferred:\n            # Guarantees that all items will be Any, we'll reject it anyway.\n            return None\n\n        keys: list[Type] = []\n        values: list[Type] = []\n        # Preserve join order while avoiding O(n) lookups at every iteration\n        keys_set: set[Type] = set()\n        values_set: set[Type] = set()\n        stargs: tuple[Type, Type] | None = None\n        for key, value in e.items:\n            if key is None:\n                st = get_proper_type(self.accept(value))\n                if (\n                    isinstance(st, Instance)\n                    and st.type.fullname == \"builtins.dict\"\n                    and len(st.args) == 2\n                ):\n                    stargs = (st.args[0], st.args[1])\n                else:\n                    return None\n            else:\n                key_t = self.accept(key)\n                if key_t not in keys_set:\n                    keys.append(key_t)\n                    keys_set.add(key_t)\n                value_t = self.accept(value)\n                if value_t not in values_set:\n                    values.append(value_t)\n                    values_set.add(value_t)\n\n        kt = self._first_or_join_fast_item(keys)\n        if kt is None:\n            return None\n\n        vt = self._first_or_join_fast_item(values)\n        if vt is None:\n            return None\n\n        if stargs and (stargs[0] != kt or stargs[1] != vt):\n            return None\n        return self.chk.named_generic_type(\"builtins.dict\", [kt, vt])\n\n    def check_typeddict_literal_in_context(\n        self, e: DictExpr, typeddict_context: TypedDictType\n    ) -> Type:\n        orig_ret_type = self.check_typeddict_call_with_dict(\n            callee=typeddict_context, kwargs=e.items, context=e, orig_callee=None\n        )\n        ret_type = get_proper_type(orig_ret_type)\n        if isinstance(ret_type, TypedDictType):\n            return ret_type.copy_modified()\n        return typeddict_context.copy_modified()\n\n    def visit_dict_expr(self, e: DictExpr) -> Type:\n        \"\"\"Type check a dict expression.\n\n        Translate it into a call to dict(), with provisions for **expr.\n        \"\"\"\n        # if the dict literal doesn't match TypedDict, check_typeddict_call_with_dict reports\n        # an error, but returns the TypedDict type that matches the literal it found\n        # that would cause a second error when that TypedDict type is returned upstream\n        # to avoid the second error, we always return TypedDict type that was requested\n        typeddict_contexts, exhaustive = self.find_typeddict_context(self.type_context[-1], e)\n        if typeddict_contexts:\n            if len(typeddict_contexts) == 1 and exhaustive:\n                return self.check_typeddict_literal_in_context(e, typeddict_contexts[0])\n            # Multiple items union, check if at least one of them matches cleanly.\n            for typeddict_context in typeddict_contexts:\n                with self.msg.filter_errors() as err, self.chk.local_type_map as tmap:\n                    ret_type = self.check_typeddict_literal_in_context(e, typeddict_context)\n                if err.has_new_errors():\n                    continue\n                self.chk.store_types(tmap)\n                return ret_type\n            # No item matched without an error, so we can't unambiguously choose the item.\n            if exhaustive:\n                self.msg.typeddict_context_ambiguous(typeddict_contexts, e)\n\n        # fast path attempt\n        dt = self.fast_dict_type(e)\n        if dt:\n            return dt\n\n        # Define type variables (used in constructors below).\n        kt = TypeVarType(\n            \"KT\",\n            \"KT\",\n            id=TypeVarId(-1, namespace=\"<dict>\"),\n            values=[],\n            upper_bound=self.object_type(),\n            default=AnyType(TypeOfAny.from_omitted_generics),\n        )\n        vt = TypeVarType(\n            \"VT\",\n            \"VT\",\n            id=TypeVarId(-2, namespace=\"<dict>\"),\n            values=[],\n            upper_bound=self.object_type(),\n            default=AnyType(TypeOfAny.from_omitted_generics),\n        )\n\n        # Collect function arguments, watching out for **expr.\n        args: list[Expression] = []\n        expected_types: list[Type] = []\n        for key, value in e.items:\n            if key is None:\n                args.append(value)\n                expected_types.append(\n                    self.chk.named_generic_type(\"_typeshed.SupportsKeysAndGetItem\", [kt, vt])\n                )\n            else:\n                tup = TupleExpr([key, value])\n                if key.line >= 0:\n                    tup.line = key.line\n                    tup.column = key.column\n                else:\n                    tup.line = value.line\n                    tup.column = value.column\n                tup.end_line = value.end_line\n                tup.end_column = value.end_column\n                args.append(tup)\n                expected_types.append(TupleType([kt, vt], self.named_type(\"builtins.tuple\")))\n\n        # The callable type represents a function like this (except we adjust for **expr):\n        #   def <dict>(*v: Tuple[kt, vt]) -> Dict[kt, vt]: ...\n        constructor = CallableType(\n            expected_types,\n            [nodes.ARG_POS] * len(expected_types),\n            [None] * len(expected_types),\n            self.chk.named_generic_type(\"builtins.dict\", [kt, vt]),\n            self.named_type(\"builtins.function\"),\n            name=\"<dict>\",\n            variables=[kt, vt],\n        )\n        return self.check_call(constructor, args, [nodes.ARG_POS] * len(args), e)[0]\n\n    def find_typeddict_context(\n        self, context: Type | None, dict_expr: DictExpr\n    ) -> tuple[list[TypedDictType], bool]:\n        \"\"\"Extract `TypedDict` members of the enclosing context.\n\n        Returns:\n            a 2-tuple, (found_candidates, is_exhaustive)\n        \"\"\"\n        context = get_proper_type(context)\n        if isinstance(context, TypedDictType):\n            return [context], True\n        elif isinstance(context, UnionType):\n            items = []\n            exhaustive = True\n            for item in context.items:\n                item_contexts, item_exhaustive = self.find_typeddict_context(item, dict_expr)\n                for item_context in item_contexts:\n                    if self.match_typeddict_call_with_dict(\n                        item_context, dict_expr.items, dict_expr\n                    ):\n                        items.append(item_context)\n                exhaustive = exhaustive and item_exhaustive\n            return items, exhaustive\n        # No TypedDict type in context.\n        return [], False\n\n    def visit_template_str_expr(self, e: TemplateStrExpr) -> Type:\n        \"\"\"Type check a template string expression (t-string).\n\n        Type-checks all interpolated expressions but the result is always\n        string.templatelib.Template.\n        \"\"\"\n        for item in e.items:\n            if isinstance(item, tuple):\n                value_expr, _source, _conversion, format_spec = item\n                self.accept(value_expr)\n                if format_spec is not None:\n                    self.accept(format_spec)\n        sym = lookup_fully_qualified(\"string.templatelib.Template\", self.chk.modules)\n        if sym is not None and isinstance(sym.node, TypeInfo):\n            return Instance(sym.node, [])\n        return AnyType(TypeOfAny.from_error)\n\n    def visit_lambda_expr(self, e: LambdaExpr) -> Type:\n        \"\"\"Type check lambda expression.\"\"\"\n        old_in_lambda = self.in_lambda_expr\n        self.in_lambda_expr = True\n        self.chk.check_default_params(e, body_is_trivial=False)\n        inferred_type, type_override = self.infer_lambda_type_using_context(e)\n        if not inferred_type:\n            self.chk.return_types.append(AnyType(TypeOfAny.special_form))\n            # Type check everything in the body except for the final return\n            # statement (it can contain tuple unpacking before return).\n            with (\n                self.chk.binder.frame_context(can_skip=True, fall_through=0),\n                self.chk.scope.push_function(e),\n            ):\n                # Lambdas can have more than one element in body,\n                # when we add \"fictional\" AssignmentStatement nodes, like in:\n                # `lambda (a, b): a`\n                for stmt in e.body.body[:-1]:\n                    stmt.accept(self.chk)\n                # Only type check the return expression, not the return statement.\n                # There's no useful type context.\n                ret_type = self.accept(e.expr(), allow_none_return=True)\n            fallback = self.named_type(\"builtins.function\")\n            self.chk.return_types.pop()\n            self.in_lambda_expr = old_in_lambda\n            return callable_type(e, fallback, ret_type)\n        else:\n            # Type context available.\n            self.chk.return_types.append(inferred_type.ret_type)\n            with self.chk.tscope.function_scope(e):\n                self.chk.check_func_item(e, type_override=type_override)\n            if not self.chk.has_type(e.expr()):\n                # TODO: return expression must be accepted before exiting function scope.\n                with self.chk.binder.frame_context(can_skip=True, fall_through=0):\n                    self.accept(e.expr(), allow_none_return=True)\n            ret_type = self.chk.lookup_type(e.expr())\n            self.chk.return_types.pop()\n            self.in_lambda_expr = old_in_lambda\n            return replace_callable_return_type(inferred_type, ret_type)\n\n    def infer_lambda_type_using_context(\n        self, e: LambdaExpr\n    ) -> tuple[CallableType | None, CallableType | None]:\n        \"\"\"Try to infer lambda expression type using context.\n\n        Return None if could not infer type.\n        The second item in the return type is the type_override parameter for check_func_item.\n        \"\"\"\n        # TODO also accept 'Any' context\n        ctx = get_proper_type(self.type_context[-1])\n\n        if isinstance(ctx, UnionType):\n            callables = [\n                t for t in get_proper_types(ctx.relevant_items()) if isinstance(t, CallableType)\n            ]\n            if len(callables) == 1:\n                ctx = callables[0]\n\n        if not ctx or not isinstance(ctx, CallableType):\n            return None, None\n\n        # The context may have function type variables in it. We replace them\n        # since these are the type variables we are ultimately trying to infer;\n        # they must be considered as indeterminate. We use ErasedType since it\n        # does not affect type inference results (it is for purposes like this\n        # only).\n        if not self.chk.options.old_type_inference:\n            # With new type inference we can preserve argument types even if they\n            # are generic, since new inference algorithm can handle constraints\n            # like S <: T (we still erase return type since it's ultimately unknown).\n            extra_vars = []\n            for arg in ctx.arg_types:\n                meta_vars = [tv for tv in get_all_type_vars(arg) if tv.id.is_meta_var()]\n                extra_vars.extend([tv for tv in meta_vars if tv not in extra_vars])\n            callable_ctx = ctx.copy_modified(\n                ret_type=replace_meta_vars(ctx.ret_type, ErasedType()),\n                variables=list(ctx.variables) + extra_vars,\n            )\n        else:\n            erased_ctx = replace_meta_vars(ctx, ErasedType())\n            assert isinstance(erased_ctx, ProperType) and isinstance(erased_ctx, CallableType)\n            callable_ctx = erased_ctx\n\n        # The callable_ctx may have a fallback of builtins.type if the context\n        # is a constructor -- but this fallback doesn't make sense for lambdas.\n        callable_ctx = callable_ctx.copy_modified(fallback=self.named_type(\"builtins.function\"))\n\n        if callable_ctx.type_guard is not None or callable_ctx.type_is is not None:\n            # Lambda's return type cannot be treated as a `TypeGuard`,\n            # because it is implicit. And `TypeGuard`s must be explicit.\n            # See https://github.com/python/mypy/issues/9927\n            return None, None\n\n        arg_kinds = [arg.kind for arg in e.arguments]\n\n        if callable_ctx.is_ellipsis_args or ctx.param_spec() is not None:\n            # Fill in Any arguments to match the arguments of the lambda.\n            callable_ctx = callable_ctx.copy_modified(\n                is_ellipsis_args=False,\n                arg_types=[AnyType(TypeOfAny.special_form)] * len(arg_kinds),\n                arg_kinds=arg_kinds,\n                arg_names=e.arg_names.copy(),\n            )\n\n        if ARG_STAR in arg_kinds or ARG_STAR2 in arg_kinds:\n            # TODO treat this case appropriately\n            return callable_ctx, None\n\n        if callable_ctx.arg_kinds != arg_kinds:\n            # Incompatible context; cannot use it to infer types.\n            self.chk.fail(message_registry.CANNOT_INFER_LAMBDA_TYPE, e)\n            return None, None\n\n        # Type of lambda must have correct argument names, to prevent false\n        # negatives when lambdas appear in `ParamSpec` context.\n        return callable_ctx.copy_modified(arg_names=e.arg_names), callable_ctx\n\n    def visit_super_expr(self, e: SuperExpr) -> Type:\n        \"\"\"Type check a super expression (non-lvalue).\"\"\"\n\n        # We have an expression like super(T, var).member\n\n        # First compute the types of T and var\n        types = self._super_arg_types(e)\n        if isinstance(types, tuple):\n            type_type, instance_type = types\n        else:\n            return types\n\n        # Now get the MRO\n        type_info = type_info_from_type(type_type)\n        if type_info is None:\n            self.chk.fail(message_registry.UNSUPPORTED_ARG_1_FOR_SUPER, e)\n            return AnyType(TypeOfAny.from_error)\n\n        instance_info = type_info_from_type(instance_type)\n        if instance_info is None:\n            self.chk.fail(message_registry.UNSUPPORTED_ARG_2_FOR_SUPER, e)\n            return AnyType(TypeOfAny.from_error)\n\n        mro = instance_info.mro\n\n        # The base is the first MRO entry *after* type_info that has a member\n        # with the right name\n        index = None\n        if type_info in mro:\n            index = mro.index(type_info)\n        else:\n            method = self.chk.scope.current_function()\n            # Mypy explicitly allows supertype upper bounds (and no upper bound at all)\n            # for annotating self-types. However, if such an annotation is used for\n            # checking super() we will still get an error. So to be consistent, we also\n            # allow such imprecise annotations for use with super(), where we fall back\n            # to the current class MRO instead. This works only from inside a method.\n            if method is not None and is_self_type_like(\n                instance_type, is_classmethod=method.is_class\n            ):\n                if e.info and type_info in e.info.mro:\n                    mro = e.info.mro\n                    index = mro.index(type_info)\n        if index is None:\n            if (\n                instance_info.is_protocol\n                and instance_info != type_info\n                and not type_info.is_protocol\n            ):\n                # A special case for mixins, in this case super() should point\n                # directly to the host protocol, this is not safe, since the real MRO\n                # is not known yet for mixin, but this feature is more like an escape hatch.\n                index = -1\n            else:\n                self.chk.fail(message_registry.SUPER_ARG_2_NOT_INSTANCE_OF_ARG_1, e)\n                return AnyType(TypeOfAny.from_error)\n\n        if len(mro) == index + 1:\n            self.chk.fail(message_registry.TARGET_CLASS_HAS_NO_BASE_CLASS, e)\n            return AnyType(TypeOfAny.from_error)\n\n        for base in mro[index + 1 :]:\n            if e.name in base.names or base == mro[-1]:\n                if e.info and e.info.fallback_to_any and base == mro[-1]:\n                    # There's an undefined base class, and we're at the end of the\n                    # chain.  That's not an error.\n                    return AnyType(TypeOfAny.special_form)\n\n                return analyze_member_access(\n                    name=e.name,\n                    typ=instance_type,\n                    is_lvalue=False,\n                    is_super=True,\n                    is_operator=False,\n                    original_type=instance_type,\n                    override_info=base,\n                    context=e,\n                    chk=self.chk,\n                    in_literal_context=self.is_literal_context(),\n                )\n\n        assert False, \"unreachable\"\n\n    def _super_arg_types(self, e: SuperExpr) -> Type | tuple[Type, Type]:\n        \"\"\"\n        Computes the types of the type and instance expressions in super(T, instance), or the\n        implicit ones for zero-argument super() expressions.  Returns a single type for the whole\n        super expression when possible (for errors, anys), otherwise the pair of computed types.\n        \"\"\"\n\n        if not self.chk.in_checked_function():\n            return AnyType(TypeOfAny.unannotated)\n        elif len(e.call.args) == 0:\n            if not e.info:\n                # This has already been reported by the semantic analyzer.\n                return AnyType(TypeOfAny.from_error)\n            elif self.chk.scope.active_class():\n                self.chk.fail(message_registry.SUPER_OUTSIDE_OF_METHOD_NOT_SUPPORTED, e)\n                return AnyType(TypeOfAny.from_error)\n\n            # Zero-argument super() is like super(<current class>, <self>)\n            current_type = fill_typevars(e.info)\n            type_type: ProperType = TypeType(current_type)\n\n            # Use the type of the self argument, in case it was annotated\n            method = self.chk.scope.current_function()\n            assert method is not None\n            if method.arguments:\n                instance_type: Type = method.arguments[0].variable.type or current_type\n            else:\n                self.chk.fail(message_registry.SUPER_ENCLOSING_POSITIONAL_ARGS_REQUIRED, e)\n                return AnyType(TypeOfAny.from_error)\n        elif ARG_STAR in e.call.arg_kinds:\n            self.chk.fail(message_registry.SUPER_VARARGS_NOT_SUPPORTED, e)\n            return AnyType(TypeOfAny.from_error)\n        elif set(e.call.arg_kinds) != {ARG_POS}:\n            self.chk.fail(message_registry.SUPER_POSITIONAL_ARGS_REQUIRED, e)\n            return AnyType(TypeOfAny.from_error)\n        elif len(e.call.args) == 1:\n            self.chk.fail(message_registry.SUPER_WITH_SINGLE_ARG_NOT_SUPPORTED, e)\n            return AnyType(TypeOfAny.from_error)\n        elif len(e.call.args) == 2:\n            type_type = get_proper_type(self.accept(e.call.args[0]))\n            instance_type = self.accept(e.call.args[1])\n        else:\n            self.chk.fail(message_registry.TOO_MANY_ARGS_FOR_SUPER, e)\n            return AnyType(TypeOfAny.from_error)\n\n        # Imprecisely assume that the type is the current class\n        if isinstance(type_type, AnyType):\n            if e.info:\n                type_type = TypeType(fill_typevars(e.info))\n            else:\n                return AnyType(TypeOfAny.from_another_any, source_any=type_type)\n        elif isinstance(type_type, TypeType):\n            type_item = type_type.item\n            if isinstance(type_item, AnyType):\n                if e.info:\n                    type_type = TypeType(fill_typevars(e.info))\n                else:\n                    return AnyType(TypeOfAny.from_another_any, source_any=type_item)\n\n        if not isinstance(type_type, TypeType) and not (\n            isinstance(type_type, FunctionLike) and type_type.is_type_obj()\n        ):\n            self.msg.first_argument_for_super_must_be_type(type_type, e)\n            return AnyType(TypeOfAny.from_error)\n\n        # Imprecisely assume that the instance is of the current class\n        instance_type = get_proper_type(instance_type)\n        if isinstance(instance_type, AnyType):\n            if e.info:\n                instance_type = fill_typevars(e.info)\n            else:\n                return AnyType(TypeOfAny.from_another_any, source_any=instance_type)\n        elif isinstance(instance_type, TypeType):\n            instance_item = instance_type.item\n            if isinstance(instance_item, AnyType):\n                if e.info:\n                    instance_type = TypeType(fill_typevars(e.info))\n                else:\n                    return AnyType(TypeOfAny.from_another_any, source_any=instance_item)\n\n        return type_type, instance_type\n\n    def visit_slice_expr(self, e: SliceExpr) -> Type:\n        try:\n            supports_index = self.chk.named_type(\"typing_extensions.SupportsIndex\")\n        except KeyError:\n            supports_index = self.chk.named_type(\"builtins.int\")  # thanks, fixture life\n        expected = make_optional_type(supports_index)\n        type_args = []\n        for index in [e.begin_index, e.end_index, e.stride]:\n            if index:\n                t = self.accept(index)\n                self.chk.check_subtype(t, expected, index, message_registry.INVALID_SLICE_INDEX)\n                type_args.append(t)\n            else:\n                type_args.append(NoneType())\n        return self.chk.named_generic_type(\"builtins.slice\", type_args)\n\n    def visit_list_comprehension(self, e: ListComprehension) -> Type:\n        return self.check_generator_or_comprehension(\n            e.generator, \"builtins.list\", \"<list-comprehension>\"\n        )\n\n    def visit_set_comprehension(self, e: SetComprehension) -> Type:\n        return self.check_generator_or_comprehension(\n            e.generator, \"builtins.set\", \"<set-comprehension>\"\n        )\n\n    def visit_generator_expr(self, e: GeneratorExpr) -> Type:\n        # If any of the comprehensions use async for, the expression will return an async generator\n        # object, or await is used anywhere but in the leftmost sequence.\n        if (\n            any(e.is_async)\n            or has_await_expression(e.left_expr)\n            or any(has_await_expression(sequence) for sequence in e.sequences[1:])\n            or any(has_await_expression(cond) for condlist in e.condlists for cond in condlist)\n        ):\n            typ = \"typing.AsyncGenerator\"\n            # received type is always None in async generator expressions\n            additional_args: list[Type] = [NoneType()]\n        else:\n            typ = \"typing.Generator\"\n            # received type and returned type are None\n            additional_args = [NoneType(), NoneType()]\n        return self.check_generator_or_comprehension(\n            e, typ, \"<generator>\", additional_args=additional_args\n        )\n\n    def check_generator_or_comprehension(\n        self,\n        gen: GeneratorExpr,\n        type_name: str,\n        id_for_messages: str,\n        additional_args: list[Type] | None = None,\n    ) -> Type:\n        \"\"\"Type check a generator expression or a list comprehension.\"\"\"\n        additional_args = additional_args or []\n        with self.chk.binder.frame_context(can_skip=True, fall_through=0):\n            self.check_for_comp(gen)\n\n            # Infer the type of the list comprehension by using a synthetic generic\n            # callable type.\n            tv = TypeVarType(\n                \"T\",\n                \"T\",\n                id=TypeVarId(-1, namespace=\"<genexp>\"),\n                values=[],\n                upper_bound=self.object_type(),\n                default=AnyType(TypeOfAny.from_omitted_generics),\n            )\n            tv_list: list[Type] = [tv]\n            constructor = CallableType(\n                tv_list,\n                [nodes.ARG_POS],\n                [None],\n                self.chk.named_generic_type(type_name, tv_list + additional_args),\n                self.chk.named_type(\"builtins.function\"),\n                name=id_for_messages,\n                variables=[tv],\n            )\n            return self.check_call(constructor, [gen.left_expr], [nodes.ARG_POS], gen)[0]\n\n    def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> Type:\n        \"\"\"Type check a dictionary comprehension.\"\"\"\n        with self.chk.binder.frame_context(can_skip=True, fall_through=0):\n            self.check_for_comp(e)\n\n            # Infer the type of the list comprehension by using a synthetic generic\n            # callable type.\n            ktdef = TypeVarType(\n                \"KT\",\n                \"KT\",\n                id=TypeVarId(-1, namespace=\"<dict>\"),\n                values=[],\n                upper_bound=self.object_type(),\n                default=AnyType(TypeOfAny.from_omitted_generics),\n            )\n            vtdef = TypeVarType(\n                \"VT\",\n                \"VT\",\n                id=TypeVarId(-2, namespace=\"<dict>\"),\n                values=[],\n                upper_bound=self.object_type(),\n                default=AnyType(TypeOfAny.from_omitted_generics),\n            )\n            constructor = CallableType(\n                [ktdef, vtdef],\n                [nodes.ARG_POS, nodes.ARG_POS],\n                [None, None],\n                self.chk.named_generic_type(\"builtins.dict\", [ktdef, vtdef]),\n                self.chk.named_type(\"builtins.function\"),\n                name=\"<dictionary-comprehension>\",\n                variables=[ktdef, vtdef],\n            )\n            return self.check_call(\n                constructor, [e.key, e.value], [nodes.ARG_POS, nodes.ARG_POS], e\n            )[0]\n\n    def check_for_comp(self, e: GeneratorExpr | DictionaryComprehension) -> None:\n        \"\"\"Check the for_comp part of comprehensions. That is the part from 'for':\n        ... for x in y if z\n\n        Note: This adds the type information derived from the condlists to the current binder.\n        \"\"\"\n        for index, sequence, conditions, is_async in zip(\n            e.indices, e.sequences, e.condlists, e.is_async\n        ):\n            if is_async:\n                _, sequence_type = self.chk.analyze_async_iterable_item_type(sequence)\n            else:\n                _, sequence_type = self.chk.analyze_iterable_item_type(sequence)\n                if (\n                    isinstance(get_proper_type(sequence_type), UninhabitedType)\n                    and isinstance(index, NameExpr)\n                    and index.name == \"_\"\n                ):\n                    # To preserve backward compatibility, avoid inferring Never for \"_\"\n                    sequence_type = AnyType(TypeOfAny.special_form)\n\n            self.chk.analyze_index_variables(index, sequence_type, True, e)\n            for condition in conditions:\n                self.accept(condition)\n\n                # values are only part of the comprehension when all conditions are true\n                true_map, false_map = self.chk.find_isinstance_check(condition)\n                self.chk.push_type_map(true_map)\n\n                if codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes:\n                    if mypy.checker.is_unreachable_map(true_map):\n                        self.msg.redundant_condition_in_comprehension(False, condition)\n                    elif mypy.checker.is_unreachable_map(false_map):\n                        self.msg.redundant_condition_in_comprehension(True, condition)\n\n    def visit_conditional_expr(self, e: ConditionalExpr, allow_none_return: bool = False) -> Type:\n        self.accept(e.cond)\n        ctx: Type | None = self.type_context[-1]\n\n        # Gain type information from isinstance if it is there\n        # but only for the current expression\n        if_map, else_map = self.chk.find_isinstance_check(e.cond)\n        if codes.REDUNDANT_EXPR in self.chk.options.enabled_error_codes:\n            if mypy.checker.is_unreachable_map(if_map):\n                self.msg.redundant_condition_in_if(False, e.cond)\n            elif mypy.checker.is_unreachable_map(else_map):\n                self.msg.redundant_condition_in_if(True, e.cond)\n\n        if ctx is None:\n            # When no context is provided, compute each branch individually, and\n            # use the union of the results as artificial context. Important for:\n            # - testUnificationDict\n            # - testConditionalExpressionWithEmpty\n            ctx_if_type = self.analyze_cond_branch(\n                if_map, e.if_expr, context=ctx, allow_none_return=allow_none_return\n            )\n            ctx_else_type = self.analyze_cond_branch(\n                else_map, e.else_expr, context=ctx, allow_none_return=allow_none_return\n            )\n            if has_ambiguous_uninhabited_component(ctx_if_type):\n                ctx = ctx_else_type\n            elif has_ambiguous_uninhabited_component(ctx_else_type):\n                ctx = ctx_if_type\n            else:\n                ctx = make_simplified_union([ctx_if_type, ctx_else_type])\n\n        if_type = self.analyze_cond_branch(\n            if_map, e.if_expr, context=ctx, allow_none_return=allow_none_return\n        )\n        else_type = self.analyze_cond_branch(\n            else_map, e.else_expr, context=ctx, allow_none_return=allow_none_return\n        )\n\n        res: Type = make_simplified_union([if_type, else_type])\n        if has_uninhabited_component(res) and not isinstance(\n            get_proper_type(self.type_context[-1]), UnionType\n        ):\n            # In rare cases with empty collections join may give a better result.\n            alternative = join.join_types(if_type, else_type)\n            p_alt = get_proper_type(alternative)\n            if not isinstance(p_alt, Instance) or p_alt.type.fullname != \"builtins.object\":\n                res = alternative\n        return res\n\n    def analyze_cond_branch(\n        self,\n        map: dict[Expression, Type],\n        node: Expression,\n        context: Type | None,\n        allow_none_return: bool = False,\n        suppress_unreachable_errors: bool = True,\n    ) -> Type:\n        with self.chk.binder.frame_context(can_skip=True, fall_through=0):\n            if mypy.checker.is_unreachable_map(map):\n                # We still need to type check node, in case we want to\n                # process it for isinstance checks later. Since the branch was\n                # determined to be unreachable, any errors should be suppressed.\n                with self.msg.filter_errors(filter_errors=suppress_unreachable_errors):\n                    self.accept(node, type_context=context, allow_none_return=allow_none_return)\n                return UninhabitedType()\n            self.chk.push_type_map(map)\n            return self.accept(node, type_context=context, allow_none_return=allow_none_return)\n\n    def _combined_context(self, ty: Type | None) -> Type | None:\n        ctx_items = []\n        if ty is not None:\n            if has_any_type(ty):\n                # HACK: Any should be contagious, `dict[str, Any] or <x>` should still\n                # infer Any in x.\n                return ty\n            ctx_items.append(ty)\n        if self.type_context and self.type_context[-1] is not None:\n            ctx_items.append(self.type_context[-1])\n        if ctx_items:\n            return make_simplified_union(ctx_items)\n        return None\n\n    #\n    # Helpers\n    #\n\n    def accept(\n        self,\n        node: Expression,\n        type_context: Type | None = None,\n        allow_none_return: bool = False,\n        always_allow_any: bool = False,\n        is_callee: bool = False,\n    ) -> Type:\n        \"\"\"Type check a node in the given type context.  If allow_none_return\n        is True and this expression is a call, allow it to return None.  This\n        applies only to this expression and not any subexpressions.\n        \"\"\"\n        if node in self.type_overrides:\n            # This branch is very fast, there is no point timing it.\n            return self.type_overrides[node]\n        # We don't use context manager here to get most precise data (and avoid overhead).\n        record_time = False\n        if self.collect_line_checking_stats and not self.in_expression:\n            t0 = time.perf_counter_ns()\n            self.in_expression = True\n            record_time = True\n        self.type_context.append(type_context)\n        old_is_callee = self.is_callee\n        self.is_callee = is_callee\n        try:\n            p_type_context = get_proper_type(type_context)\n            if allow_none_return and isinstance(node, CallExpr):\n                typ = self.visit_call_expr(node, allow_none_return=True)\n            elif allow_none_return and isinstance(node, YieldFromExpr):\n                typ = self.visit_yield_from_expr(node, allow_none_return=True)\n            elif allow_none_return and isinstance(node, ConditionalExpr):\n                typ = self.visit_conditional_expr(node, allow_none_return=True)\n            elif allow_none_return and isinstance(node, AwaitExpr):\n                typ = self.visit_await_expr(node, allow_none_return=True)\n\n            elif (\n                isinstance(p_type_context, TypeType)\n                and p_type_context.is_type_form\n                and (node_as_type := self.try_parse_as_type_expression(node)) is not None\n            ):\n                typ = TypeType.make_normalized(\n                    node_as_type,\n                    line=node_as_type.line,\n                    column=node_as_type.column,\n                    is_type_form=True,\n                )  # r-value type, when interpreted as a type expression\n            elif (\n                isinstance(p_type_context, UnionType)\n                and any(\n                    isinstance(p_item := get_proper_type(item), TypeType) and p_item.is_type_form\n                    for item in p_type_context.items\n                )\n                and (node_as_type := self.try_parse_as_type_expression(node)) is not None\n            ):\n                typ1 = TypeType.make_normalized(\n                    node_as_type,\n                    line=node_as_type.line,\n                    column=node_as_type.column,\n                    is_type_form=True,\n                )\n                if is_subtype(typ1, p_type_context):\n                    typ = typ1  # r-value type, when interpreted as a type expression\n                else:\n                    typ2 = node.accept(self)\n                    typ = typ2  # r-value type, when interpreted as a value expression\n            # Deeply nested generic calls can deteriorate performance dramatically.\n            # Although in most cases caching makes little difference, in worst case\n            # it avoids exponential complexity.\n            # We cannot use cache inside lambdas, because they skip immediate type\n            # context, and use enclosing one, see infer_lambda_type_using_context().\n            # TODO: consider using cache for more expression kinds.\n            elif (\n                isinstance(node, (CallExpr, ListExpr, TupleExpr, DictExpr, OpExpr))\n                and not (self.in_lambda_expr or self.chk.current_node_deferred)\n                and not self.chk.options.disable_expression_cache\n            ):\n                if (node, type_context) in self.expr_cache:\n                    binder_version, typ, messages, type_map = self.expr_cache[(node, type_context)]\n                    if binder_version == self.chk.binder.version:\n                        self.chk.store_types(type_map)\n                        self.msg.add_errors(messages)\n                    else:\n                        typ = self.accept_maybe_cache(node, type_context=type_context)\n                else:\n                    typ = self.accept_maybe_cache(node, type_context=type_context)\n            else:\n                typ = node.accept(self)  # r-value type, when interpreted as a value expression\n        except Exception as err:\n            report_internal_error(\n                err, self.chk.errors.file, node.line, self.chk.errors, self.chk.options\n            )\n        self.is_callee = old_is_callee\n        self.type_context.pop()\n        assert typ is not None\n        self.chk.store_type(node, typ)\n\n        if (\n            self.chk.options.disallow_any_expr\n            and not always_allow_any\n            and not self.chk.is_stub\n            and self.chk.in_checked_function()\n            and has_any_type(typ)\n            and not self.chk.current_node_deferred\n        ):\n            self.msg.disallowed_any_type(typ, node)\n\n        if not self.chk.in_checked_function() or self.chk.current_node_deferred:\n            result: Type = AnyType(TypeOfAny.unannotated)\n        else:\n            result = typ\n        if record_time:\n            self.per_line_checking_time_ns[node.line] += time.perf_counter_ns() - t0\n            self.in_expression = False\n        return result\n\n    def accept_maybe_cache(self, node: Expression, type_context: Type | None = None) -> Type:\n        binder_version = self.chk.binder.version\n        with self.msg.filter_errors(filter_errors=True, save_filtered_errors=True) as msg:\n            with self.chk.local_type_map as type_map:\n                typ = node.accept(self)\n        messages = msg.filtered_errors()\n        if binder_version == self.chk.binder.version and not self.chk.current_node_deferred:\n            self.expr_cache[(node, type_context)] = (binder_version, typ, messages, type_map)\n        self.chk.store_types(type_map)\n        self.msg.add_errors(messages)\n        return typ\n\n    def named_type(self, name: str) -> Instance:\n        \"\"\"Return an instance type with type given by the name and no type\n        arguments. Alias for TypeChecker.named_type.\n        \"\"\"\n        return self.chk.named_type(name)\n\n    def type_alias_type_type(self) -> Instance:\n        \"\"\"Returns a `typing.TypeAliasType` or `typing_extensions.TypeAliasType`.\"\"\"\n        if self.chk.options.python_version >= (3, 12):\n            return self.named_type(\"typing.TypeAliasType\")\n        return self.named_type(\"typing_extensions.TypeAliasType\")\n\n    def is_valid_var_arg(self, typ: Type) -> bool:\n        \"\"\"Is a type valid as a *args argument?\"\"\"\n        typ = get_proper_type(typ)\n        return isinstance(typ, (TupleType, AnyType, ParamSpecType, UnpackType)) or is_subtype(\n            typ, self.chk.named_generic_type(\"typing.Iterable\", [AnyType(TypeOfAny.special_form)])\n        )\n\n    def is_valid_keyword_var_arg(self, typ: Type) -> bool:\n        \"\"\"Is a type valid as a **kwargs argument?\"\"\"\n        typ = get_proper_type(typ)\n        return (\n            (\n                # This is a little ad hoc, ideally we would have a map_instance_to_supertype\n                # that worked for protocols\n                isinstance(typ, Instance)\n                and typ.type.fullname == \"builtins.dict\"\n                and is_subtype(typ.args[0], self.named_type(\"builtins.str\"))\n            )\n            or isinstance(typ, ParamSpecType)\n            or is_subtype(\n                typ,\n                self.chk.named_generic_type(\n                    \"_typeshed.SupportsKeysAndGetItem\",\n                    [self.named_type(\"builtins.str\"), AnyType(TypeOfAny.special_form)],\n                ),\n            )\n            or is_subtype(\n                typ,\n                self.chk.named_generic_type(\n                    \"_typeshed.SupportsKeysAndGetItem\", [UninhabitedType(), UninhabitedType()]\n                ),\n            )\n        )\n\n    def not_ready_callback(self, name: str, context: Context) -> None:\n        \"\"\"Called when we can't infer the type of a variable because it's not ready yet.\n\n        Either defer type checking of the enclosing function to the next\n        pass or report an error.\n        \"\"\"\n        self.chk.handle_cannot_determine_type(name, context)\n\n    def visit_yield_expr(self, e: YieldExpr) -> Type:\n        return_type = self.chk.return_types[-1]\n        expected_item_type = self.chk.get_generator_yield_type(return_type, False)\n        if e.expr is None:\n            if (\n                not isinstance(get_proper_type(expected_item_type), (NoneType, AnyType))\n                and self.chk.in_checked_function()\n            ):\n                self.chk.fail(message_registry.YIELD_VALUE_EXPECTED, e)\n        else:\n            actual_item_type = self.accept(e.expr, expected_item_type)\n            self.chk.check_subtype(\n                actual_item_type,\n                expected_item_type,\n                e,\n                message_registry.INCOMPATIBLE_TYPES_IN_YIELD,\n                \"actual type\",\n                \"expected type\",\n            )\n        return self.chk.get_generator_receive_type(return_type, False)\n\n    def visit_await_expr(self, e: AwaitExpr, allow_none_return: bool = False) -> Type:\n        expected_type = self.type_context[-1]\n        if expected_type is not None:\n            expected_type = self.chk.named_generic_type(\"typing.Awaitable\", [expected_type])\n        actual_type = get_proper_type(self.accept(e.expr, expected_type))\n        if isinstance(actual_type, AnyType):\n            return AnyType(TypeOfAny.from_another_any, source_any=actual_type)\n        ret = self.check_awaitable_expr(\n            actual_type, e, message_registry.INCOMPATIBLE_TYPES_IN_AWAIT\n        )\n        if not allow_none_return and isinstance(get_proper_type(ret), NoneType):\n            self.chk.msg.does_not_return_value(None, e)\n        return ret\n\n    def check_awaitable_expr(\n        self, t: Type, ctx: Context, msg: str | ErrorMessage, ignore_binder: bool = False\n    ) -> Type:\n        \"\"\"Check the argument to `await` and extract the type of value.\n\n        Also used by `async for` and `async with`.\n        \"\"\"\n        if not self.chk.check_subtype(\n            t, self.named_type(\"typing.Awaitable\"), ctx, msg, \"actual type\", \"expected type\"\n        ):\n            return AnyType(TypeOfAny.special_form)\n        else:\n            generator = self.check_method_call_by_name(\"__await__\", t, [], [], ctx)[0]\n            ret_type = self.chk.get_generator_return_type(generator, False)\n            ret_type = get_proper_type(ret_type)\n            if (\n                not ignore_binder\n                and isinstance(ret_type, UninhabitedType)\n                and not ret_type.ambiguous\n            ):\n                self.chk.binder.unreachable()\n            return ret_type\n\n    def visit_yield_from_expr(self, e: YieldFromExpr, allow_none_return: bool = False) -> Type:\n        # NOTE: Whether `yield from` accepts an `async def` decorated\n        # with `@types.coroutine` (or `@asyncio.coroutine`) depends on\n        # whether the generator containing the `yield from` is itself\n        # thus decorated.  But it accepts a generator regardless of\n        # how it's decorated.\n        return_type = self.chk.return_types[-1]\n        # TODO: What should the context for the sub-expression be?\n        # If the containing function has type Generator[X, Y, ...],\n        # the context should be Generator[X, Y, T], where T is the\n        # context of the 'yield from' itself (but it isn't known).\n        subexpr_type = get_proper_type(self.accept(e.expr))\n\n        # Check that the expr is an instance of Iterable and get the type of the iterator produced\n        # by __iter__.\n        if isinstance(subexpr_type, AnyType):\n            iter_type: Type = AnyType(TypeOfAny.from_another_any, source_any=subexpr_type)\n        elif self.chk.type_is_iterable(subexpr_type):\n            if is_async_def(subexpr_type) and not has_coroutine_decorator(return_type):\n                self.chk.msg.yield_from_invalid_operand_type(subexpr_type, e)\n\n            any_type = AnyType(TypeOfAny.special_form)\n            generic_generator_type = self.chk.named_generic_type(\n                \"typing.Generator\", [any_type, any_type, any_type]\n            )\n            generic_generator_type.set_line(e)\n            iter_type, _ = self.check_method_call_by_name(\n                \"__iter__\", subexpr_type, [], [], context=generic_generator_type\n            )\n        else:\n            if not (is_async_def(subexpr_type) and has_coroutine_decorator(return_type)):\n                self.chk.msg.yield_from_invalid_operand_type(subexpr_type, e)\n                iter_type = AnyType(TypeOfAny.from_error)\n            else:\n                iter_type = self.check_awaitable_expr(\n                    subexpr_type, e, message_registry.INCOMPATIBLE_TYPES_IN_YIELD_FROM\n                )\n\n        # Check that the iterator's item type matches the type yielded by the Generator function\n        # containing this `yield from` expression.\n        expected_item_type = self.chk.get_generator_yield_type(return_type, False)\n        actual_item_type = self.chk.get_generator_yield_type(iter_type, False)\n\n        self.chk.check_subtype(\n            actual_item_type,\n            expected_item_type,\n            e,\n            message_registry.INCOMPATIBLE_TYPES_IN_YIELD_FROM,\n            \"actual type\",\n            \"expected type\",\n        )\n\n        # Determine the type of the entire yield from expression.\n        iter_type = get_proper_type(iter_type)\n        expr_type = self.chk.get_generator_return_type(iter_type, is_coroutine=False)\n\n        if not allow_none_return and isinstance(get_proper_type(expr_type), NoneType):\n            self.chk.msg.does_not_return_value(None, e)\n        return expr_type\n\n    def visit_temp_node(self, e: TempNode) -> Type:\n        return e.type\n\n    def visit_type_var_expr(self, e: TypeVarExpr) -> Type:\n        p_default = get_proper_type(e.default)\n        if not (\n            isinstance(p_default, AnyType)\n            and p_default.type_of_any == TypeOfAny.from_omitted_generics\n        ):\n            if not is_subtype(p_default, e.upper_bound):\n                self.chk.fail(\"TypeVar default must be a subtype of the bound type\", e)\n            if e.values and not any(is_same_type(p_default, value) for value in e.values):\n                self.chk.fail(\"TypeVar default must be one of the constraint types\", e)\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_paramspec_expr(self, e: ParamSpecExpr) -> Type:\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_type_var_tuple_expr(self, e: TypeVarTupleExpr) -> Type:\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_newtype_expr(self, e: NewTypeExpr) -> Type:\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_namedtuple_expr(self, e: NamedTupleExpr) -> Type:\n        tuple_type = e.info.tuple_type\n        if tuple_type:\n            if self.chk.options.disallow_any_unimported and has_any_from_unimported_type(\n                tuple_type\n            ):\n                self.msg.unimported_type_becomes_any(\"NamedTuple type\", tuple_type, e)\n            check_for_explicit_any(\n                tuple_type, self.chk.options, self.chk.is_typeshed_stub, self.msg, context=e\n            )\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_enum_call_expr(self, e: EnumCallExpr) -> Type:\n        for name, value in zip(e.items, e.values):\n            if value is not None:\n                typ = self.accept(value)\n                if not isinstance(get_proper_type(typ), AnyType):\n                    var = e.info.names[name].node\n                    if isinstance(var, Var):\n                        # Inline TypeChecker.set_inferred_type(),\n                        # without the lvalue.  (This doesn't really do\n                        # much, since the value attribute is defined\n                        # to have type Any in the typeshed stub.)\n                        var.type = typ\n                        var.is_inferred = True\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_typeddict_expr(self, e: TypedDictExpr) -> Type:\n        return AnyType(TypeOfAny.special_form)\n\n    def visit__promote_expr(self, e: PromoteExpr) -> Type:\n        return e.type\n\n    def visit_star_expr(self, e: StarExpr) -> Type:\n        # TODO: should this ever be called (see e.g. mypyc visitor)?\n        return self.accept(e.expr)\n\n    def object_type(self) -> Instance:\n        \"\"\"Return instance type 'object'.\"\"\"\n        return self.named_type(\"builtins.object\")\n\n    def bool_type(self) -> Instance:\n        \"\"\"Return instance type 'bool'.\"\"\"\n        return self.named_type(\"builtins.bool\")\n\n    @overload\n    def narrow_type_from_binder(self, expr: Expression, known_type: Type) -> Type: ...\n\n    @overload\n    def narrow_type_from_binder(\n        self, expr: Expression, known_type: Type, skip_non_overlapping: bool\n    ) -> Type | None: ...\n\n    def narrow_type_from_binder(\n        self, expr: Expression, known_type: Type, skip_non_overlapping: bool = False\n    ) -> Type | None:\n        \"\"\"Narrow down a known type of expression using information in conditional type binder.\n\n        If 'skip_non_overlapping' is True, return None if the type and restriction are\n        non-overlapping.\n        \"\"\"\n        if literal(expr) >= LITERAL_TYPE:\n            restriction = self.chk.binder.get(expr)\n            # If the current node is deferred, some variables may get Any types that they\n            # otherwise wouldn't have. We don't want to narrow down these since it may\n            # produce invalid inferred Optional[Any] types, at least.\n            if restriction and not (\n                isinstance(get_proper_type(known_type), AnyType) and self.chk.current_node_deferred\n            ):\n                # Note: this call should match the one in narrow_declared_type().\n                if skip_non_overlapping and not is_overlapping_types(known_type, restriction):\n                    return None\n                narrowed = narrow_declared_type(known_type, restriction)\n                if isinstance(get_proper_type(narrowed), UninhabitedType):\n                    # If we hit this case, it means that we can't reliably mark the code as\n                    # unreachable, but the resulting type can't be expressed in type system.\n                    # Falling back to restriction is more intuitive in most cases.\n                    return restriction\n                return narrowed\n        return known_type\n\n    def has_abstract_type_part(self, caller_type: ProperType, callee_type: ProperType) -> bool:\n        # TODO: support other possible types here\n        if isinstance(caller_type, TupleType) and isinstance(callee_type, TupleType):\n            return any(\n                self.has_abstract_type(get_proper_type(caller), get_proper_type(callee))\n                for caller, callee in zip(caller_type.items, callee_type.items)\n            )\n        return self.has_abstract_type(caller_type, callee_type)\n\n    def has_abstract_type(self, caller_type: ProperType, callee_type: ProperType) -> bool:\n        return (\n            isinstance(caller_type, FunctionLike)\n            and isinstance(callee_type, TypeType)\n            and caller_type.is_type_obj()\n            and (caller_type.type_object().is_abstract or caller_type.type_object().is_protocol)\n            and isinstance(callee_type.item, Instance)\n            and (callee_type.item.type.is_abstract or callee_type.item.type.is_protocol)\n            and not self.chk.allow_abstract_call\n        )\n\n    def try_parse_as_type_expression(self, maybe_type_expr: Expression) -> Type | None:\n        \"\"\"Try to parse a value Expression as a type expression.\n        If success then return the type that it spells.\n        If fails then return None.\n\n        A value expression that is parsable as a type expression may be used\n        where a TypeForm is expected to represent the spelled type.\n\n        Unlike SemanticAnalyzer.try_parse_as_type_expression()\n        (used in the earlier SemanticAnalyzer pass), this function can only\n        recognize type expressions which contain no string annotations.\"\"\"\n        if not isinstance(maybe_type_expr, MaybeTypeExpression):\n            return None\n\n        # Check whether has already been parsed as a type expression\n        # by SemanticAnalyzer.try_parse_as_type_expression(),\n        # perhaps containing a string annotation\n        if (\n            isinstance(maybe_type_expr, (StrExpr, IndexExpr, OpExpr))\n            and maybe_type_expr.as_type != NotParsed.VALUE\n        ):\n            return maybe_type_expr.as_type\n\n        # If is potentially a type expression containing a string annotation,\n        # don't try to parse it because there isn't enough information\n        # available to the TypeChecker pass to resolve string annotations\n        if has_str_expression(maybe_type_expr):\n            self.chk.fail(\n                \"TypeForm containing a string annotation cannot be recognized here. \"\n                \"Surround with TypeForm(...) to recognize.\",\n                maybe_type_expr,\n                code=codes.MAYBE_UNRECOGNIZED_STR_TYPEFORM,\n            )\n            return None\n\n        # Collect symbols targeted by NameExprs and MemberExprs,\n        # to be looked up by TypeAnalyser when binding the\n        # UnboundTypes corresponding to those expressions.\n        name_exprs, member_exprs = all_name_and_member_expressions(maybe_type_expr)\n        sym_for_name = {e.name: SymbolTableNode(UNBOUND_IMPORTED, e.node) for e in name_exprs} | {\n            e_name: SymbolTableNode(UNBOUND_IMPORTED, e.node)\n            for e in member_exprs\n            if (e_name := get_member_expr_fullname(e)) is not None\n        }\n\n        chk_sem = mypy.checker.TypeCheckerAsSemanticAnalyzer(self.chk, sym_for_name)\n        tpan = TypeAnalyser(\n            chk_sem,\n            # NOTE: Will never need to lookup type vars in this scope because\n            #       SemanticAnalyzer.try_parse_as_type_expression() will have\n            #       already recognized any type var referenced in a NameExpr.\n            #       String annotations (which may also reference type vars)\n            #       can't be resolved in the TypeChecker pass anyway.\n            TypeVarLikeScope(),  # empty scope\n            self.plugin,\n            self.chk.options,\n            self.chk.tree,\n            self.chk.is_typeshed_stub,\n        )\n\n        try:\n            typ1 = expr_to_unanalyzed_type(\n                maybe_type_expr, self.chk.options, self.chk.is_typeshed_stub\n            )\n            typ2 = typ1.accept(tpan)\n            if chk_sem.did_fail:\n                return None\n            return typ2\n        except TypeTranslationError:\n            return None\n\n\ndef has_any_type(t: Type, ignore_in_type_obj: bool = False) -> bool:\n    \"\"\"Whether t contains an Any type\"\"\"\n    return t.accept(HasAnyType(ignore_in_type_obj))\n\n\nclass HasAnyType(types.BoolTypeQuery):\n    def __init__(self, ignore_in_type_obj: bool) -> None:\n        super().__init__(types.ANY_STRATEGY)\n        self.ignore_in_type_obj = ignore_in_type_obj\n\n    def visit_any(self, t: AnyType) -> bool:\n        return t.type_of_any != TypeOfAny.special_form  # special forms are not real Any types\n\n    def visit_callable_type(self, t: CallableType) -> bool:\n        if self.ignore_in_type_obj and t.is_type_obj():\n            return False\n        return super().visit_callable_type(t)\n\n    def visit_type_var(self, t: TypeVarType) -> bool:\n        default = [t.default] if t.has_default() else []\n        return self.query_types([t.upper_bound, *default] + t.values)\n\n    def visit_param_spec(self, t: ParamSpecType) -> bool:\n        default = [t.default] if t.has_default() else []\n        return self.query_types([t.upper_bound, *default, t.prefix])\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool:\n        default = [t.default] if t.has_default() else []\n        return self.query_types([t.upper_bound, *default])\n\n\ndef has_coroutine_decorator(t: Type) -> bool:\n    \"\"\"Whether t came from a function decorated with `@coroutine`.\"\"\"\n    t = get_proper_type(t)\n    return isinstance(t, Instance) and t.type.fullname == \"typing.AwaitableGenerator\"\n\n\ndef is_async_def(t: Type) -> bool:\n    \"\"\"Whether t came from a function defined using `async def`.\"\"\"\n    # In check_func_def(), when we see a function decorated with\n    # `@typing.coroutine` or `@async.coroutine`, we change the\n    # return type to typing.AwaitableGenerator[...], so that its\n    # type is compatible with either Generator or Awaitable.\n    # But for the check here we need to know whether the original\n    # function (before decoration) was an `async def`.  The\n    # AwaitableGenerator type conveniently preserves the original\n    # type as its 4th parameter (3rd when using 0-origin indexing\n    # :-), so that we can recover that information here.\n    # (We really need to see whether the original, undecorated\n    # function was an `async def`, which is orthogonal to its\n    # decorations.)\n    t = get_proper_type(t)\n    if (\n        isinstance(t, Instance)\n        and t.type.fullname == \"typing.AwaitableGenerator\"\n        and len(t.args) >= 4\n    ):\n        t = get_proper_type(t.args[3])\n    return isinstance(t, Instance) and t.type.fullname == \"typing.Coroutine\"\n\n\ndef is_non_empty_tuple(t: Type) -> bool:\n    t = get_proper_type(t)\n    return isinstance(t, TupleType) and bool(t.items)\n\n\ndef is_duplicate_mapping(\n    mapping: list[int], actual_types: list[Type], actual_kinds: list[ArgKind]\n) -> bool:\n    return (\n        len(mapping) > 1\n        # Multiple actuals can map to the same formal if they both come from\n        # varargs (*args and **kwargs); in this case at runtime it is possible\n        # that here are no duplicates. We need to allow this, as the convention\n        # f(..., *args, **kwargs) is common enough.\n        and not (\n            len(mapping) == 2\n            and actual_kinds[mapping[0]] == nodes.ARG_STAR\n            and actual_kinds[mapping[1]] == nodes.ARG_STAR2\n        )\n        # Multiple actuals can map to the same formal if there are multiple\n        # **kwargs which cannot be mapped with certainty (non-TypedDict\n        # **kwargs).\n        and not all(\n            actual_kinds[m] == nodes.ARG_STAR2\n            and not isinstance(get_proper_type(actual_types[m]), TypedDictType)\n            for m in mapping\n        )\n    )\n\n\ndef replace_callable_return_type(c: CallableType, new_ret_type: Type) -> CallableType:\n    \"\"\"Return a copy of a callable type with a different return type.\"\"\"\n    return c.copy_modified(ret_type=new_ret_type)\n\n\nclass ArgInferSecondPassQuery(types.BoolTypeQuery):\n    \"\"\"Query whether an argument type should be inferred in the second pass.\n\n    The result is True if the type has a type variable in a callable return\n    type anywhere. For example, the result for Callable[[], T] is True if t is\n    a type variable.\n    \"\"\"\n\n    def __init__(self) -> None:\n        super().__init__(types.ANY_STRATEGY)\n\n    def visit_callable_type(self, t: CallableType) -> bool:\n        # TODO: we need to check only for type variables of original callable.\n        return self.query_types(t.arg_types) or has_type_vars(t)\n\n\ndef has_erased_component(t: Type | None) -> bool:\n    return t is not None and t.accept(HasErasedComponentsQuery())\n\n\nclass HasErasedComponentsQuery(types.BoolTypeQuery):\n    \"\"\"Visitor for querying whether a type has an erased component.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__(types.ANY_STRATEGY)\n\n    def visit_erased_type(self, t: ErasedType) -> bool:\n        return True\n\n\ndef has_uninhabited_component(t: Type | None) -> bool:\n    return t is not None and t.accept(HasUninhabitedComponentsQuery())\n\n\nclass HasUninhabitedComponentsQuery(types.BoolTypeQuery):\n    \"\"\"Visitor for querying whether a type has an UninhabitedType component.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__(types.ANY_STRATEGY)\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> bool:\n        return True\n\n\ndef has_ambiguous_uninhabited_component(t: Type) -> bool:\n    return t.accept(HasAmbiguousUninhabitedComponentsQuery())\n\n\nclass HasAmbiguousUninhabitedComponentsQuery(types.BoolTypeQuery):\n    \"\"\"Visitor for querying whether a type has an ambiguous UninhabitedType component.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__(types.ANY_STRATEGY)\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> bool:\n        return t.ambiguous\n\n\ndef arg_approximate_similarity(actual: Type, formal: Type) -> bool:\n    \"\"\"Return if caller argument (actual) is roughly compatible with signature arg (formal).\n\n    This function is deliberately loose and will report two types are similar\n    as long as their \"shapes\" are plausibly the same.\n\n    This is useful when we're doing error reporting: for example, if we're trying\n    to select an overload alternative and there's no exact match, we can use\n    this function to help us identify which alternative the user might have\n    *meant* to match.\n    \"\"\"\n    actual = get_proper_type(actual)\n    formal = get_proper_type(formal)\n\n    # Erase typevars: we'll consider them all to have the same \"shape\".\n    if isinstance(actual, TypeVarType):\n        actual = erase_to_union_or_bound(actual)\n    if isinstance(formal, TypeVarType):\n        formal = erase_to_union_or_bound(formal)\n\n    # Callable or Type[...]-ish types\n    def is_typetype_like(typ: ProperType) -> bool:\n        return (\n            isinstance(typ, TypeType)\n            or (isinstance(typ, FunctionLike) and typ.is_type_obj())\n            or (isinstance(typ, Instance) and typ.type.fullname == \"builtins.type\")\n        )\n\n    if isinstance(formal, CallableType):\n        if isinstance(actual, (CallableType, Overloaded, TypeType)):\n            return True\n    if is_typetype_like(actual) and is_typetype_like(formal):\n        return True\n\n    # Unions\n    if isinstance(actual, UnionType):\n        return any(arg_approximate_similarity(item, formal) for item in actual.relevant_items())\n    if isinstance(formal, UnionType):\n        return any(arg_approximate_similarity(actual, item) for item in formal.relevant_items())\n\n    # TypedDicts\n    if isinstance(actual, TypedDictType):\n        if isinstance(formal, TypedDictType):\n            return True\n        return arg_approximate_similarity(actual.fallback, formal)\n\n    # Instances\n    # For instances, we mostly defer to the existing is_subtype check.\n    if isinstance(formal, Instance):\n        if isinstance(actual, CallableType):\n            actual = actual.fallback\n        if isinstance(actual, Overloaded):\n            actual = actual.items[0].fallback\n        if isinstance(actual, TupleType):\n            actual = tuple_fallback(actual)\n        if isinstance(actual, Instance) and formal.type in actual.type.mro:\n            # Try performing a quick check as an optimization\n            return True\n\n    # Fall back to a standard subtype check for the remaining kinds of type.\n    return is_subtype(erasetype.erase_type(actual), erasetype.erase_type(formal))\n\n\ndef any_causes_overload_ambiguity(\n    items: list[CallableType],\n    return_types: list[Type],\n    arg_types: list[Type],\n    arg_kinds: list[ArgKind],\n    arg_names: Sequence[str | None] | None,\n) -> bool:\n    \"\"\"May an argument containing 'Any' cause ambiguous result type on call to overloaded function?\n\n    Note that this sometimes returns True even if there is no ambiguity, since a correct\n    implementation would be complex (and the call would be imprecisely typed due to Any\n    types anyway).\n\n    Args:\n        items: Overload items matching the actual arguments\n        arg_types: Actual argument types\n        arg_kinds: Actual argument kinds\n        arg_names: Actual argument names\n    \"\"\"\n    if all_same_types(return_types):\n        return False\n\n    actual_to_formal = [\n        map_formals_to_actuals(\n            arg_kinds, arg_names, item.arg_kinds, item.arg_names, lambda i: arg_types[i]\n        )\n        for item in items\n    ]\n\n    for arg_idx, arg_type in enumerate(arg_types):\n        # We ignore Anys in type object callables as ambiguity\n        # creators, since that can lead to falsely claiming ambiguity\n        # for overloads between Type and Callable.\n        if has_any_type(arg_type, ignore_in_type_obj=True):\n            matching_formals_unfiltered = [\n                (item_idx, lookup[arg_idx])\n                for item_idx, lookup in enumerate(actual_to_formal)\n                if lookup[arg_idx]\n            ]\n\n            matching_returns = []\n            matching_formals = []\n            for item_idx, formals in matching_formals_unfiltered:\n                matched_callable = items[item_idx]\n                matching_returns.append(matched_callable.ret_type)\n\n                # Note: if an actual maps to multiple formals of differing types within\n                # a single callable, then we know at least one of those formals must be\n                # a different type then the formal(s) in some other callable.\n                # So it's safe to just append everything to the same list.\n                for formal in formals:\n                    matching_formals.append(matched_callable.arg_types[formal])\n            if not all_same_types(matching_formals) and not all_same_types(matching_returns):\n                # Any maps to multiple different types, and the return types of these items differ.\n                return True\n    return False\n\n\ndef all_same_types(types: list[Type]) -> bool:\n    if not types:\n        return True\n    return all(is_same_type(t, types[0]) for t in types[1:])\n\n\ndef merge_typevars_in_callables_by_name(\n    callables: Sequence[CallableType],\n) -> tuple[list[CallableType], list[TypeVarType]]:\n    \"\"\"Takes all the typevars present in the callables and 'combines' the ones with the same name.\n\n    For example, suppose we have two callables with signatures \"f(x: T, y: S) -> T\" and\n    \"f(x: List[Tuple[T, S]]) -> Tuple[T, S]\". Both callables use typevars named \"T\" and\n    \"S\", but we treat them as distinct, unrelated typevars. (E.g. they could both have\n    distinct ids.)\n\n    If we pass in both callables into this function, it returns a list containing two\n    new callables that are identical in signature, but use the same underlying TypeVarType\n    for T and S.\n\n    This is useful if we want to take the output lists and \"merge\" them into one callable\n    in some way -- for example, when unioning together overloads.\n\n    Returns both the new list of callables and a list of all distinct TypeVarType objects used.\n    \"\"\"\n    output: list[CallableType] = []\n    unique_typevars: dict[str, TypeVarType] = {}\n    variables: list[TypeVarType] = []\n\n    for target in callables:\n        if target.is_generic():\n            target = freshen_function_type_vars(target)\n\n            rename = {}  # Dict[TypeVarId, TypeVar]\n            for tv in target.variables:\n                name = tv.fullname\n                if name not in unique_typevars:\n                    # TODO: support ParamSpecType and TypeVarTuple.\n                    if isinstance(tv, (ParamSpecType, TypeVarTupleType)):\n                        continue\n                    assert isinstance(tv, TypeVarType)\n                    unique_typevars[name] = tv\n                    variables.append(tv)\n                rename[tv.id] = unique_typevars[name]\n\n            target = expand_type(target, rename)\n        output.append(target)\n\n    return output, variables\n\n\ndef try_getting_literal(typ: Type) -> ProperType:\n    \"\"\"If possible, get a more precise literal type for a given type.\"\"\"\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance) and typ.last_known_value is not None:\n        return typ.last_known_value\n    return typ\n\n\ndef is_expr_literal_type(node: Expression) -> bool:\n    \"\"\"Returns 'true' if the given node is a Literal\"\"\"\n    if isinstance(node, IndexExpr):\n        base = node.base\n        return isinstance(base, RefExpr) and base.fullname in LITERAL_TYPE_NAMES\n    if isinstance(node, NameExpr):\n        underlying = node.node\n        return isinstance(underlying, TypeAlias) and isinstance(\n            get_proper_type(underlying.target), LiteralType\n        )\n    return False\n\n\ndef has_bytes_component(typ: Type) -> bool:\n    \"\"\"Is this one of builtin byte types, or a union that contains it?\"\"\"\n    typ = get_proper_type(typ)\n    byte_types = {\"builtins.bytes\", \"builtins.bytearray\"}\n    if isinstance(typ, UnionType):\n        return any(has_bytes_component(t) for t in typ.items)\n    if isinstance(typ, Instance) and typ.type.fullname in byte_types:\n        return True\n    return False\n\n\ndef type_info_from_type(typ: Type) -> TypeInfo | None:\n    \"\"\"Gets the TypeInfo for a type, indirecting through things like type variables and tuples.\"\"\"\n    typ = get_proper_type(typ)\n    if isinstance(typ, FunctionLike) and typ.is_type_obj():\n        return typ.type_object()\n    if isinstance(typ, TypeType):\n        typ = typ.item\n    if isinstance(typ, TypeVarType):\n        typ = get_proper_type(typ.upper_bound)\n    if isinstance(typ, TupleType):\n        typ = tuple_fallback(typ)\n    if isinstance(typ, Instance):\n        return typ.type\n\n    # A complicated type. Too tricky, give up.\n    # TODO: Do something more clever here.\n    return None\n\n\ndef is_operator_method(fullname: str | None) -> bool:\n    if not fullname:\n        return False\n    short_name = fullname.split(\".\")[-1]\n    return (\n        short_name in operators.op_methods.values()\n        or short_name in operators.reverse_op_methods.values()\n        or short_name in operators.unary_op_methods.values()\n    )\n\n\ndef get_partial_instance_type(t: Type | None) -> PartialType | None:\n    if t is None or not isinstance(t, PartialType) or t.type is None:\n        return None\n    return t\n\n\ndef is_type_type_context(context: Type | None) -> bool:\n    context = get_proper_type(context)\n    if isinstance(context, TypeType):\n        return True\n    if isinstance(context, UnionType):\n        return any(is_type_type_context(item) for item in context.items)\n    return False\n"
  },
  {
    "path": "mypy/checkmember.py",
    "content": "\"\"\"Type checking of attribute access\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable, Sequence\nfrom typing import TypeVar, cast\n\nfrom mypy import message_registry, state\nfrom mypy.checker_shared import TypeCheckerSharedApi\nfrom mypy.erasetype import erase_typevars\nfrom mypy.expandtype import (\n    expand_self_type,\n    expand_type_by_instance,\n    freshen_all_functions_type_vars,\n)\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.meet import is_overlapping_types\nfrom mypy.messages import MessageBuilder\nfrom mypy.nodes import (\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    EXCLUDED_ENUM_ATTRIBUTES,\n    SYMBOL_FUNCBASE_TYPES,\n    Context,\n    Decorator,\n    Expression,\n    FuncBase,\n    FuncDef,\n    IndexExpr,\n    MypyFile,\n    NameExpr,\n    OverloadedFuncDef,\n    SymbolTable,\n    TempNode,\n    TypeAlias,\n    TypeInfo,\n    TypeVarLikeExpr,\n    Var,\n    is_final_node,\n)\nfrom mypy.plugin import AttributeContext\nfrom mypy.subtypes import is_subtype\nfrom mypy.typeops import (\n    bind_self,\n    erase_to_bound,\n    freeze_all_type_vars,\n    function_type,\n    get_all_type_vars,\n    make_simplified_union,\n    supported_self_type,\n    tuple_fallback,\n)\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    DeletedType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeOfAny,\n    TypeType,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UninhabitedType,\n    UnionType,\n    get_proper_type,\n)\n\n\nclass MemberContext:\n    \"\"\"Information and objects needed to type check attribute access.\n\n    Look at the docstring of analyze_member_access for more information.\n    \"\"\"\n\n    def __init__(\n        self,\n        *,\n        is_lvalue: bool,\n        is_super: bool,\n        is_operator: bool,\n        original_type: Type,\n        context: Context,\n        chk: TypeCheckerSharedApi,\n        self_type: Type | None = None,\n        module_symbol_table: SymbolTable | None = None,\n        no_deferral: bool = False,\n        is_self: bool = False,\n        rvalue: Expression | None = None,\n        suppress_errors: bool = False,\n        preserve_type_var_ids: bool = False,\n    ) -> None:\n        self.is_lvalue = is_lvalue\n        self.is_super = is_super\n        self.is_operator = is_operator\n        self.original_type = original_type\n        self.self_type = self_type or original_type\n        self.context = context  # Error context\n        self.chk = chk\n        self.msg = chk.msg\n        self.module_symbol_table = module_symbol_table\n        self.no_deferral = no_deferral\n        self.is_self = is_self\n        if rvalue is not None:\n            assert is_lvalue\n        self.rvalue = rvalue\n        self.suppress_errors = suppress_errors\n        # This attribute is only used to preserve old protocol member access logic.\n        # It is needed to avoid infinite recursion in cases involving self-referential\n        # generic methods, see find_member() for details. Do not use for other purposes!\n        self.preserve_type_var_ids = preserve_type_var_ids\n\n    def named_type(self, name: str) -> Instance:\n        return self.chk.named_type(name)\n\n    def not_ready_callback(self, name: str, context: Context) -> None:\n        self.chk.handle_cannot_determine_type(name, context)\n\n    def fail(self, msg: str) -> None:\n        if not self.suppress_errors:\n            self.msg.fail(msg, self.context)\n\n    def copy_modified(\n        self,\n        *,\n        self_type: Type | None = None,\n        is_lvalue: bool | None = None,\n        original_type: Type | None = None,\n    ) -> MemberContext:\n        mx = MemberContext(\n            is_lvalue=self.is_lvalue,\n            is_super=self.is_super,\n            is_operator=self.is_operator,\n            original_type=self.original_type,\n            context=self.context,\n            chk=self.chk,\n            self_type=self.self_type,\n            module_symbol_table=self.module_symbol_table,\n            no_deferral=self.no_deferral,\n            rvalue=self.rvalue,\n            suppress_errors=self.suppress_errors,\n            preserve_type_var_ids=self.preserve_type_var_ids,\n        )\n        if self_type is not None:\n            mx.self_type = self_type\n        if is_lvalue is not None:\n            mx.is_lvalue = is_lvalue\n        if original_type is not None:\n            mx.original_type = original_type\n        return mx\n\n\ndef analyze_member_access(\n    name: str,\n    typ: Type,\n    context: Context,\n    *,\n    is_lvalue: bool,\n    is_super: bool,\n    is_operator: bool,\n    original_type: Type,\n    chk: TypeCheckerSharedApi,\n    override_info: TypeInfo | None = None,\n    in_literal_context: bool = False,\n    self_type: Type | None = None,\n    module_symbol_table: SymbolTable | None = None,\n    no_deferral: bool = False,\n    is_self: bool = False,\n    rvalue: Expression | None = None,\n    suppress_errors: bool = False,\n) -> Type:\n    \"\"\"Return the type of attribute 'name' of 'typ'.\n\n    The actual implementation is in '_analyze_member_access' and this docstring\n    also applies to it.\n\n    This is a general operation that supports various different variations:\n\n      1. lvalue or non-lvalue access (setter or getter access)\n      2. supertype access when using super() (is_super == True and\n         'override_info' should refer to the supertype)\n\n    'original_type' is the most precise inferred or declared type of the base object\n    that we have available. When looking for an attribute of 'typ', we may perform\n    recursive calls targeting the fallback type, and 'typ' may become some supertype\n    of 'original_type'. 'original_type' is always preserved as the 'typ' type used in\n    the initial, non-recursive call. The 'self_type' is a component of 'original_type'\n    to which generic self should be bound (a narrower type that has a fallback to instance).\n    Currently, this is used only for union types.\n\n    'module_symbol_table' is passed to this function if 'typ' is actually a module,\n    and we want to keep track of the available attributes of the module (since they\n    are not available via the type object directly)\n\n    'rvalue' can be provided optionally to infer better setter type when is_lvalue is True,\n    most notably this helps for descriptors with overloaded __set__() method.\n\n    'suppress_errors' will skip any logic that is only needed to generate error messages.\n    Note that this more of a performance optimization, one should not rely on this to not\n    show any messages, as some may be show e.g. by callbacks called here,\n    use msg.filter_errors(), if needed.\n    \"\"\"\n    mx = MemberContext(\n        is_lvalue=is_lvalue,\n        is_super=is_super,\n        is_operator=is_operator,\n        original_type=original_type,\n        context=context,\n        chk=chk,\n        self_type=self_type,\n        module_symbol_table=module_symbol_table,\n        no_deferral=no_deferral,\n        is_self=is_self,\n        rvalue=rvalue,\n        suppress_errors=suppress_errors,\n    )\n    result = _analyze_member_access(name, typ, mx, override_info)\n    possible_literal = get_proper_type(result)\n    if (\n        in_literal_context\n        and isinstance(possible_literal, Instance)\n        and possible_literal.last_known_value is not None\n    ):\n        return possible_literal.last_known_value\n    else:\n        return result\n\n\ndef _analyze_member_access(\n    name: str, typ: Type, mx: MemberContext, override_info: TypeInfo | None = None\n) -> Type:\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        return analyze_instance_member_access(name, typ, mx, override_info)\n    elif isinstance(typ, AnyType):\n        # The base object has dynamic type.\n        return AnyType(TypeOfAny.from_another_any, source_any=typ)\n    elif isinstance(typ, UnionType):\n        return analyze_union_member_access(name, typ, mx)\n    elif isinstance(typ, FunctionLike) and typ.is_type_obj():\n        return analyze_type_callable_member_access(name, typ, mx)\n    elif isinstance(typ, TypeType):\n        return analyze_type_type_member_access(name, typ, mx, override_info)\n    elif isinstance(typ, TupleType):\n        # Actually look up from the fallback instance type.\n        return _analyze_member_access(name, tuple_fallback(typ), mx, override_info)\n    elif isinstance(typ, (LiteralType, FunctionLike)):\n        # Actually look up from the fallback instance type.\n        return _analyze_member_access(name, typ.fallback, mx, override_info)\n    elif isinstance(typ, TypedDictType):\n        return analyze_typeddict_access(name, typ, mx, override_info)\n    elif isinstance(typ, NoneType):\n        return analyze_none_member_access(name, typ, mx)\n    elif isinstance(typ, TypeVarLikeType):\n        if isinstance(typ, TypeVarType) and typ.values:\n            return _analyze_member_access(\n                name, make_simplified_union(typ.values), mx, override_info\n            )\n        return _analyze_member_access(name, typ.upper_bound, mx, override_info)\n    elif isinstance(typ, DeletedType):\n        if not mx.suppress_errors:\n            mx.msg.deleted_as_rvalue(typ, mx.context)\n        return AnyType(TypeOfAny.from_error)\n    elif isinstance(typ, UninhabitedType):\n        attr_type = UninhabitedType()\n        attr_type.ambiguous = typ.ambiguous\n        return attr_type\n    return report_missing_attribute(mx.original_type, typ, name, mx)\n\n\ndef may_be_awaitable_attribute(\n    name: str, typ: Type, mx: MemberContext, override_info: TypeInfo | None = None\n) -> bool:\n    \"\"\"Check if the given type has the attribute when awaited.\"\"\"\n    if mx.chk.checking_missing_await:\n        # Avoid infinite recursion.\n        return False\n    with mx.chk.checking_await_set(), mx.msg.filter_errors() as local_errors:\n        aw_type = mx.chk.get_precise_awaitable_type(typ, local_errors)\n        if aw_type is None:\n            return False\n        _ = _analyze_member_access(\n            name, aw_type, mx.copy_modified(self_type=aw_type), override_info\n        )\n        return not local_errors.has_new_errors()\n\n\ndef report_missing_attribute(\n    original_type: Type,\n    typ: Type,\n    name: str,\n    mx: MemberContext,\n    override_info: TypeInfo | None = None,\n) -> Type:\n    if mx.suppress_errors:\n        return AnyType(TypeOfAny.from_error)\n    error_code = mx.msg.has_no_attr(original_type, typ, name, mx.context, mx.module_symbol_table)\n    if not mx.msg.prefer_simple_messages():\n        if may_be_awaitable_attribute(name, typ, mx, override_info):\n            mx.msg.possible_missing_await(mx.context, error_code)\n    return AnyType(TypeOfAny.from_error)\n\n\n# The several functions that follow implement analyze_member_access for various\n# types and aren't documented individually.\n\n\ndef analyze_instance_member_access(\n    name: str, typ: Instance, mx: MemberContext, override_info: TypeInfo | None\n) -> Type:\n    info = typ.type\n    if override_info:\n        info = override_info\n\n    method = info.get_method(name)\n\n    if name == \"__init__\" and not mx.is_super and not info.is_final:\n        if not method or not method.is_final:\n            # Accessing __init__ in statically typed code would compromise\n            # type safety unless used via super() or the method/class is final.\n            mx.fail(message_registry.CANNOT_ACCESS_INIT)\n            return AnyType(TypeOfAny.from_error)\n\n    # The base object has an instance type.\n\n    if (\n        state.find_occurrences\n        and info.name == state.find_occurrences[0]\n        and name == state.find_occurrences[1]\n        and not mx.suppress_errors\n    ):\n        mx.msg.note(\"Occurrence of '{}.{}'\".format(*state.find_occurrences), mx.context)\n\n    # Look up the member. First look up the method dictionary.\n    if method and not isinstance(method, Decorator):\n        if mx.is_super and not mx.suppress_errors:\n            validate_super_call(method, mx)\n\n        if method.is_property:\n            assert isinstance(method, OverloadedFuncDef)\n            getter = method.items[0]\n            assert isinstance(getter, Decorator)\n            if mx.is_lvalue and getter.var.is_settable_property:\n                mx.chk.warn_deprecated(method.setter, mx.context)\n            return analyze_var(name, getter.var, typ, mx)\n\n        if mx.is_lvalue and not mx.suppress_errors:\n            mx.msg.cant_assign_to_method(mx.context)\n        if not isinstance(method, OverloadedFuncDef):\n            signature = function_type(method, mx.named_type(\"builtins.function\"))\n        else:\n            if method.type is None:\n                # Overloads may be not ready if they are decorated. Handle this in same\n                # manner as we would handle a regular decorated function: defer if possible.\n                if not mx.no_deferral and method.items:\n                    mx.not_ready_callback(method.name, mx.context)\n                return AnyType(TypeOfAny.special_form)\n            assert isinstance(method.type, Overloaded)\n            signature = method.type\n        if not mx.preserve_type_var_ids:\n            signature = freshen_all_functions_type_vars(signature)\n        if not method.is_static:\n            if isinstance(method, (FuncDef, OverloadedFuncDef)) and method.is_trivial_self:\n                signature = bind_self_fast(signature, mx.self_type)\n            else:\n                signature = check_self_arg(\n                    signature, mx.self_type, method.is_class, mx.context, name, mx.msg\n                )\n                signature = bind_self(signature, mx.self_type, is_classmethod=method.is_class)\n        typ = map_instance_to_supertype(typ, method.info)\n        member_type = expand_type_by_instance(signature, typ)\n        freeze_all_type_vars(member_type)\n        return member_type\n    else:\n        # Not a method.\n        return analyze_member_var_access(name, typ, info, mx)\n\n\ndef validate_super_call(node: FuncBase, mx: MemberContext) -> None:\n    unsafe_super = False\n    if isinstance(node, FuncDef) and node.is_trivial_body:\n        unsafe_super = True\n    elif isinstance(node, OverloadedFuncDef):\n        if node.impl:\n            impl = node.impl if isinstance(node.impl, FuncDef) else node.impl.func\n            unsafe_super = impl.is_trivial_body\n        elif not node.is_property and node.items:\n            assert isinstance(node.items[0], Decorator)\n            unsafe_super = node.items[0].func.is_trivial_body\n    if unsafe_super:\n        mx.msg.unsafe_super(node.name, node.info.name, mx.context)\n\n\ndef analyze_type_callable_member_access(name: str, typ: FunctionLike, mx: MemberContext) -> Type:\n    # Class attribute.\n    # TODO super?\n    ret_type = typ.items[0].ret_type\n    assert isinstance(ret_type, ProperType)\n    if isinstance(ret_type, TupleType):\n        ret_type = tuple_fallback(ret_type)\n    if isinstance(ret_type, TypedDictType):\n        ret_type = ret_type.fallback\n    if isinstance(ret_type, LiteralType):\n        ret_type = ret_type.fallback\n    if isinstance(ret_type, Instance):\n        if not mx.is_operator:\n            # When Python sees an operator (eg `3 == 4`), it automatically translates that\n            # into something like `int.__eq__(3, 4)` instead of `(3).__eq__(4)` as an\n            # optimization.\n            #\n            # While it normally it doesn't matter which of the two versions are used, it\n            # does cause inconsistencies when working with classes. For example, translating\n            # `int == int` to `int.__eq__(int)` would not work since `int.__eq__` is meant to\n            # compare two int _instances_. What we really want is `type(int).__eq__`, which\n            # is meant to compare two types or classes.\n            #\n            # This check makes sure that when we encounter an operator, we skip looking up\n            # the corresponding method in the current instance to avoid this edge case.\n            # See https://github.com/python/mypy/pull/1787 for more info.\n            # TODO: do not rely on same type variables being present in all constructor overloads.\n            result = analyze_class_attribute_access(\n                ret_type, name, mx, original_vars=typ.items[0].variables, mcs_fallback=typ.fallback\n            )\n            if result:\n                return result\n        # Look up from the 'type' type.\n        return _analyze_member_access(name, typ.fallback, mx)\n    else:\n        assert False, f\"Unexpected type {ret_type!r}\"\n\n\ndef analyze_type_type_member_access(\n    name: str, typ: TypeType, mx: MemberContext, override_info: TypeInfo | None\n) -> Type:\n    # Similar to analyze_type_callable_attribute_access.\n    item = None\n    fallback = mx.named_type(\"builtins.type\")\n    if isinstance(typ.item, Instance):\n        item = typ.item\n    elif isinstance(typ.item, AnyType):\n        with mx.msg.filter_errors():\n            return _analyze_member_access(name, fallback, mx, override_info)\n    elif isinstance(typ.item, TypeVarType):\n        upper_bound = get_proper_type(typ.item.upper_bound)\n        if isinstance(upper_bound, Instance):\n            item = upper_bound\n        elif isinstance(upper_bound, UnionType):\n            return _analyze_member_access(\n                name,\n                TypeType.make_normalized(upper_bound, line=typ.line, column=typ.column),\n                mx,\n                override_info,\n            )\n        elif isinstance(upper_bound, TupleType):\n            item = tuple_fallback(upper_bound)\n        elif isinstance(upper_bound, AnyType):\n            with mx.msg.filter_errors():\n                return _analyze_member_access(name, fallback, mx, override_info)\n    elif isinstance(typ.item, TupleType):\n        item = tuple_fallback(typ.item)\n    elif isinstance(typ.item, FunctionLike) and typ.item.is_type_obj():\n        item = typ.item.fallback\n    elif isinstance(typ.item, TypeType):\n        # Access member on metaclass object via Type[Type[C]]\n        if isinstance(typ.item.item, Instance):\n            item = typ.item.item.type.metaclass_type\n    ignore_messages = False\n\n    if item is not None:\n        fallback = item.type.metaclass_type or fallback\n\n    if item and not mx.is_operator:\n        # See comment above for why operators are skipped\n        result = analyze_class_attribute_access(\n            item, name, mx, mcs_fallback=fallback, override_info=override_info\n        )\n        if result:\n            if not (isinstance(get_proper_type(result), AnyType) and item.type.fallback_to_any):\n                return result\n            else:\n                # We don't want errors on metaclass lookup for classes with Any fallback\n                ignore_messages = True\n\n    with mx.msg.filter_errors(filter_errors=ignore_messages):\n        return _analyze_member_access(name, fallback, mx, override_info)\n\n\ndef analyze_union_member_access(name: str, typ: UnionType, mx: MemberContext) -> Type:\n    with mx.msg.disable_type_names():\n        results = []\n        for subtype in typ.relevant_items():\n            # Self types should be bound to every individual item of a union.\n            item_mx = mx.copy_modified(self_type=subtype)\n            results.append(_analyze_member_access(name, subtype, item_mx))\n    return make_simplified_union(results)\n\n\ndef analyze_none_member_access(name: str, typ: NoneType, mx: MemberContext) -> Type:\n    if name == \"__bool__\":\n        literal_false = LiteralType(False, fallback=mx.named_type(\"builtins.bool\"))\n        return CallableType(\n            arg_types=[],\n            arg_kinds=[],\n            arg_names=[],\n            ret_type=literal_false,\n            fallback=mx.named_type(\"builtins.function\"),\n        )\n    else:\n        return _analyze_member_access(name, mx.named_type(\"builtins.object\"), mx)\n\n\ndef analyze_member_var_access(\n    name: str, itype: Instance, info: TypeInfo, mx: MemberContext\n) -> Type:\n    \"\"\"Analyse attribute access that does not target a method.\n\n    This is logically part of analyze_member_access and the arguments are similar.\n\n    original_type is the type of E in the expression E.var\n    \"\"\"\n    # It was not a method. Try looking up a variable.\n    node = info.get(name)\n    v = node.node if node else None\n\n    mx.chk.warn_deprecated(v, mx.context)\n\n    vv = v\n    is_trivial_self = False\n    if isinstance(vv, Decorator):\n        # The associated Var node of a decorator contains the type.\n        v = vv.var\n        is_trivial_self = vv.func.is_trivial_self and not vv.decorators\n        if mx.is_super and not mx.suppress_errors:\n            validate_super_call(vv.func, mx)\n    if isinstance(v, FuncDef):\n        assert False, \"Did not expect a function\"\n    if isinstance(v, MypyFile):\n        # Special case: accessing module on instances is allowed, but will not\n        # be recorded by semantic analyzer.\n        mx.chk.module_refs.add(v.fullname)\n\n    if isinstance(vv, (TypeInfo, TypeAlias, MypyFile, TypeVarLikeExpr)):\n        # If the associated variable is a TypeInfo synthesize a Var node for\n        # the purposes of type checking.  This enables us to type check things\n        # like accessing class attributes on an inner class. Similar we allow\n        # using qualified type aliases in runtime context. For example:\n        #     class C:\n        #         A = List[int]\n        #     x = C.A() <- this is OK\n        typ = mx.chk.expr_checker.analyze_static_reference(vv, mx.context, mx.is_lvalue)\n        v = Var(name, type=typ)\n        v.info = info\n\n    if isinstance(v, Var):\n        implicit = info[name].implicit\n\n        # An assignment to final attribute is always an error,\n        # independently of types.\n        if mx.is_lvalue and not mx.chk.get_final_context():\n            check_final_member(name, info, mx.msg, mx.context)\n\n        return analyze_var(name, v, itype, mx, implicit=implicit, is_trivial_self=is_trivial_self)\n    elif (\n        not v\n        and name not in [\"__getattr__\", \"__setattr__\", \"__getattribute__\"]\n        and not mx.is_operator\n        and mx.module_symbol_table is None\n    ):\n        # Above we skip ModuleType.__getattr__ etc. if we have a\n        # module symbol table, since the symbol table allows precise\n        # checking.\n        if not mx.is_lvalue:\n            for method_name in (\"__getattribute__\", \"__getattr__\"):\n                method = info.get_method(method_name)\n\n                # __getattribute__ is defined on builtins.object and returns Any, so without\n                # the guard this search will always find object.__getattribute__ and conclude\n                # that the attribute exists\n                if method and method.info.fullname != \"builtins.object\":\n                    bound_method = analyze_decorator_or_funcbase_access(\n                        defn=method, itype=itype, name=method_name, mx=mx\n                    )\n                    typ = map_instance_to_supertype(itype, method.info)\n                    getattr_type = get_proper_type(expand_type_by_instance(bound_method, typ))\n                    if isinstance(getattr_type, CallableType):\n                        result = getattr_type.ret_type\n                    else:\n                        result = getattr_type\n\n                    # Call the attribute hook before returning.\n                    fullname = f\"{method.info.fullname}.{name}\"\n                    hook = mx.chk.plugin.get_attribute_hook(fullname)\n                    if hook:\n                        result = hook(\n                            AttributeContext(\n                                get_proper_type(mx.original_type),\n                                result,\n                                mx.is_lvalue,\n                                mx.context,\n                                mx.chk,\n                            )\n                        )\n                    return result\n        else:\n            setattr_meth = info.get_method(\"__setattr__\")\n            if setattr_meth and setattr_meth.info.fullname != \"builtins.object\":\n                bound_type = analyze_decorator_or_funcbase_access(\n                    defn=setattr_meth,\n                    itype=itype,\n                    name=\"__setattr__\",\n                    mx=mx.copy_modified(is_lvalue=False),\n                )\n                typ = map_instance_to_supertype(itype, setattr_meth.info)\n                setattr_type = get_proper_type(expand_type_by_instance(bound_type, typ))\n                if isinstance(setattr_type, CallableType) and len(setattr_type.arg_types) > 0:\n                    return setattr_type.arg_types[-1]\n\n    if itype.type.fallback_to_any:\n        return AnyType(TypeOfAny.special_form)\n\n    # Could not find the member.\n    if itype.extra_attrs and name in itype.extra_attrs.attrs:\n        # For modules use direct symbol table lookup.\n        if not itype.extra_attrs.mod_name:\n            return itype.extra_attrs.attrs[name]\n\n    if mx.is_super and not mx.suppress_errors:\n        mx.msg.undefined_in_superclass(name, mx.context)\n        return AnyType(TypeOfAny.from_error)\n    else:\n        ret = report_missing_attribute(mx.original_type, itype, name, mx)\n        # Avoid paying double jeopardy if we can't find the member due to --no-implicit-reexport\n        if (\n            mx.module_symbol_table is not None\n            and name in mx.module_symbol_table\n            and not mx.module_symbol_table[name].module_public\n        ):\n            v = mx.module_symbol_table[name].node\n            e = NameExpr(name)\n            e.set_line(mx.context)\n            e.node = v\n            return mx.chk.expr_checker.analyze_ref_expr(e, lvalue=mx.is_lvalue)\n        return ret\n\n\ndef check_final_member(name: str, info: TypeInfo, msg: MessageBuilder, ctx: Context) -> None:\n    \"\"\"Give an error if the name being assigned was declared as final.\"\"\"\n    for base in info.mro:\n        sym = base.names.get(name)\n        if sym and is_final_node(sym.node):\n            msg.cant_assign_to_final(name, attr_assign=True, ctx=ctx)\n\n\ndef analyze_descriptor_access(descriptor_type: Type, mx: MemberContext) -> Type:\n    \"\"\"Type check descriptor access.\n\n    Arguments:\n        descriptor_type: The type of the descriptor attribute being accessed\n            (the type of ``f`` in ``a.f`` when ``f`` is a descriptor).\n        mx: The current member access context.\n    Return:\n        The return type of the appropriate ``__get__/__set__`` overload for the descriptor.\n    \"\"\"\n    instance_type = get_proper_type(mx.self_type)\n    orig_descriptor_type = descriptor_type\n    descriptor_type = get_proper_type(descriptor_type)\n\n    if isinstance(descriptor_type, UnionType):\n        # Map the access over union types\n        return make_simplified_union(\n            [analyze_descriptor_access(typ, mx) for typ in descriptor_type.items]\n        )\n    elif not isinstance(descriptor_type, Instance):\n        return orig_descriptor_type\n\n    if not mx.is_lvalue and not descriptor_type.type.has_readable_member(\"__get__\"):\n        return orig_descriptor_type\n\n    # We do this check first to accommodate for descriptors with only __set__ method.\n    # If there is no __set__, we type-check that the assigned value matches\n    # the return type of __get__. This doesn't match the python semantics,\n    # (which allow you to override the descriptor with any value), but preserves\n    # the type of accessing the attribute (even after the override).\n    if mx.is_lvalue and descriptor_type.type.has_readable_member(\"__set__\"):\n        return analyze_descriptor_assign(descriptor_type, mx)\n\n    if mx.is_lvalue and not descriptor_type.type.has_readable_member(\"__get__\"):\n        # This turned out to be not a descriptor after all.\n        return orig_descriptor_type\n\n    dunder_get = descriptor_type.type.get_method(\"__get__\")\n    if dunder_get is None:\n        mx.fail(\n            message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format(\n                descriptor_type.str_with_options(mx.msg.options)\n            )\n        )\n        return AnyType(TypeOfAny.from_error)\n\n    bound_method = analyze_decorator_or_funcbase_access(\n        defn=dunder_get,\n        itype=descriptor_type,\n        name=\"__get__\",\n        mx=mx.copy_modified(self_type=descriptor_type),\n    )\n\n    typ = map_instance_to_supertype(descriptor_type, dunder_get.info)\n    dunder_get_type = expand_type_by_instance(bound_method, typ)\n\n    if isinstance(instance_type, FunctionLike) and instance_type.is_type_obj():\n        owner_type = instance_type.items[0].ret_type\n        instance_type = NoneType()\n    elif isinstance(instance_type, TypeType):\n        owner_type = instance_type.item\n        instance_type = NoneType()\n    else:\n        owner_type = instance_type\n\n    callable_name = mx.chk.expr_checker.method_fullname(descriptor_type, \"__get__\")\n    dunder_get_type = mx.chk.expr_checker.transform_callee_type(\n        callable_name,\n        dunder_get_type,\n        [\n            TempNode(instance_type, context=mx.context),\n            TempNode(TypeType.make_normalized(owner_type), context=mx.context),\n        ],\n        [ARG_POS, ARG_POS],\n        mx.context,\n        object_type=descriptor_type,\n    )\n\n    _, inferred_dunder_get_type = mx.chk.expr_checker.check_call(\n        dunder_get_type,\n        [\n            TempNode(instance_type, context=mx.context),\n            TempNode(TypeType.make_normalized(owner_type), context=mx.context),\n        ],\n        [ARG_POS, ARG_POS],\n        mx.context,\n        object_type=descriptor_type,\n        callable_name=callable_name,\n    )\n\n    # Search for possible deprecations:\n    mx.chk.warn_deprecated(dunder_get, mx.context)\n\n    inferred_dunder_get_type = get_proper_type(inferred_dunder_get_type)\n    if isinstance(inferred_dunder_get_type, AnyType):\n        # check_call failed, and will have reported an error\n        return inferred_dunder_get_type\n\n    if not isinstance(inferred_dunder_get_type, CallableType):\n        mx.fail(\n            message_registry.DESCRIPTOR_GET_NOT_CALLABLE.format(\n                descriptor_type.str_with_options(mx.msg.options)\n            )\n        )\n        return AnyType(TypeOfAny.from_error)\n\n    return inferred_dunder_get_type.ret_type\n\n\ndef analyze_descriptor_assign(descriptor_type: Instance, mx: MemberContext) -> Type:\n    instance_type = get_proper_type(mx.self_type)\n    dunder_set = descriptor_type.type.get_method(\"__set__\")\n    if dunder_set is None:\n        mx.fail(\n            message_registry.DESCRIPTOR_SET_NOT_CALLABLE.format(\n                descriptor_type.str_with_options(mx.msg.options)\n            ).value\n        )\n        return AnyType(TypeOfAny.from_error)\n\n    bound_method = analyze_decorator_or_funcbase_access(\n        defn=dunder_set,\n        itype=descriptor_type,\n        name=\"__set__\",\n        mx=mx.copy_modified(is_lvalue=False, self_type=descriptor_type),\n    )\n    typ = map_instance_to_supertype(descriptor_type, dunder_set.info)\n    dunder_set_type = expand_type_by_instance(bound_method, typ)\n\n    callable_name = mx.chk.expr_checker.method_fullname(descriptor_type, \"__set__\")\n    rvalue = mx.rvalue or TempNode(AnyType(TypeOfAny.special_form), context=mx.context)\n    dunder_set_type = mx.chk.expr_checker.transform_callee_type(\n        callable_name,\n        dunder_set_type,\n        [TempNode(instance_type, context=mx.context), rvalue],\n        [ARG_POS, ARG_POS],\n        mx.context,\n        object_type=descriptor_type,\n    )\n\n    # For non-overloaded setters, the result should be type-checked like a regular assignment.\n    # Hence, we first only try to infer the type by using the rvalue as type context.\n    type_context = rvalue\n    with mx.msg.filter_errors():\n        _, inferred_dunder_set_type = mx.chk.expr_checker.check_call(\n            dunder_set_type,\n            [TempNode(instance_type, context=mx.context), type_context],\n            [ARG_POS, ARG_POS],\n            mx.context,\n            object_type=descriptor_type,\n            callable_name=callable_name,\n        )\n\n    # And now we in fact type check the call, to show errors related to wrong arguments\n    # count, etc., replacing the type context for non-overloaded setters only.\n    inferred_dunder_set_type = get_proper_type(inferred_dunder_set_type)\n    if isinstance(inferred_dunder_set_type, CallableType):\n        type_context = TempNode(AnyType(TypeOfAny.special_form), context=mx.context)\n    mx.chk.expr_checker.check_call(\n        dunder_set_type,\n        [TempNode(instance_type, context=mx.context), type_context],\n        [ARG_POS, ARG_POS],\n        mx.context,\n        object_type=descriptor_type,\n        callable_name=callable_name,\n    )\n\n    # Search for possible deprecations:\n    mx.chk.warn_deprecated(dunder_set, mx.context)\n\n    # In the following cases, a message already will have been recorded in check_call.\n    if (not isinstance(inferred_dunder_set_type, CallableType)) or (\n        len(inferred_dunder_set_type.arg_types) < 2\n    ):\n        return AnyType(TypeOfAny.from_error)\n    return inferred_dunder_set_type.arg_types[1]\n\n\ndef is_instance_var(var: Var) -> bool:\n    \"\"\"Return if var is an instance variable according to PEP 526.\"\"\"\n    return (\n        # check the type_info node is the var (not a decorated function, etc.)\n        var.name in var.info.names\n        and var.info.names[var.name].node is var\n        and not var.is_classvar\n        # variables without annotations are treated as classvar\n        and not var.is_inferred\n    )\n\n\ndef analyze_var(\n    name: str,\n    var: Var,\n    itype: Instance,\n    mx: MemberContext,\n    *,\n    implicit: bool = False,\n    is_trivial_self: bool = False,\n) -> Type:\n    \"\"\"Analyze access to an attribute via a Var node.\n\n    This is conceptually part of analyze_member_access and the arguments are similar.\n    itype is the instance type in which attribute should be looked up\n    original_type is the type of E in the expression E.var\n    if implicit is True, the original Var was created as an assignment to self\n    if is_trivial_self is True, we can use fast path for bind_self().\n    \"\"\"\n    # Found a member variable.\n    original_itype = itype\n    itype = map_instance_to_supertype(itype, var.info)\n    if var.is_settable_property and mx.is_lvalue:\n        typ: Type | None = var.setter_type\n        if typ is None and var.is_ready:\n            # Existing synthetic properties may not set setter type. Fall back to getter.\n            typ = var.type\n    else:\n        typ = var.type\n    if typ:\n        if isinstance(typ, PartialType):\n            return mx.chk.handle_partial_var_type(typ, mx.is_lvalue, var, mx.context)\n        if mx.is_lvalue and not mx.suppress_errors:\n            if var.is_property and not var.is_settable_property:\n                mx.msg.read_only_property(name, itype.type, mx.context)\n            if var.is_classvar:\n                mx.msg.cant_assign_to_classvar(name, mx.context)\n        # This is the most common case for variables, so start with this.\n        result = expand_without_binding(typ, var, itype, original_itype, mx)\n\n        # A non-None value indicates that we should actually bind self for this variable.\n        call_type: ProperType | None = None\n        if var.is_initialized_in_class and (not is_instance_var(var) or mx.is_operator):\n            typ = get_proper_type(typ)\n            if isinstance(typ, FunctionLike) and not typ.is_type_obj():\n                call_type = typ\n            elif var.is_property:\n                deco_mx = mx.copy_modified(original_type=typ, self_type=typ, is_lvalue=False)\n                call_type = get_proper_type(_analyze_member_access(\"__call__\", typ, deco_mx))\n            else:\n                call_type = typ\n\n        # Bound variables with callable types are treated like methods\n        # (these are usually method aliases like __rmul__ = __mul__).\n        if isinstance(call_type, FunctionLike) and not call_type.is_type_obj():\n            if mx.is_lvalue and not var.is_property and not mx.suppress_errors:\n                mx.msg.cant_assign_to_method(mx.context)\n\n        # Bind the self type for each callable component (when needed).\n        if call_type and not var.is_staticmethod:\n            bound_items = []\n            for ct in call_type.items if isinstance(call_type, UnionType) else [call_type]:\n                p_ct = get_proper_type(ct)\n                if isinstance(p_ct, FunctionLike) and (not p_ct.bound() or var.is_property):\n                    item = expand_and_bind_callable(p_ct, var, itype, name, mx, is_trivial_self)\n                else:\n                    item = expand_without_binding(ct, var, itype, original_itype, mx)\n                bound_items.append(item)\n            result = UnionType.make_union(bound_items)\n    else:\n        if not var.is_ready and not mx.no_deferral:\n            mx.not_ready_callback(var.name, mx.context)\n        # Implicit 'Any' type.\n        result = AnyType(TypeOfAny.special_form)\n    fullname = f\"{var.info.fullname}.{name}\"\n    hook = mx.chk.plugin.get_attribute_hook(fullname)\n\n    if var.info.is_enum and not mx.is_lvalue:\n        if name in var.info.enum_members and name not in {\"name\", \"value\"}:\n            enum_literal = LiteralType(name, fallback=itype)\n            result = itype.copy_modified(last_known_value=enum_literal)\n        elif (\n            isinstance(p_result := get_proper_type(result), Instance)\n            and p_result.type.fullname == \"enum.nonmember\"\n            and p_result.args\n        ):\n            # Unwrap nonmember similar to class-level access\n            result = p_result.args[0]\n    if result and not (implicit or var.info.is_protocol and is_instance_var(var)):\n        result = analyze_descriptor_access(result, mx)\n    if hook:\n        result = hook(\n            AttributeContext(\n                get_proper_type(mx.original_type), result, mx.is_lvalue, mx.context, mx.chk\n            )\n        )\n    return result\n\n\ndef expand_without_binding(\n    typ: Type, var: Var, itype: Instance, original_itype: Instance, mx: MemberContext\n) -> Type:\n    if not mx.preserve_type_var_ids:\n        typ = freshen_all_functions_type_vars(typ)\n    typ = expand_self_type_if_needed(typ, mx, var, original_itype)\n    expanded = expand_type_by_instance(typ, itype)\n    freeze_all_type_vars(expanded)\n    return expanded\n\n\ndef expand_and_bind_callable(\n    functype: FunctionLike,\n    var: Var,\n    itype: Instance,\n    name: str,\n    mx: MemberContext,\n    is_trivial_self: bool,\n) -> Type:\n    if not mx.preserve_type_var_ids:\n        functype = freshen_all_functions_type_vars(functype)\n    typ = get_proper_type(expand_self_type(var, functype, mx.self_type))\n    assert isinstance(typ, FunctionLike)\n    if is_trivial_self:\n        typ = bind_self_fast(typ, mx.self_type)\n    else:\n        typ = check_self_arg(typ, mx.self_type, var.is_classmethod, mx.context, name, mx.msg)\n        typ = bind_self(typ, mx.self_type, var.is_classmethod)\n    expanded = expand_type_by_instance(typ, itype)\n    freeze_all_type_vars(expanded)\n    if not var.is_property:\n        return expanded\n    if isinstance(expanded, Overloaded):\n        # Legacy way to store settable properties is with overloads. Also in case it is\n        # an actual overloaded property, selecting first item that passed check_self_arg()\n        # is a good approximation, long-term we should use check_call() inference below.\n        if not expanded.items:\n            # A broken overload, error should be already reported.\n            return AnyType(TypeOfAny.from_error)\n        expanded = expanded.items[0]\n    assert isinstance(expanded, CallableType), expanded\n    if var.is_settable_property and mx.is_lvalue and var.setter_type is not None:\n        if expanded.variables:\n            type_ctx = mx.rvalue or TempNode(AnyType(TypeOfAny.special_form), context=mx.context)\n            _, inferred_expanded = mx.chk.expr_checker.check_call(\n                expanded, [type_ctx], [ARG_POS], mx.context\n            )\n            expanded = get_proper_type(inferred_expanded)\n            assert isinstance(expanded, CallableType)\n        if not expanded.arg_types:\n            # This can happen when accessing invalid property from its own body,\n            # error will be reported elsewhere.\n            return AnyType(TypeOfAny.from_error)\n        return expanded.arg_types[0]\n    else:\n        return expanded.ret_type\n\n\ndef expand_self_type_if_needed(\n    t: Type, mx: MemberContext, var: Var, itype: Instance, is_class: bool = False\n) -> Type:\n    \"\"\"Expand special Self type in a backwards compatible manner.\n\n    This should ensure that mixing old-style and new-style self-types work\n    seamlessly. Also, re-bind new style self-types in subclasses if needed.\n    \"\"\"\n    original = get_proper_type(mx.self_type)\n    if not (mx.is_self or mx.is_super):\n        repl = mx.self_type\n        if is_class:\n            if isinstance(original, TypeType):\n                repl = original.item\n            elif isinstance(original, CallableType):\n                # Problematic access errors should have been already reported.\n                repl = erase_typevars(original.ret_type)\n            else:\n                repl = itype\n        return expand_self_type(var, t, repl)\n    elif supported_self_type(\n        # Support compatibility with plain old style T -> T and Type[T] -> T only.\n        get_proper_type(mx.self_type),\n        allow_instances=False,\n        allow_callable=False,\n    ):\n        repl = mx.self_type\n        if is_class and isinstance(original, TypeType):\n            repl = original.item\n        return expand_self_type(var, t, repl)\n    elif (\n        mx.is_self\n        and itype.type != var.info\n        # If an attribute with Self-type was defined in a supertype, we need to\n        # rebind the Self type variable to Self type variable of current class...\n        and itype.type.self_type is not None\n        # ...unless `self` has an explicit non-trivial annotation.\n        and itype == mx.chk.scope.active_self_type()\n    ):\n        return expand_self_type(var, t, itype.type.self_type)\n    else:\n        return t\n\n\ndef check_self_arg(\n    functype: FunctionLike,\n    dispatched_arg_type: Type,\n    is_classmethod: bool,\n    context: Context,\n    name: str,\n    msg: MessageBuilder,\n) -> FunctionLike:\n    \"\"\"Check that an instance has a valid type for a method with annotated 'self'.\n\n    For example if the method is defined as:\n        class A:\n            def f(self: S) -> T: ...\n    then for 'x.f' we check that type(x) <: S. If the method is overloaded, we select\n    only overloads items that satisfy this requirement. If there are no matching\n    overloads, an error is generated.\n    \"\"\"\n    items = functype.items\n    if not items:\n        return functype\n    new_items = []\n    if is_classmethod:\n        dispatched_arg_type = TypeType.make_normalized(dispatched_arg_type)\n    p_dispatched_arg_type = get_proper_type(dispatched_arg_type)\n\n    for item in items:\n        if not item.arg_types or item.arg_kinds[0] not in (ARG_POS, ARG_STAR):\n            # No positional first (self) argument (*args is okay).\n            msg.no_formal_self(name, item, context)\n            # This is pretty bad, so just return the original signature if\n            # there is at least one such error.\n            return functype\n        selfarg = get_proper_type(item.arg_types[0])\n        if isinstance(selfarg, Instance) and isinstance(p_dispatched_arg_type, Instance):\n            if selfarg.type is p_dispatched_arg_type.type and selfarg.args:\n                if not is_overlapping_types(p_dispatched_arg_type, selfarg):\n                    # This special casing is needed since `actual <: erased(template)`\n                    # logic below doesn't always work, and a more correct approach may\n                    # be tricky.\n                    continue\n        new_items.append(item)\n\n    if new_items:\n        items = new_items\n        new_items = []\n\n    for item in items:\n        selfarg = get_proper_type(item.arg_types[0])\n        # This matches similar special-casing in bind_self(), see more details there.\n        self_callable = name == \"__call__\" and isinstance(selfarg, CallableType)\n        if self_callable or is_subtype(\n            dispatched_arg_type,\n            # This level of erasure matches the one in checker.check_func_def(),\n            # better keep these two checks consistent.\n            erase_typevars(erase_to_bound(selfarg)),\n            # This is to work around the fact that erased ParamSpec and TypeVarTuple\n            # callables are not always compatible with non-erased ones both ways.\n            always_covariant=any(\n                not isinstance(tv, TypeVarType) for tv in get_all_type_vars(selfarg)\n            ),\n            ignore_pos_arg_names=True,\n        ):\n            new_items.append(item)\n        elif isinstance(selfarg, ParamSpecType):\n            # TODO: This is not always right. What's the most reasonable thing to do here?\n            new_items.append(item)\n        elif isinstance(selfarg, TypeVarTupleType):\n            raise NotImplementedError\n    if not new_items:\n        # Choose first item for the message (it may be not very helpful for overloads).\n        msg.incompatible_self_argument(\n            name, dispatched_arg_type, items[0], is_classmethod, context\n        )\n        return functype\n    if len(new_items) == 1:\n        return new_items[0]\n    return Overloaded(new_items)\n\n\ndef analyze_class_attribute_access(\n    itype: Instance,\n    name: str,\n    mx: MemberContext,\n    *,\n    mcs_fallback: Instance,\n    override_info: TypeInfo | None = None,\n    original_vars: Sequence[TypeVarLikeType] | None = None,\n) -> Type | None:\n    \"\"\"Analyze access to an attribute on a class object.\n\n    itype is the return type of the class object callable, original_type is the type\n    of E in the expression E.var, original_vars are type variables of the class callable\n    (for generic classes).\n    \"\"\"\n    info = itype.type\n    if override_info:\n        info = override_info\n\n    fullname = f\"{info.fullname}.{name}\"\n    hook = mx.chk.plugin.get_class_attribute_hook(fullname)\n\n    node = info.get(name)\n    if not node:\n        if itype.extra_attrs and name in itype.extra_attrs.attrs:\n            # For modules use direct symbol table lookup.\n            if not itype.extra_attrs.mod_name:\n                return itype.extra_attrs.attrs[name]\n        if info.fallback_to_any or info.meta_fallback_to_any:\n            return apply_class_attr_hook(mx, hook, AnyType(TypeOfAny.special_form))\n        return None\n\n    if (\n        isinstance(node.node, Var)\n        and not node.node.is_classvar\n        and not hook\n        and mcs_fallback.type.get(name)\n    ):\n        # If the same attribute is declared on the metaclass and the class but with different types,\n        # and the attribute on the class is not a ClassVar,\n        # the type of the attribute on the metaclass should take priority\n        # over the type of the attribute on the class,\n        # when the attribute is being accessed from the class object itself.\n        #\n        # Return `None` here to signify that the name should be looked up\n        # on the class object itself rather than the instance.\n        return None\n\n    mx.chk.warn_deprecated(node.node, mx.context)\n\n    is_decorated = isinstance(node.node, Decorator)\n    is_method = is_decorated or isinstance(node.node, FuncBase)\n    if mx.is_lvalue and not mx.suppress_errors:\n        if is_method:\n            mx.msg.cant_assign_to_method(mx.context)\n        if isinstance(node.node, TypeInfo):\n            mx.fail(message_registry.CANNOT_ASSIGN_TO_TYPE)\n\n    # Refuse class attribute access if slot defined\n    if info.slots and name in info.slots:\n        mx.fail(message_registry.CLASS_VAR_CONFLICTS_SLOTS.format(name))\n\n    if node.implicit and isinstance(node.node, Var):\n        if node.node.is_final:\n            # If a final attribute was declared on `self` in `__init__`, then it\n            # can't be accessed on the class object.\n            mx.fail(message_registry.CANNOT_ACCESS_FINAL_INSTANCE_ATTR.format(node.node.name))\n        elif not mx.is_lvalue and not defined_in_superclass(info, name):\n            mx.fail(message_registry.CANNOT_ACCESS_INSTANCE_ONLY_ATTR.format(node.node.name))\n\n    # An assignment to final attribute on class object is also always an error,\n    # independently of types.\n    if mx.is_lvalue and not mx.chk.get_final_context():\n        check_final_member(name, info, mx.msg, mx.context)\n\n    if info.is_enum and not (mx.is_lvalue or is_decorated or is_method):\n        enum_class_attribute_type = analyze_enum_class_attribute_access(itype, name, mx)\n        if enum_class_attribute_type:\n            return apply_class_attr_hook(mx, hook, enum_class_attribute_type)\n\n    t = node.type\n    if t:\n        if isinstance(t, PartialType):\n            symnode = node.node\n            assert isinstance(symnode, Var)\n            return apply_class_attr_hook(\n                mx, hook, mx.chk.handle_partial_var_type(t, mx.is_lvalue, symnode, mx.context)\n            )\n\n        # Find the class where method/variable was defined.\n        if isinstance(node.node, Decorator):\n            super_info: TypeInfo | None = node.node.var.info\n        elif isinstance(node.node, (Var, SYMBOL_FUNCBASE_TYPES)):\n            super_info = node.node.info\n        else:\n            super_info = None\n\n        # Map the type to how it would look as a defining class. For example:\n        #     class C(Generic[T]): ...\n        #     class D(C[Tuple[T, S]]): ...\n        #     D[int, str].method()\n        # Here itype is D[int, str], isuper is C[Tuple[int, str]].\n        if not super_info:\n            isuper = None\n        else:\n            isuper = map_instance_to_supertype(itype, super_info)\n\n        if isinstance(node.node, Var):\n            assert isuper is not None\n            object_type = get_proper_type(mx.self_type)\n            # Check if original variable type has type variables. For example:\n            #     class C(Generic[T]):\n            #         x: T\n            #     C.x  # Error, ambiguous access\n            #     C[int].x  # Also an error, since C[int] is same as C at runtime\n            # Exception is Self type wrapped in ClassVar, that is safe.\n            prohibit_self = not node.node.is_classvar\n            def_vars = set(node.node.info.defn.type_vars)\n            if prohibit_self and node.node.info.self_type:\n                def_vars.add(node.node.info.self_type)\n            # Exception: access on Type[...], including first argument of class methods is OK.\n            prohibit_generic = not isinstance(object_type, TypeType) or node.implicit\n            if prohibit_generic and def_vars & set(get_all_type_vars(t)):\n                if node.node.is_classvar:\n                    message = message_registry.GENERIC_CLASS_VAR_ACCESS\n                else:\n                    message = message_registry.GENERIC_INSTANCE_VAR_CLASS_ACCESS\n                mx.fail(message)\n            t = expand_self_type_if_needed(t, mx, node.node, itype, is_class=True)\n            t = expand_type_by_instance(t, isuper)\n            # Erase non-mapped variables, but keep mapped ones, even if there is an error.\n            # In the above example this means that we infer following types:\n            #     C.x -> Any\n            #     C[int].x -> int\n            if prohibit_generic:\n                erase_vars = set(itype.type.defn.type_vars)\n                if prohibit_self and itype.type.self_type:\n                    erase_vars.add(itype.type.self_type)\n                t = erase_typevars(t, {tv.id for tv in erase_vars})\n\n        is_classmethod = (\n            (is_decorated and cast(Decorator, node.node).func.is_class)\n            or (isinstance(node.node, SYMBOL_FUNCBASE_TYPES) and node.node.is_class)\n            or isinstance(node.node, Var)\n            and node.node.is_classmethod\n        )\n        t = get_proper_type(t)\n        is_trivial_self = False\n        if isinstance(node.node, Decorator):\n            # Use fast path if there are trivial decorators like @classmethod or @property\n            is_trivial_self = node.node.func.is_trivial_self and not node.node.decorators\n        elif isinstance(node.node, (FuncDef, OverloadedFuncDef)):\n            is_trivial_self = node.node.is_trivial_self\n        if (\n            isinstance(t, FunctionLike)\n            and is_classmethod\n            and not is_trivial_self\n            and not t.bound()\n        ):\n            t = check_self_arg(t, mx.self_type, False, mx.context, name, mx.msg)\n        t = add_class_tvars(\n            t,\n            isuper,\n            is_classmethod,\n            mx,\n            original_vars=original_vars,\n            is_trivial_self=is_trivial_self,\n        )\n        if is_decorated:\n            t = expand_self_type_if_needed(\n                t, mx, cast(Decorator, node.node).var, itype, is_class=is_classmethod\n            )\n\n        result = t\n        # __set__ is not called on class objects.\n        if not mx.is_lvalue:\n            result = analyze_descriptor_access(result, mx)\n\n        return apply_class_attr_hook(mx, hook, result)\n    elif isinstance(node.node, Var):\n        mx.not_ready_callback(name, mx.context)\n        return AnyType(TypeOfAny.special_form)\n\n    if isinstance(node.node, (TypeInfo, TypeAlias, MypyFile, TypeVarLikeExpr)):\n        # TODO: should we apply class plugin here (similar to instance access)?\n        return mx.chk.expr_checker.analyze_static_reference(node.node, mx.context, mx.is_lvalue)\n\n    if is_decorated:\n        assert isinstance(node.node, Decorator)\n        if node.node.type:\n            return apply_class_attr_hook(mx, hook, node.node.type)\n        else:\n            mx.not_ready_callback(name, mx.context)\n            return AnyType(TypeOfAny.from_error)\n    else:\n        assert isinstance(node.node, SYMBOL_FUNCBASE_TYPES)\n        typ = function_type(node.node, mx.named_type(\"builtins.function\"))\n        # Note: if we are accessing class method on class object, the cls argument is bound.\n        # Annotated and/or explicit class methods go through other code paths above, for\n        # unannotated implicit class methods we do this here.\n        if node.node.is_class:\n            typ = bind_self_fast(typ)\n        return apply_class_attr_hook(mx, hook, typ)\n\n\ndef apply_class_attr_hook(\n    mx: MemberContext, hook: Callable[[AttributeContext], Type] | None, result: Type\n) -> Type | None:\n    if hook:\n        result = hook(\n            AttributeContext(\n                get_proper_type(mx.original_type), result, mx.is_lvalue, mx.context, mx.chk\n            )\n        )\n    return result\n\n\ndef analyze_enum_class_attribute_access(\n    itype: Instance, name: str, mx: MemberContext\n) -> Type | None:\n    # Skip these since Enum will remove it\n    if name in EXCLUDED_ENUM_ATTRIBUTES:\n        return report_missing_attribute(mx.original_type, itype, name, mx)\n\n    node = itype.type.get(name)\n    if node and node.type:\n        proper = get_proper_type(node.type)\n        # Support `A = nonmember(1)` function call and decorator.\n        if (\n            isinstance(proper, Instance)\n            and proper.type.fullname == \"enum.nonmember\"\n            and proper.args\n        ):\n            return proper.args[0]\n\n    if name not in itype.type.enum_members:\n        return None\n\n    enum_literal = LiteralType(name, fallback=itype)\n    return itype.copy_modified(last_known_value=enum_literal)\n\n\ndef analyze_typeddict_access(\n    name: str, typ: TypedDictType, mx: MemberContext, override_info: TypeInfo | None\n) -> Type:\n    if name == \"__setitem__\":\n        if isinstance(mx.context, IndexExpr):\n            # Since we can get this during `a['key'] = ...`\n            # it is safe to assume that the context is `IndexExpr`.\n            item_type, key_names = mx.chk.expr_checker.visit_typeddict_index_expr(\n                typ, mx.context.index, setitem=True\n            )\n            assigned_readonly_keys = typ.readonly_keys & key_names\n            if assigned_readonly_keys and not mx.suppress_errors:\n                mx.msg.readonly_keys_mutated(assigned_readonly_keys, context=mx.context)\n        else:\n            # It can also be `a.__setitem__(...)` direct call.\n            # In this case `item_type` can be `Any`,\n            # because we don't have args available yet.\n            # TODO: check in `default` plugin that `__setitem__` is correct.\n            item_type = AnyType(TypeOfAny.implementation_artifact)\n        return CallableType(\n            arg_types=[mx.chk.named_type(\"builtins.str\"), item_type],\n            arg_kinds=[ARG_POS, ARG_POS],\n            arg_names=[None, None],\n            ret_type=NoneType(),\n            fallback=mx.chk.named_type(\"builtins.function\"),\n            name=name,\n        )\n    elif name == \"__delitem__\":\n        return CallableType(\n            arg_types=[mx.chk.named_type(\"builtins.str\")],\n            arg_kinds=[ARG_POS],\n            arg_names=[None],\n            ret_type=NoneType(),\n            fallback=mx.chk.named_type(\"builtins.function\"),\n            name=name,\n        )\n    return _analyze_member_access(name, typ.fallback, mx, override_info)\n\n\ndef add_class_tvars(\n    t: ProperType,\n    isuper: Instance | None,\n    is_classmethod: bool,\n    mx: MemberContext,\n    original_vars: Sequence[TypeVarLikeType] | None = None,\n    is_trivial_self: bool = False,\n) -> Type:\n    \"\"\"Instantiate type variables during analyze_class_attribute_access,\n    e.g T and Q in the following:\n\n    class A(Generic[T]):\n        @classmethod\n        def foo(cls: Type[Q]) -> Tuple[T, Q]: ...\n\n    class B(A[str]): pass\n    B.foo()\n\n    Args:\n        t: Declared type of the method (or property)\n        isuper: Current instance mapped to the superclass where method was defined, this\n            is usually done by map_instance_to_supertype()\n        is_classmethod: True if this method is decorated with @classmethod\n        original_vars: Type variables of the class callable on which the method was accessed\n        is_trivial_self: if True, we can use fast path for bind_self().\n    Returns:\n        Expanded method type with added type variables (when needed).\n    \"\"\"\n    # TODO: verify consistency between Q and T\n\n    # We add class type variables if the class method is accessed on class object\n    # without applied type arguments, this matches the behavior of __init__().\n    # For example (continuing the example in docstring):\n    #     A       # The type of callable is def [T] () -> A[T], _not_ def () -> A[Any]\n    #     A[int]  # The type of callable is def () -> A[int]\n    # and\n    #     A.foo       # The type is generic def [T] () -> Tuple[T, A[T]]\n    #     A[int].foo  # The type is non-generic def () -> Tuple[int, A[int]]\n    #\n    # This behaviour is useful for defining alternative constructors for generic classes.\n    # To achieve such behaviour, we add the class type variables that are still free\n    # (i.e. appear in the return type of the class object on which the method was accessed).\n    if isinstance(t, CallableType):\n        tvars = original_vars if original_vars is not None else []\n        if not mx.preserve_type_var_ids:\n            t = freshen_all_functions_type_vars(t)\n        if is_classmethod and not t.is_bound:\n            if is_trivial_self:\n                t = bind_self_fast(t, mx.self_type)\n            else:\n                t = bind_self(t, mx.self_type, is_classmethod=True)\n        if isuper is not None:\n            t = expand_type_by_instance(t, isuper)\n        freeze_all_type_vars(t)\n        return t.copy_modified(variables=list(tvars) + list(t.variables))\n    elif isinstance(t, Overloaded):\n        return Overloaded(\n            [\n                cast(\n                    CallableType,\n                    add_class_tvars(item, isuper, is_classmethod, mx, original_vars=original_vars),\n                )\n                for item in t.items\n            ]\n        )\n    if isuper is not None:\n        t = expand_type_by_instance(t, isuper)\n    return t\n\n\ndef analyze_decorator_or_funcbase_access(\n    defn: Decorator | FuncBase, itype: Instance, name: str, mx: MemberContext\n) -> Type:\n    \"\"\"Analyzes the type behind method access.\n\n    The function itself can possibly be decorated.\n    See: https://github.com/python/mypy/issues/10409\n    \"\"\"\n    if isinstance(defn, Decorator):\n        return analyze_var(name, defn.var, itype, mx)\n    typ = function_type(defn, mx.chk.named_type(\"builtins.function\"))\n    if isinstance(defn, (FuncDef, OverloadedFuncDef)) and defn.is_trivial_self:\n        return bind_self_fast(typ, mx.self_type)\n    typ = check_self_arg(typ, mx.self_type, defn.is_class, mx.context, name, mx.msg)\n    return bind_self(typ, original_type=mx.self_type, is_classmethod=defn.is_class)\n\n\nF = TypeVar(\"F\", bound=FunctionLike)\n\n\ndef bind_self_fast(method: F, original_type: Type | None = None) -> F:\n    \"\"\"Return a copy of `method`, with the type of its first parameter (usually\n    self or cls) bound to original_type.\n\n    This is a faster version of mypy.typeops.bind_self() that can be used for methods\n    with trivial self/cls annotations.\n    \"\"\"\n    if isinstance(method, Overloaded):\n        items = [bind_self_fast(c, original_type) for c in method.items]\n        return cast(F, Overloaded(items))\n    assert isinstance(method, CallableType)\n    if not method.arg_types:\n        # Invalid method, return something.\n        return method\n    if method.arg_kinds[0] in (ARG_STAR, ARG_STAR2):\n        # See typeops.py for details.\n        return method\n    return method.copy_modified(\n        arg_types=method.arg_types[1:],\n        arg_kinds=method.arg_kinds[1:],\n        arg_names=method.arg_names[1:],\n        is_bound=True,\n    )\n\n\ndef has_operator(typ: Type, op_method: str, named_type: Callable[[str], Instance]) -> bool:\n    \"\"\"Does type have operator with the given name?\n\n    Note: this follows the rules for operator access, in particular:\n    * __getattr__ is not considered\n    * for class objects we only look in metaclass\n    * instance level attributes (i.e. extra_attrs) are not considered\n    \"\"\"\n    # This is much faster than analyze_member_access, and so using\n    # it first as a filter is important for performance. This is mostly relevant\n    # in situations where we can't expect that method is likely present,\n    # e.g. for __OP__ vs __rOP__.\n    typ = get_proper_type(typ)\n\n    if isinstance(typ, TypeVarLikeType):\n        typ = typ.values_or_bound()\n    if isinstance(typ, AnyType):\n        return True\n    if isinstance(typ, UnionType):\n        return all(has_operator(x, op_method, named_type) for x in typ.relevant_items())\n    if isinstance(typ, FunctionLike) and typ.is_type_obj():\n        return typ.fallback.type.has_readable_member(op_method)\n    if isinstance(typ, TypeType):\n        # Type[Union[X, ...]] is always normalized to Union[Type[X], ...],\n        # so we don't need to care about unions here, but we need to care about\n        # Type[T], where upper bound of T is a union.\n        item = typ.item\n        if isinstance(item, TypeVarType):\n            item = item.values_or_bound()\n        if isinstance(item, UnionType):\n            return all(meta_has_operator(x, op_method, named_type) for x in item.relevant_items())\n        return meta_has_operator(item, op_method, named_type)\n    return instance_fallback(typ, named_type).type.has_readable_member(op_method)\n\n\ndef instance_fallback(typ: ProperType, named_type: Callable[[str], Instance]) -> Instance:\n    if isinstance(typ, Instance):\n        return typ\n    if isinstance(typ, TupleType):\n        return tuple_fallback(typ)\n    if isinstance(typ, (LiteralType, TypedDictType)):\n        return typ.fallback\n    return named_type(\"builtins.object\")\n\n\ndef meta_has_operator(item: Type, op_method: str, named_type: Callable[[str], Instance]) -> bool:\n    item = get_proper_type(item)\n    if isinstance(item, AnyType):\n        return True\n    item = instance_fallback(item, named_type)\n    meta = item.type.metaclass_type or named_type(\"builtins.type\")\n    return meta.type.has_readable_member(op_method)\n\n\ndef defined_in_superclass(info: TypeInfo, name: str) -> bool:\n    \"\"\"Check if a variable has an explicit value at class level in any of superclasses.\"\"\"\n    for base in info.mro[1:]:\n        if (node := base.names.get(name)) is not None:\n            if not node.implicit and isinstance(node.node, Var) and node.node.has_explicit_value:\n                return True\n    return False\n"
  },
  {
    "path": "mypy/checkpattern.py",
    "content": "\"\"\"Pattern checker. This file is conceptually part of TypeChecker.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom typing import Final, NamedTuple\n\nfrom mypy import message_registry\nfrom mypy.checker_shared import TypeCheckerSharedApi, TypeRange\nfrom mypy.checkmember import analyze_member_access\nfrom mypy.expandtype import expand_type_by_instance\nfrom mypy.join import join_types\nfrom mypy.literals import literal_hash\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.meet import narrow_declared_type\nfrom mypy.messages import MessageBuilder\nfrom mypy.nodes import ARG_POS, Expression, NameExpr, TempNode, TypeAlias, Var\nfrom mypy.options import Options\nfrom mypy.patterns import (\n    AsPattern,\n    ClassPattern,\n    MappingPattern,\n    OrPattern,\n    Pattern,\n    SequencePattern,\n    SingletonPattern,\n    StarredPattern,\n    ValuePattern,\n)\nfrom mypy.plugin import Plugin\nfrom mypy.subtypes import is_subtype\nfrom mypy.typeops import (\n    coerce_to_literal,\n    make_simplified_union,\n    try_getting_str_literals_from_type,\n    tuple_fallback,\n)\nfrom mypy.types import (\n    AnyType,\n    FunctionLike,\n    Instance,\n    NoneType,\n    ProperType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeOfAny,\n    TypeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    callable_with_ellipsis,\n    find_unpack_in_list,\n    get_proper_type,\n    split_with_prefix_and_suffix,\n)\nfrom mypy.typevars import fill_typevars, fill_typevars_with_any\nfrom mypy.visitor import PatternVisitor\n\nself_match_type_names: Final = [\n    \"builtins.bool\",\n    \"builtins.bytearray\",\n    \"builtins.bytes\",\n    \"builtins.dict\",\n    \"builtins.float\",\n    \"builtins.frozenset\",\n    \"builtins.int\",\n    \"builtins.list\",\n    \"builtins.set\",\n    \"builtins.str\",\n    \"builtins.tuple\",\n]\n\nnon_sequence_match_type_names: Final = [\"builtins.str\", \"builtins.bytes\", \"builtins.bytearray\"]\n\n\n# For every Pattern a PatternType can be calculated. This requires recursively calculating\n# the PatternTypes of the sub-patterns first.\n# Using the data in the PatternType the match subject and captured names can be narrowed/inferred.\nclass PatternType(NamedTuple):\n    type: Type  # The type the match subject can be narrowed to\n    rest_type: Type  # The remaining type if the pattern didn't match\n    captures: dict[Expression, Type]  # The variables captured by the pattern\n\n\nclass PatternChecker(PatternVisitor[PatternType]):\n    \"\"\"Pattern checker.\n\n    This class checks if a pattern can match a type, what the type can be narrowed to, and what\n    type capture patterns should be inferred as.\n    \"\"\"\n\n    # Some services are provided by a TypeChecker instance.\n    chk: TypeCheckerSharedApi\n    # This is shared with TypeChecker, but stored also here for convenience.\n    msg: MessageBuilder\n    # Currently unused\n    plugin: Plugin\n    # The expression being matched against the pattern\n    subject: Expression\n\n    subject_type: Type\n    # Type of the subject to check the (sub)pattern against\n    type_context: list[Type]\n    # Types that match against self instead of their __match_args__ if used as a class pattern\n    # Filled in from self_match_type_names\n    self_match_types: list[Type]\n    # Types that are sequences, but don't match sequence patterns. Filled in from\n    # non_sequence_match_type_names\n    non_sequence_match_types: list[Type]\n\n    options: Options\n\n    def __init__(\n        self, chk: TypeCheckerSharedApi, msg: MessageBuilder, plugin: Plugin, options: Options\n    ) -> None:\n        self.chk = chk\n        self.msg = msg\n        self.plugin = plugin\n\n        self.type_context = []\n        self.self_match_types = self.generate_types_from_names(self_match_type_names)\n        self.non_sequence_match_types = self.generate_types_from_names(\n            non_sequence_match_type_names\n        )\n        self.options = options\n\n    def accept(self, o: Pattern, type_context: Type) -> PatternType:\n        self.type_context.append(type_context)\n        result = o.accept(self)\n        self.type_context.pop()\n\n        return result\n\n    def visit_as_pattern(self, o: AsPattern) -> PatternType:\n        current_type = self.type_context[-1]\n        if o.pattern is not None:\n            pattern_type = self.accept(o.pattern, current_type)\n            typ, rest_type, type_map = pattern_type\n        else:\n            typ, rest_type, type_map = current_type, UninhabitedType(), {}\n\n        if not is_uninhabited(typ) and o.name is not None:\n            typ, _ = self.chk.conditional_types_with_intersection(\n                current_type, [get_type_range(typ)], o, default=current_type\n            )\n            if not is_uninhabited(typ):\n                type_map[o.name] = typ\n\n        return PatternType(typ, rest_type, type_map)\n\n    def visit_or_pattern(self, o: OrPattern) -> PatternType:\n        current_type = self.type_context[-1]\n\n        #\n        # Check all the subpatterns\n        #\n        pattern_types = []\n        for pattern in o.patterns:\n            pattern_type = self.accept(pattern, current_type)\n            pattern_types.append(pattern_type)\n            if not is_uninhabited(pattern_type.type):\n                current_type = pattern_type.rest_type\n\n        #\n        # Collect the final type\n        #\n        types = []\n        for pattern_type in pattern_types:\n            if not is_uninhabited(pattern_type.type):\n                types.append(pattern_type.type)\n\n        #\n        # Check the capture types\n        #\n        capture_types: dict[Var, list[tuple[Expression, Type]]] = defaultdict(list)\n        # Collect captures from the first subpattern\n        for expr, typ in pattern_types[0].captures.items():\n            node = get_var(expr)\n            capture_types[node].append((expr, typ))\n\n        # Check if other subpatterns capture the same names\n        for i, pattern_type in enumerate(pattern_types[1:]):\n            vars = {get_var(expr) for expr, _ in pattern_type.captures.items()}\n            if capture_types.keys() != vars:\n                self.msg.fail(message_registry.OR_PATTERN_ALTERNATIVE_NAMES, o.patterns[i])\n            for expr, typ in pattern_type.captures.items():\n                node = get_var(expr)\n                capture_types[node].append((expr, typ))\n\n        captures: dict[Expression, Type] = {}\n        for capture_list in capture_types.values():\n            typ = UninhabitedType()\n            for _, other in capture_list:\n                typ = make_simplified_union([typ, other])\n\n            captures[capture_list[0][0]] = typ\n\n        union_type = make_simplified_union(types)\n        return PatternType(union_type, current_type, captures)\n\n    def visit_value_pattern(self, o: ValuePattern) -> PatternType:\n        current_type = self.type_context[-1]\n        typ = self.chk.expr_checker.accept(o.expr)\n        typ = coerce_to_literal(typ)\n        node = TempNode(current_type)\n        # Value patterns are essentially a syntactic sugar on top of `if x == Value`.\n        # They should be treated equivalently.\n        ok_map, rest_map = self.chk.narrow_type_by_identity_equality(\n            \"==\", [node, TempNode(typ)], [current_type, typ], [0, 1], {0}\n        )\n        ok_type = ok_map.get(node, current_type) if ok_map is not None else UninhabitedType()\n        rest_type = rest_map.get(node, current_type) if rest_map is not None else UninhabitedType()\n        return PatternType(ok_type, rest_type, {})\n\n    def visit_singleton_pattern(self, o: SingletonPattern) -> PatternType:\n        current_type = self.type_context[-1]\n        value: bool | None = o.value\n        if isinstance(value, bool):\n            typ = self.chk.expr_checker.infer_literal_expr_type(value, \"builtins.bool\")\n        elif value is None:\n            typ = NoneType()\n        else:\n            assert False\n\n        narrowed_type, rest_type = self.chk.conditional_types_with_intersection(\n            current_type, [get_type_range(typ)], o, default=current_type\n        )\n        return PatternType(narrowed_type, rest_type, {})\n\n    def visit_sequence_pattern(self, o: SequencePattern) -> PatternType:\n        #\n        # Step 1. Check for existence of a starred pattern\n        #\n        current_type = get_proper_type(self.type_context[-1])\n        if not self.can_match_sequence(current_type):\n            return self.early_non_match()\n\n        star_positions = [i for i, p in enumerate(o.patterns) if isinstance(p, StarredPattern)]\n        star_position: int | None = None\n        if len(star_positions) == 1:\n            star_position = star_positions[0]\n        elif len(star_positions) >= 2:\n            assert False, \"Parser should prevent multiple starred patterns\"\n        required_patterns = len(o.patterns)\n        if star_position is not None:\n            required_patterns -= 1\n\n        #\n        # Step 2. If we have a union, recurse and return the combined result\n        #\n        if isinstance(current_type, UnionType):\n            match_types: list[Type] = []\n            rest_types: list[Type] = []\n            captures_list: dict[Expression, list[Type]] = {}\n\n            if star_position is not None:\n                star_pattern = o.patterns[star_position]\n                assert isinstance(star_pattern, StarredPattern)\n                star_expr = star_pattern.capture\n            else:\n                star_expr = None\n\n            for t in current_type.items:\n                match_type, rest_type, captures = self.accept(o, t)\n                match_types.append(match_type)\n                rest_types.append(rest_type)\n                if not is_uninhabited(match_type):\n                    for expr, typ in captures.items():\n                        p_typ = get_proper_type(typ)\n                        if expr not in captures_list:\n                            captures_list[expr] = []\n                        # Avoid adding in a list[Never] for empty list captures\n                        if (\n                            expr == star_expr\n                            and isinstance(p_typ, Instance)\n                            and p_typ.type.fullname == \"builtins.list\"\n                            and is_uninhabited(p_typ.args[0])\n                        ):\n                            continue\n                        captures_list[expr].append(typ)\n\n            return PatternType(\n                make_simplified_union(match_types),\n                make_simplified_union(rest_types),\n                {expr: make_simplified_union(types) for expr, types in captures_list.items()},\n            )\n\n        #\n        # Step 3. Get inner types of original type\n        #\n        unpack_index = None\n        if isinstance(current_type, TupleType):\n            inner_types: list[Type] = current_type.items\n            unpack_index = find_unpack_in_list(inner_types)\n            if unpack_index is None:\n                size_diff = len(inner_types) - required_patterns\n                if size_diff < 0:\n                    return self.early_non_match()\n                elif size_diff > 0 and star_position is None:\n                    return self.early_non_match()\n            else:\n                normalized_inner_types = []\n                for it in inner_types:\n                    # Unfortunately, it is not possible to \"split\" the TypeVarTuple\n                    # into individual items, so we just use its upper bound for the whole\n                    # analysis instead.\n                    if isinstance(it, UnpackType) and isinstance(it.type, TypeVarTupleType):\n                        it = UnpackType(it.type.upper_bound)\n                    normalized_inner_types.append(it)\n                inner_types = normalized_inner_types\n                current_type = current_type.copy_modified(items=normalized_inner_types)\n                if len(inner_types) - 1 > required_patterns and star_position is None:\n                    return self.early_non_match()\n        elif isinstance(current_type, AnyType):\n            inner_type = AnyType(TypeOfAny.from_another_any, current_type)\n            inner_types = [inner_type] * len(o.patterns)\n        elif isinstance(current_type, Instance) and self.chk.type_is_iterable(current_type):\n            inner_type = self.chk.iterable_item_type(current_type, o)\n            inner_types = [inner_type] * len(o.patterns)\n        else:\n            inner_type = self.chk.named_type(\"builtins.object\")\n            inner_types = [inner_type] * len(o.patterns)\n\n        #\n        # Step 4. Match inner patterns\n        #\n        contracted_new_inner_types: list[Type] = []\n        contracted_rest_inner_types: list[Type] = []\n        captures = {}  # dict[Expression, Type]\n\n        contracted_inner_types = self.contract_starred_pattern_types(\n            inner_types, star_position, required_patterns\n        )\n        for p, t in zip(o.patterns, contracted_inner_types):\n            pattern_type = self.accept(p, t)\n            typ, rest, type_map = pattern_type\n            contracted_new_inner_types.append(typ)\n            contracted_rest_inner_types.append(rest)\n            self.update_type_map(captures, type_map)\n\n        new_inner_types = self.expand_starred_pattern_types(\n            contracted_new_inner_types, star_position, len(inner_types), unpack_index is not None\n        )\n        rest_inner_types = self.expand_starred_pattern_types(\n            contracted_rest_inner_types, star_position, len(inner_types), unpack_index is not None\n        )\n\n        #\n        # Step 5. Calculate new type\n        #\n        new_type: Type\n        rest_type = current_type\n        if isinstance(current_type, TupleType) and unpack_index is None:\n            if any(is_uninhabited(typ) for typ in new_inner_types):\n                new_type = UninhabitedType()\n            else:\n                new_type = TupleType(new_inner_types, current_type.partial_fallback)\n\n            num_always_match = sum(is_uninhabited(typ) for typ in rest_inner_types)\n            if num_always_match == len(rest_inner_types):\n                # All subpatterns always match, so we can apply negative narrowing\n                rest_type = UninhabitedType()\n            elif num_always_match == len(rest_inner_types) - 1:\n                # Exactly one subpattern may conditionally match, the rest always match.\n                # We can apply negative narrowing to this one position.\n                rest_type = TupleType(\n                    [\n                        curr if is_uninhabited(rest) else rest\n                        for curr, rest in zip(inner_types, rest_inner_types)\n                    ],\n                    current_type.partial_fallback,\n                )\n        elif isinstance(current_type, TupleType):\n            # For variadic tuples it is too tricky to match individual items like for fixed\n            # tuples, so we instead try to narrow the entire type.\n            # TODO: use more precise narrowing when possible (e.g. for identical shapes).\n            new_tuple_type = TupleType(new_inner_types, current_type.partial_fallback)\n            new_type, rest_type = self.chk.conditional_types_with_intersection(\n                new_tuple_type, [get_type_range(current_type)], o, default=new_tuple_type\n            )\n        else:\n            new_inner_type = UninhabitedType()\n            for typ in new_inner_types:\n                new_inner_type = join_types(new_inner_type, typ)\n            new_type = self.construct_sequence_child(current_type, new_inner_type)\n            new_type, possible_rest_type = self.chk.conditional_types_with_intersection(\n                current_type, [get_type_range(new_type)], o, default=current_type\n            )\n            if star_position is not None and len(o.patterns) == 1:\n                # Match cannot be refuted, so narrow the remaining type\n                rest_type = possible_rest_type\n\n        return PatternType(new_type, rest_type, captures)\n\n    def contract_starred_pattern_types(\n        self, types: list[Type], star_pos: int | None, num_patterns: int\n    ) -> list[Type]:\n        \"\"\"\n        Contracts a list of types in a sequence pattern depending on the position of a starred\n        capture pattern.\n\n        For example if the sequence pattern [a, *b, c] is matched against types [bool, int, str,\n        bytes] the contracted types are [bool, Union[int, str], bytes].\n\n        If star_pos in None the types are returned unchanged.\n        \"\"\"\n        unpack_index = find_unpack_in_list(types)\n        if unpack_index is not None:\n            # Variadic tuples require \"re-shaping\" to match the requested pattern.\n            unpack = types[unpack_index]\n            assert isinstance(unpack, UnpackType)\n            unpacked = get_proper_type(unpack.type)\n            # This should be guaranteed by the normalization in the caller.\n            assert isinstance(unpacked, Instance) and unpacked.type.fullname == \"builtins.tuple\"\n            if star_pos is None:\n                missing = num_patterns - len(types) + 1\n                new_types = types[:unpack_index]\n                new_types += [unpacked.args[0]] * missing\n                new_types += types[unpack_index + 1 :]\n                return new_types\n            prefix, middle, suffix = split_with_prefix_and_suffix(\n                tuple([UnpackType(unpacked) if isinstance(t, UnpackType) else t for t in types]),\n                star_pos,\n                num_patterns - star_pos,\n            )\n            new_middle = []\n            for m in middle:\n                # The existing code expects the star item type, rather than the type of\n                # the whole tuple \"slice\".\n                if isinstance(m, UnpackType):\n                    new_middle.append(unpacked.args[0])\n                else:\n                    new_middle.append(m)\n            return list(prefix) + [make_simplified_union(new_middle)] + list(suffix)\n        else:\n            if star_pos is None:\n                return types\n            new_types = types[:star_pos]\n            star_length = len(types) - num_patterns\n            new_types.append(make_simplified_union(types[star_pos : star_pos + star_length]))\n            new_types += types[star_pos + star_length :]\n            return new_types\n\n    def expand_starred_pattern_types(\n        self, types: list[Type], star_pos: int | None, num_types: int, original_unpack: bool\n    ) -> list[Type]:\n        \"\"\"Undoes the contraction done by contract_starred_pattern_types.\n\n        For example if the sequence pattern is [a, *b, c] and types [bool, int, str] are extended\n        to length 4 the result is [bool, int, int, str].\n        \"\"\"\n        if star_pos is None:\n            return types\n        if original_unpack:\n            # In the case where original tuple type has an unpack item, it is not practical\n            # to coerce pattern type back to the original shape (and may not even be possible),\n            # so we only restore the type of the star item.\n            res = []\n            for i, t in enumerate(types):\n                if i != star_pos:\n                    res.append(t)\n                else:\n                    res.append(UnpackType(self.chk.named_generic_type(\"builtins.tuple\", [t])))\n            return res\n        new_types = types[:star_pos]\n        star_length = num_types - len(types) + 1\n        new_types += [types[star_pos]] * star_length\n        new_types += types[star_pos + 1 :]\n\n        return new_types\n\n    def visit_starred_pattern(self, o: StarredPattern) -> PatternType:\n        captures: dict[Expression, Type] = {}\n        if o.capture is not None:\n            list_type = self.chk.named_generic_type(\"builtins.list\", [self.type_context[-1]])\n            captures[o.capture] = list_type\n        return PatternType(self.type_context[-1], UninhabitedType(), captures)\n\n    def visit_mapping_pattern(self, o: MappingPattern) -> PatternType:\n        current_type = get_proper_type(self.type_context[-1])\n        can_match = True\n        captures: dict[Expression, Type] = {}\n        for key, value in zip(o.keys, o.values):\n            inner_type = self.get_mapping_item_type(o, current_type, key)\n            if inner_type is None:\n                can_match = False\n                inner_type = self.chk.named_type(\"builtins.object\")\n            pattern_type = self.accept(value, inner_type)\n            if is_uninhabited(pattern_type.type):\n                can_match = False\n            else:\n                self.update_type_map(captures, pattern_type.captures)\n\n        if o.rest is not None:\n            mapping = self.chk.named_type(\"typing.Mapping\")\n            if is_subtype(current_type, mapping) and isinstance(current_type, Instance):\n                mapping_inst = map_instance_to_supertype(current_type, mapping.type)\n                dict_typeinfo = self.chk.lookup_typeinfo(\"builtins.dict\")\n                rest_type = Instance(dict_typeinfo, mapping_inst.args)\n            else:\n                object_type = self.chk.named_type(\"builtins.object\")\n                rest_type = self.chk.named_generic_type(\n                    \"builtins.dict\", [object_type, object_type]\n                )\n\n            captures[o.rest] = rest_type\n\n        else_type = current_type\n        if can_match:\n            # We can't narrow the type here, as Mapping key is invariant.\n            new_type = self.type_context[-1]\n            if not o.keys:\n                # Match cannot be refuted, so narrow the remaining type\n                mapping = self.chk.named_type(\"typing.Mapping\")\n                if_type, else_type = self.chk.conditional_types_with_intersection(\n                    current_type,\n                    [TypeRange(mapping, is_upper_bound=False)],\n                    o,\n                    default=current_type,\n                )\n                if not isinstance(current_type, AnyType):\n                    new_type = if_type\n        else:\n            new_type = UninhabitedType()\n        return PatternType(new_type, else_type, captures)\n\n    def get_mapping_item_type(\n        self, pattern: MappingPattern, mapping_type: Type, key: Expression\n    ) -> Type | None:\n        mapping_type = get_proper_type(mapping_type)\n        if isinstance(mapping_type, TypedDictType):\n            with self.msg.filter_errors() as local_errors:\n                result: Type | None = self.chk.expr_checker.visit_typeddict_index_expr(\n                    mapping_type, key\n                )[0]\n                has_local_errors = local_errors.has_new_errors()\n            # If we can't determine the type statically fall back to treating it as a normal\n            # mapping\n            if has_local_errors:\n                with self.msg.filter_errors() as local_errors:\n                    result = self.get_simple_mapping_item_type(pattern, mapping_type, key)\n\n                    if local_errors.has_new_errors():\n                        result = None\n        else:\n            with self.msg.filter_errors():\n                result = self.get_simple_mapping_item_type(pattern, mapping_type, key)\n        return result\n\n    def get_simple_mapping_item_type(\n        self, pattern: MappingPattern, mapping_type: Type, key: Expression\n    ) -> Type:\n        result, _ = self.chk.expr_checker.check_method_call_by_name(\n            \"__getitem__\", mapping_type, [key], [ARG_POS], pattern\n        )\n        return result\n\n    def visit_class_pattern(self, o: ClassPattern) -> PatternType:\n        current_type = get_proper_type(self.type_context[-1])\n\n        #\n        # Check class type\n        #\n        type_info = o.class_ref.node\n        if isinstance(type_info, TypeAlias) and not type_info.no_args:\n            self.msg.fail(message_registry.CLASS_PATTERN_GENERIC_TYPE_ALIAS, o)\n            return self.early_non_match()\n\n        typ = self.chk.expr_checker.accept(o.class_ref)\n        type_ranges = self.get_class_pattern_type_ranges(typ, o)\n        if type_ranges is None:\n            return self.early_non_match()\n        typ = UnionType.make_union([t.item for t in type_ranges])\n\n        new_type, rest_type = self.chk.conditional_types_with_intersection(\n            current_type, type_ranges, o, default=current_type\n        )\n        if is_uninhabited(new_type):\n            return self.early_non_match()\n        # TODO: Do I need this?\n        narrowed_type = narrow_declared_type(current_type, new_type)\n\n        #\n        # Convert positional to keyword patterns\n        #\n        keyword_pairs: list[tuple[str | None, Pattern]] = []\n        match_arg_set: set[str] = set()\n\n        captures: dict[Expression, Type] = {}\n\n        if len(o.positionals) != 0:\n            if self.should_self_match(typ):\n                if len(o.positionals) > 1:\n                    self.msg.fail(message_registry.CLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS, o)\n                pattern_type = self.accept(o.positionals[0], narrowed_type)\n                if not is_uninhabited(pattern_type.type):\n                    return PatternType(\n                        pattern_type.type,\n                        join_types(rest_type, pattern_type.rest_type),\n                        pattern_type.captures,\n                    )\n                captures = pattern_type.captures\n            else:\n                with self.msg.filter_errors() as local_errors:\n                    match_args_type = analyze_member_access(\n                        \"__match_args__\",\n                        typ,\n                        o,\n                        is_lvalue=False,\n                        is_super=False,\n                        is_operator=False,\n                        original_type=typ,\n                        chk=self.chk,\n                    )\n                    has_local_errors = local_errors.has_new_errors()\n                if has_local_errors:\n                    self.msg.fail(\n                        message_registry.MISSING_MATCH_ARGS.format(\n                            typ.str_with_options(self.options)\n                        ),\n                        o,\n                    )\n                    return self.early_non_match()\n\n                proper_match_args_type = get_proper_type(match_args_type)\n                if isinstance(proper_match_args_type, TupleType):\n                    match_arg_names = get_match_arg_names(proper_match_args_type)\n\n                    if len(o.positionals) > len(match_arg_names):\n                        self.msg.fail(message_registry.CLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS, o)\n                        return self.early_non_match()\n                else:\n                    match_arg_names = [None] * len(o.positionals)\n\n                for arg_name, pos in zip(match_arg_names, o.positionals):\n                    keyword_pairs.append((arg_name, pos))\n                    if arg_name is not None:\n                        match_arg_set.add(arg_name)\n\n        #\n        # Check for duplicate patterns\n        #\n        keyword_arg_set = set()\n        has_duplicates = False\n        for key, value in zip(o.keyword_keys, o.keyword_values):\n            keyword_pairs.append((key, value))\n            if key in match_arg_set:\n                self.msg.fail(\n                    message_registry.CLASS_PATTERN_KEYWORD_MATCHES_POSITIONAL.format(key), value\n                )\n                has_duplicates = True\n            elif key in keyword_arg_set:\n                self.msg.fail(\n                    message_registry.CLASS_PATTERN_DUPLICATE_KEYWORD_PATTERN.format(key), value\n                )\n                has_duplicates = True\n            keyword_arg_set.add(key)\n\n        if has_duplicates:\n            return self.early_non_match()\n\n        #\n        # Check keyword patterns\n        #\n        can_match = True\n        for keyword, pattern in keyword_pairs:\n            key_type: Type | None = None\n            with self.msg.filter_errors() as local_errors:\n                if keyword is not None:\n                    key_type = analyze_member_access(\n                        keyword,\n                        narrowed_type,\n                        pattern,\n                        is_lvalue=False,\n                        is_super=False,\n                        is_operator=False,\n                        original_type=new_type,\n                        chk=self.chk,\n                    )\n                else:\n                    key_type = AnyType(TypeOfAny.from_error)\n                has_local_errors = local_errors.has_new_errors()\n            if has_local_errors or key_type is None:\n                key_type = AnyType(TypeOfAny.from_error)\n                if not (type_info and type_info.fullname == \"builtins.object\"):\n                    self.msg.fail(\n                        message_registry.CLASS_PATTERN_UNKNOWN_KEYWORD.format(\n                            typ.str_with_options(self.options), keyword\n                        ),\n                        pattern,\n                    )\n                elif keyword is not None:\n                    new_type = self.chk.add_any_attribute_to_type(new_type, keyword)\n\n            inner_type, inner_rest_type, inner_captures = self.accept(pattern, key_type)\n            if is_uninhabited(inner_type):\n                can_match = False\n            else:\n                self.update_type_map(captures, inner_captures)\n                if not is_uninhabited(inner_rest_type):\n                    rest_type = current_type\n\n        if not can_match:\n            new_type = UninhabitedType()\n        return PatternType(new_type, rest_type, captures)\n\n    def get_class_pattern_type_ranges(self, typ: Type, o: ClassPattern) -> list[TypeRange] | None:\n        p_typ = get_proper_type(typ)\n\n        if isinstance(p_typ, UnionType):\n            type_ranges = []\n            for item in p_typ.items:\n                type_range = self.get_class_pattern_type_ranges(item, o)\n                if type_range is not None:\n                    type_ranges.extend(type_range)\n            if not type_ranges:\n                return None\n            return type_ranges\n\n        if isinstance(p_typ, FunctionLike) and p_typ.is_type_obj():\n            typ = fill_typevars_with_any(p_typ.type_object())\n            return [TypeRange(typ, is_upper_bound=False)]\n        if (\n            isinstance(o.class_ref.node, Var)\n            and o.class_ref.node.type is not None\n            and o.class_ref.node.fullname == \"typing.Callable\"\n        ):\n            # Create a `Callable[..., Any]`\n            fallback = self.chk.named_type(\"builtins.function\")\n            any_type = AnyType(TypeOfAny.unannotated)\n            typ = callable_with_ellipsis(any_type, ret_type=any_type, fallback=fallback)\n            return [TypeRange(typ, is_upper_bound=False)]\n        if isinstance(p_typ, TypeType):\n            typ = p_typ.item\n            return [TypeRange(p_typ.item, is_upper_bound=True)]\n        if isinstance(p_typ, AnyType):\n            return [TypeRange(p_typ, is_upper_bound=False)]\n\n        self.msg.fail(\n            message_registry.CLASS_PATTERN_TYPE_REQUIRED.format(\n                typ.str_with_options(self.options)\n            ),\n            o,\n        )\n        return None\n\n    def should_self_match(self, typ: Type) -> bool:\n        typ = get_proper_type(typ)\n        if isinstance(typ, TupleType):\n            typ = typ.partial_fallback\n        if isinstance(typ, AnyType):\n            return False\n        if isinstance(typ, Instance) and typ.type.get(\"__match_args__\") is not None:\n            # Named tuples and other subtypes of builtins that define __match_args__\n            # should not self match.\n            return False\n        for other in self.self_match_types:\n            if is_subtype(typ, other):\n                return True\n        return False\n\n    def can_match_sequence(self, typ: ProperType) -> bool:\n        if isinstance(typ, AnyType):\n            return True\n        if isinstance(typ, UnionType):\n            return any(self.can_match_sequence(get_proper_type(item)) for item in typ.items)\n        for other in self.non_sequence_match_types:\n            # We have to ignore promotions, as memoryview should match, but bytes,\n            # which it can be promoted to, shouldn't\n            if is_subtype(typ, other, ignore_promotions=True):\n                return False\n        sequence = self.chk.named_type(\"typing.Sequence\")\n        # If the static type is more general than sequence the actual type could still match\n        return is_subtype(typ, sequence) or is_subtype(sequence, typ)\n\n    def generate_types_from_names(self, type_names: list[str]) -> list[Type]:\n        types: list[Type] = []\n        for name in type_names:\n            try:\n                types.append(self.chk.named_type(name))\n            except KeyError as e:\n                # Some built in types are not defined in all test cases\n                if not name.startswith(\"builtins.\"):\n                    raise e\n        return types\n\n    def update_type_map(\n        self, original_type_map: dict[Expression, Type], extra_type_map: dict[Expression, Type]\n    ) -> None:\n        # Calculating this would not be needed if TypeMap directly used literal hashes instead of\n        # expressions, as suggested in the TODO above it's definition\n        already_captured = {literal_hash(expr) for expr in original_type_map}\n        for expr, typ in extra_type_map.items():\n            if literal_hash(expr) in already_captured:\n                node = get_var(expr)\n                self.msg.fail(\n                    message_registry.MULTIPLE_ASSIGNMENTS_IN_PATTERN.format(node.name), expr\n                )\n            else:\n                original_type_map[expr] = typ\n\n    def construct_sequence_child(self, outer_type: Type, inner_type: Type) -> Type:\n        \"\"\"\n        If outer_type is a child class of typing.Sequence returns a new instance of\n        outer_type, that is a Sequence of inner_type. If outer_type is not a child class of\n        typing.Sequence just returns a Sequence of inner_type\n\n        For example:\n        construct_sequence_child(List[int], str) = List[str]\n\n        TODO: this doesn't make sense. For example if one has class S(Sequence[int], Generic[T])\n        or class T(Sequence[Tuple[T, T]]), there is no way any of those can map to Sequence[str].\n        \"\"\"\n        proper_type = get_proper_type(outer_type)\n        if isinstance(proper_type, TypeVarType):\n            new_bound = self.construct_sequence_child(proper_type.upper_bound, inner_type)\n            return proper_type.copy_modified(upper_bound=new_bound)\n        if isinstance(proper_type, AnyType):\n            return outer_type\n        if isinstance(proper_type, UnionType):\n            types = [\n                self.construct_sequence_child(item, inner_type)\n                for item in proper_type.items\n                if self.can_match_sequence(get_proper_type(item))\n            ]\n            return make_simplified_union(types)\n        sequence = self.chk.named_generic_type(\"typing.Sequence\", [inner_type])\n        if is_subtype(outer_type, self.chk.named_type(\"typing.Sequence\")):\n            if isinstance(proper_type, TupleType):\n                proper_type = tuple_fallback(proper_type)\n            assert isinstance(proper_type, Instance)\n            empty_type = fill_typevars(proper_type.type)\n            partial_type = expand_type_by_instance(empty_type, sequence)\n            return expand_type_by_instance(partial_type, proper_type)\n        else:\n            return sequence\n\n    def early_non_match(self) -> PatternType:\n        return PatternType(UninhabitedType(), self.type_context[-1], {})\n\n\ndef get_match_arg_names(typ: TupleType) -> list[str | None]:\n    args: list[str | None] = []\n    for item in typ.items:\n        values = try_getting_str_literals_from_type(item)\n        if values is None or len(values) != 1:\n            args.append(None)\n        else:\n            args.append(values[0])\n    return args\n\n\ndef get_var(expr: Expression) -> Var:\n    \"\"\"\n    Warning: this in only true for expressions captured by a match statement.\n    Don't call it from anywhere else\n    \"\"\"\n    assert isinstance(expr, NameExpr), expr\n    node = expr.node\n    assert isinstance(node, Var), node\n    return node\n\n\ndef get_type_range(typ: Type) -> TypeRange:\n    typ = get_proper_type(typ)\n    if (\n        isinstance(typ, Instance)\n        and typ.last_known_value\n        and isinstance(typ.last_known_value.value, bool)\n    ):\n        typ = typ.last_known_value\n    return TypeRange(typ, is_upper_bound=False)\n\n\ndef is_uninhabited(typ: Type) -> bool:\n    return isinstance(get_proper_type(typ), UninhabitedType)\n"
  },
  {
    "path": "mypy/checkstrformat.py",
    "content": "\"\"\"\nFormat expression type checker.\n\nThis file is conceptually part of ExpressionChecker and TypeChecker. Main functionality\nis located in StringFormatterChecker.check_str_format_call() for '{}'.format(), and in\nStringFormatterChecker.check_str_interpolation() for printf-style % interpolation.\n\nNote that although at runtime format strings are parsed using custom parsers,\nhere we use a regexp-based approach. This way we 99% match runtime behaviour while keeping\nimplementation simple.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom collections.abc import Callable\nfrom re import Match, Pattern\nfrom typing import Final, TypeAlias as _TypeAlias, cast\n\nimport mypy.errorcodes as codes\nfrom mypy import message_registry\nfrom mypy.checker_shared import TypeCheckerSharedApi\nfrom mypy.errors import Errors\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.messages import MessageBuilder\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    BytesExpr,\n    CallExpr,\n    Context,\n    DictExpr,\n    Expression,\n    ExpressionStmt,\n    IndexExpr,\n    IntExpr,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    Node,\n    StarExpr,\n    StrExpr,\n    TempNode,\n    TupleExpr,\n)\nfrom mypy.parse import parse\nfrom mypy.subtypes import is_subtype\nfrom mypy.typeops import custom_special_method\nfrom mypy.types import (\n    AnyType,\n    Instance,\n    LiteralType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeVarTupleType,\n    TypeVarType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    get_proper_type,\n    get_proper_types,\n)\n\nFormatStringExpr: _TypeAlias = StrExpr | BytesExpr\nCheckers: _TypeAlias = tuple[Callable[[Expression], None], Callable[[Type], bool]]\nMatchMap: _TypeAlias = dict[tuple[int, int], Match[str]]  # span -> match\n\n\ndef compile_format_re() -> Pattern[str]:\n    \"\"\"Construct regexp to match format conversion specifiers in % interpolation.\n\n    See https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting\n    The regexp is intentionally a bit wider to report better errors.\n    \"\"\"\n    key_re = r\"(\\((?P<key>[^)]*)\\))?\"  # (optional) parenthesised sequence of characters.\n    flags_re = r\"(?P<flags>[#0\\-+ ]*)\"  # (optional) sequence of flags.\n    width_re = r\"(?P<width>[1-9][0-9]*|\\*)?\"  # (optional) minimum field width (* or numbers).\n    precision_re = r\"(?:\\.(?P<precision>\\*|[0-9]+)?)?\"  # (optional) . followed by * of numbers.\n    length_mod_re = r\"[hlL]?\"  # (optional) length modifier (unused).\n    type_re = r\"(?P<type>.)?\"  # conversion type.\n    format_re = \"%\" + key_re + flags_re + width_re + precision_re + length_mod_re + type_re\n    return re.compile(format_re)\n\n\ndef compile_new_format_re(custom_spec: bool) -> Pattern[str]:\n    \"\"\"Construct regexps to match format conversion specifiers in str.format() calls.\n\n    See After https://docs.python.org/3/library/string.html#formatspec for\n    specifications. The regexps are intentionally wider, to report better errors,\n    instead of just not matching.\n    \"\"\"\n\n    # Field (optional) is an integer/identifier possibly followed by several .attr and [index].\n    field = r\"(?P<field>(?P<key>[^.[!:]*)([^:!]+)?)\"\n\n    # Conversion (optional) is ! followed by one of letters for forced repr(), str(), or ascii().\n    conversion = r\"(?P<conversion>![^:])?\"\n\n    # Format specification (optional) follows its own mini-language:\n    if not custom_spec:\n        # Fill and align is valid for all builtin types.\n        fill_align = r\"(?P<fill_align>.?[<>=^])?\"\n        # Number formatting options are only valid for int, float, complex, and Decimal,\n        # except if only width is given (it is valid for all types).\n        # This contains sign, flags (sign, # and/or 0), width, grouping (_ or ,) and precision.\n        num_spec = r\"(?P<flags>[+\\- ]?#?0?)(?P<width>\\d+)?[_,]?(?P<precision>\\.\\d+)?\"\n        # The last element is type.\n        conv_type = r\"(?P<type>.)?\"  # only some are supported, but we want to give a better error\n        format_spec = r\"(?P<format_spec>:\" + fill_align + num_spec + conv_type + r\")?\"\n    else:\n        # Custom types can define their own form_spec using __format__().\n        format_spec = r\"(?P<format_spec>:.*)?\"\n\n    return re.compile(field + conversion + format_spec)\n\n\nFORMAT_RE: Final = compile_format_re()\nFORMAT_RE_NEW: Final = compile_new_format_re(False)\nFORMAT_RE_NEW_CUSTOM: Final = compile_new_format_re(True)\nDUMMY_FIELD_NAME: Final = \"__dummy_name__\"\n\n# Types that require either int or float.\nNUMERIC_TYPES_OLD: Final = {\"d\", \"i\", \"o\", \"u\", \"x\", \"X\", \"e\", \"E\", \"f\", \"F\", \"g\", \"G\"}\nNUMERIC_TYPES_NEW: Final = {\"b\", \"d\", \"o\", \"e\", \"E\", \"f\", \"F\", \"g\", \"G\", \"n\", \"x\", \"X\", \"%\"}\n\n# These types accept _only_ int.\nREQUIRE_INT_OLD: Final = {\"o\", \"x\", \"X\"}\nREQUIRE_INT_NEW: Final = {\"b\", \"d\", \"o\", \"x\", \"X\"}\n\n# These types fall back to SupportsFloat with % (other fall back to SupportsInt)\nFLOAT_TYPES: Final = {\"e\", \"E\", \"f\", \"F\", \"g\", \"G\"}\n\n\nclass ConversionSpecifier:\n    def __init__(\n        self, match: Match[str], start_pos: int = -1, non_standard_format_spec: bool = False\n    ) -> None:\n        self.whole_seq = match.group()\n        self.start_pos = start_pos\n\n        m_dict = match.groupdict()\n        self.key = m_dict.get(\"key\")\n\n        # Replace unmatched optional groups with empty matches (for convenience).\n        self.conv_type = m_dict.get(\"type\") or \"\"\n        self.flags = m_dict.get(\"flags\") or \"\"\n        self.width = m_dict.get(\"width\") or \"\"\n        self.precision = m_dict.get(\"precision\") or \"\"\n\n        # Used only for str.format() calls (it may be custom for types with __format__()).\n        self.format_spec = m_dict.get(\"format_spec\")\n        self.non_standard_format_spec = non_standard_format_spec\n        # Used only for str.format() calls.\n        self.conversion = m_dict.get(\"conversion\")\n        # Full formatted expression (i.e. key plus following attributes and/or indexes).\n        # Used only for str.format() calls.\n        self.field = m_dict.get(\"field\")\n\n    def has_key(self) -> bool:\n        return self.key is not None\n\n    def has_star(self) -> bool:\n        return self.width == \"*\" or self.precision == \"*\"\n\n\ndef parse_conversion_specifiers(format_str: str) -> list[ConversionSpecifier]:\n    \"\"\"Parse c-printf-style format string into list of conversion specifiers.\"\"\"\n    specifiers: list[ConversionSpecifier] = []\n    for m in re.finditer(FORMAT_RE, format_str):\n        specifiers.append(ConversionSpecifier(m, start_pos=m.start()))\n    return specifiers\n\n\ndef parse_format_value(\n    format_value: str, ctx: Context, msg: MessageBuilder, nested: bool = False\n) -> list[ConversionSpecifier] | None:\n    \"\"\"Parse format string into list of conversion specifiers.\n\n    The specifiers may be nested (two levels maximum), in this case they are ordered as\n    '{0:{1}}, {2:{3}{4}}'. Return None in case of an error.\n    \"\"\"\n    top_targets = find_non_escaped_targets(format_value, ctx, msg)\n    if top_targets is None:\n        return None\n\n    result: list[ConversionSpecifier] = []\n    for target, start_pos in top_targets:\n        match = FORMAT_RE_NEW.fullmatch(target)\n        if match:\n            conv_spec = ConversionSpecifier(match, start_pos=start_pos)\n        else:\n            custom_match = FORMAT_RE_NEW_CUSTOM.fullmatch(target)\n            if custom_match:\n                conv_spec = ConversionSpecifier(\n                    custom_match, start_pos=start_pos, non_standard_format_spec=True\n                )\n            else:\n                msg.fail(\n                    \"Invalid conversion specifier in format string\",\n                    ctx,\n                    code=codes.STRING_FORMATTING,\n                )\n                return None\n\n        if conv_spec.key and (\"{\" in conv_spec.key or \"}\" in conv_spec.key):\n            msg.fail(\"Conversion value must not contain { or }\", ctx, code=codes.STRING_FORMATTING)\n            return None\n        result.append(conv_spec)\n\n        # Parse nested conversions that are allowed in format specifier.\n        if (\n            conv_spec.format_spec\n            and conv_spec.non_standard_format_spec\n            and (\"{\" in conv_spec.format_spec or \"}\" in conv_spec.format_spec)\n        ):\n            if nested:\n                msg.fail(\n                    \"Formatting nesting must be at most two levels deep\",\n                    ctx,\n                    code=codes.STRING_FORMATTING,\n                )\n                return None\n            sub_conv_specs = parse_format_value(conv_spec.format_spec, ctx, msg, nested=True)\n            if sub_conv_specs is None:\n                return None\n            result.extend(sub_conv_specs)\n    return result\n\n\ndef find_non_escaped_targets(\n    format_value: str, ctx: Context, msg: MessageBuilder\n) -> list[tuple[str, int]] | None:\n    \"\"\"Return list of raw (un-parsed) format specifiers in format string.\n\n    Format specifiers don't include enclosing braces. We don't use regexp for\n    this because they don't work well with nested/repeated patterns\n    (both greedy and non-greedy), and these are heavily used internally for\n    representation of f-strings.\n\n    Return None in case of an error.\n    \"\"\"\n    result = []\n    next_spec = \"\"\n    pos = 0\n    nesting = 0\n    while pos < len(format_value):\n        c = format_value[pos]\n        if not nesting:\n            # Skip any paired '{{' and '}}', enter nesting on '{', report error on '}'.\n            if c == \"{\":\n                if pos < len(format_value) - 1 and format_value[pos + 1] == \"{\":\n                    pos += 1\n                else:\n                    nesting = 1\n            if c == \"}\":\n                if pos < len(format_value) - 1 and format_value[pos + 1] == \"}\":\n                    pos += 1\n                else:\n                    msg.fail(\n                        \"Invalid conversion specifier in format string: unexpected }\",\n                        ctx,\n                        code=codes.STRING_FORMATTING,\n                    )\n                    return None\n        else:\n            # Adjust nesting level, then either continue adding chars or move on.\n            if c == \"{\":\n                nesting += 1\n            if c == \"}\":\n                nesting -= 1\n            if nesting:\n                next_spec += c\n            else:\n                result.append((next_spec, pos - len(next_spec)))\n                next_spec = \"\"\n        pos += 1\n    if nesting:\n        msg.fail(\n            \"Invalid conversion specifier in format string: unmatched {\",\n            ctx,\n            code=codes.STRING_FORMATTING,\n        )\n        return None\n    return result\n\n\nclass StringFormatterChecker:\n    \"\"\"String interpolation/formatter type checker.\n\n    This class works closely together with checker.ExpressionChecker.\n    \"\"\"\n\n    # Some services are provided by a TypeChecker instance.\n    chk: TypeCheckerSharedApi\n    # This is shared with TypeChecker, but stored also here for convenience.\n    msg: MessageBuilder\n\n    def __init__(self, chk: TypeCheckerSharedApi, msg: MessageBuilder) -> None:\n        \"\"\"Construct an expression type checker.\"\"\"\n        self.chk = chk\n        self.msg = msg\n\n    def check_str_format_call(self, call: CallExpr, format_value: str) -> None:\n        \"\"\"Perform more precise checks for str.format() calls when possible.\n\n        Currently the checks are performed for:\n          * Actual string literals\n          * Literal types with string values\n          * Final names with string values\n\n        The checks that we currently perform:\n          * Check generic validity (e.g. unmatched { or }, and {} in invalid positions)\n          * Check consistency of specifiers' auto-numbering\n          * Verify that replacements can be found for all conversion specifiers,\n            and all arguments were used\n          * Non-standard format specs are only allowed for types with custom __format__\n          * Type check replacements with accessors applied (if any).\n          * Verify that specifier type is known and matches replacement type\n          * Perform special checks for some specifier types:\n            - 'c' requires a single character string\n            - 's' must not accept bytes\n            - non-empty flags are only allowed for numeric types\n        \"\"\"\n        conv_specs = parse_format_value(format_value, call, self.msg)\n        if conv_specs is None:\n            return\n        if not self.auto_generate_keys(conv_specs, call):\n            return\n        self.check_specs_in_format_call(call, conv_specs, format_value)\n\n    def check_specs_in_format_call(\n        self, call: CallExpr, specs: list[ConversionSpecifier], format_value: str\n    ) -> None:\n        \"\"\"Perform pairwise checks for conversion specifiers vs their replacements.\n\n        The core logic for format checking is implemented in this method.\n        \"\"\"\n        assert all(s.key for s in specs), \"Keys must be auto-generated first!\"\n        replacements = self.find_replacements_in_call(call, [cast(str, s.key) for s in specs])\n        assert len(replacements) == len(specs)\n        for spec, repl in zip(specs, replacements):\n            repl = self.apply_field_accessors(spec, repl, ctx=call)\n            actual_type = repl.type if isinstance(repl, TempNode) else self.chk.lookup_type(repl)\n            assert actual_type is not None\n\n            # Special case custom formatting.\n            if (\n                spec.format_spec\n                and spec.non_standard_format_spec\n                and\n                # Exclude \"dynamic\" specifiers (i.e. containing nested formatting).\n                not (\"{\" in spec.format_spec or \"}\" in spec.format_spec)\n            ):\n                if (\n                    not custom_special_method(actual_type, \"__format__\", check_all=True)\n                    or spec.conversion\n                ):\n                    # TODO: add support for some custom specs like datetime?\n                    self.msg.fail(\n                        f'Unrecognized format specification \"{spec.format_spec[1:]}\"',\n                        call,\n                        code=codes.STRING_FORMATTING,\n                    )\n                    continue\n            # Adjust expected and actual types.\n            if not spec.conv_type:\n                expected_type: Type | None = AnyType(TypeOfAny.special_form)\n            else:\n                assert isinstance(call.callee, MemberExpr)\n                if isinstance(call.callee.expr, StrExpr):\n                    format_str = call.callee.expr\n                else:\n                    format_str = StrExpr(format_value)\n                expected_type = self.conversion_type(\n                    spec.conv_type, call, format_str, format_call=True\n                )\n            if spec.conversion is not None:\n                # If the explicit conversion is given, then explicit conversion is called _first_.\n                if spec.conversion[1] not in \"rsa\":\n                    self.msg.fail(\n                        (\n                            f'Invalid conversion type \"{spec.conversion[1]}\", '\n                            f'must be one of \"r\", \"s\" or \"a\"'\n                        ),\n                        call,\n                        code=codes.STRING_FORMATTING,\n                    )\n                actual_type = self.named_type(\"builtins.str\")\n\n            # Perform the checks for given types.\n            if expected_type is None:\n                continue\n\n            a_type = get_proper_type(actual_type)\n            actual_items = (\n                get_proper_types(a_type.items) if isinstance(a_type, UnionType) else [a_type]\n            )\n            for a_type in actual_items:\n                if custom_special_method(a_type, \"__format__\"):\n                    continue\n                self.check_placeholder_type(a_type, expected_type, call)\n                self.perform_special_format_checks(spec, call, repl, a_type, expected_type)\n\n    def perform_special_format_checks(\n        self,\n        spec: ConversionSpecifier,\n        call: CallExpr,\n        repl: Expression,\n        actual_type: Type,\n        expected_type: Type,\n    ) -> None:\n        # TODO: try refactoring to combine this logic with % formatting.\n        if spec.conv_type == \"c\":\n            if isinstance(repl, (StrExpr, BytesExpr)) and len(repl.value) != 1:\n                self.msg.requires_int_or_char(call, format_call=True)\n            c_typ = get_proper_type(self.chk.lookup_type(repl))\n            if isinstance(c_typ, Instance) and c_typ.last_known_value:\n                c_typ = c_typ.last_known_value\n            if isinstance(c_typ, LiteralType) and isinstance(c_typ.value, str):\n                if len(c_typ.value) != 1:\n                    self.msg.requires_int_or_char(call, format_call=True)\n        if (not spec.conv_type or spec.conv_type == \"s\") and not spec.conversion:\n            if has_type_component(actual_type, \"builtins.bytes\") and not custom_special_method(\n                actual_type, \"__str__\"\n            ):\n                self.msg.fail(\n                    'If x = b\\'abc\\' then f\"{x}\" or \"{}\".format(x) produces \"b\\'abc\\'\", '\n                    'not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). '\n                    \"Otherwise, decode the bytes\",\n                    call,\n                    code=codes.STR_BYTES_PY3,\n                )\n        if spec.flags:\n            numeric_types = UnionType(\n                [self.named_type(\"builtins.int\"), self.named_type(\"builtins.float\")]\n            )\n            if (\n                spec.conv_type\n                and spec.conv_type not in NUMERIC_TYPES_NEW\n                or not spec.conv_type\n                and not is_subtype(actual_type, numeric_types)\n                and not custom_special_method(actual_type, \"__format__\")\n            ):\n                self.msg.fail(\n                    \"Numeric flags are only allowed for numeric types\",\n                    call,\n                    code=codes.STRING_FORMATTING,\n                )\n\n    def find_replacements_in_call(self, call: CallExpr, keys: list[str]) -> list[Expression]:\n        \"\"\"Find replacement expression for every specifier in str.format() call.\n\n        In case of an error use TempNode(AnyType).\n        \"\"\"\n        result: list[Expression] = []\n        used: set[Expression] = set()\n        for key in keys:\n            if key.isdecimal():\n                expr = self.get_expr_by_position(int(key), call)\n                if not expr:\n                    self.msg.fail(\n                        f\"Cannot find replacement for positional format specifier {key}\",\n                        call,\n                        code=codes.STRING_FORMATTING,\n                    )\n                    expr = TempNode(AnyType(TypeOfAny.from_error))\n            else:\n                expr = self.get_expr_by_name(key, call)\n                if not expr:\n                    self.msg.fail(\n                        f'Cannot find replacement for named format specifier \"{key}\"',\n                        call,\n                        code=codes.STRING_FORMATTING,\n                    )\n                    expr = TempNode(AnyType(TypeOfAny.from_error))\n            result.append(expr)\n            if not isinstance(expr, TempNode):\n                used.add(expr)\n        # Strictly speaking not using all replacements is not a type error, but most likely\n        # a typo in user code, so we show an error like we do for % formatting.\n        total_explicit = len([kind for kind in call.arg_kinds if kind in (ARG_POS, ARG_NAMED)])\n        if len(used) < total_explicit:\n            self.msg.too_many_string_formatting_arguments(call)\n        return result\n\n    def get_expr_by_position(self, pos: int, call: CallExpr) -> Expression | None:\n        \"\"\"Get positional replacement expression from '{0}, {1}'.format(x, y, ...) call.\n\n        If the type is from *args, return TempNode(<item type>). Return None in case of\n        an error.\n        \"\"\"\n        pos_args = [arg for arg, kind in zip(call.args, call.arg_kinds) if kind == ARG_POS]\n        if pos < len(pos_args):\n            return pos_args[pos]\n        star_args = [arg for arg, kind in zip(call.args, call.arg_kinds) if kind == ARG_STAR]\n        if not star_args:\n            return None\n\n        # Fall back to *args when present in call.\n        star_arg = star_args[0]\n        varargs_type = get_proper_type(self.chk.lookup_type(star_arg))\n        if not isinstance(varargs_type, Instance) or not varargs_type.type.has_base(\n            \"typing.Sequence\"\n        ):\n            # Error should be already reported.\n            return TempNode(AnyType(TypeOfAny.special_form))\n        iter_info = self.chk.named_generic_type(\n            \"typing.Sequence\", [AnyType(TypeOfAny.special_form)]\n        ).type\n        return TempNode(map_instance_to_supertype(varargs_type, iter_info).args[0])\n\n    def get_expr_by_name(self, key: str, call: CallExpr) -> Expression | None:\n        \"\"\"Get named replacement expression from '{name}'.format(name=...) call.\n\n        If the type is from **kwargs, return TempNode(<item type>). Return None in case of\n        an error.\n        \"\"\"\n        named_args = [\n            arg\n            for arg, kind, name in zip(call.args, call.arg_kinds, call.arg_names)\n            if kind == ARG_NAMED and name == key\n        ]\n        if named_args:\n            return named_args[0]\n        star_args_2 = [arg for arg, kind in zip(call.args, call.arg_kinds) if kind == ARG_STAR2]\n        if not star_args_2:\n            return None\n        star_arg_2 = star_args_2[0]\n        kwargs_type = get_proper_type(self.chk.lookup_type(star_arg_2))\n        if not isinstance(kwargs_type, Instance) or not kwargs_type.type.has_base(\n            \"typing.Mapping\"\n        ):\n            # Error should be already reported.\n            return TempNode(AnyType(TypeOfAny.special_form))\n        any_type = AnyType(TypeOfAny.special_form)\n        mapping_info = self.chk.named_generic_type(\"typing.Mapping\", [any_type, any_type]).type\n        return TempNode(map_instance_to_supertype(kwargs_type, mapping_info).args[1])\n\n    def auto_generate_keys(self, all_specs: list[ConversionSpecifier], ctx: Context) -> bool:\n        \"\"\"Translate '{} {name} {}' to '{0} {name} {1}'.\n\n        Return True if generation was successful, otherwise report an error and return false.\n        \"\"\"\n        some_defined = any(s.key and s.key.isdecimal() for s in all_specs)\n        all_defined = all(bool(s.key) for s in all_specs)\n        if some_defined and not all_defined:\n            self.msg.fail(\n                \"Cannot combine automatic field numbering and manual field specification\",\n                ctx,\n                code=codes.STRING_FORMATTING,\n            )\n            return False\n        if all_defined:\n            return True\n        next_index = 0\n        for spec in all_specs:\n            if not spec.key:\n                str_index = str(next_index)\n                spec.key = str_index\n                # Update also the full field (i.e. turn {.x} into {0.x}).\n                if not spec.field:\n                    spec.field = str_index\n                else:\n                    spec.field = str_index + spec.field\n                next_index += 1\n        return True\n\n    def apply_field_accessors(\n        self, spec: ConversionSpecifier, repl: Expression, ctx: Context\n    ) -> Expression:\n        \"\"\"Transform and validate expr in '{.attr[item]}'.format(expr) into expr.attr['item'].\n\n        If validation fails, return TempNode(AnyType).\n        \"\"\"\n        assert spec.key, \"Keys must be auto-generated first!\"\n        if spec.field == spec.key:\n            return repl\n        assert spec.field\n\n        temp_errors = Errors(self.chk.options)\n        dummy = DUMMY_FIELD_NAME + spec.field[len(spec.key) :]\n        temp_ast: Node = parse(\n            dummy, fnam=\"<format>\", module=None, options=self.chk.options, errors=temp_errors\n        )\n        if temp_errors.is_errors():\n            self.msg.fail(\n                f'Syntax error in format specifier \"{spec.field}\"',\n                ctx,\n                code=codes.STRING_FORMATTING,\n            )\n            return TempNode(AnyType(TypeOfAny.from_error))\n\n        # These asserts are guaranteed by the original regexp.\n        assert isinstance(temp_ast, MypyFile)\n        temp_ast = temp_ast.defs[0]\n        assert isinstance(temp_ast, ExpressionStmt)\n        temp_ast = temp_ast.expr\n        if not self.validate_and_transform_accessors(temp_ast, repl, spec, ctx=ctx):\n            return TempNode(AnyType(TypeOfAny.from_error))\n\n        # Check if there are any other errors (like missing members).\n        # TODO: fix column to point to actual start of the format specifier _within_ string.\n        temp_ast.line = ctx.line\n        temp_ast.column = ctx.column\n        self.chk.expr_checker.accept(temp_ast)\n        return temp_ast\n\n    def validate_and_transform_accessors(\n        self,\n        temp_ast: Expression,\n        original_repl: Expression,\n        spec: ConversionSpecifier,\n        ctx: Context,\n    ) -> bool:\n        \"\"\"Validate and transform (in-place) format field accessors.\n\n        On error, report it and return False. The transformations include replacing the dummy\n        variable with actual replacement expression and translating any name expressions in an\n        index into strings, so that this will work:\n\n            class User(TypedDict):\n                name: str\n                id: int\n            u: User\n            '{[id]:d} -> {[name]}'.format(u)\n        \"\"\"\n        if not isinstance(temp_ast, (MemberExpr, IndexExpr)):\n            self.msg.fail(\n                \"Only index and member expressions are allowed in\"\n                ' format field accessors; got \"{}\"'.format(spec.field),\n                ctx,\n                code=codes.STRING_FORMATTING,\n            )\n            return False\n        if isinstance(temp_ast, MemberExpr):\n            node = temp_ast.expr\n        else:\n            node = temp_ast.base\n            if not isinstance(temp_ast.index, (NameExpr, IntExpr)):\n                assert spec.key, \"Call this method only after auto-generating keys!\"\n                assert spec.field\n                self.msg.fail(\n                    'Invalid index expression in format field accessor \"{}\"'.format(\n                        spec.field[len(spec.key) :]\n                    ),\n                    ctx,\n                    code=codes.STRING_FORMATTING,\n                )\n                return False\n            if isinstance(temp_ast.index, NameExpr):\n                temp_ast.index = StrExpr(temp_ast.index.name)\n        if isinstance(node, NameExpr) and node.name == DUMMY_FIELD_NAME:\n            # Replace it with the actual replacement expression.\n            assert isinstance(temp_ast, (IndexExpr, MemberExpr))  # XXX: this is redundant\n            if isinstance(temp_ast, IndexExpr):\n                temp_ast.base = original_repl\n            else:\n                temp_ast.expr = original_repl\n            return True\n        node.line = ctx.line\n        node.column = ctx.column\n        return self.validate_and_transform_accessors(\n            node, original_repl=original_repl, spec=spec, ctx=ctx\n        )\n\n    # TODO: In Python 3, the bytes formatting has a more restricted set of options\n    #       compared to string formatting.\n    def check_str_interpolation(self, expr: FormatStringExpr, replacements: Expression) -> Type:\n        \"\"\"Check the types of the 'replacements' in a string interpolation\n        expression: str % replacements.\n        \"\"\"\n        self.chk.expr_checker.accept(expr)\n        specifiers = parse_conversion_specifiers(expr.value)\n        has_mapping_keys = self.analyze_conversion_specifiers(specifiers, expr)\n        if has_mapping_keys is None:\n            pass  # Error was reported\n        elif has_mapping_keys:\n            self.check_mapping_str_interpolation(specifiers, replacements, expr)\n        else:\n            self.check_simple_str_interpolation(specifiers, replacements, expr)\n\n        if isinstance(expr, BytesExpr):\n            return self.named_type(\"builtins.bytes\")\n        elif isinstance(expr, StrExpr):\n            return self.named_type(\"builtins.str\")\n        else:\n            assert False\n\n    def analyze_conversion_specifiers(\n        self, specifiers: list[ConversionSpecifier], context: Context\n    ) -> bool | None:\n        has_star = any(specifier.has_star() for specifier in specifiers)\n        has_key = any(specifier.has_key() for specifier in specifiers)\n        all_have_keys = all(\n            specifier.has_key() or specifier.conv_type == \"%\" for specifier in specifiers\n        )\n\n        if has_key and has_star:\n            self.msg.string_interpolation_with_star_and_key(context)\n            return None\n        if has_key and not all_have_keys:\n            self.msg.string_interpolation_mixing_key_and_non_keys(context)\n            return None\n        return has_key\n\n    def check_simple_str_interpolation(\n        self,\n        specifiers: list[ConversionSpecifier],\n        replacements: Expression,\n        expr: FormatStringExpr,\n    ) -> None:\n        \"\"\"Check % string interpolation with positional specifiers '%s, %d' % ('yes, 42').\"\"\"\n        checkers = self.build_replacement_checkers(specifiers, replacements, expr)\n        if checkers is None:\n            return\n\n        rhs_type = get_proper_type(self.accept(replacements))\n        rep_types: list[Type] = []\n        if isinstance(rhs_type, TupleType):\n            rep_types = rhs_type.items\n            unpack_index = find_unpack_in_list(rep_types)\n            if unpack_index is not None:\n                # TODO: we should probably warn about potentially short tuple.\n                # However, without special-casing for tuple(f(i) for in other_tuple)\n                # this causes false positive on mypy self-check in report.py.\n                extras = max(0, len(checkers) - len(rep_types) + 1)\n                unpacked = rep_types[unpack_index]\n                assert isinstance(unpacked, UnpackType)\n                unpacked = get_proper_type(unpacked.type)\n                if isinstance(unpacked, TypeVarTupleType):\n                    unpacked = get_proper_type(unpacked.upper_bound)\n                assert (\n                    isinstance(unpacked, Instance) and unpacked.type.fullname == \"builtins.tuple\"\n                )\n                unpack_items = [unpacked.args[0]] * extras\n                rep_types = rep_types[:unpack_index] + unpack_items + rep_types[unpack_index + 1 :]\n        elif isinstance(rhs_type, AnyType):\n            return\n        elif isinstance(rhs_type, Instance) and rhs_type.type.fullname == \"builtins.tuple\":\n            # Assume that an arbitrary-length tuple has the right number of items.\n            rep_types = [rhs_type.args[0]] * len(checkers)\n        elif isinstance(rhs_type, UnionType):\n            for typ in rhs_type.relevant_items():\n                temp_node = TempNode(typ)\n                temp_node.line = replacements.line\n                self.check_simple_str_interpolation(specifiers, temp_node, expr)\n            return\n        else:\n            rep_types = [rhs_type]\n\n        if len(checkers) > len(rep_types):\n            # Only check the fix-length Tuple type. Other Iterable types would skip.\n            if is_subtype(rhs_type, self.chk.named_type(\"typing.Iterable\")) and not isinstance(\n                rhs_type, TupleType\n            ):\n                return\n            else:\n                self.msg.too_few_string_formatting_arguments(replacements)\n        elif len(checkers) < len(rep_types):\n            self.msg.too_many_string_formatting_arguments(replacements)\n        else:\n            if len(checkers) == 1:\n                check_node, check_type = checkers[0]\n                if isinstance(rhs_type, TupleType) and len(rhs_type.items) == 1:\n                    check_type(rhs_type.items[0])\n                else:\n                    check_node(replacements)\n            elif isinstance(replacements, TupleExpr) and not any(\n                isinstance(item, StarExpr) for item in replacements.items\n            ):\n                for checks, rep_node in zip(checkers, replacements.items):\n                    check_node, check_type = checks\n                    check_node(rep_node)\n            else:\n                for checks, rep_type in zip(checkers, rep_types):\n                    check_node, check_type = checks\n                    check_type(rep_type)\n\n    def check_mapping_str_interpolation(\n        self,\n        specifiers: list[ConversionSpecifier],\n        replacements: Expression,\n        expr: FormatStringExpr,\n    ) -> None:\n        \"\"\"Check % string interpolation with names specifiers '%(name)s' % {'name': 'John'}.\"\"\"\n        if isinstance(replacements, DictExpr) and all(\n            isinstance(k, (StrExpr, BytesExpr)) for k, v in replacements.items\n        ):\n            mapping: dict[str, Type] = {}\n            for k, v in replacements.items:\n                if isinstance(expr, BytesExpr):\n                    # Special case: for bytes formatting keys must be bytes.\n                    if not isinstance(k, BytesExpr):\n                        self.msg.fail(\n                            \"Dictionary keys in bytes formatting must be bytes, not strings\",\n                            expr,\n                            code=codes.STRING_FORMATTING,\n                        )\n                key_str = cast(FormatStringExpr, k).value\n                mapping[key_str] = self.accept(v)\n\n            for specifier in specifiers:\n                if specifier.conv_type == \"%\":\n                    # %% is allowed in mappings, no checking is required\n                    continue\n                assert specifier.key is not None\n                if specifier.key not in mapping:\n                    self.msg.key_not_in_mapping(specifier.key, replacements)\n                    return\n                rep_type = mapping[specifier.key]\n                assert specifier.conv_type is not None\n                expected_type = self.conversion_type(specifier.conv_type, replacements, expr)\n                if expected_type is None:\n                    return\n                self.chk.check_subtype(\n                    rep_type,\n                    expected_type,\n                    replacements,\n                    message_registry.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION,\n                    \"expression has type\",\n                    f\"placeholder with key '{specifier.key}' has type\",\n                    code=codes.STRING_FORMATTING,\n                )\n                if specifier.conv_type == \"s\":\n                    self.check_s_special_cases(expr, rep_type, expr)\n        else:\n            rep_type = self.accept(replacements)\n            dict_type = self.build_dict_type(expr)\n            self.chk.check_subtype(\n                rep_type,\n                dict_type,\n                replacements,\n                message_registry.FORMAT_REQUIRES_MAPPING,\n                \"expression has type\",\n                \"expected type for mapping is\",\n                code=codes.STRING_FORMATTING,\n            )\n\n    def build_dict_type(self, expr: FormatStringExpr) -> Type:\n        \"\"\"Build expected mapping type for right operand in % formatting.\"\"\"\n        any_type = AnyType(TypeOfAny.special_form)\n        if isinstance(expr, BytesExpr):\n            bytes_type = self.chk.named_generic_type(\"builtins.bytes\", [])\n            return self.chk.named_generic_type(\n                \"_typeshed.SupportsKeysAndGetItem\", [bytes_type, any_type]\n            )\n        elif isinstance(expr, StrExpr):\n            str_type = self.chk.named_generic_type(\"builtins.str\", [])\n            return self.chk.named_generic_type(\n                \"_typeshed.SupportsKeysAndGetItem\", [str_type, any_type]\n            )\n        else:\n            assert False, \"Unreachable\"\n\n    def build_replacement_checkers(\n        self, specifiers: list[ConversionSpecifier], context: Context, expr: FormatStringExpr\n    ) -> list[Checkers] | None:\n        checkers: list[Checkers] = []\n        for specifier in specifiers:\n            checker = self.replacement_checkers(specifier, context, expr)\n            if checker is None:\n                return None\n            checkers.extend(checker)\n        return checkers\n\n    def replacement_checkers(\n        self, specifier: ConversionSpecifier, context: Context, expr: FormatStringExpr\n    ) -> list[Checkers] | None:\n        \"\"\"Returns a list of tuples of two functions that check whether a replacement is\n        of the right type for the specifier. The first function takes a node and checks\n        its type in the right type context. The second function just checks a type.\n        \"\"\"\n        checkers: list[Checkers] = []\n\n        if specifier.width == \"*\":\n            checkers.append(self.checkers_for_star(context))\n        if specifier.precision == \"*\":\n            checkers.append(self.checkers_for_star(context))\n\n        if specifier.conv_type == \"c\":\n            c = self.checkers_for_c_type(specifier.conv_type, context, expr)\n            if c is None:\n                return None\n            checkers.append(c)\n        elif specifier.conv_type is not None and specifier.conv_type != \"%\":\n            c = self.checkers_for_regular_type(specifier.conv_type, context, expr)\n            if c is None:\n                return None\n            checkers.append(c)\n        return checkers\n\n    def checkers_for_star(self, context: Context) -> Checkers:\n        \"\"\"Returns a tuple of check functions that check whether, respectively,\n        a node or a type is compatible with a star in a conversion specifier.\n        \"\"\"\n        expected = self.named_type(\"builtins.int\")\n\n        def check_type(type: Type) -> bool:\n            expected = self.named_type(\"builtins.int\")\n            return self.chk.check_subtype(\n                type, expected, context, \"* wants int\", code=codes.STRING_FORMATTING\n            )\n\n        def check_expr(expr: Expression) -> None:\n            type = self.accept(expr, expected)\n            check_type(type)\n\n        return check_expr, check_type\n\n    def check_placeholder_type(self, typ: Type, expected_type: Type, context: Context) -> bool:\n        return self.chk.check_subtype(\n            typ,\n            expected_type,\n            context,\n            message_registry.INCOMPATIBLE_TYPES_IN_STR_INTERPOLATION,\n            \"expression has type\",\n            \"placeholder has type\",\n            code=codes.STRING_FORMATTING,\n        )\n\n    def checkers_for_regular_type(\n        self, conv_type: str, context: Context, expr: FormatStringExpr\n    ) -> Checkers | None:\n        \"\"\"Returns a tuple of check functions that check whether, respectively,\n        a node or a type is compatible with 'type'. Return None in case of an error.\n        \"\"\"\n        expected_type = self.conversion_type(conv_type, context, expr)\n        if expected_type is None:\n            return None\n\n        def check_type(typ: Type) -> bool:\n            assert expected_type is not None\n            ret = self.check_placeholder_type(typ, expected_type, context)\n            if ret and conv_type == \"s\":\n                ret = self.check_s_special_cases(expr, typ, context)\n            return ret\n\n        def check_expr(expr: Expression) -> None:\n            type = self.accept(expr, expected_type)\n            check_type(type)\n\n        return check_expr, check_type\n\n    def check_s_special_cases(self, expr: FormatStringExpr, typ: Type, context: Context) -> bool:\n        \"\"\"Additional special cases for %s in bytes vs string context.\"\"\"\n        if isinstance(expr, StrExpr):\n            # Couple special cases for string formatting.\n            if has_type_component(typ, \"builtins.bytes\"):\n                self.msg.fail(\n                    'If x = b\\'abc\\' then \"%s\" % x produces \"b\\'abc\\'\", not \"abc\". '\n                    'If this is desired behavior use \"%r\" % x. Otherwise, decode the bytes',\n                    context,\n                    code=codes.STR_BYTES_PY3,\n                )\n                return False\n        if isinstance(expr, BytesExpr):\n            # A special case for bytes formatting: b'%s' actually requires bytes on Python 3.\n            if has_type_component(typ, \"builtins.str\"):\n                self.msg.fail(\n                    \"On Python 3 b'%s' requires bytes, not string\",\n                    context,\n                    code=codes.STRING_FORMATTING,\n                )\n                return False\n        return True\n\n    def checkers_for_c_type(\n        self, type: str, context: Context, format_expr: FormatStringExpr\n    ) -> Checkers | None:\n        \"\"\"Returns a tuple of check functions that check whether, respectively,\n        a node or a type is compatible with 'type' that is a character type.\n        \"\"\"\n        expected_type = self.conversion_type(type, context, format_expr)\n        if expected_type is None:\n            return None\n\n        def check_type(type: Type) -> bool:\n            assert expected_type is not None\n            if isinstance(format_expr, BytesExpr):\n                err_msg = '\"%c\" requires an integer in range(256) or a single byte'\n            else:\n                err_msg = '\"%c\" requires int or char'\n            return self.chk.check_subtype(\n                type,\n                expected_type,\n                context,\n                err_msg,\n                \"expression has type\",\n                code=codes.STRING_FORMATTING,\n            )\n\n        def check_expr(expr: Expression) -> None:\n            \"\"\"int, or str with length 1\"\"\"\n            type = self.accept(expr, expected_type)\n            # We need further check with expr to make sure that\n            # it has exact one char or one single byte.\n            if check_type(type):\n                # Python 3 doesn't support b'%c' % str\n                if (\n                    isinstance(format_expr, BytesExpr)\n                    and isinstance(expr, BytesExpr)\n                    and len(expr.value) != 1\n                ):\n                    self.msg.requires_int_or_single_byte(context)\n                elif isinstance(expr, (StrExpr, BytesExpr)) and len(expr.value) != 1:\n                    self.msg.requires_int_or_char(context)\n\n        return check_expr, check_type\n\n    def conversion_type(\n        self, p: str, context: Context, expr: FormatStringExpr, format_call: bool = False\n    ) -> Type | None:\n        \"\"\"Return the type that is accepted for a string interpolation conversion specifier type.\n\n        Note that both Python's float (e.g. %f) and integer (e.g. %d)\n        specifier types accept both float and integers.\n\n        The 'format_call' argument indicates whether this type came from % interpolation or from\n        a str.format() call, the meaning of few formatting types are different.\n        \"\"\"\n        NUMERIC_TYPES = NUMERIC_TYPES_NEW if format_call else NUMERIC_TYPES_OLD\n        INT_TYPES = REQUIRE_INT_NEW if format_call else REQUIRE_INT_OLD\n        if p == \"b\" and not format_call:\n            if not isinstance(expr, BytesExpr):\n                self.msg.fail(\n                    'Format character \"b\" is only supported on bytes patterns',\n                    context,\n                    code=codes.STRING_FORMATTING,\n                )\n                return None\n            return self.named_type(\"builtins.bytes\")\n        elif p == \"a\":\n            # TODO: return type object?\n            return AnyType(TypeOfAny.special_form)\n        elif p in [\"s\", \"r\"]:\n            return AnyType(TypeOfAny.special_form)\n        elif p in NUMERIC_TYPES:\n            if p in INT_TYPES:\n                numeric_types = [self.named_type(\"builtins.int\")]\n            else:\n                numeric_types = [\n                    self.named_type(\"builtins.int\"),\n                    self.named_type(\"builtins.float\"),\n                ]\n                if not format_call:\n                    if p in FLOAT_TYPES:\n                        numeric_types.append(self.named_type(\"typing.SupportsFloat\"))\n                    else:\n                        numeric_types.append(self.named_type(\"typing.SupportsInt\"))\n            return UnionType.make_union(numeric_types)\n        elif p in [\"c\"]:\n            if isinstance(expr, BytesExpr):\n                return UnionType(\n                    [self.named_type(\"builtins.int\"), self.named_type(\"builtins.bytes\")]\n                )\n            else:\n                return UnionType(\n                    [self.named_type(\"builtins.int\"), self.named_type(\"builtins.str\")]\n                )\n        else:\n            self.msg.unsupported_placeholder(p, context)\n            return None\n\n    #\n    # Helpers\n    #\n\n    def named_type(self, name: str) -> Instance:\n        \"\"\"Return an instance type with type given by the name and no type\n        arguments. Alias for TypeChecker.named_type.\n        \"\"\"\n        return self.chk.named_type(name)\n\n    def accept(self, expr: Expression, context: Type | None = None) -> Type:\n        \"\"\"Type check a node. Alias for TypeChecker.accept.\"\"\"\n        return self.chk.expr_checker.accept(expr, context)\n\n\ndef has_type_component(typ: Type, fullname: str) -> bool:\n    \"\"\"Is this a specific instance type, or a union that contains it?\n\n    We use this ad-hoc function instead of a proper visitor or subtype check\n    because some str vs bytes errors are strictly speaking not runtime errors,\n    but rather highly counter-intuitive behavior. This is similar to what is used for\n    --strict-equality.\n    \"\"\"\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        return typ.type.has_base(fullname)\n    elif isinstance(typ, TypeVarType):\n        return has_type_component(typ.upper_bound, fullname) or any(\n            has_type_component(v, fullname) for v in typ.values\n        )\n    elif isinstance(typ, UnionType):\n        return any(has_type_component(t, fullname) for t in typ.relevant_items())\n    return False\n"
  },
  {
    "path": "mypy/config_parser.py",
    "content": "from __future__ import annotations\n\nimport argparse\nimport configparser\nimport glob as fileglob\nimport os\nimport re\nimport sys\nfrom io import StringIO\n\nif sys.version_info >= (3, 11):\n    import tomllib\nelse:\n    import tomli as tomllib\n\nfrom collections.abc import Callable, Mapping, MutableMapping, Sequence\nfrom typing import Any, Final, TextIO, TypeAlias\nfrom typing_extensions import Never\n\nfrom mypy import defaults\nfrom mypy.options import PER_MODULE_OPTIONS, Options\n\n_CONFIG_VALUE_TYPES: TypeAlias = (\n    str | bool | int | float | dict[str, str] | list[str] | tuple[int, int]\n)\n_INI_PARSER_CALLABLE: TypeAlias = Callable[[Any], _CONFIG_VALUE_TYPES]\n\n\nclass VersionTypeError(argparse.ArgumentTypeError):\n    \"\"\"Provide a fallback value if the Python version is unsupported.\"\"\"\n\n    def __init__(self, *args: Any, fallback: tuple[int, int]) -> None:\n        self.fallback = fallback\n        super().__init__(*args)\n\n\ndef parse_version(v: str | float) -> tuple[int, int]:\n    m = re.match(r\"\\A(\\d)\\.(\\d+)\\Z\", str(v))\n    if not m:\n        raise argparse.ArgumentTypeError(f\"Invalid python version '{v}' (expected format: 'x.y')\")\n    major, minor = int(m.group(1)), int(m.group(2))\n    if major == 2 and minor == 7:\n        pass  # Error raised elsewhere\n    elif major == 3:\n        if minor < defaults.PYTHON3_VERSION_MIN[1]:\n            msg = \"Python 3.{} is not supported (must be {}.{} or higher)\".format(\n                minor, *defaults.PYTHON3_VERSION_MIN\n            )\n\n            if isinstance(v, float):\n                msg += \". You may need to put quotes around your Python version\"\n\n            raise VersionTypeError(msg, fallback=defaults.PYTHON3_VERSION_MIN)\n    else:\n        raise argparse.ArgumentTypeError(\n            f\"Python major version '{major}' out of range (must be 3)\"\n        )\n    return major, minor\n\n\ndef try_split(v: str | Sequence[str] | object, split_regex: str = \",\") -> list[str]:\n    \"\"\"Split and trim a str or sequence (eg: list) of str into a list of str.\n    If an element of the input is not str, a type error will be raised.\"\"\"\n\n    def complain(x: object, additional_info: str = \"\") -> Never:\n        raise argparse.ArgumentTypeError(\n            f\"Expected a list or a stringified version thereof, but got: '{x}', of type {type(x).__name__}.{additional_info}\"\n        )\n\n    if isinstance(v, str):\n        items = [p.strip() for p in re.split(split_regex, v)]\n        if items and items[-1] == \"\":\n            items.pop(-1)\n        return items\n    elif isinstance(v, Sequence):\n        return [\n            (\n                p.strip()\n                if isinstance(p, str)\n                else complain(p, additional_info=\" (As an element of the list.)\")\n            )\n            for p in v\n        ]\n    else:\n        complain(v)\n\n\ndef validate_package_allow_list(allow_list: list[str]) -> list[str]:\n    for p in allow_list:\n        msg = f\"Invalid allow list entry: {p}\"\n        if \"*\" in p:\n            raise argparse.ArgumentTypeError(\n                f\"{msg} (entries are already prefixes so must not contain *)\"\n            )\n        if \"\\\\\" in p or \"/\" in p:\n            raise argparse.ArgumentTypeError(\n                f\"{msg} (entries must be packages like foo.bar not directories or files)\"\n            )\n    return allow_list\n\n\ndef expand_path(path: str) -> str:\n    \"\"\"Expand the user home directory and any environment variables contained within\n    the provided path.\n    \"\"\"\n\n    return os.path.expandvars(os.path.expanduser(path))\n\n\ndef str_or_array_as_list(v: str | Sequence[str]) -> list[str]:\n    if isinstance(v, str):\n        return [v.strip()] if v.strip() else []\n    return [p.strip() for p in v if p.strip()]\n\n\ndef split_and_match_files_list(paths: Sequence[str]) -> list[str]:\n    \"\"\"Take a list of files/directories (with support for globbing through the glob library).\n\n    Where a path/glob matches no file, we still include the raw path in the resulting list.\n\n    Returns a list of file paths\n    \"\"\"\n    expanded_paths = []\n\n    for path in paths:\n        path = expand_path(path.strip())\n        globbed_files = fileglob.glob(path, recursive=True)\n        if globbed_files:\n            expanded_paths.extend(globbed_files)\n        else:\n            expanded_paths.append(path)\n\n    return expanded_paths\n\n\ndef split_and_match_files(paths: str) -> list[str]:\n    \"\"\"Take a string representing a list of files/directories (with support for globbing\n    through the glob library).\n\n    Where a path/glob matches no file, we still include the raw path in the resulting list.\n\n    Returns a list of file paths\n    \"\"\"\n\n    return split_and_match_files_list(split_commas(paths))\n\n\ndef check_follow_imports(choice: str) -> str:\n    choices = [\"normal\", \"silent\", \"skip\", \"error\"]\n    if choice not in choices:\n        raise argparse.ArgumentTypeError(\n            \"invalid choice '{}' (choose from {})\".format(\n                choice, \", \".join(f\"'{x}'\" for x in choices)\n            )\n        )\n    return choice\n\n\ndef check_junit_format(choice: str) -> str:\n    choices = [\"global\", \"per_file\"]\n    if choice not in choices:\n        raise argparse.ArgumentTypeError(\n            \"invalid choice '{}' (choose from {})\".format(\n                choice, \", \".join(f\"'{x}'\" for x in choices)\n            )\n        )\n    return choice\n\n\ndef split_commas(value: str) -> list[str]:\n    # Uses a bit smarter technique to allow last trailing comma\n    # and to remove last `\"\"` item from the split.\n    items = value.split(\",\")\n    if items and items[-1] == \"\":\n        items.pop(-1)\n    return items\n\n\n# For most options, the type of the default value set in options.py is\n# sufficient, and we don't have to do anything here.  This table\n# exists to specify types for values initialized to None or container\n# types.\nini_config_types: Final[dict[str, _INI_PARSER_CALLABLE]] = {\n    \"python_version\": parse_version,\n    \"custom_typing_module\": str,\n    \"custom_typeshed_dir\": expand_path,\n    \"mypy_path\": lambda s: [expand_path(p.strip()) for p in re.split(\"[,:]\", s)],\n    \"files\": split_and_match_files,\n    \"quickstart_file\": expand_path,\n    \"junit_xml\": expand_path,\n    \"junit_format\": check_junit_format,\n    \"follow_imports\": check_follow_imports,\n    \"no_site_packages\": bool,\n    \"plugins\": lambda s: [p.strip() for p in split_commas(s)],\n    \"always_true\": lambda s: [p.strip() for p in split_commas(s)],\n    \"always_false\": lambda s: [p.strip() for p in split_commas(s)],\n    \"untyped_calls_exclude\": lambda s: validate_package_allow_list(\n        [p.strip() for p in split_commas(s)]\n    ),\n    \"enable_incomplete_feature\": lambda s: [p.strip() for p in split_commas(s)],\n    \"disable_error_code\": lambda s: [p.strip() for p in split_commas(s)],\n    \"enable_error_code\": lambda s: [p.strip() for p in split_commas(s)],\n    \"package_root\": lambda s: [p.strip() for p in split_commas(s)],\n    \"cache_dir\": expand_path,\n    \"python_executable\": expand_path,\n    \"strict\": bool,\n    \"exclude\": lambda s: [s.strip()],\n    \"packages\": try_split,\n    \"modules\": try_split,\n}\n\n# Reuse the ini_config_types and overwrite the diff\ntoml_config_types: Final[dict[str, _INI_PARSER_CALLABLE]] = ini_config_types.copy()\ntoml_config_types.update(\n    {\n        \"python_version\": parse_version,\n        \"mypy_path\": lambda s: [expand_path(p) for p in try_split(s, \"[,:]\")],\n        \"files\": lambda s: split_and_match_files_list(try_split(s)),\n        \"junit_format\": lambda s: check_junit_format(str(s)),\n        \"follow_imports\": lambda s: check_follow_imports(str(s)),\n        \"plugins\": try_split,\n        \"always_true\": try_split,\n        \"always_false\": try_split,\n        \"untyped_calls_exclude\": lambda s: validate_package_allow_list(try_split(s)),\n        \"enable_incomplete_feature\": try_split,\n        \"disable_error_code\": lambda s: try_split(s),\n        \"enable_error_code\": lambda s: try_split(s),\n        \"package_root\": try_split,\n        \"exclude\": str_or_array_as_list,\n        \"packages\": try_split,\n        \"modules\": try_split,\n    }\n)\n\n\ndef _parse_individual_file(\n    config_file: str, stderr: TextIO | None = None\n) -> tuple[MutableMapping[str, Any], dict[str, _INI_PARSER_CALLABLE], str] | None:\n\n    if not os.path.exists(config_file):\n        return None\n\n    parser: MutableMapping[str, Any]\n    try:\n        if is_toml(config_file):\n            with open(config_file, \"rb\") as f:\n                toml_data = tomllib.load(f)\n            # Filter down to just mypy relevant toml keys\n            toml_data = toml_data.get(\"tool\", {})\n            if \"mypy\" not in toml_data:\n                return None\n            toml_data = {\"mypy\": toml_data[\"mypy\"]}\n            parser = destructure_overrides(toml_data)\n            config_types = toml_config_types\n        else:\n            parser = configparser.RawConfigParser()\n            parser.read(config_file)\n            config_types = ini_config_types\n\n    except (tomllib.TOMLDecodeError, configparser.Error, ConfigTOMLValueError) as err:\n        print(f\"{config_file}: {err}\", file=stderr)\n        return None\n\n    if os.path.basename(config_file) in defaults.SHARED_CONFIG_NAMES and \"mypy\" not in parser:\n        return None\n\n    return parser, config_types, config_file\n\n\ndef _find_config_file(\n    stderr: TextIO | None = None,\n) -> tuple[MutableMapping[str, Any], dict[str, _INI_PARSER_CALLABLE], str] | None:\n\n    current_dir = os.path.abspath(os.getcwd())\n\n    while True:\n        for name in defaults.CONFIG_NAMES + defaults.SHARED_CONFIG_NAMES:\n            config_file = os.path.relpath(os.path.join(current_dir, name))\n            ret = _parse_individual_file(config_file, stderr)\n            if ret is None:\n                continue\n            return ret\n\n        if any(\n            os.path.exists(os.path.join(current_dir, cvs_root)) for cvs_root in (\".git\", \".hg\")\n        ):\n            break\n        parent_dir = os.path.dirname(current_dir)\n        if parent_dir == current_dir:\n            break\n        current_dir = parent_dir\n\n    for config_file in defaults.USER_CONFIG_FILES:\n        ret = _parse_individual_file(config_file, stderr)\n        if ret is None:\n            continue\n        return ret\n\n    return None\n\n\ndef parse_config_file(\n    options: Options,\n    set_strict_flags: Callable[[], None],\n    filename: str | None,\n    stdout: TextIO | None = None,\n    stderr: TextIO | None = None,\n) -> None:\n    \"\"\"Parse a config file into an Options object.\n\n    Errors are written to stderr but are not fatal.\n\n    If filename is None, fall back to default config files.\n    \"\"\"\n    stdout = stdout or sys.stdout\n    stderr = stderr or sys.stderr\n\n    ret = (\n        _parse_individual_file(filename, stderr)\n        if filename is not None\n        else _find_config_file(stderr)\n    )\n    if ret is None:\n        return\n    parser, config_types, file_read = ret\n\n    options.config_file = file_read\n    os.environ[\"MYPY_CONFIG_FILE_DIR\"] = os.path.dirname(os.path.abspath(file_read))\n\n    if \"mypy\" not in parser:\n        if filename or os.path.basename(file_read) not in defaults.SHARED_CONFIG_NAMES:\n            print(f\"{file_read}: No [mypy] section in config file\", file=stderr)\n    else:\n        section = parser[\"mypy\"]\n        prefix = f\"{file_read}: [mypy]: \"\n        updates, report_dirs = parse_section(\n            prefix, options, set_strict_flags, section, config_types, stderr\n        )\n        for k, v in updates.items():\n            setattr(options, k, v)\n        options.report_dirs.update(report_dirs)\n\n    for name, section in parser.items():\n        if name.startswith(\"mypy-\"):\n            prefix = get_prefix(file_read, name)\n            updates, report_dirs = parse_section(\n                prefix, options, set_strict_flags, section, config_types, stderr\n            )\n            if report_dirs:\n                print(\n                    prefix,\n                    \"Per-module sections should not specify reports ({})\".format(\n                        \", \".join(s + \"_report\" for s in sorted(report_dirs))\n                    ),\n                    file=stderr,\n                )\n            if set(updates) - PER_MODULE_OPTIONS:\n                print(\n                    prefix,\n                    \"Per-module sections should only specify per-module flags ({})\".format(\n                        \", \".join(sorted(set(updates) - PER_MODULE_OPTIONS))\n                    ),\n                    file=stderr,\n                )\n                updates = {k: v for k, v in updates.items() if k in PER_MODULE_OPTIONS}\n\n            globs = name[5:]\n            for glob in globs.split(\",\"):\n                # For backwards compatibility, replace (back)slashes with dots.\n                glob = glob.replace(os.sep, \".\")\n                if os.altsep:\n                    glob = glob.replace(os.altsep, \".\")\n\n                if any(c in glob for c in \"?[]!\") or any(\n                    \"*\" in x and x != \"*\" for x in glob.split(\".\")\n                ):\n                    print(\n                        prefix,\n                        \"Patterns must be fully-qualified module names, optionally \"\n                        \"with '*' in some components (e.g spam.*.eggs.*)\",\n                        file=stderr,\n                    )\n                else:\n                    options.per_module_options[glob] = updates\n\n\ndef get_prefix(file_read: str, name: str) -> str:\n    if is_toml(file_read):\n        module_name_str = 'module = \"%s\"' % \"-\".join(name.split(\"-\")[1:])\n    else:\n        module_name_str = name\n\n    return f\"{file_read}: [{module_name_str}]:\"\n\n\ndef is_toml(filename: str) -> bool:\n    return filename.lower().endswith(\".toml\")\n\n\ndef destructure_overrides(toml_data: dict[str, Any]) -> dict[str, Any]:\n    \"\"\"Take the new [[tool.mypy.overrides]] section array in the pyproject.toml file,\n    and convert it back to a flatter structure that the existing config_parser can handle.\n\n    E.g. the following pyproject.toml file:\n\n        [[tool.mypy.overrides]]\n        module = [\n            \"a.b\",\n            \"b.*\"\n        ]\n        disallow_untyped_defs = true\n\n        [[tool.mypy.overrides]]\n        module = 'c'\n        disallow_untyped_defs = false\n\n    Would map to the following config dict that it would have gotten from parsing an equivalent\n    ini file:\n\n        {\n            \"mypy-a.b\": {\n                disallow_untyped_defs = true,\n            },\n            \"mypy-b.*\": {\n                disallow_untyped_defs = true,\n            },\n            \"mypy-c\": {\n                disallow_untyped_defs: false,\n            },\n        }\n    \"\"\"\n    if \"overrides\" not in toml_data[\"mypy\"]:\n        return toml_data\n\n    if not isinstance(toml_data[\"mypy\"][\"overrides\"], list):\n        raise ConfigTOMLValueError(\n            \"tool.mypy.overrides sections must be an array. Please make \"\n            \"sure you are using double brackets like so: [[tool.mypy.overrides]]\"\n        )\n\n    result = toml_data.copy()\n    for override in result[\"mypy\"][\"overrides\"]:\n        if \"module\" not in override:\n            raise ConfigTOMLValueError(\n                \"toml config file contains a [[tool.mypy.overrides]] \"\n                \"section, but no module to override was specified.\"\n            )\n\n        if isinstance(override[\"module\"], str):\n            modules = [override[\"module\"]]\n        elif isinstance(override[\"module\"], list):\n            modules = override[\"module\"]\n        else:\n            raise ConfigTOMLValueError(\n                \"toml config file contains a [[tool.mypy.overrides]] \"\n                \"section with a module value that is not a string or a list of \"\n                \"strings\"\n            )\n\n        for module in modules:\n            module_overrides = override.copy()\n            del module_overrides[\"module\"]\n            old_config_name = f\"mypy-{module}\"\n            if old_config_name not in result:\n                result[old_config_name] = module_overrides\n            else:\n                for new_key, new_value in module_overrides.items():\n                    if (\n                        new_key in result[old_config_name]\n                        and result[old_config_name][new_key] != new_value\n                    ):\n                        raise ConfigTOMLValueError(\n                            \"toml config file contains \"\n                            \"[[tool.mypy.overrides]] sections with conflicting \"\n                            f\"values. Module '{module}' has two different values for '{new_key}'\"\n                        )\n                    result[old_config_name][new_key] = new_value\n\n    del result[\"mypy\"][\"overrides\"]\n    return result\n\n\ndef parse_section(\n    prefix: str,\n    template: Options,\n    set_strict_flags: Callable[[], None],\n    section: Mapping[str, Any],\n    config_types: dict[str, Any],\n    stderr: TextIO = sys.stderr,\n) -> tuple[dict[str, object], dict[str, str]]:\n    \"\"\"Parse one section of a config file.\n\n    Returns a dict of option values encountered, and a dict of report directories.\n    \"\"\"\n    results: dict[str, object] = {}\n    report_dirs: dict[str, str] = {}\n\n    # Because these fields exist on Options, without proactive checking, we would accept them\n    # and crash later\n    invalid_options = {\n        \"enabled_error_codes\": \"enable_error_code\",\n        \"disabled_error_codes\": \"disable_error_code\",\n    }\n\n    for key in section:\n        invert = False\n        # Here we use `key` for original config section key, and `options_key` for\n        # the corresponding Options attribute.\n        options_key = key\n        # Match aliasing for command line flag.\n        if key.endswith(\"allow_redefinition\"):\n            options_key += \"_old\"\n        if key in config_types:\n            ct = config_types[key]\n        elif key in invalid_options:\n            print(\n                f\"{prefix}Unrecognized option: {key} = {section[key]}\"\n                f\" (did you mean {invalid_options[key]}?)\",\n                file=stderr,\n            )\n            continue\n        else:\n            dv = getattr(template, options_key, None)\n            if dv is None:\n                if key.endswith(\"_report\"):\n                    report_type = key[:-7].replace(\"_\", \"-\")\n                    if report_type in defaults.REPORTER_NAMES:\n                        report_dirs[report_type] = str(section[key])\n                    else:\n                        print(f\"{prefix}Unrecognized report type: {key}\", file=stderr)\n                    continue\n                if key.startswith(\"x_\"):\n                    pass  # Don't complain about `x_blah` flags\n                elif key.startswith(\"no_\") and hasattr(template, options_key[3:]):\n                    options_key = options_key[3:]\n                    invert = True\n                elif key.startswith(\"allow\") and hasattr(template, \"dis\" + options_key):\n                    options_key = \"dis\" + options_key\n                    invert = True\n                elif key.startswith(\"disallow\") and hasattr(template, options_key[3:]):\n                    options_key = options_key[3:]\n                    invert = True\n                elif key.startswith(\"show_\") and hasattr(template, \"hide_\" + options_key[5:]):\n                    options_key = \"hide_\" + options_key[5:]\n                    invert = True\n                elif key == \"strict\":\n                    pass  # Special handling below\n                else:\n                    print(f\"{prefix}Unrecognized option: {key} = {section[key]}\", file=stderr)\n                if invert:\n                    dv = getattr(template, options_key, None)\n                else:\n                    continue\n            ct = type(dv) if dv is not None else None\n        v: Any = None\n        try:\n            if ct is bool:\n                if isinstance(section, dict):\n                    v = convert_to_boolean(section.get(key))\n                else:\n                    v = section.getboolean(key)  # type: ignore[attr-defined]  # Until better stub\n                if invert:\n                    v = not v\n            elif callable(ct):\n                if invert:\n                    print(f\"{prefix}Can not invert non-boolean key {options_key}\", file=stderr)\n                    continue\n                try:\n                    v = ct(section.get(key))\n                except VersionTypeError as err_version:\n                    print(f\"{prefix}{key}: {err_version}\", file=stderr)\n                    v = err_version.fallback\n                except argparse.ArgumentTypeError as err:\n                    print(f\"{prefix}{key}: {err}\", file=stderr)\n                    continue\n            else:\n                print(f\"{prefix}Don't know what type {key} should have\", file=stderr)\n                continue\n        except ValueError as err:\n            print(f\"{prefix}{key}: {err}\", file=stderr)\n            continue\n        if key == \"strict\":\n            if v:\n                set_strict_flags()\n            continue\n        results[options_key] = v\n\n    # These two flags act as per-module overrides, so store the empty defaults.\n    if \"disable_error_code\" not in results:\n        results[\"disable_error_code\"] = []\n    if \"enable_error_code\" not in results:\n        results[\"enable_error_code\"] = []\n\n    return results, report_dirs\n\n\ndef convert_to_boolean(value: Any | None) -> bool:\n    \"\"\"Return a boolean value translating from other types if necessary.\"\"\"\n    if isinstance(value, bool):\n        return value\n    if not isinstance(value, str):\n        value = str(value)\n    if value.lower() not in configparser.RawConfigParser.BOOLEAN_STATES:\n        raise ValueError(f\"Not a boolean: {value}\")\n    return configparser.RawConfigParser.BOOLEAN_STATES[value.lower()]\n\n\ndef split_directive(s: str) -> tuple[list[str], list[str]]:\n    \"\"\"Split s on commas, except during quoted sections.\n\n    Returns the parts and a list of error messages.\"\"\"\n    parts = []\n    cur: list[str] = []\n    errors = []\n    i = 0\n    while i < len(s):\n        if s[i] == \",\":\n            parts.append(\"\".join(cur).strip())\n            cur = []\n        elif s[i] == '\"':\n            i += 1\n            while i < len(s) and s[i] != '\"':\n                cur.append(s[i])\n                i += 1\n            if i == len(s):\n                errors.append(\"Unterminated quote in configuration comment\")\n                cur.clear()\n        else:\n            cur.append(s[i])\n        i += 1\n    if cur:\n        parts.append(\"\".join(cur).strip())\n\n    return parts, errors\n\n\ndef mypy_comments_to_config_map(line: str, template: Options) -> tuple[dict[str, str], list[str]]:\n    \"\"\"Rewrite the mypy comment syntax into ini file syntax.\"\"\"\n    options = {}\n    entries, errors = split_directive(line)\n    for entry in entries:\n        if \"=\" not in entry:\n            name = entry\n            value = None\n        else:\n            name, value = (x.strip() for x in entry.split(\"=\", 1))\n\n        name = name.replace(\"-\", \"_\")\n        if value is None:\n            value = \"True\"\n        options[name] = value\n\n    return options, errors\n\n\ndef parse_mypy_comments(\n    args: list[tuple[int, str]], template: Options\n) -> tuple[dict[str, object], list[tuple[int, str]]]:\n    \"\"\"Parse a collection of inline mypy: configuration comments.\n\n    Returns a dictionary of options to be applied and a list of error messages\n    generated.\n    \"\"\"\n    errors: list[tuple[int, str]] = []\n    sections: dict[str, object] = {\"enable_error_code\": [], \"disable_error_code\": []}\n\n    for lineno, line in args:\n        # In order to easily match the behavior for bools, we abuse configparser.\n        # Oddly, the only way to get the SectionProxy object with the getboolean\n        # method is to create a config parser.\n        parser = configparser.RawConfigParser()\n        options, parse_errors = mypy_comments_to_config_map(line, template)\n        if \"python_version\" in options:\n            errors.append((lineno, \"python_version not supported in inline configuration\"))\n            del options[\"python_version\"]\n\n        parser[\"dummy\"] = options\n        errors.extend((lineno, x) for x in parse_errors)\n\n        stderr = StringIO()\n        strict_found = False\n\n        def set_strict_flags() -> None:\n            nonlocal strict_found\n            strict_found = True\n\n        new_sections, reports = parse_section(\n            \"\", template, set_strict_flags, parser[\"dummy\"], ini_config_types, stderr=stderr\n        )\n        errors.extend((lineno, x) for x in stderr.getvalue().strip().split(\"\\n\") if x)\n        if reports:\n            errors.append((lineno, \"Reports not supported in inline configuration\"))\n        if strict_found:\n            errors.append(\n                (\n                    lineno,\n                    'Setting \"strict\" not supported in inline configuration: specify it in '\n                    \"a configuration file instead, or set individual inline flags \"\n                    '(see \"mypy -h\" for the list of flags enabled in strict mode)',\n                )\n            )\n        # Because this is currently special-cased\n        # (the new_sections for an inline config *always* includes 'disable_error_code' and\n        # 'enable_error_code' fields, usually empty, which overwrite the old ones),\n        # we have to manipulate them specially.\n        # This could use a refactor, but so could the whole subsystem.\n        if (\n            \"enable_error_code\" in new_sections\n            and isinstance(neec := new_sections[\"enable_error_code\"], list)\n            and isinstance(eec := sections.get(\"enable_error_code\", []), list)\n        ):\n            new_sections[\"enable_error_code\"] = sorted(set(neec + eec))\n        if (\n            \"disable_error_code\" in new_sections\n            and isinstance(ndec := new_sections[\"disable_error_code\"], list)\n            and isinstance(dec := sections.get(\"disable_error_code\", []), list)\n        ):\n            new_sections[\"disable_error_code\"] = sorted(set(ndec + dec))\n        sections.update(new_sections)\n    return sections, errors\n\n\ndef get_config_module_names(filename: str | None, modules: list[str]) -> str:\n    if not filename or not modules:\n        return \"\"\n\n    if not is_toml(filename):\n        return \", \".join(f\"[mypy-{module}]\" for module in modules)\n\n    return \"module = ['%s']\" % (\"', '\".join(sorted(modules)))\n\n\nclass ConfigTOMLValueError(ValueError):\n    pass\n"
  },
  {
    "path": "mypy/constant_fold.py",
    "content": "\"\"\"Constant folding of expressions.\n\nFor example, 3 + 5 can be constant folded into 8.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final\n\nfrom mypy.nodes import (\n    ComplexExpr,\n    Expression,\n    FloatExpr,\n    IntExpr,\n    NameExpr,\n    OpExpr,\n    StrExpr,\n    UnaryExpr,\n    Var,\n)\n\n# All possible result types of constant folding\nConstantValue = int | bool | float | complex | str\nCONST_TYPES: Final = (int, bool, float, complex, str)\n\n\ndef constant_fold_expr(expr: Expression, cur_mod_id: str) -> ConstantValue | None:\n    \"\"\"Return the constant value of an expression for supported operations.\n\n    Among other things, support int arithmetic and string\n    concatenation. For example, the expression 3 + 5 has the constant\n    value 8.\n\n    Also bind simple references to final constants defined in the\n    current module (cur_mod_id). Binding to references is best effort\n    -- we don't bind references to other modules. Mypyc trusts these\n    to be correct in compiled modules, so that it can replace a\n    constant expression (or a reference to one) with the statically\n    computed value. We don't want to infer constant values based on\n    stubs, in particular, as these might not match the implementation\n    (due to version skew, for example).\n\n    Return None if unsuccessful.\n    \"\"\"\n    if isinstance(expr, IntExpr):\n        return expr.value\n    if isinstance(expr, StrExpr):\n        return expr.value\n    if isinstance(expr, FloatExpr):\n        return expr.value\n    if isinstance(expr, ComplexExpr):\n        return expr.value\n    elif isinstance(expr, NameExpr):\n        if expr.name == \"True\":\n            return True\n        elif expr.name == \"False\":\n            return False\n        node = expr.node\n        if (\n            isinstance(node, Var)\n            and node.is_final\n            and node.fullname.rsplit(\".\", 1)[0] == cur_mod_id\n        ):\n            value = node.final_value\n            if isinstance(value, (CONST_TYPES)):\n                return value\n    elif isinstance(expr, OpExpr):\n        left = constant_fold_expr(expr.left, cur_mod_id)\n        right = constant_fold_expr(expr.right, cur_mod_id)\n        if left is not None and right is not None:\n            return constant_fold_binary_op(expr.op, left, right)\n    elif isinstance(expr, UnaryExpr):\n        value = constant_fold_expr(expr.expr, cur_mod_id)\n        if value is not None:\n            return constant_fold_unary_op(expr.op, value)\n    return None\n\n\ndef constant_fold_binary_op(\n    op: str, left: ConstantValue, right: ConstantValue\n) -> ConstantValue | None:\n    if isinstance(left, int) and isinstance(right, int):\n        return constant_fold_binary_int_op(op, left, right)\n\n    # Float and mixed int/float arithmetic.\n    if isinstance(left, float) and isinstance(right, float):\n        return constant_fold_binary_float_op(op, left, right)\n    elif isinstance(left, float) and isinstance(right, int):\n        return constant_fold_binary_float_op(op, left, right)\n    elif isinstance(left, int) and isinstance(right, float):\n        return constant_fold_binary_float_op(op, left, right)\n\n    # String concatenation and multiplication.\n    if op == \"+\" and isinstance(left, str) and isinstance(right, str):\n        return left + right\n    elif op == \"*\" and isinstance(left, str) and isinstance(right, int):\n        return left * right\n    elif op == \"*\" and isinstance(left, int) and isinstance(right, str):\n        return left * right\n\n    # Complex construction.\n    if op == \"+\" and isinstance(left, (int, float)) and isinstance(right, complex):\n        return left + right\n    elif op == \"+\" and isinstance(left, complex) and isinstance(right, (int, float)):\n        return left + right\n    elif op == \"-\" and isinstance(left, (int, float)) and isinstance(right, complex):\n        return left - right\n    elif op == \"-\" and isinstance(left, complex) and isinstance(right, (int, float)):\n        return left - right\n\n    return None\n\n\ndef constant_fold_binary_int_op(op: str, left: int, right: int) -> int | float | None:\n    if op == \"+\":\n        return left + right\n    if op == \"-\":\n        return left - right\n    elif op == \"*\":\n        return left * right\n    elif op == \"/\":\n        if right != 0:\n            return left / right\n    elif op == \"//\":\n        if right != 0:\n            return left // right\n    elif op == \"%\":\n        if right != 0:\n            return left % right\n    elif op == \"&\":\n        return left & right\n    elif op == \"|\":\n        return left | right\n    elif op == \"^\":\n        return left ^ right\n    elif op == \"<<\":\n        if right >= 0:\n            return left << right\n    elif op == \">>\":\n        if right >= 0:\n            return left >> right\n    elif op == \"**\":\n        if right >= 0:\n            ret = left**right\n            assert isinstance(ret, int)\n            return ret\n    return None\n\n\ndef constant_fold_binary_float_op(op: str, left: int | float, right: int | float) -> float | None:\n    assert not (isinstance(left, int) and isinstance(right, int)), (op, left, right)\n    if op == \"+\":\n        return left + right\n    elif op == \"-\":\n        return left - right\n    elif op == \"*\":\n        return left * right\n    elif op == \"/\":\n        if right != 0:\n            return left / right\n    elif op == \"//\":\n        if right != 0:\n            return left // right\n    elif op == \"%\":\n        if right != 0:\n            return left % right\n    elif op == \"**\":\n        if (left < 0 and isinstance(right, int)) or left > 0:\n            try:\n                ret = left**right\n            except OverflowError:\n                return None\n            else:\n                assert isinstance(ret, float), ret\n                return ret\n\n    return None\n\n\ndef constant_fold_unary_op(op: str, value: ConstantValue) -> int | float | None:\n    if op == \"-\" and isinstance(value, (int, float)):\n        return -value\n    elif op == \"~\" and isinstance(value, int):\n        return ~value\n    elif op == \"+\" and isinstance(value, (int, float)):\n        return value\n    return None\n"
  },
  {
    "path": "mypy/constraints.py",
    "content": "\"\"\"Type inference constraints.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable, Sequence\nfrom typing import TYPE_CHECKING, Final, TypeGuard, cast\n\nimport mypy.subtypes\nimport mypy.typeops\nfrom mypy.argmap import ArgTypeExpander\nfrom mypy.erasetype import erase_typevars\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.nodes import (\n    ARG_OPT,\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    CONTRAVARIANT,\n    COVARIANT,\n    ArgKind,\n    TypeInfo,\n)\nfrom mypy.types import (\n    TUPLE_LIKE_INSTANCE_NAMES,\n    AnyType,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    Instance,\n    LiteralType,\n    NoneType,\n    NormalizedCallableType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    TypeVisitor,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    flatten_nested_tuples,\n    get_proper_type,\n    has_recursive_types,\n    has_type_vars,\n    is_named_instance,\n    split_with_prefix_and_suffix,\n)\nfrom mypy.types_utils import is_union_with_any\nfrom mypy.typestate import type_state\n\nif TYPE_CHECKING:\n    from mypy.infer import ArgumentInferContext\n\nSUBTYPE_OF: Final = 0\nSUPERTYPE_OF: Final = 1\n\n\nclass Constraint:\n    \"\"\"A representation of a type constraint.\n\n    It can be either T <: type or T :> type (T is a type variable).\n    \"\"\"\n\n    type_var: TypeVarId\n    op = 0  # SUBTYPE_OF or SUPERTYPE_OF\n    target: Type\n\n    def __init__(self, type_var: TypeVarLikeType, op: int, target: Type) -> None:\n        self.type_var = type_var.id\n        self.op = op\n        # TODO: should we add \"assert not isinstance(target, UnpackType)\"?\n        # UnpackType is a synthetic type, and is never valid as a constraint target.\n        self.target = target\n        self.origin_type_var = type_var\n        # These are additional type variables that should be solved for together with type_var.\n        # TODO: A cleaner solution may be to modify the return type of infer_constraints()\n        # to include these instead, but this is a rather big refactoring.\n        self.extra_tvars: list[TypeVarLikeType] = []\n\n    def __repr__(self) -> str:\n        op_str = \"<:\"\n        if self.op == SUPERTYPE_OF:\n            op_str = \":>\"\n        return f\"{self.type_var} {op_str} {self.target}\"\n\n    def __hash__(self) -> int:\n        return hash((self.type_var, self.op, self.target))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Constraint):\n            return False\n        return (self.type_var, self.op, self.target) == (other.type_var, other.op, other.target)\n\n\ndef infer_constraints_for_callable(\n    callee: CallableType,\n    arg_types: Sequence[Type | None],\n    arg_kinds: list[ArgKind],\n    arg_names: Sequence[str | None] | None,\n    formal_to_actual: list[list[int]],\n    context: ArgumentInferContext,\n) -> list[Constraint]:\n    \"\"\"Infer type variable constraints for a callable and actual arguments.\n\n    Return a list of constraints.\n    \"\"\"\n    constraints: list[Constraint] = []\n    mapper = ArgTypeExpander(context)\n\n    param_spec = callee.param_spec()\n    param_spec_arg_types = []\n    param_spec_arg_names = []\n    param_spec_arg_kinds: list[ArgKind] = []\n\n    incomplete_star_mapping = False\n    for i, actuals in enumerate(formal_to_actual):  # TODO: isn't this `enumerate(arg_types)`?\n        for actual in actuals:\n            if actual is None and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2):  # type: ignore[unreachable]\n                # We can't use arguments to infer ParamSpec constraint, if only some\n                # are present in the current inference pass.\n                incomplete_star_mapping = True  # type: ignore[unreachable]\n                break\n\n    for i, actuals in enumerate(formal_to_actual):\n        if isinstance(callee.arg_types[i], UnpackType):\n            unpack_type = callee.arg_types[i]\n            assert isinstance(unpack_type, UnpackType)\n\n            # In this case we are binding all the actuals to *args,\n            # and we want a constraint that the typevar tuple being unpacked\n            # is equal to a type list of all the actuals.\n            actual_types = []\n\n            unpacked_type = get_proper_type(unpack_type.type)\n            if isinstance(unpacked_type, TypeVarTupleType):\n                tuple_instance = unpacked_type.tuple_fallback\n            elif isinstance(unpacked_type, TupleType):\n                tuple_instance = unpacked_type.partial_fallback\n            else:\n                assert False, \"mypy bug: unhandled constraint inference case\"\n\n            for actual in actuals:\n                actual_arg_type = arg_types[actual]\n                if actual_arg_type is None:\n                    continue\n\n                expanded_actual = mapper.expand_actual_type(\n                    actual_arg_type,\n                    arg_kinds[actual],\n                    callee.arg_names[i],\n                    callee.arg_kinds[i],\n                    allow_unpack=True,\n                )\n\n                if arg_kinds[actual] != ARG_STAR or isinstance(\n                    get_proper_type(actual_arg_type), TupleType\n                ):\n                    actual_types.append(expanded_actual)\n                else:\n                    # If we are expanding an iterable inside * actual, append a homogeneous item instead\n                    actual_types.append(\n                        UnpackType(tuple_instance.copy_modified(args=[expanded_actual]))\n                    )\n\n            if isinstance(unpacked_type, TypeVarTupleType):\n                constraints.append(\n                    Constraint(\n                        unpacked_type,\n                        SUPERTYPE_OF,\n                        TupleType(actual_types, unpacked_type.tuple_fallback),\n                    )\n                )\n            elif isinstance(unpacked_type, TupleType):\n                # Prefixes get converted to positional args, so technically the only case we\n                # should have here is like Tuple[Unpack[Ts], Y1, Y2, Y3]. If this turns out\n                # not to hold we can always handle the prefixes too.\n                inner_unpack = unpacked_type.items[0]\n                assert isinstance(inner_unpack, UnpackType)\n                inner_unpacked_type = get_proper_type(inner_unpack.type)\n                suffix_len = len(unpacked_type.items) - 1\n                if isinstance(inner_unpacked_type, TypeVarTupleType):\n                    # Variadic item can be either *Ts...\n                    constraints.append(\n                        Constraint(\n                            inner_unpacked_type,\n                            SUPERTYPE_OF,\n                            TupleType(\n                                actual_types[:-suffix_len], inner_unpacked_type.tuple_fallback\n                            ),\n                        )\n                    )\n                else:\n                    # ...or it can be a homogeneous tuple.\n                    assert (\n                        isinstance(inner_unpacked_type, Instance)\n                        and inner_unpacked_type.type.fullname == \"builtins.tuple\"\n                    )\n                    for at in actual_types[:-suffix_len]:\n                        constraints.extend(\n                            infer_constraints(inner_unpacked_type.args[0], at, SUPERTYPE_OF)\n                        )\n                # Now handle the suffix (if any).\n                if suffix_len:\n                    for tt, at in zip(unpacked_type.items[1:], actual_types[-suffix_len:]):\n                        constraints.extend(infer_constraints(tt, at, SUPERTYPE_OF))\n            else:\n                assert False, \"mypy bug: unhandled constraint inference case\"\n        else:\n            for actual in actuals:\n                actual_arg_type = arg_types[actual]\n                if actual_arg_type is None:\n                    continue\n\n                if param_spec and callee.arg_kinds[i] in (ARG_STAR, ARG_STAR2):\n                    # If actual arguments are mapped to ParamSpec type, we can't infer individual\n                    # constraints, instead store them and infer single constraint at the end.\n                    # It is impossible to map actual kind to formal kind, so use some heuristic.\n                    # This inference is used as a fallback, so relying on heuristic should be OK.\n                    if not incomplete_star_mapping:\n                        param_spec_arg_types.append(\n                            mapper.expand_actual_type(\n                                actual_arg_type, arg_kinds[actual], None, arg_kinds[actual]\n                            )\n                        )\n                        actual_kind = arg_kinds[actual]\n                        param_spec_arg_kinds.append(\n                            ARG_POS if actual_kind not in (ARG_STAR, ARG_STAR2) else actual_kind\n                        )\n                        param_spec_arg_names.append(arg_names[actual] if arg_names else None)\n                else:\n                    actual_type = mapper.expand_actual_type(\n                        actual_arg_type,\n                        arg_kinds[actual],\n                        callee.arg_names[i],\n                        callee.arg_kinds[i],\n                    )\n                    c = infer_constraints(callee.arg_types[i], actual_type, SUPERTYPE_OF)\n                    constraints.extend(c)\n    if (\n        param_spec\n        and not any(c.type_var == param_spec.id for c in constraints)\n        and not incomplete_star_mapping\n    ):\n        # Use ParamSpec constraint from arguments only if there are no other constraints,\n        # since as explained above it is quite ad-hoc.\n        constraints.append(\n            Constraint(\n                param_spec,\n                SUPERTYPE_OF,\n                Parameters(\n                    arg_types=param_spec_arg_types,\n                    arg_kinds=param_spec_arg_kinds,\n                    arg_names=param_spec_arg_names,\n                    imprecise_arg_kinds=True,\n                ),\n            )\n        )\n    if any(isinstance(v, ParamSpecType) for v in callee.variables):\n        # As a perf optimization filter imprecise constraints only when we can have them.\n        constraints = filter_imprecise_kinds(constraints)\n    return constraints\n\n\ndef infer_constraints(\n    template: Type, actual: Type, direction: int, skip_neg_op: bool = False\n) -> list[Constraint]:\n    \"\"\"Infer type constraints.\n\n    Match a template type, which may contain type variable references,\n    recursively against a type which does not contain (the same) type\n    variable references. The result is a list of type constrains of\n    form 'T is a supertype/subtype of x', where T is a type variable\n    present in the template and x is a type without reference to type\n    variables present in the template.\n\n    Assume T and S are type variables. Now the following results can be\n    calculated (read as '(template, actual) --> result'):\n\n      (T, X)            -->  T :> X\n      (X[T], X[Y])      -->  T <: Y and T :> Y\n      ((T, T), (X, Y))  -->  T :> X and T :> Y\n      ((T, S), (X, Y))  -->  T :> X and S :> Y\n      (X[T], Any)       -->  T <: Any and T :> Any\n\n    The constraints are represented as Constraint objects. If skip_neg_op == True,\n    then skip adding reverse (polymorphic) constraints (since this is already a call\n    to infer such constraints).\n    \"\"\"\n    if any(\n        get_proper_type(template) == get_proper_type(t)\n        and get_proper_type(actual) == get_proper_type(a)\n        for (t, a) in reversed(type_state.inferring)\n    ):\n        return []\n    if has_recursive_types(template) or isinstance(get_proper_type(template), Instance):\n        # This case requires special care because it may cause infinite recursion.\n        # Note that we include Instances because the may be recursive as str(Sequence[str]).\n        if not has_type_vars(template):\n            # Return early on an empty branch.\n            return []\n        type_state.inferring.append((template, actual))\n        res = _infer_constraints(template, actual, direction, skip_neg_op)\n        type_state.inferring.pop()\n        return res\n    return _infer_constraints(template, actual, direction, skip_neg_op)\n\n\ndef _infer_constraints(\n    template: Type, actual: Type, direction: int, skip_neg_op: bool\n) -> list[Constraint]:\n    orig_template = template\n    template = get_proper_type(template)\n    actual = get_proper_type(actual)\n\n    # Type inference shouldn't be affected by whether union types have been simplified.\n    # We however keep any ErasedType items, so that the caller will see it when using\n    # checkexpr.has_erased_component().\n    if isinstance(template, UnionType):\n        template = mypy.typeops.make_simplified_union(template.items, keep_erased=True)\n    if isinstance(actual, UnionType):\n        actual = mypy.typeops.make_simplified_union(actual.items, keep_erased=True)\n\n    # Ignore Any types from the type suggestion engine to avoid them\n    # causing us to infer Any in situations where a better job could\n    # be done otherwise. (This can produce false positives but that\n    # doesn't really matter because it is all heuristic anyway.)\n    if isinstance(actual, AnyType) and actual.type_of_any == TypeOfAny.suggestion_engine:\n        return []\n\n    # type[A | B] is always represented as type[A] | type[B] internally.\n    # This makes our constraint solver choke on type[T] <: type[A] | type[B],\n    # solving T as generic meet(A, B) which is often `object`. Force unwrap such unions\n    # if both sides are type[...] or unions thereof. See `testTypeVarType` test\n    type_type_unwrapped = False\n    if _is_type_type(template) and _is_type_type(actual):\n        type_type_unwrapped = True\n        template = _unwrap_type_type(template)\n        actual = _unwrap_type_type(actual)\n\n    # If the template is simply a type variable, emit a Constraint directly.\n    # We need to handle this case before handling Unions for two reasons:\n    #  1. \"T <: Union[U1, U2]\" is not equivalent to \"T <: U1 or T <: U2\",\n    #     because T can itself be a union (notably, Union[U1, U2] itself).\n    #  2. \"T :> Union[U1, U2]\" is logically equivalent to \"T :> U1 and\n    #     T :> U2\", but they are not equivalent to the constraint solver,\n    #     which never introduces new Union types (it uses join() instead).\n    if isinstance(template, TypeVarType):\n        return [Constraint(template, direction, actual)]\n\n    if (\n        isinstance(actual, TypeVarType)\n        and not actual.id.is_meta_var()\n        and direction == SUPERTYPE_OF\n    ):\n        # Unless template is also a type variable (or a union that contains one), using the upper\n        # bound for inference will usually give better result for actual that is a type variable.\n        if not isinstance(template, UnionType) or not any(\n            isinstance(t, TypeVarType) for t in template.items\n        ):\n            actual = get_proper_type(actual.upper_bound)\n\n    # Now handle the case of either template or actual being a Union.\n    # For a Union to be a subtype of another type, every item of the Union\n    # must be a subtype of that type, so concatenate the constraints.\n    if direction == SUBTYPE_OF and isinstance(template, UnionType):\n        res = []\n        for t_item in template.items:\n            res.extend(infer_constraints(t_item, actual, direction))\n        return res\n    if direction == SUPERTYPE_OF and isinstance(actual, UnionType):\n        res = []\n        for a_item in actual.items:\n            # `orig_template` has to be preserved intact in case it's recursive.\n            # If we unwrapped ``type[...]`` previously, wrap the item back again,\n            # as ``type[...]`` can't be removed from `orig_template`.\n            if type_type_unwrapped:\n                a_item = TypeType.make_normalized(a_item)\n            res.extend(infer_constraints(orig_template, a_item, direction))\n        return res\n\n    # Now the potential subtype is known not to be a Union or a type\n    # variable that we are solving for. In that case, for a Union to\n    # be a supertype of the potential subtype, some item of the Union\n    # must be a supertype of it.\n    if direction == SUBTYPE_OF and isinstance(actual, UnionType):\n        # We infer constraints eagerly -- try to find constraints for a type\n        # variable if possible. This seems to help with some real-world\n        # use cases.\n        return any_constraints(\n            [\n                infer_constraints_if_possible(template, a_item, direction)\n                for a_item in actual.items\n            ],\n            eager=True,\n        )\n    if direction == SUPERTYPE_OF and isinstance(template, UnionType):\n        # When the template is a union, we are okay with leaving some\n        # type variables indeterminate. This helps with some special\n        # cases, though this isn't very principled.\n        result = any_constraints(\n            [\n                infer_constraints_if_possible(t_item, actual, direction)\n                for t_item in template.items\n            ],\n            eager=isinstance(actual, AnyType),\n        )\n        if result:\n            return result\n        elif has_recursive_types(template) and not has_recursive_types(actual):\n            return handle_recursive_union(template, actual, direction)\n        return []\n\n    # Remaining cases are handled by ConstraintBuilderVisitor.\n    return template.accept(ConstraintBuilderVisitor(actual, direction, skip_neg_op))\n\n\ndef _is_type_type(tp: ProperType) -> TypeGuard[TypeType | UnionType]:\n    \"\"\"Is ``tp`` a ``type[...]`` or a union thereof?\n\n    ``Type[A | B]`` is internally represented as ``type[A] | type[B]``, and this\n    troubles the solver sometimes.\n    \"\"\"\n    return (\n        isinstance(tp, TypeType)\n        or isinstance(tp, UnionType)\n        and all(isinstance(get_proper_type(o), TypeType) for o in tp.items)\n    )\n\n\ndef _unwrap_type_type(tp: TypeType | UnionType) -> ProperType:\n    \"\"\"Extract the inner type from ``type[...]`` expression or a union thereof.\"\"\"\n    if isinstance(tp, TypeType):\n        return tp.item\n    return UnionType.make_union([cast(TypeType, get_proper_type(o)).item for o in tp.items])\n\n\ndef infer_constraints_if_possible(\n    template: Type, actual: Type, direction: int\n) -> list[Constraint] | None:\n    \"\"\"Like infer_constraints, but return None if the input relation is\n    known to be unsatisfiable, for example if template=List[T] and actual=int.\n    (In this case infer_constraints would return [], just like it would for\n    an automatically satisfied relation like template=List[T] and actual=object.)\n    \"\"\"\n    if direction == SUBTYPE_OF and not mypy.subtypes.is_subtype(erase_typevars(template), actual):\n        return None\n    if direction == SUPERTYPE_OF and not mypy.subtypes.is_subtype(\n        actual, erase_typevars(template)\n    ):\n        return None\n    if (\n        direction == SUPERTYPE_OF\n        and isinstance(template, TypeVarType)\n        and not mypy.subtypes.is_subtype(actual, erase_typevars(template.upper_bound))\n    ):\n        # This is not caught by the above branch because of the erase_typevars() call,\n        # that would return 'Any' for a type variable.\n        return None\n    return infer_constraints(template, actual, direction)\n\n\ndef select_trivial(options: Sequence[list[Constraint] | None]) -> list[list[Constraint]]:\n    \"\"\"Select only those lists where each item is a constraint against Any.\"\"\"\n    res = []\n    for option in options:\n        if option is None:\n            continue\n        if all(isinstance(get_proper_type(c.target), AnyType) for c in option):\n            res.append(option)\n    return res\n\n\ndef merge_with_any(constraint: Constraint) -> Constraint:\n    \"\"\"Transform a constraint target into a union with given Any type.\"\"\"\n    target = constraint.target\n    if is_union_with_any(target):\n        # Do not produce redundant unions.\n        return constraint\n    # TODO: if we will support multiple sources Any, use this here instead.\n    any_type = AnyType(TypeOfAny.implementation_artifact)\n    return Constraint(\n        constraint.origin_type_var,\n        constraint.op,\n        UnionType.make_union([target, any_type], target.line, target.column),\n    )\n\n\ndef handle_recursive_union(template: UnionType, actual: Type, direction: int) -> list[Constraint]:\n    # This is a hack to special-case things like Union[T, Inst[T]] in recursive types. Although\n    # it is quite arbitrary, it is a relatively common pattern, so we should handle it well.\n    # This function may be called when inferring against such union resulted in different\n    # constraints for each item. Normally we give up in such case, but here we instead split\n    # the union in two parts, and try inferring sequentially.\n    non_type_var_items = [t for t in template.items if not isinstance(t, TypeVarType)]\n    type_var_items = [t for t in template.items if isinstance(t, TypeVarType)]\n    return infer_constraints(\n        UnionType.make_union(non_type_var_items), actual, direction\n    ) or infer_constraints(UnionType.make_union(type_var_items), actual, direction)\n\n\ndef any_constraints(options: list[list[Constraint] | None], *, eager: bool) -> list[Constraint]:\n    \"\"\"Deduce what we can from a collection of constraint lists.\n\n    It's a given that at least one of the lists must be satisfied. A\n    None element in the list of options represents an unsatisfiable\n    constraint and is ignored.  Ignore empty constraint lists if eager\n    is true -- they are always trivially satisfiable.\n    \"\"\"\n    if eager:\n        valid_options = [option for option in options if option]\n    else:\n        valid_options = [option for option in options if option is not None]\n\n    if not valid_options:\n        return []\n\n    if len(valid_options) == 1:\n        return valid_options[0]\n\n    if all(is_same_constraints(valid_options[0], c) for c in valid_options[1:]):\n        # Multiple sets of constraints that are all the same. Just pick any one of them.\n        return valid_options[0]\n\n    if all(is_similar_constraints(valid_options[0], c) for c in valid_options[1:]):\n        # All options have same structure. In this case we can merge-in trivial\n        # options (i.e. those that only have Any) and try again.\n        # TODO: More generally, if a given (variable, direction) pair appears in\n        # every option, combine the bounds with meet/join always, not just for Any.\n        trivial_options = select_trivial(valid_options)\n        if trivial_options and len(trivial_options) < len(valid_options):\n            merged_options = []\n            for option in valid_options:\n                if option in trivial_options:\n                    continue\n                merged_options.append([merge_with_any(c) for c in option])\n            return any_constraints(list(merged_options), eager=eager)\n\n    # If normal logic didn't work, try excluding trivially unsatisfiable constraint (due to\n    # upper bounds) from each option, and comparing them again.\n    filtered_options = [filter_satisfiable(o) for o in options]\n    if filtered_options != options:\n        return any_constraints(filtered_options, eager=eager)\n\n    # Try harder: if that didn't work, try to strip typevars that aren't meta vars.\n    # Note this is what we would always do, but unfortunately some callers may not\n    # set the meta var status correctly (for historical reasons), so we use this as\n    # a fallback only.\n    filtered_options = [exclude_non_meta_vars(o) for o in options]\n    if filtered_options != options:\n        return any_constraints(filtered_options, eager=eager)\n\n    # Otherwise, there are either no valid options or multiple, inconsistent valid\n    # options. Give up and deduce nothing.\n    return []\n\n\ndef filter_satisfiable(option: list[Constraint] | None) -> list[Constraint] | None:\n    \"\"\"Keep only constraints that can possibly be satisfied.\n\n    Currently, we filter out constraints where target is not a subtype of the upper bound.\n    Since those can be never satisfied. We may add more cases in future if it improves type\n    inference.\n    \"\"\"\n    if not option:\n        return option\n\n    satisfiable = []\n    for c in option:\n        if isinstance(c.origin_type_var, TypeVarType) and c.origin_type_var.values:\n            if any(\n                mypy.subtypes.is_subtype(c.target, value) for value in c.origin_type_var.values\n            ):\n                satisfiable.append(c)\n        elif mypy.subtypes.is_subtype(c.target, c.origin_type_var.upper_bound):\n            satisfiable.append(c)\n    if not satisfiable:\n        return None\n    return satisfiable\n\n\ndef exclude_non_meta_vars(option: list[Constraint] | None) -> list[Constraint] | None:\n    # If we had an empty list, keep it intact\n    if not option:\n        return option\n    # However, if none of the options actually references meta vars, better remove\n    # this constraint entirely.\n    return [c for c in option if c.type_var.is_meta_var()] or None\n\n\ndef is_same_constraints(x: list[Constraint], y: list[Constraint]) -> bool:\n    for c1 in x:\n        if not any(is_same_constraint(c1, c2) for c2 in y):\n            return False\n    for c1 in y:\n        if not any(is_same_constraint(c1, c2) for c2 in x):\n            return False\n    return True\n\n\ndef is_same_constraint(c1: Constraint, c2: Constraint) -> bool:\n    # Ignore direction when comparing constraints against Any.\n    skip_op_check = isinstance(get_proper_type(c1.target), AnyType) and isinstance(\n        get_proper_type(c2.target), AnyType\n    )\n    return (\n        c1.type_var == c2.type_var\n        and (c1.op == c2.op or skip_op_check)\n        and mypy.subtypes.is_same_type(c1.target, c2.target)\n    )\n\n\ndef is_similar_constraints(x: list[Constraint], y: list[Constraint]) -> bool:\n    \"\"\"Check that two lists of constraints have similar structure.\n\n    This means that each list has same type variable plus direction pairs (i.e we\n    ignore the target). Except for constraints where target is Any type, there\n    we ignore direction as well.\n    \"\"\"\n    return _is_similar_constraints(x, y) and _is_similar_constraints(y, x)\n\n\ndef _is_similar_constraints(x: list[Constraint], y: list[Constraint]) -> bool:\n    \"\"\"Check that every constraint in the first list has a similar one in the second.\n\n    See docstring above for definition of similarity.\n    \"\"\"\n    for c1 in x:\n        has_similar = False\n        for c2 in y:\n            # Ignore direction when either constraint is against Any.\n            skip_op_check = isinstance(get_proper_type(c1.target), AnyType) or isinstance(\n                get_proper_type(c2.target), AnyType\n            )\n            if c1.type_var == c2.type_var and (c1.op == c2.op or skip_op_check):\n                has_similar = True\n                break\n        if not has_similar:\n            return False\n    return True\n\n\nclass ConstraintBuilderVisitor(TypeVisitor[list[Constraint]]):\n    \"\"\"Visitor class for inferring type constraints.\"\"\"\n\n    # The type that is compared against a template\n    # TODO: The value may be None. Is that actually correct?\n    actual: ProperType\n\n    def __init__(self, actual: ProperType, direction: int, skip_neg_op: bool) -> None:\n        # Direction must be SUBTYPE_OF or SUPERTYPE_OF.\n        self.actual = actual\n        self.direction = direction\n        # Whether to skip polymorphic inference (involves inference in opposite direction)\n        # this is used to prevent infinite recursion when both template and actual are\n        # generic callables.\n        self.skip_neg_op = skip_neg_op\n\n    # Trivial leaf types\n\n    def visit_unbound_type(self, template: UnboundType) -> list[Constraint]:\n        return []\n\n    def visit_any(self, template: AnyType) -> list[Constraint]:\n        return []\n\n    def visit_none_type(self, template: NoneType) -> list[Constraint]:\n        return []\n\n    def visit_uninhabited_type(self, template: UninhabitedType) -> list[Constraint]:\n        return []\n\n    def visit_erased_type(self, template: ErasedType) -> list[Constraint]:\n        return []\n\n    def visit_deleted_type(self, template: DeletedType) -> list[Constraint]:\n        return []\n\n    def visit_literal_type(self, template: LiteralType) -> list[Constraint]:\n        return []\n\n    # Errors\n\n    def visit_partial_type(self, template: PartialType) -> list[Constraint]:\n        # We can't do anything useful with a partial type here.\n        assert False, \"Internal error\"\n\n    # Non-trivial leaf type\n\n    def visit_type_var(self, template: TypeVarType) -> list[Constraint]:\n        assert False, (\n            \"Unexpected TypeVarType in ConstraintBuilderVisitor\"\n            \" (should have been handled in infer_constraints)\"\n        )\n\n    def visit_param_spec(self, template: ParamSpecType) -> list[Constraint]:\n        # Can't infer ParamSpecs from component values (only via Callable[P, T]).\n        return []\n\n    def visit_type_var_tuple(self, template: TypeVarTupleType) -> list[Constraint]:\n        raise NotImplementedError\n\n    def visit_unpack_type(self, template: UnpackType) -> list[Constraint]:\n        raise RuntimeError(\"Mypy bug: unpack should be handled at a higher level.\")\n\n    def visit_parameters(self, template: Parameters) -> list[Constraint]:\n        # Constraining Any against C[P] turns into infer_against_any([P], Any)\n        if isinstance(self.actual, AnyType):\n            return self.infer_against_any(template.arg_types, self.actual)\n        if type_state.infer_polymorphic and isinstance(self.actual, Parameters):\n            # For polymorphic inference we need to be able to infer secondary constraints\n            # in situations like [x: T] <: P <: [x: int].\n            return infer_callable_arguments_constraints(template, self.actual, self.direction)\n        if type_state.infer_polymorphic and isinstance(self.actual, ParamSpecType):\n            # Similar for [x: T] <: Q <: Concatenate[int, P].\n            return infer_callable_arguments_constraints(\n                template, self.actual.prefix, self.direction\n            )\n        # There also may be unpatched types after a user error, simply ignore them.\n        return []\n\n    # Non-leaf types\n\n    def visit_instance(self, template: Instance) -> list[Constraint]:\n        original_actual = actual = self.actual\n        res: list[Constraint] = []\n        if isinstance(actual, (CallableType, Overloaded)) and template.type.is_protocol:\n            if \"__call__\" in template.type.protocol_members:\n                # Special case: a generic callback protocol\n                if not any(template == t for t in template.type.inferring):\n                    template.type.inferring.append(template)\n                    call = mypy.subtypes.find_member(\n                        \"__call__\", template, actual, is_operator=True\n                    )\n                    assert call is not None\n                    if (\n                        self.direction == SUPERTYPE_OF\n                        and mypy.subtypes.is_subtype(actual, erase_typevars(call))\n                        or self.direction == SUBTYPE_OF\n                        and mypy.subtypes.is_subtype(erase_typevars(call), actual)\n                    ):\n                        res.extend(infer_constraints(call, actual, self.direction))\n                    template.type.inferring.pop()\n        if isinstance(actual, CallableType) and actual.fallback is not None:\n            if (\n                actual.is_type_obj()\n                and template.type.is_protocol\n                and self.direction == SUPERTYPE_OF\n            ):\n                ret_type = get_proper_type(actual.ret_type)\n                if isinstance(ret_type, TupleType):\n                    ret_type = mypy.typeops.tuple_fallback(ret_type)\n                if isinstance(ret_type, Instance):\n                    res.extend(\n                        self.infer_constraints_from_protocol_members(\n                            ret_type, template, ret_type, template, class_obj=True\n                        )\n                    )\n            actual = actual.fallback\n        if isinstance(actual, TypeType) and template.type.is_protocol:\n            if self.direction == SUPERTYPE_OF:\n                a_item = actual.item\n                if isinstance(a_item, Instance):\n                    res.extend(\n                        self.infer_constraints_from_protocol_members(\n                            a_item, template, a_item, template, class_obj=True\n                        )\n                    )\n                # Infer constraints for Type[T] via metaclass of T when it makes sense.\n                if isinstance(a_item, TypeVarType):\n                    a_item = get_proper_type(a_item.upper_bound)\n                if isinstance(a_item, Instance) and a_item.type.metaclass_type:\n                    res.extend(\n                        self.infer_constraints_from_protocol_members(\n                            a_item.type.metaclass_type, template, actual, template\n                        )\n                    )\n\n        if isinstance(actual, Overloaded) and actual.fallback is not None:\n            actual = actual.fallback\n        if isinstance(actual, TypedDictType):\n            actual = actual.create_anonymous_fallback()\n        if isinstance(actual, LiteralType):\n            actual = actual.fallback\n        if isinstance(actual, Instance):\n            instance = actual\n            erased = erase_typevars(template)\n            assert isinstance(erased, Instance)  # type: ignore[misc]\n            # We always try nominal inference if possible,\n            # it is much faster than the structural one.\n            if self.direction == SUBTYPE_OF and template.type.has_base(instance.type.fullname):\n                mapped = map_instance_to_supertype(template, instance.type)\n                tvars = mapped.type.defn.type_vars\n\n                if instance.type.has_type_var_tuple_type:\n                    # Variadic types need special handling to map each type argument to\n                    # the correct corresponding type variable.\n                    assert instance.type.type_var_tuple_prefix is not None\n                    assert instance.type.type_var_tuple_suffix is not None\n                    prefix_len = instance.type.type_var_tuple_prefix\n                    suffix_len = instance.type.type_var_tuple_suffix\n                    tvt = instance.type.defn.type_vars[prefix_len]\n                    assert isinstance(tvt, TypeVarTupleType)\n                    fallback = tvt.tuple_fallback\n                    i_prefix, i_middle, i_suffix = split_with_prefix_and_suffix(\n                        instance.args, prefix_len, suffix_len\n                    )\n                    m_prefix, m_middle, m_suffix = split_with_prefix_and_suffix(\n                        mapped.args, prefix_len, suffix_len\n                    )\n                    instance_args = i_prefix + (TupleType(list(i_middle), fallback),) + i_suffix\n                    mapped_args = m_prefix + (TupleType(list(m_middle), fallback),) + m_suffix\n                else:\n                    mapped_args = mapped.args\n                    instance_args = instance.args\n\n                # N.B: We use zip instead of indexing because the lengths might have\n                # mismatches during daemon reprocessing.\n                for tvar, mapped_arg, instance_arg in zip(tvars, mapped_args, instance_args):\n                    if isinstance(tvar, TypeVarType):\n                        # The constraints for generic type parameters depend on variance.\n                        # Include constraints from both directions if invariant.\n                        if tvar.variance != CONTRAVARIANT:\n                            res.extend(infer_constraints(mapped_arg, instance_arg, self.direction))\n                        if tvar.variance != COVARIANT:\n                            res.extend(\n                                infer_constraints(mapped_arg, instance_arg, neg_op(self.direction))\n                            )\n                    elif isinstance(tvar, ParamSpecType) and isinstance(mapped_arg, ParamSpecType):\n                        prefix = mapped_arg.prefix\n                        if isinstance(instance_arg, Parameters):\n                            # No such thing as variance for ParamSpecs, consider them invariant\n                            # TODO: constraints between prefixes using\n                            # infer_callable_arguments_constraints()\n                            suffix: Type = instance_arg.copy_modified(\n                                instance_arg.arg_types[len(prefix.arg_types) :],\n                                instance_arg.arg_kinds[len(prefix.arg_kinds) :],\n                                instance_arg.arg_names[len(prefix.arg_names) :],\n                            )\n                            res.append(Constraint(mapped_arg, SUBTYPE_OF, suffix))\n                            res.append(Constraint(mapped_arg, SUPERTYPE_OF, suffix))\n                        elif isinstance(instance_arg, ParamSpecType):\n                            suffix = instance_arg.copy_modified(\n                                prefix=Parameters(\n                                    instance_arg.prefix.arg_types[len(prefix.arg_types) :],\n                                    instance_arg.prefix.arg_kinds[len(prefix.arg_kinds) :],\n                                    instance_arg.prefix.arg_names[len(prefix.arg_names) :],\n                                )\n                            )\n                            res.append(Constraint(mapped_arg, SUBTYPE_OF, suffix))\n                            res.append(Constraint(mapped_arg, SUPERTYPE_OF, suffix))\n                    elif isinstance(tvar, TypeVarTupleType):\n                        # Handle variadic type variables covariantly for consistency.\n                        res.extend(infer_constraints(mapped_arg, instance_arg, self.direction))\n\n                return res\n            elif self.direction == SUPERTYPE_OF and instance.type.has_base(template.type.fullname):\n                mapped = map_instance_to_supertype(instance, template.type)\n                tvars = template.type.defn.type_vars\n                if template.type.has_type_var_tuple_type:\n                    # Variadic types need special handling to map each type argument to\n                    # the correct corresponding type variable.\n                    assert template.type.type_var_tuple_prefix is not None\n                    assert template.type.type_var_tuple_suffix is not None\n                    prefix_len = template.type.type_var_tuple_prefix\n                    suffix_len = template.type.type_var_tuple_suffix\n                    tvt = template.type.defn.type_vars[prefix_len]\n                    assert isinstance(tvt, TypeVarTupleType)\n                    fallback = tvt.tuple_fallback\n                    t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(\n                        template.args, prefix_len, suffix_len\n                    )\n                    m_prefix, m_middle, m_suffix = split_with_prefix_and_suffix(\n                        mapped.args, prefix_len, suffix_len\n                    )\n                    template_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix\n                    mapped_args = m_prefix + (TupleType(list(m_middle), fallback),) + m_suffix\n                else:\n                    mapped_args = mapped.args\n                    template_args = template.args\n                # N.B: We use zip instead of indexing because the lengths might have\n                # mismatches during daemon reprocessing.\n                for tvar, mapped_arg, template_arg in zip(tvars, mapped_args, template_args):\n                    if isinstance(tvar, TypeVarType):\n                        # The constraints for generic type parameters depend on variance.\n                        # Include constraints from both directions if invariant.\n                        if tvar.variance != CONTRAVARIANT:\n                            res.extend(infer_constraints(template_arg, mapped_arg, self.direction))\n                        if tvar.variance != COVARIANT:\n                            res.extend(\n                                infer_constraints(template_arg, mapped_arg, neg_op(self.direction))\n                            )\n                    elif isinstance(tvar, ParamSpecType) and isinstance(\n                        template_arg, ParamSpecType\n                    ):\n                        prefix = template_arg.prefix\n                        if isinstance(mapped_arg, Parameters):\n                            # No such thing as variance for ParamSpecs, consider them invariant\n                            # TODO: constraints between prefixes using\n                            # infer_callable_arguments_constraints()\n                            suffix = mapped_arg.copy_modified(\n                                mapped_arg.arg_types[len(prefix.arg_types) :],\n                                mapped_arg.arg_kinds[len(prefix.arg_kinds) :],\n                                mapped_arg.arg_names[len(prefix.arg_names) :],\n                            )\n                            res.append(Constraint(template_arg, SUBTYPE_OF, suffix))\n                            res.append(Constraint(template_arg, SUPERTYPE_OF, suffix))\n                        elif isinstance(mapped_arg, ParamSpecType):\n                            suffix = mapped_arg.copy_modified(\n                                prefix=Parameters(\n                                    mapped_arg.prefix.arg_types[len(prefix.arg_types) :],\n                                    mapped_arg.prefix.arg_kinds[len(prefix.arg_kinds) :],\n                                    mapped_arg.prefix.arg_names[len(prefix.arg_names) :],\n                                )\n                            )\n                            res.append(Constraint(template_arg, SUBTYPE_OF, suffix))\n                            res.append(Constraint(template_arg, SUPERTYPE_OF, suffix))\n                    elif isinstance(tvar, TypeVarTupleType):\n                        # Consider variadic type variables to be invariant.\n                        res.extend(infer_constraints(template_arg, mapped_arg, SUBTYPE_OF))\n                        res.extend(infer_constraints(template_arg, mapped_arg, SUPERTYPE_OF))\n                return res\n            if (\n                template.type.is_protocol\n                and self.direction == SUPERTYPE_OF\n                and\n                # We avoid infinite recursion for structural subtypes by checking\n                # whether this type already appeared in the inference chain.\n                # This is a conservative way to break the inference cycles.\n                # It never produces any \"false\" constraints but gives up soon\n                # on purely structural inference cycles, see #3829.\n                # Note that we use is_protocol_implementation instead of is_subtype\n                # because some type may be considered a subtype of a protocol\n                # due to _promote, but still not implement the protocol.\n                not any(template == t for t in reversed(template.type.inferring))\n                and mypy.subtypes.is_protocol_implementation(instance, erased, skip=[\"__call__\"])\n            ):\n                template.type.inferring.append(template)\n                res.extend(\n                    self.infer_constraints_from_protocol_members(\n                        instance, template, original_actual, template\n                    )\n                )\n                template.type.inferring.pop()\n                return res\n            elif (\n                instance.type.is_protocol\n                and self.direction == SUBTYPE_OF\n                and\n                # We avoid infinite recursion for structural subtypes also here.\n                not any(instance == i for i in reversed(instance.type.inferring))\n                and mypy.subtypes.is_protocol_implementation(erased, instance, skip=[\"__call__\"])\n            ):\n                instance.type.inferring.append(instance)\n                res.extend(\n                    self.infer_constraints_from_protocol_members(\n                        instance, template, template, instance\n                    )\n                )\n                instance.type.inferring.pop()\n                return res\n        if res:\n            return res\n\n        if isinstance(actual, AnyType):\n            return self.infer_against_any(template.args, actual)\n        if (\n            isinstance(actual, TupleType)\n            and is_named_instance(template, TUPLE_LIKE_INSTANCE_NAMES)\n            and self.direction == SUPERTYPE_OF\n        ):\n            for item in actual.items:\n                if isinstance(item, UnpackType):\n                    unpacked = get_proper_type(item.type)\n                    if isinstance(unpacked, TypeVarTupleType):\n                        # Cannot infer anything for T from [T, ...] <: *Ts\n                        continue\n                    assert (\n                        isinstance(unpacked, Instance)\n                        and unpacked.type.fullname == \"builtins.tuple\"\n                    )\n                    item = unpacked.args[0]\n                cb = infer_constraints(template.args[0], item, SUPERTYPE_OF)\n                res.extend(cb)\n            return res\n        elif isinstance(actual, TupleType) and self.direction == SUPERTYPE_OF:\n            return infer_constraints(template, mypy.typeops.tuple_fallback(actual), self.direction)\n        elif isinstance(actual, TypeVarType):\n            if not actual.values and not actual.id.is_meta_var():\n                return infer_constraints(template, actual.upper_bound, self.direction)\n            return []\n        elif isinstance(actual, ParamSpecType):\n            return infer_constraints(template, actual.upper_bound, self.direction)\n        elif isinstance(actual, TypeVarTupleType):\n            raise NotImplementedError\n        else:\n            return []\n\n    def infer_constraints_from_protocol_members(\n        self,\n        instance: Instance,\n        template: Instance,\n        subtype: Type,\n        protocol: Instance,\n        class_obj: bool = False,\n    ) -> list[Constraint]:\n        \"\"\"Infer constraints for situations where either 'template' or 'instance' is a protocol.\n\n        The 'protocol' is the one of two that is an instance of protocol type, 'subtype'\n        is the type used to bind self during inference. Currently, we just infer constrains for\n        every protocol member type (both ways for settable members).\n        \"\"\"\n        res = []\n        for member in protocol.type.protocol_members:\n            inst = mypy.subtypes.find_member(member, instance, subtype, class_obj=class_obj)\n            temp = mypy.subtypes.find_member(member, template, subtype)\n            if inst is None or temp is None:\n                if member == \"__call__\":\n                    continue\n                return []  # See #11020\n            # The above is safe since at this point we know that 'instance' is a subtype\n            # of (erased) 'template', therefore it defines all protocol members\n            if class_obj:\n                # For class objects we must only infer constraints if possible, otherwise it\n                # can lead to confusion between class and instance, for example StrEnum is\n                # Iterable[str] for an instance, but Iterable[StrEnum] for a class object.\n                if not mypy.subtypes.is_subtype(\n                    inst, erase_typevars(temp), ignore_pos_arg_names=True\n                ):\n                    continue\n            # This exception matches the one in typeops.py, see PR #14121 for context.\n            if member == \"__call__\" and instance.type.is_metaclass(precise=True):\n                continue\n            res.extend(infer_constraints(temp, inst, self.direction))\n            if mypy.subtypes.IS_SETTABLE in mypy.subtypes.get_member_flags(member, protocol):\n                # Settable members are invariant, add opposite constraints\n                res.extend(infer_constraints(temp, inst, neg_op(self.direction)))\n        return res\n\n    def visit_callable_type(self, template: CallableType) -> list[Constraint]:\n        # Normalize callables before matching against each other.\n        # Note that non-normalized callables can be created in annotations\n        # using e.g. callback protocols.\n        # TODO: check that callables match? Ideally we should not infer constraints\n        # callables that can never be subtypes of one another in given direction.\n        template = template.with_unpacked_kwargs().with_normalized_var_args()\n        extra_tvars = False\n        if isinstance(self.actual, CallableType):\n            res: list[Constraint] = []\n            cactual = self.actual.with_unpacked_kwargs().with_normalized_var_args()\n            param_spec = template.param_spec()\n\n            template_ret_type, cactual_ret_type = template.ret_type, cactual.ret_type\n            if template.type_guard is not None and cactual.type_guard is not None:\n                template_ret_type = template.type_guard\n                cactual_ret_type = cactual.type_guard\n\n            if template.type_is is not None and cactual.type_is is not None:\n                template_ret_type = template.type_is\n                cactual_ret_type = cactual.type_is\n\n            res.extend(infer_constraints(template_ret_type, cactual_ret_type, self.direction))\n\n            if param_spec is None:\n                # TODO: Erase template variables if it is generic?\n                if (\n                    type_state.infer_polymorphic\n                    and cactual.variables\n                    and not self.skip_neg_op\n                    # Technically, the correct inferred type for application of e.g.\n                    # Callable[..., T] -> Callable[..., T] (with literal ellipsis), to a generic\n                    # like U -> U, should be Callable[..., Any], but if U is a self-type, we can\n                    # allow it to leak, to be later bound to self. A bunch of existing code\n                    # depends on this old behaviour.\n                    and not (\n                        any(tv.id.is_self() for tv in cactual.variables)\n                        and template.is_ellipsis_args\n                    )\n                ):\n                    # If the actual callable is generic, infer constraints in the opposite\n                    # direction, and indicate to the solver there are extra type variables\n                    # to solve for (see more details in mypy/solve.py).\n                    res.extend(\n                        infer_constraints(\n                            cactual, template, neg_op(self.direction), skip_neg_op=True\n                        )\n                    )\n                    extra_tvars = True\n\n                # We can't infer constraints from arguments if the template is Callable[..., T]\n                # (with literal '...').\n                if not template.is_ellipsis_args:\n                    unpack_present = find_unpack_in_list(template.arg_types)\n                    # When both ParamSpec and TypeVarTuple are present, things become messy\n                    # quickly. For now, we only allow ParamSpec to \"capture\" TypeVarTuple,\n                    # but not vice versa.\n                    # TODO: infer more from prefixes when possible.\n                    if unpack_present is not None and not cactual.param_spec():\n                        # We need to re-normalize args to the form they appear in tuples,\n                        # for callables we always pack the suffix inside another tuple.\n                        unpack = template.arg_types[unpack_present]\n                        assert isinstance(unpack, UnpackType)\n                        tuple_type = get_tuple_fallback_from_unpack(unpack)\n                        template_types = repack_callable_args(template, tuple_type)\n                        actual_types = repack_callable_args(cactual, tuple_type)\n                        # Now we can use the same general helper as for tuple types.\n                        unpack_constraints = build_constraints_for_simple_unpack(\n                            template_types, actual_types, neg_op(self.direction)\n                        )\n                        res.extend(unpack_constraints)\n                    else:\n                        # TODO: do we need some special-casing when unpack is present in actual\n                        # callable but not in template callable?\n                        res.extend(\n                            infer_callable_arguments_constraints(template, cactual, self.direction)\n                        )\n            else:\n                prefix = param_spec.prefix\n                prefix_len = len(prefix.arg_types)\n                cactual_ps = cactual.param_spec()\n\n                if type_state.infer_polymorphic and cactual.variables and not self.skip_neg_op:\n                    # Similar logic to the branch above.\n                    res.extend(\n                        infer_constraints(\n                            cactual, template, neg_op(self.direction), skip_neg_op=True\n                        )\n                    )\n                    extra_tvars = True\n\n                # Compare prefixes as well\n                cactual_prefix = cactual.copy_modified(\n                    arg_types=cactual.arg_types[:prefix_len],\n                    arg_kinds=cactual.arg_kinds[:prefix_len],\n                    arg_names=cactual.arg_names[:prefix_len],\n                )\n                res.extend(\n                    infer_callable_arguments_constraints(prefix, cactual_prefix, self.direction)\n                )\n\n                param_spec_target: Type | None = None\n                if not cactual_ps:\n                    max_prefix_len = len([k for k in cactual.arg_kinds if k in (ARG_POS, ARG_OPT)])\n                    prefix_len = min(prefix_len, max_prefix_len)\n                    param_spec_target = Parameters(\n                        arg_types=cactual.arg_types[prefix_len:],\n                        arg_kinds=cactual.arg_kinds[prefix_len:],\n                        arg_names=cactual.arg_names[prefix_len:],\n                        variables=cactual.variables if not type_state.infer_polymorphic else [],\n                        imprecise_arg_kinds=cactual.imprecise_arg_kinds,\n                    )\n                else:\n                    if len(param_spec.prefix.arg_types) <= len(cactual_ps.prefix.arg_types):\n                        param_spec_target = cactual_ps.copy_modified(\n                            prefix=Parameters(\n                                arg_types=cactual_ps.prefix.arg_types[prefix_len:],\n                                arg_kinds=cactual_ps.prefix.arg_kinds[prefix_len:],\n                                arg_names=cactual_ps.prefix.arg_names[prefix_len:],\n                                imprecise_arg_kinds=cactual_ps.prefix.imprecise_arg_kinds,\n                            )\n                        )\n                if param_spec_target is not None:\n                    res.append(Constraint(param_spec, self.direction, param_spec_target))\n            if extra_tvars:\n                for c in res:\n                    c.extra_tvars += cactual.variables\n            return res\n        elif isinstance(self.actual, AnyType):\n            param_spec = template.param_spec()\n            any_type = AnyType(TypeOfAny.from_another_any, source_any=self.actual)\n            if param_spec is None:\n                # FIX what if generic\n                res = self.infer_against_any(template.arg_types, self.actual)\n            else:\n                res = [\n                    Constraint(\n                        param_spec,\n                        SUBTYPE_OF,\n                        Parameters([any_type, any_type], [ARG_STAR, ARG_STAR2], [None, None]),\n                    )\n                ]\n            res.extend(infer_constraints(template.ret_type, any_type, self.direction))\n            return res\n        elif isinstance(self.actual, Overloaded):\n            return self.infer_against_overloaded(self.actual, template)\n        elif isinstance(self.actual, TypeType):\n            return infer_constraints(template.ret_type, self.actual.item, self.direction)\n        elif isinstance(self.actual, Instance):\n            # Instances with __call__ method defined are considered structural\n            # subtypes of Callable with a compatible signature.\n            call = mypy.subtypes.find_member(\n                \"__call__\", self.actual, self.actual, is_operator=True\n            )\n            if call:\n                return infer_constraints(template, call, self.direction)\n            else:\n                return []\n        else:\n            return []\n\n    def infer_against_overloaded(\n        self, overloaded: Overloaded, template: CallableType\n    ) -> list[Constraint]:\n        # Create constraints by matching an overloaded type against a template.\n        # This is tricky to do in general. We cheat by only matching against\n        # the first overload item that is callable compatible. This\n        # seems to work somewhat well, but we should really use a more\n        # reliable technique.\n        item = find_matching_overload_item(overloaded, template)\n        return infer_constraints(template, item, self.direction)\n\n    def visit_tuple_type(self, template: TupleType) -> list[Constraint]:\n        actual = self.actual\n        unpack_index = find_unpack_in_list(template.items)\n        is_varlength_tuple = (\n            isinstance(actual, Instance) and actual.type.fullname == \"builtins.tuple\"\n        )\n\n        if isinstance(actual, TupleType) or is_varlength_tuple:\n            res: list[Constraint] = []\n            if unpack_index is not None:\n                if is_varlength_tuple:\n                    # Variadic tuple can be only a supertype of a tuple type, but even if\n                    # direction is opposite, inferring something may give better error messages.\n                    unpack_type = template.items[unpack_index]\n                    assert isinstance(unpack_type, UnpackType)\n                    unpacked_type = get_proper_type(unpack_type.type)\n                    if isinstance(unpacked_type, TypeVarTupleType):\n                        res = [\n                            Constraint(type_var=unpacked_type, op=self.direction, target=actual)\n                        ]\n                    else:\n                        assert (\n                            isinstance(unpacked_type, Instance)\n                            and unpacked_type.type.fullname == \"builtins.tuple\"\n                        )\n                        res = infer_constraints(unpacked_type, actual, self.direction)\n                    assert isinstance(actual, Instance)  # ensured by is_varlength_tuple == True\n                    for i, ti in enumerate(template.items):\n                        if i == unpack_index:\n                            # This one we just handled above.\n                            continue\n                        # For Tuple[T, *Ts, S] <: tuple[X, ...] infer also T <: X and S <: X.\n                        res.extend(infer_constraints(ti, actual.args[0], self.direction))\n                    return res\n                else:\n                    assert isinstance(actual, TupleType)\n                    unpack_constraints = build_constraints_for_simple_unpack(\n                        template.items, actual.items, self.direction\n                    )\n                    actual_items: tuple[Type, ...] = ()\n                    template_items: tuple[Type, ...] = ()\n                    res.extend(unpack_constraints)\n            elif isinstance(actual, TupleType):\n                a_unpack_index = find_unpack_in_list(actual.items)\n                if a_unpack_index is not None:\n                    # The case where template tuple doesn't have an unpack, but actual tuple\n                    # has an unpack. We can infer something if actual unpack is a variadic tuple.\n                    # Tuple[T, S, U] <: tuple[X, *tuple[Y, ...], Z] => T <: X, S <: Y, U <: Z.\n                    a_unpack = actual.items[a_unpack_index]\n                    assert isinstance(a_unpack, UnpackType)\n                    a_unpacked = get_proper_type(a_unpack.type)\n                    if len(actual.items) + 1 <= len(template.items):\n                        a_prefix_len = a_unpack_index\n                        a_suffix_len = len(actual.items) - a_unpack_index - 1\n                        t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(\n                            tuple(template.items), a_prefix_len, a_suffix_len\n                        )\n                        actual_items = tuple(actual.items[:a_prefix_len])\n                        if a_suffix_len:\n                            actual_items += tuple(actual.items[-a_suffix_len:])\n                        template_items = t_prefix + t_suffix\n                        if isinstance(a_unpacked, Instance):\n                            assert a_unpacked.type.fullname == \"builtins.tuple\"\n                            for tm in t_middle:\n                                res.extend(\n                                    infer_constraints(tm, a_unpacked.args[0], self.direction)\n                                )\n                    else:\n                        actual_items = ()\n                        template_items = ()\n                else:\n                    actual_items = tuple(actual.items)\n                    template_items = tuple(template.items)\n            else:\n                return res\n\n            # Cases above will return if actual wasn't a TupleType.\n            assert isinstance(actual, TupleType)\n            if len(actual_items) == len(template_items):\n                if (\n                    actual.partial_fallback.type.is_named_tuple\n                    and template.partial_fallback.type.is_named_tuple\n                ):\n                    # For named tuples using just the fallbacks usually gives better results.\n                    return res + infer_constraints(\n                        template.partial_fallback, actual.partial_fallback, self.direction\n                    )\n                for i in range(len(template_items)):\n                    res.extend(\n                        infer_constraints(template_items[i], actual_items[i], self.direction)\n                    )\n            res.extend(\n                infer_constraints(\n                    template.partial_fallback, actual.partial_fallback, self.direction\n                )\n            )\n            return res\n        elif isinstance(actual, AnyType):\n            return self.infer_against_any(template.items, actual)\n        else:\n            return []\n\n    def visit_typeddict_type(self, template: TypedDictType) -> list[Constraint]:\n        actual = self.actual\n        if isinstance(actual, TypedDictType):\n            res: list[Constraint] = []\n            # NOTE: Non-matching keys are ignored. Compatibility is checked\n            #       elsewhere so this shouldn't be unsafe.\n            for item_name, template_item_type, actual_item_type in template.zip(actual):\n                res.extend(infer_constraints(template_item_type, actual_item_type, self.direction))\n            return res\n        elif isinstance(actual, AnyType):\n            return self.infer_against_any(template.items.values(), actual)\n        else:\n            return []\n\n    def visit_union_type(self, template: UnionType) -> list[Constraint]:\n        assert False, (\n            \"Unexpected UnionType in ConstraintBuilderVisitor\"\n            \" (should have been handled in infer_constraints)\"\n        )\n\n    def visit_type_alias_type(self, template: TypeAliasType) -> list[Constraint]:\n        assert False, f\"This should be never called, got {template}\"\n\n    def infer_against_any(self, types: Iterable[Type], any_type: AnyType) -> list[Constraint]:\n        res: list[Constraint] = []\n        # Some items may be things like `*Tuple[*Ts, T]` for example from callable types with\n        # suffix after *arg, so flatten them.\n        for t in flatten_nested_tuples(types):\n            if isinstance(t, UnpackType):\n                if isinstance(t.type, TypeVarTupleType):\n                    res.append(Constraint(t.type, self.direction, any_type))\n                else:\n                    unpacked = get_proper_type(t.type)\n                    assert isinstance(unpacked, Instance)\n                    res.extend(infer_constraints(unpacked, any_type, self.direction))\n            else:\n                # Note that we ignore variance and simply always use the\n                # original direction. This is because for Any targets direction is\n                # irrelevant in most cases, see e.g. is_same_constraint().\n                res.extend(infer_constraints(t, any_type, self.direction))\n        return res\n\n    def visit_overloaded(self, template: Overloaded) -> list[Constraint]:\n        if isinstance(self.actual, CallableType):\n            items = find_matching_overload_items(template, self.actual)\n        else:\n            items = template.items\n        res: list[Constraint] = []\n        for t in items:\n            res.extend(infer_constraints(t, self.actual, self.direction))\n        return res\n\n    def visit_type_type(self, template: TypeType) -> list[Constraint]:\n        if isinstance(self.actual, CallableType):\n            return infer_constraints(template.item, self.actual.ret_type, self.direction)\n        elif isinstance(self.actual, Overloaded):\n            return infer_constraints(template.item, self.actual.items[0].ret_type, self.direction)\n        elif isinstance(self.actual, TypeType):\n            return infer_constraints(template.item, self.actual.item, self.direction)\n        elif isinstance(self.actual, AnyType):\n            return infer_constraints(template.item, self.actual, self.direction)\n        else:\n            return []\n\n\ndef neg_op(op: int) -> int:\n    \"\"\"Map SubtypeOf to SupertypeOf and vice versa.\"\"\"\n\n    if op == SUBTYPE_OF:\n        return SUPERTYPE_OF\n    elif op == SUPERTYPE_OF:\n        return SUBTYPE_OF\n    else:\n        raise ValueError(f\"Invalid operator {op}\")\n\n\ndef find_matching_overload_item(overloaded: Overloaded, template: CallableType) -> CallableType:\n    \"\"\"Disambiguate overload item against a template.\"\"\"\n    items = overloaded.items\n    for item in items:\n        # Return type may be indeterminate in the template, so ignore it when performing a\n        # subtype check.\n        if mypy.subtypes.is_callable_compatible(\n            item,\n            template,\n            is_compat=mypy.subtypes.is_subtype,\n            is_proper_subtype=False,\n            ignore_return=True,\n        ):\n            return item\n    # Fall back to the first item if we can't find a match. This is totally arbitrary --\n    # maybe we should just bail out at this point.\n    return items[0]\n\n\ndef find_matching_overload_items(\n    overloaded: Overloaded, template: CallableType\n) -> list[CallableType]:\n    \"\"\"Like find_matching_overload_item, but return all matches, not just the first.\"\"\"\n    items = overloaded.items\n    res = []\n    for item in items:\n        # Return type may be indeterminate in the template, so ignore it when performing a\n        # subtype check.\n        if mypy.subtypes.is_callable_compatible(\n            item,\n            template,\n            is_compat=mypy.subtypes.is_subtype,\n            is_proper_subtype=False,\n            ignore_return=True,\n        ):\n            res.append(item)\n    if not res:\n        # Falling back to all items if we can't find a match is pretty arbitrary, but\n        # it maintains backward compatibility.\n        res = items.copy()\n    return res\n\n\ndef get_tuple_fallback_from_unpack(unpack: UnpackType) -> TypeInfo:\n    \"\"\"Get builtins.tuple type from available types to construct homogeneous tuples.\"\"\"\n    tp = get_proper_type(unpack.type)\n    if isinstance(tp, Instance) and tp.type.fullname == \"builtins.tuple\":\n        return tp.type\n    if isinstance(tp, TypeVarTupleType):\n        return tp.tuple_fallback.type\n    if isinstance(tp, TupleType):\n        for base in tp.partial_fallback.type.mro:\n            if base.fullname == \"builtins.tuple\":\n                return base\n    assert False, \"Invalid unpack type\"\n\n\ndef repack_callable_args(callable: CallableType, tuple_type: TypeInfo) -> list[Type]:\n    \"\"\"Present callable with star unpack in a normalized form.\n\n    Since positional arguments cannot follow star argument, they are packed in a suffix,\n    while prefix is represented as individual positional args. We want to put all in a single\n    list with unpack in the middle, and prefix/suffix on the sides (as they would appear\n    in e.g. a TupleType).\n    \"\"\"\n    if ARG_STAR not in callable.arg_kinds:\n        return callable.arg_types\n    star_index = callable.arg_kinds.index(ARG_STAR)\n    arg_types = callable.arg_types[:star_index]\n    star_type = callable.arg_types[star_index]\n    suffix_types = []\n    if not isinstance(star_type, UnpackType):\n        # Re-normalize *args: X -> *args: *tuple[X, ...]\n        star_type = UnpackType(Instance(tuple_type, [star_type]))\n    else:\n        tp = get_proper_type(star_type.type)\n        if isinstance(tp, TupleType):\n            assert isinstance(tp.items[0], UnpackType)\n            star_type = tp.items[0]\n            suffix_types = tp.items[1:]\n    return arg_types + [star_type] + suffix_types\n\n\ndef build_constraints_for_simple_unpack(\n    template_args: list[Type], actual_args: list[Type], direction: int\n) -> list[Constraint]:\n    \"\"\"Infer constraints between two lists of types with variadic items.\n\n    This function is only supposed to be called when a variadic item is present in templates.\n    If there is no variadic item the actuals, we simply use split_with_prefix_and_suffix()\n    and infer prefix <: prefix, suffix <: suffix, variadic <: middle. If there is a variadic\n    item in the actuals we need to be more careful, only common prefix/suffix can generate\n    constraints, also we can only infer constraints for variadic template item, if template\n    prefix/suffix are shorter that actual ones, otherwise there may be partial overlap\n    between variadic items, for example if template prefix is longer:\n\n        templates: T1, T2, Ts, Ts, Ts, ...\n        actuals:   A1, As, As, As, ...\n\n    Note: this function can only be called for builtin variadic constructors: Tuple and Callable.\n    For instances, you should first find correct type argument mapping.\n    \"\"\"\n    template_unpack = find_unpack_in_list(template_args)\n    assert template_unpack is not None\n    template_prefix = template_unpack\n    template_suffix = len(template_args) - template_prefix - 1\n\n    t_unpack = None\n    res = []\n\n    actual_unpack = find_unpack_in_list(actual_args)\n    if actual_unpack is None:\n        t_unpack = template_args[template_unpack]\n        if template_prefix + template_suffix > len(actual_args):\n            # These can't be subtypes of each-other, return fast.\n            assert isinstance(t_unpack, UnpackType)\n            if isinstance(t_unpack.type, TypeVarTupleType):\n                # Set TypeVarTuple to empty to improve error messages.\n                return [\n                    Constraint(\n                        t_unpack.type, direction, TupleType([], t_unpack.type.tuple_fallback)\n                    )\n                ]\n            else:\n                return []\n        common_prefix = template_prefix\n        common_suffix = template_suffix\n    else:\n        actual_prefix = actual_unpack\n        actual_suffix = len(actual_args) - actual_prefix - 1\n        common_prefix = min(template_prefix, actual_prefix)\n        common_suffix = min(template_suffix, actual_suffix)\n        if actual_prefix >= template_prefix and actual_suffix >= template_suffix:\n            # This is the only case where we can guarantee there will be no partial overlap\n            # (note however partial overlap is OK for variadic tuples, it is handled below).\n            t_unpack = template_args[template_unpack]\n\n    # Handle constraints from prefixes/suffixes first.\n    start, middle, end = split_with_prefix_and_suffix(\n        tuple(actual_args), common_prefix, common_suffix\n    )\n    for t, a in zip(template_args[:common_prefix], start):\n        res.extend(infer_constraints(t, a, direction))\n    if common_suffix:\n        for t, a in zip(template_args[-common_suffix:], end):\n            res.extend(infer_constraints(t, a, direction))\n\n    if t_unpack is not None:\n        # Add constraint(s) for variadic item when possible.\n        assert isinstance(t_unpack, UnpackType)\n        tp = get_proper_type(t_unpack.type)\n        if isinstance(tp, Instance) and tp.type.fullname == \"builtins.tuple\":\n            # Homogeneous case *tuple[T, ...] <: [X, Y, Z, ...].\n            for a in middle:\n                # TODO: should we use union instead of join here?\n                if not isinstance(a, UnpackType):\n                    res.extend(infer_constraints(tp.args[0], a, direction))\n                else:\n                    a_tp = get_proper_type(a.type)\n                    # This is the case *tuple[T, ...] <: *tuple[A, ...].\n                    if isinstance(a_tp, Instance) and a_tp.type.fullname == \"builtins.tuple\":\n                        res.extend(infer_constraints(tp.args[0], a_tp.args[0], direction))\n        elif isinstance(tp, TypeVarTupleType):\n            res.append(Constraint(tp, direction, TupleType(list(middle), tp.tuple_fallback)))\n    elif actual_unpack is not None:\n        # A special case for a variadic tuple unpack, we simply infer T <: X from\n        # Tuple[..., *tuple[T, ...], ...] <: Tuple[..., *tuple[X, ...], ...].\n        actual_unpack_type = actual_args[actual_unpack]\n        assert isinstance(actual_unpack_type, UnpackType)\n        a_unpacked = get_proper_type(actual_unpack_type.type)\n        if isinstance(a_unpacked, Instance) and a_unpacked.type.fullname == \"builtins.tuple\":\n            t_unpack = template_args[template_unpack]\n            assert isinstance(t_unpack, UnpackType)\n            tp = get_proper_type(t_unpack.type)\n            if isinstance(tp, Instance) and tp.type.fullname == \"builtins.tuple\":\n                res.extend(infer_constraints(tp.args[0], a_unpacked.args[0], direction))\n    return res\n\n\ndef infer_directed_arg_constraints(left: Type, right: Type, direction: int) -> list[Constraint]:\n    \"\"\"Infer constraints between two arguments using direction between original callables.\"\"\"\n    if isinstance(left, (ParamSpecType, UnpackType)) or isinstance(\n        right, (ParamSpecType, UnpackType)\n    ):\n        # This avoids bogus constraints like T <: P.args\n        # TODO: can we infer something useful for *T vs P?\n        return []\n    if direction == SUBTYPE_OF:\n        # We invert direction to account for argument contravariance.\n        return infer_constraints(left, right, neg_op(direction))\n    else:\n        return infer_constraints(right, left, neg_op(direction))\n\n\ndef infer_callable_arguments_constraints(\n    template: NormalizedCallableType | Parameters,\n    actual: NormalizedCallableType | Parameters,\n    direction: int,\n) -> list[Constraint]:\n    \"\"\"Infer constraints between argument types of two callables.\n\n    This function essentially extracts four steps from are_parameters_compatible() in\n    subtypes.py that involve subtype checks between argument types. We keep the argument\n    matching logic, but ignore various strictness flags present there, and checks that\n    do not involve subtyping. Then in place of every subtype check we put an infer_constraints()\n    call for the same types.\n    \"\"\"\n    res = []\n    if direction == SUBTYPE_OF:\n        left, right = template, actual\n    else:\n        left, right = actual, template\n    left_star = left.var_arg()\n    left_star2 = left.kw_arg()\n    right_star = right.var_arg()\n    right_star2 = right.kw_arg()\n\n    # Numbering of steps below matches the one in are_parameters_compatible() for convenience.\n    # Phase 1a: compare star vs star arguments.\n    if left_star is not None and right_star is not None:\n        res.extend(infer_directed_arg_constraints(left_star.typ, right_star.typ, direction))\n    if left_star2 is not None and right_star2 is not None:\n        res.extend(infer_directed_arg_constraints(left_star2.typ, right_star2.typ, direction))\n\n    # Phase 1b: compare left args with corresponding non-star right arguments.\n    for right_arg in right.formal_arguments():\n        left_arg = mypy.typeops.callable_corresponding_argument(left, right_arg)\n        if left_arg is None:\n            continue\n        res.extend(infer_directed_arg_constraints(left_arg.typ, right_arg.typ, direction))\n\n    # Phase 1c: compare left args with right *args.\n    if right_star is not None:\n        right_by_position = right.try_synthesizing_arg_from_vararg(None)\n        assert right_by_position is not None\n        i = right_star.pos\n        assert i is not None\n        while i < len(left.arg_kinds) and left.arg_kinds[i].is_positional():\n            left_by_position = left.argument_by_position(i)\n            assert left_by_position is not None\n            res.extend(\n                infer_directed_arg_constraints(\n                    left_by_position.typ, right_by_position.typ, direction\n                )\n            )\n            i += 1\n\n    # Phase 1d: compare left args with right **kwargs.\n    if right_star2 is not None:\n        right_names = {name for name in right.arg_names if name is not None}\n        left_only_names = set()\n        for name, kind in zip(left.arg_names, left.arg_kinds):\n            if name is None or kind.is_star() or name in right_names:\n                continue\n            left_only_names.add(name)\n\n        right_by_name = right.try_synthesizing_arg_from_kwarg(None)\n        assert right_by_name is not None\n        for name in left_only_names:\n            left_by_name = left.argument_by_name(name)\n            assert left_by_name is not None\n            res.extend(\n                infer_directed_arg_constraints(left_by_name.typ, right_by_name.typ, direction)\n            )\n    return res\n\n\ndef filter_imprecise_kinds(cs: list[Constraint]) -> list[Constraint]:\n    \"\"\"For each ParamSpec remove all imprecise constraints, if at least one precise available.\"\"\"\n    have_precise = set()\n    for c in cs:\n        if not isinstance(c.origin_type_var, ParamSpecType):\n            continue\n        if (\n            isinstance(c.target, ParamSpecType)\n            or isinstance(c.target, Parameters)\n            and not c.target.imprecise_arg_kinds\n        ):\n            have_precise.add(c.type_var)\n    new_cs = []\n    for c in cs:\n        if not isinstance(c.origin_type_var, ParamSpecType) or c.type_var not in have_precise:\n            new_cs.append(c)\n        if not isinstance(c.target, Parameters) or not c.target.imprecise_arg_kinds:\n            new_cs.append(c)\n    return new_cs\n"
  },
  {
    "path": "mypy/copytype.py",
    "content": "from __future__ import annotations\n\nfrom typing import Any, cast\n\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    TypeAliasType,\n    TypedDictType,\n    TypeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n)\n\n# type_visitor needs to be imported after types\nfrom mypy.type_visitor import TypeVisitor  # ruff: isort: skip\n\n\ndef copy_type(t: ProperType) -> ProperType:\n    \"\"\"Create a shallow copy of a type.\n\n    This can be used to mutate the copy with truthiness information.\n\n    Classes compiled with mypyc don't support copy.copy(), so we need\n    a custom implementation.\n    \"\"\"\n    return t.accept(TypeShallowCopier())\n\n\nclass TypeShallowCopier(TypeVisitor[ProperType]):\n    def visit_unbound_type(self, t: UnboundType) -> ProperType:\n        return t\n\n    def visit_any(self, t: AnyType) -> ProperType:\n        return self.copy_common(t, AnyType(t.type_of_any, t.source_any, t.missing_import_name))\n\n    def visit_none_type(self, t: NoneType) -> ProperType:\n        return self.copy_common(t, NoneType())\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:\n        dup = UninhabitedType()\n        dup.ambiguous = t.ambiguous\n        return self.copy_common(t, dup)\n\n    def visit_erased_type(self, t: ErasedType) -> ProperType:\n        return self.copy_common(t, ErasedType())\n\n    def visit_deleted_type(self, t: DeletedType) -> ProperType:\n        return self.copy_common(t, DeletedType(t.source))\n\n    def visit_instance(self, t: Instance) -> ProperType:\n        dup = Instance(t.type, t.args, last_known_value=t.last_known_value)\n        return self.copy_common(t, dup)\n\n    def visit_type_var(self, t: TypeVarType) -> ProperType:\n        return self.copy_common(t, t.copy_modified())\n\n    def visit_param_spec(self, t: ParamSpecType) -> ProperType:\n        dup = ParamSpecType(\n            t.name, t.fullname, t.id, t.flavor, t.upper_bound, t.default, prefix=t.prefix\n        )\n        return self.copy_common(t, dup)\n\n    def visit_parameters(self, t: Parameters) -> ProperType:\n        dup = Parameters(\n            t.arg_types,\n            t.arg_kinds,\n            t.arg_names,\n            variables=t.variables,\n            is_ellipsis_args=t.is_ellipsis_args,\n        )\n        return self.copy_common(t, dup)\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType:\n        dup = TypeVarTupleType(\n            t.name, t.fullname, t.id, t.upper_bound, t.tuple_fallback, t.default\n        )\n        return self.copy_common(t, dup)\n\n    def visit_unpack_type(self, t: UnpackType) -> ProperType:\n        dup = UnpackType(t.type)\n        return self.copy_common(t, dup)\n\n    def visit_partial_type(self, t: PartialType) -> ProperType:\n        return self.copy_common(t, PartialType(t.type, t.var, t.value_type))\n\n    def visit_callable_type(self, t: CallableType) -> ProperType:\n        return self.copy_common(t, t.copy_modified())\n\n    def visit_tuple_type(self, t: TupleType) -> ProperType:\n        return self.copy_common(t, TupleType(t.items, t.partial_fallback, implicit=t.implicit))\n\n    def visit_typeddict_type(self, t: TypedDictType) -> ProperType:\n        return self.copy_common(\n            t, TypedDictType(t.items, t.required_keys, t.readonly_keys, t.fallback)\n        )\n\n    def visit_literal_type(self, t: LiteralType) -> ProperType:\n        return self.copy_common(t, LiteralType(value=t.value, fallback=t.fallback))\n\n    def visit_union_type(self, t: UnionType) -> ProperType:\n        return self.copy_common(t, UnionType(t.items))\n\n    def visit_overloaded(self, t: Overloaded) -> ProperType:\n        return self.copy_common(t, Overloaded(items=t.items))\n\n    def visit_type_type(self, t: TypeType) -> ProperType:\n        # Use cast since the type annotations in TypeType are imprecise.\n        return self.copy_common(t, TypeType(cast(Any, t.item), is_type_form=t.is_type_form))\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> ProperType:\n        assert False, \"only ProperTypes supported\"\n\n    def copy_common(self, t: ProperType, t2: ProperType) -> ProperType:\n        t2.line = t.line\n        t2.column = t.column\n        t2.can_be_false = t.can_be_false\n        t2.can_be_true = t.can_be_true\n        return t2\n"
  },
  {
    "path": "mypy/defaults.py",
    "content": "from __future__ import annotations\n\nimport os\nfrom typing import Final\n\n# Earliest fully supported Python 3.x version. Used as the default Python\n# version in tests. Mypy wheels should be built starting with this version,\n# and CI tests should be run on this version (and later versions).\nPYTHON3_VERSION: Final = (3, 10)\n\n# Earliest Python 3.x version supported via --python-version 3.x. To run\n# mypy, at least version PYTHON3_VERSION is needed.\nPYTHON3_VERSION_MIN: Final = (3, 9)  # Keep in sync with typeshed's python support\n\nCACHE_DIR: Final = \".mypy_cache\"\n\nCONFIG_NAMES: Final = [\"mypy.ini\", \".mypy.ini\"]\nSHARED_CONFIG_NAMES: Final = [\"pyproject.toml\", \"setup.cfg\"]\n\nUSER_CONFIG_FILES: list[str] = [\"~/.config/mypy/config\", \"~/.mypy.ini\"]\nif os.environ.get(\"XDG_CONFIG_HOME\"):\n    USER_CONFIG_FILES.insert(0, os.path.join(os.environ[\"XDG_CONFIG_HOME\"], \"mypy/config\"))\nUSER_CONFIG_FILES = [os.path.expanduser(f) for f in USER_CONFIG_FILES]\n\n# This must include all reporters defined in mypy.report. This is defined here\n# to make reporter names available without importing mypy.report -- this speeds\n# up startup.\nREPORTER_NAMES: Final = [\n    \"linecount\",\n    \"any-exprs\",\n    \"linecoverage\",\n    \"memory-xml\",\n    \"cobertura-xml\",\n    \"xml\",\n    \"xslt-html\",\n    \"xslt-txt\",\n    \"html\",\n    \"txt\",\n    \"lineprecision\",\n]\n\n# Threshold after which we sometimes filter out most errors to avoid very\n# verbose output. The default is to show all errors.\nMANY_ERRORS_THRESHOLD: Final = -1\n\nRECURSION_LIMIT: Final = 2**14\n\nWORKER_START_INTERVAL: Final = 0.01\nWORKER_START_TIMEOUT: Final = 3\nWORKER_CONNECTION_TIMEOUT: Final = 10\nWORKER_DONE_TIMEOUT: Final = 600\n"
  },
  {
    "path": "mypy/dmypy/__init__.py",
    "content": ""
  },
  {
    "path": "mypy/dmypy/__main__.py",
    "content": "from __future__ import annotations\n\nfrom mypy.dmypy.client import console_entry\n\nif __name__ == \"__main__\":\n    console_entry()\n"
  },
  {
    "path": "mypy/dmypy/client.py",
    "content": "\"\"\"Client for mypy daemon mode.\n\nThis manages a daemon process which keeps useful state in memory\nrather than having to read it back from disk on each run.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport json\nimport os\nimport pickle\nimport sys\nimport time\nimport traceback\nfrom collections.abc import Callable, Mapping\nfrom typing import Any, NoReturn\n\nfrom librt.base64 import b64decode\n\nfrom mypy.defaults import RECURSION_LIMIT\nfrom mypy.dmypy_os import alive, kill\nfrom mypy.dmypy_util import DEFAULT_STATUS_FILE, receive, send\nfrom mypy.ipc import BadStatus, IPCClient, IPCException, read_status\nfrom mypy.util import check_python_version, get_terminal_width, should_force_color\nfrom mypy.version import __version__\n\n# Argument parser.  Subparsers are tied to action functions by the\n# @action(subparse) decorator.\n\n\nclass AugmentedHelpFormatter(argparse.RawDescriptionHelpFormatter):\n    def __init__(self, prog: str, **kwargs: Any) -> None:\n        super().__init__(prog=prog, max_help_position=30, **kwargs)\n\n\nparser = argparse.ArgumentParser(\n    prog=\"dmypy\", description=\"Client for mypy daemon mode\", fromfile_prefix_chars=\"@\"\n)\nparser.set_defaults(action=None)\nparser.add_argument(\n    \"--status-file\", default=DEFAULT_STATUS_FILE, help=\"status file to retrieve daemon details\"\n)\nparser.add_argument(\n    \"-V\",\n    \"--version\",\n    action=\"version\",\n    version=\"%(prog)s \" + __version__,\n    help=\"Show program's version number and exit\",\n)\nsubparsers = parser.add_subparsers()\n\nstart_parser = p = subparsers.add_parser(\"start\", help=\"Start daemon\")\np.add_argument(\"--log-file\", metavar=\"FILE\", type=str, help=\"Direct daemon stdout/stderr to FILE\")\np.add_argument(\n    \"--timeout\", metavar=\"TIMEOUT\", type=int, help=\"Server shutdown timeout (in seconds)\"\n)\np.add_argument(\n    \"flags\", metavar=\"FLAG\", nargs=\"*\", type=str, help=\"Regular mypy flags (precede with --)\"\n)\n\nrestart_parser = p = subparsers.add_parser(\n    \"restart\", help=\"Restart daemon (stop or kill followed by start)\"\n)\np.add_argument(\"--log-file\", metavar=\"FILE\", type=str, help=\"Direct daemon stdout/stderr to FILE\")\np.add_argument(\n    \"--timeout\", metavar=\"TIMEOUT\", type=int, help=\"Server shutdown timeout (in seconds)\"\n)\np.add_argument(\n    \"flags\", metavar=\"FLAG\", nargs=\"*\", type=str, help=\"Regular mypy flags (precede with --)\"\n)\n\nstatus_parser = p = subparsers.add_parser(\"status\", help=\"Show daemon status\")\np.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Print detailed status\")\np.add_argument(\"--fswatcher-dump-file\", help=\"Collect information about the current file state\")\n\nstop_parser = p = subparsers.add_parser(\"stop\", help=\"Stop daemon (asks it politely to go away)\")\n\nkill_parser = p = subparsers.add_parser(\"kill\", help=\"Kill daemon (kills the process)\")\n\ncheck_parser = p = subparsers.add_parser(\n    \"check\", formatter_class=AugmentedHelpFormatter, help=\"Check some files (requires daemon)\"\n)\np.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Print detailed status\")\np.add_argument(\"-q\", \"--quiet\", action=\"store_true\", help=argparse.SUPPRESS)  # Deprecated\np.add_argument(\"--junit-xml\", help=\"Write junit.xml to the given file\")\np.add_argument(\"--perf-stats-file\", help=\"write performance information to the given file\")\np.add_argument(\"files\", metavar=\"FILE\", nargs=\"+\", help=\"File (or directory) to check\")\np.add_argument(\n    \"--export-types\",\n    action=\"store_true\",\n    help=\"Store types of all expressions in a shared location (useful for inspections)\",\n)\n\nrun_parser = p = subparsers.add_parser(\n    \"run\",\n    formatter_class=AugmentedHelpFormatter,\n    help=\"Check some files, [re]starting daemon if necessary\",\n)\np.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Print detailed status\")\np.add_argument(\"--junit-xml\", help=\"Write junit.xml to the given file\")\np.add_argument(\"--perf-stats-file\", help=\"write performance information to the given file\")\np.add_argument(\n    \"--timeout\", metavar=\"TIMEOUT\", type=int, help=\"Server shutdown timeout (in seconds)\"\n)\np.add_argument(\"--log-file\", metavar=\"FILE\", type=str, help=\"Direct daemon stdout/stderr to FILE\")\np.add_argument(\n    \"--export-types\",\n    action=\"store_true\",\n    help=\"Store types of all expressions in a shared location (useful for inspections)\",\n)\np.add_argument(\n    \"flags\",\n    metavar=\"ARG\",\n    nargs=\"*\",\n    type=str,\n    help=\"Regular mypy flags and files (precede with --)\",\n)\n\nrecheck_parser = p = subparsers.add_parser(\n    \"recheck\",\n    formatter_class=AugmentedHelpFormatter,\n    help=\"Re-check the previous list of files, with optional modifications (requires daemon)\",\n)\np.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"Print detailed status\")\np.add_argument(\"-q\", \"--quiet\", action=\"store_true\", help=argparse.SUPPRESS)  # Deprecated\np.add_argument(\"--junit-xml\", help=\"Write junit.xml to the given file\")\np.add_argument(\"--perf-stats-file\", help=\"write performance information to the given file\")\np.add_argument(\n    \"--export-types\",\n    action=\"store_true\",\n    help=\"Store types of all expressions in a shared location (useful for inspections)\",\n)\np.add_argument(\n    \"--update\",\n    metavar=\"FILE\",\n    nargs=\"*\",\n    help=\"Files in the run to add or check again (default: all from previous run)\",\n)\np.add_argument(\"--remove\", metavar=\"FILE\", nargs=\"*\", help=\"Files to remove from the run\")\n\nsuggest_parser = p = subparsers.add_parser(\n    \"suggest\", help=\"Suggest a signature or show call sites for a specific function\"\n)\np.add_argument(\n    \"function\",\n    metavar=\"FUNCTION\",\n    type=str,\n    help=\"Function specified as '[package.]module.[class.]function'\",\n)\np.add_argument(\n    \"--json\",\n    action=\"store_true\",\n    help=\"Produce json that pyannotate can use to apply a suggestion\",\n)\np.add_argument(\n    \"--no-errors\", action=\"store_true\", help=\"Only produce suggestions that cause no errors\"\n)\np.add_argument(\n    \"--no-any\", action=\"store_true\", help=\"Only produce suggestions that don't contain Any\"\n)\np.add_argument(\n    \"--flex-any\",\n    type=float,\n    help=\"Allow anys in types if they go above a certain score (scores are from 0-1)\",\n)\np.add_argument(\n    \"--callsites\", action=\"store_true\", help=\"Find callsites instead of suggesting a type\"\n)\np.add_argument(\n    \"--use-fixme\",\n    metavar=\"NAME\",\n    type=str,\n    help=\"A dummy name to use instead of Any for types that can't be inferred\",\n)\np.add_argument(\n    \"--max-guesses\",\n    type=int,\n    help=\"Set the maximum number of types to try for a function (default 64)\",\n)\n\ninspect_parser = p = subparsers.add_parser(\n    \"inspect\", help=\"Locate and statically inspect expression(s)\"\n)\np.add_argument(\n    \"location\",\n    metavar=\"LOCATION\",\n    type=str,\n    help=\"Location specified as path/to/file.py:line:column[:end_line:end_column].\"\n    \" If position is given (i.e. only line and column), this will return all\"\n    \" enclosing expressions\",\n)\np.add_argument(\n    \"--show\",\n    metavar=\"INSPECTION\",\n    type=str,\n    default=\"type\",\n    choices=[\"type\", \"attrs\", \"definition\"],\n    help=\"What kind of inspection to run\",\n)\np.add_argument(\n    \"--verbose\",\n    \"-v\",\n    action=\"count\",\n    default=0,\n    help=\"Increase verbosity of the type string representation (can be repeated)\",\n)\np.add_argument(\n    \"--limit\",\n    metavar=\"NUM\",\n    type=int,\n    default=0,\n    help=\"Return at most NUM innermost expressions (if position is given); 0 means no limit\",\n)\np.add_argument(\n    \"--include-span\",\n    action=\"store_true\",\n    help=\"Prepend each inspection result with the span of corresponding expression\"\n    ' (e.g. 1:2:3:4:\"int\")',\n)\np.add_argument(\n    \"--include-kind\",\n    action=\"store_true\",\n    help=\"Prepend each inspection result with the kind of corresponding expression\"\n    ' (e.g. NameExpr:\"int\")',\n)\np.add_argument(\n    \"--include-object-attrs\",\n    action=\"store_true\",\n    help='Include attributes of \"object\" in \"attrs\" inspection',\n)\np.add_argument(\n    \"--union-attrs\",\n    action=\"store_true\",\n    help=\"Include attributes valid for some of possible expression types\"\n    \" (by default an intersection is returned)\",\n)\np.add_argument(\n    \"--force-reload\",\n    action=\"store_true\",\n    help=\"Re-parse and re-type-check file before inspection (may be slow)\",\n)\n\nhang_parser = p = subparsers.add_parser(\"hang\", help=\"Hang for 100 seconds\")\n\ndaemon_parser = p = subparsers.add_parser(\"daemon\", help=\"Run daemon in foreground\")\np.add_argument(\n    \"--timeout\", metavar=\"TIMEOUT\", type=int, help=\"Server shutdown timeout (in seconds)\"\n)\np.add_argument(\"--log-file\", metavar=\"FILE\", type=str, help=\"Direct daemon stdout/stderr to FILE\")\np.add_argument(\n    \"flags\", metavar=\"FLAG\", nargs=\"*\", type=str, help=\"Regular mypy flags (precede with --)\"\n)\np.add_argument(\"--options-data\", help=argparse.SUPPRESS)\nhelp_parser = p = subparsers.add_parser(\"help\")\n\ndel p\n\n\ndef main(argv: list[str]) -> None:\n    \"\"\"The code is top-down.\"\"\"\n    check_python_version(\"dmypy\")\n\n    # set recursion limit consistent with mypy/main.py\n    sys.setrecursionlimit(RECURSION_LIMIT)\n\n    args = parser.parse_args(argv)\n    if not args.action:\n        parser.print_usage()\n    else:\n        try:\n            args.action(args)\n        except BadStatus as err:\n            fail(err.args[0])\n        except Exception:\n            # We do this explicitly to avoid exceptions percolating up\n            # through mypy.api invocations\n            traceback.print_exc()\n            sys.exit(2)\n\n\ndef fail(msg: str) -> NoReturn:\n    print(msg, file=sys.stderr)\n    sys.exit(2)\n\n\nActionFunction = Callable[[argparse.Namespace], None]\n\n\ndef action(subparser: argparse.ArgumentParser) -> Callable[[ActionFunction], ActionFunction]:\n    \"\"\"Decorator to tie an action function to a subparser.\"\"\"\n\n    def register(func: ActionFunction) -> ActionFunction:\n        subparser.set_defaults(action=func)\n        return func\n\n    return register\n\n\n# Action functions (run in client from command line).\n\n\n@action(start_parser)\ndef do_start(args: argparse.Namespace) -> None:\n    \"\"\"Start daemon (it must not already be running).\n\n    This is where mypy flags are set from the command line.\n\n    Setting flags is a bit awkward; you have to use e.g.:\n\n      dmypy start -- --strict\n\n    since we don't want to duplicate mypy's huge list of flags.\n    \"\"\"\n    try:\n        get_status(args.status_file)\n    except BadStatus:\n        # Bad or missing status file or dead process; good to start.\n        pass\n    else:\n        fail(\"Daemon is still alive\")\n    start_server(args)\n\n\n@action(restart_parser)\ndef do_restart(args: argparse.Namespace) -> None:\n    \"\"\"Restart daemon (it may or may not be running; but not hanging).\n\n    We first try to stop it politely if it's running.  This also sets\n    mypy flags from the command line (see do_start()).\n    \"\"\"\n    restart_server(args)\n\n\ndef restart_server(args: argparse.Namespace, allow_sources: bool = False) -> None:\n    \"\"\"Restart daemon (it may or may not be running; but not hanging).\"\"\"\n    try:\n        do_stop(args)\n    except BadStatus:\n        # Bad or missing status file or dead process; good to start.\n        pass\n    start_server(args, allow_sources)\n\n\ndef start_server(args: argparse.Namespace, allow_sources: bool = False) -> None:\n    \"\"\"Start the server from command arguments and wait for it.\"\"\"\n    # Lazy import so this import doesn't slow down other commands.\n    from mypy.dmypy_server import daemonize, process_start_options\n\n    start_options = process_start_options(args.flags, allow_sources)\n    if daemonize(start_options, args.status_file, timeout=args.timeout, log_file=args.log_file):\n        sys.exit(2)\n    wait_for_server(args.status_file)\n\n\ndef wait_for_server(status_file: str, timeout: float = 5.0) -> None:\n    \"\"\"Wait until the server is up.\n\n    Exit if it doesn't happen within the timeout.\n    \"\"\"\n    endtime = time.time() + timeout\n    while time.time() < endtime:\n        try:\n            data = read_status(status_file)\n        except BadStatus:\n            # If the file isn't there yet, retry later.\n            time.sleep(0.1)\n            continue\n        # If the file's content is bogus or the process is dead, fail.\n        check_status(data)\n        print(\"Daemon started\")\n        return\n    fail(\"Timed out waiting for daemon to start\")\n\n\n@action(run_parser)\ndef do_run(args: argparse.Namespace) -> None:\n    \"\"\"Do a check, starting (or restarting) the daemon as necessary\n\n    Restarts the daemon if the running daemon reports that it is\n    required (due to a configuration change, for example).\n\n    Setting flags is a bit awkward; you have to use e.g.:\n\n      dmypy run -- --strict a.py b.py ...\n\n    since we don't want to duplicate mypy's huge list of flags.\n    (The -- is only necessary if flags are specified.)\n    \"\"\"\n    if not is_running(args.status_file):\n        # Bad or missing status file or dead process; good to start.\n        start_server(args, allow_sources=True)\n    t0 = time.time()\n    response = request(\n        args.status_file,\n        \"run\",\n        version=__version__,\n        args=args.flags,\n        export_types=args.export_types,\n    )\n    # If the daemon signals that a restart is necessary, do it\n    if \"restart\" in response:\n        print(f\"Restarting: {response['restart']}\")\n        restart_server(args, allow_sources=True)\n        response = request(\n            args.status_file,\n            \"run\",\n            version=__version__,\n            args=args.flags,\n            export_types=args.export_types,\n        )\n\n    t1 = time.time()\n    response[\"roundtrip_time\"] = t1 - t0\n    check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\n\n\n@action(status_parser)\ndef do_status(args: argparse.Namespace) -> None:\n    \"\"\"Print daemon status.\n\n    This verifies that it is responsive to requests.\n    \"\"\"\n    status = read_status(args.status_file)\n    if args.verbose:\n        show_stats(status)\n    # Both check_status() and request() may raise BadStatus,\n    # which will be handled by main().\n    check_status(status)\n    response = request(\n        args.status_file, \"status\", fswatcher_dump_file=args.fswatcher_dump_file, timeout=5\n    )\n    if args.verbose or \"error\" in response:\n        show_stats(response)\n    if \"error\" in response:\n        fail(f\"Daemon may be busy processing; if this persists, consider {sys.argv[0]} kill\")\n    print(\"Daemon is up and running\")\n\n\n@action(stop_parser)\ndef do_stop(args: argparse.Namespace) -> None:\n    \"\"\"Stop daemon via a 'stop' request.\"\"\"\n    # May raise BadStatus, which will be handled by main().\n    response = request(args.status_file, \"stop\", timeout=5)\n    if \"error\" in response:\n        show_stats(response)\n        fail(f\"Daemon may be busy processing; if this persists, consider {sys.argv[0]} kill\")\n    else:\n        print(\"Daemon stopped\")\n\n\n@action(kill_parser)\ndef do_kill(args: argparse.Namespace) -> None:\n    \"\"\"Kill daemon process with SIGKILL.\"\"\"\n    pid, _ = get_status(args.status_file)\n    try:\n        kill(pid)\n    except OSError as err:\n        fail(str(err))\n    else:\n        print(\"Daemon killed\")\n\n\n@action(check_parser)\ndef do_check(args: argparse.Namespace) -> None:\n    \"\"\"Ask the daemon to check a list of files.\"\"\"\n    t0 = time.time()\n    response = request(args.status_file, \"check\", files=args.files, export_types=args.export_types)\n    t1 = time.time()\n    response[\"roundtrip_time\"] = t1 - t0\n    check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\n\n\n@action(recheck_parser)\ndef do_recheck(args: argparse.Namespace) -> None:\n    \"\"\"Ask the daemon to recheck the previous list of files, with optional modifications.\n\n    If at least one of --remove or --update is given, the server will\n    update the list of files to check accordingly and assume that any other files\n    are unchanged.  If none of these flags are given, the server will call stat()\n    on each file last checked to determine its status.\n\n    Files given in --update ought to exist.  Files given in --remove need not exist;\n    if they don't they will be ignored.\n    The lists may be empty but oughtn't contain duplicates or overlap.\n\n    NOTE: The list of files is lost when the daemon is restarted.\n    \"\"\"\n    t0 = time.time()\n    if args.remove is not None or args.update is not None:\n        response = request(\n            args.status_file,\n            \"recheck\",\n            export_types=args.export_types,\n            remove=args.remove,\n            update=args.update,\n        )\n    else:\n        response = request(args.status_file, \"recheck\", export_types=args.export_types)\n    t1 = time.time()\n    response[\"roundtrip_time\"] = t1 - t0\n    check_output(response, args.verbose, args.junit_xml, args.perf_stats_file)\n\n\n@action(suggest_parser)\ndef do_suggest(args: argparse.Namespace) -> None:\n    \"\"\"Ask the daemon for a suggested signature.\n\n    This just prints whatever the daemon reports as output.\n    For now it may be closer to a list of call sites.\n    \"\"\"\n    response = request(\n        args.status_file,\n        \"suggest\",\n        function=args.function,\n        json=args.json,\n        callsites=args.callsites,\n        no_errors=args.no_errors,\n        no_any=args.no_any,\n        flex_any=args.flex_any,\n        use_fixme=args.use_fixme,\n        max_guesses=args.max_guesses,\n    )\n    check_output(response, verbose=False, junit_xml=None, perf_stats_file=None)\n\n\n@action(inspect_parser)\ndef do_inspect(args: argparse.Namespace) -> None:\n    \"\"\"Ask daemon to print the type of an expression.\"\"\"\n    response = request(\n        args.status_file,\n        \"inspect\",\n        show=args.show,\n        location=args.location,\n        verbosity=args.verbose,\n        limit=args.limit,\n        include_span=args.include_span,\n        include_kind=args.include_kind,\n        include_object_attrs=args.include_object_attrs,\n        union_attrs=args.union_attrs,\n        force_reload=args.force_reload,\n    )\n    check_output(response, verbose=False, junit_xml=None, perf_stats_file=None)\n\n\ndef check_output(\n    response: dict[str, Any], verbose: bool, junit_xml: str | None, perf_stats_file: str | None\n) -> None:\n    \"\"\"Print the output from a check or recheck command.\n\n    Call sys.exit() unless the status code is zero.\n    \"\"\"\n    if os.name == \"nt\":\n        # Enable ANSI color codes for Windows cmd using this strange workaround\n        # ( see https://github.com/python/cpython/issues/74261 )\n        os.system(\"\")\n    if \"error\" in response:\n        fail(response[\"error\"])\n    try:\n        out, err, status_code = response[\"out\"], response[\"err\"], response[\"status\"]\n    except KeyError:\n        fail(f\"Response: {str(response)}\")\n    sys.stdout.write(out)\n    sys.stdout.flush()\n    sys.stderr.write(err)\n    sys.stderr.flush()\n    if verbose:\n        show_stats(response)\n    if junit_xml:\n        # Lazy import so this import doesn't slow things down when not writing junit\n        from mypy.util import write_junit_xml\n\n        messages = (out + err).splitlines()\n        write_junit_xml(\n            response[\"roundtrip_time\"],\n            bool(err),\n            {None: messages} if messages else {},\n            junit_xml,\n            response[\"python_version\"],\n            response[\"platform\"],\n        )\n    if perf_stats_file:\n        telemetry = response.get(\"stats\", {})\n        with open(perf_stats_file, \"w\") as f:\n            json.dump(telemetry, f)\n\n    if status_code:\n        sys.exit(status_code)\n\n\ndef show_stats(response: Mapping[str, object]) -> None:\n    for key, value in sorted(response.items()):\n        if key in (\"out\", \"err\", \"stdout\", \"stderr\"):\n            # Special case text output to display just 40 characters of text\n            value = repr(value)[1:-1]\n            if len(value) > 50:\n                value = f\"{value[:40]} ... {len(value)-40} more characters\"\n            print(\"%-24s: %s\" % (key, value))\n            continue\n        print(\"%-24s: %10s\" % (key, \"%.3f\" % value if isinstance(value, float) else value))\n\n\n@action(hang_parser)\ndef do_hang(args: argparse.Namespace) -> None:\n    \"\"\"Hang for 100 seconds, as a debug hack.\"\"\"\n    print(request(args.status_file, \"hang\", timeout=1))\n\n\n@action(daemon_parser)\ndef do_daemon(args: argparse.Namespace) -> None:\n    \"\"\"Serve requests in the foreground.\"\"\"\n    # Lazy import so this import doesn't slow down other commands.\n    from mypy.dmypy_server import Server, process_start_options\n\n    if args.log_file:\n        sys.stdout = sys.stderr = open(args.log_file, \"a\", buffering=1)\n        fd = sys.stdout.fileno()\n        os.dup2(fd, 2)\n        os.dup2(fd, 1)\n\n    if args.options_data:\n        from mypy.options import Options\n\n        options_dict = pickle.loads(b64decode(args.options_data))\n        options_obj = Options()\n        options = options_obj.apply_changes(options_dict)\n    else:\n        options = process_start_options(args.flags, allow_sources=False)\n\n    Server(options, args.status_file, timeout=args.timeout).serve()\n\n\n@action(help_parser)\ndef do_help(args: argparse.Namespace) -> None:\n    \"\"\"Print full help (same as dmypy --help).\"\"\"\n    parser.print_help()\n\n\n# Client-side infrastructure.\n\n\ndef request(\n    status_file: str, command: str, *, timeout: int | None = None, **kwds: object\n) -> dict[str, Any]:\n    \"\"\"Send a request to the daemon.\n\n    Return the JSON dict with the response.\n\n    Raise BadStatus if there is something wrong with the status file\n    or if the process whose pid is in the status file has died.\n\n    Return {'error': <message>} if an IPC operation or receive()\n    raised OSError.  This covers cases such as connection refused or\n    closed prematurely as well as invalid JSON received.\n    \"\"\"\n    response: dict[str, str] = {}\n    args = dict(kwds)\n    args[\"command\"] = command\n    # Tell the server whether this request was initiated from a human-facing terminal,\n    # so that it can format the type checking output accordingly.\n    args[\"is_tty\"] = sys.stdout.isatty() or should_force_color()\n    args[\"terminal_width\"] = get_terminal_width()\n    _, name = get_status(status_file)\n    try:\n        with IPCClient(name, timeout) as client:\n            send(client, args)\n\n            final = False\n            while not final:\n                response = receive(client)\n                final = bool(response.pop(\"final\", False))\n                # Display debugging output written to stdout/stderr in the server process for convenience.\n                # This should not be confused with \"out\" and \"err\" fields in the response.\n                # Those fields hold the output of the \"check\" command, and are handled in check_output().\n                stdout = response.pop(\"stdout\", None)\n                if stdout:\n                    sys.stdout.write(stdout)\n                stderr = response.pop(\"stderr\", None)\n                if stderr:\n                    sys.stderr.write(stderr)\n    except (OSError, IPCException) as err:\n        return {\"error\": str(err)}\n    # TODO: Other errors, e.g. ValueError, UnicodeError\n\n    return response\n\n\ndef get_status(status_file: str) -> tuple[int, str]:\n    \"\"\"Read status file and check if the process is alive.\n\n    Return (pid, connection_name) on success.\n\n    Raise BadStatus if something's wrong.\n    \"\"\"\n    data = read_status(status_file)\n    return check_status(data)\n\n\ndef check_status(data: dict[str, Any]) -> tuple[int, str]:\n    \"\"\"Check if the process is alive.\n\n    Return (pid, connection_name) on success.\n\n    Raise BadStatus if something's wrong.\n    \"\"\"\n    if \"pid\" not in data:\n        raise BadStatus(\"Invalid status file (no pid field)\")\n    pid = data[\"pid\"]\n    if not isinstance(pid, int):\n        raise BadStatus(\"pid field is not an int\")\n    if not alive(pid):\n        raise BadStatus(\"Daemon has died\")\n    if \"connection_name\" not in data:\n        raise BadStatus(\"Invalid status file (no connection_name field)\")\n    connection_name = data[\"connection_name\"]\n    if not isinstance(connection_name, str):\n        raise BadStatus(\"connection_name field is not a string\")\n    return pid, connection_name\n\n\ndef is_running(status_file: str) -> bool:\n    \"\"\"Check if the server is running cleanly\"\"\"\n    try:\n        get_status(status_file)\n    except BadStatus:\n        return False\n    return True\n\n\n# Run main().\ndef console_entry() -> None:\n    main(sys.argv[1:])\n"
  },
  {
    "path": "mypy/dmypy_os.py",
    "content": "from __future__ import annotations\n\nimport sys\nfrom collections.abc import Callable\nfrom typing import Any\n\nif sys.platform == \"win32\":\n    import ctypes\n    import subprocess\n    from ctypes.wintypes import DWORD, HANDLE\n\n    PROCESS_QUERY_LIMITED_INFORMATION = ctypes.c_ulong(0x1000)\n\n    kernel32 = ctypes.windll.kernel32\n    OpenProcess: Callable[[DWORD, int, int], HANDLE] = kernel32.OpenProcess\n    GetExitCodeProcess: Callable[[HANDLE, Any], int] = kernel32.GetExitCodeProcess\nelse:\n    import os\n    import signal\n\n\ndef alive(pid: int) -> bool:\n    \"\"\"Is the process alive?\"\"\"\n    if sys.platform == \"win32\":\n        # why can't anything be easy...\n        status = DWORD()\n        handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid)\n        GetExitCodeProcess(handle, ctypes.byref(status))\n        return status.value == 259  # STILL_ACTIVE\n    else:\n        try:\n            os.kill(pid, 0)\n        except OSError:\n            return False\n        return True\n\n\ndef kill(pid: int) -> None:\n    \"\"\"Kill the process.\"\"\"\n    if sys.platform == \"win32\":\n        subprocess.check_output(f\"taskkill /pid {pid} /f /t\")\n    else:\n        os.kill(pid, signal.SIGKILL)\n"
  },
  {
    "path": "mypy/dmypy_server.py",
    "content": "\"\"\"Server for mypy daemon mode.\n\nThis implements a daemon process which keeps useful state in memory\nto enable fine-grained incremental reprocessing of changes.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport io\nimport json\nimport os\nimport pickle\nimport subprocess\nimport sys\nimport time\nimport traceback\nfrom collections.abc import Callable, Sequence, Set as AbstractSet\nfrom contextlib import redirect_stderr, redirect_stdout\nfrom typing import Any, Final, TypeAlias as _TypeAlias\n\nfrom librt.base64 import b64encode\n\nimport mypy.build\nimport mypy.errors\nimport mypy.main\nfrom mypy.dmypy_util import WriteToConn, receive, send\nfrom mypy.find_sources import InvalidSourceList, create_source_list\nfrom mypy.fscache import FileSystemCache\nfrom mypy.fswatcher import FileData, FileSystemWatcher\nfrom mypy.inspections import InspectionEngine\nfrom mypy.ipc import IPCServer\nfrom mypy.modulefinder import BuildSource, FindModuleCache, SearchPaths, compute_search_paths\nfrom mypy.options import Options\nfrom mypy.server.update import FineGrainedBuildManager, refresh_suppressed_submodules\nfrom mypy.suggestions import SuggestionEngine, SuggestionFailure\nfrom mypy.typestate import reset_global_state\nfrom mypy.util import FancyFormatter, count_stats\nfrom mypy.version import __version__\n\nMEM_PROFILE: Final = False  # If True, dump memory profile after initialization\n\nif sys.platform == \"win32\":\n    from subprocess import STARTUPINFO\n\n    def daemonize(\n        options: Options, status_file: str, timeout: int | None = None, log_file: str | None = None\n    ) -> int:\n        \"\"\"Create the daemon process via \"dmypy daemon\" and pass options via command line\n\n        When creating the daemon grandchild, we create it in a new console, which is\n        started hidden. We cannot use DETACHED_PROCESS since it will cause console windows\n        to pop up when starting. See\n        https://github.com/python/cpython/pull/4150#issuecomment-340215696\n        for more on why we can't have nice things.\n\n        It also pickles the options to be unpickled by mypy.\n        \"\"\"\n        command = [sys.executable, \"-m\", \"mypy.dmypy\", \"--status-file\", status_file, \"daemon\"]\n        pickled_options = pickle.dumps(options.snapshot())\n        command.append(f'--options-data=\"{b64encode(pickled_options).decode()}\"')\n        if timeout:\n            command.append(f\"--timeout={timeout}\")\n        if log_file:\n            command.append(f\"--log-file={log_file}\")\n        info = STARTUPINFO()\n        info.dwFlags = 0x1  # STARTF_USESHOWWINDOW aka use wShowWindow's value\n        info.wShowWindow = 0  # SW_HIDE aka make the window invisible\n        try:\n            subprocess.Popen(command, creationflags=0x10, startupinfo=info)  # CREATE_NEW_CONSOLE\n            return 0\n        except subprocess.CalledProcessError as e:\n            return e.returncode\n\nelse:\n\n    def _daemonize_cb(func: Callable[[], None], log_file: str | None = None) -> int:\n        \"\"\"Arrange to call func() in a grandchild of the current process.\n\n        Return 0 for success, exit status for failure, negative if\n        subprocess killed by signal.\n        \"\"\"\n        # See https://stackoverflow.com/questions/473620/how-do-you-create-a-daemon-in-python\n        sys.stdout.flush()\n        sys.stderr.flush()\n        pid = os.fork()\n        if pid:\n            # Parent process: wait for child in case things go bad there.\n            npid, sts = os.waitpid(pid, 0)\n            sig = sts & 0xFF\n            if sig:\n                print(\"Child killed by signal\", sig)\n                return -sig\n            sts = sts >> 8\n            if sts:\n                print(\"Child exit status\", sts)\n            return sts\n        # Child process: do a bunch of UNIX stuff and then fork a grandchild.\n        try:\n            os.setsid()  # Detach controlling terminal\n            os.umask(0o27)\n            devnull = os.open(\"/dev/null\", os.O_RDWR)\n            os.dup2(devnull, 0)\n            os.dup2(devnull, 1)\n            os.dup2(devnull, 2)\n            os.close(devnull)\n            pid = os.fork()\n            if pid:\n                # Child is done, exit to parent.\n                os._exit(0)\n            # Grandchild: run the server.\n            if log_file:\n                sys.stdout = sys.stderr = open(log_file, \"a\", buffering=1)\n                fd = sys.stdout.fileno()\n                os.dup2(fd, 2)\n                os.dup2(fd, 1)\n            func()\n        finally:\n            # Make sure we never get back into the caller.\n            os._exit(1)\n\n    def daemonize(\n        options: Options, status_file: str, timeout: int | None = None, log_file: str | None = None\n    ) -> int:\n        \"\"\"Run the mypy daemon in a grandchild of the current process\n\n        Return 0 for success, exit status for failure, negative if\n        subprocess killed by signal.\n        \"\"\"\n        return _daemonize_cb(Server(options, status_file, timeout).serve, log_file)\n\n\n# Server code.\n\nCONNECTION_NAME: Final = \"dmypy\"\n\n\ndef process_start_options(flags: list[str], allow_sources: bool) -> Options:\n    _, options = mypy.main.process_options(\n        [\"-i\"] + flags, require_targets=False, server_options=True\n    )\n    if options.report_dirs:\n        print(\"dmypy: Ignoring report generation settings. Start/restart cannot generate reports.\")\n    if options.junit_xml:\n        print(\n            \"dmypy: Ignoring report generation settings. \"\n            \"Start/restart does not support --junit-xml. Pass it to check/recheck instead\"\n        )\n        options.junit_xml = None\n    if not options.incremental:\n        sys.exit(\"dmypy: start/restart should not disable incremental mode\")\n    if options.follow_imports not in (\"skip\", \"error\", \"normal\"):\n        sys.exit(\"dmypy: follow-imports=silent not supported\")\n    return options\n\n\ndef ignore_suppressed_imports(module: str) -> bool:\n    \"\"\"Can we skip looking for newly unsuppressed imports to module?\"\"\"\n    # Various submodules of 'encodings' can be suppressed, since it\n    # uses module-level '__getattr__'. Skip them since there are many\n    # of them, and following imports to them is kind of pointless.\n    return module.startswith(\"encodings.\")\n\n\nModulePathPair: _TypeAlias = tuple[str, str]\nModulePathPairs: _TypeAlias = list[ModulePathPair]\nChangesAndRemovals: _TypeAlias = tuple[ModulePathPairs, ModulePathPairs]\n\n\nclass Server:\n    # NOTE: the instance is constructed in the parent process but\n    # serve() is called in the grandchild (by daemonize()).\n\n    def __init__(self, options: Options, status_file: str, timeout: int | None = None) -> None:\n        \"\"\"Initialize the server with the desired mypy flags.\"\"\"\n        self.options = options\n        # Snapshot the options info before we muck with it, to detect changes\n        self.options_snapshot = options.snapshot()\n        self.timeout = timeout\n        self.fine_grained_manager: FineGrainedBuildManager | None = None\n\n        if os.path.isfile(status_file):\n            os.unlink(status_file)\n\n        self.fscache = FileSystemCache()\n\n        options.raise_exceptions = True\n        options.incremental = True\n        options.fine_grained_incremental = True\n        options.show_traceback = True\n        if options.use_fine_grained_cache:\n            # Using fine_grained_cache implies generating and caring\n            # about the fine grained cache\n            options.cache_fine_grained = True\n        else:\n            options.cache_dir = os.devnull\n        # Fine-grained incremental doesn't support general partial types\n        # (details in https://github.com/python/mypy/issues/4492)\n        options.local_partial_types = True\n        self.status_file = status_file\n\n        # Since the object is created in the parent process we can check\n        # the output terminal options here.\n        self.formatter = FancyFormatter(sys.stdout, sys.stderr, options.hide_error_codes)\n\n    def _response_metadata(self) -> dict[str, str]:\n        py_version = f\"{self.options.python_version[0]}_{self.options.python_version[1]}\"\n        return {\"platform\": self.options.platform, \"python_version\": py_version}\n\n    def serve(self) -> None:\n        \"\"\"Serve requests, synchronously (no thread or fork).\"\"\"\n\n        command = None\n        server = IPCServer(CONNECTION_NAME, self.timeout)\n        orig_stdout = sys.stdout\n        orig_stderr = sys.stderr\n\n        try:\n            with open(self.status_file, \"w\") as f:\n                json.dump({\"pid\": os.getpid(), \"connection_name\": server.connection_name}, f)\n                f.write(\"\\n\")  # I like my JSON with a trailing newline\n            while True:\n                with server:\n                    data = receive(server)\n                    sys.stdout = WriteToConn(server, \"stdout\", sys.stdout.isatty())\n                    sys.stderr = WriteToConn(server, \"stderr\", sys.stderr.isatty())\n                    resp: dict[str, Any] = {}\n                    if \"command\" not in data:\n                        resp = {\"error\": \"No command found in request\"}\n                    else:\n                        command = data[\"command\"]\n                        if not isinstance(command, str):\n                            resp = {\"error\": \"Command is not a string\"}\n                        else:\n                            command = data.pop(\"command\")\n                            try:\n                                resp = self.run_command(command, data)\n                            except Exception:\n                                # If we are crashing, report the crash to the client\n                                tb = traceback.format_exception(*sys.exc_info())\n                                resp = {\"error\": \"Daemon crashed!\\n\" + \"\".join(tb)}\n                                resp.update(self._response_metadata())\n                                resp[\"final\"] = True\n                                send(server, resp)\n                                raise\n                    resp[\"final\"] = True\n                    try:\n                        resp.update(self._response_metadata())\n                        send(server, resp)\n                    except OSError:\n                        pass  # Maybe the client hung up\n                    if command == \"stop\":\n                        reset_global_state()\n                        sys.exit(0)\n        finally:\n            # Revert stdout/stderr so we can see any errors.\n            sys.stdout = orig_stdout\n            sys.stderr = orig_stderr\n\n            # If the final command is something other than a clean\n            # stop, remove the status file. (We can't just\n            # simplify the logic and always remove the file, since\n            # that could cause us to remove a future server's\n            # status file.)\n            if command != \"stop\":\n                os.unlink(self.status_file)\n            try:\n                server.cleanup()  # try to remove the socket dir on Linux\n            except OSError:\n                pass\n            exc_info = sys.exc_info()\n            if exc_info[0] and exc_info[0] is not SystemExit:\n                traceback.print_exception(*exc_info)\n\n    def run_command(self, command: str, data: dict[str, object]) -> dict[str, object]:\n        \"\"\"Run a specific command from the registry.\"\"\"\n        key = \"cmd_\" + command\n        method = getattr(self.__class__, key, None)\n        if method is None:\n            return {\"error\": f\"Unrecognized command '{command}'\"}\n        else:\n            if command not in {\"check\", \"recheck\", \"run\"}:\n                # Only the above commands use some error formatting.\n                del data[\"is_tty\"]\n                del data[\"terminal_width\"]\n            ret = method(self, **data)\n            assert isinstance(ret, dict)\n            return ret\n\n    # Command functions (run in the server via RPC).\n\n    def cmd_status(self, fswatcher_dump_file: str | None = None) -> dict[str, object]:\n        \"\"\"Return daemon status.\"\"\"\n        res: dict[str, object] = {}\n        res.update(get_meminfo())\n        if fswatcher_dump_file:\n            data = self.fswatcher.dump_file_data() if hasattr(self, \"fswatcher\") else {}\n            # Using .dumps and then writing was noticeably faster than using dump\n            s = json.dumps(data)\n            with open(fswatcher_dump_file, \"w\") as f:\n                f.write(s)\n        return res\n\n    def cmd_stop(self) -> dict[str, object]:\n        \"\"\"Stop daemon.\"\"\"\n        # We need to remove the status file *before* we complete the\n        # RPC. Otherwise a race condition exists where a subsequent\n        # command can see a status file from a dying server and think\n        # it is a live one.\n        os.unlink(self.status_file)\n        return {}\n\n    def cmd_run(\n        self,\n        version: str,\n        args: Sequence[str],\n        export_types: bool,\n        is_tty: bool,\n        terminal_width: int,\n    ) -> dict[str, object]:\n        \"\"\"Check a list of files, triggering a restart if needed.\"\"\"\n        stderr = io.StringIO()\n        stdout = io.StringIO()\n        try:\n            # Process options can exit on improper arguments, so we need to catch that and\n            # capture stderr so the client can report it\n            with redirect_stderr(stderr):\n                with redirect_stdout(stdout):\n                    sources, options = mypy.main.process_options(\n                        [\"-i\"] + list(args),\n                        require_targets=True,\n                        server_options=True,\n                        fscache=self.fscache,\n                        program=\"mypy-daemon\",\n                        header=argparse.SUPPRESS,\n                    )\n            # Signal that we need to restart if the options have changed\n            if not options.compare_stable(self.options_snapshot):\n                return {\"restart\": \"configuration changed\"}\n            if __version__ != version:\n                return {\"restart\": \"mypy version changed\"}\n            if self.fine_grained_manager:\n                manager = self.fine_grained_manager.manager\n                start_plugins_snapshot = manager.plugins_snapshot\n                _, current_plugins_snapshot = mypy.build.load_plugins(\n                    options, manager.errors, sys.stdout, extra_plugins=()\n                )\n                if current_plugins_snapshot != start_plugins_snapshot:\n                    return {\"restart\": \"plugins changed\"}\n        except InvalidSourceList as err:\n            return {\"out\": \"\", \"err\": str(err), \"status\": 2}\n        except SystemExit as e:\n            return {\"out\": stdout.getvalue(), \"err\": stderr.getvalue(), \"status\": e.code}\n        return self.check(sources, export_types, is_tty, terminal_width)\n\n    def cmd_check(\n        self, files: Sequence[str], export_types: bool, is_tty: bool, terminal_width: int\n    ) -> dict[str, object]:\n        \"\"\"Check a list of files.\"\"\"\n        try:\n            sources = create_source_list(files, self.options, self.fscache)\n        except InvalidSourceList as err:\n            return {\"out\": \"\", \"err\": str(err), \"status\": 2}\n        return self.check(sources, export_types, is_tty, terminal_width)\n\n    def cmd_recheck(\n        self,\n        is_tty: bool,\n        terminal_width: int,\n        export_types: bool,\n        remove: list[str] | None = None,\n        update: list[str] | None = None,\n    ) -> dict[str, object]:\n        \"\"\"Check the same list of files we checked most recently.\n\n        If remove/update is given, they modify the previous list;\n        if all are None, stat() is called for each file in the previous list.\n        \"\"\"\n        t0 = time.time()\n        if not self.fine_grained_manager:\n            return {\"error\": \"Command 'recheck' is only valid after a 'check' command\"}\n        sources = self.previous_sources\n        if remove:\n            removals = set(remove)\n            sources = [s for s in sources if s.path and s.path not in removals]\n        if update:\n            # Sort list of file updates by extension, so *.pyi files are first.\n            update.sort(key=lambda f: os.path.splitext(f)[1], reverse=True)\n\n            known = {s.path for s in sources if s.path}\n            added = [p for p in update if p not in known]\n            try:\n                added_sources = create_source_list(added, self.options, self.fscache)\n            except InvalidSourceList as err:\n                return {\"out\": \"\", \"err\": str(err), \"status\": 2}\n            sources = sources + added_sources  # Make a copy!\n        t1 = time.time()\n        manager = self.fine_grained_manager.manager\n        manager.log(f\"fine-grained increment: cmd_recheck: {t1 - t0:.3f}s\")\n        old_export_types = self.options.export_types\n        self.options.export_types = self.options.export_types or export_types\n        if not self.following_imports():\n            messages = self.fine_grained_increment(\n                sources, remove, update, explicit_export_types=export_types\n            )\n        else:\n            assert remove is None and update is None\n            messages = self.fine_grained_increment_follow_imports(\n                sources, explicit_export_types=export_types\n            )\n        res = self.increment_output(messages, sources, is_tty, terminal_width)\n        self.flush_caches()\n        self.update_stats(res)\n        self.options.export_types = old_export_types\n        return res\n\n    def check(\n        self, sources: list[BuildSource], export_types: bool, is_tty: bool, terminal_width: int\n    ) -> dict[str, Any]:\n        \"\"\"Check using fine-grained incremental mode.\n\n        If is_tty is True format the output nicely with colors and summary line\n        (unless disabled in self.options). Also pass the terminal_width to formatter.\n        \"\"\"\n        old_export_types = self.options.export_types\n        self.options.export_types = self.options.export_types or export_types\n        if not self.fine_grained_manager:\n            res = self.initialize_fine_grained(sources, is_tty, terminal_width)\n        else:\n            if not self.following_imports():\n                messages = self.fine_grained_increment(sources, explicit_export_types=export_types)\n            else:\n                messages = self.fine_grained_increment_follow_imports(\n                    sources, explicit_export_types=export_types\n                )\n            res = self.increment_output(messages, sources, is_tty, terminal_width)\n        self.flush_caches()\n        self.update_stats(res)\n        self.options.export_types = old_export_types\n        return res\n\n    def flush_caches(self) -> None:\n        self.fscache.flush()\n        if self.fine_grained_manager:\n            self.fine_grained_manager.flush_cache()\n\n    def update_stats(self, res: dict[str, Any]) -> None:\n        if self.fine_grained_manager:\n            manager = self.fine_grained_manager.manager\n            manager.dump_stats()\n            res[\"stats\"] = manager.stats\n            manager.stats = {}\n\n    def following_imports(self) -> bool:\n        \"\"\"Are we following imports?\"\"\"\n        # TODO: What about silent?\n        return self.options.follow_imports == \"normal\"\n\n    def initialize_fine_grained(\n        self, sources: list[BuildSource], is_tty: bool, terminal_width: int\n    ) -> dict[str, Any]:\n        self.fswatcher = FileSystemWatcher(self.fscache)\n        t0 = time.time()\n        self.update_sources(sources)\n        t1 = time.time()\n        try:\n            result = mypy.build.build(sources=sources, options=self.options, fscache=self.fscache)\n        except mypy.errors.CompileError as e:\n            output = \"\".join(s + \"\\n\" for s in e.messages)\n            if e.use_stdout:\n                out, err = output, \"\"\n            else:\n                out, err = \"\", output\n            return {\"out\": out, \"err\": err, \"status\": 2}\n        messages = result.errors\n        self.fine_grained_manager = FineGrainedBuildManager(result)\n\n        original_sources_len = len(sources)\n        if self.following_imports():\n            sources = find_all_sources_in_build(self.fine_grained_manager.graph, sources)\n            self.update_sources(sources)\n\n        self.previous_sources = sources\n\n        # If we are using the fine-grained cache, build hasn't actually done\n        # the typechecking on the updated files yet.\n        # Run a fine-grained update starting from the cached data\n        if result.used_cache:\n            t2 = time.time()\n            # Pull times and hashes out of the saved_cache and stick them into\n            # the fswatcher, so we pick up the changes.\n            for state in self.fine_grained_manager.graph.values():\n                meta = state.meta\n                if meta is None:\n                    continue\n                assert state.path is not None\n                self.fswatcher.set_file_data(\n                    state.path,\n                    FileData(st_mtime=float(meta.mtime), st_size=meta.size, hash=meta.hash),\n                )\n\n            changed, removed = self.find_changed(sources)\n            changed += self.find_added_suppressed(\n                self.fine_grained_manager.graph,\n                set(),\n                self.fine_grained_manager.manager.search_paths,\n            )\n\n            # Find anything that has had its dependency list change\n            for state in self.fine_grained_manager.graph.values():\n                if not state.is_fresh():\n                    assert state.path is not None\n                    changed.append((state.id, state.path))\n\n            t3 = time.time()\n            # Run an update\n            messages = self.fine_grained_manager.update(changed, removed)\n\n            if self.following_imports():\n                # We need to do another update to any new files found by following imports.\n                messages = self.fine_grained_increment_follow_imports(sources)\n\n            t4 = time.time()\n            self.fine_grained_manager.manager.add_stats(\n                update_sources_time=t1 - t0,\n                build_time=t2 - t1,\n                find_changes_time=t3 - t2,\n                fg_update_time=t4 - t3,\n                files_changed=len(removed) + len(changed),\n            )\n\n        else:\n            # Stores the initial state of sources as a side effect.\n            self.fswatcher.find_changed()\n\n        if MEM_PROFILE:\n            from mypy.memprofile import print_memory_profile\n\n            print_memory_profile(run_gc=False)\n\n        __, n_notes, __ = count_stats(messages)\n        status = 1 if messages and n_notes < len(messages) else 0\n        # We use explicit sources length to match the logic in non-incremental mode.\n        messages = self.pretty_messages(messages, original_sources_len, is_tty, terminal_width)\n        return {\"out\": \"\".join(s + \"\\n\" for s in messages), \"err\": \"\", \"status\": status}\n\n    def fine_grained_increment(\n        self,\n        sources: list[BuildSource],\n        remove: list[str] | None = None,\n        update: list[str] | None = None,\n        explicit_export_types: bool = False,\n    ) -> list[str]:\n        \"\"\"Perform a fine-grained type checking increment.\n\n        If remove and update are None, determine changed paths by using\n        fswatcher. Otherwise, assume that only these files have changes.\n\n        Args:\n            sources: sources passed on the command line\n            remove: paths of files that have been removed\n            update: paths of files that have been changed or created\n            explicit_export_types: --export-type was passed in a check command\n              (as opposite to being set in dmypy start)\n        \"\"\"\n        assert self.fine_grained_manager is not None\n        manager = self.fine_grained_manager.manager\n\n        t0 = time.time()\n        if remove is None and update is None:\n            # Use the fswatcher to determine which files were changed\n            # (updated or added) or removed.\n            self.update_sources(sources)\n            changed, removed = self.find_changed(sources)\n        else:\n            # Use the remove/update lists to update fswatcher.\n            # This avoids calling stat() for unchanged files.\n            changed, removed = self.update_changed(sources, remove or [], update or [])\n        if explicit_export_types:\n            # If --export-types is given, we need to force full re-checking of all\n            # explicitly passed files, since we need to visit each expression.\n            add_all_sources_to_changed(sources, changed)\n        changed += self.find_added_suppressed(\n            self.fine_grained_manager.graph, set(), manager.search_paths\n        )\n        manager.search_paths = compute_search_paths(sources, manager.options, manager.data_dir)\n        t1 = time.time()\n        manager.log(f\"fine-grained increment: find_changed: {t1 - t0:.3f}s\")\n        messages = self.fine_grained_manager.update(changed, removed)\n        t2 = time.time()\n        manager.log(f\"fine-grained increment: update: {t2 - t1:.3f}s\")\n        manager.add_stats(\n            find_changes_time=t1 - t0,\n            fg_update_time=t2 - t1,\n            files_changed=len(removed) + len(changed),\n        )\n\n        self.previous_sources = sources\n        return messages\n\n    def fine_grained_increment_follow_imports(\n        self, sources: list[BuildSource], explicit_export_types: bool = False\n    ) -> list[str]:\n        \"\"\"Like fine_grained_increment, but follow imports.\"\"\"\n        t0 = time.time()\n\n        # TODO: Support file events\n\n        assert self.fine_grained_manager is not None\n        fine_grained_manager = self.fine_grained_manager\n        graph = fine_grained_manager.graph\n        manager = fine_grained_manager.manager\n\n        orig_modules = list(graph.keys())\n\n        self.update_sources(sources)\n        changed_paths = self.fswatcher.find_changed()\n        manager.search_paths = compute_search_paths(sources, manager.options, manager.data_dir)\n\n        t1 = time.time()\n        manager.log(f\"fine-grained increment: find_changed: {t1 - t0:.3f}s\")\n\n        # Track all modules encountered so far. New entries for all dependencies\n        # are added below by other module finding methods below. All dependencies\n        # in graph but not in `seen` are considered deleted at the end of this method.\n        seen = {source.module for source in sources}\n\n        # Find changed modules reachable from roots (or in roots) already in graph.\n        changed, new_files = self.find_reachable_changed_modules(\n            sources, graph, seen, changed_paths\n        )\n        # Same as in fine_grained_increment().\n        self.add_explicitly_new(sources, changed)\n        if explicit_export_types:\n            # Same as in fine_grained_increment().\n            add_all_sources_to_changed(sources, changed)\n        sources.extend(new_files)\n\n        # Process changes directly reachable from roots.\n        messages = fine_grained_manager.update(changed, [], followed=True)\n\n        # Follow deps from changed modules (still within graph).\n        worklist = changed.copy()\n        while worklist:\n            module = worklist.pop()\n            if module[0] not in graph:\n                continue\n            sources2 = self.direct_imports(module, graph)\n            # Filter anything already seen before. This prevents\n            # infinite looping if there are any self edges. (Self\n            # edges are maybe a bug, but...)\n            sources2 = [source for source in sources2 if source.module not in seen]\n            changed, new_files = self.find_reachable_changed_modules(\n                sources2, graph, seen, changed_paths\n            )\n            self.update_sources(new_files)\n            messages = fine_grained_manager.update(changed, [], followed=True)\n            worklist.extend(changed)\n\n        t2 = time.time()\n\n        def refresh_file(module: str, path: str) -> list[str]:\n            return fine_grained_manager.update([(module, path)], [], followed=True)\n\n        for module_id, state in list(graph.items()):\n            new_messages = refresh_suppressed_submodules(\n                module_id, state.path, fine_grained_manager.deps, graph, self.fscache, refresh_file\n            )\n            if new_messages is not None:\n                messages = new_messages\n\n        t3 = time.time()\n\n        # There may be new files that became available, currently treated as\n        # suppressed imports. Process them.\n        while True:\n            new_unsuppressed = self.find_added_suppressed(graph, seen, manager.search_paths)\n            if not new_unsuppressed:\n                break\n            new_files = [BuildSource(mod[1], mod[0], followed=True) for mod in new_unsuppressed]\n            sources.extend(new_files)\n            self.update_sources(new_files)\n            messages = fine_grained_manager.update(new_unsuppressed, [], followed=True)\n\n            for module_id, path in new_unsuppressed:\n                new_messages = refresh_suppressed_submodules(\n                    module_id, path, fine_grained_manager.deps, graph, self.fscache, refresh_file\n                )\n                if new_messages is not None:\n                    messages = new_messages\n\n        t4 = time.time()\n\n        # Find all original modules in graph that were not reached -- they are deleted.\n        to_delete = []\n        for module_id in orig_modules:\n            if module_id not in graph:\n                continue\n            if module_id not in seen:\n                module_path = graph[module_id].path\n                assert module_path is not None\n                to_delete.append((module_id, module_path))\n        if to_delete:\n            messages = fine_grained_manager.update([], to_delete)\n\n        fix_module_deps(graph)\n\n        self.previous_sources = find_all_sources_in_build(graph)\n        self.update_sources(self.previous_sources)\n\n        # Store current file state as side effect\n        self.fswatcher.find_changed()\n\n        t5 = time.time()\n\n        manager.log(f\"fine-grained increment: update: {t5 - t1:.3f}s\")\n        manager.add_stats(\n            find_changes_time=t1 - t0,\n            fg_update_time=t2 - t1,\n            refresh_suppressed_time=t3 - t2,\n            find_added_suppressed_time=t4 - t3,\n            cleanup_time=t5 - t4,\n        )\n\n        return messages\n\n    def find_reachable_changed_modules(\n        self,\n        roots: list[BuildSource],\n        graph: mypy.build.Graph,\n        seen: set[str],\n        changed_paths: AbstractSet[str],\n    ) -> tuple[list[tuple[str, str]], list[BuildSource]]:\n        \"\"\"Follow imports within graph from given sources until hitting changed modules.\n\n        If we find a changed module, we can't continue following imports as the imports\n        may have changed.\n\n        Args:\n            roots: modules where to start search from\n            graph: module graph to use for the search\n            seen: modules we've seen before that won't be visited (mutated here!!).\n                  Needed to accumulate all modules encountered during update and remove\n                  everything that no longer exists.\n            changed_paths: which paths have changed (stop search here and return any found)\n\n        Return (encountered reachable changed modules,\n                unchanged files not in sources_set traversed).\n        \"\"\"\n        changed = []\n        new_files = []\n        worklist = roots.copy()\n        seen.update(source.module for source in worklist)\n        while worklist:\n            nxt = worklist.pop()\n            if nxt.module not in seen:\n                seen.add(nxt.module)\n                new_files.append(nxt)\n            if nxt.path in changed_paths:\n                assert nxt.path is not None  # TODO\n                changed.append((nxt.module, nxt.path))\n            elif nxt.module in graph:\n                state = graph[nxt.module]\n                ancestors = state.ancestors or []\n                for dep in state.dependencies + ancestors:\n                    if dep not in seen:\n                        seen.add(dep)\n                        worklist.append(BuildSource(graph[dep].path, graph[dep].id, followed=True))\n        return changed, new_files\n\n    def direct_imports(\n        self, module: tuple[str, str], graph: mypy.build.Graph\n    ) -> list[BuildSource]:\n        \"\"\"Return the direct imports of module not included in seen.\"\"\"\n        state = graph[module[0]]\n        return [BuildSource(graph[dep].path, dep, followed=True) for dep in state.dependencies]\n\n    def find_added_suppressed(\n        self, graph: mypy.build.Graph, seen: set[str], search_paths: SearchPaths\n    ) -> list[tuple[str, str]]:\n        \"\"\"Find suppressed modules that have been added (and not included in seen).\n\n        Args:\n            seen: reachable modules we've seen before (mutated here!!).\n                  Needed to accumulate all modules encountered during update and remove\n                  everything that no longer exists.\n\n        Return suppressed, added modules.\n        \"\"\"\n        all_suppressed = set()\n        for state in graph.values():\n            all_suppressed |= state.suppressed_set\n\n        # Filter out things that shouldn't actually be considered suppressed.\n        #\n        # TODO: Figure out why these are treated as suppressed\n        all_suppressed = {\n            module\n            for module in all_suppressed\n            if module not in graph and not ignore_suppressed_imports(module)\n        }\n\n        # Optimization: skip top-level packages that are obviously not\n        # there, to avoid calling the relatively slow find_module()\n        # below too many times.\n        packages = {module.split(\".\", 1)[0] for module in all_suppressed}\n        packages = filter_out_missing_top_level_packages(packages, search_paths, self.fscache)\n\n        # TODO: Namespace packages\n\n        finder = FindModuleCache(search_paths, self.fscache, self.options)\n\n        found = []\n\n        for module in all_suppressed:\n            top_level_pkg = module.split(\".\", 1)[0]\n            if top_level_pkg not in packages:\n                # Fast path: non-existent top-level package\n                continue\n            result = finder.find_module(module, fast_path=True)\n            if isinstance(result, str) and module not in seen:\n                # When not following imports, we only follow imports to .pyi files.\n                if not self.following_imports() and not result.endswith(\".pyi\"):\n                    continue\n                found.append((module, result))\n                seen.add(module)\n\n        return found\n\n    def increment_output(\n        self, messages: list[str], sources: list[BuildSource], is_tty: bool, terminal_width: int\n    ) -> dict[str, Any]:\n        status = 1 if messages else 0\n        messages = self.pretty_messages(messages, len(sources), is_tty, terminal_width)\n        return {\"out\": \"\".join(s + \"\\n\" for s in messages), \"err\": \"\", \"status\": status}\n\n    def pretty_messages(\n        self,\n        messages: list[str],\n        n_sources: int,\n        is_tty: bool = False,\n        terminal_width: int | None = None,\n    ) -> list[str]:\n        use_color = self.options.color_output and is_tty\n        fit_width = self.options.pretty and is_tty\n        if fit_width:\n            messages = self.formatter.fit_in_terminal(\n                messages, fixed_terminal_width=terminal_width\n            )\n        if self.options.error_summary:\n            summary: str | None = None\n            n_errors, n_notes, n_files = count_stats(messages)\n            if n_errors:\n                summary = self.formatter.format_error(\n                    n_errors, n_files, n_sources, use_color=use_color\n                )\n            elif not messages or n_notes == len(messages):\n                summary = self.formatter.format_success(n_sources, use_color)\n            if summary:\n                # Create new list to avoid appending multiple summaries on successive runs.\n                messages = messages + [summary]\n        if use_color:\n            messages = [self.formatter.colorize(m) for m in messages]\n        return messages\n\n    def update_sources(self, sources: list[BuildSource]) -> None:\n        paths = [source.path for source in sources if source.path is not None]\n        if self.following_imports():\n            # Filter out directories (used for namespace packages).\n            paths = [path for path in paths if self.fscache.isfile(path)]\n        self.fswatcher.add_watched_paths(paths)\n\n    def update_changed(\n        self, sources: list[BuildSource], remove: list[str], update: list[str]\n    ) -> ChangesAndRemovals:\n        changed_paths = self.fswatcher.update_changed(remove, update)\n        return self._find_changed(sources, changed_paths)\n\n    def find_changed(self, sources: list[BuildSource]) -> ChangesAndRemovals:\n        changed_paths = self.fswatcher.find_changed()\n        return self._find_changed(sources, changed_paths)\n\n    def _find_changed(\n        self, sources: list[BuildSource], changed_paths: AbstractSet[str]\n    ) -> ChangesAndRemovals:\n        # Find anything that has been added or modified\n        changed = [\n            (source.module, source.path)\n            for source in sources\n            if source.path and source.path in changed_paths\n        ]\n\n        # Now find anything that has been removed from the build\n        modules = {source.module for source in sources}\n        omitted = [source for source in self.previous_sources if source.module not in modules]\n        removed = []\n        for source in omitted:\n            path = source.path\n            assert path\n            removed.append((source.module, path))\n\n        self.add_explicitly_new(sources, changed)\n\n        # Find anything that has had its module path change because of added or removed __init__s\n        last = {s.path: s.module for s in self.previous_sources}\n        for s in sources:\n            assert s.path\n            if s.path in last and last[s.path] != s.module:\n                # Mark it as removed from its old name and changed at its new name\n                removed.append((last[s.path], s.path))\n                changed.append((s.module, s.path))\n\n        return changed, removed\n\n    def add_explicitly_new(\n        self, sources: list[BuildSource], changed: list[tuple[str, str]]\n    ) -> None:\n        # Always add modules that were (re-)added, since they may be detected as not changed by\n        # fswatcher (if they were actually not changed), but they may still need to be checked\n        # in case they had errors before they were deleted from sources on previous runs.\n        previous_modules = {source.module for source in self.previous_sources}\n        changed_set = set(changed)\n        changed.extend(\n            [\n                (source.module, source.path)\n                for source in sources\n                if source.path\n                and source.module not in previous_modules\n                and (source.module, source.path) not in changed_set\n            ]\n        )\n\n    def cmd_inspect(\n        self,\n        show: str,\n        location: str,\n        verbosity: int = 0,\n        limit: int = 0,\n        include_span: bool = False,\n        include_kind: bool = False,\n        include_object_attrs: bool = False,\n        union_attrs: bool = False,\n        force_reload: bool = False,\n    ) -> dict[str, object]:\n        \"\"\"Locate and inspect expression(s).\"\"\"\n        if not self.fine_grained_manager:\n            return {\n                \"error\": 'Command \"inspect\" is only valid after a \"check\" command'\n                \" (that produces no parse errors)\"\n            }\n        engine = InspectionEngine(\n            self.fine_grained_manager,\n            verbosity=verbosity,\n            limit=limit,\n            include_span=include_span,\n            include_kind=include_kind,\n            include_object_attrs=include_object_attrs,\n            union_attrs=union_attrs,\n            force_reload=force_reload,\n        )\n        old_inspections = self.options.inspections\n        self.options.inspections = True\n        try:\n            if show == \"type\":\n                result = engine.get_type(location)\n            elif show == \"attrs\":\n                result = engine.get_attrs(location)\n            elif show == \"definition\":\n                result = engine.get_definition(location)\n            else:\n                assert False, \"Unknown inspection kind\"\n        finally:\n            self.options.inspections = old_inspections\n        if \"out\" in result:\n            assert isinstance(result[\"out\"], str)\n            result[\"out\"] += \"\\n\"\n        return result\n\n    def cmd_suggest(self, function: str, callsites: bool, **kwargs: Any) -> dict[str, object]:\n        \"\"\"Suggest a signature for a function.\"\"\"\n        if not self.fine_grained_manager:\n            return {\n                \"error\": \"Command 'suggest' is only valid after a 'check' command\"\n                \" (that produces no parse errors)\"\n            }\n        engine = SuggestionEngine(self.fine_grained_manager, **kwargs)\n        try:\n            if callsites:\n                out = engine.suggest_callsites(function)\n            else:\n                out = engine.suggest(function)\n        except SuggestionFailure as err:\n            return {\"error\": str(err)}\n        else:\n            if not out:\n                out = \"No suggestions\\n\"\n            elif not out.endswith(\"\\n\"):\n                out += \"\\n\"\n            return {\"out\": out, \"err\": \"\", \"status\": 0}\n        finally:\n            self.flush_caches()\n\n    def cmd_hang(self) -> dict[str, object]:\n        \"\"\"Hang for 100 seconds, as a debug hack.\"\"\"\n        time.sleep(100)\n        return {}\n\n\n# Misc utilities.\n\n\nMiB: Final = 2**20\n\n\ndef get_meminfo() -> dict[str, Any]:\n    res: dict[str, Any] = {}\n    try:\n        import psutil\n    except ImportError:\n        res[\"memory_psutil_missing\"] = (\n            \"psutil not found, run pip install mypy[dmypy] \"\n            \"to install the needed components for dmypy\"\n        )\n    else:\n        process = psutil.Process()\n        meminfo = process.memory_info()\n        res[\"memory_rss_mib\"] = meminfo.rss / MiB\n        res[\"memory_vms_mib\"] = meminfo.vms / MiB\n        if sys.platform == \"win32\":\n            res[\"memory_maxrss_mib\"] = meminfo.peak_wset / MiB\n        else:\n            # See https://stackoverflow.com/questions/938733/total-memory-used-by-python-process\n            import resource  # Since it doesn't exist on Windows.\n\n            rusage = resource.getrusage(resource.RUSAGE_SELF)\n            if sys.platform == \"darwin\":\n                factor = 1\n            else:\n                factor = 1024  # Linux\n            res[\"memory_maxrss_mib\"] = rusage.ru_maxrss * factor / MiB\n    return res\n\n\ndef find_all_sources_in_build(\n    graph: mypy.build.Graph, extra: Sequence[BuildSource] = ()\n) -> list[BuildSource]:\n    result = list(extra)\n    seen = {source.module for source in result}\n    for module, state in graph.items():\n        if module not in seen:\n            result.append(BuildSource(state.path, module))\n    return result\n\n\ndef add_all_sources_to_changed(sources: list[BuildSource], changed: list[tuple[str, str]]) -> None:\n    \"\"\"Add all (explicit) sources to the list changed files in place.\n\n    Use this when re-processing of unchanged files is needed (e.g. for\n    the purpose of exporting types for inspections).\n    \"\"\"\n    changed_set = set(changed)\n    changed.extend(\n        [\n            (bs.module, bs.path)\n            for bs in sources\n            if bs.path and (bs.module, bs.path) not in changed_set\n        ]\n    )\n\n\ndef fix_module_deps(graph: mypy.build.Graph) -> None:\n    \"\"\"After an incremental update, update module dependencies to reflect the new state.\n\n    This can make some suppressed dependencies non-suppressed, and vice versa (if modules\n    have been added to or removed from the build).\n    \"\"\"\n    for state in graph.values():\n        new_suppressed = []\n        new_dependencies = []\n        for dep in state.dependencies + state.suppressed:\n            if dep in graph:\n                new_dependencies.append(dep)\n            else:\n                new_suppressed.append(dep)\n        state.dependencies = new_dependencies\n        state.dependencies_set = set(new_dependencies)\n        state.suppressed = new_suppressed\n        state.suppressed_set = set(new_suppressed)\n\n\ndef filter_out_missing_top_level_packages(\n    packages: set[str], search_paths: SearchPaths, fscache: FileSystemCache\n) -> set[str]:\n    \"\"\"Quickly filter out obviously missing top-level packages.\n\n    Return packages with entries that can't be found removed.\n\n    This is approximate: some packages that aren't actually valid may be\n    included. However, all potentially valid packages must be returned.\n    \"\"\"\n    # Start with a empty set and add all potential top-level packages.\n    found = set()\n    paths = (\n        search_paths.python_path\n        + search_paths.mypy_path\n        + search_paths.package_path\n        + search_paths.typeshed_path\n    )\n    for p in paths:\n        try:\n            entries = fscache.listdir(p)\n        except Exception:\n            entries = []\n        for entry in entries:\n            # The code is hand-optimized for mypyc since this may be somewhat\n            # performance-critical.\n            if entry.endswith(\".py\"):\n                entry = entry[:-3]\n            elif entry.endswith(\".pyi\"):\n                entry = entry[:-4]\n            elif entry.endswith(\"-stubs\"):\n                # Possible PEP 561 stub package\n                entry = entry[:-6]\n            if entry in packages:\n                found.add(entry)\n    return found\n"
  },
  {
    "path": "mypy/dmypy_util.py",
    "content": "\"\"\"Shared code between dmypy.py and dmypy_server.py.\n\nThis should be pretty lightweight and not depend on other mypy code (other than ipc).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport io\nimport json\nfrom collections.abc import Iterable, Iterator\nfrom types import TracebackType\nfrom typing import Any, Final, TextIO\n\nfrom mypy.ipc import IPCBase\n\nDEFAULT_STATUS_FILE: Final = \".dmypy.json\"\n\n\ndef receive(connection: IPCBase) -> Any:\n    \"\"\"Receive single JSON data frame from a connection.\n\n    Raise OSError if the data received is not valid JSON or if it is\n    not a dict.\n    \"\"\"\n    bdata = connection.read()\n    if not bdata:\n        raise OSError(\"No data received\")\n    try:\n        data = json.loads(bdata)\n    except Exception as e:\n        raise OSError(\"Data received is not valid JSON\") from e\n    if not isinstance(data, dict):\n        raise OSError(f\"Data received is not a dict ({type(data)})\")\n    return data\n\n\ndef send(connection: IPCBase, data: Any) -> None:\n    \"\"\"Send data to a connection encoded and framed.\n\n    The data must be JSON-serializable. We assume that a single send call is a\n    single frame to be sent on the connect.\n    \"\"\"\n    connection.write(json.dumps(data))\n\n\nclass WriteToConn(TextIO):\n    \"\"\"Helper class to write to a connection instead of standard output.\"\"\"\n\n    def __init__(self, server: IPCBase, output_key: str, isatty: bool) -> None:\n        self.server = server\n        self.output_key = output_key\n        self._isatty = isatty\n\n    def __enter__(self) -> TextIO:\n        return self\n\n    def __exit__(\n        self,\n        t: type[BaseException] | None,\n        value: BaseException | None,\n        traceback: TracebackType | None,\n    ) -> None:\n        pass\n\n    def __iter__(self) -> Iterator[str]:\n        raise io.UnsupportedOperation\n\n    def __next__(self) -> str:\n        raise io.UnsupportedOperation\n\n    def close(self) -> None:\n        pass\n\n    def fileno(self) -> int:\n        raise OSError\n\n    def flush(self) -> None:\n        pass\n\n    def isatty(self) -> bool:\n        return self._isatty\n\n    def read(self, n: int = 0) -> str:\n        raise io.UnsupportedOperation\n\n    def readable(self) -> bool:\n        return False\n\n    def readline(self, limit: int = 0) -> str:\n        raise io.UnsupportedOperation\n\n    def readlines(self, hint: int = 0) -> list[str]:\n        raise io.UnsupportedOperation\n\n    def seek(self, offset: int, whence: int = 0) -> int:\n        raise io.UnsupportedOperation\n\n    def seekable(self) -> bool:\n        return False\n\n    def tell(self) -> int:\n        raise io.UnsupportedOperation\n\n    def truncate(self, size: int | None = 0) -> int:\n        raise io.UnsupportedOperation\n\n    def write(self, output: str) -> int:\n        resp: dict[str, Any] = {self.output_key: output}\n        send(self.server, resp)\n        return len(output)\n\n    def writable(self) -> bool:\n        return True\n\n    def writelines(self, lines: Iterable[str]) -> None:\n        for s in lines:\n            self.write(s)\n"
  },
  {
    "path": "mypy/erasetype.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Callable, Container\nfrom typing import cast\n\nfrom mypy.nodes import ARG_STAR, ARG_STAR2\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeTranslator,\n    TypeType,\n    TypeVarId,\n    TypeVarTupleType,\n    TypeVarType,\n    TypeVisitor,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    get_proper_type,\n    get_proper_types,\n)\nfrom mypy.typevartuples import erased_vars\n\n\ndef erase_type(typ: Type) -> ProperType:\n    \"\"\"Erase any type variables from a type.\n\n    Also replace tuple types with the corresponding concrete types.\n\n    Examples:\n      A -> A\n      B[X] -> B[Any]\n      Tuple[A, B] -> tuple\n      Callable[[A1, A2, ...], R] -> Callable[..., Any]\n      Type[X] -> Type[Any]\n    \"\"\"\n    typ = get_proper_type(typ)\n    return typ.accept(EraseTypeVisitor())\n\n\nclass EraseTypeVisitor(TypeVisitor[ProperType]):\n    def visit_unbound_type(self, t: UnboundType) -> ProperType:\n        # TODO: replace with an assert after UnboundType can't leak from semantic analysis.\n        return AnyType(TypeOfAny.from_error)\n\n    def visit_any(self, t: AnyType) -> ProperType:\n        return t\n\n    def visit_none_type(self, t: NoneType) -> ProperType:\n        return t\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:\n        return t\n\n    def visit_erased_type(self, t: ErasedType) -> ProperType:\n        return t\n\n    def visit_partial_type(self, t: PartialType) -> ProperType:\n        # Should not get here.\n        raise RuntimeError(\"Cannot erase partial types\")\n\n    def visit_deleted_type(self, t: DeletedType) -> ProperType:\n        return t\n\n    def visit_instance(self, t: Instance) -> ProperType:\n        args = erased_vars(t.type.defn.type_vars, TypeOfAny.special_form)\n        return Instance(t.type, args, t.line)\n\n    def visit_type_var(self, t: TypeVarType) -> ProperType:\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_param_spec(self, t: ParamSpecType) -> ProperType:\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_parameters(self, t: Parameters) -> ProperType:\n        raise RuntimeError(\"Parameters should have been bound to a class\")\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType:\n        # Likely, we can never get here because of aggressive erasure of types that\n        # can contain this, but better still return a valid replacement.\n        return t.tuple_fallback.copy_modified(args=[AnyType(TypeOfAny.special_form)])\n\n    def visit_unpack_type(self, t: UnpackType) -> ProperType:\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_callable_type(self, t: CallableType) -> ProperType:\n        # We must preserve the fallback type for overload resolution to work.\n        any_type = AnyType(TypeOfAny.special_form)\n        return CallableType(\n            arg_types=[any_type, any_type],\n            arg_kinds=[ARG_STAR, ARG_STAR2],\n            arg_names=[None, None],\n            ret_type=any_type,\n            fallback=t.fallback,\n            is_ellipsis_args=True,\n            implicit=True,\n        )\n\n    def visit_overloaded(self, t: Overloaded) -> ProperType:\n        return t.fallback.accept(self)\n\n    def visit_tuple_type(self, t: TupleType) -> ProperType:\n        return t.partial_fallback.accept(self)\n\n    def visit_typeddict_type(self, t: TypedDictType) -> ProperType:\n        return t.fallback.accept(self)\n\n    def visit_literal_type(self, t: LiteralType) -> ProperType:\n        # The fallback for literal types should always be either\n        # something like int or str, or an enum class -- types that\n        # don't contain any TypeVars. So there's no need to visit it.\n        return t\n\n    def visit_union_type(self, t: UnionType) -> ProperType:\n        erased_items = [erase_type(item) for item in t.items]\n        from mypy.typeops import make_simplified_union\n\n        return make_simplified_union(erased_items)\n\n    def visit_type_type(self, t: TypeType) -> ProperType:\n        return TypeType.make_normalized(\n            t.item.accept(self), line=t.line, is_type_form=t.is_type_form\n        )\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> ProperType:\n        raise RuntimeError(\"Type aliases should be expanded before accepting this visitor\")\n\n\ndef erase_typevars(t: Type, ids_to_erase: Container[TypeVarId] | None = None) -> Type:\n    \"\"\"Replace all type variables in a type with any,\n    or just the ones in the provided collection.\n    \"\"\"\n\n    if ids_to_erase is None:\n        return t.accept(TypeVarEraser(None, AnyType(TypeOfAny.special_form)))\n\n    def erase_id(id: TypeVarId) -> bool:\n        return id in ids_to_erase\n\n    return t.accept(TypeVarEraser(erase_id, AnyType(TypeOfAny.special_form)))\n\n\ndef erase_meta_id(id: TypeVarId) -> bool:\n    return id.is_meta_var()\n\n\ndef replace_meta_vars(t: Type, target_type: Type) -> Type:\n    \"\"\"Replace unification variables in a type with the target type.\"\"\"\n    return t.accept(TypeVarEraser(erase_meta_id, target_type))\n\n\nclass TypeVarEraser(TypeTranslator):\n    \"\"\"Implementation of type erasure\"\"\"\n\n    def __init__(self, erase_id: Callable[[TypeVarId], bool] | None, replacement: Type) -> None:\n        super().__init__()\n        self.erase_id = erase_id\n        self.replacement = replacement\n\n    def visit_type_var(self, t: TypeVarType) -> Type:\n        if self.erase_id is None or self.erase_id(t.id):\n            return self.replacement\n        return t\n\n    # TODO: below two methods duplicate some logic with expand_type().\n    # In fact, we may want to refactor this whole visitor to use expand_type().\n    def visit_instance(self, t: Instance) -> Type:\n        result = super().visit_instance(t)\n        assert isinstance(result, ProperType) and isinstance(result, Instance)\n        if t.type.fullname == \"builtins.tuple\":\n            # Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...]\n            arg = result.args[0]\n            if isinstance(arg, UnpackType):\n                unpacked = get_proper_type(arg.type)\n                if isinstance(unpacked, Instance):\n                    assert unpacked.type.fullname == \"builtins.tuple\"\n                    return unpacked\n        return result\n\n    def visit_tuple_type(self, t: TupleType) -> Type:\n        result = super().visit_tuple_type(t)\n        assert isinstance(result, ProperType) and isinstance(result, TupleType)\n        if len(result.items) == 1:\n            # Normalize Tuple[*Tuple[X, ...]] -> Tuple[X, ...]\n            item = result.items[0]\n            if isinstance(item, UnpackType):\n                unpacked = get_proper_type(item.type)\n                if isinstance(unpacked, Instance):\n                    assert unpacked.type.fullname == \"builtins.tuple\"\n                    if result.partial_fallback.type.fullname != \"builtins.tuple\":\n                        # If it is a subtype (like named tuple) we need to preserve it,\n                        # this essentially mimics the logic in tuple_fallback().\n                        return result.partial_fallback.accept(self)\n                    return unpacked\n        return result\n\n    def visit_callable_type(self, t: CallableType) -> Type:\n        result = super().visit_callable_type(t)\n        assert isinstance(result, ProperType) and isinstance(result, CallableType)\n        # Usually this is done in semanal_typeargs.py, but erasure can create\n        # a non-normal callable from normal one.\n        result.normalize_trivial_unpack()\n        return result\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type:\n        if self.erase_id is None or self.erase_id(t.id):\n            return t.tuple_fallback.copy_modified(args=[self.replacement])\n        return t\n\n    def visit_param_spec(self, t: ParamSpecType) -> Type:\n        # TODO: we should probably preserve prefix here.\n        if self.erase_id is None or self.erase_id(t.id):\n            return self.replacement\n        return t\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        # Type alias target can't contain bound type variables (not bound by the type\n        # alias itself), so it is safe to just erase the arguments.\n        return t.copy_modified(args=[a.accept(self) for a in t.args])\n\n\ndef remove_instance_last_known_values(t: Type) -> Type:\n    return t.accept(LastKnownValueEraser())\n\n\nclass LastKnownValueEraser(TypeTranslator):\n    \"\"\"Removes the Literal[...] type that may be associated with any\n    Instance types.\"\"\"\n\n    def visit_instance(self, t: Instance) -> Type:\n        if not t.last_known_value and not t.args:\n            return t\n        return t.copy_modified(args=[a.accept(self) for a in t.args], last_known_value=None)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        # Type aliases can't contain literal values, because they are\n        # always constructed as explicit types.\n        return t\n\n    def visit_union_type(self, t: UnionType) -> Type:\n        new = cast(UnionType, super().visit_union_type(t))\n        # Erasure can result in many duplicate items; merge them.\n        # Call make_simplified_union only on lists of instance types\n        # that all have the same fullname, to avoid simplifying too\n        # much.\n        instances = [item for item in new.items if isinstance(get_proper_type(item), Instance)]\n        # Avoid merge in simple cases such as optional types.\n        if len(instances) > 1:\n            instances_by_name: dict[str, list[Instance]] = {}\n            p_new_items = get_proper_types(new.items)\n            for p_item in p_new_items:\n                if isinstance(p_item, Instance) and not p_item.args:\n                    instances_by_name.setdefault(p_item.type.fullname, []).append(p_item)\n            merged: list[Type] = []\n            for item in new.items:\n                orig_item = item\n                item = get_proper_type(item)\n                if isinstance(item, Instance) and not item.args:\n                    types = instances_by_name.get(item.type.fullname)\n                    if types is not None:\n                        if len(types) == 1:\n                            merged.append(item)\n                        else:\n                            from mypy.typeops import make_simplified_union\n\n                            merged.append(make_simplified_union(types))\n                            del instances_by_name[item.type.fullname]\n                else:\n                    merged.append(orig_item)\n            return UnionType.make_union(merged)\n        return new\n\n\ndef shallow_erase_type_for_equality(typ: Type) -> ProperType:\n    \"\"\"Erase type variables from Instance's\"\"\"\n    p_typ = get_proper_type(typ)\n    if isinstance(p_typ, Instance):\n        if not p_typ.args:\n            return p_typ\n        args = erased_vars(p_typ.type.defn.type_vars, TypeOfAny.special_form)\n        return Instance(p_typ.type, args, p_typ.line)\n    if isinstance(p_typ, UnionType):\n        items = [shallow_erase_type_for_equality(item) for item in p_typ.items]\n        return UnionType.make_union(items)\n    return p_typ\n"
  },
  {
    "path": "mypy/error_formatter.py",
    "content": "\"\"\"Defines the different custom formats in which mypy can output.\"\"\"\n\nimport json\nfrom abc import ABC, abstractmethod\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from mypy.errors import MypyError\n\n\nclass ErrorFormatter(ABC):\n    \"\"\"Base class to define how errors are formatted before being printed.\"\"\"\n\n    @abstractmethod\n    def report_error(self, error: \"MypyError\") -> str:\n        raise NotImplementedError\n\n\nclass JSONFormatter(ErrorFormatter):\n    \"\"\"Formatter for basic JSON output format.\"\"\"\n\n    def report_error(self, error: \"MypyError\") -> str:\n        \"\"\"Prints out the errors as simple, static JSON lines.\"\"\"\n        return json.dumps(\n            {\n                \"file\": error.file_path,\n                \"line\": error.line,\n                \"column\": error.column,\n                \"end_line\": error.end_line,\n                \"end_column\": error.end_column,\n                \"message\": error.message,\n                \"hint\": None if len(error.hints) == 0 else \"\\n\".join(error.hints),\n                \"code\": error.errorcode,\n                \"severity\": error.severity,\n            }\n        )\n\n\nOUTPUT_CHOICES = {\"json\": JSONFormatter()}\n"
  },
  {
    "path": "mypy/errorcodes.py",
    "content": "\"\"\"Classification of possible errors mypy can detect.\n\nThese can be used for filtering specific errors.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom typing import Final\n\nfrom mypy_extensions import mypyc_attr\n\nerror_codes: dict[str, ErrorCode] = {}\nsub_code_map: dict[str, set[str]] = defaultdict(set)\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass ErrorCode:\n    def __init__(\n        self,\n        code: str,\n        description: str,\n        category: str,\n        default_enabled: bool = True,\n        sub_code_of: ErrorCode | None = None,\n    ) -> None:\n        self.code = code\n        self.description = description\n        self.category = category\n        self.default_enabled = default_enabled\n        self.sub_code_of = sub_code_of\n        if sub_code_of is not None:\n            assert sub_code_of.sub_code_of is None, \"Nested subcategories are not supported\"\n            sub_code_map[sub_code_of.code].add(code)\n        error_codes[code] = self\n\n    def __str__(self) -> str:\n        return f\"<ErrorCode {self.code}>\"\n\n    def __repr__(self) -> str:\n        \"\"\"This doesn't fulfill the goals of repr but it's better than the default view.\"\"\"\n        return f\"<ErrorCode {self.category}: {self.code}>\"\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, ErrorCode):\n            return False\n        return self.code == other.code\n\n    def __hash__(self) -> int:\n        return hash((self.code,))\n\n\nATTR_DEFINED: Final = ErrorCode(\"attr-defined\", \"Check that attribute exists\", \"General\")\nNAME_DEFINED: Final = ErrorCode(\"name-defined\", \"Check that name is defined\", \"General\")\nCALL_ARG: Final = ErrorCode(\n    \"call-arg\", \"Check number, names and kinds of arguments in calls\", \"General\"\n)\nARG_TYPE: Final = ErrorCode(\"arg-type\", \"Check argument types in calls\", \"General\")\nCALL_OVERLOAD: Final = ErrorCode(\n    \"call-overload\", \"Check that an overload variant matches arguments\", \"General\"\n)\nVALID_TYPE: Final = ErrorCode(\"valid-type\", \"Check that type (annotation) is valid\", \"General\")\nNONETYPE_TYPE: Final = ErrorCode(\n    \"nonetype-type\", \"Check that type (annotation) is not NoneType\", \"General\"\n)\nVAR_ANNOTATED: Final = ErrorCode(\n    \"var-annotated\", \"Require variable annotation if type can't be inferred\", \"General\"\n)\nOVERRIDE: Final = ErrorCode(\n    \"override\", \"Check that method override is compatible with base class\", \"General\"\n)\nRETURN: Final = ErrorCode(\"return\", \"Check that function always returns a value\", \"General\")\nRETURN_VALUE: Final = ErrorCode(\n    \"return-value\", \"Check that return value is compatible with signature\", \"General\"\n)\nASSIGNMENT: Final = ErrorCode(\n    \"assignment\", \"Check that assigned value is compatible with target\", \"General\"\n)\nMETHOD_ASSIGN: Final = ErrorCode(\n    \"method-assign\",\n    \"Check that assignment target is not a method\",\n    \"General\",\n    sub_code_of=ASSIGNMENT,\n)\nTYPE_ARG: Final = ErrorCode(\"type-arg\", \"Check that generic type arguments are present\", \"General\")\nTYPE_VAR: Final = ErrorCode(\"type-var\", \"Check that type variable values are valid\", \"General\")\nUNION_ATTR: Final = ErrorCode(\n    \"union-attr\", \"Check that attribute exists in each item of a union\", \"General\"\n)\nINDEX: Final = ErrorCode(\"index\", \"Check indexing operations\", \"General\")\nOPERATOR: Final = ErrorCode(\"operator\", \"Check that operator is valid for operands\", \"General\")\nLIST_ITEM: Final = ErrorCode(\n    \"list-item\", \"Check list items in a list expression [item, ...]\", \"General\"\n)\nDICT_ITEM: Final = ErrorCode(\n    \"dict-item\", \"Check dict items in a dict expression {key: value, ...}\", \"General\"\n)\nTYPEDDICT_ITEM: Final = ErrorCode(\n    \"typeddict-item\", \"Check items when constructing TypedDict\", \"General\"\n)\nTYPEDDICT_UNKNOWN_KEY: Final = ErrorCode(\n    \"typeddict-unknown-key\",\n    \"Check unknown keys when constructing TypedDict\",\n    \"General\",\n    sub_code_of=TYPEDDICT_ITEM,\n)\nHAS_TYPE: Final = ErrorCode(\n    \"has-type\", \"Check that type of reference can be determined\", \"General\"\n)\nIMPORT: Final = ErrorCode(\n    \"import\", \"Require that imported module can be found or has stubs\", \"General\"\n)\nIMPORT_NOT_FOUND: Final = ErrorCode(\n    \"import-not-found\", \"Require that imported module can be found\", \"General\", sub_code_of=IMPORT\n)\nIMPORT_UNTYPED: Final = ErrorCode(\n    \"import-untyped\", \"Require that imported module has stubs\", \"General\", sub_code_of=IMPORT\n)\nNO_REDEF: Final = ErrorCode(\"no-redef\", \"Check that each name is defined once\", \"General\")\nFUNC_RETURNS_VALUE: Final = ErrorCode(\n    \"func-returns-value\", \"Check that called function returns a value in value context\", \"General\"\n)\nABSTRACT: Final = ErrorCode(\n    \"abstract\", \"Prevent instantiation of classes with abstract attributes\", \"General\"\n)\nTYPE_ABSTRACT: Final = ErrorCode(\n    \"type-abstract\", \"Require only concrete classes where Type[...] is expected\", \"General\"\n)\nVALID_NEWTYPE: Final = ErrorCode(\n    \"valid-newtype\", \"Check that argument 2 to NewType is valid\", \"General\"\n)\nSTRING_FORMATTING: Final = ErrorCode(\n    \"str-format\", \"Check that string formatting/interpolation is type-safe\", \"General\"\n)\nSTR_BYTES_PY3: Final = ErrorCode(\n    \"str-bytes-safe\", \"Warn about implicit coercions related to bytes and string types\", \"General\"\n)\nEXIT_RETURN: Final = ErrorCode(\n    \"exit-return\", \"Warn about too general return type for '__exit__'\", \"General\"\n)\nLITERAL_REQ: Final = ErrorCode(\"literal-required\", \"Check that value is a literal\", \"General\")\nUNUSED_COROUTINE: Final = ErrorCode(\n    \"unused-coroutine\", \"Ensure that all coroutines are used\", \"General\"\n)\nEMPTY_BODY: Final = ErrorCode(\n    \"empty-body\",\n    \"A dedicated error code to opt out return errors for empty/trivial bodies\",\n    \"General\",\n)\nSAFE_SUPER: Final = ErrorCode(\n    \"safe-super\", \"Warn about calls to abstract methods with empty/trivial bodies\", \"General\"\n)\nTOP_LEVEL_AWAIT: Final = ErrorCode(\n    \"top-level-await\", \"Warn about top level await expressions\", \"General\"\n)\nAWAIT_NOT_ASYNC: Final = ErrorCode(\n    \"await-not-async\", 'Warn about \"await\" outside coroutine (\"async def\")', \"General\"\n)\n# These error codes aren't enabled by default.\nNO_UNTYPED_DEF: Final = ErrorCode(\n    \"no-untyped-def\", \"Check that every function has an annotation\", \"General\"\n)\nNO_UNTYPED_CALL: Final = ErrorCode(\n    \"no-untyped-call\",\n    \"Disallow calling functions without type annotations from annotated functions\",\n    \"General\",\n)\nREDUNDANT_CAST: Final = ErrorCode(\n    \"redundant-cast\", \"Check that cast changes type of expression\", \"General\"\n)\nASSERT_TYPE: Final = ErrorCode(\"assert-type\", \"Check that assert_type() call succeeds\", \"General\")\nCOMPARISON_OVERLAP: Final = ErrorCode(\n    \"comparison-overlap\", \"Check that types in comparisons and 'in' expressions overlap\", \"General\"\n)\nNO_ANY_UNIMPORTED: Final = ErrorCode(\n    \"no-any-unimported\", 'Reject \"Any\" types from unfollowed imports', \"General\"\n)\nNO_ANY_RETURN: Final = ErrorCode(\n    \"no-any-return\",\n    'Reject returning value with \"Any\" type if return type is not \"Any\"',\n    \"General\",\n)\nUNREACHABLE: Final = ErrorCode(\n    \"unreachable\", \"Warn about unreachable statements or expressions\", \"General\"\n)\nANNOTATION_UNCHECKED: Final = ErrorCode(\n    \"annotation-unchecked\", \"Notify about type annotations in unchecked functions\", \"General\"\n)\nTYPEDDICT_READONLY_MUTATED: Final = ErrorCode(\n    \"typeddict-readonly-mutated\", \"TypedDict's ReadOnly key is mutated\", \"General\"\n)\nPOSSIBLY_UNDEFINED: Final = ErrorCode(\n    \"possibly-undefined\",\n    \"Warn about variables that are defined only in some execution paths\",\n    \"General\",\n    default_enabled=False,\n)\nREDUNDANT_EXPR: Final = ErrorCode(\n    \"redundant-expr\", \"Warn about redundant expressions\", \"General\", default_enabled=False\n)\nTRUTHY_BOOL: Final = ErrorCode(\n    \"truthy-bool\",\n    \"Warn about expressions that could always evaluate to true in boolean contexts\",\n    \"General\",\n    default_enabled=False,\n)\nTRUTHY_FUNCTION: Final = ErrorCode(\n    \"truthy-function\",\n    \"Warn about function that always evaluate to true in boolean contexts\",\n    \"General\",\n)\nTRUTHY_ITERABLE: Final = ErrorCode(\n    \"truthy-iterable\",\n    \"Warn about Iterable expressions that could always evaluate to true in boolean contexts\",\n    \"General\",\n    default_enabled=False,\n)\nSTR_UNPACK: Final[ErrorCode] = ErrorCode(\n    \"str-unpack\", \"Warn about expressions that unpack str\", \"General\"\n)\nNAME_MATCH: Final = ErrorCode(\n    \"name-match\", \"Check that type definition has consistent naming\", \"General\"\n)\nNO_OVERLOAD_IMPL: Final = ErrorCode(\n    \"no-overload-impl\",\n    \"Check that overloaded functions outside stub files have an implementation\",\n    \"General\",\n)\nIGNORE_WITHOUT_CODE: Final = ErrorCode(\n    \"ignore-without-code\",\n    \"Warn about '# type: ignore' comments which do not have error codes\",\n    \"General\",\n    default_enabled=False,\n)\nUNUSED_AWAITABLE: Final = ErrorCode(\n    \"unused-awaitable\",\n    \"Ensure that all awaitable values are used\",\n    \"General\",\n    default_enabled=False,\n)\nREDUNDANT_SELF_TYPE: Final = ErrorCode(\n    \"redundant-self\",\n    \"Warn about redundant Self type annotations on method first argument\",\n    \"General\",\n    default_enabled=False,\n)\nUSED_BEFORE_DEF: Final = ErrorCode(\n    \"used-before-def\", \"Warn about variables that are used before they are defined\", \"General\"\n)\nUNUSED_IGNORE: Final = ErrorCode(\n    \"unused-ignore\", \"Ensure that all type ignores are used\", \"General\", default_enabled=False\n)\nEXPLICIT_OVERRIDE_REQUIRED: Final = ErrorCode(\n    \"explicit-override\",\n    \"Require @override decorator if method is overriding a base class method\",\n    \"General\",\n    default_enabled=False,\n)\nUNIMPORTED_REVEAL: Final = ErrorCode(\n    \"unimported-reveal\",\n    \"Require explicit import from typing or typing_extensions for reveal_type\",\n    \"General\",\n    default_enabled=False,\n)\nMUTABLE_OVERRIDE: Final = ErrorCode(\n    \"mutable-override\",\n    \"Reject covariant overrides for mutable attributes\",\n    \"General\",\n    default_enabled=False,\n)\nEXHAUSTIVE_MATCH: Final = ErrorCode(\n    \"exhaustive-match\",\n    \"Reject match statements that are not exhaustive\",\n    \"General\",\n    default_enabled=False,\n)\nMETACLASS: Final = ErrorCode(\"metaclass\", \"Ensure that metaclass is valid\", \"General\")\nMAYBE_UNRECOGNIZED_STR_TYPEFORM: Final = ErrorCode(\n    \"maybe-unrecognized-str-typeform\",\n    \"Error when a string is used where a TypeForm is expected but a string annotation cannot be recognized\",\n    \"General\",\n)\n\n# Syntax errors are often blocking.\nSYNTAX: Final = ErrorCode(\"syntax\", \"Report syntax errors\", \"General\")\n\n# This is a catch-all for remaining uncategorized errors.\nMISC: Final = ErrorCode(\"misc\", \"Miscellaneous other checks\", \"General\")\n\nOVERLOAD_CANNOT_MATCH: Final = ErrorCode(\n    \"overload-cannot-match\",\n    \"Warn if an @overload signature can never be matched\",\n    \"General\",\n    sub_code_of=MISC,\n)\n\nOVERLOAD_OVERLAP: Final = ErrorCode(\n    \"overload-overlap\",\n    \"Warn if multiple @overload variants overlap in unsafe ways\",\n    \"General\",\n    sub_code_of=MISC,\n)\n\nPROPERTY_DECORATOR: Final = ErrorCode(\n    \"prop-decorator\",\n    \"Decorators on top of @property are not supported\",\n    \"General\",\n    sub_code_of=MISC,\n)\n\nUNTYPED_DECORATOR: Final = ErrorCode(\n    \"untyped-decorator\", \"Error if an untyped decorator makes a typed function untyped\", \"General\"\n)\n\nNARROWED_TYPE_NOT_SUBTYPE: Final = ErrorCode(\n    \"narrowed-type-not-subtype\",\n    \"Warn if a TypeIs function's narrowed type is not a subtype of the original type\",\n    \"General\",\n)\n\nEXPLICIT_ANY: Final = ErrorCode(\n    \"explicit-any\", \"Warn about explicit Any type annotations\", \"General\"\n)\n\nDEPRECATED: Final = ErrorCode(\n    \"deprecated\",\n    \"Warn when importing or using deprecated (overloaded) functions, methods or classes\",\n    \"General\",\n    default_enabled=False,\n)\n\n# This copy will not include any error codes defined later in the plugins.\nmypy_error_codes = error_codes.copy()\n"
  },
  {
    "path": "mypy/errors.py",
    "content": "from __future__ import annotations\n\nimport os.path\nimport sys\nimport traceback\nfrom collections import defaultdict\nfrom collections.abc import Callable, Iterable, Iterator\nfrom itertools import chain\nfrom typing import Final, Literal, NoReturn, TextIO, TypeVar\nfrom typing_extensions import Self\n\nfrom librt.internal import (\n    ReadBuffer,\n    WriteBuffer,\n    read_bool,\n    read_int as read_int_bare,\n    write_bool,\n    write_int as write_int_bare,\n)\n\nfrom mypy import errorcodes as codes\nfrom mypy.cache import (\n    ErrorTuple,\n    read_int,\n    read_int_list,\n    read_str,\n    read_str_opt,\n    write_int,\n    write_int_list,\n    write_str,\n    write_str_opt,\n)\nfrom mypy.error_formatter import ErrorFormatter\nfrom mypy.errorcodes import IMPORT, IMPORT_NOT_FOUND, IMPORT_UNTYPED, ErrorCode, mypy_error_codes\nfrom mypy.nodes import Context\nfrom mypy.options import Options\nfrom mypy.scope import Scope\nfrom mypy.types import Type\nfrom mypy.util import DEFAULT_SOURCE_OFFSET\nfrom mypy.version import __version__ as mypy_version\n\nT = TypeVar(\"T\")\n\n# Show error codes for some note-level messages (these usually appear alone\n# and not as a comment for a previous error-level message).\nSHOW_NOTE_CODES: Final = {codes.ANNOTATION_UNCHECKED.code, codes.DEPRECATED.code}\n\n# Do not add notes with links to error code docs to errors with these codes.\n# We can tweak this set as we get more experience about what is helpful and what is not.\nHIDE_LINK_CODES: Final = {\n    # This is a generic error code, so it has no useful docs\n    codes.MISC,\n    # These are trivial and have some custom notes (e.g. for list being invariant)\n    codes.ASSIGNMENT,\n    codes.ARG_TYPE,\n    codes.RETURN_VALUE,\n    # Undefined name/attribute errors are self-explanatory\n    codes.ATTR_DEFINED,\n    codes.NAME_DEFINED,\n    # Overrides have a custom link to docs\n    codes.OVERRIDE,\n}\n\nBASE_RTD_URL: Final = \"https://mypy.rtfd.io/en/stable/_refs.html#code\"\n\n# Keep track of the original error code when the error code of a message is changed.\n# This is used to give notes about out-of-date \"type: ignore\" comments.\noriginal_error_codes: Final = {codes.LITERAL_REQ: codes.MISC, codes.TYPE_ABSTRACT: codes.MISC}\n\n\nclass ErrorInfo:\n    \"\"\"Representation of a single error message.\"\"\"\n\n    # Description of a sequence of imports that refer to the source file\n    # related to this error. Each item is a (path, line number) tuple.\n    import_ctx: list[tuple[str, int]]\n    # Type and function/method where this error occurred. Unqualified, may be None.\n    local_ctx: tuple[str | None, str | None]\n\n    # The line number related to this error within file.\n    line = 0  # -1 if unknown\n    # The column number related to this error with file.\n    column = 0  # -1 if unknown\n    # The end line number related to this error within file.\n    end_line = 0  # -1 if unknown\n    # The end column number related to this error with file.\n    end_column = 0  # -1 if unknown\n    # Either 'error' or 'note'\n    severity = \"\"\n    # The error message.\n    message = \"\"\n    # The error code.\n    code: ErrorCode | None = None\n\n    # If True, we should halt build after the file that generated this error.\n    blocker = False\n    # Only report this particular messages once per program.\n    only_once = False\n\n    # These two are used by the daemon:\n    # The fully-qualified id of the source module for this error.\n    module: str | None\n    # Fine-grained incremental target where this was reported\n    target: str | None\n\n    # Lines where `type: ignores` will have effect on this error, for most errors\n    # this is just [line]. But sometimes may be custom, e.g. for override errors\n    # in methods with multi-line definition.\n    origin_span: Iterable[int]\n    # For errors on the same line you can use this to customize their sorting\n    # (lower value means show first).\n    priority: int\n    # If True, don't show this message in output, but still record the error.\n    hidden = False\n\n    # For notes, specifies (optionally) the error this note is attached to. This is used to\n    # simplify error code matching and de-duplication logic for complex multi-line notes.\n    parent_error: ErrorInfo | None = None\n\n    def __init__(\n        self,\n        *,\n        import_ctx: list[tuple[str, int]],\n        local_ctx: tuple[str | None, str | None],\n        line: int,\n        column: int,\n        end_line: int,\n        end_column: int,\n        severity: str,\n        message: str,\n        code: ErrorCode | None,\n        blocker: bool,\n        only_once: bool,\n        module: str | None,\n        target: str | None,\n        origin_span: Iterable[int] | None = None,\n        priority: int = 0,\n        parent_error: ErrorInfo | None = None,\n    ) -> None:\n        self.import_ctx = import_ctx\n        self.module = module\n        self.local_ctx = local_ctx\n        self.line = line\n        self.column = column\n        self.end_line = end_line\n        self.end_column = end_column\n        self.severity = severity\n        self.message = message\n        self.code = code\n        self.blocker = blocker\n        self.only_once = only_once\n        self.origin_span = origin_span or [line]\n        self.target = target\n        self.priority = priority\n        if parent_error is not None:\n            assert severity == \"note\", \"Only notes can specify parent errors\"\n        self.parent_error = parent_error\n\n    def write(self, buf: WriteBuffer) -> None:\n        assert self.parent_error is None, \"Parent errors not supported yet\"\n        write_int_bare(buf, len(self.import_ctx))\n        for file, line in self.import_ctx:\n            write_str(buf, file)\n            write_int(buf, line)\n        type, function = self.local_ctx\n        write_str_opt(buf, type)\n        write_str_opt(buf, function)\n        write_int(buf, self.line)\n        write_int(buf, self.column)\n        write_int(buf, self.end_line)\n        write_int(buf, self.end_column)\n        write_str(buf, self.severity)\n        write_str(buf, self.message)\n        write_str_opt(buf, self.code.code if self.code else None)\n        write_bool(buf, self.blocker)\n        write_bool(buf, self.only_once)\n        write_str_opt(buf, self.module)\n        write_str_opt(buf, self.target)\n        write_int_list(buf, list(self.origin_span))\n        write_int(buf, self.priority)\n\n    @classmethod\n    def read(cls, buf: ReadBuffer) -> ErrorInfo:\n        return ErrorInfo(\n            import_ctx=[(read_str(buf), read_int(buf)) for _ in range(read_int_bare(buf))],\n            local_ctx=(read_str_opt(buf), read_str_opt(buf)),\n            line=read_int(buf),\n            column=read_int(buf),\n            end_line=read_int(buf),\n            end_column=read_int(buf),\n            severity=read_str(buf),\n            message=read_str(buf),\n            code=mypy_error_codes[code] if (code := read_str_opt(buf)) else None,\n            blocker=read_bool(buf),\n            only_once=read_bool(buf),\n            module=read_str_opt(buf),\n            target=read_str_opt(buf),\n            origin_span=read_int_list(buf),\n            priority=read_int(buf),\n        )\n\n\nclass ErrorWatcher:\n    \"\"\"Context manager that can be used to keep track of new errors recorded\n    around a given operation.\n\n    Errors maintain a stack of such watchers. The handler is called starting\n    at the top of the stack, and is propagated down the stack unless filtered\n    out by one of the ErrorWatcher instances.\n    \"\"\"\n\n    # public attribute for the special treatment of `reveal_type` by\n    # `MessageBuilder.reveal_type`:\n    filter_revealed_type: bool\n\n    def __init__(\n        self,\n        errors: Errors,\n        *,\n        filter_errors: bool | Callable[[str, ErrorInfo], bool] = False,\n        save_filtered_errors: bool = False,\n        filter_deprecated: bool = False,\n        filter_revealed_type: bool = False,\n    ) -> None:\n        self.errors = errors\n        self._has_new_errors = False\n        self._filter = filter_errors\n        self._filter_deprecated = filter_deprecated\n        self.filter_revealed_type = filter_revealed_type\n        self._filtered: list[ErrorInfo] | None = [] if save_filtered_errors else None\n\n    def __enter__(self) -> Self:\n        self.errors._watchers.append(self)\n        return self\n\n    def __exit__(self, exc_type: object, exc_val: object, exc_tb: object) -> Literal[False]:\n        last = self.errors._watchers.pop()\n        assert last == self\n        return False\n\n    def on_error(self, file: str, info: ErrorInfo) -> bool:\n        \"\"\"Handler called when a new error is recorded.\n\n        The default implementation just sets the has_new_errors flag\n\n        Return True to filter out the error, preventing it from being seen by other\n        ErrorWatcher further down the stack and from being recorded by Errors\n        \"\"\"\n        if info.code == codes.DEPRECATED:\n            # Deprecated is not a type error, so it is handled on opt-in basis here.\n            if not self._filter_deprecated:\n                return False\n\n        self._has_new_errors = True\n        if isinstance(self._filter, bool):\n            should_filter = self._filter\n        elif callable(self._filter):\n            should_filter = self._filter(file, info)\n        else:\n            raise AssertionError(f\"invalid error filter: {type(self._filter)}\")\n        if should_filter and self._filtered is not None:\n            self._filtered.append(info)\n\n        return should_filter\n\n    def has_new_errors(self) -> bool:\n        return self._has_new_errors\n\n    def filtered_errors(self) -> list[ErrorInfo]:\n        assert self._filtered is not None\n        return self._filtered\n\n\nclass NonOverlapErrorInfo:\n    line: int\n    column: int\n    end_line: int | None\n    end_column: int | None\n    kind: str\n\n    def __init__(\n        self, *, line: int, column: int, end_line: int | None, end_column: int | None, kind: str\n    ) -> None:\n        self.line = line\n        self.column = column\n        self.end_line = end_line\n        self.end_column = end_column\n        self.kind = kind\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, NonOverlapErrorInfo):\n            return (\n                self.line == other.line\n                and self.column == other.column\n                and self.end_line == other.end_line\n                and self.end_column == other.end_column\n                and self.kind == other.kind\n            )\n        return False\n\n    def __hash__(self) -> int:\n        return hash((self.line, self.column, self.end_line, self.end_column, self.kind))\n\n\nclass IterationDependentErrors:\n    \"\"\"An `IterationDependentErrors` instance serves to collect the `unreachable`,\n    `redundant-expr`, and `redundant-casts` errors, as well as the revealed types and\n    non-overlapping types, handled by the individual `IterationErrorWatcher` instances\n    sequentially applied to the same code section.\"\"\"\n\n    # One set of `unreachable`, `redundant-expr`, and `redundant-casts` errors per\n    # iteration step.  Meaning of the tuple items: ErrorCode, message, line, column,\n    # end_line, end_column.\n    uselessness_errors: list[set[tuple[ErrorCode, str, int, int, int, int]]]\n\n    # One set of unreachable line numbers per iteration step.  Not only the lines where\n    # the error report occurs but really all unreachable lines.\n    unreachable_lines: list[set[int]]\n\n    # One list of revealed types for each `reveal_type` statement.  Each created list\n    # can grow during the iteration.  Meaning of the tuple items: line, column,\n    # end_line, end_column:\n    revealed_types: dict[tuple[int, int, int | None, int | None], list[Type]]\n\n    # One dictionary of non-overlapping types per iteration step:\n    nonoverlapping_types: list[dict[NonOverlapErrorInfo, tuple[Type, Type]]]\n\n    def __init__(self) -> None:\n        self.uselessness_errors = []\n        self.unreachable_lines = []\n        self.nonoverlapping_types = []\n        self.revealed_types = defaultdict(list)\n\n    def yield_uselessness_error_infos(self) -> Iterator[tuple[str, Context, ErrorCode]]:\n        \"\"\"Report only those `unreachable`, `redundant-expr`, and `redundant-casts`\n        errors that could not be ruled out in any iteration step.\"\"\"\n\n        persistent_uselessness_errors = set()\n        for candidate in set(chain(*self.uselessness_errors)):\n            if all(\n                (candidate in errors) or (candidate[2] in lines)\n                for errors, lines in zip(self.uselessness_errors, self.unreachable_lines)\n            ):\n                persistent_uselessness_errors.add(candidate)\n        for error_info in persistent_uselessness_errors:\n            context = Context(line=error_info[2], column=error_info[3])\n            context.end_line = error_info[4]\n            context.end_column = error_info[5]\n            yield error_info[1], context, error_info[0]\n\n    def yield_nonoverlapping_types(\n        self,\n    ) -> Iterator[tuple[tuple[list[Type], list[Type]], str, Context]]:\n        \"\"\"Report expressions where non-overlapping types were detected for all iterations\n        were the expression was reachable.\"\"\"\n\n        selected = set()\n        for candidate in set(chain.from_iterable(self.nonoverlapping_types)):\n            if all(\n                (candidate in nonoverlap) or (candidate.line in lines)\n                for nonoverlap, lines in zip(self.nonoverlapping_types, self.unreachable_lines)\n            ):\n                selected.add(candidate)\n\n        persistent_nonoverlaps: dict[NonOverlapErrorInfo, tuple[list[Type], list[Type]]] = (\n            defaultdict(lambda: ([], []))\n        )\n        for nonoverlaps in self.nonoverlapping_types:\n            for candidate, (left, right) in nonoverlaps.items():\n                if candidate in selected:\n                    types = persistent_nonoverlaps[candidate]\n                    types[0].append(left)\n                    types[1].append(right)\n\n        for error_info, types in persistent_nonoverlaps.items():\n            context = Context(line=error_info.line, column=error_info.column)\n            context.end_line = error_info.end_line\n            context.end_column = error_info.end_column\n            yield (types[0], types[1]), error_info.kind, context\n\n    def yield_revealed_type_infos(self) -> Iterator[tuple[list[Type], Context]]:\n        \"\"\"Yield all types revealed in at least one iteration step.\"\"\"\n\n        for note_info, types in self.revealed_types.items():\n            context = Context(line=note_info[0], column=note_info[1])\n            context.end_line = note_info[2]\n            context.end_column = note_info[3]\n            yield types, context\n\n\nclass IterationErrorWatcher(ErrorWatcher):\n    \"\"\"Error watcher that filters and separately collects `unreachable` errors,\n    `redundant-expr` and `redundant-casts` errors, and revealed types and\n    non-overlapping types when analysing code sections iteratively to help avoid\n    making too-hasty reports.\"\"\"\n\n    iteration_dependent_errors: IterationDependentErrors\n\n    def __init__(\n        self,\n        errors: Errors,\n        iteration_dependent_errors: IterationDependentErrors,\n        *,\n        filter_errors: bool | Callable[[str, ErrorInfo], bool] = False,\n        save_filtered_errors: bool = False,\n        filter_deprecated: bool = False,\n    ) -> None:\n        super().__init__(\n            errors,\n            filter_errors=filter_errors,\n            save_filtered_errors=save_filtered_errors,\n            filter_deprecated=filter_deprecated,\n        )\n        self.iteration_dependent_errors = iteration_dependent_errors\n        iteration_dependent_errors.uselessness_errors.append(set())\n        iteration_dependent_errors.nonoverlapping_types.append({})\n        iteration_dependent_errors.unreachable_lines.append(set())\n\n    def on_error(self, file: str, info: ErrorInfo) -> bool:\n        \"\"\"Filter out the \"iteration-dependent\" errors and notes and store their\n        information to handle them after iteration is completed.\"\"\"\n\n        iter_errors = self.iteration_dependent_errors\n\n        if info.code in (codes.UNREACHABLE, codes.REDUNDANT_EXPR, codes.REDUNDANT_CAST):\n            iter_errors.uselessness_errors[-1].add(\n                (info.code, info.message, info.line, info.column, info.end_line, info.end_column)\n            )\n            if info.code == codes.UNREACHABLE:\n                iter_errors.unreachable_lines[-1].update(range(info.line, info.end_line + 1))\n            return True\n\n        return super().on_error(file, info)\n\n\nclass Errors:\n    \"\"\"Container for compile errors.\n\n    This class generates and keeps tracks of compile errors and the\n    current error context (nested imports).\n    \"\"\"\n\n    # Map from files to generated error messages. Is an OrderedDict so\n    # that it can be used to order messages based on the order the\n    # files were processed.\n    error_info_map: dict[str, list[ErrorInfo]]\n\n    # optimization for legacy codebases with many files with errors\n    has_blockers: set[str]\n\n    # Files that we have reported the errors for\n    flushed_files: set[str]\n\n    # Current error context: nested import context/stack, as a list of (path, line) pairs.\n    import_ctx: list[tuple[str, int]]\n\n    # Path name prefix that is removed from all paths, if set.\n    ignore_prefix: str | None = None\n\n    # Path to current file.\n    file: str = \"\"\n\n    # Ignore some errors on these lines of each file\n    # (path -> line -> error-codes)\n    ignored_lines: dict[str, dict[int, list[str]]]\n\n    # Lines that were skipped during semantic analysis e.g. due to ALWAYS_FALSE, MYPY_FALSE,\n    # or platform/version checks. Those lines would not be type-checked.\n    skipped_lines: dict[str, set[int]]\n\n    # Lines on which an error was actually ignored.\n    used_ignored_lines: dict[str, dict[int, list[str]]]\n\n    # Files where all errors should be ignored.\n    ignored_files: set[str]\n\n    # Collection of reported only_once messages.\n    only_once_messages: set[str]\n\n    # State for keeping track of the current fine-grained incremental mode target.\n    # (See mypy.server.update for more about targets.)\n    # Current module id.\n    target_module: str | None = None\n    scope: Scope | None = None\n\n    # Have we seen an import-related error so far? If yes, we filter out other messages\n    # in some cases to avoid reporting huge numbers of errors.\n    seen_import_error = False\n\n    # Set this flag to record all raw report() calls. Recorded error (per file) can\n    # be replayed using by calling set_file() and add_error_info().\n    global_watcher = False\n    recorded: dict[str, list[ErrorInfo]]\n\n    _watchers: list[ErrorWatcher]\n\n    def __init__(\n        self,\n        options: Options,\n        *,\n        read_source: Callable[[str], list[str] | None] | None = None,\n        hide_error_codes: bool | None = None,\n    ) -> None:\n        self.options = options\n        self.hide_error_codes = (\n            hide_error_codes if hide_error_codes is not None else options.hide_error_codes\n        )\n        # We use fscache to read source code when showing snippets.\n        self.read_source = read_source\n        self.initialize()\n\n    def initialize(self) -> None:\n        self.error_info_map = {}\n        self.flushed_files = set()\n        self.import_ctx = []\n        self.function_or_member = [None]\n        self.ignored_lines = {}\n        self.skipped_lines = {}\n        self.used_ignored_lines = defaultdict(lambda: defaultdict(list))\n        self.ignored_files = set()\n        self.only_once_messages = set()\n        self.has_blockers = set()\n        self.scope = None\n        self.target_module = None\n        self.seen_import_error = False\n        self._watchers = []\n        self.global_watcher = False\n        self.recorded = defaultdict(list)\n\n    def reset(self) -> None:\n        self.initialize()\n\n    def set_ignore_prefix(self, prefix: str) -> None:\n        \"\"\"Set path prefix that will be removed from all paths.\"\"\"\n        prefix = os.path.normpath(prefix)\n        # Add separator to the end, if not given.\n        if os.path.basename(prefix) != \"\":\n            prefix += os.sep\n        self.ignore_prefix = prefix\n\n    def simplify_path(self, file: str) -> str:\n        if self.options.show_absolute_path:\n            return os.path.abspath(file)\n        else:\n            file = os.path.normpath(file)\n            return remove_path_prefix(file, self.ignore_prefix)\n\n    def set_file(\n        self, file: str, module: str | None, options: Options, scope: Scope | None = None\n    ) -> None:\n        \"\"\"Set the path and module id of the current file.\"\"\"\n        # The path will be simplified later, in render_messages. That way\n        #  * 'file' is always a key that uniquely identifies a source file\n        #    that mypy read (simplified paths might not be unique); and\n        #  * we only have to simplify in one place, while still supporting\n        #    reporting errors for files other than the one currently being\n        #    processed.\n        self.file = file\n        self.target_module = module\n        self.scope = scope\n        self.options = options\n\n    def set_file_ignored_lines(\n        self, file: str, ignored_lines: dict[int, list[str]], ignore_all: bool = False\n    ) -> None:\n        self.ignored_lines[file] = ignored_lines\n        if ignore_all:\n            self.ignored_files.add(file)\n\n    def set_skipped_lines(self, file: str, skipped_lines: set[int]) -> None:\n        self.skipped_lines[file] = skipped_lines\n\n    def current_target(self) -> str | None:\n        \"\"\"Retrieves the current target from the associated scope.\n\n        If there is no associated scope, use the target module.\"\"\"\n        if self.scope is not None:\n            return self.scope.current_target()\n        return self.target_module\n\n    def current_module(self) -> str | None:\n        return self.target_module\n\n    def import_context(self) -> list[tuple[str, int]]:\n        \"\"\"Return a copy of the import context.\"\"\"\n        return self.import_ctx.copy()\n\n    def set_import_context(self, ctx: list[tuple[str, int]]) -> None:\n        \"\"\"Replace the entire import context with a new value.\"\"\"\n        self.import_ctx = ctx.copy()\n\n    def report(\n        self,\n        line: int,\n        column: int | None,\n        message: str,\n        code: ErrorCode | None = None,\n        *,\n        blocker: bool = False,\n        severity: str = \"error\",\n        only_once: bool = False,\n        origin_span: Iterable[int] | None = None,\n        offset: int = 0,\n        end_line: int | None = None,\n        end_column: int | None = None,\n        parent_error: ErrorInfo | None = None,\n    ) -> ErrorInfo:\n        \"\"\"Report message at the given line using the current error context.\n\n        Args:\n            line: line number of error\n            column: column number of error\n            message: message to report\n            code: error code (defaults to 'misc'; not shown for notes)\n            blocker: if True, don't continue analysis after this error\n            severity: 'error' or 'note'\n            only_once: if True, only report this exact message once per build\n            origin_span: lines where `type: ignore`s have effect for this error\n                (default is [line])\n            offset: number of spaces to prefix this message\n            end_line: if known, end line of error location\n            end_column: if known, end column of error location\n            parent_error: an error this note is attached to (for notes only).\n        \"\"\"\n        if self.scope:\n            type = self.scope.current_type_name()\n            if self.scope.ignored > 0:\n                type = None  # Omit type context if nested function\n            function = self.scope.current_function_name()\n        else:\n            type = None\n            function = None\n\n        # It looks like there is a bug in how we parse f-strings,\n        # we cannot simply assert this yet.\n        if end_line is None or end_line < line:\n            end_line = line\n\n        if column is None:\n            column = -1\n        if end_column is None:\n            if column == -1:\n                end_column = -1\n            else:\n                end_column = column + 1\n        if line == end_line and end_column <= column:\n            # Be defensive, similar to the logic for lines above.\n            end_column = column + 1\n\n        if offset:\n            message = \" \" * offset + message\n\n        code = code or (parent_error.code if parent_error else None)\n        if parent_error is not None:\n            assert code == parent_error.code, \"Must have same error code as parent\"\n            assert severity == \"note\", \"Only notes can have parent errors\"\n        code = code or (codes.MISC if not blocker else None)\n\n        info = ErrorInfo(\n            import_ctx=self.import_context(),\n            local_ctx=(type, function),\n            line=line,\n            column=column,\n            end_line=end_line,\n            end_column=end_column,\n            severity=severity,\n            message=message,\n            code=code,\n            blocker=blocker,\n            only_once=only_once,\n            origin_span=origin_span,\n            module=self.current_module(),\n            target=self.current_target(),\n            parent_error=parent_error,\n        )\n        if self.global_watcher:\n            self.recorded[self.file].append(info)\n        self.add_error_info(info)\n        return info\n\n    def _add_error_info(self, file: str, info: ErrorInfo) -> None:\n        assert file not in self.flushed_files\n        # process the stack of ErrorWatchers before modifying any internal state\n        # in case we need to filter out the error entirely\n        if self._filter_error(file, info):\n            return\n        if file not in self.error_info_map:\n            self.error_info_map[file] = []\n        self.error_info_map[file].append(info)\n        if info.blocker:\n            self.has_blockers.add(file)\n        if info.code in (IMPORT, IMPORT_UNTYPED, IMPORT_NOT_FOUND):\n            self.seen_import_error = True\n\n    def note_for_info(\n        self,\n        file: str,\n        info: ErrorInfo,\n        message: str,\n        code: ErrorCode | None,\n        *,\n        only_once: bool = False,\n        priority: int = 0,\n    ) -> None:\n        \"\"\"Generate an additional note for an existing ErrorInfo.\n\n        This skip the logic in add_error_info() and goes to _add_error_info().\n        \"\"\"\n        info = ErrorInfo(\n            import_ctx=info.import_ctx,\n            local_ctx=info.local_ctx,\n            line=info.line,\n            column=info.column,\n            end_line=info.end_line,\n            end_column=info.end_column,\n            severity=\"note\",\n            message=message,\n            code=code,\n            blocker=False,\n            only_once=only_once,\n            module=info.module,\n            target=info.target,\n            origin_span=info.origin_span,\n            priority=priority,\n        )\n        self._add_error_info(file, info)\n\n    def report_simple_error(\n        self, file: str, line: int, message: str, code: ErrorCode | None\n    ) -> None:\n        \"\"\"Generate a simple error in a module.\n\n        This skip the logic in add_error_info() and goes to _add_error_info().\n        \"\"\"\n        info = ErrorInfo(\n            import_ctx=self.import_context(),\n            local_ctx=(None, None),\n            line=line,\n            column=-1,\n            end_line=line,\n            end_column=-1,\n            severity=\"error\",\n            message=message,\n            code=code,\n            blocker=False,\n            only_once=False,\n            module=self.current_module(),\n            # TODO: can we support more precise targets?\n            target=self.target_module,\n        )\n        self._add_error_info(file, info)\n\n    def get_watchers(self) -> Iterator[ErrorWatcher]:\n        \"\"\"Yield the `ErrorWatcher` stack from top to bottom.\"\"\"\n        i = len(self._watchers)\n        while i > 0:\n            i -= 1\n            yield self._watchers[i]\n\n    def _filter_error(self, file: str, info: ErrorInfo) -> bool:\n        \"\"\"\n        process ErrorWatcher stack from top to bottom,\n        stopping early if error needs to be filtered out\n        \"\"\"\n        return any(w.on_error(file, info) for w in self.get_watchers())\n\n    def add_error_info(self, info: ErrorInfo, *, file: str | None = None) -> None:\n        lines = info.origin_span\n        file = file or self.file\n        # process the stack of ErrorWatchers before modifying any internal state\n        # in case we need to filter out the error entirely\n        # NB: we need to do this both here and in _add_error_info, otherwise we\n        # might incorrectly update the sets of ignored or only_once messages\n        if self._filter_error(file, info):\n            return\n        if not info.blocker:  # Blockers cannot be ignored\n            if file in self.ignored_lines:\n                # Check each line in this context for \"type: ignore\" comments.\n                # line == end_line for most nodes, so we only loop once.\n                for scope_line in lines:\n                    if self.is_ignored_error(scope_line, info, self.ignored_lines[file]):\n                        err_code = info.code or codes.MISC\n                        if not self.is_error_code_enabled(err_code):\n                            # Error code is disabled - don't mark the current\n                            # \"type: ignore\" comment as used.\n                            return\n                        # Annotation requests us to ignore all errors on this line.\n                        self.used_ignored_lines[file][scope_line].append(err_code.code)\n                        return\n            if file in self.ignored_files:\n                return\n        if info.only_once:\n            if info.message in self.only_once_messages:\n                return\n            self.only_once_messages.add(info.message)\n        if (\n            self.seen_import_error\n            and info.code not in (IMPORT, IMPORT_UNTYPED, IMPORT_NOT_FOUND)\n            and self.has_many_errors()\n        ):\n            # Missing stubs can easily cause thousands of errors about\n            # Any types, especially when upgrading to mypy 0.900,\n            # which no longer bundles third-party library stubs. Avoid\n            # showing too many errors to make it easier to see\n            # import-related errors.\n            info.hidden = True\n            self.report_hidden_errors(file, info)\n        self._add_error_info(file, info)\n        ignored_codes = self.ignored_lines.get(file, {}).get(info.line, [])\n        if ignored_codes and info.code:\n            # Something is ignored on the line, but not this error, so maybe the error\n            # code is incorrect.\n            msg = f'Error code \"{info.code.code}\" not covered by \"type: ignore\" comment'\n            if info.code in original_error_codes:\n                # If there seems to be a \"type: ignore\" with a stale error\n                # code, report a more specific note.\n                old_code = original_error_codes[info.code].code\n                if old_code in ignored_codes:\n                    msg = (\n                        f'Error code changed to {info.code.code}; \"type: ignore\" comment '\n                        + \"may be out of date\"\n                    )\n            self.note_for_info(file, info, msg, None, only_once=False)\n        if (\n            self.options.show_error_code_links\n            and not self.options.hide_error_codes\n            and info.code is not None\n            and info.code not in HIDE_LINK_CODES\n            and info.code.code in mypy_error_codes\n        ):\n            message = f\"See {BASE_RTD_URL}-{info.code.code} for more info\"\n            if message in self.only_once_messages:\n                return\n            self.only_once_messages.add(message)\n            self.note_for_info(file, info, message, info.code, only_once=True, priority=20)\n\n    def has_many_errors(self) -> bool:\n        if self.options.many_errors_threshold < 0:\n            return False\n        if len(self.error_info_map) >= self.options.many_errors_threshold:\n            return True\n        if (\n            sum(len(errors) for errors in self.error_info_map.values())\n            >= self.options.many_errors_threshold\n        ):\n            return True\n        return False\n\n    def report_hidden_errors(self, file: str, info: ErrorInfo) -> None:\n        message = (\n            \"(Skipping most remaining errors due to unresolved imports or missing stubs; \"\n            + \"fix these first)\"\n        )\n        if message in self.only_once_messages:\n            return\n        self.only_once_messages.add(message)\n        self.note_for_info(file, info, message, None, only_once=True)\n\n    def is_ignored_error(self, line: int, info: ErrorInfo, ignores: dict[int, list[str]]) -> bool:\n        if info.blocker:\n            # Blocking errors can never be ignored\n            return False\n        if info.code and not self.is_error_code_enabled(info.code):\n            return True\n        if line not in ignores:\n            return False\n        if not ignores[line]:\n            # Empty list means that we ignore all errors\n            return True\n        if info.code and self.is_error_code_enabled(info.code):\n            return (\n                info.code.code in ignores[line]\n                or info.code.sub_code_of is not None\n                and info.code.sub_code_of.code in ignores[line]\n            )\n        return False\n\n    def is_error_code_enabled(self, error_code: ErrorCode) -> bool:\n        if self.options:\n            current_mod_disabled = self.options.disabled_error_codes\n            current_mod_enabled = self.options.enabled_error_codes\n        else:\n            current_mod_disabled = set()\n            current_mod_enabled = set()\n\n        if error_code in current_mod_disabled:\n            return False\n        elif error_code in current_mod_enabled:\n            return True\n        elif error_code.sub_code_of is not None and error_code.sub_code_of in current_mod_disabled:\n            return False\n        else:\n            return error_code.default_enabled\n\n    def clear_errors_in_targets(self, path: str, targets: set[str]) -> None:\n        \"\"\"Remove errors in specific fine-grained targets within a file.\"\"\"\n        if path in self.error_info_map:\n            new_errors = []\n            has_blocker = False\n            for info in self.error_info_map[path]:\n                if info.target not in targets:\n                    new_errors.append(info)\n                    has_blocker |= info.blocker\n                elif info.only_once:\n                    self.only_once_messages.remove(info.message)\n            self.error_info_map[path] = new_errors\n            if not has_blocker and path in self.has_blockers:\n                self.has_blockers.remove(path)\n\n    def generate_unused_ignore_errors(self, file: str, is_typeshed: bool = False) -> None:\n        if is_typeshed or file in self.ignored_files:\n            return\n        ignored_lines = self.ignored_lines[file]\n        used_ignored_lines = self.used_ignored_lines[file]\n        for line, ignored_codes in ignored_lines.items():\n            if line in self.skipped_lines[file]:\n                continue\n            if codes.UNUSED_IGNORE.code in ignored_codes:\n                continue\n            used_ignored_codes = set(used_ignored_lines[line])\n            unused_ignored_codes = [c for c in ignored_codes if c not in used_ignored_codes]\n            # `ignore` is used\n            if not ignored_codes and used_ignored_codes:\n                continue\n            # All codes appearing in `ignore[...]` are used\n            if ignored_codes and not unused_ignored_codes:\n                continue\n            # Display detail only when `ignore[...]` specifies more than one error code\n            unused_codes_message = \"\"\n            if len(ignored_codes) > 1 and unused_ignored_codes:\n                unused_codes_message = f\"[{', '.join(unused_ignored_codes)}]\"\n            message = f'Unused \"type: ignore{unused_codes_message}\" comment'\n            for unused in unused_ignored_codes:\n                narrower = set(used_ignored_codes) & codes.sub_code_map[unused]\n                if narrower:\n                    message += f\", use narrower [{', '.join(narrower)}] instead of [{unused}] code\"\n            # Don't use report() since add_error_info will ignore the error!\n            self.report_simple_error(file, line, message, code=codes.UNUSED_IGNORE)\n\n    def generate_ignore_without_code_errors(\n        self, file: str, is_warning_unused_ignores: bool, is_typeshed: bool = False\n    ) -> None:\n        if is_typeshed or file in self.ignored_files:\n            return\n\n        used_ignored_lines = self.used_ignored_lines[file]\n        for line, ignored_codes in self.ignored_lines[file].items():\n            if line in self.skipped_lines[file]:\n                continue\n            if ignored_codes:\n                continue\n\n            # If the `type: ignore` is itself unused and that would be warned about,\n            # let that error stand alone\n            if is_warning_unused_ignores and not used_ignored_lines[line]:\n                continue\n\n            codes_hint = \"\"\n            ignored_codes = sorted(set(used_ignored_lines[line]))\n            if ignored_codes:\n                codes_hint = f' (consider \"type: ignore[{\", \".join(ignored_codes)}]\" instead)'\n\n            message = f'\"type: ignore\" comment without error code{codes_hint}'\n            # Don't use report() since add_error_info will ignore the error!\n            self.report_simple_error(file, line, message, code=codes.IGNORE_WITHOUT_CODE)\n\n    def num_messages(self) -> int:\n        \"\"\"Return the number of generated messages.\"\"\"\n        return sum(len(x) for x in self.error_info_map.values())\n\n    def is_errors(self) -> bool:\n        \"\"\"Are there any generated messages?\"\"\"\n        return bool(self.error_info_map)\n\n    def is_blockers(self) -> bool:\n        \"\"\"Are the any errors that are blockers?\"\"\"\n        return bool(self.has_blockers)\n\n    def blocker_module(self) -> str | None:\n        \"\"\"Return the module with a blocking error, or None if not possible.\"\"\"\n        for path in self.has_blockers:\n            for err in self.error_info_map[path]:\n                if err.blocker:\n                    return err.module\n        return None\n\n    def is_errors_for_file(self, file: str) -> bool:\n        \"\"\"Are there any errors for the given file?\"\"\"\n        return file in self.error_info_map and file not in self.ignored_files\n\n    def prefer_simple_messages(self) -> bool:\n        \"\"\"Should we generate simple/fast error messages?\n\n        Return True if errors are not shown to user, i.e. errors are ignored\n        or they are collected for internal use only.\n\n        If True, we should prefer to generate a simple message quickly.\n        All normal errors should still be reported.\n        \"\"\"\n        if self.file in self.ignored_files:\n            # Errors ignored, so no point generating fancy messages\n            return True\n        if self.options.ignore_errors:\n            return True\n        if self._watchers:\n            _watcher = self._watchers[-1]\n            if _watcher._filter is True and _watcher._filtered is None:\n                # Errors are filtered\n                return True\n        return False\n\n    def raise_error(self, use_stdout: bool = True) -> NoReturn:\n        \"\"\"Raise a CompileError with the generated messages.\n\n        Render the messages suitable for displaying.\n        \"\"\"\n        # self.new_messages() will format all messages that haven't already\n        # been returned from a file_messages() call.\n        raise CompileError(\n            self.new_messages(), use_stdout=use_stdout, module_with_blocker=self.blocker_module()\n        )\n\n    def format_messages_default(\n        self, error_tuples: list[ErrorTuple], source_lines: list[str] | None\n    ) -> list[str]:\n        \"\"\"Return a string list that represents the error messages.\n\n        Use a form suitable for displaying to the user. If self.pretty\n        is True also append a relevant trimmed source code line (only for\n        severity 'error').\n        \"\"\"\n        a: list[str] = []\n        for file, line, column, end_line, end_column, severity, message, code in error_tuples:\n            s = \"\"\n            if file is not None:\n                if self.options.show_column_numbers and line >= 0 and column >= 0:\n                    srcloc = f\"{file}:{line}:{1 + column}\"\n                    if self.options.show_error_end and end_line >= 0 and end_column >= 0:\n                        srcloc += f\":{end_line}:{end_column}\"\n                elif line >= 0:\n                    srcloc = f\"{file}:{line}\"\n                else:\n                    srcloc = file\n                s = f\"{srcloc}: {severity}: {message}\"\n            else:\n                s = message\n            if (\n                not self.hide_error_codes\n                and code\n                and (severity != \"note\" or code in SHOW_NOTE_CODES)\n            ):\n                # If note has an error code, it is related to a previous error. Avoid\n                # displaying duplicate error codes.\n                s = f\"{s}  [{code}]\"\n            a.append(s)\n            if self.options.pretty:\n                # Add source code fragment and a location marker.\n                if severity == \"error\" and source_lines and line > 0:\n                    source_line = source_lines[line - 1]\n                    source_line_expanded = source_line.expandtabs()\n                    min_column = len(source_line) - len(source_line.lstrip())\n                    if column < min_column:\n                        # Something went wrong, take first non-empty column.\n                        column = min_column\n\n                    # Shifts column after tab expansion\n                    column = len(source_line[:column].expandtabs())\n                    end_column = len(source_line[:end_column].expandtabs())\n\n                    # Note, currently coloring uses the offset to detect source snippets,\n                    # so these offsets should not be arbitrary.\n                    a.append(\" \" * DEFAULT_SOURCE_OFFSET + source_line_expanded)\n                    marker = \"^\"\n                    if end_line == line and end_column > column:\n                        marker = f'^{\"~\" * (end_column - column - 1)}'\n                    elif end_line != line:\n                        # just highlight the first line instead\n                        marker = f'^{\"~\" * (len(source_line_expanded) - column - 1)}'\n                    a.append(\" \" * (DEFAULT_SOURCE_OFFSET + column) + marker)\n        return a\n\n    def file_messages(self, path: str) -> list[ErrorTuple]:\n        \"\"\"Return an error tuple list of new error messages from a given file.\"\"\"\n        if path not in self.error_info_map:\n            return []\n\n        error_info = self.error_info_map[path]\n        error_info = [info for info in error_info if not info.hidden]\n        error_info = self.remove_duplicates(self.sort_messages(error_info))\n        return self.render_messages(path, error_info)\n\n    def format_messages(\n        self, path: str, error_tuples: list[ErrorTuple], formatter: ErrorFormatter | None = None\n    ) -> list[str]:\n        \"\"\"Return a string list of new error messages from a given file.\n\n        Use a form suitable for displaying to the user.\n        \"\"\"\n        self.flushed_files.add(path)\n        if formatter is not None:\n            errors = create_errors(error_tuples)\n            return [formatter.report_error(err) for err in errors]\n\n        source_lines = None\n        if self.options.pretty and self.read_source:\n            # Find shadow file mapping and read source lines if a shadow file exists for the given path.\n            # If shadow file mapping is not found, read source lines\n            mapped_path = self.find_shadow_file_mapping(path)\n            if mapped_path:\n                source_lines = self.read_source(mapped_path)\n            else:\n                source_lines = self.read_source(path)\n        return self.format_messages_default(error_tuples, source_lines)\n\n    def find_shadow_file_mapping(self, path: str) -> str | None:\n        \"\"\"Return the shadow file path for a given source file path or None.\"\"\"\n        if self.options.shadow_file is None:\n            return None\n\n        for i in self.options.shadow_file:\n            if i[0] == path:\n                return i[1]\n        return None\n\n    def new_messages(self) -> list[str]:\n        \"\"\"Return a string list of new error messages.\n\n        Use a form suitable for displaying to the user.\n        Errors from different files are ordered based on the order in which\n        they first generated an error.\n        \"\"\"\n        msgs = []\n        for path in self.error_info_map.keys():\n            if path not in self.flushed_files:\n                error_tuples = self.file_messages(path)\n                msgs.extend(self.format_messages(path, error_tuples))\n        return msgs\n\n    def targets(self) -> set[str]:\n        \"\"\"Return a set of all targets that contain errors.\"\"\"\n        # TODO: Make sure that either target is always defined or that not being defined\n        #       is okay for fine-grained incremental checking.\n        return {\n            info.target for errs in self.error_info_map.values() for info in errs if info.target\n        }\n\n    def render_messages(self, file: str, errors: list[ErrorInfo]) -> list[ErrorTuple]:\n        \"\"\"Translate the messages into a sequence of tuples.\n\n        Each tuple is of form (path, line, col, severity, message, code).\n        The rendered sequence includes information about error contexts.\n        The path item may be None. If the line item is negative, the\n        line number is not defined for the tuple.\n        \"\"\"\n        file = self.simplify_path(file)\n        result: list[ErrorTuple] = []\n        prev_import_context: list[tuple[str, int]] = []\n        prev_function: str | None = None\n        prev_type: str | None = None\n\n        for e in errors:\n            # Report module import context, if different from previous message.\n            if not self.options.show_error_context:\n                pass\n            elif e.import_ctx != prev_import_context:\n                last = len(e.import_ctx) - 1\n                i = last\n                while i >= 0:\n                    path, line = e.import_ctx[i]\n                    fmt = \"{}:{}: note: In module imported here\"\n                    if i < last:\n                        fmt = \"{}:{}: note: ... from here\"\n                    if i > 0:\n                        fmt += \",\"\n                    else:\n                        fmt += \":\"\n                    # Remove prefix to ignore from path (if present) to\n                    # simplify path.\n                    path = remove_path_prefix(path, self.ignore_prefix)\n                    result.append((None, -1, -1, -1, -1, \"note\", fmt.format(path, line), None))\n                    i -= 1\n\n            # Report context within a source file.\n            type, function = e.local_ctx\n            if not self.options.show_error_context:\n                pass\n            elif function != prev_function or type != prev_type:\n                if function is None:\n                    if type is None:\n                        result.append((file, -1, -1, -1, -1, \"note\", \"At top level:\", None))\n                    else:\n                        result.append((file, -1, -1, -1, -1, \"note\", f'In class \"{type}\":', None))\n                else:\n\n                    if type is None:\n                        msg = f'In function \"{function}\":'\n                    else:\n                        msg = 'In member \"{}\" of class \"{}\":'.format(function, type)\n                    result.append((file, -1, -1, -1, -1, \"note\", msg, None))\n\n            elif type != prev_type:\n                if type is None:\n                    result.append((file, -1, -1, -1, -1, \"note\", \"At top level:\", None))\n                else:\n                    result.append((file, -1, -1, -1, -1, \"note\", f'In class \"{type}\":', None))\n\n            code = e.code.code if e.code is not None else None\n            result.append(\n                (file, e.line, e.column, e.end_line, e.end_column, e.severity, e.message, code)\n            )\n\n            prev_import_context = e.import_ctx\n            prev_function = function\n            prev_type = type\n\n        return result\n\n    def sort_messages(self, errors: list[ErrorInfo]) -> list[ErrorInfo]:\n        \"\"\"Sort an array of error messages locally by line number.\n\n        I.e., sort a run of consecutive messages with the same\n        context by line number, but otherwise retain the general\n        ordering of the messages.\n        \"\"\"\n        result: list[ErrorInfo] = []\n        i = 0\n        while i < len(errors):\n            i0 = i\n            # Find neighbouring errors with the same context and file.\n            while i + 1 < len(errors) and errors[i + 1].import_ctx == errors[i].import_ctx:\n                i += 1\n            i += 1\n\n            # Sort the errors specific to a file according to line number and column.\n            a = sorted(errors[i0:i], key=lambda x: (x.line, x.column))\n            a = self.sort_within_context(a)\n            result.extend(a)\n        return result\n\n    def sort_within_context(self, errors: list[ErrorInfo]) -> list[ErrorInfo]:\n        \"\"\"For the same location decide which messages to show first/last.\n\n        Currently, we only compare within the same error code, to decide the\n        order of various additional notes.\n        \"\"\"\n        result = []\n        i = 0\n        while i < len(errors):\n            i0 = i\n            # Find neighbouring errors with the same position and error code.\n            while (\n                i + 1 < len(errors)\n                and errors[i + 1].line == errors[i].line\n                and errors[i + 1].column == errors[i].column\n                and errors[i + 1].end_line == errors[i].end_line\n                and errors[i + 1].end_column == errors[i].end_column\n                and errors[i + 1].code == errors[i].code\n            ):\n                i += 1\n            i += 1\n\n            # Sort the messages specific to a given error by priority.\n            a = sorted(errors[i0:i], key=lambda x: x.priority)\n            result.extend(a)\n        return result\n\n    def remove_duplicates(self, errors: list[ErrorInfo]) -> list[ErrorInfo]:\n        filtered_errors = []\n        seen_by_line: defaultdict[int, set[tuple[str, str]]] = defaultdict(set)\n        removed = set()\n        for err in errors:\n            if err.parent_error is not None:\n                # Notes with specified parent are removed together with error below.\n                filtered_errors.append(err)\n            elif (err.severity, err.message) not in seen_by_line[err.line]:\n                filtered_errors.append(err)\n                seen_by_line[err.line].add((err.severity, err.message))\n            else:\n                removed.add(err)\n        return [\n            err\n            for err in filtered_errors\n            if err.parent_error is None or err.parent_error not in removed\n        ]\n\n\nclass CompileError(Exception):\n    \"\"\"Exception raised when there is a compile error.\n\n    It can be a parse, semantic analysis, type check or other\n    compilation-related error.\n\n    CompileErrors raised from an errors object carry all of the\n    messages that have not been reported out by error streaming.\n    This is patched up by build.build to contain either all error\n    messages (if errors were streamed) or none (if they were not).\n\n    \"\"\"\n\n    messages: list[str]\n    use_stdout = False\n    # Can be set in case there was a module with a blocking error\n    module_with_blocker: str | None = None\n\n    def __init__(\n        self, messages: list[str], use_stdout: bool = False, module_with_blocker: str | None = None\n    ) -> None:\n        super().__init__(\"\\n\".join(messages))\n        self.messages = messages\n        self.use_stdout = use_stdout\n        self.module_with_blocker = module_with_blocker\n\n\ndef remove_path_prefix(path: str, prefix: str | None) -> str:\n    \"\"\"If path starts with prefix, return copy of path with the prefix removed.\n    Otherwise, return path. If path is None, return None.\n    \"\"\"\n    if prefix is not None and path.startswith(prefix):\n        return path[len(prefix) :]\n    else:\n        return path\n\n\ndef report_internal_error(\n    err: Exception,\n    file: str | None,\n    line: int,\n    errors: Errors | None,\n    options: Options,\n    stdout: TextIO | None = None,\n    stderr: TextIO | None = None,\n) -> NoReturn:\n    \"\"\"Report internal error and exit.\n\n    This optionally starts pdb or shows a traceback.\n    \"\"\"\n    stdout = stdout or sys.stdout\n    stderr = stderr or sys.stderr\n    # Dump out errors so far, they often provide a clue.\n    # But catch unexpected errors rendering them.\n    if errors:\n        try:\n            for msg in errors.new_messages():\n                print(msg)\n        except Exception as e:\n            print(\"Failed to dump errors:\", repr(e), file=stderr)\n\n    # Compute file:line prefix for official-looking error messages.\n    if file:\n        if line:\n            prefix = f\"{file}:{line}: \"\n        else:\n            prefix = f\"{file}: \"\n    else:\n        prefix = \"\"\n\n    # Print \"INTERNAL ERROR\" message.\n    print(\n        f\"{prefix}error: INTERNAL ERROR --\",\n        \"Please try using mypy master on GitHub:\\n\"\n        \"https://mypy.readthedocs.io/en/stable/common_issues.html\"\n        \"#using-a-development-mypy-build\",\n        file=stderr,\n    )\n    if options.show_traceback:\n        print(\"Please report a bug at https://github.com/python/mypy/issues\", file=stderr)\n    else:\n        print(\n            \"If this issue continues with mypy master, \"\n            \"please report a bug at https://github.com/python/mypy/issues\",\n            file=stderr,\n        )\n    print(f\"version: {mypy_version}\", file=stderr)\n\n    # If requested, drop into pdb. This overrides show_tb.\n    if options.pdb:\n        print(\"Dropping into pdb\", file=stderr)\n        import pdb\n\n        pdb.post_mortem(sys.exc_info()[2])\n\n    # If requested, print traceback, else print note explaining how to get one.\n    if options.raise_exceptions:\n        raise err\n    if not options.show_traceback:\n        if not options.pdb:\n            print(\n                \"{}note: please use --show-traceback to print a traceback \"\n                \"when reporting a bug\".format(prefix),\n                file=stderr,\n            )\n    else:\n        tb = traceback.extract_stack()[:-2]\n        tb2 = traceback.extract_tb(sys.exc_info()[2])\n        print(\"Traceback (most recent call last):\")\n        for s in traceback.format_list(tb + tb2):\n            print(s.rstrip(\"\\n\"))\n        print(f\"{type(err).__name__}: {err}\", file=stdout)\n        print(f\"{prefix}note: use --pdb to drop into pdb\", file=stderr)\n\n    # Exit.  The caller has nothing more to say.\n    # We use exit code 2 to signal that this is no ordinary error.\n    raise SystemExit(2)\n\n\nclass MypyError:\n    def __init__(\n        self,\n        file_path: str,\n        line: int,\n        column: int,\n        end_line: int,\n        end_column: int,\n        message: str,\n        errorcode: str | None,\n        severity: Literal[\"error\", \"note\"],\n    ) -> None:\n        self.file_path = file_path\n        self.line = line\n        self.column = column\n        self.end_line = end_line\n        self.end_column = end_column\n        self.message = message\n        self.errorcode = errorcode\n        self.severity = severity\n        self.hints: list[str] = []\n\n\n# (file_path, line, column)\n_ErrorLocation = tuple[str, int, int]\n\n\ndef create_errors(error_tuples: list[ErrorTuple]) -> list[MypyError]:\n    errors: list[MypyError] = []\n    latest_error_at_location: dict[_ErrorLocation, MypyError] = {}\n\n    for error_tuple in error_tuples:\n        file_path, line, column, end_line, end_column, severity, message, errorcode = error_tuple\n        if file_path is None:\n            continue\n\n        assert severity in (\"error\", \"note\")\n        if severity == \"note\":\n            error_location = (file_path, line, column)\n            error = latest_error_at_location.get(error_location)\n            if error is None:\n                # This is purely a note, with no error correlated to it\n                error = MypyError(\n                    file_path,\n                    line,\n                    column,\n                    end_line,\n                    end_column,\n                    message,\n                    errorcode,\n                    severity=\"note\",\n                )\n                errors.append(error)\n                continue\n\n            error.hints.append(message)\n\n        else:\n            error = MypyError(\n                file_path, line, column, end_line, end_column, message, errorcode, severity=\"error\"\n            )\n            errors.append(error)\n            error_location = (file_path, line, column)\n            latest_error_at_location[error_location] = error\n\n    return errors\n"
  },
  {
    "path": "mypy/evalexpr.py",
    "content": "\"\"\"\n\nEvaluate an expression.\n\nUsed by stubtest; in a separate file because things break if we don't\nput it in a mypyc-compiled file.\n\n\"\"\"\n\nimport ast\nfrom typing import Final\n\nimport mypy.nodes\nfrom mypy.visitor import ExpressionVisitor\n\nUNKNOWN = object()\n\n\nclass _NodeEvaluator(ExpressionVisitor[object]):\n    def visit_int_expr(self, o: mypy.nodes.IntExpr) -> int:\n        return o.value\n\n    def visit_str_expr(self, o: mypy.nodes.StrExpr) -> str:\n        return o.value\n\n    def visit_bytes_expr(self, o: mypy.nodes.BytesExpr) -> object:\n        # The value of a BytesExpr is a string created from the repr()\n        # of the bytes object. Get the original bytes back.\n        try:\n            return ast.literal_eval(f\"b'{o.value}'\")\n        except SyntaxError:\n            return ast.literal_eval(f'b\"{o.value}\"')\n\n    def visit_float_expr(self, o: mypy.nodes.FloatExpr) -> float:\n        return o.value\n\n    def visit_complex_expr(self, o: mypy.nodes.ComplexExpr) -> object:\n        return o.value\n\n    def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr) -> object:\n        return Ellipsis\n\n    def visit_star_expr(self, o: mypy.nodes.StarExpr) -> object:\n        return UNKNOWN\n\n    def visit_name_expr(self, o: mypy.nodes.NameExpr) -> object:\n        if o.name == \"True\":\n            return True\n        elif o.name == \"False\":\n            return False\n        elif o.name == \"None\":\n            return None\n        # TODO: Handle more names by figuring out a way to hook into the\n        # symbol table.\n        return UNKNOWN\n\n    def visit_member_expr(self, o: mypy.nodes.MemberExpr) -> object:\n        return UNKNOWN\n\n    def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr) -> object:\n        return UNKNOWN\n\n    def visit_yield_expr(self, o: mypy.nodes.YieldExpr) -> object:\n        return UNKNOWN\n\n    def visit_call_expr(self, o: mypy.nodes.CallExpr) -> object:\n        return UNKNOWN\n\n    def visit_op_expr(self, o: mypy.nodes.OpExpr) -> object:\n        return UNKNOWN\n\n    def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr) -> object:\n        return UNKNOWN\n\n    def visit_cast_expr(self, o: mypy.nodes.CastExpr) -> object:\n        return o.expr.accept(self)\n\n    def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr) -> object:\n        return UNKNOWN\n\n    def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr) -> object:\n        return o.expr.accept(self)\n\n    def visit_reveal_expr(self, o: mypy.nodes.RevealExpr) -> object:\n        return UNKNOWN\n\n    def visit_super_expr(self, o: mypy.nodes.SuperExpr) -> object:\n        return UNKNOWN\n\n    def visit_unary_expr(self, o: mypy.nodes.UnaryExpr) -> object:\n        operand = o.expr.accept(self)\n        if operand is UNKNOWN:\n            return UNKNOWN\n        if o.op == \"-\":\n            if isinstance(operand, (int, float, complex)):\n                return -operand\n        elif o.op == \"+\":\n            if isinstance(operand, (int, float, complex)):\n                return +operand\n        elif o.op == \"~\":\n            if isinstance(operand, int):\n                return ~operand\n        elif o.op == \"not\":\n            if isinstance(operand, (bool, int, float, str, bytes)):\n                return not operand\n        return UNKNOWN\n\n    def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr) -> object:\n        return o.value.accept(self)\n\n    def visit_list_expr(self, o: mypy.nodes.ListExpr) -> object:\n        items = [item.accept(self) for item in o.items]\n        if all(item is not UNKNOWN for item in items):\n            return items\n        return UNKNOWN\n\n    def visit_dict_expr(self, o: mypy.nodes.DictExpr) -> object:\n        items = [\n            (UNKNOWN if key is None else key.accept(self), value.accept(self))\n            for key, value in o.items\n        ]\n        if all(key is not UNKNOWN and value is not None for key, value in items):\n            return dict(items)\n        return UNKNOWN\n\n    def visit_tuple_expr(self, o: mypy.nodes.TupleExpr) -> object:\n        items = [item.accept(self) for item in o.items]\n        if all(item is not UNKNOWN for item in items):\n            return tuple(items)\n        return UNKNOWN\n\n    def visit_set_expr(self, o: mypy.nodes.SetExpr) -> object:\n        items = [item.accept(self) for item in o.items]\n        if all(item is not UNKNOWN for item in items):\n            return set(items)\n        return UNKNOWN\n\n    def visit_index_expr(self, o: mypy.nodes.IndexExpr) -> object:\n        return UNKNOWN\n\n    def visit_type_application(self, o: mypy.nodes.TypeApplication) -> object:\n        return UNKNOWN\n\n    def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr) -> object:\n        return UNKNOWN\n\n    def visit_list_comprehension(self, o: mypy.nodes.ListComprehension) -> object:\n        return UNKNOWN\n\n    def visit_set_comprehension(self, o: mypy.nodes.SetComprehension) -> object:\n        return UNKNOWN\n\n    def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension) -> object:\n        return UNKNOWN\n\n    def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr) -> object:\n        return UNKNOWN\n\n    def visit_slice_expr(self, o: mypy.nodes.SliceExpr) -> object:\n        return UNKNOWN\n\n    def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr) -> object:\n        return UNKNOWN\n\n    def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr) -> object:\n        return UNKNOWN\n\n    def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr) -> object:\n        return UNKNOWN\n\n    def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr) -> object:\n        return UNKNOWN\n\n    def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr) -> object:\n        return UNKNOWN\n\n    def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr) -> object:\n        return UNKNOWN\n\n    def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr) -> object:\n        return UNKNOWN\n\n    def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr) -> object:\n        return UNKNOWN\n\n    def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr) -> object:\n        return UNKNOWN\n\n    def visit__promote_expr(self, o: mypy.nodes.PromoteExpr) -> object:\n        return UNKNOWN\n\n    def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> object:\n        return UNKNOWN\n\n    def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr) -> object:\n        return UNKNOWN\n\n    def visit_temp_node(self, o: mypy.nodes.TempNode) -> object:\n        return UNKNOWN\n\n\n_evaluator: Final = _NodeEvaluator()\n\n\ndef evaluate_expression(expr: mypy.nodes.Expression) -> object:\n    \"\"\"Evaluate an expression at runtime.\n\n    Return the result of the expression, or UNKNOWN if the expression cannot be\n    evaluated.\n    \"\"\"\n    return expr.accept(_evaluator)\n"
  },
  {
    "path": "mypy/expandtype.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Iterable, Mapping\nfrom typing import Final, TypeVar, cast, overload\n\nfrom mypy.nodes import ARG_STAR, ArgKind, FakeInfo, Var\nfrom mypy.state import state\nfrom mypy.types import (\n    ANY_STRATEGY,\n    AnyType,\n    BoolTypeQuery,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecFlavor,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TrivialSyntheticTypeTranslator,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    flatten_nested_unions,\n    get_proper_type,\n    split_with_prefix_and_suffix,\n)\nfrom mypy.typevartuples import split_with_instance\n\n# Solving the import cycle:\nimport mypy.type_visitor  # ruff: isort: skip\n\n# WARNING: these functions should never (directly or indirectly) depend on\n# is_subtype(), meet_types(), join_types() etc.\n# TODO: add a static dependency test for this.\n\n\n@overload\ndef expand_type(typ: CallableType, env: Mapping[TypeVarId, Type]) -> CallableType: ...\n\n\n@overload\ndef expand_type(typ: ProperType, env: Mapping[TypeVarId, Type]) -> ProperType: ...\n\n\n@overload\ndef expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type: ...\n\n\ndef expand_type(typ: Type, env: Mapping[TypeVarId, Type]) -> Type:\n    \"\"\"Substitute any type variable references in a type given by a type\n    environment.\n    \"\"\"\n    return typ.accept(ExpandTypeVisitor(env))\n\n\n@overload\ndef expand_type_by_instance(typ: CallableType, instance: Instance) -> CallableType: ...\n\n\n@overload\ndef expand_type_by_instance(typ: ProperType, instance: Instance) -> ProperType: ...\n\n\n@overload\ndef expand_type_by_instance(typ: Type, instance: Instance) -> Type: ...\n\n\ndef expand_type_by_instance(typ: Type, instance: Instance) -> Type:\n    \"\"\"Substitute type variables in type using values from an Instance.\n    Type variables are considered to be bound by the class declaration.\"\"\"\n    if not instance.args and not instance.type.has_type_var_tuple_type:\n        return typ\n    else:\n        variables: dict[TypeVarId, Type] = {}\n        if instance.type.has_type_var_tuple_type:\n            assert instance.type.type_var_tuple_prefix is not None\n            assert instance.type.type_var_tuple_suffix is not None\n\n            args_prefix, args_middle, args_suffix = split_with_instance(instance)\n            tvars_prefix, tvars_middle, tvars_suffix = split_with_prefix_and_suffix(\n                tuple(instance.type.defn.type_vars),\n                instance.type.type_var_tuple_prefix,\n                instance.type.type_var_tuple_suffix,\n            )\n            tvar = tvars_middle[0]\n            assert isinstance(tvar, TypeVarTupleType)\n            variables = {tvar.id: TupleType(list(args_middle), tvar.tuple_fallback)}\n            instance_args = args_prefix + args_suffix\n            tvars = tvars_prefix + tvars_suffix\n        else:\n            tvars = tuple(instance.type.defn.type_vars)\n            instance_args = instance.args\n\n        for binder, arg in zip(tvars, instance_args):\n            assert isinstance(binder, TypeVarLikeType)\n            variables[binder.id] = arg\n\n        return expand_type(typ, variables)\n\n\nF = TypeVar(\"F\", bound=FunctionLike)\n\n\ndef freshen_function_type_vars(callee: F) -> F:\n    \"\"\"Substitute fresh type variables for generic function type variables.\"\"\"\n    if isinstance(callee, CallableType):\n        if not callee.is_generic():\n            return callee\n        tvs = []\n        tvmap: dict[TypeVarId, Type] = {}\n        for v in callee.variables:\n            tv = v.new_unification_variable(v)\n            tvs.append(tv)\n            tvmap[v.id] = tv\n        fresh = expand_type(callee, tvmap).copy_modified(variables=tvs)\n        return cast(F, fresh)\n    else:\n        assert isinstance(callee, Overloaded)\n        fresh_overload = Overloaded([freshen_function_type_vars(item) for item in callee.items])\n        return cast(F, fresh_overload)\n\n\nclass HasGenericCallable(BoolTypeQuery):\n    def __init__(self) -> None:\n        super().__init__(ANY_STRATEGY)\n\n    def visit_callable_type(self, t: CallableType) -> bool:\n        return t.is_generic() or super().visit_callable_type(t)\n\n\n# Share a singleton since this is performance sensitive\nhas_generic_callable: Final = HasGenericCallable()\n\n\nT = TypeVar(\"T\", bound=Type)\n\n\ndef freshen_all_functions_type_vars(t: T) -> T:\n    result: Type\n    has_generic_callable.reset()\n    if not t.accept(has_generic_callable):\n        return t  # Fast path to avoid expensive freshening\n    else:\n        result = t.accept(FreshenCallableVisitor())\n        assert isinstance(result, type(t))\n        return result\n\n\nclass FreshenCallableVisitor(mypy.type_visitor.TypeTranslator):\n    def visit_callable_type(self, t: CallableType) -> Type:\n        result = super().visit_callable_type(t)\n        assert isinstance(result, ProperType) and isinstance(result, CallableType)\n        return freshen_function_type_vars(result)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        # Same as for ExpandTypeVisitor\n        return t.copy_modified(args=[arg.accept(self) for arg in t.args])\n\n\nclass ExpandTypeVisitor(TrivialSyntheticTypeTranslator):\n    \"\"\"Visitor that substitutes type variables with values.\"\"\"\n\n    variables: Mapping[TypeVarId, Type]  # TypeVar id -> TypeVar value\n\n    def __init__(self, variables: Mapping[TypeVarId, Type]) -> None:\n        super().__init__()\n        self.variables = variables\n        self.recursive_tvar_guard: dict[TypeVarId, Type | None] | None = None\n\n    def visit_unbound_type(self, t: UnboundType) -> Type:\n        return t\n\n    def visit_any(self, t: AnyType) -> Type:\n        return t\n\n    def visit_none_type(self, t: NoneType) -> Type:\n        return t\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> Type:\n        return t\n\n    def visit_deleted_type(self, t: DeletedType) -> Type:\n        return t\n\n    def visit_erased_type(self, t: ErasedType) -> Type:\n        # This may happen during type inference if some function argument\n        # type is a generic callable, and its erased form will appear in inferred\n        # constraints, then solver may check subtyping between them, which will trigger\n        # unify_generic_callables(), this is why we can get here. Another example is\n        # when inferring type of lambda in generic context, the lambda body contains\n        # a generic method in generic class.\n        return t\n\n    def visit_instance(self, t: Instance) -> Type:\n        if len(t.args) == 0:\n            return t\n\n        args = self.expand_type_tuple_with_unpack(t.args)\n\n        if isinstance(t.type, FakeInfo):\n            # The type checker expands function definitions and bodies\n            # if they depend on constrained type variables but the body\n            # might contain a tuple type comment (e.g., # type: (int, float)),\n            # in which case 't.type' is not yet available.\n            #\n            # See: https://github.com/python/mypy/issues/16649\n            return t.copy_modified(args=args)\n\n        if t.type.fullname == \"builtins.tuple\":\n            # Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...]\n            arg = args[0]\n            if isinstance(arg, UnpackType):\n                unpacked = get_proper_type(arg.type)\n                if isinstance(unpacked, Instance):\n                    # TODO: this and similar asserts below may be unsafe because get_proper_type()\n                    # may be called during semantic analysis before all invalid types are removed.\n                    assert unpacked.type.fullname == \"builtins.tuple\"\n                    args = list(unpacked.args)\n        return t.copy_modified(args=args)\n\n    def visit_type_var(self, t: TypeVarType) -> Type:\n        # Normally upper bounds can't contain other type variables, the only exception is\n        # special type variable Self`0 <: C[T, S], where C is the class where Self is used.\n        if t.id.is_self():\n            t = t.copy_modified(upper_bound=t.upper_bound.accept(self))\n        repl = self.variables.get(t.id, t)\n        if isinstance(repl, ProperType) and isinstance(repl, Instance):\n            # TODO: do we really need to do this?\n            # If I try to remove this special-casing ~40 tests fail on reveal_type().\n            return repl.copy_modified(last_known_value=None)\n        if isinstance(repl, TypeVarType) and repl.has_default():\n            if self.recursive_tvar_guard is None:\n                self.recursive_tvar_guard = {}\n            if (tvar_id := repl.id) in self.recursive_tvar_guard:\n                return self.recursive_tvar_guard[tvar_id] or repl\n            self.recursive_tvar_guard[tvar_id] = None\n            repl.default = repl.default.accept(self)\n            expanded = repl.accept(self)  # Note: `expanded is repl` may be true.\n            repl = repl if isinstance(expanded, TypeVarType) else expanded\n            self.recursive_tvar_guard[tvar_id] = repl\n        return repl\n\n    def visit_param_spec(self, t: ParamSpecType) -> Type:\n        # Set prefix to something empty, so we don't duplicate it below.\n        repl = self.variables.get(t.id, t.copy_modified(prefix=Parameters([], [], [])))\n        if isinstance(repl, ParamSpecType):\n            return repl.copy_modified(\n                flavor=t.flavor,\n                prefix=t.prefix.copy_modified(\n                    arg_types=self.expand_types(t.prefix.arg_types) + repl.prefix.arg_types,\n                    arg_kinds=t.prefix.arg_kinds + repl.prefix.arg_kinds,\n                    arg_names=t.prefix.arg_names + repl.prefix.arg_names,\n                ),\n            )\n        elif isinstance(repl, Parameters):\n            assert isinstance(t.upper_bound, ProperType) and isinstance(t.upper_bound, Instance)\n            if t.flavor == ParamSpecFlavor.BARE:\n                return Parameters(\n                    self.expand_types(t.prefix.arg_types) + repl.arg_types,\n                    t.prefix.arg_kinds + repl.arg_kinds,\n                    t.prefix.arg_names + repl.arg_names,\n                    variables=[*t.prefix.variables, *repl.variables],\n                    imprecise_arg_kinds=repl.imprecise_arg_kinds,\n                )\n            elif t.flavor == ParamSpecFlavor.ARGS:\n                assert all(k.is_positional() for k in t.prefix.arg_kinds)\n                return self._possible_callable_varargs(\n                    repl, list(t.prefix.arg_types), t.upper_bound\n                )\n            else:\n                assert t.flavor == ParamSpecFlavor.KWARGS\n                return self._possible_callable_kwargs(repl, t.upper_bound)\n        else:\n            # We could encode Any as trivial parameters etc., but it would be too verbose.\n            # TODO: assert this is a trivial type, like Any, Never, or object.\n            return repl\n\n    @classmethod\n    def _possible_callable_varargs(\n        cls, repl: Parameters, required_prefix: list[Type], tuple_type: Instance\n    ) -> ProperType:\n        \"\"\"Given a callable, extract all parameters that can be passed as `*args`.\n\n        This builds a union of all (possibly variadic) tuples representing all possible\n        argument sequences that can be passed positionally. Each such tuple starts with\n        all required (pos-only without a default) arguments, followed by some prefix\n        of other arguments that can be passed positionally.\n        \"\"\"\n        required_posargs = required_prefix\n        if repl.variables:\n            # We will tear the callable apart, do not leak type variables\n            return tuple_type\n        optional_posargs: list[Type] = []\n        for kind, name, type in zip(repl.arg_kinds, repl.arg_names, repl.arg_types):\n            if kind == ArgKind.ARG_POS and name is None:\n                if optional_posargs:\n                    # May happen following Unpack expansion without kinds correction\n                    required_posargs += optional_posargs\n                    optional_posargs = []\n                required_posargs.append(type)\n            elif kind.is_positional():\n                optional_posargs.append(type)\n            elif kind == ArgKind.ARG_STAR:\n                if isinstance(type, UnpackType):\n                    optional_posargs.append(type)\n                else:\n                    optional_posargs.append(UnpackType(Instance(tuple_type.type, [type])))\n                break\n        return UnionType.make_union(\n            [\n                TupleType(required_posargs + optional_posargs[:i], fallback=tuple_type)\n                for i in range(len(optional_posargs) + 1)\n            ]\n        )\n\n    @classmethod\n    def _possible_callable_kwargs(cls, repl: Parameters, dict_type: Instance) -> ProperType:\n        \"\"\"Given a callable, extract all parameters that can be passed as `**kwargs`.\n\n        If the function only accepts **kwargs, this will be a `dict[str, KwargsValueType]`.\n        Otherwise, this will be a `TypedDict` containing all explicit args and ignoring\n        `**kwargs` (until PEP 728 `extra_items` is supported). TypedDict entries will\n        be required iff the corresponding argument is kw-only and has no default.\n        \"\"\"\n        if repl.variables:\n            # We will tear the callable apart, do not leak type variables\n            return dict_type\n        kwargs = {}\n        required_names = set()\n        extra_items: Type = UninhabitedType()\n        for kind, name, type in zip(repl.arg_kinds, repl.arg_names, repl.arg_types):\n            if kind == ArgKind.ARG_NAMED and name is not None:\n                kwargs[name] = type\n                required_names.add(name)\n            elif kind == ArgKind.ARG_STAR2:\n                # Unpack[TypedDict] is normalized early, it isn't stored as Unpack\n                extra_items = type\n            elif not kind.is_star() and name is not None:\n                kwargs[name] = type\n        if not kwargs:\n            return Instance(dict_type.type, [dict_type.args[0], extra_items])\n        # TODO: when PEP 728 is implemented, pass extra_items below.\n        return TypedDictType(kwargs, required_names, set(), fallback=dict_type)\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type:\n        # Sometimes solver may need to expand a type variable with (a copy of) itself\n        # (usually together with other TypeVars, but it is hard to filter out TypeVarTuples).\n        repl = self.variables.get(t.id, t)\n        if isinstance(repl, TypeVarTupleType):\n            return repl\n        elif isinstance(repl, ProperType) and isinstance(repl, (AnyType, UninhabitedType)):\n            # Some failed inference scenarios will try to set all type variables to Never.\n            # Instead of being picky and require all the callers to wrap them,\n            # do this here instead.\n            # Note: most cases when this happens are handled in expand unpack below, but\n            # in rare cases (e.g. ParamSpec containing Unpack star args) it may be skipped.\n            return t.tuple_fallback.copy_modified(args=[repl])\n        raise NotImplementedError\n\n    def visit_unpack_type(self, t: UnpackType) -> Type:\n        # It is impossible to reasonably implement visit_unpack_type, because\n        # unpacking inherently expands to something more like a list of types.\n        #\n        # Relevant sections that can call unpack should call expand_unpack()\n        # instead.\n        # However, if the item is a variadic tuple, we can simply carry it over.\n        # In particular, if we expand A[*tuple[T, ...]] with substitutions {T: str},\n        # it is hard to assert this without getting proper type. Another important\n        # example is non-normalized types when called from semanal.py.\n        return UnpackType(t.type.accept(self))\n\n    def expand_unpack(self, t: UnpackType) -> list[Type]:\n        assert isinstance(t.type, TypeVarTupleType)\n        repl = get_proper_type(self.variables.get(t.type.id, t.type))\n        if isinstance(repl, UnpackType):\n            repl = get_proper_type(repl.type)\n        if isinstance(repl, TupleType):\n            return repl.items\n        elif (\n            isinstance(repl, Instance)\n            and repl.type.fullname == \"builtins.tuple\"\n            or isinstance(repl, TypeVarTupleType)\n        ):\n            return [UnpackType(typ=repl)]\n        elif isinstance(repl, (AnyType, UninhabitedType)):\n            # Replace *Ts = Any with *Ts = *tuple[Any, ...] and same for Never.\n            # These types may appear here as a result of user error or failed inference.\n            return [UnpackType(t.type.tuple_fallback.copy_modified(args=[repl]))]\n        else:\n            raise RuntimeError(f\"Invalid type replacement to expand: {repl}\")\n\n    def visit_parameters(self, t: Parameters) -> Type:\n        return t.copy_modified(arg_types=self.expand_types(t.arg_types))\n\n    def interpolate_args_for_unpack(self, t: CallableType, var_arg: UnpackType) -> list[Type]:\n        star_index = t.arg_kinds.index(ARG_STAR)\n        prefix = self.expand_types(t.arg_types[:star_index])\n        suffix = self.expand_types(t.arg_types[star_index + 1 :])\n\n        var_arg_type = get_proper_type(var_arg.type)\n        new_unpack: Type\n        if isinstance(var_arg_type, TupleType):\n            # We have something like Unpack[Tuple[Unpack[Ts], X1, X2]]\n            expanded_tuple = var_arg_type.accept(self)\n            assert isinstance(expanded_tuple, ProperType) and isinstance(expanded_tuple, TupleType)\n            expanded_items = expanded_tuple.items\n            fallback = var_arg_type.partial_fallback\n            new_unpack = UnpackType(TupleType(expanded_items, fallback))\n        elif isinstance(var_arg_type, TypeVarTupleType):\n            # We have plain Unpack[Ts]\n            fallback = var_arg_type.tuple_fallback\n            expanded_items = self.expand_unpack(var_arg)\n            new_unpack = UnpackType(TupleType(expanded_items, fallback))\n        # Since get_proper_type() may be called in semanal.py before callable\n        # normalization happens, we need to also handle non-normal cases here.\n        elif isinstance(var_arg_type, Instance):\n            # we have something like Unpack[Tuple[Any, ...]]\n            new_unpack = UnpackType(var_arg.type.accept(self))\n        else:\n            # We have invalid type in Unpack. This can happen when expanding aliases\n            # to Callable[[*Invalid], Ret]\n            new_unpack = AnyType(TypeOfAny.from_error, line=var_arg.line, column=var_arg.column)\n        return prefix + [new_unpack] + suffix\n\n    def visit_callable_type(self, t: CallableType) -> CallableType:\n        param_spec = t.param_spec()\n        if param_spec is not None:\n            repl = self.variables.get(param_spec.id)\n            # If a ParamSpec in a callable type is substituted with a\n            # callable type, we can't use normal substitution logic,\n            # since ParamSpec is actually split into two components\n            # *P.args and **P.kwargs in the original type. Instead, we\n            # must expand both of them with all the argument types,\n            # kinds and names in the replacement. The return type in\n            # the replacement is ignored.\n            if isinstance(repl, Parameters):\n                # We need to expand both the types in the prefix and the ParamSpec itself\n                expanded = t.copy_modified(\n                    arg_types=self.expand_types(t.arg_types[:-2]) + repl.arg_types,\n                    arg_kinds=t.arg_kinds[:-2] + repl.arg_kinds,\n                    arg_names=t.arg_names[:-2] + repl.arg_names,\n                    ret_type=t.ret_type.accept(self),\n                    type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None),\n                    type_is=(t.type_is.accept(self) if t.type_is is not None else None),\n                    imprecise_arg_kinds=(t.imprecise_arg_kinds or repl.imprecise_arg_kinds),\n                    variables=[*repl.variables, *t.variables],\n                )\n                var_arg = expanded.var_arg()\n                if var_arg is not None and isinstance(var_arg.typ, UnpackType):\n                    # Sometimes we get new unpacks after expanding ParamSpec.\n                    expanded.normalize_trivial_unpack()\n                return expanded\n            elif isinstance(repl, ParamSpecType):\n                # We're substituting one ParamSpec for another; this can mean that the prefix\n                # changes, e.g. substitute Concatenate[int, P] in place of Q.\n                prefix = repl.prefix\n                clean_repl = repl.copy_modified(prefix=Parameters([], [], []))\n                return t.copy_modified(\n                    arg_types=self.expand_types(t.arg_types[:-2])\n                    + prefix.arg_types\n                    + [\n                        clean_repl.with_flavor(ParamSpecFlavor.ARGS),\n                        clean_repl.with_flavor(ParamSpecFlavor.KWARGS),\n                    ],\n                    arg_kinds=t.arg_kinds[:-2] + prefix.arg_kinds + t.arg_kinds[-2:],\n                    arg_names=t.arg_names[:-2] + prefix.arg_names + t.arg_names[-2:],\n                    ret_type=t.ret_type.accept(self),\n                    from_concatenate=t.from_concatenate or bool(repl.prefix.arg_types),\n                    imprecise_arg_kinds=(t.imprecise_arg_kinds or prefix.imprecise_arg_kinds),\n                )\n\n        var_arg = t.var_arg()\n        needs_normalization = False\n        if var_arg is not None and isinstance(var_arg.typ, UnpackType):\n            needs_normalization = True\n            arg_types = self.interpolate_args_for_unpack(t, var_arg.typ)\n        else:\n            arg_types = self.expand_types(t.arg_types)\n        expanded = t.copy_modified(\n            arg_types=arg_types,\n            ret_type=t.ret_type.accept(self),\n            type_guard=(t.type_guard.accept(self) if t.type_guard is not None else None),\n            type_is=(t.type_is.accept(self) if t.type_is is not None else None),\n        )\n        if needs_normalization:\n            return expanded.with_normalized_var_args()\n        return expanded\n\n    def visit_overloaded(self, t: Overloaded) -> Type:\n        items: list[CallableType] = []\n        for item in t.items:\n            new_item = item.accept(self)\n            assert isinstance(new_item, ProperType)\n            assert isinstance(new_item, CallableType)\n            items.append(new_item)\n        return Overloaded(items)\n\n    def expand_type_list_with_unpack(self, typs: list[Type]) -> list[Type]:\n        \"\"\"Expands a list of types that has an unpack.\"\"\"\n        items: list[Type] = []\n        for item in typs:\n            if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType):\n                items.extend(self.expand_unpack(item))\n            else:\n                items.append(item.accept(self))\n        return items\n\n    def expand_type_tuple_with_unpack(self, typs: tuple[Type, ...]) -> list[Type]:\n        \"\"\"Expands a tuple of types that has an unpack.\"\"\"\n        # Micro-optimization: Specialized variant of expand_type_list_with_unpack\n        items: list[Type] = []\n        for item in typs:\n            if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType):\n                items.extend(self.expand_unpack(item))\n            else:\n                items.append(item.accept(self))\n        return items\n\n    def visit_tuple_type(self, t: TupleType) -> Type:\n        items = self.expand_type_list_with_unpack(t.items)\n        if len(items) == 1:\n            # Normalize Tuple[*Tuple[X, ...]] -> Tuple[X, ...]\n            item = items[0]\n            if isinstance(item, UnpackType):\n                unpacked = get_proper_type(item.type)\n                if isinstance(unpacked, Instance):\n                    # expand_type() may be called during semantic analysis, before invalid unpacks are fixed.\n                    if unpacked.type.fullname != \"builtins.tuple\":\n                        return t.partial_fallback.accept(self)\n                    if t.partial_fallback.type.fullname != \"builtins.tuple\":\n                        # If it is a subtype (like named tuple) we need to preserve it,\n                        # this essentially mimics the logic in tuple_fallback().\n                        return t.partial_fallback.accept(self)\n                    return unpacked\n        fallback = t.partial_fallback.accept(self)\n        assert isinstance(fallback, ProperType) and isinstance(fallback, Instance)\n        return t.copy_modified(items=items, fallback=fallback)\n\n    def visit_typeddict_type(self, t: TypedDictType) -> Type:\n        if cached := self.get_cached(t):\n            return cached\n        fallback = t.fallback.accept(self)\n        assert isinstance(fallback, ProperType) and isinstance(fallback, Instance)\n        result = t.copy_modified(item_types=self.expand_types(t.items.values()), fallback=fallback)\n        self.set_cached(t, result)\n        return result\n\n    def visit_literal_type(self, t: LiteralType) -> Type:\n        # TODO: Verify this implementation is correct\n        return t\n\n    def visit_union_type(self, t: UnionType) -> Type:\n        # Use cache to avoid O(n**2) or worse expansion of types during translation\n        # (only for large unions, since caching adds overhead)\n        use_cache = len(t.items) > 3\n        if use_cache and (cached := self.get_cached(t)):\n            return cached\n\n        expanded = self.expand_types(t.items)\n        # After substituting for type variables in t.items, some resulting types\n        # might be subtypes of others, however calling  make_simplified_union()\n        # can cause recursion, so we just remove strict duplicates.\n        simplified = UnionType.make_union(\n            remove_trivial(flatten_nested_unions(expanded)), t.line, t.column\n        )\n        # This call to get_proper_type() is unfortunate but is required to preserve\n        # the invariant that ProperType will stay ProperType after applying expand_type(),\n        # otherwise a single item union of a type alias will break it. Note this should not\n        # cause infinite recursion since pathological aliases like A = Union[A, B] are\n        # banned at the semantic analysis level.\n        result = get_proper_type(simplified)\n\n        if use_cache:\n            self.set_cached(t, result)\n        return result\n\n    def visit_partial_type(self, t: PartialType) -> Type:\n        return t\n\n    def visit_type_type(self, t: TypeType) -> Type:\n        # TODO: Verify that the new item type is valid (instance or\n        # union of instances or Any).  Sadly we can't report errors\n        # here yet.\n        item = t.item.accept(self)\n        return TypeType.make_normalized(item, is_type_form=t.is_type_form)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        # Target of the type alias cannot contain type variables (not bound by the type\n        # alias itself), so we just expand the arguments.\n        if len(t.args) == 0:\n            return t\n        args = self.expand_type_list_with_unpack(t.args)\n        # TODO: normalize if target is Tuple, and args are [*tuple[X, ...]]?\n        return t.copy_modified(args=args)\n\n    def expand_types(self, types: Iterable[Type]) -> list[Type]:\n        a: list[Type] = []\n        for t in types:\n            a.append(t.accept(self))\n        return a\n\n\n@overload\ndef expand_self_type(var: Var, typ: ProperType, replacement: ProperType) -> ProperType: ...\n\n\n@overload\ndef expand_self_type(var: Var, typ: Type, replacement: Type) -> Type: ...\n\n\ndef expand_self_type(var: Var, typ: Type, replacement: Type) -> Type:\n    \"\"\"Expand appearances of Self type in a variable type.\"\"\"\n    if var.info.self_type is not None and not var.is_property:\n        return expand_type(typ, {var.info.self_type.id: replacement})\n    return typ\n\n\ndef remove_trivial(types: Iterable[Type]) -> list[Type]:\n    \"\"\"Make trivial simplifications on a list of types without calling is_subtype().\n\n    This makes following simplifications:\n        * Remove bottom types (taking into account strict optional setting)\n        * Remove everything else if there is an `object`\n        * Remove strict duplicate types\n    \"\"\"\n    removed_none = False\n    new_types = []\n    all_types = set()\n    for t in types:\n        p_t = get_proper_type(t)\n        if isinstance(p_t, UninhabitedType):\n            continue\n        if isinstance(p_t, NoneType) and not state.strict_optional:\n            removed_none = True\n            continue\n        if isinstance(p_t, Instance) and p_t.type.fullname == \"builtins.object\":\n            return [p_t]\n        if p_t not in all_types:\n            new_types.append(t)\n            all_types.add(p_t)\n    if new_types:\n        return new_types\n    if removed_none:\n        return [NoneType()]\n    return [UninhabitedType()]\n"
  },
  {
    "path": "mypy/exportjson.py",
    "content": "\"\"\"Tool to convert binary mypy cache files (.ff) to JSON (.ff.json).\n\nUsage:\n   python -m mypy.exportjson .mypy_cache/.../my_module.data.ff\n\nThe idea is to make caches introspectable once we've switched to a binary\ncache format and removed support for the older JSON cache format.\n\nThis is primarily to support existing use cases that need to inspect\ncache files, and to support debugging mypy caching issues. This means that\nthis doesn't necessarily need to be kept 1:1 up to date with changes in the\nbinary cache format (to simplify maintenance -- we don't want this to slow\ndown mypy development).\n\"\"\"\n\nimport argparse\nimport json\nimport sys\nfrom typing import Any, TypeAlias as _TypeAlias\n\nfrom librt.internal import ReadBuffer, cache_version\n\nfrom mypy.cache import CACHE_VERSION, CacheMeta\nfrom mypy.nodes import (\n    FUNCBASE_FLAGS,\n    FUNCDEF_FLAGS,\n    VAR_FLAGS,\n    ClassDef,\n    DataclassTransformSpec,\n    Decorator,\n    FuncDef,\n    MypyFile,\n    OverloadedFuncDef,\n    OverloadPart,\n    ParamSpecExpr,\n    SymbolNode,\n    SymbolTable,\n    SymbolTableNode,\n    TypeAlias,\n    TypeInfo,\n    TypeVarExpr,\n    TypeVarTupleExpr,\n    Var,\n    get_flags,\n    node_kinds,\n)\nfrom mypy.types import (\n    NOT_READY,\n    AnyType,\n    CallableType,\n    ExtraAttrs,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    get_proper_type,\n)\n\nJson: _TypeAlias = dict[str, Any] | str\n\n\nclass Config:\n    def __init__(self, *, implicit_names: bool = True) -> None:\n        self.implicit_names = implicit_names\n\n\ndef convert_binary_cache_to_json(data: bytes, *, implicit_names: bool = True) -> Json:\n    tree = MypyFile.read(ReadBuffer(data))\n    return convert_mypy_file_to_json(tree, Config(implicit_names=implicit_names))\n\n\ndef convert_mypy_file_to_json(self: MypyFile, cfg: Config) -> Json:\n    return {\n        \".class\": \"MypyFile\",\n        \"_fullname\": self._fullname,\n        \"names\": convert_symbol_table(self.names, cfg),\n        \"is_stub\": self.is_stub,\n        \"path\": self.path,\n        \"is_partial_stub_package\": self.is_partial_stub_package,\n        \"future_import_flags\": sorted(self.future_import_flags),\n    }\n\n\ndef convert_symbol_table(self: SymbolTable, cfg: Config) -> Json:\n    data: dict[str, Any] = {\".class\": \"SymbolTable\"}\n    for key, value in self.items():\n        # Skip __builtins__: it's a reference to the builtins\n        # module that gets added to every module by\n        # SemanticAnalyzerPass2.visit_file(), but it shouldn't be\n        # accessed by users of the module.\n        if key == \"__builtins__\" or value.no_serialize:\n            continue\n        if not cfg.implicit_names and key in {\n            \"__spec__\",\n            \"__package__\",\n            \"__file__\",\n            \"__doc__\",\n            \"__annotations__\",\n            \"__name__\",\n        }:\n            continue\n        data[key] = convert_symbol_table_node(value, cfg)\n    return data\n\n\ndef convert_symbol_table_node(self: SymbolTableNode, cfg: Config) -> Json:\n    data: dict[str, Any] = {\".class\": \"SymbolTableNode\", \"kind\": node_kinds[self.kind]}\n    if self.module_hidden:\n        data[\"module_hidden\"] = True\n    if not self.module_public:\n        data[\"module_public\"] = False\n    if self.implicit:\n        data[\"implicit\"] = True\n    if self.plugin_generated:\n        data[\"plugin_generated\"] = True\n    if self.cross_ref:\n        data[\"cross_ref\"] = self.cross_ref\n    elif self.node is not None:\n        data[\"node\"] = convert_symbol_node(self.node, cfg)\n    return data\n\n\ndef convert_symbol_node(self: SymbolNode, cfg: Config) -> Json:\n    if isinstance(self, FuncDef):\n        return convert_func_def(self)\n    elif isinstance(self, OverloadedFuncDef):\n        return convert_overloaded_func_def(self)\n    elif isinstance(self, Decorator):\n        return convert_decorator(self)\n    elif isinstance(self, Var):\n        return convert_var(self)\n    elif isinstance(self, TypeInfo):\n        return convert_type_info(self, cfg)\n    elif isinstance(self, TypeAlias):\n        return convert_type_alias(self)\n    elif isinstance(self, TypeVarExpr):\n        return convert_type_var_expr(self)\n    elif isinstance(self, ParamSpecExpr):\n        return convert_param_spec_expr(self)\n    elif isinstance(self, TypeVarTupleExpr):\n        return convert_type_var_tuple_expr(self)\n    return {\"ERROR\": f\"{type(self)!r} unrecognized\"}\n\n\ndef convert_func_def(self: FuncDef) -> Json:\n    return {\n        \".class\": \"FuncDef\",\n        \"name\": self._name,\n        \"fullname\": self._fullname,\n        \"arg_names\": self.arg_names,\n        \"arg_kinds\": [int(x.value) for x in self.arg_kinds],\n        \"type\": None if self.type is None else convert_type(self.type),\n        \"flags\": get_flags(self, FUNCDEF_FLAGS),\n        \"abstract_status\": self.abstract_status,\n        # TODO: Do we need expanded, original_def?\n        \"dataclass_transform_spec\": (\n            None\n            if self.dataclass_transform_spec is None\n            else convert_dataclass_transform_spec(self.dataclass_transform_spec)\n        ),\n        \"deprecated\": self.deprecated,\n        \"original_first_arg\": self.original_first_arg,\n    }\n\n\ndef convert_dataclass_transform_spec(self: DataclassTransformSpec) -> Json:\n    return {\n        \"eq_default\": self.eq_default,\n        \"order_default\": self.order_default,\n        \"kw_only_default\": self.kw_only_default,\n        \"frozen_default\": self.frozen_default,\n        \"field_specifiers\": list(self.field_specifiers),\n    }\n\n\ndef convert_overloaded_func_def(self: OverloadedFuncDef) -> Json:\n    return {\n        \".class\": \"OverloadedFuncDef\",\n        \"items\": [convert_overload_part(i) for i in self.items],\n        \"type\": None if self.type is None else convert_type(self.type),\n        \"fullname\": self._fullname,\n        \"impl\": None if self.impl is None else convert_overload_part(self.impl),\n        \"flags\": get_flags(self, FUNCBASE_FLAGS),\n        \"deprecated\": self.deprecated,\n        \"setter_index\": self.setter_index,\n    }\n\n\ndef convert_overload_part(self: OverloadPart) -> Json:\n    if isinstance(self, FuncDef):\n        return convert_func_def(self)\n    else:\n        return convert_decorator(self)\n\n\ndef convert_decorator(self: Decorator) -> Json:\n    return {\n        \".class\": \"Decorator\",\n        \"func\": convert_func_def(self.func),\n        \"var\": convert_var(self.var),\n        \"is_overload\": self.is_overload,\n    }\n\n\ndef convert_var(self: Var) -> Json:\n    data: dict[str, Any] = {\n        \".class\": \"Var\",\n        \"name\": self._name,\n        \"fullname\": self._fullname,\n        \"type\": None if self.type is None else convert_type(self.type),\n        \"setter_type\": None if self.setter_type is None else convert_type(self.setter_type),\n        \"flags\": get_flags(self, VAR_FLAGS),\n    }\n    if self.final_value is not None:\n        data[\"final_value\"] = self.final_value\n    return data\n\n\ndef convert_type_info(self: TypeInfo, cfg: Config) -> Json:\n    data = {\n        \".class\": \"TypeInfo\",\n        \"module_name\": self.module_name,\n        \"fullname\": self.fullname,\n        \"names\": convert_symbol_table(self.names, cfg),\n        \"defn\": convert_class_def(self.defn),\n        \"abstract_attributes\": self.abstract_attributes,\n        \"type_vars\": self.type_vars,\n        \"has_param_spec_type\": self.has_param_spec_type,\n        \"bases\": [convert_type(b) for b in self.bases],\n        \"mro\": self._mro_refs,\n        \"_promote\": [convert_type(p) for p in self._promote],\n        \"alt_promote\": None if self.alt_promote is None else convert_type(self.alt_promote),\n        \"declared_metaclass\": (\n            None if self.declared_metaclass is None else convert_type(self.declared_metaclass)\n        ),\n        \"metaclass_type\": (\n            None if self.metaclass_type is None else convert_type(self.metaclass_type)\n        ),\n        \"tuple_type\": None if self.tuple_type is None else convert_type(self.tuple_type),\n        \"typeddict_type\": (\n            None if self.typeddict_type is None else convert_typeddict_type(self.typeddict_type)\n        ),\n        \"flags\": get_flags(self, TypeInfo.FLAGS),\n        \"metadata\": self.metadata,\n        \"slots\": sorted(self.slots) if self.slots is not None else None,\n        \"deletable_attributes\": self.deletable_attributes,\n        \"self_type\": convert_type(self.self_type) if self.self_type is not None else None,\n        \"dataclass_transform_spec\": (\n            convert_dataclass_transform_spec(self.dataclass_transform_spec)\n            if self.dataclass_transform_spec is not None\n            else None\n        ),\n        \"deprecated\": self.deprecated,\n    }\n    return data\n\n\ndef convert_class_def(self: ClassDef) -> Json:\n    return {\n        \".class\": \"ClassDef\",\n        \"name\": self.name,\n        \"fullname\": self.fullname,\n        \"type_vars\": [convert_type(v) for v in self.type_vars],\n    }\n\n\ndef convert_type_alias(self: TypeAlias) -> Json:\n    data: Json = {\n        \".class\": \"TypeAlias\",\n        \"fullname\": self._fullname,\n        \"module\": self.module,\n        \"target\": convert_type(self.target),\n        \"alias_tvars\": [convert_type(v) for v in self.alias_tvars],\n        \"no_args\": self.no_args,\n        \"normalized\": self.normalized,\n        \"python_3_12_type_alias\": self.python_3_12_type_alias,\n    }\n    return data\n\n\ndef convert_type_var_expr(self: TypeVarExpr) -> Json:\n    return {\n        \".class\": \"TypeVarExpr\",\n        \"name\": self._name,\n        \"fullname\": self._fullname,\n        \"values\": [convert_type(t) for t in self.values],\n        \"upper_bound\": convert_type(self.upper_bound),\n        \"default\": convert_type(self.default),\n        \"variance\": self.variance,\n    }\n\n\ndef convert_param_spec_expr(self: ParamSpecExpr) -> Json:\n    return {\n        \".class\": \"ParamSpecExpr\",\n        \"name\": self._name,\n        \"fullname\": self._fullname,\n        \"upper_bound\": convert_type(self.upper_bound),\n        \"default\": convert_type(self.default),\n        \"variance\": self.variance,\n    }\n\n\ndef convert_type_var_tuple_expr(self: TypeVarTupleExpr) -> Json:\n    return {\n        \".class\": \"TypeVarTupleExpr\",\n        \"name\": self._name,\n        \"fullname\": self._fullname,\n        \"upper_bound\": convert_type(self.upper_bound),\n        \"tuple_fallback\": convert_type(self.tuple_fallback),\n        \"default\": convert_type(self.default),\n        \"variance\": self.variance,\n    }\n\n\ndef convert_type(typ: Type) -> Json:\n    if type(typ) is TypeAliasType:\n        return convert_type_alias_type(typ)\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        return convert_instance(typ)\n    elif isinstance(typ, AnyType):\n        return convert_any_type(typ)\n    elif isinstance(typ, NoneType):\n        return convert_none_type(typ)\n    elif isinstance(typ, UnionType):\n        return convert_union_type(typ)\n    elif isinstance(typ, TupleType):\n        return convert_tuple_type(typ)\n    elif isinstance(typ, CallableType):\n        return convert_callable_type(typ)\n    elif isinstance(typ, Overloaded):\n        return convert_overloaded(typ)\n    elif isinstance(typ, LiteralType):\n        return convert_literal_type(typ)\n    elif isinstance(typ, TypeVarType):\n        return convert_type_var_type(typ)\n    elif isinstance(typ, TypeType):\n        return convert_type_type(typ)\n    elif isinstance(typ, UninhabitedType):\n        return convert_uninhabited_type(typ)\n    elif isinstance(typ, UnpackType):\n        return convert_unpack_type(typ)\n    elif isinstance(typ, ParamSpecType):\n        return convert_param_spec_type(typ)\n    elif isinstance(typ, TypeVarTupleType):\n        return convert_type_var_tuple_type(typ)\n    elif isinstance(typ, Parameters):\n        return convert_parameters(typ)\n    elif isinstance(typ, TypedDictType):\n        return convert_typeddict_type(typ)\n    elif isinstance(typ, UnboundType):\n        return convert_unbound_type(typ)\n    return {\"ERROR\": f\"{type(typ)!r} unrecognized\"}\n\n\ndef convert_instance(self: Instance) -> Json:\n    ready = self.type is not NOT_READY\n    if not self.args and not self.last_known_value and not self.extra_attrs:\n        if ready:\n            return self.type.fullname\n        elif self.type_ref:\n            return self.type_ref\n\n    data: dict[str, Any] = {\n        \".class\": \"Instance\",\n        \"type_ref\": self.type.fullname if ready else self.type_ref,\n        \"args\": [convert_type(arg) for arg in self.args],\n    }\n    if self.last_known_value is not None:\n        data[\"last_known_value\"] = convert_type(self.last_known_value)\n    data[\"extra_attrs\"] = convert_extra_attrs(self.extra_attrs) if self.extra_attrs else None\n    return data\n\n\ndef convert_extra_attrs(self: ExtraAttrs) -> Json:\n    return {\n        \".class\": \"ExtraAttrs\",\n        \"attrs\": {k: convert_type(v) for k, v in self.attrs.items()},\n        \"immutable\": sorted(self.immutable),\n        \"mod_name\": self.mod_name,\n    }\n\n\ndef convert_type_alias_type(self: TypeAliasType) -> Json:\n    data: Json = {\n        \".class\": \"TypeAliasType\",\n        \"type_ref\": self.type_ref,\n        \"args\": [convert_type(arg) for arg in self.args],\n    }\n    return data\n\n\ndef convert_any_type(self: AnyType) -> Json:\n    return {\n        \".class\": \"AnyType\",\n        \"type_of_any\": self.type_of_any,\n        \"source_any\": convert_type(self.source_any) if self.source_any is not None else None,\n        \"missing_import_name\": self.missing_import_name,\n    }\n\n\ndef convert_none_type(self: NoneType) -> Json:\n    return {\".class\": \"NoneType\"}\n\n\ndef convert_union_type(self: UnionType) -> Json:\n    return {\n        \".class\": \"UnionType\",\n        \"items\": [convert_type(t) for t in self.items],\n        \"uses_pep604_syntax\": self.uses_pep604_syntax,\n    }\n\n\ndef convert_tuple_type(self: TupleType) -> Json:\n    return {\n        \".class\": \"TupleType\",\n        \"items\": [convert_type(t) for t in self.items],\n        \"partial_fallback\": convert_type(self.partial_fallback),\n        \"implicit\": self.implicit,\n    }\n\n\ndef convert_literal_type(self: LiteralType) -> Json:\n    return {\".class\": \"LiteralType\", \"value\": self.value, \"fallback\": convert_type(self.fallback)}\n\n\ndef convert_type_var_type(self: TypeVarType) -> Json:\n    assert not self.id.is_meta_var()\n    return {\n        \".class\": \"TypeVarType\",\n        \"name\": self.name,\n        \"fullname\": self.fullname,\n        \"id\": self.id.raw_id,\n        \"namespace\": self.id.namespace,\n        \"values\": [convert_type(v) for v in self.values],\n        \"upper_bound\": convert_type(self.upper_bound),\n        \"default\": convert_type(self.default),\n        \"variance\": self.variance,\n    }\n\n\ndef convert_callable_type(self: CallableType) -> Json:\n    return {\n        \".class\": \"CallableType\",\n        \"arg_types\": [convert_type(t) for t in self.arg_types],\n        \"arg_kinds\": [int(x.value) for x in self.arg_kinds],\n        \"arg_names\": self.arg_names,\n        \"ret_type\": convert_type(self.ret_type),\n        \"fallback\": convert_type(self.fallback),\n        \"name\": self.name,\n        # We don't serialize the definition (only used for error messages).\n        \"variables\": [convert_type(v) for v in self.variables],\n        \"is_ellipsis_args\": self.is_ellipsis_args,\n        \"implicit\": self.implicit,\n        \"is_bound\": self.is_bound,\n        \"type_guard\": convert_type(self.type_guard) if self.type_guard is not None else None,\n        \"type_is\": convert_type(self.type_is) if self.type_is is not None else None,\n        \"from_concatenate\": self.from_concatenate,\n        \"imprecise_arg_kinds\": self.imprecise_arg_kinds,\n        \"unpack_kwargs\": self.unpack_kwargs,\n    }\n\n\ndef convert_overloaded(self: Overloaded) -> Json:\n    return {\".class\": \"Overloaded\", \"items\": [convert_type(t) for t in self.items]}\n\n\ndef convert_type_type(self: TypeType) -> Json:\n    return {\".class\": \"TypeType\", \"item\": convert_type(self.item)}\n\n\ndef convert_uninhabited_type(self: UninhabitedType) -> Json:\n    return {\".class\": \"UninhabitedType\"}\n\n\ndef convert_unpack_type(self: UnpackType) -> Json:\n    return {\".class\": \"UnpackType\", \"type\": convert_type(self.type)}\n\n\ndef convert_param_spec_type(self: ParamSpecType) -> Json:\n    assert not self.id.is_meta_var()\n    return {\n        \".class\": \"ParamSpecType\",\n        \"name\": self.name,\n        \"fullname\": self.fullname,\n        \"id\": self.id.raw_id,\n        \"namespace\": self.id.namespace,\n        \"flavor\": self.flavor,\n        \"upper_bound\": convert_type(self.upper_bound),\n        \"default\": convert_type(self.default),\n        \"prefix\": convert_type(self.prefix),\n    }\n\n\ndef convert_type_var_tuple_type(self: TypeVarTupleType) -> Json:\n    assert not self.id.is_meta_var()\n    return {\n        \".class\": \"TypeVarTupleType\",\n        \"name\": self.name,\n        \"fullname\": self.fullname,\n        \"id\": self.id.raw_id,\n        \"namespace\": self.id.namespace,\n        \"upper_bound\": convert_type(self.upper_bound),\n        \"tuple_fallback\": convert_type(self.tuple_fallback),\n        \"default\": convert_type(self.default),\n        \"min_len\": self.min_len,\n    }\n\n\ndef convert_parameters(self: Parameters) -> Json:\n    return {\n        \".class\": \"Parameters\",\n        \"arg_types\": [convert_type(t) for t in self.arg_types],\n        \"arg_kinds\": [int(x.value) for x in self.arg_kinds],\n        \"arg_names\": self.arg_names,\n        \"variables\": [convert_type(tv) for tv in self.variables],\n        \"imprecise_arg_kinds\": self.imprecise_arg_kinds,\n    }\n\n\ndef convert_typeddict_type(self: TypedDictType) -> Json:\n    return {\n        \".class\": \"TypedDictType\",\n        \"items\": [[n, convert_type(t)] for (n, t) in self.items.items()],\n        \"required_keys\": sorted(self.required_keys),\n        \"readonly_keys\": sorted(self.readonly_keys),\n        \"fallback\": convert_type(self.fallback),\n    }\n\n\ndef convert_unbound_type(self: UnboundType) -> Json:\n    return {\n        \".class\": \"UnboundType\",\n        \"name\": self.name,\n        \"args\": [convert_type(a) for a in self.args],\n        \"expr\": self.original_str_expr,\n        \"expr_fallback\": self.original_str_fallback,\n    }\n\n\ndef convert_binary_cache_meta_to_json(data: bytes, data_file: str) -> Json:\n    assert (\n        data[0] == cache_version() and data[1] == CACHE_VERSION\n    ), \"Cache file created by an incompatible mypy version\"\n    meta = CacheMeta.read(ReadBuffer(data[2:]), data_file)\n    assert meta is not None, f\"Error reading meta cache file associated with {data_file}\"\n    return {\n        \"id\": meta.id,\n        \"path\": meta.path,\n        \"mtime\": meta.mtime,\n        \"size\": meta.size,\n        \"hash\": meta.hash,\n        \"data_mtime\": meta.data_mtime,\n        \"dependencies\": meta.dependencies,\n        \"suppressed\": meta.suppressed,\n        \"options\": meta.options,\n        \"dep_prios\": meta.dep_prios,\n        \"dep_lines\": meta.dep_lines,\n        \"dep_hashes\": [dep.hex() for dep in meta.dep_hashes],\n        \"interface_hash\": meta.interface_hash.hex(),\n        \"version_id\": meta.version_id,\n        \"ignore_all\": meta.ignore_all,\n        \"plugin_data\": meta.plugin_data,\n    }\n\n\ndef main() -> None:\n    parser = argparse.ArgumentParser(\n        description=\"Convert binary cache files to JSON. \"\n        \"Create files in the same directory with extra .json extension.\"\n    )\n    parser.add_argument(\n        \"path\", nargs=\"+\", help=\"mypy cache data file to convert (.data.ff extension)\"\n    )\n    args = parser.parse_args()\n    fnams: list[str] = args.path\n    for fnam in fnams:\n        if fnam.endswith(\".data.ff\"):\n            is_data = True\n        elif fnam.endswith(\".meta.ff\"):\n            is_data = False\n        else:\n            sys.exit(f\"error: Expected .data.ff or .meta.ff extension, but got {fnam}\")\n        with open(fnam, \"rb\") as f:\n            data = f.read()\n        if is_data:\n            json_data = convert_binary_cache_to_json(data)\n        else:\n            data_file = fnam.removesuffix(\".meta.ff\") + \".data.ff\"\n            json_data = convert_binary_cache_meta_to_json(data, data_file)\n        new_fnam = fnam + \".json\"\n        with open(new_fnam, \"w\") as f:\n            json.dump(json_data, f)\n        print(f\"{fnam} -> {new_fnam}\")\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "mypy/exprtotype.py",
    "content": "\"\"\"Translate an Expression to a Type value.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\n\nfrom mypy.fastparse import parse_type_string\nfrom mypy.nodes import (\n    MISSING_FALLBACK,\n    BytesExpr,\n    CallExpr,\n    ComplexExpr,\n    Context,\n    DictExpr,\n    EllipsisExpr,\n    Expression,\n    FloatExpr,\n    IndexExpr,\n    IntExpr,\n    ListExpr,\n    MemberExpr,\n    NameExpr,\n    OpExpr,\n    RefExpr,\n    StarExpr,\n    StrExpr,\n    SymbolTableNode,\n    TupleExpr,\n    UnaryExpr,\n    get_member_expr_fullname,\n)\nfrom mypy.options import Options\nfrom mypy.types import (\n    ANNOTATED_TYPE_NAMES,\n    AnyType,\n    CallableArgument,\n    EllipsisType,\n    Instance,\n    ProperType,\n    RawExpressionType,\n    Type,\n    TypedDictType,\n    TypeList,\n    TypeOfAny,\n    UnboundType,\n    UnionType,\n    UnpackType,\n)\n\n\nclass TypeTranslationError(Exception):\n    \"\"\"Exception raised when an expression is not valid as a type.\"\"\"\n\n\ndef _extract_argument_name(expr: Expression) -> str | None:\n    if isinstance(expr, NameExpr) and expr.name == \"None\":\n        return None\n    elif isinstance(expr, StrExpr):\n        return expr.value\n    else:\n        raise TypeTranslationError()\n\n\ndef expr_to_unanalyzed_type(\n    expr: Expression,\n    options: Options,\n    allow_new_syntax: bool = False,\n    _parent: Expression | None = None,\n    allow_unpack: bool = False,\n    lookup_qualified: Callable[[str, Context], SymbolTableNode | None] | None = None,\n) -> ProperType:\n    \"\"\"Translate an expression to the corresponding type.\n\n    The result is not semantically analyzed. It can be UnboundType or TypeList.\n    Raise TypeTranslationError if the expression cannot represent a type.\n\n    If lookup_qualified is not provided, the expression is expected to be semantically\n    analyzed.\n\n    If allow_new_syntax is True, allow all type syntax independent of the target\n    Python version (used in stubs).\n\n    # TODO: a lot of code here is duplicated in fastparse.py, refactor this.\n    \"\"\"\n    # The `parent` parameter is used in recursive calls to provide context for\n    # understanding whether an CallableArgument is ok.\n    name: str | None = None\n    if isinstance(expr, NameExpr):\n        name = expr.name\n        if name == \"True\":\n            return RawExpressionType(True, \"builtins.bool\", line=expr.line, column=expr.column)\n        elif name == \"False\":\n            return RawExpressionType(False, \"builtins.bool\", line=expr.line, column=expr.column)\n        else:\n            return UnboundType(name, line=expr.line, column=expr.column)\n    elif isinstance(expr, MemberExpr):\n        fullname = get_member_expr_fullname(expr)\n        if fullname:\n            return UnboundType(fullname, line=expr.line, column=expr.column)\n        else:\n            raise TypeTranslationError()\n    elif isinstance(expr, IndexExpr):\n        base = expr_to_unanalyzed_type(\n            expr.base, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified\n        )\n        if isinstance(base, UnboundType):\n            if base.args:\n                raise TypeTranslationError()\n            if isinstance(expr.index, TupleExpr):\n                args = expr.index.items\n            else:\n                args = [expr.index]\n\n            if isinstance(expr.base, RefExpr):\n                # Check if the type is Annotated[...]. For this we need the fullname,\n                # which must be looked up if the expression hasn't been semantically analyzed.\n                base_fullname = None\n                if lookup_qualified is not None:\n                    sym = lookup_qualified(base.name, expr)\n                    if sym and sym.node:\n                        base_fullname = sym.node.fullname\n                else:\n                    base_fullname = expr.base.fullname\n\n                if base_fullname is not None and base_fullname in ANNOTATED_TYPE_NAMES:\n                    # TODO: this is not the optimal solution as we are basically getting rid\n                    # of the Annotation definition and only returning the type information,\n                    # losing all the annotations.\n                    return expr_to_unanalyzed_type(\n                        args[0], options, allow_new_syntax, expr, lookup_qualified=lookup_qualified\n                    )\n            base.args = tuple(\n                expr_to_unanalyzed_type(\n                    arg,\n                    options,\n                    allow_new_syntax,\n                    expr,\n                    allow_unpack=True,\n                    lookup_qualified=lookup_qualified,\n                )\n                for arg in args\n            )\n            if not base.args:\n                base.empty_tuple_index = True\n            return base\n        else:\n            raise TypeTranslationError()\n    elif (\n        isinstance(expr, OpExpr)\n        and expr.op == \"|\"\n        and ((options.python_version >= (3, 10)) or allow_new_syntax)\n    ):\n        return UnionType(\n            [\n                expr_to_unanalyzed_type(\n                    expr.left, options, allow_new_syntax, lookup_qualified=lookup_qualified\n                ),\n                expr_to_unanalyzed_type(\n                    expr.right, options, allow_new_syntax, lookup_qualified=lookup_qualified\n                ),\n            ],\n            uses_pep604_syntax=True,\n        )\n    elif isinstance(expr, CallExpr) and isinstance(_parent, ListExpr):\n        c = expr.callee\n        names = []\n        # Go through the dotted member expr chain to get the full arg\n        # constructor name to look up\n        while True:\n            if isinstance(c, NameExpr):\n                names.append(c.name)\n                break\n            elif isinstance(c, MemberExpr):\n                names.append(c.name)\n                c = c.expr\n            else:\n                raise TypeTranslationError()\n        arg_const = \".\".join(reversed(names))\n\n        # Go through the constructor args to get its name and type.\n        name = None\n        default_type = AnyType(TypeOfAny.unannotated)\n        typ: Type = default_type\n        for i, arg in enumerate(expr.args):\n            if expr.arg_names[i] is not None:\n                if expr.arg_names[i] == \"name\":\n                    if name is not None:\n                        # Two names\n                        raise TypeTranslationError()\n                    name = _extract_argument_name(arg)\n                    continue\n                elif expr.arg_names[i] == \"type\":\n                    if typ is not default_type:\n                        # Two types\n                        raise TypeTranslationError()\n                    typ = expr_to_unanalyzed_type(\n                        arg, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified\n                    )\n                    continue\n                else:\n                    raise TypeTranslationError()\n            elif i == 0:\n                typ = expr_to_unanalyzed_type(\n                    arg, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified\n                )\n            elif i == 1:\n                name = _extract_argument_name(arg)\n            else:\n                raise TypeTranslationError()\n        return CallableArgument(typ, name, arg_const, expr.line, expr.column)\n    elif isinstance(expr, ListExpr):\n        return TypeList(\n            [\n                expr_to_unanalyzed_type(\n                    t,\n                    options,\n                    allow_new_syntax,\n                    expr,\n                    allow_unpack=True,\n                    lookup_qualified=lookup_qualified,\n                )\n                for t in expr.items\n            ],\n            line=expr.line,\n            column=expr.column,\n        )\n    elif isinstance(expr, StrExpr):\n        return parse_type_string(expr.value, \"builtins.str\", expr.line, expr.column)\n    elif isinstance(expr, BytesExpr):\n        return parse_type_string(expr.value, \"builtins.bytes\", expr.line, expr.column)\n    elif isinstance(expr, UnaryExpr):\n        typ = expr_to_unanalyzed_type(\n            expr.expr, options, allow_new_syntax, lookup_qualified=lookup_qualified\n        )\n        if isinstance(typ, RawExpressionType):\n            if isinstance(typ.literal_value, int):\n                if expr.op == \"-\":\n                    typ.literal_value *= -1\n                    return typ\n                elif expr.op == \"+\":\n                    return typ\n        raise TypeTranslationError()\n    elif isinstance(expr, IntExpr):\n        return RawExpressionType(expr.value, \"builtins.int\", line=expr.line, column=expr.column)\n    elif isinstance(expr, FloatExpr):\n        # Floats are not valid parameters for RawExpressionType , so we just\n        # pass in 'None' for now. We'll report the appropriate error at a later stage.\n        return RawExpressionType(None, \"builtins.float\", line=expr.line, column=expr.column)\n    elif isinstance(expr, ComplexExpr):\n        # Same thing as above with complex numbers.\n        return RawExpressionType(None, \"builtins.complex\", line=expr.line, column=expr.column)\n    elif isinstance(expr, EllipsisExpr):\n        return EllipsisType(expr.line)\n    elif allow_unpack and isinstance(expr, StarExpr):\n        return UnpackType(\n            expr_to_unanalyzed_type(\n                expr.expr, options, allow_new_syntax, lookup_qualified=lookup_qualified\n            ),\n            from_star_syntax=True,\n        )\n    elif isinstance(expr, DictExpr):\n        if not expr.items:\n            raise TypeTranslationError()\n        items: dict[str, Type] = {}\n        extra_items_from = []\n        for item_name, value in expr.items:\n            if not isinstance(item_name, StrExpr):\n                if item_name is None:\n                    extra_items_from.append(\n                        expr_to_unanalyzed_type(\n                            value,\n                            options,\n                            allow_new_syntax,\n                            expr,\n                            lookup_qualified=lookup_qualified,\n                        )\n                    )\n                    continue\n                raise TypeTranslationError()\n            items[item_name.value] = expr_to_unanalyzed_type(\n                value, options, allow_new_syntax, expr, lookup_qualified=lookup_qualified\n            )\n        result = TypedDictType(\n            items, set(), set(), Instance(MISSING_FALLBACK, ()), expr.line, expr.column\n        )\n        result.extra_items_from = extra_items_from\n        return result\n    else:\n        raise TypeTranslationError()\n"
  },
  {
    "path": "mypy/fastparse.py",
    "content": "from __future__ import annotations\n\nimport re\nimport sys\nimport warnings\nfrom collections.abc import Callable, Sequence\nfrom typing import Any, Final, Literal, TypeVar, cast, overload\n\nfrom mypy import defaults, errorcodes as codes, message_registry\nfrom mypy.errors import Errors\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_NAMED_OPT,\n    ARG_OPT,\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    MISSING_FALLBACK,\n    PARAM_SPEC_KIND,\n    TYPE_VAR_KIND,\n    TYPE_VAR_TUPLE_KIND,\n    ArgKind,\n    Argument,\n    AssertStmt,\n    AssignmentExpr,\n    AssignmentStmt,\n    AwaitExpr,\n    Block,\n    BreakStmt,\n    BytesExpr,\n    CallExpr,\n    ClassDef,\n    ComparisonExpr,\n    ComplexExpr,\n    ConditionalExpr,\n    ContinueStmt,\n    Decorator,\n    DelStmt,\n    DictExpr,\n    DictionaryComprehension,\n    EllipsisExpr,\n    Expression,\n    ExpressionStmt,\n    FloatExpr,\n    ForStmt,\n    FuncDef,\n    GeneratorExpr,\n    GlobalDecl,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportBase,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    MatchStmt,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    Node,\n    NonlocalDecl,\n    OperatorAssignmentStmt,\n    OpExpr,\n    OverloadedFuncDef,\n    OverloadPart,\n    PassStmt,\n    RaiseStmt,\n    RefExpr,\n    ReturnStmt,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    Statement,\n    StrExpr,\n    SuperExpr,\n    TemplateStrExpr,\n    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAliasStmt,\n    TypeParam,\n    UnaryExpr,\n    Var,\n    WhileStmt,\n    WithStmt,\n    YieldExpr,\n    YieldFromExpr,\n    check_param_names,\n)\nfrom mypy.options import Options\nfrom mypy.patterns import (\n    AsPattern,\n    ClassPattern,\n    MappingPattern,\n    OrPattern,\n    SequencePattern,\n    SingletonPattern,\n    StarredPattern,\n    ValuePattern,\n)\nfrom mypy.reachability import infer_reachability_of_if_statement, mark_block_unreachable\nfrom mypy.sharedparse import argument_elide_name, special_function_elide_names\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.types import (\n    AnyType,\n    CallableArgument,\n    CallableType,\n    EllipsisType,\n    Instance,\n    ProperType,\n    RawExpressionType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeList,\n    TypeOfAny,\n    UnboundType,\n    UnionType,\n    UnpackType,\n)\nfrom mypy.util import bytes_to_human_readable_repr, unnamed_function\n\n# pull this into a final variable to make mypyc be quiet about the\n# the default argument warning\nPY_MINOR_VERSION: Final = sys.version_info[1]\n\nimport ast as ast3\nfrom ast import AST, Attribute, Call, FunctionType, Name, Starred, UAdd, UnaryOp, USub\n\n\ndef ast3_parse(\n    source: str | bytes, filename: str, mode: str, feature_version: int = PY_MINOR_VERSION\n) -> AST:\n    # Ignore warnings that look like:\n    #     <type_comment>:1: SyntaxWarning: invalid escape sequence '\\.'\n    # because `source` could be anything, including literals like r'(re\\.match)'\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\", SyntaxWarning)\n        return ast3.parse(\n            source,\n            filename,\n            mode,\n            type_comments=True,  # This works the magic\n            feature_version=feature_version,\n        )\n\n\nAstNode = ast3.expr | ast3.stmt | ast3.pattern | ast3.ExceptHandler\n\nif sys.version_info >= (3, 11):\n    TryStar = ast3.TryStar\nelse:\n    TryStar = Any\n\nif sys.version_info >= (3, 12):\n    ast_TypeAlias = ast3.TypeAlias\n    ast_ParamSpec = ast3.ParamSpec\n    ast_TypeVar = ast3.TypeVar\n    ast_TypeVarTuple = ast3.TypeVarTuple\nelse:\n    ast_TypeAlias = Any\n    ast_ParamSpec = Any\n    ast_TypeVar = Any\n    ast_TypeVarTuple = Any\n\nif sys.version_info >= (3, 14):\n    ast_TemplateStr = ast3.TemplateStr\n    ast_Interpolation = ast3.Interpolation\nelse:\n    ast_TemplateStr = Any\n    ast_Interpolation = Any\n\nN = TypeVar(\"N\", bound=Node)\n\n# There is no way to create reasonable fallbacks at this stage,\n# they must be patched later.\n_dummy_fallback: Final = Instance(MISSING_FALLBACK, [], -1)\n\nTYPE_IGNORE_PATTERN: Final = re.compile(r\"[^#]*#\\s*type:\\s*ignore\\s*(.*)\")\n\n\ndef parse(\n    source: str | bytes,\n    fnam: str,\n    module: str | None,\n    errors: Errors,\n    options: Options | None = None,\n) -> MypyFile:\n    \"\"\"Parse a source file, without doing any semantic analysis.\n\n    Return the parse tree. If errors is not provided, raise ParseError\n    on failure. Otherwise, use the errors object to report parse errors.\n    \"\"\"\n    ignore_errors = (options is not None and options.ignore_errors) or (\n        fnam in errors.ignored_files\n    )\n    # If errors are ignored, we can drop many function bodies to speed up type checking.\n    strip_function_bodies = ignore_errors and (options is None or not options.preserve_asts)\n\n    if options is None:\n        options = Options()\n    errors.set_file(fnam, module, options=options)\n    is_stub_file = fnam.endswith(\".pyi\")\n    if is_stub_file:\n        feature_version = defaults.PYTHON3_VERSION[1]\n        if options.python_version[0] == 3 and options.python_version[1] > feature_version:\n            feature_version = options.python_version[1]\n    else:\n        assert options.python_version[0] >= 3\n        feature_version = options.python_version[1]\n    try:\n        # Disable\n        # - deprecation warnings for 'invalid escape sequence' (Python 3.11 and below)\n        # - syntax warnings for 'invalid escape sequence' (3.12+) and 'return in finally' (3.14+)\n        with warnings.catch_warnings():\n            warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n            warnings.filterwarnings(\"ignore\", category=SyntaxWarning)\n            ast = ast3_parse(source, fnam, \"exec\", feature_version=feature_version)\n\n        tree = ASTConverter(\n            options=options,\n            is_stub=is_stub_file,\n            errors=errors,\n            strip_function_bodies=strip_function_bodies,\n            path=fnam,\n        ).visit(ast)\n\n    except RecursionError as e:\n        # For very complex expressions it is possible to hit recursion limit\n        # before reaching a leaf node.\n        # Should reject at top level instead at bottom, since bottom would already\n        # be at the threshold of the recursion limit, and may fail again later.\n        # E.G. x1+x2+x3+...+xn -> BinOp(left=BinOp(left=BinOp(left=...\n        try:\n            # But to prove that is the cause of this particular recursion error,\n            # try to walk the tree using builtin visitor\n            ast3.NodeVisitor().visit(ast)\n        except RecursionError:\n            errors.report(\n                -1, -1, \"Source expression too complex to parse\", blocker=False, code=codes.MISC\n            )\n\n            tree = MypyFile([], [], False, {})\n\n        else:\n            # re-raise original recursion error if it *can* be unparsed,\n            # maybe this is some other issue that shouldn't be silenced/misdirected\n            raise e\n\n    except SyntaxError as e:\n        message = e.msg\n        if feature_version > sys.version_info.minor and message.startswith(\"invalid syntax\"):\n            python_version_str = f\"{options.python_version[0]}.{options.python_version[1]}\"\n            message += f\"; you likely need to run mypy using Python {python_version_str} or newer\"\n        errors.report(\n            e.lineno if e.lineno is not None else -1,\n            e.offset,\n            re.sub(\n                r\"^(\\s*\\w)\", lambda m: m.group(1).upper(), message\n            ),  # Standardizing error message\n            blocker=True,\n            code=codes.SYNTAX,\n        )\n        tree = MypyFile([], [], False, {})\n\n    assert isinstance(tree, MypyFile)\n    return tree\n\n\ndef parse_type_ignore_tag(tag: str | None) -> list[str] | None:\n    \"\"\"Parse optional \"[code, ...]\" tag after \"# type: ignore\".\n\n    Return:\n     * [] if no tag was found (ignore all errors)\n     * list of ignored error codes if a tag was found\n     * None if the tag was invalid.\n    \"\"\"\n    if not tag or tag.strip() == \"\" or tag.strip().startswith(\"#\"):\n        # No tag -- ignore all errors.\n        return []\n    m = re.match(r\"\\s*\\[([^]#]*)\\]\\s*(#.*)?$\", tag)\n    if m is None:\n        # Invalid \"# type: ignore\" comment.\n        return None\n    return [stripped_code for code in m.group(1).split(\",\") if (stripped_code := code.strip())]\n\n\ndef parse_type_comment(\n    type_comment: str, line: int, column: int, errors: Errors | None\n) -> tuple[list[str] | None, ProperType | None]:\n    \"\"\"Parse type portion of a type comment (+ optional type ignore).\n\n    Return (ignore info, parsed type).\n    \"\"\"\n    try:\n        typ = ast3_parse(type_comment, \"<type_comment>\", \"eval\")\n    except SyntaxError:\n        if errors is not None:\n            stripped_type = type_comment.split(\"#\", 2)[0].strip()\n            err_msg = message_registry.TYPE_COMMENT_SYNTAX_ERROR_VALUE.format(stripped_type)\n            errors.report(line, column, err_msg.value, blocker=True, code=err_msg.code)\n            return None, None\n        else:\n            raise\n    else:\n        extra_ignore = TYPE_IGNORE_PATTERN.match(type_comment)\n        if extra_ignore:\n            tag: str | None = extra_ignore.group(1)\n            ignored: list[str] | None = parse_type_ignore_tag(tag)\n            if ignored is None:\n                if errors is not None:\n                    errors.report(\n                        line, column, message_registry.INVALID_TYPE_IGNORE.value, code=codes.SYNTAX\n                    )\n                else:\n                    raise SyntaxError\n        else:\n            ignored = None\n        assert isinstance(typ, ast3.Expression)\n        converted = TypeConverter(\n            errors, line=line, override_column=column, is_evaluated=False\n        ).visit(typ.body)\n        return ignored, converted\n\n\ndef parse_type_string(\n    expr_string: str, expr_fallback_name: str, line: int, column: int\n) -> ProperType:\n    \"\"\"Parses a type that was originally present inside of an explicit string.\n\n    For example, suppose we have the type `Foo[\"blah\"]`. We should parse the\n    string expression \"blah\" using this function.\n    \"\"\"\n    try:\n        _, node = parse_type_comment(f\"({expr_string})\", line=line, column=column, errors=None)\n        if isinstance(node, (UnboundType, UnionType)) and node.original_str_expr is None:\n            node.original_str_expr = expr_string\n            node.original_str_fallback = expr_fallback_name\n            return node\n        else:\n            return RawExpressionType(expr_string, expr_fallback_name, line, column)\n    except (SyntaxError, ValueError):\n        # Note: the parser will raise a `ValueError` instead of a SyntaxError if\n        # the string happens to contain things like \\x00.\n        return RawExpressionType(expr_string, expr_fallback_name, line, column)\n\n\ndef is_no_type_check_decorator(expr: ast3.expr) -> bool:\n    if isinstance(expr, Name):\n        return expr.id == \"no_type_check\"\n    elif isinstance(expr, Attribute):\n        if isinstance(expr.value, Name):\n            return expr.value.id == \"typing\" and expr.attr == \"no_type_check\"\n    return False\n\n\ndef find_disallowed_expression_in_annotation_scope(expr: ast3.expr | None) -> ast3.expr | None:\n    if expr is None:\n        return None\n    for node in ast3.walk(expr):\n        if isinstance(node, (ast3.Yield, ast3.YieldFrom, ast3.NamedExpr, ast3.Await)):\n            return node\n    return None\n\n\nclass ASTConverter:\n    def __init__(\n        self,\n        options: Options,\n        is_stub: bool,\n        errors: Errors,\n        *,\n        strip_function_bodies: bool,\n        path: str,\n    ) -> None:\n        # 'C' for class, 'D' for function signature, 'F' for function, 'L' for lambda\n        self.class_and_function_stack: list[Literal[\"C\", \"D\", \"F\", \"L\"]] = []\n        self.imports: list[ImportBase] = []\n\n        self.options = options\n        self.is_stub = is_stub\n        self.errors = errors\n        self.strip_function_bodies = strip_function_bodies\n        self.path = path\n\n        self.type_ignores: dict[int, list[str]] = {}\n        self.uses_template_strings = False\n\n        # Cache of visit_X methods keyed by type of visited object\n        self.visitor_cache: dict[type, Callable[[AST | None], Any]] = {}\n\n    def note(self, msg: str, line: int, column: int) -> None:\n        self.errors.report(line, column, msg, severity=\"note\", code=codes.SYNTAX)\n\n    def fail(self, msg: ErrorMessage, line: int, column: int, blocker: bool) -> None:\n        if blocker or not self.options.ignore_errors:\n            # Make sure self.errors reflects any type ignores that we have parsed\n            self.errors.set_file_ignored_lines(\n                self.path, self.type_ignores, self.options.ignore_errors\n            )\n            self.errors.report(line, column, msg.value, blocker=blocker, code=msg.code)\n\n    def fail_merge_overload(self, node: IfStmt) -> None:\n        self.fail(\n            message_registry.FAILED_TO_MERGE_OVERLOADS,\n            line=node.line,\n            column=node.column,\n            blocker=False,\n        )\n\n    def visit(self, node: AST | None) -> Any:\n        if node is None:\n            return None\n        typeobj = type(node)\n        visitor = self.visitor_cache.get(typeobj)\n        if visitor is None:\n            method = \"visit_\" + node.__class__.__name__\n            visitor = getattr(self, method)\n            self.visitor_cache[typeobj] = visitor\n\n        return visitor(node)\n\n    def set_line(self, node: N, n: AstNode) -> N:\n        node.line = n.lineno\n        node.column = n.col_offset\n        node.end_line = n.end_lineno\n        node.end_column = n.end_col_offset\n\n        return node\n\n    def translate_opt_expr_list(self, l: Sequence[AST | None]) -> list[Expression | None]:\n        res: list[Expression | None] = []\n        for e in l:\n            exp = self.visit(e)\n            res.append(exp)\n        return res\n\n    def translate_expr_list(self, l: Sequence[AST]) -> list[Expression]:\n        return cast(list[Expression], self.translate_opt_expr_list(l))\n\n    def get_lineno(self, node: ast3.expr | ast3.stmt) -> int:\n        if (\n            isinstance(node, (ast3.AsyncFunctionDef, ast3.ClassDef, ast3.FunctionDef))\n            and node.decorator_list\n        ):\n            return node.decorator_list[0].lineno\n        return node.lineno\n\n    def translate_stmt_list(\n        self,\n        stmts: Sequence[ast3.stmt],\n        *,\n        ismodule: bool = False,\n        can_strip: bool = False,\n        is_coroutine: bool = False,\n    ) -> list[Statement]:\n        # A \"# type: ignore\" comment before the first statement of a module\n        # ignores the whole module:\n        if (\n            ismodule\n            and stmts\n            and self.type_ignores\n            and (first := min(self.type_ignores)) < self.get_lineno(stmts[0])\n        ):\n            ignores = self.type_ignores.pop(first)\n            if ignores:\n                joined_ignores = \", \".join(ignores)\n                self.fail(\n                    message_registry.TYPE_IGNORE_WITH_ERRCODE_ON_MODULE.format(joined_ignores),\n                    line=first,\n                    column=0,\n                    blocker=False,\n                )\n            block = Block(self.fix_function_overloads(self.translate_stmt_list(stmts)))\n            self.set_block_lines(block, stmts)\n            mark_block_unreachable(block)\n            return [block]\n\n        stack = self.class_and_function_stack\n        # Fast case for stripping function bodies\n        if (\n            can_strip\n            and self.strip_function_bodies\n            and len(stack) == 1\n            and stack[0] == \"F\"\n            and not is_coroutine\n        ):\n            return []\n\n        res: list[Statement] = []\n        for stmt in stmts:\n            node = self.visit(stmt)\n            res.append(node)\n\n        # Slow case for stripping function bodies\n        if can_strip and self.strip_function_bodies:\n            if stack[-2:] == [\"C\", \"F\"]:\n                if is_possible_trivial_body(res):\n                    can_strip = False\n                else:\n                    # We only strip method bodies if they don't assign to an attribute, as\n                    # this may define an attribute which has an externally visible effect.\n                    visitor = FindAttributeAssign()\n                    for s in res:\n                        s.accept(visitor)\n                        if visitor.found:\n                            can_strip = False\n                            break\n\n            if can_strip and stack[-1] == \"F\" and is_coroutine:\n                # Yields inside an async function affect the return type and should not\n                # be stripped.\n                yield_visitor = FindYield()\n                for s in res:\n                    s.accept(yield_visitor)\n                    if yield_visitor.found:\n                        can_strip = False\n                        break\n\n            if can_strip:\n                return []\n        return res\n\n    def translate_type_comment(\n        self, n: ast3.stmt | ast3.arg, type_comment: str | None\n    ) -> ProperType | None:\n        if type_comment is None:\n            return None\n        else:\n            lineno = n.lineno\n            extra_ignore, typ = parse_type_comment(type_comment, lineno, n.col_offset, self.errors)\n            if extra_ignore is not None:\n                self.type_ignores[lineno] = extra_ignore\n            return typ\n\n    op_map: Final[dict[type[AST], str]] = {\n        ast3.Add: \"+\",\n        ast3.Sub: \"-\",\n        ast3.Mult: \"*\",\n        ast3.MatMult: \"@\",\n        ast3.Div: \"/\",\n        ast3.Mod: \"%\",\n        ast3.Pow: \"**\",\n        ast3.LShift: \"<<\",\n        ast3.RShift: \">>\",\n        ast3.BitOr: \"|\",\n        ast3.BitXor: \"^\",\n        ast3.BitAnd: \"&\",\n        ast3.FloorDiv: \"//\",\n    }\n\n    def from_operator(self, op: ast3.operator) -> str:\n        op_name = ASTConverter.op_map.get(type(op))\n        if op_name is None:\n            raise RuntimeError(\"Unknown operator \" + str(type(op)))\n        else:\n            return op_name\n\n    comp_op_map: Final[dict[type[AST], str]] = {\n        ast3.Gt: \">\",\n        ast3.Lt: \"<\",\n        ast3.Eq: \"==\",\n        ast3.GtE: \">=\",\n        ast3.LtE: \"<=\",\n        ast3.NotEq: \"!=\",\n        ast3.Is: \"is\",\n        ast3.IsNot: \"is not\",\n        ast3.In: \"in\",\n        ast3.NotIn: \"not in\",  # codespell:ignore notin\n    }\n\n    def from_comp_operator(self, op: ast3.cmpop) -> str:\n        op_name = ASTConverter.comp_op_map.get(type(op))\n        if op_name is None:\n            raise RuntimeError(\"Unknown comparison operator \" + str(type(op)))\n        else:\n            return op_name\n\n    def set_block_lines(self, b: Block, stmts: Sequence[ast3.stmt]) -> None:\n        first, last = stmts[0], stmts[-1]\n        b.line = first.lineno\n        b.column = first.col_offset\n        b.end_line = last.end_lineno\n        b.end_column = last.end_col_offset\n        if not b.body:\n            return\n        new_first = b.body[0]\n        if isinstance(new_first, (Decorator, OverloadedFuncDef)):\n            # Decorated function lines are different between Python versions.\n            # copy the normalization we do for them to block first lines.\n            b.line = new_first.line\n            b.column = new_first.column\n\n    def as_block(self, stmts: list[ast3.stmt]) -> Block | None:\n        b = None\n        if stmts:\n            b = Block(self.fix_function_overloads(self.translate_stmt_list(stmts)))\n            self.set_block_lines(b, stmts)\n        return b\n\n    def as_required_block(\n        self, stmts: list[ast3.stmt], *, can_strip: bool = False, is_coroutine: bool = False\n    ) -> Block:\n        assert stmts  # must be non-empty\n        b = Block(\n            self.fix_function_overloads(\n                self.translate_stmt_list(stmts, can_strip=can_strip, is_coroutine=is_coroutine)\n            )\n        )\n        self.set_block_lines(b, stmts)\n        return b\n\n    def fix_function_overloads(self, stmts: list[Statement]) -> list[Statement]:\n        ret: list[Statement] = []\n        current_overload: list[OverloadPart] = []\n        current_overload_name: str | None = None\n        last_unconditional_func_def: str | None = None\n        last_if_stmt: IfStmt | None = None\n        last_if_overload: Decorator | FuncDef | OverloadedFuncDef | None = None\n        last_if_stmt_overload_name: str | None = None\n        last_if_unknown_truth_value: IfStmt | None = None\n        skipped_if_stmts: list[IfStmt] = []\n        for stmt in stmts:\n            if_overload_name: str | None = None\n            if_block_with_overload: Block | None = None\n            if_unknown_truth_value: IfStmt | None = None\n            if isinstance(stmt, IfStmt):\n                # Check IfStmt block to determine if function overloads can be merged\n                if_overload_name = self._check_ifstmt_for_overloads(stmt, current_overload_name)\n                if if_overload_name is not None:\n                    if_block_with_overload, if_unknown_truth_value = (\n                        self._get_executable_if_block_with_overloads(stmt)\n                    )\n\n            if (\n                current_overload_name is not None\n                and isinstance(stmt, (Decorator, FuncDef))\n                and stmt.name == current_overload_name\n            ):\n                if last_if_stmt is not None:\n                    skipped_if_stmts.append(last_if_stmt)\n                if last_if_overload is not None:\n                    # Last stmt was an IfStmt with same overload name\n                    # Add overloads to current_overload\n                    if isinstance(last_if_overload, OverloadedFuncDef):\n                        current_overload.extend(last_if_overload.items)\n                    else:\n                        current_overload.append(last_if_overload)\n                    last_if_stmt, last_if_overload = None, None\n                if last_if_unknown_truth_value:\n                    self.fail_merge_overload(last_if_unknown_truth_value)\n                    last_if_unknown_truth_value = None\n                current_overload.append(stmt)\n                if isinstance(stmt, FuncDef):\n                    # This is, strictly speaking, wrong: there might be a decorated\n                    # implementation. However, it only affects the error message we show:\n                    # ideally it's \"already defined\", but \"implementation must come last\"\n                    # is also reasonable.\n                    # TODO: can we get rid of this completely and just always emit\n                    # \"implementation must come last\" instead?\n                    last_unconditional_func_def = stmt.name\n            elif (\n                current_overload_name is not None\n                and isinstance(stmt, IfStmt)\n                and if_overload_name == current_overload_name\n                and last_unconditional_func_def != current_overload_name\n            ):\n                # IfStmt only contains stmts relevant to current_overload.\n                # Check if stmts are reachable and add them to current_overload,\n                # otherwise skip IfStmt to allow subsequent overload\n                # or function definitions.\n                skipped_if_stmts.append(stmt)\n                if if_block_with_overload is None:\n                    if if_unknown_truth_value is not None:\n                        self.fail_merge_overload(if_unknown_truth_value)\n                    continue\n                if last_if_overload is not None:\n                    # Last stmt was an IfStmt with same overload name\n                    # Add overloads to current_overload\n                    if isinstance(last_if_overload, OverloadedFuncDef):\n                        current_overload.extend(last_if_overload.items)\n                    else:\n                        current_overload.append(last_if_overload)\n                    last_if_stmt, last_if_overload = None, None\n                if isinstance(if_block_with_overload.body[-1], OverloadedFuncDef):\n                    skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1]))\n                    current_overload.extend(if_block_with_overload.body[-1].items)\n                else:\n                    current_overload.append(\n                        cast(Decorator | FuncDef, if_block_with_overload.body[0])\n                    )\n            else:\n                if last_if_stmt is not None:\n                    ret.append(last_if_stmt)\n                    last_if_stmt_overload_name = current_overload_name\n                    last_if_stmt, last_if_overload = None, None\n                    last_if_unknown_truth_value = None\n\n                if current_overload and current_overload_name == last_if_stmt_overload_name:\n                    # Remove last stmt (IfStmt) from ret if the overload names matched\n                    # Only happens if no executable block had been found in IfStmt\n                    popped = ret.pop()\n                    assert isinstance(popped, IfStmt)\n                    skipped_if_stmts.append(popped)\n                if current_overload and skipped_if_stmts:\n                    # Add bare IfStmt (without overloads) to ret\n                    # Required for mypy to be able to still check conditions\n                    for if_stmt in skipped_if_stmts:\n                        self._strip_contents_from_if_stmt(if_stmt)\n                        ret.append(if_stmt)\n                    skipped_if_stmts = []\n                if len(current_overload) == 1:\n                    ret.append(current_overload[0])\n                elif len(current_overload) > 1:\n                    ret.append(OverloadedFuncDef(current_overload))\n\n                # If we have multiple decorated functions named \"_\" next to each, we want to treat\n                # them as a series of regular FuncDefs instead of one OverloadedFuncDef because\n                # most of mypy/mypyc assumes that all the functions in an OverloadedFuncDef are\n                # related, but multiple underscore functions next to each other aren't necessarily\n                # related\n                last_unconditional_func_def = None\n                if isinstance(stmt, Decorator) and not unnamed_function(stmt.name):\n                    current_overload = [stmt]\n                    current_overload_name = stmt.name\n                elif isinstance(stmt, IfStmt) and if_overload_name is not None:\n                    current_overload = []\n                    current_overload_name = if_overload_name\n                    last_if_stmt = stmt\n                    last_if_stmt_overload_name = None\n                    if if_block_with_overload is not None:\n                        skipped_if_stmts.extend(\n                            cast(list[IfStmt], if_block_with_overload.body[:-1])\n                        )\n                        last_if_overload = cast(\n                            Decorator | FuncDef | OverloadedFuncDef,\n                            if_block_with_overload.body[-1],\n                        )\n                    last_if_unknown_truth_value = if_unknown_truth_value\n                else:\n                    current_overload = []\n                    current_overload_name = None\n                    ret.append(stmt)\n\n        if current_overload and skipped_if_stmts:\n            # Add bare IfStmt (without overloads) to ret\n            # Required for mypy to be able to still check conditions\n            for if_stmt in skipped_if_stmts:\n                self._strip_contents_from_if_stmt(if_stmt)\n                ret.append(if_stmt)\n        if len(current_overload) == 1:\n            ret.append(current_overload[0])\n        elif len(current_overload) > 1:\n            ret.append(OverloadedFuncDef(current_overload))\n        elif last_if_overload is not None:\n            ret.append(last_if_overload)\n        elif last_if_stmt is not None:\n            ret.append(last_if_stmt)\n        return ret\n\n    def _check_ifstmt_for_overloads(\n        self, stmt: IfStmt, current_overload_name: str | None = None\n    ) -> str | None:\n        \"\"\"Check if IfStmt contains only overloads with the same name.\n        Return overload_name if found, None otherwise.\n        \"\"\"\n        # Check that block only contains a single Decorator, FuncDef, or OverloadedFuncDef.\n        # Multiple overloads have already been merged as OverloadedFuncDef.\n        if not (\n            len(stmt.body[0].body) == 1\n            and (\n                isinstance(stmt.body[0].body[0], (Decorator, OverloadedFuncDef))\n                or current_overload_name is not None\n                and isinstance(stmt.body[0].body[0], FuncDef)\n            )\n            or len(stmt.body[0].body) > 1\n            and isinstance(stmt.body[0].body[-1], OverloadedFuncDef)\n            and all(self._is_stripped_if_stmt(if_stmt) for if_stmt in stmt.body[0].body[:-1])\n        ):\n            return None\n\n        overload_name = cast(Decorator | FuncDef | OverloadedFuncDef, stmt.body[0].body[-1]).name\n        if stmt.else_body is None:\n            return overload_name\n\n        if len(stmt.else_body.body) == 1:\n            # For elif: else_body contains an IfStmt itself -> do a recursive check.\n            if (\n                isinstance(stmt.else_body.body[0], (Decorator, FuncDef, OverloadedFuncDef))\n                and stmt.else_body.body[0].name == overload_name\n            ):\n                return overload_name\n            if (\n                isinstance(stmt.else_body.body[0], IfStmt)\n                and self._check_ifstmt_for_overloads(stmt.else_body.body[0], current_overload_name)\n                == overload_name\n            ):\n                return overload_name\n\n        return None\n\n    def _get_executable_if_block_with_overloads(\n        self, stmt: IfStmt\n    ) -> tuple[Block | None, IfStmt | None]:\n        \"\"\"Return block from IfStmt that will get executed.\n\n        Return\n            0 -> A block if sure that alternative blocks are unreachable.\n            1 -> An IfStmt if the reachability of it can't be inferred,\n                 i.e. the truth value is unknown.\n        \"\"\"\n        infer_reachability_of_if_statement(stmt, self.options)\n        if stmt.else_body is None and stmt.body[0].is_unreachable is True:\n            # always False condition with no else\n            return None, None\n        if (\n            stmt.else_body is None\n            or stmt.body[0].is_unreachable is False\n            and stmt.else_body.is_unreachable is False\n        ):\n            # The truth value is unknown, thus not conclusive\n            return None, stmt\n        if stmt.else_body.is_unreachable is True:\n            # else_body will be set unreachable if condition is always True\n            return stmt.body[0], None\n        if stmt.body[0].is_unreachable is True:\n            # body will be set unreachable if condition is always False\n            # else_body can contain an IfStmt itself (for elif) -> do a recursive check\n            if isinstance(stmt.else_body.body[0], IfStmt):\n                return self._get_executable_if_block_with_overloads(stmt.else_body.body[0])\n            return stmt.else_body, None\n        return None, stmt\n\n    def _strip_contents_from_if_stmt(self, stmt: IfStmt) -> None:\n        \"\"\"Remove contents from IfStmt.\n\n        Needed to still be able to check the conditions after the contents\n        have been merged with the surrounding function overloads.\n        \"\"\"\n        if len(stmt.body) == 1:\n            stmt.body[0].body = []\n        if stmt.else_body and len(stmt.else_body.body) == 1:\n            if isinstance(stmt.else_body.body[0], IfStmt):\n                self._strip_contents_from_if_stmt(stmt.else_body.body[0])\n            else:\n                stmt.else_body.body = []\n\n    def _is_stripped_if_stmt(self, stmt: Statement) -> bool:\n        \"\"\"Check stmt to make sure it is a stripped IfStmt.\n\n        See also: _strip_contents_from_if_stmt\n        \"\"\"\n        if not isinstance(stmt, IfStmt):\n            return False\n\n        if not (len(stmt.body) == 1 and len(stmt.body[0].body) == 0):\n            # Body not empty\n            return False\n\n        if not stmt.else_body or len(stmt.else_body.body) == 0:\n            # No or empty else_body\n            return True\n\n        # For elif, IfStmt are stored recursively in else_body\n        return self._is_stripped_if_stmt(stmt.else_body.body[0])\n\n    def translate_module_id(self, id: str) -> str:\n        \"\"\"Return the actual, internal module id for a source text id.\"\"\"\n        if id == self.options.custom_typing_module:\n            return \"typing\"\n        return id\n\n    def visit_Module(self, mod: ast3.Module) -> MypyFile:\n        self.type_ignores = {}\n        self.uses_template_strings = False\n        for ti in mod.type_ignores:\n            parsed = parse_type_ignore_tag(ti.tag)\n            if parsed is not None:\n                self.type_ignores[ti.lineno] = parsed\n            else:\n                self.fail(message_registry.INVALID_TYPE_IGNORE, ti.lineno, -1, blocker=False)\n\n        body = self.fix_function_overloads(self.translate_stmt_list(mod.body, ismodule=True))\n\n        ret = MypyFile(body, self.imports, False, ignored_lines=self.type_ignores)\n        ret.is_stub = self.is_stub\n        ret.path = self.path\n        ret.uses_template_strings = self.uses_template_strings\n        return ret\n\n    # --- stmt ---\n    # FunctionDef(identifier name, arguments args,\n    #             stmt* body, expr* decorator_list, expr? returns, string? type_comment)\n    # arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults,\n    #              arg? kwarg, expr* defaults)\n    def visit_FunctionDef(self, n: ast3.FunctionDef) -> FuncDef | Decorator:\n        return self.do_func_def(n)\n\n    # AsyncFunctionDef(identifier name, arguments args,\n    #                  stmt* body, expr* decorator_list, expr? returns, string? type_comment)\n    def visit_AsyncFunctionDef(self, n: ast3.AsyncFunctionDef) -> FuncDef | Decorator:\n        return self.do_func_def(n, is_coroutine=True)\n\n    def do_func_def(\n        self, n: ast3.FunctionDef | ast3.AsyncFunctionDef, is_coroutine: bool = False\n    ) -> FuncDef | Decorator:\n        \"\"\"Helper shared between visit_FunctionDef and visit_AsyncFunctionDef.\"\"\"\n        self.class_and_function_stack.append(\"D\")\n        no_type_check = bool(\n            n.decorator_list and any(is_no_type_check_decorator(d) for d in n.decorator_list)\n        )\n\n        lineno = n.lineno\n        args = self.transform_args(n.args, lineno, no_type_check=no_type_check)\n        if self.options.pos_only_special_methods and special_function_elide_names(n.name):\n            for arg in args:\n                arg.pos_only = True\n\n        arg_kinds = [arg.kind for arg in args]\n        arg_names = [None if arg.pos_only else arg.variable.name for arg in args]\n        # Type parameters, if using new syntax for generics (PEP 695)\n        explicit_type_params: list[TypeParam] | None = None\n\n        arg_types: list[Type | None] = []\n        if no_type_check:\n            arg_types = [None] * len(args)\n            return_type = None\n        elif n.type_comment is not None:\n            try:\n                func_type_ast = ast3_parse(n.type_comment, \"<func_type>\", \"func_type\")\n                assert isinstance(func_type_ast, FunctionType)\n                # for ellipsis arg\n                if (\n                    len(func_type_ast.argtypes) == 1\n                    and isinstance(func_type_ast.argtypes[0], ast3.Constant)\n                    and func_type_ast.argtypes[0].value is Ellipsis\n                ):\n                    if n.returns:\n                        # PEP 484 disallows both type annotations and type comments\n                        self.fail(\n                            message_registry.DUPLICATE_TYPE_SIGNATURES,\n                            lineno,\n                            n.col_offset,\n                            blocker=False,\n                        )\n                    arg_types = [\n                        (\n                            a.type_annotation\n                            if a.type_annotation is not None\n                            else AnyType(TypeOfAny.unannotated)\n                        )\n                        for a in args\n                    ]\n                else:\n                    # PEP 484 disallows both type annotations and type comments\n                    if n.returns or any(a.type_annotation is not None for a in args):\n                        self.fail(\n                            message_registry.DUPLICATE_TYPE_SIGNATURES,\n                            lineno,\n                            n.col_offset,\n                            blocker=False,\n                        )\n                    translated_args: list[Type] = TypeConverter(\n                        self.errors, line=lineno, override_column=n.col_offset\n                    ).translate_expr_list(func_type_ast.argtypes)\n                    # Use a cast to work around `list` invariance\n                    arg_types = cast(list[Type | None], translated_args)\n                return_type = TypeConverter(self.errors, line=lineno).visit(func_type_ast.returns)\n\n                # add implicit self type\n                in_method_scope = self.class_and_function_stack[-2:] == [\"C\", \"D\"]\n                if in_method_scope and len(arg_types) < len(args):\n                    arg_types.insert(0, AnyType(TypeOfAny.special_form))\n            except SyntaxError:\n                stripped_type = n.type_comment.split(\"#\", 2)[0].strip()\n                err_msg = message_registry.TYPE_COMMENT_SYNTAX_ERROR_VALUE.format(stripped_type)\n                self.fail(err_msg, lineno, n.col_offset, blocker=False)\n                if n.type_comment and n.type_comment[0] not in [\"(\", \"#\"]:\n                    self.note(\n                        \"Suggestion: wrap argument types in parentheses\", lineno, n.col_offset\n                    )\n                arg_types = [AnyType(TypeOfAny.from_error)] * len(args)\n                return_type = AnyType(TypeOfAny.from_error)\n        else:\n            if sys.version_info >= (3, 12) and n.type_params:\n                explicit_type_params = self.translate_type_params(n.type_params)\n\n            arg_types = [a.type_annotation for a in args]\n            return_type = TypeConverter(\n                self.errors, line=n.returns.lineno if n.returns else lineno\n            ).visit(n.returns)\n\n        for arg, arg_type in zip(args, arg_types):\n            self.set_type_optional(arg_type, arg.initializer)\n\n        func_type = None\n        if any(arg_types) or return_type:\n            if len(arg_types) != 1 and any(isinstance(t, EllipsisType) for t in arg_types):\n                self.fail(\n                    message_registry.ELLIPSIS_WITH_OTHER_TYPEPARAMS,\n                    lineno,\n                    n.col_offset,\n                    blocker=False,\n                )\n            elif len(arg_types) > len(arg_kinds):\n                self.fail(\n                    message_registry.TYPE_SIGNATURE_TOO_MANY_PARAMS,\n                    lineno,\n                    n.col_offset,\n                    blocker=False,\n                )\n            elif len(arg_types) < len(arg_kinds):\n                self.fail(\n                    message_registry.TYPE_SIGNATURE_TOO_FEW_PARAMS,\n                    lineno,\n                    n.col_offset,\n                    blocker=False,\n                )\n            else:\n                func_type = CallableType(\n                    [a if a is not None else AnyType(TypeOfAny.unannotated) for a in arg_types],\n                    arg_kinds,\n                    arg_names,\n                    return_type if return_type is not None else AnyType(TypeOfAny.unannotated),\n                    _dummy_fallback,\n                )\n\n        # End position is always the same.\n        end_line = n.end_lineno\n        end_column = n.end_col_offset\n\n        self.class_and_function_stack.pop()\n        self.class_and_function_stack.append(\"F\")\n        body = self.as_required_block(n.body, can_strip=True, is_coroutine=is_coroutine)\n        func_def = FuncDef(n.name, args, body, func_type, explicit_type_params)\n        if isinstance(func_def.type, CallableType):\n            # semanal.py does some in-place modifications we want to avoid\n            func_def.unanalyzed_type = func_def.type.copy_modified()\n        if is_coroutine:\n            func_def.is_coroutine = True\n        if func_type is not None:\n            func_type.definition = func_def\n            func_type.set_line(lineno)\n\n        if n.decorator_list:\n            var = Var(func_def.name)\n            var.is_ready = False\n            var.set_line(lineno)\n\n            func_def.is_decorated = True\n            self.set_line(func_def, n)\n\n            deco = Decorator(func_def, self.translate_expr_list(n.decorator_list), var)\n            first = n.decorator_list[0]\n            deco.set_line(first.lineno, first.col_offset, end_line, end_column)\n            retval: FuncDef | Decorator = deco\n        else:\n            self.set_line(func_def, n)\n            retval = func_def\n        if self.options.include_docstrings:\n            func_def.docstring = ast3.get_docstring(n, clean=False)\n        self.class_and_function_stack.pop()\n        return retval\n\n    def set_type_optional(self, type: Type | None, initializer: Expression | None) -> None:\n        if not self.options.implicit_optional:\n            return\n        # Indicate that type should be wrapped in an Optional if arg is initialized to None.\n        optional = isinstance(initializer, NameExpr) and initializer.name == \"None\"\n        if isinstance(type, UnboundType):\n            type.optional = optional\n\n    def transform_args(\n        self, args: ast3.arguments, line: int, no_type_check: bool = False\n    ) -> list[Argument]:\n        new_args = []\n        names: list[ast3.arg] = []\n        posonlyargs = args.posonlyargs\n        args_args = posonlyargs + args.args\n        args_defaults = args.defaults\n        num_no_defaults = len(args_args) - len(args_defaults)\n        # positional arguments without defaults\n        for i, a in enumerate(args_args[:num_no_defaults]):\n            pos_only = i < len(posonlyargs)\n            new_args.append(self.make_argument(a, None, ARG_POS, no_type_check, pos_only))\n            names.append(a)\n\n        # positional arguments with defaults\n        for i, (a, d) in enumerate(zip(args_args[num_no_defaults:], args_defaults)):\n            pos_only = num_no_defaults + i < len(posonlyargs)\n            new_args.append(self.make_argument(a, d, ARG_OPT, no_type_check, pos_only))\n            names.append(a)\n\n        # *arg\n        if args.vararg is not None:\n            new_args.append(self.make_argument(args.vararg, None, ARG_STAR, no_type_check))\n            names.append(args.vararg)\n\n        # keyword-only arguments with defaults\n        for a, kd in zip(args.kwonlyargs, args.kw_defaults):\n            new_args.append(\n                self.make_argument(\n                    a, kd, ARG_NAMED if kd is None else ARG_NAMED_OPT, no_type_check\n                )\n            )\n            names.append(a)\n\n        # **kwarg\n        if args.kwarg is not None:\n            new_args.append(self.make_argument(args.kwarg, None, ARG_STAR2, no_type_check))\n            names.append(args.kwarg)\n\n        check_param_names([arg.variable.name for arg in new_args], names, self.fail_arg)\n\n        return new_args\n\n    def make_argument(\n        self,\n        arg: ast3.arg,\n        default: ast3.expr | None,\n        kind: ArgKind,\n        no_type_check: bool,\n        pos_only: bool = False,\n    ) -> Argument:\n        if no_type_check:\n            arg_type = None\n        else:\n            annotation = arg.annotation\n            type_comment = arg.type_comment\n            if annotation is not None and type_comment is not None:\n                self.fail(\n                    message_registry.DUPLICATE_TYPE_SIGNATURES,\n                    arg.lineno,\n                    arg.col_offset,\n                    blocker=False,\n                )\n            arg_type = None\n            if annotation is not None:\n                arg_type = TypeConverter(self.errors, line=arg.lineno).visit(annotation)\n            else:\n                arg_type = self.translate_type_comment(arg, type_comment)\n        if argument_elide_name(arg.arg):\n            pos_only = True\n\n        var = Var(arg.arg, arg_type)\n        var.is_inferred = False\n        var.is_argument = True\n        argument = Argument(var, arg_type, self.visit(default), kind, pos_only)\n        argument.set_line(arg.lineno, arg.col_offset, arg.end_lineno, arg.end_col_offset)\n        return argument\n\n    def fail_arg(self, msg: str, arg: ast3.arg) -> None:\n        self.fail(ErrorMessage(msg), arg.lineno, arg.col_offset, blocker=True)\n\n    # ClassDef(identifier name,\n    #  expr* bases,\n    #  keyword* keywords,\n    #  stmt* body,\n    #  expr* decorator_list)\n    def visit_ClassDef(self, n: ast3.ClassDef) -> ClassDef:\n        self.class_and_function_stack.append(\"C\")\n        keywords = [(kw.arg, self.visit(kw.value)) for kw in n.keywords if kw.arg]\n\n        # Type parameters, if using new syntax for generics (PEP 695)\n        explicit_type_params: list[TypeParam] | None = None\n\n        if sys.version_info >= (3, 12) and n.type_params:\n            explicit_type_params = self.translate_type_params(n.type_params)\n\n        cdef = ClassDef(\n            n.name,\n            self.as_required_block(n.body),\n            None,\n            self.translate_expr_list(n.bases),\n            metaclass=dict(keywords).get(\"metaclass\"),\n            keywords=keywords,\n            type_args=explicit_type_params,\n        )\n        cdef.decorators = self.translate_expr_list(n.decorator_list)\n        self.set_line(cdef, n)\n\n        if self.options.include_docstrings:\n            cdef.docstring = ast3.get_docstring(n, clean=False)\n        cdef.column = n.col_offset\n        cdef.end_line = n.end_lineno\n        cdef.end_column = n.end_col_offset\n        self.class_and_function_stack.pop()\n        return cdef\n\n    def validate_type_param(self, type_param: ast_TypeVar) -> None:\n        incorrect_expr = find_disallowed_expression_in_annotation_scope(type_param.bound)\n        if incorrect_expr is None:\n            return\n        if isinstance(incorrect_expr, (ast3.Yield, ast3.YieldFrom)):\n            self.fail(\n                message_registry.TYPE_VAR_YIELD_EXPRESSION_IN_BOUND,\n                type_param.lineno,\n                type_param.col_offset,\n                blocker=True,\n            )\n        if isinstance(incorrect_expr, ast3.NamedExpr):\n            self.fail(\n                message_registry.TYPE_VAR_NAMED_EXPRESSION_IN_BOUND,\n                type_param.lineno,\n                type_param.col_offset,\n                blocker=True,\n            )\n        if isinstance(incorrect_expr, ast3.Await):\n            self.fail(\n                message_registry.TYPE_VAR_AWAIT_EXPRESSION_IN_BOUND,\n                type_param.lineno,\n                type_param.col_offset,\n                blocker=True,\n            )\n\n    def translate_type_params(self, type_params: list[Any]) -> list[TypeParam]:\n        explicit_type_params = []\n        for p in type_params:\n            bound: Type | None = None\n            values: list[Type] = []\n            default: Type | None = None\n            if sys.version_info >= (3, 13):\n                default = TypeConverter(self.errors, line=p.lineno).visit(p.default_value)\n            if isinstance(p, ast_ParamSpec):  # type: ignore[misc]\n                explicit_type_params.append(TypeParam(p.name, PARAM_SPEC_KIND, None, [], default))\n            elif isinstance(p, ast_TypeVarTuple):  # type: ignore[misc]\n                explicit_type_params.append(\n                    TypeParam(p.name, TYPE_VAR_TUPLE_KIND, None, [], default)\n                )\n            else:\n                if isinstance(p.bound, ast3.Tuple):\n                    if len(p.bound.elts) < 2:\n                        self.fail(\n                            message_registry.TYPE_VAR_TOO_FEW_CONSTRAINED_TYPES,\n                            p.lineno,\n                            p.col_offset,\n                            blocker=False,\n                        )\n                    else:\n                        conv = TypeConverter(self.errors, line=p.lineno)\n                        values = [conv.visit(t) for t in p.bound.elts]\n                elif p.bound is not None:\n                    self.validate_type_param(p)\n                    bound = TypeConverter(self.errors, line=p.lineno).visit(p.bound)\n                explicit_type_params.append(\n                    TypeParam(p.name, TYPE_VAR_KIND, bound, values, default)\n                )\n        return explicit_type_params\n\n    # Return(expr? value)\n    def visit_Return(self, n: ast3.Return) -> ReturnStmt:\n        node = ReturnStmt(self.visit(n.value))\n        return self.set_line(node, n)\n\n    # Delete(expr* targets)\n    def visit_Delete(self, n: ast3.Delete) -> DelStmt:\n        if len(n.targets) > 1:\n            tup = TupleExpr(self.translate_expr_list(n.targets))\n            tup.set_line(n.lineno)\n            node = DelStmt(tup)\n        else:\n            node = DelStmt(self.visit(n.targets[0]))\n        return self.set_line(node, n)\n\n    # Assign(expr* targets, expr? value, string? type_comment, expr? annotation)\n    def visit_Assign(self, n: ast3.Assign) -> AssignmentStmt:\n        lvalues = self.translate_expr_list(n.targets)\n        rvalue = self.visit(n.value)\n        typ = self.translate_type_comment(n, n.type_comment)\n        s = AssignmentStmt(lvalues, rvalue, type=typ, new_syntax=False)\n        return self.set_line(s, n)\n\n    # AnnAssign(expr target, expr annotation, expr? value, int simple)\n    def visit_AnnAssign(self, n: ast3.AnnAssign) -> AssignmentStmt:\n        line = n.lineno\n        if n.value is None:  # always allow 'x: int'\n            rvalue: Expression = TempNode(AnyType(TypeOfAny.special_form), no_rhs=True)\n            self.set_line(rvalue, n)\n        else:\n            rvalue = self.visit(n.value)\n        typ = TypeConverter(self.errors, line=line).visit(n.annotation)\n        assert typ is not None\n        typ.column = n.annotation.col_offset\n        s = AssignmentStmt([self.visit(n.target)], rvalue, type=typ, new_syntax=True)\n        return self.set_line(s, n)\n\n    # AugAssign(expr target, operator op, expr value)\n    def visit_AugAssign(self, n: ast3.AugAssign) -> OperatorAssignmentStmt:\n        s = OperatorAssignmentStmt(\n            self.from_operator(n.op), self.visit(n.target), self.visit(n.value)\n        )\n        return self.set_line(s, n)\n\n    # For(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)\n    def visit_For(self, n: ast3.For) -> ForStmt:\n        target_type = self.translate_type_comment(n, n.type_comment)\n        node = ForStmt(\n            self.visit(n.target),\n            self.visit(n.iter),\n            self.as_required_block(n.body),\n            self.as_block(n.orelse),\n            target_type,\n        )\n        return self.set_line(node, n)\n\n    # AsyncFor(expr target, expr iter, stmt* body, stmt* orelse, string? type_comment)\n    def visit_AsyncFor(self, n: ast3.AsyncFor) -> ForStmt:\n        target_type = self.translate_type_comment(n, n.type_comment)\n        node = ForStmt(\n            self.visit(n.target),\n            self.visit(n.iter),\n            self.as_required_block(n.body),\n            self.as_block(n.orelse),\n            target_type,\n        )\n        node.is_async = True\n        return self.set_line(node, n)\n\n    # While(expr test, stmt* body, stmt* orelse)\n    def visit_While(self, n: ast3.While) -> WhileStmt:\n        node = WhileStmt(\n            self.visit(n.test), self.as_required_block(n.body), self.as_block(n.orelse)\n        )\n        return self.set_line(node, n)\n\n    # If(expr test, stmt* body, stmt* orelse)\n    def visit_If(self, n: ast3.If) -> IfStmt:\n        node = IfStmt(\n            [self.visit(n.test)], [self.as_required_block(n.body)], self.as_block(n.orelse)\n        )\n        return self.set_line(node, n)\n\n    # With(withitem* items, stmt* body, string? type_comment)\n    def visit_With(self, n: ast3.With) -> WithStmt:\n        target_type = self.translate_type_comment(n, n.type_comment)\n        node = WithStmt(\n            [self.visit(i.context_expr) for i in n.items],\n            [self.visit(i.optional_vars) for i in n.items],\n            self.as_required_block(n.body),\n            target_type,\n        )\n        return self.set_line(node, n)\n\n    # AsyncWith(withitem* items, stmt* body, string? type_comment)\n    def visit_AsyncWith(self, n: ast3.AsyncWith) -> WithStmt:\n        target_type = self.translate_type_comment(n, n.type_comment)\n        s = WithStmt(\n            [self.visit(i.context_expr) for i in n.items],\n            [self.visit(i.optional_vars) for i in n.items],\n            self.as_required_block(n.body),\n            target_type,\n        )\n        s.is_async = True\n        return self.set_line(s, n)\n\n    # Raise(expr? exc, expr? cause)\n    def visit_Raise(self, n: ast3.Raise) -> RaiseStmt:\n        node = RaiseStmt(self.visit(n.exc), self.visit(n.cause))\n        return self.set_line(node, n)\n\n    # Try(stmt* body, excepthandler* handlers, stmt* orelse, stmt* finalbody)\n    def visit_Try(self, n: ast3.Try) -> TryStmt:\n        vs = [\n            self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers\n        ]\n        types = [self.visit(h.type) for h in n.handlers]\n        handlers = [self.as_required_block(h.body) for h in n.handlers]\n\n        node = TryStmt(\n            self.as_required_block(n.body),\n            vs,\n            types,\n            handlers,\n            self.as_block(n.orelse),\n            self.as_block(n.finalbody),\n        )\n        return self.set_line(node, n)\n\n    def visit_TryStar(self, n: TryStar) -> TryStmt:\n        vs = [\n            self.set_line(NameExpr(h.name), h) if h.name is not None else None for h in n.handlers\n        ]\n        types = [self.visit(h.type) for h in n.handlers]\n        handlers = [self.as_required_block(h.body) for h in n.handlers]\n\n        node = TryStmt(\n            self.as_required_block(n.body),\n            vs,\n            types,\n            handlers,\n            self.as_block(n.orelse),\n            self.as_block(n.finalbody),\n        )\n        node.is_star = True\n        return self.set_line(node, n)\n\n    # Assert(expr test, expr? msg)\n    def visit_Assert(self, n: ast3.Assert) -> AssertStmt:\n        node = AssertStmt(self.visit(n.test), self.visit(n.msg))\n        return self.set_line(node, n)\n\n    # Import(alias* names)\n    def visit_Import(self, n: ast3.Import) -> Import:\n        names: list[tuple[str, str | None]] = []\n        for alias in n.names:\n            name = self.translate_module_id(alias.name)\n            asname = alias.asname\n            if asname is None and name != alias.name:\n                # if the module name has been translated (and it's not already\n                # an explicit import-as), make it an implicit import-as the\n                # original name\n                asname = alias.name\n            names.append((name, asname))\n        i = Import(names)\n        self.imports.append(i)\n        return self.set_line(i, n)\n\n    # ImportFrom(identifier? module, alias* names, int? level)\n    def visit_ImportFrom(self, n: ast3.ImportFrom) -> ImportBase:\n        assert n.level is not None\n        if len(n.names) == 1 and n.names[0].name == \"*\":\n            mod = n.module if n.module is not None else \"\"\n            i: ImportBase = ImportAll(mod, n.level)\n        else:\n            i = ImportFrom(\n                self.translate_module_id(n.module) if n.module is not None else \"\",\n                n.level,\n                [(a.name, a.asname) for a in n.names],\n            )\n        self.imports.append(i)\n        return self.set_line(i, n)\n\n    # Global(identifier* names)\n    def visit_Global(self, n: ast3.Global) -> GlobalDecl:\n        g = GlobalDecl(n.names)\n        return self.set_line(g, n)\n\n    # Nonlocal(identifier* names)\n    def visit_Nonlocal(self, n: ast3.Nonlocal) -> NonlocalDecl:\n        d = NonlocalDecl(n.names)\n        return self.set_line(d, n)\n\n    # Expr(expr value)\n    def visit_Expr(self, n: ast3.Expr) -> ExpressionStmt:\n        value = self.visit(n.value)\n        node = ExpressionStmt(value)\n        return self.set_line(node, n)\n\n    # Pass\n    def visit_Pass(self, n: ast3.Pass) -> PassStmt:\n        s = PassStmt()\n        return self.set_line(s, n)\n\n    # Break\n    def visit_Break(self, n: ast3.Break) -> BreakStmt:\n        s = BreakStmt()\n        return self.set_line(s, n)\n\n    # Continue\n    def visit_Continue(self, n: ast3.Continue) -> ContinueStmt:\n        s = ContinueStmt()\n        return self.set_line(s, n)\n\n    # --- expr ---\n\n    def visit_NamedExpr(self, n: ast3.NamedExpr) -> AssignmentExpr:\n        s = AssignmentExpr(self.visit(n.target), self.visit(n.value))\n        return self.set_line(s, n)\n\n    # BoolOp(boolop op, expr* values)\n    def visit_BoolOp(self, n: ast3.BoolOp) -> OpExpr:\n        # mypy translates (1 and 2 and 3) as (1 and (2 and 3))\n        assert len(n.values) >= 2\n        op_node = n.op\n        if isinstance(op_node, ast3.And):\n            op = \"and\"\n        elif isinstance(op_node, ast3.Or):\n            op = \"or\"\n        else:\n            raise RuntimeError(\"unknown BoolOp \" + str(type(n)))\n\n        # potentially inefficient!\n        return self.group(op, self.translate_expr_list(n.values), n)\n\n    def group(self, op: str, vals: list[Expression], n: ast3.expr) -> OpExpr:\n        if len(vals) == 2:\n            e = OpExpr(op, vals[0], vals[1])\n        else:\n            e = OpExpr(op, vals[0], self.group(op, vals[1:], n))\n        return self.set_line(e, n)\n\n    # BinOp(expr left, operator op, expr right)\n    def visit_BinOp(self, n: ast3.BinOp) -> OpExpr:\n        op = self.from_operator(n.op)\n\n        if op is None:\n            raise RuntimeError(\"cannot translate BinOp \" + str(type(n.op)))\n\n        e = OpExpr(op, self.visit(n.left), self.visit(n.right))\n        return self.set_line(e, n)\n\n    # UnaryOp(unaryop op, expr operand)\n    def visit_UnaryOp(self, n: ast3.UnaryOp) -> UnaryExpr:\n        op = None\n        if isinstance(n.op, ast3.Invert):\n            op = \"~\"\n        elif isinstance(n.op, ast3.Not):\n            op = \"not\"\n        elif isinstance(n.op, ast3.UAdd):\n            op = \"+\"\n        elif isinstance(n.op, ast3.USub):\n            op = \"-\"\n\n        if op is None:\n            raise RuntimeError(\"cannot translate UnaryOp \" + str(type(n.op)))\n\n        e = UnaryExpr(op, self.visit(n.operand))\n        return self.set_line(e, n)\n\n    # Lambda(arguments args, expr body)\n    def visit_Lambda(self, n: ast3.Lambda) -> LambdaExpr:\n        body = ast3.Return(n.body)\n        body.lineno = n.body.lineno\n        body.col_offset = n.body.col_offset\n\n        self.class_and_function_stack.append(\"L\")\n        e = LambdaExpr(self.transform_args(n.args, n.lineno), self.as_required_block([body]))\n        self.class_and_function_stack.pop()\n        e.set_line(n.lineno, n.col_offset)  # Overrides set_line -- can't use self.set_line\n        return e\n\n    # IfExp(expr test, expr body, expr orelse)\n    def visit_IfExp(self, n: ast3.IfExp) -> ConditionalExpr:\n        e = ConditionalExpr(self.visit(n.test), self.visit(n.body), self.visit(n.orelse))\n        return self.set_line(e, n)\n\n    # Dict(expr* keys, expr* values)\n    def visit_Dict(self, n: ast3.Dict) -> DictExpr:\n        e = DictExpr(\n            list(zip(self.translate_opt_expr_list(n.keys), self.translate_expr_list(n.values)))\n        )\n        return self.set_line(e, n)\n\n    # Set(expr* elts)\n    def visit_Set(self, n: ast3.Set) -> SetExpr:\n        e = SetExpr(self.translate_expr_list(n.elts))\n        return self.set_line(e, n)\n\n    # ListComp(expr elt, comprehension* generators)\n    def visit_ListComp(self, n: ast3.ListComp) -> ListComprehension:\n        e = ListComprehension(self.visit_GeneratorExp(cast(ast3.GeneratorExp, n)))\n        return self.set_line(e, n)\n\n    # SetComp(expr elt, comprehension* generators)\n    def visit_SetComp(self, n: ast3.SetComp) -> SetComprehension:\n        e = SetComprehension(self.visit_GeneratorExp(cast(ast3.GeneratorExp, n)))\n        return self.set_line(e, n)\n\n    # DictComp(expr key, expr value, comprehension* generators)\n    def visit_DictComp(self, n: ast3.DictComp) -> DictionaryComprehension:\n        targets = [self.visit(c.target) for c in n.generators]\n        iters = [self.visit(c.iter) for c in n.generators]\n        ifs_list = [self.translate_expr_list(c.ifs) for c in n.generators]\n        is_async = [bool(c.is_async) for c in n.generators]\n        e = DictionaryComprehension(\n            self.visit(n.key), self.visit(n.value), targets, iters, ifs_list, is_async\n        )\n        return self.set_line(e, n)\n\n    # GeneratorExp(expr elt, comprehension* generators)\n    def visit_GeneratorExp(self, n: ast3.GeneratorExp) -> GeneratorExpr:\n        targets = [self.visit(c.target) for c in n.generators]\n        iters = [self.visit(c.iter) for c in n.generators]\n        ifs_list = [self.translate_expr_list(c.ifs) for c in n.generators]\n        is_async = [bool(c.is_async) for c in n.generators]\n        e = GeneratorExpr(self.visit(n.elt), targets, iters, ifs_list, is_async)\n        return self.set_line(e, n)\n\n    # Await(expr value)\n    def visit_Await(self, n: ast3.Await) -> AwaitExpr:\n        v = self.visit(n.value)\n        e = AwaitExpr(v)\n        return self.set_line(e, n)\n\n    # Yield(expr? value)\n    def visit_Yield(self, n: ast3.Yield) -> YieldExpr:\n        e = YieldExpr(self.visit(n.value))\n        return self.set_line(e, n)\n\n    # YieldFrom(expr value)\n    def visit_YieldFrom(self, n: ast3.YieldFrom) -> YieldFromExpr:\n        e = YieldFromExpr(self.visit(n.value))\n        return self.set_line(e, n)\n\n    # Compare(expr left, cmpop* ops, expr* comparators)\n    def visit_Compare(self, n: ast3.Compare) -> ComparisonExpr:\n        operators = [self.from_comp_operator(o) for o in n.ops]\n        operands = self.translate_expr_list([n.left] + n.comparators)\n        e = ComparisonExpr(operators, operands)\n        return self.set_line(e, n)\n\n    # Call(expr func, expr* args, keyword* keywords)\n    # keyword = (identifier? arg, expr value)\n    def visit_Call(self, n: Call) -> CallExpr:\n        args = n.args\n        keywords = n.keywords\n        keyword_names = [k.arg for k in keywords]\n        arg_types = self.translate_expr_list(\n            [a.value if isinstance(a, Starred) else a for a in args] + [k.value for k in keywords]\n        )\n        arg_kinds = [ARG_STAR if type(a) is Starred else ARG_POS for a in args] + [\n            ARG_STAR2 if arg is None else ARG_NAMED for arg in keyword_names\n        ]\n        e = CallExpr(\n            self.visit(n.func),\n            arg_types,\n            arg_kinds,\n            cast(\"list[str | None]\", [None] * len(args)) + keyword_names,\n        )\n        return self.set_line(e, n)\n\n    # Constant(object value)\n    def visit_Constant(self, n: ast3.Constant) -> Any:\n        val = n.value\n        e: Any = None\n        if val is None:\n            e = NameExpr(\"None\")\n        elif isinstance(val, str):\n            e = StrExpr(val)\n        elif isinstance(val, bytes):\n            e = BytesExpr(bytes_to_human_readable_repr(val))\n        elif isinstance(val, bool):  # Must check before int!\n            e = NameExpr(str(val))\n        elif isinstance(val, int):\n            e = IntExpr(val)\n        elif isinstance(val, float):\n            e = FloatExpr(val)\n        elif isinstance(val, complex):\n            e = ComplexExpr(val)\n        elif val is Ellipsis:\n            e = EllipsisExpr()\n        else:\n            raise RuntimeError(\"Constant not implemented for \" + str(type(val)))\n        return self.set_line(e, n)\n\n    # JoinedStr(expr* values)\n    def visit_JoinedStr(self, n: ast3.JoinedStr) -> Expression:\n        # Each of n.values is a str or FormattedValue; we just concatenate\n        # them all using ''.join.\n        empty_string = StrExpr(\"\")\n        empty_string.set_line(n.lineno, n.col_offset)\n        strs_to_join = ListExpr(self.translate_expr_list(n.values))\n        strs_to_join.set_line(empty_string)\n        # Don't make unnecessary join call if there is only one str to join\n        if len(strs_to_join.items) == 1:\n            return self.set_line(strs_to_join.items[0], n)\n        elif len(strs_to_join.items) > 1:\n            last = strs_to_join.items[-1]\n            if isinstance(last, StrExpr) and last.value == \"\":\n                # 3.12 can add an empty literal at the end. Delete it for consistency\n                # between Python versions.\n                del strs_to_join.items[-1:]\n        join_method = MemberExpr(empty_string, \"join\")\n        join_method.set_line(empty_string)\n        result_expression = CallExpr(join_method, [strs_to_join], [ARG_POS], [None])\n        return self.set_line(result_expression, n)\n\n    # FormattedValue(expr value)\n    def visit_FormattedValue(self, n: ast3.FormattedValue) -> Expression:\n        # A FormattedValue is a component of a JoinedStr, or it can exist\n        # on its own. We translate them to individual '{}'.format(value)\n        # calls. Format specifier and conversion information is passed along\n        # to allow mypyc to support f-strings with format specifiers and conversions.\n        val_exp = self.visit(n.value)\n        val_exp.set_line(n.lineno, n.col_offset)\n        conv_str = \"\" if n.conversion < 0 else \"!\" + chr(n.conversion)\n        format_string = StrExpr(\"{\" + conv_str + \":{}}\")\n        format_spec_exp = self.visit(n.format_spec) if n.format_spec is not None else StrExpr(\"\")\n        format_string.set_line(n.lineno, n.col_offset)\n        format_method = MemberExpr(format_string, \"format\")\n        format_method.set_line(format_string)\n        result_expression = CallExpr(\n            format_method, [val_exp, format_spec_exp], [ARG_POS, ARG_POS], [None, None]\n        )\n        return self.set_line(result_expression, n)\n\n    # TemplateStr(expr* values)\n    def visit_TemplateStr(self, n: ast_TemplateStr) -> TemplateStrExpr:\n        self.uses_template_strings = True\n        items: list[Expression | tuple[Expression, str, str | None, Expression | None]] = []\n        for value in n.values:\n            if isinstance(value, ast_Interpolation):  # type: ignore[misc]\n                val_expr = self.visit(value.value)\n                val_expr.set_line(value.lineno, value.col_offset)\n                conversion = None if value.conversion < 0 else chr(value.conversion)\n                format_spec = (\n                    self.visit(value.format_spec) if value.format_spec is not None else None\n                )\n                items.append((val_expr, value.str, conversion, format_spec))\n            else:\n                items.append(self.visit(value))\n        e = TemplateStrExpr(items)\n        return self.set_line(e, n)\n\n    # Attribute(expr value, identifier attr, expr_context ctx)\n    def visit_Attribute(self, n: Attribute) -> MemberExpr | SuperExpr:\n        value = n.value\n        member_expr = MemberExpr(self.visit(value), n.attr)\n        obj = member_expr.expr\n        if (\n            isinstance(obj, CallExpr)\n            and isinstance(obj.callee, NameExpr)\n            and obj.callee.name == \"super\"\n        ):\n            e: MemberExpr | SuperExpr = SuperExpr(member_expr.name, obj)\n        else:\n            e = member_expr\n        return self.set_line(e, n)\n\n    # Subscript(expr value, slice slice, expr_context ctx)\n    def visit_Subscript(self, n: ast3.Subscript) -> IndexExpr:\n        e = IndexExpr(self.visit(n.value), self.visit(n.slice))\n        return self.set_line(e, n)\n\n    # Starred(expr value, expr_context ctx)\n    def visit_Starred(self, n: Starred) -> StarExpr:\n        e = StarExpr(self.visit(n.value))\n        return self.set_line(e, n)\n\n    # Name(identifier id, expr_context ctx)\n    def visit_Name(self, n: Name) -> NameExpr:\n        e = NameExpr(n.id)\n        return self.set_line(e, n)\n\n    # List(expr* elts, expr_context ctx)\n    def visit_List(self, n: ast3.List) -> ListExpr | TupleExpr:\n        expr_list: list[Expression] = [self.visit(e) for e in n.elts]\n        if isinstance(n.ctx, ast3.Store):\n            # [x, y] = z and (x, y) = z means exactly the same thing\n            e: ListExpr | TupleExpr = TupleExpr(expr_list)\n        else:\n            e = ListExpr(expr_list)\n        return self.set_line(e, n)\n\n    # Tuple(expr* elts, expr_context ctx)\n    def visit_Tuple(self, n: ast3.Tuple) -> TupleExpr:\n        e = TupleExpr(self.translate_expr_list(n.elts))\n        return self.set_line(e, n)\n\n    # Slice(expr? lower, expr? upper, expr? step)\n    def visit_Slice(self, n: ast3.Slice) -> SliceExpr:\n        e = SliceExpr(self.visit(n.lower), self.visit(n.upper), self.visit(n.step))\n        return self.set_line(e, n)\n\n    # Match(expr subject, match_case* cases) # python 3.10 and later\n    def visit_Match(self, n: ast3.Match) -> MatchStmt:\n        node = MatchStmt(\n            self.visit(n.subject),\n            [self.visit(c.pattern) for c in n.cases],\n            [self.visit(c.guard) for c in n.cases],\n            [self.as_required_block(c.body) for c in n.cases],\n        )\n        return self.set_line(node, n)\n\n    def visit_MatchValue(self, n: ast3.MatchValue) -> ValuePattern:\n        node = ValuePattern(self.visit(n.value))\n        return self.set_line(node, n)\n\n    def visit_MatchSingleton(self, n: ast3.MatchSingleton) -> SingletonPattern:\n        node = SingletonPattern(n.value)\n        return self.set_line(node, n)\n\n    def visit_MatchSequence(self, n: ast3.MatchSequence) -> SequencePattern:\n        patterns = [self.visit(p) for p in n.patterns]\n        stars = [p for p in patterns if isinstance(p, StarredPattern)]\n        assert len(stars) < 2\n\n        node = SequencePattern(patterns)\n        return self.set_line(node, n)\n\n    def visit_MatchStar(self, n: ast3.MatchStar) -> StarredPattern:\n        if n.name is None:\n            node = StarredPattern(None)\n        else:\n            name = self.set_line(NameExpr(n.name), n)\n            node = StarredPattern(name)\n\n        return self.set_line(node, n)\n\n    def visit_MatchMapping(self, n: ast3.MatchMapping) -> MappingPattern:\n        keys = [self.visit(k) for k in n.keys]\n        values = [self.visit(v) for v in n.patterns]\n\n        if n.rest is None:\n            rest = None\n        else:\n            rest = self.set_line(NameExpr(n.rest), n)\n\n        node = MappingPattern(keys, values, rest)\n        return self.set_line(node, n)\n\n    def visit_MatchClass(self, n: ast3.MatchClass) -> ClassPattern:\n        class_ref = self.visit(n.cls)\n        assert isinstance(class_ref, RefExpr)\n        positionals = [self.visit(p) for p in n.patterns]\n        keyword_keys = n.kwd_attrs\n        keyword_values = [self.visit(p) for p in n.kwd_patterns]\n\n        node = ClassPattern(class_ref, positionals, keyword_keys, keyword_values)\n        return self.set_line(node, n)\n\n    # MatchAs(expr pattern, identifier name)\n    def visit_MatchAs(self, n: ast3.MatchAs) -> AsPattern:\n        if n.name is None:\n            name = None\n        else:\n            name = NameExpr(n.name)\n            name = self.set_line(name, n)\n        node = AsPattern(self.visit(n.pattern), name)\n        return self.set_line(node, n)\n\n    # MatchOr(expr* pattern)\n    def visit_MatchOr(self, n: ast3.MatchOr) -> OrPattern:\n        node = OrPattern([self.visit(pattern) for pattern in n.patterns])\n        return self.set_line(node, n)\n\n    def validate_type_alias(self, n: ast_TypeAlias) -> None:\n        incorrect_expr = find_disallowed_expression_in_annotation_scope(n.value)\n        if incorrect_expr is None:\n            return\n        if isinstance(incorrect_expr, (ast3.Yield, ast3.YieldFrom)):\n            self.fail(\n                message_registry.TYPE_ALIAS_WITH_YIELD_EXPRESSION,\n                n.lineno,\n                n.col_offset,\n                blocker=True,\n            )\n        if isinstance(incorrect_expr, ast3.NamedExpr):\n            self.fail(\n                message_registry.TYPE_ALIAS_WITH_NAMED_EXPRESSION,\n                n.lineno,\n                n.col_offset,\n                blocker=True,\n            )\n        if isinstance(incorrect_expr, ast3.Await):\n            self.fail(\n                message_registry.TYPE_ALIAS_WITH_AWAIT_EXPRESSION,\n                n.lineno,\n                n.col_offset,\n                blocker=True,\n            )\n\n    # TypeAlias(identifier name, type_param* type_params, expr value)\n    def visit_TypeAlias(self, n: ast_TypeAlias) -> TypeAliasStmt | AssignmentStmt:\n        node: TypeAliasStmt | AssignmentStmt\n        type_params = self.translate_type_params(n.type_params)\n        self.validate_type_alias(n)\n        value = self.visit(n.value)\n        # Since the value is evaluated lazily, wrap the value inside a lambda.\n        # This helps mypyc.\n        ret = ReturnStmt(value)\n        self.set_line(ret, n.value)\n        value_func = LambdaExpr(body=Block([ret]))\n        self.set_line(value_func, n.value)\n        node = TypeAliasStmt(self.visit_Name(n.name), type_params, value_func)\n        return self.set_line(node, n)\n\n\nclass TypeConverter:\n    def __init__(\n        self,\n        errors: Errors | None,\n        line: int = -1,\n        override_column: int = -1,\n        is_evaluated: bool = True,\n    ) -> None:\n        self.errors = errors\n        self.line = line\n        self.override_column = override_column\n        self.node_stack: list[AST] = []\n        self.is_evaluated = is_evaluated\n\n    def convert_column(self, column: int) -> int:\n        \"\"\"Apply column override if defined; otherwise return column.\n\n        Column numbers are sometimes incorrect in the AST and the column\n        override can be used to work around that.\n        \"\"\"\n        if self.override_column < 0:\n            return column\n        else:\n            return self.override_column\n\n    def invalid_type(self, node: AST, note: str | None = None) -> RawExpressionType:\n        \"\"\"Constructs a type representing some expression that normally forms an invalid type.\n        For example, if we see a type hint that says \"3 + 4\", we would transform that\n        expression into a RawExpressionType.\n\n        The semantic analysis layer will report an \"Invalid type\" error when it\n        encounters this type, along with the given note if one is provided.\n\n        See RawExpressionType's docstring for more details on how it's used.\n        \"\"\"\n        return RawExpressionType(\n            None, \"typing.Any\", line=self.line, column=getattr(node, \"col_offset\", -1), note=note\n        )\n\n    @overload\n    def visit(self, node: ast3.expr) -> ProperType: ...\n\n    @overload\n    def visit(self, node: AST | None) -> ProperType | None: ...\n\n    def visit(self, node: AST | None) -> ProperType | None:\n        \"\"\"Modified visit -- keep track of the stack of nodes\"\"\"\n        if node is None:\n            return None\n        self.node_stack.append(node)\n        try:\n            method = \"visit_\" + node.__class__.__name__\n            visitor = getattr(self, method, None)\n            if visitor is not None:\n                typ = visitor(node)\n                assert isinstance(typ, ProperType)\n                return typ\n            else:\n                return self.invalid_type(node)\n        finally:\n            self.node_stack.pop()\n\n    def parent(self) -> AST | None:\n        \"\"\"Return the AST node above the one we are processing\"\"\"\n        if len(self.node_stack) < 2:\n            return None\n        return self.node_stack[-2]\n\n    def fail(self, msg: ErrorMessage, line: int, column: int) -> None:\n        if self.errors:\n            self.errors.report(line, column, msg.value, blocker=True, code=msg.code)\n\n    def note(self, msg: str, line: int, column: int) -> None:\n        if self.errors:\n            self.errors.report(line, column, msg, severity=\"note\", code=codes.SYNTAX)\n\n    def translate_expr_list(self, l: Sequence[ast3.expr]) -> list[Type]:\n        return [self.visit(e) for e in l]\n\n    def visit_Call(self, e: Call) -> Type:\n        # Parse the arg constructor\n        f = e.func\n        constructor = stringify_name(f)\n\n        if not isinstance(self.parent(), ast3.List):\n            note = None\n            if constructor:\n                note = \"Suggestion: use {0}[...] instead of {0}(...)\".format(constructor)\n            return self.invalid_type(e, note=note)\n        if not constructor:\n            self.fail(message_registry.ARG_CONSTRUCTOR_NAME_EXPECTED, e.lineno, e.col_offset)\n\n        name: str | None = None\n        default_type = AnyType(TypeOfAny.special_form)\n        typ: Type = default_type\n        for i, arg in enumerate(e.args):\n            if i == 0:\n                converted = self.visit(arg)\n                assert converted is not None\n                typ = converted\n            elif i == 1:\n                name = self._extract_argument_name(arg)\n            else:\n                self.fail(message_registry.ARG_CONSTRUCTOR_TOO_MANY_ARGS, f.lineno, f.col_offset)\n        for k in e.keywords:\n            value = k.value\n            if k.arg == \"name\":\n                if name is not None:\n                    self.fail(\n                        message_registry.MULTIPLE_VALUES_FOR_NAME_KWARG.format(constructor),\n                        f.lineno,\n                        f.col_offset,\n                    )\n                name = self._extract_argument_name(value)\n            elif k.arg == \"type\":\n                if typ is not default_type:\n                    self.fail(\n                        message_registry.MULTIPLE_VALUES_FOR_TYPE_KWARG.format(constructor),\n                        f.lineno,\n                        f.col_offset,\n                    )\n                converted = self.visit(value)\n                assert converted is not None\n                typ = converted\n            else:\n                self.fail(\n                    message_registry.ARG_CONSTRUCTOR_UNEXPECTED_ARG.format(k.arg),\n                    value.lineno,\n                    value.col_offset,\n                )\n        return CallableArgument(typ, name, constructor, e.lineno, e.col_offset)\n\n    def translate_argument_list(self, l: Sequence[ast3.expr]) -> TypeList:\n        return TypeList([self.visit(e) for e in l], line=self.line)\n\n    def _extract_argument_name(self, n: ast3.expr) -> str | None:\n        if isinstance(n, ast3.Constant) and isinstance(n.value, str):\n            return n.value.strip()\n        elif isinstance(n, ast3.Constant) and n.value is None:\n            return None\n        self.fail(\n            message_registry.ARG_NAME_EXPECTED_STRING_LITERAL.format(type(n).__name__),\n            self.line,\n            0,\n        )\n        return None\n\n    def visit_Name(self, n: Name) -> Type:\n        return UnboundType(n.id, line=self.line, column=self.convert_column(n.col_offset))\n\n    def visit_BinOp(self, n: ast3.BinOp) -> Type:\n        if not isinstance(n.op, ast3.BitOr):\n            return self.invalid_type(n)\n\n        left = self.visit(n.left)\n        right = self.visit(n.right)\n        return UnionType(\n            [left, right],\n            line=self.line,\n            column=self.convert_column(n.col_offset),\n            is_evaluated=self.is_evaluated,\n            uses_pep604_syntax=True,\n        )\n\n    def visit_Constant(self, n: ast3.Constant) -> Type:\n        val = n.value\n        if val is None:\n            # None is a type.\n            return UnboundType(\"None\", line=self.line)\n        if isinstance(val, str):\n            # Parse forward reference.\n            return parse_type_string(val, \"builtins.str\", self.line, n.col_offset)\n        if val is Ellipsis:\n            # '...' is valid in some types.\n            return EllipsisType(line=self.line)\n        if isinstance(val, bool):\n            # Special case for True/False.\n            return RawExpressionType(val, \"builtins.bool\", line=self.line)\n        if isinstance(val, (int, float, complex)):\n            return self.numeric_type(val, n)\n        if isinstance(val, bytes):\n            contents = bytes_to_human_readable_repr(val)\n            return RawExpressionType(contents, \"builtins.bytes\", self.line, column=n.col_offset)\n        # Everything else is invalid.\n\n    # UnaryOp(op, operand)\n    def visit_UnaryOp(self, n: UnaryOp) -> Type:\n        # We support specifically Literal[-4], Literal[+4], and nothing else.\n        # For example, Literal[~6] or Literal[not False] is not supported.\n        typ = self.visit(n.operand)\n        if (\n            isinstance(typ, RawExpressionType)\n            # Use type() because we do not want to allow bools.\n            and type(typ.literal_value) is int\n        ):\n            if isinstance(n.op, USub):\n                typ.literal_value *= -1\n                return typ\n            if isinstance(n.op, UAdd):\n                return typ\n        return self.invalid_type(n)\n\n    def numeric_type(self, value: object, n: AST) -> Type:\n        # The node's field has the type complex, but complex isn't *really*\n        # a parent of int and float, and this causes isinstance below\n        # to think that the complex branch is always picked. Avoid\n        # this by throwing away the type.\n        if isinstance(value, int):\n            numeric_value: int | None = value\n            type_name = \"builtins.int\"\n        else:\n            # Other kinds of numbers (floats, complex) are not valid parameters for\n            # RawExpressionType so we just pass in 'None' for now. We'll report the\n            # appropriate error at a later stage.\n            numeric_value = None\n            type_name = f\"builtins.{type(value).__name__}\"\n        return RawExpressionType(\n            numeric_value, type_name, line=self.line, column=getattr(n, \"col_offset\", -1)\n        )\n\n    def visit_Slice(self, n: ast3.Slice) -> Type:\n        return self.invalid_type(n, note=\"did you mean to use ',' instead of ':' ?\")\n\n    # Subscript(expr value, expr slice, expr_context ctx)\n    def visit_Subscript(self, n: ast3.Subscript) -> Type:\n        empty_tuple_index = False\n        if isinstance(n.slice, ast3.Tuple):\n            params = self.translate_expr_list(n.slice.elts)\n            if len(n.slice.elts) == 0:\n                empty_tuple_index = True\n        else:\n            params = [self.visit(n.slice)]\n\n        value = self.visit(n.value)\n        if isinstance(value, UnboundType) and not value.args:\n            result = UnboundType(\n                value.name,\n                params,\n                line=self.line,\n                column=value.column,\n                empty_tuple_index=empty_tuple_index,\n            )\n            result.end_column = n.end_col_offset\n            result.end_line = n.end_lineno\n            return result\n        else:\n            return self.invalid_type(n)\n\n    def visit_Tuple(self, n: ast3.Tuple) -> Type:\n        return TupleType(\n            self.translate_expr_list(n.elts),\n            _dummy_fallback,\n            implicit=True,\n            line=self.line,\n            column=self.convert_column(n.col_offset),\n        )\n\n    def visit_Dict(self, n: ast3.Dict) -> Type:\n        if not n.keys:\n            return self.invalid_type(n)\n        items: dict[str, Type] = {}\n        extra_items_from = []\n        for item_name, value in zip(n.keys, n.values):\n            if not isinstance(item_name, ast3.Constant) or not isinstance(item_name.value, str):\n                if item_name is None:\n                    extra_items_from.append(self.visit(value))\n                    continue\n                return self.invalid_type(n)\n            items[item_name.value] = self.visit(value)\n        result = TypedDictType(items, set(), set(), _dummy_fallback, n.lineno, n.col_offset)\n        result.extra_items_from = extra_items_from\n        return result\n\n    # Attribute(expr value, identifier attr, expr_context ctx)\n    def visit_Attribute(self, n: Attribute) -> Type:\n        before_dot = self.visit(n.value)\n\n        if isinstance(before_dot, UnboundType) and not before_dot.args:\n            return UnboundType(f\"{before_dot.name}.{n.attr}\", line=self.line, column=n.col_offset)\n        else:\n            return self.invalid_type(n)\n\n    # Used for Callable[[X *Ys, Z], R] etc.\n    def visit_Starred(self, n: ast3.Starred) -> Type:\n        return UnpackType(self.visit(n.value), from_star_syntax=True)\n\n    # List(expr* elts, expr_context ctx)\n    def visit_List(self, n: ast3.List) -> Type:\n        assert isinstance(n.ctx, ast3.Load)\n        result = self.translate_argument_list(n.elts)\n        return result\n\n\ndef stringify_name(n: AST) -> str | None:\n    if isinstance(n, Name):\n        return n.id\n    elif isinstance(n, Attribute):\n        sv = stringify_name(n.value)\n        if sv is not None:\n            return f\"{sv}.{n.attr}\"\n    return None  # Can't do it.\n\n\nclass FindAttributeAssign(TraverserVisitor):\n    \"\"\"Check if an AST contains attribute assignments (e.g. self.x = 0).\"\"\"\n\n    def __init__(self) -> None:\n        self.lvalue = False\n        self.found = False\n\n    def visit_assignment_stmt(self, s: AssignmentStmt) -> None:\n        self.lvalue = True\n        for lv in s.lvalues:\n            lv.accept(self)\n        self.lvalue = False\n\n    def visit_with_stmt(self, s: WithStmt) -> None:\n        self.lvalue = True\n        for lv in s.target:\n            if lv is not None:\n                lv.accept(self)\n        self.lvalue = False\n        s.body.accept(self)\n\n    def visit_for_stmt(self, s: ForStmt) -> None:\n        self.lvalue = True\n        s.index.accept(self)\n        self.lvalue = False\n        s.body.accept(self)\n        if s.else_body:\n            s.else_body.accept(self)\n\n    def visit_expression_stmt(self, s: ExpressionStmt) -> None:\n        # No need to look inside these\n        pass\n\n    def visit_call_expr(self, e: CallExpr) -> None:\n        # No need to look inside these\n        pass\n\n    def visit_index_expr(self, e: IndexExpr) -> None:\n        # No need to look inside these\n        pass\n\n    def visit_member_expr(self, e: MemberExpr) -> None:\n        if self.lvalue and isinstance(e.expr, NameExpr):\n            self.found = True\n\n\nclass FindYield(TraverserVisitor):\n    \"\"\"Check if an AST contains yields or yield froms.\"\"\"  # codespell:ignore froms\n\n    def __init__(self) -> None:\n        self.found = False\n\n    def visit_yield_expr(self, e: YieldExpr) -> None:\n        self.found = True\n\n    def visit_yield_from_expr(self, e: YieldFromExpr) -> None:\n        self.found = True\n\n\ndef is_possible_trivial_body(s: list[Statement]) -> bool:\n    \"\"\"Could the statements form a \"trivial\" function body, such as 'pass'?\n\n    This mimics mypy.semanal.is_trivial_body, but this runs before\n    semantic analysis so some checks must be conservative.\n    \"\"\"\n    l = len(s)\n    if l == 0:\n        return False\n    i = 0\n    if isinstance(s[0], ExpressionStmt) and isinstance(s[0].expr, StrExpr):\n        # Skip docstring\n        i += 1\n    if i == l:\n        return True\n    if l > i + 1:\n        return False\n    stmt = s[i]\n    return isinstance(stmt, (PassStmt, RaiseStmt)) or (\n        isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr)\n    )\n"
  },
  {
    "path": "mypy/find_sources.py",
    "content": "\"\"\"Routines for finding the sources that mypy will check\"\"\"\n\nfrom __future__ import annotations\n\nimport functools\nimport os\nfrom collections.abc import Sequence\nfrom typing import Final\n\nfrom mypy.fscache import FileSystemCache\nfrom mypy.modulefinder import (\n    PYTHON_EXTENSIONS,\n    BuildSource,\n    matches_exclude,\n    matches_gitignore,\n    mypy_path,\n)\nfrom mypy.options import Options\n\nPY_EXTENSIONS: Final = tuple(PYTHON_EXTENSIONS)\n\n\nclass InvalidSourceList(Exception):\n    \"\"\"Exception indicating a problem in the list of sources given to mypy.\"\"\"\n\n\ndef create_source_list(\n    paths: Sequence[str],\n    options: Options,\n    fscache: FileSystemCache | None = None,\n    allow_empty_dir: bool = False,\n) -> list[BuildSource]:\n    \"\"\"From a list of source files/directories, makes a list of BuildSources.\n\n    Raises InvalidSourceList on errors.\n    \"\"\"\n    fscache = fscache or FileSystemCache()\n    finder = SourceFinder(fscache, options)\n\n    sources = []\n    for path in paths:\n        path = os.path.normpath(path)\n        if path.endswith(PY_EXTENSIONS):\n            # Can raise InvalidSourceList if a directory doesn't have a valid module name.\n            name, base_dir = finder.crawl_up(path)\n            sources.append(BuildSource(path, name, None, base_dir))\n        elif fscache.isdir(path):\n            sub_sources = finder.find_sources_in_dir(path)\n            if not sub_sources and not allow_empty_dir:\n                raise InvalidSourceList(f\"There are no .py[i] files in directory '{path}'\")\n            sources.extend(sub_sources)\n        else:\n            mod = os.path.basename(path) if options.scripts_are_modules else None\n            sources.append(BuildSource(path, mod, None))\n    return sources\n\n\ndef keyfunc(name: str) -> tuple[bool, int, str]:\n    \"\"\"Determines sort order for directory listing.\n\n    The desirable properties are:\n    1) foo < foo.pyi < foo.py\n    2) __init__.py[i] < foo\n    \"\"\"\n    base, suffix = os.path.splitext(name)\n    for i, ext in enumerate(PY_EXTENSIONS):\n        if suffix == ext:\n            return (base != \"__init__\", i, base)\n    return (base != \"__init__\", -1, name)\n\n\ndef normalise_package_base(root: str) -> str:\n    if not root:\n        root = os.curdir\n    root = os.path.abspath(root)\n    if root.endswith(os.sep):\n        root = root[:-1]\n    return root\n\n\ndef get_explicit_package_bases(options: Options) -> list[str] | None:\n    \"\"\"Returns explicit package bases to use if the option is enabled, or None if disabled.\n\n    We currently use MYPYPATH and the current directory as the package bases. In the future,\n    when --namespace-packages is the default could also use the values passed with the\n    --package-root flag, see #9632.\n\n    Values returned are normalised so we can use simple string comparisons in\n    SourceFinder.is_explicit_package_base\n    \"\"\"\n    if not options.explicit_package_bases:\n        return None\n    roots = mypy_path() + options.mypy_path + [os.getcwd()]\n    return [normalise_package_base(root) for root in roots]\n\n\nclass SourceFinder:\n    def __init__(self, fscache: FileSystemCache, options: Options) -> None:\n        self.fscache = fscache\n        self.explicit_package_bases = get_explicit_package_bases(options)\n        self.namespace_packages = options.namespace_packages\n        self.exclude = options.exclude\n        self.exclude_gitignore = options.exclude_gitignore\n        self.verbosity = options.verbosity\n\n    def is_explicit_package_base(self, path: str) -> bool:\n        assert self.explicit_package_bases\n        return normalise_package_base(path) in self.explicit_package_bases\n\n    def find_sources_in_dir(self, path: str) -> list[BuildSource]:\n        sources = []\n\n        seen: set[str] = set()\n        names = sorted(self.fscache.listdir(path), key=keyfunc)\n        for name in names:\n            # Skip certain names altogether\n            if name in (\"__pycache__\", \"site-packages\", \"node_modules\") or name.startswith(\".\"):\n                continue\n            subpath = os.path.join(path, name)\n\n            if matches_exclude(subpath, self.exclude, self.fscache, self.verbosity >= 2):\n                continue\n            if self.exclude_gitignore and matches_gitignore(\n                subpath, self.fscache, self.verbosity >= 2\n            ):\n                continue\n\n            if self.fscache.isdir(subpath):\n                sub_sources = self.find_sources_in_dir(subpath)\n                if sub_sources:\n                    seen.add(name)\n                    sources.extend(sub_sources)\n            else:\n                stem, suffix = os.path.splitext(name)\n                if stem not in seen and suffix in PY_EXTENSIONS:\n                    seen.add(stem)\n                    module, base_dir = self.crawl_up(subpath)\n                    sources.append(BuildSource(subpath, module, None, base_dir))\n\n        return sources\n\n    def crawl_up(self, path: str) -> tuple[str, str]:\n        \"\"\"Given a .py[i] filename, return module and base directory.\n\n        For example, given \"xxx/yyy/foo/bar.py\", we might return something like:\n        (\"foo.bar\", \"xxx/yyy\")\n\n        If namespace packages is off, we crawl upwards until we find a directory without\n        an __init__.py\n\n        If namespace packages is on, we crawl upwards until the nearest explicit base directory.\n        Failing that, we return one past the highest directory containing an __init__.py\n\n        We won't crawl past directories with invalid package names.\n        The base directory returned is an absolute path.\n        \"\"\"\n        path = os.path.abspath(path)\n        parent, filename = os.path.split(path)\n\n        module_name = strip_py(filename) or filename\n\n        parent_module, base_dir = self.crawl_up_dir(parent)\n        if module_name == \"__init__\":\n            return parent_module, base_dir\n\n        # Note that module_name might not actually be a valid identifier, but that's okay\n        # Ignoring this possibility sidesteps some search path confusion\n        module = module_join(parent_module, module_name)\n        return module, base_dir\n\n    def crawl_up_dir(self, dir: str) -> tuple[str, str]:\n        return self._crawl_up_helper(dir) or (\"\", dir)\n\n    @functools.lru_cache  # noqa: B019\n    def _crawl_up_helper(self, dir: str) -> tuple[str, str] | None:\n        \"\"\"Given a directory, maybe returns module and base directory.\n\n        We return a non-None value if we were able to find something clearly intended as a base\n        directory (as adjudicated by being an explicit base directory or by containing a package\n        with __init__.py).\n\n        This distinction is necessary for namespace packages, so that we know when to treat\n        ourselves as a subpackage.\n        \"\"\"\n        # stop crawling if we're an explicit base directory\n        if self.explicit_package_bases is not None and self.is_explicit_package_base(dir):\n            return \"\", dir\n\n        parent, name = os.path.split(dir)\n        name = name.removesuffix(\"-stubs\")  # PEP-561 stub-only directory\n\n        # recurse if there's an __init__.py\n        init_file = self.get_init_file(dir)\n        if init_file is not None:\n            if not name.isidentifier():\n                # in most cases the directory name is invalid, we'll just stop crawling upwards\n                # but if there's an __init__.py in the directory, something is messed up\n                raise InvalidSourceList(\n                    f\"{name} contains {os.path.basename(init_file)} \"\n                    \"but is not a valid Python package name\"\n                )\n            # we're definitely a package, so we always return a non-None value\n            mod_prefix, base_dir = self.crawl_up_dir(parent)\n            return module_join(mod_prefix, name), base_dir\n\n        # stop crawling if we're out of path components or our name is an invalid identifier\n        if not name or not parent or not name.isidentifier():\n            return None\n\n        # stop crawling if namespace packages is off (since we don't have an __init__.py)\n        if not self.namespace_packages:\n            return None\n\n        # at this point: namespace packages is on, we don't have an __init__.py and we're not an\n        # explicit base directory\n        result = self._crawl_up_helper(parent)\n        if result is None:\n            # we're not an explicit base directory and we don't have an __init__.py\n            # and none of our parents are either, so return\n            return None\n        # one of our parents was an explicit base directory or had an __init__.py, so we're\n        # definitely a subpackage! chain our name to the module.\n        mod_prefix, base_dir = result\n        return module_join(mod_prefix, name), base_dir\n\n    def get_init_file(self, dir: str) -> str | None:\n        \"\"\"Check whether a directory contains a file named __init__.py[i].\n\n        If so, return the file's name (with dir prefixed).  If not, return None.\n\n        This prefers .pyi over .py (because of the ordering of PY_EXTENSIONS).\n        \"\"\"\n        for ext in PY_EXTENSIONS:\n            f = os.path.join(dir, \"__init__\" + ext)\n            if self.fscache.isfile(f):\n                return f\n            if ext == \".py\" and self.fscache.init_under_package_root(f):\n                return f\n        return None\n\n\ndef module_join(parent: str, child: str) -> str:\n    \"\"\"Join module ids, accounting for a possibly empty parent.\"\"\"\n    if parent:\n        return parent + \".\" + child\n    return child\n\n\ndef strip_py(arg: str) -> str | None:\n    \"\"\"Strip a trailing .py or .pyi suffix.\n\n    Return None if no such suffix is found.\n    \"\"\"\n    for ext in PY_EXTENSIONS:\n        if arg.endswith(ext):\n            return arg[: -len(ext)]\n    return None\n"
  },
  {
    "path": "mypy/fixup.py",
    "content": "\"\"\"Fix up various things after deserialization.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Any, Final\n\nfrom mypy.lookup import lookup_fully_qualified\nfrom mypy.nodes import (\n    Block,\n    ClassDef,\n    Decorator,\n    FuncDef,\n    MypyFile,\n    OverloadedFuncDef,\n    ParamSpecExpr,\n    SymbolTable,\n    TypeAlias,\n    TypeInfo,\n    TypeVarExpr,\n    TypeVarTupleExpr,\n    Var,\n)\nfrom mypy.types import (\n    NOT_READY,\n    AnyType,\n    CallableType,\n    Instance,\n    LiteralType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    ProperType,\n    TupleType,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeType,\n    TypeVarTupleType,\n    TypeVarType,\n    TypeVisitor,\n    UnboundType,\n    UnionType,\n    UnpackType,\n)\nfrom mypy.visitor import NodeVisitor\n\n\n# N.B: we do a allow_missing fixup when fixing up a fine-grained\n# incremental cache load (since there may be cross-refs into deleted\n# modules)\ndef fixup_module(tree: MypyFile, modules: dict[str, MypyFile], allow_missing: bool) -> None:\n    node_fixer = NodeFixer(modules, allow_missing)\n    node_fixer.visit_symbol_table(tree.names, tree.fullname)\n\n\n# TODO: Fix up .info when deserializing, i.e. much earlier.\nclass NodeFixer(NodeVisitor[None]):\n    current_info: TypeInfo | None = None\n\n    def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None:\n        self.modules = modules\n        self.allow_missing = allow_missing\n        self.type_fixer = TypeFixer(self.modules, allow_missing)\n\n    # NOTE: This method isn't (yet) part of the NodeVisitor API.\n    def visit_type_info(self, info: TypeInfo) -> None:\n        save_info = self.current_info\n        try:\n            self.current_info = info\n            if info.defn:\n                info.defn.accept(self)\n            if info.names:\n                self.visit_symbol_table(info.names, info.fullname)\n            if info.bases:\n                for base in info.bases:\n                    base.accept(self.type_fixer)\n            if info._promote:\n                for p in info._promote:\n                    p.accept(self.type_fixer)\n            if info.tuple_type:\n                info.tuple_type.accept(self.type_fixer)\n                info.update_tuple_type(info.tuple_type)\n                if info.special_alias:\n                    info.special_alias.alias_tvars = list(info.defn.type_vars)\n                    for i, t in enumerate(info.defn.type_vars):\n                        if isinstance(t, TypeVarTupleType):\n                            info.special_alias.tvar_tuple_index = i\n            if info.typeddict_type:\n                info.typeddict_type.accept(self.type_fixer)\n                info.update_typeddict_type(info.typeddict_type)\n                if info.special_alias:\n                    info.special_alias.alias_tvars = list(info.defn.type_vars)\n                    for i, t in enumerate(info.defn.type_vars):\n                        if isinstance(t, TypeVarTupleType):\n                            info.special_alias.tvar_tuple_index = i\n            if info.declared_metaclass:\n                info.declared_metaclass.accept(self.type_fixer)\n            if info.metaclass_type:\n                info.metaclass_type.accept(self.type_fixer)\n            if info.self_type:\n                info.self_type.accept(self.type_fixer)\n            if info.alt_promote:\n                info.alt_promote.accept(self.type_fixer)\n                instance = Instance(info, [])\n                # Hack: We may also need to add a backwards promotion (from int to native int),\n                # since it might not be serialized.\n                if instance not in info.alt_promote.type._promote:\n                    info.alt_promote.type._promote.append(instance)\n            if info._mro_refs:\n                info.mro = [\n                    lookup_fully_qualified_typeinfo(\n                        self.modules, name, allow_missing=self.allow_missing\n                    )\n                    for name in info._mro_refs\n                ]\n                info._mro_refs = None\n        finally:\n            self.current_info = save_info\n\n    # NOTE: This method *definitely* isn't part of the NodeVisitor API.\n    def visit_symbol_table(self, symtab: SymbolTable, table_fullname: str) -> None:\n        # Copy the items because we may mutate symtab.\n        for key in list(symtab):\n            value = symtab[key]\n            cross_ref = value.cross_ref\n            if cross_ref is not None:  # Fix up cross-reference.\n                value.cross_ref = None\n                if cross_ref in self.modules:\n                    value.node = self.modules[cross_ref]\n                else:\n                    stnode = lookup_fully_qualified(\n                        cross_ref, self.modules, raise_on_missing=not self.allow_missing\n                    )\n                    if stnode is not None:\n                        if stnode is value:\n                            # The node seems to refer to itself, which can mean that\n                            # the target is a deleted submodule of the current module,\n                            # and thus lookup falls back to the symbol table of the parent\n                            # package. Here's how this may happen:\n                            #\n                            #   pkg/__init__.py:\n                            #     from pkg import sub\n                            #\n                            # Now if pkg.sub is deleted, the pkg.sub symbol table entry\n                            # appears to refer to itself. Replace the entry with a\n                            # placeholder to avoid a crash. We can't delete the entry,\n                            # as it would stop dependency propagation.\n                            value.node = Var(key + \"@deleted\")\n                        else:\n                            assert stnode.node is not None, (table_fullname + \".\" + key, cross_ref)\n                            value.node = stnode.node\n                    elif not self.allow_missing:\n                        assert False, f\"Could not find cross-ref {cross_ref}\"\n                    else:\n                        # We have a missing crossref in allow missing mode, need to put something\n                        value.node = missing_info(self.modules)\n            else:\n                if isinstance(value.node, TypeInfo):\n                    # TypeInfo has no accept().  TODO: Add it?\n                    self.visit_type_info(value.node)\n                elif value.node is not None:\n                    value.node.accept(self)\n                else:\n                    assert False, f\"Unexpected empty node {key!r}: {value}\"\n\n    def visit_func_def(self, func: FuncDef) -> None:\n        if self.current_info is not None:\n            func.info = self.current_info\n        if func.type is not None:\n            func.type.accept(self.type_fixer)\n            if isinstance(func.type, CallableType):\n                func.type.definition = func\n\n    def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None:\n        if self.current_info is not None:\n            o.info = self.current_info\n        if o.type:\n            o.type.accept(self.type_fixer)\n        for item in o.items:\n            item.accept(self)\n        if o.impl:\n            o.impl.accept(self)\n        if isinstance(o.type, Overloaded):\n            # For error messages we link the original definition for each item.\n            for typ, item in zip(o.type.items, o.items):\n                typ.definition = item\n\n    def visit_decorator(self, d: Decorator) -> None:\n        if self.current_info is not None:\n            d.var.info = self.current_info\n        if d.func:\n            d.func.accept(self)\n        if d.var:\n            d.var.accept(self)\n        for node in d.decorators:\n            node.accept(self)\n        typ = d.var.type\n        if isinstance(typ, ProperType) and isinstance(typ, CallableType):\n            typ.definition = d.func\n\n    def visit_class_def(self, c: ClassDef) -> None:\n        for v in c.type_vars:\n            v.accept(self.type_fixer)\n\n    def visit_type_var_expr(self, tv: TypeVarExpr) -> None:\n        for value in tv.values:\n            value.accept(self.type_fixer)\n        tv.upper_bound.accept(self.type_fixer)\n        tv.default.accept(self.type_fixer)\n\n    def visit_paramspec_expr(self, p: ParamSpecExpr) -> None:\n        p.upper_bound.accept(self.type_fixer)\n        p.default.accept(self.type_fixer)\n\n    def visit_type_var_tuple_expr(self, tv: TypeVarTupleExpr) -> None:\n        tv.upper_bound.accept(self.type_fixer)\n        tv.tuple_fallback.accept(self.type_fixer)\n        tv.default.accept(self.type_fixer)\n\n    def visit_var(self, v: Var) -> None:\n        if self.current_info is not None:\n            v.info = self.current_info\n        if v.type is not None:\n            v.type.accept(self.type_fixer)\n        if v.setter_type is not None:\n            v.setter_type.accept(self.type_fixer)\n\n    def visit_type_alias(self, a: TypeAlias) -> None:\n        a.target.accept(self.type_fixer)\n        for v in a.alias_tvars:\n            v.accept(self.type_fixer)\n\n\nclass TypeFixer(TypeVisitor[None]):\n    def __init__(self, modules: dict[str, MypyFile], allow_missing: bool) -> None:\n        self.modules = modules\n        self.allow_missing = allow_missing\n\n    def visit_instance(self, inst: Instance) -> None:\n        # TODO: Combine Instances that are exactly the same?\n        type_ref = inst.type_ref\n        if type_ref is None:\n            return  # We've already been here.\n        inst.type_ref = None\n        inst.type = lookup_fully_qualified_typeinfo(\n            self.modules, type_ref, allow_missing=self.allow_missing\n        )\n        # TODO: Is this needed or redundant?\n        # Also fix up the bases, just in case.\n        for base in inst.type.bases:\n            if base.type is NOT_READY:\n                base.accept(self)\n        for a in inst.args:\n            a.accept(self)\n        if inst.last_known_value is not None:\n            inst.last_known_value.accept(self)\n        if inst.extra_attrs:\n            for v in inst.extra_attrs.attrs.values():\n                v.accept(self)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> None:\n        type_ref = t.type_ref\n        if type_ref is None:\n            return  # We've already been here.\n        t.type_ref = None\n        t.alias = lookup_fully_qualified_alias(\n            self.modules, type_ref, allow_missing=self.allow_missing\n        )\n        for a in t.args:\n            a.accept(self)\n\n    def visit_any(self, o: Any) -> None:\n        pass  # Nothing to descend into.\n\n    def visit_callable_type(self, ct: CallableType) -> None:\n        if ct.fallback:\n            ct.fallback.accept(self)\n        for argt in ct.arg_types:\n            # argt may be None, e.g. for __self in NamedTuple constructors.\n            if argt is not None:\n                argt.accept(self)\n        if ct.ret_type is not None:\n            ct.ret_type.accept(self)\n        for v in ct.variables:\n            v.accept(self)\n        if ct.type_guard is not None:\n            ct.type_guard.accept(self)\n        if ct.type_is is not None:\n            ct.type_is.accept(self)\n\n    def visit_overloaded(self, t: Overloaded) -> None:\n        for ct in t.items:\n            ct.accept(self)\n\n    def visit_erased_type(self, o: Any) -> None:\n        # This type should exist only temporarily during type inference\n        raise RuntimeError(\"Shouldn't get here\", o)\n\n    def visit_deleted_type(self, o: Any) -> None:\n        pass  # Nothing to descend into.\n\n    def visit_none_type(self, o: Any) -> None:\n        pass  # Nothing to descend into.\n\n    def visit_uninhabited_type(self, o: Any) -> None:\n        pass  # Nothing to descend into.\n\n    def visit_partial_type(self, o: Any) -> None:\n        raise RuntimeError(\"Shouldn't get here\", o)\n\n    def visit_tuple_type(self, tt: TupleType) -> None:\n        if tt.items:\n            for it in tt.items:\n                it.accept(self)\n        if tt.partial_fallback is not None:\n            tt.partial_fallback.accept(self)\n\n    def visit_typeddict_type(self, tdt: TypedDictType) -> None:\n        if tdt.items:\n            for it in tdt.items.values():\n                it.accept(self)\n        if tdt.fallback is not None:\n            if tdt.fallback.type_ref is not None:\n                if (\n                    lookup_fully_qualified(\n                        tdt.fallback.type_ref,\n                        self.modules,\n                        raise_on_missing=not self.allow_missing,\n                    )\n                    is None\n                ):\n                    # We reject fake TypeInfos for TypedDict fallbacks because\n                    # the latter are used in type checking and must be valid.\n                    tdt.fallback.type_ref = \"typing._TypedDict\"\n            tdt.fallback.accept(self)\n\n    def visit_literal_type(self, lt: LiteralType) -> None:\n        lt.fallback.accept(self)\n\n    def visit_type_var(self, tvt: TypeVarType) -> None:\n        if tvt.values:\n            for vt in tvt.values:\n                vt.accept(self)\n        tvt.upper_bound.accept(self)\n        tvt.default.accept(self)\n\n    def visit_param_spec(self, p: ParamSpecType) -> None:\n        p.upper_bound.accept(self)\n        p.default.accept(self)\n        p.prefix.accept(self)\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> None:\n        t.tuple_fallback.accept(self)\n        t.upper_bound.accept(self)\n        t.default.accept(self)\n\n    def visit_unpack_type(self, u: UnpackType) -> None:\n        u.type.accept(self)\n\n    def visit_parameters(self, p: Parameters) -> None:\n        for argt in p.arg_types:\n            if argt is not None:\n                argt.accept(self)\n        for var in p.variables:\n            var.accept(self)\n\n    def visit_unbound_type(self, o: UnboundType) -> None:\n        for a in o.args:\n            a.accept(self)\n\n    def visit_union_type(self, ut: UnionType) -> None:\n        if ut.items:\n            for it in ut.items:\n                it.accept(self)\n\n    def visit_type_type(self, t: TypeType) -> None:\n        t.item.accept(self)\n\n\ndef lookup_fully_qualified_typeinfo(\n    modules: dict[str, MypyFile], name: str, *, allow_missing: bool\n) -> TypeInfo:\n    stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing)\n    node = stnode.node if stnode else None\n    if isinstance(node, TypeInfo):\n        return node\n    else:\n        # Looks like a missing TypeInfo during an initial daemon load, put something there\n        assert (\n            allow_missing\n        ), \"Should never get here in normal mode, got {}:{} instead of TypeInfo\".format(\n            type(node).__name__, node.fullname if node else \"\"\n        )\n        return missing_info(modules)\n\n\ndef lookup_fully_qualified_alias(\n    modules: dict[str, MypyFile], name: str, *, allow_missing: bool\n) -> TypeAlias:\n    stnode = lookup_fully_qualified(name, modules, raise_on_missing=not allow_missing)\n    node = stnode.node if stnode else None\n    if isinstance(node, TypeAlias):\n        return node\n    elif isinstance(node, TypeInfo):\n        if node.special_alias:\n            # Already fixed up.\n            return node.special_alias\n        if node.tuple_type:\n            alias = TypeAlias.from_tuple_type(node)\n        elif node.typeddict_type:\n            alias = TypeAlias.from_typeddict_type(node)\n        else:\n            assert allow_missing\n            return missing_alias()\n        node.special_alias = alias\n        return alias\n    else:\n        # Looks like a missing TypeAlias during an initial daemon load, put something there\n        assert (\n            allow_missing\n        ), \"Should never get here in normal mode, got {}:{} instead of TypeAlias\".format(\n            type(node).__name__, node.fullname if node else \"\"\n        )\n        return missing_alias()\n\n\n_SUGGESTION: Final = \"<missing {}: *should* have gone away during fine-grained update>\"\n\n\ndef missing_info(modules: dict[str, MypyFile]) -> TypeInfo:\n    suggestion = _SUGGESTION.format(\"info\")\n    dummy_def = ClassDef(suggestion, Block([]))\n    dummy_def.fullname = suggestion\n\n    info = TypeInfo(SymbolTable(), dummy_def, \"<missing>\")\n    obj_type = lookup_fully_qualified_typeinfo(modules, \"builtins.object\", allow_missing=False)\n    info.bases = [Instance(obj_type, [])]\n    info.mro = [info, obj_type]\n    return info\n\n\ndef missing_alias() -> TypeAlias:\n    suggestion = _SUGGESTION.format(\"alias\")\n    return TypeAlias(AnyType(TypeOfAny.special_form), suggestion, \"<missing>\", line=-1, column=-1)\n"
  },
  {
    "path": "mypy/freetree.py",
    "content": "\"\"\"Generic node traverser visitor\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import Block, MypyFile\nfrom mypy.traverser import TraverserVisitor\n\n\nclass TreeFreer(TraverserVisitor):\n    def visit_block(self, block: Block) -> None:\n        super().visit_block(block)\n        block.body.clear()\n\n\ndef free_tree(tree: MypyFile) -> None:\n    \"\"\"Free all the ASTs associated with a module.\n\n    This needs to be done recursively, since symbol tables contain\n    references to definitions, so those won't be freed but we want their\n    contents to be.\n    \"\"\"\n    tree.accept(TreeFreer())\n    tree.defs.clear()\n"
  },
  {
    "path": "mypy/fscache.py",
    "content": "\"\"\"Interface for accessing the file system with automatic caching.\n\nThe idea is to cache the results of any file system state reads during\na single transaction. This has two main benefits:\n\n* This avoids redundant syscalls, as we won't perform the same OS\n  operations multiple times.\n\n* This makes it easier to reason about concurrent FS updates, as different\n  operations targeting the same paths can't report different state during\n  a transaction.\n\nNote that this only deals with reading state, not writing.\n\nProperties maintained by the API:\n\n* The contents of the file are always from the same or later time compared\n  to the reported mtime of the file, even if mtime is queried after reading\n  a file.\n\n* Repeating an operation produces the same result as the first one during\n  a transaction.\n\n* Call flush() to start a new transaction (flush the caches).\n\nThe API is a bit limited. It's easy to add new cached operations, however.\nYou should perform all file system reads through the API to actually take\nadvantage of the benefits.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport stat\n\nfrom mypy_extensions import mypyc_attr\n\nfrom mypy.util import hash_digest\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)  # for tests\nclass FileSystemCache:\n    def __init__(self) -> None:\n        # The package root is not flushed with the caches.\n        # It is set by set_package_root() below.\n        self.package_root: list[str] = []\n        self.flush()\n\n    def set_package_root(self, package_root: list[str]) -> None:\n        self.package_root = package_root\n\n    def flush(self) -> None:\n        \"\"\"Start another transaction and empty all caches.\"\"\"\n        self.stat_or_none_cache: dict[str, os.stat_result | None] = {}\n\n        self.listdir_cache: dict[str, list[str]] = {}\n        self.listdir_error_cache: dict[str, OSError] = {}\n        self.isfile_case_cache: dict[str, bool] = {}\n        self.exists_case_cache: dict[str, bool] = {}\n        self.read_cache: dict[str, bytes] = {}\n        self.read_error_cache: dict[str, Exception] = {}\n        self.hash_cache: dict[str, str] = {}\n        self.fake_package_cache: set[str] = set()\n\n    def stat_or_none(self, path: str) -> os.stat_result | None:\n        if path in self.stat_or_none_cache:\n            return self.stat_or_none_cache[path]\n\n        st = None\n        try:\n            st = os.stat(path)\n        except OSError:\n            if self.init_under_package_root(path):\n                try:\n                    st = self._fake_init(path)\n                except OSError:\n                    pass\n\n        self.stat_or_none_cache[path] = st\n        return st\n\n    def init_under_package_root(self, path: str) -> bool:\n        \"\"\"Is this path an __init__.py under a package root?\n\n        This is used to detect packages that don't contain __init__.py\n        files, which is needed to support Bazel.  The function should\n        only be called for non-existing files.\n\n        It will return True if it refers to a __init__.py file that\n        Bazel would create, so that at runtime Python would think the\n        directory containing it is a package.  For this to work you\n        must pass one or more package roots using the --package-root\n        flag.\n\n        As an exceptional case, any directory that is a package root\n        itself will not be considered to contain a __init__.py file.\n        This is different from the rules Bazel itself applies, but is\n        necessary for mypy to properly distinguish packages from other\n        directories.\n\n        See https://docs.bazel.build/versions/master/be/python.html,\n        where this behavior is described under legacy_create_init.\n        \"\"\"\n        if not self.package_root:\n            return False\n        dirname, basename = os.path.split(path)\n        if basename != \"__init__.py\":\n            return False\n        if not os.path.basename(dirname).isidentifier():\n            # Can't put an __init__.py in a place that's not an identifier\n            return False\n\n        st = self.stat_or_none(dirname)\n        if st is None:\n            return False\n        else:\n            if not stat.S_ISDIR(st.st_mode):\n                return False\n        ok = False\n\n        # skip if on a different drive\n        current_drive, _ = os.path.splitdrive(os.getcwd())\n        drive, _ = os.path.splitdrive(path)\n        if drive != current_drive:\n            return False\n        if os.path.isabs(path):\n            path = os.path.relpath(path)\n        path = os.path.normpath(path)\n        for root in self.package_root:\n            if path.startswith(root):\n                if path == root + basename:\n                    # A package root itself is never a package.\n                    ok = False\n                    break\n                else:\n                    ok = True\n        return ok\n\n    def _fake_init(self, path: str) -> os.stat_result:\n        \"\"\"Prime the cache with a fake __init__.py file.\n\n        This makes code that looks for path believe an empty file by\n        that name exists.  Should only be called after\n        init_under_package_root() returns True.\n        \"\"\"\n        dirname, basename = os.path.split(path)\n        assert basename == \"__init__.py\", path\n        assert not os.path.exists(path), path  # Not cached!\n        dirname = os.path.normpath(dirname)\n        st = os.stat(dirname)  # May raise OSError\n        # Get stat result as a list so we can modify it.\n        seq: list[float] = list(st)\n        seq[stat.ST_MODE] = stat.S_IFREG | 0o444\n        seq[stat.ST_INO] = 1\n        seq[stat.ST_NLINK] = 1\n        seq[stat.ST_SIZE] = 0\n        st = os.stat_result(seq)\n        # Make listdir() and read() also pretend this file exists.\n        self.fake_package_cache.add(dirname)\n        return st\n\n    def listdir(self, path: str) -> list[str]:\n        path = os.path.normpath(path)\n        if path in self.listdir_cache:\n            res = self.listdir_cache[path]\n            # Check the fake cache.\n            if path in self.fake_package_cache and \"__init__.py\" not in res:\n                res.append(\"__init__.py\")  # Updates the result as well as the cache\n            return res\n        if path in self.listdir_error_cache:\n            raise copy_os_error(self.listdir_error_cache[path])\n        try:\n            results = os.listdir(path)\n        except OSError as err:\n            # Like above, take a copy to reduce memory use.\n            self.listdir_error_cache[path] = copy_os_error(err)\n            raise err\n        self.listdir_cache[path] = results\n        # Check the fake cache.\n        if path in self.fake_package_cache and \"__init__.py\" not in results:\n            results.append(\"__init__.py\")\n        return results\n\n    def isfile(self, path: str) -> bool:\n        st = self.stat_or_none(path)\n        if st is None:\n            return False\n        return stat.S_ISREG(st.st_mode)\n\n    def isfile_case(self, path: str, prefix: str) -> bool:\n        \"\"\"Return whether path exists and is a file.\n\n        On case-insensitive filesystems (like Mac or Windows) this returns\n        False if the case of path's last component does not exactly match\n        the case found in the filesystem.\n\n        We check also the case of other path components up to prefix.\n        For example, if path is 'user-stubs/pack/mod.pyi' and prefix is 'user-stubs',\n        we check that the case of 'pack' and 'mod.py' matches exactly, 'user-stubs' will be\n        case insensitive on case insensitive filesystems.\n\n        The caller must ensure that prefix is a valid file system prefix of path.\n        \"\"\"\n        if not self.isfile(path):\n            # Fast path\n            return False\n        if path in self.isfile_case_cache:\n            return self.isfile_case_cache[path]\n        head, tail = os.path.split(path)\n        if not tail:\n            self.isfile_case_cache[path] = False\n            return False\n        try:\n            names = self.listdir(head)\n            # This allows one to check file name case sensitively in\n            # case-insensitive filesystems.\n            res = tail in names\n        except OSError:\n            res = False\n        if res:\n            # Also recursively check the other path components in case sensitive way.\n            res = self.exists_case(head, prefix)\n        self.isfile_case_cache[path] = res\n        return res\n\n    def exists_case(self, path: str, prefix: str) -> bool:\n        \"\"\"Return whether path exists - checking path components in case sensitive\n        fashion, up to prefix.\n        \"\"\"\n        if path in self.exists_case_cache:\n            return self.exists_case_cache[path]\n        head, tail = os.path.split(path)\n        if not head.startswith(prefix) or not tail:\n            # Only perform the check for paths under prefix.\n            self.exists_case_cache[path] = True\n            return True\n        try:\n            names = self.listdir(head)\n            # This allows one to check file name case sensitively in\n            # case-insensitive filesystems.\n            res = tail in names\n        except OSError:\n            res = False\n        if res:\n            # Also recursively check other path components.\n            res = self.exists_case(head, prefix)\n        self.exists_case_cache[path] = res\n        return res\n\n    def isdir(self, path: str) -> bool:\n        st = self.stat_or_none(path)\n        if st is None:\n            return False\n        return stat.S_ISDIR(st.st_mode)\n\n    def exists(self, path: str) -> bool:\n        st = self.stat_or_none(path)\n        return st is not None\n\n    def read(self, path: str) -> bytes:\n        if path in self.read_cache:\n            return self.read_cache[path]\n        if path in self.read_error_cache:\n            raise self.read_error_cache[path]\n\n        # Need to stat first so that the contents of file are from no\n        # earlier instant than the mtime reported by self.stat().\n        self.stat_or_none(path)\n\n        dirname, basename = os.path.split(path)\n        dirname = os.path.normpath(dirname)\n        # Check the fake cache.\n        if basename == \"__init__.py\" and dirname in self.fake_package_cache:\n            data = b\"\"\n        else:\n            try:\n                with open(path, \"rb\") as f:\n                    data = f.read()\n            except OSError as err:\n                self.read_error_cache[path] = err\n                raise\n\n        self.read_cache[path] = data\n        self.hash_cache[path] = hash_digest(data)\n        return data\n\n    def hash_digest(self, path: str) -> str:\n        if path not in self.hash_cache:\n            self.read(path)\n        return self.hash_cache[path]\n\n    def samefile(self, f1: str, f2: str) -> bool:\n        s1 = self.stat_or_none(f1)\n        s2 = self.stat_or_none(f2)\n        if s1 is None or s2 is None:\n            return False\n        return os.path.samestat(s1, s2)\n\n\ndef copy_os_error(e: OSError) -> OSError:\n    new = OSError(*e.args)\n    new.errno = e.errno\n    new.strerror = e.strerror\n    new.filename = e.filename\n    if e.filename2:\n        new.filename2 = e.filename2\n    return new\n"
  },
  {
    "path": "mypy/fswatcher.py",
    "content": "\"\"\"Watch parts of the file system for changes.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom collections.abc import Iterable, Set as AbstractSet\nfrom typing import NamedTuple\n\nfrom mypy.fscache import FileSystemCache\n\n\nclass FileData(NamedTuple):\n    st_mtime: float\n    st_size: int\n    hash: str\n\n\nclass FileSystemWatcher:\n    \"\"\"Watcher for file system changes among specific paths.\n\n    All file system access is performed using FileSystemCache. We\n    detect changed files by stat()ing them all and comparing hashes\n    of potentially changed files. If a file has both size and mtime\n    unmodified, the file is assumed to be unchanged.\n\n    An important goal of this class is to make it easier to eventually\n    use file system events to detect file changes.\n\n    Note: This class doesn't flush the file system cache. If you don't\n    manually flush it, changes won't be seen.\n    \"\"\"\n\n    # TODO: Watching directories?\n    # TODO: Handle non-files\n\n    def __init__(self, fs: FileSystemCache) -> None:\n        self.fs = fs\n        self._paths: set[str] = set()\n        self._file_data: dict[str, FileData | None] = {}\n\n    def dump_file_data(self) -> dict[str, tuple[float, int, str]]:\n        return {k: v for k, v in self._file_data.items() if v is not None}\n\n    def set_file_data(self, path: str, data: FileData) -> None:\n        self._file_data[path] = data\n\n    def add_watched_paths(self, paths: Iterable[str]) -> None:\n        for path in paths:\n            if path not in self._paths:\n                # By storing None this path will get reported as changed by\n                # find_changed if it exists.\n                self._file_data[path] = None\n        self._paths |= set(paths)\n\n    def remove_watched_paths(self, paths: Iterable[str]) -> None:\n        for path in paths:\n            if path in self._file_data:\n                del self._file_data[path]\n        self._paths -= set(paths)\n\n    def _update(self, path: str, st: os.stat_result) -> None:\n        hash_digest = self.fs.hash_digest(path)\n        self._file_data[path] = FileData(st.st_mtime, st.st_size, hash_digest)\n\n    def _find_changed(self, paths: Iterable[str]) -> AbstractSet[str]:\n        changed = set()\n        for path in paths:\n            old = self._file_data[path]\n            st = self.fs.stat_or_none(path)\n            if st is None:\n                if old is not None:\n                    # File was deleted.\n                    changed.add(path)\n                    self._file_data[path] = None\n            else:\n                if old is None:\n                    # File is new.\n                    changed.add(path)\n                    self._update(path, st)\n                # Round mtimes down, to match the mtimes we write to meta files\n                elif st.st_size != old.st_size or int(st.st_mtime) != int(old.st_mtime):\n                    # Only look for changes if size or mtime has changed as an\n                    # optimization, since calculating hash is expensive.\n                    new_hash = self.fs.hash_digest(path)\n                    self._update(path, st)\n                    if st.st_size != old.st_size or new_hash != old.hash:\n                        # Changed file.\n                        changed.add(path)\n        return changed\n\n    def find_changed(self) -> AbstractSet[str]:\n        \"\"\"Return paths that have changes since the last call, in the watched set.\"\"\"\n        return self._find_changed(self._paths)\n\n    def update_changed(self, remove: list[str], update: list[str]) -> AbstractSet[str]:\n        \"\"\"Alternative to find_changed() given explicit changes.\n\n        This only calls self.fs.stat() on added or updated files, not\n        on all files.  It believes all other files are unchanged!\n\n        Implies add_watched_paths() for add and update, and\n        remove_watched_paths() for remove.\n        \"\"\"\n        self.remove_watched_paths(remove)\n        self.add_watched_paths(update)\n        return self._find_changed(update)\n"
  },
  {
    "path": "mypy/gclogger.py",
    "content": "from __future__ import annotations\n\nimport gc\nimport time\nfrom collections.abc import Mapping\n\n\nclass GcLogger:\n    \"\"\"Context manager to log GC stats and overall time.\"\"\"\n\n    def __enter__(self) -> GcLogger:\n        self.gc_start_time: float | None = None\n        self.gc_time = 0.0\n        self.gc_calls = 0\n        self.gc_collected = 0\n        self.gc_uncollectable = 0\n        gc.callbacks.append(self.gc_callback)\n        self.start_time = time.time()\n        return self\n\n    def gc_callback(self, phase: str, info: Mapping[str, int]) -> None:\n        if phase == \"start\":\n            assert self.gc_start_time is None, \"Start phase out of sequence\"\n            self.gc_start_time = time.time()\n        elif phase == \"stop\":\n            assert self.gc_start_time is not None, \"Stop phase out of sequence\"\n            self.gc_calls += 1\n            self.gc_time += time.time() - self.gc_start_time\n            self.gc_start_time = None\n            self.gc_collected += info[\"collected\"]\n            self.gc_uncollectable += info[\"uncollectable\"]\n        else:\n            assert False, f\"Unrecognized gc phase ({phase!r})\"\n\n    def __exit__(self, *args: object) -> None:\n        while self.gc_callback in gc.callbacks:\n            gc.callbacks.remove(self.gc_callback)\n\n    def get_stats(self) -> Mapping[str, float]:\n        end_time = time.time()\n        result = {\n            \"gc_time\": self.gc_time,\n            \"gc_calls\": self.gc_calls,\n            \"gc_collected\": self.gc_collected,\n            \"gc_uncollectable\": self.gc_uncollectable,\n            \"build_time\": end_time - self.start_time,\n        }\n        return result\n"
  },
  {
    "path": "mypy/git.py",
    "content": "\"\"\"Git utilities.\"\"\"\n\n# Used also from setup.py, so don't pull in anything additional here (like mypy or typing):\nfrom __future__ import annotations\n\nimport os\nimport subprocess\n\n\ndef is_git_repo(dir: str) -> bool:\n    \"\"\"Is the given directory version-controlled with git?\"\"\"\n    return os.path.exists(os.path.join(dir, \".git\"))\n\n\ndef have_git() -> bool:\n    \"\"\"Can we run the git executable?\"\"\"\n    try:\n        subprocess.check_output([\"git\", \"--help\"])\n        return True\n    except subprocess.CalledProcessError:\n        return False\n    except OSError:\n        return False\n\n\ndef git_revision(dir: str) -> bytes:\n    \"\"\"Get the SHA-1 of the HEAD of a git repository.\"\"\"\n    return subprocess.check_output([\"git\", \"rev-parse\", \"HEAD\"], cwd=dir).strip()\n\n\ndef is_dirty(dir: str) -> bool:\n    \"\"\"Check whether a git repository has uncommitted changes.\"\"\"\n    output = subprocess.check_output([\"git\", \"status\", \"-uno\", \"--porcelain\"], cwd=dir)\n    return output.strip() != b\"\"\n"
  },
  {
    "path": "mypy/graph_utils.py",
    "content": "\"\"\"Helpers for manipulations with graphs.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterator, Set as AbstractSet\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\n\n\ndef strongly_connected_components(\n    vertices: AbstractSet[T], edges: dict[T, list[T]]\n) -> Iterator[set[T]]:\n    \"\"\"Compute Strongly Connected Components of a directed graph.\n\n    Args:\n      vertices: the labels for the vertices\n      edges: for each vertex, gives the target vertices of its outgoing edges\n\n    Returns:\n      An iterator yielding strongly connected components, each\n      represented as a set of vertices.  Each input vertex will occur\n      exactly once; vertices not part of a SCC are returned as\n      singleton sets.\n\n    From https://code.activestate.com/recipes/578507/.\n    \"\"\"\n    identified: set[T] = set()\n    stack: list[T] = []\n    index: dict[T, int] = {}\n    boundaries: list[int] = []\n\n    def dfs(v: T) -> Iterator[set[T]]:\n        index[v] = len(stack)\n        stack.append(v)\n        boundaries.append(index[v])\n\n        for w in edges[v]:\n            if w not in index:\n                yield from dfs(w)\n            elif w not in identified:\n                while index[w] < boundaries[-1]:\n                    boundaries.pop()\n\n        if boundaries[-1] == index[v]:\n            boundaries.pop()\n            scc = set(stack[index[v] :])\n            del stack[index[v] :]\n            identified.update(scc)\n            yield scc\n\n    for v in vertices:\n        if v not in index:\n            yield from dfs(v)\n\n\ndef prepare_sccs(\n    sccs: list[set[T]], edges: dict[T, list[T]]\n) -> dict[AbstractSet[T], set[AbstractSet[T]]]:\n    \"\"\"Use original edges to organize SCCs in a graph by dependencies between them.\"\"\"\n    sccsmap = {}\n    for scc in sccs:\n        scc_frozen = frozenset(scc)\n        for v in scc:\n            sccsmap[v] = scc_frozen\n    data: dict[AbstractSet[T], set[AbstractSet[T]]] = {}\n    for scc in sccs:\n        deps: set[AbstractSet[T]] = set()\n        for v in scc:\n            deps.update(sccsmap[x] for x in edges[v])\n        data[frozenset(scc)] = deps\n    return data\n\n\nclass topsort(Iterator[set[T]]):  # noqa: N801\n    \"\"\"Topological sort using Kahn's algorithm.\n\n    Uses in-degree counters and a reverse adjacency list, so the total work\n    is O(V + E).\n\n    Implemented as a class rather than a generator for better mypyc\n    compilation.\n\n    Args:\n      data: A map from vertices to all vertices that it has an edge\n            connecting it to. NOTE: dependency sets in this data\n            structure are modified in place to remove self-dependencies.\n            Orphans are handled internally and are not added to `data`.\n\n    Returns:\n      An iterator yielding sets of vertices that have an equivalent\n      ordering.\n\n    Example:\n      Suppose the input has the following structure:\n\n        {A: {B, C}, B: {D}, C: {D}}\n\n      The algorithm treats orphan dependencies as if normalized to:\n\n        {A: {B, C}, B: {D}, C: {D}, D: {}}\n\n      It will yield the following values:\n\n        {D}\n        {B, C}\n        {A}\n    \"\"\"\n\n    def __init__(self, data: dict[T, set[T]]) -> None:\n        # Single pass: remove self-deps, build reverse adjacency list,\n        # compute in-degree counts, detect orphans, and find initial ready set.\n        in_degree: dict[T, int] = {}\n        rev: dict[T, list[T]] = {}\n        ready: set[T] = set()\n        for item, deps in data.items():\n            deps.discard(item)  # Ignore self dependencies.\n            deg = len(deps)\n            in_degree[item] = deg\n            if deg == 0:\n                ready.add(item)\n            if item not in rev:\n                rev[item] = []\n            for dep in deps:\n                if dep in rev:\n                    rev[dep].append(item)\n                else:\n                    rev[dep] = [item]\n                    if dep not in data:\n                        # Orphan: appears as dependency but has no entry in data.\n                        in_degree[dep] = 0\n                        ready.add(dep)\n\n        self.in_degree = in_degree\n        self.rev = rev\n        self.ready = ready\n        self.remaining = len(in_degree) - len(ready)\n\n    def __iter__(self) -> Iterator[set[T]]:\n        return self\n\n    def __next__(self) -> set[T]:\n        ready = self.ready\n        if not ready:\n            assert self.remaining == 0, (\n                f\"A cyclic dependency exists amongst \"\n                f\"{[k for k, deg in self.in_degree.items() if deg > 0]!r}\"\n            )\n            raise StopIteration\n        in_degree = self.in_degree\n        rev = self.rev\n        new_ready: set[T] = set()\n        for item in ready:\n            for dependent in rev[item]:\n                new_deg = in_degree[dependent] - 1\n                in_degree[dependent] = new_deg\n                if new_deg == 0:\n                    new_ready.add(dependent)\n        self.remaining -= len(new_ready)\n        self.ready = new_ready\n        return ready\n"
  },
  {
    "path": "mypy/indirection.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Iterable\n\nimport mypy.types as types\nfrom mypy.types import TypeVisitor\n\n\nclass TypeIndirectionVisitor(TypeVisitor[None]):\n    \"\"\"Returns all module references within a particular type.\"\"\"\n\n    def __init__(self) -> None:\n        # Module references are collected here\n        self.modules: set[str] = set()\n        # User to avoid infinite recursion with recursive types\n        self.seen_types: set[types.TypeAliasType | types.Instance] = set()\n\n    def find_modules(self, typs: Iterable[types.Type]) -> set[str]:\n        self.modules = set()\n        self.seen_types = set()\n        for typ in typs:\n            self._visit(typ)\n        return self.modules\n\n    def _visit(self, typ: types.Type) -> None:\n        # Note: instances are needed for `class str(Sequence[str]): ...`\n        if (\n            isinstance(typ, types.TypeAliasType)\n            or isinstance(typ, types.ProperType)\n            and isinstance(typ, types.Instance)\n        ):\n            # Avoid infinite recursion for recursive types.\n            if typ in self.seen_types:\n                return\n            self.seen_types.add(typ)\n        typ.accept(self)\n\n    def _visit_type_tuple(self, typs: tuple[types.Type, ...]) -> None:\n        # Micro-optimization: Specialized version of _visit for lists\n        for typ in typs:\n            if (\n                isinstance(typ, types.TypeAliasType)\n                or isinstance(typ, types.ProperType)\n                and isinstance(typ, types.Instance)\n            ):\n                # Avoid infinite recursion for recursive types.\n                if typ in self.seen_types:\n                    continue\n                self.seen_types.add(typ)\n            typ.accept(self)\n\n    def _visit_type_list(self, typs: list[types.Type]) -> None:\n        # Micro-optimization: Specialized version of _visit for tuples\n        for typ in typs:\n            if (\n                isinstance(typ, types.TypeAliasType)\n                or isinstance(typ, types.ProperType)\n                and isinstance(typ, types.Instance)\n            ):\n                # Avoid infinite recursion for recursive types.\n                if typ in self.seen_types:\n                    continue\n                self.seen_types.add(typ)\n            typ.accept(self)\n\n    def visit_unbound_type(self, t: types.UnboundType) -> None:\n        self._visit_type_tuple(t.args)\n\n    def visit_any(self, t: types.AnyType) -> None:\n        pass\n\n    def visit_none_type(self, t: types.NoneType) -> None:\n        pass\n\n    def visit_uninhabited_type(self, t: types.UninhabitedType) -> None:\n        pass\n\n    def visit_erased_type(self, t: types.ErasedType) -> None:\n        pass\n\n    def visit_deleted_type(self, t: types.DeletedType) -> None:\n        pass\n\n    def visit_type_var(self, t: types.TypeVarType) -> None:\n        self._visit_type_list(t.values)\n        self._visit(t.upper_bound)\n        self._visit(t.default)\n\n    def visit_param_spec(self, t: types.ParamSpecType) -> None:\n        self._visit(t.upper_bound)\n        self._visit(t.default)\n        self._visit(t.prefix)\n\n    def visit_type_var_tuple(self, t: types.TypeVarTupleType) -> None:\n        self._visit(t.upper_bound)\n        self._visit(t.default)\n\n    def visit_unpack_type(self, t: types.UnpackType) -> None:\n        t.type.accept(self)\n\n    def visit_parameters(self, t: types.Parameters) -> None:\n        self._visit_type_list(t.arg_types)\n\n    def visit_instance(self, t: types.Instance) -> None:\n        # Instance is named, record its definition and continue digging into\n        # components that constitute semantic meaning of this type: bases, metaclass,\n        # tuple type, and typeddict type.\n        # Note: we cannot simply record the MRO, in case an intermediate base contains\n        # a reference to type alias, this affects meaning of map_instance_to_supertype(),\n        # see e.g. testDoubleReexportGenericUpdated.\n        self._visit_type_tuple(t.args)\n        if t.type:\n            # Important optimization: instead of simply recording the definition and\n            # recursing into bases, record the MRO and only traverse generic bases.\n            for s in t.type.mro:\n                self.modules.add(s.module_name)\n                for base in s.bases:\n                    if base.args:\n                        self._visit_type_tuple(base.args)\n            if t.type.metaclass_type:\n                self._visit(t.type.metaclass_type)\n            if t.type.typeddict_type:\n                self._visit(t.type.typeddict_type)\n            if t.type.tuple_type:\n                self._visit(t.type.tuple_type)\n            if t.type.is_protocol:\n                # For protocols, member types constitute the semantic meaning of the type.\n                # TODO: this doesn't cover some edge cases, like setter types and exotic nodes.\n                for m in t.type.protocol_members:\n                    node = t.type.names.get(m)\n                    if node and node.type:\n                        self._visit(node.type)\n\n    def visit_callable_type(self, t: types.CallableType) -> None:\n        self._visit_type_list(t.arg_types)\n        self._visit(t.ret_type)\n        self._visit_type_tuple(t.variables)\n\n    def visit_overloaded(self, t: types.Overloaded) -> None:\n        for item in t.items:\n            self._visit(item)\n        self._visit(t.fallback)\n\n    def visit_tuple_type(self, t: types.TupleType) -> None:\n        self._visit_type_list(t.items)\n        self._visit(t.partial_fallback)\n\n    def visit_typeddict_type(self, t: types.TypedDictType) -> None:\n        self._visit_type_list(list(t.items.values()))\n        self._visit(t.fallback)\n\n    def visit_literal_type(self, t: types.LiteralType) -> None:\n        self._visit(t.fallback)\n\n    def visit_union_type(self, t: types.UnionType) -> None:\n        self._visit_type_list(t.items)\n\n    def visit_partial_type(self, t: types.PartialType) -> None:\n        pass\n\n    def visit_type_type(self, t: types.TypeType) -> None:\n        self._visit(t.item)\n\n    def visit_type_alias_type(self, t: types.TypeAliasType) -> None:\n        # Type alias is named, record its definition and continue digging into\n        # components that constitute semantic meaning of this type: target and args.\n        if t.alias:\n            self.modules.add(t.alias.module)\n            self._visit(t.alias.target)\n        self._visit_type_list(t.args)\n"
  },
  {
    "path": "mypy/infer.py",
    "content": "\"\"\"Utilities for type argument inference.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import NamedTuple\n\nfrom mypy.constraints import (\n    SUBTYPE_OF,\n    SUPERTYPE_OF,\n    infer_constraints,\n    infer_constraints_for_callable,\n)\nfrom mypy.nodes import ArgKind\nfrom mypy.solve import solve_constraints\nfrom mypy.types import CallableType, Instance, Type, TypeVarLikeType\n\n\nclass ArgumentInferContext(NamedTuple):\n    \"\"\"Type argument inference context.\n\n    We need this because we pass around ``Mapping`` and ``Iterable`` types.\n    These types are only known by ``TypeChecker`` itself.\n    It is required for ``*`` and ``**`` argument inference.\n\n    https://github.com/python/mypy/issues/11144\n    \"\"\"\n\n    mapping_type: Instance\n    iterable_type: Instance\n\n\ndef infer_function_type_arguments(\n    callee_type: CallableType,\n    arg_types: Sequence[Type | None],\n    arg_kinds: list[ArgKind],\n    arg_names: Sequence[str | None] | None,\n    formal_to_actual: list[list[int]],\n    context: ArgumentInferContext,\n    strict: bool = True,\n    allow_polymorphic: bool = False,\n) -> tuple[list[Type | None], list[TypeVarLikeType]]:\n    \"\"\"Infer the type arguments of a generic function.\n\n    Return an array of lower bound types for the type variables -1 (at\n    index 0), -2 (at index 1), etc. A lower bound is None if a value\n    could not be inferred.\n\n    Arguments:\n      callee_type: the target generic function\n      arg_types: argument types at the call site (each optional; if None,\n                 we are not considering this argument in the current pass)\n      arg_kinds: nodes.ARG_* values for arg_types\n      formal_to_actual: mapping from formal to actual variable indices\n    \"\"\"\n    # Infer constraints.\n    constraints = infer_constraints_for_callable(\n        callee_type, arg_types, arg_kinds, arg_names, formal_to_actual, context\n    )\n\n    # Solve constraints.\n    type_vars = callee_type.variables\n    return solve_constraints(type_vars, constraints, strict, allow_polymorphic)\n\n\ndef infer_type_arguments(\n    type_vars: Sequence[TypeVarLikeType],\n    template: Type,\n    actual: Type,\n    is_supertype: bool = False,\n    skip_unsatisfied: bool = False,\n) -> list[Type | None]:\n    # Like infer_function_type_arguments, but only match a single type\n    # against a generic type.\n    constraints = infer_constraints(template, actual, SUPERTYPE_OF if is_supertype else SUBTYPE_OF)\n    return solve_constraints(type_vars, constraints, skip_unsatisfied=skip_unsatisfied)[0]\n"
  },
  {
    "path": "mypy/inspections.py",
    "content": "from __future__ import annotations\n\nimport os\nfrom collections import defaultdict\nfrom collections.abc import Callable\nfrom functools import cmp_to_key\n\nfrom mypy.build import State\nfrom mypy.messages import format_type\nfrom mypy.modulefinder import PYTHON_EXTENSIONS\nfrom mypy.nodes import (\n    LDEF,\n    Decorator,\n    Expression,\n    FuncBase,\n    MemberExpr,\n    MypyFile,\n    Node,\n    OverloadedFuncDef,\n    RefExpr,\n    SymbolNode,\n    TypeInfo,\n    Var,\n)\nfrom mypy.server.update import FineGrainedBuildManager\nfrom mypy.traverser import ExtendedTraverserVisitor\nfrom mypy.typeops import tuple_fallback\nfrom mypy.types import (\n    FunctionLike,\n    Instance,\n    LiteralType,\n    ProperType,\n    TupleType,\n    TypedDictType,\n    TypeVarType,\n    UnionType,\n    get_proper_type,\n)\nfrom mypy.typevars import fill_typevars_with_any\n\n\ndef node_starts_after(o: Node, line: int, column: int) -> bool:\n    return o.line > line or o.line == line and o.column > column\n\n\ndef node_ends_before(o: Node, line: int, column: int) -> bool:\n    # Unfortunately, end positions for some statements are a mess,\n    # e.g. overloaded functions, so we return False when we don't know.\n    if o.end_line is not None and o.end_column is not None:\n        if o.end_line < line or o.end_line == line and o.end_column < column:\n            return True\n    return False\n\n\ndef expr_span(expr: Expression) -> str:\n    \"\"\"Format expression span as in mypy error messages.\"\"\"\n    return f\"{expr.line}:{expr.column + 1}:{expr.end_line}:{expr.end_column}\"\n\n\ndef get_instance_fallback(typ: ProperType) -> list[Instance]:\n    \"\"\"Returns the Instance fallback for this type if one exists or None.\"\"\"\n    if isinstance(typ, Instance):\n        return [typ]\n    elif isinstance(typ, TupleType):\n        return [tuple_fallback(typ)]\n    elif isinstance(typ, TypedDictType):\n        return [typ.fallback]\n    elif isinstance(typ, FunctionLike):\n        return [typ.fallback]\n    elif isinstance(typ, LiteralType):\n        return [typ.fallback]\n    elif isinstance(typ, TypeVarType):\n        if typ.values:\n            res = []\n            for t in typ.values:\n                res.extend(get_instance_fallback(get_proper_type(t)))\n            return res\n        return get_instance_fallback(get_proper_type(typ.upper_bound))\n    elif isinstance(typ, UnionType):\n        res = []\n        for t in typ.items:\n            res.extend(get_instance_fallback(get_proper_type(t)))\n        return res\n    return []\n\n\ndef find_node(name: str, info: TypeInfo) -> Var | FuncBase | None:\n    \"\"\"Find the node defining member 'name' in given TypeInfo.\"\"\"\n    # TODO: this code shares some logic with checkmember.py\n    method = info.get_method(name)\n    if method:\n        if isinstance(method, Decorator):\n            return method.var\n        if method.is_property:\n            assert isinstance(method, OverloadedFuncDef)\n            dec = method.items[0]\n            assert isinstance(dec, Decorator)\n            return dec.var\n        return method\n    else:\n        # don't have such method, maybe variable?\n        node = info.get(name)\n        v = node.node if node else None\n        if isinstance(v, Var):\n            return v\n    return None\n\n\ndef find_module_by_fullname(fullname: str, modules: dict[str, State]) -> State | None:\n    \"\"\"Find module by a node fullname.\n\n    This logic mimics the one we use in fixup, so should be good enough.\n    \"\"\"\n    head = fullname\n    # Special case: a module symbol is considered to be defined in itself, not in enclosing\n    # package, since this is what users want when clicking go to definition on a module.\n    if head in modules:\n        return modules[head]\n    while True:\n        if \".\" not in head:\n            return None\n        head, tail = head.rsplit(\".\", maxsplit=1)\n        mod = modules.get(head)\n        if mod is not None:\n            return mod\n\n\nclass SearchVisitor(ExtendedTraverserVisitor):\n    \"\"\"Visitor looking for an expression whose span matches given one exactly.\"\"\"\n\n    def __init__(self, line: int, column: int, end_line: int, end_column: int) -> None:\n        self.line = line\n        self.column = column\n        self.end_line = end_line\n        self.end_column = end_column\n        self.result: Expression | None = None\n\n    def visit(self, o: Node) -> bool:\n        if node_starts_after(o, self.line, self.column):\n            return False\n        if node_ends_before(o, self.end_line, self.end_column):\n            return False\n        if (\n            o.line == self.line\n            and o.end_line == self.end_line\n            and o.column == self.column\n            and o.end_column == self.end_column\n        ):\n            if isinstance(o, Expression):\n                self.result = o\n        return self.result is None\n\n\ndef find_by_location(\n    tree: MypyFile, line: int, column: int, end_line: int, end_column: int\n) -> Expression | None:\n    \"\"\"Find an expression matching given span, or None if not found.\"\"\"\n    if end_line < line:\n        raise ValueError('\"end_line\" must not be before \"line\"')\n    if end_line == line and end_column <= column:\n        raise ValueError('\"end_column\" must be after \"column\"')\n    visitor = SearchVisitor(line, column, end_line, end_column)\n    tree.accept(visitor)\n    return visitor.result\n\n\nclass SearchAllVisitor(ExtendedTraverserVisitor):\n    \"\"\"Visitor looking for all expressions whose spans enclose given position.\"\"\"\n\n    def __init__(self, line: int, column: int) -> None:\n        self.line = line\n        self.column = column\n        self.result: list[Expression] = []\n\n    def visit(self, o: Node) -> bool:\n        if node_starts_after(o, self.line, self.column):\n            return False\n        if node_ends_before(o, self.line, self.column):\n            return False\n        if isinstance(o, Expression):\n            self.result.append(o)\n        return True\n\n\ndef find_all_by_location(tree: MypyFile, line: int, column: int) -> list[Expression]:\n    \"\"\"Find all expressions enclosing given position starting from innermost.\"\"\"\n    visitor = SearchAllVisitor(line, column)\n    tree.accept(visitor)\n    return list(reversed(visitor.result))\n\n\nclass InspectionEngine:\n    \"\"\"Engine for locating and statically inspecting expressions.\"\"\"\n\n    def __init__(\n        self,\n        fg_manager: FineGrainedBuildManager,\n        *,\n        verbosity: int = 0,\n        limit: int = 0,\n        include_span: bool = False,\n        include_kind: bool = False,\n        include_object_attrs: bool = False,\n        union_attrs: bool = False,\n        force_reload: bool = False,\n    ) -> None:\n        self.fg_manager = fg_manager\n        self.verbosity = verbosity\n        self.limit = limit\n        self.include_span = include_span\n        self.include_kind = include_kind\n        self.include_object_attrs = include_object_attrs\n        self.union_attrs = union_attrs\n        self.force_reload = force_reload\n        # Module for which inspection was requested.\n        self.module: State | None = None\n\n    def reload_module(self, state: State) -> None:\n        \"\"\"Reload given module while temporary exporting types.\"\"\"\n        old = self.fg_manager.manager.options.export_types\n        self.fg_manager.manager.options.export_types = True\n        try:\n            self.fg_manager.flush_cache()\n            assert state.path is not None\n            self.fg_manager.update([(state.id, state.path)], [])\n        finally:\n            self.fg_manager.manager.options.export_types = old\n\n    def expr_type(self, expression: Expression) -> tuple[str, bool]:\n        \"\"\"Format type for an expression using current options.\n\n        If type is known, second item returned is True. If type is not known, an error\n        message is returned instead, and second item returned is False.\n        \"\"\"\n        expr_type = self.fg_manager.manager.all_types.get(expression)\n        if expr_type is None:\n            return self.missing_type(expression), False\n\n        type_str = format_type(\n            expr_type, self.fg_manager.manager.options, verbosity=self.verbosity\n        )\n        return self.add_prefixes(type_str, expression), True\n\n    def object_type(self) -> Instance:\n        builtins = self.fg_manager.graph[\"builtins\"].tree\n        assert builtins is not None\n        object_node = builtins.names[\"object\"].node\n        assert isinstance(object_node, TypeInfo)\n        return Instance(object_node, [])\n\n    def collect_attrs(self, instances: list[Instance]) -> dict[TypeInfo, list[str]]:\n        \"\"\"Collect attributes from all union/typevar variants.\"\"\"\n\n        def item_attrs(attr_dict: dict[TypeInfo, list[str]]) -> set[str]:\n            attrs = set()\n            for base in attr_dict:\n                attrs |= set(attr_dict[base])\n            return attrs\n\n        def cmp_types(x: TypeInfo, y: TypeInfo) -> int:\n            if x in y.mro:\n                return 1\n            if y in x.mro:\n                return -1\n            return 0\n\n        # First gather all attributes for every union variant.\n        assert instances\n        all_attrs = []\n        for instance in instances:\n            attrs = {}\n            mro = instance.type.mro\n            if not self.include_object_attrs:\n                mro = mro[:-1]\n            for base in mro:\n                attrs[base] = sorted(base.names)\n            all_attrs.append(attrs)\n\n        # Find attributes valid for all variants in a union or type variable.\n        intersection = item_attrs(all_attrs[0])\n        for item in all_attrs[1:]:\n            intersection &= item_attrs(item)\n\n        # Combine attributes from all variants into a single dict while\n        # also removing invalid attributes (unless using --union-attrs).\n        combined_attrs = defaultdict(list)\n        for item in all_attrs:\n            for base in item:\n                if base in combined_attrs:\n                    continue\n                for name in item[base]:\n                    if self.union_attrs or name in intersection:\n                        combined_attrs[base].append(name)\n\n        # Sort bases by MRO, unrelated will appear in the order they appeared as union variants.\n        sorted_bases = sorted(combined_attrs.keys(), key=cmp_to_key(cmp_types))\n        result = {}\n        for base in sorted_bases:\n            if not combined_attrs[base]:\n                # Skip bases where everytihng was filtered out.\n                continue\n            result[base] = combined_attrs[base]\n        return result\n\n    def _fill_from_dict(\n        self, attrs_strs: list[str], attrs_dict: dict[TypeInfo, list[str]]\n    ) -> None:\n        for base in attrs_dict:\n            cls_name = base.name if self.verbosity < 1 else base.fullname\n            attrs = [f'\"{attr}\"' for attr in attrs_dict[base]]\n            attrs_strs.append(f'\"{cls_name}\": [{\", \".join(attrs)}]')\n\n    def expr_attrs(self, expression: Expression) -> tuple[str, bool]:\n        \"\"\"Format attributes that are valid for a given expression.\n\n        If expression type is not an Instance, try using fallback. Attributes are\n        returned as a JSON (ordered by MRO) that maps base class name to list of\n        attributes. Attributes may appear in multiple bases if overridden (we simply\n        follow usual mypy logic for creating new Vars etc).\n        \"\"\"\n        expr_type = self.fg_manager.manager.all_types.get(expression)\n        if expr_type is None:\n            return self.missing_type(expression), False\n\n        expr_type = get_proper_type(expr_type)\n        instances = get_instance_fallback(expr_type)\n        if not instances:\n            # Everything is an object in Python.\n            instances = [self.object_type()]\n\n        attrs_dict = self.collect_attrs(instances)\n\n        # Special case: modules have names apart from those from ModuleType.\n        if isinstance(expression, RefExpr) and isinstance(expression.node, MypyFile):\n            node = expression.node\n            names = sorted(node.names)\n            if \"__builtins__\" in names:\n                # This is just to make tests stable. No one will really need this name.\n                names.remove(\"__builtins__\")\n            mod_dict = {f'\"<{node.fullname}>\"': [f'\"{name}\"' for name in names]}\n        else:\n            mod_dict = {}\n\n        # Special case: for class callables, prepend with the class attributes.\n        # TODO: also handle cases when such callable appears in a union.\n        if isinstance(expr_type, FunctionLike) and expr_type.is_type_obj():\n            template = fill_typevars_with_any(expr_type.type_object())\n            class_dict = self.collect_attrs(get_instance_fallback(template))\n        else:\n            class_dict = {}\n\n        # We don't use JSON dump to be sure keys order is always preserved.\n        base_attrs = []\n        if mod_dict:\n            for mod in mod_dict:\n                base_attrs.append(f'{mod}: [{\", \".join(mod_dict[mod])}]')\n        self._fill_from_dict(base_attrs, class_dict)\n        self._fill_from_dict(base_attrs, attrs_dict)\n        return self.add_prefixes(f'{{{\", \".join(base_attrs)}}}', expression), True\n\n    def format_node(self, module: State, node: FuncBase | SymbolNode) -> str:\n        return f\"{module.path}:{node.line}:{node.column + 1}:{node.name}\"\n\n    def collect_nodes(self, expression: RefExpr) -> list[FuncBase | SymbolNode]:\n        \"\"\"Collect nodes that can be referred to by an expression.\n\n        Note: it can be more than one for example in case of a union attribute.\n        \"\"\"\n        node: FuncBase | SymbolNode | None = expression.node\n        nodes: list[FuncBase | SymbolNode]\n        if node is None:\n            # Tricky case: instance attribute\n            if isinstance(expression, MemberExpr) and expression.kind is None:\n                base_type = self.fg_manager.manager.all_types.get(expression.expr)\n                if base_type is None:\n                    return []\n\n                # Now we use the base type to figure out where the attribute is defined.\n                base_type = get_proper_type(base_type)\n                instances = get_instance_fallback(base_type)\n                nodes = []\n                for instance in instances:\n                    node = find_node(expression.name, instance.type)\n                    if node:\n                        nodes.append(node)\n                if not nodes:\n                    # Try checking class namespace if attribute is on a class object.\n                    if isinstance(base_type, FunctionLike) and base_type.is_type_obj():\n                        instances = get_instance_fallback(\n                            fill_typevars_with_any(base_type.type_object())\n                        )\n                        for instance in instances:\n                            node = find_node(expression.name, instance.type)\n                            if node:\n                                nodes.append(node)\n                    else:\n                        # Still no luck, give up.\n                        return []\n            else:\n                return []\n        else:\n            # Easy case: a module-level definition\n            nodes = [node]\n        return nodes\n\n    def modules_for_nodes(\n        self, nodes: list[FuncBase | SymbolNode], expression: RefExpr\n    ) -> tuple[dict[FuncBase | SymbolNode, State], bool]:\n        \"\"\"Gather modules where given nodes where defined.\n\n        Also check if they need to be refreshed (cached nodes may have\n        lines/columns missing).\n        \"\"\"\n        modules = {}\n        reload_needed = False\n        for node in nodes:\n            module = find_module_by_fullname(node.fullname, self.fg_manager.graph)\n            if not module:\n                if expression.kind == LDEF and self.module:\n                    module = self.module\n                else:\n                    continue\n            modules[node] = module\n            if not module.tree or module.tree.is_cache_skeleton or self.force_reload:\n                reload_needed |= not module.tree or module.tree.is_cache_skeleton\n                self.reload_module(module)\n        return modules, reload_needed\n\n    def expression_def(self, expression: Expression) -> tuple[str, bool]:\n        \"\"\"Find and format definition location for an expression.\n\n        If it is not a RefExpr, it is effectively skipped by returning an\n        empty result.\n        \"\"\"\n        if not isinstance(expression, RefExpr):\n            # If there are no suitable matches at all, we return error later.\n            return \"\", True\n\n        nodes = self.collect_nodes(expression)\n\n        if not nodes:\n            return self.missing_node(expression), False\n\n        modules, reload_needed = self.modules_for_nodes(nodes, expression)\n        if reload_needed:\n            # TODO: line/column are not stored in cache for vast majority of symbol nodes.\n            # Adding them will make thing faster, but will have visible memory impact.\n            nodes = self.collect_nodes(expression)\n            modules, reload_needed = self.modules_for_nodes(nodes, expression)\n            assert not reload_needed\n\n        result = []\n        for node in modules:\n            result.append(self.format_node(modules[node], node))\n\n        if not result:\n            return self.missing_node(expression), False\n\n        return self.add_prefixes(\", \".join(result), expression), True\n\n    def missing_type(self, expression: Expression) -> str:\n        alt_suggestion = \"\"\n        if not self.force_reload:\n            alt_suggestion = \" or try --force-reload\"\n        return (\n            f'No known type available for \"{type(expression).__name__}\"'\n            f\" (maybe unreachable{alt_suggestion})\"\n        )\n\n    def missing_node(self, expression: Expression) -> str:\n        return (\n            f'Cannot find definition for \"{type(expression).__name__}\" at {expr_span(expression)}'\n        )\n\n    def add_prefixes(self, result: str, expression: Expression) -> str:\n        prefixes = []\n        if self.include_kind:\n            prefixes.append(f\"{type(expression).__name__}\")\n        if self.include_span:\n            prefixes.append(expr_span(expression))\n        if prefixes:\n            prefix = \":\".join(prefixes) + \" -> \"\n        else:\n            prefix = \"\"\n        return prefix + result\n\n    def run_inspection_by_exact_location(\n        self,\n        tree: MypyFile,\n        line: int,\n        column: int,\n        end_line: int,\n        end_column: int,\n        method: Callable[[Expression], tuple[str, bool]],\n    ) -> dict[str, object]:\n        \"\"\"Get type of an expression matching a span.\n\n        Type or error is returned as a standard daemon response dict.\n        \"\"\"\n        try:\n            expression = find_by_location(tree, line, column - 1, end_line, end_column)\n        except ValueError as err:\n            return {\"error\": str(err)}\n\n        if expression is None:\n            span = f\"{line}:{column}:{end_line}:{end_column}\"\n            return {\"out\": f\"Can't find expression at span {span}\", \"err\": \"\", \"status\": 1}\n\n        inspection_str, success = method(expression)\n        return {\"out\": inspection_str, \"err\": \"\", \"status\": 0 if success else 1}\n\n    def run_inspection_by_position(\n        self,\n        tree: MypyFile,\n        line: int,\n        column: int,\n        method: Callable[[Expression], tuple[str, bool]],\n    ) -> dict[str, object]:\n        \"\"\"Get types of all expressions enclosing a position.\n\n        Types and/or errors are returned as a standard daemon response dict.\n        \"\"\"\n        expressions = find_all_by_location(tree, line, column - 1)\n        if not expressions:\n            position = f\"{line}:{column}\"\n            return {\n                \"out\": f\"Can't find any expressions at position {position}\",\n                \"err\": \"\",\n                \"status\": 1,\n            }\n\n        inspection_strs = []\n        status = 0\n        for expression in expressions:\n            inspection_str, success = method(expression)\n            if not success:\n                status = 1\n            if inspection_str:\n                inspection_strs.append(inspection_str)\n        if self.limit:\n            inspection_strs = inspection_strs[: self.limit]\n        return {\"out\": \"\\n\".join(inspection_strs), \"err\": \"\", \"status\": status}\n\n    def find_module(self, file: str) -> tuple[State | None, dict[str, object]]:\n        \"\"\"Find module by path, or return a suitable error message.\n\n        Note we don't use exceptions to simplify handling 1 vs 2 statuses.\n        \"\"\"\n        if not any(file.endswith(ext) for ext in PYTHON_EXTENSIONS):\n            return None, {\"error\": \"Source file is not a Python file\"}\n\n        # We are using a bit slower but robust way to find a module by path,\n        # to be sure that namespace packages are handled properly.\n        abs_path = os.path.abspath(file)\n        state = next((s for s in self.fg_manager.graph.values() if s.abspath == abs_path), None)\n        self.module = state\n        return (\n            state,\n            {\"out\": f\"Unknown module: {file}\", \"err\": \"\", \"status\": 1} if state is None else {},\n        )\n\n    def run_inspection(\n        self, location: str, method: Callable[[Expression], tuple[str, bool]]\n    ) -> dict[str, object]:\n        \"\"\"Top-level logic to inspect expression(s) at a location.\n\n        This can be reused by various simple inspections.\n        \"\"\"\n        try:\n            file, pos = parse_location(location)\n        except ValueError as err:\n            return {\"error\": str(err)}\n\n        state, err_dict = self.find_module(file)\n        if state is None:\n            assert err_dict\n            return err_dict\n\n        # Force reloading to load from cache, account for any edits, etc.\n        if not state.tree or state.tree.is_cache_skeleton or self.force_reload:\n            self.reload_module(state)\n        assert state.tree is not None\n\n        if len(pos) == 4:\n            # Full span, return an exact match only.\n            line, column, end_line, end_column = pos\n            return self.run_inspection_by_exact_location(\n                state.tree, line, column, end_line, end_column, method\n            )\n        assert len(pos) == 2\n        # Inexact location, return all expressions.\n        line, column = pos\n        return self.run_inspection_by_position(state.tree, line, column, method)\n\n    def get_type(self, location: str) -> dict[str, object]:\n        \"\"\"Get types of expression(s) at a location.\"\"\"\n        return self.run_inspection(location, self.expr_type)\n\n    def get_attrs(self, location: str) -> dict[str, object]:\n        \"\"\"Get attributes of expression(s) at a location.\"\"\"\n        return self.run_inspection(location, self.expr_attrs)\n\n    def get_definition(self, location: str) -> dict[str, object]:\n        \"\"\"Get symbol definitions of expression(s) at a location.\"\"\"\n        result = self.run_inspection(location, self.expression_def)\n        if \"out\" in result and not result[\"out\"]:\n            # None of the expressions found turns out to be a RefExpr.\n            _, location = location.split(\":\", maxsplit=1)\n            result[\"out\"] = f\"No name or member expressions at {location}\"\n            result[\"status\"] = 1\n        return result\n\n\ndef parse_location(location: str) -> tuple[str, list[int]]:\n    if location.count(\":\") < 2:\n        raise ValueError(\"Format should be file:line:column[:end_line:end_column]\")\n    parts = location.rsplit(\":\", maxsplit=2)\n    start, *rest = parts\n    # Note: we must allow drive prefix like `C:` on Windows.\n    if start.count(\":\") < 2:\n        return start, [int(p) for p in rest]\n    parts = start.rsplit(\":\", maxsplit=2)\n    start, *start_rest = parts\n    if start.count(\":\") < 2:\n        return start, [int(p) for p in start_rest + rest]\n    raise ValueError(\"Format should be file:line:column[:end_line:end_column]\")\n"
  },
  {
    "path": "mypy/ipc.py",
    "content": "\"\"\"Cross-platform abstractions for inter-process communication\n\nOn Unix, this uses AF_UNIX sockets.\nOn Windows, this uses NamedPipes.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\nimport shutil\nimport struct\nimport sys\nimport tempfile\nfrom abc import abstractmethod\nfrom collections.abc import Callable\nfrom select import select\nfrom types import TracebackType\nfrom typing import Final\nfrom typing_extensions import Self\n\nfrom librt.base64 import urlsafe_b64encode\nfrom librt.internal import ReadBuffer, WriteBuffer\n\nif sys.platform == \"win32\":\n    # This may be private, but it is needed for IPC on Windows, and is basically stable\n    import _winapi\n    import ctypes\n\n    _IPCHandle = int\n\n    kernel32 = ctypes.windll.kernel32\n    DisconnectNamedPipe: Callable[[_IPCHandle], int] = kernel32.DisconnectNamedPipe\n    FlushFileBuffers: Callable[[_IPCHandle], int] = kernel32.FlushFileBuffers\nelse:\n    import socket\n\n    _IPCHandle = socket.socket\n\n# Size of the message packed as !L, i.e. 4 bytes in network order (big-endian).\nHEADER_SIZE = 4\n\n\n# TODO: we should make sure consistent exceptions are raised on different platforms.\n# Currently we raise either IPCException or OSError for equivalent conditions.\nclass IPCException(Exception):\n    \"\"\"Exception for IPC issues.\"\"\"\n\n\nclass IPCBase:\n    \"\"\"Base class for communication between the dmypy client and server.\n\n    This contains logic shared between the client and server, such as reading\n    and writing.\n    We want to be able to send multiple \"messages\" over a single connection and\n    to be able to separate the messages. We do this by prefixing each message\n    with its size in a fixed format.\n    \"\"\"\n\n    connection: _IPCHandle\n\n    def __init__(self, name: str, timeout: float | None) -> None:\n        self.name = name\n        self.timeout = timeout\n        self.message_size: int | None = None\n        self.buffer = bytearray()\n\n    def frame_from_buffer(self) -> bytes | None:\n        \"\"\"Return a full frame from the bytes we have in the buffer.\"\"\"\n        size = len(self.buffer)\n        if size < HEADER_SIZE:\n            return None\n        if self.message_size is None:\n            self.message_size = struct.unpack(\"!L\", self.buffer[:HEADER_SIZE])[0]\n        if size < self.message_size + HEADER_SIZE:\n            return None\n        # We have a full frame, avoid extra copy in case we get a large frame.\n        bdata = memoryview(self.buffer)[HEADER_SIZE : HEADER_SIZE + self.message_size]\n        self.buffer = self.buffer[HEADER_SIZE + self.message_size :]\n        self.message_size = None\n        return bytes(bdata)\n\n    def read(self, size: int = 100000) -> str:\n        return self.read_bytes(size).decode(\"utf-8\")\n\n    def read_bytes(self, size: int = 100000) -> bytes:\n        \"\"\"Read bytes from an IPC connection until we have a full frame.\"\"\"\n        if sys.platform == \"win32\":\n            while True:\n                # Check if we already have a message in the buffer before\n                # receiving any more data from the socket.\n                bdata = self.frame_from_buffer()\n                if bdata is not None:\n                    break\n\n                # Receive more data into the buffer.\n                ov, err = _winapi.ReadFile(self.connection, size, overlapped=True)\n                try:\n                    if err == _winapi.ERROR_IO_PENDING:\n                        timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE\n                        res = _winapi.WaitForSingleObject(ov.event, timeout)\n                        if res != _winapi.WAIT_OBJECT_0:\n                            raise IPCException(f\"Bad result from I/O wait: {res}\")\n                except BaseException:\n                    ov.cancel()\n                    raise\n                _, err = ov.GetOverlappedResult(True)\n                more = ov.getbuffer()\n                if more:\n                    self.buffer.extend(more)\n                    bdata = self.frame_from_buffer()\n                    if bdata is not None:\n                        break\n                if err == 0:\n                    # we are done!\n                    break\n                elif err == _winapi.ERROR_MORE_DATA:\n                    # read again\n                    continue\n                elif err == _winapi.ERROR_OPERATION_ABORTED:\n                    raise IPCException(\"ReadFile operation aborted.\")\n        else:\n            while True:\n                # Check if we already have a message in the buffer before\n                # receiving any more data from the socket.\n                bdata = self.frame_from_buffer()\n                if bdata is not None:\n                    break\n\n                # Receive more data into the buffer.\n                more = self.connection.recv(size)\n                if not more:\n                    # Connection closed\n                    break\n                self.buffer.extend(more)\n\n        if not bdata:\n            # Socket was empty, and we didn't get any frame.\n            # This should only happen if the socket was closed.\n            return b\"\"\n        return bdata\n\n    def write(self, data: str) -> None:\n        self.write_bytes(data.encode(\"utf-8\"))\n\n    def write_bytes(self, data: bytes) -> None:\n        \"\"\"Write to an IPC connection.\"\"\"\n\n        # Frame the data by adding fixed size header.\n        encoded_data = struct.pack(\"!L\", len(data)) + data\n\n        if sys.platform == \"win32\":\n            try:\n                ov, err = _winapi.WriteFile(self.connection, encoded_data, overlapped=True)\n                try:\n                    if err == _winapi.ERROR_IO_PENDING:\n                        timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE\n                        res = _winapi.WaitForSingleObject(ov.event, timeout)\n                        if res != _winapi.WAIT_OBJECT_0:\n                            raise IPCException(f\"Bad result from I/O wait: {res}\")\n                    elif err != 0:\n                        raise IPCException(f\"Failed writing to pipe with error: {err}\")\n                except BaseException:\n                    ov.cancel()\n                    raise\n                bytes_written, err = ov.GetOverlappedResult(True)\n                assert err == 0, err\n                assert bytes_written == len(encoded_data)\n            except OSError as e:\n                raise IPCException(f\"Failed to write with error: {e.winerror}\") from e\n        else:\n            self.connection.sendall(encoded_data)\n\n    def close(self) -> None:\n        if sys.platform == \"win32\":\n            if self.connection != _winapi.NULL:\n                _winapi.CloseHandle(self.connection)\n        else:\n            self.connection.close()\n\n\nclass IPCClient(IPCBase):\n    \"\"\"The client side of an IPC connection.\"\"\"\n\n    def __init__(self, name: str, timeout: float | None) -> None:\n        super().__init__(name, timeout)\n        if sys.platform == \"win32\":\n            timeout = int(self.timeout * 1000) if self.timeout else _winapi.NMPWAIT_WAIT_FOREVER\n            try:\n                _winapi.WaitNamedPipe(self.name, timeout)\n            except FileNotFoundError as e:\n                raise IPCException(f\"The NamedPipe at {self.name} was not found.\") from e\n            except OSError as e:\n                if e.winerror == _winapi.ERROR_SEM_TIMEOUT:\n                    raise IPCException(\"Timed out waiting for connection.\") from e\n                else:\n                    raise\n            try:\n                self.connection = _winapi.CreateFile(\n                    self.name,\n                    _winapi.GENERIC_READ | _winapi.GENERIC_WRITE,\n                    0,\n                    _winapi.NULL,\n                    _winapi.OPEN_EXISTING,\n                    _winapi.FILE_FLAG_OVERLAPPED,\n                    _winapi.NULL,\n                )\n            except OSError as e:\n                if e.winerror == _winapi.ERROR_PIPE_BUSY:\n                    raise IPCException(\"The connection is busy.\") from e\n                else:\n                    raise\n            _winapi.SetNamedPipeHandleState(\n                self.connection, _winapi.PIPE_READMODE_MESSAGE, None, None\n            )\n        else:\n            self.connection = socket.socket(socket.AF_UNIX)\n            self.connection.settimeout(timeout)\n            self.connection.connect(name)\n\n    def __enter__(self) -> IPCClient:\n        return self\n\n    def __exit__(\n        self,\n        exc_ty: type[BaseException] | None = None,\n        exc_val: BaseException | None = None,\n        exc_tb: TracebackType | None = None,\n    ) -> None:\n        self.close()\n\n\nclass IPCServer(IPCBase):\n    BUFFER_SIZE: Final = 2**16\n\n    def __init__(self, name: str, timeout: float | None = None) -> None:\n        if sys.platform == \"win32\":\n            name = r\"\\\\.\\pipe\\{}-{}.pipe\".format(name, urlsafe_b64encode(os.urandom(6)).decode())\n        else:\n            name = f\"{name}.sock\"\n        super().__init__(name, timeout)\n        if sys.platform == \"win32\":\n            self.connection = _winapi.CreateNamedPipe(\n                self.name,\n                _winapi.PIPE_ACCESS_DUPLEX\n                | _winapi.FILE_FLAG_FIRST_PIPE_INSTANCE\n                | _winapi.FILE_FLAG_OVERLAPPED,\n                _winapi.PIPE_READMODE_MESSAGE\n                | _winapi.PIPE_TYPE_MESSAGE\n                | _winapi.PIPE_WAIT\n                | 0x8,  # PIPE_REJECT_REMOTE_CLIENTS\n                1,  # one instance\n                self.BUFFER_SIZE,\n                self.BUFFER_SIZE,\n                _winapi.NMPWAIT_WAIT_FOREVER,\n                0,  # Use default security descriptor\n            )\n            if self.connection == -1:  # INVALID_HANDLE_VALUE\n                err = _winapi.GetLastError()\n                raise IPCException(f\"Invalid handle to pipe: {err}\")\n        else:\n            self.sock_directory = tempfile.mkdtemp()\n            sockfile = os.path.join(self.sock_directory, self.name)\n            self.sock = socket.socket(socket.AF_UNIX)\n            self.sock.bind(sockfile)\n            self.sock.listen(1)\n            if timeout is not None:\n                self.sock.settimeout(timeout)\n\n    def __enter__(self) -> IPCServer:\n        if sys.platform == \"win32\":\n            # NOTE: It is theoretically possible that this will hang forever if the\n            # client never connects, though this can be \"solved\" by killing the server\n            try:\n                ov = _winapi.ConnectNamedPipe(self.connection, overlapped=True)\n            except OSError as e:\n                # Don't raise if the client already exists, or the client already connected\n                if e.winerror not in (_winapi.ERROR_PIPE_CONNECTED, _winapi.ERROR_NO_DATA):\n                    raise\n            else:\n                try:\n                    timeout = int(self.timeout * 1000) if self.timeout else _winapi.INFINITE\n                    res = _winapi.WaitForSingleObject(ov.event, timeout)\n                    assert res == _winapi.WAIT_OBJECT_0\n                except BaseException:\n                    ov.cancel()\n                    _winapi.CloseHandle(self.connection)\n                    raise\n                _, err = ov.GetOverlappedResult(True)\n                assert err == 0\n        else:\n            try:\n                self.connection, _ = self.sock.accept()\n            except TimeoutError as e:\n                raise IPCException(\"The socket timed out\") from e\n        return self\n\n    def __exit__(\n        self,\n        exc_ty: type[BaseException] | None = None,\n        exc_val: BaseException | None = None,\n        exc_tb: TracebackType | None = None,\n    ) -> None:\n        if sys.platform == \"win32\":\n            try:\n                # Wait for the client to finish reading the last write before disconnecting\n                if not FlushFileBuffers(self.connection):\n                    raise IPCException(\n                        \"Failed to flush NamedPipe buffer, maybe the client hung up?\"\n                    )\n            finally:\n                DisconnectNamedPipe(self.connection)\n        else:\n            self.close()\n\n    def cleanup(self) -> None:\n        if sys.platform == \"win32\":\n            self.close()\n        else:\n            shutil.rmtree(self.sock_directory)\n\n    @property\n    def connection_name(self) -> str:\n        if sys.platform == \"win32\":\n            return self.name\n        elif sys.platform == \"gnu0\":\n            # GNU/Hurd returns empty string from getsockname()\n            # for AF_UNIX sockets\n            return os.path.join(self.sock_directory, self.name)\n        else:\n            name = self.sock.getsockname()\n            assert isinstance(name, str)\n            return name\n\n\nclass BadStatus(Exception):\n    \"\"\"Exception raised when there is something wrong with the status file.\n\n    For example:\n    - No status file found\n    - Status file malformed\n    - Process whose pid is in the status file does not exist\n    \"\"\"\n\n\ndef read_status(status_file: str) -> dict[str, object]:\n    \"\"\"Read status file.\n\n    Raise BadStatus if the status file doesn't exist or contains\n    invalid JSON or the JSON is not a dict.\n    \"\"\"\n    if not os.path.isfile(status_file):\n        raise BadStatus(\"No status file found\")\n    with open(status_file) as f:\n        try:\n            data = json.load(f)\n        except Exception as e:\n            raise BadStatus(f\"Malformed status file: {str(e)}\") from e\n    if not isinstance(data, dict):\n        raise BadStatus(f\"Invalid status file (not a dict): {data}\")\n    return data\n\n\ndef ready_to_read(conns: list[IPCClient], timeout: float | None = None) -> list[int]:\n    \"\"\"Wait until some connections are readable.\n\n    Return index of each readable connection in the original list.\n    \"\"\"\n    if sys.platform == \"win32\":\n        # Windows doesn't support select() on named pipes. Instead, start an overlapped\n        # ReadFile on each pipe (which internally creates an event via CreateEventW),\n        # then WaitForMultipleObjects on those events for efficient OS-level waiting.\n        # Any data consumed by the probe reads is stored into each connection's buffer\n        # so the subsequent read_bytes() call will find it via frame_from_buffer().\n        WAIT_FAILED = 0xFFFFFFFF\n        pending: list[tuple[int, _winapi.Overlapped]] = []\n        events: list[int] = []\n        ready: list[int] = []\n\n        for i, conn in enumerate(conns):\n            try:\n                ov, err = _winapi.ReadFile(conn.connection, 1, overlapped=True)\n            except OSError:\n                # Broken/closed pipe. Mimic Linux behavior here, caller will get\n                # the exception when trying to read from this socket.\n                ready.append(i)\n                continue\n            if err == _winapi.ERROR_IO_PENDING:\n                events.append(ov.event)\n                pending.append((i, ov))\n            else:\n                # Data was immediately available (err == 0 or ERROR_MORE_DATA)\n                _, err = ov.GetOverlappedResult(True)\n                data = ov.getbuffer()\n                if data:\n                    conn.buffer.extend(data)\n                ready.append(i)\n\n        # Wait only if nothing is immediately ready and there are pending operations\n        if not ready and events:\n            timeout_ms = int(timeout * 1000) if timeout is not None else _winapi.INFINITE\n            res = _winapi.WaitForMultipleObjects(events, False, timeout_ms)\n            if res == WAIT_FAILED:\n                for _, ov in pending:\n                    ov.cancel()\n                raise IPCException(f\"Failed to wait for connections: {_winapi.GetLastError()}\")\n\n        # Check which pending operations completed, cancel the rest\n        for i, ov in pending:\n            if _winapi.WaitForSingleObject(ov.event, 0) == _winapi.WAIT_OBJECT_0:\n                _, err = ov.GetOverlappedResult(True)\n                data = ov.getbuffer()\n                if data:\n                    conns[i].buffer.extend(data)\n                ready.append(i)\n            else:\n                ov.cancel()\n\n        return ready\n\n    else:\n        connections = [conn.connection for conn in conns]\n        ready, _, _ = select(connections, [], [], timeout)\n        return [connections.index(r) for r in ready]\n\n\ndef send(connection: IPCBase, data: IPCMessage) -> None:\n    \"\"\"Send data to a connection encoded and framed.\n\n    The data must be a non-abstract IPCMessage. We assume that a single send call is a\n    single frame to be sent.\n    \"\"\"\n    buf = WriteBuffer()\n    data.write(buf)\n    connection.write_bytes(buf.getvalue())\n\n\ndef receive(connection: IPCBase) -> ReadBuffer:\n    \"\"\"Receive single encoded IPCMessage frame from a connection.\n\n    Raise OSError if the data received is not valid.\n    \"\"\"\n    bdata = connection.read_bytes()\n    if not bdata:\n        raise OSError(\"No data received\")\n    return ReadBuffer(bdata)\n\n\nclass IPCMessage:\n    @classmethod\n    @abstractmethod\n    def read(cls, buf: ReadBuffer) -> Self:\n        raise NotImplementedError\n\n    @abstractmethod\n    def write(self, buf: WriteBuffer) -> None:\n        raise NotImplementedError\n"
  },
  {
    "path": "mypy/join.py",
    "content": "\"\"\"Calculation of the least upper bound types (joins).\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import overload\n\nimport mypy.typeops\nfrom mypy.expandtype import expand_type\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.nodes import CONTRAVARIANT, COVARIANT, INVARIANT, VARIANCE_NOT_READY, TypeInfo\nfrom mypy.state import state\nfrom mypy.subtypes import (\n    SubtypeContext,\n    find_member,\n    is_equivalent,\n    is_proper_subtype,\n    is_protocol_implementation,\n    is_subtype,\n)\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    TypeVisitor,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    get_proper_type,\n    get_proper_types,\n    split_with_prefix_and_suffix,\n)\n\n\nclass InstanceJoiner:\n    def __init__(self) -> None:\n        self.seen_instances: list[tuple[Instance, Instance]] = []\n\n    def join_instances(self, t: Instance, s: Instance) -> ProperType:\n        if (t, s) in self.seen_instances or (s, t) in self.seen_instances:\n            return object_from_instance(t)\n\n        self.seen_instances.append((t, s))\n\n        # Calculate the join of two instance types\n        if t.type == s.type:\n            # Simplest case: join two types with the same base type (but\n            # potentially different arguments).\n\n            # Combine type arguments.\n            args: list[Type] = []\n            # N.B: We use zip instead of indexing because the lengths might have\n            # mismatches during daemon reprocessing.\n            if t.type.has_type_var_tuple_type:\n                # We handle joins of variadic instances by simply creating correct mapping\n                # for type arguments and compute the individual joins same as for regular\n                # instances. All the heavy lifting is done in the join of tuple types.\n                assert s.type.type_var_tuple_prefix is not None\n                assert s.type.type_var_tuple_suffix is not None\n                prefix = s.type.type_var_tuple_prefix\n                suffix = s.type.type_var_tuple_suffix\n                tvt = s.type.defn.type_vars[prefix]\n                assert isinstance(tvt, TypeVarTupleType)\n                fallback = tvt.tuple_fallback\n                s_prefix, s_middle, s_suffix = split_with_prefix_and_suffix(s.args, prefix, suffix)\n                t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(t.args, prefix, suffix)\n                s_args = s_prefix + (TupleType(list(s_middle), fallback),) + s_suffix\n                t_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix\n            else:\n                t_args = t.args\n                s_args = s.args\n            for ta, sa, type_var in zip(t_args, s_args, t.type.defn.type_vars):\n                ta_proper = get_proper_type(ta)\n                sa_proper = get_proper_type(sa)\n                new_type: Type | None = None\n                if isinstance(ta_proper, AnyType):\n                    new_type = AnyType(TypeOfAny.from_another_any, ta_proper)\n                elif isinstance(sa_proper, AnyType):\n                    new_type = AnyType(TypeOfAny.from_another_any, sa_proper)\n                elif isinstance(type_var, TypeVarType):\n                    if type_var.variance in (COVARIANT, VARIANCE_NOT_READY):\n                        new_type = join_types(ta, sa, self)\n                        if len(type_var.values) != 0 and new_type not in type_var.values:\n                            self.seen_instances.pop()\n                            return object_from_instance(t)\n                        if not is_subtype(new_type, type_var.upper_bound):\n                            self.seen_instances.pop()\n                            return object_from_instance(t)\n                    # TODO: contravariant case should use meet but pass seen instances as\n                    # an argument to keep track of recursive checks.\n                    elif type_var.variance in (INVARIANT, CONTRAVARIANT):\n                        if isinstance(ta_proper, UninhabitedType) and ta_proper.ambiguous:\n                            new_type = sa\n                        elif isinstance(sa_proper, UninhabitedType) and sa_proper.ambiguous:\n                            new_type = ta\n                        elif not is_equivalent(ta, sa):\n                            self.seen_instances.pop()\n                            return object_from_instance(t)\n                        else:\n                            # If the types are different but equivalent, then an Any is involved\n                            # so using a join in the contravariant case is also OK.\n                            new_type = join_types(ta, sa, self)\n                elif isinstance(type_var, TypeVarTupleType):\n                    new_type = get_proper_type(join_types(ta, sa, self))\n                    # Put the joined arguments back into instance in the normal form:\n                    #   a) Tuple[X, Y, Z] -> [X, Y, Z]\n                    #   b) tuple[X, ...] -> [*tuple[X, ...]]\n                    if isinstance(new_type, Instance):\n                        assert new_type.type.fullname == \"builtins.tuple\"\n                        new_type = UnpackType(new_type)\n                    else:\n                        assert isinstance(new_type, TupleType)\n                        args.extend(new_type.items)\n                        continue\n                else:\n                    # ParamSpec type variables behave the same, independent of variance\n                    if not is_equivalent(ta, sa):\n                        return get_proper_type(type_var.upper_bound)\n                    new_type = join_types(ta, sa, self)\n                assert new_type is not None\n                args.append(new_type)\n            result: ProperType = Instance(t.type, args)\n        elif t.type.bases and is_proper_subtype(\n            t, s, subtype_context=SubtypeContext(ignore_type_params=True)\n        ):\n            result = self.join_instances_via_supertype(t, s)\n        else:\n            # Now t is not a subtype of s, and t != s. Now s could be a subtype\n            # of t; alternatively, we need to find a common supertype. This works\n            # in of the both cases.\n            result = self.join_instances_via_supertype(s, t)\n\n        self.seen_instances.pop()\n        return result\n\n    def join_instances_via_supertype(self, t: Instance, s: Instance) -> ProperType:\n        # Give preference to joins via duck typing relationship, so that\n        # join(int, float) == float, for example.\n        for p in t.type._promote:\n            if is_subtype(p, s):\n                return join_types(p, s, self)\n        for p in s.type._promote:\n            if is_subtype(p, t):\n                return join_types(t, p, self)\n\n        # Compute the \"best\" supertype of t when joined with s.\n        # The definition of \"best\" may evolve; for now it is the one with\n        # the longest MRO.  Ties are broken by using the earlier base.\n\n        # Go over both sets of bases in case there's an explicit Protocol base. This is important\n        # to ensure commutativity of join (although in cases where both classes have relevant\n        # Protocol bases this maybe might still not be commutative)\n        base_types: dict[TypeInfo, None] = {}  # dict to deduplicate but preserve order\n        for base in t.type.bases:\n            base_types[base.type] = None\n        for base in s.type.bases:\n            if base.type.is_protocol and is_subtype(t, base):\n                base_types[base.type] = None\n\n        best: ProperType | None = None\n        for base_type in base_types:\n            mapped = map_instance_to_supertype(t, base_type)\n            res = self.join_instances(mapped, s)\n            if best is None or is_better(res, best):\n                best = res\n        assert best is not None\n        for promote in t.type._promote:\n            if isinstance(promote, Instance):\n                res = self.join_instances(promote, s)\n                if is_better(res, best):\n                    best = res\n        return best\n\n\ndef trivial_join(s: Type, t: Type) -> Type:\n    \"\"\"Return one of types (expanded) if it is a supertype of other, otherwise top type.\"\"\"\n    if is_subtype(s, t):\n        return t\n    elif is_subtype(t, s):\n        return s\n    else:\n        return object_or_any_from_type(get_proper_type(t))\n\n\n@overload\ndef join_types(\n    s: ProperType, t: ProperType, instance_joiner: InstanceJoiner | None = None\n) -> ProperType: ...\n\n\n@overload\ndef join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type: ...\n\n\ndef join_types(s: Type, t: Type, instance_joiner: InstanceJoiner | None = None) -> Type:\n    \"\"\"Return the least upper bound of s and t.\n\n    For example, the join of 'int' and 'object' is 'object'.\n    \"\"\"\n    if mypy.typeops.is_recursive_pair(s, t):\n        # This case can trigger an infinite recursion, general support for this will be\n        # tricky so we use a trivial join (like for protocols).\n        return trivial_join(s, t)\n    s = get_proper_type(s)\n    t = get_proper_type(t)\n\n    if (s.can_be_true, s.can_be_false) != (t.can_be_true, t.can_be_false):\n        # if types are restricted in different ways, use the more general versions\n        s = mypy.typeops.true_or_false(s)\n        t = mypy.typeops.true_or_false(t)\n\n    if isinstance(s, UnionType) and not isinstance(t, UnionType):\n        s, t = t, s\n\n    if isinstance(s, AnyType):\n        return s\n\n    if isinstance(s, ErasedType):\n        return t\n\n    if isinstance(s, NoneType) and not isinstance(t, NoneType):\n        s, t = t, s\n\n    if isinstance(s, UninhabitedType) and not isinstance(t, UninhabitedType):\n        s, t = t, s\n\n    # Meets/joins require callable type normalization.\n    s, t = normalize_callables(s, t)\n\n    # Use a visitor to handle non-trivial cases.\n    return t.accept(TypeJoinVisitor(s, instance_joiner))\n\n\nclass TypeJoinVisitor(TypeVisitor[ProperType]):\n    \"\"\"Implementation of the least upper bound algorithm.\n\n    Attributes:\n      s: The other (left) type operand.\n    \"\"\"\n\n    def __init__(self, s: ProperType, instance_joiner: InstanceJoiner | None = None) -> None:\n        self.s = s\n        self.instance_joiner = instance_joiner\n\n    def visit_unbound_type(self, t: UnboundType) -> ProperType:\n        return AnyType(TypeOfAny.special_form)\n\n    def visit_union_type(self, t: UnionType) -> ProperType:\n        if is_proper_subtype(self.s, t):\n            return t\n        else:\n            return mypy.typeops.make_simplified_union([self.s, t])\n\n    def visit_any(self, t: AnyType) -> ProperType:\n        return t\n\n    def visit_none_type(self, t: NoneType) -> ProperType:\n        if state.strict_optional:\n            if isinstance(self.s, (NoneType, UninhabitedType)):\n                return t\n            elif isinstance(self.s, (UnboundType, AnyType)):\n                return AnyType(TypeOfAny.special_form)\n            else:\n                return mypy.typeops.make_simplified_union([self.s, t])\n        else:\n            return self.s\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:\n        return self.s\n\n    def visit_deleted_type(self, t: DeletedType) -> ProperType:\n        return self.s\n\n    def visit_erased_type(self, t: ErasedType) -> ProperType:\n        return self.s\n\n    def visit_type_var(self, t: TypeVarType) -> ProperType:\n        if isinstance(self.s, TypeVarType):\n            if self.s.id == t.id:\n                if self.s.upper_bound == t.upper_bound:\n                    return self.s\n                return self.s.copy_modified(\n                    upper_bound=join_types(self.s.upper_bound, t.upper_bound)\n                )\n            # Fix non-commutative joins\n            return get_proper_type(join_types(self.s.upper_bound, t.upper_bound))\n        else:\n            return self.default(self.s)\n\n    def visit_param_spec(self, t: ParamSpecType) -> ProperType:\n        if self.s == t:\n            return t\n        return self.default(self.s)\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType:\n        if self.s == t:\n            return t\n        if isinstance(self.s, Instance) and is_subtype(t.upper_bound, self.s):\n            # TODO: should we do this more generally and for all TypeVarLikeTypes?\n            return self.s\n        return self.default(self.s)\n\n    def visit_unpack_type(self, t: UnpackType) -> UnpackType:\n        raise NotImplementedError\n\n    def visit_parameters(self, t: Parameters) -> ProperType:\n        if isinstance(self.s, Parameters):\n            if not is_similar_params(t, self.s):\n                # TODO: it would be prudent to return [*object, **object] instead of Any.\n                return self.default(self.s)\n            from mypy.meet import meet_types\n\n            return t.copy_modified(\n                arg_types=[\n                    meet_types(s_a, t_a) for s_a, t_a in zip(self.s.arg_types, t.arg_types)\n                ],\n                arg_names=combine_arg_names(self.s, t),\n            )\n        else:\n            return self.default(self.s)\n\n    def visit_instance(self, t: Instance) -> ProperType:\n        if isinstance(self.s, Instance):\n            if self.instance_joiner is None:\n                self.instance_joiner = InstanceJoiner()\n            nominal = self.instance_joiner.join_instances(t, self.s)\n            structural: Instance | None = None\n            if t.type.is_protocol and is_protocol_implementation(self.s, t):\n                structural = t\n            elif self.s.type.is_protocol and is_protocol_implementation(t, self.s):\n                structural = self.s\n            # Structural join is preferred in the case where we have found both\n            # structural and nominal and they have same MRO length (see two comments\n            # in join_instances_via_supertype). Otherwise, just return the nominal join.\n            if not structural or is_better(nominal, structural):\n                return nominal\n            return structural\n        elif isinstance(self.s, FunctionLike):\n            if t.type.is_protocol:\n                call = unpack_callback_protocol(t)\n                if call:\n                    return join_types(call, self.s)\n            return join_types(t, self.s.fallback)\n        elif isinstance(self.s, TypeType):\n            return join_types(t, self.s)\n        elif isinstance(self.s, TypedDictType):\n            return join_types(t, self.s)\n        elif isinstance(self.s, TupleType):\n            return join_types(t, self.s)\n        elif isinstance(self.s, LiteralType):\n            return join_types(t, self.s)\n        elif isinstance(self.s, TypeVarTupleType) and is_subtype(self.s.upper_bound, t):\n            return t\n        else:\n            return self.default(self.s)\n\n    def visit_callable_type(self, t: CallableType) -> ProperType:\n        if isinstance(self.s, CallableType):\n            if is_similar_callables(t, self.s):\n                if is_equivalent(t, self.s):\n                    return combine_similar_callables(t, self.s)\n                result = join_similar_callables(t, self.s)\n                if any(\n                    isinstance(tp, (NoneType, UninhabitedType))\n                    for tp in get_proper_types(result.arg_types)\n                ):\n                    # We don't want to return unusable Callable, attempt fallback instead.\n                    return join_types(t.fallback, self.s)\n                # We set the from_type_type flag to suppress error when a collection of\n                # concrete class objects gets inferred as their common abstract superclass.\n                if not (\n                    (t.is_type_obj() and t.type_object().is_abstract)\n                    or (self.s.is_type_obj() and self.s.type_object().is_abstract)\n                ):\n                    result.from_type_type = True\n                return result\n            else:\n                s2, t2 = self.s, t\n                if t2.is_var_arg:\n                    s2, t2 = t2, s2\n                if is_subtype(s2, t2):\n                    return t2.copy_modified()\n                elif is_subtype(t2, s2):\n                    return s2.copy_modified()\n                return join_types(t.fallback, self.s)\n        elif isinstance(self.s, Overloaded):\n            # Switch the order of arguments to that we'll get to visit_overloaded.\n            return join_types(t, self.s)\n        elif isinstance(self.s, Instance) and self.s.type.is_protocol:\n            call = unpack_callback_protocol(self.s)\n            if call:\n                return join_types(t, call)\n        return join_types(t.fallback, self.s)\n\n    def visit_overloaded(self, t: Overloaded) -> ProperType:\n        # This is more complex than most other cases. Here are some\n        # examples that illustrate how this works.\n        #\n        # First let's define a concise notation:\n        #  - Cn are callable types (for n in 1, 2, ...)\n        #  - Ov(C1, C2, ...) is an overloaded type with items C1, C2, ...\n        #  - Callable[[T, ...], S] is written as [T, ...] -> S.\n        #\n        # We want some basic properties to hold (assume Cn are all\n        # unrelated via Any-similarity):\n        #\n        #   join(Ov(C1, C2), C1) == C1\n        #   join(Ov(C1, C2), Ov(C1, C2)) == Ov(C1, C2)\n        #   join(Ov(C1, C2), Ov(C1, C3)) == C1\n        #   join(Ov(C2, C2), C3) == join of fallback types\n        #\n        # The presence of Any types makes things more interesting. The join is the\n        # most general type we can get with respect to Any:\n        #\n        #   join(Ov([int] -> int, [str] -> str), [Any] -> str) == Any -> str\n        #\n        # We could use a simplification step that removes redundancies, but that's not\n        # implemented right now. Consider this example, where we get a redundancy:\n        #\n        #   join(Ov([int, Any] -> Any, [str, Any] -> Any), [Any, int] -> Any) ==\n        #       Ov([Any, int] -> Any, [Any, int] -> Any)\n        #\n        # TODO: Consider more cases of callable subtyping.\n        result: list[CallableType] = []\n        s = self.s\n        if isinstance(s, FunctionLike):\n            # The interesting case where both types are function types.\n            for t_item in t.items:\n                for s_item in s.items:\n                    if is_similar_callables(t_item, s_item):\n                        if is_equivalent(t_item, s_item):\n                            result.append(combine_similar_callables(t_item, s_item))\n                        elif is_subtype(t_item, s_item):\n                            result.append(s_item)\n            if result:\n                # TODO: Simplify redundancies from the result.\n                if len(result) == 1:\n                    return result[0]\n                else:\n                    return Overloaded(result)\n            return join_types(t.fallback, s.fallback)\n        elif isinstance(s, Instance) and s.type.is_protocol:\n            call = unpack_callback_protocol(s)\n            if call:\n                return join_types(t, call)\n        return join_types(t.fallback, s)\n\n    def join_tuples(self, s: TupleType, t: TupleType) -> list[Type] | None:\n        \"\"\"Join two tuple types while handling variadic entries.\n\n        This is surprisingly tricky, and we don't handle some tricky corner cases.\n        Most of the trickiness comes from the variadic tuple items like *tuple[X, ...]\n        since they can have arbitrary partial overlaps (while *Ts can't be split).\n        \"\"\"\n        s_unpack_index = find_unpack_in_list(s.items)\n        t_unpack_index = find_unpack_in_list(t.items)\n        if s_unpack_index is None and t_unpack_index is None:\n            if s.length() == t.length():\n                items: list[Type] = []\n                for i in range(t.length()):\n                    items.append(join_types(t.items[i], s.items[i]))\n                return items\n            return None\n        if s_unpack_index is not None and t_unpack_index is not None:\n            # The most complex case: both tuples have an unpack item.\n            s_unpack = s.items[s_unpack_index]\n            assert isinstance(s_unpack, UnpackType)\n            s_unpacked = get_proper_type(s_unpack.type)\n            t_unpack = t.items[t_unpack_index]\n            assert isinstance(t_unpack, UnpackType)\n            t_unpacked = get_proper_type(t_unpack.type)\n            if s.length() == t.length() and s_unpack_index == t_unpack_index:\n                # We can handle a case where arity is perfectly aligned, e.g.\n                # join(Tuple[X1, *tuple[Y1, ...], Z1], Tuple[X2, *tuple[Y2, ...], Z2]).\n                # We can essentially perform the join elementwise.\n                prefix_len = t_unpack_index\n                suffix_len = t.length() - t_unpack_index - 1\n                items = []\n                for si, ti in zip(s.items[:prefix_len], t.items[:prefix_len]):\n                    items.append(join_types(si, ti))\n                joined = join_types(s_unpacked, t_unpacked)\n                if isinstance(joined, TypeVarTupleType):\n                    items.append(UnpackType(joined))\n                elif isinstance(joined, Instance) and joined.type.fullname == \"builtins.tuple\":\n                    items.append(UnpackType(joined))\n                else:\n                    if isinstance(t_unpacked, Instance):\n                        assert t_unpacked.type.fullname == \"builtins.tuple\"\n                        tuple_instance = t_unpacked\n                    else:\n                        assert isinstance(t_unpacked, TypeVarTupleType)\n                        tuple_instance = t_unpacked.tuple_fallback\n                    items.append(\n                        UnpackType(\n                            tuple_instance.copy_modified(\n                                args=[object_from_instance(tuple_instance)]\n                            )\n                        )\n                    )\n                if suffix_len:\n                    for si, ti in zip(s.items[-suffix_len:], t.items[-suffix_len:]):\n                        items.append(join_types(si, ti))\n                return items\n            if s.length() == 1 or t.length() == 1:\n                # Another case we can handle is when one of tuple is purely variadic\n                # (i.e. a non-normalized form of tuple[X, ...]), in this case the join\n                # will be again purely variadic.\n                if not (isinstance(s_unpacked, Instance) and isinstance(t_unpacked, Instance)):\n                    return None\n                assert s_unpacked.type.fullname == \"builtins.tuple\"\n                assert t_unpacked.type.fullname == \"builtins.tuple\"\n                mid_joined = join_types(s_unpacked.args[0], t_unpacked.args[0])\n                t_other = [a for i, a in enumerate(t.items) if i != t_unpack_index]\n                s_other = [a for i, a in enumerate(s.items) if i != s_unpack_index]\n                other_joined = join_type_list(s_other + t_other)\n                mid_joined = join_types(mid_joined, other_joined)\n                return [UnpackType(s_unpacked.copy_modified(args=[mid_joined]))]\n            # TODO: are there other case we can handle (e.g. both prefix/suffix are shorter)?\n            return None\n        if s_unpack_index is not None:\n            variadic = s\n            unpack_index = s_unpack_index\n            fixed = t\n        else:\n            assert t_unpack_index is not None\n            variadic = t\n            unpack_index = t_unpack_index\n            fixed = s\n        # Case where one tuple has variadic item and the other one doesn't. The join will\n        # be variadic, since fixed tuple is a subtype of variadic, but not vice versa.\n        unpack = variadic.items[unpack_index]\n        assert isinstance(unpack, UnpackType)\n        unpacked = get_proper_type(unpack.type)\n        if not isinstance(unpacked, Instance):\n            return None\n        if fixed.length() < variadic.length() - 1:\n            # There are no non-trivial types that are supertype of both.\n            return None\n        prefix_len = unpack_index\n        suffix_len = variadic.length() - prefix_len - 1\n        prefix, middle, suffix = split_with_prefix_and_suffix(\n            tuple(fixed.items), prefix_len, suffix_len\n        )\n        items = []\n        for fi, vi in zip(prefix, variadic.items[:prefix_len]):\n            items.append(join_types(fi, vi))\n        mid_joined = join_type_list(list(middle))\n        mid_joined = join_types(mid_joined, unpacked.args[0])\n        items.append(UnpackType(unpacked.copy_modified(args=[mid_joined])))\n        if suffix_len:\n            for fi, vi in zip(suffix, variadic.items[-suffix_len:]):\n                items.append(join_types(fi, vi))\n        return items\n\n    def visit_tuple_type(self, t: TupleType) -> ProperType:\n        # When given two fixed-length tuples:\n        # * If they have the same length, join their subtypes item-wise:\n        #   Tuple[int, bool] + Tuple[bool, bool] becomes Tuple[int, bool]\n        # * If lengths do not match, return a variadic tuple:\n        #   Tuple[bool, int] + Tuple[bool] becomes Tuple[int, ...]\n        #\n        # Otherwise, `t` is a fixed-length tuple but `self.s` is NOT:\n        # * Joining with a variadic tuple returns variadic tuple:\n        #   Tuple[int, bool] + Tuple[bool, ...] becomes Tuple[int, ...]\n        # * Joining with any Sequence also returns a Sequence:\n        #   Tuple[int, bool] + List[bool] becomes Sequence[int]\n        if isinstance(self.s, TupleType):\n            if self.instance_joiner is None:\n                self.instance_joiner = InstanceJoiner()\n            fallback = self.instance_joiner.join_instances(\n                mypy.typeops.tuple_fallback(self.s), mypy.typeops.tuple_fallback(t)\n            )\n            assert isinstance(fallback, Instance)\n            items = self.join_tuples(self.s, t)\n            if items is not None:\n                if len(items) == 1 and isinstance(item := items[0], UnpackType):\n                    if isinstance(unpacked := get_proper_type(item.type), Instance):\n                        # Avoid double-wrapping tuple[*tuple[X, ...]]\n                        return unpacked\n                return TupleType(items, fallback)\n            else:\n                # TODO: should this be a default fallback behaviour like for meet?\n                if is_proper_subtype(self.s, t):\n                    return t\n                if is_proper_subtype(t, self.s):\n                    return self.s\n                return fallback\n        else:\n            return join_types(self.s, mypy.typeops.tuple_fallback(t))\n\n    def visit_typeddict_type(self, t: TypedDictType) -> ProperType:\n        if isinstance(self.s, TypedDictType):\n            items = {\n                item_name: s_item_type\n                for (item_name, s_item_type, t_item_type) in self.s.zip(t)\n                if (\n                    is_equivalent(s_item_type, t_item_type)\n                    and (item_name in t.required_keys) == (item_name in self.s.required_keys)\n                )\n            }\n            fallback = self.s.create_anonymous_fallback()\n            all_keys = set(items.keys())\n            # We need to filter by items.keys() since some required keys present in both t and\n            # self.s might be missing from the join if the types are incompatible.\n            required_keys = all_keys & t.required_keys & self.s.required_keys\n            # If one type has a key as readonly, we mark it as readonly for both:\n            readonly_keys = (t.readonly_keys | t.readonly_keys) & all_keys\n            return TypedDictType(items, required_keys, readonly_keys, fallback)\n        elif isinstance(self.s, Instance):\n            return join_types(self.s, t.fallback)\n        else:\n            return self.default(self.s)\n\n    def visit_literal_type(self, t: LiteralType) -> ProperType:\n        if isinstance(self.s, LiteralType):\n            if t == self.s:\n                return t\n            if self.s.fallback.type.is_enum and t.fallback.type.is_enum:\n                return mypy.typeops.make_simplified_union([self.s, t])\n            return join_types(self.s.fallback, t.fallback)\n        elif isinstance(self.s, Instance) and self.s.last_known_value == t:\n            return t\n        else:\n            return join_types(self.s, t.fallback)\n\n    def visit_partial_type(self, t: PartialType) -> ProperType:\n        # We only have partial information so we can't decide the join result. We should\n        # never get here.\n        assert False, \"Internal error\"\n\n    def visit_type_type(self, t: TypeType) -> ProperType:\n        if isinstance(self.s, TypeType):\n            return TypeType.make_normalized(\n                join_types(t.item, self.s.item),\n                line=t.line,\n                is_type_form=self.s.is_type_form or t.is_type_form,\n            )\n        elif isinstance(self.s, Instance) and self.s.type.fullname == \"builtins.type\":\n            return self.s\n        else:\n            return self.default(self.s)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> ProperType:\n        assert False, f\"This should be never called, got {t}\"\n\n    def default(self, typ: Type) -> ProperType:\n        typ = get_proper_type(typ)\n        if isinstance(typ, Instance):\n            return object_from_instance(typ)\n        elif isinstance(typ, TypeType):\n            return self.default(typ.item)\n        elif isinstance(typ, UnboundType):\n            return AnyType(TypeOfAny.special_form)\n        elif isinstance(typ, TupleType):\n            return self.default(mypy.typeops.tuple_fallback(typ))\n        elif isinstance(typ, TypedDictType):\n            return self.default(typ.fallback)\n        elif isinstance(typ, FunctionLike):\n            return self.default(typ.fallback)\n        elif isinstance(typ, TypeVarType):\n            return self.default(typ.upper_bound)\n        elif isinstance(typ, ParamSpecType):\n            return self.default(typ.upper_bound)\n        else:\n            return AnyType(TypeOfAny.special_form)\n\n\ndef is_better(t: Type, s: Type) -> bool:\n    # Given two possible results from join_instances_via_supertype(),\n    # indicate whether t is the better one.\n    t = get_proper_type(t)\n    s = get_proper_type(s)\n\n    if isinstance(t, Instance):\n        if not isinstance(s, Instance):\n            return True\n        if t.type.is_protocol != s.type.is_protocol:\n            if t.type.fullname != \"builtins.object\" and s.type.fullname != \"builtins.object\":\n                # mro of protocol is not really relevant\n                return not t.type.is_protocol\n        # Use len(mro) as a proxy for the better choice.\n        if len(t.type.mro) > len(s.type.mro):\n            return True\n    return False\n\n\ndef normalize_callables(s: ProperType, t: ProperType) -> tuple[ProperType, ProperType]:\n    if isinstance(s, (CallableType, Overloaded)):\n        s = s.with_unpacked_kwargs()\n    if isinstance(t, (CallableType, Overloaded)):\n        t = t.with_unpacked_kwargs()\n    return s, t\n\n\ndef is_similar_callables(t: CallableType, s: CallableType) -> bool:\n    \"\"\"Return True if t and s have identical numbers of\n    arguments, default arguments and varargs.\n    \"\"\"\n    return (\n        len(t.arg_types) == len(s.arg_types)\n        and t.min_args == s.min_args\n        and t.is_var_arg == s.is_var_arg\n    )\n\n\ndef is_similar_params(t: Parameters, s: Parameters) -> bool:\n    # This matches the logic in is_similar_callables() above.\n    return (\n        len(t.arg_types) == len(s.arg_types)\n        and t.min_args == s.min_args\n        and (t.var_arg() is not None) == (s.var_arg() is not None)\n    )\n\n\ndef update_callable_ids(c: CallableType, ids: list[TypeVarId]) -> CallableType:\n    tv_map = {}\n    tvs = []\n    for tv, new_id in zip(c.variables, ids):\n        new_tv = tv.copy_modified(id=new_id)\n        tvs.append(new_tv)\n        tv_map[tv.id] = new_tv\n    return expand_type(c, tv_map).copy_modified(variables=tvs)\n\n\ndef match_generic_callables(t: CallableType, s: CallableType) -> tuple[CallableType, CallableType]:\n    # The case where we combine/join/meet similar callables, situation where both are generic\n    # requires special care. A more principled solution may involve unify_generic_callable(),\n    # but it would have two problems:\n    #   * This adds risk of infinite recursion: e.g. join -> unification -> solver -> join\n    #   * Using unification is an incorrect thing for meets, as it \"widens\" the types\n    # Finally, this effectively falls back to an old behaviour before namespaces were added to\n    # type variables, and it worked relatively well.\n    max_len = max(len(t.variables), len(s.variables))\n    min_len = min(len(t.variables), len(s.variables))\n    if min_len == 0:\n        return t, s\n    new_ids = [TypeVarId.new(meta_level=0) for _ in range(max_len)]\n    # Note: this relies on variables being in order they appear in function definition.\n    return update_callable_ids(t, new_ids), update_callable_ids(s, new_ids)\n\n\ndef join_similar_callables(t: CallableType, s: CallableType) -> CallableType:\n    t, s = match_generic_callables(t, s)\n    arg_types: list[Type] = []\n    for i in range(len(t.arg_types)):\n        arg_types.append(safe_meet(t.arg_types[i], s.arg_types[i]))\n    # TODO in combine_similar_callables also applies here (names and kinds; user metaclasses)\n    # The fallback type can be either 'function', 'type', or some user-provided metaclass.\n    # The result should always use 'function' as a fallback if either operands are using it.\n    if t.fallback.type.fullname == \"builtins.function\":\n        fallback = t.fallback\n    else:\n        fallback = s.fallback\n    return t.copy_modified(\n        arg_types=arg_types,\n        arg_names=combine_arg_names(t, s),\n        ret_type=join_types(t.ret_type, s.ret_type),\n        fallback=fallback,\n        name=None,\n    )\n\n\ndef safe_join(t: Type, s: Type) -> Type:\n    # This is a temporary solution to prevent crashes in combine_similar_callables() etc.,\n    # until relevant TODOs on handling arg_kinds will be addressed there.\n    if not isinstance(t, UnpackType) and not isinstance(s, UnpackType):\n        return join_types(t, s)\n    if isinstance(t, UnpackType) and isinstance(s, UnpackType):\n        return UnpackType(join_types(t.type, s.type))\n    return object_or_any_from_type(get_proper_type(t))\n\n\ndef safe_meet(t: Type, s: Type) -> Type:\n    # Similar to above but for meet_types().\n    from mypy.meet import meet_types\n\n    if not isinstance(t, UnpackType) and not isinstance(s, UnpackType):\n        return meet_types(t, s)\n    if isinstance(t, UnpackType) and isinstance(s, UnpackType):\n        unpacked = get_proper_type(t.type)\n        if isinstance(unpacked, TypeVarTupleType):\n            fallback_type = unpacked.tuple_fallback.type\n        elif isinstance(unpacked, TupleType):\n            fallback_type = unpacked.partial_fallback.type\n        else:\n            assert isinstance(unpacked, Instance) and unpacked.type.fullname == \"builtins.tuple\"\n            fallback_type = unpacked.type\n        res = meet_types(t.type, s.type)\n        if isinstance(res, UninhabitedType):\n            res = Instance(fallback_type, [res])\n        return UnpackType(res)\n    return UninhabitedType()\n\n\ndef combine_similar_callables(t: CallableType, s: CallableType) -> CallableType:\n    t, s = match_generic_callables(t, s)\n    arg_types: list[Type] = []\n    for i in range(len(t.arg_types)):\n        arg_types.append(safe_join(t.arg_types[i], s.arg_types[i]))\n    # TODO kinds and argument names\n    # TODO what should happen if one fallback is 'type' and the other is a user-provided metaclass?\n    # The fallback type can be either 'function', 'type', or some user-provided metaclass.\n    # The result should always use 'function' as a fallback if either operands are using it.\n    if t.fallback.type.fullname == \"builtins.function\":\n        fallback = t.fallback\n    else:\n        fallback = s.fallback\n    return t.copy_modified(\n        arg_types=arg_types,\n        arg_names=combine_arg_names(t, s),\n        ret_type=join_types(t.ret_type, s.ret_type),\n        fallback=fallback,\n        name=None,\n    )\n\n\ndef combine_arg_names(\n    t: CallableType | Parameters, s: CallableType | Parameters\n) -> list[str | None]:\n    \"\"\"Produces a list of argument names compatible with both callables.\n\n    For example, suppose 't' and 's' have the following signatures:\n\n    - t: (a: int, b: str, X: str) -> None\n    - s: (a: int, b: str, Y: str) -> None\n\n    This function would return [\"a\", \"b\", None]. This information\n    is then used above to compute the join of t and s, which results\n    in a signature of (a: int, b: str, str) -> None.\n\n    Note that the third argument's name is omitted and 't' and 's'\n    are both valid subtypes of this inferred signature.\n\n    Precondition: is_similar_types(t, s) is true.\n    \"\"\"\n    num_args = len(t.arg_types)\n    new_names = []\n    for i in range(num_args):\n        t_name = t.arg_names[i]\n        s_name = s.arg_names[i]\n        if t_name == s_name or t.arg_kinds[i].is_named() or s.arg_kinds[i].is_named():\n            new_names.append(t_name)\n        else:\n            new_names.append(None)\n    return new_names\n\n\ndef object_from_instance(instance: Instance) -> Instance:\n    \"\"\"Construct the type 'builtins.object' from an instance type.\"\"\"\n    # Use the fact that 'object' is always the last class in the mro.\n    res = Instance(instance.type.mro[-1], [])\n    return res\n\n\ndef object_or_any_from_type(typ: ProperType) -> ProperType:\n    # Similar to object_from_instance() but tries hard for all types.\n    # TODO: find a better way to get object, or make this more reliable.\n    if isinstance(typ, Instance):\n        return object_from_instance(typ)\n    elif isinstance(typ, (CallableType, TypedDictType, LiteralType)):\n        return object_from_instance(typ.fallback)\n    elif isinstance(typ, TupleType):\n        return object_from_instance(typ.partial_fallback)\n    elif isinstance(typ, TypeType):\n        return object_or_any_from_type(typ.item)\n    elif isinstance(typ, TypeVarLikeType) and isinstance(typ.upper_bound, ProperType):\n        return object_or_any_from_type(typ.upper_bound)\n    elif isinstance(typ, UnionType):\n        for item in typ.items:\n            if isinstance(item, ProperType):\n                candidate = object_or_any_from_type(item)\n                if isinstance(candidate, Instance):\n                    return candidate\n    elif isinstance(typ, UnpackType):\n        object_or_any_from_type(get_proper_type(typ.type))\n    return AnyType(TypeOfAny.implementation_artifact)\n\n\ndef join_type_list(types: Sequence[Type]) -> Type:\n    if not types:\n        # This is a little arbitrary but reasonable. Any empty tuple should be compatible\n        # with all variable length tuples, and this makes it possible.\n        return UninhabitedType()\n    joined = types[0]\n    for t in types[1:]:\n        joined = join_types(joined, t)\n    return joined\n\n\ndef unpack_callback_protocol(t: Instance) -> ProperType | None:\n    assert t.type.is_protocol\n    if t.type.protocol_members == [\"__call__\"]:\n        return get_proper_type(find_member(\"__call__\", t, t, is_operator=True))\n    return None\n"
  },
  {
    "path": "mypy/literals.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Iterable\nfrom typing import Any, Final, TypeAlias as _TypeAlias\n\nfrom mypy.nodes import (\n    LITERAL_NO,\n    LITERAL_TYPE,\n    LITERAL_YES,\n    AssertTypeExpr,\n    AssignmentExpr,\n    AwaitExpr,\n    BytesExpr,\n    CallExpr,\n    CastExpr,\n    ComparisonExpr,\n    ComplexExpr,\n    ConditionalExpr,\n    DictExpr,\n    DictionaryComprehension,\n    EllipsisExpr,\n    EnumCallExpr,\n    Expression,\n    FloatExpr,\n    GeneratorExpr,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    MemberExpr,\n    NamedTupleExpr,\n    NameExpr,\n    NewTypeExpr,\n    OpExpr,\n    ParamSpecExpr,\n    PromoteExpr,\n    RevealExpr,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    StrExpr,\n    SuperExpr,\n    TemplateStrExpr,\n    TempNode,\n    TupleExpr,\n    TypeAliasExpr,\n    TypeApplication,\n    TypedDictExpr,\n    TypeFormExpr,\n    TypeVarExpr,\n    TypeVarTupleExpr,\n    UnaryExpr,\n    Var,\n    YieldExpr,\n    YieldFromExpr,\n)\nfrom mypy.visitor import ExpressionVisitor\n\n# [Note Literals and literal_hash]\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Mypy uses the term \"literal\" to refer to any expression built out of\n# the following:\n#\n# * Plain literal expressions, like `1` (integer, float, string, etc.)\n#\n# * Compound literal expressions, like `(lit1, lit2)` (list, dict,\n#   set, or tuple)\n#\n# * Operator expressions, like `lit1 + lit2`\n#\n# * Variable references, like `x`\n#\n# * Member references, like `lit.m`\n#\n# * Index expressions, like `lit[0]`\n#\n# A typical \"literal\" looks like `x[(i,j+1)].m`.\n#\n# An expression that is a literal has a `literal_hash`, with the\n# following properties.\n#\n# * `literal_hash` is a Key: a tuple containing basic data types and\n#   possibly other Keys. So it can be used as a key in a dictionary\n#   that will be compared by value (as opposed to the Node itself,\n#   which is compared by identity).\n#\n# * Two expressions have equal `literal_hash`es if and only if they\n#   are syntactically equal expressions. (NB: Actually, we also\n#   identify as equal expressions like `3` and `3.0`; is this a good\n#   idea?)\n#\n# * The elements of `literal_hash` that are tuples are exactly the\n#   subexpressions of the original expression (e.g. the base and index\n#   of an index expression, or the operands of an operator expression).\n\n\nKey: _TypeAlias = tuple[Any, ...]\n\n\ndef literal_hash(e: Expression) -> Key | None:\n    \"\"\"Generate a hashable, (mostly) opaque key for expressions supported by the binder.\n\n    These allow using expressions as dictionary keys based on structural/value\n    matching (instead of based on expression identity).\n\n    Return None if the expression type is not supported (it cannot be narrowed).\n\n    See the comment above for more information.\n\n    NOTE: This is not directly related to literal types.\n    \"\"\"\n    return e.accept(_hasher)\n\n\ndef literal(e: Expression) -> int:\n    \"\"\"Return the literal kind for an expression.\"\"\"\n\n    if isinstance(e, ComparisonExpr):\n        return min(literal(o) for o in e.operands)\n\n    elif isinstance(e, OpExpr):\n        return min(literal(e.left), literal(e.right))\n\n    elif isinstance(e, (MemberExpr, UnaryExpr, StarExpr)):\n        return literal(e.expr)\n\n    elif isinstance(e, AssignmentExpr):\n        return literal(e.target)\n\n    elif isinstance(e, IndexExpr):\n        if literal(e.index) == LITERAL_YES:\n            return literal(e.base)\n        else:\n            return LITERAL_NO\n\n    elif isinstance(e, NameExpr):\n        if isinstance(e.node, Var) and e.node.is_final and e.node.final_value is not None:\n            return LITERAL_YES\n        return LITERAL_TYPE\n\n    if isinstance(e, (IntExpr, FloatExpr, ComplexExpr, StrExpr, BytesExpr)):\n        return LITERAL_YES\n\n    if literal_hash(e):\n        return LITERAL_YES\n\n    return LITERAL_NO\n\n\ndef subkeys(key: Key) -> Iterable[Key]:\n    return [elt for elt in key if isinstance(elt, tuple)]\n\n\ndef extract_var_from_literal_hash(key: Key) -> Var | None:\n    \"\"\"If key refers to a Var node, return it.\n\n    Return None otherwise.\n    \"\"\"\n    if len(key) == 2 and key[0] == \"Var\" and isinstance(key[1], Var):\n        return key[1]\n    return None\n\n\nclass _Hasher(ExpressionVisitor[Key | None]):\n    def visit_int_expr(self, e: IntExpr) -> Key:\n        return (\"Literal\", e.value)\n\n    def visit_str_expr(self, e: StrExpr) -> Key:\n        return (\"Literal\", e.value)\n\n    def visit_bytes_expr(self, e: BytesExpr) -> Key:\n        return (\"Literal\", e.value)\n\n    def visit_float_expr(self, e: FloatExpr) -> Key:\n        return (\"Literal\", e.value)\n\n    def visit_complex_expr(self, e: ComplexExpr) -> Key:\n        return (\"Literal\", e.value)\n\n    def visit_star_expr(self, e: StarExpr) -> Key:\n        return (\"Star\", literal_hash(e.expr))\n\n    def visit_name_expr(self, e: NameExpr) -> Key:\n        if isinstance(e.node, Var) and e.node.is_final and e.node.final_value is not None:\n            return (\"Literal\", e.node.final_value)\n        # N.B: We use the node itself as the key, and not the name,\n        # because using the name causes issues when there is shadowing\n        # (for example, in list comprehensions).\n        return (\"Var\", e.node)\n\n    def visit_member_expr(self, e: MemberExpr) -> Key:\n        return (\"Member\", literal_hash(e.expr), e.name)\n\n    def visit_op_expr(self, e: OpExpr) -> Key:\n        return (\"Binary\", e.op, literal_hash(e.left), literal_hash(e.right))\n\n    def visit_comparison_expr(self, e: ComparisonExpr) -> Key:\n        rest: tuple[str | Key | None, ...] = tuple(e.operators)\n        rest += tuple(literal_hash(o) for o in e.operands)\n        return (\"Comparison\",) + rest\n\n    def visit_unary_expr(self, e: UnaryExpr) -> Key:\n        return (\"Unary\", e.op, literal_hash(e.expr))\n\n    def seq_expr(self, e: ListExpr | TupleExpr | SetExpr, name: str) -> Key | None:\n        if all(literal(x) == LITERAL_YES for x in e.items):\n            rest: tuple[Key | None, ...] = tuple(literal_hash(x) for x in e.items)\n            return (name,) + rest\n        return None\n\n    def visit_list_expr(self, e: ListExpr) -> Key | None:\n        return self.seq_expr(e, \"List\")\n\n    def visit_dict_expr(self, e: DictExpr) -> Key | None:\n        if all(a and literal(a) == literal(b) == LITERAL_YES for a, b in e.items):\n            rest: tuple[Key | None, ...] = tuple(\n                (literal_hash(a) if a else None, literal_hash(b)) for a, b in e.items\n            )\n            return (\"Dict\",) + rest\n        return None\n\n    def visit_tuple_expr(self, e: TupleExpr) -> Key | None:\n        return self.seq_expr(e, \"Tuple\")\n\n    def visit_set_expr(self, e: SetExpr) -> Key | None:\n        return self.seq_expr(e, \"Set\")\n\n    def visit_index_expr(self, e: IndexExpr) -> Key | None:\n        if literal(e.index) == LITERAL_YES:\n            return (\"Index\", literal_hash(e.base), literal_hash(e.index))\n        return None\n\n    def visit_assignment_expr(self, e: AssignmentExpr) -> Key | None:\n        return literal_hash(e.target)\n\n    def visit_call_expr(self, e: CallExpr) -> None:\n        return None\n\n    def visit_slice_expr(self, e: SliceExpr) -> None:\n        return None\n\n    def visit_cast_expr(self, e: CastExpr) -> None:\n        return None\n\n    def visit_type_form_expr(self, e: TypeFormExpr) -> None:\n        return None\n\n    def visit_assert_type_expr(self, e: AssertTypeExpr) -> None:\n        return None\n\n    def visit_conditional_expr(self, e: ConditionalExpr) -> None:\n        return None\n\n    def visit_ellipsis(self, e: EllipsisExpr) -> None:\n        return None\n\n    def visit_yield_from_expr(self, e: YieldFromExpr) -> None:\n        return None\n\n    def visit_yield_expr(self, e: YieldExpr) -> None:\n        return None\n\n    def visit_reveal_expr(self, e: RevealExpr) -> None:\n        return None\n\n    def visit_super_expr(self, e: SuperExpr) -> None:\n        return None\n\n    def visit_type_application(self, e: TypeApplication) -> None:\n        return None\n\n    def visit_lambda_expr(self, e: LambdaExpr) -> None:\n        return None\n\n    def visit_list_comprehension(self, e: ListComprehension) -> None:\n        return None\n\n    def visit_set_comprehension(self, e: SetComprehension) -> None:\n        return None\n\n    def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> None:\n        return None\n\n    def visit_generator_expr(self, e: GeneratorExpr) -> None:\n        return None\n\n    def visit_type_var_expr(self, e: TypeVarExpr) -> None:\n        return None\n\n    def visit_paramspec_expr(self, e: ParamSpecExpr) -> None:\n        return None\n\n    def visit_type_var_tuple_expr(self, e: TypeVarTupleExpr) -> None:\n        return None\n\n    def visit_type_alias_expr(self, e: TypeAliasExpr) -> None:\n        return None\n\n    def visit_namedtuple_expr(self, e: NamedTupleExpr) -> None:\n        return None\n\n    def visit_enum_call_expr(self, e: EnumCallExpr) -> None:\n        return None\n\n    def visit_typeddict_expr(self, e: TypedDictExpr) -> None:\n        return None\n\n    def visit_newtype_expr(self, e: NewTypeExpr) -> None:\n        return None\n\n    def visit__promote_expr(self, e: PromoteExpr) -> None:\n        return None\n\n    def visit_await_expr(self, e: AwaitExpr) -> None:\n        return None\n\n    def visit_template_str_expr(self, e: TemplateStrExpr) -> None:\n        return None\n\n    def visit_temp_node(self, e: TempNode) -> None:\n        return None\n\n\n_hasher: Final = _Hasher()\n"
  },
  {
    "path": "mypy/lookup.py",
    "content": "\"\"\"\nThis is a module for various lookup functions:\nfunctions that will find a semantic node by its name.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import MypyFile, SymbolTableNode, TypeInfo\n\n# TODO: gradually move existing lookup functions to this module.\n\n\ndef lookup_fully_qualified(\n    name: str, modules: dict[str, MypyFile], *, raise_on_missing: bool = False\n) -> SymbolTableNode | None:\n    \"\"\"Find a symbol using it fully qualified name.\n\n    The algorithm has two steps: first we try splitting the name on '.' to find\n    the module, then iteratively look for each next chunk after a '.' (e.g. for\n    nested classes).\n\n    This function should *not* be used to find a module. Those should be looked\n    in the modules dictionary.\n    \"\"\"\n    # 1. Exclude the names of ad hoc instance intersections from step 2.\n    i = name.find(\"<subclass \")\n    head = name if i == -1 else name[:i]\n    rest = []\n    # 2. Find a module tree in modules dictionary.\n    while True:\n        if \".\" not in head:\n            if raise_on_missing:\n                assert \".\" in head, f\"Cannot find module for {name}\"\n            return None\n        # TODO: this logic is not correct as it confuses a submodule and a local symbol.\n        # A potential solution may be to use format like pkg.mod:Cls.method for fullname,\n        # but this is a relatively big change.\n        head, tail = head.rsplit(\".\", maxsplit=1)\n        rest.append(tail)\n        mod = modules.get(head)\n        if mod is not None:\n            break\n    names = mod.names\n    # 3. Find the symbol in the module tree.\n    if not rest:\n        # Looks like a module, don't use this to avoid confusions.\n        if raise_on_missing:\n            assert rest, f\"Cannot find {name}, got a module symbol\"\n        return None\n    if i != -1:\n        rest[0] += name[i:]\n    while True:\n        key = rest.pop()\n        if key not in names:\n            if raise_on_missing:\n                assert key in names, f\"Cannot find component {key!r} for {name!r}\"\n            return None\n        stnode = names[key]\n        if not rest:\n            return stnode\n        node = stnode.node\n        # In fine-grained mode, could be a cross-reference to a deleted module\n        # or a Var made up for a missing module.\n        if not isinstance(node, TypeInfo):\n            if raise_on_missing:\n                assert node, f\"Cannot find {name}\"\n            return None\n        names = node.names\n"
  },
  {
    "path": "mypy/main.py",
    "content": "\"\"\"Mypy type checker command line tool.\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport os\nimport platform\nimport subprocess\nimport sys\nimport time\nfrom collections import defaultdict\nfrom collections.abc import Sequence\nfrom gettext import gettext\nfrom io import TextIOWrapper\nfrom typing import IO, TYPE_CHECKING, Any, Final, NoReturn, TextIO\n\nif platform.python_implementation() == \"PyPy\":\n    sys.stderr.write(\n        \"ERROR: Running mypy on PyPy is not supported yet.\\n\"\n        \"To type-check a PyPy library please use an equivalent CPython version,\\n\"\n        \"see https://github.com/mypyc/librt/issues/16 for possible workarounds.\\n\"\n    )\n    sys.exit(2)\n\nfrom mypy import build, defaults, state, util\nfrom mypy.config_parser import parse_config_file, parse_version, validate_package_allow_list\nfrom mypy.defaults import RECURSION_LIMIT\nfrom mypy.error_formatter import OUTPUT_CHOICES\nfrom mypy.errors import CompileError\nfrom mypy.find_sources import InvalidSourceList, create_source_list\nfrom mypy.fscache import FileSystemCache\nfrom mypy.modulefinder import (\n    BuildSource,\n    FindModuleCache,\n    ModuleNotFoundReason,\n    SearchPaths,\n    get_search_dirs,\n    mypy_path,\n)\nfrom mypy.options import INCOMPLETE_FEATURES, BuildType, Options\nfrom mypy.split_namespace import SplitNamespace\nfrom mypy.version import __version__\n\nif TYPE_CHECKING:\n    from _typeshed import SupportsWrite\n\norig_stat: Final = os.stat\nMEM_PROFILE: Final = False  # If True, dump memory profile\n\n\ndef stat_proxy(path: str) -> os.stat_result:\n    try:\n        st = orig_stat(path)\n    except OSError as err:\n        print(f\"stat({path!r}) -> {err}\")\n        raise\n    else:\n        print(\n            \"stat(%r) -> (st_mode=%o, st_mtime=%d, st_size=%d)\"\n            % (path, st.st_mode, st.st_mtime, st.st_size)\n        )\n        return st\n\n\ndef main(\n    *,\n    args: list[str] | None = None,\n    stdout: TextIO = sys.stdout,\n    stderr: TextIO = sys.stderr,\n    clean_exit: bool = False,\n) -> None:\n    \"\"\"Main entry point to the type checker.\n\n    Args:\n        args: Custom command-line arguments.  If not given, sys.argv[1:] will\n            be used.\n        clean_exit: Don't hard kill the process on exit. This allows catching\n            SystemExit.\n    \"\"\"\n    util.check_python_version(\"mypy\")\n    t0 = time.time()\n    # To log stat() calls: os.stat = stat_proxy\n    sys.setrecursionlimit(RECURSION_LIMIT)\n    if args is None:\n        args = sys.argv[1:]\n\n    # Write an escape sequence instead of raising an exception on encoding errors.\n    if isinstance(stdout, TextIOWrapper) and stdout.errors == \"strict\":\n        stdout.reconfigure(errors=\"backslashreplace\")\n\n    fscache = FileSystemCache()\n    sources, options = process_options(args, stdout=stdout, stderr=stderr, fscache=fscache)\n    if clean_exit:\n        options.fast_exit = False\n\n    formatter = util.FancyFormatter(\n        stdout, stderr, options.hide_error_codes, hide_success=bool(options.output)\n    )\n\n    if options.num_workers:\n        # Supporting both parsers would be really tricky, so just support the new one.\n        options.native_parser = True\n\n    if options.allow_redefinition_new and not options.local_partial_types:\n        fail(\n            \"error: --local-partial-types must be enabled if using --allow-redefinition-new\",\n            stderr,\n            options,\n        )\n\n    if options.allow_redefinition_new and options.allow_redefinition_old:\n        fail(\n            \"--allow-redefinition-old and --allow-redefinition-new should not be used together\",\n            stderr,\n            options,\n        )\n\n    if options.install_types and (stdout is not sys.stdout or stderr is not sys.stderr):\n        # Since --install-types performs user input, we want regular stdout and stderr.\n        fail(\"error: --install-types not supported in this mode of running mypy\", stderr, options)\n\n    if options.non_interactive and not options.install_types:\n        fail(\"error: --non-interactive is only supported with --install-types\", stderr, options)\n\n    if options.install_types and not options.incremental:\n        fail(\n            \"error: --install-types not supported with incremental mode disabled\", stderr, options\n        )\n\n    if options.install_types and options.python_executable is None:\n        fail(\n            \"error: --install-types not supported without python executable or site packages\",\n            stderr,\n            options,\n        )\n\n    if options.install_types and not sources:\n        install_types(formatter, options, non_interactive=options.non_interactive)\n        return\n\n    res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr)\n\n    if options.non_interactive:\n        missing_pkgs = read_types_packages_to_install(options.cache_dir, after_run=True)\n        if missing_pkgs:\n            # Install missing type packages and rerun build.\n            install_types(formatter, options, after_run=True, non_interactive=True)\n            fscache.flush()\n            print()\n            res, messages, blockers = run_build(sources, options, fscache, t0, stdout, stderr)\n        show_messages(messages, stderr, formatter, options)\n\n    if MEM_PROFILE:\n        from mypy.memprofile import print_memory_profile\n\n        print_memory_profile()\n\n    code = 0\n    n_errors, n_notes, n_files = util.count_stats(messages)\n    if messages and n_notes < len(messages):\n        code = 2 if blockers else 1\n    if options.error_summary:\n        if n_errors:\n            summary = formatter.format_error(\n                n_errors, n_files, len(sources), blockers=blockers, use_color=options.color_output\n            )\n            stdout.write(summary + \"\\n\")\n        # Only notes should also output success\n        elif not messages or n_notes == len(messages):\n            stdout.write(formatter.format_success(len(sources), options.color_output) + \"\\n\")\n        stdout.flush()\n\n    if options.install_types and not options.non_interactive:\n        result = install_types(formatter, options, after_run=True, non_interactive=False)\n        if result:\n            print()\n            print(\"note: Run mypy again for up-to-date results with installed types\")\n            code = 2\n\n    if options.fast_exit:\n        # Exit without freeing objects -- it's faster.\n        #\n        # NOTE: We don't flush all open files on exit (or run other destructors)!\n        util.hard_exit(code)\n    elif code:\n        sys.exit(code)\n\n    # HACK: keep res alive so that mypyc won't free it before the hard_exit\n    list([res])  # noqa: C410\n\n\ndef run_build(\n    sources: list[BuildSource],\n    options: Options,\n    fscache: FileSystemCache,\n    t0: float,\n    stdout: TextIO,\n    stderr: TextIO,\n) -> tuple[build.BuildResult | None, list[str], bool]:\n    formatter = util.FancyFormatter(\n        stdout, stderr, options.hide_error_codes, hide_success=bool(options.output)\n    )\n\n    messages = []\n    messages_by_file = defaultdict(list)\n\n    def flush_errors(filename: str | None, new_messages: list[str], serious: bool) -> None:\n        if options.pretty:\n            new_messages = formatter.fit_in_terminal(new_messages)\n        messages.extend(new_messages)\n        if new_messages:\n            messages_by_file[filename].extend(new_messages)\n        if options.non_interactive:\n            # Collect messages and possibly show them later.\n            return\n        f = stderr if serious else stdout\n        show_messages(new_messages, f, formatter, options)\n\n    serious = False\n    blockers = False\n    res = None\n    try:\n        # Keep a dummy reference (res) for memory profiling afterwards, as otherwise\n        # the result could be freed.\n        res = build.build(sources, options, None, flush_errors, fscache, stdout, stderr)\n    except CompileError as e:\n        blockers = True\n        if not e.use_stdout:\n            serious = True\n    maybe_write_junit_xml(time.time() - t0, serious, messages, messages_by_file, options)\n    return res, messages, blockers\n\n\ndef show_messages(\n    messages: list[str], f: TextIO, formatter: util.FancyFormatter, options: Options\n) -> None:\n    for msg in messages:\n        if options.color_output:\n            msg = formatter.colorize(msg)\n        f.write(msg + \"\\n\")\n    f.flush()\n\n\n# Make the help output a little less jarring.\nclass AugmentedHelpFormatter(argparse.RawDescriptionHelpFormatter):\n    def __init__(self, prog: str, **kwargs: Any) -> None:\n        super().__init__(prog=prog, max_help_position=28, **kwargs)\n\n    def _fill_text(self, text: str, width: int, indent: str) -> str:\n        if \"\\n\" in text:\n            # Assume we want to manually format the text\n            return super()._fill_text(text, width, indent)\n        # Format the text like argparse, but overflow rather than\n        # breaking long words (like URLs)\n        text = self._whitespace_matcher.sub(\" \", text).strip()\n        import textwrap\n\n        return textwrap.fill(\n            text,\n            width,\n            initial_indent=indent,\n            subsequent_indent=indent,\n            break_on_hyphens=False,\n            break_long_words=False,\n        )\n\n\n# Define pairs of flag prefixes with inverse meaning.\nflag_prefix_pairs: Final = [(\"allow\", \"disallow\"), (\"show\", \"hide\")]\nflag_prefix_map: Final[dict[str, str]] = {}\nfor a, b in flag_prefix_pairs:\n    flag_prefix_map[a] = b\n    flag_prefix_map[b] = a\n\n\ndef invert_flag_name(flag: str) -> str:\n    split = flag[2:].split(\"-\", 1)\n    if len(split) == 2:\n        prefix, rest = split\n        if prefix in flag_prefix_map:\n            return f\"--{flag_prefix_map[prefix]}-{rest}\"\n        elif prefix == \"no\":\n            return f\"--{rest}\"\n\n    return f\"--no-{flag[2:]}\"\n\n\nclass PythonExecutableInferenceError(Exception):\n    \"\"\"Represents a failure to infer the version or executable while searching.\"\"\"\n\n\ndef python_executable_prefix(v: str) -> list[str]:\n    if sys.platform == \"win32\":\n        # on Windows, all Python executables are named `python`. To handle this, there\n        # is the `py` launcher, which can be passed a version e.g. `py -3.8`, and it will\n        # execute an installed Python 3.8 interpreter. See also:\n        # https://docs.python.org/3/using/windows.html#python-launcher-for-windows\n        return [\"py\", f\"-{v}\"]\n    else:\n        return [f\"python{v}\"]\n\n\ndef _python_executable_from_version(python_version: tuple[int, int]) -> str:\n    if sys.version_info[:2] == python_version:\n        return sys.executable\n    str_ver = \".\".join(map(str, python_version))\n    try:\n        sys_exe = (\n            subprocess.check_output(\n                python_executable_prefix(str_ver) + [\"-c\", \"import sys; print(sys.executable)\"],\n                stderr=subprocess.STDOUT,\n            )\n            .decode()\n            .strip()\n        )\n        return sys_exe\n    except (subprocess.CalledProcessError, FileNotFoundError) as e:\n        raise PythonExecutableInferenceError(\n            \"failed to find a Python executable matching version {},\"\n            \" perhaps try --python-executable, or --no-site-packages?\".format(python_version)\n        ) from e\n\n\ndef infer_python_executable(options: Options, special_opts: argparse.Namespace) -> None:\n    \"\"\"Infer the Python executable from the given version.\n\n    This function mutates options based on special_opts to infer the correct Python executable\n    to use.\n    \"\"\"\n    # TODO: (ethanhs) Look at folding these checks and the site packages subprocess calls into\n    # one subprocess call for speed.\n\n    # Use the command line specified executable, or fall back to one set in the\n    # config file. If an executable is not specified, infer it from the version\n    # (unless no_executable is set)\n    python_executable = special_opts.python_executable or options.python_executable\n\n    if python_executable is None:\n        if not special_opts.no_executable and not options.no_site_packages:\n            python_executable = _python_executable_from_version(options.python_version)\n    options.python_executable = python_executable\n\n\nHEADER: Final = \"\"\"%(prog)s [-h] [-v] [-V] [more options; see below]\n            [-m MODULE] [-p PACKAGE] [-c PROGRAM_TEXT] [files ...]\"\"\"\n\n\nDESCRIPTION: Final = \"\"\"\nMypy is a program that will type check your Python code.\n\nPass in any files or folders you want to type check. Mypy will\nrecursively traverse any provided folders to find .py files:\n\n    $ mypy my_program.py my_src_folder\n\nFor more information on getting started, see:\n\n- https://mypy.readthedocs.io/en/stable/getting_started.html\n\nFor more details on both running mypy and using the flags below, see:\n\n- https://mypy.readthedocs.io/en/stable/running_mypy.html\n- https://mypy.readthedocs.io/en/stable/command_line.html\n\nYou can also use a config file to configure mypy instead of using\ncommand line flags. For more details, see:\n\n- https://mypy.readthedocs.io/en/stable/config_file.html\n\"\"\"\n\nFOOTER: Final = \"\"\"Environment variables:\n  Define MYPYPATH for additional module search path entries.\n  Define MYPY_CACHE_DIR to override configuration cache_dir path.\"\"\"\n\n\nclass CapturableArgumentParser(argparse.ArgumentParser):\n    \"\"\"Override ArgumentParser methods that use sys.stdout/sys.stderr directly.\n\n    This is needed because hijacking sys.std* is not thread-safe,\n    yet output must be captured to properly support mypy.api.run.\n    \"\"\"\n\n    def __init__(self, *args: Any, **kwargs: Any) -> None:\n        self.stdout = kwargs.pop(\"stdout\", sys.stdout)\n        self.stderr = kwargs.pop(\"stderr\", sys.stderr)\n        super().__init__(*args, **kwargs)\n\n    # =====================\n    # Help-printing methods\n    # =====================\n    def print_usage(self, file: SupportsWrite[str] | None = None) -> None:\n        if file is None:\n            file = self.stdout\n        self._print_message(self.format_usage(), file)\n\n    def print_help(self, file: SupportsWrite[str] | None = None) -> None:\n        if file is None:\n            file = self.stdout\n        self._print_message(self.format_help(), file)\n\n    def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None:\n        if message:\n            if file is None:\n                file = self.stderr\n            file.write(message)\n\n    # ===============\n    # Exiting methods\n    # ===============\n    def exit(self, status: int = 0, message: str | None = None) -> NoReturn:\n        if message:\n            self._print_message(message, self.stderr)\n        sys.exit(status)\n\n    def error(self, message: str) -> NoReturn:\n        \"\"\"error(message: string)\n\n        Prints a usage message incorporating the message to stderr and\n        exits.\n\n        If you override this in a subclass, it should not return -- it\n        should either exit or raise an exception.\n        \"\"\"\n        self.print_usage(self.stderr)\n        args = {\"prog\": self.prog, \"message\": message}\n        self.exit(2, gettext(\"%(prog)s: error: %(message)s\\n\") % args)\n\n\nclass CapturableVersionAction(argparse.Action):\n    \"\"\"Supplement CapturableArgumentParser to handle --version.\n\n    This is nearly identical to argparse._VersionAction except,\n    like CapturableArgumentParser, it allows output to be captured.\n\n    Another notable difference is that version is mandatory.\n    This allows removing a line in __call__ that falls back to parser.version\n    (which does not appear to exist).\n    \"\"\"\n\n    def __init__(\n        self,\n        option_strings: Sequence[str],\n        version: str,\n        dest: str = argparse.SUPPRESS,\n        default: str = argparse.SUPPRESS,\n        help: str = \"show program's version number and exit\",\n        stdout: IO[str] | None = None,\n    ) -> None:\n        super().__init__(\n            option_strings=option_strings, dest=dest, default=default, nargs=0, help=help\n        )\n        self.version = version\n        self.stdout = stdout or sys.stdout\n\n    def __call__(\n        self,\n        parser: argparse.ArgumentParser,\n        namespace: argparse.Namespace,\n        values: str | Sequence[Any] | None,\n        option_string: str | None = None,\n    ) -> NoReturn:\n        formatter = parser._get_formatter()\n        formatter.add_text(self.version)\n        parser._print_message(formatter.format_help(), self.stdout)\n        parser.exit()\n\n\ndef define_options(\n    program: str = \"mypy\",\n    header: str = HEADER,\n    stdout: TextIO = sys.stdout,\n    stderr: TextIO = sys.stderr,\n    server_options: bool = False,\n) -> tuple[CapturableArgumentParser, list[str], list[tuple[str, bool]]]:\n    \"\"\"Define the options in the parser (by calling a bunch of methods that express/build our desired command-line flags).\n    Returns a tuple of:\n      a parser object, that can parse command line arguments to mypy (expected consumer: main's process_options),\n      a list of what flags are strict (expected consumer: docs' html_builder's _add_strict_list),\n      strict_flag_assignments (expected consumer: main's process_options).\"\"\"\n    parser = CapturableArgumentParser(\n        prog=program,\n        usage=header,\n        description=DESCRIPTION,\n        epilog=FOOTER,\n        fromfile_prefix_chars=\"@\",\n        formatter_class=AugmentedHelpFormatter,\n        add_help=False,\n        stdout=stdout,\n        stderr=stderr,\n    )\n\n    strict_flag_names: list[str] = []\n    strict_flag_assignments: list[tuple[str, bool]] = []\n\n    def add_invertible_flag(\n        flag: str,\n        *,\n        inverse: str | None = None,\n        default: bool,\n        dest: str | None = None,\n        help: str,\n        strict_flag: bool = False,\n        group: argparse._ActionsContainer | None = None,\n    ) -> None:\n        if inverse is None:\n            inverse = invert_flag_name(flag)\n        if group is None:\n            group = parser\n\n        if help is not argparse.SUPPRESS:\n            help += f\" (inverse: {inverse})\"\n\n        arg = group.add_argument(\n            flag, action=\"store_false\" if default else \"store_true\", dest=dest, help=help\n        )\n        dest = arg.dest\n        group.add_argument(\n            inverse,\n            action=\"store_true\" if default else \"store_false\",\n            dest=dest,\n            help=argparse.SUPPRESS,\n        )\n        if strict_flag:\n            assert dest is not None\n            strict_flag_names.append(flag)\n            strict_flag_assignments.append((dest, not default))\n\n    # Unless otherwise specified, arguments will be parsed directly onto an\n    # Options object.  Options that require further processing should have\n    # their `dest` prefixed with `special-opts:`, which will cause them to be\n    # parsed into the separate special_opts namespace object.\n\n    # Our style guide for formatting the output of running `mypy --help`:\n    # Flags:\n    # 1.  The flag help text should start with a capital letter but never end with a period.\n    # 2.  Keep the flag help text brief -- ideally just a single sentence.\n    # 3.  All flags must be a part of a group, unless the flag is deprecated or suppressed.\n    # 4.  Avoid adding new flags to the \"miscellaneous\" groups -- instead add them to an\n    #     existing group or, if applicable, create a new group. Feel free to move existing\n    #     flags to a new group: just be sure to also update the documentation to match.\n    #\n    # Groups:\n    # 1.  The group title and description should start with a capital letter.\n    # 2.  The first sentence of a group description should be written in the bare infinitive.\n    #     Tip: try substituting the group title and description into the following sentence:\n    #     > {group_title}: these flags will {group_description}\n    #     Feel free to add subsequent sentences that add additional details.\n    # 3.  If you cannot think of a meaningful description for a new group, omit it entirely.\n    #     (E.g. see the \"miscellaneous\" sections).\n    # 4.  The text of the group description should end with a period, optionally followed\n    #     by a documentation reference (URL).\n    # 5.  If you want to include a documentation reference, place it at the end of the\n    #     description. Feel free to open with a brief reference (\"See also:\", \"For more\n    #     information:\", etc.), followed by a space, then the entire URL including\n    #     \"https://\" scheme identifier and fragment (\"#some-target-heading\"), if any.\n    #     Do not end with a period (or any other characters not part of the URL).\n    #     URLs longer than the available terminal width will overflow without being\n    #     broken apart. This facilitates both URL detection, and manual copy-pasting.\n\n    general_group = parser.add_argument_group(title=\"Optional arguments\")\n    general_group.add_argument(\n        \"-h\", \"--help\", action=\"help\", help=\"Show this help message and exit\"\n    )\n    general_group.add_argument(\n        \"-v\", \"--verbose\", action=\"count\", dest=\"verbosity\", help=\"More verbose messages\"\n    )\n\n    compilation_status = \"no\" if __file__.endswith(\".py\") else \"yes\"\n    general_group.add_argument(\n        \"-V\",\n        \"--version\",\n        action=CapturableVersionAction,\n        version=\"%(prog)s \" + __version__ + f\" (compiled: {compilation_status})\",\n        help=\"Show program's version number and exit\",\n        stdout=stdout,\n    )\n\n    general_group.add_argument(\n        \"-O\",\n        \"--output\",\n        metavar=\"FORMAT\",\n        help=\"Set a custom output format\",\n        choices=OUTPUT_CHOICES,\n    )\n\n    config_group = parser.add_argument_group(\n        title=\"Config file\",\n        description=\"Use a config file instead of command line arguments. \"\n        \"This is useful if you are using many flags or want \"\n        \"to set different options per each module.\",\n    )\n    config_group.add_argument(\n        \"--config-file\",\n        help=(\n            f\"Configuration file, must have a [mypy] section \"\n            f\"(defaults to {', '.join(defaults.CONFIG_NAMES + defaults.SHARED_CONFIG_NAMES)})\"\n        ),\n    )\n    add_invertible_flag(\n        \"--warn-unused-configs\",\n        default=False,\n        strict_flag=True,\n        help=\"Warn about unused '[mypy-<pattern>]' or '[[tool.mypy.overrides]]' config sections\",\n        group=config_group,\n    )\n\n    imports_group = parser.add_argument_group(\n        title=\"Import discovery\", description=\"Configure how imports are discovered and followed.\"\n    )\n    add_invertible_flag(\n        \"--no-namespace-packages\",\n        dest=\"namespace_packages\",\n        default=True,\n        help=\"Disable support for namespace packages (PEP 420, __init__.py-less)\",\n        group=imports_group,\n    )\n    imports_group.add_argument(\n        \"--ignore-missing-imports\",\n        action=\"store_true\",\n        help=\"Silently ignore imports of missing modules\",\n    )\n    imports_group.add_argument(\n        \"--follow-untyped-imports\",\n        action=\"store_true\",\n        help=\"Typecheck modules without stubs or py.typed marker\",\n    )\n    imports_group.add_argument(\n        \"--follow-imports\",\n        choices=[\"normal\", \"silent\", \"skip\", \"error\"],\n        default=\"normal\",\n        help=\"How to treat imports (default normal)\",\n    )\n    imports_group.add_argument(\n        \"--python-executable\",\n        action=\"store\",\n        metavar=\"EXECUTABLE\",\n        help=\"Python executable used for finding PEP 561 compliant installed packages and stubs\",\n        dest=\"special-opts:python_executable\",\n    )\n    imports_group.add_argument(\n        \"--no-site-packages\",\n        action=\"store_true\",\n        dest=\"special-opts:no_executable\",\n        help=\"Do not search for installed PEP 561 compliant packages\",\n    )\n    imports_group.add_argument(\n        \"--no-silence-site-packages\",\n        action=\"store_true\",\n        help=\"Do not silence errors in PEP 561 compliant installed packages\",\n    )\n\n    platform_group = parser.add_argument_group(\n        title=\"Platform configuration\",\n        description=\"Type check code assuming it will be run under certain \"\n        \"runtime conditions. By default, mypy assumes your code \"\n        \"will be run using the same operating system and Python \"\n        \"version you are using to run mypy itself.\",\n    )\n    platform_group.add_argument(\n        \"--python-version\",\n        type=parse_version,\n        metavar=\"x.y\",\n        help=\"Type check code assuming it will be running on Python x.y\",\n        dest=\"special-opts:python_version\",\n    )\n    platform_group.add_argument(\n        \"--platform\",\n        action=\"store\",\n        metavar=\"PLATFORM\",\n        help=\"Type check special-cased code for the given OS platform (defaults to sys.platform)\",\n    )\n    platform_group.add_argument(\n        \"--always-true\",\n        metavar=\"NAME\",\n        action=\"append\",\n        default=[],\n        help=\"Additional variable to be considered True (may be repeated)\",\n    )\n    platform_group.add_argument(\n        \"--always-false\",\n        metavar=\"NAME\",\n        action=\"append\",\n        default=[],\n        help=\"Additional variable to be considered False (may be repeated)\",\n    )\n\n    disallow_any_group = parser.add_argument_group(\n        title=\"Disallow dynamic typing\",\n        description=\"Disallow the use of the dynamic 'Any' type under certain conditions.\",\n    )\n    disallow_any_group.add_argument(\n        \"--disallow-any-expr\",\n        default=False,\n        action=\"store_true\",\n        help=\"Disallow all expressions that have type Any\",\n    )\n    disallow_any_group.add_argument(\n        \"--disallow-any-decorated\",\n        default=False,\n        action=\"store_true\",\n        help=\"Disallow functions that have Any in their signature after decorator transformation\",\n    )\n    disallow_any_group.add_argument(\n        \"--disallow-any-explicit\",\n        default=False,\n        action=\"store_true\",\n        help=\"Disallow explicit Any in type positions\",\n    )\n    add_invertible_flag(\n        \"--disallow-any-generics\",\n        default=False,\n        strict_flag=True,\n        help=\"Disallow usage of generic types that do not specify explicit type parameters\",\n        group=disallow_any_group,\n    )\n    add_invertible_flag(\n        \"--disallow-any-unimported\",\n        default=False,\n        help=\"Disallow Any types resulting from unfollowed imports\",\n        group=disallow_any_group,\n    )\n    add_invertible_flag(\n        \"--disallow-subclassing-any\",\n        default=False,\n        strict_flag=True,\n        help=\"Disallow subclassing values of type 'Any' when defining classes\",\n        group=disallow_any_group,\n    )\n\n    untyped_group = parser.add_argument_group(\n        title=\"Untyped definitions and calls\",\n        description=\"Configure how untyped definitions and calls are handled. \"\n        \"Note: by default, mypy ignores any untyped function definitions \"\n        \"and assumes any calls to such functions have a return \"\n        \"type of 'Any'.\",\n    )\n    add_invertible_flag(\n        \"--disallow-untyped-calls\",\n        default=False,\n        strict_flag=True,\n        help=\"Disallow calling functions without type annotations\"\n        \" from functions with type annotations\",\n        group=untyped_group,\n    )\n    untyped_group.add_argument(\n        \"--untyped-calls-exclude\",\n        metavar=\"MODULE\",\n        action=\"append\",\n        default=[],\n        help=\"Disable --disallow-untyped-calls for functions/methods coming\"\n        \" from specific package, module, or class\",\n    )\n    add_invertible_flag(\n        \"--disallow-untyped-defs\",\n        default=False,\n        strict_flag=True,\n        help=\"Disallow defining functions without type annotations\"\n        \" or with incomplete type annotations\",\n        group=untyped_group,\n    )\n    add_invertible_flag(\n        \"--disallow-incomplete-defs\",\n        default=False,\n        strict_flag=True,\n        help=\"Disallow defining functions with incomplete type annotations \"\n        \"(while still allowing entirely unannotated definitions)\",\n        group=untyped_group,\n    )\n    add_invertible_flag(\n        \"--check-untyped-defs\",\n        default=False,\n        strict_flag=True,\n        help=\"Type check the interior of functions without type annotations\",\n        group=untyped_group,\n    )\n    add_invertible_flag(\n        \"--disallow-untyped-decorators\",\n        default=False,\n        strict_flag=True,\n        help=\"Disallow decorating typed functions with untyped decorators\",\n        group=untyped_group,\n    )\n\n    none_group = parser.add_argument_group(\n        title=\"None and Optional handling\",\n        description=\"Adjust how values of type 'None' are handled. For more context on \"\n        \"how mypy handles values of type 'None', see: \"\n        \"https://mypy.readthedocs.io/en/stable/kinds_of_types.html#optional-types-and-the-none-type\",\n    )\n    add_invertible_flag(\n        \"--implicit-optional\",\n        default=False,\n        help=\"Assume arguments with default values of None are Optional\",\n        group=none_group,\n    )\n    none_group.add_argument(\"--strict-optional\", action=\"store_true\", help=argparse.SUPPRESS)\n    none_group.add_argument(\n        \"--no-strict-optional\",\n        action=\"store_false\",\n        dest=\"strict_optional\",\n        help=\"Disable strict Optional checks (inverse: --strict-optional)\",\n    )\n\n    lint_group = parser.add_argument_group(\n        title=\"Configuring warnings\",\n        description=\"Detect code that is sound but redundant or problematic.\",\n    )\n    add_invertible_flag(\n        \"--warn-redundant-casts\",\n        default=False,\n        strict_flag=True,\n        help=\"Warn about casting an expression to its inferred type\",\n        group=lint_group,\n    )\n    add_invertible_flag(\n        \"--warn-unused-ignores\",\n        default=False,\n        strict_flag=True,\n        help=\"Warn about unneeded '# type: ignore' comments\",\n        group=lint_group,\n    )\n    add_invertible_flag(\n        \"--no-warn-no-return\",\n        dest=\"warn_no_return\",\n        default=True,\n        help=\"Do not warn about functions that end without returning\",\n        group=lint_group,\n    )\n    add_invertible_flag(\n        \"--warn-return-any\",\n        default=False,\n        strict_flag=True,\n        help=\"Warn about returning values of type Any from non-Any typed functions\",\n        group=lint_group,\n    )\n    add_invertible_flag(\n        \"--warn-unreachable\",\n        default=False,\n        strict_flag=False,\n        help=\"Warn about statements or expressions inferred to be unreachable\",\n        group=lint_group,\n    )\n    add_invertible_flag(\n        \"--report-deprecated-as-note\",\n        default=False,\n        strict_flag=False,\n        help=\"Report importing or using deprecated features as notes instead of errors\",\n        group=lint_group,\n    )\n    lint_group.add_argument(\n        \"--deprecated-calls-exclude\",\n        metavar=\"MODULE\",\n        action=\"append\",\n        default=[],\n        help=\"Disable deprecated warnings for functions/methods coming\"\n        \" from specific package, module, or class\",\n    )\n\n    # Note: this group is intentionally added here even though we don't add\n    # --strict to this group near the end.\n    #\n    # That way, this group will appear after the various strictness groups\n    # but before the remaining flags.\n    # We add `--strict` near the end so we don't accidentally miss any strictness\n    # flags that are added after this group.\n    strictness_group = parser.add_argument_group(title=\"Miscellaneous strictness flags\")\n\n    add_invertible_flag(\n        \"--allow-untyped-globals\",\n        default=False,\n        strict_flag=False,\n        help=\"Suppress toplevel errors caused by missing annotations\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--allow-redefinition\",\n        default=False,\n        strict_flag=False,\n        help=\"Alias to --allow-redefinition-old; will point to --allow-redefinition-new in v2.0\",\n        group=strictness_group,\n        dest=\"allow_redefinition_old\",\n    )\n\n    add_invertible_flag(\n        \"--allow-redefinition-old\",\n        default=False,\n        strict_flag=False,\n        help=\"Allow restricted, unconditional variable redefinition with a new type\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--allow-redefinition-new\",\n        default=False,\n        strict_flag=False,\n        help=\"Allow more flexible variable redefinition semantics\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--no-implicit-reexport\",\n        default=True,\n        strict_flag=True,\n        dest=\"implicit_reexport\",\n        help=\"Treat imports as private unless aliased\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--strict-equality\",\n        default=False,\n        strict_flag=True,\n        help=\"Prohibit equality, identity, and container checks for non-overlapping types \"\n        \"(except `None`)\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--strict-equality-for-none\",\n        default=False,\n        strict_flag=False,\n        help=\"Extend `--strict-equality` for `None` checks\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--strict-bytes\",\n        default=False,\n        strict_flag=True,\n        help=\"Disable treating bytearray and memoryview as subtypes of bytes\",\n        group=strictness_group,\n    )\n\n    add_invertible_flag(\n        \"--extra-checks\",\n        default=False,\n        strict_flag=True,\n        help=\"Enable additional checks that are technically correct but may be impractical \"\n        \"in real code. For example, this prohibits partial overlap in TypedDict updates, \"\n        \"and makes arguments prepended via Concatenate positional-only\",\n        group=strictness_group,\n    )\n\n    strict_help = \"Strict mode; enables the following flags: {}\".format(\n        \", \".join(strict_flag_names)\n    )\n    strictness_group.add_argument(\n        \"--strict\", action=\"store_true\", dest=\"special-opts:strict\", help=strict_help\n    )\n\n    strictness_group.add_argument(\n        \"--disable-error-code\",\n        metavar=\"NAME\",\n        action=\"append\",\n        default=[],\n        help=\"Disable a specific error code\",\n    )\n    strictness_group.add_argument(\n        \"--enable-error-code\",\n        metavar=\"NAME\",\n        action=\"append\",\n        default=[],\n        help=\"Enable a specific error code\",\n    )\n\n    error_group = parser.add_argument_group(\n        title=\"Configuring error messages\",\n        description=\"Adjust the amount of detail shown in error messages.\",\n    )\n    add_invertible_flag(\n        \"--show-error-context\",\n        default=False,\n        dest=\"show_error_context\",\n        help='Precede errors with \"note:\" messages explaining context',\n        group=error_group,\n    )\n    add_invertible_flag(\n        \"--show-column-numbers\",\n        default=False,\n        help=\"Show column numbers in error messages\",\n        group=error_group,\n    )\n    add_invertible_flag(\n        \"--show-error-end\",\n        default=False,\n        help=\"Show end line/end column numbers in error messages.\"\n        \" This implies --show-column-numbers\",\n        group=error_group,\n    )\n    add_invertible_flag(\n        \"--hide-error-codes\",\n        default=False,\n        help=\"Hide error codes in error messages\",\n        group=error_group,\n    )\n    add_invertible_flag(\n        \"--show-error-code-links\",\n        default=False,\n        help=\"Show links to error code documentation\",\n        group=error_group,\n    )\n    add_invertible_flag(\n        \"--pretty\",\n        default=False,\n        help=\"Use visually nicer output in error messages:\"\n        \" Use soft word wrap, show source code snippets,\"\n        \" and show error location markers\",\n        group=error_group,\n    )\n    add_invertible_flag(\n        \"--no-color-output\",\n        dest=\"color_output\",\n        default=True,\n        help=\"Do not colorize error messages\",\n        group=error_group,\n    )\n    add_invertible_flag(\n        \"--no-error-summary\",\n        dest=\"error_summary\",\n        default=True,\n        help=\"Do not show error stats summary\",\n        group=error_group,\n    )\n    add_invertible_flag(\n        \"--show-absolute-path\",\n        default=False,\n        help=\"Show absolute paths to files\",\n        group=error_group,\n    )\n    error_group.add_argument(\n        \"--soft-error-limit\",\n        default=defaults.MANY_ERRORS_THRESHOLD,\n        type=int,\n        dest=\"many_errors_threshold\",\n        help=argparse.SUPPRESS,\n    )\n\n    incremental_group = parser.add_argument_group(\n        title=\"Incremental mode\",\n        description=\"Adjust how mypy incrementally type checks and caches modules. \"\n        \"Mypy caches type information about modules into a cache to \"\n        \"let you speed up future invocations of mypy. Also see \"\n        \"mypy's daemon mode: \"\n        \"https://mypy.readthedocs.io/en/stable/mypy_daemon.html#mypy-daemon\",\n    )\n    incremental_group.add_argument(\n        \"-i\", \"--incremental\", action=\"store_true\", help=argparse.SUPPRESS\n    )\n    incremental_group.add_argument(\n        \"--no-incremental\",\n        action=\"store_false\",\n        dest=\"incremental\",\n        help=\"Disable module cache (inverse: --incremental)\",\n    )\n    incremental_group.add_argument(\n        \"--cache-dir\",\n        action=\"store\",\n        metavar=\"DIR\",\n        help=\"Store module cache info in the given folder in incremental mode \"\n        \"(defaults to '{}')\".format(defaults.CACHE_DIR),\n    )\n    add_invertible_flag(\n        \"--sqlite-cache\",\n        default=False,\n        help=\"Use a sqlite database to store the cache\",\n        group=incremental_group,\n    )\n    incremental_group.add_argument(\n        \"--cache-fine-grained\",\n        action=\"store_true\",\n        help=\"Include fine-grained dependency information in the cache for the mypy daemon\",\n    )\n    add_invertible_flag(\n        \"--no-fixed-format-cache\",\n        dest=\"fixed_format_cache\",\n        default=True,\n        help=\"Do not use new fixed format cache\",\n        group=incremental_group,\n    )\n    incremental_group.add_argument(\n        \"--skip-version-check\",\n        action=\"store_true\",\n        help=\"Allow using cache written by older mypy version\",\n    )\n    incremental_group.add_argument(\n        \"--skip-cache-mtime-checks\",\n        action=\"store_true\",\n        help=\"Skip cache internal consistency checks based on mtime\",\n    )\n\n    internals_group = parser.add_argument_group(\n        title=\"Advanced options\", description=\"Debug and customize mypy internals.\"\n    )\n    internals_group.add_argument(\"--pdb\", action=\"store_true\", help=\"Invoke pdb on fatal error\")\n    internals_group.add_argument(\n        \"--show-traceback\", \"--tb\", action=\"store_true\", help=\"Show traceback on fatal error\"\n    )\n    internals_group.add_argument(\n        \"--raise-exceptions\", action=\"store_true\", help=\"Raise exception on fatal error\"\n    )\n    internals_group.add_argument(\n        \"--custom-typing-module\",\n        metavar=\"MODULE\",\n        dest=\"custom_typing_module\",\n        help=\"Use a custom typing module\",\n    )\n    internals_group.add_argument(\n        \"--old-type-inference\", action=\"store_true\", help=argparse.SUPPRESS\n    )\n    internals_group.add_argument(\n        \"--disable-expression-cache\", action=\"store_true\", help=argparse.SUPPRESS\n    )\n    parser.add_argument(\n        \"--enable-incomplete-feature\",\n        action=\"append\",\n        metavar=\"{\" + \",\".join(sorted(INCOMPLETE_FEATURES)) + \"}\",\n        help=\"Enable support of incomplete/experimental features for early preview\",\n    )\n    internals_group.add_argument(\n        \"--custom-typeshed-dir\", metavar=\"DIR\", help=\"Use the custom typeshed in DIR\"\n    )\n    add_invertible_flag(\n        \"--warn-incomplete-stub\",\n        default=False,\n        help=\"Warn if missing type annotation in typeshed, only relevant with\"\n        \" --disallow-untyped-defs or --disallow-incomplete-defs enabled\",\n        group=internals_group,\n    )\n    internals_group.add_argument(\n        \"--shadow-file\",\n        nargs=2,\n        metavar=(\"SOURCE_FILE\", \"SHADOW_FILE\"),\n        dest=\"shadow_file\",\n        action=\"append\",\n        help=\"When encountering SOURCE_FILE, read and type check \"\n        \"the contents of SHADOW_FILE instead.\",\n    )\n    internals_group.add_argument(\"--fast-exit\", action=\"store_true\", help=argparse.SUPPRESS)\n    internals_group.add_argument(\n        \"--no-fast-exit\", action=\"store_false\", dest=\"fast_exit\", help=argparse.SUPPRESS\n    )\n    # This flag is useful for mypy tests, where function bodies may be omitted. Plugin developers\n    # may want to use this as well in their tests.\n    add_invertible_flag(\n        \"--allow-empty-bodies\", default=False, help=argparse.SUPPRESS, group=internals_group\n    )\n    # This undocumented feature exports limited line-level dependency information.\n    internals_group.add_argument(\"--export-ref-info\", action=\"store_true\", help=argparse.SUPPRESS)\n\n    # Experimental parallel type-checking support.\n    internals_group.add_argument(\n        \"-n\", \"--num-workers\", type=int, default=0, help=argparse.SUPPRESS\n    )\n\n    report_group = parser.add_argument_group(\n        title=\"Report generation\", description=\"Generate a report in the specified format.\"\n    )\n    for report_type in sorted(defaults.REPORTER_NAMES):\n        if report_type not in {\"memory-xml\"}:\n            report_group.add_argument(\n                f\"--{report_type.replace('_', '-')}-report\",\n                metavar=\"DIR\",\n                dest=f\"special-opts:{report_type}_report\",\n            )\n\n    # Undocumented mypyc feature: generate annotated HTML source file\n    report_group.add_argument(\n        \"-a\", dest=\"mypyc_annotation_file\", type=str, default=None, help=argparse.SUPPRESS\n    )\n    # Hidden mypyc feature: do not write any C files (keep existing ones and assume they exist).\n    # This can be useful when debugging mypyc bugs.\n    report_group.add_argument(\n        \"--skip-c-gen\", dest=\"mypyc_skip_c_generation\", action=\"store_true\", help=argparse.SUPPRESS\n    )\n\n    misc_group = parser.add_argument_group(title=\"Miscellaneous\")\n    misc_group.add_argument(\"--quickstart-file\", help=argparse.SUPPRESS)\n    misc_group.add_argument(\n        \"--junit-xml\",\n        metavar=\"JUNIT_XML_OUTPUT_FILE\",\n        help=\"Write a JUnit XML test result document with type checking results to the given file\",\n    )\n    misc_group.add_argument(\n        \"--junit-format\",\n        choices=[\"global\", \"per_file\"],\n        default=\"global\",\n        help=\"If --junit-xml is set, specifies format. global (default): single test with all errors; per_file: one test entry per file with failures\",\n    )\n    misc_group.add_argument(\n        \"--find-occurrences\",\n        metavar=\"CLASS.MEMBER\",\n        dest=\"special-opts:find_occurrences\",\n        help=\"Print out all usages of a class member (experimental)\",\n    )\n    misc_group.add_argument(\n        \"--scripts-are-modules\",\n        action=\"store_true\",\n        help=\"Script x becomes module x instead of __main__\",\n    )\n\n    add_invertible_flag(\n        \"--install-types\",\n        default=False,\n        strict_flag=False,\n        help=\"Install detected missing library stub packages using pip\",\n        group=misc_group,\n    )\n    add_invertible_flag(\n        \"--non-interactive\",\n        default=False,\n        strict_flag=False,\n        help=(\n            \"Install stubs without asking for confirmation and hide \"\n            + \"errors, with --install-types\"\n        ),\n        group=misc_group,\n        inverse=\"--interactive\",\n    )\n\n    if server_options:\n        misc_group.add_argument(\n            \"--use-fine-grained-cache\",\n            action=\"store_true\",\n            help=\"Use the cache in fine-grained incremental mode\",\n        )\n\n    # hidden options\n    parser.add_argument(\n        \"--stats\", action=\"store_true\", dest=\"dump_type_stats\", help=argparse.SUPPRESS\n    )\n    parser.add_argument(\n        \"--inferstats\", action=\"store_true\", dest=\"dump_inference_stats\", help=argparse.SUPPRESS\n    )\n    parser.add_argument(\"--dump-build-stats\", action=\"store_true\", help=argparse.SUPPRESS)\n    # Dump timing stats for each processed file into the given output file\n    parser.add_argument(\"--timing-stats\", dest=\"timing_stats\", help=argparse.SUPPRESS)\n    # Dump per line type checking timing stats for each processed file into the given\n    # output file. Only total time spent in each top level expression will be shown.\n    # Times are show in microseconds.\n    parser.add_argument(\n        \"--line-checking-stats\", dest=\"line_checking_stats\", help=argparse.SUPPRESS\n    )\n    # --debug-cache will disable any cache-related compressions/optimizations,\n    # which will make the cache writing process output pretty-printed JSON (which\n    # is easier to debug).\n    parser.add_argument(\"--debug-cache\", action=\"store_true\", help=argparse.SUPPRESS)\n    # --dump-deps will dump all fine-grained dependencies to stdout\n    parser.add_argument(\"--dump-deps\", action=\"store_true\", help=argparse.SUPPRESS)\n    # --dump-graph will dump the contents of the graph of SCCs and exit.\n    parser.add_argument(\"--dump-graph\", action=\"store_true\", help=argparse.SUPPRESS)\n    # --semantic-analysis-only does exactly that.\n    parser.add_argument(\"--semantic-analysis-only\", action=\"store_true\", help=argparse.SUPPRESS)\n    # Some tests use this to tell mypy that we are running a test.\n    parser.add_argument(\"--test-env\", action=\"store_true\", help=argparse.SUPPRESS)\n    # --local-partial-types disallows partial types spanning module top level and a function\n    # (implicitly defined in fine-grained incremental mode)\n    add_invertible_flag(\"--local-partial-types\", default=False, help=argparse.SUPPRESS)\n    # --native-parser enables the native parser (experimental)\n    add_invertible_flag(\"--native-parser\", default=False, help=argparse.SUPPRESS)\n    # --logical-deps adds some more dependencies that are not semantically needed, but\n    # may be helpful to determine relative importance of classes and functions for overall\n    # type precision in a code base. It also _removes_ some deps, so this flag should be never\n    # used except for generating code stats. This also automatically enables --cache-fine-grained.\n    # NOTE: This is an experimental option that may be modified or removed at any time.\n    parser.add_argument(\"--logical-deps\", action=\"store_true\", help=argparse.SUPPRESS)\n    # --bazel changes some behaviors for use with Bazel (https://bazel.build).\n    parser.add_argument(\"--bazel\", action=\"store_true\", help=argparse.SUPPRESS)\n    # --package-root adds a directory below which directories are considered\n    # packages even without __init__.py.  May be repeated.\n    parser.add_argument(\n        \"--package-root\", metavar=\"ROOT\", action=\"append\", default=[], help=argparse.SUPPRESS\n    )\n    # --cache-map FILE ... gives a mapping from source files to cache files.\n    # Each triple of arguments is a source file, a cache meta file, and a cache data file.\n    # Modules not mentioned in the file will go through cache_dir.\n    # Must be followed by another flag or by '--' (and then only file args may follow).\n    parser.add_argument(\n        \"--cache-map\", nargs=\"+\", dest=\"special-opts:cache_map\", help=argparse.SUPPRESS\n    )\n    # --debug-serialize will run tree.serialize() even if cache generation is disabled.\n    # Useful for mypy_primer to detect serialize errors earlier.\n    parser.add_argument(\"--debug-serialize\", action=\"store_true\", help=argparse.SUPPRESS)\n\n    parser.add_argument(\n        \"--disable-bytearray-promotion\", action=\"store_true\", help=argparse.SUPPRESS\n    )\n    parser.add_argument(\n        \"--disable-memoryview-promotion\", action=\"store_true\", help=argparse.SUPPRESS\n    )\n    # This flag is deprecated, it has been moved to --extra-checks\n    parser.add_argument(\"--strict-concatenate\", action=\"store_true\", help=argparse.SUPPRESS)\n\n    # options specifying code to check\n    code_group = parser.add_argument_group(\n        title=\"Running code\",\n        description=\"Specify the code you want to type check. For more details, see \"\n        \"https://mypy.readthedocs.io/en/stable/running_mypy.html#running-mypy\",\n    )\n    add_invertible_flag(\n        \"--explicit-package-bases\",\n        default=False,\n        help=\"Use current directory and MYPYPATH to determine module names of files passed\",\n        group=code_group,\n    )\n    add_invertible_flag(\n        \"--fast-module-lookup\", default=False, help=argparse.SUPPRESS, group=code_group\n    )\n    code_group.add_argument(\n        \"--exclude\",\n        action=\"append\",\n        metavar=\"PATTERN\",\n        default=[],\n        help=(\n            \"Regular expression to match file names, directory names or paths which mypy should \"\n            \"ignore while recursively discovering files to check, e.g. --exclude '/setup\\\\.py$'. \"\n            \"May be specified more than once, eg. --exclude a --exclude b\"\n        ),\n    )\n    add_invertible_flag(\n        \"--exclude-gitignore\",\n        default=False,\n        help=(\n            \"Use .gitignore file(s) to exclude files from checking \"\n            \"(in addition to any explicit --exclude if present)\"\n        ),\n        group=code_group,\n    )\n    code_group.add_argument(\n        \"-m\",\n        \"--module\",\n        action=\"append\",\n        metavar=\"MODULE\",\n        default=[],\n        dest=\"special-opts:modules\",\n        help=\"Type-check module; can repeat for more modules\",\n    )\n    code_group.add_argument(\n        \"-p\",\n        \"--package\",\n        action=\"append\",\n        metavar=\"PACKAGE\",\n        default=[],\n        dest=\"special-opts:packages\",\n        help=\"Type-check package recursively; can be repeated\",\n    )\n    code_group.add_argument(\n        \"-c\",\n        \"--command\",\n        action=\"append\",\n        metavar=\"PROGRAM_TEXT\",\n        dest=\"special-opts:command\",\n        help=\"Type-check program passed in as string\",\n    )\n    code_group.add_argument(\n        metavar=\"files\",\n        nargs=\"*\",\n        dest=\"special-opts:files\",\n        help=\"Type-check given files or directories\",\n    )\n    return parser, strict_flag_names, strict_flag_assignments\n\n\ndef process_options(\n    args: list[str],\n    stdout: TextIO | None = None,\n    stderr: TextIO | None = None,\n    require_targets: bool = True,\n    server_options: bool = False,\n    fscache: FileSystemCache | None = None,\n    program: str = \"mypy\",\n    header: str = HEADER,\n    mypyc: bool = False,\n) -> tuple[list[BuildSource], Options]:\n    \"\"\"Parse command line arguments.\n\n    If a FileSystemCache is passed in, and package_root options are given,\n    call fscache.set_package_root() to set the cache's package root.\n\n    Returns a tuple of: a list of source files, an Options collected from flags.\n    \"\"\"\n    stdout = stdout if stdout is not None else sys.stdout\n    stderr = stderr if stderr is not None else sys.stderr\n\n    parser, _, strict_flag_assignments = define_options(\n        program, header, stdout, stderr, server_options\n    )\n\n    # Parse arguments once into a dummy namespace so we can get the\n    # filename for the config file and know if the user requested all strict options.\n    dummy = argparse.Namespace()\n    parser.parse_args(args, dummy)\n    config_file = dummy.config_file\n    # Don't explicitly test if \"config_file is not None\" for this check.\n    # This lets `--config-file=` (an empty string) be used to disable all config files.\n    if config_file and not os.path.exists(config_file):\n        parser.error(f\"Cannot find config file '{config_file}'\")\n\n    options = Options()\n    strict_option_set = False\n    if mypyc:\n        # Mypyc has strict_bytes enabled by default\n        options.strict_bytes = True\n\n    def set_strict_flags() -> None:\n        nonlocal strict_option_set\n        strict_option_set = True\n        for dest, value in strict_flag_assignments:\n            setattr(options, dest, value)\n\n    # Parse config file first, so command line can override.\n    parse_config_file(options, set_strict_flags, config_file, stdout, stderr)\n\n    # Set strict flags before parsing (if strict mode enabled), so other command\n    # line options can override.\n    if getattr(dummy, \"special-opts:strict\"):\n        set_strict_flags()\n\n    # Override cache_dir if provided in the environment\n    environ_cache_dir = os.getenv(\"MYPY_CACHE_DIR\", \"\")\n    if environ_cache_dir.strip():\n        options.cache_dir = environ_cache_dir\n    options.cache_dir = os.path.expanduser(options.cache_dir)\n\n    # Parse command line for real, using a split namespace.\n    special_opts = argparse.Namespace()\n    parser.parse_args(args, SplitNamespace(options, special_opts, \"special-opts:\"))\n\n    # The python_version is either the default, which can be overridden via a config file,\n    # or stored in special_opts and is passed via the command line.\n    options.python_version = special_opts.python_version or options.python_version\n    if options.python_version < (3,):\n        parser.error(\n            \"Mypy no longer supports checking Python 2 code. \"\n            \"Consider pinning to mypy<0.980 if you need to check Python 2 code.\"\n        )\n    try:\n        infer_python_executable(options, special_opts)\n    except PythonExecutableInferenceError as e:\n        parser.error(str(e))\n\n    if special_opts.no_executable or options.no_site_packages:\n        options.python_executable = None\n\n    # Paths listed in the config file will be ignored if any paths, modules or packages\n    # are passed on the command line.\n    if not (special_opts.files or special_opts.packages or special_opts.modules):\n        if options.files:\n            special_opts.files = options.files\n        if options.packages:\n            special_opts.packages = options.packages\n        if options.modules:\n            special_opts.modules = options.modules\n\n    # Check for invalid argument combinations.\n    if require_targets:\n        code_methods = sum(\n            bool(c)\n            for c in [\n                special_opts.modules + special_opts.packages,\n                special_opts.command,\n                special_opts.files,\n            ]\n        )\n        if code_methods == 0 and not options.install_types:\n            parser.error(\"Missing target module, package, files, or command.\")\n        elif code_methods > 1:\n            parser.error(\"May only specify one of: module/package, files, or command.\")\n    if options.explicit_package_bases and not options.namespace_packages:\n        parser.error(\n            \"Can only use --explicit-package-bases with --namespace-packages, since otherwise \"\n            \"examining __init__.py's is sufficient to determine module names for files\"\n        )\n\n    # Check for overlapping `--always-true` and `--always-false` flags.\n    overlap = set(options.always_true) & set(options.always_false)\n    if overlap:\n        parser.error(\n            \"You can't make a variable always true and always false (%s)\"\n            % \", \".join(sorted(overlap))\n        )\n\n    validate_package_allow_list(options.untyped_calls_exclude)\n    validate_package_allow_list(options.deprecated_calls_exclude)\n\n    options.process_incomplete_features(error_callback=parser.error, warning_callback=print)\n\n    # Compute absolute path for custom typeshed (if present).\n    if options.custom_typeshed_dir is not None:\n        options.abs_custom_typeshed_dir = os.path.abspath(options.custom_typeshed_dir)\n\n    # Set build flags.\n    if special_opts.find_occurrences:\n        _find_occurrences = tuple(special_opts.find_occurrences.split(\".\"))\n        if len(_find_occurrences) < 2:\n            parser.error(\"Can only find occurrences of class members.\")\n        if len(_find_occurrences) != 2:\n            parser.error(\"Can only find occurrences of non-nested class members.\")\n        state.find_occurrences = _find_occurrences\n\n    # Set reports.\n    for flag, val in vars(special_opts).items():\n        if flag.endswith(\"_report\") and val is not None:\n            report_type = flag[:-7].replace(\"_\", \"-\")\n            report_dir = val\n            options.report_dirs[report_type] = report_dir\n\n    # Process --package-root.\n    if options.package_root:\n        process_package_roots(fscache, parser, options)\n\n    # Process --cache-map.\n    if special_opts.cache_map:\n        if options.sqlite_cache:\n            parser.error(\"--cache-map is incompatible with --sqlite-cache\")\n\n        process_cache_map(parser, special_opts, options)\n\n    # Process --strict-bytes\n    options.process_strict_bytes()\n\n    # An explicitly specified cache_fine_grained implies local_partial_types\n    # (because otherwise the cache is not compatible with dmypy)\n    if options.cache_fine_grained:\n        options.local_partial_types = True\n\n    #  Implicitly show column numbers if error location end is shown\n    if options.show_error_end:\n        options.show_column_numbers = True\n\n    # Let logical_deps imply cache_fine_grained (otherwise the former is useless).\n    if options.logical_deps:\n        options.cache_fine_grained = True\n\n    if options.strict_concatenate and not strict_option_set:\n        print(\"Warning: --strict-concatenate is deprecated; use --extra-checks instead\")\n\n    # Set target.\n    if special_opts.modules + special_opts.packages:\n        options.build_type = BuildType.MODULE\n        sys_path, _ = get_search_dirs(options.python_executable)\n        search_paths = SearchPaths(\n            (os.getcwd(),), tuple(mypy_path() + options.mypy_path), tuple(sys_path), ()\n        )\n        targets = []\n        # TODO: use the same cache that the BuildManager will\n        cache = FindModuleCache(search_paths, fscache, options)\n        for p in special_opts.packages:\n            if os.sep in p or os.altsep and os.altsep in p:\n                fail(f\"Package name '{p}' cannot have a slash in it.\", stderr, options)\n            p_targets = cache.find_modules_recursive(p)\n            if not p_targets:\n                reason = cache.find_module(p)\n                if reason is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS:\n                    fail(\n                        f\"Package '{p}' cannot be type checked due to missing py.typed marker. See https://mypy.readthedocs.io/en/stable/installed_packages.html for more details\",\n                        stderr,\n                        options,\n                    )\n                else:\n                    fail(f\"Can't find package '{p}'\", stderr, options)\n            targets.extend(p_targets)\n        for m in special_opts.modules:\n            targets.append(BuildSource(None, m, None))\n    elif special_opts.command:\n        options.build_type = BuildType.PROGRAM_TEXT\n        targets = [BuildSource(None, None, \"\\n\".join(special_opts.command))]\n    else:\n        try:\n            targets = create_source_list(special_opts.files, options, fscache)\n        # Variable named e2 instead of e to work around mypyc bug #620\n        # which causes issues when using the same variable to catch\n        # exceptions of different types.\n        except InvalidSourceList as e2:\n            fail(str(e2), stderr, options)\n    return targets, options\n\n\ndef process_package_roots(\n    fscache: FileSystemCache | None, parser: argparse.ArgumentParser, options: Options\n) -> None:\n    \"\"\"Validate and normalize package_root.\"\"\"\n    if fscache is None:\n        parser.error(\"--package-root does not work here (no fscache)\")\n    assert fscache is not None  # Since mypy doesn't know parser.error() raises.\n    # Do some stuff with drive letters to make Windows happy (esp. tests).\n    current_drive, _ = os.path.splitdrive(os.getcwd())\n    dot = os.curdir\n    dotslash = os.curdir + os.sep\n    dotdotslash = os.pardir + os.sep\n    trivial_paths = {dot, dotslash}\n    package_root = []\n    for root in options.package_root:\n        if os.path.isabs(root):\n            parser.error(f\"Package root cannot be absolute: {root!r}\")\n        drive, root = os.path.splitdrive(root)\n        if drive and drive != current_drive:\n            parser.error(f\"Package root must be on current drive: {drive + root!r}\")\n        # Empty package root is always okay.\n        if root:\n            root = os.path.relpath(root)  # Normalize the heck out of it.\n            if not root.endswith(os.sep):\n                root = root + os.sep\n            if root.startswith(dotdotslash):\n                parser.error(f\"Package root cannot be above current directory: {root!r}\")\n            if root in trivial_paths:\n                root = \"\"\n        package_root.append(root)\n    options.package_root = package_root\n    # Pass the package root on the filesystem cache.\n    fscache.set_package_root(package_root)\n\n\ndef process_cache_map(\n    parser: argparse.ArgumentParser, special_opts: argparse.Namespace, options: Options\n) -> None:\n    \"\"\"Validate cache_map and copy into options.cache_map.\"\"\"\n    n = len(special_opts.cache_map)\n    if n % 3 != 0:\n        parser.error(\"--cache-map requires one or more triples (see source)\")\n    for i in range(0, n, 3):\n        source, meta_file, data_file = special_opts.cache_map[i : i + 3]\n        if source in options.cache_map:\n            parser.error(f\"Duplicate --cache-map source {source})\")\n        if not source.endswith(\".py\") and not source.endswith(\".pyi\"):\n            parser.error(f\"Invalid --cache-map source {source} (triple[0] must be *.py[i])\")\n        if not meta_file.endswith(\".meta.json\"):\n            parser.error(\n                \"Invalid --cache-map meta_file %s (triple[1] must be *.meta.json)\" % meta_file\n            )\n        if not data_file.endswith(\".data.json\"):\n            parser.error(\n                \"Invalid --cache-map data_file %s (triple[2] must be *.data.json)\" % data_file\n            )\n        options.cache_map[source] = (meta_file, data_file)\n\n\ndef maybe_write_junit_xml(\n    td: float,\n    serious: bool,\n    all_messages: list[str],\n    messages_by_file: dict[str | None, list[str]],\n    options: Options,\n) -> None:\n    if options.junit_xml:\n        py_version = f\"{options.python_version[0]}_{options.python_version[1]}\"\n        if options.junit_format == \"global\":\n            util.write_junit_xml(\n                td,\n                serious,\n                {None: all_messages} if all_messages else {},\n                options.junit_xml,\n                py_version,\n                options.platform,\n            )\n        else:\n            # per_file\n            util.write_junit_xml(\n                td, serious, messages_by_file, options.junit_xml, py_version, options.platform\n            )\n\n\ndef fail(msg: str, stderr: TextIO, options: Options) -> NoReturn:\n    \"\"\"Fail with a serious error.\"\"\"\n    stderr.write(f\"{msg}\\n\")\n    maybe_write_junit_xml(\n        0.0, serious=True, all_messages=[msg], messages_by_file={None: [msg]}, options=options\n    )\n    sys.exit(2)\n\n\ndef read_types_packages_to_install(cache_dir: str, after_run: bool) -> list[str]:\n    if not os.path.isdir(cache_dir):\n        if not after_run:\n            sys.stderr.write(\n                \"error: Can't determine which types to install with no files to check \"\n                + \"(and no cache from previous mypy run)\\n\"\n            )\n        else:\n            sys.stderr.write(\n                \"error: --install-types failed (an error blocked analysis of which types to install)\\n\"\n            )\n    fnam = build.missing_stubs_file(cache_dir)\n    if not os.path.isfile(fnam):\n        # No missing stubs.\n        return []\n    with open(fnam) as f:\n        return [line.strip() for line in f]\n\n\ndef install_types(\n    formatter: util.FancyFormatter,\n    options: Options,\n    *,\n    after_run: bool = False,\n    non_interactive: bool = False,\n) -> bool:\n    \"\"\"Install stub packages using pip if some missing stubs were detected.\"\"\"\n    packages = read_types_packages_to_install(options.cache_dir, after_run)\n    if not packages:\n        # If there are no missing stubs, generate no output.\n        return False\n    if after_run and not non_interactive:\n        print()\n    print(\"Installing missing stub packages:\")\n    assert options.python_executable, \"Python executable required to install types\"\n    cmd = [options.python_executable, \"-m\", \"pip\", \"install\"] + packages\n    print(formatter.style(\" \".join(cmd), \"none\", bold=True))\n    print()\n    if not non_interactive:\n        x = input(\"Install? [yN] \")\n        if not x.strip() or not x.lower().startswith(\"y\"):\n            print(formatter.style(\"mypy: Skipping installation\", \"red\", bold=True))\n            sys.exit(2)\n        print()\n    subprocess.run(cmd)\n    return True\n"
  },
  {
    "path": "mypy/maptype.py",
    "content": "from __future__ import annotations\n\nfrom mypy.expandtype import expand_type_by_instance\nfrom mypy.nodes import TypeInfo\nfrom mypy.types import AnyType, Instance, TupleType, TypeOfAny, has_type_vars\n\n\ndef map_instance_to_supertype(instance: Instance, superclass: TypeInfo) -> Instance:\n    \"\"\"Produce a supertype of `instance` that is an Instance\n    of `superclass`, mapping type arguments up the chain of bases.\n\n    If `superclass` is not a nominal superclass of `instance.type`,\n    then all type arguments are mapped to 'Any'.\n    \"\"\"\n    if instance.type == superclass:\n        # Fast path: `instance` already belongs to `superclass`.\n        return instance\n\n    if superclass.fullname == \"builtins.tuple\" and instance.type.tuple_type:\n        if has_type_vars(instance.type.tuple_type):\n            # We special case mapping generic tuple types to tuple base, because for\n            # such tuples fallback can't be calculated before applying type arguments.\n            alias = instance.type.special_alias\n            assert alias is not None\n            if not alias._is_recursive:\n                # Unfortunately we can't support this for generic recursive tuples.\n                # If we skip this special casing we will fall back to tuple[Any, ...].\n                tuple_type = expand_type_by_instance(instance.type.tuple_type, instance)\n                if isinstance(tuple_type, TupleType):\n                    # Make the import here to avoid cyclic imports.\n                    import mypy.typeops\n\n                    return mypy.typeops.tuple_fallback(tuple_type)\n                elif isinstance(tuple_type, Instance):\n                    # This can happen after normalizing variadic tuples.\n                    return tuple_type\n\n    if not superclass.type_vars:\n        # Fast path: `superclass` has no type variables to map to.\n        return Instance(superclass, [])\n\n    return map_instance_to_supertypes(instance, superclass)[0]\n\n\ndef map_instance_to_supertypes(instance: Instance, supertype: TypeInfo) -> list[Instance]:\n    # FIX: Currently we should only have one supertype per interface, so no\n    #      need to return an array\n    result: list[Instance] = []\n    for path in class_derivation_paths(instance.type, supertype):\n        types = [instance]\n        for sup in path:\n            a: list[Instance] = []\n            for t in types:\n                a.extend(map_instance_to_direct_supertypes(t, sup))\n            types = a\n        result.extend(types)\n    if result:\n        return result\n    else:\n        # Nothing. Presumably due to an error. Construct a dummy using Any.\n        any_type = AnyType(TypeOfAny.from_error)\n        return [Instance(supertype, [any_type] * len(supertype.type_vars))]\n\n\ndef class_derivation_paths(typ: TypeInfo, supertype: TypeInfo) -> list[list[TypeInfo]]:\n    \"\"\"Return an array of non-empty paths of direct base classes from\n    type to supertype.  Return [] if no such path could be found.\n\n      InterfaceImplementationPaths(A, B) == [[B]] if A inherits B\n      InterfaceImplementationPaths(A, C) == [[B, C]] if A inherits B and\n                                                        B inherits C\n    \"\"\"\n    # FIX: Currently we might only ever have a single path, so this could be\n    #      simplified\n    result: list[list[TypeInfo]] = []\n\n    for base in typ.bases:\n        btype = base.type\n        if btype == supertype:\n            result.append([btype])\n        else:\n            # Try constructing a longer path via the base class.\n            for path in class_derivation_paths(btype, supertype):\n                result.append([btype] + path)\n\n    return result\n\n\ndef map_instance_to_direct_supertypes(instance: Instance, supertype: TypeInfo) -> list[Instance]:\n    # FIX: There should only be one supertypes, always.\n    typ = instance.type\n    result: list[Instance] = []\n\n    for b in typ.bases:\n        if b.type == supertype:\n            t = expand_type_by_instance(b, instance)\n            assert isinstance(t, Instance)\n            result.append(t)\n\n    if result:\n        return result\n    else:\n        # Relationship with the supertype not specified explicitly. Use dynamic\n        # type arguments implicitly.\n        any_type = AnyType(TypeOfAny.unannotated)\n        return [Instance(supertype, [any_type] * len(supertype.type_vars))]\n"
  },
  {
    "path": "mypy/meet.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Callable\n\nfrom mypy import join\nfrom mypy.erasetype import erase_type\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.state import state\nfrom mypy.subtypes import (\n    are_parameters_compatible,\n    find_member,\n    is_callable_compatible,\n    is_equivalent,\n    is_proper_subtype,\n    is_same_type,\n    is_subtype,\n)\nfrom mypy.typeops import is_recursive_pair, make_simplified_union, tuple_fallback\nfrom mypy.types import (\n    MYPYC_NATIVE_INT_NAMES,\n    TUPLE_LIKE_INSTANCE_NAMES,\n    AnyType,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeGuardedType,\n    TypeOfAny,\n    TypeType,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    TypeVisitor,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    get_proper_type,\n    get_proper_types,\n    has_type_vars,\n    is_named_instance,\n    split_with_prefix_and_suffix,\n)\n\n# TODO Describe this module.\n\n\ndef trivial_meet(s: Type, t: Type) -> ProperType:\n    \"\"\"Return one of types (expanded) if it is a subtype of other, otherwise bottom type.\"\"\"\n    if is_subtype(s, t):\n        return get_proper_type(s)\n    elif is_subtype(t, s):\n        return get_proper_type(t)\n    else:\n        if state.strict_optional:\n            return UninhabitedType()\n        else:\n            return NoneType()\n\n\ndef meet_types(s: Type, t: Type) -> ProperType:\n    \"\"\"Return the greatest lower bound of two types.\"\"\"\n    if is_recursive_pair(s, t):\n        # This case can trigger an infinite recursion, general support for this will be\n        # tricky, so we use a trivial meet (like for protocols).\n        return trivial_meet(s, t)\n    s = get_proper_type(s)\n    t = get_proper_type(t)\n\n    if isinstance(s, Instance) and isinstance(t, Instance) and s.type == t.type:\n        # Code in checker.py should merge any extra_items where possible, so we\n        # should have only compatible extra_items here. We check this before\n        # the below subtype check, so that extra_attrs will not get erased.\n        if (s.extra_attrs or t.extra_attrs) and is_same_type(s, t):\n            if s.extra_attrs and t.extra_attrs:\n                if len(s.extra_attrs.attrs) > len(t.extra_attrs.attrs):\n                    # Return the one that has more precise information.\n                    return s\n                return t\n            if s.extra_attrs:\n                return s\n            return t\n\n    if not isinstance(s, UnboundType) and not isinstance(t, UnboundType):\n        if is_proper_subtype(s, t, ignore_promotions=True):\n            return s\n        if is_proper_subtype(t, s, ignore_promotions=True):\n            return t\n\n    if isinstance(s, ErasedType):\n        return s\n    if isinstance(s, AnyType):\n        return t\n    if isinstance(s, UnionType) and not isinstance(t, UnionType):\n        s, t = t, s\n\n    # Meets/joins require callable type normalization.\n    s, t = join.normalize_callables(s, t)\n\n    return t.accept(TypeMeetVisitor(s))\n\n\ndef narrow_declared_type(declared: Type, narrowed: Type) -> Type:\n    \"\"\"Return the declared type narrowed down to another type.\"\"\"\n    # TODO: check infinite recursion for aliases here.\n    if isinstance(narrowed, TypeGuardedType):\n        # A type guard forces the new type even if it doesn't overlap the old...\n        if is_proper_subtype(declared, narrowed.type_guard, ignore_promotions=True):\n            # ...unless it is a proper supertype of declared type.\n            return declared\n        return narrowed.type_guard\n\n    original_declared = declared\n    original_narrowed = narrowed\n    declared = get_proper_type(declared)\n    narrowed = get_proper_type(narrowed)\n\n    if declared == narrowed:\n        return original_declared\n    if isinstance(declared, UnionType):\n        declared_items = declared.relevant_items()\n        if isinstance(narrowed, UnionType):\n            narrowed_items = narrowed.relevant_items()\n        else:\n            narrowed_items = [narrowed]\n        return make_simplified_union(\n            [\n                narrow_declared_type(d, n)\n                for d in declared_items\n                for n in narrowed_items\n                # This (ugly) special-casing is needed to support checking\n                # branches like this:\n                # x: Union[float, complex]\n                # if isinstance(x, int):\n                #     ...\n                # And assignments like this:\n                # x: float | None\n                # y: int | None\n                # x = y\n                if (\n                    is_overlapping_types(d, n, ignore_promotions=True)\n                    or is_subtype(n, d, ignore_promotions=False)\n                )\n            ]\n        )\n    if is_enum_overlapping_union(declared, narrowed):\n        # Quick check before reaching `is_overlapping_types`. If it's enum/literal overlap,\n        # avoid full expansion and make it faster.\n        assert isinstance(narrowed, UnionType)\n        return make_simplified_union(\n            [narrow_declared_type(declared, x) for x in narrowed.relevant_items()]\n        )\n    elif (\n        isinstance(declared, TypeVarType)\n        and not has_type_vars(original_narrowed)\n        and is_subtype(original_narrowed, declared.upper_bound)\n    ):\n        # We put this branch early to get T(bound=Union[A, B]) instead of\n        # Union[T(bound=A), T(bound=B)] that will be confusing for users.\n        return declared.copy_modified(\n            upper_bound=narrow_declared_type(declared.upper_bound, original_narrowed)\n        )\n    elif not is_overlapping_types(declared, narrowed):\n        if state.strict_optional:\n            return UninhabitedType()\n        else:\n            return NoneType()\n    elif isinstance(narrowed, UnionType):\n        return make_simplified_union(\n            [narrow_declared_type(declared, x) for x in narrowed.relevant_items()]\n        )\n    elif isinstance(narrowed, AnyType):\n        return original_narrowed\n    elif isinstance(narrowed, TypeVarType) and is_subtype(narrowed.upper_bound, declared):\n        return narrowed\n    elif isinstance(declared, TypeType) and isinstance(narrowed, TypeType):\n        return TypeType.make_normalized(\n            narrow_declared_type(declared.item, narrowed.item),\n            is_type_form=declared.is_type_form and narrowed.is_type_form,\n        )\n    elif (\n        isinstance(declared, TypeType)\n        and isinstance(narrowed, Instance)\n        and narrowed.type.is_metaclass()\n    ):\n        if declared.is_type_form:\n            # The declared TypeForm[T] after narrowing must be a kind of\n            # type object at least as narrow as Type[T]\n            return narrow_declared_type(\n                TypeType.make_normalized(\n                    declared.item, line=declared.line, column=declared.column, is_type_form=False\n                ),\n                original_narrowed,\n            )\n        # We'd need intersection types, so give up.\n        return original_declared\n    elif isinstance(declared, Instance):\n        if declared.type.alt_promote:\n            # Special case: low-level integer type can't be narrowed\n            return original_declared\n        if (\n            isinstance(narrowed, Instance)\n            and narrowed.type.alt_promote\n            and narrowed.type.alt_promote.type is declared.type\n        ):\n            # Special case: 'int' can't be narrowed down to a native int type such as\n            # i64, since they have different runtime representations.\n            return original_declared\n        return meet_types(original_declared, original_narrowed)\n    elif isinstance(declared, (TupleType, TypeType, LiteralType)):\n        return meet_types(original_declared, original_narrowed)\n    elif isinstance(declared, TypedDictType) and isinstance(narrowed, Instance):\n        # Special case useful for selecting TypedDicts from unions using isinstance(x, dict).\n        if narrowed.type.fullname == \"builtins.dict\" and all(\n            isinstance(t, AnyType) for t in get_proper_types(narrowed.args)\n        ):\n            return original_declared\n        return meet_types(original_declared, original_narrowed)\n    elif (\n        isinstance(declared, CallableType)\n        and isinstance(narrowed, CallableType)\n        and has_type_vars(declared.ret_type)\n    ):\n        return narrowed.copy_modified(\n            ret_type=narrow_declared_type(declared.ret_type, narrowed.ret_type)\n        )\n\n    return original_narrowed\n\n\ndef get_possible_variants(typ: Type) -> list[Type]:\n    \"\"\"This function takes any \"Union-like\" type and returns a list of the available \"options\".\n\n    Specifically, there are currently exactly three different types that can have\n    \"variants\" or are \"union-like\":\n\n    - Unions\n    - TypeVars with value restrictions\n    - Overloads\n\n    This function will return a list of each \"option\" present in those types.\n\n    If this function receives any other type, we return a list containing just that\n    original type. (E.g. pretend the type was contained within a singleton union).\n\n    The only current exceptions are regular TypeVars and ParamSpecs. For these \"TypeVarLike\"s,\n    we return a list containing that TypeVarLike's upper bound.\n\n    This function is useful primarily when checking to see if two types are overlapping:\n    the algorithm to check if two unions are overlapping is fundamentally the same as\n    the algorithm for checking if two overloads are overlapping.\n\n    Normalizing both kinds of types in the same way lets us reuse the same algorithm\n    for both.\n    \"\"\"\n    typ = get_proper_type(typ)\n\n    if isinstance(typ, TypeVarType):\n        if len(typ.values) > 0:\n            return typ.values\n        else:\n            return [typ.upper_bound]\n    elif isinstance(typ, ParamSpecType):\n        # Extract 'object' from the final mro item\n        upper_bound = get_proper_type(typ.upper_bound)\n        if isinstance(upper_bound, Instance):\n            return [Instance(upper_bound.type.mro[-1], [])]\n        return [AnyType(TypeOfAny.implementation_artifact)]\n    elif isinstance(typ, TypeVarTupleType):\n        return [typ.upper_bound]\n    elif isinstance(typ, UnionType):\n        return list(typ.items)\n    elif isinstance(typ, Overloaded):\n        # Note: doing 'return typ.items()' makes mypy\n        # infer a too-specific return type of List[CallableType]\n        return list(typ.items)\n    else:\n        return [typ]\n\n\ndef is_enum_overlapping_union(x: ProperType, y: ProperType) -> bool:\n    \"\"\"Return True if x is an Enum, and y is an Union with at least one Literal from x\"\"\"\n    return (\n        isinstance(x, Instance)\n        and x.type.is_enum\n        and isinstance(y, UnionType)\n        and any(\n            isinstance(p := get_proper_type(z), LiteralType) and x.type == p.fallback.type\n            for z in y.relevant_items()\n        )\n    )\n\n\ndef is_literal_in_union(x: ProperType, y: ProperType) -> bool:\n    \"\"\"Return True if x is a Literal and y is an Union that includes x\"\"\"\n    return (\n        isinstance(x, LiteralType)\n        and isinstance(y, UnionType)\n        and any(x == get_proper_type(z) for z in y.items)\n    )\n\n\ndef is_object(t: ProperType) -> bool:\n    return isinstance(t, Instance) and t.type.fullname == \"builtins.object\"\n\n\ndef is_none_object_overlap(t1: ProperType, t2: ProperType) -> bool:\n    return (\n        isinstance(t1, NoneType)\n        and isinstance(t2, Instance)\n        and t2.type.fullname == \"builtins.object\"\n    )\n\n\ndef are_related_types(\n    left: Type, right: Type, *, proper_subtype: bool, ignore_promotions: bool\n) -> bool:\n    if proper_subtype:\n        return is_proper_subtype(\n            left, right, ignore_promotions=ignore_promotions\n        ) or is_proper_subtype(right, left, ignore_promotions=ignore_promotions)\n    else:\n        return is_subtype(left, right, ignore_promotions=ignore_promotions) or is_subtype(\n            right, left, ignore_promotions=ignore_promotions\n        )\n\n\ndef is_overlapping_types(\n    left: Type,\n    right: Type,\n    ignore_promotions: bool = False,\n    overlap_for_overloads: bool = False,\n    seen_types: set[tuple[Type, Type]] | None = None,\n) -> bool:\n    \"\"\"Can a value of type 'left' also be of type 'right' or vice-versa?\n\n    If 'ignore_promotions' is True, we ignore promotions while checking for overlaps.\n    If 'overlap_for_overloads' is True, we check for overlaps more strictly (to avoid false\n    positives), for example: None only overlaps with explicitly optional types, Any\n    doesn't overlap with anything except object, we don't ignore positional argument names.\n    \"\"\"\n    if isinstance(left, TypeGuardedType) or isinstance(right, TypeGuardedType):\n        # A type guard forces the new type even if it doesn't overlap the old.\n        return True\n\n    if seen_types is None:\n        seen_types = set()\n    elif (left, right) in seen_types:\n        return True\n    if is_recursive_pair(left, right):\n        seen_types.add((left, right))\n\n    left, right = get_proper_types((left, right))\n\n    # We should never encounter this type.\n    if isinstance(left, PartialType) or isinstance(right, PartialType):\n        assert False, \"Unexpectedly encountered partial type\"\n\n    # We should also never encounter these types, but it's possible a few\n    # have snuck through due to unrelated bugs. For now, we handle these\n    # in the same way we handle 'Any'.\n    #\n    # TODO: Replace these with an 'assert False' once we are more confident.\n    illegal_types = (UnboundType, ErasedType, DeletedType)\n    if isinstance(left, illegal_types) or isinstance(right, illegal_types):\n        return True\n\n    # When running under non-strict optional mode, simplify away types of\n    # the form 'Union[A, B, C, None]' into just 'Union[A, B, C]'.\n\n    if not state.strict_optional:\n        if isinstance(left, UnionType):\n            left = UnionType.make_union(left.relevant_items())\n        if isinstance(right, UnionType):\n            right = UnionType.make_union(right.relevant_items())\n        left, right = get_proper_types((left, right))\n\n    # 'Any' may or may not be overlapping with the other type\n    if isinstance(left, AnyType) or isinstance(right, AnyType):\n        return not overlap_for_overloads or is_object(left) or is_object(right)\n\n    # We check for complete overlaps next as a general-purpose failsafe.\n    # If this check fails, we start checking to see if there exists a\n    # *partial* overlap between types.\n    #\n    # These checks will also handle the NoneType and UninhabitedType cases for us.\n\n    # enums are sometimes expanded into an Union of Literals\n    # when that happens we want to make sure we treat the two as overlapping\n    # and crucially, we want to do that *fast* in case the enum is large\n    # so we do it before expanding variants below to avoid O(n**2) behavior\n    if (\n        is_enum_overlapping_union(left, right)\n        or is_enum_overlapping_union(right, left)\n        or is_literal_in_union(left, right)\n        or is_literal_in_union(right, left)\n    ):\n        return True\n\n    if overlap_for_overloads:\n        if is_none_object_overlap(left, right) or is_none_object_overlap(right, left):\n            return False\n\n    if are_related_types(\n        left, right, proper_subtype=overlap_for_overloads, ignore_promotions=ignore_promotions\n    ):\n        return True\n\n    # See the docstring for 'get_possible_variants' for more info on what the\n    # following lines are doing.\n\n    left_possible = get_possible_variants(left)\n    right_possible = get_possible_variants(right)\n\n    # Now move on to checking multi-variant types like Unions. We also perform\n    # the same logic if either type happens to be a TypeVar/ParamSpec/TypeVarTuple.\n    #\n    # Handling the TypeVarLikes now lets us simulate having them bind to the corresponding\n    # type -- if we deferred these checks, the \"return-early\" logic of the other\n    # checks will prevent us from detecting certain overlaps.\n    #\n    # If both types are singleton variants (and are not TypeVarLikes), we've hit the base case:\n    # we skip these checks to avoid infinitely recursing.\n\n    def _is_overlapping_types(left: Type, right: Type) -> bool:\n        \"\"\"Encode the kind of overlapping check to perform.\n\n        This function mostly exists, so we don't have to repeat keyword arguments everywhere.\n        \"\"\"\n        return is_overlapping_types(\n            left,\n            right,\n            ignore_promotions=ignore_promotions,\n            overlap_for_overloads=overlap_for_overloads,\n            seen_types=seen_types.copy(),\n        )\n\n    if (\n        len(left_possible) > 1\n        or len(right_possible) > 1\n        or isinstance(left, TypeVarLikeType)\n        or isinstance(right, TypeVarLikeType)\n    ):\n        for l in left_possible:\n            for r in right_possible:\n                if _is_overlapping_types(l, r):\n                    return True\n        return False\n\n    # Now that we've finished handling TypeVarLikes, we're free to end early\n    # if one one of the types is None and we're running in strict-optional mode.\n    # (None only overlaps with None in strict-optional mode).\n    #\n    # We must perform this check after the TypeVarLike checks because\n    # a TypeVar could be bound to None, for example.\n\n    if state.strict_optional and isinstance(left, NoneType) != isinstance(right, NoneType):\n        return False\n\n    # Next, we handle single-variant types that may be inherently partially overlapping:\n    #\n    # - TypedDicts\n    # - Tuples\n    #\n    # If we cannot identify a partial overlap and end early, we degrade these two types\n    # into their 'Instance' fallbacks.\n\n    if isinstance(left, TypedDictType) and isinstance(right, TypedDictType):\n        return are_typed_dicts_overlapping(left, right, _is_overlapping_types)\n    elif typed_dict_mapping_pair(left, right):\n        # Overlaps between TypedDicts and Mappings require dedicated logic.\n        return typed_dict_mapping_overlap(left, right, overlapping=_is_overlapping_types)\n    elif isinstance(left, TypedDictType):\n        left = left.fallback\n    elif isinstance(right, TypedDictType):\n        right = right.fallback\n\n    if is_tuple(left) and is_tuple(right):\n        return are_tuples_overlapping(left, right, _is_overlapping_types)\n    elif isinstance(left, TupleType):\n        left = tuple_fallback(left)\n    elif isinstance(right, TupleType):\n        right = tuple_fallback(right)\n\n    # Next, we handle single-variant types that cannot be inherently partially overlapping,\n    # but do require custom logic to inspect.\n    #\n    # As before, we degrade into 'Instance' whenever possible.\n\n    if isinstance(left, TypeType) and isinstance(right, TypeType):\n        return _is_overlapping_types(left.item, right.item)\n\n    if isinstance(left, TypeType) or isinstance(right, TypeType):\n\n        def _type_object_overlap(left: Type, right: Type) -> bool:\n            \"\"\"Special cases for type object types overlaps.\"\"\"\n            # TODO: these checks are a bit in gray area, adjust if they cause problems.\n            left, right = get_proper_types((left, right))\n            # 1. Type[C] vs Callable[..., C] overlap even if the latter is not class object.\n            if isinstance(left, TypeType) and isinstance(right, CallableType):\n                return _is_overlapping_types(left.item, right.ret_type)\n            # 2. Type[C] vs Meta, where Meta is a metaclass for C.\n            if isinstance(left, TypeType) and isinstance(right, Instance):\n                if isinstance(left.item, Instance):\n                    left_meta = left.item.type.metaclass_type\n                    if left_meta is not None:\n                        return _is_overlapping_types(left_meta, right)\n                    # builtins.type (default metaclass) overlaps with all metaclasses\n                    return right.type.has_base(\"builtins.type\")\n                elif isinstance(left.item, AnyType):\n                    return right.type.has_base(\"builtins.type\")\n            # 3. Callable[..., C] vs Meta is considered below, when we switch to fallbacks.\n            return False\n\n        return _type_object_overlap(left, right) or _type_object_overlap(right, left)\n\n    if isinstance(left, Parameters) and isinstance(right, Parameters):\n        return are_parameters_compatible(\n            left,\n            right,\n            is_compat=_is_overlapping_types,\n            is_proper_subtype=False,\n            ignore_pos_arg_names=not overlap_for_overloads,\n            allow_partial_overlap=True,\n        )\n    # A `Parameters` does not overlap with anything else, however\n    if isinstance(left, Parameters) or isinstance(right, Parameters):\n        return False\n\n    if isinstance(left, CallableType) and isinstance(right, CallableType):\n        return is_callable_compatible(\n            left,\n            right,\n            is_compat=_is_overlapping_types,\n            is_proper_subtype=False,\n            ignore_pos_arg_names=not overlap_for_overloads,\n            allow_partial_overlap=True,\n        )\n\n    call = None\n    other = None\n    if isinstance(left, CallableType) and isinstance(right, Instance):\n        call = find_member(\"__call__\", right, right, is_operator=True)\n        other = left\n    if isinstance(right, CallableType) and isinstance(left, Instance):\n        call = find_member(\"__call__\", left, left, is_operator=True)\n        other = right\n    if isinstance(get_proper_type(call), FunctionLike):\n        assert call is not None and other is not None\n        return _is_overlapping_types(call, other)\n\n    if isinstance(left, CallableType):\n        left = left.fallback\n    if isinstance(right, CallableType):\n        right = right.fallback\n\n    if isinstance(left, LiteralType) and isinstance(right, LiteralType):\n        if left.value == right.value:\n            # If values are the same, we still need to check if fallbacks are overlapping,\n            # this is done below.\n            left = left.fallback\n            right = right.fallback\n        else:\n            return False\n    elif isinstance(left, LiteralType):\n        left = left.fallback\n    elif isinstance(right, LiteralType):\n        right = right.fallback\n\n    # Finally, we handle the case where left and right are instances.\n\n    if isinstance(left, Instance) and isinstance(right, Instance):\n        # First we need to handle promotions and structural compatibility for instances\n        # that came as fallbacks, so simply call is_subtype() to avoid code duplication.\n        if are_related_types(\n            left, right, proper_subtype=overlap_for_overloads, ignore_promotions=ignore_promotions\n        ):\n            return True\n\n        if right.type.fullname == \"builtins.int\" and left.type.fullname in MYPYC_NATIVE_INT_NAMES:\n            return True\n\n        # Two unrelated types cannot be partially overlapping: they're disjoint.\n        if left.type.has_base(right.type.fullname):\n            left = map_instance_to_supertype(left, right.type)\n        elif right.type.has_base(left.type.fullname):\n            right = map_instance_to_supertype(right, left.type)\n        else:\n            return False\n\n        if right.type.has_type_var_tuple_type:\n            # Similar to subtyping, we delegate the heavy lifting to the tuple overlap.\n            assert right.type.type_var_tuple_prefix is not None\n            assert right.type.type_var_tuple_suffix is not None\n            prefix = right.type.type_var_tuple_prefix\n            suffix = right.type.type_var_tuple_suffix\n            tvt = right.type.defn.type_vars[prefix]\n            assert isinstance(tvt, TypeVarTupleType)\n            fallback = tvt.tuple_fallback\n            left_prefix, left_middle, left_suffix = split_with_prefix_and_suffix(\n                left.args, prefix, suffix\n            )\n            right_prefix, right_middle, right_suffix = split_with_prefix_and_suffix(\n                right.args, prefix, suffix\n            )\n            left_args = left_prefix + (TupleType(list(left_middle), fallback),) + left_suffix\n            right_args = right_prefix + (TupleType(list(right_middle), fallback),) + right_suffix\n        else:\n            left_args = left.args\n            right_args = right.args\n        if len(left_args) == len(right_args):\n            # Note: we don't really care about variance here, since the overlapping check\n            # is symmetric and since we want to return 'True' even for partial overlaps.\n            #\n            # For example, suppose we have two types Wrapper[Parent] and Wrapper[Child].\n            # It doesn't matter whether Wrapper is covariant or contravariant since\n            # either way, one of the two types will overlap with the other.\n            #\n            # Similarly, if Wrapper was invariant, the two types could still be partially\n            # overlapping -- what if Wrapper[Parent] happened to contain only instances of\n            # specifically Child?\n            #\n            # Or, to use a more concrete example, List[Union[A, B]] and List[Union[B, C]]\n            # would be considered partially overlapping since it's possible for both lists\n            # to contain only instances of B at runtime.\n            if all(\n                _is_overlapping_types(left_arg, right_arg)\n                for left_arg, right_arg in zip(left_args, right_args)\n            ):\n                return True\n\n        return False\n\n    # We ought to have handled every case by now: we conclude the\n    # two types are not overlapping, either completely or partially.\n    #\n    # Note: it's unclear however, whether returning False is the right thing\n    # to do when inferring reachability -- see  https://github.com/python/mypy/issues/5529\n\n    assert type(left) != type(right), f\"{type(left)} vs {type(right)}\"\n    return False\n\n\ndef is_overlapping_erased_types(\n    left: Type, right: Type, *, ignore_promotions: bool = False\n) -> bool:\n    \"\"\"The same as 'is_overlapping_erased_types', except the types are erased first.\"\"\"\n    return is_overlapping_types(\n        erase_type(left), erase_type(right), ignore_promotions=ignore_promotions\n    )\n\n\ndef are_typed_dicts_overlapping(\n    left: TypedDictType, right: TypedDictType, is_overlapping: Callable[[Type, Type], bool]\n) -> bool:\n    \"\"\"Returns 'true' if left and right are overlapping TypeDictTypes.\"\"\"\n    # All required keys in left are present and overlapping with something in right\n    for key in left.required_keys:\n        if key not in right.items:\n            return False\n        if not is_overlapping(left.items[key], right.items[key]):\n            return False\n\n    # Repeat check in the other direction\n    for key in right.required_keys:\n        if key not in left.items:\n            return False\n        if not is_overlapping(left.items[key], right.items[key]):\n            return False\n\n    # The presence of any additional optional keys does not affect whether the two\n    # TypedDicts are partially overlapping: the dicts would be overlapping if the\n    # keys happened to be missing.\n    return True\n\n\ndef are_tuples_overlapping(\n    left: Type, right: Type, is_overlapping: Callable[[Type, Type], bool]\n) -> bool:\n    \"\"\"Returns true if left and right are overlapping tuples.\"\"\"\n    left, right = get_proper_types((left, right))\n    left = adjust_tuple(left, right) or left\n    right = adjust_tuple(right, left) or right\n    assert isinstance(left, TupleType), f\"Type {left} is not a tuple\"\n    assert isinstance(right, TupleType), f\"Type {right} is not a tuple\"\n\n    # This algorithm works well if only one tuple is variadic, if both are\n    # variadic we may get rare false negatives for overlapping prefix/suffix.\n    # Also, this ignores empty unpack case, but it is probably consistent with\n    # how we handle e.g. empty lists in overload overlaps.\n    # TODO: write a more robust algorithm for cases where both types are variadic.\n    left_unpack = find_unpack_in_list(left.items)\n    right_unpack = find_unpack_in_list(right.items)\n    if left_unpack is not None:\n        left = expand_tuple_if_possible(left, len(right.items))\n    if right_unpack is not None:\n        right = expand_tuple_if_possible(right, len(left.items))\n\n    if len(left.items) != len(right.items):\n        return False\n    if not all(is_overlapping(l, r) for l, r in zip(left.items, right.items)):\n        return False\n\n    # Check that the tuples aren't from e.g. different NamedTuples.\n    if is_named_instance(right.partial_fallback, \"builtins.tuple\") or is_named_instance(\n        left.partial_fallback, \"builtins.tuple\"\n    ):\n        return True\n    else:\n        return is_overlapping(left.partial_fallback, right.partial_fallback)\n\n\ndef expand_tuple_if_possible(tup: TupleType, target: int) -> TupleType:\n    if len(tup.items) > target + 1:\n        return tup\n    extra = target + 1 - len(tup.items)\n    new_items = []\n    for it in tup.items:\n        if not isinstance(it, UnpackType):\n            new_items.append(it)\n            continue\n        unpacked = get_proper_type(it.type)\n        if isinstance(unpacked, TypeVarTupleType):\n            instance = unpacked.tuple_fallback\n        else:\n            # Nested non-variadic tuples should be normalized at this point.\n            assert isinstance(unpacked, Instance)\n            instance = unpacked\n        assert instance.type.fullname == \"builtins.tuple\"\n        new_items.extend([instance.args[0]] * extra)\n    return tup.copy_modified(items=new_items)\n\n\ndef adjust_tuple(left: ProperType, r: ProperType) -> TupleType | None:\n    \"\"\"Find out if `left` is a Tuple[A, ...], and adjust its length to `right`\"\"\"\n    if isinstance(left, Instance) and left.type.fullname == \"builtins.tuple\":\n        n = r.length() if isinstance(r, TupleType) else 1\n        return TupleType([left.args[0]] * n, left)\n    return None\n\n\ndef is_tuple(typ: Type) -> bool:\n    typ = get_proper_type(typ)\n    return isinstance(typ, TupleType) or (\n        isinstance(typ, Instance) and typ.type.fullname == \"builtins.tuple\"\n    )\n\n\nclass TypeMeetVisitor(TypeVisitor[ProperType]):\n    def __init__(self, s: ProperType) -> None:\n        self.s = s\n\n    def visit_unbound_type(self, t: UnboundType) -> ProperType:\n        if isinstance(self.s, NoneType):\n            if state.strict_optional:\n                return UninhabitedType()\n            else:\n                return self.s\n        elif isinstance(self.s, UninhabitedType):\n            return self.s\n        else:\n            return AnyType(TypeOfAny.special_form)\n\n    def visit_any(self, t: AnyType) -> ProperType:\n        return self.s\n\n    def visit_union_type(self, t: UnionType) -> ProperType:\n        if isinstance(self.s, UnionType):\n            meets: list[Type] = []\n            for x in t.items:\n                for y in self.s.items:\n                    meets.append(meet_types(x, y))\n        else:\n            meets = [meet_types(x, self.s) for x in t.items]\n        return make_simplified_union(meets)\n\n    def visit_none_type(self, t: NoneType) -> ProperType:\n        if state.strict_optional:\n            if isinstance(self.s, NoneType) or (\n                isinstance(self.s, Instance) and self.s.type.fullname == \"builtins.object\"\n            ):\n                return t\n            else:\n                return UninhabitedType()\n        else:\n            return t\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> ProperType:\n        return t\n\n    def visit_deleted_type(self, t: DeletedType) -> ProperType:\n        if isinstance(self.s, NoneType):\n            if state.strict_optional:\n                return t\n            else:\n                return self.s\n        elif isinstance(self.s, UninhabitedType):\n            return self.s\n        else:\n            return t\n\n    def visit_erased_type(self, t: ErasedType) -> ProperType:\n        return self.s\n\n    def visit_type_var(self, t: TypeVarType) -> ProperType:\n        if isinstance(self.s, TypeVarType) and self.s.id == t.id:\n            if self.s.upper_bound == t.upper_bound:\n                return self.s\n            return self.s.copy_modified(upper_bound=self.meet(self.s.upper_bound, t.upper_bound))\n        else:\n            return self.default(self.s)\n\n    def visit_param_spec(self, t: ParamSpecType) -> ProperType:\n        if self.s == t:\n            return self.s\n        else:\n            return self.default(self.s)\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> ProperType:\n        if isinstance(self.s, TypeVarTupleType) and self.s.id == t.id:\n            return self.s if self.s.min_len > t.min_len else t\n        else:\n            return self.default(self.s)\n\n    def visit_unpack_type(self, t: UnpackType) -> ProperType:\n        raise NotImplementedError\n\n    def visit_parameters(self, t: Parameters) -> ProperType:\n        if isinstance(self.s, Parameters):\n            if len(t.arg_types) != len(self.s.arg_types):\n                return self.default(self.s)\n            from mypy.join import join_types\n\n            return t.copy_modified(\n                arg_types=[join_types(s_a, t_a) for s_a, t_a in zip(self.s.arg_types, t.arg_types)]\n            )\n        else:\n            return self.default(self.s)\n\n    def visit_instance(self, t: Instance) -> ProperType:\n        if isinstance(self.s, Instance):\n            if t.type == self.s.type:\n                if is_subtype(t, self.s) or is_subtype(self.s, t):\n                    # Combine type arguments. We could have used join below\n                    # equivalently.\n                    args: list[Type] = []\n                    # N.B: We use zip instead of indexing because the lengths might have\n                    # mismatches during daemon reprocessing.\n                    if t.type.has_type_var_tuple_type:\n                        # We handle meet of variadic instances by simply creating correct mapping\n                        # for type arguments and compute the individual meets same as for regular\n                        # instances. All the heavy lifting is done in the meet of tuple types.\n                        s = self.s\n                        assert s.type.type_var_tuple_prefix is not None\n                        assert s.type.type_var_tuple_suffix is not None\n                        prefix = s.type.type_var_tuple_prefix\n                        suffix = s.type.type_var_tuple_suffix\n                        tvt = s.type.defn.type_vars[prefix]\n                        assert isinstance(tvt, TypeVarTupleType)\n                        fallback = tvt.tuple_fallback\n                        s_prefix, s_middle, s_suffix = split_with_prefix_and_suffix(\n                            s.args, prefix, suffix\n                        )\n                        t_prefix, t_middle, t_suffix = split_with_prefix_and_suffix(\n                            t.args, prefix, suffix\n                        )\n                        s_args = s_prefix + (TupleType(list(s_middle), fallback),) + s_suffix\n                        t_args = t_prefix + (TupleType(list(t_middle), fallback),) + t_suffix\n                    else:\n                        t_args = t.args\n                        s_args = self.s.args\n                    for ta, sa, tv in zip(t_args, s_args, t.type.defn.type_vars):\n                        meet = self.meet(ta, sa)\n                        if isinstance(tv, TypeVarTupleType):\n                            # Correctly unpack possible outcomes of meets of tuples: it can be\n                            # either another tuple type or Never (normalized as *tuple[Never, ...])\n                            if isinstance(meet, TupleType):\n                                args.extend(meet.items)\n                                continue\n                            else:\n                                assert isinstance(meet, UninhabitedType)\n                                meet = UnpackType(tv.tuple_fallback.copy_modified(args=[meet]))\n                        args.append(meet)\n                    return Instance(t.type, args)\n                else:\n                    if state.strict_optional:\n                        return UninhabitedType()\n                    else:\n                        return NoneType()\n            else:\n                alt_promote = t.type.alt_promote\n                if alt_promote and alt_promote.type is self.s.type:\n                    return t\n                alt_promote = self.s.type.alt_promote\n                if alt_promote and alt_promote.type is t.type:\n                    return self.s\n                if is_subtype(t, self.s):\n                    return t\n                elif is_subtype(self.s, t):\n                    # See also above comment.\n                    return self.s\n                else:\n                    if state.strict_optional:\n                        return UninhabitedType()\n                    else:\n                        return NoneType()\n        elif isinstance(self.s, FunctionLike) and t.type.is_protocol:\n            call = join.unpack_callback_protocol(t)\n            if call:\n                return meet_types(call, self.s)\n        elif isinstance(self.s, FunctionLike) and self.s.is_type_obj() and t.type.is_metaclass():\n            if is_subtype(self.s.fallback, t):\n                return self.s\n            return self.default(self.s)\n        elif isinstance(self.s, TypeType):\n            return meet_types(t, self.s)\n        elif isinstance(self.s, TupleType):\n            return meet_types(t, self.s)\n        elif isinstance(self.s, LiteralType):\n            return meet_types(t, self.s)\n        elif isinstance(self.s, TypedDictType):\n            return meet_types(t, self.s)\n        return self.default(self.s)\n\n    def visit_callable_type(self, t: CallableType) -> ProperType:\n        if isinstance(self.s, CallableType) and join.is_similar_callables(t, self.s):\n            if is_equivalent(t, self.s):\n                return join.combine_similar_callables(t, self.s)\n            result = meet_similar_callables(t, self.s)\n            # We set the from_type_type flag to suppress error when a collection of\n            # concrete class objects gets inferred as their common abstract superclass.\n            if not (\n                (t.is_type_obj() and t.type_object().is_abstract)\n                or (self.s.is_type_obj() and self.s.type_object().is_abstract)\n            ):\n                result.from_type_type = True\n            if isinstance(get_proper_type(result.ret_type), UninhabitedType):\n                # Return a plain None or <uninhabited> instead of a weird function.\n                return self.default(self.s)\n            return result\n        elif isinstance(self.s, TypeType) and t.is_type_obj() and not t.is_generic():\n            # In this case we are able to potentially produce a better meet.\n            res = meet_types(self.s.item, t.ret_type)\n            if not isinstance(res, (NoneType, UninhabitedType)):\n                return TypeType.make_normalized(res)\n            return self.default(self.s)\n        elif isinstance(self.s, Instance) and self.s.type.is_protocol:\n            call = join.unpack_callback_protocol(self.s)\n            if call:\n                return meet_types(t, call)\n        return self.default(self.s)\n\n    def visit_overloaded(self, t: Overloaded) -> ProperType:\n        # TODO: Implement a better algorithm that covers at least the same cases\n        # as TypeJoinVisitor.visit_overloaded().\n        s = self.s\n        if isinstance(s, FunctionLike):\n            if s.items == t.items:\n                return Overloaded(t.items)\n            elif is_subtype(s, t):\n                return s\n            elif is_subtype(t, s):\n                return t\n            else:\n                return meet_types(t.fallback, s.fallback)\n        elif isinstance(self.s, Instance) and self.s.type.is_protocol:\n            call = join.unpack_callback_protocol(self.s)\n            if call:\n                return meet_types(t, call)\n        return meet_types(t.fallback, s)\n\n    def meet_tuples(self, s: TupleType, t: TupleType) -> list[Type] | None:\n        \"\"\"Meet two tuple types while handling variadic entries.\n\n        This is surprisingly tricky, and we don't handle some tricky corner cases.\n        Most of the trickiness comes from the variadic tuple items like *tuple[X, ...]\n        since they can have arbitrary partial overlaps (while *Ts can't be split). This\n        function is roughly a mirror of join_tuples() w.r.t. to the fact that fixed\n        tuples are subtypes of variadic ones but not vice versa.\n        \"\"\"\n        s_unpack_index = find_unpack_in_list(s.items)\n        t_unpack_index = find_unpack_in_list(t.items)\n        if s_unpack_index is None and t_unpack_index is None:\n            if s.length() == t.length():\n                items: list[Type] = []\n                for i in range(t.length()):\n                    items.append(self.meet(t.items[i], s.items[i]))\n                return items\n            return None\n        if s_unpack_index is not None and t_unpack_index is not None:\n            # The only simple case we can handle if both tuples are variadic\n            # is when their structure fully matches. Other cases are tricky because\n            # a variadic item is effectively a union of tuples of all length, thus\n            # potentially causing overlap between a suffix in `s` and a prefix\n            # in `t` (see how this is handled in is_subtype() for details).\n            # TODO: handle more cases (like when both prefix/suffix are shorter in s or t).\n            if s.length() == t.length() and s_unpack_index == t_unpack_index:\n                unpack_index = s_unpack_index\n                s_unpack = s.items[unpack_index]\n                assert isinstance(s_unpack, UnpackType)\n                s_unpacked = get_proper_type(s_unpack.type)\n                t_unpack = t.items[unpack_index]\n                assert isinstance(t_unpack, UnpackType)\n                t_unpacked = get_proper_type(t_unpack.type)\n                if not (isinstance(s_unpacked, Instance) and isinstance(t_unpacked, Instance)):\n                    return None\n                meet = self.meet(s_unpacked, t_unpacked)\n                if not isinstance(meet, Instance):\n                    return None\n                m_prefix: list[Type] = []\n                for si, ti in zip(s.items[:unpack_index], t.items[:unpack_index]):\n                    m_prefix.append(meet_types(si, ti))\n                m_suffix: list[Type] = []\n                for si, ti in zip(s.items[unpack_index + 1 :], t.items[unpack_index + 1 :]):\n                    m_suffix.append(meet_types(si, ti))\n                return m_prefix + [UnpackType(meet)] + m_suffix\n            return None\n        if s_unpack_index is not None:\n            variadic = s\n            unpack_index = s_unpack_index\n            fixed = t\n        else:\n            assert t_unpack_index is not None\n            variadic = t\n            unpack_index = t_unpack_index\n            fixed = s\n        # If one tuple is variadic one, and the other one is fixed, the meet will be fixed.\n        unpack = variadic.items[unpack_index]\n        assert isinstance(unpack, UnpackType)\n        unpacked = get_proper_type(unpack.type)\n        if not isinstance(unpacked, Instance):\n            return None\n        if fixed.length() < variadic.length() - 1:\n            return None\n        prefix_len = unpack_index\n        suffix_len = variadic.length() - prefix_len - 1\n        prefix, middle, suffix = split_with_prefix_and_suffix(\n            tuple(fixed.items), prefix_len, suffix_len\n        )\n        items = []\n        for fi, vi in zip(prefix, variadic.items[:prefix_len]):\n            items.append(self.meet(fi, vi))\n        for mi in middle:\n            items.append(self.meet(mi, unpacked.args[0]))\n        if suffix_len:\n            for fi, vi in zip(suffix, variadic.items[-suffix_len:]):\n                items.append(self.meet(fi, vi))\n        return items\n\n    def visit_tuple_type(self, t: TupleType) -> ProperType:\n        if isinstance(self.s, TupleType):\n            items = self.meet_tuples(self.s, t)\n            if items is None:\n                return self.default(self.s)\n            # TODO: What if the fallbacks are different?\n            return TupleType(items, tuple_fallback(t))\n        elif isinstance(self.s, Instance):\n            # meet(Tuple[t1, t2, <...>], Tuple[s, ...]) == Tuple[meet(t1, s), meet(t2, s), <...>].\n            if self.s.type.fullname in TUPLE_LIKE_INSTANCE_NAMES and self.s.args:\n                return t.copy_modified(items=[meet_types(it, self.s.args[0]) for it in t.items])\n            elif is_proper_subtype(t, self.s):\n                # A named tuple that inherits from a normal class\n                return t\n            elif self.s.type.has_type_var_tuple_type and is_subtype(t, self.s):\n                # This is a bit ad-hoc but more principled handling is tricky, and this\n                # special case is important for type narrowing in binder to work.\n                return t\n        return self.default(self.s)\n\n    def visit_typeddict_type(self, t: TypedDictType) -> ProperType:\n        if isinstance(self.s, TypedDictType):\n            for name, l, r in self.s.zip(t):\n                if not is_equivalent(l, r) or (name in t.required_keys) != (\n                    name in self.s.required_keys\n                ):\n                    return self.default(self.s)\n            item_list: list[tuple[str, Type]] = []\n            for item_name, s_item_type, t_item_type in self.s.zipall(t):\n                if s_item_type is not None:\n                    item_list.append((item_name, s_item_type))\n                else:\n                    # at least one of s_item_type and t_item_type is not None\n                    assert t_item_type is not None\n                    item_list.append((item_name, t_item_type))\n            items = dict(item_list)\n            fallback = self.s.create_anonymous_fallback()\n            required_keys = t.required_keys | self.s.required_keys\n            readonly_keys = t.readonly_keys | self.s.readonly_keys\n            return TypedDictType(items, required_keys, readonly_keys, fallback)\n        elif isinstance(self.s, Instance) and is_subtype(t, self.s):\n            return t\n        else:\n            return self.default(self.s)\n\n    def visit_literal_type(self, t: LiteralType) -> ProperType:\n        if isinstance(self.s, LiteralType) and self.s == t:\n            return t\n        elif isinstance(self.s, Instance) and is_subtype(t.fallback, self.s):\n            return t\n        else:\n            return self.default(self.s)\n\n    def visit_partial_type(self, t: PartialType) -> ProperType:\n        # We can't determine the meet of partial types. We should never get here.\n        assert False, \"Internal error\"\n\n    def visit_type_type(self, t: TypeType) -> ProperType:\n        if isinstance(self.s, TypeType):\n            typ = self.meet(t.item, self.s.item)\n            if not isinstance(typ, NoneType):\n                typ = TypeType.make_normalized(\n                    typ, line=t.line, is_type_form=self.s.is_type_form and t.is_type_form\n                )\n            return typ\n        elif isinstance(self.s, Instance) and self.s.type.fullname == \"builtins.type\":\n            return t\n        elif isinstance(self.s, CallableType):\n            return self.meet(t, self.s)\n        else:\n            return self.default(self.s)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> ProperType:\n        assert False, f\"This should be never called, got {t}\"\n\n    def meet(self, s: Type, t: Type) -> ProperType:\n        return meet_types(s, t)\n\n    def default(self, typ: Type) -> ProperType:\n        if isinstance(typ, UnboundType):\n            return AnyType(TypeOfAny.special_form)\n        else:\n            if state.strict_optional:\n                return UninhabitedType()\n            else:\n                return NoneType()\n\n\ndef meet_similar_callables(t: CallableType, s: CallableType) -> CallableType:\n    from mypy.join import match_generic_callables, safe_join\n\n    t, s = match_generic_callables(t, s)\n    arg_types: list[Type] = []\n    for i in range(len(t.arg_types)):\n        arg_types.append(safe_join(t.arg_types[i], s.arg_types[i]))\n    # TODO in combine_similar_callables also applies here (names and kinds)\n    # The fallback type can be either 'function' or 'type'. The result should have 'function' as\n    # fallback only if both operands have it as 'function'.\n    if t.fallback.type.fullname != \"builtins.function\":\n        fallback = t.fallback\n    else:\n        fallback = s.fallback\n    return t.copy_modified(\n        arg_types=arg_types,\n        ret_type=meet_types(t.ret_type, s.ret_type),\n        fallback=fallback,\n        name=None,\n    )\n\n\ndef meet_type_list(types: list[Type]) -> Type:\n    if not types:\n        # This should probably be builtins.object but that is hard to get and\n        # it doesn't matter for any current users.\n        return AnyType(TypeOfAny.implementation_artifact)\n    met = types[0]\n    for t in types[1:]:\n        met = meet_types(met, t)\n    return met\n\n\ndef typed_dict_mapping_pair(left: Type, right: Type) -> bool:\n    \"\"\"Is this a pair where one type is a TypedDict and another one is an instance of Mapping?\n\n    This case requires a precise/principled consideration because there are two use cases\n    that push the boundary the opposite ways: we need to avoid spurious overlaps to avoid\n    false positives for overloads, but we also need to avoid spuriously non-overlapping types\n    to avoid false positives with --strict-equality.\n    \"\"\"\n    left, right = get_proper_types((left, right))\n    assert not isinstance(left, TypedDictType) or not isinstance(right, TypedDictType)\n\n    if isinstance(left, TypedDictType):\n        _, other = left, right\n    elif isinstance(right, TypedDictType):\n        _, other = right, left\n    else:\n        return False\n    return isinstance(other, Instance) and other.type.has_base(\"typing.Mapping\")\n\n\ndef typed_dict_mapping_overlap(\n    left: Type, right: Type, overlapping: Callable[[Type, Type], bool]\n) -> bool:\n    \"\"\"Check if a TypedDict type is overlapping with a Mapping.\n\n    The basic logic here consists of two rules:\n\n    * A TypedDict with some required keys is overlapping with Mapping[str, <some type>]\n      if and only if every key type is overlapping with <some type>. For example:\n\n      - TypedDict(x=int, y=str) overlaps with Dict[str, Union[str, int]]\n      - TypedDict(x=int, y=str) doesn't overlap with Dict[str, int]\n\n      Note that any additional non-required keys can't change the above result.\n\n    * A TypedDict with no required keys overlaps with Mapping[str, <some type>] if and\n      only if at least one of key types overlaps with <some type>. For example:\n\n      - TypedDict(x=str, y=str, total=False) overlaps with Dict[str, str]\n      - TypedDict(x=str, y=str, total=False) doesn't overlap with Dict[str, int]\n      - TypedDict(x=int, y=str, total=False) overlaps with Dict[str, str]\n\n    * A TypedDict with at least one ReadOnly[] key does not overlap\n      with Dict or MutableMapping, because they assume mutable data.\n\n    As usual empty, dictionaries lie in a gray area. In general, List[str] and List[str]\n    are considered non-overlapping despite empty list belongs to both. However, List[int]\n    and List[Never] are considered overlapping.\n\n    So here we follow the same logic: a TypedDict with no required keys is considered\n    non-overlapping with Mapping[str, <some type>], but is considered overlapping with\n    Mapping[Never, Never]. This way we avoid false positives for overloads, and also\n    avoid false positives for comparisons like SomeTypedDict == {} under --strict-equality.\n    \"\"\"\n    left, right = get_proper_types((left, right))\n    assert not isinstance(left, TypedDictType) or not isinstance(right, TypedDictType)\n\n    if isinstance(left, TypedDictType):\n        assert isinstance(right, Instance)\n        typed, other = left, right\n    else:\n        assert isinstance(left, Instance)\n        assert isinstance(right, TypedDictType)\n        typed, other = right, left\n\n    mutable_mapping = next(\n        (base for base in other.type.mro if base.fullname == \"typing.MutableMapping\"), None\n    )\n    if mutable_mapping is not None and typed.readonly_keys:\n        return False\n\n    mapping = next(base for base in other.type.mro if base.fullname == \"typing.Mapping\")\n    other = map_instance_to_supertype(other, mapping)\n    key_type, value_type = get_proper_types(other.args)\n\n    # TODO: is there a cleaner way to get str_type here?\n    fallback = typed.create_anonymous_fallback()\n    str_type = fallback.type.bases[0].args[0]  # typing._TypedDict inherits Mapping[str, object]\n\n    # Special case: a TypedDict with no required keys overlaps with an empty dict.\n    if isinstance(key_type, UninhabitedType) and isinstance(value_type, UninhabitedType):\n        return not typed.required_keys\n\n    if typed.required_keys:\n        if not overlapping(key_type, str_type):\n            return False\n        return all(overlapping(typed.items[k], value_type) for k in typed.required_keys)\n    else:\n        if not overlapping(key_type, str_type):\n            return False\n        non_required = set(typed.items.keys()) - typed.required_keys\n        return any(overlapping(typed.items[k], value_type) for k in non_required)\n"
  },
  {
    "path": "mypy/memprofile.py",
    "content": "\"\"\"Utility for dumping memory usage stats.\n\nThis is tailored to mypy and knows (a little) about which list objects are\nowned by particular AST nodes, etc.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport gc\nimport sys\nfrom collections import defaultdict\nfrom collections.abc import Iterable\nfrom typing import cast\n\nfrom mypy.nodes import FakeInfo, Node\nfrom mypy.types import Type\nfrom mypy.util import get_class_descriptors\n\n\ndef collect_memory_stats() -> tuple[dict[str, int], dict[str, int]]:\n    \"\"\"Return stats about memory use.\n\n    Return a tuple with these items:\n      - Dict from object kind to number of instances of that kind\n      - Dict from object kind to total bytes used by all instances of that kind\n    \"\"\"\n    objs = gc.get_objects()\n    find_recursive_objects(objs)\n\n    inferred = {}\n    for obj in objs:\n        if type(obj) is FakeInfo:\n            # Processing these would cause a crash.\n            continue\n        n = type(obj).__name__\n        if hasattr(obj, \"__dict__\"):\n            # Keep track of which class a particular __dict__ is associated with.\n            inferred[id(obj.__dict__)] = f\"{n} (__dict__)\"\n        if isinstance(obj, (Node, Type)):  # type: ignore[misc]\n            if hasattr(obj, \"__dict__\"):\n                for x in obj.__dict__.values():\n                    if isinstance(x, list):\n                        # Keep track of which node a list is associated with.\n                        inferred[id(x)] = f\"{n} (list)\"\n                    if isinstance(x, tuple):\n                        # Keep track of which node a list is associated with.\n                        inferred[id(x)] = f\"{n} (tuple)\"\n\n            for k in get_class_descriptors(type(obj)):\n                x = getattr(obj, k, None)\n                if isinstance(x, list):\n                    inferred[id(x)] = f\"{n} (list)\"\n                if isinstance(x, tuple):\n                    inferred[id(x)] = f\"{n} (tuple)\"\n\n    freqs: dict[str, int] = {}\n    memuse: dict[str, int] = {}\n    for obj in objs:\n        if id(obj) in inferred:\n            name = inferred[id(obj)]\n        else:\n            name = type(obj).__name__\n        freqs[name] = freqs.get(name, 0) + 1\n        memuse[name] = memuse.get(name, 0) + sys.getsizeof(obj)\n\n    return freqs, memuse\n\n\ndef print_memory_profile(run_gc: bool = True) -> None:\n    if not sys.platform.startswith(\"win\"):\n        import resource\n\n        system_memuse = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss\n    else:\n        system_memuse = -1  # TODO: Support this on Windows\n    if run_gc:\n        gc.collect()\n    freqs, memuse = collect_memory_stats()\n    print(\"%7s  %7s  %7s  %s\" % (\"Freq\", \"Size(k)\", \"AvgSize\", \"Type\"))\n    print(\"-------------------------------------------\")\n    totalmem = 0\n    i = 0\n    for n, mem in sorted(memuse.items(), key=lambda x: -x[1]):\n        f = freqs[n]\n        if i < 50:\n            print(\"%7d  %7d  %7.0f  %s\" % (f, mem // 1024, mem / f, n))\n        i += 1\n        totalmem += mem\n    print()\n    print(\"Mem usage RSS   \", system_memuse // 1024)\n    print(\"Total reachable \", totalmem // 1024)\n\n\ndef find_recursive_objects(objs: list[object]) -> None:\n    \"\"\"Find additional objects referenced by objs and append them to objs.\n\n    We use this since gc.get_objects() does not return objects without pointers\n    in them such as strings.\n    \"\"\"\n    seen = {id(o) for o in objs}\n\n    def visit(o: object) -> None:\n        if id(o) not in seen:\n            objs.append(o)\n            seen.add(id(o))\n\n    for obj in objs.copy():\n        if type(obj) is FakeInfo:\n            # Processing these would cause a crash.\n            continue\n        if type(obj) in (dict, defaultdict):\n            for key, val in cast(dict[object, object], obj).items():\n                visit(key)\n                visit(val)\n        if type(obj) in (list, tuple, set):\n            for x in cast(Iterable[object], obj):\n                visit(x)\n        if hasattr(obj, \"__slots__\"):\n            for base in type.mro(type(obj)):\n                for slot in getattr(base, \"__slots__\", ()):\n                    if hasattr(obj, slot):\n                        visit(getattr(obj, slot))\n"
  },
  {
    "path": "mypy/message_registry.py",
    "content": "\"\"\"Message constants for generating error messages during type checking.\n\nLiteral messages should be defined as constants in this module so they won't get out of sync\nif used in more than one place, and so that they can be easily introspected. These messages are\nultimately consumed by messages.MessageBuilder.fail(). For more non-trivial message generation,\nadd a method to MessageBuilder and call this instead.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final, NamedTuple\n\nfrom mypy import errorcodes as codes\nfrom mypy.errorcodes import ErrorCode\n\n\nclass ErrorMessage(NamedTuple):\n    value: str\n    code: ErrorCode | None = None\n\n    def format(self, *args: object, **kwargs: object) -> ErrorMessage:\n        return ErrorMessage(self.value.format(*args, **kwargs), code=self.code)\n\n    def with_additional_msg(self, info: str) -> ErrorMessage:\n        return ErrorMessage(self.value + info, code=self.code)\n\n\n# Invalid types\nINVALID_TYPE_RAW_ENUM_VALUE: Final = ErrorMessage(\n    \"Invalid type: try using Literal[{}.{}] instead?\", codes.VALID_TYPE\n)\n\n# Type checker error message constants\nNO_RETURN_VALUE_EXPECTED: Final = ErrorMessage(\"No return value expected\", codes.RETURN_VALUE)\nMISSING_RETURN_STATEMENT: Final = ErrorMessage(\"Missing return statement\", codes.RETURN)\nEMPTY_BODY_ABSTRACT: Final = ErrorMessage(\n    \"If the method is meant to be abstract, use @abc.abstractmethod\", codes.EMPTY_BODY\n)\nINVALID_IMPLICIT_RETURN: Final = ErrorMessage(\"Implicit return in function which does not return\")\nINCOMPATIBLE_RETURN_VALUE_TYPE: Final = ErrorMessage(\n    \"Incompatible return value type\", codes.RETURN_VALUE\n)\nRETURN_VALUE_EXPECTED: Final = ErrorMessage(\"Return value expected\", codes.RETURN_VALUE)\nNO_RETURN_EXPECTED: Final = ErrorMessage(\"Return statement in function which does not return\")\nINVALID_EXCEPTION: Final = ErrorMessage(\"Exception must be derived from BaseException\")\nINVALID_EXCEPTION_TYPE: Final = ErrorMessage(\n    \"Exception type must be derived from BaseException (or be a tuple of exception classes)\"\n)\nINVALID_EXCEPTION_GROUP: Final = ErrorMessage(\n    \"Exception type in except* cannot derive from BaseExceptionGroup\"\n)\nRETURN_IN_ASYNC_GENERATOR: Final = ErrorMessage(\n    '\"return\" with value in async generator is not allowed'\n)\nINVALID_RETURN_TYPE_FOR_GENERATOR: Final = ErrorMessage(\n    'The return type of a generator function should be \"Generator\" or one of its supertypes'\n)\nINVALID_RETURN_TYPE_FOR_ASYNC_GENERATOR: Final = ErrorMessage(\n    'The return type of an async generator function should be \"AsyncGenerator\" or one of its '\n    \"supertypes\"\n)\nYIELD_VALUE_EXPECTED: Final = ErrorMessage(\"Yield value expected\")\nINCOMPATIBLE_TYPES: Final = ErrorMessage(\"Incompatible types\")\nINCOMPATIBLE_TYPES_IN_ASSIGNMENT: Final = ErrorMessage(\n    \"Incompatible types in assignment\", code=codes.ASSIGNMENT\n)\nCOVARIANT_OVERRIDE_OF_MUTABLE_ATTRIBUTE: Final = ErrorMessage(\n    \"Covariant override of a mutable attribute\", code=codes.MUTABLE_OVERRIDE\n)\nINCOMPATIBLE_TYPES_IN_AWAIT: Final = ErrorMessage('Incompatible types in \"await\"')\nINCOMPATIBLE_REDEFINITION: Final = ErrorMessage(\"Incompatible redefinition\")\nINCOMPATIBLE_TYPES_IN_ASYNC_WITH_AENTER: Final = (\n    'Incompatible types in \"async with\" for \"__aenter__\"'\n)\nINCOMPATIBLE_TYPES_IN_ASYNC_WITH_AEXIT: Final = (\n    'Incompatible types in \"async with\" for \"__aexit__\"'\n)\nINCOMPATIBLE_TYPES_IN_ASYNC_FOR: Final = 'Incompatible types in \"async for\"'\nINVALID_TYPE_FOR_SLOTS: Final = 'Invalid type for \"__slots__\"'\n\nASYNC_FOR_OUTSIDE_COROUTINE: Final = '\"async for\" outside async function'\nASYNC_WITH_OUTSIDE_COROUTINE: Final = '\"async with\" outside async function'\n\nINCOMPATIBLE_TYPES_IN_YIELD: Final = ErrorMessage('Incompatible types in \"yield\"')\nINCOMPATIBLE_TYPES_IN_YIELD_FROM: Final = ErrorMessage('Incompatible types in \"yield from\"')\nINCOMPATIBLE_TYPES_IN_STR_INTERPOLATION: Final = \"Incompatible types in string interpolation\"\nINCOMPATIBLE_TYPES_IN_CAPTURE: Final = ErrorMessage(\"Incompatible types in capture pattern\")\nMUST_HAVE_NONE_RETURN_TYPE: Final = ErrorMessage('The return type of \"{}\" must be None')\nTUPLE_INDEX_OUT_OF_RANGE: Final = ErrorMessage(\"Tuple index out of range\")\nAMBIGUOUS_SLICE_OF_VARIADIC_TUPLE: Final = ErrorMessage(\"Ambiguous slice of a variadic tuple\")\nTOO_MANY_TARGETS_FOR_VARIADIC_UNPACK: Final = ErrorMessage(\n    \"Too many assignment targets for variadic unpack\"\n)\nINVALID_SLICE_INDEX: Final = ErrorMessage(\"Slice index must be an integer, SupportsIndex or None\")\nCANNOT_INFER_LAMBDA_TYPE: Final = ErrorMessage(\"Cannot infer type of lambda\")\nCANNOT_ACCESS_INIT: Final = (\n    'Accessing \"__init__\" on an instance is unsound, since instance.__init__ could be from'\n    \" an incompatible subclass\"\n)\nNON_INSTANCE_NEW_TYPE: Final = ErrorMessage('\"__new__\" must return a class instance (got {})')\nINVALID_NEW_TYPE: Final = ErrorMessage('Incompatible return type for \"__new__\"')\nBAD_CONSTRUCTOR_TYPE: Final = ErrorMessage(\"Unsupported decorated constructor type\")\nCANNOT_ASSIGN_TO_METHOD: Final = \"Cannot assign to a method\"\nCANNOT_ASSIGN_TO_TYPE: Final = \"Cannot assign to a type\"\nINCONSISTENT_ABSTRACT_OVERLOAD: Final = ErrorMessage(\n    \"Overloaded method has both abstract and non-abstract variants\"\n)\nMULTIPLE_OVERLOADS_REQUIRED: Final = ErrorMessage(\"Single overload definition, multiple required\")\nREAD_ONLY_PROPERTY_OVERRIDES_READ_WRITE: Final = ErrorMessage(\n    \"Read-only property cannot override read-write property\"\n)\nFORMAT_REQUIRES_MAPPING: Final = \"Format requires a mapping\"\nRETURN_TYPE_CANNOT_BE_CONTRAVARIANT: Final = ErrorMessage(\n    \"Cannot use a contravariant type variable as return type\"\n)\nFUNCTION_PARAMETER_CANNOT_BE_COVARIANT: Final = ErrorMessage(\n    \"Cannot use a covariant type variable as a parameter\"\n)\nINCOMPATIBLE_IMPORT_OF: Final = ErrorMessage('Incompatible import of \"{}\"', code=codes.ASSIGNMENT)\nFUNCTION_TYPE_EXPECTED: Final = ErrorMessage(\n    \"Function is missing a type annotation\", codes.NO_UNTYPED_DEF\n)\nONLY_CLASS_APPLICATION: Final = ErrorMessage(\n    \"Type application is only supported for generic classes\"\n)\nRETURN_TYPE_EXPECTED: Final = ErrorMessage(\n    \"Function is missing a return type annotation\", codes.NO_UNTYPED_DEF\n)\nPARAM_TYPE_EXPECTED: Final = ErrorMessage(\n    \"Function is missing a type annotation for one or more parameters\", codes.NO_UNTYPED_DEF\n)\nKEYWORD_ARGUMENT_REQUIRES_STR_KEY_TYPE: Final = ErrorMessage(\n    'Keyword argument only valid with \"str\" key type in call to \"dict\"'\n)\nALL_MUST_BE_SEQ_STR: Final = ErrorMessage(\"Type of __all__ must be {}, not {}\")\nINVALID_TYPEDDICT_ARGS: Final = ErrorMessage(\n    \"Expected keyword arguments, {...}, or dict(...) in TypedDict constructor\"\n)\nTYPEDDICT_KEY_MUST_BE_STRING_LITERAL: Final = ErrorMessage(\n    \"Expected TypedDict key to be string literal\"\n)\nTYPEDDICT_OVERRIDE_MERGE: Final = 'Overwriting TypedDict field \"{}\" while merging'\nMALFORMED_ASSERT: Final = ErrorMessage(\"Assertion is always true, perhaps remove parentheses?\")\nDUPLICATE_TYPE_SIGNATURES: Final = ErrorMessage(\"Function has duplicate type signatures\")\nDESCRIPTOR_SET_NOT_CALLABLE: Final = ErrorMessage(\"{}.__set__ is not callable\")\nDESCRIPTOR_GET_NOT_CALLABLE: Final = \"{}.__get__ is not callable\"\nMODULE_LEVEL_GETATTRIBUTE: Final = ErrorMessage(\n    \"__getattribute__ is not valid at the module level\"\n)\nCLASS_VAR_CONFLICTS_SLOTS: Final = '\"{}\" in __slots__ conflicts with class variable access'\nNAME_NOT_IN_SLOTS: Final = ErrorMessage(\n    'Trying to assign name \"{}\" that is not in \"__slots__\" of type \"{}\"'\n)\nTYPE_ALWAYS_TRUE: Final = ErrorMessage(\n    \"{} which does not implement __bool__ or __len__ \"\n    \"so it could always be true in boolean context\",\n    code=codes.TRUTHY_BOOL,\n)\nTYPE_ALWAYS_TRUE_UNIONTYPE: Final = ErrorMessage(\n    \"{} of which no members implement __bool__ or __len__ \"\n    \"so it could always be true in boolean context\",\n    code=codes.TRUTHY_BOOL,\n)\nFUNCTION_ALWAYS_TRUE: Final = ErrorMessage(\n    \"Function {} could always be true in boolean context\", code=codes.TRUTHY_FUNCTION\n)\nITERABLE_ALWAYS_TRUE: Final = ErrorMessage(\n    \"{} which can always be true in boolean context. Consider using {} instead.\",\n    code=codes.TRUTHY_ITERABLE,\n)\nNOT_CALLABLE: Final = \"{} not callable\"\nTYPE_MUST_BE_USED: Final = \"Value of type {} must be used\"\n\n# Generic\nGENERIC_INSTANCE_VAR_CLASS_ACCESS: Final = (\n    \"Access to generic instance variables via class is ambiguous\"\n)\nGENERIC_CLASS_VAR_ACCESS: Final = \"Access to generic class variables is ambiguous\"\nBARE_GENERIC: Final = \"Missing type arguments for generic type {}\"\nIMPLICIT_GENERIC_ANY_BUILTIN: Final = (\n    'Implicit generic \"Any\". Use \"{}\" and specify generic parameters'\n)\nINVALID_UNPACK: Final = \"{} cannot be unpacked (must be tuple or TypeVarTuple)\"\nINVALID_UNPACK_POSITION: Final = \"Unpack is only valid in a variadic position\"\nINVALID_PARAM_SPEC_LOCATION: Final = \"Invalid location for ParamSpec {}\"\nINVALID_PARAM_SPEC_LOCATION_NOTE: Final = (\n    'You can use ParamSpec as the first argument to Callable, e.g., \"Callable[{}, int]\"'\n)\n\n# TypeVar\nINCOMPATIBLE_TYPEVAR_VALUE: Final = 'Value of type variable \"{}\" of {} cannot be {}'\nINVALID_TYPEVAR_AS_TYPEARG: Final = 'Type variable \"{}\" not valid as type argument value for \"{}\"'\nINVALID_TYPEVAR_ARG_BOUND: Final = 'Type argument {} of \"{}\" must be a subtype of {}'\nINVALID_TYPEVAR_ARG_VALUE: Final = 'Invalid type argument value for \"{}\"'\nTYPEVAR_VARIANCE_DEF: Final = 'TypeVar \"{}\" may only be a literal bool'\nTYPEVAR_ARG_MUST_BE_TYPE: Final = '{} \"{}\" must be a type'\nTYPEVAR_UNEXPECTED_ARGUMENT: Final = 'Unexpected argument to \"TypeVar()\"'\nUNBOUND_TYPEVAR: Final = (\n    \"A function returning TypeVar should receive at least one argument containing the same TypeVar\"\n)\nTYPE_PARAMETERS_SHOULD_BE_DECLARED: Final = (\n    \"All type parameters should be declared ({} not declared)\"\n)\n\n# Super\nTOO_MANY_ARGS_FOR_SUPER: Final = ErrorMessage('Too many arguments for \"super\"')\nSUPER_WITH_SINGLE_ARG_NOT_SUPPORTED: Final = ErrorMessage(\n    '\"super\" with a single argument not supported'\n)\nUNSUPPORTED_ARG_1_FOR_SUPER: Final = ErrorMessage('Unsupported argument 1 for \"super\"')\nUNSUPPORTED_ARG_2_FOR_SUPER: Final = ErrorMessage('Unsupported argument 2 for \"super\"')\nSUPER_VARARGS_NOT_SUPPORTED: Final = ErrorMessage('Varargs not supported with \"super\"')\nSUPER_POSITIONAL_ARGS_REQUIRED: Final = ErrorMessage('\"super\" only accepts positional arguments')\nSUPER_ARG_2_NOT_INSTANCE_OF_ARG_1: Final = ErrorMessage(\n    'Argument 2 for \"super\" not an instance of argument 1'\n)\nTARGET_CLASS_HAS_NO_BASE_CLASS: Final = ErrorMessage(\"Target class has no base class\")\nSUPER_OUTSIDE_OF_METHOD_NOT_SUPPORTED: Final = ErrorMessage(\n    '\"super()\" outside of a method is not supported'\n)\nSUPER_ENCLOSING_POSITIONAL_ARGS_REQUIRED: Final = ErrorMessage(\n    '\"super()\" requires one or two positional arguments in enclosing function'\n)\n\n# Self-type\nMISSING_OR_INVALID_SELF_TYPE: Final = ErrorMessage(\n    '\"self\" parameter missing for a non-static method (or an invalid type for self)'\n)\nERASED_SELF_TYPE_NOT_SUPERTYPE: Final = ErrorMessage(\n    'The erased type of self \"{}\" is not a supertype of its class \"{}\"'\n)\n\n# Final\nCANNOT_INHERIT_FROM_FINAL: Final = ErrorMessage('Cannot inherit from final class \"{}\"')\nDEPENDENT_FINAL_IN_CLASS_BODY: Final = ErrorMessage(\n    \"Final name declared in class body cannot depend on type variables\"\n)\nCANNOT_ACCESS_FINAL_INSTANCE_ATTR: Final = (\n    'Cannot access final instance attribute \"{}\" on class object'\n)\nCANNOT_ACCESS_INSTANCE_ONLY_ATTR: Final = (\n    'Cannot access instance-only attribute \"{}\" on class object'\n)\nCANNOT_MAKE_DELETABLE_FINAL: Final = ErrorMessage(\"Deletable attribute cannot be final\")\n\n# Disjoint bases\nINCOMPATIBLE_DISJOINT_BASES: Final = ErrorMessage('Class \"{}\" has incompatible disjoint bases')\n\n# Enum\nENUM_MEMBERS_ATTR_WILL_BE_OVERRIDDEN: Final = ErrorMessage(\n    'Assigned \"__members__\" will be overridden by \"Enum\" internally'\n)\n\n# ClassVar\nCANNOT_OVERRIDE_INSTANCE_VAR: Final = ErrorMessage(\n    'Cannot override instance variable (previously declared on base class \"{}\") with class '\n    \"variable\"\n)\nCANNOT_OVERRIDE_CLASS_VAR: Final = ErrorMessage(\n    'Cannot override class variable (previously declared on base class \"{}\") with instance '\n    \"variable\"\n)\nCLASS_VAR_WITH_GENERIC_SELF: Final = \"ClassVar cannot contain Self type in generic classes\"\nCLASS_VAR_OUTSIDE_OF_CLASS: Final = \"ClassVar can only be used for assignments in class body\"\n\n# Protocol\nRUNTIME_PROTOCOL_EXPECTED: Final = ErrorMessage(\n    \"Only @runtime_checkable protocols can be used with instance and class checks\"\n)\nCANNOT_INSTANTIATE_PROTOCOL: Final = ErrorMessage('Cannot instantiate protocol class \"{}\"')\nTOO_MANY_UNION_COMBINATIONS: Final = ErrorMessage(\n    \"Not all union combinations were tried because there are too many unions\"\n)\n\nCONTIGUOUS_ITERABLE_EXPECTED: Final = ErrorMessage(\"Contiguous iterable with same type expected\")\nITERABLE_TYPE_EXPECTED: Final = ErrorMessage(\"Invalid type '{}' for *expr (iterable expected)\")\nTYPE_GUARD_POS_ARG_REQUIRED: Final = ErrorMessage(\"Type {} requires positional argument\")\n\n# Match Statement\nMISSING_MATCH_ARGS: Final = 'Class \"{}\" doesn\\'t define \"__match_args__\"'\nOR_PATTERN_ALTERNATIVE_NAMES: Final = \"Alternative patterns bind different names\"\nCLASS_PATTERN_GENERIC_TYPE_ALIAS: Final = (\n    \"Class pattern class must not be a type alias with type parameters\"\n)\nCLASS_PATTERN_TYPE_REQUIRED: Final = 'Expected type in class pattern; found \"{}\"'\nCLASS_PATTERN_TOO_MANY_POSITIONAL_ARGS: Final = \"Too many positional patterns for class pattern\"\nCLASS_PATTERN_KEYWORD_MATCHES_POSITIONAL: Final = (\n    'Keyword \"{}\" already matches a positional pattern'\n)\nCLASS_PATTERN_DUPLICATE_KEYWORD_PATTERN: Final = 'Duplicate keyword pattern \"{}\"'\nCLASS_PATTERN_UNKNOWN_KEYWORD: Final = 'Class \"{}\" has no attribute \"{}\"'\nCLASS_PATTERN_CLASS_OR_STATIC_METHOD: Final = \"Cannot have both classmethod and staticmethod\"\nMULTIPLE_ASSIGNMENTS_IN_PATTERN: Final = 'Multiple assignments to name \"{}\" in pattern'\nCANNOT_MODIFY_MATCH_ARGS: Final = 'Cannot assign to \"__match_args__\"'\n\nDATACLASS_FIELD_ALIAS_MUST_BE_LITERAL: Final = (\n    '\"alias\" argument to dataclass field must be a string literal'\n)\nDATACLASS_POST_INIT_MUST_BE_A_FUNCTION: Final = '\"__post_init__\" method must be an instance method'\n\n# fastparse\nFAILED_TO_MERGE_OVERLOADS: Final = ErrorMessage(\n    \"Condition can't be inferred, unable to merge overloads\"\n)\nTYPE_IGNORE_WITH_ERRCODE_ON_MODULE: Final = ErrorMessage(\n    \"Type ignore with error code is not supported for modules; \"\n    'use `# mypy: disable-error-code=\"{}\"`',\n    codes.SYNTAX,\n)\nINVALID_TYPE_IGNORE: Final = ErrorMessage('Invalid \"type: ignore\" comment', codes.SYNTAX)\nTYPE_COMMENT_SYNTAX_ERROR_VALUE: Final = ErrorMessage(\n    'Syntax error in type comment \"{}\"', codes.SYNTAX\n)\nELLIPSIS_WITH_OTHER_TYPEPARAMS: Final = ErrorMessage(\n    \"Ellipses cannot accompany other parameter types in function type signature\", codes.SYNTAX\n)\nTYPE_SIGNATURE_TOO_MANY_PARAMS: Final = ErrorMessage(\n    \"Type signature has too many parameters\", codes.SYNTAX\n)\nTYPE_SIGNATURE_TOO_FEW_PARAMS: Final = ErrorMessage(\n    \"Type signature has too few parameters\", codes.SYNTAX\n)\nARG_CONSTRUCTOR_NAME_EXPECTED: Final = ErrorMessage(\"Expected arg constructor name\", codes.SYNTAX)\nARG_CONSTRUCTOR_TOO_MANY_ARGS: Final = ErrorMessage(\n    \"Too many arguments for argument constructor\", codes.SYNTAX\n)\nMULTIPLE_VALUES_FOR_NAME_KWARG: Final = ErrorMessage(\n    '\"{}\" gets multiple values for keyword argument \"name\"', codes.SYNTAX\n)\nMULTIPLE_VALUES_FOR_TYPE_KWARG: Final = ErrorMessage(\n    '\"{}\" gets multiple values for keyword argument \"type\"', codes.SYNTAX\n)\nARG_CONSTRUCTOR_UNEXPECTED_ARG: Final = ErrorMessage(\n    'Unexpected argument \"{}\" for argument constructor', codes.SYNTAX\n)\nARG_NAME_EXPECTED_STRING_LITERAL: Final = ErrorMessage(\n    \"Expected string literal for argument name, got {}\", codes.SYNTAX\n)\nNARROWED_TYPE_NOT_SUBTYPE: Final = ErrorMessage(\n    \"Narrowed type {} is not a subtype of input type {}\", codes.NARROWED_TYPE_NOT_SUBTYPE\n)\nTYPE_VAR_TOO_FEW_CONSTRAINED_TYPES: Final = ErrorMessage(\n    \"Type variable must have at least two constrained types\", codes.MISC\n)\n\nTYPE_VAR_YIELD_EXPRESSION_IN_BOUND: Final = ErrorMessage(\n    \"Yield expression cannot be used as a type variable bound\", codes.SYNTAX\n)\n\nTYPE_VAR_NAMED_EXPRESSION_IN_BOUND: Final = ErrorMessage(\n    \"Named expression cannot be used as a type variable bound\", codes.SYNTAX\n)\n\nTYPE_VAR_AWAIT_EXPRESSION_IN_BOUND: Final = ErrorMessage(\n    \"Await expression cannot be used as a type variable bound\", codes.SYNTAX\n)\n\nTYPE_VAR_GENERIC_CONSTRAINT_TYPE: Final = ErrorMessage(\n    \"TypeVar constraint type cannot be parametrized by type variables\", codes.MISC\n)\n\nTYPE_VAR_REDECLARED_IN_NESTED_CLASS: Final = ErrorMessage(\n    'Type variable \"{}\" is bound by an outer class', codes.VALID_TYPE\n)\n\nTYPE_ALIAS_WITH_YIELD_EXPRESSION: Final = ErrorMessage(\n    \"Yield expression cannot be used within a type alias\", codes.SYNTAX\n)\n\nTYPE_ALIAS_WITH_NAMED_EXPRESSION: Final = ErrorMessage(\n    \"Named expression cannot be used within a type alias\", codes.SYNTAX\n)\n\nTYPE_ALIAS_WITH_AWAIT_EXPRESSION: Final = ErrorMessage(\n    \"Await expression cannot be used within a type alias\", codes.SYNTAX\n)\n"
  },
  {
    "path": "mypy/messages.py",
    "content": "\"\"\"Facilities for generating error messages during type checking.\n\nDon't add any non-trivial message construction logic to the type\nchecker, as it can compromise clarity and make messages less\nconsistent. Add such logic to this module instead. Literal messages, including those\nwith format args, should be defined as constants in mypy.message_registry.\n\nHistorically we tried to avoid all message string literals in the type\nchecker but we are moving away from this convention.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport difflib\nimport itertools\nimport re\nfrom collections.abc import Callable, Collection, Iterable, Iterator, Sequence\nfrom contextlib import contextmanager\nfrom textwrap import dedent\nfrom typing import Any, Final, cast\n\nimport mypy.typeops\nfrom mypy import errorcodes as codes, message_registry\nfrom mypy.erasetype import erase_type\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.errors import (\n    ErrorInfo,\n    Errors,\n    ErrorWatcher,\n    IterationDependentErrors,\n    IterationErrorWatcher,\n    NonOverlapErrorInfo,\n)\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_NAMED_OPT,\n    ARG_OPT,\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    CONTRAVARIANT,\n    COVARIANT,\n    SYMBOL_FUNCBASE_TYPES,\n    ArgKind,\n    CallExpr,\n    Context,\n    Expression,\n    FuncDef,\n    IndexExpr,\n    MypyFile,\n    NameExpr,\n    ReturnStmt,\n    StrExpr,\n    SymbolNode,\n    SymbolTable,\n    TypeInfo,\n    Var,\n    get_func_def,\n    reverse_builtin_aliases,\n)\nfrom mypy.operators import op_methods, op_methods_to_symbols\nfrom mypy.options import Options\nfrom mypy.subtypes import (\n    IS_CLASS_OR_STATIC,\n    IS_CLASSVAR,\n    IS_EXPLICIT_SETTER,\n    IS_SETTABLE,\n    IS_VAR,\n    find_member,\n    get_member_flags,\n    is_same_type,\n    is_subtype,\n)\nfrom mypy.typeops import separate_union_literals\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    DeletedType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeStrVisitor,\n    TypeType,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    flatten_nested_unions,\n    get_proper_type,\n    get_proper_types,\n)\nfrom mypy.typetraverser import TypeTraverserVisitor\nfrom mypy.util import plural_s, unmangle\n\nTYPES_FOR_UNIMPORTED_HINTS: Final = {\n    \"typing.Any\",\n    \"typing.Callable\",\n    \"typing.Dict\",\n    \"typing.Iterable\",\n    \"typing.Iterator\",\n    \"typing.List\",\n    \"typing.Optional\",\n    \"typing.Set\",\n    \"typing.Tuple\",\n    \"typing.TypeVar\",\n    \"typing.Union\",\n    \"typing.cast\",\n}\n\n\nARG_CONSTRUCTOR_NAMES: Final = {\n    ARG_POS: \"Arg\",\n    ARG_OPT: \"DefaultArg\",\n    ARG_NAMED: \"NamedArg\",\n    ARG_NAMED_OPT: \"DefaultNamedArg\",\n    ARG_STAR: \"VarArg\",\n    ARG_STAR2: \"KwArg\",\n}\n\n\n# Map from the full name of a missing definition to the test fixture (under\n# test-data/unit/fixtures/) that provides the definition. This is used for\n# generating better error messages when running mypy tests only.\nSUGGESTED_TEST_FIXTURES: Final = {\n    \"builtins.set\": \"set.pyi\",\n    \"builtins.tuple\": \"tuple.pyi\",\n    \"builtins.bool\": \"bool.pyi\",\n    \"builtins.Exception\": \"exception.pyi\",\n    \"builtins.BaseException\": \"exception.pyi\",\n    \"builtins.isinstance\": \"isinstancelist.pyi\",\n    \"builtins.property\": \"property.pyi\",\n    \"builtins.classmethod\": \"classmethod.pyi\",\n    \"typing._SpecialForm\": \"typing-medium.pyi\",\n}\n\nUNSUPPORTED_NUMBERS_TYPES: Final = {\n    \"numbers.Number\",\n    \"numbers.Complex\",\n    \"numbers.Real\",\n    \"numbers.Rational\",\n    \"numbers.Integral\",\n}\n\nMAX_TUPLE_ITEMS = 10\nMAX_UNION_ITEMS = 10\n\n\nclass MessageBuilder:\n    \"\"\"Helper class for reporting type checker error messages with parameters.\n\n    The methods of this class need to be provided with the context within a\n    file; the errors member manages the wider context.\n\n    IDEA: Support a 'verbose mode' that includes full information about types\n          in error messages and that may otherwise produce more detailed error\n          messages.\n    \"\"\"\n\n    # Report errors using this instance. It knows about the current file and\n    # import context.\n    errors: Errors\n\n    modules: dict[str, MypyFile]\n\n    # Hack to deduplicate error messages from union types\n    _disable_type_names: list[bool]\n\n    def __init__(self, errors: Errors, modules: dict[str, MypyFile]) -> None:\n        self.errors = errors\n        self.options = errors.options\n        self.modules = modules\n        self._disable_type_names = []\n\n    #\n    # Helpers\n    #\n\n    def filter_errors(\n        self,\n        *,\n        filter_errors: bool | Callable[[str, ErrorInfo], bool] = True,\n        save_filtered_errors: bool = False,\n        filter_deprecated: bool = False,\n        filter_revealed_type: bool = False,\n    ) -> ErrorWatcher:\n        return ErrorWatcher(\n            self.errors,\n            filter_errors=filter_errors,\n            save_filtered_errors=save_filtered_errors,\n            filter_deprecated=filter_deprecated,\n            filter_revealed_type=filter_revealed_type,\n        )\n\n    def add_errors(self, errors: list[ErrorInfo]) -> None:\n        \"\"\"Add errors in messages to this builder.\"\"\"\n        for info in errors:\n            self.errors.add_error_info(info)\n\n    @contextmanager\n    def disable_type_names(self) -> Iterator[None]:\n        self._disable_type_names.append(True)\n        try:\n            yield\n        finally:\n            self._disable_type_names.pop()\n\n    def are_type_names_disabled(self) -> bool:\n        return len(self._disable_type_names) > 0 and self._disable_type_names[-1]\n\n    def prefer_simple_messages(self) -> bool:\n        \"\"\"Should we generate simple/fast error messages?\n\n        If errors aren't shown to the user, we don't want to waste cycles producing\n        complex error messages.\n        \"\"\"\n        return self.errors.prefer_simple_messages()\n\n    def span_from_context(self, ctx: Context) -> Iterable[int]:\n        \"\"\"This determines where a type: ignore for a given context has effect.\"\"\"\n        if not isinstance(ctx, Expression):\n            return [ctx.line]\n        return range(ctx.line, (ctx.end_line or ctx.line) + 1)\n\n    def report(\n        self,\n        msg: str,\n        context: Context,\n        severity: str,\n        offset: int = 0,\n        *,\n        code: ErrorCode | None = None,\n        origin_context: Context | None,\n        parent_error: ErrorInfo | None = None,\n    ) -> ErrorInfo:\n        \"\"\"Report an error or note (unless disabled).\n\n        Note that context controls where error is reported, while origin_context\n        controls where # type: ignore comments have effect.\n        \"\"\"\n\n        origin_span = self.span_from_context(context)\n        if origin_context is not None:\n            origin_span = itertools.chain(origin_span, self.span_from_context(origin_context))\n\n        return self.errors.report(\n            context.line if context else -1,\n            context.column if context else -1,\n            msg,\n            code=code,\n            severity=severity,\n            offset=offset,\n            origin_span=origin_span,\n            end_line=context.end_line if context else -1,\n            end_column=context.end_column if context else -1,\n            parent_error=parent_error,\n        )\n\n    def fail(\n        self,\n        msg: str,\n        context: Context,\n        *,\n        code: ErrorCode | None = None,\n        origin_context: Context | None = None,\n    ) -> ErrorInfo:\n        \"\"\"Report an error message (unless disabled).\"\"\"\n        return self.report(msg, context, \"error\", code=code, origin_context=origin_context)\n\n    def note(\n        self,\n        msg: str,\n        context: Context,\n        offset: int = 0,\n        *,\n        code: ErrorCode | None = None,\n        origin_context: Context | None = None,\n        parent_error: ErrorInfo | None = None,\n    ) -> None:\n        \"\"\"Report a note (unless disabled).\"\"\"\n        self.report(\n            msg,\n            context,\n            \"note\",\n            offset=offset,\n            code=code,\n            origin_context=origin_context,\n            parent_error=parent_error,\n        )\n\n    def note_multiline(\n        self,\n        messages: str,\n        context: Context,\n        offset: int = 0,\n        *,\n        code: ErrorCode | None = None,\n        origin_context: Context | None = None,\n        parent_error: ErrorInfo | None = None,\n    ) -> None:\n        \"\"\"Report as many notes as lines in the message (unless disabled).\"\"\"\n        for msg in dedent(messages.lstrip(\"\\n\")).splitlines():\n            self.report(\n                msg,\n                context,\n                \"note\",\n                offset,\n                code=code,\n                origin_context=origin_context,\n                parent_error=parent_error,\n            )\n\n    #\n    # Specific operations\n    #\n\n    # The following operations are for generating specific error messages. They\n    # get some information as arguments, and they build an error message based\n    # on them.\n\n    def has_no_attr(\n        self,\n        original_type: Type,\n        typ: Type,\n        member: str,\n        context: Context,\n        module_symbol_table: SymbolTable | None = None,\n    ) -> ErrorCode | None:\n        \"\"\"Report a missing or non-accessible member.\n\n        original_type is the top-level type on which the error occurred.\n        typ is the actual type that is missing the member. These can be\n        different, e.g., in a union, original_type will be the union and typ\n        will be the specific item in the union that does not have the member\n        attribute.\n\n        'module_symbol_table' is passed to this function if the type for which we\n        are trying to get a member was originally a module. The SymbolTable allows\n        us to look up and suggests attributes of the module since they are not\n        directly available on original_type\n\n        If member corresponds to an operator, use the corresponding operator\n        name in the messages. Return the error code that was produced, if any.\n        \"\"\"\n        original_type = get_proper_type(original_type)\n        typ = get_proper_type(typ)\n\n        if isinstance(original_type, Instance) and original_type.type.has_readable_member(member):\n            self.fail(f'Member \"{member}\" is not assignable', context)\n            return None\n        elif member == \"__contains__\":\n            self.fail(\n                f\"Unsupported right operand type for in ({format_type(original_type, self.options)})\",\n                context,\n                code=codes.OPERATOR,\n            )\n            return codes.OPERATOR\n        elif member in op_methods.values():\n            # Access to a binary operator member (e.g. _add). This case does\n            # not handle indexing operations.\n            for op, method in op_methods.items():\n                if method == member:\n                    self.unsupported_left_operand(op, original_type, context)\n                    return codes.OPERATOR\n        elif member == \"__neg__\":\n            self.fail(\n                f\"Unsupported operand type for unary - ({format_type(original_type, self.options)})\",\n                context,\n                code=codes.OPERATOR,\n            )\n            return codes.OPERATOR\n        elif member == \"__pos__\":\n            self.fail(\n                f\"Unsupported operand type for unary + ({format_type(original_type, self.options)})\",\n                context,\n                code=codes.OPERATOR,\n            )\n            return codes.OPERATOR\n        elif member == \"__invert__\":\n            self.fail(\n                f\"Unsupported operand type for ~ ({format_type(original_type, self.options)})\",\n                context,\n                code=codes.OPERATOR,\n            )\n            return codes.OPERATOR\n        elif member == \"__getitem__\":\n            # Indexed get.\n            # TODO: Fix this consistently in format_type\n            if isinstance(original_type, FunctionLike) and original_type.is_type_obj():\n                self.fail(\n                    \"The type {} is not generic and not indexable\".format(\n                        format_type(original_type, self.options)\n                    ),\n                    context,\n                )\n                return None\n            else:\n                self.fail(\n                    f\"Value of type {format_type(original_type, self.options)} is not indexable\",\n                    context,\n                    code=codes.INDEX,\n                )\n                return codes.INDEX\n        elif member == \"__setitem__\":\n            # Indexed set.\n            self.fail(\n                \"Unsupported target for indexed assignment ({})\".format(\n                    format_type(original_type, self.options)\n                ),\n                context,\n                code=codes.INDEX,\n            )\n            return codes.INDEX\n        elif member == \"__call__\":\n            if isinstance(original_type, Instance) and (\n                original_type.type.fullname == \"builtins.function\"\n            ):\n                # \"'function' not callable\" is a confusing error message.\n                # Explain that the problem is that the type of the function is not known.\n                self.fail(\"Cannot call function of unknown type\", context, code=codes.OPERATOR)\n                return codes.OPERATOR\n            else:\n                self.fail(\n                    message_registry.NOT_CALLABLE.format(format_type(original_type, self.options)),\n                    context,\n                    code=codes.OPERATOR,\n                )\n                return codes.OPERATOR\n        else:\n            # The non-special case: a missing ordinary attribute.\n            extra = \"\"\n            if member == \"__iter__\":\n                extra = \" (not iterable)\"\n            elif member == \"__aiter__\":\n                extra = \" (not async iterable)\"\n            if not self.are_type_names_disabled():\n                failed = False\n                if isinstance(original_type, Instance) and original_type.type.names:\n                    if (\n                        module_symbol_table is not None\n                        and member in module_symbol_table\n                        and not module_symbol_table[member].module_public\n                    ):\n                        self.fail(\n                            f\"{format_type(original_type, self.options, module_names=True)} does not \"\n                            f'explicitly export attribute \"{member}\"',\n                            context,\n                            code=codes.ATTR_DEFINED,\n                        )\n                        failed = True\n                    else:\n                        alternatives = set(original_type.type.names.keys())\n                        if module_symbol_table is not None:\n                            alternatives |= {\n                                k for k, v in module_symbol_table.items() if v.module_public\n                            }\n                        # Rare but possible, see e.g. testNewAnalyzerCyclicDefinitionCrossModule\n                        alternatives.discard(member)\n\n                        matches = [m for m in COMMON_MISTAKES.get(member, []) if m in alternatives]\n                        matches.extend(best_matches(member, alternatives, n=3))\n                        if member == \"__aiter__\" and matches == [\"__iter__\"]:\n                            matches = []  # Avoid misleading suggestion\n                        if matches:\n                            self.fail(\n                                '{} has no attribute \"{}\"; maybe {}?{}'.format(\n                                    format_type(original_type, self.options),\n                                    member,\n                                    pretty_seq(matches, \"or\"),\n                                    extra,\n                                ),\n                                context,\n                                code=codes.ATTR_DEFINED,\n                            )\n                            failed = True\n                if not failed:\n                    self.fail(\n                        '{} has no attribute \"{}\"{}'.format(\n                            format_type(original_type, self.options), member, extra\n                        ),\n                        context,\n                        code=codes.ATTR_DEFINED,\n                    )\n                return codes.ATTR_DEFINED\n            elif isinstance(original_type, UnionType):\n                # The checker passes \"object\" in lieu of \"None\" for attribute\n                # checks, so we manually convert it back.\n                typ_format, orig_type_format = format_type_distinctly(\n                    typ, original_type, options=self.options\n                )\n                if typ_format == '\"object\"' and any(\n                    type(item) == NoneType for item in original_type.items\n                ):\n                    typ_format = '\"None\"'\n                self.fail(\n                    'Item {} of {} has no attribute \"{}\"{}'.format(\n                        typ_format, orig_type_format, member, extra\n                    ),\n                    context,\n                    code=codes.UNION_ATTR,\n                )\n                return codes.UNION_ATTR\n            elif isinstance(original_type, TypeVarType):\n                bound = get_proper_type(original_type.upper_bound)\n                if isinstance(bound, UnionType):\n                    typ_fmt, bound_fmt = format_type_distinctly(typ, bound, options=self.options)\n                    original_type_fmt = format_type(original_type, self.options)\n                    self.fail(\n                        \"Item {} of the upper bound {} of type variable {} has no \"\n                        'attribute \"{}\"{}'.format(\n                            typ_fmt, bound_fmt, original_type_fmt, member, extra\n                        ),\n                        context,\n                        code=codes.UNION_ATTR,\n                    )\n                    return codes.UNION_ATTR\n            else:\n                self.fail(\n                    '{} has no attribute \"{}\"{}'.format(\n                        format_type(original_type, self.options), member, extra\n                    ),\n                    context,\n                    code=codes.ATTR_DEFINED,\n                )\n                return codes.ATTR_DEFINED\n        return None\n\n    def unsupported_operand_types(\n        self,\n        op: str,\n        left_type: Any,\n        right_type: Any,\n        context: Context,\n        *,\n        code: ErrorCode = codes.OPERATOR,\n    ) -> ErrorInfo:\n        \"\"\"Report unsupported operand types for a binary operation.\n\n        Types can be Type objects or strings.\n        \"\"\"\n        left_str = \"\"\n        if isinstance(left_type, str):\n            left_str = left_type\n        else:\n            left_str = format_type(left_type, self.options)\n\n        right_str = \"\"\n        if isinstance(right_type, str):\n            right_str = right_type\n        else:\n            right_str = format_type(right_type, self.options)\n\n        if self.are_type_names_disabled():\n            msg = f\"Unsupported operand types for {op} (likely involving Union)\"\n        else:\n            msg = f\"Unsupported operand types for {op} ({left_str} and {right_str})\"\n        return self.fail(msg, context, code=code)\n\n    def unsupported_left_operand(self, op: str, typ: Type, context: Context) -> None:\n        if self.are_type_names_disabled():\n            msg = f\"Unsupported left operand type for {op} (some union)\"\n        else:\n            msg = f\"Unsupported left operand type for {op} ({format_type(typ, self.options)})\"\n        self.fail(msg, context, code=codes.OPERATOR)\n\n    def not_callable(self, typ: Type, context: Context) -> Type:\n        self.fail(message_registry.NOT_CALLABLE.format(format_type(typ, self.options)), context)\n        return AnyType(TypeOfAny.from_error)\n\n    def untyped_function_call(self, callee: CallableType, context: Context) -> Type:\n        name = callable_name(callee) or \"(unknown)\"\n        self.fail(\n            f\"Call to untyped function {name} in typed context\",\n            context,\n            code=codes.NO_UNTYPED_CALL,\n        )\n        return AnyType(TypeOfAny.from_error)\n\n    def incompatible_argument(\n        self,\n        n: int,\n        m: int,\n        callee: CallableType,\n        arg_type: Type,\n        arg_kind: ArgKind,\n        object_type: Type | None,\n        context: Context,\n        outer_context: Context,\n    ) -> ErrorInfo:\n        \"\"\"Report an error about an incompatible argument type.\n\n        The argument type is arg_type, argument number is n and the\n        callee type is 'callee'. If the callee represents a method\n        that corresponds to an operator, use the corresponding\n        operator name in the messages.\n\n        Return the error code that used for the argument (multiple error\n        codes are possible).\n        \"\"\"\n        arg_type = get_proper_type(arg_type)\n\n        target = \"\"\n        callee_name = callable_name(callee)\n        if callee_name is not None:\n            name = callee_name\n            if object_type is not None:\n                base = format_type(object_type, self.options)\n            else:\n                base = extract_type(name)\n\n            if name.startswith('\"__getitem__\" of'):\n                return self.invalid_index_type(\n                    arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX\n                )\n            elif name.startswith('\"__setitem__\" of'):\n                if n == 1:\n                    return self.invalid_index_type(\n                        arg_type, callee.arg_types[n - 1], base, context, code=codes.INDEX\n                    )\n                else:\n                    arg_type_str, callee_type_str = format_type_distinctly(\n                        arg_type, callee.arg_types[n - 1], options=self.options\n                    )\n                    info = (\n                        f\" (expression has type {arg_type_str}, target has type {callee_type_str})\"\n                    )\n                    error_msg = (\n                        message_registry.INCOMPATIBLE_TYPES_IN_ASSIGNMENT.with_additional_msg(info)\n                    )\n                    return self.fail(error_msg.value, context, code=error_msg.code)\n            elif name.startswith('\"__'):\n                for method, op in op_methods_to_symbols.items():\n                    for variant in method, \"__r\" + method[2:]:\n                        # FIX: do not rely on textual formatting\n                        if name.startswith(f'\"{variant}\" of'):\n                            if op == \"in\" or variant != method:\n                                # Reversed order of base/argument.\n                                return self.unsupported_operand_types(\n                                    op, arg_type, base, context, code=codes.OPERATOR\n                                )\n                            else:\n                                return self.unsupported_operand_types(\n                                    op, base, arg_type, context, code=codes.OPERATOR\n                                )\n\n            target = f\"to {name} \"\n\n        msg = \"\"\n        code = codes.MISC\n        notes: list[str] = []\n        if callee_name == \"<list>\":\n            name = callee_name[1:-1]\n            n -= 1\n            actual_type_str, expected_type_str = format_type_distinctly(\n                arg_type, callee.arg_types[0], options=self.options\n            )\n            msg = \"{} item {} has incompatible type {}; expected {}\".format(\n                name.title(), n, actual_type_str, expected_type_str\n            )\n            code = codes.LIST_ITEM\n        elif callee_name == \"<dict>\" and isinstance(\n            get_proper_type(callee.arg_types[n - 1]), TupleType\n        ):\n            name = callee_name[1:-1]\n            n -= 1\n            key_type, value_type = cast(TupleType, arg_type).items\n            expected_key_type, expected_value_type = cast(TupleType, callee.arg_types[n]).items\n\n            # don't increase verbosity unless there is need to do so\n            if is_subtype(key_type, expected_key_type):\n                key_type_str = format_type(key_type, self.options)\n                expected_key_type_str = format_type(expected_key_type, self.options)\n            else:\n                key_type_str, expected_key_type_str = format_type_distinctly(\n                    key_type, expected_key_type, options=self.options\n                )\n            if is_subtype(value_type, expected_value_type):\n                value_type_str = format_type(value_type, self.options)\n                expected_value_type_str = format_type(expected_value_type, self.options)\n            else:\n                value_type_str, expected_value_type_str = format_type_distinctly(\n                    value_type, expected_value_type, options=self.options\n                )\n\n            msg = \"{} entry {} has incompatible type {}: {}; expected {}: {}\".format(\n                name.title(),\n                n,\n                key_type_str,\n                value_type_str,\n                expected_key_type_str,\n                expected_value_type_str,\n            )\n            code = codes.DICT_ITEM\n        elif callee_name == \"<dict>\":\n            value_type_str, expected_value_type_str = format_type_distinctly(\n                arg_type, callee.arg_types[n - 1], options=self.options\n            )\n            msg = \"Unpacked dict entry {} has incompatible type {}; expected {}\".format(\n                n - 1, value_type_str, expected_value_type_str\n            )\n            code = codes.DICT_ITEM\n        elif callee_name == \"<list-comprehension>\":\n            actual_type_str, expected_type_str = map(\n                strip_quotes,\n                format_type_distinctly(arg_type, callee.arg_types[0], options=self.options),\n            )\n            msg = \"List comprehension has incompatible type List[{}]; expected List[{}]\".format(\n                actual_type_str, expected_type_str\n            )\n        elif callee_name == \"<set-comprehension>\":\n            actual_type_str, expected_type_str = map(\n                strip_quotes,\n                format_type_distinctly(arg_type, callee.arg_types[0], options=self.options),\n            )\n            msg = \"Set comprehension has incompatible type Set[{}]; expected Set[{}]\".format(\n                actual_type_str, expected_type_str\n            )\n        elif callee_name == \"<dictionary-comprehension>\":\n            actual_type_str, expected_type_str = format_type_distinctly(\n                arg_type, callee.arg_types[n - 1], options=self.options\n            )\n            msg = (\n                \"{} expression in dictionary comprehension has incompatible type {}; \"\n                \"expected type {}\"\n            ).format(\"Key\" if n == 1 else \"Value\", actual_type_str, expected_type_str)\n        elif callee_name == \"<generator>\":\n            actual_type_str, expected_type_str = format_type_distinctly(\n                arg_type, callee.arg_types[0], options=self.options\n            )\n            msg = \"Generator has incompatible item type {}; expected {}\".format(\n                actual_type_str, expected_type_str\n            )\n        else:\n            if self.prefer_simple_messages():\n                msg = \"Argument has incompatible type\"\n            else:\n                try:\n                    expected_type = callee.arg_types[m - 1]\n                except IndexError:  # Varargs callees\n                    expected_type = callee.arg_types[-1]\n                arg_type_str, expected_type_str = format_type_distinctly(\n                    arg_type, expected_type, bare=True, options=self.options\n                )\n                if arg_kind == ARG_STAR:\n                    arg_type_str = \"*\" + arg_type_str\n                elif arg_kind == ARG_STAR2:\n                    arg_type_str = \"**\" + arg_type_str\n\n                # For function calls with keyword arguments, display the argument name rather\n                # than the number.\n                arg_label = str(n)\n                if isinstance(outer_context, CallExpr) and len(outer_context.arg_names) >= n:\n                    arg_name = outer_context.arg_names[n - 1]\n                    if arg_name is not None:\n                        arg_label = f'\"{arg_name}\"'\n                if (\n                    arg_kind == ARG_STAR2\n                    and isinstance(arg_type, TypedDictType)\n                    and m <= len(callee.arg_names)\n                    and callee.arg_names[m - 1] is not None\n                    and callee.arg_kinds[m - 1] != ARG_STAR2\n                ):\n                    arg_name = callee.arg_names[m - 1]\n                    assert arg_name is not None\n                    arg_type_str, expected_type_str = format_type_distinctly(\n                        arg_type.items[arg_name], expected_type, bare=True, options=self.options\n                    )\n                    arg_label = f'\"{arg_name}\"'\n                if isinstance(outer_context, IndexExpr) and isinstance(\n                    outer_context.index, StrExpr\n                ):\n                    msg = 'Value of \"{}\" has incompatible type {}; expected {}'.format(\n                        outer_context.index.value,\n                        quote_type_string(arg_type_str),\n                        quote_type_string(expected_type_str),\n                    )\n                else:\n                    msg = \"Argument {} {}has incompatible type {}; expected {}\".format(\n                        arg_label,\n                        target,\n                        quote_type_string(arg_type_str),\n                        quote_type_string(expected_type_str),\n                    )\n                expected_type = get_proper_type(expected_type)\n                if isinstance(expected_type, UnionType):\n                    expected_types = get_proper_types(expected_type.items)\n                else:\n                    expected_types = [expected_type]\n                for type in expected_types:\n                    if isinstance(arg_type, Instance) and isinstance(type, Instance):\n                        notes = append_invariance_notes(notes, arg_type, type)\n                        notes = append_numbers_notes(notes, arg_type, type)\n            object_type = get_proper_type(object_type)\n            if isinstance(object_type, TypedDictType):\n                code = codes.TYPEDDICT_ITEM\n            else:\n                code = codes.ARG_TYPE\n        error = self.fail(msg, context, code=code)\n        if notes:\n            for note_msg in notes:\n                self.note(note_msg, context, code=code)\n        return error\n\n    def incompatible_argument_note(\n        self,\n        original_caller_type: ProperType,\n        callee_type: ProperType,\n        context: Context,\n        parent_error: ErrorInfo,\n    ) -> None:\n        if self.prefer_simple_messages():\n            return\n        if isinstance(\n            original_caller_type, (Instance, TupleType, TypedDictType, TypeType, CallableType)\n        ):\n            if isinstance(callee_type, Instance) and callee_type.type.is_protocol:\n                self.report_protocol_problems(\n                    original_caller_type, callee_type, context, parent_error=parent_error\n                )\n            if isinstance(callee_type, UnionType):\n                for item in callee_type.items:\n                    item = get_proper_type(item)\n                    if isinstance(item, Instance) and item.type.is_protocol:\n                        self.report_protocol_problems(\n                            original_caller_type, item, context, parent_error=parent_error\n                        )\n        if isinstance(callee_type, CallableType) and isinstance(original_caller_type, Instance):\n            call = find_member(\n                \"__call__\", original_caller_type, original_caller_type, is_operator=True\n            )\n            if call:\n                self.note_call(original_caller_type, call, context, code=parent_error.code)\n        if isinstance(callee_type, Instance) and callee_type.type.is_protocol:\n            call = find_member(\"__call__\", callee_type, callee_type, is_operator=True)\n            if call:\n                self.note_call(callee_type, call, context, code=parent_error.code)\n        self.maybe_note_concatenate_pos_args(\n            original_caller_type, callee_type, context, parent_error.code\n        )\n\n    def maybe_note_concatenate_pos_args(\n        self,\n        original_caller_type: ProperType,\n        callee_type: ProperType,\n        context: Context,\n        code: ErrorCode | None = None,\n    ) -> None:\n        # pos-only vs positional can be confusing, with Concatenate\n        if (\n            isinstance(callee_type, CallableType)\n            and isinstance(original_caller_type, CallableType)\n            and (original_caller_type.from_concatenate or callee_type.from_concatenate)\n        ):\n            names: list[str] = []\n            for c, o in zip(\n                callee_type.formal_arguments(), original_caller_type.formal_arguments()\n            ):\n                if None in (c.pos, o.pos):\n                    # non-positional\n                    continue\n                if c.name != o.name and c.name is None and o.name is not None:\n                    names.append(o.name)\n\n            if names:\n                missing_arguments = '\"' + '\", \"'.join(names) + '\"'\n                self.note(\n                    f'This is likely because \"{original_caller_type.name}\" has named arguments: '\n                    f\"{missing_arguments}. Consider marking them positional-only\",\n                    context,\n                    code=code,\n                )\n\n    def invalid_index_type(\n        self,\n        index_type: Type,\n        expected_type: Type,\n        base_str: str,\n        context: Context,\n        *,\n        code: ErrorCode,\n    ) -> ErrorInfo:\n        index_str, expected_str = format_type_distinctly(\n            index_type, expected_type, options=self.options\n        )\n        return self.fail(\n            \"Invalid index type {} for {}; expected type {}\".format(\n                index_str, base_str, expected_str\n            ),\n            context,\n            code=code,\n        )\n\n    def readonly_keys_mutated(self, keys: set[str], context: Context) -> None:\n        if len(keys) == 1:\n            suffix = \"is\"\n        else:\n            suffix = \"are\"\n        self.fail(\n            \"ReadOnly {} TypedDict {} mutated\".format(format_key_list(sorted(keys)), suffix),\n            code=codes.TYPEDDICT_READONLY_MUTATED,\n            context=context,\n        )\n\n    def too_few_arguments(\n        self, callee: CallableType, context: Context, argument_names: Sequence[str | None] | None\n    ) -> None:\n        if self.prefer_simple_messages():\n            msg = \"Too few arguments\"\n        elif argument_names is not None:\n            num_positional_args = sum(k is None for k in argument_names)\n            arguments_left = callee.arg_names[num_positional_args : callee.min_args]\n            diff = [k for k in arguments_left if k not in argument_names]\n            if len(diff) == 1:\n                msg = \"Missing positional argument\"\n            else:\n                msg = \"Missing positional arguments\"\n            callee_name = callable_name(callee)\n            if callee_name is not None and diff and all(d is not None for d in diff):\n                args = '\", \"'.join(cast(list[str], diff))\n                msg += f' \"{args}\" in call to {callee_name}'\n            else:\n                msg = \"Too few arguments\" + for_function(callee)\n\n        else:\n            msg = \"Too few arguments\" + for_function(callee)\n        self.fail(msg, context, code=codes.CALL_ARG)\n\n    def missing_named_argument(self, callee: CallableType, context: Context, name: str) -> None:\n        msg = f'Missing named argument \"{name}\"' + for_function(callee)\n        self.fail(msg, context, code=codes.CALL_ARG)\n        self.note_defined_here(callee, context)\n\n    def too_many_arguments(self, callee: CallableType, context: Context) -> None:\n        if self.prefer_simple_messages():\n            msg = \"Too many arguments\"\n        else:\n            msg = \"Too many arguments\" + for_function(callee)\n        self.fail(msg, context, code=codes.CALL_ARG)\n        self.maybe_note_about_special_args(callee, context)\n\n    def too_many_arguments_from_typed_dict(\n        self, callee: CallableType, arg_type: TypedDictType, context: Context\n    ) -> None:\n        # Try to determine the name of the extra argument.\n        for key in arg_type.items:\n            if key not in callee.arg_names:\n                msg = f'Extra argument \"{key}\" from **args' + for_function(callee)\n                break\n        else:\n            self.too_many_arguments(callee, context)\n            return\n        self.fail(msg, context)\n\n    def too_many_positional_arguments(self, callee: CallableType, context: Context) -> None:\n        if self.prefer_simple_messages():\n            msg = \"Too many positional arguments\"\n        else:\n            msg = \"Too many positional arguments\" + for_function(callee)\n        self.fail(msg, context)\n        self.maybe_note_about_special_args(callee, context)\n\n    def maybe_note_about_special_args(self, callee: CallableType, context: Context) -> None:\n        if self.prefer_simple_messages():\n            return\n        # https://github.com/python/mypy/issues/11309\n        first_arg = get_first_arg(callee)\n        if first_arg and first_arg not in {\"self\", \"cls\", \"mcs\"}:\n            self.note(\n                \"Looks like the first special argument in a method \"\n                'is not named \"self\", \"cls\", or \"mcs\", '\n                \"maybe it is missing?\",\n                context,\n            )\n\n    def unexpected_keyword_argument_for_function(\n        self, for_func: str, name: str, context: Context, *, matches: list[str] | None = None\n    ) -> None:\n        msg = f'Unexpected keyword argument \"{name}\"' + for_func\n        if matches:\n            msg += f\"; did you mean {pretty_seq(matches, 'or')}?\"\n        self.fail(msg, context, code=codes.CALL_ARG)\n\n    def unexpected_keyword_argument(\n        self, callee: CallableType, name: str, arg_type: Type, context: Context\n    ) -> None:\n        # Suggest intended keyword, look for type match else fallback on any match.\n        matching_type_args = []\n        not_matching_type_args = []\n        for i, kwarg_type in enumerate(callee.arg_types):\n            callee_arg_name = callee.arg_names[i]\n            if callee_arg_name is not None and callee.arg_kinds[i] != ARG_STAR:\n                if is_subtype(arg_type, kwarg_type):\n                    matching_type_args.append(callee_arg_name)\n                else:\n                    not_matching_type_args.append(callee_arg_name)\n        matches = best_matches(name, matching_type_args, n=3)\n        if not matches:\n            matches = best_matches(name, not_matching_type_args, n=3)\n        self.unexpected_keyword_argument_for_function(\n            for_function(callee), name, context, matches=matches\n        )\n        self.note_defined_here(callee, context)\n\n    def note_defined_here(self, callee: CallableType, context: Context) -> None:\n        module = find_defining_module(self.modules, callee)\n        if (\n            module\n            and module.path != self.errors.file\n            and module.fullname not in (\"builtins\", \"typing\")\n        ):\n            assert callee.definition is not None\n            fname = callable_name(callee)\n            if not fname:  # an alias to function with a different name\n                fname = \"Called function\"\n            else:\n                fname = fname.split(\" of \")[0]  # use short method names in the note\n            self.note(f'{fname} defined in \"{module.fullname}\"', context, code=codes.CALL_ARG)\n\n    def duplicate_argument_value(self, callee: CallableType, index: int, context: Context) -> None:\n        self.fail(\n            '{} gets multiple values for keyword argument \"{}\"'.format(\n                callable_name(callee) or \"Function\", callee.arg_names[index]\n            ),\n            context,\n        )\n\n    def does_not_return_value(self, callee_type: Type | None, context: Context) -> None:\n        \"\"\"Report an error about use of an unusable type.\"\"\"\n        callee_type = get_proper_type(callee_type)\n        callee_name = callable_name(callee_type) if isinstance(callee_type, FunctionLike) else None\n        name = callee_name or \"Function\"\n        message = f\"{name} does not return a value (it only ever returns None)\"\n        self.fail(message, context, code=codes.FUNC_RETURNS_VALUE)\n\n    def deleted_as_rvalue(self, typ: DeletedType, context: Context) -> None:\n        \"\"\"Report an error about using an deleted type as an rvalue.\"\"\"\n        if typ.source is None:\n            s = \"\"\n        else:\n            s = f' \"{typ.source}\"'\n        self.fail(f\"Trying to read deleted variable{s}\", context)\n\n    def deleted_as_lvalue(self, typ: DeletedType, context: Context) -> None:\n        \"\"\"Report an error about using an deleted type as an lvalue.\n\n        Currently, this only occurs when trying to assign to an\n        exception variable outside the local except: blocks.\n        \"\"\"\n        if typ.source is None:\n            s = \"\"\n        else:\n            s = f' \"{typ.source}\"'\n        self.fail(f\"Assignment to variable{s} outside except: block\", context)\n\n    def no_variant_matches_arguments(\n        self,\n        overload: Overloaded,\n        arg_types: list[Type],\n        context: Context,\n        *,\n        code: ErrorCode | None = None,\n    ) -> None:\n        code = code or codes.CALL_OVERLOAD\n        name = callable_name(overload)\n        if name:\n            name_str = f\" of {name}\"\n        else:\n            name_str = \"\"\n        arg_types_str = \", \".join(format_type(arg, self.options) for arg in arg_types)\n        num_args = len(arg_types)\n        if num_args == 0:\n            self.fail(\n                f\"All overload variants{name_str} require at least one argument\",\n                context,\n                code=code,\n            )\n        elif num_args == 1:\n            self.fail(\n                f\"No overload variant{name_str} matches argument type {arg_types_str}\",\n                context,\n                code=code,\n            )\n        else:\n            self.fail(\n                f\"No overload variant{name_str} matches argument types {arg_types_str}\",\n                context,\n                code=code,\n            )\n\n        self.note(f\"Possible overload variant{plural_s(len(overload.items))}:\", context, code=code)\n        for item in overload.items:\n            self.note(pretty_callable(item, self.options), context, offset=4, code=code)\n\n    def wrong_number_values_to_unpack(\n        self, provided: int, expected: int, context: Context\n    ) -> None:\n        if provided < expected:\n            if provided == 1:\n                self.fail(f\"Need more than 1 value to unpack ({expected} expected)\", context)\n            else:\n                self.fail(\n                    f\"Need more than {provided} values to unpack ({expected} expected)\", context\n                )\n        elif provided > expected:\n            self.fail(\n                f\"Too many values to unpack ({expected} expected, {provided} provided)\", context\n            )\n\n    def unpacking_strings_disallowed(self, context: Context) -> None:\n        self.fail(\"Unpacking a string is disallowed\", context, code=codes.STR_UNPACK)\n\n    def type_not_iterable(self, type: Type, context: Context) -> None:\n        self.fail(f\"{format_type(type, self.options)} object is not iterable\", context)\n\n    def possible_missing_await(self, context: Context, code: ErrorCode | None) -> None:\n        self.note('Maybe you forgot to use \"await\"?', context, code=code)\n\n    def incompatible_operator_assignment(self, op: str, context: Context) -> None:\n        self.fail(f\"Result type of {op} incompatible in assignment\", context)\n\n    def overload_signature_incompatible_with_supertype(\n        self, name: str, name_in_super: str, supertype: str, context: Context\n    ) -> None:\n        target = self.override_target(name, name_in_super, supertype)\n        self.fail(\n            f'Signature of \"{name}\" incompatible with {target}', context, code=codes.OVERRIDE\n        )\n\n        note_template = 'Overload variants must be defined in the same order as they are in \"{}\"'\n        self.note(note_template.format(supertype), context, code=codes.OVERRIDE)\n\n    def incompatible_setter_override(\n        self, defn: Context, typ: Type, original_type: Type, base: TypeInfo\n    ) -> None:\n        self.fail(\"Incompatible override of a setter type\", defn, code=codes.OVERRIDE)\n        base_str, override_str = format_type_distinctly(original_type, typ, options=self.options)\n        self.note(\n            f' (base class \"{base.name}\" defined the type as {base_str},',\n            defn,\n            code=codes.OVERRIDE,\n        )\n        self.note(f\" override has type {override_str})\", defn, code=codes.OVERRIDE)\n        if is_subtype(typ, original_type):\n            self.note(\" Setter types should behave contravariantly\", defn, code=codes.OVERRIDE)\n\n    def signature_incompatible_with_supertype(\n        self,\n        name: str,\n        name_in_super: str,\n        supertype: str,\n        context: Context,\n        *,\n        original: ProperType,\n        override: ProperType,\n    ) -> None:\n        target = self.override_target(name, name_in_super, supertype)\n        error = self.fail(\n            f'Signature of \"{name}\" incompatible with {target}', context, code=codes.OVERRIDE\n        )\n\n        original_str, override_str = format_type_distinctly(\n            original, override, options=self.options, bare=True\n        )\n\n        INCLUDE_DECORATOR = True  # Include @classmethod and @staticmethod decorators, if any\n        ALIGN_OFFSET = 1  # One space, to account for the difference between error and note\n        OFFSET = 4  # Four spaces, so that notes will look like this:\n        # error: Signature of \"f\" incompatible with supertype \"A\"\n        # note:      Superclass:\n        # note:          def f(self) -> str\n        # note:      Subclass:\n        # note:          def f(self, x: str) -> None\n        self.note(\"Superclass:\", context, offset=ALIGN_OFFSET + OFFSET, parent_error=error)\n        if isinstance(original, (CallableType, Overloaded)):\n            self.pretty_callable_or_overload(\n                original,\n                context,\n                offset=ALIGN_OFFSET + 2 * OFFSET,\n                add_class_or_static_decorator=INCLUDE_DECORATOR,\n                parent_error=error,\n            )\n        else:\n            self.note(original_str, context, offset=ALIGN_OFFSET + 2 * OFFSET, parent_error=error)\n\n        self.note(\"Subclass:\", context, offset=ALIGN_OFFSET + OFFSET, parent_error=error)\n        if isinstance(override, (CallableType, Overloaded)):\n            self.pretty_callable_or_overload(\n                override,\n                context,\n                offset=ALIGN_OFFSET + 2 * OFFSET,\n                add_class_or_static_decorator=INCLUDE_DECORATOR,\n                parent_error=error,\n            )\n        else:\n            self.note(override_str, context, offset=ALIGN_OFFSET + 2 * OFFSET, parent_error=error)\n\n    def pretty_callable_or_overload(\n        self,\n        tp: CallableType | Overloaded,\n        context: Context,\n        *,\n        parent_error: ErrorInfo,\n        offset: int = 0,\n        add_class_or_static_decorator: bool = False,\n    ) -> None:\n        if isinstance(tp, CallableType):\n            if add_class_or_static_decorator:\n                decorator = pretty_class_or_static_decorator(tp)\n                if decorator is not None:\n                    self.note(decorator, context, offset=offset, parent_error=parent_error)\n            self.note(\n                pretty_callable(tp, self.options),\n                context,\n                offset=offset,\n                parent_error=parent_error,\n            )\n        elif isinstance(tp, Overloaded):\n            self.pretty_overload(\n                tp,\n                context,\n                offset,\n                add_class_or_static_decorator=add_class_or_static_decorator,\n                parent_error=parent_error,\n            )\n\n    def argument_incompatible_with_supertype(\n        self,\n        arg_num: int,\n        name: str,\n        type_name: str | None,\n        name_in_supertype: str,\n        arg_type_in_supertype: Type,\n        supertype: str,\n        context: Context,\n        origin_context: Context,\n    ) -> None:\n        target = self.override_target(name, name_in_supertype, supertype)\n        arg_type_in_supertype_f = format_type_bare(arg_type_in_supertype, self.options)\n        self.fail(\n            'Argument {} of \"{}\" is incompatible with {}; '\n            'supertype defines the argument type as \"{}\"'.format(\n                arg_num, name, target, arg_type_in_supertype_f\n            ),\n            context,\n            code=codes.OVERRIDE,\n            origin_context=origin_context,\n        )\n        if name != \"__post_init__\":\n            # `__post_init__` is special, it can be incompatible by design.\n            # So, this note is misleading.\n            invariant_message = \"\"\"\n            This violates the Liskov substitution principle\n            See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n            \"\"\"\n            self.note_multiline(\n                invariant_message, context, code=codes.OVERRIDE, origin_context=origin_context\n            )\n        if name == \"__eq__\" and type_name:\n            eq_message = \"\"\"\n            It is recommended for \"__eq__\" to work with arbitrary objects, for example:\n                def __eq__(self, other: object) -> bool:\n                    if not isinstance(other, {class_name}):\n                        return NotImplemented\n                    return <logic to compare two {class_name} instances>\n            \"\"\".format(class_name=type_name)\n            self.note_multiline(\n                eq_message, context, code=codes.OVERRIDE, origin_context=origin_context\n            )\n\n    def return_type_incompatible_with_supertype(\n        self,\n        name: str,\n        name_in_supertype: str,\n        supertype: str,\n        original: Type,\n        override: Type,\n        context: Context,\n    ) -> None:\n        target = self.override_target(name, name_in_supertype, supertype)\n        override_str, original_str = format_type_distinctly(\n            override, original, options=self.options\n        )\n        self.fail(\n            'Return type {} of \"{}\" incompatible with return type {} in {}'.format(\n                override_str, name, original_str, target\n            ),\n            context,\n            code=codes.OVERRIDE,\n        )\n\n        original = get_proper_type(original)\n        override = get_proper_type(override)\n        if (\n            isinstance(original, Instance)\n            and isinstance(override, Instance)\n            and override.type.fullname == \"typing.AsyncIterator\"\n            and original.type.fullname == \"typing.Coroutine\"\n            and len(original.args) == 3\n            and original.args[2] == override\n        ):\n            self.note(f'Consider declaring \"{name}\" in {target} without \"async\"', context)\n            self.note(\n                \"See https://mypy.readthedocs.io/en/stable/more_types.html#asynchronous-iterators\",\n                context,\n            )\n\n    def override_target(self, name: str, name_in_super: str, supertype: str) -> str:\n        target = f'supertype \"{supertype}\"'\n        if name_in_super != name:\n            target = f'\"{name_in_super}\" of {target}'\n        return target\n\n    def incompatible_type_application(\n        self, min_arg_count: int, max_arg_count: int, actual_arg_count: int, context: Context\n    ) -> None:\n        if max_arg_count == 0:\n            self.fail(\"Type application targets a non-generic function or class\", context)\n            return\n\n        if min_arg_count == max_arg_count:\n            s = f\"{max_arg_count} expected\"\n        else:\n            s = f\"expected between {min_arg_count} and {max_arg_count}\"\n\n        if actual_arg_count > max_arg_count:\n            self.fail(f\"Type application has too many types ({s})\", context)\n        else:\n            self.fail(f\"Type application has too few types ({s})\", context)\n\n    def could_not_infer_type_arguments(\n        self, callee_type: CallableType, tv: TypeVarLikeType, context: Context\n    ) -> None:\n        callee_name = callable_name(callee_type)\n        if callee_name is not None:\n            self.fail(\n                f\"Cannot infer value of type parameter {format_type(tv, self.options)} of {callee_name}\",\n                context,\n            )\n            if callee_name == \"<dict>\":\n                # Invariance in key type causes more of these errors than we would want.\n                self.note(\n                    \"Try assigning the literal to a variable annotated as dict[<key>, <val>]\",\n                    context,\n                )\n        else:\n            self.fail(\"Cannot infer function type argument\", context)\n\n    def invalid_var_arg(self, typ: Type, context: Context) -> None:\n        self.fail(\"Expected iterable as variadic argument\", context)\n\n    def invalid_keyword_var_arg(self, typ: Type, is_mapping: bool, context: Context) -> None:\n        typ = get_proper_type(typ)\n        if isinstance(typ, Instance) and is_mapping:\n            self.fail(\"Argument after ** must have string keys\", context, code=codes.ARG_TYPE)\n        else:\n            self.fail(\n                f\"Argument after ** must be a mapping, not {format_type(typ, self.options)}\",\n                context,\n                code=codes.ARG_TYPE,\n            )\n\n    def undefined_in_superclass(self, member: str, context: Context) -> None:\n        self.fail(f'\"{member}\" undefined in superclass', context)\n\n    def variable_may_be_undefined(self, name: str, context: Context) -> None:\n        self.fail(f'Name \"{name}\" may be undefined', context, code=codes.POSSIBLY_UNDEFINED)\n\n    def var_used_before_def(self, name: str, context: Context) -> None:\n        self.fail(f'Name \"{name}\" is used before definition', context, code=codes.USED_BEFORE_DEF)\n\n    def first_argument_for_super_must_be_type(self, actual: Type, context: Context) -> None:\n        actual = get_proper_type(actual)\n        if isinstance(actual, Instance):\n            # Don't include type of instance, because it can look confusingly like a type\n            # object.\n            type_str = \"a non-type instance\"\n        else:\n            type_str = format_type(actual, self.options)\n        self.fail(\n            f'Argument 1 for \"super\" must be a type object; got {type_str}',\n            context,\n            code=codes.ARG_TYPE,\n        )\n\n    def unsafe_super(self, method: str, cls: str, ctx: Context) -> None:\n        self.fail(\n            f'Call to abstract method \"{method}\" of \"{cls}\" with trivial body via super() is unsafe',\n            ctx,\n            code=codes.SAFE_SUPER,\n        )\n\n    def too_few_string_formatting_arguments(self, context: Context) -> None:\n        self.fail(\"Not enough arguments for format string\", context, code=codes.STRING_FORMATTING)\n\n    def too_many_string_formatting_arguments(self, context: Context) -> None:\n        self.fail(\n            \"Not all arguments converted during string formatting\",\n            context,\n            code=codes.STRING_FORMATTING,\n        )\n\n    def unsupported_placeholder(self, placeholder: str, context: Context) -> None:\n        self.fail(\n            f'Unsupported format character \"{placeholder}\"', context, code=codes.STRING_FORMATTING\n        )\n\n    def string_interpolation_with_star_and_key(self, context: Context) -> None:\n        self.fail(\n            \"String interpolation contains both stars and mapping keys\",\n            context,\n            code=codes.STRING_FORMATTING,\n        )\n\n    def requires_int_or_single_byte(self, context: Context, format_call: bool = False) -> None:\n        self.fail(\n            '\"{}c\" requires an integer in range(256) or a single byte'.format(\n                \":\" if format_call else \"%\"\n            ),\n            context,\n            code=codes.STRING_FORMATTING,\n        )\n\n    def requires_int_or_char(self, context: Context, format_call: bool = False) -> None:\n        self.fail(\n            '\"{}c\" requires int or char'.format(\":\" if format_call else \"%\"),\n            context,\n            code=codes.STRING_FORMATTING,\n        )\n\n    def key_not_in_mapping(self, key: str, context: Context) -> None:\n        self.fail(f'Key \"{key}\" not found in mapping', context, code=codes.STRING_FORMATTING)\n\n    def string_interpolation_mixing_key_and_non_keys(self, context: Context) -> None:\n        self.fail(\n            \"String interpolation mixes specifier with and without mapping keys\",\n            context,\n            code=codes.STRING_FORMATTING,\n        )\n\n    def cannot_determine_type(self, name: str, context: Context) -> None:\n        self.fail(f'Cannot determine type of \"{name}\"', context, code=codes.HAS_TYPE)\n\n    def cannot_determine_type_in_base(self, name: str, base: str, context: Context) -> None:\n        self.fail(f'Cannot determine type of \"{name}\" in base class \"{base}\"', context)\n\n    def no_formal_self(self, name: str, item: CallableType, context: Context) -> None:\n        type = format_type(item, self.options)\n        self.fail(\n            f'Attribute function \"{name}\" with type {type} does not accept self argument', context\n        )\n\n    def incompatible_self_argument(\n        self, name: str, arg: Type, sig: CallableType, is_classmethod: bool, context: Context\n    ) -> None:\n        kind = \"class attribute function\" if is_classmethod else \"attribute function\"\n        arg_type = format_type(arg, self.options)\n        sig_type = format_type(sig, self.options)\n        self.fail(\n            f'Invalid self argument {arg_type} to {kind} \"{name}\" with type {sig_type}', context\n        )\n\n    def incompatible_conditional_function_def(\n        self, defn: FuncDef, old_type: FunctionLike, new_type: FunctionLike\n    ) -> None:\n        error = self.fail(\"All conditional function variants must have identical signatures\", defn)\n        if isinstance(old_type, (CallableType, Overloaded)) and isinstance(\n            new_type, (CallableType, Overloaded)\n        ):\n            self.note(\"Original:\", defn)\n            self.pretty_callable_or_overload(old_type, defn, offset=4, parent_error=error)\n            self.note(\"Redefinition:\", defn)\n            self.pretty_callable_or_overload(new_type, defn, offset=4, parent_error=error)\n\n    def cannot_instantiate_abstract_class(\n        self, class_name: str, abstract_attributes: dict[str, bool], context: Context\n    ) -> None:\n        attrs = format_string_list([f'\"{a}\"' for a in abstract_attributes])\n        self.fail(\n            f'Cannot instantiate abstract class \"{class_name}\" with abstract '\n            f\"attribute{plural_s(abstract_attributes)} {attrs}\",\n            context,\n            code=codes.ABSTRACT,\n        )\n        attrs_with_none = [\n            f'\"{a}\"'\n            for a, implicit_and_can_return_none in abstract_attributes.items()\n            if implicit_and_can_return_none\n        ]\n        if not attrs_with_none:\n            return\n        if len(attrs_with_none) == 1:\n            note = (\n                f\"{attrs_with_none[0]} is implicitly abstract because it has an empty function \"\n                \"body. If it is not meant to be abstract, explicitly `return` or `return None`.\"\n            )\n        else:\n            note = (\n                \"The following methods were marked implicitly abstract because they have empty \"\n                f\"function bodies: {format_string_list(attrs_with_none)}. \"\n                \"If they are not meant to be abstract, explicitly `return` or `return None`.\"\n            )\n        self.note(note, context, code=codes.ABSTRACT)\n\n    def base_class_definitions_incompatible(\n        self, name: str, base1: TypeInfo, base2: TypeInfo, context: Context\n    ) -> None:\n        self.fail(\n            'Definition of \"{}\" in base class \"{}\" is incompatible '\n            'with definition in base class \"{}\"'.format(name, base1.name, base2.name),\n            context,\n        )\n\n    def cant_assign_to_method(self, context: Context) -> None:\n        self.fail(message_registry.CANNOT_ASSIGN_TO_METHOD, context, code=codes.METHOD_ASSIGN)\n\n    def cant_assign_to_classvar(self, name: str, context: Context) -> None:\n        self.fail(f'Cannot assign to class variable \"{name}\" via instance', context)\n\n    def no_overridable_method(self, name: str, context: Context) -> None:\n        self.fail(\n            f'Method \"{name}\" is marked as an override, '\n            \"but no base method was found with this name\",\n            context,\n        )\n\n    def explicit_override_decorator_missing(\n        self, name: str, base_name: str, context: Context\n    ) -> None:\n        self.fail(\n            f'Method \"{name}\" is not using @override '\n            f'but is overriding a method in class \"{base_name}\"',\n            context,\n            code=codes.EXPLICIT_OVERRIDE_REQUIRED,\n        )\n\n    def final_cant_override_writable(self, name: str, ctx: Context) -> None:\n        self.fail(f'Cannot override writable attribute \"{name}\" with a final one', ctx)\n\n    def cant_override_final(self, name: str, base_name: str, ctx: Context) -> None:\n        self.fail(\n            (\n                f'Cannot override final attribute \"{name}\" '\n                f'(previously declared in base class \"{base_name}\")'\n            ),\n            ctx,\n        )\n\n    def cant_assign_to_final(self, name: str, attr_assign: bool, ctx: Context) -> None:\n        \"\"\"Warn about a prohibited assignment to a final attribute.\n\n        Pass `attr_assign=True` if the assignment assigns to an attribute.\n        \"\"\"\n        kind = \"attribute\" if attr_assign else \"name\"\n        self.fail(f'Cannot assign to final {kind} \"{unmangle(name)}\"', ctx)\n\n    def protocol_members_cant_be_final(self, ctx: Context) -> None:\n        self.fail(\"Protocol member cannot be final\", ctx)\n\n    def final_without_value(self, ctx: Context) -> None:\n        self.fail(\"Final name must be initialized with a value\", ctx)\n\n    def read_only_property(self, name: str, type: TypeInfo, context: Context) -> None:\n        self.fail(f'Property \"{name}\" defined in \"{type.name}\" is read-only', context)\n\n    def incompatible_typevar_value(\n        self, callee: CallableType, typ: Type, typevar_name: str, context: Context\n    ) -> None:\n        self.fail(\n            message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format(\n                typevar_name, callable_name(callee) or \"function\", format_type(typ, self.options)\n            ),\n            context,\n            code=codes.TYPE_VAR,\n        )\n\n    def dangerous_comparison(self, left: Type, right: Type, kind: str, ctx: Context) -> None:\n        # In loops (and similar cases), the same expression might be analysed multiple\n        # times and thereby confronted with different types.  We only want to raise a\n        # `comparison-overlap` error if it occurs in all cases and therefore collect the\n        # respective types of the current iteration here so that we can report the error\n        # later if it is persistent over all iteration steps:\n        for watcher in self.errors.get_watchers():\n            if watcher._filter:\n                break\n            if isinstance(watcher, IterationErrorWatcher):\n                watcher.iteration_dependent_errors.nonoverlapping_types[-1][\n                    NonOverlapErrorInfo(\n                        line=ctx.line,\n                        column=ctx.column,\n                        end_line=ctx.end_line,\n                        end_column=ctx.end_column,\n                        kind=kind,\n                    )\n                ] = (left, right)\n                return\n\n        left_str = \"element\" if kind == \"container\" else \"left operand\"\n        right_str = \"container item\" if kind == \"container\" else \"right operand\"\n        message = \"Non-overlapping {} check ({} type: {}, {} type: {})\"\n        left_typ, right_typ = format_type_distinctly(left, right, options=self.options)\n        self.fail(\n            message.format(kind, left_str, left_typ, right_str, right_typ),\n            ctx,\n            code=codes.COMPARISON_OVERLAP,\n        )\n\n    def overload_inconsistently_applies_decorator(self, decorator: str, context: Context) -> None:\n        self.fail(\n            f'Overload does not consistently use the \"@{decorator}\" '\n            + \"decorator on all function signatures.\",\n            context,\n        )\n\n    def overloaded_signatures_overlap(\n        self, index1: int, index2: int, flip_note: bool, context: Context\n    ) -> None:\n        self.fail(\n            \"Overloaded function signatures {} and {} overlap with \"\n            \"incompatible return types\".format(index1, index2),\n            context,\n            code=codes.OVERLOAD_OVERLAP,\n        )\n        if flip_note:\n            self.note(\n                \"Flipping the order of overloads will fix this error\",\n                context,\n                code=codes.OVERLOAD_OVERLAP,\n            )\n\n    def overloaded_signature_will_never_match(\n        self, index1: int, index2: int, context: Context\n    ) -> None:\n        self.fail(\n            \"Overloaded function signature {index2} will never be matched: \"\n            \"signature {index1}'s parameter type(s) are the same or broader\".format(\n                index1=index1, index2=index2\n            ),\n            context,\n            code=codes.OVERLOAD_CANNOT_MATCH,\n        )\n\n    def overloaded_signatures_typevar_specific(self, index: int, context: Context) -> None:\n        self.fail(\n            f\"Overloaded function implementation cannot satisfy signature {index} \"\n            + \"due to inconsistencies in how they use type variables\",\n            context,\n        )\n\n    def overloaded_signatures_param_specific(self, index: int, context: Context) -> None:\n        self.fail(\n            (\n                f\"Overloaded function implementation does not accept all possible parameters \"\n                f\"of signature {index}\"\n            ),\n            context,\n        )\n\n    def overloaded_signatures_ret_specific(self, index: int, context: Context) -> None:\n        self.fail(\n            f\"Overloaded function implementation cannot produce return type of signature {index}\",\n            context,\n        )\n\n    def warn_both_operands_are_from_unions(self, context: Context) -> None:\n        self.note(\"Both left and right operands are unions\", context, code=codes.OPERATOR)\n\n    def warn_operand_was_from_union(self, side: str, original: Type, context: Context) -> None:\n        self.note(\n            f\"{side} operand is of type {format_type(original, self.options)}\",\n            context,\n            code=codes.OPERATOR,\n        )\n\n    def operator_method_signatures_overlap(\n        self,\n        reverse_class: TypeInfo,\n        reverse_method: str,\n        forward_class: Type,\n        forward_method: str,\n        context: Context,\n    ) -> None:\n        self.fail(\n            'Signatures of \"{}\" of \"{}\" and \"{}\" of {} are unsafely overlapping'.format(\n                reverse_method,\n                reverse_class.name,\n                forward_method,\n                format_type(forward_class, self.options),\n            ),\n            context,\n        )\n\n    def forward_operator_not_callable(self, forward_method: str, context: Context) -> None:\n        self.fail(f'Forward operator \"{forward_method}\" is not callable', context)\n\n    def signatures_incompatible(self, method: str, other_method: str, context: Context) -> None:\n        self.fail(f'Signatures of \"{method}\" and \"{other_method}\" are incompatible', context)\n\n    def yield_from_invalid_operand_type(self, expr: Type, context: Context) -> Type:\n        text = (\n            format_type(expr, self.options)\n            if format_type(expr, self.options) != \"object\"\n            else expr\n        )\n        self.fail(f'\"yield from\" can\\'t be applied to {text}', context)\n        return AnyType(TypeOfAny.from_error)\n\n    def invalid_signature(self, func_type: Type, context: Context) -> None:\n        self.fail(f\"Invalid signature {format_type(func_type, self.options)}\", context)\n\n    def invalid_signature_for_special_method(\n        self, func_type: Type, context: Context, method_name: str\n    ) -> None:\n        self.fail(\n            f'Invalid signature {format_type(func_type, self.options)} for \"{method_name}\"',\n            context,\n        )\n\n    def reveal_type(self, typ: Type, context: Context) -> None:\n\n        # Search for an error watcher that modifies the \"normal\" behaviour (we do not\n        # rely on the normal `ErrorWatcher` filtering approach because we might need to\n        # collect the original types for a later unionised response):\n        for watcher in self.errors.get_watchers():\n            # The `reveal_type` statement should be ignored:\n            if watcher.filter_revealed_type:\n                return\n            # The `reveal_type` statement might be visited iteratively due to being\n            # placed in a loop or so. Hence, we collect the respective types of\n            # individual iterations so that we can report them all in one step later:\n            if isinstance(watcher, IterationErrorWatcher):\n                watcher.iteration_dependent_errors.revealed_types[\n                    (context.line, context.column, context.end_line, context.end_column)\n                ].append(typ)\n                return\n\n        # Nothing special here; just create the note:\n        visitor = TypeStrVisitor(options=self.options)\n        self.note(f'Revealed type is \"{typ.accept(visitor)}\"', context)\n\n    def reveal_locals(self, type_map: dict[str, Type | None], context: Context) -> None:\n        # To ensure that the output is predictable on Python < 3.6,\n        # use an ordered dictionary sorted by variable name\n        sorted_locals = dict(sorted(type_map.items(), key=lambda t: t[0]))\n        if sorted_locals:\n            self.note(\"Revealed local types are:\", context)\n            for k, v in sorted_locals.items():\n                visitor = TypeStrVisitor(options=self.options)\n                self.note(f\"    {k}: {v.accept(visitor) if v is not None else None}\", context)\n        else:\n            self.note(\"There are no locals to reveal\", context)\n\n    def unsupported_type_type(self, item: Type, context: Context) -> None:\n        self.fail(\n            f'Cannot instantiate type \"type[{format_type_bare(item, self.options)}]\"', context\n        )\n\n    def redundant_cast(self, typ: Type, context: Context) -> None:\n        self.fail(\n            f\"Redundant cast to {format_type(typ, self.options)}\",\n            context,\n            code=codes.REDUNDANT_CAST,\n        )\n\n    def assert_type_fail(self, source_type: Type, target_type: Type, context: Context) -> None:\n        source, target = format_type_distinctly(source_type, target_type, options=self.options)\n        self.fail(f\"Expression is of type {source}, not {target}\", context, code=codes.ASSERT_TYPE)\n\n    def unimported_type_becomes_any(self, prefix: str, typ: Type, ctx: Context) -> None:\n        self.fail(\n            f\"{prefix} becomes {format_type(typ, self.options)} due to an unfollowed import\",\n            ctx,\n            code=codes.NO_ANY_UNIMPORTED,\n        )\n\n    def need_annotation_for_var(\n        self, node: SymbolNode, context: Context, options: Options | None = None\n    ) -> None:\n        hint = \"\"\n        # type to recommend the user adds\n        recommended_type = None\n        # Only gives hint if it's a variable declaration and the partial type is a builtin type\n        if options and isinstance(node, Var) and isinstance(node.type, PartialType):\n            type_dec = \"<type>\"\n            if not node.type.type:\n                # partial None\n                recommended_type = f\"{type_dec} | None\"\n            elif node.type.type.fullname in reverse_builtin_aliases:\n                # partial types other than partial None\n                name = node.type.type.fullname.partition(\".\")[2]\n                if name == \"dict\":\n                    type_dec = f\"{type_dec}, {type_dec}\"\n                recommended_type = f\"{name}[{type_dec}]\"\n        if recommended_type is not None:\n            hint = f' (hint: \"{node.name}: {recommended_type} = ...\")'\n\n        self.fail(\n            f'Need type annotation for \"{unmangle(node.name)}\"{hint}',\n            context,\n            code=codes.VAR_ANNOTATED,\n        )\n\n    def explicit_any(self, ctx: Context) -> None:\n        self.fail('Explicit \"Any\" is not allowed', ctx, code=codes.EXPLICIT_ANY)\n\n    def unsupported_target_for_star_typeddict(self, typ: Type, ctx: Context) -> None:\n        self.fail(\n            \"Unsupported type {} for ** expansion in TypedDict\".format(\n                format_type(typ, self.options)\n            ),\n            ctx,\n            code=codes.TYPEDDICT_ITEM,\n        )\n\n    def non_required_keys_absent_with_star(self, keys: list[str], ctx: Context) -> None:\n        self.fail(\n            \"Non-required {} not explicitly found in any ** item\".format(\n                format_key_list(keys, short=True)\n            ),\n            ctx,\n            code=codes.TYPEDDICT_ITEM,\n        )\n\n    def unexpected_typeddict_keys(\n        self,\n        typ: TypedDictType,\n        expected_keys: list[str],\n        actual_keys: list[str],\n        context: Context,\n    ) -> None:\n        actual_set = set(actual_keys)\n        expected_set = set(expected_keys)\n        if not typ.is_anonymous():\n            # Generate simpler messages for some common special cases.\n            # Use list comprehension instead of set operations to preserve order.\n            missing = [key for key in expected_keys if key not in actual_set]\n            if missing:\n                self.fail(\n                    \"Missing {} for TypedDict {}\".format(\n                        format_key_list(missing, short=True), format_type(typ, self.options)\n                    ),\n                    context,\n                    code=codes.TYPEDDICT_ITEM,\n                )\n            extra = [key for key in actual_keys if key not in expected_set]\n            if extra:\n                self.fail(\n                    \"Extra {} for TypedDict {}\".format(\n                        format_key_list(extra, short=True), format_type(typ, self.options)\n                    ),\n                    context,\n                    code=codes.TYPEDDICT_UNKNOWN_KEY,\n                )\n            if missing or extra:\n                # No need to check for further errors\n                return\n        found = format_key_list(actual_keys, short=True)\n        if not expected_keys:\n            self.fail(f\"Unexpected TypedDict {found}\", context)\n            return\n        expected = format_key_list(expected_keys)\n        if actual_keys and actual_set < expected_set:\n            found = f\"only {found}\"\n        self.fail(f\"Expected {expected} but found {found}\", context, code=codes.TYPEDDICT_ITEM)\n\n    def typeddict_key_must_be_string_literal(self, typ: TypedDictType, context: Context) -> None:\n        self.fail(\n            \"TypedDict key must be a string literal; expected one of {}\".format(\n                format_item_name_list(typ.items.keys())\n            ),\n            context,\n            code=codes.LITERAL_REQ,\n        )\n\n    def typeddict_key_not_found(\n        self, typ: TypedDictType, item_name: str, context: Context, setitem: bool = False\n    ) -> None:\n        \"\"\"Handle error messages for TypedDicts that have unknown keys.\n\n        Note, that we differentiate in between reading a value and setting a\n        value.\n        Setting a value on a TypedDict is an 'unknown-key' error, whereas\n        reading it is the more serious/general 'item' error.\n        \"\"\"\n        if typ.is_anonymous():\n            self.fail(\n                '\"{}\" is not a valid TypedDict key; expected one of {}'.format(\n                    item_name, format_item_name_list(typ.items.keys())\n                ),\n                context,\n            )\n        else:\n            err_code = codes.TYPEDDICT_UNKNOWN_KEY if setitem else codes.TYPEDDICT_ITEM\n            self.fail(\n                f'TypedDict {format_type(typ, self.options)} has no key \"{item_name}\"',\n                context,\n                code=err_code,\n            )\n            matches = best_matches(item_name, typ.items.keys(), n=3)\n            if matches:\n                self.note(\n                    \"Did you mean {}?\".format(pretty_seq(matches, \"or\")), context, code=err_code\n                )\n\n    def typeddict_context_ambiguous(self, types: list[TypedDictType], context: Context) -> None:\n        formatted_types = \", \".join(list(format_type_distinctly(*types, options=self.options)))\n        self.fail(\n            f\"Type of TypedDict is ambiguous, none of ({formatted_types}) matches cleanly\", context\n        )\n\n    def typeddict_key_cannot_be_deleted(\n        self, typ: TypedDictType, item_name: str, context: Context\n    ) -> None:\n        if typ.is_anonymous():\n            self.fail(f'TypedDict key \"{item_name}\" cannot be deleted', context)\n        else:\n            self.fail(\n                f'Key \"{item_name}\" of TypedDict {format_type(typ, self.options)} cannot be deleted',\n                context,\n            )\n\n    def typeddict_setdefault_arguments_inconsistent(\n        self, default: Type, expected: Type, context: Context\n    ) -> None:\n        msg = 'Argument 2 to \"setdefault\" of \"TypedDict\" has incompatible type {}; expected {}'\n        self.fail(\n            msg.format(format_type(default, self.options), format_type(expected, self.options)),\n            context,\n            code=codes.TYPEDDICT_ITEM,\n        )\n\n    def type_arguments_not_allowed(self, context: Context) -> None:\n        self.fail(\"Parameterized generics cannot be used with class or instance checks\", context)\n\n    def disallowed_any_type(self, typ: Type, context: Context) -> None:\n        typ = get_proper_type(typ)\n        if isinstance(typ, AnyType):\n            message = 'Expression has type \"Any\"'\n        else:\n            message = f'Expression type contains \"Any\" (has type {format_type(typ, self.options)})'\n        self.fail(message, context)\n\n    def incorrectly_returning_any(self, typ: Type, context: Context) -> None:\n        message = (\n            f\"Returning Any from function declared to return {format_type(typ, self.options)}\"\n        )\n        self.fail(message, context, code=codes.NO_ANY_RETURN)\n\n    def incorrect__exit__return(self, context: Context) -> None:\n        self.fail(\n            '\"bool\" is invalid as return type for \"__exit__\" that always returns False',\n            context,\n            code=codes.EXIT_RETURN,\n        )\n        self.note(\n            'Use \"typing.Literal[False]\" as the return type or change it to \"None\"',\n            context,\n            code=codes.EXIT_RETURN,\n        )\n        self.note(\n            'If return type of \"__exit__\" implies that it may return True, '\n            \"the context manager may swallow exceptions\",\n            context,\n            code=codes.EXIT_RETURN,\n        )\n\n    def untyped_decorated_function(self, typ: Type, context: Context) -> None:\n        typ = get_proper_type(typ)\n        if isinstance(typ, AnyType):\n            self.fail(\"Function is untyped after decorator transformation\", context)\n        else:\n            self.fail(\n                f'Type of decorated function contains type \"Any\" ({format_type(typ, self.options)})',\n                context,\n            )\n\n    def typed_function_untyped_decorator(self, func_name: str, context: Context) -> None:\n        self.fail(\n            f'Untyped decorator makes function \"{func_name}\" untyped',\n            context,\n            code=codes.UNTYPED_DECORATOR,\n        )\n\n    def bad_proto_variance(\n        self, actual: int, tvar_name: str, expected: int, context: Context\n    ) -> None:\n        msg = capitalize(\n            '{} type variable \"{}\" used in protocol where {} one is expected'.format(\n                variance_string(actual), tvar_name, variance_string(expected)\n            )\n        )\n        self.fail(msg, context)\n\n    def concrete_only_assign(self, typ: Type, context: Context) -> None:\n        self.fail(\n            f\"Can only assign concrete classes to a variable of type {format_type(typ, self.options)}\",\n            context,\n            code=codes.TYPE_ABSTRACT,\n        )\n\n    def concrete_only_call(self, typ: Type, context: Context) -> None:\n        self.fail(\n            f\"Only concrete class can be given where {format_type(typ, self.options)} is expected\",\n            context,\n            code=codes.TYPE_ABSTRACT,\n        )\n\n    def cannot_use_function_with_type(\n        self, method_name: str, type_name: str, context: Context\n    ) -> None:\n        self.fail(f\"Cannot use {method_name}() with {type_name} type\", context)\n\n    def report_non_method_protocol(\n        self, tp: TypeInfo, members: list[str], context: Context\n    ) -> None:\n        self.fail(\n            \"Only protocols that don't have non-method members can be used with issubclass()\",\n            context,\n        )\n        if len(members) < 3:\n            attrs = \", \".join(members)\n            self.note(f'Protocol \"{tp.name}\" has non-method member(s): {attrs}', context)\n\n    def note_call(\n        self, subtype: Type, call: Type, context: Context, *, code: ErrorCode | None\n    ) -> None:\n        self.note(\n            '\"{}.__call__\" has type {}'.format(\n                format_type_bare(subtype, self.options),\n                format_type(call, self.options, verbosity=1),\n            ),\n            context,\n            code=code,\n        )\n\n    def unreachable_statement(self, context: Context) -> None:\n        self.fail(\"Statement is unreachable\", context, code=codes.UNREACHABLE)\n\n    def redundant_left_operand(self, op_name: str, context: Context) -> None:\n        \"\"\"Indicates that the left operand of a boolean expression is redundant:\n        it does not change the truth value of the entire condition as a whole.\n        'op_name' should either be the string \"and\" or the string \"or\".\n        \"\"\"\n        self.redundant_expr(f'Left operand of \"{op_name}\"', op_name == \"and\", context)\n\n    def unreachable_right_operand(self, op_name: str, context: Context) -> None:\n        \"\"\"Indicates that the right operand of a boolean expression is redundant:\n        it does not change the truth value of the entire condition as a whole.\n        'op_name' should either be the string \"and\" or the string \"or\".\n        \"\"\"\n        self.fail(\n            f'Right operand of \"{op_name}\" is never evaluated', context, code=codes.UNREACHABLE\n        )\n\n    def redundant_condition_in_comprehension(self, truthiness: bool, context: Context) -> None:\n        self.redundant_expr(\"If condition in comprehension\", truthiness, context)\n\n    def redundant_condition_in_if(self, truthiness: bool, context: Context) -> None:\n        self.redundant_expr(\"If condition\", truthiness, context)\n\n    def redundant_expr(self, description: str, truthiness: bool, context: Context) -> None:\n        self.fail(\n            f\"{description} is always {str(truthiness).lower()}\",\n            context,\n            code=codes.REDUNDANT_EXPR,\n        )\n\n    def impossible_intersection(\n        self, formatted_base_class_list: str, reason: str, context: Context\n    ) -> None:\n        template = \"Subclass of {} cannot exist: {}\"\n        self.fail(\n            template.format(formatted_base_class_list, reason), context, code=codes.UNREACHABLE\n        )\n\n    def tvar_without_default_type(\n        self, tvar_name: str, last_tvar_name_with_default: str, context: Context\n    ) -> None:\n        self.fail(\n            f'\"{tvar_name}\" cannot appear after \"{last_tvar_name_with_default}\" '\n            \"in type parameter list because it has no default type\",\n            context,\n        )\n\n    def report_protocol_problems(\n        self,\n        subtype: Instance | TupleType | TypedDictType | TypeType | CallableType,\n        supertype: Instance,\n        context: Context,\n        *,\n        parent_error: ErrorInfo,\n    ) -> None:\n        \"\"\"Report possible protocol conflicts between 'subtype' and 'supertype'.\n\n        This includes missing members, incompatible types, and incompatible\n        attribute flags, such as settable vs read-only or class variable vs\n        instance variable.\n        \"\"\"\n        OFFSET = 4  # Four spaces, so that notes will look like this:\n        # note: 'Cls' is missing following 'Proto' members:\n        # note:     method, attr\n        MAX_ITEMS = 2  # Maximum number of conflicts, missing members, and overloads shown\n        # List of special situations where we don't want to report additional problems\n        exclusions: dict[type, list[str]] = {\n            TypedDictType: [\"typing.Mapping\"],\n            TupleType: [\"typing.Iterable\", \"typing.Sequence\"],\n        }\n        if supertype.type.fullname in exclusions.get(type(subtype), []):\n            return\n        if any(isinstance(tp, UninhabitedType) for tp in get_proper_types(supertype.args)):\n            # We don't want to add notes for failed inference (e.g. Iterable[Never]).\n            # This will be only confusing a user even more.\n            return\n\n        class_obj = False\n        is_module = False\n        skip = []\n        if isinstance(subtype, TupleType):\n            subtype = subtype.partial_fallback\n        elif isinstance(subtype, TypedDictType):\n            subtype = subtype.fallback\n        elif isinstance(subtype, TypeType):\n            if not isinstance(subtype.item, Instance):\n                return\n            class_obj = True\n            subtype = subtype.item\n        elif isinstance(subtype, CallableType):\n            if subtype.is_type_obj():\n                ret_type = get_proper_type(subtype.ret_type)\n                if isinstance(ret_type, TupleType):\n                    ret_type = ret_type.partial_fallback\n                if not isinstance(ret_type, Instance):\n                    return\n                class_obj = True\n                subtype = ret_type\n            else:\n                subtype = subtype.fallback\n                skip = [\"__call__\"]\n        if subtype.extra_attrs and subtype.extra_attrs.mod_name:\n            is_module = True\n\n        # Report missing members\n        missing = get_missing_protocol_members(subtype, supertype, skip=skip)\n        if (\n            missing\n            and (len(missing) < len(supertype.type.protocol_members) or missing == [\"__call__\"])\n            and len(missing) <= MAX_ITEMS\n        ):\n            if missing == [\"__call__\"] and class_obj:\n                self.note(\n                    '\"{}\" has constructor incompatible with \"__call__\" of \"{}\"'.format(\n                        subtype.type.name, supertype.type.name\n                    ),\n                    context,\n                    parent_error=parent_error,\n                )\n            else:\n                self.note(\n                    '\"{}\" is missing following \"{}\" protocol member{}:'.format(\n                        subtype.type.name, supertype.type.name, plural_s(missing)\n                    ),\n                    context,\n                    parent_error=parent_error,\n                )\n                self.note(\", \".join(missing), context, offset=OFFSET, parent_error=parent_error)\n        elif len(missing) > MAX_ITEMS or len(missing) == len(supertype.type.protocol_members):\n            # This is an obviously wrong type: too many missing members\n            return\n\n        # Report member type conflicts\n        conflict_types = get_conflict_protocol_types(\n            subtype, supertype, class_obj=class_obj, options=self.options\n        )\n        if conflict_types and (\n            not is_subtype(subtype, erase_type(supertype), options=self.options)\n            or not subtype.type.defn.type_vars\n            or not supertype.type.defn.type_vars\n            # Always show detailed message for ParamSpec\n            or subtype.type.has_param_spec_type\n            or supertype.type.has_param_spec_type\n        ):\n            type_name = format_type(subtype, self.options, module_names=True)\n            self.note(\n                f\"Following member(s) of {type_name} have conflicts:\",\n                context,\n                parent_error=parent_error,\n            )\n            for name, got, exp, is_lvalue in conflict_types[:MAX_ITEMS]:\n                exp = get_proper_type(exp)\n                got = get_proper_type(got)\n                setter_suffix = \" setter type\" if is_lvalue else \"\"\n                if (\n                    not isinstance(exp, (CallableType, Overloaded))\n                    or not isinstance(got, (CallableType, Overloaded))\n                    # If expected type is a type object, it means it is a nested class.\n                    # Showing constructor signature in errors would be confusing in this case,\n                    # since we don't check the signature, only subclassing of type objects.\n                    or exp.is_type_obj()\n                ):\n                    self.note(\n                        \"{}: expected{} {}, got {}\".format(\n                            name,\n                            setter_suffix,\n                            *format_type_distinctly(exp, got, options=self.options),\n                        ),\n                        context,\n                        offset=OFFSET,\n                        parent_error=parent_error,\n                    )\n                    if is_lvalue and is_subtype(got, exp, options=self.options):\n                        self.note(\n                            \"Setter types should behave contravariantly\",\n                            context,\n                            offset=OFFSET,\n                            parent_error=parent_error,\n                        )\n                else:\n                    self.note(\n                        \"Expected{}:\".format(setter_suffix),\n                        context,\n                        offset=OFFSET,\n                        parent_error=parent_error,\n                    )\n                    if isinstance(exp, CallableType):\n                        self.note(\n                            pretty_callable(exp, self.options, skip_self=class_obj or is_module),\n                            context,\n                            offset=2 * OFFSET,\n                            parent_error=parent_error,\n                        )\n                    else:\n                        assert isinstance(exp, Overloaded)\n                        self.pretty_overload(\n                            exp,\n                            context,\n                            2 * OFFSET,\n                            parent_error=parent_error,\n                            skip_self=class_obj or is_module,\n                        )\n                    self.note(\"Got:\", context, offset=OFFSET, parent_error=parent_error)\n                    if isinstance(got, CallableType):\n                        self.note(\n                            pretty_callable(got, self.options, skip_self=class_obj or is_module),\n                            context,\n                            offset=2 * OFFSET,\n                            parent_error=parent_error,\n                        )\n                    else:\n                        assert isinstance(got, Overloaded)\n                        self.pretty_overload(\n                            got,\n                            context,\n                            2 * OFFSET,\n                            parent_error=parent_error,\n                            skip_self=class_obj or is_module,\n                        )\n            self.print_more(conflict_types, context, OFFSET, MAX_ITEMS, code=parent_error.code)\n\n        # Report flag conflicts (i.e. settable vs read-only etc.)\n        conflict_flags = get_bad_protocol_flags(subtype, supertype, class_obj=class_obj)\n        for name, subflags, superflags in conflict_flags[:MAX_ITEMS]:\n            if not class_obj and IS_CLASSVAR in subflags and IS_CLASSVAR not in superflags:\n                self.note(\n                    \"Protocol member {}.{} expected instance variable, got class variable\".format(\n                        supertype.type.name, name\n                    ),\n                    context,\n                    parent_error=parent_error,\n                )\n            if not class_obj and IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags:\n                self.note(\n                    \"Protocol member {}.{} expected class variable, got instance variable\".format(\n                        supertype.type.name, name\n                    ),\n                    context,\n                    parent_error=parent_error,\n                )\n            if IS_SETTABLE in superflags and IS_SETTABLE not in subflags:\n                self.note(\n                    \"Protocol member {}.{} expected settable variable,\"\n                    \" got read-only attribute\".format(supertype.type.name, name),\n                    context,\n                    parent_error=parent_error,\n                )\n            if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags:\n                self.note(\n                    \"Protocol member {}.{} expected class or static method\".format(\n                        supertype.type.name, name\n                    ),\n                    context,\n                    parent_error=parent_error,\n                )\n            if (\n                class_obj\n                and IS_VAR in superflags\n                and (IS_VAR in subflags and IS_CLASSVAR not in subflags)\n            ):\n                self.note(\n                    \"Only class variables allowed for class object access on protocols,\"\n                    ' {} is an instance variable of \"{}\"'.format(name, subtype.type.name),\n                    context,\n                    parent_error=parent_error,\n                )\n            if class_obj and IS_CLASSVAR in superflags:\n                self.note(\n                    \"ClassVar protocol member {}.{} can never be matched by a class object\".format(\n                        supertype.type.name, name\n                    ),\n                    context,\n                    parent_error=parent_error,\n                )\n        self.print_more(conflict_flags, context, OFFSET, MAX_ITEMS, code=parent_error.code)\n\n    def pretty_overload(\n        self,\n        tp: Overloaded,\n        context: Context,\n        offset: int,\n        *,\n        parent_error: ErrorInfo,\n        add_class_or_static_decorator: bool = False,\n        skip_self: bool = False,\n    ) -> None:\n        for item in tp.items:\n            self.note(\"@overload\", context, offset=offset, parent_error=parent_error)\n\n            if add_class_or_static_decorator:\n                decorator = pretty_class_or_static_decorator(item)\n                if decorator is not None:\n                    self.note(decorator, context, offset=offset, parent_error=parent_error)\n\n            self.note(\n                pretty_callable(item, self.options, skip_self=skip_self),\n                context,\n                offset=offset,\n                parent_error=parent_error,\n            )\n\n    def print_more(\n        self,\n        conflicts: Sequence[Any],\n        context: Context,\n        offset: int,\n        max_items: int,\n        *,\n        code: ErrorCode | None = None,\n    ) -> None:\n        if len(conflicts) > max_items:\n            self.note(\n                f\"<{len(conflicts) - max_items} more conflict(s) not shown>\",\n                context,\n                offset=offset,\n                code=code,\n            )\n\n    def try_report_long_tuple_assignment_error(\n        self,\n        subtype: ProperType,\n        supertype: ProperType,\n        context: Context,\n        msg: message_registry.ErrorMessage,\n        subtype_label: str | None = None,\n        supertype_label: str | None = None,\n    ) -> bool:\n        \"\"\"Try to generate meaningful error message for very long tuple assignment\n\n        Returns a bool: True when generating long tuple assignment error,\n        False when no such error reported\n        \"\"\"\n        if isinstance(subtype, TupleType):\n            if (\n                len(subtype.items) > MAX_TUPLE_ITEMS\n                and isinstance(supertype, Instance)\n                and supertype.type.fullname == \"builtins.tuple\"\n            ):\n                lhs_type = supertype.args[0]\n                lhs_types = [lhs_type] * len(subtype.items)\n                self.generate_incompatible_tuple_error(lhs_types, subtype.items, context, msg)\n                return True\n            elif isinstance(supertype, TupleType) and (\n                len(subtype.items) > MAX_TUPLE_ITEMS or len(supertype.items) > MAX_TUPLE_ITEMS\n            ):\n                if len(subtype.items) != len(supertype.items):\n                    if supertype_label is not None and subtype_label is not None:\n                        msg = msg.with_additional_msg(\n                            \" ({} {}, {} {})\".format(\n                                subtype_label,\n                                self.format_long_tuple_type(subtype),\n                                supertype_label,\n                                self.format_long_tuple_type(supertype),\n                            )\n                        )\n                        self.fail(msg.value, context, code=msg.code)\n                        return True\n                self.generate_incompatible_tuple_error(\n                    supertype.items, subtype.items, context, msg\n                )\n                return True\n        return False\n\n    def format_long_tuple_type(self, typ: TupleType) -> str:\n        \"\"\"Format very long tuple type using an ellipsis notation\"\"\"\n        item_cnt = len(typ.items)\n        if item_cnt > MAX_TUPLE_ITEMS:\n            return '\"tuple[{}, {}, ... <{} more items>]\"'.format(\n                format_type_bare(typ.items[0], self.options),\n                format_type_bare(typ.items[1], self.options),\n                str(item_cnt - 2),\n            )\n        else:\n            return format_type(typ, self.options)\n\n    def generate_incompatible_tuple_error(\n        self,\n        lhs_types: list[Type],\n        rhs_types: list[Type],\n        context: Context,\n        msg: message_registry.ErrorMessage,\n    ) -> None:\n        \"\"\"Generate error message for individual incompatible tuple pairs\"\"\"\n        error_cnt = 0\n        notes: list[str] = []\n        for i, (lhs_t, rhs_t) in enumerate(zip(lhs_types, rhs_types)):\n            if not is_subtype(rhs_t, lhs_t):\n                if error_cnt < 3:\n                    notes.append(\n                        \"Expression tuple item {} has type {}; {} expected; \".format(\n                            str(i),\n                            format_type(rhs_t, self.options),\n                            format_type(lhs_t, self.options),\n                        )\n                    )\n                error_cnt += 1\n\n        info = f\" ({str(error_cnt)} tuple items are incompatible\"\n        if error_cnt - 3 > 0:\n            info += f\"; {str(error_cnt - 3)} items are omitted)\"\n        else:\n            info += \")\"\n        msg = msg.with_additional_msg(info)\n        self.fail(msg.value, context, code=msg.code)\n        for note in notes:\n            self.note(note, context, code=msg.code)\n\n    def add_fixture_note(self, fullname: str, ctx: Context) -> None:\n        self.note(f'Maybe your test fixture does not define \"{fullname}\"?', ctx)\n        if fullname in SUGGESTED_TEST_FIXTURES:\n            self.note(\n                \"Consider adding [builtins fixtures/{}] to your test description\".format(\n                    SUGGESTED_TEST_FIXTURES[fullname]\n                ),\n                ctx,\n            )\n\n    def annotation_in_unchecked_function(self, context: Context) -> None:\n        self.note(\n            \"By default the bodies of untyped functions are not checked,\"\n            \" consider using --check-untyped-defs\",\n            context,\n            code=codes.ANNOTATION_UNCHECKED,\n        )\n\n    def type_parameters_should_be_declared(self, undeclared: list[str], context: Context) -> None:\n        names = \", \".join('\"' + n + '\"' for n in undeclared)\n        self.fail(\n            message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format(names),\n            context,\n            code=codes.VALID_TYPE,\n        )\n\n    def match_statement_inexhaustive_match(self, typ: Type, context: Context) -> None:\n        type_str = format_type(typ, self.options)\n        msg = f\"Match statement has unhandled case for values of type {type_str}\"\n        self.fail(msg, context, code=codes.EXHAUSTIVE_MATCH)\n        self.note(\n            \"If match statement is intended to be non-exhaustive, add `case _: pass`\",\n            context,\n            code=codes.EXHAUSTIVE_MATCH,\n        )\n\n    def iteration_dependent_errors(self, iter_errors: IterationDependentErrors) -> None:\n        for error_info in iter_errors.yield_uselessness_error_infos():\n            self.fail(*error_info[:2], code=error_info[2])\n        for nonoverlaps, kind, context in iter_errors.yield_nonoverlapping_types():\n            self.dangerous_comparison(\n                mypy.typeops.make_simplified_union(nonoverlaps[0]),\n                mypy.typeops.make_simplified_union(nonoverlaps[1]),\n                kind,\n                context,\n            )\n        for types, context in iter_errors.yield_revealed_type_infos():\n            self.reveal_type(mypy.typeops.make_simplified_union(types), context)\n\n\ndef quote_type_string(type_string: str) -> str:\n    \"\"\"Quotes a type representation for use in messages.\"\"\"\n    if (\n        type_string in [\"Module\", \"overloaded function\", \"<deleted>\"]\n        or type_string.startswith(\"Module \")\n        or type_string.endswith(\"?\")\n    ):\n        # These messages are easier to read if these aren't quoted.\n        return type_string\n    return f'\"{type_string}\"'\n\n\ndef should_format_arg_as_type(arg_kind: ArgKind, arg_name: str | None, verbosity: int) -> bool:\n    \"\"\"\n    Determine whether a function argument should be formatted as its Type or with name.\n    \"\"\"\n    return (arg_kind == ARG_POS and arg_name is None) or (\n        verbosity == 0 and arg_kind.is_positional()\n    )\n\n\ndef format_callable_args(\n    arg_types: list[Type],\n    arg_kinds: list[ArgKind],\n    arg_names: list[str | None],\n    format: Callable[[Type], str],\n    verbosity: int,\n) -> str:\n    \"\"\"Format a bunch of Callable arguments into a string\"\"\"\n    arg_strings = []\n    for arg_name, arg_type, arg_kind in zip(arg_names, arg_types, arg_kinds):\n        if should_format_arg_as_type(arg_kind, arg_name, verbosity):\n            arg_strings.append(format(arg_type))\n        else:\n            constructor = ARG_CONSTRUCTOR_NAMES[arg_kind]\n            if arg_kind.is_star() or arg_name is None:\n                arg_strings.append(f\"{constructor}({format(arg_type)})\")\n            else:\n                arg_strings.append(f\"{constructor}({format(arg_type)}, {repr(arg_name)})\")\n\n    return \", \".join(arg_strings)\n\n\ndef format_type_inner(\n    typ: Type,\n    verbosity: int,\n    options: Options,\n    fullnames: set[str] | None,\n    module_names: bool = False,\n    use_pretty_callable: bool = True,\n) -> str:\n    \"\"\"\n    Convert a type to a relatively short string suitable for error messages.\n\n    Args:\n      typ: type to be formatted\n      verbosity: a coarse grained control on the verbosity of the type\n      options: Options object controlling formatting\n      fullnames: a set of names that should be printed in full\n      module_names: whether to show module names for module types\n      use_pretty_callable: use pretty_callable to format Callable types.\n    \"\"\"\n\n    def format(typ: Type) -> str:\n        return format_type_inner(typ, verbosity, options, fullnames)\n\n    def format_list(types: Sequence[Type]) -> str:\n        return \", \".join(format(typ) for typ in types)\n\n    def format_union_items(types: Sequence[Type]) -> list[str]:\n        formatted = [format(typ) for typ in types if format(typ) != \"None\"]\n        if len(formatted) > MAX_UNION_ITEMS and verbosity == 0:\n            more = len(formatted) - MAX_UNION_ITEMS // 2\n            formatted = formatted[: MAX_UNION_ITEMS // 2]\n        else:\n            more = 0\n        if more:\n            formatted.append(f\"<{more} more items>\")\n        if any(format(typ) == \"None\" for typ in types):\n            formatted.append(\"None\")\n        return formatted\n\n    def format_union(types: Sequence[Type]) -> str:\n        return \" | \".join(format_union_items(types))\n\n    def format_literal_value(typ: LiteralType) -> str:\n        if typ.is_enum_literal():\n            underlying_type = format(typ.fallback)\n            return f\"{underlying_type}.{typ.value}\"\n        else:\n            return typ.value_repr()\n\n    if isinstance(typ, TypeAliasType) and typ.is_recursive:\n        if typ.alias is None:\n            type_str = \"<alias (unfixed)>\"\n        else:\n            if verbosity >= 2 or (fullnames and typ.alias.fullname in fullnames):\n                type_str = typ.alias.fullname\n            else:\n                type_str = typ.alias.name\n            if typ.args:\n                type_str += f\"[{format_list(typ.args)}]\"\n        return type_str\n\n    # TODO: always mention type alias names in errors.\n    typ = get_proper_type(typ)\n\n    if isinstance(typ, Instance):\n        itype = typ\n        # Get the short name of the type.\n        if itype.type.fullname == \"types.ModuleType\":\n            # Make some common error messages simpler and tidier.\n            base_str = \"Module\"\n            if itype.extra_attrs and itype.extra_attrs.mod_name and module_names:\n                return f'{base_str} \"{itype.extra_attrs.mod_name}\"'\n            return base_str\n        if itype.type.fullname == \"typing._SpecialForm\":\n            # This is not a real type but used for some typing-related constructs.\n            return \"<typing special form>\"\n        if verbosity >= 2 or (fullnames and itype.type.fullname in fullnames):\n            base_str = itype.type.fullname\n        else:\n            base_str = itype.type.name\n        if not itype.args:\n            if itype.type.has_type_var_tuple_type and len(itype.type.type_vars) == 1:\n                return base_str + \"[()]\"\n            # No type arguments, just return the type name\n            return base_str\n        elif itype.type.fullname == \"builtins.tuple\":\n            item_type_str = format(itype.args[0])\n            return f\"tuple[{item_type_str}, ...]\"\n        else:\n            # There are type arguments. Convert the arguments to strings.\n            return f\"{base_str}[{format_list(itype.args)}]\"\n    elif isinstance(typ, UnpackType):\n        if options.use_star_unpack():\n            return f\"*{format(typ.type)}\"\n        return f\"Unpack[{format(typ.type)}]\"\n    elif isinstance(typ, TypeVarType):\n        # This is similar to non-generic instance types.\n        fullname = scoped_type_var_name(typ)\n        if verbosity >= 2 or (fullnames and fullname in fullnames):\n            return fullname\n        return typ.name\n    elif isinstance(typ, TypeVarTupleType):\n        # This is similar to non-generic instance types.\n        fullname = scoped_type_var_name(typ)\n        if verbosity >= 2 or (fullnames and fullname in fullnames):\n            return fullname\n        return typ.name\n    elif isinstance(typ, ParamSpecType):\n        # Concatenate[..., P]\n        if typ.prefix.arg_types:\n            args = format_callable_args(\n                typ.prefix.arg_types, typ.prefix.arg_kinds, typ.prefix.arg_names, format, verbosity\n            )\n\n            return f\"[{args}, **{typ.name_with_suffix()}]\"\n        else:\n            # TODO: better disambiguate ParamSpec name clashes.\n            return typ.name_with_suffix()\n    elif isinstance(typ, TupleType):\n        # Prefer the name of the fallback class (if not tuple), as it's more informative.\n        if typ.partial_fallback.type.fullname != \"builtins.tuple\":\n            return format(typ.partial_fallback)\n        type_items = format_list(typ.items) or \"()\"\n        return f\"tuple[{type_items}]\"\n    elif isinstance(typ, TypedDictType):\n        # If the TypedDictType is named, return the name\n        if not typ.is_anonymous():\n            return format(typ.fallback)\n        items = []\n        for item_name, item_type in typ.items.items():\n            modifier = \"\"\n            if item_name not in typ.required_keys:\n                modifier += \"?\"\n            if item_name in typ.readonly_keys:\n                modifier += \"=\"\n            items.append(f\"{item_name!r}{modifier}: {format(item_type)}\")\n        return f\"TypedDict({{{', '.join(items)}}})\"\n    elif isinstance(typ, LiteralType):\n        return f\"Literal[{format_literal_value(typ)}]\"\n    elif isinstance(typ, UnionType):\n        typ = get_proper_type(ignore_last_known_values(typ))\n        if not isinstance(typ, UnionType):\n            return format(typ)\n        literal_items, union_items = separate_union_literals(typ)\n\n        # Coalesce multiple Literal[] members. This also changes output order.\n        # If there's just one Literal item, retain the original ordering.\n        if len(literal_items) > 1:\n            literal_str = \"Literal[{}]\".format(\n                \", \".join(format_literal_value(t) for t in literal_items)\n            )\n\n            if len(union_items) == 1 and isinstance(get_proper_type(union_items[0]), NoneType):\n                return f\"{literal_str} | None\"\n            elif union_items:\n                return f\"{literal_str} | {format_union(union_items)}\"\n            else:\n                return literal_str\n        else:\n            # Only print Union as Optional if the Optional wouldn't have to contain another Union\n            print_as_optional = (\n                len(typ.items) - sum(isinstance(get_proper_type(t), NoneType) for t in typ.items)\n                == 1\n            )\n            if print_as_optional:\n                rest = [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)]\n                return f\"{format(rest[0])} | None\"\n            else:\n                s = format_union(typ.items)\n            return s\n    elif isinstance(typ, NoneType):\n        return \"None\"\n    elif isinstance(typ, AnyType):\n        return \"Any\"\n    elif isinstance(typ, DeletedType):\n        return \"<deleted>\"\n    elif isinstance(typ, UninhabitedType):\n        return \"Never\"\n    elif isinstance(typ, TypeType):\n        if typ.is_type_form:\n            type_name = \"TypeForm\"\n        else:\n            type_name = \"type\"\n        return f\"{type_name}[{format(typ.item)}]\"\n    elif isinstance(typ, FunctionLike):\n        func = typ\n        if func.is_type_obj():\n            # The type of a type object type can be derived from the\n            # return type (this always works).\n            return format(TypeType.make_normalized(func.items[0].ret_type))\n        elif isinstance(func, CallableType):\n            if func.type_guard is not None:\n                return_type = f\"TypeGuard[{format(func.type_guard)}]\"\n            elif func.type_is is not None:\n                return_type = f\"TypeIs[{format(func.type_is)}]\"\n            else:\n                return_type = format(func.ret_type)\n            if func.is_ellipsis_args:\n                return f\"Callable[..., {return_type}]\"\n            param_spec = func.param_spec()\n            if param_spec is not None:\n                return f\"Callable[{format(param_spec)}, {return_type}]\"\n\n            # Use pretty format (def-style) for complex signatures with named, optional, or star args.\n            # Use compact Callable[[...], ...] only for signatures with all simple positional args.\n            if use_pretty_callable:\n                if any(\n                    not should_format_arg_as_type(kind, name, verbosity)\n                    for kind, name in zip(func.arg_kinds, func.arg_names)\n                ):\n                    return pretty_callable(func, options)\n\n            args = format_callable_args(\n                func.arg_types, func.arg_kinds, func.arg_names, format, verbosity\n            )\n            return f\"Callable[[{args}], {return_type}]\"\n        else:\n            # Use a simple representation for function types; proper\n            # function types may result in long and difficult-to-read\n            # error messages.\n            return \"overloaded function\"\n    elif isinstance(typ, UnboundType):\n        return typ.accept(TypeStrVisitor(options=options))\n    elif isinstance(typ, Parameters):\n        args = format_callable_args(typ.arg_types, typ.arg_kinds, typ.arg_names, format, verbosity)\n        return f\"[{args}]\"\n    elif typ is None:\n        raise RuntimeError(\"Type is None\")\n    else:\n        # Default case; we simply have to return something meaningful here.\n        return \"object\"\n\n\ndef collect_all_named_types(t: Type) -> list[Type]:\n    \"\"\"Return all instances/aliases/type variables that `t` contains (including `t`).\n\n    This is similar to collect_all_inner_types from typeanal but only\n    returns instances and will recurse into fallbacks.\n    \"\"\"\n    visitor = CollectAllNamedTypesQuery()\n    t.accept(visitor)\n    return visitor.types\n\n\nclass CollectAllNamedTypesQuery(TypeTraverserVisitor):\n    def __init__(self) -> None:\n        self.types: list[Type] = []\n\n    def visit_instance(self, t: Instance) -> None:\n        self.types.append(t)\n        super().visit_instance(t)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> None:\n        if t.alias and not t.is_recursive:\n            get_proper_type(t).accept(self)\n        else:\n            self.types.append(t)\n            super().visit_type_alias_type(t)\n\n    def visit_type_var(self, t: TypeVarType) -> None:\n        self.types.append(t)\n        super().visit_type_var(t)\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> None:\n        self.types.append(t)\n        super().visit_type_var_tuple(t)\n\n    def visit_param_spec(self, t: ParamSpecType) -> None:\n        self.types.append(t)\n        super().visit_param_spec(t)\n\n\ndef scoped_type_var_name(t: TypeVarLikeType) -> str:\n    if not t.id.namespace:\n        return t.name\n    # TODO: support rare cases when both TypeVar name and namespace suffix coincide.\n    *_, suffix = t.id.namespace.split(\".\")\n    return f\"{t.name}@{suffix}\"\n\n\ndef find_type_overlaps(*types: Type) -> set[str]:\n    \"\"\"Return a set of fullnames that share a short name and appear in either type.\n\n    This is used to ensure that distinct types with the same short name are printed\n    with their fullname.\n    \"\"\"\n    d: dict[str, set[str]] = {}\n    for type in types:\n        for t in collect_all_named_types(type):\n            if isinstance(t, ProperType) and isinstance(t, Instance):\n                d.setdefault(t.type.name, set()).add(t.type.fullname)\n            elif isinstance(t, TypeAliasType) and t.alias:\n                d.setdefault(t.alias.name, set()).add(t.alias.fullname)\n            else:\n                assert isinstance(t, TypeVarLikeType)\n                d.setdefault(t.name, set()).add(scoped_type_var_name(t))\n    for shortname in d.keys():\n        if f\"typing.{shortname}\" in TYPES_FOR_UNIMPORTED_HINTS:\n            d[shortname].add(f\"typing.{shortname}\")\n\n    overlaps: set[str] = set()\n    for fullnames in d.values():\n        if len(fullnames) > 1:\n            overlaps.update(fullnames)\n    return overlaps\n\n\ndef format_type(\n    typ: Type, options: Options, verbosity: int = 0, module_names: bool = False\n) -> str:\n    \"\"\"\n    Convert a type to a relatively short string suitable for error messages.\n\n    `verbosity` is a coarse-grained control on the verbosity of the type\n\n    This function returns a string appropriate for unmodified use in error\n    messages; this means that it will be quoted in most cases.  If\n    modification of the formatted string is required, callers should use\n    format_type_bare.\n    \"\"\"\n    return quote_type_string(format_type_bare(typ, options, verbosity, module_names))\n\n\ndef format_type_bare(\n    typ: Type, options: Options, verbosity: int = 0, module_names: bool = False\n) -> str:\n    \"\"\"\n    Convert a type to a relatively short string suitable for error messages.\n\n    `verbosity` is a coarse-grained control on the verbosity of the type\n    `fullnames` specifies a set of names that should be printed in full\n\n    This function will return an unquoted string.  If a caller doesn't need to\n    perform post-processing on the string output, format_type should be used\n    instead.  (The caller may want to use quote_type_string after\n    processing has happened, to maintain consistent quoting in messages.)\n    \"\"\"\n    return format_type_inner(typ, verbosity, options, find_type_overlaps(typ), module_names)\n\n\ndef format_type_distinctly(*types: Type, options: Options, bare: bool = False) -> tuple[str, ...]:\n    \"\"\"Jointly format types to distinct strings.\n\n    Increase the verbosity of the type strings until they become distinct\n    while also requiring that distinct types with the same short name are\n    formatted distinctly.\n\n    By default, the returned strings are created using format_type() and will be\n    quoted accordingly. If ``bare`` is True, the returned strings will not\n    be quoted; callers who need to do post-processing of the strings before\n    quoting them (such as prepending * or **) should use this.\n    \"\"\"\n    overlapping = find_type_overlaps(*types)\n\n    def format_single(arg: Type) -> str:\n        return format_type_inner(arg, verbosity=0, options=options, fullnames=overlapping)\n\n    min_verbosity = 0\n    # Prevent emitting weird errors like:\n    # ... has incompatible type \"Callable[[int], Child]\"; expected \"Callable[[int], Parent]\"\n    if len(types) == 2:\n        left, right = types\n        left = get_proper_type(left)\n        right = get_proper_type(right)\n        # If the right type has named arguments, they may be the reason for incompatibility.\n        # This excludes cases when right is Callable[[Something], None] without named args,\n        # because that's usually the right thing to do.\n        if (\n            isinstance(left, CallableType)\n            and isinstance(right, CallableType)\n            and any(right.arg_names)\n            and is_subtype(left, right, ignore_pos_arg_names=True)\n        ):\n            min_verbosity = 1\n\n    for verbosity in range(min_verbosity, 2):\n        strs = [\n            format_type_inner(type, verbosity=verbosity, options=options, fullnames=overlapping)\n            for type in types\n        ]\n        if len(set(strs)) == len(strs):\n            break\n    if bare:\n        return tuple(strs)\n    else:\n        return tuple(quote_type_string(s) for s in strs)\n\n\ndef pretty_class_or_static_decorator(tp: CallableType) -> str | None:\n    \"\"\"Return @classmethod or @staticmethod, if any, for the given callable type.\"\"\"\n    definition = get_func_def(tp)\n    if definition is not None and isinstance(definition, SYMBOL_FUNCBASE_TYPES):\n        if definition.is_class:\n            return \"@classmethod\"\n        if definition.is_static:\n            return \"@staticmethod\"\n    return None\n\n\ndef pretty_callable(tp: CallableType, options: Options, skip_self: bool = False) -> str:\n    \"\"\"Return a nice easily-readable representation of a callable type.\n    For example:\n        def [T <: int] f(self, x: int, y: T) -> None\n\n    If skip_self is True, print an actual callable type, as it would appear\n    when bound on an instance/class, rather than how it would appear in the\n    defining statement.\n    \"\"\"\n    s = \"\"\n    asterisk = False\n    slash = False\n    for i in range(len(tp.arg_types)):\n        if s:\n            s += \", \"\n        if tp.arg_kinds[i].is_named() and not asterisk:\n            s += \"*, \"\n            asterisk = True\n        if tp.arg_kinds[i] == ARG_STAR:\n            s += \"*\"\n            asterisk = True\n        if tp.arg_kinds[i] == ARG_STAR2:\n            s += \"**\"\n        name = tp.arg_names[i]\n        if not name and not options.reveal_verbose_types:\n            # Avoid ambiguous (and weird) formatting for anonymous args/kwargs.\n            if tp.arg_kinds[i] == ARG_STAR and isinstance(tp.arg_types[i], UnpackType):\n                name = \"args\"\n            elif tp.arg_kinds[i] == ARG_STAR2 and tp.unpack_kwargs:\n                name = \"kwargs\"\n        if name:\n            s += name + \": \"\n        type_str = format_type_bare(tp.arg_types[i], options)\n        if tp.arg_kinds[i] == ARG_STAR2 and tp.unpack_kwargs:\n            if options.reveal_verbose_types:\n                type_str = f\"Unpack[{type_str}]\"\n            else:\n                type_str = f\"**{type_str}\"\n        s += type_str\n        if tp.arg_kinds[i].is_optional():\n            s += \" = ...\"\n        if (\n            not slash\n            and tp.arg_kinds[i].is_positional()\n            and name is None\n            and (\n                i == len(tp.arg_types) - 1\n                or (tp.arg_names[i + 1] is not None or not tp.arg_kinds[i + 1].is_positional())\n            )\n        ):\n            s += \", /\"\n            slash = True\n\n    definition = get_func_def(tp)\n\n    # Extract function name, prefer the \"human-readable\" name if available.\n    func_name = None\n    if tp.name:\n        func_name = tp.name.split()[0]  # skip \"of Class\" part\n    elif isinstance(definition, FuncDef):\n        func_name = definition.name\n\n    # If we got a \"special arg\" (i.e: self, cls, etc...), prepend it to the arg list\n    first_arg = None\n    if (\n        isinstance(definition, FuncDef)\n        and hasattr(definition, \"arguments\")\n        and not tp.from_concatenate\n    ):\n        definition_arg_names = [arg.variable.name for arg in definition.arguments]\n        if len(definition_arg_names) > len(tp.arg_names) and definition_arg_names[0]:\n            first_arg = definition_arg_names[0]\n    else:\n        # TODO: avoid different logic for incremental runs.\n        first_arg = get_first_arg(tp)\n\n    if tp.is_type_obj():\n        skip_self = True\n    if first_arg and not skip_self:\n        if s:\n            s = \", \" + s\n        s = first_arg + s\n    if func_name:\n        s = f\"{func_name}({s})\"\n    else:\n        s = f\"({s})\"\n\n    s += \" -> \"\n    if tp.type_guard is not None:\n        s += f\"TypeGuard[{format_type_bare(tp.type_guard, options)}]\"\n    elif tp.type_is is not None:\n        s += f\"TypeIs[{format_type_bare(tp.type_is, options)}]\"\n    else:\n        s += format_type_bare(tp.ret_type, options)\n\n    if tp.variables:\n        tvars = []\n        for tvar in tp.variables:\n            if isinstance(tvar, TypeVarType):\n                upper_bound = get_proper_type(tvar.upper_bound)\n                if not (\n                    isinstance(upper_bound, Instance)\n                    and upper_bound.type.fullname == \"builtins.object\"\n                ):\n                    tvars.append(f\"{tvar.name}: {format_type_bare(upper_bound, options)}\")\n                elif tvar.values:\n                    tvars.append(\n                        \"{}: ({})\".format(\n                            tvar.name,\n                            \", \".join([format_type_bare(tp, options) for tp in tvar.values]),\n                        )\n                    )\n                else:\n                    tvars.append(tvar.name)\n            else:\n                # For other TypeVarLikeTypes, just use the repr\n                tvars.append(repr(tvar))\n        s = f\"[{', '.join(tvars)}] {s}\"\n    return f\"def {s}\"\n\n\ndef get_first_arg(tp: CallableType) -> str | None:\n    definition = get_func_def(tp)\n    if not isinstance(definition, FuncDef) or not definition.info or definition.is_static:\n        return None\n    return definition.original_first_arg\n\n\ndef variance_string(variance: int) -> str:\n    if variance == COVARIANT:\n        return \"covariant\"\n    elif variance == CONTRAVARIANT:\n        return \"contravariant\"\n    else:\n        return \"invariant\"\n\n\ndef get_missing_protocol_members(left: Instance, right: Instance, skip: list[str]) -> list[str]:\n    \"\"\"Find all protocol members of 'right' that are not implemented\n    (i.e. completely missing) in 'left'.\n    \"\"\"\n    assert right.type.is_protocol\n    missing: list[str] = []\n    for member in right.type.protocol_members:\n        if member in skip:\n            continue\n        if not find_member(member, left, left):\n            missing.append(member)\n    return missing\n\n\ndef get_conflict_protocol_types(\n    left: Instance, right: Instance, class_obj: bool = False, options: Options | None = None\n) -> list[tuple[str, Type, Type, bool]]:\n    \"\"\"Find members that are defined in 'left' but have incompatible types.\n    Return them as a list of ('member', 'got', 'expected', 'is_lvalue').\n    \"\"\"\n    assert right.type.is_protocol\n    conflicts: list[tuple[str, Type, Type, bool]] = []\n    for member in right.type.protocol_members:\n        if member in (\"__init__\", \"__new__\"):\n            continue\n        supertype = find_member(member, right, left)\n        assert supertype is not None\n        subtype = mypy.typeops.get_protocol_member(left, member, class_obj)\n        if not subtype:\n            continue\n        is_compat = is_subtype(subtype, supertype, ignore_pos_arg_names=True, options=options)\n        if not is_compat:\n            conflicts.append((member, subtype, supertype, False))\n        superflags = get_member_flags(member, right)\n        if IS_SETTABLE not in superflags:\n            continue\n        different_setter = False\n        if IS_EXPLICIT_SETTER in superflags:\n            set_supertype = find_member(member, right, left, is_lvalue=True)\n            if set_supertype and not is_same_type(set_supertype, supertype):\n                different_setter = True\n            supertype = set_supertype\n        if IS_EXPLICIT_SETTER in get_member_flags(member, left):\n            set_subtype = mypy.typeops.get_protocol_member(left, member, class_obj, is_lvalue=True)\n            if set_subtype and not is_same_type(set_subtype, subtype):\n                different_setter = True\n            subtype = set_subtype\n        if not is_compat and not different_setter:\n            # We already have this conflict listed, avoid duplicates.\n            continue\n        assert supertype is not None and subtype is not None\n        is_compat = is_subtype(supertype, subtype, options=options)\n        if not is_compat:\n            conflicts.append((member, subtype, supertype, different_setter))\n    return conflicts\n\n\ndef get_bad_protocol_flags(\n    left: Instance, right: Instance, class_obj: bool = False\n) -> list[tuple[str, set[int], set[int]]]:\n    \"\"\"Return all incompatible attribute flags for members that are present in both\n    'left' and 'right'.\n    \"\"\"\n    assert right.type.is_protocol\n    all_flags: list[tuple[str, set[int], set[int]]] = []\n    for member in right.type.protocol_members:\n        if find_member(member, left, left, class_obj=class_obj):\n            all_flags.append(\n                (\n                    member,\n                    get_member_flags(member, left, class_obj=class_obj),\n                    get_member_flags(member, right),\n                )\n            )\n    bad_flags = []\n    for name, subflags, superflags in all_flags:\n        if (\n            IS_CLASSVAR in subflags\n            and IS_CLASSVAR not in superflags\n            and IS_SETTABLE in superflags\n            or IS_CLASSVAR in superflags\n            and IS_CLASSVAR not in subflags\n            or IS_SETTABLE in superflags\n            and IS_SETTABLE not in subflags\n            or IS_CLASS_OR_STATIC in superflags\n            and IS_CLASS_OR_STATIC not in subflags\n            or class_obj\n            and IS_VAR in superflags\n            and IS_CLASSVAR not in subflags\n            or class_obj\n            and IS_CLASSVAR in superflags\n        ):\n            bad_flags.append((name, subflags, superflags))\n    return bad_flags\n\n\ndef capitalize(s: str) -> str:\n    \"\"\"Capitalize the first character of a string.\"\"\"\n    if s == \"\":\n        return \"\"\n    else:\n        return s[0].upper() + s[1:]\n\n\ndef extract_type(name: str) -> str:\n    \"\"\"If the argument is the name of a method (of form C.m), return\n    the type portion in quotes (e.g. \"y\"). Otherwise, return the string\n    unmodified.\n    \"\"\"\n    name = re.sub('^\"[a-zA-Z0-9_]+\" of ', \"\", name)\n    return name\n\n\ndef strip_quotes(s: str) -> str:\n    \"\"\"Strip a double quote at the beginning and end of the string, if any.\"\"\"\n    s = re.sub('^\"', \"\", s)\n    s = re.sub('\"$', \"\", s)\n    return s\n\n\ndef format_string_list(lst: list[str]) -> str:\n    assert lst\n    if len(lst) == 1:\n        return lst[0]\n    elif len(lst) <= 5:\n        return f\"{', '.join(lst[:-1])} and {lst[-1]}\"\n    else:\n        return \"%s, ... and %s (%i methods suppressed)\" % (\n            \", \".join(lst[:2]),\n            lst[-1],\n            len(lst) - 3,\n        )\n\n\ndef format_item_name_list(s: Iterable[str]) -> str:\n    lst = list(s)\n    if len(lst) <= 5:\n        return \"(\" + \", \".join([f'\"{name}\"' for name in lst]) + \")\"\n    else:\n        return \"(\" + \", \".join([f'\"{name}\"' for name in lst[:5]]) + \", ...)\"\n\n\ndef callable_name(type: FunctionLike) -> str | None:\n    name = type.get_name()\n    if name is not None and name[0] != \"<\":\n        return f'\"{name}\"'.replace(\" of \", '\" of \"')\n    return name\n\n\ndef for_function(callee: CallableType) -> str:\n    name = callable_name(callee)\n    if name is not None:\n        return f\" for {name}\"\n    return \"\"\n\n\ndef wrong_type_arg_count(low: int, high: int, act: str, name: str) -> str:\n    if low == high:\n        s = f\"{low} type arguments\"\n        if low == 0:\n            s = \"no type arguments\"\n        elif low == 1:\n            s = \"1 type argument\"\n    else:\n        s = f\"between {low} and {high} type arguments\"\n    if act == \"0\":\n        act = \"none\"\n    return f'\"{name}\" expects {s}, but {act} given'\n\n\ndef find_defining_module(modules: dict[str, MypyFile], typ: CallableType) -> MypyFile | None:\n    if not typ.definition:\n        return None\n    fullname = typ.definition.fullname\n    if \".\" in fullname:\n        for i in range(fullname.count(\".\")):\n            module_name = fullname.rsplit(\".\", i + 1)[0]\n            try:\n                return modules[module_name]\n            except KeyError:\n                pass\n        assert False, \"Couldn't determine module from CallableType\"\n    return None\n\n\n# For hard-coding suggested missing member alternatives.\nCOMMON_MISTAKES: Final[dict[str, Sequence[str]]] = {\"add\": (\"append\", \"extend\")}\n\n\ndef _real_quick_ratio(a: str, b: str) -> float:\n    # this is an upper bound on difflib.SequenceMatcher.ratio\n    # similar to difflib.SequenceMatcher.real_quick_ratio, but faster since we don't instantiate\n    al = len(a)\n    bl = len(b)\n    return 2.0 * min(al, bl) / (al + bl)\n\n\ndef best_matches(current: str, options: Collection[str], n: int) -> list[str]:\n    if not current:\n        return []\n    # narrow down options cheaply\n    options = [o for o in options if _real_quick_ratio(current, o) > 0.75]\n    if len(options) >= 50:\n        options = [o for o in options if abs(len(o) - len(current)) <= 1]\n\n    ratios = {option: difflib.SequenceMatcher(a=current, b=option).ratio() for option in options}\n    options = [option for option, ratio in ratios.items() if ratio > 0.75]\n    return sorted(options, key=lambda v: (-ratios[v], v))[:n]\n\n\ndef pretty_seq(args: Sequence[str], conjunction: str) -> str:\n    quoted = ['\"' + a + '\"' for a in args]\n    if len(quoted) == 1:\n        return quoted[0]\n    if len(quoted) == 2:\n        return f\"{quoted[0]} {conjunction} {quoted[1]}\"\n    last_sep = \", \" + conjunction + \" \"\n    return \", \".join(quoted[:-1]) + last_sep + quoted[-1]\n\n\ndef append_invariance_notes(\n    notes: list[str], arg_type: Instance, expected_type: Instance\n) -> list[str]:\n    \"\"\"Explain that the type is invariant and give notes for how to solve the issue.\"\"\"\n    invariant_type = \"\"\n    covariant_suggestion = \"\"\n    if (\n        arg_type.type.fullname == \"builtins.list\"\n        and expected_type.type.fullname == \"builtins.list\"\n        and is_subtype(arg_type.args[0], expected_type.args[0])\n    ):\n        invariant_type = \"list\"\n        covariant_suggestion = 'Consider using \"Sequence\" instead, which is covariant'\n    elif (\n        arg_type.type.fullname == \"builtins.dict\"\n        and expected_type.type.fullname == \"builtins.dict\"\n        and is_same_type(arg_type.args[0], expected_type.args[0])\n        and is_subtype(arg_type.args[1], expected_type.args[1])\n    ):\n        invariant_type = \"dict\"\n        covariant_suggestion = (\n            'Consider using \"Mapping\" instead, which is covariant in the value type'\n        )\n    if invariant_type and covariant_suggestion:\n        notes.append(\n            f'\"{invariant_type}\" is invariant -- see '\n            + \"https://mypy.readthedocs.io/en/stable/common_issues.html#variance\"\n        )\n        notes.append(covariant_suggestion)\n    return notes\n\n\ndef append_union_note(\n    notes: list[str], arg_type: UnionType, expected_type: UnionType, options: Options\n) -> list[str]:\n    \"\"\"Point to specific union item(s) that may cause failure in subtype check.\"\"\"\n    non_matching = []\n    items = flatten_nested_unions(arg_type.items)\n    if len(items) < MAX_UNION_ITEMS:\n        return notes\n    for item in items:\n        if not is_subtype(item, expected_type):\n            non_matching.append(item)\n    if non_matching:\n        types = \", \".join([format_type(typ, options) for typ in non_matching])\n        notes.append(f\"Item{plural_s(non_matching)} in the first union not in the second: {types}\")\n    return notes\n\n\ndef append_numbers_notes(\n    notes: list[str], arg_type: Instance, expected_type: Instance\n) -> list[str]:\n    \"\"\"Explain if an unsupported type from \"numbers\" is used in a subtype check.\"\"\"\n    if expected_type.type.fullname in UNSUPPORTED_NUMBERS_TYPES:\n        notes.append('Types from \"numbers\" are not supported for static type checking')\n        notes.append(\"See https://peps.python.org/pep-0484/#the-numeric-tower\")\n        notes.append(\"Consider using a protocol instead, such as typing.SupportsFloat\")\n    return notes\n\n\ndef make_inferred_type_note(\n    context: Context, subtype: Type, supertype: Type, supertype_str: str\n) -> str:\n    \"\"\"Explain that the user may have forgotten to type a variable.\n\n    The user does not expect an error if the inferred container type is the same as the return\n    type of a function and the argument type(s) are a subtype of the argument type(s) of the\n    return type. This note suggests that they add a type annotation with the return type instead\n    of relying on the inferred type.\n    \"\"\"\n    subtype = get_proper_type(subtype)\n    supertype = get_proper_type(supertype)\n    if (\n        isinstance(subtype, Instance)\n        and isinstance(supertype, Instance)\n        and subtype.type.fullname == supertype.type.fullname\n        and subtype.args\n        and supertype.args\n        and isinstance(context, ReturnStmt)\n        and isinstance(context.expr, NameExpr)\n        and isinstance(context.expr.node, Var)\n        and context.expr.node.is_inferred\n    ):\n        for subtype_arg, supertype_arg in zip(subtype.args, supertype.args):\n            if not is_subtype(subtype_arg, supertype_arg):\n                return \"\"\n        var_name = context.expr.name\n        return 'Perhaps you need a type annotation for \"{}\"? Suggestion: {}'.format(\n            var_name, supertype_str\n        )\n    return \"\"\n\n\ndef format_key_list(keys: list[str], *, short: bool = False) -> str:\n    formatted_keys = [f'\"{key}\"' for key in keys]\n    td = \"\" if short else \"TypedDict \"\n    if len(keys) == 0:\n        return f\"no {td}keys\"\n    elif len(keys) == 1:\n        return f\"{td}key {formatted_keys[0]}\"\n    else:\n        return f\"{td}keys ({', '.join(formatted_keys)})\"\n\n\ndef ignore_last_known_values(t: UnionType) -> Type:\n    \"\"\"This will avoid types like str | str in error messages.\n\n    last_known_values are kept during union simplification, but may cause\n    weird formatting for e.g. tuples of literals.\n    \"\"\"\n    union_items: list[Type] = []\n    seen_instances = set()\n    for item in t.items:\n        if isinstance(item, ProperType) and isinstance(item, Instance):\n            erased = item.copy_modified(last_known_value=None)\n            if erased in seen_instances:\n                continue\n            seen_instances.add(erased)\n            union_items.append(erased)\n        else:\n            union_items.append(item)\n    return UnionType.make_union(union_items, t.line, t.column)\n"
  },
  {
    "path": "mypy/metastore.py",
    "content": "\"\"\"Interfaces for accessing metadata.\n\nWe provide two implementations.\n * The \"classic\" file system implementation, which uses a directory\n   structure of files.\n * A hokey sqlite backed implementation, which basically simulates\n   the file system in an effort to work around poor file system performance\n   on OS X.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport binascii\nimport os\nimport time\nfrom abc import abstractmethod\nfrom collections.abc import Iterable\nfrom typing import TYPE_CHECKING, Any\n\nfrom mypy.util import os_path_join\n\nif TYPE_CHECKING:\n    # We avoid importing sqlite3 unless we are using it so we can mostly work\n    # on semi-broken pythons that are missing it.\n    import sqlite3\n\n\nclass MetadataStore:\n    \"\"\"Generic interface for metadata storage.\"\"\"\n\n    @abstractmethod\n    def getmtime(self, name: str) -> float:\n        \"\"\"Read the mtime of a metadata entry.\n\n        Raises FileNotFound if the entry does not exist.\n        \"\"\"\n\n    @abstractmethod\n    def read(self, name: str) -> bytes:\n        \"\"\"Read the contents of a metadata entry.\n\n        Raises FileNotFound if the entry does not exist.\n        \"\"\"\n\n    @abstractmethod\n    def write(self, name: str, data: bytes, mtime: float | None = None) -> bool:\n        \"\"\"Write a metadata entry.\n\n        If mtime is specified, set it as the mtime of the entry. Otherwise,\n        the current time is used.\n\n        Returns True if the entry is successfully written, False otherwise.\n        \"\"\"\n\n    @abstractmethod\n    def remove(self, name: str) -> None:\n        \"\"\"Delete a metadata entry\"\"\"\n\n    @abstractmethod\n    def commit(self) -> None:\n        \"\"\"If the backing store requires a commit, do it.\n\n        But N.B. that this is not *guaranteed* to do anything, and\n        there is no guarantee that changes are not made until it is\n        called.\n        \"\"\"\n\n    @abstractmethod\n    def list_all(self) -> Iterable[str]: ...\n\n    @abstractmethod\n    def close(self) -> None:\n        \"\"\"Release any resources held by the backing store.\"\"\"\n\n\ndef random_string() -> str:\n    return binascii.hexlify(os.urandom(8)).decode(\"ascii\")\n\n\nclass FilesystemMetadataStore(MetadataStore):\n    def __init__(self, cache_dir_prefix: str) -> None:\n        # We check startswith instead of equality because the version\n        # will have already been appended by the time the cache dir is\n        # passed here.\n        if cache_dir_prefix.startswith(os.devnull):\n            self.cache_dir_prefix = None\n        else:\n            self.cache_dir_prefix = cache_dir_prefix\n\n    def getmtime(self, name: str) -> float:\n        if not self.cache_dir_prefix:\n            raise FileNotFoundError()\n\n        return int(os.path.getmtime(os_path_join(self.cache_dir_prefix, name)))\n\n    def read(self, name: str) -> bytes:\n        assert not os.path.isabs(name), \"Don't use absolute paths!\"\n\n        if not self.cache_dir_prefix:\n            raise FileNotFoundError()\n\n        with open(os_path_join(self.cache_dir_prefix, name), \"rb\", buffering=0) as f:\n            return f.read()\n\n    def write(self, name: str, data: bytes, mtime: float | None = None) -> bool:\n        assert not os.path.isabs(name), \"Don't use absolute paths!\"\n\n        if not self.cache_dir_prefix:\n            return False\n\n        path = os_path_join(self.cache_dir_prefix, name)\n        tmp_filename = path + \".\" + random_string()\n        try:\n            os.makedirs(os.path.dirname(path), exist_ok=True)\n            with open(tmp_filename, \"wb\") as f:\n                f.write(data)\n            os.replace(tmp_filename, path)\n            if mtime is not None:\n                os.utime(path, times=(mtime, mtime))\n\n        except OSError:\n            return False\n        return True\n\n    def remove(self, name: str) -> None:\n        if not self.cache_dir_prefix:\n            raise FileNotFoundError()\n\n        os.remove(os_path_join(self.cache_dir_prefix, name))\n\n    def commit(self) -> None:\n        pass\n\n    def list_all(self) -> Iterable[str]:\n        if not self.cache_dir_prefix:\n            return\n\n        for dir, _, files in os.walk(self.cache_dir_prefix):\n            dir = os.path.relpath(dir, self.cache_dir_prefix)\n            for file in files:\n                yield os.path.normpath(os_path_join(dir, file))\n\n    def close(self) -> None:\n        pass\n\n\nSCHEMA = \"\"\"\nCREATE TABLE IF NOT EXISTS files2 (\n    path TEXT UNIQUE NOT NULL,\n    mtime REAL,\n    data BLOB\n);\nCREATE INDEX IF NOT EXISTS path_idx on files2(path);\n\"\"\"\n\n\ndef connect_db(db_file: str, sync_off: bool = False) -> sqlite3.Connection:\n    import sqlite3.dbapi2\n\n    db = sqlite3.dbapi2.connect(db_file)\n    if sync_off:\n        # This is a bit unfortunate (as we may get corrupt cache after e.g. Ctrl + C),\n        # but without this flag, commits are *very* slow, especially when using HDDs,\n        # see https://www.sqlite.org/faq.html#q19 for details.\n        db.execute(\"PRAGMA synchronous=OFF\")\n    db.executescript(SCHEMA)\n    return db\n\n\nclass SqliteMetadataStore(MetadataStore):\n    def __init__(self, cache_dir_prefix: str, sync_off: bool = False) -> None:\n        # We check startswith instead of equality because the version\n        # will have already been appended by the time the cache dir is\n        # passed here.\n        if cache_dir_prefix.startswith(os.devnull):\n            self.db = None\n            return\n\n        os.makedirs(cache_dir_prefix, exist_ok=True)\n        self.db = connect_db(os_path_join(cache_dir_prefix, \"cache.db\"), sync_off=sync_off)\n\n    def _query(self, name: str, field: str) -> Any:\n        # Raises FileNotFound for consistency with the file system version\n        if not self.db:\n            raise FileNotFoundError()\n\n        cur = self.db.execute(f\"SELECT {field} FROM files2 WHERE path = ?\", (name,))\n        results = cur.fetchall()\n        if not results:\n            raise FileNotFoundError()\n        assert len(results) == 1\n        return results[0][0]\n\n    def getmtime(self, name: str) -> float:\n        mtime = self._query(name, \"mtime\")\n        assert isinstance(mtime, float)\n        return mtime\n\n    def read(self, name: str) -> bytes:\n        data = self._query(name, \"data\")\n        assert isinstance(data, bytes)\n        return data\n\n    def write(self, name: str, data: bytes, mtime: float | None = None) -> bool:\n        import sqlite3\n\n        if not self.db:\n            return False\n        try:\n            if mtime is None:\n                mtime = time.time()\n            self.db.execute(\n                \"INSERT OR REPLACE INTO files2(path, mtime, data) VALUES(?, ?, ?)\",\n                (name, mtime, data),\n            )\n        except sqlite3.OperationalError:\n            return False\n        return True\n\n    def remove(self, name: str) -> None:\n        if not self.db:\n            raise FileNotFoundError()\n\n        self.db.execute(\"DELETE FROM files2 WHERE path = ?\", (name,))\n\n    def commit(self) -> None:\n        if self.db:\n            self.db.commit()\n\n    def list_all(self) -> Iterable[str]:\n        if self.db:\n            for row in self.db.execute(\"SELECT path FROM files2\"):\n                yield row[0]\n\n    def close(self) -> None:\n        if self.db:\n            db = self.db\n            self.db = None\n            db.close()\n\n    def __del__(self) -> None:\n        self.close()\n"
  },
  {
    "path": "mypy/mixedtraverser.py",
    "content": "from __future__ import annotations\n\nfrom mypy.nodes import (\n    AssertTypeExpr,\n    AssignmentStmt,\n    CastExpr,\n    ClassDef,\n    ForStmt,\n    FuncItem,\n    NamedTupleExpr,\n    NewTypeExpr,\n    PromoteExpr,\n    TypeAlias,\n    TypeAliasExpr,\n    TypeAliasStmt,\n    TypeApplication,\n    TypedDictExpr,\n    TypeFormExpr,\n    TypeVarExpr,\n    Var,\n    WithStmt,\n)\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.types import Type\nfrom mypy.typetraverser import TypeTraverserVisitor\n\n\nclass MixedTraverserVisitor(TraverserVisitor, TypeTraverserVisitor):\n    \"\"\"Recursive traversal of both Node and Type objects.\"\"\"\n\n    def __init__(self) -> None:\n        self.in_type_alias_expr = False\n\n    # Symbol nodes\n\n    def visit_var(self, var: Var, /) -> None:\n        self.visit_optional_type(var.type)\n\n    def visit_func(self, o: FuncItem, /) -> None:\n        super().visit_func(o)\n        self.visit_optional_type(o.type)\n\n    def visit_class_def(self, o: ClassDef, /) -> None:\n        # TODO: Should we visit generated methods/variables as well, either here or in\n        #       TraverserVisitor?\n        super().visit_class_def(o)\n        info = o.info\n        if info:\n            for base in info.bases:\n                base.accept(self)\n            if info.special_alias:\n                info.special_alias.accept(self)\n\n    def visit_type_alias_expr(self, o: TypeAliasExpr, /) -> None:\n        super().visit_type_alias_expr(o)\n        o.node.accept(self)\n\n    def visit_type_var_expr(self, o: TypeVarExpr, /) -> None:\n        super().visit_type_var_expr(o)\n        o.upper_bound.accept(self)\n        o.default.accept(self)\n        for value in o.values:\n            value.accept(self)\n\n    def visit_typeddict_expr(self, o: TypedDictExpr, /) -> None:\n        super().visit_typeddict_expr(o)\n        self.visit_optional_type(o.info.typeddict_type)\n\n    def visit_namedtuple_expr(self, o: NamedTupleExpr, /) -> None:\n        super().visit_namedtuple_expr(o)\n        assert o.info.tuple_type\n        o.info.tuple_type.accept(self)\n\n    def visit__promote_expr(self, o: PromoteExpr, /) -> None:\n        super().visit__promote_expr(o)\n        o.type.accept(self)\n\n    def visit_newtype_expr(self, o: NewTypeExpr, /) -> None:\n        super().visit_newtype_expr(o)\n        self.visit_optional_type(o.old_type)\n\n    # Statements\n\n    def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None:\n        super().visit_assignment_stmt(o)\n        self.visit_optional_type(o.type)\n\n    def visit_type_alias_stmt(self, o: TypeAliasStmt, /) -> None:\n        super().visit_type_alias_stmt(o)\n        if o.alias_node is not None:\n            o.alias_node.accept(self)\n\n    def visit_type_alias(self, o: TypeAlias, /) -> None:\n        super().visit_type_alias(o)\n        self.in_type_alias_expr = True\n        o.target.accept(self)\n        self.in_type_alias_expr = False\n\n    def visit_for_stmt(self, o: ForStmt, /) -> None:\n        super().visit_for_stmt(o)\n        self.visit_optional_type(o.index_type)\n\n    def visit_with_stmt(self, o: WithStmt, /) -> None:\n        super().visit_with_stmt(o)\n        for typ in o.analyzed_types:\n            typ.accept(self)\n\n    # Expressions\n\n    def visit_cast_expr(self, o: CastExpr, /) -> None:\n        super().visit_cast_expr(o)\n        o.type.accept(self)\n\n    def visit_type_form_expr(self, o: TypeFormExpr, /) -> None:\n        super().visit_type_form_expr(o)\n        o.type.accept(self)\n\n    def visit_assert_type_expr(self, o: AssertTypeExpr, /) -> None:\n        super().visit_assert_type_expr(o)\n        o.type.accept(self)\n\n    def visit_type_application(self, o: TypeApplication, /) -> None:\n        super().visit_type_application(o)\n        for t in o.types:\n            t.accept(self)\n\n    # Helpers\n\n    def visit_optional_type(self, t: Type | None, /) -> None:\n        if t:\n            t.accept(self)\n"
  },
  {
    "path": "mypy/modulefinder.py",
    "content": "\"\"\"Low-level infrastructure to find modules.\n\nThis builds on fscache.py; find_sources.py builds on top of this.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport ast\nimport collections\nimport functools\nimport os\nimport re\nimport subprocess\nimport sys\nfrom enum import Enum, unique\nfrom typing import Final, TypeAlias as _TypeAlias\n\nfrom pathspec import PathSpec\nfrom pathspec.patterns.gitignore import GitIgnorePatternError\n\nfrom mypy import pyinfo\nfrom mypy.errors import CompileError\nfrom mypy.fscache import FileSystemCache\nfrom mypy.nodes import MypyFile\nfrom mypy.options import Options\nfrom mypy.stubinfo import stub_distribution_name\nfrom mypy.util import os_path_join\n\n\n# Paths to be searched in find_module().\nclass SearchPaths:\n    def __init__(\n        self,\n        python_path: tuple[str, ...],\n        mypy_path: tuple[str, ...],\n        package_path: tuple[str, ...],\n        typeshed_path: tuple[str, ...],\n    ) -> None:\n        # where user code is found\n        self.python_path = tuple(map(os.path.abspath, python_path))\n        # from $MYPYPATH or config variable\n        self.mypy_path = tuple(map(os.path.abspath, mypy_path))\n        # from get_site_packages_dirs()\n        self.package_path = tuple(map(os.path.abspath, package_path))\n        # paths in typeshed\n        self.typeshed_path = tuple(map(os.path.abspath, typeshed_path))\n\n    def asdict(self) -> dict[str, tuple[str, ...]]:\n        return {\n            \"python_path\": self.python_path,\n            \"mypy_path\": self.mypy_path,\n            \"package_path\": self.package_path,\n            \"typeshed_path\": self.typeshed_path,\n        }\n\n\n# Package dirs are a two-tuple of path to search and whether to verify the module\nOnePackageDir = tuple[str, bool]\nPackageDirs = list[OnePackageDir]\n\n# Minimum and maximum Python versions for modules in stdlib as (major, minor)\nStdlibVersions: _TypeAlias = dict[str, tuple[tuple[int, int], tuple[int, int] | None]]\n\nPYTHON_EXTENSIONS: Final = [\".pyi\", \".py\"]\n\n\n# TODO: Consider adding more reasons here?\n# E.g. if we deduce a module would likely be found if the user were\n# to set the --namespace-packages flag.\n@unique\nclass ModuleNotFoundReason(Enum):\n    # The module was not found: we found neither stubs nor a plausible code\n    # implementation (with or without a py.typed file).\n    NOT_FOUND = 0\n\n    # The implementation for this module plausibly exists (e.g. we\n    # found a matching folder or *.py file), but either the parent package\n    # did not contain a py.typed file or we were unable to find a\n    # corresponding *-stubs package.\n    FOUND_WITHOUT_TYPE_HINTS = 1\n\n    # The module was not found in the current working directory, but\n    # was able to be found in the parent directory.\n    WRONG_WORKING_DIRECTORY = 2\n\n    # Stub PyPI package (typically types-pkgname) known to exist but not installed.\n    APPROVED_STUBS_NOT_INSTALLED = 3\n\n    def error_message_templates(self, daemon: bool) -> tuple[str, list[str]]:\n        doc_link = \"See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\"\n        if self is ModuleNotFoundReason.NOT_FOUND:\n            msg = 'Cannot find implementation or library stub for module named \"{module}\"'\n            notes = [doc_link]\n        elif self is ModuleNotFoundReason.WRONG_WORKING_DIRECTORY:\n            msg = 'Cannot find implementation or library stub for module named \"{module}\"'\n            notes = [\n                \"You may be running mypy in a subpackage, mypy should be run on the package root\"\n            ]\n        elif self is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS:\n            msg = (\n                'Skipping analyzing \"{module}\": module is installed, but missing library stubs '\n                \"or py.typed marker\"\n            )\n            notes = [doc_link]\n        elif self is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:\n            msg = 'Library stubs not installed for \"{module}\"'\n            notes = ['Hint: \"python3 -m pip install {stub_dist}\"']\n            if not daemon:\n                notes.append(\n                    '(or run \"mypy --install-types\" to install all missing stub packages)'\n                )\n            notes.append(doc_link)\n        else:\n            assert False\n        return msg, notes\n\n\n# If we found the module, returns the path to the module as a str.\n# Otherwise, returns the reason why the module wasn't found.\nModuleSearchResult = str | ModuleNotFoundReason\n\n\nclass BuildSource:\n    \"\"\"A single source file.\"\"\"\n\n    def __init__(\n        self,\n        path: str | None,\n        module: str | None,\n        text: str | None = None,\n        base_dir: str | None = None,\n        followed: bool = False,\n    ) -> None:\n        self.path = path  # File where it's found (e.g. 'xxx/yyy/foo/bar.py')\n        self.module = module or \"__main__\"  # Module name (e.g. 'foo.bar')\n        self.text = text  # Source code, if initially supplied, else None\n        self.base_dir = base_dir  # Directory where the package is rooted (e.g. 'xxx/yyy')\n        self.followed = followed  # Was this found by following imports?\n\n    def __repr__(self) -> str:\n        return (\n            \"BuildSource(path={!r}, module={!r}, has_text={}, base_dir={!r}, followed={})\".format(\n                self.path, self.module, self.text is not None, self.base_dir, self.followed\n            )\n        )\n\n\nclass BuildSourceSet:\n    \"\"\"Helper to efficiently test a file's membership in a set of build sources.\"\"\"\n\n    def __init__(self, sources: list[BuildSource]) -> None:\n        self.source_text_present = False\n        self.source_modules: dict[str, str] = {}\n        self.source_paths: set[str] = set()\n\n        for source in sources:\n            if source.text is not None:\n                self.source_text_present = True\n            if source.path:\n                self.source_paths.add(source.path)\n            if source.module:\n                self.source_modules[source.module] = source.path or \"\"\n\n    def is_source(self, file: MypyFile) -> bool:\n        return (\n            (file.path and file.path in self.source_paths)\n            or file._fullname in self.source_modules\n            or self.source_text_present\n        )\n\n\nclass FindModuleCache:\n    \"\"\"Module finder with integrated cache.\n\n    Module locations and some intermediate results are cached internally\n    and can be cleared with the clear() method.\n\n    All file system accesses are performed through a FileSystemCache,\n    which is not ever cleared by this class. If necessary it must be\n    cleared by client code.\n    \"\"\"\n\n    def __init__(\n        self,\n        search_paths: SearchPaths,\n        fscache: FileSystemCache | None,\n        options: Options | None,\n        stdlib_py_versions: StdlibVersions | None = None,\n        source_set: BuildSourceSet | None = None,\n    ) -> None:\n        self.search_paths = search_paths\n        self.source_set = source_set\n        self.fscache = fscache or FileSystemCache()\n        # Cache for get_toplevel_possibilities:\n        # search_paths -> (toplevel_id -> list(package_dirs))\n        self.initial_components: dict[tuple[str, ...], dict[str, list[str]]] = {}\n        # Cache find_module: id -> result\n        self.results: dict[str, ModuleSearchResult] = {}\n        self.ns_ancestors: dict[str, str] = {}\n        self.options = options\n        custom_typeshed_dir = None\n        if options:\n            custom_typeshed_dir = options.custom_typeshed_dir\n        self.stdlib_py_versions = stdlib_py_versions or load_stdlib_py_versions(\n            custom_typeshed_dir\n        )\n\n    def clear(self) -> None:\n        self.results.clear()\n        self.initial_components.clear()\n        self.ns_ancestors.clear()\n\n    def find_module_via_source_set(self, id: str) -> ModuleSearchResult | None:\n        \"\"\"Fast path to find modules by looking through the input sources\n\n        This is only used when --fast-module-lookup is passed on the command line.\"\"\"\n        if not self.source_set:\n            return None\n\n        p = self.source_set.source_modules.get(id, None)\n        if p and self.fscache.isfile(p):\n            # We need to make sure we still have __init__.py all the way up\n            # otherwise we might have false positives compared to slow path\n            # in case of deletion of init files, which is covered by some tests.\n            # TODO: are there some combination of flags in which this check should be skipped?\n            d = os.path.dirname(p)\n            for _ in range(id.count(\".\")):\n                if not any(\n                    self.fscache.isfile(os_path_join(d, \"__init__\" + x)) for x in PYTHON_EXTENSIONS\n                ):\n                    return None\n                d = os.path.dirname(d)\n            return p\n\n        idx = id.rfind(\".\")\n        if idx != -1:\n            # When we're looking for foo.bar.baz and can't find a matching module\n            # in the source set, look up for a foo.bar module.\n            parent = self.find_module_via_source_set(id[:idx])\n            if parent is None or not isinstance(parent, str):\n                return None\n\n            basename, ext = os.path.splitext(parent)\n            if not any(parent.endswith(\"__init__\" + x) for x in PYTHON_EXTENSIONS) and (\n                ext in PYTHON_EXTENSIONS and not self.fscache.isdir(basename)\n            ):\n                # If we do find such a *module* (and crucially, we don't want a package,\n                # hence the filtering out of __init__ files, and checking for the presence\n                # of a folder with a matching name), then we can be pretty confident that\n                # 'baz' will either be a top-level variable in foo.bar, or will not exist.\n                #\n                # Either way, spelunking in other search paths for another 'foo.bar.baz'\n                # module should be avoided because:\n                #  1. in the unlikely event that one were found, it's highly likely that\n                #     it would be unrelated to the source being typechecked and therefore\n                #     more likely to lead to erroneous results\n                #  2. as described in _find_module, in some cases the search itself could\n                #  potentially waste significant amounts of time\n                return ModuleNotFoundReason.NOT_FOUND\n        return None\n\n    def find_lib_path_dirs(self, id: str, lib_path: tuple[str, ...]) -> PackageDirs:\n        \"\"\"Find which elements of a lib_path have the directory a module needs to exist.\"\"\"\n        components = id.split(\".\")\n        dir_chain = os.sep.join(components[:-1])  # e.g., 'foo/bar'\n\n        dirs = []\n        for pathitem in self.get_toplevel_possibilities(lib_path, components[0]):\n            # e.g., '/usr/lib/python3.4/foo/bar'\n            if dir_chain:\n                dir = os_path_join(pathitem, dir_chain)\n            else:\n                dir = pathitem\n            if self.fscache.isdir(dir):\n                dirs.append((dir, True))\n        return dirs\n\n    def get_toplevel_possibilities(self, lib_path: tuple[str, ...], id: str) -> list[str]:\n        \"\"\"Find which elements of lib_path could contain a particular top-level module.\n\n        In practice, almost all modules can be routed to the correct entry in\n        lib_path by looking at just the first component of the module name.\n\n        We take advantage of this by enumerating the contents of all of the\n        directories on the lib_path and building a map of which entries in\n        the lib_path could contain each potential top-level module that appears.\n        \"\"\"\n\n        if lib_path in self.initial_components:\n            return self.initial_components[lib_path].get(id, [])\n\n        # Enumerate all the files in the directories on lib_path and produce the map\n        components: dict[str, list[str]] = {}\n        for dir in lib_path:\n            try:\n                contents = self.fscache.listdir(dir)\n            except OSError:\n                contents = []\n            # False positives are fine for correctness here, since we will check\n            # precisely later, so we only look at the root of every filename without\n            # any concern for the exact details.\n            for name in contents:\n                name = os.path.splitext(name)[0]\n                components.setdefault(name, []).append(dir)\n\n        self.initial_components[lib_path] = components\n        return components.get(id, [])\n\n    def find_module(self, id: str, *, fast_path: bool = False) -> ModuleSearchResult:\n        \"\"\"Return the path of the module source file or why it wasn't found.\n\n        If fast_path is True, prioritize performance over generating detailed\n        error descriptions.\n        \"\"\"\n        if id not in self.results:\n            top_level = id.partition(\".\")[0]\n            use_typeshed = True\n            if id in self.stdlib_py_versions:\n                use_typeshed = self._typeshed_has_version(id)\n            elif top_level in self.stdlib_py_versions:\n                use_typeshed = self._typeshed_has_version(top_level)\n            result, should_cache = self._find_module(id, use_typeshed)\n            if should_cache:\n                if (\n                    not (\n                        fast_path or (self.options is not None and self.options.fast_module_lookup)\n                    )\n                    and result is ModuleNotFoundReason.NOT_FOUND\n                    and self._can_find_module_in_parent_dir(id)\n                ):\n                    self.results[id] = ModuleNotFoundReason.WRONG_WORKING_DIRECTORY\n                else:\n                    self.results[id] = result\n                return self.results[id]\n            else:\n                return result\n        return self.results[id]\n\n    def _typeshed_has_version(self, module: str) -> bool:\n        if not self.options:\n            return True\n        version = typeshed_py_version(self.options)\n        min_version, max_version = self.stdlib_py_versions[module]\n        return version >= min_version and (max_version is None or version <= max_version)\n\n    def _find_module_non_stub_helper(\n        self, id: str, pkg_dir: str\n    ) -> OnePackageDir | ModuleNotFoundReason:\n        plausible_match = False\n        dir_path = pkg_dir\n        components = id.split(\".\")\n        for index, component in enumerate(components):\n            dir_path = os_path_join(dir_path, component)\n            if self.fscache.isfile(os_path_join(dir_path, \"py.typed\")):\n                return os.path.join(pkg_dir, *components[:-1]), index == 0\n            elif not plausible_match and (\n                self.fscache.isdir(dir_path) or self.fscache.isfile(dir_path + \".py\")\n            ):\n                plausible_match = True\n            # If this is not a directory then we can't traverse further into it\n            if not self.fscache.isdir(dir_path):\n                break\n        if plausible_match:\n            if self.options:\n                module_specific_options = self.options.clone_for_module(id)\n                if module_specific_options.follow_untyped_imports:\n                    return os.path.join(pkg_dir, *components[:-1]), False\n            return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS\n        else:\n            return ModuleNotFoundReason.NOT_FOUND\n\n    def _update_ns_ancestors(self, components: list[str], match: tuple[str, bool]) -> None:\n        path, verify = match\n        for i in range(1, len(components)):\n            pkg_id = \".\".join(components[:-i])\n            if pkg_id not in self.ns_ancestors and self.fscache.isdir(path):\n                self.ns_ancestors[pkg_id] = path\n            path = os.path.dirname(path)\n\n    def _can_find_module_in_parent_dir(self, id: str) -> bool:\n        \"\"\"Test if a module can be found by checking the parent directories\n        of the current working directory.\n        \"\"\"\n        working_dir = os.getcwd()\n        parent_search = FindModuleCache(\n            SearchPaths((), (), (), ()),\n            self.fscache,\n            self.options,\n            stdlib_py_versions=self.stdlib_py_versions,\n        )\n        while any(is_init_file(file) for file in os.listdir(working_dir)):\n            working_dir = os.path.dirname(working_dir)\n            parent_search.search_paths = SearchPaths((working_dir,), (), (), ())\n            if not isinstance(parent_search._find_module(id, False)[0], ModuleNotFoundReason):\n                return True\n        return False\n\n    def _find_module(self, id: str, use_typeshed: bool) -> tuple[ModuleSearchResult, bool]:\n        \"\"\"Try to find a module in all available sources.\n\n        Returns:\n            ``(result, can_be_cached)`` pair.\n        \"\"\"\n        fscache = self.fscache\n\n        # Fast path for any modules in the current source set.\n        # This is particularly important when there are a large number of search\n        # paths which share the first (few) component(s) due to the use of namespace\n        # packages, for instance:\n        # foo/\n        #    company/\n        #        __init__.py\n        #        foo/\n        # bar/\n        #    company/\n        #        __init__.py\n        #        bar/\n        # baz/\n        #    company/\n        #        __init__.py\n        #        baz/\n        #\n        # mypy gets [foo/company/foo, bar/company/bar, baz/company/baz, ...] as input\n        # and computes [foo, bar, baz, ...] as the module search path.\n        #\n        # This would result in O(n) search for every import of company.*, leading to\n        # O(n**2) behavior in load_graph as such imports are unsurprisingly present\n        # at least once, and usually many more times than that, in each and every file\n        # being parsed.\n        #\n        # Thankfully, such cases are efficiently handled by looking up the module path\n        # via BuildSourceSet.\n        p = (\n            self.find_module_via_source_set(id)\n            if (self.options is not None and self.options.fast_module_lookup)\n            else None\n        )\n        if p:\n            return p, True\n\n        # If we're looking for a module like 'foo.bar.baz', it's likely that most of the\n        # many elements of lib_path don't even have a subdirectory 'foo/bar'.  Discover\n        # that only once and cache it for when we look for modules like 'foo.bar.blah'\n        # that will require the same subdirectory.\n        components = id.split(\".\")\n        dir_chain = os.sep.join(components[:-1])  # e.g., 'foo/bar'\n\n        # We have two sets of folders so that we collect *all* stubs folders and\n        # put them in the front of the search path\n        third_party_inline_dirs: PackageDirs = []\n        third_party_stubs_dirs: PackageDirs = []\n        found_possible_third_party_missing_type_hints = False\n        # Third-party stub/typed packages\n        candidate_package_dirs = {\n            package_dir[0]\n            for component in (components[0], components[0] + \"-stubs\")\n            for package_dir in self.find_lib_path_dirs(component, self.search_paths.package_path)\n        }\n        # Caching FOUND_WITHOUT_TYPE_HINTS is not always safe. That causes issues with\n        # typed subpackages in namespace packages.\n        can_cache_any_result = True\n        for pkg_dir in self.search_paths.package_path:\n            if pkg_dir not in candidate_package_dirs:\n                continue\n            stub_name = components[0] + \"-stubs\"\n            stub_dir = os_path_join(pkg_dir, stub_name)\n            if fscache.isdir(stub_dir):\n                stub_typed_file = os_path_join(stub_dir, \"py.typed\")\n                stub_components = [stub_name] + components[1:]\n                path = os.path.join(pkg_dir, *stub_components[:-1])\n                if fscache.isdir(path):\n                    if fscache.isfile(stub_typed_file):\n                        # Stub packages can have a py.typed file, which must include\n                        # 'partial\\n' to make the package partial.\n                        # Partial here means that mypy should look at the runtime\n                        # package if installed.\n                        if fscache.read(stub_typed_file).decode().strip() == \"partial\":\n                            runtime_path = os_path_join(pkg_dir, dir_chain)\n                            third_party_inline_dirs.append((runtime_path, True))\n                            # if the package is partial, we don't verify the module, as\n                            # the partial stub package may not have a __init__.pyi\n                            third_party_stubs_dirs.append((path, False))\n                        else:\n                            # handle the edge case where people put a py.typed file\n                            # in a stub package, but it isn't partial\n                            third_party_stubs_dirs.append((path, True))\n                    else:\n                        third_party_stubs_dirs.append((path, True))\n            non_stub_match = self._find_module_non_stub_helper(id, pkg_dir)\n            if isinstance(non_stub_match, ModuleNotFoundReason):\n                if non_stub_match is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS:\n                    found_possible_third_party_missing_type_hints = True\n                    can_cache_any_result = False\n            else:\n                third_party_inline_dirs.append(non_stub_match)\n                self._update_ns_ancestors(components, non_stub_match)\n\n        if self.options and self.options.use_builtins_fixtures:\n            # Everything should be in fixtures.\n            third_party_inline_dirs.clear()\n            third_party_stubs_dirs.clear()\n            found_possible_third_party_missing_type_hints = False\n        python_mypy_path = self.search_paths.mypy_path + self.search_paths.python_path\n        candidate_base_dirs = self.find_lib_path_dirs(id, python_mypy_path)\n        if use_typeshed:\n            # Search for stdlib stubs in typeshed before installed\n            # stubs to avoid picking up backports (dataclasses, for\n            # example) when the library is included in stdlib.\n            candidate_base_dirs += self.find_lib_path_dirs(id, self.search_paths.typeshed_path)\n        candidate_base_dirs += third_party_stubs_dirs + third_party_inline_dirs\n\n        # If we're looking for a module like 'foo.bar.baz', then candidate_base_dirs now\n        # contains just the subdirectories 'foo/bar' that actually exist under the\n        # elements of lib_path.  This is probably much shorter than lib_path itself.\n        # Now just look for 'baz.pyi', 'baz/__init__.py', etc., inside those directories.\n        seplast = os.sep + components[-1]  # so e.g. '/baz'\n        sepinit = os.sep + \"__init__\"\n        near_misses = []  # Collect near misses for namespace mode (see below).\n        for base_dir, verify in candidate_base_dirs:\n            base_path = base_dir + seplast  # so e.g. '/usr/lib/python3.4/foo/bar/baz'\n            has_init = False\n            dir_prefix = base_dir\n            for _ in range(len(components) - 1):\n                dir_prefix = os.path.dirname(dir_prefix)\n\n            # Stubs-only packages always take precedence over py.typed packages\n            path_stubs = f\"{base_path}-stubs{sepinit}.pyi\"\n            if fscache.isfile_case(path_stubs, dir_prefix):\n                if verify and not verify_module(fscache, id, path_stubs, dir_prefix):\n                    near_misses.append((path_stubs, dir_prefix))\n                else:\n                    return path_stubs, True\n\n            # Prefer package over module, i.e. baz/__init__.py* over baz.py*.\n            for extension in PYTHON_EXTENSIONS:\n                path = base_path + sepinit + extension\n                if fscache.isfile_case(path, dir_prefix):\n                    has_init = True\n                    if verify and not verify_module(fscache, id, path, dir_prefix):\n                        near_misses.append((path, dir_prefix))\n                        continue\n                    return path, True\n\n            # In namespace mode, register a potential namespace package\n            if self.options and self.options.namespace_packages:\n                if (\n                    not has_init\n                    and fscache.exists_case(base_path, dir_prefix)\n                    and not fscache.isfile_case(base_path, dir_prefix)\n                ):\n                    near_misses.append((base_path, dir_prefix))\n\n            # No package, look for module.\n            for extension in PYTHON_EXTENSIONS:\n                path = base_path + extension\n                if fscache.isfile_case(path, dir_prefix):\n                    if verify and not verify_module(fscache, id, path, dir_prefix):\n                        near_misses.append((path, dir_prefix))\n                        continue\n                    return path, True\n\n        # In namespace mode, re-check those entries that had 'verify'.\n        # Assume search path entries xxx, yyy and zzz, and we're\n        # looking for foo.bar.baz.  Suppose near_misses has:\n        #\n        # - xxx/foo/bar/baz.py\n        # - yyy/foo/bar/baz/__init__.py\n        # - zzz/foo/bar/baz.pyi\n        #\n        # If any of the foo directories has __init__.py[i], it wins.\n        # Else, we look for foo/bar/__init__.py[i], etc.  If there are\n        # none, the first hit wins.  Note that this does not take into\n        # account whether the lowest-level module is a file (baz.py),\n        # a package (baz/__init__.py), or a stub file (baz.pyi) -- for\n        # these the first one encountered along the search path wins.\n        #\n        # The helper function highest_init_level() returns an int that\n        # indicates the highest level at which a __init__.py[i] file\n        # is found; if no __init__ was found it returns 0, if we find\n        # only foo/bar/__init__.py it returns 1, and if we have\n        # foo/__init__.py it returns 2 (regardless of what's in\n        # foo/bar).  It doesn't look higher than that.\n        if self.options and self.options.namespace_packages and near_misses:\n            levels = [\n                highest_init_level(fscache, id, path, dir_prefix)\n                for path, dir_prefix in near_misses\n            ]\n            index = levels.index(max(levels))\n            return near_misses[index][0], True\n\n        # Finally, we may be asked to produce an ancestor for an\n        # installed package with a py.typed marker that is a\n        # subpackage of a namespace package.  We only fess up to these\n        # if we would otherwise return \"not found\".\n        ancestor = self.ns_ancestors.get(id)\n        if ancestor is not None:\n            return ancestor, True\n\n        approved_dist_name = stub_distribution_name(id)\n        if approved_dist_name:\n            if len(components) == 1:\n                return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True\n            # If we're a missing submodule of an already installed approved stubs, we don't want to\n            # error with APPROVED_STUBS_NOT_INSTALLED, but rather want to return NOT_FOUND.\n            for i in range(1, len(components)):\n                parent_id = \".\".join(components[:i])\n                if stub_distribution_name(parent_id) == approved_dist_name:\n                    break\n            else:\n                return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True\n            if self.find_module(parent_id) is ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED:\n                return ModuleNotFoundReason.APPROVED_STUBS_NOT_INSTALLED, True\n            return ModuleNotFoundReason.NOT_FOUND, True\n\n        if found_possible_third_party_missing_type_hints:\n            return ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS, can_cache_any_result\n        return ModuleNotFoundReason.NOT_FOUND, True\n\n    def find_modules_recursive(self, module: str) -> list[BuildSource]:\n        module_path = self.find_module(module, fast_path=True)\n        if isinstance(module_path, ModuleNotFoundReason):\n            return []\n        sources = [BuildSource(module_path, module, None)]\n\n        package_path = None\n        if is_init_file(module_path):\n            package_path = os.path.dirname(module_path)\n        elif self.fscache.isdir(module_path):\n            package_path = module_path\n        if package_path is None:\n            return sources\n\n        # This logic closely mirrors that in find_sources. One small but important difference is\n        # that we do not sort names with keyfunc. The recursive call to find_modules_recursive\n        # calls find_module, which will handle the preference between packages, pyi and py.\n        # Another difference is it doesn't handle nested search paths / package roots.\n\n        seen: set[str] = set()\n        names = sorted(self.fscache.listdir(package_path))\n        for name in names:\n            # Skip certain names altogether\n            if name in (\"__pycache__\", \"site-packages\", \"node_modules\") or name.startswith(\".\"):\n                continue\n            subpath = os_path_join(package_path, name)\n\n            if self.options and matches_exclude(\n                subpath, self.options.exclude, self.fscache, self.options.verbosity >= 2\n            ):\n                continue\n            if (\n                self.options\n                and self.options.exclude_gitignore\n                and matches_gitignore(subpath, self.fscache, self.options.verbosity >= 2)\n            ):\n                continue\n\n            if self.fscache.isdir(subpath):\n                # Only recurse into packages\n                if (self.options and self.options.namespace_packages) or (\n                    self.fscache.isfile(os_path_join(subpath, \"__init__.py\"))\n                    or self.fscache.isfile(os_path_join(subpath, \"__init__.pyi\"))\n                ):\n                    seen.add(name)\n                    sources.extend(self.find_modules_recursive(module + \".\" + name))\n            else:\n                stem, suffix = os.path.splitext(name)\n                if stem == \"__init__\":\n                    continue\n                if stem not in seen and \".\" not in stem and suffix in PYTHON_EXTENSIONS:\n                    # (If we sorted names by keyfunc) we could probably just make the BuildSource\n                    # ourselves, but this ensures compatibility with find_module / the cache\n                    seen.add(stem)\n                    sources.extend(self.find_modules_recursive(module + \".\" + stem))\n        return sources\n\n\ndef matches_exclude(\n    subpath: str, excludes: list[str], fscache: FileSystemCache, verbose: bool\n) -> bool:\n    if not excludes:\n        return False\n    subpath_str = os.path.relpath(subpath).replace(os.sep, \"/\")\n    if fscache.isdir(subpath):\n        subpath_str += \"/\"\n    for exclude in excludes:\n        try:\n            if re.search(exclude, subpath_str):\n                if verbose:\n                    print(\n                        f\"TRACE: Excluding {subpath_str} (matches pattern {exclude})\",\n                        file=sys.stderr,\n                    )\n                return True\n        except re.error as e:\n            print(\n                f\"error: The exclude {exclude} is an invalid regular expression, because: {e}\"\n                + (\n                    \"\\n(Hint: use / as a path separator, even if you're on Windows!)\"\n                    if \"\\\\\" in exclude\n                    else \"\"\n                )\n                + \"\\nFor more information on Python's flavor of regex, see:\"\n                + \" https://docs.python.org/3/library/re.html\",\n                file=sys.stderr,\n            )\n            sys.exit(2)\n    return False\n\n\ndef matches_gitignore(subpath: str, fscache: FileSystemCache, verbose: bool) -> bool:\n    dir, _ = os.path.split(subpath)\n    for gi_path, gi_spec in find_gitignores(dir):\n        relative_path = os.path.relpath(subpath, gi_path)\n        if fscache.isdir(relative_path):\n            relative_path = relative_path + \"/\"\n        if gi_spec.match_file(relative_path):\n            if verbose:\n                print(\n                    f\"TRACE: Excluding {relative_path} (matches .gitignore) in {gi_path}\",\n                    file=sys.stderr,\n                )\n            return True\n    return False\n\n\n@functools.lru_cache\ndef find_gitignores(dir: str) -> list[tuple[str, PathSpec]]:\n    parent_dir = os.path.dirname(dir)\n    if parent_dir == dir or os.path.exists(os.path.join(dir, \".git\")):\n        parent_gitignores = []\n    else:\n        parent_gitignores = find_gitignores(parent_dir)\n\n    gitignore = os.path.join(dir, \".gitignore\")\n    if os.path.isfile(gitignore):\n        with open(gitignore) as f:\n            lines = f.readlines()\n        try:\n            return parent_gitignores + [(dir, PathSpec.from_lines(\"gitignore\", lines))]\n        except GitIgnorePatternError:\n            print(f\"error: could not parse {gitignore}\", file=sys.stderr)\n            return parent_gitignores\n    return parent_gitignores\n\n\ndef is_init_file(path: str) -> bool:\n    return os.path.basename(path) in (\"__init__.py\", \"__init__.pyi\")\n\n\ndef verify_module(fscache: FileSystemCache, id: str, path: str, prefix: str) -> bool:\n    \"\"\"Check that all packages containing id have a __init__ file.\"\"\"\n    if is_init_file(path):\n        path = os.path.dirname(path)\n    for i in range(id.count(\".\")):\n        path = os.path.dirname(path)\n        if not any(\n            fscache.isfile_case(os_path_join(path, f\"__init__{extension}\"), prefix)\n            for extension in PYTHON_EXTENSIONS\n        ):\n            return False\n    return True\n\n\ndef highest_init_level(fscache: FileSystemCache, id: str, path: str, prefix: str) -> int:\n    \"\"\"Compute the highest level where an __init__ file is found.\"\"\"\n    if is_init_file(path):\n        path = os.path.dirname(path)\n    level = 0\n    for i in range(id.count(\".\")):\n        path = os.path.dirname(path)\n        if any(\n            fscache.isfile_case(os_path_join(path, f\"__init__{extension}\"), prefix)\n            for extension in PYTHON_EXTENSIONS\n        ):\n            level = i + 1\n    return level\n\n\ndef mypy_path() -> list[str]:\n    path_env = os.getenv(\"MYPYPATH\")\n    if not path_env:\n        return []\n    return path_env.split(os.pathsep)\n\n\ndef default_lib_path(\n    data_dir: str, pyversion: tuple[int, int], custom_typeshed_dir: str | None\n) -> list[str]:\n    \"\"\"Return default standard library search paths. Guaranteed to be normalised.\"\"\"\n\n    data_dir = os.path.abspath(data_dir)\n    path: list[str] = []\n\n    if custom_typeshed_dir:\n        custom_typeshed_dir = os.path.abspath(custom_typeshed_dir)\n        typeshed_dir = os.path.join(custom_typeshed_dir, \"stdlib\")\n        mypy_extensions_dir = os.path.join(custom_typeshed_dir, \"stubs\", \"mypy-extensions\")\n        librt_dir = os.path.join(custom_typeshed_dir, \"stubs\", \"librt\")\n        versions_file = os.path.join(typeshed_dir, \"VERSIONS\")\n        if not os.path.isdir(typeshed_dir) or not os.path.isfile(versions_file):\n            print(\n                \"error: --custom-typeshed-dir does not point to a valid typeshed ({})\".format(\n                    custom_typeshed_dir\n                ),\n                file=sys.stderr,\n            )\n            sys.exit(2)\n    else:\n        auto = os.path.join(data_dir, \"stubs-auto\")\n        if os.path.isdir(auto):\n            data_dir = auto\n        typeshed_dir = os.path.join(data_dir, \"typeshed\", \"stdlib\")\n        mypy_extensions_dir = os.path.join(data_dir, \"typeshed\", \"stubs\", \"mypy-extensions\")\n        librt_dir = os.path.join(data_dir, \"typeshed\", \"stubs\", \"librt\")\n    path.append(typeshed_dir)\n\n    # Get mypy-extensions and librt stubs from typeshed, since we treat them as\n    # \"internal\" libraries, similar to typing and typing-extensions.\n    path.append(mypy_extensions_dir)\n    path.append(librt_dir)\n\n    # Add fallback path that can be used if we have a broken installation.\n    if sys.platform != \"win32\":\n        path.append(\"/usr/local/lib/mypy\")\n    if not path:\n        print(\n            \"Could not resolve typeshed subdirectories. Your mypy install is broken.\\n\"\n            \"Python executable is located at {}.\\nMypy located at {}\".format(\n                sys.executable, data_dir\n            ),\n            file=sys.stderr,\n        )\n        sys.exit(1)\n    return path\n\n\n@functools.cache\ndef get_search_dirs(python_executable: str | None) -> tuple[list[str], list[str]]:\n    \"\"\"Find package directories for given python. Guaranteed to return absolute paths.\n\n    This runs a subprocess call, which generates a list of the directories in sys.path.\n    To avoid repeatedly calling a subprocess (which can be slow!) we\n    lru_cache the results.\n    \"\"\"\n\n    if python_executable is None:\n        return ([], [])\n    elif python_executable == sys.executable:\n        # Use running Python's package dirs\n        sys_path, site_packages = pyinfo.getsearchdirs()\n    else:\n        # Use subprocess to get the package directory of given Python\n        # executable\n        env = {**dict(os.environ), \"PYTHONSAFEPATH\": \"1\"}\n        try:\n            sys_path, site_packages = ast.literal_eval(\n                subprocess.check_output(\n                    [python_executable, pyinfo.__file__, \"getsearchdirs\"],\n                    env=env,\n                    stderr=subprocess.PIPE,\n                ).decode()\n            )\n        except subprocess.CalledProcessError as err:\n            print(err.stderr)\n            print(err.stdout)\n            raise\n        except OSError as err:\n            assert err.errno is not None\n            reason = os.strerror(err.errno)\n            raise CompileError(\n                [f\"mypy: Invalid python executable '{python_executable}': {reason}\"]\n            ) from err\n    return sys_path, site_packages\n\n\ndef compute_search_paths(\n    sources: list[BuildSource], options: Options, data_dir: str, alt_lib_path: str | None = None\n) -> SearchPaths:\n    \"\"\"Compute the search paths as specified in PEP 561.\n\n    There are the following 4 members created:\n    - User code (from `sources`)\n    - MYPYPATH (set either via config or environment variable)\n    - installed package directories (which will later be split into stub-only and inline)\n    - typeshed\n    \"\"\"\n    # Determine the default module search path.\n    lib_path = collections.deque(\n        default_lib_path(\n            data_dir, options.python_version, custom_typeshed_dir=options.custom_typeshed_dir\n        )\n    )\n\n    if options.use_builtins_fixtures:\n        # Use stub builtins (to speed up test cases and to make them easier to\n        # debug).  This is a test-only feature, so assume our files are laid out\n        # as in the source tree.\n        # We also need to allow overriding where to look for it. Argh.\n        root_dir = os.getenv(\"MYPY_TEST_PREFIX\", None)\n        if not root_dir:\n            root_dir = os.path.dirname(os.path.dirname(__file__))\n        root_dir = os.path.abspath(root_dir)\n        lib_path.appendleft(os.path.join(root_dir, \"test-data\", \"unit\", \"lib-stub\"))\n    # alt_lib_path is used by some tests to bypass the normal lib_path mechanics.\n    # If we don't have one, grab directories of source files.\n    python_path: list[str] = []\n    if not alt_lib_path:\n        for source in sources:\n            # Include directory of the program file in the module search path.\n            if source.base_dir:\n                dir = source.base_dir\n                if dir not in python_path:\n                    python_path.append(dir)\n\n        # Do this even if running as a file, for sanity (mainly because with\n        # multiple builds, there could be a mix of files/modules, so its easier\n        # to just define the semantics that we always add the current director\n        # to the lib_path\n        # TODO: Don't do this in some cases; for motivation see see\n        # https://github.com/python/mypy/issues/4195#issuecomment-341915031\n        if options.bazel:\n            dir = \".\"\n        else:\n            dir = os.getcwd()\n        if dir not in lib_path:\n            python_path.insert(0, dir)\n\n    # Start with a MYPYPATH environment variable at the front of the mypy_path, if defined.\n    mypypath = mypy_path()\n\n    # Add a config-defined mypy path.\n    mypypath.extend(options.mypy_path)\n\n    # If provided, insert the caller-supplied extra module path to the\n    # beginning (highest priority) of the search path.\n    if alt_lib_path:\n        mypypath.insert(0, alt_lib_path)\n\n    sys_path, site_packages = get_search_dirs(options.python_executable)\n    # We only use site packages for this check\n    for site in site_packages:\n        assert site not in lib_path\n        if (\n            site in mypypath\n            or any(p.startswith(site + os.path.sep) for p in mypypath)\n            or (os.path.altsep and any(p.startswith(site + os.path.altsep) for p in mypypath))\n        ):\n            print(f\"{site} is in the MYPYPATH. Please remove it.\", file=sys.stderr)\n            print(\n                \"See https://mypy.readthedocs.io/en/stable/running_mypy.html\"\n                \"#how-mypy-handles-imports for more info\",\n                file=sys.stderr,\n            )\n            sys.exit(1)\n\n    return SearchPaths(\n        python_path=tuple(reversed(python_path)),\n        mypy_path=tuple(mypypath),\n        package_path=tuple(sys_path + site_packages),\n        typeshed_path=tuple(lib_path),\n    )\n\n\ndef load_stdlib_py_versions(custom_typeshed_dir: str | None) -> StdlibVersions:\n    \"\"\"Return dict with minimum and maximum Python versions of stdlib modules.\n\n    The contents look like\n    {..., 'secrets': ((3, 6), None), 'symbol': ((2, 7), (3, 9)), ...}\n\n    None means there is no maximum version.\n    \"\"\"\n    typeshed_dir = custom_typeshed_dir or os_path_join(os.path.dirname(__file__), \"typeshed\")\n    stdlib_dir = os_path_join(typeshed_dir, \"stdlib\")\n    result = {}\n\n    versions_path = os_path_join(stdlib_dir, \"VERSIONS\")\n    assert os.path.isfile(versions_path), (custom_typeshed_dir, versions_path, __file__)\n    with open(versions_path) as f:\n        for line in f:\n            line = line.split(\"#\")[0].strip()\n            if line == \"\":\n                continue\n            module, version_range = line.split(\":\")\n            versions = version_range.split(\"-\")\n            min_version = parse_version(versions[0])\n            max_version = (\n                parse_version(versions[1]) if len(versions) >= 2 and versions[1].strip() else None\n            )\n            result[module] = min_version, max_version\n    return result\n\n\ndef parse_version(version: str) -> tuple[int, int]:\n    major, minor = version.strip().split(\".\")\n    return int(major), int(minor)\n\n\ndef typeshed_py_version(options: Options) -> tuple[int, int]:\n    \"\"\"Return Python version used for checking whether module supports typeshed.\"\"\"\n    # Typeshed no longer covers Python 3.x versions before 3.9, so 3.9 is\n    # the earliest we can support.\n    return max(options.python_version, (3, 9))\n"
  },
  {
    "path": "mypy/moduleinspect.py",
    "content": "\"\"\"Basic introspection of modules.\"\"\"\n\nfrom __future__ import annotations\n\nimport importlib\nimport inspect\nimport os\nimport pkgutil\nimport queue\nimport sys\nfrom multiprocessing import Queue, get_context\nfrom types import ModuleType\n\n\nclass ModuleProperties:\n    # Note that all __init__ args must have default values\n    def __init__(\n        self,\n        name: str = \"\",\n        file: str | None = None,\n        path: list[str] | None = None,\n        all: list[str] | None = None,\n        is_c_module: bool = False,\n        subpackages: list[str] | None = None,\n    ) -> None:\n        self.name = name  # __name__ attribute\n        self.file = file  # __file__ attribute\n        self.path = path  # __path__ attribute\n        self.all = all  # __all__ attribute\n        self.is_c_module = is_c_module\n        self.subpackages = subpackages or []\n\n\ndef is_c_module(module: ModuleType) -> bool:\n    if module.__dict__.get(\"__file__\") is None:\n        # Could be a namespace package. These must be handled through\n        # introspection, since there is no source file.\n        return True\n    return os.path.splitext(module.__dict__[\"__file__\"])[-1] in [\".so\", \".pyd\", \".dll\"]\n\n\ndef is_pyc_only(file: str | None) -> bool:\n    return bool(file and file.endswith(\".pyc\") and not os.path.exists(file[:-1]))\n\n\nclass InspectError(Exception):\n    pass\n\n\ndef get_package_properties(package_id: str) -> ModuleProperties:\n    \"\"\"Use runtime introspection to get information about a module/package.\"\"\"\n    try:\n        package = importlib.import_module(package_id)\n    except BaseException as e:\n        raise InspectError(str(e)) from e\n    name = getattr(package, \"__name__\", package_id)\n    file = getattr(package, \"__file__\", None)\n    path: list[str] | None = getattr(package, \"__path__\", None)\n    if not isinstance(path, list):\n        path = None\n    pkg_all = getattr(package, \"__all__\", None)\n    if pkg_all is not None:\n        try:\n            pkg_all = list(pkg_all)\n        except Exception:\n            pkg_all = None\n    is_c = is_c_module(package)\n\n    if path is None:\n        # Object has no path; this means it's either a module inside a package\n        # (and thus no sub-packages), or it could be a C extension package.\n        if is_c:\n            # This is a C extension module, now get the list of all sub-packages\n            # using the inspect module\n            subpackages = [\n                package.__name__ + \".\" + name\n                for name, val in inspect.getmembers(package)\n                if inspect.ismodule(val) and val.__name__ == package.__name__ + \".\" + name\n            ]\n        else:\n            # It's a module inside a package.  There's nothing else to walk/yield.\n            subpackages = []\n    else:\n        all_packages = pkgutil.walk_packages(\n            path, prefix=package.__name__ + \".\", onerror=lambda r: None\n        )\n        subpackages = [qualified_name for importer, qualified_name, ispkg in all_packages]\n    return ModuleProperties(\n        name=name, file=file, path=path, all=pkg_all, is_c_module=is_c, subpackages=subpackages\n    )\n\n\ndef worker(tasks: Queue[str], results: Queue[str | ModuleProperties], sys_path: list[str]) -> None:\n    \"\"\"The main loop of a worker introspection process.\"\"\"\n    sys.path = sys_path\n    while True:\n        mod = tasks.get()\n        try:\n            prop = get_package_properties(mod)\n        except InspectError as e:\n            results.put(str(e))\n            continue\n        results.put(prop)\n\n\nclass ModuleInspect:\n    \"\"\"Perform runtime introspection of modules in a separate process.\n\n    Reuse the process for multiple modules for efficiency. However, if there is an\n    error, retry using a fresh process to avoid cross-contamination of state between\n    modules.\n\n    We use a separate process to isolate us from many side effects. For example, the\n    import of a module may kill the current process, and we want to recover from that.\n\n    Always use in a with statement for proper clean-up:\n\n      with ModuleInspect() as m:\n          p = m.get_package_properties('urllib.parse')\n    \"\"\"\n\n    def __init__(self) -> None:\n        self._start()\n\n    def _start(self) -> None:\n        if sys.platform == \"linux\":\n            ctx = get_context(\"forkserver\")\n        else:\n            ctx = get_context(\"spawn\")\n        self.tasks: Queue[str] = ctx.Queue()\n        self.results: Queue[ModuleProperties | str] = ctx.Queue()\n        self.proc = ctx.Process(target=worker, args=(self.tasks, self.results, sys.path))\n        self.proc.start()\n        self.counter = 0  # Number of successful roundtrips\n\n    def close(self) -> None:\n        \"\"\"Free any resources used.\"\"\"\n        self.proc.terminate()\n\n    def get_package_properties(self, package_id: str) -> ModuleProperties:\n        \"\"\"Return some properties of a module/package using runtime introspection.\n\n        Raise InspectError if the target couldn't be imported.\n        \"\"\"\n        self.tasks.put(package_id)\n        res = self._get_from_queue()\n        if res is None:\n            # The process died; recover and report error.\n            self._start()\n            raise InspectError(f\"Process died when importing {package_id!r}\")\n        if isinstance(res, str):\n            # Error importing module\n            if self.counter > 0:\n                # Also try with a fresh process. Maybe one of the previous imports has\n                # corrupted some global state.\n                self.close()\n                self._start()\n                return self.get_package_properties(package_id)\n            raise InspectError(res)\n        self.counter += 1\n        return res\n\n    def _get_from_queue(self) -> ModuleProperties | str | None:\n        \"\"\"Get value from the queue.\n\n        Return the value read from the queue, or None if the process unexpectedly died.\n        \"\"\"\n        max_iter = 600\n        n = 0\n        while True:\n            if n == max_iter:\n                raise RuntimeError(\"Timeout waiting for subprocess\")\n            try:\n                return self.results.get(timeout=0.05)\n            except queue.Empty:\n                if not self.proc.is_alive():\n                    return None\n            n += 1\n\n    def __enter__(self) -> ModuleInspect:\n        return self\n\n    def __exit__(self, *args: object) -> None:\n        self.close()\n"
  },
  {
    "path": "mypy/mro.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Callable\n\nfrom mypy.nodes import TypeInfo\nfrom mypy.types import Instance\nfrom mypy.typestate import type_state\n\n\ndef calculate_mro(info: TypeInfo, obj_type: Callable[[], Instance] | None = None) -> None:\n    \"\"\"Calculate and set mro (method resolution order).\n\n    Raise MroError if cannot determine mro.\n    \"\"\"\n    mro = linearize_hierarchy(info, obj_type)\n    assert mro, f\"Could not produce a MRO at all for {info}\"\n    info.mro = mro\n    # The property of falling back to Any is inherited.\n    info.fallback_to_any = any(baseinfo.fallback_to_any for baseinfo in info.mro)\n    type_state.reset_all_subtype_caches_for(info)\n\n\nclass MroError(Exception):\n    \"\"\"Raised if a consistent mro cannot be determined for a class.\"\"\"\n\n\ndef linearize_hierarchy(\n    info: TypeInfo, obj_type: Callable[[], Instance] | None = None\n) -> list[TypeInfo]:\n    # TODO describe\n    if info.mro:\n        return info.mro\n    bases = info.direct_base_classes()\n    if not bases and info.fullname != \"builtins.object\" and obj_type is not None:\n        # Probably an error, add a dummy `object` base class,\n        # otherwise MRO calculation may spuriously fail.\n        bases = [obj_type().type]\n    lin_bases = []\n    for base in bases:\n        assert base is not None, f\"Cannot linearize bases for {info.fullname} {bases}\"\n        lin_bases.append(linearize_hierarchy(base, obj_type))\n    lin_bases.append(bases)\n    return [info] + merge(lin_bases)\n\n\ndef merge(seqs: list[list[TypeInfo]]) -> list[TypeInfo]:\n    seqs = [s.copy() for s in seqs]\n    result: list[TypeInfo] = []\n    while True:\n        seqs = [s for s in seqs if s]\n        if not seqs:\n            return result\n        for seq in seqs:\n            head = seq[0]\n            if not [s for s in seqs if head in s[1:]]:\n                break\n        else:\n            raise MroError()\n        result.append(head)\n        for s in seqs:\n            if s[0] is head:\n                del s[0]\n"
  },
  {
    "path": "mypy/nativeparse.py",
    "content": "# mypy: allow-redefinition-new, local-partial-types\n\"\"\"Python parser that directly constructs a native AST (when compiled).\n\nUse a Rust extension to generate a serialized AST, and deserialize the AST directly\nto a mypy AST.\n\nNOTE: This is work in progress. To use this, you need to manually build the\n      ast_serialize Rust extension. See the README at https://github.com/mypyc/ast_serialize.\n\nExpected benefits over mypy.fastparse:\n * No intermediate non-mypyc Python-level AST created, to improve performance\n * Parsing doesn't need GIL => use multithreading to construct serialized ASTs in parallel\n * Produce import dependencies without having to build an AST => helps parallel type checking\n * Support all Python syntax even if mypy is running on an older Python version\n * Generate an AST even if there are syntax errors\n * Potential to support incremental parsing (quickly process modified sections in a file)\n * Stripping function bodies in third-party code can happen earlier, for extra performance\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom typing import Any, Final, cast\n\nimport ast_serialize  # type: ignore[import-untyped, import-not-found, unused-ignore]\nfrom librt.internal import (\n    read_float as read_float_bare,\n    read_int as read_int_bare,\n    read_str as read_str_bare,\n)\n\nfrom mypy import message_registry, nodes, types\nfrom mypy.cache import (\n    DICT_STR_GEN,\n    END_TAG,\n    LIST_GEN,\n    LIST_INT,\n    LITERAL_FLOAT,\n    LITERAL_NONE,\n    LITERAL_STR,\n    LOCATION,\n    ReadBuffer,\n    Tag,\n    read_bool,\n    read_int,\n    read_str,\n    read_str_opt,\n    read_tag,\n)\nfrom mypy.nodes import (\n    ARG_KINDS,\n    ARG_POS,\n    IMPORT_METADATA,\n    IMPORTALL_METADATA,\n    IMPORTFROM_METADATA,\n    MISSING_FALLBACK,\n    Argument,\n    AssertStmt,\n    AssignmentExpr,\n    AssignmentStmt,\n    AwaitExpr,\n    Block,\n    BreakStmt,\n    BytesExpr,\n    CallExpr,\n    ClassDef,\n    ComparisonExpr,\n    ComplexExpr,\n    ConditionalExpr,\n    Context,\n    ContinueStmt,\n    Decorator,\n    DelStmt,\n    DictExpr,\n    DictionaryComprehension,\n    EllipsisExpr,\n    Expression,\n    ExpressionStmt,\n    FileRawData,\n    FloatExpr,\n    ForStmt,\n    FuncDef,\n    GeneratorExpr,\n    GlobalDecl,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportBase,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    MatchStmt,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    NonlocalDecl,\n    OperatorAssignmentStmt,\n    OpExpr,\n    OverloadedFuncDef,\n    OverloadPart,\n    PassStmt,\n    RaiseStmt,\n    RefExpr,\n    ReturnStmt,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    Statement,\n    StrExpr,\n    SuperExpr,\n    TemplateStrExpr,\n    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAliasStmt,\n    TypeParam,\n    UnaryExpr,\n    Var,\n    WhileStmt,\n    WithStmt,\n    YieldExpr,\n    YieldFromExpr,\n)\nfrom mypy.options import Options\nfrom mypy.patterns import (\n    AsPattern,\n    ClassPattern,\n    MappingPattern,\n    OrPattern,\n    Pattern,\n    SequencePattern,\n    SingletonPattern,\n    StarredPattern,\n    ValuePattern,\n)\nfrom mypy.reachability import infer_reachability_of_if_statement\nfrom mypy.sharedparse import special_function_elide_names\nfrom mypy.types import (\n    AnyType,\n    CallableArgument,\n    CallableType,\n    EllipsisType,\n    Instance,\n    ProperType,\n    RawExpressionType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeList,\n    TypeOfAny,\n    UnboundType,\n    UnionType,\n    UnpackType,\n)\nfrom mypy.util import unnamed_function\n\nTypeIgnores = list[tuple[int, list[str]]]\n\n# There is no way to create reasonable fallbacks at this stage,\n# they must be patched later.\n_dummy_fallback: Final = Instance(MISSING_FALLBACK, [], -1)\n\n\nclass State:\n    def __init__(self, options: Options) -> None:\n        self.options = options\n        self.errors: list[dict[str, Any]] = []\n        self.num_funcs = 0\n\n    def add_error(\n        self,\n        message: str,\n        line: int,\n        column: int,\n        *,\n        blocker: bool = False,\n        code: str | None = None,\n    ) -> None:\n        \"\"\"Report an error at a specific location.\n\n        Args:\n            message: Error message to display\n            line: Line number where error occurred\n            column: Column number where error occurred\n            blocker: If True, this error blocks further analysis\n            code: Error code for categorization\n        \"\"\"\n        self.errors.append(\n            {\"line\": line, \"column\": column, \"message\": message, \"blocker\": blocker, \"code\": code}\n        )\n\n\ndef native_parse(\n    filename: str, options: Options, skip_function_bodies: bool = False, imports_only: bool = False\n) -> tuple[MypyFile, list[dict[str, Any]], TypeIgnores]:\n    \"\"\"Parse a Python file using the native Rust-based parser.\n\n    Uses the ast_serialize Rust extension to parse Python code and deserialize\n    the resulting AST directly into mypy's native AST representation.\n\n    Args:\n        filename: Path to the Python source file to parse\n        options: Mypy options affecting parsing behavior (e.g., Python version)\n        skip_function_bodies: If True, many function and method bodies are omitted from\n            the AST, useful for parsing stubs or extracting signatures without full\n            implementation details\n        imports_only: If True create an empty MypyFile with actual serialized defs\n            stored in binary_data.\n\n    Returns:\n        A tuple containing:\n        - MypyFile: The parsed AST as a mypy AST node\n        - list[dict[str, Any]]: List of parse errors and deserialization errors\n        - TypeIgnores: List of (line_number, ignored_codes) tuples for type: ignore comments\n    \"\"\"\n    # If the path is a directory, return empty AST (matching fastparse behavior)\n    # This can happen for packages that only contain .pyc files without source\n    if os.path.isdir(filename):\n        node = MypyFile([], [])\n        node.path = filename\n        return node, [], []\n\n    b, errors, ignores, import_bytes, is_partial_package, uses_template_strings = (\n        parse_to_binary_ast(filename, options, skip_function_bodies)\n    )\n    data = ReadBuffer(b)\n    n = read_int(data)\n    state = State(options)\n    if imports_only:\n        defs = []\n    else:\n        defs = read_statements(state, data, n)\n\n    imports = deserialize_imports(import_bytes)\n\n    node = MypyFile(defs, imports)\n    node.path = filename\n    node.is_partial_stub_package = is_partial_package\n    if imports_only:\n        node.raw_data = FileRawData(\n            b, import_bytes, errors, dict(ignores), is_partial_package, uses_template_strings\n        )\n    node.uses_template_strings = uses_template_strings\n    # Merge deserialization errors with parsing errors\n    all_errors = errors + state.errors\n    return node, all_errors, ignores\n\n\ndef expect_end_tag(data: ReadBuffer) -> None:\n    assert read_tag(data) == END_TAG\n\n\ndef expect_tag(data: ReadBuffer, tag: Tag) -> None:\n    assert (actual := read_tag(data)) == tag, actual\n\n\ndef read_statements(state: State, data: ReadBuffer, n: int) -> list[Statement]:\n    defs: list[Statement] = []\n    old_num_funcs = state.num_funcs\n    for _ in range(n):\n        stmt = read_statement(state, data)\n        defs.append(stmt)\n    if state.num_funcs > old_num_funcs + 1:\n        # There were at least two functions, so we may need to merge overloads.\n        defs = fix_function_overloads(state, defs)\n    return defs\n\n\ndef parse_to_binary_ast(\n    filename: str, options: Options, skip_function_bodies: bool = False\n) -> tuple[bytes, list[dict[str, Any]], TypeIgnores, bytes, bool, bool]:\n    ast_bytes, errors, ignores, import_bytes, ast_data = ast_serialize.parse(\n        filename,\n        skip_function_bodies=skip_function_bodies,\n        python_version=options.python_version,\n        platform=options.platform,\n        always_true=options.always_true,\n        always_false=options.always_false,\n    )\n    return (\n        ast_bytes,\n        cast(\"list[dict[str, Any]]\", errors),\n        ignores,\n        import_bytes,\n        ast_data[\"is_partial_package\"],\n        ast_data[\"uses_template_strings\"],\n    )\n\n\ndef read_statement(state: State, data: ReadBuffer) -> Statement:\n    tag = read_tag(data)\n    stmt: Statement\n    if tag == nodes.FUNC_DEF_STMT:\n        return read_func_def(state, data)\n    elif tag == nodes.DECORATOR:\n        expect_tag(data, LIST_GEN)\n        n_decorators = read_int_bare(data)\n        decorators = [read_expression(state, data) for i in range(n_decorators)]\n        line = read_int(data)\n        column = read_int(data)\n        fdef = read_statement(state, data)\n        assert isinstance(fdef, FuncDef)\n        fdef.is_decorated = True\n        var = Var(fdef.name)\n        var.line = fdef.line\n        var.is_ready = False\n        stmt = Decorator(fdef, decorators, var)\n        stmt.line = line\n        stmt.column = column\n        stmt.end_line = fdef.end_line\n        stmt.end_column = fdef.end_column\n        # TODO: Adjust funcdef location to start after decorator?\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.EXPR_STMT:\n        es = ExpressionStmt(read_expression(state, data))\n        set_line_column_range(es, es.expr)\n        expect_end_tag(data)\n        return es\n    elif tag == nodes.ASSIGNMENT_STMT:\n        lvalues = read_expression_list(state, data)\n        rvalue = read_expression(state, data)\n        has_type = read_bool(data)\n        if has_type:\n            type_annotation = read_type(state, data)\n        else:\n            type_annotation = None\n        new_syntax = read_bool(data)\n        a = AssignmentStmt(lvalues, rvalue, type=type_annotation, new_syntax=new_syntax)\n        read_loc(data, a)\n        # If rvalue is TempNode, copy location from AssignmentStmt\n        if isinstance(rvalue, TempNode):\n            set_line_column_range(rvalue, a)\n        expect_end_tag(data)\n        return a\n    elif tag == nodes.OPERATOR_ASSIGNMENT_STMT:\n        # Read operator string\n        op = read_str(data)\n        # Read lvalue (target)\n        lvalue = read_expression(state, data)\n        # Read rvalue (value)\n        rvalue = read_expression(state, data)\n        stmt = OperatorAssignmentStmt(op, lvalue, rvalue)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.IF_STMT:\n        # Read the main if condition and body\n        expr = read_expression(state, data)\n        body = read_block(state, data)\n\n        # Read elif clauses\n        num_elif = read_int(data)\n        elif_exprs = []\n        elif_bodies = []\n        for i in range(num_elif):\n            elif_exprs.append(read_expression(state, data))\n            elif_bodies.append(read_block(state, data))\n\n        has_else = read_bool(data)\n        if has_else:\n            else_body = read_block(state, data)\n        else:\n            else_body = None\n\n        # Normalize elif into nested if/else statements\n        # Build from the bottom up, starting with the final else body\n        current_else = else_body\n\n        # Process elif clauses in reverse order\n        for i in range(len(elif_exprs) - 1, -1, -1):\n            elif_stmt = IfStmt([elif_exprs[i]], [elif_bodies[i]], current_else)\n            # Set location from the elif expression\n            elif_stmt.line = elif_exprs[i].line\n            elif_stmt.column = elif_exprs[i].column\n            # Set end location based on what follows\n            if current_else is not None:\n                elif_stmt.end_line = current_else.end_line\n                elif_stmt.end_column = current_else.end_column\n            else:\n                elif_stmt.end_line = elif_bodies[i].end_line\n                elif_stmt.end_column = elif_bodies[i].end_column\n\n            # Wrap in a Block to become the else clause for the outer if\n            current_else = Block([elif_stmt])\n            set_line_column_range(current_else, elif_stmt)\n\n        if_stmt = IfStmt([expr], [body], current_else)\n        read_loc(data, if_stmt)\n        expect_end_tag(data)\n        return if_stmt\n    elif tag == nodes.RETURN_STMT:\n        has_value = read_bool(data)\n        if has_value:\n            value = read_expression(state, data)\n        else:\n            value = None\n        stmt = ReturnStmt(value)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.RAISE_STMT:\n        has_exc = read_bool(data)\n        if has_exc:\n            exc = read_expression(state, data)\n        else:\n            exc = None\n        has_from = read_bool(data)\n        if has_from:\n            from_expr = read_expression(state, data)\n        else:\n            from_expr = None\n        stmt = RaiseStmt(exc, from_expr)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.ASSERT_STMT:\n        test = read_expression(state, data)\n        has_msg = read_bool(data)\n        if has_msg:\n            msg = read_expression(state, data)\n        else:\n            msg = None\n        stmt = AssertStmt(test, msg)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.WHILE_STMT:\n        expr = read_expression(state, data)\n        body = read_block(state, data)\n        else_body = read_optional_block(state, data)\n        stmt = WhileStmt(expr, body, else_body)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.FOR_STMT:\n        index = read_expression(state, data)\n        expr = read_expression(state, data)\n        body = read_block(state, data)\n        else_body = read_optional_block(state, data)\n        is_async = read_bool(data)\n        stmt = ForStmt(index, expr, body, else_body)\n        stmt.is_async = is_async\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.WITH_STMT:\n        n = read_int(data)\n        expr_list = []\n        target_list: list[Expression | None] = []\n        for _ in range(n):\n            context_expr = read_expression(state, data)\n            expr_list.append(context_expr)\n            has_target = read_bool(data)\n            if has_target:\n                target = read_expression(state, data)\n                target_list.append(target)\n            else:\n                target_list.append(None)\n        body = read_block(state, data)\n        is_async = read_bool(data)\n        stmt = WithStmt(expr_list, target_list, body)\n        stmt.is_async = is_async\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.PASS_STMT:\n        stmt = PassStmt()\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.BREAK_STMT:\n        stmt = BreakStmt()\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.CONTINUE_STMT:\n        stmt = ContinueStmt()\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.IMPORT:\n        n = read_int(data)\n        ids = []\n        for _ in range(n):\n            name = read_str(data)\n            has_asname = read_bool(data)\n            if has_asname:\n                asname = read_str(data)\n            else:\n                asname = None\n            ids.append((name, asname))\n        stmt = Import(ids)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.IMPORT_FROM:\n        relative = read_int(data)\n        module_id = read_str(data)  # Empty string for \"from . import x\"\n        n = read_int(data)\n        names = []\n        for _ in range(n):\n            name = read_str(data)\n            has_asname = read_bool(data)\n            if has_asname:\n                asname = read_str(data)\n            else:\n                asname = None\n            names.append((name, asname))\n\n        stmt = ImportFrom(module_id, relative, names)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.IMPORT_ALL:\n        module_id = read_str(data)  # Empty string for \"from . import *\"\n        relative = read_int(data)\n\n        stmt = ImportAll(module_id, relative)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.CLASS_DEF:\n        return read_class_def(state, data)\n    elif tag == nodes.TYPE_ALIAS_STMT:\n        return read_type_alias_stmt(state, data)\n    elif tag == nodes.TRY_STMT:\n        return read_try_stmt(state, data)\n    elif tag == nodes.DEL_STMT:\n        expr = read_expression(state, data)\n        stmt = DelStmt(expr)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.GLOBAL_DECL:\n        n = read_int(data)\n        decl_names = []\n        for _ in range(n):\n            decl_names.append(read_str(data))\n        stmt = GlobalDecl(decl_names)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.NONLOCAL_DECL:\n        n = read_int(data)\n        decl_names = []\n        for _ in range(n):\n            decl_names.append(read_str(data))\n        stmt = NonlocalDecl(decl_names)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    elif tag == nodes.MATCH_STMT:\n        subject = read_expression(state, data)\n        n_cases = read_int(data)\n        patterns = []\n        guards: list[Expression | None] = []\n        bodies = []\n        for _ in range(n_cases):\n            pattern = read_pattern(state, data)\n            patterns.append(pattern)\n            has_guard = read_bool(data)\n            if has_guard:\n                guard = read_expression(state, data)\n                guards.append(guard)\n            else:\n                guards.append(None)\n            body = read_block(state, data)\n            bodies.append(body)\n        stmt = MatchStmt(subject, patterns, guards, bodies)\n        read_loc(data, stmt)\n        expect_end_tag(data)\n        return stmt\n    else:\n        assert False, tag\n\n\ndef read_parameters(state: State, data: ReadBuffer) -> tuple[list[Argument], bool]:\n    \"\"\"Read function/lambda parameters from the buffer.\n\n    Returns:\n        A tuple of (arguments list, has_annotations flag)\n    \"\"\"\n    expect_tag(data, LIST_GEN)\n    n_args = read_int_bare(data)\n    arguments = []\n    has_ann = False\n    for _ in range(n_args):\n        arg_name = read_str(data)\n        arg_kind_int = read_int(data)\n        arg_kind = ARG_KINDS[arg_kind_int]\n        has_type = read_bool(data)\n        if has_type:\n            ann = read_type(state, data)\n            has_ann = True\n        else:\n            ann = None\n        has_default = read_bool(data)\n        if has_default:\n            default = read_expression(state, data)\n        else:\n            default = None\n        pos_only = read_bool(data)\n\n        # Apply implicit_optional if enabled and default is None\n        if state.options.implicit_optional and ann is not None:\n            optional = isinstance(default, NameExpr) and default.name == \"None\"\n            if isinstance(ann, UnboundType):\n                ann.optional = optional\n\n        var = Var(arg_name, ann)\n        var.is_inferred = False\n        var.is_argument = True\n        arg = Argument(var, ann, default, arg_kind, pos_only)\n        read_loc(data, arg)\n        set_line_column_range(var, arg)\n        arguments.append(arg)\n\n    return arguments, has_ann\n\n\ndef read_type_params(state: State, data: ReadBuffer) -> list[TypeParam]:\n    \"\"\"Read type parameters (PEP 695 generics).\"\"\"\n    type_params: list[TypeParam] = []\n    n = read_int_bare(data)\n    for _ in range(n):\n        kind = read_int(data)\n        name = read_str(data)\n        has_bound = read_bool(data)\n        if has_bound:\n            upper_bound = read_type(state, data)\n        else:\n            upper_bound = None\n\n        expect_tag(data, LIST_GEN)\n        n_values = read_int_bare(data)\n        values = [read_type(state, data) for _ in range(n_values)]\n\n        has_default = read_bool(data)\n        if has_default:\n            default = read_type(state, data)\n        else:\n            default = None\n\n        type_params.append(TypeParam(name, kind, upper_bound, values, default))\n\n    return type_params\n\n\ndef read_func_def(state: State, data: ReadBuffer) -> FuncDef:\n    state.num_funcs += 1\n\n    name = read_str(data)\n    arguments, has_ann = read_parameters(state, data)\n\n    if special_function_elide_names(name):\n        for arg in arguments:\n            arg.pos_only = True\n\n    body = read_block(state, data)\n    is_async = read_bool(data)\n\n    # Type parameters (PEP 695)\n    has_type_params = read_bool(data)\n    if has_type_params:\n        type_params = read_type_params(state, data)\n    else:\n        type_params = None\n\n    has_return_type = read_bool(data)\n    if has_return_type:\n        return_type = read_type(state, data)\n        has_ann = True\n    else:\n        return_type = None\n\n    if has_ann:\n        typ = CallableType(\n            [\n                arg.type_annotation if arg.type_annotation else AnyType(TypeOfAny.unannotated)\n                for arg in arguments\n            ],\n            [arg.kind for arg in arguments],\n            [None if arg.pos_only else arg.variable.name for arg in arguments],\n            return_type if return_type else AnyType(TypeOfAny.unannotated),\n            _dummy_fallback,\n        )\n    else:\n        typ = None\n\n    func_def = FuncDef(name, arguments, body, typ=typ, type_args=type_params)\n    if is_async:\n        func_def.is_coroutine = True\n    read_loc(data, func_def)\n    if typ:\n        typ.line = func_def.line\n        typ.column = func_def.column\n        typ.definition = func_def\n        # TODO: This seems wasteful, can we avoid it?\n        func_def.unanalyzed_type = typ.copy_modified()\n    expect_end_tag(data)\n    return func_def\n\n\ndef read_class_def(state: State, data: ReadBuffer) -> ClassDef:\n    name = read_str(data)\n    body = read_block(state, data)\n    base_type_exprs = read_expression_list(state, data)\n\n    expect_tag(data, LIST_GEN)\n    n_decorators = read_int_bare(data)\n    decorators = [read_expression(state, data) for _ in range(n_decorators)]\n\n    # Type parameters (PEP 695)\n    has_type_params = read_bool(data)\n    if has_type_params:\n        type_params = read_type_params(state, data)\n    else:\n        type_params = None\n\n    # Keywords (all keyword arguments including metaclass)\n    expect_tag(data, DICT_STR_GEN)\n    n_keywords = read_int_bare(data)\n    keywords = []\n    for _ in range(n_keywords):\n        key = read_str(data)\n        value = read_expression(state, data)\n        keywords.append((key, value))\n\n    # Extract metaclass from keywords if present\n    metaclass = dict(keywords).get(\"metaclass\") if keywords else None\n    # Remove metaclass from keywords since it's passed as a separate field\n    filtered_keywords = [(k, v) for k, v in keywords if k != \"metaclass\"] if keywords else None\n\n    class_def = ClassDef(\n        name,\n        body,\n        base_type_exprs=base_type_exprs if base_type_exprs else None,\n        metaclass=metaclass,\n        keywords=filtered_keywords,\n        type_args=type_params,\n    )\n    class_def.decorators = decorators\n    read_loc(data, class_def)\n    expect_end_tag(data)\n    return class_def\n\n\ndef read_type_alias_stmt(state: State, data: ReadBuffer) -> TypeAliasStmt:\n    \"\"\"Read PEP 695 type alias statement.\"\"\"\n    name = read_expression(state, data)\n    assert isinstance(name, NameExpr), f\"Expected NameExpr for type alias name, got {type(name)}\"\n\n    n_type_params = read_int_bare(data)\n    if n_type_params > 0:\n        type_params = []\n        for _ in range(n_type_params):\n            kind = read_int(data)\n            param_name = read_str(data)\n            has_bound = read_bool(data)\n            if has_bound:\n                upper_bound = read_type(state, data)\n            else:\n                upper_bound = None\n\n            # Read values (for constrained TypeVar)\n            expect_tag(data, LIST_GEN)\n            n_values = read_int_bare(data)\n            values = [read_type(state, data) for _ in range(n_values)]\n\n            has_default = read_bool(data)\n            if has_default:\n                default = read_type(state, data)\n            else:\n                default = None\n\n            type_params.append(TypeParam(param_name, kind, upper_bound, values, default))\n    else:\n        type_params = []\n\n    value_expr = read_expression(state, data)\n\n    # Wrap the value expression in a LambdaExpr as expected by TypeAliasStmt\n    # The LambdaExpr body is a Block with a single ReturnStmt\n    return_stmt = ReturnStmt(value_expr)\n    set_line_column_range(return_stmt, value_expr)\n\n    block = Block([return_stmt])\n    block.line = -1  # Synthetic block\n    block.column = 0\n    block.end_line = -1\n    block.end_column = 0\n\n    lambda_expr = LambdaExpr([], block)\n    set_line_column_range(lambda_expr, value_expr)\n\n    stmt = TypeAliasStmt(name, type_params, lambda_expr)\n    read_loc(data, stmt)\n    expect_end_tag(data)\n    return stmt\n\n\ndef read_try_stmt(state: State, data: ReadBuffer) -> TryStmt:\n    body = read_block(state, data)\n    num_handlers = read_int(data)\n\n    types_list: list[Expression | None] = []\n    for _ in range(num_handlers):\n        has_type = read_bool(data)\n        if has_type:\n            exc_type = read_expression(state, data)\n            types_list.append(exc_type)\n        else:\n            types_list.append(None)\n\n    vars_list: list[NameExpr | None] = []\n    for _ in range(num_handlers):\n        has_name = read_bool(data)\n        if has_name:\n            var_name = read_str(data)\n            var_expr = NameExpr(var_name)\n            vars_list.append(var_expr)\n        else:\n            vars_list.append(None)\n\n    handlers = []\n    for _ in range(num_handlers):\n        handler_body = read_block(state, data)\n        handlers.append(handler_body)\n\n    has_else = read_bool(data)\n    if has_else:\n        else_body = read_block(state, data)\n    else:\n        else_body = None\n\n    has_finally = read_bool(data)\n    if has_finally:\n        finally_body = read_block(state, data)\n    else:\n        finally_body = None\n\n    # Read is_star flag (for except* in Python 3.11+)\n    is_star = read_bool(data)\n\n    stmt = TryStmt(body, vars_list, types_list, handlers, else_body, finally_body)\n    stmt.is_star = is_star\n    read_loc(data, stmt)\n    expect_end_tag(data)\n    return stmt\n\n\ndef read_type(state: State, data: ReadBuffer) -> Type:\n    tag = read_tag(data)\n    if tag == types.UNBOUND_TYPE:\n        name = read_str(data)\n        expect_tag(data, LIST_GEN)\n        n = read_int_bare(data)\n        args = tuple(read_type(state, data) for i in range(n))\n        empty_tuple_index = read_bool(data)\n        # Read optional original_str_expr\n        t = read_tag(data)\n        if t == LITERAL_NONE:\n            original_str_expr = None\n        elif t == LITERAL_STR:\n            original_str_expr = read_str_bare(data)\n        else:\n            assert False, f\"Unexpected tag for original_str_expr: {t}\"\n        # Read optional original_str_fallback\n        t = read_tag(data)\n        if t == LITERAL_NONE:\n            original_str_fallback = None\n        elif t == LITERAL_STR:\n            original_str_fallback = read_str_bare(data)\n        else:\n            assert False, f\"Unexpected tag for original_str_fallback: {t}\"\n        unbound = UnboundType(\n            name,\n            args,\n            empty_tuple_index=empty_tuple_index,\n            original_str_expr=original_str_expr,\n            original_str_fallback=original_str_fallback,\n        )\n        read_loc(data, unbound)\n        expect_end_tag(data)\n        return unbound\n    elif tag == types.UNION_TYPE:\n        # Read items list\n        expect_tag(data, LIST_GEN)\n        n = read_int_bare(data)\n        items = [read_type(state, data) for i in range(n)]\n        # Read uses_pep604_syntax flag\n        uses_pep604_syntax = read_bool(data)\n        # Read optional original_str_expr\n        t = read_tag(data)\n        if t == LITERAL_NONE:\n            original_str_expr = None\n        elif t == LITERAL_STR:\n            original_str_expr = read_str_bare(data)\n        else:\n            assert False, f\"Unexpected tag for original_str_expr: {t}\"\n        # Read optional original_str_fallback\n        t = read_tag(data)\n        if t == LITERAL_NONE:\n            original_str_fallback = None\n        elif t == LITERAL_STR:\n            original_str_fallback = read_str_bare(data)\n        else:\n            assert False, f\"Unexpected tag for original_str_fallback: {t}\"\n        union = UnionType(items, uses_pep604_syntax=uses_pep604_syntax)\n        union.original_str_expr = original_str_expr\n        union.original_str_fallback = original_str_fallback\n        union.is_evaluated = read_bool(data)\n        read_loc(data, union)\n        expect_end_tag(data)\n        return union\n    elif tag == types.LIST_TYPE:\n        # Read items list\n        expect_tag(data, LIST_GEN)\n        n = read_int_bare(data)\n        items = [read_type(state, data) for i in range(n)]\n        type_list = TypeList(items)\n        read_loc(data, type_list)\n        expect_end_tag(data)\n        return type_list\n    elif tag == types.TUPLE_TYPE:\n        # Read items list\n        expect_tag(data, LIST_GEN)\n        n = read_int_bare(data)\n        items = [read_type(state, data) for i in range(n)]\n        implicit = read_bool(data)\n        tuple_type = TupleType(items, _dummy_fallback, implicit=implicit)\n        read_loc(data, tuple_type)\n        expect_end_tag(data)\n        return tuple_type\n    elif tag == types.TYPED_DICT_TYPE:\n        expect_tag(data, LIST_GEN)\n        n = read_int_bare(data)\n        keys = [read_str_opt(data) for i in range(n)]\n        expect_tag(data, LIST_GEN)\n        n = read_int_bare(data)\n        values = [read_type(state, data) for i in range(n)]\n        td_items = {}\n        extra_items_from = []\n        for key, val in zip(keys, values):\n            if key is None:\n                assert isinstance(val, ProperType)\n                extra_items_from.append(val)\n            else:\n                td_items[key] = val\n        typeddict_type = TypedDictType(td_items, set(), set(), _dummy_fallback)\n        typeddict_type.extra_items_from = extra_items_from\n        read_loc(data, typeddict_type)\n        expect_end_tag(data)\n        return typeddict_type\n    elif tag == types.ELLIPSIS_TYPE:\n        # EllipsisType has no attributes\n        ellipsis_type = EllipsisType()\n        read_loc(data, ellipsis_type)\n        expect_end_tag(data)\n        return ellipsis_type\n    elif tag == types.RAW_EXPRESSION_TYPE:\n        type_name = read_str(data)\n        value: types.LiteralValue | str | None\n        if type_name == \"builtins.bool\":\n            value = read_bool(data)\n        elif type_name == \"builtins.int\":\n            value = read_int(data)\n        elif type_name == \"builtins.str\":\n            value = read_str(data)\n        elif type_name == \"builtins.bytes\":\n            # Bytes literals are serialized as escaped strings\n            value = read_str(data)\n        elif type_name == \"typing.Any\":\n            # Invalid type - read None value\n            tag = read_tag(data)\n            assert tag == LITERAL_NONE, f\"Expected LITERAL_NONE for invalid type, got {tag}\"\n            value = None\n        else:\n            assert False, f\"Unsupported RawExpressionType: {type_name}\"\n        raw_type = RawExpressionType(value, type_name)\n        read_loc(data, raw_type)\n        expect_end_tag(data)\n        return raw_type\n    elif tag == types.UNPACK_TYPE:\n        inner_type = read_type(state, data)\n        from_star_syntax = read_bool(data)\n        unpack = UnpackType(inner_type, from_star_syntax=from_star_syntax)\n        read_loc(data, unpack)\n        expect_end_tag(data)\n        return unpack\n    elif tag == types.CALL_TYPE:\n        return read_call_type(state, data)\n    else:\n        assert False, tag\n\n\ndef stringify_type_name(typ: Type) -> str | None:\n    \"\"\"Extract qualified name from a type (for Arg constructor detection).\"\"\"\n    if isinstance(typ, UnboundType):\n        return typ.name\n    return None\n\n\ndef extract_arg_name(typ: Type) -> str | None:\n    \"\"\"Extract argument name from a type (for Arg name parameter).\"\"\"\n    if isinstance(typ, RawExpressionType) and typ.base_type_name == \"builtins.str\":\n        return typ.literal_value  # type: ignore[return-value]\n    elif isinstance(typ, UnboundType):\n        # String literals in type context are parsed as UnboundType (forward references)\n        # For Arg names, these are typically simple names without dots\n        if typ.name == \"None\":\n            return None\n        # Return the name as-is (it's the argument name)\n        return typ.name\n    return None  # Invalid, but let validation handle it\n\n\ndef read_call_type(state: State, data: ReadBuffer) -> Type:\n    \"\"\"Read Call in type context - check if it's an Arg/DefaultArg/VarArg/KwArg constructor.\n\n    This performs validation and error reporting similar to mypy/fastparse.py.\n    \"\"\"\n    callee_type = read_type(state, data)\n\n    # Read positional arguments\n    expect_tag(data, LIST_GEN)\n    n_args = read_int_bare(data)\n    args = [read_type(state, data) for _ in range(n_args)]\n\n    # Read keyword arguments\n    expect_tag(data, LIST_GEN)\n    n_kwargs = read_int_bare(data)\n    kwargs = []\n    for _ in range(n_kwargs):\n        tag_kw = read_tag(data)\n        if tag_kw == LITERAL_NONE:\n            kw_name = None\n        elif tag_kw == LITERAL_STR:\n            kw_name = read_str_bare(data)\n        else:\n            assert False, f\"Unexpected tag for keyword name: {tag_kw}\"\n        kw_value = read_type(state, data)\n        kwargs.append((kw_name, kw_value))\n\n    # Try to detect Arg/DefaultArg/VarArg/KwArg pattern\n    constructor = stringify_type_name(callee_type)\n\n    # We'll read location before processing errors so we can report them correctly\n    invalid = AnyType(TypeOfAny.from_error)\n    read_loc(data, invalid)\n    expect_end_tag(data)\n\n    if not constructor:\n        # ARG_CONSTRUCTOR_NAME_EXPECTED\n        state.add_error(\n            message_registry.ARG_CONSTRUCTOR_NAME_EXPECTED.value,\n            invalid.line,\n            invalid.column,\n            blocker=True,\n            code=\"misc\",\n        )\n        return invalid\n\n    # Extract type and name from arguments\n    name: str | None = None\n    name_set_from_positional = False\n    default_type = AnyType(TypeOfAny.special_form)\n    typ: Type = default_type\n    typ_set_from_positional = False\n\n    # Process positional arguments\n    for i, arg in enumerate(args):\n        if i == 0:\n            typ = arg\n            typ_set_from_positional = True\n        elif i == 1:\n            name = extract_arg_name(arg)\n            name_set_from_positional = True\n        else:\n            # ARG_CONSTRUCTOR_TOO_MANY_ARGS\n            state.add_error(\n                message_registry.ARG_CONSTRUCTOR_TOO_MANY_ARGS.value,\n                invalid.line,\n                invalid.column,\n                blocker=True,\n                code=\"misc\",\n            )\n\n    # Process keyword arguments\n    for kw_name, kw_value in kwargs:\n        if kw_name == \"name\":\n            # MULTIPLE_VALUES_FOR_NAME_KWARG\n            if name is not None and name_set_from_positional:\n                state.add_error(\n                    message_registry.MULTIPLE_VALUES_FOR_NAME_KWARG.format(constructor).value,\n                    invalid.line,\n                    invalid.column,\n                    blocker=True,\n                    code=\"misc\",\n                )\n            name = extract_arg_name(kw_value)\n        elif kw_name == \"type\":\n            # MULTIPLE_VALUES_FOR_TYPE_KWARG\n            if typ is not default_type and typ_set_from_positional:\n                state.add_error(\n                    message_registry.MULTIPLE_VALUES_FOR_TYPE_KWARG.format(constructor).value,\n                    invalid.line,\n                    invalid.column,\n                    blocker=True,\n                    code=\"misc\",\n                )\n            typ = kw_value\n        else:\n            # ARG_CONSTRUCTOR_UNEXPECTED_ARG\n            state.add_error(\n                message_registry.ARG_CONSTRUCTOR_UNEXPECTED_ARG.format(kw_name).value,\n                invalid.line,\n                invalid.column,\n                blocker=True,\n                code=\"misc\",\n            )\n\n    # Create CallableArgument\n    call_arg = CallableArgument(typ, name, constructor)\n    set_line_column_range(call_arg, invalid)\n    return call_arg\n\n\ndef read_pattern(state: State, data: ReadBuffer) -> Pattern:\n    \"\"\"Read a pattern node from the buffer.\"\"\"\n    tag = read_tag(data)\n    if tag == nodes.AS_PATTERN:\n        has_pattern = read_bool(data)\n        if has_pattern:\n            pattern = read_pattern(state, data)\n        else:\n            pattern = None\n        has_name = read_bool(data)\n        if has_name:\n            name_str = read_str(data)\n            name = NameExpr(name_str)\n            read_loc(data, name)\n        else:\n            name = None\n        as_pattern = AsPattern(pattern, name)\n        read_loc(data, as_pattern)\n        expect_end_tag(data)\n        return as_pattern\n    elif tag == nodes.OR_PATTERN:\n        n = read_int(data)\n        patterns = [read_pattern(state, data) for _ in range(n)]\n        or_pattern = OrPattern(patterns)\n        read_loc(data, or_pattern)\n        expect_end_tag(data)\n        return or_pattern\n    elif tag == nodes.VALUE_PATTERN:\n        expr = read_expression(state, data)\n        value_pattern = ValuePattern(expr)\n        read_loc(data, value_pattern)\n        expect_end_tag(data)\n        return value_pattern\n    elif tag == nodes.SINGLETON_PATTERN:\n        singleton_tag = read_tag(data)\n        if singleton_tag == LITERAL_NONE:\n            value = None\n        else:\n            # It's a boolean\n            value = singleton_tag == 1  # TAG_LITERAL_TRUE\n        singleton_pattern = SingletonPattern(value)\n        read_loc(data, singleton_pattern)\n        expect_end_tag(data)\n        return singleton_pattern\n    elif tag == nodes.SEQUENCE_PATTERN:\n        n = read_int(data)\n        patterns = [read_pattern(state, data) for _ in range(n)]\n        sequence_pattern = SequencePattern(patterns)\n        read_loc(data, sequence_pattern)\n        expect_end_tag(data)\n        return sequence_pattern\n    elif tag == nodes.STARRED_PATTERN:\n        # Read optional capture name\n        has_name = read_bool(data)\n        if has_name:\n            name_str = read_str(data)\n            name = NameExpr(name_str)\n            read_loc(data, name)\n        else:\n            name = None\n        starred_pattern = StarredPattern(name)\n        read_loc(data, starred_pattern)\n        expect_end_tag(data)\n        return starred_pattern\n    elif tag == nodes.MAPPING_PATTERN:\n        n = read_int(data)\n        keys = []\n        values = []\n        for _ in range(n):\n            key = read_expression(state, data)\n            value = read_pattern(state, data)\n            keys.append(key)\n            values.append(value)\n        has_rest = read_bool(data)\n        if has_rest:\n            rest_str = read_str(data)\n            rest = NameExpr(rest_str)\n            read_loc(data, rest)\n        else:\n            rest = None\n        mapping_pattern = MappingPattern(keys, values, rest)\n        read_loc(data, mapping_pattern)\n        expect_end_tag(data)\n        return mapping_pattern\n    elif tag == nodes.CLASS_PATTERN:\n        class_ref = cast(RefExpr, read_expression(state, data))\n        n_positional = read_int(data)\n        positionals = [read_pattern(state, data) for _ in range(n_positional)]\n        n_keywords = read_int(data)\n        keyword_keys = []\n        keyword_values = []\n        for _ in range(n_keywords):\n            key = read_str(data)\n            value = read_pattern(state, data)\n            keyword_keys.append(key)\n            keyword_values.append(value)\n        class_pattern = ClassPattern(class_ref, positionals, keyword_keys, keyword_values)\n        read_loc(data, class_pattern)\n        expect_end_tag(data)\n        return class_pattern\n    else:\n        assert False, f\"Unknown pattern tag: {tag}\"\n\n\ndef read_block(state: State, data: ReadBuffer) -> Block:\n    expect_tag(data, nodes.BLOCK)\n    expect_tag(data, LIST_GEN)\n    n = read_int_bare(data)\n    is_unreachable = read_bool(data)\n    if n == 0:\n        # Empty block - read explicit location\n        b = Block([], is_unreachable=is_unreachable)\n        read_loc(data, b)\n        expect_end_tag(data)\n        return b\n    else:\n        # Non-empty block - read statements and set location from them\n        a = read_statements(state, data, n)\n        expect_end_tag(data)\n        b = Block(a, is_unreachable=is_unreachable)\n        b.line = a[0].line\n        b.column = a[0].column\n        b.end_line = a[-1].end_line\n        b.end_column = a[-1].end_column\n        return b\n\n\ndef read_optional_block(state: State, data: ReadBuffer) -> Block | None:\n    expect_tag(data, nodes.BLOCK)\n    expect_tag(data, LIST_GEN)\n    n = read_int_bare(data)\n    is_unreachable = read_bool(data)\n    if n == 0:\n        b = None\n    else:\n        a = [read_statement(state, data) for i in range(n)]\n        b = Block(a, is_unreachable=is_unreachable)\n        b.line = a[0].line\n        b.column = a[0].column\n        b.end_line = a[-1].end_line\n        b.end_column = a[-1].end_column\n    expect_end_tag(data)\n    return b\n\n\nbin_ops: Final = [\"+\", \"-\", \"*\", \"@\", \"/\", \"%\", \"**\", \"<<\", \">>\", \"|\", \"^\", \"&\", \"//\"]\nbool_ops: Final = [\"and\", \"or\"]\ncmp_ops: Final = [\"==\", \"!=\", \"<\", \"<=\", \">\", \">=\", \"is\", \"is not\", \"in\", \"not in\"]\nunary_ops: Final = [\"~\", \"not\", \"+\", \"-\"]\n\n\ndef read_expression(state: State, data: ReadBuffer) -> Expression:\n    tag = read_tag(data)\n    expr: Expression\n    if tag == nodes.CALL_EXPR:\n        callee = read_expression(state, data)\n        args = read_expression_list(state, data)\n        # Read argument kinds\n        expect_tag(data, LIST_INT)\n        n_kinds = read_int_bare(data)\n        arg_kinds = [ARG_KINDS[read_int_bare(data)] for _ in range(n_kinds)]\n        # Read argument names\n        expect_tag(data, LIST_GEN)\n        n_names = read_int_bare(data)\n        arg_names: list[str | None] = []\n        for _ in range(n_names):\n            tag = read_tag(data)\n            if tag == LITERAL_NONE:\n                arg_names.append(None)\n            elif tag == LITERAL_STR:\n                arg_names.append(read_str_bare(data))\n            else:\n                assert False, f\"Unexpected tag for arg_name: {tag}\"\n        ce = CallExpr(callee, args, arg_kinds, arg_names)\n        read_loc(data, ce)\n        expect_end_tag(data)\n        return ce\n    elif tag == nodes.NAME_EXPR:\n        s = read_str(data)\n        ne = NameExpr(s)\n        read_loc(data, ne)\n        expect_end_tag(data)\n        return ne\n    elif tag == nodes.MEMBER_EXPR:\n        e = read_expression(state, data)\n        attr = read_str(data)\n        m = MemberExpr(e, attr)\n        # Check if this is a super() call - if so, convert to SuperExpr\n        if isinstance(e, CallExpr) and isinstance(e.callee, NameExpr) and e.callee.name == \"super\":\n            result: Expression = SuperExpr(attr, e)\n        else:\n            result = m\n        read_loc(data, result)\n        expect_end_tag(data)\n        return result\n    elif tag == nodes.STR_EXPR:\n        se = StrExpr(read_str(data))\n        read_loc(data, se)\n        expect_end_tag(data)\n        return se\n    elif tag == nodes.INT_EXPR:\n        ie = IntExpr(read_int(data))\n        read_loc(data, ie)\n        expect_end_tag(data)\n        return ie\n    elif tag == nodes.FLOAT_EXPR:\n        expect_tag(data, LITERAL_FLOAT)\n        value = read_float_bare(data)\n        fe = FloatExpr(value)\n        read_loc(data, fe)\n        expect_end_tag(data)\n        return fe\n    elif tag == nodes.LIST_EXPR:\n        items = read_expression_list(state, data)\n        expr = ListExpr(items)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.TUPLE_EXPR:\n        items = read_expression_list(state, data)\n        t = TupleExpr(items)\n        read_loc(data, t)\n        expect_end_tag(data)\n        return t\n    elif tag == nodes.SET_EXPR:\n        items = read_expression_list(state, data)\n        expr = SetExpr(items)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.GENERATOR_EXPR:\n        expr = read_generator_expr(state, data)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.LIST_COMPREHENSION:\n        generator = read_generator_expr(state, data)\n        expr = ListComprehension(generator)\n        read_loc(data, expr)\n        # Also copy location to the inner generator\n        set_line_column_range(generator, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.SET_COMPREHENSION:\n        generator = read_generator_expr(state, data)\n        expr = SetComprehension(generator)\n        read_loc(data, expr)\n        # Also copy location to the inner generator\n        set_line_column_range(generator, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.DICT_COMPREHENSION:\n        key = read_expression(state, data)\n        value = read_expression(state, data)\n        n_generators = read_int(data)\n        indices = [read_expression(state, data) for _ in range(n_generators)]\n        sequences = [read_expression(state, data) for _ in range(n_generators)]\n        condlists = [read_expression_list(state, data) for _ in range(n_generators)]\n        is_async = [read_bool(data) for _ in range(n_generators)]\n        expr = DictionaryComprehension(key, value, indices, sequences, condlists, is_async)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.YIELD_EXPR:\n        has_value = read_bool(data)\n        if has_value:\n            value = read_expression(state, data)\n        else:\n            value = None\n        expr = YieldExpr(value)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.YIELD_FROM_EXPR:\n        value = read_expression(state, data)\n        expr = YieldFromExpr(value)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.OP_EXPR:\n        op = bin_ops[read_int(data)]\n        left = read_expression(state, data)\n        right = read_expression(state, data)\n        o = OpExpr(op, left, right)\n        # TODO: Store these explicitly?\n        o.line = left.line\n        o.column = left.column\n        o.end_line = right.end_line\n        o.end_column = right.end_column\n        expect_end_tag(data)\n        return o\n    elif tag == nodes.INDEX_EXPR:\n        base = read_expression(state, data)\n        index = read_expression(state, data)\n        expr = IndexExpr(base, index)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.BOOL_OP_EXPR:\n        op = bool_ops[read_int(data)]\n        values = read_expression_list(state, data)\n        # Convert list of values to nested OpExpr nodes\n        # E.g., [a, b, c] with \"and\" becomes OpExpr(\"and\", OpExpr(\"and\", a, b), c)\n        assert len(values) >= 2\n        result = values[0]\n        for val in values[1:]:\n            result = OpExpr(op, result, val)\n            result.line = values[0].line\n            result.column = values[0].column\n            result.end_line = val.end_line\n            result.end_column = val.end_column\n        read_loc(data, result)\n        expect_end_tag(data)\n        return result\n    elif tag == nodes.COMPARISON_EXPR:\n        left = read_expression(state, data)\n        expect_tag(data, LIST_INT)\n        n_ops = read_int_bare(data)\n        ops = [cmp_ops[read_int_bare(data)] for _ in range(n_ops)]\n        comparators = read_expression_list(state, data)\n        assert len(ops) == len(comparators)\n        expr = ComparisonExpr(ops, [left] + comparators)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.UNARY_EXPR:\n        op = unary_ops[read_int(data)]\n        operand = read_expression(state, data)\n        expr = UnaryExpr(op, operand)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.DICT_EXPR:\n        expect_tag(data, LIST_GEN)\n        n_keys = read_int_bare(data)\n        keys: list[Expression | None] = []\n        for _ in range(n_keys):\n            has_key = read_bool(data)\n            if has_key:\n                keys.append(read_expression(state, data))\n            else:\n                keys.append(None)\n        values = read_expression_list(state, data)\n        # Zip keys and values into items\n        items = list(zip(keys, values))\n        expr = DictExpr(items)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.COMPLEX_EXPR:\n        expect_tag(data, LITERAL_FLOAT)\n        real = read_float_bare(data)\n        expect_tag(data, LITERAL_FLOAT)\n        imag = read_float_bare(data)\n        value = complex(real, imag)\n        expr = ComplexExpr(value)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.SLICE_EXPR:\n        has_begin = read_bool(data)\n        begin_index = read_expression(state, data) if has_begin else None\n        has_end = read_bool(data)\n        end_index = read_expression(state, data) if has_end else None\n        has_stride = read_bool(data)\n        stride = read_expression(state, data) if has_stride else None\n        expr = SliceExpr(begin_index, end_index, stride)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.TEMP_NODE:\n        # TempNode with no attributes\n        temp = TempNode(AnyType(TypeOfAny.special_form), no_rhs=True)\n        expect_end_tag(data)\n        return temp\n    elif tag == nodes.ELLIPSIS_EXPR:\n        expr = EllipsisExpr()\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.CONDITIONAL_EXPR:\n        if_expr = read_expression(state, data)\n        cond = read_expression(state, data)\n        else_expr = read_expression(state, data)\n        expr = ConditionalExpr(cond, if_expr, else_expr)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.FSTRING_EXPR:\n        # F-strings are converted into nodes representing \"\".join([...]), to match\n        # pre-existing behavior.\n        nparts = read_int(data)\n        fitems = []\n        for _ in range(nparts):\n            b = read_bool(data)\n            if b:\n                n = read_int(data)\n                for i in range(n):\n                    fitems.append(read_fstring_item(state, data))\n            else:\n                s = StrExpr(read_str(data))\n                read_loc(data, s)\n                fitems.append(s)\n        expr = build_fstring_join(state, data, fitems)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.TSTRING_EXPR:\n        nparts = read_int(data)\n        titems: list[Expression | tuple[Expression, str, str | None, Expression | None]] = []\n        for _ in range(nparts):\n            if read_bool(data):\n                e = read_expression(state, data)\n                s = read_str(data)\n                if read_bool(data):\n                    conv = read_str(data)\n                else:\n                    conv = None\n                if read_bool(data):\n                    # Parse format spec as a JoinedStr, this matches the old parser behavior.\n                    format_spec = read_fstring_items(state, data)\n                else:\n                    format_spec = None\n                titems.append((e, s, conv, format_spec))\n            else:\n                s = StrExpr(read_str(data))\n                read_loc(data, s)\n                titems.append(s)\n        expr = TemplateStrExpr(titems)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.LAMBDA_EXPR:\n        arguments, has_ann = read_parameters(state, data)\n        body = read_block(state, data)\n\n        if has_ann:\n            typ = CallableType(\n                [\n                    arg.type_annotation if arg.type_annotation else AnyType(TypeOfAny.unannotated)\n                    for arg in arguments\n                ],\n                [arg.kind for arg in arguments],\n                [None if arg.pos_only else arg.variable.name for arg in arguments],\n                AnyType(TypeOfAny.unannotated),\n                _dummy_fallback,\n            )\n        else:\n            typ = None\n\n        expr = LambdaExpr(arguments, body)\n        expr.type = typ\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.NAMED_EXPR:\n        target = read_expression(state, data)\n        value = read_expression(state, data)\n        # AssignmentExpr expects target to be a NameExpr\n        if not isinstance(target, NameExpr):\n            # In case target is not a NameExpr, we need to handle this\n            # For now, we'll assert since the grammar should ensure it's a NameExpr\n            assert isinstance(\n                target, NameExpr\n            ), f\"Expected NameExpr for target, got {type(target)}\"\n        expr = AssignmentExpr(target, value)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.STAR_EXPR:\n        wrapped_expr = read_expression(state, data)\n        expr = StarExpr(wrapped_expr)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.BYTES_EXPR:\n        # Read bytes literal as string\n        value = read_str(data)\n        expr = BytesExpr(value)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.AWAIT_EXPR:\n        value = read_expression(state, data)\n        expr = AwaitExpr(value)\n        read_loc(data, expr)\n        expect_end_tag(data)\n        return expr\n    elif tag == nodes.BIG_INT_EXPR:\n        strval = read_str(data)\n        ie = IntExpr(int(strval, base=0))\n        read_loc(data, ie)\n        expect_end_tag(data)\n        return ie\n    else:\n        assert False, tag\n\n\ndef read_fstring_items(state: State, data: ReadBuffer) -> Expression:\n    items = []\n    n = read_int(data)\n    items = [read_fstring_item(state, data) for i in range(n)]\n    return build_fstring_join(state, data, items)\n\n\ndef build_fstring_join(state: State, data: ReadBuffer, items: list[Expression]) -> Expression:\n    if len(items) == 1:\n        expr = items[0]\n        read_loc(data, expr)\n        return expr\n    if all(isinstance(item, StrExpr) for item in items):\n        s = \"\".join([cast(StrExpr, item).value for item in items])\n        expr = StrExpr(s)\n        read_loc(data, expr)\n        return expr\n    args = ListExpr(items)\n    str_expr = StrExpr(\"\")\n    member = MemberExpr(str_expr, \"join\")\n    call = CallExpr(member, [args], [ARG_POS], [None])\n    read_loc(data, call)\n    set_line_column(args, call)\n    set_line_column(str_expr, call)\n    set_line_column(member, call)\n    return call\n\n\ndef read_fstring_item(state: State, data: ReadBuffer) -> Expression:\n    t = read_tag(data)\n    if t == LITERAL_STR:\n        str_expr = StrExpr(read_str_bare(data))\n        read_loc(data, str_expr)\n        return str_expr\n    elif t == nodes.FSTRING_INTERPOLATION:\n        expr = read_expression(state, data)\n\n        # Read conversion flag such as !r\n        has_conv = read_bool(data)\n        if has_conv:\n            c = read_str(data)\n            fmt = \"{\" + c + \":{}}\"\n        else:\n            fmt = \"{:{}}\"\n\n        # Read format spec such as <30 (which may have nested {...})\n        has_spec = read_bool(data)\n        if has_spec:\n            spec = read_fstring_items(state, data)\n        else:\n            spec = StrExpr(\"\")\n\n        member = MemberExpr(StrExpr(fmt), \"format\")\n        set_line_column(member, expr)\n        call = CallExpr(member, [expr, spec], [ARG_POS, ARG_POS], [None, None])\n        set_line_column(call, expr)\n        expect_end_tag(data)\n        return call\n    else:\n        raise ValueError(f\"Unexpected tag {t}\")\n\n\ndef set_line_column(target: Context, src: Context) -> None:\n    target.line = src.line\n    target.column = src.column\n\n\ndef set_line_column_range(target: Context, src: Context) -> None:\n    target.line = src.line\n    target.column = src.column\n    target.end_line = src.end_line\n    target.end_column = src.end_column\n\n\ndef read_expression_list(state: State, data: ReadBuffer) -> list[Expression]:\n    expect_tag(data, LIST_GEN)\n    n = read_int_bare(data)\n    return [read_expression(state, data) for i in range(n)]\n\n\ndef read_generator_expr(state: State, data: ReadBuffer) -> GeneratorExpr:\n    \"\"\"Helper function to read comprehension data (shared by Generator, ListComp, SetComp)\"\"\"\n    left_expr = read_expression(state, data)\n    n_generators = read_int(data)\n    indices = [read_expression(state, data) for _ in range(n_generators)]\n    sequences = [read_expression(state, data) for _ in range(n_generators)]\n    condlists = [read_expression_list(state, data) for _ in range(n_generators)]\n    is_async = [read_bool(data) for _ in range(n_generators)]\n    return GeneratorExpr(left_expr, indices, sequences, condlists, is_async)\n\n\ndef read_loc(data: ReadBuffer, node: Context) -> None:\n    expect_tag(data, LOCATION)\n    line = read_int_bare(data)\n    node.line = line\n    column = read_int_bare(data)\n    node.column = column\n    node.end_line = line + read_int_bare(data)\n    node.end_column = column + read_int_bare(data)\n\n\ndef strip_contents_from_if_stmt(stmt: IfStmt) -> None:\n    \"\"\"Remove contents from IfStmt.\n\n    Needed to still be able to check the conditions after the contents\n    have been merged with the surrounding function overloads.\n    \"\"\"\n    if len(stmt.body) == 1:\n        stmt.body[0].body = []\n    if stmt.else_body and len(stmt.else_body.body) == 1:\n        if isinstance(stmt.else_body.body[0], IfStmt):\n            strip_contents_from_if_stmt(stmt.else_body.body[0])\n        else:\n            stmt.else_body.body = []\n\n\ndef is_stripped_if_stmt(stmt: Statement) -> bool:\n    \"\"\"Check stmt to make sure it is a stripped IfStmt.\n\n    See also: strip_contents_from_if_stmt\n    \"\"\"\n    if not isinstance(stmt, IfStmt):\n        return False\n\n    if not (len(stmt.body) == 1 and len(stmt.body[0].body) == 0):\n        # Body not empty\n        return False\n\n    if not stmt.else_body or len(stmt.else_body.body) == 0:\n        # No or empty else_body\n        return True\n\n    # For elif, IfStmt are stored recursively in else_body\n    return is_stripped_if_stmt(stmt.else_body.body[0])\n\n\ndef fail_merge_overload(state: State, node: IfStmt) -> None:\n    \"\"\"Report an error when overloads cannot be merged due to unknown condition.\"\"\"\n    state.add_error(\n        message_registry.FAILED_TO_MERGE_OVERLOADS.value,\n        node.line,\n        node.column,\n        blocker=False,\n        code=\"misc\",\n    )\n\n\ndef check_ifstmt_for_overloads(\n    stmt: IfStmt, current_overload_name: str | None = None\n) -> str | None:\n    \"\"\"Check if IfStmt contains only overloads with the same name.\n    Return overload_name if found, None otherwise.\n    \"\"\"\n    # Check that block only contains a single Decorator, FuncDef, or OverloadedFuncDef.\n    # Multiple overloads have already been merged as OverloadedFuncDef.\n    if not (\n        len(stmt.body[0].body) == 1\n        and (\n            isinstance(stmt.body[0].body[0], (Decorator, OverloadedFuncDef))\n            or current_overload_name is not None\n            and isinstance(stmt.body[0].body[0], FuncDef)\n        )\n        or len(stmt.body[0].body) > 1\n        and isinstance(stmt.body[0].body[-1], OverloadedFuncDef)\n        and all(is_stripped_if_stmt(if_stmt) for if_stmt in stmt.body[0].body[:-1])\n    ):\n        return None\n\n    overload_name = cast(Decorator | FuncDef | OverloadedFuncDef, stmt.body[0].body[-1]).name\n    if stmt.else_body is None or stmt.else_body.is_unreachable:\n        return overload_name\n\n    if len(stmt.else_body.body) == 1:\n        # For elif: else_body contains an IfStmt itself -> do a recursive check.\n        if (\n            isinstance(stmt.else_body.body[0], (Decorator, FuncDef, OverloadedFuncDef))\n            and stmt.else_body.body[0].name == overload_name\n        ):\n            return overload_name\n        if (\n            isinstance(stmt.else_body.body[0], IfStmt)\n            and check_ifstmt_for_overloads(stmt.else_body.body[0], current_overload_name)\n            == overload_name\n        ):\n            return overload_name\n\n    return None\n\n\ndef get_executable_if_block_with_overloads(\n    stmt: IfStmt, options: Options\n) -> tuple[Block | None, IfStmt | None]:\n    \"\"\"Return block from IfStmt that will get executed.\n\n    Return\n        0 -> A block if sure that alternative blocks are unreachable.\n        1 -> An IfStmt if the reachability of it can't be inferred,\n             i.e. the truth value is unknown.\n    \"\"\"\n    infer_reachability_of_if_statement(stmt, options)\n    if stmt.else_body is None and stmt.body[0].is_unreachable is True:\n        # always False condition with no else\n        return None, None\n    if (\n        stmt.else_body is None\n        or stmt.body[0].is_unreachable is False\n        and stmt.else_body.is_unreachable is False\n    ):\n        # The truth value is unknown, thus not conclusive\n        return None, stmt\n    if stmt.else_body.is_unreachable:\n        # else_body will be set unreachable if condition is always True\n        return stmt.body[0], None\n    if stmt.body[0].is_unreachable is True:\n        # body will be set unreachable if condition is always False\n        # else_body can contain an IfStmt itself (for elif) -> do a recursive check\n        if isinstance(stmt.else_body.body[0], IfStmt):\n            return get_executable_if_block_with_overloads(stmt.else_body.body[0], options)\n        return stmt.else_body, None\n    return None, stmt\n\n\ndef fix_function_overloads(state: State, stmts: list[Statement]) -> list[Statement]:\n    \"\"\"Merge consecutive function overloads into OverloadedFuncDef nodes.\n\n    This function processes a list of statements and combines function overloads\n    (marked with @overload decorator) that have the same name into a single\n    OverloadedFuncDef node. It also handles conditional overloads (overloads\n    inside if statements) when the condition can be evaluated.\n    \"\"\"\n    ret: list[Statement] = []\n    current_overload: list[OverloadPart] = []\n    current_overload_name: str | None = None\n    last_unconditional_func_def: str | None = None\n    last_if_stmt: IfStmt | None = None\n    last_if_overload: Decorator | FuncDef | OverloadedFuncDef | None = None\n    last_if_stmt_overload_name: str | None = None\n    last_if_unknown_truth_value: IfStmt | None = None\n    skipped_if_stmts: list[IfStmt] = []\n    for stmt in stmts:\n        if_overload_name: str | None = None\n        if_block_with_overload: Block | None = None\n        if_unknown_truth_value: IfStmt | None = None\n        if isinstance(stmt, IfStmt):\n            # Check IfStmt block to determine if function overloads can be merged\n            if_overload_name = check_ifstmt_for_overloads(stmt, current_overload_name)\n            if if_overload_name is not None:\n                if_block_with_overload, if_unknown_truth_value = (\n                    get_executable_if_block_with_overloads(stmt, state.options)\n                )\n\n        if (\n            current_overload_name is not None\n            and isinstance(stmt, (Decorator, FuncDef))\n            and stmt.name == current_overload_name\n        ):\n            if last_if_stmt is not None:\n                skipped_if_stmts.append(last_if_stmt)\n            if last_if_overload is not None:\n                # Last stmt was an IfStmt with same overload name\n                # Add overloads to current_overload\n                if isinstance(last_if_overload, OverloadedFuncDef):\n                    current_overload.extend(last_if_overload.items)\n                else:\n                    current_overload.append(last_if_overload)\n                last_if_stmt, last_if_overload = None, None\n            if last_if_unknown_truth_value:\n                fail_merge_overload(state, last_if_unknown_truth_value)\n                last_if_unknown_truth_value = None\n            current_overload.append(stmt)\n            if isinstance(stmt, FuncDef):\n                # This is, strictly speaking, wrong: there might be a decorated\n                # implementation. However, it only affects the error message we show:\n                # ideally it's \"already defined\", but \"implementation must come last\"\n                # is also reasonable.\n                # TODO: can we get rid of this completely and just always emit\n                # \"implementation must come last\" instead?\n                last_unconditional_func_def = stmt.name\n        elif (\n            current_overload_name is not None\n            and isinstance(stmt, IfStmt)\n            and if_overload_name == current_overload_name\n            and last_unconditional_func_def != current_overload_name\n        ):\n            # IfStmt only contains stmts relevant to current_overload.\n            # Check if stmts are reachable and add them to current_overload,\n            # otherwise skip IfStmt to allow subsequent overload\n            # or function definitions.\n            skipped_if_stmts.append(stmt)\n            if if_block_with_overload is None:\n                if if_unknown_truth_value is not None:\n                    fail_merge_overload(state, if_unknown_truth_value)\n                continue\n            if last_if_overload is not None:\n                # Last stmt was an IfStmt with same overload name\n                # Add overloads to current_overload\n                if isinstance(last_if_overload, OverloadedFuncDef):\n                    current_overload.extend(last_if_overload.items)\n                else:\n                    current_overload.append(last_if_overload)\n                last_if_stmt, last_if_overload = None, None\n            if isinstance(if_block_with_overload.body[-1], OverloadedFuncDef):\n                skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1]))\n                current_overload.extend(if_block_with_overload.body[-1].items)\n            else:\n                current_overload.append(cast(Decorator | FuncDef, if_block_with_overload.body[0]))\n        else:\n            if last_if_stmt is not None:\n                ret.append(last_if_stmt)\n                last_if_stmt_overload_name = current_overload_name\n                last_if_stmt, last_if_overload = None, None\n                last_if_unknown_truth_value = None\n\n            if current_overload and current_overload_name == last_if_stmt_overload_name:\n                # Remove last stmt (IfStmt) from ret if the overload names matched\n                # Only happens if no executable block had been found in IfStmt\n                popped = ret.pop()\n                assert isinstance(popped, IfStmt)\n                skipped_if_stmts.append(popped)\n            if current_overload and skipped_if_stmts:\n                # Add bare IfStmt (without overloads) to ret\n                # Required for mypy to be able to still check conditions\n                for if_stmt in skipped_if_stmts:\n                    strip_contents_from_if_stmt(if_stmt)\n                    ret.append(if_stmt)\n                skipped_if_stmts = []\n            if len(current_overload) == 1:\n                ret.append(current_overload[0])\n            elif len(current_overload) > 1:\n                ret.append(OverloadedFuncDef(current_overload))\n\n            # If we have multiple decorated functions named \"_\" next to each, we want to treat\n            # them as a series of regular FuncDefs instead of one OverloadedFuncDef because\n            # most of mypy/mypyc assumes that all the functions in an OverloadedFuncDef are\n            # related, but multiple underscore functions next to each other aren't necessarily\n            # related\n            last_unconditional_func_def = None\n            if isinstance(stmt, Decorator) and not unnamed_function(stmt.name):\n                current_overload = [stmt]\n                current_overload_name = stmt.name\n            elif isinstance(stmt, IfStmt) and if_overload_name is not None:\n                current_overload = []\n                current_overload_name = if_overload_name\n                last_if_stmt = stmt\n                last_if_stmt_overload_name = None\n                if if_block_with_overload is not None:\n                    skipped_if_stmts.extend(cast(list[IfStmt], if_block_with_overload.body[:-1]))\n                    last_if_overload = cast(\n                        Decorator | FuncDef | OverloadedFuncDef, if_block_with_overload.body[-1]\n                    )\n                last_if_unknown_truth_value = if_unknown_truth_value\n            else:\n                current_overload = []\n                current_overload_name = None\n                ret.append(stmt)\n\n    if current_overload and skipped_if_stmts:\n        # Add bare IfStmt (without overloads) to ret\n        # Required for mypy to be able to still check conditions\n        for if_stmt in skipped_if_stmts:\n            strip_contents_from_if_stmt(if_stmt)\n            ret.append(if_stmt)\n    if len(current_overload) == 1:\n        ret.append(current_overload[0])\n    elif len(current_overload) > 1:\n        ret.append(OverloadedFuncDef(current_overload))\n    elif last_if_overload is not None:\n        ret.append(last_if_overload)\n    elif last_if_stmt is not None:\n        ret.append(last_if_stmt)\n    return ret\n\n\ndef deserialize_imports(import_bytes: bytes) -> list[ImportBase]:\n    \"\"\"Deserialize import metadata from bytes into mypy AST nodes.\n\n    Args:\n        import_bytes: Serialized import metadata from the Rust parser\n\n    Returns:\n        List of Import and ImportFrom AST nodes with location and metadata\n    \"\"\"\n    if not import_bytes:\n        return []\n\n    data = ReadBuffer(import_bytes)\n\n    expect_tag(data, LIST_GEN)\n    n_imports = read_int_bare(data)\n\n    imports: list[ImportBase] = []\n\n    for _ in range(n_imports):\n        tag = read_tag(data)\n\n        if tag == IMPORT_METADATA:\n            name = read_str(data)\n            relative = read_int(data)\n\n            has_asname = read_bool(data)\n            if has_asname:\n                asname = read_str(data)\n            else:\n                asname = None\n\n            # Note: relative imports are handled via ImportFrom, so relative should be 0 here\n            stmt = Import([(name, asname)])\n            _read_and_set_import_metadata(data, stmt)\n            imports.append(stmt)\n\n        elif tag == IMPORTFROM_METADATA:\n            module = read_str(data)\n            relative = read_int(data)\n\n            expect_tag(data, LIST_GEN)\n            n_names = read_int_bare(data)\n            names: list[tuple[str, str | None]] = []\n\n            for _ in range(n_names):\n                name = read_str(data)\n                has_asname = read_bool(data)\n                if has_asname:\n                    asname = read_str(data)\n                else:\n                    asname = None\n                names.append((name, asname))\n\n            stmt = ImportFrom(module, relative, names)\n            _read_and_set_import_metadata(data, stmt)\n            imports.append(stmt)\n\n        elif tag == IMPORTALL_METADATA:\n            module = read_str(data)\n            relative = read_int(data)\n\n            stmt = ImportAll(module, relative)\n            _read_and_set_import_metadata(data, stmt)\n            imports.append(stmt)\n\n        else:\n            raise ValueError(f\"Unexpected tag in import metadata: {tag}\")\n\n    return imports\n\n\ndef _read_and_set_import_metadata(data: ReadBuffer, stmt: Import | ImportFrom | ImportAll) -> None:\n    \"\"\"Read location and metadata flags from buffer and set them on the import statement.\n\n    Args:\n        data: Buffer containing serialized data\n        stmt: Import, ImportFrom, or ImportAll statement to populate with location and metadata\n    \"\"\"\n    read_loc(data, stmt)\n\n    # Metadata flags as a single integer bitfield\n    flags = read_int(data)\n\n    # Extract individual flags using bitwise operations\n    # Bit 0: is_top_level\n    # Bit 1: is_unreachable\n    # Bit 2: is_mypy_only\n    stmt.is_top_level = (flags & 0x01) != 0\n    stmt.is_unreachable = (flags & 0x02) != 0\n    stmt.is_mypy_only = (flags & 0x04) != 0\n"
  },
  {
    "path": "mypy/nodes.py",
    "content": "\"\"\"Abstract syntax tree node classes (i.e. parse tree).\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom abc import abstractmethod\nfrom collections import defaultdict\nfrom collections.abc import Callable, Iterator, Sequence\nfrom contextlib import contextmanager\nfrom enum import Enum, unique\nfrom typing import (\n    TYPE_CHECKING,\n    Any,\n    Final,\n    Optional,\n    TypeAlias as _TypeAlias,\n    TypeGuard,\n    TypeVar,\n    Union,\n    cast,\n)\n\nfrom librt.internal import (\n    read_float as read_float_bare,\n    read_int as read_int_bare,\n    read_str as read_str_bare,\n    write_int as write_int_bare,\n    write_str as write_str_bare,\n)\nfrom mypy_extensions import trait\n\nimport mypy.strconv\nfrom mypy.cache import (\n    DICT_INT_GEN,\n    DICT_STR_GEN,\n    DT_SPEC,\n    END_TAG,\n    LIST_GEN,\n    LIST_STR,\n    LITERAL_COMPLEX,\n    LITERAL_NONE,\n    ReadBuffer,\n    Tag,\n    WriteBuffer,\n    read_bool,\n    read_bytes,\n    read_int,\n    read_int_list,\n    read_int_opt,\n    read_json,\n    read_literal,\n    read_str,\n    read_str_list,\n    read_str_opt,\n    read_str_opt_list,\n    read_tag,\n    write_bool,\n    write_bytes,\n    write_int,\n    write_int_list,\n    write_int_opt,\n    write_json,\n    write_literal,\n    write_str,\n    write_str_list,\n    write_str_opt,\n    write_str_opt_list,\n    write_tag,\n)\nfrom mypy.options import Options\nfrom mypy.util import is_sunder, is_typeshed_file, short_type\nfrom mypy.visitor import ExpressionVisitor, NodeVisitor, StatementVisitor\n\nif TYPE_CHECKING:\n    from mypy.patterns import Pattern\n\n\n@unique\nclass NotParsed(Enum):\n    VALUE = \"NotParsed\"\n\n\nclass Context:\n    \"\"\"Base type for objects that are valid as error message locations.\"\"\"\n\n    __slots__ = (\"line\", \"column\", \"end_line\", \"end_column\")\n\n    def __init__(self, line: int = -1, column: int = -1) -> None:\n        self.line = line\n        self.column = column\n        self.end_line: int | None = None\n        self.end_column: int | None = None\n\n    def set_line(\n        self,\n        target: Context | int,\n        column: int | None = None,\n        end_line: int | None = None,\n        end_column: int | None = None,\n    ) -> None:\n        \"\"\"If target is a node, pull line (and column) information\n        into this node. If column is specified, this will override any column\n        information coming from a node.\n        \"\"\"\n        if isinstance(target, int):\n            self.line = target\n        else:\n            self.line = target.line\n            self.column = target.column\n            self.end_line = target.end_line\n            self.end_column = target.end_column\n\n        if column is not None:\n            self.column = column\n\n        if end_line is not None:\n            self.end_line = end_line\n\n        if end_column is not None:\n            self.end_column = end_column\n\n\nif TYPE_CHECKING:\n    # break import cycle only needed for mypy\n    import mypy.types\n\n\nT = TypeVar(\"T\")\n\nJsonDict: _TypeAlias = dict[str, Any]\n\n\n# Symbol table node kinds\n#\n# TODO rename to use more descriptive names\n\nLDEF: Final = 0\nGDEF: Final = 1\nMDEF: Final = 2\n\n# Placeholder for a name imported via 'from ... import'. Second phase of\n# semantic will replace this the actual imported reference. This is\n# needed so that we can detect whether a name has been imported during\n# XXX what?\nUNBOUND_IMPORTED: Final = 3\n\n# RevealExpr node kinds\nREVEAL_TYPE: Final = 0\nREVEAL_LOCALS: Final = 1\n\n# Kinds of 'literal' expressions.\n#\n# Use the function mypy.literals.literal to calculate these.\n#\n# TODO: Can we make these less confusing?\nLITERAL_YES: Final = 2  # Value of expression known statically\nLITERAL_TYPE: Final = 1  # Type of expression can be narrowed (e.g. variable reference)\nLITERAL_NO: Final = 0  # None of the above\n\nnode_kinds: Final = {LDEF: \"Ldef\", GDEF: \"Gdef\", MDEF: \"Mdef\", UNBOUND_IMPORTED: \"UnboundImported\"}\ninverse_node_kinds: Final = {_kind: _name for _name, _kind in node_kinds.items()}\n\n\nimplicit_module_attrs: Final = {\n    \"__name__\": \"__builtins__.str\",\n    \"__doc__\": None,  # depends on Python version, see semanal.py\n    \"__path__\": None,  # depends on if the module is a package\n    \"__file__\": \"__builtins__.str\",\n    \"__package__\": \"__builtins__.str\",\n    \"__annotations__\": None,  # dict[str, Any] bounded in add_implicit_module_attrs()\n    \"__spec__\": None,  # importlib.machinery.ModuleSpec bounded in add_implicit_module_attrs()\n}\n\n\n# These aliases exist because built-in class objects are not subscriptable.\n# For example `list[int]` fails at runtime. Instead List[int] should be used.\ntype_aliases: Final = {\n    \"typing.List\": \"builtins.list\",\n    \"typing.Dict\": \"builtins.dict\",\n    \"typing.Set\": \"builtins.set\",\n    \"typing.FrozenSet\": \"builtins.frozenset\",\n    \"typing.ChainMap\": \"collections.ChainMap\",\n    \"typing.Counter\": \"collections.Counter\",\n    \"typing.DefaultDict\": \"collections.defaultdict\",\n    \"typing.Deque\": \"collections.deque\",\n    \"typing.OrderedDict\": \"collections.OrderedDict\",\n    # HACK: a lie in lieu of actual support for PEP 675\n    \"typing.LiteralString\": \"builtins.str\",\n}\n\n# This keeps track of the oldest supported Python version where the corresponding\n# alias source is available.\ntype_aliases_source_versions: Final = {\"typing.LiteralString\": (3, 11)}\n\n# This keeps track of aliases in `typing_extensions`, which we treat specially.\ntyping_extensions_aliases: Final = {\n    # See: https://github.com/python/mypy/issues/11528\n    \"typing_extensions.OrderedDict\": \"collections.OrderedDict\",\n    # HACK: a lie in lieu of actual support for PEP 675\n    \"typing_extensions.LiteralString\": \"builtins.str\",\n}\n\nreverse_builtin_aliases: Final = {\n    \"builtins.list\": \"typing.List\",\n    \"builtins.dict\": \"typing.Dict\",\n    \"builtins.set\": \"typing.Set\",\n    \"builtins.frozenset\": \"typing.FrozenSet\",\n}\n\n\nRUNTIME_PROTOCOL_DECOS: Final = (\n    \"typing.runtime_checkable\",\n    \"typing_extensions.runtime\",\n    \"typing_extensions.runtime_checkable\",\n)\n\nLAMBDA_NAME: Final = \"<lambda>\"\n\n\nclass Node(Context):\n    \"\"\"Common base class for all non-type parse tree nodes.\"\"\"\n\n    __slots__ = ()\n\n    def __str__(self) -> str:\n        return self.accept(mypy.strconv.StrConv(options=Options()))\n\n    def str_with_options(self, options: Options) -> str:\n        a = self.accept(mypy.strconv.StrConv(options=options))\n        assert a\n        return a\n\n    def accept(self, visitor: NodeVisitor[T]) -> T:\n        raise RuntimeError(\"Not implemented\", type(self))\n\n\n@trait\nclass Statement(Node):\n    \"\"\"A statement node.\"\"\"\n\n    __slots__ = ()\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        raise RuntimeError(\"Not implemented\", type(self))\n\n\n@trait\nclass Expression(Node):\n    \"\"\"An expression node.\"\"\"\n\n    __slots__ = ()\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        raise RuntimeError(\"Not implemented\", type(self))\n\n\nclass FakeExpression(Expression):\n    \"\"\"A dummy expression.\n\n    We need a dummy expression in one place, and can't instantiate Expression\n    because it is a trait and mypyc barfs.\n    \"\"\"\n\n    __slots__ = ()\n\n\n# TODO:\n# Lvalue = Union['NameExpr', 'MemberExpr', 'IndexExpr', 'SuperExpr', 'StarExpr'\n#                'TupleExpr']; see #1783.\nLvalue: _TypeAlias = Expression\n\n\n@trait\nclass SymbolNode(Node):\n    \"\"\"Nodes that can be stored in a symbol table.\"\"\"\n\n    __slots__ = ()\n\n    @property\n    @abstractmethod\n    def name(self) -> str:\n        pass\n\n    # Fully qualified name\n    @property\n    @abstractmethod\n    def fullname(self) -> str:\n        pass\n\n    @abstractmethod\n    def serialize(self) -> JsonDict:\n        pass\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> SymbolNode:\n        classname = data[\".class\"]\n        method = deserialize_map.get(classname)\n        if method is not None:\n            return method(data)\n        raise NotImplementedError(f\"unexpected .class {classname}\")\n\n    def write(self, data: WriteBuffer) -> None:\n        raise NotImplementedError(f\"Cannot serialize {self.__class__.__name__} instance\")\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> SymbolNode:\n        raise NotImplementedError(f\"Cannot deserialize {cls.__name__} instance\")\n\n\n# Items: fullname, related symbol table node, surrounding type (if any)\nDefinition: _TypeAlias = tuple[str, \"SymbolTableNode\", Optional[\"TypeInfo\"]]\n\n\nclass FileRawData:\n    \"\"\"Raw (binary) data representing parsed, but not deserialized file.\"\"\"\n\n    __slots__ = (\n        \"defs\",\n        \"imports\",\n        \"raw_errors\",\n        \"ignored_lines\",\n        \"is_partial_stub_package\",\n        \"uses_template_strings\",\n    )\n\n    defs: bytes\n    imports: bytes\n    raw_errors: list[dict[str, Any]]  # TODO: switch to more precise type here.\n    ignored_lines: dict[int, list[str]]\n    is_partial_stub_package: bool\n    uses_template_strings: bool\n\n    def __init__(\n        self,\n        defs: bytes,\n        imports: bytes,\n        raw_errors: list[dict[str, Any]],\n        ignored_lines: dict[int, list[str]],\n        is_partial_stub_package: bool,\n        uses_template_strings: bool,\n    ) -> None:\n        self.defs = defs\n        self.imports = imports\n        self.raw_errors = raw_errors\n        self.ignored_lines = ignored_lines\n        self.is_partial_stub_package = is_partial_stub_package\n        self.uses_template_strings = uses_template_strings\n\n    def write(self, data: WriteBuffer) -> None:\n        write_bytes(data, self.defs)\n        write_bytes(data, self.imports)\n        write_tag(data, LIST_GEN)\n        write_int_bare(data, len(self.raw_errors))\n        for err in self.raw_errors:\n            write_json(data, err)\n        write_tag(data, DICT_INT_GEN)\n        write_int_bare(data, len(self.ignored_lines))\n        for line, codes in self.ignored_lines.items():\n            write_int(data, line)\n            write_str_list(data, codes)\n        write_bool(data, self.is_partial_stub_package)\n        write_bool(data, self.uses_template_strings)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> FileRawData:\n        defs = read_bytes(data)\n        imports = read_bytes(data)\n        assert read_tag(data) == LIST_GEN\n        raw_errors = [read_json(data) for _ in range(read_int_bare(data))]\n        assert read_tag(data) == DICT_INT_GEN\n        ignored_lines = {read_int(data): read_str_list(data) for _ in range(read_int_bare(data))}\n        return FileRawData(\n            defs, imports, raw_errors, ignored_lines, read_bool(data), read_bool(data)\n        )\n\n\nclass MypyFile(SymbolNode):\n    \"\"\"The abstract syntax tree of a single source file.\"\"\"\n\n    __slots__ = (\n        \"_fullname\",\n        \"path\",\n        \"defs\",\n        \"alias_deps\",\n        \"module_refs\",\n        \"is_bom\",\n        \"names\",\n        \"imports\",\n        \"ignored_lines\",\n        \"skipped_lines\",\n        \"is_stub\",\n        \"is_cache_skeleton\",\n        \"is_partial_stub_package\",\n        \"uses_template_strings\",\n        \"plugin_deps\",\n        \"future_import_flags\",\n        \"_is_typeshed_file\",\n        \"raw_data\",\n    )\n\n    __match_args__ = (\"name\", \"path\", \"defs\")\n\n    # Fully qualified module name\n    _fullname: str\n    # Path to the file (empty string if not known)\n    path: str\n    # Top-level definitions and statements\n    defs: list[Statement]\n    # Type alias dependencies as mapping from target to set of alias full names\n    alias_deps: defaultdict[str, set[str]]\n    # The set of all dependencies (suppressed or not) that this module accesses, either\n    # directly or indirectly.\n    module_refs: set[str]\n    # Is there a UTF-8 BOM at the start?\n    is_bom: bool\n    names: SymbolTable\n    # All import nodes within the file (also ones within functions etc.)\n    imports: list[ImportBase]\n    # Lines on which to ignore certain errors when checking.\n    # If the value is empty, ignore all errors; otherwise, the list contains all\n    # error codes to ignore.\n    ignored_lines: dict[int, list[str]]\n    # Lines that were skipped during semantic analysis e.g. due to ALWAYS_FALSE, MYPY_FALSE,\n    # or platform/version checks. Those lines would not be type-checked.\n    skipped_lines: set[int]\n    # Is this file represented by a stub file (.pyi)?\n    is_stub: bool\n    # Is this loaded from the cache and thus missing the actual body of the file?\n    is_cache_skeleton: bool\n    # Does this represent an __init__.pyi stub with a module __getattr__\n    # (i.e. a partial stub package), for such packages we suppress any missing\n    # module errors in addition to missing attribute errors.\n    is_partial_stub_package: bool\n    # True if module contains at least one t-string (PEP 750 TemplateStr).\n    uses_template_strings: bool\n    # Plugin-created dependencies\n    plugin_deps: dict[str, set[str]]\n    # Future imports defined in this file. Populated during semantic analysis.\n    future_import_flags: set[str]\n    _is_typeshed_file: bool | None\n    # For native parser store actual serialized data here.\n    raw_data: FileRawData | None\n\n    def __init__(\n        self,\n        defs: list[Statement],\n        imports: list[ImportBase],\n        is_bom: bool = False,\n        ignored_lines: dict[int, list[str]] | None = None,\n    ) -> None:\n        super().__init__()\n        self.defs = defs\n        self.line = 1  # Dummy line number\n        self.column = 0  # Dummy column\n        self.imports = imports\n        self.is_bom = is_bom\n        self.alias_deps = defaultdict(set)\n        self.module_refs = set()\n        self.plugin_deps = {}\n        if ignored_lines:\n            self.ignored_lines = ignored_lines\n        else:\n            self.ignored_lines = {}\n        self.skipped_lines = set()\n\n        self.path = \"\"\n        self.is_stub = False\n        self.is_cache_skeleton = False\n        self.is_partial_stub_package = False\n        self.uses_template_strings = False\n        self.future_import_flags = set()\n        self._is_typeshed_file = None\n        self.raw_data = None\n\n    def local_definitions(self) -> Iterator[Definition]:\n        \"\"\"Return all definitions within the module (including nested).\n\n        This doesn't include imported definitions.\n        \"\"\"\n        return local_definitions(self.names, self.fullname)\n\n    @property\n    def name(self) -> str:\n        return \"\" if not self._fullname else self._fullname.split(\".\")[-1]\n\n    @property\n    def fullname(self) -> str:\n        return self._fullname\n\n    def accept(self, visitor: NodeVisitor[T]) -> T:\n        return visitor.visit_mypy_file(self)\n\n    def is_package_init_file(self) -> bool:\n        return len(self.path) != 0 and os.path.basename(self.path).startswith(\"__init__.\")\n\n    def is_future_flag_set(self, flag: str) -> bool:\n        return flag in self.future_import_flags\n\n    def is_typeshed_file(self, options: Options) -> bool:\n        # Cache result since this is called a lot\n        if self._is_typeshed_file is None:\n            self._is_typeshed_file = is_typeshed_file(options.abs_custom_typeshed_dir, self.path)\n        return self._is_typeshed_file\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"MypyFile\",\n            \"_fullname\": self._fullname,\n            \"names\": self.names.serialize(self._fullname),\n            \"is_stub\": self.is_stub,\n            \"path\": self.path,\n            \"is_partial_stub_package\": self.is_partial_stub_package,\n            \"future_import_flags\": sorted(self.future_import_flags),\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> MypyFile:\n        assert data[\".class\"] == \"MypyFile\", data\n        tree = MypyFile([], [])\n        tree._fullname = data[\"_fullname\"]\n        tree.names = SymbolTable.deserialize(data[\"names\"])\n        tree.is_stub = data[\"is_stub\"]\n        tree.path = data[\"path\"]\n        tree.is_partial_stub_package = data[\"is_partial_stub_package\"]\n        tree.is_cache_skeleton = True\n        tree.future_import_flags = set(data[\"future_import_flags\"])\n        return tree\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, MYPY_FILE)\n        write_str(data, self._fullname)\n        self.names.write(data, self._fullname)\n        write_bool(data, self.is_stub)\n        write_str(data, self.path)\n        write_bool(data, self.is_partial_stub_package)\n        write_str_list(data, sorted(self.future_import_flags))\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> MypyFile:\n        assert read_tag(data) == MYPY_FILE\n        tree = MypyFile([], [])\n        tree._fullname = read_str(data)\n        tree.names = SymbolTable.read(data)\n        tree.is_stub = read_bool(data)\n        tree.path = read_str(data)\n        tree.is_partial_stub_package = read_bool(data)\n        tree.future_import_flags = set(read_str_list(data))\n        tree.is_cache_skeleton = True\n        assert read_tag(data) == END_TAG\n        return tree\n\n\nclass ImportBase(Statement):\n    \"\"\"Base class for all import statements.\"\"\"\n\n    __slots__ = (\"is_unreachable\", \"is_top_level\", \"is_mypy_only\", \"assignments\")\n\n    is_unreachable: bool  # Set by semanal.SemanticAnalyzerPass1 if inside `if False` etc.\n    is_top_level: bool  # Ditto if outside any class or def\n    is_mypy_only: bool  # Ditto if inside `if TYPE_CHECKING` or `if MYPY`\n\n    # If an import replaces existing definitions, we construct dummy assignment\n    # statements that assign the imported names to the names in the current scope,\n    # for type checking purposes. Example:\n    #\n    #     x = 1\n    #     from m import x   <-- add assignment representing \"x = m.x\"\n    assignments: list[AssignmentStmt]\n\n    def __init__(self) -> None:\n        super().__init__()\n        self.assignments = []\n        self.is_unreachable = False\n        self.is_top_level = False\n        self.is_mypy_only = False\n\n\nclass Import(ImportBase):\n    \"\"\"import m [as n]\"\"\"\n\n    __slots__ = (\"ids\",)\n\n    __match_args__ = (\"ids\",)\n\n    ids: list[tuple[str, str | None]]  # (module id, as id)\n\n    def __init__(self, ids: list[tuple[str, str | None]]) -> None:\n        super().__init__()\n        self.ids = ids\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_import(self)\n\n\nclass ImportFrom(ImportBase):\n    \"\"\"from m import x [as y], ...\"\"\"\n\n    __slots__ = (\"id\", \"names\", \"relative\")\n\n    __match_args__ = (\"id\", \"names\", \"relative\")\n\n    id: str\n    relative: int\n    names: list[tuple[str, str | None]]  # Tuples (name, as name)\n\n    def __init__(self, id: str, relative: int, names: list[tuple[str, str | None]]) -> None:\n        super().__init__()\n        self.id = id\n        self.names = names\n        self.relative = relative\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_import_from(self)\n\n\nclass ImportAll(ImportBase):\n    \"\"\"from m import *\"\"\"\n\n    __slots__ = (\"id\", \"relative\")\n\n    __match_args__ = (\"id\", \"relative\")\n\n    id: str\n    relative: int\n\n    def __init__(self, id: str, relative: int) -> None:\n        super().__init__()\n        self.id = id\n        self.relative = relative\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_import_all(self)\n\n\nFUNCBASE_FLAGS: Final = [\"is_property\", \"is_class\", \"is_static\", \"is_final\"]\n\n\nclass FuncBase(Node):\n    \"\"\"Abstract base class for function-like nodes.\n\n    N.B: Although this has SymbolNode subclasses (FuncDef,\n    OverloadedFuncDef), avoid calling isinstance(..., FuncBase) on\n    something that is typed as SymbolNode.  This is to work around\n    mypy bug #3603, in which mypy doesn't understand multiple\n    inheritance very well, and will assume that a SymbolNode\n    cannot be a FuncBase.\n\n    Instead, test against SYMBOL_FUNCBASE_TYPES, which enumerates\n    SymbolNode subclasses that are also FuncBase subclasses.\n    \"\"\"\n\n    __slots__ = (\n        \"type\",\n        \"unanalyzed_type\",\n        \"info\",\n        \"is_property\",\n        \"is_class\",  # Uses \"@classmethod\" (explicit or implicit)\n        \"is_static\",  # Uses \"@staticmethod\" (explicit or implicit)\n        \"is_final\",  # Uses \"@final\"\n        \"is_explicit_override\",  # Uses \"@override\"\n        \"is_type_check_only\",  # Uses \"@type_check_only\"\n        \"def_or_infer_vars\",\n        \"_fullname\",\n    )\n\n    def __init__(self) -> None:\n        super().__init__()\n        # Type signature. This is usually CallableType or Overloaded, but it can be\n        # something else for decorated functions.\n        self.type: mypy.types.ProperType | None = None\n        # Original, not semantically analyzed type (used for reprocessing)\n        self.unanalyzed_type: mypy.types.ProperType | None = None\n        # If method, reference to TypeInfo\n        self.info = FUNC_NO_INFO\n        self.is_property = False\n        self.is_class = False\n        # Is this a `@staticmethod` (explicit or implicit)?\n        # Note: use has_self_or_cls_argument to check if there is `self` or `cls` argument\n        self.is_static = False\n        self.is_final = False\n        self.is_explicit_override = False\n        self.is_type_check_only = False\n        # Can this function/method define variables or infer variables defined outside?\n        # In particular, we set this in cases like:\n        #     x = None\n        #     def foo() -> None:\n        #         global x\n        #         x = 1\n        # and\n        #     class C:\n        #         x = None\n        #         def foo(self) -> None:\n        #             self.x = 1\n        self.def_or_infer_vars = False\n        # Name with module prefix\n        self._fullname = \"\"\n\n    @property\n    @abstractmethod\n    def name(self) -> str:\n        pass\n\n    @property\n    def fullname(self) -> str:\n        return self._fullname\n\n    @property\n    def has_self_or_cls_argument(self) -> bool:\n        \"\"\"If used as a method, does it have an argument for method binding (`self`, `cls`)?\n\n        This is true for `__new__` even though `__new__` does not undergo method binding,\n        because we still usually assume that `cls` corresponds to the enclosing class.\n        \"\"\"\n        return not self.is_static or self.name == \"__new__\"\n\n\nOverloadPart: _TypeAlias = Union[\"FuncDef\", \"Decorator\"]\n\n\nclass OverloadedFuncDef(FuncBase, SymbolNode, Statement):\n    \"\"\"A logical node representing all the variants of a multi-declaration function.\n\n    A multi-declaration function is often an @overload, but can also be a\n    @property with a setter and a/or a deleter.\n\n    This node has no explicit representation in the source program.\n    Overloaded variants must be consecutive in the source file.\n    \"\"\"\n\n    __slots__ = (\n        \"items\",\n        \"unanalyzed_items\",\n        \"impl\",\n        \"deprecated\",\n        \"setter_index\",\n        \"_is_trivial_self\",\n    )\n\n    items: list[OverloadPart]\n    unanalyzed_items: list[OverloadPart]\n    impl: OverloadPart | None\n    deprecated: str | None\n    setter_index: int | None\n\n    def __init__(self, items: list[OverloadPart]) -> None:\n        super().__init__()\n        self.items = items\n        self.unanalyzed_items = items.copy()\n        self.impl = None\n        self.deprecated = None\n        self.setter_index = None\n        self._is_trivial_self: bool | None = None\n        if items:\n            # TODO: figure out how to reliably set end position (we don't know the impl here).\n            self.set_line(items[0].line, items[0].column)\n\n    @property\n    def name(self) -> str:\n        if self.items:\n            return self.items[0].name\n        else:\n            # This may happen for malformed overload\n            assert self.impl is not None\n            return self.impl.name\n\n    @property\n    def is_trivial_self(self) -> bool:\n        \"\"\"Check we can use bind_self() fast path for this overload.\n\n        This will return False if at least one overload:\n          * Has an explicit self annotation, or Self in signature.\n          * Has a non-trivial decorator.\n        \"\"\"\n        if self._is_trivial_self is not None:\n            return self._is_trivial_self\n        for i, item in enumerate(self.items):\n            # Note: bare @property is removed in visit_decorator().\n            trivial = 1 if i > 0 or not self.is_property else 0\n            if isinstance(item, FuncDef):\n                if not item.is_trivial_self:\n                    self._is_trivial_self = False\n                    return False\n            elif len(item.decorators) > trivial or not item.func.is_trivial_self:\n                self._is_trivial_self = False\n                return False\n        self._is_trivial_self = True\n        return True\n\n    @property\n    def setter(self) -> Decorator:\n        # Do some consistency checks first.\n        first_item = self.items[0]\n        assert isinstance(first_item, Decorator)\n        assert first_item.var.is_settable_property\n        assert self.setter_index is not None\n        item = self.items[self.setter_index]\n        assert isinstance(item, Decorator)\n        return item\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_overloaded_func_def(self)\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"OverloadedFuncDef\",\n            \"items\": [i.serialize() for i in self.items],\n            \"type\": None if self.type is None else self.type.serialize(),\n            \"fullname\": self._fullname,\n            \"impl\": None if self.impl is None else self.impl.serialize(),\n            \"flags\": get_flags(self, FUNCBASE_FLAGS),\n            \"deprecated\": self.deprecated,\n            \"setter_index\": self.setter_index,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> OverloadedFuncDef:\n        assert data[\".class\"] == \"OverloadedFuncDef\"\n        res = OverloadedFuncDef(\n            [cast(OverloadPart, SymbolNode.deserialize(d)) for d in data[\"items\"]]\n        )\n        if data.get(\"impl\") is not None:\n            res.impl = cast(OverloadPart, SymbolNode.deserialize(data[\"impl\"]))\n            # set line for empty overload items, as not set in __init__\n            if len(res.items) > 0:\n                res.set_line(res.impl.line)\n        if data.get(\"type\") is not None:\n            typ = mypy.types.deserialize_type(data[\"type\"])\n            assert isinstance(typ, mypy.types.ProperType)\n            res.type = typ\n        res._fullname = data[\"fullname\"]\n        set_flags(res, data[\"flags\"])\n        res.deprecated = data[\"deprecated\"]\n        res.setter_index = data[\"setter_index\"]\n        # NOTE: res.info will be set in the fixup phase.\n        return res\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, OVERLOADED_FUNC_DEF)\n        write_tag(data, LIST_GEN)\n        write_int_bare(data, len(self.items))\n        for item in self.items:\n            item.write(data)\n        mypy.types.write_type_opt(data, self.type)\n        write_str(data, self._fullname)\n        if self.impl is None:\n            write_tag(data, LITERAL_NONE)\n        else:\n            self.impl.write(data)\n        write_flags(data, [self.is_property, self.is_class, self.is_static, self.is_final])\n        write_str_opt(data, self.deprecated)\n        write_int_opt(data, self.setter_index)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> OverloadedFuncDef:\n        assert read_tag(data) == LIST_GEN\n        res = OverloadedFuncDef([read_overload_part(data) for _ in range(read_int_bare(data))])\n        typ = mypy.types.read_type_opt(data)\n        if typ is not None:\n            assert isinstance(typ, mypy.types.ProperType)\n            res.type = typ\n        res._fullname = read_str(data)\n        tag = read_tag(data)\n        if tag != LITERAL_NONE:\n            res.impl = read_overload_part(data, tag)\n            # set line for empty overload items, as not set in __init__\n            if len(res.items) > 0:\n                res.set_line(res.impl.line)\n        res.is_property, res.is_class, res.is_static, res.is_final = read_flags(data, num_flags=4)\n        res.deprecated = read_str_opt(data)\n        res.setter_index = read_int_opt(data)\n        # NOTE: res.info will be set in the fixup phase.\n        assert read_tag(data) == END_TAG\n        return res\n\n    def is_dynamic(self) -> bool:\n        return all(item.is_dynamic() for item in self.items)\n\n\nclass Argument(Node):\n    \"\"\"A single argument in a FuncItem.\"\"\"\n\n    __slots__ = (\"variable\", \"type_annotation\", \"initializer\", \"kind\", \"pos_only\")\n\n    __match_args__ = (\"variable\", \"type_annotation\", \"initializer\", \"kind\", \"pos_only\")\n\n    def __init__(\n        self,\n        variable: Var,\n        type_annotation: mypy.types.Type | None,\n        initializer: Expression | None,\n        kind: ArgKind,\n        pos_only: bool = False,\n    ) -> None:\n        super().__init__()\n        self.variable = variable\n        self.type_annotation = type_annotation\n        self.initializer = initializer\n        self.kind = kind  # must be an ARG_* constant\n        self.pos_only = pos_only\n\n    def set_line(\n        self,\n        target: Context | int,\n        column: int | None = None,\n        end_line: int | None = None,\n        end_column: int | None = None,\n    ) -> None:\n        super().set_line(target, column, end_line, end_column)\n\n        if self.initializer and self.initializer.line < 0:\n            self.initializer.set_line(self.line, self.column, self.end_line, self.end_column)\n\n        self.variable.set_line(self.line, self.column, self.end_line, self.end_column)\n\n\n# These specify the kind of a TypeParam\nTYPE_VAR_KIND: Final = 0\nPARAM_SPEC_KIND: Final = 1\nTYPE_VAR_TUPLE_KIND: Final = 2\n\n\nclass TypeParam:\n    __slots__ = (\"name\", \"kind\", \"upper_bound\", \"values\", \"default\")\n\n    def __init__(\n        self,\n        name: str,\n        kind: int,\n        upper_bound: mypy.types.Type | None,\n        values: list[mypy.types.Type],\n        default: mypy.types.Type | None,\n    ) -> None:\n        self.name = name\n        self.kind = kind\n        self.upper_bound = upper_bound\n        self.values = values\n        self.default = default\n\n\nFUNCITEM_FLAGS: Final = FUNCBASE_FLAGS + [\n    \"is_overload\",\n    \"is_generator\",\n    \"is_coroutine\",\n    \"is_async_generator\",\n    \"is_awaitable_coroutine\",\n]\n\n\nclass FuncItem(FuncBase):\n    \"\"\"Base class for nodes usable as overloaded function items.\"\"\"\n\n    __slots__ = (\n        \"arguments\",  # Note that can be unset if deserialized (type is a lie!)\n        \"arg_names\",  # Names of arguments\n        \"arg_kinds\",  # Kinds of arguments\n        \"min_args\",  # Minimum number of arguments\n        \"max_pos\",  # Maximum number of positional arguments, -1 if no explicit\n        # limit (*args not included)\n        \"type_args\",  # New-style type parameters (PEP 695)\n        \"body\",  # Body of the function\n        \"is_overload\",  # Is this an overload variant of function with more than\n        # one overload variant?\n        \"is_generator\",  # Contains a yield statement?\n        \"is_coroutine\",  # Defined using 'async def' syntax?\n        \"is_async_generator\",  # Is an async def generator?\n        \"is_awaitable_coroutine\",  # Decorated with '@{typing,asyncio}.coroutine'?\n        \"expanded\",  # Variants of function with type variables with values expanded\n    )\n\n    __deletable__ = (\"arguments\", \"max_pos\", \"min_args\")\n\n    def __init__(\n        self,\n        arguments: list[Argument] | None = None,\n        body: Block | None = None,\n        typ: mypy.types.FunctionLike | None = None,\n        type_args: list[TypeParam] | None = None,\n    ) -> None:\n        super().__init__()\n        self.arguments = arguments or []\n        self.arg_names = [None if arg.pos_only else arg.variable.name for arg in self.arguments]\n        self.arg_kinds: list[ArgKind] = [arg.kind for arg in self.arguments]\n        self.max_pos: int = self.arg_kinds.count(ARG_POS) + self.arg_kinds.count(ARG_OPT)\n        self.type_args: list[TypeParam] | None = type_args\n        self.body: Block = body or Block([])\n        self.type = typ\n        self.unanalyzed_type = typ\n        self.is_overload: bool = False\n        self.is_generator: bool = False\n        self.is_coroutine: bool = False\n        self.is_async_generator: bool = False\n        self.is_awaitable_coroutine: bool = False\n        self.expanded: list[FuncItem] = []\n\n        self.min_args = 0\n        for i in range(len(self.arguments)):\n            if self.arguments[i] is None and i < self.max_fixed_argc():\n                self.min_args = i + 1\n\n    def max_fixed_argc(self) -> int:\n        return self.max_pos\n\n    def is_dynamic(self) -> bool:\n        return self.type is None\n\n\nFUNCDEF_FLAGS: Final = FUNCITEM_FLAGS + [\n    \"is_decorated\",\n    \"is_conditional\",\n    \"is_trivial_body\",\n    \"is_trivial_self\",\n    \"is_mypy_only\",\n]\n\n# Abstract status of a function\nNOT_ABSTRACT: Final = 0\n# Explicitly abstract (with @abstractmethod or overload without implementation)\nIS_ABSTRACT: Final = 1\n# Implicitly abstract: used for functions with trivial bodies defined in Protocols\nIMPLICITLY_ABSTRACT: Final = 2\n\n\nclass FuncDef(FuncItem, SymbolNode, Statement):\n    \"\"\"Function definition.\n\n    This is a non-lambda function defined using 'def'.\n    \"\"\"\n\n    __slots__ = (\n        \"_name\",\n        \"is_decorated\",\n        \"is_conditional\",\n        \"abstract_status\",\n        \"original_def\",\n        \"is_trivial_body\",\n        \"is_trivial_self\",\n        \"is_mypy_only\",\n        # Present only when a function is decorated with @typing.dataclass_transform or similar\n        \"dataclass_transform_spec\",\n        \"docstring\",\n        \"deprecated\",\n        \"original_first_arg\",\n    )\n\n    __match_args__ = (\"name\", \"arguments\", \"type\", \"body\")\n\n    # Note that all __init__ args must have default values\n    def __init__(\n        self,\n        name: str = \"\",  # Function name\n        arguments: list[Argument] | None = None,\n        body: Block | None = None,\n        typ: mypy.types.FunctionLike | None = None,\n        type_args: list[TypeParam] | None = None,\n    ) -> None:\n        super().__init__(arguments, body, typ, type_args)\n        self._name = name\n        self.is_decorated = False\n        self.is_conditional = False  # Defined conditionally (within block)?\n        self.abstract_status = NOT_ABSTRACT\n        # Is this an abstract method with trivial body?\n        # Such methods can't be called via super().\n        self.is_trivial_body = False\n        # Original conditional definition\n        self.original_def: None | FuncDef | Var | Decorator = None\n        # Definitions that appear in if TYPE_CHECKING are marked with this flag.\n        self.is_mypy_only = False\n        self.dataclass_transform_spec: DataclassTransformSpec | None = None\n        self.docstring: str | None = None\n        self.deprecated: str | None = None\n        # This is used to simplify bind_self() logic in trivial cases (which are\n        # the majority). In cases where self is not annotated and there are no Self\n        # in the signature we can simply drop the first argument.\n        self.is_trivial_self = False\n        # This is needed because for positional-only arguments the name is set to None,\n        # but we sometimes still want to show it in error messages.\n        if arguments:\n            self.original_first_arg: str | None = arguments[0].variable.name\n        else:\n            self.original_first_arg = None\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_func_def(self)\n\n    def serialize(self) -> JsonDict:\n        # We're deliberating omitting arguments and storing only arg_names and\n        # arg_kinds for space-saving reasons (arguments is not used in later\n        # stages of mypy).\n        # TODO: After a FuncDef is deserialized, the only time we use `arg_names`\n        # and `arg_kinds` is when `type` is None and we need to infer a type. Can\n        # we store the inferred type ahead of time?\n        return {\n            \".class\": \"FuncDef\",\n            \"name\": self._name,\n            \"fullname\": self._fullname,\n            \"arg_names\": self.arg_names,\n            \"arg_kinds\": [int(x.value) for x in self.arg_kinds],\n            \"type\": None if self.type is None else self.type.serialize(),\n            \"flags\": get_flags(self, FUNCDEF_FLAGS),\n            \"abstract_status\": self.abstract_status,\n            # TODO: Do we need expanded, original_def?\n            \"dataclass_transform_spec\": (\n                None\n                if self.dataclass_transform_spec is None\n                else self.dataclass_transform_spec.serialize()\n            ),\n            \"deprecated\": self.deprecated,\n            \"original_first_arg\": self.original_first_arg,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> FuncDef:\n        assert data[\".class\"] == \"FuncDef\"\n        body = Block([])\n        ret = FuncDef(\n            data[\"name\"],\n            [],\n            body,\n            (\n                None\n                if data[\"type\"] is None\n                else cast(mypy.types.FunctionLike, mypy.types.deserialize_type(data[\"type\"]))\n            ),\n        )\n        ret._fullname = data[\"fullname\"]\n        set_flags(ret, data[\"flags\"])\n        # NOTE: ret.info is set in the fixup phase.\n        ret.arg_names = data[\"arg_names\"]\n        ret.original_first_arg = data.get(\"original_first_arg\")\n        ret.arg_kinds = [ARG_KINDS[x] for x in data[\"arg_kinds\"]]\n        ret.abstract_status = data[\"abstract_status\"]\n        ret.dataclass_transform_spec = (\n            DataclassTransformSpec.deserialize(data[\"dataclass_transform_spec\"])\n            if data[\"dataclass_transform_spec\"] is not None\n            else None\n        )\n        ret.deprecated = data[\"deprecated\"]\n        # Leave these uninitialized so that future uses will trigger an error\n        del ret.arguments\n        del ret.max_pos\n        del ret.min_args\n        return ret\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, FUNC_DEF)\n        write_str(data, self._name)\n        mypy.types.write_type_opt(data, self.type)\n        write_str(data, self._fullname)\n        write_flags(\n            data,\n            [\n                self.is_property,\n                self.is_class,\n                self.is_static,\n                self.is_final,\n                self.is_overload,\n                self.is_generator,\n                self.is_coroutine,\n                self.is_async_generator,\n                self.is_awaitable_coroutine,\n                self.is_decorated,\n                self.is_conditional,\n                self.is_trivial_body,\n                self.is_trivial_self,\n                self.is_mypy_only,\n            ],\n        )\n        write_str_opt_list(data, self.arg_names)\n        write_int_list(data, [int(ak.value) for ak in self.arg_kinds])\n        write_int(data, self.abstract_status)\n        if self.dataclass_transform_spec is None:\n            write_tag(data, LITERAL_NONE)\n        else:\n            self.dataclass_transform_spec.write(data)\n        write_str_opt(data, self.deprecated)\n        write_str_opt(data, self.original_first_arg)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> FuncDef:\n        name = read_str(data)\n        typ: mypy.types.FunctionLike | None = None\n        tag = read_tag(data)\n        if tag != LITERAL_NONE:\n            typ = mypy.types.read_function_like(data, tag)\n        ret = FuncDef(name, [], Block([]), typ)\n        ret._fullname = read_str(data)\n        (\n            ret.is_property,\n            ret.is_class,\n            ret.is_static,\n            ret.is_final,\n            ret.is_overload,\n            ret.is_generator,\n            ret.is_coroutine,\n            ret.is_async_generator,\n            ret.is_awaitable_coroutine,\n            ret.is_decorated,\n            ret.is_conditional,\n            ret.is_trivial_body,\n            ret.is_trivial_self,\n            ret.is_mypy_only,\n        ) = read_flags(data, num_flags=14)\n        # NOTE: ret.info is set in the fixup phase.\n        ret.arg_names = read_str_opt_list(data)\n        ret.arg_kinds = [ARG_KINDS[ak] for ak in read_int_list(data)]\n        ret.abstract_status = read_int(data)\n        tag = read_tag(data)\n        if tag != LITERAL_NONE:\n            assert tag == DT_SPEC\n            ret.dataclass_transform_spec = DataclassTransformSpec.read(data)\n        ret.deprecated = read_str_opt(data)\n        ret.original_first_arg = read_str_opt(data)\n        # Leave these uninitialized so that future uses will trigger an error\n        del ret.arguments\n        del ret.max_pos\n        del ret.min_args\n        assert read_tag(data) == END_TAG\n        return ret\n\n\n# All types that are both SymbolNodes and FuncBases. See the FuncBase\n# docstring for the rationale.\n# See https://github.com/python/mypy/pull/13607#issuecomment-1236357236\n# TODO: we want to remove this at some point and just use `FuncBase` ideally.\nSYMBOL_FUNCBASE_TYPES: Final = (OverloadedFuncDef, FuncDef)\n\n\nclass Decorator(SymbolNode, Statement):\n    \"\"\"A decorated function.\n\n    A single Decorator object can include any number of function decorators.\n    \"\"\"\n\n    __slots__ = (\"func\", \"decorators\", \"original_decorators\", \"var\", \"is_overload\")\n\n    __match_args__ = (\"decorators\", \"var\", \"func\")\n\n    func: FuncDef  # Decorated function\n    decorators: list[Expression]  # Decorators (may be empty)\n    # Some decorators are removed by semanal, keep the original here.\n    original_decorators: list[Expression]\n    # TODO: This is mostly used for the type; consider replacing with a 'type' attribute\n    var: Var  # Represents the decorated function obj\n    is_overload: bool\n\n    def __init__(self, func: FuncDef, decorators: list[Expression], var: Var) -> None:\n        super().__init__()\n        self.func = func\n        self.decorators = decorators\n        self.original_decorators = decorators.copy()\n        self.var = var\n        self.is_overload = False\n\n    @property\n    def name(self) -> str:\n        return self.func.name\n\n    @property\n    def fullname(self) -> str:\n        return self.func.fullname\n\n    @property\n    def is_final(self) -> bool:\n        return self.func.is_final\n\n    @property\n    def info(self) -> TypeInfo:\n        return self.func.info\n\n    @property\n    def type(self) -> mypy.types.Type | None:\n        return self.var.type\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_decorator(self)\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"Decorator\",\n            \"func\": self.func.serialize(),\n            \"var\": self.var.serialize(),\n            \"is_overload\": self.is_overload,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> Decorator:\n        assert data[\".class\"] == \"Decorator\"\n        dec = Decorator(FuncDef.deserialize(data[\"func\"]), [], Var.deserialize(data[\"var\"]))\n        dec.is_overload = data[\"is_overload\"]\n        return dec\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, DECORATOR)\n        self.func.write(data)\n        self.var.write(data)\n        write_bool(data, self.is_overload)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> Decorator:\n        assert read_tag(data) == FUNC_DEF\n        func = FuncDef.read(data)\n        assert read_tag(data) == VAR\n        var = Var.read(data)\n        dec = Decorator(func, [], var)\n        dec.is_overload = read_bool(data)\n        assert read_tag(data) == END_TAG\n        return dec\n\n    def is_dynamic(self) -> bool:\n        return self.func.is_dynamic()\n\n\nVAR_FLAGS: Final = [\n    \"is_self\",\n    \"is_cls\",\n    \"is_initialized_in_class\",\n    \"is_staticmethod\",\n    \"is_classmethod\",\n    \"is_property\",\n    \"is_settable_property\",\n    \"is_suppressed_import\",\n    \"is_classvar\",\n    \"is_abstract_var\",\n    \"is_final\",\n    \"is_index_var\",\n    \"final_unset_in_class\",\n    \"final_set_in_init\",\n    \"explicit_self_type\",\n    \"is_ready\",\n    \"is_inferred\",\n    \"invalid_partial_type\",\n    \"from_module_getattr\",\n    \"has_explicit_value\",\n    \"allow_incompatible_override\",\n]\n\n\nclass Var(SymbolNode):\n    \"\"\"A variable.\n\n    It can refer to global/local variable or a data attribute.\n    \"\"\"\n\n    __slots__ = (\n        \"_name\",\n        \"_fullname\",\n        \"info\",\n        \"type\",\n        \"setter_type\",\n        \"final_value\",\n        \"is_self\",\n        \"is_cls\",\n        \"is_ready\",\n        \"is_inferred\",\n        \"is_initialized_in_class\",\n        \"is_staticmethod\",\n        \"is_classmethod\",\n        \"is_property\",\n        \"is_settable_property\",\n        \"is_classvar\",\n        \"is_abstract_var\",\n        \"is_final\",\n        \"is_index_var\",\n        \"final_unset_in_class\",\n        \"final_set_in_init\",\n        \"is_suppressed_import\",\n        \"explicit_self_type\",\n        \"from_module_getattr\",\n        \"has_explicit_value\",\n        \"allow_incompatible_override\",\n        \"invalid_partial_type\",\n        \"is_argument\",\n    )\n\n    __match_args__ = (\"name\", \"type\", \"final_value\")\n\n    def __init__(self, name: str, type: mypy.types.Type | None = None) -> None:\n        super().__init__()\n        self._name = name  # Name without module prefix\n        # TODO: Should be Optional[str]\n        self._fullname = \"\"  # Name with module prefix\n        # TODO: Should be Optional[TypeInfo]\n        self.info = VAR_NO_INFO\n        self.type: mypy.types.Type | None = type  # Declared or inferred type, or None\n        # The setter type for settable properties.\n        self.setter_type: mypy.types.CallableType | None = None\n        # Is this the first argument to an ordinary method (usually \"self\")?\n        self.is_self = False\n        # Is this the first argument to a classmethod (typically \"cls\")?\n        self.is_cls = False\n        self.is_ready = True  # If inferred, is the inferred type available?\n        self.is_inferred = self.type is None\n        # Is this variable declared in class body? The name is confusing, but it\n        # is a very old attribute, and changing will break some plugins.\n        self.is_initialized_in_class = False\n        self.is_staticmethod = False\n        self.is_classmethod = False\n        self.is_property = False\n        self.is_settable_property = False\n        self.is_classvar = False\n        self.is_abstract_var = False\n        self.is_index_var = False\n        # Set to true when this variable refers to a module we were unable to\n        # parse for some reason (eg a silenced module)\n        self.is_suppressed_import = False\n        # Was this \"variable\" (rather a constant) defined as Final[...]?\n        self.is_final = False\n        # If constant value is a simple literal,\n        # store the literal value (unboxed) for the benefit of\n        # tools like mypyc.\n        self.final_value: int | float | complex | bool | str | None = None\n        # Where the value was set (only for class attributes)\n        self.final_unset_in_class = False\n        self.final_set_in_init = False\n        # This is True for a variable that was declared on self with an explicit type:\n        #     class C:\n        #         def __init__(self) -> None:\n        #             self.x: int\n        # This case is important because this defines a new Var, even if there is one\n        # present in a superclass (without explicit type this doesn't create a new Var).\n        # See SemanticAnalyzer.analyze_member_lvalue() for details.\n        self.explicit_self_type = False\n        # If True, this is an implicit Var created due to module-level __getattr__.\n        self.from_module_getattr = False\n        # Var can be created with an explicit value `a = 1` or without one `a: int`,\n        # we need a way to tell which one is which.\n        self.has_explicit_value = False\n        # If True, subclasses can override this with an incompatible type.\n        self.allow_incompatible_override = False\n        # If True, this means we didn't manage to infer full type and fall back to\n        # something like list[Any]. We may decide to not use such types as context.\n        self.invalid_partial_type = False\n        # Is it a variable symbol for a function argument?\n        self.is_argument = False\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    @property\n    def fullname(self) -> str:\n        return self._fullname\n\n    def __repr__(self) -> str:\n        name = self.fullname or self.name\n        return f\"<Var {name!r} at {hex(id(self))}>\"\n\n    def accept(self, visitor: NodeVisitor[T]) -> T:\n        return visitor.visit_var(self)\n\n    def serialize(self) -> JsonDict:\n        # TODO: Leave default values out?\n        # NOTE: Sometimes self.is_ready is False here, but we don't care.\n        data: JsonDict = {\n            \".class\": \"Var\",\n            \"name\": self._name,\n            \"fullname\": self._fullname,\n            \"type\": None if self.type is None else self.type.serialize(),\n            \"setter_type\": None if self.setter_type is None else self.setter_type.serialize(),\n            \"flags\": get_flags(self, VAR_FLAGS),\n        }\n        if self.final_value is not None:\n            data[\"final_value\"] = self.final_value\n        return data\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> Var:\n        assert data[\".class\"] == \"Var\"\n        name = data[\"name\"]\n        type = None if data[\"type\"] is None else mypy.types.deserialize_type(data[\"type\"])\n        setter_type = (\n            None\n            if data[\"setter_type\"] is None\n            else mypy.types.deserialize_type(data[\"setter_type\"])\n        )\n        v = Var(name, type)\n        assert (\n            setter_type is None\n            or isinstance(setter_type, mypy.types.ProperType)\n            and isinstance(setter_type, mypy.types.CallableType)\n        )\n        v.setter_type = setter_type\n        v.is_ready = False  # Override True default set in __init__\n        v._fullname = data[\"fullname\"]\n        set_flags(v, data[\"flags\"])\n        v.final_value = data.get(\"final_value\")\n        return v\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, VAR)\n        write_str(data, self._name)\n        mypy.types.write_type_opt(data, self.type)\n        mypy.types.write_type_opt(data, self.setter_type)\n        write_str(data, self._fullname)\n        write_flags(\n            data,\n            [\n                self.is_initialized_in_class,\n                self.is_staticmethod,\n                self.is_classmethod,\n                self.is_property,\n                self.is_settable_property,\n                self.is_suppressed_import,\n                self.is_classvar,\n                self.is_abstract_var,\n                self.is_final,\n                self.is_index_var,\n                self.final_unset_in_class,\n                self.final_set_in_init,\n                self.explicit_self_type,\n                self.is_ready,\n                self.is_inferred,\n                self.invalid_partial_type,\n                self.from_module_getattr,\n                self.has_explicit_value,\n                self.allow_incompatible_override,\n            ],\n        )\n        write_literal(data, self.final_value)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> Var:\n        name = read_str(data)\n        typ = mypy.types.read_type_opt(data)\n        v = Var(name, typ)\n        setter_type: mypy.types.CallableType | None = None\n        tag = read_tag(data)\n        if tag != LITERAL_NONE:\n            assert tag == mypy.types.CALLABLE_TYPE\n            setter_type = mypy.types.CallableType.read(data)\n        v.setter_type = setter_type\n        v._fullname = read_str(data)\n        (\n            v.is_initialized_in_class,\n            v.is_staticmethod,\n            v.is_classmethod,\n            v.is_property,\n            v.is_settable_property,\n            v.is_suppressed_import,\n            v.is_classvar,\n            v.is_abstract_var,\n            v.is_final,\n            v.is_index_var,\n            v.final_unset_in_class,\n            v.final_set_in_init,\n            v.explicit_self_type,\n            v.is_ready,\n            v.is_inferred,\n            v.invalid_partial_type,\n            v.from_module_getattr,\n            v.has_explicit_value,\n            v.allow_incompatible_override,\n        ) = read_flags(data, num_flags=19)\n        tag = read_tag(data)\n        if tag == LITERAL_COMPLEX:\n            v.final_value = complex(read_float_bare(data), read_float_bare(data))\n        elif tag != LITERAL_NONE:\n            v.final_value = read_literal(data, tag)\n        assert read_tag(data) == END_TAG\n        return v\n\n\nclass ClassDef(Statement):\n    \"\"\"Class definition\"\"\"\n\n    __slots__ = (\n        \"name\",\n        \"_fullname\",\n        \"defs\",\n        \"type_args\",\n        \"type_vars\",\n        \"base_type_exprs\",\n        \"removed_base_type_exprs\",\n        \"info\",\n        \"metaclass\",\n        \"decorators\",\n        \"keywords\",\n        \"analyzed\",\n        \"has_incompatible_baseclass\",\n        \"docstring\",\n        \"removed_statements\",\n    )\n\n    __match_args__ = (\"name\", \"defs\")\n\n    name: str  # Name of the class without module prefix\n    _fullname: str  # Fully qualified name of the class\n    defs: Block\n    # New-style type parameters (PEP 695), unanalyzed\n    type_args: list[TypeParam] | None\n    # Semantically analyzed type parameters (all syntax variants)\n    type_vars: list[mypy.types.TypeVarLikeType]\n    # Base class expressions (not semantically analyzed -- can be arbitrary expressions)\n    base_type_exprs: list[Expression]\n    # Special base classes like Generic[...] get moved here during semantic analysis\n    removed_base_type_exprs: list[Expression]\n    info: TypeInfo  # Related TypeInfo\n    metaclass: Expression | None\n    decorators: list[Expression]\n    keywords: dict[str, Expression]\n    analyzed: Expression | None\n    has_incompatible_baseclass: bool\n    # Used by special forms like NamedTuple and TypedDict to store invalid statements\n    removed_statements: list[Statement]\n\n    def __init__(\n        self,\n        name: str,\n        defs: Block,\n        type_vars: list[mypy.types.TypeVarLikeType] | None = None,\n        base_type_exprs: list[Expression] | None = None,\n        metaclass: Expression | None = None,\n        keywords: list[tuple[str, Expression]] | None = None,\n        type_args: list[TypeParam] | None = None,\n    ) -> None:\n        super().__init__()\n        self.name = name\n        self._fullname = \"\"\n        self.defs = defs\n        self.type_vars = type_vars or []\n        self.type_args = type_args\n        self.base_type_exprs = base_type_exprs or []\n        self.removed_base_type_exprs = []\n        self.info = CLASSDEF_NO_INFO\n        self.metaclass = metaclass\n        self.decorators = []\n        self.keywords = dict(keywords) if keywords else {}\n        self.analyzed = None\n        self.has_incompatible_baseclass = False\n        self.docstring: str | None = None\n        self.removed_statements = []\n\n    @property\n    def fullname(self) -> str:\n        return self._fullname\n\n    @fullname.setter\n    def fullname(self, v: str) -> None:\n        self._fullname = v\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_class_def(self)\n\n    def is_generic(self) -> bool:\n        return self.info.is_generic()\n\n    def serialize(self) -> JsonDict:\n        # Not serialized: defs, base_type_exprs, metaclass, decorators,\n        # analyzed (for named tuples etc.)\n        return {\n            \".class\": \"ClassDef\",\n            \"name\": self.name,\n            \"fullname\": self.fullname,\n            \"type_vars\": [v.serialize() for v in self.type_vars],\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> ClassDef:\n        assert data[\".class\"] == \"ClassDef\"\n        res = ClassDef(\n            data[\"name\"],\n            Block([]),\n            # https://github.com/python/mypy/issues/12257\n            [\n                cast(mypy.types.TypeVarLikeType, mypy.types.deserialize_type(v))\n                for v in data[\"type_vars\"]\n            ],\n        )\n        res.fullname = data[\"fullname\"]\n        return res\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, CLASS_DEF)\n        write_str(data, self.name)\n        mypy.types.write_type_list(data, self.type_vars)\n        write_str(data, self.fullname)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> ClassDef:\n        res = ClassDef(read_str(data), Block([]), mypy.types.read_type_var_likes(data))\n        res.fullname = read_str(data)\n        assert read_tag(data) == END_TAG\n        return res\n\n\nclass GlobalDecl(Statement):\n    \"\"\"Declaration global x, y, ...\"\"\"\n\n    __slots__ = (\"names\",)\n\n    __match_args__ = (\"names\",)\n\n    names: list[str]\n\n    def __init__(self, names: list[str]) -> None:\n        super().__init__()\n        self.names = names\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_global_decl(self)\n\n\nclass NonlocalDecl(Statement):\n    \"\"\"Declaration nonlocal x, y, ...\"\"\"\n\n    __slots__ = (\"names\",)\n\n    __match_args__ = (\"names\",)\n\n    names: list[str]\n\n    def __init__(self, names: list[str]) -> None:\n        super().__init__()\n        self.names = names\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_nonlocal_decl(self)\n\n\nclass Block(Statement):\n    __slots__ = (\"body\", \"is_unreachable\")\n\n    __match_args__ = (\"body\", \"is_unreachable\")\n\n    def __init__(self, body: list[Statement], *, is_unreachable: bool = False) -> None:\n        super().__init__()\n        self.body = body\n        # True if we can determine that this block is not executed during semantic\n        # analysis. For example, this applies to blocks that are protected by\n        # something like \"if PY3:\" when using Python 2. However, some code is\n        # only considered unreachable during type checking and this is not true\n        # in those cases.\n        self.is_unreachable = is_unreachable\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_block(self)\n\n\n# Statements\n\n\nclass ExpressionStmt(Statement):\n    \"\"\"An expression as a statement, such as print(s).\"\"\"\n\n    __slots__ = (\"expr\",)\n\n    __match_args__ = (\"expr\",)\n\n    expr: Expression\n\n    def __init__(self, expr: Expression) -> None:\n        super().__init__()\n        self.expr = expr\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_expression_stmt(self)\n\n\nclass AssignmentStmt(Statement):\n    \"\"\"Assignment statement.\n\n    The same node class is used for single assignment, multiple assignment\n    (e.g. x, y = z) and chained assignment (e.g. x = y = z), assignments\n    that define new names, and assignments with explicit types (\"# type: t\"\n    or \"x: t [= ...]\").\n\n    An lvalue can be NameExpr, TupleExpr, ListExpr, MemberExpr, or IndexExpr.\n    \"\"\"\n\n    __slots__ = (\n        \"lvalues\",\n        \"rvalue\",\n        \"type\",\n        \"unanalyzed_type\",\n        \"new_syntax\",\n        \"is_alias_def\",\n        \"is_final_def\",\n        \"invalid_recursive_alias\",\n    )\n\n    __match_args__ = (\"lvalues\", \"rvalues\", \"type\")\n\n    lvalues: list[Lvalue]\n    # This is a TempNode if and only if no rvalue (x: t).\n    rvalue: Expression\n    # Declared type in a comment, may be None.\n    type: mypy.types.Type | None\n    # Original, not semantically analyzed type in annotation (used for reprocessing)\n    unanalyzed_type: mypy.types.Type | None\n    # This indicates usage of PEP 526 type annotation syntax in assignment.\n    new_syntax: bool\n    # Does this assignment define a type alias?\n    is_alias_def: bool\n    # Is this a final definition?\n    # Final attributes can't be re-assigned once set, and can't be overridden\n    # in a subclass. This flag is not set if an attempted declaration was found to\n    # be invalid during semantic analysis. It is still set to `True` if\n    # a final declaration overrides another final declaration (this is checked\n    # during type checking when MROs are known).\n    is_final_def: bool\n    # Stop further processing of this assignment, to prevent flipping back and forth\n    # during semantic analysis passes.\n    invalid_recursive_alias: bool\n\n    def __init__(\n        self,\n        lvalues: list[Lvalue],\n        rvalue: Expression,\n        type: mypy.types.Type | None = None,\n        new_syntax: bool = False,\n    ) -> None:\n        super().__init__()\n        self.lvalues = lvalues\n        self.rvalue = rvalue\n        self.type = type\n        self.unanalyzed_type = type\n        self.new_syntax = new_syntax\n        self.is_alias_def = False\n        self.is_final_def = False\n        self.invalid_recursive_alias = False\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_assignment_stmt(self)\n\n\nclass OperatorAssignmentStmt(Statement):\n    \"\"\"Operator assignment statement such as x += 1\"\"\"\n\n    __slots__ = (\"op\", \"lvalue\", \"rvalue\")\n\n    __match_args__ = (\"lvalue\", \"op\", \"rvalue\")\n\n    op: str  # TODO: Enum?\n    lvalue: Lvalue\n    rvalue: Expression\n\n    def __init__(self, op: str, lvalue: Lvalue, rvalue: Expression) -> None:\n        super().__init__()\n        self.op = op\n        self.lvalue = lvalue\n        self.rvalue = rvalue\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_operator_assignment_stmt(self)\n\n\nclass WhileStmt(Statement):\n    __slots__ = (\"expr\", \"body\", \"else_body\")\n\n    __match_args__ = (\"expr\", \"body\", \"else_body\")\n\n    expr: Expression\n    body: Block\n    else_body: Block | None\n\n    def __init__(self, expr: Expression, body: Block, else_body: Block | None) -> None:\n        super().__init__()\n        self.expr = expr\n        self.body = body\n        self.else_body = else_body\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_while_stmt(self)\n\n\nclass ForStmt(Statement):\n    __slots__ = (\n        \"index\",\n        \"index_type\",\n        \"unanalyzed_index_type\",\n        \"inferred_item_type\",\n        \"inferred_iterator_type\",\n        \"expr\",\n        \"body\",\n        \"else_body\",\n        \"is_async\",\n    )\n\n    __match_args__ = (\"index\", \"index_type\", \"expr\", \"body\", \"else_body\")\n\n    # Index variables\n    index: Lvalue\n    # Type given by type comments for index, can be None\n    index_type: mypy.types.Type | None\n    # Original, not semantically analyzed type in annotation (used for reprocessing)\n    unanalyzed_index_type: mypy.types.Type | None\n    # Inferred iterable item type\n    inferred_item_type: mypy.types.Type | None\n    # Inferred iterator type\n    inferred_iterator_type: mypy.types.Type | None\n    # Expression to iterate\n    expr: Expression\n    body: Block\n    else_body: Block | None\n    is_async: bool  # True if `async for ...` (PEP 492, Python 3.5)\n\n    def __init__(\n        self,\n        index: Lvalue,\n        expr: Expression,\n        body: Block,\n        else_body: Block | None,\n        index_type: mypy.types.Type | None = None,\n    ) -> None:\n        super().__init__()\n        self.index = index\n        self.index_type = index_type\n        self.unanalyzed_index_type = index_type\n        self.inferred_item_type = None\n        self.inferred_iterator_type = None\n        self.expr = expr\n        self.body = body\n        self.else_body = else_body\n        self.is_async = False\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_for_stmt(self)\n\n\nclass ReturnStmt(Statement):\n    __slots__ = (\"expr\",)\n\n    __match_args__ = (\"expr\",)\n\n    expr: Expression | None\n\n    def __init__(self, expr: Expression | None) -> None:\n        super().__init__()\n        self.expr = expr\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_return_stmt(self)\n\n\nclass AssertStmt(Statement):\n    __slots__ = (\"expr\", \"msg\")\n\n    __match_args__ = (\"expr\", \"msg\")\n\n    expr: Expression\n    msg: Expression | None\n\n    def __init__(self, expr: Expression, msg: Expression | None = None) -> None:\n        super().__init__()\n        self.expr = expr\n        self.msg = msg\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_assert_stmt(self)\n\n\nclass DelStmt(Statement):\n    __slots__ = (\"expr\",)\n\n    __match_args__ = (\"expr\",)\n\n    expr: Lvalue\n\n    def __init__(self, expr: Lvalue) -> None:\n        super().__init__()\n        self.expr = expr\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_del_stmt(self)\n\n\nclass BreakStmt(Statement):\n    __slots__ = ()\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_break_stmt(self)\n\n\nclass ContinueStmt(Statement):\n    __slots__ = ()\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_continue_stmt(self)\n\n\nclass PassStmt(Statement):\n    __slots__ = ()\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_pass_stmt(self)\n\n\nclass IfStmt(Statement):\n    __slots__ = (\"expr\", \"body\", \"else_body\", \"unreachable_else\")\n\n    __match_args__ = (\"expr\", \"body\", \"else_body\", \"unreachable_else\")\n\n    expr: list[Expression]\n    body: list[Block]\n    else_body: Block | None\n    # (If there is actually no else statement, semantic analysis may nevertheless create an\n    # empty else block and mark it permanently as unreachable to tell that the control flow\n    # must always go through the if block.)\n    unreachable_else: bool\n    # (Type checking may modify this flag repeatedly to indicate whether an actually available\n    # or unavailable else block is unreachable, considering the current type information.)\n\n    def __init__(self, expr: list[Expression], body: list[Block], else_body: Block | None) -> None:\n        super().__init__()\n        self.expr = expr\n        self.body = body\n        self.else_body = else_body\n        self.unreachable_else = False\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_if_stmt(self)\n\n\nclass RaiseStmt(Statement):\n    __slots__ = (\"expr\", \"from_expr\")\n\n    __match_args__ = (\"expr\", \"from_expr\")\n\n    # Plain 'raise' is a valid statement.\n    expr: Expression | None\n    from_expr: Expression | None\n\n    def __init__(self, expr: Expression | None, from_expr: Expression | None) -> None:\n        super().__init__()\n        self.expr = expr\n        self.from_expr = from_expr\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_raise_stmt(self)\n\n\nclass TryStmt(Statement):\n    __slots__ = (\"body\", \"types\", \"vars\", \"handlers\", \"else_body\", \"finally_body\", \"is_star\")\n\n    __match_args__ = (\"body\", \"types\", \"vars\", \"handlers\", \"else_body\", \"finally_body\", \"is_star\")\n\n    body: Block  # Try body\n    # Plain 'except:' also possible\n    types: list[Expression | None]  # Except type expressions\n    vars: list[NameExpr | None]  # Except variable names\n    handlers: list[Block]  # Except bodies\n    else_body: Block | None\n    finally_body: Block | None\n    # Whether this is try ... except* (added in Python 3.11)\n    is_star: bool\n\n    def __init__(\n        self,\n        body: Block,\n        vars: list[NameExpr | None],\n        types: list[Expression | None],\n        handlers: list[Block],\n        else_body: Block | None,\n        finally_body: Block | None,\n    ) -> None:\n        super().__init__()\n        self.body = body\n        self.vars = vars\n        self.types = types\n        self.handlers = handlers\n        self.else_body = else_body\n        self.finally_body = finally_body\n        self.is_star = False\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_try_stmt(self)\n\n\nclass WithStmt(Statement):\n    __slots__ = (\"expr\", \"target\", \"unanalyzed_type\", \"analyzed_types\", \"body\", \"is_async\")\n\n    __match_args__ = (\"expr\", \"target\", \"body\")\n\n    expr: list[Expression]\n    target: list[Lvalue | None]\n    # Type given by type comments for target, can be None\n    unanalyzed_type: mypy.types.Type | None\n    # Semantically analyzed types from type comment (TypeList type expanded)\n    analyzed_types: list[mypy.types.Type]\n    body: Block\n    is_async: bool  # True if `async with ...` (PEP 492, Python 3.5)\n\n    def __init__(\n        self,\n        expr: list[Expression],\n        target: list[Lvalue | None],\n        body: Block,\n        target_type: mypy.types.Type | None = None,\n    ) -> None:\n        super().__init__()\n        self.expr = expr\n        self.target = target\n        self.unanalyzed_type = target_type\n        self.analyzed_types = []\n        self.body = body\n        self.is_async = False\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_with_stmt(self)\n\n\nclass MatchStmt(Statement):\n    __slots__ = (\"subject\", \"subject_dummy\", \"patterns\", \"guards\", \"bodies\")\n\n    __match_args__ = (\"subject\", \"patterns\", \"guards\", \"bodies\")\n\n    subject: Expression\n    subject_dummy: NameExpr | None\n    patterns: list[Pattern]\n    guards: list[Expression | None]\n    bodies: list[Block]\n\n    def __init__(\n        self,\n        subject: Expression,\n        patterns: list[Pattern],\n        guards: list[Expression | None],\n        bodies: list[Block],\n    ) -> None:\n        super().__init__()\n        assert len(patterns) == len(guards) == len(bodies)\n        self.subject = subject\n        self.subject_dummy = None\n        self.patterns = patterns\n        self.guards = guards\n        self.bodies = bodies\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_match_stmt(self)\n\n\nclass TypeAliasStmt(Statement):\n    __slots__ = (\"name\", \"type_args\", \"value\", \"invalid_recursive_alias\", \"alias_node\")\n\n    __match_args__ = (\"name\", \"type_args\", \"value\")\n\n    name: NameExpr\n    type_args: list[TypeParam]\n    value: LambdaExpr  # Return value will get translated into a type\n    invalid_recursive_alias: bool\n    alias_node: TypeAlias | None\n\n    def __init__(self, name: NameExpr, type_args: list[TypeParam], value: LambdaExpr) -> None:\n        super().__init__()\n        self.name = name\n        self.type_args = type_args\n        self.value = value\n        self.invalid_recursive_alias = False\n        self.alias_node = None\n\n    def accept(self, visitor: StatementVisitor[T]) -> T:\n        return visitor.visit_type_alias_stmt(self)\n\n\n# Expressions\n\n\nclass IntExpr(Expression):\n    \"\"\"Integer literal\"\"\"\n\n    __slots__ = (\"value\",)\n\n    __match_args__ = (\"value\",)\n\n    value: int  # 0 by default\n\n    def __init__(self, value: int) -> None:\n        super().__init__()\n        self.value = value\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_int_expr(self)\n\n\n# How mypy uses StrExpr and BytesExpr:\n#\n# b'x' -> BytesExpr\n# 'x', u'x' -> StrExpr\n\n\nclass StrExpr(Expression):\n    \"\"\"String literal\"\"\"\n\n    __slots__ = (\"value\", \"as_type\")\n\n    __match_args__ = (\"value\",)\n\n    value: str  # '' by default\n    # If this value expression can also be parsed as a valid type expression,\n    # represents the type denoted by the type expression.\n    # None means \"is not a type expression\".\n    as_type: NotParsed | mypy.types.Type | None\n\n    def __init__(self, value: str) -> None:\n        super().__init__()\n        self.value = value\n        self.as_type = NotParsed.VALUE\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_str_expr(self)\n\n\ndef is_StrExpr_list(seq: list[Expression]) -> TypeGuard[list[StrExpr]]:  # noqa: N802\n    return all(isinstance(item, StrExpr) for item in seq)\n\n\nclass BytesExpr(Expression):\n    \"\"\"Bytes literal\"\"\"\n\n    __slots__ = (\"value\",)\n\n    __match_args__ = (\"value\",)\n\n    # Note: we deliberately do NOT use bytes here because it ends up\n    # unnecessarily complicating a lot of the result logic. For example,\n    # we'd have to worry about converting the bytes into a format we can\n    # easily serialize/deserialize to and from JSON, would have to worry\n    # about turning the bytes into a human-readable representation in\n    # error messages...\n    #\n    # It's more convenient to just store the human-readable representation\n    # from the very start.\n    value: str\n\n    def __init__(self, value: str) -> None:\n        super().__init__()\n        self.value = value\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_bytes_expr(self)\n\n\nclass FloatExpr(Expression):\n    \"\"\"Float literal\"\"\"\n\n    __slots__ = (\"value\",)\n\n    __match_args__ = (\"value\",)\n\n    value: float  # 0.0 by default\n\n    def __init__(self, value: float) -> None:\n        super().__init__()\n        self.value = value\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_float_expr(self)\n\n\nclass ComplexExpr(Expression):\n    \"\"\"Complex literal\"\"\"\n\n    __slots__ = (\"value\",)\n\n    __match_args__ = (\"value\",)\n\n    value: complex\n\n    def __init__(self, value: complex) -> None:\n        super().__init__()\n        self.value = value\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_complex_expr(self)\n\n\nclass EllipsisExpr(Expression):\n    \"\"\"Ellipsis (...)\"\"\"\n\n    __slots__ = ()\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_ellipsis(self)\n\n\nclass StarExpr(Expression):\n    \"\"\"Star expression\"\"\"\n\n    __slots__ = (\"expr\", \"valid\")\n\n    __match_args__ = (\"expr\", \"valid\")\n\n    expr: Expression\n    valid: bool\n\n    def __init__(self, expr: Expression) -> None:\n        super().__init__()\n        self.expr = expr\n\n        # Whether this starred expression is used in a tuple/list and as lvalue\n        self.valid = False\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_star_expr(self)\n\n\nclass RefExpr(Expression):\n    \"\"\"Abstract base class for name-like constructs\"\"\"\n\n    __slots__ = (\n        \"kind\",\n        \"node\",\n        \"_fullname\",\n        \"is_new_def\",\n        \"is_inferred_def\",\n        \"is_alias_rvalue\",\n        \"type_guard\",\n        \"type_is\",\n    )\n\n    def __init__(self) -> None:\n        super().__init__()\n        # LDEF/GDEF/MDEF/... (None if not available)\n        self.kind: int | None = None\n        # Var, FuncDef or TypeInfo that describes this\n        self.node: SymbolNode | None = None\n        # Fully qualified name (or name if not global)\n        self._fullname = \"\"\n        # Does this define a new name?\n        self.is_new_def = False\n        # Does this define a new name with inferred type?\n        #\n        # For members, after semantic analysis, this does not take base\n        # classes into consideration at all; the type checker deals with these.\n        self.is_inferred_def = False\n        # Is this expression appears as an rvalue of a valid type alias definition?\n        self.is_alias_rvalue = False\n        # Cache type guard from callable_type.type_guard\n        self.type_guard: mypy.types.Type | None = None\n        # And same for TypeIs\n        self.type_is: mypy.types.Type | None = None\n\n    @property\n    def fullname(self) -> str:\n        return self._fullname\n\n    @fullname.setter\n    def fullname(self, v: str) -> None:\n        self._fullname = v\n\n\nclass NameExpr(RefExpr):\n    \"\"\"Name expression\n\n    This refers to a local name, global name or a module.\n    \"\"\"\n\n    __slots__ = (\"name\", \"is_special_form\")\n\n    __match_args__ = (\"name\", \"node\")\n\n    def __init__(self, name: str) -> None:\n        super().__init__()\n        self.name = name  # Name referred to\n        # Is this a l.h.s. of a special form assignment like typed dict or type variable?\n        self.is_special_form = False\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_name_expr(self)\n\n    def serialize(self) -> JsonDict:\n        assert False, f\"Serializing NameExpr: {self}\"\n\n\nclass MemberExpr(RefExpr):\n    \"\"\"Member access expression x.y\"\"\"\n\n    __slots__ = (\"expr\", \"name\", \"def_var\")\n\n    __match_args__ = (\"expr\", \"name\", \"node\")\n\n    def __init__(self, expr: Expression, name: str) -> None:\n        super().__init__()\n        self.expr = expr\n        self.name = name\n        # The variable node related to a definition through 'self.x = <initializer>'.\n        # The nodes of other kinds of member expressions are resolved during type checking.\n        self.def_var: Var | None = None\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_member_expr(self)\n\n\n# Kinds of arguments\n@unique\nclass ArgKind(Enum):\n    # Positional argument\n    ARG_POS = 0\n    # Positional, optional argument (functions only, not calls)\n    ARG_OPT = 1\n    # *arg argument\n    ARG_STAR = 2\n    # Keyword argument x=y in call, or keyword-only function arg\n    ARG_NAMED = 3\n    # **arg argument\n    ARG_STAR2 = 4\n    # In an argument list, keyword-only and also optional\n    ARG_NAMED_OPT = 5\n\n    def is_positional(self, star: bool = False) -> bool:\n        return self == ARG_POS or self == ARG_OPT or (star and self == ARG_STAR)\n\n    def is_named(self, star: bool = False) -> bool:\n        return self == ARG_NAMED or self == ARG_NAMED_OPT or (star and self == ARG_STAR2)\n\n    def is_required(self) -> bool:\n        return self == ARG_POS or self == ARG_NAMED\n\n    def is_optional(self) -> bool:\n        return self == ARG_OPT or self == ARG_NAMED_OPT\n\n    def is_star(self) -> bool:\n        return self == ARG_STAR or self == ARG_STAR2\n\n\nARG_POS: Final = ArgKind.ARG_POS\nARG_OPT: Final = ArgKind.ARG_OPT\nARG_STAR: Final = ArgKind.ARG_STAR\nARG_NAMED: Final = ArgKind.ARG_NAMED\nARG_STAR2: Final = ArgKind.ARG_STAR2\nARG_NAMED_OPT: Final = ArgKind.ARG_NAMED_OPT\n\nARG_KINDS: Final = (ARG_POS, ARG_OPT, ARG_STAR, ARG_NAMED, ARG_STAR2, ARG_NAMED_OPT)\n\n\nclass CallExpr(Expression):\n    \"\"\"Call expression.\n\n    This can also represent several special forms that are syntactically calls\n    such as cast(...) and None  # type: ....\n    \"\"\"\n\n    __slots__ = (\"callee\", \"args\", \"arg_kinds\", \"arg_names\", \"analyzed\")\n\n    __match_args__ = (\"callee\", \"args\", \"arg_kinds\", \"arg_names\")\n\n    def __init__(\n        self,\n        callee: Expression,\n        args: list[Expression],\n        arg_kinds: list[ArgKind],\n        arg_names: list[str | None],\n        analyzed: Expression | None = None,\n    ) -> None:\n        super().__init__()\n        if not arg_names:\n            arg_names = [None] * len(args)\n\n        self.callee = callee\n        self.args = args\n        self.arg_kinds = arg_kinds  # ARG_ constants\n        # Each name can be None if not a keyword argument.\n        self.arg_names: list[str | None] = arg_names\n        # If not None, the node that represents the meaning of the CallExpr. For\n        # cast(...) this is a CastExpr.\n        self.analyzed = analyzed\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_call_expr(self)\n\n\nclass YieldFromExpr(Expression):\n    __slots__ = (\"expr\",)\n\n    __match_args__ = (\"expr\",)\n\n    expr: Expression\n\n    def __init__(self, expr: Expression) -> None:\n        super().__init__()\n        self.expr = expr\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_yield_from_expr(self)\n\n\nclass YieldExpr(Expression):\n    __slots__ = (\"expr\",)\n\n    __match_args__ = (\"expr\",)\n\n    expr: Expression | None\n\n    def __init__(self, expr: Expression | None) -> None:\n        super().__init__()\n        self.expr = expr\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_yield_expr(self)\n\n\nclass IndexExpr(Expression):\n    \"\"\"Index expression x[y].\n\n    Also wraps type application such as List[int] as a special form.\n    \"\"\"\n\n    __slots__ = (\"base\", \"index\", \"method_type\", \"analyzed\", \"as_type\")\n\n    __match_args__ = (\"base\", \"index\")\n\n    base: Expression\n    index: Expression\n    # Inferred __getitem__ method type\n    method_type: mypy.types.Type | None\n    # If not None, this is actually semantically a type application\n    # Class[type, ...] or a type alias initializer.\n    analyzed: TypeApplication | TypeAliasExpr | None\n    # If this value expression can also be parsed as a valid type expression,\n    # represents the type denoted by the type expression.\n    # None means \"is not a type expression\".\n    as_type: NotParsed | mypy.types.Type | None\n\n    def __init__(self, base: Expression, index: Expression) -> None:\n        super().__init__()\n        self.base = base\n        self.index = index\n        self.method_type = None\n        self.analyzed = None\n        self.as_type = NotParsed.VALUE\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_index_expr(self)\n\n\nclass UnaryExpr(Expression):\n    \"\"\"Unary operation\"\"\"\n\n    __slots__ = (\"op\", \"expr\", \"method_type\")\n\n    __match_args__ = (\"op\", \"expr\")\n\n    op: str  # TODO: Enum?\n    expr: Expression\n    # Inferred operator method type\n    method_type: mypy.types.Type | None\n\n    def __init__(self, op: str, expr: Expression) -> None:\n        super().__init__()\n        self.op = op\n        self.expr = expr\n        self.method_type = None\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_unary_expr(self)\n\n\nclass AssignmentExpr(Expression):\n    \"\"\"Assignment expressions in Python 3.8+, like \"a := 2\".\"\"\"\n\n    __slots__ = (\"target\", \"value\")\n\n    __match_args__ = (\"target\", \"value\")\n\n    def __init__(self, target: NameExpr, value: Expression) -> None:\n        super().__init__()\n        self.target = target\n        self.value = value\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_assignment_expr(self)\n\n\nclass OpExpr(Expression):\n    \"\"\"Binary operation.\n\n    The dot (.), [] and comparison operators have more specific nodes.\n    \"\"\"\n\n    __slots__ = (\n        \"op\",\n        \"left\",\n        \"right\",\n        \"method_type\",\n        \"right_always\",\n        \"right_unreachable\",\n        \"analyzed\",\n        \"as_type\",\n    )\n\n    __match_args__ = (\"left\", \"op\", \"right\")\n\n    op: str  # TODO: Enum?\n    left: Expression\n    right: Expression\n    # Inferred type for the operator method type (when relevant).\n    method_type: mypy.types.Type | None\n    # Per static analysis only: Is the right side going to be evaluated every time?\n    right_always: bool\n    # Per static analysis only: Is the right side unreachable?\n    right_unreachable: bool\n    # Used for expressions that represent a type \"X | Y\" in some contexts\n    analyzed: TypeAliasExpr | None\n    # If this value expression can also be parsed as a valid type expression,\n    # represents the type denoted by the type expression.\n    # None means \"is not a type expression\".\n    as_type: NotParsed | mypy.types.Type | None\n\n    def __init__(\n        self, op: str, left: Expression, right: Expression, analyzed: TypeAliasExpr | None = None\n    ) -> None:\n        super().__init__()\n        self.op = op\n        self.left = left\n        self.right = right\n        self.method_type = None\n        self.right_always = False\n        self.right_unreachable = False\n        self.analyzed = analyzed\n        self.as_type = NotParsed.VALUE\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_op_expr(self)\n\n\n# Expression subtypes that could represent the root of a valid type expression.\n#\n# May have an \"as_type\" attribute to hold the type for a type expression parsed\n# during the SemanticAnalyzer pass.\nMaybeTypeExpression = (IndexExpr, MemberExpr, NameExpr, OpExpr, StrExpr)\n\n\nclass ComparisonExpr(Expression):\n    \"\"\"Comparison expression (e.g. a < b > c < d).\"\"\"\n\n    __slots__ = (\"operators\", \"operands\", \"method_types\")\n\n    __match_args__ = (\"operands\", \"operators\")\n\n    operators: list[str]\n    operands: list[Expression]\n    # Inferred type for the operator methods (when relevant; None for 'is').\n    method_types: list[mypy.types.Type | None]\n\n    def __init__(self, operators: list[str], operands: list[Expression]) -> None:\n        super().__init__()\n        self.operators = operators\n        self.operands = operands\n        self.method_types = []\n\n    def pairwise(self) -> Iterator[tuple[str, Expression, Expression]]:\n        \"\"\"If this comparison expr is \"a < b is c == d\", yields the sequence\n        (\"<\", a, b), (\"is\", b, c), (\"==\", c, d)\n        \"\"\"\n        for i, operator in enumerate(self.operators):\n            yield operator, self.operands[i], self.operands[i + 1]\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_comparison_expr(self)\n\n\nclass SliceExpr(Expression):\n    \"\"\"Slice expression (e.g. 'x:y', 'x:', '::2' or ':').\n\n    This is only valid as index in index expressions.\n    \"\"\"\n\n    __slots__ = (\"begin_index\", \"end_index\", \"stride\")\n\n    __match_args__ = (\"begin_index\", \"end_index\", \"stride\")\n\n    begin_index: Expression | None\n    end_index: Expression | None\n    stride: Expression | None\n\n    def __init__(\n        self,\n        begin_index: Expression | None,\n        end_index: Expression | None,\n        stride: Expression | None,\n    ) -> None:\n        super().__init__()\n        self.begin_index = begin_index\n        self.end_index = end_index\n        self.stride = stride\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_slice_expr(self)\n\n\nclass CastExpr(Expression):\n    \"\"\"Cast expression cast(type, expr).\"\"\"\n\n    __slots__ = (\"expr\", \"type\")\n\n    __match_args__ = (\"expr\", \"type\")\n\n    expr: Expression\n    type: mypy.types.Type\n\n    def __init__(self, expr: Expression, typ: mypy.types.Type) -> None:\n        super().__init__()\n        self.expr = expr\n        self.type = typ\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_cast_expr(self)\n\n\nclass TypeFormExpr(Expression):\n    \"\"\"TypeForm(type) expression.\"\"\"\n\n    __slots__ = (\"type\",)\n\n    __match_args__ = (\"type\",)\n\n    type: mypy.types.Type\n\n    def __init__(self, typ: mypy.types.Type) -> None:\n        super().__init__()\n        self.type = typ\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_type_form_expr(self)\n\n\nclass AssertTypeExpr(Expression):\n    \"\"\"Represents a typing.assert_type(expr, type) call.\"\"\"\n\n    __slots__ = (\"expr\", \"type\")\n\n    __match_args__ = (\"expr\", \"type\")\n\n    expr: Expression\n    type: mypy.types.Type\n\n    def __init__(self, expr: Expression, typ: mypy.types.Type) -> None:\n        super().__init__()\n        self.expr = expr\n        self.type = typ\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_assert_type_expr(self)\n\n\nclass RevealExpr(Expression):\n    \"\"\"Reveal type expression reveal_type(expr) or reveal_locals() expression.\"\"\"\n\n    __slots__ = (\"expr\", \"kind\", \"local_nodes\", \"is_imported\")\n\n    __match_args__ = (\"expr\", \"kind\", \"local_nodes\", \"is_imported\")\n\n    expr: Expression | None\n    kind: int\n    local_nodes: list[Var] | None\n\n    def __init__(\n        self,\n        kind: int,\n        expr: Expression | None = None,\n        local_nodes: list[Var] | None = None,\n        is_imported: bool = False,\n    ) -> None:\n        super().__init__()\n        self.expr = expr\n        self.kind = kind\n        self.local_nodes = local_nodes\n        self.is_imported = is_imported\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_reveal_expr(self)\n\n\nclass SuperExpr(Expression):\n    \"\"\"Expression super().name\"\"\"\n\n    __slots__ = (\"name\", \"info\", \"call\")\n\n    __match_args__ = (\"name\", \"call\", \"info\")\n\n    name: str\n    info: TypeInfo | None  # Type that contains this super expression\n    call: CallExpr  # The expression super(...)\n\n    def __init__(self, name: str, call: CallExpr) -> None:\n        super().__init__()\n        self.name = name\n        self.call = call\n        self.info = None\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_super_expr(self)\n\n\nclass LambdaExpr(FuncItem, Expression):\n    \"\"\"Lambda expression\"\"\"\n\n    __match_args__ = (\"arguments\", \"arg_names\", \"arg_kinds\", \"body\")\n\n    @property\n    def name(self) -> str:\n        return LAMBDA_NAME\n\n    def expr(self) -> Expression:\n        \"\"\"Return the expression (the body) of the lambda.\"\"\"\n        ret = self.body.body[-1]\n        assert isinstance(ret, ReturnStmt)\n        expr = ret.expr\n        assert expr is not None  # lambda can't have empty body\n        return expr\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_lambda_expr(self)\n\n    def is_dynamic(self) -> bool:\n        return False\n\n\nclass ListExpr(Expression):\n    \"\"\"List literal expression [...].\"\"\"\n\n    __slots__ = (\"items\",)\n\n    __match_args__ = (\"items\",)\n\n    items: list[Expression]\n\n    def __init__(self, items: list[Expression]) -> None:\n        super().__init__()\n        self.items = items\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_list_expr(self)\n\n\nclass DictExpr(Expression):\n    \"\"\"Dictionary literal expression {key: value, ...}.\"\"\"\n\n    __slots__ = (\"items\",)\n\n    __match_args__ = (\"items\",)\n\n    items: list[tuple[Expression | None, Expression]]\n\n    def __init__(self, items: list[tuple[Expression | None, Expression]]) -> None:\n        super().__init__()\n        self.items = items\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_dict_expr(self)\n\n\nclass TemplateStrExpr(Expression):\n    \"\"\"Template string expression t'...'.\"\"\"\n\n    __slots__ = (\"items\",)\n    __match_args__ = (\"items\",)\n\n    # Each item is either:\n    #   - a StrExpr (literal string segment), or\n    #   - a tuple (value_expr, source_text, conversion, format_spec_expr)\n    #     where conversion is str | None (\"r\", \"s\", \"a\", or None)\n    #     and format_spec_expr is Expression | None\n    items: list[Expression | tuple[Expression, str, str | None, Expression | None]]\n\n    def __init__(\n        self, items: list[Expression | tuple[Expression, str, str | None, Expression | None]]\n    ) -> None:\n        super().__init__()\n        self.items = items\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_template_str_expr(self)\n\n\nclass TupleExpr(Expression):\n    \"\"\"Tuple literal expression (..., ...)\n\n    Also lvalue sequences (..., ...) and [..., ...]\"\"\"\n\n    __slots__ = (\"items\",)\n\n    __match_args__ = (\"items\",)\n\n    items: list[Expression]\n\n    def __init__(self, items: list[Expression]) -> None:\n        super().__init__()\n        self.items = items\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_tuple_expr(self)\n\n\nclass SetExpr(Expression):\n    \"\"\"Set literal expression {value, ...}.\"\"\"\n\n    __slots__ = (\"items\",)\n\n    __match_args__ = (\"items\",)\n\n    items: list[Expression]\n\n    def __init__(self, items: list[Expression]) -> None:\n        super().__init__()\n        self.items = items\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_set_expr(self)\n\n\nclass GeneratorExpr(Expression):\n    \"\"\"Generator expression ... for ... in ... [ for ...  in ... ] [ if ... ].\"\"\"\n\n    __slots__ = (\"left_expr\", \"sequences\", \"condlists\", \"is_async\", \"indices\")\n\n    __match_args__ = (\"left_expr\", \"indices\", \"sequences\", \"condlists\")\n\n    left_expr: Expression\n    sequences: list[Expression]\n    condlists: list[list[Expression]]\n    is_async: list[bool]\n    indices: list[Lvalue]\n\n    def __init__(\n        self,\n        left_expr: Expression,\n        indices: list[Lvalue],\n        sequences: list[Expression],\n        condlists: list[list[Expression]],\n        is_async: list[bool],\n    ) -> None:\n        super().__init__()\n        self.left_expr = left_expr\n        self.sequences = sequences\n        self.condlists = condlists\n        self.indices = indices\n        self.is_async = is_async\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_generator_expr(self)\n\n\nclass ListComprehension(Expression):\n    \"\"\"List comprehension (e.g. [x + 1 for x in a])\"\"\"\n\n    __slots__ = (\"generator\",)\n\n    __match_args__ = (\"generator\",)\n\n    generator: GeneratorExpr\n\n    def __init__(self, generator: GeneratorExpr) -> None:\n        super().__init__()\n        self.generator = generator\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_list_comprehension(self)\n\n\nclass SetComprehension(Expression):\n    \"\"\"Set comprehension (e.g. {x + 1 for x in a})\"\"\"\n\n    __slots__ = (\"generator\",)\n\n    __match_args__ = (\"generator\",)\n\n    generator: GeneratorExpr\n\n    def __init__(self, generator: GeneratorExpr) -> None:\n        super().__init__()\n        self.generator = generator\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_set_comprehension(self)\n\n\nclass DictionaryComprehension(Expression):\n    \"\"\"Dictionary comprehension (e.g. {k: v for k, v in a}\"\"\"\n\n    __slots__ = (\"key\", \"value\", \"sequences\", \"condlists\", \"is_async\", \"indices\")\n\n    __match_args__ = (\"key\", \"value\", \"indices\", \"sequences\", \"condlists\")\n\n    key: Expression\n    value: Expression\n    sequences: list[Expression]\n    condlists: list[list[Expression]]\n    is_async: list[bool]\n    indices: list[Lvalue]\n\n    def __init__(\n        self,\n        key: Expression,\n        value: Expression,\n        indices: list[Lvalue],\n        sequences: list[Expression],\n        condlists: list[list[Expression]],\n        is_async: list[bool],\n    ) -> None:\n        super().__init__()\n        self.key = key\n        self.value = value\n        self.sequences = sequences\n        self.condlists = condlists\n        self.indices = indices\n        self.is_async = is_async\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_dictionary_comprehension(self)\n\n\nclass ConditionalExpr(Expression):\n    \"\"\"Conditional expression (e.g. x if y else z)\"\"\"\n\n    __slots__ = (\"cond\", \"if_expr\", \"else_expr\")\n\n    __match_args__ = (\"if_expr\", \"cond\", \"else_expr\")\n\n    cond: Expression\n    if_expr: Expression\n    else_expr: Expression\n\n    def __init__(self, cond: Expression, if_expr: Expression, else_expr: Expression) -> None:\n        super().__init__()\n        self.cond = cond\n        self.if_expr = if_expr\n        self.else_expr = else_expr\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_conditional_expr(self)\n\n\nclass TypeApplication(Expression):\n    \"\"\"Type application expr[type, ...]\"\"\"\n\n    __slots__ = (\"expr\", \"types\")\n\n    __match_args__ = (\"expr\", \"types\")\n\n    expr: Expression\n    types: list[mypy.types.Type]\n\n    def __init__(self, expr: Expression, types: list[mypy.types.Type]) -> None:\n        super().__init__()\n        self.expr = expr\n        self.types = types\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_type_application(self)\n\n\n# Variance of a type variable. For example, T in the definition of\n# List[T] is invariant, so List[int] is not a subtype of List[object],\n# and also List[object] is not a subtype of List[int].\n#\n# The T in Iterable[T] is covariant, so Iterable[int] is a subtype of\n# Iterable[object], but not vice versa.\n#\n# If T is contravariant in Foo[T], Foo[object] is a subtype of\n# Foo[int], but not vice versa.\nINVARIANT: Final = 0\nCOVARIANT: Final = 1\nCONTRAVARIANT: Final = 2\nVARIANCE_NOT_READY: Final = 3  # Variance hasn't been inferred (using Python 3.12 syntax)\n\n\nclass TypeVarLikeExpr(SymbolNode, Expression):\n    \"\"\"Base class for TypeVarExpr, ParamSpecExpr and TypeVarTupleExpr.\n\n    Note that they are constructed by the semantic analyzer.\n    \"\"\"\n\n    __slots__ = (\"_name\", \"_fullname\", \"upper_bound\", \"default\", \"variance\", \"is_new_style\")\n\n    _name: str\n    _fullname: str\n    # Upper bound: only subtypes of upper_bound are valid as values. By default\n    # this is 'object', meaning no restriction.\n    upper_bound: mypy.types.Type\n    # Default: used to resolve the TypeVar if the default is not explicitly given.\n    # By default this is 'AnyType(TypeOfAny.from_omitted_generics)'. See PEP 696.\n    default: mypy.types.Type\n    # Variance of the type variable. Invariant is the default.\n    # TypeVar(..., covariant=True) defines a covariant type variable.\n    # TypeVar(..., contravariant=True) defines a contravariant type\n    # variable.\n    variance: int\n\n    def __init__(\n        self,\n        name: str,\n        fullname: str,\n        upper_bound: mypy.types.Type,\n        default: mypy.types.Type,\n        variance: int = INVARIANT,\n        is_new_style: bool = False,\n        line: int = -1,\n    ) -> None:\n        super().__init__(line=line)\n        self._name = name\n        self._fullname = fullname\n        self.upper_bound = upper_bound\n        self.default = default\n        self.variance = variance\n        self.is_new_style = is_new_style\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n    @property\n    def fullname(self) -> str:\n        return self._fullname\n\n\n# All types that are both SymbolNodes and Expressions.\n# Use when common children of them are needed.\nSYMBOL_NODE_EXPRESSION_TYPES: Final = (TypeVarLikeExpr,)\n\n\nclass TypeVarExpr(TypeVarLikeExpr):\n    \"\"\"Type variable expression TypeVar(...).\n\n    This is also used to represent type variables in symbol tables.\n\n    A type variable is not valid as a type unless bound in a TypeVarLikeScope.\n    That happens within:\n\n     1. a generic class that uses the type variable as a type argument or\n     2. a generic function that refers to the type variable in its signature.\n    \"\"\"\n\n    __slots__ = (\"values\",)\n\n    __match_args__ = (\"name\", \"values\", \"upper_bound\", \"default\")\n\n    # Value restriction: only types in the list are valid as values. If the\n    # list is empty, there is no restriction.\n    values: list[mypy.types.Type]\n\n    def __init__(\n        self,\n        name: str,\n        fullname: str,\n        values: list[mypy.types.Type],\n        upper_bound: mypy.types.Type,\n        default: mypy.types.Type,\n        variance: int = INVARIANT,\n        is_new_style: bool = False,\n        line: int = -1,\n    ) -> None:\n        super().__init__(name, fullname, upper_bound, default, variance, is_new_style, line=line)\n        self.values = values\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_type_var_expr(self)\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"TypeVarExpr\",\n            \"name\": self._name,\n            \"fullname\": self._fullname,\n            \"values\": [t.serialize() for t in self.values],\n            \"upper_bound\": self.upper_bound.serialize(),\n            \"default\": self.default.serialize(),\n            \"variance\": self.variance,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypeVarExpr:\n        assert data[\".class\"] == \"TypeVarExpr\"\n        return TypeVarExpr(\n            data[\"name\"],\n            data[\"fullname\"],\n            [mypy.types.deserialize_type(v) for v in data[\"values\"]],\n            mypy.types.deserialize_type(data[\"upper_bound\"]),\n            mypy.types.deserialize_type(data[\"default\"]),\n            data[\"variance\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, TYPE_VAR_EXPR)\n        write_str(data, self._name)\n        write_str(data, self._fullname)\n        mypy.types.write_type_list(data, self.values)\n        self.upper_bound.write(data)\n        self.default.write(data)\n        write_int(data, self.variance)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> TypeVarExpr:\n        ret = TypeVarExpr(\n            read_str(data),\n            read_str(data),\n            mypy.types.read_type_list(data),\n            mypy.types.read_type(data),\n            mypy.types.read_type(data),\n            read_int(data),\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass ParamSpecExpr(TypeVarLikeExpr):\n    __slots__ = ()\n\n    __match_args__ = (\"name\", \"upper_bound\", \"default\")\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_paramspec_expr(self)\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"ParamSpecExpr\",\n            \"name\": self._name,\n            \"fullname\": self._fullname,\n            \"upper_bound\": self.upper_bound.serialize(),\n            \"default\": self.default.serialize(),\n            \"variance\": self.variance,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> ParamSpecExpr:\n        assert data[\".class\"] == \"ParamSpecExpr\"\n        return ParamSpecExpr(\n            data[\"name\"],\n            data[\"fullname\"],\n            mypy.types.deserialize_type(data[\"upper_bound\"]),\n            mypy.types.deserialize_type(data[\"default\"]),\n            data[\"variance\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, PARAM_SPEC_EXPR)\n        write_str(data, self._name)\n        write_str(data, self._fullname)\n        self.upper_bound.write(data)\n        self.default.write(data)\n        write_int(data, self.variance)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> ParamSpecExpr:\n        ret = ParamSpecExpr(\n            read_str(data),\n            read_str(data),\n            mypy.types.read_type(data),\n            mypy.types.read_type(data),\n            read_int(data),\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass TypeVarTupleExpr(TypeVarLikeExpr):\n    \"\"\"Type variable tuple expression TypeVarTuple(...).\"\"\"\n\n    __slots__ = \"tuple_fallback\"\n\n    tuple_fallback: mypy.types.Instance\n\n    __match_args__ = (\"name\", \"upper_bound\", \"default\")\n\n    def __init__(\n        self,\n        name: str,\n        fullname: str,\n        upper_bound: mypy.types.Type,\n        tuple_fallback: mypy.types.Instance,\n        default: mypy.types.Type,\n        variance: int = INVARIANT,\n        is_new_style: bool = False,\n        line: int = -1,\n    ) -> None:\n        super().__init__(name, fullname, upper_bound, default, variance, is_new_style, line=line)\n        self.tuple_fallback = tuple_fallback\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_type_var_tuple_expr(self)\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"TypeVarTupleExpr\",\n            \"name\": self._name,\n            \"fullname\": self._fullname,\n            \"upper_bound\": self.upper_bound.serialize(),\n            \"tuple_fallback\": self.tuple_fallback.serialize(),\n            \"default\": self.default.serialize(),\n            \"variance\": self.variance,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypeVarTupleExpr:\n        assert data[\".class\"] == \"TypeVarTupleExpr\"\n        return TypeVarTupleExpr(\n            data[\"name\"],\n            data[\"fullname\"],\n            mypy.types.deserialize_type(data[\"upper_bound\"]),\n            mypy.types.Instance.deserialize(data[\"tuple_fallback\"]),\n            mypy.types.deserialize_type(data[\"default\"]),\n            data[\"variance\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, TYPE_VAR_TUPLE_EXPR)\n        self.tuple_fallback.write(data)\n        write_str(data, self._name)\n        write_str(data, self._fullname)\n        self.upper_bound.write(data)\n        self.default.write(data)\n        write_int(data, self.variance)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> TypeVarTupleExpr:\n        assert read_tag(data) == mypy.types.INSTANCE\n        fallback = mypy.types.Instance.read(data)\n        ret = TypeVarTupleExpr(\n            read_str(data),\n            read_str(data),\n            mypy.types.read_type(data),\n            fallback,\n            mypy.types.read_type(data),\n            read_int(data),\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass TypeAliasExpr(Expression):\n    \"\"\"Type alias expression (rvalue).\"\"\"\n\n    __slots__ = (\"node\",)\n\n    __match_args__ = (\"node\",)\n\n    node: TypeAlias\n\n    def __init__(self, node: TypeAlias) -> None:\n        super().__init__()\n        self.node = node\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_type_alias_expr(self)\n\n\nclass NamedTupleExpr(Expression):\n    \"\"\"Named tuple expression namedtuple(...) or NamedTuple(...).\"\"\"\n\n    __slots__ = (\"info\", \"is_typed\")\n\n    __match_args__ = (\"info\",)\n\n    # The class representation of this named tuple (its tuple_type attribute contains\n    # the tuple item types)\n    info: TypeInfo\n    is_typed: bool  # whether this class was created with typing(_extensions).NamedTuple\n\n    def __init__(self, info: TypeInfo, is_typed: bool = False) -> None:\n        super().__init__()\n        self.info = info\n        self.is_typed = is_typed\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_namedtuple_expr(self)\n\n\nclass TypedDictExpr(Expression):\n    \"\"\"Typed dict expression TypedDict(...).\"\"\"\n\n    __slots__ = (\"info\",)\n\n    __match_args__ = (\"info\",)\n\n    # The class representation of this typed dict\n    info: TypeInfo\n\n    def __init__(self, info: TypeInfo) -> None:\n        super().__init__()\n        self.info = info\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_typeddict_expr(self)\n\n\nclass EnumCallExpr(Expression):\n    \"\"\"Named tuple expression Enum('name', 'val1 val2 ...').\"\"\"\n\n    __slots__ = (\"info\", \"items\", \"values\")\n\n    __match_args__ = (\"info\", \"items\", \"values\")\n\n    # The class representation of this enumerated type\n    info: TypeInfo\n    # The item names (for debugging)\n    items: list[str]\n    values: list[Expression | None]\n\n    def __init__(self, info: TypeInfo, items: list[str], values: list[Expression | None]) -> None:\n        super().__init__()\n        self.info = info\n        self.items = items\n        self.values = values\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_enum_call_expr(self)\n\n\nclass PromoteExpr(Expression):\n    \"\"\"Ducktype class decorator expression _promote(...).\"\"\"\n\n    __slots__ = (\"type\",)\n\n    type: mypy.types.ProperType\n\n    def __init__(self, type: mypy.types.ProperType) -> None:\n        super().__init__()\n        self.type = type\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit__promote_expr(self)\n\n\nclass NewTypeExpr(Expression):\n    \"\"\"NewType expression NewType(...).\"\"\"\n\n    __slots__ = (\"name\", \"old_type\", \"info\")\n\n    __match_args__ = (\"name\", \"old_type\", \"info\")\n\n    name: str\n    # The base type (the second argument to NewType)\n    old_type: mypy.types.Type | None\n    # The synthesized class representing the new type (inherits old_type)\n    info: TypeInfo | None\n\n    def __init__(\n        self, name: str, old_type: mypy.types.Type | None, line: int, column: int\n    ) -> None:\n        super().__init__(line=line, column=column)\n        self.name = name\n        self.old_type = old_type\n        self.info = None\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_newtype_expr(self)\n\n\nclass AwaitExpr(Expression):\n    \"\"\"Await expression (await ...).\"\"\"\n\n    __slots__ = (\"expr\",)\n\n    __match_args__ = (\"expr\",)\n\n    expr: Expression\n\n    def __init__(self, expr: Expression) -> None:\n        super().__init__()\n        self.expr = expr\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_await_expr(self)\n\n\n# Constants\n\n\nclass TempNode(Expression):\n    \"\"\"Temporary dummy node used during type checking.\n\n    This node is not present in the original program; it is just an artifact\n    of the type checker implementation. It only represents an opaque node with\n    some fixed type.\n    \"\"\"\n\n    __slots__ = (\"type\", \"no_rhs\")\n\n    type: mypy.types.Type\n    # Is this TempNode used to indicate absence of a right hand side in an annotated assignment?\n    # (e.g. for 'x: int' the rvalue is TempNode(AnyType(TypeOfAny.special_form), no_rhs=True))\n    no_rhs: bool\n\n    def __init__(\n        self, typ: mypy.types.Type, no_rhs: bool = False, *, context: Context | None = None\n    ) -> None:\n        \"\"\"Construct a dummy node; optionally borrow line/column from context object.\"\"\"\n        super().__init__()\n        self.type = typ\n        self.no_rhs = no_rhs\n        if context is not None:\n            self.line = context.line\n            self.column = context.column\n\n    def __repr__(self) -> str:\n        return \"TempNode:%d(%s)\" % (self.line, str(self.type))\n\n    def accept(self, visitor: ExpressionVisitor[T]) -> T:\n        return visitor.visit_temp_node(self)\n\n\n# Special attributes not collected as protocol members by Python 3.12\n# See typing._SPECIAL_NAMES\nEXCLUDED_PROTOCOL_ATTRIBUTES: Final = frozenset(\n    {\n        \"__abstractmethods__\",\n        \"__annotations__\",\n        \"__dict__\",\n        \"__doc__\",\n        \"__init__\",\n        \"__module__\",\n        \"__new__\",\n        \"__slots__\",\n        \"__subclasshook__\",\n        \"__weakref__\",\n        \"__class_getitem__\",  # Since Python 3.9\n    }\n)\n\n# Attributes that can optionally be defined in the body of a subclass of\n# enum.Enum but are removed from the class __dict__ by EnumMeta.\nEXCLUDED_ENUM_ATTRIBUTES: Final = frozenset({\"_ignore_\", \"_order_\", \"__order__\"})\n\n\nclass TypeInfo(SymbolNode):\n    \"\"\"The type structure of a single class.\n\n    Each TypeInfo corresponds one-to-one to a ClassDef, which\n    represents the AST of the class.\n\n    In type-theory terms, this is a \"type constructor\", and if the\n    class is generic then it will be a type constructor of higher kind.\n    Where the class is used in an actual type, it's in the form of an\n    Instance, which amounts to a type application of the tycon to\n    the appropriate number of arguments.\n    \"\"\"\n\n    __slots__ = (\n        \"_fullname\",\n        \"module_name\",\n        \"defn\",\n        \"mro\",\n        \"_mro_refs\",\n        \"bad_mro\",\n        \"is_final\",\n        \"is_disjoint_base\",\n        \"declared_metaclass\",\n        \"metaclass_type\",\n        \"names\",\n        \"is_abstract\",\n        \"is_protocol\",\n        \"runtime_protocol\",\n        \"abstract_attributes\",\n        \"deletable_attributes\",\n        \"slots\",\n        \"assuming\",\n        \"assuming_proper\",\n        \"inferring\",\n        \"is_enum\",\n        \"fallback_to_any\",\n        \"meta_fallback_to_any\",\n        \"type_vars\",\n        \"has_param_spec_type\",\n        \"bases\",\n        \"_promote\",\n        \"tuple_type\",\n        \"special_alias\",\n        \"is_named_tuple\",\n        \"typeddict_type\",\n        \"is_newtype\",\n        \"is_intersection\",\n        \"metadata\",\n        \"alt_promote\",\n        \"has_type_var_tuple_type\",\n        \"type_var_tuple_prefix\",\n        \"type_var_tuple_suffix\",\n        \"self_type\",\n        \"dataclass_transform_spec\",\n        \"is_type_check_only\",\n        \"deprecated\",\n        \"type_object_type\",\n    )\n\n    _fullname: str  # Fully qualified name\n    # Fully qualified name for the module this type was defined in. This\n    # information is also in the fullname, but is harder to extract in the\n    # case of nested class definitions.\n    module_name: str\n    defn: ClassDef  # Corresponding ClassDef\n    # Method Resolution Order: the order of looking up attributes. The first\n    # value always to refers to this class.\n    mro: list[TypeInfo]\n    # Used to stash the names of the mro classes temporarily between\n    # deserialization and fixup. See deserialize() for why.\n    _mro_refs: list[str] | None\n    bad_mro: bool  # Could not construct full MRO\n    is_final: bool\n    is_disjoint_base: bool\n\n    declared_metaclass: mypy.types.Instance | None\n    metaclass_type: mypy.types.Instance | None\n\n    names: SymbolTable  # Names defined directly in this type\n    is_abstract: bool  # Does the class have any abstract attributes?\n    is_protocol: bool  # Is this a protocol class?\n    runtime_protocol: bool  # Does this protocol support isinstance checks?\n    # List of names of abstract attributes together with their abstract status.\n    # The abstract status must be one of `NOT_ABSTRACT`, `IS_ABSTRACT`, `IMPLICITLY_ABSTRACT`.\n    abstract_attributes: list[tuple[str, int]]\n    deletable_attributes: list[str]  # Used by mypyc only\n    # Does this type have concrete `__slots__` defined?\n    # If class does not have `__slots__` defined then it is `None`,\n    # if it has empty `__slots__` then it is an empty set.\n    slots: set[str] | None\n\n    # The attributes 'assuming' and 'assuming_proper' represent structural subtype matrices.\n    #\n    # In languages with structural subtyping, one can keep a global subtype matrix like this:\n    #   . A B C .\n    #   A 1 0 0\n    #   B 1 1 1\n    #   C 1 0 1\n    #   .\n    # where 1 indicates that the type in corresponding row is a subtype of the type\n    # in corresponding column. This matrix typically starts filled with all 1's and\n    # a typechecker tries to \"disprove\" every subtyping relation using atomic (or nominal) types.\n    # However, we don't want to keep this huge global state. Instead, we keep the subtype\n    # information in the form of list of pairs (subtype, supertype) shared by all Instances\n    # with given supertype's TypeInfo. When we enter a subtype check we push a pair in this list\n    # thus assuming that we started with 1 in corresponding matrix element. Such algorithm allows\n    # to treat recursive and mutually recursive protocols and other kinds of complex situations.\n    #\n    # If concurrent/parallel type checking will be added in future,\n    # then there should be one matrix per thread/process to avoid false negatives\n    # during the type checking phase.\n    assuming: list[tuple[mypy.types.Instance, mypy.types.Instance]]\n    assuming_proper: list[tuple[mypy.types.Instance, mypy.types.Instance]]\n    # Ditto for temporary 'inferring' stack of recursive constraint inference.\n    # It contains Instances of protocol types that appeared as an argument to\n    # constraints.infer_constraints(). We need 'inferring' to avoid infinite recursion for\n    # recursive and mutually recursive protocols.\n    #\n    # We make 'assuming' and 'inferring' attributes here instead of passing they as kwargs,\n    # since this would require to pass them in many dozens of calls. In particular,\n    # there is a dependency infer_constraint -> is_subtype -> is_callable_subtype ->\n    # -> infer_constraints.\n    inferring: list[mypy.types.Instance]\n    # 'inferring' and 'assuming' can't be made sets, since we need to use\n    # is_same_type to correctly treat unions.\n\n    # Classes inheriting from Enum shadow their true members with a __getattr__, so we\n    # have to treat them as a special case.\n    is_enum: bool\n    # If true, any unknown attributes should have type 'Any' instead\n    # of generating a type error.  This would be true if there is a\n    # base class with type 'Any', but other use cases may be\n    # possible. This is similar to having __getattr__ that returns Any\n    # (and __setattr__), but without the __getattr__ method.\n    fallback_to_any: bool\n\n    # Same as above but for cases where metaclass has type Any. This will suppress\n    # all attribute errors only for *class object* access.\n    meta_fallback_to_any: bool\n\n    # Information related to type annotations.\n\n    # Generic type variable names (full names)\n    type_vars: list[str]\n\n    # Whether this class has a ParamSpec type variable\n    has_param_spec_type: bool\n\n    # Direct base classes.\n    bases: list[mypy.types.Instance]\n\n    # Another type which this type will be treated as a subtype of,\n    # even though it's not a subclass in Python.  The non-standard\n    # `@_promote` decorator introduces this, and there are also\n    # several builtin examples, in particular `int` -> `float`.\n    _promote: list[mypy.types.ProperType]\n\n    # This is used for promoting native integer types such as 'i64' to\n    # 'int'. (_promote is used for the other direction.) This only\n    # supports one-step promotions (e.g., i64 -> int, not\n    # i64 -> int -> float, and this isn't used to promote in joins.\n    #\n    # This results in some unintuitive results, such as that even\n    # though i64 is compatible with int and int is compatible with\n    # float, i64 is *not* compatible with float.\n    alt_promote: mypy.types.Instance | None\n\n    # Representation of a Tuple[...] base class, if the class has any\n    # (e.g., for named tuples). If this is not None, the actual Type\n    # object used for this class is not an Instance but a TupleType;\n    # the corresponding Instance is set as the fallback type of the\n    # tuple type.\n    tuple_type: mypy.types.TupleType | None\n\n    # Is this a named tuple type?\n    is_named_tuple: bool\n\n    # If this class is defined by the TypedDict type constructor,\n    # then this is not None.\n    typeddict_type: mypy.types.TypedDictType | None\n\n    # Is this a newtype type?\n    is_newtype: bool\n\n    # Is this a synthesized intersection type?\n    is_intersection: bool\n\n    # This is a dictionary that will be serialized and un-serialized as is.\n    # It is useful for plugins to add their data to save in the cache.\n    metadata: dict[str, JsonDict]\n\n    # Store type alias representing this type (for named tuples and TypedDicts).\n    # Although definitions of these types are stored in symbol tables as TypeInfo,\n    # when a type analyzer will find them, it should construct a TupleType, or\n    # a TypedDict type. However, we can't use the plain types, since if the definition\n    # is recursive, this will create an actual recursive structure of types (i.e. as\n    # internal Python objects) causing infinite recursions everywhere during type checking.\n    # To overcome this, we create a TypeAlias node, that will point to these types.\n    # We store this node in the `special_alias` attribute, because it must be the same node\n    # in case we are doing multiple semantic analysis passes.\n    special_alias: TypeAlias | None\n\n    # Shared type variable for typing.Self in this class (if used, otherwise None).\n    self_type: mypy.types.TypeVarType | None\n\n    # Added if the corresponding class is directly decorated with `typing.dataclass_transform`\n    dataclass_transform_spec: DataclassTransformSpec | None\n\n    # Is set to `True` when class is decorated with `@typing.type_check_only`\n    is_type_check_only: bool\n\n    # The type's deprecation message (in case it is deprecated)\n    deprecated: str | None\n\n    # Cached value of class constructor type, i.e. the type of class object when it\n    # appears in runtime context.\n    type_object_type: mypy.types.FunctionLike | None\n\n    FLAGS: Final = [\n        \"is_abstract\",\n        \"is_enum\",\n        \"fallback_to_any\",\n        \"meta_fallback_to_any\",\n        \"is_named_tuple\",\n        \"is_newtype\",\n        \"is_protocol\",\n        \"runtime_protocol\",\n        \"is_final\",\n        \"is_disjoint_base\",\n        \"is_intersection\",\n    ]\n\n    def __init__(self, names: SymbolTable, defn: ClassDef, module_name: str) -> None:\n        \"\"\"Initialize a TypeInfo.\"\"\"\n        super().__init__()\n        self._fullname = defn.fullname\n        self.names = names\n        self.defn = defn\n        self.module_name = module_name\n        self.type_vars = []\n        self.has_param_spec_type = False\n        self.has_type_var_tuple_type = False\n        self.bases = []\n        self.mro = []\n        self._mro_refs = None\n        self.bad_mro = False\n        self.declared_metaclass = None\n        self.metaclass_type = None\n        self.is_abstract = False\n        self.abstract_attributes = []\n        self.deletable_attributes = []\n        self.slots = None\n        self.assuming = []\n        self.assuming_proper = []\n        self.inferring = []\n        self.is_protocol = False\n        self.runtime_protocol = False\n        self.type_var_tuple_prefix: int | None = None\n        self.type_var_tuple_suffix: int | None = None\n        self.add_type_vars()\n        self.is_final = False\n        self.is_disjoint_base = False\n        self.is_enum = False\n        self.fallback_to_any = False\n        self.meta_fallback_to_any = False\n        self._promote = []\n        self.alt_promote = None\n        self.tuple_type = None\n        self.special_alias = None\n        self.is_named_tuple = False\n        self.typeddict_type = None\n        self.is_newtype = False\n        self.is_intersection = False\n        self.metadata = {}\n        self.self_type = None\n        self.dataclass_transform_spec = None\n        self.is_type_check_only = False\n        self.deprecated = None\n        self.type_object_type = None\n\n    def add_type_vars(self) -> None:\n        self.has_type_var_tuple_type = False\n        if self.defn.type_vars:\n            for i, vd in enumerate(self.defn.type_vars):\n                if isinstance(vd, mypy.types.ParamSpecType):\n                    self.has_param_spec_type = True\n                if isinstance(vd, mypy.types.TypeVarTupleType):\n                    assert not self.has_type_var_tuple_type\n                    self.has_type_var_tuple_type = True\n                    self.type_var_tuple_prefix = i\n                    self.type_var_tuple_suffix = len(self.defn.type_vars) - i - 1\n                self.type_vars.append(vd.name)\n\n    @property\n    def name(self) -> str:\n        \"\"\"Short name.\"\"\"\n        return self.defn.name\n\n    @property\n    def fullname(self) -> str:\n        return self._fullname\n\n    def is_generic(self) -> bool:\n        \"\"\"Is the type generic (i.e. does it have type variables)?\"\"\"\n        return len(self.type_vars) > 0\n\n    def get(self, name: str) -> SymbolTableNode | None:\n        for cls in self.mro:\n            n = cls.names.get(name)\n            if n:\n                return n\n        return None\n\n    def get_containing_type_info(self, name: str) -> TypeInfo | None:\n        for cls in self.mro:\n            if name in cls.names:\n                return cls\n        return None\n\n    @property\n    def protocol_members(self) -> list[str]:\n        # Protocol members are names of all attributes/methods defined in a protocol\n        # and in all its supertypes (except for 'object').\n        members: set[str] = set()\n        assert self.mro, \"This property can be only accessed after MRO is (re-)calculated\"\n        for base in self.mro[:-1]:  # we skip \"object\" since everyone implements it\n            if base.is_protocol:\n                for name, node in base.names.items():\n                    if isinstance(node.node, (TypeAlias, TypeVarExpr, MypyFile)):\n                        # These are auxiliary definitions (and type aliases are prohibited).\n                        continue\n                    if name in EXCLUDED_PROTOCOL_ATTRIBUTES:\n                        continue\n                    members.add(name)\n        return sorted(members)\n\n    @property\n    def enum_members(self) -> list[str]:\n        # TODO: cache the results?\n        members = []\n        for name, sym in self.names.items():\n            # Case 1:\n            #\n            # class MyEnum(Enum):\n            #     @member\n            #     def some(self): ...\n            if isinstance(sym.node, Decorator):\n                if any(\n                    dec.fullname == \"enum.member\"\n                    for dec in sym.node.decorators\n                    if isinstance(dec, RefExpr)\n                ):\n                    members.append(name)\n                    continue\n            # Case 2:\n            #\n            # class MyEnum(Enum):\n            #     x = 1\n            #\n            # Case 3:\n            #\n            # class MyEnum(Enum):\n            #     class Other: ...\n            elif isinstance(sym.node, (Var, TypeInfo)):\n                if (\n                    # TODO: properly support ignored names from `_ignore_`\n                    name in EXCLUDED_ENUM_ATTRIBUTES\n                    or is_sunder(name)\n                    or name.startswith(\"__\")  # dunder and private\n                ):\n                    continue  # name is excluded\n\n                if isinstance(sym.node, Var):\n                    if not sym.node.has_explicit_value:\n                        continue  # unannotated value not a member\n\n                    typ = mypy.types.get_proper_type(sym.node.type)\n                    if (\n                        isinstance(typ, mypy.types.FunctionLike) and not typ.is_type_obj()\n                    ) or (  # explicit `@member` is required\n                        isinstance(typ, mypy.types.Instance)\n                        and typ.type.fullname == \"enum.nonmember\"\n                    ):\n                        continue  # name is not a member\n\n                members.append(name)\n        return members\n\n    def __getitem__(self, name: str) -> SymbolTableNode:\n        n = self.get(name)\n        if n:\n            return n\n        else:\n            raise KeyError(name)\n\n    def __repr__(self) -> str:\n        return f\"<TypeInfo {self.fullname}>\"\n\n    def __bool__(self) -> bool:\n        # We defined this here instead of just overriding it in\n        # FakeInfo so that mypyc can generate a direct call instead of\n        # using the generic bool handling.\n        return not isinstance(self, FakeInfo)\n\n    def has_readable_member(self, name: str) -> bool:\n        return self.get(name) is not None\n\n    def get_method(self, name: str) -> FuncBase | Decorator | None:\n        for cls in self.mro:\n            if name in cls.names:\n                node = cls.names[name].node\n            elif possible_redefinitions := sorted(\n                [n for n in cls.names.keys() if n.startswith(f\"{name}-redefinition\")]\n            ):\n                node = cls.names[possible_redefinitions[-1]].node\n            else:\n                continue\n            if isinstance(node, SYMBOL_FUNCBASE_TYPES):\n                return node\n            elif isinstance(node, Decorator):  # Two `if`s make `mypyc` happy\n                return node\n            else:\n                return None\n        return None\n\n    def calculate_metaclass_type(self) -> mypy.types.Instance | None:\n        declared = self.declared_metaclass\n        if declared is not None and not declared.type.has_base(\"builtins.type\"):\n            return declared\n        if self._fullname == \"builtins.type\":\n            return mypy.types.Instance(self, [])\n\n        winner = declared\n        for super_class in self.mro[1:]:\n            super_meta = super_class.declared_metaclass\n            if super_meta is None or super_meta.type is None:\n                continue\n            if winner is None:\n                winner = super_meta\n                continue\n            if winner.type.has_base(super_meta.type.fullname):\n                continue\n            if super_meta.type.has_base(winner.type.fullname):\n                winner = super_meta\n                continue\n            # metaclass conflict\n            winner = None\n            break\n\n        return winner\n\n    def explain_metaclass_conflict(self) -> str | None:\n        # Compare to logic in calculate_metaclass_type\n        declared = self.declared_metaclass\n        if declared is not None and not declared.type.has_base(\"builtins.type\"):\n            return None\n        if self._fullname == \"builtins.type\":\n            return None\n\n        winner = declared\n        if declared is None:\n            resolution_steps = []\n        else:\n            resolution_steps = [f'\"{declared.type.fullname}\" (metaclass of \"{self.fullname}\")']\n        for super_class in self.mro[1:]:\n            super_meta = super_class.declared_metaclass\n            if super_meta is None or super_meta.type is None:\n                continue\n            if winner is None:\n                winner = super_meta\n                resolution_steps.append(\n                    f'\"{winner.type.fullname}\" (metaclass of \"{super_class.fullname}\")'\n                )\n                continue\n            if winner.type.has_base(super_meta.type.fullname):\n                continue\n            if super_meta.type.has_base(winner.type.fullname):\n                winner = super_meta\n                resolution_steps.append(\n                    f'\"{winner.type.fullname}\" (metaclass of \"{super_class.fullname}\")'\n                )\n                continue\n            # metaclass conflict\n            conflict = f'\"{super_meta.type.fullname}\" (metaclass of \"{super_class.fullname}\")'\n            return f\"{' > '.join(resolution_steps)} conflicts with {conflict}\"\n\n        return None\n\n    def is_metaclass(self, *, precise: bool = False) -> bool:\n        return (\n            self.has_base(\"builtins.type\")\n            or self.fullname == \"abc.ABCMeta\"\n            or (self.fallback_to_any and not precise)\n        )\n\n    def has_base(self, fullname: str) -> bool:\n        \"\"\"Return True if type has a base type with the specified name.\n\n        This can be either via extension or via implementation.\n        \"\"\"\n        for cls in self.mro:\n            if cls.fullname == fullname:\n                return True\n        return False\n\n    def direct_base_classes(self) -> list[TypeInfo]:\n        \"\"\"Return a direct base classes.\n\n        Omit base classes of other base classes.\n        \"\"\"\n        return [base.type for base in self.bases]\n\n    def update_tuple_type(self, typ: mypy.types.TupleType) -> None:\n        \"\"\"Update tuple_type and special_alias as needed.\"\"\"\n        self.tuple_type = typ\n        alias = TypeAlias.from_tuple_type(self)\n        if not self.special_alias:\n            self.special_alias = alias\n        else:\n            self.special_alias.target = alias.target\n            # Invalidate recursive status cache in case it was previously set.\n            self.special_alias._is_recursive = None\n\n    def update_typeddict_type(self, typ: mypy.types.TypedDictType) -> None:\n        \"\"\"Update typeddict_type and special_alias as needed.\"\"\"\n        self.typeddict_type = typ\n        alias = TypeAlias.from_typeddict_type(self)\n        if not self.special_alias:\n            self.special_alias = alias\n        else:\n            self.special_alias.target = alias.target\n            # Invalidate recursive status cache in case it was previously set.\n            self.special_alias._is_recursive = None\n\n    def __str__(self) -> str:\n        \"\"\"Return a string representation of the type.\n\n        This includes the most important information about the type.\n        \"\"\"\n        options = Options()\n        return self.dump(\n            str_conv=mypy.strconv.StrConv(options=options),\n            type_str_conv=mypy.types.TypeStrVisitor(options=options),\n        )\n\n    def dump(\n        self, str_conv: mypy.strconv.StrConv, type_str_conv: mypy.types.TypeStrVisitor\n    ) -> str:\n        \"\"\"Return a string dump of the contents of the TypeInfo.\"\"\"\n\n        base: str = \"\"\n\n        def type_str(typ: mypy.types.Type) -> str:\n            return typ.accept(type_str_conv)\n\n        head = \"TypeInfo\" + str_conv.format_id(self)\n        if self.bases:\n            base = f\"Bases({', '.join(type_str(base) for base in self.bases)})\"\n        mro = \"Mro({})\".format(\n            \", \".join(item.fullname + str_conv.format_id(item) for item in self.mro)\n        )\n        names = []\n        for name in sorted(self.names):\n            description = name + str_conv.format_id(self.names[name].node)\n            node = self.names[name].node\n            if isinstance(node, Var) and node.type:\n                description += f\" ({type_str(node.type)})\"\n            names.append(description)\n        items = [f\"Name({self.fullname})\", base, mro, (\"Names\", names)]\n        if self.declared_metaclass:\n            items.append(f\"DeclaredMetaclass({type_str(self.declared_metaclass)})\")\n        if self.metaclass_type:\n            items.append(f\"MetaclassType({type_str(self.metaclass_type)})\")\n        return mypy.strconv.dump_tagged(items, head, str_conv=str_conv)\n\n    def serialize(self) -> JsonDict:\n        # NOTE: This is where all ClassDefs originate, so there shouldn't be duplicates.\n        data = {\n            \".class\": \"TypeInfo\",\n            \"module_name\": self.module_name,\n            \"fullname\": self.fullname,\n            \"names\": self.names.serialize(self.fullname),\n            \"defn\": self.defn.serialize(),\n            \"abstract_attributes\": self.abstract_attributes,\n            \"type_vars\": self.type_vars,\n            \"has_param_spec_type\": self.has_param_spec_type,\n            \"bases\": [b.serialize() for b in self.bases],\n            \"mro\": [c.fullname for c in self.mro],\n            \"_promote\": [p.serialize() for p in self._promote],\n            \"alt_promote\": None if self.alt_promote is None else self.alt_promote.serialize(),\n            \"declared_metaclass\": (\n                None if self.declared_metaclass is None else self.declared_metaclass.serialize()\n            ),\n            \"metaclass_type\": (\n                None if self.metaclass_type is None else self.metaclass_type.serialize()\n            ),\n            \"tuple_type\": None if self.tuple_type is None else self.tuple_type.serialize(),\n            \"typeddict_type\": (\n                None if self.typeddict_type is None else self.typeddict_type.serialize()\n            ),\n            \"flags\": get_flags(self, TypeInfo.FLAGS),\n            \"metadata\": self.metadata,\n            \"slots\": sorted(self.slots) if self.slots is not None else None,\n            \"deletable_attributes\": self.deletable_attributes,\n            \"self_type\": self.self_type.serialize() if self.self_type is not None else None,\n            \"dataclass_transform_spec\": (\n                self.dataclass_transform_spec.serialize()\n                if self.dataclass_transform_spec is not None\n                else None\n            ),\n            \"deprecated\": self.deprecated,\n        }\n        return data\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypeInfo:\n        names = SymbolTable.deserialize(data[\"names\"])\n        defn = ClassDef.deserialize(data[\"defn\"])\n        module_name = data[\"module_name\"]\n        ti = TypeInfo(names, defn, module_name)\n        ti._fullname = data[\"fullname\"]\n        ti.abstract_attributes = [(attr[0], attr[1]) for attr in data[\"abstract_attributes\"]]\n        ti.type_vars = data[\"type_vars\"]\n        ti.has_param_spec_type = data[\"has_param_spec_type\"]\n        ti.bases = [mypy.types.Instance.deserialize(b) for b in data[\"bases\"]]\n        _promote = []\n        for p in data[\"_promote\"]:\n            t = mypy.types.deserialize_type(p)\n            assert isinstance(t, mypy.types.ProperType)\n            _promote.append(t)\n        ti._promote = _promote\n        ti.alt_promote = (\n            None\n            if data[\"alt_promote\"] is None\n            else mypy.types.Instance.deserialize(data[\"alt_promote\"])\n        )\n        ti.declared_metaclass = (\n            None\n            if data[\"declared_metaclass\"] is None\n            else mypy.types.Instance.deserialize(data[\"declared_metaclass\"])\n        )\n        ti.metaclass_type = (\n            None\n            if data[\"metaclass_type\"] is None\n            else mypy.types.Instance.deserialize(data[\"metaclass_type\"])\n        )\n        # NOTE: ti.mro will be set in the fixup phase based on these\n        # names.  The reason we need to store the mro instead of just\n        # recomputing it from base classes has to do with a subtle\n        # point about fine-grained incremental: the cache files might\n        # not be loaded until after a class in the mro has changed its\n        # bases, which causes the mro to change. If we recomputed our\n        # mro, we would compute the *new* mro, which leaves us with no\n        # way to detect that the mro has changed! Thus we need to make\n        # sure to load the original mro so that once the class is\n        # rechecked, it can tell that the mro has changed.\n        ti._mro_refs = data[\"mro\"]\n        ti.tuple_type = (\n            None\n            if data[\"tuple_type\"] is None\n            else mypy.types.TupleType.deserialize(data[\"tuple_type\"])\n        )\n        ti.typeddict_type = (\n            None\n            if data[\"typeddict_type\"] is None\n            else mypy.types.TypedDictType.deserialize(data[\"typeddict_type\"])\n        )\n        ti.metadata = data[\"metadata\"]\n        ti.slots = set(data[\"slots\"]) if data[\"slots\"] is not None else None\n        ti.deletable_attributes = data[\"deletable_attributes\"]\n        set_flags(ti, data[\"flags\"])\n        st = data[\"self_type\"]\n        ti.self_type = mypy.types.TypeVarType.deserialize(st) if st is not None else None\n        if data.get(\"dataclass_transform_spec\") is not None:\n            ti.dataclass_transform_spec = DataclassTransformSpec.deserialize(\n                data[\"dataclass_transform_spec\"]\n            )\n        ti.deprecated = data.get(\"deprecated\")\n        return ti\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, TYPE_INFO)\n        self.names.write(data, self.fullname)\n        self.defn.write(data)\n        write_str(data, self.module_name)\n        write_str(data, self.fullname)\n        write_str_list(data, [a for a, _ in self.abstract_attributes])\n        write_int_list(data, [s for _, s in self.abstract_attributes])\n        write_str_list(data, self.type_vars)\n        write_bool(data, self.has_param_spec_type)\n        mypy.types.write_type_list(data, self.bases)\n        write_str_list(data, [c.fullname for c in self.mro])\n        mypy.types.write_type_list(data, self._promote)\n        mypy.types.write_type_opt(data, self.alt_promote)\n        mypy.types.write_type_opt(data, self.declared_metaclass)\n        mypy.types.write_type_opt(data, self.metaclass_type)\n        mypy.types.write_type_opt(data, self.tuple_type)\n        mypy.types.write_type_opt(data, self.typeddict_type)\n        write_flags(\n            data,\n            [\n                self.is_abstract,\n                self.is_enum,\n                self.fallback_to_any,\n                self.meta_fallback_to_any,\n                self.is_named_tuple,\n                self.is_newtype,\n                self.is_protocol,\n                self.runtime_protocol,\n                self.is_final,\n                self.is_disjoint_base,\n                self.is_intersection,\n            ],\n        )\n        write_json(data, self.metadata)\n        if self.slots is None:\n            write_tag(data, LITERAL_NONE)\n        else:\n            write_str_list(data, sorted(self.slots))\n        write_str_list(data, self.deletable_attributes)\n        mypy.types.write_type_opt(data, self.self_type)\n        if self.dataclass_transform_spec is None:\n            write_tag(data, LITERAL_NONE)\n        else:\n            self.dataclass_transform_spec.write(data)\n        write_str_opt(data, self.deprecated)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> TypeInfo:\n        names = SymbolTable.read(data)\n        assert read_tag(data) == CLASS_DEF\n        defn = ClassDef.read(data)\n        module_name = read_str(data)\n        ti = TypeInfo(names, defn, module_name)\n        ti._fullname = read_str(data)\n        attrs = read_str_list(data)\n        statuses = read_int_list(data)\n        ti.abstract_attributes = list(zip(attrs, statuses))\n        ti.type_vars = read_str_list(data)\n        ti.has_param_spec_type = read_bool(data)\n        ti.bases = []\n        assert read_tag(data) == LIST_GEN\n        for _ in range(read_int_bare(data)):\n            assert read_tag(data) == mypy.types.INSTANCE\n            ti.bases.append(mypy.types.Instance.read(data))\n        # NOTE: ti.mro will be set in the fixup phase based on these\n        # names.  The reason we need to store the mro instead of just\n        # recomputing it from base classes has to do with a subtle\n        # point about fine-grained incremental: the cache files might\n        # not be loaded until after a class in the mro has changed its\n        # bases, which causes the mro to change. If we recomputed our\n        # mro, we would compute the *new* mro, which leaves us with no\n        # way to detect that the mro has changed! Thus, we need to make\n        # sure to load the original mro so that once the class is\n        # rechecked, it can tell that the mro has changed.\n        ti._mro_refs = read_str_list(data)\n        ti._promote = cast(list[mypy.types.ProperType], mypy.types.read_type_list(data))\n        if (tag := read_tag(data)) != LITERAL_NONE:\n            assert tag == mypy.types.INSTANCE\n            ti.alt_promote = mypy.types.Instance.read(data)\n        if (tag := read_tag(data)) != LITERAL_NONE:\n            assert tag == mypy.types.INSTANCE\n            ti.declared_metaclass = mypy.types.Instance.read(data)\n        if (tag := read_tag(data)) != LITERAL_NONE:\n            assert tag == mypy.types.INSTANCE\n            ti.metaclass_type = mypy.types.Instance.read(data)\n        if (tag := read_tag(data)) != LITERAL_NONE:\n            assert tag == mypy.types.TUPLE_TYPE\n            ti.tuple_type = mypy.types.TupleType.read(data)\n        if (tag := read_tag(data)) != LITERAL_NONE:\n            assert tag == mypy.types.TYPED_DICT_TYPE\n            ti.typeddict_type = mypy.types.TypedDictType.read(data)\n        (\n            ti.is_abstract,\n            ti.is_enum,\n            ti.fallback_to_any,\n            ti.meta_fallback_to_any,\n            ti.is_named_tuple,\n            ti.is_newtype,\n            ti.is_protocol,\n            ti.runtime_protocol,\n            ti.is_final,\n            ti.is_disjoint_base,\n            ti.is_intersection,\n        ) = read_flags(data, num_flags=11)\n        ti.metadata = read_json(data)\n        tag = read_tag(data)\n        if tag != LITERAL_NONE:\n            assert tag == LIST_STR\n            ti.slots = {read_str_bare(data) for _ in range(read_int_bare(data))}\n        ti.deletable_attributes = read_str_list(data)\n        if (tag := read_tag(data)) != LITERAL_NONE:\n            assert tag == mypy.types.TYPE_VAR_TYPE\n            ti.self_type = mypy.types.TypeVarType.read(data)\n        tag = read_tag(data)\n        if tag != LITERAL_NONE:\n            assert tag == DT_SPEC\n            ti.dataclass_transform_spec = DataclassTransformSpec.read(data)\n        ti.deprecated = read_str_opt(data)\n        assert read_tag(data) == END_TAG\n        return ti\n\n\nclass FakeInfo(TypeInfo):\n    __slots__ = (\"msg\",)\n\n    # types.py defines a single instance of this class, called types.NOT_READY.\n    # This instance is used as a temporary placeholder in the process of de-serialization\n    # of 'Instance' types. The de-serialization happens in two steps: In the first step,\n    # Instance.type is set to NOT_READY. In the second step (in fixup.py) it is replaced by\n    # an actual TypeInfo. If you see the assertion error below, then most probably something\n    # went wrong during the second step and an 'Instance' that raised this error was not fixed.\n    # Note:\n    # 'None' is not used as a dummy value for two reasons:\n    # 1. This will require around 80-100 asserts to make 'mypy --strict-optional mypy'\n    #    pass cleanly.\n    # 2. If NOT_READY value is accidentally used somewhere, it will be obvious where the value\n    #    is from, whereas a 'None' value could come from anywhere.\n    #\n    # Additionally, this serves as a more general-purpose placeholder\n    # for missing TypeInfos in a number of places where the excuses\n    # for not being Optional are a little weaker.\n    #\n    # TypeInfo defines a __bool__ method that returns False for FakeInfo\n    # so that it can be conveniently tested against in the same way that it\n    # would be if things were properly optional.\n    def __init__(self, msg: str) -> None:\n        self.msg = msg\n\n    def __getattribute__(self, attr: str) -> type:\n        # Handle __class__ so that isinstance still works...\n        if attr == \"__class__\":\n            return object.__getattribute__(self, attr)  # type: ignore[no-any-return]\n        raise AssertionError(object.__getattribute__(self, \"msg\"))\n\n\nVAR_NO_INFO: Final[TypeInfo] = FakeInfo(\"Var is lacking info\")\nCLASSDEF_NO_INFO: Final[TypeInfo] = FakeInfo(\"ClassDef is lacking info\")\nFUNC_NO_INFO: Final[TypeInfo] = FakeInfo(\"FuncBase for non-methods lack info\")\nMISSING_FALLBACK: Final = FakeInfo(\"fallback can't be filled out until semanal\")\n\n\nclass TypeAlias(SymbolNode):\n    \"\"\"\n    A symbol node representing a type alias.\n\n    Type alias is a static concept, in contrast to variables with types\n    like Type[...]. Namely:\n        * type aliases\n            - can be used in type context (annotations)\n            - cannot be re-assigned\n        * variables with type Type[...]\n            - cannot be used in type context\n            - but can be re-assigned\n\n    An alias can be defined only by an assignment to a name (not any other lvalues).\n\n    Such assignment defines an alias by default. To define a variable,\n    an explicit Type[...] annotation is required. As an exception,\n    at non-global scope non-subscripted rvalue creates a variable even without\n    an annotation. This exception exists to accommodate the common use case of\n    class-valued attributes. See SemanticAnalyzerPass2.check_and_set_up_type_alias\n    for details.\n\n    Aliases can be generic. We use bound type variables for generic aliases, similar\n    to classes. Essentially, type aliases work as macros that expand textually.\n    The definition and expansion rules are following:\n\n        1. An alias targeting a generic class without explicit variables act as\n        the given class (this doesn't apply to TypedDict, Tuple and Callable, which\n        are not proper classes but special type constructors):\n\n            A = List\n            AA = List[Any]\n\n            x: A  # same as List[Any]\n            x: A[int]  # same as List[int]\n\n            x: AA  # same as List[Any]\n            x: AA[int]  # Error!\n\n            C = Callable  # Same as Callable[..., Any]\n            T = Tuple  # Same as Tuple[Any, ...]\n\n        2. An alias using explicit type variables in its rvalue expects\n        replacements (type arguments) for these variables. If missing, they\n        are treated as Any, like for other generics:\n\n            B = List[Tuple[T, T]]\n\n            x: B  # same as List[Tuple[Any, Any]]\n            x: B[int]  # same as List[Tuple[int, int]]\n\n            def f(x: B[T]) -> T: ...  # without T, Any would be used here\n\n        3. An alias can be defined using another aliases. In the definition\n        rvalue the Any substitution doesn't happen for top level unsubscripted\n        generic classes:\n\n            A = List\n            B = A  # here A is expanded to List, _not_ List[Any],\n                   # to match the Python runtime behaviour\n            x: B[int]  # same as List[int]\n            C = List[A]  # this expands to List[List[Any]]\n\n            AA = List[T]\n            D = AA  # here AA expands to List[Any]\n            x: D[int]  # Error!\n\n    Note: the fact that we support aliases like `A = List` means that the target\n    type will be initially an instance type with wrong number of type arguments.\n    Such instances are all fixed either during or after main semantic analysis passes.\n    We therefore store the difference between `List` and `List[Any]` rvalues (targets)\n    using the `no_args` flag.\n\n    Meaning of other fields:\n\n    target: The target type. For generic aliases contains bound type variables\n        as nested types (currently TypeVar and ParamSpec are supported).\n    _fullname: Qualified name of this type alias. This is used in particular\n        to track fine-grained dependencies from aliases.\n    module: Module where the alias was defined.\n    alias_tvars: Type variables used to define this alias.\n    normalized: Used to distinguish between `A = List`, and `A = list`. Both\n        are internally stored using `builtins.list` (because `typing.List` is\n        itself an alias), while the second cannot be subscripted because of\n        Python runtime limitation.\n    line and column: Line and column on the original alias definition.\n    eager: If True, immediately expand alias when referred to (useful for aliases\n        within functions that can't be looked up from the symbol table)\n    \"\"\"\n\n    __slots__ = (\n        \"target\",\n        \"_fullname\",\n        \"module\",\n        \"alias_tvars\",\n        \"no_args\",\n        \"normalized\",\n        \"_is_recursive\",\n        \"eager\",\n        \"tvar_tuple_index\",\n        \"python_3_12_type_alias\",\n    )\n\n    __match_args__ = (\"name\", \"target\", \"alias_tvars\", \"no_args\")\n\n    def __init__(\n        self,\n        target: mypy.types.Type,\n        fullname: str,\n        module: str,\n        line: int,\n        column: int,\n        *,\n        alias_tvars: list[mypy.types.TypeVarLikeType] | None = None,\n        no_args: bool = False,\n        normalized: bool = False,\n        eager: bool = False,\n        python_3_12_type_alias: bool = False,\n    ) -> None:\n        self._fullname = fullname\n        self.module = module\n        self.target = target\n        if alias_tvars is None:\n            alias_tvars = []\n        self.alias_tvars = alias_tvars\n        self.no_args = no_args\n        self.normalized = normalized\n        # This attribute is manipulated by TypeAliasType. If non-None,\n        # it is the cached value.\n        self._is_recursive: bool | None = None\n        self.eager = eager\n        self.python_3_12_type_alias = python_3_12_type_alias\n        self.tvar_tuple_index = None\n        for i, t in enumerate(alias_tvars):\n            if isinstance(t, mypy.types.TypeVarTupleType):\n                self.tvar_tuple_index = i\n        super().__init__(line, column)\n\n    @classmethod\n    def from_tuple_type(cls, info: TypeInfo) -> TypeAlias:\n        \"\"\"Generate an alias to the tuple type described by a given TypeInfo.\n\n        NOTE: this doesn't set type alias type variables (for generic tuple types),\n        they must be set by the caller (when fully analyzed).\n        \"\"\"\n        assert info.tuple_type\n        # TODO: is it possible to refactor this to set the correct type vars here?\n        return TypeAlias(\n            info.tuple_type.copy_modified(\n                # Create an Instance similar to fill_typevars().\n                fallback=mypy.types.Instance(\n                    info, mypy.types.type_vars_as_args(info.defn.type_vars)\n                )\n            ),\n            info.fullname,\n            info.module_name,\n            info.line,\n            info.column,\n        )\n\n    @classmethod\n    def from_typeddict_type(cls, info: TypeInfo) -> TypeAlias:\n        \"\"\"Generate an alias to the TypedDict type described by a given TypeInfo.\n\n        NOTE: this doesn't set type alias type variables (for generic TypedDicts),\n        they must be set by the caller (when fully analyzed).\n        \"\"\"\n        assert info.typeddict_type\n        # TODO: is it possible to refactor this to set the correct type vars here?\n        return TypeAlias(\n            info.typeddict_type.copy_modified(\n                # Create an Instance similar to fill_typevars().\n                fallback=mypy.types.Instance(\n                    info, mypy.types.type_vars_as_args(info.defn.type_vars)\n                )\n            ),\n            info.fullname,\n            info.module_name,\n            info.line,\n            info.column,\n        )\n\n    @property\n    def name(self) -> str:\n        return self._fullname.split(\".\")[-1]\n\n    @property\n    def fullname(self) -> str:\n        return self._fullname\n\n    @property\n    def has_param_spec_type(self) -> bool:\n        return any(isinstance(v, mypy.types.ParamSpecType) for v in self.alias_tvars)\n\n    def accept(self, visitor: NodeVisitor[T]) -> T:\n        return visitor.visit_type_alias(self)\n\n    def serialize(self) -> JsonDict:\n        data: JsonDict = {\n            \".class\": \"TypeAlias\",\n            \"fullname\": self._fullname,\n            \"module\": self.module,\n            \"target\": self.target.serialize(),\n            \"alias_tvars\": [v.serialize() for v in self.alias_tvars],\n            \"no_args\": self.no_args,\n            \"normalized\": self.normalized,\n            \"python_3_12_type_alias\": self.python_3_12_type_alias,\n        }\n        return data\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypeAlias:\n        assert data[\".class\"] == \"TypeAlias\"\n        fullname = data[\"fullname\"]\n        module = data[\"module\"]\n        alias_tvars = [mypy.types.deserialize_type(v) for v in data[\"alias_tvars\"]]\n        assert all(isinstance(t, mypy.types.TypeVarLikeType) for t in alias_tvars)\n        target = mypy.types.deserialize_type(data[\"target\"])\n        no_args = data[\"no_args\"]\n        normalized = data[\"normalized\"]\n        python_3_12_type_alias = data[\"python_3_12_type_alias\"]\n        return cls(\n            target,\n            fullname,\n            module,\n            -1,\n            -1,\n            alias_tvars=cast(list[mypy.types.TypeVarLikeType], alias_tvars),\n            no_args=no_args,\n            normalized=normalized,\n            python_3_12_type_alias=python_3_12_type_alias,\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, TYPE_ALIAS)\n        write_str(data, self._fullname)\n        write_str(data, self.module)\n        self.target.write(data)\n        mypy.types.write_type_list(data, self.alias_tvars)\n        write_bool(data, self.no_args)\n        write_bool(data, self.normalized)\n        write_bool(data, self.python_3_12_type_alias)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> TypeAlias:\n        fullname = read_str(data)\n        module = read_str(data)\n        target = mypy.types.read_type(data)\n        alias_tvars = mypy.types.read_type_var_likes(data)\n        ret = TypeAlias(\n            target,\n            fullname,\n            module,\n            -1,\n            -1,\n            alias_tvars=alias_tvars,\n            no_args=read_bool(data),\n            normalized=read_bool(data),\n            python_3_12_type_alias=read_bool(data),\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass PlaceholderNode(SymbolNode):\n    \"\"\"Temporary symbol node that will later become a real SymbolNode.\n\n    These are only present during semantic analysis when using the new\n    semantic analyzer. These are created if some essential dependencies\n    of a definition are not yet complete.\n\n    A typical use is for names imported from a module which is still\n    incomplete (within an import cycle):\n\n      from m import f  # Initially may create PlaceholderNode\n\n    This is particularly important if the imported shadows a name from\n    an enclosing scope or builtins:\n\n      from m import int  # Placeholder avoids mixups with builtins.int\n\n    Another case where this is useful is when there is another definition\n    or assignment:\n\n      from m import f\n      def f() -> None: ...\n\n    In the above example, the presence of PlaceholderNode allows us to\n    handle the second definition as a redefinition.\n\n    They are also used to create PlaceholderType instances for types\n    that refer to incomplete types. Example:\n\n      class C(Sequence[C]): ...\n\n    We create a PlaceholderNode (with becomes_typeinfo=True) for C so\n    that the type C in Sequence[C] can be bound.\n\n    Attributes:\n\n      fullname: Full name of the PlaceholderNode.\n      node: AST node that contains the definition that caused this to\n          be created. This is useful for tracking order of incomplete definitions\n          and for debugging.\n      becomes_typeinfo: If True, this refers something that could later\n          become a TypeInfo. It can't be used with type variables, in\n          particular, as this would cause issues with class type variable\n          detection.\n\n    The long-term purpose of placeholder nodes/types is to evolve into\n    something that can support general recursive types.\n    \"\"\"\n\n    __slots__ = (\"_fullname\", \"node\", \"becomes_typeinfo\")\n\n    def __init__(\n        self, fullname: str, node: Node, line: int, *, becomes_typeinfo: bool = False\n    ) -> None:\n        self._fullname = fullname\n        self.node = node\n        self.becomes_typeinfo = becomes_typeinfo\n        self.line = line\n\n    @property\n    def name(self) -> str:\n        return self._fullname.split(\".\")[-1]\n\n    @property\n    def fullname(self) -> str:\n        return self._fullname\n\n    def serialize(self) -> JsonDict:\n        assert False, \"PlaceholderNode can't be serialized\"\n\n    def accept(self, visitor: NodeVisitor[T]) -> T:\n        return visitor.visit_placeholder_node(self)\n\n\nclass SymbolTableNode:\n    \"\"\"Description of a name binding in a symbol table.\n\n    These are only used as values in module (global), function (local)\n    and class symbol tables (see SymbolTable). The name that is bound is\n    the key in SymbolTable.\n\n    Symbol tables don't contain direct references to AST nodes primarily\n    because there can be multiple symbol table references to a single\n    AST node (due to imports and aliases), and different references can\n    behave differently. This class describes the unique properties of\n    each reference.\n\n    The most fundamental attribute is 'node', which is the AST node that\n    the name refers to.\n\n    The kind is usually one of LDEF, GDEF or MDEF, depending on the scope\n    of the definition. These three kinds can usually be used\n    interchangeably and the difference between local, global and class\n    scopes is mostly descriptive, with no semantic significance.\n    However, some tools that consume mypy ASTs may care about these so\n    they should be correct.\n\n    Attributes:\n        node: AST node of definition. Among others, this can be one of\n            FuncDef, Var, TypeInfo, TypeVarExpr or MypyFile -- or None\n            for cross_ref that hasn't been fixed up yet.\n        kind: Kind of node. Possible values:\n               - LDEF: local definition\n               - GDEF: global (module-level) definition\n               - MDEF: class member definition\n               - UNBOUND_IMPORTED: temporary kind for imported names (we\n                 don't know the final kind yet)\n        module_public: If False, this name won't be imported via\n            'from <module> import *'. This has no effect on names within\n            classes.\n        module_hidden: If True, the name will be never exported (needed for\n            stub files)\n        cross_ref: For deserialized MypyFile nodes, the referenced module\n            name; for other nodes, optionally the name of the referenced object.\n        implicit: Was this defined by assignment to self attribute?\n        plugin_generated: Was this symbol generated by a plugin?\n            (And therefore needs to be removed in aststrip.)\n        no_serialize: Do not serialize this node if True. This is used to prevent\n            keys in the cache that refer to modules on which this file does not\n            depend. Currently this can happen if there is a module not in build\n            used e.g. like this:\n                import a.b.c # type: ignore\n            This will add a submodule symbol to parent module `a` symbol table,\n            but `a.b` is _not_ added as its dependency. Therefore, we should\n            not serialize these symbols as they may not be found during fixup\n            phase, instead they will be re-added during subsequent patch parents\n            phase.\n            TODO: Refactor build.py to make dependency tracking more transparent\n            and/or refactor look-up functions to not require parent patching.\n\n    NOTE: No other attributes should be added to this class unless they\n    are shared by all node kinds.\n    \"\"\"\n\n    __slots__ = (\n        \"kind\",\n        \"node\",\n        \"module_public\",\n        \"module_hidden\",\n        \"cross_ref\",\n        \"implicit\",\n        \"plugin_generated\",\n        \"no_serialize\",\n    )\n\n    def __init__(\n        self,\n        kind: int,\n        node: SymbolNode | None,\n        module_public: bool = True,\n        implicit: bool = False,\n        module_hidden: bool = False,\n        *,\n        plugin_generated: bool = False,\n        no_serialize: bool = False,\n    ) -> None:\n        self.kind = kind\n        self.node = node\n        self.module_public = module_public\n        self.implicit = implicit\n        self.module_hidden = module_hidden\n        self.cross_ref: str | None = None\n        self.plugin_generated = plugin_generated\n        self.no_serialize = no_serialize\n\n    @property\n    def fullname(self) -> str | None:\n        if self.node is not None:\n            return self.node.fullname\n        else:\n            return None\n\n    @property\n    def type(self) -> mypy.types.Type | None:\n        node = self.node\n        if isinstance(node, (Var, SYMBOL_FUNCBASE_TYPES)) and node.type is not None:\n            return node.type\n        elif isinstance(node, Decorator):\n            return node.var.type\n        else:\n            return None\n\n    def copy(self) -> SymbolTableNode:\n        new = SymbolTableNode(\n            self.kind, self.node, self.module_public, self.implicit, self.module_hidden\n        )\n        new.cross_ref = self.cross_ref\n        return new\n\n    def __str__(self) -> str:\n        s = f\"{node_kinds[self.kind]}/{short_type(self.node)}\"\n        if isinstance(self.node, SymbolNode):\n            s += f\" ({self.node.fullname})\"\n        # Include declared type of variables and functions.\n        if self.type is not None:\n            s += f\" : {self.type}\"\n        if self.cross_ref:\n            s += f\" cross_ref:{self.cross_ref}\"\n        return s\n\n    def serialize(self, prefix: str, name: str) -> JsonDict:\n        \"\"\"Serialize a SymbolTableNode.\n\n        Args:\n          prefix: full name of the containing module or class; or None\n          name: name of this object relative to the containing object\n        \"\"\"\n        data: JsonDict = {\".class\": \"SymbolTableNode\", \"kind\": node_kinds[self.kind]}\n        if self.module_hidden:\n            data[\"module_hidden\"] = True\n        if not self.module_public:\n            data[\"module_public\"] = False\n        if self.implicit:\n            data[\"implicit\"] = True\n        if self.plugin_generated:\n            data[\"plugin_generated\"] = True\n        if isinstance(self.node, MypyFile):\n            data[\"cross_ref\"] = self.node.fullname\n        else:\n            assert self.node is not None, f\"{prefix}:{name}\"\n            if prefix is not None:\n                fullname = self.node.fullname\n                if (\n                    \".\" in fullname\n                    and fullname != prefix + \".\" + name\n                    and not (isinstance(self.node, Var) and self.node.from_module_getattr)\n                ):\n                    assert not isinstance(\n                        self.node, PlaceholderNode\n                    ), f\"Definition of {fullname} is unexpectedly incomplete\"\n                    data[\"cross_ref\"] = fullname\n                    return data\n            data[\"node\"] = self.node.serialize()\n        return data\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> SymbolTableNode:\n        assert data[\".class\"] == \"SymbolTableNode\"\n        kind = inverse_node_kinds[data[\"kind\"]]\n        if \"cross_ref\" in data:\n            # This will be fixed up later.\n            stnode = SymbolTableNode(kind, None)\n            stnode.cross_ref = data[\"cross_ref\"]\n        else:\n            assert \"node\" in data, data\n            node = SymbolNode.deserialize(data[\"node\"])\n            stnode = SymbolTableNode(kind, node)\n        if \"module_hidden\" in data:\n            stnode.module_hidden = data[\"module_hidden\"]\n        if \"module_public\" in data:\n            stnode.module_public = data[\"module_public\"]\n        if \"implicit\" in data:\n            stnode.implicit = data[\"implicit\"]\n        if \"plugin_generated\" in data:\n            stnode.plugin_generated = data[\"plugin_generated\"]\n        return stnode\n\n    def write(self, data: WriteBuffer, prefix: str, name: str) -> None:\n        write_tag(data, SYMBOL_TABLE_NODE)\n        write_int(data, self.kind)\n        write_bool(data, self.module_hidden)\n        write_bool(data, self.module_public)\n        write_bool(data, self.implicit)\n        write_bool(data, self.plugin_generated)\n\n        cross_ref = None\n        if isinstance(self.node, MypyFile):\n            cross_ref = self.node.fullname\n        else:\n            assert self.node is not None, f\"{prefix}:{name}\"\n            if prefix is not None:\n                fullname = self.node.fullname\n                if (\n                    \".\" in fullname\n                    and fullname != prefix + \".\" + name\n                    and not (isinstance(self.node, Var) and self.node.from_module_getattr)\n                ):\n                    assert not isinstance(\n                        self.node, PlaceholderNode\n                    ), f\"Definition of {fullname} is unexpectedly incomplete\"\n                    cross_ref = fullname\n\n        write_str_opt(data, cross_ref)\n        if cross_ref is None:\n            assert self.node is not None\n            self.node.write(data)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> SymbolTableNode:\n        assert read_tag(data) == SYMBOL_TABLE_NODE\n        sym = SymbolTableNode(read_int(data), None)\n        sym.module_hidden = read_bool(data)\n        sym.module_public = read_bool(data)\n        sym.implicit = read_bool(data)\n        sym.plugin_generated = read_bool(data)\n        cross_ref = read_str_opt(data)\n        if cross_ref is None:\n            sym.node = read_symbol(data)\n        else:\n            sym.cross_ref = cross_ref\n        assert read_tag(data) == END_TAG\n        return sym\n\n\nclass SymbolTable(dict[str, SymbolTableNode]):\n    \"\"\"Static representation of a namespace dictionary.\n\n    This is used for module, class and function namespaces.\n    \"\"\"\n\n    __slots__ = ()\n\n    def __str__(self) -> str:\n        a: list[str] = []\n        for key, value in self.items():\n            # Filter out the implicit import of builtins.\n            if isinstance(value, SymbolTableNode):\n                if (\n                    value.fullname != \"builtins\"\n                    and (value.fullname or \"\").split(\".\")[-1] not in implicit_module_attrs\n                ):\n                    a.append(\"  \" + str(key) + \" : \" + str(value))\n            else:\n                # Used in debugging:\n                a.append(\"  <invalid item>\")  # type: ignore[unreachable]\n        a = sorted(a)\n        a.insert(0, \"SymbolTable(\")\n        a[-1] += \")\"\n        return \"\\n\".join(a)\n\n    def copy(self) -> SymbolTable:\n        return SymbolTable([(key, node.copy()) for key, node in self.items()])\n\n    def serialize(self, fullname: str) -> JsonDict:\n        data: JsonDict = {\".class\": \"SymbolTable\"}\n        for key, value in self.items():\n            # Skip __builtins__: it's a reference to the builtins\n            # module that gets added to every module by\n            # SemanticAnalyzerPass2.visit_file(), but it shouldn't be\n            # accessed by users of the module.\n            if key == \"__builtins__\" or value.no_serialize:\n                continue\n            data[key] = value.serialize(fullname, key)\n        return data\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> SymbolTable:\n        assert data[\".class\"] == \"SymbolTable\"\n        st = SymbolTable()\n        for key, value in data.items():\n            if key != \".class\":\n                st[key] = SymbolTableNode.deserialize(value)\n        return st\n\n    def write(self, data: WriteBuffer, fullname: str) -> None:\n        size = 0\n        for key, value in self.items():\n            # Skip __builtins__: it's a reference to the builtins\n            # module that gets added to every module by\n            # SemanticAnalyzerPass2.visit_file(), but it shouldn't be\n            # accessed by users of the module.\n            if key == \"__builtins__\" or value.no_serialize:\n                continue\n            size += 1\n        # We intentionally tag SymbolTable as a simple dictionary str -> SymbolTableNode.\n        write_tag(data, DICT_STR_GEN)\n        write_int_bare(data, size)\n        for key in sorted(self):\n            value = self[key]\n            if key == \"__builtins__\" or value.no_serialize:\n                continue\n            write_str_bare(data, key)\n            value.write(data, fullname, key)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> SymbolTable:\n        assert read_tag(data) == DICT_STR_GEN\n        size = read_int_bare(data)\n        return SymbolTable(\n            [(read_str_bare(data), SymbolTableNode.read(data)) for _ in range(size)]\n        )\n\n\nclass DataclassTransformSpec:\n    \"\"\"Specifies how a dataclass-like transform should be applied. The fields here are based on the\n    parameters accepted by `typing.dataclass_transform`.\"\"\"\n\n    __slots__ = (\n        \"eq_default\",\n        \"order_default\",\n        \"kw_only_default\",\n        \"frozen_default\",\n        \"field_specifiers\",\n    )\n\n    def __init__(\n        self,\n        *,\n        eq_default: bool | None = None,\n        order_default: bool | None = None,\n        kw_only_default: bool | None = None,\n        field_specifiers: tuple[str, ...] | None = None,\n        # Specified outside of PEP 681:\n        # frozen_default was added to CPythonin https://github.com/python/cpython/pull/99958 citing\n        # positive discussion in typing-sig\n        frozen_default: bool | None = None,\n    ) -> None:\n        self.eq_default = eq_default if eq_default is not None else True\n        self.order_default = order_default if order_default is not None else False\n        self.kw_only_default = kw_only_default if kw_only_default is not None else False\n        self.frozen_default = frozen_default if frozen_default is not None else False\n        self.field_specifiers = field_specifiers if field_specifiers is not None else ()\n\n    def serialize(self) -> JsonDict:\n        return {\n            \"eq_default\": self.eq_default,\n            \"order_default\": self.order_default,\n            \"kw_only_default\": self.kw_only_default,\n            \"frozen_default\": self.frozen_default,\n            \"field_specifiers\": list(self.field_specifiers),\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> DataclassTransformSpec:\n        return DataclassTransformSpec(\n            eq_default=data.get(\"eq_default\"),\n            order_default=data.get(\"order_default\"),\n            kw_only_default=data.get(\"kw_only_default\"),\n            frozen_default=data.get(\"frozen_default\"),\n            field_specifiers=tuple(data.get(\"field_specifiers\", [])),\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, DT_SPEC)\n        write_bool(data, self.eq_default)\n        write_bool(data, self.order_default)\n        write_bool(data, self.kw_only_default)\n        write_bool(data, self.frozen_default)\n        write_str_list(data, self.field_specifiers)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> DataclassTransformSpec:\n        ret = DataclassTransformSpec(\n            eq_default=read_bool(data),\n            order_default=read_bool(data),\n            kw_only_default=read_bool(data),\n            frozen_default=read_bool(data),\n            field_specifiers=tuple(read_str_list(data)),\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n\n@trait\nclass SplittingVisitor:\n    # If True, process function definitions. If False, don't. This is used\n    # for processing module top levels in fine-grained incremental mode.\n    recurse_into_functions: bool\n\n    @contextmanager\n    def set_recurse_into_functions(self) -> Iterator[None]:\n        \"\"\"Temporarily set recurse_into_functions to True.\n\n        This is used to process top-level functions/methods as a whole.\n        \"\"\"\n        old_recurse_into_functions = self.recurse_into_functions\n        self.recurse_into_functions = True\n        try:\n            yield\n        finally:\n            self.recurse_into_functions = old_recurse_into_functions\n\n\ndef get_flags(node: Node, names: list[str]) -> list[str]:\n    return [name for name in names if getattr(node, name)]\n\n\ndef set_flags(node: Node, flags: list[str]) -> None:\n    for name in flags:\n        setattr(node, name, True)\n\n\ndef write_flags(data: WriteBuffer, flags: list[bool]) -> None:\n    assert len(flags) <= 26, \"This many flags not supported yet\"\n    packed = 0\n    for i, flag in enumerate(flags):\n        if flag:\n            packed |= 1 << i\n    write_int(data, packed)\n\n\ndef read_flags(data: ReadBuffer, num_flags: int) -> list[bool]:\n    packed = read_int(data)\n    return [(packed & (1 << i)) != 0 for i in range(num_flags)]\n\n\ndef get_member_expr_fullname(expr: MemberExpr) -> str | None:\n    \"\"\"Return the qualified name representation of a member expression.\n\n    Return a string of form foo.bar, foo.bar.baz, or similar, or None if the\n    argument cannot be represented in this form.\n    \"\"\"\n    initial: str | None = None\n    if isinstance(expr.expr, NameExpr):\n        initial = expr.expr.name\n    elif isinstance(expr.expr, MemberExpr):\n        initial = get_member_expr_fullname(expr.expr)\n    if initial is None:\n        return None\n    return f\"{initial}.{expr.name}\"\n\n\ndeserialize_map: Final = {\n    key: obj.deserialize\n    for key, obj in globals().items()\n    if type(obj) is not FakeInfo\n    and isinstance(obj, type)\n    and issubclass(obj, SymbolNode)\n    and obj is not SymbolNode\n}\n\n\ndef check_arg_kinds(\n    arg_kinds: list[ArgKind], nodes: list[T], fail: Callable[[str, T], None]\n) -> None:\n    is_var_arg = False\n    is_kw_arg = False\n    seen_named = False\n    seen_opt = False\n    for kind, node in zip(arg_kinds, nodes):\n        if kind == ARG_POS:\n            if is_var_arg or is_kw_arg or seen_named or seen_opt:\n                fail(\n                    \"Required positional args may not appear after default, named or var args\",\n                    node,\n                )\n                break\n        elif kind == ARG_OPT:\n            if is_var_arg or is_kw_arg or seen_named:\n                fail(\"Positional default args may not appear after named or var args\", node)\n                break\n            seen_opt = True\n        elif kind == ARG_STAR:\n            if is_var_arg or is_kw_arg or seen_named:\n                fail(\"Var args may not appear after named or var args\", node)\n                break\n            is_var_arg = True\n        elif kind == ARG_NAMED or kind == ARG_NAMED_OPT:\n            seen_named = True\n            if is_kw_arg:\n                fail(\"A **kwargs argument must be the last argument\", node)\n                break\n        elif kind == ARG_STAR2:\n            if is_kw_arg:\n                fail(\"You may only have one **kwargs argument\", node)\n                break\n            is_kw_arg = True\n\n\ndef check_param_names(\n    names: Sequence[str | None],\n    nodes: list[T],\n    fail: Callable[[str, T], None],\n    description: str = \"function definition\",\n) -> None:\n    seen_names: set[str | None] = set()\n    for name, node in zip(names, nodes):\n        if name is not None and name in seen_names:\n            fail(f'Duplicate parameter \"{name}\" in {description}', node)\n            break\n        seen_names.add(name)\n\n\ndef is_class_var(expr: NameExpr) -> bool:\n    \"\"\"Return whether the expression is ClassVar[...]\"\"\"\n    if isinstance(expr.node, Var):\n        return expr.node.is_classvar\n    return False\n\n\ndef is_final_node(node: SymbolNode | None) -> bool:\n    \"\"\"Check whether `node` corresponds to a final attribute.\"\"\"\n    return isinstance(node, (Var, FuncDef, OverloadedFuncDef, Decorator)) and node.is_final\n\n\ndef get_func_def(typ: mypy.types.CallableType) -> SymbolNode | None:\n    definition = typ.definition\n    if isinstance(definition, Decorator):\n        definition = definition.func\n    return definition\n\n\ndef local_definitions(\n    names: SymbolTable, name_prefix: str, info: TypeInfo | None = None\n) -> Iterator[Definition]:\n    \"\"\"Iterate over local definitions (not imported) in a symbol table.\n\n    Recursively iterate over class members and nested classes.\n    \"\"\"\n    # TODO: What should the name be? Or maybe remove it?\n    for name, symnode in names.items():\n        shortname = name\n        if \"-redef\" in name:\n            # Restore original name from mangled name of multiply defined function\n            shortname = name.split(\"-redef\")[0]\n        fullname = name_prefix + \".\" + shortname\n        node = symnode.node\n        if node and node.fullname == fullname:\n            yield fullname, symnode, info\n            if isinstance(node, TypeInfo):\n                yield from local_definitions(node.names, fullname, node)\n\n\n# See docstring for mypy/cache.py for reserved tag ranges.\nMYPY_FILE: Final[Tag] = 50\nOVERLOADED_FUNC_DEF: Final[Tag] = 51\nFUNC_DEF: Final[Tag] = 52\nDECORATOR: Final[Tag] = 53\nVAR: Final[Tag] = 54\nTYPE_VAR_EXPR: Final[Tag] = 55\nPARAM_SPEC_EXPR: Final[Tag] = 56\nTYPE_VAR_TUPLE_EXPR: Final[Tag] = 57\nTYPE_INFO: Final[Tag] = 58\nTYPE_ALIAS: Final[Tag] = 59\nCLASS_DEF: Final[Tag] = 60\nSYMBOL_TABLE_NODE: Final[Tag] = 61\n\nEXPR_STMT: Final[Tag] = 160\nCALL_EXPR: Final[Tag] = 161\nNAME_EXPR: Final[Tag] = 162\nSTR_EXPR: Final[Tag] = 163\nIMPORT: Final[Tag] = 164\nMEMBER_EXPR: Final[Tag] = 165\nOP_EXPR: Final[Tag] = 166\nINT_EXPR: Final[Tag] = 167\nIF_STMT: Final[Tag] = 168\nASSIGNMENT_STMT: Final[Tag] = 169\nTUPLE_EXPR: Final[Tag] = 170\nBLOCK: Final[Tag] = 171\nINDEX_EXPR: Final[Tag] = 172\nLIST_EXPR: Final[Tag] = 173\nSET_EXPR: Final[Tag] = 174\nRETURN_STMT: Final[Tag] = 175\nWHILE_STMT: Final[Tag] = 176\nCOMPARISON_EXPR: Final[Tag] = 177\nBOOL_OP_EXPR: Final[Tag] = 178\nFUNC_DEF_STMT: Final[Tag] = 179\nPASS_STMT: Final[Tag] = 180\nFLOAT_EXPR: Final[Tag] = 181\nUNARY_EXPR: Final[Tag] = 182\nDICT_EXPR: Final[Tag] = 183\nCOMPLEX_EXPR: Final[Tag] = 184\nSLICE_EXPR: Final[Tag] = 185\nTEMP_NODE: Final[Tag] = 186\nRAISE_STMT: Final[Tag] = 187\nBREAK_STMT: Final[Tag] = 188\nCONTINUE_STMT: Final[Tag] = 189\nGENERATOR_EXPR: Final[Tag] = 190\nYIELD_EXPR: Final[Tag] = 191\nYIELD_FROM_EXPR: Final[Tag] = 192\nLIST_COMPREHENSION: Final[Tag] = 193\nSET_COMPREHENSION: Final[Tag] = 194\nDICT_COMPREHENSION: Final[Tag] = 195\nIMPORT_FROM: Final[Tag] = 196\nASSERT_STMT: Final[Tag] = 197\nFOR_STMT: Final[Tag] = 198\nWITH_STMT: Final[Tag] = 199\nOPERATOR_ASSIGNMENT_STMT: Final[Tag] = 200\nTRY_STMT: Final[Tag] = 201\nELLIPSIS_EXPR: Final[Tag] = 202\nCONDITIONAL_EXPR: Final[Tag] = 203\nDEL_STMT: Final[Tag] = 204\nFSTRING_EXPR: Final[Tag] = 205\nFSTRING_INTERPOLATION: Final[Tag] = 206\nLAMBDA_EXPR: Final[Tag] = 207\nNAMED_EXPR: Final[Tag] = 208\nSTAR_EXPR: Final[Tag] = 209\nBYTES_EXPR: Final[Tag] = 210\nGLOBAL_DECL: Final[Tag] = 211\nNONLOCAL_DECL: Final[Tag] = 212\nAWAIT_EXPR: Final[Tag] = 213\nBIG_INT_EXPR: Final[Tag] = 214\nIMPORT_ALL: Final[Tag] = 215\nMATCH_STMT: Final[Tag] = 216\nAS_PATTERN: Final[Tag] = 217\nOR_PATTERN: Final[Tag] = 218\nVALUE_PATTERN: Final[Tag] = 219\nSINGLETON_PATTERN: Final[Tag] = 220\nSEQUENCE_PATTERN: Final[Tag] = 221\nSTARRED_PATTERN: Final[Tag] = 222\nMAPPING_PATTERN: Final[Tag] = 223\nCLASS_PATTERN: Final[Tag] = 224\nTYPE_ALIAS_STMT: Final[Tag] = 225\nIMPORT_METADATA: Final[Tag] = 226\nIMPORTFROM_METADATA: Final[Tag] = 227\nIMPORTALL_METADATA: Final[Tag] = 228\nTSTRING_EXPR: Final[Tag] = 229\n\n\ndef read_symbol(data: ReadBuffer) -> SymbolNode:\n    tag = read_tag(data)\n    # The branches here are ordered manually by type \"popularity\".\n    if tag == VAR:\n        return Var.read(data)\n    if tag == FUNC_DEF:\n        return FuncDef.read(data)\n    if tag == DECORATOR:\n        return Decorator.read(data)\n    if tag == TYPE_INFO:\n        return TypeInfo.read(data)\n    if tag == OVERLOADED_FUNC_DEF:\n        return OverloadedFuncDef.read(data)\n    if tag == TYPE_VAR_EXPR:\n        return TypeVarExpr.read(data)\n    if tag == TYPE_ALIAS:\n        return TypeAlias.read(data)\n    if tag == PARAM_SPEC_EXPR:\n        return ParamSpecExpr.read(data)\n    if tag == TYPE_VAR_TUPLE_EXPR:\n        return TypeVarTupleExpr.read(data)\n    assert False, f\"Unknown symbol tag {tag}\"\n\n\ndef read_overload_part(data: ReadBuffer, tag: Tag | None = None) -> OverloadPart:\n    if tag is None:\n        tag = read_tag(data)\n    if tag == DECORATOR:\n        return Decorator.read(data)\n    if tag == FUNC_DEF:\n        return FuncDef.read(data)\n    assert False, f\"Invalid tag for an OverloadPart {tag}\"\n"
  },
  {
    "path": "mypy/operators.py",
    "content": "\"\"\"Information about Python operators\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final\n\n# Map from binary operator id to related method name (in Python 3).\nop_methods: Final = {\n    \"+\": \"__add__\",\n    \"-\": \"__sub__\",\n    \"*\": \"__mul__\",\n    \"/\": \"__truediv__\",\n    \"%\": \"__mod__\",\n    \"divmod\": \"__divmod__\",\n    \"//\": \"__floordiv__\",\n    \"**\": \"__pow__\",\n    \"@\": \"__matmul__\",\n    \"&\": \"__and__\",\n    \"|\": \"__or__\",\n    \"^\": \"__xor__\",\n    \"<<\": \"__lshift__\",\n    \">>\": \"__rshift__\",\n    \"==\": \"__eq__\",\n    \"!=\": \"__ne__\",\n    \"<\": \"__lt__\",\n    \">=\": \"__ge__\",\n    \">\": \"__gt__\",\n    \"<=\": \"__le__\",\n    \"in\": \"__contains__\",\n}\n\nop_methods_to_symbols: Final = {v: k for (k, v) in op_methods.items()}\n\nops_falling_back_to_cmp: Final = {\"__ne__\", \"__eq__\", \"__lt__\", \"__le__\", \"__gt__\", \"__ge__\"}\n\n\nops_with_inplace_method: Final = {\n    \"+\",\n    \"-\",\n    \"*\",\n    \"/\",\n    \"%\",\n    \"//\",\n    \"**\",\n    \"@\",\n    \"&\",\n    \"|\",\n    \"^\",\n    \"<<\",\n    \">>\",\n}\n\ninplace_operator_methods: Final = {\"__i\" + op_methods[op][2:] for op in ops_with_inplace_method}\n\nreverse_op_methods: Final = {\n    \"__add__\": \"__radd__\",\n    \"__sub__\": \"__rsub__\",\n    \"__mul__\": \"__rmul__\",\n    \"__truediv__\": \"__rtruediv__\",\n    \"__mod__\": \"__rmod__\",\n    \"__divmod__\": \"__rdivmod__\",\n    \"__floordiv__\": \"__rfloordiv__\",\n    \"__pow__\": \"__rpow__\",\n    \"__matmul__\": \"__rmatmul__\",\n    \"__and__\": \"__rand__\",\n    \"__or__\": \"__ror__\",\n    \"__xor__\": \"__rxor__\",\n    \"__lshift__\": \"__rlshift__\",\n    \"__rshift__\": \"__rrshift__\",\n    \"__eq__\": \"__eq__\",\n    \"__ne__\": \"__ne__\",\n    \"__lt__\": \"__gt__\",\n    \"__ge__\": \"__le__\",\n    \"__gt__\": \"__lt__\",\n    \"__le__\": \"__ge__\",\n}\n\nreverse_op_method_names: Final = set(reverse_op_methods.values())\n\n# Suppose we have some class A. When we do A() + A(), Python will only check\n# the output of A().__add__(A()) and skip calling the __radd__ method entirely.\n# This shortcut is used only for the following methods:\nop_methods_that_shortcut: Final = {\n    \"__add__\",\n    \"__sub__\",\n    \"__mul__\",\n    \"__truediv__\",\n    \"__mod__\",\n    \"__divmod__\",\n    \"__floordiv__\",\n    \"__pow__\",\n    \"__matmul__\",\n    \"__and__\",\n    \"__or__\",\n    \"__xor__\",\n    \"__lshift__\",\n    \"__rshift__\",\n}\n\nnormal_from_reverse_op: Final = {m: n for n, m in reverse_op_methods.items()}\nreverse_op_method_set: Final = set(reverse_op_methods.values())\n\nunary_op_methods: Final = {\"-\": \"__neg__\", \"+\": \"__pos__\", \"~\": \"__invert__\"}\n\nint_op_to_method: Final = {\n    \"==\": int.__eq__,\n    \"is\": int.__eq__,\n    \"<\": int.__lt__,\n    \"<=\": int.__le__,\n    \"!=\": int.__ne__,\n    \"is not\": int.__ne__,\n    \">\": int.__gt__,\n    \">=\": int.__ge__,\n}\n\nflip_ops: Final = {\"<\": \">\", \"<=\": \">=\", \">\": \"<\", \">=\": \"<=\"}\nneg_ops: Final = {\n    \"==\": \"!=\",\n    \"!=\": \"==\",\n    \"is\": \"is not\",\n    \"is not\": \"is\",\n    \"<\": \">=\",\n    \"<=\": \">\",\n    \">\": \"<=\",\n    \">=\": \"<\",\n}\n"
  },
  {
    "path": "mypy/options.py",
    "content": "from __future__ import annotations\n\nimport pprint\nimport re\nimport sys\nimport sysconfig\nfrom collections.abc import Callable\nfrom re import Pattern\nfrom typing import Any, Final\n\nfrom librt.internal import WriteBuffer, write_bool, write_str\n\nfrom mypy import defaults\nfrom mypy.errorcodes import ErrorCode, error_codes\nfrom mypy.util import get_class_descriptors, replace_object_state\n\n\nclass BuildType:\n    STANDARD: Final = 0\n    MODULE: Final = 1\n    PROGRAM_TEXT: Final = 2\n\n\nPER_MODULE_OPTIONS: Final = {\n    # Please keep this list sorted\n    \"allow_redefinition_old\",\n    \"allow_redefinition_new\",\n    \"allow_untyped_globals\",\n    \"always_false\",\n    \"always_true\",\n    \"check_untyped_defs\",\n    \"debug_cache\",\n    \"disable_error_code\",\n    \"disabled_error_codes\",\n    \"disallow_any_decorated\",\n    \"disallow_any_explicit\",\n    \"disallow_any_expr\",\n    \"disallow_any_generics\",\n    \"disallow_any_unimported\",\n    \"disallow_incomplete_defs\",\n    \"disallow_subclassing_any\",\n    \"disallow_untyped_calls\",\n    \"disallow_untyped_decorators\",\n    \"disallow_untyped_defs\",\n    \"enable_error_code\",\n    \"enabled_error_codes\",\n    \"extra_checks\",\n    \"follow_imports_for_stubs\",\n    \"follow_imports\",\n    \"follow_untyped_imports\",\n    \"ignore_errors\",\n    \"ignore_missing_imports\",\n    \"implicit_optional\",\n    \"implicit_reexport\",\n    \"local_partial_types\",\n    \"mypyc\",\n    \"strict_concatenate\",\n    \"strict_equality\",\n    \"strict_equality_for_none\",\n    \"strict_optional\",\n    \"warn_no_return\",\n    \"warn_return_any\",\n    \"warn_unreachable\",\n    \"warn_unused_ignores\",\n}\n\nOPTIONS_AFFECTING_CACHE: Final = (\n    PER_MODULE_OPTIONS\n    | {\n        \"platform\",\n        \"bazel\",\n        \"native_parser\",\n        \"old_type_inference\",\n        \"plugins\",\n        \"disable_bytearray_promotion\",\n        \"disable_memoryview_promotion\",\n        \"strict_bytes\",\n        \"fixed_format_cache\",\n        \"untyped_calls_exclude\",\n        \"enable_incomplete_feature\",\n    }\n) - {\"debug_cache\"}\n\n# OPTIONS_AFFECTING_CACHE without \"platform\", as a sorted tuple for fast iteration.\n# \"platform\" is handled separately in options_snapshot().\nOPTIONS_AFFECTING_CACHE_NO_PLATFORM: Final = tuple(sorted(OPTIONS_AFFECTING_CACHE - {\"platform\"}))\n\n# Features that are currently (or were recently) incomplete/experimental\nTYPE_VAR_TUPLE: Final = \"TypeVarTuple\"\nUNPACK: Final = \"Unpack\"\nPRECISE_TUPLE_TYPES: Final = \"PreciseTupleTypes\"\nNEW_GENERIC_SYNTAX: Final = \"NewGenericSyntax\"\nINLINE_TYPEDDICT: Final = \"InlineTypedDict\"\nTYPE_FORM: Final = \"TypeForm\"\nINCOMPLETE_FEATURES: Final = frozenset((PRECISE_TUPLE_TYPES, INLINE_TYPEDDICT, TYPE_FORM))\nCOMPLETE_FEATURES: Final = frozenset((TYPE_VAR_TUPLE, UNPACK, NEW_GENERIC_SYNTAX))\n\n\nclass Options:\n    \"\"\"Options collected from flags.\"\"\"\n\n    def __init__(self) -> None:\n        # Cache for clone_for_module()\n        self._per_module_cache: dict[str, Options] | None = None\n\n        # -- build options --\n        self.build_type = BuildType.STANDARD\n        self.python_version: tuple[int, int] = sys.version_info[:2]\n        # The executable used to search for PEP 561 packages. If this is None,\n        # then mypy does not search for PEP 561 packages.\n        self.python_executable: str | None = sys.executable\n\n        # When cross compiling to emscripten, we need to rely on MACHDEP because\n        # sys.platform is the host build platform, not emscripten.\n        MACHDEP = sysconfig.get_config_var(\"MACHDEP\")\n        if MACHDEP == \"emscripten\":\n            self.platform = MACHDEP\n        else:\n            self.platform = sys.platform\n\n        self.custom_typing_module: str | None = None\n        self.custom_typeshed_dir: str | None = None\n        # The abspath() version of the above, we compute it once as an optimization.\n        self.abs_custom_typeshed_dir: str | None = None\n        self.mypy_path: list[str] = []\n        self.report_dirs: dict[str, str] = {}\n        # Show errors in PEP 561 packages/site-packages modules\n        self.no_silence_site_packages = False\n        self.no_site_packages = False\n        self.ignore_missing_imports = False\n        # Is ignore_missing_imports set in a per-module section\n        self.ignore_missing_imports_per_module = False\n        # Typecheck modules without stubs or py.typed marker\n        self.follow_untyped_imports = False\n        self.follow_imports = \"normal\"  # normal|silent|skip|error\n        # Whether to respect the follow_imports setting even for stub files.\n        # Intended to be used for disabling specific stubs.\n        self.follow_imports_for_stubs = False\n        # PEP 420 namespace packages\n        # This allows definitions of packages without __init__.py and allows packages to span\n        # multiple directories. This flag affects both import discovery and the association of\n        # input files/modules/packages to the relevant file and fully qualified module name.\n        self.namespace_packages = True\n        # Use current directory and MYPYPATH to determine fully qualified module names of files\n        # passed by automatically considering their subdirectories as packages. This is only\n        # relevant if namespace packages are enabled, since otherwise examining __init__.py's is\n        # sufficient to determine module names for files. As a possible alternative, add a single\n        # top-level __init__.py to your packages.\n        self.explicit_package_bases = False\n        # File names, directory names or subpaths to avoid checking\n        self.exclude: list[str] = []\n        self.exclude_gitignore: bool = False\n\n        # disallow_any options\n        self.disallow_any_generics = False\n        self.disallow_any_unimported = False\n        self.disallow_any_expr = False\n        self.disallow_any_decorated = False\n        self.disallow_any_explicit = False\n\n        # Disallow calling untyped functions from typed ones\n        self.disallow_untyped_calls = False\n\n        # Always allow untyped calls for function coming from modules/packages\n        # in this list (each item effectively acts as a prefix match)\n        self.untyped_calls_exclude: list[str] = []\n\n        # Disallow defining untyped (or incompletely typed) functions\n        self.disallow_untyped_defs = False\n\n        # Disallow defining incompletely typed functions\n        self.disallow_incomplete_defs = False\n\n        # Type check unannotated functions\n        self.check_untyped_defs = False\n\n        # Disallow decorating typed functions with untyped decorators\n        self.disallow_untyped_decorators = False\n\n        # Disallow subclassing values of type 'Any'\n        self.disallow_subclassing_any = False\n\n        # Also check typeshed for missing annotations\n        self.warn_incomplete_stub = False\n\n        # Warn about casting an expression to its inferred type\n        self.warn_redundant_casts = False\n\n        # Warn about falling off the end of a function returning non-None\n        self.warn_no_return = True\n\n        # Warn about returning objects of type Any when the function is\n        # declared with a precise type\n        self.warn_return_any = False\n\n        # Report importing or using deprecated features as errors instead of notes.\n        self.report_deprecated_as_note = False\n\n        # Allow deprecated calls from function coming from modules/packages\n        # in this list (each item effectively acts as a prefix match)\n        self.deprecated_calls_exclude: list[str] = []\n\n        # Warn about unused '# type: ignore' comments\n        self.warn_unused_ignores = False\n\n        # Warn about unused '[mypy-<pattern>]'  or '[[tool.mypy.overrides]]' config sections\n        self.warn_unused_configs = False\n\n        # Files in which to ignore all non-fatal errors\n        self.ignore_errors = False\n\n        # Apply strict None checking\n        self.strict_optional = True\n\n        # Show \"note: In function \"foo\":\" messages.\n        self.show_error_context = False\n\n        # Use nicer output (when possible).\n        self.color_output = True\n        self.error_summary = True\n\n        # Assume arguments with default values of None are Optional\n        self.implicit_optional = False\n\n        # Don't re-export names unless they are imported with `from ... as ...`\n        self.implicit_reexport = True\n\n        # Suppress toplevel errors caused by missing annotations\n        self.allow_untyped_globals = False\n\n        # Allow variable to be redefined with an arbitrary type in the same block\n        # and the same nesting level as the initialization\n        self.allow_redefinition_old = False\n\n        # Allow flexible variable redefinition with an arbitrary type, in different\n        # blocks and at different nesting levels\n        self.allow_redefinition_new = False\n\n        # Prohibit equality, identity, and container checks for non-overlapping types.\n        # This makes 1 == '1', 1 in ['1'], and 1 is '1' errors.\n        self.strict_equality = False\n\n        # Extend the logic of `strict_equality` to comparisons with `None`.\n        self.strict_equality_for_none = False\n\n        # Disable treating bytearray and memoryview as subtypes of bytes\n        self.strict_bytes = False\n\n        # Deprecated, use extra_checks instead.\n        self.strict_concatenate = False\n\n        # Enable additional checks that are technically correct but impractical.\n        self.extra_checks = False\n\n        # Report an error for any branches inferred to be unreachable as a result of\n        # type analysis.\n        self.warn_unreachable = False\n\n        # Variable names considered True\n        self.always_true: list[str] = []\n\n        # Variable names considered False\n        self.always_false: list[str] = []\n\n        # Error codes to disable\n        self.disable_error_code: list[str] = []\n        self.disabled_error_codes: set[ErrorCode] = set()\n\n        # Error codes to enable\n        self.enable_error_code: list[str] = []\n        self.enabled_error_codes: set[ErrorCode] = set()\n\n        # Use script name instead of __main__\n        self.scripts_are_modules = False\n\n        # Config file name\n        self.config_file: str | None = None\n\n        # A filename containing a JSON mapping from filenames to\n        # mtime/size/hash arrays, used to avoid having to recalculate\n        # source hashes as often.\n        self.quickstart_file: str | None = None\n\n        # A comma-separated list of files/directories for mypy to type check;\n        # supports globbing\n        self.files: list[str] | None = None\n\n        # A list of packages for mypy to type check\n        self.packages: list[str] | None = None\n\n        # A list of modules for mypy to type check\n        self.modules: list[str] | None = None\n\n        # Write junit.xml to given file\n        self.junit_xml: str | None = None\n\n        self.junit_format: str = \"global\"  # global|per_file\n\n        # Caching and incremental checking options\n        self.incremental = True\n        self.cache_dir = defaults.CACHE_DIR\n        self.sqlite_cache = True\n        self.fixed_format_cache = True\n        self.debug_cache = False\n        self.skip_version_check = False\n        self.skip_cache_mtime_checks = False\n        self.fine_grained_incremental = False\n        # Include fine-grained dependencies in written cache files\n        self.cache_fine_grained = False\n        # Read cache files in fine-grained incremental mode (cache must include dependencies)\n        self.use_fine_grained_cache = False\n\n        # Run tree.serialize() even if cache generation is disabled\n        self.debug_serialize = False\n\n        # Tune certain behaviors when being used as a front-end to mypyc. Set per-module\n        # in modules being compiled. Not in the config file or command line.\n        self.mypyc = False\n\n        # An internal flag to modify some type-checking logic while\n        # running inspections (e.g. don't expand function definitions).\n        # Not in the config file or command line.\n        self.inspections = False\n\n        # Disable the memory optimization of freeing ASTs when\n        # possible. This isn't exposed as a command line option\n        # because it is intended for software integrating with\n        # mypy. (Like mypyc.)\n        self.preserve_asts = False\n\n        # If True, function and class docstrings will be extracted and retained.\n        # This isn't exposed as a command line option\n        # because it is intended for software integrating with\n        # mypy. (Like stubgen.)\n        self.include_docstrings = False\n\n        # Paths of user plugins\n        self.plugins: list[str] = []\n\n        # Per-module options (raw)\n        self.per_module_options: dict[str, dict[str, object]] = {}\n        self._glob_options: list[tuple[str, Pattern[str]]] = []\n        self.unused_configs: set[str] = set()\n\n        # -- development options --\n        self.verbosity = 0  # More verbose messages (for troubleshooting)\n        self.pdb = False\n        self.show_traceback = False\n        self.raise_exceptions = False\n        self.dump_type_stats = False\n        self.dump_inference_stats = False\n        self.dump_build_stats = False\n        self.enable_incomplete_feature: list[str] = []\n        self.timing_stats: str | None = None\n        self.line_checking_stats: str | None = None\n\n        # -- test options --\n        # Stop after the semantic analysis phase\n        self.semantic_analysis_only = False\n\n        # Use stub builtins fixtures to speed up tests\n        self.use_builtins_fixtures = False\n\n        # This should only be set when running certain mypy tests.\n        # Use this sparingly to avoid tests diverging from non-test behavior.\n        self.test_env = False\n\n        # -- experimental options --\n        self.num_workers: int = 0\n        self.shadow_file: list[list[str]] | None = None\n        self.show_column_numbers: bool = False\n        self.show_error_end: bool = False\n        self.hide_error_codes = False\n        self.show_error_code_links = False\n        # This is an internal-only flag to simplify migrating test output.\n        self.reveal_verbose_types = False\n        # Use soft word wrap and show trimmed source snippets with error location markers.\n        self.pretty = False\n        self.dump_graph = False\n        self.dump_deps = False\n        self.logical_deps = False\n        # If True, partial types can't span a module top level and a function\n        self.local_partial_types = False\n        # If True, use the native parser (experimental)\n        self.native_parser = False\n        # Some behaviors are changed when using Bazel (https://bazel.build).\n        self.bazel = False\n        # If True, export inferred types for all expressions as BuildResult.types\n        self.export_types = False\n        # List of package roots -- directories under these are packages even\n        # if they don't have __init__.py.\n        self.package_root: list[str] = []\n        self.cache_map: dict[str, tuple[str, str]] = {}\n        # Don't properly free objects on exit, just kill the current process.\n        self.fast_exit = True\n        # fast path for finding modules from source set\n        self.fast_module_lookup = False\n        # Allow empty function bodies even if it is not safe, used for testing only.\n        self.allow_empty_bodies = False\n        # Used to transform source code before parsing if not None\n        # TODO: Make the type precise (AnyStr -> AnyStr)\n        self.transform_source: Callable[[Any], Any] | None = None\n        # Print full path to each file in the report.\n        self.show_absolute_path: bool = False\n        # Install missing stub packages if True\n        self.install_types = False\n        # Install missing stub packages in non-interactive mode (don't prompt for\n        # confirmation, and don't show any errors)\n        self.non_interactive = False\n        # When we encounter errors that may cause many additional errors,\n        # skip most errors after this many messages have been reported.\n        # -1 means unlimited.\n        self.many_errors_threshold = defaults.MANY_ERRORS_THRESHOLD\n        # Disable new type inference algorithm.\n        self.old_type_inference = False\n        # Disable expression cache (for debugging).\n        self.disable_expression_cache = False\n        # Export line-level, limited, fine-grained dependency information in cache data\n        # (undocumented feature).\n        self.export_ref_info = False\n        # Treat special methods as being implicitly positional-only.\n        # Set to False when running stubtest.\n        self.pos_only_special_methods = True\n\n        self.disable_bytearray_promotion = False\n        self.disable_memoryview_promotion = False\n\n        # Sets custom output format\n        self.output: str | None = None\n\n        # Output html file for mypyc -a\n        self.mypyc_annotation_file: str | None = None\n        # Skip writing C output files, but perform all other steps of a build (allows\n        # preserving manual tweaks to generated C file)\n        self.mypyc_skip_c_generation = False\n\n    def use_star_unpack(self) -> bool:\n        return self.python_version >= (3, 11) or not self.reveal_verbose_types\n\n    def snapshot(self) -> dict[str, object]:\n        \"\"\"Produce a comparable snapshot of this Option\"\"\"\n        # Under mypyc, we don't have a __dict__, so we need to do worse things.\n        d = dict(getattr(self, \"__dict__\", ()))\n        for k in get_class_descriptors(Options):\n            if hasattr(self, k):\n                d[k] = getattr(self, k)\n        # Remove private attributes from snapshot\n        d = {k: v for k, v in d.items() if not k.startswith(\"_\")}\n        return d\n\n    def __repr__(self) -> str:\n        return f\"Options({pprint.pformat(self.snapshot())})\"\n\n    def process_error_codes(self, *, error_callback: Callable[[str], Any]) -> None:\n        \"\"\"Process `--enable-error-code` and `--disable-error-code` flags.\"\"\"\n        disabled_code_names = set(self.disable_error_code)\n        enabled_code_names = set(self.enable_error_code)\n\n        valid_error_code_names = set(error_codes.keys())\n\n        invalid_code_names_here = (\n            enabled_code_names | disabled_code_names\n        ) - valid_error_code_names\n        if invalid_code_names_here:\n            error_callback(f\"Invalid error code(s): {', '.join(sorted(invalid_code_names_here))}\")\n\n        self.disabled_error_codes |= {error_codes[code] for code in disabled_code_names}\n        self.enabled_error_codes |= {error_codes[code] for code in enabled_code_names}\n\n        # Enabling an error code always overrides disabling\n        self.disabled_error_codes -= self.enabled_error_codes\n\n    def process_incomplete_features(\n        self, *, error_callback: Callable[[str], Any], warning_callback: Callable[[str], Any]\n    ) -> None:\n        # Validate incomplete features.\n        for feature in self.enable_incomplete_feature:\n            if feature not in INCOMPLETE_FEATURES | COMPLETE_FEATURES:\n                error_callback(f\"Unknown incomplete feature: {feature}\")\n            if feature in COMPLETE_FEATURES:\n                warning_callback(f\"Warning: {feature} is already enabled by default\")\n\n    def process_strict_bytes(self) -> None:\n        # Sync `--strict-bytes` and `--disable-{bytearray,memoryview}-promotion`\n        if self.strict_bytes:\n            # backwards compatibility\n            self.disable_bytearray_promotion = True\n            self.disable_memoryview_promotion = True\n        elif self.disable_bytearray_promotion and self.disable_memoryview_promotion:\n            # forwards compatibility\n            self.strict_bytes = True\n\n    def apply_changes(self, changes: dict[str, object]) -> Options:\n        # Note: effects of this method *must* be idempotent.\n        new_options = Options()\n        # Under mypyc, we don't have a __dict__, so we need to do worse things.\n        replace_object_state(new_options, self, copy_dict=True)\n        for key, value in changes.items():\n            setattr(new_options, key, value)\n        if changes.get(\"ignore_missing_imports\"):\n            # This is the only option for which a per-module and a global\n            # option sometimes beheave differently.\n            new_options.ignore_missing_imports_per_module = True\n\n        # These two act as overrides, so apply them when cloning.\n        # Similar to global codes enabling overrides disabling, so we start from latter.\n        new_options.disabled_error_codes = self.disabled_error_codes.copy()\n        new_options.enabled_error_codes = self.enabled_error_codes.copy()\n        for code_str in new_options.disable_error_code:\n            code = error_codes[code_str]\n            new_options.disabled_error_codes.add(code)\n            new_options.enabled_error_codes.discard(code)\n        for code_str in new_options.enable_error_code:\n            code = error_codes[code_str]\n            new_options.enabled_error_codes.add(code)\n            new_options.disabled_error_codes.discard(code)\n        return new_options\n\n    def compare_stable(self, other_snapshot: dict[str, object]) -> bool:\n        \"\"\"Compare options in a way that is stable for snapshot() -> apply_changes() roundtrip.\n\n        This is needed because apply_changes() has non-trivial effects for some flags, so\n        Options().apply_changes(options.snapshot()) may result in a (slightly) different object.\n        \"\"\"\n        return (\n            Options().apply_changes(self.snapshot()).snapshot()\n            == Options().apply_changes(other_snapshot).snapshot()\n        )\n\n    def build_per_module_cache(self) -> None:\n        self._per_module_cache = {}\n\n        # Config precedence is as follows:\n        #  1. Concrete section names: foo.bar.baz\n        #  2. \"Unstructured\" glob patterns: foo.*.baz, in the order\n        #     they appear in the file (last wins)\n        #  3. \"Well-structured\" wildcard patterns: foo.bar.*, in specificity order.\n\n        # Since structured configs inherit from structured configs above them in the hierarchy,\n        # we need to process per-module configs in a careful order.\n        # We have to process foo.* before foo.bar.* before foo.bar,\n        # and we need to apply *.bar to foo.bar but not to foo.bar.*.\n        # To do this, process all well-structured glob configs before non-glob configs and\n        # exploit the fact that foo.* sorts earlier ASCIIbetically (unicodebetically?)\n        # than foo.bar.*.\n        # (A section being \"processed last\" results in its config \"winning\".)\n        # Unstructured glob configs are stored and are all checked for each module.\n        unstructured_glob_keys = [k for k in self.per_module_options.keys() if \"*\" in k[:-1]]\n        structured_keys = [k for k in self.per_module_options.keys() if \"*\" not in k[:-1]]\n        wildcards = sorted(k for k in structured_keys if k.endswith(\".*\"))\n        concrete = [k for k in structured_keys if not k.endswith(\".*\")]\n\n        for glob in unstructured_glob_keys:\n            self._glob_options.append((glob, self.compile_glob(glob)))\n\n        # We (for ease of implementation) treat unstructured glob\n        # sections as used if any real modules use them or if any\n        # concrete config sections use them. This means we need to\n        # track which get used while constructing.\n        self.unused_configs = set(unstructured_glob_keys)\n\n        for key in wildcards + concrete:\n            # Find what the options for this key would be, just based\n            # on inheriting from parent configs.\n            options = self.clone_for_module(key)\n            # And then update it with its per-module options.\n            self._per_module_cache[key] = options.apply_changes(self.per_module_options[key])\n\n        # Add the more structured sections into unused configs, since\n        # they only count as used if actually used by a real module.\n        self.unused_configs.update(structured_keys)\n\n    def clone_for_module(self, module: str) -> Options:\n        \"\"\"Create an Options object that incorporates per-module options.\n\n        NOTE: Once this method is called all Options objects should be\n        considered read-only, else the caching might be incorrect.\n        \"\"\"\n        if self._per_module_cache is None:\n            self.build_per_module_cache()\n        assert self._per_module_cache is not None\n\n        # If the module just directly has a config entry, use it.\n        if module in self._per_module_cache:\n            self.unused_configs.discard(module)\n            return self._per_module_cache[module]\n\n        # If not, search for glob paths at all the parents. So if we are looking for\n        # options for foo.bar.baz, we search foo.bar.baz.*, foo.bar.*, foo.*,\n        # in that order, looking for an entry.\n        # This is technically quadratic in the length of the path, but module paths\n        # don't actually get all that long.\n        options = self\n        path = module.split(\".\")\n        for i in range(len(path), 0, -1):\n            key = \".\".join(path[:i] + [\"*\"])\n            if key in self._per_module_cache:\n                self.unused_configs.discard(key)\n                options = self._per_module_cache[key]\n                break\n\n        # OK and *now* we need to look for unstructured glob matches.\n        # We only do this for concrete modules, not structured wildcards.\n        if not module.endswith(\".*\"):\n            for key, pattern in self._glob_options:\n                if pattern.match(module):\n                    self.unused_configs.discard(key)\n                    options = options.apply_changes(self.per_module_options[key])\n\n        # We could update the cache to directly point to modules once\n        # they have been looked up, but in testing this made things\n        # slower and not faster, so we don't bother.\n\n        return options\n\n    def compile_glob(self, s: str) -> Pattern[str]:\n        # Compile one of the glob patterns to a regex so that '.*' can\n        # match *zero or more* module sections. This means we compile\n        # '.*' into '(\\..*)?'.\n        parts = s.split(\".\")\n        expr = re.escape(parts[0]) if parts[0] != \"*\" else \".*\"\n        for part in parts[1:]:\n            expr += re.escape(\".\" + part) if part != \"*\" else r\"(\\..*)?\"\n        return re.compile(expr + \"\\\\Z\")\n\n    def select_options_affecting_cache(self) -> tuple[str, list[object]]:\n        \"\"\"Return (platform, [values...]) for options that affect the cache.\n\n        The list contains values for OPTIONS_AFFECTING_CACHE_NO_PLATFORM\n        in sorted attribute name order. Keys are omitted since the cache\n        is invalidated when the mypy version changes, and keys are constant\n        on any specific mypy version.\n        \"\"\"\n        result: list[object] = []\n        for opt in OPTIONS_AFFECTING_CACHE_NO_PLATFORM:\n            val = getattr(self, opt)\n            if opt in (\"disabled_error_codes\", \"enabled_error_codes\"):\n                val = sorted([code.code for code in val])\n            result.append(val)\n        return self.platform, result\n\n    def dep_import_options(self) -> bytes:\n        \"\"\"Return opaque bytes with options that can affect dependent modules as well.\n\n        The value can be compared for equality to detect changed options.\n        \"\"\"\n        buf = WriteBuffer()\n        write_bool(buf, self.ignore_missing_imports)\n        write_str(buf, self.follow_imports)\n        write_bool(buf, self.follow_imports_for_stubs)\n        return buf.getvalue()\n"
  },
  {
    "path": "mypy/parse.py",
    "content": "from __future__ import annotations\n\nimport os\nimport re\n\nfrom librt.internal import ReadBuffer\n\nfrom mypy import errorcodes as codes\nfrom mypy.cache import read_int\nfrom mypy.errors import Errors\nfrom mypy.nodes import FileRawData, MypyFile\nfrom mypy.options import Options\n\n\ndef parse(\n    source: str | bytes,\n    fnam: str,\n    module: str | None,\n    errors: Errors,\n    options: Options,\n    raise_on_error: bool = False,\n    imports_only: bool = False,\n) -> MypyFile:\n    \"\"\"Parse a source file, without doing any semantic analysis.\n\n    Return the parse tree. If errors is not provided, raise ParseError\n    on failure. Otherwise, use the errors object to report parse errors.\n\n    The python_version (major, minor) option determines the Python syntax variant.\n    \"\"\"\n    if options.native_parser:\n        # Native parser only works with actual files on disk\n        # Fall back to fastparse for in-memory source or non-existent files\n        if os.path.exists(fnam):\n            import mypy.nativeparse\n\n            ignore_errors = options.ignore_errors or fnam in errors.ignored_files\n            # If errors are ignored, we can drop many function bodies to speed up type checking.\n            strip_function_bodies = ignore_errors and not options.preserve_asts\n\n            errors.set_file(fnam, module, options=options)\n            tree, parse_errors, type_ignores = mypy.nativeparse.native_parse(\n                fnam,\n                options,\n                skip_function_bodies=strip_function_bodies,\n                imports_only=imports_only,\n            )\n            # Convert type ignores list to dict\n            tree.ignored_lines = dict(type_ignores)\n            # Set is_stub based on file extension\n            tree.is_stub = fnam.endswith(\".pyi\")\n            # Note: tree.imports is populated directly by native_parse with deserialized\n            # import metadata, so we don't need to collect imports via AST traversal\n\n            # Report parse errors\n            for error in parse_errors:\n                message = error[\"message\"]\n                # Standardize error message by capitalizing the first word\n                message = re.sub(r\"^(\\s*\\w)\", lambda m: m.group(1).upper(), message)\n                # Respect blocker status from error, default to True for syntax errors\n                is_blocker = error.get(\"blocker\", True)\n                error_code = error.get(\"code\")\n                if error_code is None:\n                    error_code = codes.SYNTAX\n                else:\n                    # Fallback to [syntax] for backwards compatibility.\n                    error_code = codes.error_codes.get(error_code) or codes.SYNTAX\n                errors.report(\n                    error[\"line\"], error[\"column\"], message, blocker=is_blocker, code=error_code\n                )\n            if raise_on_error and errors.is_errors():\n                errors.raise_error()\n            return tree\n        # Fall through to fastparse for non-existent files\n\n    assert not imports_only\n    if options.transform_source is not None:\n        source = options.transform_source(source)\n    import mypy.fastparse\n\n    tree = mypy.fastparse.parse(source, fnam=fnam, module=module, errors=errors, options=options)\n    if raise_on_error and errors.is_errors():\n        errors.raise_error()\n    return tree\n\n\ndef load_from_raw(\n    fnam: str, module: str | None, raw_data: FileRawData, errors: Errors, options: Options\n) -> MypyFile:\n    \"\"\"Load AST from parsed binary data.\n\n    This essentially replicates parse() above but expects FileRawData instead of actually\n    parsing the source code in the file.\n    \"\"\"\n    from mypy.nativeparse import State, deserialize_imports, read_statements\n\n    # This part mimics the logic in native_parse().\n    data = ReadBuffer(raw_data.defs)\n    n = read_int(data)\n    state = State(options)\n    defs = read_statements(state, data, n)\n    imports = deserialize_imports(raw_data.imports)\n\n    tree = MypyFile(defs, imports)\n    tree.path = fnam\n    tree.ignored_lines = raw_data.ignored_lines\n    tree.is_partial_stub_package = raw_data.is_partial_stub_package\n    tree.uses_template_strings = raw_data.uses_template_strings\n    tree.is_stub = fnam.endswith(\".pyi\")\n\n    # Report parse errors, this replicates the logic in parse().\n    all_errors = raw_data.raw_errors + state.errors\n    errors.set_file(fnam, module, options=options)\n    for error in all_errors:\n        message = error[\"message\"]\n        message = re.sub(r\"^(\\s*\\w)\", lambda m: m.group(1).upper(), message)\n        is_blocker = error.get(\"blocker\", True)\n        error_code = error.get(\"code\")\n        if error_code is None:\n            error_code = codes.SYNTAX\n        else:\n            error_code = codes.error_codes.get(error_code) or codes.SYNTAX\n        # Note we never raise in this function, so it should not be called in coordinator.\n        errors.report(error[\"line\"], error[\"column\"], message, blocker=is_blocker, code=error_code)\n    return tree\n"
  },
  {
    "path": "mypy/partially_defined.py",
    "content": "from __future__ import annotations\n\nfrom enum import Enum\n\nfrom mypy import checker, errorcodes\nfrom mypy.messages import MessageBuilder\nfrom mypy.nodes import (\n    AssertStmt,\n    AssignmentExpr,\n    AssignmentStmt,\n    BreakStmt,\n    ClassDef,\n    Context,\n    ContinueStmt,\n    DictionaryComprehension,\n    Expression,\n    ExpressionStmt,\n    ForStmt,\n    FuncDef,\n    FuncItem,\n    GeneratorExpr,\n    GlobalDecl,\n    IfStmt,\n    Import,\n    ImportFrom,\n    LambdaExpr,\n    ListExpr,\n    Lvalue,\n    MatchStmt,\n    MypyFile,\n    NameExpr,\n    NonlocalDecl,\n    RaiseStmt,\n    ReturnStmt,\n    StarExpr,\n    SymbolTable,\n    TryStmt,\n    TupleExpr,\n    TypeAliasStmt,\n    WhileStmt,\n    WithStmt,\n    implicit_module_attrs,\n)\nfrom mypy.options import Options\nfrom mypy.patterns import AsPattern, StarredPattern\nfrom mypy.reachability import ALWAYS_TRUE, infer_pattern_value\nfrom mypy.traverser import ExtendedTraverserVisitor\nfrom mypy.types import Type, UninhabitedType, get_proper_type\n\n\nclass BranchState:\n    \"\"\"BranchState contains information about variable definition at the end of a branching statement.\n    `if` and `match` are examples of branching statements.\n\n    `may_be_defined` contains variables that were defined in only some branches.\n    `must_be_defined` contains variables that were defined in all branches.\n    \"\"\"\n\n    def __init__(\n        self,\n        must_be_defined: set[str] | None = None,\n        may_be_defined: set[str] | None = None,\n        skipped: bool = False,\n    ) -> None:\n        if may_be_defined is None:\n            may_be_defined = set()\n        if must_be_defined is None:\n            must_be_defined = set()\n\n        self.may_be_defined = set(may_be_defined)\n        self.must_be_defined = set(must_be_defined)\n        self.skipped = skipped\n\n    def copy(self) -> BranchState:\n        return BranchState(\n            must_be_defined=set(self.must_be_defined),\n            may_be_defined=set(self.may_be_defined),\n            skipped=self.skipped,\n        )\n\n\nclass BranchStatement:\n    def __init__(self, initial_state: BranchState | None = None) -> None:\n        if initial_state is None:\n            initial_state = BranchState()\n        self.initial_state = initial_state\n        self.branches: list[BranchState] = [\n            BranchState(\n                must_be_defined=self.initial_state.must_be_defined,\n                may_be_defined=self.initial_state.may_be_defined,\n            )\n        ]\n\n    def copy(self) -> BranchStatement:\n        result = BranchStatement(self.initial_state)\n        result.branches = [b.copy() for b in self.branches]\n        return result\n\n    def next_branch(self) -> None:\n        self.branches.append(\n            BranchState(\n                must_be_defined=self.initial_state.must_be_defined,\n                may_be_defined=self.initial_state.may_be_defined,\n            )\n        )\n\n    def record_definition(self, name: str) -> None:\n        assert len(self.branches) > 0\n        self.branches[-1].must_be_defined.add(name)\n        self.branches[-1].may_be_defined.discard(name)\n\n    def delete_var(self, name: str) -> None:\n        assert len(self.branches) > 0\n        self.branches[-1].must_be_defined.discard(name)\n        self.branches[-1].may_be_defined.discard(name)\n\n    def record_nested_branch(self, state: BranchState) -> None:\n        assert len(self.branches) > 0\n        current_branch = self.branches[-1]\n        if state.skipped:\n            current_branch.skipped = True\n            return\n        current_branch.must_be_defined.update(state.must_be_defined)\n        current_branch.may_be_defined.update(state.may_be_defined)\n        current_branch.may_be_defined.difference_update(current_branch.must_be_defined)\n\n    def skip_branch(self) -> None:\n        assert len(self.branches) > 0\n        self.branches[-1].skipped = True\n\n    def is_possibly_undefined(self, name: str) -> bool:\n        assert len(self.branches) > 0\n        return name in self.branches[-1].may_be_defined\n\n    def is_undefined(self, name: str) -> bool:\n        assert len(self.branches) > 0\n        branch = self.branches[-1]\n        return name not in branch.may_be_defined and name not in branch.must_be_defined\n\n    def is_defined_in_a_branch(self, name: str) -> bool:\n        assert len(self.branches) > 0\n        for b in self.branches:\n            if name in b.must_be_defined or name in b.may_be_defined:\n                return True\n        return False\n\n    def done(self) -> BranchState:\n        # First, compute all vars, including skipped branches. We include skipped branches\n        # because our goal is to capture all variables that semantic analyzer would\n        # consider defined.\n        all_vars = set()\n        for b in self.branches:\n            all_vars.update(b.may_be_defined)\n            all_vars.update(b.must_be_defined)\n        # For the rest of the things, we only care about branches that weren't skipped.\n        non_skipped_branches = [b for b in self.branches if not b.skipped]\n        if non_skipped_branches:\n            must_be_defined = non_skipped_branches[0].must_be_defined\n            for b in non_skipped_branches[1:]:\n                must_be_defined.intersection_update(b.must_be_defined)\n        else:\n            must_be_defined = set()\n        # Everything that wasn't defined in all branches but was defined\n        # in at least one branch should be in `may_be_defined`!\n        may_be_defined = all_vars.difference(must_be_defined)\n        return BranchState(\n            must_be_defined=must_be_defined,\n            may_be_defined=may_be_defined,\n            skipped=len(non_skipped_branches) == 0,\n        )\n\n\nclass ScopeType(Enum):\n    Global = 1\n    Class = 2\n    Func = 3\n    Generator = 4\n\n\nclass Scope:\n    def __init__(self, stmts: list[BranchStatement], scope_type: ScopeType) -> None:\n        self.branch_stmts: list[BranchStatement] = stmts\n        self.scope_type = scope_type\n        self.undefined_refs: dict[str, set[NameExpr]] = {}\n\n    def copy(self) -> Scope:\n        result = Scope([s.copy() for s in self.branch_stmts], self.scope_type)\n        result.undefined_refs = self.undefined_refs.copy()\n        return result\n\n    def record_undefined_ref(self, o: NameExpr) -> None:\n        if o.name not in self.undefined_refs:\n            self.undefined_refs[o.name] = set()\n        self.undefined_refs[o.name].add(o)\n\n    def pop_undefined_ref(self, name: str) -> set[NameExpr]:\n        return self.undefined_refs.pop(name, set())\n\n\nclass DefinedVariableTracker:\n    \"\"\"DefinedVariableTracker manages the state and scope for the UndefinedVariablesVisitor.\"\"\"\n\n    def __init__(self) -> None:\n        # There's always at least one scope. Within each scope, there's at least one \"global\" BranchingStatement.\n        self.scopes: list[Scope] = [Scope([BranchStatement()], ScopeType.Global)]\n        # disable_branch_skip is used to disable skipping a branch due to a return/raise/etc. This is useful\n        # in things like try/except/finally statements.\n        self.disable_branch_skip = False\n        self.in_finally = False\n\n    def copy(self) -> DefinedVariableTracker:\n        result = DefinedVariableTracker()\n        result.scopes = [s.copy() for s in self.scopes]\n        result.disable_branch_skip = self.disable_branch_skip\n        result.in_finally = self.in_finally\n        return result\n\n    def _scope(self) -> Scope:\n        assert len(self.scopes) > 0\n        return self.scopes[-1]\n\n    def enter_scope(self, scope_type: ScopeType) -> None:\n        assert len(self._scope().branch_stmts) > 0\n        initial_state = None\n        if scope_type == ScopeType.Generator:\n            # Generators are special because they inherit the outer scope.\n            initial_state = self._scope().branch_stmts[-1].branches[-1]\n        self.scopes.append(Scope([BranchStatement(initial_state)], scope_type))\n\n    def exit_scope(self) -> None:\n        self.scopes.pop()\n\n    def in_scope(self, scope_type: ScopeType) -> bool:\n        return self._scope().scope_type == scope_type\n\n    def start_branch_statement(self) -> None:\n        assert len(self._scope().branch_stmts) > 0\n        self._scope().branch_stmts.append(\n            BranchStatement(self._scope().branch_stmts[-1].branches[-1])\n        )\n\n    def next_branch(self) -> None:\n        assert len(self._scope().branch_stmts) > 1\n        self._scope().branch_stmts[-1].next_branch()\n\n    def end_branch_statement(self) -> None:\n        assert len(self._scope().branch_stmts) > 1\n        result = self._scope().branch_stmts.pop().done()\n        self._scope().branch_stmts[-1].record_nested_branch(result)\n\n    def skip_branch(self) -> None:\n        # Only skip branch if we're outside of \"root\" branch statement.\n        if len(self._scope().branch_stmts) > 1 and not self.disable_branch_skip:\n            self._scope().branch_stmts[-1].skip_branch()\n\n    def record_definition(self, name: str) -> None:\n        assert len(self.scopes) > 0\n        assert len(self.scopes[-1].branch_stmts) > 0\n        self._scope().branch_stmts[-1].record_definition(name)\n\n    def delete_var(self, name: str) -> None:\n        assert len(self.scopes) > 0\n        assert len(self.scopes[-1].branch_stmts) > 0\n        self._scope().branch_stmts[-1].delete_var(name)\n\n    def record_undefined_ref(self, o: NameExpr) -> None:\n        \"\"\"Records an undefined reference. These can later be retrieved via `pop_undefined_ref`.\"\"\"\n        assert len(self.scopes) > 0\n        self._scope().record_undefined_ref(o)\n\n    def pop_undefined_ref(self, name: str) -> set[NameExpr]:\n        \"\"\"If name has previously been reported as undefined, the NameExpr that was called will be returned.\"\"\"\n        assert len(self.scopes) > 0\n        return self._scope().pop_undefined_ref(name)\n\n    def is_possibly_undefined(self, name: str) -> bool:\n        assert len(self._scope().branch_stmts) > 0\n        # A variable is undefined if it's in a set of `may_be_defined` but not in `must_be_defined`.\n        return self._scope().branch_stmts[-1].is_possibly_undefined(name)\n\n    def is_defined_in_different_branch(self, name: str) -> bool:\n        \"\"\"This will return true if a variable is defined in a branch that's not the current branch.\"\"\"\n        assert len(self._scope().branch_stmts) > 0\n        stmt = self._scope().branch_stmts[-1]\n        if not stmt.is_undefined(name):\n            return False\n        for stmt in self._scope().branch_stmts:\n            if stmt.is_defined_in_a_branch(name):\n                return True\n        return False\n\n    def is_undefined(self, name: str) -> bool:\n        assert len(self._scope().branch_stmts) > 0\n        return self._scope().branch_stmts[-1].is_undefined(name)\n\n\nclass Loop:\n    def __init__(self) -> None:\n        self.has_break = False\n        # variables defined in every loop branch with `break`\n        self.break_vars: set[str] | None = None\n\n\nclass PossiblyUndefinedVariableVisitor(ExtendedTraverserVisitor):\n    \"\"\"Detects the following cases:\n    - A variable that's defined only part of the time.\n    - If a variable is used before definition\n\n    An example of a partial definition:\n    if foo():\n        x = 1\n    print(x)  # Error: \"x\" may be undefined.\n\n    Example of a used before definition:\n    x = y\n    y: int = 2\n\n    Note that this code does not detect variables not defined in any of the branches -- that is\n    handled by the semantic analyzer.\n    \"\"\"\n\n    def __init__(\n        self,\n        msg: MessageBuilder,\n        type_map: dict[Expression, Type],\n        options: Options,\n        names: SymbolTable,\n    ) -> None:\n        self.msg = msg\n        self.type_map = type_map\n        self.options = options\n        self.builtins = SymbolTable()\n        builtins_mod = names.get(\"__builtins__\", None)\n        if builtins_mod:\n            assert isinstance(builtins_mod.node, MypyFile)\n            self.builtins = builtins_mod.node.names\n        self.loops: list[Loop] = []\n        self.try_depth = 0\n        self.tracker = DefinedVariableTracker()\n        for name in implicit_module_attrs:\n            self.tracker.record_definition(name)\n\n    def var_used_before_def(self, name: str, context: Context) -> None:\n        if self.msg.errors.is_error_code_enabled(errorcodes.USED_BEFORE_DEF):\n            self.msg.var_used_before_def(name, context)\n\n    def variable_may_be_undefined(self, name: str, context: Context) -> None:\n        if self.msg.errors.is_error_code_enabled(errorcodes.POSSIBLY_UNDEFINED):\n            self.msg.variable_may_be_undefined(name, context)\n\n    def process_definition(self, name: str) -> None:\n        # Was this name previously used? If yes, it's a used-before-definition error.\n        if not self.tracker.in_scope(ScopeType.Class):\n            refs = self.tracker.pop_undefined_ref(name)\n            for ref in refs:\n                if self.loops:\n                    self.variable_may_be_undefined(name, ref)\n                else:\n                    self.var_used_before_def(name, ref)\n        else:\n            # Errors in class scopes are caught by the semantic analyzer.\n            pass\n        self.tracker.record_definition(name)\n\n    def visit_global_decl(self, o: GlobalDecl) -> None:\n        for name in o.names:\n            self.process_definition(name)\n        super().visit_global_decl(o)\n\n    def visit_nonlocal_decl(self, o: NonlocalDecl) -> None:\n        for name in o.names:\n            self.process_definition(name)\n        super().visit_nonlocal_decl(o)\n\n    def process_lvalue(self, lvalue: Lvalue | None) -> None:\n        if isinstance(lvalue, NameExpr):\n            self.process_definition(lvalue.name)\n        elif isinstance(lvalue, StarExpr):\n            self.process_lvalue(lvalue.expr)\n        elif isinstance(lvalue, (ListExpr, TupleExpr)):\n            for item in lvalue.items:\n                self.process_lvalue(item)\n\n    def visit_assignment_stmt(self, o: AssignmentStmt) -> None:\n        for lvalue in o.lvalues:\n            self.process_lvalue(lvalue)\n        super().visit_assignment_stmt(o)\n\n    def visit_assignment_expr(self, o: AssignmentExpr) -> None:\n        o.value.accept(self)\n        self.process_lvalue(o.target)\n\n    def visit_if_stmt(self, o: IfStmt) -> None:\n        for e in o.expr:\n            e.accept(self)\n        self.tracker.start_branch_statement()\n        for b in o.body:\n            if b.is_unreachable:\n                continue\n            b.accept(self)\n            self.tracker.next_branch()\n        if o.unreachable_else:\n            self.tracker.skip_branch()\n        elif o.else_body:\n            if o.else_body.is_unreachable:\n                self.tracker.skip_branch()\n            else:\n                o.else_body.accept(self)\n        self.tracker.end_branch_statement()\n\n    def visit_match_stmt(self, o: MatchStmt) -> None:\n        o.subject.accept(self)\n        self.tracker.start_branch_statement()\n        for i in range(len(o.patterns)):\n            pattern = o.patterns[i]\n            pattern.accept(self)\n            guard = o.guards[i]\n            if guard is not None:\n                guard.accept(self)\n            if not o.bodies[i].is_unreachable:\n                o.bodies[i].accept(self)\n            else:\n                self.tracker.skip_branch()\n            is_catchall = infer_pattern_value(pattern) == ALWAYS_TRUE\n            if not is_catchall:\n                self.tracker.next_branch()\n        self.tracker.end_branch_statement()\n\n    def visit_func_def(self, o: FuncDef) -> None:\n        self.process_definition(o.name)\n        super().visit_func_def(o)\n\n    def visit_func(self, o: FuncItem) -> None:\n        if o.is_dynamic() and not self.options.check_untyped_defs:\n            return\n\n        args = o.arguments or []\n        # Process initializers (defaults) outside the function scope.\n        for arg in args:\n            if arg.initializer is not None:\n                arg.initializer.accept(self)\n\n        self.tracker.enter_scope(ScopeType.Func)\n        for arg in args:\n            self.process_definition(arg.variable.name)\n            super().visit_var(arg.variable)\n        o.body.accept(self)\n        self.tracker.exit_scope()\n\n    def visit_generator_expr(self, o: GeneratorExpr) -> None:\n        self.tracker.enter_scope(ScopeType.Generator)\n        for idx in o.indices:\n            self.process_lvalue(idx)\n        super().visit_generator_expr(o)\n        self.tracker.exit_scope()\n\n    def visit_dictionary_comprehension(self, o: DictionaryComprehension) -> None:\n        self.tracker.enter_scope(ScopeType.Generator)\n        for idx in o.indices:\n            self.process_lvalue(idx)\n        super().visit_dictionary_comprehension(o)\n        self.tracker.exit_scope()\n\n    def visit_for_stmt(self, o: ForStmt) -> None:\n        o.expr.accept(self)\n        self.process_lvalue(o.index)\n        o.index.accept(self)\n        self.tracker.start_branch_statement()\n        loop = Loop()\n        self.loops.append(loop)\n        o.body.accept(self)\n        self.tracker.next_branch()\n        self.tracker.end_branch_statement()\n        if o.else_body is not None:\n            # If the loop has a `break` inside, `else` is executed conditionally.\n            # If the loop doesn't have a `break` either the function will return or\n            # execute the `else`.\n            has_break = loop.has_break\n            if has_break:\n                self.tracker.start_branch_statement()\n                if loop.break_vars is not None:\n                    for bv in loop.break_vars:\n                        self.tracker.record_definition(bv)\n                self.tracker.next_branch()\n            o.else_body.accept(self)\n            if has_break:\n                self.tracker.end_branch_statement()\n        self.loops.pop()\n\n    def visit_return_stmt(self, o: ReturnStmt) -> None:\n        super().visit_return_stmt(o)\n        self.tracker.skip_branch()\n\n    def visit_lambda_expr(self, o: LambdaExpr) -> None:\n        self.tracker.enter_scope(ScopeType.Func)\n        super().visit_lambda_expr(o)\n        self.tracker.exit_scope()\n\n    def visit_assert_stmt(self, o: AssertStmt) -> None:\n        super().visit_assert_stmt(o)\n        if checker.is_false_literal(o.expr):\n            self.tracker.skip_branch()\n\n    def visit_raise_stmt(self, o: RaiseStmt) -> None:\n        super().visit_raise_stmt(o)\n        self.tracker.skip_branch()\n\n    def visit_continue_stmt(self, o: ContinueStmt) -> None:\n        super().visit_continue_stmt(o)\n        self.tracker.skip_branch()\n\n    def visit_break_stmt(self, o: BreakStmt) -> None:\n        super().visit_break_stmt(o)\n        if self.loops:\n            self.loops[-1].has_break = True\n            # Track variables that are definitely defined at the point of break\n            if len(self.tracker._scope().branch_stmts) > 0:\n                branch = self.tracker._scope().branch_stmts[-1].branches[-1]\n                if self.loops[-1].break_vars is None:\n                    self.loops[-1].break_vars = set(branch.must_be_defined)\n                else:\n                    # we only want variables that have been defined in each branch\n                    self.loops[-1].break_vars.intersection_update(branch.must_be_defined)\n        self.tracker.skip_branch()\n\n    def visit_expression_stmt(self, o: ExpressionStmt) -> None:\n        typ = self.type_map.get(o.expr)\n        if typ is None or isinstance(get_proper_type(typ), UninhabitedType):\n            self.tracker.skip_branch()\n        super().visit_expression_stmt(o)\n\n    def visit_try_stmt(self, o: TryStmt) -> None:\n        \"\"\"\n        Note that finding undefined vars in `finally` requires different handling from\n        the rest of the code. In particular, we want to disallow skipping branches due to jump\n        statements in except/else clauses for finally but not for other cases. Imagine a case like:\n        def f() -> int:\n            try:\n                x = 1\n            except:\n                # This jump statement needs to be handled differently depending on whether or\n                # not we're trying to process `finally` or not.\n                return 0\n            finally:\n                # `x` may be undefined here.\n                pass\n            # `x` is always defined here.\n            return x\n        \"\"\"\n        self.try_depth += 1\n        if o.finally_body is not None:\n            # In order to find undefined vars in `finally`, we need to\n            # process try/except with branch skipping disabled. However, for the rest of the code\n            # after finally, we need to process try/except with branch skipping enabled.\n            # Therefore, we need to process try/finally twice.\n            # Because processing is not idempotent, we should make a copy of the tracker.\n            old_tracker = self.tracker.copy()\n            self.tracker.disable_branch_skip = True\n            self.process_try_stmt(o)\n            self.tracker = old_tracker\n        self.process_try_stmt(o)\n        self.try_depth -= 1\n\n    def process_try_stmt(self, o: TryStmt) -> None:\n        \"\"\"\n        Processes try statement decomposing it into the following:\n        if ...:\n            body\n            else_body\n        elif ...:\n            except 1\n        elif ...:\n            except 2\n        else:\n            except n\n        finally\n        \"\"\"\n        self.tracker.start_branch_statement()\n        o.body.accept(self)\n        if o.else_body is not None:\n            o.else_body.accept(self)\n        if len(o.handlers) > 0:\n            assert len(o.handlers) == len(o.vars) == len(o.types)\n            for i in range(len(o.handlers)):\n                self.tracker.next_branch()\n                exc_type = o.types[i]\n                if exc_type is not None:\n                    exc_type.accept(self)\n                var = o.vars[i]\n                if var is not None:\n                    self.process_definition(var.name)\n                    var.accept(self)\n                o.handlers[i].accept(self)\n                if var is not None:\n                    self.tracker.delete_var(var.name)\n        self.tracker.end_branch_statement()\n\n        if o.finally_body is not None:\n            self.tracker.in_finally = True\n            o.finally_body.accept(self)\n            self.tracker.in_finally = False\n\n    def visit_while_stmt(self, o: WhileStmt) -> None:\n        o.expr.accept(self)\n        self.tracker.start_branch_statement()\n        loop = Loop()\n        self.loops.append(loop)\n        o.body.accept(self)\n        has_break = loop.has_break\n        if not checker.is_true_literal(o.expr):\n            # If this is a loop like `while True`, we can consider the body to be\n            # a single branch statement (we're guaranteed that the body is executed at least once).\n            # If not, call next_branch() to make all variables defined there conditional.\n            self.tracker.next_branch()\n        self.tracker.end_branch_statement()\n        if o.else_body is not None:\n            # If the loop has a `break` inside, `else` is executed conditionally.\n            # If the loop doesn't have a `break` either the function will return or\n            # execute the `else`.\n            if has_break:\n                self.tracker.start_branch_statement()\n                self.tracker.next_branch()\n            if o.else_body:\n                o.else_body.accept(self)\n            if has_break:\n                self.tracker.end_branch_statement()\n        self.loops.pop()\n\n    def visit_as_pattern(self, o: AsPattern) -> None:\n        if o.name is not None:\n            self.process_lvalue(o.name)\n        super().visit_as_pattern(o)\n\n    def visit_starred_pattern(self, o: StarredPattern) -> None:\n        if o.capture is not None:\n            self.process_lvalue(o.capture)\n        super().visit_starred_pattern(o)\n\n    def visit_name_expr(self, o: NameExpr) -> None:\n        if o.name in self.builtins and self.tracker.in_scope(ScopeType.Global):\n            return\n        if (\n            self.tracker.is_possibly_undefined(o.name)\n            and self.tracker.in_finally == self.tracker.disable_branch_skip\n        ):\n            # A variable is only defined in some branches.\n            self.variable_may_be_undefined(o.name, o)\n            # We don't want to report the error on the same variable multiple times.\n            self.tracker.record_definition(o.name)\n        elif self.tracker.is_defined_in_different_branch(o.name):\n            # A variable is defined in one branch but used in a different branch.\n            if self.loops or self.try_depth > 0:\n                # If we're in a loop or in a try, we can't be sure that this variable\n                # is undefined. Report it as \"may be undefined\".\n                self.variable_may_be_undefined(o.name, o)\n            else:\n                self.var_used_before_def(o.name, o)\n        elif self.tracker.is_undefined(o.name):\n            # A variable is undefined. It could be due to two things:\n            # 1. A variable is just totally undefined\n            # 2. The variable is defined later in the code.\n            # Case (1) will be caught by semantic analyzer. Case (2) is a forward ref that should\n            # be caught by this visitor. Save the ref for later, so that if we see a definition,\n            # we know it's a used-before-definition scenario.\n            self.tracker.record_undefined_ref(o)\n        super().visit_name_expr(o)\n\n    def visit_with_stmt(self, o: WithStmt) -> None:\n        for expr, idx in zip(o.expr, o.target):\n            expr.accept(self)\n            self.process_lvalue(idx)\n        o.body.accept(self)\n\n    def visit_class_def(self, o: ClassDef) -> None:\n        self.process_definition(o.name)\n        self.tracker.enter_scope(ScopeType.Class)\n        super().visit_class_def(o)\n        self.tracker.exit_scope()\n\n    def visit_import(self, o: Import) -> None:\n        for mod, alias in o.ids:\n            if alias is not None:\n                self.tracker.record_definition(alias)\n            else:\n                # When you do `import x.y`, only `x` becomes defined.\n                names = mod.split(\".\")\n                if names:\n                    # `names` should always be nonempty, but we don't want mypy\n                    # to crash on invalid code.\n                    self.tracker.record_definition(names[0])\n        super().visit_import(o)\n\n    def visit_import_from(self, o: ImportFrom) -> None:\n        for mod, alias in o.names:\n            name = alias\n            if name is None:\n                name = mod\n            self.tracker.record_definition(name)\n        super().visit_import_from(o)\n\n    def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None:\n        # Type alias target may contain forward references\n        self.tracker.record_definition(o.name.name)\n"
  },
  {
    "path": "mypy/patterns.py",
    "content": "\"\"\"Classes for representing match statement patterns.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TypeVar\n\nfrom mypy_extensions import trait\n\nfrom mypy.nodes import Expression, NameExpr, Node, RefExpr\nfrom mypy.visitor import PatternVisitor\n\nT = TypeVar(\"T\")\n\n\n@trait\nclass Pattern(Node):\n    \"\"\"A pattern node.\"\"\"\n\n    __slots__ = ()\n\n    def accept(self, visitor: PatternVisitor[T]) -> T:\n        raise RuntimeError(\"Not implemented\", type(self))\n\n\nclass AsPattern(Pattern):\n    \"\"\"The pattern <pattern> as <name>\"\"\"\n\n    # The python ast, and therefore also our ast merges capture, wildcard and as patterns into one\n    # for easier handling.\n    # If pattern is None this is a capture pattern. If name and pattern are both none this is a\n    # wildcard pattern.\n    # Only name being None should not happen but also won't break anything.\n    pattern: Pattern | None\n    name: NameExpr | None\n\n    def __init__(self, pattern: Pattern | None, name: NameExpr | None) -> None:\n        super().__init__()\n        self.pattern = pattern\n        self.name = name\n\n    def accept(self, visitor: PatternVisitor[T]) -> T:\n        return visitor.visit_as_pattern(self)\n\n\nclass OrPattern(Pattern):\n    \"\"\"The pattern <pattern> | <pattern> | ...\"\"\"\n\n    patterns: list[Pattern]\n\n    def __init__(self, patterns: list[Pattern]) -> None:\n        super().__init__()\n        self.patterns = patterns\n\n    def accept(self, visitor: PatternVisitor[T]) -> T:\n        return visitor.visit_or_pattern(self)\n\n\nclass ValuePattern(Pattern):\n    \"\"\"The pattern x.y (or x.y.z, ...)\"\"\"\n\n    expr: Expression\n\n    def __init__(self, expr: Expression) -> None:\n        super().__init__()\n        self.expr = expr\n\n    def accept(self, visitor: PatternVisitor[T]) -> T:\n        return visitor.visit_value_pattern(self)\n\n\nclass SingletonPattern(Pattern):\n    # This can be exactly True, False or None\n    value: bool | None\n\n    def __init__(self, value: bool | None) -> None:\n        super().__init__()\n        self.value = value\n\n    def accept(self, visitor: PatternVisitor[T]) -> T:\n        return visitor.visit_singleton_pattern(self)\n\n\nclass SequencePattern(Pattern):\n    \"\"\"The pattern [<pattern>, ...]\"\"\"\n\n    patterns: list[Pattern]\n\n    def __init__(self, patterns: list[Pattern]) -> None:\n        super().__init__()\n        self.patterns = patterns\n\n    def accept(self, visitor: PatternVisitor[T]) -> T:\n        return visitor.visit_sequence_pattern(self)\n\n\nclass StarredPattern(Pattern):\n    # None corresponds to *_ in a list pattern. It will match multiple items but won't bind them to\n    # a name.\n    capture: NameExpr | None\n\n    def __init__(self, capture: NameExpr | None) -> None:\n        super().__init__()\n        self.capture = capture\n\n    def accept(self, visitor: PatternVisitor[T]) -> T:\n        return visitor.visit_starred_pattern(self)\n\n\nclass MappingPattern(Pattern):\n    keys: list[Expression]\n    values: list[Pattern]\n    rest: NameExpr | None\n\n    def __init__(\n        self, keys: list[Expression], values: list[Pattern], rest: NameExpr | None\n    ) -> None:\n        super().__init__()\n        assert len(keys) == len(values)\n        self.keys = keys\n        self.values = values\n        self.rest = rest\n\n    def accept(self, visitor: PatternVisitor[T]) -> T:\n        return visitor.visit_mapping_pattern(self)\n\n\nclass ClassPattern(Pattern):\n    \"\"\"The pattern Cls(...)\"\"\"\n\n    class_ref: RefExpr\n    positionals: list[Pattern]\n    keyword_keys: list[str]\n    keyword_values: list[Pattern]\n\n    def __init__(\n        self,\n        class_ref: RefExpr,\n        positionals: list[Pattern],\n        keyword_keys: list[str],\n        keyword_values: list[Pattern],\n    ) -> None:\n        super().__init__()\n        assert len(keyword_keys) == len(keyword_values)\n        self.class_ref = class_ref\n        self.positionals = positionals\n        self.keyword_keys = keyword_keys\n        self.keyword_values = keyword_values\n\n    def accept(self, visitor: PatternVisitor[T]) -> T:\n        return visitor.visit_class_pattern(self)\n"
  },
  {
    "path": "mypy/plugin.py",
    "content": "\"\"\"Plugin system for extending mypy.\n\nAt large scale the plugin system works as following:\n\n* Plugins are collected from the corresponding mypy config file option\n  (either via paths to Python files, or installed Python modules)\n  and imported using importlib.\n\n* Every module should get an entry point function (called 'plugin' by default,\n  but may be overridden in the config file) that should accept a single string\n  argument that is a full mypy version (includes git commit hash for dev\n  versions) and return a subclass of mypy.plugins.Plugin.\n\n* All plugin class constructors should match the signature of mypy.plugin.Plugin\n  (i.e. should accept an mypy.options.Options object), and *must* call\n  super().__init__().\n\n* At several steps during semantic analysis and type checking mypy calls\n  special `get_xxx` methods on user plugins with a single string argument that\n  is a fully qualified name (full name) of a relevant definition\n  (see mypy.plugin.Plugin method docstrings for details).\n\n* The plugins are called in the order they are passed in the config option.\n  Every plugin must decide whether to act on a given full name. The first\n  plugin that returns non-None object will be used.\n\n* The above decision should be made using the limited common API specified by\n  mypy.plugin.CommonPluginApi.\n\n* The callback returned by the plugin will be called with a larger context that\n  includes relevant current state (e.g. a default return type, or a default\n  attribute type) and a wider relevant API provider (e.g.\n  SemanticAnalyzerPluginInterface or CheckerPluginInterface).\n\n* The result of this is used for further processing. See various `XxxContext`\n  named tuples for details about which information is given to each hook.\n\nPlugin developers should ensure that their plugins work well in incremental and\ndaemon modes. In particular, plugins should not hold global state, and should\nalways call add_plugin_dependency() in plugin hooks called during semantic\nanalysis. See the method docstring for more details.\n\nThere is no dedicated cache storage for plugins, but plugins can store\nper-TypeInfo data in a special .metadata attribute that is serialized to the\nmypy caches between incremental runs. To avoid collisions between plugins, they\nare encouraged to store their state under a dedicated key coinciding with\nplugin name in the metadata dictionary. Every value stored there must be\nJSON-serializable.\n\n## Notes about the semantic analyzer\n\nMypy 0.710 introduced a new semantic analyzer that changed how plugins are\nexpected to work in several notable ways (from mypy 0.730 the old semantic\nanalyzer is no longer available):\n\n1. The order of processing AST nodes in modules is different. The old semantic\n   analyzer processed modules in textual order, one module at a time. The new\n   semantic analyzer first processes the module top levels, including bodies of\n   any top-level classes and classes nested within classes. (\"Top-level\" here\n   means \"not nested within a function/method\".) Functions and methods are\n   processed only after module top levels have been finished. If there is an\n   import cycle, all module top levels in the cycle are processed before\n   processing any functions or methods. Each unit of processing (a module top\n   level or a function/method) is called a *target*.\n\n   This also means that function signatures in the same module have not been\n   analyzed yet when analyzing the module top level. If you need access to\n   a function signature, you'll need to explicitly analyze the signature first\n   using `anal_type()`.\n\n2. Each target can be processed multiple times. This may happen if some forward\n   references are not ready yet, for example. This means that semantic analyzer\n   related plugin hooks can be called multiple times for the same full name.\n   These plugin methods must thus be idempotent.\n\n3. The `anal_type` API function returns None if some part of the type is not\n   available yet. If this happens, the current target being analyzed will be\n   *deferred*, which means that it will be processed again soon, in the hope\n   that additional dependencies will be available. This may happen if there are\n   forward references to types or inter-module references to types within an\n   import cycle.\n\n   Note that if there is a circular definition, mypy may decide to stop\n   processing to avoid an infinite number of iterations. When this happens,\n   `anal_type` will generate an error and return an `AnyType` type object\n   during the final iteration (instead of None).\n\n4. There is a new API method `defer()`. This can be used to explicitly request\n   the current target to be reprocessed one more time. You don't need this\n   to call this if `anal_type` returns None, however.\n\n5. There is a new API property `final_iteration`, which is true once mypy\n   detected no progress during the previous iteration or if the maximum\n   semantic analysis iteration count has been reached. You must never\n   defer during the final iteration, as it will cause a crash.\n\n6. The `node` attribute of SymbolTableNode objects may contain a reference to\n   a PlaceholderNode object. This object means that this definition has not\n   been fully processed yet. If you encounter a PlaceholderNode, you should\n   defer unless it's the final iteration. If it's the final iteration, you\n   should generate an error message. It usually means that there's a cyclic\n   definition that cannot be resolved by mypy. PlaceholderNodes can only refer\n   to references inside an import cycle. If you are looking up things from\n   another module, such as the builtins, that is outside the current module or\n   import cycle, you can safely assume that you won't receive a placeholder.\n\nWhen testing your plugin, you should have a test case that forces a module top\nlevel to be processed multiple times. The easiest way to do this is to include\na forward reference to a class in a top-level annotation. Example:\n\n    c: C  # Forward reference causes second analysis pass\n    class C: pass\n\nNote that a forward reference in a function signature won't trigger another\npass, since all functions are processed only after the top level has been fully\nanalyzed.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections.abc import Callable\nfrom typing import TYPE_CHECKING, Any, NamedTuple, TypeVar\n\nfrom mypy_extensions import mypyc_attr, trait\n\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.errors import ErrorInfo\nfrom mypy.lookup import lookup_fully_qualified\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.nodes import (\n    ArgKind,\n    CallExpr,\n    ClassDef,\n    Context,\n    Expression,\n    MypyFile,\n    SymbolTableNode,\n    TypeInfo,\n)\nfrom mypy.options import Options\nfrom mypy.types import (\n    CallableType,\n    FunctionLike,\n    Instance,\n    ProperType,\n    Type,\n    TypeList,\n    UnboundType,\n)\n\nif TYPE_CHECKING:\n    from mypy.messages import MessageBuilder\n    from mypy.tvar_scope import TypeVarLikeScope\n\n\n@trait\nclass TypeAnalyzerPluginInterface:\n    \"\"\"Interface for accessing semantic analyzer functionality in plugins.\n\n    Methods docstrings contain only basic info. Look for corresponding implementation\n    docstrings in typeanal.py for more details.\n    \"\"\"\n\n    # An options object. Note: these are the cloned options for the current file.\n    # This might be different from Plugin.options (that contains default/global options)\n    # if there are per-file options in the config. This applies to all other interfaces\n    # in this file.\n    options: Options\n\n    @abstractmethod\n    def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:\n        \"\"\"Emit an error message at given location.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def named_type(self, fullname: str, args: list[Type], /) -> Instance:\n        \"\"\"Construct an instance of a builtin type with given name.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def analyze_type(self, typ: Type, /) -> Type:\n        \"\"\"Analyze an unbound type using the default mypy logic.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def analyze_callable_args(\n        self, arglist: TypeList\n    ) -> tuple[list[Type], list[ArgKind], list[str | None]] | None:\n        \"\"\"Find types, kinds, and names of arguments from extended callable syntax.\"\"\"\n        raise NotImplementedError\n\n\n# A context for a hook that semantically analyzes an unbound type.\nclass AnalyzeTypeContext(NamedTuple):\n    type: UnboundType  # Type to analyze\n    context: Context  # Relevant location context (e.g. for error messages)\n    api: TypeAnalyzerPluginInterface\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass CommonPluginApi:\n    \"\"\"\n    A common plugin API (shared between semantic analysis and type checking phases)\n    that all plugin hooks get independently of the context.\n    \"\"\"\n\n    # Global mypy options.\n    # Per-file options can be only accessed on various\n    # XxxPluginInterface classes.\n    options: Options\n\n    @abstractmethod\n    def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode | None:\n        \"\"\"Lookup a symbol by its full name (including module).\n\n        This lookup function available for all plugins. Return None if a name\n        is not found. This function doesn't support lookup from current scope.\n        Use SemanticAnalyzerPluginInterface.lookup_qualified() for this.\"\"\"\n        raise NotImplementedError\n\n\n@trait\nclass CheckerPluginInterface:\n    \"\"\"Interface for accessing type checker functionality in plugins.\n\n    Methods docstrings contain only basic info. Look for corresponding implementation\n    docstrings in checker.py for more details.\n    \"\"\"\n\n    msg: MessageBuilder\n    options: Options\n    path: str\n\n    # Type context for type inference\n    @property\n    @abstractmethod\n    def type_context(self) -> list[Type | None]:\n        \"\"\"Return the type context of the plugin\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def fail(\n        self, msg: str | ErrorMessage, ctx: Context, /, *, code: ErrorCode | None = None\n    ) -> ErrorInfo | None:\n        \"\"\"Emit an error message at given location.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def named_generic_type(self, name: str, args: list[Type]) -> Instance:\n        \"\"\"Construct an instance of a generic type with given type arguments.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def get_expression_type(self, node: Expression, type_context: Type | None = None) -> Type:\n        \"\"\"Checks the type of the given expression.\"\"\"\n        raise NotImplementedError\n\n\n@trait\nclass SemanticAnalyzerPluginInterface:\n    \"\"\"Interface for accessing semantic analyzer functionality in plugins.\n\n    Methods docstrings contain only basic info. Look for corresponding implementation\n    docstrings in semanal.py for more details.\n\n    # TODO: clean-up lookup functions.\n    \"\"\"\n\n    modules: dict[str, MypyFile]\n    # Options for current file.\n    options: Options\n    cur_mod_id: str\n    msg: MessageBuilder\n\n    @abstractmethod\n    def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance:\n        \"\"\"Construct an instance of a builtin type with given type arguments.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def builtin_type(self, fully_qualified_name: str) -> Instance:\n        \"\"\"Legacy function -- use named_type() instead.\"\"\"\n        # NOTE: Do not delete this since many plugins may still use it.\n        raise NotImplementedError\n\n    @abstractmethod\n    def named_type_or_none(self, fullname: str, args: list[Type] | None = None) -> Instance | None:\n        \"\"\"Construct an instance of a type with given type arguments.\n\n        Return None if a type could not be constructed for the qualified\n        type name. This is possible when the qualified name includes a\n        module name and the module has not been imported.\n        \"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo:\n        raise NotImplementedError\n\n    @abstractmethod\n    def parse_bool(self, expr: Expression) -> bool | None:\n        \"\"\"Parse True/False literals.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def parse_str_literal(self, expr: Expression) -> str | None:\n        \"\"\"Parse string literals.\"\"\"\n\n    @abstractmethod\n    def fail(\n        self,\n        msg: str,\n        ctx: Context,\n        serious: bool = False,\n        *,\n        blocker: bool = False,\n        code: ErrorCode | None = None,\n    ) -> None:\n        \"\"\"Emit an error message at given location.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def anal_type(\n        self,\n        typ: Type,\n        /,\n        *,\n        tvar_scope: TypeVarLikeScope | None = None,\n        allow_tuple_literal: bool = False,\n        allow_unbound_tvars: bool = False,\n        report_invalid_types: bool = True,\n    ) -> Type | None:\n        \"\"\"Analyze an unbound type.\n\n        Return None if some part of the type is not ready yet. In this\n        case the current target being analyzed will be deferred and\n        analyzed again.\n        \"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def class_type(self, self_type: Type) -> Type:\n        \"\"\"Generate type of first argument of class methods from type of self.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def lookup_fully_qualified(self, fullname: str, /) -> SymbolTableNode:\n        \"\"\"Lookup a symbol by its fully qualified name.\n\n        Raise an error if not found.\n        \"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def lookup_fully_qualified_or_none(self, fullname: str, /) -> SymbolTableNode | None:\n        \"\"\"Lookup a symbol by its fully qualified name.\n\n        Return None if not found.\n        \"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def lookup_qualified(\n        self, name: str, ctx: Context, suppress_errors: bool = False\n    ) -> SymbolTableNode | None:\n        \"\"\"Lookup symbol using a name in current scope.\n\n        This follows Python local->non-local->global->builtins rules.\n        \"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def add_plugin_dependency(self, trigger: str, target: str | None = None) -> None:\n        \"\"\"Specify semantic dependencies for generated methods/variables.\n\n        If the symbol with full name given by trigger is found to be stale by mypy,\n        then the body of node with full name given by target will be re-checked.\n        By default, this is the node that is currently analyzed.\n\n        For example, the dataclass plugin adds a generated __init__ method with\n        a signature that depends on types of attributes in ancestor classes. If any\n        attribute in an ancestor class gets stale (modified), we need to reprocess\n        the subclasses (and thus regenerate __init__ methods).\n\n        This is used by fine-grained incremental mode (mypy daemon). See mypy/server/deps.py\n        for more details.\n        \"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def add_symbol_table_node(self, name: str, symbol: SymbolTableNode) -> Any:\n        \"\"\"Add node to global symbol table (or to nearest class if there is one).\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def qualified_name(self, name: str) -> str:\n        \"\"\"Make qualified name using current module and enclosing class (if any).\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def defer(self) -> None:\n        \"\"\"Call this to defer the processing of the current node.\n\n        This will request an additional iteration of semantic analysis.\n        \"\"\"\n        raise NotImplementedError\n\n    @property\n    @abstractmethod\n    def final_iteration(self) -> bool:\n        \"\"\"Is this the final iteration of semantic analysis?\"\"\"\n        raise NotImplementedError\n\n    @property\n    @abstractmethod\n    def is_stub_file(self) -> bool:\n        raise NotImplementedError\n\n    @abstractmethod\n    def analyze_simple_literal_type(self, rvalue: Expression, is_final: bool) -> Type | None:\n        raise NotImplementedError\n\n\n# A context for querying for configuration data about a module for\n# cache invalidation purposes.\nclass ReportConfigContext(NamedTuple):\n    id: str  # Module name\n    path: str  # Module file path\n    is_check: bool  # Is this invocation for checking whether the config matches\n\n\n# A context for a function signature hook that infers a better signature for a\n# function.  Note that argument types aren't available yet.  If you need them,\n# you have to use a method hook instead.\nclass FunctionSigContext(NamedTuple):\n    args: list[list[Expression]]  # Actual expressions for each formal argument\n    default_signature: CallableType  # Original signature of the method\n    context: Context  # Relevant location context (e.g. for error messages)\n    api: CheckerPluginInterface\n\n\n# A context for a function hook that infers the return type of a function with\n# a special signature.\n#\n# A no-op callback would just return the inferred return type, but a useful\n# callback at least sometimes can infer a more precise type.\nclass FunctionContext(NamedTuple):\n    arg_types: list[list[Type]]  # List of actual caller types for each formal argument\n    arg_kinds: list[list[ArgKind]]  # Ditto for argument kinds, see nodes.ARG_* constants\n    # Names of formal parameters from the callee definition,\n    # these will be sufficient in most cases.\n    callee_arg_names: list[str | None]\n    # Names of actual arguments in the call expression. For example,\n    # in a situation like this:\n    #     def func(**kwargs) -> None:\n    #         pass\n    #     func(kw1=1, kw2=2)\n    # callee_arg_names will be ['kwargs'] and arg_names will be [['kw1', 'kw2']].\n    arg_names: list[list[str | None]]\n    default_return_type: Type  # Return type inferred from signature\n    args: list[list[Expression]]  # Actual expressions for each formal argument\n    context: Context  # Relevant location context (e.g. for error messages)\n    api: CheckerPluginInterface\n\n\n# A context for a method signature hook that infers a better signature for a\n# method.  Note that argument types aren't available yet.  If you need them,\n# you have to use a method hook instead.\n# TODO: document ProperType in the plugin changelog/update issue.\nclass MethodSigContext(NamedTuple):\n    type: ProperType  # Base object type for method call\n    args: list[list[Expression]]  # Actual expressions for each formal argument\n    default_signature: CallableType  # Original signature of the method\n    context: Context  # Relevant location context (e.g. for error messages)\n    api: CheckerPluginInterface\n\n\n# A context for a method hook that infers the return type of a method with a\n# special signature.\n#\n# This is very similar to FunctionContext (only differences are documented).\nclass MethodContext(NamedTuple):\n    type: ProperType  # Base object type for method call\n    arg_types: list[list[Type]]  # List of actual caller types for each formal argument\n    # see FunctionContext for details about names and kinds\n    arg_kinds: list[list[ArgKind]]\n    callee_arg_names: list[str | None]\n    arg_names: list[list[str | None]]\n    default_return_type: Type  # Return type inferred by mypy\n    args: list[list[Expression]]  # Lists of actual expressions for every formal argument\n    context: Context\n    api: CheckerPluginInterface\n\n\n# A context for an attribute type hook that infers the type of an attribute.\nclass AttributeContext(NamedTuple):\n    type: ProperType  # Type of object with attribute\n    default_attr_type: Type  # Original attribute type\n    is_lvalue: bool  # Whether the attribute is the target of an assignment\n    context: Context  # Relevant location context (e.g. for error messages)\n    api: CheckerPluginInterface\n\n\n# A context for a class hook that modifies the class definition.\nclass ClassDefContext(NamedTuple):\n    cls: ClassDef  # The class definition\n    reason: Expression  # The expression being applied (decorator, metaclass, base class)\n    api: SemanticAnalyzerPluginInterface\n\n\n# A context for dynamic class definitions like\n# Base = declarative_base()\nclass DynamicClassDefContext(NamedTuple):\n    call: CallExpr  # The r.h.s. of dynamic class definition\n    name: str  # The name this class is being assigned to\n    api: SemanticAnalyzerPluginInterface\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass Plugin(CommonPluginApi):\n    \"\"\"Base class of all type checker plugins.\n\n    This defines a no-op plugin.  Subclasses can override some methods to\n    provide some actual functionality.\n\n    All get_ methods are treated as pure functions (you should assume that\n    results might be cached). A plugin should return None from a get_ method\n    to give way to other plugins.\n\n    Look at the comments of various *Context objects for additional information on\n    various hooks.\n    \"\"\"\n\n    def __init__(self, options: Options) -> None:\n        self.options = options\n        self.python_version = options.python_version\n        # This can't be set in __init__ because it is executed too soon in build.py.\n        # Therefore, build.py *must* set it later before graph processing starts\n        # by calling set_modules().\n        self._modules: dict[str, MypyFile] | None = None\n\n    def set_modules(self, modules: dict[str, MypyFile]) -> None:\n        self._modules = modules\n\n    def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode | None:\n        assert self._modules is not None\n        return lookup_fully_qualified(fullname, self._modules)\n\n    def report_config_data(self, ctx: ReportConfigContext) -> Any:\n        \"\"\"Get representation of configuration data for a module.\n\n        The data must be encodable as JSON and will be stored in the\n        cache metadata for the module. A mismatch between the cached\n        values and the returned will result in that module's cache\n        being invalidated and the module being rechecked.\n\n        This can be called twice for each module, once after loading\n        the cache to check if it is valid and once while writing new\n        cache information.\n\n        If is_check in the context is true, then the return of this\n        call will be checked against the cached version. Otherwise the\n        call is being made to determine what to put in the cache. This\n        can be used to allow consulting extra cache files in certain\n        complex situations.\n\n        This can be used to incorporate external configuration information\n        that might require changes to typechecking.\n        \"\"\"\n        return None\n\n    def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]:\n        \"\"\"Customize dependencies for a module.\n\n        This hook allows adding in new dependencies for a module. It\n        is called after parsing a file but before analysis. This can\n        be useful if a library has dependencies that are dynamic based\n        on configuration information, for example.\n\n        Returns a list of (priority, module name, line number) tuples.\n\n        The line number can be -1 when there is not a known real line number.\n\n        Priorities are defined in mypy.build (but maybe shouldn't be).\n        10 is a good choice for priority.\n        \"\"\"\n        return []\n\n    def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None:\n        \"\"\"Customize behaviour of the type analyzer for given full names.\n\n        This method is called during the semantic analysis pass whenever mypy sees an\n        unbound type. For example, while analysing this code:\n\n            from lib import Special, Other\n\n            var: Special\n            def func(x: Other[int]) -> None:\n                ...\n\n        this method will be called with 'lib.Special', and then with 'lib.Other'.\n        The callback returned by plugin must return an analyzed type,\n        i.e. an instance of `mypy.types.Type`.\n        \"\"\"\n        return None\n\n    def get_function_signature_hook(\n        self, fullname: str\n    ) -> Callable[[FunctionSigContext], FunctionLike] | None:\n        \"\"\"Adjust the signature of a function.\n\n        This method is called before type checking a function call. Plugin\n        may infer a better type for the function.\n\n            from lib import Class, do_stuff\n\n            do_stuff(42)\n            Class()\n\n        This method will be called with 'lib.do_stuff' and then with 'lib.Class'.\n        \"\"\"\n        return None\n\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        \"\"\"Adjust the return type of a function call.\n\n        This method is called after type checking a call. Plugin may adjust the return\n        type inferred by mypy, and/or emit some error messages. Note, this hook is also\n        called for class instantiation calls, so that in this example:\n\n            from lib import Class, do_stuff\n\n            do_stuff(42)\n            Class()\n\n        This method will be called with 'lib.do_stuff' and then with 'lib.Class'.\n        \"\"\"\n        return None\n\n    def get_method_signature_hook(\n        self, fullname: str\n    ) -> Callable[[MethodSigContext], FunctionLike] | None:\n        \"\"\"Adjust the signature of a method.\n\n        This method is called before type checking a method call. Plugin\n        may infer a better type for the method. The hook is also called for special\n        Python dunder methods except __init__ and __new__ (use get_function_hook to customize\n        class instantiation). This function is called with the method full name using\n        the class where it was _defined_. For example, in this code:\n\n            from lib import Special\n\n            class Base:\n                def method(self, arg: Any) -> Any:\n                    ...\n            class Derived(Base):\n                ...\n\n            var: Derived\n            var.method(42)\n\n            x: Special\n            y = x[0]\n\n        this method is called with '__main__.Base.method', and then with\n        'lib.Special.__getitem__'.\n        \"\"\"\n        return None\n\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        \"\"\"Adjust return type of a method call.\n\n        This is the same as get_function_hook(), but is called with the\n        method full name (again, using the class where the method is defined).\n        \"\"\"\n        return None\n\n    def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:\n        \"\"\"Adjust type of an instance attribute.\n\n        This method is called with attribute full name using the class of the instance where\n        the attribute was defined (or Var.info.fullname for generated attributes).\n\n        For classes without __getattr__ or __getattribute__, this hook is only called for\n        names of fields/properties (but not methods) that exist in the instance MRO.\n\n        For classes that implement __getattr__ or __getattribute__, this hook is called\n        for all fields/properties, including nonexistent ones (but still not methods).\n\n        For example:\n\n            class Base:\n                x: Any\n                def __getattr__(self, attr: str) -> Any: ...\n\n            class Derived(Base):\n                ...\n\n            var: Derived\n            var.x\n            var.y\n\n        get_attribute_hook is called with '__main__.Base.x' and '__main__.Base.y'.\n        However, if we had not implemented __getattr__ on Base, you would only get\n        the callback for 'var.x'; 'var.y' would produce an error without calling the hook.\n        \"\"\"\n        return None\n\n    def get_class_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:\n        \"\"\"\n        Adjust type of a class attribute.\n\n        This method is called with attribute full name using the class where the attribute was\n        defined (or Var.info.fullname for generated attributes).\n\n        For example:\n\n            class Cls:\n                x: Any\n\n            Cls.x\n\n        get_class_attribute_hook is called with '__main__.Cls.x' as fullname.\n        \"\"\"\n        return None\n\n    def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        \"\"\"Update class definition for given class decorators.\n\n        The plugin can modify a TypeInfo _in place_ (for example add some generated\n        methods to the symbol table). This hook is called after the class body was\n        semantically analyzed, but *there may still be placeholders* (typically\n        caused by forward references).\n\n        NOTE: Usually get_class_decorator_hook_2 is the better option, since it\n              guarantees that there are no placeholders.\n\n        The hook is called with full names of all class decorators.\n\n        The hook can be called multiple times per class, so it must be\n        idempotent.\n        \"\"\"\n        return None\n\n    def get_class_decorator_hook_2(\n        self, fullname: str\n    ) -> Callable[[ClassDefContext], bool] | None:\n        \"\"\"Update class definition for given class decorators.\n\n        Similar to get_class_decorator_hook, but this runs in a later pass when\n        placeholders have been resolved.\n\n        The hook can return False if some base class hasn't been\n        processed yet using class hooks. It causes all class hooks\n        (that are run in this same pass) to be invoked another time for\n        the file(s) currently being processed.\n\n        The hook can be called multiple times per class, so it must be\n        idempotent.\n        \"\"\"\n        return None\n\n    def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        \"\"\"Update class definition for given declared metaclasses.\n\n        Same as get_class_decorator_hook() but for metaclasses. Note:\n        this hook will be only called for explicit metaclasses, not for\n        inherited ones.\n\n        TODO: probably it should also be called on inherited metaclasses.\n        \"\"\"\n        return None\n\n    def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        \"\"\"Update class definition for given base classes.\n\n        Same as get_class_decorator_hook() but for base classes. Base classes\n        don't need to refer to TypeInfos, if a base class refers to a variable with\n        Any type, this hook will still be called.\n        \"\"\"\n        return None\n\n    def get_customize_class_mro_hook(\n        self, fullname: str\n    ) -> Callable[[ClassDefContext], None] | None:\n        \"\"\"Customize MRO for given classes.\n\n        The plugin can modify the class MRO _in place_. This method is called\n        with the class full name before its body was semantically analyzed.\n        \"\"\"\n        return None\n\n    def get_dynamic_class_hook(\n        self, fullname: str\n    ) -> Callable[[DynamicClassDefContext], None] | None:\n        \"\"\"Semantically analyze a dynamic class definition.\n\n        This plugin hook allows one to semantically analyze dynamic class definitions like:\n\n            from lib import dynamic_class\n\n            X = dynamic_class('X', [])\n\n        For such definition, this hook will be called with 'lib.dynamic_class'.\n        The plugin should create the corresponding TypeInfo, and place it into a relevant\n        symbol table, e.g. using ctx.api.add_symbol_table_node().\n        \"\"\"\n        return None\n\n\nT = TypeVar(\"T\")\n\n\nclass ChainedPlugin(Plugin):\n    \"\"\"A plugin that represents a sequence of chained plugins.\n\n    Each lookup method returns the hook for the first plugin that\n    reports a match.\n\n    This class should not be subclassed -- use Plugin as the base class\n    for all plugins.\n    \"\"\"\n\n    # TODO: Support caching of lookup results (through a LRU cache, for example).\n\n    def __init__(self, options: Options, plugins: list[Plugin]) -> None:\n        \"\"\"Initialize chained plugin.\n\n        Assume that the child plugins aren't mutated (results may be cached).\n        \"\"\"\n        super().__init__(options)\n        self._plugins = plugins\n\n    def set_modules(self, modules: dict[str, MypyFile]) -> None:\n        for plugin in self._plugins:\n            plugin.set_modules(modules)\n\n    def report_config_data(self, ctx: ReportConfigContext) -> Any:\n        config_data = [plugin.report_config_data(ctx) for plugin in self._plugins]\n        return config_data if any(x is not None for x in config_data) else None\n\n    def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]:\n        deps = []\n        for plugin in self._plugins:\n            deps.extend(plugin.get_additional_deps(file))\n        return deps\n\n    def get_type_analyze_hook(self, fullname: str) -> Callable[[AnalyzeTypeContext], Type] | None:\n        # Micro-optimization: Inline iteration over plugins\n        for plugin in self._plugins:\n            hook = plugin.get_type_analyze_hook(fullname)\n            if hook is not None:\n                return hook\n        return None\n\n    def get_function_signature_hook(\n        self, fullname: str\n    ) -> Callable[[FunctionSigContext], FunctionLike] | None:\n        # Micro-optimization: Inline iteration over plugins\n        for plugin in self._plugins:\n            hook = plugin.get_function_signature_hook(fullname)\n            if hook is not None:\n                return hook\n        return None\n\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        return self._find_hook(lambda plugin: plugin.get_function_hook(fullname))\n\n    def get_method_signature_hook(\n        self, fullname: str\n    ) -> Callable[[MethodSigContext], FunctionLike] | None:\n        # Micro-optimization: Inline iteration over plugins\n        for plugin in self._plugins:\n            hook = plugin.get_method_signature_hook(fullname)\n            if hook is not None:\n                return hook\n        return None\n\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        # Micro-optimization: Inline iteration over plugins\n        for plugin in self._plugins:\n            hook = plugin.get_method_hook(fullname)\n            if hook is not None:\n                return hook\n        return None\n\n    def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:\n        # Micro-optimization: Inline iteration over plugins\n        for plugin in self._plugins:\n            hook = plugin.get_attribute_hook(fullname)\n            if hook is not None:\n                return hook\n        return None\n\n    def get_class_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:\n        return self._find_hook(lambda plugin: plugin.get_class_attribute_hook(fullname))\n\n    def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        return self._find_hook(lambda plugin: plugin.get_class_decorator_hook(fullname))\n\n    def get_class_decorator_hook_2(\n        self, fullname: str\n    ) -> Callable[[ClassDefContext], bool] | None:\n        return self._find_hook(lambda plugin: plugin.get_class_decorator_hook_2(fullname))\n\n    def get_metaclass_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        return self._find_hook(lambda plugin: plugin.get_metaclass_hook(fullname))\n\n    def get_base_class_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        return self._find_hook(lambda plugin: plugin.get_base_class_hook(fullname))\n\n    def get_customize_class_mro_hook(\n        self, fullname: str\n    ) -> Callable[[ClassDefContext], None] | None:\n        return self._find_hook(lambda plugin: plugin.get_customize_class_mro_hook(fullname))\n\n    def get_dynamic_class_hook(\n        self, fullname: str\n    ) -> Callable[[DynamicClassDefContext], None] | None:\n        return self._find_hook(lambda plugin: plugin.get_dynamic_class_hook(fullname))\n\n    def _find_hook(self, lookup: Callable[[Plugin], T]) -> T | None:\n        for plugin in self._plugins:\n            hook = lookup(plugin)\n            if hook is not None:\n                return hook\n        return None\n"
  },
  {
    "path": "mypy/plugins/__init__.py",
    "content": ""
  },
  {
    "path": "mypy/plugins/attrs.py",
    "content": "\"\"\"Plugin for supporting the attrs library (http://www.attrs.org)\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom collections.abc import Iterable, Mapping\nfrom functools import reduce\nfrom typing import Final, Literal, cast\n\nimport mypy.plugin  # To avoid circular imports.\nfrom mypy.applytype import apply_generic_arguments\nfrom mypy.errorcodes import LITERAL_REQ\nfrom mypy.expandtype import expand_type, expand_type_by_instance\nfrom mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type\nfrom mypy.meet import meet_types\nfrom mypy.messages import format_type_bare\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_NAMED_OPT,\n    ARG_OPT,\n    ARG_POS,\n    MDEF,\n    Argument,\n    AssignmentStmt,\n    CallExpr,\n    Context,\n    Decorator,\n    Expression,\n    FuncDef,\n    IndexExpr,\n    JsonDict,\n    LambdaExpr,\n    ListExpr,\n    MemberExpr,\n    NameExpr,\n    OverloadedFuncDef,\n    PlaceholderNode,\n    RefExpr,\n    SymbolTableNode,\n    TempNode,\n    TupleExpr,\n    TypeApplication,\n    TypeInfo,\n    TypeVarExpr,\n    Var,\n    is_class_var,\n)\nfrom mypy.plugin import SemanticAnalyzerPluginInterface\nfrom mypy.plugins.common import (\n    _get_argument,\n    _get_bool_argument,\n    _get_decorator_bool_argument,\n    add_attribute_to_class,\n    add_method_to_class,\n    deserialize_and_fixup_type,\n)\nfrom mypy.server.trigger import make_wildcard_trigger\nfrom mypy.state import state\nfrom mypy.typeops import (\n    get_type_vars,\n    make_simplified_union,\n    map_type_from_supertype,\n    type_object_type,\n)\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    ProperType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeType,\n    TypeVarId,\n    TypeVarType,\n    UninhabitedType,\n    UnionType,\n    get_proper_type,\n)\nfrom mypy.typevars import fill_typevars\nfrom mypy.util import unmangle\n\n# The names of the different functions that create classes or arguments.\nattr_class_makers: Final = {\"attr.s\", \"attr.attrs\", \"attr.attributes\"}\nattr_dataclass_makers: Final = {\"attr.dataclass\"}\nattr_frozen_makers: Final = {\"attr.frozen\", \"attrs.frozen\"}\nattr_define_makers: Final = {\"attr.define\", \"attr.mutable\", \"attrs.define\", \"attrs.mutable\"}\nattr_attrib_makers: Final = {\"attr.ib\", \"attr.attrib\", \"attr.attr\", \"attr.field\", \"attrs.field\"}\nattr_optional_converters: Final = {\"attr.converters.optional\", \"attrs.converters.optional\"}\n\nSELF_TVAR_NAME: Final = \"_AT\"\nMAGIC_ATTR_NAME: Final = \"__attrs_attrs__\"\nMAGIC_ATTR_CLS_NAME_TEMPLATE: Final = \"__{}_AttrsAttributes__\"  # The tuple subclass pattern.\nATTRS_INIT_NAME: Final = \"__attrs_init__\"\n\n\nclass Converter:\n    \"\"\"Holds information about a `converter=` argument\"\"\"\n\n    def __init__(self, init_type: Type | None = None, ret_type: Type | None = None) -> None:\n        self.init_type = init_type\n        self.ret_type = ret_type\n\n\nclass Attribute:\n    \"\"\"The value of an attr.ib() call.\"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        alias: str | None,\n        info: TypeInfo,\n        has_default: bool,\n        init: bool,\n        kw_only: bool,\n        converter: Converter | None,\n        context: Context,\n        init_type: Type | None,\n    ) -> None:\n        self.name = name\n        self.alias = alias\n        self.info = info\n        self.has_default = has_default\n        self.init = init\n        self.kw_only = kw_only\n        self.converter = converter\n        self.context = context\n        self.init_type = init_type\n\n    def argument(self, ctx: mypy.plugin.ClassDefContext) -> Argument:\n        \"\"\"Return this attribute as an argument to __init__.\"\"\"\n        assert self.init\n        init_type: Type | None = None\n        if self.converter:\n            if self.converter.init_type:\n                init_type = self.converter.init_type\n                if init_type and self.init_type and self.converter.ret_type:\n                    # The converter return type should be the same type as the attribute type.\n                    # Copy type vars from attr type to converter.\n                    converter_vars = get_type_vars(self.converter.ret_type)\n                    init_vars = get_type_vars(self.init_type)\n                    if converter_vars and len(converter_vars) == len(init_vars):\n                        variables = {\n                            binder.id: arg for binder, arg in zip(converter_vars, init_vars)\n                        }\n                        init_type = expand_type(init_type, variables)\n            else:\n                ctx.api.fail(\"Cannot determine __init__ type from converter\", self.context)\n                init_type = AnyType(TypeOfAny.from_error)\n        else:  # There is no converter, the init type is the normal type.\n            init_type = self.init_type or self.info[self.name].type\n\n        unannotated = False\n        if init_type is None:\n            unannotated = True\n            # Convert type not set to Any.\n            init_type = AnyType(TypeOfAny.unannotated)\n        else:\n            proper_type = get_proper_type(init_type)\n            if isinstance(proper_type, AnyType):\n                if proper_type.type_of_any == TypeOfAny.unannotated:\n                    unannotated = True\n\n        if unannotated and ctx.api.options.disallow_untyped_defs:\n            # This is a compromise.  If you don't have a type here then the\n            # __init__ will be untyped. But since the __init__ is added it's\n            # pointing at the decorator. So instead we also show the error in the\n            # assignment, which is where you would fix the issue.\n            node = self.info[self.name].node\n            assert node is not None\n            ctx.api.msg.need_annotation_for_var(node, self.context)\n\n        if self.kw_only:\n            arg_kind = ARG_NAMED_OPT if self.has_default else ARG_NAMED\n        else:\n            arg_kind = ARG_OPT if self.has_default else ARG_POS\n\n        # Attrs removes leading underscores when creating the __init__ arguments.\n        name = self.alias or self.name.lstrip(\"_\")\n        return Argument(Var(name, init_type), init_type, None, arg_kind)\n\n    def serialize(self) -> JsonDict:\n        \"\"\"Serialize this object so it can be saved and restored.\"\"\"\n        return {\n            \"name\": self.name,\n            \"alias\": self.alias,\n            \"has_default\": self.has_default,\n            \"init\": self.init,\n            \"kw_only\": self.kw_only,\n            \"has_converter\": self.converter is not None,\n            \"converter_init_type\": (\n                self.converter.init_type.serialize()\n                if self.converter and self.converter.init_type\n                else None\n            ),\n            \"context_line\": self.context.line,\n            \"context_column\": self.context.column,\n            \"init_type\": self.init_type.serialize() if self.init_type else None,\n        }\n\n    @classmethod\n    def deserialize(\n        cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface\n    ) -> Attribute:\n        \"\"\"Return the Attribute that was serialized.\"\"\"\n        raw_init_type = data[\"init_type\"]\n        init_type = deserialize_and_fixup_type(raw_init_type, api) if raw_init_type else None\n        raw_converter_init_type = data[\"converter_init_type\"]\n        converter_init_type = (\n            deserialize_and_fixup_type(raw_converter_init_type, api)\n            if raw_converter_init_type\n            else None\n        )\n\n        return Attribute(\n            data[\"name\"],\n            data[\"alias\"],\n            info,\n            data[\"has_default\"],\n            data[\"init\"],\n            data[\"kw_only\"],\n            Converter(converter_init_type) if data[\"has_converter\"] else None,\n            Context(line=data[\"context_line\"], column=data[\"context_column\"]),\n            init_type,\n        )\n\n    def expand_typevar_from_subtype(self, sub_type: TypeInfo) -> None:\n        \"\"\"Expands type vars in the context of a subtype when an attribute is inherited\n        from a generic super type.\"\"\"\n        if self.init_type:\n            self.init_type = map_type_from_supertype(self.init_type, sub_type, self.info)\n        else:\n            self.init_type = None\n\n\ndef _determine_eq_order(ctx: mypy.plugin.ClassDefContext) -> bool:\n    \"\"\"\n    Validate the combination of *cmp*, *eq*, and *order*. Derive the effective\n    value of order.\n    \"\"\"\n    cmp = _get_decorator_optional_bool_argument(ctx, \"cmp\")\n    eq = _get_decorator_optional_bool_argument(ctx, \"eq\")\n    order = _get_decorator_optional_bool_argument(ctx, \"order\")\n\n    if cmp is not None and any((eq is not None, order is not None)):\n        ctx.api.fail('Don\\'t mix \"cmp\" with \"eq\" and \"order\"', ctx.reason)\n\n    # cmp takes precedence due to bw-compatibility.\n    if cmp is not None:\n        return cmp\n\n    # If left None, equality is on and ordering mirrors equality.\n    if eq is None:\n        eq = True\n\n    if order is None:\n        order = eq\n\n    if eq is False and order is True:\n        ctx.api.fail(\"eq must be True if order is True\", ctx.reason)\n\n    return order\n\n\ndef _get_decorator_optional_bool_argument(\n    ctx: mypy.plugin.ClassDefContext, name: str, default: bool | None = None\n) -> bool | None:\n    \"\"\"Return the Optional[bool] argument for the decorator.\n\n    This handles both @decorator(...) and @decorator.\n    \"\"\"\n    if isinstance(ctx.reason, CallExpr):\n        attr_value = _get_argument(ctx.reason, name)\n        if attr_value:\n            if isinstance(attr_value, NameExpr):\n                if attr_value.fullname == \"builtins.True\":\n                    return True\n                if attr_value.fullname == \"builtins.False\":\n                    return False\n                if attr_value.fullname == \"builtins.None\":\n                    return None\n            ctx.api.fail(\n                f'\"{name}\" argument must be a True, False, or None literal',\n                ctx.reason,\n                code=LITERAL_REQ,\n            )\n            return default\n        return default\n    else:\n        return default\n\n\ndef attr_tag_callback(ctx: mypy.plugin.ClassDefContext) -> None:\n    \"\"\"Record that we have an attrs class in the main semantic analysis pass.\n\n    The later pass implemented by attr_class_maker_callback will use this\n    to detect attrs classes in base classes.\n    \"\"\"\n    # The value is ignored, only the existence matters.\n    ctx.cls.info.metadata[\"attrs_tag\"] = {}\n\n\ndef attr_class_maker_callback(\n    ctx: mypy.plugin.ClassDefContext,\n    auto_attribs_default: bool | None = False,\n    frozen_default: bool = False,\n    slots_default: bool = False,\n) -> bool:\n    \"\"\"Add necessary dunder methods to classes decorated with attr.s.\n\n    attrs is a package that lets you define classes without writing dull boilerplate code.\n\n    At a quick glance, the decorator searches the class body for assignments of `attr.ib`s (or\n    annotated variables if auto_attribs=True), then depending on how the decorator is called,\n    it will add an __init__ or all the compare methods.\n    For frozen=True it will turn the attrs into properties.\n\n    Hashability will be set according to https://www.attrs.org/en/stable/hashing.html.\n\n    See https://www.attrs.org/en/stable/how-does-it-work.html for information on how attrs works.\n\n    If this returns False, some required metadata was not ready yet, and we need another\n    pass.\n    \"\"\"\n    with state.strict_optional_set(ctx.api.options.strict_optional):\n        # This hook is called during semantic analysis, but it uses a bunch of\n        # type-checking ops, so it needs the strict optional set properly.\n        return attr_class_maker_callback_impl(\n            ctx, auto_attribs_default, frozen_default, slots_default\n        )\n\n\ndef attr_class_maker_callback_impl(\n    ctx: mypy.plugin.ClassDefContext,\n    auto_attribs_default: bool | None,\n    frozen_default: bool,\n    slots_default: bool,\n) -> bool:\n    info = ctx.cls.info\n\n    init = _get_decorator_bool_argument(ctx, \"init\", True)\n    frozen = _get_frozen(ctx, frozen_default)\n    order = _determine_eq_order(ctx)\n    slots = _get_decorator_bool_argument(ctx, \"slots\", slots_default)\n\n    auto_attribs = _get_decorator_optional_bool_argument(ctx, \"auto_attribs\", auto_attribs_default)\n    kw_only = _get_decorator_bool_argument(ctx, \"kw_only\", False)\n    match_args = _get_decorator_bool_argument(ctx, \"match_args\", True)\n\n    for super_info in ctx.cls.info.mro[1:-1]:\n        if \"attrs_tag\" in super_info.metadata and \"attrs\" not in super_info.metadata:\n            # Super class is not ready yet. Request another pass.\n            return False\n\n    attributes = _analyze_class(ctx, auto_attribs, kw_only)\n\n    # Check if attribute types are ready.\n    for attr in attributes:\n        node = info.get(attr.name)\n        if node is None:\n            # This name is likely blocked by some semantic analysis error that\n            # should have been reported already.\n            _add_empty_metadata(info)\n            return True\n\n    _add_attrs_magic_attribute(ctx, [(attr.name, info[attr.name].type) for attr in attributes])\n    if slots:\n        _add_slots(ctx, attributes)\n    if match_args and ctx.api.options.python_version[:2] >= (3, 10):\n        # `.__match_args__` is only added for python3.10+, but the argument\n        # exists for earlier versions as well.\n        _add_match_args(ctx, attributes)\n\n    # Save the attributes so that subclasses can reuse them.\n    ctx.cls.info.metadata[\"attrs\"] = {\n        \"attributes\": [attr.serialize() for attr in attributes],\n        \"frozen\": frozen,\n    }\n\n    adder = MethodAdder(ctx)\n    # If  __init__ is not being generated, attrs still generates it as __attrs_init__ instead.\n    _add_init(ctx, attributes, adder, \"__init__\" if init else ATTRS_INIT_NAME)\n\n    if order:\n        _add_order(ctx, adder)\n    if frozen:\n        _make_frozen(ctx, attributes)\n        # Frozen classes are hashable by default, even if inheriting from non-frozen ones.\n        hashable: bool | None = _get_decorator_bool_argument(\n            ctx, \"hash\", True\n        ) and _get_decorator_bool_argument(ctx, \"unsafe_hash\", True)\n    else:\n        hashable = _get_decorator_optional_bool_argument(ctx, \"unsafe_hash\")\n        if hashable is None:  # unspecified\n            hashable = _get_decorator_optional_bool_argument(ctx, \"hash\")\n\n    eq = _get_decorator_optional_bool_argument(ctx, \"eq\")\n    has_own_hash = \"__hash__\" in ctx.cls.info.names\n\n    if has_own_hash or (hashable is None and eq is False):\n        pass  # Do nothing.\n    elif hashable:\n        # We copy the `__hash__` signature from `object` to make them hashable.\n        ctx.cls.info.names[\"__hash__\"] = ctx.cls.info.mro[-1].names[\"__hash__\"]\n    else:\n        _remove_hashability(ctx)\n\n    return True\n\n\ndef _get_frozen(ctx: mypy.plugin.ClassDefContext, frozen_default: bool) -> bool:\n    \"\"\"Return whether this class is frozen.\"\"\"\n    if _get_decorator_bool_argument(ctx, \"frozen\", frozen_default):\n        return True\n    # Subclasses of frozen classes are frozen so check that.\n    for super_info in ctx.cls.info.mro[1:-1]:\n        if \"attrs\" in super_info.metadata and super_info.metadata[\"attrs\"][\"frozen\"]:\n            return True\n    return False\n\n\ndef _analyze_class(\n    ctx: mypy.plugin.ClassDefContext, auto_attribs: bool | None, class_kw_only: bool\n) -> list[Attribute]:\n    \"\"\"Analyze the class body of an attr maker, its parents, and return the Attributes found.\n\n    auto_attribs=True means we'll generate attributes from type annotations also.\n    auto_attribs=None means we'll detect which mode to use.\n    class_kw_only=True means that all attributes created here will be keyword only args by\n        default in __init__.\n    \"\"\"\n    own_attrs: dict[str, Attribute] = {}\n    if auto_attribs is None:\n        auto_attribs = _detect_auto_attribs(ctx)\n\n    # Walk the body looking for assignments and decorators.\n    for stmt in ctx.cls.defs.body:\n        if isinstance(stmt, AssignmentStmt):\n            for attr in _attributes_from_assignment(ctx, stmt, auto_attribs, class_kw_only):\n                # When attrs are defined twice in the same body we want to use the 2nd definition\n                # in the 2nd location. So remove it from the OrderedDict.\n                # Unless it's auto_attribs in which case we want the 2nd definition in the\n                # 1st location.\n                if not auto_attribs and attr.name in own_attrs:\n                    del own_attrs[attr.name]\n                own_attrs[attr.name] = attr\n        elif isinstance(stmt, Decorator):\n            _cleanup_decorator(stmt, own_attrs)\n\n    for attribute in own_attrs.values():\n        # Even though these look like class level assignments we want them to look like\n        # instance level assignments.\n        if attribute.name in ctx.cls.info.names:\n            node = ctx.cls.info.names[attribute.name].node\n            if isinstance(node, PlaceholderNode):\n                # This node is not ready yet.\n                continue\n            assert isinstance(node, Var), node\n            node.is_initialized_in_class = False\n\n    # Traverse the MRO and collect attributes from the parents.\n    taken_attr_names = set(own_attrs)\n    super_attrs = []\n    for super_info in ctx.cls.info.mro[1:-1]:\n        if \"attrs\" in super_info.metadata:\n            # Each class depends on the set of attributes in its attrs ancestors.\n            ctx.api.add_plugin_dependency(make_wildcard_trigger(super_info.fullname))\n\n            for data in super_info.metadata[\"attrs\"][\"attributes\"]:\n                # Only add an attribute if it hasn't been defined before.  This\n                # allows for overwriting attribute definitions by subclassing.\n                if data[\"name\"] not in taken_attr_names:\n                    a = Attribute.deserialize(super_info, data, ctx.api)\n                    a.expand_typevar_from_subtype(ctx.cls.info)\n                    super_attrs.append(a)\n                    taken_attr_names.add(a.name)\n    attributes = super_attrs + list(own_attrs.values())\n\n    # Check the init args for correct default-ness.  Note: This has to be done after all the\n    # attributes for all classes have been read, because subclasses can override parents.\n    last_default = False\n\n    for i, attribute in enumerate(attributes):\n        if not attribute.init:\n            continue\n\n        if attribute.kw_only:\n            # Keyword-only attributes don't care whether they are default or not.\n            continue\n\n        # If the issue comes from merging different classes, report it\n        # at the class definition point.\n        context = attribute.context if i >= len(super_attrs) else ctx.cls\n\n        if not attribute.has_default and last_default:\n            ctx.api.fail(\"Non-default attributes not allowed after default attributes.\", context)\n        last_default |= attribute.has_default\n\n    return attributes\n\n\ndef _add_empty_metadata(info: TypeInfo) -> None:\n    \"\"\"Add empty metadata to mark that we've finished processing this class.\"\"\"\n    info.metadata[\"attrs\"] = {\"attributes\": [], \"frozen\": False}\n\n\ndef _detect_auto_attribs(ctx: mypy.plugin.ClassDefContext) -> bool:\n    \"\"\"Return whether auto_attribs should be enabled or disabled.\n\n    It's disabled if there are any unannotated attribs()\n    \"\"\"\n    for stmt in ctx.cls.defs.body:\n        if isinstance(stmt, AssignmentStmt):\n            for lvalue in stmt.lvalues:\n                lvalues, rvalues = _parse_assignments(lvalue, stmt)\n\n                if len(lvalues) != len(rvalues):\n                    # This means we have some assignment that isn't 1 to 1.\n                    # It can't be an attrib.\n                    continue\n\n                for lhs, rvalue in zip(lvalues, rvalues):\n                    # Check if the right hand side is a call to an attribute maker.\n                    if (\n                        isinstance(rvalue, CallExpr)\n                        and isinstance(rvalue.callee, RefExpr)\n                        and rvalue.callee.fullname in attr_attrib_makers\n                        and not stmt.new_syntax\n                    ):\n                        # This means we have an attrib without an annotation and so\n                        # we can't do auto_attribs=True\n                        return False\n    return True\n\n\ndef _attributes_from_assignment(\n    ctx: mypy.plugin.ClassDefContext, stmt: AssignmentStmt, auto_attribs: bool, class_kw_only: bool\n) -> Iterable[Attribute]:\n    \"\"\"Return Attribute objects that are created by this assignment.\n\n    The assignments can look like this:\n        x = attr.ib()\n        x = y = attr.ib()\n        x, y = attr.ib(), attr.ib()\n    or if auto_attribs is enabled also like this:\n        x: type\n        x: type = default_value\n        x: type = attr.ib(...)\n    \"\"\"\n    for lvalue in stmt.lvalues:\n        lvalues, rvalues = _parse_assignments(lvalue, stmt)\n\n        if len(lvalues) != len(rvalues):\n            # This means we have some assignment that isn't 1 to 1.\n            # It can't be an attrib.\n            continue\n\n        for lhs, rvalue in zip(lvalues, rvalues):\n            # Check if the right hand side is a call to an attribute maker.\n            if (\n                isinstance(rvalue, CallExpr)\n                and isinstance(rvalue.callee, RefExpr)\n                and rvalue.callee.fullname in attr_attrib_makers\n            ):\n                attr = _attribute_from_attrib_maker(\n                    ctx, auto_attribs, class_kw_only, lhs, rvalue, stmt\n                )\n                if attr:\n                    yield attr\n            elif auto_attribs and stmt.type and stmt.new_syntax and not is_class_var(lhs):\n                yield _attribute_from_auto_attrib(ctx, class_kw_only, lhs, rvalue, stmt)\n\n\ndef _cleanup_decorator(stmt: Decorator, attr_map: dict[str, Attribute]) -> None:\n    \"\"\"Handle decorators in class bodies.\n\n    `x.default` will set a default value on x\n    `x.validator` and `x.default` will get removed to avoid throwing a type error.\n    \"\"\"\n    remove_me = []\n    for func_decorator in stmt.decorators:\n        if (\n            isinstance(func_decorator, MemberExpr)\n            and isinstance(func_decorator.expr, NameExpr)\n            and func_decorator.expr.name in attr_map\n        ):\n            if func_decorator.name == \"default\":\n                attr_map[func_decorator.expr.name].has_default = True\n\n            if func_decorator.name in (\"default\", \"validator\"):\n                # These are decorators on the attrib object that only exist during\n                # class creation time.  In order to not trigger a type error later we\n                # just remove them.  This might leave us with a Decorator with no\n                # decorators (Emperor's new clothes?)\n                # TODO: It would be nice to type-check these rather than remove them.\n                #       default should be Callable[[], T]\n                #       validator should be Callable[[Any, 'Attribute', T], Any]\n                #       where T is the type of the attribute.\n                remove_me.append(func_decorator)\n    for dec in remove_me:\n        stmt.decorators.remove(dec)\n\n\ndef _attribute_from_auto_attrib(\n    ctx: mypy.plugin.ClassDefContext,\n    class_kw_only: bool,\n    lhs: NameExpr,\n    rvalue: Expression,\n    stmt: AssignmentStmt,\n) -> Attribute:\n    \"\"\"Return an Attribute for a new type assignment.\"\"\"\n    name = unmangle(lhs.name)\n    # `x: int` (without equal sign) assigns rvalue to TempNode(AnyType())\n    has_rhs = not isinstance(rvalue, TempNode)\n    sym = ctx.cls.info.names.get(name)\n    init_type = sym.type if sym else None\n    return Attribute(name, None, ctx.cls.info, has_rhs, True, class_kw_only, None, stmt, init_type)\n\n\ndef _attribute_from_attrib_maker(\n    ctx: mypy.plugin.ClassDefContext,\n    auto_attribs: bool,\n    class_kw_only: bool,\n    lhs: NameExpr,\n    rvalue: CallExpr,\n    stmt: AssignmentStmt,\n) -> Attribute | None:\n    \"\"\"Return an Attribute from the assignment or None if you can't make one.\"\"\"\n    if auto_attribs and not stmt.new_syntax:\n        # auto_attribs requires an annotation on *every* attr.ib.\n        assert lhs.node is not None\n        ctx.api.msg.need_annotation_for_var(lhs.node, stmt)\n        return None\n\n    if len(stmt.lvalues) > 1:\n        ctx.api.fail(\"Too many names for one attribute\", stmt)\n        return None\n\n    # This is the type that belongs in the __init__ method for this attrib.\n    init_type = stmt.type\n\n    # Read all the arguments from the call.\n    init = _get_bool_argument(ctx, rvalue, \"init\", True)\n    # The class decorator kw_only value can be overridden by the attribute value\n    # See https://github.com/python-attrs/attrs/pull/1457\n    kw_only = _get_bool_argument(ctx, rvalue, \"kw_only\", class_kw_only)\n\n    # TODO: Check for attr.NOTHING\n    attr_has_default = bool(_get_argument(rvalue, \"default\"))\n    attr_has_factory = bool(_get_argument(rvalue, \"factory\"))\n\n    if attr_has_default and attr_has_factory:\n        ctx.api.fail('Can\\'t pass both \"default\" and \"factory\".', rvalue)\n    elif attr_has_factory:\n        attr_has_default = True\n\n    # If the type isn't set through annotation but is passed through `type=` use that.\n    type_arg = _get_argument(rvalue, \"type\")\n    if type_arg and not init_type:\n        try:\n            un_type = expr_to_unanalyzed_type(type_arg, ctx.api.options, ctx.api.is_stub_file)\n        except TypeTranslationError:\n            ctx.api.fail(\"Invalid argument to type\", type_arg)\n        else:\n            init_type = ctx.api.anal_type(un_type)\n            if init_type and isinstance(lhs.node, Var) and not lhs.node.type:\n                # If there is no annotation, add one.\n                lhs.node.type = init_type\n                lhs.is_inferred_def = False\n\n    # Note: convert is deprecated but works the same as converter.\n    converter = _get_argument(rvalue, \"converter\")\n    convert = _get_argument(rvalue, \"convert\")\n    if convert and converter:\n        ctx.api.fail('Can\\'t pass both \"convert\" and \"converter\".', rvalue)\n    elif convert:\n        ctx.api.fail(\"convert is deprecated, use converter\", rvalue)\n        converter = convert\n    converter_info = _parse_converter(ctx, converter)\n\n    # Custom alias might be defined:\n    alias = None\n    alias_expr = _get_argument(rvalue, \"alias\")\n    if alias_expr:\n        alias = ctx.api.parse_str_literal(alias_expr)\n        if alias is None:\n            ctx.api.fail(\n                '\"alias\" argument to attrs field must be a string literal',\n                rvalue,\n                code=LITERAL_REQ,\n            )\n    name = unmangle(lhs.name)\n    return Attribute(\n        name, alias, ctx.cls.info, attr_has_default, init, kw_only, converter_info, stmt, init_type\n    )\n\n\ndef _parse_converter(\n    ctx: mypy.plugin.ClassDefContext, converter_expr: Expression | None\n) -> Converter | None:\n    \"\"\"Return the Converter object from an Expression.\"\"\"\n    # TODO: Support complex converters, e.g. lambdas, calls, etc.\n    if not converter_expr:\n        return None\n    converter_info = Converter()\n    if (\n        isinstance(converter_expr, CallExpr)\n        and isinstance(converter_expr.callee, RefExpr)\n        and converter_expr.callee.fullname in attr_optional_converters\n        and converter_expr.args\n        and converter_expr.args[0]\n    ):\n        # Special handling for attr.converters.optional(type)\n        # We extract the type and add make the init_args Optional in Attribute.argument\n        converter_expr = converter_expr.args[0]\n        is_attr_converters_optional = True\n    else:\n        is_attr_converters_optional = False\n\n    converter_type: Type | None = None\n    if isinstance(converter_expr, RefExpr) and converter_expr.node:\n        if isinstance(converter_expr.node, FuncDef):\n            if converter_expr.node.type and isinstance(converter_expr.node.type, FunctionLike):\n                converter_type = converter_expr.node.type\n            else:  # The converter is an unannotated function.\n                converter_info.init_type = AnyType(TypeOfAny.unannotated)\n                return converter_info\n        elif isinstance(converter_expr.node, OverloadedFuncDef) and is_valid_overloaded_converter(\n            converter_expr.node\n        ):\n            converter_type = converter_expr.node.type\n        elif isinstance(converter_expr.node, TypeInfo):\n            converter_type = type_object_type(converter_expr.node, ctx.api.named_type)\n    elif (\n        isinstance(converter_expr, IndexExpr)\n        and isinstance(converter_expr.analyzed, TypeApplication)\n        and isinstance(converter_expr.base, RefExpr)\n        and isinstance(converter_expr.base.node, TypeInfo)\n    ):\n        # The converter is a generic type.\n        converter_type = type_object_type(converter_expr.base.node, ctx.api.named_type)\n        if isinstance(converter_type, CallableType):\n            converter_type = apply_generic_arguments(\n                converter_type,\n                converter_expr.analyzed.types,\n                ctx.api.msg.incompatible_typevar_value,\n                converter_type,\n            )\n        else:\n            converter_type = None\n\n    if isinstance(converter_expr, LambdaExpr):\n        # TODO: should we send a fail if converter_expr.min_args > 1?\n        converter_info.init_type = AnyType(TypeOfAny.unannotated)\n        return converter_info\n\n    if not converter_type:\n        # Signal that we have an unsupported converter.\n        ctx.api.fail(\n            \"Unsupported converter, only named functions, types and lambdas are currently \"\n            \"supported\",\n            converter_expr,\n        )\n        converter_info.init_type = AnyType(TypeOfAny.from_error)\n        return converter_info\n\n    converter_type = get_proper_type(converter_type)\n    if isinstance(converter_type, CallableType) and converter_type.arg_types:\n        converter_info.init_type = converter_type.arg_types[0]\n        if not is_attr_converters_optional:\n            converter_info.ret_type = converter_type.ret_type\n    elif isinstance(converter_type, Overloaded):\n        types: list[Type] = []\n        for item in converter_type.items:\n            # Walk the overloads looking for methods that can accept one argument.\n            num_arg_types = len(item.arg_types)\n            if not num_arg_types:\n                continue\n            if num_arg_types > 1 and any(kind == ARG_POS for kind in item.arg_kinds[1:]):\n                continue\n            types.append(item.arg_types[0])\n        # Make a union of all the valid types.\n        if types:\n            converter_info.init_type = make_simplified_union(types)\n\n    if is_attr_converters_optional and converter_info.init_type:\n        # If the converter was attr.converter.optional(type) then add None to\n        # the allowed init_type.\n        converter_info.init_type = UnionType.make_union([converter_info.init_type, NoneType()])\n\n    return converter_info\n\n\ndef is_valid_overloaded_converter(defn: OverloadedFuncDef) -> bool:\n    return all(\n        (not isinstance(item, Decorator) or isinstance(item.func.type, FunctionLike))\n        for item in defn.items\n    )\n\n\ndef _parse_assignments(\n    lvalue: Expression, stmt: AssignmentStmt\n) -> tuple[list[NameExpr], list[Expression]]:\n    \"\"\"Convert a possibly complex assignment expression into lists of lvalues and rvalues.\"\"\"\n    lvalues: list[NameExpr] = []\n    rvalues: list[Expression] = []\n    if isinstance(lvalue, (TupleExpr, ListExpr)):\n        if all(isinstance(item, NameExpr) for item in lvalue.items):\n            lvalues = cast(list[NameExpr], lvalue.items)\n        if isinstance(stmt.rvalue, (TupleExpr, ListExpr)):\n            rvalues = stmt.rvalue.items\n    elif isinstance(lvalue, NameExpr):\n        lvalues = [lvalue]\n        rvalues = [stmt.rvalue]\n    return lvalues, rvalues\n\n\ndef _add_order(ctx: mypy.plugin.ClassDefContext, adder: MethodAdder) -> None:\n    \"\"\"Generate all the ordering methods for this class.\"\"\"\n    bool_type = ctx.api.named_type(\"builtins.bool\")\n    object_type = ctx.api.named_type(\"builtins.object\")\n    # Make the types be:\n    #    AT = TypeVar('AT')\n    #    def __lt__(self: AT, other: AT) -> bool\n    # This way comparisons with subclasses will work correctly.\n    fullname = f\"{ctx.cls.info.fullname}.{SELF_TVAR_NAME}\"\n    tvd = TypeVarType(\n        SELF_TVAR_NAME,\n        fullname,\n        # Namespace is patched per-method below.\n        id=TypeVarId(-1, namespace=\"\"),\n        values=[],\n        upper_bound=object_type,\n        default=AnyType(TypeOfAny.from_omitted_generics),\n    )\n    self_tvar_expr = TypeVarExpr(\n        SELF_TVAR_NAME, fullname, [], object_type, AnyType(TypeOfAny.from_omitted_generics)\n    )\n    ctx.cls.info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)\n\n    for method in [\"__lt__\", \"__le__\", \"__gt__\", \"__ge__\"]:\n        namespace = f\"{ctx.cls.info.fullname}.{method}\"\n        tvd = tvd.copy_modified(id=TypeVarId(tvd.id.raw_id, namespace=namespace))\n        args = [Argument(Var(\"other\", tvd), tvd, None, ARG_POS)]\n        adder.add_method(method, args, bool_type, self_type=tvd, tvd=tvd)\n\n\ndef _make_frozen(ctx: mypy.plugin.ClassDefContext, attributes: list[Attribute]) -> None:\n    \"\"\"Turn all the attributes into properties to simulate frozen classes.\"\"\"\n    for attribute in attributes:\n        if attribute.name in ctx.cls.info.names:\n            # This variable belongs to this class so we can modify it.\n            node = ctx.cls.info.names[attribute.name].node\n            if not isinstance(node, Var):\n                # The superclass attribute was overridden with a non-variable.\n                # No need to do anything here, override will be verified during\n                # type checking.\n                continue\n            node.is_property = True\n        else:\n            # This variable belongs to a super class so create new Var so we\n            # can modify it.\n            var = Var(attribute.name, attribute.init_type)\n            var.info = ctx.cls.info\n            var._fullname = f\"{ctx.cls.info.fullname}.{var.name}\"\n            ctx.cls.info.names[var.name] = SymbolTableNode(MDEF, var)\n            var.is_property = True\n\n\ndef _add_init(\n    ctx: mypy.plugin.ClassDefContext,\n    attributes: list[Attribute],\n    adder: MethodAdder,\n    method_name: Literal[\"__init__\", \"__attrs_init__\"],\n) -> None:\n    \"\"\"Generate an __init__ method for the attributes and add it to the class.\"\"\"\n    # Convert attributes to arguments with kw_only arguments at the end of\n    # the argument list\n    pos_args = []\n    kw_only_args = []\n    sym_table = ctx.cls.info.names\n    for attribute in attributes:\n        if not attribute.init:\n            continue\n        if attribute.kw_only:\n            kw_only_args.append(attribute.argument(ctx))\n        else:\n            pos_args.append(attribute.argument(ctx))\n\n        # If the attribute is Final, present in `__init__` and has\n        # no default, make sure it doesn't error later.\n        if not attribute.has_default and attribute.name in sym_table:\n            sym_node = sym_table[attribute.name].node\n            if isinstance(sym_node, Var) and sym_node.is_final:\n                sym_node.final_set_in_init = True\n    args = pos_args + kw_only_args\n    if all(\n        # We use getattr rather than instance checks because the variable.type\n        # might be wrapped into a Union or some other type, but even non-Any\n        # types reliably track the fact that the argument was not annotated.\n        getattr(arg.variable.type, \"type_of_any\", None) == TypeOfAny.unannotated\n        for arg in args\n    ):\n        # This workaround makes --disallow-incomplete-defs usable with attrs,\n        # but is definitely suboptimal as a long-term solution.\n        # See https://github.com/python/mypy/issues/5954 for discussion.\n        for a in args:\n            a.variable.type = AnyType(TypeOfAny.implementation_artifact)\n            a.type_annotation = AnyType(TypeOfAny.implementation_artifact)\n    adder.add_method(method_name, args, NoneType())\n\n\ndef _add_attrs_magic_attribute(\n    ctx: mypy.plugin.ClassDefContext, attrs: list[tuple[str, Type | None]]\n) -> None:\n    any_type = AnyType(TypeOfAny.explicit)\n    attributes_types: list[Type] = [\n        ctx.api.named_type_or_none(\"attr.Attribute\", [attr_type or any_type]) or any_type\n        for _, attr_type in attrs\n    ]\n    fallback_type = ctx.api.named_type(\n        \"builtins.tuple\", [ctx.api.named_type_or_none(\"attr.Attribute\", [any_type]) or any_type]\n    )\n\n    attr_name = MAGIC_ATTR_CLS_NAME_TEMPLATE.format(ctx.cls.fullname.replace(\".\", \"_\"))\n    ti = ctx.api.basic_new_typeinfo(attr_name, fallback_type, 0)\n    for (name, _), attr_type in zip(attrs, attributes_types):\n        var = Var(name, attr_type)\n        var._fullname = name\n        var.is_property = True\n        proper_type = get_proper_type(attr_type)\n        if isinstance(proper_type, Instance):\n            var.info = proper_type.type\n        ti.names[name] = SymbolTableNode(MDEF, var, plugin_generated=True)\n    attributes_type = Instance(ti, [])\n\n    # We need to stash the type of the magic attribute so it can be\n    # loaded on cached runs.\n    ctx.cls.info.names[attr_name] = SymbolTableNode(MDEF, ti, plugin_generated=True)\n\n    add_attribute_to_class(\n        ctx.api,\n        ctx.cls,\n        MAGIC_ATTR_NAME,\n        TupleType(attributes_types, fallback=attributes_type),\n        fullname=f\"{ctx.cls.fullname}.{MAGIC_ATTR_NAME}\",\n        override_allow_incompatible=True,\n        is_classvar=True,\n    )\n\n\ndef _add_slots(ctx: mypy.plugin.ClassDefContext, attributes: list[Attribute]) -> None:\n    if any(p.slots is None for p in ctx.cls.info.mro[1:-1]):\n        # At least one type in mro (excluding `self` and `object`)\n        # does not have concrete `__slots__` defined. Ignoring.\n        return\n\n    # Unlike `@dataclasses.dataclass`, `__slots__` is rewritten here.\n    ctx.cls.info.slots = {attr.name for attr in attributes}\n\n    # Also, inject `__slots__` attribute to class namespace:\n    slots_type = TupleType(\n        [ctx.api.named_type(\"builtins.str\") for _ in attributes],\n        fallback=ctx.api.named_type(\"builtins.tuple\"),\n    )\n    add_attribute_to_class(api=ctx.api, cls=ctx.cls, name=\"__slots__\", typ=slots_type)\n\n\ndef _add_match_args(ctx: mypy.plugin.ClassDefContext, attributes: list[Attribute]) -> None:\n    if (\n        \"__match_args__\" not in ctx.cls.info.names\n        or ctx.cls.info.names[\"__match_args__\"].plugin_generated\n    ):\n        str_type = ctx.api.named_type(\"builtins.str\")\n        match_args = TupleType(\n            [\n                str_type.copy_modified(last_known_value=LiteralType(attr.name, fallback=str_type))\n                for attr in attributes\n                if not attr.kw_only and attr.init\n            ],\n            fallback=ctx.api.named_type(\"builtins.tuple\"),\n        )\n        add_attribute_to_class(api=ctx.api, cls=ctx.cls, name=\"__match_args__\", typ=match_args)\n\n\ndef _remove_hashability(ctx: mypy.plugin.ClassDefContext) -> None:\n    \"\"\"Remove hashability from a class.\"\"\"\n    add_attribute_to_class(\n        ctx.api, ctx.cls, \"__hash__\", NoneType(), is_classvar=True, overwrite_existing=True\n    )\n\n\nclass MethodAdder:\n    \"\"\"Helper to add methods to a TypeInfo.\n\n    ctx: The ClassDefCtx we are using on which we will add methods.\n    \"\"\"\n\n    # TODO: Combine this with the code build_namedtuple_typeinfo to support both.\n\n    def __init__(self, ctx: mypy.plugin.ClassDefContext) -> None:\n        self.ctx = ctx\n        self.self_type = fill_typevars(ctx.cls.info)\n\n    def add_method(\n        self,\n        method_name: str,\n        args: list[Argument],\n        ret_type: Type,\n        self_type: Type | None = None,\n        tvd: TypeVarType | None = None,\n    ) -> None:\n        \"\"\"Add a method: def <method_name>(self, <args>) -> <ret_type>): ... to info.\n\n        self_type: The type to use for the self argument or None to use the inferred self type.\n        tvd: If the method is generic these should be the type variables.\n        \"\"\"\n        self_type = self_type if self_type is not None else self.self_type\n        add_method_to_class(\n            self.ctx.api, self.ctx.cls, method_name, args, ret_type, self_type, tvd\n        )\n\n\ndef _get_attrs_init_type(typ: Instance) -> CallableType | None:\n    \"\"\"\n    If `typ` refers to an attrs class, get the type of its initializer method.\n    \"\"\"\n    magic_attr = typ.type.get(MAGIC_ATTR_NAME)\n    if magic_attr is None or not magic_attr.plugin_generated:\n        return None\n    init_method = typ.type.get_method(\"__init__\") or typ.type.get_method(ATTRS_INIT_NAME)\n    if not isinstance(init_method, FuncDef) or not isinstance(init_method.type, CallableType):\n        return None\n    return init_method.type\n\n\ndef _fail_not_attrs_class(ctx: mypy.plugin.FunctionSigContext, t: Type, parent_t: Type) -> None:\n    t_name = format_type_bare(t, ctx.api.options)\n    if parent_t is t:\n        msg = (\n            f'Argument 1 to \"evolve\" has a variable type \"{t_name}\" not bound to an attrs class'\n            if isinstance(t, TypeVarType)\n            else f'Argument 1 to \"evolve\" has incompatible type \"{t_name}\"; expected an attrs class'\n        )\n    else:\n        pt_name = format_type_bare(parent_t, ctx.api.options)\n        msg = (\n            f'Argument 1 to \"evolve\" has type \"{pt_name}\" whose item \"{t_name}\" is not bound to an attrs class'\n            if isinstance(t, TypeVarType)\n            else f'Argument 1 to \"evolve\" has incompatible type \"{pt_name}\" whose item \"{t_name}\" is not an attrs class'\n        )\n\n    ctx.api.fail(msg, ctx.context)\n\n\ndef _get_expanded_attr_types(\n    ctx: mypy.plugin.FunctionSigContext,\n    typ: ProperType,\n    display_typ: ProperType,\n    parent_typ: ProperType,\n) -> list[Mapping[str, Type]] | None:\n    \"\"\"\n    For a given type, determine what attrs classes it can be: for each class, return the field types.\n    For generic classes, the field types are expanded.\n    If the type contains Any or a non-attrs type, returns None; in the latter case, also reports an error.\n    \"\"\"\n    if isinstance(typ, AnyType):\n        return None\n    elif isinstance(typ, UnionType):\n        ret: list[Mapping[str, Type]] | None = []\n        for item in typ.relevant_items():\n            item = get_proper_type(item)\n            item_types = _get_expanded_attr_types(ctx, item, item, parent_typ)\n            if ret is not None and item_types is not None:\n                ret += item_types\n            else:\n                ret = None  # but keep iterating to emit all errors\n        return ret\n    elif isinstance(typ, TypeVarType):\n        return _get_expanded_attr_types(\n            ctx, get_proper_type(typ.upper_bound), display_typ, parent_typ\n        )\n    elif isinstance(typ, Instance):\n        init_func = _get_attrs_init_type(typ)\n        if init_func is None:\n            _fail_not_attrs_class(ctx, display_typ, parent_typ)\n            return None\n        init_func = expand_type_by_instance(init_func, typ)\n        # [1:] to skip the self argument of AttrClass.__init__\n        field_names = cast(list[str], init_func.arg_names[1:])\n        field_types = init_func.arg_types[1:]\n        return [dict(zip(field_names, field_types))]\n    else:\n        _fail_not_attrs_class(ctx, display_typ, parent_typ)\n        return None\n\n\ndef _meet_fields(types: list[Mapping[str, Type]]) -> Mapping[str, Type]:\n    \"\"\"\n    \"Meet\" the fields of a list of attrs classes, i.e. for each field, its new type will be the lower bound.\n    \"\"\"\n    field_to_types = defaultdict(list)\n    for fields in types:\n        for name, typ in fields.items():\n            field_to_types[name].append(typ)\n\n    return {\n        name: (\n            get_proper_type(reduce(meet_types, f_types))\n            if len(f_types) == len(types)\n            else UninhabitedType()\n        )\n        for name, f_types in field_to_types.items()\n    }\n\n\ndef evolve_function_sig_callback(ctx: mypy.plugin.FunctionSigContext) -> CallableType:\n    \"\"\"\n    Generate a signature for the 'attr.evolve' function that's specific to the call site\n    and dependent on the type of the first argument.\n    \"\"\"\n    if len(ctx.args) != 2:\n        # Ideally the name and context should be callee's, but we don't have it in FunctionSigContext.\n        ctx.api.fail(f'\"{ctx.default_signature.name}\" has unexpected type annotation', ctx.context)\n        return ctx.default_signature\n\n    if len(ctx.args[0]) != 1:\n        return ctx.default_signature  # leave it to the type checker to complain\n\n    inst_arg = ctx.args[0][0]\n    inst_type = get_proper_type(ctx.api.get_expression_type(inst_arg))\n    inst_type_str = format_type_bare(inst_type, ctx.api.options)\n\n    attr_types = _get_expanded_attr_types(ctx, inst_type, inst_type, inst_type)\n    if attr_types is None:\n        return ctx.default_signature\n    fields = _meet_fields(attr_types)\n\n    return CallableType(\n        arg_names=[\"inst\", *fields.keys()],\n        arg_kinds=[ARG_POS] + [ARG_NAMED_OPT] * len(fields),\n        arg_types=[inst_type, *fields.values()],\n        ret_type=inst_type,\n        fallback=ctx.default_signature.fallback,\n        name=f\"{ctx.default_signature.name} of {inst_type_str}\",\n    )\n\n\ndef fields_function_sig_callback(ctx: mypy.plugin.FunctionSigContext) -> CallableType:\n    \"\"\"Provide the signature for `attrs.fields`.\"\"\"\n    if len(ctx.args) != 1 or len(ctx.args[0]) != 1:\n        return ctx.default_signature\n\n    proper_type = get_proper_type(ctx.api.get_expression_type(ctx.args[0][0]))\n\n    # fields(Any) -> Any, fields(type[Any]) -> Any\n    if (\n        isinstance(proper_type, AnyType)\n        or isinstance(proper_type, TypeType)\n        and isinstance(proper_type.item, AnyType)\n    ):\n        return ctx.default_signature\n\n    cls = None\n    arg_types = ctx.default_signature.arg_types\n\n    if isinstance(proper_type, TypeVarType):\n        inner = get_proper_type(proper_type.upper_bound)\n        if isinstance(inner, Instance):\n            # We need to work arg_types to compensate for the attrs stubs.\n            arg_types = [proper_type]\n            cls = inner.type\n    elif isinstance(proper_type, CallableType):\n        cls = proper_type.type_object()\n\n    if cls is not None and MAGIC_ATTR_NAME in cls.names:\n        # This is a proper attrs class.\n        ret_type = cls.names[MAGIC_ATTR_NAME].type\n        assert ret_type is not None\n        return ctx.default_signature.copy_modified(arg_types=arg_types, ret_type=ret_type)\n\n    return ctx.default_signature\n"
  },
  {
    "path": "mypy/plugins/common.py",
    "content": "from __future__ import annotations\n\nfrom typing import NamedTuple\n\nfrom mypy.argmap import map_actuals_to_formals\nfrom mypy.fixup import TypeFixer\nfrom mypy.nodes import (\n    ARG_POS,\n    MDEF,\n    SYMBOL_FUNCBASE_TYPES,\n    Argument,\n    Block,\n    CallExpr,\n    ClassDef,\n    Decorator,\n    Expression,\n    FuncDef,\n    JsonDict,\n    NameExpr,\n    Node,\n    OverloadedFuncDef,\n    PassStmt,\n    RefExpr,\n    SymbolTableNode,\n    TypeInfo,\n    Var,\n)\nfrom mypy.plugin import CheckerPluginInterface, ClassDefContext, SemanticAnalyzerPluginInterface\nfrom mypy.semanal_shared import (\n    ALLOW_INCOMPATIBLE_OVERRIDE,\n    parse_bool,\n    require_bool_literal_argument,\n    set_callable_name,\n)\nfrom mypy.typeops import try_getting_str_literals as try_getting_str_literals\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Type,\n    TypeOfAny,\n    TypeType,\n    TypeVarType,\n    deserialize_type,\n    get_proper_type,\n)\nfrom mypy.types_utils import is_overlapping_none\nfrom mypy.typevars import fill_typevars\nfrom mypy.util import get_unique_redefinition_name\n\n\ndef _get_decorator_bool_argument(ctx: ClassDefContext, name: str, default: bool) -> bool:\n    \"\"\"Return the bool argument for the decorator.\n\n    This handles both @decorator(...) and @decorator.\n    \"\"\"\n    if isinstance(ctx.reason, CallExpr):\n        return _get_bool_argument(ctx, ctx.reason, name, default)\n    else:\n        return default\n\n\ndef _get_bool_argument(ctx: ClassDefContext, expr: CallExpr, name: str, default: bool) -> bool:\n    \"\"\"Return the boolean value for an argument to a call or the\n    default if it's not found.\n    \"\"\"\n    attr_value = _get_argument(expr, name)\n    if attr_value:\n        return require_bool_literal_argument(ctx.api, attr_value, name, default)\n    return default\n\n\ndef _get_argument(call: CallExpr, name: str) -> Expression | None:\n    \"\"\"Return the expression for the specific argument.\"\"\"\n    # To do this we use the CallableType of the callee to find the FormalArgument,\n    # then walk the actual CallExpr looking for the appropriate argument.\n    #\n    # Note: I'm not hard-coding the index so that in the future we can support other\n    # attrib and class makers.\n    callee_type = _get_callee_type(call)\n    if not callee_type:\n        return None\n\n    argument = callee_type.argument_by_name(name)\n    if not argument:\n        return None\n    assert argument.name\n\n    for i, (attr_name, attr_value) in enumerate(zip(call.arg_names, call.args)):\n        if argument.pos is not None and not attr_name and i == argument.pos:\n            return attr_value\n        if attr_name == argument.name:\n            return attr_value\n\n    return None\n\n\ndef find_shallow_matching_overload_item(overload: Overloaded, call: CallExpr) -> CallableType:\n    \"\"\"Perform limited lookup of a matching overload item.\n\n    Full overload resolution is only supported during type checking, but plugins\n    sometimes need to resolve overloads. This can be used in some such use cases.\n\n    Resolve overloads based on these things only:\n\n    * Match using argument kinds and names\n    * If formal argument has type None, only accept the \"None\" expression in the callee\n    * If formal argument has type Literal[True] or Literal[False], only accept the\n      relevant bool literal\n\n    Return the first matching overload item, or the last one if nothing matches.\n    \"\"\"\n    for item in overload.items[:-1]:\n        ok = True\n        mapped = map_actuals_to_formals(\n            call.arg_kinds,\n            call.arg_names,\n            item.arg_kinds,\n            item.arg_names,\n            lambda i: AnyType(TypeOfAny.special_form),\n        )\n\n        # Look for extra actuals\n        matched_actuals = set()\n        for actuals in mapped:\n            matched_actuals.update(actuals)\n        if any(i not in matched_actuals for i in range(len(call.args))):\n            ok = False\n\n        for arg_type, kind, actuals in zip(item.arg_types, item.arg_kinds, mapped):\n            if kind.is_required() and not actuals:\n                # Missing required argument\n                ok = False\n                break\n            elif actuals:\n                args = [call.args[i] for i in actuals]\n                arg_type = get_proper_type(arg_type)\n                arg_none = any(isinstance(arg, NameExpr) and arg.name == \"None\" for arg in args)\n                if isinstance(arg_type, NoneType):\n                    if not arg_none:\n                        ok = False\n                        break\n                elif (\n                    arg_none\n                    and not is_overlapping_none(arg_type)\n                    and not (\n                        isinstance(arg_type, Instance)\n                        and arg_type.type.fullname == \"builtins.object\"\n                    )\n                    and not isinstance(arg_type, AnyType)\n                ):\n                    ok = False\n                    break\n                elif isinstance(arg_type, LiteralType) and isinstance(arg_type.value, bool):\n                    if not any(parse_bool(arg) == arg_type.value for arg in args):\n                        ok = False\n                        break\n        if ok:\n            return item\n    return overload.items[-1]\n\n\ndef _get_callee_type(call: CallExpr) -> CallableType | None:\n    \"\"\"Return the type of the callee, regardless of its syntactic form.\"\"\"\n\n    callee_node: Node | None = call.callee\n\n    if isinstance(callee_node, RefExpr):\n        callee_node = callee_node.node\n\n    # Some decorators may be using typing.dataclass_transform, which is itself a decorator, so we\n    # need to unwrap them to get at the true callee\n    if isinstance(callee_node, Decorator):\n        callee_node = callee_node.func\n\n    if isinstance(callee_node, (Var, SYMBOL_FUNCBASE_TYPES)) and callee_node.type:\n        callee_node_type = get_proper_type(callee_node.type)\n        if isinstance(callee_node_type, Overloaded):\n            return find_shallow_matching_overload_item(callee_node_type, call)\n        elif isinstance(callee_node_type, CallableType):\n            return callee_node_type\n\n    return None\n\n\ndef add_method(\n    ctx: ClassDefContext,\n    name: str,\n    args: list[Argument],\n    return_type: Type,\n    self_type: Type | None = None,\n    tvar_def: TypeVarType | None = None,\n    is_classmethod: bool = False,\n    is_staticmethod: bool = False,\n) -> None:\n    \"\"\"\n    Adds a new method to a class.\n    Deprecated, use add_method_to_class() instead.\n    \"\"\"\n    add_method_to_class(\n        ctx.api,\n        ctx.cls,\n        name=name,\n        args=args,\n        return_type=return_type,\n        self_type=self_type,\n        tvar_def=tvar_def,\n        is_classmethod=is_classmethod,\n        is_staticmethod=is_staticmethod,\n    )\n\n\nclass MethodSpec(NamedTuple):\n    \"\"\"Represents a method signature to be added, except for `name`.\"\"\"\n\n    args: list[Argument]\n    return_type: Type\n    self_type: Type | None = None\n    tvar_defs: list[TypeVarType] | None = None\n\n\ndef add_method_to_class(\n    api: SemanticAnalyzerPluginInterface | CheckerPluginInterface,\n    cls: ClassDef,\n    name: str,\n    # MethodSpec items kept for backward compatibility:\n    args: list[Argument],\n    return_type: Type,\n    self_type: Type | None = None,\n    tvar_def: list[TypeVarType] | TypeVarType | None = None,\n    is_classmethod: bool = False,\n    is_staticmethod: bool = False,\n) -> FuncDef | Decorator:\n    \"\"\"Adds a new method to a class definition.\"\"\"\n    _prepare_class_namespace(cls, name)\n\n    if tvar_def is not None and not isinstance(tvar_def, list):\n        tvar_def = [tvar_def]\n\n    func, sym = _add_method_by_spec(\n        api,\n        cls.info,\n        name,\n        MethodSpec(args=args, return_type=return_type, self_type=self_type, tvar_defs=tvar_def),\n        is_classmethod=is_classmethod,\n        is_staticmethod=is_staticmethod,\n    )\n    cls.info.names[name] = sym\n    cls.info.defn.defs.body.append(func)\n    return func\n\n\ndef add_overloaded_method_to_class(\n    api: SemanticAnalyzerPluginInterface | CheckerPluginInterface,\n    cls: ClassDef,\n    name: str,\n    items: list[MethodSpec],\n    is_classmethod: bool = False,\n    is_staticmethod: bool = False,\n) -> OverloadedFuncDef:\n    \"\"\"Adds a new overloaded method to a class definition.\"\"\"\n    assert len(items) >= 2, \"Overloads must contain at least two cases\"\n\n    # Save old definition, if it exists.\n    _prepare_class_namespace(cls, name)\n\n    # Create function bodies for each passed method spec.\n    funcs: list[Decorator | FuncDef] = []\n    for item in items:\n        func, _sym = _add_method_by_spec(\n            api,\n            cls.info,\n            name=name,\n            spec=item,\n            is_classmethod=is_classmethod,\n            is_staticmethod=is_staticmethod,\n        )\n        if isinstance(func, FuncDef):\n            var = Var(func.name, func.type)\n            var.set_line(func.line)\n            func.is_decorated = True\n\n            deco = Decorator(func, [], var)\n        else:\n            deco = func\n        deco.is_overload = True\n        funcs.append(deco)\n\n    # Create the final OverloadedFuncDef node:\n    overload_def = OverloadedFuncDef(funcs)\n    overload_def.info = cls.info\n    overload_def.is_class = is_classmethod\n    overload_def.is_static = is_staticmethod\n    sym = SymbolTableNode(MDEF, overload_def)\n    sym.plugin_generated = True\n\n    cls.info.names[name] = sym\n    cls.info.defn.defs.body.append(overload_def)\n    return overload_def\n\n\ndef _prepare_class_namespace(cls: ClassDef, name: str) -> None:\n    info = cls.info\n    assert info\n\n    # First remove any previously generated methods with the same name\n    # to avoid clashes and problems in the semantic analyzer.\n    if name in info.names:\n        sym = info.names[name]\n        if sym.plugin_generated and isinstance(sym.node, FuncDef):\n            cls.defs.body.remove(sym.node)\n\n    # NOTE: we would like the plugin generated node to dominate, but we still\n    # need to keep any existing definitions so they get semantically analyzed.\n    if name in info.names:\n        # Get a nice unique name instead.\n        r_name = get_unique_redefinition_name(name, info.names)\n        info.names[r_name] = info.names[name]\n\n\ndef _add_method_by_spec(\n    api: SemanticAnalyzerPluginInterface | CheckerPluginInterface,\n    info: TypeInfo,\n    name: str,\n    spec: MethodSpec,\n    *,\n    is_classmethod: bool,\n    is_staticmethod: bool,\n) -> tuple[FuncDef | Decorator, SymbolTableNode]:\n    args, return_type, self_type, tvar_defs = spec\n\n    assert not (\n        is_classmethod is True and is_staticmethod is True\n    ), \"Can't add a new method that's both staticmethod and classmethod.\"\n\n    if isinstance(api, SemanticAnalyzerPluginInterface):\n        function_type = api.named_type(\"builtins.function\")\n    else:\n        function_type = api.named_generic_type(\"builtins.function\", [])\n\n    if is_classmethod:\n        self_type = self_type or TypeType(fill_typevars(info))\n        first = [Argument(Var(\"_cls\"), self_type, None, ARG_POS, True)]\n    elif is_staticmethod:\n        first = []\n    else:\n        self_type = self_type or fill_typevars(info)\n        first = [Argument(Var(\"self\"), self_type, None, ARG_POS)]\n    args = first + args\n\n    arg_types, arg_names, arg_kinds = [], [], []\n    for arg in args:\n        assert arg.type_annotation, \"All arguments must be fully typed.\"\n        arg_types.append(arg.type_annotation)\n        arg_names.append(arg.variable.name)\n        arg_kinds.append(arg.kind)\n\n    signature = CallableType(arg_types, arg_kinds, arg_names, return_type, function_type)\n    if tvar_defs:\n        signature.variables = tuple(tvar_defs)\n\n    func = FuncDef(name, args, Block([PassStmt()]))\n    func.info = info\n    func.type = set_callable_name(signature, func)\n    func.is_class = is_classmethod\n    func.is_static = is_staticmethod\n    func._fullname = info.fullname + \".\" + name\n    func.line = info.line\n\n    # Add decorator for is_staticmethod. It's unnecessary for is_classmethod.\n    if is_staticmethod:\n        func.is_decorated = True\n        v = Var(name, func.type)\n        v.info = info\n        v._fullname = func._fullname\n        v.is_staticmethod = True\n        dec = Decorator(func, [], v)\n        dec.line = info.line\n        sym = SymbolTableNode(MDEF, dec)\n        sym.plugin_generated = True\n        return dec, sym\n\n    sym = SymbolTableNode(MDEF, func)\n    sym.plugin_generated = True\n    return func, sym\n\n\ndef add_attribute_to_class(\n    api: SemanticAnalyzerPluginInterface,\n    cls: ClassDef,\n    name: str,\n    typ: Type,\n    final: bool = False,\n    no_serialize: bool = False,\n    override_allow_incompatible: bool = False,\n    fullname: str | None = None,\n    is_classvar: bool = False,\n    overwrite_existing: bool = False,\n) -> Var:\n    \"\"\"\n    Adds a new attribute to a class definition.\n    This currently only generates the symbol table entry and no corresponding AssignmentStatement\n    \"\"\"\n    info = cls.info\n\n    # NOTE: we would like the plugin generated node to dominate, but we still\n    # need to keep any existing definitions so they get semantically analyzed.\n    if name in info.names and not overwrite_existing:\n        # Get a nice unique name instead.\n        r_name = get_unique_redefinition_name(name, info.names)\n        info.names[r_name] = info.names[name]\n\n    node = Var(name, typ)\n    node.info = info\n    node.is_final = final\n    node.is_classvar = is_classvar\n    if name in ALLOW_INCOMPATIBLE_OVERRIDE:\n        node.allow_incompatible_override = True\n    else:\n        node.allow_incompatible_override = override_allow_incompatible\n\n    if fullname:\n        node._fullname = fullname\n    else:\n        node._fullname = info.fullname + \".\" + name\n\n    info.names[name] = SymbolTableNode(\n        MDEF, node, plugin_generated=True, no_serialize=no_serialize\n    )\n    return node\n\n\ndef deserialize_and_fixup_type(data: str | JsonDict, api: SemanticAnalyzerPluginInterface) -> Type:\n    typ = deserialize_type(data)\n    typ.accept(TypeFixer(api.modules, allow_missing=False))\n    return typ\n"
  },
  {
    "path": "mypy/plugins/constants.py",
    "content": "\"\"\"Constant definitions for plugins kept here to help with import cycles.\"\"\"\n\nfrom typing import Final\n\nfrom mypy.semanal_enum import ENUM_BASES\n\nSINGLEDISPATCH_TYPE: Final = \"functools._SingleDispatchCallable\"\nSINGLEDISPATCH_REGISTER_METHOD: Final = f\"{SINGLEDISPATCH_TYPE}.register\"\nSINGLEDISPATCH_CALLABLE_CALL_METHOD: Final = f\"{SINGLEDISPATCH_TYPE}.__call__\"\nSINGLEDISPATCH_REGISTER_RETURN_CLASS: Final = \"_SingleDispatchRegisterCallable\"\nSINGLEDISPATCH_REGISTER_CALLABLE_CALL_METHOD: Final = (\n    f\"functools.{SINGLEDISPATCH_REGISTER_RETURN_CLASS}.__call__\"\n)\n\nENUM_NAME_ACCESS: Final = {f\"{prefix}.name\" for prefix in ENUM_BASES} | {\n    f\"{prefix}._name_\" for prefix in ENUM_BASES\n}\nENUM_VALUE_ACCESS: Final = {f\"{prefix}.value\" for prefix in ENUM_BASES} | {\n    f\"{prefix}._value_\" for prefix in ENUM_BASES\n}\n"
  },
  {
    "path": "mypy/plugins/ctypes.py",
    "content": "\"\"\"Plugin to provide accurate types for some parts of the ctypes module.\"\"\"\n\nfrom __future__ import annotations\n\n# Fully qualified instead of \"from mypy.plugin import ...\" to avoid circular import problems.\nimport mypy.plugin\nfrom mypy import nodes\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.messages import format_type\nfrom mypy.subtypes import is_subtype\nfrom mypy.typeops import make_simplified_union\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    NoneType,\n    ProperType,\n    Type,\n    TypeOfAny,\n    UnionType,\n    flatten_nested_unions,\n    get_proper_type,\n)\n\n\ndef _find_simplecdata_base_arg(\n    tp: Instance, api: mypy.plugin.CheckerPluginInterface\n) -> ProperType | None:\n    \"\"\"Try to find a parametrized _SimpleCData in tp's bases and return its single type argument.\n\n    None is returned if _SimpleCData appears nowhere in tp's (direct or indirect) bases.\n    \"\"\"\n    if tp.type.has_base(\"_ctypes._SimpleCData\"):\n        simplecdata_base = map_instance_to_supertype(\n            tp,\n            api.named_generic_type(\"_ctypes._SimpleCData\", [AnyType(TypeOfAny.special_form)]).type,\n        )\n        assert len(simplecdata_base.args) == 1, \"_SimpleCData takes exactly one type argument\"\n        return get_proper_type(simplecdata_base.args[0])\n    return None\n\n\ndef _autoconvertible_to_cdata(tp: Type, api: mypy.plugin.CheckerPluginInterface) -> Type:\n    \"\"\"Get a type that is compatible with all types that can be implicitly converted to the given\n    CData type.\n\n    Examples:\n    * c_int -> Union[c_int, int]\n    * c_char_p -> Union[c_char_p, bytes, int, NoneType]\n    * MyStructure -> MyStructure\n    \"\"\"\n    allowed_types = []\n    # If tp is a union, we allow all types that are convertible to at least one of the union\n    # items. This is not quite correct - strictly speaking, only types convertible to *all* of the\n    # union items should be allowed. This may be worth changing in the future, but the more\n    # correct algorithm could be too strict to be useful.\n    for t in flatten_nested_unions([tp]):\n        t = get_proper_type(t)\n        # Every type can be converted from itself (obviously).\n        allowed_types.append(t)\n        if isinstance(t, Instance):\n            unboxed = _find_simplecdata_base_arg(t, api)\n            if unboxed is not None:\n                # If _SimpleCData appears in tp's (direct or indirect) bases, its type argument\n                # specifies the type's \"unboxed\" version, which can always be converted back to\n                # the original \"boxed\" type.\n                allowed_types.append(unboxed)\n\n                if t.type.has_base(\"ctypes._PointerLike\"):\n                    # Pointer-like _SimpleCData subclasses can also be converted from\n                    # an int or None.\n                    allowed_types.append(api.named_generic_type(\"builtins.int\", []))\n                    allowed_types.append(NoneType())\n\n    return make_simplified_union(allowed_types)\n\n\ndef _autounboxed_cdata(tp: Type) -> ProperType:\n    \"\"\"Get the auto-unboxed version of a CData type, if applicable.\n\n    For *direct* _SimpleCData subclasses, the only type argument of _SimpleCData in the bases list\n    is returned.\n    For all other CData types, including indirect _SimpleCData subclasses, tp is returned as-is.\n    \"\"\"\n    tp = get_proper_type(tp)\n\n    if isinstance(tp, UnionType):\n        return make_simplified_union([_autounboxed_cdata(t) for t in tp.items])\n    elif isinstance(tp, Instance):\n        for base in tp.type.bases:\n            if base.type.fullname == \"_ctypes._SimpleCData\":\n                # If tp has _SimpleCData as a direct base class,\n                # the auto-unboxed type is the single type argument of the _SimpleCData type.\n                assert len(base.args) == 1\n                return get_proper_type(base.args[0])\n    # If tp is not a concrete type, or if there is no _SimpleCData in the bases,\n    # the type is not auto-unboxed.\n    return tp\n\n\ndef _get_array_element_type(tp: Type) -> ProperType | None:\n    \"\"\"Get the element type of the Array type tp, or None if not specified.\"\"\"\n    tp = get_proper_type(tp)\n    if isinstance(tp, Instance):\n        assert tp.type.fullname == \"_ctypes.Array\"\n        if len(tp.args) == 1:\n            return get_proper_type(tp.args[0])\n    return None\n\n\ndef array_constructor_callback(ctx: mypy.plugin.FunctionContext) -> Type:\n    \"\"\"Callback to provide an accurate signature for the ctypes.Array constructor.\"\"\"\n    # Extract the element type from the constructor's return type, i. e. the type of the array\n    # being constructed.\n    et = _get_array_element_type(ctx.default_return_type)\n    if et is not None:\n        allowed = _autoconvertible_to_cdata(et, ctx.api)\n        assert (\n            len(ctx.arg_types) == 1\n        ), \"The stub of the ctypes.Array constructor should have a single vararg parameter\"\n        for arg_num, (arg_kind, arg_type) in enumerate(zip(ctx.arg_kinds[0], ctx.arg_types[0]), 1):\n            if arg_kind == nodes.ARG_POS and not is_subtype(arg_type, allowed):\n                ctx.api.msg.fail(\n                    \"Array constructor argument {} of type {}\"\n                    \" is not convertible to the array element type {}\".format(\n                        arg_num,\n                        format_type(arg_type, ctx.api.options),\n                        format_type(et, ctx.api.options),\n                    ),\n                    ctx.context,\n                )\n            elif arg_kind == nodes.ARG_STAR:\n                ty = ctx.api.named_generic_type(\"typing.Iterable\", [allowed])\n                if not is_subtype(arg_type, ty):\n                    it = ctx.api.named_generic_type(\"typing.Iterable\", [et])\n                    ctx.api.msg.fail(\n                        \"Array constructor argument {} of type {}\"\n                        \" is not convertible to the array element type {}\".format(\n                            arg_num,\n                            format_type(arg_type, ctx.api.options),\n                            format_type(it, ctx.api.options),\n                        ),\n                        ctx.context,\n                    )\n\n    return ctx.default_return_type\n\n\ndef array_getitem_callback(ctx: mypy.plugin.MethodContext) -> Type:\n    \"\"\"Callback to provide an accurate return type for ctypes.Array.__getitem__.\"\"\"\n    et = _get_array_element_type(ctx.type)\n    if et is not None:\n        unboxed = _autounboxed_cdata(et)\n        assert (\n            len(ctx.arg_types) == 1\n        ), \"The stub of ctypes.Array.__getitem__ should have exactly one parameter\"\n        assert (\n            len(ctx.arg_types[0]) == 1\n        ), \"ctypes.Array.__getitem__'s parameter should not be variadic\"\n        index_type = get_proper_type(ctx.arg_types[0][0])\n        if isinstance(index_type, Instance):\n            if index_type.type.has_base(\"builtins.int\"):\n                return unboxed\n            elif index_type.type.has_base(\"builtins.slice\"):\n                return ctx.api.named_generic_type(\"builtins.list\", [unboxed])\n    return ctx.default_return_type\n\n\ndef array_setitem_callback(ctx: mypy.plugin.MethodSigContext) -> CallableType:\n    \"\"\"Callback to provide an accurate signature for ctypes.Array.__setitem__.\"\"\"\n    et = _get_array_element_type(ctx.type)\n    if et is not None:\n        allowed = _autoconvertible_to_cdata(et, ctx.api)\n        assert len(ctx.default_signature.arg_types) == 2\n        index_type = get_proper_type(ctx.default_signature.arg_types[0])\n        if isinstance(index_type, Instance):\n            arg_type = None\n            if index_type.type.has_base(\"builtins.int\"):\n                arg_type = allowed\n            elif index_type.type.has_base(\"builtins.slice\"):\n                arg_type = ctx.api.named_generic_type(\"builtins.list\", [allowed])\n            if arg_type is not None:\n                # Note: arg_type can only be None if index_type is invalid, in which case we use\n                # the default signature and let mypy report an error about it.\n                return ctx.default_signature.copy_modified(\n                    arg_types=ctx.default_signature.arg_types[:1] + [arg_type]\n                )\n    return ctx.default_signature\n\n\ndef array_iter_callback(ctx: mypy.plugin.MethodContext) -> Type:\n    \"\"\"Callback to provide an accurate return type for ctypes.Array.__iter__.\"\"\"\n    et = _get_array_element_type(ctx.type)\n    if et is not None:\n        unboxed = _autounboxed_cdata(et)\n        return ctx.api.named_generic_type(\"typing.Iterator\", [unboxed])\n    return ctx.default_return_type\n\n\ndef array_value_callback(ctx: mypy.plugin.AttributeContext) -> Type:\n    \"\"\"Callback to provide an accurate type for ctypes.Array.value.\"\"\"\n    et = _get_array_element_type(ctx.type)\n    if et is not None:\n        types: list[Type] = []\n        for tp in flatten_nested_unions([et]):\n            tp = get_proper_type(tp)\n            if isinstance(tp, AnyType):\n                types.append(AnyType(TypeOfAny.from_another_any, source_any=tp))\n            elif isinstance(tp, Instance) and tp.type.fullname == \"ctypes.c_char\":\n                types.append(ctx.api.named_generic_type(\"builtins.bytes\", []))\n            elif isinstance(tp, Instance) and tp.type.fullname == \"ctypes.c_wchar\":\n                types.append(ctx.api.named_generic_type(\"builtins.str\", []))\n            else:\n                ctx.api.msg.fail(\n                    'Array attribute \"value\" is only available'\n                    ' with element type \"c_char\" or \"c_wchar\", not {}'.format(\n                        format_type(et, ctx.api.options)\n                    ),\n                    ctx.context,\n                )\n        return make_simplified_union(types)\n    return ctx.default_attr_type\n\n\ndef array_raw_callback(ctx: mypy.plugin.AttributeContext) -> Type:\n    \"\"\"Callback to provide an accurate type for ctypes.Array.raw.\"\"\"\n    et = _get_array_element_type(ctx.type)\n    if et is not None:\n        types: list[Type] = []\n        for tp in flatten_nested_unions([et]):\n            tp = get_proper_type(tp)\n            if (\n                isinstance(tp, AnyType)\n                or isinstance(tp, Instance)\n                and tp.type.fullname == \"ctypes.c_char\"\n            ):\n                types.append(ctx.api.named_generic_type(\"builtins.bytes\", []))\n            else:\n                ctx.api.msg.fail(\n                    'Array attribute \"raw\" is only available'\n                    ' with element type \"c_char\", not {}'.format(format_type(et, ctx.api.options)),\n                    ctx.context,\n                )\n        return make_simplified_union(types)\n    return ctx.default_attr_type\n"
  },
  {
    "path": "mypy/plugins/dataclasses.py",
    "content": "\"\"\"Plugin that provides support for dataclasses.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom typing import TYPE_CHECKING, Final, Literal\n\nfrom mypy import errorcodes, message_registry\nfrom mypy.expandtype import expand_type, expand_type_by_instance\nfrom mypy.meet import meet_types\nfrom mypy.messages import format_type_bare\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_NAMED_OPT,\n    ARG_OPT,\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    MDEF,\n    Argument,\n    AssignmentStmt,\n    Block,\n    CallExpr,\n    ClassDef,\n    Context,\n    DataclassTransformSpec,\n    Decorator,\n    EllipsisExpr,\n    Expression,\n    FuncDef,\n    FuncItem,\n    IfStmt,\n    JsonDict,\n    NameExpr,\n    Node,\n    PlaceholderNode,\n    RefExpr,\n    Statement,\n    SymbolTableNode,\n    TempNode,\n    TypeAlias,\n    TypeInfo,\n    TypeVarExpr,\n    Var,\n)\nfrom mypy.plugin import ClassDefContext, FunctionSigContext, SemanticAnalyzerPluginInterface\nfrom mypy.plugins.common import (\n    _get_callee_type,\n    _get_decorator_bool_argument,\n    add_attribute_to_class,\n    add_method_to_class,\n    deserialize_and_fixup_type,\n)\nfrom mypy.semanal_shared import find_dataclass_transform_spec, require_bool_literal_argument\nfrom mypy.server.trigger import make_wildcard_trigger\nfrom mypy.state import state\nfrom mypy.typeops import map_type_from_supertype, try_getting_literals_from_type\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeVarId,\n    TypeVarType,\n    UninhabitedType,\n    UnionType,\n    get_proper_type,\n)\nfrom mypy.typevars import fill_typevars\n\nif TYPE_CHECKING:\n    from mypy.checker import TypeChecker\n\n# The set of decorators that generate dataclasses.\ndataclass_makers: Final = {\"dataclass\", \"dataclasses.dataclass\"}\n# Default field specifiers for dataclasses\nDATACLASS_FIELD_SPECIFIERS: Final = (\"dataclasses.Field\", \"dataclasses.field\")\n\n\nSELF_TVAR_NAME: Final = \"_DT\"\n_TRANSFORM_SPEC_FOR_DATACLASSES: Final = DataclassTransformSpec(\n    eq_default=True,\n    order_default=False,\n    kw_only_default=False,\n    frozen_default=False,\n    field_specifiers=DATACLASS_FIELD_SPECIFIERS,\n)\n_INTERNAL_REPLACE_SYM_NAME: Final = \"__mypy-replace\"\n_INTERNAL_POST_INIT_SYM_NAME: Final = \"__mypy-post_init\"\n\n\nclass DataclassAttribute:\n    def __init__(\n        self,\n        name: str,\n        alias: str | None,\n        is_in_init: bool,\n        is_init_var: bool,\n        has_default: bool,\n        line: int,\n        column: int,\n        type: Type | None,\n        info: TypeInfo,\n        kw_only: bool,\n        is_neither_frozen_nor_nonfrozen: bool,\n        api: SemanticAnalyzerPluginInterface,\n    ) -> None:\n        self.name = name\n        self.alias = alias\n        self.is_in_init = is_in_init\n        self.is_init_var = is_init_var\n        self.has_default = has_default\n        self.line = line\n        self.column = column\n        self.type = type  # Type as __init__ argument\n        self.info = info\n        self.kw_only = kw_only\n        self.is_neither_frozen_nor_nonfrozen = is_neither_frozen_nor_nonfrozen\n        self._api = api\n\n    def to_argument(\n        self, current_info: TypeInfo, *, of: Literal[\"__init__\", \"replace\", \"__post_init__\"]\n    ) -> Argument:\n        if of == \"__init__\":\n            arg_kind = ARG_POS\n            if self.kw_only and self.has_default:\n                arg_kind = ARG_NAMED_OPT\n            elif self.kw_only and not self.has_default:\n                arg_kind = ARG_NAMED\n            elif not self.kw_only and self.has_default:\n                arg_kind = ARG_OPT\n        elif of == \"replace\":\n            arg_kind = ARG_NAMED if self.is_init_var and not self.has_default else ARG_NAMED_OPT\n        elif of == \"__post_init__\":\n            # We always use `ARG_POS` without a default value, because it is practical.\n            # Consider this case:\n            #\n            # @dataclass\n            # class My:\n            #     y: dataclasses.InitVar[str] = 'a'\n            #     def __post_init__(self, y: str) -> None: ...\n            #\n            # We would be *required* to specify `y: str = ...` if default is added here.\n            # But, most people won't care about adding default values to `__post_init__`,\n            # because it is not designed to be called directly, and duplicating default values\n            # for the sake of type-checking is unpleasant.\n            arg_kind = ARG_POS\n        return Argument(\n            variable=self.to_var(current_info),\n            type_annotation=self.expand_type(current_info),\n            initializer=EllipsisExpr() if self.has_default else None,  # Only used by stubgen\n            kind=arg_kind,\n        )\n\n    def expand_type(self, current_info: TypeInfo) -> Type | None:\n        if self.type is not None and self.info.self_type is not None:\n            # In general, it is not safe to call `expand_type()` during semantic analysis,\n            # however this plugin is called very late, so all types should be fully ready.\n            # Also, it is tricky to avoid eager expansion of Self types here (e.g. because\n            # we serialize attributes).\n            with state.strict_optional_set(self._api.options.strict_optional):\n                return expand_type(\n                    self.type, {self.info.self_type.id: fill_typevars(current_info)}\n                )\n        return self.type\n\n    def to_var(self, current_info: TypeInfo) -> Var:\n        return Var(self.alias or self.name, self.expand_type(current_info))\n\n    def serialize(self) -> JsonDict:\n        assert self.type\n        return {\n            \"name\": self.name,\n            \"alias\": self.alias,\n            \"is_in_init\": self.is_in_init,\n            \"is_init_var\": self.is_init_var,\n            \"has_default\": self.has_default,\n            \"line\": self.line,\n            \"column\": self.column,\n            \"type\": self.type.serialize(),\n            \"kw_only\": self.kw_only,\n            \"is_neither_frozen_nor_nonfrozen\": self.is_neither_frozen_nor_nonfrozen,\n        }\n\n    @classmethod\n    def deserialize(\n        cls, info: TypeInfo, data: JsonDict, api: SemanticAnalyzerPluginInterface\n    ) -> DataclassAttribute:\n        data = data.copy()\n        typ = deserialize_and_fixup_type(data.pop(\"type\"), api)\n        return cls(type=typ, info=info, **data, api=api)\n\n    def expand_typevar_from_subtype(self, sub_type: TypeInfo) -> None:\n        \"\"\"Expands type vars in the context of a subtype when an attribute is inherited\n        from a generic super type.\"\"\"\n        if self.type is not None:\n            with state.strict_optional_set(self._api.options.strict_optional):\n                self.type = map_type_from_supertype(self.type, sub_type, self.info)\n\n\nclass DataclassTransformer:\n    \"\"\"Implement the behavior of @dataclass.\n\n    Note that this may be executed multiple times on the same class, so\n    everything here must be idempotent.\n\n    This runs after the main semantic analysis pass, so you can assume that\n    there are no placeholders.\n    \"\"\"\n\n    def __init__(\n        self,\n        cls: ClassDef,\n        # Statement must also be accepted since class definition itself may be passed as the reason\n        # for subclass/metaclass-based uses of `typing.dataclass_transform`\n        reason: Expression | Statement,\n        spec: DataclassTransformSpec,\n        api: SemanticAnalyzerPluginInterface,\n    ) -> None:\n        self._cls = cls\n        self._reason = reason\n        self._spec = spec\n        self._api = api\n\n    def transform(self) -> bool:\n        \"\"\"Apply all the necessary transformations to the underlying\n        dataclass so as to ensure it is fully type checked according\n        to the rules in PEP 557.\n        \"\"\"\n        info = self._cls.info\n        attributes = self.collect_attributes()\n        if attributes is None:\n            # Some definitions are not ready. We need another pass.\n            return False\n        for attr in attributes:\n            if attr.type is None:\n                return False\n        decorator_arguments = {\n            \"init\": self._get_bool_arg(\"init\", True),\n            \"eq\": self._get_bool_arg(\"eq\", self._spec.eq_default),\n            \"order\": self._get_bool_arg(\"order\", self._spec.order_default),\n            \"frozen\": self._get_bool_arg(\"frozen\", self._spec.frozen_default),\n            \"slots\": self._get_bool_arg(\"slots\", False),\n            \"match_args\": self._get_bool_arg(\"match_args\", True),\n        }\n        py_version = self._api.options.python_version\n\n        # If there are no attributes, it may be that the semantic analyzer has not\n        # processed them yet. In order to work around this, we can simply skip generating\n        # __init__ if there are no attributes, because if the user truly did not define any,\n        # then the object default __init__ with an empty signature will be present anyway.\n        if (\n            decorator_arguments[\"init\"]\n            and (\"__init__\" not in info.names or info.names[\"__init__\"].plugin_generated)\n            and attributes\n        ):\n            args = [\n                attr.to_argument(info, of=\"__init__\")\n                for attr in attributes\n                if attr.is_in_init and not self._is_kw_only_type(attr.type)\n            ]\n\n            if info.fallback_to_any:\n                # Make positional args optional since we don't know their order.\n                # This will at least allow us to typecheck them if they are called\n                # as kwargs\n                for arg in args:\n                    if arg.kind == ARG_POS:\n                        arg.kind = ARG_OPT\n\n                existing_args_names = {arg.variable.name for arg in args}\n                gen_args_name = \"generated_args\"\n                while gen_args_name in existing_args_names:\n                    gen_args_name += \"_\"\n                gen_kwargs_name = \"generated_kwargs\"\n                while gen_kwargs_name in existing_args_names:\n                    gen_kwargs_name += \"_\"\n                args = [\n                    Argument(Var(gen_args_name), AnyType(TypeOfAny.explicit), None, ARG_STAR),\n                    *args,\n                    Argument(Var(gen_kwargs_name), AnyType(TypeOfAny.explicit), None, ARG_STAR2),\n                ]\n\n            add_method_to_class(\n                self._api, self._cls, \"__init__\", args=args, return_type=NoneType()\n            )\n\n        if (\n            decorator_arguments[\"eq\"]\n            and info.get(\"__eq__\") is None\n            or decorator_arguments[\"order\"]\n        ):\n            # Type variable for self types in generated methods.\n            obj_type = self._api.named_type(\"builtins.object\")\n            self_tvar_expr = TypeVarExpr(\n                SELF_TVAR_NAME,\n                info.fullname + \".\" + SELF_TVAR_NAME,\n                [],\n                obj_type,\n                AnyType(TypeOfAny.from_omitted_generics),\n            )\n            info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)\n\n        # Add <, >, <=, >=, but only if the class has an eq method.\n        if decorator_arguments[\"order\"]:\n            if not decorator_arguments[\"eq\"]:\n                self._api.fail('\"eq\" must be True if \"order\" is True', self._reason)\n\n            for method_name in [\"__lt__\", \"__gt__\", \"__le__\", \"__ge__\"]:\n                # Like for __eq__ and __ne__, we want \"other\" to match\n                # the self type.\n                obj_type = self._api.named_type(\"builtins.object\")\n                order_tvar_def = TypeVarType(\n                    SELF_TVAR_NAME,\n                    f\"{info.fullname}.{SELF_TVAR_NAME}\",\n                    id=TypeVarId(-1, namespace=f\"{info.fullname}.{method_name}\"),\n                    values=[],\n                    upper_bound=obj_type,\n                    default=AnyType(TypeOfAny.from_omitted_generics),\n                )\n                order_return_type = self._api.named_type(\"builtins.bool\")\n                order_args = [\n                    Argument(Var(\"other\", order_tvar_def), order_tvar_def, None, ARG_POS)\n                ]\n\n                existing_method = info.get(method_name)\n                if existing_method is not None and not existing_method.plugin_generated:\n                    assert existing_method.node\n                    self._api.fail(\n                        f'You may not have a custom \"{method_name}\" method when \"order\" is True',\n                        existing_method.node,\n                    )\n\n                add_method_to_class(\n                    self._api,\n                    self._cls,\n                    method_name,\n                    args=order_args,\n                    return_type=order_return_type,\n                    self_type=order_tvar_def,\n                    tvar_def=order_tvar_def,\n                )\n\n        parent_decorator_arguments = []\n        for parent in info.mro[1:-1]:\n            parent_args = parent.metadata.get(\"dataclass\")\n\n            # Ignore parent classes that directly specify a dataclass transform-decorated metaclass\n            # when searching for usage of the frozen parameter. PEP 681 states that a class that\n            # directly specifies such a metaclass must be treated as neither frozen nor non-frozen.\n            if parent_args and not _has_direct_dataclass_transform_metaclass(parent):\n                parent_decorator_arguments.append(parent_args)\n\n        if decorator_arguments[\"frozen\"]:\n            if any(not parent[\"frozen\"] for parent in parent_decorator_arguments):\n                self._api.fail(\"Frozen dataclass cannot inherit from a non-frozen dataclass\", info)\n            self._propertize_callables(attributes, settable=False)\n            self._freeze(attributes)\n        else:\n            if any(parent[\"frozen\"] for parent in parent_decorator_arguments):\n                self._api.fail(\"Non-frozen dataclass cannot inherit from a frozen dataclass\", info)\n            self._propertize_callables(attributes)\n\n        if decorator_arguments[\"slots\"]:\n            self.add_slots(info, attributes, correct_version=py_version >= (3, 10))\n\n        self.reset_init_only_vars(info, attributes)\n\n        if (\n            decorator_arguments[\"match_args\"]\n            and (\n                \"__match_args__\" not in info.names or info.names[\"__match_args__\"].plugin_generated\n            )\n            and py_version >= (3, 10)\n        ):\n            str_type = self._api.named_type(\"builtins.str\")\n            literals: list[Type] = [\n                LiteralType(attr.name, str_type)\n                for attr in attributes\n                if attr.is_in_init and not attr.kw_only\n            ]\n            match_args_type = TupleType(literals, self._api.named_type(\"builtins.tuple\"))\n            add_attribute_to_class(self._api, self._cls, \"__match_args__\", match_args_type)\n\n        self._add_dataclass_fields_magic_attribute()\n        self._add_internal_replace_method(attributes)\n        if self._api.options.python_version >= (3, 13):\n            self._add_dunder_replace(attributes)\n\n        if \"__post_init__\" in info.names:\n            self._add_internal_post_init_method(attributes)\n\n        info.metadata[\"dataclass\"] = {\n            \"attributes\": [attr.serialize() for attr in attributes],\n            \"frozen\": decorator_arguments[\"frozen\"],\n        }\n\n        return True\n\n    def _add_dunder_replace(self, attributes: list[DataclassAttribute]) -> None:\n        \"\"\"Add a `__replace__` method to the class, which is used to replace attributes in the `copy` module.\"\"\"\n        args = [\n            attr.to_argument(self._cls.info, of=\"replace\")\n            for attr in attributes\n            if attr.is_in_init\n        ]\n        add_method_to_class(\n            self._api,\n            self._cls,\n            \"__replace__\",\n            args=args,\n            return_type=fill_typevars(self._cls.info),\n        )\n\n    def _add_internal_replace_method(self, attributes: list[DataclassAttribute]) -> None:\n        \"\"\"\n        Stashes the signature of 'dataclasses.replace(...)' for this specific dataclass\n        to be used later whenever 'dataclasses.replace' is called for this dataclass.\n        \"\"\"\n        add_method_to_class(\n            self._api,\n            self._cls,\n            _INTERNAL_REPLACE_SYM_NAME,\n            args=[attr.to_argument(self._cls.info, of=\"replace\") for attr in attributes],\n            return_type=NoneType(),\n            is_staticmethod=True,\n        )\n\n    def _add_internal_post_init_method(self, attributes: list[DataclassAttribute]) -> None:\n        add_method_to_class(\n            self._api,\n            self._cls,\n            _INTERNAL_POST_INIT_SYM_NAME,\n            args=[\n                attr.to_argument(self._cls.info, of=\"__post_init__\")\n                for attr in attributes\n                if attr.is_init_var\n            ],\n            return_type=NoneType(),\n        )\n\n    def add_slots(\n        self, info: TypeInfo, attributes: list[DataclassAttribute], *, correct_version: bool\n    ) -> None:\n        if not correct_version:\n            # This means that version is lower than `3.10`,\n            # it is just a non-existent argument for `dataclass` function.\n            self._api.fail(\n                'Keyword argument \"slots\" for \"dataclass\" is only valid in Python 3.10 and higher',\n                self._reason,\n            )\n            return\n\n        existing_slots = info.names.get(\"__slots__\")\n        slots_defined_by_plugin = existing_slots is not None and existing_slots.plugin_generated\n        if existing_slots is not None and not slots_defined_by_plugin:\n            # This means we have a slots conflict.\n            # Class explicitly specifies a different `__slots__` field.\n            # And `@dataclass(slots=True)` is used.\n            # In runtime this raises a type error.\n            self._api.fail(\n                '\"{}\" both defines \"__slots__\" and is used with \"slots=True\"'.format(\n                    self._cls.name\n                ),\n                self._cls,\n            )\n            return\n\n        if any(p.slots is None for p in info.mro[1:-1]):\n            # At least one type in mro (excluding `self` and `object`)\n            # does not have concrete `__slots__` defined. Ignoring.\n            return\n\n        generated_slots = {attr.name for attr in attributes}\n        info.slots = generated_slots\n\n        # Now, insert `.__slots__` attribute to class namespace:\n        slots_type = TupleType(\n            [self._api.named_type(\"builtins.str\") for _ in generated_slots],\n            self._api.named_type(\"builtins.tuple\"),\n        )\n        add_attribute_to_class(\n            self._api,\n            self._cls,\n            \"__slots__\",\n            slots_type,\n            overwrite_existing=slots_defined_by_plugin,\n        )\n\n    def reset_init_only_vars(self, info: TypeInfo, attributes: list[DataclassAttribute]) -> None:\n        \"\"\"Remove init-only vars from the class and reset init var declarations.\"\"\"\n        for attr in attributes:\n            if attr.is_init_var:\n                if attr.name in info.names:\n                    del info.names[attr.name]\n                else:\n                    # Nodes of superclass InitVars not used in __init__ cannot be reached.\n                    assert attr.is_init_var\n                for stmt in info.defn.defs.body:\n                    if isinstance(stmt, AssignmentStmt) and stmt.unanalyzed_type:\n                        lvalue = stmt.lvalues[0]\n                        if isinstance(lvalue, NameExpr) and lvalue.name == attr.name:\n                            # Reset node so that another semantic analysis pass will\n                            # recreate a symbol node for this attribute.\n                            lvalue.node = None\n\n    def _get_assignment_statements_from_if_statement(\n        self, stmt: IfStmt\n    ) -> Iterator[AssignmentStmt]:\n        for body in stmt.body:\n            if not body.is_unreachable:\n                yield from self._get_assignment_statements_from_block(body)\n        if stmt.else_body is not None and not stmt.else_body.is_unreachable:\n            yield from self._get_assignment_statements_from_block(stmt.else_body)\n\n    def _get_assignment_statements_from_block(self, block: Block) -> Iterator[AssignmentStmt]:\n        for stmt in block.body:\n            if isinstance(stmt, AssignmentStmt):\n                yield stmt\n            elif isinstance(stmt, IfStmt):\n                yield from self._get_assignment_statements_from_if_statement(stmt)\n\n    def collect_attributes(self) -> list[DataclassAttribute] | None:\n        \"\"\"Collect all attributes declared in the dataclass and its parents.\n\n        All assignments of the form\n\n          a: SomeType\n          b: SomeOtherType = ...\n\n        are collected.\n\n        Return None if some dataclass base class hasn't been processed\n        yet and thus we'll need to ask for another pass.\n        \"\"\"\n        cls = self._cls\n\n        # First, collect attributes belonging to any class in the MRO, ignoring duplicates.\n        #\n        # We iterate through the MRO in reverse because attrs defined in the parent must appear\n        # earlier in the attributes list than attrs defined in the child. See:\n        # https://docs.python.org/3/library/dataclasses.html#inheritance\n        #\n        # However, we also want attributes defined in the subtype to override ones defined\n        # in the parent. We can implement this via a dict without disrupting the attr order\n        # because dicts preserve insertion order in Python 3.7+.\n        found_attrs: dict[str, DataclassAttribute] = {}\n        for info in reversed(cls.info.mro[1:-1]):\n            if \"dataclass_tag\" in info.metadata and \"dataclass\" not in info.metadata:\n                # We haven't processed the base class yet. Need another pass.\n                return None\n            if \"dataclass\" not in info.metadata:\n                continue\n\n            # Each class depends on the set of attributes in its dataclass ancestors.\n            self._api.add_plugin_dependency(make_wildcard_trigger(info.fullname))\n\n            for data in info.metadata[\"dataclass\"][\"attributes\"]:\n                name: str = data[\"name\"]\n\n                attr = DataclassAttribute.deserialize(info, data, self._api)\n                # TODO: We shouldn't be performing type operations during the main\n                #       semantic analysis pass, since some TypeInfo attributes might\n                #       still be in flux. This should be performed in a later phase.\n                attr.expand_typevar_from_subtype(cls.info)\n                found_attrs[name] = attr\n\n                sym_node = cls.info.names.get(name)\n                if sym_node and sym_node.node and not isinstance(sym_node.node, Var):\n                    self._api.fail(\n                        \"Dataclass attribute may only be overridden by another attribute\",\n                        sym_node.node,\n                    )\n\n        # Second, collect attributes belonging to the current class.\n        current_attr_names: set[str] = set()\n        kw_only = self._get_bool_arg(\"kw_only\", self._spec.kw_only_default)\n        for stmt in self._get_assignment_statements_from_block(cls.defs):\n            # Any assignment that doesn't use the new type declaration\n            # syntax can be ignored out of hand.\n            if not stmt.new_syntax:\n                continue\n\n            # a: int, b: str = 1, 'foo' is not supported syntax so we\n            # don't have to worry about it.\n            lhs = stmt.lvalues[0]\n            if not isinstance(lhs, NameExpr):\n                continue\n\n            sym = cls.info.names.get(lhs.name)\n            if sym is None:\n                # There was probably a semantic analysis error.\n                continue\n\n            node = sym.node\n            assert not isinstance(node, PlaceholderNode)\n\n            if isinstance(node, TypeAlias):\n                self._api.fail(\n                    (\"Type aliases inside dataclass definitions are not supported at runtime\"),\n                    node,\n                )\n                # Skip processing this node. This doesn't match the runtime behaviour,\n                # but the only alternative would be to modify the SymbolTable,\n                # and it's a little hairy to do that in a plugin.\n                continue\n            if isinstance(node, Decorator):\n                # This might be a property / field name clash.\n                # We will issue an error later.\n                continue\n\n            assert isinstance(node, Var), node\n\n            # x: ClassVar[int] is ignored by dataclasses.\n            if node.is_classvar:\n                continue\n\n            # x: InitVar[int] is turned into x: int and is removed from the class.\n            is_init_var = False\n            node_type = get_proper_type(node.type)\n            if (\n                isinstance(node_type, Instance)\n                and node_type.type.fullname == \"dataclasses.InitVar\"\n            ):\n                is_init_var = True\n                node.type = node_type.args[0]\n\n            if self._is_kw_only_type(node_type):\n                kw_only = True\n\n            has_field_call, field_args = self._collect_field_args(stmt.rvalue)\n\n            is_in_init_param = field_args.get(\"init\")\n            if is_in_init_param is None:\n                is_in_init = self._get_default_init_value_for_field_specifier(stmt.rvalue)\n            else:\n                is_in_init = bool(self._api.parse_bool(is_in_init_param))\n\n            has_default = False\n            # Ensure that something like x: int = field() is rejected\n            # after an attribute with a default.\n            if has_field_call:\n                has_default = (\n                    \"default\" in field_args\n                    or \"default_factory\" in field_args\n                    # alias for default_factory defined in PEP 681\n                    or \"factory\" in field_args\n                )\n\n            # All other assignments are already type checked.\n            elif not isinstance(stmt.rvalue, TempNode):\n                has_default = True\n\n            if not has_default and self._spec is _TRANSFORM_SPEC_FOR_DATACLASSES:\n                # Make all non-default dataclass attributes implicit because they are de-facto\n                # set on self in the generated __init__(), not in the class body. On the other\n                # hand, we don't know how custom dataclass transforms initialize attributes,\n                # so we don't treat them as implicit. This is required to support descriptors\n                # (https://github.com/python/mypy/issues/14868).\n                sym.implicit = True\n\n            is_kw_only = kw_only\n            # Use the kw_only field arg if it is provided. Otherwise use the\n            # kw_only value from the decorator parameter.\n            field_kw_only_param = field_args.get(\"kw_only\")\n            if field_kw_only_param is not None:\n                value = self._api.parse_bool(field_kw_only_param)\n                if value is not None:\n                    is_kw_only = value\n                else:\n                    self._api.fail('\"kw_only\" argument must be a boolean literal', stmt.rvalue)\n\n            if sym.type is None and node.is_final and node.is_inferred:\n                # This is a special case, assignment like x: Final = 42 is classified\n                # annotated above, but mypy strips the `Final` turning it into x = 42.\n                # We do not support inferred types in dataclasses, so we can try inferring\n                # type for simple literals, and otherwise require an explicit type\n                # argument for Final[...].\n                typ = self._api.analyze_simple_literal_type(stmt.rvalue, is_final=True)\n                if typ:\n                    node.type = typ\n                else:\n                    self._api.fail(\n                        \"Need type argument for Final[...] with non-literal default in dataclass\",\n                        stmt,\n                    )\n                    node.type = AnyType(TypeOfAny.from_error)\n\n            alias = None\n            if \"alias\" in field_args:\n                alias = self._api.parse_str_literal(field_args[\"alias\"])\n                if alias is None:\n                    self._api.fail(\n                        message_registry.DATACLASS_FIELD_ALIAS_MUST_BE_LITERAL,\n                        stmt.rvalue,\n                        code=errorcodes.LITERAL_REQ,\n                    )\n\n            current_attr_names.add(lhs.name)\n            with state.strict_optional_set(self._api.options.strict_optional):\n                init_type = self._infer_dataclass_attr_init_type(sym, lhs.name, stmt)\n            found_attrs[lhs.name] = DataclassAttribute(\n                name=lhs.name,\n                alias=alias,\n                is_in_init=is_in_init,\n                is_init_var=is_init_var,\n                has_default=has_default,\n                line=stmt.line,\n                column=stmt.column,\n                type=init_type,\n                info=cls.info,\n                kw_only=is_kw_only,\n                is_neither_frozen_nor_nonfrozen=_has_direct_dataclass_transform_metaclass(\n                    cls.info\n                ),\n                api=self._api,\n            )\n\n        all_attrs = list(found_attrs.values())\n        all_attrs.sort(key=lambda a: a.kw_only)\n\n        # Third, ensure that arguments without a default don't follow\n        # arguments that have a default and that the KW_ONLY sentinel\n        # is only provided once.\n        found_default = False\n        found_kw_sentinel = False\n        for attr in all_attrs:\n            # If we find any attribute that is_in_init, not kw_only, and that\n            # doesn't have a default after one that does have one,\n            # then that's an error.\n            if found_default and attr.is_in_init and not attr.has_default and not attr.kw_only:\n                # If the issue comes from merging different classes, report it\n                # at the class definition point.\n                context: Context = cls\n                if attr.name in current_attr_names:\n                    context = Context(line=attr.line, column=attr.column)\n                self._api.fail(\n                    \"Attributes without a default cannot follow attributes with one\", context\n                )\n\n            found_default = found_default or (attr.has_default and attr.is_in_init)\n            if found_kw_sentinel and self._is_kw_only_type(attr.type):\n                context = cls\n                if attr.name in current_attr_names:\n                    context = Context(line=attr.line, column=attr.column)\n                self._api.fail(\n                    \"There may not be more than one field with the KW_ONLY type\", context\n                )\n            found_kw_sentinel = found_kw_sentinel or self._is_kw_only_type(attr.type)\n        return all_attrs\n\n    def _freeze(self, attributes: list[DataclassAttribute]) -> None:\n        \"\"\"Converts all attributes to @property methods in order to\n        emulate frozen classes.\n        \"\"\"\n        info = self._cls.info\n        for attr in attributes:\n            # Classes that directly specify a dataclass_transform metaclass must be neither frozen\n            # non non-frozen per PEP681. Though it is surprising, this means that attributes from\n            # such a class must be writable even if the rest of the class hierarchy is frozen. This\n            # matches the behavior of Pyright (the reference implementation).\n            if attr.is_neither_frozen_nor_nonfrozen:\n                continue\n\n            sym_node = info.names.get(attr.name)\n            if sym_node is not None:\n                var = sym_node.node\n                if isinstance(var, Var):\n                    if var.is_final:\n                        continue  # do not turn `Final` attrs to `@property`\n                    var.is_property = True\n            else:\n                var = attr.to_var(info)\n                var.info = info\n                var.is_property = True\n                var._fullname = info.fullname + \".\" + var.name\n                info.names[var.name] = SymbolTableNode(MDEF, var)\n\n    def _propertize_callables(\n        self, attributes: list[DataclassAttribute], settable: bool = True\n    ) -> None:\n        \"\"\"Converts all attributes with callable types to @property methods.\n\n        This avoids the typechecker getting confused and thinking that\n        `my_dataclass_instance.callable_attr(foo)` is going to receive a\n        `self` argument (it is not).\n\n        \"\"\"\n        info = self._cls.info\n        for attr in attributes:\n            if isinstance(get_proper_type(attr.type), CallableType):\n                var = attr.to_var(info)\n                var.info = info\n                var.is_property = True\n                var.is_settable_property = settable\n                var._fullname = info.fullname + \".\" + var.name\n                info.names[var.name] = SymbolTableNode(MDEF, var)\n\n    def _is_kw_only_type(self, node: Type | None) -> bool:\n        \"\"\"Checks if the type of the node is the KW_ONLY sentinel value.\"\"\"\n        if node is None:\n            return False\n        node_type = get_proper_type(node)\n        if not isinstance(node_type, Instance):\n            return False\n        return node_type.type.fullname == \"dataclasses.KW_ONLY\"\n\n    def _add_dataclass_fields_magic_attribute(self) -> None:\n        attr_name = \"__dataclass_fields__\"\n        any_type = AnyType(TypeOfAny.explicit)\n        # For `dataclasses`, use the type `dict[str, Field[Any]]` for accuracy. For dataclass\n        # transforms, it's inaccurate to use `Field` since a given transform may use a completely\n        # different type (or none); fall back to `Any` there.\n        #\n        # In either case, we're aiming to match the Typeshed stub for `is_dataclass`, which expects\n        # the instance to have a `__dataclass_fields__` attribute of type `dict[str, Field[Any]]`.\n        if self._spec is _TRANSFORM_SPEC_FOR_DATACLASSES:\n            field_type = self._api.named_type_or_none(\"dataclasses.Field\", [any_type]) or any_type\n        else:\n            field_type = any_type\n        attr_type = self._api.named_type(\n            \"builtins.dict\", [self._api.named_type(\"builtins.str\"), field_type]\n        )\n        var = Var(name=attr_name, type=attr_type)\n        var.info = self._cls.info\n        var._fullname = self._cls.info.fullname + \".\" + attr_name\n        var.is_classvar = True\n        self._cls.info.names[attr_name] = SymbolTableNode(\n            kind=MDEF, node=var, plugin_generated=True\n        )\n\n    def _collect_field_args(self, expr: Expression) -> tuple[bool, dict[str, Expression]]:\n        \"\"\"Returns a tuple where the first value represents whether or not\n        the expression is a call to dataclass.field and the second is a\n        dictionary of the keyword arguments that field() was called with.\n        \"\"\"\n        if (\n            isinstance(expr, CallExpr)\n            and isinstance(expr.callee, RefExpr)\n            and expr.callee.fullname in self._spec.field_specifiers\n        ):\n            # field() only takes keyword arguments.\n            args = {}\n            for name, arg, kind in zip(expr.arg_names, expr.args, expr.arg_kinds):\n                if not kind.is_named():\n                    if kind.is_named(star=True):\n                        # This means that `field` is used with `**` unpacking,\n                        # the best we can do for now is not to fail.\n                        # TODO: we can infer what's inside `**` and try to collect it.\n                        message = 'Unpacking **kwargs in \"field()\" is not supported'\n                    elif self._spec is not _TRANSFORM_SPEC_FOR_DATACLASSES:\n                        # dataclasses.field can only be used with keyword args, but this\n                        # restriction is only enforced for the *standardized* arguments to\n                        # dataclass_transform field specifiers. If this is not a\n                        # dataclasses.dataclass class, we can just skip positional args safely.\n                        continue\n                    else:\n                        message = '\"field()\" does not accept positional arguments'\n                    self._api.fail(message, expr)\n                    return True, {}\n                assert name is not None\n                args[name] = arg\n            return True, args\n        return False, {}\n\n    def _get_bool_arg(self, name: str, default: bool) -> bool:\n        # Expressions are always CallExprs (either directly or via a wrapper like Decorator), so\n        # we can use the helpers from common\n        if isinstance(self._reason, Expression):\n            return _get_decorator_bool_argument(\n                ClassDefContext(self._cls, self._reason, self._api), name, default\n            )\n\n        # Subclass/metaclass use of `typing.dataclass_transform` reads the parameters from the\n        # class's keyword arguments (ie `class Subclass(Parent, kwarg1=..., kwarg2=...)`)\n        expression = self._cls.keywords.get(name)\n        if expression is not None:\n            return require_bool_literal_argument(self._api, expression, name, default)\n        return default\n\n    def _get_default_init_value_for_field_specifier(self, call: Expression) -> bool:\n        \"\"\"\n        Find a default value for the `init` parameter of the specifier being called. If the\n        specifier's type signature includes an `init` parameter with a type of `Literal[True]` or\n        `Literal[False]`, return the appropriate boolean value from the literal. Otherwise,\n        fall back to the standard default of `True`.\n        \"\"\"\n        if not isinstance(call, CallExpr):\n            return True\n\n        specifier_type = _get_callee_type(call)\n        if specifier_type is None:\n            return True\n\n        parameter = specifier_type.argument_by_name(\"init\")\n        if parameter is None:\n            return True\n\n        literals = try_getting_literals_from_type(parameter.typ, bool, \"builtins.bool\")\n        if literals is None or len(literals) != 1:\n            return True\n\n        return literals[0]\n\n    def _infer_dataclass_attr_init_type(\n        self, sym: SymbolTableNode, name: str, context: Context\n    ) -> Type | None:\n        \"\"\"Infer __init__ argument type for an attribute.\n\n        In particular, possibly use the signature of __set__.\n        \"\"\"\n        default = sym.type\n        if sym.implicit:\n            return default\n        t = get_proper_type(sym.type)\n\n        # Perform a simple-minded inference from the signature of __set__, if present.\n        # We can't use mypy.checkmember here, since this plugin runs before type checking.\n        # We only support some basic scanerios here, which is hopefully sufficient for\n        # the vast majority of use cases.\n        if not isinstance(t, Instance):\n            return default\n        setter = t.type.get(\"__set__\")\n        if setter:\n            if isinstance(setter.node, FuncDef):\n                super_info = t.type.get_containing_type_info(\"__set__\")\n                assert super_info\n                if setter.type:\n                    setter_type = get_proper_type(\n                        map_type_from_supertype(setter.type, t.type, super_info)\n                    )\n                else:\n                    return AnyType(TypeOfAny.unannotated)\n                if isinstance(setter_type, CallableType) and setter_type.arg_kinds == [\n                    ARG_POS,\n                    ARG_POS,\n                    ARG_POS,\n                ]:\n                    return expand_type_by_instance(setter_type.arg_types[2], t)\n                else:\n                    self._api.fail(\n                        f'Unsupported signature for \"__set__\" in \"{t.type.name}\"', context\n                    )\n            else:\n                self._api.fail(f'Unsupported \"__set__\" in \"{t.type.name}\"', context)\n\n        return default\n\n\ndef add_dataclass_tag(info: TypeInfo) -> None:\n    # The value is ignored, only the existence matters.\n    info.metadata[\"dataclass_tag\"] = {}\n\n\ndef dataclass_tag_callback(ctx: ClassDefContext) -> None:\n    \"\"\"Record that we have a dataclass in the main semantic analysis pass.\n\n    The later pass implemented by DataclassTransformer will use this\n    to detect dataclasses in base classes.\n    \"\"\"\n    add_dataclass_tag(ctx.cls.info)\n\n\ndef dataclass_class_maker_callback(ctx: ClassDefContext) -> bool:\n    \"\"\"Hooks into the class typechecking process to add support for dataclasses.\"\"\"\n    if any(i.is_named_tuple for i in ctx.cls.info.mro):\n        ctx.api.fail(\"A NamedTuple cannot be a dataclass\", ctx=ctx.cls.info)\n        return True\n    transformer = DataclassTransformer(\n        ctx.cls, ctx.reason, _get_transform_spec(ctx.reason), ctx.api\n    )\n    return transformer.transform()\n\n\ndef _get_transform_spec(reason: Expression) -> DataclassTransformSpec:\n    \"\"\"Find the relevant transform parameters from the decorator/parent class/metaclass that\n    triggered the dataclasses plugin.\n\n    Although the resulting DataclassTransformSpec is based on the typing.dataclass_transform\n    function, we also use it for traditional dataclasses.dataclass classes as well for simplicity.\n    In those cases, we return a default spec rather than one based on a call to\n    `typing.dataclass_transform`.\n    \"\"\"\n    if _is_dataclasses_decorator(reason):\n        return _TRANSFORM_SPEC_FOR_DATACLASSES\n\n    spec = find_dataclass_transform_spec(reason)\n    assert spec is not None, (\n        \"trying to find dataclass transform spec, but reason is neither dataclasses.dataclass nor \"\n        \"decorated with typing.dataclass_transform\"\n    )\n    return spec\n\n\ndef _is_dataclasses_decorator(node: Node) -> bool:\n    if isinstance(node, CallExpr):\n        node = node.callee\n    if isinstance(node, RefExpr):\n        return node.fullname in dataclass_makers\n    return False\n\n\ndef _has_direct_dataclass_transform_metaclass(info: TypeInfo) -> bool:\n    return (\n        info.declared_metaclass is not None\n        and info.declared_metaclass.type.dataclass_transform_spec is not None\n    )\n\n\ndef _get_expanded_dataclasses_fields(\n    ctx: FunctionSigContext, typ: ProperType, display_typ: ProperType, parent_typ: ProperType\n) -> list[CallableType] | None:\n    \"\"\"\n    For a given type, determine what dataclasses it can be: for each class, return the field types.\n    For generic classes, the field types are expanded.\n    If the type contains Any or a non-dataclass, returns None; in the latter case, also reports an error.\n    \"\"\"\n    if isinstance(typ, UnionType):\n        ret: list[CallableType] | None = []\n        for item in typ.relevant_items():\n            item = get_proper_type(item)\n            item_types = _get_expanded_dataclasses_fields(ctx, item, item, parent_typ)\n            if ret is not None and item_types is not None:\n                ret += item_types\n            else:\n                ret = None  # but keep iterating to emit all errors\n        return ret\n    elif isinstance(typ, TypeVarType):\n        return _get_expanded_dataclasses_fields(\n            ctx, get_proper_type(typ.upper_bound), display_typ, parent_typ\n        )\n    elif isinstance(typ, Instance):\n        replace_sym = typ.type.get_method(_INTERNAL_REPLACE_SYM_NAME)\n        if replace_sym is None:\n            return None\n        replace_sig = replace_sym.type\n        assert isinstance(replace_sig, ProperType)\n        assert isinstance(replace_sig, CallableType)\n        return [expand_type_by_instance(replace_sig, typ)]\n    else:\n        return None\n\n\n# TODO: we can potentially get the function signature hook to allow returning a union\n#  and leave this to the regular machinery of resolving a union of callables\n#  (https://github.com/python/mypy/issues/15457)\ndef _meet_replace_sigs(sigs: list[CallableType]) -> CallableType:\n    \"\"\"\n    Produces the lowest bound of the 'replace' signatures of multiple dataclasses.\n    \"\"\"\n    args = {\n        name: (typ, kind)\n        for name, typ, kind in zip(sigs[0].arg_names, sigs[0].arg_types, sigs[0].arg_kinds)\n    }\n\n    for sig in sigs[1:]:\n        sig_args = {\n            name: (typ, kind)\n            for name, typ, kind in zip(sig.arg_names, sig.arg_types, sig.arg_kinds)\n        }\n        for name in (*args.keys(), *sig_args.keys()):\n            sig_typ, sig_kind = args.get(name, (UninhabitedType(), ARG_NAMED_OPT))\n            sig2_typ, sig2_kind = sig_args.get(name, (UninhabitedType(), ARG_NAMED_OPT))\n            args[name] = (\n                meet_types(sig_typ, sig2_typ),\n                ARG_NAMED_OPT if sig_kind == sig2_kind == ARG_NAMED_OPT else ARG_NAMED,\n            )\n\n    return sigs[0].copy_modified(\n        arg_names=list(args.keys()),\n        arg_types=[typ for typ, _ in args.values()],\n        arg_kinds=[kind for _, kind in args.values()],\n    )\n\n\ndef replace_function_sig_callback(ctx: FunctionSigContext) -> CallableType:\n    \"\"\"\n    Returns a signature for the 'dataclasses.replace' function that's dependent on the type\n    of the first positional argument.\n    \"\"\"\n    if len(ctx.args) != 2:\n        # Ideally the name and context should be callee's, but we don't have it in FunctionSigContext.\n        ctx.api.fail(f'\"{ctx.default_signature.name}\" has unexpected type annotation', ctx.context)\n        return ctx.default_signature\n\n    if len(ctx.args[0]) != 1:\n        return ctx.default_signature  # leave it to the type checker to complain\n\n    obj_arg = ctx.args[0][0]\n    obj_type = get_proper_type(ctx.api.get_expression_type(obj_arg))\n    inst_type_str = format_type_bare(obj_type, ctx.api.options)\n\n    replace_sigs = _get_expanded_dataclasses_fields(ctx, obj_type, obj_type, obj_type)\n    if replace_sigs is None:\n        return ctx.default_signature\n    replace_sig = _meet_replace_sigs(replace_sigs)\n\n    return replace_sig.copy_modified(\n        arg_names=[None, *replace_sig.arg_names],\n        arg_kinds=[ARG_POS, *replace_sig.arg_kinds],\n        arg_types=[obj_type, *replace_sig.arg_types],\n        ret_type=obj_type,\n        fallback=ctx.default_signature.fallback,\n        name=f\"{ctx.default_signature.name} of {inst_type_str}\",\n    )\n\n\ndef is_processed_dataclass(info: TypeInfo) -> bool:\n    return bool(info) and \"dataclass\" in info.metadata\n\n\ndef check_post_init(api: TypeChecker, defn: FuncItem, info: TypeInfo) -> None:\n    if defn.type is None:\n        return\n    assert isinstance(defn.type, FunctionLike)\n\n    ideal_sig_method = info.get_method(_INTERNAL_POST_INIT_SYM_NAME)\n    assert ideal_sig_method is not None and ideal_sig_method.type is not None\n    ideal_sig = ideal_sig_method.type\n    assert isinstance(ideal_sig, ProperType)  # we set it ourselves\n    assert isinstance(ideal_sig, CallableType)\n    ideal_sig = ideal_sig.copy_modified(name=\"__post_init__\")\n\n    api.check_override(\n        override=defn.type,\n        original=ideal_sig,\n        name=\"__post_init__\",\n        name_in_super=\"__post_init__\",\n        supertype=\"dataclass\",\n        original_class_or_static=False,\n        override_class_or_static=False,\n        node=defn,\n    )\n"
  },
  {
    "path": "mypy/plugins/default.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Callable\nfrom functools import partial\nfrom typing import Final\n\nimport mypy.errorcodes as codes\nfrom mypy import message_registry\nfrom mypy.nodes import DictExpr, Expression, IntExpr, StrExpr, UnaryExpr\nfrom mypy.plugin import (\n    AttributeContext,\n    ClassDefContext,\n    FunctionContext,\n    FunctionSigContext,\n    MethodContext,\n    MethodSigContext,\n    Plugin,\n)\nfrom mypy.plugins.attrs import (\n    attr_class_maker_callback,\n    attr_class_makers,\n    attr_dataclass_makers,\n    attr_define_makers,\n    attr_frozen_makers,\n    attr_tag_callback,\n    evolve_function_sig_callback,\n    fields_function_sig_callback,\n)\nfrom mypy.plugins.common import try_getting_str_literals\nfrom mypy.plugins.constants import (\n    ENUM_NAME_ACCESS,\n    ENUM_VALUE_ACCESS,\n    SINGLEDISPATCH_CALLABLE_CALL_METHOD,\n    SINGLEDISPATCH_REGISTER_CALLABLE_CALL_METHOD,\n    SINGLEDISPATCH_REGISTER_METHOD,\n)\nfrom mypy.plugins.ctypes import (\n    array_constructor_callback,\n    array_getitem_callback,\n    array_iter_callback,\n    array_raw_callback,\n    array_setitem_callback,\n    array_value_callback,\n)\nfrom mypy.plugins.dataclasses import (\n    dataclass_class_maker_callback,\n    dataclass_makers,\n    dataclass_tag_callback,\n    replace_function_sig_callback,\n)\nfrom mypy.plugins.enums import enum_member_callback, enum_name_callback, enum_value_callback\nfrom mypy.plugins.functools import (\n    functools_total_ordering_maker_callback,\n    functools_total_ordering_makers,\n    partial_call_callback,\n    partial_new_callback,\n)\nfrom mypy.plugins.singledispatch import (\n    call_singledispatch_function_after_register_argument,\n    call_singledispatch_function_callback,\n    create_singledispatch_function_callback,\n    singledispatch_register_callback,\n)\nfrom mypy.subtypes import is_subtype\nfrom mypy.typeops import is_literal_type_like, make_simplified_union\nfrom mypy.types import (\n    TPDICT_FB_NAMES,\n    AnyType,\n    CallableType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeOfAny,\n    TypeVarType,\n    UnionType,\n    get_proper_type,\n    get_proper_types,\n)\n\nTD_SETDEFAULT_NAMES: Final = {n + \".setdefault\" for n in TPDICT_FB_NAMES}\nTD_POP_NAMES: Final = {n + \".pop\" for n in TPDICT_FB_NAMES}\nTD_DELITEM_NAMES: Final = {n + \".__delitem__\" for n in TPDICT_FB_NAMES}\n\nTD_UPDATE_METHOD_NAMES: Final = (\n    {n + \".update\" for n in TPDICT_FB_NAMES}\n    | {n + \".__or__\" for n in TPDICT_FB_NAMES}\n    | {n + \".__ror__\" for n in TPDICT_FB_NAMES}\n    | {n + \".__ior__\" for n in TPDICT_FB_NAMES}\n)\n\n\nclass DefaultPlugin(Plugin):\n    \"\"\"Type checker plugin that is enabled by default.\"\"\"\n\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if fullname == \"_ctypes.Array\":\n            return array_constructor_callback\n        elif fullname == \"functools.singledispatch\":\n            return create_singledispatch_function_callback\n        elif fullname == \"functools.partial\":\n            return partial_new_callback\n        elif fullname == \"enum.member\":\n            return enum_member_callback\n        elif fullname == \"builtins.len\":\n            return len_callback\n        return None\n\n    def get_function_signature_hook(\n        self, fullname: str\n    ) -> Callable[[FunctionSigContext], FunctionLike] | None:\n        if fullname in (\"attr.evolve\", \"attrs.evolve\", \"attr.assoc\", \"attrs.assoc\"):\n            return evolve_function_sig_callback\n        elif fullname in (\"attr.fields\", \"attrs.fields\"):\n            return fields_function_sig_callback\n        elif fullname == \"dataclasses.replace\":\n            return replace_function_sig_callback\n        return None\n\n    def get_method_signature_hook(\n        self, fullname: str\n    ) -> Callable[[MethodSigContext], FunctionLike] | None:\n        if fullname == \"typing.Mapping.get\":\n            return typed_dict_get_signature_callback\n        elif fullname in TD_SETDEFAULT_NAMES:\n            return typed_dict_setdefault_signature_callback\n        elif fullname in TD_POP_NAMES:\n            return typed_dict_pop_signature_callback\n        elif fullname == \"_ctypes.Array.__setitem__\":\n            return array_setitem_callback\n        elif fullname == SINGLEDISPATCH_CALLABLE_CALL_METHOD:\n            return call_singledispatch_function_callback\n        elif fullname in TD_UPDATE_METHOD_NAMES:\n            return typed_dict_update_signature_callback\n        return None\n\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        if fullname == \"typing.Mapping.get\":\n            return typed_dict_get_callback\n        elif fullname == \"builtins.int.__pow__\":\n            return int_pow_callback\n        elif fullname == \"builtins.int.__neg__\":\n            return int_neg_callback\n        elif fullname == \"builtins.int.__pos__\":\n            return int_pos_callback\n        elif fullname in (\"builtins.tuple.__mul__\", \"builtins.tuple.__rmul__\"):\n            return tuple_mul_callback\n        elif fullname in TD_SETDEFAULT_NAMES:\n            return typed_dict_setdefault_callback\n        elif fullname in TD_POP_NAMES:\n            return typed_dict_pop_callback\n        elif fullname in TD_DELITEM_NAMES:\n            return typed_dict_delitem_callback\n        elif fullname == \"_ctypes.Array.__getitem__\":\n            return array_getitem_callback\n        elif fullname == \"_ctypes.Array.__iter__\":\n            return array_iter_callback\n        elif fullname == SINGLEDISPATCH_REGISTER_METHOD:\n            return singledispatch_register_callback\n        elif fullname == SINGLEDISPATCH_REGISTER_CALLABLE_CALL_METHOD:\n            return call_singledispatch_function_after_register_argument\n        elif fullname == \"functools.partial.__call__\":\n            return partial_call_callback\n        return None\n\n    def get_attribute_hook(self, fullname: str) -> Callable[[AttributeContext], Type] | None:\n        if fullname == \"_ctypes.Array.value\":\n            return array_value_callback\n        elif fullname == \"_ctypes.Array.raw\":\n            return array_raw_callback\n        elif fullname in ENUM_NAME_ACCESS:\n            return enum_name_callback\n        elif fullname in ENUM_VALUE_ACCESS:\n            return enum_value_callback\n        return None\n\n    def get_class_decorator_hook(self, fullname: str) -> Callable[[ClassDefContext], None] | None:\n        # These dataclass and attrs hooks run in the main semantic analysis pass\n        # and only tag known dataclasses/attrs classes, so that the second\n        # hooks (in get_class_decorator_hook_2) can detect dataclasses/attrs classes\n        # in the MRO.\n        if fullname in dataclass_makers:\n            return dataclass_tag_callback\n        if (\n            fullname in attr_class_makers\n            or fullname in attr_dataclass_makers\n            or fullname in attr_frozen_makers\n            or fullname in attr_define_makers\n        ):\n            return attr_tag_callback\n        return None\n\n    def get_class_decorator_hook_2(\n        self, fullname: str\n    ) -> Callable[[ClassDefContext], bool] | None:\n        if fullname in dataclass_makers:\n            return dataclass_class_maker_callback\n        elif fullname in functools_total_ordering_makers:\n            return functools_total_ordering_maker_callback\n        elif fullname in attr_class_makers:\n            return attr_class_maker_callback\n        elif fullname in attr_dataclass_makers:\n            return partial(attr_class_maker_callback, auto_attribs_default=True)\n        elif fullname in attr_frozen_makers:\n            return partial(\n                attr_class_maker_callback, auto_attribs_default=None, frozen_default=True\n            )\n        elif fullname in attr_define_makers:\n            return partial(\n                attr_class_maker_callback, auto_attribs_default=None, slots_default=True\n            )\n        return None\n\n\ndef len_callback(ctx: FunctionContext) -> Type:\n    \"\"\"Infer a better return type for 'len'.\"\"\"\n    if len(ctx.arg_types) == 1 and len(ctx.arg_types[0]) == 1:\n        arg_type = ctx.arg_types[0][0]\n        arg_type = get_proper_type(arg_type)\n        if isinstance(arg_type, Instance) and arg_type.type.fullname == \"librt.vecs.vec\":\n            # The length of vec is a fixed-width integer, for more\n            # low-level optimization potential.\n            return ctx.api.named_generic_type(\"mypy_extensions.i64\", [])\n    return ctx.default_return_type\n\n\ndef typed_dict_get_signature_callback(ctx: MethodSigContext) -> CallableType:\n    \"\"\"Try to infer a better signature type for TypedDict.get.\n\n    This is used to get better type context for the second argument that\n    depends on a TypedDict value type.\n    \"\"\"\n    signature = ctx.default_signature\n    if (\n        isinstance(ctx.type, TypedDictType)\n        and len(ctx.args) == 2\n        and len(ctx.args[0]) == 1\n        and isinstance(ctx.args[0][0], StrExpr)\n        and len(signature.arg_types) == 2\n        and len(signature.variables) == 1\n        and len(ctx.args[1]) == 1\n    ):\n        key = ctx.args[0][0].value\n        value_type = get_proper_type(ctx.type.items.get(key))\n        ret_type = signature.ret_type\n        if value_type:\n            default_arg = ctx.args[1][0]\n            if (\n                isinstance(value_type, TypedDictType)\n                and isinstance(default_arg, DictExpr)\n                and len(default_arg.items) == 0\n            ):\n                # Caller has empty dict {} as default for typed dict.\n                value_type = value_type.copy_modified(required_keys=set())\n            # Tweak the signature to include the value type as context. It's\n            # only needed for type inference since there's a union with a type\n            # variable that accepts everything.\n            tv = signature.variables[0]\n            assert isinstance(tv, TypeVarType)\n            return signature.copy_modified(\n                arg_types=[signature.arg_types[0], make_simplified_union([value_type, tv])],\n                ret_type=ret_type,\n            )\n    return signature\n\n\ndef typed_dict_get_callback(ctx: MethodContext) -> Type:\n    \"\"\"Infer a precise return type for TypedDict.get with literal first argument.\"\"\"\n    if (\n        isinstance(ctx.type, TypedDictType)\n        and len(ctx.arg_types) >= 1\n        and len(ctx.arg_types[0]) == 1\n    ):\n        keys = try_getting_str_literals(ctx.args[0][0], ctx.arg_types[0][0])\n        if keys is None:\n            return ctx.default_return_type\n\n        default_type: Type\n        default_arg: Expression | None\n        if len(ctx.arg_types) <= 1 or not ctx.arg_types[1]:\n            default_arg = None\n            default_type = NoneType()\n        elif len(ctx.arg_types[1]) == 1 and len(ctx.args[1]) == 1:\n            default_arg = ctx.args[1][0]\n            default_type = ctx.arg_types[1][0]\n        else:\n            return ctx.default_return_type\n\n        output_types: list[Type] = []\n        for key in keys:\n            value_type: Type | None = ctx.type.items.get(key)\n            if value_type is None:\n                return ctx.default_return_type\n\n            if key in ctx.type.required_keys:\n                output_types.append(value_type)\n            else:\n                # HACK to deal with get(key, {})\n                if (\n                    isinstance(default_arg, DictExpr)\n                    and len(default_arg.items) == 0\n                    and isinstance(vt := get_proper_type(value_type), TypedDictType)\n                ):\n                    output_types.append(vt.copy_modified(required_keys=set()))\n                else:\n                    output_types.append(value_type)\n                    output_types.append(default_type)\n\n        # for nicer reveal_type, put default at the end, if it is present\n        if default_type in output_types:\n            output_types = [t for t in output_types if t != default_type] + [default_type]\n        return make_simplified_union(output_types)\n    return ctx.default_return_type\n\n\ndef typed_dict_pop_signature_callback(ctx: MethodSigContext) -> CallableType:\n    \"\"\"Try to infer a better signature type for TypedDict.pop.\n\n    This is used to get better type context for the second argument that\n    depends on a TypedDict value type.\n    \"\"\"\n    signature = ctx.default_signature\n    str_type = ctx.api.named_generic_type(\"builtins.str\", [])\n    if (\n        isinstance(ctx.type, TypedDictType)\n        and len(ctx.args) == 2\n        and len(ctx.args[0]) == 1\n        and isinstance(ctx.args[0][0], StrExpr)\n        and len(signature.arg_types) == 2\n        and len(signature.variables) == 1\n        and len(ctx.args[1]) == 1\n    ):\n        key = ctx.args[0][0].value\n        value_type = ctx.type.items.get(key)\n        if value_type:\n            # Tweak the signature to include the value type as context. It's\n            # only needed for type inference since there's a union with a type\n            # variable that accepts everything.\n            tv = signature.variables[0]\n            assert isinstance(tv, TypeVarType)\n            typ = make_simplified_union([value_type, tv])\n            return signature.copy_modified(arg_types=[str_type, typ], ret_type=typ)\n    return signature.copy_modified(arg_types=[str_type, signature.arg_types[1]])\n\n\ndef typed_dict_pop_callback(ctx: MethodContext) -> Type:\n    \"\"\"Type check and infer a precise return type for TypedDict.pop.\"\"\"\n    if (\n        isinstance(ctx.type, TypedDictType)\n        and len(ctx.arg_types) >= 1\n        and len(ctx.arg_types[0]) == 1\n    ):\n        key_expr = ctx.args[0][0]\n        keys = try_getting_str_literals(key_expr, ctx.arg_types[0][0])\n        if keys is None:\n            ctx.api.fail(\n                message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,\n                key_expr,\n                code=codes.LITERAL_REQ,\n            )\n            return AnyType(TypeOfAny.from_error)\n\n        value_types = []\n        for key in keys:\n            if key in ctx.type.required_keys or key in ctx.type.readonly_keys:\n                ctx.api.msg.typeddict_key_cannot_be_deleted(ctx.type, key, key_expr)\n\n            value_type = ctx.type.items.get(key)\n            if value_type:\n                value_types.append(value_type)\n            else:\n                ctx.api.msg.typeddict_key_not_found(ctx.type, key, key_expr)\n                return AnyType(TypeOfAny.from_error)\n\n        if len(ctx.args[1]) == 0:\n            return make_simplified_union(value_types)\n        elif len(ctx.arg_types) == 2 and len(ctx.arg_types[1]) == 1 and len(ctx.args[1]) == 1:\n            return make_simplified_union([*value_types, ctx.arg_types[1][0]])\n    return ctx.default_return_type\n\n\ndef typed_dict_setdefault_signature_callback(ctx: MethodSigContext) -> CallableType:\n    \"\"\"Try to infer a better signature type for TypedDict.setdefault.\n\n    This is used to get better type context for the second argument that\n    depends on a TypedDict value type.\n    \"\"\"\n    signature = ctx.default_signature\n    str_type = ctx.api.named_generic_type(\"builtins.str\", [])\n    if (\n        isinstance(ctx.type, TypedDictType)\n        and len(ctx.args) == 2\n        and len(ctx.args[0]) == 1\n        and isinstance(ctx.args[0][0], StrExpr)\n        and len(signature.arg_types) == 2\n        and len(ctx.args[1]) == 1\n    ):\n        key = ctx.args[0][0].value\n        value_type = ctx.type.items.get(key)\n        if value_type:\n            return signature.copy_modified(arg_types=[str_type, value_type])\n    return signature.copy_modified(arg_types=[str_type, signature.arg_types[1]])\n\n\ndef typed_dict_setdefault_callback(ctx: MethodContext) -> Type:\n    \"\"\"Type check TypedDict.setdefault and infer a precise return type.\"\"\"\n    if (\n        isinstance(ctx.type, TypedDictType)\n        and len(ctx.arg_types) == 2\n        and len(ctx.arg_types[0]) == 1\n        and len(ctx.arg_types[1]) == 1\n    ):\n        key_expr = ctx.args[0][0]\n        keys = try_getting_str_literals(key_expr, ctx.arg_types[0][0])\n        if keys is None:\n            ctx.api.fail(\n                message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,\n                key_expr,\n                code=codes.LITERAL_REQ,\n            )\n            return AnyType(TypeOfAny.from_error)\n\n        assigned_readonly_keys = ctx.type.readonly_keys & set(keys)\n        if assigned_readonly_keys:\n            ctx.api.msg.readonly_keys_mutated(assigned_readonly_keys, context=key_expr)\n\n        default_type = ctx.arg_types[1][0]\n        default_expr = ctx.args[1][0]\n\n        value_types = []\n        for key in keys:\n            value_type = ctx.type.items.get(key)\n\n            if value_type is None:\n                ctx.api.msg.typeddict_key_not_found(ctx.type, key, key_expr)\n                return AnyType(TypeOfAny.from_error)\n\n            # The signature_callback above can't always infer the right signature\n            # (e.g. when the expression is a variable that happens to be a Literal str)\n            # so we need to handle the check ourselves here and make sure the provided\n            # default can be assigned to all key-value pairs we're updating.\n            if not is_subtype(default_type, value_type):\n                ctx.api.msg.typeddict_setdefault_arguments_inconsistent(\n                    default_type, value_type, default_expr\n                )\n                return AnyType(TypeOfAny.from_error)\n\n            value_types.append(value_type)\n\n        return make_simplified_union(value_types)\n    return ctx.default_return_type\n\n\ndef typed_dict_delitem_callback(ctx: MethodContext) -> Type:\n    \"\"\"Type check TypedDict.__delitem__.\"\"\"\n    if (\n        isinstance(ctx.type, TypedDictType)\n        and len(ctx.arg_types) == 1\n        and len(ctx.arg_types[0]) == 1\n    ):\n        key_expr = ctx.args[0][0]\n        keys = try_getting_str_literals(key_expr, ctx.arg_types[0][0])\n        if keys is None:\n            ctx.api.fail(\n                message_registry.TYPEDDICT_KEY_MUST_BE_STRING_LITERAL,\n                key_expr,\n                code=codes.LITERAL_REQ,\n            )\n            return AnyType(TypeOfAny.from_error)\n\n        for key in keys:\n            if key in ctx.type.required_keys or key in ctx.type.readonly_keys:\n                ctx.api.msg.typeddict_key_cannot_be_deleted(ctx.type, key, key_expr)\n            elif key not in ctx.type.items:\n                ctx.api.msg.typeddict_key_not_found(ctx.type, key, key_expr)\n    return ctx.default_return_type\n\n\n_TP_DICT_MUTATING_METHODS: Final = frozenset({\"update of TypedDict\", \"__ior__ of TypedDict\"})\n\n\ndef typed_dict_update_signature_callback(ctx: MethodSigContext) -> CallableType:\n    \"\"\"Try to infer a better signature type for methods that update `TypedDict`.\n\n    This includes: `TypedDict.update`, `TypedDict.__or__`, `TypedDict.__ror__`,\n    and `TypedDict.__ior__`.\n    \"\"\"\n    signature = ctx.default_signature\n    if isinstance(ctx.type, TypedDictType) and len(signature.arg_types) == 1:\n        arg_type = get_proper_type(signature.arg_types[0])\n        if not isinstance(arg_type, TypedDictType):\n            return signature\n        arg_type = ctx.type.copy_modified(\n            fallback=arg_type.create_anonymous_fallback(), required_keys=set()\n        )\n        if ctx.args and ctx.args[0]:\n            if signature.name in _TP_DICT_MUTATING_METHODS:\n                # If we want to mutate this object in place, we need to set this flag,\n                # it will trigger an extra check in TypedDict's checker.\n                arg_type.to_be_mutated = True\n            with ctx.api.msg.filter_errors(\n                filter_errors=lambda name, info: info.code != codes.TYPEDDICT_READONLY_MUTATED,\n                save_filtered_errors=True,\n            ):\n                inferred = get_proper_type(\n                    ctx.api.get_expression_type(ctx.args[0][0], type_context=arg_type)\n                )\n            if arg_type.to_be_mutated:\n                arg_type.to_be_mutated = False  # Done!\n            possible_tds = []\n            if isinstance(inferred, TypedDictType):\n                possible_tds = [inferred]\n            elif isinstance(inferred, UnionType):\n                possible_tds = [\n                    t\n                    for t in get_proper_types(inferred.relevant_items())\n                    if isinstance(t, TypedDictType)\n                ]\n            items = []\n            for td in possible_tds:\n                item = arg_type.copy_modified(\n                    required_keys=(arg_type.required_keys | td.required_keys)\n                    & arg_type.items.keys()\n                )\n                if not ctx.api.options.extra_checks:\n                    item = item.copy_modified(item_names=list(td.items))\n                items.append(item)\n            if items:\n                arg_type = make_simplified_union(items)\n        return signature.copy_modified(arg_types=[arg_type])\n    return signature\n\n\ndef int_pow_callback(ctx: MethodContext) -> Type:\n    \"\"\"Infer a more precise return type for int.__pow__.\"\"\"\n    # int.__pow__ has an optional modulo argument,\n    # so we expect 2 argument positions\n    if len(ctx.arg_types) == 2 and len(ctx.arg_types[0]) == 1 and len(ctx.arg_types[1]) == 0:\n        arg = ctx.args[0][0]\n        if isinstance(arg, IntExpr):\n            exponent = arg.value\n        elif isinstance(arg, UnaryExpr) and arg.op == \"-\" and isinstance(arg.expr, IntExpr):\n            exponent = -arg.expr.value\n        else:\n            # Right operand not an int literal or a negated literal -- give up.\n            return ctx.default_return_type\n        if exponent >= 0:\n            return ctx.api.named_generic_type(\"builtins.int\", [])\n        else:\n            return ctx.api.named_generic_type(\"builtins.float\", [])\n    return ctx.default_return_type\n\n\ndef int_neg_callback(ctx: MethodContext, multiplier: int = -1) -> Type:\n    \"\"\"Infer a more precise return type for int.__neg__ and int.__pos__.\n\n    This is mainly used to infer the return type as LiteralType\n    if the original underlying object is a LiteralType object.\n    \"\"\"\n    if isinstance(ctx.type, Instance) and ctx.type.last_known_value is not None:\n        value = ctx.type.last_known_value.value\n        fallback = ctx.type.last_known_value.fallback\n        if isinstance(value, int):\n            if is_literal_type_like(ctx.api.type_context[-1]):\n                return LiteralType(value=multiplier * value, fallback=fallback)\n            else:\n                return ctx.type.copy_modified(\n                    last_known_value=LiteralType(\n                        value=multiplier * value,\n                        fallback=fallback,\n                        line=ctx.type.line,\n                        column=ctx.type.column,\n                    )\n                )\n    elif isinstance(ctx.type, LiteralType):\n        value = ctx.type.value\n        fallback = ctx.type.fallback\n        if isinstance(value, int):\n            return LiteralType(value=multiplier * value, fallback=fallback)\n    return ctx.default_return_type\n\n\ndef int_pos_callback(ctx: MethodContext) -> Type:\n    \"\"\"Infer a more precise return type for int.__pos__.\n\n    This is identical to __neg__, except the value is not inverted.\n    \"\"\"\n    return int_neg_callback(ctx, +1)\n\n\ndef tuple_mul_callback(ctx: MethodContext) -> Type:\n    \"\"\"Infer a more precise return type for tuple.__mul__ and tuple.__rmul__.\n\n    This is used to return a specific sized tuple if multiplied by Literal int\n    \"\"\"\n    if not isinstance(ctx.type, TupleType):\n        return ctx.default_return_type\n\n    arg_type = get_proper_type(ctx.arg_types[0][0])\n    if isinstance(arg_type, Instance) and arg_type.last_known_value is not None:\n        value = arg_type.last_known_value.value\n        if isinstance(value, int):\n            return ctx.type.copy_modified(items=ctx.type.items * value)\n    elif isinstance(arg_type, LiteralType):\n        value = arg_type.value\n        if isinstance(value, int):\n            return ctx.type.copy_modified(items=ctx.type.items * value)\n\n    return ctx.default_return_type\n"
  },
  {
    "path": "mypy/plugins/enums.py",
    "content": "\"\"\"\nThis file contains a variety of plugins for refining how mypy infers types of\nexpressions involving Enums.\n\nCurrently, this file focuses on providing better inference for expressions like\n'SomeEnum.FOO.name' and 'SomeEnum.FOO.value'. Note that the type of both expressions\nwill vary depending on exactly which instance of SomeEnum we're looking at.\n\nNote that this file does *not* contain all special-cased logic related to enums:\nwe actually bake some of it directly in to the semantic analysis layer (see\nsemanal_enum.py).\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable, Sequence\nfrom typing import TypeVar, cast\n\nimport mypy.plugin  # To avoid circular imports.\nfrom mypy.checker_shared import TypeCheckerSharedApi\nfrom mypy.nodes import TypeInfo, Var\nfrom mypy.subtypes import is_equivalent\nfrom mypy.typeops import fixup_partial_type, make_simplified_union\nfrom mypy.types import (\n    ELLIPSIS_TYPE_NAMES,\n    CallableType,\n    Instance,\n    LiteralType,\n    ProperType,\n    Type,\n    get_proper_type,\n    is_named_instance,\n)\n\n\ndef enum_name_callback(ctx: mypy.plugin.AttributeContext) -> Type:\n    \"\"\"This plugin refines the 'name' attribute in enums to act as if\n    they were declared to be final.\n\n    For example, the expression 'MyEnum.FOO.name' normally is inferred\n    to be of type 'str'.\n\n    This plugin will instead make the inferred type be a 'str' where the\n    last known value is 'Literal[\"FOO\"]'. This means it would be legal to\n    use 'MyEnum.FOO.name' in contexts that expect a Literal type, just like\n    any other Final variable or attribute.\n\n    This plugin assumes that the provided context is an attribute access\n    matching one of the strings found in 'ENUM_NAME_ACCESS'.\n    \"\"\"\n    enum_field_name = _extract_underlying_field_name(ctx.type)\n    if enum_field_name is None:\n        return ctx.default_attr_type\n    else:\n        str_type = ctx.api.named_generic_type(\"builtins.str\", [])\n        literal_type = LiteralType(enum_field_name, fallback=str_type)\n        return str_type.copy_modified(last_known_value=literal_type)\n\n\n_T = TypeVar(\"_T\")\n\n\ndef _first(it: Iterable[_T]) -> _T | None:\n    \"\"\"Return the first value from any iterable.\n\n    Returns ``None`` if the iterable is empty.\n    \"\"\"\n    for val in it:\n        return val\n    return None\n\n\ndef _infer_value_type_with_auto_fallback(\n    ctx: mypy.plugin.AttributeContext, proper_type: ProperType | None\n) -> Type | None:\n    \"\"\"Figure out the type of an enum value accounting for `auto()`.\n\n    This method is a no-op for a `None` proper_type and also in the case where\n    the type is not \"enum.auto\"\n    \"\"\"\n    if proper_type is None:\n        return None\n    proper_type = get_proper_type(fixup_partial_type(proper_type))\n    # Enums in stubs may have ... instead of actual values. If `_value_` is annotated\n    # (manually or inherited from IntEnum, for example), it is a more reasonable guess\n    # than literal ellipsis type.\n    if (\n        _is_defined_in_stub(ctx)\n        and isinstance(proper_type, Instance)\n        and proper_type.type.fullname in ELLIPSIS_TYPE_NAMES\n        and isinstance(ctx.type, Instance)\n    ):\n        value_type = ctx.type.type.get(\"_value_\")\n        if value_type is not None and isinstance(var := value_type.node, Var):\n            return var.type\n        return proper_type\n    if not (isinstance(proper_type, Instance) and proper_type.type.fullname == \"enum.auto\"):\n        if is_named_instance(proper_type, \"enum.member\") and proper_type.args:\n            return proper_type.args[0]\n        return proper_type\n    assert isinstance(ctx.type, Instance), \"An incorrect ctx.type was passed.\"\n    info = ctx.type.type\n    # Find the first _generate_next_value_ on the mro.  We need to know\n    # if it is `Enum` because `Enum` types say that the return-value of\n    # `_generate_next_value_` is `Any`.  In reality the default `auto()`\n    # returns an `int` (presumably the `Any` in typeshed is to make it\n    # easier to subclass and change the returned type).\n    type_with_gnv = _first(ti for ti in info.mro if ti.names.get(\"_generate_next_value_\"))\n    if type_with_gnv is None:\n        return ctx.default_attr_type\n\n    stnode = type_with_gnv.names[\"_generate_next_value_\"]\n\n    # This should be a `CallableType`\n    node_type = get_proper_type(stnode.type)\n    if isinstance(node_type, CallableType):\n        if type_with_gnv.fullname == \"enum.Enum\":\n            int_type = ctx.api.named_generic_type(\"builtins.int\", [])\n            return int_type\n        return get_proper_type(node_type.ret_type)\n    return ctx.default_attr_type\n\n\ndef _is_defined_in_stub(ctx: mypy.plugin.AttributeContext) -> bool:\n    assert isinstance(ctx.api, TypeCheckerSharedApi)\n    return isinstance(ctx.type, Instance) and ctx.api.is_defined_in_stub(ctx.type)\n\n\ndef _implements_new(info: TypeInfo) -> bool:\n    \"\"\"Check whether __new__ comes from enum.Enum or was implemented in a\n    subclass of enum.Enum. In the latter case, we must infer Any as long as mypy can't infer\n    the type of _value_ from assignments in __new__.\n\n    If, however, __new__ comes from a user-defined class that is not an Enum subclass (i.e.\n    the data type) this is allowed, because we should in general infer that an enum entry's\n    value has that type.\n    \"\"\"\n    type_with_new = _first(ti for ti in info.mro if ti.is_enum and ti.names.get(\"__new__\"))\n    if type_with_new is None:\n        return False\n    return type_with_new.fullname not in (\"enum.Enum\", \"enum.IntEnum\", \"enum.StrEnum\")\n\n\ndef enum_member_callback(ctx: mypy.plugin.FunctionContext) -> Type:\n    \"\"\"By default `member(1)` will be inferred as `member[int]`,\n    we want to improve the inference to be `Literal[1]` here.\"\"\"\n    if ctx.arg_types and ctx.arg_types[0]:\n        arg = get_proper_type(ctx.arg_types[0][0])\n        proper_return = get_proper_type(ctx.default_return_type)\n        if (\n            isinstance(arg, Instance)\n            and arg.last_known_value\n            and isinstance(proper_return, Instance)\n            and len(proper_return.args) == 1\n        ):\n            return proper_return.copy_modified(args=[arg])\n    return ctx.default_return_type\n\n\ndef enum_value_callback(ctx: mypy.plugin.AttributeContext) -> Type:\n    \"\"\"This plugin refines the 'value' attribute in enums to refer to\n    the original underlying value. For example, suppose we have the\n    following:\n\n        class SomeEnum:\n            FOO = A()\n            BAR = B()\n\n    By default, mypy will infer that 'SomeEnum.FOO.value' and\n    'SomeEnum.BAR.value' both are of type 'Any'. This plugin refines\n    this inference so that mypy understands the expressions are\n    actually of types 'A' and 'B' respectively. This better reflects\n    the actual runtime behavior.\n\n    This plugin works simply by looking up the original value assigned\n    to the enum. For example, when this plugin sees 'SomeEnum.BAR.value',\n    it will look up whatever type 'BAR' had in the SomeEnum TypeInfo and\n    use that as the inferred type of the overall expression.\n\n    This plugin assumes that the provided context is an attribute access\n    matching one of the strings found in 'ENUM_VALUE_ACCESS'.\n    \"\"\"\n    enum_field_name = _extract_underlying_field_name(ctx.type)\n    if enum_field_name is None:\n        # We do not know the enum field name (perhaps it was passed to a\n        # function and we only know that it _is_ a member).  All is not lost\n        # however, if we can prove that the all of the enum members have the\n        # same value-type, then it doesn't matter which member was passed in.\n        # The value-type is still known.\n        if isinstance(ctx.type, Instance):\n            info = ctx.type.type\n\n            # As long as mypy doesn't understand attribute creation in __new__,\n            # there is no way to predict the value type if the enum class has a\n            # custom implementation\n            if _implements_new(info):\n                return ctx.default_attr_type\n\n            stnodes = (info.get(name) for name in info.names)\n\n            # Enums _can_ have methods, instance attributes, and `nonmember`s.\n            # Omit methods and attributes created by assigning to self.*\n            # for our value inference.\n            node_types = (\n                get_proper_type(n.type) if n else None\n                for n in stnodes\n                if n is None or not n.implicit\n            )\n            proper_types = [\n                _infer_value_type_with_auto_fallback(ctx, t)\n                for t in node_types\n                if t is None\n                or (not isinstance(t, CallableType) and not is_named_instance(t, \"enum.nonmember\"))\n            ]\n            underlying_type = _first(proper_types)\n            if underlying_type is None:\n                return ctx.default_attr_type\n\n            # At first we try to predict future `value` type if all other items\n            # have the same type. For example, `int`.\n            # If this is the case, we simply return this type.\n            # See https://github.com/python/mypy/pull/9443\n            all_same_value_type = all(\n                proper_type is not None and proper_type == underlying_type\n                for proper_type in proper_types\n            )\n            if all_same_value_type:\n                if underlying_type is not None:\n                    return underlying_type\n\n            # But, after we started treating all `Enum` values as `Final`,\n            # we start to infer types in\n            # `item = 1` as `Literal[1]`, not just `int`.\n            # So, for example types in this `Enum` will all be different:\n            #\n            #  class Ordering(IntEnum):\n            #      one = 1\n            #      two = 2\n            #      three = 3\n            #\n            # We will infer three `Literal` types here.\n            # They are not the same, but they are equivalent.\n            # So, we unify them to make sure `.value` prediction still works.\n            # Result will be `Literal[1] | Literal[2] | Literal[3]` for this case.\n            all_equivalent_types = all(\n                proper_type is not None and is_equivalent(proper_type, underlying_type)\n                for proper_type in proper_types\n            )\n            if all_equivalent_types:\n                return make_simplified_union(cast(Sequence[Type], proper_types))\n        return ctx.default_attr_type\n\n    assert isinstance(ctx.type, Instance)\n    info = ctx.type.type\n\n    # As long as mypy doesn't understand attribute creation in __new__,\n    # there is no way to predict the value type if the enum class has a\n    # custom implementation\n    if _implements_new(info):\n        return ctx.default_attr_type\n\n    stnode = info.get(enum_field_name)\n    if stnode is None:\n        return ctx.default_attr_type\n\n    underlying_type = _infer_value_type_with_auto_fallback(ctx, get_proper_type(stnode.type))\n    if underlying_type is None:\n        return ctx.default_attr_type\n\n    return underlying_type\n\n\ndef _extract_underlying_field_name(typ: Type) -> str | None:\n    \"\"\"If the given type corresponds to some Enum instance, returns the\n    original name of that enum. For example, if we receive in the type\n    corresponding to 'SomeEnum.FOO', we return the string \"SomeEnum.Foo\".\n\n    This helper takes advantage of the fact that Enum instances are valid\n    to use inside Literal[...] types. An expression like 'SomeEnum.FOO' is\n    actually represented by an Instance type with a Literal enum fallback.\n\n    We can examine this Literal fallback to retrieve the string.\n    \"\"\"\n    typ = get_proper_type(typ)\n    if not isinstance(typ, Instance):\n        return None\n\n    if not typ.type.is_enum:\n        return None\n\n    underlying_literal = typ.last_known_value\n    if underlying_literal is None:\n        return None\n\n    # The checks above have verified this LiteralType is representing an enum value,\n    # which means the 'value' field is guaranteed to be the name of the enum field\n    # as a string.\n    assert isinstance(underlying_literal.value, str)\n    return underlying_literal.value\n"
  },
  {
    "path": "mypy/plugins/functools.py",
    "content": "\"\"\"Plugin for supporting the functools standard library module.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final, NamedTuple\n\nimport mypy.checker\nimport mypy.plugin\nimport mypy.semanal\nfrom mypy.argmap import map_actuals_to_formals\nfrom mypy.erasetype import erase_typevars\nfrom mypy.nodes import (\n    ARG_POS,\n    ARG_STAR2,\n    SYMBOL_FUNCBASE_TYPES,\n    ArgKind,\n    Argument,\n    CallExpr,\n    NameExpr,\n    Var,\n)\nfrom mypy.plugins.common import add_method_to_class\nfrom mypy.typeops import get_all_type_vars\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    Overloaded,\n    ParamSpecFlavor,\n    ParamSpecType,\n    Type,\n    TypeOfAny,\n    TypeVarType,\n    UnboundType,\n    UnionType,\n    get_proper_type,\n)\n\nfunctools_total_ordering_makers: Final = {\"functools.total_ordering\"}\n\n_ORDERING_METHODS: Final = {\"__lt__\", \"__le__\", \"__gt__\", \"__ge__\"}\n\nPARTIAL: Final = \"functools.partial\"\n\n\nclass _MethodInfo(NamedTuple):\n    is_static: bool\n    type: CallableType\n\n\ndef functools_total_ordering_maker_callback(\n    ctx: mypy.plugin.ClassDefContext, auto_attribs_default: bool = False\n) -> bool:\n    \"\"\"Add dunder methods to classes decorated with functools.total_ordering.\"\"\"\n    comparison_methods = _analyze_class(ctx)\n    if not comparison_methods:\n        ctx.api.fail(\n            'No ordering operation defined when using \"functools.total_ordering\": < > <= >=',\n            ctx.reason,\n        )\n        return True\n\n    # prefer __lt__ to __le__ to __gt__ to __ge__\n    root = max(comparison_methods, key=lambda k: (comparison_methods[k] is None, k))\n    root_method = comparison_methods[root]\n    if not root_method:\n        # None of the defined comparison methods can be analysed\n        return True\n\n    other_type = _find_other_type(root_method)\n    bool_type = ctx.api.named_type(\"builtins.bool\")\n    ret_type: Type = bool_type\n    if root_method.type.ret_type != ctx.api.named_type(\"builtins.bool\"):\n        proper_ret_type = get_proper_type(root_method.type.ret_type)\n        if not (\n            isinstance(proper_ret_type, UnboundType)\n            and proper_ret_type.name.split(\".\")[-1] == \"bool\"\n        ):\n            ret_type = AnyType(TypeOfAny.implementation_artifact)\n    for additional_op in _ORDERING_METHODS:\n        # Either the method is not implemented\n        # or has an unknown signature that we can now extrapolate.\n        if not comparison_methods.get(additional_op):\n            args = [Argument(Var(\"other\", other_type), other_type, None, ARG_POS)]\n            add_method_to_class(ctx.api, ctx.cls, additional_op, args, ret_type)\n\n    return True\n\n\ndef _find_other_type(method: _MethodInfo) -> Type:\n    \"\"\"Find the type of the ``other`` argument in a comparison method.\"\"\"\n    first_arg_pos = 0 if method.is_static else 1\n    cur_pos_arg = 0\n    other_arg = None\n    for arg_kind, arg_type in zip(method.type.arg_kinds, method.type.arg_types):\n        if arg_kind.is_positional():\n            if cur_pos_arg == first_arg_pos:\n                other_arg = arg_type\n                break\n\n            cur_pos_arg += 1\n        elif arg_kind != ARG_STAR2:\n            other_arg = arg_type\n            break\n\n    if other_arg is None:\n        return AnyType(TypeOfAny.implementation_artifact)\n\n    return other_arg\n\n\ndef _analyze_class(ctx: mypy.plugin.ClassDefContext) -> dict[str, _MethodInfo | None]:\n    \"\"\"Analyze the class body, its parents, and return the comparison methods found.\"\"\"\n    # Traverse the MRO and collect ordering methods.\n    comparison_methods: dict[str, _MethodInfo | None] = {}\n    # Skip object because total_ordering does not use methods from object\n    for cls in ctx.cls.info.mro[:-1]:\n        for name in _ORDERING_METHODS:\n            if name in cls.names and name not in comparison_methods:\n                node = cls.names[name].node\n                if isinstance(node, SYMBOL_FUNCBASE_TYPES) and isinstance(node.type, CallableType):\n                    comparison_methods[name] = _MethodInfo(node.is_static, node.type)\n                    continue\n\n                if isinstance(node, Var):\n                    proper_type = get_proper_type(node.type)\n                    if isinstance(proper_type, CallableType):\n                        comparison_methods[name] = _MethodInfo(node.is_staticmethod, proper_type)\n                        continue\n\n                comparison_methods[name] = None\n\n    return comparison_methods\n\n\ndef partial_new_callback(ctx: mypy.plugin.FunctionContext) -> Type:\n    \"\"\"Infer a more precise return type for functools.partial\"\"\"\n    if not isinstance(ctx.api, mypy.checker.TypeChecker):  # use internals\n        return ctx.default_return_type\n    if len(ctx.arg_types) != 3:  # fn, *args, **kwargs\n        return ctx.default_return_type\n    if len(ctx.arg_types[0]) != 1:\n        return ctx.default_return_type\n\n    if isinstance(get_proper_type(ctx.arg_types[0][0]), Overloaded):\n        # TODO: handle overloads, just fall back to whatever the non-plugin code does\n        return ctx.default_return_type\n    return handle_partial_with_callee(ctx, callee=ctx.arg_types[0][0])\n\n\ndef handle_partial_with_callee(ctx: mypy.plugin.FunctionContext, callee: Type) -> Type:\n    if not isinstance(ctx.api, mypy.checker.TypeChecker):  # use internals\n        return ctx.default_return_type\n\n    if isinstance(callee_proper := get_proper_type(callee), UnionType):\n        return UnionType.make_union(\n            [handle_partial_with_callee(ctx, item) for item in callee_proper.items]\n        )\n\n    fn_type = ctx.api.extract_callable_type(callee, ctx=ctx.default_return_type)\n    if fn_type is None:\n        return ctx.default_return_type\n\n    # We must normalize from the start to have coherent view together with TypeChecker.\n    fn_type = fn_type.with_unpacked_kwargs().with_normalized_var_args()\n\n    last_context = ctx.api.type_context[-1]\n    if not fn_type.is_type_obj():\n        # We wrap the return type to get use of a possible type context provided by caller.\n        # We cannot do this in case of class objects, since otherwise the plugin may get\n        # falsely triggered when evaluating the constructed call itself.\n        ret_type: Type = ctx.api.named_generic_type(PARTIAL, [fn_type.ret_type])\n        wrapped_return = True\n    else:\n        ret_type = fn_type.ret_type\n        # Instead, for class objects we ignore any type context to avoid spurious errors,\n        # since the type context will be partial[X] etc., not X.\n        ctx.api.type_context[-1] = None\n        wrapped_return = False\n\n    # Flatten actual to formal mapping, since this is what check_call() expects.\n    actual_args = []\n    actual_arg_kinds = []\n    actual_arg_names = []\n    actual_types = []\n    seen_args = set()\n    for i, param in enumerate(ctx.args[1:], start=1):\n        for j, a in enumerate(param):\n            if a in seen_args:\n                # Same actual arg can map to multiple formals, but we need to include\n                # each one only once.\n                continue\n            # Here we rely on the fact that expressions are essentially immutable, so\n            # they can be compared by identity.\n            seen_args.add(a)\n            actual_args.append(a)\n            actual_arg_kinds.append(ctx.arg_kinds[i][j])\n            actual_arg_names.append(ctx.arg_names[i][j])\n            actual_types.append(ctx.arg_types[i][j])\n\n    formal_to_actual = map_actuals_to_formals(\n        actual_kinds=actual_arg_kinds,\n        actual_names=actual_arg_names,\n        formal_kinds=fn_type.arg_kinds,\n        formal_names=fn_type.arg_names,\n        actual_arg_type=lambda i: actual_types[i],\n    )\n\n    # We need to remove any type variables that appear only in formals that have\n    # no actuals, to avoid eagerly binding them in check_call() below.\n    can_infer_ids = set()\n    for i, arg_type in enumerate(fn_type.arg_types):\n        if not formal_to_actual[i]:\n            continue\n        can_infer_ids.update({tv.id for tv in get_all_type_vars(arg_type)})\n\n    # special_sig=\"partial\" allows omission of args/kwargs typed with ParamSpec\n    defaulted = fn_type.copy_modified(\n        arg_kinds=[\n            (\n                ArgKind.ARG_OPT\n                if k == ArgKind.ARG_POS\n                else (ArgKind.ARG_NAMED_OPT if k == ArgKind.ARG_NAMED else k)\n            )\n            for k in fn_type.arg_kinds\n        ],\n        ret_type=ret_type,\n        variables=[\n            tv\n            for tv in fn_type.variables\n            # Keep TypeVarTuple/ParamSpec to avoid spurious errors on empty args.\n            if tv.id in can_infer_ids or not isinstance(tv, TypeVarType)\n        ],\n        special_sig=\"partial\",\n    )\n    if defaulted.line < 0:\n        # Make up a line number if we don't have one\n        defaulted.set_line(ctx.default_return_type)\n\n    # Create a valid context for various ad-hoc inspections in check_call().\n    call_expr = CallExpr(\n        callee=ctx.args[0][0],\n        args=actual_args,\n        arg_kinds=actual_arg_kinds,\n        arg_names=actual_arg_names,\n        analyzed=ctx.context.analyzed if isinstance(ctx.context, CallExpr) else None,\n    )\n    call_expr.set_line(ctx.context)\n\n    _, bound = ctx.api.expr_checker.check_call(\n        callee=defaulted,\n        args=actual_args,\n        arg_kinds=actual_arg_kinds,\n        arg_names=actual_arg_names,\n        context=call_expr,\n    )\n    if not wrapped_return:\n        # Restore previously ignored context.\n        ctx.api.type_context[-1] = last_context\n\n    bound = get_proper_type(bound)\n    if not isinstance(bound, CallableType):\n        return ctx.default_return_type\n\n    if wrapped_return:\n        # Reverse the wrapping we did above.\n        ret_type = get_proper_type(bound.ret_type)\n        if not isinstance(ret_type, Instance) or ret_type.type.fullname != PARTIAL:\n            return ctx.default_return_type\n        bound = bound.copy_modified(ret_type=ret_type.args[0])\n\n    partial_kinds = []\n    partial_types = []\n    partial_names = []\n    # We need to fully apply any positional arguments (they cannot be respecified)\n    # However, keyword arguments can be respecified, so just give them a default\n    for i, actuals in enumerate(formal_to_actual):\n        if len(bound.arg_types) == len(fn_type.arg_types):\n            arg_type = bound.arg_types[i]\n            if not mypy.checker.is_valid_inferred_type(arg_type, ctx.api.options):\n                arg_type = fn_type.arg_types[i]  # bit of a hack\n        else:\n            # TODO: I assume that bound and fn_type have the same arguments. It appears this isn't\n            # true when PEP 646 things are happening. See testFunctoolsPartialTypeVarTuple\n            arg_type = fn_type.arg_types[i]\n\n        if not actuals or fn_type.arg_kinds[i] in (ArgKind.ARG_STAR, ArgKind.ARG_STAR2):\n            partial_kinds.append(fn_type.arg_kinds[i])\n            partial_types.append(arg_type)\n            partial_names.append(fn_type.arg_names[i])\n        else:\n            assert actuals\n            if any(actual_arg_kinds[j] in (ArgKind.ARG_POS, ArgKind.ARG_STAR) for j in actuals):\n                # Don't add params for arguments passed positionally\n                continue\n            # Add defaulted params for arguments passed via keyword\n            kind = actual_arg_kinds[actuals[0]]\n            if kind == ArgKind.ARG_NAMED or kind == ArgKind.ARG_STAR2:\n                kind = ArgKind.ARG_NAMED_OPT\n            partial_kinds.append(kind)\n            partial_types.append(arg_type)\n            partial_names.append(fn_type.arg_names[i])\n\n    ret_type = bound.ret_type\n    if not mypy.checker.is_valid_inferred_type(ret_type, ctx.api.options):\n        ret_type = fn_type.ret_type  # same kind of hack as above\n\n    # Technically, we should set definition to None here, since it will not be recovered\n    # on warm cache runs in fixup.py. This however may hide some helpful info in error\n    # messages, so we are keeping it for now. See also issue #20640.\n    partially_applied = fn_type.copy_modified(\n        arg_types=partial_types,\n        arg_kinds=partial_kinds,\n        arg_names=partial_names,\n        ret_type=ret_type,\n        special_sig=\"partial\",\n    )\n\n    # Do not leak typevars from generic functions - they cannot be usable.\n    # Keep them in the wrapped callable, but avoid `partial[SomeStrayTypeVar]`\n    erased_ret_type = erase_typevars(ret_type, [tv.id for tv in fn_type.variables])\n\n    ret = ctx.api.named_generic_type(PARTIAL, [erased_ret_type])\n    ret = ret.copy_with_extra_attr(\"__mypy_partial\", partially_applied)\n    if partially_applied.param_spec():\n        assert ret.extra_attrs is not None  # copy_with_extra_attr above ensures this\n        attrs = ret.extra_attrs.copy()\n        if ArgKind.ARG_STAR in actual_arg_kinds:\n            attrs.immutable.add(\"__mypy_partial_paramspec_args_bound\")\n        if ArgKind.ARG_STAR2 in actual_arg_kinds:\n            attrs.immutable.add(\"__mypy_partial_paramspec_kwargs_bound\")\n        ret.extra_attrs = attrs\n    return ret\n\n\ndef partial_call_callback(ctx: mypy.plugin.MethodContext) -> Type:\n    \"\"\"Infer a more precise return type for functools.partial.__call__.\"\"\"\n    if (\n        not isinstance(ctx.api, mypy.checker.TypeChecker)  # use internals\n        or not isinstance(ctx.type, Instance)\n        or ctx.type.type.fullname != PARTIAL\n        or not ctx.type.extra_attrs\n        or \"__mypy_partial\" not in ctx.type.extra_attrs.attrs\n    ):\n        return ctx.default_return_type\n\n    extra_attrs = ctx.type.extra_attrs\n    partial_type = get_proper_type(extra_attrs.attrs[\"__mypy_partial\"])\n    if len(ctx.arg_types) != 2:  # *args, **kwargs\n        return ctx.default_return_type\n\n    # See comments for similar actual to formal code above\n    actual_args = []\n    actual_arg_kinds = []\n    actual_arg_names = []\n    seen_args = set()\n    for i, param in enumerate(ctx.args):\n        for j, a in enumerate(param):\n            if a in seen_args:\n                continue\n            seen_args.add(a)\n            actual_args.append(a)\n            actual_arg_kinds.append(ctx.arg_kinds[i][j])\n            actual_arg_names.append(ctx.arg_names[i][j])\n\n    result, _ = ctx.api.expr_checker.check_call(\n        callee=partial_type,\n        args=actual_args,\n        arg_kinds=actual_arg_kinds,\n        arg_names=actual_arg_names,\n        context=ctx.context,\n    )\n    if not isinstance(partial_type, CallableType) or partial_type.param_spec() is None:\n        return result\n\n    args_bound = \"__mypy_partial_paramspec_args_bound\" in extra_attrs.immutable\n    kwargs_bound = \"__mypy_partial_paramspec_kwargs_bound\" in extra_attrs.immutable\n\n    passed_paramspec_parts = [\n        arg.node.type\n        for arg in actual_args\n        if isinstance(arg, NameExpr)\n        and isinstance(arg.node, Var)\n        and isinstance(arg.node.type, ParamSpecType)\n    ]\n    # ensure *args: P.args\n    args_passed = any(part.flavor == ParamSpecFlavor.ARGS for part in passed_paramspec_parts)\n    if not args_bound and not args_passed:\n        ctx.api.expr_checker.msg.too_few_arguments(partial_type, ctx.context, actual_arg_names)\n    elif args_bound and args_passed:\n        ctx.api.expr_checker.msg.too_many_arguments(partial_type, ctx.context)\n\n    # ensure **kwargs: P.kwargs\n    kwargs_passed = any(part.flavor == ParamSpecFlavor.KWARGS for part in passed_paramspec_parts)\n    if not kwargs_bound and not kwargs_passed:\n        ctx.api.expr_checker.msg.too_few_arguments(partial_type, ctx.context, actual_arg_names)\n\n    return result\n"
  },
  {
    "path": "mypy/plugins/proper_plugin.py",
    "content": "\"\"\"\nThis plugin is helpful for mypy development itself.\nBy default, it is not enabled for mypy users.\n\nIt also can be used by plugin developers as a part of their CI checks.\n\nIt finds missing ``get_proper_type()`` call, which can lead to multiple errors.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\n\nfrom mypy.checker import TypeChecker\nfrom mypy.nodes import TypeInfo\nfrom mypy.plugin import FunctionContext, Plugin\nfrom mypy.subtypes import is_proper_subtype\nfrom mypy.types import (\n    AnyType,\n    FunctionLike,\n    Instance,\n    NoneTyp,\n    ProperType,\n    TupleType,\n    Type,\n    UnionType,\n    get_proper_type,\n    get_proper_types,\n)\n\n\nclass ProperTypePlugin(Plugin):\n    \"\"\"\n    A plugin to ensure that every type is expanded before doing any special-casing.\n\n    This solves the problem that we have hundreds of call sites like:\n\n        if isinstance(typ, UnionType):\n            ...  # special-case union\n\n    But after introducing a new type TypeAliasType (and removing immediate expansion)\n    all these became dangerous because typ may be e.g. an alias to union.\n    \"\"\"\n\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if fullname == \"builtins.isinstance\":\n            return isinstance_proper_hook\n        if fullname == \"mypy.types.get_proper_type\":\n            return proper_type_hook\n        if fullname == \"mypy.types.get_proper_types\":\n            return proper_types_hook\n        return None\n\n\ndef isinstance_proper_hook(ctx: FunctionContext) -> Type:\n    if len(ctx.arg_types) != 2 or not ctx.arg_types[1]:\n        return ctx.default_return_type\n\n    right = get_proper_type(ctx.arg_types[1][0])\n    for arg in ctx.arg_types[0]:\n        if (\n            is_improper_type(arg) or isinstance(get_proper_type(arg), AnyType)\n        ) and is_dangerous_target(right):\n            if is_special_target(right):\n                return ctx.default_return_type\n            ctx.api.fail(\n                \"Never apply isinstance() to unexpanded types;\"\n                \" use mypy.types.get_proper_type() first\",\n                ctx.context,\n            )\n            ctx.api.note(  # type: ignore[attr-defined]\n                \"If you pass on the original type\"\n                \" after the check, always use its unexpanded version\",\n                ctx.context,\n            )\n    return ctx.default_return_type\n\n\ndef is_special_target(right: ProperType) -> bool:\n    \"\"\"Whitelist some special cases for use in isinstance() with improper types.\"\"\"\n    if isinstance(right, FunctionLike) and right.is_type_obj():\n        if right.type_object().fullname == \"builtins.tuple\":\n            # Used with Union[Type, Tuple[Type, ...]].\n            return True\n        if right.type_object().fullname in (\n            \"mypy.types.Type\",\n            \"mypy.types.ProperType\",\n            \"mypy.types.TypeAliasType\",\n        ):\n            # Special case: things like assert isinstance(typ, ProperType) are always OK.\n            return True\n        if right.type_object().fullname in (\n            \"mypy.types.UnboundType\",\n            \"mypy.types.TypeVarLikeType\",\n            \"mypy.types.TypeVarType\",\n            \"mypy.types.UnpackType\",\n            \"mypy.types.TypeVarTupleType\",\n            \"mypy.types.ParamSpecType\",\n            \"mypy.types.Parameters\",\n            \"mypy.types.RawExpressionType\",\n            \"mypy.types.EllipsisType\",\n            \"mypy.types.StarType\",\n            \"mypy.types.TypeList\",\n            \"mypy.types.CallableArgument\",\n            \"mypy.types.PartialType\",\n            \"mypy.types.ErasedType\",\n            \"mypy.types.DeletedType\",\n            \"mypy.types.RequiredType\",\n            \"mypy.types.ReadOnlyType\",\n            \"mypy.types.TypeGuardedType\",\n            \"mypy.types.PlaceholderType\",\n        ):\n            # Special case: these are not valid targets for a type alias and thus safe.\n            # TODO: introduce a SyntheticType base to simplify this?\n            return True\n    elif isinstance(right, TupleType):\n        return all(is_special_target(t) for t in get_proper_types(right.items))\n    return False\n\n\ndef is_improper_type(typ: Type) -> bool:\n    \"\"\"Is this a type that is not a subtype of ProperType?\"\"\"\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        info = typ.type\n        return info.has_base(\"mypy.types.Type\") and not info.has_base(\"mypy.types.ProperType\")\n    if isinstance(typ, UnionType):\n        return any(is_improper_type(t) for t in typ.items)\n    return False\n\n\ndef is_dangerous_target(typ: ProperType) -> bool:\n    \"\"\"Is this a dangerous target (right argument) for an isinstance() check?\"\"\"\n    if isinstance(typ, TupleType):\n        return any(is_dangerous_target(get_proper_type(t)) for t in typ.items)\n    if isinstance(typ, FunctionLike) and typ.is_type_obj():\n        return typ.type_object().has_base(\"mypy.types.Type\")\n    return False\n\n\ndef proper_type_hook(ctx: FunctionContext) -> Type:\n    \"\"\"Check if this get_proper_type() call is not redundant.\"\"\"\n    arg_types = ctx.arg_types[0]\n    if arg_types:\n        arg_type = get_proper_type(arg_types[0])\n        proper_type = get_proper_type_instance(ctx)\n        if is_proper_subtype(arg_type, UnionType.make_union([NoneTyp(), proper_type])):\n            # Minimize amount of spurious errors from overload machinery.\n            # TODO: call the hook on the overload as a whole?\n            if isinstance(arg_type, (UnionType, Instance)):\n                ctx.api.fail(\"Redundant call to get_proper_type()\", ctx.context)\n    return ctx.default_return_type\n\n\ndef proper_types_hook(ctx: FunctionContext) -> Type:\n    \"\"\"Check if this get_proper_types() call is not redundant.\"\"\"\n    arg_types = ctx.arg_types[0]\n    if arg_types:\n        arg_type = arg_types[0]\n        proper_type = get_proper_type_instance(ctx)\n        item_type = UnionType.make_union([NoneTyp(), proper_type])\n        ok_type = ctx.api.named_generic_type(\"typing.Iterable\", [item_type])\n        if is_proper_subtype(arg_type, ok_type):\n            ctx.api.fail(\"Redundant call to get_proper_types()\", ctx.context)\n    return ctx.default_return_type\n\n\ndef get_proper_type_instance(ctx: FunctionContext) -> Instance:\n    checker = ctx.api\n    assert isinstance(checker, TypeChecker)\n    types = checker.modules[\"mypy.types\"]\n    proper_type_info = types.names[\"ProperType\"]\n    assert isinstance(proper_type_info.node, TypeInfo)\n    return Instance(proper_type_info.node, [])\n\n\ndef plugin(version: str) -> type[ProperTypePlugin]:\n    return ProperTypePlugin\n"
  },
  {
    "path": "mypy/plugins/singledispatch.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import NamedTuple, TypeAlias as _TypeAlias, TypeVar\n\nfrom mypy.messages import format_type\nfrom mypy.nodes import ARG_POS, Argument, Block, ClassDef, Context, SymbolTable, TypeInfo, Var\nfrom mypy.options import Options\nfrom mypy.plugin import CheckerPluginInterface, FunctionContext, MethodContext, MethodSigContext\nfrom mypy.plugins.common import add_method_to_class\nfrom mypy.plugins.constants import SINGLEDISPATCH_REGISTER_RETURN_CLASS\nfrom mypy.subtypes import is_subtype\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    FunctionLike,\n    Instance,\n    NoneType,\n    Overloaded,\n    Type,\n    TypeOfAny,\n    get_proper_type,\n)\n\n\nclass SingledispatchTypeVars(NamedTuple):\n    return_type: Type\n    fallback: CallableType\n\n\nclass RegisterCallableInfo(NamedTuple):\n    register_type: Type\n    singledispatch_obj: Instance\n\n\ndef get_singledispatch_info(typ: Instance) -> SingledispatchTypeVars | None:\n    if len(typ.args) == 2:\n        return SingledispatchTypeVars(*typ.args)  # type: ignore[arg-type]\n    return None\n\n\nT = TypeVar(\"T\")\n\n\ndef get_first_arg(args: list[list[T]]) -> T | None:\n    \"\"\"Get the element that corresponds to the first argument passed to the function\"\"\"\n    if args and args[0]:\n        return args[0][0]\n    return None\n\n\ndef make_fake_register_class_instance(\n    api: CheckerPluginInterface, type_args: Sequence[Type]\n) -> Instance:\n    defn = ClassDef(SINGLEDISPATCH_REGISTER_RETURN_CLASS, Block([]))\n    defn.fullname = f\"functools.{SINGLEDISPATCH_REGISTER_RETURN_CLASS}\"\n    info = TypeInfo(SymbolTable(), defn, \"functools\")\n    obj_type = api.named_generic_type(\"builtins.object\", []).type\n    info.bases = [Instance(obj_type, [])]\n    info.mro = [info, obj_type]\n    defn.info = info\n\n    func_arg = Argument(Var(\"name\"), AnyType(TypeOfAny.implementation_artifact), None, ARG_POS)\n    add_method_to_class(api, defn, \"__call__\", [func_arg], NoneType())\n\n    return Instance(info, type_args)\n\n\nPluginContext: _TypeAlias = FunctionContext | MethodContext\n\n\ndef fail(ctx: PluginContext, msg: str, context: Context | None) -> None:\n    \"\"\"Emit an error message.\n\n    This tries to emit an error message at the location specified by `context`, falling back to the\n    location specified by `ctx.context`. This is helpful when the only context information about\n    where you want to put the error message may be None (like it is for `CallableType.definition`)\n    and falling back to the location of the calling function is fine.\"\"\"\n    # TODO: figure out if there is some more reliable way of getting context information, so this\n    # function isn't necessary\n    if context is not None:\n        err_context = context\n    else:\n        err_context = ctx.context\n    ctx.api.fail(msg, err_context)\n\n\ndef create_singledispatch_function_callback(ctx: FunctionContext) -> Type:\n    \"\"\"Called for functools.singledispatch\"\"\"\n    func_type = get_proper_type(get_first_arg(ctx.arg_types))\n    if isinstance(func_type, CallableType):\n        if len(func_type.arg_kinds) < 1:\n            fail(\n                ctx, \"Singledispatch function requires at least one argument\", func_type.definition\n            )\n            return ctx.default_return_type\n\n        elif not func_type.arg_kinds[0].is_positional(star=True):\n            fail(\n                ctx,\n                \"First argument to singledispatch function must be a positional argument\",\n                func_type.definition,\n            )\n            return ctx.default_return_type\n\n        # singledispatch returns an instance of functools._SingleDispatchCallable according to\n        # typeshed\n        singledispatch_obj = get_proper_type(ctx.default_return_type)\n        assert isinstance(singledispatch_obj, Instance)\n        singledispatch_obj.args += (func_type,)\n\n    return ctx.default_return_type\n\n\ndef singledispatch_register_callback(ctx: MethodContext) -> Type:\n    \"\"\"Called for functools._SingleDispatchCallable.register\"\"\"\n    assert isinstance(ctx.type, Instance)\n    # TODO: check that there's only one argument\n    first_arg_type = get_proper_type(get_first_arg(ctx.arg_types))\n    if isinstance(first_arg_type, (CallableType, Overloaded)) and first_arg_type.is_type_obj():\n        # HACK: We received a class as an argument to register. We need to be able\n        # to access the function that register is being applied to, and the typeshed definition\n        # of register has it return a generic Callable, so we create a new\n        # SingleDispatchRegisterCallable class, define a __call__ method, and then add a\n        # plugin hook for that.\n\n        # is_subtype doesn't work when the right type is Overloaded, so we need the\n        # actual type\n        register_type = first_arg_type.items[0].ret_type\n        type_args = RegisterCallableInfo(register_type, ctx.type)\n        register_callable = make_fake_register_class_instance(ctx.api, type_args)\n        return register_callable\n    elif isinstance(first_arg_type, CallableType):\n        # TODO: do more checking for registered functions\n        register_function(ctx, ctx.type, first_arg_type, ctx.api.options)\n        # The typeshed stubs for register say that the function returned is Callable[..., T], even\n        # though the function returned is the same as the one passed in. We return the type of the\n        # function so that mypy can properly type check cases where the registered function is used\n        # directly (instead of through singledispatch)\n        return first_arg_type\n\n    # fallback in case we don't recognize the arguments\n    return ctx.default_return_type\n\n\ndef register_function(\n    ctx: PluginContext,\n    singledispatch_obj: Instance,\n    func: Type,\n    options: Options,\n    register_arg: Type | None = None,\n) -> None:\n    \"\"\"Register a function\"\"\"\n\n    func = get_proper_type(func)\n    if not isinstance(func, CallableType):\n        return\n    metadata = get_singledispatch_info(singledispatch_obj)\n    if metadata is None:\n        # if we never added the fallback to the type variables, we already reported an error, so\n        # just don't do anything here\n        return\n    dispatch_type = get_dispatch_type(func, register_arg)\n    if dispatch_type is None:\n        # TODO: report an error here that singledispatch requires at least one argument\n        # (might want to do the error reporting in get_dispatch_type)\n        return\n    fallback = metadata.fallback\n\n    fallback_dispatch_type = fallback.arg_types[0]\n    if not is_subtype(dispatch_type, fallback_dispatch_type):\n        fail(\n            ctx,\n            \"Dispatch type {} must be subtype of fallback function first argument {}\".format(\n                format_type(dispatch_type, options), format_type(fallback_dispatch_type, options)\n            ),\n            func.definition,\n        )\n        return\n    return\n\n\ndef get_dispatch_type(func: CallableType, register_arg: Type | None) -> Type | None:\n    if register_arg is not None:\n        return register_arg\n    if func.arg_types:\n        return func.arg_types[0]\n    return None\n\n\ndef call_singledispatch_function_after_register_argument(ctx: MethodContext) -> Type:\n    \"\"\"Called on the function after passing a type to register\"\"\"\n    register_callable = ctx.type\n    if isinstance(register_callable, Instance):\n        type_args = RegisterCallableInfo(*register_callable.args)  # type: ignore[arg-type]\n        func = get_first_arg(ctx.arg_types)\n        if func is not None:\n            register_function(\n                ctx, type_args.singledispatch_obj, func, ctx.api.options, type_args.register_type\n            )\n            # see call to register_function in the callback for register\n            return func\n    return ctx.default_return_type\n\n\ndef call_singledispatch_function_callback(ctx: MethodSigContext) -> FunctionLike:\n    \"\"\"Called for functools._SingleDispatchCallable.__call__\"\"\"\n    if not isinstance(ctx.type, Instance):\n        return ctx.default_signature\n    metadata = get_singledispatch_info(ctx.type)\n    if metadata is None:\n        return ctx.default_signature\n    return metadata.fallback\n"
  },
  {
    "path": "mypy/py.typed",
    "content": "# Marker file for PEP 561.  The mypy package uses inline types.\n"
  },
  {
    "path": "mypy/pyinfo.py",
    "content": "from __future__ import annotations\n\n\"\"\"Utilities to find the site and prefix information of a Python executable.\n\nThis file MUST remain compatible with all Python 3.9+ versions. Since we cannot make any\nassumptions about the Python being executed, this module should not use *any* dependencies outside\nof the standard library found in Python 3.9. This file is run each mypy run, so it should be kept\nas fast as possible.\n\"\"\"\nimport sys\n\nif __name__ == \"__main__\":\n    # HACK: We don't want to pick up mypy.types as the top-level types\n    #       module. This could happen if this file is run as a script.\n    #       This workaround fixes this for Python versions before 3.11.\n    if sys.version_info < (3, 11):\n        old_sys_path = sys.path\n        sys.path = sys.path[1:]\n        import types  # noqa: F401\n\n        sys.path = old_sys_path\n\nimport os\nimport site\nimport sysconfig\n\n\ndef getsitepackages() -> list[str]:\n    res = []\n    if hasattr(site, \"getsitepackages\"):\n        res.extend(site.getsitepackages())\n\n        if hasattr(site, \"getusersitepackages\") and site.ENABLE_USER_SITE:\n            res.insert(0, site.getusersitepackages())\n    else:\n        res = [sysconfig.get_paths()[\"purelib\"]]\n    return res\n\n\ndef getsyspath() -> list[str]:\n    # Do not include things from the standard library\n    # because those should come from typeshed.\n    stdlib_zip = os.path.join(\n        sys.base_exec_prefix,\n        getattr(sys, \"platlibdir\", \"lib\"),\n        f\"python{sys.version_info.major}{sys.version_info.minor}.zip\",\n    )\n    stdlib = sysconfig.get_path(\"stdlib\")\n    stdlib_ext = os.path.join(stdlib, \"lib-dynload\")\n    excludes = {stdlib_zip, stdlib, stdlib_ext}\n\n    # Drop the first entry of sys.path\n    # - If pyinfo.py is executed as a script (in a subprocess), this is the directory\n    #   containing pyinfo.py\n    # - Otherwise, if mypy launched via console script, this is the directory of the script\n    # - Otherwise, if mypy launched via python -m mypy, this is the current directory\n    # In all these cases, it is desirable to drop the first entry\n    # Note that mypy adds the cwd to SearchPaths.python_path, so we still find things on the\n    # cwd consistently (the return value here sets SearchPaths.package_path)\n\n    # Python 3.11 adds a \"safe_path\" flag wherein Python won't automatically prepend\n    # anything to sys.path. In this case, the first entry of sys.path is no longer special.\n    offset = 0 if sys.version_info >= (3, 11) and sys.flags.safe_path else 1\n\n    abs_sys_path = (os.path.abspath(p) for p in sys.path[offset:])\n    return [p for p in abs_sys_path if p not in excludes]\n\n\ndef getsearchdirs() -> tuple[list[str], list[str]]:\n    return (getsyspath(), getsitepackages())\n\n\nif __name__ == \"__main__\":\n    sys.stdout.reconfigure(encoding=\"utf-8\")  # type: ignore[union-attr]\n    if sys.argv[-1] == \"getsearchdirs\":\n        print(repr(getsearchdirs()))\n    else:\n        print(\"ERROR: incorrect argument to pyinfo.py.\", file=sys.stderr)\n        sys.exit(1)\n"
  },
  {
    "path": "mypy/reachability.py",
    "content": "\"\"\"Utilities related to determining the reachability of code (in semantic analysis).\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final, TypeVar\n\nfrom mypy.literals import literal\nfrom mypy.nodes import (\n    LITERAL_YES,\n    AssertStmt,\n    Block,\n    CallExpr,\n    ComparisonExpr,\n    Expression,\n    FuncDef,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    MatchStmt,\n    MemberExpr,\n    NameExpr,\n    OpExpr,\n    SliceExpr,\n    StrExpr,\n    TupleExpr,\n    UnaryExpr,\n)\nfrom mypy.options import Options\nfrom mypy.patterns import AsPattern, OrPattern, Pattern\nfrom mypy.traverser import TraverserVisitor\n\n# Inferred truth value of an expression.\nALWAYS_TRUE: Final = 1\nMYPY_TRUE: Final = 2  # True in mypy, False at runtime\nALWAYS_FALSE: Final = 3\nMYPY_FALSE: Final = 4  # False in mypy, True at runtime\nTRUTH_VALUE_UNKNOWN: Final = 5\n\ninverted_truth_mapping: Final = {\n    ALWAYS_TRUE: ALWAYS_FALSE,\n    ALWAYS_FALSE: ALWAYS_TRUE,\n    TRUTH_VALUE_UNKNOWN: TRUTH_VALUE_UNKNOWN,\n    MYPY_TRUE: MYPY_FALSE,\n    MYPY_FALSE: MYPY_TRUE,\n}\n\nreverse_op: Final = {\"==\": \"==\", \"!=\": \"!=\", \"<\": \">\", \">\": \"<\", \"<=\": \">=\", \">=\": \"<=\"}\n\n\ndef infer_reachability_of_if_statement(s: IfStmt, options: Options) -> None:\n    for i in range(len(s.expr)):\n        result = infer_condition_value(s.expr[i], options)\n        if result in (ALWAYS_FALSE, MYPY_FALSE):\n            # The condition is considered always false, so we skip the if/elif body.\n            mark_block_unreachable(s.body[i])\n        elif result in (ALWAYS_TRUE, MYPY_TRUE):\n            # This condition is considered always true, so all of the remaining\n            # elif/else bodies should not be checked.\n            if result == MYPY_TRUE:\n                # This condition is false at runtime; this will affect\n                # import priorities.\n                mark_block_mypy_only(s.body[i])\n            for body in s.body[i + 1 :]:\n                mark_block_unreachable(body)\n\n            # Make sure else body always exists and is marked as\n            # unreachable so the type checker always knows that\n            # all control flow paths will flow through the if\n            # statement body.\n            if not s.else_body:\n                s.else_body = Block([])\n            mark_block_unreachable(s.else_body)\n            break\n\n\ndef infer_reachability_of_match_statement(s: MatchStmt, options: Options) -> None:\n    for i, guard in enumerate(s.guards):\n        pattern_value = infer_pattern_value(s.patterns[i])\n\n        if guard is not None:\n            guard_value = infer_condition_value(guard, options)\n        else:\n            guard_value = ALWAYS_TRUE\n\n        if pattern_value in (ALWAYS_FALSE, MYPY_FALSE) or guard_value in (\n            ALWAYS_FALSE,\n            MYPY_FALSE,\n        ):\n            # The case is considered always false, so we skip the case body.\n            mark_block_unreachable(s.bodies[i])\n        elif pattern_value in (ALWAYS_TRUE, MYPY_TRUE) and guard_value in (ALWAYS_TRUE, MYPY_TRUE):\n            for body in s.bodies[i + 1 :]:\n                mark_block_unreachable(body)\n\n        if guard_value == MYPY_TRUE:\n            # This condition is false at runtime; this will affect\n            # import priorities.\n            mark_block_mypy_only(s.bodies[i])\n\n\ndef assert_will_always_fail(s: AssertStmt, options: Options) -> bool:\n    return infer_condition_value(s.expr, options) in (ALWAYS_FALSE, MYPY_FALSE)\n\n\ndef infer_condition_value(expr: Expression, options: Options) -> int:\n    \"\"\"Infer whether the given condition is always true/false.\n\n    Return ALWAYS_TRUE if always true, ALWAYS_FALSE if always false,\n    MYPY_TRUE if true under mypy and false at runtime, MYPY_FALSE if\n    false under mypy and true at runtime, else TRUTH_VALUE_UNKNOWN.\n    \"\"\"\n    if isinstance(expr, UnaryExpr) and expr.op == \"not\":\n        positive = infer_condition_value(expr.expr, options)\n        return inverted_truth_mapping[positive]\n\n    pyversion = options.python_version\n    name = \"\"\n\n    result = TRUTH_VALUE_UNKNOWN\n    if isinstance(expr, NameExpr):\n        name = expr.name\n    elif isinstance(expr, MemberExpr):\n        name = expr.name\n    elif isinstance(expr, OpExpr):\n        if expr.op not in (\"or\", \"and\"):\n            return TRUTH_VALUE_UNKNOWN\n\n        left = infer_condition_value(expr.left, options)\n        right = infer_condition_value(expr.right, options)\n        results = {left, right}\n        if expr.op == \"or\":\n            if ALWAYS_TRUE in results:\n                return ALWAYS_TRUE\n            elif MYPY_TRUE in results:\n                return MYPY_TRUE\n            elif left == right == MYPY_FALSE:\n                return MYPY_FALSE\n            elif results <= {ALWAYS_FALSE, MYPY_FALSE}:\n                return ALWAYS_FALSE\n        elif expr.op == \"and\":\n            if ALWAYS_FALSE in results:\n                return ALWAYS_FALSE\n            elif MYPY_FALSE in results:\n                return MYPY_FALSE\n            elif left == right == ALWAYS_TRUE:\n                return ALWAYS_TRUE\n            elif results <= {ALWAYS_TRUE, MYPY_TRUE}:\n                return MYPY_TRUE\n        return TRUTH_VALUE_UNKNOWN\n    else:\n        result = consider_sys_version_info(expr, pyversion)\n        if result == TRUTH_VALUE_UNKNOWN:\n            result = consider_sys_platform(expr, options.platform)\n    if result == TRUTH_VALUE_UNKNOWN:\n        if name == \"PY2\":\n            result = ALWAYS_FALSE\n        elif name == \"PY3\":\n            result = ALWAYS_TRUE\n        elif name == \"MYPY\" or name == \"TYPE_CHECKING\":\n            result = MYPY_TRUE\n        elif name in options.always_true:\n            result = ALWAYS_TRUE\n        elif name in options.always_false:\n            result = ALWAYS_FALSE\n    return result\n\n\ndef infer_pattern_value(pattern: Pattern) -> int:\n    if isinstance(pattern, AsPattern) and pattern.pattern is None:\n        return ALWAYS_TRUE\n    elif isinstance(pattern, OrPattern) and any(\n        infer_pattern_value(p) == ALWAYS_TRUE for p in pattern.patterns\n    ):\n        return ALWAYS_TRUE\n    else:\n        return TRUTH_VALUE_UNKNOWN\n\n\ndef consider_sys_version_info(expr: Expression, pyversion: tuple[int, ...]) -> int:\n    \"\"\"Consider whether expr is a comparison involving sys.version_info.\n\n    Return ALWAYS_TRUE, ALWAYS_FALSE, or TRUTH_VALUE_UNKNOWN.\n    \"\"\"\n    # Cases supported:\n    # - sys.version_info[<int>] <compare_op> <int>\n    # - sys.version_info[:<int>] <compare_op> <tuple_of_n_ints>\n    # - sys.version_info <compare_op> <tuple_of_1_or_2_ints>\n    #   (in this case <compare_op> must be >, >=, <, <=, but cannot be ==, !=)\n    if not isinstance(expr, ComparisonExpr):\n        return TRUTH_VALUE_UNKNOWN\n    # Let's not yet support chained comparisons.\n    if len(expr.operators) > 1:\n        return TRUTH_VALUE_UNKNOWN\n    op = expr.operators[0]\n    if op not in (\"==\", \"!=\", \"<=\", \">=\", \"<\", \">\"):\n        return TRUTH_VALUE_UNKNOWN\n\n    index = contains_sys_version_info(expr.operands[0])\n    thing = contains_int_or_tuple_of_ints(expr.operands[1])\n    if index is None or thing is None:\n        index = contains_sys_version_info(expr.operands[1])\n        thing = contains_int_or_tuple_of_ints(expr.operands[0])\n        op = reverse_op[op]\n    if isinstance(index, int) and isinstance(thing, int):\n        # sys.version_info[i] <compare_op> k\n        if 0 <= index <= 1:\n            return fixed_comparison(pyversion[index], op, thing)\n        else:\n            return TRUTH_VALUE_UNKNOWN\n    elif isinstance(index, tuple) and isinstance(thing, tuple):\n        lo, hi = index\n        if lo is None:\n            lo = 0\n        if hi is None:\n            hi = 2\n        if 0 <= lo < hi <= 2:\n            val = pyversion[lo:hi]\n            if len(val) == len(thing) or len(val) > len(thing) and op not in (\"==\", \"!=\"):\n                return fixed_comparison(val, op, thing)\n    return TRUTH_VALUE_UNKNOWN\n\n\ndef consider_sys_platform(expr: Expression, platform: str) -> int:\n    \"\"\"Consider whether expr is a comparison involving sys.platform.\n\n    Return ALWAYS_TRUE, ALWAYS_FALSE, or TRUTH_VALUE_UNKNOWN.\n    \"\"\"\n    # Cases supported:\n    # - sys.platform == 'linux'\n    # - sys.platform != 'win32'\n    # - sys.platform.startswith('win')\n    if isinstance(expr, ComparisonExpr):\n        # Let's not yet support chained comparisons.\n        if len(expr.operators) > 1:\n            return TRUTH_VALUE_UNKNOWN\n        op = expr.operators[0]\n        if op not in (\"==\", \"!=\"):\n            return TRUTH_VALUE_UNKNOWN\n        if not is_sys_attr(expr.operands[0], \"platform\"):\n            return TRUTH_VALUE_UNKNOWN\n        right = expr.operands[1]\n        if not isinstance(right, StrExpr):\n            return TRUTH_VALUE_UNKNOWN\n        return fixed_comparison(platform, op, right.value)\n    elif isinstance(expr, CallExpr):\n        if not isinstance(expr.callee, MemberExpr):\n            return TRUTH_VALUE_UNKNOWN\n        if len(expr.args) != 1 or not isinstance(expr.args[0], StrExpr):\n            return TRUTH_VALUE_UNKNOWN\n        if not is_sys_attr(expr.callee.expr, \"platform\"):\n            return TRUTH_VALUE_UNKNOWN\n        if expr.callee.name != \"startswith\":\n            return TRUTH_VALUE_UNKNOWN\n        if platform.startswith(expr.args[0].value):\n            return ALWAYS_TRUE\n        else:\n            return ALWAYS_FALSE\n    else:\n        return TRUTH_VALUE_UNKNOWN\n\n\nTarg = TypeVar(\"Targ\", int, str, tuple[int, ...])\n\n\ndef fixed_comparison(left: Targ, op: str, right: Targ) -> int:\n    rmap = {False: ALWAYS_FALSE, True: ALWAYS_TRUE}\n    if op == \"==\":\n        return rmap[left == right]\n    if op == \"!=\":\n        return rmap[left != right]\n    if op == \"<=\":\n        return rmap[left <= right]\n    if op == \">=\":\n        return rmap[left >= right]\n    if op == \"<\":\n        return rmap[left < right]\n    if op == \">\":\n        return rmap[left > right]\n    return TRUTH_VALUE_UNKNOWN\n\n\ndef contains_int_or_tuple_of_ints(expr: Expression) -> None | int | tuple[int, ...]:\n    if isinstance(expr, IntExpr):\n        return expr.value\n    if isinstance(expr, TupleExpr):\n        if literal(expr) == LITERAL_YES:\n            thing = []\n            for x in expr.items:\n                if not isinstance(x, IntExpr):\n                    return None\n                thing.append(x.value)\n            return tuple(thing)\n    return None\n\n\ndef contains_sys_version_info(expr: Expression) -> None | int | tuple[int | None, int | None]:\n    if is_sys_attr(expr, \"version_info\"):\n        return (None, None)  # Same as sys.version_info[:]\n    if isinstance(expr, IndexExpr) and is_sys_attr(expr.base, \"version_info\"):\n        index = expr.index\n        if isinstance(index, IntExpr):\n            return index.value\n        if isinstance(index, SliceExpr):\n            if index.stride is not None:\n                if not isinstance(index.stride, IntExpr) or index.stride.value != 1:\n                    return None\n            begin = end = None\n            if index.begin_index is not None:\n                if not isinstance(index.begin_index, IntExpr):\n                    return None\n                begin = index.begin_index.value\n            if index.end_index is not None:\n                if not isinstance(index.end_index, IntExpr):\n                    return None\n                end = index.end_index.value\n            return (begin, end)\n    return None\n\n\ndef is_sys_attr(expr: Expression, name: str) -> bool:\n    # TODO: This currently doesn't work with code like this:\n    # - import sys as _sys\n    # - from sys import version_info\n    if isinstance(expr, MemberExpr) and expr.name == name:\n        if isinstance(expr.expr, NameExpr) and expr.expr.name == \"sys\":\n            # TODO: Guard against a local named sys, etc.\n            # (Though later passes will still do most checking.)\n            return True\n    return False\n\n\ndef mark_block_unreachable(block: Block) -> None:\n    block.is_unreachable = True\n    block.accept(MarkImportsUnreachableVisitor())\n\n\nclass MarkImportsUnreachableVisitor(TraverserVisitor):\n    \"\"\"Visitor that flags all imports nested within a node as unreachable.\"\"\"\n\n    def visit_import(self, node: Import) -> None:\n        node.is_unreachable = True\n\n    def visit_import_from(self, node: ImportFrom) -> None:\n        node.is_unreachable = True\n\n    def visit_import_all(self, node: ImportAll) -> None:\n        node.is_unreachable = True\n\n\ndef mark_block_mypy_only(block: Block) -> None:\n    block.accept(MarkImportsMypyOnlyVisitor())\n\n\nclass MarkImportsMypyOnlyVisitor(TraverserVisitor):\n    \"\"\"Visitor that sets is_mypy_only (which affects priority).\"\"\"\n\n    def visit_import(self, node: Import) -> None:\n        node.is_mypy_only = True\n\n    def visit_import_from(self, node: ImportFrom) -> None:\n        node.is_mypy_only = True\n\n    def visit_import_all(self, node: ImportAll) -> None:\n        node.is_mypy_only = True\n\n    def visit_func_def(self, node: FuncDef) -> None:\n        node.is_mypy_only = True\n"
  },
  {
    "path": "mypy/refinfo.py",
    "content": "\"\"\"Find line-level reference information from a mypy AST (undocumented feature)\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import (\n    LDEF,\n    Expression,\n    FuncDef,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    RefExpr,\n    SymbolNode,\n    TypeInfo,\n)\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.typeops import tuple_fallback\nfrom mypy.types import (\n    FunctionLike,\n    Instance,\n    TupleType,\n    Type,\n    TypeType,\n    TypeVarLikeType,\n    get_proper_type,\n)\n\n\nclass RefInfoVisitor(TraverserVisitor):\n    def __init__(self, type_map: dict[Expression, Type]) -> None:\n        super().__init__()\n        self.type_map = type_map\n        self.data: list[dict[str, object]] = []\n\n    def visit_name_expr(self, expr: NameExpr) -> None:\n        super().visit_name_expr(expr)\n        self.record_ref_expr(expr)\n\n    def visit_member_expr(self, expr: MemberExpr) -> None:\n        super().visit_member_expr(expr)\n        self.record_ref_expr(expr)\n\n    def visit_func_def(self, func: FuncDef) -> None:\n        if func.expanded:\n            for item in func.expanded:\n                if isinstance(item, FuncDef):\n                    super().visit_func_def(item)\n        else:\n            super().visit_func_def(func)\n\n    def record_ref_expr(self, expr: RefExpr) -> None:\n        fullname = None\n        if expr.kind != LDEF and \".\" in expr.fullname:\n            fullname = expr.fullname\n        elif isinstance(expr, MemberExpr):\n            typ = self.type_map.get(expr.expr)\n            sym = None\n            if isinstance(expr.expr, RefExpr):\n                sym = expr.expr.node\n            if typ:\n                tfn = type_fullname(typ, sym)\n                if tfn:\n                    fullname = f\"{tfn}.{expr.name}\"\n            if not fullname:\n                fullname = f\"*.{expr.name}\"\n        if fullname is not None:\n            self.data.append({\"line\": expr.line, \"column\": expr.column, \"target\": fullname})\n\n\ndef type_fullname(typ: Type, node: SymbolNode | None = None) -> str | None:\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        return typ.type.fullname\n    elif isinstance(typ, TypeType):\n        return type_fullname(typ.item)\n    elif isinstance(typ, FunctionLike) and typ.is_type_obj():\n        if isinstance(node, TypeInfo):\n            return node.fullname\n        return type_fullname(typ.fallback)\n    elif isinstance(typ, TupleType):\n        return type_fullname(tuple_fallback(typ))\n    elif isinstance(typ, TypeVarLikeType):\n        return type_fullname(typ.upper_bound)\n    return None\n\n\ndef get_undocumented_ref_info_json(\n    tree: MypyFile, type_map: dict[Expression, Type]\n) -> list[dict[str, object]]:\n    visitor = RefInfoVisitor(type_map)\n    tree.accept(visitor)\n    return visitor.data\n"
  },
  {
    "path": "mypy/renaming.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom typing import Final\n\nfrom mypy.nodes import (\n    AssignmentStmt,\n    Block,\n    BreakStmt,\n    ClassDef,\n    ContinueStmt,\n    ForStmt,\n    FuncDef,\n    Import,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    ListExpr,\n    Lvalue,\n    MatchStmt,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    StarExpr,\n    TryStmt,\n    TupleExpr,\n    WhileStmt,\n    WithStmt,\n)\nfrom mypy.patterns import AsPattern\nfrom mypy.traverser import TraverserVisitor\n\n# Scope kinds\nFILE: Final = 0\nFUNCTION: Final = 1\nCLASS: Final = 2\n\n\nclass VariableRenameVisitor(TraverserVisitor):\n    \"\"\"Rename variables to allow redefinition of variables.\n\n    For example, consider this code:\n\n      x = 0\n      f(x)\n\n      x = \"a\"\n      g(x)\n\n    It will be transformed like this:\n\n      x' = 0\n      f(x')\n\n      x = \"a\"\n      g(x)\n\n    There will be two independent variables (x' and x) that will have separate\n    inferred types. The publicly exposed variant will get the non-suffixed name.\n    This is the last definition at module top level and the first definition\n    (argument) within a function.\n\n    Renaming only happens for assignments within the same block. Renaming is\n    performed before semantic analysis, immediately after parsing.\n\n    The implementation performs a rudimentary static analysis. The analysis is\n    overly conservative to keep things simple.\n    \"\"\"\n\n    def __init__(self) -> None:\n        # Counter for labeling new blocks\n        self.block_id = 0\n        # Number of surrounding try statements that disallow variable redefinition\n        self.disallow_redef_depth = 0\n        # Number of surrounding loop statements\n        self.loop_depth = 0\n        # Map block id to loop depth.\n        self.block_loop_depth: dict[int, int] = {}\n        # Stack of block ids being processed.\n        self.blocks: list[int] = []\n        # List of scopes; each scope maps short (unqualified) name to block id.\n        self.var_blocks: list[dict[str, int]] = []\n\n        # References to variables that we may need to rename. List of\n        # scopes; each scope is a mapping from name to list of collections\n        # of names that refer to the same logical variable.\n        self.refs: list[dict[str, list[list[NameExpr]]]] = []\n        # Number of reads of the most recent definition of a variable (per scope)\n        self.num_reads: list[dict[str, int]] = []\n        # Kinds of nested scopes (FILE, FUNCTION or CLASS)\n        self.scope_kinds: list[int] = []\n\n    def visit_mypy_file(self, file_node: MypyFile) -> None:\n        \"\"\"Rename variables within a file.\n\n        This is the main entry point to this class.\n        \"\"\"\n        self.clear()\n        with self.enter_scope(FILE), self.enter_block():\n            for d in file_node.defs:\n                d.accept(self)\n\n    def visit_func_def(self, fdef: FuncDef) -> None:\n        # Conservatively do not allow variable defined before a function to\n        # be redefined later, since function could refer to either definition.\n        self.reject_redefinition_of_vars_in_scope()\n\n        with self.enter_scope(FUNCTION), self.enter_block():\n            for arg in fdef.arguments:\n                name = arg.variable.name\n                # 'self' can't be redefined since it's special as it allows definition of\n                # attributes. 'cls' can't be used to define attributes so we can ignore it.\n                can_be_redefined = name != \"self\"  # TODO: Proper check\n                self.record_assignment(arg.variable.name, can_be_redefined)\n                self.handle_arg(name)\n\n            for stmt in fdef.body.body:\n                stmt.accept(self)\n\n    def visit_class_def(self, cdef: ClassDef) -> None:\n        self.reject_redefinition_of_vars_in_scope()\n        with self.enter_scope(CLASS):\n            super().visit_class_def(cdef)\n\n    def visit_block(self, block: Block) -> None:\n        with self.enter_block():\n            super().visit_block(block)\n\n    def visit_while_stmt(self, stmt: WhileStmt) -> None:\n        with self.enter_loop():\n            super().visit_while_stmt(stmt)\n\n    def visit_for_stmt(self, stmt: ForStmt) -> None:\n        stmt.expr.accept(self)\n        self.analyze_lvalue(stmt.index, True)\n        # Also analyze as non-lvalue so that every for loop index variable is assumed to be read.\n        stmt.index.accept(self)\n        with self.enter_loop():\n            stmt.body.accept(self)\n        if stmt.else_body:\n            stmt.else_body.accept(self)\n\n    def visit_break_stmt(self, stmt: BreakStmt) -> None:\n        self.reject_redefinition_of_vars_in_loop()\n\n    def visit_continue_stmt(self, stmt: ContinueStmt) -> None:\n        self.reject_redefinition_of_vars_in_loop()\n\n    def visit_try_stmt(self, stmt: TryStmt) -> None:\n        # Variables defined by a try statement get special treatment in the\n        # type checker which allows them to be always redefined, so no need to\n        # do renaming here.\n        with self.enter_try():\n            stmt.body.accept(self)\n\n        for var, tp, handler in zip(stmt.vars, stmt.types, stmt.handlers):\n            with self.enter_block():\n                # Handle except variable together with its body\n                if tp is not None:\n                    tp.accept(self)\n                if var is not None:\n                    self.handle_def(var)\n                for s in handler.body:\n                    s.accept(self)\n        if stmt.else_body is not None:\n            stmt.else_body.accept(self)\n        if stmt.finally_body is not None:\n            stmt.finally_body.accept(self)\n\n    def visit_with_stmt(self, stmt: WithStmt) -> None:\n        for expr in stmt.expr:\n            expr.accept(self)\n        for target in stmt.target:\n            if target is not None:\n                self.analyze_lvalue(target)\n        # We allow redefinitions in the body of a with statement for\n        # convenience.  This is unsafe since with statements can affect control\n        # flow by catching exceptions, but this is rare except for\n        # assertRaises() and other similar functions, where the exception is\n        # raised by the last statement in the body, which usually isn't a\n        # problem.\n        stmt.body.accept(self)\n\n    def visit_import(self, imp: Import) -> None:\n        for id, as_id in imp.ids:\n            self.record_assignment(as_id or id, False)\n\n    def visit_import_from(self, imp: ImportFrom) -> None:\n        for id, as_id in imp.names:\n            self.record_assignment(as_id or id, False)\n\n    def visit_assignment_stmt(self, s: AssignmentStmt) -> None:\n        s.rvalue.accept(self)\n        for lvalue in s.lvalues:\n            self.analyze_lvalue(lvalue)\n\n    def visit_match_stmt(self, s: MatchStmt) -> None:\n        s.subject.accept(self)\n        for i in range(len(s.patterns)):\n            with self.enter_block():\n                s.patterns[i].accept(self)\n                guard = s.guards[i]\n                if guard is not None:\n                    guard.accept(self)\n                # We already entered a block, so visit this block's statements directly\n                for stmt in s.bodies[i].body:\n                    stmt.accept(self)\n\n    def visit_capture_pattern(self, p: AsPattern) -> None:\n        if p.name is not None:\n            self.analyze_lvalue(p.name)\n\n    def analyze_lvalue(self, lvalue: Lvalue, is_nested: bool = False) -> None:\n        \"\"\"Process assignment; in particular, keep track of (re)defined names.\n\n        Args:\n            is_nested: True for non-outermost Lvalue in a multiple assignment such as\n                \"x, y = ...\"\n        \"\"\"\n        if isinstance(lvalue, NameExpr):\n            name = lvalue.name\n            is_new = self.record_assignment(name, True)\n            if is_new:\n                self.handle_def(lvalue)\n            else:\n                self.handle_refine(lvalue)\n            if is_nested:\n                # This allows these to be redefined freely even if never read. Multiple\n                # assignment like \"x, _ _ = y\" defines dummy variables that are never read.\n                self.handle_ref(lvalue)\n        elif isinstance(lvalue, (ListExpr, TupleExpr)):\n            for item in lvalue.items:\n                self.analyze_lvalue(item, is_nested=True)\n        elif isinstance(lvalue, MemberExpr):\n            lvalue.expr.accept(self)\n        elif isinstance(lvalue, IndexExpr):\n            lvalue.base.accept(self)\n            lvalue.index.accept(self)\n        elif isinstance(lvalue, StarExpr):\n            # Propagate is_nested since in a typical use case like \"x, *rest = ...\" 'rest' may\n            # be freely reused.\n            self.analyze_lvalue(lvalue.expr, is_nested=is_nested)\n\n    def visit_name_expr(self, expr: NameExpr) -> None:\n        self.handle_ref(expr)\n\n    # Helpers for renaming references\n\n    def handle_arg(self, name: str) -> None:\n        \"\"\"Store function argument.\"\"\"\n        self.refs[-1][name] = [[]]\n        self.num_reads[-1][name] = 0\n\n    def handle_def(self, expr: NameExpr) -> None:\n        \"\"\"Store new name definition.\"\"\"\n        name = expr.name\n        names = self.refs[-1].setdefault(name, [])\n        names.append([expr])\n        self.num_reads[-1][name] = 0\n\n    def handle_refine(self, expr: NameExpr) -> None:\n        \"\"\"Store assignment to an existing name (that replaces previous value, if any).\"\"\"\n        name = expr.name\n        if name in self.refs[-1]:\n            names = self.refs[-1][name]\n            if not names:\n                names.append([])\n            names[-1].append(expr)\n\n    def handle_ref(self, expr: NameExpr) -> None:\n        \"\"\"Store reference to defined name.\"\"\"\n        name = expr.name\n        if name in self.refs[-1]:\n            names = self.refs[-1][name]\n            if not names:\n                names.append([])\n            names[-1].append(expr)\n        num_reads = self.num_reads[-1]\n        num_reads[name] = num_reads.get(name, 0) + 1\n\n    def flush_refs(self) -> None:\n        \"\"\"Rename all references within the current scope.\n\n        This will be called at the end of a scope.\n        \"\"\"\n        is_func = self.scope_kinds[-1] == FUNCTION\n        for refs in self.refs[-1].values():\n            if len(refs) == 1:\n                # Only one definition -- no renaming needed.\n                continue\n            if is_func:\n                # In a function, don't rename the first definition, as it\n                # may be an argument that must preserve the name.\n                to_rename = refs[1:]\n            else:\n                # At module top level, don't rename the final definition,\n                # as it will be publicly visible outside the module.\n                to_rename = refs[:-1]\n            for i, item in enumerate(to_rename):\n                rename_refs(item, i)\n        self.refs.pop()\n\n    # Helpers for determining which assignments define new variables\n\n    def clear(self) -> None:\n        self.blocks = []\n        self.var_blocks = []\n\n    @contextmanager\n    def enter_block(self) -> Iterator[None]:\n        self.block_id += 1\n        self.blocks.append(self.block_id)\n        self.block_loop_depth[self.block_id] = self.loop_depth\n        try:\n            yield\n        finally:\n            self.blocks.pop()\n\n    @contextmanager\n    def enter_try(self) -> Iterator[None]:\n        self.disallow_redef_depth += 1\n        try:\n            yield\n        finally:\n            self.disallow_redef_depth -= 1\n\n    @contextmanager\n    def enter_loop(self) -> Iterator[None]:\n        self.loop_depth += 1\n        try:\n            yield\n        finally:\n            self.loop_depth -= 1\n\n    def current_block(self) -> int:\n        return self.blocks[-1]\n\n    @contextmanager\n    def enter_scope(self, kind: int) -> Iterator[None]:\n        self.var_blocks.append({})\n        self.refs.append({})\n        self.num_reads.append({})\n        self.scope_kinds.append(kind)\n        try:\n            yield\n        finally:\n            self.flush_refs()\n            self.var_blocks.pop()\n            self.num_reads.pop()\n            self.scope_kinds.pop()\n\n    def is_nested(self) -> int:\n        return len(self.var_blocks) > 1\n\n    def reject_redefinition_of_vars_in_scope(self) -> None:\n        \"\"\"Make it impossible to redefine defined variables in the current scope.\n\n        This is used if we encounter a function definition that\n        can make it ambiguous which definition is live. Example:\n\n          x = 0\n\n          def f() -> int:\n              return x\n\n          x = ''  # Error -- cannot redefine x across function definition\n        \"\"\"\n        var_blocks = self.var_blocks[-1]\n        for key in var_blocks:\n            var_blocks[key] = -1\n\n    def reject_redefinition_of_vars_in_loop(self) -> None:\n        \"\"\"Reject redefinition of variables in the innermost loop.\n\n        If there is an early exit from a loop, there may be ambiguity about which\n        value may escape the loop. Example where this matters:\n\n          while f():\n              x = 0\n              if g():\n                  break\n              x = ''  # Error -- not a redefinition\n          reveal_type(x)  # int\n\n        This method ensures that the second assignment to 'x' doesn't introduce a new\n        variable.\n        \"\"\"\n        var_blocks = self.var_blocks[-1]\n        for key, block in var_blocks.items():\n            if self.block_loop_depth.get(block) == self.loop_depth:\n                var_blocks[key] = -1\n\n    def record_assignment(self, name: str, can_be_redefined: bool) -> bool:\n        \"\"\"Record assignment to given name and return True if it defines a new variable.\n\n        Args:\n            can_be_redefined: If True, allows assignment in the same block to redefine\n                this name (if this is a new definition)\n        \"\"\"\n        if self.num_reads[-1].get(name, -1) == 0:\n            # Only set, not read, so no reason to redefine\n            return False\n        if self.disallow_redef_depth > 0:\n            # Can't redefine within try/with a block.\n            can_be_redefined = False\n        block = self.current_block()\n        var_blocks = self.var_blocks[-1]\n        if name not in var_blocks:\n            # New definition in this scope.\n            if can_be_redefined:\n                # Store the block where this was defined to allow redefinition in\n                # the same block only.\n                var_blocks[name] = block\n            else:\n                # This doesn't support arbitrary redefinition.\n                var_blocks[name] = -1\n            return True\n        elif var_blocks[name] == block:\n            # Redefinition -- defines a new variable with the same name.\n            return True\n        else:\n            # Assigns to an existing variable.\n            return False\n\n\nclass LimitedVariableRenameVisitor(TraverserVisitor):\n    \"\"\"Perform some limited variable renaming in with statements.\n\n    This allows reusing a variable in multiple with statements with\n    different types. For example, the two instances of 'x' can have\n    incompatible types:\n\n       with C() as x:\n           f(x)\n       with D() as x:\n           g(x)\n\n    The above code gets renamed conceptually into this (not valid Python!):\n\n       with C() as x':\n           f(x')\n       with D() as x:\n           g(x)\n\n    If there's a reference to a variable defined in 'with' outside the\n    statement, or if there's any trickiness around variable visibility\n    (e.g. function definitions), we give up and won't perform renaming.\n\n    The main use case is to allow binding both readable and writable\n    binary files into the same variable. These have different types:\n\n        with open(fnam, 'rb') as f: ...\n        with open(fnam, 'wb') as f: ...\n    \"\"\"\n\n    def __init__(self) -> None:\n        # Short names of variables bound in with statements using \"as\"\n        # in a surrounding scope\n        self.bound_vars: list[str] = []\n        # Stack of names that can't be safely renamed, per scope ('*' means that\n        # no names can be renamed)\n        self.skipped: list[set[str]] = []\n        # References to variables that we may need to rename. Stack of\n        # scopes; each scope is a mapping from name to list of collections\n        # of names that refer to the same logical variable.\n        self.refs: list[dict[str, list[list[NameExpr]]]] = []\n\n    def visit_mypy_file(self, file_node: MypyFile) -> None:\n        \"\"\"Rename variables within a file.\n\n        This is the main entry point to this class.\n        \"\"\"\n        with self.enter_scope():\n            for d in file_node.defs:\n                d.accept(self)\n\n    def visit_func_def(self, fdef: FuncDef) -> None:\n        self.reject_redefinition_of_vars_in_scope()\n        with self.enter_scope():\n            for arg in fdef.arguments:\n                self.record_skipped(arg.variable.name)\n            super().visit_func_def(fdef)\n\n    def visit_class_def(self, cdef: ClassDef) -> None:\n        self.reject_redefinition_of_vars_in_scope()\n        with self.enter_scope():\n            super().visit_class_def(cdef)\n\n    def visit_with_stmt(self, stmt: WithStmt) -> None:\n        for expr in stmt.expr:\n            expr.accept(self)\n        old_len = len(self.bound_vars)\n        for target in stmt.target:\n            if target is not None:\n                self.analyze_lvalue(target)\n        for target in stmt.target:\n            if target:\n                target.accept(self)\n        stmt.body.accept(self)\n\n        while len(self.bound_vars) > old_len:\n            self.bound_vars.pop()\n\n    def analyze_lvalue(self, lvalue: Lvalue) -> None:\n        if isinstance(lvalue, NameExpr):\n            name = lvalue.name\n            if name in self.bound_vars:\n                # Name bound in a surrounding with statement, so it can be renamed\n                self.visit_name_expr(lvalue)\n            else:\n                var_info = self.refs[-1]\n                if name not in var_info:\n                    var_info[name] = []\n                var_info[name].append([])\n                self.bound_vars.append(name)\n        elif isinstance(lvalue, (ListExpr, TupleExpr)):\n            for item in lvalue.items:\n                self.analyze_lvalue(item)\n        elif isinstance(lvalue, MemberExpr):\n            lvalue.expr.accept(self)\n        elif isinstance(lvalue, IndexExpr):\n            lvalue.base.accept(self)\n            lvalue.index.accept(self)\n        elif isinstance(lvalue, StarExpr):\n            self.analyze_lvalue(lvalue.expr)\n\n    def visit_import(self, imp: Import) -> None:\n        # We don't support renaming imports\n        for id, as_id in imp.ids:\n            self.record_skipped(as_id or id)\n\n    def visit_import_from(self, imp: ImportFrom) -> None:\n        # We don't support renaming imports\n        for id, as_id in imp.names:\n            self.record_skipped(as_id or id)\n\n    def visit_import_all(self, imp: ImportAll) -> None:\n        # Give up, since we don't know all imported names yet\n        self.reject_redefinition_of_vars_in_scope()\n\n    def visit_name_expr(self, expr: NameExpr) -> None:\n        name = expr.name\n        if name in self.bound_vars:\n            # Record reference so that it can be renamed later\n            for scope in reversed(self.refs):\n                if name in scope:\n                    scope[name][-1].append(expr)\n        else:\n            self.record_skipped(name)\n\n    @contextmanager\n    def enter_scope(self) -> Iterator[None]:\n        self.skipped.append(set())\n        self.refs.append({})\n        yield None\n        self.flush_refs()\n\n    def reject_redefinition_of_vars_in_scope(self) -> None:\n        self.record_skipped(\"*\")\n\n    def record_skipped(self, name: str) -> None:\n        self.skipped[-1].add(name)\n\n    def flush_refs(self) -> None:\n        ref_dict = self.refs.pop()\n        skipped = self.skipped.pop()\n        if \"*\" not in skipped:\n            for name, refs in ref_dict.items():\n                if len(refs) <= 1 or name in skipped:\n                    continue\n                # At module top level we must not rename the final definition,\n                # as it may be publicly visible\n                to_rename = refs[:-1]\n                for i, item in enumerate(to_rename):\n                    rename_refs(item, i)\n\n\ndef rename_refs(names: list[NameExpr], index: int) -> None:\n    name = names[0].name\n    new_name = name + \"'\" * (index + 1)\n    for expr in names:\n        expr.name = new_name\n"
  },
  {
    "path": "mypy/report.py",
    "content": "\"\"\"Classes for producing HTML reports about imprecision.\"\"\"\n\nfrom __future__ import annotations\n\nimport collections\nimport itertools\nimport json\nimport os\nimport shutil\nimport sys\nimport sysconfig\nimport time\nimport tokenize\nfrom abc import ABCMeta, abstractmethod\nfrom collections.abc import Callable, Iterator\nfrom operator import attrgetter\nfrom typing import Any, Final, TypeAlias as _TypeAlias\nfrom urllib.request import pathname2url\n\nfrom mypy import stats\nfrom mypy.defaults import REPORTER_NAMES\nfrom mypy.nodes import Expression, FuncDef, MypyFile\nfrom mypy.options import Options\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.types import Type, TypeOfAny\nfrom mypy.version import __version__\n\ntry:\n    if sys.version_info >= (3, 14) and bool(sysconfig.get_config_var(\"Py_GIL_DISABLED\")):\n        # lxml doesn't support free-threading yet\n        LXML_INSTALLED = False\n    else:\n        from lxml import etree  # type: ignore[import-untyped]\n\n        LXML_INSTALLED = True\nexcept ImportError:\n    LXML_INSTALLED = False\n\ntype_of_any_name_map: Final[collections.OrderedDict[int, str]] = collections.OrderedDict(\n    [\n        (TypeOfAny.unannotated, \"Unannotated\"),\n        (TypeOfAny.explicit, \"Explicit\"),\n        (TypeOfAny.from_unimported_type, \"Unimported\"),\n        (TypeOfAny.from_omitted_generics, \"Omitted Generics\"),\n        (TypeOfAny.from_error, \"Error\"),\n        (TypeOfAny.special_form, \"Special Form\"),\n        (TypeOfAny.implementation_artifact, \"Implementation Artifact\"),\n    ]\n)\n\nReporterClasses: _TypeAlias = dict[\n    str, tuple[Callable[[\"Reports\", str], \"AbstractReporter\"], bool]\n]\n\nreporter_classes: Final[ReporterClasses] = {}\n\n\nclass Reports:\n    def __init__(self, data_dir: str, report_dirs: dict[str, str]) -> None:\n        self.data_dir = data_dir\n        self.reporters: list[AbstractReporter] = []\n        self.named_reporters: dict[str, AbstractReporter] = {}\n\n        for report_type, report_dir in sorted(report_dirs.items()):\n            self.add_report(report_type, report_dir)\n\n    def add_report(self, report_type: str, report_dir: str) -> AbstractReporter:\n        try:\n            return self.named_reporters[report_type]\n        except KeyError:\n            pass\n        reporter_cls, needs_lxml = reporter_classes[report_type]\n        if needs_lxml and not LXML_INSTALLED:\n            print(\n                (\n                    \"You must install the lxml package before you can run mypy\"\n                    \" with `--{}-report`.\\n\"\n                    \"You can do this with `python3 -m pip install lxml`.\"\n                ).format(report_type),\n                file=sys.stderr,\n            )\n            raise ImportError\n        reporter = reporter_cls(self, report_dir)\n        self.reporters.append(reporter)\n        self.named_reporters[report_type] = reporter\n        return reporter\n\n    def file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        for reporter in self.reporters:\n            reporter.on_file(tree, modules, type_map, options)\n\n    def finish(self) -> None:\n        for reporter in self.reporters:\n            reporter.on_finish()\n\n\nclass AbstractReporter(metaclass=ABCMeta):\n    def __init__(self, reports: Reports, output_dir: str) -> None:\n        self.output_dir = output_dir\n        if output_dir != \"<memory>\":\n            os.makedirs(output_dir, exist_ok=True)\n\n    @abstractmethod\n    def on_file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        pass\n\n    @abstractmethod\n    def on_finish(self) -> None:\n        pass\n\n\ndef register_reporter(\n    report_name: str,\n    reporter: Callable[[Reports, str], AbstractReporter],\n    needs_lxml: bool = False,\n) -> None:\n    reporter_classes[report_name] = (reporter, needs_lxml)\n\n\ndef alias_reporter(source_reporter: str, target_reporter: str) -> None:\n    reporter_classes[target_reporter] = reporter_classes[source_reporter]\n\n\ndef should_skip_path(path: str) -> bool:\n    if stats.is_special_module(path):\n        return True\n    if path.startswith(\"..\"):\n        return True\n    if \"stubs\" in path.split(\"/\") or \"stubs\" in path.split(os.sep):\n        return True\n    return False\n\n\ndef iterate_python_lines(path: str) -> Iterator[tuple[int, str]]:\n    \"\"\"Return an iterator over (line number, line text) from a Python file.\"\"\"\n    if not os.path.isdir(path):  # can happen with namespace packages\n        with tokenize.open(path) as input_file:\n            yield from enumerate(input_file, 1)\n\n\nclass FuncCounterVisitor(TraverserVisitor):\n    def __init__(self) -> None:\n        super().__init__()\n        self.counts = [0, 0]\n\n    def visit_func_def(self, defn: FuncDef) -> None:\n        self.counts[defn.type is not None] += 1\n\n\nclass LineCountReporter(AbstractReporter):\n    def __init__(self, reports: Reports, output_dir: str) -> None:\n        super().__init__(reports, output_dir)\n        self.counts: dict[str, tuple[int, int, int, int]] = {}\n\n    def on_file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        # Count physical lines.  This assumes the file's encoding is a\n        # superset of ASCII (or at least uses \\n in its line endings).\n        if not os.path.isdir(tree.path):  # can happen with namespace packages\n            with open(tree.path, \"rb\") as f:\n                physical_lines = len(f.readlines())\n        else:\n            physical_lines = 0\n\n        func_counter = FuncCounterVisitor()\n        tree.accept(func_counter)\n        unannotated_funcs, annotated_funcs = func_counter.counts\n        total_funcs = annotated_funcs + unannotated_funcs\n\n        # Don't count lines or functions as annotated if they have their errors ignored.\n        if options.ignore_errors:\n            annotated_funcs = 0\n\n        imputed_annotated_lines = (\n            physical_lines * annotated_funcs // total_funcs if total_funcs else physical_lines\n        )\n\n        self.counts[tree._fullname] = (\n            imputed_annotated_lines,\n            physical_lines,\n            annotated_funcs,\n            total_funcs,\n        )\n\n    def on_finish(self) -> None:\n        counts: list[tuple[tuple[int, int, int, int], str]] = sorted(\n            ((c, p) for p, c in self.counts.items()), reverse=True\n        )\n        total_counts = tuple(sum(c[i] for c, p in counts) for i in range(4))\n        with open(os.path.join(self.output_dir, \"linecount.txt\"), \"w\") as f:\n            f.write(\"{:7} {:7} {:6} {:6} total\\n\".format(*total_counts))\n            for c, p in counts:\n                f.write(f\"{c[0]:7} {c[1]:7} {c[2]:6} {c[3]:6} {p}\\n\")\n\n\nregister_reporter(\"linecount\", LineCountReporter)\n\n\nclass AnyExpressionsReporter(AbstractReporter):\n    \"\"\"Report frequencies of different kinds of Any types.\"\"\"\n\n    def __init__(self, reports: Reports, output_dir: str) -> None:\n        super().__init__(reports, output_dir)\n        self.counts: dict[str, tuple[int, int]] = {}\n        self.any_types_counter: dict[str, collections.Counter[int]] = {}\n\n    def on_file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        visitor = stats.StatisticsVisitor(\n            inferred=True,\n            filename=tree.fullname,\n            modules=modules,\n            typemap=type_map,\n            all_nodes=True,\n            visit_untyped_defs=False,\n        )\n        tree.accept(visitor)\n        self.any_types_counter[tree.fullname] = visitor.type_of_any_counter\n        num_unanalyzed_lines = list(visitor.line_map.values()).count(stats.TYPE_UNANALYZED)\n        # count each line of dead code as one expression of type \"Any\"\n        num_any = visitor.num_any_exprs + num_unanalyzed_lines\n        num_total = visitor.num_imprecise_exprs + visitor.num_precise_exprs + num_any\n        if num_total > 0:\n            self.counts[tree.fullname] = (num_any, num_total)\n\n    def on_finish(self) -> None:\n        self._report_any_exprs()\n        self._report_types_of_anys()\n\n    def _write_out_report(\n        self, filename: str, header: list[str], rows: list[list[str]], footer: list[str]\n    ) -> None:\n        row_len = len(header)\n        assert all(len(row) == row_len for row in rows + [header, footer])\n        min_column_distance = 3  # minimum distance between numbers in two columns\n        widths = [-1] * row_len\n        for row in rows + [header, footer]:\n            for i, value in enumerate(row):\n                widths[i] = max(widths[i], len(value))\n        for i, w in enumerate(widths):\n            # Do not add min_column_distance to the first column.\n            if i > 0:\n                widths[i] = w + min_column_distance\n        with open(os.path.join(self.output_dir, filename), \"w\") as f:\n            header_str = (\"{:>{}}\" * len(widths)).format(*itertools.chain(*zip(header, widths)))\n            separator = \"-\" * len(header_str)\n            f.write(header_str + \"\\n\")\n            f.write(separator + \"\\n\")\n            for row_values in rows:\n                r = (\"{:>{}}\" * len(widths)).format(*itertools.chain(*zip(row_values, widths)))\n                f.write(r + \"\\n\")\n            f.write(separator + \"\\n\")\n            footer_str = (\"{:>{}}\" * len(widths)).format(*itertools.chain(*zip(footer, widths)))\n            f.write(footer_str + \"\\n\")\n\n    def _report_any_exprs(self) -> None:\n        total_any = sum(num_any for num_any, _ in self.counts.values())\n        total_expr = sum(total for _, total in self.counts.values())\n        total_coverage = 100.0\n        if total_expr > 0:\n            total_coverage = (float(total_expr - total_any) / float(total_expr)) * 100\n\n        column_names = [\"Name\", \"Anys\", \"Exprs\", \"Coverage\"]\n        rows: list[list[str]] = []\n        for filename in sorted(self.counts):\n            num_any, num_total = self.counts[filename]\n            coverage = (float(num_total - num_any) / float(num_total)) * 100\n            coverage_str = f\"{coverage:.2f}%\"\n            rows.append([filename, str(num_any), str(num_total), coverage_str])\n        rows.sort(key=lambda x: x[0])\n        total_row = [\"Total\", str(total_any), str(total_expr), f\"{total_coverage:.2f}%\"]\n        self._write_out_report(\"any-exprs.txt\", column_names, rows, total_row)\n\n    def _report_types_of_anys(self) -> None:\n        total_counter: collections.Counter[int] = collections.Counter()\n        for counter in self.any_types_counter.values():\n            for any_type, value in counter.items():\n                total_counter[any_type] += value\n        file_column_name = \"Name\"\n        total_row_name = \"Total\"\n        column_names = [file_column_name] + list(type_of_any_name_map.values())\n        rows: list[list[str]] = []\n        for filename, counter in self.any_types_counter.items():\n            rows.append([filename] + [str(counter[typ]) for typ in type_of_any_name_map])\n        rows.sort(key=lambda x: x[0])\n        total_row = [total_row_name] + [str(total_counter[typ]) for typ in type_of_any_name_map]\n        self._write_out_report(\"types-of-anys.txt\", column_names, rows, total_row)\n\n\nregister_reporter(\"any-exprs\", AnyExpressionsReporter)\n\n\nclass LineCoverageVisitor(TraverserVisitor):\n    def __init__(self, source: list[str]) -> None:\n        self.source = source\n\n        # For each line of source, we maintain a pair of\n        #  * the indentation level of the surrounding function\n        #    (-1 if not inside a function), and\n        #  * whether the surrounding function is typed.\n        # Initially, everything is covered at indentation level -1.\n        self.lines_covered = [(-1, True) for l in source]\n\n    # The Python AST has position information for the starts of\n    # elements, but not for their ends. Fortunately the\n    # indentation-based syntax makes it pretty easy to find where a\n    # block ends without doing any real parsing.\n\n    # TODO: Handle line continuations (explicit and implicit) and\n    # multi-line string literals. (But at least line continuations\n    # are normally more indented than their surrounding block anyways,\n    # by PEP 8.)\n\n    def indentation_level(self, line_number: int) -> int | None:\n        \"\"\"Return the indentation of a line of the source (specified by\n        zero-indexed line number). Returns None for blank lines or comments.\"\"\"\n        line = self.source[line_number]\n        indent = 0\n        for char in list(line):\n            if char == \" \":\n                indent += 1\n            elif char == \"\\t\":\n                indent = 8 * ((indent + 8) // 8)\n            elif char == \"#\":\n                # Line is a comment; ignore it\n                return None\n            elif char == \"\\n\":\n                # Line is entirely whitespace; ignore it\n                return None\n            # TODO line continuation (\\)\n            else:\n                # Found a non-whitespace character\n                return indent\n        # Line is entirely whitespace, and at end of file\n        # with no trailing newline; ignore it\n        return None\n\n    def visit_func_def(self, defn: FuncDef) -> None:\n        start_line = defn.line - 1\n        start_indent = None\n        # When a function is decorated, sometimes the start line will point to\n        # whitespace or comments between the decorator and the function, so\n        # we have to look for the start.\n        while start_line < len(self.source):\n            start_indent = self.indentation_level(start_line)\n            if start_indent is not None:\n                break\n            start_line += 1\n        # If we can't find the function give up and don't annotate anything.\n        # Our line numbers are not reliable enough to be asserting on.\n        if start_indent is None:\n            return\n\n        cur_line = start_line + 1\n        end_line = cur_line\n        # After this loop, function body will be lines [start_line, end_line)\n        while cur_line < len(self.source):\n            cur_indent = self.indentation_level(cur_line)\n            if cur_indent is None:\n                # Consume the line, but don't mark it as belonging to the function yet.\n                cur_line += 1\n            elif cur_indent > start_indent:\n                # A non-blank line that belongs to the function.\n                cur_line += 1\n                end_line = cur_line\n            else:\n                # We reached a line outside the function definition.\n                break\n\n        is_typed = defn.type is not None\n        for line in range(start_line, end_line):\n            old_indent, _ = self.lines_covered[line]\n            # If there was an old indent level for this line, and the new\n            # level isn't increasing the indentation, ignore it.\n            # This is to be defensive against funniness in our line numbers,\n            # which are not always reliable.\n            if old_indent <= start_indent:\n                self.lines_covered[line] = (start_indent, is_typed)\n\n        # Visit the body, in case there are nested functions\n        super().visit_func_def(defn)\n\n\nclass LineCoverageReporter(AbstractReporter):\n    \"\"\"Exact line coverage reporter.\n\n    This reporter writes a JSON dictionary with one field 'lines' to\n    the file 'coverage.json' in the specified report directory. The\n    value of that field is a dictionary which associates to each\n    source file's absolute pathname the list of line numbers that\n    belong to typed functions in that file.\n    \"\"\"\n\n    def __init__(self, reports: Reports, output_dir: str) -> None:\n        super().__init__(reports, output_dir)\n        self.lines_covered: dict[str, list[int]] = {}\n\n    def on_file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        if os.path.isdir(tree.path):  # can happen with namespace packages\n            return\n\n        with open(tree.path) as f:\n            tree_source = f.readlines()\n\n        coverage_visitor = LineCoverageVisitor(tree_source)\n        tree.accept(coverage_visitor)\n\n        covered_lines = []\n        for line_number, (_, typed) in enumerate(coverage_visitor.lines_covered):\n            if typed:\n                covered_lines.append(line_number + 1)\n\n        self.lines_covered[os.path.abspath(tree.path)] = covered_lines\n\n    def on_finish(self) -> None:\n        with open(os.path.join(self.output_dir, \"coverage.json\"), \"w\") as f:\n            json.dump({\"lines\": self.lines_covered}, f)\n\n\nregister_reporter(\"linecoverage\", LineCoverageReporter)\n\n\nclass FileInfo:\n    def __init__(self, name: str, module: str) -> None:\n        self.name = name\n        self.module = module\n        self.counts = [0] * len(stats.precision_names)\n\n    def total(self) -> int:\n        return sum(self.counts)\n\n    def attrib(self) -> dict[str, str]:\n        return {name: str(val) for name, val in sorted(zip(stats.precision_names, self.counts))}\n\n\nclass MemoryXmlReporter(AbstractReporter):\n    \"\"\"Internal reporter that generates XML in memory.\n\n    This is used by all other XML-based reporters to avoid duplication.\n    \"\"\"\n\n    def __init__(self, reports: Reports, output_dir: str) -> None:\n        super().__init__(reports, output_dir)\n\n        self.xslt_html_path = os.path.join(reports.data_dir, \"xml\", \"mypy-html.xslt\")\n        self.xslt_txt_path = os.path.join(reports.data_dir, \"xml\", \"mypy-txt.xslt\")\n        self.css_html_path = os.path.join(reports.data_dir, \"xml\", \"mypy-html.css\")\n        xsd_path = os.path.join(reports.data_dir, \"xml\", \"mypy.xsd\")\n        self.schema = etree.XMLSchema(etree.parse(xsd_path))\n        self.last_xml: Any | None = None\n        self.files: list[FileInfo] = []\n\n    # XML doesn't like control characters, but they are sometimes\n    # legal in source code (e.g. comments, string literals).\n    # Tabs (#x09) are allowed in XML content.\n    control_fixer: Final = str.maketrans(\"\".join(chr(i) for i in range(32) if i != 9), \"?\" * 31)\n\n    def on_file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        self.last_xml = None\n\n        try:\n            path = os.path.relpath(tree.path)\n        except ValueError:\n            return\n\n        if should_skip_path(path) or os.path.isdir(path):\n            return  # `path` can sometimes be a directory, see #11334\n\n        visitor = stats.StatisticsVisitor(\n            inferred=True,\n            filename=tree.fullname,\n            modules=modules,\n            typemap=type_map,\n            all_nodes=True,\n        )\n        tree.accept(visitor)\n\n        root = etree.Element(\"mypy-report-file\", name=path, module=tree._fullname)\n        doc = etree.ElementTree(root)\n        file_info = FileInfo(path, tree._fullname)\n\n        for lineno, line_text in iterate_python_lines(path):\n            status = visitor.line_map.get(lineno, stats.TYPE_EMPTY)\n            file_info.counts[status] += 1\n            etree.SubElement(\n                root,\n                \"line\",\n                any_info=self._get_any_info_for_line(visitor, lineno),\n                content=line_text.rstrip(\"\\n\").translate(self.control_fixer),\n                number=str(lineno),\n                precision=stats.precision_names[status],\n            )\n        # Assumes a layout similar to what XmlReporter uses.\n        xslt_path = os.path.relpath(\"mypy-html.xslt\", path)\n        transform_pi = etree.ProcessingInstruction(\n            \"xml-stylesheet\", f'type=\"text/xsl\" href=\"{pathname2url(xslt_path)}\"'\n        )\n        root.addprevious(transform_pi)\n        self.schema.assertValid(doc)\n\n        self.last_xml = doc\n        self.files.append(file_info)\n\n    @staticmethod\n    def _get_any_info_for_line(visitor: stats.StatisticsVisitor, lineno: int) -> str:\n        if lineno in visitor.any_line_map:\n            result = \"Any Types on this line: \"\n            counter: collections.Counter[int] = collections.Counter()\n            for typ in visitor.any_line_map[lineno]:\n                counter[typ.type_of_any] += 1\n            for any_type, occurrences in counter.items():\n                result += f\"\\n{type_of_any_name_map[any_type]} (x{occurrences})\"\n            return result\n        else:\n            return \"No Anys on this line!\"\n\n    def on_finish(self) -> None:\n        self.last_xml = None\n        # index_path = os.path.join(self.output_dir, 'index.xml')\n        output_files = sorted(self.files, key=lambda x: x.module)\n\n        root = etree.Element(\"mypy-report-index\", name=\"index\")\n        doc = etree.ElementTree(root)\n\n        for file_info in output_files:\n            etree.SubElement(\n                root,\n                \"file\",\n                file_info.attrib(),\n                module=file_info.module,\n                name=pathname2url(file_info.name),\n                total=str(file_info.total()),\n            )\n        xslt_path = os.path.relpath(\"mypy-html.xslt\", \".\")\n        transform_pi = etree.ProcessingInstruction(\n            \"xml-stylesheet\", f'type=\"text/xsl\" href=\"{pathname2url(xslt_path)}\"'\n        )\n        root.addprevious(transform_pi)\n        self.schema.assertValid(doc)\n\n        self.last_xml = doc\n\n\nregister_reporter(\"memory-xml\", MemoryXmlReporter, needs_lxml=True)\n\n\ndef get_line_rate(covered_lines: int, total_lines: int) -> str:\n    if total_lines == 0:\n        return str(1.0)\n    else:\n        return f\"{covered_lines / total_lines:.4f}\"\n\n\nclass CoberturaPackage:\n    \"\"\"Container for XML and statistics mapping python modules to Cobertura package.\"\"\"\n\n    def __init__(self, name: str) -> None:\n        self.name = name\n        self.classes: dict[str, Any] = {}\n        self.packages: dict[str, CoberturaPackage] = {}\n        self.total_lines = 0\n        self.covered_lines = 0\n\n    def as_xml(self) -> Any:\n        package_element = etree.Element(\"package\", complexity=\"1.0\", name=self.name)\n        package_element.attrib[\"branch-rate\"] = \"0\"\n        package_element.attrib[\"line-rate\"] = get_line_rate(self.covered_lines, self.total_lines)\n        classes_element = etree.SubElement(package_element, \"classes\")\n        for class_name in sorted(self.classes):\n            classes_element.append(self.classes[class_name])\n        self.add_packages(package_element)\n        return package_element\n\n    def add_packages(self, parent_element: Any) -> None:\n        if self.packages:\n            packages_element = etree.SubElement(parent_element, \"packages\")\n            for package in sorted(self.packages.values(), key=attrgetter(\"name\")):\n                packages_element.append(package.as_xml())\n\n\nclass CoberturaXmlReporter(AbstractReporter):\n    \"\"\"Reporter for generating Cobertura compliant XML.\"\"\"\n\n    def __init__(self, reports: Reports, output_dir: str) -> None:\n        super().__init__(reports, output_dir)\n\n        self.root = etree.Element(\"coverage\", timestamp=str(int(time.time())), version=__version__)\n        self.doc = etree.ElementTree(self.root)\n        self.root_package = CoberturaPackage(\".\")\n\n    def on_file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        path = os.path.relpath(tree.path)\n        visitor = stats.StatisticsVisitor(\n            inferred=True,\n            filename=tree.fullname,\n            modules=modules,\n            typemap=type_map,\n            all_nodes=True,\n        )\n        tree.accept(visitor)\n\n        class_name = os.path.basename(path)\n        file_info = FileInfo(path, tree._fullname)\n        class_element = etree.Element(\"class\", complexity=\"1.0\", filename=path, name=class_name)\n        etree.SubElement(class_element, \"methods\")\n        lines_element = etree.SubElement(class_element, \"lines\")\n\n        class_lines_covered = 0\n        class_total_lines = 0\n        for lineno, _ in iterate_python_lines(path):\n            status = visitor.line_map.get(lineno, stats.TYPE_EMPTY)\n            hits = 0\n            branch = False\n            if status == stats.TYPE_EMPTY:\n                continue\n            class_total_lines += 1\n            if status != stats.TYPE_ANY:\n                class_lines_covered += 1\n                hits = 1\n            if status == stats.TYPE_IMPRECISE:\n                branch = True\n            file_info.counts[status] += 1\n            line_element = etree.SubElement(\n                lines_element,\n                \"line\",\n                branch=str(branch).lower(),\n                hits=str(hits),\n                number=str(lineno),\n                precision=stats.precision_names[status],\n            )\n            if branch:\n                line_element.attrib[\"condition-coverage\"] = \"50% (1/2)\"\n        class_element.attrib[\"branch-rate\"] = \"0\"\n        class_element.attrib[\"line-rate\"] = get_line_rate(class_lines_covered, class_total_lines)\n        # parent_module is set to whichever module contains this file.  For most files, we want\n        # to simply strip the last element off of the module.  But for __init__.py files,\n        # the module == the parent module.\n        parent_module = file_info.module.rsplit(\".\", 1)[0]\n        if file_info.name.endswith(\"__init__.py\"):\n            parent_module = file_info.module\n\n        if parent_module not in self.root_package.packages:\n            self.root_package.packages[parent_module] = CoberturaPackage(parent_module)\n        current_package = self.root_package.packages[parent_module]\n        packages_to_update = [self.root_package, current_package]\n        for package in packages_to_update:\n            package.total_lines += class_total_lines\n            package.covered_lines += class_lines_covered\n        current_package.classes[class_name] = class_element\n\n    def on_finish(self) -> None:\n        self.root.attrib[\"line-rate\"] = get_line_rate(\n            self.root_package.covered_lines, self.root_package.total_lines\n        )\n        self.root.attrib[\"branch-rate\"] = \"0\"\n        self.root.attrib[\"lines-covered\"] = str(self.root_package.covered_lines)\n        self.root.attrib[\"lines-valid\"] = str(self.root_package.total_lines)\n        sources = etree.SubElement(self.root, \"sources\")\n        source_element = etree.SubElement(sources, \"source\")\n        source_element.text = os.getcwd()\n        self.root_package.add_packages(self.root)\n        out_path = os.path.join(self.output_dir, \"cobertura.xml\")\n        self.doc.write(out_path, encoding=\"utf-8\", pretty_print=True)\n        print(\"Generated Cobertura report:\", os.path.abspath(out_path))\n\n\nregister_reporter(\"cobertura-xml\", CoberturaXmlReporter, needs_lxml=True)\n\n\nclass AbstractXmlReporter(AbstractReporter):\n    \"\"\"Internal abstract class for reporters that work via XML.\"\"\"\n\n    def __init__(self, reports: Reports, output_dir: str) -> None:\n        super().__init__(reports, output_dir)\n\n        memory_reporter = reports.add_report(\"memory-xml\", \"<memory>\")\n        assert isinstance(memory_reporter, MemoryXmlReporter)\n        # The dependency will be called first.\n        self.memory_xml = memory_reporter\n\n\nclass XmlReporter(AbstractXmlReporter):\n    \"\"\"Public reporter that exports XML.\n\n    The produced XML files contain a reference to the absolute path\n    of the html transform, so they will be locally viewable in a browser.\n\n    However, there is a bug in Chrome and all other WebKit-based browsers\n    that makes it fail from file:// URLs but work on http:// URLs.\n    \"\"\"\n\n    def on_file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        last_xml = self.memory_xml.last_xml\n        if last_xml is None:\n            return\n        path = os.path.relpath(tree.path)\n        if path.startswith(\"..\"):\n            return\n        out_path = os.path.join(self.output_dir, \"xml\", path + \".xml\")\n        os.makedirs(os.path.dirname(out_path), exist_ok=True)\n        last_xml.write(out_path, encoding=\"utf-8\")\n\n    def on_finish(self) -> None:\n        last_xml = self.memory_xml.last_xml\n        assert last_xml is not None\n        out_path = os.path.join(self.output_dir, \"index.xml\")\n        out_xslt = os.path.join(self.output_dir, \"mypy-html.xslt\")\n        out_css = os.path.join(self.output_dir, \"mypy-html.css\")\n        last_xml.write(out_path, encoding=\"utf-8\")\n        shutil.copyfile(self.memory_xml.xslt_html_path, out_xslt)\n        shutil.copyfile(self.memory_xml.css_html_path, out_css)\n        print(\"Generated XML report:\", os.path.abspath(out_path))\n\n\nregister_reporter(\"xml\", XmlReporter, needs_lxml=True)\n\n\nclass XsltHtmlReporter(AbstractXmlReporter):\n    \"\"\"Public reporter that exports HTML via XSLT.\n\n    This is slightly different than running `xsltproc` on the .xml files,\n    because it passes a parameter to rewrite the links.\n    \"\"\"\n\n    def __init__(self, reports: Reports, output_dir: str) -> None:\n        super().__init__(reports, output_dir)\n\n        self.xslt_html = etree.XSLT(etree.parse(self.memory_xml.xslt_html_path))\n        self.param_html = etree.XSLT.strparam(\"html\")\n\n    def on_file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        last_xml = self.memory_xml.last_xml\n        if last_xml is None:\n            return\n        path = os.path.relpath(tree.path)\n        if path.startswith(\"..\"):\n            return\n        out_path = os.path.join(self.output_dir, \"html\", path + \".html\")\n        os.makedirs(os.path.dirname(out_path), exist_ok=True)\n        transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html))\n        with open(out_path, \"wb\") as out_file:\n            out_file.write(transformed_html)\n\n    def on_finish(self) -> None:\n        last_xml = self.memory_xml.last_xml\n        assert last_xml is not None\n        out_path = os.path.join(self.output_dir, \"index.html\")\n        out_css = os.path.join(self.output_dir, \"mypy-html.css\")\n        transformed_html = bytes(self.xslt_html(last_xml, ext=self.param_html))\n        with open(out_path, \"wb\") as out_file:\n            out_file.write(transformed_html)\n        shutil.copyfile(self.memory_xml.css_html_path, out_css)\n        print(\"Generated HTML report (via XSLT):\", os.path.abspath(out_path))\n\n\nregister_reporter(\"xslt-html\", XsltHtmlReporter, needs_lxml=True)\n\n\nclass XsltTxtReporter(AbstractXmlReporter):\n    \"\"\"Public reporter that exports TXT via XSLT.\n\n    Currently this only does the summary, not the individual reports.\n    \"\"\"\n\n    def __init__(self, reports: Reports, output_dir: str) -> None:\n        super().__init__(reports, output_dir)\n\n        self.xslt_txt = etree.XSLT(etree.parse(self.memory_xml.xslt_txt_path))\n\n    def on_file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        pass\n\n    def on_finish(self) -> None:\n        last_xml = self.memory_xml.last_xml\n        assert last_xml is not None\n        out_path = os.path.join(self.output_dir, \"index.txt\")\n        transformed_txt = bytes(self.xslt_txt(last_xml))\n        with open(out_path, \"wb\") as out_file:\n            out_file.write(transformed_txt)\n        print(\"Generated TXT report (via XSLT):\", os.path.abspath(out_path))\n\n\nregister_reporter(\"xslt-txt\", XsltTxtReporter, needs_lxml=True)\n\nalias_reporter(\"xslt-html\", \"html\")\nalias_reporter(\"xslt-txt\", \"txt\")\n\n\nclass LinePrecisionReporter(AbstractReporter):\n    \"\"\"Report per-module line counts for typing precision.\n\n    Each line is classified into one of these categories:\n\n    * precise (fully type checked)\n    * imprecise (Any types in a type component, such as List[Any])\n    * any (something with an Any type, implicit or explicit)\n    * empty (empty line, comment or docstring)\n    * unanalyzed (mypy considers line unreachable)\n\n    The meaning of these categories varies slightly depending on\n    context.\n    \"\"\"\n\n    def __init__(self, reports: Reports, output_dir: str) -> None:\n        super().__init__(reports, output_dir)\n        self.files: list[FileInfo] = []\n\n    def on_file(\n        self,\n        tree: MypyFile,\n        modules: dict[str, MypyFile],\n        type_map: dict[Expression, Type],\n        options: Options,\n    ) -> None:\n        try:\n            path = os.path.relpath(tree.path)\n        except ValueError:\n            return\n\n        if should_skip_path(path):\n            return\n\n        visitor = stats.StatisticsVisitor(\n            inferred=True,\n            filename=tree.fullname,\n            modules=modules,\n            typemap=type_map,\n            all_nodes=True,\n        )\n        tree.accept(visitor)\n\n        file_info = FileInfo(path, tree._fullname)\n        for lineno, _ in iterate_python_lines(path):\n            status = visitor.line_map.get(lineno, stats.TYPE_EMPTY)\n            file_info.counts[status] += 1\n\n        self.files.append(file_info)\n\n    def on_finish(self) -> None:\n        if not self.files:\n            # Nothing to do.\n            return\n        output_files = sorted(self.files, key=lambda x: x.module)\n        report_file = os.path.join(self.output_dir, \"lineprecision.txt\")\n        width = max(4, max(len(info.module) for info in output_files))\n        titles = (\"Lines\", \"Precise\", \"Imprecise\", \"Any\", \"Empty\", \"Unanalyzed\")\n        widths = (width,) + tuple(len(t) for t in titles)\n        fmt = \"{:%d}  {:%d}  {:%d}  {:%d}  {:%d}  {:%d}  {:%d}\\n\" % widths\n        with open(report_file, \"w\") as f:\n            f.write(fmt.format(\"Name\", *titles))\n            f.write(\"-\" * (width + 51) + \"\\n\")\n            for file_info in output_files:\n                counts = file_info.counts\n                f.write(\n                    fmt.format(\n                        file_info.module.ljust(width),\n                        file_info.total(),\n                        counts[stats.TYPE_PRECISE],\n                        counts[stats.TYPE_IMPRECISE],\n                        counts[stats.TYPE_ANY],\n                        counts[stats.TYPE_EMPTY],\n                        counts[stats.TYPE_UNANALYZED],\n                    )\n                )\n\n\nregister_reporter(\"lineprecision\", LinePrecisionReporter)\n\n\n# Reporter class names are defined twice to speed up mypy startup, as this\n# module is slow to import. Ensure that the two definitions match.\nassert set(reporter_classes) == set(REPORTER_NAMES)\n"
  },
  {
    "path": "mypy/scope.py",
    "content": "\"\"\"Track current scope to easily calculate the corresponding fine-grained target.\n\nTODO: Use everywhere where we track targets, including in mypy.errors.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager, nullcontext\nfrom typing import TypeAlias as _TypeAlias\n\nfrom mypy.nodes import FuncBase, TypeInfo\n\nSavedScope: _TypeAlias = tuple[str, TypeInfo | None, FuncBase | None]\n\n\nclass Scope:\n    \"\"\"Track which target we are processing at any given time.\"\"\"\n\n    def __init__(self) -> None:\n        self.module: str | None = None\n        self.classes: list[TypeInfo] = []\n        self.function: FuncBase | None = None\n        self.functions: list[FuncBase] = []\n        # Number of nested scopes ignored (that don't get their own separate targets)\n        self.ignored = 0\n\n    def current_module_id(self) -> str:\n        assert self.module\n        return self.module\n\n    def current_target(self) -> str:\n        \"\"\"Return the current target (non-class; for a class return enclosing module).\"\"\"\n        assert self.module\n        if self.function:\n            fullname = self.function.fullname\n            return fullname or \"\"\n        return self.module\n\n    def current_full_target(self) -> str:\n        \"\"\"Return the current target (may be a class).\"\"\"\n        assert self.module\n        if self.function:\n            return self.function.fullname\n        if self.classes:\n            return self.classes[-1].fullname\n        return self.module\n\n    def current_type_name(self) -> str | None:\n        \"\"\"Return the current type's short name if it exists\"\"\"\n        return self.classes[-1].name if self.classes else None\n\n    def current_function_name(self) -> str | None:\n        \"\"\"Return the current function's short name if it exists\"\"\"\n        return self.function.name if self.function else None\n\n    @contextmanager\n    def module_scope(self, prefix: str) -> Iterator[None]:\n        self.module = prefix\n        self.classes = []\n        self.function = None\n        self.ignored = 0\n        yield\n        assert self.module\n        self.module = None\n\n    @contextmanager\n    def function_scope(self, fdef: FuncBase) -> Iterator[None]:\n        self.functions.append(fdef)\n        if not self.function:\n            self.function = fdef\n        else:\n            # Nested functions are part of the topmost function target.\n            self.ignored += 1\n        yield\n        self.functions.pop()\n        if self.ignored:\n            # Leave a scope that's included in the enclosing target.\n            self.ignored -= 1\n        else:\n            assert self.function\n            self.function = None\n\n    def outer_functions(self) -> list[FuncBase]:\n        return self.functions[:-1]\n\n    def enter_class(self, info: TypeInfo) -> None:\n        \"\"\"Enter a class target scope.\"\"\"\n        if not self.function:\n            self.classes.append(info)\n        else:\n            # Classes within functions are part of the enclosing function target.\n            self.ignored += 1\n\n    def leave_class(self) -> None:\n        \"\"\"Leave a class target scope.\"\"\"\n        if self.ignored:\n            # Leave a scope that's included in the enclosing target.\n            self.ignored -= 1\n        else:\n            assert self.classes\n            # Leave the innermost class.\n            self.classes.pop()\n\n    @contextmanager\n    def class_scope(self, info: TypeInfo) -> Iterator[None]:\n        self.enter_class(info)\n        yield\n        self.leave_class()\n\n    def save(self) -> SavedScope:\n        \"\"\"Produce a saved scope that can be entered with saved_scope()\"\"\"\n        assert self.module\n        # We only save the innermost class, which is sufficient since\n        # the rest are only needed for when classes are left.\n        cls = self.classes[-1] if self.classes else None\n        return self.module, cls, self.function\n\n    @contextmanager\n    def saved_scope(self, saved: SavedScope) -> Iterator[None]:\n        module, info, function = saved\n        with self.module_scope(module):\n            with self.class_scope(info) if info else nullcontext():\n                with self.function_scope(function) if function else nullcontext():\n                    yield\n"
  },
  {
    "path": "mypy/semanal.py",
    "content": "\"\"\"The semantic analyzer.\n\nBind names to definitions and do various other simple consistency\nchecks.  Populate symbol tables.  The semantic analyzer also detects\nspecial forms which reuse generic syntax such as NamedTuple and\ncast().  Multiple analysis iterations may be needed to analyze forward\nreferences and import cycles. Each iteration \"fills in\" additional\nbindings and references until everything has been bound.\n\nFor example, consider this program:\n\n  x = 1\n  y = x\n\nHere semantic analysis would detect that the assignment 'x = 1'\ndefines a new variable, the type of which is to be inferred (in a\nlater pass; type inference or type checking is not part of semantic\nanalysis).  Also, it would bind both references to 'x' to the same\nmodule-level variable (Var) node.  The second assignment would also\nbe analyzed, and the type of 'y' marked as being inferred.\n\nSemantic analysis of types is implemented in typeanal.py.\n\nSee semanal_main.py for the top-level logic.\n\nSome important properties:\n\n* After semantic analysis is complete, no PlaceholderNode and\n  PlaceholderType instances should remain. During semantic analysis,\n  if we encounter one of these, the current target should be deferred.\n\n* A TypeInfo is only created once we know certain basic information about\n  a type, such as the MRO, existence of a Tuple base class (e.g., for named\n  tuples), and whether we have a TypedDict. We use a temporary\n  PlaceholderNode node in the symbol table if some such information is\n  missing.\n\n* For assignments, we only add a non-placeholder symbol table entry once\n  we know the sort of thing being defined (variable, NamedTuple, type alias,\n  etc.).\n\n* Every part of the analysis step must support multiple iterations over\n  the same AST nodes, and each iteration must be able to fill in arbitrary\n  things that were missing or incomplete in previous iterations.\n\n* Changes performed by the analysis need to be reversible, since mypy\n  daemon strips and reuses existing ASTs (to improve performance and/or\n  reduce memory use).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom collections.abc import Callable, Collection, Iterable, Iterator\nfrom contextlib import contextmanager\nfrom typing import Any, Final, TypeAlias as _TypeAlias, TypeGuard, TypeVar, cast\nfrom typing_extensions import assert_never\n\nfrom mypy import errorcodes as codes, message_registry\nfrom mypy.constant_fold import constant_fold_expr\nfrom mypy.errorcodes import PROPERTY_DECORATOR, ErrorCode\nfrom mypy.errors import Errors, report_internal_error\nfrom mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type\nfrom mypy.message_registry import ErrorMessage\nfrom mypy.messages import (\n    SUGGESTED_TEST_FIXTURES,\n    TYPES_FOR_UNIMPORTED_HINTS,\n    MessageBuilder,\n    best_matches,\n    pretty_seq,\n)\nfrom mypy.mro import MroError, calculate_mro\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    ARG_STAR2,\n    CONTRAVARIANT,\n    COVARIANT,\n    GDEF,\n    IMPLICITLY_ABSTRACT,\n    INVARIANT,\n    IS_ABSTRACT,\n    LDEF,\n    MDEF,\n    NOT_ABSTRACT,\n    PARAM_SPEC_KIND,\n    REVEAL_LOCALS,\n    REVEAL_TYPE,\n    RUNTIME_PROTOCOL_DECOS,\n    SYMBOL_FUNCBASE_TYPES,\n    TYPE_VAR_KIND,\n    TYPE_VAR_TUPLE_KIND,\n    VARIANCE_NOT_READY,\n    ArgKind,\n    AssertStmt,\n    AssertTypeExpr,\n    AssignmentExpr,\n    AssignmentStmt,\n    AwaitExpr,\n    Block,\n    BreakStmt,\n    BytesExpr,\n    CallExpr,\n    CastExpr,\n    ClassDef,\n    ComparisonExpr,\n    ComplexExpr,\n    ConditionalExpr,\n    Context,\n    ContinueStmt,\n    DataclassTransformSpec,\n    Decorator,\n    DelStmt,\n    DictExpr,\n    DictionaryComprehension,\n    EllipsisExpr,\n    EnumCallExpr,\n    Expression,\n    ExpressionStmt,\n    FakeExpression,\n    FloatExpr,\n    ForStmt,\n    FuncBase,\n    FuncDef,\n    FuncItem,\n    GeneratorExpr,\n    GlobalDecl,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportBase,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    Lvalue,\n    MatchStmt,\n    MaybeTypeExpression,\n    MemberExpr,\n    MypyFile,\n    NamedTupleExpr,\n    NameExpr,\n    Node,\n    NonlocalDecl,\n    OperatorAssignmentStmt,\n    OpExpr,\n    OverloadedFuncDef,\n    OverloadPart,\n    ParamSpecExpr,\n    PassStmt,\n    PlaceholderNode,\n    PromoteExpr,\n    RaiseStmt,\n    RefExpr,\n    ReturnStmt,\n    RevealExpr,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    SplittingVisitor,\n    StarExpr,\n    Statement,\n    StrExpr,\n    SuperExpr,\n    SymbolNode,\n    SymbolTable,\n    SymbolTableNode,\n    TemplateStrExpr,\n    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAlias,\n    TypeAliasExpr,\n    TypeAliasStmt,\n    TypeApplication,\n    TypedDictExpr,\n    TypeFormExpr,\n    TypeInfo,\n    TypeParam,\n    TypeVarExpr,\n    TypeVarLikeExpr,\n    TypeVarTupleExpr,\n    UnaryExpr,\n    Var,\n    WhileStmt,\n    WithStmt,\n    YieldExpr,\n    YieldFromExpr,\n    get_member_expr_fullname,\n    implicit_module_attrs,\n    is_final_node,\n    type_aliases,\n    type_aliases_source_versions,\n    typing_extensions_aliases,\n)\nfrom mypy.options import TYPE_FORM, Options\nfrom mypy.patterns import (\n    AsPattern,\n    ClassPattern,\n    MappingPattern,\n    OrPattern,\n    SequencePattern,\n    SingletonPattern,\n    StarredPattern,\n    ValuePattern,\n)\nfrom mypy.plugin import (\n    ClassDefContext,\n    DynamicClassDefContext,\n    Plugin,\n    SemanticAnalyzerPluginInterface,\n)\nfrom mypy.plugins import dataclasses as dataclasses_plugin\nfrom mypy.reachability import (\n    ALWAYS_FALSE,\n    ALWAYS_TRUE,\n    MYPY_FALSE,\n    MYPY_TRUE,\n    infer_condition_value,\n    infer_reachability_of_if_statement,\n    infer_reachability_of_match_statement,\n)\nfrom mypy.scope import Scope\nfrom mypy.semanal_enum import EnumCallAnalyzer\nfrom mypy.semanal_namedtuple import NamedTupleAnalyzer\nfrom mypy.semanal_newtype import NewTypeAnalyzer\nfrom mypy.semanal_shared import (\n    ALLOW_INCOMPATIBLE_OVERRIDE,\n    PRIORITY_FALLBACKS,\n    SemanticAnalyzerInterface,\n    calculate_tuple_fallback,\n    find_dataclass_transform_spec,\n    has_placeholder,\n    parse_bool,\n    require_bool_literal_argument,\n    set_callable_name as set_callable_name,\n)\nfrom mypy.semanal_typeddict import TypedDictAnalyzer\nfrom mypy.tvar_scope import TypeVarLikeScope\nfrom mypy.typeanal import (\n    SELF_TYPE_NAMES,\n    FindTypeVarVisitor,\n    TypeAnalyser,\n    TypeVarDefaultTranslator,\n    TypeVarLikeList,\n    analyze_type_alias,\n    check_for_explicit_any,\n    check_vec_type_args,\n    detect_diverging_alias,\n    find_self_type,\n    fix_instance,\n    has_any_from_unimported_type,\n    type_constructors,\n    validate_instance,\n)\nfrom mypy.typeops import function_type, get_type_vars, try_getting_str_literals_from_type\nfrom mypy.types import (\n    ASSERT_TYPE_NAMES,\n    DATACLASS_TRANSFORM_NAMES,\n    DEPRECATED_TYPE_NAMES,\n    DISJOINT_BASE_DECORATOR_NAMES,\n    FINAL_DECORATOR_NAMES,\n    FINAL_TYPE_NAMES,\n    IMPORTED_REVEAL_TYPE_NAMES,\n    NEVER_NAMES,\n    OVERLOAD_NAMES,\n    OVERRIDE_DECORATOR_NAMES,\n    PROTOCOL_NAMES,\n    REVEAL_TYPE_NAMES,\n    TPDICT_NAMES,\n    TYPE_ALIAS_NAMES,\n    TYPE_CHECK_ONLY_NAMES,\n    TYPE_NAMES,\n    TYPE_VAR_LIKE_NAMES,\n    TYPED_NAMEDTUPLE_NAMES,\n    UNPACK_TYPE_NAMES,\n    AnyType,\n    CallableType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PlaceholderType,\n    ProperType,\n    TrivialSyntheticTypeTranslator,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeStrVisitor,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UnionType,\n    UnpackType,\n    flatten_nested_tuples,\n    get_proper_type,\n    get_proper_types,\n    has_type_vars,\n    is_named_instance,\n    remove_dups,\n    type_vars_as_args,\n)\nfrom mypy.types_utils import is_invalid_recursive_alias, store_argument_type\nfrom mypy.typevars import fill_typevars\nfrom mypy.util import correct_relative_import, is_dunder, module_prefix, unmangle, unnamed_function\nfrom mypy.visitor import NodeVisitor\n\nT = TypeVar(\"T\")\n\n\n# Whether to print diagnostic information for failed full parses\n# in SemanticAnalyzer.try_parse_as_type_expression().\n#\n# See also: misc/analyze_typeform_stats.py\nDEBUG_TYPE_EXPRESSION_FULL_PARSE_FAILURES: Final = False\n\n\nFUTURE_IMPORTS: Final = {\n    \"__future__.nested_scopes\": \"nested_scopes\",\n    \"__future__.generators\": \"generators\",\n    \"__future__.division\": \"division\",\n    \"__future__.absolute_import\": \"absolute_import\",\n    \"__future__.with_statement\": \"with_statement\",\n    \"__future__.print_function\": \"print_function\",\n    \"__future__.unicode_literals\": \"unicode_literals\",\n    \"__future__.barry_as_FLUFL\": \"barry_as_FLUFL\",\n    \"__future__.generator_stop\": \"generator_stop\",\n    \"__future__.annotations\": \"annotations\",\n}\n\n\n# Special cased built-in classes that are needed for basic functionality and need to be\n# available very early on.\nCORE_BUILTIN_CLASSES: Final = [\"object\", \"bool\", \"function\"]\n\n\n# Python has several different scope/namespace kinds with subtly different semantics.\nSCOPE_GLOBAL: Final = 0  # Module top level\nSCOPE_CLASS: Final = 1  # Class body\nSCOPE_FUNC: Final = 2  # Function or lambda\nSCOPE_COMPREHENSION: Final = 3  # Comprehension or generator expression\nSCOPE_ANNOTATION: Final = 4  # Annotation scopes for type parameters and aliases (PEP 695)\n\n\n# Used for tracking incomplete references\nTag: _TypeAlias = int\n\n\n# Matches two words separated by whitespace, where each word lacks\n# any symbols which have special meaning in a type expression.\n#\n# Any string literal matching this common pattern cannot be a valid\n# type expression and can be ignored quickly when attempting to parse a\n# string literal as a type expression.\n_MULTIPLE_WORDS_NONTYPE_RE = re.compile(r'\\s*[^\\s.\\'\"|\\[]+\\s+[^\\s.\\'\"|\\[]')\n\n# Matches any valid Python identifier, including identifiers with Unicode characters.\n#\n# [^\\d\\W] = word character that is not a digit\n# \\w = word character\n# \\Z = match end of string; does not allow a trailing \\n, unlike $\n_IDENTIFIER_RE = re.compile(r\"^[^\\d\\W]\\w*\\Z\", re.UNICODE)\n\n\nclass SemanticAnalyzer(\n    NodeVisitor[None], SemanticAnalyzerInterface, SemanticAnalyzerPluginInterface, SplittingVisitor\n):\n    \"\"\"Semantically analyze parsed mypy files.\n\n    The analyzer binds names and does various consistency checks for an\n    AST. Note that type checking is performed as a separate pass.\n    \"\"\"\n\n    __deletable__ = [\"patches\", \"options\", \"cur_mod_node\"]\n\n    # Module name space\n    modules: dict[str, MypyFile]\n    # Global name space for current module\n    globals: SymbolTable\n    # Names declared using \"global\" (separate set for each scope)\n    global_decls: list[set[str]]\n    # Names declared using \"nonlocal\" (separate set for each scope)\n    nonlocal_decls: list[set[str]]\n    # Local names of function scopes; None for non-function scopes.\n    locals: list[SymbolTable | None]\n    # Type of each scope (SCOPE_*, indexes match locals)\n    scope_stack: list[int]\n    # Nested block depths of scopes\n    block_depth: list[int]\n    # TypeInfo of directly enclosing class (or None)\n    _type: TypeInfo | None = None\n    # Stack of outer classes (the second tuple item contains tvars).\n    type_stack: list[TypeInfo | None]\n    # Type variables bound by the current scope, be it class or function\n    tvar_scope: TypeVarLikeScope\n    # Per-module options\n    options: Options\n\n    # Stack of functions being analyzed\n    function_stack: list[FuncItem]\n\n    # Set to True if semantic analysis defines a name, or replaces a\n    # placeholder definition. If some iteration makes no progress,\n    # there can be at most one additional final iteration (see below).\n    progress = False\n    deferred = False  # Set to true if another analysis pass is needed\n    incomplete = False  # Set to true if current module namespace is missing things\n    # Is this the final iteration of semantic analysis (where we report\n    # unbound names due to cyclic definitions and should not defer)?\n    _final_iteration = False\n    # These names couldn't be added to the symbol table due to incomplete deps.\n    # Note that missing names are per module, _not_ per namespace. This means that e.g.\n    # a missing name at global scope will block adding same name at a class scope.\n    # This should not affect correctness and is purely a performance issue,\n    # since it can cause unnecessary deferrals. These are represented as\n    # PlaceholderNodes in the symbol table. We use this to ensure that the first\n    # definition takes precedence even if it's incomplete.\n    #\n    # Note that a star import adds a special name '*' to the set, this blocks\n    # adding _any_ names in the current file.\n    missing_names: list[set[str]]\n    # Callbacks that will be called after semantic analysis to tweak things.\n    patches: list[tuple[int, Callable[[], None]]]\n    loop_depth: list[int]  # Depth of breakable loops\n    cur_mod_id = \"\"  # Current module id (or None) (phase 2)\n    _is_stub_file = False  # Are we analyzing a stub file?\n    _is_typeshed_stub_file = False  # Are we analyzing a typeshed stub file?\n    imports: set[str]  # Imported modules (during phase 2 analysis)\n    # Note: some imports (and therefore dependencies) might\n    # not be found in phase 1, for example due to * imports.\n    errors: Errors  # Keeps track of generated errors\n    plugin: Plugin  # Mypy plugin for special casing of library features\n    statement: Statement | None = None  # Statement/definition being analyzed\n\n    # Mapping from 'async def' function definitions to their return type wrapped as a\n    # 'Coroutine[Any, Any, T]'. Used to keep track of whether a function definition's\n    # return type has already been wrapped, by checking if the function definition's\n    # type is stored in this mapping and that it still matches.\n    wrapped_coro_return_types: dict[FuncDef, Type] = {}\n\n    def __init__(\n        self,\n        modules: dict[str, MypyFile],\n        missing_modules: dict[str, int],\n        incomplete_namespaces: set[str],\n        errors: Errors,\n        plugin: Plugin,\n        import_map: dict[str, set[str]],\n    ) -> None:\n        \"\"\"Construct semantic analyzer.\n\n        We reuse the same semantic analyzer instance across multiple modules.\n\n        Args:\n            modules: Global modules dictionary\n            missing_modules: Modules that could not be imported encountered so far\n            incomplete_namespaces: Namespaces that are being populated during semantic analysis\n                (can contain modules and classes within the current SCC; mutated by the caller)\n            errors: Report analysis errors using this instance\n        \"\"\"\n        self.locals = [None]\n        self.scope_stack = [SCOPE_GLOBAL]\n        # Saved namespaces from previous iteration. Every top-level function/method body is\n        # analyzed in several iterations until all names are resolved. We need to save\n        # the local namespaces for the top level function and all nested functions between\n        # these iterations. See also semanal_main.process_top_level_function().\n        self.saved_locals: dict[\n            FuncItem | GeneratorExpr | DictionaryComprehension, SymbolTable\n        ] = {}\n        self.imports = set()\n        self._type = None\n        self.type_stack = []\n        # Are the namespaces of classes being processed complete?\n        self.incomplete_type_stack: list[bool] = []\n        self.tvar_scope = TypeVarLikeScope()\n        self.function_stack = []\n        self.block_depth = [0]\n        self.loop_depth = [0]\n        self.errors = errors\n        self.modules = modules\n        self.import_map = import_map\n        self.msg = MessageBuilder(errors, modules)\n        self.missing_modules = missing_modules\n        self.missing_names = [set()]\n        # These namespaces are still in process of being populated. If we encounter a\n        # missing name in these namespaces, we need to defer the current analysis target,\n        # since it's possible that the name will be there once the namespace is complete.\n        self.incomplete_namespaces = incomplete_namespaces\n        self.all_exports: list[str] = []\n        self.plugin = plugin\n        self.recurse_into_functions = True\n        self.scope = Scope()\n\n        # Trace line numbers for every file where deferral happened during analysis of\n        # current SCC or top-level function.\n        self.deferral_debug_context: list[tuple[str, int]] = []\n\n        # This is needed to properly support recursive type aliases. The problem is that\n        # Foo[Bar] could mean three things depending on context: a target for type alias,\n        # a normal index expression (including enum index), or a type application.\n        # The latter is particularly problematic as it can falsely create incomplete\n        # refs while analysing rvalues of type aliases. To avoid this we first analyse\n        # rvalues while temporarily setting this to True.\n        self.basic_type_applications = False\n\n        # Used to temporarily enable unbound type variables in some contexts. Namely,\n        # in base class expressions, and in right hand sides of type aliases. Do not add\n        # new uses of this, as this may cause leaking `UnboundType`s to type checking.\n        self.allow_unbound_tvars = False\n\n        # Used to pass information about current overload index to visit_func_def().\n        self.current_overload_item: int | None = None\n\n        # Used to track whether currently inside an except* block. This helps\n        # to invoke errors when continue/break/return is used inside except* block.\n        self.inside_except_star_block: bool = False\n        # Used to track edge case when return is still inside except* if it enters a loop\n        self.return_stmt_inside_except_star_block: bool = False\n\n        self._str_type: Instance | None = None\n        self._function_type: Instance | None = None\n        self._object_type: Instance | None = None\n\n        # TypeForm profiling counters\n        self.type_expression_parse_count: int = 0  # Total try_parse_as_type_expression calls\n        self.type_expression_full_parse_success_count: int = 0  # Successful full parses\n        self.type_expression_full_parse_failure_count: int = 0  # Failed full parses\n\n        # Imports of submodules transitively visible from given module.\n        # This is needed to support patterns like this\n        #   [a.py]\n        #     import b\n        #     import foo\n        #     foo.bar  # <- this should work even if bar is not re-exported in foo\n        #   [b.py]\n        #     import foo.bar\n        self.transitive_submodule_imports: dict[str, set[str]] = {}\n\n    # mypyc doesn't properly handle implementing an abstractproperty\n    # with a regular attribute so we make them properties\n    @property\n    def type(self) -> TypeInfo | None:\n        return self._type\n\n    @property\n    def is_stub_file(self) -> bool:\n        return self._is_stub_file\n\n    @property\n    def is_typeshed_stub_file(self) -> bool:\n        return self._is_typeshed_stub_file\n\n    @property\n    def final_iteration(self) -> bool:\n        return self._final_iteration\n\n    @contextmanager\n    def allow_unbound_tvars_set(self) -> Iterator[None]:\n        old = self.allow_unbound_tvars\n        self.allow_unbound_tvars = True\n        try:\n            yield\n        finally:\n            self.allow_unbound_tvars = old\n\n    @contextmanager\n    def inside_except_star_block_set(\n        self, value: bool, entering_loop: bool = False\n    ) -> Iterator[None]:\n        old = self.inside_except_star_block\n        self.inside_except_star_block = value\n\n        # Return statement would still be in except* scope if entering loops\n        if not entering_loop:\n            old_return_stmt_flag = self.return_stmt_inside_except_star_block\n            self.return_stmt_inside_except_star_block = value\n\n        try:\n            yield\n        finally:\n            self.inside_except_star_block = old\n            if not entering_loop:\n                self.return_stmt_inside_except_star_block = old_return_stmt_flag\n\n    #\n    # Preparing module (performed before semantic analysis)\n    #\n\n    def prepare_file(self, file_node: MypyFile) -> None:\n        \"\"\"Prepare a freshly parsed file for semantic analysis.\"\"\"\n        if \"builtins\" in self.modules:\n            file_node.names[\"__builtins__\"] = SymbolTableNode(GDEF, self.modules[\"builtins\"])\n        if file_node.fullname == \"builtins\":\n            self.prepare_builtins_namespace(file_node)\n        if file_node.fullname == \"typing\":\n            self.prepare_typing_namespace(file_node, type_aliases)\n        if file_node.fullname == \"typing_extensions\":\n            self.prepare_typing_namespace(file_node, typing_extensions_aliases)\n\n    def prepare_typing_namespace(self, file_node: MypyFile, aliases: dict[str, str]) -> None:\n        \"\"\"Remove dummy alias definitions such as List = TypeAlias(object) from typing.\n\n        They will be replaced with real aliases when corresponding targets are ready.\n        \"\"\"\n\n        # This is all pretty unfortunate. typeshed now has a\n        # sys.version_info check for OrderedDict, and we shouldn't\n        # take it out, because it is correct and a typechecker should\n        # use that as a source of truth. But instead we rummage\n        # through IfStmts to remove the info first.  (I tried to\n        # remove this whole machinery and ran into issues with the\n        # builtins/typing import cycle.)\n        def helper(defs: list[Statement]) -> None:\n            for stmt in defs.copy():\n                if isinstance(stmt, IfStmt):\n                    for body in stmt.body:\n                        helper(body.body)\n                    if stmt.else_body:\n                        helper(stmt.else_body.body)\n                if (\n                    isinstance(stmt, AssignmentStmt)\n                    and len(stmt.lvalues) == 1\n                    and isinstance(stmt.lvalues[0], NameExpr)\n                ):\n                    # Assignment to a simple name, remove it if it is a dummy alias.\n                    if f\"{file_node.fullname}.{stmt.lvalues[0].name}\" in aliases:\n                        defs.remove(stmt)\n\n        helper(file_node.defs)\n\n    def prepare_builtins_namespace(self, file_node: MypyFile) -> None:\n        \"\"\"Add certain special-cased definitions to the builtins module.\n\n        Some definitions are too special or fundamental to be processed\n        normally from the AST.\n        \"\"\"\n        names = file_node.names\n\n        # Add empty definition for core built-in classes, since they are required for basic\n        # operation. These will be completed later on.\n        for name in CORE_BUILTIN_CLASSES:\n            cdef = ClassDef(name, Block([]))  # Dummy ClassDef, will be replaced later\n            info = TypeInfo(SymbolTable(), cdef, \"builtins\")\n            info._fullname = f\"builtins.{name}\"\n            names[name] = SymbolTableNode(GDEF, info)\n\n        bool_info = names[\"bool\"].node\n        assert isinstance(bool_info, TypeInfo)\n        bool_type = Instance(bool_info, [])\n\n        special_var_types: list[tuple[str, Type]] = [\n            (\"None\", NoneType()),\n            # reveal_type is a mypy-only function that gives an error with\n            # the type of its arg.\n            (\"reveal_type\", AnyType(TypeOfAny.special_form)),\n            # reveal_locals is a mypy-only function that gives an error with the types of\n            # locals\n            (\"reveal_locals\", AnyType(TypeOfAny.special_form)),\n            (\"True\", bool_type),\n            (\"False\", bool_type),\n            (\"__debug__\", bool_type),\n        ]\n\n        for name, typ in special_var_types:\n            v = Var(name, typ)\n            v._fullname = f\"builtins.{name}\"\n            file_node.names[name] = SymbolTableNode(GDEF, v)\n\n    #\n    # Analyzing a target\n    #\n\n    def refresh_partial(\n        self,\n        node: MypyFile | FuncDef | OverloadedFuncDef,\n        patches: list[tuple[int, Callable[[], None]]],\n        final_iteration: bool,\n        file_node: MypyFile,\n        options: Options,\n        active_type: TypeInfo | None = None,\n    ) -> None:\n        \"\"\"Refresh a stale target in fine-grained incremental mode.\"\"\"\n        self.patches = patches\n        self.deferred = False\n        self.incomplete = False\n        self._final_iteration = final_iteration\n        self.missing_names[-1] = set()\n\n        with self.file_context(file_node, options, active_type):\n            if isinstance(node, MypyFile):\n                self.refresh_top_level(node)\n            else:\n                self.recurse_into_functions = True\n                self.accept(node)\n        del self.patches\n\n    def refresh_top_level(self, file_node: MypyFile) -> None:\n        \"\"\"Reanalyze a stale module top-level in fine-grained incremental mode.\"\"\"\n        if self.options.allow_redefinition_new and not self.options.local_partial_types:\n            n = TempNode(AnyType(TypeOfAny.special_form))\n            n.line = 1\n            n.column = 0\n            n.end_line = 1\n            n.end_column = 0\n            self.fail(\"--local-partial-types must be enabled if using --allow-redefinition-new\", n)\n        if self.options.allow_redefinition_new and self.options.allow_redefinition_old:\n            n = TempNode(AnyType(TypeOfAny.special_form))\n            n.line = 1\n            n.column = 0\n            n.end_line = 1\n            n.end_column = 0\n            self.fail(\n                \"--allow-redefinition-old and --allow-redefinition-new\"\n                \" should not be used together\",\n                n,\n            )\n        self.recurse_into_functions = False\n        self.add_implicit_module_attrs(file_node)\n        for d in file_node.defs:\n            self.accept(d)\n        if file_node.fullname == \"typing\":\n            self.add_builtin_aliases(file_node)\n        if file_node.fullname == \"typing_extensions\":\n            self.add_typing_extension_aliases(file_node)\n        self.adjust_public_exports()\n        self.all_exports = []\n\n    def add_implicit_module_attrs(self, file_node: MypyFile) -> None:\n        \"\"\"Manually add implicit definitions of module '__name__' etc.\"\"\"\n        str_type: Type | None = self.named_type_or_none(\"builtins.str\")\n        if str_type is None:\n            str_type = UnboundType(\"builtins.str\")\n        inst: Type | None\n        for name, t in implicit_module_attrs.items():\n            if name == \"__doc__\":\n                typ: Type = str_type\n            elif name == \"__path__\":\n                if not file_node.is_package_init_file():\n                    continue\n                # Need to construct the type ourselves, to avoid issues with __builtins__.list\n                # not being subscriptable or typing.List not getting bound\n                inst = self.named_type_or_none(\"builtins.list\", [str_type])\n                if inst is None:\n                    assert not self.final_iteration, \"Cannot find builtins.list to add __path__\"\n                    self.defer()\n                    return\n                typ = inst\n            elif name == \"__annotations__\":\n                inst = self.named_type_or_none(\n                    \"builtins.dict\", [str_type, AnyType(TypeOfAny.special_form)]\n                )\n                if inst is None:\n                    assert (\n                        not self.final_iteration\n                    ), \"Cannot find builtins.dict to add __annotations__\"\n                    self.defer()\n                    return\n                typ = inst\n            elif name == \"__spec__\":\n                if self.options.use_builtins_fixtures:\n                    inst = self.named_type_or_none(\"builtins.object\")\n                else:\n                    inst = self.named_type_or_none(\"importlib.machinery.ModuleSpec\")\n                if inst is None:\n                    if (\n                        self.final_iteration\n                        or self.options.clone_for_module(\"importlib.machinery\").follow_imports\n                        == \"skip\"\n                    ):\n                        # If we are not allowed to resolve imports from `importlib.machinery`,\n                        # ModuleSpec will not be available at any iteration.\n                        # Use the fallback earlier.\n                        # (see https://github.com/python/mypy/issues/18237)\n                        inst = self.named_type_or_none(\"builtins.object\")\n                        assert inst is not None, \"Cannot find builtins.object\"\n                    else:\n                        self.defer()\n                        return\n                if file_node.name == \"__main__\":\n                    # https://docs.python.org/3/reference/import.html#main-spec\n                    inst = UnionType.make_union([inst, NoneType()])\n                typ = inst\n            else:\n                assert t is not None, f\"type should be specified for {name}\"\n                typ = UnboundType(t)\n\n            existing = file_node.names.get(name)\n            if existing is not None and not isinstance(existing.node, PlaceholderNode):\n                # Already exists.\n                continue\n\n            an_type = self.anal_type(typ)\n            if an_type:\n                var = Var(name, an_type)\n                var._fullname = self.qualified_name(name)\n                var.is_ready = True\n                self.add_symbol(name, var, dummy_context())\n            else:\n                self.add_symbol(\n                    name,\n                    PlaceholderNode(self.qualified_name(name), file_node, -1),\n                    dummy_context(),\n                )\n\n    def add_builtin_aliases(self, tree: MypyFile) -> None:\n        \"\"\"Add builtin type aliases to typing module.\n\n        For historical reasons, the aliases like `List = list` are not defined\n        in typeshed stubs for typing module. Instead we need to manually add the\n        corresponding nodes on the fly. We explicitly mark these aliases as normalized,\n        so that a user can write `typing.List[int]`.\n        \"\"\"\n        assert tree.fullname == \"typing\"\n        for alias, target_name in type_aliases.items():\n            if (\n                alias in type_aliases_source_versions\n                and type_aliases_source_versions[alias] > self.options.python_version\n            ):\n                # This alias is not available on this Python version.\n                continue\n            name = alias.split(\".\")[-1]\n            if name in tree.names and not isinstance(tree.names[name].node, PlaceholderNode):\n                continue\n            self.create_alias(tree, target_name, alias, name)\n\n    def add_typing_extension_aliases(self, tree: MypyFile) -> None:\n        \"\"\"Typing extensions module does contain some type aliases.\n\n        We need to analyze them as such, because in typeshed\n        they are just defined as `_Alias()` call.\n        Which is not supported natively.\n        \"\"\"\n        assert tree.fullname == \"typing_extensions\"\n\n        for alias, target_name in typing_extensions_aliases.items():\n            name = alias.split(\".\")[-1]\n            if name in tree.names and isinstance(tree.names[name].node, TypeAlias):\n                continue  # Do not reset TypeAliases on the second pass.\n\n            # We need to remove any node that is there at the moment. It is invalid.\n            tree.names.pop(name, None)\n\n            # Now, create a new alias.\n            self.create_alias(tree, target_name, alias, name)\n\n    def create_alias(self, tree: MypyFile, target_name: str, alias: str, name: str) -> None:\n        tag = self.track_incomplete_refs()\n        n = self.lookup_fully_qualified_or_none(target_name)\n        if n:\n            if isinstance(n.node, PlaceholderNode):\n                self.mark_incomplete(name, tree)\n            else:\n                # Found built-in class target. Create alias.\n                target = self.named_type_or_none(target_name, [])\n                assert target is not None\n                # Transform List to List[Any], etc.\n                fix_instance(\n                    target, self.fail, self.note, disallow_any=False, options=self.options\n                )\n                alias_node = TypeAlias(\n                    target,\n                    alias,\n                    tree.fullname,\n                    line=-1,\n                    column=-1,  # there is no context\n                    no_args=True,\n                    normalized=True,\n                )\n                self.add_symbol(name, alias_node, tree)\n        elif self.found_incomplete_ref(tag):\n            # Built-in class target may not ready yet -- defer.\n            self.mark_incomplete(name, tree)\n        else:\n            # Test fixtures may be missing some builtin classes, which is okay.\n            # Kill the placeholder if there is one.\n            if name in tree.names:\n                assert isinstance(tree.names[name].node, PlaceholderNode)\n                del tree.names[name]\n\n    def adjust_public_exports(self) -> None:\n        \"\"\"Adjust the module visibility of globals due to __all__.\"\"\"\n        if \"__all__\" in self.globals:\n            for name, g in self.globals.items():\n                # Being included in __all__ explicitly exports and makes public.\n                if name in self.all_exports:\n                    g.module_public = True\n                    g.module_hidden = False\n                # But when __all__ is defined, and a symbol is not included in it,\n                # it cannot be public.\n                else:\n                    g.module_public = False\n\n    @contextmanager\n    def file_context(\n        self, file_node: MypyFile, options: Options, active_type: TypeInfo | None = None\n    ) -> Iterator[None]:\n        \"\"\"Configure analyzer for analyzing targets within a file/class.\n\n        Args:\n            file_node: target file\n            options: options specific to the file\n            active_type: must be the surrounding class to analyze method targets\n        \"\"\"\n        scope = self.scope\n        self.options = options\n        self.errors.set_file(file_node.path, file_node.fullname, scope=scope, options=options)\n        self.cur_mod_node = file_node\n        self.cur_mod_id = file_node.fullname\n        with scope.module_scope(self.cur_mod_id):\n            self._is_stub_file = file_node.path.lower().endswith(\".pyi\")\n            self._is_typeshed_stub_file = file_node.is_typeshed_file(options)\n            self.globals = file_node.names\n            self.tvar_scope = TypeVarLikeScope()\n\n            self.named_tuple_analyzer = NamedTupleAnalyzer(options, self, self.msg)\n            self.typed_dict_analyzer = TypedDictAnalyzer(options, self, self.msg)\n            self.enum_call_analyzer = EnumCallAnalyzer(options, self)\n            self.newtype_analyzer = NewTypeAnalyzer(options, self, self.msg)\n\n            # Counter that keeps track of references to undefined things potentially caused by\n            # incomplete namespaces.\n            self.num_incomplete_refs = 0\n\n            if active_type:\n                enclosing_fullname = active_type.fullname.rsplit(\".\", 1)[0]\n                if \".\" in enclosing_fullname:\n                    enclosing_node = self.lookup_fully_qualified_or_none(enclosing_fullname)\n                    if enclosing_node and isinstance(enclosing_node.node, TypeInfo):\n                        self._type = enclosing_node.node\n                self.push_type_args(active_type.defn.type_args, active_type.defn)\n                self.incomplete_type_stack.append(False)\n                scope.enter_class(active_type)\n                self.enter_class(active_type.defn.info)\n                for tvar in active_type.defn.type_vars:\n                    self.tvar_scope.bind_existing(tvar)\n\n            yield\n\n            if active_type:\n                scope.leave_class()\n                self.leave_class()\n                self._type = None\n                self.incomplete_type_stack.pop()\n                self.pop_type_args(active_type.defn.type_args)\n        del self.options\n\n    #\n    # Functions\n    #\n\n    def visit_func_def(self, defn: FuncDef) -> None:\n        self.statement = defn\n\n        # Visit default values because they may contain assignment expressions.\n        for arg in defn.arguments:\n            if arg.initializer:\n                arg.initializer.accept(self)\n\n        defn.is_conditional = self.block_depth[-1] > 0\n\n        # Set full names even for those definitions that aren't added\n        # to a symbol table. For example, for overload items.\n        defn._fullname = self.qualified_name(defn.name)\n\n        # We don't add module top-level functions to symbol tables\n        # when we analyze their bodies in the second phase on analysis,\n        # since they were added in the first phase. Nested functions\n        # get always added, since they aren't separate targets.\n        if not self.recurse_into_functions or len(self.function_stack) > 0:\n            if not defn.is_decorated and not defn.is_overload:\n                self.add_function_to_symbol_table(defn)\n\n        if not self.recurse_into_functions and not defn.def_or_infer_vars:\n            return\n\n        with self.scope.function_scope(defn), self.set_recurse_into_functions():\n            with self.inside_except_star_block_set(value=False):\n                self.analyze_func_def(defn)\n\n    def function_fullname(self, fullname: str) -> str:\n        if self.current_overload_item is None:\n            return fullname\n        return f\"{fullname}#{self.current_overload_item}\"\n\n    def analyze_func_def(self, defn: FuncDef) -> None:\n        if self.push_type_args(defn.type_args, defn) is None:\n            self.defer(defn)\n            return\n\n        self.function_stack.append(defn)\n\n        if defn.type:\n            assert isinstance(defn.type, CallableType)\n            has_self_type = self.update_function_type_variables(defn.type, defn)\n        else:\n            has_self_type = False\n\n        self.function_stack.pop()\n\n        if self.is_class_scope():\n            # Method definition\n            assert self.type is not None\n            defn.info = self.type\n            if defn.type is not None and defn.name in (\"__init__\", \"__init_subclass__\"):\n                assert isinstance(defn.type, CallableType)\n                if isinstance(get_proper_type(defn.type.ret_type), AnyType):\n                    defn.type = defn.type.copy_modified(ret_type=NoneType())\n            self.prepare_method_signature(defn, self.type, has_self_type)\n\n        # Analyze function signature\n        fullname = self.function_fullname(defn.fullname)\n        with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)):\n            if defn.type:\n                self.check_classvar_in_signature(defn.type)\n                assert isinstance(defn.type, CallableType)\n                # Signature must be analyzed in the surrounding scope so that\n                # class-level imported names and type variables are in scope.\n                analyzer = self.type_analyzer()\n                tag = self.track_incomplete_refs()\n                result = analyzer.visit_callable_type(defn.type, nested=False, namespace=fullname)\n                # Don't store not ready types (including placeholders).\n                if self.found_incomplete_ref(tag) or has_placeholder(result):\n                    self.defer(defn)\n                    self.pop_type_args(defn.type_args)\n                    return\n                assert isinstance(result, ProperType)\n                if isinstance(result, CallableType):\n                    # type guards need to have a positional argument, to spec\n                    skip_self = self.is_class_scope() and not defn.is_static\n                    if result.type_guard and ARG_POS not in result.arg_kinds[skip_self:]:\n                        self.fail(\n                            \"TypeGuard functions must have a positional argument\",\n                            result,\n                            code=codes.VALID_TYPE,\n                        )\n                        # in this case, we just kind of just ... remove the type guard.\n                        result = result.copy_modified(type_guard=None)\n                    if result.type_is and ARG_POS not in result.arg_kinds[skip_self:]:\n                        self.fail(\n                            '\"TypeIs\" functions must have a positional argument',\n                            result,\n                            code=codes.VALID_TYPE,\n                        )\n                        result = result.copy_modified(type_is=None)\n\n                    result = self.remove_unpack_kwargs(defn, result)\n                    if has_self_type and self.type is not None:\n                        info = self.type\n                        if info.self_type is not None:\n                            result.variables = (info.self_type,) + result.variables\n                defn.type = result\n                self.add_type_alias_deps(analyzer.aliases_used)\n                self.check_function_signature(defn)\n                if isinstance(defn, FuncDef):\n                    assert isinstance(defn.type, CallableType)\n                    defn.type = set_callable_name(defn.type, defn)\n\n        self.analyze_arg_initializers(defn)\n        self.analyze_function_body(defn)\n\n        if self.is_class_scope():\n            assert self.type is not None\n            # Mark protocol methods with empty bodies as implicitly abstract.\n            # This makes explicit protocol subclassing type-safe.\n            if (\n                self.type.is_protocol\n                and not self.is_stub_file  # Bodies in stub files are always empty.\n                and (not isinstance(self.scope.function, OverloadedFuncDef) or defn.is_property)\n                and defn.abstract_status != IS_ABSTRACT\n                and is_trivial_body(defn.body)\n            ):\n                defn.abstract_status = IMPLICITLY_ABSTRACT\n            if (\n                is_trivial_body(defn.body)\n                and not self.is_stub_file\n                and defn.abstract_status != NOT_ABSTRACT\n            ):\n                defn.is_trivial_body = True\n\n        if (\n            defn.is_coroutine\n            and isinstance(defn.type, CallableType)\n            and self.wrapped_coro_return_types.get(defn) != defn.type\n        ):\n            if defn.is_async_generator:\n                # Async generator types are handled elsewhere\n                pass\n            else:\n                # A coroutine defined as `async def foo(...) -> T: ...`\n                # has external return type `Coroutine[Any, Any, T]`.\n                any_type = AnyType(TypeOfAny.special_form)\n                ret_type = self.named_type_or_none(\n                    \"typing.Coroutine\", [any_type, any_type, defn.type.ret_type]\n                )\n                assert ret_type is not None, \"Internal error: typing.Coroutine not found\"\n                defn.type = defn.type.copy_modified(ret_type=ret_type)\n                self.wrapped_coro_return_types[defn] = defn.type\n\n        self.pop_type_args(defn.type_args)\n\n    def remove_unpack_kwargs(self, defn: FuncDef, typ: CallableType) -> CallableType:\n        if not typ.arg_kinds or typ.arg_kinds[-1] is not ArgKind.ARG_STAR2:\n            return typ\n        last_type = typ.arg_types[-1]\n        if not isinstance(last_type, UnpackType):\n            return typ\n        p_last_type = get_proper_type(last_type.type)\n        if not isinstance(p_last_type, TypedDictType):\n            self.fail(\"Unpack item in ** parameter must be a TypedDict\", last_type)\n            new_arg_types = typ.arg_types[:-1] + [AnyType(TypeOfAny.from_error)]\n            return typ.copy_modified(arg_types=new_arg_types)\n        overlap = set(typ.arg_names) & set(p_last_type.items)\n        # It is OK for TypedDict to have a key named 'kwargs'.\n        overlap.discard(typ.arg_names[-1])\n        if overlap:\n            overlapped = \", \".join([f'\"{name}\"' for name in sorted(filter(None, overlap))])\n            self.fail(\n                f\"Overlap between parameter names and ** TypedDict items: {overlapped}\", defn\n            )\n            new_arg_types = typ.arg_types[:-1] + [AnyType(TypeOfAny.from_error)]\n            return typ.copy_modified(arg_types=new_arg_types)\n        # OK, everything looks right now, mark the callable type as using unpack.\n        new_arg_types = typ.arg_types[:-1] + [p_last_type]\n        return typ.copy_modified(arg_types=new_arg_types, unpack_kwargs=True)\n\n    def prepare_method_signature(self, func: FuncDef, info: TypeInfo, has_self_type: bool) -> None:\n        \"\"\"Check basic signature validity and tweak annotation of self/cls argument.\"\"\"\n        # Only non-static methods are special, as well as __new__.\n        functype = func.type\n        if func.name == \"__new__\":\n            func.is_static = True\n        if func.has_self_or_cls_argument:\n            if func.name in [\"__init_subclass__\", \"__class_getitem__\"]:\n                func.is_class = True\n            if func.arguments and isinstance(functype, CallableType):\n                self_type = get_proper_type(functype.arg_types[0])\n                if isinstance(self_type, AnyType):\n                    if has_self_type:\n                        assert self.type is not None and self.type.self_type is not None\n                        leading_type: Type = self.type.self_type\n                    else:\n                        func.is_trivial_self = True\n                        leading_type = fill_typevars(info)\n                    if func.is_class or func.name == \"__new__\":\n                        leading_type = self.class_type(leading_type)\n                    func.type = replace_implicit_first_type(functype, leading_type)\n                elif has_self_type and isinstance(func.unanalyzed_type, CallableType):\n                    if not isinstance(get_proper_type(func.unanalyzed_type.arg_types[0]), AnyType):\n                        if self.is_expected_self_type(\n                            self_type, func.is_class or func.name == \"__new__\"\n                        ):\n                            # This error is off by default, since it is explicitly allowed\n                            # by the PEP 673.\n                            self.fail(\n                                'Redundant \"Self\" annotation for the first method argument',\n                                func,\n                                code=codes.REDUNDANT_SELF_TYPE,\n                            )\n                        else:\n                            self.fail(\n                                \"Method cannot have explicit self annotation and Self type\", func\n                            )\n        elif has_self_type:\n            self.fail(\"Static methods cannot use Self type\", func)\n\n    def is_expected_self_type(self, typ: Type, is_classmethod: bool) -> bool:\n        \"\"\"Does this (analyzed or not) type represent the expected Self type for a method?\"\"\"\n        assert self.type is not None\n        typ = get_proper_type(typ)\n        if is_classmethod:\n            if isinstance(typ, TypeType):\n                return self.is_expected_self_type(typ.item, is_classmethod=False)\n            if isinstance(typ, UnboundType):\n                sym = self.lookup_qualified(typ.name, typ, suppress_errors=True)\n                if sym is not None and sym.fullname in TYPE_NAMES and typ.args:\n                    return self.is_expected_self_type(typ.args[0], is_classmethod=False)\n            return False\n        if isinstance(typ, TypeVarType):\n            return typ == self.type.self_type\n        if isinstance(typ, UnboundType):\n            sym = self.lookup_qualified(typ.name, typ, suppress_errors=True)\n            return sym is not None and sym.fullname in SELF_TYPE_NAMES\n        return False\n\n    def set_original_def(self, previous: Node | None, new: FuncDef | Decorator) -> bool:\n        \"\"\"If 'new' conditionally redefine 'previous', set 'previous' as original\n\n        We reject straight redefinitions of functions, as they are usually\n        a programming error. For example:\n\n          def f(): ...\n          def f(): ...  # Error: 'f' redefined\n        \"\"\"\n        if isinstance(new, Decorator):\n            new = new.func\n        if (\n            isinstance(previous, (FuncDef, Decorator))\n            and unnamed_function(new.name)\n            and unnamed_function(previous.name)\n        ):\n            return True\n        if isinstance(previous, (FuncDef, Var, Decorator)) and new.is_conditional:\n            new.original_def = previous\n            return True\n        else:\n            return False\n\n    def update_function_type_variables(self, fun_type: CallableType, defn: FuncItem) -> bool:\n        \"\"\"Make any type variables in the signature of defn explicit.\n\n        Update the signature of defn to contain type variable definitions\n        if defn is generic. Return True, if the signature contains typing.Self\n        type, or False otherwise.\n        \"\"\"\n        fullname = self.function_fullname(defn.fullname)\n        with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)):\n            a = self.type_analyzer()\n            fun_type.variables, has_self_type = a.bind_function_type_variables(fun_type, defn)\n            if has_self_type and self.type is not None:\n                self.setup_self_type()\n            if defn.type_args:\n                bound_fullnames = {v.fullname for v in fun_type.variables}\n                declared_fullnames = {self.qualified_name(p.name) for p in defn.type_args}\n                extra = sorted(bound_fullnames - declared_fullnames)\n                if extra:\n                    self.msg.type_parameters_should_be_declared(\n                        [n.split(\".\")[-1] for n in extra], defn\n                    )\n            return has_self_type\n\n    def setup_self_type(self) -> None:\n        \"\"\"Setup a (shared) Self type variable for current class.\n\n        We intentionally don't add it to the class symbol table,\n        so it can be accessed only by mypy and will not cause\n        clashes with user defined names.\n        \"\"\"\n        assert self.type is not None\n        info = self.type\n        if info.self_type is not None:\n            if has_placeholder(info.self_type.upper_bound):\n                # Similar to regular (user defined) type variables.\n                self.process_placeholder(\n                    None,\n                    \"Self upper bound\",\n                    info,\n                    force_progress=info.self_type.upper_bound != fill_typevars(info),\n                )\n            else:\n                return\n        info.self_type = TypeVarType(\n            \"Self\",\n            f\"{info.fullname}.Self\",\n            id=TypeVarId(0),  # 0 is a special value for self-types.\n            values=[],\n            upper_bound=fill_typevars(info),\n            default=AnyType(TypeOfAny.from_omitted_generics),\n        )\n\n    def visit_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:\n        self.statement = defn\n        self.add_function_to_symbol_table(defn)\n\n        if not self.recurse_into_functions and not defn.def_or_infer_vars:\n            return\n\n        # NB: Since _visit_overloaded_func_def will call accept on the\n        # underlying FuncDefs, the function might get entered twice.\n        # This is fine, though, because only the outermost function is\n        # used to compute targets.\n        with self.scope.function_scope(defn), self.set_recurse_into_functions():\n            self.analyze_overloaded_func_def(defn)\n\n    @contextmanager\n    def overload_item_set(self, item: int | None) -> Iterator[None]:\n        self.current_overload_item = item\n        try:\n            yield\n        finally:\n            self.current_overload_item = None\n\n    def analyze_overloaded_func_def(self, defn: OverloadedFuncDef) -> None:\n        # OverloadedFuncDef refers to any legitimate situation where you have\n        # more than one declaration for the same function in a row.  This occurs\n        # with a @property with a setter or a deleter, and for a classic\n        # @overload.\n\n        defn._fullname = self.qualified_name(defn.name)\n        # TODO: avoid modifying items.\n        defn.items = defn.unanalyzed_items.copy()\n\n        first_item = defn.items[0]\n        first_item.is_overload = True\n        with self.overload_item_set(0):\n            first_item.accept(self)\n\n        bare_setter_type = None\n        is_property = False\n        if isinstance(first_item, Decorator) and first_item.func.is_property:\n            is_property = True\n            # This is a property.\n            first_item.func.is_overload = True\n            bare_setter_type = self.analyze_property_with_multi_part_definition(defn)\n            typ = function_type(first_item.func, self.function_type())\n            assert isinstance(typ, CallableType)\n            typ.definition = first_item\n            types = [typ]\n        else:\n            # This is a normal overload. Find the item signatures, the\n            # implementation (if outside a stub), and any missing @overload\n            # decorators.\n            types, impl, non_overload_indexes = self.analyze_overload_sigs_and_impl(defn)\n            defn.impl = impl\n            if non_overload_indexes:\n                self.handle_missing_overload_decorators(\n                    defn, non_overload_indexes, some_overload_decorators=len(types) > 0\n                )\n            # If we found an implementation, remove it from the overload item list,\n            # as it's special.\n            if impl is not None:\n                assert impl is defn.items[-1]\n                defn.items = defn.items[:-1]\n            elif not non_overload_indexes:\n                self.handle_missing_overload_implementation(defn)\n\n        if types and not any(\n            # If some overload items are decorated with other decorators, then\n            # the overload type will be determined during type checking.\n            # Note: bare @property is removed in visit_decorator().\n            isinstance(it, Decorator)\n            and len(it.decorators) > (1 if i > 0 or not is_property else 0)\n            for i, it in enumerate(defn.items)\n        ):\n            # TODO: should we enforce decorated overloads consistency somehow?\n            # Some existing code uses both styles:\n            #   * Put decorator only on implementation, use \"effective\" types in overloads\n            #   * Put decorator everywhere, use \"bare\" types in overloads.\n            defn.type = Overloaded(types)\n            defn.type.line = defn.line\n            # In addition, we can set the getter/setter type for valid properties as some\n            # code paths may either use the above type, or var.type etc. of the first item.\n            if isinstance(first_item, Decorator) and bare_setter_type:\n                first_item.var.type = types[0]\n                first_item.var.setter_type = bare_setter_type\n\n        if not defn.items:\n            # It was not a real overload after all, but function redefinition. We've\n            # visited the redefinition(s) already.\n            if not defn.impl:\n                # For really broken overloads with no items and no implementation we need to keep\n                # at least one item to hold basic information like function name.\n                defn.impl = defn.unanalyzed_items[-1]\n            return\n\n        # We know this is an overload def. Infer properties and perform some checks.\n        self.process_deprecated_overload(defn)\n        self.process_final_in_overload(defn)\n        self.process_static_or_class_method_in_overload(defn)\n        self.process_overload_impl(defn)\n\n    def process_deprecated_overload(self, defn: OverloadedFuncDef) -> None:\n        if defn.is_property:\n            return\n\n        if isinstance(impl := defn.impl, Decorator) and (\n            (deprecated := impl.func.deprecated) is not None\n        ):\n            defn.deprecated = deprecated\n            for item in defn.items:\n                if isinstance(item, Decorator):\n                    item.func.deprecated = deprecated\n\n        for item in defn.items:\n            deprecation = False\n            if isinstance(item, Decorator):\n                for d in item.decorators:\n                    if deprecation and refers_to_fullname(d, OVERLOAD_NAMES):\n                        self.msg.note(\"@overload should be placed before @deprecated\", d)\n                    elif (deprecated := self.get_deprecated(d)) is not None:\n                        deprecation = True\n                        if isinstance(typ := item.func.type, CallableType):\n                            typestr = f\" {typ.accept(TypeStrVisitor(options=self.options))} \"\n                        else:\n                            typestr = \" \"\n                        item.func.deprecated = (\n                            f\"overload{typestr}of function {defn.fullname} is deprecated: \"\n                            f\"{deprecated}\"\n                        )\n\n    @staticmethod\n    def get_deprecated(expression: Expression) -> str | None:\n        if (\n            isinstance(expression, CallExpr)\n            and refers_to_fullname(expression.callee, DEPRECATED_TYPE_NAMES)\n            and (len(args := expression.args) >= 1)\n            and isinstance(deprecated := args[0], StrExpr)\n        ):\n            return deprecated.value\n        return None\n\n    def process_overload_impl(self, defn: OverloadedFuncDef) -> None:\n        \"\"\"Set flags for an overload implementation.\n\n        Currently, this checks for a trivial body in protocols classes,\n        where it makes the method implicitly abstract.\n        \"\"\"\n        if defn.impl is None:\n            return\n        impl = defn.impl if isinstance(defn.impl, FuncDef) else defn.impl.func\n        if is_trivial_body(impl.body) and self.is_class_scope() and not self.is_stub_file:\n            assert self.type is not None\n            if self.type.is_protocol:\n                impl.abstract_status = IMPLICITLY_ABSTRACT\n            if impl.abstract_status != NOT_ABSTRACT:\n                impl.is_trivial_body = True\n\n    def analyze_overload_sigs_and_impl(\n        self, defn: OverloadedFuncDef\n    ) -> tuple[list[CallableType], OverloadPart | None, list[int]]:\n        \"\"\"Find overload signatures, the implementation, and items with missing @overload.\n\n        Assume that the first was already analyzed. As a side effect:\n        analyzes remaining items and updates 'is_overload' flags.\n        \"\"\"\n        types = []\n        non_overload_indexes = []\n        impl: OverloadPart | None = None\n        for i, item in enumerate(defn.items):\n            if i != 0:\n                # Assume that the first item was already visited\n                item.is_overload = True\n                with self.overload_item_set(i if i < len(defn.items) - 1 else None):\n                    item.accept(self)\n            # TODO: support decorated overloaded functions properly\n            if isinstance(item, Decorator):\n                callable = function_type(item.func, self.function_type())\n                assert isinstance(callable, CallableType)\n                callable.definition = item\n                if not any(refers_to_fullname(dec, OVERLOAD_NAMES) for dec in item.decorators):\n                    if i == len(defn.items) - 1 and not self.is_stub_file:\n                        # Last item outside a stub is impl\n                        impl = item\n                    else:\n                        # Oops it wasn't an overload after all. A clear error\n                        # will vary based on where in the list it is, record\n                        # that.\n                        non_overload_indexes.append(i)\n                else:\n                    item.func.is_overload = True\n                    types.append(callable)\n                    if item.var.is_property:\n                        self.fail(\"An overload can not be a property\", item)\n                # If any item was decorated with `@override`, the whole overload\n                # becomes an explicit override.\n                defn.is_explicit_override |= item.func.is_explicit_override\n            elif isinstance(item, FuncDef):\n                if i == len(defn.items) - 1 and not self.is_stub_file:\n                    impl = item\n                else:\n                    non_overload_indexes.append(i)\n        return types, impl, non_overload_indexes\n\n    def handle_missing_overload_decorators(\n        self,\n        defn: OverloadedFuncDef,\n        non_overload_indexes: list[int],\n        some_overload_decorators: bool,\n    ) -> None:\n        \"\"\"Generate errors for overload items without @overload.\n\n        Side effect: remote non-overload items.\n        \"\"\"\n        if some_overload_decorators:\n            # Some of them were overloads, but not all.\n            for idx in non_overload_indexes:\n                if self.is_stub_file:\n                    self.fail(\n                        \"An implementation for an overloaded function \"\n                        \"is not allowed in a stub file\",\n                        defn.items[idx],\n                    )\n                else:\n                    self.fail(\n                        \"The implementation for an overloaded function must come last\",\n                        defn.items[idx],\n                    )\n        else:\n            for idx in non_overload_indexes[1:]:\n                self.name_already_defined(defn.name, defn.items[idx], defn.items[0])\n            if defn.impl:\n                self.name_already_defined(defn.name, defn.impl, defn.items[0])\n        # Remove the non-overloads\n        for idx in reversed(non_overload_indexes):\n            del defn.items[idx]\n\n    def handle_missing_overload_implementation(self, defn: OverloadedFuncDef) -> None:\n        \"\"\"Generate error about missing overload implementation (only if needed).\"\"\"\n        if not self.is_stub_file:\n            if self.type and self.type.is_protocol and not self.is_func_scope():\n                # An overloaded protocol method doesn't need an implementation,\n                # but if it doesn't have one, then it is considered abstract.\n                for item in defn.items:\n                    if isinstance(item, Decorator):\n                        item.func.abstract_status = IS_ABSTRACT\n                    else:\n                        item.abstract_status = IS_ABSTRACT\n            elif all(\n                isinstance(item, Decorator) and item.func.abstract_status == IS_ABSTRACT\n                for item in defn.items\n            ):\n                # Since there is no implementation, it can't be called via super().\n                if defn.items:\n                    assert isinstance(defn.items[0], Decorator)\n                    defn.items[0].func.is_trivial_body = True\n            else:\n                self.fail(\n                    \"An overloaded function outside a stub file must have an implementation\",\n                    defn,\n                    code=codes.NO_OVERLOAD_IMPL,\n                )\n\n    def process_final_in_overload(self, defn: OverloadedFuncDef) -> None:\n        \"\"\"Detect the @final status of an overloaded function (and perform checks).\"\"\"\n        # If the implementation is marked as @final (or the first overload in\n        # stubs), then the whole overloaded definition if @final.\n        if any(item.is_final for item in defn.items):\n            # We anyway mark it as final because it was probably the intention.\n            defn.is_final = True\n            # Only show the error once per overload\n            bad_final = next(ov for ov in defn.items if ov.is_final)\n            if not self.is_stub_file:\n                self.fail(\"@final should be applied only to overload implementation\", bad_final)\n            elif any(item.is_final for item in defn.items[1:]):\n                bad_final = next(ov for ov in defn.items[1:] if ov.is_final)\n                self.fail(\n                    \"In a stub file @final must be applied only to the first overload\", bad_final\n                )\n        if defn.impl is not None and defn.impl.is_final:\n            defn.is_final = True\n\n    def process_static_or_class_method_in_overload(self, defn: OverloadedFuncDef) -> None:\n        class_status = []\n        static_status = []\n        for item in defn.items:\n            if isinstance(item, Decorator):\n                inner = item.func\n            elif isinstance(item, FuncDef):\n                inner = item\n            else:\n                assert False, f\"The 'item' variable is an unexpected type: {type(item)}\"\n            class_status.append(inner.is_class)\n            static_status.append(inner.is_static)\n\n        if defn.impl is not None:\n            if isinstance(defn.impl, Decorator):\n                inner = defn.impl.func\n            elif isinstance(defn.impl, FuncDef):\n                inner = defn.impl\n            else:\n                assert False, f\"Unexpected impl type: {type(defn.impl)}\"\n            class_status.append(inner.is_class)\n            static_status.append(inner.is_static)\n\n        if len(set(class_status)) != 1:\n            self.msg.overload_inconsistently_applies_decorator(\"classmethod\", defn)\n        elif len(set(static_status)) != 1:\n            self.msg.overload_inconsistently_applies_decorator(\"staticmethod\", defn)\n        else:\n            defn.is_class = class_status[0]\n            defn.is_static = static_status[0]\n\n    def analyze_property_with_multi_part_definition(\n        self, defn: OverloadedFuncDef\n    ) -> CallableType | None:\n        \"\"\"Analyze a property defined using multiple methods (e.g., using @x.setter).\n\n        Assume that the first method (@property) has already been analyzed.\n        Return bare setter type (without any other decorators applied), this may be used\n        by the caller for performance optimizations.\n        \"\"\"\n        defn.is_property = True\n        items = defn.items\n        first_item = defn.items[0]\n        assert isinstance(first_item, Decorator)\n        deleted_items = []\n        bare_setter_type = None\n        func_name = first_item.func.name\n        for i, item in enumerate(items[1:]):\n            if isinstance(item, Decorator):\n                item.func.accept(self)\n                if item.decorators:\n                    first_node = item.decorators[0]\n                    if self._is_valid_property_decorator(first_node, func_name):\n                        # Get abstractness from the original definition.\n                        item.func.abstract_status = first_item.func.abstract_status\n                        if first_node.name == \"setter\":\n                            # The first item represents the entire property.\n                            first_item.var.is_settable_property = True\n                            setter_func_type = function_type(item.func, self.function_type())\n                            assert isinstance(setter_func_type, CallableType)\n                            bare_setter_type = setter_func_type\n                            defn.setter_index = i + 1\n                        for other_node in item.decorators[1:]:\n                            other_node.accept(self)\n                    else:\n                        self.fail(\n                            f'Only supported top decorators are \"@{func_name}.setter\" and \"@{func_name}.deleter\"',\n                            first_node,\n                        )\n            else:\n                self.fail(f'Unexpected definition for property \"{func_name}\"', item)\n                deleted_items.append(i + 1)\n        for i in reversed(deleted_items):\n            del items[i]\n\n        for item in items[1:]:\n            if isinstance(item, Decorator):\n                for d in item.decorators:\n                    if (deprecated := self.get_deprecated(d)) is not None:\n                        item.func.deprecated = (\n                            f\"function {item.fullname} is deprecated: {deprecated}\"\n                        )\n        return bare_setter_type\n\n    def _is_valid_property_decorator(\n        self, deco: Expression, property_name: str\n    ) -> TypeGuard[MemberExpr]:\n        if not isinstance(deco, MemberExpr):\n            return False\n        if not isinstance(deco.expr, NameExpr) or deco.expr.name != property_name:\n            return False\n        if deco.name not in {\"setter\", \"deleter\"}:\n            # This intentionally excludes getter. While `@prop.getter` is valid at\n            # runtime, that would mean replacing the already processed getter type.\n            # Such usage is almost definitely a mistake (except for overrides in\n            # subclasses but we don't support them anyway) and might be a typo\n            # (only one letter away from `setter`), it's likely almost never used,\n            # so supporting it properly won't pay off.\n            return False\n        return True\n\n    def add_function_to_symbol_table(self, func: FuncDef | OverloadedFuncDef) -> None:\n        if self.is_class_scope():\n            assert self.type is not None\n            func.info = self.type\n        func._fullname = self.qualified_name(func.name)\n        self.add_symbol(func.name, func, func)\n\n    def analyze_arg_initializers(self, defn: FuncItem) -> None:\n        fullname = self.function_fullname(defn.fullname)\n        with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)):\n            # Analyze default arguments\n            for arg in defn.arguments:\n                if arg.initializer:\n                    arg.initializer.accept(self)\n\n    def analyze_function_body(self, defn: FuncItem) -> None:\n        is_method = self.is_class_scope()\n        fullname = self.function_fullname(defn.fullname)\n        with self.tvar_scope_frame(self.tvar_scope.method_frame(fullname)):\n            # Bind the type variables again to visit the body.\n            if defn.type:\n                a = self.type_analyzer()\n                typ = defn.type\n                assert isinstance(typ, CallableType)\n                a.bind_function_type_variables(typ, defn)\n                for i in range(len(typ.arg_types)):\n                    store_argument_type(defn, i, typ, self.named_type)\n            self.function_stack.append(defn)\n            with self.enter(defn):\n                for arg in defn.arguments:\n                    self.add_local(arg.variable, defn)\n\n                # The first argument of a non-static, non-class method is like 'self'\n                # (though the name could be different), having the enclosing class's\n                # instance type.\n                if is_method and defn.has_self_or_cls_argument and defn.arguments:\n                    if not defn.is_class:\n                        defn.arguments[0].variable.is_self = True\n                    else:\n                        defn.arguments[0].variable.is_cls = True\n\n                defn.body.accept(self)\n            self.function_stack.pop()\n\n    def check_classvar_in_signature(self, typ: ProperType) -> None:\n        t: ProperType\n        if isinstance(typ, Overloaded):\n            for t in typ.items:\n                self.check_classvar_in_signature(t)\n            return\n        if not isinstance(typ, CallableType):\n            return\n        for t in get_proper_types(typ.arg_types) + [get_proper_type(typ.ret_type)]:\n            if self.is_classvar(t):\n                self.fail_invalid_classvar(t)\n                # Show only one error per signature\n                break\n\n    def check_function_signature(self, fdef: FuncItem) -> None:\n        sig = fdef.type\n        assert isinstance(sig, CallableType)\n        if len(sig.arg_types) < len(fdef.arguments):\n            self.fail(\"Type signature has too few arguments\", fdef)\n            # Add dummy Any arguments to prevent crashes later.\n            num_extra_anys = len(fdef.arguments) - len(sig.arg_types)\n            extra_anys = [AnyType(TypeOfAny.from_error)] * num_extra_anys\n            sig.arg_types.extend(extra_anys)\n        elif len(sig.arg_types) > len(fdef.arguments):\n            self.fail(\"Type signature has too many arguments\", fdef, blocker=True)\n\n    def visit_decorator(self, dec: Decorator) -> None:\n        self.statement = dec\n        # TODO: better don't modify them at all.\n        dec.decorators = dec.original_decorators.copy()\n        dec.func.is_conditional = self.block_depth[-1] > 0\n        if not dec.is_overload:\n            self.add_symbol(dec.name, dec, dec)\n        dec.func._fullname = self.qualified_name(dec.name)\n        dec.var._fullname = self.qualified_name(dec.name)\n        for d in dec.decorators:\n            d.accept(self)\n        removed: list[int] = []\n        no_type_check = False\n        could_be_decorated_property = False\n        for i, d in enumerate(dec.decorators):\n            # A bunch of decorators are special cased here.\n            if refers_to_fullname(d, \"abc.abstractmethod\"):\n                removed.append(i)\n                dec.func.abstract_status = IS_ABSTRACT\n                self.check_decorated_function_is_method(\"abstractmethod\", dec)\n            elif refers_to_fullname(d, (\"asyncio.coroutines.coroutine\", \"types.coroutine\")):\n                removed.append(i)\n                dec.func.is_awaitable_coroutine = True\n            elif refers_to_fullname(d, \"builtins.staticmethod\"):\n                removed.append(i)\n                dec.func.is_static = True\n                dec.var.is_staticmethod = True\n                self.check_decorated_function_is_method(\"staticmethod\", dec)\n            elif refers_to_fullname(d, \"builtins.classmethod\"):\n                removed.append(i)\n                dec.func.is_class = True\n                dec.var.is_classmethod = True\n                self.check_decorated_function_is_method(\"classmethod\", dec)\n            elif refers_to_fullname(d, OVERRIDE_DECORATOR_NAMES):\n                removed.append(i)\n                dec.func.is_explicit_override = True\n                self.check_decorated_function_is_method(\"override\", dec)\n            elif refers_to_fullname(\n                d,\n                (\n                    \"builtins.property\",\n                    \"abc.abstractproperty\",\n                    \"functools.cached_property\",\n                    \"enum.property\",\n                    \"types.DynamicClassAttribute\",\n                ),\n            ):\n                removed.append(i)\n                dec.func.is_property = True\n                dec.var.is_property = True\n                if refers_to_fullname(d, \"abc.abstractproperty\"):\n                    dec.func.abstract_status = IS_ABSTRACT\n                elif refers_to_fullname(d, \"functools.cached_property\"):\n                    dec.var.is_settable_property = True\n                self.check_decorated_function_is_method(\"property\", dec)\n            elif refers_to_fullname(d, \"typing.no_type_check\"):\n                dec.var.type = AnyType(TypeOfAny.special_form)\n                no_type_check = True\n            elif refers_to_fullname(d, FINAL_DECORATOR_NAMES):\n                if self.is_class_scope():\n                    assert self.type is not None, \"No type set at class scope\"\n                    if self.type.is_protocol:\n                        self.msg.protocol_members_cant_be_final(d)\n                    else:\n                        dec.func.is_final = True\n                        dec.var.is_final = True\n                    removed.append(i)\n                else:\n                    self.fail(\"@final cannot be used with non-method functions\", d)\n            elif refers_to_fullname(d, TYPE_CHECK_ONLY_NAMES):\n                # TODO: support `@overload` funcs.\n                dec.func.is_type_check_only = True\n            elif isinstance(d, CallExpr) and refers_to_fullname(\n                d.callee, DATACLASS_TRANSFORM_NAMES\n            ):\n                dec.func.dataclass_transform_spec = self.parse_dataclass_transform_spec(d)\n            elif (deprecated := self.get_deprecated(d)) is not None:\n                dec.func.deprecated = f\"function {dec.fullname} is deprecated: {deprecated}\"\n            elif not dec.var.is_property:\n                # We have seen a \"non-trivial\" decorator before seeing @property, if\n                # we will see a @property later, give an error, as we don't support this.\n                could_be_decorated_property = True\n        for i in reversed(removed):\n            del dec.decorators[i]\n        if (not dec.is_overload or dec.var.is_property) and self.type:\n            dec.var.info = self.type\n            dec.var.is_initialized_in_class = True\n        if no_type_check:\n            erase_func_annotations(dec.func)\n        if not no_type_check and (self.recurse_into_functions or dec.func.def_or_infer_vars):\n            with self.set_recurse_into_functions():\n                dec.func.accept(self)\n        if could_be_decorated_property and dec.decorators and dec.var.is_property:\n            self.fail(\n                \"Decorators on top of @property are not supported\", dec, code=PROPERTY_DECORATOR\n            )\n        if (dec.func.is_static or dec.func.is_class) and dec.var.is_property:\n            self.fail(\"Only instance methods can be decorated with @property\", dec)\n        if dec.func.abstract_status == IS_ABSTRACT and dec.func.is_final:\n            self.fail(f\"Method {dec.func.name} is both abstract and final\", dec)\n        if dec.func.is_static and dec.func.is_class:\n            self.fail(message_registry.CLASS_PATTERN_CLASS_OR_STATIC_METHOD, dec)\n\n    def check_decorated_function_is_method(self, decorator: str, context: Context) -> None:\n        if not self.type or self.is_func_scope():\n            self.fail(f'\"{decorator}\" used with a non-method', context)\n\n    #\n    # Classes\n    #\n\n    def visit_class_def(self, defn: ClassDef) -> None:\n        self.statement = defn\n        self.incomplete_type_stack.append(not defn.info)\n        namespace = self.qualified_name(defn.name)\n        with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)):\n            if self.push_type_args(defn.type_args, defn) is None:\n                self.mark_incomplete(defn.name, defn)\n                return\n\n            self.analyze_class(defn)\n            self.pop_type_args(defn.type_args)\n        self.incomplete_type_stack.pop()\n\n    def push_type_args(\n        self, type_args: list[TypeParam] | None, context: Context\n    ) -> list[tuple[str, TypeVarLikeExpr]] | None:\n        if not type_args:\n            return []\n        self.locals.append(SymbolTable())\n        self.scope_stack.append(SCOPE_ANNOTATION)\n        tvs: list[tuple[str, TypeVarLikeExpr]] = []\n        for p in type_args:\n            tv = self.analyze_type_param(p, context)\n            if tv is None:\n                return None\n            tvs.append((p.name, tv))\n\n            if self.is_defined_type_param(p.name):\n                self.fail(f'\"{p.name}\" already defined as a type parameter', context)\n            else:\n                assert self.add_symbol(\n                    p.name, tv, context, no_progress=True, type_param=True\n                ), \"Type parameter should not be discarded\"\n\n        return tvs\n\n    def is_defined_type_param(self, name: str) -> bool:\n        for names in self.locals:\n            if names is None:\n                continue\n            if name in names:\n                node = names[name].node\n                if isinstance(node, TypeVarLikeExpr):\n                    return True\n        return False\n\n    def analyze_type_param(\n        self, type_param: TypeParam, context: Context\n    ) -> TypeVarLikeExpr | None:\n        fullname = self.qualified_name(type_param.name)\n        if type_param.upper_bound:\n            upper_bound = self.anal_type(type_param.upper_bound, allow_placeholder=True)\n            # TODO: we should validate the upper bound is valid for a given kind.\n            if upper_bound is None:\n                # This and below copies special-casing for old-style type variables, that\n                # is equally necessary for new-style classes to break a vicious circle.\n                upper_bound = PlaceholderType(None, [], context.line)\n        else:\n            if type_param.kind == TYPE_VAR_TUPLE_KIND:\n                upper_bound = self.named_type(\"builtins.tuple\", [self.object_type()])\n            else:\n                upper_bound = self.object_type()\n        if type_param.default:\n            default = self.anal_type(\n                type_param.default,\n                allow_placeholder=True,\n                allow_unbound_tvars=True,\n                report_invalid_types=False,\n                allow_param_spec_literals=type_param.kind == PARAM_SPEC_KIND,\n                allow_tuple_literal=type_param.kind == PARAM_SPEC_KIND,\n                allow_unpack=type_param.kind == TYPE_VAR_TUPLE_KIND,\n            )\n            if default is None:\n                default = PlaceholderType(None, [], context.line)\n            elif type_param.kind == TYPE_VAR_KIND:\n                default = self.check_typevar_default(default, type_param.default)\n            elif type_param.kind == PARAM_SPEC_KIND:\n                default = self.check_paramspec_default(default, type_param.default)\n            elif type_param.kind == TYPE_VAR_TUPLE_KIND:\n                default = self.check_typevartuple_default(default, type_param.default)\n        else:\n            default = AnyType(TypeOfAny.from_omitted_generics)\n        if type_param.kind == TYPE_VAR_KIND:\n            values: list[Type] = []\n            if type_param.values:\n                for value in type_param.values:\n                    analyzed = self.anal_type(value, allow_placeholder=True)\n                    if analyzed is None:\n                        analyzed = PlaceholderType(None, [], context.line)\n                    if has_type_vars(analyzed):\n                        self.fail(message_registry.TYPE_VAR_GENERIC_CONSTRAINT_TYPE, context)\n                        values.append(AnyType(TypeOfAny.from_error))\n                    else:\n                        values.append(analyzed)\n            return TypeVarExpr(\n                name=type_param.name,\n                fullname=fullname,\n                values=values,\n                upper_bound=upper_bound,\n                default=default,\n                variance=VARIANCE_NOT_READY,\n                is_new_style=True,\n                line=context.line,\n            )\n        elif type_param.kind == PARAM_SPEC_KIND:\n            return ParamSpecExpr(\n                name=type_param.name,\n                fullname=fullname,\n                upper_bound=upper_bound,\n                default=default,\n                is_new_style=True,\n                line=context.line,\n            )\n        else:\n            assert type_param.kind == TYPE_VAR_TUPLE_KIND\n            tuple_fallback = self.named_type(\"builtins.tuple\", [self.object_type()])\n            return TypeVarTupleExpr(\n                name=type_param.name,\n                fullname=fullname,\n                upper_bound=upper_bound,\n                tuple_fallback=tuple_fallback,\n                default=default,\n                is_new_style=True,\n                line=context.line,\n            )\n\n    def pop_type_args(self, type_args: list[TypeParam] | None) -> None:\n        if not type_args:\n            return\n        self.locals.pop()\n        self.scope_stack.pop()\n\n    def analyze_class(self, defn: ClassDef) -> None:\n        fullname = self.qualified_name(defn.name)\n        if not defn.info and not self.is_core_builtin_class(defn):\n            # Add placeholder so that self-references in base classes can be\n            # resolved.  We don't want this to cause a deferral, since if there\n            # are no incomplete references, we'll replace this with a TypeInfo\n            # before returning.\n            placeholder = PlaceholderNode(fullname, defn, defn.line, becomes_typeinfo=True)\n            self.add_symbol(defn.name, placeholder, defn, can_defer=False)\n\n        tag = self.track_incomplete_refs()\n\n        # Restore base classes after previous iteration (things like Generic[T] might be removed).\n        defn.base_type_exprs.extend(defn.removed_base_type_exprs)\n        defn.removed_base_type_exprs.clear()\n\n        self.infer_metaclass_and_bases_from_compat_helpers(defn)\n\n        bases = defn.base_type_exprs\n        bases, tvar_defs, is_protocol = self.clean_up_bases_and_infer_type_variables(\n            defn, bases, context=defn\n        )\n\n        self.check_type_alias_bases(bases)\n\n        for tvd in tvar_defs:\n            if isinstance(tvd, TypeVarType) and any(\n                has_placeholder(t) for t in [tvd.upper_bound] + tvd.values\n            ):\n                # Some type variable bounds or values are not ready, we need\n                # to re-analyze this class.\n                self.defer()\n            if has_placeholder(tvd.default):\n                # Placeholder values in TypeVarLikeTypes may get substituted in.\n                # Defer current target until they are ready.\n                self.mark_incomplete(defn.name, defn)\n                return\n\n        self.analyze_class_keywords(defn)\n        bases_result = self.analyze_base_classes(bases)\n        if bases_result is None or self.found_incomplete_ref(tag):\n            # Something was incomplete. Defer current target.\n            self.mark_incomplete(defn.name, defn)\n            return\n\n        base_types, base_error = bases_result\n        if any(isinstance(base, PlaceholderType) for base, _ in base_types):\n            # We need to know the TypeInfo of each base to construct the MRO. Placeholder types\n            # are okay in nested positions, since they can't affect the MRO.\n            self.mark_incomplete(defn.name, defn)\n            return\n\n        declared_metaclass, should_defer, any_meta = self.get_declared_metaclass(\n            defn.name, defn.metaclass\n        )\n        if should_defer or self.found_incomplete_ref(tag):\n            # Metaclass was not ready. Defer current target.\n            self.mark_incomplete(defn.name, defn)\n            return\n\n        if self.analyze_typeddict_classdef(defn):\n            if defn.info:\n                self.setup_type_vars(defn, tvar_defs)\n                self.setup_alias_type_vars(defn)\n            return\n\n        if self.analyze_namedtuple_classdef(defn, tvar_defs):\n            return\n\n        # Create TypeInfo for class now that base classes and the MRO can be calculated.\n        self.prepare_class_def(defn)\n        self.setup_type_vars(defn, tvar_defs)\n        if base_error:\n            defn.info.fallback_to_any = True\n        if any_meta:\n            defn.info.meta_fallback_to_any = True\n\n        with self.scope.class_scope(defn.info):\n            self.configure_base_classes(defn, base_types)\n            defn.info.is_protocol = is_protocol\n            self.recalculate_metaclass(defn, declared_metaclass)\n            defn.info.runtime_protocol = False\n\n            if defn.type_args:\n                # PEP 695 type parameters are not in scope in class decorators, so\n                # temporarily disable type parameter namespace.\n                type_params_names = self.locals.pop()\n                self.scope_stack.pop()\n            for decorator in defn.decorators:\n                self.analyze_class_decorator(defn, decorator)\n            if defn.type_args:\n                self.locals.append(type_params_names)\n                self.scope_stack.append(SCOPE_ANNOTATION)\n\n            self.analyze_class_body_common(defn)\n\n    def check_type_alias_bases(self, bases: list[Expression]) -> None:\n        for base in bases:\n            if isinstance(base, IndexExpr):\n                base = base.base\n            if (\n                isinstance(base, RefExpr)\n                and isinstance(base.node, TypeAlias)\n                and base.node.python_3_12_type_alias\n            ):\n                self.fail(\n                    'Type alias defined using \"type\" statement not valid as base class', base\n                )\n\n    def setup_type_vars(self, defn: ClassDef, tvar_defs: list[TypeVarLikeType]) -> None:\n        defn.type_vars = tvar_defs\n        defn.info.type_vars = []\n        # we want to make sure any additional logic in add_type_vars gets run\n        defn.info.add_type_vars()\n\n    def setup_alias_type_vars(self, defn: ClassDef) -> None:\n        assert defn.info.special_alias is not None\n        defn.info.special_alias.alias_tvars = list(defn.type_vars)\n        # It is a bit unfortunate that we need to inline some logic from TypeAlias constructor,\n        # but it is required, since type variables may change during semantic analyzer passes.\n        for i, t in enumerate(defn.type_vars):\n            if isinstance(t, TypeVarTupleType):\n                defn.info.special_alias.tvar_tuple_index = i\n        target = defn.info.special_alias.target\n        assert isinstance(target, ProperType)\n        if isinstance(target, TypedDictType):\n            target.fallback.args = type_vars_as_args(defn.type_vars)\n        elif isinstance(target, TupleType):\n            target.partial_fallback.args = type_vars_as_args(defn.type_vars)\n        else:\n            assert False, f\"Unexpected special alias type: {type(target)}\"\n\n    def is_core_builtin_class(self, defn: ClassDef) -> bool:\n        return self.cur_mod_id == \"builtins\" and defn.name in CORE_BUILTIN_CLASSES\n\n    def analyze_class_body_common(self, defn: ClassDef) -> None:\n        \"\"\"Parts of class body analysis that are common to all kinds of class defs.\"\"\"\n        self.enter_class(defn.info)\n        if any(b.self_type is not None for b in defn.info.mro):\n            self.setup_self_type()\n        defn.defs.accept(self)\n        self.apply_class_plugin_hooks(defn)\n        self.leave_class()\n\n    def analyze_typeddict_classdef(self, defn: ClassDef) -> bool:\n        if (\n            defn.info\n            and defn.info.typeddict_type\n            and not has_placeholder(defn.info.typeddict_type)\n        ):\n            # This is a valid TypedDict, and it is fully analyzed.\n            return True\n        is_typeddict, info = self.typed_dict_analyzer.analyze_typeddict_classdef(defn)\n        if is_typeddict:\n            for decorator in defn.decorators:\n                decorator.accept(self)\n                if info is not None:\n                    self.analyze_class_decorator_common(defn, info, decorator)\n            if info is None:\n                self.mark_incomplete(defn.name, defn)\n            else:\n                self.prepare_class_def(defn, info, custom_names=True)\n            return True\n        return False\n\n    def analyze_namedtuple_classdef(\n        self, defn: ClassDef, tvar_defs: list[TypeVarLikeType]\n    ) -> bool:\n        \"\"\"Check if this class can define a named tuple.\"\"\"\n        if (\n            defn.info\n            and defn.info.is_named_tuple\n            and defn.info.tuple_type\n            and not has_placeholder(defn.info.tuple_type)\n        ):\n            # Don't reprocess everything. We just need to process methods defined\n            # in the named tuple class body.\n            is_named_tuple = True\n            info: TypeInfo | None = defn.info\n        else:\n            is_named_tuple, info = self.named_tuple_analyzer.analyze_namedtuple_classdef(\n                defn, self.is_stub_file, self.is_func_scope()\n            )\n        if is_named_tuple:\n            if info is None:\n                self.mark_incomplete(defn.name, defn)\n            else:\n                self.prepare_class_def(defn, info, custom_names=True)\n                self.setup_type_vars(defn, tvar_defs)\n                self.setup_alias_type_vars(defn)\n                with self.scope.class_scope(defn.info):\n                    for deco in defn.decorators:\n                        deco.accept(self)\n                        self.analyze_class_decorator_common(defn, defn.info, deco)\n                    with self.named_tuple_analyzer.save_namedtuple_body(info):\n                        self.analyze_class_body_common(defn)\n            return True\n        return False\n\n    def apply_class_plugin_hooks(self, defn: ClassDef) -> None:\n        \"\"\"Apply a plugin hook that may infer a more precise definition for a class.\"\"\"\n\n        for decorator in defn.decorators:\n            decorator_name = self.get_fullname_for_hook(decorator)\n            if decorator_name:\n                hook = self.plugin.get_class_decorator_hook(decorator_name)\n                # Special case: if the decorator is itself decorated with\n                # typing.dataclass_transform, apply the hook for the dataclasses plugin\n                # TODO: remove special casing here\n                if hook is None and find_dataclass_transform_spec(decorator):\n                    hook = dataclasses_plugin.dataclass_tag_callback\n                if hook:\n                    hook(ClassDefContext(defn, decorator, self))\n\n        if defn.metaclass:\n            metaclass_name = self.get_fullname_for_hook(defn.metaclass)\n            if metaclass_name:\n                hook = self.plugin.get_metaclass_hook(metaclass_name)\n                if hook:\n                    hook(ClassDefContext(defn, defn.metaclass, self))\n\n        for base_expr in defn.base_type_exprs:\n            base_name = self.get_fullname_for_hook(base_expr)\n            if base_name:\n                hook = self.plugin.get_base_class_hook(base_name)\n                if hook:\n                    hook(ClassDefContext(defn, base_expr, self))\n\n        # Check if the class definition itself triggers a dataclass transform (via a parent class/\n        # metaclass)\n        spec = find_dataclass_transform_spec(defn)\n        if spec is not None:\n            dataclasses_plugin.add_dataclass_tag(defn.info)\n\n    def get_fullname_for_hook(self, expr: Expression) -> str | None:\n        if isinstance(expr, CallExpr):\n            return self.get_fullname_for_hook(expr.callee)\n        elif isinstance(expr, IndexExpr):\n            return self.get_fullname_for_hook(expr.base)\n        elif isinstance(expr, RefExpr):\n            if expr.fullname:\n                return expr.fullname\n            # If we don't have a fullname look it up. This happens because base classes are\n            # analyzed in a different manner (see exprtotype.py) and therefore those AST\n            # nodes will not have full names.\n            sym = self.lookup_type_node(expr)\n            if sym:\n                return sym.fullname\n        return None\n\n    def analyze_class_keywords(self, defn: ClassDef) -> None:\n        for value in defn.keywords.values():\n            value.accept(self)\n\n    def enter_class(self, info: TypeInfo) -> None:\n        # Remember previous active class\n        self.type_stack.append(self.type)\n        self.locals.append(None)  # Add class scope\n        self.scope_stack.append(SCOPE_CLASS)\n        self.block_depth.append(-1)  # The class body increments this to 0\n        self.loop_depth.append(0)\n        self._type = info\n        self.missing_names.append(set())\n\n    def leave_class(self) -> None:\n        \"\"\"Restore analyzer state.\"\"\"\n        self.block_depth.pop()\n        self.loop_depth.pop()\n        self.locals.pop()\n        self.scope_stack.pop()\n        self._type = self.type_stack.pop()\n        self.missing_names.pop()\n\n    def analyze_class_decorator(self, defn: ClassDef, decorator: Expression) -> None:\n        decorator.accept(self)\n        self.analyze_class_decorator_common(defn, defn.info, decorator)\n        if isinstance(decorator, RefExpr):\n            if decorator.fullname in RUNTIME_PROTOCOL_DECOS:\n                if defn.info.is_protocol:\n                    defn.info.runtime_protocol = True\n                else:\n                    self.fail(\"@runtime_checkable can only be used with protocol classes\", defn)\n        elif isinstance(decorator, CallExpr) and refers_to_fullname(\n            decorator.callee, DATACLASS_TRANSFORM_NAMES\n        ):\n            defn.info.dataclass_transform_spec = self.parse_dataclass_transform_spec(decorator)\n\n    def analyze_class_decorator_common(\n        self, defn: ClassDef, info: TypeInfo, decorator: Expression\n    ) -> None:\n        \"\"\"Common method for applying class decorators.\n\n        Called on regular classes, typeddicts, and namedtuples.\n        \"\"\"\n        if refers_to_fullname(decorator, FINAL_DECORATOR_NAMES):\n            info.is_final = True\n        elif refers_to_fullname(decorator, DISJOINT_BASE_DECORATOR_NAMES):\n            if info.is_protocol:\n                self.fail(\"@disjoint_base cannot be used with protocol class\", decorator)\n            elif info.typeddict_type is not None:\n                self.fail(\"@disjoint_base cannot be used with TypedDict\", decorator)\n            else:\n                info.is_disjoint_base = True\n        elif refers_to_fullname(decorator, TYPE_CHECK_ONLY_NAMES):\n            info.is_type_check_only = True\n        elif (deprecated := self.get_deprecated(decorator)) is not None:\n            info.deprecated = f\"class {defn.fullname} is deprecated: {deprecated}\"\n\n    def clean_up_bases_and_infer_type_variables(\n        self, defn: ClassDef, base_type_exprs: list[Expression], context: Context\n    ) -> tuple[list[Expression], list[TypeVarLikeType], bool]:\n        \"\"\"Remove extra base classes such as Generic and infer type vars.\n\n        For example, consider this class:\n\n          class Foo(Bar, Generic[T]): ...\n\n        Now we will remove Generic[T] from bases of Foo and infer that the\n        type variable 'T' is a type argument of Foo.\n\n        Note that this is performed *before* semantic analysis.\n\n        Returns (remaining base expressions, inferred type variables, is protocol).\n        \"\"\"\n        removed: list[int] = []\n        declared_tvars: TypeVarLikeList = []\n        is_protocol = False\n        has_type_var_tuple = False\n        if defn.type_args is not None:\n            for p in defn.type_args:\n                node = self.lookup(p.name, context)\n                assert node is not None\n                assert isinstance(node.node, TypeVarLikeExpr)\n                if isinstance(node.node, TypeVarTupleExpr):\n                    if has_type_var_tuple:\n                        self.fail(\"Can only use one type var tuple in a class def\", context)\n                        continue\n                    has_type_var_tuple = True\n                declared_tvars.append((p.name, node.node))\n\n        for i, base_expr in enumerate(base_type_exprs):\n            if isinstance(base_expr, StarExpr):\n                base_expr.valid = True\n            self.analyze_type_expr(base_expr)\n\n            try:\n                base = self.expr_to_unanalyzed_type(base_expr)\n            except TypeTranslationError:\n                # This error will be caught later.\n                continue\n            result = self.analyze_class_typevar_declaration(base, has_type_var_tuple)\n            if result is not None:\n                tvars = result[0]\n                is_protocol |= result[1]\n                if declared_tvars:\n                    if defn.type_args:\n                        if is_protocol:\n                            self.fail('No arguments expected for \"Protocol\" base class', context)\n                        else:\n                            self.fail(\"Generic[...] base class is redundant\", context)\n                    else:\n                        self.fail(\n                            \"Only single Generic[...] or Protocol[...] can be in bases\", context\n                        )\n                removed.append(i)\n                declared_tvars.extend(tvars)\n            if isinstance(base, UnboundType):\n                sym = self.lookup_qualified(base.name, base)\n                if sym is not None and sym.node is not None:\n                    if sym.node.fullname in PROTOCOL_NAMES and i not in removed:\n                        # also remove bare 'Protocol' bases\n                        removed.append(i)\n                        is_protocol = True\n\n        all_tvars = self.get_all_bases_tvars(base_type_exprs, removed)\n        if declared_tvars:\n            if len(remove_dups(declared_tvars)) < len(declared_tvars) and not defn.type_args:\n                self.fail(\"Duplicate type variables in Generic[...] or Protocol[...]\", context)\n            declared_tvars = remove_dups(declared_tvars)\n            if not set(all_tvars).issubset(set(declared_tvars)):\n                if defn.type_args:\n                    undeclared = sorted(set(all_tvars) - set(declared_tvars))\n                    self.msg.type_parameters_should_be_declared(\n                        [tv[0] for tv in undeclared], context\n                    )\n                else:\n                    self.fail(\n                        \"If Generic[...] or Protocol[...] is present\"\n                        \" it should list all type variables\",\n                        context,\n                    )\n                # In case of error, Generic tvars will go first\n                declared_tvars = remove_dups(declared_tvars + all_tvars)\n        else:\n            declared_tvars = all_tvars\n        for i in reversed(removed):\n            # We need to actually remove the base class expressions like Generic[T],\n            # mostly because otherwise they will create spurious dependencies in fine\n            # grained incremental mode.\n            defn.removed_base_type_exprs.append(defn.base_type_exprs[i])\n            del base_type_exprs[i]\n        tvar_defs = self.tvar_defs_from_tvars(declared_tvars, context)\n        return base_type_exprs, tvar_defs, is_protocol\n\n    def analyze_class_typevar_declaration(\n        self, base: Type, has_type_var_tuple: bool\n    ) -> tuple[TypeVarLikeList, bool] | None:\n        \"\"\"Analyze type variables declared using Generic[...] or Protocol[...].\n\n        Args:\n            base: Non-analyzed base class\n\n        Return None if the base class does not declare type variables. Otherwise,\n        return the type variables.\n        \"\"\"\n        if not isinstance(base, UnboundType):\n            return None\n        unbound = base\n        sym = self.lookup_qualified(unbound.name, unbound)\n        if sym is None or sym.node is None:\n            return None\n        if (\n            sym.node.fullname == \"typing.Generic\"\n            or sym.node.fullname in PROTOCOL_NAMES\n            and base.args\n        ):\n            is_proto = sym.node.fullname != \"typing.Generic\"\n            tvars: TypeVarLikeList = []\n            for arg in unbound.args:\n                tag = self.track_incomplete_refs()\n                tvar = self.analyze_unbound_tvar(arg)\n                if tvar:\n                    if isinstance(tvar[1], TypeVarTupleExpr):\n                        if has_type_var_tuple:\n                            self.fail(\"Can only use one type var tuple in a class def\", base)\n                            continue\n                        has_type_var_tuple = True\n                    tvars.append(tvar)\n                elif not self.found_incomplete_ref(tag):\n                    self.fail(\"Free type variable expected in %s[...]\" % sym.node.name, base)\n            return tvars, is_proto\n        return None\n\n    def analyze_unbound_tvar(self, t: Type) -> tuple[str, TypeVarLikeExpr] | None:\n        if isinstance(t, UnpackType) and isinstance(t.type, UnboundType):\n            return self.analyze_unbound_tvar_impl(t.type, is_unpacked=True)\n        if isinstance(t, UnboundType):\n            sym = self.lookup_qualified(t.name, t)\n            if sym and sym.fullname in UNPACK_TYPE_NAMES:\n                inner_t = t.args[0]\n                if isinstance(inner_t, UnboundType):\n                    return self.analyze_unbound_tvar_impl(inner_t, is_unpacked=True)\n                return None\n            return self.analyze_unbound_tvar_impl(t)\n        return None\n\n    def analyze_unbound_tvar_impl(\n        self, t: UnboundType, is_unpacked: bool = False, is_typealias_param: bool = False\n    ) -> tuple[str, TypeVarLikeExpr] | None:\n        assert not is_unpacked or not is_typealias_param, \"Mutually exclusive conditions\"\n        sym = self.lookup_qualified(t.name, t)\n        if sym and isinstance(sym.node, PlaceholderNode):\n            self.record_incomplete_ref()\n        if not is_unpacked and sym and isinstance(sym.node, ParamSpecExpr):\n            if sym.fullname and not self.tvar_scope.allow_binding(sym.fullname):\n                # It's bound by our type variable scope\n                return None\n            return t.name, sym.node\n        if (is_unpacked or is_typealias_param) and sym and isinstance(sym.node, TypeVarTupleExpr):\n            if sym.fullname and not self.tvar_scope.allow_binding(sym.fullname):\n                # It's bound by our type variable scope\n                return None\n            return t.name, sym.node\n        if sym is None or not isinstance(sym.node, TypeVarExpr) or is_unpacked:\n            return None\n        elif sym.fullname and not self.tvar_scope.allow_binding(sym.fullname):\n            # It's bound by our type variable scope\n            return None\n        else:\n            assert isinstance(sym.node, TypeVarExpr)\n            return t.name, sym.node\n\n    def find_type_var_likes(self, t: Type) -> TypeVarLikeList:\n        visitor = FindTypeVarVisitor(self, self.tvar_scope)\n        t.accept(visitor)\n        return visitor.type_var_likes\n\n    def get_all_bases_tvars(\n        self, base_type_exprs: list[Expression], removed: list[int]\n    ) -> TypeVarLikeList:\n        \"\"\"Return all type variable references in bases.\"\"\"\n        tvars: TypeVarLikeList = []\n        for i, base_expr in enumerate(base_type_exprs):\n            if i not in removed:\n                try:\n                    base = self.expr_to_unanalyzed_type(base_expr)\n                except TypeTranslationError:\n                    # This error will be caught later.\n                    continue\n                base_tvars = self.find_type_var_likes(base)\n                tvars.extend(base_tvars)\n        return remove_dups(tvars)\n\n    def tvar_defs_from_tvars(\n        self, tvars: TypeVarLikeList, context: Context\n    ) -> list[TypeVarLikeType]:\n        tvar_defs: list[TypeVarLikeType] = []\n        last_tvar_name_with_default: str | None = None\n        for name, tvar_expr in tvars:\n            tvar_expr.default = tvar_expr.default.accept(\n                TypeVarDefaultTranslator(self, tvar_expr.name, context)\n            )\n            # PEP-695 type variables that are redeclared in an inner scope are warned\n            # about elsewhere.\n            if not tvar_expr.is_new_style and not self.tvar_scope.allow_binding(\n                tvar_expr.fullname\n            ):\n                self.fail(\n                    message_registry.TYPE_VAR_REDECLARED_IN_NESTED_CLASS.format(name), context\n                )\n            tvar_def = self.tvar_scope.bind_new(name, tvar_expr, self.fail, context)\n            if last_tvar_name_with_default is not None and not tvar_def.has_default():\n                self.msg.tvar_without_default_type(\n                    tvar_def.name, last_tvar_name_with_default, context\n                )\n                tvar_def.default = AnyType(TypeOfAny.from_error)\n            elif tvar_def.has_default():\n                last_tvar_name_with_default = tvar_def.name\n            tvar_defs.append(tvar_def)\n        return tvar_defs\n\n    def get_and_bind_all_tvars(self, type_exprs: list[Expression]) -> list[TypeVarLikeType]:\n        \"\"\"Return all type variable references in item type expressions.\n\n        This is a helper for generic TypedDicts and NamedTuples. Essentially it is\n        a simplified version of the logic we use for ClassDef bases. We duplicate\n        some amount of code, because it is hard to refactor common pieces.\n        \"\"\"\n        tvars: dict[str, tuple[TypeVarLikeExpr, Expression]] = {}\n        for base_expr in type_exprs:\n            try:\n                base = self.expr_to_unanalyzed_type(base_expr)\n            except TypeTranslationError:\n                # This error will be caught later.\n                continue\n            for name, expr in self.find_type_var_likes(base):\n                tvars.setdefault(name, (expr, base_expr))\n        tvar_defs = []\n        for name, (tvar_expr, context) in tvars.items():\n            tvar_def = self.tvar_scope.bind_new(name, tvar_expr, self.fail, context)\n            tvar_defs.append(tvar_def)\n        return tvar_defs\n\n    def prepare_class_def(\n        self, defn: ClassDef, info: TypeInfo | None = None, custom_names: bool = False\n    ) -> None:\n        \"\"\"Prepare for the analysis of a class definition.\n\n        Create an empty TypeInfo and store it in a symbol table, or if the 'info'\n        argument is provided, store it instead (used for magic type definitions).\n        \"\"\"\n        if not defn.info:\n            defn.fullname = self.qualified_name(defn.name)\n            # TODO: Nested classes\n            info = info or self.make_empty_type_info(defn)\n            defn.info = info\n            info.defn = defn\n            if not custom_names:\n                # Some special classes (in particular NamedTuples) use custom fullname logic.\n                # Don't override it here (also see comment below, this needs cleanup).\n                if not self.is_func_scope():\n                    info._fullname = self.qualified_name(defn.name)\n                else:\n                    info._fullname = info.name\n        local_name = defn.name\n        if \"@\" in local_name:\n            local_name = local_name.split(\"@\")[0]\n        self.add_symbol(local_name, defn.info, defn)\n        if self.is_nested_within_func_scope():\n            # We need to preserve local classes, let's store them\n            # in globals under mangled unique names\n            #\n            # TODO: Putting local classes into globals breaks assumptions in fine-grained\n            #       incremental mode and we should avoid it. In general, this logic is too\n            #       ad-hoc and needs to be removed/refactored.\n            if \"@\" not in defn.info._fullname:\n                global_name = defn.info.name + \"@\" + str(defn.line)\n                defn.info._fullname = self.cur_mod_id + \".\" + global_name\n            else:\n                # Preserve name from previous fine-grained incremental run.\n                global_name = defn.info.name\n            defn.fullname = defn.info._fullname\n            if defn.info.is_named_tuple or defn.info.typeddict_type:\n                # Named tuples and Typed dicts nested within a class are stored\n                # in the class symbol table.\n                self.add_symbol_skip_local(global_name, defn.info)\n            else:\n                self.globals[global_name] = SymbolTableNode(GDEF, defn.info)\n\n    def make_empty_type_info(self, defn: ClassDef) -> TypeInfo:\n        if (\n            self.is_module_scope()\n            and self.cur_mod_id == \"builtins\"\n            and defn.name in CORE_BUILTIN_CLASSES\n        ):\n            # Special case core built-in classes. A TypeInfo was already\n            # created for it before semantic analysis, but with a dummy\n            # ClassDef. Patch the real ClassDef object.\n            info = self.globals[defn.name].node\n            assert isinstance(info, TypeInfo)\n        else:\n            info = TypeInfo(SymbolTable(), defn, self.cur_mod_id)\n            info.set_line(defn)\n        return info\n\n    def get_name_repr_of_expr(self, expr: Expression) -> str | None:\n        \"\"\"Try finding a short simplified textual representation of a base class expression.\"\"\"\n        if isinstance(expr, NameExpr):\n            return expr.name\n        if isinstance(expr, MemberExpr):\n            return get_member_expr_fullname(expr)\n        if isinstance(expr, IndexExpr):\n            return self.get_name_repr_of_expr(expr.base)\n        if isinstance(expr, CallExpr):\n            return self.get_name_repr_of_expr(expr.callee)\n        return None\n\n    def analyze_base_classes(\n        self, base_type_exprs: list[Expression]\n    ) -> tuple[list[tuple[ProperType, Expression]], bool] | None:\n        \"\"\"Analyze base class types.\n\n        Return None if some definition was incomplete. Otherwise, return a tuple\n        with these items:\n\n         * List of (analyzed type, original expression) tuples\n         * Boolean indicating whether one of the bases had a semantic analysis error\n        \"\"\"\n        is_error = False\n        bases = []\n        for base_expr in base_type_exprs:\n            if (\n                isinstance(base_expr, RefExpr)\n                and base_expr.fullname in TYPED_NAMEDTUPLE_NAMES + TPDICT_NAMES\n            ) or (\n                isinstance(base_expr, CallExpr)\n                and isinstance(base_expr.callee, RefExpr)\n                and base_expr.callee.fullname in TPDICT_NAMES\n            ):\n                # Ignore magic bases for now.\n                # For example:\n                #  class Foo(TypedDict): ...  # RefExpr\n                #  class Foo(NamedTuple): ...  # RefExpr\n                #  class Foo(TypedDict(\"Foo\", {\"a\": int})): ...  # CallExpr\n                continue\n\n            try:\n                base = self.expr_to_analyzed_type(\n                    base_expr, allow_placeholder=True, allow_type_any=True\n                )\n            except TypeTranslationError:\n                name = self.get_name_repr_of_expr(base_expr)\n                if isinstance(base_expr, CallExpr):\n                    msg = \"Unsupported dynamic base class\"\n                else:\n                    msg = \"Invalid base class\"\n                if name:\n                    msg += f' \"{name}\"'\n                self.fail(msg, base_expr)\n                is_error = True\n                continue\n            if base is None:\n                return None\n            base = get_proper_type(base)\n            bases.append((base, base_expr))\n        return bases, is_error\n\n    def configure_base_classes(\n        self, defn: ClassDef, bases: list[tuple[ProperType, Expression]]\n    ) -> None:\n        \"\"\"Set up base classes.\n\n        This computes several attributes on the corresponding TypeInfo defn.info\n        related to the base classes: defn.info.bases, defn.info.mro, and\n        miscellaneous others (at least tuple_type, fallback_to_any, and is_enum.)\n        \"\"\"\n        base_types: list[Instance] = []\n        info = defn.info\n\n        for base, base_expr in bases:\n            if isinstance(base, TupleType):\n                actual_base = self.configure_tuple_base_class(defn, base)\n                base_types.append(actual_base)\n            elif isinstance(base, Instance):\n                if base.type.is_newtype:\n                    self.fail('Cannot subclass \"NewType\"', defn)\n                base_types.append(base)\n            elif isinstance(base, AnyType):\n                if self.options.disallow_subclassing_any:\n                    if isinstance(base_expr, (NameExpr, MemberExpr)):\n                        msg = f'Class cannot subclass \"{base_expr.name}\" (has type \"Any\")'\n                    else:\n                        msg = 'Class cannot subclass value of type \"Any\"'\n                    self.fail(msg, base_expr)\n                info.fallback_to_any = True\n            elif isinstance(base, TypedDictType):\n                base_types.append(base.fallback)\n            else:\n                msg = \"Invalid base class\"\n                name = self.get_name_repr_of_expr(base_expr)\n                if name:\n                    msg += f' \"{name}\"'\n                self.fail(msg, base_expr)\n                info.fallback_to_any = True\n            if self.options.disallow_any_unimported and has_any_from_unimported_type(base):\n                if isinstance(base_expr, (NameExpr, MemberExpr)):\n                    prefix = f\"Base type {base_expr.name}\"\n                else:\n                    prefix = \"Base type\"\n                self.msg.unimported_type_becomes_any(prefix, base, base_expr)\n            check_for_explicit_any(\n                base, self.options, self.is_typeshed_stub_file, self.msg, context=base_expr\n            )\n\n        # Add 'object' as implicit base if there is no other base class.\n        if not base_types and defn.fullname != \"builtins.object\":\n            base_types.append(self.object_type())\n\n        info.bases = base_types\n\n        # Calculate the MRO.\n        if not self.verify_base_classes(defn):\n            self.set_dummy_mro(defn.info)\n            return\n        if not self.verify_duplicate_base_classes(defn):\n            # We don't want to block the typechecking process,\n            # so, we just insert `Any` as the base class and show an error.\n            self.set_any_mro(defn.info)\n        self.calculate_class_mro(defn, self.object_type)\n\n    def configure_tuple_base_class(self, defn: ClassDef, base: TupleType) -> Instance:\n        info = defn.info\n\n        # There may be an existing valid tuple type from previous semanal iterations.\n        # Use equality to check if it is the case.\n        if info.tuple_type and info.tuple_type != base and not has_placeholder(info.tuple_type):\n            self.fail(\"Class has two incompatible bases derived from tuple\", defn)\n            defn.has_incompatible_baseclass = True\n        if has_placeholder(base):\n            self.process_placeholder(\n                None, \"tuple base\", defn, force_progress=base != info.tuple_type\n            )\n        info.update_tuple_type(base)\n        self.setup_alias_type_vars(defn)\n\n        if base.partial_fallback.type.fullname == \"builtins.tuple\" and not has_placeholder(base):\n            # Fallback can only be safely calculated after semantic analysis, since base\n            # classes may be incomplete. Postpone the calculation.\n            self.schedule_patch(PRIORITY_FALLBACKS, lambda: calculate_tuple_fallback(base))\n\n        return base.partial_fallback\n\n    def set_dummy_mro(self, info: TypeInfo) -> None:\n        # Give it an MRO consisting of just the class itself and object.\n        info.mro = [info, self.object_type().type]\n        info.bad_mro = True\n\n    def set_any_mro(self, info: TypeInfo) -> None:\n        # Give it an MRO consisting direct `Any` subclass.\n        info.fallback_to_any = True\n        info.mro = [info, self.object_type().type]\n\n    def calculate_class_mro(\n        self, defn: ClassDef, obj_type: Callable[[], Instance] | None = None\n    ) -> None:\n        \"\"\"Calculate method resolution order for a class.\n\n        `obj_type` exists just to fill in empty base class list in case of an error.\n        \"\"\"\n        try:\n            calculate_mro(defn.info, obj_type)\n        except MroError:\n            self.fail(\n                f'Cannot determine consistent method resolution order (MRO) for \"{defn.name}\"',\n                defn,\n            )\n            self.set_dummy_mro(defn.info)\n        # Allow plugins to alter the MRO to handle the fact that `def mro()`\n        # on metaclasses permits MRO rewriting.\n        if defn.fullname:\n            hook = self.plugin.get_customize_class_mro_hook(defn.fullname)\n            if hook:\n                hook(ClassDefContext(defn, FakeExpression(), self))\n\n    def infer_metaclass_and_bases_from_compat_helpers(self, defn: ClassDef) -> None:\n        \"\"\"Lookup for special metaclass declarations, and update defn fields accordingly.\n\n        * six.with_metaclass(M, B1, B2, ...)\n        * @six.add_metaclass(M)\n        * future.utils.with_metaclass(M, B1, B2, ...)\n        * past.utils.with_metaclass(M, B1, B2, ...)\n        \"\"\"\n\n        # Look for six.with_metaclass(M, B1, B2, ...)\n        with_meta_expr: Expression | None = None\n        if len(defn.base_type_exprs) == 1:\n            base_expr = defn.base_type_exprs[0]\n            if isinstance(base_expr, CallExpr) and isinstance(base_expr.callee, RefExpr):\n                self.analyze_type_expr(base_expr)\n                if (\n                    base_expr.callee.fullname\n                    in {\n                        \"six.with_metaclass\",\n                        \"future.utils.with_metaclass\",\n                        \"past.utils.with_metaclass\",\n                    }\n                    and len(base_expr.args) >= 1\n                    and all(kind == ARG_POS for kind in base_expr.arg_kinds)\n                ):\n                    with_meta_expr = base_expr.args[0]\n                    defn.base_type_exprs = base_expr.args[1:]\n\n        # Look for @six.add_metaclass(M)\n        add_meta_expr: Expression | None = None\n        for dec_expr in defn.decorators:\n            if isinstance(dec_expr, CallExpr) and isinstance(dec_expr.callee, RefExpr):\n                dec_expr.callee.accept(self)\n                if (\n                    dec_expr.callee.fullname == \"six.add_metaclass\"\n                    and len(dec_expr.args) == 1\n                    and dec_expr.arg_kinds[0] == ARG_POS\n                ):\n                    add_meta_expr = dec_expr.args[0]\n                    break\n\n        metas = {defn.metaclass, with_meta_expr, add_meta_expr} - {None}\n        if len(metas) == 0:\n            return\n        if len(metas) > 1:\n            self.fail(\"Multiple metaclass definitions\", defn, code=codes.METACLASS)\n            return\n        defn.metaclass = metas.pop()\n\n    def verify_base_classes(self, defn: ClassDef) -> bool:\n        info = defn.info\n        cycle = False\n        for base in info.bases:\n            baseinfo = base.type\n            if self.is_base_class(info, baseinfo):\n                self.fail(\"Cycle in inheritance hierarchy\", defn)\n                cycle = True\n        return not cycle\n\n    def verify_duplicate_base_classes(self, defn: ClassDef) -> bool:\n        dup = find_duplicate(defn.info.direct_base_classes())\n        if dup:\n            self.fail(f'Duplicate base class \"{dup.name}\"', defn)\n        return not dup\n\n    def is_base_class(self, t: TypeInfo, s: TypeInfo) -> bool:\n        \"\"\"Determine if t is a base class of s (but do not use mro).\"\"\"\n        # Search the base class graph for t, starting from s.\n        worklist = [s]\n        visited = {s}\n        while worklist:\n            nxt = worklist.pop()\n            if nxt == t:\n                return True\n            for base in nxt.bases:\n                if base.type not in visited:\n                    worklist.append(base.type)\n                    visited.add(base.type)\n        return False\n\n    def get_declared_metaclass(\n        self, name: str, metaclass_expr: Expression | None\n    ) -> tuple[Instance | None, bool, bool]:\n        \"\"\"Get declared metaclass from metaclass expression.\n\n        Returns a tuple of three values:\n          * A metaclass instance or None\n          * A boolean indicating whether we should defer\n          * A boolean indicating whether we should set metaclass Any fallback\n            (either for Any metaclass or invalid/dynamic metaclass).\n\n        The two boolean flags can only be True if instance is None.\n        \"\"\"\n        declared_metaclass = None\n        if metaclass_expr:\n            metaclass_name = None\n            if isinstance(metaclass_expr, NameExpr):\n                metaclass_name = metaclass_expr.name\n            elif isinstance(metaclass_expr, MemberExpr):\n                metaclass_name = get_member_expr_fullname(metaclass_expr)\n            if metaclass_name is None:\n                self.fail(\n                    f'Dynamic metaclass not supported for \"{name}\"',\n                    metaclass_expr,\n                    code=codes.METACLASS,\n                )\n                return None, False, True\n            sym = self.lookup_qualified(metaclass_name, metaclass_expr)\n            if sym is None:\n                # Probably a name error - it is already handled elsewhere\n                return None, False, True\n            if isinstance(sym.node, Var) and isinstance(get_proper_type(sym.node.type), AnyType):\n                if self.options.disallow_subclassing_any:\n                    self.fail(\n                        f'Class cannot use \"{sym.node.name}\" as a metaclass (has type \"Any\")',\n                        metaclass_expr,\n                        code=codes.METACLASS,\n                    )\n                return None, False, True\n            if isinstance(sym.node, PlaceholderNode):\n                return None, True, False  # defer later in the caller\n\n            # Support type aliases, like `_Meta: TypeAlias = type`\n            metaclass_info: Node | None = sym.node\n            if (\n                isinstance(sym.node, TypeAlias)\n                and not sym.node.python_3_12_type_alias\n                and not sym.node.alias_tvars\n            ):\n                target = get_proper_type(sym.node.target)\n                if isinstance(target, Instance):\n                    metaclass_info = target.type\n\n            if not isinstance(metaclass_info, TypeInfo) or metaclass_info.tuple_type is not None:\n                self.fail(\n                    f'Invalid metaclass \"{metaclass_name}\"', metaclass_expr, code=codes.METACLASS\n                )\n                return None, False, False\n            if not metaclass_info.is_metaclass():\n                self.fail(\n                    'Metaclasses not inheriting from \"type\" are not supported',\n                    metaclass_expr,\n                    code=codes.METACLASS,\n                )\n                return None, False, False\n            inst = fill_typevars(metaclass_info)\n            assert isinstance(inst, Instance)\n            declared_metaclass = inst\n        return declared_metaclass, False, False\n\n    def recalculate_metaclass(self, defn: ClassDef, declared_metaclass: Instance | None) -> None:\n        defn.info.declared_metaclass = declared_metaclass\n        defn.info.metaclass_type = defn.info.calculate_metaclass_type()\n        if any(info.is_protocol for info in defn.info.mro):\n            if (\n                not defn.info.metaclass_type\n                or defn.info.metaclass_type.type.fullname == \"builtins.type\"\n            ):\n                # All protocols and their subclasses have ABCMeta metaclass by default.\n                # TODO: add a metaclass conflict check if there is another metaclass.\n                abc_meta = self.named_type_or_none(\"abc.ABCMeta\", [])\n                if abc_meta is not None:  # May be None in tests with incomplete lib-stub.\n                    defn.info.metaclass_type = abc_meta\n        if defn.info.metaclass_type and defn.info.metaclass_type.type.has_base(\"enum.EnumMeta\"):\n            defn.info.is_enum = True\n            if defn.type_vars:\n                self.fail(\"Enum class cannot be generic\", defn)\n\n    #\n    # Imports\n    #\n\n    def visit_import(self, i: Import) -> None:\n        self.statement = i\n        for id, as_id in i.ids:\n            # Modules imported in a stub file without using 'import X as X' won't get exported\n            # When implicit re-exporting is disabled, we have the same behavior as stubs.\n            use_implicit_reexport = not self.is_stub_file and self.options.implicit_reexport\n            if as_id is not None:\n                base_id = id\n                imported_id = as_id\n                module_public = use_implicit_reexport or id == as_id\n            else:\n                base_id = id.split(\".\")[0]\n                imported_id = base_id\n                module_public = use_implicit_reexport\n\n            if base_id in self.modules:\n                node = self.modules[base_id]\n                if self.is_func_scope():\n                    kind = LDEF\n                elif self.type is not None:\n                    kind = MDEF\n                else:\n                    kind = GDEF\n                symbol = SymbolTableNode(\n                    kind, node, module_public=module_public, module_hidden=not module_public\n                )\n                self.add_imported_symbol(\n                    imported_id,\n                    symbol,\n                    context=i,\n                    module_public=module_public,\n                    module_hidden=not module_public,\n                )\n            else:\n                self.add_unknown_imported_symbol(\n                    imported_id,\n                    context=i,\n                    target_name=base_id,\n                    module_public=module_public,\n                    module_hidden=not module_public,\n                )\n\n    def visit_import_from(self, imp: ImportFrom) -> None:\n        self.statement = imp\n        module_id = self.correct_relative_import(imp)\n        module = self.modules.get(module_id)\n        for id, as_id in imp.names:\n            fullname = module_id + \".\" + id\n            self.set_future_import_flags(fullname)\n            if module is None:\n                node = None\n            elif module_id == self.cur_mod_id and fullname in self.modules:\n                # Submodule takes precedence over definition in surround package, for\n                # compatibility with runtime semantics in typical use cases. This\n                # could more precisely model runtime semantics by taking into account\n                # the line number beyond which the local definition should take\n                # precedence, but doesn't seem to be important in most use cases.\n                node = SymbolTableNode(GDEF, self.modules[fullname])\n            else:\n                if id == as_id == \"__all__\":\n                    # For modules with __all__ public status of symbols is determined uniquely\n                    # by contents of __all__, so we can recover the latter here, and avoid\n                    # serializing this (redundant) information in MypyFile.\n                    self.all_exports[:] = [\n                        name for name, sym in module.names.items() if sym.module_public\n                    ]\n                node = module.names.get(id)\n\n            missing_submodule = False\n            imported_id = as_id or id\n\n            # Modules imported in a stub file without using 'from Y import X as X' will\n            # not get exported.\n            # When implicit re-exporting is disabled, we have the same behavior as stubs.\n            use_implicit_reexport = not self.is_stub_file and self.options.implicit_reexport\n            module_public = use_implicit_reexport or (as_id is not None and id == as_id)\n\n            # If the module does not contain a symbol with the name 'id',\n            # try checking if it's a module instead.\n            if not node:\n                mod = self.modules.get(fullname)\n                if mod is not None:\n                    kind = self.current_symbol_kind()\n                    node = SymbolTableNode(kind, mod)\n                elif fullname in self.missing_modules:\n                    missing_submodule = True\n            # If it is still not resolved, check for a module level __getattr__\n            if module and not node and \"__getattr__\" in module.names:\n                # We store the fullname of the original definition so that we can\n                # detect whether two imported names refer to the same thing.\n                fullname = module_id + \".\" + id\n                gvar = self.create_getattr_var(module.names[\"__getattr__\"], imported_id, fullname)\n                if gvar:\n                    self.add_symbol(\n                        imported_id,\n                        gvar,\n                        imp,\n                        module_public=module_public,\n                        module_hidden=not module_public,\n                    )\n                    continue\n\n            if node:\n                self.process_imported_symbol(\n                    node, module_id, id, imported_id, fullname, module_public, context=imp\n                )\n                if node.module_hidden:\n                    self.report_missing_module_attribute(\n                        module_id,\n                        id,\n                        imported_id,\n                        module_public=module_public,\n                        module_hidden=not module_public,\n                        context=imp,\n                        add_unknown_imported_symbol=False,\n                    )\n            elif module and not missing_submodule:\n                # Target module exists but the imported name is missing or hidden.\n                self.report_missing_module_attribute(\n                    module_id,\n                    id,\n                    imported_id,\n                    module_public=module_public,\n                    module_hidden=not module_public,\n                    context=imp,\n                )\n            else:\n                # Import of a missing (sub)module.\n                self.add_unknown_imported_symbol(\n                    imported_id,\n                    imp,\n                    target_name=fullname,\n                    module_public=module_public,\n                    module_hidden=not module_public,\n                )\n\n    def process_imported_symbol(\n        self,\n        node: SymbolTableNode,\n        module_id: str,\n        id: str,\n        imported_id: str,\n        fullname: str,\n        module_public: bool,\n        context: ImportBase,\n    ) -> None:\n        module_hidden = not module_public and (\n            # `from package import submodule` should work regardless of whether package\n            # re-exports submodule, so we shouldn't hide it\n            not isinstance(node.node, MypyFile)\n            or fullname not in self.modules\n            # but given `from somewhere import random_unrelated_module` we should hide\n            # random_unrelated_module\n            or not fullname.startswith(self.cur_mod_id + \".\")\n        )\n\n        if isinstance(node.node, PlaceholderNode):\n            if self.final_iteration:\n                self.report_missing_module_attribute(\n                    module_id,\n                    id,\n                    imported_id,\n                    module_public=module_public,\n                    module_hidden=module_hidden,\n                    context=context,\n                )\n                return\n            else:\n                # This might become a type.\n                self.mark_incomplete(\n                    imported_id,\n                    node.node,\n                    module_public=module_public,\n                    module_hidden=module_hidden,\n                    becomes_typeinfo=True,\n                )\n        # NOTE: we take the original node even for final `Var`s. This is to support\n        # a common pattern when constants are re-exported (same applies to import *).\n        self.add_imported_symbol(\n            imported_id, node, context, module_public=module_public, module_hidden=module_hidden\n        )\n\n    def report_missing_module_attribute(\n        self,\n        import_id: str,\n        source_id: str,\n        imported_id: str,\n        module_public: bool,\n        module_hidden: bool,\n        context: Node,\n        add_unknown_imported_symbol: bool = True,\n    ) -> None:\n        # Missing attribute.\n        if self.is_incomplete_namespace(import_id):\n            # We don't know whether the name will be there, since the namespace\n            # is incomplete. Defer the current target.\n            self.mark_incomplete(\n                imported_id, context, module_public=module_public, module_hidden=module_hidden\n            )\n            return\n        message = f'Module \"{import_id}\" has no attribute \"{source_id}\"'\n        # Suggest alternatives, if any match is found.\n        module = self.modules.get(import_id)\n        if module:\n            if source_id in module.names.keys() and not module.names[source_id].module_public:\n                message = (\n                    f'Module \"{import_id}\" does not explicitly export attribute \"{source_id}\"'\n                )\n            elif not (\n                self.options.ignore_errors or self.cur_mod_node.path in self.errors.ignored_files\n            ):\n                alternatives = set(module.names.keys()).difference({source_id})\n                matches = best_matches(source_id, alternatives, n=3)\n                if matches:\n                    suggestion = f\"; maybe {pretty_seq(matches, 'or')}?\"\n                    message += f\"{suggestion}\"\n        self.fail(message, context, code=codes.ATTR_DEFINED)\n        if add_unknown_imported_symbol:\n            self.add_unknown_imported_symbol(\n                imported_id,\n                context,\n                target_name=None,\n                module_public=module_public,\n                module_hidden=not module_public,\n            )\n\n        if import_id == \"typing\":\n            # The user probably has a missing definition in a test fixture. Let's verify.\n            fullname = f\"builtins.{source_id.lower()}\"\n            if (\n                self.lookup_fully_qualified_or_none(fullname) is None\n                and fullname in SUGGESTED_TEST_FIXTURES\n            ):\n                # Yes. Generate a helpful note.\n                self.msg.add_fixture_note(fullname, context)\n            else:\n                typing_extensions = self.modules.get(\"typing_extensions\")\n                if typing_extensions and source_id in typing_extensions.names:\n                    self.msg.note(\n                        f\"Use `from typing_extensions import {source_id}` instead\",\n                        context,\n                        code=codes.ATTR_DEFINED,\n                    )\n                    self.msg.note(\n                        \"See https://mypy.readthedocs.io/en/stable/runtime_troubles.html#using-new-additions-to-the-typing-module\",\n                        context,\n                        code=codes.ATTR_DEFINED,\n                    )\n\n    def process_import_over_existing_name(\n        self,\n        imported_id: str,\n        existing_symbol: SymbolTableNode,\n        module_symbol: SymbolTableNode,\n        import_node: ImportBase,\n    ) -> bool:\n        if existing_symbol.node is module_symbol.node:\n            # We added this symbol on previous iteration.\n            return False\n        if existing_symbol.kind in (LDEF, GDEF, MDEF) and isinstance(\n            existing_symbol.node, (Var, FuncDef, TypeInfo, Decorator, TypeAlias)\n        ):\n            # This is a valid import over an existing definition in the file. Construct a dummy\n            # assignment that we'll use to type check the import.\n            lvalue = NameExpr(imported_id)\n            lvalue.kind = existing_symbol.kind\n            lvalue.node = existing_symbol.node\n            rvalue = NameExpr(imported_id)\n            rvalue.kind = module_symbol.kind\n            rvalue.node = module_symbol.node\n            if isinstance(rvalue.node, TypeAlias):\n                # Suppress bogus errors from the dummy assignment if rvalue is an alias.\n                # Otherwise mypy may complain that alias is invalid in runtime context.\n                rvalue.is_alias_rvalue = True\n            assignment = AssignmentStmt([lvalue], rvalue)\n            for node in assignment, lvalue, rvalue:\n                node.set_line(import_node)\n            import_node.assignments.append(assignment)\n            return True\n        return False\n\n    def correct_relative_import(self, node: ImportFrom | ImportAll) -> str:\n        import_id, ok = correct_relative_import(\n            self.cur_mod_id, node.relative, node.id, self.cur_mod_node.is_package_init_file()\n        )\n        if not ok:\n            self.fail(\"Relative import climbs too many namespaces\", node)\n        return import_id\n\n    def visit_import_all(self, i: ImportAll) -> None:\n        i_id = self.correct_relative_import(i)\n        if i_id in self.modules:\n            m = self.modules[i_id]\n            if self.is_incomplete_namespace(i_id):\n                # Any names could be missing from the current namespace if the target module\n                # namespace is incomplete.\n                self.mark_incomplete(\"*\", i)\n            for name, node in m.names.items():\n                if node.no_serialize:\n                    # This is either internal or generated symbol, skip it to avoid problems\n                    # like accidental name conflicts or invalid cross-references.\n                    continue\n                fullname = i_id + \".\" + name\n                self.set_future_import_flags(fullname)\n                # if '__all__' exists, all nodes not included have had module_public set to\n                # False, and we can skip checking '_' because it's been explicitly included.\n                if node.module_public and (not name.startswith(\"_\") or \"__all__\" in m.names):\n                    if isinstance(node.node, MypyFile):\n                        # Star import of submodule from a package, add it as a dependency.\n                        self.imports.add(node.node.fullname)\n                    # `from x import *` always reexports symbols\n                    self.add_imported_symbol(\n                        name, node, context=i, module_public=True, module_hidden=False\n                    )\n                    # This is a (minimalist) copy of the logic in visit_import_from(), we need\n                    # to clean-up any remaining placeholders by replacing them with Var(Any).\n                    if isinstance(node.node, PlaceholderNode) and self.final_iteration:\n                        self.add_unknown_imported_symbol(\n                            name, i, target_name=None, module_public=True, module_hidden=False\n                        )\n\n        else:\n            # Don't add any dummy symbols for 'from x import *' if 'x' is unknown.\n            pass\n\n    #\n    # Assignment\n    #\n\n    def visit_assignment_expr(self, s: AssignmentExpr) -> None:\n        s.value.accept(self)\n        if self.is_func_scope():\n            if not self.check_valid_comprehension(s):\n                return\n        self.analyze_lvalue(s.target, escape_comprehensions=True, has_explicit_value=True)\n\n    def check_valid_comprehension(self, s: AssignmentExpr) -> bool:\n        \"\"\"Check that assignment expression is not nested within comprehension at class scope.\n\n        class C:\n            [(j := i) for i in [1, 2, 3]]\n        is a syntax error that is not enforced by Python parser, but at later steps.\n        \"\"\"\n        for i, scope_type in enumerate(reversed(self.scope_stack)):\n            if scope_type != SCOPE_COMPREHENSION and i < len(self.locals) - 1:\n                if self.locals[-1 - i] is None:\n                    self.fail(\n                        \"Assignment expression within a comprehension\"\n                        \" cannot be used in a class body\",\n                        s,\n                        code=codes.SYNTAX,\n                        serious=True,\n                        blocker=True,\n                    )\n                    return False\n                break\n        return True\n\n    def visit_assignment_stmt(self, s: AssignmentStmt) -> None:\n        self.statement = s\n\n        # Special case assignment like X = X.\n        if self.analyze_identity_global_assignment(s):\n            return\n\n        tag = self.track_incomplete_refs()\n\n        # Here we have a chicken and egg problem: at this stage we can't call\n        # can_be_type_alias(), because we have not enough information about rvalue.\n        # But we can't use a full visit because it may emit extra incomplete refs (namely\n        # when analysing any type applications there) thus preventing the further analysis.\n        # To break the tie, we first analyse rvalue partially, if it can be a type alias.\n        if self.can_possibly_be_type_form(s):\n            old_basic_type_applications = self.basic_type_applications\n            self.basic_type_applications = True\n            with self.allow_unbound_tvars_set():\n                s.rvalue.accept(self)\n            self.basic_type_applications = old_basic_type_applications\n        elif self.can_possibly_be_typevarlike_declaration(s):\n            # Allow unbound tvars inside TypeVarLike defaults to be evaluated later\n            with self.allow_unbound_tvars_set():\n                s.rvalue.accept(self)\n        else:\n            s.rvalue.accept(self)\n\n        if self.found_incomplete_ref(tag) or self.should_wait_rhs(s.rvalue):\n            # Initializer couldn't be fully analyzed. Defer the current node and give up.\n            # Make sure that if we skip the definition of some local names, they can't be\n            # added later in this scope, since an earlier definition should take precedence.\n            for expr in names_modified_by_assignment(s):\n                self.mark_incomplete(expr.name, expr)\n            return\n        if self.can_possibly_be_type_form(s):\n            # Now re-visit those rvalues that were we skipped type applications above.\n            # This should be safe as generally semantic analyzer is idempotent.\n            with self.allow_unbound_tvars_set():\n                s.rvalue.accept(self)\n\n        # The r.h.s. is now ready to be classified, first check if it is a special form:\n        special_form = False\n        # * type alias\n        if self.check_and_set_up_type_alias(s):\n            s.is_alias_def = True\n            special_form = True\n        elif isinstance(s.rvalue, CallExpr):\n            # * type variable definition\n            if self.process_typevar_declaration(s):\n                special_form = True\n            elif self.process_paramspec_declaration(s):\n                special_form = True\n            elif self.process_typevartuple_declaration(s):\n                special_form = True\n            # * type constructors\n            elif self.analyze_namedtuple_assign(s):\n                special_form = True\n            elif self.analyze_typeddict_assign(s):\n                special_form = True\n            elif self.newtype_analyzer.process_newtype_declaration(s):\n                special_form = True\n            elif self.analyze_enum_assign(s):\n                special_form = True\n\n        if special_form:\n            self.record_special_form_lvalue(s)\n            return\n        # Clear the alias flag if assignment turns out not a special form after all. It\n        # may be set to True while there were still placeholders due to forward refs.\n        s.is_alias_def = False\n\n        # OK, this is a regular assignment, perform the necessary analysis steps.\n        s.is_final_def = self.unwrap_final(s)\n        self.analyze_lvalues(s)\n        self.check_final_implicit_def(s)\n        self.store_final_status(s)\n        self.check_classvar(s)\n        self.process_type_annotation(s)\n        self.analyze_rvalue_as_type_form(s)\n        self.apply_dynamic_class_hook(s)\n        if not s.type:\n            self.process_module_assignment(s.lvalues, s.rvalue, s)\n        self.process__all__(s)\n        self.process__deletable__(s)\n        self.process__slots__(s)\n\n    def analyze_identity_global_assignment(self, s: AssignmentStmt) -> bool:\n        \"\"\"Special case 'X = X' in global scope.\n\n        This allows supporting some important use cases.\n\n        Return true if special casing was applied.\n        \"\"\"\n        if not isinstance(s.rvalue, NameExpr) or len(s.lvalues) != 1:\n            # Not of form 'X = X'\n            return False\n        lvalue = s.lvalues[0]\n        if not isinstance(lvalue, NameExpr) or s.rvalue.name != lvalue.name:\n            # Not of form 'X = X'\n            return False\n        if self.type is not None or self.is_func_scope():\n            # Not in global scope\n            return False\n        # It's an assignment like 'X = X' in the global scope.\n        name = lvalue.name\n        sym = self.lookup(name, s)\n        if sym is None:\n            if self.final_iteration:\n                # Fall back to normal assignment analysis.\n                return False\n            else:\n                self.defer()\n                return True\n        else:\n            if sym.node is None:\n                # Something special -- fall back to normal assignment analysis.\n                return False\n            if name not in self.globals:\n                # The name is from builtins. Add an alias to the current module.\n                self.add_symbol(name, sym.node, s)\n            if not isinstance(sym.node, PlaceholderNode):\n                for node in s.rvalue, lvalue:\n                    node.node = sym.node\n                    node.kind = GDEF\n                    node.fullname = sym.node.fullname\n            return True\n\n    def should_wait_rhs(self, rv: Expression) -> bool:\n        \"\"\"Can we already classify this r.h.s. of an assignment or should we wait?\n\n        This returns True if we don't have enough information to decide whether\n        an assignment is just a normal variable definition or a special form.\n        Always return False if this is a final iteration. This will typically cause\n        the lvalue to be classified as a variable plus emit an error.\n        \"\"\"\n        if self.final_iteration:\n            # No chance, nothing has changed.\n            return False\n        if isinstance(rv, NameExpr):\n            n = self.lookup(rv.name, rv)\n            if n and isinstance(n.node, PlaceholderNode) and not n.node.becomes_typeinfo:\n                return True\n        elif isinstance(rv, MemberExpr):\n            fname = get_member_expr_fullname(rv)\n            if fname:\n                n = self.lookup_qualified(fname, rv, suppress_errors=True)\n                if n and isinstance(n.node, PlaceholderNode) and not n.node.becomes_typeinfo:\n                    return True\n        elif isinstance(rv, IndexExpr) and isinstance(rv.base, RefExpr):\n            return self.should_wait_rhs(rv.base)\n        elif isinstance(rv, CallExpr) and isinstance(rv.callee, RefExpr):\n            # This is only relevant for builtin SCC where things like 'TypeVar'\n            # may be not ready.\n            return self.should_wait_rhs(rv.callee)\n        return False\n\n    def can_be_type_alias(self, rv: Expression, allow_none: bool = False) -> bool:\n        \"\"\"Is this a valid r.h.s. for an alias definition?\n\n        Note: this function should be only called for expressions where self.should_wait_rhs()\n        returns False.\n        \"\"\"\n        if isinstance(rv, RefExpr) and self.is_type_ref(rv, bare=True):\n            return True\n        if isinstance(rv, IndexExpr) and self.is_type_ref(rv.base, bare=False):\n            return True\n        if self.is_none_alias(rv):\n            return True\n        if allow_none and isinstance(rv, NameExpr) and rv.fullname == \"builtins.None\":\n            return True\n        if isinstance(rv, OpExpr) and rv.op == \"|\":\n            if self.is_stub_file:\n                return True\n            if self.can_be_type_alias(rv.left, allow_none=True) and self.can_be_type_alias(\n                rv.right, allow_none=True\n            ):\n                return True\n        return False\n\n    def can_possibly_be_type_form(self, s: AssignmentStmt) -> bool:\n        \"\"\"Like can_be_type_alias(), but simpler and doesn't require fully analyzed rvalue.\n\n        Instead, use lvalues/annotations structure to figure out whether this can potentially be\n        a type alias definition, NamedTuple, or TypedDict. Another difference from above function\n        is that we are only interested IndexExpr, CallExpr and OpExpr rvalues, since only those\n        can be potentially recursive (things like `A = A` are never valid).\n        \"\"\"\n        if len(s.lvalues) > 1:\n            return False\n        if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.callee, RefExpr):\n            ref = s.rvalue.callee.fullname\n            return ref in TPDICT_NAMES or ref in TYPED_NAMEDTUPLE_NAMES\n        if not isinstance(s.lvalues[0], NameExpr):\n            return False\n        if s.unanalyzed_type is not None and not self.is_pep_613(s):\n            return False\n        if not isinstance(s.rvalue, (IndexExpr, OpExpr)):\n            return False\n        # Something that looks like Foo = Bar[Baz, ...]\n        return True\n\n    def can_possibly_be_typevarlike_declaration(self, s: AssignmentStmt) -> bool:\n        \"\"\"Check if r.h.s. can be a TypeVarLike declaration.\"\"\"\n        if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr):\n            return False\n        if not isinstance(s.rvalue, CallExpr) or not isinstance(s.rvalue.callee, NameExpr):\n            return False\n        ref = s.rvalue.callee\n        ref.accept(self)\n        return ref.fullname in TYPE_VAR_LIKE_NAMES\n\n    def is_type_ref(self, rv: Expression, bare: bool = False) -> bool:\n        \"\"\"Does this expression refer to a type?\n\n        This includes:\n          * Special forms, like Any or Union\n          * Classes (except subscripted enums)\n          * Other type aliases\n          * PlaceholderNodes with becomes_typeinfo=True (these can be not ready class\n            definitions, and not ready aliases).\n\n        If bare is True, this is not a base of an index expression, so some special\n        forms are not valid (like a bare Union).\n\n        Note: This method should be only used in context of a type alias definition.\n        This method can only return True for RefExprs, to check if C[int] is a valid\n        target for type alias call this method on expr.base (i.e. on C in C[int]).\n        See also can_be_type_alias().\n        \"\"\"\n        if not isinstance(rv, RefExpr):\n            return False\n        if isinstance(rv.node, TypeVarLikeExpr):\n            self.fail(f'Type variable \"{rv.fullname}\" is invalid as target for type alias', rv)\n            return False\n\n        if bare:\n            # These three are valid even if bare, for example\n            # A = Tuple is just equivalent to A = Tuple[Any, ...].\n            valid_refs = {\"typing.Any\", \"typing.Tuple\", \"typing.Callable\"}\n        else:\n            valid_refs = type_constructors\n\n        if isinstance(rv.node, TypeAlias) or rv.fullname in valid_refs:\n            return True\n        if isinstance(rv.node, TypeInfo):\n            if bare:\n                return True\n            # Assignment color = Color['RED'] defines a variable, not an alias.\n            return not rv.node.is_enum\n        if isinstance(rv.node, Var):\n            return rv.node.fullname in NEVER_NAMES\n\n        if isinstance(rv, NameExpr):\n            n = self.lookup(rv.name, rv)\n            if n and isinstance(n.node, PlaceholderNode) and n.node.becomes_typeinfo:\n                return True\n        elif isinstance(rv, MemberExpr):\n            fname = get_member_expr_fullname(rv)\n            if fname:\n                # The r.h.s. for variable definitions may not be a type reference but just\n                # an instance attribute, so suppress the errors.\n                n = self.lookup_qualified(fname, rv, suppress_errors=True)\n                if n and isinstance(n.node, PlaceholderNode) and n.node.becomes_typeinfo:\n                    return True\n        return False\n\n    def is_none_alias(self, node: Expression) -> bool:\n        \"\"\"Is this a r.h.s. for a None alias?\n\n        We special case the assignments like Void = type(None), to allow using\n        Void in type annotations.\n        \"\"\"\n        if isinstance(node, CallExpr):\n            if (\n                isinstance(node.callee, NameExpr)\n                and len(node.args) == 1\n                and isinstance(node.args[0], NameExpr)\n            ):\n                call = self.lookup_qualified(node.callee.name, node.callee)\n                arg = self.lookup_qualified(node.args[0].name, node.args[0])\n                if (\n                    call is not None\n                    and call.node\n                    and call.node.fullname == \"builtins.type\"\n                    and arg is not None\n                    and arg.node\n                    and arg.node.fullname == \"builtins.None\"\n                ):\n                    return True\n        return False\n\n    def record_special_form_lvalue(self, s: AssignmentStmt) -> None:\n        \"\"\"Record minimal necessary information about l.h.s. of a special form.\n\n        This exists mostly for compatibility with the old semantic analyzer.\n        \"\"\"\n        lvalue = s.lvalues[0]\n        assert isinstance(lvalue, NameExpr)\n        lvalue.is_special_form = True\n        if self.current_symbol_kind() == GDEF:\n            lvalue.fullname = self.qualified_name(lvalue.name)\n        lvalue.kind = self.current_symbol_kind()\n\n    def analyze_enum_assign(self, s: AssignmentStmt) -> bool:\n        \"\"\"Check if s defines an Enum.\"\"\"\n        if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, EnumCallExpr):\n            # This is an analyzed enum definition.\n            # It is valid iff it can be stored correctly, failures were already reported.\n            return self._is_single_name_assignment(s)\n        return self.enum_call_analyzer.process_enum_call(s, self.is_func_scope())\n\n    def analyze_namedtuple_assign(self, s: AssignmentStmt) -> bool:\n        \"\"\"Check if s defines a namedtuple.\"\"\"\n        if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, NamedTupleExpr):\n            if s.rvalue.analyzed.info.tuple_type and not has_placeholder(\n                s.rvalue.analyzed.info.tuple_type\n            ):\n                # This is an analyzed named tuple definition.\n                # It is valid iff it can be stored correctly, failures were already reported.\n                return self._is_single_name_assignment(s)\n        if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)):\n            return False\n        lvalue = s.lvalues[0]\n        if isinstance(lvalue, MemberExpr):\n            if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.callee, RefExpr):\n                fullname = s.rvalue.callee.fullname\n                if fullname == \"collections.namedtuple\" or fullname in TYPED_NAMEDTUPLE_NAMES:\n                    self.fail(\"NamedTuple type as an attribute is not supported\", lvalue)\n            return False\n        name = lvalue.name\n        namespace = self.qualified_name(name)\n        with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)):\n            internal_name, info, tvar_defs = self.named_tuple_analyzer.check_namedtuple(\n                s.rvalue, name, self.is_func_scope()\n            )\n            if internal_name is None:\n                return False\n            if internal_name != name:\n                self.fail(\n                    'First argument to namedtuple() should be \"{}\", not \"{}\"'.format(\n                        name, internal_name\n                    ),\n                    s.rvalue,\n                    code=codes.NAME_MATCH,\n                )\n                return True\n            # Yes, it's a valid namedtuple, but defer if it is not ready.\n            if not info:\n                self.mark_incomplete(name, lvalue, becomes_typeinfo=True)\n            else:\n                self.setup_type_vars(info.defn, tvar_defs)\n                self.setup_alias_type_vars(info.defn)\n            return True\n\n    def analyze_typeddict_assign(self, s: AssignmentStmt) -> bool:\n        \"\"\"Check if s defines a typed dict.\"\"\"\n        if isinstance(s.rvalue, CallExpr) and isinstance(s.rvalue.analyzed, TypedDictExpr):\n            if s.rvalue.analyzed.info.typeddict_type and not has_placeholder(\n                s.rvalue.analyzed.info.typeddict_type\n            ):\n                # This is an analyzed typed dict definition.\n                # It is valid iff it can be stored correctly, failures were already reported.\n                return self._is_single_name_assignment(s)\n        if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)):\n            return False\n        lvalue = s.lvalues[0]\n        name = lvalue.name\n        namespace = self.qualified_name(name)\n        with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)):\n            is_typed_dict, info, tvar_defs = self.typed_dict_analyzer.check_typeddict(\n                s.rvalue, name, self.is_func_scope()\n            )\n            if not is_typed_dict:\n                return False\n            if isinstance(lvalue, MemberExpr):\n                self.fail(\"TypedDict type as attribute is not supported\", lvalue)\n                return False\n            # Yes, it's a valid typed dict, but defer if it is not ready.\n            if not info:\n                self.mark_incomplete(name, lvalue, becomes_typeinfo=True)\n            else:\n                defn = info.defn\n                self.setup_type_vars(defn, tvar_defs)\n                self.setup_alias_type_vars(defn)\n            return True\n\n    def _is_single_name_assignment(self, s: AssignmentStmt) -> bool:\n        return len(s.lvalues) == 1 and isinstance(s.lvalues[0], NameExpr)\n\n    def analyze_lvalues(self, s: AssignmentStmt) -> None:\n        # We cannot use s.type, because analyze_simple_literal_type() will set it.\n        explicit = s.unanalyzed_type is not None\n        if self.is_final_type(s.unanalyzed_type):\n            # We need to exclude bare Final.\n            assert isinstance(s.unanalyzed_type, UnboundType)\n            if not s.unanalyzed_type.args:\n                explicit = False\n\n        if s.rvalue:\n            if isinstance(s.rvalue, TempNode):\n                has_explicit_value = not s.rvalue.no_rhs\n            else:\n                has_explicit_value = True\n        else:\n            has_explicit_value = False\n\n        for lval in s.lvalues:\n            self.analyze_lvalue(\n                lval,\n                explicit_type=explicit,\n                is_final=s.is_final_def,\n                has_explicit_value=has_explicit_value,\n            )\n\n    def analyze_rvalue_as_type_form(self, s: AssignmentStmt) -> None:\n        if TYPE_FORM in self.options.enable_incomplete_feature:\n            self.try_parse_as_type_expression(s.rvalue)\n\n    def apply_dynamic_class_hook(self, s: AssignmentStmt) -> None:\n        if not isinstance(s.rvalue, CallExpr):\n            return\n        fname = \"\"\n        call = s.rvalue\n        while True:\n            if isinstance(call.callee, RefExpr):\n                fname = call.callee.fullname\n            # check if method call\n            if not fname and isinstance(call.callee, MemberExpr):\n                callee_expr = call.callee.expr\n                if isinstance(callee_expr, RefExpr) and callee_expr.fullname:\n                    method_name = call.callee.name\n                    fname = callee_expr.fullname + \".\" + method_name\n                elif (\n                    isinstance(callee_expr, IndexExpr)\n                    and isinstance(callee_expr.base, RefExpr)\n                    and isinstance(callee_expr.analyzed, TypeApplication)\n                ):\n                    method_name = call.callee.name\n                    fname = callee_expr.base.fullname + \".\" + method_name\n                elif isinstance(callee_expr, CallExpr):\n                    # check if chain call\n                    call = callee_expr\n                    continue\n            break\n        if not fname:\n            return\n        hook = self.plugin.get_dynamic_class_hook(fname)\n        if not hook:\n            return\n        for lval in s.lvalues:\n            if not isinstance(lval, NameExpr):\n                continue\n            hook(DynamicClassDefContext(call, lval.name, self))\n\n    def unwrap_final(self, s: AssignmentStmt) -> bool:\n        \"\"\"Strip Final[...] if present in an assignment.\n\n        This is done to invoke type inference during type checking phase for this\n        assignment. Also, Final[...] doesn't affect type in any way -- it is rather an\n        access qualifier for given `Var`.\n\n        Also perform various consistency checks.\n\n        Returns True if Final[...] was present.\n        \"\"\"\n        if not s.unanalyzed_type or not self.is_final_type(s.unanalyzed_type):\n            return False\n        assert isinstance(s.unanalyzed_type, UnboundType)\n        if len(s.unanalyzed_type.args) > 1:\n            self.fail(\"Final[...] takes at most one type argument\", s.unanalyzed_type)\n        invalid_bare_final = False\n        if not s.unanalyzed_type.args:\n            s.type = None\n            if (\n                isinstance(s.rvalue, TempNode)\n                and s.rvalue.no_rhs\n                # Filter duplicate errors, we already reported this:\n                and not (self.type and self.type.is_named_tuple)\n            ):\n                invalid_bare_final = True\n                self.fail(\"Type in Final[...] can only be omitted if there is an initializer\", s)\n        else:\n            s.type = s.unanalyzed_type.args[0]\n\n        if (\n            s.type is not None\n            and self.options.python_version < (3, 13)\n            and self.is_classvar(s.type)\n        ):\n            self.fail(\"Variable should not be annotated with both ClassVar and Final\", s)\n            return False\n\n        if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], RefExpr):\n            self.fail(\"Invalid final declaration\", s)\n            return False\n        lval = s.lvalues[0]\n        assert isinstance(lval, RefExpr)\n\n        # Reset inferred status if it was set due to simple literal rvalue on previous iteration.\n        # TODO: this is a best-effort quick fix, we should avoid the need to manually sync this,\n        # see https://github.com/python/mypy/issues/6458.\n        if lval.is_new_def:\n            lval.is_inferred_def = s.type is None\n\n        if self.loop_depth[-1] > 0:\n            self.fail(\"Cannot use Final inside a loop\", s)\n        if self.type and self.type.is_protocol:\n            if self.is_class_scope():\n                self.msg.protocol_members_cant_be_final(s)\n        if (\n            isinstance(s.rvalue, TempNode)\n            and s.rvalue.no_rhs\n            and not self.is_stub_file\n            and not self.is_class_scope()\n        ):\n            if not invalid_bare_final:  # Skip extra error messages.\n                self.msg.final_without_value(s)\n        return True\n\n    def check_final_implicit_def(self, s: AssignmentStmt) -> None:\n        \"\"\"Do basic checks for final declaration on self in __init__.\n\n        Additional re-definition checks are performed by `analyze_lvalue`.\n        \"\"\"\n        if not s.is_final_def:\n            return\n        lval = s.lvalues[0]\n        assert isinstance(lval, RefExpr)\n        if isinstance(lval, MemberExpr):\n            if not self.is_self_member_ref(lval):\n                self.fail(\"Final can be only applied to a name or an attribute on self\", s)\n                s.is_final_def = False\n                return\n            else:\n                assert self.function_stack\n                if self.function_stack[-1].name != \"__init__\":\n                    self.fail(\"Can only declare a final attribute in class body or __init__\", s)\n                    s.is_final_def = False\n                    return\n\n    def store_final_status(self, s: AssignmentStmt) -> None:\n        \"\"\"If this is a locally valid final declaration, set the corresponding flag on `Var`.\"\"\"\n        if s.is_final_def:\n            if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr):\n                node = s.lvalues[0].node\n                if isinstance(node, Var):\n                    node.is_final = True\n                    if s.type:\n                        node.final_value = constant_fold_expr(s.rvalue, self.cur_mod_id)\n                    if self.is_class_scope() and (\n                        isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs\n                    ):\n                        node.final_unset_in_class = True\n        else:\n            for lval in self.flatten_lvalues(s.lvalues):\n                # Special case: we are working with an `Enum`:\n                #\n                #   class MyEnum(Enum):\n                #       key = 'some value'\n                #\n                # Here `key` is implicitly final. In runtime, code like\n                #\n                #     MyEnum.key = 'modified'\n                #\n                # will fail with `AttributeError: Cannot reassign members.`\n                # That's why we need to replicate this.\n                if (\n                    isinstance(lval, NameExpr)\n                    and isinstance(self.type, TypeInfo)\n                    and self.type.is_enum\n                ):\n                    cur_node = self.type.names.get(lval.name, None)\n                    if (\n                        cur_node\n                        and isinstance(cur_node.node, Var)\n                        and not (isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs)\n                    ):\n                        # Double underscored members are writable on an `Enum`.\n                        # (Except read-only `__members__` but that is handled in type checker)\n                        cur_node.node.is_final = s.is_final_def = not is_dunder(cur_node.node.name)\n\n                # Special case: deferred initialization of a final attribute in __init__.\n                # In this case we just pretend this is a valid final definition to suppress\n                # errors about assigning to final attribute.\n                if isinstance(lval, MemberExpr) and self.is_self_member_ref(lval):\n                    assert self.type, \"Self member outside a class\"\n                    cur_node = self.type.names.get(lval.name, None)\n                    if cur_node and isinstance(cur_node.node, Var) and cur_node.node.is_final:\n                        assert self.function_stack\n                        current_function = self.function_stack[-1]\n                        if (\n                            current_function.name == \"__init__\"\n                            and cur_node.node.final_unset_in_class\n                            and not cur_node.node.final_set_in_init\n                            and not (isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs)\n                        ):\n                            cur_node.node.final_set_in_init = True\n                            s.is_final_def = True\n\n    def flatten_lvalues(self, lvalues: list[Expression]) -> list[Expression]:\n        res: list[Expression] = []\n        for lv in lvalues:\n            if isinstance(lv, (TupleExpr, ListExpr)):\n                res.extend(self.flatten_lvalues(lv.items))\n            else:\n                res.append(lv)\n        return res\n\n    def process_type_annotation(self, s: AssignmentStmt) -> None:\n        \"\"\"Analyze type annotation or infer simple literal type.\"\"\"\n        if s.type:\n            lvalue = s.lvalues[-1]\n            allow_tuple_literal = isinstance(lvalue, TupleExpr)\n            analyzed = self.anal_type(s.type, allow_tuple_literal=allow_tuple_literal)\n            # Don't store not ready types (including placeholders).\n            if analyzed is None or has_placeholder(analyzed):\n                self.defer(s)\n                return\n            s.type = analyzed\n            if (\n                self.type\n                and self.type.is_protocol\n                and isinstance(lvalue, NameExpr)\n                and isinstance(s.rvalue, TempNode)\n                and s.rvalue.no_rhs\n            ):\n                if isinstance(lvalue.node, Var):\n                    lvalue.node.is_abstract_var = True\n        else:\n            if (\n                self.type\n                and self.type.is_protocol\n                and self.is_annotated_protocol_member(s)\n                and not self.is_func_scope()\n            ):\n                self.fail(\"All protocol members must have explicitly declared types\", s)\n            # Set the type if the rvalue is a simple literal (even if the above error occurred).\n            if len(s.lvalues) == 1 and isinstance(s.lvalues[0], RefExpr):\n                ref_expr = s.lvalues[0]\n                safe_literal_inference = True\n                if self.type and isinstance(ref_expr, NameExpr) and len(self.type.mro) > 1:\n                    # Check if there is a definition in supertype. If yes, we can't safely\n                    # decide here what to infer: int or Literal[42].\n                    safe_literal_inference = self.type.mro[1].get(ref_expr.name) is None\n                if safe_literal_inference and ref_expr.is_inferred_def:\n                    s.type = self.analyze_simple_literal_type(s.rvalue, s.is_final_def)\n        if s.type:\n            # Store type into nodes.\n            for lvalue in s.lvalues:\n                self.store_declared_types(lvalue, s.type)\n\n    def is_annotated_protocol_member(self, s: AssignmentStmt) -> bool:\n        \"\"\"Check whether a protocol member is annotated.\n\n        There are some exceptions that can be left unannotated, like ``__slots__``.\"\"\"\n        return any(\n            (isinstance(lv, NameExpr) and lv.name != \"__slots__\" and lv.is_inferred_def)\n            for lv in s.lvalues\n        )\n\n    def analyze_simple_literal_type(self, rvalue: Expression, is_final: bool) -> Type | None:\n        \"\"\"Return builtins.int if rvalue is an int literal, etc.\n\n        If this is a 'Final' context, we return \"Literal[...]\" instead.\n        \"\"\"\n        if self.function_stack:\n            # Skip inside a function; this is to avoid confusing\n            # the code that handles dead code due to isinstance()\n            # inside type variables with value restrictions (like\n            # AnyStr).\n            return None\n\n        value = constant_fold_expr(rvalue, self.cur_mod_id)\n        if value is None or isinstance(value, complex):\n            return None\n\n        if isinstance(value, bool):\n            type_name = \"builtins.bool\"\n        elif isinstance(value, int):\n            type_name = \"builtins.int\"\n        elif isinstance(value, str):\n            type_name = \"builtins.str\"\n        elif isinstance(value, float):\n            type_name = \"builtins.float\"\n\n        typ = self.named_type_or_none(type_name)\n        if typ and is_final:\n            return typ.copy_modified(last_known_value=LiteralType(value=value, fallback=typ))\n        return typ\n\n    def analyze_alias(\n        self,\n        name: str,\n        rvalue: Expression,\n        allow_placeholder: bool = False,\n        declared_type_vars: TypeVarLikeList | None = None,\n        all_declared_type_params_names: list[str] | None = None,\n        python_3_12_type_alias: bool = False,\n    ) -> tuple[Type | None, list[TypeVarLikeType], set[str], bool]:\n        \"\"\"Check if 'rvalue' is a valid type allowed for aliasing (e.g. not a type variable).\n\n        If yes, return the corresponding type, a list of type variables for generic aliases,\n        a set of names the alias depends on, and True if the original type has empty tuple index.\n        An example for the dependencies:\n            A = int\n            B = str\n            analyze_alias(dict[A, B])[2] == {'__main__.A', '__main__.B'}\n        \"\"\"\n        dynamic = bool(self.function_stack and self.function_stack[-1].is_dynamic())\n        global_scope = not self.type and not self.function_stack\n        try:\n            typ = expr_to_unanalyzed_type(\n                rvalue, self.options, self.is_stub_file, lookup_qualified=self.lookup_qualified\n            )\n        except TypeTranslationError:\n            self.fail(\n                \"Invalid type alias: expression is not a valid type\", rvalue, code=codes.VALID_TYPE\n            )\n            return None, [], set(), False\n\n        found_type_vars = self.find_type_var_likes(typ)\n        namespace = self.qualified_name(name)\n        alias_type_vars = found_type_vars if declared_type_vars is None else declared_type_vars\n        with self.tvar_scope_frame(self.tvar_scope.class_frame(namespace)):\n            tvar_defs = self.tvar_defs_from_tvars(alias_type_vars, typ)\n\n            if python_3_12_type_alias:\n                with self.allow_unbound_tvars_set():\n                    rvalue.accept(self)\n\n            analyzed, depends_on = analyze_type_alias(\n                typ,\n                self,\n                self.tvar_scope,\n                self.plugin,\n                self.options,\n                self.cur_mod_node,\n                self.is_typeshed_stub_file,\n                allow_placeholder=allow_placeholder,\n                in_dynamic_func=dynamic,\n                global_scope=global_scope,\n                allowed_alias_tvars=tvar_defs,\n                alias_type_params_names=all_declared_type_params_names,\n                python_3_12_type_alias=python_3_12_type_alias,\n            )\n\n        # There can be only one variadic variable at most, the error is reported elsewhere.\n        new_tvar_defs = []\n        variadic = False\n        for td in tvar_defs:\n            if isinstance(td, TypeVarTupleType):\n                if variadic:\n                    continue\n                variadic = True\n            new_tvar_defs.append(td)\n\n        indexed = bool(isinstance(typ, UnboundType) and (typ.args or typ.empty_tuple_index))\n        return analyzed, new_tvar_defs, depends_on, indexed\n\n    def is_pep_613(self, s: AssignmentStmt) -> bool:\n        if s.unanalyzed_type is not None and isinstance(s.unanalyzed_type, UnboundType):\n            lookup = self.lookup_qualified(s.unanalyzed_type.name, s, suppress_errors=True)\n            if lookup and lookup.fullname in TYPE_ALIAS_NAMES:\n                return True\n        return False\n\n    def check_and_set_up_type_alias(self, s: AssignmentStmt) -> bool:\n        \"\"\"Check if assignment creates a type alias and set it up as needed.\n\n        Return True if it is a type alias (even if the target is not ready),\n        or False otherwise.\n\n        Note: the resulting types for subscripted (including generic) aliases\n        are also stored in rvalue.analyzed.\n        \"\"\"\n        if s.invalid_recursive_alias:\n            return True\n        lvalue = s.lvalues[0]\n        if len(s.lvalues) > 1 or not isinstance(lvalue, NameExpr):\n            # First rule: Only simple assignments like Alias = ... create aliases.\n            return False\n\n        pep_613 = self.is_pep_613(s)\n        if not pep_613 and s.unanalyzed_type is not None:\n            # Second rule: Explicit type (cls: Type[A] = A) always creates variable, not alias.\n            # unless using PEP 613 `cls: TypeAlias = A`\n            return False\n\n        # It can be `A = TypeAliasType('A', ...)` call, in this case,\n        # we just take the second argument and analyze it:\n        type_params: TypeVarLikeList | None\n        all_type_params_names: list[str] | None\n        if self.check_type_alias_type_call(s.rvalue, name=lvalue.name):\n            rvalue = (\n                s.rvalue.args[1]\n                if s.rvalue.arg_kinds[1] == ARG_POS\n                else s.rvalue.args[s.rvalue.arg_names.index(\"value\")]\n            )\n            pep_695 = True\n            type_params, all_type_params_names = self.analyze_type_alias_type_params(s.rvalue)\n        else:\n            rvalue = s.rvalue\n            pep_695 = False\n            type_params = None\n            all_type_params_names = None\n\n        if isinstance(rvalue, CallExpr) and rvalue.analyzed:\n            return False\n\n        existing = self.current_symbol_table().get(lvalue.name)\n        # Third rule: type aliases can't be re-defined. For example:\n        #     A: Type[float] = int\n        #     A = float  # OK, but this doesn't define an alias\n        #     B = int\n        #     B = float  # Error!\n        # Don't create an alias in these cases:\n        if existing and (\n            isinstance(existing.node, Var)  # existing variable\n            or (isinstance(existing.node, TypeAlias) and not s.is_alias_def)  # existing alias\n            or (isinstance(existing.node, PlaceholderNode) and existing.node.node.line < s.line)\n        ):  # previous incomplete definition\n            # TODO: find a more robust way to track the order of definitions.\n            # Note: if is_alias_def=True, this is just a node from previous iteration.\n            if isinstance(existing.node, TypeAlias) and not s.is_alias_def:\n                self.fail(\n                    'Cannot assign multiple types to name \"{}\"'\n                    ' without an explicit \"type[...]\" annotation'.format(lvalue.name),\n                    lvalue,\n                )\n            return False\n\n        non_global_scope = self.type or self.is_func_scope()\n        if not pep_613 and not pep_695 and isinstance(rvalue, RefExpr) and non_global_scope:\n            # Fourth rule (special case): Non-subscripted right hand side creates a variable\n            # at class and function scopes. For example:\n            #\n            #   class Model:\n            #       ...\n            #   class C:\n            #       model = Model # this is automatically a variable with type 'Type[Model]'\n            #\n            # without this rule, this typical use case will require a lot of explicit\n            # annotations (see the second rule).\n            return False\n        if not pep_613 and not pep_695 and not self.can_be_type_alias(rvalue):\n            return False\n\n        if existing and not isinstance(existing.node, (PlaceholderNode, TypeAlias)):\n            # Cannot redefine existing node as type alias.\n            return False\n\n        res: Type | None = None\n        if self.is_none_alias(rvalue):\n            res = NoneType()\n            alias_tvars: list[TypeVarLikeType] = []\n            depends_on: set[str] = set()\n            indexed = False\n        else:\n            tag = self.track_incomplete_refs()\n            res, alias_tvars, depends_on, indexed = self.analyze_alias(\n                lvalue.name,\n                rvalue,\n                allow_placeholder=True,\n                declared_type_vars=type_params,\n                all_declared_type_params_names=all_type_params_names,\n            )\n            if not res:\n                return False\n            if not self.is_func_scope():\n                # Only marking incomplete for top-level placeholders makes recursive aliases like\n                # `A = Sequence[str | A]` valid here, similar to how we treat base classes in class\n                # definitions, allowing `class str(Sequence[str]): ...`\n                incomplete_target = isinstance(res, ProperType) and isinstance(\n                    res, PlaceholderType\n                )\n            else:\n                incomplete_target = has_placeholder(res)\n            if self.found_incomplete_ref(tag) or incomplete_target:\n                # Since we have got here, we know this must be a type alias (incomplete refs\n                # may appear in nested positions), therefore use becomes_typeinfo=True.\n                self.mark_incomplete(lvalue.name, rvalue, becomes_typeinfo=True)\n                return True\n        self.add_type_alias_deps(depends_on)\n        check_for_explicit_any(res, self.options, self.is_typeshed_stub_file, self.msg, context=s)\n        # When this type alias gets \"inlined\", the Any is not explicit anymore,\n        # so we need to replace it with non-explicit Anys.\n        res = make_any_non_explicit(res)\n        if self.options.disallow_any_unimported and has_any_from_unimported_type(res):\n            # Only show error message once, when the type is fully analyzed.\n            if not has_placeholder(res):\n                self.msg.unimported_type_becomes_any(\"Type alias target\", res, s)\n                res = make_any_non_unimported(res)\n        # Note: with the new (lazy) type alias representation we only need to set no_args to True\n        # if the expected number of arguments is non-zero, so that aliases like `A = List` work\n        # but not aliases like `A = TypeAliasType(\"A\", List)` as these need explicit type params.\n        # However, eagerly expanding aliases like Text = str is a nice performance optimization.\n        no_args = (\n            isinstance(res, ProperType)\n            and isinstance(res, Instance)\n            and not pep_695\n            and not indexed\n        )\n        if isinstance(res, ProperType) and isinstance(res, Instance):\n            if not validate_instance(res, self.fail, indexed):\n                fix_instance(res, self.fail, self.note, disallow_any=False, options=self.options)\n        # Aliases defined within functions can't be accessed outside\n        # the function, since the symbol table will no longer\n        # exist. Work around by expanding them eagerly when used.\n        eager = self.is_func_scope()\n        alias_node = TypeAlias(\n            res,\n            self.qualified_name(lvalue.name),\n            self.cur_mod_id,\n            s.line,\n            s.column,\n            alias_tvars=alias_tvars,\n            no_args=no_args,\n            eager=eager,\n            python_3_12_type_alias=pep_695,\n        )\n        if isinstance(s.rvalue, (IndexExpr, CallExpr, OpExpr)) and (\n            not isinstance(rvalue, OpExpr)\n            or (self.options.python_version >= (3, 10) or self.is_stub_file)\n        ):\n            # Note: CallExpr is for \"void = type(None)\" and OpExpr is for \"X | Y\" union syntax.\n            if not isinstance(s.rvalue.analyzed, TypeAliasExpr):\n                # Any existing node will be updated in-place below.\n                s.rvalue.analyzed = TypeAliasExpr(alias_node)\n            s.rvalue.analyzed.line = s.line\n            # we use the column from resulting target, to get better location for errors\n            s.rvalue.analyzed.column = res.column\n        elif isinstance(s.rvalue, RefExpr):\n            s.rvalue.is_alias_rvalue = True\n\n        if existing:\n            # An alias gets updated.\n            updated = False\n            if isinstance(existing.node, TypeAlias):\n                if existing.node.target != res:\n                    # Copy expansion to the existing alias, this matches how we update base classes\n                    # for a TypeInfo _in place_ if there are nested placeholders.\n                    existing.node.target = res\n                    existing.node.alias_tvars = alias_tvars\n                    existing.node.no_args = no_args\n                    updated = True\n                    # Invalidate recursive status cache in case it was previously set.\n                    existing.node._is_recursive = None\n            else:\n                # Otherwise just replace existing placeholder with type alias.\n                existing.node = alias_node\n                updated = True\n            if updated:\n                if self.final_iteration:\n                    self.cannot_resolve_name(lvalue.name, \"name\", s)\n                    return True\n                else:\n                    # We need to defer so that this change can get propagated to base classes.\n                    self.defer(s, force_progress=True)\n        else:\n            self.add_symbol(lvalue.name, alias_node, s)\n        if isinstance(rvalue, RefExpr) and isinstance(rvalue.node, TypeAlias):\n            alias_node.normalized = rvalue.node.normalized\n        current_node = existing.node if existing else alias_node\n        assert isinstance(current_node, TypeAlias)\n        self.disable_invalid_recursive_aliases(s, current_node, s.rvalue)\n        if self.is_class_scope():\n            assert self.type is not None\n            if self.type.is_protocol:\n                self.fail(\"Type aliases are prohibited in protocol bodies\", s)\n                if not lvalue.name[0].isupper():\n                    self.note(\"Use variable annotation syntax to define protocol members\", s)\n        return True\n\n    def check_type_alias_type_call(self, rvalue: Expression, *, name: str) -> TypeGuard[CallExpr]:\n        if not isinstance(rvalue, CallExpr):\n            return False\n\n        names = [\"typing_extensions.TypeAliasType\"]\n        if self.options.python_version >= (3, 12):\n            names.append(\"typing.TypeAliasType\")\n        if not refers_to_fullname(rvalue.callee, tuple(names)):\n            return False\n        if not self.check_typevarlike_name(rvalue, name, rvalue):\n            return False\n        if rvalue.arg_kinds.count(ARG_POS) != (\n            2 - (\"value\" in rvalue.arg_names) - (\"name\" in rvalue.arg_names)\n        ):\n            return False\n\n        return True\n\n    def analyze_type_alias_type_params(\n        self, rvalue: CallExpr\n    ) -> tuple[TypeVarLikeList, list[str]]:\n        \"\"\"Analyze type_params of TypeAliasType.\n\n        Returns declared unbound type variable expressions and a list of all declared type\n        variable names for error reporting.\n        \"\"\"\n        if \"type_params\" in rvalue.arg_names:\n            type_params_arg = rvalue.args[rvalue.arg_names.index(\"type_params\")]\n            if not isinstance(type_params_arg, TupleExpr):\n                self.fail(\n                    \"Tuple literal expected as the type_params argument to TypeAliasType\",\n                    type_params_arg,\n                )\n                return [], []\n            type_params = type_params_arg.items\n        else:\n            return [], []\n\n        declared_tvars: TypeVarLikeList = []\n        all_declared_tvar_names: list[str] = []  # includes bound type variables\n        have_type_var_tuple = False\n        for tp_expr in type_params:\n            if isinstance(tp_expr, StarExpr):\n                tp_expr.valid = False\n            self.analyze_type_expr(tp_expr)\n            try:\n                base = self.expr_to_unanalyzed_type(tp_expr)\n            except TypeTranslationError:\n                continue\n            if not isinstance(base, UnboundType):\n                continue\n\n            tag = self.track_incomplete_refs()\n            tvar = self.analyze_unbound_tvar_impl(base, is_typealias_param=True)\n            if tvar:\n                if isinstance(tvar[1], TypeVarTupleExpr):\n                    if have_type_var_tuple:\n                        self.fail(\n                            \"Can only use one TypeVarTuple in type_params argument to TypeAliasType\",\n                            base,\n                            code=codes.TYPE_VAR,\n                        )\n                        have_type_var_tuple = True\n                        continue\n                    have_type_var_tuple = True\n            elif not self.found_incomplete_ref(tag):\n                sym = self.lookup_qualified(base.name, base)\n                if sym and isinstance(sym.node, TypeVarLikeExpr):\n                    all_declared_tvar_names.append(sym.node.name)  # Error will be reported later\n                else:\n                    self.fail(\n                        \"Free type variable expected in type_params argument to TypeAliasType\",\n                        base,\n                        code=codes.TYPE_VAR,\n                    )\n                    if sym and sym.fullname in UNPACK_TYPE_NAMES:\n                        self.note(\n                            \"Don't Unpack type variables in type_params\", base, code=codes.TYPE_VAR\n                        )\n                continue\n            if tvar in declared_tvars:\n                self.fail(\n                    f'Duplicate type variable \"{tvar[0]}\" in type_params argument to TypeAliasType',\n                    base,\n                    code=codes.TYPE_VAR,\n                )\n                continue\n            if tvar:\n                all_declared_tvar_names.append(tvar[0])\n                declared_tvars.append(tvar)\n        return declared_tvars, all_declared_tvar_names\n\n    def disable_invalid_recursive_aliases(\n        self, s: AssignmentStmt | TypeAliasStmt, current_node: TypeAlias, ctx: Context\n    ) -> None:\n        \"\"\"Prohibit and fix recursive type aliases that are invalid/unsupported.\"\"\"\n        messages = []\n        if (\n            isinstance(current_node.target, TypeAliasType)\n            and current_node.target.alias is current_node\n        ):\n            # We want to have consistent error messages, but not calling name_not_defined(),\n            # since it will do a bunch of unrelated things we don't want here.\n            messages.append(\n                f'Cannot resolve name \"{current_node.name}\" (possible cyclic definition)'\n            )\n        elif is_invalid_recursive_alias({current_node}, current_node.target):\n            target = (\n                \"tuple\" if isinstance(get_proper_type(current_node.target), TupleType) else \"union\"\n            )\n            messages.append(f\"Invalid recursive alias: a {target} item of itself\")\n        if detect_diverging_alias(\n            current_node, current_node.target, self.lookup_qualified, self.tvar_scope\n        ):\n            messages.append(\"Invalid recursive alias: type variable nesting on right hand side\")\n        if messages:\n            current_node.target = AnyType(TypeOfAny.from_error)\n            s.invalid_recursive_alias = True\n        for msg in messages:\n            self.fail(msg, ctx)\n\n    def analyze_lvalue(\n        self,\n        lval: Lvalue,\n        nested: bool = False,\n        explicit_type: bool = False,\n        is_final: bool = False,\n        escape_comprehensions: bool = False,\n        has_explicit_value: bool = False,\n        is_index_var: bool = False,\n    ) -> None:\n        \"\"\"Analyze an lvalue or assignment target.\n\n        Args:\n            lval: The target lvalue\n            nested: If true, the lvalue is within a tuple or list lvalue expression\n            explicit_type: Assignment has type annotation\n            escape_comprehensions: If we are inside a comprehension, set the variable\n                in the enclosing scope instead. This implements\n                https://www.python.org/dev/peps/pep-0572/#scope-of-the-target\n            is_index_var: If lval is the index variable in a for loop\n        \"\"\"\n        if escape_comprehensions:\n            assert isinstance(lval, NameExpr), \"assignment expression target must be NameExpr\"\n        if isinstance(lval, NameExpr):\n            self.analyze_name_lvalue(\n                lval,\n                explicit_type,\n                is_final,\n                escape_comprehensions,\n                has_explicit_value=has_explicit_value,\n                is_index_var=is_index_var,\n            )\n        elif isinstance(lval, MemberExpr):\n            self.analyze_member_lvalue(lval, explicit_type, is_final, has_explicit_value)\n            if explicit_type and not self.is_self_member_ref(lval):\n                self.fail(\"Type cannot be declared in assignment to non-self attribute\", lval)\n        elif isinstance(lval, IndexExpr):\n            if explicit_type:\n                self.fail(\"Unexpected type declaration\", lval)\n            lval.accept(self)\n        elif isinstance(lval, TupleExpr):\n            self.analyze_tuple_or_list_lvalue(lval, explicit_type)\n        elif isinstance(lval, StarExpr):\n            if nested:\n                self.analyze_lvalue(lval.expr, nested, explicit_type)\n            else:\n                self.fail(\"Starred assignment target must be in a list or tuple\", lval)\n        else:\n            self.fail(\"Invalid assignment target\", lval)\n\n    def analyze_name_lvalue(\n        self,\n        lvalue: NameExpr,\n        explicit_type: bool,\n        is_final: bool,\n        escape_comprehensions: bool,\n        has_explicit_value: bool,\n        is_index_var: bool,\n    ) -> None:\n        \"\"\"Analyze an lvalue that targets a name expression.\n\n        Arguments are similar to \"analyze_lvalue\".\n        \"\"\"\n        if lvalue.node:\n            # This has been bound already in a previous iteration.\n            return\n\n        name = lvalue.name\n        if self.is_alias_for_final_name(name):\n            if is_final:\n                self.fail(\"Cannot redefine an existing name as final\", lvalue)\n            else:\n                self.msg.cant_assign_to_final(name, self.type is not None, lvalue)\n\n        kind = self.current_symbol_kind()\n        names = self.current_symbol_table(escape_comprehensions=escape_comprehensions)\n        existing = names.get(name)\n\n        outer = self.is_global_or_nonlocal(name)\n        if (\n            kind == MDEF\n            and isinstance(self.type, TypeInfo)\n            and self.type.is_enum\n            and not name.startswith(\"__\")\n        ):\n            # Special case: we need to be sure that `Enum` keys are unique.\n            if existing is not None and not isinstance(existing.node, PlaceholderNode):\n                self.fail(\n                    'Attempted to reuse member name \"{}\" in Enum definition \"{}\"'.format(\n                        name, self.type.name\n                    ),\n                    lvalue,\n                )\n\n            if explicit_type and has_explicit_value:\n                self.fail(\"Enum members must be left unannotated\", lvalue)\n                self.note(\n                    \"See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members\",\n                    lvalue,\n                )\n\n        if (not existing or isinstance(existing.node, PlaceholderNode)) and not outer:\n            # Define new variable.\n            var = self.make_name_lvalue_var(\n                lvalue, kind, not explicit_type, has_explicit_value, is_index_var\n            )\n            added = self.add_symbol(name, var, lvalue, escape_comprehensions=escape_comprehensions)\n            # Only bind expression if we successfully added name to symbol table.\n            if added:\n                lvalue.is_new_def = True\n                lvalue.is_inferred_def = True\n                lvalue.kind = kind\n                lvalue.node = var\n                if kind == GDEF:\n                    lvalue.fullname = var._fullname\n                else:\n                    lvalue.fullname = lvalue.name\n                if self.is_func_scope():\n                    if unmangle(name) == \"_\" and not self.options.allow_redefinition_new:\n                        # Special case for assignment to local named '_': always infer 'Any'.\n                        # This isn't needed with --allow-redefinition-new, since arbitrary\n                        # types can be assigned to '_' anyway.\n                        typ = AnyType(TypeOfAny.special_form)\n                        self.store_declared_types(lvalue, typ)\n            if is_final and self.is_final_redefinition(kind, name):\n                self.fail(\"Cannot redefine an existing name as final\", lvalue)\n        else:\n            self.make_name_lvalue_point_to_existing_def(lvalue, explicit_type, is_final)\n\n    def is_final_redefinition(self, kind: int, name: str) -> bool:\n        if kind == GDEF:\n            return self.is_mangled_global(name) and not self.is_initial_mangled_global(name)\n        elif kind == MDEF and self.type:\n            return unmangle(name) + \"'\" in self.type.names\n        return False\n\n    def is_alias_for_final_name(self, name: str) -> bool:\n        if self.is_func_scope():\n            if not name.endswith(\"'\"):\n                # Not a mangled name -- can't be an alias\n                return False\n            name = unmangle(name)\n            assert self.locals[-1] is not None, \"No locals at function scope\"\n            existing = self.locals[-1].get(name)\n            return existing is not None and is_final_node(existing.node)\n        elif self.type is not None:\n            orig_name = unmangle(name) + \"'\"\n            if name == orig_name:\n                return False\n            existing = self.type.names.get(orig_name)\n            return existing is not None and is_final_node(existing.node)\n        else:\n            orig_name = unmangle(name) + \"'\"\n            if name == orig_name:\n                return False\n            existing = self.globals.get(orig_name)\n            return existing is not None and is_final_node(existing.node)\n\n    def make_name_lvalue_var(\n        self,\n        lvalue: NameExpr,\n        kind: int,\n        inferred: bool,\n        has_explicit_value: bool,\n        is_index_var: bool,\n    ) -> Var:\n        \"\"\"Return a Var node for an lvalue that is a name expression.\"\"\"\n        name = lvalue.name\n        v = Var(name)\n        v.set_line(lvalue)\n        v.is_inferred = inferred\n        if kind == MDEF:\n            assert self.type is not None\n            v.info = self.type\n            v.is_initialized_in_class = True\n            v.allow_incompatible_override = name in ALLOW_INCOMPATIBLE_OVERRIDE\n        if kind != LDEF:\n            v._fullname = self.qualified_name(name)\n        else:\n            # fullname should never stay None\n            v._fullname = name\n        v.is_ready = False  # Type not inferred yet\n        v.has_explicit_value = has_explicit_value\n        v.is_index_var = is_index_var\n        return v\n\n    def make_name_lvalue_point_to_existing_def(\n        self, lval: NameExpr, explicit_type: bool, is_final: bool\n    ) -> None:\n        \"\"\"Update an lvalue to point to existing definition in the same scope.\n\n        Arguments are similar to \"analyze_lvalue\".\n\n        Assume that an existing name exists.\n        \"\"\"\n        if is_final:\n            # Redefining an existing name with final is always an error.\n            self.fail(\"Cannot redefine an existing name as final\", lval)\n        original_def = self.lookup(lval.name, lval, suppress_errors=True)\n        if original_def is None and self.type and not self.is_func_scope():\n            # Workaround to allow \"x, x = ...\" in class body.\n            original_def = self.type.get(lval.name)\n        if explicit_type:\n            # Don't re-bind if there is a type annotation.\n            self.name_already_defined(lval.name, lval, original_def)\n        else:\n            # Bind to an existing name.\n            if original_def:\n                self.bind_name_expr(lval, original_def)\n            else:\n                self.name_not_defined(lval.name, lval)\n            self.check_lvalue_validity(lval.node, lval)\n\n        if self.scope.functions and lval.name in self.global_decls[-1]:\n            # Technically, we only need to set this if original r.h.s. would be inferred\n            # as None, but it is tricky to detect reliably during semantic analysis.\n            if (\n                original_def\n                and isinstance(original_def.node, Var)\n                and original_def.node.is_inferred\n            ):\n                for func in self.scope.functions:\n                    func.def_or_infer_vars = True\n\n    def analyze_tuple_or_list_lvalue(self, lval: TupleExpr, explicit_type: bool = False) -> None:\n        \"\"\"Analyze an lvalue or assignment target that is a list or tuple.\"\"\"\n        items = lval.items\n        star_exprs = [item for item in items if isinstance(item, StarExpr)]\n\n        if len(star_exprs) > 1:\n            self.fail(\"Two starred expressions in assignment\", lval)\n        else:\n            if len(star_exprs) == 1:\n                star_exprs[0].valid = True\n            for i in items:\n                self.analyze_lvalue(\n                    lval=i,\n                    nested=True,\n                    explicit_type=explicit_type,\n                    # Lists and tuples always have explicit values defined:\n                    # `a, b, c = value`\n                    has_explicit_value=True,\n                )\n\n    def analyze_member_lvalue(\n        self, lval: MemberExpr, explicit_type: bool, is_final: bool, has_explicit_value: bool\n    ) -> None:\n        \"\"\"Analyze lvalue that is a member expression.\n\n        Arguments:\n            lval: The target lvalue\n            explicit_type: Assignment has type annotation\n            is_final: Is the target final\n        \"\"\"\n        if lval.node:\n            # This has been bound already in a previous iteration.\n            return\n        lval.accept(self)\n        if self.is_self_member_ref(lval):\n            assert self.type, \"Self member outside a class\"\n            cur_node = self.type.names.get(lval.name)\n            node = self.type.get(lval.name)\n            if cur_node and is_final:\n                # Overrides will be checked in type checker.\n                self.fail(\"Cannot redefine an existing name as final\", lval)\n            # On first encounter with this definition, if this attribute was defined before\n            # with an inferred type and it's marked with an explicit type now, give an error.\n            if (\n                not lval.node\n                and cur_node\n                and isinstance(cur_node.node, Var)\n                and cur_node.node.is_inferred\n                and explicit_type\n            ):\n                self.attribute_already_defined(lval.name, lval, cur_node)\n            if self.type.is_protocol and has_explicit_value and cur_node is not None:\n                # Make this variable non-abstract, it would be safer to do this only if we\n                # are inside __init__, but we do this always to preserve historical behaviour.\n                if isinstance(cur_node.node, Var):\n                    cur_node.node.is_abstract_var = False\n            if (\n                # If the attribute of self is not defined, create a new Var, ...\n                node is None\n                # ... or if it is defined as abstract in a *superclass*.\n                or (cur_node is None and isinstance(node.node, Var) and node.node.is_abstract_var)\n                # ... also an explicit declaration on self also creates a new Var.\n                # Note that `explicit_type` might have been erased for bare `Final`,\n                # so we also check if `is_final` is passed.\n                or (cur_node is None and (explicit_type or is_final))\n            ):\n                if self.type.is_protocol and node is None:\n                    self.fail(\"Protocol members cannot be defined via assignment to self\", lval)\n                else:\n                    # Implicit attribute definition in __init__.\n                    lval.is_new_def = True\n                    lval.is_inferred_def = True\n                    v = Var(lval.name)\n                    v.set_line(lval)\n                    v._fullname = self.qualified_name(lval.name)\n                    v.info = self.type\n                    v.is_ready = False\n                    v.explicit_self_type = explicit_type or is_final\n                    lval.def_var = v\n                    lval.node = v\n                    # TODO: should we also set lval.kind = MDEF?\n                    self.type.names[lval.name] = SymbolTableNode(MDEF, v, implicit=True)\n                    for func in self.scope.functions:\n                        func.def_or_infer_vars = True\n            if (\n                cur_node\n                and isinstance(cur_node.node, Var)\n                and cur_node.node.is_inferred\n                and cur_node.node.is_initialized_in_class\n            ):\n                for func in self.scope.functions:\n                    func.def_or_infer_vars = True\n        self.check_lvalue_validity(lval.node, lval)\n\n    def is_self_member_ref(self, memberexpr: MemberExpr) -> bool:\n        \"\"\"Does memberexpr to refer to an attribute of self?\"\"\"\n        if not isinstance(memberexpr.expr, NameExpr):\n            return False\n        node = memberexpr.expr.node\n        return isinstance(node, Var) and node.is_self\n\n    def check_lvalue_validity(self, node: Expression | SymbolNode | None, ctx: Context) -> None:\n        if isinstance(node, TypeVarExpr):\n            self.fail(\"Invalid assignment target\", ctx)\n        elif isinstance(node, TypeInfo):\n            self.fail(message_registry.CANNOT_ASSIGN_TO_TYPE, ctx)\n\n    def store_declared_types(self, lvalue: Lvalue, typ: Type) -> None:\n        if isinstance(lvalue, RefExpr):\n            lvalue.is_inferred_def = False\n            if isinstance(lvalue.node, Var):\n                var = lvalue.node\n                var.type = typ\n                var.is_ready = True\n                typ = get_proper_type(typ)\n                if (\n                    var.is_final\n                    and isinstance(typ, Instance)\n                    and typ.last_known_value\n                    and (not self.type or not self.type.is_enum)\n                ):\n                    var.final_value = typ.last_known_value.value\n            # If node is not a variable, we'll catch it elsewhere.\n        elif isinstance(lvalue, TupleExpr):\n            typ = get_proper_type(typ)\n            if isinstance(typ, TupleType):\n                if len(lvalue.items) != len(typ.items):\n                    self.fail(\"Incompatible number of tuple items\", lvalue)\n                    return\n                for item, itemtype in zip(lvalue.items, typ.items):\n                    self.store_declared_types(item, itemtype)\n            else:\n                self.fail(\"Tuple type expected for multiple variables\", lvalue)\n        elif isinstance(lvalue, StarExpr):\n            # Historical behavior for the old parser\n            self.store_declared_types(lvalue.expr, typ)\n        else:\n            # This has been flagged elsewhere as an error, so just ignore here.\n            pass\n\n    def process_typevar_declaration(self, s: AssignmentStmt) -> bool:\n        \"\"\"Check if s declares a TypeVar; it yes, store it in symbol table.\n\n        Return True if this looks like a type variable declaration (but maybe\n        with errors), otherwise return False.\n        \"\"\"\n        call = self.get_typevarlike_declaration(s, (\"typing.TypeVar\", \"typing_extensions.TypeVar\"))\n        if not call:\n            return False\n\n        name = self.extract_typevarlike_name(s, call)\n        if name is None:\n            return False\n\n        # Constraining types\n        n_values = call.arg_kinds[1:].count(ARG_POS)\n        values = self.analyze_value_types(call.args[1 : 1 + n_values])\n\n        res = self.process_typevar_parameters(\n            call.args[1 + n_values :],\n            call.arg_names[1 + n_values :],\n            call.arg_kinds[1 + n_values :],\n            n_values,\n            s,\n        )\n        if res is None:\n            return False\n        variance, upper_bound, default = res\n\n        existing = self.current_symbol_table().get(name)\n        if existing and not (\n            isinstance(existing.node, PlaceholderNode)\n            or\n            # Also give error for another type variable with the same name.\n            (isinstance(existing.node, TypeVarExpr) and existing.node is call.analyzed)\n        ):\n            self.fail(f'Cannot redefine \"{name}\" as a type variable', s)\n            return False\n\n        if self.options.disallow_any_unimported:\n            for idx, constraint in enumerate(values, start=1):\n                if has_any_from_unimported_type(constraint):\n                    prefix = f\"Constraint {idx}\"\n                    self.msg.unimported_type_becomes_any(prefix, constraint, s)\n\n            if has_any_from_unimported_type(upper_bound):\n                prefix = \"Upper bound of type variable\"\n                self.msg.unimported_type_becomes_any(prefix, upper_bound, s)\n\n        for t in values + [upper_bound, default]:\n            check_for_explicit_any(\n                t, self.options, self.is_typeshed_stub_file, self.msg, context=s\n            )\n\n        # mypyc suppresses making copies of a function to check each\n        # possible type, so set the upper bound to Any to prevent that\n        # from causing errors.\n        if values and self.options.mypyc:\n            upper_bound = AnyType(TypeOfAny.implementation_artifact)\n\n        # Yes, it's a valid type variable definition! Add it to the symbol table.\n        if not call.analyzed:\n            type_var = TypeVarExpr(\n                name, self.qualified_name(name), values, upper_bound, default, variance\n            )\n            type_var.line = call.line\n            call.analyzed = type_var\n            updated = True\n        else:\n            assert isinstance(call.analyzed, TypeVarExpr)\n            updated = (\n                values != call.analyzed.values\n                or upper_bound != call.analyzed.upper_bound\n                or default != call.analyzed.default\n            )\n            call.analyzed.upper_bound = upper_bound\n            call.analyzed.values = values\n            call.analyzed.default = default\n        if any(has_placeholder(v) for v in values):\n            self.process_placeholder(None, \"TypeVar values\", s, force_progress=updated)\n        elif has_placeholder(upper_bound):\n            self.process_placeholder(None, \"TypeVar upper bound\", s, force_progress=updated)\n        elif has_placeholder(default):\n            self.process_placeholder(None, \"TypeVar default\", s, force_progress=updated)\n\n        self.add_symbol(name, call.analyzed, s)\n        return True\n\n    def check_typevar_default(self, default: Type, context: Context) -> Type:\n        typ = get_proper_type(default)\n        if isinstance(typ, AnyType) and typ.is_from_error:\n            self.fail(\n                message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(\"TypeVar\", \"default\"), context\n            )\n        return default\n\n    def check_paramspec_default(self, default: Type, context: Context) -> Type:\n        typ = get_proper_type(default)\n        if isinstance(typ, Parameters):\n            for i, arg_type in enumerate(typ.arg_types):\n                arg_ptype = get_proper_type(arg_type)\n                if isinstance(arg_ptype, AnyType) and arg_ptype.is_from_error:\n                    self.fail(f\"Argument {i} of ParamSpec default must be a type\", context)\n        elif (\n            isinstance(typ, AnyType)\n            and typ.is_from_error\n            or not isinstance(typ, (AnyType, UnboundType))\n        ):\n            self.fail(\n                \"The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\",\n                context,\n            )\n            default = AnyType(TypeOfAny.from_error)\n        return default\n\n    def check_typevartuple_default(self, default: Type, context: Context) -> Type:\n        typ = get_proper_type(default)\n        if not isinstance(typ, UnpackType):\n            self.fail(\"The default argument to TypeVarTuple must be an Unpacked tuple\", context)\n            default = AnyType(TypeOfAny.from_error)\n        return default\n\n    def check_typevarlike_name(self, call: CallExpr, name: str, context: Context) -> bool:\n        \"\"\"Checks that the name of a TypeVar or ParamSpec matches its variable.\"\"\"\n        name = unmangle(name)\n        assert isinstance(call.callee, RefExpr)\n        typevarlike_type = (\n            call.callee.name if isinstance(call.callee, NameExpr) else call.callee.fullname\n        )\n        if len(call.args) < 1:\n            self.fail(f\"Too few arguments for {typevarlike_type}()\", context)\n            return False\n        if not isinstance(call.args[0], StrExpr) or call.arg_kinds[0] != ARG_POS:\n            self.fail(f\"{typevarlike_type}() expects a string literal as first argument\", context)\n            return False\n        elif call.args[0].value != name:\n            msg = 'String argument 1 \"{}\" to {}(...) does not match variable name \"{}\"'\n            self.fail(msg.format(call.args[0].value, typevarlike_type, name), context)\n            return False\n        return True\n\n    def get_typevarlike_declaration(\n        self, s: AssignmentStmt, typevarlike_types: tuple[str, ...]\n    ) -> CallExpr | None:\n        \"\"\"Returns the call expression if `s` is a declaration of `typevarlike_type`\n        (TypeVar or ParamSpec), or None otherwise.\n        \"\"\"\n        if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], NameExpr):\n            return None\n        if not isinstance(s.rvalue, CallExpr):\n            return None\n        call = s.rvalue\n        callee = call.callee\n        if not isinstance(callee, RefExpr):\n            return None\n        if callee.fullname not in typevarlike_types:\n            return None\n        return call\n\n    def process_typevar_parameters(\n        self,\n        args: list[Expression],\n        names: list[str | None],\n        kinds: list[ArgKind],\n        num_values: int,\n        context: Context,\n    ) -> tuple[int, Type, Type] | None:\n        has_values = num_values > 0\n        covariant = False\n        contravariant = False\n        upper_bound: Type = self.object_type()\n        default: Type = AnyType(TypeOfAny.from_omitted_generics)\n        for param_value, param_name, param_kind in zip(args, names, kinds):\n            if not param_kind.is_named():\n                self.fail(message_registry.TYPEVAR_UNEXPECTED_ARGUMENT, context)\n                return None\n            if param_name == \"covariant\":\n                if isinstance(param_value, NameExpr) and param_value.name in (\"True\", \"False\"):\n                    covariant = param_value.name == \"True\"\n                else:\n                    self.fail(message_registry.TYPEVAR_VARIANCE_DEF.format(\"covariant\"), context)\n                    return None\n            elif param_name == \"contravariant\":\n                if isinstance(param_value, NameExpr) and param_value.name in (\"True\", \"False\"):\n                    contravariant = param_value.name == \"True\"\n                else:\n                    self.fail(\n                        message_registry.TYPEVAR_VARIANCE_DEF.format(\"contravariant\"), context\n                    )\n                    return None\n            elif param_name == \"bound\":\n                if has_values:\n                    self.fail(\"TypeVar cannot have both values and an upper bound\", context)\n                    return None\n                tv_arg = self.get_typevarlike_argument(\"TypeVar\", param_name, param_value, context)\n                if tv_arg is None:\n                    return None\n                upper_bound = tv_arg\n            elif param_name == \"default\":\n                tv_arg = self.get_typevarlike_argument(\n                    \"TypeVar\", param_name, param_value, context, allow_unbound_tvars=True\n                )\n                default = tv_arg or AnyType(TypeOfAny.from_error)\n            elif param_name == \"values\":\n                # Probably using obsolete syntax with values=(...). Explain the current syntax.\n                self.fail('TypeVar \"values\" argument not supported', context)\n                self.fail(\n                    \"Use TypeVar('T', t, ...) instead of TypeVar('T', values=(t, ...))\", context\n                )\n                return None\n            else:\n                self.fail(\n                    f'{message_registry.TYPEVAR_UNEXPECTED_ARGUMENT}: \"{param_name}\"', context\n                )\n                return None\n\n        if covariant and contravariant:\n            self.fail(\"TypeVar cannot be both covariant and contravariant\", context)\n            return None\n        elif num_values == 1:\n            self.fail(message_registry.TYPE_VAR_TOO_FEW_CONSTRAINED_TYPES, context)\n            return None\n        elif covariant:\n            variance = COVARIANT\n        elif contravariant:\n            variance = CONTRAVARIANT\n        else:\n            variance = INVARIANT\n        return variance, upper_bound, default\n\n    def get_typevarlike_argument(\n        self,\n        typevarlike_name: str,\n        param_name: str,\n        param_value: Expression,\n        context: Context,\n        *,\n        allow_unbound_tvars: bool = False,\n        allow_param_spec_literals: bool = False,\n        allow_unpack: bool = False,\n        report_invalid_typevar_arg: bool = True,\n    ) -> ProperType | None:\n        try:\n            # We want to use our custom error message below, so we suppress\n            # the default error message for invalid types here.\n            analyzed = self.expr_to_analyzed_type(\n                param_value,\n                allow_placeholder=True,\n                report_invalid_types=False,\n                allow_unbound_tvars=allow_unbound_tvars,\n                allow_param_spec_literals=allow_param_spec_literals,\n                allow_unpack=allow_unpack,\n            )\n            if analyzed is None:\n                # Type variables are special: we need to place them in the symbol table\n                # soon, even if upper bound is not ready yet. Otherwise, avoiding\n                # a \"deadlock\" in this common pattern would be tricky:\n                #     T = TypeVar('T', bound=Custom[Any])\n                #     class Custom(Generic[T]):\n                #         ...\n                analyzed = PlaceholderType(None, [], context.line)\n            typ = get_proper_type(analyzed)\n            if report_invalid_typevar_arg and isinstance(typ, AnyType) and typ.is_from_error:\n                self.fail(\n                    message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(typevarlike_name, param_name),\n                    param_value,\n                )\n                # Note: we do not return 'None' here -- we want to continue\n                # using the AnyType.\n            return typ\n        except TypeTranslationError:\n            if report_invalid_typevar_arg:\n                self.fail(\n                    message_registry.TYPEVAR_ARG_MUST_BE_TYPE.format(typevarlike_name, param_name),\n                    param_value,\n                )\n            return None\n\n    def extract_typevarlike_name(self, s: AssignmentStmt, call: CallExpr) -> str | None:\n        if not call:\n            return None\n\n        lvalue = s.lvalues[0]\n        assert isinstance(lvalue, NameExpr)\n        if s.type:\n            self.fail(\"Cannot declare the type of a TypeVar or similar construct\", s)\n            return None\n\n        if not self.check_typevarlike_name(call, lvalue.name, s):\n            return None\n        return lvalue.name\n\n    def process_paramspec_declaration(self, s: AssignmentStmt) -> bool:\n        \"\"\"Checks if s declares a ParamSpec; if yes, store it in symbol table.\n\n        Return True if this looks like a ParamSpec (maybe with errors), otherwise return False.\n\n        In the future, ParamSpec may accept bounds and variance arguments, in which\n        case more aggressive sharing of code with process_typevar_declaration should be pursued.\n        \"\"\"\n        call = self.get_typevarlike_declaration(\n            s, (\"typing_extensions.ParamSpec\", \"typing.ParamSpec\")\n        )\n        if not call:\n            return False\n\n        name = self.extract_typevarlike_name(s, call)\n        if name is None:\n            return False\n\n        n_values = call.arg_kinds[1:].count(ARG_POS)\n        if n_values != 0:\n            self.fail('Too many positional arguments for \"ParamSpec\"', s)\n\n        default: Type = AnyType(TypeOfAny.from_omitted_generics)\n        for param_value, param_name in zip(\n            call.args[1 + n_values :], call.arg_names[1 + n_values :]\n        ):\n            if param_name == \"default\":\n                tv_arg = self.get_typevarlike_argument(\n                    \"ParamSpec\",\n                    param_name,\n                    param_value,\n                    s,\n                    allow_unbound_tvars=True,\n                    allow_param_spec_literals=True,\n                    report_invalid_typevar_arg=False,\n                )\n                default = tv_arg or AnyType(TypeOfAny.from_error)\n                default = self.check_paramspec_default(default, param_value)\n            else:\n                # ParamSpec is different from a regular TypeVar:\n                # arguments are not semantically valid. But, allowed in runtime.\n                # So, we need to warn users about possible invalid usage.\n                self.fail(\n                    \"The variance and bound arguments to ParamSpec do not have defined semantics yet\",\n                    s,\n                )\n\n        # PEP 612 reserves the right to define bound, covariant and contravariant arguments to\n        # ParamSpec in a later PEP. If and when that happens, we should do something\n        # on the lines of process_typevar_parameters\n\n        if not call.analyzed:\n            paramspec_var = ParamSpecExpr(\n                name, self.qualified_name(name), self.object_type(), default, INVARIANT\n            )\n            paramspec_var.line = call.line\n            call.analyzed = paramspec_var\n            updated = True\n        else:\n            assert isinstance(call.analyzed, ParamSpecExpr)\n            updated = default != call.analyzed.default\n            call.analyzed.default = default\n        if has_placeholder(default):\n            self.process_placeholder(None, \"ParamSpec default\", s, force_progress=updated)\n\n        self.add_symbol(name, call.analyzed, s)\n        return True\n\n    def process_typevartuple_declaration(self, s: AssignmentStmt) -> bool:\n        \"\"\"Checks if s declares a TypeVarTuple; if yes, store it in symbol table.\n\n        Return True if this looks like a TypeVarTuple (maybe with errors), otherwise return False.\n        \"\"\"\n        call = self.get_typevarlike_declaration(\n            s, (\"typing_extensions.TypeVarTuple\", \"typing.TypeVarTuple\")\n        )\n        if not call:\n            return False\n\n        n_values = call.arg_kinds[1:].count(ARG_POS)\n        if n_values != 0:\n            self.fail('Too many positional arguments for \"TypeVarTuple\"', s)\n\n        default: Type = AnyType(TypeOfAny.from_omitted_generics)\n        for param_value, param_name in zip(\n            call.args[1 + n_values :], call.arg_names[1 + n_values :]\n        ):\n            if param_name == \"default\":\n                tv_arg = self.get_typevarlike_argument(\n                    \"TypeVarTuple\",\n                    param_name,\n                    param_value,\n                    s,\n                    allow_unbound_tvars=True,\n                    report_invalid_typevar_arg=False,\n                    allow_unpack=True,\n                )\n                default = tv_arg or AnyType(TypeOfAny.from_error)\n                default = self.check_typevartuple_default(default, param_value)\n            else:\n                self.fail(f'Unexpected keyword argument \"{param_name}\" for \"TypeVarTuple\"', s)\n\n        name = self.extract_typevarlike_name(s, call)\n        if name is None:\n            return False\n\n        # PEP 646 does not specify the behavior of variance, constraints, or bounds.\n        if not call.analyzed:\n            tuple_fallback = self.named_type(\"builtins.tuple\", [self.object_type()])\n            typevartuple_var = TypeVarTupleExpr(\n                name,\n                self.qualified_name(name),\n                # Upper bound for *Ts is *tuple[object, ...], it can never be object.\n                tuple_fallback.copy_modified(),\n                tuple_fallback,\n                default,\n                INVARIANT,\n            )\n            typevartuple_var.line = call.line\n            call.analyzed = typevartuple_var\n            updated = True\n        else:\n            assert isinstance(call.analyzed, TypeVarTupleExpr)\n            updated = default != call.analyzed.default\n            call.analyzed.default = default\n        if has_placeholder(default):\n            self.process_placeholder(None, \"TypeVarTuple default\", s, force_progress=updated)\n\n        self.add_symbol(name, call.analyzed, s)\n        return True\n\n    def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo:\n        if self.is_func_scope() and not self.type and \"@\" not in name:\n            name += \"@\" + str(line)\n        class_def = ClassDef(name, Block([]))\n        if self.is_func_scope() and not self.type:\n            # Full names of generated classes should always be prefixed with the module names\n            # even if they are nested in a function, since these classes will be (de-)serialized.\n            # (Note that the caller should append @line to the name to avoid collisions.)\n            # TODO: clean this up, see #6422.\n            class_def.fullname = self.cur_mod_id + \".\" + self.qualified_name(name)\n        else:\n            class_def.fullname = self.qualified_name(name)\n\n        info = TypeInfo(SymbolTable(), class_def, self.cur_mod_id)\n        class_def.info = info\n        mro = basetype_or_fallback.type.mro\n        if not mro:\n            # Probably an error, we should not crash so generate something meaningful.\n            mro = [basetype_or_fallback.type, self.object_type().type]\n        info.mro = [info] + mro\n        info.bases = [basetype_or_fallback]\n        return info\n\n    def analyze_value_types(self, items: list[Expression]) -> list[Type]:\n        \"\"\"Analyze types from values expressions in type variable definition.\"\"\"\n        result: list[Type] = []\n        for node in items:\n            try:\n                analyzed = self.anal_type(\n                    self.expr_to_unanalyzed_type(node), allow_placeholder=True\n                )\n                if analyzed is None:\n                    # Type variables are special: we need to place them in the symbol table\n                    # soon, even if some value is not ready yet, see process_typevar_parameters()\n                    # for an example.\n                    analyzed = PlaceholderType(None, [], node.line)\n                if has_type_vars(analyzed):\n                    self.fail(message_registry.TYPE_VAR_GENERIC_CONSTRAINT_TYPE, node)\n                    result.append(AnyType(TypeOfAny.from_error))\n                else:\n                    result.append(analyzed)\n            except TypeTranslationError:\n                self.fail(\"Type expected\", node)\n                result.append(AnyType(TypeOfAny.from_error))\n        return result\n\n    def check_classvar(self, s: AssignmentStmt) -> None:\n        \"\"\"Check if assignment defines a class variable.\"\"\"\n        lvalue = s.lvalues[0]\n        if len(s.lvalues) != 1 or not isinstance(lvalue, RefExpr):\n            return\n        if not s.type or not self.is_classvar(s.type):\n            return\n        assert isinstance(s.type, UnboundType)\n        if self.is_class_scope() and isinstance(lvalue, NameExpr):\n            node = lvalue.node\n            if isinstance(node, Var):\n                node.is_classvar = True\n            analyzed = self.anal_type(s.type)\n            assert self.type is not None\n            if (\n                analyzed is not None\n                and self.type.self_type in get_type_vars(analyzed)\n                and self.type.defn.type_vars\n            ):\n                self.fail(message_registry.CLASS_VAR_WITH_GENERIC_SELF, s)\n        elif not isinstance(lvalue, MemberExpr) or self.is_self_member_ref(lvalue):\n            # In case of member access, report error only when assigning to self\n            # Other kinds of member assignments should be already reported\n            self.fail_invalid_classvar(lvalue)\n        if not s.type.args:\n            if isinstance(s.rvalue, TempNode) and s.rvalue.no_rhs:\n                if self.options.disallow_any_generics:\n                    self.fail(\"ClassVar without type argument becomes Any\", s, code=codes.TYPE_ARG)\n                return\n            s.type = None\n\n    def is_classvar(self, typ: Type) -> bool:\n        if not isinstance(typ, UnboundType):\n            return False\n        sym = self.lookup_qualified(typ.name, typ)\n        if not sym or not sym.node:\n            return False\n        return sym.node.fullname == \"typing.ClassVar\"\n\n    def is_final_type(self, typ: Type | None) -> bool:\n        if not isinstance(typ, UnboundType):\n            return False\n        sym = self.lookup_qualified(typ.name, typ)\n        if not sym or not sym.node:\n            return False\n        return sym.node.fullname in FINAL_TYPE_NAMES\n\n    def fail_invalid_classvar(self, context: Context) -> None:\n        self.fail(message_registry.CLASS_VAR_OUTSIDE_OF_CLASS, context)\n\n    def process_module_assignment(\n        self, lvals: list[Lvalue], rval: Expression, ctx: AssignmentStmt\n    ) -> None:\n        \"\"\"Propagate module references across assignments.\n\n        Recursively handles the simple form of iterable unpacking; doesn't\n        handle advanced unpacking with *rest, dictionary unpacking, etc.\n\n        In an expression like x = y = z, z is the rval and lvals will be [x,\n        y].\n\n        \"\"\"\n        if isinstance(rval, (TupleExpr, ListExpr)) and all(\n            isinstance(v, TupleExpr) for v in lvals\n        ):\n            # rval and all lvals are either list or tuple, so we are dealing\n            # with unpacking assignment like `x, y = a, b`. Mypy didn't\n            # understand our all(isinstance(...)), so cast them as TupleExpr\n            # so mypy knows it is safe to access their .items attribute.\n            seq_lvals = cast(list[TupleExpr], lvals)\n            # given an assignment like:\n            #     (x, y) = (m, n) = (a, b)\n            # we now have:\n            #     seq_lvals = [(x, y), (m, n)]\n            #     seq_rval = (a, b)\n            # We now zip this into:\n            #     elementwise_assignments = [(a, x, m), (b, y, n)]\n            # where each elementwise assignment includes one element of rval and the\n            # corresponding element of each lval. Basically we unpack\n            #     (x, y) = (m, n) = (a, b)\n            # into elementwise assignments\n            #     x = m = a\n            #     y = n = b\n            # and then we recursively call this method for each of those assignments.\n            # If the rval and all lvals are not all of the same length, zip will just ignore\n            # extra elements, so no error will be raised here; mypy will later complain\n            # about the length mismatch in type-checking.\n            elementwise_assignments = zip(rval.items, *[v.items for v in seq_lvals])\n            for rv, *lvs in elementwise_assignments:\n                self.process_module_assignment(lvs, rv, ctx)\n        elif isinstance(rval, RefExpr):\n            rnode = self.lookup_type_node(rval)\n            if rnode and isinstance(rnode.node, MypyFile):\n                for lval in lvals:\n                    if not isinstance(lval, RefExpr):\n                        continue\n                    # respect explicitly annotated type\n                    if isinstance(lval.node, Var) and lval.node.type is not None:\n                        continue\n\n                    # We can handle these assignments to locals and to self\n                    if isinstance(lval, NameExpr):\n                        lnode = self.current_symbol_table().get(lval.name)\n                    elif isinstance(lval, MemberExpr) and self.is_self_member_ref(lval):\n                        assert self.type is not None\n                        lnode = self.type.names.get(lval.name)\n                    else:\n                        continue\n\n                    if lnode:\n                        if isinstance(lnode.node, MypyFile) and lnode.node is not rnode.node:\n                            assert isinstance(lval, (NameExpr, MemberExpr))\n                            self.fail(\n                                'Cannot assign multiple modules to name \"{}\" '\n                                'without explicit \"types.ModuleType\" annotation'.format(lval.name),\n                                ctx,\n                            )\n                        # never create module alias except on initial var definition\n                        elif lval.is_inferred_def:\n                            assert rnode.node is not None\n                            lnode.node = rnode.node\n\n    def process__all__(self, s: AssignmentStmt) -> None:\n        \"\"\"Export names if argument is a __all__ assignment.\"\"\"\n        if (\n            len(s.lvalues) == 1\n            and isinstance(s.lvalues[0], NameExpr)\n            and s.lvalues[0].name == \"__all__\"\n            and s.lvalues[0].kind == GDEF\n            and isinstance(s.rvalue, (ListExpr, TupleExpr))\n        ):\n            self.add_exports(s.rvalue.items)\n\n    def process__deletable__(self, s: AssignmentStmt) -> None:\n        if not self.options.mypyc:\n            return\n        if (\n            len(s.lvalues) == 1\n            and isinstance(s.lvalues[0], NameExpr)\n            and s.lvalues[0].name == \"__deletable__\"\n            and s.lvalues[0].kind == MDEF\n        ):\n            rvalue = s.rvalue\n            if not isinstance(rvalue, (ListExpr, TupleExpr)):\n                self.fail('\"__deletable__\" must be initialized with a list or tuple expression', s)\n                return\n            items = rvalue.items\n            attrs = []\n            for item in items:\n                if not isinstance(item, StrExpr):\n                    self.fail('Invalid \"__deletable__\" item; string literal expected', item)\n                else:\n                    attrs.append(item.value)\n            assert self.type\n            self.type.deletable_attributes = attrs\n\n    def process__slots__(self, s: AssignmentStmt) -> None:\n        \"\"\"\n        Processing ``__slots__`` if defined in type.\n\n        See: https://docs.python.org/3/reference/datamodel.html#slots\n        \"\"\"\n        # Later we can support `__slots__` defined as `__slots__ = other = ('a', 'b')`\n        if (\n            isinstance(self.type, TypeInfo)\n            and len(s.lvalues) == 1\n            and isinstance(s.lvalues[0], NameExpr)\n            and s.lvalues[0].name == \"__slots__\"\n            and s.lvalues[0].kind == MDEF\n        ):\n            # We understand `__slots__` defined as string, tuple, list, set, and dict:\n            if not isinstance(s.rvalue, (StrExpr, ListExpr, TupleExpr, SetExpr, DictExpr)):\n                # For example, `__slots__` can be defined as a variable,\n                # we don't support it for now.\n                return\n\n            if any(p.slots is None for p in self.type.mro[1:-1]):\n                # At least one type in mro (excluding `self` and `object`)\n                # does not have concrete `__slots__` defined. Ignoring.\n                return\n\n            concrete_slots = True\n            rvalue: list[Expression] = []\n            if isinstance(s.rvalue, StrExpr):\n                rvalue.append(s.rvalue)\n            elif isinstance(s.rvalue, (ListExpr, TupleExpr, SetExpr)):\n                rvalue.extend(s.rvalue.items)\n            else:\n                # We have a special treatment of `dict` with possible `{**kwargs}` usage.\n                # In this case we consider all `__slots__` to be non-concrete.\n                for key, _ in s.rvalue.items:\n                    if concrete_slots and key is not None:\n                        rvalue.append(key)\n                    else:\n                        concrete_slots = False\n\n            slots = []\n            for item in rvalue:\n                # Special case for `'__dict__'` value:\n                # when specified it will still allow any attribute assignment.\n                if isinstance(item, StrExpr) and item.value != \"__dict__\":\n                    slots.append(item.value)\n                else:\n                    concrete_slots = False\n            if not concrete_slots:\n                # Some slot items are dynamic, we don't want any false positives,\n                # so, we just pretend that this type does not have any slots at all.\n                return\n\n            # We need to copy all slots from super types:\n            for super_type in self.type.mro[1:-1]:\n                assert super_type.slots is not None\n                slots.extend(super_type.slots)\n            self.type.slots = set(slots)\n\n    #\n    # Misc statements\n    #\n\n    def visit_block(self, b: Block) -> None:\n        if b.is_unreachable:\n            return\n        self.block_depth[-1] += 1\n        for s in b.body:\n            self.accept(s)\n        self.block_depth[-1] -= 1\n\n    def visit_block_maybe(self, b: Block | None) -> None:\n        if b:\n            self.visit_block(b)\n\n    def visit_expression_stmt(self, s: ExpressionStmt) -> None:\n        self.statement = s\n        s.expr.accept(self)\n\n    def visit_return_stmt(self, s: ReturnStmt) -> None:\n        old = self.statement\n        self.statement = s\n        if not self.is_func_scope():\n            self.fail('\"return\" outside function', s)\n        if self.return_stmt_inside_except_star_block:\n            self.fail('\"return\" not allowed in except* block', s, serious=True)\n        if s.expr:\n            s.expr.accept(self)\n            if TYPE_FORM in self.options.enable_incomplete_feature:\n                self.try_parse_as_type_expression(s.expr)\n        self.statement = old\n\n    def visit_raise_stmt(self, s: RaiseStmt) -> None:\n        self.statement = s\n        if s.expr:\n            s.expr.accept(self)\n        if s.from_expr:\n            s.from_expr.accept(self)\n\n    def visit_assert_stmt(self, s: AssertStmt) -> None:\n        self.statement = s\n        if s.expr:\n            s.expr.accept(self)\n        if s.msg:\n            s.msg.accept(self)\n\n    def visit_operator_assignment_stmt(self, s: OperatorAssignmentStmt) -> None:\n        self.statement = s\n        s.lvalue.accept(self)\n        s.rvalue.accept(self)\n        if (\n            isinstance(s.lvalue, NameExpr)\n            and s.lvalue.name == \"__all__\"\n            and s.lvalue.kind == GDEF\n            and isinstance(s.rvalue, (ListExpr, TupleExpr))\n        ):\n            self.add_exports(s.rvalue.items)\n\n    def visit_while_stmt(self, s: WhileStmt) -> None:\n        self.statement = s\n        s.expr.accept(self)\n        self.loop_depth[-1] += 1\n        with self.inside_except_star_block_set(value=False, entering_loop=True):\n            s.body.accept(self)\n        self.loop_depth[-1] -= 1\n        self.visit_block_maybe(s.else_body)\n\n    def visit_for_stmt(self, s: ForStmt) -> None:\n        if s.is_async:\n            if not self.is_func_scope() or not self.function_stack[-1].is_coroutine:\n                self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, s, code=codes.SYNTAX)\n\n        self.statement = s\n        s.expr.accept(self)\n\n        # Bind index variables and check if they define new names.\n        self.analyze_lvalue(s.index, explicit_type=s.index_type is not None, is_index_var=True)\n        if s.index_type:\n            if self.is_classvar(s.index_type):\n                self.fail_invalid_classvar(s.index)\n            allow_tuple_literal = isinstance(s.index, TupleExpr)\n            analyzed = self.anal_type(s.index_type, allow_tuple_literal=allow_tuple_literal)\n            if analyzed is not None:\n                self.store_declared_types(s.index, analyzed)\n                s.index_type = analyzed\n\n        self.loop_depth[-1] += 1\n        with self.inside_except_star_block_set(value=False, entering_loop=True):\n            self.visit_block(s.body)\n        self.loop_depth[-1] -= 1\n        self.visit_block_maybe(s.else_body)\n\n    def visit_break_stmt(self, s: BreakStmt) -> None:\n        self.statement = s\n        if self.loop_depth[-1] == 0:\n            self.fail('\"break\" outside loop', s, serious=True, blocker=True)\n        if self.inside_except_star_block:\n            self.fail('\"break\" not allowed in except* block', s, serious=True)\n\n    def visit_continue_stmt(self, s: ContinueStmt) -> None:\n        self.statement = s\n        if self.loop_depth[-1] == 0:\n            self.fail('\"continue\" outside loop', s, serious=True, blocker=True)\n        if self.inside_except_star_block:\n            self.fail('\"continue\" not allowed in except* block', s, serious=True)\n\n    def visit_if_stmt(self, s: IfStmt) -> None:\n        self.statement = s\n        infer_reachability_of_if_statement(s, self.options)\n        for i in range(len(s.expr)):\n            s.expr[i].accept(self)\n            self.visit_block(s.body[i])\n        self.visit_block_maybe(s.else_body)\n\n    def visit_try_stmt(self, s: TryStmt) -> None:\n        self.statement = s\n        self.analyze_try_stmt(s, self)\n\n    def analyze_try_stmt(self, s: TryStmt, visitor: NodeVisitor[None]) -> None:\n        s.body.accept(visitor)\n        for type, var, handler in zip(s.types, s.vars, s.handlers):\n            if type:\n                type.accept(visitor)\n            if var:\n                self.analyze_lvalue(var)\n            with self.inside_except_star_block_set(self.inside_except_star_block or s.is_star):\n                handler.accept(visitor)\n        if s.else_body:\n            s.else_body.accept(visitor)\n        if s.finally_body:\n            s.finally_body.accept(visitor)\n\n    def visit_with_stmt(self, s: WithStmt) -> None:\n        self.statement = s\n        types: list[Type] = []\n\n        if s.is_async:\n            if not self.is_func_scope() or not self.function_stack[-1].is_coroutine:\n                self.fail(message_registry.ASYNC_WITH_OUTSIDE_COROUTINE, s, code=codes.SYNTAX)\n\n        if s.unanalyzed_type:\n            assert isinstance(s.unanalyzed_type, ProperType)\n            actual_targets = [t for t in s.target if t is not None]\n            if len(actual_targets) == 0:\n                # We have a type for no targets\n                self.fail('Invalid type comment: \"with\" statement has no targets', s)\n            elif len(actual_targets) == 1:\n                # We have one target and one type\n                types = [s.unanalyzed_type]\n            elif isinstance(s.unanalyzed_type, TupleType):\n                # We have multiple targets and multiple types\n                if len(actual_targets) == len(s.unanalyzed_type.items):\n                    types = s.unanalyzed_type.items.copy()\n                else:\n                    # But it's the wrong number of items\n                    self.fail('Incompatible number of types for \"with\" targets', s)\n            else:\n                # We have multiple targets and one type\n                self.fail('Multiple types expected for multiple \"with\" targets', s)\n\n        new_types: list[Type] = []\n        for e, n in zip(s.expr, s.target):\n            e.accept(self)\n            if n:\n                self.analyze_lvalue(n, explicit_type=s.unanalyzed_type is not None)\n\n                # Since we have a target, pop the next type from types\n                if types:\n                    t = types.pop(0)\n                    if self.is_classvar(t):\n                        self.fail_invalid_classvar(n)\n                    allow_tuple_literal = isinstance(n, TupleExpr)\n                    analyzed = self.anal_type(t, allow_tuple_literal=allow_tuple_literal)\n                    if analyzed is not None:\n                        # TODO: Deal with this better\n                        new_types.append(analyzed)\n                        self.store_declared_types(n, analyzed)\n\n        s.analyzed_types = new_types\n\n        self.visit_block(s.body)\n\n    def visit_del_stmt(self, s: DelStmt) -> None:\n        self.statement = s\n        s.expr.accept(self)\n        if not self.is_valid_del_target(s.expr):\n            self.fail(\"Invalid delete target\", s)\n\n    def is_valid_del_target(self, s: Expression) -> bool:\n        if isinstance(s, (IndexExpr, NameExpr, MemberExpr)):\n            return True\n        elif isinstance(s, (TupleExpr, ListExpr)):\n            return all(self.is_valid_del_target(item) for item in s.items)\n        else:\n            return False\n\n    def visit_global_decl(self, g: GlobalDecl) -> None:\n        self.statement = g\n        for name in g.names:\n            if name in self.nonlocal_decls[-1]:\n                self.fail(f'Name \"{name}\" is nonlocal and global', g)\n            self.global_decls[-1].add(name)\n\n    def visit_nonlocal_decl(self, d: NonlocalDecl) -> None:\n        self.statement = d\n        if self.is_module_scope():\n            self.fail(\"nonlocal declaration not allowed at module level\", d)\n        else:\n            for name in d.names:\n                for table, scope_type in zip(\n                    reversed(self.locals[:-1]), reversed(self.scope_stack[:-1])\n                ):\n                    if table is not None and name in table:\n                        if scope_type == SCOPE_ANNOTATION:\n                            self.fail(\n                                f'nonlocal binding not allowed for type parameter \"{name}\"', d\n                            )\n                        break\n                else:\n                    self.fail(f'No binding for nonlocal \"{name}\" found', d)\n\n                if self.locals[-1] is not None and name in self.locals[-1]:\n                    self.fail(\n                        'Name \"{}\" is already defined in local '\n                        \"scope before nonlocal declaration\".format(name),\n                        d,\n                    )\n\n                if name in self.global_decls[-1]:\n                    self.fail(f'Name \"{name}\" is nonlocal and global', d)\n                self.nonlocal_decls[-1].add(name)\n\n    def visit_match_stmt(self, s: MatchStmt) -> None:\n        self.statement = s\n        infer_reachability_of_match_statement(s, self.options)\n        s.subject.accept(self)\n        for i in range(len(s.patterns)):\n            s.patterns[i].accept(self)\n            guard = s.guards[i]\n            if guard is not None:\n                guard.accept(self)\n            self.visit_block(s.bodies[i])\n\n    def visit_type_alias_stmt(self, s: TypeAliasStmt) -> None:\n        if s.invalid_recursive_alias:\n            return\n        self.statement = s\n        type_params = self.push_type_args(s.type_args, s)\n        if type_params is None:\n            self.defer(s)\n            return\n        all_type_params_names = [p.name for p in s.type_args]\n\n        try:\n            existing = self.current_symbol_table().get(s.name.name)\n            if existing and not (\n                isinstance(existing.node, TypeAlias)\n                or (isinstance(existing.node, PlaceholderNode) and existing.node.line == s.line)\n            ):\n                self.already_defined(s.name.name, s, existing, \"Name\")\n                return\n\n            tag = self.track_incomplete_refs()\n            res, alias_tvars, depends_on, indexed = self.analyze_alias(\n                s.name.name,\n                s.value.expr(),\n                allow_placeholder=True,\n                declared_type_vars=type_params,\n                all_declared_type_params_names=all_type_params_names,\n                python_3_12_type_alias=True,\n            )\n            if not res:\n                res = AnyType(TypeOfAny.from_error)\n\n            if not self.is_func_scope():\n                # Only marking incomplete for top-level placeholders makes recursive aliases like\n                # `A = Sequence[str | A]` valid here, similar to how we treat base classes in class\n                # definitions, allowing `class str(Sequence[str]): ...`\n                incomplete_target = isinstance(res, ProperType) and isinstance(\n                    res, PlaceholderType\n                )\n            else:\n                incomplete_target = has_placeholder(res)\n\n            if self.found_incomplete_ref(tag) or incomplete_target:\n                # Since we have got here, we know this must be a type alias (incomplete refs\n                # may appear in nested positions), therefore use becomes_typeinfo=True.\n                self.mark_incomplete(s.name.name, s.value, becomes_typeinfo=True)\n                return\n\n            # Now go through all new variables and temporary replace all tvars that still\n            # refer to some placeholders. We defer the whole alias and will revisit it again,\n            # as well as all its dependents.\n            for i, tv in enumerate(alias_tvars):\n                if has_placeholder(tv):\n                    self.mark_incomplete(s.name.name, s.value, becomes_typeinfo=True)\n                    alias_tvars[i] = self._trivial_typevarlike_like(tv)\n\n            self.add_type_alias_deps(depends_on)\n            check_for_explicit_any(\n                res, self.options, self.is_typeshed_stub_file, self.msg, context=s\n            )\n            # When this type alias gets \"inlined\", the Any is not explicit anymore,\n            # so we need to replace it with non-explicit Anys.\n            res = make_any_non_explicit(res)\n            if self.options.disallow_any_unimported and has_any_from_unimported_type(res):\n                self.msg.unimported_type_becomes_any(\"Type alias target\", res, s)\n                res = make_any_non_unimported(res)\n            eager = self.is_func_scope()\n            if isinstance(res, ProperType) and isinstance(res, Instance):\n                fix_instance(res, self.fail, self.note, disallow_any=False, options=self.options)\n            alias_node = TypeAlias(\n                res,\n                self.qualified_name(s.name.name),\n                self.cur_mod_id,\n                s.line,\n                s.column,\n                alias_tvars=alias_tvars,\n                no_args=False,\n                eager=eager,\n                python_3_12_type_alias=True,\n            )\n            s.alias_node = alias_node\n\n            if (\n                existing\n                and isinstance(existing.node, (PlaceholderNode, TypeAlias))\n                and existing.node.line == s.line\n            ):\n                updated = False\n                if isinstance(existing.node, TypeAlias):\n                    if (\n                        existing.node.target != res\n                        or existing.node.alias_tvars != alias_node.alias_tvars\n                    ):\n                        # Copy expansion to the existing alias, this matches how we update base classes\n                        # for a TypeInfo _in place_ if there are nested placeholders.\n                        existing.node.target = res\n                        existing.node.alias_tvars = alias_tvars\n                        updated = True\n                        # Invalidate recursive status cache in case it was previously set.\n                        existing.node._is_recursive = None\n                else:\n                    # Otherwise just replace existing placeholder with type alias.\n                    existing.node = alias_node\n                    updated = True\n\n                if updated:\n                    if self.final_iteration:\n                        self.cannot_resolve_name(s.name.name, \"name\", s)\n                        return\n                    else:\n                        # We need to defer so that this change can get propagated to base classes.\n                        self.defer(s, force_progress=True)\n            else:\n                self.add_symbol(s.name.name, alias_node, s)\n\n            current_node = existing.node if existing else alias_node\n            assert isinstance(current_node, TypeAlias)\n            self.disable_invalid_recursive_aliases(s, current_node, s.value)\n            s.name.accept(self)\n        finally:\n            self.pop_type_args(s.type_args)\n\n    def _trivial_typevarlike_like(self, tv: TypeVarLikeType) -> TypeVarLikeType:\n        object_type = self.named_type(\"builtins.object\")\n        if isinstance(tv, TypeVarType):\n            return TypeVarType(\n                tv.name,\n                tv.fullname,\n                tv.id,\n                values=[],\n                upper_bound=object_type,\n                default=AnyType(TypeOfAny.from_omitted_generics),\n                variance=tv.variance,\n                line=tv.line,\n                column=tv.column,\n            )\n        elif isinstance(tv, TypeVarTupleType):\n            tuple_type = self.named_type(\"builtins.tuple\", [object_type])\n            return TypeVarTupleType(\n                tv.name,\n                tv.fullname,\n                tv.id,\n                upper_bound=tuple_type,\n                tuple_fallback=tuple_type,\n                default=AnyType(TypeOfAny.from_omitted_generics),\n                line=tv.line,\n                column=tv.column,\n            )\n        elif isinstance(tv, ParamSpecType):\n            return ParamSpecType(\n                tv.name,\n                tv.fullname,\n                tv.id,\n                flavor=tv.flavor,\n                upper_bound=object_type,\n                default=AnyType(TypeOfAny.from_omitted_generics),\n                line=tv.line,\n                column=tv.column,\n            )\n        else:\n            assert False, f\"Unknown TypeVarLike: {tv!r}\"\n\n    #\n    # Expressions\n    #\n\n    def visit_name_expr(self, expr: NameExpr) -> None:\n        n = self.lookup(expr.name, expr)\n        if n:\n            self.bind_name_expr(expr, n)\n\n    def bind_name_expr(self, expr: NameExpr, sym: SymbolTableNode) -> None:\n        \"\"\"Bind name expression to a symbol table node.\"\"\"\n        if (\n            isinstance(sym.node, TypeVarExpr)\n            and self.tvar_scope.get_binding(sym)\n            and not self.allow_unbound_tvars\n        ):\n            self.fail(f'\"{expr.name}\" is a type variable and only valid in type context', expr)\n        elif isinstance(sym.node, PlaceholderNode):\n            self.process_placeholder(expr.name, \"name\", expr)\n        else:\n            expr.kind = sym.kind\n            expr.node = sym.node\n            expr.fullname = sym.fullname or \"\"\n\n    def visit_super_expr(self, expr: SuperExpr) -> None:\n        if not self.type and not expr.call.args:\n            self.fail('\"super\" used outside class', expr)\n            return\n        expr.info = self.type\n        for arg in expr.call.args:\n            arg.accept(self)\n\n    def visit_tuple_expr(self, expr: TupleExpr) -> None:\n        for item in expr.items:\n            if isinstance(item, StarExpr):\n                item.valid = True\n            item.accept(self)\n\n    def visit_list_expr(self, expr: ListExpr) -> None:\n        for item in expr.items:\n            if isinstance(item, StarExpr):\n                item.valid = True\n            item.accept(self)\n\n    def visit_set_expr(self, expr: SetExpr) -> None:\n        for item in expr.items:\n            if isinstance(item, StarExpr):\n                item.valid = True\n            item.accept(self)\n\n    def visit_dict_expr(self, expr: DictExpr) -> None:\n        for key, value in expr.items:\n            if key is not None:\n                key.accept(self)\n            value.accept(self)\n\n    def visit_template_str_expr(self, expr: TemplateStrExpr) -> None:\n        for item in expr.items:\n            if isinstance(item, tuple):\n                item[0].accept(self)\n                if item[3] is not None:\n                    item[3].accept(self)\n            else:\n                item.accept(self)\n\n    def visit_star_expr(self, expr: StarExpr) -> None:\n        if not expr.valid:\n            self.fail(\"can't use starred expression here\", expr, blocker=True)\n        else:\n            expr.expr.accept(self)\n\n    def visit_yield_from_expr(self, e: YieldFromExpr) -> None:\n        if not self.is_func_scope():\n            self.fail('\"yield from\" outside function', e, serious=True, blocker=True)\n        elif self.scope_stack[-1] == SCOPE_COMPREHENSION:\n            self.fail(\n                '\"yield from\" inside comprehension or generator expression',\n                e,\n                serious=True,\n                blocker=True,\n            )\n        elif self.function_stack[-1].is_coroutine:\n            self.fail('\"yield from\" in async function', e, serious=True, blocker=True)\n        else:\n            self.function_stack[-1].is_generator = True\n        if e.expr:\n            e.expr.accept(self)\n\n    def visit_call_expr(self, expr: CallExpr) -> None:\n        \"\"\"Analyze a call expression.\n\n        Some call expressions are recognized as special forms, including\n        cast(...).\n        \"\"\"\n        expr.callee.accept(self)\n        if refers_to_fullname(expr.callee, \"typing.cast\"):\n            # Special form cast(...).\n            if not self.check_fixed_args(expr, 2, \"cast\"):\n                return\n            # Translate first argument to an unanalyzed type.\n            try:\n                target = self.expr_to_unanalyzed_type(expr.args[0])\n            except TypeTranslationError:\n                self.fail(\"Cast target is not a type\", expr)\n                return\n            # Piggyback CastExpr object to the CallExpr object; it takes\n            # precedence over the CallExpr semantics.\n            expr.analyzed = CastExpr(expr.args[1], target)\n            expr.analyzed.line = expr.line\n            expr.analyzed.column = expr.column\n            expr.analyzed.accept(self)\n        elif refers_to_fullname(expr.callee, ASSERT_TYPE_NAMES):\n            if not self.check_fixed_args(expr, 2, \"assert_type\"):\n                return\n            # Translate second argument to an unanalyzed type.\n            try:\n                target = self.expr_to_unanalyzed_type(expr.args[1])\n            except TypeTranslationError:\n                self.fail(\"assert_type() type is not a type\", expr)\n                return\n            expr.analyzed = AssertTypeExpr(expr.args[0], target)\n            expr.analyzed.line = expr.line\n            expr.analyzed.column = expr.column\n            expr.analyzed.accept(self)\n        elif refers_to_fullname(expr.callee, REVEAL_TYPE_NAMES):\n            if not self.check_fixed_args(expr, 1, \"reveal_type\"):\n                return\n            reveal_imported = False\n            reveal_type_node = self.lookup(\"reveal_type\", expr, suppress_errors=True)\n            if (\n                reveal_type_node\n                and isinstance(reveal_type_node.node, SYMBOL_FUNCBASE_TYPES)\n                and reveal_type_node.fullname in IMPORTED_REVEAL_TYPE_NAMES\n            ):\n                reveal_imported = True\n            expr.analyzed = RevealExpr(\n                kind=REVEAL_TYPE, expr=expr.args[0], is_imported=reveal_imported\n            )\n            expr.analyzed.line = expr.line\n            expr.analyzed.column = expr.column\n            expr.analyzed.accept(self)\n        elif refers_to_fullname(expr.callee, \"builtins.reveal_locals\"):\n            # Store the local variable names into the RevealExpr for use in the\n            # type checking pass\n            local_nodes: list[Var] = []\n            if self.is_module_scope():\n                # try to determine just the variable declarations in module scope\n                # self.globals.values() contains SymbolTableNode's\n                # Each SymbolTableNode has an attribute node that is nodes.Var\n                # look for variable nodes that marked as is_inferred\n                # Each symboltable node has a Var node as .node\n                local_nodes = [\n                    n.node\n                    for name, n in self.globals.items()\n                    if getattr(n.node, \"is_inferred\", False) and isinstance(n.node, Var)\n                ]\n            elif self.is_class_scope():\n                # type = None  # type: Optional[TypeInfo]\n                if self.type is not None:\n                    local_nodes = [\n                        st.node for st in self.type.names.values() if isinstance(st.node, Var)\n                    ]\n            elif self.is_func_scope():\n                # locals = None  # type: List[Optional[SymbolTable]]\n                if self.locals is not None:\n                    symbol_table = self.locals[-1]\n                    if symbol_table is not None:\n                        local_nodes = [\n                            st.node for st in symbol_table.values() if isinstance(st.node, Var)\n                        ]\n            expr.analyzed = RevealExpr(kind=REVEAL_LOCALS, local_nodes=local_nodes)\n            expr.analyzed.line = expr.line\n            expr.analyzed.column = expr.column\n            expr.analyzed.accept(self)\n        elif refers_to_fullname(expr.callee, \"typing.Any\"):\n            # Special form Any(...) no longer supported.\n            self.fail(\"Any(...) is no longer supported. Use cast(Any, ...) instead\", expr)\n        elif refers_to_fullname(expr.callee, \"typing._promote\"):\n            # Special form _promote(...).\n            if not self.check_fixed_args(expr, 1, \"_promote\"):\n                return\n            # Translate first argument to an unanalyzed type.\n            try:\n                target = self.expr_to_unanalyzed_type(expr.args[0])\n            except TypeTranslationError:\n                self.fail(\"Argument 1 to _promote is not a type\", expr)\n                return\n            expr.analyzed = PromoteExpr(target)\n            expr.analyzed.line = expr.line\n            expr.analyzed.accept(self)\n        elif refers_to_fullname(expr.callee, \"builtins.dict\") and not (\n            isinstance(expr.callee, RefExpr)\n            and isinstance(expr.callee.node, TypeAlias)\n            and not expr.callee.node.no_args\n        ):\n            expr.analyzed = self.translate_dict_call(expr)\n        elif refers_to_fullname(expr.callee, \"builtins.divmod\"):\n            if not self.check_fixed_args(expr, 2, \"divmod\"):\n                return\n            expr.analyzed = OpExpr(\"divmod\", expr.args[0], expr.args[1])\n            expr.analyzed.line = expr.line\n            expr.analyzed.accept(self)\n        elif refers_to_fullname(\n            expr.callee, (\"typing.TypeAliasType\", \"typing_extensions.TypeAliasType\")\n        ):\n            with self.allow_unbound_tvars_set():\n                for a in expr.args:\n                    a.accept(self)\n        elif refers_to_fullname(expr.callee, (\"typing.TypeForm\", \"typing_extensions.TypeForm\")):\n            # Special form TypeForm(...).\n            if not self.check_fixed_args(expr, 1, \"TypeForm\"):\n                return\n            # Translate first argument to an unanalyzed type.\n            try:\n                typ = self.expr_to_unanalyzed_type(expr.args[0])\n            except TypeTranslationError:\n                self.fail(\"TypeForm argument is not a type\", expr)\n                # Suppress future error: \"<typing special form>\" not callable\n                expr.analyzed = CastExpr(expr.args[0], AnyType(TypeOfAny.from_error))\n                return\n            # Piggyback TypeFormExpr object to the CallExpr object; it takes\n            # precedence over the CallExpr semantics.\n            expr.analyzed = TypeFormExpr(typ)\n            expr.analyzed.line = expr.line\n            expr.analyzed.column = expr.column\n            expr.analyzed.accept(self)\n        else:\n            # Normal call expression.\n            calculate_type_forms = TYPE_FORM in self.options.enable_incomplete_feature\n            for a in expr.args:\n                a.accept(self)\n                if calculate_type_forms:\n                    self.try_parse_as_type_expression(a)\n\n            if (\n                isinstance(expr.callee, MemberExpr)\n                and isinstance(expr.callee.expr, NameExpr)\n                and expr.callee.expr.name == \"__all__\"\n                and expr.callee.expr.kind == GDEF\n                and expr.callee.name in (\"append\", \"extend\", \"remove\")\n            ):\n                if expr.callee.name == \"append\" and expr.args:\n                    self.add_exports(expr.args[0])\n                elif (\n                    expr.callee.name == \"extend\"\n                    and expr.args\n                    and isinstance(expr.args[0], (ListExpr, TupleExpr))\n                ):\n                    self.add_exports(expr.args[0].items)\n                elif (\n                    expr.callee.name == \"remove\"\n                    and expr.args\n                    and isinstance(expr.args[0], StrExpr)\n                ):\n                    self.all_exports = [n for n in self.all_exports if n != expr.args[0].value]\n\n    def translate_dict_call(self, call: CallExpr) -> DictExpr | None:\n        \"\"\"Translate 'dict(x=y, ...)' to {'x': y, ...} and 'dict()' to {}.\n\n        For other variants of dict(...), return None.\n        \"\"\"\n        if not all(kind in (ARG_NAMED, ARG_STAR2) for kind in call.arg_kinds):\n            # Must still accept those args.\n            for a in call.args:\n                a.accept(self)\n            return None\n        expr = DictExpr(\n            [\n                (StrExpr(key) if key is not None else None, value)\n                for key, value in zip(call.arg_names, call.args)\n            ]\n        )\n        expr.set_line(call)\n        expr.accept(self)\n        return expr\n\n    def check_fixed_args(self, expr: CallExpr, numargs: int, name: str) -> bool:\n        \"\"\"Verify that expr has specified number of positional args.\n\n        Return True if the arguments are valid.\n        \"\"\"\n        s = \"s\"\n        if numargs == 1:\n            s = \"\"\n        if len(expr.args) != numargs:\n            self.fail('\"%s\" expects %d argument%s' % (name, numargs, s), expr)\n            return False\n        if expr.arg_kinds != [ARG_POS] * numargs:\n            self.fail(f'\"{name}\" must be called with {numargs} positional argument{s}', expr)\n            return False\n        return True\n\n    def visit_member_expr(self, expr: MemberExpr) -> None:\n        base = expr.expr\n        base.accept(self)\n        if isinstance(base, RefExpr) and isinstance(base.node, MypyFile):\n            # Handle module attribute.\n            sym = self.get_module_symbol(base.node, expr.name)\n            if sym:\n                if isinstance(sym.node, PlaceholderNode):\n                    self.process_placeholder(expr.name, \"attribute\", expr)\n                    return\n                self.record_imported_symbol(sym)\n                expr.kind = sym.kind\n                expr.fullname = sym.fullname or \"\"\n                expr.node = sym.node\n        elif isinstance(base, RefExpr):\n            # This branch handles the case C.bar (or cls.bar or self.bar inside\n            # a classmethod/method), where C is a class and bar is a type\n            # definition or a module resulting from `import bar` (or a module\n            # assignment) inside class C. We look up bar in the class' TypeInfo\n            # namespace.  This is done only when bar is a module or a type;\n            # other things (e.g. methods) are handled by other code in\n            # checkmember.\n            type_info = None\n            if isinstance(base.node, TypeInfo):\n                # C.bar where C is a class\n                type_info = base.node\n            elif isinstance(base.node, Var) and self.type and self.function_stack:\n                # check for self.bar or cls.bar in method/classmethod\n                func_def = self.function_stack[-1]\n                if (\n                    func_def.has_self_or_cls_argument\n                    and func_def.info is self.type\n                    and isinstance(func_def.type, CallableType)\n                    and func_def.arguments\n                    and base.node is func_def.arguments[0].variable\n                ):\n                    type_info = self.type\n            elif isinstance(base.node, TypeAlias) and base.node.no_args:\n                assert isinstance(base.node.target, ProperType)\n                if isinstance(base.node.target, Instance):\n                    type_info = base.node.target.type\n\n            if type_info:\n                n = type_info.names.get(expr.name)\n                if n is not None and isinstance(n.node, (MypyFile, TypeInfo, TypeAlias)):\n                    self.record_imported_symbol(n)\n                    expr.kind = n.kind\n                    expr.fullname = n.fullname or \"\"\n                    expr.node = n.node\n\n    def visit_op_expr(self, expr: OpExpr) -> None:\n        expr.left.accept(self)\n\n        if expr.op in (\"and\", \"or\"):\n            inferred = infer_condition_value(expr.left, self.options)\n            if (inferred in (ALWAYS_FALSE, MYPY_FALSE) and expr.op == \"and\") or (\n                inferred in (ALWAYS_TRUE, MYPY_TRUE) and expr.op == \"or\"\n            ):\n                expr.right_unreachable = True\n                return\n            elif (inferred in (ALWAYS_TRUE, MYPY_TRUE) and expr.op == \"and\") or (\n                inferred in (ALWAYS_FALSE, MYPY_FALSE) and expr.op == \"or\"\n            ):\n                expr.right_always = True\n\n        expr.right.accept(self)\n\n    def visit_comparison_expr(self, expr: ComparisonExpr) -> None:\n        for operand in expr.operands:\n            operand.accept(self)\n\n    def visit_unary_expr(self, expr: UnaryExpr) -> None:\n        expr.expr.accept(self)\n\n    def visit_index_expr(self, expr: IndexExpr) -> None:\n        base = expr.base\n        base.accept(self)\n        if (\n            isinstance(base, RefExpr)\n            and isinstance(base.node, TypeInfo)\n            and not base.node.is_generic()\n        ):\n            expr.index.accept(self)\n        elif (\n            isinstance(base, RefExpr) and isinstance(base.node, TypeAlias)\n        ) or refers_to_class_or_function(base):\n            # We need to do full processing on every iteration, since some type\n            # arguments may contain placeholder types.\n            self.analyze_type_application(expr)\n        else:\n            expr.index.accept(self)\n\n    def analyze_type_application(self, expr: IndexExpr) -> None:\n        \"\"\"Analyze special form -- type application (either direct or via type aliasing).\"\"\"\n        types = self.analyze_type_application_args(expr)\n        if types is None:\n            return\n        base = expr.base\n        expr.analyzed = TypeApplication(base, types)\n        expr.analyzed.line = expr.line\n        expr.analyzed.column = expr.column\n\n        if isinstance(base, RefExpr) and base.fullname == \"librt.vecs.vec\":\n            # Apply restrictions specific to vec\n            check_vec_type_args(types, expr, self)\n\n    def analyze_type_application_args(self, expr: IndexExpr) -> list[Type] | None:\n        \"\"\"Analyze type arguments (index) in a type application.\n\n        Return None if anything was incomplete.\n        \"\"\"\n        index = expr.index\n        tag = self.track_incomplete_refs()\n        self.analyze_type_expr(index)\n        if self.found_incomplete_ref(tag):\n            return None\n        if self.basic_type_applications:\n            # Postpone the rest until we have more information (for r.h.s. of an assignment)\n            return None\n        types: list[Type] = []\n        if isinstance(index, TupleExpr):\n            items = index.items\n            is_tuple = isinstance(expr.base, RefExpr) and expr.base.fullname == \"builtins.tuple\"\n            if is_tuple and len(items) == 2 and isinstance(items[-1], EllipsisExpr):\n                items = items[:-1]\n        else:\n            items = [index]\n\n        # TODO: this needs a clean-up.\n        # Probably always allow Parameters literals, and validate in semanal_typeargs.py\n        base = expr.base\n        if isinstance(base, RefExpr) and isinstance(base.node, TypeAlias):\n            allow_unpack = base.node.tvar_tuple_index is not None\n            alias = base.node\n            if any(isinstance(t, ParamSpecType) for t in alias.alias_tvars):\n                has_param_spec = True\n                num_args = len(alias.alias_tvars)\n            else:\n                has_param_spec = False\n                num_args = -1\n        elif isinstance(base, RefExpr) and isinstance(base.node, TypeInfo):\n            allow_unpack = (\n                base.node.has_type_var_tuple_type or base.node.fullname == \"builtins.tuple\"\n            )\n            has_param_spec = base.node.has_param_spec_type\n            num_args = len(base.node.type_vars)\n        else:\n            allow_unpack = False\n            has_param_spec = False\n            num_args = -1\n\n        for item in items:\n            try:\n                typearg = self.expr_to_unanalyzed_type(item, allow_unpack=True)\n            except TypeTranslationError:\n                self.fail(\"Type expected within [...]\", expr)\n                return None\n            analyzed = self.anal_type(\n                typearg,\n                # The type application may appear in base class expression,\n                # where type variables are not bound yet. Or when accepting\n                # r.h.s. of type alias before we figured out it is a type alias.\n                allow_unbound_tvars=self.allow_unbound_tvars,\n                allow_placeholder=True,\n                allow_param_spec_literals=has_param_spec,\n                allow_unpack=allow_unpack,\n            )\n            if analyzed is None:\n                return None\n            types.append(analyzed)\n\n        if allow_unpack:\n            # need to flatten away harmless unpacks like Unpack[tuple[int]]\n            flattened_items = flatten_nested_tuples(types)\n            types = self.type_analyzer().check_unpacks_in_list(flattened_items)\n        if has_param_spec and num_args == 1 and types:\n            first_arg = get_proper_type(types[0])\n            single_any = len(types) == 1 and isinstance(first_arg, AnyType)\n            if not (single_any or any(isinstance(t, (Parameters, ParamSpecType)) for t in types)):\n                types = [Parameters(types, [ARG_POS] * len(types), [None] * len(types))]\n\n        return types\n\n    def visit_slice_expr(self, expr: SliceExpr) -> None:\n        if expr.begin_index:\n            expr.begin_index.accept(self)\n        if expr.end_index:\n            expr.end_index.accept(self)\n        if expr.stride:\n            expr.stride.accept(self)\n\n    def visit_cast_expr(self, expr: CastExpr) -> None:\n        expr.expr.accept(self)\n        analyzed = self.anal_type(expr.type)\n        if analyzed is not None:\n            expr.type = analyzed\n\n    def visit_type_form_expr(self, expr: TypeFormExpr) -> None:\n        analyzed = self.anal_type(expr.type)\n        if analyzed is not None:\n            expr.type = analyzed\n\n    def visit_assert_type_expr(self, expr: AssertTypeExpr) -> None:\n        expr.expr.accept(self)\n        analyzed = self.anal_type(expr.type)\n        if analyzed is not None:\n            expr.type = analyzed\n\n    def visit_reveal_expr(self, expr: RevealExpr) -> None:\n        if expr.kind == REVEAL_TYPE:\n            if expr.expr is not None:\n                expr.expr.accept(self)\n        else:\n            # Reveal locals doesn't have an inner expression, there's no\n            # need to traverse inside it\n            pass\n\n    def visit_type_application(self, expr: TypeApplication) -> None:\n        expr.expr.accept(self)\n        for i in range(len(expr.types)):\n            analyzed = self.anal_type(expr.types[i])\n            if analyzed is not None:\n                expr.types[i] = analyzed\n\n    def visit_list_comprehension(self, expr: ListComprehension) -> None:\n        if any(expr.generator.is_async):\n            if (\n                not self.is_func_scope()\n                or not self.function_stack\n                or not self.function_stack[-1].is_coroutine\n            ):\n                self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX)\n\n        expr.generator.accept(self)\n\n    def visit_set_comprehension(self, expr: SetComprehension) -> None:\n        if any(expr.generator.is_async):\n            if (\n                not self.is_func_scope()\n                or not self.function_stack\n                or not self.function_stack[-1].is_coroutine\n            ):\n                self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX)\n\n        expr.generator.accept(self)\n\n    def visit_dictionary_comprehension(self, expr: DictionaryComprehension) -> None:\n        if any(expr.is_async):\n            if (\n                not self.is_func_scope()\n                or not self.function_stack\n                or not self.function_stack[-1].is_coroutine\n            ):\n                self.fail(message_registry.ASYNC_FOR_OUTSIDE_COROUTINE, expr, code=codes.SYNTAX)\n\n        with self.enter(expr):\n            self.analyze_comp_for(expr)\n            expr.key.accept(self)\n            expr.value.accept(self)\n        self.analyze_comp_for_2(expr)\n\n    def visit_generator_expr(self, expr: GeneratorExpr) -> None:\n        with self.enter(expr):\n            self.analyze_comp_for(expr)\n            expr.left_expr.accept(self)\n        self.analyze_comp_for_2(expr)\n\n    def analyze_comp_for(self, expr: GeneratorExpr | DictionaryComprehension) -> None:\n        \"\"\"Analyses the 'comp_for' part of comprehensions (part 1).\n\n        That is the part after 'for' in (x for x in l if p). This analyzes\n        variables and conditions which are analyzed in a local scope.\n        \"\"\"\n        for i, (index, sequence, conditions) in enumerate(\n            zip(expr.indices, expr.sequences, expr.condlists)\n        ):\n            if i > 0:\n                sequence.accept(self)\n            # Bind index variables.\n            self.analyze_lvalue(index)\n            for cond in conditions:\n                cond.accept(self)\n\n    def analyze_comp_for_2(self, expr: GeneratorExpr | DictionaryComprehension) -> None:\n        \"\"\"Analyses the 'comp_for' part of comprehensions (part 2).\n\n        That is the part after 'for' in (x for x in l if p). This analyzes\n        the 'l' part which is analyzed in the surrounding scope.\n        \"\"\"\n        expr.sequences[0].accept(self)\n\n    def visit_lambda_expr(self, expr: LambdaExpr) -> None:\n        self.analyze_arg_initializers(expr)\n        with self.inside_except_star_block_set(False, entering_loop=False):\n            self.analyze_function_body(expr)\n\n    def visit_conditional_expr(self, expr: ConditionalExpr) -> None:\n        expr.if_expr.accept(self)\n        expr.cond.accept(self)\n        expr.else_expr.accept(self)\n\n    def visit__promote_expr(self, expr: PromoteExpr) -> None:\n        analyzed = self.anal_type(expr.type)\n        if analyzed is not None:\n            assert isinstance(analyzed, ProperType), \"Cannot use type aliases for promotions\"\n            expr.type = analyzed\n\n    def visit_yield_expr(self, e: YieldExpr) -> None:\n        if not self.is_func_scope():\n            self.fail('\"yield\" outside function', e, serious=True, blocker=True)\n        elif self.scope_stack[-1] == SCOPE_COMPREHENSION:\n            self.fail(\n                '\"yield\" inside comprehension or generator expression',\n                e,\n                serious=True,\n                blocker=True,\n            )\n        elif self.function_stack[-1].is_coroutine:\n            self.function_stack[-1].is_generator = True\n            self.function_stack[-1].is_async_generator = True\n        else:\n            self.function_stack[-1].is_generator = True\n        if e.expr:\n            e.expr.accept(self)\n\n    def visit_await_expr(self, expr: AwaitExpr) -> None:\n        if not self.is_func_scope() or not self.function_stack:\n            # We check both because is_function_scope() returns True inside comprehensions.\n            # This is not a blocker, because some environments (like ipython)\n            # support top level awaits.\n            self.fail('\"await\" outside function', expr, serious=True, code=codes.TOP_LEVEL_AWAIT)\n        elif not self.function_stack[-1].is_coroutine:\n            self.fail(\n                '\"await\" outside coroutine (\"async def\")',\n                expr,\n                serious=True,\n                code=codes.AWAIT_NOT_ASYNC,\n            )\n        expr.expr.accept(self)\n\n    #\n    # Patterns\n    #\n\n    def visit_as_pattern(self, p: AsPattern) -> None:\n        if p.pattern is not None:\n            p.pattern.accept(self)\n        if p.name is not None:\n            self.analyze_lvalue(p.name)\n\n    def visit_or_pattern(self, p: OrPattern) -> None:\n        for pattern in p.patterns:\n            pattern.accept(self)\n\n    def visit_value_pattern(self, p: ValuePattern) -> None:\n        p.expr.accept(self)\n\n    def visit_sequence_pattern(self, p: SequencePattern) -> None:\n        for pattern in p.patterns:\n            pattern.accept(self)\n\n    def visit_starred_pattern(self, p: StarredPattern) -> None:\n        if p.capture is not None:\n            self.analyze_lvalue(p.capture)\n\n    def visit_mapping_pattern(self, p: MappingPattern) -> None:\n        for key in p.keys:\n            key.accept(self)\n        for value in p.values:\n            value.accept(self)\n        if p.rest is not None:\n            self.analyze_lvalue(p.rest)\n\n    def visit_class_pattern(self, p: ClassPattern) -> None:\n        p.class_ref.accept(self)\n        for pos in p.positionals:\n            pos.accept(self)\n        for v in p.keyword_values:\n            v.accept(self)\n\n    #\n    # Lookup functions\n    #\n\n    def lookup(\n        self, name: str, ctx: Context, suppress_errors: bool = False\n    ) -> SymbolTableNode | None:\n        node = self._lookup(name, ctx, suppress_errors)\n        if node is not None:\n            # This call is unfortunate from performance point of view, but\n            # needed for rare cases like e.g. testIncrementalChangingAlias.\n            self.record_imported_symbol(node)\n        return node\n\n    def record_imported_symbol(self, sym: SymbolTableNode) -> None:\n        \"\"\"If the symbol was not defined in current module, add its module to module_refs.\"\"\"\n        if sym.kind == LDEF or sym.node is None:\n            return\n        node = sym.node\n        if isinstance(node, PlaceholderNode) or not node.fullname:\n            # This node is not ready yet.\n            return\n        if node.fullname.startswith((\"builtins.\", \"typing.\")):\n            # Skip dependencies on builtins/typing.\n            return\n        # Modules, classes, and type aliases store defining module directly.\n        if isinstance(node, MypyFile):\n            fullname = node.fullname\n        elif isinstance(node, TypeInfo):\n            fullname = node.module_name\n        elif isinstance(node, TypeAlias):\n            fullname = node.module\n        elif isinstance(node, (Var, FuncDef, OverloadedFuncDef, Decorator)):\n            # For functions/variables infer defining module from enclosing class.\n            info = node.var.info if isinstance(node, Decorator) else node.info\n            if info:\n                fullname = info.module_name\n            else:\n                # global function/variable\n                fullname = node.fullname.rsplit(\".\", maxsplit=1)[0]\n        else:\n            # Some nodes (currently only TypeVarLikeExpr subclasses) don't store\n            # module fullname explicitly, infer it from the node fullname iteratively.\n            # TODO: this is not 100% robust for type variables nested within a class\n            # with a name that matches name of a submodule.\n            fullname = node.fullname.rsplit(\".\", maxsplit=1)[0]\n            if fullname == self.cur_mod_id:\n                return\n            while \".\" in fullname and fullname not in self.modules:\n                fullname = fullname.rsplit(\".\", maxsplit=1)[0]\n        if fullname != self.cur_mod_id:\n            self.cur_mod_node.module_refs.add(fullname)\n\n    def _lookup(\n        self, name: str, ctx: Context, suppress_errors: bool = False\n    ) -> SymbolTableNode | None:\n        \"\"\"Look up an unqualified (no dots) name in all active namespaces.\n\n        Note that the result may contain a PlaceholderNode. The caller may\n        want to defer in that case.\n\n        Generate an error if the name is not defined unless suppress_errors\n        is true or the current namespace is incomplete. In the latter case\n        defer.\n        \"\"\"\n        implicit_name = False\n        # 1a. Name declared using 'global x' takes precedence\n        if name in self.global_decls[-1]:\n            if name in self.globals:\n                return self.globals[name]\n            if not suppress_errors:\n                self.name_not_defined(name, ctx)\n            return None\n        # 1b. Name declared using 'nonlocal x' takes precedence\n        if name in self.nonlocal_decls[-1]:\n            for table in reversed(self.locals[:-1]):\n                if table is not None and name in table:\n                    return table[name]\n            if not suppress_errors:\n                self.name_not_defined(name, ctx)\n            return None\n        # 2a. Class attributes (if within class definition)\n        if self.type and not self.is_func_scope() and name in self.type.names:\n            node = self.type.names[name]\n            if not node.implicit:\n                if self.is_active_symbol_in_class_body(node.node):\n                    return node\n            else:\n                # Defined through self.x assignment\n                implicit_name = True\n                implicit_node = node\n        # 2b. Class attributes __qualname__ and __module__\n        if self.type and not self.is_func_scope() and name in {\"__qualname__\", \"__module__\"}:\n            v = Var(name, self.str_type())\n            v._fullname = self.qualified_name(name)\n            return SymbolTableNode(MDEF, v)\n        # 3. Local (function) scopes\n        for table in reversed(self.locals):\n            if table is not None and name in table:\n                return table[name]\n\n        # 4. Current file global scope\n        if name in self.globals:\n            return self.globals[name]\n        # 5. Builtins\n        b = self.globals.get(\"__builtins__\", None)\n        if b:\n            assert isinstance(b.node, MypyFile)\n            table = b.node.names\n            if name in table:\n                if len(name) > 1 and name[0] == \"_\" and name[1] != \"_\":\n                    if not suppress_errors:\n                        self.name_not_defined(name, ctx)\n                    return None\n                node = table[name]\n                return node\n        # Give up.\n        if not implicit_name and not suppress_errors:\n            self.name_not_defined(name, ctx)\n        else:\n            if implicit_name:\n                return implicit_node\n        return None\n\n    def is_active_symbol_in_class_body(self, node: SymbolNode | None) -> bool:\n        \"\"\"Can a symbol defined in class body accessed at current statement?\n\n        Only allow access to class attributes textually after\n        the definition, so that it's possible to fall back to the\n        outer scope. Example:\n\n            class X: ...\n\n            class C:\n                X = X  # Initializer refers to outer scope\n\n        Nested classes are an exception, since we want to support\n        arbitrary forward references in type annotations. Also, we\n        allow forward references to type aliases to support recursive\n        types.\n        \"\"\"\n        # TODO: Forward reference to name imported in class body is not\n        #       caught.\n        if self.statement is None:\n            # Assume it's fine -- don't have enough context to check\n            return True\n        if (\n            node is None\n            or self.is_textually_before_statement(node)\n            or not self.is_defined_in_current_module(node.fullname)\n        ):\n            return True\n        if self.is_type_like(node):\n            # Allow forward references to classes/type aliases (see docstring), but\n            # a forward reference should never shadow an existing regular reference.\n            if node.name not in self.globals:\n                return True\n            global_node = self.globals[node.name]\n            if not self.is_textually_before_class(global_node.node):\n                return True\n            return not self.is_type_like(global_node.node)\n        return False\n\n    def is_type_like(self, node: SymbolNode | None) -> bool:\n        return isinstance(node, (TypeInfo, TypeAlias)) or (\n            isinstance(node, PlaceholderNode) and node.becomes_typeinfo\n        )\n\n    def is_textually_before_statement(self, node: SymbolNode) -> bool:\n        \"\"\"Check if a node is defined textually before the current statement\n\n        Note that decorated functions' line number are the same as\n        the top decorator.\n        \"\"\"\n        assert self.statement\n        line_diff = self.statement.line - node.line\n\n        # The first branch handles reference an overloaded function variant inside itself,\n        # this is a corner case where mypy technically deviates from runtime name resolution,\n        # but it is fine because we want an overloaded function to be treated as a single unit.\n        if self.is_overloaded_item(node, self.statement):\n            return False\n        elif isinstance(node, Decorator) and not node.is_overload:\n            return line_diff > len(node.original_decorators)\n        else:\n            return line_diff > 0\n\n    def is_textually_before_class(self, node: SymbolNode | None) -> bool:\n        \"\"\"Similar to above, but check if a node is defined before current class.\"\"\"\n        assert self.type is not None\n        if node is None:\n            return False\n        return node.line < self.type.defn.line\n\n    def is_overloaded_item(self, node: SymbolNode, statement: Statement) -> bool:\n        \"\"\"Check whether the function belongs to the overloaded variants\"\"\"\n        if isinstance(node, OverloadedFuncDef) and isinstance(statement, FuncDef):\n            in_items = statement in {\n                item.func if isinstance(item, Decorator) else item for item in node.items\n            }\n            in_impl = node.impl is not None and (\n                (isinstance(node.impl, Decorator) and statement is node.impl.func)\n                or statement is node.impl\n            )\n            return in_items or in_impl\n        return False\n\n    def is_defined_in_current_module(self, fullname: str | None) -> bool:\n        if not fullname:\n            return False\n        return module_prefix(self.modules, fullname) == self.cur_mod_id\n\n    def lookup_qualified(\n        self, name: str, ctx: Context, suppress_errors: bool = False\n    ) -> SymbolTableNode | None:\n        \"\"\"Lookup a qualified name in all activate namespaces.\n\n        Note that the result may contain a PlaceholderNode. The caller may\n        want to defer in that case.\n\n        Generate an error if the name is not defined unless suppress_errors\n        is true or the current namespace is incomplete. In the latter case\n        defer.\n        \"\"\"\n        if \".\" not in name:\n            # Simple case: look up a short name.\n            return self.lookup(name, ctx, suppress_errors=suppress_errors)\n        parts = name.split(\".\")\n        namespace = self.cur_mod_id\n        sym = self.lookup(parts[0], ctx, suppress_errors=suppress_errors)\n        if sym:\n            for i in range(1, len(parts)):\n                node = sym.node\n                part = parts[i]\n                if isinstance(node, TypeInfo):\n                    nextsym = node.get(part)\n                elif isinstance(node, MypyFile):\n                    nextsym = self.get_module_symbol(node, part)\n                    namespace = node.fullname\n                elif isinstance(node, PlaceholderNode):\n                    return sym\n                elif isinstance(node, TypeAlias) and node.no_args:\n                    assert isinstance(node.target, ProperType)\n                    if isinstance(node.target, Instance):\n                        nextsym = node.target.type.get(part)\n                    else:\n                        nextsym = None\n                else:\n                    if isinstance(node, Var):\n                        typ = get_proper_type(node.type)\n                        if isinstance(typ, AnyType):\n                            # Allow access through Var with Any type without error.\n                            return self.implicit_symbol(sym, name, parts[i:], typ)\n                    # This might be something like valid `P.args` or invalid `P.__bound__` access.\n                    # Important note that `ParamSpecExpr` is also ignored in other places.\n                    # See https://github.com/python/mypy/pull/13468\n                    if isinstance(node, ParamSpecExpr) and part in (\"args\", \"kwargs\"):\n                        return None\n                    # Lookup through invalid node, such as variable or function\n                    nextsym = None\n                if not nextsym or nextsym.module_hidden:\n                    if not suppress_errors:\n                        self.name_not_defined(name, ctx, namespace=namespace)\n                    return None\n                sym = nextsym\n        if sym is not None:\n            self.record_imported_symbol(sym)\n        return sym\n\n    def lookup_type_node(self, expr: Expression) -> SymbolTableNode | None:\n        try:\n            t = self.expr_to_unanalyzed_type(expr)\n        except TypeTranslationError:\n            return None\n        if isinstance(t, UnboundType):\n            n = self.lookup_qualified(t.name, expr, suppress_errors=True)\n            return n\n        return None\n\n    def get_module_symbol(self, node: MypyFile, name: str) -> SymbolTableNode | None:\n        \"\"\"Look up a symbol from a module.\n\n        Return None if no matching symbol could be bound.\n        \"\"\"\n        module = node.fullname\n        names = node.names\n        sym = names.get(name)\n        if not sym:\n            fullname = module + \".\" + name\n            if fullname in self.modules and self.is_visible_import(module, fullname):\n                sym = SymbolTableNode(GDEF, self.modules[fullname])\n            elif self.is_incomplete_namespace(module):\n                self.record_incomplete_ref()\n            elif \"__getattr__\" in names:\n                gvar = self.create_getattr_var(names[\"__getattr__\"], name, fullname)\n                if gvar:\n                    sym = SymbolTableNode(GDEF, gvar)\n            elif self.is_missing_module(fullname):\n                # We use the fullname of the original definition so that we can\n                # detect whether two names refer to the same thing.\n                var_type = AnyType(TypeOfAny.from_unimported_type)\n                v = Var(name, type=var_type)\n                v._fullname = fullname\n                sym = SymbolTableNode(GDEF, v)\n        elif sym.module_hidden:\n            sym = None\n        return sym\n\n    def is_visible_import(self, base_id: str, id: str) -> bool:\n        # TODO: can we reuse SCC-level tracking from build.py instead?\n        if id in self.import_map[self.cur_mod_id]:\n            # Fast path: module is imported locally.\n            return True\n        if base_id not in self.transitive_submodule_imports:\n            # This is a performance optimization for a common pattern. If one module\n            # in a codebase uses import numpy as np; np.foo.bar, then it is likely that\n            # other modules use similar pattern as well. So we pre-compute transitive\n            # dependencies for np, to avoid possible duplicate work in the future.\n            self.add_transitive_submodule_imports(base_id)\n        if self.cur_mod_id not in self.transitive_submodule_imports:\n            self.add_transitive_submodule_imports(self.cur_mod_id)\n        return id in self.transitive_submodule_imports[self.cur_mod_id]\n\n    def add_transitive_submodule_imports(self, mod_id: str) -> None:\n        if mod_id not in self.import_map:\n            return\n        todo = self.import_map[mod_id]\n        seen = {mod_id}\n        result = {mod_id}\n        while todo:\n            dep = todo.pop()\n            if dep in seen:\n                continue\n            seen.add(dep)\n            if \".\" in dep:\n                result.add(dep)\n            if dep in self.transitive_submodule_imports:\n                result |= self.transitive_submodule_imports[dep]\n                continue\n            if dep in self.import_map:\n                todo |= self.import_map[dep]\n        self.transitive_submodule_imports[mod_id] = result\n\n    def is_missing_module(self, module: str) -> bool:\n        return module in self.missing_modules\n\n    def implicit_symbol(\n        self, sym: SymbolTableNode, name: str, parts: list[str], source_type: AnyType\n    ) -> SymbolTableNode:\n        \"\"\"Create symbol for a qualified name reference through Any type.\"\"\"\n        if sym.node is None:\n            basename = None\n        else:\n            basename = sym.node.fullname\n        if basename is None:\n            fullname = name\n        else:\n            fullname = basename + \".\" + \".\".join(parts)\n        var_type = AnyType(TypeOfAny.from_another_any, source_type)\n        var = Var(parts[-1], var_type)\n        var._fullname = fullname\n        return SymbolTableNode(GDEF, var)\n\n    def create_getattr_var(\n        self, getattr_defn: SymbolTableNode, name: str, fullname: str\n    ) -> Var | None:\n        \"\"\"Create a dummy variable using module-level __getattr__ return type.\n\n        If not possible, return None.\n\n        Note that multiple Var nodes can be created for a single name. We\n        can use the from_module_getattr and the fullname attributes to\n        check if two dummy Var nodes refer to the same thing. Reusing Var\n        nodes would require non-local mutable state, which we prefer to\n        avoid.\n        \"\"\"\n        if isinstance(getattr_defn.node, (FuncDef, Var)):\n            node_type = get_proper_type(getattr_defn.node.type)\n            if isinstance(node_type, CallableType):\n                typ = node_type.ret_type\n            else:\n                typ = AnyType(TypeOfAny.from_error)\n            v = Var(name, type=typ)\n            v._fullname = fullname\n            v.from_module_getattr = True\n            return v\n        return None\n\n    def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode:\n        ret = self.lookup_fully_qualified_or_none(fullname)\n        assert ret is not None, fullname\n        return ret\n\n    def lookup_fully_qualified_or_none(self, fullname: str) -> SymbolTableNode | None:\n        \"\"\"Lookup a fully qualified name that refers to a module-level definition.\n\n        Don't assume that the name is defined. This happens in the global namespace --\n        the local module namespace is ignored. This does not dereference indirect\n        refs.\n\n        Note that this can't be used for names nested in class namespaces.\n        \"\"\"\n        # TODO: unify/clean-up/simplify lookup methods, see #4157.\n        module, name = fullname.rsplit(\".\", maxsplit=1)\n\n        if module in self.modules:\n            # If the module exists, look up the name in the module.\n            # This is the common case.\n            filenode = self.modules[module]\n            result = filenode.names.get(name)\n            if result is None and self.is_incomplete_namespace(module):\n                # TODO: More explicit handling of incomplete refs?\n                self.record_incomplete_ref()\n            return result\n        else:\n            # Else, try to find the longest prefix of the module name that is in the modules dictionary.\n            splitted_modules = fullname.split(\".\")\n            names = []\n\n            while splitted_modules and \".\".join(splitted_modules) not in self.modules:\n                names.append(splitted_modules.pop())\n\n            if not splitted_modules or not names:\n                # If no module or name is found, return None.\n                return None\n\n            # Reverse the names list to get the correct order of names.\n            names.reverse()\n\n            module = \".\".join(splitted_modules)\n            filenode = self.modules[module]\n            result = filenode.names.get(names[0])\n\n            if result is None and self.is_incomplete_namespace(module):\n                # TODO: More explicit handling of incomplete refs?\n                self.record_incomplete_ref()\n\n            for part in names[1:]:\n                if result is not None and isinstance(result.node, TypeInfo):\n                    result = result.node.names.get(part)\n                else:\n                    return None\n            return result\n\n    def object_type(self) -> Instance:\n        if self._object_type is None:\n            self._object_type = self.named_type(\"builtins.object\")\n        return self._object_type\n\n    def str_type(self) -> Instance:\n        if self._str_type is None:\n            self._str_type = self.named_type(\"builtins.str\")\n        return self._str_type\n\n    def function_type(self) -> Instance:\n        if self._function_type is None:\n            self._function_type = self.named_type(\"builtins.function\")\n        return self._function_type\n\n    def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance:\n        sym = self.lookup_fully_qualified(fullname)\n        assert sym, \"Internal error: attempted to construct unknown type\"\n        node = sym.node\n        assert isinstance(node, TypeInfo), node\n        if args:\n            # TODO: assert len(args) == len(node.defn.type_vars)\n            return Instance(node, args)\n        return Instance(node, [AnyType(TypeOfAny.special_form)] * len(node.defn.type_vars))\n\n    def named_type_or_none(self, fullname: str, args: list[Type] | None = None) -> Instance | None:\n        sym = self.lookup_fully_qualified_or_none(fullname)\n        if not sym or isinstance(sym.node, PlaceholderNode):\n            return None\n        node = sym.node\n        if isinstance(node, TypeAlias):\n            assert isinstance(node.target, Instance)  # type: ignore[misc]\n            node = node.target.type\n        assert isinstance(node, TypeInfo), node\n        if args is not None:\n            # TODO: assert len(args) == len(node.defn.type_vars)\n            return Instance(node, args)\n        return Instance(node, [AnyType(TypeOfAny.unannotated)] * len(node.defn.type_vars))\n\n    def builtin_type(self, fully_qualified_name: str) -> Instance:\n        \"\"\"Legacy function -- use named_type() instead.\"\"\"\n        return self.named_type(fully_qualified_name)\n\n    def lookup_current_scope(self, name: str) -> SymbolTableNode | None:\n        if self.locals[-1] is not None:\n            return self.locals[-1].get(name)\n        elif self.type is not None:\n            return self.type.names.get(name)\n        else:\n            return self.globals.get(name)\n\n    #\n    # Adding symbols\n    #\n\n    def add_symbol(\n        self,\n        name: str,\n        node: SymbolNode,\n        context: Context,\n        module_public: bool = True,\n        module_hidden: bool = False,\n        can_defer: bool = True,\n        escape_comprehensions: bool = False,\n        no_progress: bool = False,\n        type_param: bool = False,\n    ) -> bool:\n        \"\"\"Add symbol to the currently active symbol table.\n\n        Generally additions to symbol table should go through this method or\n        one of the methods below so that kinds, redefinitions, conditional\n        definitions, and skipped names are handled consistently.\n\n        Return True if we actually added the symbol, or False if we refused to do so\n        (because something is not ready).\n\n        If can_defer is True, defer current target if adding a placeholder.\n        \"\"\"\n        if self.is_func_scope():\n            kind = LDEF\n        elif self.type is not None:\n            kind = MDEF\n        else:\n            kind = GDEF\n        symbol = SymbolTableNode(\n            kind, node, module_public=module_public, module_hidden=module_hidden\n        )\n        return self.add_symbol_table_node(\n            name, symbol, context, can_defer, escape_comprehensions, no_progress, type_param\n        )\n\n    def add_symbol_skip_local(self, name: str, node: SymbolNode) -> None:\n        \"\"\"Same as above, but skipping the local namespace.\n\n        This doesn't check for previous definition and is only used\n        for serialization of method-level classes.\n\n        Classes defined within methods can be exposed through an\n        attribute type, but method-level symbol tables aren't serialized.\n        This method can be used to add such classes to an enclosing,\n        serialized symbol table.\n        \"\"\"\n        # TODO: currently this is only used by named tuples and typed dicts.\n        # Use this method also by normal classes, see issue #6422.\n        if self.type is not None:\n            names = self.type.names\n            kind = MDEF\n        else:\n            names = self.globals\n            kind = GDEF\n        symbol = SymbolTableNode(kind, node)\n        names[name] = symbol\n\n    def add_symbol_table_node(\n        self,\n        name: str,\n        symbol: SymbolTableNode,\n        context: Context | None = None,\n        can_defer: bool = True,\n        escape_comprehensions: bool = False,\n        no_progress: bool = False,\n        type_param: bool = False,\n    ) -> bool:\n        \"\"\"Add symbol table node to the currently active symbol table.\n\n        Return True if we actually added the symbol, or False if we refused\n        to do so (because something is not ready or it was a no-op).\n\n        Generate an error if there is an invalid redefinition.\n\n        If context is None, unconditionally add node, since we can't report\n        an error. Note that this is used by plugins to forcibly replace nodes!\n\n        TODO: Prevent plugins from replacing nodes, as it could cause problems?\n\n        Args:\n            name: short name of symbol\n            symbol: Node to add\n            can_defer: if True, defer current target if adding a placeholder\n            context: error context (see above about None value)\n        \"\"\"\n        names = self.current_symbol_table(\n            escape_comprehensions=escape_comprehensions, type_param=type_param\n        )\n        existing = names.get(name)\n        if isinstance(symbol.node, PlaceholderNode) and can_defer:\n            if context is not None:\n                self.process_placeholder(name, \"name\", context)\n            else:\n                # see note in docstring describing None contexts\n                self.defer()\n\n        if (\n            existing is not None\n            and context is not None\n            and not is_valid_replacement(existing, symbol)\n        ):\n            # There is an existing node, so this may be a redefinition.\n            # If the new node points to the same node as the old one,\n            # or if both old and new nodes are placeholders, we don't\n            # need to do anything.\n            old = existing.node\n            new = symbol.node\n            if isinstance(new, PlaceholderNode):\n                # We don't know whether this is okay. Let's wait until the next iteration.\n                return False\n            if not is_same_symbol(old, new):\n                if isinstance(new, (FuncDef, Decorator, OverloadedFuncDef, TypeInfo)):\n                    self.add_redefinition(names, name, symbol)\n                if isinstance(old, Var) and is_init_only(old):\n                    if old.has_explicit_value:\n                        self.fail(\"InitVar with default value cannot be redefined\", context)\n                elif not (\n                    isinstance(new, (FuncDef, Decorator)) and self.set_original_def(old, new)\n                ):\n                    self.name_already_defined(name, context, existing)\n        elif type_param or (\n            name not in self.missing_names[-1] and \"*\" not in self.missing_names[-1]\n        ):\n            names[name] = symbol\n            if not no_progress:\n                self.progress = True\n            return True\n        return False\n\n    def add_redefinition(self, names: SymbolTable, name: str, symbol: SymbolTableNode) -> None:\n        \"\"\"Add a symbol table node that reflects a redefinition as a function or a class.\n\n        Redefinitions need to be added to the symbol table so that they can be found\n        through AST traversal, but they have dummy names of form 'name-redefinition[N]',\n        where N ranges over 2, 3, ... (omitted for the first redefinition).\n\n        Note: we always store redefinitions independently of whether they are valid or not\n        (so they will be semantically analyzed), the caller should give an error for invalid\n        redefinitions (such as e.g. variable redefined as a class).\n        \"\"\"\n        i = 1\n        # Don't serialize redefined nodes. They are likely to have\n        # busted internal references which can cause problems with\n        # serialization and they can't have any external references to\n        # them.\n        symbol.no_serialize = True\n        while True:\n            if i == 1:\n                new_name = f\"{name}-redefinition\"\n            else:\n                new_name = f\"{name}-redefinition{i}\"\n            existing = names.get(new_name)\n            if existing is None:\n                names[new_name] = symbol\n                return\n            elif existing.node is symbol.node:\n                # Already there\n                return\n            i += 1\n\n    def add_local(self, node: Var | FuncDef | OverloadedFuncDef, context: Context) -> None:\n        \"\"\"Add local variable or function.\"\"\"\n        assert self.is_func_scope()\n        name = node.name\n        node._fullname = name\n        self.add_symbol(name, node, context)\n\n    def _get_node_for_class_scoped_import(\n        self, name: str, symbol_node: SymbolNode | None, context: Context\n    ) -> SymbolNode | None:\n        if symbol_node is None:\n            return None\n        # I promise this type checks; I'm just making mypyc issues go away.\n        # mypyc is absolutely convinced that `symbol_node` narrows to a Var in the following,\n        # when it can also be a FuncBase. Once fixed, `f` in the following can be removed.\n        # See also https://github.com/mypyc/mypyc/issues/892\n        f: Callable[[object], Any] = lambda x: x\n        if isinstance(f(symbol_node), (Decorator, FuncBase, Var)):\n            # For imports in class scope, we construct a new node to represent the symbol and\n            # set its `info` attribute to `self.type`.\n            existing = self.current_symbol_table().get(name)\n            if (\n                # The redefinition checks in `add_symbol_table_node` don't work for our\n                # constructed Var / FuncBase, so check for possible redefinitions here.\n                existing is not None\n                and isinstance(f(existing.node), (Decorator, FuncBase, Var))\n                and (\n                    isinstance(f(existing.type), f(AnyType))\n                    or f(existing.type) == f(symbol_node).type\n                )\n            ):\n                return existing.node\n\n            # Construct the new node\n            if isinstance(f(symbol_node), (FuncBase, Decorator)):\n                # In theory we could construct a new node here as well, but in practice\n                # it doesn't work well, see #12197\n                typ: Type | None = AnyType(TypeOfAny.from_error)\n                self.fail(\"Unsupported class scoped import\", context)\n            else:\n                typ = f(symbol_node).type\n            symbol_node = Var(name, typ)\n            symbol_node._fullname = self.qualified_name(name)\n            assert self.type is not None  # guaranteed by is_class_scope\n            symbol_node.info = self.type\n            symbol_node.line = context.line\n            symbol_node.column = context.column\n        return symbol_node\n\n    def add_imported_symbol(\n        self,\n        name: str,\n        node: SymbolTableNode,\n        context: ImportBase,\n        module_public: bool,\n        module_hidden: bool,\n    ) -> None:\n        \"\"\"Add an alias to an existing symbol through import.\"\"\"\n        assert not module_hidden or not module_public\n\n        existing_symbol = self.lookup_current_scope(name)\n        if (\n            existing_symbol\n            and not isinstance(existing_symbol.node, PlaceholderNode)\n            and not isinstance(node.node, PlaceholderNode)\n        ):\n            # Import can redefine a variable. They get special treatment.\n            if self.process_import_over_existing_name(name, existing_symbol, node, context):\n                return\n\n        symbol_node: SymbolNode | None = node.node\n\n        if self.is_class_scope():\n            symbol_node = self._get_node_for_class_scoped_import(name, symbol_node, context)\n\n        symbol = SymbolTableNode(\n            node.kind, symbol_node, module_public=module_public, module_hidden=module_hidden\n        )\n        self.add_symbol_table_node(name, symbol, context)\n\n    def add_unknown_imported_symbol(\n        self,\n        name: str,\n        context: Context,\n        target_name: str | None,\n        module_public: bool,\n        module_hidden: bool,\n    ) -> None:\n        \"\"\"Add symbol that we don't know what it points to because resolving an import failed.\n\n        This can happen if a module is missing, or it is present, but doesn't have\n        the imported attribute. The `target_name` is the name of symbol in the namespace\n        it is imported from. For example, for 'from mod import x as y' the target_name is\n        'mod.x'. This is currently used only to track logical dependencies.\n        \"\"\"\n        existing = self.current_symbol_table().get(name)\n        if existing and isinstance(existing.node, Var) and existing.node.is_suppressed_import:\n            # This missing import was already added -- nothing to do here.\n            return\n        var = Var(name)\n        if self.options.logical_deps and target_name is not None:\n            # This makes it possible to add logical fine-grained dependencies\n            # from a missing module. We can't use this by default, since in a\n            # few places we assume that the full name points to a real\n            # definition, but this name may point to nothing.\n            var._fullname = target_name\n        elif self.type:\n            var._fullname = self.type.fullname + \".\" + name\n            var.info = self.type\n        else:\n            var._fullname = self.qualified_name(name)\n        var.is_ready = True\n        any_type = AnyType(TypeOfAny.from_unimported_type, missing_import_name=var._fullname)\n        var.type = any_type\n        var.is_suppressed_import = True\n        self.add_symbol(\n            name, var, context, module_public=module_public, module_hidden=module_hidden\n        )\n\n    #\n    # Other helpers\n    #\n\n    @contextmanager\n    def tvar_scope_frame(self, frame: TypeVarLikeScope) -> Iterator[None]:\n        old_scope = self.tvar_scope\n        self.tvar_scope = frame\n        yield\n        self.tvar_scope = old_scope\n\n    def defer(self, debug_context: Context | None = None, force_progress: bool = False) -> None:\n        \"\"\"Defer current analysis target to be analyzed again.\n\n        This must be called if something in the current target is\n        incomplete or has a placeholder node. However, this must *not*\n        be called during the final analysis iteration! Instead, an error\n        should be generated. Often 'process_placeholder' is a good\n        way to either defer or generate an error.\n\n        NOTE: Some methods, such as 'anal_type', 'mark_incomplete' and\n              'record_incomplete_ref', call this implicitly, or when needed.\n              They are usually preferable to a direct defer() call.\n        \"\"\"\n        assert not self.final_iteration, \"Must not defer during final iteration\"\n        if force_progress:\n            # Usually, we report progress if we have replaced a placeholder node\n            # with an actual valid node. However, sometimes we need to update an\n            # existing node *in-place*. For example, this is used by type aliases\n            # in context of forward references and/or recursive aliases, and in\n            # similar situations (recursive named tuples etc).\n            self.progress = True\n        self.deferred = True\n        # Store debug info for this deferral.\n        line = (\n            debug_context.line if debug_context else self.statement.line if self.statement else -1\n        )\n        self.deferral_debug_context.append((self.cur_mod_id, line))\n\n    def track_incomplete_refs(self) -> Tag:\n        \"\"\"Return tag that can be used for tracking references to incomplete names.\"\"\"\n        return self.num_incomplete_refs\n\n    def found_incomplete_ref(self, tag: Tag) -> bool:\n        \"\"\"Have we encountered an incomplete reference since starting tracking?\"\"\"\n        return self.num_incomplete_refs != tag\n\n    def record_incomplete_ref(self) -> None:\n        \"\"\"Record the encounter of an incomplete reference and defer current analysis target.\"\"\"\n        self.defer()\n        self.num_incomplete_refs += 1\n\n    def mark_incomplete(\n        self,\n        name: str,\n        node: Node,\n        becomes_typeinfo: bool = False,\n        module_public: bool = True,\n        module_hidden: bool = False,\n    ) -> None:\n        \"\"\"Mark a definition as incomplete (and defer current analysis target).\n\n        Also potentially mark the current namespace as incomplete.\n\n        Args:\n            name: The name that we weren't able to define (or '*' if the name is unknown)\n            node: The node that refers to the name (definition or lvalue)\n            becomes_typeinfo: Pass this to PlaceholderNode (used by special forms like\n                named tuples that will create TypeInfos).\n        \"\"\"\n        self.defer(node)\n        if name == \"*\":\n            self.incomplete = True\n        elif not self.is_global_or_nonlocal(name):\n            fullname = self.qualified_name(name)\n            assert self.statement\n            placeholder = PlaceholderNode(\n                fullname, node, self.statement.line, becomes_typeinfo=becomes_typeinfo\n            )\n            self.add_symbol(\n                name,\n                placeholder,\n                module_public=module_public,\n                module_hidden=module_hidden,\n                context=dummy_context(),\n            )\n        self.missing_names[-1].add(name)\n\n    def is_incomplete_namespace(self, fullname: str) -> bool:\n        \"\"\"Is a module or class namespace potentially missing some definitions?\n\n        If a name is missing from an incomplete namespace, we'll need to defer the\n        current analysis target.\n        \"\"\"\n        return fullname in self.incomplete_namespaces\n\n    def process_placeholder(\n        self, name: str | None, kind: str, ctx: Context, force_progress: bool = False\n    ) -> None:\n        \"\"\"Process a reference targeting placeholder node.\n\n        If this is not a final iteration, defer current node,\n        otherwise report an error.\n\n        The 'kind' argument indicates if this a name or attribute expression\n        (used for better error message).\n        \"\"\"\n        if self.final_iteration:\n            self.cannot_resolve_name(name, kind, ctx)\n        else:\n            self.defer(ctx, force_progress=force_progress)\n\n    def cannot_resolve_name(self, name: str | None, kind: str, ctx: Context) -> None:\n        name_format = f' \"{name}\"' if name else \"\"\n        self.fail(f\"Cannot resolve {kind}{name_format} (possible cyclic definition)\", ctx)\n        if self.is_func_scope():\n            self.note(\"Recursive types are not allowed at function scope\", ctx)\n\n    def qualified_name(self, name: str) -> str:\n        if self.type is not None:\n            return self.type._fullname + \".\" + name\n        elif self.is_func_scope():\n            return name\n        else:\n            return self.cur_mod_id + \".\" + name\n\n    @contextmanager\n    def enter(\n        self, function: FuncItem | GeneratorExpr | DictionaryComprehension\n    ) -> Iterator[None]:\n        \"\"\"Enter a function, generator or comprehension scope.\"\"\"\n        names = self.saved_locals.setdefault(function, SymbolTable())\n        self.locals.append(names)\n        is_comprehension = isinstance(function, (GeneratorExpr, DictionaryComprehension))\n        self.scope_stack.append(SCOPE_FUNC if not is_comprehension else SCOPE_COMPREHENSION)\n        self.global_decls.append(set())\n        self.nonlocal_decls.append(set())\n        # -1 since entering block will increment this to 0.\n        self.block_depth.append(-1)\n        self.loop_depth.append(0)\n        self.missing_names.append(set())\n        try:\n            yield\n        finally:\n            self.locals.pop()\n            self.scope_stack.pop()\n            self.global_decls.pop()\n            self.nonlocal_decls.pop()\n            self.block_depth.pop()\n            self.loop_depth.pop()\n            self.missing_names.pop()\n\n    def is_func_scope(self) -> bool:\n        scope_type = self.scope_stack[-1]\n        if scope_type == SCOPE_ANNOTATION:\n            scope_type = self.scope_stack[-2]\n        return scope_type in (SCOPE_FUNC, SCOPE_COMPREHENSION)\n\n    def is_nested_within_func_scope(self) -> bool:\n        \"\"\"Are we underneath a function scope, even if we are in a nested class also?\"\"\"\n        return any(s in (SCOPE_FUNC, SCOPE_COMPREHENSION) for s in self.scope_stack)\n\n    def is_class_scope(self) -> bool:\n        return self.type is not None and not self.is_func_scope()\n\n    def is_module_scope(self) -> bool:\n        return not (self.is_class_scope() or self.is_func_scope())\n\n    def current_symbol_kind(self) -> int:\n        if self.is_class_scope():\n            kind = MDEF\n        elif self.is_func_scope():\n            kind = LDEF\n        else:\n            kind = GDEF\n        return kind\n\n    def current_symbol_table(\n        self, escape_comprehensions: bool = False, type_param: bool = False\n    ) -> SymbolTable:\n        if type_param and self.scope_stack[-1] == SCOPE_ANNOTATION:\n            n = self.locals[-1]\n            assert n is not None\n            return n\n        elif self.is_func_scope():\n            if self.scope_stack[-1] == SCOPE_ANNOTATION:\n                n = self.locals[-2]\n            else:\n                n = self.locals[-1]\n            assert n is not None\n            if escape_comprehensions:\n                assert len(self.locals) == len(self.scope_stack)\n                # Retrieve the symbol table from the enclosing non-comprehension scope.\n                for i, scope_type in enumerate(reversed(self.scope_stack)):\n                    if scope_type != SCOPE_COMPREHENSION:\n                        if i == len(self.locals) - 1:  # The last iteration.\n                            # The caller of the comprehension is in the global space.\n                            names = self.globals\n                        else:\n                            names_candidate = self.locals[-1 - i]\n                            assert (\n                                names_candidate is not None\n                            ), \"Escaping comprehension from invalid scope\"\n                            names = names_candidate\n                        break\n                else:\n                    assert False, \"Should have at least one non-comprehension scope\"\n            else:\n                names = n\n            assert names is not None\n        elif self.type is not None:\n            names = self.type.names\n        else:\n            names = self.globals\n        return names\n\n    def is_global_or_nonlocal(self, name: str) -> bool:\n        return self.is_func_scope() and (\n            name in self.global_decls[-1] or name in self.nonlocal_decls[-1]\n        )\n\n    def add_exports(self, exp_or_exps: Iterable[Expression] | Expression) -> None:\n        exps = [exp_or_exps] if isinstance(exp_or_exps, Expression) else exp_or_exps\n        for exp in exps:\n            if isinstance(exp, StrExpr):\n                self.all_exports.append(exp.value)\n\n    def name_not_defined(self, name: str, ctx: Context, namespace: str | None = None) -> None:\n        incomplete = self.is_incomplete_namespace(namespace or self.cur_mod_id)\n        if (\n            namespace is None\n            and self.type\n            and not self.is_func_scope()\n            and self.incomplete_type_stack\n            and self.incomplete_type_stack[-1]\n            and not self.final_iteration\n        ):\n            # We are processing a class body for the first time, so it is incomplete.\n            incomplete = True\n        if incomplete:\n            # Target namespace is incomplete, so it's possible that the name will be defined\n            # later on. Defer current target.\n            self.record_incomplete_ref()\n            return\n        message = f'Name \"{name}\" is not defined'\n        self.fail(message, ctx, code=codes.NAME_DEFINED)\n\n        if f\"builtins.{name}\" in SUGGESTED_TEST_FIXTURES:\n            # The user probably has a missing definition in a test fixture. Let's verify.\n            fullname = f\"builtins.{name}\"\n            if self.lookup_fully_qualified_or_none(fullname) is None:\n                # Yes. Generate a helpful note.\n                self.msg.add_fixture_note(fullname, ctx)\n\n        modules_with_unimported_hints = {\n            name.split(\".\", 1)[0] for name in TYPES_FOR_UNIMPORTED_HINTS\n        }\n        lowercased = {name.lower(): name for name in TYPES_FOR_UNIMPORTED_HINTS}\n        for module in modules_with_unimported_hints:\n            fullname = f\"{module}.{name}\".lower()\n            if fullname not in lowercased:\n                continue\n            # User probably forgot to import these types.\n            hint = (\n                'Did you forget to import it from \"{module}\"?'\n                ' (Suggestion: \"from {module} import {name}\")'\n            ).format(module=module, name=lowercased[fullname].rsplit(\".\", 1)[-1])\n            self.note(hint, ctx, code=codes.NAME_DEFINED)\n\n    def already_defined(\n        self, name: str, ctx: Context, original_ctx: SymbolTableNode | SymbolNode | None, noun: str\n    ) -> None:\n        if isinstance(original_ctx, SymbolTableNode):\n            node: SymbolNode | None = original_ctx.node\n        elif isinstance(original_ctx, SymbolNode):\n            node = original_ctx\n        else:\n            node = None\n\n        if isinstance(original_ctx, SymbolTableNode) and isinstance(original_ctx.node, MypyFile):\n            # Since this is an import, original_ctx.node points to the module definition.\n            # Therefore, its line number is always 1, which is not useful for this\n            # error message.\n            extra_msg = \" (by an import)\"\n        elif node and node.line != -1 and self.is_local_name(node.fullname):\n            # TODO: Using previous symbol node may give wrong line. We should use\n            #       the line number where the binding was established instead.\n            extra_msg = f\" on line {node.line}\"\n        else:\n            extra_msg = \" (possibly by an import)\"\n        self.fail(\n            f'{noun} \"{unmangle(name)}\" already defined{extra_msg}', ctx, code=codes.NO_REDEF\n        )\n\n    def name_already_defined(\n        self, name: str, ctx: Context, original_ctx: SymbolTableNode | SymbolNode | None = None\n    ) -> None:\n        self.already_defined(name, ctx, original_ctx, noun=\"Name\")\n\n    def attribute_already_defined(\n        self, name: str, ctx: Context, original_ctx: SymbolTableNode | SymbolNode | None = None\n    ) -> None:\n        self.already_defined(name, ctx, original_ctx, noun=\"Attribute\")\n\n    def is_local_name(self, name: str) -> bool:\n        \"\"\"Does name look like reference to a definition in the current module?\"\"\"\n        return self.is_defined_in_current_module(name) or \".\" not in name\n\n    def in_checked_function(self) -> bool:\n        \"\"\"Should we type-check the current function?\n\n        - Yes if --check-untyped-defs is set.\n        - Yes outside functions.\n        - Yes in annotated functions.\n        - No otherwise.\n        \"\"\"\n        if self.options.check_untyped_defs or not self.function_stack:\n            return True\n\n        current_index = len(self.function_stack) - 1\n        while current_index >= 0:\n            current_func = self.function_stack[current_index]\n            if not isinstance(current_func, LambdaExpr):\n                return not current_func.is_dynamic()\n\n            # Special case, `lambda` inherits the \"checked\" state from its parent.\n            # Because `lambda` itself cannot be annotated.\n            # `lambdas` can be deeply nested, so we try to find at least one other parent.\n            current_index -= 1\n\n        # This means that we only have a stack of `lambda` functions,\n        # no regular functions.\n        return True\n\n    def fail(\n        self,\n        msg: str | ErrorMessage,\n        ctx: Context,\n        serious: bool = False,\n        *,\n        code: ErrorCode | None = None,\n        blocker: bool = False,\n    ) -> None:\n        if not serious and not self.in_checked_function():\n            return\n        # In case it's a bug and we don't really have context\n        assert ctx is not None, msg\n        if isinstance(msg, ErrorMessage):\n            if code is None:\n                code = msg.code\n            msg = msg.value\n        self.errors.report(\n            ctx.line,\n            ctx.column,\n            msg,\n            blocker=blocker,\n            code=code,\n            end_line=ctx.end_line,\n            end_column=ctx.end_column,\n        )\n\n    def note(self, msg: str, ctx: Context, code: ErrorCode | None = None) -> None:\n        if not self.in_checked_function():\n            return\n        self.errors.report(ctx.line, ctx.column, msg, severity=\"note\", code=code)\n\n    def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool:\n        if feature not in self.options.enable_incomplete_feature:\n            self.fail(\n                f'\"{feature}\" support is experimental,'\n                f\" use --enable-incomplete-feature={feature} to enable\",\n                ctx,\n            )\n            return False\n        return True\n\n    def accept(self, node: Node) -> None:\n        try:\n            node.accept(self)\n        except Exception as err:\n            report_internal_error(err, self.errors.file, node.line, self.errors, self.options)\n\n    def expr_to_analyzed_type(\n        self,\n        expr: Expression,\n        report_invalid_types: bool = True,\n        allow_placeholder: bool = False,\n        allow_type_any: bool = False,\n        allow_unbound_tvars: bool = False,\n        allow_param_spec_literals: bool = False,\n        allow_unpack: bool = False,\n    ) -> Type | None:\n        if isinstance(expr, CallExpr):\n            # This is a legacy syntax intended mostly for Python 2, we keep it for\n            # backwards compatibility, but new features like generic named tuples\n            # and recursive named tuples will be not supported.\n            expr.accept(self)\n            internal_name, info, tvar_defs = self.named_tuple_analyzer.check_namedtuple(\n                expr, None, self.is_func_scope()\n            )\n            if tvar_defs:\n                self.fail(\"Generic named tuples are not supported for legacy class syntax\", expr)\n                self.note(\"Use either Python 3 class syntax, or the assignment syntax\", expr)\n            if internal_name is None:\n                # Some form of namedtuple is the only valid type that looks like a call\n                # expression. This isn't a valid type.\n                raise TypeTranslationError()\n            elif not info:\n                self.defer(expr)\n                return None\n            assert info.tuple_type, \"NamedTuple without tuple type\"\n            fallback = Instance(info, [])\n            return TupleType(info.tuple_type.items, fallback=fallback)\n        typ = self.expr_to_unanalyzed_type(expr)\n        return self.anal_type(\n            typ,\n            report_invalid_types=report_invalid_types,\n            allow_placeholder=allow_placeholder,\n            allow_type_any=allow_type_any,\n            allow_unbound_tvars=allow_unbound_tvars,\n            allow_param_spec_literals=allow_param_spec_literals,\n            allow_unpack=allow_unpack,\n        )\n\n    def analyze_type_expr(self, expr: Expression) -> None:\n        # There are certain expressions that mypy does not need to semantically analyze,\n        # since they analyzed solely as type. (For example, indexes in type alias definitions\n        # and base classes in class defs). External consumers of the mypy AST may need\n        # them semantically analyzed, however, if they need to treat it as an expression\n        # and not a type. (Which is to say, mypyc needs to do this.) Do the analysis\n        # in a fresh tvar scope in order to suppress any errors about using type variables.\n        with self.tvar_scope_frame(TypeVarLikeScope()), self.allow_unbound_tvars_set():\n            expr.accept(self)\n\n    def type_analyzer(\n        self,\n        *,\n        tvar_scope: TypeVarLikeScope | None = None,\n        allow_tuple_literal: bool = False,\n        allow_unbound_tvars: bool = False,\n        allow_placeholder: bool = False,\n        allow_typed_dict_special_forms: bool = False,\n        allow_final: bool = False,\n        allow_param_spec_literals: bool = False,\n        allow_unpack: bool = False,\n        report_invalid_types: bool = True,\n        prohibit_self_type: str | None = None,\n        prohibit_special_class_field_types: str | None = None,\n        allow_type_any: bool = False,\n    ) -> TypeAnalyser:\n        if tvar_scope is None:\n            tvar_scope = self.tvar_scope\n        tpan = TypeAnalyser(\n            self,\n            tvar_scope,\n            self.plugin,\n            self.options,\n            self.cur_mod_node,\n            self.is_typeshed_stub_file,\n            allow_unbound_tvars=allow_unbound_tvars,\n            allow_tuple_literal=allow_tuple_literal,\n            report_invalid_types=report_invalid_types,\n            allow_placeholder=allow_placeholder,\n            allow_typed_dict_special_forms=allow_typed_dict_special_forms,\n            allow_final=allow_final,\n            allow_param_spec_literals=allow_param_spec_literals,\n            allow_unpack=allow_unpack,\n            prohibit_self_type=prohibit_self_type,\n            prohibit_special_class_field_types=prohibit_special_class_field_types,\n            allow_type_any=allow_type_any,\n        )\n        tpan.in_dynamic_func = bool(self.function_stack and self.function_stack[-1].is_dynamic())\n        tpan.global_scope = not self.type and not self.function_stack\n        return tpan\n\n    def expr_to_unanalyzed_type(self, node: Expression, allow_unpack: bool = False) -> ProperType:\n        return expr_to_unanalyzed_type(\n            node, self.options, self.is_stub_file, allow_unpack=allow_unpack\n        )\n\n    def anal_type(\n        self,\n        typ: Type,\n        *,\n        tvar_scope: TypeVarLikeScope | None = None,\n        allow_tuple_literal: bool = False,\n        allow_unbound_tvars: bool = False,\n        allow_placeholder: bool = False,\n        allow_typed_dict_special_forms: bool = False,\n        allow_final: bool = False,\n        allow_param_spec_literals: bool = False,\n        allow_unpack: bool = False,\n        report_invalid_types: bool = True,\n        prohibit_self_type: str | None = None,\n        prohibit_special_class_field_types: str | None = None,\n        allow_type_any: bool = False,\n    ) -> Type | None:\n        \"\"\"Semantically analyze a type.\n\n        Args:\n            typ: Type to analyze (if already analyzed, this is a no-op)\n            allow_placeholder: If True, may return PlaceholderType if\n                encountering an incomplete definition\n\n        Return None only if some part of the type couldn't be bound *and* it\n        referred to an incomplete namespace or definition. In this case also\n        defer as needed. During a final iteration this won't return None;\n        instead report an error if the type can't be analyzed and return\n        AnyType.\n\n        In case of other errors, report an error message and return AnyType.\n\n        NOTE: The caller shouldn't defer even if this returns None or a\n              placeholder type.\n        \"\"\"\n        has_self_type = find_self_type(\n            typ, lambda name: self.lookup_qualified(name, typ, suppress_errors=True)\n        )\n        if has_self_type and self.type and prohibit_self_type is None:\n            self.setup_self_type()\n        a = self.type_analyzer(\n            tvar_scope=tvar_scope,\n            allow_unbound_tvars=allow_unbound_tvars,\n            allow_tuple_literal=allow_tuple_literal,\n            allow_placeholder=allow_placeholder,\n            allow_typed_dict_special_forms=allow_typed_dict_special_forms,\n            allow_final=allow_final,\n            allow_param_spec_literals=allow_param_spec_literals,\n            allow_unpack=allow_unpack,\n            report_invalid_types=report_invalid_types,\n            prohibit_self_type=prohibit_self_type,\n            prohibit_special_class_field_types=prohibit_special_class_field_types,\n            allow_type_any=allow_type_any,\n        )\n        tag = self.track_incomplete_refs()\n        typ = typ.accept(a)\n        if self.found_incomplete_ref(tag):\n            # Something could not be bound yet.\n            return None\n        self.add_type_alias_deps(a.aliases_used)\n        return typ\n\n    def class_type(self, self_type: Type) -> Type:\n        return TypeType.make_normalized(self_type)\n\n    def schedule_patch(self, priority: int, patch: Callable[[], None]) -> None:\n        self.patches.append((priority, patch))\n\n    def report_hang(self) -> None:\n        print(\"Deferral trace:\")\n        for mod, line in self.deferral_debug_context:\n            print(f\"    {mod}:{line}\")\n        self.errors.report(\n            -1,\n            -1,\n            \"INTERNAL ERROR: maximum semantic analysis iteration count reached\",\n            blocker=True,\n        )\n\n    def add_plugin_dependency(self, trigger: str, target: str | None = None) -> None:\n        \"\"\"Add dependency from trigger to a target.\n\n        If the target is not given explicitly, use the current target.\n        \"\"\"\n        if target is None:\n            target = self.scope.current_target()\n        self.cur_mod_node.plugin_deps.setdefault(trigger, set()).add(target)\n\n    def add_type_alias_deps(\n        self, aliases_used: Collection[str], target: str | None = None\n    ) -> None:\n        \"\"\"Add full names of type aliases on which the current node depends.\n\n        This is used by fine-grained incremental mode to re-check the corresponding nodes.\n        If `target` is None, then the target node used will be the current scope.\n        \"\"\"\n        if not aliases_used:\n            return\n        if target is None:\n            target = self.scope.current_target()\n        self.cur_mod_node.alias_deps[target].update(aliases_used)\n\n    def is_mangled_global(self, name: str) -> bool:\n        # A global is mangled if there exists at least one renamed variant.\n        return unmangle(name) + \"'\" in self.globals\n\n    def is_initial_mangled_global(self, name: str) -> bool:\n        # If there are renamed definitions for a global, the first one has exactly one prime.\n        return name == unmangle(name) + \"'\"\n\n    def parse_bool(self, expr: Expression) -> bool | None:\n        # This wrapper is preserved for plugins.\n        return parse_bool(expr)\n\n    def parse_str_literal(self, expr: Expression) -> str | None:\n        \"\"\"Attempt to find the string literal value of the given expression. Returns `None` if no\n        literal value can be found.\"\"\"\n        if isinstance(expr, StrExpr):\n            return expr.value\n        if isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.type is not None:\n            values = try_getting_str_literals_from_type(expr.node.type)\n            if values is not None and len(values) == 1:\n                return values[0]\n        return None\n\n    def set_future_import_flags(self, module_name: str) -> None:\n        if module_name in FUTURE_IMPORTS:\n            self.modules[self.cur_mod_id].future_import_flags.add(FUTURE_IMPORTS[module_name])\n\n    def is_future_flag_set(self, flag: str) -> bool:\n        return self.modules[self.cur_mod_id].is_future_flag_set(flag)\n\n    def parse_dataclass_transform_spec(self, call: CallExpr) -> DataclassTransformSpec:\n        \"\"\"Build a DataclassTransformSpec from the arguments passed to the given call to\n        typing.dataclass_transform.\"\"\"\n        parameters = DataclassTransformSpec()\n        for name, value in zip(call.arg_names, call.args):\n            # Skip any positional args. Note that any such args are invalid, but we can rely on\n            # typeshed to enforce this and don't need an additional error here.\n            if name is None:\n                continue\n\n            # field_specifiers is currently the only non-boolean argument; check for it first so\n            # so the rest of the block can fail through to handling booleans\n            if name == \"field_specifiers\":\n                parameters.field_specifiers = self.parse_dataclass_transform_field_specifiers(\n                    value\n                )\n                continue\n\n            boolean = require_bool_literal_argument(self, value, name)\n            if boolean is None:\n                continue\n\n            if name == \"eq_default\":\n                parameters.eq_default = boolean\n            elif name == \"order_default\":\n                parameters.order_default = boolean\n            elif name == \"kw_only_default\":\n                parameters.kw_only_default = boolean\n            elif name == \"frozen_default\":\n                parameters.frozen_default = boolean\n            else:\n                self.fail(f'Unrecognized dataclass_transform parameter \"{name}\"', call)\n\n        return parameters\n\n    def parse_dataclass_transform_field_specifiers(self, arg: Expression) -> tuple[str, ...]:\n        if not isinstance(arg, TupleExpr):\n            self.fail('\"field_specifiers\" argument must be a tuple literal', arg)\n            return ()\n\n        names = []\n        for specifier in arg.items:\n            if not isinstance(specifier, RefExpr):\n                self.fail('\"field_specifiers\" must only contain identifiers', specifier)\n                return ()\n            names.append(specifier.fullname)\n        return tuple(names)\n\n    # leafs\n    def visit_int_expr(self, o: IntExpr, /) -> None:\n        return None\n\n    def visit_str_expr(self, o: StrExpr, /) -> None:\n        return None\n\n    def visit_bytes_expr(self, o: BytesExpr, /) -> None:\n        return None\n\n    def visit_float_expr(self, o: FloatExpr, /) -> None:\n        return None\n\n    def visit_complex_expr(self, o: ComplexExpr, /) -> None:\n        return None\n\n    def visit_ellipsis(self, o: EllipsisExpr, /) -> None:\n        return None\n\n    def visit_temp_node(self, o: TempNode, /) -> None:\n        return None\n\n    def visit_pass_stmt(self, o: PassStmt, /) -> None:\n        return None\n\n    def visit_singleton_pattern(self, o: SingletonPattern, /) -> None:\n        return None\n\n    def try_parse_as_type_expression(self, maybe_type_expr: Expression) -> None:\n        \"\"\"Try to parse a value Expression as a type expression.\n        If success then annotate the Expression with the type that it spells.\n        If fails then emit no errors and take no further action.\n\n        A value expression that is parsable as a type expression may be used\n        where a TypeForm is expected to represent the spelled type.\n\n        Unlike ExpressionChecker.try_parse_as_type_expression()\n        (used in the later TypeChecker pass), this function can recognize\n        ALL kinds of type expressions, including type expressions containing\n        string annotations.\n\n        If the provided Expression will be parsable later in\n        ExpressionChecker.try_parse_as_type_expression(), this function will\n        skip parsing the Expression to improve performance, because the later\n        function is called many fewer times (i.e. only lazily in a rare TypeForm\n        type context) than this function is called (i.e. eagerly for EVERY\n        expression in certain syntactic positions).\n        \"\"\"\n        # Count every call to this method for profiling\n        self.type_expression_parse_count += 1\n\n        # Bail ASAP if the Expression matches a common pattern that cannot possibly\n        # be a valid type expression, because this function is called very frequently\n        if not isinstance(maybe_type_expr, MaybeTypeExpression):\n            return\n        # Check types in order from most common to least common, for best performance\n        if isinstance(maybe_type_expr, (NameExpr, MemberExpr)):\n            # Defer parsing to the later TypeChecker pass,\n            # and only lazily in contexts where a TypeForm is expected\n            return\n        elif isinstance(maybe_type_expr, StrExpr):\n            str_value = maybe_type_expr.value  # cache\n            # Filter out string literals with common patterns that could not\n            # possibly be in a type expression\n            if _MULTIPLE_WORDS_NONTYPE_RE.match(str_value):\n                # A common pattern in string literals containing a sentence.\n                # But cannot be a type expression.\n                maybe_type_expr.as_type = None\n                return\n            # Filter out string literals which look like an identifier but\n            # cannot be a type expression, for a few common reasons\n            if _IDENTIFIER_RE.fullmatch(str_value):\n                sym = self.lookup(str_value, UnboundType(str_value), suppress_errors=True)\n                if sym is None:\n                    # Does not refer to anything in the local symbol table\n                    maybe_type_expr.as_type = None\n                    return\n                else:  # sym is not None\n                    node = sym.node  # cache\n                    if isinstance(node, PlaceholderNode) and not node.becomes_typeinfo:\n                        # Either:\n                        # 1. f'Cannot resolve name \"{t.name}\" (possible cyclic definition)'\n                        # 2. Reference to an unknown placeholder node.\n                        maybe_type_expr.as_type = None\n                        return\n                    unbound_tvar_or_paramspec = (\n                        isinstance(node, (TypeVarExpr, TypeVarTupleExpr, ParamSpecExpr))\n                        and self.tvar_scope.get_binding(sym) is None\n                    )\n                    if unbound_tvar_or_paramspec:\n                        # Either:\n                        # 1. unbound_tvar: 'Type variable \"{}\" is unbound' [codes.VALID_TYPE]\n                        # 2. unbound_paramspec: f'ParamSpec \"{name}\" is unbound' [codes.VALID_TYPE]\n                        maybe_type_expr.as_type = None\n                        return\n            else:  # does not look like an identifier\n                if '\"' in str_value or \"'\" in str_value:\n                    # Only valid inside a Literal[...] type\n                    if \"[\" not in str_value:\n                        # Cannot be a Literal[...] type\n                        maybe_type_expr.as_type = None\n                        return\n                elif str_value == \"\":\n                    # Empty string is not a valid type\n                    maybe_type_expr.as_type = None\n                    return\n        elif isinstance(maybe_type_expr, IndexExpr):\n            if isinstance(maybe_type_expr.base, NameExpr):\n                if isinstance(\n                    maybe_type_expr.base.node, Var\n                ) and not self.var_is_typing_special_form(maybe_type_expr.base.node):\n                    # Leftmost part of IndexExpr refers to a Var. Not a valid type.\n                    maybe_type_expr.as_type = None\n                    return\n            elif isinstance(maybe_type_expr.base, MemberExpr):\n                next_leftmost = maybe_type_expr.base\n                while True:\n                    leftmost = next_leftmost.expr\n                    if not isinstance(leftmost, MemberExpr):\n                        break\n                    next_leftmost = leftmost\n                if isinstance(leftmost, NameExpr):\n                    if isinstance(leftmost.node, Var) and not self.var_is_typing_special_form(\n                        leftmost.node\n                    ):\n                        # Leftmost part of IndexExpr refers to a Var. Not a valid type.\n                        maybe_type_expr.as_type = None\n                        return\n                else:\n                    # Leftmost part of IndexExpr is not a NameExpr. Not a valid type.\n                    maybe_type_expr.as_type = None\n                    return\n            else:\n                # IndexExpr base is neither a NameExpr nor MemberExpr. Not a valid type.\n                maybe_type_expr.as_type = None\n                return\n        elif isinstance(maybe_type_expr, OpExpr):\n            if maybe_type_expr.op != \"|\":\n                # Binary operators other than '|' never spell a valid type\n                maybe_type_expr.as_type = None\n                return\n        else:\n            assert_never(maybe_type_expr)\n\n        with self.isolated_error_analysis():\n            try:\n                t = self.expr_to_analyzed_type(maybe_type_expr)\n                if self.errors.is_errors():\n                    t = None\n            except TypeTranslationError:\n                # Not a type expression\n                t = None\n\n            if DEBUG_TYPE_EXPRESSION_FULL_PARSE_FAILURES and t is None:\n                original_flushed_files = set(self.errors.flushed_files)  # save\n                try:\n                    errors = self.errors.new_messages()  # capture\n                finally:\n                    self.errors.flushed_files = original_flushed_files  # restore\n\n                print(\n                    f\"SA.try_parse_as_type_expression: Full parse failure: {maybe_type_expr}, errors={errors!r}\"\n                )\n\n        # Count full parse attempts for profiling\n        if t is not None:\n            self.type_expression_full_parse_success_count += 1\n        else:\n            self.type_expression_full_parse_failure_count += 1\n\n        maybe_type_expr.as_type = t\n\n    @staticmethod\n    def var_is_typing_special_form(var: Var) -> bool:\n        return var.fullname.startswith(\"typing\") and var.fullname in [\n            \"typing.Annotated\",\n            \"typing_extensions.Annotated\",\n            \"typing.Callable\",\n            \"typing.Literal\",\n            \"typing_extensions.Literal\",\n            \"typing.Optional\",\n            \"typing.TypeGuard\",\n            \"typing_extensions.TypeGuard\",\n            \"typing.TypeIs\",\n            \"typing_extensions.TypeIs\",\n            \"typing.Union\",\n        ]\n\n    @contextmanager\n    def isolated_error_analysis(self) -> Iterator[None]:\n        \"\"\"\n        Context manager for performing error analysis that should not\n        affect the main SemanticAnalyzer state.\n\n        Upon entering this context, `self.errors` will start empty.\n        Within this context, you can analyze expressions for errors.\n        Upon exiting this context, the original `self.errors` will be restored,\n        and any errors collected during the analysis will be discarded.\n        \"\"\"\n        # Save state\n        original_errors = self.errors\n        original_num_incomplete_refs = self.num_incomplete_refs\n        original_progress = self.progress\n        original_deferred = self.deferred\n        original_deferral_debug_context_len = len(self.deferral_debug_context)\n\n        self.errors = Errors(Options())\n        try:\n            yield\n        finally:\n            # Restore state\n            self.errors = original_errors\n            self.num_incomplete_refs = original_num_incomplete_refs\n            self.progress = original_progress\n            self.deferred = original_deferred\n            del self.deferral_debug_context[original_deferral_debug_context_len:]\n\n\ndef replace_implicit_first_type(sig: FunctionLike, new: Type) -> FunctionLike:\n    if isinstance(sig, CallableType):\n        if len(sig.arg_types) == 0:\n            return sig\n        return sig.copy_modified(arg_types=[new] + sig.arg_types[1:])\n    elif isinstance(sig, Overloaded):\n        return Overloaded(\n            [cast(CallableType, replace_implicit_first_type(i, new)) for i in sig.items]\n        )\n    else:\n        assert False\n\n\ndef refers_to_fullname(node: Expression, fullnames: str | tuple[str, ...]) -> bool:\n    \"\"\"Is node a name or member expression with the given full name?\"\"\"\n    if not isinstance(fullnames, tuple):\n        fullnames = (fullnames,)\n\n    if not isinstance(node, RefExpr):\n        return False\n    if node.fullname in fullnames:\n        return True\n    if isinstance(node.node, TypeAlias) and not node.node.python_3_12_type_alias:\n        return is_named_instance(node.node.target, fullnames)\n    return False\n\n\ndef refers_to_class_or_function(node: Expression) -> bool:\n    \"\"\"Does semantically analyzed node refer to a class?\"\"\"\n    return isinstance(node, RefExpr) and isinstance(\n        node.node, (TypeInfo, FuncDef, OverloadedFuncDef)\n    )\n\n\ndef find_duplicate(list: list[T]) -> T | None:\n    \"\"\"If the list has duplicates, return one of the duplicates.\n\n    Otherwise, return None.\n    \"\"\"\n    for i in range(1, len(list)):\n        if list[i] in list[:i]:\n            return list[i]\n    return None\n\n\ndef remove_imported_names_from_symtable(names: SymbolTable, module: str) -> None:\n    \"\"\"Remove all imported names from the symbol table of a module.\"\"\"\n    removed: list[str] = []\n    for name, node in names.items():\n        if node.node is None:\n            continue\n        fullname = node.node.fullname\n        prefix = fullname[: fullname.rfind(\".\")]\n        if prefix != module:\n            removed.append(name)\n    for name in removed:\n        del names[name]\n\n\ndef make_any_non_explicit(t: Type) -> Type:\n    \"\"\"Replace all Any types within in with Any that has attribute 'explicit' set to False\"\"\"\n    return t.accept(MakeAnyNonExplicit())\n\n\nclass MakeAnyNonExplicit(TrivialSyntheticTypeTranslator):\n    def visit_any(self, t: AnyType) -> Type:\n        if t.type_of_any == TypeOfAny.explicit:\n            return t.copy_modified(TypeOfAny.special_form)\n        return t\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        return t.copy_modified(args=[a.accept(self) for a in t.args])\n\n\ndef make_any_non_unimported(t: Type) -> Type:\n    \"\"\"Replace all Any types that come from unimported types with special form Any.\"\"\"\n    return t.accept(MakeAnyNonUnimported())\n\n\nclass MakeAnyNonUnimported(TrivialSyntheticTypeTranslator):\n    def visit_any(self, t: AnyType) -> Type:\n        if t.type_of_any == TypeOfAny.from_unimported_type:\n            return t.copy_modified(TypeOfAny.special_form, missing_import_name=None)\n        return t\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        return t.copy_modified(args=[a.accept(self) for a in t.args])\n\n\ndef apply_semantic_analyzer_patches(patches: list[tuple[int, Callable[[], None]]]) -> None:\n    \"\"\"Call patch callbacks in the right order.\n\n    This should happen after semantic analyzer pass 3.\n    \"\"\"\n    patches_by_priority = sorted(patches, key=lambda x: x[0])\n    for priority, patch_func in patches_by_priority:\n        patch_func()\n\n\ndef names_modified_by_assignment(s: AssignmentStmt) -> list[NameExpr]:\n    \"\"\"Return all unqualified (short) names assigned to in an assignment statement.\"\"\"\n    result: list[NameExpr] = []\n    for lvalue in s.lvalues:\n        result += names_modified_in_lvalue(lvalue)\n    return result\n\n\ndef names_modified_in_lvalue(lvalue: Lvalue) -> list[NameExpr]:\n    \"\"\"Return all NameExpr assignment targets in an Lvalue.\"\"\"\n    if isinstance(lvalue, NameExpr):\n        return [lvalue]\n    elif isinstance(lvalue, StarExpr):\n        return names_modified_in_lvalue(lvalue.expr)\n    elif isinstance(lvalue, (ListExpr, TupleExpr)):\n        result: list[NameExpr] = []\n        for item in lvalue.items:\n            result += names_modified_in_lvalue(item)\n        return result\n    return []\n\n\ndef is_same_var_from_getattr(n1: SymbolNode | None, n2: SymbolNode | None) -> bool:\n    \"\"\"Do n1 and n2 refer to the same Var derived from module-level __getattr__?\"\"\"\n    return (\n        isinstance(n1, Var)\n        and n1.from_module_getattr\n        and isinstance(n2, Var)\n        and n2.from_module_getattr\n        and n1.fullname == n2.fullname\n    )\n\n\ndef dummy_context() -> Context:\n    return TempNode(AnyType(TypeOfAny.special_form))\n\n\ndef is_valid_replacement(old: SymbolTableNode, new: SymbolTableNode) -> bool:\n    \"\"\"Can symbol table node replace an existing one?\n\n    These are the only valid cases:\n\n    1. Placeholder gets replaced with a non-placeholder\n    2. Placeholder that isn't known to become type replaced with a\n       placeholder that can become a type\n    \"\"\"\n    if isinstance(old.node, PlaceholderNode):\n        if isinstance(new.node, PlaceholderNode):\n            return not old.node.becomes_typeinfo and new.node.becomes_typeinfo\n        else:\n            return True\n    return False\n\n\ndef is_same_symbol(a: SymbolNode | None, b: SymbolNode | None) -> bool:\n    return (\n        a == b\n        or (isinstance(a, PlaceholderNode) and isinstance(b, PlaceholderNode))\n        or is_same_var_from_getattr(a, b)\n    )\n\n\ndef is_trivial_body(block: Block) -> bool:\n    \"\"\"Returns 'true' if the given body is \"trivial\" -- if it contains just a \"pass\",\n    \"...\" (ellipsis), or \"raise NotImplementedError()\". A trivial body may also\n    start with a statement containing just a string (e.g. a docstring).\n\n    Note: Functions that raise other kinds of exceptions do not count as\n    \"trivial\". We use this function to help us determine when it's ok to\n    relax certain checks on body, but functions that raise arbitrary exceptions\n    are more likely to do non-trivial work. For example:\n\n       def halt(self, reason: str = ...) -> NoReturn:\n           raise MyCustomError(\"Fatal error: \" + reason, self.line, self.context)\n\n    A function that raises just NotImplementedError is much less likely to be\n    this complex.\n\n    Note: If you update this, you may also need to update\n    mypy.fastparse.is_possible_trivial_body!\n    \"\"\"\n    body = block.body\n    if not body:\n        # Functions have empty bodies only if the body is stripped or the function is\n        # generated or deserialized. In these cases the body is unknown.\n        return False\n\n    # Skip a docstring\n    if isinstance(body[0], ExpressionStmt) and isinstance(body[0].expr, StrExpr):\n        body = block.body[1:]\n\n    if len(body) == 0:\n        # There's only a docstring (or no body at all).\n        return True\n    elif len(body) > 1:\n        return False\n\n    stmt = body[0]\n\n    if isinstance(stmt, RaiseStmt):\n        expr = stmt.expr\n        if expr is None:\n            return False\n        if isinstance(expr, CallExpr):\n            expr = expr.callee\n\n        return isinstance(expr, NameExpr) and expr.fullname == \"builtins.NotImplementedError\"\n\n    return isinstance(stmt, PassStmt) or (\n        isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr)\n    )\n\n\ndef is_init_only(node: Var) -> bool:\n    return (\n        isinstance(type := get_proper_type(node.type), Instance)\n        and type.type.fullname == \"dataclasses.InitVar\"\n    )\n\n\ndef erase_func_annotations(func: FuncDef) -> None:\n    func.type_args = None\n    for arg in func.arguments:\n        arg.type_annotation = None\n        arg.variable.type = None\n    func.type = None\n    func.unanalyzed_type = None\n"
  },
  {
    "path": "mypy/semanal_classprop.py",
    "content": "\"\"\"Calculate some properties of classes.\n\nThese happen after semantic analysis and before type checking.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final\n\nfrom mypy.errors import Errors\nfrom mypy.nodes import (\n    IMPLICITLY_ABSTRACT,\n    IS_ABSTRACT,\n    CallExpr,\n    Decorator,\n    FuncDef,\n    Node,\n    OverloadedFuncDef,\n    PromoteExpr,\n    SymbolTable,\n    TypeInfo,\n    Var,\n)\nfrom mypy.options import Options\nfrom mypy.types import MYPYC_NATIVE_INT_NAMES, Instance, ProperType\n\n# Hard coded type promotions (shared between all Python versions).\n# These add extra ad-hoc edges to the subtyping relation. For example,\n# int is considered a subtype of float, even though there is no\n# subclass relationship.\n# Note that the bytearray -> bytes promotion is a little unsafe\n# as some functions only accept bytes objects. Here convenience\n# trumps safety.\nTYPE_PROMOTIONS: Final = {\n    \"builtins.int\": \"float\",\n    \"builtins.float\": \"complex\",\n    \"builtins.bytearray\": \"bytes\",\n    \"builtins.memoryview\": \"bytes\",\n}\n\n\ndef calculate_class_abstract_status(typ: TypeInfo, is_stub_file: bool, errors: Errors) -> None:\n    \"\"\"Calculate abstract status of a class.\n\n    Set is_abstract of the type to True if the type has an unimplemented\n    abstract attribute.  Also compute a list of abstract attributes.\n    Report error is required ABCMeta metaclass is missing.\n    \"\"\"\n    typ.is_abstract = False\n    typ.abstract_attributes = []\n    if typ.typeddict_type:\n        return  # TypedDict can't be abstract\n    concrete: set[str] = set()\n    # List of abstract attributes together with their abstract status\n    abstract: list[tuple[str, int]] = []\n    abstract_in_this_class: list[str] = []\n    if typ.is_newtype:\n        # Special case: NewTypes are considered as always non-abstract, so they can be used as:\n        #     Config = NewType('Config', Mapping[str, str])\n        #     default = Config({'cannot': 'modify'})  # OK\n        return\n    for base in typ.mro:\n        for name, symnode in base.names.items():\n            node = symnode.node\n            if isinstance(node, OverloadedFuncDef):\n                # Unwrap an overloaded function definition. We can just\n                # check arbitrarily the first overload item. If the\n                # different items have a different abstract status, there\n                # should be an error reported elsewhere.\n                if node.items:  # can be empty for invalid overloads\n                    func: Node | None = node.items[0]\n                else:\n                    func = None\n            else:\n                func = node\n            if isinstance(func, Decorator):\n                func = func.func\n            if isinstance(func, FuncDef):\n                if (\n                    func.abstract_status in (IS_ABSTRACT, IMPLICITLY_ABSTRACT)\n                    and name not in concrete\n                ):\n                    typ.is_abstract = True\n                    abstract.append((name, func.abstract_status))\n                    if base is typ:\n                        abstract_in_this_class.append(name)\n            elif isinstance(node, Var):\n                if node.is_abstract_var and name not in concrete:\n                    typ.is_abstract = True\n                    abstract.append((name, IS_ABSTRACT))\n                    if base is typ:\n                        abstract_in_this_class.append(name)\n            concrete.add(name)\n    # In stubs, abstract classes need to be explicitly marked because it is too\n    # easy to accidentally leave a concrete class abstract by forgetting to\n    # implement some methods.\n    typ.abstract_attributes = sorted(abstract)\n    if is_stub_file:\n        if typ.declared_metaclass and typ.declared_metaclass.type.has_base(\"abc.ABCMeta\"):\n            return\n        if typ.is_protocol:\n            return\n        if abstract and not abstract_in_this_class:\n\n            def report(message: str, severity: str) -> None:\n                errors.report(typ.line, typ.column, message, severity=severity)\n\n            attrs = \", \".join(f'\"{attr}\"' for attr, _ in sorted(abstract))\n            report(f\"Class {typ.fullname} has abstract attributes {attrs}\", \"error\")\n            report(\n                \"If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass\", \"note\"\n            )\n    if typ.is_final and abstract:\n        attrs = \", \".join(f'\"{attr}\"' for attr, _ in sorted(abstract))\n        errors.report(\n            typ.line, typ.column, f\"Final class {typ.fullname} has abstract attributes {attrs}\"\n        )\n\n\ndef check_protocol_status(info: TypeInfo, errors: Errors) -> None:\n    \"\"\"Check that all classes in MRO of a protocol are protocols\"\"\"\n    if info.is_protocol:\n        for type in info.bases:\n            if not type.type.is_protocol and type.type.fullname != \"builtins.object\":\n                errors.report(\n                    info.line,\n                    info.column,\n                    \"All bases of a protocol must be protocols\",\n                    severity=\"error\",\n                )\n\n\ndef calculate_class_vars(info: TypeInfo) -> None:\n    \"\"\"Try to infer additional class variables.\n\n    Subclass attribute assignments with no type annotation are assumed\n    to be classvar if overriding a declared classvar from the base\n    class.\n\n    This must happen after the main semantic analysis pass, since\n    this depends on base class bodies having been fully analyzed.\n    \"\"\"\n    for name, sym in info.names.items():\n        node = sym.node\n        if isinstance(node, Var) and node.info and node.is_inferred and not node.is_classvar:\n            for base in info.mro[1:]:\n                member = base.names.get(name)\n                if member is not None and isinstance(member.node, Var) and member.node.is_classvar:\n                    node.is_classvar = True\n\n\ndef add_type_promotion(\n    info: TypeInfo, module_names: SymbolTable, options: Options, builtin_names: SymbolTable\n) -> None:\n    \"\"\"Setup extra, ad-hoc subtyping relationships between classes (promotion).\n\n    This includes things like 'int' being compatible with 'float'.\n    \"\"\"\n    defn = info.defn\n    promote_targets: list[ProperType] = []\n    for decorator in defn.decorators:\n        if isinstance(decorator, CallExpr):\n            analyzed = decorator.analyzed\n            if isinstance(analyzed, PromoteExpr):\n                # _promote class decorator (undocumented feature).\n                promote_targets.append(analyzed.type)\n    if not promote_targets:\n        if defn.fullname in TYPE_PROMOTIONS:\n            target_sym = module_names.get(TYPE_PROMOTIONS[defn.fullname])\n            if defn.fullname == \"builtins.bytearray\" and options.disable_bytearray_promotion:\n                target_sym = None\n            elif defn.fullname == \"builtins.memoryview\" and options.disable_memoryview_promotion:\n                target_sym = None\n            # With test stubs, the target may not exist.\n            if target_sym:\n                target_info = target_sym.node\n                assert isinstance(target_info, TypeInfo)\n                promote_targets.append(Instance(target_info, []))\n    # Special case the promotions between 'int' and native integer types.\n    # These have promotions going both ways, such as from 'int' to 'i64'\n    # and 'i64' to 'int', for convenience.\n    if defn.fullname in MYPYC_NATIVE_INT_NAMES:\n        int_sym = builtin_names[\"int\"]\n        assert isinstance(int_sym.node, TypeInfo)\n        int_sym.node._promote.append(Instance(defn.info, []))\n        defn.info.alt_promote = Instance(int_sym.node, [])\n    if promote_targets:\n        defn.info._promote.extend(promote_targets)\n"
  },
  {
    "path": "mypy/semanal_enum.py",
    "content": "\"\"\"Semantic analysis of call-based Enum definitions.\n\nThis is conceptually part of mypy.semanal (semantic analyzer pass 2).\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final, cast\n\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    EXCLUDED_ENUM_ATTRIBUTES,\n    MDEF,\n    AssignmentStmt,\n    CallExpr,\n    Context,\n    DictExpr,\n    EnumCallExpr,\n    Expression,\n    ListExpr,\n    MemberExpr,\n    NameExpr,\n    RefExpr,\n    StrExpr,\n    SymbolTableNode,\n    TupleExpr,\n    TypeInfo,\n    Var,\n    is_StrExpr_list,\n)\nfrom mypy.options import Options\nfrom mypy.semanal_shared import SemanticAnalyzerInterface\nfrom mypy.types import LiteralType, get_proper_type\n\n# Note: 'enum.EnumMeta' is deliberately excluded from this list. Classes that directly use\n# enum.EnumMeta do not necessarily automatically have the 'name' and 'value' attributes.\nENUM_BASES: Final = frozenset(\n    (\"enum.Enum\", \"enum.IntEnum\", \"enum.Flag\", \"enum.IntFlag\", \"enum.StrEnum\")\n)\nENUM_SPECIAL_PROPS: Final = frozenset(\n    (\n        \"name\",\n        \"value\",\n        \"_name_\",\n        \"_value_\",\n        *EXCLUDED_ENUM_ATTRIBUTES,\n        # Also attributes from `object`:\n        \"__module__\",\n        \"__annotations__\",\n        \"__doc__\",\n        \"__slots__\",\n        \"__dict__\",\n    )\n)\n\n\nclass EnumCallAnalyzer:\n    def __init__(self, options: Options, api: SemanticAnalyzerInterface) -> None:\n        self.options = options\n        self.api = api\n\n    def process_enum_call(self, s: AssignmentStmt, is_func_scope: bool) -> bool:\n        \"\"\"Check if s defines an Enum; if yes, store the definition in symbol table.\n\n        Return True if this looks like an Enum definition (but maybe with errors),\n        otherwise return False.\n        \"\"\"\n        if len(s.lvalues) != 1 or not isinstance(s.lvalues[0], (NameExpr, MemberExpr)):\n            return False\n        lvalue = s.lvalues[0]\n        name = lvalue.name\n        enum_call = self.check_enum_call(s.rvalue, name, is_func_scope)\n        if enum_call is None:\n            return False\n        if isinstance(lvalue, MemberExpr):\n            self.fail(\"Enum type as attribute is not supported\", lvalue)\n            return False\n        # Yes, it's a valid Enum definition. Add it to the symbol table.\n        self.api.add_symbol(name, enum_call, s)\n        return True\n\n    def check_enum_call(\n        self, node: Expression, var_name: str, is_func_scope: bool\n    ) -> TypeInfo | None:\n        \"\"\"Check if a call defines an Enum.\n\n        Example:\n\n          A = enum.Enum('A', 'foo bar')\n\n        is equivalent to:\n\n          class A(enum.Enum):\n              foo = 1\n              bar = 2\n        \"\"\"\n        if not isinstance(node, CallExpr):\n            return None\n        call = node\n        callee = call.callee\n        if not isinstance(callee, RefExpr):\n            return None\n        fullname = callee.fullname\n        if fullname not in ENUM_BASES:\n            return None\n\n        new_class_name, items, values, ok = self.parse_enum_call_args(\n            call, fullname.split(\".\")[-1]\n        )\n        if not ok:\n            # Error. Construct dummy return value.\n            name = var_name\n            if is_func_scope:\n                name += \"@\" + str(call.line)\n            info = self.build_enum_call_typeinfo(name, [], fullname, node.line)\n        else:\n            if new_class_name != var_name:\n                msg = f'String argument 1 \"{new_class_name}\" to {fullname}(...) does not match variable name \"{var_name}\"'\n                self.fail(msg, call)\n\n            name = cast(StrExpr, call.args[0]).value\n            if name != var_name or is_func_scope:\n                # Give it a unique name derived from the line number.\n                name += \"@\" + str(call.line)\n            info = self.build_enum_call_typeinfo(name, items, fullname, call.line)\n        # Store generated TypeInfo under both names, see semanal_namedtuple for more details.\n        if name != var_name or is_func_scope:\n            self.api.add_symbol_skip_local(name, info)\n        call.analyzed = EnumCallExpr(info, items, values)\n        call.analyzed.set_line(call)\n        info.line = node.line\n        return info\n\n    def build_enum_call_typeinfo(\n        self, name: str, items: list[str], fullname: str, line: int\n    ) -> TypeInfo:\n        base = self.api.named_type_or_none(fullname)\n        assert base is not None\n        info = self.api.basic_new_typeinfo(name, base, line)\n        info.metaclass_type = info.calculate_metaclass_type()\n        info.is_enum = True\n        for item in items:\n            var = Var(item)\n            var.info = info\n            var.is_property = True\n            # When an enum is created by its functional form `Enum(name, values)`\n            # - if it is a string it is first split by commas/whitespace\n            # - if it is an iterable of single items each item is assigned a value starting at `start`\n            # - if it is an iterable of (name, value) then the given values will be used\n            # either way, each item should be treated as if it has an explicit value.\n            var.has_explicit_value = True\n            var._fullname = f\"{info.fullname}.{item}\"\n            info.names[item] = SymbolTableNode(MDEF, var)\n        return info\n\n    def parse_enum_call_args(\n        self, call: CallExpr, class_name: str\n    ) -> tuple[str, list[str], list[Expression | None], bool]:\n        \"\"\"Parse arguments of an Enum call.\n\n        Return a tuple of fields, values, was there an error.\n        \"\"\"\n        args = call.args\n        if not all(arg_kind in [ARG_POS, ARG_NAMED] for arg_kind in call.arg_kinds):\n            return self.fail_enum_call_arg(f\"Unexpected arguments to {class_name}()\", call)\n        if len(args) < 2:\n            return self.fail_enum_call_arg(f\"Too few arguments for {class_name}()\", call)\n        if len(args) > 6:\n            return self.fail_enum_call_arg(f\"Too many arguments for {class_name}()\", call)\n        valid_name = [None, \"value\", \"names\", \"module\", \"qualname\", \"type\", \"start\"]\n        for arg_name in call.arg_names:\n            if arg_name not in valid_name:\n                self.fail_enum_call_arg(f'Unexpected keyword argument \"{arg_name}\"', call)\n        value, names = None, None\n        for arg_name, arg in zip(call.arg_names, args):\n            if arg_name == \"value\":\n                value = arg\n            if arg_name == \"names\":\n                names = arg\n        if value is None:\n            value = args[0]\n        if names is None:\n            names = args[1]\n        if not isinstance(value, StrExpr):\n            return self.fail_enum_call_arg(\n                f\"{class_name}() expects a string literal as the first argument\", call\n            )\n        new_class_name = value.value\n\n        items = []\n        values: list[Expression | None] = []\n        if isinstance(names, StrExpr):\n            fields = names.value\n            for field in fields.replace(\",\", \" \").split():\n                items.append(field)\n        elif isinstance(names, (TupleExpr, ListExpr)):\n            seq_items = names.items\n            if is_StrExpr_list(seq_items):\n                items = [seq_item.value for seq_item in seq_items]\n            elif all(\n                isinstance(seq_item, (TupleExpr, ListExpr))\n                and len(seq_item.items) == 2\n                and isinstance(seq_item.items[0], StrExpr)\n                for seq_item in seq_items\n            ):\n                for seq_item in seq_items:\n                    assert isinstance(seq_item, (TupleExpr, ListExpr))\n                    name, value = seq_item.items\n                    assert isinstance(name, StrExpr)\n                    items.append(name.value)\n                    values.append(value)\n            else:\n                return self.fail_enum_call_arg(\n                    \"%s() with tuple or list expects strings or (name, value) pairs\" % class_name,\n                    call,\n                )\n        elif isinstance(names, DictExpr):\n            for key, value in names.items:\n                if not isinstance(key, StrExpr):\n                    return self.fail_enum_call_arg(\n                        f\"{class_name}() with dict literal requires string literals\", call\n                    )\n                items.append(key.value)\n                values.append(value)\n        elif isinstance(args[1], RefExpr) and isinstance(args[1].node, Var):\n            proper_type = get_proper_type(args[1].node.type)\n            if (\n                proper_type is not None\n                and isinstance(proper_type, LiteralType)\n                and isinstance(proper_type.value, str)\n            ):\n                fields = proper_type.value\n                for field in fields.replace(\",\", \" \").split():\n                    items.append(field)\n            elif args[1].node.is_final and isinstance(args[1].node.final_value, str):\n                fields = args[1].node.final_value\n                for field in fields.replace(\",\", \" \").split():\n                    items.append(field)\n            else:\n                return self.fail_enum_call_arg(\n                    \"Second argument of %s() must be string, tuple, list or dict literal for mypy to determine Enum members\"\n                    % class_name,\n                    call,\n                )\n        else:\n            # TODO: Allow dict(x=1, y=2) as a substitute for {'x': 1, 'y': 2}?\n            return self.fail_enum_call_arg(\n                \"Second argument of %s() must be string, tuple, list or dict literal for mypy to determine Enum members\"\n                % class_name,\n                call,\n            )\n        if not items:\n            return self.fail_enum_call_arg(f\"{class_name}() needs at least one item\", call)\n        if not values:\n            values = [None] * len(items)\n        assert len(items) == len(values)\n        return new_class_name, items, values, True\n\n    def fail_enum_call_arg(\n        self, message: str, context: Context\n    ) -> tuple[str, list[str], list[Expression | None], bool]:\n        self.fail(message, context)\n        return \"\", [], [], False\n\n    # Helpers\n\n    def fail(self, msg: str, ctx: Context) -> None:\n        self.api.fail(msg, ctx)\n"
  },
  {
    "path": "mypy/semanal_infer.py",
    "content": "\"\"\"Simple type inference for decorated functions during semantic analysis.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import ARG_POS, CallExpr, Decorator, Expression, FuncDef, RefExpr, Var\nfrom mypy.semanal_shared import SemanticAnalyzerInterface\nfrom mypy.typeops import function_type\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    ProperType,\n    Type,\n    TypeOfAny,\n    TypeVarType,\n    get_proper_type,\n)\nfrom mypy.typevars import has_no_typevars\n\n\ndef infer_decorator_signature_if_simple(\n    dec: Decorator, analyzer: SemanticAnalyzerInterface\n) -> None:\n    \"\"\"Try to infer the type of the decorated function.\n\n    This lets us resolve additional references to decorated functions\n    during type checking. Otherwise the type might not be available\n    when we need it, since module top levels can't be deferred.\n\n    This basically uses a simple special-purpose type inference\n    engine just for decorators.\n    \"\"\"\n    if dec.var.is_property:\n        # Decorators are expected to have a callable type (it's a little odd).\n        # TODO: this may result in wrong type if @property is applied to decorated method.\n        if dec.func.type is None:\n            dec.var.type = CallableType(\n                [AnyType(TypeOfAny.special_form)],\n                [ARG_POS],\n                [None],\n                AnyType(TypeOfAny.special_form),\n                analyzer.named_type(\"builtins.function\"),\n                name=dec.var.name,\n            )\n        elif isinstance(dec.func.type, CallableType):\n            dec.var.type = dec.func.type\n        return\n    decorator_preserves_type = True\n    for expr in dec.decorators:\n        preserve_type = False\n        if isinstance(expr, RefExpr) and isinstance(expr.node, FuncDef):\n            if expr.fullname == \"typing.no_type_check\":\n                return\n            if expr.node.type and is_identity_signature(expr.node.type):\n                preserve_type = True\n        if not preserve_type:\n            decorator_preserves_type = False\n            break\n    if decorator_preserves_type:\n        # No non-identity decorators left. We can trivially infer the type\n        # of the function here.\n        dec.var.type = function_type(dec.func, analyzer.named_type(\"builtins.function\"))\n    if dec.decorators:\n        return_type = calculate_return_type(dec.decorators[0])\n        if return_type and isinstance(return_type, AnyType):\n            # The outermost decorator will return Any so we know the type of the\n            # decorated function.\n            dec.var.type = AnyType(TypeOfAny.from_another_any, source_any=return_type)\n        sig = find_fixed_callable_return(dec.decorators[0])\n        if sig:\n            # The outermost decorator always returns the same kind of function,\n            # so we know that this is the type of the decorated function.\n            orig_sig = function_type(dec.func, analyzer.named_type(\"builtins.function\"))\n            sig.name = orig_sig.items[0].name\n            dec.var.type = sig\n\n\ndef is_identity_signature(sig: Type) -> bool:\n    \"\"\"Is type a callable of form T -> T (where T is a type variable)?\"\"\"\n    sig = get_proper_type(sig)\n    if isinstance(sig, CallableType) and sig.arg_kinds == [ARG_POS]:\n        if isinstance(sig.arg_types[0], TypeVarType) and isinstance(sig.ret_type, TypeVarType):\n            return sig.arg_types[0].id == sig.ret_type.id\n    return False\n\n\ndef calculate_return_type(expr: Expression) -> ProperType | None:\n    \"\"\"Return the return type if we can calculate it.\n\n    This only uses information available during semantic analysis so this\n    will sometimes return None because of insufficient information (as\n    type inference hasn't run yet).\n    \"\"\"\n    if isinstance(expr, RefExpr):\n        if isinstance(expr.node, FuncDef):\n            typ = expr.node.type\n            if typ is None:\n                # No signature -> default to Any.\n                return AnyType(TypeOfAny.unannotated)\n            # Explicit Any return?\n            if isinstance(typ, CallableType):\n                return get_proper_type(typ.ret_type)\n            return None\n        elif isinstance(expr.node, Var):\n            return get_proper_type(expr.node.type)\n    elif isinstance(expr, CallExpr):\n        return calculate_return_type(expr.callee)\n    return None\n\n\ndef find_fixed_callable_return(expr: Expression) -> CallableType | None:\n    \"\"\"Return the return type, if expression refers to a callable that returns a callable.\n\n    But only do this if the return type has no type variables. Return None otherwise.\n    This approximates things a lot as this is supposed to be called before type checking\n    when full type information is not available yet.\n    \"\"\"\n    if isinstance(expr, RefExpr):\n        if isinstance(expr.node, FuncDef):\n            typ = expr.node.type\n            if typ:\n                if isinstance(typ, CallableType) and has_no_typevars(typ.ret_type):\n                    ret_type = get_proper_type(typ.ret_type)\n                    if isinstance(ret_type, CallableType):\n                        return ret_type\n    elif isinstance(expr, CallExpr):\n        t = find_fixed_callable_return(expr.callee)\n        if t:\n            ret_type = get_proper_type(t.ret_type)\n            if isinstance(ret_type, CallableType):\n                return ret_type\n    return None\n"
  },
  {
    "path": "mypy/semanal_main.py",
    "content": "\"\"\"Top-level logic for the semantic analyzer.\n\nThe semantic analyzer binds names, resolves imports, detects various\nspecial constructs that don't have dedicated AST nodes after parse\n(such as 'cast' which looks like a call), populates symbol tables, and\nperforms various simple consistency checks.\n\nSemantic analysis of each SCC (strongly connected component; import\ncycle) is performed in one unit. Each module is analyzed as multiple\nseparate *targets*; the module top level is one target and each function\nis a target. Nested functions are not separate targets, however. This is\nmostly identical to targets used by mypy daemon (but classes aren't\ntargets in semantic analysis).\n\nWe first analyze each module top level in an SCC. If we encounter some\nnames that we can't bind because the target of the name may not have\nbeen processed yet, we *defer* the current target for further\nprocessing. Deferred targets will be analyzed additional times until\neverything can be bound, or we reach a maximum number of iterations.\n\nWe keep track of a set of incomplete namespaces, i.e. namespaces that we\nhaven't finished populating yet. References to these namespaces cause a\ndeferral if they can't be satisfied. Initially every module in the SCC\nwill be incomplete.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable, Iterator\nfrom contextlib import nullcontext\nfrom itertools import groupby\nfrom typing import TYPE_CHECKING, Final, TypeAlias as _TypeAlias\n\nimport mypy.state\nfrom mypy.checker import FineGrainedDeferredNode\nfrom mypy.errors import Errors\nfrom mypy.nodes import Decorator, FuncDef, MypyFile, OverloadedFuncDef, TypeInfo\nfrom mypy.options import Options\nfrom mypy.plugin import ClassDefContext\nfrom mypy.plugins import dataclasses as dataclasses_plugin\nfrom mypy.semanal import (\n    SemanticAnalyzer,\n    apply_semantic_analyzer_patches,\n    remove_imported_names_from_symtable,\n)\nfrom mypy.semanal_classprop import (\n    add_type_promotion,\n    calculate_class_abstract_status,\n    calculate_class_vars,\n    check_protocol_status,\n)\nfrom mypy.semanal_infer import infer_decorator_signature_if_simple\nfrom mypy.semanal_shared import find_dataclass_transform_spec\nfrom mypy.semanal_typeargs import TypeArgumentAnalyzer\n\nif TYPE_CHECKING:\n    from mypy.build import Graph, State\n\n\nPatches: _TypeAlias = list[tuple[int, Callable[[], None]]]\n\n\n# If we perform this many iterations, raise an exception since we are likely stuck.\nMAX_ITERATIONS: Final = 20\n\n\n# Number of passes over core modules before going on to the rest of the builtin SCC.\nCORE_WARMUP: Final = 2\ncore_modules: Final = [\n    \"typing\",\n    \"_collections_abc\",\n    \"builtins\",\n    \"abc\",\n    \"collections\",\n    \"collections.abc\",\n]\n\n\ndef semantic_analysis_for_scc(graph: Graph, scc: list[str], errors: Errors) -> None:\n    \"\"\"Perform semantic analysis for all modules in a SCC (import cycle).\n\n    Assume that reachability analysis has already been performed.\n\n    The scc will be processed roughly in the order the modules are included\n    in the list.\n    \"\"\"\n    patches: Patches = []\n    # Note that functions can't define new module-level attributes\n    # using 'global x', since module top levels are fully processed\n    # before functions. This limitation is unlikely to go away soon.\n    process_top_levels(graph, scc, patches)\n    process_functions(graph, scc, patches)\n    # We use patch callbacks to fix up things when we expect relatively few\n    # callbacks to be required.\n    apply_semantic_analyzer_patches(patches)\n    # Run class decorator hooks (they requite complete MROs and no placeholders).\n    apply_class_plugin_hooks(graph, scc, errors)\n    # This pass might need fallbacks calculated above and the results of hooks.\n    check_type_arguments(graph, scc, errors)\n    calculate_class_properties(graph, scc, errors)\n    check_blockers(graph, scc)\n    # Clean-up builtins, so that TypeVar etc. are not accessible without importing.\n    if \"builtins\" in scc:\n        cleanup_builtin_scc(graph[\"builtins\"])\n\n    # Report TypeForm profiling stats\n    if len(scc) >= 1:\n        # Get manager from any state in the SCC (they all share the same manager)\n        manager = graph[scc[0]].manager\n        analyzer = manager.semantic_analyzer\n        manager.add_stats(\n            type_expression_parse_count=analyzer.type_expression_parse_count,\n            type_expression_full_parse_success_count=analyzer.type_expression_full_parse_success_count,\n            type_expression_full_parse_failure_count=analyzer.type_expression_full_parse_failure_count,\n        )\n\n\ndef cleanup_builtin_scc(state: State) -> None:\n    \"\"\"Remove imported names from builtins namespace.\n\n    This way names imported from typing in builtins.pyi aren't available\n    by default (without importing them). We can only do this after processing\n    the whole SCC is finished, when the imported names aren't needed for\n    processing builtins.pyi itself.\n    \"\"\"\n    assert state.tree is not None\n    remove_imported_names_from_symtable(state.tree.names, \"builtins\")\n\n\ndef semantic_analysis_for_targets(\n    state: State, nodes: list[FineGrainedDeferredNode], graph: Graph\n) -> None:\n    \"\"\"Semantically analyze only selected nodes in a given module.\n\n    This essentially mirrors the logic of semantic_analysis_for_scc()\n    except that we process only some targets. This is used in fine-grained\n    incremental mode, when propagating an update.\n    \"\"\"\n    patches: Patches = []\n    if any(isinstance(n.node, MypyFile) for n in nodes):\n        # Process module top level first (if needed).\n        process_top_levels(graph, [state.id], patches)\n    analyzer = state.manager.semantic_analyzer\n    for n in nodes:\n        if isinstance(n.node, MypyFile):\n            # Already done above.\n            continue\n        process_top_level_function(\n            analyzer, state, state.id, n.node.fullname, n.node, n.active_typeinfo, patches\n        )\n    apply_semantic_analyzer_patches(patches)\n    apply_class_plugin_hooks(graph, [state.id], state.manager.errors)\n    check_type_arguments_in_targets(nodes, state, state.manager.errors)\n    calculate_class_properties(graph, [state.id], state.manager.errors)\n\n\ndef process_top_levels(graph: Graph, scc: list[str], patches: Patches) -> None:\n    # Process top levels until everything has been bound.\n\n    # Reverse order of the scc so the first modules in the original list will be\n    # be processed first. This helps with performance.\n    scc = list(reversed(scc))  # noqa: FURB187 intentional copy\n\n    # Initialize ASTs and symbol tables.\n    for id in scc:\n        state = graph[id]\n        assert state.tree is not None\n        state.manager.semantic_analyzer.prepare_file(state.tree)\n\n    # Initially all namespaces in the SCC are incomplete (well they are empty).\n    state.manager.incomplete_namespaces.update(scc)\n\n    worklist = scc.copy()\n    # HACK: process core stuff first. This is mostly needed to support defining\n    # named tuples in builtin SCC.\n    if all(m in worklist for m in core_modules):\n        worklist += list(reversed(core_modules)) * CORE_WARMUP\n    final_iteration = False\n    iteration = 0\n    analyzer = state.manager.semantic_analyzer\n    analyzer.deferral_debug_context.clear()\n\n    while worklist:\n        iteration += 1\n        if iteration > MAX_ITERATIONS:\n            # Just pick some module inside the current SCC for error context.\n            assert state.tree is not None\n            with analyzer.file_context(state.tree, state.options):\n                analyzer.report_hang()\n            break\n        if final_iteration:\n            # Give up. It's impossible to bind all names.\n            state.manager.incomplete_namespaces.clear()\n        all_deferred: list[str] = []\n        any_progress = False\n        while worklist:\n            next_id = worklist.pop()\n            state = graph[next_id]\n            assert state.tree is not None\n            deferred, incomplete, progress = semantic_analyze_target(\n                next_id, next_id, state, state.tree, None, final_iteration, patches\n            )\n            all_deferred += deferred\n            any_progress = any_progress or progress\n            if not incomplete:\n                state.manager.incomplete_namespaces.discard(next_id)\n        if final_iteration:\n            assert not all_deferred, \"Must not defer during final iteration\"\n        # Reverse to process the targets in the same order on every iteration. This avoids\n        # processing the same target twice in a row, which is inefficient.\n        worklist = list(reversed(all_deferred))\n        final_iteration = not any_progress\n    # Functions/methods that define/infer attributes are processed as part of top-levels.\n    # We need to clear the locals for those between fine-grained iterations.\n    analyzer.saved_locals.clear()\n\n\ndef order_by_subclassing(targets: list[FullTargetInfo]) -> Iterator[FullTargetInfo]:\n    \"\"\"Make sure that superclass methods are always processed before subclass methods.\n\n    This algorithm is not very optimal, but it is simple and should work well for lists\n    that are already almost correctly ordered.\n    \"\"\"\n\n    # First, group the targets by their TypeInfo (since targets are sorted by line,\n    # we know that each TypeInfo will appear as group key only once).\n    grouped = [(k, list(g)) for k, g in groupby(targets, key=lambda x: x[3])]\n    remaining_infos = {info for info, _ in grouped if info is not None}\n\n    next_group = 0\n    while grouped:\n        if next_group >= len(grouped):\n            # This should never happen, if there is an MRO cycle, it should be reported\n            # and fixed during top-level processing.\n            raise ValueError(\"Cannot order method targets by MRO\")\n        next_info, group = grouped[next_group]\n        if next_info is None:\n            # Trivial case, not methods but functions, process them straight away.\n            yield from group\n            grouped.pop(next_group)\n            continue\n        if any(parent in remaining_infos for parent in next_info.mro[1:]):\n            # We cannot process this method group yet, try a next one.\n            next_group += 1\n            continue\n        yield from group\n        grouped.pop(next_group)\n        remaining_infos.discard(next_info)\n        # Each time after processing a method group we should retry from start,\n        # since there may be some groups that are not blocked on parents anymore.\n        next_group = 0\n\n\ndef process_functions(graph: Graph, scc: list[str], patches: Patches) -> None:\n    # Process functions.\n    all_targets = []\n    for module in scc:\n        tree = graph[module].tree\n        assert tree is not None\n        # In principle, functions can be processed in arbitrary order,\n        # but _methods_ must be processed in the order they are defined,\n        # because some features (most notably partial types) depend on\n        # order of definitions on self.\n        #\n        # There can be multiple generated methods per line. Use target\n        # name as the second sort key to get a repeatable sort order.\n        targets = sorted(get_all_leaf_targets(tree), key=lambda x: (x[1].line, x[0]))\n        all_targets.extend(\n            [(module, target, node, active_type) for target, node, active_type in targets]\n        )\n\n    for module, target, node, active_type in order_by_subclassing(all_targets):\n        analyzer = graph[module].manager.semantic_analyzer\n        assert isinstance(node, (FuncDef, OverloadedFuncDef, Decorator)), node\n        process_top_level_function(\n            analyzer, graph[module], module, target, node, active_type, patches\n        )\n\n\ndef process_top_level_function(\n    analyzer: SemanticAnalyzer,\n    state: State,\n    module: str,\n    target: str,\n    node: FuncDef | OverloadedFuncDef | Decorator,\n    active_type: TypeInfo | None,\n    patches: Patches,\n) -> None:\n    \"\"\"Analyze single top-level function or method.\n\n    Process the body of the function (including nested functions) again and again,\n    until all names have been resolved (or iteration limit reached).\n    \"\"\"\n    # We need one more iteration after incomplete is False (e.g. to report errors, if any).\n    final_iteration = False\n    incomplete = True\n    # Start in the incomplete state (no missing names will be reported on first pass).\n    # Note that we use module name, since functions don't create qualified names.\n    deferred = [module]\n    analyzer.deferral_debug_context.clear()\n    analyzer.incomplete_namespaces.add(module)\n    iteration = 0\n    while deferred:\n        iteration += 1\n        if iteration == MAX_ITERATIONS:\n            # Just pick some module inside the current SCC for error context.\n            assert state.tree is not None\n            with analyzer.file_context(state.tree, state.options):\n                analyzer.report_hang()\n            break\n        if not (deferred or incomplete) or final_iteration:\n            # OK, this is one last pass, now missing names will be reported.\n            analyzer.incomplete_namespaces.discard(module)\n        deferred, incomplete, progress = semantic_analyze_target(\n            target, module, state, node, active_type, final_iteration, patches\n        )\n        if not incomplete:\n            state.manager.incomplete_namespaces.discard(module)\n        if final_iteration:\n            assert not deferred, \"Must not defer during final iteration\"\n        if not progress:\n            final_iteration = True\n\n    analyzer.incomplete_namespaces.discard(module)\n    # After semantic analysis is done, discard local namespaces\n    # to avoid memory hoarding.\n    analyzer.saved_locals.clear()\n\n\nTargetInfo: _TypeAlias = tuple[\n    str, MypyFile | FuncDef | OverloadedFuncDef | Decorator, TypeInfo | None\n]\n\n# Same as above but includes module as first item.\nFullTargetInfo: _TypeAlias = tuple[\n    str, str, MypyFile | FuncDef | OverloadedFuncDef | Decorator, TypeInfo | None\n]\n\n\ndef get_all_leaf_targets(file: MypyFile) -> list[TargetInfo]:\n    \"\"\"Return all leaf targets in a symbol table (module-level and methods).\"\"\"\n    result: list[TargetInfo] = []\n    for fullname, node, active_type in file.local_definitions():\n        if isinstance(node.node, (FuncDef, OverloadedFuncDef, Decorator)):\n            result.append((fullname, node.node, active_type))\n    return result\n\n\ndef semantic_analyze_target(\n    target: str,\n    module: str,\n    state: State,\n    node: MypyFile | FuncDef | OverloadedFuncDef | Decorator,\n    active_type: TypeInfo | None,\n    final_iteration: bool,\n    patches: Patches,\n) -> tuple[list[str], bool, bool]:\n    \"\"\"Semantically analyze a single target.\n\n    Return tuple with these items:\n    - list of deferred targets\n    - was some definition incomplete (need to run another pass)\n    - were any new names defined (or placeholders replaced)\n    \"\"\"\n    state.manager.processed_targets.append((module, target))\n    tree = state.tree\n    assert tree is not None\n    analyzer = state.manager.semantic_analyzer\n    # TODO: Move initialization to somewhere else\n    analyzer.global_decls = [set()]\n    analyzer.nonlocal_decls = [set()]\n    analyzer.globals = tree.names\n    analyzer.imports = set()\n    analyzer.progress = False\n    with state.wrap_context(check_blockers=False):\n        refresh_node = node\n        if isinstance(refresh_node, Decorator):\n            # Decorator expressions will be processed as part of the module top level.\n            refresh_node = refresh_node.func\n        analyzer.refresh_partial(\n            refresh_node,\n            patches,\n            final_iteration,\n            file_node=tree,\n            options=state.options,\n            active_type=active_type,\n        )\n        if isinstance(node, Decorator):\n            infer_decorator_signature_if_simple(node, analyzer)\n\n    # Clear out some stale data to avoid memory leaks and astmerge\n    # validity check confusion\n    analyzer.statement = None\n    del analyzer.cur_mod_node\n\n    if analyzer.deferred:\n        return [target], analyzer.incomplete, analyzer.progress\n    else:\n        return [], analyzer.incomplete, analyzer.progress\n\n\ndef check_type_arguments(graph: Graph, scc: list[str], errors: Errors) -> None:\n    for module in scc:\n        state = graph[module]\n        assert state.tree\n        analyzer = TypeArgumentAnalyzer(\n            errors,\n            state.options,\n            state.tree.is_typeshed_file(state.options),\n            state.manager.semantic_analyzer.named_type,\n        )\n        with state.wrap_context():\n            with mypy.state.state.strict_optional_set(state.options.strict_optional):\n                state.tree.accept(analyzer)\n\n\ndef check_type_arguments_in_targets(\n    targets: list[FineGrainedDeferredNode], state: State, errors: Errors\n) -> None:\n    \"\"\"Check type arguments against type variable bounds and restrictions.\n\n    This mirrors the logic in check_type_arguments() except that we process only\n    some targets. This is used in fine grained incremental mode.\n    \"\"\"\n    assert state.tree\n    analyzer = TypeArgumentAnalyzer(\n        errors,\n        state.options,\n        state.tree.is_typeshed_file(state.options),\n        state.manager.semantic_analyzer.named_type,\n    )\n    with state.wrap_context():\n        with mypy.state.state.strict_optional_set(state.options.strict_optional):\n            for target in targets:\n                func: FuncDef | OverloadedFuncDef | None = None\n                if isinstance(target.node, (FuncDef, OverloadedFuncDef)):\n                    func = target.node\n                saved = (state.id, target.active_typeinfo, func)  # module, class, function\n                with errors.scope.saved_scope(saved) if errors.scope else nullcontext():\n                    analyzer.recurse_into_functions = func is not None\n                    target.node.accept(analyzer)\n\n\ndef apply_class_plugin_hooks(graph: Graph, scc: list[str], errors: Errors) -> None:\n    \"\"\"Apply class plugin hooks within a SCC.\n\n    We run these after to the main semantic analysis so that the hooks\n    don't need to deal with incomplete definitions such as placeholder\n    types.\n\n    Note that some hooks incorrectly run during the main semantic\n    analysis pass, for historical reasons.\n    \"\"\"\n    num_passes = 0\n    incomplete = True\n    # If we encounter a base class that has not been processed, we'll run another\n    # pass. This should eventually reach a fixed point.\n    while incomplete:\n        assert num_passes < 10, \"Internal error: too many class plugin hook passes\"\n        num_passes += 1\n        incomplete = False\n        for module in scc:\n            state = graph[module]\n            tree = state.tree\n            assert tree\n            for _, node, _ in tree.local_definitions():\n                if isinstance(node.node, TypeInfo):\n                    if not apply_hooks_to_class(\n                        state.manager.semantic_analyzer,\n                        module,\n                        node.node,\n                        state.options,\n                        tree,\n                        errors,\n                    ):\n                        incomplete = True\n\n\ndef apply_hooks_to_class(\n    self: SemanticAnalyzer,\n    module: str,\n    info: TypeInfo,\n    options: Options,\n    file_node: MypyFile,\n    errors: Errors,\n) -> bool:\n    # TODO: Move more class-related hooks here?\n    defn = info.defn\n    ok = True\n    for decorator in defn.decorators:\n        with self.file_context(file_node, options, info):\n            hook = None\n\n            decorator_name = self.get_fullname_for_hook(decorator)\n            if decorator_name:\n                hook = self.plugin.get_class_decorator_hook_2(decorator_name)\n            # Special case: if the decorator is itself decorated with\n            # typing.dataclass_transform, apply the hook for the dataclasses plugin\n            # TODO: remove special casing here\n            if hook is None and find_dataclass_transform_spec(decorator):\n                hook = dataclasses_plugin.dataclass_class_maker_callback\n\n            if hook:\n                ok = ok and hook(ClassDefContext(defn, decorator, self))\n\n    # Check if the class definition itself triggers a dataclass transform (via a parent class/\n    # metaclass)\n    spec = find_dataclass_transform_spec(info)\n    if spec is not None:\n        with self.file_context(file_node, options, info):\n            # We can't use the normal hook because reason = defn, and ClassDefContext only accepts\n            # an Expression for reason\n            ok = ok and dataclasses_plugin.DataclassTransformer(defn, defn, spec, self).transform()\n\n    return ok\n\n\ndef calculate_class_properties(graph: Graph, scc: list[str], errors: Errors) -> None:\n    builtins = graph[\"builtins\"].tree\n    assert builtins\n    for module in scc:\n        state = graph[module]\n        tree = state.tree\n        assert tree\n        for _, node, _ in tree.local_definitions():\n            if isinstance(node.node, TypeInfo):\n                with state.manager.semantic_analyzer.file_context(tree, state.options, node.node):\n                    calculate_class_abstract_status(node.node, tree.is_stub, errors)\n                    check_protocol_status(node.node, errors)\n                    calculate_class_vars(node.node)\n                    add_type_promotion(\n                        node.node, tree.names, graph[module].options, builtins.names\n                    )\n\n\ndef check_blockers(graph: Graph, scc: list[str]) -> None:\n    for module in scc:\n        graph[module].check_blockers()\n"
  },
  {
    "path": "mypy/semanal_namedtuple.py",
    "content": "\"\"\"Semantic analysis of named tuple definitions.\n\nThis is conceptually part of mypy.semanal.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport keyword\nfrom collections.abc import Container, Iterator, Mapping\nfrom contextlib import contextmanager\nfrom typing import Final, cast\n\nfrom mypy.errorcodes import ARG_TYPE, ErrorCode\nfrom mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type\nfrom mypy.messages import MessageBuilder\nfrom mypy.nodes import (\n    ARG_NAMED_OPT,\n    ARG_OPT,\n    ARG_POS,\n    MDEF,\n    Argument,\n    AssignmentStmt,\n    Block,\n    CallExpr,\n    ClassDef,\n    Context,\n    Decorator,\n    EllipsisExpr,\n    Expression,\n    ExpressionStmt,\n    FuncBase,\n    FuncDef,\n    ListExpr,\n    NamedTupleExpr,\n    NameExpr,\n    PassStmt,\n    PlaceholderNode,\n    RefExpr,\n    Statement,\n    StrExpr,\n    SymbolTable,\n    SymbolTableNode,\n    TempNode,\n    TupleExpr,\n    TypeInfo,\n    TypeVarExpr,\n    Var,\n    is_StrExpr_list,\n)\nfrom mypy.options import Options\nfrom mypy.semanal_shared import (\n    PRIORITY_FALLBACKS,\n    SemanticAnalyzerInterface,\n    calculate_tuple_fallback,\n    has_placeholder,\n    set_callable_name,\n)\nfrom mypy.types import (\n    TYPED_NAMEDTUPLE_NAMES,\n    AnyType,\n    CallableType,\n    LiteralType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarType,\n    UnboundType,\n    has_type_vars,\n)\nfrom mypy.util import get_unique_redefinition_name\n\n# Matches \"_prohibited\" in typing.py, but adds __annotations__, which works at runtime but can't\n# easily be supported in a static checker.\nNAMEDTUPLE_PROHIBITED_NAMES: Final = (\n    \"__new__\",\n    \"__init__\",\n    \"__slots__\",\n    \"__getnewargs__\",\n    \"_fields\",\n    \"_field_defaults\",\n    \"_field_types\",\n    \"_make\",\n    \"_replace\",\n    \"_asdict\",\n    \"_source\",\n    \"__annotations__\",\n)\n\nNAMEDTUP_CLASS_ERROR: Final = (\n    'Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\"'\n)\n\nSELF_TVAR_NAME: Final = \"_NT\"\n\n\nclass NamedTupleAnalyzer:\n    def __init__(\n        self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder\n    ) -> None:\n        self.options = options\n        self.api = api\n        self.msg = msg\n\n    def analyze_namedtuple_classdef(\n        self, defn: ClassDef, is_stub_file: bool, is_func_scope: bool\n    ) -> tuple[bool, TypeInfo | None]:\n        \"\"\"Analyze if given class definition can be a named tuple definition.\n\n        Return a tuple where first item indicates whether this can possibly be a named tuple,\n        and the second item is the corresponding TypeInfo (may be None if not ready and should be\n        deferred).\n        \"\"\"\n        for base_expr in defn.base_type_exprs:\n            if isinstance(base_expr, RefExpr):\n                self.api.accept(base_expr)\n                if base_expr.fullname in TYPED_NAMEDTUPLE_NAMES:\n                    result = self.check_namedtuple_classdef(defn, is_stub_file)\n                    if result is None:\n                        # This is a valid named tuple, but some types are incomplete.\n                        return True, None\n                    items, types, default_items, statements = result\n                    if is_func_scope and \"@\" not in defn.name:\n                        defn.name += \"@\" + str(defn.line)\n                    existing_info = None\n                    if isinstance(defn.analyzed, NamedTupleExpr):\n                        existing_info = defn.analyzed.info\n                    info = self.build_namedtuple_typeinfo(\n                        defn.name, items, types, default_items, defn.line, existing_info\n                    )\n                    defn.analyzed = NamedTupleExpr(info, is_typed=True)\n                    defn.analyzed.line = defn.line\n                    defn.analyzed.column = defn.column\n                    defn.defs.body = statements\n                    # All done: this is a valid named tuple with all types known.\n                    return True, info\n        # This can't be a valid named tuple.\n        return False, None\n\n    def check_namedtuple_classdef(\n        self, defn: ClassDef, is_stub_file: bool\n    ) -> tuple[list[str], list[Type], dict[str, Expression], list[Statement]] | None:\n        \"\"\"Parse and validate fields in named tuple class definition.\n\n        Return a four tuple:\n          * field names\n          * field types\n          * field default values\n          * valid statements\n        or None, if any of the types are not ready.\n        \"\"\"\n        if len(defn.base_type_exprs) > 1:\n            self.fail(\"NamedTuple should be a single base\", defn)\n        items: list[str] = []\n        types: list[Type] = []\n        default_items: dict[str, Expression] = {}\n        statements: list[Statement] = []\n        for stmt in defn.defs.body:\n            statements.append(stmt)\n            if not isinstance(stmt, AssignmentStmt):\n                # Still allow pass or ... (for empty namedtuples).\n                if isinstance(stmt, PassStmt) or (\n                    isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr)\n                ):\n                    continue\n                # Also allow methods, including decorated ones.\n                if isinstance(stmt, (Decorator, FuncBase)):\n                    continue\n                # And docstrings.\n                if isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, StrExpr):\n                    continue\n                statements.pop()\n                defn.removed_statements.append(stmt)\n                self.fail(NAMEDTUP_CLASS_ERROR, stmt)\n            elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr):\n                # An assignment, but an invalid one.\n                statements.pop()\n                defn.removed_statements.append(stmt)\n                self.fail(NAMEDTUP_CLASS_ERROR, stmt)\n            else:\n                # Append name and type in this case...\n                name = stmt.lvalues[0].name\n                items.append(name)\n                if stmt.type is None:\n                    types.append(AnyType(TypeOfAny.unannotated))\n                else:\n                    # We never allow recursive types at function scope. Although it is\n                    # possible to support this for named tuples, it is still tricky, and\n                    # it would be inconsistent with type aliases.\n                    analyzed = self.api.anal_type(\n                        stmt.type,\n                        allow_placeholder=not self.api.is_func_scope(),\n                        prohibit_self_type=\"NamedTuple item type\",\n                        prohibit_special_class_field_types=\"NamedTuple\",\n                    )\n                    if analyzed is None:\n                        # Something is incomplete. We need to defer this named tuple.\n                        return None\n                    types.append(analyzed)\n                # ...despite possible minor failures that allow further analysis.\n                if name.startswith(\"_\"):\n                    self.fail(\n                        f\"NamedTuple field name cannot start with an underscore: {name}\", stmt\n                    )\n                if stmt.type is None or hasattr(stmt, \"new_syntax\") and not stmt.new_syntax:\n                    self.fail(NAMEDTUP_CLASS_ERROR, stmt)\n                elif isinstance(stmt.rvalue, TempNode):\n                    # x: int assigns rvalue to TempNode(AnyType())\n                    if default_items:\n                        self.fail(\n                            \"Non-default NamedTuple fields cannot follow default fields\", stmt\n                        )\n                else:\n                    default_items[name] = stmt.rvalue\n        if defn.keywords:\n            for_function = ' for \"__init_subclass__\" of \"NamedTuple\"'\n            for key in defn.keywords:\n                self.msg.unexpected_keyword_argument_for_function(for_function, key, defn)\n        return items, types, default_items, statements\n\n    def check_namedtuple(\n        self, node: Expression, var_name: str | None, is_func_scope: bool\n    ) -> tuple[str | None, TypeInfo | None, list[TypeVarLikeType]]:\n        \"\"\"Check if a call defines a namedtuple.\n\n        The optional var_name argument is the name of the variable to\n        which this is assigned, if any.\n\n        Return a tuple of two items:\n          * Internal name of the named tuple (e.g. the name passed as an argument to namedtuple)\n            or None if it is not a valid named tuple\n          * Corresponding TypeInfo, or None if not ready.\n\n        If the definition is invalid but looks like a namedtuple,\n        report errors but return (some) TypeInfo.\n        \"\"\"\n        if not isinstance(node, CallExpr):\n            return None, None, []\n        call = node\n        callee = call.callee\n        if not isinstance(callee, RefExpr):\n            return None, None, []\n        fullname = callee.fullname\n        if fullname == \"collections.namedtuple\":\n            is_typed = False\n        elif fullname in TYPED_NAMEDTUPLE_NAMES:\n            is_typed = True\n        else:\n            return None, None, []\n        result = self.parse_namedtuple_args(call, fullname)\n        if result:\n            items, types, defaults, typename, tvar_defs, ok = result\n        else:\n            # Error. Construct dummy return value.\n            if var_name:\n                name = var_name\n                if is_func_scope:\n                    name += \"@\" + str(call.line)\n            else:\n                name = var_name = \"namedtuple@\" + str(call.line)\n            info = self.build_namedtuple_typeinfo(name, [], [], {}, node.line, None)\n            self.store_namedtuple_info(info, var_name, call, is_typed)\n            if name != var_name or is_func_scope:\n                # NOTE: we skip local namespaces since they are not serialized.\n                self.api.add_symbol_skip_local(name, info)\n            return var_name, info, []\n        if not ok:\n            # This is a valid named tuple but some types are not ready.\n            return typename, None, []\n\n        # We use the variable name as the class name if it exists. If\n        # it doesn't, we use the name passed as an argument. We prefer\n        # the variable name because it should be unique inside a\n        # module, and so we don't need to disambiguate it with a line\n        # number.\n        if var_name:\n            name = var_name\n        else:\n            name = typename\n\n        if var_name is None or is_func_scope:\n            # There are two special cases where need to give it a unique name derived\n            # from the line number:\n            #   * This is a base class expression, since it often matches the class name:\n            #         class NT(NamedTuple('NT', [...])):\n            #             ...\n            #   * This is a local (function or method level) named tuple, since\n            #     two methods of a class can define a named tuple with the same name,\n            #     and they will be stored in the same namespace (see below).\n            name += \"@\" + str(call.line)\n        if defaults:\n            default_items = {\n                arg_name: default for arg_name, default in zip(items[-len(defaults) :], defaults)\n            }\n        else:\n            default_items = {}\n\n        existing_info = None\n        if isinstance(node.analyzed, NamedTupleExpr):\n            existing_info = node.analyzed.info\n        info = self.build_namedtuple_typeinfo(\n            name, items, types, default_items, node.line, existing_info\n        )\n\n        # If var_name is not None (i.e. this is not a base class expression), we always\n        # store the generated TypeInfo under var_name in the current scope, so that\n        # other definitions can use it.\n        if var_name:\n            self.store_namedtuple_info(info, var_name, call, is_typed)\n        else:\n            call.analyzed = NamedTupleExpr(info, is_typed=is_typed)\n            call.analyzed.set_line(call)\n        # There are three cases where we need to store the generated TypeInfo\n        # second time (for the purpose of serialization):\n        #   * If there is a name mismatch like One = NamedTuple('Other', [...])\n        #     we also store the info under name 'Other@lineno', this is needed\n        #     because classes are (de)serialized using their actual fullname, not\n        #     the name of l.h.s.\n        #   * If this is a method level named tuple. It can leak from the method\n        #     via assignment to self attribute and therefore needs to be serialized\n        #     (local namespaces are not serialized).\n        #   * If it is a base class expression. It was not stored above, since\n        #     there is no var_name (but it still needs to be serialized\n        #     since it is in MRO of some class).\n        if name != var_name or is_func_scope:\n            # NOTE: we skip local namespaces since they are not serialized.\n            self.api.add_symbol_skip_local(name, info)\n        return typename, info, tvar_defs\n\n    def store_namedtuple_info(\n        self, info: TypeInfo, name: str, call: CallExpr, is_typed: bool\n    ) -> None:\n        self.api.add_symbol(name, info, call)\n        call.analyzed = NamedTupleExpr(info, is_typed=is_typed)\n        call.analyzed.set_line(call)\n\n    def parse_namedtuple_args(\n        self, call: CallExpr, fullname: str\n    ) -> None | (tuple[list[str], list[Type], list[Expression], str, list[TypeVarLikeType], bool]):\n        \"\"\"Parse a namedtuple() call into data needed to construct a type.\n\n        Returns a 6-tuple:\n        - List of argument names\n        - List of argument types\n        - List of default values\n        - First argument of namedtuple\n        - All typevars found in the field definition\n        - Whether all types are ready.\n\n        Return None if the definition didn't typecheck.\n        \"\"\"\n        type_name = \"NamedTuple\" if fullname in TYPED_NAMEDTUPLE_NAMES else \"namedtuple\"\n        # TODO: Share code with check_argument_count in checkexpr.py?\n        args = call.args\n        if len(args) < 2:\n            self.fail(f'Too few arguments for \"{type_name}()\"', call)\n            return None\n        defaults: list[Expression] = []\n        rename = False\n        if len(args) > 2:\n            # Typed namedtuple doesn't support additional arguments.\n            if fullname in TYPED_NAMEDTUPLE_NAMES:\n                self.fail('Too many arguments for \"NamedTuple()\"', call)\n                return None\n            for i, arg_name in enumerate(call.arg_names[2:], 2):\n                if arg_name == \"defaults\":\n                    arg = args[i]\n                    # We don't care what the values are, as long as the argument is an iterable\n                    # and we can count how many defaults there are.\n                    if isinstance(arg, (ListExpr, TupleExpr)):\n                        defaults = list(arg.items)\n                    else:\n                        self.fail(\n                            \"List or tuple literal expected as the defaults argument to \"\n                            \"{}()\".format(type_name),\n                            arg,\n                        )\n                elif arg_name == \"rename\":\n                    arg = args[i]\n                    if isinstance(arg, NameExpr) and arg.name in (\"True\", \"False\"):\n                        rename = arg.name == \"True\"\n                    else:\n                        self.fail(\n                            f'Boolean literal expected as the \"rename\" argument to {type_name}()',\n                            arg,\n                            code=ARG_TYPE,\n                        )\n        if call.arg_kinds[:2] != [ARG_POS, ARG_POS]:\n            self.fail(f'Unexpected arguments to \"{type_name}()\"', call)\n            return None\n        if not isinstance(args[0], StrExpr):\n            self.fail(f'\"{type_name}()\" expects a string literal as the first argument', call)\n            return None\n        typename = args[0].value\n        types: list[Type] = []\n        tvar_defs = []\n        if not isinstance(args[1], (ListExpr, TupleExpr)):\n            if fullname == \"collections.namedtuple\" and isinstance(args[1], StrExpr):\n                str_expr = args[1]\n                items = str_expr.value.replace(\",\", \" \").split()\n            else:\n                self.fail(\n                    'List or tuple literal expected as the second argument to \"{}()\"'.format(\n                        type_name\n                    ),\n                    call,\n                )\n                return None\n        else:\n            listexpr = args[1]\n            if fullname == \"collections.namedtuple\":\n                # The fields argument contains just names, with implicit Any types.\n                if not is_StrExpr_list(listexpr.items):\n                    self.fail('String literal expected as \"namedtuple()\" item', call)\n                    return None\n                items = [item.value for item in listexpr.items]\n            else:\n                type_exprs = [\n                    t.items[1]\n                    for t in listexpr.items\n                    if isinstance(t, TupleExpr) and len(t.items) == 2\n                ]\n                tvar_defs = self.api.get_and_bind_all_tvars(type_exprs)\n                # The fields argument contains (name, type) tuples.\n                result = self.parse_namedtuple_fields_with_types(listexpr.items, call)\n                if result is None:\n                    # One of the types is not ready, defer.\n                    return None\n                items, types, _, ok = result\n                if not ok:\n                    return [], [], [], typename, [], False\n        if not types:\n            types = [AnyType(TypeOfAny.unannotated) for _ in items]\n        processed_items = []\n        seen_names: set[str] = set()\n        for i, item in enumerate(items):\n            problem = self.check_namedtuple_field_name(item, seen_names)\n            if problem is None:\n                processed_items.append(item)\n                seen_names.add(item)\n            else:\n                if not rename:\n                    self.fail(f'\"{type_name}()\" {problem}', call)\n                # Even if rename=False, we pretend that it is True.\n                # At runtime namedtuple creation would throw an error;\n                # applying the rename logic means we create a more sensible\n                # namedtuple.\n                new_name = f\"_{i}\"\n                processed_items.append(new_name)\n                seen_names.add(new_name)\n\n        if len(defaults) > len(items):\n            self.fail(f'Too many defaults given in call to \"{type_name}()\"', call)\n            defaults = defaults[: len(items)]\n        return processed_items, types, defaults, typename, tvar_defs, True\n\n    def parse_namedtuple_fields_with_types(\n        self, nodes: list[Expression], context: Context\n    ) -> tuple[list[str], list[Type], list[Expression], bool] | None:\n        \"\"\"Parse typed named tuple fields.\n\n        Return (names, types, defaults, whether types are all ready), or None if error occurred.\n        \"\"\"\n        items: list[str] = []\n        types: list[Type] = []\n        for item in nodes:\n            if isinstance(item, TupleExpr):\n                if len(item.items) != 2:\n                    self.fail('Invalid \"NamedTuple()\" field definition', item)\n                    return None\n                name, type_node = item.items\n                if isinstance(name, StrExpr):\n                    items.append(name.value)\n                else:\n                    self.fail('Invalid \"NamedTuple()\" field name', item)\n                    return None\n                try:\n                    type = expr_to_unanalyzed_type(type_node, self.options, self.api.is_stub_file)\n                except TypeTranslationError:\n                    self.fail(\"Invalid field type\", type_node)\n                    return None\n                # We never allow recursive types at function scope.\n                analyzed = self.api.anal_type(\n                    type,\n                    allow_placeholder=not self.api.is_func_scope(),\n                    prohibit_self_type=\"NamedTuple item type\",\n                    prohibit_special_class_field_types=\"NamedTuple\",\n                )\n                # Workaround #4987 and avoid introducing a bogus UnboundType\n                if isinstance(analyzed, UnboundType):\n                    analyzed = AnyType(TypeOfAny.from_error)\n                # These should be all known, otherwise we would defer in visit_assignment_stmt().\n                if analyzed is None:\n                    return [], [], [], False\n                types.append(analyzed)\n            else:\n                self.fail('Tuple expected as \"NamedTuple()\" field', item)\n                return None\n        return items, types, [], True\n\n    def build_namedtuple_typeinfo(\n        self,\n        name: str,\n        items: list[str],\n        types: list[Type],\n        default_items: Mapping[str, Expression],\n        line: int,\n        existing_info: TypeInfo | None,\n    ) -> TypeInfo:\n        strtype = self.api.named_type(\"builtins.str\")\n        implicit_any = AnyType(TypeOfAny.special_form)\n        basetuple_type = self.api.named_type(\"builtins.tuple\", [implicit_any])\n        dictype = self.api.named_type(\"builtins.dict\", [strtype, implicit_any])\n        # Actual signature should return OrderedDict[str, Union[types]]\n        ordereddictype = self.api.named_type(\"builtins.dict\", [strtype, implicit_any])\n        fallback = self.api.named_type(\"builtins.tuple\", [implicit_any])\n        # Note: actual signature should accept an invariant version of Iterable[UnionType[types]].\n        # but it can't be expressed. 'new' and 'len' should be callable types.\n        iterable_type = self.api.named_type_or_none(\"typing.Iterable\", [implicit_any])\n        function_type = self.api.named_type(\"builtins.function\")\n\n        literals: list[Type] = [LiteralType(item, strtype) for item in items]\n        match_args_type = TupleType(literals, basetuple_type)\n\n        info = existing_info or self.api.basic_new_typeinfo(name, fallback, line)\n        info.is_named_tuple = True\n        tuple_base = TupleType(types, fallback)\n        if has_placeholder(tuple_base):\n            self.api.process_placeholder(\n                None, \"NamedTuple item\", info, force_progress=tuple_base != info.tuple_type\n            )\n        info.update_tuple_type(tuple_base)\n        info.line = line\n        # For use by mypyc.\n        info.metadata[\"namedtuple\"] = {\"fields\": items.copy()}\n\n        # We can't calculate the complete fallback type until after semantic\n        # analysis, since otherwise base classes might be incomplete. Postpone a\n        # callback function that patches the fallback.\n        if not has_placeholder(tuple_base) and not has_type_vars(tuple_base):\n            self.api.schedule_patch(\n                PRIORITY_FALLBACKS, lambda: calculate_tuple_fallback(tuple_base)\n            )\n\n        def add_field(\n            var: Var, is_initialized_in_class: bool = False, is_property: bool = False\n        ) -> None:\n            var.info = info\n            var.is_initialized_in_class = is_initialized_in_class\n            var.is_property = is_property\n            var._fullname = f\"{info.fullname}.{var.name}\"\n            info.names[var.name] = SymbolTableNode(MDEF, var)\n\n        fields = [Var(item, typ) for item, typ in zip(items, types)]\n        for var in fields:\n            add_field(var, is_property=True)\n        # We can't share Vars between fields and method arguments, since they\n        # have different full names (the latter are normally used as local variables\n        # in functions, so their full names are set to short names when generated methods\n        # are analyzed).\n        vars = [Var(item, typ) for item, typ in zip(items, types)]\n\n        tuple_of_strings = TupleType([strtype for _ in items], basetuple_type)\n        add_field(Var(\"_fields\", tuple_of_strings), is_initialized_in_class=True)\n        add_field(Var(\"_field_types\", dictype), is_initialized_in_class=True)\n        add_field(Var(\"_field_defaults\", dictype), is_initialized_in_class=True)\n        add_field(Var(\"_source\", strtype), is_initialized_in_class=True)\n        add_field(Var(\"__annotations__\", ordereddictype), is_initialized_in_class=True)\n        add_field(Var(\"__doc__\", strtype), is_initialized_in_class=True)\n        if self.options.python_version >= (3, 10):\n            add_field(Var(\"__match_args__\", match_args_type), is_initialized_in_class=True)\n\n        assert info.tuple_type is not None  # Set by update_tuple_type() above.\n        shared_self_type = TypeVarType(\n            name=SELF_TVAR_NAME,\n            fullname=f\"{info.fullname}.{SELF_TVAR_NAME}\",\n            # Namespace is patched per-method below.\n            id=self.api.tvar_scope.new_unique_func_id(),\n            values=[],\n            upper_bound=info.tuple_type,\n            default=AnyType(TypeOfAny.from_omitted_generics),\n        )\n\n        def add_method(\n            funcname: str,\n            ret: Type | None,  # None means use (patched) self-type\n            args: list[Argument],\n            is_classmethod: bool = False,\n            is_new: bool = False,\n        ) -> None:\n            fullname = f\"{info.fullname}.{funcname}\"\n            self_type = shared_self_type.copy_modified(\n                id=TypeVarId(shared_self_type.id.raw_id, namespace=fullname)\n            )\n            if ret is None:\n                ret = self_type\n            if is_classmethod or is_new:\n                first = [Argument(Var(\"_cls\"), TypeType.make_normalized(self_type), None, ARG_POS)]\n            else:\n                first = [Argument(Var(\"_self\"), self_type, None, ARG_POS)]\n            args = first + args\n\n            types = [arg.type_annotation for arg in args]\n            items = [arg.variable.name for arg in args]\n            arg_kinds = [arg.kind for arg in args]\n            assert None not in types\n            signature = CallableType(cast(list[Type], types), arg_kinds, items, ret, function_type)\n            signature.variables = (self_type,)\n            func = FuncDef(funcname, args, Block([]))\n            func.info = info\n            func.is_class = is_classmethod\n            func.type = set_callable_name(signature, func)\n            func._fullname = fullname\n            func.line = line\n            if is_classmethod:\n                v = Var(funcname, func.type)\n                v.is_classmethod = True\n                v.info = info\n                v._fullname = func._fullname\n                func.is_decorated = True\n                dec = Decorator(func, [NameExpr(\"classmethod\")], v)\n                dec.line = line\n                sym = SymbolTableNode(MDEF, dec)\n            else:\n                sym = SymbolTableNode(MDEF, func)\n            sym.plugin_generated = True\n            info.names[funcname] = sym\n\n        add_method(\n            \"_replace\",\n            ret=None,\n            args=[Argument(var, var.type, EllipsisExpr(), ARG_NAMED_OPT) for var in vars],\n        )\n        if self.options.python_version >= (3, 13):\n            add_method(\n                \"__replace__\",\n                ret=None,\n                args=[Argument(var, var.type, EllipsisExpr(), ARG_NAMED_OPT) for var in vars],\n            )\n\n        def make_init_arg(var: Var) -> Argument:\n            default = default_items.get(var.name, None)\n            kind = ARG_POS if default is None else ARG_OPT\n            return Argument(var, var.type, default, kind)\n\n        add_method(\"__new__\", ret=None, args=[make_init_arg(var) for var in vars], is_new=True)\n        add_method(\"_asdict\", args=[], ret=ordereddictype)\n        add_method(\n            \"_make\",\n            ret=None,\n            is_classmethod=True,\n            args=[Argument(Var(\"iterable\", iterable_type), iterable_type, None, ARG_POS)],\n        )\n\n        self_tvar_expr = TypeVarExpr(\n            SELF_TVAR_NAME,\n            info.fullname + \".\" + SELF_TVAR_NAME,\n            [],\n            info.tuple_type,\n            AnyType(TypeOfAny.from_omitted_generics),\n        )\n        info.names[SELF_TVAR_NAME] = SymbolTableNode(MDEF, self_tvar_expr)\n        return info\n\n    @contextmanager\n    def save_namedtuple_body(self, named_tuple_info: TypeInfo) -> Iterator[None]:\n        \"\"\"Preserve the generated body of class-based named tuple and then restore it.\n\n        Temporarily clear the names dict so we don't get errors about duplicate names\n        that were already set in build_namedtuple_typeinfo (we already added the tuple\n        field names while generating the TypeInfo, and actual duplicates are\n        already reported).\n        \"\"\"\n        nt_names = named_tuple_info.names\n        named_tuple_info.names = SymbolTable()\n\n        yield\n\n        # Make sure we didn't use illegal names, then reset the names in the typeinfo.\n        for prohibited in NAMEDTUPLE_PROHIBITED_NAMES:\n            if prohibited in named_tuple_info.names:\n                if nt_names.get(prohibited) is named_tuple_info.names[prohibited]:\n                    continue\n                ctx = named_tuple_info.names[prohibited].node\n                assert ctx is not None\n                self.fail(f'Cannot overwrite NamedTuple attribute \"{prohibited}\"', ctx)\n\n        # Restore the names in the original symbol table. This ensures that the symbol\n        # table contains the field objects created by build_namedtuple_typeinfo. Exclude\n        # __doc__, which can legally be overwritten by the class.\n        for key, value in nt_names.items():\n            if key in named_tuple_info.names:\n                if key == \"__doc__\":\n                    continue\n                sym = named_tuple_info.names[key]\n                if isinstance(sym.node, (FuncBase, Decorator)) and not sym.plugin_generated:\n                    # Keep user-defined methods as is.\n                    continue\n                # Do not retain placeholders - we'll get back here if they cease to\n                # be placeholders later. If we keep placeholders alive, they may never\n                # be reached again, making it to cacheable symtable.\n                if not isinstance(sym.node, PlaceholderNode):\n                    # Keep existing (user-provided) definitions under mangled names, so they\n                    # get semantically analyzed.\n                    r_key = get_unique_redefinition_name(key, named_tuple_info.names)\n                    named_tuple_info.names[r_key] = sym\n            named_tuple_info.names[key] = value\n\n    # Helpers\n\n    def check_namedtuple_field_name(self, field: str, seen_names: Container[str]) -> str | None:\n        \"\"\"Return None for valid fields, a string description for invalid ones.\"\"\"\n        if field in seen_names:\n            return f'has duplicate field name \"{field}\"'\n        elif not field.isidentifier():\n            return f'field name \"{field}\" is not a valid identifier'\n        elif field.startswith(\"_\"):\n            return f'field name \"{field}\" starts with an underscore'\n        elif keyword.iskeyword(field):\n            return f'field name \"{field}\" is a keyword'\n        return None\n\n    def fail(self, msg: str, ctx: Context, code: ErrorCode | None = None) -> None:\n        self.api.fail(msg, ctx, code=code)\n"
  },
  {
    "path": "mypy/semanal_newtype.py",
    "content": "\"\"\"Semantic analysis of NewType definitions.\n\nThis is conceptually part of mypy.semanal (semantic analyzer pass 2).\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy import errorcodes as codes\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type\nfrom mypy.messages import MessageBuilder, format_type\nfrom mypy.nodes import (\n    ARG_POS,\n    MDEF,\n    Argument,\n    AssignmentStmt,\n    Block,\n    CallExpr,\n    Context,\n    FuncDef,\n    NameExpr,\n    NewTypeExpr,\n    PlaceholderNode,\n    RefExpr,\n    StrExpr,\n    SymbolTableNode,\n    TypeInfo,\n    Var,\n)\nfrom mypy.options import Options\nfrom mypy.semanal_shared import SemanticAnalyzerInterface, has_placeholder\nfrom mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    NoneType,\n    PlaceholderType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    get_proper_type,\n)\n\n\nclass NewTypeAnalyzer:\n    def __init__(\n        self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder\n    ) -> None:\n        self.options = options\n        self.api = api\n        self.msg = msg\n\n    def process_newtype_declaration(self, s: AssignmentStmt) -> bool:\n        \"\"\"Check if s declares a NewType; if yes, store it in symbol table.\n\n        Return True if it's a NewType declaration. The current target may be\n        deferred as a side effect if the base type is not ready, even if\n        the return value is True.\n\n        The logic in this function mostly copies the logic for visit_class_def()\n        with a single (non-Generic) base.\n        \"\"\"\n        var_name, call = self.analyze_newtype_declaration(s)\n        if var_name is None or call is None:\n            return False\n        name = var_name\n        # OK, now we know this is a NewType. But the base type may be not ready yet,\n        # add placeholder as we do for ClassDef.\n\n        if self.api.is_func_scope():\n            name += \"@\" + str(s.line)\n        fullname = self.api.qualified_name(name)\n\n        if not call.analyzed or isinstance(call.analyzed, NewTypeExpr) and not call.analyzed.info:\n            # Start from labeling this as a future class, as we do for normal ClassDefs.\n            placeholder = PlaceholderNode(fullname, s, s.line, becomes_typeinfo=True)\n            self.api.add_symbol(var_name, placeholder, s, can_defer=False)\n\n        old_type, should_defer = self.check_newtype_args(var_name, call, s)\n        old_type = get_proper_type(old_type)\n        if not isinstance(call.analyzed, NewTypeExpr):\n            call.analyzed = NewTypeExpr(var_name, old_type, line=call.line, column=call.column)\n        else:\n            call.analyzed.old_type = old_type\n        if old_type is None:\n            if should_defer:\n                # Base type is not ready.\n                self.api.defer()\n                return True\n\n        # Create the corresponding class definition if the aliased type is subtypeable\n        assert isinstance(call.analyzed, NewTypeExpr)\n        if isinstance(old_type, TupleType):\n            newtype_class_info = self.build_newtype_typeinfo(\n                name, old_type, old_type.partial_fallback, s.line, call.analyzed.info\n            )\n            newtype_class_info.update_tuple_type(old_type)\n        elif isinstance(old_type, Instance):\n            if old_type.type.is_protocol:\n                self.fail(\"NewType cannot be used with protocol classes\", s)\n            newtype_class_info = self.build_newtype_typeinfo(\n                name, old_type, old_type, s.line, call.analyzed.info\n            )\n        else:\n            if old_type is not None:\n                message = \"Argument 2 to NewType(...) must be subclassable (got {})\"\n                self.fail(\n                    message.format(format_type(old_type, self.options)),\n                    s,\n                    code=codes.VALID_NEWTYPE,\n                )\n            # Otherwise the error was already reported.\n            old_type = AnyType(TypeOfAny.from_error)\n            object_type = self.api.named_type(\"builtins.object\")\n            newtype_class_info = self.build_newtype_typeinfo(\n                name, old_type, object_type, s.line, call.analyzed.info\n            )\n            newtype_class_info.fallback_to_any = True\n\n        check_for_explicit_any(\n            old_type, self.options, self.api.is_typeshed_stub_file, self.msg, context=s\n        )\n\n        if self.options.disallow_any_unimported and has_any_from_unimported_type(old_type):\n            self.msg.unimported_type_becomes_any(\"Argument 2 to NewType(...)\", old_type, s)\n\n        # If so, add it to the symbol table.\n        assert isinstance(call.analyzed, NewTypeExpr)\n        # As we do for normal classes, create the TypeInfo only once, then just\n        # update base classes on next iterations (to get rid of placeholders there).\n        if not call.analyzed.info:\n            call.analyzed.info = newtype_class_info\n        else:\n            call.analyzed.info.bases = newtype_class_info.bases\n        self.api.add_symbol(var_name, call.analyzed.info, s)\n        if self.api.is_func_scope():\n            self.api.add_symbol_skip_local(name, call.analyzed.info)\n        newtype_class_info.line = s.line\n        return True\n\n    def analyze_newtype_declaration(self, s: AssignmentStmt) -> tuple[str | None, CallExpr | None]:\n        \"\"\"Return the NewType call expression if `s` is a newtype declaration or None otherwise.\"\"\"\n        name, call = None, None\n        if (\n            len(s.lvalues) == 1\n            and isinstance(s.lvalues[0], NameExpr)\n            and isinstance(s.rvalue, CallExpr)\n            and isinstance(s.rvalue.callee, RefExpr)\n            and (s.rvalue.callee.fullname in (\"typing.NewType\", \"typing_extensions.NewType\"))\n        ):\n            name = s.lvalues[0].name\n\n            if s.type:\n                self.fail(\"Cannot declare the type of a NewType declaration\", s)\n\n            names = self.api.current_symbol_table()\n            existing = names.get(name)\n            # Give a better error message than generic \"Name already defined\".\n            if (\n                existing\n                and not isinstance(existing.node, PlaceholderNode)\n                and not s.rvalue.analyzed\n            ):\n                self.fail(f'Cannot redefine \"{name}\" as a NewType', s)\n\n            # This dummy NewTypeExpr marks the call as sufficiently analyzed; it will be\n            # overwritten later with a fully complete NewTypeExpr if there are no other\n            # errors with the NewType() call.\n            call = s.rvalue\n\n        return name, call\n\n    def check_newtype_args(\n        self, name: str, call: CallExpr, context: Context\n    ) -> tuple[Type | None, bool]:\n        \"\"\"Analyze base type in NewType call.\n\n        Return a tuple (type, should defer).\n        \"\"\"\n        has_failed = False\n        args, arg_kinds = call.args, call.arg_kinds\n        if len(args) != 2 or arg_kinds[0] != ARG_POS or arg_kinds[1] != ARG_POS:\n            self.fail(\"NewType(...) expects exactly two positional arguments\", context)\n            return None, False\n\n        # Check first argument\n        if not isinstance(args[0], StrExpr):\n            self.fail(\"Argument 1 to NewType(...) must be a string literal\", context)\n            has_failed = True\n        elif args[0].value != name:\n            msg = 'String argument 1 \"{}\" to NewType(...) does not match variable name \"{}\"'\n            self.fail(msg.format(args[0].value, name), context)\n            has_failed = True\n\n        # Check second argument\n        msg = \"Argument 2 to NewType(...) must be a valid type\"\n        try:\n            unanalyzed_type = expr_to_unanalyzed_type(args[1], self.options, self.api.is_stub_file)\n        except TypeTranslationError:\n            self.fail(msg, context)\n            return None, False\n\n        # We want to use our custom error message (see above), so we suppress\n        # the default error message for invalid types here.\n        old_type = get_proper_type(\n            self.api.anal_type(\n                unanalyzed_type,\n                report_invalid_types=False,\n                allow_placeholder=not self.api.is_func_scope(),\n            )\n        )\n        should_defer = False\n        if isinstance(old_type, PlaceholderType):\n            old_type = None\n        if old_type is None:\n            should_defer = True\n\n        # The caller of this function assumes that if we return a Type, it's always\n        # a valid one. So, we translate AnyTypes created from errors into None.\n        if isinstance(old_type, AnyType) and old_type.is_from_error:\n            self.fail(msg, context)\n            return None, False\n\n        return None if has_failed else old_type, should_defer\n\n    def build_newtype_typeinfo(\n        self,\n        name: str,\n        old_type: Type,\n        base_type: Instance,\n        line: int,\n        existing_info: TypeInfo | None,\n    ) -> TypeInfo:\n        info = existing_info or self.api.basic_new_typeinfo(name, base_type, line)\n        info.bases = [base_type]  # Update in case there were nested placeholders.\n        info.is_newtype = True\n\n        # Add __init__ method\n        args = [\n            Argument(Var(\"self\"), NoneType(), None, ARG_POS),\n            self.make_argument(\"item\", old_type),\n        ]\n        signature = CallableType(\n            arg_types=[Instance(info, []), old_type],\n            arg_kinds=[arg.kind for arg in args],\n            arg_names=[\"self\", \"item\"],\n            ret_type=NoneType(),\n            fallback=self.api.named_type(\"builtins.function\"),\n            name=name,\n        )\n        init_func = FuncDef(\"__init__\", args, Block([]), typ=signature)\n        init_func.info = info\n        init_func._fullname = info.fullname + \".__init__\"\n        if not existing_info:\n            updated = True\n        else:\n            previous_sym = info.names[\"__init__\"].node\n            assert isinstance(previous_sym, FuncDef)\n            updated = old_type != previous_sym.arguments[1].variable.type\n        info.names[\"__init__\"] = SymbolTableNode(MDEF, init_func)\n\n        if has_placeholder(old_type):\n            self.api.process_placeholder(None, \"NewType base\", info, force_progress=updated)\n        return info\n\n    # Helpers\n\n    def make_argument(self, name: str, type: Type) -> Argument:\n        return Argument(Var(name), type, None, ARG_POS)\n\n    def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:\n        self.api.fail(msg, ctx, code=code)\n"
  },
  {
    "path": "mypy/semanal_pass1.py",
    "content": "\"\"\"Block/import reachability analysis.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import (\n    AssertStmt,\n    AssignmentStmt,\n    Block,\n    ClassDef,\n    ExpressionStmt,\n    ForStmt,\n    FuncDef,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportFrom,\n    MatchStmt,\n    MypyFile,\n    ReturnStmt,\n)\nfrom mypy.options import Options\nfrom mypy.reachability import (\n    assert_will_always_fail,\n    infer_reachability_of_if_statement,\n    infer_reachability_of_match_statement,\n)\nfrom mypy.traverser import TraverserVisitor\n\n\nclass SemanticAnalyzerPreAnalysis(TraverserVisitor):\n    \"\"\"Analyze reachability of blocks and imports and other local things.\n\n    This runs before semantic analysis, so names have not been bound. Imports are\n    also not resolved yet, so we can only access the current module.\n\n    This determines static reachability of blocks and imports due to version and\n    platform checks, among others.\n\n    The main entry point is 'visit_file'.\n\n    Reachability of imports needs to be determined very early in the build since\n    this affects which modules will ultimately be processed.\n\n    Consider this example:\n\n      import sys\n\n      def do_stuff() -> None:\n          if sys.version_info >= (3, 10):\n              import xyz  # Only available in Python 3.10+\n              xyz.whatever()\n          ...\n\n    The block containing 'import xyz' is unreachable in Python 3 mode. The import\n    shouldn't be processed in Python 3 mode, even if the module happens to exist.\n    \"\"\"\n\n    def visit_file(self, file: MypyFile, fnam: str, mod_id: str, options: Options) -> None:\n        self.platform = options.platform\n        self.cur_mod_id = mod_id\n        self.cur_mod_node = file\n        self.options = options\n        self.is_global_scope = True\n        self.skipped_lines: set[int] = set()\n\n        for i, defn in enumerate(file.defs):\n            defn.accept(self)\n            if isinstance(defn, AssertStmt) and assert_will_always_fail(defn, options):\n                # We've encountered an assert that's always false,\n                # e.g. assert sys.platform == 'lol'.  Truncate the\n                # list of statements.  This mutates file.defs too.\n                if i < len(file.defs) - 1:\n                    next_def, last = file.defs[i + 1], file.defs[-1]\n                    if last.end_line is not None:\n                        # We are on a Python version recent enough to support end lines.\n                        self.skipped_lines |= set(range(next_def.line, last.end_line + 1))\n                file.imports = [\n                    i for i in file.imports if (i.line, i.column) <= (defn.line, defn.column)\n                ]\n                del file.defs[i + 1 :]\n                break\n        file.skipped_lines = self.skipped_lines\n\n    def visit_func_def(self, node: FuncDef) -> None:\n        old_global_scope = self.is_global_scope\n        self.is_global_scope = False\n        super().visit_func_def(node)\n        self.is_global_scope = old_global_scope\n        file_node = self.cur_mod_node\n        if (\n            self.is_global_scope\n            and file_node.is_stub\n            and node.name == \"__getattr__\"\n            and file_node.is_package_init_file()\n        ):\n            # __init__.pyi with __getattr__ means that any submodules are assumed\n            # to exist, even if there is no stub. Note that we can't verify that the\n            # return type is compatible, since we haven't bound types yet.\n            file_node.is_partial_stub_package = True\n\n    def visit_class_def(self, node: ClassDef) -> None:\n        old_global_scope = self.is_global_scope\n        self.is_global_scope = False\n        super().visit_class_def(node)\n        self.is_global_scope = old_global_scope\n\n    def visit_import_from(self, node: ImportFrom) -> None:\n        node.is_top_level = self.is_global_scope\n        super().visit_import_from(node)\n\n    def visit_import_all(self, node: ImportAll) -> None:\n        node.is_top_level = self.is_global_scope\n        super().visit_import_all(node)\n\n    def visit_import(self, node: Import) -> None:\n        node.is_top_level = self.is_global_scope\n        super().visit_import(node)\n\n    def visit_if_stmt(self, s: IfStmt) -> None:\n        infer_reachability_of_if_statement(s, self.options)\n        for expr in s.expr:\n            expr.accept(self)\n        for node in s.body:\n            node.accept(self)\n        if s.else_body:\n            s.else_body.accept(self)\n\n    def visit_block(self, b: Block) -> None:\n        if b.is_unreachable:\n            if b.end_line is not None:\n                # We are on a Python version recent enough to support end lines.\n                self.skipped_lines |= set(range(b.line, b.end_line + 1))\n            return\n        super().visit_block(b)\n\n    def visit_match_stmt(self, s: MatchStmt) -> None:\n        infer_reachability_of_match_statement(s, self.options)\n        for guard in s.guards:\n            if guard is not None:\n                guard.accept(self)\n        for body in s.bodies:\n            body.accept(self)\n\n    # The remaining methods are an optimization: don't visit nested expressions\n    # of common statements, since they can have no effect.\n\n    def visit_assignment_stmt(self, s: AssignmentStmt) -> None:\n        pass\n\n    def visit_expression_stmt(self, s: ExpressionStmt) -> None:\n        pass\n\n    def visit_return_stmt(self, s: ReturnStmt) -> None:\n        pass\n\n    def visit_for_stmt(self, s: ForStmt) -> None:\n        s.body.accept(self)\n        if s.else_body is not None:\n            s.else_body.accept(self)\n"
  },
  {
    "path": "mypy/semanal_shared.py",
    "content": "\"\"\"Shared definitions used by different parts of semantic analysis.\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections.abc import Callable\nfrom typing import Final, Literal, Protocol, overload\n\nfrom mypy_extensions import trait\n\nfrom mypy.errorcodes import LITERAL_REQ, ErrorCode\nfrom mypy.nodes import (\n    CallExpr,\n    ClassDef,\n    Context,\n    DataclassTransformSpec,\n    Decorator,\n    Expression,\n    FuncDef,\n    NameExpr,\n    Node,\n    OverloadedFuncDef,\n    RefExpr,\n    SymbolNode,\n    SymbolTable,\n    SymbolTableNode,\n    TypeInfo,\n)\nfrom mypy.plugin import SemanticAnalyzerPluginInterface\nfrom mypy.tvar_scope import TypeVarLikeScope\nfrom mypy.type_visitor import ANY_STRATEGY, BoolTypeQuery\nfrom mypy.typeops import make_simplified_union\nfrom mypy.types import (\n    TPDICT_FB_NAMES,\n    AnyType,\n    FunctionLike,\n    Instance,\n    Parameters,\n    ParamSpecFlavor,\n    ParamSpecType,\n    PlaceholderType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    UnpackType,\n    flatten_nested_tuples,\n    get_proper_type,\n)\n\n# Subclasses can override these Var attributes with incompatible types. This can also be\n# set for individual attributes using 'allow_incompatible_override' of Var.\nALLOW_INCOMPATIBLE_OVERRIDE: Final = (\"__slots__\", \"__deletable__\", \"__match_args__\")\n\n\n# Priorities for ordering of patches within the \"patch\" phase of semantic analysis\n# (after the main pass):\n\n# Fix fallbacks (does subtype checks).\nPRIORITY_FALLBACKS: Final = 1\n\n\n@trait\nclass SemanticAnalyzerCoreInterface:\n    \"\"\"A core abstract interface to generic semantic analyzer functionality.\n\n    This is implemented by both semantic analyzer passes 2 and 3.\n    \"\"\"\n\n    @abstractmethod\n    def lookup_qualified(\n        self, name: str, ctx: Context, suppress_errors: bool = False\n    ) -> SymbolTableNode | None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def lookup_fully_qualified(self, fullname: str, /) -> SymbolTableNode:\n        raise NotImplementedError\n\n    @abstractmethod\n    def lookup_fully_qualified_or_none(self, fullname: str, /) -> SymbolTableNode | None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def fail(\n        self,\n        msg: str,\n        ctx: Context,\n        serious: bool = False,\n        *,\n        blocker: bool = False,\n        code: ErrorCode | None = None,\n    ) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def incomplete_feature_enabled(self, feature: str, ctx: Context) -> bool:\n        raise NotImplementedError\n\n    @abstractmethod\n    def record_incomplete_ref(self) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def defer(self, debug_context: Context | None = None, force_progress: bool = False) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def is_incomplete_namespace(self, fullname: str) -> bool:\n        \"\"\"Is a module or class namespace potentially missing some definitions?\"\"\"\n        raise NotImplementedError\n\n    @property\n    @abstractmethod\n    def final_iteration(self) -> bool:\n        \"\"\"Is this the final iteration of semantic analysis?\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def is_future_flag_set(self, flag: str) -> bool:\n        \"\"\"Is the specific __future__ feature imported\"\"\"\n        raise NotImplementedError\n\n    @property\n    @abstractmethod\n    def is_stub_file(self) -> bool:\n        raise NotImplementedError\n\n    @abstractmethod\n    def is_func_scope(self) -> bool:\n        raise NotImplementedError\n\n    @property\n    @abstractmethod\n    def type(self) -> TypeInfo | None:\n        raise NotImplementedError\n\n\n@trait\nclass SemanticAnalyzerInterface(SemanticAnalyzerCoreInterface):\n    \"\"\"A limited abstract interface to some generic semantic analyzer pass 2 functionality.\n\n    We use this interface for various reasons:\n\n    * Looser coupling\n    * Cleaner import graph\n    * Less need to pass around callback functions\n    \"\"\"\n\n    tvar_scope: TypeVarLikeScope\n\n    @abstractmethod\n    def lookup(\n        self, name: str, ctx: Context, suppress_errors: bool = False\n    ) -> SymbolTableNode | None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def named_type(self, fullname: str, args: list[Type] | None = None) -> Instance:\n        raise NotImplementedError\n\n    @abstractmethod\n    def named_type_or_none(self, fullname: str, args: list[Type] | None = None) -> Instance | None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def accept(self, node: Node) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def anal_type(\n        self,\n        typ: Type,\n        /,\n        *,\n        tvar_scope: TypeVarLikeScope | None = None,\n        allow_tuple_literal: bool = False,\n        allow_unbound_tvars: bool = False,\n        allow_typed_dict_special_forms: bool = False,\n        allow_placeholder: bool = False,\n        report_invalid_types: bool = True,\n        prohibit_self_type: str | None = None,\n        prohibit_special_class_field_types: str | None = None,\n    ) -> Type | None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def get_and_bind_all_tvars(self, type_exprs: list[Expression]) -> list[TypeVarLikeType]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def basic_new_typeinfo(self, name: str, basetype_or_fallback: Instance, line: int) -> TypeInfo:\n        raise NotImplementedError\n\n    @abstractmethod\n    def schedule_patch(self, priority: int, patch: Callable[[], None]) -> None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def add_symbol_table_node(self, name: str, symbol: SymbolTableNode) -> bool:\n        \"\"\"Add node to the current symbol table.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def current_symbol_table(self) -> SymbolTable:\n        \"\"\"Get currently active symbol table.\n\n        May be module, class, or local namespace.\n        \"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def add_symbol(\n        self,\n        name: str,\n        node: SymbolNode,\n        context: Context,\n        module_public: bool = True,\n        module_hidden: bool = False,\n        can_defer: bool = True,\n    ) -> bool:\n        \"\"\"Add symbol to the current symbol table.\"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def add_symbol_skip_local(self, name: str, node: SymbolNode) -> None:\n        \"\"\"Add symbol to the current symbol table, skipping locals.\n\n        This is used to store symbol nodes in a symbol table that\n        is going to be serialized (local namespaces are not serialized).\n        See implementation docstring for more details.\n        \"\"\"\n        raise NotImplementedError\n\n    @abstractmethod\n    def parse_bool(self, expr: Expression) -> bool | None:\n        raise NotImplementedError\n\n    @abstractmethod\n    def qualified_name(self, name: str) -> str:\n        raise NotImplementedError\n\n    @property\n    @abstractmethod\n    def is_typeshed_stub_file(self) -> bool:\n        raise NotImplementedError\n\n    @abstractmethod\n    def process_placeholder(\n        self, name: str | None, kind: str, ctx: Context, force_progress: bool = False\n    ) -> None:\n        raise NotImplementedError\n\n\ndef set_callable_name(sig: Type, fdef: FuncDef) -> ProperType:\n    sig = get_proper_type(sig)\n    if isinstance(sig, FunctionLike):\n        if fdef.info:\n            if fdef.info.fullname in TPDICT_FB_NAMES:\n                # Avoid exposing the internal _TypedDict name.\n                class_name = \"TypedDict\"\n            else:\n                class_name = fdef.info.name\n            return sig.with_name(f\"{fdef.name} of {class_name}\")\n        else:\n            return sig.with_name(fdef.name)\n    else:\n        return sig\n\n\ndef calculate_tuple_fallback(typ: TupleType) -> None:\n    \"\"\"Calculate a precise item type for the fallback of a tuple type.\n\n    This must be called only after the main semantic analysis pass, since joins\n    aren't available before that.\n\n    Note that there is an apparent chicken and egg problem with respect\n    to verifying type arguments against bounds. Verifying bounds might\n    require fallbacks, but we might use the bounds to calculate the\n    fallbacks. In practice this is not a problem, since the worst that\n    can happen is that we have invalid type argument values, and these\n    can happen in later stages as well (they will generate errors, but\n    we don't prevent their existence).\n    \"\"\"\n    fallback = typ.partial_fallback\n    assert fallback.type.fullname == \"builtins.tuple\"\n    items = []\n    for item in flatten_nested_tuples(typ.items):\n        # TODO: this duplicates some logic in typeops.tuple_fallback().\n        if isinstance(item, UnpackType):\n            unpacked_type = get_proper_type(item.type)\n            if isinstance(unpacked_type, TypeVarTupleType):\n                unpacked_type = get_proper_type(unpacked_type.upper_bound)\n            if (\n                isinstance(unpacked_type, Instance)\n                and unpacked_type.type.fullname == \"builtins.tuple\"\n            ):\n                items.append(unpacked_type.args[0])\n            else:\n                # This is called before semanal_typeargs.py fixes broken unpacks,\n                # where the error should also be generated.\n                items.append(AnyType(TypeOfAny.from_error))\n        else:\n            items.append(item)\n    fallback.args = (make_simplified_union(items),)\n\n\nclass _NamedTypeCallback(Protocol):\n    def __call__(self, fullname: str, args: list[Type] | None = None) -> Instance: ...\n\n\ndef paramspec_args(\n    name: str,\n    fullname: str,\n    id: TypeVarId,\n    *,\n    named_type_func: _NamedTypeCallback,\n    line: int = -1,\n    column: int = -1,\n    prefix: Parameters | None = None,\n) -> ParamSpecType:\n    return ParamSpecType(\n        name,\n        fullname,\n        id,\n        flavor=ParamSpecFlavor.ARGS,\n        upper_bound=named_type_func(\"builtins.tuple\", [named_type_func(\"builtins.object\")]),\n        default=AnyType(TypeOfAny.from_omitted_generics),\n        line=line,\n        column=column,\n        prefix=prefix,\n    )\n\n\ndef paramspec_kwargs(\n    name: str,\n    fullname: str,\n    id: TypeVarId,\n    *,\n    named_type_func: _NamedTypeCallback,\n    line: int = -1,\n    column: int = -1,\n    prefix: Parameters | None = None,\n) -> ParamSpecType:\n    return ParamSpecType(\n        name,\n        fullname,\n        id,\n        flavor=ParamSpecFlavor.KWARGS,\n        upper_bound=named_type_func(\n            \"builtins.dict\", [named_type_func(\"builtins.str\"), named_type_func(\"builtins.object\")]\n        ),\n        default=AnyType(TypeOfAny.from_omitted_generics),\n        line=line,\n        column=column,\n        prefix=prefix,\n    )\n\n\nclass HasPlaceholders(BoolTypeQuery):\n    def __init__(self) -> None:\n        super().__init__(ANY_STRATEGY)\n\n    def visit_placeholder_type(self, t: PlaceholderType) -> bool:\n        return True\n\n\ndef has_placeholder(typ: Type) -> bool:\n    \"\"\"Check if a type contains any placeholder types (recursively).\"\"\"\n    return typ.accept(HasPlaceholders())\n\n\ndef find_dataclass_transform_spec(node: Node | None) -> DataclassTransformSpec | None:\n    \"\"\"\n    Find the dataclass transform spec for the given node, if any exists.\n\n    Per PEP 681 (https://peps.python.org/pep-0681/#the-dataclass-transform-decorator), dataclass\n    transforms can be specified in multiple ways, including decorator functions and\n    metaclasses/base classes. This function resolves the spec from any of these variants.\n    \"\"\"\n\n    # The spec only lives on the function/class definition itself, so we need to unwrap down to that\n    # point\n    if isinstance(node, CallExpr):\n        # Like dataclasses.dataclass, transform-based decorators can be applied either with or\n        # without parameters; ie, both of these forms are accepted:\n        #\n        # @typing.dataclass_transform\n        # class Foo: ...\n        # @typing.dataclass_transform(eq=True, order=True, ...)\n        # class Bar: ...\n        #\n        # We need to unwrap the call for the second variant.\n        node = node.callee\n\n    if isinstance(node, RefExpr):\n        node = node.node\n\n    if isinstance(node, Decorator):\n        # typing.dataclass_transform usage must always result in a Decorator; it always uses the\n        # `@dataclass_transform(...)` syntax and never `@dataclass_transform`\n        node = node.func\n\n    if isinstance(node, OverloadedFuncDef):\n        # The dataclass_transform decorator may be attached to any single overload, so we must\n        # search them all.\n        # Note that using more than one decorator is undefined behavior, so we can just take the\n        # first that we find.\n        for candidate in node.items:\n            spec = find_dataclass_transform_spec(candidate)\n            if spec is not None:\n                return spec\n        return find_dataclass_transform_spec(node.impl)\n\n    # For functions, we can directly consult the AST field for the spec\n    if isinstance(node, FuncDef):\n        return node.dataclass_transform_spec\n\n    if isinstance(node, ClassDef):\n        node = node.info\n    if isinstance(node, TypeInfo):\n        # Search all parent classes to see if any are decorated with `typing.dataclass_transform`\n        for base in node.mro[1:]:\n            if base.dataclass_transform_spec is not None:\n                return base.dataclass_transform_spec\n\n        # Check if there is a metaclass that is decorated with `typing.dataclass_transform`\n        #\n        # Note that PEP 681 only discusses using a metaclass that is directly decorated with\n        # `typing.dataclass_transform`; subclasses thereof should be treated with dataclass\n        # semantics rather than as transforms:\n        #\n        # > If dataclass_transform is applied to a class, dataclass-like semantics will be assumed\n        # > for any class that directly or indirectly derives from the decorated class or uses the\n        # > decorated class as a metaclass.\n        #\n        # The wording doesn't make this entirely explicit, but Pyright (the reference\n        # implementation for this PEP) only handles directly-decorated metaclasses.\n        metaclass_type = node.metaclass_type\n        if metaclass_type is not None and metaclass_type.type.dataclass_transform_spec is not None:\n            return metaclass_type.type.dataclass_transform_spec\n\n    return None\n\n\n# Never returns `None` if a default is given\n@overload\ndef require_bool_literal_argument(\n    api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface,\n    expression: Expression,\n    name: str,\n    default: Literal[True, False],\n) -> bool: ...\n\n\n@overload\ndef require_bool_literal_argument(\n    api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface,\n    expression: Expression,\n    name: str,\n    default: None = None,\n) -> bool | None: ...\n\n\ndef require_bool_literal_argument(\n    api: SemanticAnalyzerInterface | SemanticAnalyzerPluginInterface,\n    expression: Expression,\n    name: str,\n    default: bool | None = None,\n) -> bool | None:\n    \"\"\"Attempt to interpret an expression as a boolean literal, and fail analysis if we can't.\"\"\"\n    value = parse_bool(expression)\n    if value is None:\n        api.fail(\n            f'\"{name}\" argument must be a True or False literal', expression, code=LITERAL_REQ\n        )\n        return default\n\n    return value\n\n\ndef parse_bool(expr: Expression) -> bool | None:\n    if isinstance(expr, NameExpr):\n        if expr.fullname == \"builtins.True\":\n            return True\n        if expr.fullname == \"builtins.False\":\n            return False\n    return None\n"
  },
  {
    "path": "mypy/semanal_typeargs.py",
    "content": "\"\"\"Verify properties of type arguments, like 'int' in C[int] being valid.\n\nThis must happen after semantic analysis since there can be placeholder\ntypes until the end of semantic analysis, and these break various type\noperations, including subtype checks.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\n\nfrom mypy import errorcodes as codes, message_registry\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.errors import Errors\nfrom mypy.message_registry import INVALID_PARAM_SPEC_LOCATION, INVALID_PARAM_SPEC_LOCATION_NOTE\nfrom mypy.messages import format_type\nfrom mypy.mixedtraverser import MixedTraverserVisitor\nfrom mypy.nodes import Block, ClassDef, Context, FakeInfo, FuncItem, MypyFile\nfrom mypy.options import Options\nfrom mypy.scope import Scope\nfrom mypy.subtypes import is_same_type, is_subtype\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    Parameters,\n    ParamSpecType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypeOfAny,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UnpackType,\n    flatten_nested_tuples,\n    get_proper_type,\n    get_proper_types,\n    split_with_prefix_and_suffix,\n)\nfrom mypy.typevartuples import erased_vars\n\n\nclass TypeArgumentAnalyzer(MixedTraverserVisitor):\n    def __init__(\n        self,\n        errors: Errors,\n        options: Options,\n        is_typeshed_file: bool,\n        named_type: Callable[[str, list[Type]], Instance],\n    ) -> None:\n        super().__init__()\n        self.errors = errors\n        self.options = options\n        self.is_typeshed_file = is_typeshed_file\n        self.named_type = named_type\n        self.scope = Scope()\n        # Should we also analyze function definitions, or only module top-levels?\n        self.recurse_into_functions = True\n        # Keep track of the type aliases already visited. This is needed to avoid\n        # infinite recursion on types like A = Union[int, List[A]].\n        self.seen_aliases: set[TypeAliasType] = set()\n\n    def visit_mypy_file(self, o: MypyFile) -> None:\n        self.errors.set_file(o.path, o.fullname, scope=self.scope, options=self.options)\n        with self.scope.module_scope(o.fullname):\n            super().visit_mypy_file(o)\n\n    def visit_func(self, defn: FuncItem) -> None:\n        if not self.recurse_into_functions:\n            return\n        with self.scope.function_scope(defn):\n            super().visit_func(defn)\n\n    def visit_class_def(self, defn: ClassDef) -> None:\n        with self.scope.class_scope(defn.info):\n            super().visit_class_def(defn)\n\n    def visit_block(self, o: Block) -> None:\n        if not o.is_unreachable:\n            super().visit_block(o)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> None:\n        super().visit_type_alias_type(t)\n        if t.is_recursive:\n            if t in self.seen_aliases:\n                # Avoid infinite recursion on recursive type aliases.\n                return\n            self.seen_aliases.add(t)\n        assert t.alias is not None, f\"Unfixed type alias {t.type_ref}\"\n        is_error, is_invalid = self.validate_args(\n            t.alias.name, tuple(t.args), t.alias.alias_tvars, t\n        )\n        if is_invalid:\n            # If there is an arity error (e.g. non-Parameters used for ParamSpec etc.),\n            # then it is safer to erase the arguments completely, to avoid crashes later.\n            # TODO: can we move this logic to typeanal.py?\n            t.args = erased_vars(t.alias.alias_tvars, TypeOfAny.from_error)\n        if not is_error:\n            # If there was already an error for the alias itself, there is no point in checking\n            # the expansion, most likely it will result in the same kind of error.\n            if t.args:\n                # Since we always allow unbounded type variables in alias definitions, we need\n                # to verify the arguments satisfy the upper bounds of the expansion as well.\n                get_proper_type(t).accept(self)\n        if t.is_recursive:\n            self.seen_aliases.discard(t)\n\n    def visit_tuple_type(self, t: TupleType) -> None:\n        t.items = flatten_nested_tuples(t.items)\n        for i, it in enumerate(t.items):\n            if self.check_non_paramspec(it, \"tuple\", t):\n                t.items[i] = AnyType(TypeOfAny.from_error)\n\n        # We could also normalize Tuple[*tuple[X, ...]] -> tuple[X, ...] like in\n        # expand_type() but we can't do this here since it is not a translator visitor,\n        # and we need to return an Instance instead of TupleType.\n        super().visit_tuple_type(t)\n\n    def visit_callable_type(self, t: CallableType) -> None:\n        super().visit_callable_type(t)\n        t.normalize_trivial_unpack()\n\n    def visit_instance(self, t: Instance) -> None:\n        super().visit_instance(t)\n        # Type argument counts were checked in the main semantic analyzer pass. We assume\n        # that the counts are correct here.\n        info = t.type\n        if isinstance(info, FakeInfo):\n            return  # https://github.com/python/mypy/issues/11079\n        _, is_invalid = self.validate_args(info.name, t.args, info.defn.type_vars, t)\n        if is_invalid:\n            t.args = tuple(erased_vars(info.defn.type_vars, TypeOfAny.from_error))\n        if t.type.fullname == \"builtins.tuple\" and len(t.args) == 1:\n            # Normalize Tuple[*Tuple[X, ...], ...] -> Tuple[X, ...]\n            arg = t.args[0]\n            if isinstance(arg, UnpackType):\n                unpacked = get_proper_type(arg.type)\n                if isinstance(unpacked, Instance):\n                    assert unpacked.type.fullname == \"builtins.tuple\"\n                    t.args = unpacked.args\n\n    def check_non_paramspec(self, arg: Type, tv_kind: str, context: Context) -> bool:\n        if isinstance(arg, ParamSpecType):\n            self.fail(\n                INVALID_PARAM_SPEC_LOCATION.format(format_type(arg, self.options)),\n                context,\n                code=codes.VALID_TYPE,\n            )\n            self.note(\n                INVALID_PARAM_SPEC_LOCATION_NOTE.format(arg.name), context, code=codes.VALID_TYPE\n            )\n            return True\n        if isinstance(arg, Parameters):\n            self.fail(\n                f\"Cannot use {format_type(arg, self.options)} for {tv_kind},\"\n                \" only for ParamSpec\",\n                context,\n                code=codes.VALID_TYPE,\n            )\n            return True\n\n        return False\n\n    def validate_args(\n        self, name: str, args: tuple[Type, ...], type_vars: list[TypeVarLikeType], ctx: Context\n    ) -> tuple[bool, bool]:\n        if any(isinstance(v, TypeVarTupleType) for v in type_vars):\n            prefix = next(i for (i, v) in enumerate(type_vars) if isinstance(v, TypeVarTupleType))\n            tvt = type_vars[prefix]\n            assert isinstance(tvt, TypeVarTupleType)\n            start, middle, end = split_with_prefix_and_suffix(\n                tuple(args), prefix, len(type_vars) - prefix - 1\n            )\n            args = start + (TupleType(list(middle), tvt.tuple_fallback),) + end\n\n        is_error = False\n        is_invalid = False\n        for arg, tvar in zip(args, type_vars):\n            context = ctx if arg.line < 0 else arg\n            if isinstance(tvar, TypeVarType):\n                if self.check_non_paramspec(arg, \"regular type variable\", context):\n                    is_invalid = True\n                    continue\n\n                if self.in_type_alias_expr and isinstance(arg, TypeVarType):\n                    # Type aliases are allowed to use unconstrained type variables\n                    # error will be checked at substitution point.\n                    continue\n                if tvar.values:\n                    if isinstance(arg, TypeVarType):\n                        arg_values = arg.values\n                        if not arg_values:\n                            is_error = True\n                            self.fail(\n                                message_registry.INVALID_TYPEVAR_AS_TYPEARG.format(arg.name, name),\n                                context,\n                                code=codes.TYPE_VAR,\n                            )\n                            continue\n                    else:\n                        arg_values = [arg]\n                    if self.check_type_var_values(\n                        name, arg_values, tvar.name, tvar.values, context\n                    ):\n                        is_error = True\n                # Check against upper bound. Since it's object the vast majority of the time,\n                # add fast path to avoid a potentially slow subtype check.\n                upper_bound = tvar.upper_bound\n                object_upper_bound = (\n                    type(upper_bound) is Instance\n                    and upper_bound.type.fullname == \"builtins.object\"\n                )\n                if not object_upper_bound and not is_subtype(arg, upper_bound):\n                    is_error = True\n                    self.fail(\n                        message_registry.INVALID_TYPEVAR_ARG_BOUND.format(\n                            format_type(arg, self.options),\n                            name,\n                            format_type(upper_bound, self.options),\n                        ),\n                        context,\n                        code=codes.TYPE_VAR,\n                    )\n            elif isinstance(tvar, ParamSpecType):\n                if not isinstance(\n                    get_proper_type(arg), (ParamSpecType, Parameters, AnyType, UnboundType)\n                ):\n                    is_invalid = True\n                    self.fail(\n                        \"Can only replace ParamSpec with a parameter types list or\"\n                        f\" another ParamSpec, got {format_type(arg, self.options)}\",\n                        context,\n                        code=codes.VALID_TYPE,\n                    )\n            elif isinstance(tvar, TypeVarTupleType):\n                p_arg = get_proper_type(arg)\n                assert isinstance(p_arg, TupleType)\n                for it in p_arg.items:\n                    if self.check_non_paramspec(it, \"TypeVarTuple\", context):\n                        is_invalid = True\n        if is_invalid:\n            is_error = True\n        return is_error, is_invalid\n\n    def visit_unpack_type(self, typ: UnpackType) -> None:\n        super().visit_unpack_type(typ)\n        proper_type = get_proper_type(typ.type)\n        if isinstance(proper_type, TupleType):\n            return\n        if isinstance(proper_type, TypeVarTupleType):\n            return\n        # TODO: this should probably be .has_base(\"builtins.tuple\"), also elsewhere. This is\n        # tricky however, since this needs map_instance_to_supertype() available in many places.\n        if isinstance(proper_type, Instance) and proper_type.type.fullname == \"builtins.tuple\":\n            return\n        if not isinstance(proper_type, (UnboundType, AnyType)):\n            # Avoid extra errors if there were some errors already. Also interpret plain Any\n            # as tuple[Any, ...] (this is better for the code in type checker).\n            self.fail(\n                message_registry.INVALID_UNPACK.format(format_type(proper_type, self.options)),\n                typ.type,\n                code=codes.VALID_TYPE,\n            )\n        typ.type = self.named_type(\"builtins.tuple\", [AnyType(TypeOfAny.from_error)])\n\n    def check_type_var_values(\n        self, name: str, actuals: list[Type], arg_name: str, valids: list[Type], context: Context\n    ) -> bool:\n        if self.in_type_alias_expr:\n            # See testValidTypeAliasValues - we do not enforce typevar compatibility\n            # at the definition site. We check instantiation validity later.\n            return False\n        is_error = False\n        for actual in get_proper_types(actuals):\n            # We skip UnboundType here, since they may appear in defn.bases,\n            # the error will be caught when visiting info.bases, that have bound type\n            # variables.\n            if not isinstance(actual, (AnyType, UnboundType)) and not any(\n                is_same_type(actual, value) for value in valids\n            ):\n                is_error = True\n                if len(actuals) > 1 or not isinstance(actual, Instance):\n                    self.fail(\n                        message_registry.INVALID_TYPEVAR_ARG_VALUE.format(name),\n                        context,\n                        code=codes.TYPE_VAR,\n                    )\n                else:\n                    class_name = f'\"{name}\"'\n                    actual_type_name = f'\"{actual.type.name}\"'\n                    self.fail(\n                        message_registry.INCOMPATIBLE_TYPEVAR_VALUE.format(\n                            arg_name, class_name, actual_type_name\n                        ),\n                        context,\n                        code=codes.TYPE_VAR,\n                    )\n        return is_error\n\n    def fail(self, msg: str, context: Context, *, code: ErrorCode | None = None) -> None:\n        self.errors.report(context.line, context.column, msg, code=code)\n\n    def note(self, msg: str, context: Context, *, code: ErrorCode | None = None) -> None:\n        self.errors.report(context.line, context.column, msg, severity=\"note\", code=code)\n"
  },
  {
    "path": "mypy/semanal_typeddict.py",
    "content": "\"\"\"Semantic analysis of TypedDict definitions.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Collection\nfrom typing import Final\n\nfrom mypy import errorcodes as codes, message_registry\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.expandtype import expand_type\nfrom mypy.exprtotype import TypeTranslationError, expr_to_unanalyzed_type\nfrom mypy.message_registry import TYPEDDICT_OVERRIDE_MERGE\nfrom mypy.messages import MessageBuilder\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    AssignmentStmt,\n    CallExpr,\n    ClassDef,\n    Context,\n    DictExpr,\n    EllipsisExpr,\n    Expression,\n    ExpressionStmt,\n    IndexExpr,\n    NameExpr,\n    PassStmt,\n    RefExpr,\n    Statement,\n    StrExpr,\n    TempNode,\n    TupleExpr,\n    TypeAlias,\n    TypedDictExpr,\n    TypeInfo,\n)\nfrom mypy.options import Options\nfrom mypy.semanal_shared import (\n    SemanticAnalyzerInterface,\n    has_placeholder,\n    require_bool_literal_argument,\n)\nfrom mypy.state import state\nfrom mypy.typeanal import check_for_explicit_any, has_any_from_unimported_type\nfrom mypy.types import (\n    TPDICT_NAMES,\n    AnyType,\n    ReadOnlyType,\n    RequiredType,\n    Type,\n    TypedDictType,\n    TypeOfAny,\n    TypeVarLikeType,\n    get_proper_type,\n)\n\nTPDICT_CLASS_ERROR: Final = (\n    'Invalid statement in TypedDict definition; expected \"field_name: field_type\"'\n)\n\n\nclass TypedDictAnalyzer:\n    def __init__(\n        self, options: Options, api: SemanticAnalyzerInterface, msg: MessageBuilder\n    ) -> None:\n        self.options = options\n        self.api = api\n        self.msg = msg\n\n    def analyze_typeddict_classdef(self, defn: ClassDef) -> tuple[bool, TypeInfo | None]:\n        \"\"\"Analyze a class that may define a TypedDict.\n\n        Assume that base classes have been analyzed already.\n\n        Note: Unlike normal classes, we won't create a TypeInfo until\n        the whole definition of the TypeDict (including the body and all\n        key names and types) is complete.  This is mostly because we\n        store the corresponding TypedDictType in the TypeInfo.\n\n        Return (is this a TypedDict, new TypeInfo). Specifics:\n         * If we couldn't finish due to incomplete reference anywhere in\n           the definition, return (True, None).\n         * If this is not a TypedDict, return (False, None).\n        \"\"\"\n        possible = False\n        for base_expr in defn.base_type_exprs:\n            if isinstance(base_expr, CallExpr):\n                base_expr = base_expr.callee\n            if isinstance(base_expr, IndexExpr):\n                base_expr = base_expr.base\n            if isinstance(base_expr, RefExpr):\n                self.api.accept(base_expr)\n                if base_expr.fullname in TPDICT_NAMES or self.is_typeddict(base_expr):\n                    possible = True\n                    if isinstance(base_expr.node, TypeInfo) and base_expr.node.is_final:\n                        err = message_registry.CANNOT_INHERIT_FROM_FINAL\n                        self.fail(err.format(base_expr.node.name).value, defn, code=err.code)\n        if not possible:\n            return False, None\n        existing_info = None\n        if isinstance(defn.analyzed, TypedDictExpr):\n            existing_info = defn.analyzed.info\n\n        field_types: dict[str, Type] | None\n        if (\n            len(defn.base_type_exprs) == 1\n            and isinstance(defn.base_type_exprs[0], RefExpr)\n            and defn.base_type_exprs[0].fullname in TPDICT_NAMES\n        ):\n            # Building a new TypedDict\n            field_types, statements, required_keys, readonly_keys = (\n                self.analyze_typeddict_classdef_fields(defn)\n            )\n            if field_types is None:\n                return True, None  # Defer\n            if self.api.is_func_scope() and \"@\" not in defn.name:\n                defn.name += \"@\" + str(defn.line)\n            info = self.build_typeddict_typeinfo(\n                defn.name, field_types, required_keys, readonly_keys, defn.line, existing_info\n            )\n            defn.analyzed = TypedDictExpr(info)\n            defn.analyzed.line = defn.line\n            defn.analyzed.column = defn.column\n            defn.defs.body = statements\n            return True, info\n\n        # Extending/merging existing TypedDicts\n        typeddict_bases: list[Expression] = []\n        typeddict_bases_set = set()\n        for expr in defn.base_type_exprs:\n            ok, maybe_type_info, _ = self.check_typeddict(expr, None, False)\n            if ok and maybe_type_info is not None:\n                # expr is a CallExpr\n                info = maybe_type_info\n                typeddict_bases_set.add(info.fullname)\n                typeddict_bases.append(expr)\n            elif isinstance(expr, RefExpr) and expr.fullname in TPDICT_NAMES:\n                if \"TypedDict\" not in typeddict_bases_set:\n                    typeddict_bases_set.add(\"TypedDict\")\n                else:\n                    self.fail('Duplicate base class \"TypedDict\"', defn)\n            elif (\n                isinstance(expr, RefExpr)\n                and self.is_typeddict(expr)\n                or isinstance(expr, IndexExpr)\n                and self.is_typeddict(expr.base)\n            ):\n                info = self._parse_typeddict_base(expr, defn)\n                if info.fullname not in typeddict_bases_set:\n                    typeddict_bases_set.add(info.fullname)\n                    typeddict_bases.append(expr)\n                else:\n                    self.fail(f'Duplicate base class \"{info.name}\"', defn)\n            else:\n                self.fail(\"All bases of a new TypedDict must be TypedDict types\", defn)\n\n        field_types = {}\n        required_keys = set()\n        readonly_keys = set()\n        # Iterate over bases in reverse order so that leftmost base class' keys take precedence\n        for base in reversed(typeddict_bases):\n            self.add_keys_and_types_from_base(\n                base, field_types, required_keys, readonly_keys, defn\n            )\n        new_field_types, new_statements, new_required_keys, new_readonly_keys = (\n            self.analyze_typeddict_classdef_fields(defn, oldfields=field_types)\n        )\n        if new_field_types is None:\n            return True, None  # Defer\n        field_types.update(new_field_types)\n        required_keys.update(new_required_keys)\n        readonly_keys.update(new_readonly_keys)\n        info = self.build_typeddict_typeinfo(\n            defn.name, field_types, required_keys, readonly_keys, defn.line, existing_info\n        )\n        defn.analyzed = TypedDictExpr(info)\n        defn.analyzed.line = defn.line\n        defn.analyzed.column = defn.column\n        defn.defs.body = new_statements\n        return True, info\n\n    def add_keys_and_types_from_base(\n        self,\n        base: Expression,\n        field_types: dict[str, Type],\n        required_keys: set[str],\n        readonly_keys: set[str],\n        ctx: Context,\n    ) -> None:\n        info = self._parse_typeddict_base(base, ctx)\n        base_args: list[Type] = []\n        if isinstance(base, IndexExpr):\n            args = self.analyze_base_args(base, ctx)\n            if args is None:\n                return\n            base_args = args\n\n        assert info.typeddict_type is not None\n        base_typed_dict = info.typeddict_type\n        base_items = base_typed_dict.items\n        valid_items = base_items.copy()\n\n        # Always fix invalid bases to avoid crashes.\n        tvars = info.defn.type_vars\n        if len(base_args) != len(tvars):\n            any_kind = TypeOfAny.from_omitted_generics\n            if base_args:\n                self.fail(f'Invalid number of type arguments for \"{info.name}\"', ctx)\n                any_kind = TypeOfAny.from_error\n            base_args = [AnyType(any_kind) for _ in tvars]\n\n        with state.strict_optional_set(self.options.strict_optional):\n            valid_items = self.map_items_to_base(valid_items, tvars, base_args)\n        for key in base_items:\n            if key in field_types:\n                self.fail(TYPEDDICT_OVERRIDE_MERGE.format(key), ctx)\n\n        field_types.update(valid_items)\n        required_keys.update(base_typed_dict.required_keys)\n        readonly_keys.update(base_typed_dict.readonly_keys)\n\n    def _parse_typeddict_base(self, base: Expression, ctx: Context) -> TypeInfo:\n        if isinstance(base, RefExpr):\n            if isinstance(base.node, TypeInfo):\n                return base.node\n            elif isinstance(base.node, TypeAlias):\n                # Only old TypeAlias / plain assignment, PEP695 `type` stmt\n                # cannot be used as a base class\n                target = get_proper_type(base.node.target)\n                assert isinstance(target, TypedDictType)\n                return target.fallback.type\n            else:\n                assert False\n        elif isinstance(base, IndexExpr):\n            assert isinstance(base.base, RefExpr)\n            return self._parse_typeddict_base(base.base, ctx)\n        else:\n            assert isinstance(base, CallExpr)\n            assert isinstance(base.analyzed, TypedDictExpr)\n            return base.analyzed.info\n\n    def analyze_base_args(self, base: IndexExpr, ctx: Context) -> list[Type] | None:\n        \"\"\"Analyze arguments of base type expressions as types.\n\n        We need to do this, because normal base class processing happens after\n        the TypedDict special-casing (plus we get a custom error message).\n        \"\"\"\n        base_args = []\n        if isinstance(base.index, TupleExpr):\n            args = base.index.items\n        else:\n            args = [base.index]\n\n        for arg_expr in args:\n            try:\n                type = expr_to_unanalyzed_type(arg_expr, self.options, self.api.is_stub_file)\n            except TypeTranslationError:\n                self.fail(\"Invalid TypedDict type argument\", ctx)\n                return None\n            analyzed = self.api.anal_type(\n                type,\n                allow_typed_dict_special_forms=True,\n                allow_placeholder=not self.api.is_func_scope(),\n            )\n            if analyzed is None:\n                return None\n            base_args.append(analyzed)\n        return base_args\n\n    def map_items_to_base(\n        self, valid_items: dict[str, Type], tvars: list[TypeVarLikeType], base_args: list[Type]\n    ) -> dict[str, Type]:\n        \"\"\"Map item types to how they would look in their base with type arguments applied.\n\n        Note it is safe to use expand_type() during semantic analysis, because it should never\n        (indirectly) call is_subtype().\n        \"\"\"\n        mapped_items = {}\n        for key in valid_items:\n            type_in_base = valid_items[key]\n            if not tvars:\n                mapped_items[key] = type_in_base\n                continue\n            # TODO: simple zip can't be used for variadic types.\n            mapped_items[key] = expand_type(\n                type_in_base, {t.id: a for (t, a) in zip(tvars, base_args)}\n            )\n        return mapped_items\n\n    def analyze_typeddict_classdef_fields(\n        self, defn: ClassDef, oldfields: Collection[str] | None = None\n    ) -> tuple[dict[str, Type] | None, list[Statement], set[str], set[str]]:\n        \"\"\"Analyze fields defined in a TypedDict class definition.\n\n        This doesn't consider inherited fields (if any). Also consider totality,\n        if given.\n\n        Return tuple with these items:\n         * Dict of key -> type (or None if found an incomplete reference -> deferral)\n         * List of statements from defn.defs.body that are legally allowed to be a\n           part of a TypedDict definition\n         * Set of required keys\n        \"\"\"\n        fields: dict[str, Type] = {}\n        readonly_keys = set[str]()\n        required_keys = set[str]()\n        statements: list[Statement] = []\n\n        total: bool | None = True\n        for key in defn.keywords:\n            if key == \"total\":\n                total = require_bool_literal_argument(\n                    self.api, defn.keywords[\"total\"], \"total\", True\n                )\n                continue\n            for_function = ' for \"__init_subclass__\" of \"TypedDict\"'\n            self.msg.unexpected_keyword_argument_for_function(for_function, key, defn)\n\n        for stmt in defn.defs.body:\n            if not isinstance(stmt, AssignmentStmt):\n                # Still allow pass or ... (for empty TypedDict's) and docstrings\n                if isinstance(stmt, PassStmt) or (\n                    isinstance(stmt, ExpressionStmt)\n                    and isinstance(stmt.expr, (EllipsisExpr, StrExpr))\n                ):\n                    statements.append(stmt)\n                else:\n                    defn.removed_statements.append(stmt)\n                    self.fail(TPDICT_CLASS_ERROR, stmt)\n            elif len(stmt.lvalues) > 1 or not isinstance(stmt.lvalues[0], NameExpr):\n                # An assignment, but an invalid one.\n                defn.removed_statements.append(stmt)\n                self.fail(TPDICT_CLASS_ERROR, stmt)\n            else:\n                name = stmt.lvalues[0].name\n                if name in (oldfields or []):\n                    self.fail(f'Overwriting TypedDict field \"{name}\" while extending', stmt)\n                if name in fields:\n                    self.fail(f'Duplicate TypedDict key \"{name}\"', stmt)\n                    continue\n                # Append stmt, name, and type in this case...\n                statements.append(stmt)\n\n                field_type: Type\n                if stmt.unanalyzed_type is None:\n                    field_type = AnyType(TypeOfAny.unannotated)\n                else:\n                    analyzed = self.api.anal_type(\n                        stmt.unanalyzed_type,\n                        allow_typed_dict_special_forms=True,\n                        allow_placeholder=not self.api.is_func_scope(),\n                        prohibit_self_type=\"TypedDict item type\",\n                        prohibit_special_class_field_types=\"TypedDict\",\n                    )\n                    if analyzed is None:\n                        return None, [], set(), set()  # Need to defer\n                    field_type = analyzed\n                    if not has_placeholder(analyzed):\n                        stmt.type = self.extract_meta_info(analyzed, stmt)[0]\n\n                field_type, required, readonly = self.extract_meta_info(field_type)\n                fields[name] = field_type\n\n                if (total or required is True) and required is not False:\n                    required_keys.add(name)\n                if readonly:\n                    readonly_keys.add(name)\n\n                # ...despite possible minor failures that allow further analysis.\n                if stmt.type is None or hasattr(stmt, \"new_syntax\") and not stmt.new_syntax:\n                    self.fail(TPDICT_CLASS_ERROR, stmt)\n                elif not isinstance(stmt.rvalue, TempNode):\n                    # x: int assigns rvalue to TempNode(AnyType())\n                    self.fail(\"Right hand side values are not supported in TypedDict\", stmt)\n\n        return fields, statements, required_keys, readonly_keys\n\n    def extract_meta_info(\n        self, typ: Type, context: Context | None = None\n    ) -> tuple[Type, bool | None, bool]:\n        \"\"\"Unwrap all metadata types.\"\"\"\n        is_required = None  # default, no modification\n        readonly = False  # by default all is mutable\n\n        seen_required = False\n        seen_readonly = False\n        while isinstance(typ, (RequiredType, ReadOnlyType)):\n            if isinstance(typ, RequiredType):\n                if context is not None and seen_required:\n                    self.fail(\n                        '\"{}\" type cannot be nested'.format(\n                            \"Required[]\" if typ.required else \"NotRequired[]\"\n                        ),\n                        context,\n                        code=codes.VALID_TYPE,\n                    )\n                is_required = typ.required\n                seen_required = True\n                typ = typ.item\n            if isinstance(typ, ReadOnlyType):\n                if context is not None and seen_readonly:\n                    self.fail('\"ReadOnly[]\" type cannot be nested', context, code=codes.VALID_TYPE)\n                readonly = True\n                seen_readonly = True\n                typ = typ.item\n        return typ, is_required, readonly\n\n    def check_typeddict(\n        self, node: Expression, var_name: str | None, is_func_scope: bool\n    ) -> tuple[bool, TypeInfo | None, list[TypeVarLikeType]]:\n        \"\"\"Check if a call defines a TypedDict.\n\n        The optional var_name argument is the name of the variable to\n        which this is assigned, if any.\n\n        Return a pair (is it a typed dict, corresponding TypeInfo).\n\n        If the definition is invalid but looks like a TypedDict,\n        report errors but return (some) TypeInfo. If some type is not ready,\n        return (True, None).\n        \"\"\"\n        if not isinstance(node, CallExpr):\n            return False, None, []\n        call = node\n        callee = call.callee\n        if not isinstance(callee, RefExpr):\n            return False, None, []\n        fullname = callee.fullname\n        if fullname not in TPDICT_NAMES:\n            return False, None, []\n        res = self.parse_typeddict_args(call)\n        if res is None:\n            # This is a valid typed dict, but some type is not ready.\n            # The caller should defer this until next iteration.\n            return True, None, []\n        name, items, types, total, tvar_defs, ok = res\n        if not ok:\n            # Error. Construct dummy return value.\n            if var_name:\n                name = var_name\n                if is_func_scope:\n                    name += \"@\" + str(call.line)\n            else:\n                name = var_name = \"TypedDict@\" + str(call.line)\n            info = self.build_typeddict_typeinfo(name, {}, set(), set(), call.line, None)\n        else:\n            if var_name is not None and name != var_name:\n                self.fail(\n                    'First argument \"{}\" to TypedDict() does not match variable name \"{}\"'.format(\n                        name, var_name\n                    ),\n                    node,\n                    code=codes.NAME_MATCH,\n                )\n            if name != var_name or is_func_scope:\n                # Give it a unique name derived from the line number.\n                name += \"@\" + str(call.line)\n            required_keys = {\n                field\n                for (field, t) in zip(items, types)\n                if (total or (isinstance(t, RequiredType) and t.required))\n                and not (isinstance(t, RequiredType) and not t.required)\n            }\n            readonly_keys = {\n                field for (field, t) in zip(items, types) if isinstance(t, ReadOnlyType)\n            }\n            types = [  # unwrap Required[T] or ReadOnly[T] to just T\n                t.item if isinstance(t, (RequiredType, ReadOnlyType)) else t for t in types\n            ]\n\n            # Perform various validations after unwrapping.\n            for t in types:\n                check_for_explicit_any(\n                    t, self.options, self.api.is_typeshed_stub_file, self.msg, context=call\n                )\n            if self.options.disallow_any_unimported:\n                for t in types:\n                    if has_any_from_unimported_type(t):\n                        self.msg.unimported_type_becomes_any(\"Type of a TypedDict key\", t, call)\n\n            existing_info = None\n            if isinstance(node.analyzed, TypedDictExpr):\n                existing_info = node.analyzed.info\n            info = self.build_typeddict_typeinfo(\n                name,\n                dict(zip(items, types)),\n                required_keys,\n                readonly_keys,\n                call.line,\n                existing_info,\n            )\n            info.line = node.line\n        # Store generated TypeInfo under both names, see semanal_namedtuple for more details.\n        if name != var_name or is_func_scope:\n            self.api.add_symbol_skip_local(name, info)\n        if var_name:\n            self.api.add_symbol(var_name, info, node)\n        call.analyzed = TypedDictExpr(info)\n        call.analyzed.set_line(call)\n        return True, info, tvar_defs\n\n    def parse_typeddict_args(\n        self, call: CallExpr\n    ) -> tuple[str, list[str], list[Type], bool, list[TypeVarLikeType], bool] | None:\n        \"\"\"Parse typed dict call expression.\n\n        Return names, types, totality, was there an error during parsing.\n        If some type is not ready, return None.\n        \"\"\"\n        # TODO: Share code with check_argument_count in checkexpr.py?\n        args = call.args\n        if len(args) < 2:\n            return self.fail_typeddict_arg(\"Too few arguments for TypedDict()\", call)\n        if len(args) > 3:\n            return self.fail_typeddict_arg(\"Too many arguments for TypedDict()\", call)\n        # TODO: Support keyword arguments\n        if call.arg_kinds not in ([ARG_POS, ARG_POS], [ARG_POS, ARG_POS, ARG_NAMED]):\n            return self.fail_typeddict_arg(\"Unexpected arguments to TypedDict()\", call)\n        if len(args) == 3 and call.arg_names[2] != \"total\":\n            return self.fail_typeddict_arg(\n                f'Unexpected keyword argument \"{call.arg_names[2]}\" for \"TypedDict\"', call\n            )\n        if not isinstance(args[0], StrExpr):\n            return self.fail_typeddict_arg(\n                \"TypedDict() expects a string literal as the first argument\", call\n            )\n        if not isinstance(args[1], DictExpr):\n            return self.fail_typeddict_arg(\n                \"TypedDict() expects a dictionary literal as the second argument\", call\n            )\n        total: bool | None = True\n        if len(args) == 3:\n            total = require_bool_literal_argument(self.api, call.args[2], \"total\")\n            if total is None:\n                return \"\", [], [], True, [], False\n        dictexpr = args[1]\n        tvar_defs = self.api.get_and_bind_all_tvars([t for k, t in dictexpr.items])\n        res = self.parse_typeddict_fields_with_types(dictexpr.items)\n        if res is None:\n            # One of the types is not ready, defer.\n            return None\n        items, types, ok = res\n        assert total is not None\n        return args[0].value, items, types, total, tvar_defs, ok\n\n    def parse_typeddict_fields_with_types(\n        self, dict_items: list[tuple[Expression | None, Expression]]\n    ) -> tuple[list[str], list[Type], bool] | None:\n        \"\"\"Parse typed dict items passed as pairs (name expression, type expression).\n\n        Return names, types, was there an error. If some type is not ready, return None.\n        \"\"\"\n        seen_keys = set()\n        items: list[str] = []\n        types: list[Type] = []\n        for field_name_expr, field_type_expr in dict_items:\n            if isinstance(field_name_expr, StrExpr):\n                key = field_name_expr.value\n                items.append(key)\n                if key in seen_keys:\n                    self.fail(f'Duplicate TypedDict key \"{key}\"', field_name_expr)\n                seen_keys.add(key)\n            else:\n                name_context = field_name_expr or field_type_expr\n                self.fail_typeddict_arg(\"Invalid TypedDict() field name\", name_context)\n                return [], [], False\n            try:\n                type = expr_to_unanalyzed_type(\n                    field_type_expr, self.options, self.api.is_stub_file\n                )\n            except TypeTranslationError:\n                self.fail_typeddict_arg(\"Use dict literal for nested TypedDict\", field_type_expr)\n                return [], [], False\n            analyzed = self.api.anal_type(\n                type,\n                allow_typed_dict_special_forms=True,\n                allow_placeholder=not self.api.is_func_scope(),\n                prohibit_self_type=\"TypedDict item type\",\n                prohibit_special_class_field_types=\"TypedDict\",\n            )\n            if analyzed is None:\n                return None\n            types.append(analyzed)\n        return items, types, True\n\n    def fail_typeddict_arg(\n        self, message: str, context: Context\n    ) -> tuple[str, list[str], list[Type], bool, list[TypeVarLikeType], bool]:\n        self.fail(message, context)\n        return \"\", [], [], True, [], False\n\n    def build_typeddict_typeinfo(\n        self,\n        name: str,\n        item_types: dict[str, Type],\n        required_keys: set[str],\n        readonly_keys: set[str],\n        line: int,\n        existing_info: TypeInfo | None,\n    ) -> TypeInfo:\n        # Prefer typing then typing_extensions if available.\n        fallback = (\n            self.api.named_type_or_none(\"typing._TypedDict\", [])\n            or self.api.named_type_or_none(\"typing_extensions._TypedDict\", [])\n            or self.api.named_type_or_none(\"mypy_extensions._TypedDict\", [])\n        )\n        assert fallback is not None\n        info = existing_info or self.api.basic_new_typeinfo(name, fallback, line)\n        typeddict_type = TypedDictType(item_types, required_keys, readonly_keys, fallback)\n        if has_placeholder(typeddict_type):\n            self.api.process_placeholder(\n                None, \"TypedDict item\", info, force_progress=typeddict_type != info.typeddict_type\n            )\n        info.update_typeddict_type(typeddict_type)\n        return info\n\n    # Helpers\n\n    def is_typeddict(self, expr: Expression) -> bool:\n        return isinstance(expr, RefExpr) and (\n            isinstance(expr.node, TypeInfo)\n            and expr.node.typeddict_type is not None\n            or isinstance(expr.node, TypeAlias)\n            and isinstance(get_proper_type(expr.node.target), TypedDictType)\n        )\n\n    def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:\n        self.api.fail(msg, ctx, code=code)\n\n    def note(self, msg: str, ctx: Context) -> None:\n        self.api.note(msg, ctx)\n"
  },
  {
    "path": "mypy/server/__init__.py",
    "content": ""
  },
  {
    "path": "mypy/server/astdiff.py",
    "content": "\"\"\"Utilities for comparing two versions of a module symbol table.\n\nThe goal is to find which AST nodes have externally visible changes, so\nthat we can fire triggers and re-process other parts of the program\nthat are stale because of the changes.\n\nOnly look at detail at definitions at the current module -- don't\nrecurse into other modules.\n\nA summary of the module contents:\n\n* snapshot_symbol_table(...) creates an opaque snapshot description of a\n  module/class symbol table (recursing into nested class symbol tables).\n\n* compare_symbol_table_snapshots(...) compares two snapshots for the same\n  module id and returns fully qualified names of differences (which act as\n  triggers).\n\nTo compare two versions of a module symbol table, take snapshots of both\nversions and compare the snapshots. The use of snapshots makes it easy to\ncompare two versions of the *same* symbol table that is being mutated.\n\nSummary of how this works for certain kinds of differences:\n\n* If a symbol table node is deleted or added (only present in old/new version\n  of the symbol table), it is considered different, of course.\n\n* If a symbol table node refers to a different sort of thing in the new version,\n  it is considered different (for example, if a class is replaced with a\n  function).\n\n* If the signature of a function has changed, it is considered different.\n\n* If the type of a variable changes, it is considered different.\n\n* If the MRO of a class changes, or a non-generic class is turned into a\n  generic class, the class is considered different (there are other such \"big\"\n  differences that cause a class to be considered changed). However, just changes\n  to attributes or methods don't generally constitute a difference at the\n  class level -- these are handled at attribute level (say, 'mod.Cls.method'\n  is different rather than 'mod.Cls' being different).\n\n* If an imported name targets a different name (say, 'from x import y' is\n  replaced with 'from z import y'), the name in the module is considered\n  different. If the target of an import continues to have the same name,\n  but it's specifics change, this doesn't mean that the imported name is\n  treated as changed. Say, there is 'from x import y' in 'm', and the\n  type of 'x.y' has changed. This doesn't mean that that 'm.y' is considered\n  changed. Instead, processing the difference in 'm' will be handled through\n  fine-grained dependencies.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import TypeAlias as _TypeAlias, Union\n\nfrom mypy.expandtype import expand_type\nfrom mypy.nodes import (\n    SYMBOL_FUNCBASE_TYPES,\n    UNBOUND_IMPORTED,\n    Decorator,\n    FuncDef,\n    FuncItem,\n    MypyFile,\n    OverloadedFuncDef,\n    ParamSpecExpr,\n    SymbolNode,\n    SymbolTable,\n    TypeAlias,\n    TypeInfo,\n    TypeVarExpr,\n    TypeVarTupleExpr,\n    Var,\n)\nfrom mypy.semanal_shared import find_dataclass_transform_spec\nfrom mypy.state import state\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    TypeVisitor,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n)\nfrom mypy.util import get_prefix\n\n# Snapshot representation of a symbol table node or type. The representation is\n# opaque -- the only supported operations are comparing for equality and\n# hashing (latter for type snapshots only). Snapshots can contain primitive\n# objects, nested tuples, lists and dictionaries and primitive objects (type\n# snapshots are immutable).\n#\n# For example, the snapshot of the 'int' type is ('Instance', 'builtins.int', ()).\n\n# Type snapshots are strict, they must be hashable and ordered (e.g. for Unions).\nPrimitive: _TypeAlias = str | float | int | bool  # float is for Literal[3.14] support.\nSnapshotItem: _TypeAlias = tuple[Union[Primitive, \"SnapshotItem\"], ...]\n\n# Symbol snapshots can be more lenient.\nSymbolSnapshot: _TypeAlias = tuple[object, ...]\n\n\ndef compare_symbol_table_snapshots(\n    name_prefix: str, snapshot1: dict[str, SymbolSnapshot], snapshot2: dict[str, SymbolSnapshot]\n) -> set[str]:\n    \"\"\"Return names that are different in two snapshots of a symbol table.\n\n    Only shallow (intra-module) differences are considered. References to things defined\n    outside the module are compared based on the name of the target only.\n\n    Recurse into class symbol tables (if the class is defined in the target module).\n\n    Return a set of fully-qualified names (e.g., 'mod.func' or 'mod.Class.method').\n    \"\"\"\n    # Find names only defined only in one version.\n    names1 = {f\"{name_prefix}.{name}\" for name in snapshot1}\n    names2 = {f\"{name_prefix}.{name}\" for name in snapshot2}\n    triggers = names1 ^ names2\n\n    # Look for names defined in both versions that are different.\n    for name in set(snapshot1.keys()) & set(snapshot2.keys()):\n        item1 = snapshot1[name]\n        item2 = snapshot2[name]\n        kind1 = item1[0]\n        kind2 = item2[0]\n        item_name = f\"{name_prefix}.{name}\"\n        if kind1 != kind2:\n            # Different kind of node in two snapshots -> trivially different.\n            triggers.add(item_name)\n        elif kind1 == \"TypeInfo\":\n            if item1[:-1] != item2[:-1]:\n                # Record major difference (outside class symbol tables).\n                triggers.add(item_name)\n            # Look for differences in nested class symbol table entries.\n            assert isinstance(item1[-1], dict)\n            assert isinstance(item2[-1], dict)\n            triggers |= compare_symbol_table_snapshots(item_name, item1[-1], item2[-1])\n        else:\n            # Shallow node (no interesting internal structure). Just use equality.\n            if snapshot1[name] != snapshot2[name]:\n                triggers.add(item_name)\n\n    return triggers\n\n\ndef snapshot_symbol_table(name_prefix: str, table: SymbolTable) -> dict[str, SymbolSnapshot]:\n    \"\"\"Create a snapshot description that represents the state of a symbol table.\n\n    The snapshot has a representation based on nested tuples and dicts\n    that makes it easy and fast to find differences.\n\n    Only \"shallow\" state is included in the snapshot -- references to\n    things defined in other modules are represented just by the names of\n    the targets.\n    \"\"\"\n    result: dict[str, SymbolSnapshot] = {}\n    for name, symbol in table.items():\n        node = symbol.node\n        # TODO: cross_ref?\n        fullname = node.fullname if node else None\n        common = (fullname, symbol.kind, symbol.module_public)\n        if isinstance(node, MypyFile):\n            # This is a cross-reference to another module.\n            # If the reference is busted because the other module is missing,\n            # the node will be a \"stale_info\" TypeInfo produced by fixup,\n            # but that doesn't really matter to us here.\n            result[name] = (\"Moduleref\", common)\n        elif isinstance(node, TypeVarExpr):\n            result[name] = (\n                \"TypeVar\",\n                node.variance,\n                [snapshot_type(value) for value in node.values],\n                snapshot_type(node.upper_bound),\n                snapshot_type(node.default),\n            )\n        elif isinstance(node, TypeAlias):\n            result[name] = (\n                \"TypeAlias\",\n                snapshot_types(node.alias_tvars),\n                node.normalized,\n                node.no_args,\n                snapshot_optional_type(node.target),\n            )\n        elif isinstance(node, ParamSpecExpr):\n            result[name] = (\n                \"ParamSpec\",\n                node.variance,\n                snapshot_type(node.upper_bound),\n                snapshot_type(node.default),\n            )\n        elif isinstance(node, TypeVarTupleExpr):\n            result[name] = (\n                \"TypeVarTuple\",\n                node.variance,\n                snapshot_type(node.upper_bound),\n                snapshot_type(node.default),\n            )\n        else:\n            assert symbol.kind != UNBOUND_IMPORTED\n            if node and get_prefix(node.fullname) != name_prefix:\n                # This is a cross-reference to a node defined in another module.\n                # Include the node kind (FuncDef, Decorator, TypeInfo, ...), so that we will\n                # reprocess when a *new* node is created instead of merging an existing one.\n                result[name] = (\"CrossRef\", common, type(node).__name__)\n            else:\n                result[name] = snapshot_definition(node, common)\n    return result\n\n\ndef snapshot_definition(node: SymbolNode | None, common: SymbolSnapshot) -> SymbolSnapshot:\n    \"\"\"Create a snapshot description of a symbol table node.\n\n    The representation is nested tuples and dicts. Only externally\n    visible attributes are included.\n    \"\"\"\n    if isinstance(node, SYMBOL_FUNCBASE_TYPES):\n        # TODO: info\n        if node.type:\n            signature: tuple[object, ...] = snapshot_type(node.type)\n        else:\n            signature = snapshot_untyped_signature(node)\n        impl: FuncDef | None = None\n        if isinstance(node, FuncDef):\n            impl = node\n        elif node.impl:\n            impl = node.impl.func if isinstance(node.impl, Decorator) else node.impl\n        setter_type = None\n        if isinstance(node, OverloadedFuncDef) and node.items:\n            first_item = node.items[0]\n            if isinstance(first_item, Decorator) and first_item.func.is_property:\n                setter_type = snapshot_optional_type(first_item.var.setter_type)\n        is_trivial_body = impl.is_trivial_body if impl else False\n        dataclass_transform_spec = find_dataclass_transform_spec(node)\n\n        deprecated: str | list[str | None] | None = None\n        if isinstance(node, FuncDef):\n            deprecated = node.deprecated\n        elif isinstance(node, OverloadedFuncDef):\n            deprecated = [node.deprecated] + [\n                i.func.deprecated for i in node.items if isinstance(i, Decorator)\n            ]\n\n        return (\n            \"Func\",\n            common,\n            node.is_property,\n            node.is_final,\n            node.is_class,\n            node.is_static,\n            signature,\n            is_trivial_body,\n            dataclass_transform_spec.serialize() if dataclass_transform_spec is not None else None,\n            deprecated,\n            setter_type,  # multi-part properties are stored as OverloadedFuncDef\n        )\n    elif isinstance(node, Var):\n        return (\"Var\", common, snapshot_optional_type(node.type), node.is_final)\n    elif isinstance(node, Decorator):\n        # Note that decorated methods are represented by Decorator instances in\n        # a symbol table since we need to preserve information about the\n        # decorated function (whether it's a class function, for\n        # example). Top-level decorated functions, however, are represented by\n        # the corresponding Var node, since that happens to provide enough\n        # context.\n        return (\n            \"Decorator\",\n            node.is_overload,\n            snapshot_optional_type(node.var.type),\n            snapshot_definition(node.func, common),\n        )\n    elif isinstance(node, TypeInfo):\n        dataclass_transform_spec = node.dataclass_transform_spec\n        if dataclass_transform_spec is None:\n            dataclass_transform_spec = find_dataclass_transform_spec(node)\n\n        attrs = (\n            node.is_abstract,\n            node.is_enum,\n            node.is_protocol,\n            node.fallback_to_any,\n            node.meta_fallback_to_any,\n            node.is_named_tuple,\n            node.is_newtype,\n            # We need this to e.g. trigger metaclass calculation in subclasses.\n            snapshot_optional_type(node.metaclass_type),\n            snapshot_optional_type(node.tuple_type),\n            snapshot_optional_type(node.typeddict_type),\n            [base.fullname for base in node.mro],\n            # Note that the structure of type variables is a part of the external interface,\n            # since creating instances might fail, for example:\n            #     T = TypeVar('T', bound=int)\n            #     class C(Generic[T]):\n            #         ...\n            #     x: C[str] <- this is invalid, and needs to be re-checked if `T` changes.\n            # An alternative would be to create both deps: <...> -> C, and <...> -> <C>,\n            # but this currently seems a bit ad hoc.\n            tuple(snapshot_type(tdef) for tdef in node.defn.type_vars),\n            [snapshot_type(base) for base in node.bases],\n            [snapshot_type(p) for p in node._promote],\n            dataclass_transform_spec.serialize() if dataclass_transform_spec is not None else None,\n            node.deprecated,\n        )\n        prefix = node.fullname\n        symbol_table = snapshot_symbol_table(prefix, node.names)\n        # Special dependency for abstract attribute handling.\n        symbol_table[\"(abstract)\"] = (\"Abstract\", tuple(sorted(node.abstract_attributes)))\n        return (\"TypeInfo\", common, attrs, symbol_table)\n    else:\n        # Other node types are handled elsewhere.\n        assert False, type(node)\n\n\ndef snapshot_type(typ: Type) -> SnapshotItem:\n    \"\"\"Create a snapshot representation of a type using nested tuples.\"\"\"\n    return typ.accept(SnapshotTypeVisitor())\n\n\ndef snapshot_optional_type(typ: Type | None) -> SnapshotItem:\n    if typ:\n        return snapshot_type(typ)\n    else:\n        return (\"<not set>\",)\n\n\ndef snapshot_types(types: Sequence[Type]) -> SnapshotItem:\n    return tuple(snapshot_type(item) for item in types)\n\n\ndef snapshot_simple_type(typ: Type) -> SnapshotItem:\n    return (type(typ).__name__,)\n\n\ndef encode_optional_str(s: str | None) -> str:\n    if s is None:\n        return \"<None>\"\n    else:\n        return s\n\n\nclass SnapshotTypeVisitor(TypeVisitor[SnapshotItem]):\n    \"\"\"Creates a read-only, self-contained snapshot of a type object.\n\n    Properties of a snapshot:\n\n    - Contains (nested) tuples and other immutable primitive objects only.\n    - References to AST nodes are replaced with full names of targets.\n    - Has no references to mutable or non-primitive objects.\n    - Two snapshots represent the same object if and only if they are\n      equal.\n    - Results must be sortable. It's important that tuples have\n      consistent types and can't arbitrarily mix str and None values,\n      for example, since they can't be compared.\n    \"\"\"\n\n    def visit_unbound_type(self, typ: UnboundType) -> SnapshotItem:\n        return (\n            \"UnboundType\",\n            typ.name,\n            typ.optional,\n            typ.empty_tuple_index,\n            snapshot_types(typ.args),\n        )\n\n    def visit_any(self, typ: AnyType) -> SnapshotItem:\n        return snapshot_simple_type(typ)\n\n    def visit_none_type(self, typ: NoneType) -> SnapshotItem:\n        return snapshot_simple_type(typ)\n\n    def visit_uninhabited_type(self, typ: UninhabitedType) -> SnapshotItem:\n        return snapshot_simple_type(typ)\n\n    def visit_erased_type(self, typ: ErasedType) -> SnapshotItem:\n        return snapshot_simple_type(typ)\n\n    def visit_deleted_type(self, typ: DeletedType) -> SnapshotItem:\n        return snapshot_simple_type(typ)\n\n    def visit_instance(self, typ: Instance) -> SnapshotItem:\n        extra_attrs: SnapshotItem\n        if typ.extra_attrs:\n            extra_attrs = (\n                tuple(sorted((k, v.accept(self)) for k, v in typ.extra_attrs.attrs.items())),\n                tuple(typ.extra_attrs.immutable),\n            )\n        else:\n            extra_attrs = ()\n        return (\n            \"Instance\",\n            encode_optional_str(typ.type.fullname),\n            snapshot_types(typ.args),\n            (\"None\",) if typ.last_known_value is None else snapshot_type(typ.last_known_value),\n            extra_attrs,\n        )\n\n    def visit_type_var(self, typ: TypeVarType) -> SnapshotItem:\n        return (\n            \"TypeVar\",\n            typ.name,\n            typ.fullname,\n            typ.id.raw_id,\n            typ.id.meta_level,\n            snapshot_types(typ.values),\n            snapshot_type(typ.upper_bound),\n            snapshot_type(typ.default),\n            typ.variance,\n        )\n\n    def visit_param_spec(self, typ: ParamSpecType) -> SnapshotItem:\n        return (\n            \"ParamSpec\",\n            typ.id.raw_id,\n            typ.id.meta_level,\n            typ.flavor,\n            snapshot_type(typ.upper_bound),\n            snapshot_type(typ.default),\n            snapshot_type(typ.prefix),\n        )\n\n    def visit_type_var_tuple(self, typ: TypeVarTupleType) -> SnapshotItem:\n        return (\n            \"TypeVarTupleType\",\n            typ.id.raw_id,\n            typ.id.meta_level,\n            snapshot_type(typ.upper_bound),\n            snapshot_type(typ.default),\n        )\n\n    def visit_unpack_type(self, typ: UnpackType) -> SnapshotItem:\n        return (\"UnpackType\", snapshot_type(typ.type))\n\n    def visit_parameters(self, typ: Parameters) -> SnapshotItem:\n        return (\n            \"Parameters\",\n            snapshot_types(typ.arg_types),\n            tuple(encode_optional_str(name) for name in typ.arg_names),\n            tuple(k.value for k in typ.arg_kinds),\n        )\n\n    def visit_callable_type(self, typ: CallableType) -> SnapshotItem:\n        if typ.is_generic():\n            typ = self.normalize_callable_variables(typ)\n        return (\n            \"CallableType\",\n            snapshot_types(typ.arg_types),\n            snapshot_type(typ.ret_type),\n            tuple(encode_optional_str(name) for name in typ.arg_names),\n            tuple(k.value for k in typ.arg_kinds),\n            typ.is_type_obj(),\n            typ.is_ellipsis_args,\n            snapshot_types(typ.variables),\n            typ.is_bound,\n        )\n\n    def normalize_callable_variables(self, typ: CallableType) -> CallableType:\n        \"\"\"Normalize all type variable ids to run from -1 to -len(variables).\"\"\"\n        tvs = []\n        tvmap: dict[TypeVarId, Type] = {}\n        for i, v in enumerate(typ.variables):\n            tid = TypeVarId(-1 - i)\n            if isinstance(v, TypeVarType):\n                tv: TypeVarLikeType = v.copy_modified(id=tid)\n            elif isinstance(v, TypeVarTupleType):\n                tv = v.copy_modified(id=tid)\n            else:\n                assert isinstance(v, ParamSpecType)\n                tv = v.copy_modified(id=tid)\n            tvs.append(tv)\n            tvmap[v.id] = tv\n        with state.strict_optional_set(True):\n            return expand_type(typ, tvmap).copy_modified(variables=tvs)\n\n    def visit_tuple_type(self, typ: TupleType) -> SnapshotItem:\n        return (\"TupleType\", snapshot_types(typ.items))\n\n    def visit_typeddict_type(self, typ: TypedDictType) -> SnapshotItem:\n        items = tuple((key, snapshot_type(item_type)) for key, item_type in typ.items.items())\n        required = tuple(sorted(typ.required_keys))\n        readonly = tuple(sorted(typ.readonly_keys))\n        return (\"TypedDictType\", items, required, readonly)\n\n    def visit_literal_type(self, typ: LiteralType) -> SnapshotItem:\n        return (\"LiteralType\", snapshot_type(typ.fallback), typ.value)\n\n    def visit_union_type(self, typ: UnionType) -> SnapshotItem:\n        # Sort and remove duplicates so that we can use equality to test for\n        # equivalent union type snapshots.\n        items = {snapshot_type(item) for item in typ.items}\n        normalized = tuple(sorted(items))\n        return (\"UnionType\", normalized)\n\n    def visit_overloaded(self, typ: Overloaded) -> SnapshotItem:\n        return (\"Overloaded\", snapshot_types(typ.items))\n\n    def visit_partial_type(self, typ: PartialType) -> SnapshotItem:\n        # A partial type is not fully defined, so the result is indeterminate. We shouldn't\n        # get here.\n        raise RuntimeError\n\n    def visit_type_type(self, typ: TypeType) -> SnapshotItem:\n        return (\"TypeType\", snapshot_type(typ.item), typ.is_type_form)\n\n    def visit_type_alias_type(self, typ: TypeAliasType) -> SnapshotItem:\n        assert typ.alias is not None\n        return (\"TypeAliasType\", typ.alias.fullname, snapshot_types(typ.args))\n\n\ndef snapshot_untyped_signature(func: OverloadedFuncDef | FuncItem) -> SymbolSnapshot:\n    \"\"\"Create a snapshot of the signature of a function that has no explicit signature.\n\n    If the arguments to a function without signature change, it must be\n    considered as different. We have this special casing since we don't store\n    the implicit signature anywhere, and we'd rather not construct new\n    Callable objects in this module (the idea is to only read properties of\n    the AST here).\n    \"\"\"\n    if isinstance(func, FuncItem):\n        return (tuple(func.arg_names), tuple(func.arg_kinds))\n    else:\n        result: list[SymbolSnapshot] = []\n        for item in func.items:\n            if isinstance(item, Decorator):\n                if item.var.type:\n                    result.append(snapshot_type(item.var.type))\n                else:\n                    result.append((\"DecoratorWithoutType\",))\n            else:\n                result.append(snapshot_untyped_signature(item))\n        return tuple(result)\n"
  },
  {
    "path": "mypy/server/astmerge.py",
    "content": "\"\"\"Merge a new version of a module AST and symbol table to older versions of those.\n\nWhen the source code of a module has a change in fine-grained incremental mode,\nwe build a new AST from the updated source. However, other parts of the program\nmay have direct references to parts of the old AST (namely, those nodes exposed\nin the module symbol table). The merge operation changes the identities of new\nAST nodes that have a correspondence in the old AST to the old ones so that\nexisting cross-references in other modules will continue to point to the correct\nnodes. Also internal cross-references within the new AST are replaced. AST nodes\nthat aren't externally visible will get new, distinct object identities. This\napplies to most expression and statement nodes, for example.\n\nWe perform this merge operation so that we don't have to update all\nexternal references (which would be slow and fragile) or always perform\ntranslation when looking up references (which would be hard to retrofit).\n\nThe AST merge operation is performed after semantic analysis. Semantic\nanalysis has to deal with potentially multiple aliases to certain AST\nnodes (in particular, MypyFile nodes). Type checking assumes that we\ndon't have multiple variants of a single AST node visible to the type\nchecker.\n\nDiscussion of some notable special cases:\n\n* If a node is replaced with a different kind of node (say, a function is\n  replaced with a class), we don't perform the merge. Fine-grained dependencies\n  will be used to rebind all references to the node.\n\n* If a function is replaced with another function with an identical signature,\n  call sites continue to point to the same object (by identity) and don't need\n  to be reprocessed. Similarly, if a class is replaced with a class that is\n  sufficiently similar (MRO preserved, etc.), class references don't need any\n  processing. A typical incremental update to a file only changes a few\n  externally visible things in a module, and this means that often only few\n  external references need any processing, even if the modified module is large.\n\n* A no-op update of a module should not require any processing outside the\n  module, since all relevant object identities are preserved.\n\n* The AST diff operation (mypy.server.astdiff) and the top-level fine-grained\n  incremental logic (mypy.server.update) handle the cases where the new AST has\n  differences from the old one that may need to be propagated to elsewhere in the\n  program.\n\nSee the main entry point merge_asts for more details.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TypeVar, cast\n\nfrom mypy.nodes import (\n    MDEF,\n    SYMBOL_NODE_EXPRESSION_TYPES,\n    AssertTypeExpr,\n    AssignmentStmt,\n    Block,\n    CallExpr,\n    CastExpr,\n    ClassDef,\n    EnumCallExpr,\n    FuncBase,\n    FuncDef,\n    LambdaExpr,\n    MemberExpr,\n    MypyFile,\n    NamedTupleExpr,\n    NameExpr,\n    NewTypeExpr,\n    OverloadedFuncDef,\n    RefExpr,\n    Statement,\n    SuperExpr,\n    SymbolNode,\n    SymbolTable,\n    TypeAlias,\n    TypedDictExpr,\n    TypeFormExpr,\n    TypeInfo,\n    Var,\n)\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.types import (\n    AnyType,\n    CallableArgument,\n    CallableType,\n    DeletedType,\n    EllipsisType,\n    ErasedType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    PlaceholderType,\n    RawExpressionType,\n    SyntheticTypeVisitor,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeList,\n    TypeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n)\nfrom mypy.typestate import type_state\nfrom mypy.util import get_prefix, replace_object_state\n\n\ndef merge_asts(\n    old: MypyFile, old_symbols: SymbolTable, new: MypyFile, new_symbols: SymbolTable\n) -> None:\n    \"\"\"Merge a new version of a module AST to a previous version.\n\n    The main idea is to preserve the identities of externally visible\n    nodes in the old AST (that have a corresponding node in the new AST).\n    All old node state (outside identity) will come from the new AST.\n\n    When this returns, 'old' will refer to the merged AST, but 'new_symbols'\n    will be the new symbol table. 'new' and 'old_symbols' will no longer be\n    valid.\n    \"\"\"\n    assert new.fullname == old.fullname\n    # Find the mapping from new to old node identities for all nodes\n    # whose identities should be preserved.\n    replacement_map = replacement_map_from_symbol_table(\n        old_symbols, new_symbols, prefix=old.fullname\n    )\n    # Also replace references to the new MypyFile node.\n    replacement_map[new] = old\n    # Perform replacements to everywhere within the new AST (not including symbol\n    # tables).\n    node = replace_nodes_in_ast(new, replacement_map)\n    assert node is old\n    # Also replace AST node references in the *new* symbol table (we'll\n    # continue to use the new symbol table since it has all the new definitions\n    # that have no correspondence in the old AST).\n    replace_nodes_in_symbol_table(new_symbols, replacement_map)\n\n\ndef replacement_map_from_symbol_table(\n    old: SymbolTable, new: SymbolTable, prefix: str\n) -> dict[SymbolNode, SymbolNode]:\n    \"\"\"Create a new-to-old object identity map by comparing two symbol table revisions.\n\n    Both symbol tables must refer to revisions of the same module id. The symbol tables\n    are compared recursively (recursing into nested class symbol tables), but only within\n    the given module prefix. Don't recurse into other modules accessible through the symbol\n    table.\n    \"\"\"\n    replacements: dict[SymbolNode, SymbolNode] = {}\n    for name, node in old.items():\n        if name in new and (\n            node.kind == MDEF or node.node and get_prefix(node.node.fullname) == prefix\n        ):\n            new_node = new[name]\n            if (\n                type(new_node.node) == type(node.node)\n                and new_node.node\n                and node.node\n                and new_node.node.fullname == node.node.fullname\n                and new_node.kind == node.kind\n            ):\n                replacements[new_node.node] = node.node\n                if isinstance(node.node, TypeInfo) and isinstance(new_node.node, TypeInfo):\n                    type_repl = replacement_map_from_symbol_table(\n                        node.node.names, new_node.node.names, prefix\n                    )\n                    replacements.update(type_repl)\n                    if node.node.special_alias and new_node.node.special_alias:\n                        replacements[new_node.node.special_alias] = node.node.special_alias\n    return replacements\n\n\ndef replace_nodes_in_ast(\n    node: SymbolNode, replacements: dict[SymbolNode, SymbolNode]\n) -> SymbolNode:\n    \"\"\"Replace all references to replacement map keys within an AST node, recursively.\n\n    Also replace the *identity* of any nodes that have replacements. Return the\n    *replaced* version of the argument node (which may have a different identity, if\n    it's included in the replacement map).\n    \"\"\"\n    visitor = NodeReplaceVisitor(replacements)\n    node.accept(visitor)\n    return replacements.get(node, node)\n\n\nSN = TypeVar(\"SN\", bound=SymbolNode)\n\n\nclass NodeReplaceVisitor(TraverserVisitor):\n    \"\"\"Transform some nodes to new identities in an AST.\n\n    Only nodes that live in the symbol table may be\n    replaced, which simplifies the implementation some. Also\n    replace all references to the old identities.\n    \"\"\"\n\n    def __init__(self, replacements: dict[SymbolNode, SymbolNode]) -> None:\n        self.replacements = replacements\n\n    def visit_mypy_file(self, node: MypyFile) -> None:\n        node = self.fixup(node)\n        node.defs = self.replace_statements(node.defs)\n        super().visit_mypy_file(node)\n\n    def visit_block(self, node: Block) -> None:\n        node.body = self.replace_statements(node.body)\n        super().visit_block(node)\n\n    def visit_func_def(self, node: FuncDef) -> None:\n        node = self.fixup(node)\n        self.process_base_func(node)\n        super().visit_func_def(node)\n\n    def visit_overloaded_func_def(self, node: OverloadedFuncDef) -> None:\n        self.process_base_func(node)\n        super().visit_overloaded_func_def(node)\n\n    def visit_class_def(self, node: ClassDef) -> None:\n        # TODO additional things?\n        node.info = self.fixup_and_reset_typeinfo(node.info)\n        node.defs.body = self.replace_statements(node.defs.body)\n        info = node.info\n        for tv in node.type_vars:\n            if isinstance(tv, TypeVarType):\n                self.process_type_var_def(tv)\n        if info:\n            if info.is_named_tuple:\n                self.process_synthetic_type_info(info)\n            else:\n                self.process_type_info(info)\n        super().visit_class_def(node)\n\n    def process_base_func(self, node: FuncBase) -> None:\n        self.fixup_type(node.type)\n        node.info = self.fixup(node.info)\n        if node.unanalyzed_type:\n            # Unanalyzed types can have AST node references\n            self.fixup_type(node.unanalyzed_type)\n\n    def process_type_var_def(self, tv: TypeVarType) -> None:\n        for value in tv.values:\n            self.fixup_type(value)\n        self.fixup_type(tv.upper_bound)\n        self.fixup_type(tv.default)\n\n    def process_param_spec_def(self, tv: ParamSpecType) -> None:\n        self.fixup_type(tv.upper_bound)\n        self.fixup_type(tv.default)\n\n    def process_type_var_tuple_def(self, tv: TypeVarTupleType) -> None:\n        self.fixup_type(tv.upper_bound)\n        self.fixup_type(tv.default)\n\n    def visit_assignment_stmt(self, node: AssignmentStmt) -> None:\n        self.fixup_type(node.type)\n        super().visit_assignment_stmt(node)\n\n    # Expressions\n\n    def visit_name_expr(self, node: NameExpr) -> None:\n        self.visit_ref_expr(node)\n\n    def visit_member_expr(self, node: MemberExpr) -> None:\n        if node.def_var:\n            node.def_var = self.fixup(node.def_var)\n        self.visit_ref_expr(node)\n        super().visit_member_expr(node)\n\n    def visit_ref_expr(self, node: RefExpr) -> None:\n        if node.node is not None:\n            node.node = self.fixup(node.node)\n            if isinstance(node.node, Var):\n                # The Var node may be an orphan and won't otherwise be processed.\n                node.node.accept(self)\n\n    def visit_namedtuple_expr(self, node: NamedTupleExpr) -> None:\n        super().visit_namedtuple_expr(node)\n        node.info = self.fixup_and_reset_typeinfo(node.info)\n        self.process_synthetic_type_info(node.info)\n\n    def visit_cast_expr(self, node: CastExpr) -> None:\n        super().visit_cast_expr(node)\n        self.fixup_type(node.type)\n\n    def visit_type_form_expr(self, node: TypeFormExpr) -> None:\n        super().visit_type_form_expr(node)\n        self.fixup_type(node.type)\n\n    def visit_assert_type_expr(self, node: AssertTypeExpr) -> None:\n        super().visit_assert_type_expr(node)\n        self.fixup_type(node.type)\n\n    def visit_super_expr(self, node: SuperExpr) -> None:\n        super().visit_super_expr(node)\n        if node.info is not None:\n            node.info = self.fixup(node.info)\n\n    def visit_call_expr(self, node: CallExpr) -> None:\n        super().visit_call_expr(node)\n        if isinstance(node.analyzed, SYMBOL_NODE_EXPRESSION_TYPES):\n            node.analyzed = self.fixup(node.analyzed)\n\n    def visit_newtype_expr(self, node: NewTypeExpr) -> None:\n        if node.info:\n            node.info = self.fixup_and_reset_typeinfo(node.info)\n            self.process_synthetic_type_info(node.info)\n        self.fixup_type(node.old_type)\n        super().visit_newtype_expr(node)\n\n    def visit_lambda_expr(self, node: LambdaExpr) -> None:\n        node.info = self.fixup(node.info)\n        super().visit_lambda_expr(node)\n\n    def visit_typeddict_expr(self, node: TypedDictExpr) -> None:\n        super().visit_typeddict_expr(node)\n        node.info = self.fixup_and_reset_typeinfo(node.info)\n        self.process_synthetic_type_info(node.info)\n\n    def visit_enum_call_expr(self, node: EnumCallExpr) -> None:\n        node.info = self.fixup_and_reset_typeinfo(node.info)\n        self.process_synthetic_type_info(node.info)\n        super().visit_enum_call_expr(node)\n\n    # Others\n\n    def visit_var(self, node: Var) -> None:\n        node.info = self.fixup(node.info)\n        self.fixup_type(node.type)\n        self.fixup_type(node.setter_type)\n        super().visit_var(node)\n\n    def visit_type_alias(self, node: TypeAlias) -> None:\n        self.fixup_type(node.target)\n        for v in node.alias_tvars:\n            self.fixup_type(v)\n        super().visit_type_alias(node)\n\n    # Helpers\n\n    def fixup(self, node: SN) -> SN:\n        if node in self.replacements:\n            new = self.replacements[node]\n            if isinstance(node, TypeInfo) and isinstance(new, TypeInfo):\n                # Special case: special_alias is not exposed in symbol tables, but may appear\n                # in external types (e.g. named tuples), so we need to update it manually.\n                replace_object_state(new.special_alias, node.special_alias)\n            replace_object_state(new, node, skip_slots=_get_ignored_slots(new))\n            return cast(SN, new)\n        return node\n\n    def fixup_and_reset_typeinfo(self, node: TypeInfo) -> TypeInfo:\n        \"\"\"Fix-up type info and reset subtype caches.\n\n        This needs to be called at least once per each merged TypeInfo, as otherwise we\n        may leak stale caches.\n        \"\"\"\n        if node in self.replacements:\n            # The subclass relationships may change, so reset all caches relevant to the\n            # old MRO.\n            new = self.replacements[node]\n            assert isinstance(new, TypeInfo)\n            type_state.reset_all_subtype_caches_for(new)\n        return self.fixup(node)\n\n    def fixup_type(self, typ: Type | None) -> None:\n        if typ is not None:\n            typ.accept(TypeReplaceVisitor(self.replacements))\n\n    def process_type_info(self, info: TypeInfo | None) -> None:\n        if info is None:\n            return\n        self.fixup_type(info.declared_metaclass)\n        self.fixup_type(info.metaclass_type)\n        for target in info._promote:\n            self.fixup_type(target)\n        self.fixup_type(info.tuple_type)\n        self.fixup_type(info.typeddict_type)\n        if info.special_alias:\n            self.fixup_type(info.special_alias.target)\n        info.defn.info = self.fixup(info)\n        replace_nodes_in_symbol_table(info.names, self.replacements)\n        for i, item in enumerate(info.mro):\n            info.mro[i] = self.fixup(info.mro[i])\n        for i, base in enumerate(info.bases):\n            self.fixup_type(info.bases[i])\n\n    def process_synthetic_type_info(self, info: TypeInfo) -> None:\n        # Synthetic types (types not created using a class statement) don't\n        # have bodies in the AST so we need to iterate over their symbol\n        # tables separately, unlike normal classes.\n        self.process_type_info(info)\n        for node in info.names.values():\n            if node.node:\n                node.node.accept(self)\n\n    def replace_statements(self, nodes: list[Statement]) -> list[Statement]:\n        result = []\n        for node in nodes:\n            if isinstance(node, SymbolNode):\n                node = self.fixup(node)\n            result.append(node)\n        return result\n\n\nclass TypeReplaceVisitor(SyntheticTypeVisitor[None]):\n    \"\"\"Similar to NodeReplaceVisitor, but for type objects.\n\n    Note: this visitor may sometimes visit unanalyzed types\n    such as 'UnboundType' and 'RawExpressionType' For example, see\n    NodeReplaceVisitor.process_base_func.\n    \"\"\"\n\n    def __init__(self, replacements: dict[SymbolNode, SymbolNode]) -> None:\n        self.replacements = replacements\n\n    def visit_instance(self, typ: Instance) -> None:\n        typ.type = self.fixup(typ.type)\n        for arg in typ.args:\n            arg.accept(self)\n        if typ.last_known_value:\n            typ.last_known_value.accept(self)\n\n    def visit_type_alias_type(self, typ: TypeAliasType) -> None:\n        assert typ.alias is not None\n        typ.alias = self.fixup(typ.alias)\n        for arg in typ.args:\n            arg.accept(self)\n\n    def visit_any(self, typ: AnyType) -> None:\n        pass\n\n    def visit_none_type(self, typ: NoneType) -> None:\n        pass\n\n    def visit_callable_type(self, typ: CallableType) -> None:\n        for arg in typ.arg_types:\n            arg.accept(self)\n        typ.ret_type.accept(self)\n        if typ.definition:\n            # No need to fixup since this is just a cross-reference.\n            typ.definition = self.replacements.get(typ.definition, typ.definition)\n        # Fallback can be None for callable types that haven't been semantically analyzed.\n        if typ.fallback is not None:\n            typ.fallback.accept(self)\n        for tv in typ.variables:\n            if isinstance(tv, TypeVarType):\n                tv.upper_bound.accept(self)\n                for value in tv.values:\n                    value.accept(self)\n\n    def visit_overloaded(self, t: Overloaded) -> None:\n        for item in t.items:\n            item.accept(self)\n        # Fallback can be None for overloaded types that haven't been semantically analyzed.\n        if t.fallback is not None:\n            t.fallback.accept(self)\n\n    def visit_erased_type(self, t: ErasedType) -> None:\n        # This type should exist only temporarily during type inference\n        raise RuntimeError(\"Cannot handle erased type\")\n\n    def visit_deleted_type(self, typ: DeletedType) -> None:\n        pass\n\n    def visit_partial_type(self, typ: PartialType) -> None:\n        raise RuntimeError(\"Cannot handle partial type\")\n\n    def visit_tuple_type(self, typ: TupleType) -> None:\n        for item in typ.items:\n            item.accept(self)\n        # Fallback can be None for implicit tuple types that haven't been semantically analyzed.\n        if typ.partial_fallback is not None:\n            typ.partial_fallback.accept(self)\n\n    def visit_type_type(self, typ: TypeType) -> None:\n        typ.item.accept(self)\n\n    def visit_type_var(self, typ: TypeVarType) -> None:\n        typ.upper_bound.accept(self)\n        typ.default.accept(self)\n        for value in typ.values:\n            value.accept(self)\n\n    def visit_param_spec(self, typ: ParamSpecType) -> None:\n        typ.upper_bound.accept(self)\n        typ.default.accept(self)\n        typ.prefix.accept(self)\n\n    def visit_type_var_tuple(self, typ: TypeVarTupleType) -> None:\n        typ.upper_bound.accept(self)\n        typ.default.accept(self)\n\n    def visit_unpack_type(self, typ: UnpackType) -> None:\n        typ.type.accept(self)\n\n    def visit_parameters(self, typ: Parameters) -> None:\n        for arg in typ.arg_types:\n            arg.accept(self)\n\n    def visit_typeddict_type(self, typ: TypedDictType) -> None:\n        for value_type in typ.items.values():\n            value_type.accept(self)\n        typ.fallback.accept(self)\n\n    def visit_raw_expression_type(self, t: RawExpressionType) -> None:\n        pass\n\n    def visit_literal_type(self, typ: LiteralType) -> None:\n        typ.fallback.accept(self)\n\n    def visit_unbound_type(self, typ: UnboundType) -> None:\n        for arg in typ.args:\n            arg.accept(self)\n\n    def visit_type_list(self, typ: TypeList) -> None:\n        for item in typ.items:\n            item.accept(self)\n\n    def visit_callable_argument(self, typ: CallableArgument) -> None:\n        typ.typ.accept(self)\n\n    def visit_ellipsis_type(self, typ: EllipsisType) -> None:\n        pass\n\n    def visit_uninhabited_type(self, typ: UninhabitedType) -> None:\n        pass\n\n    def visit_union_type(self, typ: UnionType) -> None:\n        for item in typ.items:\n            item.accept(self)\n\n    def visit_placeholder_type(self, t: PlaceholderType) -> None:\n        for item in t.args:\n            item.accept(self)\n\n    # Helpers\n\n    def fixup(self, node: SN) -> SN:\n        if node in self.replacements:\n            new = self.replacements[node]\n            return cast(SN, new)\n        return node\n\n\ndef replace_nodes_in_symbol_table(\n    symbols: SymbolTable, replacements: dict[SymbolNode, SymbolNode]\n) -> None:\n    for node in symbols.values():\n        if node.node:\n            if node.node in replacements:\n                new = replacements[node.node]\n                old = node.node\n                replace_object_state(new, old, skip_slots=_get_ignored_slots(new))\n                node.node = new\n            if isinstance(node.node, (Var, TypeAlias)):\n                # Handle them here just in case these aren't exposed through the AST.\n                node.node.accept(NodeReplaceVisitor(replacements))\n\n\ndef _get_ignored_slots(node: SymbolNode) -> tuple[str, ...]:\n    if isinstance(node, OverloadedFuncDef):\n        return (\"setter\",)\n    if isinstance(node, TypeInfo):\n        return (\"special_alias\",)\n    return ()\n"
  },
  {
    "path": "mypy/server/aststrip.py",
    "content": "\"\"\"Strip/reset AST in-place to match state after semantic analyzer pre-analysis.\n\nFine-grained incremental mode reruns semantic analysis main pass\nand type checking for *existing* AST nodes (targets) when changes are\npropagated using fine-grained dependencies.  AST nodes attributes are\nsometimes changed during semantic analysis main pass, and running\nsemantic analysis again on those nodes would produce incorrect\nresults, since this pass isn't idempotent. This pass resets AST\nnodes to reflect the state after semantic pre-analysis, so that we\ncan rerun semantic analysis.\n(The above is in contrast to behavior with modules that have source code\nchanges, for which we re-parse the entire module and reconstruct a fresh\nAST. No stripping is required in this case. Both modes of operation should\nhave the same outcome.)\nNotes:\n* This is currently pretty fragile, as we must carefully undo whatever\n  changes can be made in semantic analysis main pass, including changes\n  to symbol tables.\n* We reuse existing AST nodes because it makes it relatively straightforward\n  to reprocess only a single target within a module efficiently. If there\n  was a way to parse a single target within a file, in time proportional to\n  the size of the target, we'd rather create fresh AST nodes than strip them.\n  (This is possible only in Python 3.8+)\n* Currently we don't actually reset all changes, but only those known to affect\n  non-idempotent semantic analysis behavior.\n  TODO: It would be more principled and less fragile to reset everything\n      changed in semantic analysis main pass and later.\n* Reprocessing may recreate AST nodes (such as Var nodes, and TypeInfo nodes\n  created with assignment statements) that will get different identities from\n  the original AST. Thus running an AST merge is necessary after stripping,\n  even though some identities are preserved.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager, nullcontext\n\nfrom mypy.nodes import (\n    CLASSDEF_NO_INFO,\n    AssignmentStmt,\n    Block,\n    CallExpr,\n    ClassDef,\n    Decorator,\n    ForStmt,\n    FuncDef,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    ListExpr,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    Node,\n    OpExpr,\n    OverloadedFuncDef,\n    RefExpr,\n    SplittingVisitor,\n    StarExpr,\n    SuperExpr,\n    TupleExpr,\n    TypeInfo,\n)\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.types import CallableType\nfrom mypy.typestate import type_state\n\n\ndef strip_target(node: MypyFile | FuncDef | OverloadedFuncDef) -> None:\n    \"\"\"Reset a fine-grained incremental target to state before semantic analysis.\n\n    Args:\n        node: node to strip\n    \"\"\"\n    visitor = NodeStripVisitor()\n    if isinstance(node, MypyFile):\n        visitor.strip_file_top_level(node)\n    else:\n        node.accept(visitor)\n\n\nclass NodeStripVisitor(TraverserVisitor, SplittingVisitor):\n    def __init__(self) -> None:\n        # The current active class.\n        self.type: TypeInfo | None = None\n        # This is True at class scope, but not in methods.\n        self.is_class_body = False\n        self.recurse_into_functions = True\n\n    def strip_file_top_level(self, file_node: MypyFile) -> None:\n        \"\"\"Strip a module top-level (don't recursive into functions).\"\"\"\n        self.recurse_into_functions = False\n        file_node.plugin_deps.clear()\n        file_node.accept(self)\n        for name in file_node.names.copy():\n            # TODO: this is a hot fix, we should delete all names,\n            # see https://github.com/python/mypy/issues/6422.\n            if \"@\" not in name:\n                del file_node.names[name]\n\n    def visit_block(self, b: Block) -> None:\n        if b.is_unreachable:\n            return\n        super().visit_block(b)\n\n    def visit_class_def(self, node: ClassDef) -> None:\n        \"\"\"Strip class body and type info, but don't strip methods.\"\"\"\n        # We need to delete any entries that were generated by plugins,\n        # since they will get regenerated.\n        to_delete = {v.node for v in node.info.names.values() if v.plugin_generated}\n        node.type_vars = []\n        node.base_type_exprs.extend(node.removed_base_type_exprs)\n        node.removed_base_type_exprs = []\n        node.defs.body = [\n            s\n            for s in node.defs.body\n            if s not in to_delete  # type: ignore[comparison-overlap, redundant-expr]\n        ]\n        with self.enter_class(node.info):\n            super().visit_class_def(node)\n        node.defs.body.extend(node.removed_statements)\n        node.removed_statements = []\n        type_state.reset_subtype_caches_for(node.info)\n        # Kill the TypeInfo, since there is none before semantic analysis.\n        node.info = CLASSDEF_NO_INFO\n        node.analyzed = None\n\n    def visit_func_def(self, node: FuncDef) -> None:\n        if not self.recurse_into_functions and not node.def_or_infer_vars:\n            return\n        node.expanded = []\n        node.type = node.unanalyzed_type\n        if node.type:\n            # Type variable binder binds type variables before the type is analyzed,\n            # this causes unanalyzed_type to be modified in place. We needed to revert this\n            # in order to get the state exactly as it was before semantic analysis.\n            # See also #4814.\n            assert isinstance(node.type, CallableType)\n            node.type.variables = ()\n        with (\n            self.enter_method(node.info) if node.info else nullcontext(),\n            self.set_recurse_into_functions(),\n        ):\n            super().visit_func_def(node)\n\n    def visit_decorator(self, node: Decorator) -> None:\n        node.var.type = None\n        for expr in node.decorators:\n            expr.accept(self)\n        if self.recurse_into_functions or node.func.def_or_infer_vars:\n            with self.set_recurse_into_functions():\n                node.func.accept(self)\n        else:\n            # Only touch the final status if we re-process\n            # the top level, since decorators are processed there.\n            node.var.is_final = False\n            node.func.is_final = False\n\n    def visit_overloaded_func_def(self, node: OverloadedFuncDef) -> None:\n        if not self.recurse_into_functions and not node.def_or_infer_vars:\n            return\n        # Revert change made during semantic analysis main pass.\n        node.items = node.unanalyzed_items.copy()\n        node.impl = None\n        node.is_final = False\n        with self.set_recurse_into_functions():\n            super().visit_overloaded_func_def(node)\n\n    def visit_assignment_stmt(self, node: AssignmentStmt) -> None:\n        node.type = node.unanalyzed_type\n        node.is_final_def = False\n        node.is_alias_def = False\n        if self.type and not self.is_class_body:\n            for lvalue in node.lvalues:\n                # Revert assignments made via self attributes.\n                self.process_lvalue_in_method(lvalue)\n        super().visit_assignment_stmt(node)\n\n    def visit_import_from(self, node: ImportFrom) -> None:\n        node.assignments = []\n\n    def visit_import_all(self, node: ImportAll) -> None:\n        node.assignments = []\n\n    def visit_for_stmt(self, node: ForStmt) -> None:\n        node.index_type = node.unanalyzed_index_type\n        node.inferred_item_type = None\n        node.inferred_iterator_type = None\n        super().visit_for_stmt(node)\n\n    def visit_name_expr(self, node: NameExpr) -> None:\n        self.strip_ref_expr(node)\n\n    def visit_member_expr(self, node: MemberExpr) -> None:\n        self.strip_ref_expr(node)\n        super().visit_member_expr(node)\n\n    def visit_index_expr(self, node: IndexExpr) -> None:\n        node.analyzed = None  # May have been an alias or type application.\n        super().visit_index_expr(node)\n\n    def visit_op_expr(self, node: OpExpr) -> None:\n        node.analyzed = None  # May have been an alias\n        super().visit_op_expr(node)\n\n    def strip_ref_expr(self, node: RefExpr) -> None:\n        node.kind = None\n        node.node = None\n        node.fullname = \"\"\n        node.is_new_def = False\n        node.is_inferred_def = False\n\n    def visit_call_expr(self, node: CallExpr) -> None:\n        node.analyzed = None\n        super().visit_call_expr(node)\n\n    def visit_super_expr(self, node: SuperExpr) -> None:\n        node.info = None\n        super().visit_super_expr(node)\n\n    def process_lvalue_in_method(self, lvalue: Node) -> None:\n        if isinstance(lvalue, MemberExpr):\n            if lvalue.is_new_def:\n                # Remove defined attribute from the class symbol table. If is_new_def is\n                # true for a MemberExpr, we know that it must be an assignment through\n                # self, since only those can define new attributes.\n                assert self.type is not None\n                if lvalue.name in self.type.names:\n                    del self.type.names[lvalue.name]\n        elif isinstance(lvalue, (TupleExpr, ListExpr)):\n            for item in lvalue.items:\n                self.process_lvalue_in_method(item)\n        elif isinstance(lvalue, StarExpr):\n            self.process_lvalue_in_method(lvalue.expr)\n\n    @contextmanager\n    def enter_class(self, info: TypeInfo) -> Iterator[None]:\n        old_type = self.type\n        old_is_class_body = self.is_class_body\n        self.type = info\n        self.is_class_body = True\n        yield\n        self.type = old_type\n        self.is_class_body = old_is_class_body\n\n    @contextmanager\n    def enter_method(self, info: TypeInfo) -> Iterator[None]:\n        old_type = self.type\n        old_is_class_body = self.is_class_body\n        self.type = info\n        self.is_class_body = False\n        yield\n        self.type = old_type\n        self.is_class_body = old_is_class_body\n"
  },
  {
    "path": "mypy/server/deps.py",
    "content": "\"\"\"Generate fine-grained dependencies for AST nodes, for use in the daemon mode.\n\nDependencies are stored in a map from *triggers* to *sets of affected locations*.\n\nA trigger is a string that represents a program property that has changed, such\nas the signature of a specific function. Triggers are written as '<...>' (angle\nbrackets). When a program property changes, we determine the relevant trigger(s)\nand all affected locations. The latter are stale and will have to be reprocessed.\n\nAn affected location is a string than can refer to a *target* (a non-nested\nfunction or method, or a module top level), a class, or a trigger (for\nrecursively triggering other triggers).\n\nHere's an example representation of a simple dependency map (in format\n\"<trigger> -> locations\"):\n\n  <m.A.g> -> m.f\n  <m.A> -> <m.f>, m.A, m.f\n\nAssuming 'A' is a class, this means that\n\n1) if a property of 'm.A.g', such as the signature, is changed, we need\n   to process target (function) 'm.f'\n\n2) if the MRO or other significant property of class 'm.A' changes, we\n   need to process target 'm.f', the entire class 'm.A', and locations\n   triggered by trigger '<m.f>' (this explanation is a bit simplified;\n   see below for more details).\n\nThe triggers to fire are determined using mypy.server.astdiff.\n\nExamples of triggers:\n\n* '<mod.x>' represents a module attribute/function/class. If any externally\n  visible property of 'x' changes, this gets fired. For changes within\n  classes, only \"big\" changes cause the class to be triggered (such as a\n  change in MRO). Smaller changes, such as changes to some attributes, don't\n  trigger the entire class.\n* '<mod.Cls.x>' represents the type and kind of attribute/method 'x' of\n  class 'mod.Cls'. This can also refer to an attribute inherited from a\n  base class (relevant if it's accessed through a value of type 'Cls'\n  instead of the base class type).\n* '<package.mod>' represents the existence of module 'package.mod'. This\n  gets triggered if 'package.mod' is created or deleted, or if it gets\n  changed into something other than a module.\n\nExamples of locations:\n\n* 'mod' is the top level of module 'mod' (doesn't include any function bodies,\n  but includes class bodies not nested within a function).\n* 'mod.f' is function 'f' in module 'mod' (module-level variables aren't separate\n  locations but are included in the module top level). Functions also include\n  any nested functions and classes -- such nested definitions aren't separate\n  locations, for simplicity of implementation.\n* 'mod.Cls.f' is method 'f' of 'mod.Cls'. Non-method attributes aren't locations.\n* 'mod.Cls' represents each method in class 'mod.Cls' + the top-level of the\n  module 'mod'. (To simplify the implementation, there is no location that only\n  includes the body of a class without the entire surrounding module top level.)\n* Trigger '<...>' as a location is an indirect way of referring to all\n  locations triggered by the trigger. These indirect locations keep the\n  dependency map smaller and easier to manage.\n\nTriggers can be triggered by program changes such as these:\n\n* Addition or deletion of an attribute (or module).\n* Change of the kind of thing a name represents (such as a change from a function\n  to a class).\n* Change of the static type of a name.\n\nChanges in the body of a function that aren't reflected in the signature don't\ncause the function to be triggered. More generally, we trigger only on changes\nthat may affect type checking results outside the module that contains the\nchange.\n\nWe don't generate dependencies from builtins and certain other stdlib modules,\nsince these change very rarely, and they would just increase the size of the\ndependency map significantly without significant benefit.\n\nTest cases for this module live in 'test-data/unit/deps*.test'.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\n\nfrom mypy.nodes import (\n    GDEF,\n    LDEF,\n    MDEF,\n    SYMBOL_FUNCBASE_TYPES,\n    AssertTypeExpr,\n    AssignmentStmt,\n    AwaitExpr,\n    Block,\n    CallExpr,\n    CastExpr,\n    ClassDef,\n    ComparisonExpr,\n    Decorator,\n    DelStmt,\n    DictionaryComprehension,\n    EnumCallExpr,\n    Expression,\n    ForStmt,\n    FuncBase,\n    FuncDef,\n    GeneratorExpr,\n    Import,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    MemberExpr,\n    MypyFile,\n    NamedTupleExpr,\n    NameExpr,\n    NewTypeExpr,\n    Node,\n    OperatorAssignmentStmt,\n    OpExpr,\n    OverloadedFuncDef,\n    RefExpr,\n    StarExpr,\n    SuperExpr,\n    TupleExpr,\n    TypeAliasExpr,\n    TypeApplication,\n    TypedDictExpr,\n    TypeFormExpr,\n    TypeInfo,\n    TypeVarExpr,\n    UnaryExpr,\n    Var,\n    WithStmt,\n    YieldFromExpr,\n)\nfrom mypy.operators import (\n    op_methods,\n    ops_with_inplace_method,\n    reverse_op_methods,\n    unary_op_methods,\n)\nfrom mypy.options import Options\nfrom mypy.scope import Scope\nfrom mypy.server.trigger import make_trigger, make_wildcard_trigger\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.typeops import bind_self\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeType,\n    TypeVarTupleType,\n    TypeVarType,\n    TypeVisitor,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    get_proper_type,\n)\nfrom mypy.typestate import type_state\nfrom mypy.util import correct_relative_import\n\n\ndef get_dependencies(\n    target: MypyFile,\n    type_map: dict[Expression, Type],\n    python_version: tuple[int, int],\n    options: Options,\n) -> dict[str, set[str]]:\n    \"\"\"Get all dependencies of a node, recursively.\"\"\"\n    visitor = DependencyVisitor(type_map, python_version, target.alias_deps, options)\n    target.accept(visitor)\n    return visitor.map\n\n\ndef get_dependencies_of_target(\n    module_id: str,\n    module_tree: MypyFile,\n    target: Node,\n    type_map: dict[Expression, Type],\n    python_version: tuple[int, int],\n) -> dict[str, set[str]]:\n    \"\"\"Get dependencies of a target -- don't recursive into nested targets.\"\"\"\n    # TODO: Add tests for this function.\n    visitor = DependencyVisitor(type_map, python_version, module_tree.alias_deps)\n    with visitor.scope.module_scope(module_id):\n        if isinstance(target, MypyFile):\n            # Only get dependencies of the top-level of the module. Don't recurse into\n            # functions.\n            for defn in target.defs:\n                # TODO: Recurse into top-level statements and class bodies but skip functions.\n                if not isinstance(defn, (ClassDef, Decorator, FuncDef, OverloadedFuncDef)):\n                    defn.accept(visitor)\n        elif isinstance(target, FuncBase) and target.info:\n            # It's a method.\n            # TODO: Methods in nested classes.\n            with visitor.scope.class_scope(target.info):\n                target.accept(visitor)\n        else:\n            target.accept(visitor)\n    return visitor.map\n\n\nclass DependencyVisitor(TraverserVisitor):\n    def __init__(\n        self,\n        type_map: dict[Expression, Type],\n        python_version: tuple[int, int],\n        alias_deps: defaultdict[str, set[str]],\n        options: Options | None = None,\n    ) -> None:\n        self.scope = Scope()\n        self.type_map = type_map\n        # This attribute holds a mapping from target to names of type aliases\n        # it depends on. These need to be processed specially, since they may\n        # appear in expanded form in symbol tables, because of a get_proper_type()\n        # somewhere. For example, after:\n        #    A = int\n        #    x: A\n        # the module symbol table will just have a Var `x` with type `int`,\n        # and the dependency of `x` on `A` is lost. Therefore, the alias dependencies\n        # are preserved at alias expansion points in `semanal.py`, stored as an attribute\n        # on MypyFile, and then passed here.\n        # TODO: fine-grained is more susceptible to this partially because we are reckless\n        # about get_proper_type() in *this specific file*.\n        self.alias_deps = alias_deps\n        self.map: dict[str, set[str]] = {}\n        self.is_class = False\n        self.is_package_init_file = False\n        self.options = options\n\n    def visit_mypy_file(self, o: MypyFile) -> None:\n        with self.scope.module_scope(o.fullname):\n            self.is_package_init_file = o.is_package_init_file()\n            self.add_type_alias_deps(self.scope.current_target())\n            for trigger, targets in o.plugin_deps.items():\n                self.map.setdefault(trigger, set()).update(targets)\n            super().visit_mypy_file(o)\n\n    def visit_func_def(self, o: FuncDef) -> None:\n        with self.scope.function_scope(o):\n            target = self.scope.current_target()\n            if o.type:\n                if self.is_class and isinstance(o.type, FunctionLike):\n                    signature: Type = bind_self(o.type)\n                else:\n                    signature = o.type\n                for trigger in self.get_type_triggers(signature):\n                    self.add_dependency(trigger)\n                    self.add_dependency(trigger, target=make_trigger(target))\n            if o.info:\n                for base in non_trivial_bases(o.info):\n                    # Base class __init__/__new__ doesn't generate a logical\n                    # dependency since the override can be incompatible.\n                    if not self.use_logical_deps() or o.name not in (\"__init__\", \"__new__\"):\n                        self.add_dependency(make_trigger(base.fullname + \".\" + o.name))\n            self.add_type_alias_deps(self.scope.current_target())\n            super().visit_func_def(o)\n            variants = set(o.expanded) - {o}\n            for ex in variants:\n                if isinstance(ex, FuncDef):\n                    super().visit_func_def(ex)\n\n    def visit_decorator(self, o: Decorator) -> None:\n        if not self.use_logical_deps():\n            # We don't need to recheck outer scope for an overload, only overload itself.\n            # Also if any decorator is nested, it is not externally visible, so we don't need to\n            # generate dependency.\n            if not o.func.is_overload and self.scope.current_function_name() is None:\n                self.add_dependency(make_trigger(o.func.fullname))\n        else:\n            # Add logical dependencies from decorators to the function. For example,\n            # if we have\n            #     @dec\n            #     def func(): ...\n            # then if `dec` is unannotated, then it will \"spoil\" `func` and consequently\n            # all call sites, making them all `Any`.\n            for d in o.decorators:\n                tname: str | None = None\n                if isinstance(d, RefExpr) and d.fullname:\n                    tname = d.fullname\n                if isinstance(d, CallExpr) and isinstance(d.callee, RefExpr) and d.callee.fullname:\n                    tname = d.callee.fullname\n                if tname is not None:\n                    self.add_dependency(make_trigger(tname), make_trigger(o.func.fullname))\n        super().visit_decorator(o)\n\n    def visit_class_def(self, o: ClassDef) -> None:\n        with self.scope.class_scope(o.info):\n            target = self.scope.current_full_target()\n            self.add_dependency(make_trigger(target), target)\n            old_is_class = self.is_class\n            self.is_class = True\n            # Add dependencies to type variables of a generic class.\n            for tv in o.type_vars:\n                self.add_dependency(make_trigger(tv.fullname), target)\n            self.process_type_info(o.info)\n            super().visit_class_def(o)\n            self.is_class = old_is_class\n\n    def visit_newtype_expr(self, o: NewTypeExpr) -> None:\n        if o.info:\n            with self.scope.class_scope(o.info):\n                self.process_type_info(o.info)\n\n    def process_type_info(self, info: TypeInfo) -> None:\n        target = self.scope.current_full_target()\n        for base in info.bases:\n            self.add_type_dependencies(base, target=target)\n        if info.tuple_type:\n            self.add_type_dependencies(info.tuple_type, target=make_trigger(target))\n        if info.typeddict_type:\n            self.add_type_dependencies(info.typeddict_type, target=make_trigger(target))\n        if info.declared_metaclass:\n            self.add_type_dependencies(info.declared_metaclass, target=make_trigger(target))\n        if info.is_protocol:\n            for base_info in info.mro[:-1]:\n                # We add dependencies from whole MRO to cover explicit subprotocols.\n                # For example:\n                #\n                #     class Super(Protocol):\n                #         x: int\n                #     class Sub(Super, Protocol):\n                #         y: int\n                #\n                # In this example we add <Super[wildcard]> -> <Sub>, to invalidate Sub if\n                # a new member is added to Super.\n                self.add_dependency(\n                    make_wildcard_trigger(base_info.fullname), target=make_trigger(target)\n                )\n                # More protocol dependencies are collected in type_state._snapshot_protocol_deps\n                # after a full run or update is finished.\n\n        self.add_type_alias_deps(self.scope.current_target())\n        for name, node in info.names.items():\n            if isinstance(node.node, Var):\n                # Recheck Liskov if needed, self definitions are checked in the defining method\n                if node.node.is_initialized_in_class and has_user_bases(info):\n                    self.add_dependency(make_trigger(info.fullname + \".\" + name))\n                for base_info in non_trivial_bases(info):\n                    # If the type of an attribute changes in a base class, we make references\n                    # to the attribute in the subclass stale.\n                    self.add_dependency(\n                        make_trigger(base_info.fullname + \".\" + name),\n                        target=make_trigger(info.fullname + \".\" + name),\n                    )\n        for base_info in non_trivial_bases(info):\n            for name, node in base_info.names.items():\n                if self.use_logical_deps():\n                    # Skip logical dependency if an attribute is not overridden. For example,\n                    # in case of:\n                    #     class Base:\n                    #         x = 1\n                    #         y = 2\n                    #     class Sub(Base):\n                    #         x = 3\n                    # we skip <Base.y> -> <Child.y>, because even if `y` is unannotated it\n                    # doesn't affect precision of Liskov checking.\n                    if name not in info.names:\n                        continue\n                    # __init__ and __new__ can be overridden with different signatures, so no\n                    # logical dependency.\n                    if name in (\"__init__\", \"__new__\"):\n                        continue\n                self.add_dependency(\n                    make_trigger(base_info.fullname + \".\" + name),\n                    target=make_trigger(info.fullname + \".\" + name),\n                )\n            if not self.use_logical_deps():\n                # These dependencies are only useful for propagating changes --\n                # they aren't logical dependencies since __init__ and __new__ can be\n                # overridden with a different signature.\n                self.add_dependency(\n                    make_trigger(base_info.fullname + \".__init__\"),\n                    target=make_trigger(info.fullname + \".__init__\"),\n                )\n                self.add_dependency(\n                    make_trigger(base_info.fullname + \".__new__\"),\n                    target=make_trigger(info.fullname + \".__new__\"),\n                )\n                # If the set of abstract attributes change, this may invalidate class\n                # instantiation, or change the generated error message, since Python checks\n                # class abstract status when creating an instance.\n                self.add_dependency(\n                    make_trigger(base_info.fullname + \".(abstract)\"),\n                    target=make_trigger(info.fullname + \".__init__\"),\n                )\n                # If the base class abstract attributes change, subclass abstract\n                # attributes need to be recalculated.\n                self.add_dependency(make_trigger(base_info.fullname + \".(abstract)\"))\n\n    def visit_import(self, o: Import) -> None:\n        for id, as_id in o.ids:\n            self.add_dependency(make_trigger(id), self.scope.current_target())\n\n    def visit_import_from(self, o: ImportFrom) -> None:\n        if self.use_logical_deps():\n            # Just importing a name doesn't create a logical dependency.\n            return\n        module_id, _ = correct_relative_import(\n            self.scope.current_module_id(), o.relative, o.id, self.is_package_init_file\n        )\n        self.add_dependency(make_trigger(module_id))  # needed if module is added/removed\n        for name, as_name in o.names:\n            self.add_dependency(make_trigger(module_id + \".\" + name))\n\n    def visit_import_all(self, o: ImportAll) -> None:\n        module_id, _ = correct_relative_import(\n            self.scope.current_module_id(), o.relative, o.id, self.is_package_init_file\n        )\n        # The current target needs to be rechecked if anything \"significant\" changes in the\n        # target module namespace (as the imported definitions will need to be updated).\n        self.add_dependency(make_wildcard_trigger(module_id))\n\n    def visit_block(self, o: Block) -> None:\n        if not o.is_unreachable:\n            super().visit_block(o)\n\n    def visit_assignment_stmt(self, o: AssignmentStmt) -> None:\n        rvalue = o.rvalue\n        if isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, TypeVarExpr):\n            analyzed = rvalue.analyzed\n            self.add_type_dependencies(\n                analyzed.upper_bound, target=make_trigger(analyzed.fullname)\n            )\n            for val in analyzed.values:\n                self.add_type_dependencies(val, target=make_trigger(analyzed.fullname))\n            # We need to re-analyze the definition if bound or value is deleted.\n            super().visit_call_expr(rvalue)\n        elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, NamedTupleExpr):\n            # Depend on types of named tuple items.\n            info = rvalue.analyzed.info\n            prefix = f\"{self.scope.current_full_target()}.{info.name}\"\n            for name, symnode in info.names.items():\n                if not name.startswith(\"_\") and isinstance(symnode.node, Var):\n                    typ = symnode.node.type\n                    if typ:\n                        self.add_type_dependencies(typ)\n                        self.add_type_dependencies(typ, target=make_trigger(prefix))\n                        attr_target = make_trigger(f\"{prefix}.{name}\")\n                        self.add_type_dependencies(typ, target=attr_target)\n        elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, TypedDictExpr):\n            # Depend on the underlying typeddict type\n            info = rvalue.analyzed.info\n            assert info.typeddict_type is not None\n            prefix = f\"{self.scope.current_full_target()}.{info.name}\"\n            self.add_type_dependencies(info.typeddict_type, target=make_trigger(prefix))\n        elif isinstance(rvalue, CallExpr) and isinstance(rvalue.analyzed, EnumCallExpr):\n            # Enum values are currently not checked, but for future we add the deps on them\n            for name, symnode in rvalue.analyzed.info.names.items():\n                if isinstance(symnode.node, Var) and symnode.node.type:\n                    self.add_type_dependencies(symnode.node.type)\n        elif o.is_alias_def:\n            assert len(o.lvalues) == 1\n            lvalue = o.lvalues[0]\n            assert isinstance(lvalue, NameExpr)\n            typ = get_proper_type(self.type_map.get(lvalue))\n            if isinstance(typ, FunctionLike) and typ.is_type_obj():\n                class_name = typ.type_object().fullname\n                self.add_dependency(make_trigger(class_name + \".__init__\"))\n                self.add_dependency(make_trigger(class_name + \".__new__\"))\n            if isinstance(rvalue, IndexExpr) and isinstance(rvalue.analyzed, TypeAliasExpr):\n                self.add_type_dependencies(rvalue.analyzed.node.target)\n            elif typ:\n                self.add_type_dependencies(typ)\n        else:\n            # Normal assignment\n            super().visit_assignment_stmt(o)\n            for lvalue in o.lvalues:\n                self.process_lvalue(lvalue)\n            items = o.lvalues + [rvalue]\n            for i in range(len(items) - 1):\n                lvalue = items[i]\n                rvalue = items[i + 1]\n                if isinstance(lvalue, TupleExpr):\n                    self.add_attribute_dependency_for_expr(rvalue, \"__iter__\")\n            if o.type:\n                self.add_type_dependencies(o.type)\n        if self.use_logical_deps() and o.unanalyzed_type is None:\n            # Special case: for definitions without an explicit type like this:\n            #     x = func(...)\n            # we add a logical dependency <func> -> <x>, because if `func` is not annotated,\n            # then it will make all points of use of `x` unchecked.\n            if (\n                isinstance(rvalue, CallExpr)\n                and isinstance(rvalue.callee, RefExpr)\n                and rvalue.callee.fullname\n            ):\n                fname: str | None = None\n                if isinstance(rvalue.callee.node, TypeInfo):\n                    # use actual __init__ as a dependency source\n                    init = rvalue.callee.node.get(\"__init__\")\n                    if init and isinstance(init.node, SYMBOL_FUNCBASE_TYPES):\n                        fname = init.node.fullname\n                else:\n                    fname = rvalue.callee.fullname\n                if not fname:\n                    return\n                for lv in o.lvalues:\n                    if isinstance(lv, RefExpr) and lv.fullname and lv.is_new_def:\n                        if lv.kind == LDEF:\n                            return  # local definitions don't generate logical deps\n                        self.add_dependency(make_trigger(fname), make_trigger(lv.fullname))\n\n    def process_lvalue(self, lvalue: Expression) -> None:\n        \"\"\"Generate additional dependencies for an lvalue.\"\"\"\n        if isinstance(lvalue, IndexExpr):\n            self.add_operator_method_dependency(lvalue.base, \"__setitem__\")\n        elif isinstance(lvalue, NameExpr):\n            if lvalue.kind in (MDEF, GDEF):\n                # Assignment to an attribute in the class body, or direct assignment to a\n                # global variable.\n                lvalue_type = self.get_non_partial_lvalue_type(lvalue)\n                type_triggers = self.get_type_triggers(lvalue_type)\n                attr_trigger = make_trigger(f\"{self.scope.current_full_target()}.{lvalue.name}\")\n                for type_trigger in type_triggers:\n                    self.add_dependency(type_trigger, attr_trigger)\n        elif isinstance(lvalue, MemberExpr):\n            if self.is_self_member_ref(lvalue) and lvalue.is_new_def:\n                node = lvalue.node\n                if isinstance(node, Var):\n                    info = node.info\n                    if info and has_user_bases(info):\n                        # Recheck Liskov for self definitions\n                        self.add_dependency(make_trigger(info.fullname + \".\" + lvalue.name))\n            if lvalue.kind is None:\n                # Reference to a non-module attribute\n                if lvalue.expr not in self.type_map:\n                    # Unreachable assignment -> not checked so no dependencies to generate.\n                    return\n                object_type = self.type_map[lvalue.expr]\n                lvalue_type = self.get_non_partial_lvalue_type(lvalue)\n                type_triggers = self.get_type_triggers(lvalue_type)\n                for attr_trigger in self.attribute_triggers(object_type, lvalue.name):\n                    for type_trigger in type_triggers:\n                        self.add_dependency(type_trigger, attr_trigger)\n        elif isinstance(lvalue, TupleExpr):\n            for item in lvalue.items:\n                self.process_lvalue(item)\n        elif isinstance(lvalue, StarExpr):\n            self.process_lvalue(lvalue.expr)\n\n    def is_self_member_ref(self, memberexpr: MemberExpr) -> bool:\n        \"\"\"Does memberexpr to refer to an attribute of self?\"\"\"\n        if not isinstance(memberexpr.expr, NameExpr):\n            return False\n        node = memberexpr.expr.node\n        return isinstance(node, Var) and node.is_self\n\n    def get_non_partial_lvalue_type(self, lvalue: RefExpr) -> Type:\n        if lvalue not in self.type_map:\n            # Likely a block considered unreachable during type checking.\n            return UninhabitedType()\n        lvalue_type = get_proper_type(self.type_map[lvalue])\n        if isinstance(lvalue_type, PartialType):\n            if isinstance(lvalue.node, Var):\n                if lvalue.node.type:\n                    lvalue_type = get_proper_type(lvalue.node.type)\n                else:\n                    lvalue_type = UninhabitedType()\n            else:\n                # Probably a secondary, non-definition assignment that doesn't\n                # result in a non-partial type. We won't be able to infer any\n                # dependencies from this so just return something. (The first,\n                # definition assignment with a partial type is handled\n                # differently, in the semantic analyzer.)\n                assert not lvalue.is_new_def\n                return UninhabitedType()\n        return lvalue_type\n\n    def visit_operator_assignment_stmt(self, o: OperatorAssignmentStmt) -> None:\n        super().visit_operator_assignment_stmt(o)\n        self.process_lvalue(o.lvalue)\n        method = op_methods[o.op]\n        self.add_attribute_dependency_for_expr(o.lvalue, method)\n        if o.op in ops_with_inplace_method:\n            inplace_method = \"__i\" + method[2:]\n            self.add_attribute_dependency_for_expr(o.lvalue, inplace_method)\n\n    def visit_for_stmt(self, o: ForStmt) -> None:\n        super().visit_for_stmt(o)\n        if not o.is_async:\n            # __getitem__ is only used if __iter__ is missing but for simplicity we\n            # just always depend on both.\n            self.add_attribute_dependency_for_expr(o.expr, \"__iter__\")\n            self.add_attribute_dependency_for_expr(o.expr, \"__getitem__\")\n            if o.inferred_iterator_type:\n                self.add_attribute_dependency(o.inferred_iterator_type, \"__next__\")\n        else:\n            self.add_attribute_dependency_for_expr(o.expr, \"__aiter__\")\n            if o.inferred_iterator_type:\n                self.add_attribute_dependency(o.inferred_iterator_type, \"__anext__\")\n\n        self.process_lvalue(o.index)\n        if isinstance(o.index, TupleExpr):\n            # Process multiple assignment to index variables.\n            item_type = o.inferred_item_type\n            if item_type:\n                # This is similar to above.\n                self.add_attribute_dependency(item_type, \"__iter__\")\n                self.add_attribute_dependency(item_type, \"__getitem__\")\n        if o.index_type:\n            self.add_type_dependencies(o.index_type)\n\n    def visit_with_stmt(self, o: WithStmt) -> None:\n        super().visit_with_stmt(o)\n        for e in o.expr:\n            if not o.is_async:\n                self.add_attribute_dependency_for_expr(e, \"__enter__\")\n                self.add_attribute_dependency_for_expr(e, \"__exit__\")\n            else:\n                self.add_attribute_dependency_for_expr(e, \"__aenter__\")\n                self.add_attribute_dependency_for_expr(e, \"__aexit__\")\n        for typ in o.analyzed_types:\n            self.add_type_dependencies(typ)\n\n    def visit_del_stmt(self, o: DelStmt) -> None:\n        super().visit_del_stmt(o)\n        if isinstance(o.expr, IndexExpr):\n            self.add_attribute_dependency_for_expr(o.expr.base, \"__delitem__\")\n\n    # Expressions\n\n    def process_global_ref_expr(self, o: RefExpr) -> None:\n        if o.fullname:\n            self.add_dependency(make_trigger(o.fullname))\n\n        # If this is a reference to a type, generate a dependency to its\n        # constructor.\n        # IDEA: Avoid generating spurious dependencies for except statements,\n        #       class attribute references, etc., if performance is a problem.\n        typ = get_proper_type(self.type_map.get(o))\n        if isinstance(typ, FunctionLike) and typ.is_type_obj():\n            class_name = typ.type_object().fullname\n            self.add_dependency(make_trigger(class_name + \".__init__\"))\n            self.add_dependency(make_trigger(class_name + \".__new__\"))\n\n    def visit_name_expr(self, o: NameExpr) -> None:\n        if o.kind == LDEF:\n            # We don't track dependencies to local variables, since they\n            # aren't externally visible.\n            return\n        if o.kind == MDEF:\n            # Direct reference to member is only possible in the scope that\n            # defined the name, so no dependency is required.\n            return\n        self.process_global_ref_expr(o)\n\n    def visit_member_expr(self, e: MemberExpr) -> None:\n        if isinstance(e.expr, RefExpr) and isinstance(e.expr.node, TypeInfo):\n            # Special case class attribute so that we don't depend on \"__init__\".\n            self.add_dependency(make_trigger(e.expr.node.fullname))\n        else:\n            super().visit_member_expr(e)\n        if e.kind is not None:\n            # Reference to a module attribute\n            self.process_global_ref_expr(e)\n        else:\n            # Reference to a non-module (or missing) attribute\n            if e.expr not in self.type_map:\n                # No type available -- this happens for unreachable code. Since it's unreachable,\n                # it wasn't type checked and we don't need to generate dependencies.\n                return\n            if isinstance(e.expr, RefExpr) and isinstance(e.expr.node, MypyFile):\n                # Special case: reference to a missing module attribute.\n                self.add_dependency(make_trigger(e.expr.node.fullname + \".\" + e.name))\n                return\n            typ = get_proper_type(self.type_map[e.expr])\n            self.add_attribute_dependency(typ, e.name)\n            if self.use_logical_deps() and isinstance(typ, AnyType):\n                name = self.get_unimported_fullname(e, typ)\n                if name is not None:\n                    # Generate a logical dependency from an unimported\n                    # definition (which comes from a missing module).\n                    # Example:\n                    #     import missing  # \"missing\" not in build\n                    #\n                    #     def g() -> None:\n                    #         missing.f()  # Generate dependency from \"missing.f\"\n                    self.add_dependency(make_trigger(name))\n\n    def get_unimported_fullname(self, e: MemberExpr, typ: AnyType) -> str | None:\n        \"\"\"If e refers to an unimported definition, infer the fullname of this.\n\n        Return None if e doesn't refer to an unimported definition or if we can't\n        determine the name.\n        \"\"\"\n        suffix = \"\"\n        # Unwrap nested member expression to handle cases like \"a.b.c.d\" where\n        # \"a.b\" is a known reference to an unimported module. Find the base\n        # reference to an unimported module (such as \"a.b\") and the name suffix\n        # (such as \"c.d\") needed to build a full name.\n        while typ.type_of_any == TypeOfAny.from_another_any and isinstance(e.expr, MemberExpr):\n            suffix = \".\" + e.name + suffix\n            e = e.expr\n            if e.expr not in self.type_map:\n                return None\n            obj_type = get_proper_type(self.type_map[e.expr])\n            if not isinstance(obj_type, AnyType):\n                # Can't find the base reference to the unimported module.\n                return None\n            typ = obj_type\n        if typ.type_of_any == TypeOfAny.from_unimported_type and typ.missing_import_name:\n            # Infer the full name of the unimported definition.\n            return typ.missing_import_name + \".\" + e.name + suffix\n        return None\n\n    def visit_super_expr(self, e: SuperExpr) -> None:\n        # Arguments in \"super(C, self)\" won't generate useful logical deps.\n        if not self.use_logical_deps():\n            super().visit_super_expr(e)\n        if e.info is not None:\n            name = e.name\n            for base in non_trivial_bases(e.info):\n                self.add_dependency(make_trigger(base.fullname + \".\" + name))\n                if name in base.names:\n                    # No need to depend on further base classes, since we found\n                    # the target.  This is safe since if the target gets\n                    # deleted or modified, we'll trigger it.\n                    break\n\n    def visit_call_expr(self, e: CallExpr) -> None:\n        if isinstance(e.callee, RefExpr) and e.callee.fullname == \"builtins.isinstance\":\n            self.process_isinstance_call(e)\n        else:\n            super().visit_call_expr(e)\n            typ = self.type_map.get(e.callee)\n            if typ is not None:\n                typ = get_proper_type(typ)\n                if not isinstance(typ, FunctionLike):\n                    self.add_attribute_dependency(typ, \"__call__\")\n\n    def process_isinstance_call(self, e: CallExpr) -> None:\n        \"\"\"Process \"isinstance(...)\" in a way to avoid some extra dependencies.\"\"\"\n        if len(e.args) == 2:\n            arg = e.args[1]\n            if (\n                isinstance(arg, RefExpr)\n                and arg.kind == GDEF\n                and isinstance(arg.node, TypeInfo)\n                and arg.fullname\n            ):\n                # Special case to avoid redundant dependencies from \"__init__\".\n                self.add_dependency(make_trigger(arg.fullname))\n                return\n        # In uncommon cases generate normal dependencies. These will include\n        # spurious dependencies, but the performance impact is small.\n        super().visit_call_expr(e)\n\n    def visit_cast_expr(self, e: CastExpr) -> None:\n        super().visit_cast_expr(e)\n        self.add_type_dependencies(e.type)\n\n    def visit_type_form_expr(self, e: TypeFormExpr) -> None:\n        super().visit_type_form_expr(e)\n        self.add_type_dependencies(e.type)\n\n    def visit_assert_type_expr(self, e: AssertTypeExpr) -> None:\n        super().visit_assert_type_expr(e)\n        self.add_type_dependencies(e.type)\n\n    def visit_type_application(self, e: TypeApplication) -> None:\n        super().visit_type_application(e)\n        for typ in e.types:\n            self.add_type_dependencies(typ)\n\n    def visit_index_expr(self, e: IndexExpr) -> None:\n        super().visit_index_expr(e)\n        self.add_operator_method_dependency(e.base, \"__getitem__\")\n\n    def visit_unary_expr(self, e: UnaryExpr) -> None:\n        super().visit_unary_expr(e)\n        if e.op not in unary_op_methods:\n            return\n        method = unary_op_methods[e.op]\n        self.add_operator_method_dependency(e.expr, method)\n\n    def visit_op_expr(self, e: OpExpr) -> None:\n        super().visit_op_expr(e)\n        self.process_binary_op(e.op, e.left, e.right)\n\n    def visit_comparison_expr(self, e: ComparisonExpr) -> None:\n        super().visit_comparison_expr(e)\n        for i, op in enumerate(e.operators):\n            left = e.operands[i]\n            right = e.operands[i + 1]\n            self.process_binary_op(op, left, right)\n\n    def process_binary_op(self, op: str, left: Expression, right: Expression) -> None:\n        method = op_methods.get(op)\n        if method:\n            if op == \"in\":\n                self.add_operator_method_dependency(right, method)\n            else:\n                self.add_operator_method_dependency(left, method)\n                rev_method = reverse_op_methods.get(method)\n                if rev_method:\n                    self.add_operator_method_dependency(right, rev_method)\n\n    def add_operator_method_dependency(self, e: Expression, method: str) -> None:\n        typ = get_proper_type(self.type_map.get(e))\n        if typ is not None:\n            self.add_operator_method_dependency_for_type(typ, method)\n\n    def add_operator_method_dependency_for_type(self, typ: ProperType, method: str) -> None:\n        # Note that operator methods can't be (non-metaclass) methods of type objects\n        # (that is, TypeType objects or Callables representing a type).\n        if isinstance(typ, TypeVarType):\n            typ = get_proper_type(typ.upper_bound)\n        if isinstance(typ, TupleType):\n            typ = typ.partial_fallback\n        if isinstance(typ, Instance):\n            trigger = make_trigger(typ.type.fullname + \".\" + method)\n            self.add_dependency(trigger)\n        elif isinstance(typ, UnionType):\n            for item in typ.items:\n                self.add_operator_method_dependency_for_type(get_proper_type(item), method)\n        elif isinstance(typ, FunctionLike) and typ.is_type_obj():\n            self.add_operator_method_dependency_for_type(typ.fallback, method)\n        elif isinstance(typ, TypeType):\n            if isinstance(typ.item, Instance) and typ.item.type.metaclass_type is not None:\n                self.add_operator_method_dependency_for_type(typ.item.type.metaclass_type, method)\n\n    def visit_generator_expr(self, e: GeneratorExpr) -> None:\n        super().visit_generator_expr(e)\n        for seq in e.sequences:\n            self.add_iter_dependency(seq)\n\n    def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> None:\n        super().visit_dictionary_comprehension(e)\n        for seq in e.sequences:\n            self.add_iter_dependency(seq)\n\n    def visit_star_expr(self, e: StarExpr) -> None:\n        super().visit_star_expr(e)\n        self.add_iter_dependency(e.expr)\n\n    def visit_yield_from_expr(self, e: YieldFromExpr) -> None:\n        super().visit_yield_from_expr(e)\n        self.add_iter_dependency(e.expr)\n\n    def visit_await_expr(self, e: AwaitExpr) -> None:\n        super().visit_await_expr(e)\n        self.add_attribute_dependency_for_expr(e.expr, \"__await__\")\n\n    # Helpers\n\n    def add_type_alias_deps(self, target: str) -> None:\n        # Type aliases are special, because some of the dependencies are calculated\n        # in semanal.py, before they are expanded.\n        if target in self.alias_deps:\n            for alias in self.alias_deps[target]:\n                self.add_dependency(make_trigger(alias))\n\n    def add_dependency(self, trigger: str, target: str | None = None) -> None:\n        \"\"\"Add dependency from trigger to a target.\n\n        If the target is not given explicitly, use the current target.\n        \"\"\"\n        if trigger.startswith(\n            (\"<builtins.\", \"<typing.\", \"<mypy_extensions.\", \"<typing_extensions.\")\n        ):\n            # Don't track dependencies to certain library modules to keep the size of\n            # the dependencies manageable. These dependencies should only\n            # change on mypy version updates, which will require a full rebuild\n            # anyway.\n            return\n        if target is None:\n            target = self.scope.current_target()\n        self.map.setdefault(trigger, set()).add(target)\n\n    def add_type_dependencies(self, typ: Type, target: str | None = None) -> None:\n        \"\"\"Add dependencies to all components of a type.\n\n        Args:\n            target: If not None, override the default (current) target of the\n                generated dependency.\n        \"\"\"\n        for trigger in self.get_type_triggers(typ):\n            self.add_dependency(trigger, target)\n\n    def add_attribute_dependency(self, typ: Type, name: str) -> None:\n        \"\"\"Add dependencies for accessing a named attribute of a type.\"\"\"\n        targets = self.attribute_triggers(typ, name)\n        for target in targets:\n            self.add_dependency(target)\n\n    def attribute_triggers(self, typ: Type, name: str) -> list[str]:\n        \"\"\"Return all triggers associated with the attribute of a type.\"\"\"\n        typ = get_proper_type(typ)\n        if isinstance(typ, TypeVarType):\n            typ = get_proper_type(typ.upper_bound)\n        if isinstance(typ, TupleType):\n            typ = typ.partial_fallback\n        if isinstance(typ, Instance):\n            member = f\"{typ.type.fullname}.{name}\"\n            return [make_trigger(member)]\n        elif isinstance(typ, FunctionLike) and typ.is_type_obj():\n            member = f\"{typ.type_object().fullname}.{name}\"\n            triggers = [make_trigger(member)]\n            triggers.extend(self.attribute_triggers(typ.fallback, name))\n            return triggers\n        elif isinstance(typ, UnionType):\n            targets = []\n            for item in typ.items:\n                targets.extend(self.attribute_triggers(item, name))\n            return targets\n        elif isinstance(typ, TypeType):\n            triggers = self.attribute_triggers(typ.item, name)\n            if isinstance(typ.item, Instance) and typ.item.type.metaclass_type is not None:\n                triggers.append(\n                    make_trigger(f\"{typ.item.type.metaclass_type.type.fullname}.{name}\")\n                )\n            return triggers\n        else:\n            return []\n\n    def add_attribute_dependency_for_expr(self, e: Expression, name: str) -> None:\n        typ = self.type_map.get(e)\n        if typ is not None:\n            self.add_attribute_dependency(typ, name)\n\n    def add_iter_dependency(self, node: Expression) -> None:\n        typ = self.type_map.get(node)\n        if typ:\n            self.add_attribute_dependency(typ, \"__iter__\")\n\n    def use_logical_deps(self) -> bool:\n        return self.options is not None and self.options.logical_deps\n\n    def get_type_triggers(self, typ: Type) -> list[str]:\n        return get_type_triggers(typ, self.use_logical_deps())\n\n\ndef get_type_triggers(\n    typ: Type, use_logical_deps: bool, seen_aliases: set[TypeAliasType] | None = None\n) -> list[str]:\n    \"\"\"Return all triggers that correspond to a type becoming stale.\"\"\"\n    return typ.accept(TypeTriggersVisitor(use_logical_deps, seen_aliases))\n\n\nclass TypeTriggersVisitor(TypeVisitor[list[str]]):\n    def __init__(\n        self, use_logical_deps: bool, seen_aliases: set[TypeAliasType] | None = None\n    ) -> None:\n        self.deps: list[str] = []\n        self.seen_aliases: set[TypeAliasType] = seen_aliases or set()\n        self.use_logical_deps = use_logical_deps\n\n    def get_type_triggers(self, typ: Type) -> list[str]:\n        return get_type_triggers(typ, self.use_logical_deps, self.seen_aliases)\n\n    def visit_instance(self, typ: Instance) -> list[str]:\n        trigger = make_trigger(typ.type.fullname)\n        triggers = [trigger]\n        for arg in typ.args:\n            triggers.extend(self.get_type_triggers(arg))\n        if typ.last_known_value:\n            triggers.extend(self.get_type_triggers(typ.last_known_value))\n        if typ.extra_attrs and typ.extra_attrs.mod_name:\n            # Module as type effectively depends on all module attributes, use wildcard.\n            triggers.append(make_wildcard_trigger(typ.extra_attrs.mod_name))\n        return triggers\n\n    def visit_type_alias_type(self, typ: TypeAliasType) -> list[str]:\n        if typ in self.seen_aliases:\n            return []\n        self.seen_aliases.add(typ)\n        assert typ.alias is not None\n        trigger = make_trigger(typ.alias.fullname)\n        triggers = [trigger]\n        for arg in typ.args:\n            triggers.extend(self.get_type_triggers(arg))\n        triggers.extend(self.get_type_triggers(typ.alias.target))\n        return triggers\n\n    def visit_any(self, typ: AnyType) -> list[str]:\n        if typ.missing_import_name is not None:\n            return [make_trigger(typ.missing_import_name)]\n        return []\n\n    def visit_none_type(self, typ: NoneType) -> list[str]:\n        return []\n\n    def visit_callable_type(self, typ: CallableType) -> list[str]:\n        triggers = []\n        for arg in typ.arg_types:\n            triggers.extend(self.get_type_triggers(arg))\n        triggers.extend(self.get_type_triggers(typ.ret_type))\n        # fallback is a metaclass type for class objects, and is\n        # processed separately.\n        return triggers\n\n    def visit_overloaded(self, typ: Overloaded) -> list[str]:\n        triggers = []\n        for item in typ.items:\n            triggers.extend(self.get_type_triggers(item))\n        return triggers\n\n    def visit_erased_type(self, t: ErasedType) -> list[str]:\n        # This type should exist only temporarily during type inference\n        assert False, \"Should not see an erased type here\"\n\n    def visit_deleted_type(self, typ: DeletedType) -> list[str]:\n        return []\n\n    def visit_partial_type(self, typ: PartialType) -> list[str]:\n        assert False, \"Should not see a partial type here\"\n\n    def visit_tuple_type(self, typ: TupleType) -> list[str]:\n        triggers = []\n        for item in typ.items:\n            triggers.extend(self.get_type_triggers(item))\n        triggers.extend(self.get_type_triggers(typ.partial_fallback))\n        return triggers\n\n    def visit_type_type(self, typ: TypeType) -> list[str]:\n        triggers = self.get_type_triggers(typ.item)\n        if not self.use_logical_deps:\n            old_triggers = triggers.copy()\n            for trigger in old_triggers:\n                triggers.append(trigger.rstrip(\">\") + \".__init__>\")\n                triggers.append(trigger.rstrip(\">\") + \".__new__>\")\n        return triggers\n\n    def visit_type_var(self, typ: TypeVarType) -> list[str]:\n        triggers = []\n        if typ.fullname:\n            triggers.append(make_trigger(typ.fullname))\n        triggers.extend(self.get_type_triggers(typ.upper_bound))\n        triggers.extend(self.get_type_triggers(typ.default))\n        for val in typ.values:\n            triggers.extend(self.get_type_triggers(val))\n        return triggers\n\n    def visit_param_spec(self, typ: ParamSpecType) -> list[str]:\n        triggers = []\n        if typ.fullname:\n            triggers.append(make_trigger(typ.fullname))\n        triggers.extend(self.get_type_triggers(typ.upper_bound))\n        triggers.extend(self.get_type_triggers(typ.default))\n        triggers.extend(self.get_type_triggers(typ.prefix))\n        return triggers\n\n    def visit_type_var_tuple(self, typ: TypeVarTupleType) -> list[str]:\n        triggers = []\n        if typ.fullname:\n            triggers.append(make_trigger(typ.fullname))\n        triggers.extend(self.get_type_triggers(typ.upper_bound))\n        triggers.extend(self.get_type_triggers(typ.default))\n        return triggers\n\n    def visit_unpack_type(self, typ: UnpackType) -> list[str]:\n        return typ.type.accept(self)\n\n    def visit_parameters(self, typ: Parameters) -> list[str]:\n        triggers = []\n        for arg in typ.arg_types:\n            triggers.extend(self.get_type_triggers(arg))\n        return triggers\n\n    def visit_typeddict_type(self, typ: TypedDictType) -> list[str]:\n        triggers = []\n        for item in typ.items.values():\n            triggers.extend(self.get_type_triggers(item))\n        triggers.extend(self.get_type_triggers(typ.fallback))\n        return triggers\n\n    def visit_literal_type(self, typ: LiteralType) -> list[str]:\n        return self.get_type_triggers(typ.fallback)\n\n    def visit_unbound_type(self, typ: UnboundType) -> list[str]:\n        return []\n\n    def visit_uninhabited_type(self, typ: UninhabitedType) -> list[str]:\n        return []\n\n    def visit_union_type(self, typ: UnionType) -> list[str]:\n        triggers = []\n        for item in typ.items:\n            triggers.extend(self.get_type_triggers(item))\n        return triggers\n\n\ndef merge_dependencies(new_deps: dict[str, set[str]], deps: dict[str, set[str]]) -> None:\n    for trigger, targets in new_deps.items():\n        deps.setdefault(trigger, set()).update(targets)\n\n\ndef non_trivial_bases(info: TypeInfo) -> list[TypeInfo]:\n    return [base for base in info.mro[1:] if base.fullname != \"builtins.object\"]\n\n\ndef has_user_bases(info: TypeInfo) -> bool:\n    return any(base.module_name not in (\"builtins\", \"typing\", \"enum\") for base in info.mro[1:])\n\n\ndef dump_all_dependencies(\n    modules: dict[str, MypyFile],\n    type_map: dict[Expression, Type],\n    python_version: tuple[int, int],\n    options: Options,\n) -> None:\n    \"\"\"Generate dependencies for all interesting modules and print them to stdout.\"\"\"\n    all_deps: dict[str, set[str]] = {}\n    for id, node in modules.items():\n        # Uncomment for debugging:\n        # print('processing', id)\n        if id in (\"builtins\", \"typing\") or \"/typeshed/\" in node.path:\n            continue\n        assert id == node.fullname\n        deps = get_dependencies(node, type_map, python_version, options)\n        for trigger, targets in deps.items():\n            all_deps.setdefault(trigger, set()).update(targets)\n    type_state.add_all_protocol_deps(all_deps)\n\n    for trigger, targets in sorted(all_deps.items(), key=lambda x: x[0]):\n        print(trigger)\n        for target in sorted(targets):\n            print(f\"    {target}\")\n"
  },
  {
    "path": "mypy/server/mergecheck.py",
    "content": "\"\"\"Check for duplicate AST nodes after merge.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final\n\nfrom mypy.nodes import Decorator, FakeInfo, FuncDef, SymbolNode, Var\nfrom mypy.server.objgraph import get_path, get_reachable_graph\n\n# If True, print more verbose output on failure.\nDUMP_MISMATCH_NODES: Final = False\n\n\ndef check_consistency(o: object) -> None:\n    \"\"\"Fail if there are two AST nodes with the same fullname reachable from 'o'.\n\n    Raise AssertionError on failure and print some debugging output.\n    \"\"\"\n    seen, parents = get_reachable_graph(o)\n    reachable = list(seen.values())\n    syms = [x for x in reachable if isinstance(x, SymbolNode)]\n\n    m: dict[str, SymbolNode] = {}\n    for sym in syms:\n        if isinstance(sym, FakeInfo):\n            continue\n\n        fn = sym.fullname\n        # Skip None and empty names, since they are ambiguous.\n        # TODO: Everything should have a proper full name?\n        if not fn:\n            continue\n\n        # Skip stuff that should be expected to have duplicate names\n        if isinstance(sym, (Var, Decorator)):\n            continue\n        if isinstance(sym, FuncDef) and sym.is_overload:\n            continue\n\n        if fn not in m:\n            m[fn] = sym\n            continue\n\n        # We have trouble and need to decide what to do about it.\n        sym1, sym2 = sym, m[fn]\n\n        # If the type changed, then it shouldn't have been merged.\n        if type(sym1) is not type(sym2):\n            continue\n\n        path1 = get_path(sym1, seen, parents)\n        path2 = get_path(sym2, seen, parents)\n\n        if fn in m:\n            print(f\"\\nDuplicate {type(sym).__name__!r} nodes with fullname {fn!r} found:\")\n            print(\"[1] %d: %s\" % (id(sym1), path_to_str(path1)))\n            print(\"[2] %d: %s\" % (id(sym2), path_to_str(path2)))\n\n        if DUMP_MISMATCH_NODES and fn in m:\n            # Add verbose output with full AST node contents.\n            print(\"---\")\n            print(id(sym1), sym1)\n            print(\"---\")\n            print(id(sym2), sym2)\n\n        assert sym.fullname not in m\n\n\ndef path_to_str(path: list[tuple[object, object]]) -> str:\n    result = \"<root>\"\n    for attr, obj in path:\n        t = type(obj).__name__\n        if t in (\"dict\", \"tuple\", \"SymbolTable\", \"list\"):\n            result += f\"[{repr(attr)}]\"\n        else:\n            if isinstance(obj, Var):\n                result += f\".{attr}({t}:{obj.name})\"\n            elif t in (\"BuildManager\", \"FineGrainedBuildManager\"):\n                # Omit class name for some classes that aren't part of a class\n                # hierarchy since there isn't much ambiguity.\n                result += f\".{attr}\"\n            else:\n                result += f\".{attr}({t})\"\n    return result\n"
  },
  {
    "path": "mypy/server/objgraph.py",
    "content": "\"\"\"Find all objects reachable from a root object.\"\"\"\n\nfrom __future__ import annotations\n\nimport types\nimport weakref\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom typing import Final\n\nmethod_descriptor_type: Final = type(object.__dir__)\nmethod_wrapper_type: Final = type(object().__ne__)\nwrapper_descriptor_type: Final = type(object.__ne__)\n\nFUNCTION_TYPES: Final = (\n    types.BuiltinFunctionType,\n    types.FunctionType,\n    types.MethodType,\n    method_descriptor_type,\n    wrapper_descriptor_type,\n    method_wrapper_type,\n)\n\nATTR_BLACKLIST: Final = {\"__doc__\", \"__name__\", \"__class__\", \"__dict__\"}\n\n# Instances of these types can't have references to other objects\nATOMIC_TYPE_BLACKLIST: Final = {bool, int, float, str, type(None), object}\n\n# Don't look at most attributes of these types\nCOLLECTION_TYPE_BLACKLIST: Final = {list, set, dict, tuple}\n\n# Don't return these objects\nTYPE_BLACKLIST: Final = {weakref.ReferenceType}\n\n\ndef isproperty(o: object, attr: str) -> bool:\n    return isinstance(getattr(type(o), attr, None), property)\n\n\ndef get_edge_candidates(o: object) -> Iterator[tuple[object, object]]:\n    # use getattr because mypyc expects dict, not mappingproxy\n    if \"__getattribute__\" in getattr(type(o), \"__dict__\"):  # noqa: B009\n        return\n    if type(o) not in COLLECTION_TYPE_BLACKLIST:\n        for attr in dir(o):\n            try:\n                if attr not in ATTR_BLACKLIST and hasattr(o, attr) and not isproperty(o, attr):\n                    e = getattr(o, attr)\n                    if type(e) not in ATOMIC_TYPE_BLACKLIST:\n                        yield attr, e\n            except AssertionError:\n                pass\n    if isinstance(o, Mapping):\n        yield from o.items()\n    elif isinstance(o, Iterable) and not isinstance(o, str):\n        for i, e in enumerate(o):\n            yield i, e\n\n\ndef get_edges(o: object) -> Iterator[tuple[object, object]]:\n    for s, e in get_edge_candidates(o):\n        if isinstance(e, FUNCTION_TYPES):\n            # We don't want to collect methods, but do want to collect values\n            # in closures and self pointers to other objects\n\n            if hasattr(e, \"__closure__\"):\n                yield (s, \"__closure__\"), e.__closure__\n            if hasattr(e, \"__self__\"):\n                se = e.__self__\n                if se is not o and se is not type(o) and hasattr(s, \"__self__\"):\n                    yield s.__self__, se\n        else:\n            if type(e) not in TYPE_BLACKLIST:\n                yield s, e\n\n\ndef get_reachable_graph(root: object) -> tuple[dict[int, object], dict[int, tuple[int, object]]]:\n    parents = {}\n    seen = {id(root): root}\n    worklist = [root]\n    while worklist:\n        o = worklist.pop()\n        for s, e in get_edges(o):\n            if id(e) in seen:\n                continue\n            parents[id(e)] = (id(o), s)\n            seen[id(e)] = e\n            worklist.append(e)\n\n    return seen, parents\n\n\ndef get_path(\n    o: object, seen: dict[int, object], parents: dict[int, tuple[int, object]]\n) -> list[tuple[object, object]]:\n    path = []\n    while id(o) in parents:\n        pid, attr = parents[id(o)]\n        o = seen[pid]\n        path.append((attr, o))\n    path.reverse()\n    return path\n"
  },
  {
    "path": "mypy/server/subexpr.py",
    "content": "\"\"\"Find all subexpressions of an AST node.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import (\n    AssertTypeExpr,\n    AssignmentExpr,\n    AwaitExpr,\n    CallExpr,\n    CastExpr,\n    ComparisonExpr,\n    ConditionalExpr,\n    DictExpr,\n    DictionaryComprehension,\n    Expression,\n    GeneratorExpr,\n    IndexExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    MemberExpr,\n    Node,\n    OpExpr,\n    RevealExpr,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    TemplateStrExpr,\n    TupleExpr,\n    TypeApplication,\n    TypeFormExpr,\n    UnaryExpr,\n    YieldExpr,\n    YieldFromExpr,\n)\nfrom mypy.traverser import TraverserVisitor\n\n\ndef get_subexpressions(node: Node) -> list[Expression]:\n    visitor = SubexpressionFinder()\n    node.accept(visitor)\n    return visitor.expressions\n\n\nclass SubexpressionFinder(TraverserVisitor):\n    def __init__(self) -> None:\n        self.expressions: list[Expression] = []\n\n    def visit_int_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_name_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_float_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_str_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_bytes_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_unicode_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_complex_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_ellipsis(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_super_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_type_var_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_type_alias_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_namedtuple_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_typeddict_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit__promote_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_newtype_expr(self, o: Expression) -> None:\n        self.add(o)\n\n    def visit_member_expr(self, e: MemberExpr) -> None:\n        self.add(e)\n        super().visit_member_expr(e)\n\n    def visit_yield_from_expr(self, e: YieldFromExpr) -> None:\n        self.add(e)\n        super().visit_yield_from_expr(e)\n\n    def visit_yield_expr(self, e: YieldExpr) -> None:\n        self.add(e)\n        super().visit_yield_expr(e)\n\n    def visit_call_expr(self, e: CallExpr) -> None:\n        self.add(e)\n        super().visit_call_expr(e)\n\n    def visit_op_expr(self, e: OpExpr) -> None:\n        self.add(e)\n        super().visit_op_expr(e)\n\n    def visit_comparison_expr(self, e: ComparisonExpr) -> None:\n        self.add(e)\n        super().visit_comparison_expr(e)\n\n    def visit_slice_expr(self, e: SliceExpr) -> None:\n        self.add(e)\n        super().visit_slice_expr(e)\n\n    def visit_cast_expr(self, e: CastExpr) -> None:\n        self.add(e)\n        super().visit_cast_expr(e)\n\n    def visit_type_form_expr(self, e: TypeFormExpr) -> None:\n        self.add(e)\n        super().visit_type_form_expr(e)\n\n    def visit_assert_type_expr(self, e: AssertTypeExpr) -> None:\n        self.add(e)\n        super().visit_assert_type_expr(e)\n\n    def visit_reveal_expr(self, e: RevealExpr) -> None:\n        self.add(e)\n        super().visit_reveal_expr(e)\n\n    def visit_assignment_expr(self, e: AssignmentExpr) -> None:\n        self.add(e)\n        super().visit_assignment_expr(e)\n\n    def visit_unary_expr(self, e: UnaryExpr) -> None:\n        self.add(e)\n        super().visit_unary_expr(e)\n\n    def visit_list_expr(self, e: ListExpr) -> None:\n        self.add(e)\n        super().visit_list_expr(e)\n\n    def visit_tuple_expr(self, e: TupleExpr) -> None:\n        self.add(e)\n        super().visit_tuple_expr(e)\n\n    def visit_dict_expr(self, e: DictExpr) -> None:\n        self.add(e)\n        super().visit_dict_expr(e)\n\n    def visit_template_str_expr(self, e: TemplateStrExpr) -> None:\n        self.add(e)\n        super().visit_template_str_expr(e)\n\n    def visit_set_expr(self, e: SetExpr) -> None:\n        self.add(e)\n        super().visit_set_expr(e)\n\n    def visit_index_expr(self, e: IndexExpr) -> None:\n        self.add(e)\n        super().visit_index_expr(e)\n\n    def visit_generator_expr(self, e: GeneratorExpr) -> None:\n        self.add(e)\n        super().visit_generator_expr(e)\n\n    def visit_dictionary_comprehension(self, e: DictionaryComprehension) -> None:\n        self.add(e)\n        super().visit_dictionary_comprehension(e)\n\n    def visit_list_comprehension(self, e: ListComprehension) -> None:\n        self.add(e)\n        super().visit_list_comprehension(e)\n\n    def visit_set_comprehension(self, e: SetComprehension) -> None:\n        self.add(e)\n        super().visit_set_comprehension(e)\n\n    def visit_conditional_expr(self, e: ConditionalExpr) -> None:\n        self.add(e)\n        super().visit_conditional_expr(e)\n\n    def visit_type_application(self, e: TypeApplication) -> None:\n        self.add(e)\n        super().visit_type_application(e)\n\n    def visit_lambda_expr(self, e: LambdaExpr) -> None:\n        self.add(e)\n        super().visit_lambda_expr(e)\n\n    def visit_star_expr(self, e: StarExpr) -> None:\n        self.add(e)\n        super().visit_star_expr(e)\n\n    def visit_await_expr(self, e: AwaitExpr) -> None:\n        self.add(e)\n        super().visit_await_expr(e)\n\n    def add(self, e: Expression) -> None:\n        self.expressions.append(e)\n"
  },
  {
    "path": "mypy/server/target.py",
    "content": "from __future__ import annotations\n\n\ndef trigger_to_target(s: str) -> str:\n    assert s[0] == \"<\"\n    # Strip off the angle brackets\n    s = s[1:-1]\n    # If there is a [wildcard] or similar, strip that off too\n    if s[-1] == \"]\":\n        s = s.split(\"[\")[0]\n    return s\n"
  },
  {
    "path": "mypy/server/trigger.py",
    "content": "\"\"\"AST triggers that are used for fine-grained dependency handling.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final\n\n# Used as a suffix for triggers to handle \"from m import *\" dependencies (see also\n# make_wildcard_trigger)\n\nWILDCARD_TAG: Final = \"[wildcard]\"\n\n\ndef make_trigger(name: str) -> str:\n    return f\"<{name}>\"\n\n\ndef make_wildcard_trigger(module: str) -> str:\n    \"\"\"Special trigger fired when any top-level name is changed in a module.\n\n    Note that this is different from a module trigger, as module triggers are only\n    fired if the module is created, deleted, or replaced with a non-module, whereas\n    a wildcard trigger is triggered for namespace changes.\n\n    This is used for \"from m import *\" dependencies.\n    \"\"\"\n    return f\"<{module}{WILDCARD_TAG}>\"\n"
  },
  {
    "path": "mypy/server/update.py",
    "content": "\"\"\"Update build by processing changes using fine-grained dependencies.\n\nUse fine-grained dependencies to update targets in other modules that\nmay be affected by externally-visible changes in the changed modules.\n\nThis forms the core of the fine-grained incremental daemon mode. This\nmodule is not used at all by the 'classic' (non-daemon) incremental\nmode.\n\nHere is some motivation for this mode:\n\n* By keeping program state in memory between incremental runs, we\n  only have to process changed modules, not their dependencies. The\n  classic incremental mode has to deserialize the symbol tables of\n  all dependencies of changed modules, which can be slow for large\n  programs.\n\n* Fine-grained dependencies allow processing only the relevant parts\n  of modules indirectly affected by a change. Say, if only one function\n  in a large module is affected by a change in another module, only this\n  function is processed. The classic incremental mode always processes\n  an entire file as a unit, which is typically much slower.\n\n* It's possible to independently process individual modules within an\n  import cycle (SCC). Small incremental changes can be fast independent\n  of the size of the related SCC. In classic incremental mode, any change\n  within a SCC requires the entire SCC to be processed, which can slow\n  things down considerably.\n\nSome terms:\n\n* A *target* is a function/method definition or the top level of a module.\n  We refer to targets using their fully qualified name (e.g.\n  'mod.Cls.method'). Targets are the smallest units of processing during\n  fine-grained incremental checking.\n\n* A *trigger* represents the properties of a part of a program, and it\n  gets triggered/fired when these properties change. For example,\n  '<mod.func>' refers to a module-level function. It gets triggered if\n  the signature of the function changes, or if the function is removed,\n  for example.\n\nSome program state is maintained across multiple build increments in\nmemory:\n\n* The full ASTs of all modules are stored in memory all the time (this\n  includes the type map).\n\n* A fine-grained dependency map is maintained, which maps triggers to\n  affected program locations (these can be targets, triggers, or\n  classes). The latter determine what other parts of a program need to\n  be processed again due to a fired trigger.\n\nHere's a summary of how a fine-grained incremental program update happens:\n\n* Determine which modules have changes in their source code since the\n  previous update.\n\n* Process changed modules one at a time. Perform a separate full update\n  for each changed module, but only report the errors after all modules\n  have been processed, since the intermediate states can generate bogus\n  errors due to only seeing a partial set of changes.\n\n* Each changed module is processed in full. We parse the module, and\n  run semantic analysis to create a new AST and symbol table for the\n  module. Reuse the existing ASTs and symbol tables of modules that\n  have no changes in their source code. At the end of this stage, we have\n  two ASTs and symbol tables for the changed module (the old and the new\n  versions). The latter AST has not yet been type checked.\n\n* Take a snapshot of the old symbol table. This is used later to determine\n  which properties of the module have changed and which triggers to fire.\n\n* Merge the old AST with the new AST, preserving the identities of\n  externally visible AST nodes for which we can find a corresponding node\n  in the new AST. (Look at mypy.server.astmerge for the details.) This\n  way all external references to AST nodes in the changed module will\n  continue to point to the right nodes (assuming they still have a valid\n  target).\n\n* Type check the new module.\n\n* Take another snapshot of the symbol table of the changed module.\n  Look at the differences between the old and new snapshots to determine\n  which parts of the changed modules have changed. The result is a set of\n  fired triggers.\n\n* Using the dependency map and the fired triggers, decide which other\n  targets have become stale and need to be reprocessed.\n\n* Create new fine-grained dependencies for the changed module. We don't\n  garbage collect old dependencies, since extra dependencies are relatively\n  harmless (they take some memory and can theoretically slow things down\n  a bit by causing redundant work). This is implemented in\n  mypy.server.deps.\n\n* Strip the stale AST nodes that we found above. This returns them to a\n  state resembling the end of semantic analysis pass 1. We'll run semantic\n  analysis again on the existing AST nodes, and since semantic analysis\n  is not idempotent, we need to revert some changes made during semantic\n  analysis. This is implemented in mypy.server.aststrip.\n\n* Run semantic analyzer passes 2 and 3 on the stale AST nodes, and type\n  check them. We also need to do the symbol table snapshot comparison\n  dance to find any changes, and we need to merge ASTs to preserve AST node\n  identities.\n\n* If some triggers haven been fired, continue processing and repeat the\n  previous steps until no triggers are fired.\n\nThis is module is tested using end-to-end fine-grained incremental mode\ntest cases (test-data/unit/fine-grained*.test).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport re\nimport sys\nimport time\nfrom collections.abc import Callable, Sequence\nfrom typing import Final, NamedTuple, TypeAlias as _TypeAlias\n\nfrom mypy.build import (\n    DEBUG_FINE_GRAINED,\n    FAKE_ROOT_MODULE,\n    BuildManager,\n    BuildResult,\n    Graph,\n    State,\n    SuppressionReason,\n    load_graph,\n    process_fresh_modules,\n)\nfrom mypy.checker import FineGrainedDeferredNode\nfrom mypy.errors import CompileError\nfrom mypy.fscache import FileSystemCache\nfrom mypy.modulefinder import BuildSource\nfrom mypy.nodes import (\n    Decorator,\n    FuncBase,\n    FuncDef,\n    ImportFrom,\n    MypyFile,\n    OverloadedFuncDef,\n    SymbolNode,\n    SymbolTable,\n    TypeInfo,\n)\nfrom mypy.options import Options\nfrom mypy.semanal_main import semantic_analysis_for_scc, semantic_analysis_for_targets\nfrom mypy.server.astdiff import (\n    SymbolSnapshot,\n    compare_symbol_table_snapshots,\n    snapshot_symbol_table,\n)\nfrom mypy.server.astmerge import merge_asts\nfrom mypy.server.aststrip import strip_target\nfrom mypy.server.deps import get_dependencies_of_target, merge_dependencies\nfrom mypy.server.target import trigger_to_target\nfrom mypy.server.trigger import WILDCARD_TAG, make_trigger\nfrom mypy.typestate import type_state\nfrom mypy.util import is_stdlib_file, module_prefix, split_target\n\nMAX_ITER: Final = 1000\n\n# These are modules beyond stdlib that have some special meaning for mypy.\nSENSITIVE_INTERNAL_MODULES = (\"mypy_extensions\", \"typing_extensions\")\n\n\nclass FineGrainedBuildManager:\n    def __init__(self, result: BuildResult) -> None:\n        \"\"\"Initialize fine-grained build based on a batch build.\n\n        Args:\n            result: Result from the initialized build.\n                    The manager and graph will be taken over by this class.\n            manager: State of the build (mutated by this class)\n            graph: Additional state of the build (mutated by this class)\n        \"\"\"\n        manager = result.manager\n        self.manager = manager\n        self.graph = result.graph\n        self.previous_modules = get_module_to_path_map(self.graph)\n        self.deps = manager.fg_deps\n        # Merge in any root dependencies that may not have been loaded\n        merge_dependencies(manager.load_fine_grained_deps(FAKE_ROOT_MODULE), self.deps)\n        self.previous_targets_with_errors = manager.errors.targets()\n        self.previous_messages: list[str] = result.errors.copy()\n        # Module, if any, that had blocking errors in the last run as (id, path) tuple.\n        self.blocking_error: tuple[str, str] | None = None\n        # Module that we haven't processed yet but that are known to be stale.\n        self.stale: list[tuple[str, str]] = []\n        # Disable the cache so that load_graph doesn't try going back to disk\n        # for the cache.\n        self.manager.cache_enabled = False\n\n        # Some hints to the test suite about what is going on:\n        # Active triggers during the last update\n        self.triggered: list[str] = []\n        # Modules passed to update during the last update\n        self.changed_modules: list[tuple[str, str]] = []\n        # Modules processed during the last update\n        self.updated_modules: list[str] = []\n        # Targets processed during last update (for testing only).\n        self.processed_targets: list[str] = []\n\n    def update(\n        self,\n        changed_modules: list[tuple[str, str]],\n        removed_modules: list[tuple[str, str]],\n        followed: bool = False,\n    ) -> list[str]:\n        \"\"\"Update previous build result by processing changed modules.\n\n        Also propagate changes to other modules as needed, but only process\n        those parts of other modules that are affected by the changes. Retain\n        the existing ASTs and symbol tables of unaffected modules.\n\n        Reuses original BuildManager and Graph.\n\n        Args:\n            changed_modules: Modules changed since the previous update/build; each is\n                a (module id, path) tuple. Includes modified and added modules.\n                Assume this is correct; it's not validated here.\n            removed_modules: Modules that have been deleted since the previous update\n                or removed from the build.\n            followed: If True, the modules were found through following imports\n\n        Returns:\n            A list of errors.\n        \"\"\"\n        self.processed_targets.clear()\n        changed_modules = changed_modules + removed_modules\n        removed_set = {module for module, _ in removed_modules}\n        self.changed_modules = changed_modules\n\n        if not changed_modules:\n            return self.previous_messages\n\n        # Reset find_module's caches for the new build.\n        self.manager.find_module_cache.clear()\n\n        self.triggered = []\n        self.updated_modules = []\n        changed_modules = dedupe_modules(changed_modules + self.stale)\n        initial_set = {id for id, _ in changed_modules}\n        self.manager.log_fine_grained(\n            \"==== update %s ====\" % \", \".join(repr(id) for id, _ in changed_modules)\n        )\n        if self.previous_targets_with_errors and is_verbose(self.manager):\n            self.manager.log_fine_grained(\n                \"previous targets with errors: %s\" % sorted(self.previous_targets_with_errors)\n            )\n\n        blocking_error = None\n        if self.blocking_error:\n            # Handle blocking errors first. We'll exit as soon as we find a\n            # module that still has blocking errors.\n            self.manager.log_fine_grained(f\"existing blocker: {self.blocking_error[0]}\")\n            changed_modules = dedupe_modules([self.blocking_error] + changed_modules)\n            blocking_error = self.blocking_error[0]\n            self.blocking_error = None\n\n        while True:\n            result = self.update_one(\n                changed_modules, initial_set, removed_set, blocking_error, followed\n            )\n            changed_modules, (next_id, next_path), blocker_messages = result\n\n            if blocker_messages is not None:\n                self.blocking_error = (next_id, next_path)\n                self.stale = changed_modules\n                messages = blocker_messages\n                break\n\n            # It looks like we are done processing everything, so now\n            # reprocess all targets with errors. We are careful to\n            # support the possibility that reprocessing an errored module\n            # might trigger loading of a module, but I am not sure\n            # if this can really happen.\n            if not changed_modules:\n                # N.B: We just checked next_id, so manager.errors contains\n                # the errors from it. Thus we consider next_id up to date\n                # when propagating changes from the errored targets,\n                # which prevents us from reprocessing errors in it.\n                changed_modules = propagate_changes_using_dependencies(\n                    self.manager,\n                    self.graph,\n                    self.deps,\n                    set(),\n                    {next_id},\n                    self.previous_targets_with_errors,\n                    self.processed_targets,\n                )\n                changed_modules = dedupe_modules(changed_modules)\n                if not changed_modules:\n                    # Preserve state needed for the next update.\n                    self.previous_targets_with_errors = self.manager.errors.targets()\n                    messages = self.manager.errors.new_messages()\n                    break\n\n        messages = sort_messages_preserving_file_order(messages, self.previous_messages)\n        self.previous_messages = messages.copy()\n        return messages\n\n    def trigger(self, target: str) -> list[str]:\n        \"\"\"Trigger a specific target explicitly.\n\n        This is intended for use by the suggestions engine.\n        \"\"\"\n        self.manager.errors.reset()\n        changed_modules = propagate_changes_using_dependencies(\n            self.manager,\n            self.graph,\n            self.deps,\n            set(),\n            set(),\n            self.previous_targets_with_errors | {target},\n            [],\n        )\n        # Preserve state needed for the next update.\n        self.previous_targets_with_errors = self.manager.errors.targets()\n        self.previous_messages = self.manager.errors.new_messages().copy()\n        return self.update(changed_modules, [])\n\n    def flush_cache(self) -> None:\n        \"\"\"Flush AST cache.\n\n        This needs to be called after each increment, or file changes won't\n        be detected reliably.\n        \"\"\"\n        self.manager.ast_cache.clear()\n\n    def update_one(\n        self,\n        changed_modules: list[tuple[str, str]],\n        initial_set: set[str],\n        removed_set: set[str],\n        blocking_error: str | None,\n        followed: bool,\n    ) -> tuple[list[tuple[str, str]], tuple[str, str], list[str] | None]:\n        \"\"\"Process a module from the list of changed modules.\n\n        Returns:\n            Tuple with these items:\n\n            - Updated list of pending changed modules as (module id, path) tuples\n            - Module which was actually processed as (id, path) tuple\n            - If there was a blocking error, the error messages from it\n        \"\"\"\n        t0 = time.time()\n        next_id, next_path = changed_modules.pop(0)\n\n        # If we have a module with a blocking error that is no longer\n        # in the import graph, we must skip it as otherwise we'll be\n        # stuck with the blocking error.\n        if (\n            next_id == blocking_error\n            and next_id not in self.previous_modules\n            and next_id not in initial_set\n        ):\n            self.manager.log_fine_grained(\n                f\"skip {next_id!r} (module with blocking error not in import graph)\"\n            )\n            return changed_modules, (next_id, next_path), None\n\n        result = self.update_module(next_id, next_path, next_id in removed_set, followed)\n        remaining, (next_id, next_path), blocker_messages = result\n        changed_modules = [(id, path) for id, path in changed_modules if id != next_id]\n        changed_modules = dedupe_modules(remaining + changed_modules)\n        t1 = time.time()\n\n        self.manager.log_fine_grained(\n            f\"update once: {next_id} in {t1 - t0:.3f}s - {len(changed_modules)} left\"\n        )\n\n        return changed_modules, (next_id, next_path), blocker_messages\n\n    def update_module(\n        self, module: str, path: str, force_removed: bool, followed: bool\n    ) -> tuple[list[tuple[str, str]], tuple[str, str], list[str] | None]:\n        \"\"\"Update a single modified module.\n\n        If the module contains imports of previously unseen modules, only process one of\n        the new modules and return the remaining work to be done.\n\n        Args:\n            module: Id of the module\n            path: File system path of the module\n            force_removed: If True, consider module removed from the build even if path\n                exists (used for removing an existing file from the build)\n            followed: Was this found via import following?\n\n        Returns:\n            Tuple with these items:\n\n            - Remaining modules to process as (module id, path) tuples\n            - Module which was actually processed as (id, path) tuple\n            - If there was a blocking error, the error messages from it\n        \"\"\"\n        self.manager.log_fine_grained(f\"--- update single {module!r} ---\")\n        self.updated_modules.append(module)\n\n        # builtins and friends could potentially get triggered because\n        # of protocol stuff, but nothing good could possibly come from\n        # actually updating them.\n        if (\n            is_stdlib_file(self.manager.options.abs_custom_typeshed_dir, path)\n            or module in SENSITIVE_INTERNAL_MODULES\n        ):\n            return [], (module, path), None\n\n        manager = self.manager\n        previous_modules = self.previous_modules\n        graph = self.graph\n\n        ensure_deps_loaded(module, self.deps, graph)\n\n        # If this is an already existing module, make sure that we have\n        # its tree loaded so that we can snapshot it for comparison.\n        ensure_trees_loaded(manager, graph, [module])\n\n        t0 = time.time()\n        # Record symbol table snapshot of old version the changed module.\n        old_snapshots: dict[str, dict[str, SymbolSnapshot]] = {}\n        if module in manager.modules:\n            snapshot = snapshot_symbol_table(module, manager.modules[module].names)\n            old_snapshots[module] = snapshot\n\n        manager.errors.reset()\n        self.processed_targets.append(module)\n        result = update_module_isolated(\n            module, path, manager, previous_modules, graph, force_removed, followed\n        )\n        if isinstance(result, BlockedUpdate):\n            # Blocking error -- just give up\n            module, path, remaining, errors = result\n            self.previous_modules = get_module_to_path_map(graph)\n            return remaining, (module, path), errors\n        assert isinstance(result, NormalUpdate)  # Work around #4124\n        module, path, remaining, tree = result\n\n        # TODO: What to do with stale dependencies?\n        t1 = time.time()\n        triggered = calculate_active_triggers(manager, old_snapshots, {module: tree})\n        if is_verbose(self.manager):\n            filtered = [trigger for trigger in triggered if not trigger.endswith(\"__>\")]\n            self.manager.log_fine_grained(f\"triggered: {sorted(filtered)!r}\")\n        self.triggered.extend(triggered | self.previous_targets_with_errors)\n        if module in graph:\n            graph[module].update_fine_grained_deps(self.deps)\n            graph[module].free_state()\n        remaining += propagate_changes_using_dependencies(\n            manager,\n            graph,\n            self.deps,\n            triggered,\n            {module},\n            targets_with_errors=set(),\n            processed_targets=self.processed_targets,\n        )\n        t2 = time.time()\n        manager.add_stats(update_isolated_time=t1 - t0, propagate_time=t2 - t1)\n\n        # Preserve state needed for the next update.\n        self.previous_targets_with_errors.update(manager.errors.targets())\n        self.previous_modules = get_module_to_path_map(graph)\n\n        return remaining, (module, path), None\n\n\ndef find_unloaded_deps(\n    manager: BuildManager, graph: dict[str, State], initial: Sequence[str]\n) -> list[str]:\n    \"\"\"Find all the deps of the nodes in initial that haven't had their tree loaded.\n\n    The key invariant here is that if a module is loaded, so are all\n    of their dependencies. This means that when we encounter a loaded\n    module, we don't need to explore its dependencies.  (This\n    invariant is slightly violated when dependencies are added, which\n    can be handled by calling find_unloaded_deps directly on the new\n    dependencies.)\n    \"\"\"\n    worklist = list(initial)\n    seen: set[str] = set()\n    unloaded = []\n    while worklist:\n        node = worklist.pop()\n        if node in seen or node not in graph:\n            continue\n        seen.add(node)\n        if node not in manager.modules:\n            ancestors = graph[node].ancestors or []\n            worklist.extend(graph[node].dependencies + ancestors)\n            unloaded.append(node)\n\n    return unloaded\n\n\ndef ensure_deps_loaded(module: str, deps: dict[str, set[str]], graph: dict[str, State]) -> None:\n    \"\"\"Ensure that the dependencies on a module are loaded.\n\n    Dependencies are loaded into the 'deps' dictionary.\n\n    This also requires loading dependencies from any parent modules,\n    since dependencies will get stored with parent modules when a module\n    doesn't exist.\n    \"\"\"\n    if module in graph and graph[module].fine_grained_deps_loaded:\n        return\n    parts = module.split(\".\")\n    for i in range(len(parts)):\n        base = \".\".join(parts[: i + 1])\n        if base in graph and not graph[base].fine_grained_deps_loaded:\n            merge_dependencies(graph[base].load_fine_grained_deps(), deps)\n            graph[base].fine_grained_deps_loaded = True\n\n\ndef ensure_trees_loaded(\n    manager: BuildManager, graph: dict[str, State], initial: Sequence[str]\n) -> None:\n    \"\"\"Ensure that the modules in initial and their deps have loaded trees.\"\"\"\n    to_process = find_unloaded_deps(manager, graph, initial)\n    if to_process:\n        if is_verbose(manager):\n            manager.log_fine_grained(\n                \"Calling process_fresh_modules on set of size {} ({})\".format(\n                    len(to_process), sorted(to_process)\n                )\n            )\n        process_fresh_modules(graph, to_process, manager)\n\n\n# The result of update_module_isolated when no blockers, with these items:\n#\n# - Id of the changed module (can be different from the module argument)\n# - Path of the changed module\n# - New AST for the changed module (None if module was deleted)\n# - Remaining changed modules that are not processed yet as (module id, path)\n#   tuples (non-empty if the original changed module imported other new\n#   modules)\nclass NormalUpdate(NamedTuple):\n    module: str\n    path: str\n    remaining: list[tuple[str, str]]\n    tree: MypyFile | None\n\n\n# The result of update_module_isolated when there is a blocking error. Items\n# are similar to NormalUpdate (but there are fewer).\nclass BlockedUpdate(NamedTuple):\n    module: str\n    path: str\n    remaining: list[tuple[str, str]]\n    messages: list[str]\n\n\nUpdateResult: _TypeAlias = NormalUpdate | BlockedUpdate\n\n\ndef update_module_isolated(\n    module: str,\n    path: str,\n    manager: BuildManager,\n    previous_modules: dict[str, str],\n    graph: Graph,\n    force_removed: bool,\n    followed: bool,\n) -> UpdateResult:\n    \"\"\"Build a new version of one changed module only.\n\n    Don't propagate changes to elsewhere in the program. Raise CompileError on\n    encountering a blocking error.\n\n    Args:\n        module: Changed module (modified, created or deleted)\n        path: Path of the changed module\n        manager: Build manager\n        graph: Build graph\n        force_removed: If True, consider the module removed from the build even it the\n            file exists\n\n    Returns a named tuple describing the result (see above for details).\n    \"\"\"\n    if module not in graph:\n        manager.log_fine_grained(f\"new module {module!r}\")\n\n    if not manager.fscache.isfile(path) or force_removed:\n        delete_module(module, path, graph, manager)\n        return NormalUpdate(module, path, [], None)\n\n    sources = get_sources(manager.fscache, previous_modules, [(module, path)], followed)\n\n    if module in manager.missing_modules:\n        del manager.missing_modules[module]\n\n    orig_module = module\n    orig_state = graph.get(module)\n    orig_tree = manager.modules.get(module)\n\n    def restore(ids: list[str]) -> None:\n        # For each of the modules in ids, restore that id's old\n        # manager.modules and graphs entries. (Except for the original\n        # module, this means deleting them.)\n        for id in ids:\n            if id == orig_module and orig_tree:\n                manager.modules[id] = orig_tree\n            elif id in manager.modules:\n                del manager.modules[id]\n            if id == orig_module and orig_state:\n                graph[id] = orig_state\n            elif id in graph:\n                del graph[id]\n\n    new_modules: list[State] = []\n    try:\n        if module in graph:\n            del graph[module]\n        load_graph(sources, manager, graph, new_modules)\n    except CompileError as err:\n        # Parse error somewhere in the program -- a blocker\n        assert err.module_with_blocker\n        restore([module] + [st.id for st in new_modules])\n        return BlockedUpdate(err.module_with_blocker, path, [], err.messages)\n\n    # Reparsing the file may have brought in dependencies that we\n    # didn't have before. Make sure that they are loaded to restore\n    # the invariant that a module having a loaded tree implies that\n    # its dependencies do as well.\n    ensure_trees_loaded(manager, graph, graph[module].dependencies)\n\n    # Find any other modules brought in by imports.\n    changed_modules = [(st.id, st.xpath) for st in new_modules]\n    for m in new_modules:\n        manager.import_map[m.id] = set(m.dependencies + m.suppressed)\n\n    # If there are multiple modules to process, only process one of them and return\n    # the remaining ones to the caller.\n    if len(changed_modules) > 1:\n        # As an optimization, look for a module that imports no other changed modules.\n        module, path = find_relative_leaf_module(changed_modules, graph)\n        changed_modules.remove((module, path))\n        remaining_modules = changed_modules\n        # The remaining modules haven't been processed yet so drop them.\n        restore([id for id, _ in remaining_modules])\n        manager.log_fine_grained(f\"--> {module!r} (newly imported)\")\n    else:\n        remaining_modules = []\n\n    state = graph[module]\n\n    # Process the changed file.\n    state.parse_file()\n    assert state.tree is not None, \"file must be at least parsed\"\n    t0 = time.time()\n    try:\n        semantic_analysis_for_scc(graph, [state.id], manager.errors)\n    except CompileError as err:\n        # There was a blocking error, so module AST is incomplete. Restore old modules.\n        restore([module])\n        return BlockedUpdate(module, path, remaining_modules, err.messages)\n\n    # Merge old and new ASTs.\n    new_modules_dict: dict[str, MypyFile | None] = {module: state.tree}\n    replace_modules_with_new_variants(manager, graph, {orig_module: orig_tree}, new_modules_dict)\n\n    t1 = time.time()\n    # Perform type checking.\n    state.type_checker().reset()\n    state.type_check_first_pass()\n    state.type_check_second_pass()\n    state.detect_possibly_undefined_vars()\n    state.generate_unused_ignore_notes()\n    state.generate_ignore_without_code_notes()\n    t2 = time.time()\n    state.finish_passes()\n    t3 = time.time()\n    manager.add_stats(semanal_time=t1 - t0, typecheck_time=t2 - t1, finish_passes_time=t3 - t2)\n\n    graph[module] = state\n\n    return NormalUpdate(module, path, remaining_modules, state.tree)\n\n\ndef find_relative_leaf_module(modules: list[tuple[str, str]], graph: Graph) -> tuple[str, str]:\n    \"\"\"Find a module in a list that directly imports no other module in the list.\n\n    If no such module exists, return the lexicographically first module from the list.\n    Always return one of the items in the modules list.\n\n    NOTE: If both 'abc' and 'typing' have changed, an effect of the above rule is that\n        we prefer 'abc', even if both are in the same SCC. This works around a false\n        positive in 'typing', at least in tests.\n\n    Args:\n        modules: List of (module, path) tuples (non-empty)\n        graph: Program import graph that contains all modules in the module list\n    \"\"\"\n    assert modules\n    # Sort for repeatable results.\n    modules = sorted(modules)\n    module_set = {module for module, _ in modules}\n    for module, path in modules:\n        state = graph[module]\n        if len(set(state.dependencies) & module_set) == 0:\n            # Found it!\n            return module, path\n    # Could not find any. Just return the first module (by lexicographic order).\n    return modules[0]\n\n\ndef delete_module(module_id: str, path: str, graph: Graph, manager: BuildManager) -> None:\n    manager.log_fine_grained(f\"delete module {module_id!r}\")\n    # TODO: Remove deps for the module (this only affects memory use, not correctness)\n    if module_id in graph:\n        del graph[module_id]\n    if module_id in manager.modules:\n        del manager.modules[module_id]\n    components = module_id.split(\".\")\n    if len(components) > 1:\n        # Delete reference to module in parent module.\n        parent_id = \".\".join(components[:-1])\n        # If parent module is ignored, it won't be included in the modules dictionary.\n        if parent_id in manager.modules:\n            parent = manager.modules[parent_id]\n            if components[-1] in parent.names:\n                del parent.names[components[-1]]\n    # If the module is removed from the build but still exists, then\n    # we mark it as missing so that it will get picked up by import from still.\n    if manager.fscache.isfile(path):\n        # TODO: check if there is an equivalent of #20800 for the daemon.\n        manager.missing_modules[module_id] = SuppressionReason.NOT_FOUND\n\n\ndef dedupe_modules(modules: list[tuple[str, str]]) -> list[tuple[str, str]]:\n    seen: set[str] = set()\n    result = []\n    for id, path in modules:\n        if id not in seen:\n            seen.add(id)\n            result.append((id, path))\n    return result\n\n\ndef get_module_to_path_map(graph: Graph) -> dict[str, str]:\n    return {module: node.xpath for module, node in graph.items()}\n\n\ndef get_sources(\n    fscache: FileSystemCache,\n    modules: dict[str, str],\n    changed_modules: list[tuple[str, str]],\n    followed: bool,\n) -> list[BuildSource]:\n    sources = []\n    for id, path in changed_modules:\n        if fscache.isfile(path):\n            sources.append(BuildSource(path, id, None, followed=followed))\n    return sources\n\n\ndef calculate_active_triggers(\n    manager: BuildManager,\n    old_snapshots: dict[str, dict[str, SymbolSnapshot]],\n    new_modules: dict[str, MypyFile | None],\n) -> set[str]:\n    \"\"\"Determine activated triggers by comparing old and new symbol tables.\n\n    For example, if only the signature of function m.f is different in the new\n    symbol table, return {'<m.f>'}.\n    \"\"\"\n    names: set[str] = set()\n    for id in new_modules:\n        snapshot1 = old_snapshots.get(id)\n        if snapshot1 is None:\n            names.add(id)\n            snapshot1 = {}\n        new = new_modules[id]\n        if new is None:\n            snapshot2 = snapshot_symbol_table(id, SymbolTable())\n            names.add(id)\n        else:\n            snapshot2 = snapshot_symbol_table(id, new.names)\n        diff = compare_symbol_table_snapshots(id, snapshot1, snapshot2)\n        package_nesting_level = id.count(\".\")\n        for item in diff.copy():\n            if item.count(\".\") <= package_nesting_level + 1 and item.split(\".\")[-1] not in (\n                \"__builtins__\",\n                \"__file__\",\n                \"__name__\",\n                \"__package__\",\n                \"__doc__\",\n            ):\n                # Activate catch-all wildcard trigger for top-level module changes (used for\n                # \"from m import *\"). This also gets triggered by changes to module-private\n                # entries, but as these unneeded dependencies only result in extra processing,\n                # it's a minor problem.\n                #\n                # TODO: Some __* names cause mistriggers. Fix the underlying issue instead of\n                #     special casing them here.\n                diff.add(id + WILDCARD_TAG)\n            if item.count(\".\") > package_nesting_level + 1:\n                # These are for changes within classes, used by protocols.\n                diff.add(item.rsplit(\".\", 1)[0] + WILDCARD_TAG)\n\n        names |= diff\n    return {make_trigger(name) for name in names}\n\n\ndef replace_modules_with_new_variants(\n    manager: BuildManager,\n    graph: dict[str, State],\n    old_modules: dict[str, MypyFile | None],\n    new_modules: dict[str, MypyFile | None],\n) -> None:\n    \"\"\"Replace modules with newly builds versions.\n\n    Retain the identities of externally visible AST nodes in the\n    old ASTs so that references to the affected modules from other\n    modules will still be valid (unless something was deleted or\n    replaced with an incompatible definition, in which case there\n    will be dangling references that will be handled by\n    propagate_changes_using_dependencies).\n    \"\"\"\n    for id in new_modules:\n        preserved_module = old_modules.get(id)\n        new_module = new_modules[id]\n        if preserved_module and new_module is not None:\n            merge_asts(preserved_module, preserved_module.names, new_module, new_module.names)\n            manager.modules[id] = preserved_module\n            graph[id].tree = preserved_module\n\n\ndef propagate_changes_using_dependencies(\n    manager: BuildManager,\n    graph: dict[str, State],\n    deps: dict[str, set[str]],\n    triggered: set[str],\n    up_to_date_modules: set[str],\n    targets_with_errors: set[str],\n    processed_targets: list[str],\n) -> list[tuple[str, str]]:\n    \"\"\"Transitively rechecks targets based on triggers and the dependency map.\n\n    Returns a list (module id, path) tuples representing modules that contain\n    a target that needs to be reprocessed but that has not been parsed yet.\n\n    Processed targets should be appended to processed_targets (used in tests only,\n    to test the order of processing targets).\n    \"\"\"\n\n    num_iter = 0\n    remaining_modules: list[tuple[str, str]] = []\n\n    # Propagate changes until nothing visible has changed during the last\n    # iteration.\n    while triggered or targets_with_errors:\n        num_iter += 1\n        if num_iter > MAX_ITER:\n            raise RuntimeError(\"Max number of iterations (%d) reached (endless loop?)\" % MAX_ITER)\n\n        todo, unloaded, stale_protos = find_targets_recursive(\n            manager, graph, triggered, deps, up_to_date_modules\n        )\n        # TODO: we sort to make it deterministic, but this is *incredibly* ad hoc\n        remaining_modules.extend((id, graph[id].xpath) for id in sorted(unloaded))\n        # Also process targets that used to have errors, as otherwise some\n        # errors might be lost.\n        for target in targets_with_errors:\n            id = module_prefix(graph, target)\n            if id is not None and id not in up_to_date_modules:\n                if id not in todo:\n                    todo[id] = set()\n                manager.log_fine_grained(f\"process target with error: {target}\")\n                more_nodes, _ = lookup_target(manager, target, id)\n                todo[id].update(more_nodes)\n        triggered = set()\n        # First invalidate subtype caches in all stale protocols.\n        # We need to do this to avoid false negatives if the protocol itself is\n        # unchanged, but was marked stale because its sub- (or super-) type changed.\n        for info in stale_protos:\n            type_state.reset_subtype_caches_for(info)\n        # Then fully reprocess all targets.\n        # TODO: Preserve order (set is not optimal)\n        for id, nodes in sorted(todo.items(), key=lambda x: x[0]):\n            assert id not in up_to_date_modules\n            triggered |= reprocess_nodes(manager, graph, id, nodes, deps, processed_targets)\n        # Changes elsewhere may require us to reprocess modules that were\n        # previously considered up to date. For example, there may be a\n        # dependency loop that loops back to an originally processed module.\n        up_to_date_modules = set()\n        targets_with_errors = set()\n        if is_verbose(manager):\n            manager.log_fine_grained(f\"triggered: {list(triggered)!r}\")\n\n    return remaining_modules\n\n\ndef find_targets_recursive(\n    manager: BuildManager,\n    graph: Graph,\n    triggers: set[str],\n    deps: dict[str, set[str]],\n    up_to_date_modules: set[str],\n) -> tuple[dict[str, set[FineGrainedDeferredNode]], set[str], set[TypeInfo]]:\n    \"\"\"Find names of all targets that need to reprocessed, given some triggers.\n\n    Returns: A tuple containing a:\n     * Dictionary from module id to a set of stale targets.\n     * A set of module ids for unparsed modules with stale targets.\n    \"\"\"\n    result: dict[str, set[FineGrainedDeferredNode]] = {}\n    worklist = triggers\n    processed: set[str] = set()\n    stale_protos: set[TypeInfo] = set()\n    unloaded_files: set[str] = set()\n\n    # Find AST nodes corresponding to each target.\n    #\n    # TODO: Don't rely on a set, since the items are in an unpredictable order.\n    while worklist:\n        processed |= worklist\n        current = worklist\n        worklist = set()\n        for target in current:\n            if target.startswith(\"<\"):\n                module_id = module_prefix(graph, trigger_to_target(target))\n                if module_id:\n                    ensure_deps_loaded(module_id, deps, graph)\n\n                worklist |= deps.get(target, set()) - processed\n            else:\n                module_id = module_prefix(graph, target)\n                if module_id is None:\n                    # Deleted module.\n                    continue\n                if module_id in up_to_date_modules:\n                    # Already processed.\n                    continue\n                if (\n                    module_id not in manager.modules\n                    or manager.modules[module_id].is_cache_skeleton\n                ):\n                    # We haven't actually parsed and checked the module, so we don't have\n                    # access to the actual nodes.\n                    # Add it to the queue of files that need to be processed fully.\n                    unloaded_files.add(module_id)\n                    continue\n\n                if module_id not in result:\n                    result[module_id] = set()\n                manager.log_fine_grained(f\"process: {target}\")\n                deferred, stale_proto = lookup_target(manager, target, module_id)\n                if stale_proto:\n                    stale_protos.add(stale_proto)\n                result[module_id].update(deferred)\n\n    return result, unloaded_files, stale_protos\n\n\ndef reprocess_nodes(\n    manager: BuildManager,\n    graph: dict[str, State],\n    module_id: str,\n    nodeset: set[FineGrainedDeferredNode],\n    deps: dict[str, set[str]],\n    processed_targets: list[str],\n) -> set[str]:\n    \"\"\"Reprocess a set of nodes within a single module.\n\n    Return fired triggers.\n    \"\"\"\n    if module_id not in graph:\n        manager.log_fine_grained(\"%s not in graph (blocking errors or deleted?)\" % module_id)\n        return set()\n\n    file_node = manager.modules[module_id]\n    old_symbols = find_symbol_tables_recursive(file_node.fullname, file_node.names)\n    old_symbols = {name: names.copy() for name, names in old_symbols.items()}\n    old_symbols_snapshot = snapshot_symbol_table(file_node.fullname, file_node.names)\n\n    def key(node: FineGrainedDeferredNode) -> int:\n        # Unlike modules which are sorted by name within SCC,\n        # nodes within the same module are sorted by line number, because\n        # this is how they are processed in normal mode.\n        return node.node.line\n\n    nodes = sorted(nodeset, key=key)\n\n    state = graph[module_id]\n    options = state.options\n    manager.errors.set_file_ignored_lines(\n        file_node.path, file_node.ignored_lines, options.ignore_errors or state.ignore_all\n    )\n    manager.errors.set_skipped_lines(file_node.path, file_node.skipped_lines)\n\n    targets = set()\n    for node in nodes:\n        target = target_from_node(module_id, node.node)\n        if target is not None:\n            targets.add(target)\n    manager.errors.clear_errors_in_targets(file_node.path, targets)\n\n    # If one of the nodes is the module itself, emit any errors that\n    # happened before semantic analysis.\n    for target in targets:\n        if target == module_id:\n            for info in graph[module_id].early_errors:\n                manager.errors.add_error_info(info, file=graph[module_id].xpath)\n\n    # Strip semantic analysis information.\n    for deferred in nodes:\n        processed_targets.append(deferred.node.fullname)\n        strip_target(deferred.node)\n    semantic_analysis_for_targets(graph[module_id], nodes, graph)\n    # Merge symbol tables to preserve identities of AST nodes. The file node will remain\n    # the same, but other nodes may have been recreated with different identities, such as\n    # NamedTuples defined using assignment statements.\n    new_symbols = find_symbol_tables_recursive(file_node.fullname, file_node.names)\n    for name in old_symbols:\n        if name in new_symbols:\n            merge_asts(file_node, old_symbols[name], file_node, new_symbols[name])\n\n    # Type check.\n    checker = graph[module_id].type_checker()\n    checker.reset()\n    # We seem to need additional passes in fine-grained incremental mode.\n    checker.pass_num = 0\n    checker.last_pass = 3\n    # It is tricky to reliably invalidate constructor cache in fine-grained increments.\n    # See PR 19514 description for details.\n    more = checker.check_second_pass(nodes, allow_constructor_cache=False)\n    while more:\n        more = False\n        if graph[module_id].type_checker().check_second_pass(allow_constructor_cache=False):\n            more = True\n\n    if manager.options.export_types:\n        manager.all_types.update(graph[module_id].type_map())\n\n    new_symbols_snapshot = snapshot_symbol_table(file_node.fullname, file_node.names)\n    # Check if any attribute types were changed and need to be propagated further.\n    changed = compare_symbol_table_snapshots(\n        file_node.fullname, old_symbols_snapshot, new_symbols_snapshot\n    )\n    new_triggered = {make_trigger(name) for name in changed}\n\n    # Dependencies may have changed.\n    update_deps(module_id, nodes, graph, deps, options)\n\n    # Report missing imports.\n    graph[module_id].verify_dependencies()\n\n    graph[module_id].free_state()\n\n    return new_triggered\n\n\ndef find_symbol_tables_recursive(prefix: str, symbols: SymbolTable) -> dict[str, SymbolTable]:\n    \"\"\"Find all nested symbol tables.\n\n    Args:\n        prefix: Full name prefix (used for return value keys and to filter result so that\n            cross references to other modules aren't included)\n        symbols: Root symbol table\n\n    Returns a dictionary from full name to corresponding symbol table.\n    \"\"\"\n    result = {prefix: symbols}\n    for name, node in symbols.items():\n        if isinstance(node.node, TypeInfo) and node.node.fullname.startswith(prefix + \".\"):\n            more = find_symbol_tables_recursive(prefix + \".\" + name, node.node.names)\n            result.update(more)\n    return result\n\n\ndef update_deps(\n    module_id: str,\n    nodes: list[FineGrainedDeferredNode],\n    graph: dict[str, State],\n    deps: dict[str, set[str]],\n    options: Options,\n) -> None:\n    for deferred in nodes:\n        node = deferred.node\n        type_map = graph[module_id].type_map()\n        tree = graph[module_id].tree\n        assert tree is not None, \"Tree must be processed at this stage\"\n        new_deps = get_dependencies_of_target(\n            module_id, tree, node, type_map, options.python_version\n        )\n        for trigger, targets in new_deps.items():\n            deps.setdefault(trigger, set()).update(targets)\n    # Merge also the newly added protocol deps (if any).\n    type_state.update_protocol_deps(deps)\n\n\ndef lookup_target(\n    manager: BuildManager, target: str, module_id: str\n) -> tuple[list[FineGrainedDeferredNode], TypeInfo | None]:\n    \"\"\"Look up a target by fully-qualified name.\n\n    The first item in the return tuple is a list of deferred nodes that\n    needs to be reprocessed. If the target represents a TypeInfo corresponding\n    to a protocol, return it as a second item in the return tuple, otherwise None.\n    \"\"\"\n    deferred, stale_proto = _lookup_target_impl(manager, target)\n\n    # If there are function targets that can infer outer variables, they should\n    # be re-processed as part of the module top-level instead (for consistency).\n    regular = []\n    shared = []\n    for d in deferred:\n        if isinstance(d.node, FuncBase) and d.node.def_or_infer_vars:\n            shared.append(d)\n        else:\n            regular.append(d)\n    deferred = regular\n    if shared:\n        deferred.append(FineGrainedDeferredNode(manager.modules[module_id], None))\n    return deferred, stale_proto\n\n\ndef _lookup_target_impl(\n    manager: BuildManager, target: str\n) -> tuple[list[FineGrainedDeferredNode], TypeInfo | None]:\n    def not_found() -> None:\n        manager.log_fine_grained(f\"Can't find matching target for {target} (stale dependency?)\")\n\n    modules = manager.modules\n    items = split_target(modules, target)\n    if items is None:\n        not_found()  # Stale dependency\n        return [], None\n    module, rest = items\n    if rest:\n        components = rest.split(\".\")\n    else:\n        components = []\n    node: SymbolNode | None = modules[module]\n    file: MypyFile | None = None\n    active_class = None\n    for c in components:\n        if isinstance(node, TypeInfo):\n            active_class = node\n        if isinstance(node, MypyFile):\n            file = node\n        if not isinstance(node, (MypyFile, TypeInfo)) or c not in node.names:\n            not_found()  # Stale dependency\n            return [], None\n        # Don't reprocess plugin generated targets. They should get\n        # stripped and regenerated when the containing target is\n        # reprocessed.\n        if node.names[c].plugin_generated:\n            return [], None\n        node = node.names[c].node\n    if isinstance(node, TypeInfo):\n        # A ClassDef target covers the body of the class and everything defined\n        # within it.  To get the body we include the entire surrounding target,\n        # typically a module top-level, since we don't support processing class\n        # bodies as separate entities for simplicity.\n        assert file is not None\n        if node.fullname != target:\n            # This is a reference to a different TypeInfo, likely due to a stale dependency.\n            # Processing them would spell trouble -- for example, we could be refreshing\n            # a deserialized TypeInfo with missing attributes.\n            not_found()\n            return [], None\n        result = [FineGrainedDeferredNode(file, None)]\n        stale_info: TypeInfo | None = None\n        if node.is_protocol:\n            stale_info = node\n        for name, symnode in node.names.items():\n            node = symnode.node\n            if isinstance(node, FuncDef):\n                method, _ = _lookup_target_impl(manager, target + \".\" + name)\n                result.extend(method)\n        return result, stale_info\n    if isinstance(node, Decorator):\n        # Decorator targets actually refer to the function definition only.\n        node = node.func\n    if not isinstance(node, (FuncDef, MypyFile, OverloadedFuncDef)):\n        # The target can't be refreshed. It's possible that the target was\n        # changed to another type and we have a stale dependency pointing to it.\n        not_found()\n        return [], None\n    if node.fullname != target:\n        # Stale reference points to something unexpected. We shouldn't process since the\n        # context will be wrong and it could be a partially initialized deserialized node.\n        not_found()\n        return [], None\n    return [FineGrainedDeferredNode(node, active_class)], None\n\n\ndef is_verbose(manager: BuildManager) -> bool:\n    return manager.options.verbosity >= 1 or DEBUG_FINE_GRAINED\n\n\ndef target_from_node(module: str, node: FuncDef | MypyFile | OverloadedFuncDef) -> str | None:\n    \"\"\"Return the target name corresponding to a deferred node.\n\n    Args:\n        module: Must be module id of the module that defines 'node'\n\n    Returns the target name, or None if the node is not a valid target in the given\n    module (for example, if it's actually defined in another module).\n    \"\"\"\n    if isinstance(node, MypyFile):\n        if module != node.fullname:\n            # Actually a reference to another module -- likely a stale dependency.\n            return None\n        return module\n    else:  # OverloadedFuncDef or FuncDef\n        if node.info:\n            return f\"{node.info.fullname}.{node.name}\"\n        else:\n            return f\"{module}.{node.name}\"\n\n\nif sys.platform != \"win32\":\n    INIT_SUFFIXES: Final = (\"/__init__.py\", \"/__init__.pyi\")\nelse:\n    INIT_SUFFIXES: Final = (\n        os.sep + \"__init__.py\",\n        os.sep + \"__init__.pyi\",\n        os.altsep + \"__init__.py\",\n        os.altsep + \"__init__.pyi\",\n    )\n\n\ndef refresh_suppressed_submodules(\n    module: str,\n    path: str | None,\n    deps: dict[str, set[str]],\n    graph: Graph,\n    fscache: FileSystemCache,\n    refresh_file: Callable[[str, str], list[str]],\n) -> list[str] | None:\n    \"\"\"Look for submodules that are now suppressed in target package.\n\n    If a submodule a.b gets added, we need to mark it as suppressed\n    in modules that contain \"from a import b\". Previously we assumed\n    that 'a.b' is not a module but a regular name.\n\n    This is only relevant when following imports normally.\n\n    Args:\n        module: target package in which to look for submodules\n        path: path of the module\n        refresh_file: function that reads the AST of a module (returns error messages)\n\n    Return a list of errors from refresh_file() if it was called. If the\n    return value is None, we didn't call refresh_file().\n    \"\"\"\n    messages = None\n    if path is None or not path.endswith(INIT_SUFFIXES):\n        # Only packages have submodules.\n        return None\n    # Find any submodules present in the directory.\n    pkgdir = os.path.dirname(path)\n    try:\n        entries = fscache.listdir(pkgdir)\n    except FileNotFoundError:\n        entries = []\n    for fnam in entries:\n        if (\n            not fnam.endswith((\".py\", \".pyi\"))\n            or fnam.startswith(\"__init__.\")\n            or fnam.count(\".\") != 1\n        ):\n            continue\n        shortname = fnam.split(\".\")[0]\n        submodule = module + \".\" + shortname\n        trigger = make_trigger(submodule)\n\n        # We may be missing the required fine-grained deps.\n        ensure_deps_loaded(module, deps, graph)\n\n        if trigger in deps:\n            for dep in deps[trigger]:\n                # We can ignore <...> deps since a submodule can't trigger any.\n                state = graph.get(dep)\n                if not state:\n                    # Maybe it's a non-top-level target. We only care about the module.\n                    dep_module = module_prefix(graph, dep)\n                    if dep_module is not None:\n                        state = graph.get(dep_module)\n                if state:\n                    # Is the file may missing an AST in case it's read from cache?\n                    if state.tree is None:\n                        # Create AST for the file. This may produce some new errors\n                        # that we need to propagate.\n                        assert state.path is not None\n                        messages = refresh_file(state.id, state.path)\n                    tree = state.tree\n                    assert tree  # Will be fine, due to refresh_file() above\n                    for imp in tree.imports:\n                        if isinstance(imp, ImportFrom):\n                            if (\n                                imp.id == module\n                                and any(name == shortname for name, _ in imp.names)\n                                and submodule not in state.suppressed_set\n                            ):\n                                state.suppressed.append(submodule)\n                                state.suppressed_set.add(submodule)\n    return messages\n\n\ndef extract_fnam_from_message(message: str) -> str | None:\n    m = re.match(r\"([^:]+):[0-9]+: (error|note): \", message)\n    if m:\n        return m.group(1)\n    return None\n\n\ndef extract_possible_fnam_from_message(message: str) -> str:\n    # This may return non-path things if there is some random colon on the line\n    return message.split(\":\", 1)[0]\n\n\ndef sort_messages_preserving_file_order(\n    messages: list[str], prev_messages: list[str]\n) -> list[str]:\n    \"\"\"Sort messages so that the order of files is preserved.\n\n    An update generates messages so that the files can be in a fairly\n    arbitrary order.  Preserve the order of files to avoid messages\n    getting reshuffled continuously.  If there are messages in\n    additional files, sort them towards the end.\n    \"\"\"\n    # Calculate file order from the previous messages\n    n = 0\n    order = {}\n    for msg in prev_messages:\n        fnam = extract_fnam_from_message(msg)\n        if fnam and fnam not in order:\n            order[fnam] = n\n            n += 1\n\n    # Related messages must be sorted as a group of successive lines\n    groups = []\n    i = 0\n    while i < len(messages):\n        msg = messages[i]\n        maybe_fnam = extract_possible_fnam_from_message(msg)\n        group = [msg]\n        if maybe_fnam in order:\n            # This looks like a file name. Collect all lines related to this message.\n            while (\n                i + 1 < len(messages)\n                and extract_possible_fnam_from_message(messages[i + 1]) not in order\n                and extract_fnam_from_message(messages[i + 1]) is None\n                and not messages[i + 1].startswith(\"mypy: \")\n            ):\n                i += 1\n                group.append(messages[i])\n        groups.append((order.get(maybe_fnam, n), group))\n        i += 1\n\n    groups = sorted(groups, key=lambda g: g[0])\n    result = []\n    for key, group in groups:\n        result.extend(group)\n    return result\n"
  },
  {
    "path": "mypy/sharedparse.py",
    "content": "from __future__ import annotations\n\nfrom typing import Final\n\n\"\"\"Shared logic between our three mypy parser files.\"\"\"\n\n\n_NON_BINARY_MAGIC_METHODS: Final = {\n    \"__abs__\",\n    \"__call__\",\n    \"__complex__\",\n    \"__contains__\",\n    \"__buffer__\",\n    \"__del__\",\n    \"__delattr__\",\n    \"__delitem__\",\n    \"__enter__\",\n    \"__exit__\",\n    \"__float__\",\n    \"__getattr__\",\n    \"__getattribute__\",\n    \"__getitem__\",\n    \"__hex__\",\n    \"__init__\",\n    \"__init_subclass__\",\n    \"__int__\",\n    \"__invert__\",\n    \"__iter__\",\n    \"__len__\",\n    \"__long__\",\n    \"__neg__\",\n    \"__new__\",\n    \"__oct__\",\n    \"__pos__\",\n    \"__release_buffer__\",\n    \"__repr__\",\n    \"__reversed__\",\n    \"__setattr__\",\n    \"__setitem__\",\n    \"__str__\",\n}\n\nMAGIC_METHODS_ALLOWING_KWARGS: Final = {\n    \"__init__\",\n    \"__init_subclass__\",\n    \"__new__\",\n    \"__call__\",\n    \"__setattr__\",\n}\n\nBINARY_MAGIC_METHODS: Final = {\n    \"__add__\",\n    \"__and__\",\n    \"__divmod__\",\n    \"__eq__\",\n    \"__floordiv__\",\n    \"__ge__\",\n    \"__gt__\",\n    \"__iadd__\",\n    \"__iand__\",\n    \"__idiv__\",\n    \"__ifloordiv__\",\n    \"__ilshift__\",\n    \"__imatmul__\",\n    \"__imod__\",\n    \"__imul__\",\n    \"__ior__\",\n    \"__ipow__\",\n    \"__irshift__\",\n    \"__isub__\",\n    \"__itruediv__\",\n    \"__ixor__\",\n    \"__le__\",\n    \"__lshift__\",\n    \"__lt__\",\n    \"__matmul__\",\n    \"__mod__\",\n    \"__mul__\",\n    \"__ne__\",\n    \"__or__\",\n    \"__pow__\",\n    \"__radd__\",\n    \"__rand__\",\n    \"__rdiv__\",\n    \"__rfloordiv__\",\n    \"__rlshift__\",\n    \"__rmatmul__\",\n    \"__rmod__\",\n    \"__rmul__\",\n    \"__ror__\",\n    \"__rpow__\",\n    \"__rrshift__\",\n    \"__rshift__\",\n    \"__rsub__\",\n    \"__rtruediv__\",\n    \"__rxor__\",\n    \"__sub__\",\n    \"__truediv__\",\n    \"__xor__\",\n}\n\nassert not (_NON_BINARY_MAGIC_METHODS & BINARY_MAGIC_METHODS)\n\nMAGIC_METHODS: Final = _NON_BINARY_MAGIC_METHODS | BINARY_MAGIC_METHODS\n\nMAGIC_METHODS_POS_ARGS_ONLY: Final = MAGIC_METHODS - MAGIC_METHODS_ALLOWING_KWARGS\n\n\ndef special_function_elide_names(name: str) -> bool:\n    return name in MAGIC_METHODS_POS_ARGS_ONLY\n\n\ndef argument_elide_name(name: str | None) -> bool:\n    return name is not None and name.startswith(\"__\") and not name.endswith(\"__\")\n"
  },
  {
    "path": "mypy/solve.py",
    "content": "\"\"\"Type inference constraint solving\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom collections.abc import Iterable, Sequence\nfrom typing import TypeAlias as _TypeAlias\n\nfrom mypy.constraints import SUBTYPE_OF, SUPERTYPE_OF, Constraint, infer_constraints, neg_op\nfrom mypy.expandtype import expand_type\nfrom mypy.graph_utils import prepare_sccs, strongly_connected_components, topsort\nfrom mypy.join import join_type_list\nfrom mypy.meet import meet_type_list, meet_types\nfrom mypy.subtypes import is_subtype\nfrom mypy.typeops import get_all_type_vars\nfrom mypy.types import (\n    AnyType,\n    Instance,\n    NoneType,\n    ParamSpecType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    get_proper_type,\n)\nfrom mypy.typestate import type_state\n\nBounds: _TypeAlias = \"dict[TypeVarId, set[Type]]\"\nGraph: _TypeAlias = \"set[tuple[TypeVarId, TypeVarId]]\"\nSolutions: _TypeAlias = \"dict[TypeVarId, Type | None]\"\n\n\ndef solve_constraints(\n    original_vars: Sequence[TypeVarLikeType],\n    constraints: list[Constraint],\n    strict: bool = True,\n    allow_polymorphic: bool = False,\n    skip_unsatisfied: bool = False,\n) -> tuple[list[Type | None], list[TypeVarLikeType]]:\n    \"\"\"Solve type constraints.\n\n    Return the best type(s) for type variables; each type can be None if the value of\n    the variable could not be solved.\n\n    If a variable has no constraints, if strict=True then arbitrarily\n    pick UninhabitedType as the value of the type variable. If strict=False, pick AnyType.\n    If allow_polymorphic=True, then use the full algorithm that can potentially return\n    free type variables in solutions (these require special care when applying). Otherwise,\n    use a simplified algorithm that just solves each type variable individually if possible.\n\n    The skip_unsatisfied flag matches the same one in applytype.apply_generic_arguments().\n    \"\"\"\n    vars = [tv.id for tv in original_vars]\n    if not vars:\n        return [], []\n\n    originals = {tv.id: tv for tv in original_vars}\n    extra_vars: list[TypeVarId] = []\n    # Get additional type variables from generic actuals.\n    for c in constraints:\n        extra_vars.extend([v.id for v in c.extra_tvars if v.id not in vars + extra_vars])\n        originals.update({v.id: v for v in c.extra_tvars if v.id not in originals})\n\n    if allow_polymorphic:\n        # Constraints inferred from unions require special handling in polymorphic inference.\n        constraints = skip_reverse_union_constraints(constraints)\n\n    # Collect a list of constraints for each type variable.\n    cmap: dict[TypeVarId, list[Constraint]] = {tv: [] for tv in vars + extra_vars}\n    for con in constraints:\n        if con.type_var in vars + extra_vars:\n            cmap[con.type_var].append(con)\n\n    if allow_polymorphic:\n        if constraints:\n            solutions, free_vars = solve_with_dependent(\n                vars + extra_vars, constraints, vars, originals\n            )\n        else:\n            solutions = {}\n            free_vars = []\n    else:\n        solutions = {}\n        free_vars = []\n        for tv, cs in cmap.items():\n            if not cs:\n                continue\n            lowers = [c.target for c in cs if c.op == SUPERTYPE_OF]\n            uppers = [c.target for c in cs if c.op == SUBTYPE_OF]\n            solution = solve_one(lowers, uppers)\n\n            # Do not leak type variables in non-polymorphic solutions.\n            if solution is None or not get_vars(\n                solution, [tv for tv in extra_vars if tv not in vars]\n            ):\n                solutions[tv] = solution\n\n    res: list[Type | None] = []\n    for v in vars:\n        if v in solutions:\n            res.append(solutions[v])\n        else:\n            # No constraints for type variable -- 'UninhabitedType' is the most specific type.\n            candidate: Type\n            if strict:\n                candidate = UninhabitedType()\n                candidate.ambiguous = True\n            else:\n                candidate = AnyType(TypeOfAny.special_form)\n            res.append(candidate)\n\n    if not free_vars and not skip_unsatisfied:\n        # Most of the validation for solutions is done in applytype.py, but here we can\n        # quickly test solutions w.r.t. to upper bounds, and use the latter (if possible),\n        # if solutions are actually not valid (due to poor inference context).\n        res = pre_validate_solutions(res, original_vars, constraints)\n\n    return res, free_vars\n\n\ndef solve_with_dependent(\n    vars: list[TypeVarId],\n    constraints: list[Constraint],\n    original_vars: list[TypeVarId],\n    originals: dict[TypeVarId, TypeVarLikeType],\n) -> tuple[Solutions, list[TypeVarLikeType]]:\n    \"\"\"Solve set of constraints that may depend on each other, like T <: List[S].\n\n    The whole algorithm consists of five steps:\n      * Propagate via linear constraints and use secondary constraints to get transitive closure\n      * Find dependencies between type variables, group them in SCCs, and sort topologically\n      * Check that all SCC are intrinsically linear, we can't solve (express) T <: List[T]\n      * Variables in leaf SCCs that don't have constant bounds are free (choose one per SCC)\n      * Solve constraints iteratively starting from leaves, updating bounds after each step.\n    \"\"\"\n    graph, lowers, uppers = transitive_closure(vars, constraints)\n\n    dmap = compute_dependencies(vars, graph, lowers, uppers)\n    sccs = list(strongly_connected_components(set(vars), dmap))\n    if not all(check_linear(scc, lowers, uppers) for scc in sccs):\n        return {}, []\n    raw_batches = list(topsort(prepare_sccs(sccs, dmap)))\n\n    free_vars = []\n    free_solutions = {}\n    for scc in raw_batches[0]:\n        # If there are no bounds on this SCC, then the only meaningful solution we can\n        # express, is that each variable is equal to a new free variable. For example,\n        # if we have T <: S, S <: U, we deduce: T = S = U = <free>.\n        if all(not lowers[tv] and not uppers[tv] for tv in scc):\n            best_free = choose_free([originals[tv] for tv in scc], original_vars)\n            if best_free:\n                # TODO: failing to choose may cause leaking type variables,\n                # we need to fail gracefully instead.\n                free_vars.append(best_free.id)\n                free_solutions[best_free.id] = best_free\n\n    # Update lowers/uppers with free vars, so these can now be used\n    # as valid solutions.\n    for l, u in graph:\n        if l in free_vars:\n            lowers[u].add(free_solutions[l])\n        if u in free_vars:\n            uppers[l].add(free_solutions[u])\n\n    # Flatten the SCCs that are independent, we can solve them together,\n    # since we don't need to update any targets in between.\n    batches = []\n    for batch in raw_batches:\n        next_bc = []\n        for scc in batch:\n            next_bc.extend(list(scc))\n        batches.append(next_bc)\n\n    solutions: dict[TypeVarId, Type | None] = {}\n    for flat_batch in batches:\n        res = solve_iteratively(flat_batch, graph, lowers, uppers)\n        solutions.update(res)\n    return solutions, [free_solutions[tv] for tv in free_vars]\n\n\ndef solve_iteratively(\n    batch: list[TypeVarId], graph: Graph, lowers: Bounds, uppers: Bounds\n) -> Solutions:\n    \"\"\"Solve transitive closure sequentially, updating upper/lower bounds after each step.\n\n    Transitive closure is represented as a linear graph plus lower/upper bounds for each\n    type variable, see transitive_closure() docstring for details.\n\n    We solve for type variables that appear in `batch`. If a bound is not constant (i.e. it\n    looks like T :> F[S, ...]), we substitute solutions found so far in the target F[S, ...]\n    after solving the batch.\n\n    Importantly, after solving each variable in a batch, we move it from linear graph to\n    upper/lower bounds, this way we can guarantee consistency of solutions (see comment below\n    for an example when this is important).\n    \"\"\"\n    solutions = {}\n    s_batch = set(batch)\n    while s_batch:\n        for tv in sorted(s_batch, key=lambda x: x.raw_id):\n            if lowers[tv] or uppers[tv]:\n                solvable_tv = tv\n                break\n        else:\n            break\n        # Solve each solvable type variable separately.\n        s_batch.remove(solvable_tv)\n        result = solve_one(lowers[solvable_tv], uppers[solvable_tv])\n        solutions[solvable_tv] = result\n        if result is None:\n            # TODO: support backtracking lower/upper bound choices and order within SCCs.\n            # (will require switching this function from iterative to recursive).\n            continue\n\n        # Update the (transitive) bounds from graph if there is a solution.\n        # This is needed to guarantee solutions will never contradict the initial\n        # constraints. For example, consider {T <: S, T <: A, S :> B} with A :> B.\n        # If we would not update the uppers/lowers from graph, we would infer T = A, S = B\n        # which is not correct.\n        for l, u in graph.copy():\n            if l == u:\n                continue\n            if l == solvable_tv:\n                lowers[u].add(result)\n                graph.remove((l, u))\n            if u == solvable_tv:\n                uppers[l].add(result)\n                graph.remove((l, u))\n\n    # We can update uppers/lowers only once after solving the whole SCC,\n    # since uppers/lowers can't depend on type variables in the SCC\n    # (and we would reject such SCC as non-linear and therefore not solvable).\n    subs = {tv: s for (tv, s) in solutions.items() if s is not None}\n    for tv in lowers:\n        lowers[tv] = {expand_type(lt, subs) for lt in lowers[tv]}\n    for tv in uppers:\n        uppers[tv] = {expand_type(ut, subs) for ut in uppers[tv]}\n    return solutions\n\n\ndef _join_sorted_key(t: Type) -> int:\n    t = get_proper_type(t)\n    if isinstance(t, UnionType):\n        return -2\n    if isinstance(t, NoneType):\n        return -1\n    return 0\n\n\ndef solve_one(lowers: Iterable[Type], uppers: Iterable[Type]) -> Type | None:\n    \"\"\"Solve constraints by finding by using meets of upper bounds, and joins of lower bounds.\"\"\"\n\n    candidate: Type | None = None\n\n    # Filter out previous results of failed inference, they will only spoil the current pass...\n    new_uppers = []\n    for u in uppers:\n        pu = get_proper_type(u)\n        if not isinstance(pu, UninhabitedType) or not pu.ambiguous:\n            new_uppers.append(u)\n    uppers = new_uppers\n\n    # ...unless this is the only information we have, then we just pass it on.\n    lowers = list(lowers)\n    if not uppers and not lowers:\n        candidate = UninhabitedType()\n        candidate.ambiguous = True\n        return candidate\n\n    bottom: Type | None = None\n    top: Type | None = None\n\n    # Process each bound separately, and calculate the lower and upper\n    # bounds based on constraints. Note that we assume that the constraint\n    # targets do not have constraint references.\n    if type_state.infer_unions and lowers:\n        # This deviates from the general mypy semantics because\n        # recursive types are union-heavy in 95% of cases.\n        # Retain `None` when no bottoms were provided to avoid bogus `Never` inference.\n        bottom = UnionType.make_union(lowers)\n    else:\n        # The order of lowers is non-deterministic.\n        # We attempt to sort lowers because joins are non-associative. For instance:\n        # join(join(int, str), int | str) == join(object, int | str) == object\n        # join(int, join(str, int | str)) == join(int, int | str)    == int | str\n        # Note that joins in theory should be commutative, but in practice some bugs mean this is\n        # also a source of non-deterministic type checking results.\n        sorted_lowers = sorted(lowers, key=_join_sorted_key)\n        if sorted_lowers:\n            bottom = join_type_list(sorted_lowers)\n\n    for target in uppers:\n        if top is None:\n            top = target\n        else:\n            top = meet_types(top, target)\n\n    p_top = get_proper_type(top)\n    p_bottom = get_proper_type(bottom)\n    if isinstance(p_top, AnyType) or isinstance(p_bottom, AnyType):\n        source_any = top if isinstance(p_top, AnyType) else bottom\n        assert isinstance(source_any, ProperType) and isinstance(source_any, AnyType)\n        return AnyType(TypeOfAny.from_another_any, source_any=source_any)\n    elif bottom is None:\n        if top:\n            candidate = top\n        else:\n            # No constraints for type variable\n            return None\n    elif top is None:\n        candidate = bottom\n    elif is_subtype(bottom, top):\n        candidate = bottom\n    else:\n        candidate = None\n    return candidate\n\n\ndef choose_free(\n    scc: list[TypeVarLikeType], original_vars: list[TypeVarId]\n) -> TypeVarLikeType | None:\n    \"\"\"Choose the best solution for an SCC containing only type variables.\n\n    This is needed to preserve e.g. the upper bound in a situation like this:\n        def dec(f: Callable[[T], S]) -> Callable[[T], S]: ...\n\n        @dec\n        def test(x: U) -> U: ...\n\n    where U <: A.\n    \"\"\"\n\n    if len(scc) == 1:\n        # Fast path, choice is trivial.\n        return scc[0]\n\n    common_upper_bound = meet_type_list([t.upper_bound for t in scc])\n    common_upper_bound_p = get_proper_type(common_upper_bound)\n    # We include None for when strict-optional is disabled.\n    if isinstance(common_upper_bound_p, (UninhabitedType, NoneType)):\n        # This will cause to infer Never, which is better than a free TypeVar\n        # that has an upper bound Never.\n        return None\n\n    values: list[Type] = []\n    for tv in scc:\n        if isinstance(tv, TypeVarType) and tv.values:\n            if values:\n                # It is too tricky to support multiple TypeVars with values\n                # within the same SCC.\n                return None\n            values = tv.values.copy()\n\n    if values and not is_trivial_bound(common_upper_bound_p):\n        # If there are both values and upper bound present, we give up,\n        # since type variables having both are not supported.\n        return None\n\n    # For convenience with current type application machinery, we use a stable\n    # choice that prefers the original type variables (not polymorphic ones) in SCC.\n    best = min(scc, key=lambda x: (x.id not in original_vars, x.id.raw_id))\n    if isinstance(best, TypeVarType):\n        return best.copy_modified(values=values, upper_bound=common_upper_bound)\n    if is_trivial_bound(common_upper_bound_p, allow_tuple=True):\n        # TODO: support more cases for ParamSpecs/TypeVarTuples\n        return best\n    return None\n\n\ndef is_trivial_bound(tp: ProperType, allow_tuple: bool = False) -> bool:\n    if isinstance(tp, Instance) and tp.type.fullname == \"builtins.tuple\":\n        return allow_tuple and is_trivial_bound(get_proper_type(tp.args[0]))\n    return isinstance(tp, Instance) and tp.type.fullname == \"builtins.object\"\n\n\ndef find_linear(c: Constraint) -> tuple[bool, TypeVarId | None]:\n    \"\"\"Find out if this constraint represent a linear relationship, return target id if yes.\"\"\"\n    if isinstance(c.origin_type_var, TypeVarType):\n        if isinstance(c.target, TypeVarType):\n            return True, c.target.id\n    if isinstance(c.origin_type_var, ParamSpecType):\n        if isinstance(c.target, ParamSpecType) and not c.target.prefix.arg_types:\n            return True, c.target.id\n    if isinstance(c.origin_type_var, TypeVarTupleType):\n        target = get_proper_type(c.target)\n        if isinstance(target, TupleType) and len(target.items) == 1:\n            item = target.items[0]\n            if isinstance(item, UnpackType) and isinstance(item.type, TypeVarTupleType):\n                return True, item.type.id\n    return False, None\n\n\ndef transitive_closure(\n    tvars: list[TypeVarId], constraints: list[Constraint]\n) -> tuple[Graph, Bounds, Bounds]:\n    \"\"\"Find transitive closure for given constraints on type variables.\n\n    Transitive closure gives maximal set of lower/upper bounds for each type variable,\n    such that we cannot deduce any further bounds by chaining other existing bounds.\n\n    The transitive closure is represented by:\n      * A set of lower and upper bounds for each type variable, where only constant and\n        non-linear terms are included in the bounds.\n      * A graph of linear constraints between type variables (represented as a set of pairs)\n    Such separation simplifies reasoning, and allows an efficient and simple incremental\n    transitive closure algorithm that we use here.\n\n    For example if we have initial constraints [T <: S, S <: U, U <: int], the transitive\n    closure is given by:\n      * {} <: T <: {int}\n      * {} <: S <: {int}\n      * {} <: U <: {int}\n      * {T <: S, S <: U, T <: U}\n    \"\"\"\n    uppers: Bounds = defaultdict(set)\n    lowers: Bounds = defaultdict(set)\n    graph: Graph = {(tv, tv) for tv in tvars}\n\n    remaining = set(constraints)\n    while remaining:\n        c = remaining.pop()\n        # Note that ParamSpec constraint P <: Q may be considered linear only if Q has no prefix,\n        # for cases like P <: Concatenate[T, Q] we should consider this non-linear and put {P} and\n        # {T, Q} into separate SCCs. Similarly, Ts <: Tuple[*Us] considered linear, while\n        # Ts <: Tuple[*Us, U] is non-linear.\n        is_linear, target_id = find_linear(c)\n        if is_linear and target_id in tvars:\n            assert target_id is not None\n            if c.op == SUBTYPE_OF:\n                lower, upper = c.type_var, target_id\n            else:\n                lower, upper = target_id, c.type_var\n            if (lower, upper) in graph:\n                continue\n            graph |= {\n                (l, u) for l in tvars for u in tvars if (l, lower) in graph and (upper, u) in graph\n            }\n            for u in tvars:\n                if (upper, u) in graph:\n                    lowers[u] |= lowers[lower]\n            for l in tvars:\n                if (l, lower) in graph:\n                    uppers[l] |= uppers[upper]\n            for lt in lowers[lower]:\n                for ut in uppers[upper]:\n                    add_secondary_constraints(remaining, lt, ut)\n        elif c.op == SUBTYPE_OF:\n            if c.target in uppers[c.type_var]:\n                continue\n            for l in tvars:\n                if (l, c.type_var) in graph:\n                    uppers[l].add(c.target)\n            for lt in lowers[c.type_var]:\n                add_secondary_constraints(remaining, lt, c.target)\n        else:\n            assert c.op == SUPERTYPE_OF\n            if c.target in lowers[c.type_var]:\n                continue\n            for u in tvars:\n                if (c.type_var, u) in graph:\n                    lowers[u].add(c.target)\n            for ut in uppers[c.type_var]:\n                add_secondary_constraints(remaining, c.target, ut)\n    return graph, lowers, uppers\n\n\ndef add_secondary_constraints(cs: set[Constraint], lower: Type, upper: Type) -> None:\n    \"\"\"Add secondary constraints inferred between lower and upper (in place).\"\"\"\n    if isinstance(get_proper_type(upper), UnionType) and isinstance(\n        get_proper_type(lower), UnionType\n    ):\n        # When both types are unions, this can lead to inferring spurious constraints,\n        # for example Union[T, int] <: S <: Union[T, int] may infer T <: int.\n        # To avoid this, just skip them for now.\n        return\n    # TODO: what if secondary constraints result in inference against polymorphic actual?\n    cs.update(set(infer_constraints(lower, upper, SUBTYPE_OF)))\n    cs.update(set(infer_constraints(upper, lower, SUPERTYPE_OF)))\n\n\ndef compute_dependencies(\n    tvars: list[TypeVarId], graph: Graph, lowers: Bounds, uppers: Bounds\n) -> dict[TypeVarId, list[TypeVarId]]:\n    \"\"\"Compute dependencies between type variables induced by constraints.\n\n    If we have a constraint like T <: List[S], we say that T depends on S, since\n    we will need to solve for S first before we can solve for T.\n    \"\"\"\n    res = {}\n    for tv in tvars:\n        deps = set()\n        for lt in lowers[tv]:\n            deps |= get_vars(lt, tvars)\n        for ut in uppers[tv]:\n            deps |= get_vars(ut, tvars)\n        for other in tvars:\n            if other == tv:\n                continue\n            if (tv, other) in graph or (other, tv) in graph:\n                deps.add(other)\n        res[tv] = list(deps)\n    return res\n\n\ndef check_linear(scc: set[TypeVarId], lowers: Bounds, uppers: Bounds) -> bool:\n    \"\"\"Check there are only linear constraints between type variables in SCC.\n\n    Linear are constraints like T <: S (while T <: F[S] are non-linear).\n    \"\"\"\n    for tv in scc:\n        if any(get_vars(lt, list(scc)) for lt in lowers[tv]):\n            return False\n        if any(get_vars(ut, list(scc)) for ut in uppers[tv]):\n            return False\n    return True\n\n\ndef skip_reverse_union_constraints(cs: list[Constraint]) -> list[Constraint]:\n    \"\"\"Avoid ambiguities for constraints inferred from unions during polymorphic inference.\n\n    Polymorphic inference implicitly relies on assumption that a reverse of a linear constraint\n    is a linear constraint. This is however not true in presence of union types, for example\n    T :> Union[S, int] vs S <: T. Trying to solve such constraints would be detected ambiguous\n    as (T, S) form a non-linear SCC. However, simply removing the linear part results in a valid\n    solution T = Union[S, int], S = <free>. A similar scenario is when we get T <: Union[T, int],\n    such constraints carry no information, and will equally confuse linearity check.\n\n    TODO: a cleaner solution may be to avoid inferring such constraints in first place, but\n    this would require passing around a flag through all infer_constraints() calls.\n    \"\"\"\n    reverse_union_cs = set()\n    for c in cs:\n        p_target = get_proper_type(c.target)\n        if isinstance(p_target, UnionType):\n            for item in p_target.items:\n                if isinstance(item, TypeVarType):\n                    if item == c.origin_type_var and c.op == SUBTYPE_OF:\n                        reverse_union_cs.add(c)\n                        continue\n                    # These two forms are semantically identical, but are different from\n                    # the point of view of Constraint.__eq__().\n                    reverse_union_cs.add(Constraint(item, neg_op(c.op), c.origin_type_var))\n                    reverse_union_cs.add(Constraint(c.origin_type_var, c.op, item))\n    return [c for c in cs if c not in reverse_union_cs]\n\n\ndef get_vars(target: Type, vars: list[TypeVarId]) -> set[TypeVarId]:\n    \"\"\"Find type variables for which we are solving in a target type.\"\"\"\n    return {tv.id for tv in get_all_type_vars(target)} & set(vars)\n\n\ndef pre_validate_solutions(\n    solutions: list[Type | None],\n    original_vars: Sequence[TypeVarLikeType],\n    constraints: list[Constraint],\n) -> list[Type | None]:\n    \"\"\"Check is each solution satisfies the upper bound of the corresponding type variable.\n\n    If it doesn't satisfy the bound, check if bound itself satisfies all constraints, and\n    if yes, use it instead as a fallback solution.\n    \"\"\"\n    new_solutions: list[Type | None] = []\n    for t, s in zip(original_vars, solutions):\n        if is_callable_protocol(t.upper_bound):\n            # This is really ad-hoc, but a proper fix would be much more complex,\n            # and otherwise this may cause crash in a relatively common scenario.\n            new_solutions.append(s)\n            continue\n        if s is not None and not is_subtype(s, t.upper_bound):\n            bound_satisfies_all = True\n            for c in constraints:\n                if c.op == SUBTYPE_OF and not is_subtype(t.upper_bound, c.target):\n                    bound_satisfies_all = False\n                    break\n                if c.op == SUPERTYPE_OF and not is_subtype(c.target, t.upper_bound):\n                    bound_satisfies_all = False\n                    break\n            if bound_satisfies_all:\n                new_solutions.append(t.upper_bound)\n                continue\n        new_solutions.append(s)\n    return new_solutions\n\n\ndef is_callable_protocol(t: Type) -> bool:\n    proper_t = get_proper_type(t)\n    if isinstance(proper_t, Instance) and proper_t.type.is_protocol:\n        return \"__call__\" in proper_t.type.protocol_members\n    return False\n"
  },
  {
    "path": "mypy/split_namespace.py",
    "content": "\"\"\"Split namespace for argparse to allow separating options by prefix.\n\nWe use this to direct some options to an Options object and some to a\nregular namespace.\n\"\"\"\n\n# In its own file largely because mypyc doesn't support its use of\n# __getattr__/__setattr__ and has some issues with __dict__\n\nfrom __future__ import annotations\n\nimport argparse\nfrom typing import Any\n\n\nclass SplitNamespace(argparse.Namespace):\n    def __init__(self, standard_namespace: object, alt_namespace: object, alt_prefix: str) -> None:\n        self.__dict__[\"_standard_namespace\"] = standard_namespace\n        self.__dict__[\"_alt_namespace\"] = alt_namespace\n        self.__dict__[\"_alt_prefix\"] = alt_prefix\n\n    def _get(self) -> tuple[Any, Any]:\n        return (self._standard_namespace, self._alt_namespace)\n\n    def __setattr__(self, name: str, value: Any) -> None:\n        if name.startswith(self._alt_prefix):\n            setattr(self._alt_namespace, name[len(self._alt_prefix) :], value)\n        else:\n            setattr(self._standard_namespace, name, value)\n\n    def __getattr__(self, name: str) -> Any:\n        if name.startswith(self._alt_prefix):\n            return getattr(self._alt_namespace, name[len(self._alt_prefix) :])\n        else:\n            return getattr(self._standard_namespace, name)\n"
  },
  {
    "path": "mypy/state.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom typing import Final\n\n# These are global mutable state. Don't add anything here unless there's a very\n# good reason.\n\n\nclass StrictOptionalState:\n    # Wrap this in a class since it's faster that using a module-level attribute.\n\n    def __init__(self, strict_optional: bool) -> None:\n        # Value varies by file being processed\n        self.strict_optional = strict_optional\n\n    @contextmanager\n    def strict_optional_set(self, value: bool) -> Iterator[None]:\n        saved = self.strict_optional\n        self.strict_optional = value\n        try:\n            yield\n        finally:\n            self.strict_optional = saved\n\n\nstate: Final = StrictOptionalState(strict_optional=True)\nfind_occurrences: tuple[str, str] | None = None\n"
  },
  {
    "path": "mypy/stats.py",
    "content": "\"\"\"Utilities for calculating and reporting statistics about types.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nfrom collections import Counter\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom typing import Final\n\nfrom mypy import nodes\nfrom mypy.argmap import map_formals_to_actuals\nfrom mypy.nodes import (\n    AssignmentExpr,\n    AssignmentStmt,\n    BreakStmt,\n    BytesExpr,\n    CallExpr,\n    ClassDef,\n    ComparisonExpr,\n    ComplexExpr,\n    ContinueStmt,\n    EllipsisExpr,\n    Expression,\n    ExpressionStmt,\n    FloatExpr,\n    FuncDef,\n    Import,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    Node,\n    OpExpr,\n    PassStmt,\n    RefExpr,\n    StrExpr,\n    TypeApplication,\n    UnaryExpr,\n    YieldFromExpr,\n)\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.type_visitor import ANY_STRATEGY, BoolTypeQuery\nfrom mypy.typeanal import collect_all_inner_types\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    FunctionLike,\n    Instance,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeVarType,\n    get_proper_type,\n    get_proper_types,\n)\nfrom mypy.util import correct_relative_import\n\nTYPE_EMPTY: Final = 0\nTYPE_UNANALYZED: Final = 1  # type of non-typechecked code\nTYPE_PRECISE: Final = 2\nTYPE_IMPRECISE: Final = 3\nTYPE_ANY: Final = 4\n\nprecision_names: Final = [\"empty\", \"unanalyzed\", \"precise\", \"imprecise\", \"any\"]\n\n\nclass StatisticsVisitor(TraverserVisitor):\n    def __init__(\n        self,\n        inferred: bool,\n        filename: str,\n        modules: dict[str, MypyFile],\n        typemap: dict[Expression, Type] | None = None,\n        all_nodes: bool = False,\n        visit_untyped_defs: bool = True,\n    ) -> None:\n        self.inferred = inferred\n        self.filename = filename\n        self.modules = modules\n        self.typemap = typemap\n        self.all_nodes = all_nodes\n        self.visit_untyped_defs = visit_untyped_defs\n\n        self.num_precise_exprs = 0\n        self.num_imprecise_exprs = 0\n        self.num_any_exprs = 0\n\n        self.num_simple_types = 0\n        self.num_generic_types = 0\n        self.num_tuple_types = 0\n        self.num_function_types = 0\n        self.num_typevar_types = 0\n        self.num_complex_types = 0\n        self.num_any_types = 0\n\n        self.line = -1\n\n        self.line_map: dict[int, int] = {}\n\n        self.type_of_any_counter: Counter[int] = Counter()\n        self.any_line_map: dict[int, list[AnyType]] = {}\n\n        # For each scope (top level/function), whether the scope was type checked\n        # (annotated function).\n        #\n        # TODO: Handle --check-untyped-defs\n        self.checked_scopes = [True]\n\n        self.output: list[str] = []\n\n        TraverserVisitor.__init__(self)\n\n    def visit_mypy_file(self, o: MypyFile) -> None:\n        self.cur_mod_node = o\n        self.cur_mod_id = o.fullname\n        super().visit_mypy_file(o)\n\n    def visit_import_from(self, imp: ImportFrom) -> None:\n        self.process_import(imp)\n\n    def visit_import_all(self, imp: ImportAll) -> None:\n        self.process_import(imp)\n\n    def process_import(self, imp: ImportFrom | ImportAll) -> None:\n        import_id, ok = correct_relative_import(\n            self.cur_mod_id, imp.relative, imp.id, self.cur_mod_node.is_package_init_file()\n        )\n        if ok and import_id in self.modules:\n            kind = TYPE_PRECISE\n        else:\n            kind = TYPE_ANY\n        self.record_line(imp.line, kind)\n\n    def visit_import(self, imp: Import) -> None:\n        if all(id in self.modules for id, _ in imp.ids):\n            kind = TYPE_PRECISE\n        else:\n            kind = TYPE_ANY\n        self.record_line(imp.line, kind)\n\n    def visit_func_def(self, o: FuncDef) -> None:\n        with self.enter_scope(o):\n            self.line = o.line\n            if len(o.expanded) > 1 and o.expanded != [o] * len(o.expanded):\n                if o in o.expanded:\n                    print(\n                        \"{}:{}: ERROR: cycle in function expansion; skipping\".format(\n                            self.filename, o.line\n                        )\n                    )\n                    return\n                for defn in o.expanded:\n                    assert isinstance(defn, FuncDef)\n                    self.visit_func_def(defn)\n            else:\n                if o.type:\n                    assert isinstance(o.type, CallableType)\n                    sig = o.type\n                    arg_types = sig.arg_types\n                    if sig.arg_names and sig.arg_names[0] == \"self\" and not self.inferred:\n                        arg_types = arg_types[1:]\n                    for arg in arg_types:\n                        self.type(arg)\n                    self.type(sig.ret_type)\n                elif self.all_nodes:\n                    self.record_line(self.line, TYPE_ANY)\n                if not o.is_dynamic() or self.visit_untyped_defs:\n                    super().visit_func_def(o)\n\n    @contextmanager\n    def enter_scope(self, o: FuncDef) -> Iterator[None]:\n        self.checked_scopes.append(o.type is not None and self.checked_scopes[-1])\n        yield None\n        self.checked_scopes.pop()\n\n    def is_checked_scope(self) -> bool:\n        return self.checked_scopes[-1]\n\n    def visit_class_def(self, o: ClassDef) -> None:\n        self.record_line(o.line, TYPE_PRECISE)  # TODO: Look at base classes\n        # Override this method because we don't want to analyze base_type_exprs (base_type_exprs\n        # are base classes in a class declaration).\n        # While base_type_exprs are technically expressions, type analyzer does not visit them and\n        # they are not in the typemap.\n        for d in o.decorators:\n            d.accept(self)\n        o.defs.accept(self)\n\n    def visit_type_application(self, o: TypeApplication) -> None:\n        self.line = o.line\n        for t in o.types:\n            self.type(t)\n        super().visit_type_application(o)\n\n    def visit_assignment_stmt(self, o: AssignmentStmt) -> None:\n        self.line = o.line\n        if isinstance(o.rvalue, nodes.CallExpr) and isinstance(\n            o.rvalue.analyzed, nodes.TypeVarExpr\n        ):\n            # Type variable definition -- not a real assignment.\n            return\n        if o.type:\n            # If there is an explicit type, don't visit the l.h.s. as an expression\n            # to avoid double-counting and mishandling special forms.\n            self.type(o.type)\n            o.rvalue.accept(self)\n            return\n        elif self.inferred and not self.all_nodes:\n            # if self.all_nodes is set, lvalues will be visited later\n            for lvalue in o.lvalues:\n                if isinstance(lvalue, nodes.TupleExpr):\n                    items = lvalue.items\n                else:\n                    items = [lvalue]\n                for item in items:\n                    if isinstance(item, RefExpr) and item.is_inferred_def:\n                        if self.typemap is not None:\n                            self.type(self.typemap.get(item))\n        super().visit_assignment_stmt(o)\n\n    def visit_expression_stmt(self, o: ExpressionStmt) -> None:\n        if isinstance(o.expr, (StrExpr, BytesExpr)):\n            # Docstring\n            self.record_line(o.line, TYPE_EMPTY)\n        else:\n            super().visit_expression_stmt(o)\n\n    def visit_pass_stmt(self, o: PassStmt) -> None:\n        self.record_precise_if_checked_scope(o)\n\n    def visit_break_stmt(self, o: BreakStmt) -> None:\n        self.record_precise_if_checked_scope(o)\n\n    def visit_continue_stmt(self, o: ContinueStmt) -> None:\n        self.record_precise_if_checked_scope(o)\n\n    def visit_name_expr(self, o: NameExpr) -> None:\n        if o.fullname in (\"builtins.None\", \"builtins.True\", \"builtins.False\", \"builtins.Ellipsis\"):\n            self.record_precise_if_checked_scope(o)\n        else:\n            self.process_node(o)\n            super().visit_name_expr(o)\n\n    def visit_yield_from_expr(self, o: YieldFromExpr) -> None:\n        if o.expr:\n            o.expr.accept(self)\n\n    def visit_call_expr(self, o: CallExpr) -> None:\n        self.process_node(o)\n        if o.analyzed:\n            o.analyzed.accept(self)\n        else:\n            o.callee.accept(self)\n            for a in o.args:\n                a.accept(self)\n            self.record_call_target_precision(o)\n\n    def record_call_target_precision(self, o: CallExpr) -> None:\n        \"\"\"Record precision of formal argument types used in a call.\"\"\"\n        if not self.typemap or o.callee not in self.typemap:\n            # Type not available.\n            return\n        callee_type = get_proper_type(self.typemap[o.callee])\n        if isinstance(callee_type, CallableType):\n            self.record_callable_target_precision(o, callee_type)\n        else:\n            pass  # TODO: Handle overloaded functions, etc.\n\n    def record_callable_target_precision(self, o: CallExpr, callee: CallableType) -> None:\n        \"\"\"Record imprecision caused by callee argument types.\n\n        This only considers arguments passed in a call expression. Arguments\n        with default values that aren't provided in a call arguably don't\n        contribute to typing imprecision at the *call site* (but they\n        contribute at the function definition).\n        \"\"\"\n        assert self.typemap\n        typemap = self.typemap\n        actual_to_formal = map_formals_to_actuals(\n            o.arg_kinds,\n            o.arg_names,\n            callee.arg_kinds,\n            callee.arg_names,\n            lambda n: typemap[o.args[n]],\n        )\n        for formals in actual_to_formal:\n            for n in formals:\n                formal = get_proper_type(callee.arg_types[n])\n                if isinstance(formal, AnyType):\n                    self.record_line(o.line, TYPE_ANY)\n                elif is_imprecise(formal):\n                    self.record_line(o.line, TYPE_IMPRECISE)\n\n    def visit_member_expr(self, o: MemberExpr) -> None:\n        self.process_node(o)\n        super().visit_member_expr(o)\n\n    def visit_op_expr(self, o: OpExpr) -> None:\n        self.process_node(o)\n        super().visit_op_expr(o)\n\n    def visit_comparison_expr(self, o: ComparisonExpr) -> None:\n        self.process_node(o)\n        super().visit_comparison_expr(o)\n\n    def visit_index_expr(self, o: IndexExpr) -> None:\n        self.process_node(o)\n        super().visit_index_expr(o)\n\n    def visit_assignment_expr(self, o: AssignmentExpr) -> None:\n        self.process_node(o)\n        super().visit_assignment_expr(o)\n\n    def visit_unary_expr(self, o: UnaryExpr) -> None:\n        self.process_node(o)\n        super().visit_unary_expr(o)\n\n    def visit_str_expr(self, o: StrExpr) -> None:\n        self.record_precise_if_checked_scope(o)\n\n    def visit_bytes_expr(self, o: BytesExpr) -> None:\n        self.record_precise_if_checked_scope(o)\n\n    def visit_int_expr(self, o: IntExpr) -> None:\n        self.record_precise_if_checked_scope(o)\n\n    def visit_float_expr(self, o: FloatExpr) -> None:\n        self.record_precise_if_checked_scope(o)\n\n    def visit_complex_expr(self, o: ComplexExpr) -> None:\n        self.record_precise_if_checked_scope(o)\n\n    def visit_ellipsis(self, o: EllipsisExpr) -> None:\n        self.record_precise_if_checked_scope(o)\n\n    # Helpers\n\n    def process_node(self, node: Expression) -> None:\n        if self.all_nodes:\n            if self.typemap is not None:\n                self.line = node.line\n                self.type(self.typemap.get(node))\n\n    def record_precise_if_checked_scope(self, node: Node) -> None:\n        if isinstance(node, Expression) and self.typemap and node not in self.typemap:\n            kind = TYPE_UNANALYZED\n        elif self.is_checked_scope():\n            kind = TYPE_PRECISE\n        else:\n            kind = TYPE_ANY\n        self.record_line(node.line, kind)\n\n    def type(self, t: Type | None) -> None:\n        t = get_proper_type(t)\n\n        if not t:\n            # If an expression does not have a type, it is often due to dead code.\n            # Don't count these because there can be an unanalyzed value on a line with other\n            # analyzed expressions, which overwrite the TYPE_UNANALYZED.\n            self.record_line(self.line, TYPE_UNANALYZED)\n            return\n\n        if isinstance(t, AnyType) and is_special_form_any(t):\n            # TODO: What if there is an error in special form definition?\n            self.record_line(self.line, TYPE_PRECISE)\n            return\n\n        if isinstance(t, AnyType):\n            self.log(\"  !! Any type around line %d\" % self.line)\n            self.num_any_exprs += 1\n            self.record_line(self.line, TYPE_ANY)\n        elif (not self.all_nodes and is_imprecise(t)) or (self.all_nodes and is_imprecise2(t)):\n            self.log(\"  !! Imprecise type around line %d\" % self.line)\n            self.num_imprecise_exprs += 1\n            self.record_line(self.line, TYPE_IMPRECISE)\n        else:\n            self.num_precise_exprs += 1\n            self.record_line(self.line, TYPE_PRECISE)\n\n        for typ in get_proper_types(collect_all_inner_types(t)) + [t]:\n            if isinstance(typ, AnyType):\n                typ = get_original_any(typ)\n                if is_special_form_any(typ):\n                    continue\n                self.type_of_any_counter[typ.type_of_any] += 1\n                self.num_any_types += 1\n                if self.line in self.any_line_map:\n                    self.any_line_map[self.line].append(typ)\n                else:\n                    self.any_line_map[self.line] = [typ]\n            elif isinstance(typ, Instance):\n                if typ.args:\n                    if any(is_complex(arg) for arg in typ.args):\n                        self.num_complex_types += 1\n                    else:\n                        self.num_generic_types += 1\n                else:\n                    self.num_simple_types += 1\n            elif isinstance(typ, FunctionLike):\n                self.num_function_types += 1\n            elif isinstance(typ, TupleType):\n                if any(is_complex(item) for item in typ.items):\n                    self.num_complex_types += 1\n                else:\n                    self.num_tuple_types += 1\n            elif isinstance(typ, TypeVarType):\n                self.num_typevar_types += 1\n\n    def log(self, string: str) -> None:\n        self.output.append(string)\n\n    def record_line(self, line: int, precision: int) -> None:\n        self.line_map[line] = max(precision, self.line_map.get(line, TYPE_EMPTY))\n\n\ndef dump_type_stats(\n    tree: MypyFile,\n    path: str,\n    modules: dict[str, MypyFile],\n    inferred: bool = False,\n    typemap: dict[Expression, Type] | None = None,\n) -> None:\n    if is_special_module(path):\n        return\n    print(path)\n    visitor = StatisticsVisitor(inferred, filename=tree.fullname, modules=modules, typemap=typemap)\n    tree.accept(visitor)\n    for line in visitor.output:\n        print(line)\n    print(\"  ** precision **\")\n    print(\"  precise  \", visitor.num_precise_exprs)\n    print(\"  imprecise\", visitor.num_imprecise_exprs)\n    print(\"  any      \", visitor.num_any_exprs)\n    print(\"  ** kinds **\")\n    print(\"  simple   \", visitor.num_simple_types)\n    print(\"  generic  \", visitor.num_generic_types)\n    print(\"  function \", visitor.num_function_types)\n    print(\"  tuple    \", visitor.num_tuple_types)\n    print(\"  TypeVar  \", visitor.num_typevar_types)\n    print(\"  complex  \", visitor.num_complex_types)\n    print(\"  any      \", visitor.num_any_types)\n\n\ndef is_special_module(path: str) -> bool:\n    return os.path.basename(path) in (\"abc.pyi\", \"typing.pyi\", \"builtins.pyi\")\n\n\ndef is_imprecise(t: Type) -> bool:\n    return t.accept(HasAnyQuery())\n\n\nclass HasAnyQuery(BoolTypeQuery):\n    def __init__(self) -> None:\n        super().__init__(ANY_STRATEGY)\n\n    def visit_any(self, t: AnyType) -> bool:\n        return not is_special_form_any(t)\n\n\ndef is_imprecise2(t: Type) -> bool:\n    return t.accept(HasAnyQuery2())\n\n\nclass HasAnyQuery2(HasAnyQuery):\n    def visit_callable_type(self, t: CallableType) -> bool:\n        # We don't want to flag references to functions with some Any\n        # argument types (etc.) since they generally don't mean trouble.\n        return False\n\n\ndef is_generic(t: Type) -> bool:\n    t = get_proper_type(t)\n    return isinstance(t, Instance) and bool(t.args)\n\n\ndef is_complex(t: Type) -> bool:\n    t = get_proper_type(t)\n    return is_generic(t) or isinstance(t, (FunctionLike, TupleType, TypeVarType))\n\n\ndef is_special_form_any(t: AnyType) -> bool:\n    return get_original_any(t).type_of_any == TypeOfAny.special_form\n\n\ndef get_original_any(t: AnyType) -> AnyType:\n    if t.type_of_any == TypeOfAny.from_another_any:\n        assert t.source_any\n        assert t.source_any.type_of_any != TypeOfAny.from_another_any\n        t = t.source_any\n    return t\n"
  },
  {
    "path": "mypy/strconv.py",
    "content": "\"\"\"Conversion of parse tree nodes to strings.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport re\nfrom collections.abc import Sequence\nfrom typing import TYPE_CHECKING, Any\n\nimport mypy.nodes\nfrom mypy.options import Options\nfrom mypy.util import IdMapper, short_type\nfrom mypy.visitor import NodeVisitor\n\nif TYPE_CHECKING:\n    import mypy.patterns\n    import mypy.types\n\n\nclass StrConv(NodeVisitor[str]):\n    \"\"\"Visitor for converting a node to a human-readable string.\n\n    For example, an MypyFile node from program '1' is converted into\n    something like this:\n\n      MypyFile:1(\n        fnam\n        ExpressionStmt:1(\n          IntExpr(1)))\n    \"\"\"\n\n    __slots__ = [\"options\", \"show_ids\", \"id_mapper\"]\n\n    def __init__(self, *, show_ids: bool = False, options: Options) -> None:\n        self.options = options\n        self.show_ids = show_ids\n        self.id_mapper: IdMapper | None = None\n        if show_ids:\n            self.id_mapper = IdMapper()\n\n    def stringify_type(self, t: mypy.types.Type) -> str:\n        import mypy.types\n\n        return t.accept(mypy.types.TypeStrVisitor(id_mapper=self.id_mapper, options=self.options))\n\n    def get_id(self, o: object) -> int | None:\n        if self.id_mapper:\n            return self.id_mapper.id(o)\n        return None\n\n    def format_id(self, o: object) -> str:\n        if self.id_mapper:\n            return f\"<{self.get_id(o)}>\"\n        else:\n            return \"\"\n\n    def dump(self, nodes: Sequence[object], obj: mypy.nodes.Context) -> str:\n        \"\"\"Convert a list of items to a multiline pretty-printed string.\n\n        The tag is produced from the type name of obj and its line\n        number. See mypy.util.dump_tagged for a description of the nodes\n        argument.\n        \"\"\"\n        tag = short_type(obj) + \":\" + str(obj.line)\n        if self.show_ids:\n            assert self.id_mapper is not None\n            tag += f\"<{self.get_id(obj)}>\"\n        return dump_tagged(nodes, tag, self)\n\n    def func_helper(self, o: mypy.nodes.FuncItem) -> list[object]:\n        \"\"\"Return a list in a format suitable for dump() that represents the\n        arguments and the body of a function. The caller can then decorate the\n        array with information specific to methods, global functions or\n        anonymous functions.\n        \"\"\"\n        args: list[mypy.nodes.Var | tuple[str, list[mypy.nodes.Node]]] = []\n        extra: list[tuple[str, list[mypy.nodes.Var]]] = []\n        for arg in o.arguments:\n            kind: mypy.nodes.ArgKind = arg.kind\n            if kind.is_required():\n                args.append(arg.variable)\n            elif kind.is_optional():\n                assert arg.initializer is not None\n                args.append((\"default\", [arg.variable, arg.initializer]))\n            elif kind == mypy.nodes.ARG_STAR:\n                extra.append((\"VarArg\", [arg.variable]))\n            elif kind == mypy.nodes.ARG_STAR2:\n                extra.append((\"DictVarArg\", [arg.variable]))\n        a: list[Any] = []\n        if o.type_args:\n            for p in o.type_args:\n                a.append(self.type_param(p))\n        if args:\n            a.append((\"Args\", args))\n        if o.type:\n            a.append(o.type)\n        if o.is_generator:\n            a.append(\"Generator\")\n        a.extend(extra)\n        a.append(o.body)\n        return a\n\n    # Top-level structures\n\n    def visit_mypy_file(self, o: mypy.nodes.MypyFile) -> str:\n        # Skip implicit definitions.\n        a: list[Any] = [o.defs]\n        if o.is_bom:\n            a.insert(0, \"BOM\")\n        # Omit path to special file with name \"main\". This is used to simplify\n        # test case descriptions; the file \"main\" is used by default in many\n        # test cases.\n        if o.path != \"main\":\n            # Insert path. Normalize directory separators to / to unify test\n            # case# output in all platforms.\n            a.insert(0, o.path.replace(os.getcwd() + os.sep, \"\").replace(os.sep, \"/\"))\n        if o.ignored_lines:\n            a.append(\"IgnoredLines(%s)\" % \", \".join(str(line) for line in sorted(o.ignored_lines)))\n        return self.dump(a, o)\n\n    def visit_import(self, o: mypy.nodes.Import) -> str:\n        a = []\n        for id, as_id in o.ids:\n            if as_id is not None:\n                a.append(f\"{id} : {as_id}\")\n            else:\n                a.append(id)\n        return f\"Import:{o.line}({', '.join(a)})\"\n\n    def visit_import_from(self, o: mypy.nodes.ImportFrom) -> str:\n        a = []\n        for name, as_name in o.names:\n            if as_name is not None:\n                a.append(f\"{name} : {as_name}\")\n            else:\n                a.append(name)\n        return f\"ImportFrom:{o.line}({'.' * o.relative + o.id}, [{', '.join(a)}])\"\n\n    def visit_import_all(self, o: mypy.nodes.ImportAll) -> str:\n        return f\"ImportAll:{o.line}({'.' * o.relative + o.id})\"\n\n    # Definitions\n\n    def visit_func_def(self, o: mypy.nodes.FuncDef) -> str:\n        a = self.func_helper(o)\n        a.insert(0, o.name)\n        arg_kinds = {arg.kind for arg in o.arguments}\n        if len(arg_kinds & {mypy.nodes.ARG_NAMED, mypy.nodes.ARG_NAMED_OPT}) > 0:\n            a.insert(1, f\"MaxPos({o.max_pos})\")\n        if o.is_coroutine:\n            a.insert(1, \"Async\")\n        if o.abstract_status in (mypy.nodes.IS_ABSTRACT, mypy.nodes.IMPLICITLY_ABSTRACT):\n            a.insert(-1, \"Abstract\")\n        if o.is_static:\n            a.insert(-1, \"Static\")\n        if o.is_class:\n            a.insert(-1, \"Class\")\n        if o.is_property:\n            a.insert(-1, \"Property\")\n        return self.dump(a, o)\n\n    def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef) -> str:\n        a: Any = o.items.copy()\n        if o.type:\n            a.insert(0, o.type)\n        if o.impl:\n            a.insert(0, o.impl)\n        if o.is_static:\n            a.insert(-1, \"Static\")\n        if o.is_class:\n            a.insert(-1, \"Class\")\n        return self.dump(a, o)\n\n    def visit_class_def(self, o: mypy.nodes.ClassDef) -> str:\n        a = [o.name, o.defs.body]\n        # Display base types unless they are implicitly just builtins.object\n        # (in this case base_type_exprs is empty).\n        if o.base_type_exprs:\n            if o.info and o.info.bases:\n                if len(o.info.bases) != 1 or o.info.bases[0].type.fullname != \"builtins.object\":\n                    a.insert(1, (\"BaseType\", o.info.bases))\n            else:\n                a.insert(1, (\"BaseTypeExpr\", o.base_type_exprs))\n        if o.type_vars:\n            a.insert(1, (\"TypeVars\", o.type_vars))\n        if o.metaclass:\n            a.insert(1, f\"Metaclass({o.metaclass.accept(self)})\")\n        if o.keywords:\n            keyword_items = [f\"{k}={v.accept(self)}\" for k, v in o.keywords.items()]\n            a.insert(1, f\"Keywords({', '.join(keyword_items)})\")\n        if o.decorators:\n            a.insert(1, (\"Decorators\", o.decorators))\n        if o.info and o.info._promote:\n            a.insert(1, f\"Promote([{','.join(self.stringify_type(p) for p in o.info._promote)}])\")\n        if o.info and o.info.tuple_type:\n            a.insert(1, (\"TupleType\", [o.info.tuple_type]))\n        if o.info and o.info.fallback_to_any:\n            a.insert(1, \"FallbackToAny\")\n        if o.type_args:\n            for p in reversed(o.type_args):\n                a.insert(1, self.type_param(p))\n        return self.dump(a, o)\n\n    def visit_var(self, o: mypy.nodes.Var) -> str:\n        lst = \"\"\n        # Add :nil line number tag if no line number is specified to remain\n        # compatible with old test case descriptions that assume this.\n        if o.line < 0:\n            lst = \":nil\"\n        return \"Var\" + lst + \"(\" + o.name + \")\"\n\n    def visit_global_decl(self, o: mypy.nodes.GlobalDecl) -> str:\n        return self.dump([o.names], o)\n\n    def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl) -> str:\n        return self.dump([o.names], o)\n\n    def visit_decorator(self, o: mypy.nodes.Decorator) -> str:\n        return self.dump([o.var, o.decorators, o.func], o)\n\n    def visit_type_alias(self, o: mypy.nodes.TypeAlias, /) -> str:\n        return self.dump([o.name, o.target, o.alias_tvars, o.no_args], o)\n\n    def visit_placeholder_node(self, o: mypy.nodes.PlaceholderNode, /) -> str:\n        return self.dump([o.fullname], o)\n\n    # Statements\n\n    def visit_block(self, o: mypy.nodes.Block) -> str:\n        return self.dump(o.body, o)\n\n    def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt) -> str:\n        return self.dump([o.expr], o)\n\n    def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt) -> str:\n        a: list[Any] = []\n        if len(o.lvalues) > 1:\n            a = [(\"Lvalues\", o.lvalues)]\n        else:\n            a = [o.lvalues[0]]\n        a.append(o.rvalue)\n        if o.type:\n            a.append(o.type)\n        return self.dump(a, o)\n\n    def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt) -> str:\n        return self.dump([o.op, o.lvalue, o.rvalue], o)\n\n    def visit_while_stmt(self, o: mypy.nodes.WhileStmt) -> str:\n        a: list[Any] = [o.expr, o.body]\n        if o.else_body:\n            a.append((\"Else\", o.else_body.body))\n        return self.dump(a, o)\n\n    def visit_for_stmt(self, o: mypy.nodes.ForStmt) -> str:\n        a: list[Any] = []\n        if o.is_async:\n            a.append((\"Async\", \"\"))\n        a.append(o.index)\n        if o.index_type:\n            a.append(o.index_type)\n        a.extend([o.expr, o.body])\n        if o.else_body:\n            a.append((\"Else\", o.else_body.body))\n        return self.dump(a, o)\n\n    def visit_return_stmt(self, o: mypy.nodes.ReturnStmt) -> str:\n        return self.dump([o.expr], o)\n\n    def visit_if_stmt(self, o: mypy.nodes.IfStmt) -> str:\n        a: list[Any] = []\n        for i in range(len(o.expr)):\n            a.append((\"If\", [o.expr[i]]))\n            a.append((\"Then\", o.body[i].body))\n\n        if not o.else_body:\n            return self.dump(a, o)\n        else:\n            return self.dump([a, (\"Else\", o.else_body.body)], o)\n\n    def visit_break_stmt(self, o: mypy.nodes.BreakStmt) -> str:\n        return self.dump([], o)\n\n    def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt) -> str:\n        return self.dump([], o)\n\n    def visit_pass_stmt(self, o: mypy.nodes.PassStmt) -> str:\n        return self.dump([], o)\n\n    def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt) -> str:\n        return self.dump([o.expr, o.from_expr], o)\n\n    def visit_assert_stmt(self, o: mypy.nodes.AssertStmt) -> str:\n        if o.msg is not None:\n            return self.dump([o.expr, o.msg], o)\n        else:\n            return self.dump([o.expr], o)\n\n    def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> str:\n        return self.dump([o.expr], o)\n\n    def visit_del_stmt(self, o: mypy.nodes.DelStmt) -> str:\n        return self.dump([o.expr], o)\n\n    def visit_try_stmt(self, o: mypy.nodes.TryStmt) -> str:\n        a: list[Any] = [o.body]\n        if o.is_star:\n            a.append(\"*\")\n\n        for i in range(len(o.vars)):\n            a.append(o.types[i])\n            if o.vars[i]:\n                a.append(o.vars[i])\n            a.append(o.handlers[i])\n\n        if o.else_body:\n            a.append((\"Else\", o.else_body.body))\n        if o.finally_body:\n            a.append((\"Finally\", o.finally_body.body))\n\n        return self.dump(a, o)\n\n    def visit_with_stmt(self, o: mypy.nodes.WithStmt) -> str:\n        a: list[Any] = []\n        if o.is_async:\n            a.append((\"Async\", \"\"))\n        for i in range(len(o.expr)):\n            a.append((\"Expr\", [o.expr[i]]))\n            if o.target[i]:\n                a.append((\"Target\", [o.target[i]]))\n        if o.unanalyzed_type:\n            a.append(o.unanalyzed_type)\n        return self.dump(a + [o.body], o)\n\n    def visit_match_stmt(self, o: mypy.nodes.MatchStmt) -> str:\n        a: list[Any] = [o.subject]\n        for i in range(len(o.patterns)):\n            a.append((\"Pattern\", [o.patterns[i]]))\n            if o.guards[i] is not None:\n                a.append((\"Guard\", [o.guards[i]]))\n            a.append((\"Body\", o.bodies[i].body))\n        return self.dump(a, o)\n\n    def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt) -> str:\n        a: list[Any] = [o.name]\n        for p in o.type_args:\n            a.append(self.type_param(p))\n        a.append(o.value)\n        return self.dump(a, o)\n\n    def type_param(self, p: mypy.nodes.TypeParam) -> list[Any]:\n        a: list[Any] = []\n        if p.kind == mypy.nodes.PARAM_SPEC_KIND:\n            prefix = \"**\"\n        elif p.kind == mypy.nodes.TYPE_VAR_TUPLE_KIND:\n            prefix = \"*\"\n        else:\n            prefix = \"\"\n        a.append(prefix + p.name)\n        if p.upper_bound:\n            a.append(p.upper_bound)\n        if p.values:\n            a.append((\"Values\", p.values))\n        if p.default:\n            a.append((\"Default\", [p.default]))\n        return [(\"TypeParam\", a)]\n\n    # Expressions\n\n    # Simple expressions\n\n    def visit_int_expr(self, o: mypy.nodes.IntExpr) -> str:\n        return f\"IntExpr({o.value})\"\n\n    def visit_str_expr(self, o: mypy.nodes.StrExpr) -> str:\n        return f\"StrExpr({self.str_repr(o.value)})\"\n\n    def visit_bytes_expr(self, o: mypy.nodes.BytesExpr) -> str:\n        return f\"BytesExpr({self.str_repr(o.value)})\"\n\n    def str_repr(self, s: str) -> str:\n        s = re.sub(r\"\\\\u[0-9a-fA-F]{4}\", lambda m: \"\\\\\" + m.group(0), s)\n        return re.sub(\"[^\\\\x20-\\\\x7e]\", lambda m: r\"\\u%.4x\" % ord(m.group(0)), s)\n\n    def visit_float_expr(self, o: mypy.nodes.FloatExpr) -> str:\n        return f\"FloatExpr({o.value})\"\n\n    def visit_complex_expr(self, o: mypy.nodes.ComplexExpr) -> str:\n        return f\"ComplexExpr({o.value})\"\n\n    def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr) -> str:\n        return \"Ellipsis\"\n\n    def visit_star_expr(self, o: mypy.nodes.StarExpr) -> str:\n        return self.dump([o.expr], o)\n\n    def visit_name_expr(self, o: mypy.nodes.NameExpr) -> str:\n        pretty = self.pretty_name(\n            o.name, o.kind, o.fullname, o.is_inferred_def or o.is_special_form, o.node\n        )\n        if isinstance(o.node, mypy.nodes.Var) and o.node.is_final:\n            final_value = o.node.final_value\n            if final_value is not None:\n                pretty += f\" = {o.node.final_value}\"\n        return short_type(o) + \"(\" + pretty + \")\"\n\n    def pretty_name(\n        self,\n        name: str,\n        kind: int | None,\n        fullname: str | None,\n        is_inferred_def: bool,\n        target_node: mypy.nodes.Node | None = None,\n    ) -> str:\n        n = name\n        if is_inferred_def:\n            n += \"*\"\n        if target_node:\n            id = self.format_id(target_node)\n        else:\n            id = \"\"\n        if isinstance(target_node, mypy.nodes.MypyFile) and name == fullname:\n            n += id\n        elif kind == mypy.nodes.GDEF or (fullname != name and fullname):\n            # Append fully qualified name for global references.\n            n += f\" [{fullname}{id}]\"\n        elif kind == mypy.nodes.LDEF:\n            # Add tag to signify a local reference.\n            n += f\" [l{id}]\"\n        elif kind == mypy.nodes.MDEF:\n            # Add tag to signify a member reference.\n            n += f\" [m{id}]\"\n        else:\n            n += id\n        return n\n\n    def visit_member_expr(self, o: mypy.nodes.MemberExpr) -> str:\n        pretty = self.pretty_name(o.name, o.kind, o.fullname, o.is_inferred_def, o.node)\n        return self.dump([o.expr, pretty], o)\n\n    def visit_yield_expr(self, o: mypy.nodes.YieldExpr) -> str:\n        return self.dump([o.expr], o)\n\n    def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr) -> str:\n        if o.expr:\n            return self.dump([o.expr.accept(self)], o)\n        else:\n            return self.dump([], o)\n\n    def visit_call_expr(self, o: mypy.nodes.CallExpr) -> str:\n        if o.analyzed:\n            return o.analyzed.accept(self)\n        args: list[mypy.nodes.Expression] = []\n        extra: list[str | tuple[str, list[Any]]] = []\n        for i, kind in enumerate(o.arg_kinds):\n            if kind in [mypy.nodes.ARG_POS, mypy.nodes.ARG_STAR]:\n                args.append(o.args[i])\n                if kind == mypy.nodes.ARG_STAR:\n                    extra.append(\"VarArg\")\n            elif kind == mypy.nodes.ARG_NAMED:\n                extra.append((\"KwArgs\", [o.arg_names[i], o.args[i]]))\n            elif kind == mypy.nodes.ARG_STAR2:\n                extra.append((\"DictVarArg\", [o.args[i]]))\n            else:\n                raise RuntimeError(f\"unknown kind {kind}\")\n        a: list[Any] = [o.callee, (\"Args\", args)]\n        return self.dump(a + extra, o)\n\n    def visit_op_expr(self, o: mypy.nodes.OpExpr) -> str:\n        if o.analyzed:\n            return o.analyzed.accept(self)\n        return self.dump([o.op, o.left, o.right], o)\n\n    def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr) -> str:\n        return self.dump([o.operators, o.operands], o)\n\n    def visit_cast_expr(self, o: mypy.nodes.CastExpr) -> str:\n        return self.dump([o.expr, o.type], o)\n\n    def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr) -> str:\n        return self.dump([o.type], o)\n\n    def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr) -> str:\n        return self.dump([o.expr, o.type], o)\n\n    def visit_reveal_expr(self, o: mypy.nodes.RevealExpr) -> str:\n        if o.kind == mypy.nodes.REVEAL_TYPE:\n            return self.dump([o.expr], o)\n        else:\n            # REVEAL_LOCALS\n            return self.dump([o.local_nodes], o)\n\n    def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr) -> str:\n        return self.dump([o.target, o.value], o)\n\n    def visit_unary_expr(self, o: mypy.nodes.UnaryExpr) -> str:\n        return self.dump([o.op, o.expr], o)\n\n    def visit_list_expr(self, o: mypy.nodes.ListExpr) -> str:\n        return self.dump(o.items, o)\n\n    def visit_dict_expr(self, o: mypy.nodes.DictExpr) -> str:\n        return self.dump([[k, v] for k, v in o.items], o)\n\n    def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr) -> str:\n        items_repr: list[object] = []\n        for item in o.items:\n            if isinstance(item, tuple):\n                value_expr, source, conversion, format_spec = item\n                interpolation: list[object] = [\n                    (\"Value\", [value_expr]),\n                    f\"Source({source!r})\",\n                    f\"Conversion({conversion!r})\",\n                ]\n                if format_spec is None:\n                    interpolation.append(\"FormatSpec(None)\")\n                else:\n                    interpolation.append((\"FormatSpec\", [format_spec]))\n                items_repr.append((\"Interpolation\", interpolation))\n            else:\n                items_repr.append(item)\n        return self.dump(items_repr, o)\n\n    def visit_set_expr(self, o: mypy.nodes.SetExpr) -> str:\n        return self.dump(o.items, o)\n\n    def visit_tuple_expr(self, o: mypy.nodes.TupleExpr) -> str:\n        return self.dump(o.items, o)\n\n    def visit_index_expr(self, o: mypy.nodes.IndexExpr) -> str:\n        if o.analyzed:\n            return o.analyzed.accept(self)\n        return self.dump([o.base, o.index], o)\n\n    def visit_super_expr(self, o: mypy.nodes.SuperExpr) -> str:\n        return self.dump([o.name, o.call], o)\n\n    def visit_type_application(self, o: mypy.nodes.TypeApplication) -> str:\n        return self.dump([o.expr, (\"Types\", o.types)], o)\n\n    def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr) -> str:\n        import mypy.types\n\n        a: list[Any] = []\n        if o.variance == mypy.nodes.COVARIANT:\n            a += [\"Variance(COVARIANT)\"]\n        if o.variance == mypy.nodes.CONTRAVARIANT:\n            a += [\"Variance(CONTRAVARIANT)\"]\n        if o.values:\n            a += [(\"Values\", o.values)]\n        if not mypy.types.is_named_instance(o.upper_bound, \"builtins.object\"):\n            a += [f\"UpperBound({self.stringify_type(o.upper_bound)})\"]\n        return self.dump(a, o)\n\n    def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr) -> str:\n        import mypy.types\n\n        a: list[Any] = []\n        if o.variance == mypy.nodes.COVARIANT:\n            a += [\"Variance(COVARIANT)\"]\n        if o.variance == mypy.nodes.CONTRAVARIANT:\n            a += [\"Variance(CONTRAVARIANT)\"]\n        if not mypy.types.is_named_instance(o.upper_bound, \"builtins.object\"):\n            a += [f\"UpperBound({self.stringify_type(o.upper_bound)})\"]\n        return self.dump(a, o)\n\n    def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr) -> str:\n        import mypy.types\n\n        a: list[Any] = []\n        if o.variance == mypy.nodes.COVARIANT:\n            a += [\"Variance(COVARIANT)\"]\n        if o.variance == mypy.nodes.CONTRAVARIANT:\n            a += [\"Variance(CONTRAVARIANT)\"]\n        if not mypy.types.is_named_instance(o.upper_bound, \"builtins.object\"):\n            a += [f\"UpperBound({self.stringify_type(o.upper_bound)})\"]\n        return self.dump(a, o)\n\n    def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr) -> str:\n        return f\"TypeAliasExpr({self.stringify_type(o.node.target)})\"\n\n    def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr) -> str:\n        return f\"NamedTupleExpr:{o.line}({o.info.name}, {self.stringify_type(o.info.tuple_type) if o.info.tuple_type is not None else None})\"\n\n    def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr) -> str:\n        return f\"EnumCallExpr:{o.line}({o.info.name}, {o.items})\"\n\n    def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr) -> str:\n        return f\"TypedDictExpr:{o.line}({o.info.name})\"\n\n    def visit__promote_expr(self, o: mypy.nodes.PromoteExpr) -> str:\n        return f\"PromoteExpr:{o.line}({self.stringify_type(o.type)})\"\n\n    def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr) -> str:\n        return f\"NewTypeExpr:{o.line}({o.name}, {self.dump([o.old_type], o)})\"\n\n    def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr) -> str:\n        a = self.func_helper(o)\n        return self.dump(a, o)\n\n    def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr) -> str:\n        condlists = o.condlists if any(o.condlists) else None\n        return self.dump([o.left_expr, o.indices, o.sequences, condlists], o)\n\n    def visit_list_comprehension(self, o: mypy.nodes.ListComprehension) -> str:\n        return self.dump([o.generator], o)\n\n    def visit_set_comprehension(self, o: mypy.nodes.SetComprehension) -> str:\n        return self.dump([o.generator], o)\n\n    def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension) -> str:\n        condlists = o.condlists if any(o.condlists) else None\n        return self.dump([o.key, o.value, o.indices, o.sequences, condlists], o)\n\n    def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr) -> str:\n        return self.dump([(\"Condition\", [o.cond]), o.if_expr, o.else_expr], o)\n\n    def visit_slice_expr(self, o: mypy.nodes.SliceExpr) -> str:\n        a: list[Any] = [o.begin_index, o.end_index, o.stride]\n        if not a[0]:\n            a[0] = \"<empty>\"\n        if not a[1]:\n            a[1] = \"<empty>\"\n        return self.dump(a, o)\n\n    def visit_temp_node(self, o: mypy.nodes.TempNode) -> str:\n        return self.dump([o.type], o)\n\n    def visit_as_pattern(self, o: mypy.patterns.AsPattern) -> str:\n        return self.dump([o.pattern, o.name], o)\n\n    def visit_or_pattern(self, o: mypy.patterns.OrPattern) -> str:\n        return self.dump(o.patterns, o)\n\n    def visit_value_pattern(self, o: mypy.patterns.ValuePattern) -> str:\n        return self.dump([o.expr], o)\n\n    def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern) -> str:\n        return self.dump([o.value], o)\n\n    def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern) -> str:\n        return self.dump(o.patterns, o)\n\n    def visit_starred_pattern(self, o: mypy.patterns.StarredPattern) -> str:\n        return self.dump([o.capture], o)\n\n    def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern) -> str:\n        a: list[Any] = []\n        for i in range(len(o.keys)):\n            a.append((\"Key\", [o.keys[i]]))\n            a.append((\"Value\", [o.values[i]]))\n        if o.rest is not None:\n            a.append((\"Rest\", [o.rest]))\n        return self.dump(a, o)\n\n    def visit_class_pattern(self, o: mypy.patterns.ClassPattern) -> str:\n        a: list[Any] = [o.class_ref]\n        if len(o.positionals) > 0:\n            a.append((\"Positionals\", o.positionals))\n        for i in range(len(o.keyword_keys)):\n            a.append((\"Keyword\", [o.keyword_keys[i], o.keyword_values[i]]))\n\n        return self.dump(a, o)\n\n\ndef dump_tagged(nodes: Sequence[object], tag: str | None, str_conv: StrConv) -> str:\n    \"\"\"Convert an array into a pretty-printed multiline string representation.\n\n    The format is\n      tag(\n        item1..\n        itemN)\n    Individual items are formatted like this:\n     - arrays are flattened\n     - pairs (str, array) are converted recursively, so that str is the tag\n     - other items are converted to strings and indented\n    \"\"\"\n    from mypy.types import Type, TypeStrVisitor\n\n    a: list[str] = []\n    if tag:\n        a.append(tag + \"(\")\n    for n in nodes:\n        if isinstance(n, list):\n            if n:\n                a.append(dump_tagged(n, None, str_conv))\n        elif isinstance(n, tuple):\n            s = dump_tagged(n[1], n[0], str_conv)\n            a.append(indent(s, 2))\n        elif isinstance(n, mypy.nodes.Node):\n            a.append(indent(n.accept(str_conv), 2))\n        elif isinstance(n, Type):\n            a.append(\n                indent(n.accept(TypeStrVisitor(str_conv.id_mapper, options=str_conv.options)), 2)\n            )\n        elif n is not None:\n            a.append(indent(str(n), 2))\n    if tag:\n        a[-1] += \")\"\n    return \"\\n\".join(a)\n\n\ndef indent(s: str, n: int) -> str:\n    \"\"\"Indent all the lines in s (separated by newlines) by n spaces.\"\"\"\n    s = \" \" * n + s\n    s = s.replace(\"\\n\", \"\\n\" + \" \" * n)\n    return s\n"
  },
  {
    "path": "mypy/stubdoc.py",
    "content": "\"\"\"Parsing/inferring signatures from documentation.\n\nThis module provides several functions to generate better stubs using\ndocstrings and Sphinx docs (.rst files).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport io\nimport keyword\nimport re\nimport tokenize\nfrom collections.abc import MutableMapping, MutableSequence, Sequence\nfrom typing import Any, Final, NamedTuple, TypeAlias as _TypeAlias\n\nimport mypy.util\n\n# Type alias for signatures strings in format ('func_name', '(arg, opt_arg=False)').\nSig: _TypeAlias = tuple[str, str]\n\n\n_TYPE_RE: Final = re.compile(r\"^[a-zA-Z_][\\w\\[\\], .\\\"\\'|]*(\\.[a-zA-Z_][\\w\\[\\], ]*)*$\")\n_ARG_NAME_RE: Final = re.compile(r\"\\**[A-Za-z_][A-Za-z0-9_]*$\")\n\n\ndef is_valid_type(s: str) -> bool:\n    \"\"\"Try to determine whether a string might be a valid type annotation.\"\"\"\n    if s in (\"True\", \"False\", \"retval\"):\n        return False\n    if \",\" in s and \"[\" not in s:\n        return False\n    return _TYPE_RE.match(s) is not None\n\n\nclass ArgSig:\n    \"\"\"Signature info for a single argument.\"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        type: str | None = None,\n        *,\n        default: bool = False,\n        default_value: str = \"...\",\n    ) -> None:\n        self.name = name\n        self.type = type\n        # Does this argument have a default value?\n        self.default = default\n        self.default_value = default_value\n\n    def is_star_arg(self) -> bool:\n        return self.name.startswith(\"*\") and not self.name.startswith(\"**\")\n\n    def is_star_kwarg(self) -> bool:\n        return self.name.startswith(\"**\")\n\n    def __repr__(self) -> str:\n        return \"ArgSig(name={}, type={}, default={})\".format(\n            repr(self.name), repr(self.type), repr(self.default)\n        )\n\n    def __eq__(self, other: Any) -> bool:\n        if isinstance(other, ArgSig):\n            return (\n                self.name == other.name\n                and self.type == other.type\n                and self.default == other.default\n                and self.default_value == other.default_value\n            )\n        return False\n\n\nclass FunctionSig(NamedTuple):\n    name: str\n    args: list[ArgSig]\n    ret_type: str | None\n    type_args: str = \"\"  # TODO implement in stubgenc and remove the default\n    docstring: str | None = None\n\n    def is_special_method(self) -> bool:\n        return bool(\n            self.name.startswith(\"__\")\n            and self.name.endswith(\"__\")\n            and self.args\n            and self.args[0].name in (\"self\", \"cls\")\n        )\n\n    def has_catchall_args(self) -> bool:\n        \"\"\"Return if this signature has catchall args: (*args, **kwargs)\"\"\"\n        if self.args and self.args[0].name in (\"self\", \"cls\"):\n            args = self.args[1:]\n        else:\n            args = self.args\n        return (\n            len(args) == 2\n            and all(a.type in (None, \"object\", \"Any\", \"typing.Any\") for a in args)\n            and args[0].is_star_arg()\n            and args[1].is_star_kwarg()\n        )\n\n    def is_catchall_signature(self) -> bool:\n        \"\"\"Return if this signature is the catchall identity: (*args, **kwargs) -> Any\"\"\"\n        return self.has_catchall_args() and self.ret_type in (None, \"Any\", \"typing.Any\")\n\n    def format_sig(\n        self,\n        indent: str = \"\",\n        is_async: bool = False,\n        any_val: str | None = None,\n        docstring: str | None = None,\n        include_docstrings: bool = False,\n    ) -> str:\n        args: list[str] = []\n        for arg in self.args:\n            arg_def = arg.name\n\n            if arg_def in keyword.kwlist:\n                arg_def = \"_\" + arg_def\n\n            if (\n                arg.type is None\n                and any_val is not None\n                and arg.name not in (\"self\", \"cls\")\n                and not arg.name.startswith(\"*\")\n            ):\n                arg_type: str | None = any_val\n            else:\n                arg_type = arg.type\n            if arg_type:\n                arg_def += \": \" + arg_type\n                if arg.default:\n                    arg_def += f\" = {arg.default_value}\"\n\n            elif arg.default:\n                arg_def += f\"={arg.default_value}\"\n\n            args.append(arg_def)\n\n        retfield = \"\"\n        ret_type = self.ret_type if self.ret_type else any_val\n        if ret_type is not None:\n            retfield = \" -> \" + ret_type\n\n        prefix = \"async \" if is_async else \"\"\n        sig = f\"{indent}{prefix}def {self.name}{self.type_args}({', '.join(args)}){retfield}:\"\n        # if this object has a docstring it's probably produced by a SignatureGenerator, so it\n        # takes precedence over the passed docstring, which acts as a fallback.\n        doc = (self.docstring or docstring) if include_docstrings else None\n        if doc:\n            suffix = f\"\\n{indent}    {mypy.util.quote_docstring(doc)}\"\n        else:\n            suffix = \" ...\"\n        return f\"{sig}{suffix}\"\n\n\n# States of the docstring parser.\nSTATE_INIT: Final = 1\nSTATE_FUNCTION_NAME: Final = 2\nSTATE_ARGUMENT_LIST: Final = 3\nSTATE_ARGUMENT_TYPE: Final = 4\nSTATE_ARGUMENT_DEFAULT: Final = 5\nSTATE_RETURN_VALUE: Final = 6\nSTATE_OPEN_BRACKET: Final = 7  # For generic types.\n\n\nclass DocStringParser:\n    \"\"\"Parse function signatures in documentation.\"\"\"\n\n    def __init__(self, function_name: str) -> None:\n        # Only search for signatures of function with this name.\n        self.function_name = function_name\n        self.state = [STATE_INIT]\n        self.accumulator = \"\"\n        self.arg_type: str | None = None\n        self.arg_name = \"\"\n        self.arg_default: str | None = None\n        self.ret_type = \"Any\"\n        self.found = False\n        self.args: list[ArgSig] = []\n        self.pos_only: int | None = None\n        self.keyword_only: int | None = None\n        # Valid signatures found so far.\n        self.signatures: list[FunctionSig] = []\n\n    def add_token(self, token: tokenize.TokenInfo) -> None:\n        \"\"\"Process next token from the token stream.\"\"\"\n        if (\n            token.type == tokenize.NAME\n            and token.string == self.function_name\n            and self.state[-1] == STATE_INIT\n        ):\n            self.state.append(STATE_FUNCTION_NAME)\n\n        elif (\n            token.type == tokenize.OP\n            and token.string == \"(\"\n            and self.state[-1] == STATE_FUNCTION_NAME\n        ):\n            self.state.pop()\n            self.accumulator = \"\"\n            self.found = True\n            self.state.append(STATE_ARGUMENT_LIST)\n\n        elif self.state[-1] == STATE_FUNCTION_NAME:\n            # Reset state, function name not followed by '('.\n            self.state.pop()\n\n        elif (\n            token.type == tokenize.OP\n            and token.string in (\"[\", \"(\", \"{\")\n            and self.state[-1] != STATE_INIT\n        ):\n            self.accumulator += token.string\n            self.state.append(STATE_OPEN_BRACKET)\n\n        elif (\n            token.type == tokenize.OP\n            and token.string in (\"]\", \")\", \"}\")\n            and self.state[-1] == STATE_OPEN_BRACKET\n        ):\n            self.accumulator += token.string\n            self.state.pop()\n\n        elif (\n            token.type == tokenize.OP\n            and token.string == \":\"\n            and self.state[-1] == STATE_ARGUMENT_LIST\n        ):\n            self.arg_name = self.accumulator\n            self.accumulator = \"\"\n            self.state.append(STATE_ARGUMENT_TYPE)\n\n        elif (\n            token.type == tokenize.OP\n            and token.string == \":\"\n            and self.state[-1] == STATE_ARGUMENT_TYPE\n            and self.accumulator == \"\"\n        ):\n            # We thought we were after the colon of an \"arg_name: arg_type\"\n            # stanza, so we were expecting an \"arg_type\" now. However, we ended\n            # up with \"arg_name::\" (with two colons). That's a C++ type name,\n            # not an argument name followed by a Python type. This function\n            # signature is malformed / invalid.\n            self.reset()\n\n        elif (\n            token.type == tokenize.OP\n            and token.string == \"=\"\n            and self.state[-1] in (STATE_ARGUMENT_LIST, STATE_ARGUMENT_TYPE)\n        ):\n            if self.state[-1] == STATE_ARGUMENT_TYPE:\n                self.arg_type = self.accumulator\n                self.state.pop()\n            else:\n                self.arg_name = self.accumulator\n            self.accumulator = \"\"\n            self.state.append(STATE_ARGUMENT_DEFAULT)\n\n        elif (\n            token.type == tokenize.OP\n            and token.string in (\",\", \")\")\n            and self.state[-1]\n            in (STATE_ARGUMENT_LIST, STATE_ARGUMENT_DEFAULT, STATE_ARGUMENT_TYPE)\n        ):\n            if self.state[-1] == STATE_ARGUMENT_DEFAULT:\n                self.arg_default = self.accumulator\n                self.state.pop()\n            elif self.state[-1] == STATE_ARGUMENT_TYPE:\n                self.arg_type = self.accumulator\n                self.state.pop()\n            elif self.state[-1] == STATE_ARGUMENT_LIST:\n                if self.accumulator == \"*\":\n                    if self.keyword_only is not None:\n                        # Error condition: cannot have * twice\n                        self.reset()\n                        return\n                    self.keyword_only = len(self.args)\n                    self.accumulator = \"\"\n                else:\n                    if self.accumulator.startswith(\"*\"):\n                        self.keyword_only = len(self.args) + 1\n                    self.arg_name = self.accumulator\n                    if not (\n                        token.string == \")\" and self.accumulator.strip() == \"\"\n                    ) and not _ARG_NAME_RE.match(self.arg_name):\n                        # Invalid argument name.\n                        self.reset()\n                        return\n\n            if token.string == \")\":\n                if (\n                    self.state[-1] == STATE_ARGUMENT_LIST\n                    and self.keyword_only is not None\n                    and self.keyword_only == len(self.args)\n                    and not self.arg_name\n                ):\n                    # Error condition: * must be followed by arguments\n                    self.reset()\n                    return\n                self.state.pop()\n\n            # arg_name is empty when there are no args. e.g. func()\n            if self.arg_name:\n                if self.arg_type and not is_valid_type(self.arg_type):\n                    # wrong type, use Any\n                    self.args.append(\n                        ArgSig(name=self.arg_name, type=None, default=bool(self.arg_default))\n                    )\n                else:\n                    self.args.append(\n                        ArgSig(\n                            name=self.arg_name, type=self.arg_type, default=bool(self.arg_default)\n                        )\n                    )\n            self.arg_name = \"\"\n            self.arg_type = None\n            self.arg_default = None\n            self.accumulator = \"\"\n        elif (\n            token.type == tokenize.OP\n            and token.string == \"/\"\n            and self.state[-1] == STATE_ARGUMENT_LIST\n        ):\n            if token.string == \"/\":\n                if self.pos_only is not None or self.keyword_only is not None or not self.args:\n                    # Error cases:\n                    # - / shows up more than once\n                    # - / shows up after *\n                    # - / shows up before any arguments\n                    self.reset()\n                    return\n                self.pos_only = len(self.args)\n                self.state.append(STATE_ARGUMENT_TYPE)\n                self.accumulator = \"\"\n\n        elif token.type == tokenize.OP and token.string == \"->\" and self.state[-1] == STATE_INIT:\n            self.accumulator = \"\"\n            self.state.append(STATE_RETURN_VALUE)\n\n        # ENDMAKER is necessary for python 3.4 and 3.5.\n        elif token.type in (tokenize.NEWLINE, tokenize.ENDMARKER) and self.state[-1] in (\n            STATE_INIT,\n            STATE_RETURN_VALUE,\n        ):\n            if self.state[-1] == STATE_RETURN_VALUE:\n                if not is_valid_type(self.accumulator):\n                    self.reset()\n                    return\n                self.ret_type = self.accumulator\n                self.accumulator = \"\"\n                self.state.pop()\n\n            if self.found:\n                self.signatures.append(\n                    FunctionSig(name=self.function_name, args=self.args, ret_type=self.ret_type)\n                )\n                self.found = False\n            self.args = []\n            self.ret_type = \"Any\"\n            # Leave state as INIT.\n        else:\n            self.accumulator += token.string\n\n    def reset(self) -> None:\n        self.state = [STATE_INIT]\n        self.args = []\n        self.found = False\n        self.accumulator = \"\"\n\n    def get_signatures(self) -> list[FunctionSig]:\n        \"\"\"Return sorted copy of the list of signatures found so far.\"\"\"\n\n        def has_arg(name: str, signature: FunctionSig) -> bool:\n            return any(x.name == name for x in signature.args)\n\n        def args_kwargs(signature: FunctionSig) -> bool:\n            return has_arg(\"*args\", signature) and has_arg(\"**kwargs\", signature)\n\n        # Move functions with (*args, **kwargs) in their signature to last place.\n        return sorted(self.signatures, key=lambda x: 1 if args_kwargs(x) else 0)\n\n\ndef infer_sig_from_docstring(docstr: str | None, name: str) -> list[FunctionSig] | None:\n    \"\"\"Convert function signature to list of FunctionSig\n\n    Look for function signatures of function in docstring. Signature is a string of\n    the format <function_name>(<signature>) -> <return type> or perhaps without\n    the return type.\n\n    Returns empty list, when no signature is found, one signature in typical case,\n    multiple signatures, if docstring specifies multiple signatures for overload functions.\n    Return None if the docstring is empty.\n\n    Arguments:\n        * docstr: docstring\n        * name: name of function for which signatures are to be found\n    \"\"\"\n    if not (isinstance(docstr, str) and docstr):\n        return None\n\n    state = DocStringParser(name)\n    # Return all found signatures, even if there is a parse error after some are found.\n    with contextlib.suppress(tokenize.TokenError):\n        try:\n            tokens = tokenize.tokenize(io.BytesIO(docstr.encode(\"utf-8\")).readline)\n            for token in tokens:\n                state.add_token(token)\n        except IndentationError:\n            return None\n    sigs = state.get_signatures()\n\n    def is_unique_args(sig: FunctionSig) -> bool:\n        \"\"\"return true if function argument names are unique\"\"\"\n        return len(sig.args) == len({arg.name for arg in sig.args})\n\n    # Return only signatures that have unique argument names. Mypy fails on non-unique arg names.\n    return [sig for sig in sigs if is_unique_args(sig)]\n\n\ndef infer_arg_sig_from_anon_docstring(docstr: str) -> list[ArgSig]:\n    \"\"\"Convert signature in form of \"(self: TestClass, arg0: str='ada')\" to List[TypedArgList].\"\"\"\n    ret = infer_sig_from_docstring(\"stub\" + docstr, \"stub\")\n    if ret:\n        return ret[0].args\n    return []\n\n\ndef infer_ret_type_sig_from_docstring(docstr: str, name: str) -> str | None:\n    \"\"\"Convert signature in form of \"func(self: TestClass, arg0) -> int\" to their return type.\"\"\"\n    ret = infer_sig_from_docstring(docstr, name)\n    if ret:\n        return ret[0].ret_type\n    return None\n\n\ndef infer_ret_type_sig_from_anon_docstring(docstr: str) -> str | None:\n    \"\"\"Convert signature in form of \"(self: TestClass, arg0) -> int\" to their return type.\"\"\"\n    lines = [\"stub\" + line.strip() for line in docstr.splitlines() if line.strip().startswith(\"(\")]\n    return infer_ret_type_sig_from_docstring(\"\".join(lines), \"stub\")\n\n\ndef parse_signature(sig: str) -> tuple[str, list[str], list[str]] | None:\n    \"\"\"Split function signature into its name, positional an optional arguments.\n\n    The expected format is \"func_name(arg, opt_arg=False)\". Return the name of function\n    and lists of positional and optional argument names.\n    \"\"\"\n    m = re.match(r\"([.a-zA-Z0-9_]+)\\(([^)]*)\\)\", sig)\n    if not m:\n        return None\n    name = m.group(1)\n    name = name.split(\".\")[-1]\n    arg_string = m.group(2)\n    if not arg_string.strip():\n        # Simple case -- no arguments.\n        return name, [], []\n\n    args = [arg.strip() for arg in arg_string.split(\",\")]\n    positional = []\n    optional = []\n    i = 0\n    while i < len(args):\n        # Accept optional arguments as in both formats: x=None and [x].\n        if args[i].startswith(\"[\") or \"=\" in args[i]:\n            break\n        positional.append(args[i].rstrip(\"[\"))\n        i += 1\n        if args[i - 1].endswith(\"[\"):\n            break\n    while i < len(args):\n        arg = args[i]\n        arg = arg.strip(\"[]\")\n        arg = arg.split(\"=\")[0]\n        optional.append(arg)\n        i += 1\n    return name, positional, optional\n\n\ndef build_signature(positional: Sequence[str], optional: Sequence[str]) -> str:\n    \"\"\"Build function signature from lists of positional and optional argument names.\"\"\"\n    args: MutableSequence[str] = []\n    args.extend(positional)\n    for arg in optional:\n        if arg.startswith(\"*\"):\n            args.append(arg)\n        else:\n            args.append(f\"{arg}=...\")\n    sig = f\"({', '.join(args)})\"\n    # Ad-hoc fixes.\n    sig = sig.replace(\"(self)\", \"\")\n    return sig\n\n\ndef parse_all_signatures(lines: Sequence[str]) -> tuple[list[Sig], list[Sig]]:\n    \"\"\"Parse all signatures in a given reST document.\n\n    Return lists of found signatures for functions and classes.\n    \"\"\"\n    sigs = []\n    class_sigs = []\n    for line in lines:\n        line = line.strip()\n        m = re.match(r\"\\.\\. *(function|method|class) *:: *[a-zA-Z_]\", line)\n        if m:\n            sig = line.split(\"::\")[1].strip()\n            parsed = parse_signature(sig)\n            if parsed:\n                name, fixed, optional = parsed\n                if m.group(1) != \"class\":\n                    sigs.append((name, build_signature(fixed, optional)))\n                else:\n                    class_sigs.append((name, build_signature(fixed, optional)))\n\n    return sorted(sigs), sorted(class_sigs)\n\n\ndef find_unique_signatures(sigs: Sequence[Sig]) -> list[Sig]:\n    \"\"\"Remove names with duplicate found signatures.\"\"\"\n    sig_map: MutableMapping[str, list[str]] = {}\n    for name, sig in sigs:\n        sig_map.setdefault(name, []).append(sig)\n\n    result = []\n    for name, name_sigs in sig_map.items():\n        if len(set(name_sigs)) == 1:\n            result.append((name, name_sigs[0]))\n    return sorted(result)\n\n\ndef infer_prop_type_from_docstring(docstr: str | None) -> str | None:\n    \"\"\"Check for Google/Numpy style docstring type annotation for a property.\n\n    The docstring has the format \"<type>: <descriptions>\".\n    In the type string, we allow the following characters:\n    * dot: because sometimes classes are annotated using full path\n    * brackets: to allow type hints like List[int]\n    * comma/space: things like Tuple[int, int]\n    \"\"\"\n    if not docstr:\n        return None\n    test_str = r\"^([a-zA-Z0-9_, \\.\\[\\]]*): \"\n    m = re.match(test_str, docstr)\n    return m.group(1) if m else None\n"
  },
  {
    "path": "mypy/stubgen.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Generator of dynamically typed draft stubs for arbitrary modules.\n\nThe logic of this script can be split in three steps:\n* parsing options and finding sources:\n  - use runtime imports be default (to find also C modules)\n  - or use mypy's mechanisms, if importing is prohibited\n* (optionally) semantically analysing the sources using mypy (as a single set)\n* emitting the stubs text:\n  - for Python modules: from ASTs using ASTStubGenerator\n  - for C modules using runtime introspection and (optionally) Sphinx docs\n\nDuring first and third steps some problematic files can be skipped, but any\nblocking error during second step will cause the whole program to stop.\n\nBasic usage:\n\n  $ stubgen foo.py bar.py some_directory\n  => Generate out/foo.pyi, out/bar.pyi, and stubs for some_directory (recursively).\n\n  $ stubgen -m urllib.parse\n  => Generate out/urllib/parse.pyi.\n\n  $ stubgen -p urllib\n  => Generate stubs for whole urllib package (recursively).\n\nFor C modules, you can get more precise function signatures by parsing .rst (Sphinx)\ndocumentation for extra information. For this, use the --doc-dir option:\n\n  $ stubgen --doc-dir <DIR>/Python-3.4.2/Doc/library -m curses\n\nNote: The generated stubs should be verified manually.\n\nTODO:\n - maybe use .rst docs also for Python modules\n - maybe export more imported names if there is no __all__ (this affects ssl.SSLError, for example)\n   - a quick and dirty heuristic would be to turn this on if a module has something like\n     'from x import y as _y'\n - we don't seem to always detect properties ('closed' in 'io', for example)\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport keyword\nimport os\nimport os.path\nimport sys\nimport traceback\nfrom collections.abc import Iterable, Iterator\nfrom typing import Final\n\nimport mypy.build\nimport mypy.mixedtraverser\nimport mypy.parse\nimport mypy.traverser\nimport mypy.util\nimport mypy.version\nfrom mypy.build import build\nfrom mypy.errors import CompileError, Errors\nfrom mypy.find_sources import InvalidSourceList, create_source_list\nfrom mypy.modulefinder import (\n    BuildSource,\n    FindModuleCache,\n    ModuleNotFoundReason,\n    SearchPaths,\n    default_lib_path,\n)\nfrom mypy.moduleinspect import ModuleInspect, is_pyc_only\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    IS_ABSTRACT,\n    NOT_ABSTRACT,\n    AssignmentStmt,\n    Block,\n    BytesExpr,\n    CallExpr,\n    CastExpr,\n    ClassDef,\n    ComparisonExpr,\n    ComplexExpr,\n    ConditionalExpr,\n    Decorator,\n    DictExpr,\n    DictionaryComprehension,\n    EllipsisExpr,\n    Expression,\n    ExpressionStmt,\n    FloatExpr,\n    FuncBase,\n    FuncDef,\n    GeneratorExpr,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    OpExpr,\n    OverloadedFuncDef,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    Statement,\n    StrExpr,\n    TemplateStrExpr,\n    TempNode,\n    TupleExpr,\n    TypeAliasStmt,\n    TypeInfo,\n    UnaryExpr,\n    Var,\n)\nfrom mypy.options import Options as MypyOptions\nfrom mypy.plugins.dataclasses import DATACLASS_FIELD_SPECIFIERS\nfrom mypy.semanal_shared import find_dataclass_transform_spec\nfrom mypy.sharedparse import MAGIC_METHODS_POS_ARGS_ONLY\nfrom mypy.stubdoc import ArgSig, FunctionSig\nfrom mypy.stubgenc import InspectionStubGenerator, generate_stub_for_c_module\nfrom mypy.stubutil import (\n    TYPING_BUILTIN_REPLACEMENTS,\n    BaseStubGenerator,\n    CantImport,\n    ClassInfo,\n    FunctionContext,\n    common_dir_prefix,\n    fail_missing,\n    find_module_path_and_all_py3,\n    generate_guarded,\n    infer_method_arg_types,\n    infer_method_ret_type,\n    remove_misplaced_type_comments,\n    report_missing,\n    walk_packages,\n)\nfrom mypy.traverser import (\n    all_yield_expressions,\n    has_return_statement,\n    has_yield_expression,\n    has_yield_from_expression,\n)\nfrom mypy.types import (\n    DATACLASS_TRANSFORM_NAMES,\n    OVERLOAD_NAMES,\n    TPDICT_NAMES,\n    TYPE_VAR_LIKE_NAMES,\n    TYPED_NAMEDTUPLE_NAMES,\n    AnyType,\n    CallableType,\n    Instance,\n    TupleType,\n    Type,\n    UnboundType,\n    get_proper_type,\n)\nfrom mypy.visitor import NodeVisitor\n\n# Common ways of naming package containing vendored modules.\nVENDOR_PACKAGES: Final = [\"packages\", \"vendor\", \"vendored\", \"_vendor\", \"_vendored_packages\"]\n\n# Avoid some file names that are unnecessary or likely to cause trouble (\\n for end of path).\nBLACKLIST: Final = [\n    \"/six.py\\n\",  # Likely vendored six; too dynamic for us to handle\n    \"/vendored/\",  # Vendored packages\n    \"/vendor/\",  # Vendored packages\n    \"/_vendor/\",\n    \"/_vendored_packages/\",\n]\n\n# These methods are expected to always return a non-trivial value.\nMETHODS_WITH_RETURN_VALUE: Final = {\n    \"__ne__\",\n    \"__eq__\",\n    \"__lt__\",\n    \"__le__\",\n    \"__gt__\",\n    \"__ge__\",\n    \"__hash__\",\n    \"__iter__\",\n}\n\n\nclass Options:\n    \"\"\"Represents stubgen options.\n\n    This class is mutable to simplify testing.\n    \"\"\"\n\n    def __init__(\n        self,\n        pyversion: tuple[int, int],\n        no_import: bool,\n        inspect: bool,\n        doc_dir: str,\n        search_path: list[str],\n        interpreter: str,\n        parse_only: bool,\n        ignore_errors: bool,\n        include_private: bool,\n        output_dir: str,\n        modules: list[str],\n        packages: list[str],\n        files: list[str],\n        verbose: bool,\n        quiet: bool,\n        export_less: bool,\n        include_docstrings: bool,\n    ) -> None:\n        # See parse_options for descriptions of the flags.\n        self.pyversion = pyversion\n        self.no_import = no_import\n        self.inspect = inspect\n        self.doc_dir = doc_dir\n        self.search_path = search_path\n        self.interpreter = interpreter\n        self.decointerpreter = interpreter\n        self.parse_only = parse_only\n        self.ignore_errors = ignore_errors\n        self.include_private = include_private\n        self.output_dir = output_dir\n        self.modules = modules\n        self.packages = packages\n        self.files = files\n        self.verbose = verbose\n        self.quiet = quiet\n        self.export_less = export_less\n        self.include_docstrings = include_docstrings\n\n\nclass StubSource:\n    \"\"\"A single source for stub: can be a Python or C module.\n\n    A simple extension of BuildSource that also carries the AST and\n    the value of __all__ detected at runtime.\n    \"\"\"\n\n    def __init__(\n        self, module: str, path: str | None = None, runtime_all: list[str] | None = None\n    ) -> None:\n        self.source = BuildSource(path, module, None)\n        self.runtime_all = runtime_all\n        self.ast: MypyFile | None = None\n\n    def __repr__(self) -> str:\n        return f\"StubSource({self.source})\"\n\n    @property\n    def module(self) -> str:\n        return self.source.module\n\n    @property\n    def path(self) -> str | None:\n        return self.source.path\n\n\n# What was generated previously in the stub file. We keep track of these to generate\n# nicely formatted output (add empty line between non-empty classes, for example).\nEMPTY: Final = \"EMPTY\"\nFUNC: Final = \"FUNC\"\nCLASS: Final = \"CLASS\"\nEMPTY_CLASS: Final = \"EMPTY_CLASS\"\nVAR: Final = \"VAR\"\nNOT_IN_ALL: Final = \"NOT_IN_ALL\"\n\n# Indicates that we failed to generate a reasonable output\n# for a given node. These should be manually replaced by a user.\n\nERROR_MARKER: Final = \"<ERROR>\"\n\n\nclass AliasPrinter(NodeVisitor[str]):\n    \"\"\"Visitor used to collect type aliases _and_ type variable definitions.\n\n    Visit r.h.s of the definition to get the string representation of type alias.\n    \"\"\"\n\n    def __init__(self, stubgen: ASTStubGenerator) -> None:\n        self.stubgen = stubgen\n        super().__init__()\n\n    def visit_call_expr(self, node: CallExpr) -> str:\n        # Call expressions are not usually types, but we also treat `X = TypeVar(...)` as a\n        # type alias that has to be preserved (even if TypeVar is not the same as an alias)\n        callee = node.callee.accept(self)\n        args = []\n        for name, arg, kind in zip(node.arg_names, node.args, node.arg_kinds):\n            if kind == ARG_POS:\n                args.append(arg.accept(self))\n            elif kind == ARG_STAR:\n                args.append(\"*\" + arg.accept(self))\n            elif kind == ARG_STAR2:\n                args.append(\"**\" + arg.accept(self))\n            elif kind == ARG_NAMED:\n                args.append(f\"{name}={arg.accept(self)}\")\n            else:\n                raise ValueError(f\"Unknown argument kind {kind} in call\")\n        return f\"{callee}({', '.join(args)})\"\n\n    def _visit_ref_expr(self, node: NameExpr | MemberExpr) -> str:\n        fullname = self.stubgen.get_fullname(node)\n        if fullname in TYPING_BUILTIN_REPLACEMENTS:\n            return self.stubgen.add_name(TYPING_BUILTIN_REPLACEMENTS[fullname], require=False)\n        qualname = get_qualified_name(node)\n        self.stubgen.import_tracker.require_name(qualname)\n        return qualname\n\n    def visit_name_expr(self, node: NameExpr) -> str:\n        return self._visit_ref_expr(node)\n\n    def visit_member_expr(self, o: MemberExpr) -> str:\n        return self._visit_ref_expr(o)\n\n    def _visit_literal_node(\n        self, node: StrExpr | BytesExpr | IntExpr | FloatExpr | ComplexExpr\n    ) -> str:\n        return repr(node.value)\n\n    def visit_str_expr(self, node: StrExpr) -> str:\n        return self._visit_literal_node(node)\n\n    def visit_bytes_expr(self, node: BytesExpr) -> str:\n        return f\"b{self._visit_literal_node(node)}\"\n\n    def visit_int_expr(self, node: IntExpr) -> str:\n        return self._visit_literal_node(node)\n\n    def visit_float_expr(self, node: FloatExpr) -> str:\n        return self._visit_literal_node(node)\n\n    def visit_complex_expr(self, node: ComplexExpr) -> str:\n        return self._visit_literal_node(node)\n\n    def visit_index_expr(self, node: IndexExpr) -> str:\n        base_fullname = self.stubgen.get_fullname(node.base)\n        if base_fullname == \"typing.Union\":\n            if isinstance(node.index, TupleExpr):\n                return \" | \".join([item.accept(self) for item in node.index.items])\n            return node.index.accept(self)\n        if base_fullname == \"typing.Optional\":\n            if isinstance(node.index, TupleExpr):\n                return self.stubgen.add_name(\"_typeshed.Incomplete\")\n            return f\"{node.index.accept(self)} | None\"\n        base = node.base.accept(self)\n        index = node.index.accept(self)\n        if len(index) > 2 and index.startswith(\"(\") and index.endswith(\")\"):\n            index = index[1:-1].rstrip(\",\")\n        return f\"{base}[{index}]\"\n\n    def visit_tuple_expr(self, node: TupleExpr) -> str:\n        suffix = \",\" if len(node.items) == 1 else \"\"\n        return f\"({', '.join(n.accept(self) for n in node.items)}{suffix})\"\n\n    def visit_list_expr(self, node: ListExpr) -> str:\n        return f\"[{', '.join(n.accept(self) for n in node.items)}]\"\n\n    def visit_set_expr(self, node: SetExpr) -> str:\n        return f\"{{{', '.join(n.accept(self) for n in node.items)}}}\"\n\n    def visit_dict_expr(self, o: DictExpr) -> str:\n        dict_items = []\n        for key, value in o.items:\n            # This is currently only used for TypedDict where all keys are strings.\n            assert isinstance(key, StrExpr)\n            dict_items.append(f\"{key.accept(self)}: {value.accept(self)}\")\n        return f\"{{{', '.join(dict_items)}}}\"\n\n    def visit_template_str_expr(self, o: TemplateStrExpr) -> str:\n        return self.stubgen.add_name(\"_typeshed.Incomplete\")\n\n    def visit_ellipsis(self, node: EllipsisExpr) -> str:\n        return \"...\"\n\n    def visit_op_expr(self, o: OpExpr) -> str:\n        return f\"{o.left.accept(self)} {o.op} {o.right.accept(self)}\"\n\n    def visit_unary_expr(self, o: UnaryExpr, /) -> str:\n        return f\"{o.op}{o.expr.accept(self)}\"\n\n    def visit_slice_expr(self, o: SliceExpr, /) -> str:\n        blocks = [\n            o.begin_index.accept(self) if o.begin_index is not None else \"\",\n            o.end_index.accept(self) if o.end_index is not None else \"\",\n        ]\n        if o.stride is not None:\n            blocks.append(o.stride.accept(self))\n        return \":\".join(blocks)\n\n    def visit_star_expr(self, o: StarExpr) -> str:\n        return f\"*{o.expr.accept(self)}\"\n\n    def visit_lambda_expr(self, o: LambdaExpr) -> str:\n        # TODO: Required for among other things dataclass.field default_factory\n        return self.stubgen.add_name(\"_typeshed.Incomplete\")\n\n    def _visit_unsupported_expr(self, o: object) -> str:\n        # Something we do not understand.\n        return self.stubgen.add_name(\"_typeshed.Incomplete\")\n\n    def visit_comparison_expr(self, o: ComparisonExpr) -> str:\n        return self._visit_unsupported_expr(o)\n\n    def visit_cast_expr(self, o: CastExpr) -> str:\n        return self._visit_unsupported_expr(o)\n\n    def visit_conditional_expr(self, o: ConditionalExpr) -> str:\n        return self._visit_unsupported_expr(o)\n\n    def visit_list_comprehension(self, o: ListComprehension) -> str:\n        return self._visit_unsupported_expr(o)\n\n    def visit_set_comprehension(self, o: SetComprehension) -> str:\n        return self._visit_unsupported_expr(o)\n\n    def visit_dictionary_comprehension(self, o: DictionaryComprehension) -> str:\n        return self._visit_unsupported_expr(o)\n\n    def visit_generator_expr(self, o: GeneratorExpr) -> str:\n        return self._visit_unsupported_expr(o)\n\n\ndef find_defined_names(file: MypyFile) -> set[str]:\n    finder = DefinitionFinder()\n    file.accept(finder)\n    return finder.names\n\n\ndef get_assigned_names(lvalues: Iterable[Expression]) -> Iterator[str]:\n    for lvalue in lvalues:\n        if isinstance(lvalue, NameExpr):\n            yield lvalue.name\n        elif isinstance(lvalue, TupleExpr):\n            yield from get_assigned_names(lvalue.items)\n\n\nclass DefinitionFinder(mypy.traverser.TraverserVisitor):\n    \"\"\"Find names of things defined at the top level of a module.\"\"\"\n\n    def __init__(self) -> None:\n        # Short names of things defined at the top level.\n        self.names: set[str] = set()\n\n    def visit_class_def(self, o: ClassDef) -> None:\n        # Don't recurse into classes, as we only keep track of top-level definitions.\n        self.names.add(o.name)\n\n    def visit_func_def(self, o: FuncDef) -> None:\n        # Don't recurse, as we only keep track of top-level definitions.\n        self.names.add(o.name)\n\n    def visit_assignment_stmt(self, o: AssignmentStmt) -> None:\n        for name in get_assigned_names(o.lvalues):\n            self.names.add(name)\n\n    def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None:\n        self.names.add(o.name.name)\n\n\ndef find_referenced_names(file: MypyFile) -> set[str]:\n    finder = ReferenceFinder()\n    file.accept(finder)\n    return finder.refs\n\n\ndef is_none_expr(expr: Expression) -> bool:\n    return isinstance(expr, NameExpr) and expr.name == \"None\"\n\n\nclass ReferenceFinder(mypy.mixedtraverser.MixedTraverserVisitor):\n    \"\"\"Find all name references (both local and global).\"\"\"\n\n    # TODO: Filter out local variable and class attribute references\n\n    def __init__(self) -> None:\n        # Short names of things defined at the top level.\n        self.refs: set[str] = set()\n\n    def visit_block(self, block: Block) -> None:\n        if not block.is_unreachable:\n            super().visit_block(block)\n\n    def visit_name_expr(self, e: NameExpr) -> None:\n        self.refs.add(e.name)\n\n    def visit_instance(self, t: Instance) -> None:\n        self.add_ref(t.type.name)\n        super().visit_instance(t)\n\n    def visit_unbound_type(self, t: UnboundType) -> None:\n        if t.name:\n            self.add_ref(t.name)\n\n    def visit_tuple_type(self, t: TupleType) -> None:\n        # Ignore fallback\n        for item in t.items:\n            item.accept(self)\n\n    def visit_callable_type(self, t: CallableType) -> None:\n        # Ignore fallback\n        for arg in t.arg_types:\n            arg.accept(self)\n        t.ret_type.accept(self)\n\n    def add_ref(self, fullname: str) -> None:\n        self.refs.add(fullname)\n        while \".\" in fullname:\n            fullname = fullname.rsplit(\".\", 1)[0]\n            self.refs.add(fullname)\n\n\nclass ASTStubGenerator(BaseStubGenerator, mypy.traverser.TraverserVisitor):\n    \"\"\"Generate stub text from a mypy AST.\"\"\"\n\n    def __init__(\n        self,\n        _all_: list[str] | None = None,\n        include_private: bool = False,\n        analyzed: bool = False,\n        export_less: bool = False,\n        include_docstrings: bool = False,\n    ) -> None:\n        super().__init__(_all_, include_private, export_less, include_docstrings)\n        self._decorators: list[str] = []\n        # Stack of defined variables (per scope).\n        self._vars: list[list[str]] = [[]]\n        # What was generated previously in the stub file.\n        self._state = EMPTY\n        self._class_stack: list[ClassDef] = []\n        # Was the tree semantically analysed before?\n        self.analyzed = analyzed\n        # Short names of methods defined in the body of the current class\n        self.method_names: set[str] = set()\n        self.processing_enum = False\n        self.processing_dataclass = False\n        self.dataclass_field_specifier: tuple[str, ...] = ()\n\n    @property\n    def _current_class(self) -> ClassDef | None:\n        return self._class_stack[-1] if self._class_stack else None\n\n    def visit_mypy_file(self, o: MypyFile) -> None:\n        self.module_name = o.fullname  # Current module being processed\n        self.path = o.path\n        self.set_defined_names(find_defined_names(o))\n        self.referenced_names = find_referenced_names(o)\n        super().visit_mypy_file(o)\n        self.check_undefined_names()\n\n    def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None:\n        \"\"\"@property with setters and getters, @overload chain and some others.\"\"\"\n        overload_chain = False\n        for item in o.items:\n            if not isinstance(item, Decorator):\n                continue\n            if self.is_private_name(item.func.name, item.func.fullname):\n                continue\n\n            self.process_decorator(item)\n            if not overload_chain:\n                self.visit_func_def(item.func)\n                if item.func.is_overload:\n                    overload_chain = True\n            elif item.func.is_overload:\n                self.visit_func_def(item.func)\n            else:\n                # skip the overload implementation and clear the decorator we just processed\n                self.clear_decorators()\n\n    def get_default_function_sig(self, func_def: FuncDef, ctx: FunctionContext) -> FunctionSig:\n        args = self._get_func_args(func_def, ctx)\n        retname = self._get_func_return(func_def, ctx)\n        type_args = self.format_type_args(func_def)\n        return FunctionSig(func_def.name, args, retname, type_args)\n\n    def _get_func_args(self, o: FuncDef, ctx: FunctionContext) -> list[ArgSig]:\n        args: list[ArgSig] = []\n\n        # Ignore pos-only status of magic methods whose args names are elided by mypy at parse\n        actually_pos_only_args = o.name not in MAGIC_METHODS_POS_ARGS_ONLY\n        pos_only_marker_position = 0  # Where to insert \"/\", if any\n        for i, arg_ in enumerate(o.arguments):\n            var = arg_.variable\n            kind = arg_.kind\n            name = var.name\n            annotated_type = (\n                o.unanalyzed_type.arg_types[i]\n                if isinstance(o.unanalyzed_type, CallableType)\n                else None\n            )\n            # I think the name check is incorrect: there are libraries which\n            # name their 0th argument other than self/cls\n            is_self_arg = i == 0 and name == \"self\"\n            is_cls_arg = i == 0 and name == \"cls\"\n            typename: str | None = None\n            if annotated_type and not is_self_arg and not is_cls_arg:\n                # Luckily, an argument explicitly annotated with \"Any\" has\n                # type \"UnboundType\" and will not match.\n                if not isinstance(get_proper_type(annotated_type), AnyType):\n                    typename = self.print_annotation(annotated_type)\n\n            if actually_pos_only_args and arg_.pos_only:\n                pos_only_marker_position += 1\n\n            if kind.is_named() and not any(arg.name.startswith(\"*\") for arg in args):\n                args.append(ArgSig(\"*\"))\n\n            default = \"...\"\n            if arg_.initializer:\n                if not typename:\n                    typename = self.get_str_type_of_node(arg_.initializer, can_be_incomplete=False)\n                potential_default, valid = self.get_str_default_of_node(arg_.initializer)\n                if valid and len(potential_default) <= 200:\n                    default = potential_default\n            elif kind == ARG_STAR:\n                name = f\"*{name}\"\n            elif kind == ARG_STAR2:\n                name = f\"**{name}\"\n\n            args.append(\n                ArgSig(name, typename, default=bool(arg_.initializer), default_value=default)\n            )\n        if pos_only_marker_position:\n            args.insert(pos_only_marker_position, ArgSig(\"/\"))\n\n        if ctx.class_info is not None and all(\n            arg.type is None and arg.default is False for arg in args\n        ):\n            new_args = infer_method_arg_types(\n                ctx.name, ctx.class_info.self_var, [arg.name for arg in args]\n            )\n\n            if ctx.name == \"__exit__\":\n                self.import_tracker.add_import(\"types\")\n                self.import_tracker.require_name(\"types\")\n\n            if new_args is not None:\n                args = new_args\n\n        return args\n\n    def _get_func_return(self, o: FuncDef, ctx: FunctionContext) -> str | None:\n        if o.name != \"__init__\" and isinstance(o.unanalyzed_type, CallableType):\n            if isinstance(get_proper_type(o.unanalyzed_type.ret_type), AnyType):\n                # Luckily, a return type explicitly annotated with \"Any\" has\n                # type \"UnboundType\" and will enter the else branch.\n                return None  # implicit Any\n            else:\n                return self.print_annotation(o.unanalyzed_type.ret_type)\n        if o.abstract_status == IS_ABSTRACT or o.name in METHODS_WITH_RETURN_VALUE:\n            # Always assume abstract methods return Any unless explicitly annotated. Also\n            # some dunder methods should not have a None return type.\n            return None  # implicit Any\n        retname = infer_method_ret_type(o.name)\n        if retname is not None:\n            return retname\n        if has_yield_expression(o) or has_yield_from_expression(o):\n            generator_name = self.add_name(\"collections.abc.Generator\")\n            yield_name = \"None\"\n            send_name: str | None = None\n            return_name: str | None = None\n            if has_yield_from_expression(o):\n                yield_name = send_name = self.add_name(\"_typeshed.Incomplete\")\n            else:\n                for expr, in_assignment in all_yield_expressions(o):\n                    if expr.expr is not None and not is_none_expr(expr.expr):\n                        yield_name = self.add_name(\"_typeshed.Incomplete\")\n                    if in_assignment:\n                        send_name = self.add_name(\"_typeshed.Incomplete\")\n            if has_return_statement(o):\n                return_name = self.add_name(\"_typeshed.Incomplete\")\n            if return_name is not None:\n                if send_name is None:\n                    send_name = \"None\"\n                return f\"{generator_name}[{yield_name}, {send_name}, {return_name}]\"\n            elif send_name is not None:\n                return f\"{generator_name}[{yield_name}, {send_name}]\"\n            else:\n                return f\"{generator_name}[{yield_name}]\"\n        if not has_return_statement(o) and o.abstract_status == NOT_ABSTRACT:\n            return \"None\"\n        return None\n\n    def _get_func_docstring(self, node: FuncDef) -> str | None:\n        if not node.body.body:\n            return None\n        expr = node.body.body[0]\n        if isinstance(expr, ExpressionStmt) and isinstance(expr.expr, StrExpr):\n            return expr.expr.value\n        return None\n\n    def visit_func_def(self, o: FuncDef) -> None:\n        is_dataclass_generated = (\n            self.analyzed and self.processing_dataclass and o.info.names[o.name].plugin_generated\n        )\n        if is_dataclass_generated:\n            # Skip methods generated by the @dataclass decorator\n            return\n        if (\n            self.is_private_name(o.name, o.fullname)\n            or self.is_not_in_all(o.name)\n            or (self.is_recorded_name(o.name) and not o.is_overload)\n        ):\n            self.clear_decorators()\n            return\n        if self.is_top_level() and self._state not in (EMPTY, FUNC):\n            self.add(\"\\n\")\n        if not self.is_top_level():\n            self_inits = find_self_initializers(o)\n            for init, value, annotation in self_inits:\n                if init in self.method_names:\n                    # Can't have both an attribute and a method/property with the same name.\n                    continue\n                init_code = self.get_init(init, value, annotation)\n                if init_code:\n                    self.add(init_code)\n\n        if self._class_stack:\n            if len(o.arguments):\n                self_var = o.arguments[0].variable.name\n            else:\n                self_var = \"self\"\n            class_info: ClassInfo | None = None\n            for class_def in self._class_stack:\n                class_info = ClassInfo(class_def.name, self_var, parent=class_info)\n        else:\n            class_info = None\n\n        ctx = FunctionContext(\n            module_name=self.module_name,\n            name=o.name,\n            docstring=self._get_func_docstring(o),\n            is_abstract=o.abstract_status != NOT_ABSTRACT,\n            class_info=class_info,\n        )\n\n        self.record_name(o.name)\n\n        default_sig = self.get_default_function_sig(o, ctx)\n        sigs = self.get_signatures(default_sig, self.sig_generators, ctx)\n\n        for output in self.format_func_def(\n            sigs, is_coroutine=o.is_coroutine, decorators=self._decorators, docstring=ctx.docstring\n        ):\n            self.add(output + \"\\n\")\n\n        self.clear_decorators()\n        self._state = FUNC\n\n    def visit_decorator(self, o: Decorator) -> None:\n        if self.is_private_name(o.func.name, o.func.fullname):\n            return\n        self.process_decorator(o)\n        self.visit_func_def(o.func)\n\n    def process_decorator(self, o: Decorator) -> None:\n        \"\"\"Process a series of decorators.\n\n        Only preserve certain special decorators such as @abstractmethod.\n        \"\"\"\n        o.func.is_overload = False\n        for decorator in o.original_decorators:\n            d = decorator\n            if isinstance(d, CallExpr):\n                d = d.callee\n            if not isinstance(d, (NameExpr, MemberExpr)):\n                continue\n            qualname = get_qualified_name(d)\n            fullname = self.get_fullname(d)\n            if fullname in (\n                \"builtins.property\",\n                \"builtins.staticmethod\",\n                \"builtins.classmethod\",\n                \"functools.cached_property\",\n            ):\n                self.add_decorator(qualname, require_name=True)\n            elif fullname in (\n                \"asyncio.coroutine\",\n                \"asyncio.coroutines.coroutine\",\n                \"types.coroutine\",\n            ):\n                o.func.is_awaitable_coroutine = True\n                self.add_decorator(qualname, require_name=True)\n            elif fullname == \"abc.abstractmethod\":\n                self.add_decorator(qualname, require_name=True)\n                o.func.abstract_status = IS_ABSTRACT\n            elif fullname in (\n                \"abc.abstractproperty\",\n                \"abc.abstractstaticmethod\",\n                \"abc.abstractclassmethod\",\n            ):\n                abc_module = qualname.rpartition(\".\")[0]\n                if not abc_module:\n                    self.import_tracker.add_import(\"abc\")\n                builtin_decorator_replacement = fullname[len(\"abc.abstract\") :]\n                self.add_decorator(builtin_decorator_replacement, require_name=False)\n                self.add_decorator(f\"{abc_module or 'abc'}.abstractmethod\", require_name=True)\n                o.func.abstract_status = IS_ABSTRACT\n            elif fullname in OVERLOAD_NAMES:\n                self.add_decorator(qualname, require_name=True)\n                o.func.is_overload = True\n            elif qualname.endswith((\".setter\", \".deleter\")):\n                self.add_decorator(qualname, require_name=False)\n            elif fullname in DATACLASS_TRANSFORM_NAMES:\n                p = AliasPrinter(self)\n                self._decorators.append(f\"@{decorator.accept(p)}\")\n            elif isinstance(decorator, (NameExpr, MemberExpr)):\n                p = AliasPrinter(self)\n                self._decorators.append(f\"@{decorator.accept(p)}\")\n\n    def get_fullname(self, expr: Expression) -> str:\n        \"\"\"Return the expression's full name.\"\"\"\n        if (\n            self.analyzed\n            and isinstance(expr, (NameExpr, MemberExpr))\n            and expr.fullname\n            and not (isinstance(expr.node, Var) and expr.node.is_suppressed_import)\n        ):\n            return expr.fullname\n        name = get_qualified_name(expr)\n        return self.resolve_name(name)\n\n    def visit_class_def(self, o: ClassDef) -> None:\n        self._class_stack.append(o)\n        self.method_names = find_method_names(o.defs.body)\n        sep: int | None = None\n        if self.is_top_level() and self._state != EMPTY:\n            sep = len(self._output)\n            self.add(\"\\n\")\n        decorators = self.get_class_decorators(o)\n        for d in decorators:\n            self.add(f\"{self._indent}@{d}\\n\")\n        self.record_name(o.name)\n        base_types = self.get_base_types(o)\n        if base_types:\n            for base in base_types:\n                self.import_tracker.require_name(base)\n        if self.analyzed and o.info.is_enum:\n            self.processing_enum = True\n        if isinstance(o.metaclass, (NameExpr, MemberExpr)):\n            meta = o.metaclass.accept(AliasPrinter(self))\n            base_types.append(\"metaclass=\" + meta)\n        elif self.analyzed and o.info.is_abstract and not o.info.is_protocol:\n            base_types.append(\"metaclass=abc.ABCMeta\")\n            self.import_tracker.add_import(\"abc\")\n            self.import_tracker.require_name(\"abc\")\n        bases = f\"({', '.join(base_types)})\" if base_types else \"\"\n        type_args = self.format_type_args(o)\n        self.add(f\"{self._indent}class {o.name}{type_args}{bases}:\\n\")\n        self.indent()\n        if self._include_docstrings and o.docstring:\n            docstring = mypy.util.quote_docstring(o.docstring)\n            self.add(f\"{self._indent}{docstring}\\n\")\n        n = len(self._output)\n        self._vars.append([])\n        if self.analyzed and (spec := find_dataclass_transform_spec(o)):\n            self.processing_dataclass = True\n            self.dataclass_field_specifier = spec.field_specifiers\n        super().visit_class_def(o)\n        self.dedent()\n        self._vars.pop()\n        self._vars[-1].append(o.name)\n        if len(self._output) == n:\n            if self._state == EMPTY_CLASS and sep is not None:\n                self._output[sep] = \"\"\n            if not (self._include_docstrings and o.docstring):\n                self._output[-1] = self._output[-1][:-1] + \" ...\\n\"\n            self._state = EMPTY_CLASS\n        else:\n            self._state = CLASS\n        self.method_names = set()\n        self.processing_dataclass = False\n        self.dataclass_field_specifier = ()\n        self._class_stack.pop(-1)\n        self.processing_enum = False\n\n    def get_base_types(self, cdef: ClassDef) -> list[str]:\n        \"\"\"Get list of base classes for a class.\"\"\"\n        base_types: list[str] = []\n        p = AliasPrinter(self)\n        for base in cdef.base_type_exprs + cdef.removed_base_type_exprs:\n            if isinstance(base, (NameExpr, MemberExpr)):\n                if self.get_fullname(base) != \"builtins.object\":\n                    base_types.append(get_qualified_name(base))\n            elif isinstance(base, IndexExpr):\n                base_types.append(base.accept(p))\n            elif isinstance(base, CallExpr):\n                # namedtuple(typename, fields), NamedTuple(typename, fields) calls can\n                # be used as a base class. The first argument is a string literal that\n                # is usually the same as the class name.\n                #\n                # Note:\n                # A call-based named tuple as a base class cannot be safely converted to\n                # a class-based NamedTuple definition because class attributes defined\n                # in the body of the class inheriting from the named tuple call are not\n                # namedtuple fields at runtime.\n                if self.is_namedtuple(base):\n                    nt_fields = self._get_namedtuple_fields(base)\n                    assert isinstance(base.args[0], StrExpr)\n                    typename = base.args[0].value\n                    if nt_fields is None:\n                        # Invalid namedtuple() call, cannot determine fields\n                        base_types.append(self.add_name(\"_typeshed.Incomplete\"))\n                        continue\n                    fields_str = \", \".join(f\"({f!r}, {t})\" for f, t in nt_fields)\n                    namedtuple_name = self.add_name(\"typing.NamedTuple\")\n                    base_types.append(f\"{namedtuple_name}({typename!r}, [{fields_str}])\")\n                elif self.is_typed_namedtuple(base):\n                    base_types.append(base.accept(p))\n                else:\n                    # At this point, we don't know what the base class is, so we\n                    # just use Incomplete as the base class.\n                    base_types.append(self.add_name(\"_typeshed.Incomplete\"))\n        for name, value in cdef.keywords.items():\n            if name == \"metaclass\":\n                continue  # handled separately\n            processed_value = value.accept(p) or \"...\"  # at least, don't crash\n            base_types.append(f\"{name}={processed_value}\")\n        return base_types\n\n    def get_class_decorators(self, cdef: ClassDef) -> list[str]:\n        decorators: list[str] = []\n        p = AliasPrinter(self)\n        for d in cdef.decorators:\n            if self.is_dataclass(d):\n                decorators.append(d.accept(p))\n                self.import_tracker.require_name(get_qualified_name(d))\n                self.processing_dataclass = True\n            if self.is_dataclass_transform(d):\n                decorators.append(d.accept(p))\n                self.import_tracker.require_name(get_qualified_name(d))\n        return decorators\n\n    def is_dataclass(self, expr: Expression) -> bool:\n        if isinstance(expr, CallExpr):\n            expr = expr.callee\n        return self.get_fullname(expr) == \"dataclasses.dataclass\"\n\n    def is_dataclass_transform(self, expr: Expression) -> bool:\n        if isinstance(expr, CallExpr):\n            expr = expr.callee\n        if self.get_fullname(expr) in DATACLASS_TRANSFORM_NAMES:\n            return True\n        if (spec := find_dataclass_transform_spec(expr)) is not None:\n            self.processing_dataclass = True\n            self.dataclass_field_specifier = spec.field_specifiers\n            return True\n        return False\n\n    def visit_block(self, o: Block) -> None:\n        # Unreachable statements may be partially uninitialized and that may\n        # cause trouble.\n        if not o.is_unreachable:\n            super().visit_block(o)\n\n    def visit_assignment_stmt(self, o: AssignmentStmt) -> None:\n        foundl = []\n\n        for lvalue in o.lvalues:\n            if isinstance(lvalue, NameExpr) and isinstance(o.rvalue, CallExpr):\n                if self.is_namedtuple(o.rvalue) or self.is_typed_namedtuple(o.rvalue):\n                    self.process_namedtuple(lvalue, o.rvalue)\n                    foundl.append(False)  # state is updated in process_namedtuple\n                    continue\n                if self.is_typeddict(o.rvalue):\n                    self.process_typeddict(lvalue, o.rvalue)\n                    foundl.append(False)  # state is updated in process_typeddict\n                    continue\n            if (\n                isinstance(lvalue, NameExpr)\n                and self.is_alias_expression(o.rvalue)\n                and not self.is_private_name(lvalue.name)\n            ):\n                is_explicit_type_alias = (\n                    o.unanalyzed_type and getattr(o.type, \"name\", None) == \"TypeAlias\"\n                )\n                if is_explicit_type_alias:\n                    self.process_typealias(lvalue, o.rvalue, is_explicit_type_alias=True)\n                    continue\n\n                if not o.unanalyzed_type:\n                    self.process_typealias(lvalue, o.rvalue)\n                    continue\n\n            if isinstance(lvalue, (TupleExpr, ListExpr)):\n                items = lvalue.items\n                if isinstance(o.unanalyzed_type, TupleType):  # type: ignore[misc]\n                    annotations: Iterable[Type | None] = o.unanalyzed_type.items\n                else:\n                    annotations = [None] * len(items)\n            else:\n                items = [lvalue]\n                annotations = [o.unanalyzed_type]\n            sep = False\n            found = False\n            for item, annotation in zip(items, annotations):\n                if isinstance(item, NameExpr):\n                    init = self.get_init(item.name, o.rvalue, annotation)\n                    if init:\n                        found = True\n                        if not sep and self.is_top_level() and self._state not in (EMPTY, VAR):\n                            init = \"\\n\" + init\n                            sep = True\n                        self.add(init)\n                        self.record_name(item.name)\n            foundl.append(found)\n\n        if all(foundl):\n            self._state = VAR\n\n    def is_namedtuple(self, expr: CallExpr) -> bool:\n        return self.get_fullname(expr.callee) == \"collections.namedtuple\"\n\n    def is_typed_namedtuple(self, expr: CallExpr) -> bool:\n        return self.get_fullname(expr.callee) in TYPED_NAMEDTUPLE_NAMES\n\n    def _get_namedtuple_fields(self, call: CallExpr) -> list[tuple[str, str]] | None:\n        if self.is_namedtuple(call):\n            fields_arg = call.args[1]\n            if isinstance(fields_arg, StrExpr):\n                field_names = fields_arg.value.replace(\",\", \" \").split()\n            elif isinstance(fields_arg, (ListExpr, TupleExpr)):\n                field_names = []\n                for field in fields_arg.items:\n                    if not isinstance(field, StrExpr):\n                        return None\n                    field_names.append(field.value)\n            else:\n                return None  # Invalid namedtuple fields type\n            if field_names:\n                incomplete = self.add_name(\"_typeshed.Incomplete\")\n                return [(field_name, incomplete) for field_name in field_names]\n            else:\n                return []\n\n        elif self.is_typed_namedtuple(call):\n            fields_arg = call.args[1]\n            if not isinstance(fields_arg, (ListExpr, TupleExpr)):\n                return None\n            fields: list[tuple[str, str]] = []\n            p = AliasPrinter(self)\n            for field in fields_arg.items:\n                if not (isinstance(field, TupleExpr) and len(field.items) == 2):\n                    return None\n                field_name, field_type = field.items\n                if not isinstance(field_name, StrExpr):\n                    return None\n                fields.append((field_name.value, field_type.accept(p)))\n            return fields\n        else:\n            return None  # Not a named tuple call\n\n    def process_namedtuple(self, lvalue: NameExpr, rvalue: CallExpr) -> None:\n        if self._state == CLASS:\n            self.add(\"\\n\")\n\n        if not isinstance(rvalue.args[0], StrExpr):\n            self.annotate_as_incomplete(lvalue)\n            return\n\n        fields = self._get_namedtuple_fields(rvalue)\n        if fields is None:\n            self.annotate_as_incomplete(lvalue)\n            return\n        bases = self.add_name(\"typing.NamedTuple\")\n        # TODO: Add support for generic NamedTuples. Requires `Generic` as base class.\n        class_def = f\"{self._indent}class {lvalue.name}({bases}):\"\n        if len(fields) == 0:\n            self.add(f\"{class_def} ...\\n\")\n            self._state = EMPTY_CLASS\n        else:\n            if self._state not in (EMPTY, CLASS):\n                self.add(\"\\n\")\n            self.add(f\"{class_def}\\n\")\n            for f_name, f_type in fields:\n                self.add(f\"{self._indent}    {f_name}: {f_type}\\n\")\n            self._state = CLASS\n\n    def is_typeddict(self, expr: CallExpr) -> bool:\n        return self.get_fullname(expr.callee) in TPDICT_NAMES\n\n    def process_typeddict(self, lvalue: NameExpr, rvalue: CallExpr) -> None:\n        if self._state == CLASS:\n            self.add(\"\\n\")\n\n        if not isinstance(rvalue.args[0], StrExpr):\n            self.annotate_as_incomplete(lvalue)\n            return\n\n        items: list[tuple[str, Expression]] = []\n        total: Expression | None = None\n        if len(rvalue.args) > 1 and rvalue.arg_kinds[1] == ARG_POS:\n            if not isinstance(rvalue.args[1], DictExpr):\n                self.annotate_as_incomplete(lvalue)\n                return\n            for attr_name, attr_type in rvalue.args[1].items:\n                if not isinstance(attr_name, StrExpr):\n                    self.annotate_as_incomplete(lvalue)\n                    return\n                items.append((attr_name.value, attr_type))\n            if len(rvalue.args) > 2:\n                if rvalue.arg_kinds[2] != ARG_NAMED or rvalue.arg_names[2] != \"total\":\n                    self.annotate_as_incomplete(lvalue)\n                    return\n                total = rvalue.args[2]\n        else:\n            for arg_name, arg in zip(rvalue.arg_names[1:], rvalue.args[1:]):\n                if not isinstance(arg_name, str):\n                    self.annotate_as_incomplete(lvalue)\n                    return\n                if arg_name == \"total\":\n                    total = arg\n                else:\n                    items.append((arg_name, arg))\n        p = AliasPrinter(self)\n        if any(not key.isidentifier() or keyword.iskeyword(key) for key, _ in items):\n            # Keep the call syntax if there are non-identifier or reserved keyword keys.\n            self.add(f\"{self._indent}{lvalue.name} = {rvalue.accept(p)}\\n\")\n            self._state = VAR\n        else:\n            bases = self.add_name(\"typing_extensions.TypedDict\")\n            # TODO: Add support for generic TypedDicts. Requires `Generic` as base class.\n            if total is not None:\n                bases += f\", total={total.accept(p)}\"\n            class_def = f\"{self._indent}class {lvalue.name}({bases}):\"\n            if len(items) == 0:\n                self.add(f\"{class_def} ...\\n\")\n                self._state = EMPTY_CLASS\n            else:\n                if self._state not in (EMPTY, CLASS):\n                    self.add(\"\\n\")\n                self.add(f\"{class_def}\\n\")\n                for key, key_type in items:\n                    self.add(f\"{self._indent}    {key}: {key_type.accept(p)}\\n\")\n                self._state = CLASS\n\n    def annotate_as_incomplete(self, lvalue: NameExpr) -> None:\n        incomplete = self.add_name(\"_typeshed.Incomplete\")\n        self.add(f\"{self._indent}{lvalue.name}: {incomplete}\\n\")\n        self._state = VAR\n\n    def is_alias_expression(self, expr: Expression, top_level: bool = True) -> bool:\n        \"\"\"Return True for things that look like target for an alias.\n\n        Used to know if assignments look like type aliases, function alias,\n        or module alias.\n        \"\"\"\n        # Assignment of TypeVar(...)  and other typevar-likes are passed through\n        if isinstance(expr, CallExpr) and self.get_fullname(expr.callee) in TYPE_VAR_LIKE_NAMES:\n            return True\n        elif isinstance(expr, EllipsisExpr):\n            return not top_level\n        elif isinstance(expr, NameExpr):\n            if expr.name in (\"True\", \"False\"):\n                return False\n            elif expr.name == \"None\":\n                return not top_level\n            else:\n                return not self.is_private_name(expr.name)\n        elif isinstance(expr, MemberExpr) and self.analyzed:\n            # Also add function and module aliases.\n            return (\n                top_level\n                and isinstance(expr.node, (FuncDef, Decorator, MypyFile))\n                or isinstance(expr.node, TypeInfo)\n            ) and not self.is_private_member(expr.node.fullname)\n        elif isinstance(expr, IndexExpr) and (\n            (isinstance(expr.base, NameExpr) and not self.is_private_name(expr.base.name))\n            or (  # Also some known aliases that could be member expression\n                isinstance(expr.base, MemberExpr)\n                and not self.is_private_member(get_qualified_name(expr.base))\n                and self.get_fullname(expr.base).startswith(\n                    (\"builtins.\", \"typing.\", \"typing_extensions.\", \"collections.abc.\")\n                )\n            )\n        ):\n            if isinstance(expr.index, TupleExpr):\n                indices = expr.index.items\n            else:\n                indices = [expr.index]\n            if expr.base.name == \"Callable\" and len(indices) == 2:\n                args, ret = indices\n                if isinstance(args, EllipsisExpr):\n                    indices = [ret]\n                elif isinstance(args, ListExpr):\n                    indices = args.items + [ret]\n                else:\n                    return False\n            return all(self.is_alias_expression(i, top_level=False) for i in indices)\n        elif isinstance(expr, OpExpr) and expr.op == \"|\":\n            return self.is_alias_expression(\n                expr.left, top_level=False\n            ) and self.is_alias_expression(expr.right, top_level=False)\n        else:\n            return False\n\n    def process_typealias(\n        self, lvalue: NameExpr, rvalue: Expression, is_explicit_type_alias: bool = False\n    ) -> None:\n        p = AliasPrinter(self)\n        if is_explicit_type_alias:\n            self.import_tracker.require_name(\"TypeAlias\")\n            self.add(f\"{self._indent}{lvalue.name}: TypeAlias = {rvalue.accept(p)}\\n\")\n        else:\n            self.add(f\"{self._indent}{lvalue.name} = {rvalue.accept(p)}\\n\")\n        self.record_name(lvalue.name)\n        self._vars[-1].append(lvalue.name)\n\n    def visit_type_alias_stmt(self, o: TypeAliasStmt) -> None:\n        \"\"\"Type aliases defined with the `type` keyword (PEP 695).\"\"\"\n        p = AliasPrinter(self)\n        name = o.name.name\n        rvalue = o.value.expr()\n        type_args = self.format_type_args(o)\n        self.add(f\"{self._indent}type {name}{type_args} = {rvalue.accept(p)}\\n\")\n        self.record_name(name)\n        self._vars[-1].append(name)\n\n    def visit_if_stmt(self, o: IfStmt) -> None:\n        # Ignore if __name__ == '__main__'.\n        expr = o.expr[0]\n        if (\n            isinstance(expr, ComparisonExpr)\n            and isinstance(expr.operands[0], NameExpr)\n            and isinstance(expr.operands[1], StrExpr)\n            and expr.operands[0].name == \"__name__\"\n            and \"__main__\" in expr.operands[1].value\n        ):\n            return\n        super().visit_if_stmt(o)\n\n    def visit_import_all(self, o: ImportAll) -> None:\n        self.add_import_line(f\"from {'.' * o.relative}{o.id} import *\\n\")\n\n    def visit_import_from(self, o: ImportFrom) -> None:\n        exported_names: set[str] = set()\n        import_names = []\n        module, relative = translate_module_name(o.id, o.relative)\n        if self.module_name:\n            full_module, ok = mypy.util.correct_relative_import(\n                self.module_name, relative, module, self.path.endswith(\".__init__.py\")\n            )\n            if not ok:\n                full_module = module\n        else:\n            full_module = module\n        if module == \"__future__\":\n            return  # Not preserved\n        for name, as_name in o.names:\n            if name == \"six\":\n                # Vendored six -- translate into plain 'import six'.\n                self.visit_import(Import([(\"six\", None)]))\n                continue\n            if self.should_reexport(name, full_module, as_name is not None):\n                self.import_tracker.reexport(name)\n                as_name = name\n            import_names.append((name, as_name))\n        self.import_tracker.add_import_from(\".\" * relative + module, import_names)\n        self._vars[-1].extend(alias or name for name, alias in import_names)\n        for name, alias in import_names:\n            self.record_name(alias or name)\n\n        if self._all_:\n            # Include \"import from\"s that import names defined in __all__.\n            names = [\n                name\n                for name, alias in o.names\n                if name in self._all_ and alias is None and name not in self.IGNORED_DUNDERS\n            ]\n            exported_names.update(names)\n\n    def visit_import(self, o: Import) -> None:\n        for id, as_id in o.ids:\n            self.import_tracker.add_import(id, as_id)\n            if as_id is None:\n                target_name = id.split(\".\")[0]\n            else:\n                target_name = as_id\n            self._vars[-1].append(target_name)\n            self.record_name(target_name)\n\n    def get_init(\n        self, lvalue: str, rvalue: Expression, annotation: Type | None = None\n    ) -> str | None:\n        \"\"\"Return initializer for a variable.\n\n        Return None if we've generated one already or if the variable is internal.\n        \"\"\"\n        if lvalue in self._vars[-1]:\n            # We've generated an initializer already for this variable.\n            return None\n        # TODO: Only do this at module top level.\n        if self.is_private_name(lvalue) or self.is_not_in_all(lvalue):\n            return None\n        self._vars[-1].append(lvalue)\n        if annotation is not None:\n            typename = self.print_annotation(annotation)\n            if (\n                isinstance(annotation, UnboundType)\n                and not annotation.args\n                and annotation.name == \"Final\"\n                and self.import_tracker.module_for.get(\"Final\") in self.TYPING_MODULE_NAMES\n            ):\n                # Final without type argument is invalid in stubs.\n                final_arg = self.get_str_type_of_node(rvalue)\n                typename += f\"[{final_arg}]\"\n        elif self.processing_enum:\n            initializer, _ = self.get_str_default_of_node(rvalue)\n            return f\"{self._indent}{lvalue} = {initializer}\\n\"\n        elif self.processing_dataclass:\n            # attribute without annotation is not a dataclass field, don't add annotation.\n            return f\"{self._indent}{lvalue} = ...\\n\"\n        else:\n            typename = self.get_str_type_of_node(rvalue)\n        initializer = self.get_assign_initializer(rvalue)\n        return f\"{self._indent}{lvalue}: {typename}{initializer}\\n\"\n\n    def get_assign_initializer(self, rvalue: Expression) -> str:\n        \"\"\"Does this rvalue need some special initializer value?\"\"\"\n        if not self._current_class:\n            return \"\"\n        # Current rules\n        # 1. Return `...` if we are dealing with `NamedTuple` or `dataclass` field and\n        #    it has an existing default value\n        if (\n            self._current_class.info\n            and self._current_class.info.is_named_tuple\n            and not isinstance(rvalue, TempNode)\n        ):\n            return \" = ...\"\n        if self.processing_dataclass:\n            if isinstance(rvalue, CallExpr):\n                fullname = self.get_fullname(rvalue.callee)\n                if fullname in (self.dataclass_field_specifier or DATACLASS_FIELD_SPECIFIERS):\n                    p = AliasPrinter(self)\n                    return f\" = {rvalue.accept(p)}\"\n            if not (isinstance(rvalue, TempNode) and rvalue.no_rhs):\n                return \" = ...\"\n        # TODO: support other possible cases, where initializer is important\n\n        # By default, no initializer is required:\n        return \"\"\n\n    def add_decorator(self, name: str, require_name: bool = False) -> None:\n        if require_name:\n            self.import_tracker.require_name(name)\n        self._decorators.append(f\"@{name}\")\n\n    def clear_decorators(self) -> None:\n        self._decorators.clear()\n\n    def is_private_member(self, fullname: str) -> bool:\n        parts = fullname.split(\".\")\n        return any(self.is_private_name(part) for part in parts)\n\n    def get_str_type_of_node(self, rvalue: Expression, *, can_be_incomplete: bool = True) -> str:\n        rvalue = self.maybe_unwrap_unary_expr(rvalue)\n\n        if isinstance(rvalue, IntExpr):\n            return \"int\"\n        if isinstance(rvalue, StrExpr):\n            return \"str\"\n        if isinstance(rvalue, BytesExpr):\n            return \"bytes\"\n        if isinstance(rvalue, FloatExpr):\n            return \"float\"\n        if isinstance(rvalue, ComplexExpr):  # 1j\n            return \"complex\"\n        if isinstance(rvalue, OpExpr) and rvalue.op in (\"-\", \"+\"):  # -1j + 1\n            if isinstance(self.maybe_unwrap_unary_expr(rvalue.left), ComplexExpr) or isinstance(\n                self.maybe_unwrap_unary_expr(rvalue.right), ComplexExpr\n            ):\n                return \"complex\"\n        if isinstance(rvalue, NameExpr) and rvalue.name in (\"True\", \"False\"):\n            return \"bool\"\n        if can_be_incomplete:\n            return self.add_name(\"_typeshed.Incomplete\")\n        else:\n            return \"\"\n\n    def maybe_unwrap_unary_expr(self, expr: Expression) -> Expression:\n        \"\"\"Unwrap (possibly nested) unary expressions.\n\n        But, some unary expressions can change the type of expression.\n        While we want to preserve it. For example, `~True` is `int`.\n        So, we only allow a subset of unary expressions to be unwrapped.\n        \"\"\"\n        if not isinstance(expr, UnaryExpr):\n            return expr\n\n        # First, try to unwrap `[+-]+ (int|float|complex)` expr:\n        math_ops = (\"+\", \"-\")\n        if expr.op in math_ops:\n            while isinstance(expr, UnaryExpr):\n                if expr.op not in math_ops or not isinstance(\n                    expr.expr, (IntExpr, FloatExpr, ComplexExpr, UnaryExpr)\n                ):\n                    break\n                expr = expr.expr\n            return expr\n\n        # Next, try `not bool` expr:\n        if expr.op == \"not\":\n            while isinstance(expr, UnaryExpr):\n                if expr.op != \"not\" or not isinstance(expr.expr, (NameExpr, UnaryExpr)):\n                    break\n                if isinstance(expr.expr, NameExpr) and expr.expr.name not in (\"True\", \"False\"):\n                    break\n                expr = expr.expr\n            return expr\n\n        # This is some other unary expr, we cannot do anything with it (yet?).\n        return expr\n\n    def get_str_default_of_node(self, rvalue: Expression) -> tuple[str, bool]:\n        \"\"\"Get a string representation of the default value of a node.\n\n        Returns a 2-tuple of the default and whether or not it is valid.\n        \"\"\"\n        if isinstance(rvalue, NameExpr):\n            if rvalue.name in (\"None\", \"True\", \"False\"):\n                return rvalue.name, True\n        elif isinstance(rvalue, (IntExpr, FloatExpr)):\n            return f\"{rvalue.value}\", True\n        elif isinstance(rvalue, UnaryExpr):\n            if isinstance(rvalue.expr, (IntExpr, FloatExpr)):\n                return f\"{rvalue.op}{rvalue.expr.value}\", True\n        elif isinstance(rvalue, StrExpr):\n            return repr(rvalue.value), True\n        elif isinstance(rvalue, BytesExpr):\n            return \"b\" + repr(rvalue.value).replace(\"\\\\\\\\\", \"\\\\\"), True\n        elif isinstance(rvalue, TupleExpr):\n            items_defaults = []\n            for e in rvalue.items:\n                e_default, valid = self.get_str_default_of_node(e)\n                if not valid:\n                    break\n                items_defaults.append(e_default)\n            else:\n                closing = \",)\" if len(items_defaults) == 1 else \")\"\n                default = \"(\" + \", \".join(items_defaults) + closing\n                return default, True\n        elif isinstance(rvalue, ListExpr):\n            items_defaults = []\n            for e in rvalue.items:\n                e_default, valid = self.get_str_default_of_node(e)\n                if not valid:\n                    break\n                items_defaults.append(e_default)\n            else:\n                default = \"[\" + \", \".join(items_defaults) + \"]\"\n                return default, True\n        elif isinstance(rvalue, SetExpr):\n            items_defaults = []\n            for e in rvalue.items:\n                e_default, valid = self.get_str_default_of_node(e)\n                if not valid:\n                    break\n                items_defaults.append(e_default)\n            else:\n                if items_defaults:\n                    default = \"{\" + \", \".join(items_defaults) + \"}\"\n                    return default, True\n        elif isinstance(rvalue, DictExpr):\n            items_defaults = []\n            for k, v in rvalue.items:\n                if k is None:\n                    break\n                k_default, k_valid = self.get_str_default_of_node(k)\n                v_default, v_valid = self.get_str_default_of_node(v)\n                if not (k_valid and v_valid):\n                    break\n                items_defaults.append(f\"{k_default}: {v_default}\")\n            else:\n                default = \"{\" + \", \".join(items_defaults) + \"}\"\n                return default, True\n        return \"...\", False\n\n    def should_reexport(self, name: str, full_module: str, name_is_alias: bool) -> bool:\n        is_private = self.is_private_name(name, full_module + \".\" + name)\n        if (\n            not name_is_alias\n            and name not in self.referenced_names\n            and (not self._all_ or name in self.IGNORED_DUNDERS)\n            and not is_private\n            and full_module not in (\"abc\", \"asyncio\") + self.TYPING_MODULE_NAMES\n        ):\n            # An imported name that is never referenced in the module is assumed to be\n            # exported, unless there is an explicit __all__. Note that we need to special\n            # case 'abc' since some references are deleted during semantic analysis.\n            return True\n        return super().should_reexport(name, full_module, name_is_alias)\n\n\ndef find_method_names(defs: list[Statement]) -> set[str]:\n    # TODO: Traverse into nested definitions\n    result = set()\n    for defn in defs:\n        if isinstance(defn, FuncDef):\n            result.add(defn.name)\n        elif isinstance(defn, Decorator):\n            result.add(defn.func.name)\n        elif isinstance(defn, OverloadedFuncDef):\n            for item in defn.items:\n                result.update(find_method_names([item]))\n    return result\n\n\nclass SelfTraverser(mypy.traverser.TraverserVisitor):\n    def __init__(self) -> None:\n        self.results: list[tuple[str, Expression, Type | None]] = []\n\n    def visit_assignment_stmt(self, o: AssignmentStmt) -> None:\n        lvalue = o.lvalues[0]\n        if (\n            isinstance(lvalue, MemberExpr)\n            and isinstance(lvalue.expr, NameExpr)\n            and lvalue.expr.name == \"self\"\n        ):\n            self.results.append((lvalue.name, o.rvalue, o.unanalyzed_type))\n\n\ndef find_self_initializers(fdef: FuncBase) -> list[tuple[str, Expression, Type | None]]:\n    \"\"\"Find attribute initializers in a method.\n\n    Return a list of pairs (attribute name, r.h.s. expression).\n    \"\"\"\n    traverser = SelfTraverser()\n    fdef.accept(traverser)\n    return traverser.results\n\n\ndef get_qualified_name(o: Expression) -> str:\n    if isinstance(o, NameExpr):\n        return o.name\n    elif isinstance(o, MemberExpr):\n        return f\"{get_qualified_name(o.expr)}.{o.name}\"\n    else:\n        return ERROR_MARKER\n\n\ndef remove_blacklisted_modules(modules: list[StubSource]) -> list[StubSource]:\n    return [\n        module for module in modules if module.path is None or not is_blacklisted_path(module.path)\n    ]\n\n\ndef split_pyc_from_py(modules: list[StubSource]) -> tuple[list[StubSource], list[StubSource]]:\n    py_modules = []\n    pyc_modules = []\n    for mod in modules:\n        if is_pyc_only(mod.path):\n            pyc_modules.append(mod)\n        else:\n            py_modules.append(mod)\n    return pyc_modules, py_modules\n\n\ndef is_blacklisted_path(path: str) -> bool:\n    return any(substr in (normalize_path_separators(path) + \"\\n\") for substr in BLACKLIST)\n\n\ndef normalize_path_separators(path: str) -> str:\n    return path.replace(\"\\\\\", \"/\") if sys.platform == \"win32\" else path\n\n\ndef collect_build_targets(\n    options: Options, mypy_opts: MypyOptions\n) -> tuple[list[StubSource], list[StubSource], list[StubSource]]:\n    \"\"\"Collect files for which we need to generate stubs.\n\n    Return list of py modules, pyc modules, and C modules.\n    \"\"\"\n    if options.packages or options.modules:\n        if options.no_import:\n            py_modules = find_module_paths_using_search(\n                options.modules, options.packages, options.search_path, options.pyversion\n            )\n            c_modules: list[StubSource] = []\n        else:\n            # Using imports is the default, since we can also find C modules.\n            py_modules, c_modules = find_module_paths_using_imports(\n                options.modules, options.packages, options.verbose, options.quiet\n            )\n    else:\n        # Use mypy native source collection for files and directories.\n        try:\n            source_list = create_source_list(options.files, mypy_opts)\n        except InvalidSourceList as e:\n            raise SystemExit(str(e)) from e\n        py_modules = [StubSource(m.module, m.path) for m in source_list]\n        c_modules = []\n\n    py_modules = remove_blacklisted_modules(py_modules)\n    pyc_mod, py_mod = split_pyc_from_py(py_modules)\n    return py_mod, pyc_mod, c_modules\n\n\ndef find_module_paths_using_imports(\n    modules: list[str], packages: list[str], verbose: bool, quiet: bool\n) -> tuple[list[StubSource], list[StubSource]]:\n    \"\"\"Find path and runtime value of __all__ (if possible) for modules and packages.\n\n    This function uses runtime Python imports to get the information.\n    \"\"\"\n    with ModuleInspect() as inspect:\n        py_modules: list[StubSource] = []\n        c_modules: list[StubSource] = []\n        found = list(walk_packages(inspect, packages, verbose))\n        modules = modules + found\n        modules = [\n            mod for mod in modules if not is_non_library_module(mod)\n        ]  # We don't want to run any tests or scripts\n        for mod in modules:\n            try:\n                result = find_module_path_and_all_py3(inspect, mod, verbose)\n            except CantImport as e:\n                tb = traceback.format_exc()\n                if verbose:\n                    sys.stderr.write(tb)\n                if not quiet:\n                    report_missing(mod, e.message, tb)\n                continue\n            if not result:\n                c_modules.append(StubSource(mod))\n            else:\n                path, runtime_all = result\n                py_modules.append(StubSource(mod, path, runtime_all))\n        return py_modules, c_modules\n\n\ndef is_non_library_module(module: str) -> bool:\n    \"\"\"Does module look like a test module or a script?\"\"\"\n    if module.endswith(\n        (\n            \".tests\",\n            \".test\",\n            \".testing\",\n            \"_tests\",\n            \"_test_suite\",\n            \"test_util\",\n            \"test_utils\",\n            \"test_base\",\n            \".__main__\",\n            \".conftest\",  # Used by pytest\n            \".setup\",  # Typically an install script\n        )\n    ):\n        return True\n    if module.split(\".\")[-1].startswith(\"test_\"):\n        return True\n    if (\n        \".tests.\" in module\n        or \".test.\" in module\n        or \".testing.\" in module\n        or \".SelfTest.\" in module\n    ):\n        return True\n    return False\n\n\ndef translate_module_name(module: str, relative: int) -> tuple[str, int]:\n    for pkg in VENDOR_PACKAGES:\n        for alt in \"six.moves\", \"six\":\n            substr = f\"{pkg}.{alt}\"\n            if module.endswith(\".\" + substr) or (module == substr and relative):\n                return alt, 0\n            if \".\" + substr + \".\" in module:\n                return alt + \".\" + module.partition(\".\" + substr + \".\")[2], 0\n    return module, relative\n\n\ndef find_module_paths_using_search(\n    modules: list[str], packages: list[str], search_path: list[str], pyversion: tuple[int, int]\n) -> list[StubSource]:\n    \"\"\"Find sources for modules and packages requested.\n\n    This function just looks for source files at the file system level.\n    This is used if user passes --no-import, and will not find C modules.\n    Exit if some of the modules or packages can't be found.\n    \"\"\"\n    result: list[StubSource] = []\n    typeshed_path = default_lib_path(mypy.build.default_data_dir(), pyversion, None)\n    search_paths = SearchPaths((\".\",) + tuple(search_path), (), (), tuple(typeshed_path))\n    cache = FindModuleCache(search_paths, fscache=None, options=None)\n    for module in modules:\n        m_result = cache.find_module(module)\n        if isinstance(m_result, ModuleNotFoundReason):\n            fail_missing(module, m_result)\n            module_path = None\n        else:\n            module_path = m_result\n        result.append(StubSource(module, module_path))\n    for package in packages:\n        p_result = cache.find_modules_recursive(package)\n        if p_result:\n            fail_missing(package, ModuleNotFoundReason.NOT_FOUND)\n        sources = [StubSource(m.module, m.path) for m in p_result]\n        result.extend(sources)\n\n    result = [m for m in result if not is_non_library_module(m.module)]\n\n    return result\n\n\ndef mypy_options(stubgen_options: Options) -> MypyOptions:\n    \"\"\"Generate mypy options using the flag passed by user.\"\"\"\n    options = MypyOptions()\n    options.follow_imports = \"skip\"\n    options.incremental = False\n    options.ignore_errors = True\n    options.semantic_analysis_only = True\n    options.python_version = stubgen_options.pyversion\n    options.show_traceback = True\n    options.transform_source = remove_misplaced_type_comments\n    options.preserve_asts = True\n    options.include_docstrings = stubgen_options.include_docstrings\n\n    # Override cache_dir if provided in the environment\n    environ_cache_dir = os.getenv(\"MYPY_CACHE_DIR\", \"\")\n    if environ_cache_dir.strip():\n        options.cache_dir = environ_cache_dir\n    options.cache_dir = os.path.expanduser(options.cache_dir)\n\n    return options\n\n\ndef parse_source_file(mod: StubSource, mypy_options: MypyOptions) -> None:\n    \"\"\"Parse a source file.\n\n    On success, store AST in the corresponding attribute of the stub source.\n    If there are syntax errors, print them and exit.\n    \"\"\"\n    assert mod.path is not None, \"Not found module was not skipped\"\n    with open(mod.path, \"rb\") as f:\n        data = f.read()\n    source = mypy.util.decode_python_encoding(data)\n    errors = Errors(mypy_options)\n    mod.ast = mypy.parse.parse(\n        source, fnam=mod.path, module=mod.module, errors=errors, options=mypy_options\n    )\n    mod.ast._fullname = mod.module\n    if errors.is_blockers():\n        # Syntax error!\n        for m in errors.new_messages():\n            sys.stderr.write(f\"{m}\\n\")\n        sys.exit(1)\n\n\ndef generate_asts_for_modules(\n    py_modules: list[StubSource], parse_only: bool, mypy_options: MypyOptions, verbose: bool\n) -> None:\n    \"\"\"Use mypy to parse (and optionally analyze) source files.\"\"\"\n    if not py_modules:\n        return  # Nothing to do here, but there may be C modules\n    if verbose:\n        print(f\"Processing {len(py_modules)} files...\")\n    if parse_only:\n        for mod in py_modules:\n            parse_source_file(mod, mypy_options)\n        return\n    # Perform full semantic analysis of the source set.\n    try:\n        res = build([module.source for module in py_modules], mypy_options)\n    except CompileError as e:\n        raise SystemExit(f\"Critical error during semantic analysis: {e}\") from e\n\n    for mod in py_modules:\n        mod.ast = res.graph[mod.module].tree\n        # Use statically inferred __all__ if there is no runtime one.\n        if mod.runtime_all is None:\n            mod_names = res.manager.semantic_analyzer.modules[mod.module].names\n            if \"__all__\" in mod_names:\n                mod.runtime_all = [name for name, sym in mod_names.items() if sym.module_public]\n\n\ndef generate_stub_for_py_module(\n    mod: StubSource,\n    target: str,\n    *,\n    parse_only: bool = False,\n    inspect: bool = False,\n    include_private: bool = False,\n    export_less: bool = False,\n    include_docstrings: bool = False,\n    doc_dir: str = \"\",\n    all_modules: list[str],\n) -> None:\n    \"\"\"Use analysed (or just parsed) AST to generate type stub for single file.\n\n    If directory for target doesn't exist it will created. Existing stub\n    will be overwritten.\n    \"\"\"\n    if inspect:\n        ngen = InspectionStubGenerator(\n            module_name=mod.module,\n            known_modules=all_modules,\n            _all_=mod.runtime_all,\n            doc_dir=doc_dir,\n            include_private=include_private,\n            export_less=export_less,\n            include_docstrings=include_docstrings,\n        )\n        ngen.generate_module()\n        output = ngen.output()\n\n    else:\n        gen = ASTStubGenerator(\n            mod.runtime_all,\n            include_private=include_private,\n            analyzed=not parse_only,\n            export_less=export_less,\n            include_docstrings=include_docstrings,\n        )\n        assert mod.ast is not None, \"This function must be used only with analyzed modules\"\n        mod.ast.accept(gen)\n        output = gen.output()\n\n    # Write output to file.\n    subdir = os.path.dirname(target)\n    if subdir and not os.path.isdir(subdir):\n        os.makedirs(subdir)\n    with open(target, \"w\", encoding=\"utf-8\") as file:\n        file.write(output)\n\n\ndef generate_stubs(options: Options) -> None:\n    \"\"\"Main entry point for the program.\"\"\"\n    mypy_opts = mypy_options(options)\n    py_modules, pyc_modules, c_modules = collect_build_targets(options, mypy_opts)\n    all_modules = py_modules + pyc_modules + c_modules\n    all_module_names = sorted(m.module for m in all_modules)\n    # Use parsed sources to generate stubs for Python modules.\n    generate_asts_for_modules(py_modules, options.parse_only, mypy_opts, options.verbose)\n    files = []\n    for mod in py_modules + pyc_modules:\n        assert mod.path is not None, \"Not found module was not skipped\"\n        target = mod.module.replace(\".\", \"/\")\n        if os.path.basename(mod.path) in [\"__init__.py\", \"__init__.pyc\"]:\n            target += \"/__init__.pyi\"\n        else:\n            target += \".pyi\"\n        target = os.path.join(options.output_dir, target)\n        files.append(target)\n        with generate_guarded(mod.module, target, options.ignore_errors, options.verbose):\n            generate_stub_for_py_module(\n                mod,\n                target,\n                parse_only=options.parse_only,\n                inspect=options.inspect or mod in pyc_modules,\n                include_private=options.include_private,\n                export_less=options.export_less,\n                include_docstrings=options.include_docstrings,\n                doc_dir=options.doc_dir,\n                all_modules=all_module_names,\n            )\n\n    # Separately analyse C modules using different logic.\n    for mod in c_modules:\n        if any(py_mod.module.startswith(mod.module + \".\") for py_mod in all_modules):\n            target = mod.module.replace(\".\", \"/\") + \"/__init__.pyi\"\n        else:\n            target = mod.module.replace(\".\", \"/\") + \".pyi\"\n        target = os.path.join(options.output_dir, target)\n        files.append(target)\n        with generate_guarded(mod.module, target, options.ignore_errors, options.verbose):\n            generate_stub_for_c_module(\n                mod.module,\n                target,\n                known_modules=all_module_names,\n                doc_dir=options.doc_dir,\n                include_private=options.include_private,\n                export_less=options.export_less,\n                include_docstrings=options.include_docstrings,\n            )\n    num_modules = len(all_modules)\n    if not options.quiet and num_modules > 0:\n        print(\"Processed %d modules\" % num_modules)\n        if len(files) == 1:\n            print(f\"Generated {files[0]}\")\n        else:\n            print(f\"Generated files under {common_dir_prefix(files)}\" + os.sep)\n\n\nHEADER = \"\"\"%(prog)s [-h] [more options, see -h]\n                     [-m MODULE] [-p PACKAGE] [files ...]\"\"\"\n\nDESCRIPTION = \"\"\"\nGenerate draft stubs for modules.\n\nStubs are generated in directory ./out, to avoid overriding files with\nmanual changes.  This directory is assumed to exist.\n\"\"\"\n\n\ndef parse_options(args: list[str]) -> Options:\n    parser = argparse.ArgumentParser(\n        prog=\"stubgen\", usage=HEADER, description=DESCRIPTION, fromfile_prefix_chars=\"@\"\n    )\n\n    parser.add_argument(\n        \"--ignore-errors\",\n        action=\"store_true\",\n        help=\"ignore errors when trying to generate stubs for modules\",\n    )\n    parser.add_argument(\n        \"--no-import\",\n        action=\"store_true\",\n        help=\"don't import the modules, just parse and analyze them \"\n        \"(doesn't work with C extension modules and might not \"\n        \"respect __all__)\",\n    )\n    parser.add_argument(\n        \"--no-analysis\",\n        \"--parse-only\",\n        dest=\"parse_only\",\n        action=\"store_true\",\n        help=\"don't perform semantic analysis of sources, just parse them \"\n        \"(only applies to Python modules, might affect quality of stubs. \"\n        \"Not compatible with --inspect-mode)\",\n    )\n    parser.add_argument(\n        \"--inspect-mode\",\n        dest=\"inspect\",\n        action=\"store_true\",\n        help=\"import and inspect modules instead of parsing source code.\"\n        \"This is the default behavior for c modules and pyc-only packages, but \"\n        \"it is also useful for pure python modules with dynamically generated members.\",\n    )\n    parser.add_argument(\n        \"--include-private\",\n        action=\"store_true\",\n        help=\"generate stubs for objects and members considered private \"\n        \"(single leading underscore and no trailing underscores)\",\n    )\n    parser.add_argument(\n        \"--export-less\",\n        action=\"store_true\",\n        help=\"don't implicitly export all names imported from other modules in the same package\",\n    )\n    parser.add_argument(\n        \"--include-docstrings\",\n        action=\"store_true\",\n        help=\"include existing docstrings with the stubs\",\n    )\n    parser.add_argument(\"-v\", \"--verbose\", action=\"store_true\", help=\"show more verbose messages\")\n    parser.add_argument(\"-q\", \"--quiet\", action=\"store_true\", help=\"show fewer messages\")\n    parser.add_argument(\n        \"--doc-dir\",\n        metavar=\"PATH\",\n        default=\"\",\n        help=\"use .rst documentation in PATH (this may result in \"\n        \"better stubs in some cases; consider setting this to \"\n        \"DIR/Python-X.Y.Z/Doc/library)\",\n    )\n    parser.add_argument(\n        \"--search-path\",\n        metavar=\"PATH\",\n        default=\"\",\n        help=\"specify module search directories, separated by ':' \"\n        \"(currently only used if --no-import is given)\",\n    )\n    parser.add_argument(\n        \"-o\",\n        \"--output\",\n        metavar=\"PATH\",\n        dest=\"output_dir\",\n        default=\"out\",\n        help=\"change the output directory [default: %(default)s]\",\n    )\n    parser.add_argument(\n        \"-m\",\n        \"--module\",\n        action=\"append\",\n        metavar=\"MODULE\",\n        dest=\"modules\",\n        default=[],\n        help=\"generate stub for module; can repeat for more modules\",\n    )\n    parser.add_argument(\n        \"-p\",\n        \"--package\",\n        action=\"append\",\n        metavar=\"PACKAGE\",\n        dest=\"packages\",\n        default=[],\n        help=\"generate stubs for package recursively; can be repeated\",\n    )\n    parser.add_argument(\n        metavar=\"files\",\n        nargs=\"*\",\n        dest=\"files\",\n        help=\"generate stubs for given files or directories\",\n    )\n    parser.add_argument(\n        \"--version\", action=\"version\", version=\"%(prog)s \" + mypy.version.__version__\n    )\n\n    ns = parser.parse_args(args)\n\n    pyversion = sys.version_info[:2]\n    ns.interpreter = sys.executable\n\n    if ns.modules + ns.packages and ns.files:\n        parser.error(\"May only specify one of: modules/packages or files.\")\n    if ns.quiet and ns.verbose:\n        parser.error(\"Cannot specify both quiet and verbose messages\")\n    if ns.inspect and ns.parse_only:\n        parser.error(\"Cannot specify both --parse-only/--no-analysis and --inspect-mode\")\n\n    # Create the output folder if it doesn't already exist.\n    os.makedirs(ns.output_dir, exist_ok=True)\n\n    return Options(\n        pyversion=pyversion,\n        no_import=ns.no_import,\n        inspect=ns.inspect,\n        doc_dir=ns.doc_dir,\n        search_path=ns.search_path.split(\":\"),\n        interpreter=ns.interpreter,\n        ignore_errors=ns.ignore_errors,\n        parse_only=ns.parse_only,\n        include_private=ns.include_private,\n        output_dir=ns.output_dir,\n        modules=ns.modules,\n        packages=ns.packages,\n        files=ns.files,\n        verbose=ns.verbose,\n        quiet=ns.quiet,\n        export_less=ns.export_less,\n        include_docstrings=ns.include_docstrings,\n    )\n\n\ndef main(args: list[str] | None = None) -> None:\n    mypy.util.check_python_version(\"stubgen\")\n    # Make sure that the current directory is in sys.path so that\n    # stubgen can be run on packages in the current directory.\n    if not (\"\" in sys.path or \".\" in sys.path):\n        sys.path.insert(0, \"\")\n\n    options = parse_options(sys.argv[1:] if args is None else args)\n    generate_stubs(options)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "mypy/stubgenc.py",
    "content": "#!/usr/bin/env python3\n\"\"\"Stub generator for C modules.\n\nThe public interface is via the mypy.stubgen module.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport enum\nimport glob\nimport importlib\nimport inspect\nimport keyword\nimport os.path\nfrom collections.abc import Callable, Mapping\nfrom types import FunctionType, ModuleType\nfrom typing import Any\n\nfrom mypy.fastparse import parse_type_comment\nfrom mypy.moduleinspect import is_c_module\nfrom mypy.stubdoc import (\n    ArgSig,\n    FunctionSig,\n    Sig,\n    find_unique_signatures,\n    infer_arg_sig_from_anon_docstring,\n    infer_prop_type_from_docstring,\n    infer_ret_type_sig_from_anon_docstring,\n    infer_ret_type_sig_from_docstring,\n    infer_sig_from_docstring,\n    parse_all_signatures,\n)\nfrom mypy.stubutil import (\n    BaseStubGenerator,\n    ClassInfo,\n    FunctionContext,\n    SignatureGenerator,\n    infer_method_arg_types,\n    infer_method_ret_type,\n)\nfrom mypy.util import quote_docstring\n\n\nclass ExternalSignatureGenerator(SignatureGenerator):\n    def __init__(\n        self, func_sigs: dict[str, str] | None = None, class_sigs: dict[str, str] | None = None\n    ) -> None:\n        \"\"\"\n        Takes a mapping of function/method names to signatures and class name to\n        class signatures (usually corresponds to __init__).\n        \"\"\"\n        self.func_sigs = func_sigs or {}\n        self.class_sigs = class_sigs or {}\n\n    @classmethod\n    def from_doc_dir(cls, doc_dir: str) -> ExternalSignatureGenerator:\n        \"\"\"Instantiate from a directory of .rst files.\"\"\"\n        all_sigs: list[Sig] = []\n        all_class_sigs: list[Sig] = []\n        for path in glob.glob(f\"{doc_dir}/*.rst\"):\n            with open(path) as f:\n                loc_sigs, loc_class_sigs = parse_all_signatures(f.readlines())\n            all_sigs += loc_sigs\n            all_class_sigs += loc_class_sigs\n        sigs = dict(find_unique_signatures(all_sigs))\n        class_sigs = dict(find_unique_signatures(all_class_sigs))\n        return ExternalSignatureGenerator(sigs, class_sigs)\n\n    def get_function_sig(\n        self, default_sig: FunctionSig, ctx: FunctionContext\n    ) -> list[FunctionSig] | None:\n        # method:\n        if (\n            ctx.class_info\n            and ctx.name in (\"__new__\", \"__init__\")\n            and ctx.name not in self.func_sigs\n            and ctx.class_info.name in self.class_sigs\n        ):\n            return [\n                FunctionSig(\n                    name=ctx.name,\n                    args=infer_arg_sig_from_anon_docstring(self.class_sigs[ctx.class_info.name]),\n                    ret_type=infer_method_ret_type(ctx.name),\n                )\n            ]\n\n        # function:\n        if ctx.name not in self.func_sigs:\n            return None\n\n        inferred = [\n            FunctionSig(\n                name=ctx.name,\n                args=infer_arg_sig_from_anon_docstring(self.func_sigs[ctx.name]),\n                ret_type=None,\n            )\n        ]\n        if ctx.class_info:\n            return self.remove_self_type(inferred, ctx.class_info.self_var)\n        else:\n            return inferred\n\n    def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None:\n        return None\n\n\nclass DocstringSignatureGenerator(SignatureGenerator):\n    def get_function_sig(\n        self, default_sig: FunctionSig, ctx: FunctionContext\n    ) -> list[FunctionSig] | None:\n        inferred = infer_sig_from_docstring(ctx.docstring, ctx.name)\n        if inferred:\n            assert ctx.docstring is not None\n            if is_pybind11_overloaded_function_docstring(ctx.docstring, ctx.name):\n                # Remove pybind11 umbrella (*args, **kwargs) for overloaded functions\n                del inferred[-1]\n\n        if ctx.class_info:\n            if not inferred and ctx.name == \"__init__\":\n                # look for class-level constructor signatures of the form <class_name>(<signature>)\n                inferred = infer_sig_from_docstring(ctx.class_info.docstring, ctx.class_info.name)\n                if inferred:\n                    inferred = [sig._replace(name=\"__init__\") for sig in inferred]\n            return self.remove_self_type(inferred, ctx.class_info.self_var)\n        else:\n            return inferred\n\n    def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None:\n        \"\"\"Infer property type from docstring or docstring signature.\"\"\"\n        if ctx.docstring is not None:\n            inferred = infer_ret_type_sig_from_anon_docstring(ctx.docstring)\n            if inferred:\n                return inferred\n            inferred = infer_ret_type_sig_from_docstring(ctx.docstring, ctx.name)\n            if inferred:\n                return inferred\n            inferred = infer_prop_type_from_docstring(ctx.docstring)\n            return inferred\n        else:\n            return None\n\n\ndef is_pybind11_overloaded_function_docstring(docstring: str, name: str) -> bool:\n    return docstring.startswith(f\"{name}(*args, **kwargs)\\nOverloaded function.\\n\\n\")\n\n\ndef generate_stub_for_c_module(\n    module_name: str,\n    target: str,\n    known_modules: list[str],\n    doc_dir: str = \"\",\n    *,\n    include_private: bool = False,\n    export_less: bool = False,\n    include_docstrings: bool = False,\n) -> None:\n    \"\"\"Generate stub for C module.\n\n    Signature generators are called in order until a list of signatures is returned.  The order\n    is:\n    - signatures inferred from .rst documentation (if given)\n    - simple runtime introspection (looking for docstrings and attributes\n      with simple builtin types)\n    - fallback based special method names or \"(*args, **kwargs)\"\n\n    If directory for target doesn't exist it will be created. Existing stub\n    will be overwritten.\n    \"\"\"\n    subdir = os.path.dirname(target)\n    if subdir and not os.path.isdir(subdir):\n        os.makedirs(subdir)\n\n    gen = InspectionStubGenerator(\n        module_name,\n        known_modules,\n        doc_dir,\n        include_private=include_private,\n        export_less=export_less,\n        include_docstrings=include_docstrings,\n    )\n    gen.generate_module()\n    output = gen.output()\n\n    with open(target, \"w\", encoding=\"utf-8\") as file:\n        file.write(output)\n\n\nclass CFunctionStub:\n    \"\"\"\n    Class that mimics a C function in order to provide parseable docstrings.\n    \"\"\"\n\n    def __init__(self, name: str, doc: str, is_abstract: bool = False) -> None:\n        self.__name__ = name\n        self.__doc__ = doc\n        self.__abstractmethod__ = is_abstract\n\n    @classmethod\n    def _from_sig(cls, sig: FunctionSig, is_abstract: bool = False) -> CFunctionStub:\n        return CFunctionStub(sig.name, sig.format_sig()[:-4], is_abstract)\n\n    @classmethod\n    def _from_sigs(cls, sigs: list[FunctionSig], is_abstract: bool = False) -> CFunctionStub:\n        return CFunctionStub(\n            sigs[0].name, \"\\n\".join(sig.format_sig()[:-4] for sig in sigs), is_abstract\n        )\n\n    def __get__(self) -> None:  # noqa: PLE0302\n        \"\"\"\n        This exists to make this object look like a method descriptor and thus\n        return true for CStubGenerator.ismethod()\n        \"\"\"\n        pass\n\n\n_Missing = enum.Enum(\"_Missing\", \"VALUE\")\n\n\nclass InspectionStubGenerator(BaseStubGenerator):\n    \"\"\"Stub generator that does not parse code.\n\n    Generation is performed by inspecting the module's contents, and thus works\n    for highly dynamic modules, pyc files, and C modules (via the CStubGenerator\n    subclass).\n    \"\"\"\n\n    def __init__(\n        self,\n        module_name: str,\n        known_modules: list[str],\n        doc_dir: str = \"\",\n        _all_: list[str] | None = None,\n        include_private: bool = False,\n        export_less: bool = False,\n        include_docstrings: bool = False,\n        module: ModuleType | None = None,\n    ) -> None:\n        self.doc_dir = doc_dir\n        if module is None:\n            self.module = importlib.import_module(module_name)\n        else:\n            self.module = module\n        self.is_c_module = is_c_module(self.module)\n        self.known_modules = known_modules\n        self.resort_members = self.is_c_module\n        super().__init__(_all_, include_private, export_less, include_docstrings)\n        self.module_name = module_name\n        if self.is_c_module:\n            # Add additional implicit imports.\n            # C-extensions are given more latitude since they do not import the typing module.\n            self.known_imports.update(\n                {\n                    \"typing\": [\n                        \"Any\",\n                        \"Callable\",\n                        \"ClassVar\",\n                        \"Dict\",\n                        \"Iterable\",\n                        \"Iterator\",\n                        \"List\",\n                        \"Literal\",\n                        \"NamedTuple\",\n                        \"Optional\",\n                        \"Tuple\",\n                        \"Union\",\n                    ]\n                }\n            )\n\n    def get_default_function_sig(self, func: object, ctx: FunctionContext) -> FunctionSig:\n        argspec = None\n        if not self.is_c_module:\n            # Get the full argument specification of the function\n            try:\n                argspec = inspect.getfullargspec(func)\n            except TypeError:\n                # some callables cannot be inspected, e.g. functools.partial\n                pass\n        if argspec is None:\n            if ctx.class_info is not None:\n                # method:\n                return FunctionSig(\n                    name=ctx.name,\n                    args=infer_c_method_args(ctx.name, ctx.class_info.self_var),\n                    ret_type=infer_method_ret_type(ctx.name),\n                )\n            else:\n                # function:\n                return FunctionSig(\n                    name=ctx.name,\n                    args=[ArgSig(name=\"*args\"), ArgSig(name=\"**kwargs\")],\n                    ret_type=None,\n                )\n\n        # Extract the function arguments, defaults, and varargs\n        args = argspec.args\n        defaults = argspec.defaults\n        varargs = argspec.varargs\n        kwargs = argspec.varkw\n        annotations = argspec.annotations\n        kwonlyargs = argspec.kwonlyargs\n        kwonlydefaults = argspec.kwonlydefaults\n\n        def get_annotation(key: str) -> str | None:\n            if key not in annotations:\n                return None\n            argtype = annotations[key]\n            if argtype is None:\n                return \"None\"\n            if not isinstance(argtype, str):\n                return self.get_type_fullname(argtype)\n            return argtype\n\n        arglist: list[ArgSig] = []\n\n        # Add the arguments to the signature\n        def add_args(\n            args: list[str], get_default_value: Callable[[int, str], object | _Missing]\n        ) -> None:\n            for i, arg in enumerate(args):\n                # Check if the argument has a default value\n                default_value = get_default_value(i, arg)\n                if default_value is not _Missing.VALUE:\n                    if arg in annotations:\n                        argtype = get_annotation(arg)\n                    else:\n                        argtype = self.get_type_annotation(default_value)\n                        if argtype == \"None\":\n                            # None is not a useful annotation, but we can infer that the arg\n                            # is optional\n                            incomplete = self.add_name(\"_typeshed.Incomplete\")\n                            argtype = f\"{incomplete} | None\"\n\n                    arglist.append(ArgSig(arg, argtype, default=True))\n                else:\n                    arglist.append(ArgSig(arg, get_annotation(arg), default=False))\n\n        def get_pos_default(i: int, _arg: str) -> Any | _Missing:\n            if defaults and i >= len(args) - len(defaults):\n                return defaults[i - (len(args) - len(defaults))]\n            else:\n                return _Missing.VALUE\n\n        add_args(args, get_pos_default)\n\n        # Add *args if present\n        if varargs:\n            arglist.append(ArgSig(f\"*{varargs}\", get_annotation(varargs)))\n        # if we have keyword only args, then we need to add \"*\"\n        elif kwonlyargs:\n            arglist.append(ArgSig(\"*\"))\n\n        def get_kw_default(_i: int, arg: str) -> Any | _Missing:\n            if kwonlydefaults and arg in kwonlydefaults:\n                return kwonlydefaults[arg]\n            else:\n                return _Missing.VALUE\n\n        add_args(kwonlyargs, get_kw_default)\n\n        # Add **kwargs if present\n        if kwargs:\n            arglist.append(ArgSig(f\"**{kwargs}\", get_annotation(kwargs)))\n\n        # add types for known special methods\n        if ctx.class_info is not None and all(\n            arg.type is None and arg.default is False for arg in arglist\n        ):\n            new_args = infer_method_arg_types(\n                ctx.name, ctx.class_info.self_var, [arg.name for arg in arglist if arg.name]\n            )\n            if new_args is not None:\n                arglist = new_args\n\n        ret_type = get_annotation(\"return\") or infer_method_ret_type(ctx.name)\n        return FunctionSig(ctx.name, arglist, ret_type)\n\n    def get_sig_generators(self) -> list[SignatureGenerator]:\n        if not self.is_c_module:\n            return []\n        else:\n            sig_generators: list[SignatureGenerator] = [DocstringSignatureGenerator()]\n            if self.doc_dir:\n                # Collect info from docs (if given). Always check these first.\n                sig_generators.insert(0, ExternalSignatureGenerator.from_doc_dir(self.doc_dir))\n            return sig_generators\n\n    def strip_or_import(self, type_name: str) -> str:\n        \"\"\"Strips unnecessary module names from typ.\n\n        If typ represents a type that is inside module or is a type coming from builtins, remove\n        module declaration from it. Return stripped name of the type.\n\n        Arguments:\n            typ: name of the type\n        \"\"\"\n        local_modules = [\"builtins\", self.module_name]\n        parsed_type = parse_type_comment(type_name, 0, 0, None)[1]\n        assert parsed_type is not None, type_name\n        return self.print_annotation(parsed_type, self.known_modules, local_modules)\n\n    def get_obj_module(self, obj: object) -> str | None:\n        \"\"\"Return module name of the object.\"\"\"\n        return getattr(obj, \"__module__\", None)\n\n    def is_defined_in_module(self, obj: object) -> bool:\n        \"\"\"Check if object is considered defined in the current module.\"\"\"\n        module = self.get_obj_module(obj)\n        return module is None or module == self.module_name\n\n    def generate_module(self) -> None:\n        all_items = self.get_members(self.module)\n        if self.resort_members:\n            all_items = sorted(all_items, key=lambda x: x[0])\n        items = []\n        for name, obj in all_items:\n            if inspect.ismodule(obj) and obj.__name__ in self.known_modules:\n                module_name = obj.__name__\n                if module_name.startswith(self.module_name + \".\"):\n                    # from {.rel_name} import {mod_name} as {name}\n                    pkg_name, mod_name = module_name.rsplit(\".\", 1)\n                    rel_module = pkg_name[len(self.module_name) :] or \".\"\n                    self.import_tracker.add_import_from(rel_module, [(mod_name, name)])\n                    self.import_tracker.reexport(name)\n                else:\n                    # import {module_name} as {name}\n                    self.import_tracker.add_import(module_name, name)\n                    self.import_tracker.reexport(name)\n            elif self.is_defined_in_module(obj) and not inspect.ismodule(obj):\n                # process this below\n                items.append((name, obj))\n            else:\n                # from {obj_module} import {obj_name}\n                obj_module_name = self.get_obj_module(obj)\n                if obj_module_name:\n                    self.import_tracker.add_import_from(obj_module_name, [(name, None)])\n                    if self.should_reexport(name, obj_module_name, name_is_alias=False):\n                        self.import_tracker.reexport(name)\n\n        self.set_defined_names({name for name, obj in all_items if not inspect.ismodule(obj)})\n\n        if self.resort_members:\n            functions: list[str] = []\n            types: list[str] = []\n            variables: list[str] = []\n        else:\n            output: list[str] = []\n            functions = types = variables = output\n\n        for name, obj in items:\n            if self.is_function(obj):\n                self.generate_function_stub(name, obj, output=functions)\n            elif inspect.isclass(obj):\n                self.generate_class_stub(name, obj, output=types)\n            else:\n                self.generate_variable_stub(name, obj, output=variables)\n\n        self._output = []\n\n        if self.resort_members:\n            for line in variables:\n                self._output.append(line + \"\\n\")\n            for line in types:\n                if line.startswith(\"class\") and self._output and self._output[-1]:\n                    self._output.append(\"\\n\")\n                self._output.append(line + \"\\n\")\n            if self._output and functions:\n                self._output.append(\"\\n\")\n            for line in functions:\n                self._output.append(line + \"\\n\")\n        else:\n            for i, line in enumerate(output):\n                if (\n                    self._output\n                    and line.startswith(\"class\")\n                    and (\n                        not self._output[-1].startswith(\"class\")\n                        or (len(output) > i + 1 and output[i + 1].startswith(\"    \"))\n                    )\n                ) or (\n                    self._output\n                    and self._output[-1].startswith(\"def\")\n                    and not line.startswith(\"def\")\n                ):\n                    self._output.append(\"\\n\")\n                self._output.append(line + \"\\n\")\n        self.check_undefined_names()\n\n    def is_skipped_attribute(self, attr: str) -> bool:\n        return (\n            attr\n            in (\n                \"__class__\",\n                \"__getattribute__\",\n                \"__str__\",\n                \"__repr__\",\n                \"__doc__\",\n                \"__dict__\",\n                \"__module__\",\n                \"__weakref__\",\n                \"__annotations__\",\n                \"__firstlineno__\",\n                \"__static_attributes__\",\n                \"__annotate__\",\n            )\n            or attr in self.IGNORED_DUNDERS\n            or is_pybind_skipped_attribute(attr)  # For pickling\n            or keyword.iskeyword(attr)\n        )\n\n    def get_members(self, obj: object) -> list[tuple[str, Any]]:\n        obj_dict: Mapping[str, Any] = getattr(obj, \"__dict__\")  # noqa: B009\n        results = []\n        for name in obj_dict:\n            if self.is_skipped_attribute(name):\n                continue\n            # Try to get the value via getattr\n            try:\n                value = getattr(obj, name)\n            except AttributeError:\n                continue\n            else:\n                results.append((name, value))\n        return results\n\n    def get_type_annotation(self, obj: object) -> str:\n        \"\"\"\n        Given an instance, return a string representation of its type that is valid\n        to use as a type annotation.\n        \"\"\"\n        if obj is None or obj is type(None):\n            return \"None\"\n        elif inspect.isclass(obj):\n            return f\"type[{self.get_type_fullname(obj)}]\"\n        elif isinstance(obj, FunctionType):\n            return self.add_name(\"typing.Callable\")\n        elif isinstance(obj, ModuleType):\n            return self.add_name(\"types.ModuleType\", require=False)\n        else:\n            return self.get_type_fullname(type(obj))\n\n    def is_function(self, obj: object) -> bool:\n        if self.is_c_module:\n            return inspect.isbuiltin(obj)\n        else:\n            return inspect.isfunction(obj)\n\n    def is_method(self, class_info: ClassInfo, name: str, obj: object) -> bool:\n        if self.is_c_module:\n            return inspect.ismethoddescriptor(obj) or type(obj) in (\n                type(str.index),\n                type(str.__add__),\n                type(str.__new__),\n            )\n        else:\n            # this is valid because it is only called on members of a class\n            return inspect.isfunction(obj)\n\n    def is_classmethod(self, class_info: ClassInfo, name: str, obj: object) -> bool:\n        if self.is_c_module:\n            return inspect.isbuiltin(obj) or type(obj).__name__ in (\n                \"classmethod\",\n                \"classmethod_descriptor\",\n            )\n        else:\n            return inspect.ismethod(obj)\n\n    def is_staticmethod(self, class_info: ClassInfo | None, name: str, obj: object) -> bool:\n        if class_info is None:\n            return False\n        elif self.is_c_module:\n            raw_lookup: Mapping[str, Any] = getattr(class_info.cls, \"__dict__\")  # noqa: B009\n            raw_value = raw_lookup.get(name, obj)\n            return isinstance(raw_value, staticmethod)\n        else:\n            return isinstance(inspect.getattr_static(class_info.cls, name), staticmethod)\n\n    @staticmethod\n    def is_abstract_method(obj: object) -> bool:\n        return getattr(obj, \"__abstractmethod__\", False)\n\n    @staticmethod\n    def is_property(class_info: ClassInfo, name: str, obj: object) -> bool:\n        return inspect.isdatadescriptor(obj) or hasattr(obj, \"fget\")\n\n    @staticmethod\n    def is_property_readonly(prop: Any) -> bool:\n        return hasattr(prop, \"fset\") and prop.fset is None\n\n    def is_static_property(self, obj: object) -> bool:\n        \"\"\"For c-modules, whether the property behaves like an attribute\"\"\"\n        if self.is_c_module:\n            # StaticProperty is from boost-python\n            return type(obj).__name__ in (\"pybind11_static_property\", \"StaticProperty\")\n        else:\n            return False\n\n    def process_inferred_sigs(self, inferred: list[FunctionSig]) -> None:\n        for i, sig in enumerate(inferred):\n            for arg in sig.args:\n                if arg.type is not None:\n                    arg.type = self.strip_or_import(arg.type)\n            if sig.ret_type is not None:\n                inferred[i] = sig._replace(ret_type=self.strip_or_import(sig.ret_type))\n\n    def generate_function_stub(\n        self, name: str, obj: object, *, output: list[str], class_info: ClassInfo | None = None\n    ) -> None:\n        \"\"\"Generate stub for a single function or method.\n\n        The result (always a single line) will be appended to 'output'.\n        If necessary, any required names will be added to 'imports'.\n        The 'class_name' is used to find signature of __init__ or __new__ in\n        'class_sigs'.\n        \"\"\"\n        docstring: Any = getattr(obj, \"__doc__\", None)\n        if not isinstance(docstring, str):\n            docstring = None\n\n        ctx = FunctionContext(\n            self.module_name,\n            name,\n            docstring=docstring,\n            is_abstract=self.is_abstract_method(obj),\n            class_info=class_info,\n        )\n        if self.is_private_name(name, ctx.fullname) or self.is_not_in_all(name):\n            return\n\n        self.record_name(ctx.name)\n        default_sig = self.get_default_function_sig(obj, ctx)\n        inferred = self.get_signatures(default_sig, self.sig_generators, ctx)\n        self.process_inferred_sigs(inferred)\n\n        decorators = []\n        if len(inferred) > 1:\n            decorators.append(\"@{}\".format(self.add_name(\"typing.overload\")))\n\n        if ctx.is_abstract:\n            decorators.append(\"@{}\".format(self.add_name(\"abc.abstractmethod\")))\n\n        if class_info is not None:\n            if self.is_staticmethod(class_info, name, obj):\n                decorators.append(\"@staticmethod\")\n            else:\n                for sig in inferred:\n                    if not sig.args or sig.args[0].name not in (\"self\", \"cls\"):\n                        sig.args.insert(0, ArgSig(name=class_info.self_var))\n                # a sig generator indicates @classmethod by specifying the cls arg.\n                if inferred[0].args and inferred[0].args[0].name == \"cls\":\n                    decorators.append(\"@classmethod\")\n\n        docstring = self._indent_docstring(ctx.docstring) if ctx.docstring else None\n        output.extend(self.format_func_def(inferred, decorators=decorators, docstring=docstring))\n        self._fix_iter(ctx, inferred, output)\n\n    def _indent_docstring(self, docstring: str) -> str:\n        \"\"\"Fix indentation of docstring extracted from pybind11 or other binding generators.\"\"\"\n        lines = docstring.splitlines(keepends=True)\n        indent = self._indent + \"    \"\n        if len(lines) > 1:\n            if not all(line.startswith(indent) or not line.strip() for line in lines):\n                # if the docstring is not indented, then indent all but the first line\n                for i, line in enumerate(lines[1:]):\n                    if line.strip():\n                        lines[i + 1] = indent + line\n        # if there's a trailing newline, add a final line to visually indent the quoted docstring\n        if lines[-1].endswith(\"\\n\"):\n            if len(lines) > 1:\n                lines.append(indent)\n            else:\n                lines[-1] = lines[-1][:-1]\n        return \"\".join(lines)\n\n    def _fix_iter(\n        self, ctx: FunctionContext, inferred: list[FunctionSig], output: list[str]\n    ) -> None:\n        \"\"\"Ensure that objects which implement old-style iteration via __getitem__\n        are considered iterable.\n        \"\"\"\n        if (\n            ctx.class_info\n            and ctx.class_info.cls is not None\n            and ctx.name == \"__getitem__\"\n            and \"__iter__\" not in ctx.class_info.cls.__dict__\n        ):\n            item_type: str | None = None\n            for sig in inferred:\n                if sig.args and sig.args[-1].type == \"int\":\n                    item_type = sig.ret_type\n                    break\n            if item_type is None:\n                return\n            obj = CFunctionStub(\n                \"__iter__\", f\"def __iter__(self) -> typing.Iterator[{item_type}]\\n\"\n            )\n            self.generate_function_stub(\"__iter__\", obj, output=output, class_info=ctx.class_info)\n\n    def generate_property_stub(\n        self,\n        name: str,\n        raw_obj: object,\n        obj: object,\n        static_properties: list[str],\n        rw_properties: list[str],\n        ro_properties: list[str],\n        class_info: ClassInfo | None = None,\n    ) -> None:\n        \"\"\"Generate property stub using introspection of 'obj'.\n\n        Try to infer type from docstring, append resulting lines to 'output'.\n\n        raw_obj : object before evaluation of descriptor (if any)\n        obj : object after evaluation of descriptor\n        \"\"\"\n\n        docstring = getattr(raw_obj, \"__doc__\", None)\n        fget = getattr(raw_obj, \"fget\", None)\n        if fget:\n            alt_docstr = getattr(fget, \"__doc__\", None)\n            if alt_docstr and docstring:\n                docstring += \"\\n\" + alt_docstr\n            elif alt_docstr:\n                docstring = alt_docstr\n\n        ctx = FunctionContext(\n            self.module_name, name, docstring=docstring, is_abstract=False, class_info=class_info\n        )\n\n        if self.is_private_name(name, ctx.fullname) or self.is_not_in_all(name):\n            return\n\n        self.record_name(ctx.name)\n        static = self.is_static_property(raw_obj)\n        readonly = self.is_property_readonly(raw_obj)\n        if static:\n            ret_type: str | None = self.strip_or_import(self.get_type_annotation(obj))\n        else:\n            default_sig = self.get_default_function_sig(raw_obj, ctx)\n            ret_type = default_sig.ret_type\n\n        inferred_type = self.get_property_type(ret_type, self.sig_generators, ctx)\n        if inferred_type is not None:\n            inferred_type = self.strip_or_import(inferred_type)\n\n        if static:\n            classvar = self.add_name(\"typing.ClassVar\")\n            trailing_comment = \"  # read-only\" if readonly else \"\"\n            if inferred_type is None:\n                inferred_type = self.add_name(\"_typeshed.Incomplete\")\n\n            static_properties.append(\n                f\"{self._indent}{name}: {classvar}[{inferred_type}] = ...{trailing_comment}\"\n            )\n        else:  # regular property\n            if readonly:\n                docstring = self._indent_docstring(ctx.docstring) if ctx.docstring else None\n                ro_properties.append(f\"{self._indent}@property\")\n                sig = FunctionSig(name, [ArgSig(\"self\")], inferred_type, docstring=docstring)\n                ro_properties.append(\n                    sig.format_sig(\n                        indent=self._indent, include_docstrings=self._include_docstrings\n                    )\n                )\n            else:\n                if inferred_type is None:\n                    inferred_type = self.add_name(\"_typeshed.Incomplete\")\n\n                rw_properties.append(f\"{self._indent}{name}: {inferred_type}\")\n\n    def get_type_fullname(self, typ: type) -> str:\n        \"\"\"Given a type, return a string representation\"\"\"\n        if typ is Any:\n            return \"Any\"\n        typename = getattr(typ, \"__qualname__\", typ.__name__)\n        module_name = self.get_obj_module(typ)\n        if module_name is None:\n            # This should not normally happen, but some types may resist our\n            # introspection attempts too hard. See\n            # https://github.com/python/mypy/issues/19031\n            return \"_typeshed.Incomplete\"\n        if module_name != \"builtins\":\n            typename = f\"{module_name}.{typename}\"\n        return typename\n\n    def get_base_types(self, obj: type) -> list[str]:\n        all_bases = type.mro(obj)\n        if all_bases[-1] is object:\n            # TODO: Is this always object?\n            del all_bases[-1]\n        # remove pybind11_object. All classes generated by pybind11 have pybind11_object in their MRO,\n        # which only overrides a few functions in object type\n        if all_bases and all_bases[-1].__name__ == \"pybind11_object\":\n            del all_bases[-1]\n        # remove the class itself\n        all_bases = all_bases[1:]\n        # Remove base classes of other bases as redundant.\n        bases: list[type] = []\n        for base in all_bases:\n            if not any(issubclass(b, base) for b in bases):\n                bases.append(base)\n        return [self.strip_or_import(self.get_type_fullname(base)) for base in bases]\n\n    def generate_class_stub(\n        self, class_name: str, cls: type, output: list[str], parent_class: ClassInfo | None = None\n    ) -> None:\n        \"\"\"Generate stub for a single class using runtime introspection.\n\n        The result lines will be appended to 'output'. If necessary, any\n        required names will be added to 'imports'.\n        \"\"\"\n        raw_lookup: Mapping[str, Any] = getattr(cls, \"__dict__\")  # noqa: B009\n        items = self.get_members(cls)\n        if self.resort_members:\n            items = sorted(items, key=lambda x: method_name_sort_key(x[0]))\n        names = {x[0] for x in items}\n        methods: list[str] = []\n        types: list[str] = []\n        static_properties: list[str] = []\n        rw_properties: list[str] = []\n        ro_properties: list[str] = []\n        attrs: list[tuple[str, Any]] = []\n\n        self.record_name(class_name)\n        self.indent()\n\n        class_info = ClassInfo(\n            class_name, \"\", getattr(cls, \"__doc__\", None), cls, parent=parent_class\n        )\n\n        for attr, value in items:\n            # use unevaluated descriptors when dealing with property inspection\n            raw_value = raw_lookup.get(attr, value)\n            if self.is_method(class_info, attr, value) or self.is_classmethod(\n                class_info, attr, value\n            ):\n                if attr == \"__new__\":\n                    # TODO: We should support __new__.\n                    if \"__init__\" in names:\n                        # Avoid duplicate functions if both are present.\n                        # But is there any case where .__new__() has a\n                        # better signature than __init__() ?\n                        continue\n                    attr = \"__init__\"\n                # FIXME: make this nicer\n                if self.is_staticmethod(class_info, attr, value):\n                    class_info.self_var = \"\"\n                elif self.is_classmethod(class_info, attr, value):\n                    class_info.self_var = \"cls\"\n                else:\n                    class_info.self_var = \"self\"\n                self.generate_function_stub(attr, value, output=methods, class_info=class_info)\n            elif self.is_property(class_info, attr, raw_value):\n                self.generate_property_stub(\n                    attr,\n                    raw_value,\n                    value,\n                    static_properties,\n                    rw_properties,\n                    ro_properties,\n                    class_info,\n                )\n            elif inspect.isclass(value) and self.is_defined_in_module(value):\n                self.generate_class_stub(attr, value, types, parent_class=class_info)\n            else:\n                attrs.append((attr, value))\n\n        for attr, value in attrs:\n            if attr == \"__hash__\" and value is None:\n                # special case for __hash__\n                continue\n            prop_type_name = self.strip_or_import(self.get_type_annotation(value))\n            classvar = self.add_name(\"typing.ClassVar\")\n            static_properties.append(f\"{self._indent}{attr}: {classvar}[{prop_type_name}] = ...\")\n\n        self.dedent()\n\n        bases = self.get_base_types(cls)\n        if bases:\n            bases_str = \"(%s)\" % \", \".join(bases)\n        else:\n            bases_str = \"\"\n\n        if class_info.docstring and self._include_docstrings:\n            doc = quote_docstring(self._indent_docstring(class_info.docstring))\n            doc = f\"    {self._indent}{doc}\"\n            docstring = doc.splitlines(keepends=False)\n        else:\n            docstring = []\n\n        if docstring or types or static_properties or rw_properties or methods or ro_properties:\n            output.append(f\"{self._indent}class {class_name}{bases_str}:\")\n            output.extend(docstring)\n            for line in types:\n                if (\n                    output\n                    and output[-1]\n                    and not output[-1].strip().startswith(\"class\")\n                    and line.strip().startswith(\"class\")\n                ):\n                    output.append(\"\")\n                output.append(line)\n            output.extend(static_properties)\n            output.extend(rw_properties)\n            output.extend(methods)\n            output.extend(ro_properties)\n        else:\n            output.append(f\"{self._indent}class {class_name}{bases_str}: ...\")\n\n    def generate_variable_stub(self, name: str, obj: object, output: list[str]) -> None:\n        \"\"\"Generate stub for a single variable using runtime introspection.\n\n        The result lines will be appended to 'output'. If necessary, any\n        required names will be added to 'imports'.\n        \"\"\"\n        if self.is_private_name(name, f\"{self.module_name}.{name}\") or self.is_not_in_all(name):\n            return\n        self.record_name(name)\n        type_str = self.strip_or_import(self.get_type_annotation(obj))\n        output.append(f\"{name}: {type_str}\")\n\n\ndef method_name_sort_key(name: str) -> tuple[int, str]:\n    \"\"\"Sort methods in classes in a typical order.\n\n    I.e.: constructor, normal methods, special methods.\n    \"\"\"\n    if name in (\"__new__\", \"__init__\"):\n        return 0, name\n    if name.startswith(\"__\") and name.endswith(\"__\"):\n        return 2, name\n    return 1, name\n\n\ndef is_pybind_skipped_attribute(attr: str) -> bool:\n    return attr.startswith(\"__pybind11_module_local_\")\n\n\ndef infer_c_method_args(\n    name: str, self_var: str = \"self\", arg_names: list[str] | None = None\n) -> list[ArgSig]:\n    args: list[ArgSig] | None = None\n    if name.startswith(\"__\") and name.endswith(\"__\"):\n        name = name[2:-2]\n        if name in (\n            \"hash\",\n            \"iter\",\n            \"next\",\n            \"sizeof\",\n            \"copy\",\n            \"deepcopy\",\n            \"reduce\",\n            \"getinitargs\",\n            \"int\",\n            \"float\",\n            \"trunc\",\n            \"complex\",\n            \"bool\",\n            \"abs\",\n            \"bytes\",\n            \"dir\",\n            \"len\",\n            \"reversed\",\n            \"round\",\n            \"index\",\n            \"enter\",\n        ):\n            args = []\n        elif name == \"getitem\":\n            args = [ArgSig(name=\"index\")]\n        elif name == \"setitem\":\n            args = [ArgSig(name=\"index\"), ArgSig(name=\"object\")]\n        elif name in (\"delattr\", \"getattr\"):\n            args = [ArgSig(name=\"name\")]\n        elif name == \"setattr\":\n            args = [ArgSig(name=\"name\"), ArgSig(name=\"value\")]\n        elif name == \"getstate\":\n            args = []\n        elif name == \"setstate\":\n            args = [ArgSig(name=\"state\")]\n        elif name in (\"eq\", \"ne\", \"lt\", \"le\", \"gt\", \"ge\"):\n            args = [ArgSig(name=\"other\", type=\"object\")]\n        elif name in (\n            \"add\",\n            \"radd\",\n            \"sub\",\n            \"rsub\",\n            \"mul\",\n            \"rmul\",\n            \"mod\",\n            \"rmod\",\n            \"floordiv\",\n            \"rfloordiv\",\n            \"truediv\",\n            \"rtruediv\",\n            \"divmod\",\n            \"rdivmod\",\n            \"pow\",\n            \"rpow\",\n            \"xor\",\n            \"rxor\",\n            \"or\",\n            \"ror\",\n            \"and\",\n            \"rand\",\n            \"lshift\",\n            \"rlshift\",\n            \"rshift\",\n            \"rrshift\",\n            \"contains\",\n            \"delitem\",\n            \"iadd\",\n            \"iand\",\n            \"ifloordiv\",\n            \"ilshift\",\n            \"imod\",\n            \"imul\",\n            \"ior\",\n            \"ipow\",\n            \"irshift\",\n            \"isub\",\n            \"itruediv\",\n            \"ixor\",\n        ):\n            args = [ArgSig(name=\"other\")]\n        elif name in (\"neg\", \"pos\", \"invert\"):\n            args = []\n        elif name == \"get\":\n            args = [ArgSig(name=\"instance\"), ArgSig(name=\"owner\")]\n        elif name == \"set\":\n            args = [ArgSig(name=\"instance\"), ArgSig(name=\"value\")]\n        elif name == \"reduce_ex\":\n            args = [ArgSig(name=\"protocol\")]\n        elif name == \"exit\":\n            args = [\n                ArgSig(name=\"type\", type=\"type[BaseException] | None\"),\n                ArgSig(name=\"value\", type=\"BaseException | None\"),\n                ArgSig(name=\"traceback\", type=\"types.TracebackType | None\"),\n            ]\n    if args is None:\n        args = infer_method_arg_types(name, self_var, arg_names)\n    else:\n        args = [ArgSig(name=self_var)] + args\n    if args is None:\n        args = [ArgSig(name=\"*args\"), ArgSig(name=\"**kwargs\")]\n    return args\n"
  },
  {
    "path": "mypy/stubinfo.py",
    "content": "from __future__ import annotations\n\n\ndef is_module_from_legacy_bundled_package(module: str) -> bool:\n    top_level = module.split(\".\", 1)[0]\n    return top_level in legacy_bundled_packages\n\n\ndef stub_distribution_name(module: str) -> str | None:\n    top_level = module.split(\".\", 1)[0]\n\n    dist = legacy_bundled_packages.get(top_level)\n    if dist:\n        return dist\n    dist = non_bundled_packages_flat.get(top_level)\n    if dist:\n        return dist\n\n    if top_level in non_bundled_packages_namespace:\n        namespace = non_bundled_packages_namespace[top_level]\n        components = module.split(\".\")\n        for i in range(len(components), 0, -1):\n            module = \".\".join(components[:i])\n            dist = namespace.get(module)\n            if dist:\n                return dist\n\n    return None\n\n\n# Stubs for these third-party packages used to be shipped with mypy.\n#\n# Map package name to PyPI stub distribution name.\nlegacy_bundled_packages: dict[str, str] = {\n    \"aiofiles\": \"types-aiofiles\",\n    \"bleach\": \"types-bleach\",\n    \"cachetools\": \"types-cachetools\",\n    \"click_spinner\": \"types-click-spinner\",\n    \"croniter\": \"types-croniter\",\n    \"dateparser\": \"types-dateparser\",\n    \"dateutil\": \"types-python-dateutil\",\n    \"decorator\": \"types-decorator\",\n    \"deprecated\": \"types-Deprecated\",\n    \"docutils\": \"types-docutils\",\n    \"first\": \"types-first\",\n    \"markdown\": \"types-Markdown\",\n    \"mock\": \"types-mock\",\n    \"paramiko\": \"types-paramiko\",\n    \"polib\": \"types-polib\",\n    \"pycurl\": \"types-pycurl\",\n    \"pymysql\": \"types-PyMySQL\",\n    \"pyrfc3339\": \"types-pyRFC3339\",\n    \"pytz\": \"types-pytz\",\n    \"requests\": \"types-requests\",\n    \"retry\": \"types-retry\",\n    \"simplejson\": \"types-simplejson\",\n    \"singledispatch\": \"types-singledispatch\",\n    \"six\": \"types-six\",\n    \"tabulate\": \"types-tabulate\",\n    \"toml\": \"types-toml\",\n    \"ujson\": \"types-ujson\",\n    \"waitress\": \"types-waitress\",\n    \"yaml\": \"types-PyYAML\",\n}\n\n# Map package name to PyPI stub distribution name from typeshed.\n# Stubs for these packages were never bundled with mypy. Don't\n# include packages that have a release that includes PEP 561 type\n# information.\n#\n# Note that these packages are omitted for now:\n#   pika:       typeshed's stubs are on PyPI as types-pika-ts.\n#               types-pika already exists on PyPI, and is more complete in many ways,\n#               but is a non-typeshed stubs package.\nnon_bundled_packages_flat: dict[str, str] = {\n    \"_cffi_backend\": \"types-cffi\",\n    \"_jsonnet\": \"types-jsonnet\",\n    \"_win32typing\": \"types-pywin32\",\n    \"antlr4\": \"types-antlr4-python3-runtime\",\n    \"assertpy\": \"types-assertpy\",\n    \"atheris\": \"types-atheris\",\n    \"auth0\": \"types-auth0-python\",\n    \"authlib\": \"types-Authlib\",\n    \"aws_xray_sdk\": \"types-aws-xray-sdk\",\n    \"binaryornot\": \"types-binaryornot\",\n    \"boltons\": \"types-boltons\",\n    \"braintree\": \"types-braintree\",\n    \"bugbear\": \"types-flake8-bugbear\",\n    \"capturer\": \"types-capturer\",\n    \"cffi\": \"types-cffi\",\n    \"channels\": \"types-channels\",\n    \"chevron\": \"types-chevron\",\n    \"click_default_group\": \"types-click-default-group\",\n    \"click_log\": \"types-click-log\",\n    \"click_shell\": \"types-click-shell\",\n    \"click_web\": \"types-click-web\",\n    \"colorama\": \"types-colorama\",\n    \"colorful\": \"types-colorful\",\n    \"commctrl\": \"types-pywin32\",\n    \"consolemenu\": \"types-console-menu\",\n    \"convertdate\": \"types-convertdate\",\n    \"cronlog\": \"types-python-crontab\",\n    \"crontab\": \"types-python-crontab\",\n    \"crontabs\": \"types-python-crontab\",\n    \"dateparser_data\": \"types-dateparser\",\n    \"dde\": \"types-pywin32\",\n    \"defusedxml\": \"types-defusedxml\",\n    \"dirhash\": \"types-dirhash\",\n    \"django_filters\": \"types-django-filter\",\n    \"docker\": \"types-docker\",\n    \"dockerfile_parse\": \"types-dockerfile-parse\",\n    \"editdistance\": \"types-editdistance\",\n    \"entrypoints\": \"types-entrypoints\",\n    \"ephem\": \"types-ephem\",\n    \"et_xmlfile\": \"types-et_xmlfile\",\n    \"fanstatic\": \"types-fanstatic\",\n    \"farmhash\": \"types-pyfarmhash\",\n    \"flake8_builtins\": \"types-flake8-builtins\",\n    \"flake8_docstrings\": \"types-flake8-docstrings\",\n    \"flake8_rst_docstrings\": \"types-flake8-rst-docstrings\",\n    \"flake8_simplify\": \"types-flake8-simplify\",\n    \"flake8_typing_imports\": \"types-flake8-typing-imports\",\n    \"flake8\": \"types-flake8\",\n    \"flask_cors\": \"types-Flask-Cors\",\n    \"flask_migrate\": \"types-Flask-Migrate\",\n    \"flask_socketio\": \"types-Flask-SocketIO\",\n    \"fpdf\": \"types-fpdf2\",\n    \"gdb\": \"types-gdb\",\n    \"geopandas\": \"types-geopandas\",\n    \"gevent\": \"types-gevent\",\n    \"greenlet\": \"types-greenlet\",\n    \"grpc_channelz\": \"types-grpcio-channelz\",\n    \"grpc_health\": \"types-grpcio-health-checking\",\n    \"grpc_reflection\": \"types-grpcio-reflection\",\n    \"grpc_status\": \"types-grpcio-status\",\n    \"grpc\": \"types-grpcio\",\n    \"gunicorn\": \"types-gunicorn\",\n    \"hdbcli\": \"types-hdbcli\",\n    \"hnswlib\": \"types-hnswlib\",\n    \"html5lib\": \"types-html5lib\",\n    \"httplib2\": \"types-httplib2\",\n    \"hvac\": \"types-hvac\",\n    \"ibm_db\": \"types-ibm-db\",\n    \"icalendar\": \"types-icalendar\",\n    \"import_export\": \"types-django-import-export\",\n    \"inifile\": \"types-inifile\",\n    \"isapi\": \"types-pywin32\",\n    \"jack\": \"types-JACK-Client\",\n    \"jenkins\": \"types-python-jenkins\",\n    \"Jetson\": \"types-Jetson.GPIO\",\n    \"jks\": \"types-pyjks\",\n    \"jmespath\": \"types-jmespath\",\n    \"jose\": \"types-python-jose\",\n    \"jsonschema\": \"types-jsonschema\",\n    \"jwcrypto\": \"types-jwcrypto\",\n    \"keyboard\": \"types-keyboard\",\n    \"ldap3\": \"types-ldap3\",\n    \"lunardate\": \"types-lunardate\",\n    \"lupa\": \"types-lupa\",\n    \"lzstring\": \"types-lzstring\",\n    \"m3u8\": \"types-m3u8\",\n    \"management\": \"types-django-import-export\",\n    \"mmapfile\": \"types-pywin32\",\n    \"mmsystem\": \"types-pywin32\",\n    \"mypy_extensions\": \"types-mypy-extensions\",\n    \"MySQLdb\": \"types-mysqlclient\",\n    \"nanoid\": \"types-nanoid\",\n    \"nanoleafapi\": \"types-nanoleafapi\",\n    \"netaddr\": \"types-netaddr\",\n    \"netifaces\": \"types-netifaces\",\n    \"networkx\": \"types-networkx\",\n    \"nmap\": \"types-python-nmap\",\n    \"ntsecuritycon\": \"types-pywin32\",\n    \"oauthlib\": \"types-oauthlib\",\n    \"objgraph\": \"types-objgraph\",\n    \"odbc\": \"types-pywin32\",\n    \"olefile\": \"types-olefile\",\n    \"openpyxl\": \"types-openpyxl\",\n    \"opentracing\": \"types-opentracing\",\n    \"parsimonious\": \"types-parsimonious\",\n    \"passlib\": \"types-passlib\",\n    \"passpy\": \"types-passpy\",\n    \"peewee\": \"types-peewee\",\n    \"pep8ext_naming\": \"types-pep8-naming\",\n    \"perfmon\": \"types-pywin32\",\n    \"pexpect\": \"types-pexpect\",\n    \"playhouse\": \"types-peewee\",\n    \"pony\": \"types-pony\",\n    \"portpicker\": \"types-portpicker\",\n    \"psutil\": \"types-psutil\",\n    \"psycopg2\": \"types-psycopg2\",\n    \"punq\": \"types-punq\",\n    \"pyasn1\": \"types-pyasn1\",\n    \"pyaudio\": \"types-pyaudio\",\n    \"pyautogui\": \"types-PyAutoGUI\",\n    \"pycocotools\": \"types-pycocotools\",\n    \"pyflakes\": \"types-pyflakes\",\n    \"pygments\": \"types-Pygments\",\n    \"pyi_splash\": \"types-pyinstaller\",\n    \"PyInstaller\": \"types-pyinstaller\",\n    \"pyluach\": \"types-pyluach\",\n    \"pymeeus\": \"types-PyMeeus\",\n    \"pynput\": \"types-pynput\",\n    \"pyperclip\": \"types-pyperclip\",\n    \"pyscreeze\": \"types-PyScreeze\",\n    \"pysftp\": \"types-pysftp\",\n    \"pytest_lazyfixture\": \"types-pytest-lazy-fixture\",\n    \"python_http_client\": \"types-python-http-client\",\n    \"pythoncom\": \"types-pywin32\",\n    \"pythonwin\": \"types-pywin32\",\n    \"pywintypes\": \"types-pywin32\",\n    \"qrbill\": \"types-qrbill\",\n    \"qrcode\": \"types-qrcode\",\n    \"ratelimit\": \"types-ratelimit\",\n    \"regex\": \"types-regex\",\n    \"regutil\": \"types-pywin32\",\n    \"reportlab\": \"types-reportlab\",\n    \"requests_oauthlib\": \"types-requests-oauthlib\",\n    \"rfc3339_validator\": \"types-rfc3339-validator\",\n    \"RPi\": \"types-RPi.GPIO\",\n    \"s2clientprotocol\": \"types-s2clientprotocol\",\n    \"sass\": \"types-libsass\",\n    \"sassutils\": \"types-libsass\",\n    \"seaborn\": \"types-seaborn\",\n    \"send2trash\": \"types-Send2Trash\",\n    \"serial\": \"types-pyserial\",\n    \"servicemanager\": \"types-pywin32\",\n    \"setuptools\": \"types-setuptools\",\n    \"shapely\": \"types-shapely\",\n    \"simple_websocket\": \"types-simple-websocket\",\n    \"slumber\": \"types-slumber\",\n    \"socks\": \"types-PySocks\",\n    \"sockshandler\": \"types-PySocks\",\n    \"sspicon\": \"types-pywin32\",\n    \"str2bool\": \"types-str2bool\",\n    \"tensorflow\": \"types-tensorflow\",\n    \"tgcrypto\": \"types-TgCrypto\",\n    \"timer\": \"types-pywin32\",\n    \"toposort\": \"types-toposort\",\n    \"tqdm\": \"types-tqdm\",\n    \"translationstring\": \"types-translationstring\",\n    \"ttkthemes\": \"types-ttkthemes\",\n    \"tzdata\": \"types-tzdata\",\n    \"unidiff\": \"types-unidiff\",\n    \"untangle\": \"types-untangle\",\n    \"usersettings\": \"types-usersettings\",\n    \"uwsgi\": \"types-uWSGI\",\n    \"uwsgidecorators\": \"types-uWSGI\",\n    \"vobject\": \"types-vobject\",\n    \"watchpoints\": \"types-watchpoints\",\n    \"webencodings\": \"types-webencodings\",\n    \"webob\": \"types-WebOb\",\n    \"whatthepatch\": \"types-whatthepatch\",\n    \"win2kras\": \"types-pywin32\",\n    \"win32\": \"types-pywin32\",\n    \"win32api\": \"types-pywin32\",\n    \"win32clipboard\": \"types-pywin32\",\n    \"win32com\": \"types-pywin32\",\n    \"win32comext\": \"types-pywin32\",\n    \"win32con\": \"types-pywin32\",\n    \"win32console\": \"types-pywin32\",\n    \"win32cred\": \"types-pywin32\",\n    \"win32crypt\": \"types-pywin32\",\n    \"win32cryptcon\": \"types-pywin32\",\n    \"win32event\": \"types-pywin32\",\n    \"win32evtlog\": \"types-pywin32\",\n    \"win32evtlogutil\": \"types-pywin32\",\n    \"win32file\": \"types-pywin32\",\n    \"win32gui_struct\": \"types-pywin32\",\n    \"win32gui\": \"types-pywin32\",\n    \"win32help\": \"types-pywin32\",\n    \"win32inet\": \"types-pywin32\",\n    \"win32inetcon\": \"types-pywin32\",\n    \"win32job\": \"types-pywin32\",\n    \"win32lz\": \"types-pywin32\",\n    \"win32net\": \"types-pywin32\",\n    \"win32netcon\": \"types-pywin32\",\n    \"win32pdh\": \"types-pywin32\",\n    \"win32pdhquery\": \"types-pywin32\",\n    \"win32pipe\": \"types-pywin32\",\n    \"win32print\": \"types-pywin32\",\n    \"win32process\": \"types-pywin32\",\n    \"win32profile\": \"types-pywin32\",\n    \"win32ras\": \"types-pywin32\",\n    \"win32security\": \"types-pywin32\",\n    \"win32service\": \"types-pywin32\",\n    \"win32serviceutil\": \"types-pywin32\",\n    \"win32timezone\": \"types-pywin32\",\n    \"win32trace\": \"types-pywin32\",\n    \"win32transaction\": \"types-pywin32\",\n    \"win32ts\": \"types-pywin32\",\n    \"win32ui\": \"types-pywin32\",\n    \"win32uiole\": \"types-pywin32\",\n    \"win32verstamp\": \"types-pywin32\",\n    \"win32wnet\": \"types-pywin32\",\n    \"winerror\": \"types-pywin32\",\n    \"winioctlcon\": \"types-pywin32\",\n    \"winnt\": \"types-pywin32\",\n    \"winperf\": \"types-pywin32\",\n    \"winxpgui\": \"types-pywin32\",\n    \"winxptheme\": \"types-pywin32\",\n    \"workalendar\": \"types-workalendar\",\n    \"wtforms\": \"types-WTForms\",\n    \"wurlitzer\": \"types-wurlitzer\",\n    \"www_authenticate\": \"types-www-authenticate\",\n    \"xdg\": \"types-pyxdg\",\n    \"xdgenvpy\": \"types-xdgenvpy\",\n    \"Xlib\": \"types-python-xlib\",\n    \"xlrd\": \"types-xlrd\",\n    \"xmldiff\": \"types-xmldiff\",\n    \"xmltodict\": \"types-xmltodict\",\n    \"yt_dlp\": \"types-yt-dlp\",\n    \"zstd\": \"types-zstd\",\n    \"zxcvbn\": \"types-zxcvbn\",\n    # Stub packages that are not from typeshed\n    # Since these can be installed automatically via --install-types, we have a high trust bar\n    # for additions here\n    \"pandas\": \"pandas-stubs\",  # https://github.com/pandas-dev/pandas-stubs\n    \"lxml\": \"lxml-stubs\",  # https://github.com/lxml/lxml-stubs\n    \"scipy\": \"scipy-stubs\",  # https://github.com/scipy/scipy-stubs\n}\n\n\nnon_bundled_packages_namespace: dict[str, dict[str, str]] = {\n    \"backports\": {\"backports.ssl_match_hostname\": \"types-backports.ssl_match_hostname\"},\n    \"google\": {\"google.cloud.ndb\": \"types-google-cloud-ndb\", \"google.protobuf\": \"types-protobuf\"},\n    \"paho\": {\"paho.mqtt\": \"types-paho-mqtt\"},\n}\n"
  },
  {
    "path": "mypy/stubtest.py",
    "content": "\"\"\"Tests for stubs.\n\nVerify that various things in stubs are consistent with how things behave at runtime.\n\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport collections.abc\nimport copy\nimport enum\nimport functools\nimport importlib\nimport inspect\nimport os\nimport pkgutil\nimport re\nimport struct\nimport symtable\nimport sys\nimport traceback\nimport types\nimport typing\nimport typing_extensions\nimport warnings\nfrom collections import defaultdict\nfrom collections.abc import Iterator\nfrom contextlib import redirect_stderr, redirect_stdout\nfrom functools import singledispatch\nfrom pathlib import Path\nfrom typing import Any, Final, Generic, TypeVar, Union, get_origin\nfrom typing_extensions import is_typeddict\n\nimport mypy.build\nimport mypy.checkexpr\nimport mypy.erasetype\nimport mypy.modulefinder\nimport mypy.nodes\nimport mypy.state\nimport mypy.subtypes\nimport mypy.types\nimport mypy.version\nfrom mypy import nodes\nfrom mypy.config_parser import parse_config_file\nfrom mypy.evalexpr import UNKNOWN, evaluate_expression\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.options import Options\nfrom mypy.util import FancyFormatter, bytes_to_human_readable_repr, is_dunder, plural_s\n\n\nclass Missing:\n    \"\"\"Marker object for things that are missing (from a stub or the runtime).\"\"\"\n\n    def __repr__(self) -> str:\n        return \"MISSING\"\n\n\nMISSING: Final = Missing()\n\nT = TypeVar(\"T\")\nMaybeMissing: typing_extensions.TypeAlias = T | Missing\n\n\nclass Unrepresentable:\n    \"\"\"Marker object for unrepresentable parameter defaults.\"\"\"\n\n    def __repr__(self) -> str:\n        return \"<unrepresentable>\"\n\n\nUNREPRESENTABLE: Final = Unrepresentable()\n\n\n_formatter: Final = FancyFormatter(sys.stdout, sys.stderr, False)\n\n\ndef _style(message: str, **kwargs: Any) -> str:\n    \"\"\"Wrapper around mypy.util for fancy formatting.\"\"\"\n    kwargs.setdefault(\"color\", \"none\")\n    return _formatter.style(message, **kwargs)\n\n\ndef _truncate(message: str, length: int) -> str:\n    if len(message) > length:\n        return message[: length - 3] + \"...\"\n    return message\n\n\nclass StubtestFailure(Exception):\n    pass\n\n\nclass Error:\n    def __init__(\n        self,\n        object_path: list[str],\n        message: str,\n        stub_object: MaybeMissing[nodes.Node],\n        runtime_object: MaybeMissing[Any],\n        *,\n        stub_desc: str | None = None,\n        runtime_desc: str | None = None,\n    ) -> None:\n        \"\"\"Represents an error found by stubtest.\n\n        :param object_path: Location of the object with the error,\n            e.g. ``[\"module\", \"Class\", \"method\"]``\n        :param message: Error message\n        :param stub_object: The mypy node representing the stub\n        :param runtime_object: Actual object obtained from the runtime\n        :param stub_desc: Specialised description for the stub object, should you wish\n        :param runtime_desc: Specialised description for the runtime object, should you wish\n\n        \"\"\"\n        self.object_path = object_path\n        self.object_desc = \".\".join(object_path)\n        self.message = message\n        self.stub_object = stub_object\n        self.runtime_object = runtime_object\n        self.stub_desc = stub_desc or str(getattr(stub_object, \"type\", stub_object))\n\n        if runtime_desc is None:\n            runtime_sig = safe_inspect_signature(runtime_object)\n            if runtime_sig is None:\n                self.runtime_desc = _truncate(repr(runtime_object), 100)\n            else:\n                runtime_is_async = inspect.iscoroutinefunction(runtime_object)\n                description = describe_runtime_callable(runtime_sig, is_async=runtime_is_async)\n                self.runtime_desc = _truncate(description, 100)\n        else:\n            self.runtime_desc = runtime_desc\n\n    def is_missing_stub(self) -> bool:\n        \"\"\"Whether or not the error is for something missing from the stub.\"\"\"\n        return isinstance(self.stub_object, Missing)\n\n    def is_positional_only_related(self) -> bool:\n        \"\"\"Whether or not the error is for something being (or not being) positional-only.\"\"\"\n        # TODO: This is hacky, use error codes or something more resilient\n        return \"should be positional\" in self.message\n\n    def is_disjoint_base_related(self) -> bool:\n        \"\"\"Whether or not the error is related to @disjoint_base.\"\"\"\n        # TODO: This is hacky, use error codes or something more resilient\n        return \"@disjoint_base\" in self.message\n\n    def get_description(self, concise: bool = False) -> str:\n        \"\"\"Returns a description of the error.\n\n        :param concise: Whether to return a concise, one-line description\n\n        \"\"\"\n        if concise:\n            return _style(self.object_desc, bold=True) + \" \" + self.message\n\n        stub_line = None\n        stub_file = None\n        if not isinstance(self.stub_object, Missing):\n            stub_line = self.stub_object.line\n        stub_node = get_stub(self.object_path[0])\n        if stub_node is not None:\n            stub_file = stub_node.path or None\n\n        stub_loc_str = \"\"\n        if stub_file:\n            stub_loc_str += f\" in file {Path(stub_file)}\"\n        if stub_line:\n            stub_loc_str += f\"{':' if stub_file else ' at line '}{stub_line}\"\n\n        runtime_line = None\n        runtime_file = None\n        if not isinstance(self.runtime_object, Missing):\n            try:\n                runtime_line = inspect.getsourcelines(self.runtime_object)[1]\n            except (OSError, TypeError, SyntaxError):\n                pass\n            try:\n                runtime_file = inspect.getsourcefile(self.runtime_object)\n            except TypeError:\n                pass\n\n        runtime_loc_str = \"\"\n        if runtime_file:\n            runtime_loc_str += f\" in file {Path(runtime_file)}\"\n        if runtime_line:\n            runtime_loc_str += f\"{':' if runtime_file else ' at line '}{runtime_line}\"\n\n        output = [\n            _style(\"error: \", color=\"red\", bold=True),\n            _style(self.object_desc, bold=True),\n            \" \",\n            self.message,\n            \"\\n\",\n            \"Stub:\",\n            _style(stub_loc_str, dim=True),\n            \"\\n\",\n            _style(self.stub_desc + \"\\n\", color=\"blue\", dim=True),\n            \"Runtime:\",\n            _style(runtime_loc_str, dim=True),\n            \"\\n\",\n            _style(self.runtime_desc + \"\\n\", color=\"blue\", dim=True),\n        ]\n        return \"\".join(output)\n\n\n# ====================\n# Core logic\n# ====================\n\n\ndef silent_import_module(module_name: str) -> types.ModuleType:\n    with open(os.devnull, \"w\") as devnull:\n        with warnings.catch_warnings(), redirect_stdout(devnull), redirect_stderr(devnull):\n            warnings.simplefilter(\"ignore\")\n            runtime = importlib.import_module(module_name)\n            # Also run the equivalent of `from module import *`\n            # This could have the additional effect of loading not-yet-loaded submodules\n            # mentioned in __all__\n            __import__(module_name, fromlist=[\"*\"])\n    return runtime\n\n\ndef test_module(module_name: str) -> Iterator[Error]:\n    \"\"\"Tests a given module's stub against introspecting it at runtime.\n\n    Requires the stub to have been built already, accomplished by a call to ``build_stubs``.\n\n    :param module_name: The module to test\n\n    \"\"\"\n    stub = get_stub(module_name)\n    if stub is None:\n        if not is_probably_private(module_name.split(\".\")[-1]):\n            runtime_desc = repr(sys.modules[module_name]) if module_name in sys.modules else \"N/A\"\n            yield Error(\n                [module_name], \"failed to find stubs\", MISSING, None, runtime_desc=runtime_desc\n            )\n        return\n\n    try:\n        runtime = silent_import_module(module_name)\n    except KeyboardInterrupt:\n        raise\n    except BaseException as e:\n        note = \"\"\n        if isinstance(e, ModuleNotFoundError):\n            note = \" Maybe install the runtime package or alter PYTHONPATH?\"\n        yield Error(\n            [module_name], f\"failed to import.{note} {type(e).__name__}: {e}\", stub, MISSING\n        )\n        return\n\n    with warnings.catch_warnings():\n        warnings.simplefilter(\"ignore\")\n        try:\n            yield from verify(stub, runtime, [module_name])\n        except Exception as e:\n            bottom_frame = list(traceback.walk_tb(e.__traceback__))[-1][0]\n            bottom_module = bottom_frame.f_globals.get(\"__name__\", \"\")\n            # Pass on any errors originating from stubtest or mypy\n            # These can occur expectedly, e.g. StubtestFailure\n            if bottom_module == \"__main__\" or bottom_module.split(\".\")[0] == \"mypy\":\n                raise\n            yield Error(\n                [module_name],\n                f\"encountered unexpected error, {type(e).__name__}: {e}\",\n                stub,\n                runtime,\n                stub_desc=\"N/A\",\n                runtime_desc=(\n                    \"This is most likely the fault of something very dynamic in your library. \"\n                    \"It's also possible this is a bug in stubtest.\\nIf in doubt, please \"\n                    \"open an issue at https://github.com/python/mypy\\n\\n\"\n                    + traceback.format_exc().strip()\n                ),\n            )\n\n\n@singledispatch\ndef verify(\n    stub: MaybeMissing[nodes.Node], runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\n    \"\"\"Entry point for comparing a stub to a runtime object.\n\n    We use single dispatch based on the type of ``stub``.\n\n    :param stub: The mypy node representing a part of the stub\n    :param runtime: The runtime object corresponding to ``stub``\n\n    \"\"\"\n    yield Error(object_path, \"is an unknown mypy node\", stub, runtime)\n\n\ndef _verify_exported_names(\n    object_path: list[str], stub: nodes.MypyFile, runtime_all_as_set: set[str]\n) -> Iterator[Error]:\n    # note that this includes the case the stub simply defines `__all__: list[str]`\n    assert \"__all__\" in stub.names\n    public_names_in_stub = {m for m, o in stub.names.items() if o.module_public}\n    names_in_stub_not_runtime = sorted(public_names_in_stub - runtime_all_as_set)\n    names_in_runtime_not_stub = sorted(runtime_all_as_set - public_names_in_stub)\n    if not (names_in_runtime_not_stub or names_in_stub_not_runtime):\n        return\n    yield Error(\n        object_path + [\"__all__\"],\n        (\n            \"names exported from the stub do not correspond to the names exported at runtime. \"\n            \"This is probably due to things being missing from the stub or an inaccurate `__all__` in the stub\"\n        ),\n        # Pass in MISSING instead of the stub and runtime objects, as the line numbers aren't very\n        # relevant here, and it makes for a prettier error message\n        # This means this error will be ignored when using `--ignore-missing-stub`, which is\n        # desirable in at least the `names_in_runtime_not_stub` case\n        stub_object=MISSING,\n        runtime_object=MISSING,\n        stub_desc=(f\"Names exported in the stub but not at runtime: {names_in_stub_not_runtime}\"),\n        runtime_desc=(\n            f\"Names exported at runtime but not in the stub: {names_in_runtime_not_stub}\"\n        ),\n    )\n\n\n@functools.lru_cache\ndef _module_symbol_table(runtime: types.ModuleType) -> symtable.SymbolTable | None:\n    \"\"\"Retrieve the symbol table for the module (or None on failure).\n\n    1) Use inspect to retrieve the source code of the module\n    2) Use symtable to parse the source (and use what symtable knows for its purposes)\n    \"\"\"\n    try:\n        source = inspect.getsource(runtime)\n    except (OSError, TypeError, SyntaxError):\n        return None\n\n    try:\n        return symtable.symtable(source, runtime.__name__, \"exec\")\n    except SyntaxError:\n        return None\n\n\n@verify.register(nodes.MypyFile)\ndef verify_mypyfile(\n    stub: nodes.MypyFile, runtime: MaybeMissing[types.ModuleType], object_path: list[str]\n) -> Iterator[Error]:\n    if isinstance(runtime, Missing):\n        yield Error(object_path, \"is not present at runtime\", stub, runtime)\n        return\n    if not isinstance(runtime, types.ModuleType):\n        # Can possibly happen:\n        yield Error(object_path, \"is not a module\", stub, runtime)  # type: ignore[unreachable]\n        return\n\n    runtime_all_as_set: set[str] | None\n\n    if hasattr(runtime, \"__all__\"):\n        runtime_all_as_set = set(runtime.__all__)\n        if \"__all__\" in stub.names:\n            # Only verify the contents of the stub's __all__\n            # if the stub actually defines __all__\n            yield from _verify_exported_names(object_path, stub, runtime_all_as_set)\n        else:\n            yield Error(object_path + [\"__all__\"], \"is not present in stub\", MISSING, runtime)\n    else:\n        runtime_all_as_set = None\n\n    # Check things in the stub\n    to_check = {\n        m\n        for m, o in stub.names.items()\n        if not o.module_hidden and (not is_probably_private(m) or hasattr(runtime, m))\n    }\n\n    def _belongs_to_runtime(r: types.ModuleType, attr: str) -> bool:\n        \"\"\"Heuristics to determine whether a name originates from another module.\"\"\"\n        obj = getattr(r, attr)\n        if isinstance(obj, types.ModuleType):\n            return False\n\n        symbol_table = _module_symbol_table(r)\n        if symbol_table is not None:\n            try:\n                symbol = symbol_table.lookup(attr)\n            except KeyError:\n                pass\n            else:\n                if symbol.is_imported():\n                    # symtable says we got this from another module\n                    return False\n                # But we can't just return True here, because symtable doesn't know about symbols\n                # that come from `from module import *`\n                if symbol.is_assigned():\n                    # symtable knows we assigned this symbol in the module\n                    return True\n\n        # The __module__ attribute is unreliable for anything except functions and classes,\n        # but it's our best guess at this point\n        try:\n            obj_mod = obj.__module__\n        except Exception:\n            pass\n        else:\n            if isinstance(obj_mod, str):\n                return bool(obj_mod == r.__name__)\n        return True\n\n    runtime_public_contents = (\n        runtime_all_as_set\n        if runtime_all_as_set is not None\n        else {\n            m\n            for m in dir(runtime)\n            if not is_probably_private(m)\n            # Filter out objects that originate from other modules (best effort). Note that in the\n            # absence of __all__, we don't have a way to detect explicit / intentional re-exports\n            # at runtime\n            and _belongs_to_runtime(runtime, m)\n        }\n    )\n    # Check all things declared in module's __all__, falling back to our best guess\n    to_check.update(runtime_public_contents)\n    to_check.difference_update(IGNORED_MODULE_DUNDERS)\n\n    for entry in sorted(to_check):\n        stub_entry = stub.names[entry].node if entry in stub.names else MISSING\n        if entry in stub.names:\n            if xref := stub.names[entry].cross_ref:\n                orig_module = xref.rsplit(\".\", 1)[0]\n            elif isinstance(stub_entry, nodes.SymbolNode) and (name := stub_entry.fullname):\n                orig_module = name.rsplit(\".\", 1)[0]\n            else:\n                orig_module = None\n\n            if orig_module and orig_module != stub.fullname and orig_module in _all_stubs:\n                # Skip re-exported names whose defining module will be checked separately.\n                continue\n\n        if isinstance(stub_entry, nodes.MypyFile):\n            # Don't recursively check exported modules, since that leads to infinite recursion\n            continue\n        assert stub_entry is not None\n        try:\n            runtime_entry = getattr(runtime, entry, MISSING)\n        except Exception:\n            # Catch all exceptions in case the runtime raises an unexpected exception\n            # from __getattr__ or similar.\n            continue\n        yield from verify(stub_entry, runtime_entry, object_path + [entry])\n\n\ndef _verify_final(\n    stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str]\n) -> Iterator[Error]:\n    try:\n\n        class SubClass(runtime):  # type: ignore[misc]\n            pass\n\n    except TypeError:\n        # Enum classes are implicitly @final\n        if not stub.is_final and not issubclass(runtime, enum.Enum):\n            yield Error(\n                object_path,\n                \"cannot be subclassed at runtime, but isn't marked with @final in the stub\",\n                stub,\n                runtime,\n                stub_desc=repr(stub),\n            )\n    except Exception:\n        # The class probably wants its subclasses to do something special.\n        # Examples: ctypes.Array, ctypes._SimpleCData\n        pass\n\n    # Runtime class might be annotated with `@final`:\n    try:\n        runtime_final = getattr(runtime, \"__final__\", False)\n    except Exception:\n        runtime_final = False\n\n    if runtime_final and not stub.is_final:\n        yield Error(\n            object_path,\n            \"has `__final__` attribute, but isn't marked with @final in the stub\",\n            stub,\n            runtime,\n            stub_desc=repr(stub),\n        )\n\n\nSIZEOF_PYOBJECT = struct.calcsize(\"P\")\n\n\ndef _shape_differs(t1: type[object], t2: type[object]) -> bool:\n    \"\"\"Check whether two types differ in shape.\n\n    Mirrors the shape_differs() function in typeobject.c in CPython.\"\"\"\n    if sys.version_info >= (3, 12):\n        return t1.__basicsize__ != t2.__basicsize__ or t1.__itemsize__ != t2.__itemsize__\n    else:\n        # CPython had more complicated logic before 3.12:\n        # https://github.com/python/cpython/blob/f3c6f882cddc8dc30320d2e73edf019e201394fc/Objects/typeobject.c#L2224\n        # We attempt to mirror it here well enough to support the most common cases.\n        if t1.__itemsize__ or t2.__itemsize__:\n            return t1.__basicsize__ != t2.__basicsize__ or t1.__itemsize__ != t2.__itemsize__\n        t_size = t1.__basicsize__\n        if not t2.__weakrefoffset__ and t1.__weakrefoffset__ + SIZEOF_PYOBJECT == t_size:\n            t_size -= SIZEOF_PYOBJECT\n        if not t2.__dictoffset__ and t1.__dictoffset__ + SIZEOF_PYOBJECT == t_size:\n            t_size -= SIZEOF_PYOBJECT\n        if not t2.__weakrefoffset__ and t2.__weakrefoffset__ == t_size:\n            t_size -= SIZEOF_PYOBJECT\n        return t_size != t2.__basicsize__\n\n\ndef _is_disjoint_base(typ: type[object]) -> bool:\n    \"\"\"Return whether a type is a disjoint base at runtime, mirroring CPython's logic in typeobject.c.\n\n    See PEP 800.\"\"\"\n    if typ is object:\n        return True\n    base = typ.__base__\n    assert base is not None, f\"Type {typ} has no base\"\n    return _shape_differs(typ, base)\n\n\ndef _verify_disjoint_base(\n    stub: nodes.TypeInfo, runtime: type[object], object_path: list[str]\n) -> Iterator[Error]:\n    is_disjoint_runtime = _is_disjoint_base(runtime)\n    # Don't complain about missing @disjoint_base if there are __slots__, because\n    # in that case we can infer that it's a disjoint base.\n    if (\n        is_disjoint_runtime\n        and not stub.is_disjoint_base\n        and not runtime.__dict__.get(\"__slots__\")\n        and not stub.is_final\n        and not (stub.is_enum and stub.enum_members)\n    ):\n        yield Error(\n            object_path,\n            \"is a disjoint base at runtime, but isn't marked with @disjoint_base in the stub\",\n            stub,\n            runtime,\n            stub_desc=repr(stub),\n        )\n    elif stub.is_disjoint_base:\n        if not is_disjoint_runtime:\n            yield Error(\n                object_path,\n                \"is marked with @disjoint_base in the stub, but isn't a disjoint base at runtime\",\n                stub,\n                runtime,\n                stub_desc=repr(stub),\n            )\n        if runtime.__dict__.get(\"__slots__\"):\n            yield Error(\n                object_path,\n                \"is marked as @disjoint_base, but also has slots; add __slots__ instead\",\n                stub,\n                runtime,\n                stub_desc=repr(stub),\n            )\n        elif stub.is_final:\n            yield Error(\n                object_path,\n                \"is marked as @disjoint_base, but also marked as @final; remove @disjoint_base\",\n                stub,\n                runtime,\n                stub_desc=repr(stub),\n            )\n        elif stub.is_enum and stub.enum_members:\n            yield Error(\n                object_path,\n                \"is marked as @disjoint_base, but is an enum with members, which is implicitly final; \"\n                \"remove @disjoint_base\",\n                stub,\n                runtime,\n                stub_desc=repr(stub),\n            )\n\n\ndef _verify_metaclass(\n    stub: nodes.TypeInfo, runtime: type[Any], object_path: list[str], *, is_runtime_typeddict: bool\n) -> Iterator[Error]:\n    # We exclude protocols, because of how complex their implementation is in different versions of\n    # python. Enums are also hard, as are runtime TypedDicts; ignoring.\n    # TODO: check that metaclasses are identical?\n    if not stub.is_protocol and not stub.is_enum and not is_runtime_typeddict:\n        runtime_metaclass = type(runtime)\n        if runtime_metaclass is not type and stub.metaclass_type is None:\n            # This means that runtime has a custom metaclass, but a stub does not.\n            yield Error(\n                object_path,\n                \"is inconsistent, metaclass differs\",\n                stub,\n                runtime,\n                stub_desc=\"N/A\",\n                runtime_desc=f\"{runtime_metaclass}\",\n            )\n        elif (\n            runtime_metaclass is type\n            and stub.metaclass_type is not None\n            # We ignore extra `ABCMeta` metaclass on stubs, this might be typing hack.\n            # We also ignore `builtins.type` metaclass as an implementation detail in mypy.\n            and not mypy.types.is_named_instance(\n                stub.metaclass_type, (\"abc.ABCMeta\", \"builtins.type\")\n            )\n        ):\n            # This means that our stub has a metaclass that is not present at runtime.\n            yield Error(\n                object_path,\n                \"metaclass mismatch\",\n                stub,\n                runtime,\n                stub_desc=f\"{stub.metaclass_type.type.fullname}\",\n                runtime_desc=\"N/A\",\n            )\n\n\n@verify.register(nodes.TypeInfo)\ndef verify_typeinfo(\n    stub: nodes.TypeInfo,\n    runtime: MaybeMissing[type[Any]],\n    object_path: list[str],\n    *,\n    is_alias_target: bool = False,\n) -> Iterator[Error]:\n    if stub.is_type_check_only and not is_alias_target:\n        # This type only exists in stubs, we only check that the runtime part\n        # is missing. Other checks are not required.\n        if not isinstance(runtime, Missing):\n            yield Error(\n                object_path,\n                'is marked as \"@type_check_only\", but also exists at runtime',\n                stub,\n                runtime,\n                stub_desc=repr(stub),\n            )\n        return\n\n    if isinstance(runtime, Missing):\n        yield Error(object_path, \"is not present at runtime\", stub, runtime, stub_desc=repr(stub))\n        return\n    if not isinstance(runtime, type):\n        # Yes, some runtime objects can be not types, no way to tell mypy about that.\n        yield Error(object_path, \"is not a type\", stub, runtime, stub_desc=repr(stub))  # type: ignore[unreachable]\n        return\n\n    yield from _verify_final(stub, runtime, object_path)\n    yield from _verify_disjoint_base(stub, runtime, object_path)\n    is_runtime_typeddict = stub.typeddict_type is not None and is_typeddict(runtime)\n    yield from _verify_metaclass(\n        stub, runtime, object_path, is_runtime_typeddict=is_runtime_typeddict\n    )\n\n    # Check everything already defined on the stub class itself (i.e. not inherited)\n    #\n    # Filter out non-identifier names, as these are (hopefully always?) whacky/fictional things\n    # (like __mypy-replace or __mypy-post_init, etc.) that don't exist at runtime,\n    # and exist purely for internal mypy reasons\n    to_check = {name for name in stub.names if name.isidentifier()}\n    # Check all public things on the runtime class\n    to_check.update(\n        m for m in vars(runtime) if not is_probably_private(m) and m not in IGNORABLE_CLASS_DUNDERS\n    )\n    # Special-case the __init__ method for Protocols and the __new__ method for TypedDicts\n    #\n    # TODO: On Python <3.11, __init__ methods on Protocol classes\n    # are silently discarded and replaced.\n    # However, this is not the case on Python 3.11+.\n    # Ideally, we'd figure out a good way of validating Protocol __init__ methods on 3.11+.\n    if stub.is_protocol:\n        to_check.discard(\"__init__\")\n    if is_runtime_typeddict:\n        to_check.discard(\"__new__\")\n\n    for entry in sorted(to_check):\n        mangled_entry = entry\n        if entry.startswith(\"__\") and not entry.endswith(\"__\"):\n            mangled_entry = f\"_{stub.name.lstrip('_')}{entry}\"\n        stub_to_verify = next((t.names[entry].node for t in stub.mro if entry in t.names), MISSING)\n        assert stub_to_verify is not None\n        try:\n            try:\n                runtime_attr = getattr(runtime, mangled_entry)\n            except AttributeError:\n                runtime_attr = inspect.getattr_static(runtime, mangled_entry, MISSING)\n        except Exception:\n            # Catch all exceptions in case the runtime raises an unexpected exception\n            # from __getattr__ or similar.\n            continue\n\n        # If it came from the metaclass, consider the runtime_attr to be MISSING\n        # for a more accurate message\n        if (\n            runtime_attr is not MISSING\n            and type(runtime) is not runtime\n            and getattr(runtime_attr, \"__objclass__\", None) is type(runtime)\n        ):\n            runtime_attr = MISSING\n\n        # __setattr__ and __delattr__ on object are a special case,\n        # so if we only have these methods inherited from there, pretend that\n        # we don't have them. See python/typeshed#7385.\n        if (\n            entry in (\"__setattr__\", \"__delattr__\")\n            and runtime_attr is not MISSING\n            and runtime is not object\n            and getattr(runtime_attr, \"__objclass__\", None) is object\n        ):\n            runtime_attr = MISSING\n\n        # Do not error for an object missing from the stub\n        # If the runtime object is a types.WrapperDescriptorType object\n        # and has a non-special dunder name.\n        # The vast majority of these are false positives.\n        if not (\n            isinstance(stub_to_verify, Missing)\n            and isinstance(runtime_attr, types.WrapperDescriptorType)\n            and is_dunder(mangled_entry, exclude_special=True)\n        ):\n            yield from verify(stub_to_verify, runtime_attr, object_path + [entry])\n\n\ndef _static_lookup_runtime(object_path: list[str]) -> MaybeMissing[Any]:\n    static_runtime = importlib.import_module(object_path[0])\n    for entry in object_path[1:]:\n        try:\n            static_runtime = inspect.getattr_static(static_runtime, entry)\n        except AttributeError:\n            # This can happen with mangled names, ignore for now.\n            # TODO: pass more information about ancestors of nodes/objects to verify, so we don't\n            # have to do this hacky lookup. Would be useful in several places.\n            return MISSING\n    return static_runtime\n\n\ndef _verify_static_class_methods(\n    stub: nodes.FuncBase, runtime: Any, static_runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[str]:\n    if stub.name in (\"__new__\", \"__init_subclass__\", \"__class_getitem__\"):\n        # Special cased by Python, so don't bother checking\n        return\n    if inspect.isbuiltin(runtime):\n        # The isinstance checks don't work reliably for builtins, e.g. datetime.datetime.now, so do\n        # something a little hacky that seems to work well\n        probably_class_method = isinstance(getattr(runtime, \"__self__\", None), type)\n        if probably_class_method and not stub.is_class:\n            yield \"runtime is a classmethod but stub is not\"\n        if not probably_class_method and stub.is_class:\n            yield \"stub is a classmethod but runtime is not\"\n        return\n\n    if static_runtime is MISSING:\n        return\n\n    if isinstance(static_runtime, classmethod) and not stub.is_class:\n        yield \"runtime is a classmethod but stub is not\"\n    if not isinstance(static_runtime, classmethod) and stub.is_class:\n        yield \"stub is a classmethod but runtime is not\"\n    if isinstance(static_runtime, staticmethod) and not stub.is_static:\n        yield \"runtime is a staticmethod but stub is not\"\n    if not isinstance(static_runtime, staticmethod) and stub.is_static:\n        yield \"stub is a staticmethod but runtime is not\"\n\n\ndef _verify_arg_name(\n    stub_arg: nodes.Argument, runtime_arg: inspect.Parameter, function_name: str\n) -> Iterator[str]:\n    \"\"\"Checks whether argument names match.\"\"\"\n    # Ignore exact names for most dunder methods\n    if is_dunder(function_name, exclude_special=True):\n        return\n\n    if (\n        stub_arg.variable.name == runtime_arg.name\n        or stub_arg.variable.name.removeprefix(\"__\") == runtime_arg.name\n    ):\n        return\n\n    nonspecific_names = {\"object\", \"args\"}\n    if runtime_arg.name in nonspecific_names:\n        return\n\n    def names_approx_match(a: str, b: str) -> bool:\n        a = a.strip(\"_\")\n        b = b.strip(\"_\")\n        return a.startswith(b) or b.startswith(a) or len(a) == 1 or len(b) == 1\n\n    # Be more permissive about names matching for positional-only arguments\n    if runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY and names_approx_match(\n        stub_arg.variable.name, runtime_arg.name\n    ):\n        return\n    # This comes up with namedtuples, so ignore\n    if stub_arg.variable.name == \"_self\":\n        return\n    yield (\n        f'stub parameter \"{stub_arg.variable.name}\" '\n        f'differs from runtime parameter \"{runtime_arg.name}\"'\n    )\n\n\ndef _verify_arg_default_value(\n    stub_arg: nodes.Argument, runtime_arg: inspect.Parameter\n) -> Iterator[str]:\n    \"\"\"Checks whether argument default values are compatible.\"\"\"\n    if runtime_arg.default is not inspect.Parameter.empty:\n        if stub_arg.kind.is_required():\n            yield (\n                f'runtime parameter \"{runtime_arg.name}\" '\n                \"has a default value but stub parameter does not\"\n            )\n        else:\n            type_context = stub_arg.variable.type\n            runtime_type = get_mypy_type_of_runtime_value(\n                runtime_arg.default, type_context=type_context\n            )\n\n            # Fallback to the type annotation type if var type is missing. The type annotation\n            # is an UnboundType, but I don't know enough to know what the pros and cons here are.\n            # UnboundTypes have ugly question marks following them, so default to var type.\n            # Note we do this same fallback when constructing signatures in from_overloadedfuncdef\n            stub_type = stub_arg.variable.type or stub_arg.type_annotation\n            if isinstance(stub_type, mypy.types.TypeVarType):\n                stub_type = stub_type.upper_bound\n            if (\n                runtime_type is not None\n                and stub_type is not None\n                # Avoid false positives for marker objects\n                and type(runtime_arg.default) is not object\n                # And ellipsis\n                and runtime_arg.default is not ...\n                and not is_subtype_helper(runtime_type, stub_type)\n            ):\n                yield (\n                    f'runtime parameter \"{runtime_arg.name}\" '\n                    f\"has a default value of type {runtime_type}, \"\n                    f\"which is incompatible with stub parameter type {stub_type}\"\n                )\n            if stub_arg.initializer is not None:\n                stub_default = evaluate_expression(stub_arg.initializer)\n                if (\n                    stub_default is not UNKNOWN\n                    and stub_default is not ...\n                    and runtime_arg.default is not UNREPRESENTABLE\n                ):\n                    defaults_match = True\n                    # We want the types to match exactly, e.g. in case the stub has\n                    # True and the runtime has 1 (or vice versa).\n                    if type(stub_default) is not type(runtime_arg.default):\n                        defaults_match = False\n                    else:\n                        try:\n                            defaults_match = bool(stub_default == runtime_arg.default)\n                        except Exception:\n                            # Exception can be raised in bool dunder method (e.g. numpy arrays)\n                            # At this point, consider the default to be different, it is probably\n                            # too complex to put in a stub anyway.\n                            defaults_match = False\n                    if not defaults_match:\n                        yield (\n                            f'runtime parameter \"{runtime_arg.name}\" '\n                            f\"has a default value of {runtime_arg.default!r}, \"\n                            f\"which is different from stub parameter default {stub_default!r}\"\n                        )\n    else:\n        if stub_arg.kind.is_optional():\n            yield (\n                f'stub parameter \"{stub_arg.variable.name}\" has a default value '\n                f\"but runtime parameter does not\"\n            )\n\n\ndef maybe_strip_cls(name: str, args: list[nodes.Argument]) -> list[nodes.Argument]:\n    if args and name in (\"__init_subclass__\", \"__class_getitem__\"):\n        # These are implicitly classmethods. If the stub chooses not to have @classmethod, we\n        # should remove the cls argument\n        if args[0].variable.name == \"cls\":\n            return args[1:]\n    return args\n\n\nclass Signature(Generic[T]):\n    def __init__(self) -> None:\n        self.pos: list[T] = []\n        self.kwonly: dict[str, T] = {}\n        self.varpos: T | None = None\n        self.varkw: T | None = None\n\n    def __str__(self) -> str:\n        def get_name(arg: Any) -> str:\n            if isinstance(arg, inspect.Parameter):\n                return arg.name\n            if isinstance(arg, nodes.Argument):\n                return arg.variable.name\n            raise AssertionError\n\n        def get_type(arg: Any) -> str | None:\n            if isinstance(arg, inspect.Parameter):\n                return None\n            if isinstance(arg, nodes.Argument):\n                return str(arg.variable.type or arg.type_annotation)\n            raise AssertionError\n\n        def has_default(arg: Any) -> bool:\n            if isinstance(arg, inspect.Parameter):\n                return arg.default is not inspect.Parameter.empty\n            if isinstance(arg, nodes.Argument):\n                return arg.kind.is_optional()\n            raise AssertionError\n\n        def get_desc(arg: Any) -> str:\n            arg_type = get_type(arg)\n            return (\n                get_name(arg)\n                + (f\": {arg_type}\" if arg_type else \"\")\n                + (\" = ...\" if has_default(arg) else \"\")\n            )\n\n        kw_only = sorted(self.kwonly.values(), key=lambda a: (has_default(a), get_name(a)))\n        ret = \"def (\"\n        ret += \", \".join(\n            [get_desc(arg) for arg in self.pos]\n            + ([\"*\" + get_name(self.varpos)] if self.varpos else ([\"*\"] if self.kwonly else []))\n            + [get_desc(arg) for arg in kw_only]\n            + ([\"**\" + get_name(self.varkw)] if self.varkw else [])\n        )\n        ret += \")\"\n        return ret\n\n    @staticmethod\n    def from_funcitem(stub: nodes.FuncItem) -> Signature[nodes.Argument]:\n        stub_sig: Signature[nodes.Argument] = Signature()\n        stub_args = maybe_strip_cls(stub.name, stub.arguments)\n        for stub_arg in stub_args:\n            if stub_arg.kind.is_positional():\n                stub_sig.pos.append(stub_arg)\n            elif stub_arg.kind.is_named():\n                stub_sig.kwonly[stub_arg.variable.name] = stub_arg\n            elif stub_arg.kind == nodes.ARG_STAR:\n                stub_sig.varpos = stub_arg\n            elif stub_arg.kind == nodes.ARG_STAR2:\n                stub_sig.varkw = stub_arg\n            else:\n                raise AssertionError\n        return stub_sig\n\n    @staticmethod\n    def from_inspect_signature(signature: inspect.Signature) -> Signature[inspect.Parameter]:\n        runtime_sig: Signature[inspect.Parameter] = Signature()\n        for runtime_arg in signature.parameters.values():\n            if runtime_arg.kind in (\n                inspect.Parameter.POSITIONAL_ONLY,\n                inspect.Parameter.POSITIONAL_OR_KEYWORD,\n            ):\n                runtime_sig.pos.append(runtime_arg)\n            elif runtime_arg.kind == inspect.Parameter.KEYWORD_ONLY:\n                runtime_sig.kwonly[runtime_arg.name] = runtime_arg\n            elif runtime_arg.kind == inspect.Parameter.VAR_POSITIONAL:\n                runtime_sig.varpos = runtime_arg\n            elif runtime_arg.kind == inspect.Parameter.VAR_KEYWORD:\n                runtime_sig.varkw = runtime_arg\n            else:\n                raise AssertionError\n        return runtime_sig\n\n    @staticmethod\n    def from_overloadedfuncdef(stub: nodes.OverloadedFuncDef) -> Signature[nodes.Argument]:\n        \"\"\"Returns a Signature from an OverloadedFuncDef.\n\n        If life were simple, to verify_overloadedfuncdef, we'd just verify_funcitem for each of its\n        items. Unfortunately, life isn't simple and overloads are pretty deceitful. So instead, we\n        try and combine the overload's items into a single signature that is compatible with any\n        lies it might try to tell.\n\n        \"\"\"\n        # For most dunder methods, just assume all args are positional-only\n        assume_positional_only = is_dunder(stub.name, exclude_special=True)\n\n        is_arg_pos_only: defaultdict[str, set[bool]] = defaultdict(set)\n        for func in map(_resolve_funcitem_from_decorator, stub.items):\n            assert func is not None, f\"Failed to resolve decorated overload of {stub.fullname!r}\"\n            args = maybe_strip_cls(stub.name, func.arguments)\n            for index, arg in enumerate(args):\n                if (\n                    arg.variable.name.startswith(\"__\")\n                    or arg.pos_only\n                    or assume_positional_only\n                    or arg.variable.name.strip(\"_\") == \"self\"\n                    or (index == 0 and arg.variable.name.strip(\"_\") == \"cls\")\n                ):\n                    is_arg_pos_only[arg.variable.name].add(True)\n                else:\n                    is_arg_pos_only[arg.variable.name].add(False)\n\n        all_args: dict[str, list[tuple[nodes.Argument, int]]] = {}\n        for func in map(_resolve_funcitem_from_decorator, stub.items):\n            assert func is not None, f\"Failed to resolve decorated overload of {stub.fullname!r}\"\n            args = maybe_strip_cls(stub.name, func.arguments)\n            for index, arg in enumerate(args):\n                # For positional-only args, we allow overloads to have different names for the same\n                # argument. To accomplish this, we just make up a fake index-based name.\n                # We can only use the index-based name if the argument is always\n                # positional only. Sometimes overloads have an arg as positional-only\n                # in some but not all branches of the overload.\n                name = arg.variable.name\n                if is_arg_pos_only[name] == {True}:\n                    name = f\"__{index}\"\n\n                all_args.setdefault(name, []).append((arg, index))\n\n        def get_position(arg_name: str) -> int:\n            # We just need this to return the positional args in the correct order.\n            return max(index for _, index in all_args[arg_name])\n\n        def get_type(arg_name: str) -> mypy.types.ProperType:\n            with mypy.state.state.strict_optional_set(True):\n                all_types = [\n                    arg.variable.type or arg.type_annotation for arg, _ in all_args[arg_name]\n                ]\n                return mypy.typeops.make_simplified_union([t for t in all_types if t])\n\n        def get_kind(arg_name: str) -> nodes.ArgKind:\n            kinds = {arg.kind for arg, _ in all_args[arg_name]}\n            if nodes.ARG_STAR in kinds:\n                return nodes.ARG_STAR\n            if nodes.ARG_STAR2 in kinds:\n                return nodes.ARG_STAR2\n            # The logic here is based on two tenets:\n            # 1) If an arg is ever optional (or unspecified), it is optional\n            # 2) If an arg is ever positional, it is positional\n            is_opt = (\n                len(all_args[arg_name]) < len(stub.items)\n                or nodes.ARG_OPT in kinds\n                or nodes.ARG_NAMED_OPT in kinds\n            )\n            is_pos = nodes.ARG_OPT in kinds or nodes.ARG_POS in kinds\n            if is_opt:\n                return nodes.ARG_OPT if is_pos else nodes.ARG_NAMED_OPT\n            return nodes.ARG_POS if is_pos else nodes.ARG_NAMED\n\n        sig: Signature[nodes.Argument] = Signature()\n        for arg_name in sorted(all_args, key=get_position):\n            # example_arg_name gives us a real name (in case we had a fake index-based name)\n            example_arg_name = all_args[arg_name][0][0].variable.name\n            arg = nodes.Argument(\n                nodes.Var(example_arg_name, get_type(arg_name)),\n                type_annotation=None,\n                initializer=None,\n                kind=get_kind(arg_name),\n                pos_only=all(arg.pos_only for arg, _ in all_args[arg_name]),\n            )\n            if arg.kind.is_positional():\n                sig.pos.append(arg)\n            elif arg.kind.is_named():\n                sig.kwonly[arg.variable.name] = arg\n            elif arg.kind == nodes.ARG_STAR:\n                sig.varpos = arg\n            elif arg.kind == nodes.ARG_STAR2:\n                sig.varkw = arg\n            else:\n                raise AssertionError\n        return sig\n\n\ndef _verify_signature(\n    stub: Signature[nodes.Argument],\n    runtime: Signature[inspect.Parameter],\n    function_name: str,\n    warn_runtime_is_object_init: bool = False,\n) -> Iterator[str]:\n    # Check positional arguments match up\n    for stub_arg, runtime_arg in zip(stub.pos, runtime.pos):\n        yield from _verify_arg_name(stub_arg, runtime_arg, function_name)\n        yield from _verify_arg_default_value(stub_arg, runtime_arg)\n        if (\n            runtime_arg.kind == inspect.Parameter.POSITIONAL_ONLY\n            and not stub_arg.pos_only\n            and not stub_arg.variable.name.startswith(\"__\")\n            and stub_arg.variable.name.strip(\"_\") != \"self\"\n            and stub_arg.variable.name.strip(\"_\") != \"cls\"\n        ):\n            yield (\n                f'stub parameter \"{stub_arg.variable.name}\" should be positional-only '\n                f'(add \"/\", e.g. \"{runtime_arg.name}, /\")'\n            )\n        if (\n            runtime_arg.kind != inspect.Parameter.POSITIONAL_ONLY\n            and (stub_arg.pos_only or stub_arg.variable.name.startswith(\"__\"))\n            and not runtime_arg.name.startswith(\"__\")\n            and stub_arg.variable.name.strip(\"_\") != \"self\"\n            and stub_arg.variable.name.strip(\"_\") != \"cls\"\n            and not is_dunder(function_name, exclude_special=True)  # noisy for dunder methods\n        ):\n            yield (\n                f'stub parameter \"{stub_arg.variable.name}\" should be positional or keyword '\n                '(remove \"/\")'\n            )\n\n    # Check unmatched positional args\n    if len(stub.pos) > len(runtime.pos):\n        # There are cases where the stub exhaustively lists out the extra parameters the function\n        # would take through *args. Hence, a) if runtime accepts *args, we don't check whether the\n        # runtime has all of the stub's parameters, b) below, we don't enforce that the stub takes\n        # *args, since runtime logic may prevent arbitrary arguments from actually being accepted.\n        if runtime.varpos is None:\n            for stub_arg in stub.pos[len(runtime.pos) :]:\n                # If the variable is in runtime.kwonly, it's just mislabelled as not a\n                # keyword-only argument\n                if stub_arg.variable.name not in runtime.kwonly:\n                    msg = f'runtime does not have parameter \"{stub_arg.variable.name}\"'\n                    if runtime.varkw is not None:\n                        msg += \". Maybe you forgot to make it keyword-only in the stub?\"\n                    elif warn_runtime_is_object_init:\n                        msg += \". You may need to write stubs for __new__ instead of __init__.\"\n                    yield msg\n                else:\n                    yield f'stub parameter \"{stub_arg.variable.name}\" is not keyword-only'\n            if stub.varpos is not None:\n                yield f'runtime does not have *args parameter \"{stub.varpos.variable.name}\"'\n    elif len(stub.pos) < len(runtime.pos):\n        for runtime_arg in runtime.pos[len(stub.pos) :]:\n            if runtime_arg.name not in stub.kwonly:\n                if not _is_private_parameter(runtime_arg):\n                    yield f'stub does not have parameter \"{runtime_arg.name}\"'\n            else:\n                yield f'runtime parameter \"{runtime_arg.name}\" is not keyword-only'\n\n    # Checks involving *args\n    if len(stub.pos) <= len(runtime.pos) or runtime.varpos is None:\n        if stub.varpos is None and runtime.varpos is not None:\n            yield f'stub does not have *args parameter \"{runtime.varpos.name}\"'\n        if stub.varpos is not None and runtime.varpos is None:\n            yield f'runtime does not have *args parameter \"{stub.varpos.variable.name}\"'\n\n    # Check keyword-only args\n    for arg in sorted(set(stub.kwonly) & set(runtime.kwonly)):\n        stub_arg, runtime_arg = stub.kwonly[arg], runtime.kwonly[arg]\n        yield from _verify_arg_name(stub_arg, runtime_arg, function_name)\n        yield from _verify_arg_default_value(stub_arg, runtime_arg)\n\n    # Check unmatched keyword-only args\n    if runtime.varkw is None or not set(runtime.kwonly).issubset(set(stub.kwonly)):\n        # There are cases where the stub exhaustively lists out the extra parameters the function\n        # would take through **kwargs. Hence, a) if runtime accepts **kwargs (and the stub hasn't\n        # exhaustively listed out params), we don't check whether the runtime has all of the stub's\n        # parameters, b) below, we don't enforce that the stub takes **kwargs, since runtime logic\n        # may prevent arbitrary keyword arguments from actually being accepted.\n        for arg in sorted(set(stub.kwonly) - set(runtime.kwonly)):\n            if arg in {runtime_arg.name for runtime_arg in runtime.pos}:\n                # Don't report this if we've reported it before\n                if arg not in {runtime_arg.name for runtime_arg in runtime.pos[len(stub.pos) :]}:\n                    yield f'runtime parameter \"{arg}\" is not keyword-only'\n            else:\n                msg = f'runtime does not have parameter \"{arg}\"'\n                if warn_runtime_is_object_init:\n                    msg += \". You may need to write stubs for __new__ instead of __init__.\"\n                yield msg\n\n    for arg in sorted(set(runtime.kwonly) - set(stub.kwonly)):\n        if arg in {stub_arg.variable.name for stub_arg in stub.pos}:\n            # Don't report this if we've reported it before\n            if not (\n                runtime.varpos is None\n                and arg in {stub_arg.variable.name for stub_arg in stub.pos[len(runtime.pos) :]}\n            ):\n                yield f'stub parameter \"{arg}\" is not keyword-only'\n        else:\n            if not _is_private_parameter(runtime.kwonly[arg]):\n                yield f'stub does not have parameter \"{arg}\"'\n\n    # Checks involving **kwargs\n    if stub.varkw is None and runtime.varkw is not None:\n        # As mentioned above, don't enforce that the stub takes **kwargs.\n        # Also check against positional parameters, to avoid a nitpicky message when an argument\n        # isn't marked as keyword-only\n        stub_pos_names = {stub_arg.variable.name for stub_arg in stub.pos}\n        # Ideally we'd do a strict subset check, but in practice the errors from that aren't useful\n        if not set(runtime.kwonly).issubset(set(stub.kwonly) | stub_pos_names):\n            yield f'stub does not have **kwargs parameter \"{runtime.varkw.name}\"'\n    if stub.varkw is not None and runtime.varkw is None:\n        yield f'runtime does not have **kwargs parameter \"{stub.varkw.variable.name}\"'\n\n\ndef _is_private_parameter(arg: inspect.Parameter) -> bool:\n    return (\n        arg.name.startswith(\"_\")\n        and not arg.name.startswith(\"__\")\n        and arg.default is not inspect.Parameter.empty\n    )\n\n\n@verify.register(nodes.FuncItem)\ndef verify_funcitem(\n    stub: nodes.FuncItem, runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\n    if isinstance(runtime, Missing):\n        yield Error(object_path, \"is not present at runtime\", stub, runtime)\n        return\n\n    if not is_probably_a_function(runtime):\n        yield Error(object_path, \"is not a function\", stub, runtime)\n        if not callable(runtime):\n            return\n\n    # Look the object up statically, to avoid binding by the descriptor protocol\n    static_runtime = _static_lookup_runtime(object_path)\n\n    if isinstance(stub, nodes.FuncDef):\n        for error_text in _verify_abstract_status(stub, runtime):\n            yield Error(object_path, error_text, stub, runtime)\n        for error_text in _verify_final_method(stub, runtime, static_runtime):\n            yield Error(object_path, error_text, stub, runtime)\n\n    for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path):\n        yield Error(object_path, \"is inconsistent, \" + message, stub, runtime)\n\n    signature = safe_inspect_signature(runtime)\n    runtime_is_coroutine = inspect.iscoroutinefunction(runtime)\n\n    if signature:\n        stub_sig = Signature.from_funcitem(stub)\n        runtime_sig = Signature.from_inspect_signature(signature)\n        runtime_sig_desc = describe_runtime_callable(signature, is_async=runtime_is_coroutine)\n        stub_desc = str(stub_sig)\n    else:\n        runtime_sig_desc, stub_desc = None, None\n\n    # Don't raise an error if the stub is a coroutine, but the runtime isn't.\n    # That results in false positives.\n    # See https://github.com/python/typeshed/issues/7344\n    if runtime_is_coroutine and not stub.is_coroutine:\n        yield Error(\n            object_path,\n            'is an \"async def\" function at runtime, but not in the stub',\n            stub,\n            runtime,\n            stub_desc=stub_desc,\n            runtime_desc=runtime_sig_desc,\n        )\n\n    if not signature:\n        return\n\n    for message in _verify_signature(\n        stub_sig,\n        runtime_sig,\n        function_name=stub.name,\n        warn_runtime_is_object_init=runtime is object.__init__,\n    ):\n        yield Error(\n            object_path,\n            \"is inconsistent, \" + message,\n            stub,\n            runtime,\n            runtime_desc=runtime_sig_desc,\n        )\n\n\n@verify.register(Missing)\ndef verify_missing(\n    stub: Missing, runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\n    if runtime is MISSING:\n        return\n    yield Error(object_path, \"is not present in stub\", stub, runtime)\n\n\n@verify.register(nodes.Var)\ndef verify_var(\n    stub: nodes.Var, runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\n    if isinstance(runtime, Missing):\n        # Don't always yield an error here, because we often can't find instance variables\n        if len(object_path) <= 2:\n            yield Error(object_path, \"is not present at runtime\", stub, runtime)\n        return\n\n    if (\n        stub.is_initialized_in_class\n        and is_read_only_property(runtime)\n        and (stub.is_settable_property or not stub.is_property)\n    ):\n        yield Error(object_path, \"is read-only at runtime but not in the stub\", stub, runtime)\n\n    runtime_type = get_mypy_type_of_runtime_value(runtime, type_context=stub.type)\n    note = \"\"\n    if (\n        runtime_type is not None\n        and stub.type is not None\n        and not is_subtype_helper(runtime_type, stub.type)\n    ):\n        should_error = True\n        # Avoid errors when defining enums, since runtime_type is the enum itself, but we'd\n        # annotate it with the type of runtime.value\n        if isinstance(runtime, enum.Enum):\n            runtime_type = get_mypy_type_of_runtime_value(runtime.value)\n            if runtime_type is not None and is_subtype_helper(runtime_type, stub.type):\n                should_error = False\n            # We always allow setting the stub value to Ellipsis (...), but use\n            # _value_ type as a fallback if given. If a member is ... and _value_\n            # type is given, all runtime types should be assignable to _value_.\n            proper_type = mypy.types.get_proper_type(stub.type)\n            if (\n                isinstance(proper_type, mypy.types.Instance)\n                and proper_type.type.fullname in mypy.types.ELLIPSIS_TYPE_NAMES\n            ):\n                value_t = stub.info.get(\"_value_\")\n                if value_t is None or value_t.type is None or runtime_type is None:\n                    should_error = False\n                elif is_subtype_helper(runtime_type, value_t.type):\n                    should_error = False\n                else:\n                    note = \" (incompatible '_value_')\"\n\n        if should_error:\n            yield Error(\n                object_path,\n                f\"variable differs from runtime type {runtime_type}{note}\",\n                stub,\n                runtime,\n            )\n    elif stub.final_value is not None and stub.final_value != runtime:\n        yield Error(\n            object_path,\n            \"is inconsistent, stub value for Final var differs from runtime value\",\n            stub,\n            runtime,\n            stub_desc=repr(stub.final_value),\n        )\n\n\n@verify.register(nodes.OverloadedFuncDef)\ndef verify_overloadedfuncdef(\n    stub: nodes.OverloadedFuncDef, runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\n    # TODO: support `@type_check_only` decorator\n    if isinstance(runtime, Missing):\n        yield Error(object_path, \"is not present at runtime\", stub, runtime)\n        return\n\n    if stub.is_property:\n        # Any property with a setter is represented as an OverloadedFuncDef\n        if is_read_only_property(runtime):\n            yield Error(object_path, \"is read-only at runtime but not in the stub\", stub, runtime)\n        return\n\n    if not is_probably_a_function(runtime):\n        yield Error(object_path, \"is not a function\", stub, runtime)\n        if not callable(runtime):\n            return\n\n    # mypy doesn't allow overloads where one overload is abstract but another isn't,\n    # so it should be okay to just check whether the first overload is abstract or not.\n    #\n    # TODO: Mypy *does* allow properties where e.g. the getter is abstract but the setter is not;\n    # and any property with a setter is represented as an OverloadedFuncDef internally;\n    # not sure exactly what (if anything) we should do about that.\n    first_part = stub.items[0]\n    if isinstance(first_part, nodes.Decorator) and first_part.is_overload:\n        for msg in _verify_abstract_status(first_part.func, runtime):\n            yield Error(object_path, msg, stub, runtime)\n\n    # Look the object up statically, to avoid binding by the descriptor protocol\n    static_runtime = _static_lookup_runtime(object_path)\n\n    for message in _verify_static_class_methods(stub, runtime, static_runtime, object_path):\n        yield Error(object_path, \"is inconsistent, \" + message, stub, runtime)\n\n    # TODO: Should call _verify_final_method here,\n    # but overloaded final methods in stubs cause a stubtest crash: see #14950\n\n    signature = safe_inspect_signature(runtime)\n    if not signature:\n        return\n\n    stub_sig = Signature.from_overloadedfuncdef(stub)\n    runtime_sig = Signature.from_inspect_signature(signature)\n\n    for message in _verify_signature(\n        stub_sig,\n        runtime_sig,\n        function_name=stub.name,\n        warn_runtime_is_object_init=runtime is object.__init__,\n    ):\n        # TODO: This is a little hacky, but the addition here is super useful\n        if \"has a default value of type\" in message:\n            message += (\n                \". This is often caused by overloads failing to account for explicitly passing \"\n                \"in the default value.\"\n            )\n        yield Error(\n            object_path,\n            \"is inconsistent, \" + message,\n            stub,\n            runtime,\n            stub_desc=(str(stub.type)) + f\"\\nInferred signature: {stub_sig}\",\n            runtime_desc=\"def \" + str(signature),\n        )\n\n\n@verify.register(nodes.TypeVarExpr)\ndef verify_typevarexpr(\n    stub: nodes.TypeVarExpr, runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\n    if isinstance(runtime, Missing):\n        # We seem to insert these typevars into NamedTuple stubs, but they\n        # don't exist at runtime. Just ignore!\n        if stub.name == \"_NT\":\n            return\n        yield Error(object_path, \"is not present at runtime\", stub, runtime)\n        return\n    if not isinstance(runtime, TypeVar):\n        yield Error(object_path, \"is not a TypeVar\", stub, runtime)\n        return\n\n\n@verify.register(nodes.ParamSpecExpr)\ndef verify_paramspecexpr(\n    stub: nodes.ParamSpecExpr, runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\n    if isinstance(runtime, Missing):\n        yield Error(object_path, \"is not present at runtime\", stub, runtime)\n        return\n    maybe_paramspec_types = (\n        getattr(typing, \"ParamSpec\", None),\n        getattr(typing_extensions, \"ParamSpec\", None),\n    )\n    paramspec_types = tuple(t for t in maybe_paramspec_types if t is not None)\n    if not paramspec_types or not isinstance(runtime, paramspec_types):\n        yield Error(object_path, \"is not a ParamSpec\", stub, runtime)\n        return\n\n\ndef _is_django_cached_property(runtime: Any) -> bool:  # pragma: no cover\n    # This is a special case for\n    # https://docs.djangoproject.com/en/5.2/ref/utils/#django.utils.functional.cached_property\n    # This is needed in `django-stubs` project:\n    # https://github.com/typeddjango/django-stubs\n    if type(runtime).__name__ != \"cached_property\":\n        return False\n    try:\n        return bool(runtime.func)\n    except Exception:\n        return False\n\n\ndef _verify_readonly_property(stub: nodes.Decorator, runtime: Any) -> Iterator[str]:\n    assert stub.func.is_property\n    if isinstance(runtime, property):\n        yield from _verify_final_method(stub.func, runtime.fget, MISSING)\n        return\n    if isinstance(runtime, functools.cached_property):\n        yield from _verify_final_method(stub.func, runtime.func, MISSING)\n        return\n    if _is_django_cached_property(runtime):\n        yield from _verify_final_method(stub.func, runtime.func, MISSING)\n        return\n    if inspect.isdatadescriptor(runtime):\n        # It's enough like a property...\n        return\n    # Sometimes attributes pretend to be properties, for instance, to express that they\n    # are read only. So allowlist if runtime_type matches the return type of stub.\n    runtime_type = get_mypy_type_of_runtime_value(runtime)\n    func_type = (\n        stub.func.type.ret_type if isinstance(stub.func.type, mypy.types.CallableType) else None\n    )\n    if (\n        runtime_type is not None\n        and func_type is not None\n        and is_subtype_helper(runtime_type, func_type)\n    ):\n        return\n    yield \"is inconsistent, cannot reconcile @property on stub with runtime object\"\n\n\ndef _verify_abstract_status(stub: nodes.FuncDef, runtime: Any) -> Iterator[str]:\n    stub_abstract = stub.abstract_status == nodes.IS_ABSTRACT\n    runtime_abstract = getattr(runtime, \"__isabstractmethod__\", False)\n    # The opposite can exist: some implementations omit `@abstractmethod` decorators\n    if runtime_abstract and not stub_abstract:\n        item_type = \"property\" if stub.is_property else \"method\"\n        yield f\"is inconsistent, runtime {item_type} is abstract but stub is not\"\n\n\ndef _verify_final_method(\n    stub: nodes.FuncDef, runtime: Any, static_runtime: MaybeMissing[Any]\n) -> Iterator[str]:\n    if stub.is_final:\n        return\n    if getattr(runtime, \"__final__\", False) or (\n        static_runtime is not MISSING and getattr(static_runtime, \"__final__\", False)\n    ):\n        yield \"is decorated with @final at runtime, but not in the stub\"\n\n\ndef _resolve_funcitem_from_decorator(dec: nodes.OverloadPart) -> nodes.FuncItem | None:\n    \"\"\"Returns a FuncItem that corresponds to the output of the decorator.\n\n    Returns None if we can't figure out what that would be. For convenience, this function also\n    accepts FuncItems.\n    \"\"\"\n    if isinstance(dec, nodes.FuncItem):\n        return dec\n    if dec.func.is_property:\n        return None\n\n    def apply_decorator_to_funcitem(\n        decorator: nodes.Expression, func: nodes.FuncItem\n    ) -> nodes.FuncItem | None:\n        if (\n            isinstance(decorator, nodes.CallExpr)\n            and isinstance(decorator.callee, nodes.RefExpr)\n            and decorator.callee.fullname in mypy.types.DEPRECATED_TYPE_NAMES\n        ):\n            return func\n        if not isinstance(decorator, nodes.RefExpr):\n            return None\n        if not decorator.fullname:\n            # Happens with namedtuple\n            return None\n        if (\n            decorator.fullname in (\"builtins.staticmethod\", \"abc.abstractmethod\")\n            or decorator.fullname in mypy.types.OVERLOAD_NAMES\n            or decorator.fullname in mypy.types.OVERRIDE_DECORATOR_NAMES\n            or decorator.fullname in mypy.types.FINAL_DECORATOR_NAMES\n        ):\n            return func\n        if decorator.fullname == \"builtins.classmethod\":\n            if func.arguments[0].variable.name not in (\"_cls\", \"cls\", \"mcs\", \"metacls\"):\n                raise StubtestFailure(\n                    f\"unexpected class parameter name {func.arguments[0].variable.name!r} \"\n                    f\"in {dec.fullname}\"\n                )\n            # FuncItem is written so that copy.copy() actually works, even when compiled\n            ret = copy.copy(func)\n            # Remove the cls argument, since it's not present in inspect.signature of classmethods\n            ret.arguments = ret.arguments[1:]\n            return ret\n        # Just give up on any other decorators. After excluding properties, we don't run into\n        # anything else when running on typeshed's stdlib.\n        return None\n\n    func: nodes.FuncItem = dec.func\n    for decorator in dec.original_decorators:\n        resulting_func = apply_decorator_to_funcitem(decorator, func)\n        if resulting_func is None:\n            # We couldn't figure out how to apply the decorator by transforming nodes, so try to\n            # reconstitute a FuncDef from the resulting type of the decorator\n            # This is worse because e.g. we lose the values of defaults\n            dec_type = mypy.types.get_proper_type(dec.type)\n            callable_type = None\n            if isinstance(dec_type, mypy.types.Instance):\n                callable_type = mypy.subtypes.find_member(\n                    \"__call__\", dec_type, dec_type, is_operator=True\n                )\n            elif isinstance(dec_type, mypy.types.CallableType):\n                callable_type = dec_type\n\n            callable_type = mypy.types.get_proper_type(callable_type)\n            if isinstance(callable_type, mypy.types.CallableType):\n                return _resolve_funcitem_from_callable_type(dec, callable_type)\n            return None\n\n        func = resulting_func\n    return func\n\n\ndef _resolve_funcitem_from_callable_type(\n    dec: nodes.Decorator, typ: mypy.types.CallableType\n) -> nodes.FuncDef | None:\n    if (\n        typ.arg_kinds == [nodes.ARG_STAR, nodes.ARG_STAR2]\n        and (var_arg := typ.var_arg()) is not None\n        and isinstance(mypy.types.get_proper_type(var_arg.typ), mypy.types.AnyType)\n        and (var_kwarg := typ.kw_arg()) is not None\n        and isinstance(mypy.types.get_proper_type(var_kwarg.typ), mypy.types.AnyType)\n    ):\n        # There isn't a FuncDef we can invent corresponding to a Callable[..., T]\n        return None\n\n    args: list[nodes.Argument] = []\n    for i, (arg_type, arg_kind, arg_name) in enumerate(\n        zip(typ.arg_types, typ.arg_kinds, typ.arg_names, strict=True)\n    ):\n        var_name = arg_name if arg_name is not None else f\"__arg{i}\"\n        var = nodes.Var(var_name, arg_type)\n        pos_only = arg_name is None and arg_kind == nodes.ARG_POS\n        args.append(\n            nodes.Argument(\n                variable=var,\n                type_annotation=arg_type,\n                initializer=None,  # CallableType doesn't store the values of defaults\n                kind=arg_kind,\n                pos_only=pos_only,\n            )\n        )\n\n    if dec.func.is_class:\n        if not args:\n            return None\n        # Munge classmethods, similar to logic in _resolve_funcitem_from_decorator\n        if args[0].variable.name not in (\"_cls\", \"cls\", \"mcs\", \"metacls\"):\n            return None\n        args.pop(0)\n\n    ret = nodes.FuncDef(name=typ.name or \"\", arguments=args, body=nodes.Block([]), typ=typ)\n    ret.is_class = dec.func.is_class\n    return ret\n\n\n@verify.register(nodes.Decorator)\ndef verify_decorator(\n    stub: nodes.Decorator, runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\n    if stub.func.is_type_check_only:\n        # This function only exists in stubs, we only check that the runtime part\n        # is missing. Other checks are not required.\n        if not isinstance(runtime, Missing):\n            yield Error(\n                object_path,\n                'is marked as \"@type_check_only\", but also exists at runtime',\n                stub,\n                runtime,\n                stub_desc=repr(stub),\n            )\n        return\n\n    if isinstance(runtime, Missing):\n        yield Error(object_path, \"is not present at runtime\", stub, runtime)\n        return\n    if stub.func.is_property:\n        for message in _verify_readonly_property(stub, runtime):\n            yield Error(object_path, message, stub, runtime)\n        for message in _verify_abstract_status(stub.func, runtime):\n            yield Error(object_path, message, stub, runtime)\n        return\n\n    func = _resolve_funcitem_from_decorator(stub)\n    if func is not None:\n        yield from verify(func, runtime, object_path)\n\n\n@verify.register(nodes.TypeAlias)\ndef verify_typealias(\n    stub: nodes.TypeAlias, runtime: MaybeMissing[Any], object_path: list[str]\n) -> Iterator[Error]:\n    stub_target = mypy.types.get_proper_type(stub.target)\n    stub_desc = f\"Type alias for {stub_target}\"\n    if isinstance(runtime, Missing):\n        yield Error(object_path, \"is not present at runtime\", stub, runtime, stub_desc=stub_desc)\n        return\n    runtime_origin = get_origin(runtime) or runtime\n    if isinstance(stub_target, mypy.types.Instance):\n        if not isinstance(runtime_origin, type):\n            yield Error(\n                object_path,\n                \"is inconsistent, runtime is not a type\",\n                stub,\n                runtime,\n                stub_desc=stub_desc,\n            )\n            return\n\n        stub_origin = stub_target.type\n        # Do our best to figure out the fullname of the runtime object...\n        runtime_name: object\n        try:\n            runtime_name = runtime_origin.__qualname__\n        except AttributeError:\n            runtime_name = getattr(runtime_origin, \"__name__\", MISSING)\n        if isinstance(runtime_name, str):\n            runtime_module: object = getattr(runtime_origin, \"__module__\", MISSING)\n            if isinstance(runtime_module, str):\n                if runtime_module == \"collections.abc\" or (\n                    runtime_module == \"re\" and runtime_name in {\"Match\", \"Pattern\"}\n                ):\n                    runtime_module = \"typing\"\n                runtime_fullname = f\"{runtime_module}.{runtime_name}\"\n                if re.fullmatch(rf\"_?{re.escape(stub_origin.fullname)}\", runtime_fullname):\n                    # Okay, we're probably fine.\n                    return\n\n        # Okay, either we couldn't construct a fullname\n        # or the fullname of the stub didn't match the fullname of the runtime.\n        # Fallback to a full structural check of the runtime vis-a-vis the stub.\n        yield from verify_typeinfo(stub_origin, runtime_origin, object_path, is_alias_target=True)\n        return\n    if isinstance(stub_target, mypy.types.UnionType):\n        # complain if runtime is not a Union or UnionType\n        if runtime_origin is not Union and (\n            not (sys.version_info >= (3, 10) and isinstance(runtime, types.UnionType))\n        ):\n            yield Error(object_path, \"is not a Union\", stub, runtime, stub_desc=str(stub_target))\n        # could check Union contents here...\n        return\n    if isinstance(stub_target, mypy.types.TupleType):\n        if tuple not in getattr(runtime_origin, \"__mro__\", ()):\n            yield Error(\n                object_path, \"is not a subclass of tuple\", stub, runtime, stub_desc=stub_desc\n            )\n        # could check Tuple contents here...\n        return\n    if isinstance(stub_target, mypy.types.CallableType):\n        if runtime_origin is not collections.abc.Callable:\n            yield Error(\n                object_path, \"is not a type alias for Callable\", stub, runtime, stub_desc=stub_desc\n            )\n        # could check Callable contents here...\n        return\n    if isinstance(stub_target, mypy.types.AnyType):\n        return\n    yield Error(object_path, \"is not a recognised type alias\", stub, runtime, stub_desc=stub_desc)\n\n\n# ====================\n# Helpers\n# ====================\n\n\nIGNORED_MODULE_DUNDERS: Final = frozenset(\n    {\n        \"__file__\",\n        \"__doc__\",\n        \"__name__\",\n        \"__builtins__\",\n        \"__package__\",\n        \"__cached__\",\n        \"__loader__\",\n        \"__spec__\",\n        \"__annotations__\",\n        \"__conditional_annotations__\",  # 3.14+\n        \"__annotate__\",\n        \"__path__\",  # mypy adds __path__ to packages, but C packages don't have it\n        \"__getattr__\",  # resulting behaviour might be typed explicitly\n        # Created by `warnings.warn`, does not make much sense to have in stubs:\n        \"__warningregistry__\",\n        # TODO: remove the following from this list\n        \"__author__\",\n        \"__version__\",\n        \"__copyright__\",\n    }\n)\n\nIGNORABLE_CLASS_DUNDERS: Final = frozenset(\n    {\n        # Special attributes\n        \"__dict__\",\n        \"__annotations__\",\n        \"__annotate__\",\n        \"__annotations_cache__\",\n        \"__annotate_func__\",\n        \"__text_signature__\",\n        \"__weakref__\",\n        \"__hash__\",\n        \"__getattr__\",  # resulting behaviour might be typed explicitly\n        \"__setattr__\",  # defining this on a class can cause worse type checking\n        \"__vectorcalloffset__\",  # undocumented implementation detail of the vectorcall protocol\n        \"__firstlineno__\",\n        \"__static_attributes__\",\n        \"__classdictcell__\",\n        # isinstance/issubclass hooks that type-checkers don't usually care about\n        \"__instancecheck__\",\n        \"__subclasshook__\",\n        \"__subclasscheck__\",\n        # python2 only magic methods:\n        \"__cmp__\",\n        \"__nonzero__\",\n        \"__unicode__\",\n        \"__div__\",\n        # cython methods\n        \"__pyx_vtable__\",\n        # Pickle methods\n        \"__setstate__\",\n        \"__getstate__\",\n        \"__getnewargs__\",\n        \"__getinitargs__\",\n        \"__reduce_ex__\",\n        \"__reduce__\",\n        \"__slotnames__\",  # Cached names of slots added by `copyreg` module.\n        # ctypes weirdness\n        \"__ctype_be__\",\n        \"__ctype_le__\",\n        \"__ctypes_from_outparam__\",\n        # mypy limitations\n        \"__abstractmethods__\",  # Classes with metaclass=ABCMeta inherit this attribute\n        \"__new_member__\",  # If an enum defines __new__, the method is renamed as __new_member__\n        \"__dataclass_fields__\",  # Generated by dataclasses\n        \"__dataclass_params__\",  # Generated by dataclasses\n        \"__doc__\",  # mypy's semanal for namedtuples assumes this is str, not Optional[str]\n        # Added to all protocol classes on 3.12+ (or if using typing_extensions.Protocol)\n        \"__protocol_attrs__\",\n        \"__callable_proto_members_only__\",\n        \"__non_callable_proto_members__\",\n        # typing implementation details, consider removing some of these:\n        \"__parameters__\",\n        \"__origin__\",\n        \"__args__\",\n        \"__orig_bases__\",\n        \"__final__\",  # Has a specialized check\n        # Consider removing __slots__?\n        \"__slots__\",\n    }\n)\n\n\ndef is_probably_private(name: str) -> bool:\n    return name.startswith(\"_\") and not is_dunder(name)\n\n\ndef is_probably_a_function(runtime: Any) -> bool:\n    return (\n        isinstance(\n            runtime,\n            (\n                types.FunctionType,\n                types.BuiltinFunctionType,\n                types.MethodType,\n                types.BuiltinMethodType,\n            ),\n        )\n        or (inspect.ismethoddescriptor(runtime) and callable(runtime))\n        or (isinstance(runtime, types.MethodWrapperType) and callable(runtime))\n    )\n\n\ndef is_read_only_property(runtime: object) -> bool:\n    return isinstance(runtime, property) and runtime.fset is None\n\n\ndef safe_inspect_signature(runtime: Any) -> inspect.Signature | None:\n    if (\n        hasattr(runtime, \"__name__\")\n        and runtime.__name__ == \"__init__\"\n        and hasattr(runtime, \"__text_signature__\")\n        and runtime.__text_signature__ == \"($self, /, *args, **kwargs)\"\n        and hasattr(runtime, \"__objclass__\")\n        and hasattr(runtime.__objclass__, \"__text_signature__\")\n        and runtime.__objclass__.__text_signature__ is not None\n    ):\n        # This is an __init__ method with the generic C-class signature.\n        # In this case, the underlying class often has a better signature,\n        # which we can convert into an __init__ signature by adding in the\n        # self parameter.\n        try:\n            s = inspect.signature(runtime.__objclass__)\n\n            parameter_kind: inspect._ParameterKind = inspect.Parameter.POSITIONAL_OR_KEYWORD\n            if s.parameters:\n                first_parameter = next(iter(s.parameters.values()))\n                if first_parameter.kind == inspect.Parameter.POSITIONAL_ONLY:\n                    parameter_kind = inspect.Parameter.POSITIONAL_ONLY\n            return s.replace(\n                parameters=[inspect.Parameter(\"self\", parameter_kind), *s.parameters.values()]\n            )\n        except Exception:\n            pass\n\n    if (\n        hasattr(runtime, \"__name__\")\n        and runtime.__name__ == \"__new__\"\n        and hasattr(runtime, \"__text_signature__\")\n        and runtime.__text_signature__ == \"($type, *args, **kwargs)\"\n        and hasattr(runtime, \"__self__\")\n        and hasattr(runtime.__self__, \"__text_signature__\")\n        and runtime.__self__.__text_signature__ is not None\n    ):\n        # This is a __new__ method with the generic C-class signature.\n        # In this case, the underlying class often has a better signature,\n        # which we can convert into a __new__ signature by adding in the\n        # cls parameter.\n\n        # If the attached class has a valid __init__, skip recovering a\n        # signature for this __new__ method.\n        has_init = False\n        if (\n            hasattr(runtime.__self__, \"__init__\")\n            and hasattr(runtime.__self__.__init__, \"__objclass__\")\n            and runtime.__self__.__init__.__objclass__ is runtime.__self__\n        ):\n            has_init = True\n\n        if not has_init:\n            try:\n                s = inspect.signature(runtime.__self__)\n                parameter_kind = inspect.Parameter.POSITIONAL_OR_KEYWORD\n                if s.parameters:\n                    first_parameter = next(iter(s.parameters.values()))\n                    if first_parameter.kind == inspect.Parameter.POSITIONAL_ONLY:\n                        parameter_kind = inspect.Parameter.POSITIONAL_ONLY\n                return s.replace(\n                    parameters=[inspect.Parameter(\"cls\", parameter_kind), *s.parameters.values()]\n                )\n            except Exception:\n                pass\n\n    try:\n        try:\n            return inspect.signature(runtime)\n        except ValueError:\n            if (\n                hasattr(runtime, \"__text_signature__\")\n                and \"<unrepresentable>\" in runtime.__text_signature__\n            ):\n                # Try to fix up the signature. Workaround for\n                # https://github.com/python/cpython/issues/87233\n                sig = runtime.__text_signature__.replace(\"<unrepresentable>\", \"...\")\n                sig = inspect._signature_fromstr(inspect.Signature, runtime, sig)  # type: ignore[attr-defined]\n                assert isinstance(sig, inspect.Signature)\n                new_params = [\n                    (\n                        parameter.replace(default=UNREPRESENTABLE)\n                        if parameter.default is ...\n                        else parameter\n                    )\n                    for parameter in sig.parameters.values()\n                ]\n                return sig.replace(parameters=new_params)\n            else:\n                raise\n    except Exception:\n        # inspect.signature throws ValueError all the time\n        # catch RuntimeError because of https://bugs.python.org/issue39504\n        # catch TypeError because of https://github.com/python/typeshed/pull/5762\n        # catch AttributeError because of inspect.signature(_curses.window.border)\n        return None\n\n\ndef describe_runtime_callable(signature: inspect.Signature, *, is_async: bool) -> str:\n    return f'{\"async \" if is_async else \"\"}def {signature}'\n\n\nclass _TypeCheckOnlyBaseMapper(mypy.types.TypeTranslator):\n    \"\"\"Rewrites @type_check_only instances to the nearest runtime-visible base class.\"\"\"\n\n    def visit_instance(self, t: mypy.types.Instance, /) -> mypy.types.Type:\n        instance = mypy.types.get_proper_type(super().visit_instance(t))\n        assert isinstance(instance, mypy.types.Instance)\n\n        if instance.type.is_type_check_only:\n            # find the nearest non-@type_check_only base class\n            for base_info in instance.type.mro[1:]:\n                if not base_info.is_type_check_only:\n                    return map_instance_to_supertype(instance, base_info)\n\n            msg = f\"all base classes of {instance.type.fullname!r} are @type_check_only\"\n            assert False, msg\n\n        return instance\n\n    def visit_type_alias_type(self, t: mypy.types.TypeAliasType, /) -> mypy.types.Type:\n        return t\n\n\n_TYPE_CHECK_ONLY_BASE_MAPPER = _TypeCheckOnlyBaseMapper()\n\n\ndef _relax_type_check_only_type(typ: mypy.types.ProperType) -> mypy.types.ProperType:\n    return mypy.types.get_proper_type(typ.accept(_TYPE_CHECK_ONLY_BASE_MAPPER))\n\n\ndef is_subtype_helper(left: mypy.types.Type, right: mypy.types.Type) -> bool:\n    \"\"\"Checks whether ``left`` is a subtype of ``right``.\"\"\"\n    left = _relax_type_check_only_type(mypy.types.get_proper_type(left))\n    right = _relax_type_check_only_type(mypy.types.get_proper_type(right))\n    if (\n        isinstance(left, mypy.types.LiteralType)\n        and isinstance(left.value, int)\n        and left.value in (0, 1)\n        and mypy.types.is_named_instance(right, \"builtins.bool\")\n    ):\n        # Pretend Literal[0, 1] is a subtype of bool to avoid unhelpful errors.\n        return True\n\n    if isinstance(right, mypy.types.TypedDictType) and mypy.types.is_named_instance(\n        left, \"builtins.dict\"\n    ):\n        # Special case checks against TypedDicts\n        return True\n\n    with mypy.state.state.strict_optional_set(True):\n        return mypy.subtypes.is_subtype(left, right)\n\n\ndef get_mypy_node_for_name(module: str, type_name: str) -> mypy.nodes.SymbolNode | None:\n    stub = get_stub(module)\n    if stub is None:\n        return None\n    if type_name not in stub.names:\n        return None\n    return stub.names[type_name].node\n\n\ndef get_mypy_type_of_runtime_value(\n    runtime: Any, type_context: mypy.types.Type | None = None\n) -> mypy.types.Type | None:\n    \"\"\"Returns a mypy type object representing the type of ``runtime``.\n\n    Returns None if we can't find something that works.\n\n    \"\"\"\n    if runtime is None:\n        return mypy.types.NoneType()\n    if isinstance(runtime, property):\n        # Give up on properties to avoid issues with things that are typed as attributes.\n        return None\n\n    def anytype() -> mypy.types.AnyType:\n        return mypy.types.AnyType(mypy.types.TypeOfAny.unannotated)\n\n    if isinstance(\n        runtime,\n        (types.FunctionType, types.BuiltinFunctionType, types.MethodType, types.BuiltinMethodType),\n    ):\n        builtins = get_stub(\"builtins\")\n        assert builtins is not None\n        type_info = builtins.names[\"function\"].node\n        assert isinstance(type_info, nodes.TypeInfo)\n        fallback = mypy.types.Instance(type_info, [anytype()])\n        signature = safe_inspect_signature(runtime)\n        if signature:\n            arg_types = []\n            arg_kinds = []\n            arg_names = []\n            for arg in signature.parameters.values():\n                arg_types.append(anytype())\n                arg_names.append(\n                    None if arg.kind == inspect.Parameter.POSITIONAL_ONLY else arg.name\n                )\n                no_default = arg.default is inspect.Parameter.empty\n                if arg.kind == inspect.Parameter.POSITIONAL_ONLY:\n                    arg_kinds.append(nodes.ARG_POS if no_default else nodes.ARG_OPT)\n                elif arg.kind == inspect.Parameter.POSITIONAL_OR_KEYWORD:\n                    arg_kinds.append(nodes.ARG_POS if no_default else nodes.ARG_OPT)\n                elif arg.kind == inspect.Parameter.KEYWORD_ONLY:\n                    arg_kinds.append(nodes.ARG_NAMED if no_default else nodes.ARG_NAMED_OPT)\n                elif arg.kind == inspect.Parameter.VAR_POSITIONAL:\n                    arg_kinds.append(nodes.ARG_STAR)\n                elif arg.kind == inspect.Parameter.VAR_KEYWORD:\n                    arg_kinds.append(nodes.ARG_STAR2)\n                else:\n                    raise AssertionError\n        else:\n            arg_types = [anytype(), anytype()]\n            arg_kinds = [nodes.ARG_STAR, nodes.ARG_STAR2]\n            arg_names = [None, None]\n\n        return mypy.types.CallableType(\n            arg_types,\n            arg_kinds,\n            arg_names,\n            ret_type=anytype(),\n            fallback=fallback,\n            is_ellipsis_args=True,\n        )\n\n    skip_type_object_type = False\n    if type_context:\n        # Don't attempt to process the type object when context is generic\n        # This is related to issue #3737\n        type_context = mypy.types.get_proper_type(type_context)\n        # Callable types with a generic return value\n        if isinstance(type_context, mypy.types.CallableType):\n            if isinstance(type_context.ret_type, mypy.types.TypeVarType):\n                skip_type_object_type = True\n        # Type[x] where x is generic\n        if isinstance(type_context, mypy.types.TypeType):\n            if isinstance(type_context.item, mypy.types.TypeVarType):\n                skip_type_object_type = True\n\n    if isinstance(runtime, type) and not skip_type_object_type:\n\n        def _named_type(name: str) -> mypy.types.Instance:\n            parts = name.rsplit(\".\", maxsplit=1)\n            node = get_mypy_node_for_name(parts[0], parts[1])\n            assert isinstance(node, nodes.TypeInfo)\n            any_type = mypy.types.AnyType(mypy.types.TypeOfAny.special_form)\n            return mypy.types.Instance(node, [any_type] * len(node.defn.type_vars))\n\n        # Try and look up a stub for the runtime object itself\n        # The logic here is similar to ExpressionChecker.analyze_ref_expr\n        type_info = get_mypy_node_for_name(runtime.__module__, runtime.__name__)\n        if isinstance(type_info, nodes.TypeInfo):\n            result: mypy.types.Type | None = None\n            result = mypy.typeops.type_object_type(type_info, _named_type)\n            if mypy.checkexpr.is_type_type_context(type_context):\n                # This is the type in a type[] expression, so substitute type\n                # variables with Any.\n                result = mypy.erasetype.erase_typevars(result)\n            return result\n\n    # Try and look up a stub for the runtime object's type\n    type_info = get_mypy_node_for_name(type(runtime).__module__, type(runtime).__name__)\n    if type_info is None:\n        return None\n    if isinstance(type_info, nodes.Var):\n        return type_info.type\n    if not isinstance(type_info, nodes.TypeInfo):\n        return None\n\n    if isinstance(runtime, tuple):\n        # Special case tuples so we construct a valid mypy.types.TupleType\n        optional_items = [get_mypy_type_of_runtime_value(v) for v in runtime]\n        items = [(i if i is not None else anytype()) for i in optional_items]\n        fallback = mypy.types.Instance(type_info, [anytype()])\n        return mypy.types.TupleType(items, fallback)\n\n    fallback = mypy.types.Instance(type_info, [anytype() for _ in type_info.type_vars])\n    if type(runtime) != runtime.__class__:\n        # Since `__class__` is redefined for an instance, we can't trust\n        # its `isinstance` checks, it can be dynamic. See #20919\n        return fallback\n\n    value: bool | int | str\n    if isinstance(runtime, enum.Enum) and isinstance(runtime.name, str):\n        value = runtime.name\n    elif isinstance(runtime, bytes):\n        value = bytes_to_human_readable_repr(runtime)\n    elif isinstance(runtime, (bool, int, str)):\n        value = runtime\n    else:\n        return fallback\n\n    return mypy.types.LiteralType(value=value, fallback=fallback)\n\n\n# ====================\n# Build and entrypoint\n# ====================\n\n\n_all_stubs: dict[str, nodes.MypyFile] = {}\n\n\ndef build_stubs(modules: list[str], options: Options, find_submodules: bool = False) -> list[str]:\n    \"\"\"Uses mypy to construct stub objects for the given modules.\n\n    This sets global state that ``get_stub`` can access.\n\n    Returns all modules we might want to check. If ``find_submodules`` is False, this is equal\n    to ``modules``.\n\n    :param modules: List of modules to build stubs for.\n    :param options: Mypy options for finding and building stubs.\n    :param find_submodules: Whether to attempt to find submodules of the given modules as well.\n\n    \"\"\"\n    data_dir = mypy.build.default_data_dir()\n    search_path = mypy.modulefinder.compute_search_paths([], options, data_dir)\n    find_module_cache = mypy.modulefinder.FindModuleCache(\n        search_path, fscache=None, options=options\n    )\n\n    all_modules = []\n    sources = []\n    for module in modules:\n        all_modules.append(module)\n        if not find_submodules:\n            module_path = find_module_cache.find_module(module)\n            if not isinstance(module_path, str):\n                # test_module will yield an error later when it can't find stubs\n                continue\n            sources.append(mypy.modulefinder.BuildSource(module_path, module, None))\n        else:\n            found_sources = find_module_cache.find_modules_recursive(module)\n            sources.extend(found_sources)\n            # find submodules via mypy\n            all_modules.extend(s.module for s in found_sources if s.module not in all_modules)\n            # find submodules via pkgutil\n            try:\n                runtime = silent_import_module(module)\n                all_modules.extend(\n                    m.name\n                    for m in pkgutil.walk_packages(runtime.__path__, runtime.__name__ + \".\")\n                    if m.name not in all_modules\n                )\n            except KeyboardInterrupt:\n                raise\n            except BaseException:\n                pass\n\n    if sources:\n        try:\n            res = mypy.build.build(sources=sources, options=options)\n        except mypy.errors.CompileError as e:\n            raise StubtestFailure(f\"failed mypy compile:\\n{e}\") from e\n        if res.errors:\n            raise StubtestFailure(\"mypy build errors:\\n\" + \"\\n\".join(res.errors))\n\n        global _all_stubs\n        _all_stubs = res.files\n\n    return all_modules\n\n\ndef get_stub(module: str) -> nodes.MypyFile | None:\n    \"\"\"Returns a stub object for the given module, if we've built one.\"\"\"\n    return _all_stubs.get(module)\n\n\ndef get_typeshed_stdlib_modules(\n    custom_typeshed_dir: str | None, version_info: tuple[int, int] | None = None\n) -> set[str]:\n    \"\"\"Returns a list of stdlib modules in typeshed (for current Python version).\"\"\"\n    stdlib_py_versions = mypy.modulefinder.load_stdlib_py_versions(custom_typeshed_dir)\n    if version_info is None:\n        version_info = sys.version_info[0:2]\n\n    def exists_in_version(module: str) -> bool:\n        assert version_info is not None\n        parts = module.split(\".\")\n        for i in range(len(parts), 0, -1):\n            current_module = \".\".join(parts[:i])\n            if current_module in stdlib_py_versions:\n                minver, maxver = stdlib_py_versions[current_module]\n                return version_info >= minver and (maxver is None or version_info <= maxver)\n        return False\n\n    if custom_typeshed_dir:\n        typeshed_dir = Path(custom_typeshed_dir)\n    else:\n        typeshed_dir = Path(mypy.build.default_data_dir()) / \"typeshed\"\n    stdlib_dir = typeshed_dir / \"stdlib\"\n\n    modules: set[str] = set()\n    for path in stdlib_dir.rglob(\"*.pyi\"):\n        if path.stem == \"__init__\":\n            path = path.parent\n        module = \".\".join(path.relative_to(stdlib_dir).parts[:-1] + (path.stem,))\n        if exists_in_version(module):\n            modules.add(module)\n    return modules\n\n\ndef get_importable_stdlib_modules() -> set[str]:\n    \"\"\"Return all importable stdlib modules at runtime.\"\"\"\n    importable_stdlib_modules: set[str] = set()\n    for module_name in sys.stdlib_module_names:\n        if module_name in ANNOYING_STDLIB_MODULES:\n            continue\n\n        try:\n            runtime = silent_import_module(module_name)\n        except ImportError:\n            continue\n        else:\n            importable_stdlib_modules.add(module_name)\n\n        try:\n            # some stdlib modules (e.g. `nt`) don't have __path__ set...\n            runtime_path = runtime.__path__\n            runtime_name = runtime.__name__\n        except AttributeError:\n            continue\n\n        for submodule in pkgutil.walk_packages(runtime_path, runtime_name + \".\"):\n            submodule_name = submodule.name\n\n            # There are many annoying *.__main__ stdlib modules,\n            # and including stubs for them isn't really that useful anyway:\n            # tkinter.__main__ opens a tkinter windows; unittest.__main__ raises SystemExit; etc.\n            #\n            # The idlelib.* submodules are similarly annoying in opening random tkinter windows,\n            # and we're unlikely to ever add stubs for idlelib in typeshed\n            # (see discussion in https://github.com/python/typeshed/pull/9193)\n            #\n            # test.* modules do weird things like raising exceptions in __del__ methods,\n            # leading to unraisable exceptions being logged to the terminal\n            # as a warning at the end of the stubtest run\n            if submodule_name.endswith(\".__main__\") or submodule_name.startswith(\n                (\"idlelib.\", \"test.\")\n            ):\n                continue\n\n            try:\n                silent_import_module(submodule_name)\n            except KeyboardInterrupt:\n                raise\n            # importing multiprocessing.popen_forkserver on Windows raises AttributeError...\n            # some submodules also appear to raise SystemExit as well on some Python versions\n            # (not sure exactly which)\n            except BaseException:\n                continue\n            else:\n                importable_stdlib_modules.add(submodule_name)\n\n    return importable_stdlib_modules\n\n\ndef get_allowlist_entries(allowlist_file: str) -> Iterator[str]:\n    def strip_comments(s: str) -> str:\n        try:\n            return s[: s.index(\"#\")].strip()\n        except ValueError:\n            return s.strip()\n\n    with open(allowlist_file) as f:\n        for line in f:\n            entry = strip_comments(line)\n            if entry:\n                yield entry\n\n\nclass _Arguments:\n    modules: list[str]\n    concise: bool\n    ignore_missing_stub: bool\n    ignore_positional_only: bool\n    ignore_disjoint_bases: bool\n    allowlist: list[str]\n    generate_allowlist: bool\n    ignore_unused_allowlist: bool\n    mypy_config_file: str | None\n    custom_typeshed_dir: str | None\n    check_typeshed: bool\n    version: str\n    show_traceback: bool\n    pdb: bool\n\n\n# typeshed added a stub for __main__, but that causes stubtest to check itself\nANNOYING_STDLIB_MODULES: Final = frozenset({\"antigravity\", \"this\", \"__main__\", \"_ios_support\"})\n\n\ndef test_stubs(args: _Arguments, use_builtins_fixtures: bool = False) -> int:\n    \"\"\"This is stubtest! It's time to test the stubs!\"\"\"\n    # Load the allowlist. This is a series of strings corresponding to Error.object_desc\n    # Values in the dict will store whether we used the allowlist entry or not.\n    allowlist = {\n        entry: False\n        for allowlist_file in args.allowlist\n        for entry in get_allowlist_entries(allowlist_file)\n    }\n    allowlist_regexes = {entry: re.compile(entry) for entry in allowlist}\n\n    # If we need to generate an allowlist, we store Error.object_desc for each error here.\n    generated_allowlist = set()\n\n    modules = args.modules\n    if args.check_typeshed:\n        if args.modules:\n            print(\n                _style(\"error:\", color=\"red\", bold=True),\n                \"cannot pass both --check-typeshed and a list of modules\",\n            )\n            return 1\n        typeshed_modules = get_typeshed_stdlib_modules(args.custom_typeshed_dir)\n        runtime_modules = get_importable_stdlib_modules()\n        modules = sorted((typeshed_modules | runtime_modules) - ANNOYING_STDLIB_MODULES)\n\n    if not modules:\n        print(_style(\"error:\", color=\"red\", bold=True), \"no modules to check\")\n        return 1\n\n    options = Options()\n    options.incremental = False\n    options.custom_typeshed_dir = args.custom_typeshed_dir\n    if options.custom_typeshed_dir:\n        options.abs_custom_typeshed_dir = os.path.abspath(options.custom_typeshed_dir)\n    options.config_file = args.mypy_config_file\n    options.use_builtins_fixtures = use_builtins_fixtures\n    options.show_traceback = args.show_traceback\n    options.pdb = args.pdb\n    options.pos_only_special_methods = False\n\n    if options.config_file:\n\n        def set_strict_flags() -> None:  # not needed yet\n            return\n\n        parse_config_file(options, set_strict_flags, options.config_file, sys.stdout, sys.stderr)\n\n    def error_callback(msg: str) -> typing.NoReturn:\n        print(_style(\"error:\", color=\"red\", bold=True), msg)\n        sys.exit(1)\n\n    def warning_callback(msg: str) -> None:\n        print(_style(\"warning:\", color=\"yellow\", bold=True), msg)\n\n    options.process_error_codes(error_callback=error_callback)\n    options.process_incomplete_features(\n        error_callback=error_callback, warning_callback=warning_callback\n    )\n    options.process_strict_bytes()\n\n    try:\n        modules = build_stubs(modules, options, find_submodules=not args.check_typeshed)\n    except StubtestFailure as stubtest_failure:\n        print(\n            _style(\"error:\", color=\"red\", bold=True),\n            f\"not checking stubs due to {stubtest_failure}\",\n        )\n        return 1\n\n    exit_code = 0\n    error_count = 0\n    for module in modules:\n        for error in test_module(module):\n            # Filter errors\n            if args.ignore_missing_stub and error.is_missing_stub():\n                continue\n            if args.ignore_positional_only and error.is_positional_only_related():\n                continue\n            if args.ignore_disjoint_bases and error.is_disjoint_base_related():\n                continue\n            if error.object_desc in allowlist:\n                allowlist[error.object_desc] = True\n                continue\n            is_allowlisted = False\n            for w in allowlist:\n                if allowlist_regexes[w].fullmatch(error.object_desc):\n                    allowlist[w] = True\n                    is_allowlisted = True\n                    break\n            if is_allowlisted:\n                continue\n\n            # We have errors, so change exit code, and output whatever necessary\n            exit_code = 1\n            if args.generate_allowlist:\n                generated_allowlist.add(error.object_desc)\n                continue\n            safe_print(error.get_description(concise=args.concise))\n            error_count += 1\n\n    # Print unused allowlist entries\n    if not args.ignore_unused_allowlist:\n        for w in allowlist:\n            # Don't consider an entry unused if it regex-matches the empty string\n            # This lets us allowlist errors that don't manifest at all on some systems\n            if not allowlist[w] and not allowlist_regexes[w].fullmatch(\"\"):\n                exit_code = 1\n                error_count += 1\n                print(f\"note: unused allowlist entry {w}\")\n\n    # Print the generated allowlist\n    if args.generate_allowlist:\n        for e in sorted(generated_allowlist):\n            print(e)\n        exit_code = 0\n    elif not args.concise:\n        if error_count:\n            print(\n                _style(\n                    f\"Found {error_count} error{plural_s(error_count)}\"\n                    f\" (checked {len(modules)} module{plural_s(modules)})\",\n                    color=\"red\",\n                    bold=True,\n                )\n            )\n        else:\n            print(\n                _style(\n                    f\"Success: no issues found in {len(modules)} module{plural_s(modules)}\",\n                    color=\"green\",\n                    bold=True,\n                )\n            )\n\n    return exit_code\n\n\ndef safe_print(text: str) -> None:\n    \"\"\"Print a text replacing chars not representable in stdout encoding.\"\"\"\n    # If `sys.stdout` encoding is not the same as out (usually UTF8) string,\n    # if may cause painful crashes. I don't want to reconfigure `sys.stdout`\n    # to do `errors = \"replace\"` as that sounds scary.\n    out_encoding = sys.stdout.encoding\n    if out_encoding is not None:\n        # Can be None if stdout is replaced (including our own tests). This should be\n        # safe to omit if the actual stream doesn't care about encoding.\n        text = text.encode(out_encoding, errors=\"replace\").decode(out_encoding, errors=\"replace\")\n    print(text)\n\n\ndef parse_options(args: list[str]) -> _Arguments:\n    parser = argparse.ArgumentParser(\n        description=\"Compares stubs to objects introspected from the runtime.\"\n    )\n    parser.add_argument(\"modules\", nargs=\"*\", help=\"Modules to test\")\n    parser.add_argument(\n        \"--concise\",\n        action=\"store_true\",\n        help=\"Makes stubtest's output more concise, one line per error\",\n    )\n    parser.add_argument(\n        \"--ignore-missing-stub\",\n        action=\"store_true\",\n        help=\"Ignore errors for stub missing things that are present at runtime\",\n    )\n    parser.add_argument(\n        \"--ignore-positional-only\",\n        action=\"store_true\",\n        help=\"Ignore errors for whether an argument should or shouldn't be positional-only\",\n    )\n    # TODO: Remove once PEP 800 is accepted\n    parser.add_argument(\n        \"--ignore-disjoint-bases\",\n        action=\"store_true\",\n        help=\"Disable checks for PEP 800 @disjoint_base classes\",\n    )\n    parser.add_argument(\n        \"--allowlist\",\n        \"--whitelist\",\n        action=\"append\",\n        metavar=\"FILE\",\n        default=[],\n        help=(\n            \"Use file as an allowlist. Can be passed multiple times to combine multiple \"\n            \"allowlists. Allowlists can be created with --generate-allowlist. Allowlists \"\n            \"support regular expressions.\"\n        ),\n    )\n    parser.add_argument(\n        \"--generate-allowlist\",\n        \"--generate-whitelist\",\n        action=\"store_true\",\n        help=\"Print an allowlist (to stdout) to be used with --allowlist\",\n    )\n    parser.add_argument(\n        \"--ignore-unused-allowlist\",\n        \"--ignore-unused-whitelist\",\n        action=\"store_true\",\n        help=\"Ignore unused allowlist entries\",\n    )\n    parser.add_argument(\n        \"--mypy-config-file\",\n        metavar=\"FILE\",\n        help=(\"Use specified mypy config file to determine mypy plugins and mypy path\"),\n    )\n    parser.add_argument(\n        \"--custom-typeshed-dir\", metavar=\"DIR\", help=\"Use the custom typeshed in DIR\"\n    )\n    parser.add_argument(\n        \"--check-typeshed\", action=\"store_true\", help=\"Check all stdlib modules in typeshed\"\n    )\n    parser.add_argument(\n        \"--version\", action=\"version\", version=\"%(prog)s \" + mypy.version.__version__\n    )\n    parser.add_argument(\"--pdb\", action=\"store_true\", help=\"Invoke pdb on fatal error\")\n    parser.add_argument(\n        \"--show-traceback\", \"--tb\", action=\"store_true\", help=\"Show traceback on fatal error\"\n    )\n\n    return parser.parse_args(args, namespace=_Arguments())\n\n\ndef main() -> int:\n    mypy.util.check_python_version(\"stubtest\")\n    return test_stubs(parse_options(sys.argv[1:]))\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())\n"
  },
  {
    "path": "mypy/stubutil.py",
    "content": "\"\"\"Utilities for mypy.stubgen, mypy.stubgenc, and mypy.stubdoc modules.\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\nimport re\nimport sys\nimport traceback\nfrom abc import abstractmethod\nfrom collections import defaultdict\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom contextlib import contextmanager\nfrom typing import Final, overload\n\nfrom mypy_extensions import mypyc_attr\n\nimport mypy.options\nfrom mypy.modulefinder import ModuleNotFoundReason\nfrom mypy.moduleinspect import InspectError, ModuleInspect\nfrom mypy.nodes import PARAM_SPEC_KIND, TYPE_VAR_TUPLE_KIND, ClassDef, FuncDef, TypeAliasStmt\nfrom mypy.stubdoc import ArgSig, FunctionSig\nfrom mypy.types import (\n    AnyType,\n    NoneType,\n    Type,\n    TypeList,\n    TypeStrVisitor,\n    UnboundType,\n    UnionType,\n    UnpackType,\n)\n\n# Modules that may fail when imported, or that may have side effects (fully qualified).\nNOT_IMPORTABLE_MODULES: tuple[str, ...] = ()\n\n# Typing constructs to be replaced by their builtin equivalents.\nTYPING_BUILTIN_REPLACEMENTS: Final = {\n    # From typing\n    \"typing.Text\": \"builtins.str\",\n    \"typing.Tuple\": \"builtins.tuple\",\n    \"typing.List\": \"builtins.list\",\n    \"typing.Dict\": \"builtins.dict\",\n    \"typing.Set\": \"builtins.set\",\n    \"typing.FrozenSet\": \"builtins.frozenset\",\n    \"typing.Type\": \"builtins.type\",\n    # From typing_extensions\n    \"typing_extensions.Text\": \"builtins.str\",\n    \"typing_extensions.Tuple\": \"builtins.tuple\",\n    \"typing_extensions.List\": \"builtins.list\",\n    \"typing_extensions.Dict\": \"builtins.dict\",\n    \"typing_extensions.Set\": \"builtins.set\",\n    \"typing_extensions.FrozenSet\": \"builtins.frozenset\",\n    \"typing_extensions.Type\": \"builtins.type\",\n}\n\n\nclass CantImport(Exception):\n    def __init__(self, module: str, message: str) -> None:\n        self.module = module\n        self.message = message\n\n\ndef walk_packages(\n    inspect: ModuleInspect, packages: list[str], verbose: bool = False\n) -> Iterator[str]:\n    \"\"\"Iterates through all packages and sub-packages in the given list.\n\n    This uses runtime imports (in another process) to find both Python and C modules.\n    For Python packages we simply pass the __path__ attribute to pkgutil.walk_packages() to\n    get the content of the package (all subpackages and modules).  However, packages in C\n    extensions do not have this attribute, so we have to roll out our own logic: recursively\n    find all modules imported in the package that have matching names.\n    \"\"\"\n    for package_name in packages:\n        if package_name in NOT_IMPORTABLE_MODULES:\n            print(f\"{package_name}: Skipped (blacklisted)\")\n            continue\n        if verbose:\n            print(f\"Trying to import {package_name!r} for runtime introspection\")\n        try:\n            prop = inspect.get_package_properties(package_name)\n        except InspectError:\n            if verbose:\n                tb = traceback.format_exc()\n                sys.stderr.write(tb)\n            report_missing(package_name)\n            continue\n        yield prop.name\n        if prop.is_c_module:\n            # Recursively iterate through the subpackages\n            yield from walk_packages(inspect, prop.subpackages, verbose)\n        else:\n            yield from prop.subpackages\n\n\ndef find_module_path_using_sys_path(module: str, sys_path: list[str]) -> str | None:\n    relative_candidates = (\n        module.replace(\".\", \"/\") + \".py\",\n        os.path.join(module.replace(\".\", \"/\"), \"__init__.py\"),\n    )\n    for base in sys_path:\n        for relative_path in relative_candidates:\n            path = os.path.join(base, relative_path)\n            if os.path.isfile(path):\n                return path\n    return None\n\n\ndef find_module_path_and_all_py3(\n    inspect: ModuleInspect, module: str, verbose: bool\n) -> tuple[str | None, list[str] | None] | None:\n    \"\"\"Find module and determine __all__ for a Python 3 module.\n\n    Return None if the module is a C or pyc-only module.\n    Return (module_path, __all__) if it is a Python module.\n    Raise CantImport if import failed.\n    \"\"\"\n    if module in NOT_IMPORTABLE_MODULES:\n        raise CantImport(module, \"\")\n\n    # TODO: Support custom interpreters.\n    if verbose:\n        print(f\"Trying to import {module!r} for runtime introspection\")\n    try:\n        mod = inspect.get_package_properties(module)\n    except InspectError as e:\n        # Fall back to finding the module using sys.path.\n        path = find_module_path_using_sys_path(module, sys.path)\n        if path is None:\n            raise CantImport(module, str(e)) from e\n        return path, None\n    if mod.is_c_module:\n        return None\n    return mod.file, mod.all\n\n\n@contextmanager\ndef generate_guarded(\n    mod: str, target: str, ignore_errors: bool = True, verbose: bool = False\n) -> Iterator[None]:\n    \"\"\"Ignore or report errors during stub generation.\n\n    Optionally report success.\n    \"\"\"\n    if verbose:\n        print(f\"Processing {mod}\")\n    try:\n        yield\n    except Exception as e:\n        if not ignore_errors:\n            raise e\n        else:\n            # --ignore-errors was passed\n            print(\"Stub generation failed for\", mod, file=sys.stderr)\n    else:\n        if verbose:\n            print(f\"Created {target}\")\n\n\ndef report_missing(mod: str, message: str | None = \"\", traceback: str = \"\") -> None:\n    if message:\n        message = \" with error: \" + message\n    print(f\"{mod}: Failed to import, skipping{message}\")\n\n\ndef fail_missing(mod: str, reason: ModuleNotFoundReason) -> None:\n    if reason is ModuleNotFoundReason.NOT_FOUND:\n        clarification = \"(consider using --search-path)\"\n    elif reason is ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS:\n        clarification = \"(module likely exists, but is not PEP 561 compatible)\"\n    else:\n        clarification = f\"(unknown reason '{reason}')\"\n    raise SystemExit(f\"Can't find module '{mod}' {clarification}\")\n\n\n@overload\ndef remove_misplaced_type_comments(source: bytes) -> bytes: ...\n\n\n@overload\ndef remove_misplaced_type_comments(source: str) -> str: ...\n\n\ndef remove_misplaced_type_comments(source: str | bytes) -> str | bytes:\n    \"\"\"Remove comments from source that could be understood as misplaced type comments.\n\n    Normal comments may look like misplaced type comments, and since they cause blocking\n    parse errors, we want to avoid them.\n    \"\"\"\n    if isinstance(source, bytes):\n        # This gives us a 1-1 character code mapping, so it's roundtrippable.\n        text = source.decode(\"latin1\")\n    else:\n        text = source\n\n    # Remove something that looks like a variable type comment but that's by itself\n    # on a line, as it will often generate a parse error (unless it's # type: ignore).\n    text = re.sub(r'^[ \\t]*# +type: +[\"\\'a-zA-Z_].*$', \"\", text, flags=re.MULTILINE)\n\n    # Remove something that looks like a function type comment after docstring,\n    # which will result in a parse error.\n    text = re.sub(r'\"\"\" *\\n[ \\t\\n]*# +type: +\\(.*$', '\"\"\"\\n', text, flags=re.MULTILINE)\n    text = re.sub(r\"''' *\\n[ \\t\\n]*# +type: +\\(.*$\", \"'''\\n\", text, flags=re.MULTILINE)\n\n    # Remove something that looks like a badly formed function type comment.\n    text = re.sub(r\"^[ \\t]*# +type: +\\([^()]+(\\)[ \\t]*)?$\", \"\", text, flags=re.MULTILINE)\n\n    if isinstance(source, bytes):\n        return text.encode(\"latin1\")\n    else:\n        return text\n\n\ndef common_dir_prefix(paths: list[str]) -> str:\n    if not paths:\n        return \".\"\n    cur = os.path.dirname(os.path.normpath(paths[0]))\n    for path in paths[1:]:\n        while True:\n            path = os.path.dirname(os.path.normpath(path))\n            if (cur + os.sep).startswith(path + os.sep):\n                cur = path\n                break\n    return cur or \".\"\n\n\nclass AnnotationPrinter(TypeStrVisitor):\n    \"\"\"Visitor used to print existing annotations in a file.\n\n    The main difference from TypeStrVisitor is a better treatment of\n    unbound types.\n\n    Notes:\n    * This visitor doesn't add imports necessary for annotations, this is done separately\n      by ImportTracker.\n    * It can print all kinds of types, but the generated strings may not be valid (notably\n      callable types) since it prints the same string that reveal_type() does.\n    * For Instance types it prints the fully qualified names.\n    \"\"\"\n\n    # TODO: Generate valid string representation for callable types.\n    # TODO: Use short names for Instances.\n    def __init__(\n        self,\n        stubgen: BaseStubGenerator,\n        known_modules: list[str] | None = None,\n        local_modules: list[str] | None = None,\n    ) -> None:\n        super().__init__(options=mypy.options.Options())\n        self.stubgen = stubgen\n        self.known_modules = known_modules\n        self.local_modules = local_modules or [\"builtins\"]\n\n    def visit_any(self, t: AnyType) -> str:\n        s = super().visit_any(t)\n        self.stubgen.import_tracker.require_name(s)\n        return s\n\n    def visit_unbound_type(self, t: UnboundType) -> str:\n        s = t.name\n        fullname = self.stubgen.resolve_name(s)\n        if fullname == \"typing.Union\":\n            return \" | \".join([item.accept(self) for item in t.args])\n        if fullname == \"typing.Optional\":\n            if len(t.args) == 1:\n                return f\"{t.args[0].accept(self)} | None\"\n            return self.stubgen.add_name(\"_typeshed.Incomplete\")\n        if fullname in TYPING_BUILTIN_REPLACEMENTS:\n            s = self.stubgen.add_name(TYPING_BUILTIN_REPLACEMENTS[fullname], require=True)\n        if self.known_modules is not None and \".\" in s:\n            # see if this object is from any of the modules that we're currently processing.\n            # reverse sort so that subpackages come before parents: e.g. \"foo.bar\" before \"foo\".\n            for module_name in self.local_modules + sorted(self.known_modules, reverse=True):\n                if s.startswith(module_name + \".\"):\n                    if module_name in self.local_modules:\n                        s = s[len(module_name) + 1 :]\n                    arg_module = module_name\n                    break\n            else:\n                arg_module = s[: s.rindex(\".\")]\n            if arg_module not in self.local_modules:\n                self.stubgen.import_tracker.add_import(arg_module, require=True)\n        elif s == \"NoneType\":\n            # when called without analysis all types are unbound, so this won't hit\n            # visit_none_type().\n            s = \"None\"\n        else:\n            self.stubgen.import_tracker.require_name(s)\n        if t.args:\n            s += f\"[{self.args_str(t.args)}]\"\n        elif t.empty_tuple_index:\n            s += \"[()]\"\n        return s\n\n    def visit_none_type(self, t: NoneType) -> str:\n        return \"None\"\n\n    def visit_type_list(self, t: TypeList) -> str:\n        return f\"[{self.list_str(t.items)}]\"\n\n    def visit_union_type(self, t: UnionType) -> str:\n        return \" | \".join([item.accept(self) for item in t.items])\n\n    def visit_unpack_type(self, t: UnpackType) -> str:\n        if self.options.python_version >= (3, 11):\n            return f\"*{t.type.accept(self)}\"\n        return super().visit_unpack_type(t)\n\n    def args_str(self, args: Iterable[Type]) -> str:\n        \"\"\"Convert an array of arguments to strings and join the results with commas.\n\n        The main difference from list_str is the preservation of quotes for string\n        arguments\n        \"\"\"\n        types = [\"builtins.bytes\", \"builtins.str\"]\n        res = []\n        for arg in args:\n            arg_str = arg.accept(self)\n            if isinstance(arg, UnboundType) and arg.original_str_fallback in types:\n                res.append(f\"'{arg_str}'\")\n            else:\n                res.append(arg_str)\n        return \", \".join(res)\n\n\nclass ClassInfo:\n    def __init__(\n        self,\n        name: str,\n        self_var: str,\n        docstring: str | None = None,\n        cls: type | None = None,\n        parent: ClassInfo | None = None,\n    ) -> None:\n        self.name = name\n        self.self_var = self_var\n        self.docstring = docstring\n        self.cls = cls\n        self.parent = parent\n\n\nclass FunctionContext:\n    def __init__(\n        self,\n        module_name: str,\n        name: str,\n        docstring: str | None = None,\n        is_abstract: bool = False,\n        class_info: ClassInfo | None = None,\n    ) -> None:\n        self.module_name = module_name\n        self.name = name\n        self.docstring = docstring\n        self.is_abstract = is_abstract\n        self.class_info = class_info\n        self._fullname: str | None = None\n\n    @property\n    def fullname(self) -> str:\n        if self._fullname is None:\n            if self.class_info:\n                parents = []\n                class_info: ClassInfo | None = self.class_info\n                while class_info is not None:\n                    parents.append(class_info.name)\n                    class_info = class_info.parent\n                namespace = \".\".join(reversed(parents))\n                self._fullname = f\"{self.module_name}.{namespace}.{self.name}\"\n            else:\n                self._fullname = f\"{self.module_name}.{self.name}\"\n        return self._fullname\n\n\ndef infer_method_ret_type(name: str) -> str | None:\n    \"\"\"Infer return types for known special methods\"\"\"\n    if name.startswith(\"__\") and name.endswith(\"__\"):\n        name = name[2:-2]\n        if name in (\"float\", \"bool\", \"bytes\", \"int\", \"complex\", \"str\"):\n            return name\n        # Note: __eq__ and co may return arbitrary types, but bool is good enough for stubgen.\n        elif name in (\"eq\", \"ne\", \"lt\", \"le\", \"gt\", \"ge\", \"contains\"):\n            return \"bool\"\n        elif name in (\"len\", \"length_hint\", \"index\", \"hash\", \"sizeof\", \"trunc\", \"floor\", \"ceil\"):\n            return \"int\"\n        elif name in (\"format\", \"repr\"):\n            return \"str\"\n        elif name in (\"init\", \"setitem\", \"del\", \"delitem\"):\n            return \"None\"\n    return None\n\n\ndef infer_method_arg_types(\n    name: str, self_var: str = \"self\", arg_names: list[str] | None = None\n) -> list[ArgSig] | None:\n    \"\"\"Infer argument types for known special methods\"\"\"\n    args: list[ArgSig] | None = None\n    if name.startswith(\"__\") and name.endswith(\"__\"):\n        if arg_names and len(arg_names) >= 1 and arg_names[0] == \"self\":\n            arg_names = arg_names[1:]\n\n        name = name[2:-2]\n        if name == \"exit\":\n            if arg_names is None:\n                arg_names = [\"type\", \"value\", \"traceback\"]\n            if len(arg_names) == 3:\n                arg_types = [\n                    \"type[BaseException] | None\",\n                    \"BaseException | None\",\n                    \"types.TracebackType | None\",\n                ]\n                args = [\n                    ArgSig(name=arg_name, type=arg_type)\n                    for arg_name, arg_type in zip(arg_names, arg_types)\n                ]\n    if args is not None:\n        return [ArgSig(name=self_var)] + args\n    return None\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass SignatureGenerator:\n    \"\"\"Abstract base class for extracting a list of FunctionSigs for each function.\"\"\"\n\n    def remove_self_type(\n        self, inferred: list[FunctionSig] | None, self_var: str\n    ) -> list[FunctionSig] | None:\n        \"\"\"Remove type annotation from self/cls argument\"\"\"\n        if inferred:\n            for signature in inferred:\n                if signature.args:\n                    if signature.args[0].name == self_var:\n                        signature.args[0].type = None\n        return inferred\n\n    @abstractmethod\n    def get_function_sig(\n        self, default_sig: FunctionSig, ctx: FunctionContext\n    ) -> list[FunctionSig] | None:\n        \"\"\"Return a list of signatures for the given function.\n\n        If no signature can be found, return None. If all of the registered SignatureGenerators\n        for the stub generator return None, then the default_sig will be used.\n        \"\"\"\n        pass\n\n    @abstractmethod\n    def get_property_type(self, default_type: str | None, ctx: FunctionContext) -> str | None:\n        \"\"\"Return the type of the given property\"\"\"\n        pass\n\n\nclass ImportTracker:\n    \"\"\"Record necessary imports during stub generation.\"\"\"\n\n    def __init__(self) -> None:\n        # module_for['foo'] has the module name where 'foo' was imported from, or None if\n        # 'foo' is a module imported directly;\n        # direct_imports['foo'] is the module path used when the name 'foo' was added to the\n        # namespace.\n        # reverse_alias['foo'] is the name that 'foo' had originally when imported with an\n        # alias; examples\n        #     'from pkg import mod'      ==> module_for['mod'] == 'pkg'\n        #     'from pkg import mod as m' ==> module_for['m'] == 'pkg'\n        #                                ==> reverse_alias['m'] == 'mod'\n        #     'import pkg.mod as m'      ==> module_for['m'] == None\n        #                                ==> reverse_alias['m'] == 'pkg.mod'\n        #     'import pkg.mod'           ==> module_for['pkg'] == None\n        #                                ==> module_for['pkg.mod'] == None\n        #                                ==> direct_imports['pkg'] == 'pkg.mod'\n        #                                ==> direct_imports['pkg.mod'] == 'pkg.mod'\n        self.module_for: dict[str, str | None] = {}\n        self.direct_imports: dict[str, str] = {}\n        self.reverse_alias: dict[str, str] = {}\n\n        # required_names is the set of names that are actually used in a type annotation\n        self.required_names: set[str] = set()\n\n        # Names that should be reexported if they come from another module\n        self.reexports: set[str] = set()\n\n    def add_import_from(\n        self, module: str, names: list[tuple[str, str | None]], require: bool = False\n    ) -> None:\n        for name, alias in names:\n            if alias:\n                # 'from {module} import {name} as {alias}'\n                self.module_for[alias] = module\n                self.reverse_alias[alias] = name\n            else:\n                # 'from {module} import {name}'\n                self.module_for[name] = module\n                self.reverse_alias.pop(name, None)\n            if require:\n                self.require_name(alias or name)\n            self.direct_imports.pop(alias or name, None)\n\n    def add_import(self, module: str, alias: str | None = None, require: bool = False) -> None:\n        if alias:\n            # 'import {module} as {alias}'\n            assert \".\" not in alias  # invalid syntax\n            self.module_for[alias] = None\n            self.reverse_alias[alias] = module\n            if require:\n                self.required_names.add(alias)\n        else:\n            # 'import {module}'\n            name = module\n            if require:\n                self.required_names.add(name)\n            # add module and its parent packages\n            while name:\n                self.module_for[name] = None\n                self.direct_imports[name] = module\n                self.reverse_alias.pop(name, None)\n                name = name.rpartition(\".\")[0]\n\n    def require_name(self, name: str) -> None:\n        while name not in self.direct_imports and \".\" in name:\n            name = name.rsplit(\".\", 1)[0]\n        self.required_names.add(name)\n\n    def reexport(self, name: str) -> None:\n        \"\"\"Mark a given non qualified name as needed in __all__.\n\n        This means that in case it comes from a module, it should be\n        imported with an alias even if the alias is the same as the name.\n        \"\"\"\n        self.require_name(name)\n        self.reexports.add(name)\n\n    def import_lines(self) -> list[str]:\n        \"\"\"The list of required import lines (as strings with python code).\n\n        In order for a module be included in this output, an identifier must be both\n        'required' via require_name() and 'imported' via add_import_from()\n        or add_import()\n        \"\"\"\n        result = []\n\n        # To summarize multiple names imported from a same module, we collect those\n        # in the `module_map` dictionary, mapping a module path to the list of names that should\n        # be imported from it. the names can also be alias in the form 'original as alias'\n        module_map: Mapping[str, list[str]] = defaultdict(list)\n\n        for name in sorted(\n            self.required_names,\n            key=lambda n: (self.reverse_alias[n], n) if n in self.reverse_alias else (n, \"\"),\n        ):\n            # If we haven't seen this name in an import statement, ignore it\n            if name not in self.module_for:\n                continue\n\n            m = self.module_for[name]\n            if m is not None:\n                # This name was found in a from ... import ...\n                # Collect the name in the module_map\n                if name in self.reverse_alias:\n                    name = f\"{self.reverse_alias[name]} as {name}\"\n                elif name in self.reexports:\n                    name = f\"{name} as {name}\"\n                module_map[m].append(name)\n            else:\n                # This name was found in an import ...\n                # We can already generate the import line\n                if name in self.reverse_alias:\n                    source = self.reverse_alias[name]\n                    result.append(f\"import {source} as {name}\\n\")\n                elif name in self.reexports:\n                    assert \".\" not in name  # Because reexports only has nonqualified names\n                    result.append(f\"import {name} as {name}\\n\")\n                else:\n                    result.append(f\"import {name}\\n\")\n\n        # Now generate all the from ... import ... lines collected in module_map\n        for module, names in sorted(module_map.items()):\n            result.append(f\"from {module} import {', '.join(sorted(names))}\\n\")\n        return result\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass BaseStubGenerator:\n    # These names should be omitted from generated stubs.\n    IGNORED_DUNDERS: Final = {\n        \"__all__\",\n        \"__author__\",\n        \"__about__\",\n        \"__copyright__\",\n        \"__email__\",\n        \"__license__\",\n        \"__summary__\",\n        \"__title__\",\n        \"__uri__\",\n        \"__str__\",\n        \"__repr__\",\n        \"__getstate__\",\n        \"__setstate__\",\n        \"__slots__\",\n        \"__builtins__\",\n        \"__cached__\",\n        \"__file__\",\n        \"__name__\",\n        \"__package__\",\n        \"__path__\",\n        \"__spec__\",\n        \"__loader__\",\n    }\n    TYPING_MODULE_NAMES: Final = (\"typing\", \"typing_extensions\")\n    # Special-cased names that are implicitly exported from the stub (from m import y as y).\n    EXTRA_EXPORTED: Final = {\n        \"pyasn1_modules.rfc2437.univ\",\n        \"pyasn1_modules.rfc2459.char\",\n        \"pyasn1_modules.rfc2459.univ\",\n    }\n\n    def __init__(\n        self,\n        _all_: list[str] | None = None,\n        include_private: bool = False,\n        export_less: bool = False,\n        include_docstrings: bool = False,\n    ) -> None:\n        # Best known value of __all__.\n        self._all_ = _all_\n        self._include_private = include_private\n        self._include_docstrings = include_docstrings\n        # Disable implicit exports of package-internal imports?\n        self.export_less = export_less\n        self._import_lines: list[str] = []\n        self._output: list[str] = []\n        # Current indent level (indent is hardcoded to 4 spaces).\n        self._indent = \"\"\n        self._toplevel_names: list[str] = []\n        self.import_tracker = ImportTracker()\n        # Top-level members\n        self.defined_names: set[str] = set()\n        self.sig_generators = self.get_sig_generators()\n        # populated by visit_mypy_file\n        self.module_name: str = \"\"\n        # These are \"soft\" imports for objects which might appear in annotations but not have\n        # a corresponding import statement.\n        self.known_imports = {\n            \"_typeshed\": [\"Incomplete\"],\n            \"typing\": [\"Any\", \"TypeVar\", \"NamedTuple\", \"TypedDict\"],\n            \"collections.abc\": [\"Generator\"],\n            \"typing_extensions\": [\"ParamSpec\", \"TypeVarTuple\"],\n        }\n\n    def get_sig_generators(self) -> list[SignatureGenerator]:\n        return []\n\n    def resolve_name(self, name: str) -> str:\n        \"\"\"Return the full name resolving imports and import aliases.\"\"\"\n        if \".\" not in name:\n            real_module = self.import_tracker.module_for.get(name)\n            real_short = self.import_tracker.reverse_alias.get(name, name)\n            if real_module is None and real_short not in self.defined_names:\n                real_module = \"builtins\"  # not imported and not defined, must be a builtin\n        else:\n            name_module, real_short = name.split(\".\", 1)\n            real_module = self.import_tracker.reverse_alias.get(name_module, name_module)\n        resolved_name = real_short if real_module is None else f\"{real_module}.{real_short}\"\n        return resolved_name\n\n    def add_name(self, fullname: str, require: bool = True) -> str:\n        \"\"\"Add a name to be imported and return the name reference.\n\n        The import will be internal to the stub (i.e don't reexport).\n        \"\"\"\n        module, name = fullname.rsplit(\".\", 1)\n        alias = \"_\" + name if name in self.defined_names else None\n        while alias in self.defined_names:\n            alias = \"_\" + alias\n        if module != \"builtins\" or alias:  # don't import from builtins unless needed\n            self.import_tracker.add_import_from(module, [(name, alias)], require=require)\n        return alias or name\n\n    def add_import_line(self, line: str) -> None:\n        \"\"\"Add a line of text to the import section, unless it's already there.\"\"\"\n        if line not in self._import_lines:\n            self._import_lines.append(line)\n\n    def get_imports(self) -> str:\n        \"\"\"Return the import statements for the stub.\"\"\"\n        imports = \"\"\n        if self._import_lines:\n            imports += \"\".join(self._import_lines)\n        imports += \"\".join(self.import_tracker.import_lines())\n        return imports\n\n    def output(self) -> str:\n        \"\"\"Return the text for the stub.\"\"\"\n        pieces: list[str] = []\n        if imports := self.get_imports():\n            pieces.append(imports)\n        if dunder_all := self.get_dunder_all():\n            pieces.append(dunder_all)\n        if self._output:\n            pieces.append(\"\".join(self._output))\n        return \"\\n\".join(pieces)\n\n    def get_dunder_all(self) -> str:\n        \"\"\"Return the __all__ list for the stub.\"\"\"\n        if self._all_:\n            # Note we emit all names in the runtime __all__ here, even if they\n            # don't actually exist. If that happens, the runtime has a bug, and\n            # it's not obvious what the correct behavior should be. We choose\n            # to reflect the runtime __all__ as closely as possible.\n            return f\"__all__ = {self._all_!r}\\n\"\n        return \"\"\n\n    def add(self, string: str) -> None:\n        \"\"\"Add text to generated stub.\"\"\"\n        self._output.append(string)\n\n    def is_top_level(self) -> bool:\n        \"\"\"Are we processing the top level of a file?\"\"\"\n        return self._indent == \"\"\n\n    def indent(self) -> None:\n        \"\"\"Add one level of indentation.\"\"\"\n        self._indent += \"    \"\n\n    def dedent(self) -> None:\n        \"\"\"Remove one level of indentation.\"\"\"\n        self._indent = self._indent[:-4]\n\n    def record_name(self, name: str) -> None:\n        \"\"\"Mark a name as defined.\n\n        This only does anything if at the top level of a module.\n        \"\"\"\n        if self.is_top_level():\n            self._toplevel_names.append(name)\n\n    def is_recorded_name(self, name: str) -> bool:\n        \"\"\"Has this name been recorded previously?\"\"\"\n        return self.is_top_level() and name in self._toplevel_names\n\n    def set_defined_names(self, defined_names: set[str]) -> None:\n        self.defined_names = defined_names\n        # Names in __all__ are required\n        for name in self._all_ or ():\n            self.import_tracker.reexport(name)\n\n        for pkg, imports in self.known_imports.items():\n            for t in imports:\n                # require=False means that the import won't be added unless require_name() is called\n                # for the object during generation.\n                self.add_name(f\"{pkg}.{t}\", require=False)\n\n    def check_undefined_names(self) -> None:\n        undefined_names = [name for name in self._all_ or [] if name not in self._toplevel_names]\n        if undefined_names:\n            if self._output:\n                self.add(\"\\n\")\n            self.add(\"# Names in __all__ with no definition:\\n\")\n            for name in sorted(undefined_names):\n                self.add(f\"#   {name}\\n\")\n\n    def get_signatures(\n        self,\n        default_signature: FunctionSig,\n        sig_generators: list[SignatureGenerator],\n        func_ctx: FunctionContext,\n    ) -> list[FunctionSig]:\n        for sig_gen in sig_generators:\n            inferred = sig_gen.get_function_sig(default_signature, func_ctx)\n            if inferred:\n                return inferred\n\n        return [default_signature]\n\n    def get_property_type(\n        self,\n        default_type: str | None,\n        sig_generators: list[SignatureGenerator],\n        func_ctx: FunctionContext,\n    ) -> str | None:\n        for sig_gen in sig_generators:\n            inferred = sig_gen.get_property_type(default_type, func_ctx)\n            if inferred:\n                return inferred\n\n        return default_type\n\n    def format_func_def(\n        self,\n        sigs: list[FunctionSig],\n        is_coroutine: bool = False,\n        decorators: list[str] | None = None,\n        docstring: str | None = None,\n    ) -> list[str]:\n        lines: list[str] = []\n        if decorators is None:\n            decorators = []\n\n        for signature in sigs:\n            # dump decorators, just before \"def ...\"\n            for deco in decorators:\n                lines.append(f\"{self._indent}{deco}\")\n\n            lines.append(\n                signature.format_sig(\n                    indent=self._indent,\n                    is_async=is_coroutine,\n                    docstring=docstring,\n                    include_docstrings=self._include_docstrings,\n                )\n            )\n        return lines\n\n    def format_type_args(self, o: TypeAliasStmt | FuncDef | ClassDef) -> str:\n        if not o.type_args:\n            return \"\"\n        p = AnnotationPrinter(self)\n        type_args_list: list[str] = []\n        for type_arg in o.type_args:\n            if type_arg.kind == PARAM_SPEC_KIND:\n                prefix = \"**\"\n            elif type_arg.kind == TYPE_VAR_TUPLE_KIND:\n                prefix = \"*\"\n            else:\n                prefix = \"\"\n            if type_arg.upper_bound:\n                bound_or_values = f\": {type_arg.upper_bound.accept(p)}\"\n            elif type_arg.values:\n                bound_or_values = f\": ({', '.join(v.accept(p) for v in type_arg.values)})\"\n            else:\n                bound_or_values = \"\"\n            if type_arg.default:\n                default = f\" = {type_arg.default.accept(p)}\"\n            else:\n                default = \"\"\n            type_args_list.append(f\"{prefix}{type_arg.name}{bound_or_values}{default}\")\n        return \"[\" + \", \".join(type_args_list) + \"]\"\n\n    def print_annotation(\n        self,\n        t: Type,\n        known_modules: list[str] | None = None,\n        local_modules: list[str] | None = None,\n    ) -> str:\n        printer = AnnotationPrinter(self, known_modules, local_modules)\n        return t.accept(printer)\n\n    def is_not_in_all(self, name: str) -> bool:\n        if self.is_private_name(name):\n            return False\n        if self._all_:\n            return self.is_top_level() and name not in self._all_\n        return False\n\n    def is_private_name(self, name: str, fullname: str | None = None) -> bool:\n        if \"__mypy-\" in name:\n            return True  # Never include mypy generated symbols\n        if self._include_private:\n            return False\n        if fullname in self.EXTRA_EXPORTED:\n            return False\n        if name == \"_\":\n            return False\n        if not name.startswith(\"_\"):\n            return False\n        if self._all_ and name in self._all_:\n            return False\n        if name.startswith(\"__\") and name.endswith(\"__\"):\n            return name in self.IGNORED_DUNDERS\n        return True\n\n    def should_reexport(self, name: str, full_module: str, name_is_alias: bool) -> bool:\n        if (\n            not name_is_alias\n            and self.module_name\n            and (self.module_name + \".\" + name) in self.EXTRA_EXPORTED\n        ):\n            # Special case certain names that should be exported, against our general rules.\n            return True\n        if name_is_alias:\n            return False\n        if self.export_less:\n            return False\n        if not self.module_name:\n            return False\n        is_private = self.is_private_name(name, full_module + \".\" + name)\n        if is_private:\n            return False\n        top_level = full_module.split(\".\")[0]\n        self_top_level = self.module_name.split(\".\", 1)[0]\n        if top_level not in (self_top_level, \"_\" + self_top_level):\n            # Export imports from the same package, since we can't reliably tell whether they\n            # are part of the public API.\n            return False\n        if self._all_:\n            return name in self._all_\n        return True\n"
  },
  {
    "path": "mypy/subtypes.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Callable, Iterable, Iterator\nfrom contextlib import contextmanager\nfrom typing import Any, Final, TypeAlias as _TypeAlias, TypeVar, cast\n\nimport mypy.applytype\nimport mypy.constraints\nimport mypy.typeops\nfrom mypy.checker_state import checker_state\nfrom mypy.erasetype import erase_type\nfrom mypy.expandtype import (\n    expand_self_type,\n    expand_type,\n    expand_type_by_instance,\n    freshen_function_type_vars,\n)\nfrom mypy.maptype import map_instance_to_supertype\n\n# Circular import; done in the function instead.\n# import mypy.solve\nfrom mypy.nodes import (\n    ARG_STAR,\n    ARG_STAR2,\n    CONTRAVARIANT,\n    COVARIANT,\n    INVARIANT,\n    VARIANCE_NOT_READY,\n    Context,\n    Decorator,\n    FuncBase,\n    OverloadedFuncDef,\n    TypeInfo,\n    Var,\n)\nfrom mypy.options import Options\nfrom mypy.state import state\nfrom mypy.types import (\n    MYPYC_NATIVE_INT_NAMES,\n    TUPLE_LIKE_INSTANCE_NAMES,\n    TYPED_NAMEDTUPLE_NAMES,\n    AnyType,\n    CallableType,\n    DeletedType,\n    ErasedType,\n    FormalArgument,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    NormalizedCallableType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeType,\n    TypeVarTupleType,\n    TypeVarType,\n    TypeVisitor,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    find_unpack_in_list,\n    flatten_nested_unions,\n    get_proper_type,\n    is_named_instance,\n    split_with_prefix_and_suffix,\n)\nfrom mypy.types_utils import flatten_types\nfrom mypy.typestate import SubtypeKind, type_state\nfrom mypy.typevars import fill_typevars, fill_typevars_with_any\n\n# Flags for detected protocol members\nIS_SETTABLE: Final = 1\nIS_CLASSVAR: Final = 2\nIS_CLASS_OR_STATIC: Final = 3\nIS_VAR: Final = 4\nIS_EXPLICIT_SETTER: Final = 5\n\nTypeParameterChecker: _TypeAlias = Callable[[Type, Type, int, bool, \"SubtypeContext\"], bool]\n\n\nclass SubtypeContext:\n    def __init__(\n        self,\n        *,\n        # Non-proper subtype flags\n        ignore_type_params: bool = False,\n        ignore_pos_arg_names: bool = False,\n        ignore_declared_variance: bool = False,\n        # Supported for both proper and non-proper\n        always_covariant: bool = False,\n        ignore_promotions: bool = False,\n        # Proper subtype flags\n        erase_instances: bool = False,\n        keep_erased_types: bool = False,\n        options: Options | None = None,\n    ) -> None:\n        self.ignore_type_params = ignore_type_params\n        self.ignore_pos_arg_names = ignore_pos_arg_names\n        self.ignore_declared_variance = ignore_declared_variance\n        self.always_covariant = always_covariant\n        self.ignore_promotions = ignore_promotions\n        self.erase_instances = erase_instances\n        self.keep_erased_types = keep_erased_types\n        self.options = options\n\n    def check_context(self, proper_subtype: bool) -> None:\n        # Historically proper and non-proper subtypes were defined using different helpers\n        # and different visitors. Check if flag values are such that we definitely support.\n        if proper_subtype:\n            assert not self.ignore_pos_arg_names and not self.ignore_declared_variance\n        else:\n            assert not self.erase_instances and not self.keep_erased_types\n\n\ndef is_subtype(\n    left: Type,\n    right: Type,\n    *,\n    subtype_context: SubtypeContext | None = None,\n    ignore_type_params: bool = False,\n    ignore_pos_arg_names: bool = False,\n    ignore_declared_variance: bool = False,\n    always_covariant: bool = False,\n    ignore_promotions: bool = False,\n    options: Options | None = None,\n) -> bool:\n    \"\"\"Is 'left' subtype of 'right'?\n\n    Also consider Any to be a subtype of any type, and vice versa. This\n    recursively applies to components of composite types (List[int] is subtype\n    of List[Any], for example).\n\n    type_parameter_checker is used to check the type parameters (for example,\n    A with B in is_subtype(C[A], C[B]). The default checks for subtype relation\n    between the type arguments (e.g., A and B), taking the variance of the\n    type var into account.\n    \"\"\"\n    if left == right:\n        return True\n    if subtype_context is None:\n        subtype_context = SubtypeContext(\n            ignore_type_params=ignore_type_params,\n            ignore_pos_arg_names=ignore_pos_arg_names,\n            ignore_declared_variance=ignore_declared_variance,\n            always_covariant=always_covariant,\n            ignore_promotions=ignore_promotions,\n            options=options,\n        )\n    else:\n        assert (\n            not ignore_type_params\n            and not ignore_pos_arg_names\n            and not ignore_declared_variance\n            and not always_covariant\n            and not ignore_promotions\n            and options is None\n        ), \"Don't pass both context and individual flags\"\n    if type_state.is_assumed_subtype(left, right):\n        return True\n    if mypy.typeops.is_recursive_pair(left, right):\n        # This case requires special care because it may cause infinite recursion.\n        # Our view on recursive types is known under a fancy name of iso-recursive mu-types.\n        # Roughly this means that a recursive type is defined as an alias where right hand side\n        # can refer to the type as a whole, for example:\n        #     A = Union[int, Tuple[A, ...]]\n        # and an alias unrolled once represents the *same type*, in our case all these represent\n        # the same type:\n        #    A\n        #    Union[int, Tuple[A, ...]]\n        #    Union[int, Tuple[Union[int, Tuple[A, ...]], ...]]\n        # The algorithm for subtyping is then essentially under the assumption that left <: right,\n        # check that get_proper_type(left) <: get_proper_type(right). On the example above,\n        # If we start with:\n        #     A = Union[int, Tuple[A, ...]]\n        #     B = Union[int, Tuple[B, ...]]\n        # When checking if A <: B we push pair (A, B) onto 'assuming' stack, then when after few\n        # steps we come back to initial call is_subtype(A, B) and immediately return True.\n        with pop_on_exit(type_state.get_assumptions(is_proper=False), left, right):\n            return _is_subtype(left, right, subtype_context, proper_subtype=False)\n    return _is_subtype(left, right, subtype_context, proper_subtype=False)\n\n\ndef is_proper_subtype(\n    left: Type,\n    right: Type,\n    *,\n    subtype_context: SubtypeContext | None = None,\n    ignore_promotions: bool = False,\n    erase_instances: bool = False,\n    keep_erased_types: bool = False,\n) -> bool:\n    \"\"\"Is left a proper subtype of right?\n\n    For proper subtypes, there's no need to rely on compatibility due to\n    Any types. Every usable type is a proper subtype of itself.\n\n    If erase_instances is True, erase left instance *after* mapping it to supertype\n    (this is useful for runtime isinstance() checks). If keep_erased_types is True,\n    do not consider ErasedType a subtype of all types (used by type inference against unions).\n    \"\"\"\n    if left == right:\n        return True\n    if subtype_context is None:\n        subtype_context = SubtypeContext(\n            ignore_promotions=ignore_promotions,\n            erase_instances=erase_instances,\n            keep_erased_types=keep_erased_types,\n        )\n    else:\n        assert (\n            not ignore_promotions and not erase_instances and not keep_erased_types\n        ), \"Don't pass both context and individual flags\"\n    if type_state.is_assumed_proper_subtype(left, right):\n        return True\n    if mypy.typeops.is_recursive_pair(left, right):\n        # Same as for non-proper subtype, see detailed comment there for explanation.\n        with pop_on_exit(type_state.get_assumptions(is_proper=True), left, right):\n            return _is_subtype(left, right, subtype_context, proper_subtype=True)\n    return _is_subtype(left, right, subtype_context, proper_subtype=True)\n\n\ndef is_equivalent(\n    a: Type,\n    b: Type,\n    *,\n    ignore_type_params: bool = False,\n    ignore_pos_arg_names: bool = False,\n    options: Options | None = None,\n    subtype_context: SubtypeContext | None = None,\n) -> bool:\n    return is_subtype(\n        a,\n        b,\n        ignore_type_params=ignore_type_params,\n        ignore_pos_arg_names=ignore_pos_arg_names,\n        options=options,\n        subtype_context=subtype_context,\n    ) and is_subtype(\n        b,\n        a,\n        ignore_type_params=ignore_type_params,\n        ignore_pos_arg_names=ignore_pos_arg_names,\n        options=options,\n        subtype_context=subtype_context,\n    )\n\n\ndef is_same_type(\n    a: Type, b: Type, ignore_promotions: bool = True, subtype_context: SubtypeContext | None = None\n) -> bool:\n    \"\"\"Are these types proper subtypes of each other?\n\n    This means types may have different representation (e.g. an alias, or\n    a non-simplified union) but are semantically exchangeable in all contexts.\n    \"\"\"\n    # First, use fast path for some common types. This is performance-critical.\n    if (\n        type(a) is Instance\n        and type(b) is Instance\n        and a.type == b.type\n        and len(a.args) == len(b.args)\n        and a.last_known_value is b.last_known_value\n    ):\n        return all(is_same_type(x, y) for x, y in zip(a.args, b.args))\n    elif (\n        isinstance(a, TypeVarType)\n        and isinstance(b, TypeVarType)\n        and a.id == b.id\n        and a.upper_bound == b.upper_bound\n    ):\n        return True\n\n    # Note that using ignore_promotions=True (default) makes types like int and int64\n    # considered not the same type (which is the case at runtime).\n    # Also Union[bool, int] (if it wasn't simplified before) will be different\n    # from plain int, etc.\n    return is_proper_subtype(\n        a, b, ignore_promotions=ignore_promotions, subtype_context=subtype_context\n    ) and is_proper_subtype(\n        b, a, ignore_promotions=ignore_promotions, subtype_context=subtype_context\n    )\n\n\n# This is a common entry point for subtyping checks (both proper and non-proper).\n# Never call this private function directly, use the public versions.\ndef _is_subtype(\n    left: Type, right: Type, subtype_context: SubtypeContext, proper_subtype: bool\n) -> bool:\n    subtype_context.check_context(proper_subtype)\n    orig_right = right\n    orig_left = left\n    left = get_proper_type(left)\n    right = get_proper_type(right)\n\n    # Note: Unpack type should not be a subtype of Any, since it may represent\n    # multiple types. This should always go through the visitor, to check arity.\n    if (\n        not proper_subtype\n        and isinstance(right, (AnyType, UnboundType, ErasedType))\n        and not isinstance(left, UnpackType)\n    ):\n        # TODO: should we consider all types proper subtypes of UnboundType and/or\n        # ErasedType as we do for non-proper subtyping.\n        return True\n\n    if isinstance(right, UnionType) and not isinstance(left, UnionType):\n        # Normally, when 'left' is not itself a union, the only way\n        # 'left' can be a subtype of the union 'right' is if it is a\n        # subtype of one of the items making up the union.\n        if proper_subtype:\n            is_subtype_of_item = any(\n                is_proper_subtype(orig_left, item, subtype_context=subtype_context)\n                for item in right.items\n            )\n        else:\n            is_subtype_of_item = any(\n                is_subtype(orig_left, item, subtype_context=subtype_context)\n                for item in right.items\n            )\n        # Recombine rhs literal types, to make an enum type a subtype\n        # of a union of all enum items as literal types. Only do it if\n        # the previous check didn't succeed, since recombining can be\n        # expensive.\n        # `bool` is a special case, because `bool` is `Literal[True, False]`.\n        if (\n            not is_subtype_of_item\n            and isinstance(left, Instance)\n            and (left.type.is_enum or left.type.fullname == \"builtins.bool\")\n        ):\n            right = UnionType(\n                mypy.typeops.try_contracting_literals_in_union(flatten_nested_unions(right.items))\n            )\n            if proper_subtype:\n                is_subtype_of_item = any(\n                    is_proper_subtype(orig_left, item, subtype_context=subtype_context)\n                    for item in right.items\n                )\n            else:\n                is_subtype_of_item = any(\n                    is_subtype(orig_left, item, subtype_context=subtype_context)\n                    for item in right.items\n                )\n        # However, if 'left' is a type variable T, T might also have\n        # an upper bound which is itself a union. This case will be\n        # handled below by the SubtypeVisitor. We have to check both\n        # possibilities, to handle both cases like T <: Union[T, U]\n        # and cases like T <: B where B is the upper bound of T and is\n        # a union. (See #2314.)\n        if not isinstance(left, TypeVarType):\n            return is_subtype_of_item\n        elif is_subtype_of_item:\n            return True\n        # otherwise, fall through\n    return left.accept(SubtypeVisitor(orig_right, subtype_context, proper_subtype))\n\n\ndef check_type_parameter(\n    left: Type, right: Type, variance: int, proper_subtype: bool, subtype_context: SubtypeContext\n) -> bool:\n    # It is safe to consider empty collection literals and similar as covariant, since\n    # such type can't be stored in a variable, see checker.is_valid_inferred_type().\n    if variance == INVARIANT:\n        p_left = get_proper_type(left)\n        if isinstance(p_left, UninhabitedType) and p_left.ambiguous:\n            variance = COVARIANT\n    # If variance hasn't been inferred yet, we are lenient and default to\n    # covariance. This shouldn't happen often, but it's very difficult to\n    # avoid these cases altogether.\n    if variance == COVARIANT or variance == VARIANCE_NOT_READY:\n        if proper_subtype:\n            return is_proper_subtype(left, right, subtype_context=subtype_context)\n        else:\n            return is_subtype(left, right, subtype_context=subtype_context)\n    elif variance == CONTRAVARIANT:\n        if proper_subtype:\n            return is_proper_subtype(right, left, subtype_context=subtype_context)\n        else:\n            return is_subtype(right, left, subtype_context=subtype_context)\n    else:\n        if proper_subtype:\n            # We pass ignore_promotions=False because it is a default for subtype checks.\n            # The actual value will be taken from the subtype_context, and it is whatever\n            # the original caller passed.\n            return is_same_type(\n                left, right, ignore_promotions=False, subtype_context=subtype_context\n            )\n        else:\n            return is_equivalent(left, right, subtype_context=subtype_context)\n\n\nclass SubtypeVisitor(TypeVisitor[bool]):\n    __slots__ = (\n        \"right\",\n        \"orig_right\",\n        \"proper_subtype\",\n        \"subtype_context\",\n        \"options\",\n        \"_subtype_kind\",\n    )\n\n    def __init__(self, right: Type, subtype_context: SubtypeContext, proper_subtype: bool) -> None:\n        self.right = get_proper_type(right)\n        self.orig_right = right\n        self.proper_subtype = proper_subtype\n        self.subtype_context = subtype_context\n        self.options = subtype_context.options\n        self._subtype_kind = SubtypeVisitor.build_subtype_kind(subtype_context, proper_subtype)\n\n    @staticmethod\n    def build_subtype_kind(subtype_context: SubtypeContext, proper_subtype: bool) -> SubtypeKind:\n        return (\n            state.strict_optional,\n            proper_subtype,\n            subtype_context.ignore_type_params,\n            subtype_context.ignore_pos_arg_names,\n            subtype_context.ignore_declared_variance,\n            subtype_context.always_covariant,\n            subtype_context.ignore_promotions,\n            subtype_context.erase_instances,\n            subtype_context.keep_erased_types,\n        )\n\n    def _is_subtype(self, left: Type, right: Type) -> bool:\n        if self.proper_subtype:\n            return is_proper_subtype(left, right, subtype_context=self.subtype_context)\n        return is_subtype(left, right, subtype_context=self.subtype_context)\n\n    def _all_subtypes(self, lefts: Iterable[Type], rights: Iterable[Type]) -> bool:\n        return all(self._is_subtype(li, ri) for (li, ri) in zip(lefts, rights))\n\n    # visit_x(left) means: is left (which is an instance of X) a subtype of right?\n\n    def visit_unbound_type(self, left: UnboundType) -> bool:\n        # This can be called if there is a bad type annotation. The result probably\n        # doesn't matter much but by returning True we simplify these bad types away\n        # from unions, which could filter out some bogus messages.\n        return True\n\n    def visit_any(self, left: AnyType) -> bool:\n        return isinstance(self.right, AnyType) if self.proper_subtype else True\n\n    def visit_none_type(self, left: NoneType) -> bool:\n        if state.strict_optional:\n            if isinstance(self.right, NoneType) or is_named_instance(\n                self.right, \"builtins.object\"\n            ):\n                return True\n            if isinstance(self.right, Instance) and self.right.type.is_protocol:\n                members = self.right.type.protocol_members\n                # None is compatible with Hashable (and other similar protocols). This is\n                # slightly sloppy since we don't check the signature of \"__hash__\".\n                # None is also compatible with `SupportsStr` protocol.\n                return not members or all(member in (\"__hash__\", \"__str__\") for member in members)\n            return False\n        else:\n            return True\n\n    def visit_uninhabited_type(self, left: UninhabitedType) -> bool:\n        return True\n\n    def visit_erased_type(self, left: ErasedType) -> bool:\n        # This may be encountered during type inference. The result probably doesn't\n        # matter much.\n        # TODO: it actually does matter, figure out more principled logic about this.\n        return not self.subtype_context.keep_erased_types\n\n    def visit_deleted_type(self, left: DeletedType) -> bool:\n        return True\n\n    def visit_instance(self, left: Instance) -> bool:\n        if left.type.fallback_to_any and not self.proper_subtype:\n            # NOTE: `None` is a *non-subclassable* singleton, therefore no class\n            # can by a subtype of it, even with an `Any` fallback.\n            # This special case is needed to treat descriptors in classes with\n            # dynamic base classes correctly, see #5456.\n            return not isinstance(self.right, NoneType)\n        right = self.right\n        if isinstance(right, TupleType) and right.partial_fallback.type.is_enum:\n            return self._is_subtype(left, mypy.typeops.tuple_fallback(right))\n        if isinstance(right, TupleType):\n            if len(right.items) == 1:\n                # Non-normalized Tuple type (may be left after semantic analysis\n                # because semanal_typearg visitor is not a type translator).\n                item = right.items[0]\n                if isinstance(item, UnpackType):\n                    unpacked = get_proper_type(item.type)\n                    if isinstance(unpacked, Instance):\n                        return self._is_subtype(left, unpacked)\n            if left.type.has_base(right.partial_fallback.type.fullname):\n                if not self.proper_subtype:\n                    # Special cases to consider:\n                    #   * Plain tuple[Any, ...] instance is a subtype of all tuple types.\n                    #   * Foo[*tuple[Any, ...]] (normalized) instance is a subtype of all\n                    #     tuples with fallback to Foo (e.g. for variadic NamedTuples).\n                    mapped = map_instance_to_supertype(left, right.partial_fallback.type)\n                    if is_erased_instance(mapped):\n                        if (\n                            mapped.type.fullname == \"builtins.tuple\"\n                            or mapped.type.has_type_var_tuple_type\n                        ):\n                            return True\n            return False\n        if isinstance(right, TypeVarTupleType):\n            # tuple[Any, ...] is like Any in the world of tuples (see special case above).\n            if left.type.has_base(\"builtins.tuple\"):\n                mapped = map_instance_to_supertype(left, right.tuple_fallback.type)\n                if isinstance(get_proper_type(mapped.args[0]), AnyType):\n                    return not self.proper_subtype\n        if isinstance(right, Instance):\n            if type_state.is_cached_subtype_check(self._subtype_kind, left, right):\n                return True\n            if type_state.is_cached_negative_subtype_check(self._subtype_kind, left, right):\n                return False\n            if not self.subtype_context.ignore_promotions and not right.type.is_protocol:\n                for base in left.type.mro:\n                    if base._promote and any(\n                        self._is_subtype(p, self.right) for p in base._promote\n                    ):\n                        type_state.record_subtype_cache_entry(self._subtype_kind, left, right)\n                        return True\n                # Special case: Low-level integer types are compatible with 'int'. We can't\n                # use promotions, since 'int' is already promoted to low-level integer types,\n                # and we can't have circular promotions.\n                if left.type.alt_promote and left.type.alt_promote.type is right.type:\n                    return True\n            rname = right.type.fullname\n            # Always try a nominal check if possible,\n            # there might be errors that a user wants to silence *once*.\n            # NamedTuples are a special case, because `NamedTuple` is not listed\n            # in `TypeInfo.mro`, so when `(a: NamedTuple) -> None` is used,\n            # we need to check for `is_named_tuple` property\n            if (\n                left.type.has_base(rname)\n                or rname == \"builtins.object\"\n                or (\n                    rname in TYPED_NAMEDTUPLE_NAMES\n                    and any(l.is_named_tuple for l in left.type.mro)\n                )\n            ) and not self.subtype_context.ignore_declared_variance:\n                # Map left type to corresponding right instances.\n                t = map_instance_to_supertype(left, right.type)\n                if self.subtype_context.erase_instances:\n                    erased = erase_type(t)\n                    assert isinstance(erased, Instance)\n                    t = erased\n                nominal = True\n                if right.type.has_type_var_tuple_type:\n                    # For variadic instances we simply find the correct type argument mappings,\n                    # all the heavy lifting is done by the tuple subtyping.\n                    assert right.type.type_var_tuple_prefix is not None\n                    assert right.type.type_var_tuple_suffix is not None\n                    prefix = right.type.type_var_tuple_prefix\n                    suffix = right.type.type_var_tuple_suffix\n                    tvt = right.type.defn.type_vars[prefix]\n                    assert isinstance(tvt, TypeVarTupleType)\n                    fallback = tvt.tuple_fallback\n                    left_prefix, left_middle, left_suffix = split_with_prefix_and_suffix(\n                        t.args, prefix, suffix\n                    )\n                    right_prefix, right_middle, right_suffix = split_with_prefix_and_suffix(\n                        right.args, prefix, suffix\n                    )\n                    left_args = (\n                        left_prefix + (TupleType(list(left_middle), fallback),) + left_suffix\n                    )\n                    right_args = (\n                        right_prefix + (TupleType(list(right_middle), fallback),) + right_suffix\n                    )\n                    if not self.proper_subtype and is_erased_instance(t):\n                        return True\n                    if len(left_args) != len(right_args):\n                        return False\n                    type_params = zip(left_args, right_args, right.type.defn.type_vars)\n                else:\n                    type_params = zip(t.args, right.args, right.type.defn.type_vars)\n                if not self.subtype_context.ignore_type_params:\n                    tried_infer = False\n                    for lefta, righta, tvar in type_params:\n                        if isinstance(tvar, TypeVarType):\n                            if tvar.variance == VARIANCE_NOT_READY and not tried_infer:\n                                infer_class_variances(right.type)\n                                tried_infer = True\n                            if (\n                                self.subtype_context.always_covariant\n                                and tvar.variance == INVARIANT\n                            ):\n                                variance = COVARIANT\n                            else:\n                                variance = tvar.variance\n                            if not check_type_parameter(\n                                lefta, righta, variance, self.proper_subtype, self.subtype_context\n                            ):\n                                nominal = False\n                        else:\n                            # TODO: everywhere else ParamSpecs are handled as invariant.\n                            if not check_type_parameter(\n                                lefta, righta, COVARIANT, self.proper_subtype, self.subtype_context\n                            ):\n                                nominal = False\n                if nominal:\n                    type_state.record_subtype_cache_entry(self._subtype_kind, left, right)\n                else:\n                    type_state.record_negative_subtype_cache_entry(self._subtype_kind, left, right)\n                return nominal\n            if right.type.is_protocol and is_protocol_implementation(\n                left, right, proper_subtype=self.proper_subtype, options=self.options\n            ):\n                return True\n            # We record negative cache entry here, and not in the protocol check like we do for\n            # positive cache, to avoid accidentally adding a type that is not a structural\n            # subtype, but is a nominal subtype (involving type: ignore override).\n            type_state.record_negative_subtype_cache_entry(self._subtype_kind, left, right)\n            return False\n        if isinstance(right, TypeType):\n            item = right.item\n            if isinstance(item, TupleType):\n                item = mypy.typeops.tuple_fallback(item)\n            # TODO: this is a bit arbitrary, we should only skip Any-related cases.\n            if not self.proper_subtype:\n                if is_named_instance(left, \"builtins.type\"):\n                    return self._is_subtype(TypeType(AnyType(TypeOfAny.special_form)), right)\n                if left.type.is_metaclass():\n                    if isinstance(item, AnyType):\n                        return True\n                    if isinstance(item, Instance):\n                        return is_named_instance(item, \"builtins.object\")\n        if isinstance(right, LiteralType) and left.last_known_value is not None:\n            return self._is_subtype(left.last_known_value, right)\n        if isinstance(right, FunctionLike):\n            # Special case: Instance can be a subtype of Callable / Overloaded.\n            call = find_member(\"__call__\", left, left, is_operator=True)\n            if call:\n                return self._is_subtype(call, right)\n            return False\n        else:\n            return False\n\n    def visit_type_var(self, left: TypeVarType) -> bool:\n        right = self.right\n        if isinstance(right, TypeVarType) and left.id == right.id:\n            # Fast path for most common case.\n            if left.upper_bound == right.upper_bound:\n                return True\n            # Corner case for self-types in classes generic in type vars\n            # with value restrictions.\n            if left.id.is_self():\n                return True\n            return self._is_subtype(left.upper_bound, right.upper_bound)\n        if left.values and self._is_subtype(UnionType.make_union(left.values), right):\n            return True\n        return self._is_subtype(left.upper_bound, self.right)\n\n    def visit_param_spec(self, left: ParamSpecType) -> bool:\n        right = self.right\n        if (\n            isinstance(right, ParamSpecType)\n            and right.id == left.id\n            and right.flavor == left.flavor\n        ):\n            return self._is_subtype(left.prefix, right.prefix)\n        if isinstance(right, Parameters) and are_trivial_parameters(right):\n            return True\n        return self._is_subtype(left.upper_bound, self.right)\n\n    def visit_type_var_tuple(self, left: TypeVarTupleType) -> bool:\n        right = self.right\n        if isinstance(right, TypeVarTupleType) and right.id == left.id:\n            return left.min_len >= right.min_len\n        return self._is_subtype(left.upper_bound, self.right)\n\n    def visit_unpack_type(self, left: UnpackType) -> bool:\n        # TODO: Ideally we should not need this (since it is not a real type).\n        # Instead callers (upper level types) should handle it when it appears in type list.\n        if isinstance(self.right, UnpackType):\n            return self._is_subtype(left.type, self.right.type)\n        if isinstance(self.right, Instance) and self.right.type.fullname == \"builtins.object\":\n            return True\n        return False\n\n    def visit_parameters(self, left: Parameters) -> bool:\n        if isinstance(self.right, Parameters):\n            return are_parameters_compatible(\n                left,\n                self.right,\n                is_compat=self._is_subtype,\n                # TODO: this should pass the current value, but then couple tests fail.\n                is_proper_subtype=False,\n                ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names,\n            )\n        elif isinstance(self.right, Instance):\n            return self.right.type.fullname == \"builtins.object\"\n        else:\n            return False\n\n    def visit_callable_type(self, left: CallableType) -> bool:\n        right = self.right\n        if isinstance(right, CallableType):\n            if left.type_guard is not None and right.type_guard is not None:\n                if not self._is_subtype(left.type_guard, right.type_guard):\n                    return False\n            elif left.type_is is not None and right.type_is is not None:\n                # For TypeIs we have to check both ways; it is unsafe to pass\n                # a TypeIs[Child] when a TypeIs[Parent] is expected, because\n                # if the narrower returns False, we assume that the narrowed value is\n                # *not* a Parent.\n                if not self._is_subtype(left.type_is, right.type_is) or not self._is_subtype(\n                    right.type_is, left.type_is\n                ):\n                    return False\n            elif right.type_guard is not None and left.type_guard is None:\n                # This means that one function has `TypeGuard` and other does not.\n                # They are not compatible. See https://github.com/python/mypy/issues/11307\n                return False\n            elif right.type_is is not None and left.type_is is None:\n                # Similarly, if one function has `TypeIs` and the other does not,\n                # they are not compatible.\n                return False\n            return is_callable_compatible(\n                left,\n                right,\n                is_compat=self._is_subtype,\n                is_proper_subtype=self.proper_subtype,\n                ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names,\n                strict_concatenate=(\n                    (self.options.extra_checks or self.options.strict_concatenate)\n                    if self.options\n                    else False\n                ),\n            )\n        elif isinstance(right, Overloaded):\n            return all(self._is_subtype(left, item) for item in right.items)\n        elif isinstance(right, Instance):\n            if right.type.is_protocol and \"__call__\" in right.type.protocol_members:\n                # OK, a callable can implement a protocol with a `__call__` member.\n                call = find_member(\"__call__\", right, right, is_operator=True)\n                assert call is not None\n                if self._is_subtype(left, call):\n                    if len(right.type.protocol_members) == 1:\n                        return True\n                    if is_protocol_implementation(left.fallback, right, skip=[\"__call__\"]):\n                        return True\n            if right.type.is_protocol and left.is_type_obj():\n                ret_type = get_proper_type(left.ret_type)\n                if isinstance(ret_type, TupleType):\n                    ret_type = mypy.typeops.tuple_fallback(ret_type)\n                if isinstance(ret_type, Instance) and is_protocol_implementation(\n                    ret_type, right, proper_subtype=self.proper_subtype, class_obj=True\n                ):\n                    return True\n            return self._is_subtype(left.fallback, right)\n        elif isinstance(right, TypeType):\n            # This is unsound, we don't check the __init__ signature.\n            return left.is_type_obj() and self._is_subtype(left.ret_type, right.item)\n        else:\n            return False\n\n    def visit_tuple_type(self, left: TupleType) -> bool:\n        right = self.right\n        if isinstance(right, Instance):\n            if is_named_instance(right, \"typing.Sized\"):\n                return True\n            elif is_named_instance(right, TUPLE_LIKE_INSTANCE_NAMES):\n                if right.args:\n                    iter_type = right.args[0]\n                else:\n                    if self.proper_subtype:\n                        return False\n                    iter_type = AnyType(TypeOfAny.special_form)\n                if is_named_instance(right, \"builtins.tuple\") and isinstance(\n                    get_proper_type(iter_type), AnyType\n                ):\n                    # TODO: We shouldn't need this special case. This is currently needed\n                    #       for isinstance(x, tuple), though it's unclear why.\n                    return True\n                for li in left.items:\n                    if isinstance(li, UnpackType):\n                        unpack = get_proper_type(li.type)\n                        if isinstance(unpack, TypeVarTupleType):\n                            unpack = get_proper_type(unpack.upper_bound)\n                        assert (\n                            isinstance(unpack, Instance)\n                            and unpack.type.fullname == \"builtins.tuple\"\n                        )\n                        li = unpack.args[0]\n                    if not self._is_subtype(li, iter_type):\n                        return False\n                return True\n            elif self._is_subtype(left.partial_fallback, right) and self._is_subtype(\n                mypy.typeops.tuple_fallback(left), right\n            ):\n                return True\n            return False\n        elif isinstance(right, TupleType):\n            # If right has a variadic unpack this needs special handling. If there is a TypeVarTuple\n            # unpack, item count must coincide. If the left has variadic unpack but right\n            # doesn't have one, we will fall through to False down the line.\n            if self.variadic_tuple_subtype(left, right):\n                return True\n            if len(left.items) != len(right.items):\n                return False\n            if any(not self._is_subtype(l, r) for l, r in zip(left.items, right.items)):\n                return False\n            if is_named_instance(right.partial_fallback, \"builtins.tuple\"):\n                # No need to verify fallback. This is useful since the calculated fallback\n                # may be inconsistent due to how we calculate joins between unions vs.\n                # non-unions. For example, join(int, str) == object, whereas\n                # join(Union[int, C], Union[str, C]) == Union[int, str, C].\n                return True\n            if is_named_instance(left.partial_fallback, \"builtins.tuple\"):\n                # Again, no need to verify. At this point we know the right fallback\n                # is a subclass of tuple, so if left is plain tuple, it cannot be a subtype.\n                return False\n            # At this point we know both fallbacks are non-tuple.\n            return self._is_subtype(left.partial_fallback, right.partial_fallback)\n        else:\n            return False\n\n    def variadic_tuple_subtype(self, left: TupleType, right: TupleType) -> bool:\n        \"\"\"Check subtyping between two potentially variadic tuples.\n\n        Most non-trivial cases here are due to variadic unpacks like *tuple[X, ...],\n        we handle such unpacks as infinite unions Tuple[()] | Tuple[X] | Tuple[X, X] | ...\n\n        Note: the cases where right is fixed or has *Ts unpack should be handled\n        by the caller.\n        \"\"\"\n        right_unpack_index = find_unpack_in_list(right.items)\n        if right_unpack_index is None:\n            # This case should be handled by the caller.\n            return False\n        right_unpack = right.items[right_unpack_index]\n        assert isinstance(right_unpack, UnpackType)\n        right_unpacked = get_proper_type(right_unpack.type)\n        if not isinstance(right_unpacked, Instance):\n            # This case should be handled by the caller.\n            return False\n        assert right_unpacked.type.fullname == \"builtins.tuple\"\n        right_item = right_unpacked.args[0]\n        right_prefix = right_unpack_index\n        right_suffix = len(right.items) - right_prefix - 1\n        left_unpack_index = find_unpack_in_list(left.items)\n        if left_unpack_index is None:\n            # Simple case: left is fixed, simply find correct mapping to the right\n            # (effectively selecting item with matching length from an infinite union).\n            if len(left.items) < right_prefix + right_suffix:\n                return False\n            prefix, middle, suffix = split_with_prefix_and_suffix(\n                tuple(left.items), right_prefix, right_suffix\n            )\n            if not all(\n                self._is_subtype(li, ri) for li, ri in zip(prefix, right.items[:right_prefix])\n            ):\n                return False\n            if right_suffix and not all(\n                self._is_subtype(li, ri) for li, ri in zip(suffix, right.items[-right_suffix:])\n            ):\n                return False\n            return all(self._is_subtype(li, right_item) for li in middle)\n        else:\n            if len(left.items) < len(right.items):\n                # There are some items on the left that will never have a matching length\n                # on the right.\n                return False\n            left_prefix = left_unpack_index\n            left_suffix = len(left.items) - left_prefix - 1\n            left_unpack = left.items[left_unpack_index]\n            assert isinstance(left_unpack, UnpackType)\n            left_unpacked = get_proper_type(left_unpack.type)\n            if not isinstance(left_unpacked, Instance):\n                # *Ts unpack can't be split, except if it is all mapped to Anys or objects.\n                if self.is_top_type(right_item):\n                    right_prefix_types, middle, right_suffix_types = split_with_prefix_and_suffix(\n                        tuple(right.items), left_prefix, left_suffix\n                    )\n                    if not all(\n                        self.is_top_type(ri) or isinstance(ri, UnpackType) for ri in middle\n                    ):\n                        return False\n                    # Also check the tails match as well.\n                    return self._all_subtypes(\n                        left.items[:left_prefix], right_prefix_types\n                    ) and self._all_subtypes(left.items[-left_suffix:], right_suffix_types)\n                return False\n            assert left_unpacked.type.fullname == \"builtins.tuple\"\n            left_item = left_unpacked.args[0]\n\n            # The most tricky case with two variadic unpacks we handle similar to union\n            # subtyping: *each* item on the left, must be a subtype of *some* item on the right.\n            # For this we first check the \"asymptotic case\", i.e. that both unpacks a subtypes,\n            # and then check subtyping for all finite overlaps.\n            if not self._is_subtype(left_item, right_item):\n                return False\n            max_overlap = max(0, right_prefix - left_prefix, right_suffix - left_suffix)\n            for overlap in range(max_overlap + 1):\n                repr_items = left.items[:left_prefix] + [left_item] * overlap\n                if left_suffix:\n                    repr_items += left.items[-left_suffix:]\n                left_repr = left.copy_modified(items=repr_items)\n                if not self._is_subtype(left_repr, right):\n                    return False\n            return True\n\n    def is_top_type(self, typ: Type) -> bool:\n        if not self.proper_subtype and isinstance(get_proper_type(typ), AnyType):\n            return True\n        return is_named_instance(typ, \"builtins.object\")\n\n    def visit_typeddict_type(self, left: TypedDictType) -> bool:\n        right = self.right\n        if isinstance(right, Instance):\n            return self._is_subtype(left.fallback, right)\n        elif isinstance(right, TypedDictType):\n            if left == right:\n                return True  # Fast path\n            if not left.names_are_wider_than(right):\n                return False\n            for name, l, r in left.zip(right):\n                # TODO: should we pass on the full subtype_context here and below?\n                right_readonly = name in right.readonly_keys\n                if not right_readonly:\n                    if self.proper_subtype:\n                        check = is_same_type(l, r)\n                    else:\n                        check = is_equivalent(\n                            l,\n                            r,\n                            ignore_type_params=self.subtype_context.ignore_type_params,\n                            options=self.options,\n                        )\n                else:\n                    # Read-only items behave covariantly\n                    check = self._is_subtype(l, r)\n                if not check:\n                    return False\n                # Non-required key is not compatible with a required key since\n                # indexing may fail unexpectedly if a required key is missing.\n                # Required key is not compatible with a non-read-only non-required\n                # key since the prior doesn't support 'del' but the latter should\n                # support it.\n                # Required key is compatible with a read-only non-required key.\n                required_differ = (name in left.required_keys) != (name in right.required_keys)\n                if not right_readonly and required_differ:\n                    return False\n                # Readonly fields check:\n                #\n                # A = TypedDict('A', {'x': ReadOnly[int]})\n                # B = TypedDict('B', {'x': int})\n                # def reset_x(b: B) -> None:\n                #     b['x'] = 0\n                #\n                # So, `A` cannot be a subtype of `B`, while `B` can be a subtype of `A`,\n                # because you can use `B` everywhere you use `A`, but not the other way around.\n                if name in left.readonly_keys and name not in right.readonly_keys:\n                    return False\n            # (NOTE: Fallbacks don't matter.)\n            return True\n        else:\n            return False\n\n    def visit_literal_type(self, left: LiteralType) -> bool:\n        if isinstance(self.right, LiteralType):\n            return left == self.right\n        else:\n            return self._is_subtype(left.fallback, self.right)\n\n    def visit_overloaded(self, left: Overloaded) -> bool:\n        right = self.right\n        if isinstance(right, Instance):\n            if right.type.is_protocol and \"__call__\" in right.type.protocol_members:\n                # same as for CallableType\n                call = find_member(\"__call__\", right, right, is_operator=True)\n                assert call is not None\n                if self._is_subtype(left, call):\n                    if len(right.type.protocol_members) == 1:\n                        return True\n                    if is_protocol_implementation(left.fallback, right, skip=[\"__call__\"]):\n                        return True\n            return self._is_subtype(left.fallback, right)\n        elif isinstance(right, CallableType):\n            for item in left.items:\n                if self._is_subtype(item, right):\n                    return True\n            return False\n        elif isinstance(right, Overloaded):\n            if left == self.right:\n                # When it is the same overload, then the types are equal.\n                return True\n\n            # Ensure each overload on the right side (the supertype) is accounted for.\n            previous_match_left_index = -1\n            matched_overloads = set()\n\n            for right_item in right.items:\n                found_match = False\n\n                for left_index, left_item in enumerate(left.items):\n                    subtype_match = self._is_subtype(left_item, right_item)\n\n                    # Order matters: we need to make sure that the index of\n                    # this item is at least the index of the previous one.\n                    if subtype_match and previous_match_left_index <= left_index:\n                        previous_match_left_index = left_index\n                        found_match = True\n                        matched_overloads.add(left_index)\n                        break\n                    else:\n                        # If this one overlaps with the supertype in any way, but it wasn't\n                        # an exact match, then it's a potential error.\n                        strict_concat = (\n                            (self.options.extra_checks or self.options.strict_concatenate)\n                            if self.options\n                            else False\n                        )\n                        if left_index not in matched_overloads and (\n                            is_callable_compatible(\n                                left_item,\n                                right_item,\n                                is_compat=self._is_subtype,\n                                is_proper_subtype=self.proper_subtype,\n                                ignore_return=True,\n                                ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names,\n                                strict_concatenate=strict_concat,\n                            )\n                            or is_callable_compatible(\n                                right_item,\n                                left_item,\n                                is_compat=self._is_subtype,\n                                is_proper_subtype=self.proper_subtype,\n                                ignore_return=True,\n                                ignore_pos_arg_names=self.subtype_context.ignore_pos_arg_names,\n                                strict_concatenate=strict_concat,\n                            )\n                        ):\n                            return False\n\n                if not found_match:\n                    return False\n            return True\n        elif isinstance(right, UnboundType):\n            return True\n        elif isinstance(right, TypeType):\n            # All the items must have the same type object status, so\n            # it's sufficient to query only (any) one of them.\n            # This is unsound, we don't check all the __init__ signatures.\n            return left.is_type_obj() and self._is_subtype(left.items[0], right)\n        else:\n            return False\n\n    def visit_union_type(self, left: UnionType) -> bool:\n        if isinstance(self.right, Instance):\n            literal_types: set[Instance] = set()\n            # avoid redundant check for union of literals\n            for item in left.relevant_items():\n                p_item = get_proper_type(item)\n                lit_type = mypy.typeops.simple_literal_type(p_item)\n                if lit_type is not None:\n                    if lit_type in literal_types:\n                        continue\n                    literal_types.add(lit_type)\n                    item = lit_type\n                if not self._is_subtype(item, self.orig_right):\n                    return False\n            return True\n\n        elif isinstance(self.right, UnionType):\n            # prune literals early to avoid nasty quadratic behavior which would otherwise arise when checking\n            # subtype relationships between slightly different narrowings of an Enum\n            # we achieve O(N+M) instead of O(N*M)\n\n            fast_check: set[ProperType] = set()\n\n            for item in flatten_types(self.right.relevant_items()):\n                p_item = get_proper_type(item)\n                fast_check.add(p_item)\n                if isinstance(p_item, Instance) and p_item.last_known_value is not None:\n                    fast_check.add(p_item.last_known_value)\n\n            for item in left.relevant_items():\n                p_item = get_proper_type(item)\n                if p_item in fast_check:\n                    continue\n                lit_type = mypy.typeops.simple_literal_type(p_item)\n                if lit_type in fast_check:\n                    continue\n                if not self._is_subtype(item, self.orig_right):\n                    return False\n            return True\n\n        return all(self._is_subtype(item, self.orig_right) for item in left.items)\n\n    def visit_partial_type(self, left: PartialType) -> bool:\n        # This is indeterminate as we don't really know the complete type yet.\n        if self.proper_subtype:\n            # TODO: What's the right thing to do here?\n            return False\n        if left.type is None:\n            # Special case, partial `None`. This might happen when defining\n            # class-level attributes with explicit `None`.\n            # We can still recover from this.\n            # https://github.com/python/mypy/issues/11105\n            return self.visit_none_type(NoneType())\n        raise RuntimeError(f'Partial type \"{left}\" cannot be checked with \"issubtype()\"')\n\n    def visit_type_type(self, left: TypeType) -> bool:\n        right = self.right\n        if left.is_type_form:\n            if isinstance(right, TypeType):\n                if not right.is_type_form:\n                    return False\n                return self._is_subtype(left.item, right.item)\n            if isinstance(right, Instance):\n                if right.type.fullname == \"builtins.object\":\n                    return True\n                return False\n            return False\n        else:  # not left.is_type_form\n            if isinstance(right, TypeType):\n                return self._is_subtype(left.item, right.item)\n            if isinstance(right, Overloaded) and right.is_type_obj():\n                # Same as in other direction: if it's a constructor callable, all\n                # items should belong to the same class' constructor, so it's enough\n                # to check one of them.\n                return self._is_subtype(left, right.items[0])\n            if isinstance(right, CallableType):\n                if self.proper_subtype and not right.is_type_obj():\n                    # We can't accept `Type[X]` as a *proper* subtype of Callable[P, X]\n                    # since this will break transitivity of subtyping.\n                    return False\n                # This is unsound, we don't check the __init__ signature.\n                return self._is_subtype(left.item, right.ret_type)\n\n            if isinstance(right, Instance):\n                if right.type.fullname in [\"builtins.object\", \"builtins.type\"]:\n                    # TODO: Strictly speaking, the type builtins.type is considered equivalent to\n                    #       Type[Any]. However, this would break the is_proper_subtype check in\n                    #       conditional_types for cases like isinstance(x, type) when the type\n                    #       of x is Type[int]. It's unclear what's the right way to address this.\n                    return True\n                item = left.item\n                if isinstance(item, TypeVarType):\n                    item = get_proper_type(item.upper_bound)\n                if isinstance(item, Instance):\n                    if right.type.is_protocol and is_protocol_implementation(\n                        item, right, proper_subtype=self.proper_subtype, class_obj=True\n                    ):\n                        return True\n                    metaclass = item.type.metaclass_type\n                    return metaclass is not None and self._is_subtype(metaclass, right)\n            return False\n\n    def visit_type_alias_type(self, left: TypeAliasType) -> bool:\n        assert False, f\"This should be never called, got {left}\"\n\n\nT = TypeVar(\"T\", bound=Type)\n\n\n@contextmanager\ndef pop_on_exit(stack: list[tuple[T, T]], left: T, right: T) -> Iterator[None]:\n    stack.append((left, right))\n    yield\n    stack.pop()\n\n\ndef is_protocol_implementation(\n    left: Instance,\n    right: Instance,\n    proper_subtype: bool = False,\n    class_obj: bool = False,\n    skip: list[str] | None = None,\n    options: Options | None = None,\n) -> bool:\n    \"\"\"Check whether 'left' implements the protocol 'right'.\n\n    If 'proper_subtype' is True, then check for a proper subtype.\n    Treat recursive protocols by using the 'assuming' structural subtype matrix\n    (in sparse representation, i.e. as a list of pairs (subtype, supertype)),\n    see also comment in nodes.TypeInfo. When we enter a check for classes\n    (A, P), defined as following::\n\n      class P(Protocol):\n          def f(self) -> P: ...\n      class A:\n          def f(self) -> A: ...\n\n    this results in A being a subtype of P without infinite recursion.\n    On every false result, we pop the assumption, thus avoiding an infinite recursion\n    as well.\n    \"\"\"\n    assert right.type.is_protocol\n    if skip is None:\n        skip = []\n    # We need to record this check to generate protocol fine-grained dependencies.\n    type_state.record_protocol_subtype_check(left.type, right.type)\n    # nominal subtyping currently ignores '__init__' and '__new__' signatures\n    members_not_to_check = {\"__init__\", \"__new__\"}\n    members_not_to_check.update(skip)\n    # Trivial check that circumvents the bug described in issue 9771:\n    if left.type.is_protocol:\n        members_right = set(right.type.protocol_members) - members_not_to_check\n        members_left = set(left.type.protocol_members) - members_not_to_check\n        if not members_right.issubset(members_left):\n            return False\n    assuming = right.type.assuming_proper if proper_subtype else right.type.assuming\n    for l, r in reversed(assuming):\n        if l == left and r == right:\n            return True\n    with pop_on_exit(assuming, left, right):\n        for member in right.type.protocol_members:\n            if member in members_not_to_check:\n                continue\n            ignore_names = member != \"__call__\"  # __call__ can be passed kwargs\n            # The third argument below indicates to what self type is bound.\n            # We always bind self to the subtype. (Similarly to nominal types).\n            supertype = find_member(member, right, left)\n            assert supertype is not None\n\n            subtype = mypy.typeops.get_protocol_member(left, member, class_obj)\n            # Useful for debugging:\n            # print(member, 'of', left, 'has type', subtype)\n            # print(member, 'of', right, 'has type', supertype)\n            if not subtype:\n                return False\n            if not proper_subtype:\n                # Nominal check currently ignores arg names\n                # NOTE: If we ever change this, be sure to also change the call to\n                # SubtypeVisitor.build_subtype_kind(...) down below.\n                is_compat = is_subtype(\n                    subtype, supertype, ignore_pos_arg_names=ignore_names, options=options\n                )\n            else:\n                is_compat = is_proper_subtype(subtype, supertype)\n            if not is_compat:\n                return False\n            if isinstance(get_proper_type(subtype), NoneType) and isinstance(\n                get_proper_type(supertype), CallableType\n            ):\n                # We want __hash__ = None idiom to work even without --strict-optional\n                return False\n            subflags = get_member_flags(member, left, class_obj=class_obj)\n            superflags = get_member_flags(member, right)\n            if IS_SETTABLE in superflags:\n                # Check opposite direction for settable attributes.\n                if IS_EXPLICIT_SETTER in superflags:\n                    supertype = find_member(member, right, left, is_lvalue=True)\n                if IS_EXPLICIT_SETTER in subflags:\n                    subtype = mypy.typeops.get_protocol_member(\n                        left, member, class_obj, is_lvalue=True\n                    )\n                # At this point we know attribute is present on subtype, otherwise we\n                # would return False above.\n                assert supertype is not None and subtype is not None\n                if not is_subtype(supertype, subtype, options=options):\n                    return False\n            if IS_SETTABLE in superflags and IS_SETTABLE not in subflags:\n                return False\n            if not class_obj:\n                if IS_SETTABLE not in superflags:\n                    if IS_CLASSVAR in superflags and IS_CLASSVAR not in subflags:\n                        return False\n                elif (IS_CLASSVAR in subflags) != (IS_CLASSVAR in superflags):\n                    return False\n            else:\n                if IS_VAR in superflags and IS_CLASSVAR not in subflags:\n                    # Only class variables are allowed for class object access.\n                    return False\n                if IS_CLASSVAR in superflags:\n                    # This can be never matched by a class object.\n                    return False\n            # This rule is copied from nominal check in checker.py\n            if IS_CLASS_OR_STATIC in superflags and IS_CLASS_OR_STATIC not in subflags:\n                return False\n\n    if not proper_subtype:\n        # Nominal check currently ignores arg names, but __call__ is special for protocols\n        ignore_names = right.type.protocol_members != [\"__call__\"]\n    else:\n        ignore_names = False\n    subtype_kind = SubtypeVisitor.build_subtype_kind(\n        subtype_context=SubtypeContext(ignore_pos_arg_names=ignore_names),\n        proper_subtype=proper_subtype,\n    )\n    type_state.record_subtype_cache_entry(subtype_kind, left, right)\n    return True\n\n\ndef find_member(\n    name: str,\n    itype: Instance,\n    subtype: Type,\n    *,\n    is_operator: bool = False,\n    class_obj: bool = False,\n    is_lvalue: bool = False,\n) -> Type | None:\n    type_checker = checker_state.type_checker\n    if type_checker is None:\n        # Unfortunately, there are many scenarios where someone calls is_subtype() before\n        # type checking phase. In this case we fallback to old (incomplete) logic.\n        # TODO: reduce number of such cases (e.g. semanal_typeargs, post-semanal plugins).\n        return find_member_simple(\n            name, itype, subtype, is_operator=is_operator, class_obj=class_obj, is_lvalue=is_lvalue\n        )\n\n    # We don't use ATTR_DEFINED error code below (since missing attributes can cause various\n    # other error codes), instead we perform quick node lookup with all the fallbacks.\n    info = itype.type\n    sym = info.get(name)\n    node = sym.node if sym else None\n    if not node:\n        name_not_found = True\n        if (\n            name not in [\"__getattr__\", \"__setattr__\", \"__getattribute__\"]\n            and not is_operator\n            and not class_obj\n            and itype.extra_attrs is None  # skip ModuleType.__getattr__\n        ):\n            for method_name in (\"__getattribute__\", \"__getattr__\"):\n                method = info.get_method(method_name)\n                if method and method.info.fullname != \"builtins.object\":\n                    name_not_found = False\n                    break\n        if name_not_found:\n            if info.fallback_to_any or class_obj and info.meta_fallback_to_any:\n                return AnyType(TypeOfAny.special_form)\n            if itype.extra_attrs and name in itype.extra_attrs.attrs:\n                return itype.extra_attrs.attrs[name]\n            return None\n\n    from mypy.checkmember import (\n        MemberContext,\n        analyze_class_attribute_access,\n        analyze_instance_member_access,\n    )\n\n    mx = MemberContext(\n        is_lvalue=is_lvalue,\n        is_super=False,\n        is_operator=is_operator,\n        original_type=TypeType.make_normalized(itype) if class_obj else itype,\n        self_type=TypeType.make_normalized(subtype) if class_obj else subtype,\n        context=Context(),  # all errors are filtered, but this is a required argument\n        chk=type_checker,\n        suppress_errors=True,\n        # This is needed to avoid infinite recursion in situations involving protocols like\n        #     class P(Protocol[T]):\n        #         def combine(self, other: P[S]) -> P[Tuple[T, S]]: ...\n        # Normally we call freshen_all_functions_type_vars() during attribute access,\n        # to avoid type variable id collisions, but for protocols this means we can't\n        # use the assumption stack, that will grow indefinitely.\n        # TODO: find a cleaner solution that doesn't involve massive perf impact.\n        preserve_type_var_ids=True,\n    )\n    with type_checker.msg.filter_errors(filter_deprecated=True):\n        if class_obj:\n            fallback = itype.type.metaclass_type or mx.named_type(\"builtins.type\")\n            return analyze_class_attribute_access(itype, name, mx, mcs_fallback=fallback)\n        else:\n            return analyze_instance_member_access(name, itype, mx, info)\n\n\ndef find_member_simple(\n    name: str,\n    itype: Instance,\n    subtype: Type,\n    *,\n    is_operator: bool = False,\n    class_obj: bool = False,\n    is_lvalue: bool = False,\n) -> Type | None:\n    \"\"\"Find the type of member by 'name' in 'itype's TypeInfo.\n\n    Find the member type after applying type arguments from 'itype', and binding\n    'self' to 'subtype'. Return None if member was not found.\n    \"\"\"\n    info = itype.type\n    method = info.get_method(name)\n    if method:\n        if isinstance(method, Decorator):\n            return find_node_type(method.var, itype, subtype, class_obj=class_obj)\n        if method.is_property:\n            assert isinstance(method, OverloadedFuncDef)\n            dec = method.items[0]\n            assert isinstance(dec, Decorator)\n            # Pass on is_lvalue flag as this may be a property with different setter type.\n            return find_node_type(\n                dec.var, itype, subtype, class_obj=class_obj, is_lvalue=is_lvalue\n            )\n        return find_node_type(method, itype, subtype, class_obj=class_obj)\n    else:\n        # don't have such method, maybe variable or decorator?\n        node = info.get(name)\n        v = node.node if node else None\n        if isinstance(v, Var):\n            return find_node_type(v, itype, subtype, class_obj=class_obj)\n        if (\n            not v\n            and name not in [\"__getattr__\", \"__setattr__\", \"__getattribute__\"]\n            and not is_operator\n            and not class_obj\n            and itype.extra_attrs is None  # skip ModuleType.__getattr__\n        ):\n            for method_name in (\"__getattribute__\", \"__getattr__\"):\n                # Normally, mypy assumes that instances that define __getattr__ have all\n                # attributes with the corresponding return type. If this will produce\n                # many false negatives, then this could be prohibited for\n                # structural subtyping.\n                method = info.get_method(method_name)\n                if method and method.info.fullname != \"builtins.object\":\n                    if isinstance(method, Decorator):\n                        getattr_type = get_proper_type(find_node_type(method.var, itype, subtype))\n                    else:\n                        getattr_type = get_proper_type(find_node_type(method, itype, subtype))\n                    if isinstance(getattr_type, CallableType):\n                        return getattr_type.ret_type\n                    return getattr_type\n        if itype.type.fallback_to_any or class_obj and itype.type.meta_fallback_to_any:\n            return AnyType(TypeOfAny.special_form)\n        if isinstance(v, TypeInfo):\n            # PEP 544 doesn't specify anything about such use cases. So we just try\n            # to do something meaningful (at least we should not crash).\n            return TypeType(fill_typevars_with_any(v))\n    if itype.extra_attrs and name in itype.extra_attrs.attrs:\n        return itype.extra_attrs.attrs[name]\n    return None\n\n\ndef get_member_flags(name: str, itype: Instance, class_obj: bool = False) -> set[int]:\n    \"\"\"Detect whether a member 'name' is settable, whether it is an\n    instance or class variable, and whether it is class or static method.\n\n    The flags are defined as following:\n    * IS_SETTABLE: whether this attribute can be set, not set for methods and\n      non-settable properties;\n    * IS_CLASSVAR: set if the variable is annotated as 'x: ClassVar[t]';\n    * IS_CLASS_OR_STATIC: set for methods decorated with @classmethod or\n      with @staticmethod.\n    \"\"\"\n    info = itype.type\n    method = info.get_method(name)\n    setattr_meth = info.get_method(\"__setattr__\")\n    if method:\n        if isinstance(method, Decorator):\n            if method.var.is_staticmethod or method.var.is_classmethod:\n                return {IS_CLASS_OR_STATIC}\n            elif method.var.is_property:\n                return {IS_VAR}\n        elif method.is_property:  # this could be settable property\n            assert isinstance(method, OverloadedFuncDef)\n            dec = method.items[0]\n            assert isinstance(dec, Decorator)\n            if dec.var.is_settable_property or setattr_meth:\n                flags = {IS_VAR, IS_SETTABLE}\n                if dec.var.setter_type is not None:\n                    flags.add(IS_EXPLICIT_SETTER)\n                return flags\n            else:\n                return {IS_VAR}\n        return set()  # Just a regular method\n    node = info.get(name)\n    if not node:\n        if setattr_meth:\n            return {IS_SETTABLE}\n        if itype.extra_attrs and name in itype.extra_attrs.attrs:\n            flags = set()\n            if name not in itype.extra_attrs.immutable:\n                flags.add(IS_SETTABLE)\n            return flags\n        return set()\n    v = node.node\n    # just a variable\n    if isinstance(v, Var):\n        if v.is_property:\n            return {IS_VAR}\n        flags = {IS_VAR}\n        if not v.is_final:\n            flags.add(IS_SETTABLE)\n        # TODO: define cleaner rules for class vs instance variables.\n        if v.is_classvar and not is_descriptor(v.type):\n            flags.add(IS_CLASSVAR)\n        if class_obj and v.is_inferred:\n            flags.add(IS_CLASSVAR)\n        return flags\n    return set()\n\n\ndef is_descriptor(typ: Type | None) -> bool:\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        return typ.type.get(\"__get__\") is not None\n    if isinstance(typ, UnionType):\n        return all(is_descriptor(item) for item in typ.relevant_items())\n    return False\n\n\ndef find_node_type(\n    node: Var | FuncBase,\n    itype: Instance,\n    subtype: Type,\n    class_obj: bool = False,\n    is_lvalue: bool = False,\n) -> Type:\n    \"\"\"Find type of a variable or method 'node' (maybe also a decorated method).\n    Apply type arguments from 'itype', and bind 'self' to 'subtype'.\n    \"\"\"\n    from mypy.typeops import bind_self\n\n    if isinstance(node, FuncBase):\n        typ: Type | None = mypy.typeops.function_type(\n            node, fallback=Instance(itype.type.mro[-1], [])\n        )\n    else:\n        # This part and the one below are simply copies of the logic from checkmember.py.\n        if node.is_settable_property and is_lvalue:\n            typ = node.setter_type\n            if typ is None and node.is_ready:\n                typ = node.type\n        else:\n            typ = node.type\n        if typ is not None:\n            typ = expand_self_type(node, typ, subtype)\n    p_typ = get_proper_type(typ)\n    if typ is None:\n        return AnyType(TypeOfAny.from_error)\n    # We don't need to bind 'self' for static methods, since there is no 'self'.\n    if isinstance(node, FuncBase) or (\n        isinstance(p_typ, FunctionLike)\n        and node.is_initialized_in_class\n        and not node.is_staticmethod\n    ):\n        assert isinstance(p_typ, FunctionLike)\n        if class_obj and not (\n            node.is_class if isinstance(node, FuncBase) else node.is_classmethod\n        ):\n            # Don't bind instance methods on class objects.\n            signature = p_typ\n        else:\n            signature = bind_self(\n                p_typ, subtype, is_classmethod=isinstance(node, Var) and node.is_classmethod\n            )\n        if node.is_property and not class_obj:\n            assert isinstance(signature, CallableType)\n            if (\n                isinstance(node, Var)\n                and node.is_settable_property\n                and is_lvalue\n                and node.setter_type is not None\n            ):\n                typ = signature.arg_types[0]\n            else:\n                typ = signature.ret_type\n        else:\n            typ = signature\n    itype = map_instance_to_supertype(itype, node.info)\n    typ = expand_type_by_instance(typ, itype)\n    return typ\n\n\ndef non_method_protocol_members(tp: TypeInfo) -> list[str]:\n    \"\"\"Find all non-callable members of a protocol.\"\"\"\n\n    assert tp.is_protocol\n    result: list[str] = []\n    anytype = AnyType(TypeOfAny.special_form)\n    instance = Instance(tp, [anytype] * len(tp.defn.type_vars))\n\n    for member in tp.protocol_members:\n        typ = get_proper_type(find_member(member, instance, instance))\n        if not isinstance(typ, (Overloaded, CallableType)):\n            result.append(member)\n    return result\n\n\ndef is_callable_compatible(\n    left: CallableType,\n    right: CallableType,\n    *,\n    is_compat: Callable[[Type, Type], bool],\n    is_proper_subtype: bool,\n    is_compat_return: Callable[[Type, Type], bool] | None = None,\n    ignore_return: bool = False,\n    ignore_pos_arg_names: bool = False,\n    check_args_covariantly: bool = False,\n    allow_partial_overlap: bool = False,\n    strict_concatenate: bool = False,\n) -> bool:\n    \"\"\"Is the left compatible with the right, using the provided compatibility check?\n\n    is_compat:\n        The check we want to run against the parameters.\n\n    is_compat_return:\n        The check we want to run against the return type.\n        If None, use the 'is_compat' check.\n\n    check_args_covariantly:\n        If true, check if the left's args is compatible with the right's\n        instead of the other way around (contravariantly).\n\n        This function is mostly used to check if the left is a subtype of the right which\n        is why the default is to check the args contravariantly. However, it's occasionally\n        useful to check the args using some other check, so we leave the variance\n        configurable.\n\n        For example, when checking the validity of overloads, it's useful to see if\n        the first overload alternative has more precise arguments than the second.\n        We would want to check the arguments covariantly in that case.\n\n        Note! The following two function calls are NOT equivalent:\n\n            is_callable_compatible(f, g, is_compat=is_subtype, check_args_covariantly=False)\n            is_callable_compatible(g, f, is_compat=is_subtype, check_args_covariantly=True)\n\n        The two calls are similar in that they both check the function arguments in\n        the same direction: they both run `is_subtype(argument_from_g, argument_from_f)`.\n\n        However, the two calls differ in which direction they check things like\n        keyword arguments. For example, suppose f and g are defined like so:\n\n            def f(x: int, *y: int) -> int: ...\n            def g(x: int) -> int: ...\n\n        In this case, the first call will succeed and the second will fail: f is a\n        valid stand-in for g but not vice-versa.\n\n    allow_partial_overlap:\n        By default this function returns True if and only if *all* calls to left are\n        also calls to right (with respect to the provided 'is_compat' function).\n\n        If this parameter is set to 'True', we return True if *there exists at least one*\n        call to left that's also a call to right.\n\n        In other words, we perform an existential check instead of a universal one;\n        we require left to only overlap with right instead of being a subset.\n\n        For example, suppose we set 'is_compat' to some subtype check and compare following:\n\n            f(x: float, y: str = \"...\", *args: bool) -> str\n            g(*args: int) -> str\n\n        This function would normally return 'False': f is not a subtype of g.\n        However, we would return True if this parameter is set to 'True': the two\n        calls are compatible if the user runs \"f_or_g(3)\". In the context of that\n        specific call, the two functions effectively have signatures of:\n\n            f2(float) -> str\n            g2(int) -> str\n\n        Here, f2 is a valid subtype of g2 so we return True.\n\n        Specifically, if this parameter is set this function will:\n\n        -   Ignore optional arguments on either the left or right that have no\n            corresponding match.\n        -   No longer mandate optional arguments on either side are also optional\n            on the other.\n        -   No longer mandate that if right has a *arg or **kwarg that left must also\n            have the same.\n\n        Note: when this argument is set to True, this function becomes \"symmetric\" --\n        the following calls are equivalent:\n\n            is_callable_compatible(f, g,\n                                   is_compat=some_check,\n                                   check_args_covariantly=False,\n                                   allow_partial_overlap=True)\n            is_callable_compatible(g, f,\n                                   is_compat=some_check,\n                                   check_args_covariantly=True,\n                                   allow_partial_overlap=True)\n\n        If the 'some_check' function is also symmetric, the two calls would be equivalent\n        whether or not we check the args covariantly.\n    \"\"\"\n    # Normalize both types before comparing them.\n    left = left.with_unpacked_kwargs().with_normalized_var_args()\n    right = right.with_unpacked_kwargs().with_normalized_var_args()\n\n    if is_compat_return is None:\n        is_compat_return = is_compat\n\n    # If either function is implicitly typed, ignore positional arg names too\n    if left.implicit or right.implicit:\n        ignore_pos_arg_names = True\n\n    # Non-type cannot be a subtype of type.\n    if right.is_type_obj() and not left.is_type_obj() and not allow_partial_overlap:\n        return False\n\n    # A callable L is a subtype of a generic callable R if L is a\n    # subtype of every type obtained from R by substituting types for\n    # the variables of R. We can check this by simply leaving the\n    # generic variables of R as type variables, effectively varying\n    # over all possible values.\n\n    # It's okay even if these variables share ids with generic\n    # type variables of L, because generating and solving\n    # constraints for the variables of L to make L a subtype of R\n    # (below) treats type variables on the two sides as independent.\n    if left.variables:\n        # Apply generic type variables away in left via type inference.\n        unified = unify_generic_callable(left, right, ignore_return=ignore_return)\n        if unified is None:\n            return False\n        left = unified\n\n    # Check return types.\n    if not ignore_return and not is_compat_return(left.ret_type, right.ret_type):\n        return False\n\n    if check_args_covariantly:\n        is_compat = flip_compat_check(is_compat)\n\n    if not strict_concatenate and (left.from_concatenate or right.from_concatenate):\n        strict_concatenate_check = False\n    else:\n        strict_concatenate_check = True\n\n    return are_parameters_compatible(\n        left,\n        right,\n        is_compat=is_compat,\n        is_proper_subtype=is_proper_subtype,\n        ignore_pos_arg_names=ignore_pos_arg_names,\n        allow_partial_overlap=allow_partial_overlap,\n        strict_concatenate_check=strict_concatenate_check,\n    )\n\n\ndef are_trivial_parameters(param: Parameters | NormalizedCallableType) -> bool:\n    param_star = param.var_arg()\n    param_star2 = param.kw_arg()\n    return (\n        param.arg_kinds == [ARG_STAR, ARG_STAR2]\n        and param_star is not None\n        and isinstance(get_proper_type(param_star.typ), AnyType)\n        and param_star2 is not None\n        and isinstance(get_proper_type(param_star2.typ), AnyType)\n    )\n\n\ndef is_trivial_suffix(param: Parameters | NormalizedCallableType) -> bool:\n    param_star = param.var_arg()\n    param_star2 = param.kw_arg()\n    return (\n        param.arg_kinds[-2:] == [ARG_STAR, ARG_STAR2]\n        and param_star is not None\n        and isinstance(get_proper_type(param_star.typ), AnyType)\n        and param_star2 is not None\n        and isinstance(get_proper_type(param_star2.typ), AnyType)\n    )\n\n\ndef are_parameters_compatible(\n    left: Parameters | NormalizedCallableType,\n    right: Parameters | NormalizedCallableType,\n    *,\n    is_compat: Callable[[Type, Type], bool],\n    is_proper_subtype: bool,\n    ignore_pos_arg_names: bool = False,\n    allow_partial_overlap: bool = False,\n    strict_concatenate_check: bool = False,\n) -> bool:\n    \"\"\"Helper function for is_callable_compatible, used for Parameter compatibility\"\"\"\n    if right.is_ellipsis_args and not is_proper_subtype:\n        return True\n\n    left_star = left.var_arg()\n    left_star2 = left.kw_arg()\n    right_star = right.var_arg()\n    right_star2 = right.kw_arg()\n\n    # Treat \"def _(*a: Any, **kw: Any) -> X\" similarly to \"Callable[..., X]\"\n    if are_trivial_parameters(right) and not is_proper_subtype:\n        return True\n    trivial_suffix = is_trivial_suffix(right) and not is_proper_subtype\n\n    trivial_vararg_suffix = False\n    if (\n        right.arg_kinds[-1:] == [ARG_STAR]\n        and isinstance(get_proper_type(right.arg_types[-1]), AnyType)\n        and not is_proper_subtype\n        and all(k.is_positional(star=True) for k in left.arg_kinds)\n    ):\n        # Similar to how (*Any, **Any) is considered a supertype of all callables, we consider\n        # (*Any) a supertype of all callables with positional arguments. This is needed in\n        # particular because we often refuse to try type inference if actual type is not\n        # a subtype of erased template type.\n        trivial_vararg_suffix = True\n\n    # Match up corresponding arguments and check them for compatibility. In\n    # every pair (argL, argR) of corresponding arguments from L and R, argL must\n    # be \"more general\" than argR if L is to be a subtype of R.\n\n    # Arguments are corresponding if they either share a name, share a position,\n    # or both. If L's corresponding argument is ambiguous, L is not a subtype of R.\n\n    # If left has one corresponding argument by name and another by position,\n    # consider them to be one \"merged\" argument (and not ambiguous) if they're\n    # both optional, they're name-only and position-only respectively, and they\n    # have the same type.  This rule allows functions with (*args, **kwargs) to\n    # properly stand in for the full domain of formal arguments that they're\n    # used for in practice.\n\n    # Every argument in R must have a corresponding argument in L, and every\n    # required argument in L must have a corresponding argument in R.\n\n    # Phase 1: Confirm every argument in R has a corresponding argument in L.\n\n    # Phase 1a: If left and right can both accept an infinite number of args,\n    #           their types must be compatible.\n    #\n    #           Furthermore, if we're checking for compatibility in all cases,\n    #           we confirm that if R accepts an infinite number of arguments,\n    #           L must accept the same.\n    def _incompatible(left_arg: FormalArgument | None, right_arg: FormalArgument | None) -> bool:\n        if right_arg is None:\n            return False\n        if left_arg is None:\n            return not allow_partial_overlap and not trivial_suffix\n        return not is_compat(right_arg.typ, left_arg.typ)\n\n    if (\n        _incompatible(left_star, right_star)\n        and not trivial_vararg_suffix\n        or _incompatible(left_star2, right_star2)\n    ):\n        return False\n\n    # Phase 1b: Check non-star args: for every arg right can accept, left must\n    #           also accept. The only exception is if we are allowing partial\n    #           overlaps: in that case, we ignore optional args on the right.\n    for right_arg in right.formal_arguments():\n        left_arg = mypy.typeops.callable_corresponding_argument(left, right_arg)\n        if left_arg is None:\n            if allow_partial_overlap and not right_arg.required:\n                continue\n            return False\n        if not are_args_compatible(\n            left_arg,\n            right_arg,\n            is_compat,\n            ignore_pos_arg_names=ignore_pos_arg_names,\n            allow_partial_overlap=allow_partial_overlap,\n            allow_imprecise_kinds=right.imprecise_arg_kinds,\n        ):\n            return False\n\n    if trivial_suffix:\n        # For trivial right suffix we *only* check that every non-star right argument\n        # has a valid match on the left.\n        return True\n\n    # Phase 1c: Check var args. Right has an infinite series of optional positional\n    #           arguments. Get all further positional args of left, and make sure\n    #           they're more general than the corresponding member in right.\n    # TODO: handle suffix in UnpackType (i.e. *args: *Tuple[Ts, X, Y]).\n    if right_star is not None and not trivial_vararg_suffix:\n        # Synthesize an anonymous formal argument for the right\n        right_by_position = right.try_synthesizing_arg_from_vararg(None)\n        assert right_by_position is not None\n\n        i = right_star.pos\n        assert i is not None\n        while i < len(left.arg_kinds) and left.arg_kinds[i].is_positional():\n            if allow_partial_overlap and left.arg_kinds[i].is_optional():\n                break\n\n            left_by_position = left.argument_by_position(i)\n            assert left_by_position is not None\n\n            if not are_args_compatible(\n                left_by_position,\n                right_by_position,\n                is_compat,\n                ignore_pos_arg_names=ignore_pos_arg_names,\n                allow_partial_overlap=allow_partial_overlap,\n            ):\n                return False\n            i += 1\n\n    # Phase 1d: Check kw args. Right has an infinite series of optional named\n    #           arguments. Get all further named args of left, and make sure\n    #           they're more general than the corresponding member in right.\n    if right_star2 is not None:\n        right_names = {name for name in right.arg_names if name is not None}\n        left_only_names = set()\n        for name, kind in zip(left.arg_names, left.arg_kinds):\n            if (\n                name is None\n                or kind.is_star()\n                or name in right_names\n                or not strict_concatenate_check\n            ):\n                continue\n            left_only_names.add(name)\n\n        # Synthesize an anonymous formal argument for the right\n        right_by_name = right.try_synthesizing_arg_from_kwarg(None)\n        assert right_by_name is not None\n\n        for name in left_only_names:\n            left_by_name = left.argument_by_name(name)\n            assert left_by_name is not None\n\n            if allow_partial_overlap and not left_by_name.required:\n                continue\n\n            if not are_args_compatible(\n                left_by_name,\n                right_by_name,\n                is_compat,\n                ignore_pos_arg_names=ignore_pos_arg_names,\n                allow_partial_overlap=allow_partial_overlap,\n            ):\n                return False\n\n    # Phase 2: Left must not impose additional restrictions.\n    #          (Every required argument in L must have a corresponding argument in R)\n    #          Note: we already checked the *arg and **kwarg arguments in phase 1a.\n    for left_arg in left.formal_arguments():\n        right_by_name = (\n            right.argument_by_name(left_arg.name) if left_arg.name is not None else None\n        )\n\n        right_by_pos = (\n            right.argument_by_position(left_arg.pos) if left_arg.pos is not None else None\n        )\n\n        # If the left hand argument corresponds to two right-hand arguments,\n        # neither of them can be required.\n        if (\n            right_by_name is not None\n            and right_by_pos is not None\n            and right_by_name != right_by_pos\n            and (right_by_pos.required or right_by_name.required)\n            and strict_concatenate_check\n            and not right.imprecise_arg_kinds\n        ):\n            return False\n\n        # All *required* left-hand arguments must have a corresponding\n        # right-hand argument.  Optional args do not matter.\n        if left_arg.required and right_by_pos is None and right_by_name is None:\n            return False\n\n    return True\n\n\ndef are_args_compatible(\n    left: FormalArgument,\n    right: FormalArgument,\n    is_compat: Callable[[Type, Type], bool],\n    *,\n    ignore_pos_arg_names: bool,\n    allow_partial_overlap: bool,\n    allow_imprecise_kinds: bool = False,\n) -> bool:\n    if left.required and right.required:\n        # If both arguments are required allow_partial_overlap has no effect.\n        allow_partial_overlap = False\n\n    def is_different(\n        left_item: object | None, right_item: object | None, allow_overlap: bool\n    ) -> bool:\n        \"\"\"Checks if the left and right items are different.\n\n        If the right item is unspecified (e.g. if the right callable doesn't care\n        about what name or position its arg has), we default to returning False.\n\n        If we're allowing partial overlap, we also default to returning False\n        if the left callable also doesn't care.\"\"\"\n        if right_item is None:\n            return False\n        if allow_overlap and left_item is None:\n            return False\n        return left_item != right_item\n\n    # If right has a specific name it wants this argument to be, left must\n    # have the same.\n    if is_different(left.name, right.name, allow_partial_overlap):\n        # But pay attention to whether we're ignoring positional arg names\n        if not ignore_pos_arg_names or right.pos is None:\n            return False\n\n    # If right is at a specific position, left must have the same.\n    # TODO: partial overlap logic is flawed for positions.\n    # We disable it to avoid false positives at a cost of few false negatives.\n    if is_different(left.pos, right.pos, allow_overlap=False) and not allow_imprecise_kinds:\n        return False\n\n    # If right's argument is optional, left's must also be\n    # (unless we're relaxing the checks to allow potential\n    # rather than definite compatibility).\n    if not allow_partial_overlap and not right.required and left.required:\n        return False\n\n    # If we're allowing partial overlaps and neither arg is required,\n    # the types don't actually need to be the same\n    if allow_partial_overlap and not left.required and not right.required:\n        return True\n\n    # Left must have a more general type\n    return is_compat(right.typ, left.typ)\n\n\ndef flip_compat_check(is_compat: Callable[[Type, Type], bool]) -> Callable[[Type, Type], bool]:\n    def new_is_compat(left: Type, right: Type) -> bool:\n        return is_compat(right, left)\n\n    return new_is_compat\n\n\ndef unify_generic_callable(\n    type: NormalizedCallableType,\n    target: NormalizedCallableType,\n    ignore_return: bool,\n    return_constraint_direction: int | None = None,\n) -> NormalizedCallableType | None:\n    \"\"\"Try to unify a generic callable type with another callable type.\n\n    Return unified CallableType if successful; otherwise, return None.\n    \"\"\"\n    import mypy.solve\n\n    if set(type.type_var_ids()) & {v.id for v in mypy.typeops.get_all_type_vars(target)}:\n        # Overload overlap check does nasty things like unifying in opposite direction.\n        # This can easily create type variable clashes, so we need to refresh.\n        type = freshen_function_type_vars(type)\n\n    if return_constraint_direction is None:\n        return_constraint_direction = mypy.constraints.SUBTYPE_OF\n\n    constraints: list[mypy.constraints.Constraint] = []\n    # There is some special logic for inference in callables, so better use them\n    # as wholes instead of picking separate arguments.\n    cs = mypy.constraints.infer_constraints(\n        type.copy_modified(ret_type=UninhabitedType()),\n        target.copy_modified(ret_type=UninhabitedType()),\n        mypy.constraints.SUBTYPE_OF,\n        skip_neg_op=True,\n    )\n    constraints.extend(cs)\n    if not ignore_return:\n        c = mypy.constraints.infer_constraints(\n            type.ret_type, target.ret_type, return_constraint_direction\n        )\n        constraints.extend(c)\n    inferred_vars, _ = mypy.solve.solve_constraints(\n        type.variables, constraints, allow_polymorphic=True\n    )\n    if None in inferred_vars:\n        return None\n    non_none_inferred_vars = cast(list[Type], inferred_vars)\n    had_errors = False\n\n    def report(*args: Any) -> None:\n        nonlocal had_errors\n        had_errors = True\n\n    # This function may be called by the solver, so we need to allow erased types here.\n    # We anyway allow checking subtyping between other types containing <Erased>\n    # (probably also because solver needs subtyping). See also comment in\n    # ExpandTypeVisitor.visit_erased_type().\n    applied = mypy.applytype.apply_generic_arguments(\n        type, non_none_inferred_vars, report, context=target\n    )\n    if had_errors:\n        return None\n    return cast(NormalizedCallableType, applied)\n\n\ndef try_restrict_literal_union(t: UnionType, s: Type) -> list[Type] | None:\n    \"\"\"Return the items of t, excluding any occurrence of s, if and only if\n      - t only contains simple literals\n      - s is a simple literal\n\n    Otherwise, returns None\n    \"\"\"\n    ps = get_proper_type(s)\n    if not mypy.typeops.is_simple_literal(ps):\n        return None\n\n    new_items: list[Type] = []\n    for i in t.relevant_items():\n        pi = get_proper_type(i)\n        if not mypy.typeops.is_simple_literal(pi):\n            return None\n        if pi != ps:\n            new_items.append(i)\n    return new_items\n\n\ndef restrict_subtype_away(t: Type, s: Type, *, consider_runtime_isinstance: bool = True) -> Type:\n    \"\"\"Return t minus s for runtime type assertions.\n\n    If we can't determine a precise result, return a supertype of the\n    ideal result (just t is a valid result).\n\n    This is used for type inference of runtime type checks such as\n    isinstance(). Currently, this just removes elements of a union type.\n    \"\"\"\n    p_t = get_proper_type(t)\n    if isinstance(p_t, UnionType):\n        new_items = try_restrict_literal_union(p_t, s)\n        if new_items is None:\n            new_items = [\n                restrict_subtype_away(\n                    item, s, consider_runtime_isinstance=consider_runtime_isinstance\n                )\n                for item in p_t.relevant_items()\n            ]\n        return UnionType.make_union(\n            [item for item in new_items if not isinstance(get_proper_type(item), UninhabitedType)]\n        )\n    elif isinstance(p_t, TypeVarType):\n        return p_t.copy_modified(upper_bound=restrict_subtype_away(p_t.upper_bound, s))\n\n    if consider_runtime_isinstance:\n        if covers_at_runtime(t, s):\n            return UninhabitedType()\n        else:\n            return t\n    else:\n        if is_proper_subtype(t, s, ignore_promotions=True):\n            return UninhabitedType()\n        if is_proper_subtype(t, s, ignore_promotions=True, erase_instances=True):\n            return UninhabitedType()\n        return t\n\n\ndef covers_at_runtime(item: Type, supertype: Type) -> bool:\n    \"\"\"Will isinstance(item, supertype) always return True at runtime?\"\"\"\n    item = get_proper_type(item)\n    supertype = get_proper_type(supertype)\n\n    # Since runtime type checks will ignore type arguments, erase the types.\n    if not (isinstance(supertype, FunctionLike) and supertype.is_type_obj()):\n        supertype = erase_type(supertype)\n    if is_proper_subtype(\n        erase_type(item), supertype, ignore_promotions=True, erase_instances=True\n    ):\n        return True\n    if isinstance(supertype, Instance):\n        if supertype.type.is_protocol:\n            # TODO: Implement more robust support for runtime isinstance() checks, see issue #3827.\n            if is_proper_subtype(item, supertype, ignore_promotions=True):\n                return True\n        if isinstance(item, TypedDictType):\n            # Special case useful for selecting TypedDicts from unions using isinstance(x, dict).\n            if supertype.type.fullname == \"builtins.dict\":\n                return True\n        elif isinstance(item, TypeVarType):\n            if is_proper_subtype(item.upper_bound, supertype, ignore_promotions=True):\n                return True\n        elif isinstance(item, Instance) and supertype.type.fullname == \"builtins.int\":\n            # \"int\" covers all native int types\n            if item.type.fullname in MYPYC_NATIVE_INT_NAMES:\n                return True\n    # TODO: Add more special cases.\n    return False\n\n\ndef is_more_precise(left: Type, right: Type, *, ignore_promotions: bool = False) -> bool:\n    \"\"\"Check if left is a more precise type than right.\n\n    A left is a proper subtype of right, left is also more precise than\n    right. Also, if right is Any, left is more precise than right, for\n    any left.\n    \"\"\"\n    # TODO Should List[int] be more precise than List[Any]?\n    right = get_proper_type(right)\n    if isinstance(right, AnyType):\n        return True\n    return is_proper_subtype(left, right, ignore_promotions=ignore_promotions)\n\n\ndef all_non_object_members(info: TypeInfo) -> set[str]:\n    members = set(info.names)\n    for base in info.mro[1:-1]:\n        members.update(base.names)\n    return members\n\n\ndef infer_variance(info: TypeInfo, i: int) -> bool:\n    \"\"\"Infer the variance of the ith type variable of a generic class.\n\n    Return True if successful. This can fail if some inferred types aren't ready.\n    \"\"\"\n    object_type = Instance(info.mro[-1], [])\n\n    for variance in COVARIANT, CONTRAVARIANT, INVARIANT:\n        tv = info.defn.type_vars[i]\n        assert isinstance(tv, TypeVarType)\n        if tv.variance != VARIANCE_NOT_READY:\n            continue\n        tv.variance = variance\n        co = True\n        contra = True\n        tvar = info.defn.type_vars[i]\n        self_type = fill_typevars(info)\n        for member in all_non_object_members(info):\n            # __mypy-replace is an implementation detail of the dataclass plugin\n            if member in (\"__init__\", \"__new__\", \"__mypy-replace\"):\n                continue\n\n            if isinstance(self_type, TupleType):\n                self_type = mypy.typeops.tuple_fallback(self_type)\n            flags = get_member_flags(member, self_type)\n            settable = IS_SETTABLE in flags\n\n            node = info[member].node\n            if isinstance(node, Var):\n                if node.type is None:\n                    tv.variance = VARIANCE_NOT_READY\n                    return False\n                if has_underscore_prefix(member):\n                    # Special case to avoid false positives (and to pass conformance tests)\n                    settable = False\n\n            # TODO: handle settable properties with setter type different from getter.\n            typ = find_member(member, self_type, self_type)\n            if typ:\n                # It's okay for a method in a generic class with a contravariant type\n                # variable to return a generic instance of the class, if it doesn't involve\n                # variance (i.e. values of type variables are propagated). Our normal rules\n                # would disallow this. Replace such return types with 'Any' to allow this.\n                #\n                # This could probably be more lenient (e.g. allow self type be nested, don't\n                # require all type arguments to be identical to self_type), but this will\n                # hopefully cover the vast majority of such cases, including Self.\n                typ = erase_return_self_types(typ, self_type)\n\n                typ2 = expand_type(typ, {tvar.id: object_type})\n                if not is_subtype(typ, typ2):\n                    co = False\n                if not is_subtype(typ2, typ):\n                    contra = False\n                    if settable:\n                        co = False\n\n        # Infer variance from base classes, in case they have explicit variances\n        for base in info.bases:\n            base2 = expand_type(base, {tvar.id: object_type})\n            if not is_subtype(base, base2):\n                co = False\n            if not is_subtype(base2, base):\n                contra = False\n\n        if co:\n            v = COVARIANT\n        elif contra:\n            v = CONTRAVARIANT\n        else:\n            v = INVARIANT\n        if v == variance:\n            break\n        tv.variance = VARIANCE_NOT_READY\n    return True\n\n\ndef has_underscore_prefix(name: str) -> bool:\n    return name.startswith(\"_\") and not (name.startswith(\"__\") and name.endswith(\"__\"))\n\n\ndef infer_class_variances(info: TypeInfo) -> bool:\n    if not info.defn.type_args:\n        return True\n    tvs = info.defn.type_vars\n    success = True\n    for i, tv in enumerate(tvs):\n        if isinstance(tv, TypeVarType) and tv.variance == VARIANCE_NOT_READY:\n            if not infer_variance(info, i):\n                success = False\n    return success\n\n\ndef erase_return_self_types(typ: Type, self_type: Instance) -> Type:\n    \"\"\"If a typ is function-like and returns self_type, replace return type with Any.\"\"\"\n    proper_type = get_proper_type(typ)\n    if isinstance(proper_type, CallableType):\n        ret = get_proper_type(proper_type.ret_type)\n        if isinstance(ret, Instance) and ret == self_type:\n            return proper_type.copy_modified(ret_type=AnyType(TypeOfAny.implementation_artifact))\n    elif isinstance(proper_type, Overloaded):\n        return Overloaded(\n            [\n                cast(CallableType, erase_return_self_types(it, self_type))\n                for it in proper_type.items\n            ]\n        )\n    return typ\n\n\ndef is_erased_instance(t: Instance) -> bool:\n    \"\"\"Is this an instance where all args are Any types?\"\"\"\n    if not t.args:\n        return False\n    for arg in t.args:\n        if isinstance(arg, UnpackType):\n            unpacked = get_proper_type(arg.type)\n            if not isinstance(unpacked, Instance):\n                return False\n            assert unpacked.type.fullname == \"builtins.tuple\"\n            if not isinstance(get_proper_type(unpacked.args[0]), AnyType):\n                return False\n        elif not isinstance(get_proper_type(arg), AnyType):\n            return False\n    return True\n"
  },
  {
    "path": "mypy/suggestions.py",
    "content": "\"\"\"Mechanisms for inferring function types based on callsites.\n\nCurrently works by collecting all argument types at callsites,\nsynthesizing a list of possible function types from that, trying them\nall, and picking the one with the fewest errors that we think is the\n\"best\".\n\nCan return JSON that pyannotate can use to apply the annotations to code.\n\nThere are a bunch of TODOs here:\n * Maybe want a way to surface the choices not selected??\n * We can generate an exponential number of type suggestions, and probably want\n   a way to not always need to check them all.\n * Our heuristics for what types to try are primitive and not yet\n   supported by real practice.\n * More!\n\nOther things:\n * This is super brute force. Could we integrate with the typechecker\n   more to understand more about what is going on?\n * Like something with tracking constraints/unification variables?\n * No understanding of type variables at *all*\n\"\"\"\n\nfrom __future__ import annotations\n\nimport itertools\nimport json\nimport os\nimport sys\nfrom collections.abc import Callable, Iterator\nfrom contextlib import contextmanager\nfrom typing import NamedTuple, TypedDict, TypeVar, cast\n\nfrom mypy.argmap import map_actuals_to_formals\nfrom mypy.build import Graph, State\nfrom mypy.checkexpr import has_any_type\nfrom mypy.find_sources import InvalidSourceList, SourceFinder\nfrom mypy.join import join_type_list\nfrom mypy.meet import meet_type_list\nfrom mypy.modulefinder import PYTHON_EXTENSIONS\nfrom mypy.nodes import (\n    ARG_STAR,\n    ARG_STAR2,\n    ArgKind,\n    CallExpr,\n    Decorator,\n    Expression,\n    FuncDef,\n    MypyFile,\n    RefExpr,\n    ReturnStmt,\n    SymbolNode,\n    SymbolTable,\n    TypeInfo,\n    Var,\n)\nfrom mypy.options import Options\nfrom mypy.plugin import FunctionContext, MethodContext, Plugin\nfrom mypy.server.update import FineGrainedBuildManager\nfrom mypy.state import state\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.typeops import bind_self, make_simplified_union\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    FunctionLike,\n    Instance,\n    NoneType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeStrVisitor,\n    TypeTranslator,\n    TypeVarType,\n    UninhabitedType,\n    UnionType,\n    get_proper_type,\n)\nfrom mypy.types_utils import is_overlapping_none, remove_optional\nfrom mypy.util import split_target\n\n\nclass PyAnnotateSignature(TypedDict):\n    return_type: str\n    arg_types: list[str]\n\n\nclass Callsite(NamedTuple):\n    path: str\n    line: int\n    arg_kinds: list[list[ArgKind]]\n    callee_arg_names: list[str | None]\n    arg_names: list[list[str | None]]\n    arg_types: list[list[Type]]\n\n\nclass SuggestionPlugin(Plugin):\n    \"\"\"Plugin that records all calls to a given target.\"\"\"\n\n    def __init__(self, target: str) -> None:\n        if target.endswith((\".__new__\", \".__init__\")):\n            target = target.rsplit(\".\", 1)[0]\n\n        self.target = target\n        # List of call sites found by dmypy suggest:\n        # (path, line, <arg kinds>, <arg names>, <arg types>)\n        self.mystery_hits: list[Callsite] = []\n\n    def get_function_hook(self, fullname: str) -> Callable[[FunctionContext], Type] | None:\n        if fullname == self.target:\n            return self.log\n        else:\n            return None\n\n    def get_method_hook(self, fullname: str) -> Callable[[MethodContext], Type] | None:\n        if fullname == self.target:\n            return self.log\n        else:\n            return None\n\n    def log(self, ctx: FunctionContext | MethodContext) -> Type:\n        self.mystery_hits.append(\n            Callsite(\n                ctx.api.path,\n                ctx.context.line,\n                ctx.arg_kinds,\n                ctx.callee_arg_names,\n                ctx.arg_names,\n                ctx.arg_types,\n            )\n        )\n        return ctx.default_return_type\n\n\n# NOTE: We could make this a bunch faster by implementing a StatementVisitor that skips\n# traversing into expressions\nclass ReturnFinder(TraverserVisitor):\n    \"\"\"Visitor for finding all types returned from a function.\"\"\"\n\n    def __init__(self, typemap: dict[Expression, Type]) -> None:\n        self.typemap = typemap\n        self.return_types: list[Type] = []\n\n    def visit_return_stmt(self, o: ReturnStmt) -> None:\n        if o.expr is not None and o.expr in self.typemap:\n            self.return_types.append(self.typemap[o.expr])\n\n    def visit_func_def(self, o: FuncDef) -> None:\n        # Skip nested functions\n        pass\n\n\ndef get_return_types(typemap: dict[Expression, Type], func: FuncDef) -> list[Type]:\n    \"\"\"Find all the types returned by return statements in func.\"\"\"\n    finder = ReturnFinder(typemap)\n    func.body.accept(finder)\n    return finder.return_types\n\n\nclass ArgUseFinder(TraverserVisitor):\n    \"\"\"Visitor for finding all the types of arguments that each arg is passed to.\n\n    This is extremely simple minded but might be effective anyways.\n    \"\"\"\n\n    def __init__(self, func: FuncDef, typemap: dict[Expression, Type]) -> None:\n        self.typemap = typemap\n        self.arg_types: dict[SymbolNode, list[Type]] = {arg.variable: [] for arg in func.arguments}\n\n    def visit_call_expr(self, o: CallExpr) -> None:\n        if not any(isinstance(e, RefExpr) and e.node in self.arg_types for e in o.args):\n            return\n\n        typ = get_proper_type(self.typemap.get(o.callee))\n        if not isinstance(typ, CallableType):\n            return\n\n        formal_to_actual = map_actuals_to_formals(\n            o.arg_kinds,\n            o.arg_names,\n            typ.arg_kinds,\n            typ.arg_names,\n            lambda n: AnyType(TypeOfAny.special_form),\n        )\n\n        for i, args in enumerate(formal_to_actual):\n            for arg_idx in args:\n                arg = o.args[arg_idx]\n                if isinstance(arg, RefExpr) and arg.node in self.arg_types:\n                    self.arg_types[arg.node].append(typ.arg_types[i])\n\n\ndef get_arg_uses(typemap: dict[Expression, Type], func: FuncDef) -> list[list[Type]]:\n    \"\"\"Find all the types of arguments that each arg is passed to.\n\n    For example, given\n      def foo(x: int) -> None: ...\n      def bar(x: str) -> None: ...\n      def test(x, y):\n          foo(x)\n          bar(y)\n\n    this will return [[int], [str]].\n    \"\"\"\n    finder = ArgUseFinder(func, typemap)\n    func.body.accept(finder)\n    return [finder.arg_types[arg.variable] for arg in func.arguments]\n\n\nclass SuggestionFailure(Exception):\n    pass\n\n\ndef is_explicit_any(typ: AnyType) -> bool:\n    # Originally I wanted to count as explicit anything derived from an explicit any, but that\n    # seemed too strict in some testing.\n    # return (typ.type_of_any == TypeOfAny.explicit\n    #         or (typ.source_any is not None and typ.source_any.type_of_any == TypeOfAny.explicit))\n    # Important question: what should we do with source_any stuff? Does that count?\n    # And actually should explicit anys count at all?? Maybe not!\n    return typ.type_of_any == TypeOfAny.explicit\n\n\ndef is_implicit_any(typ: Type) -> bool:\n    typ = get_proper_type(typ)\n    return isinstance(typ, AnyType) and not is_explicit_any(typ)\n\n\ndef _arg_accepts_function(typ: ProperType) -> bool:\n    return (\n        # TypeVar / Callable\n        isinstance(typ, (TypeVarType, CallableType))\n        or\n        # Protocol with __call__\n        isinstance(typ, Instance)\n        and typ.type.is_protocol\n        and typ.type.get_method(\"__call__\") is not None\n    )\n\n\nclass SuggestionEngine:\n    \"\"\"Engine for finding call sites and suggesting signatures.\"\"\"\n\n    def __init__(\n        self,\n        fgmanager: FineGrainedBuildManager,\n        *,\n        json: bool,\n        no_errors: bool = False,\n        no_any: bool = False,\n        flex_any: float | None = None,\n        use_fixme: str | None = None,\n        max_guesses: int | None = None,\n    ) -> None:\n        self.fgmanager = fgmanager\n        self.manager = fgmanager.manager\n        self.plugin = self.manager.plugin\n        self.graph = fgmanager.graph\n        self.finder = SourceFinder(self.manager.fscache, self.manager.options)\n\n        self.give_json = json\n        self.no_errors = no_errors\n        self.flex_any = flex_any\n        if no_any:\n            self.flex_any = 1.0\n\n        self.max_guesses = max_guesses or 64\n        self.use_fixme = use_fixme\n\n    def suggest(self, function: str) -> str:\n        \"\"\"Suggest an inferred type for function.\"\"\"\n        mod, func_name, node = self.find_node(function)\n\n        with self.restore_after(mod):\n            with self.with_export_types():\n                suggestion = self.get_suggestion(mod, node)\n\n        if self.give_json:\n            return self.json_suggestion(mod, func_name, node, suggestion)\n        else:\n            return self.format_signature(suggestion)\n\n    def suggest_callsites(self, function: str) -> str:\n        \"\"\"Find a list of call sites of function.\"\"\"\n        mod, _, node = self.find_node(function)\n        with self.restore_after(mod):\n            callsites, _ = self.get_callsites(node)\n\n        return \"\\n\".join(\n            dedup(\n                [\n                    f\"{path}:{line}: {self.format_args(arg_kinds, arg_names, arg_types)}\"\n                    for path, line, arg_kinds, _, arg_names, arg_types in callsites\n                ]\n            )\n        )\n\n    @contextmanager\n    def restore_after(self, module: str) -> Iterator[None]:\n        \"\"\"Context manager that reloads a module after executing the body.\n\n        This should undo any damage done to the module state while mucking around.\n        \"\"\"\n        try:\n            yield\n        finally:\n            self.reload(self.graph[module])\n\n    @contextmanager\n    def with_export_types(self) -> Iterator[None]:\n        \"\"\"Context manager that enables the export_types flag in the body.\n\n        This causes type information to be exported into the manager's all_types variable.\n        \"\"\"\n        old = self.manager.options.export_types\n        self.manager.options.export_types = True\n        try:\n            yield\n        finally:\n            self.manager.options.export_types = old\n\n    def get_trivial_type(self, fdef: FuncDef) -> CallableType:\n        \"\"\"Generate a trivial callable type from a func def, with all Anys\"\"\"\n        # The Anys are marked as being from the suggestion engine\n        # since they need some special treatment (specifically,\n        # constraint generation ignores them.)\n        return CallableType(\n            [AnyType(TypeOfAny.suggestion_engine) for _ in fdef.arg_kinds],\n            fdef.arg_kinds,\n            fdef.arg_names,\n            AnyType(TypeOfAny.suggestion_engine),\n            self.named_type(\"builtins.function\"),\n        )\n\n    def get_starting_type(self, fdef: FuncDef) -> CallableType:\n        if isinstance(fdef.type, CallableType):\n            return make_suggestion_anys(fdef.type)\n        else:\n            return self.get_trivial_type(fdef)\n\n    def get_args(\n        self,\n        is_method: bool,\n        base: CallableType,\n        defaults: list[Type | None],\n        callsites: list[Callsite],\n        uses: list[list[Type]],\n    ) -> list[list[Type]]:\n        \"\"\"Produce a list of type suggestions for each argument type.\"\"\"\n        types: list[list[Type]] = []\n        for i in range(len(base.arg_kinds)):\n            # Make self args Any but this will get overridden somewhere in the checker\n            if i == 0 and is_method:\n                types.append([AnyType(TypeOfAny.suggestion_engine)])\n                continue\n\n            all_arg_types = []\n            for call in callsites:\n                for typ in call.arg_types[i - is_method]:\n                    # Collect all the types except for implicit anys\n                    if not is_implicit_any(typ):\n                        all_arg_types.append(typ)\n            all_use_types = []\n            for typ in uses[i]:\n                # Collect all the types except for implicit anys\n                if not is_implicit_any(typ):\n                    all_use_types.append(typ)\n            # Add in any default argument types\n            default = defaults[i]\n            if default:\n                all_arg_types.append(default)\n                if all_use_types:\n                    all_use_types.append(default)\n\n            arg_types = []\n\n            if all_arg_types and all(\n                isinstance(get_proper_type(tp), NoneType) for tp in all_arg_types\n            ):\n                arg_types.append(\n                    UnionType.make_union([all_arg_types[0], AnyType(TypeOfAny.explicit)])\n                )\n            elif all_arg_types:\n                arg_types.extend(generate_type_combinations(all_arg_types))\n            else:\n                arg_types.append(AnyType(TypeOfAny.explicit))\n\n            if all_use_types:\n                # This is a meet because the type needs to be compatible with all the uses\n                arg_types.append(meet_type_list(all_use_types))\n\n            types.append(arg_types)\n        return types\n\n    def get_default_arg_types(self, fdef: FuncDef) -> list[Type | None]:\n        return [\n            self.manager.all_types[arg.initializer] if arg.initializer else None\n            for arg in fdef.arguments\n        ]\n\n    def get_guesses(\n        self,\n        is_method: bool,\n        base: CallableType,\n        defaults: list[Type | None],\n        callsites: list[Callsite],\n        uses: list[list[Type]],\n    ) -> list[CallableType]:\n        \"\"\"Compute a list of guesses for a function's type.\n\n        This focuses just on the argument types, and doesn't change the provided return type.\n        \"\"\"\n        options = self.get_args(is_method, base, defaults, callsites, uses)\n\n        # Take the first `max_guesses` guesses.\n        product = itertools.islice(itertools.product(*options), 0, self.max_guesses)\n        return [refine_callable(base, base.copy_modified(arg_types=list(x))) for x in product]\n\n    def get_callsites(self, func: FuncDef) -> tuple[list[Callsite], list[str]]:\n        \"\"\"Find all call sites of a function.\"\"\"\n        new_type = self.get_starting_type(func)\n\n        collector_plugin = SuggestionPlugin(func.fullname)\n\n        self.plugin._plugins.insert(0, collector_plugin)\n        try:\n            errors = self.try_type(func, new_type)\n        finally:\n            self.plugin._plugins.pop(0)\n\n        return collector_plugin.mystery_hits, errors\n\n    def filter_options(\n        self, guesses: list[CallableType], is_method: bool, ignore_return: bool\n    ) -> list[CallableType]:\n        \"\"\"Apply any configured filters to the possible guesses.\n\n        Currently the only option is filtering based on Any prevalance.\"\"\"\n        return [\n            t\n            for t in guesses\n            if self.flex_any is None\n            or any_score_callable(t, is_method, ignore_return) >= self.flex_any\n        ]\n\n    def find_best(self, func: FuncDef, guesses: list[CallableType]) -> tuple[CallableType, int]:\n        \"\"\"From a list of possible function types, find the best one.\n\n        For best, we want the fewest errors, then the best \"score\" from score_callable.\n        \"\"\"\n        if not guesses:\n            raise SuggestionFailure(\"No guesses that match criteria!\")\n        errors = {guess: self.try_type(func, guess) for guess in guesses}\n        best = min(guesses, key=lambda s: (count_errors(errors[s]), self.score_callable(s)))\n        return best, count_errors(errors[best])\n\n    def get_guesses_from_parent(self, node: FuncDef) -> list[CallableType]:\n        \"\"\"Try to get a guess of a method type from a parent class.\"\"\"\n        if not node.info:\n            return []\n\n        for parent in node.info.mro[1:]:\n            pnode = parent.names.get(node.name)\n            if pnode and isinstance(pnode.node, (FuncDef, Decorator)):\n                typ = get_proper_type(pnode.node.type)\n                # FIXME: Doesn't work right with generic types\n                if isinstance(typ, CallableType) and len(typ.arg_types) == len(node.arguments):\n                    # Return the first thing we find, since it probably doesn't make sense\n                    # to grab things further up in the chain if an earlier parent has it.\n                    return [typ]\n\n        return []\n\n    def get_suggestion(self, mod: str, node: FuncDef) -> PyAnnotateSignature:\n        \"\"\"Compute a suggestion for a function.\n\n        Return the type and whether the first argument should be ignored.\n        \"\"\"\n        graph = self.graph\n        callsites, orig_errors = self.get_callsites(node)\n        uses = get_arg_uses(self.manager.all_types, node)\n\n        if self.no_errors and orig_errors:\n            raise SuggestionFailure(\"Function does not typecheck.\")\n\n        is_method = bool(node.info) and node.has_self_or_cls_argument\n\n        with state.strict_optional_set(graph[mod].options.strict_optional):\n            guesses = self.get_guesses(\n                is_method,\n                self.get_starting_type(node),\n                self.get_default_arg_types(node),\n                callsites,\n                uses,\n            )\n        guesses += self.get_guesses_from_parent(node)\n        guesses = self.filter_options(guesses, is_method, ignore_return=True)\n        best, _ = self.find_best(node, guesses)\n\n        # Now try to find the return type!\n        self.try_type(node, best)\n        returns = get_return_types(self.manager.all_types, node)\n        with state.strict_optional_set(graph[mod].options.strict_optional):\n            if returns:\n                ret_types = generate_type_combinations(returns)\n            else:\n                ret_types = [NoneType()]\n\n        guesses = [best.copy_modified(ret_type=refine_type(best.ret_type, t)) for t in ret_types]\n        guesses = self.filter_options(guesses, is_method, ignore_return=False)\n        best, errors = self.find_best(node, guesses)\n\n        if self.no_errors and errors:\n            raise SuggestionFailure(\"No annotation without errors\")\n\n        return self.pyannotate_signature(mod, is_method, best)\n\n    def format_args(\n        self,\n        arg_kinds: list[list[ArgKind]],\n        arg_names: list[list[str | None]],\n        arg_types: list[list[Type]],\n    ) -> str:\n        args: list[str] = []\n        for i in range(len(arg_types)):\n            for kind, name, typ in zip(arg_kinds[i], arg_names[i], arg_types[i]):\n                arg = self.format_type(None, typ)\n                if kind == ARG_STAR:\n                    arg = \"*\" + arg\n                elif kind == ARG_STAR2:\n                    arg = \"**\" + arg\n                elif kind.is_named():\n                    if name:\n                        arg = f\"{name}={arg}\"\n            args.append(arg)\n        return f\"({', '.join(args)})\"\n\n    def find_node(self, key: str) -> tuple[str, str, FuncDef]:\n        \"\"\"From a target name, return module/target names and the func def.\n\n        The 'key' argument can be in one of two formats:\n        * As the function full name, e.g., package.module.Cls.method\n        * As the function location as file and line separated by column,\n          e.g., path/to/file.py:42\n        \"\"\"\n        # TODO: Also return OverloadedFuncDef -- currently these are ignored.\n        node: SymbolNode | None = None\n        if \":\" in key:\n            # A colon might be part of a drive name on Windows (like `C:/foo/bar`)\n            # and is also used as a delimiter between file path and lineno.\n            # If a colon is there for any of those reasons, it must be a file+line\n            # reference.\n            platform_key_count = 2 if sys.platform == \"win32\" else 1\n            if key.count(\":\") > platform_key_count:\n                raise SuggestionFailure(\n                    \"Malformed location for function: {}. Must be either\"\n                    \" package.module.Class.method or path/to/file.py:line\".format(key)\n                )\n            file, line = key.rsplit(\":\", 1)\n            if not line.isdigit():\n                raise SuggestionFailure(f\"Line number must be a number. Got {line}\")\n            line_number = int(line)\n            modname, node = self.find_node_by_file_and_line(file, line_number)\n            tail = node.fullname[len(modname) + 1 :]  # add one to account for '.'\n        else:\n            target = split_target(self.fgmanager.graph, key)\n            if not target:\n                raise SuggestionFailure(f\"Cannot find module for {key}\")\n            modname, tail = target\n            node = self.find_node_by_module_and_name(modname, tail)\n\n        if isinstance(node, Decorator):\n            node = self.extract_from_decorator(node)\n            if not node:\n                raise SuggestionFailure(f\"Object {key} is a decorator we can't handle\")\n\n        if not isinstance(node, FuncDef):\n            raise SuggestionFailure(f\"Object {key} is not a function\")\n\n        return modname, tail, node\n\n    def find_node_by_module_and_name(self, modname: str, tail: str) -> SymbolNode | None:\n        \"\"\"Find symbol node by module id and qualified name.\n\n        Raise SuggestionFailure if can't find one.\n        \"\"\"\n        tree = self.ensure_loaded(self.fgmanager.graph[modname])\n\n        # N.B. This is reimplemented from update's lookup_target\n        # basically just to produce better error messages.\n\n        names: SymbolTable = tree.names\n\n        # Look through any classes\n        components = tail.split(\".\")\n        for i, component in enumerate(components[:-1]):\n            if component not in names:\n                raise SuggestionFailure(\n                    \"Unknown class {}.{}\".format(modname, \".\".join(components[: i + 1]))\n                )\n            node: SymbolNode | None = names[component].node\n            if not isinstance(node, TypeInfo):\n                raise SuggestionFailure(\n                    \"Object {}.{} is not a class\".format(modname, \".\".join(components[: i + 1]))\n                )\n            names = node.names\n\n        # Look for the actual function/method\n        funcname = components[-1]\n        if funcname not in names:\n            key = modname + \".\" + tail\n            raise SuggestionFailure(\n                \"Unknown {} {}\".format(\"method\" if len(components) > 1 else \"function\", key)\n            )\n        return names[funcname].node\n\n    def find_node_by_file_and_line(self, file: str, line: int) -> tuple[str, SymbolNode]:\n        \"\"\"Find symbol node by path to file and line number.\n\n        Find the first function declared *before or on* the line number.\n\n        Return module id and the node found. Raise SuggestionFailure if can't find one.\n        \"\"\"\n        if not any(file.endswith(ext) for ext in PYTHON_EXTENSIONS):\n            raise SuggestionFailure(\"Source file is not a Python file\")\n        try:\n            modname, _ = self.finder.crawl_up(os.path.normpath(file))\n        except InvalidSourceList as e:\n            raise SuggestionFailure(\"Invalid source file name: \" + file) from e\n        if modname not in self.graph:\n            raise SuggestionFailure(\"Unknown module: \" + modname)\n        # We must be sure about any edits in this file as this might affect the line numbers.\n        tree = self.ensure_loaded(self.fgmanager.graph[modname], force=True)\n        node: SymbolNode | None = None\n        closest_line: int | None = None\n        # TODO: Handle nested functions.\n        for _, sym, _ in tree.local_definitions():\n            if isinstance(sym.node, (FuncDef, Decorator)):\n                sym_line = sym.node.line\n            # TODO: add support for OverloadedFuncDef.\n            else:\n                continue\n\n            # We want the closest function above the specified line\n            if sym_line <= line and (closest_line is None or sym_line > closest_line):\n                closest_line = sym_line\n                node = sym.node\n        if not node:\n            raise SuggestionFailure(f\"Cannot find a function at line {line}\")\n        return modname, node\n\n    def extract_from_decorator(self, node: Decorator) -> FuncDef | None:\n        for dec in node.decorators:\n            typ = None\n            if isinstance(dec, RefExpr) and isinstance(dec.node, (Var, FuncDef)):\n                typ = get_proper_type(dec.node.type)\n            elif (\n                isinstance(dec, CallExpr)\n                and isinstance(dec.callee, RefExpr)\n                and isinstance(dec.callee.node, (Decorator, FuncDef, Var))\n                and isinstance((call_tp := get_proper_type(dec.callee.node.type)), CallableType)\n            ):\n                typ = get_proper_type(call_tp.ret_type)\n\n            if isinstance(typ, Instance):\n                call_method = typ.type.get_method(\"__call__\")\n                if isinstance(call_method, FuncDef) and isinstance(call_method.type, FunctionLike):\n                    typ = bind_self(call_method.type, None)\n\n            if not isinstance(typ, FunctionLike):\n                return None\n            for ct in typ.items:\n                if not (\n                    len(ct.arg_types) == 1\n                    and _arg_accepts_function(get_proper_type(ct.arg_types[0]))\n                    and ct.arg_types[0] == ct.ret_type\n                ):\n                    return None\n\n        return node.func\n\n    def try_type(self, func: FuncDef, typ: ProperType) -> list[str]:\n        \"\"\"Recheck a function while assuming it has type typ.\n\n        Return all error messages.\n        \"\"\"\n        old = func.unanalyzed_type\n        # During reprocessing, unanalyzed_type gets copied to type (by aststrip).\n        # We set type to None to ensure that the type always changes during\n        # reprocessing.\n        func.type = None\n        func.unanalyzed_type = typ\n        try:\n            res = self.fgmanager.trigger(func.fullname)\n            # if res:\n            #     print('===', typ)\n            #     print('\\n'.join(res))\n            return res\n        finally:\n            func.unanalyzed_type = old\n\n    def reload(self, state: State) -> list[str]:\n        \"\"\"Recheck the module given by state.\"\"\"\n        assert state.path is not None\n        self.fgmanager.flush_cache()\n        return self.fgmanager.update([(state.id, state.path)], [])\n\n    def ensure_loaded(self, state: State, force: bool = False) -> MypyFile:\n        \"\"\"Make sure that the module represented by state is fully loaded.\"\"\"\n        if not state.tree or state.tree.is_cache_skeleton or force:\n            self.reload(state)\n        assert state.tree is not None\n        return state.tree\n\n    def named_type(self, s: str) -> Instance:\n        return self.manager.semantic_analyzer.named_type(s)\n\n    def json_suggestion(\n        self, mod: str, func_name: str, node: FuncDef, suggestion: PyAnnotateSignature\n    ) -> str:\n        \"\"\"Produce a json blob for a suggestion suitable for application by pyannotate.\"\"\"\n        # pyannotate irritatingly drops class names for class and static methods\n        if node.is_class or node.is_static:\n            func_name = func_name.split(\".\", 1)[-1]\n\n        # pyannotate works with either paths relative to where the\n        # module is rooted or with absolute paths. We produce absolute\n        # paths because it is simpler.\n        path = os.path.abspath(self.graph[mod].xpath)\n\n        obj = {\n            \"signature\": suggestion,\n            \"line\": node.line,\n            \"path\": path,\n            \"func_name\": func_name,\n            \"samples\": 0,\n        }\n        return json.dumps([obj], sort_keys=True)\n\n    def pyannotate_signature(\n        self, cur_module: str | None, is_method: bool, typ: CallableType\n    ) -> PyAnnotateSignature:\n        \"\"\"Format a callable type as a pyannotate dict\"\"\"\n        start = int(is_method)\n        return {\n            \"arg_types\": [self.format_type(cur_module, t) for t in typ.arg_types[start:]],\n            \"return_type\": self.format_type(cur_module, typ.ret_type),\n        }\n\n    def format_signature(self, sig: PyAnnotateSignature) -> str:\n        \"\"\"Format a callable type in a way suitable as an annotation... kind of\"\"\"\n        return f\"({', '.join(sig['arg_types'])}) -> {sig['return_type']}\"\n\n    def format_type(self, cur_module: str | None, typ: Type) -> str:\n        if self.use_fixme and isinstance(get_proper_type(typ), AnyType):\n            return self.use_fixme\n        return typ.accept(TypeFormatter(cur_module, self.graph, self.manager.options))\n\n    def score_type(self, t: Type, arg_pos: bool) -> int:\n        \"\"\"Generate a score for a type that we use to pick which type to use.\n\n        Lower is better, prefer non-union/non-any types. Don't penalize optionals.\n        \"\"\"\n        t = get_proper_type(t)\n        if isinstance(t, AnyType):\n            return 20\n        if arg_pos and isinstance(t, NoneType):\n            return 20\n        if isinstance(t, UnionType):\n            if any(isinstance(get_proper_type(x), AnyType) for x in t.items):\n                return 20\n            if any(has_any_type(x) for x in t.items):\n                return 15\n            if not is_overlapping_none(t):\n                return 10\n        if isinstance(t, CallableType) and (has_any_type(t) or is_tricky_callable(t)):\n            return 10\n        return 0\n\n    def score_callable(self, t: CallableType) -> int:\n        return sum(self.score_type(x, arg_pos=True) for x in t.arg_types) + self.score_type(\n            t.ret_type, arg_pos=False\n        )\n\n\ndef any_score_type(ut: Type, arg_pos: bool) -> float:\n    \"\"\"Generate a very made up number representing the Anyness of a type.\n\n    Higher is better, 1.0 is max\n    \"\"\"\n    t = get_proper_type(ut)\n    if isinstance(t, AnyType) and t.type_of_any != TypeOfAny.suggestion_engine:\n        return 0\n    if isinstance(t, NoneType) and arg_pos:\n        return 0.5\n    if isinstance(t, UnionType):\n        if any(isinstance(get_proper_type(x), AnyType) for x in t.items):\n            return 0.5\n        if any(has_any_type(x) for x in t.items):\n            return 0.25\n    if isinstance(t, CallableType) and is_tricky_callable(t):\n        return 0.5\n    if has_any_type(t):\n        return 0.5\n\n    return 1.0\n\n\ndef any_score_callable(t: CallableType, is_method: bool, ignore_return: bool) -> float:\n    # Ignore the first argument of methods\n    scores = [any_score_type(x, arg_pos=True) for x in t.arg_types[int(is_method) :]]\n    # Return type counts twice (since it spreads type information), unless it is\n    # None in which case it does not count at all. (Though it *does* still count\n    # if there are no arguments.)\n    if not isinstance(get_proper_type(t.ret_type), NoneType) or not scores:\n        ret = 1.0 if ignore_return else any_score_type(t.ret_type, arg_pos=False)\n        scores += [ret, ret]\n\n    return sum(scores) / len(scores)\n\n\ndef is_tricky_callable(t: CallableType) -> bool:\n    \"\"\"Is t a callable that we need to put a ... in for syntax reasons?\"\"\"\n    return t.is_ellipsis_args or any(k.is_star() or k.is_named() for k in t.arg_kinds)\n\n\nclass TypeFormatter(TypeStrVisitor):\n    \"\"\"Visitor used to format types\"\"\"\n\n    # TODO: Probably a lot\n    def __init__(self, module: str | None, graph: Graph, options: Options) -> None:\n        super().__init__(options=options)\n        self.module = module\n        self.graph = graph\n\n    def visit_any(self, t: AnyType) -> str:\n        if t.missing_import_name:\n            return t.missing_import_name\n        else:\n            return \"Any\"\n\n    def visit_instance(self, t: Instance) -> str:\n        s = t.type.fullname or t.type.name or None\n        if s is None:\n            return \"<???>\"\n\n        mod_obj = split_target(self.graph, s)\n        assert mod_obj\n        mod, obj = mod_obj\n\n        # If a class is imported into the current module, rewrite the reference\n        # to point to the current module. This helps the annotation tool avoid\n        # inserting redundant imports when a type has been reexported.\n        if self.module:\n            parts = obj.split(\".\")  # need to split the object part if it is a nested class\n            tree = self.graph[self.module].tree\n            if tree and parts[0] in tree.names and mod not in tree.names:\n                mod = self.module\n\n        if (mod, obj) == (\"builtins\", \"tuple\"):\n            mod, obj = \"typing\", \"Tuple[\" + t.args[0].accept(self) + \", ...]\"\n        elif t.args:\n            obj += f\"[{self.list_str(t.args)}]\"\n\n        if mod_obj == (\"builtins\", \"unicode\"):\n            return \"Text\"\n        elif mod == \"builtins\":\n            return obj\n        else:\n            delim = \".\" if \".\" not in obj else \":\"\n            return mod + delim + obj\n\n    def visit_tuple_type(self, t: TupleType) -> str:\n        if t.partial_fallback and t.partial_fallback.type:\n            fallback_name = t.partial_fallback.type.fullname\n            if fallback_name != \"builtins.tuple\":\n                return t.partial_fallback.accept(self)\n        s = self.list_str(t.items)\n        return f\"Tuple[{s}]\"\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> str:\n        return \"Any\"\n\n    def visit_typeddict_type(self, t: TypedDictType) -> str:\n        return t.fallback.accept(self)\n\n    def visit_union_type(self, t: UnionType) -> str:\n        if len(t.items) == 2 and is_overlapping_none(t):\n            s = remove_optional(t).accept(self)\n            return f\"{s} | None\"\n        else:\n            return super().visit_union_type(t)\n\n    def visit_callable_type(self, t: CallableType) -> str:\n        # TODO: use extended callables?\n        if is_tricky_callable(t):\n            arg_str = \"...\"\n        else:\n            # Note: for default arguments, we just assume that they\n            # are required.  This isn't right, but neither is the\n            # other thing, and I suspect this will produce more better\n            # results than falling back to `...`\n            args = [typ.accept(self) for typ in t.arg_types]\n            arg_str = f\"[{', '.join(args)}]\"\n\n        return f\"Callable[{arg_str}, {t.ret_type.accept(self)}]\"\n\n\nTType = TypeVar(\"TType\", bound=Type)\n\n\ndef make_suggestion_anys(t: TType) -> TType:\n    \"\"\"Make all anys in the type as coming from the suggestion engine.\n\n    This keeps those Anys from influencing constraint generation,\n    which allows us to do better when refining types.\n    \"\"\"\n    return cast(TType, t.accept(MakeSuggestionAny()))\n\n\nclass MakeSuggestionAny(TypeTranslator):\n    def visit_any(self, t: AnyType) -> Type:\n        if not t.missing_import_name:\n            return t.copy_modified(type_of_any=TypeOfAny.suggestion_engine)\n        else:\n            return t\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        return t.copy_modified(args=[a.accept(self) for a in t.args])\n\n\ndef generate_type_combinations(types: list[Type]) -> list[Type]:\n    \"\"\"Generate possible combinations of a list of types.\n\n    mypy essentially supports two different ways to do this: joining the types\n    and unioning the types. We try both.\n    \"\"\"\n    joined_type = join_type_list(types)\n    union_type = make_simplified_union(types)\n    if joined_type == union_type:\n        return [joined_type]\n    else:\n        return [joined_type, union_type]\n\n\ndef count_errors(msgs: list[str]) -> int:\n    return len([x for x in msgs if \" error: \" in x])\n\n\ndef refine_type(ti: Type, si: Type) -> Type:\n    \"\"\"Refine `ti` by replacing Anys in it with information taken from `si`\n\n    This basically works by, when the types have the same structure,\n    traversing both of them in parallel and replacing Any on the left\n    with whatever the type on the right is. If the types don't have the\n    same structure (or aren't supported), the left type is chosen.\n\n    For example:\n      refine(Any, T) = T,  for all T\n      refine(float, int) = float\n      refine(List[Any], List[int]) = List[int]\n      refine(Dict[int, Any], Dict[Any, int]) = Dict[int, int]\n      refine(Tuple[int, Any], Tuple[Any, int]) = Tuple[int, int]\n\n      refine(Callable[[Any], Any], Callable[[int], int]) = Callable[[int], int]\n      refine(Callable[..., int], Callable[[int, float], Any]) = Callable[[int, float], int]\n\n      refine(Optional[Any], int) = Optional[int]\n      refine(Optional[Any], Optional[int]) = Optional[int]\n      refine(Optional[Any], Union[int, str]) = Optional[Union[int, str]]\n      refine(Optional[List[Any]], List[int]) = List[int]\n\n    \"\"\"\n    t = get_proper_type(ti)\n    s = get_proper_type(si)\n\n    if isinstance(t, AnyType):\n        # If s is also an Any, we return if it is a missing_import Any\n        return t if isinstance(s, AnyType) and t.missing_import_name else s\n\n    if isinstance(t, Instance) and isinstance(s, Instance) and t.type == s.type:\n        return t.copy_modified(args=[refine_type(ta, sa) for ta, sa in zip(t.args, s.args)])\n\n    if (\n        isinstance(t, TupleType)\n        and isinstance(s, TupleType)\n        and t.partial_fallback == s.partial_fallback\n        and len(t.items) == len(s.items)\n    ):\n        return t.copy_modified(items=[refine_type(ta, sa) for ta, sa in zip(t.items, s.items)])\n\n    if isinstance(t, CallableType) and isinstance(s, CallableType):\n        return refine_callable(t, s)\n\n    if isinstance(t, UnionType):\n        return refine_union(t, s)\n\n    # TODO: Refining of builtins.tuple, Type?\n\n    return t\n\n\ndef refine_union(t: UnionType, s: ProperType) -> Type:\n    \"\"\"Refine a union type based on another type.\n\n    This is done by refining every component of the union against the\n    right hand side type (or every component of its union if it is\n    one). If an element of the union is successfully refined, we drop it\n    from the union in favor of the refined versions.\n    \"\"\"\n    # Don't try to do any union refining if the types are already the\n    # same.  This prevents things like refining Optional[Any] against\n    # itself and producing None.\n    if t == s:\n        return t\n\n    rhs_items = s.items if isinstance(s, UnionType) else [s]\n\n    new_items = []\n    for lhs in t.items:\n        refined = False\n        for rhs in rhs_items:\n            new = refine_type(lhs, rhs)\n            if new != lhs:\n                new_items.append(new)\n                refined = True\n        if not refined:\n            new_items.append(lhs)\n\n    # Turn strict optional on when simplifying the union since we\n    # don't want to drop Nones.\n    with state.strict_optional_set(True):\n        return make_simplified_union(new_items)\n\n\ndef refine_callable(t: CallableType, s: CallableType) -> CallableType:\n    \"\"\"Refine a callable based on another.\n\n    See comments for refine_type.\n    \"\"\"\n    if t.fallback != s.fallback:\n        return t\n\n    if t.is_ellipsis_args and not is_tricky_callable(s):\n        return s.copy_modified(ret_type=refine_type(t.ret_type, s.ret_type))\n\n    if is_tricky_callable(t) or t.arg_kinds != s.arg_kinds:\n        return t\n\n    return t.copy_modified(\n        arg_types=[refine_type(ta, sa) for ta, sa in zip(t.arg_types, s.arg_types)],\n        ret_type=refine_type(t.ret_type, s.ret_type),\n    )\n\n\nT = TypeVar(\"T\")\n\n\ndef dedup(old: list[T]) -> list[T]:\n    new: list[T] = []\n    for x in old:\n        if x not in new:\n            new.append(x)\n    return new\n"
  },
  {
    "path": "mypy/test/__init__.py",
    "content": ""
  },
  {
    "path": "mypy/test/config.py",
    "content": "from __future__ import annotations\n\nimport os.path\n\nprovided_prefix = os.getenv(\"MYPY_TEST_PREFIX\", None)\nif provided_prefix:\n    PREFIX = provided_prefix\nelse:\n    this_file_dir = os.path.dirname(os.path.realpath(__file__))\n    PREFIX = os.path.dirname(os.path.dirname(this_file_dir))\n\n# Location of test data files such as test case descriptions.\ntest_data_prefix = os.path.join(PREFIX, \"test-data\", \"unit\")\npackage_path = os.path.join(PREFIX, \"test-data\", \"packages\")\n\n# Temp directory used for the temp files created when running test cases.\n# This is *within* the tempfile.TemporaryDirectory that is chroot'ed per testcase.\n# It is also hard-coded in numerous places, so don't change it.\ntest_temp_dir = \"tmp\"\n\n# Mypyc tests may write intermediate files (e.g. generated C) here on failure\nmypyc_output_dir = os.path.join(PREFIX, \".mypyc_test_output\")\n\n# The PEP 561 tests do a bunch of pip installs which, even though they operate\n# on distinct temporary virtual environments, run into race conditions on shared\n# file-system state. To make this work reliably in parallel mode, we'll use a\n# FileLock courtesy of the tox-dev/py-filelock package.\n# Ref. https://github.com/python/mypy/issues/12615\n# Ref. mypy/test/testpep561.py\npip_lock = os.path.join(package_path, \".pip_lock\")\npip_timeout = 60\n"
  },
  {
    "path": "mypy/test/data.py",
    "content": "\"\"\"Utilities for processing .test files containing test case descriptions.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport os.path\nimport posixpath\nimport re\nimport shutil\nimport sys\nimport tempfile\nfrom abc import abstractmethod\nfrom collections.abc import Iterator\nfrom dataclasses import dataclass\nfrom pathlib import Path\nfrom re import Pattern\nfrom typing import Any, Final, NamedTuple, NoReturn, TypeAlias as _TypeAlias\n\nimport pytest\n\nfrom mypy import defaults\nfrom mypy.test.config import PREFIX, mypyc_output_dir, test_data_prefix, test_temp_dir\n\nroot_dir = os.path.normpath(PREFIX)\n\n# Debuggers that we support for debugging mypyc run tests\n# implementation of using each of these debuggers is in test_run.py\n# TODO: support more debuggers\nSUPPORTED_DEBUGGERS: Final = [\"gdb\", \"lldb\"]\n\n\n# File modify/create operation: copy module contents from source_path.\nclass UpdateFile(NamedTuple):\n    module: str\n    content: str\n    target_path: str\n\n\n# File delete operation: delete module file.\nclass DeleteFile(NamedTuple):\n    module: str\n    path: str\n\n\nFileOperation: _TypeAlias = UpdateFile | DeleteFile\n\n\ndef _file_arg_to_module(filename: str) -> str:\n    filename, _ = os.path.splitext(filename)\n    parts = filename.split(\"/\")  # not os.sep since it comes from test data\n    if parts[-1] == \"__init__\":\n        parts.pop()\n    return \".\".join(parts)\n\n\ndef parse_test_case(case: DataDrivenTestCase) -> None:\n    \"\"\"Parse and prepare a single case from suite with test case descriptions.\n\n    This method is part of the setup phase, just before the test case is run.\n    \"\"\"\n    test_items = parse_test_data(case.data, case.name)\n    base_path = case.suite.base_path\n    if case.suite.native_sep:\n        join = os.path.join\n    else:\n        join = posixpath.join\n\n    out_section_missing = case.suite.required_out_section\n\n    files: list[tuple[str, str]] = []  # path and contents\n    output_files: list[tuple[str, str | Pattern[str]]] = []  # output path and contents\n    output: list[str] = []  # Regular output errors\n    output2: dict[int, list[str]] = {}  # Output errors for incremental, runs 2+\n    deleted_paths: dict[int, set[str]] = {}  # from run number of paths\n    stale_modules: dict[int, set[str]] = {}  # from run number to module names\n    rechecked_modules: dict[int, set[str]] = {}  # from run number module names\n    triggered: list[str] = []  # Active triggers (one line per incremental step)\n    targets: dict[int, list[str]] = {}  # Fine-grained targets (per fine-grained update)\n    test_modules: list[str] = []  # Modules which are deemed \"test\" (vs \"fixture\")\n\n    def _case_fail(msg: str) -> NoReturn:\n        pytest.fail(f\"{case.file}:{case.line}: {msg}\", pytrace=False)\n\n    # Process the parsed items. Each item has a header of form [id args],\n    # optionally followed by lines of text.\n    item = first_item = test_items[0]\n    test_modules.append(\"__main__\")\n    for item in test_items[1:]:\n\n        def _item_fail(msg: str) -> NoReturn:\n            item_abs_line = case.line + item.line - 2\n            pytest.fail(f\"{case.file}:{item_abs_line}: {msg}\", pytrace=False)\n\n        if item.id in {\"file\", \"fixture\", \"outfile\", \"outfile-re\"}:\n            # Record an extra file needed for the test case.\n            assert item.arg is not None\n            contents = expand_variables(\"\\n\".join(item.data))\n            path = join(base_path, item.arg)\n            if item.id != \"fixture\":\n                test_modules.append(_file_arg_to_module(item.arg))\n            if item.id in {\"file\", \"fixture\"}:\n                files.append((path, contents))\n            elif item.id == \"outfile-re\":\n                output_files.append((path, re.compile(contents.rstrip(), re.S)))\n            elif item.id == \"outfile\":\n                output_files.append((path, contents))\n        elif item.id == \"builtins\":\n            # Use an alternative stub file for the builtins module.\n            assert item.arg is not None\n            mpath = join(os.path.dirname(case.file), item.arg)\n            with open(mpath, encoding=\"utf8\") as f:\n                files.append((join(base_path, \"builtins.pyi\"), f.read()))\n        elif item.id == \"typing\":\n            # Use an alternative stub file for the typing module.\n            assert item.arg is not None\n            src_path = join(os.path.dirname(case.file), item.arg)\n            with open(src_path, encoding=\"utf8\") as f:\n                files.append((join(base_path, \"typing.pyi\"), f.read()))\n        elif item.id == \"_typeshed\":\n            # Use an alternative stub file for the _typeshed module.\n            assert item.arg is not None\n            src_path = join(os.path.dirname(case.file), item.arg)\n            with open(src_path, encoding=\"utf8\") as f:\n                files.append((join(base_path, \"_typeshed.pyi\"), f.read()))\n        elif re.match(r\"stale[0-9]*$\", item.id):\n            passnum = 1 if item.id == \"stale\" else int(item.id[len(\"stale\") :])\n            assert passnum > 0\n            modules = set() if item.arg is None else {t.strip() for t in item.arg.split(\",\")}\n            stale_modules[passnum] = modules\n        elif re.match(r\"rechecked[0-9]*$\", item.id):\n            passnum = 1 if item.id == \"rechecked\" else int(item.id[len(\"rechecked\") :])\n            assert passnum > 0\n            modules = set() if item.arg is None else {t.strip() for t in item.arg.split(\",\")}\n            rechecked_modules[passnum] = modules\n        elif re.match(r\"targets[0-9]*$\", item.id):\n            passnum = 1 if item.id == \"targets\" else int(item.id[len(\"targets\") :])\n            assert passnum > 0\n            reprocessed = [] if item.arg is None else [t.strip() for t in item.arg.split(\",\")]\n            targets[passnum] = reprocessed\n        elif item.id == \"delete\":\n            # File/directory to delete during a multi-step test case\n            assert item.arg is not None\n            m = re.match(r\"(.*)\\.([0-9]+)$\", item.arg)\n            if m is None:\n                _item_fail(f\"Invalid delete section {item.arg!r}\")\n            num = int(m.group(2))\n            if num < 2:\n                _item_fail(f\"Can't delete during step {num}\")\n            full = join(base_path, m.group(1))\n            deleted_paths.setdefault(num, set()).add(full)\n        elif re.match(r\"out[0-9]*$\", item.id):\n            if item.arg is None:\n                args = []\n            else:\n                args = item.arg.split(\",\")\n\n            version_check = True\n            for arg in args:\n                if arg.startswith(\"version\"):\n                    compare_op = arg[7:9]\n                    if compare_op not in {\">=\", \"==\"}:\n                        _item_fail(\"Only >= and == version checks are currently supported\")\n                    version_str = arg[9:]\n                    try:\n                        version = tuple(int(x) for x in version_str.split(\".\"))\n                    except ValueError:\n                        _item_fail(f\"{version_str!r} is not a valid python version\")\n                    if compare_op == \">=\":\n                        if version <= defaults.PYTHON3_VERSION:\n                            _item_fail(\n                                f\"{arg} always true since minimum runtime version is {defaults.PYTHON3_VERSION}\"\n                            )\n                        version_check = sys.version_info >= version\n                    elif compare_op == \"==\":\n                        if version < defaults.PYTHON3_VERSION:\n                            _item_fail(\n                                f\"{arg} always false since minimum runtime version is {defaults.PYTHON3_VERSION}\"\n                            )\n                        if not 1 < len(version) < 4:\n                            _item_fail(\n                                f'Only minor or patch version checks are currently supported with \"==\": {version_str!r}'\n                            )\n                        version_check = sys.version_info[: len(version)] == version\n            if version_check:\n                tmp_output = [expand_variables(line) for line in item.data]\n                if os.path.sep == \"\\\\\" and case.normalize_output:\n                    tmp_output = [fix_win_path(line) for line in tmp_output]\n                if item.id == \"out\" or item.id == \"out1\":\n                    output = tmp_output\n                else:\n                    passnum = int(item.id[len(\"out\") :])\n                    assert passnum > 1\n                    output2[passnum] = tmp_output\n                out_section_missing = False\n        elif item.id == \"triggered\" and item.arg is None:\n            triggered = item.data\n        else:\n            section_str = item.id + (f\" {item.arg}\" if item.arg else \"\")\n            _item_fail(f\"Invalid section header [{section_str}] in case {case.name!r}\")\n\n    if out_section_missing:\n        _case_fail(f\"Required output section not found in case {case.name!r}\")\n\n    for passnum in stale_modules.keys():\n        if passnum not in rechecked_modules:\n            # If the set of rechecked modules isn't specified, make it the same as the set\n            # of modules with a stale public interface.\n            rechecked_modules[passnum] = stale_modules[passnum]\n        if (\n            passnum in stale_modules\n            and passnum in rechecked_modules\n            and not stale_modules[passnum].issubset(rechecked_modules[passnum])\n        ):\n            _case_fail(f\"Stale modules after pass {passnum} must be a subset of rechecked modules\")\n\n    output_inline_start = len(output)\n    input = first_item.data\n    expand_errors(input, output, \"main\")\n    for file_path, contents in files:\n        expand_errors(contents.split(\"\\n\"), output, file_path)\n\n    seen_files = set()\n    for file, _ in files:\n        if file in seen_files:\n            _case_fail(f\"Duplicated filename {file}. Did you include it multiple times?\")\n\n        seen_files.add(file)\n\n    case.input = input\n    case.output = output\n    case.output_inline_start = output_inline_start\n    case.output2 = output2\n    case.last_line = case.line + item.line + len(item.data) - 2\n    case.files = files\n    case.output_files = output_files\n    case.expected_stale_modules = stale_modules\n    case.expected_rechecked_modules = rechecked_modules\n    case.deleted_paths = deleted_paths\n    case.triggered = triggered or []\n    case.expected_fine_grained_targets = targets\n    case.test_modules = test_modules\n\n\nclass DataDrivenTestCase(pytest.Item):\n    \"\"\"Holds parsed data-driven test cases, and handles directory setup and teardown.\"\"\"\n\n    # Override parent member type\n    parent: DataFileCollector\n\n    input: list[str]\n    output: list[str]  # Output for the first pass\n    output_inline_start: int\n    output2: dict[int, list[str]]  # Output for runs 2+, indexed by run number\n\n    # full path of test suite\n    file = \"\"\n    line = 0\n\n    # (file path, file content) tuples\n    files: list[tuple[str, str]]\n    # Modules which is to be considered \"test\" rather than \"fixture\"\n    test_modules: list[str]\n    expected_stale_modules: dict[int, set[str]]\n    expected_rechecked_modules: dict[int, set[str]]\n    expected_fine_grained_targets: dict[int, list[str]]\n\n    # Whether or not we should normalize the output to standardize things like\n    # forward vs backward slashes in file paths for Windows vs Linux.\n    normalize_output: bool\n\n    # Extra attributes used by some tests.\n    last_line: int\n    output_files: list[tuple[str, str | Pattern[str]]]  # Path and contents for output files\n    deleted_paths: dict[int, set[str]]  # Mapping run number -> paths\n    triggered: list[str]  # Active triggers (one line per incremental step)\n\n    def __init__(\n        self,\n        parent: DataFileCollector,\n        suite: DataSuite,\n        *,\n        file: str,\n        name: str,\n        writescache: bool,\n        only_when: str,\n        normalize_output: bool,\n        platform: str | None,\n        skip: bool,\n        xfail: bool,\n        data: str,\n        line: int,\n    ) -> None:\n        assert isinstance(parent, DataFileCollector)\n        super().__init__(name, parent)\n        self.suite = suite\n        self.file = file\n        self.writescache = writescache\n        self.only_when = only_when\n        self.normalize_output = normalize_output\n        if (platform == \"windows\" and sys.platform != \"win32\") or (\n            platform == \"posix\" and sys.platform == \"win32\"\n        ):\n            skip = True\n        self.skip = skip\n        self.xfail = xfail\n        self.data = data\n        self.line = line\n        self.old_cwd: str | None = None\n        self.tmpdir: str | None = None\n\n    def runtest(self) -> None:\n        if self.skip:\n            pytest.skip()\n        # TODO: add a better error message for when someone uses skip and xfail at the same time\n        elif self.xfail:\n            self.add_marker(pytest.mark.xfail)\n\n        if (\n            not [line for line in self.input if line.strip()]\n            and \"Empty\" not in self.name\n            and not [\n                file\n                for file in self.files\n                # these files are added based on other things\n                if os.path.basename(file[0]) not in (\"typing.pyi\", \"_typeshed.pyi\", \"builtins.pyi\")\n            ]\n        ):\n            raise AssertionError(f\"{self.name} is empty.\")\n\n        parent = self.getparent(DataSuiteCollector)\n        assert parent is not None, \"Should not happen\"\n        suite = parent.obj()\n        suite.setup()\n        try:\n            suite.run_case(self)\n        except Exception:\n            # As a debugging aid, support copying the contents of the tmp directory somewhere\n            save_dir: str | None = self.config.getoption(\"--save-failures-to\", None)\n            if save_dir:\n                assert self.tmpdir is not None\n                target_dir = os.path.join(save_dir, os.path.basename(self.tmpdir))\n                print(f\"Copying data from test {self.name} to {target_dir}\")\n                if not os.path.isabs(target_dir):\n                    assert self.old_cwd\n                    target_dir = os.path.join(self.old_cwd, target_dir)\n                shutil.copytree(self.tmpdir, target_dir)\n            raise\n\n    def setup(self) -> None:\n        parse_test_case(case=self)\n        self.old_cwd = os.getcwd()\n        self.tmpdir = tempfile.mkdtemp(prefix=\"mypy-test-\")\n        os.chdir(self.tmpdir)\n        os.mkdir(test_temp_dir)\n\n        # Precalculate steps for find_steps()\n        steps: dict[int, list[FileOperation]] = {}\n\n        for path, content in self.files:\n            m = re.match(r\".*\\.([0-9]+)$\", path)\n            if m:\n                # Skip writing subsequent incremental steps - rather\n                # store them as operations.\n                num = int(m.group(1))\n                assert num >= 2\n                target_path = re.sub(r\"\\.[0-9]+$\", \"\", path)\n                module = module_from_path(target_path)\n                operation = UpdateFile(module, content, target_path)\n                steps.setdefault(num, []).append(operation)\n            else:\n                # Write the first incremental steps\n                dir = os.path.dirname(path)\n                os.makedirs(dir, exist_ok=True)\n                with open(path, \"w\", encoding=\"utf8\") as f:\n                    f.write(content)\n\n        for num, paths in self.deleted_paths.items():\n            assert num >= 2\n            for path in paths:\n                module = module_from_path(path)\n                steps.setdefault(num, []).append(DeleteFile(module, path))\n        max_step = max(steps) if steps else 2\n        self.steps = [steps.get(num, []) for num in range(2, max_step + 1)]\n\n    def teardown(self) -> None:\n        if self.old_cwd is not None:\n            os.chdir(self.old_cwd)\n        if self.tmpdir is not None:\n            shutil.rmtree(self.tmpdir, ignore_errors=True)\n        self.old_cwd = None\n        self.tmpdir = None\n\n    def reportinfo(self) -> tuple[str, int, str]:\n        return self.file, self.line, self.name\n\n    def repr_failure(\n        self, excinfo: pytest.ExceptionInfo[BaseException], style: Any | None = None\n    ) -> str:\n        excrepr: object\n        if isinstance(excinfo.value, SystemExit):\n            # We assume that before doing exit() (which raises SystemExit) we've printed\n            # enough context about what happened so that a stack trace is not useful.\n            # In particular, uncaught exceptions during semantic analysis or type checking\n            # call exit() and they already print out a stack trace.\n            excrepr = excinfo.exconly()\n        elif isinstance(excinfo.value, pytest.fail.Exception) and not excinfo.value.pytrace:\n            excrepr = excinfo.exconly()\n        else:\n            excinfo.traceback = self.parent._traceback_filter(excinfo)\n            excrepr = excinfo.getrepr(style=\"short\")\n\n        return f\"data: {self.file}:{self.line}:\\n{excrepr}\"\n\n    def find_steps(self) -> list[list[FileOperation]]:\n        \"\"\"Return a list of descriptions of file operations for each incremental step.\n\n        The first list item corresponds to the first incremental step, the second for the\n        second step, etc. Each operation can either be a file modification/creation (UpdateFile)\n        or deletion (DeleteFile).\n\n        Defaults to having two steps if there aern't any operations.\n        \"\"\"\n        return self.steps\n\n\ndef module_from_path(path: str) -> str:\n    path = re.sub(r\"\\.pyi?$\", \"\", path)\n    # We can have a mix of Unix-style and Windows-style separators.\n    parts = re.split(r\"[/\\\\]\", path)\n    del parts[0]\n    module = \".\".join(parts)\n    module = re.sub(r\"\\.__init__$\", \"\", module)\n    return module\n\n\n@dataclass\nclass TestItem:\n    \"\"\"Parsed test caseitem.\n\n    An item is of the form\n      [id arg]\n      .. data ..\n    \"\"\"\n\n    id: str\n    arg: str | None\n    # Processed, collapsed text data\n    data: list[str]\n    # Start line: 1-based, inclusive, relative to testcase\n    line: int\n    # End line: 1-based, exclusive, relative to testcase; not same as `line + len(test_item.data)` due to collapsing\n    end_line: int\n\n    @property\n    def trimmed_newlines(self) -> int:  # compensates for strip_list\n        return self.end_line - self.line - len(self.data)\n\n\ndef parse_test_data(raw_data: str, name: str) -> list[TestItem]:\n    \"\"\"Parse a list of lines that represent a sequence of test items.\"\"\"\n\n    lines = [\"\", \"[case \" + name + \"]\"] + raw_data.split(\"\\n\")\n    ret: list[TestItem] = []\n    data: list[str] = []\n\n    id: str | None = None\n    arg: str | None = None\n\n    i = 0\n    i0 = 0\n    while i < len(lines):\n        s = lines[i].strip()\n\n        if lines[i].startswith(\"[\") and s.endswith(\"]\"):\n            if id:\n                data = collapse_line_continuation(data)\n                data = strip_list(data)\n                ret.append(TestItem(id, arg, data, i0 + 1, i))\n\n            i0 = i\n            id = s[1:-1]\n            arg = None\n            if \" \" in id:\n                arg = id[id.index(\" \") + 1 :]\n                id = id[: id.index(\" \")]\n            data = []\n        elif lines[i].startswith(\"\\\\[\"):\n            data.append(lines[i][1:])\n        elif not lines[i].startswith(\"--\"):\n            data.append(lines[i])\n        elif lines[i].startswith(\"----\"):\n            data.append(lines[i][2:])\n        i += 1\n\n    # Process the last item.\n    if id:\n        data = collapse_line_continuation(data)\n        data = strip_list(data)\n        ret.append(TestItem(id, arg, data, i0 + 1, i - 1))\n\n    return ret\n\n\ndef strip_list(l: list[str]) -> list[str]:\n    \"\"\"Return a stripped copy of l.\n\n    Strip whitespace at the end of all lines, and strip all empty\n    lines from the end of the array.\n    \"\"\"\n\n    r: list[str] = []\n    for s in l:\n        # Strip spaces at end of line\n        r.append(re.sub(r\"\\s+$\", \"\", s))\n\n    while r and r[-1] == \"\":\n        r.pop()\n\n    return r\n\n\ndef collapse_line_continuation(l: list[str]) -> list[str]:\n    r: list[str] = []\n    cont = False\n    for s in l:\n        ss = re.sub(r\"\\\\$\", \"\", s)\n        if cont:\n            r[-1] += re.sub(\"^ +\", \"\", ss)\n        else:\n            r.append(ss)\n        cont = s.endswith(\"\\\\\")\n    return r\n\n\ndef expand_variables(s: str) -> str:\n    return s.replace(\"<ROOT>\", root_dir)\n\n\ndef expand_errors(input: list[str], output: list[str], fnam: str) -> None:\n    \"\"\"Transform comments such as '# E: message' or\n    '# E:3: message' in input.\n\n    The result is lines like 'fnam:line: error: message'.\n    \"\"\"\n\n    for i in range(len(input)):\n        # The first in the split things isn't a comment\n        for possible_err_comment in input[i].split(\" # \")[1:]:\n            m = re.search(\n                r\"^([ENW]):((?P<col>\\d+):)? (?P<message>.*)$\", possible_err_comment.strip()\n            )\n            if m:\n                if m.group(1) == \"E\":\n                    severity = \"error\"\n                elif m.group(1) == \"N\":\n                    severity = \"note\"\n                elif m.group(1) == \"W\":\n                    severity = \"warning\"\n                col = m.group(\"col\")\n                message = m.group(\"message\")\n                message = message.replace(\"\\\\#\", \"#\")  # adds back escaped # character\n                if col is None:\n                    output.append(f\"{fnam}:{i + 1}: {severity}: {message}\")\n                else:\n                    output.append(f\"{fnam}:{i + 1}:{col}: {severity}: {message}\")\n\n\ndef fix_win_path(line: str) -> str:\n    r\"\"\"Changes Windows paths to Linux paths in error messages.\n\n    E.g. foo\\bar.py -> foo/bar.py.\n    \"\"\"\n    line = line.replace(root_dir, root_dir.replace(\"\\\\\", \"/\"))\n    m = re.match(r\"^([\\S/]+):(\\d+:)?(\\s+.*)\", line)\n    if not m:\n        return line\n    else:\n        filename, lineno, message = m.groups()\n        return \"{}:{}{}\".format(filename.replace(\"\\\\\", \"/\"), lineno or \"\", message)\n\n\ndef fix_cobertura_filename(line: str) -> str:\n    r\"\"\"Changes filename paths to Linux paths in Cobertura output files.\n\n    E.g. filename=\"pkg\\subpkg\\a.py\" -> filename=\"pkg/subpkg/a.py\".\n    \"\"\"\n    m = re.search(r'<class .* filename=\"(?P<filename>.*?)\"', line)\n    if not m:\n        return line\n    return \"{}{}{}\".format(\n        line[: m.start(1)], m.group(\"filename\").replace(\"\\\\\", \"/\"), line[m.end(1) :]\n    )\n\n\n##\n#\n# pytest setup\n#\n##\n\n\ndef pytest_sessionstart(session: Any) -> None:\n    # Clean up directory where mypyc tests write intermediate files on failure\n    # to avoid any confusion between test runs\n    if os.path.isdir(mypyc_output_dir):\n        shutil.rmtree(mypyc_output_dir)\n\n\n# This function name is special to pytest.  See\n# https://docs.pytest.org/en/latest/reference.html#initialization-hooks\ndef pytest_addoption(parser: Any) -> None:\n    group = parser.getgroup(\"mypy\")\n    group.addoption(\n        \"--update-data\",\n        action=\"store_true\",\n        default=False,\n        help=\"Update test data to reflect actual output (supported only for certain tests)\",\n    )\n    group.addoption(\n        \"--mypy-num-workers\",\n        type=int,\n        default=0,\n        help=\"Run tests using multiple worker processes for each test case\",\n    )\n    group.addoption(\n        \"--save-failures-to\",\n        default=None,\n        help=\"Copy the temp directories from failing tests to a target directory\",\n    )\n    group.addoption(\n        \"--mypy-verbose\", action=\"count\", help=\"Set the verbose flag when creating mypy Options\"\n    )\n    group.addoption(\n        \"--mypyc-showc\",\n        action=\"store_true\",\n        default=False,\n        help=\"Display C code on mypyc test failures\",\n    )\n    group.addoption(\n        \"--mypyc-debug\",\n        default=None,\n        dest=\"debugger\",\n        choices=SUPPORTED_DEBUGGERS,\n        help=\"Run the first mypyc run test with the specified debugger\",\n    )\n\n\n@pytest.hookimpl(tryfirst=True)\ndef pytest_cmdline_main(config: pytest.Config) -> None:\n    if config.getoption(\"--collectonly\"):\n        return\n    # --update-data is not compatible with parallelized tests, disable parallelization\n    if config.getoption(\"--update-data\"):\n        config.option.numprocesses = 0\n\n\n# This function name is special to pytest.  See\n# https://doc.pytest.org/en/latest/how-to/writing_plugins.html#collection-hooks\ndef pytest_pycollect_makeitem(collector: Any, name: str, obj: object) -> Any | None:\n    \"\"\"Called by pytest on each object in modules configured in conftest.py files.\n\n    collector is pytest.Collector, returns Optional[pytest.Class]\n    \"\"\"\n    if isinstance(obj, type):\n        # Only classes derived from DataSuite contain test cases, not the DataSuite class itself\n        if issubclass(obj, DataSuite) and obj is not DataSuite:\n            # Non-None result means this obj is a test case.\n            # The collect method of the returned DataSuiteCollector instance will be called later,\n            # with self.obj being obj.\n            return DataSuiteCollector.from_parent(parent=collector, name=name)\n    return None\n\n\n_case_name_pattern = re.compile(\n    r\"(?P<name>[a-zA-Z_0-9]+)\"\n    r\"(?P<writescache>-writescache)?\"\n    r\"(?P<only_when>-only_when_cache|-only_when_nocache)?\"\n    r\"(?P<skip_path_normalization>-skip_path_normalization)?\"\n    r\"(-(?P<platform>posix|windows))?\"\n    r\"(?P<skip>-skip)?\"\n    r\"(?P<xfail>-xfail)?\"\n)\n\n\ndef split_test_cases(\n    parent: DataFileCollector, suite: DataSuite, file: str\n) -> Iterator[DataDrivenTestCase]:\n    \"\"\"Iterate over raw test cases in file, at collection time, ignoring sub items.\n\n    The collection phase is slow, so any heavy processing should be deferred to after\n    uninteresting tests are filtered (when using -k PATTERN switch).\n    \"\"\"\n    with open(file, encoding=\"utf-8\") as f:\n        data = f.read()\n    cases = re.split(r\"^\\[case ([^]+)]+)\\][ \\t]*$\\n\", data, flags=re.DOTALL | re.MULTILINE)\n    cases_iter = iter(cases)\n    line_no = next(cases_iter).count(\"\\n\") + 1\n    test_names = set()\n    for case_id in cases_iter:\n        data = next(cases_iter)\n\n        m = _case_name_pattern.fullmatch(case_id)\n        if not m:\n            raise RuntimeError(f\"Invalid testcase id {case_id!r}\")\n        name = m.group(\"name\")\n        if name in test_names:\n            raise RuntimeError(\n                'Found a duplicate test name \"{}\" in {} on line {}'.format(\n                    name, parent.name, line_no\n                )\n            )\n        yield DataDrivenTestCase.from_parent(\n            parent=parent,\n            suite=suite,\n            file=file,\n            name=add_test_name_suffix(name, suite.test_name_suffix),\n            writescache=bool(m.group(\"writescache\")),\n            only_when=m.group(\"only_when\"),\n            platform=m.group(\"platform\"),\n            skip=bool(m.group(\"skip\")),\n            xfail=bool(m.group(\"xfail\")),\n            normalize_output=not m.group(\"skip_path_normalization\"),\n            data=data,\n            line=line_no,\n        )\n        line_no += data.count(\"\\n\") + 1\n\n        # Record existing tests to prevent duplicates:\n        test_names.update({name})\n\n\nclass DataSuiteCollector(pytest.Class):\n    def collect(self) -> Iterator[DataFileCollector]:\n        \"\"\"Called by pytest on each of the object returned from pytest_pycollect_makeitem\"\"\"\n\n        # obj is the object for which pytest_pycollect_makeitem returned self.\n        suite: DataSuite = self.obj\n\n        assert os.path.isdir(\n            suite.data_prefix\n        ), f\"Test data prefix ({suite.data_prefix}) not set correctly\"\n\n        for data_file in suite.files:\n            yield DataFileCollector.from_parent(parent=self, name=data_file)\n\n\nclass DataFileFix(NamedTuple):\n    lineno: int  # 1-offset, inclusive\n    end_lineno: int  # 1-offset, exclusive\n    lines: list[str]\n\n\nclass DataFileCollector(pytest.Collector):\n    \"\"\"Represents a single `.test` data driven test file.\n\n    More context: https://github.com/python/mypy/issues/11662\n    \"\"\"\n\n    parent: DataSuiteCollector\n\n    _fixes: list[DataFileFix]\n\n    @classmethod  # We have to fight with pytest here:\n    def from_parent(\n        cls, parent: DataSuiteCollector, *, name: str  # type: ignore[override]\n    ) -> DataFileCollector:\n        collector = super().from_parent(parent, name=name)\n        assert isinstance(collector, DataFileCollector)\n        return collector\n\n    def collect(self) -> Iterator[DataDrivenTestCase]:\n        yield from split_test_cases(\n            parent=self,\n            suite=self.parent.obj,\n            file=os.path.join(self.parent.obj.data_prefix, self.name),\n        )\n\n    def setup(self) -> None:\n        super().setup()\n        self._fixes = []\n\n    def teardown(self) -> None:\n        super().teardown()\n        self._apply_fixes()\n\n    def enqueue_fix(self, fix: DataFileFix) -> None:\n        self._fixes.append(fix)\n\n    def _apply_fixes(self) -> None:\n        if not self._fixes:\n            return\n        data_path = Path(self.parent.obj.data_prefix) / self.name\n        lines = data_path.read_text().split(\"\\n\")\n        # start from end to prevent line offsets from shifting as we update\n        for fix in sorted(self._fixes, reverse=True):\n            lines[fix.lineno - 1 : fix.end_lineno - 1] = fix.lines\n        data_path.write_text(\"\\n\".join(lines))\n\n\ndef add_test_name_suffix(name: str, suffix: str) -> str:\n    # Find magic suffix of form \"-foobar\" (used for things like \"-skip\").\n    m = re.search(r\"-[-A-Za-z0-9]+$\", name)\n    if m:\n        # Insert suite-specific test name suffix before the magic suffix\n        # which must be the last thing in the test case name since we\n        # are using endswith() checks.\n        magic_suffix = m.group(0)\n        return name[: -len(magic_suffix)] + suffix + magic_suffix\n    else:\n        return name + suffix\n\n\ndef is_incremental(testcase: DataDrivenTestCase) -> bool:\n    return \"incremental\" in testcase.name.lower() or \"incremental\" in testcase.file\n\n\ndef has_stable_flags(testcase: DataDrivenTestCase) -> bool:\n    if any(re.match(r\"# flags[2-9]:\", line) for line in testcase.input):\n        return False\n    for filename, contents in testcase.files:\n        if os.path.basename(filename).startswith(\"mypy.ini.\"):\n            return False\n    return True\n\n\nclass DataSuite:\n    # option fields - class variables\n    files: list[str]\n\n    base_path = test_temp_dir\n\n    # Allow external users of the test code to override the data prefix\n    data_prefix = test_data_prefix\n\n    required_out_section = False\n\n    native_sep = False\n\n    # Name suffix automatically added to each test case in the suite (can be\n    # used to distinguish test cases in suites that share data files)\n    test_name_suffix = \"\"\n\n    def setup(self) -> None:\n        \"\"\"Setup fixtures (ad-hoc)\"\"\"\n\n    @abstractmethod\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        raise NotImplementedError\n"
  },
  {
    "path": "mypy/test/helpers.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport difflib\nimport os\nimport pathlib\nimport re\nimport shutil\nimport sys\nimport time\nfrom collections.abc import Callable, Iterable, Iterator\nfrom re import Pattern\nfrom typing import IO, Any\n\n# Exporting Suite as alias to TestCase for backwards compatibility\n# TODO: avoid aliasing - import and subclass TestCase directly\nfrom unittest import TestCase\n\nSuite = TestCase  # re-exporting\n\nimport pytest\n\nimport mypy.api as api\nimport mypy.version\nfrom mypy import defaults\nfrom mypy.main import process_options\nfrom mypy.options import Options\nfrom mypy.test.config import test_data_prefix, test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DeleteFile, UpdateFile, fix_cobertura_filename\n\nskip = pytest.mark.skip\n\n# AssertStringArraysEqual displays special line alignment helper messages if\n# the first different line has at least this many characters,\nMIN_LINE_LENGTH_FOR_ALIGNMENT = 5\n\n\ndef run_mypy(args: list[str]) -> None:\n    __tracebackhide__ = True\n    # We must enable site packages even though they could cause problems,\n    # since stubs for typing_extensions live there.\n    outval, errval, status = api.run(args + [\"--show-traceback\", \"--no-silence-site-packages\"])\n    if status != 0:\n        sys.stdout.write(outval)\n        sys.stderr.write(errval)\n        pytest.fail(reason=\"Sample check failed\", pytrace=False)\n\n\ndef diff_ranges(\n    left: list[str], right: list[str]\n) -> tuple[list[tuple[int, int]], list[tuple[int, int]]]:\n    seq = difflib.SequenceMatcher(None, left, right)\n    # note last triple is a dummy, so don't need to worry\n    blocks = seq.get_matching_blocks()\n\n    i = 0\n    j = 0\n    left_ranges = []\n    right_ranges = []\n    for block in blocks:\n        # mismatched range\n        left_ranges.append((i, block.a))\n        right_ranges.append((j, block.b))\n\n        i = block.a + block.size\n        j = block.b + block.size\n\n        # matched range\n        left_ranges.append((block.a, i))\n        right_ranges.append((block.b, j))\n    return left_ranges, right_ranges\n\n\ndef render_diff_range(\n    ranges: list[tuple[int, int]],\n    content: list[str],\n    *,\n    colour: str | None = None,\n    output: IO[str] = sys.stderr,\n    indent: int = 2,\n) -> None:\n    for i, line_range in enumerate(ranges):\n        is_matching = i % 2 == 1\n        lines = content[line_range[0] : line_range[1]]\n        for j, line in enumerate(lines):\n            if (\n                is_matching\n                # elide the middle of matching blocks\n                and j >= 3\n                and j < len(lines) - 3\n            ):\n                if j == 3:\n                    output.write(\" \" * indent + \"...\\n\")\n                continue\n\n            if not is_matching and colour:\n                output.write(colour)\n\n            output.write(\" \" * indent + line)\n\n            if not is_matching:\n                if colour:\n                    output.write(\"\\033[0m\")\n                output.write(\" (diff)\")\n\n            output.write(\"\\n\")\n\n\ndef assert_string_arrays_equal(\n    expected: list[str], actual: list[str], msg: str, *, traceback: bool = False\n) -> None:\n    \"\"\"Assert that two string arrays are equal.\n\n    Display any differences in a human-readable form.\n    \"\"\"\n    actual = clean_up(actual)\n    if expected != actual:\n        expected_ranges, actual_ranges = diff_ranges(expected, actual)\n        sys.stderr.write(\"Expected:\\n\")\n        red = \"\\033[31m\" if sys.platform != \"win32\" else None\n        render_diff_range(expected_ranges, expected, colour=red)\n        sys.stderr.write(\"Actual:\\n\")\n        green = \"\\033[32m\" if sys.platform != \"win32\" else None\n        render_diff_range(actual_ranges, actual, colour=green)\n\n        sys.stderr.write(\"\\n\")\n        first_diff = next(\n            (i for i, (a, b) in enumerate(zip(expected, actual)) if a != b),\n            max(len(expected), len(actual)),\n        )\n        if 0 <= first_diff < len(actual) and (\n            len(expected[first_diff]) >= MIN_LINE_LENGTH_FOR_ALIGNMENT\n            or len(actual[first_diff]) >= MIN_LINE_LENGTH_FOR_ALIGNMENT\n        ):\n            # Display message that helps visualize the differences between two\n            # long lines.\n            show_align_message(expected[first_diff], actual[first_diff])\n\n        sys.stderr.write(\n            \"Update the test output using --update-data \"\n            \"(implies -n0; you can additionally use the -k selector to update only specific tests)\\n\"\n        )\n        pytest.fail(msg, pytrace=traceback)\n\n\ndef assert_module_equivalence(name: str, expected: Iterable[str], actual: Iterable[str]) -> None:\n    expected_normalized = sorted(expected)\n    actual_normalized = sorted(set(actual).difference({\"__main__\"}))\n    assert_string_arrays_equal(\n        expected_normalized,\n        actual_normalized,\n        ('Actual modules ({}) do not match expected modules ({}) for \"[{} ...]\"').format(\n            \", \".join(actual_normalized), \", \".join(expected_normalized), name\n        ),\n    )\n\n\ndef assert_target_equivalence(name: str, expected: list[str], actual: list[str]) -> None:\n    \"\"\"Compare actual and expected targets (order sensitive).\"\"\"\n    assert_string_arrays_equal(\n        expected,\n        actual,\n        ('Actual targets ({}) do not match expected targets ({}) for \"[{} ...]\"').format(\n            \", \".join(actual), \", \".join(expected), name\n        ),\n    )\n\n\ndef show_align_message(s1: str, s2: str) -> None:\n    \"\"\"Align s1 and s2 so that the their first difference is highlighted.\n\n    For example, if s1 is 'foobar' and s2 is 'fobar', display the\n    following lines:\n\n      E: foobar\n      A: fobar\n           ^\n\n    If s1 and s2 are long, only display a fragment of the strings around the\n    first difference. If s1 is very short, do nothing.\n    \"\"\"\n\n    # Seeing what went wrong is trivial even without alignment if the expected\n    # string is very short. In this case do nothing to simplify output.\n    if len(s1) < 4:\n        return\n\n    maxw = 72  # Maximum number of characters shown\n\n    sys.stderr.write(\"Alignment of first line difference:\\n\")\n\n    trunc = False\n    while s1[:30] == s2[:30]:\n        s1 = s1[10:]\n        s2 = s2[10:]\n        trunc = True\n\n    if trunc:\n        s1 = \"...\" + s1\n        s2 = \"...\" + s2\n\n    max_len = max(len(s1), len(s2))\n    extra = \"\"\n    if max_len > maxw:\n        extra = \"...\"\n\n    # Write a chunk of both lines, aligned.\n    sys.stderr.write(f\"  E: {s1[:maxw]}{extra}\\n\")\n    sys.stderr.write(f\"  A: {s2[:maxw]}{extra}\\n\")\n    # Write an indicator character under the different columns.\n    sys.stderr.write(\"     \")\n    for j in range(min(maxw, max(len(s1), len(s2)))):\n        if s1[j : j + 1] != s2[j : j + 1]:\n            sys.stderr.write(\"^\")  # Difference\n            break\n        else:\n            sys.stderr.write(\" \")  # Equal\n    sys.stderr.write(\"\\n\")\n\n\ndef clean_up(a: list[str]) -> list[str]:\n    \"\"\"Remove common directory prefix from all strings in a.\n\n    This uses a naive string replace; it seems to work well enough. Also\n    remove trailing carriage returns.\n    \"\"\"\n    res = []\n    pwd = os.getcwd()\n    driver = pwd + \"/driver.py\"\n    for s in a:\n        prefix = os.sep\n        ss = s\n        for p in prefix, prefix.replace(os.sep, \"/\"):\n            if p != \"/\" and p != \"//\" and p != \"\\\\\" and p != \"\\\\\\\\\":\n                ss = ss.replace(p, \"\")\n        # Replace memory address with zeros\n        if \"at 0x\" in ss:\n            ss = re.sub(r\"(at 0x)\\w+>\", r\"\\g<1>000000000000>\", ss)\n        # Ignore spaces at end of line.\n        ss = re.sub(\" +$\", \"\", ss)\n        # Remove pwd from driver.py's path\n        ss = ss.replace(driver, \"driver.py\")\n        res.append(re.sub(\"\\\\r$\", \"\", ss))\n    return res\n\n\n@contextlib.contextmanager\ndef local_sys_path_set() -> Iterator[None]:\n    \"\"\"Temporary insert current directory into sys.path.\n\n    This can be used by test cases that do runtime imports, for example\n    by the stubgen tests.\n    \"\"\"\n    old_sys_path = sys.path.copy()\n    if not (\"\" in sys.path or \".\" in sys.path):\n        sys.path.insert(0, \"\")\n    try:\n        yield\n    finally:\n        sys.path = old_sys_path\n\n\ndef testfile_pyversion(path: str) -> tuple[int, int]:\n    if m := re.search(r\"python3([0-9]+)\\.test$\", path):\n        # For older unsupported version like python38,\n        # default to that earliest supported version.\n        return max((3, int(m.group(1))), defaults.PYTHON3_VERSION_MIN)\n    else:\n        return defaults.PYTHON3_VERSION_MIN\n\n\ndef normalize_error_messages(messages: list[str]) -> list[str]:\n    \"\"\"Translate an array of error messages to use / as path separator.\"\"\"\n\n    a = []\n    for m in messages:\n        a.append(m.replace(os.sep, \"/\"))\n    return a\n\n\ndef retry_on_error(func: Callable[[], Any], max_wait: float = 1.0) -> None:\n    \"\"\"Retry callback with exponential backoff when it raises OSError.\n\n    If the function still generates an error after max_wait seconds, propagate\n    the exception.\n\n    This can be effective against random file system operation failures on\n    Windows.\n    \"\"\"\n    t0 = time.time()\n    wait_time = 0.01\n    while True:\n        try:\n            func()\n            return\n        except OSError:\n            wait_time = min(wait_time * 2, t0 + max_wait - time.time())\n            if wait_time <= 0.01:\n                # Done enough waiting, the error seems persistent.\n                raise\n            time.sleep(wait_time)\n\n\ndef good_repr(obj: object) -> str:\n    if isinstance(obj, str):\n        if obj.count(\"\\n\") > 1:\n            bits = [\"'''\\\\\"]\n            for line in obj.split(\"\\n\"):\n                # force repr to use ' not \", then cut it off\n                bits.append(repr('\"' + line)[2:-1])\n            bits[-1] += \"'''\"\n            return \"\\n\".join(bits)\n    return repr(obj)\n\n\ndef assert_equal(a: object, b: object, fmt: str = \"{} != {}\") -> None:\n    __tracebackhide__ = True\n    if a != b:\n        raise AssertionError(fmt.format(good_repr(a), good_repr(b)))\n\n\ndef typename(t: type) -> str:\n    if \".\" in str(t):\n        return str(t).split(\".\")[-1].rstrip(\"'>\")\n    else:\n        return str(t)[8:-2]\n\n\ndef assert_type(typ: type, value: object) -> None:\n    __tracebackhide__ = True\n    if type(value) != typ:\n        raise AssertionError(f\"Invalid type {typename(type(value))}, expected {typename(typ)}\")\n\n\ndef parse_options(\n    program_text: str, testcase: DataDrivenTestCase, incremental_step: int\n) -> Options:\n    \"\"\"Parse comments like '# flags: --foo' in a test case.\"\"\"\n    options = Options()\n    flags = re.search(\"# flags: (.*)$\", program_text, flags=re.MULTILINE)\n    if incremental_step > 1:\n        flags2 = re.search(f\"# flags{incremental_step}: (.*)$\", program_text, flags=re.MULTILINE)\n        if flags2:\n            flags = flags2\n\n    if flags:\n        flag_list = flags.group(1).split()\n        flag_list.append(\"--no-site-packages\")  # the tests shouldn't need an installed Python\n        targets, options = process_options(flag_list, require_targets=False)\n        if targets:\n            # TODO: support specifying targets via the flags pragma\n            raise RuntimeError(\"Specifying targets via the flags pragma is not supported.\")\n        if \"--show-error-codes\" not in flag_list:\n            options.hide_error_codes = True\n    else:\n        flag_list = []\n        options = Options()\n        options.error_summary = False\n        options.hide_error_codes = True\n\n    # Allow custom python version to override testfile_pyversion.\n    if all(flag.split(\"=\")[0] != \"--python-version\" for flag in flag_list):\n        options.python_version = testfile_pyversion(testcase.file)\n\n    if testcase.config.getoption(\"--mypy-verbose\"):\n        options.verbosity = testcase.config.getoption(\"--mypy-verbose\")\n    if testcase.config.getoption(\"--mypy-num-workers\"):\n        options.num_workers = testcase.config.getoption(\"--mypy-num-workers\")\n\n    return options\n\n\ndef split_lines(*streams: bytes) -> list[str]:\n    \"\"\"Returns a single list of string lines from the byte streams in args.\"\"\"\n    return [s for stream in streams for s in stream.decode(\"utf8\").splitlines()]\n\n\ndef write_and_fudge_mtime(content: str, target_path: str) -> None:\n    # In some systems, mtime has a resolution of 1 second which can\n    # cause annoying-to-debug issues when a file has the same size\n    # after a change. We manually set the mtime to circumvent this.\n    # Note that we increment the old file's mtime, which guarantees a\n    # different value, rather than incrementing the mtime after the\n    # copy, which could leave the mtime unchanged if the old file had\n    # a similarly fudged mtime.\n    new_time = None\n    if os.path.isfile(target_path):\n        new_time = os.stat(target_path).st_mtime + 1\n\n    dir = os.path.dirname(target_path)\n    os.makedirs(dir, exist_ok=True)\n    with open(target_path, \"w\", encoding=\"utf-8\") as target:\n        target.write(content)\n\n    if new_time:\n        os.utime(target_path, times=(new_time, new_time))\n\n\ndef perform_file_operations(operations: list[UpdateFile | DeleteFile]) -> None:\n    for op in operations:\n        if isinstance(op, UpdateFile):\n            # Modify/create file\n            write_and_fudge_mtime(op.content, op.target_path)\n        else:\n            # Delete file/directory\n            if os.path.isdir(op.path):\n                # Sanity check to avoid unexpected deletions\n                assert op.path.startswith(\"tmp\")\n                shutil.rmtree(op.path)\n            else:\n                # Use retries to work around potential flakiness on Windows (AppVeyor).\n                path = op.path\n                retry_on_error(lambda: os.remove(path))\n\n\ndef check_test_output_files(\n    testcase: DataDrivenTestCase, step: int, strip_prefix: str = \"\"\n) -> None:\n    for path, expected_content in testcase.output_files:\n        path = path.removeprefix(strip_prefix)\n        if not os.path.exists(path):\n            raise AssertionError(\n                \"Expected file {} was not produced by test case{}\".format(\n                    path, \" on step %d\" % step if testcase.output2 else \"\"\n                )\n            )\n        with open(path, encoding=\"utf8\") as output_file:\n            actual_output_content = output_file.read()\n\n        if isinstance(expected_content, Pattern):\n            if expected_content.fullmatch(actual_output_content) is not None:\n                continue\n            raise AssertionError(\n                \"Output file {} did not match its expected output pattern\\n---\\n{}\\n---\".format(\n                    path, actual_output_content\n                )\n            )\n\n        normalized_output = normalize_file_output(\n            actual_output_content.splitlines(), os.path.abspath(test_temp_dir)\n        )\n        # We always normalize things like timestamp, but only handle operating-system\n        # specific things if requested.\n        if testcase.normalize_output:\n            if testcase.suite.native_sep and os.path.sep == \"\\\\\":\n                normalized_output = [fix_cobertura_filename(line) for line in normalized_output]\n            normalized_output = normalize_error_messages(normalized_output)\n        if os.path.basename(testcase.file) == \"reports.test\":\n            normalized_output = normalize_report_meta(normalized_output)\n        assert_string_arrays_equal(\n            expected_content.splitlines(),\n            normalized_output,\n            \"Output file {} did not match its expected output{}\".format(\n                path, \" on step %d\" % step if testcase.output2 else \"\"\n            ),\n        )\n\n\ndef normalize_file_output(content: list[str], current_abs_path: str) -> list[str]:\n    \"\"\"Normalize file output for comparison.\"\"\"\n    timestamp_regex = re.compile(r\"\\d{10}\")\n    result = [x.replace(current_abs_path, \"$PWD\") for x in content]\n    version = mypy.version.__version__\n    result = [re.sub(r\"\\b\" + re.escape(version) + r\"\\b\", \"$VERSION\", x) for x in result]\n    # We generate a new mypy.version when building mypy wheels that\n    # lacks base_version, so handle that case.\n    base_version = getattr(mypy.version, \"base_version\", version)\n    result = [re.sub(r\"\\b\" + re.escape(base_version) + r\"\\b\", \"$VERSION\", x) for x in result]\n    result = [timestamp_regex.sub(\"$TIMESTAMP\", x) for x in result]\n    return result\n\n\ndef normalize_report_meta(content: list[str]) -> list[str]:\n    # libxml 2.15 and newer emits the \"modern\" version of this <meta> element.\n    # Normalize the old style to look the same.\n    html_meta = '<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">'\n    return ['<meta charset=\"UTF-8\">' if x == html_meta else x for x in content]\n\n\ndef find_test_files(pattern: str, exclude: list[str] | None = None) -> list[str]:\n    return [\n        path.name\n        for path in (pathlib.Path(test_data_prefix).rglob(pattern))\n        if path.name not in (exclude or [])\n    ]\n\n\ndef remove_typevar_ids(a: list[str]) -> list[str]:\n    return [re.sub(r\"`-?\\d+\", \"\", line) for line in a]\n"
  },
  {
    "path": "mypy/test/meta/__init__.py",
    "content": ""
  },
  {
    "path": "mypy/test/meta/_pytest.py",
    "content": "import shlex\nimport subprocess\nimport sys\nimport textwrap\nimport uuid\nfrom collections.abc import Iterable\nfrom dataclasses import dataclass\nfrom pathlib import Path\n\nfrom mypy.test.config import test_data_prefix\n\n\n@dataclass\nclass PytestResult:\n    input: str\n    input_updated: str  # any updates made by --update-data\n    stdout: str\n    stderr: str\n\n\ndef dedent_docstring(s: str) -> str:\n    return textwrap.dedent(s).lstrip()\n\n\ndef run_pytest_data_suite(\n    data_suite: str,\n    *,\n    data_file_prefix: str = \"check\",\n    pytest_node_prefix: str = \"mypy/test/testcheck.py::TypeCheckSuite\",\n    extra_args: Iterable[str],\n    max_attempts: int,\n) -> PytestResult:\n    \"\"\"\n    Runs a suite of data test cases through pytest until either tests pass\n    or until a maximum number of attempts (needed for incremental tests).\n\n    :param data_suite: the actual \"suite\" i.e. the contents of a .test file\n    \"\"\"\n    p_test_data = Path(test_data_prefix)\n    p_root = p_test_data.parent.parent\n    p = p_test_data / f\"{data_file_prefix}-meta-{uuid.uuid4()}.test\"\n    assert not p.exists()\n    data_suite = dedent_docstring(data_suite)\n    try:\n        p.write_text(data_suite)\n\n        test_nodeid = f\"{pytest_node_prefix}::{p.name}\"\n        extra_args = [sys.executable, \"-m\", \"pytest\", \"-n\", \"0\", \"-s\", *extra_args, test_nodeid]\n        cmd = shlex.join(extra_args)\n        for i in range(max_attempts - 1, -1, -1):\n            print(f\">> {cmd}\")\n            proc = subprocess.run(extra_args, capture_output=True, check=False, cwd=p_root)\n            if proc.returncode == 0:\n                break\n            prefix = \"NESTED PYTEST STDOUT\"\n            for line in proc.stdout.decode().splitlines():\n                print(f\"{prefix}: {line}\")\n                prefix = \" \" * len(prefix)\n            prefix = \"NESTED PYTEST STDERR\"\n            for line in proc.stderr.decode().splitlines():\n                print(f\"{prefix}: {line}\")\n                prefix = \" \" * len(prefix)\n            print(f\"Exit code {proc.returncode} ({i} attempts remaining)\")\n\n        return PytestResult(\n            input=data_suite,\n            input_updated=p.read_text(),\n            stdout=proc.stdout.decode(),\n            stderr=proc.stderr.decode(),\n        )\n    finally:\n        p.unlink()\n"
  },
  {
    "path": "mypy/test/meta/test_diff_helper.py",
    "content": "import io\n\nfrom mypy.test.helpers import Suite, diff_ranges, render_diff_range\n\n\nclass DiffHelperSuite(Suite):\n    def test_render_diff_range(self) -> None:\n        expected = [\"hello\", \"world\"]\n        actual = [\"goodbye\", \"world\"]\n\n        expected_ranges, actual_ranges = diff_ranges(expected, actual)\n\n        output = io.StringIO()\n        render_diff_range(expected_ranges, expected, output=output)\n        assert output.getvalue() == \"  hello (diff)\\n  world\\n\"\n        output = io.StringIO()\n        render_diff_range(actual_ranges, actual, output=output)\n        assert output.getvalue() == \"  goodbye (diff)\\n  world\\n\"\n\n        expected = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"circle\", \"i\", \"j\"]\n        actual = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"square\", \"i\", \"j\"]\n\n        expected_ranges, actual_ranges = diff_ranges(expected, actual)\n\n        output = io.StringIO()\n        render_diff_range(expected_ranges, expected, output=output, indent=0)\n        assert output.getvalue() == \"a\\nb\\nc\\n...\\nf\\ng\\nh\\ncircle (diff)\\ni\\nj\\n\"\n        output = io.StringIO()\n        render_diff_range(actual_ranges, actual, output=output, indent=0)\n        assert output.getvalue() == \"a\\nb\\nc\\n...\\nf\\ng\\nh\\nsquare (diff)\\ni\\nj\\n\"\n\n    def test_diff_ranges(self) -> None:\n        a = [\"hello\", \"world\"]\n        b = [\"hello\", \"world\"]\n\n        assert diff_ranges(a, b) == (\n            [(0, 0), (0, 2), (2, 2), (2, 2)],\n            [(0, 0), (0, 2), (2, 2), (2, 2)],\n        )\n\n        a = [\"hello\", \"world\"]\n        b = [\"goodbye\", \"world\"]\n\n        assert diff_ranges(a, b) == (\n            [(0, 1), (1, 2), (2, 2), (2, 2)],\n            [(0, 1), (1, 2), (2, 2), (2, 2)],\n        )\n"
  },
  {
    "path": "mypy/test/meta/test_parse_data.py",
    "content": "\"\"\"\nA \"meta test\" which tests the parsing of .test files. This is not meant to become exhaustive\nbut to ensure we maintain a basic level of ergonomics for mypy contributors.\n\"\"\"\n\nfrom mypy.test.helpers import Suite\nfrom mypy.test.meta._pytest import PytestResult, run_pytest_data_suite\n\n\ndef _run_pytest(data_suite: str) -> PytestResult:\n    return run_pytest_data_suite(data_suite, extra_args=[], max_attempts=1)\n\n\nclass ParseTestDataSuite(Suite):\n    def test_parse_invalid_case(self) -> None:\n        # Act\n        result = _run_pytest(\"\"\"\n            [case abc]\n            s: str\n            [case foo-XFAIL]\n            s: str\n            \"\"\")\n\n        # Assert\n        assert \"Invalid testcase id 'foo-XFAIL'\" in result.stdout\n\n    def test_parse_invalid_section(self) -> None:\n        # Act\n        result = _run_pytest(\"\"\"\n            [case abc]\n            s: str\n            [unknownsection]\n            abc\n            \"\"\")\n\n        # Assert\n        expected_lineno = result.input.splitlines().index(\"[unknownsection]\") + 1\n        expected = (\n            f\".test:{expected_lineno}: Invalid section header [unknownsection] in case 'abc'\"\n        )\n        assert expected in result.stdout\n\n    def test_bad_ge_version_check(self) -> None:\n        # Act\n        actual = _run_pytest(\"\"\"\n            [case abc]\n            s: str\n            [out version>=3.10]\n            abc\n            \"\"\")\n\n        # Assert\n        assert (\n            \"version>=3.10 always true since minimum runtime version is (3, 10)\" in actual.stdout\n        )\n\n    def test_bad_eq_version_check(self) -> None:\n        # Act\n        actual = _run_pytest(\"\"\"\n            [case abc]\n            s: str\n            [out version==3.7]\n            abc\n            \"\"\")\n\n        # Assert\n        assert (\n            \"version==3.7 always false since minimum runtime version is (3, 10)\" in actual.stdout\n        )\n"
  },
  {
    "path": "mypy/test/meta/test_update_data.py",
    "content": "\"\"\"\nA \"meta test\" which tests the `--update-data` feature for updating .test files.\nUpdating the expected output, especially when it's in the form of inline (comment) assertions,\ncan be brittle, which is why we're \"meta-testing\" here.\n\"\"\"\n\nfrom mypy.test.helpers import Suite\nfrom mypy.test.meta._pytest import PytestResult, dedent_docstring, run_pytest_data_suite\n\n\ndef _run_pytest_update_data(data_suite: str) -> PytestResult:\n    \"\"\"\n    Runs a suite of data test cases through 'pytest --update-data' until either tests pass\n    or until a maximum number of attempts (needed for incremental tests).\n    \"\"\"\n    return run_pytest_data_suite(data_suite, extra_args=[\"--update-data\"], max_attempts=3)\n\n\nclass UpdateDataSuite(Suite):\n    def test_update_data(self) -> None:\n        # Note: We test multiple testcases rather than 'test case per test case'\n        #       so we could also exercise rewriting multiple testcases at once.\n        result = _run_pytest_update_data(\"\"\"\n            [case testCorrect]\n            s: str = 42  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n            [case testWrong]\n            s: str = 42  # E: wrong error\n\n            [case testXfail-xfail]\n            s: str = 42  # E: wrong error\n\n            [case testWrongMultiline]\n            s: str = 42  # E: foo \\\n                         # N: bar\n\n            [case testMissingMultiline]\n            s: str = 42;  i: int = 'foo'\n\n            [case testExtraneous]\n            s: str = 'foo'  # E: wrong error\n\n            [case testExtraneousMultiline]\n            s: str = 'foo'  # E: foo \\\n                            # E: bar\n\n            [case testExtraneousMultilineNonError]\n            s: str = 'foo'  # W: foo \\\n                            # N: bar\n\n            [case testOutCorrect]\n            s: str = 42\n            [out]\n            main:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n            [case testOutWrong]\n            s: str = 42\n            [out]\n            main:1: error: foobar\n\n            [case testOutWrongIncremental]\n            s: str = 42\n            [out]\n            main:1: error: foobar\n            [out2]\n            main:1: error: foobar\n\n            [case testWrongMultipleFiles]\n            import a, b\n            s: str = 42  # E: foo\n            [file a.py]\n            s1: str = 42  # E: bar\n            [file b.py]\n            s2: str = 43  # E: baz\n            [builtins fixtures/list.pyi]\n            \"\"\")\n\n        # Assert\n        expected = dedent_docstring(\"\"\"\n        [case testCorrect]\n        s: str = 42  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n        [case testWrong]\n        s: str = 42  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n        [case testXfail-xfail]\n        s: str = 42  # E: wrong error\n\n        [case testWrongMultiline]\n        s: str = 42  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n        [case testMissingMultiline]\n        s: str = 42;  i: int = 'foo'  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\") \\\\\n                                      # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n        [case testExtraneous]\n        s: str = 'foo'\n\n        [case testExtraneousMultiline]\n        s: str = 'foo'\n\n        [case testExtraneousMultilineNonError]\n        s: str = 'foo'\n\n        [case testOutCorrect]\n        s: str = 42\n        [out]\n        main:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n        [case testOutWrong]\n        s: str = 42\n        [out]\n        main:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n        [case testOutWrongIncremental]\n        s: str = 42\n        [out]\n        main:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        [out2]\n        main:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n        [case testWrongMultipleFiles]\n        import a, b\n        s: str = 42  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        [file a.py]\n        s1: str = 42  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        [file b.py]\n        s2: str = 43  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        [builtins fixtures/list.pyi]\n        \"\"\")\n        assert result.input_updated == expected\n"
  },
  {
    "path": "mypy/test/test_config_parser.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport os\nimport tempfile\nimport unittest\nfrom collections.abc import Iterator\nfrom pathlib import Path\n\nfrom mypy.config_parser import _find_config_file\nfrom mypy.defaults import CONFIG_NAMES, SHARED_CONFIG_NAMES\n\n\n@contextlib.contextmanager\ndef chdir(target: Path) -> Iterator[None]:\n    # Replace with contextlib.chdir in Python 3.11\n    dir = os.getcwd()\n    os.chdir(target)\n    try:\n        yield\n    finally:\n        os.chdir(dir)\n\n\ndef write_config(path: Path, content: str | None = None) -> None:\n    if path.suffix == \".toml\":\n        if content is None:\n            content = \"[tool.mypy]\\nstrict = true\"\n        path.write_text(content)\n    else:\n        if content is None:\n            content = \"[mypy]\\nstrict = True\"\n        path.write_text(content)\n\n\nclass FindConfigFileSuite(unittest.TestCase):\n\n    def test_no_config(self) -> None:\n        with tempfile.TemporaryDirectory() as _tmpdir:\n            tmpdir = Path(_tmpdir)\n            (tmpdir / \".git\").touch()\n            with chdir(tmpdir):\n                result = _find_config_file()\n                assert result is None\n\n    def test_parent_config_with_and_without_git(self) -> None:\n        for name in CONFIG_NAMES + SHARED_CONFIG_NAMES:\n            with tempfile.TemporaryDirectory() as _tmpdir:\n                tmpdir = Path(_tmpdir)\n\n                config = tmpdir / name\n                write_config(config)\n\n                child = tmpdir / \"child\"\n                child.mkdir()\n\n                with chdir(child):\n                    result = _find_config_file()\n                    assert result is not None\n                    assert Path(result[2]).resolve() == config.resolve()\n\n                    git = child / \".git\"\n                    git.touch()\n\n                    result = _find_config_file()\n                    assert result is None\n\n                    git.unlink()\n                    result = _find_config_file()\n                    assert result is not None\n                    hg = child / \".hg\"\n                    hg.touch()\n\n                    result = _find_config_file()\n                    assert result is None\n\n    def test_precedence(self) -> None:\n        with tempfile.TemporaryDirectory() as _tmpdir:\n            tmpdir = Path(_tmpdir)\n\n            pyproject = tmpdir / \"pyproject.toml\"\n            setup_cfg = tmpdir / \"setup.cfg\"\n            mypy_ini = tmpdir / \"mypy.ini\"\n            dot_mypy = tmpdir / \".mypy.ini\"\n\n            child = tmpdir / \"child\"\n            child.mkdir()\n\n            for cwd in [tmpdir, child]:\n                write_config(pyproject)\n                write_config(setup_cfg)\n                write_config(mypy_ini)\n                write_config(dot_mypy)\n\n                with chdir(cwd):\n                    result = _find_config_file()\n                    assert result is not None\n                    assert os.path.basename(result[2]) == \"mypy.ini\"\n\n                    mypy_ini.unlink()\n                    result = _find_config_file()\n                    assert result is not None\n                    assert os.path.basename(result[2]) == \".mypy.ini\"\n\n                    dot_mypy.unlink()\n                    result = _find_config_file()\n                    assert result is not None\n                    assert os.path.basename(result[2]) == \"pyproject.toml\"\n\n                    pyproject.unlink()\n                    result = _find_config_file()\n                    assert result is not None\n                    assert os.path.basename(result[2]) == \"setup.cfg\"\n\n    def test_precedence_missing_section(self) -> None:\n        with tempfile.TemporaryDirectory() as _tmpdir:\n            tmpdir = Path(_tmpdir)\n\n            child = tmpdir / \"child\"\n            child.mkdir()\n\n            parent_mypy = tmpdir / \"mypy.ini\"\n            child_pyproject = child / \"pyproject.toml\"\n            write_config(parent_mypy)\n            write_config(child_pyproject, content=\"\")\n\n            with chdir(child):\n                result = _find_config_file()\n                assert result is not None\n                assert Path(result[2]).resolve() == parent_mypy.resolve()\n"
  },
  {
    "path": "mypy/test/test_diff_cache.py",
    "content": "\"\"\"Integration tests for misc/diff-cache.py and misc/apply-cache-diff.py.\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nimport time\nimport unittest\n\nfrom mypy.test.config import PREFIX\n\n_MISC_DIR = os.path.join(PREFIX, \"misc\")\n_DIFF_CACHE_PATH = os.path.join(_MISC_DIR, \"diff-cache.py\")\n_APPLY_CACHE_DIFF_PATH = os.path.join(_MISC_DIR, \"apply-cache-diff.py\")\n\n\nclass DiffCacheIntegrationTests(unittest.TestCase):\n    \"\"\"Run mypy twice with different sources, diff the caches, and apply the diff.\"\"\"\n\n    def test_diff_cache_produces_valid_json(self) -> None:\n        # Use a single source directory with two cache directories so that\n        # source paths in the cache metadata are identical between runs.\n        # b.py is modified and c.py is added in the second run.\n        src_dir = tempfile.mkdtemp()\n        output_file = os.path.join(tempfile.mkdtemp(), \"diff.json\")\n        env = os.environ.copy()\n        env[\"PYTHONPATH\"] = PREFIX\n        try:\n            cache1 = os.path.join(src_dir, \"cache1\")\n            cache2 = os.path.join(src_dir, \"cache2\")\n\n            # Write sources and run mypy for cache1 (using sqlite cache)\n            with open(os.path.join(src_dir, \"a.py\"), \"w\") as f:\n                f.write(\"x: int = 1\\n\")\n            with open(os.path.join(src_dir, \"b.py\"), \"w\") as f:\n                f.write(\"import a\\ndef foo() -> int:\\n    return 1\\n\")\n            result = subprocess.run(\n                [\n                    sys.executable,\n                    \"-m\",\n                    \"mypy\",\n                    \"--sqlite-cache\",\n                    \"--cache-fine-grained\",\n                    \"--cache-dir\",\n                    cache1,\n                    \"b.py\",\n                ],\n                cwd=src_dir,\n                capture_output=True,\n                text=True,\n                env=env,\n            )\n            assert result.returncode == 0, f\"mypy run 1 failed: {result.stderr}\"\n\n            # Sleep so that mtimes will be different between runs\n            time.sleep(1)\n\n            # Touch a.py to change its mtime without modifying content\n            os.utime(os.path.join(src_dir, \"a.py\"))\n\n            # Modify b.py to access a.x (adding a fine-grained dependency),\n            # and add a new c.py, then run mypy for cache2\n            with open(os.path.join(src_dir, \"b.py\"), \"w\") as f:\n                f.write(\"import a\\ndef foo() -> str:\\n    return str(a.x)\\n\")\n            with open(os.path.join(src_dir, \"c.py\"), \"w\") as f:\n                f.write(\"import a\\ny: str = 'world'\\n\")\n            result = subprocess.run(\n                [\n                    sys.executable,\n                    \"-m\",\n                    \"mypy\",\n                    \"--sqlite-cache\",\n                    \"--cache-fine-grained\",\n                    \"--cache-dir\",\n                    cache2,\n                    \"b.py\",\n                    \"c.py\",\n                ],\n                cwd=src_dir,\n                capture_output=True,\n                text=True,\n                env=env,\n            )\n            assert result.returncode == 0, f\"mypy run 2 failed: {result.stderr}\"\n\n            # Find the Python version subdirectory (e.g. \"3.14\")\n            subdirs = [\n                e\n                for e in os.listdir(cache1)\n                if os.path.isdir(os.path.join(cache1, e)) and e[0].isdigit()\n            ]\n            assert len(subdirs) == 1, f\"Expected one version subdir, got {subdirs}\"\n            ver = subdirs[0]\n\n            # Run diff-cache.py with --sqlite\n            result = subprocess.run(\n                [\n                    sys.executable,\n                    _DIFF_CACHE_PATH,\n                    \"--sqlite\",\n                    os.path.join(cache1, ver),\n                    os.path.join(cache2, ver),\n                    output_file,\n                ],\n                capture_output=True,\n                text=True,\n                env=env,\n            )\n            assert result.returncode == 0, f\"diff-cache.py failed: {result.stderr}\"\n\n            # Verify the output is valid JSON\n            with open(output_file) as f:\n                data = json.load(f)\n            assert isinstance(data, dict)\n            assert len(data) > 0, \"Expected non-empty diff\"\n\n            # Only modified or new files should appear in the diff.\n            # b.py changed and c.py is new, so both should be present.\n            # a.py did not change, so no a.* keys should appear.\n            keys = set(data.keys())\n            b_keys = {k for k in keys if \"/b.\" in k or k.startswith(\"b.\")}\n            c_keys = {k for k in keys if \"/c.\" in k or k.startswith(\"c.\")}\n            a_keys = {k for k in keys if \"/a.\" in k or k.startswith(\"a.\")}\n            assert len(a_keys) == 0, f\"Unexpected a.* entries in diff: {a_keys}\"\n            assert len(b_keys) == 2, f\"Expected 2 b.* entries in diff, got: {b_keys}\"\n            assert len(c_keys) == 4, f\"Expected 3 c.* entries in diff, got: {c_keys}\"\n\n            # The new access to a.x in b.py should create a fine-grained\n            # dependency recorded in @root.deps.json.\n            assert \"@root.deps.json\" in keys\n            root_deps = json.loads(data[\"@root.deps.json\"])\n            assert set(root_deps.keys()) == {\n                \"<a.x>\",\n                \"<a>\",\n            }, f\"Unexpected root deps keys: {sorted(root_deps.keys())}\"\n            assert sorted(root_deps[\"<a.x>\"]) == [\"b.foo\"]\n            assert sorted(root_deps[\"<a>\"]) == [\"b.foo\", \"c\"]\n\n            # Apply the diff to a copy of cache1 and verify the result.\n            cache2_ver = os.path.join(cache2, ver)\n            patched = os.path.join(src_dir, \"patched\")\n            patched_ver = os.path.join(patched, ver)\n            shutil.copytree(cache1, patched)\n\n            # Snapshot cache entries before applying the diff\n            from mypy.metastore import SqliteMetadataStore\n\n            def read_all(cache_dir: str) -> dict[str, bytes]:\n                store = SqliteMetadataStore(cache_dir)\n                result = {name: store.read(name) for name in store.list_all()}\n                assert store.db is not None\n                store.db.close()\n                return result\n\n            before = read_all(patched_ver)\n\n            # Apply the diff\n            result = subprocess.run(\n                [sys.executable, _APPLY_CACHE_DIFF_PATH, \"--sqlite\", patched_ver, output_file],\n                capture_output=True,\n                text=True,\n                env=env,\n            )\n            assert result.returncode == 0, f\"apply-cache-diff.py failed: {result.stderr}\"\n\n            after = read_all(patched_ver)\n\n            # a.py entries should be unchanged\n            for name in before:\n                if name.startswith(\"a.\") or \"/a.\" in name:\n                    assert name in after, f\"{name} missing after apply\"\n                    assert before[name] == after[name], f\"{name} changed after apply\"\n\n            # b.py and c.py entries should match cache2 after applying the diff.\n            # Skip .meta.ff files since they contain mtimes that legitimately differ.\n            target = read_all(cache2_ver)\n            for prefix in (\"b.\", \"c.\"):\n                for name in target:\n                    if not (name.startswith(prefix) or f\"/{prefix}\" in name):\n                        continue\n                    assert name in after, f\"{name} missing after apply\"\n                    if name.endswith(\".meta.ff\"):\n                        # mtimes legitimately differ, but content should not be identical\n                        # to the pre-apply version (it was updated by the diff)\n                        assert after[name] != before.get(name), f\"{name} unchanged after apply\"\n                    else:\n                        assert after[name] == target[name], f\"{name} differs from target\"\n\n            # Verify fine-grained deps were applied correctly\n            from mypy.util import json_loads\n\n            applied_root_deps = json_loads(after[\"@root.deps.json\"])\n            assert set(applied_root_deps.keys()) == {\n                \"<a.x>\",\n                \"<a>\",\n            }, f\"Unexpected applied root deps keys: {sorted(applied_root_deps.keys())}\"\n            assert sorted(applied_root_deps[\"<a.x>\"]) == [\"b.foo\"]\n            assert sorted(applied_root_deps[\"<a>\"]) == [\"b.foo\", \"c\"]\n        finally:\n            shutil.rmtree(src_dir, ignore_errors=True)\n            shutil.rmtree(os.path.dirname(output_file), ignore_errors=True)\n\n\nif __name__ == \"__main__\":\n    unittest.main()\n"
  },
  {
    "path": "mypy/test/test_find_sources.py",
    "content": "from __future__ import annotations\n\nimport os\nimport shutil\nimport tempfile\nimport unittest\n\nimport pytest\n\nfrom mypy.find_sources import InvalidSourceList, SourceFinder, create_source_list\nfrom mypy.fscache import FileSystemCache\nfrom mypy.modulefinder import BuildSource\nfrom mypy.options import Options\n\n\nclass FakeFSCache(FileSystemCache):\n    def __init__(self, files: set[str]) -> None:\n        self.files = {os.path.abspath(f) for f in files}\n\n    def isfile(self, path: str) -> bool:\n        return path in self.files\n\n    def isdir(self, path: str) -> bool:\n        if not path.endswith(os.sep):\n            path += os.sep\n        return any(f.startswith(path) for f in self.files)\n\n    def listdir(self, path: str) -> list[str]:\n        if not path.endswith(os.sep):\n            path += os.sep\n        return list({f[len(path) :].split(os.sep)[0] for f in self.files if f.startswith(path)})\n\n    def init_under_package_root(self, path: str) -> bool:\n        return False\n\n\ndef normalise_path(path: str) -> str:\n    path = os.path.splitdrive(path)[1]\n    path = path.replace(os.sep, \"/\")\n    return path\n\n\ndef normalise_build_source_list(sources: list[BuildSource]) -> list[tuple[str, str | None]]:\n    return sorted(\n        (s.module, (normalise_path(s.base_dir) if s.base_dir is not None else None))\n        for s in sources\n    )\n\n\ndef crawl(finder: SourceFinder, f: str) -> tuple[str, str]:\n    module, base_dir = finder.crawl_up(f)\n    return module, normalise_path(base_dir)\n\n\ndef find_sources_in_dir(finder: SourceFinder, f: str) -> list[tuple[str, str | None]]:\n    return normalise_build_source_list(finder.find_sources_in_dir(os.path.abspath(f)))\n\n\ndef find_sources(\n    paths: list[str], options: Options, fscache: FileSystemCache\n) -> list[tuple[str, str | None]]:\n    paths = [os.path.abspath(p) for p in paths]\n    return normalise_build_source_list(create_source_list(paths, options, fscache))\n\n\nclass SourceFinderSuite(unittest.TestCase):\n    def setUp(self) -> None:\n        self.tempdir = tempfile.mkdtemp()\n        self.oldcwd = os.getcwd()\n        os.chdir(self.tempdir)\n\n    def tearDown(self) -> None:\n        os.chdir(self.oldcwd)\n        shutil.rmtree(self.tempdir)\n\n    def test_crawl_no_namespace(self) -> None:\n        options = Options()\n        options.namespace_packages = False\n\n        finder = SourceFinder(FakeFSCache({\"/setup.py\"}), options)\n        assert crawl(finder, \"/setup.py\") == (\"setup\", \"/\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/setup.py\"}), options)\n        assert crawl(finder, \"/a/setup.py\") == (\"setup\", \"/a\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/b/setup.py\"}), options)\n        assert crawl(finder, \"/a/b/setup.py\") == (\"setup\", \"/a/b\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/setup.py\", \"/a/__init__.py\"}), options)\n        assert crawl(finder, \"/a/setup.py\") == (\"a.setup\", \"/\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/invalid-name/setup.py\", \"/a/__init__.py\"}), options)\n        assert crawl(finder, \"/a/invalid-name/setup.py\") == (\"setup\", \"/a/invalid-name\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/b/setup.py\", \"/a/__init__.py\"}), options)\n        assert crawl(finder, \"/a/b/setup.py\") == (\"setup\", \"/a/b\")\n\n        finder = SourceFinder(\n            FakeFSCache({\"/a/b/c/setup.py\", \"/a/__init__.py\", \"/a/b/c/__init__.py\"}), options\n        )\n        assert crawl(finder, \"/a/b/c/setup.py\") == (\"c.setup\", \"/a/b\")\n\n    def test_crawl_namespace(self) -> None:\n        options = Options()\n        options.namespace_packages = True\n\n        finder = SourceFinder(FakeFSCache({\"/setup.py\"}), options)\n        assert crawl(finder, \"/setup.py\") == (\"setup\", \"/\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/setup.py\"}), options)\n        assert crawl(finder, \"/a/setup.py\") == (\"setup\", \"/a\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/b/setup.py\"}), options)\n        assert crawl(finder, \"/a/b/setup.py\") == (\"setup\", \"/a/b\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/setup.py\", \"/a/__init__.py\"}), options)\n        assert crawl(finder, \"/a/setup.py\") == (\"a.setup\", \"/\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/invalid-name/setup.py\", \"/a/__init__.py\"}), options)\n        assert crawl(finder, \"/a/invalid-name/setup.py\") == (\"setup\", \"/a/invalid-name\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/b/setup.py\", \"/a/__init__.py\"}), options)\n        assert crawl(finder, \"/a/b/setup.py\") == (\"a.b.setup\", \"/\")\n\n        finder = SourceFinder(\n            FakeFSCache({\"/a/b/c/setup.py\", \"/a/__init__.py\", \"/a/b/c/__init__.py\"}), options\n        )\n        assert crawl(finder, \"/a/b/c/setup.py\") == (\"a.b.c.setup\", \"/\")\n\n    def test_crawl_namespace_explicit_base(self) -> None:\n        options = Options()\n        options.namespace_packages = True\n        options.explicit_package_bases = True\n\n        finder = SourceFinder(FakeFSCache({\"/setup.py\"}), options)\n        assert crawl(finder, \"/setup.py\") == (\"setup\", \"/\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/setup.py\"}), options)\n        assert crawl(finder, \"/a/setup.py\") == (\"setup\", \"/a\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/b/setup.py\"}), options)\n        assert crawl(finder, \"/a/b/setup.py\") == (\"setup\", \"/a/b\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/setup.py\", \"/a/__init__.py\"}), options)\n        assert crawl(finder, \"/a/setup.py\") == (\"a.setup\", \"/\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/invalid-name/setup.py\", \"/a/__init__.py\"}), options)\n        assert crawl(finder, \"/a/invalid-name/setup.py\") == (\"setup\", \"/a/invalid-name\")\n\n        finder = SourceFinder(FakeFSCache({\"/a/b/setup.py\", \"/a/__init__.py\"}), options)\n        assert crawl(finder, \"/a/b/setup.py\") == (\"a.b.setup\", \"/\")\n\n        finder = SourceFinder(\n            FakeFSCache({\"/a/b/c/setup.py\", \"/a/__init__.py\", \"/a/b/c/__init__.py\"}), options\n        )\n        assert crawl(finder, \"/a/b/c/setup.py\") == (\"a.b.c.setup\", \"/\")\n\n        # set mypy path, so we actually have some explicit base dirs\n        options.mypy_path = [\"/a/b\"]\n\n        finder = SourceFinder(FakeFSCache({\"/a/b/c/setup.py\"}), options)\n        assert crawl(finder, \"/a/b/c/setup.py\") == (\"c.setup\", \"/a/b\")\n\n        finder = SourceFinder(\n            FakeFSCache({\"/a/b/c/setup.py\", \"/a/__init__.py\", \"/a/b/c/__init__.py\"}), options\n        )\n        assert crawl(finder, \"/a/b/c/setup.py\") == (\"c.setup\", \"/a/b\")\n\n        options.mypy_path = [\"/a/b\", \"/a/b/c\"]\n        finder = SourceFinder(FakeFSCache({\"/a/b/c/setup.py\"}), options)\n        assert crawl(finder, \"/a/b/c/setup.py\") == (\"setup\", \"/a/b/c\")\n\n    def test_crawl_namespace_multi_dir(self) -> None:\n        options = Options()\n        options.namespace_packages = True\n        options.explicit_package_bases = True\n        options.mypy_path = [\"/a\", \"/b\"]\n\n        finder = SourceFinder(FakeFSCache({\"/a/pkg/a.py\", \"/b/pkg/b.py\"}), options)\n        assert crawl(finder, \"/a/pkg/a.py\") == (\"pkg.a\", \"/a\")\n        assert crawl(finder, \"/b/pkg/b.py\") == (\"pkg.b\", \"/b\")\n\n    def test_find_sources_in_dir_no_namespace(self) -> None:\n        options = Options()\n        options.namespace_packages = False\n\n        files = {\n            \"/pkg/a1/b/c/d/e.py\",\n            \"/pkg/a1/b/f.py\",\n            \"/pkg/a2/__init__.py\",\n            \"/pkg/a2/b/c/d/e.py\",\n            \"/pkg/a2/b/f.py\",\n        }\n        finder = SourceFinder(FakeFSCache(files), options)\n        assert find_sources_in_dir(finder, \"/\") == [\n            (\"a2\", \"/pkg\"),\n            (\"e\", \"/pkg/a1/b/c/d\"),\n            (\"e\", \"/pkg/a2/b/c/d\"),\n            (\"f\", \"/pkg/a1/b\"),\n            (\"f\", \"/pkg/a2/b\"),\n        ]\n\n    def test_find_sources_in_dir_namespace(self) -> None:\n        options = Options()\n        options.namespace_packages = True\n\n        files = {\n            \"/pkg/a1/b/c/d/e.py\",\n            \"/pkg/a1/b/f.py\",\n            \"/pkg/a2/__init__.py\",\n            \"/pkg/a2/b/c/d/e.py\",\n            \"/pkg/a2/b/f.py\",\n        }\n        finder = SourceFinder(FakeFSCache(files), options)\n        assert find_sources_in_dir(finder, \"/\") == [\n            (\"a2\", \"/pkg\"),\n            (\"a2.b.c.d.e\", \"/pkg\"),\n            (\"a2.b.f\", \"/pkg\"),\n            (\"e\", \"/pkg/a1/b/c/d\"),\n            (\"f\", \"/pkg/a1/b\"),\n        ]\n\n    def test_find_sources_in_dir_namespace_explicit_base(self) -> None:\n        options = Options()\n        options.namespace_packages = True\n        options.explicit_package_bases = True\n        options.mypy_path = [\"/\"]\n\n        files = {\n            \"/pkg/a1/b/c/d/e.py\",\n            \"/pkg/a1/b/f.py\",\n            \"/pkg/a2/__init__.py\",\n            \"/pkg/a2/b/c/d/e.py\",\n            \"/pkg/a2/b/f.py\",\n        }\n        finder = SourceFinder(FakeFSCache(files), options)\n        assert find_sources_in_dir(finder, \"/\") == [\n            (\"pkg.a1.b.c.d.e\", \"/\"),\n            (\"pkg.a1.b.f\", \"/\"),\n            (\"pkg.a2\", \"/\"),\n            (\"pkg.a2.b.c.d.e\", \"/\"),\n            (\"pkg.a2.b.f\", \"/\"),\n        ]\n\n        options.mypy_path = [\"/pkg\"]\n        finder = SourceFinder(FakeFSCache(files), options)\n        assert find_sources_in_dir(finder, \"/\") == [\n            (\"a1.b.c.d.e\", \"/pkg\"),\n            (\"a1.b.f\", \"/pkg\"),\n            (\"a2\", \"/pkg\"),\n            (\"a2.b.c.d.e\", \"/pkg\"),\n            (\"a2.b.f\", \"/pkg\"),\n        ]\n\n    def test_find_sources_in_dir_namespace_multi_dir(self) -> None:\n        options = Options()\n        options.namespace_packages = True\n        options.explicit_package_bases = True\n        options.mypy_path = [\"/a\", \"/b\"]\n\n        finder = SourceFinder(FakeFSCache({\"/a/pkg/a.py\", \"/b/pkg/b.py\"}), options)\n        assert find_sources_in_dir(finder, \"/\") == [(\"pkg.a\", \"/a\"), (\"pkg.b\", \"/b\")]\n\n    def test_find_sources_exclude(self) -> None:\n        options = Options()\n        options.namespace_packages = True\n\n        # default\n        for excluded_dir in [\"site-packages\", \".whatever\", \"node_modules\", \".x/.z\"]:\n            fscache = FakeFSCache({\"/dir/a.py\", f\"/dir/venv/{excluded_dir}/b.py\"})\n            assert find_sources([\"/\"], options, fscache) == [(\"a\", \"/dir\")]\n            with pytest.raises(InvalidSourceList):\n                find_sources([\"/dir/venv/\"], options, fscache)\n            assert find_sources([f\"/dir/venv/{excluded_dir}\"], options, fscache) == [\n                (\"b\", f\"/dir/venv/{excluded_dir}\")\n            ]\n            assert find_sources([f\"/dir/venv/{excluded_dir}/b.py\"], options, fscache) == [\n                (\"b\", f\"/dir/venv/{excluded_dir}\")\n            ]\n\n        files = {\n            \"/pkg/a1/b/c/d/e.py\",\n            \"/pkg/a1/b/f.py\",\n            \"/pkg/a2/__init__.py\",\n            \"/pkg/a2/b/c/d/e.py\",\n            \"/pkg/a2/b/f.py\",\n        }\n\n        # file name\n        options.exclude = [r\"/f\\.py$\"]\n        fscache = FakeFSCache(files)\n        assert find_sources([\"/\"], options, fscache) == [\n            (\"a2\", \"/pkg\"),\n            (\"a2.b.c.d.e\", \"/pkg\"),\n            (\"e\", \"/pkg/a1/b/c/d\"),\n        ]\n        assert find_sources([\"/pkg/a1/b/f.py\"], options, fscache) == [(\"f\", \"/pkg/a1/b\")]\n        assert find_sources([\"/pkg/a2/b/f.py\"], options, fscache) == [(\"a2.b.f\", \"/pkg\")]\n\n        # directory name\n        options.exclude = [\"/a1/\"]\n        fscache = FakeFSCache(files)\n        assert find_sources([\"/\"], options, fscache) == [\n            (\"a2\", \"/pkg\"),\n            (\"a2.b.c.d.e\", \"/pkg\"),\n            (\"a2.b.f\", \"/pkg\"),\n        ]\n        with pytest.raises(InvalidSourceList):\n            find_sources([\"/pkg/a1\"], options, fscache)\n        with pytest.raises(InvalidSourceList):\n            find_sources([\"/pkg/a1/\"], options, fscache)\n        with pytest.raises(InvalidSourceList):\n            find_sources([\"/pkg/a1/b\"], options, fscache)\n\n        options.exclude = [\"/a1/$\"]\n        assert find_sources([\"/pkg/a1\"], options, fscache) == [\n            (\"e\", \"/pkg/a1/b/c/d\"),\n            (\"f\", \"/pkg/a1/b\"),\n        ]\n\n        # paths\n        options.exclude = [\"/pkg/a1/\"]\n        fscache = FakeFSCache(files)\n        assert find_sources([\"/\"], options, fscache) == [\n            (\"a2\", \"/pkg\"),\n            (\"a2.b.c.d.e\", \"/pkg\"),\n            (\"a2.b.f\", \"/pkg\"),\n        ]\n        with pytest.raises(InvalidSourceList):\n            find_sources([\"/pkg/a1\"], options, fscache)\n\n        # OR two patterns together\n        for orred in [[\"/(a1|a3)/\"], [\"a1\", \"a3\"], [\"a3\", \"a1\"]]:\n            options.exclude = orred\n            fscache = FakeFSCache(files)\n            assert find_sources([\"/\"], options, fscache) == [\n                (\"a2\", \"/pkg\"),\n                (\"a2.b.c.d.e\", \"/pkg\"),\n                (\"a2.b.f\", \"/pkg\"),\n            ]\n\n        options.exclude = [\"b/c/\"]\n        fscache = FakeFSCache(files)\n        assert find_sources([\"/\"], options, fscache) == [\n            (\"a2\", \"/pkg\"),\n            (\"a2.b.f\", \"/pkg\"),\n            (\"f\", \"/pkg/a1/b\"),\n        ]\n\n        # nothing should be ignored as a result of this\n        big_exclude1 = [\n            \"/pkg/a/\",\n            \"/2\",\n            \"/1\",\n            \"/pk/\",\n            \"/kg\",\n            \"/g.py\",\n            \"/bc\",\n            \"/xxx/pkg/a2/b/f.py\",\n            \"xxx/pkg/a2/b/f.py\",\n        ]\n        big_exclude2 = [\"|\".join(big_exclude1)]\n        for big_exclude in [big_exclude1, big_exclude2]:\n            options.exclude = big_exclude\n            fscache = FakeFSCache(files)\n            assert len(find_sources([\"/\"], options, fscache)) == len(files)\n\n            files = {\n                \"pkg/a1/b/c/d/e.py\",\n                \"pkg/a1/b/f.py\",\n                \"pkg/a2/__init__.py\",\n                \"pkg/a2/b/c/d/e.py\",\n                \"pkg/a2/b/f.py\",\n            }\n            fscache = FakeFSCache(files)\n            assert len(find_sources([\".\"], options, fscache)) == len(files)\n"
  },
  {
    "path": "mypy/test/test_nativeparse.py",
    "content": "\"\"\"Tests for the experimental native mypy parser.\n\nTo run these, you will need to manually install ast_serialize from\nhttps://github.com/mypyc/ast_serialize first (see the README for the details).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport os\nimport tempfile\nimport unittest\nfrom collections.abc import Iterator\nfrom typing import Any\n\nfrom mypy import defaults, nodes\nfrom mypy.cache import (\n    END_TAG,\n    LIST_GEN,\n    LIST_INT,\n    LITERAL_INT,\n    LITERAL_NONE,\n    LITERAL_STR,\n    LOCATION,\n)\nfrom mypy.config_parser import parse_mypy_comments\nfrom mypy.errors import CompileError\nfrom mypy.nodes import MypyFile\nfrom mypy.options import Options\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal\nfrom mypy.util import get_mypy_comments\n\n# If the experimental ast_serialize module isn't installed, the following import will fail\n# and we won't run any native parser tests.\ntry:\n    from mypy.nativeparse import native_parse, parse_to_binary_ast\n\n    has_nativeparse = True\nexcept ImportError:\n    has_nativeparse = False\n\n\nclass NativeParserSuite(DataSuite):\n    required_out_section = True\n    base_path = \".\"\n    files = [\"native-parser.test\"] if has_nativeparse else []\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_parser(testcase)\n\n\nclass NativeParserImportsSuite(DataSuite):\n    required_out_section = True\n    base_path = \".\"\n    files = [\"native-parser-imports.test\"] if has_nativeparse else []\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_parser_imports(testcase)\n\n\ndef test_parser(testcase: DataDrivenTestCase) -> None:\n    \"\"\"Perform a single native parser test case.\n\n    The argument contains the description of the test case.\n    \"\"\"\n    options = Options()\n    options.hide_error_codes = True\n\n    if testcase.file.endswith(\"python310.test\"):\n        options.python_version = (3, 10)\n    elif testcase.file.endswith(\"python312.test\"):\n        options.python_version = (3, 12)\n    elif testcase.file.endswith(\"python313.test\"):\n        options.python_version = (3, 13)\n    elif testcase.file.endswith(\"python314.test\"):\n        options.python_version = (3, 14)\n    else:\n        options.python_version = defaults.PYTHON3_VERSION\n\n    source = \"\\n\".join(testcase.input)\n\n    # Apply mypy: comments to options.\n    comments = get_mypy_comments(source)\n    changes, _ = parse_mypy_comments(comments, options)\n    options = options.apply_changes(changes)\n\n    # Check if we should skip function bodies (when ignoring errors)\n    skip_function_bodies = \"# mypy: ignore-errors=True\" in source\n\n    try:\n        with temp_source(source) as fnam:\n            node, errors, type_ignores = native_parse(fnam, options, skip_function_bodies)\n            node.path = \"main\"\n            a = node.str_with_options(options).split(\"\\n\")\n            a = [format_error(err) for err in errors] + a\n            a = [format_ignore(ignore) for ignore in type_ignores] + a\n    except CompileError as e:\n        a = e.messages\n    assert_string_arrays_equal(\n        testcase.output, a, f\"Invalid parser output ({testcase.file}, line {testcase.line})\"\n    )\n\n\ndef format_error(err: dict[str, Any]) -> str:\n    return f\"{err['line']}:{err['column']}: error: {err['message']}\"\n\n\ndef format_ignore(ignore: tuple[int, list[str]]) -> str:\n    line, codes = ignore\n    if not codes:\n        return f\"ignore: {line}\"\n    else:\n        return f\"ignore: {line} [{', '.join(codes)}]\"\n\n\ndef test_parser_imports(testcase: DataDrivenTestCase) -> None:\n    \"\"\"Perform a single native parser imports test case.\n\n    The argument contains the description of the test case.\n    This test outputs only reachable import information.\n    \"\"\"\n    options = Options()\n    options.hide_error_codes = True\n    options.python_version = (3, 10)\n\n    source = \"\\n\".join(testcase.input)\n\n    try:\n        with temp_source(source) as fnam:\n            node, errors, type_ignores = native_parse(fnam, options)\n\n            # Extract and format reachable imports\n            a = format_reachable_imports(node)\n            a = [format_error(err) for err in errors] + a\n    except CompileError as e:\n        a = e.messages\n\n    assert_string_arrays_equal(\n        testcase.output, a, f\"Invalid parser output ({testcase.file}, line {testcase.line})\"\n    )\n\n\ndef format_reachable_imports(node: MypyFile) -> list[str]:\n    \"\"\"Format reachable imports from a MypyFile node.\n\n    Returns a list of strings representing reachable imports with line numbers and flags.\n    \"\"\"\n    from mypy.nodes import Import, ImportAll, ImportFrom\n\n    output: list[str] = []\n\n    # Filter for reachable imports (is_unreachable == False)\n    reachable_imports = [imp for imp in node.imports if not imp.is_unreachable]\n\n    for imp in reachable_imports:\n        line_num = imp.line\n\n        # Collect flags (only show when flag is False/not set)\n        flags = []\n        if not imp.is_top_level:\n            flags.append(\"not top_level\")\n        if imp.is_mypy_only:\n            flags.append(\"mypy_only\")\n\n        flags_str = \" [\" + \", \".join(flags) + \"]\" if flags else \"\"\n\n        if isinstance(imp, Import):\n            # Format: line: import foo [as bar] [flags]\n            for module_id, as_id in imp.ids:\n                if as_id:\n                    output.append(f\"{line_num}: import {module_id} as {as_id}{flags_str}\")\n                else:\n                    output.append(f\"{line_num}: import {module_id}{flags_str}\")\n        elif isinstance(imp, ImportFrom):\n            # Format: line: from foo import bar, baz [as b] [flags]\n            # Handle relative imports\n            if imp.relative > 0:\n                prefix = \".\" * imp.relative\n                if imp.id:\n                    module = f\"{prefix}{imp.id}\"\n                else:\n                    module = prefix\n            else:\n                module = imp.id\n\n            # Group all names together\n            name_parts = []\n            for name, as_name in imp.names:\n                if as_name:\n                    name_parts.append(f\"{name} as {as_name}\")\n                else:\n                    name_parts.append(name)\n\n            names_str = \", \".join(name_parts)\n            output.append(f\"{line_num}: from {module} import {names_str}{flags_str}\")\n        elif isinstance(imp, ImportAll):\n            # Format: line: from foo import * [flags]\n            # Handle relative imports\n            if imp.relative > 0:\n                prefix = \".\" * imp.relative\n                if imp.id:\n                    module = f\"{prefix}{imp.id}\"\n                else:\n                    module = prefix\n            else:\n                module = imp.id\n\n            output.append(f\"{line_num}: from {module} import *{flags_str}\")\n\n    return output\n\n\n@unittest.skipUnless(has_nativeparse, \"nativeparse not available\")\nclass TestNativeParserBinaryFormat(unittest.TestCase):\n    def test_trivial_binary_data(self) -> None:\n        # A quick sanity check to ensure the serialized data looks as expected. Only covers\n        # a few AST nodes.\n\n        def int_enc(n: int) -> int:\n            return (n + 10) << 1\n\n        def locs(start_line: int, start_column: int, end_line: int, end_column: int) -> list[int]:\n            return [\n                LOCATION,\n                int_enc(start_line),\n                int_enc(start_column),\n                int_enc(end_line - start_line),\n                int_enc(end_column - start_column),\n            ]\n\n        with temp_source(\"print('hello')\") as fnam:\n            b, _, _, _, _, _ = parse_to_binary_ast(fnam, Options())\n            assert list(b) == (\n                [LITERAL_INT, 22, nodes.EXPR_STMT, nodes.CALL_EXPR]\n                + [nodes.NAME_EXPR, LITERAL_STR]\n                + [int_enc(5)]\n                + list(b\"print\")\n                + locs(1, 0, 1, 5)\n                + [END_TAG, LIST_GEN, 22, nodes.STR_EXPR]\n                + [LITERAL_STR, int_enc(5)]\n                + list(b\"hello\")\n                + locs(1, 6, 1, 13)\n                + [END_TAG]\n                # arg_kinds: [ARG_POS]\n                + [LIST_INT, 22, int_enc(0)]\n                # arg_names: [None]\n                + [LIST_GEN, 22, LITERAL_NONE]\n                + locs(1, 0, 1, 14)\n                + [END_TAG, END_TAG]\n            )\n\n\n@contextlib.contextmanager\ndef temp_source(text: str) -> Iterator[str]:\n    with tempfile.TemporaryDirectory() as temp_dir:\n        temp_path = os.path.join(temp_dir, \"t.py\")\n        with open(temp_path, \"w\") as f:\n            f.write(text)\n        yield temp_path\n"
  },
  {
    "path": "mypy/test/test_ref_info.py",
    "content": "\"\"\"Test exporting line-level reference information (undocumented feature)\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\nimport sys\n\nfrom mypy import build\nfrom mypy.modulefinder import BuildSource\nfrom mypy.options import Options\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal\n\n\nclass RefInfoSuite(DataSuite):\n    required_out_section = True\n    files = [\"ref-info.test\"]\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        options = Options()\n        options.use_builtins_fixtures = True\n        options.show_traceback = True\n        options.export_ref_info = True  # This is the flag we are testing\n        options.sqlite_cache = False\n\n        src = \"\\n\".join(testcase.input)\n        result = build.build(\n            sources=[BuildSource(\"main\", None, src)], options=options, alt_lib_path=test_temp_dir\n        )\n        assert not result.errors\n\n        major, minor = sys.version_info[:2]\n        ref_path = os.path.join(options.cache_dir, f\"{major}.{minor}\", \"__main__.refs.json\")\n\n        with open(ref_path) as refs_file:\n            data = json.load(refs_file)\n\n        a = []\n        for item in data:\n            a.append(f\"{item['line']}:{item['column']}:{item['target']}\")\n\n        assert_string_arrays_equal(\n            testcase.output, a, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n        )\n"
  },
  {
    "path": "mypy/test/testapi.py",
    "content": "from __future__ import annotations\n\nimport sys\nfrom io import StringIO\n\nimport mypy.api\nfrom mypy.test.helpers import Suite\n\n\nclass APISuite(Suite):\n    def setUp(self) -> None:\n        self.sys_stdout = sys.stdout\n        self.sys_stderr = sys.stderr\n        sys.stdout = self.stdout = StringIO()\n        sys.stderr = self.stderr = StringIO()\n\n    def tearDown(self) -> None:\n        sys.stdout = self.sys_stdout\n        sys.stderr = self.sys_stderr\n        assert self.stdout.getvalue() == \"\"\n        assert self.stderr.getvalue() == \"\"\n\n    def test_capture_bad_opt(self) -> None:\n        \"\"\"stderr should be captured when a bad option is passed.\"\"\"\n        _, stderr, _ = mypy.api.run([\"--some-bad-option\"])\n        assert isinstance(stderr, str)\n        assert stderr != \"\"\n\n    def test_capture_empty(self) -> None:\n        \"\"\"stderr should be captured when a bad option is passed.\"\"\"\n        _, stderr, _ = mypy.api.run([])\n        assert isinstance(stderr, str)\n        assert stderr != \"\"\n\n    def test_capture_help(self) -> None:\n        \"\"\"stdout should be captured when --help is passed.\"\"\"\n        stdout, _, _ = mypy.api.run([\"--help\"])\n        assert isinstance(stdout, str)\n        assert stdout != \"\"\n\n    def test_capture_version(self) -> None:\n        \"\"\"stdout should be captured when --version is passed.\"\"\"\n        stdout, _, _ = mypy.api.run([\"--version\"])\n        assert isinstance(stdout, str)\n        assert stdout != \"\"\n"
  },
  {
    "path": "mypy/test/testargs.py",
    "content": "\"\"\"Ensure the argparse parser and Options class are in sync.\n\nIn particular, verify that the argparse defaults are the same as the Options\ndefaults, and that argparse doesn't assign any new members to the Options\nobject it creates.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport argparse\nimport sys\nfrom typing import Any, cast\n\nfrom mypy.main import infer_python_executable, process_options\nfrom mypy.options import Options\nfrom mypy.test.helpers import Suite, assert_equal\n\n\nclass ArgSuite(Suite):\n    def test_coherence(self) -> None:\n        options = Options()\n        _, parsed_options = process_options([], require_targets=False)\n        # FIX: test this too. Requires changing working dir to avoid finding 'setup.cfg'\n        options.config_file = parsed_options.config_file\n        assert_equal(options.snapshot(), parsed_options.snapshot())\n\n    def test_executable_inference(self) -> None:\n        \"\"\"Test the --python-executable flag with --python-version\"\"\"\n        sys_ver_str = \"{ver.major}.{ver.minor}\".format(ver=sys.version_info)\n\n        base = [\"file.py\"]  # dummy file\n\n        # test inference given one (infer the other)\n        matching_version = base + [f\"--python-version={sys_ver_str}\"]\n        _, options = process_options(matching_version)\n        assert options.python_version == sys.version_info[:2]\n        assert options.python_executable == sys.executable\n\n        matching_version = base + [f\"--python-executable={sys.executable}\"]\n        _, options = process_options(matching_version)\n        assert options.python_version == sys.version_info[:2]\n        assert options.python_executable == sys.executable\n\n        # test inference given both\n        matching_version = base + [\n            f\"--python-version={sys_ver_str}\",\n            f\"--python-executable={sys.executable}\",\n        ]\n        _, options = process_options(matching_version)\n        assert options.python_version == sys.version_info[:2]\n        assert options.python_executable == sys.executable\n\n        # test that --no-site-packages will disable executable inference\n        matching_version = base + [f\"--python-version={sys_ver_str}\", \"--no-site-packages\"]\n        _, options = process_options(matching_version)\n        assert options.python_version == sys.version_info[:2]\n        assert options.python_executable is None\n\n        # Test setting python_version/executable from config file\n        special_opts = argparse.Namespace()\n        special_opts.python_executable = None\n        special_opts.python_version = None\n        special_opts.no_executable = None\n\n        # first test inferring executable from version\n        options = Options()\n        options.python_executable = cast(Any, None)\n        options.python_version = sys.version_info[:2]\n        infer_python_executable(options, special_opts)\n        assert options.python_version == sys.version_info[:2]\n        assert options.python_executable == sys.executable\n\n        # then test inferring version from executable\n        options = Options()\n        options.python_executable = sys.executable\n        infer_python_executable(options, special_opts)\n        assert options.python_version == sys.version_info[:2]\n        assert options.python_executable == sys.executable\n"
  },
  {
    "path": "mypy/test/testcheck.py",
    "content": "\"\"\"Type checker test cases\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport re\nimport sys\nimport sysconfig\nimport tempfile\nfrom pathlib import Path\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.modulefinder import BuildSource, FindModuleCache, SearchPaths\nfrom mypy.test.config import test_data_prefix, test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite, FileOperation, module_from_path\nfrom mypy.test.helpers import (\n    assert_module_equivalence,\n    assert_string_arrays_equal,\n    assert_target_equivalence,\n    check_test_output_files,\n    find_test_files,\n    normalize_error_messages,\n    parse_options,\n    perform_file_operations,\n    remove_typevar_ids,\n)\nfrom mypy.test.update_data import update_testcase_output\n\ntry:\n    if sys.version_info >= (3, 14) and bool(sysconfig.get_config_var(\"Py_GIL_DISABLED\")):\n        # lxml doesn't support free-threading yet\n        lxml = None\n    else:\n        import lxml  # type: ignore[import-untyped]\nexcept ImportError:\n    lxml = None\n\n\nimport pytest\n\n# List of files that contain test case descriptions.\n# Includes all check-* files with the .test extension in the test-data/unit directory\ntypecheck_files = find_test_files(pattern=\"check-*.test\")\n\n# Tests that use Python version specific features:\nif sys.version_info < (3, 11):\n    typecheck_files.remove(\"check-python311.test\")\nif sys.version_info < (3, 12):\n    typecheck_files.remove(\"check-python312.test\")\nif sys.version_info < (3, 13):\n    typecheck_files.remove(\"check-python313.test\")\nif sys.version_info < (3, 14):\n    typecheck_files.remove(\"check-python314.test\")\n\n\nclass TypeCheckSuite(DataSuite):\n    files = typecheck_files\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        if os.path.basename(testcase.file) == \"check-modules-case.test\":\n            with tempfile.NamedTemporaryFile(prefix=\"test\", dir=\".\") as temp_file:\n                temp_path = Path(temp_file.name)\n                if not temp_path.with_name(temp_path.name.upper()).exists():\n                    pytest.skip(\"File system is not case-insensitive\")\n        if lxml is None and os.path.basename(testcase.file) == \"check-reports.test\":\n            pytest.skip(\"Cannot import lxml. Is it installed?\")\n        incremental = (\n            \"incremental\" in testcase.name.lower()\n            or \"incremental\" in testcase.file\n            or \"serialize\" in testcase.file\n        )\n        if incremental:\n            # Incremental tests are run once with a cold cache, once with a warm cache.\n            # Expect success on first run, errors from testcase.output (if any) on second run.\n            num_steps = max([2] + list(testcase.output2.keys()))\n            # Check that there are no file changes beyond the last run (they would be ignored).\n            for dn, dirs, files in os.walk(os.curdir):\n                for file in files:\n                    m = re.search(r\"\\.([2-9])$\", file)\n                    if m and int(m.group(1)) > num_steps:\n                        raise ValueError(\n                            \"Output file {} exists though test case only has {} runs\".format(\n                                file, num_steps\n                            )\n                        )\n            steps = testcase.find_steps()\n            for step in range(1, num_steps + 1):\n                idx = step - 2\n                ops = steps[idx] if idx < len(steps) and idx >= 0 else []\n                self.run_case_once(testcase, ops, step)\n        else:\n            self.run_case_once(testcase)\n\n    def _sort_output_if_needed(self, testcase: DataDrivenTestCase, a: list[str]) -> None:\n        idx = testcase.output_inline_start\n        if not testcase.files or idx == len(testcase.output):\n            return\n\n        def _filename(_msg: str) -> str:\n            return _msg.partition(\":\")[0]\n\n        file_weights = {file: idx for idx, file in enumerate(_filename(msg) for msg in a)}\n        testcase.output[idx:] = sorted(\n            testcase.output[idx:], key=lambda msg: file_weights.get(_filename(msg), -1)\n        )\n\n    def run_case_once(\n        self,\n        testcase: DataDrivenTestCase,\n        operations: list[FileOperation] | None = None,\n        incremental_step: int = 0,\n    ) -> None:\n        if operations is None:\n            operations = []\n        original_program_text = \"\\n\".join(testcase.input)\n        module_data = self.parse_module(original_program_text, incremental_step)\n\n        # Unload already loaded plugins, they may be updated.\n        for file, _ in testcase.files:\n            module = module_from_path(file)\n            if module.endswith(\"_plugin\") and module in sys.modules:\n                del sys.modules[module]\n        if incremental_step == 0 or incremental_step == 1:\n            # In run 1, copy program text to program file.\n            for module_name, program_path, program_text in module_data:\n                if module_name == \"__main__\":\n                    with open(program_path, \"w\", encoding=\"utf8\") as f:\n                        f.write(program_text)\n                    break\n        elif incremental_step > 1:\n            # In runs 2+, copy *.[num] files to * files.\n            perform_file_operations(operations)\n\n        # Parse options after moving files (in case mypy.ini is being moved).\n        options = parse_options(original_program_text, testcase, incremental_step)\n        options.use_builtins_fixtures = True\n        options.show_traceback = True\n        options.native_parser = bool(os.environ.get(\"TEST_NATIVE_PARSER\"))\n        options.reveal_verbose_types = not testcase.name.endswith(\"_no_verbose_reveal\")\n\n        if options.num_workers:\n            options.fixed_format_cache = True\n            options.native_parser = True\n            if testcase.output_files:\n                raise pytest.skip(\"Reports are not supported in parallel mode\")\n            # Note: do not use this unless really needed!\n            if testcase.name.endswith(\"_no_parallel\"):\n                raise pytest.skip(\"Test not supported in parallel mode yet\")\n\n        if options.native_parser and testcase.name.endswith(\"_no_native_parse\"):\n            raise pytest.skip(\"Test not supported by native parser yet\")\n\n        # Enable some options automatically based on test file name.\n        if \"columns\" in testcase.file:\n            options.show_column_numbers = True\n        if \"errorcodes\" in testcase.file:\n            options.hide_error_codes = False\n        if \"abstract\" not in testcase.file:\n            options.allow_empty_bodies = not testcase.name.endswith(\"_no_empty\")\n\n        if incremental_step and options.incremental or options.num_workers > 0:\n            # Don't overwrite # flags: --no-incremental in incremental test cases\n            options.incremental = True\n        else:\n            options.incremental = False\n            # Don't waste time writing cache unless we are specifically looking for it\n            if not testcase.writescache:\n                options.cache_dir = os.devnull\n\n        sources = []\n        for module_name, program_path, program_text in module_data:\n            # Always set to None, so we're forced to reread the module in incremental mode\n            sources.append(\n                BuildSource(program_path, module_name, None if incremental_step else program_text)\n            )\n\n        plugin_dir = os.path.join(test_data_prefix, \"plugins\")\n\n        worker_env = None\n        if options.num_workers > 0:\n            worker_env = os.environ.copy()\n            # Make sure we are running tests with current worktree files, *not* with\n            # an installed version of mypy.\n            root_dir = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))\n            worker_env[\"PYTHONPATH\"] = os.pathsep.join([root_dir, plugin_dir])\n            worker_env[\"MYPY_TEST_PREFIX\"] = root_dir\n            worker_env[\"MYPY_ALT_LIB_PATH\"] = test_temp_dir\n\n        sys.path.insert(0, plugin_dir)\n        res = None\n        blocker = False\n        try:\n            res = build.build(\n                sources=sources, options=options, alt_lib_path=test_temp_dir, worker_env=worker_env\n            )\n            a = res.errors\n        except CompileError as e:\n            a = e.messages\n            blocker = True\n        finally:\n            assert sys.path[0] == plugin_dir\n            del sys.path[0]\n\n        if testcase.normalize_output:\n            a = normalize_error_messages(a)\n\n        # Make sure error messages match\n        if incremental_step < 2:\n            if incremental_step == 1:\n                msg = \"Unexpected type checker output in incremental, run 1 ({}, line {})\"\n            else:\n                assert incremental_step == 0\n                msg = \"Unexpected type checker output ({}, line {})\"\n            self._sort_output_if_needed(testcase, a)\n            output = testcase.output\n        else:\n            msg = (\n                f\"Unexpected type checker output in incremental, run {incremental_step}\"\n                + \" ({}, line {})\"\n            )\n            output = testcase.output2.get(incremental_step, [])\n\n        if output != a and testcase.config.getoption(\"--update-data\", False):\n            update_testcase_output(testcase, a, incremental_step=incremental_step)\n\n        if options.num_workers > 0:\n            # TypeVarIds are not stable in parallel checking, normalize.\n            a = remove_typevar_ids(a)\n            output = remove_typevar_ids(output)\n        assert_string_arrays_equal(output, a, msg.format(testcase.file, testcase.line))\n\n        if res:\n            if options.cache_dir != os.devnull:\n                self.verify_cache(module_data, res.manager, blocker, incremental_step)\n\n            name = \"targets\"\n            if incremental_step:\n                name += str(incremental_step + 1)\n            expected = testcase.expected_fine_grained_targets.get(incremental_step + 1)\n            actual = [\n                target\n                for module, target in res.manager.processed_targets\n                if module in testcase.test_modules\n            ]\n            # TODO: check targets in parallel mode (e.g. per SCC).\n            if options.num_workers == 0 and expected is not None:\n                assert_target_equivalence(name, expected, actual)\n            if incremental_step > 1:\n                suffix = \"\" if incremental_step == 2 else str(incremental_step - 1)\n                expected_rechecked = testcase.expected_rechecked_modules.get(incremental_step - 1)\n                if expected_rechecked is not None:\n                    assert_module_equivalence(\n                        \"rechecked\" + suffix, expected_rechecked, res.manager.rechecked_modules\n                    )\n                expected_stale = testcase.expected_stale_modules.get(incremental_step - 1)\n                if expected_stale is not None:\n                    assert_module_equivalence(\n                        \"stale\" + suffix, expected_stale, res.manager.stale_modules\n                    )\n            res.manager.metastore.close()\n\n        if testcase.output_files:\n            check_test_output_files(testcase, incremental_step, strip_prefix=\"tmp/\")\n\n    def verify_cache(\n        self,\n        module_data: list[tuple[str, str, str]],\n        manager: build.BuildManager,\n        blocker: bool,\n        step: int,\n    ) -> None:\n        if not blocker:\n            # There should be valid cache metadata for each module except\n            # in case of a blocking error in themselves or one of their\n            # dependencies.\n            modules = self.find_module_files(manager)\n            modules.update({module_name: path for module_name, path, text in module_data})\n            missing_paths = self.find_missing_cache_files(modules, manager)\n            if missing_paths:\n                raise AssertionError(f\"cache data missing for {missing_paths} on run {step}\")\n        assert os.path.isfile(os.path.join(manager.options.cache_dir, \".gitignore\"))\n        cachedir_tag = os.path.join(manager.options.cache_dir, \"CACHEDIR.TAG\")\n        assert os.path.isfile(cachedir_tag)\n        with open(cachedir_tag) as f:\n            assert f.read().startswith(\"Signature: 8a477f597d28d172789f06886806bc55\")\n\n    def find_module_files(self, manager: build.BuildManager) -> dict[str, str]:\n        return {id: module.path for id, module in manager.modules.items()}\n\n    def find_missing_cache_files(\n        self, modules: dict[str, str], manager: build.BuildManager\n    ) -> set[str]:\n        ignore_errors = True\n        missing = {}\n        for id, path in modules.items():\n            meta, _ = build.find_cache_meta(id, path, manager)\n            if not build.validate_meta(meta, id, path, ignore_errors, manager):\n                missing[id] = path\n        return set(missing.values())\n\n    def parse_module(\n        self, program_text: str, incremental_step: int = 0\n    ) -> list[tuple[str, str, str]]:\n        \"\"\"Return the module and program names for a test case.\n\n        Normally, the unit tests will parse the default ('__main__')\n        module and follow all the imports listed there. You can override\n        this behavior and instruct the tests to check multiple modules\n        by using a comment like this in the test case input:\n\n          # cmd: mypy -m foo.bar foo.baz\n\n        You can also use `# cmdN:` to have a different cmd for incremental\n        step N (2, 3, ...).\n\n        Return a list of tuples (module name, file name, program text).\n        \"\"\"\n        m = re.search(\"# cmd: mypy -m ([a-zA-Z0-9_. ]+)$\", program_text, flags=re.MULTILINE)\n        if incremental_step > 1:\n            alt_regex = f\"# cmd{incremental_step}: mypy -m ([a-zA-Z0-9_. ]+)$\"\n            alt_m = re.search(alt_regex, program_text, flags=re.MULTILINE)\n            if alt_m is not None:\n                # Optionally return a different command if in a later step\n                # of incremental mode, otherwise default to reusing the\n                # original cmd.\n                m = alt_m\n\n        if m:\n            # The test case wants to use a non-default main\n            # module. Look up the module and give it as the thing to\n            # analyze.\n            module_names = m.group(1)\n            out = []\n            search_paths = SearchPaths((test_temp_dir,), (), (), ())\n            cache = FindModuleCache(search_paths, fscache=None, options=None)\n            for module_name in module_names.split(\" \"):\n                path = cache.find_module(module_name)\n                assert isinstance(path, str), f\"Can't find ad hoc case file: {module_name}\"\n                with open(path, encoding=\"utf8\") as f:\n                    program_text = f.read()\n                out.append((module_name, path, program_text))\n            return out\n        else:\n            return [(\"__main__\", \"main\", program_text)]\n"
  },
  {
    "path": "mypy/test/testcmdline.py",
    "content": "\"\"\"Test cases for the command line.\n\nTo begin we test that \"mypy <directory>[/]\" always recurses down the\nwhole tree.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport re\nimport subprocess\nimport sys\nimport sysconfig\n\nfrom mypy.test.config import PREFIX, test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import (\n    assert_string_arrays_equal,\n    check_test_output_files,\n    normalize_error_messages,\n)\n\ntry:\n    if sys.version_info >= (3, 14) and bool(sysconfig.get_config_var(\"Py_GIL_DISABLED\")):\n        # lxml doesn't support free-threading yet\n        lxml = None\n    else:\n        import lxml  # type: ignore[import-untyped]\nexcept ImportError:\n    lxml = None\n\nimport pytest\n\n# Path to Python 3 interpreter\npython3_path = sys.executable\n\n# Files containing test case descriptions.\ncmdline_files = [\"cmdline.test\", \"cmdline.pyproject.test\", \"reports.test\", \"envvars.test\"]\n\n\nclass PythonCmdlineSuite(DataSuite):\n    files = cmdline_files\n    native_sep = True\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        if lxml is None and os.path.basename(testcase.file) == \"reports.test\":\n            pytest.skip(\"Cannot import lxml. Is it installed?\")\n        for step in [1] + sorted(testcase.output2):\n            test_python_cmdline(testcase, step)\n\n\ndef test_python_cmdline(testcase: DataDrivenTestCase, step: int) -> None:\n    assert testcase.old_cwd is not None, \"test was not properly set up\"\n    # Write the program to a file.\n    program = \"_program.py\"\n    program_path = os.path.join(test_temp_dir, program)\n    with open(program_path, \"w\", encoding=\"utf8\") as file:\n        for s in testcase.input:\n            file.write(f\"{s}\\n\")\n    args = parse_args(testcase.input[0])\n    custom_cwd = parse_cwd(testcase.input[1]) if len(testcase.input) > 1 else None\n    args.append(\"--show-traceback\")\n    if \"--error-summary\" not in args:\n        args.append(\"--no-error-summary\")\n    if \"--show-error-codes\" not in args:\n        args.append(\"--hide-error-codes\")\n    if \"--disallow-empty-bodies\" not in args:\n        args.append(\"--allow-empty-bodies\")\n    # Type check the program.\n    fixed = [python3_path, \"-m\", \"mypy\"]\n    env = os.environ.copy()\n    env.pop(\"COLUMNS\", None)\n    extra_path = os.path.join(os.path.abspath(test_temp_dir), \"pypath\")\n    env[\"PYTHONPATH\"] = PREFIX\n    if os.path.isdir(extra_path):\n        env[\"PYTHONPATH\"] += os.pathsep + extra_path\n    cwd = os.path.join(test_temp_dir, custom_cwd or \"\")\n    args = [arg.replace(\"$CWD\", os.path.abspath(cwd)) for arg in args]\n    process = subprocess.Popen(\n        fixed + args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=cwd, env=env\n    )\n    outb, errb = process.communicate()\n    result = process.returncode\n    # Split output into lines.\n    out = [s.rstrip(\"\\n\\r\") for s in str(outb, \"utf8\").splitlines()]\n    err = [s.rstrip(\"\\n\\r\") for s in str(errb, \"utf8\").splitlines()]\n\n    if \"PYCHARM_HOSTED\" in os.environ:\n        for pos, line in enumerate(err):\n            if line.startswith(\"pydev debugger: \"):\n                # Delete the attaching debugger message itself, plus the extra newline added.\n                del err[pos : pos + 2]\n                break\n\n    # Remove temp file.\n    os.remove(program_path)\n    # Compare actual output to expected.\n    if testcase.output_files:\n        # Ignore stdout, but we insist on empty stderr and zero status.\n        if err or result:\n            raise AssertionError(\n                \"Expected zero status and empty stderr%s, got %d and\\n%s\"\n                % (\" on step %d\" % step if testcase.output2 else \"\", result, \"\\n\".join(err + out))\n            )\n        check_test_output_files(testcase, step)\n    else:\n        if testcase.normalize_output:\n            out = normalize_error_messages(err + out)\n        obvious_result = 1 if out else 0\n        if obvious_result != result:\n            out.append(f\"== Return code: {result}\")\n        expected_out = testcase.output if step == 1 else testcase.output2[step]\n        # Strip \"tmp/\" out of the test so that # E: works...\n        expected_out = [s.replace(\"tmp\" + os.sep, \"\") for s in expected_out]\n        assert_string_arrays_equal(\n            expected_out,\n            out,\n            \"Invalid output ({}, line {}){}\".format(\n                testcase.file, testcase.line, \" on step %d\" % step if testcase.output2 else \"\"\n            ),\n        )\n\n\ndef parse_args(line: str) -> list[str]:\n    \"\"\"Parse the first line of the program for the command line.\n\n    This should have the form\n\n      # cmd: mypy <options>\n\n    For example:\n\n      # cmd: mypy pkg/\n    \"\"\"\n    m = re.match(\"# cmd: mypy (.*)$\", line)\n    if not m:\n        return []  # No args; mypy will spit out an error.\n    return m.group(1).split()\n\n\ndef parse_cwd(line: str) -> str | None:\n    \"\"\"Parse the second line of the program for the command line.\n\n    This should have the form\n\n      # cwd: <directory>\n\n    For example:\n\n      # cwd: main/subdir\n    \"\"\"\n    m = re.match(\"# cwd: (.*)$\", line)\n    return m.group(1) if m else None\n"
  },
  {
    "path": "mypy/test/testconstraints.py",
    "content": "from __future__ import annotations\n\nfrom mypy.constraints import SUBTYPE_OF, SUPERTYPE_OF, Constraint, infer_constraints\nfrom mypy.test.helpers import Suite\nfrom mypy.test.typefixture import TypeFixture\nfrom mypy.types import Instance, TupleType, UnpackType\n\n\nclass ConstraintsSuite(Suite):\n    def setUp(self) -> None:\n        self.fx = TypeFixture()\n\n    def test_no_type_variables(self) -> None:\n        assert not infer_constraints(self.fx.o, self.fx.o, SUBTYPE_OF)\n\n    def test_basic_type_variable(self) -> None:\n        fx = self.fx\n        for direction in [SUBTYPE_OF, SUPERTYPE_OF]:\n            assert infer_constraints(fx.gt, fx.ga, direction) == [\n                Constraint(type_var=fx.t, op=direction, target=fx.a)\n            ]\n\n    def test_basic_type_var_tuple_subtype(self) -> None:\n        fx = self.fx\n        assert infer_constraints(\n            Instance(fx.gvi, [UnpackType(fx.ts)]), Instance(fx.gvi, [fx.a, fx.b]), SUBTYPE_OF\n        ) == [\n            Constraint(type_var=fx.ts, op=SUBTYPE_OF, target=TupleType([fx.a, fx.b], fx.std_tuple))\n        ]\n\n    def test_basic_type_var_tuple(self) -> None:\n        fx = self.fx\n        assert set(\n            infer_constraints(\n                Instance(fx.gvi, [UnpackType(fx.ts)]), Instance(fx.gvi, [fx.a, fx.b]), SUPERTYPE_OF\n            )\n        ) == {\n            Constraint(\n                type_var=fx.ts, op=SUPERTYPE_OF, target=TupleType([fx.a, fx.b], fx.std_tuple)\n            ),\n            Constraint(\n                type_var=fx.ts, op=SUBTYPE_OF, target=TupleType([fx.a, fx.b], fx.std_tuple)\n            ),\n        }\n\n    def test_type_var_tuple_with_prefix_and_suffix(self) -> None:\n        fx = self.fx\n        assert set(\n            infer_constraints(\n                Instance(fx.gv2i, [fx.t, UnpackType(fx.ts), fx.s]),\n                Instance(fx.gv2i, [fx.a, fx.b, fx.c, fx.d]),\n                SUPERTYPE_OF,\n            )\n        ) == {\n            Constraint(type_var=fx.t, op=SUPERTYPE_OF, target=fx.a),\n            Constraint(\n                type_var=fx.ts, op=SUPERTYPE_OF, target=TupleType([fx.b, fx.c], fx.std_tuple)\n            ),\n            Constraint(\n                type_var=fx.ts, op=SUBTYPE_OF, target=TupleType([fx.b, fx.c], fx.std_tuple)\n            ),\n            Constraint(type_var=fx.s, op=SUPERTYPE_OF, target=fx.d),\n        }\n\n    def test_unpack_homogeneous_tuple(self) -> None:\n        fx = self.fx\n        assert set(\n            infer_constraints(\n                Instance(fx.gvi, [UnpackType(Instance(fx.std_tuplei, [fx.t]))]),\n                Instance(fx.gvi, [fx.a, fx.b]),\n                SUPERTYPE_OF,\n            )\n        ) == {\n            Constraint(type_var=fx.t, op=SUPERTYPE_OF, target=fx.a),\n            Constraint(type_var=fx.t, op=SUBTYPE_OF, target=fx.a),\n            Constraint(type_var=fx.t, op=SUPERTYPE_OF, target=fx.b),\n            Constraint(type_var=fx.t, op=SUBTYPE_OF, target=fx.b),\n        }\n\n    def test_unpack_homogeneous_tuple_with_prefix_and_suffix(self) -> None:\n        fx = self.fx\n        assert set(\n            infer_constraints(\n                Instance(fx.gv2i, [fx.t, UnpackType(Instance(fx.std_tuplei, [fx.s])), fx.u]),\n                Instance(fx.gv2i, [fx.a, fx.b, fx.c, fx.d]),\n                SUPERTYPE_OF,\n            )\n        ) == {\n            Constraint(type_var=fx.t, op=SUPERTYPE_OF, target=fx.a),\n            Constraint(type_var=fx.s, op=SUPERTYPE_OF, target=fx.b),\n            Constraint(type_var=fx.s, op=SUBTYPE_OF, target=fx.b),\n            Constraint(type_var=fx.s, op=SUPERTYPE_OF, target=fx.c),\n            Constraint(type_var=fx.s, op=SUBTYPE_OF, target=fx.c),\n            Constraint(type_var=fx.u, op=SUPERTYPE_OF, target=fx.d),\n        }\n\n    def test_unpack_with_prefix_and_suffix(self) -> None:\n        fx = self.fx\n        assert set(\n            infer_constraints(\n                Instance(fx.gv2i, [fx.u, fx.t, fx.s, fx.u]),\n                Instance(fx.gv2i, [fx.a, fx.b, fx.c, fx.d]),\n                SUPERTYPE_OF,\n            )\n        ) == {\n            Constraint(type_var=fx.u, op=SUPERTYPE_OF, target=fx.a),\n            Constraint(type_var=fx.t, op=SUPERTYPE_OF, target=fx.b),\n            Constraint(type_var=fx.t, op=SUBTYPE_OF, target=fx.b),\n            Constraint(type_var=fx.s, op=SUPERTYPE_OF, target=fx.c),\n            Constraint(type_var=fx.s, op=SUBTYPE_OF, target=fx.c),\n            Constraint(type_var=fx.u, op=SUPERTYPE_OF, target=fx.d),\n        }\n\n    def test_unpack_tuple_length_non_match(self) -> None:\n        fx = self.fx\n        assert set(\n            infer_constraints(\n                Instance(fx.gv2i, [fx.u, fx.t, fx.s, fx.u]),\n                Instance(fx.gv2i, [fx.a, fx.b, fx.d]),\n                SUPERTYPE_OF,\n            )\n            # We still get constraints on the prefix/suffix in this case.\n        ) == {\n            Constraint(type_var=fx.u, op=SUPERTYPE_OF, target=fx.a),\n            Constraint(type_var=fx.u, op=SUPERTYPE_OF, target=fx.d),\n        }\n\n    def test_var_length_tuple_with_fixed_length_tuple(self) -> None:\n        fx = self.fx\n        assert not infer_constraints(\n            TupleType([fx.t, fx.s], fallback=Instance(fx.std_tuplei, [fx.o])),\n            Instance(fx.std_tuplei, [fx.a]),\n            SUPERTYPE_OF,\n        )\n"
  },
  {
    "path": "mypy/test/testdaemon.py",
    "content": "\"\"\"End-to-end test cases for the daemon (dmypy).\n\nThese are special because they run multiple shell commands.\n\nThis also includes some unit tests.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\n\nfrom mypy.dmypy_server import filter_out_missing_top_level_packages\nfrom mypy.fscache import FileSystemCache\nfrom mypy.modulefinder import SearchPaths\nfrom mypy.test.config import PREFIX, test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, normalize_error_messages\n\n# Files containing test cases descriptions.\ndaemon_files = [\"daemon.test\"]\n\n\nclass DaemonSuite(DataSuite):\n    files = daemon_files\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        try:\n            test_daemon(testcase)\n        finally:\n            # Kill the daemon if it's still running.\n            run_cmd(\"dmypy kill\")\n\n\ndef test_daemon(testcase: DataDrivenTestCase) -> None:\n    assert testcase.old_cwd is not None, \"test was not properly set up\"\n    for i, step in enumerate(parse_script(testcase.input)):\n        cmd = step[0]\n        expected_lines = step[1:]\n        assert cmd.startswith(\"$\")\n        cmd = cmd[1:].strip()\n        cmd = cmd.replace(\"{python}\", sys.executable)\n        sts, output = run_cmd(cmd)\n        output_lines = output.splitlines()\n        output_lines = normalize_error_messages(output_lines)\n        if sts:\n            output_lines.append(\"== Return code: %d\" % sts)\n        assert_string_arrays_equal(\n            expected_lines,\n            output_lines,\n            \"Command %d (%s) did not give expected output\" % (i + 1, cmd),\n        )\n\n\ndef parse_script(input: list[str]) -> list[list[str]]:\n    \"\"\"Parse testcase.input into steps.\n\n    Each command starts with a line starting with '$'.\n    The first line (less '$') is sent to the shell.\n    The remaining lines are expected output.\n    \"\"\"\n    steps = []\n    step: list[str] = []\n    for line in input:\n        if line.startswith(\"$\"):\n            if step:\n                assert step[0].startswith(\"$\")\n                steps.append(step)\n                step = []\n        step.append(line)\n    if step:\n        steps.append(step)\n    return steps\n\n\ndef run_cmd(input: str) -> tuple[int, str]:\n    if input[1:].startswith(\"mypy run --\") and \"--show-error-codes\" not in input:\n        input += \" --hide-error-codes\"\n    if input.startswith(\"dmypy \"):\n        input = sys.executable + \" -m mypy.\" + input\n    if input.startswith(\"mypy \"):\n        input = sys.executable + \" -m\" + input\n    env = os.environ.copy()\n    env[\"PYTHONPATH\"] = PREFIX\n    try:\n        output = subprocess.check_output(\n            input, shell=True, stderr=subprocess.STDOUT, text=True, cwd=test_temp_dir, env=env\n        )\n        return 0, output\n    except subprocess.CalledProcessError as err:\n        return err.returncode, err.output\n\n\nclass DaemonUtilitySuite(unittest.TestCase):\n    \"\"\"Unit tests for helpers\"\"\"\n\n    def test_filter_out_missing_top_level_packages(self) -> None:\n        with tempfile.TemporaryDirectory() as td:\n            self.make_file(td, \"base/a/\")\n            self.make_file(td, \"base/b.py\")\n            self.make_file(td, \"base/c.pyi\")\n            self.make_file(td, \"base/missing.txt\")\n            self.make_file(td, \"typeshed/d.pyi\")\n            self.make_file(td, \"typeshed/@python2/e\")  # outdated\n            self.make_file(td, \"pkg1/f-stubs\")\n            self.make_file(td, \"pkg2/g-python2-stubs\")  # outdated\n            self.make_file(td, \"mpath/sub/long_name/\")\n\n            def makepath(p: str) -> str:\n                return os.path.join(td, p)\n\n            search = SearchPaths(\n                python_path=(makepath(\"base\"),),\n                mypy_path=(makepath(\"mpath/sub\"),),\n                package_path=(makepath(\"pkg1\"), makepath(\"pkg2\")),\n                typeshed_path=(makepath(\"typeshed\"),),\n            )\n            fscache = FileSystemCache()\n            res = filter_out_missing_top_level_packages(\n                {\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"long_name\", \"ff\", \"missing\"}, search, fscache\n            )\n            assert res == {\"a\", \"b\", \"c\", \"d\", \"f\", \"long_name\"}\n\n    def make_file(self, base: str, path: str) -> None:\n        fullpath = os.path.join(base, path)\n        os.makedirs(os.path.dirname(fullpath), exist_ok=True)\n        if not path.endswith(\"/\"):\n            with open(fullpath, \"w\") as f:\n                f.write(\"# test file\")\n"
  },
  {
    "path": "mypy/test/testdeps.py",
    "content": "\"\"\"Test cases for generating node-level dependencies (for fine-grained incremental checking)\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport sys\nfrom collections import defaultdict\n\nimport pytest\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.modulefinder import BuildSource\nfrom mypy.nodes import Expression, MypyFile\nfrom mypy.options import Options\nfrom mypy.server.deps import get_dependencies\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, find_test_files, parse_options\nfrom mypy.types import Type\nfrom mypy.typestate import type_state\n\n# Only dependencies in these modules are dumped\ndumped_modules = [\"__main__\", \"pkg\", \"pkg.mod\"]\n\n\nclass GetDependenciesSuite(DataSuite):\n    files = find_test_files(pattern=\"deps*.test\")\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        src = \"\\n\".join(testcase.input)\n        dump_all = \"# __dump_all__\" in src\n        options = parse_options(src, testcase, incremental_step=1)\n        if options.python_version > sys.version_info:\n            pytest.skip(\"Test case requires a newer Python version\")\n        options.use_builtins_fixtures = True\n        options.show_traceback = True\n        options.cache_dir = os.devnull\n        options.export_types = True\n        options.preserve_asts = True\n        options.allow_empty_bodies = True\n        messages, files, type_map = self.build(src, options)\n        a = messages\n        if files is None or type_map is None:\n            if not a:\n                a = [\"Unknown compile error (likely syntax error in test case or fixture)\"]\n        else:\n            deps: defaultdict[str, set[str]] = defaultdict(set)\n            for module, file in files.items():\n                if (module in dumped_modules or dump_all) and (module in testcase.test_modules):\n                    new_deps = get_dependencies(file, type_map, options.python_version, options)\n                    for source in new_deps:\n                        deps[source].update(new_deps[source])\n\n            type_state.add_all_protocol_deps(deps)\n\n            for source, targets in sorted(deps.items()):\n                if source.startswith((\"<enum\", \"<typing\", \"<mypy\", \"<_typeshed.\")):\n                    # Remove noise.\n                    continue\n                line = f\"{source} -> {', '.join(sorted(targets))}\"\n                # Clean up output a bit\n                line = line.replace(\"__main__\", \"m\")\n                a.append(line)\n\n        assert_string_arrays_equal(\n            testcase.output, a, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n        )\n\n    def build(\n        self, source: str, options: Options\n    ) -> tuple[list[str], dict[str, MypyFile] | None, dict[Expression, Type] | None]:\n        try:\n            result = build.build(\n                sources=[BuildSource(\"main\", None, source)],\n                options=options,\n                alt_lib_path=test_temp_dir,\n            )\n        except CompileError as e:\n            # TODO: Should perhaps not return None here.\n            return e.messages, None, None\n        return result.errors, result.files, result.types\n"
  },
  {
    "path": "mypy/test/testdiff.py",
    "content": "\"\"\"Test cases for AST diff (used for fine-grained incremental checking)\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport sys\n\nimport pytest\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.modulefinder import BuildSource\nfrom mypy.nodes import MypyFile\nfrom mypy.options import Options\nfrom mypy.server.astdiff import compare_symbol_table_snapshots, snapshot_symbol_table\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, parse_options\n\n\nclass ASTDiffSuite(DataSuite):\n    files = [\"diff.test\"]\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        first_src = \"\\n\".join(testcase.input)\n        files_dict = dict(testcase.files)\n        second_src = files_dict[\"tmp/next.py\"]\n        options = parse_options(first_src, testcase, 1)\n        if options.python_version > sys.version_info:\n            pytest.skip(\"Test case requires a newer Python version\")\n\n        messages1, files1 = self.build(first_src, options)\n        messages2, files2 = self.build(second_src, options)\n\n        a = []\n        if messages1:\n            a.extend(messages1)\n        if messages2:\n            a.append(\"== next ==\")\n            a.extend(messages2)\n\n        assert (\n            files1 is not None and files2 is not None\n        ), \"cases where CompileError occurred should not be run\"\n        prefix = \"__main__\"\n        snapshot1 = snapshot_symbol_table(prefix, files1[\"__main__\"].names)\n        snapshot2 = snapshot_symbol_table(prefix, files2[\"__main__\"].names)\n        diff = compare_symbol_table_snapshots(prefix, snapshot1, snapshot2)\n        for trigger in sorted(diff):\n            a.append(trigger)\n\n        assert_string_arrays_equal(\n            testcase.output, a, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n        )\n\n    def build(self, source: str, options: Options) -> tuple[list[str], dict[str, MypyFile] | None]:\n        options.use_builtins_fixtures = True\n        options.show_traceback = True\n        options.cache_dir = os.devnull\n        options.allow_empty_bodies = True\n        try:\n            result = build.build(\n                sources=[BuildSource(\"main\", None, source)],\n                options=options,\n                alt_lib_path=test_temp_dir,\n            )\n        except CompileError as e:\n            # TODO: Is it okay to return None?\n            return e.messages, None\n        return result.errors, result.files\n"
  },
  {
    "path": "mypy/test/testerrorstream.py",
    "content": "\"\"\"Tests for mypy incremental error output.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.modulefinder import BuildSource\nfrom mypy.options import Options\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal\n\n\nclass ErrorStreamSuite(DataSuite):\n    required_out_section = True\n    base_path = \".\"\n    files = [\"errorstream.test\"]\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_error_stream(testcase)\n\n\ndef test_error_stream(testcase: DataDrivenTestCase) -> None:\n    \"\"\"Perform a single error streaming test case.\n\n    The argument contains the description of the test case.\n    \"\"\"\n    options = Options()\n    options.show_traceback = True\n    options.hide_error_codes = True\n\n    logged_messages: list[str] = []\n\n    def flush_errors(filename: str | None, msgs: list[str], serious: bool) -> None:\n        if msgs:\n            logged_messages.append(\"==== Errors flushed ====\")\n            logged_messages.extend(msgs)\n\n    sources = [BuildSource(\"main\", \"__main__\", \"\\n\".join(testcase.input))]\n    try:\n        build.build(sources=sources, options=options, flush_errors=flush_errors)\n    except CompileError as e:\n        assert e.messages == []\n\n    assert_string_arrays_equal(\n        testcase.output, logged_messages, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n    )\n"
  },
  {
    "path": "mypy/test/testexportjson.py",
    "content": "\"\"\"Test cases for the mypy cache JSON export tool.\"\"\"\n\nfrom __future__ import annotations\n\nimport json\nimport os\nimport re\nimport sys\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.exportjson import convert_binary_cache_meta_to_json, convert_binary_cache_to_json\nfrom mypy.modulefinder import BuildSource\nfrom mypy.options import Options\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal\n\n\nclass TypeExportSuite(DataSuite):\n    required_out_section = True\n    files = [\"exportjson.test\"]\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        error = False\n        src = \"\\n\".join(testcase.input)\n        is_meta = testcase.name.endswith(\"_meta\")\n        try:\n            options = Options()\n            options.use_builtins_fixtures = True\n            options.show_traceback = True\n            options.allow_empty_bodies = True\n            options.fixed_format_cache = True\n            options.sqlite_cache = False\n            fnam = os.path.join(self.base_path, \"main.py\")\n            with open(fnam, \"w\") as f:\n                f.write(src)\n            result = build.build(\n                sources=[BuildSource(fnam, \"main\")], options=options, alt_lib_path=test_temp_dir\n            )\n            a = result.errors\n            error = bool(a)\n\n            major, minor = sys.version_info[:2]\n            cache_dir = os.path.join(\".mypy_cache\", f\"{major}.{minor}\")\n\n            for module in result.files:\n                if module in (\n                    \"builtins\",\n                    \"typing\",\n                    \"_typeshed\",\n                    \"__future__\",\n                    \"typing_extensions\",\n                    \"sys\",\n                    \"collections\",\n                ):\n                    continue\n                fnam = os.path.join(cache_dir, f\"{module}.data.ff\")\n                if not is_meta:\n                    with open(fnam, \"rb\") as f:\n                        json_data = convert_binary_cache_to_json(f.read(), implicit_names=False)\n                else:\n                    meta_fnam = os.path.join(cache_dir, f\"{module}.meta.ff\")\n                    with open(meta_fnam, \"rb\") as f:\n                        json_data = convert_binary_cache_meta_to_json(f.read(), fnam)\n                for line in json.dumps(json_data, indent=4).splitlines():\n                    if '\"path\": ' in line:\n                        # The source file path is unpredictable, so filter it out\n                        line = re.sub(r'\"[^\"]+\\.pyi?\"', \"...\", line)\n                    if is_meta:\n                        if '\"version_id\"' in line:\n                            line = re.sub(r'\"[0-9][^\"]+\"', \"...\", line)\n                        if '\"mtime\"' in line or '\"data_mtime\"' in line:\n                            line = re.sub(r\": [0-9]+\", \": ...\", line)\n                        if '\"platform\"' in line:\n                            line = re.sub(': \"[^\"]+\"', \": ...\", line)\n                        if '\"hash\"' not in line:\n                            # Some hashes are unpredictable so filter them out\n                            line = re.sub(r'\"[a-f0-9]{40}\"', '\"<hash>\"', line)\n                    assert \"ERROR\" not in line, line\n                    a.append(line)\n        except CompileError as e:\n            a = e.messages\n            error = True\n        if error or \"\\n\".join(testcase.output).strip() != \"<not checked>\":\n            if is_meta and sys.platform == \"win32\":\n                out = filter_platform_specific(testcase.output)\n                a = filter_platform_specific(a)\n            else:\n                out = testcase.output\n            assert_string_arrays_equal(\n                out, a, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n            )\n\n\ndef filter_platform_specific(lines: list[str]) -> list[str]:\n    return [l for l in lines if '\"size\":' not in l and '\"hash\":' not in l]\n"
  },
  {
    "path": "mypy/test/testfinegrained.py",
    "content": "\"\"\"Test cases for fine-grained incremental checking.\n\nEach test cases runs a batch build followed by one or more fine-grained\nincremental steps. We verify that each step produces the expected output.\n\nSee the comment at the top of test-data/unit/fine-grained.test for more\ninformation.\n\nN.B.: Unlike most of the other test suites, testfinegrained does not\nrely on an alt_lib_path for finding source files. This means that they\ncan test interactions with the lib_path that is built implicitly based\non specified sources.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport re\nimport sys\nimport unittest\nfrom typing import Any\n\nimport pytest\n\nfrom mypy import build\nfrom mypy.config_parser import parse_config_file\nfrom mypy.dmypy_server import Server\nfrom mypy.dmypy_util import DEFAULT_STATUS_FILE\nfrom mypy.errors import CompileError\nfrom mypy.find_sources import create_source_list\nfrom mypy.modulefinder import BuildSource\nfrom mypy.options import Options\nfrom mypy.server.mergecheck import check_consistency\nfrom mypy.server.update import sort_messages_preserving_file_order\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite, DeleteFile, UpdateFile\nfrom mypy.test.helpers import (\n    assert_module_equivalence,\n    assert_string_arrays_equal,\n    assert_target_equivalence,\n    find_test_files,\n    parse_options,\n    perform_file_operations,\n)\n\n# Set to True to perform (somewhat expensive) checks for duplicate AST nodes after merge\nCHECK_CONSISTENCY = False\n\n\nclass FineGrainedSuite(DataSuite):\n    files = find_test_files(\n        pattern=\"fine-grained*.test\", exclude=[\"fine-grained-cache-incremental.test\"]\n    )\n\n    # Whether to use the fine-grained cache in the testing. This is overridden\n    # by a trivial subclass to produce a suite that uses the cache.\n    use_cache = False\n\n    def should_skip(self, testcase: DataDrivenTestCase) -> bool:\n        # Decide whether to skip the test. This could have been structured\n        # as a filter() classmethod also, but we want the tests reported\n        # as skipped, not just elided.\n        if self.use_cache:\n            if testcase.only_when == \"-only_when_nocache\":\n                return True\n            # TODO: In caching mode we currently don't well support\n            # starting from cached states with errors in them.\n            if testcase.output and testcase.output[0] != \"==\":\n                return True\n        else:\n            if testcase.only_when == \"-only_when_cache\":\n                return True\n        return False\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        if self.should_skip(testcase):\n            pytest.skip()\n\n        main_src = \"\\n\".join(testcase.input)\n        main_path = os.path.join(test_temp_dir, \"main\")\n        with open(main_path, \"w\", encoding=\"utf8\") as f:\n            f.write(main_src)\n\n        options = self.get_options(main_src, testcase, build_cache=False)\n        if options.python_version > sys.version_info:\n            pytest.skip(\"Test case requires a newer Python version\")\n\n        build_options = self.get_options(main_src, testcase, build_cache=True)\n        server = Server(options, DEFAULT_STATUS_FILE)\n\n        num_regular_incremental_steps = self.get_build_steps(main_src)\n        step = 1\n        sources = self.parse_sources(main_src, step, options)\n        if step <= num_regular_incremental_steps:\n            messages = self.build(build_options, sources)\n        else:\n            messages = self.run_check(server, sources)\n\n        a = []\n        if messages:\n            a.extend(normalize_messages(messages))\n\n        assert testcase.tmpdir is not None\n        a.extend(self.maybe_suggest(step, server, main_src, testcase.tmpdir))\n        a.extend(self.maybe_inspect(step, server, main_src))\n\n        if server.fine_grained_manager:\n            if CHECK_CONSISTENCY:\n                check_consistency(server.fine_grained_manager)\n\n        steps = testcase.find_steps()\n        all_triggered = []\n\n        for operations in steps:\n            step += 1\n            output, triggered = self.perform_step(\n                operations,\n                server,\n                options,\n                build_options,\n                testcase,\n                main_src,\n                step,\n                num_regular_incremental_steps,\n            )\n            a.append(\"==\")\n            a.extend(output)\n            all_triggered.extend(triggered)\n\n        # Normalize paths in test output (for Windows).\n        a = [line.replace(\"\\\\\", \"/\") for line in a]\n\n        assert_string_arrays_equal(\n            testcase.output, a, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n        )\n\n        if testcase.triggered:\n            assert_string_arrays_equal(\n                testcase.triggered,\n                self.format_triggered(all_triggered),\n                f\"Invalid active triggers ({testcase.file}, line {testcase.line})\",\n            )\n\n    def get_options(self, source: str, testcase: DataDrivenTestCase, build_cache: bool) -> Options:\n        # This handles things like '# flags: --foo'.\n        options = parse_options(source, testcase, incremental_step=1)\n        options.incremental = True\n        options.use_builtins_fixtures = True\n        options.show_traceback = True\n        options.error_summary = False\n        options.fine_grained_incremental = not build_cache\n        options.use_fine_grained_cache = self.use_cache and not build_cache\n        options.cache_fine_grained = self.use_cache\n        options.local_partial_types = True\n        options.export_types = \"inspect\" in testcase.file\n        # Treat empty bodies safely for these test cases.\n        options.allow_empty_bodies = not testcase.name.endswith(\"_no_empty\")\n        options.reveal_verbose_types = True\n        if re.search(\"flags:.*--follow-imports\", source) is None:\n            # Override the default for follow_imports\n            options.follow_imports = \"error\"\n\n        for name, _ in testcase.files:\n            if \"mypy.ini\" in name or \"pyproject.toml\" in name:\n                parse_config_file(options, lambda: None, name)\n                break\n\n        return options\n\n    def run_check(self, server: Server, sources: list[BuildSource]) -> list[str]:\n        response = server.check(sources, export_types=False, is_tty=False, terminal_width=-1)\n        out = response[\"out\"] or response[\"err\"]\n        assert isinstance(out, str)\n        return out.splitlines()\n\n    def build(self, options: Options, sources: list[BuildSource]) -> list[str]:\n        try:\n            result = build.build(sources=sources, options=options)\n        except CompileError as e:\n            return e.messages\n        return result.errors\n\n    def format_triggered(self, triggered: list[list[str]]) -> list[str]:\n        result = []\n        for n, triggers in enumerate(triggered):\n            filtered = [trigger for trigger in triggers if not trigger.endswith(\"__>\")]\n            filtered = sorted(filtered)\n            result.append((\"%d: %s\" % (n + 2, \", \".join(filtered))).strip())\n        return result\n\n    def get_build_steps(self, program_text: str) -> int:\n        \"\"\"Get the number of regular incremental steps to run, from the test source\"\"\"\n        if not self.use_cache:\n            return 0\n        m = re.search(\"# num_build_steps: ([0-9]+)$\", program_text, flags=re.MULTILINE)\n        if m is not None:\n            return int(m.group(1))\n        return 1\n\n    def perform_step(\n        self,\n        operations: list[UpdateFile | DeleteFile],\n        server: Server,\n        options: Options,\n        build_options: Options,\n        testcase: DataDrivenTestCase,\n        main_src: str,\n        step: int,\n        num_regular_incremental_steps: int,\n    ) -> tuple[list[str], list[list[str]]]:\n        \"\"\"Perform one fine-grained incremental build step (after some file updates/deletions).\n\n        Return (mypy output, triggered targets).\n        \"\"\"\n        perform_file_operations(operations)\n        sources = self.parse_sources(main_src, step, options)\n\n        if step <= num_regular_incremental_steps:\n            new_messages = self.build(build_options, sources)\n        else:\n            new_messages = self.run_check(server, sources)\n\n        updated: list[str] = []\n        changed: list[str] = []\n        targets: list[str] = []\n        triggered = []\n        if server.fine_grained_manager:\n            if CHECK_CONSISTENCY:\n                check_consistency(server.fine_grained_manager)\n            triggered.append(server.fine_grained_manager.triggered)\n\n            updated = server.fine_grained_manager.updated_modules\n            changed = [mod for mod, file in server.fine_grained_manager.changed_modules]\n            targets = server.fine_grained_manager.processed_targets\n\n        expected_stale = testcase.expected_stale_modules.get(step - 1)\n        if expected_stale is not None:\n            assert_module_equivalence(\"stale\" + str(step - 1), expected_stale, changed)\n\n        expected_rechecked = testcase.expected_rechecked_modules.get(step - 1)\n        if expected_rechecked is not None:\n            assert_module_equivalence(\"rechecked\" + str(step - 1), expected_rechecked, updated)\n\n        expected = testcase.expected_fine_grained_targets.get(step)\n        if expected:\n            assert_target_equivalence(\"targets\" + str(step), expected, targets)\n\n        new_messages = normalize_messages(new_messages)\n\n        a = new_messages\n        assert testcase.tmpdir is not None\n        a.extend(self.maybe_suggest(step, server, main_src, testcase.tmpdir))\n        a.extend(self.maybe_inspect(step, server, main_src))\n\n        return a, triggered\n\n    def parse_sources(\n        self, program_text: str, incremental_step: int, options: Options\n    ) -> list[BuildSource]:\n        \"\"\"Return target BuildSources for a test case.\n\n        Normally, the unit tests will check all files included in the test\n        case. This differs from how testcheck works by default, as dmypy\n        doesn't currently support following imports.\n\n        You can override this behavior and instruct the tests to check\n        multiple modules by using a comment like this in the test case\n        input:\n\n          # cmd: main a.py\n\n        You can also use `# cmdN:` to have a different cmd for incremental\n        step N (2, 3, ...).\n\n        \"\"\"\n        m = re.search(\"# cmd: mypy ([a-zA-Z0-9_./ ]+)$\", program_text, flags=re.MULTILINE)\n        regex = f\"# cmd{incremental_step}: mypy ([a-zA-Z0-9_./ ]+)$\"\n        alt_m = re.search(regex, program_text, flags=re.MULTILINE)\n        if alt_m is not None:\n            # Optionally return a different command if in a later step\n            # of incremental mode, otherwise default to reusing the\n            # original cmd.\n            m = alt_m\n\n        if m:\n            # The test case wants to use a non-default set of files.\n            paths = [os.path.join(test_temp_dir, path) for path in m.group(1).strip().split()]\n            return create_source_list(paths, options)\n        else:\n            base = BuildSource(os.path.join(test_temp_dir, \"main\"), \"__main__\", None)\n            # Use expand_dir instead of create_source_list to avoid complaints\n            # when there aren't any .py files in an increment\n            return [base] + create_source_list([test_temp_dir], options, allow_empty_dir=True)\n\n    def maybe_suggest(self, step: int, server: Server, src: str, tmp_dir: str) -> list[str]:\n        output: list[str] = []\n        targets = self.get_suggest(src, step)\n        for flags, target in targets:\n            json = \"--json\" in flags\n            callsites = \"--callsites\" in flags\n            no_any = \"--no-any\" in flags\n            no_errors = \"--no-errors\" in flags\n            m = re.match(\"--flex-any=([0-9.]+)\", flags)\n            flex_any = float(m.group(1)) if m else None\n            m = re.match(r\"--use-fixme=(\\w+)\", flags)\n            use_fixme = m.group(1) if m else None\n            m = re.match(\"--max-guesses=([0-9]+)\", flags)\n            max_guesses = int(m.group(1)) if m else None\n            res: dict[str, Any] = server.cmd_suggest(\n                target.strip(),\n                json=json,\n                no_any=no_any,\n                no_errors=no_errors,\n                flex_any=flex_any,\n                use_fixme=use_fixme,\n                callsites=callsites,\n                max_guesses=max_guesses,\n            )\n            val = res[\"error\"] if \"error\" in res else res[\"out\"] + res[\"err\"]\n            if json:\n                # JSON contains already escaped \\ on Windows, so requires a bit of care.\n                val = val.replace(\"\\\\\\\\\", \"\\\\\")\n                val = val.replace(os.path.realpath(tmp_dir) + os.path.sep, \"\")\n                val = val.replace(os.path.abspath(tmp_dir) + os.path.sep, \"\")\n            output.extend(val.strip().split(\"\\n\"))\n        return normalize_messages(output)\n\n    def maybe_inspect(self, step: int, server: Server, src: str) -> list[str]:\n        output: list[str] = []\n        targets = self.get_inspect(src, step)\n        for flags, location in targets:\n            m = re.match(r\"--show=(\\w+)\", flags)\n            show = m.group(1) if m else \"type\"\n            verbosity = 0\n            if \"-v\" in flags:\n                verbosity = 1\n            if \"-vv\" in flags:\n                verbosity = 2\n            m = re.match(r\"--limit=([0-9]+)\", flags)\n            limit = int(m.group(1)) if m else 0\n            include_span = \"--include-span\" in flags\n            include_kind = \"--include-kind\" in flags\n            include_object_attrs = \"--include-object-attrs\" in flags\n            union_attrs = \"--union-attrs\" in flags\n            force_reload = \"--force-reload\" in flags\n            res: dict[str, Any] = server.cmd_inspect(\n                show,\n                location,\n                verbosity=verbosity,\n                limit=limit,\n                include_span=include_span,\n                include_kind=include_kind,\n                include_object_attrs=include_object_attrs,\n                union_attrs=union_attrs,\n                force_reload=force_reload,\n            )\n            val = res[\"error\"] if \"error\" in res else res[\"out\"] + res[\"err\"]\n            output.extend(val.strip().split(\"\\n\"))\n        return output\n\n    def get_suggest(self, program_text: str, incremental_step: int) -> list[tuple[str, str]]:\n        step_bit = \"1?\" if incremental_step == 1 else str(incremental_step)\n        regex = f\"# suggest{step_bit}: (--[a-zA-Z0-9_\\\\-./=?^ ]+ )*([a-zA-Z0-9_.:/?^ ]+)$\"\n        m = re.findall(regex, program_text, flags=re.MULTILINE)\n        return m\n\n    def get_inspect(self, program_text: str, incremental_step: int) -> list[tuple[str, str]]:\n        step_bit = \"1?\" if incremental_step == 1 else str(incremental_step)\n        regex = f\"# inspect{step_bit}: (--[a-zA-Z0-9_\\\\-=?^ ]+ )*([a-zA-Z0-9_.:/?^ ]+)$\"\n        m = re.findall(regex, program_text, flags=re.MULTILINE)\n        return m\n\n\ndef normalize_messages(messages: list[str]) -> list[str]:\n    return [re.sub(\"^tmp\" + re.escape(os.sep), \"\", message) for message in messages]\n\n\nclass TestMessageSorting(unittest.TestCase):\n    def test_simple_sorting(self) -> None:\n        msgs = ['x.py:1: error: \"int\" not callable', 'foo/y.py:123: note: \"X\" not defined']\n        old_msgs = ['foo/y.py:12: note: \"Y\" not defined', 'x.py:8: error: \"str\" not callable']\n        assert sort_messages_preserving_file_order(msgs, old_msgs) == list(reversed(msgs))\n        assert sort_messages_preserving_file_order(list(reversed(msgs)), old_msgs) == list(\n            reversed(msgs)\n        )\n\n    def test_long_form_sorting(self) -> None:\n        # Multi-line errors should be sorted together and not split.\n        msg1 = [\n            'x.py:1: error: \"int\" not callable',\n            \"and message continues (x: y)\",\n            \"    1()\",\n            \"    ^~~\",\n        ]\n        msg2 = [\n            'foo/y.py: In function \"f\":',\n            'foo/y.py:123: note: \"X\" not defined',\n            \"and again message continues\",\n        ]\n        old_msgs = ['foo/y.py:12: note: \"Y\" not defined', 'x.py:8: error: \"str\" not callable']\n        assert sort_messages_preserving_file_order(msg1 + msg2, old_msgs) == msg2 + msg1\n        assert sort_messages_preserving_file_order(msg2 + msg1, old_msgs) == msg2 + msg1\n\n    def test_mypy_error_prefix(self) -> None:\n        # Some errors don't have a file and start with \"mypy: \". These\n        # shouldn't be sorted together with file-specific errors.\n        msg1 = 'x.py:1: error: \"int\" not callable'\n        msg2 = 'foo/y:123: note: \"X\" not defined'\n        msg3 = \"mypy: Error not associated with a file\"\n        old_msgs = [\n            \"mypy: Something wrong\",\n            'foo/y:12: note: \"Y\" not defined',\n            'x.py:8: error: \"str\" not callable',\n        ]\n        assert sort_messages_preserving_file_order([msg1, msg2, msg3], old_msgs) == [\n            msg2,\n            msg1,\n            msg3,\n        ]\n        assert sort_messages_preserving_file_order([msg3, msg2, msg1], old_msgs) == [\n            msg2,\n            msg1,\n            msg3,\n        ]\n\n    def test_new_file_at_the_end(self) -> None:\n        msg1 = 'x.py:1: error: \"int\" not callable'\n        msg2 = 'foo/y.py:123: note: \"X\" not defined'\n        new1 = \"ab.py:3: error: Problem: error\"\n        new2 = \"aaa:3: error: Bad\"\n        old_msgs = ['foo/y.py:12: note: \"Y\" not defined', 'x.py:8: error: \"str\" not callable']\n        assert sort_messages_preserving_file_order([msg1, msg2, new1], old_msgs) == [\n            msg2,\n            msg1,\n            new1,\n        ]\n        assert sort_messages_preserving_file_order([new1, msg1, msg2, new2], old_msgs) == [\n            msg2,\n            msg1,\n            new1,\n            new2,\n        ]\n"
  },
  {
    "path": "mypy/test/testfinegrainedcache.py",
    "content": "\"\"\"Tests for fine-grained incremental checking using the cache.\n\nAll of the real code for this lives in testfinegrained.py.\n\"\"\"\n\n# We can't \"import FineGrainedSuite from ...\" because that will cause pytest\n# to collect the non-caching tests when running this file.\nfrom __future__ import annotations\n\nimport mypy.test.testfinegrained\n\n\nclass FineGrainedCacheSuite(mypy.test.testfinegrained.FineGrainedSuite):\n    use_cache = True\n    test_name_suffix = \"_cached\"\n    files = mypy.test.testfinegrained.FineGrainedSuite.files + [\n        \"fine-grained-cache-incremental.test\"\n    ]\n"
  },
  {
    "path": "mypy/test/testformatter.py",
    "content": "from __future__ import annotations\n\nfrom unittest import TestCase, main\n\nfrom mypy.util import split_words, trim_source_line\n\n\nclass FancyErrorFormattingTestCases(TestCase):\n    def test_trim_source(self) -> None:\n        assert trim_source_line(\"0123456789abcdef\", max_len=16, col=5, min_width=2) == (\n            \"0123456789abcdef\",\n            0,\n        )\n\n        # Locations near start.\n        assert trim_source_line(\"0123456789abcdef\", max_len=7, col=0, min_width=2) == (\n            \"0123456...\",\n            0,\n        )\n        assert trim_source_line(\"0123456789abcdef\", max_len=7, col=4, min_width=2) == (\n            \"0123456...\",\n            0,\n        )\n\n        # Middle locations.\n        assert trim_source_line(\"0123456789abcdef\", max_len=7, col=5, min_width=2) == (\n            \"...1234567...\",\n            -2,\n        )\n        assert trim_source_line(\"0123456789abcdef\", max_len=7, col=6, min_width=2) == (\n            \"...2345678...\",\n            -1,\n        )\n        assert trim_source_line(\"0123456789abcdef\", max_len=7, col=8, min_width=2) == (\n            \"...456789a...\",\n            1,\n        )\n\n        # Locations near the end.\n        assert trim_source_line(\"0123456789abcdef\", max_len=7, col=11, min_width=2) == (\n            \"...789abcd...\",\n            4,\n        )\n        assert trim_source_line(\"0123456789abcdef\", max_len=7, col=13, min_width=2) == (\n            \"...9abcdef\",\n            6,\n        )\n        assert trim_source_line(\"0123456789abcdef\", max_len=7, col=15, min_width=2) == (\n            \"...9abcdef\",\n            6,\n        )\n\n    def test_split_words(self) -> None:\n        assert split_words(\"Simple message\") == [\"Simple\", \"message\"]\n        assert split_words('Message with \"Some[Long, Types]\" in it') == [\n            \"Message\",\n            \"with\",\n            '\"Some[Long, Types]\"',\n            \"in\",\n            \"it\",\n        ]\n        assert split_words('Message with \"Some[Long, Types]\" and [error-code]') == [\n            \"Message\",\n            \"with\",\n            '\"Some[Long, Types]\"',\n            \"and\",\n            \"[error-code]\",\n        ]\n        assert split_words('\"Type[Stands, First]\" then words') == [\n            '\"Type[Stands, First]\"',\n            \"then\",\n            \"words\",\n        ]\n        assert split_words('First words \"Then[Stands, Type]\"') == [\n            \"First\",\n            \"words\",\n            '\"Then[Stands, Type]\"',\n        ]\n        assert split_words('\"Type[Only, Here]\"') == ['\"Type[Only, Here]\"']\n        assert split_words(\"OneWord\") == [\"OneWord\"]\n        assert split_words(\" \") == [\"\", \"\"]\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "mypy/test/testfscache.py",
    "content": "\"\"\"Unit tests for file system cache.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport shutil\nimport tempfile\nimport unittest\n\nfrom mypy.fscache import FileSystemCache\n\n\nclass TestFileSystemCache(unittest.TestCase):\n    def setUp(self) -> None:\n        self.tempdir = tempfile.mkdtemp()\n        self.oldcwd = os.getcwd()\n        os.chdir(self.tempdir)\n        self.fscache = FileSystemCache()\n\n    def tearDown(self) -> None:\n        os.chdir(self.oldcwd)\n        shutil.rmtree(self.tempdir)\n\n    def test_isfile_case_1(self) -> None:\n        self.make_file(\"bar.py\")\n        self.make_file(\"pkg/sub_package/__init__.py\")\n        self.make_file(\"pkg/sub_package/foo.py\")\n        # Run twice to test both cached and non-cached code paths.\n        for i in range(2):\n            assert self.isfile_case(\"bar.py\")\n            assert self.isfile_case(\"pkg/sub_package/__init__.py\")\n            assert self.isfile_case(\"pkg/sub_package/foo.py\")\n            assert not self.isfile_case(\"non_existent.py\")\n            assert not self.isfile_case(\"pkg/non_existent.py\")\n            assert not self.isfile_case(\"pkg/\")\n            assert not self.isfile_case(\"bar.py/\")\n        for i in range(2):\n            assert not self.isfile_case(\"Bar.py\")\n            assert not self.isfile_case(\"pkg/sub_package/__init__.PY\")\n            assert not self.isfile_case(\"pkg/Sub_Package/foo.py\")\n            assert not self.isfile_case(\"Pkg/sub_package/foo.py\")\n\n    def test_isfile_case_2(self) -> None:\n        self.make_file(\"bar.py\")\n        self.make_file(\"pkg/sub_package/__init__.py\")\n        self.make_file(\"pkg/sub_package/foo.py\")\n        # Run twice to test both cached and non-cached code paths.\n        # This reverses the order of checks from test_isfile_case_1.\n        for i in range(2):\n            assert not self.isfile_case(\"Bar.py\")\n            assert not self.isfile_case(\"pkg/sub_package/__init__.PY\")\n            assert not self.isfile_case(\"pkg/Sub_Package/foo.py\")\n            assert not self.isfile_case(\"Pkg/sub_package/foo.py\")\n        for i in range(2):\n            assert self.isfile_case(\"bar.py\")\n            assert self.isfile_case(\"pkg/sub_package/__init__.py\")\n            assert self.isfile_case(\"pkg/sub_package/foo.py\")\n            assert not self.isfile_case(\"non_existent.py\")\n            assert not self.isfile_case(\"pkg/non_existent.py\")\n\n    def test_isfile_case_3(self) -> None:\n        self.make_file(\"bar.py\")\n        self.make_file(\"pkg/sub_package/__init__.py\")\n        self.make_file(\"pkg/sub_package/foo.py\")\n        # Run twice to test both cached and non-cached code paths.\n        for i in range(2):\n            assert self.isfile_case(\"bar.py\")\n            assert not self.isfile_case(\"non_existent.py\")\n            assert not self.isfile_case(\"pkg/non_existent.py\")\n            assert not self.isfile_case(\"Bar.py\")\n            assert not self.isfile_case(\"pkg/sub_package/__init__.PY\")\n            assert not self.isfile_case(\"pkg/Sub_Package/foo.py\")\n            assert not self.isfile_case(\"Pkg/sub_package/foo.py\")\n            assert self.isfile_case(\"pkg/sub_package/__init__.py\")\n            assert self.isfile_case(\"pkg/sub_package/foo.py\")\n\n    def test_isfile_case_other_directory(self) -> None:\n        self.make_file(\"bar.py\")\n        with tempfile.TemporaryDirectory() as other:\n            self.make_file(\"other_dir.py\", base=other)\n            self.make_file(\"pkg/other_dir.py\", base=other)\n            assert self.isfile_case(os.path.join(other, \"other_dir.py\"))\n            assert not self.isfile_case(os.path.join(other, \"Other_Dir.py\"))\n            assert not self.isfile_case(os.path.join(other, \"bar.py\"))\n            if os.path.exists(os.path.join(other, \"PKG/other_dir.py\")):\n                # We only check case for directories under our prefix, and since\n                # this path is not under the prefix, case difference is fine.\n                assert self.isfile_case(os.path.join(other, \"PKG/other_dir.py\"))\n\n    def make_file(self, path: str, base: str | None = None) -> None:\n        if base is None:\n            base = self.tempdir\n        fullpath = os.path.join(base, path)\n        os.makedirs(os.path.dirname(fullpath), exist_ok=True)\n        if not path.endswith(\"/\"):\n            with open(fullpath, \"w\") as f:\n                f.write(\"# test file\")\n\n    def isfile_case(self, path: str) -> bool:\n        return self.fscache.isfile_case(os.path.join(self.tempdir, path), self.tempdir)\n"
  },
  {
    "path": "mypy/test/testgraph.py",
    "content": "\"\"\"Test cases for graph processing code in build.py.\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nfrom collections.abc import Set as AbstractSet\n\nfrom mypy.build import BuildManager, BuildSourceSet, State, order_ascc, sorted_components\nfrom mypy.errors import Errors\nfrom mypy.fscache import FileSystemCache\nfrom mypy.graph_utils import strongly_connected_components, topsort\nfrom mypy.modulefinder import SearchPaths\nfrom mypy.options import Options\nfrom mypy.plugin import Plugin\nfrom mypy.report import Reports\nfrom mypy.test.helpers import Suite, assert_equal\nfrom mypy.version import __version__\n\n\nclass GraphSuite(Suite):\n    def test_topsort_empty(self) -> None:\n        data: dict[AbstractSet[str], set[AbstractSet[str]]] = {}\n        assert_equal(list(topsort(data)), [])\n\n    def test_topsort(self) -> None:\n        a = frozenset({\"A\"})\n        b = frozenset({\"B\"})\n        c = frozenset({\"C\"})\n        d = frozenset({\"D\"})\n        data: dict[AbstractSet[str], set[AbstractSet[str]]] = {a: {b, c}, b: {d}, c: {d}}\n        res = list(topsort(data))\n        assert_equal(res, [{d}, {b, c}, {a}])\n\n    def test_topsort_orphan(self) -> None:\n        a = frozenset({\"A\"})\n        b = frozenset({\"B\"})\n        data: dict[AbstractSet[str], set[AbstractSet[str]]] = {a: {b}}\n        res = list(topsort(data))\n        assert_equal(res, [{b}, {a}])\n\n    def test_topsort_independent(self) -> None:\n        a = frozenset({\"A\"})\n        b = frozenset({\"B\"})\n        c = frozenset({\"C\"})\n        data: dict[AbstractSet[str], set[AbstractSet[str]]] = {a: set(), b: set(), c: set()}\n        res = list(topsort(data))\n        assert_equal(res, [{a, b, c}])\n\n    def test_topsort_linear_chain(self) -> None:\n        a = frozenset({\"A\"})\n        b = frozenset({\"B\"})\n        c = frozenset({\"C\"})\n        d = frozenset({\"D\"})\n        data: dict[AbstractSet[str], set[AbstractSet[str]]] = {a: {b}, b: {c}, c: {d}, d: set()}\n        res = list(topsort(data))\n        assert_equal(res, [{d}, {c}, {b}, {a}])\n\n    def test_topsort_self_dependency(self) -> None:\n        a = frozenset({\"A\"})\n        b = frozenset({\"B\"})\n        data: dict[AbstractSet[str], set[AbstractSet[str]]] = {a: {a, b}, b: set()}\n        res = list(topsort(data))\n        assert_equal(res, [{b}, {a}])\n\n    def test_topsort_orphan_diamond(self) -> None:\n        a = frozenset({\"A\"})\n        b = frozenset({\"B\"})\n        c = frozenset({\"C\"})\n        # B and C are orphans -- they appear only in values, not as keys.\n        data: dict[AbstractSet[str], set[AbstractSet[str]]] = {a: {b, c}}\n        res = list(topsort(data))\n        assert_equal(res, [{b, c}, {a}])\n\n    def test_topsort_cycle(self) -> None:\n        a = frozenset({\"A\"})\n        b = frozenset({\"B\"})\n        data: dict[AbstractSet[str], set[AbstractSet[str]]] = {a: {b}, b: {a}}\n        with self.assertRaises(AssertionError):\n            list(topsort(data))\n\n    def test_scc(self) -> None:\n        vertices = {\"A\", \"B\", \"C\", \"D\"}\n        edges: dict[str, list[str]] = {\"A\": [\"B\", \"C\"], \"B\": [\"C\"], \"C\": [\"B\", \"D\"], \"D\": []}\n        sccs = {frozenset(x) for x in strongly_connected_components(vertices, edges)}\n        assert_equal(sccs, {frozenset({\"A\"}), frozenset({\"B\", \"C\"}), frozenset({\"D\"})})\n\n    def _make_manager(self) -> BuildManager:\n        options = Options()\n        options.use_builtins_fixtures = True\n        errors = Errors(options)\n        fscache = FileSystemCache()\n        search_paths = SearchPaths((), (), (), ())\n        manager = BuildManager(\n            data_dir=\"\",\n            search_paths=search_paths,\n            ignore_prefix=\"\",\n            source_set=BuildSourceSet([]),\n            reports=Reports(\"\", {}),\n            options=options,\n            version_id=__version__,\n            plugin=Plugin(options),\n            plugins_snapshot={},\n            errors=errors,\n            flush_errors=lambda filename, msgs, serious: None,\n            fscache=fscache,\n            stdout=sys.stdout,\n            stderr=sys.stderr,\n        )\n        return manager\n\n    def test_sorted_components(self) -> None:\n        manager = self._make_manager()\n        graph = {\n            \"a\": State.new_state(\"a\", None, \"import b, c\", manager),\n            \"d\": State.new_state(\"d\", None, \"pass\", manager),\n            \"b\": State.new_state(\"b\", None, \"import c\", manager),\n            \"c\": State.new_state(\"c\", None, \"import b, d\", manager),\n            \"builtins\": State.new_state(\"builtins\", None, \"\", manager),\n        }\n        res = [scc.mod_ids for scc in sorted_components(graph)]\n        assert_equal(res, [{\"builtins\"}, {\"d\"}, {\"c\", \"b\"}, {\"a\"}])\n\n    def test_order_ascc(self) -> None:\n        manager = self._make_manager()\n        graph = {\n            \"a\": State.new_state(\"a\", None, \"import b, c\", manager),\n            \"d\": State.new_state(\"d\", None, \"def f(): import a\", manager),\n            \"b\": State.new_state(\"b\", None, \"import c\", manager),\n            \"c\": State.new_state(\"c\", None, \"import b, d\", manager),\n            \"builtins\": State.new_state(\"builtins\", None, \"\", manager),\n        }\n        res = [scc.mod_ids for scc in sorted_components(graph)]\n        assert_equal(res, [{\"builtins\"}, {\"a\", \"d\", \"c\", \"b\"}])\n        ascc = res[1]\n        scc = order_ascc(graph, ascc)\n        assert_equal(scc, [\"d\", \"c\", \"b\", \"a\"])\n"
  },
  {
    "path": "mypy/test/testinfer.py",
    "content": "\"\"\"Test cases for type inference helper functions.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.argmap import map_actuals_to_formals\nfrom mypy.checker import DisjointDict, group_comparison_operands\nfrom mypy.literals import Key\nfrom mypy.nodes import ARG_NAMED, ARG_OPT, ARG_POS, ARG_STAR, ARG_STAR2, ArgKind, NameExpr\nfrom mypy.test.helpers import Suite, assert_equal\nfrom mypy.test.typefixture import TypeFixture\nfrom mypy.types import AnyType, TupleType, Type, TypeOfAny\n\n\nclass MapActualsToFormalsSuite(Suite):\n    \"\"\"Test cases for argmap.map_actuals_to_formals.\"\"\"\n\n    def test_basic(self) -> None:\n        self.assert_map([], [], [])\n\n    def test_positional_only(self) -> None:\n        self.assert_map([ARG_POS], [ARG_POS], [[0]])\n        self.assert_map([ARG_POS, ARG_POS], [ARG_POS, ARG_POS], [[0], [1]])\n\n    def test_optional(self) -> None:\n        self.assert_map([], [ARG_OPT], [[]])\n        self.assert_map([ARG_POS], [ARG_OPT], [[0]])\n        self.assert_map([ARG_POS], [ARG_OPT, ARG_OPT], [[0], []])\n\n    def test_callee_star(self) -> None:\n        self.assert_map([], [ARG_STAR], [[]])\n        self.assert_map([ARG_POS], [ARG_STAR], [[0]])\n        self.assert_map([ARG_POS, ARG_POS], [ARG_STAR], [[0, 1]])\n\n    def test_caller_star(self) -> None:\n        self.assert_map([ARG_STAR], [ARG_STAR], [[0]])\n        self.assert_map([ARG_POS, ARG_STAR], [ARG_STAR], [[0, 1]])\n        self.assert_map([ARG_STAR], [ARG_POS, ARG_STAR], [[0], [0]])\n        self.assert_map([ARG_STAR], [ARG_OPT, ARG_STAR], [[0], [0]])\n\n    def test_too_many_caller_args(self) -> None:\n        self.assert_map([ARG_POS], [], [])\n        self.assert_map([ARG_STAR], [], [])\n        self.assert_map([ARG_STAR], [ARG_POS], [[0]])\n\n    def test_tuple_star(self) -> None:\n        any_type = AnyType(TypeOfAny.special_form)\n        self.assert_vararg_map([ARG_STAR], [ARG_POS], [[0]], self.make_tuple(any_type))\n        self.assert_vararg_map(\n            [ARG_STAR], [ARG_POS, ARG_POS], [[0], [0]], self.make_tuple(any_type, any_type)\n        )\n        self.assert_vararg_map(\n            [ARG_STAR],\n            [ARG_POS, ARG_OPT, ARG_OPT],\n            [[0], [0], []],\n            self.make_tuple(any_type, any_type),\n        )\n\n    def make_tuple(self, *args: Type) -> TupleType:\n        return TupleType(list(args), TypeFixture().std_tuple)\n\n    def test_named_args(self) -> None:\n        self.assert_map([\"x\"], [(ARG_POS, \"x\")], [[0]])\n        self.assert_map([\"y\", \"x\"], [(ARG_POS, \"x\"), (ARG_POS, \"y\")], [[1], [0]])\n\n    def test_some_named_args(self) -> None:\n        self.assert_map([\"y\"], [(ARG_OPT, \"x\"), (ARG_OPT, \"y\"), (ARG_OPT, \"z\")], [[], [0], []])\n\n    def test_missing_named_arg(self) -> None:\n        self.assert_map([\"y\"], [(ARG_OPT, \"x\")], [[]])\n\n    def test_duplicate_named_arg(self) -> None:\n        self.assert_map([\"x\", \"x\"], [(ARG_OPT, \"x\")], [[0, 1]])\n\n    def test_varargs_and_bare_asterisk(self) -> None:\n        self.assert_map([ARG_STAR], [ARG_STAR, (ARG_NAMED, \"x\")], [[0], []])\n        self.assert_map([ARG_STAR, \"x\"], [ARG_STAR, (ARG_NAMED, \"x\")], [[0], [1]])\n\n    def test_keyword_varargs(self) -> None:\n        self.assert_map([\"x\"], [ARG_STAR2], [[0]])\n        self.assert_map([\"x\", ARG_STAR2], [ARG_STAR2], [[0, 1]])\n        self.assert_map([\"x\", ARG_STAR2], [(ARG_POS, \"x\"), ARG_STAR2], [[0], [1]])\n        self.assert_map([ARG_POS, ARG_STAR2], [(ARG_POS, \"x\"), ARG_STAR2], [[0], [1]])\n\n    def test_both_kinds_of_varargs(self) -> None:\n        self.assert_map([ARG_STAR, ARG_STAR2], [(ARG_POS, \"x\"), (ARG_POS, \"y\")], [[0, 1], [0, 1]])\n\n    def test_special_cases(self) -> None:\n        self.assert_map([ARG_STAR], [ARG_STAR, ARG_STAR2], [[0], []])\n        self.assert_map([ARG_STAR, ARG_STAR2], [ARG_STAR, ARG_STAR2], [[0], [1]])\n        self.assert_map([ARG_STAR2], [(ARG_POS, \"x\"), ARG_STAR2], [[0], [0]])\n        self.assert_map([ARG_STAR2], [ARG_STAR2], [[0]])\n\n    def assert_map(\n        self,\n        caller_kinds_: list[ArgKind | str],\n        callee_kinds_: list[ArgKind | tuple[ArgKind, str]],\n        expected: list[list[int]],\n    ) -> None:\n        caller_kinds, caller_names = expand_caller_kinds(caller_kinds_)\n        callee_kinds, callee_names = expand_callee_kinds(callee_kinds_)\n        result = map_actuals_to_formals(\n            caller_kinds,\n            caller_names,\n            callee_kinds,\n            callee_names,\n            lambda i: AnyType(TypeOfAny.special_form),\n        )\n        assert_equal(result, expected)\n\n    def assert_vararg_map(\n        self,\n        caller_kinds: list[ArgKind],\n        callee_kinds: list[ArgKind],\n        expected: list[list[int]],\n        vararg_type: Type,\n    ) -> None:\n        result = map_actuals_to_formals(caller_kinds, [], callee_kinds, [], lambda i: vararg_type)\n        assert_equal(result, expected)\n\n\ndef expand_caller_kinds(\n    kinds_or_names: list[ArgKind | str],\n) -> tuple[list[ArgKind], list[str | None]]:\n    kinds = []\n    names: list[str | None] = []\n    for k in kinds_or_names:\n        if isinstance(k, str):\n            kinds.append(ARG_NAMED)\n            names.append(k)\n        else:\n            kinds.append(k)\n            names.append(None)\n    return kinds, names\n\n\ndef expand_callee_kinds(\n    kinds_and_names: list[ArgKind | tuple[ArgKind, str]],\n) -> tuple[list[ArgKind], list[str | None]]:\n    kinds = []\n    names: list[str | None] = []\n    for v in kinds_and_names:\n        if isinstance(v, tuple):\n            kinds.append(v[0])\n            names.append(v[1])\n        else:\n            kinds.append(v)\n            names.append(None)\n    return kinds, names\n\n\nclass OperandDisjointDictSuite(Suite):\n    \"\"\"Test cases for checker.DisjointDict, which is used for type inference with operands.\"\"\"\n\n    def new(self) -> DisjointDict[int, str]:\n        return DisjointDict()\n\n    def test_independent_maps(self) -> None:\n        d = self.new()\n        d.add_mapping({0, 1}, {\"group1\"})\n        d.add_mapping({2, 3, 4}, {\"group2\"})\n        d.add_mapping({5, 6, 7}, {\"group3\"})\n\n        self.assertEqual(\n            d.items(), [({0, 1}, {\"group1\"}), ({2, 3, 4}, {\"group2\"}), ({5, 6, 7}, {\"group3\"})]\n        )\n\n    def test_partial_merging(self) -> None:\n        d = self.new()\n        d.add_mapping({0, 1}, {\"group1\"})\n        d.add_mapping({1, 2}, {\"group2\"})\n        d.add_mapping({3, 4}, {\"group3\"})\n        d.add_mapping({5, 0}, {\"group4\"})\n        d.add_mapping({5, 6}, {\"group5\"})\n        d.add_mapping({4, 7}, {\"group6\"})\n\n        self.assertEqual(\n            d.items(),\n            [\n                ({0, 1, 2, 5, 6}, {\"group1\", \"group2\", \"group4\", \"group5\"}),\n                ({3, 4, 7}, {\"group3\", \"group6\"}),\n            ],\n        )\n\n    def test_full_merging(self) -> None:\n        d = self.new()\n        d.add_mapping({0, 1, 2}, {\"a\"})\n        d.add_mapping({3, 4, 2}, {\"b\"})\n        d.add_mapping({10, 11, 12}, {\"c\"})\n        d.add_mapping({13, 14, 15}, {\"d\"})\n        d.add_mapping({14, 10, 16}, {\"e\"})\n        d.add_mapping({0, 10}, {\"f\"})\n\n        self.assertEqual(\n            d.items(),\n            [({0, 1, 2, 3, 4, 10, 11, 12, 13, 14, 15, 16}, {\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"})],\n        )\n\n    def test_merge_with_multiple_overlaps(self) -> None:\n        d = self.new()\n        d.add_mapping({0, 1, 2}, {\"a\"})\n        d.add_mapping({3, 4, 5}, {\"b\"})\n        d.add_mapping({1, 2, 4, 5}, {\"c\"})\n        d.add_mapping({6, 1, 2, 4, 5}, {\"d\"})\n        d.add_mapping({6, 1, 2, 4, 5}, {\"e\"})\n\n        self.assertEqual(d.items(), [({0, 1, 2, 3, 4, 5, 6}, {\"a\", \"b\", \"c\", \"d\", \"e\"})])\n\n\nclass OperandComparisonGroupingSuite(Suite):\n    \"\"\"Test cases for checker.group_comparison_operands.\"\"\"\n\n    def literal_keymap(self, assignable_operands: dict[int, NameExpr]) -> dict[int, Key]:\n        output: dict[int, Key] = {}\n        for index, expr in assignable_operands.items():\n            output[index] = (\"FakeExpr\", expr.name)\n        return output\n\n    def test_basic_cases(self) -> None:\n        # Note: the grouping function doesn't actually inspect the input exprs, so we\n        # just default to using NameExprs for simplicity.\n        x0 = NameExpr(\"x0\")\n        x1 = NameExpr(\"x1\")\n        x2 = NameExpr(\"x2\")\n        x3 = NameExpr(\"x3\")\n        x4 = NameExpr(\"x4\")\n\n        basic_input = [(\"==\", x0, x1), (\"==\", x1, x2), (\"<\", x2, x3), (\"==\", x3, x4)]\n\n        none_assignable = self.literal_keymap({})\n        all_assignable = self.literal_keymap({0: x0, 1: x1, 2: x2, 3: x3, 4: x4})\n\n        for assignable in [none_assignable, all_assignable]:\n            self.assertEqual(\n                group_comparison_operands(basic_input, assignable, set()),\n                [(\"==\", [0, 1]), (\"==\", [1, 2]), (\"<\", [2, 3]), (\"==\", [3, 4])],\n            )\n            self.assertEqual(\n                group_comparison_operands(basic_input, assignable, {\"==\"}),\n                [(\"==\", [0, 1, 2]), (\"<\", [2, 3]), (\"==\", [3, 4])],\n            )\n            self.assertEqual(\n                group_comparison_operands(basic_input, assignable, {\"<\"}),\n                [(\"==\", [0, 1]), (\"==\", [1, 2]), (\"<\", [2, 3]), (\"==\", [3, 4])],\n            )\n            self.assertEqual(\n                group_comparison_operands(basic_input, assignable, {\"==\", \"<\"}),\n                [(\"==\", [0, 1, 2]), (\"<\", [2, 3]), (\"==\", [3, 4])],\n            )\n\n    def test_multiple_groups(self) -> None:\n        x0 = NameExpr(\"x0\")\n        x1 = NameExpr(\"x1\")\n        x2 = NameExpr(\"x2\")\n        x3 = NameExpr(\"x3\")\n        x4 = NameExpr(\"x4\")\n        x5 = NameExpr(\"x5\")\n\n        self.assertEqual(\n            group_comparison_operands(\n                [(\"==\", x0, x1), (\"==\", x1, x2), (\"is\", x2, x3), (\"is\", x3, x4)],\n                self.literal_keymap({}),\n                {\"==\", \"is\"},\n            ),\n            [(\"==\", [0, 1, 2]), (\"is\", [2, 3, 4])],\n        )\n        self.assertEqual(\n            group_comparison_operands(\n                [(\"==\", x0, x1), (\"==\", x1, x2), (\"==\", x2, x3), (\"==\", x3, x4)],\n                self.literal_keymap({}),\n                {\"==\", \"is\"},\n            ),\n            [(\"==\", [0, 1, 2, 3, 4])],\n        )\n        self.assertEqual(\n            group_comparison_operands(\n                [(\"is\", x0, x1), (\"==\", x1, x2), (\"==\", x2, x3), (\"==\", x3, x4)],\n                self.literal_keymap({}),\n                {\"==\", \"is\"},\n            ),\n            [(\"is\", [0, 1]), (\"==\", [1, 2, 3, 4])],\n        )\n        self.assertEqual(\n            group_comparison_operands(\n                [(\"is\", x0, x1), (\"is\", x1, x2), (\"<\", x2, x3), (\"==\", x3, x4), (\"==\", x4, x5)],\n                self.literal_keymap({}),\n                {\"==\", \"is\"},\n            ),\n            [(\"is\", [0, 1, 2]), (\"<\", [2, 3]), (\"==\", [3, 4, 5])],\n        )\n\n    def test_multiple_groups_coalescing(self) -> None:\n        x0 = NameExpr(\"x0\")\n        x1 = NameExpr(\"x1\")\n        x2 = NameExpr(\"x2\")\n        x3 = NameExpr(\"x3\")\n        x4 = NameExpr(\"x4\")\n\n        nothing_combined = [(\"==\", [0, 1, 2]), (\"<\", [2, 3]), (\"==\", [3, 4, 5])]\n        everything_combined = [(\"==\", [0, 1, 2, 3, 4, 5]), (\"<\", [2, 3])]\n\n        # Note: We do 'x4 == x0' at the very end!\n        two_groups = [\n            (\"==\", x0, x1),\n            (\"==\", x1, x2),\n            (\"<\", x2, x3),\n            (\"==\", x3, x4),\n            (\"==\", x4, x0),\n        ]\n        self.assertEqual(\n            group_comparison_operands(\n                two_groups, self.literal_keymap({0: x0, 1: x1, 2: x2, 3: x3, 4: x4, 5: x0}), {\"==\"}\n            ),\n            everything_combined,\n            \"All vars are assignable, everything is combined\",\n        )\n        self.assertEqual(\n            group_comparison_operands(\n                two_groups, self.literal_keymap({1: x1, 2: x2, 3: x3, 4: x4}), {\"==\"}\n            ),\n            nothing_combined,\n            \"x0 is unassignable, so no combining\",\n        )\n        self.assertEqual(\n            group_comparison_operands(\n                two_groups, self.literal_keymap({0: x0, 1: x1, 3: x3, 5: x0}), {\"==\"}\n            ),\n            everything_combined,\n            \"Some vars are unassignable but x0 is, so we combine\",\n        )\n        self.assertEqual(\n            group_comparison_operands(two_groups, self.literal_keymap({0: x0, 5: x0}), {\"==\"}),\n            everything_combined,\n            \"All vars are unassignable but x0 is, so we combine\",\n        )\n\n    def test_multiple_groups_different_operators(self) -> None:\n        x0 = NameExpr(\"x0\")\n        x1 = NameExpr(\"x1\")\n        x2 = NameExpr(\"x2\")\n        x3 = NameExpr(\"x3\")\n\n        groups = [(\"==\", x0, x1), (\"==\", x1, x2), (\"is\", x2, x3), (\"is\", x3, x0)]\n        keymap = self.literal_keymap({0: x0, 1: x1, 2: x2, 3: x3, 4: x0})\n        self.assertEqual(\n            group_comparison_operands(groups, keymap, {\"==\", \"is\"}),\n            [(\"==\", [0, 1, 2]), (\"is\", [2, 3, 4])],\n            \"Different operators can never be combined\",\n        )\n\n    def test_single_pair(self) -> None:\n        x0 = NameExpr(\"x0\")\n        x1 = NameExpr(\"x1\")\n\n        single_comparison = [(\"==\", x0, x1)]\n        expected_output = [(\"==\", [0, 1])]\n\n        assignable_combinations: list[dict[int, NameExpr]] = [{}, {0: x0}, {1: x1}, {0: x0, 1: x1}]\n        to_group_by: list[set[str]] = [set(), {\"==\"}, {\"is\"}]\n\n        for combo in assignable_combinations:\n            for operators in to_group_by:\n                keymap = self.literal_keymap(combo)\n                self.assertEqual(\n                    group_comparison_operands(single_comparison, keymap, operators),\n                    expected_output,\n                )\n\n    def test_empty_pair_list(self) -> None:\n        # This case should never occur in practice -- ComparisonExprs\n        # always contain at least one comparison. But in case it does...\n\n        self.assertEqual(group_comparison_operands([], {}, set()), [])\n        self.assertEqual(group_comparison_operands([], {}, {\"==\"}), [])\n"
  },
  {
    "path": "mypy/test/testipc.py",
    "content": "from __future__ import annotations\n\nimport sys\nimport time\nfrom multiprocessing import Queue, get_context\nfrom unittest import TestCase, main\n\nimport pytest\n\nfrom mypy.ipc import IPCClient, IPCServer\n\nCONNECTION_NAME = \"dmypy-test-ipc\"\n\n\ndef server(msg: str, q: Queue[str]) -> None:\n    server = IPCServer(CONNECTION_NAME)\n    q.put(server.connection_name)\n    data = \"\"\n    while not data:\n        with server:\n            server.write(msg)\n            data = server.read()\n    server.cleanup()\n\n\ndef server_multi_message_echo(q: Queue[str]) -> None:\n    server = IPCServer(CONNECTION_NAME)\n    q.put(server.connection_name)\n    data = \"\"\n    with server:\n        while data != \"quit\":\n            data = server.read()\n            server.write(data)\n    server.cleanup()\n\n\nclass IPCTests(TestCase):\n    def setUp(self) -> None:\n        if sys.platform == \"linux\":\n            # The default \"fork\" start method is potentially unsafe\n            self.ctx = get_context(\"forkserver\")\n        else:\n            self.ctx = get_context(\"spawn\")\n\n    def test_transaction_large(self) -> None:\n        queue: Queue[str] = self.ctx.Queue()\n        msg = \"t\" * 200000  # longer than the max read size of 100_000\n        p = self.ctx.Process(target=server, args=(msg, queue), daemon=True)\n        p.start()\n        connection_name = queue.get()\n        with IPCClient(connection_name, timeout=1) as client:\n            assert client.read() == msg\n            client.write(\"test\")\n        queue.close()\n        queue.join_thread()\n        p.join()\n\n    def test_connect_twice(self) -> None:\n        queue: Queue[str] = self.ctx.Queue()\n        msg = \"this is a test message\"\n        p = self.ctx.Process(target=server, args=(msg, queue), daemon=True)\n        p.start()\n        connection_name = queue.get()\n        with IPCClient(connection_name, timeout=1) as client:\n            assert client.read() == msg\n            client.write(\"\")  # don't let the server hang up yet, we want to connect again.\n\n        with IPCClient(connection_name, timeout=1) as client:\n            assert client.read() == msg\n            client.write(\"test\")\n        queue.close()\n        queue.join_thread()\n        p.join()\n        assert p.exitcode == 0\n\n    def test_multiple_messages(self) -> None:\n        queue: Queue[str] = self.ctx.Queue()\n        p = self.ctx.Process(target=server_multi_message_echo, args=(queue,), daemon=True)\n        p.start()\n        connection_name = queue.get()\n        with IPCClient(connection_name, timeout=1) as client:\n            # \"foo bar\" with extra accents on letters.\n            # In UTF-8 encoding so we don't confuse editors opening this file.\n            fancy_text = b\"f\\xcc\\xb6o\\xcc\\xb2\\xf0\\x9d\\x91\\x9c \\xd0\\xb2\\xe2\\xb7\\xa1a\\xcc\\xb6r\\xcc\\x93\\xcd\\x98\\xcd\\x8c\"\n            client.write(fancy_text.decode(\"utf-8\"))\n            assert client.read() == fancy_text.decode(\"utf-8\")\n\n            client.write(\"Test with spaces\")\n            client.write(\"Test write before reading previous\")\n            time.sleep(0)  # yield to the server to force reading of all messages by server.\n            assert client.read() == \"Test with spaces\"\n            assert client.read() == \"Test write before reading previous\"\n\n            client.write(\"quit\")\n            assert client.read() == \"quit\"\n        queue.close()\n        queue.join_thread()\n        p.join()\n        assert p.exitcode == 0\n\n    # Run test_connect_twice a lot, in the hopes of finding issues.\n    # This is really slow, so it is skipped, but can be enabled if\n    # needed to debug IPC issues.\n    @pytest.mark.skip\n    def test_connect_alot(self) -> None:\n        t0 = time.time()\n        for i in range(1000):\n            try:\n                print(i, \"start\")\n                self.test_connect_twice()\n            finally:\n                t1 = time.time()\n                print(i, t1 - t0)\n                sys.stdout.flush()\n                t0 = t1\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "mypy/test/testmerge.py",
    "content": "\"\"\"Test cases for AST merge (used for fine-grained incremental checking)\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport shutil\n\nfrom mypy import build\nfrom mypy.build import BuildResult\nfrom mypy.errors import CompileError\nfrom mypy.modulefinder import BuildSource\nfrom mypy.nodes import (\n    UNBOUND_IMPORTED,\n    Expression,\n    MypyFile,\n    SymbolTable,\n    SymbolTableNode,\n    TypeInfo,\n    TypeVarExpr,\n    Var,\n)\nfrom mypy.options import Options\nfrom mypy.server.subexpr import get_subexpressions\nfrom mypy.server.update import FineGrainedBuildManager\nfrom mypy.strconv import StrConv\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, normalize_error_messages, parse_options\nfrom mypy.types import Type, TypeStrVisitor\nfrom mypy.util import IdMapper, short_type\n\n# Which data structures to dump in a test case?\nSYMTABLE = \"SYMTABLE\"\nTYPEINFO = \" TYPEINFO\"\nTYPES = \"TYPES\"\nAST = \"AST\"\n\n\nclass ASTMergeSuite(DataSuite):\n    files = [\"merge.test\"]\n\n    def setup(self) -> None:\n        super().setup()\n        self.str_conv = StrConv(show_ids=True, options=Options())\n        assert self.str_conv.id_mapper is not None\n        self.id_mapper: IdMapper = self.str_conv.id_mapper\n        self.type_str_conv = TypeStrVisitor(self.id_mapper, options=Options())\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        name = testcase.name\n        # We use the test case name to decide which data structures to dump.\n        # Dumping everything would result in very verbose test cases.\n        if name.endswith(\"_symtable\"):\n            kind = SYMTABLE\n        elif name.endswith(\"_typeinfo\"):\n            kind = TYPEINFO\n        elif name.endswith(\"_types\"):\n            kind = TYPES\n        else:\n            kind = AST\n\n        main_src = \"\\n\".join(testcase.input)\n        result = self.build(main_src, testcase)\n        assert result is not None, \"cases where CompileError occurred should not be run\"\n        result.manager.fscache.flush()\n        fine_grained_manager = FineGrainedBuildManager(result)\n\n        a = []\n        if result.errors:\n            a.extend(result.errors)\n\n        target_path = os.path.join(test_temp_dir, \"target.py\")\n        shutil.copy(os.path.join(test_temp_dir, \"target.py.next\"), target_path)\n\n        a.extend(self.dump(fine_grained_manager, kind, testcase.test_modules))\n        old_subexpr = get_subexpressions(result.manager.modules[\"target\"])\n\n        a.append(\"==>\")\n\n        new_file, new_types = self.build_increment(fine_grained_manager, \"target\", target_path)\n        a.extend(self.dump(fine_grained_manager, kind, testcase.test_modules))\n\n        for expr in old_subexpr:\n            if isinstance(expr, TypeVarExpr):\n                # These are merged so we can't perform the check.\n                continue\n            # Verify that old AST nodes are removed from the expression type map.\n            assert expr not in new_types\n\n        if testcase.normalize_output:\n            a = normalize_error_messages(a)\n\n        assert_string_arrays_equal(\n            testcase.output, a, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n        )\n\n    def build(self, source: str, testcase: DataDrivenTestCase) -> BuildResult | None:\n        options = parse_options(source, testcase, incremental_step=1)\n        options.incremental = True\n        options.fine_grained_incremental = True\n        options.use_builtins_fixtures = True\n        options.export_types = True\n        options.show_traceback = True\n        options.allow_empty_bodies = True\n        options.reveal_verbose_types = True\n        main_path = os.path.join(test_temp_dir, \"main\")\n\n        self.str_conv.options = options\n        self.type_str_conv.options = options\n        with open(main_path, \"w\", encoding=\"utf8\") as f:\n            f.write(source)\n        try:\n            result = build.build(\n                sources=[BuildSource(main_path, None, None)],\n                options=options,\n                alt_lib_path=test_temp_dir,\n            )\n        except CompileError:\n            # TODO: Is it okay to return None?\n            return None\n        return result\n\n    def build_increment(\n        self, manager: FineGrainedBuildManager, module_id: str, path: str\n    ) -> tuple[MypyFile, dict[Expression, Type]]:\n        manager.flush_cache()\n        manager.update([(module_id, path)], [])\n        module = manager.manager.modules[module_id]\n        type_map = manager.graph[module_id].type_map()\n        return module, type_map\n\n    def dump(\n        self, manager: FineGrainedBuildManager, kind: str, test_modules: list[str]\n    ) -> list[str]:\n        modules = {\n            name: file for name, file in manager.manager.modules.items() if name in test_modules\n        }\n        if kind == AST:\n            return self.dump_asts(modules)\n        elif kind == TYPEINFO:\n            return self.dump_typeinfos(modules)\n        elif kind == SYMTABLE:\n            return self.dump_symbol_tables(modules)\n        elif kind == TYPES:\n            return self.dump_types(modules, manager)\n        assert False, f\"Invalid kind {kind}\"\n\n    def dump_asts(self, modules: dict[str, MypyFile]) -> list[str]:\n        a = []\n        for m in sorted(modules):\n            s = modules[m].accept(self.str_conv)\n            a.extend(s.splitlines())\n        return a\n\n    def dump_symbol_tables(self, modules: dict[str, MypyFile]) -> list[str]:\n        a = []\n        for id in sorted(modules):\n            a.extend(self.dump_symbol_table(id, modules[id].names))\n        return a\n\n    def dump_symbol_table(self, module_id: str, symtable: SymbolTable) -> list[str]:\n        a = [f\"{module_id}:\"]\n        for name in sorted(symtable):\n            if name.startswith(\"__\"):\n                continue\n            a.append(f\"    {name}: {self.format_symbol_table_node(symtable[name])}\")\n        return a\n\n    def format_symbol_table_node(self, node: SymbolTableNode) -> str:\n        if node.node is None:\n            if node.kind == UNBOUND_IMPORTED:\n                return \"UNBOUND_IMPORTED\"\n            return \"None\"\n        s = f\"{str(type(node.node).__name__)}<{self.id_mapper.id(node.node)}>\"\n        if (\n            isinstance(node.node, Var)\n            and node.node.type\n            and not node.node.fullname.startswith(\"typing.\")\n        ):\n            typestr = self.format_type(node.node.type)\n            s += f\"({typestr})\"\n        return s\n\n    def dump_typeinfos(self, modules: dict[str, MypyFile]) -> list[str]:\n        a = []\n        for id in sorted(modules):\n            a.extend(self.dump_typeinfos_recursive(modules[id].names))\n        return a\n\n    def dump_typeinfos_recursive(self, names: SymbolTable) -> list[str]:\n        a = []\n        for name, node in sorted(names.items(), key=lambda x: x[0]):\n            if isinstance(node.node, TypeInfo):\n                a.extend(self.dump_typeinfo(node.node))\n                a.extend(self.dump_typeinfos_recursive(node.node.names))\n        return a\n\n    def dump_typeinfo(self, info: TypeInfo) -> list[str]:\n        if info.fullname == \"enum.Enum\":\n            # Avoid noise\n            return []\n        s = info.dump(str_conv=self.str_conv, type_str_conv=self.type_str_conv)\n        return s.splitlines()\n\n    def dump_types(\n        self, modules: dict[str, MypyFile], manager: FineGrainedBuildManager\n    ) -> list[str]:\n        a = []\n        # To make the results repeatable, we try to generate unique and\n        # deterministic sort keys.\n        for module_id in sorted(modules):\n            all_types = manager.manager.all_types\n            # Compute a module type map from the global type map\n            tree = manager.graph[module_id].tree\n            assert tree is not None\n            type_map = {\n                node: all_types[node] for node in get_subexpressions(tree) if node in all_types\n            }\n            if type_map:\n                a.append(f\"## {module_id}\")\n                for expr in sorted(\n                    type_map,\n                    key=lambda n: (\n                        n.line,\n                        short_type(n),\n                        n.str_with_options(self.str_conv.options)\n                        + type_map[n].accept(self.type_str_conv),\n                    ),\n                ):\n                    typ = type_map[expr]\n                    a.append(f\"{short_type(expr)}:{expr.line}: {self.format_type(typ)}\")\n        return a\n\n    def format_type(self, typ: Type) -> str:\n        return typ.accept(self.type_str_conv)\n"
  },
  {
    "path": "mypy/test/testmodulefinder.py",
    "content": "from __future__ import annotations\n\nimport os\n\nfrom mypy.modulefinder import FindModuleCache, ModuleNotFoundReason, SearchPaths\nfrom mypy.options import Options\nfrom mypy.test.config import package_path\nfrom mypy.test.helpers import Suite, assert_equal\n\ndata_path = os.path.relpath(os.path.join(package_path, \"modulefinder\"))\n\n\nclass ModuleFinderSuite(Suite):\n    def setUp(self) -> None:\n        self.search_paths = SearchPaths(\n            python_path=(),\n            mypy_path=(\n                os.path.join(data_path, \"nsx-pkg1\"),\n                os.path.join(data_path, \"nsx-pkg2\"),\n                os.path.join(data_path, \"nsx-pkg3\"),\n                os.path.join(data_path, \"nsy-pkg1\"),\n                os.path.join(data_path, \"nsy-pkg2\"),\n                os.path.join(data_path, \"pkg1\"),\n                os.path.join(data_path, \"pkg2\"),\n            ),\n            package_path=(),\n            typeshed_path=(),\n        )\n        options = Options()\n        options.namespace_packages = True\n        self.fmc_ns = FindModuleCache(self.search_paths, fscache=None, options=options)\n\n        options = Options()\n        options.namespace_packages = False\n        self.fmc_nons = FindModuleCache(self.search_paths, fscache=None, options=options)\n\n    def test__no_namespace_packages__nsx(self) -> None:\n        \"\"\"\n        If namespace_packages is False, we shouldn't find nsx\n        \"\"\"\n        found_module = self.fmc_nons.find_module(\"nsx\")\n        assert_equal(ModuleNotFoundReason.NOT_FOUND, found_module)\n\n    def test__no_namespace_packages__nsx_a(self) -> None:\n        \"\"\"\n        If namespace_packages is False, we shouldn't find nsx.a.\n        \"\"\"\n        found_module = self.fmc_nons.find_module(\"nsx.a\")\n        assert_equal(ModuleNotFoundReason.NOT_FOUND, found_module)\n\n    def test__no_namespace_packages__find_a_in_pkg1(self) -> None:\n        \"\"\"\n        Find find pkg1/a.py for \"a\" with namespace_packages False.\n        \"\"\"\n        found_module = self.fmc_nons.find_module(\"a\")\n        expected = os.path.abspath(os.path.join(data_path, \"pkg1\", \"a.py\"))\n        assert_equal(expected, found_module)\n\n    def test__no_namespace_packages__find_b_in_pkg2(self) -> None:\n        found_module = self.fmc_ns.find_module(\"b\")\n        expected = os.path.abspath(os.path.join(data_path, \"pkg2\", \"b\", \"__init__.py\"))\n        assert_equal(expected, found_module)\n\n    def test__find_nsx_as_namespace_pkg_in_pkg1(self) -> None:\n        \"\"\"\n        There's no __init__.py in any of the nsx dirs, return\n        the path to the first one found in mypypath.\n        \"\"\"\n        found_module = self.fmc_ns.find_module(\"nsx\")\n        expected = os.path.abspath(os.path.join(data_path, \"nsx-pkg1\", \"nsx\"))\n        assert_equal(expected, found_module)\n\n    def test__find_nsx_a_init_in_pkg1(self) -> None:\n        \"\"\"\n        Find nsx-pkg1/nsx/a/__init__.py for \"nsx.a\" in namespace mode.\n        \"\"\"\n        found_module = self.fmc_ns.find_module(\"nsx.a\")\n        expected = os.path.abspath(os.path.join(data_path, \"nsx-pkg1\", \"nsx\", \"a\", \"__init__.py\"))\n        assert_equal(expected, found_module)\n\n    def test__find_nsx_b_init_in_pkg2(self) -> None:\n        \"\"\"\n        Find nsx-pkg2/nsx/b/__init__.py for \"nsx.b\" in namespace mode.\n        \"\"\"\n        found_module = self.fmc_ns.find_module(\"nsx.b\")\n        expected = os.path.abspath(os.path.join(data_path, \"nsx-pkg2\", \"nsx\", \"b\", \"__init__.py\"))\n        assert_equal(expected, found_module)\n\n    def test__find_nsx_c_c_in_pkg3(self) -> None:\n        \"\"\"\n        Find nsx-pkg3/nsx/c/c.py for \"nsx.c.c\" in namespace mode.\n        \"\"\"\n        found_module = self.fmc_ns.find_module(\"nsx.c.c\")\n        expected = os.path.abspath(os.path.join(data_path, \"nsx-pkg3\", \"nsx\", \"c\", \"c.py\"))\n        assert_equal(expected, found_module)\n\n    def test__find_nsy_a__init_pyi(self) -> None:\n        \"\"\"\n        Prefer nsy-pkg1/a/__init__.pyi file over __init__.py.\n        \"\"\"\n        found_module = self.fmc_ns.find_module(\"nsy.a\")\n        expected = os.path.abspath(os.path.join(data_path, \"nsy-pkg1\", \"nsy\", \"a\", \"__init__.pyi\"))\n        assert_equal(expected, found_module)\n\n    def test__find_nsy_b__init_py(self) -> None:\n        \"\"\"\n        There is a nsy-pkg2/nsy/b.pyi, but also a nsy-pkg2/nsy/b/__init__.py.\n        We expect to find the latter when looking up \"nsy.b\" as\n        a package is preferred over a module.\n        \"\"\"\n        found_module = self.fmc_ns.find_module(\"nsy.b\")\n        expected = os.path.abspath(os.path.join(data_path, \"nsy-pkg2\", \"nsy\", \"b\", \"__init__.py\"))\n        assert_equal(expected, found_module)\n\n    def test__find_nsy_c_pyi(self) -> None:\n        \"\"\"\n        There is a nsy-pkg2/nsy/c.pyi and nsy-pkg2/nsy/c.py\n        We expect to find the former when looking up \"nsy.b\" as\n        .pyi is preferred over .py.\n        \"\"\"\n        found_module = self.fmc_ns.find_module(\"nsy.c\")\n        expected = os.path.abspath(os.path.join(data_path, \"nsy-pkg2\", \"nsy\", \"c.pyi\"))\n        assert_equal(expected, found_module)\n\n    def test__find_a_in_pkg1(self) -> None:\n        found_module = self.fmc_ns.find_module(\"a\")\n        expected = os.path.abspath(os.path.join(data_path, \"pkg1\", \"a.py\"))\n        assert_equal(expected, found_module)\n\n    def test__find_b_init_in_pkg2(self) -> None:\n        found_module = self.fmc_ns.find_module(\"b\")\n        expected = os.path.abspath(os.path.join(data_path, \"pkg2\", \"b\", \"__init__.py\"))\n        assert_equal(expected, found_module)\n\n    def test__find_d_nowhere(self) -> None:\n        found_module = self.fmc_ns.find_module(\"d\")\n        assert_equal(ModuleNotFoundReason.NOT_FOUND, found_module)\n\n\nclass ModuleFinderSitePackagesSuite(Suite):\n    def setUp(self) -> None:\n        self.package_dir = os.path.relpath(\n            os.path.join(package_path, \"modulefinder-site-packages\")\n        )\n\n        package_paths = (\n            os.path.join(self.package_dir, \"baz\"),\n            os.path.join(self.package_dir, \"..\", \"not-a-directory\"),\n            os.path.join(self.package_dir, \"..\", \"modulefinder-src\"),\n            self.package_dir,\n        )\n\n        self.search_paths = SearchPaths(\n            python_path=(),\n            mypy_path=(os.path.join(data_path, \"pkg1\"),),\n            package_path=tuple(package_paths),\n            typeshed_path=(),\n        )\n        options = Options()\n        options.namespace_packages = True\n        self.fmc_ns = FindModuleCache(self.search_paths, fscache=None, options=options)\n\n        options = Options()\n        options.namespace_packages = False\n        self.fmc_nons = FindModuleCache(self.search_paths, fscache=None, options=options)\n\n    def path(self, *parts: str) -> str:\n        return os.path.abspath(os.path.join(self.package_dir, *parts))\n\n    def test__packages_with_ns(self) -> None:\n        cases = [\n            # Namespace package with py.typed\n            (\"ns_pkg_typed\", self.path(\"ns_pkg_typed\")),\n            (\"ns_pkg_typed.a\", self.path(\"ns_pkg_typed\", \"a.py\")),\n            (\"ns_pkg_typed.b\", self.path(\"ns_pkg_typed\", \"b\")),\n            (\"ns_pkg_typed.b.c\", self.path(\"ns_pkg_typed\", \"b\", \"c.py\")),\n            (\"ns_pkg_typed.a.a_var\", ModuleNotFoundReason.NOT_FOUND),\n            # Namespace package without py.typed\n            (\"ns_pkg_untyped\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"ns_pkg_untyped.a\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"ns_pkg_untyped.b\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"ns_pkg_untyped.b.c\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"ns_pkg_untyped.a.a_var\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            # Namespace package without stub package\n            (\"ns_pkg_w_stubs\", self.path(\"ns_pkg_w_stubs\")),\n            (\"ns_pkg_w_stubs.typed\", self.path(\"ns_pkg_w_stubs-stubs\", \"typed\", \"__init__.pyi\")),\n            (\n                \"ns_pkg_w_stubs.typed_inline\",\n                self.path(\"ns_pkg_w_stubs\", \"typed_inline\", \"__init__.py\"),\n            ),\n            (\"ns_pkg_w_stubs.untyped\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            # Regular package with py.typed\n            (\"pkg_typed\", self.path(\"pkg_typed\", \"__init__.py\")),\n            (\"pkg_typed.a\", self.path(\"pkg_typed\", \"a.py\")),\n            (\"pkg_typed.b\", self.path(\"pkg_typed\", \"b\", \"__init__.py\")),\n            (\"pkg_typed.b.c\", self.path(\"pkg_typed\", \"b\", \"c.py\")),\n            (\"pkg_typed.a.a_var\", ModuleNotFoundReason.NOT_FOUND),\n            # Regular package with py.typed, bundled stubs, and external stubs-only package\n            (\"pkg_typed_w_stubs\", self.path(\"pkg_typed_w_stubs-stubs\", \"__init__.pyi\")),\n            (\"pkg_typed_w_stubs.spam\", self.path(\"pkg_typed_w_stubs-stubs\", \"spam.pyi\")),\n            # Regular package without py.typed\n            (\"pkg_untyped\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"pkg_untyped.a\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"pkg_untyped.b\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"pkg_untyped.b.c\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"pkg_untyped.a.a_var\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            # Top-level Python file in site-packages\n            (\"standalone\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"standalone.standalone_var\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            # Packages found by following .pth files\n            (\"baz_pkg\", self.path(\"baz\", \"baz_pkg\", \"__init__.py\")),\n            (\"ns_baz_pkg.a\", self.path(\"baz\", \"ns_baz_pkg\", \"a.py\")),\n            (\"neighbor_pkg\", self.path(\"..\", \"modulefinder-src\", \"neighbor_pkg\", \"__init__.py\")),\n            (\"ns_neighbor_pkg.a\", self.path(\"..\", \"modulefinder-src\", \"ns_neighbor_pkg\", \"a.py\")),\n            # Something that doesn't exist\n            (\"does_not_exist\", ModuleNotFoundReason.NOT_FOUND),\n            # A regular package with an installed set of stubs\n            (\"foo.bar\", self.path(\"foo-stubs\", \"bar.pyi\")),\n            # A regular, non-site-packages module\n            (\"a\", os.path.abspath(os.path.join(data_path, \"pkg1\", \"a.py\"))),\n        ]\n        for module, expected in cases:\n            template = \"Find(\" + module + \") got {}; expected {}\"\n\n            actual = self.fmc_ns.find_module(module)\n            assert_equal(actual, expected, template)\n\n    def test__packages_without_ns(self) -> None:\n        cases = [\n            # Namespace package with py.typed\n            (\"ns_pkg_typed\", ModuleNotFoundReason.NOT_FOUND),\n            (\"ns_pkg_typed.a\", ModuleNotFoundReason.NOT_FOUND),\n            (\"ns_pkg_typed.b\", ModuleNotFoundReason.NOT_FOUND),\n            (\"ns_pkg_typed.b.c\", ModuleNotFoundReason.NOT_FOUND),\n            (\"ns_pkg_typed.a.a_var\", ModuleNotFoundReason.NOT_FOUND),\n            # Namespace package without py.typed\n            (\"ns_pkg_untyped\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"ns_pkg_untyped.a\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"ns_pkg_untyped.b\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"ns_pkg_untyped.b.c\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"ns_pkg_untyped.a.a_var\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            # Namespace package without stub package\n            (\"ns_pkg_w_stubs\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"ns_pkg_w_stubs.typed\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\n                \"ns_pkg_w_stubs.typed_inline\",\n                self.path(\"ns_pkg_w_stubs\", \"typed_inline\", \"__init__.py\"),\n            ),\n            (\"ns_pkg_w_stubs.untyped\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            # Regular package with py.typed\n            (\"pkg_typed\", self.path(\"pkg_typed\", \"__init__.py\")),\n            (\"pkg_typed.a\", self.path(\"pkg_typed\", \"a.py\")),\n            (\"pkg_typed.b\", self.path(\"pkg_typed\", \"b\", \"__init__.py\")),\n            (\"pkg_typed.b.c\", self.path(\"pkg_typed\", \"b\", \"c.py\")),\n            (\"pkg_typed.a.a_var\", ModuleNotFoundReason.NOT_FOUND),\n            # Regular package with py.typed, bundled stubs, and external stubs-only package\n            (\"pkg_typed_w_stubs\", self.path(\"pkg_typed_w_stubs-stubs\", \"__init__.pyi\")),\n            (\"pkg_typed_w_stubs.spam\", self.path(\"pkg_typed_w_stubs-stubs\", \"spam.pyi\")),\n            # Regular package without py.typed\n            (\"pkg_untyped\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"pkg_untyped.a\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"pkg_untyped.b\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"pkg_untyped.b.c\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"pkg_untyped.a.a_var\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            # Top-level Python file in site-packages\n            (\"standalone\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            (\"standalone.standalone_var\", ModuleNotFoundReason.FOUND_WITHOUT_TYPE_HINTS),\n            # Packages found by following .pth files\n            (\"baz_pkg\", self.path(\"baz\", \"baz_pkg\", \"__init__.py\")),\n            (\"ns_baz_pkg.a\", ModuleNotFoundReason.NOT_FOUND),\n            (\"neighbor_pkg\", self.path(\"..\", \"modulefinder-src\", \"neighbor_pkg\", \"__init__.py\")),\n            (\"ns_neighbor_pkg.a\", ModuleNotFoundReason.NOT_FOUND),\n            # Something that doesn't exist\n            (\"does_not_exist\", ModuleNotFoundReason.NOT_FOUND),\n            # A regular package with an installed set of stubs\n            (\"foo.bar\", self.path(\"foo-stubs\", \"bar.pyi\")),\n            # A regular, non-site-packages module\n            (\"a\", os.path.abspath(os.path.join(data_path, \"pkg1\", \"a.py\"))),\n        ]\n        for module, expected in cases:\n            template = \"Find(\" + module + \") got {}; expected {}\"\n\n            actual = self.fmc_nons.find_module(module)\n            assert_equal(actual, expected, template)\n"
  },
  {
    "path": "mypy/test/testmypyc.py",
    "content": "\"\"\"A basic check to make sure that we are using a mypyc-compiled version when expected.\"\"\"\n\nfrom __future__ import annotations\n\nimport filecmp\nimport os\nfrom unittest import TestCase\n\nimport mypy\nimport mypyc\n\n\nclass MypycTest(TestCase):\n    def test_using_mypyc(self) -> None:\n        if os.getenv(\"TEST_MYPYC\", None) == \"1\":\n            assert not mypy.__file__.endswith(\".py\"), \"Expected to find a mypyc-compiled version\"\n\n    def test_shared_files_consistent(self) -> None:\n        if os.getenv(\"TEST_MYPYC\", None) != \"1\":\n            mypyc_path = mypyc.__path__[0]\n            for f in [\"build_setup.py\"]:\n                assert filecmp.cmp(\n                    os.path.join(mypyc_path, f),\n                    os.path.join(mypyc_path, \"lib-rt\", f),\n                    shallow=False,\n                ), f\"Shared files inconsistent, run cp mypyc/{f} mypyc/lib-rt\"\n"
  },
  {
    "path": "mypy/test/testoutput.py",
    "content": "\"\"\"Test cases for `--output=json`.\n\nThese cannot be run by the usual unit test runner because of the backslashes in\nthe output, which get normalized to forward slashes by the test suite on Windows.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport os.path\n\nfrom mypy import api\nfrom mypy.defaults import PYTHON3_VERSION\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\n\n\nclass OutputJSONsuite(DataSuite):\n    files = [\"outputjson.test\"]\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_output_json(testcase)\n\n\ndef test_output_json(testcase: DataDrivenTestCase) -> None:\n    \"\"\"Runs Mypy in a subprocess, and ensures that `--output=json` works as intended.\"\"\"\n    mypy_cmdline = [\"--output=json\"]\n    mypy_cmdline.append(f\"--python-version={'.'.join(map(str, PYTHON3_VERSION))}\")\n\n    # Write the program to a file.\n    program_path = os.path.join(test_temp_dir, \"main\")\n    mypy_cmdline.append(program_path)\n    with open(program_path, \"w\", encoding=\"utf8\") as file:\n        for s in testcase.input:\n            file.write(f\"{s}\\n\")\n\n    output = []\n    # Type check the program.\n    out, err, returncode = api.run(mypy_cmdline)\n    # split lines, remove newlines, and remove directory of test case\n    for line in (out + err).rstrip(\"\\n\").splitlines():\n        if line.startswith(test_temp_dir + os.sep):\n            output.append(line[len(test_temp_dir + os.sep) :].rstrip(\"\\r\\n\"))\n        else:\n            output.append(line.rstrip(\"\\r\\n\"))\n\n    if returncode > 1:\n        output.append(\"!!! Mypy crashed !!!\")\n\n    # Remove temp file.\n    os.remove(program_path)\n\n    # JSON encodes every `\\` character into `\\\\`, so we need to remove `\\\\` from windows paths\n    # and `/` from POSIX paths\n    json_os_separator = os.sep.replace(\"\\\\\", \"\\\\\\\\\")\n    normalized_output = [line.replace(test_temp_dir + json_os_separator, \"\") for line in output]\n\n    assert normalized_output == testcase.output\n"
  },
  {
    "path": "mypy/test/testparse.py",
    "content": "\"\"\"Tests for the mypy parser.\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\n\nfrom pytest import skip\n\nfrom mypy import defaults\nfrom mypy.config_parser import parse_mypy_comments\nfrom mypy.errors import CompileError, Errors\nfrom mypy.options import Options\nfrom mypy.parse import parse\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, find_test_files, parse_options\nfrom mypy.util import get_mypy_comments\n\n\nclass ParserSuite(DataSuite):\n    required_out_section = True\n    base_path = \".\"\n    files = find_test_files(pattern=\"parse*.test\", exclude=[\"parse-errors.test\"])\n\n    if sys.version_info < (3, 12):\n        files.remove(\"parse-python312.test\")\n    if sys.version_info < (3, 13):\n        files.remove(\"parse-python313.test\")\n    if sys.version_info < (3, 14):\n        files.remove(\"parse-python314.test\")\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_parser(testcase)\n\n\ndef test_parser(testcase: DataDrivenTestCase) -> None:\n    \"\"\"Perform a single parser test case.\n\n    The argument contains the description of the test case.\n    \"\"\"\n    options = Options()\n    options.hide_error_codes = True\n\n    if testcase.file.endswith(\"python310.test\"):\n        options.python_version = (3, 10)\n    elif testcase.file.endswith(\"python312.test\"):\n        options.python_version = (3, 12)\n    elif testcase.file.endswith(\"python313.test\"):\n        options.python_version = (3, 13)\n    elif testcase.file.endswith(\"python314.test\"):\n        options.python_version = (3, 14)\n    else:\n        options.python_version = defaults.PYTHON3_VERSION\n\n    source = \"\\n\".join(testcase.input)\n\n    # Apply mypy: comments to options.\n    comments = get_mypy_comments(source)\n    changes, _ = parse_mypy_comments(comments, options)\n    options = options.apply_changes(changes)\n\n    try:\n        n = parse(\n            bytes(source, \"ascii\"),\n            fnam=\"main\",\n            module=\"__main__\",\n            errors=Errors(options),\n            options=options,\n            raise_on_error=True,\n        )\n        a = n.str_with_options(options).split(\"\\n\")\n    except CompileError as e:\n        a = e.messages\n    assert_string_arrays_equal(\n        testcase.output, a, f\"Invalid parser output ({testcase.file}, line {testcase.line})\"\n    )\n\n\n# The file name shown in test case output. This is displayed in error\n# messages, and must match the file name in the test case descriptions.\nINPUT_FILE_NAME = \"file\"\n\n\nclass ParseErrorSuite(DataSuite):\n    required_out_section = True\n    base_path = \".\"\n    files = [\"parse-errors.test\"]\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_parse_error(testcase)\n\n\ndef test_parse_error(testcase: DataDrivenTestCase) -> None:\n    try:\n        options = parse_options(\"\\n\".join(testcase.input), testcase, 0)\n        if options.python_version < defaults.PYTHON3_VERSION:\n            options.python_version = defaults.PYTHON3_VERSION\n        if options.python_version != sys.version_info[:2]:\n            skip()\n        # Compile temporary file. The test file contains non-ASCII characters.\n        parse(\n            bytes(\"\\n\".join(testcase.input), \"utf-8\"),\n            INPUT_FILE_NAME,\n            \"__main__\",\n            errors=Errors(options),\n            options=options,\n            raise_on_error=True,\n        )\n        raise AssertionError(\"No errors reported\")\n    except CompileError as e:\n        if e.module_with_blocker is not None:\n            assert e.module_with_blocker == \"__main__\"\n        # Verify that there was a compile error and that the error messages\n        # are equivalent.\n        assert_string_arrays_equal(\n            testcase.output,\n            e.messages,\n            f\"Invalid compiler output ({testcase.file}, line {testcase.line})\",\n        )\n"
  },
  {
    "path": "mypy/test/testpep561.py",
    "content": "from __future__ import annotations\n\nimport os\nimport re\nimport subprocess\nimport sys\nimport tempfile\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\n\nimport filelock\n\nimport mypy.api\nfrom mypy.test.config import package_path, pip_lock, pip_timeout, test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, perform_file_operations\n\n# NOTE: options.use_builtins_fixtures should not be set in these\n# tests, otherwise mypy will ignore installed third-party packages.\n\n\nclass PEP561Suite(DataSuite):\n    files = [\"pep561.test\"]\n    base_path = \".\"\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_pep561(testcase)\n\n\n@contextmanager\ndef virtualenv(python_executable: str = sys.executable) -> Iterator[tuple[str, str]]:\n    \"\"\"Context manager that creates a virtualenv in a temporary directory\n\n    Returns the path to the created Python executable\n    \"\"\"\n    with tempfile.TemporaryDirectory() as venv_dir:\n        proc = subprocess.run(\n            [python_executable, \"-m\", \"venv\", venv_dir], cwd=os.getcwd(), capture_output=True\n        )\n        if proc.returncode != 0:\n            err = proc.stdout.decode(\"utf-8\") + proc.stderr.decode(\"utf-8\")\n            raise Exception(\"Failed to create venv.\\n\" + err)\n        if sys.platform == \"win32\":\n            yield venv_dir, os.path.abspath(os.path.join(venv_dir, \"Scripts\", \"python\"))\n        else:\n            yield venv_dir, os.path.abspath(os.path.join(venv_dir, \"bin\", \"python\"))\n\n\ndef upgrade_pip(python_executable: str) -> None:\n    \"\"\"Install pip>=21.3.1. Required for editable installs with PEP 660.\"\"\"\n    if (\n        sys.version_info >= (3, 11)\n        or (3, 10, 3) <= sys.version_info < (3, 11)\n        or (3, 9, 11) <= sys.version_info < (3, 10)\n    ):\n        # Skip for more recent Python releases which come with pip>=21.3.1\n        # out of the box - for performance reasons.\n        return\n\n    install_cmd = [python_executable, \"-m\", \"pip\", \"install\", \"pip>=21.3.1\"]\n    try:\n        with filelock.FileLock(pip_lock, timeout=pip_timeout):\n            proc = subprocess.run(install_cmd, capture_output=True, env=os.environ)\n    except filelock.Timeout as err:\n        raise Exception(f\"Failed to acquire {pip_lock}\") from err\n    if proc.returncode != 0:\n        raise Exception(proc.stdout.decode(\"utf-8\") + proc.stderr.decode(\"utf-8\"))\n\n\ndef install_package(\n    pkg: str, python_executable: str = sys.executable, editable: bool = False\n) -> None:\n    \"\"\"Install a package from test-data/packages/pkg/\"\"\"\n    working_dir = os.path.join(package_path, pkg)\n    with tempfile.TemporaryDirectory() as dir:\n        install_cmd = [python_executable, \"-m\", \"pip\", \"install\"]\n        if editable:\n            install_cmd.append(\"-e\")\n        install_cmd.append(\".\")\n\n        # Note that newer versions of pip (21.3+) don't\n        # follow this env variable, but this is for compatibility\n        env = {\"PIP_BUILD\": dir}\n        # Inherit environment for Windows\n        env.update(os.environ)\n        try:\n            with filelock.FileLock(pip_lock, timeout=pip_timeout):\n                proc = subprocess.run(install_cmd, cwd=working_dir, capture_output=True, env=env)\n        except filelock.Timeout as err:\n            raise Exception(f\"Failed to acquire {pip_lock}\") from err\n    if proc.returncode != 0:\n        raise Exception(proc.stdout.decode(\"utf-8\") + proc.stderr.decode(\"utf-8\"))\n\n\ndef test_pep561(testcase: DataDrivenTestCase) -> None:\n    \"\"\"Test running mypy on files that depend on PEP 561 packages.\"\"\"\n    assert testcase.old_cwd is not None, \"test was not properly set up\"\n    python = sys.executable\n\n    assert python is not None, \"Should be impossible\"\n    pkgs, pip_args = parse_pkgs(testcase.input[0])\n    mypy_args = parse_mypy_args(testcase.input[1])\n    editable = False\n    for arg in pip_args:\n        if arg == \"editable\":\n            editable = True\n        else:\n            raise ValueError(f\"Unknown pip argument: {arg}\")\n    assert pkgs, \"No packages to install for PEP 561 test?\"\n    with virtualenv(python) as venv:\n        venv_dir, python_executable = venv\n        if editable:\n            # Editable installs with PEP 660 require pip>=21.3\n            upgrade_pip(python_executable)\n        for pkg in pkgs:\n            install_package(pkg, python_executable, editable)\n\n        cmd_line = list(mypy_args)\n        has_program = not (\"-p\" in cmd_line or \"--package\" in cmd_line)\n        if has_program:\n            program = testcase.name + \".py\"\n            with open(program, \"w\", encoding=\"utf-8\") as f:\n                for s in testcase.input:\n                    f.write(f\"{s}\\n\")\n            cmd_line.append(program)\n\n        cmd_line.extend([\"--no-error-summary\", \"--hide-error-codes\"])\n        if python_executable != sys.executable:\n            cmd_line.append(f\"--python-executable={python_executable}\")\n\n        steps = testcase.find_steps()\n        if steps != [[]]:\n            steps = [[]] + steps\n\n        for i, operations in enumerate(steps):\n            perform_file_operations(operations)\n\n            output = []\n            # Type check the module\n            out, err, returncode = mypy.api.run(cmd_line)\n\n            # split lines, remove newlines, and remove directory of test case\n            for line in (out + err).splitlines():\n                if line.startswith(test_temp_dir + os.sep):\n                    output.append(line[len(test_temp_dir + os.sep) :].rstrip(\"\\r\\n\"))\n                else:\n                    # Normalize paths so that the output is the same on Windows and Linux/macOS.\n                    # Yes, this is naive: replace all slashes preceding first colon, if any.\n                    path, *rest = line.split(\":\", maxsplit=1)\n                    if rest:\n                        path = path.replace(os.sep, \"/\")\n                    output.append(\":\".join([path, *rest]).rstrip(\"\\r\\n\"))\n            iter_count = \"\" if i == 0 else f\" on iteration {i + 1}\"\n            expected = testcase.output if i == 0 else testcase.output2.get(i + 1, [])\n\n            assert_string_arrays_equal(\n                expected,\n                output,\n                f\"Invalid output ({testcase.file}, line {testcase.line}){iter_count}\",\n            )\n\n        if has_program:\n            os.remove(program)\n\n\ndef parse_pkgs(comment: str) -> tuple[list[str], list[str]]:\n    if not comment.startswith(\"# pkgs:\"):\n        return ([], [])\n    else:\n        pkgs_str, *args = comment[7:].split(\";\")\n        return ([pkg.strip() for pkg in pkgs_str.split(\",\")], [arg.strip() for arg in args])\n\n\ndef parse_mypy_args(line: str) -> list[str]:\n    m = re.match(\"# flags: (.*)$\", line)\n    if not m:\n        return []  # No args; mypy will spit out an error.\n    return m.group(1).split()\n"
  },
  {
    "path": "mypy/test/testpythoneval.py",
    "content": "\"\"\"Test cases for running mypy programs using a Python interpreter.\n\nEach test case type checks a program then runs it using Python. The\noutput (stdout) of the program is compared to expected output. Type checking\nuses full builtins and other stubs.\n\nNote: Currently Python interpreter paths are hard coded.\n\nNote: These test cases are *not* included in the main test suite, as including\n      this suite would slow down the main suite too much.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport os.path\nimport re\nimport subprocess\nimport sys\nfrom tempfile import TemporaryDirectory\n\nfrom mypy import api\nfrom mypy.defaults import PYTHON3_VERSION\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, split_lines\n\n# Path to Python 3 interpreter\npython3_path = sys.executable\nprogram_re = re.compile(r\"\\b_program.py\\b\")\n\n\nclass PythonEvaluationSuite(DataSuite):\n    files = [\"pythoneval.test\", \"pythoneval-asyncio.test\"]\n    cache_dir = TemporaryDirectory()\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_python_evaluation(testcase, os.path.join(self.cache_dir.name, \".mypy_cache\"))\n\n\ndef test_python_evaluation(testcase: DataDrivenTestCase, cache_dir: str) -> None:\n    \"\"\"Runs Mypy in a subprocess.\n\n    If this passes without errors, executes the script again with a given Python\n    version.\n    \"\"\"\n    assert testcase.old_cwd is not None, \"test was not properly set up\"\n    # We must enable site packages to get access to installed stubs.\n    mypy_cmdline = [\n        \"--show-traceback\",\n        \"--no-silence-site-packages\",\n        \"--no-error-summary\",\n        \"--hide-error-codes\",\n        \"--allow-empty-bodies\",\n        \"--test-env\",  # Speeds up some checks\n    ]\n    interpreter = python3_path\n    mypy_cmdline.append(f\"--python-version={'.'.join(map(str, PYTHON3_VERSION))}\")\n\n    m = re.search(\"# flags: (.*)$\", \"\\n\".join(testcase.input), re.MULTILINE)\n    if m:\n        additional_flags = m.group(1).split()\n        for flag in additional_flags:\n            if flag.startswith(\"--python-version=\"):\n                targeted_python_version = flag.split(\"=\")[1]\n                targeted_major, targeted_minor = targeted_python_version.split(\".\")\n                if (int(targeted_major), int(targeted_minor)) > (\n                    sys.version_info.major,\n                    sys.version_info.minor,\n                ):\n                    return\n        mypy_cmdline.extend(additional_flags)\n\n    # Write the program to a file.\n    program = \"_\" + testcase.name + \".py\"\n    program_path = os.path.join(test_temp_dir, program)\n    mypy_cmdline.append(program_path)\n    with open(program_path, \"w\", encoding=\"utf8\") as file:\n        for s in testcase.input:\n            file.write(f\"{s}\\n\")\n    mypy_cmdline.append(f\"--cache-dir={cache_dir}\")\n    output = []\n    # Type check the program.\n    out, err, returncode = api.run(mypy_cmdline)\n    # split lines, remove newlines, and remove directory of test case\n    for line in (out + err).splitlines():\n        if line.startswith(test_temp_dir + os.sep):\n            output.append(line[len(test_temp_dir + os.sep) :].rstrip(\"\\r\\n\"))\n        else:\n            # Normalize paths so that the output is the same on Windows and Linux/macOS.\n            line = line.replace(test_temp_dir + os.sep, test_temp_dir + \"/\")\n            output.append(line.rstrip(\"\\r\\n\"))\n    if returncode > 1 and not testcase.output:\n        # Either api.run() doesn't work well in case of a crash, or pytest interferes with it.\n        # Tweak output to prevent tests with empty expected output to pass in case of a crash.\n        output.append(\"!!! Mypy crashed !!!\")\n    if returncode == 0 and not output:\n        # Execute the program.\n        proc = subprocess.run(\n            [interpreter, \"-Wignore\", program], cwd=test_temp_dir, capture_output=True\n        )\n        output.extend(split_lines(proc.stdout, proc.stderr))\n    # Remove temp file.\n    os.remove(program_path)\n    for i, line in enumerate(output):\n        if os.path.sep + \"typeshed\" + os.path.sep in line:\n            output[i] = line.split(os.path.sep)[-1]\n    assert_string_arrays_equal(\n        adapt_output(testcase), output, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n    )\n\n\ndef adapt_output(testcase: DataDrivenTestCase) -> list[str]:\n    \"\"\"Translates the generic _program.py into the actual filename.\"\"\"\n    program = \"_\" + testcase.name + \".py\"\n    return [program_re.sub(program, line) for line in testcase.output]\n"
  },
  {
    "path": "mypy/test/testreports.py",
    "content": "\"\"\"Test cases for reports generated by mypy.\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nimport sysconfig\nimport textwrap\n\nfrom mypy.report import CoberturaPackage, get_line_rate\nfrom mypy.test.helpers import Suite, assert_equal\n\ntry:\n    if sys.version_info >= (3, 14) and bool(sysconfig.get_config_var(\"Py_GIL_DISABLED\")):\n        # lxml doesn't support free-threading yet\n        lxml = None\n    else:\n        import lxml  # type: ignore[import-untyped]\nexcept ImportError:\n    lxml = None\n\nimport pytest\n\n\nclass CoberturaReportSuite(Suite):\n    @pytest.mark.skipif(lxml is None, reason=\"Cannot import lxml. Is it installed?\")\n    def test_get_line_rate(self) -> None:\n        assert_equal(\"1.0\", get_line_rate(0, 0))\n        assert_equal(\"0.3333\", get_line_rate(1, 3))\n\n    @pytest.mark.skipif(lxml is None, reason=\"Cannot import lxml. Is it installed?\")\n    def test_as_xml(self) -> None:\n        import lxml.etree as etree  # type: ignore[import-untyped]\n\n        cobertura_package = CoberturaPackage(\"foobar\")\n        cobertura_package.covered_lines = 21\n        cobertura_package.total_lines = 42\n\n        child_package = CoberturaPackage(\"raz\")\n        child_package.covered_lines = 10\n        child_package.total_lines = 10\n        child_package.classes[\"class\"] = etree.Element(\"class\")\n\n        cobertura_package.packages[\"raz\"] = child_package\n\n        expected_output = textwrap.dedent(\"\"\"\\\n            <package complexity=\"1.0\" name=\"foobar\" branch-rate=\"0\" line-rate=\"0.5000\">\n              <classes/>\n              <packages>\n                <package complexity=\"1.0\" name=\"raz\" branch-rate=\"0\" line-rate=\"1.0000\">\n                  <classes>\n                    <class/>\n                  </classes>\n                </package>\n              </packages>\n            </package>\n        \"\"\").encode(\"ascii\")\n        assert_equal(\n            expected_output, etree.tostring(cobertura_package.as_xml(), pretty_print=True)\n        )\n"
  },
  {
    "path": "mypy/test/testsemanal.py",
    "content": "\"\"\"Semantic analyzer test cases\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy import build\nfrom mypy.defaults import PYTHON3_VERSION\nfrom mypy.errors import CompileError\nfrom mypy.modulefinder import BuildSource\nfrom mypy.nodes import TypeInfo\nfrom mypy.options import Options\nfrom mypy.strconv import StrConv\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import (\n    assert_string_arrays_equal,\n    find_test_files,\n    normalize_error_messages,\n    parse_options,\n    testfile_pyversion,\n)\n\n# Semantic analyzer test cases: dump parse tree\n# Semantic analysis test case description files.\nfrom mypy.types import TypeStrVisitor\n\nsemanal_files = find_test_files(\n    pattern=\"semanal-*.test\",\n    exclude=[\n        \"semanal-errors.test\",\n        \"semanal-errors-python310.test\",\n        \"semanal-typeinfo.test\",\n        \"semanal-symtable.test\",\n    ],\n)\n\n\ndef get_semanal_options(program_text: str, testcase: DataDrivenTestCase) -> Options:\n    options = parse_options(program_text, testcase, 1)\n    options.use_builtins_fixtures = True\n    options.semantic_analysis_only = True\n    options.show_traceback = True\n    options.python_version = PYTHON3_VERSION\n    options.reveal_verbose_types = True\n    return options\n\n\nclass SemAnalSuite(DataSuite):\n    files = semanal_files\n    native_sep = True\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_semanal(testcase)\n\n\ndef test_semanal(testcase: DataDrivenTestCase) -> None:\n    \"\"\"Perform a semantic analysis test case.\n\n    The testcase argument contains a description of the test case\n    (inputs and output).\n    \"\"\"\n\n    try:\n        src = \"\\n\".join(testcase.input)\n        options = get_semanal_options(src, testcase)\n        options.python_version = testfile_pyversion(testcase.file)\n        result = build.build(\n            sources=[BuildSource(\"main\", None, src)], options=options, alt_lib_path=test_temp_dir\n        )\n        a = result.errors\n        if a:\n            raise CompileError(a)\n        # Include string representations of the source files in the actual\n        # output.\n        for module in sorted(result.files.keys()):\n            if module in testcase.test_modules:\n                a += result.files[module].str_with_options(options).split(\"\\n\")\n    except CompileError as e:\n        a = e.messages\n    if testcase.normalize_output:\n        a = normalize_error_messages(a)\n    assert_string_arrays_equal(\n        testcase.output,\n        a,\n        f\"Invalid semantic analyzer output ({testcase.file}, line {testcase.line})\",\n    )\n\n\n# Semantic analyzer error test cases\n\n\nclass SemAnalErrorSuite(DataSuite):\n    files = [\"semanal-errors.test\", \"semanal-errors-python310.test\"]\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_semanal_error(testcase)\n\n\ndef test_semanal_error(testcase: DataDrivenTestCase) -> None:\n    \"\"\"Perform a test case.\"\"\"\n\n    try:\n        src = \"\\n\".join(testcase.input)\n        res = build.build(\n            sources=[BuildSource(\"main\", None, src)],\n            options=get_semanal_options(src, testcase),\n            alt_lib_path=test_temp_dir,\n        )\n        a = res.errors\n    except CompileError as e:\n        # Verify that there was a compile error and that the error messages\n        # are equivalent.\n        a = e.messages\n    if testcase.normalize_output:\n        a = normalize_error_messages(a)\n    assert_string_arrays_equal(\n        testcase.output, a, f\"Invalid compiler output ({testcase.file}, line {testcase.line})\"\n    )\n\n\n# SymbolNode table export test cases\n\n\nclass SemAnalSymtableSuite(DataSuite):\n    required_out_section = True\n    files = [\"semanal-symtable.test\"]\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        \"\"\"Perform a test case.\"\"\"\n        try:\n            # Build test case input.\n            src = \"\\n\".join(testcase.input)\n            result = build.build(\n                sources=[BuildSource(\"main\", None, src)],\n                options=get_semanal_options(src, testcase),\n                alt_lib_path=test_temp_dir,\n            )\n            # The output is the symbol table converted into a string.\n            a = result.errors\n            if a:\n                raise CompileError(a)\n            for module in sorted(result.files.keys()):\n                if module in testcase.test_modules:\n                    a.append(f\"{module}:\")\n                    for s in str(result.files[module].names).split(\"\\n\"):\n                        a.append(\"  \" + s)\n        except CompileError as e:\n            a = e.messages\n        assert_string_arrays_equal(\n            testcase.output,\n            a,\n            f\"Invalid semantic analyzer output ({testcase.file}, line {testcase.line})\",\n        )\n\n\n# Type info export test cases\nclass SemAnalTypeInfoSuite(DataSuite):\n    required_out_section = True\n    files = [\"semanal-typeinfo.test\"]\n\n    def setup(self) -> None:\n        super().setup()\n        self.str_conv = StrConv(options=Options())\n        self.type_str_conv = TypeStrVisitor(options=Options())\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        \"\"\"Perform a test case.\"\"\"\n        src = \"\\n\".join(testcase.input)\n        options = get_semanal_options(src, testcase)\n        self.str_conv.options = options\n        self.type_str_conv.options = options\n        try:\n            # Build test case input.\n            result = build.build(\n                sources=[BuildSource(\"main\", None, src)],\n                options=options,\n                alt_lib_path=test_temp_dir,\n            )\n            a = result.errors\n            if a:\n                raise CompileError(a)\n\n            # Collect all TypeInfos in top-level modules.\n            typeinfos = TypeInfoMap()\n            for module, file in result.files.items():\n                if module in testcase.test_modules:\n                    for n in file.names.values():\n                        if isinstance(n.node, TypeInfo):\n                            assert n.fullname\n                            if any(n.fullname.startswith(m + \".\") for m in testcase.test_modules):\n                                typeinfos[n.fullname] = n.node\n\n            # The output is the symbol table converted into a string.\n            a = typeinfos.dump(self.str_conv, self.type_str_conv).split(\"\\n\")\n        except CompileError as e:\n            a = e.messages\n        assert_string_arrays_equal(\n            testcase.output,\n            a,\n            f\"Invalid semantic analyzer output ({testcase.file}, line {testcase.line})\",\n        )\n\n\nclass TypeInfoMap(dict[str, TypeInfo]):\n    def dump(self, str_conv: StrConv, type_str_conv: TypeStrVisitor) -> str:\n        a: list[str] = [\"TypeInfoMap(\"]\n        for x, y in sorted(self.items()):\n            ti = (\"\\n\" + \"  \").join(y.dump(str_conv, type_str_conv).split(\"\\n\"))\n            a.append(f\"  {x} : {ti}\")\n        a[-1] += \")\"\n        return \"\\n\".join(a)\n"
  },
  {
    "path": "mypy/test/testsolve.py",
    "content": "\"\"\"Test cases for the constraint solver used in type inference.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.constraints import SUBTYPE_OF, SUPERTYPE_OF, Constraint\nfrom mypy.solve import Bounds, Graph, solve_constraints, transitive_closure\nfrom mypy.test.helpers import Suite, assert_equal\nfrom mypy.test.typefixture import TypeFixture\nfrom mypy.types import Type, TypeVarId, TypeVarLikeType, TypeVarType\n\n\nclass SolveSuite(Suite):\n    def setUp(self) -> None:\n        self.fx = TypeFixture()\n\n    def test_empty_input(self) -> None:\n        self.assert_solve([], [], [])\n\n    def test_simple_supertype_constraints(self) -> None:\n        self.assert_solve([self.fx.t], [self.supc(self.fx.t, self.fx.a)], [self.fx.a])\n        self.assert_solve(\n            [self.fx.t],\n            [self.supc(self.fx.t, self.fx.a), self.supc(self.fx.t, self.fx.b)],\n            [self.fx.a],\n        )\n\n    def test_simple_subtype_constraints(self) -> None:\n        self.assert_solve([self.fx.t], [self.subc(self.fx.t, self.fx.a)], [self.fx.a])\n        self.assert_solve(\n            [self.fx.t],\n            [self.subc(self.fx.t, self.fx.a), self.subc(self.fx.t, self.fx.b)],\n            [self.fx.b],\n        )\n\n    def test_both_kinds_of_constraints(self) -> None:\n        self.assert_solve(\n            [self.fx.t],\n            [self.supc(self.fx.t, self.fx.b), self.subc(self.fx.t, self.fx.a)],\n            [self.fx.b],\n        )\n\n    def test_unsatisfiable_constraints(self) -> None:\n        # The constraints are impossible to satisfy.\n        self.assert_solve(\n            [self.fx.t], [self.supc(self.fx.t, self.fx.a), self.subc(self.fx.t, self.fx.b)], [None]\n        )\n\n    def test_exactly_specified_result(self) -> None:\n        self.assert_solve(\n            [self.fx.t],\n            [self.supc(self.fx.t, self.fx.b), self.subc(self.fx.t, self.fx.b)],\n            [self.fx.b],\n        )\n\n    def test_multiple_variables(self) -> None:\n        self.assert_solve(\n            [self.fx.t, self.fx.s],\n            [\n                self.supc(self.fx.t, self.fx.b),\n                self.supc(self.fx.s, self.fx.c),\n                self.subc(self.fx.t, self.fx.a),\n            ],\n            [self.fx.b, self.fx.c],\n        )\n\n    def test_no_constraints_for_var(self) -> None:\n        self.assert_solve([self.fx.t], [], [self.fx.a_uninhabited])\n        self.assert_solve(\n            [self.fx.t, self.fx.s], [], [self.fx.a_uninhabited, self.fx.a_uninhabited]\n        )\n        self.assert_solve(\n            [self.fx.t, self.fx.s],\n            [self.supc(self.fx.s, self.fx.a)],\n            [self.fx.a_uninhabited, self.fx.a],\n        )\n\n    def test_simple_constraints_with_dynamic_type(self) -> None:\n        self.assert_solve([self.fx.t], [self.supc(self.fx.t, self.fx.anyt)], [self.fx.anyt])\n        self.assert_solve(\n            [self.fx.t],\n            [self.supc(self.fx.t, self.fx.anyt), self.supc(self.fx.t, self.fx.anyt)],\n            [self.fx.anyt],\n        )\n        self.assert_solve(\n            [self.fx.t],\n            [self.supc(self.fx.t, self.fx.anyt), self.supc(self.fx.t, self.fx.a)],\n            [self.fx.anyt],\n        )\n\n        self.assert_solve([self.fx.t], [self.subc(self.fx.t, self.fx.anyt)], [self.fx.anyt])\n        self.assert_solve(\n            [self.fx.t],\n            [self.subc(self.fx.t, self.fx.anyt), self.subc(self.fx.t, self.fx.anyt)],\n            [self.fx.anyt],\n        )\n        # self.assert_solve([self.fx.t],\n        #                   [self.subc(self.fx.t, self.fx.anyt),\n        #                    self.subc(self.fx.t, self.fx.a)],\n        #                   [self.fx.anyt])\n        # TODO: figure out what this should be after changes to meet(any, X)\n\n    def test_both_normal_and_any_types_in_results(self) -> None:\n        # If one of the bounds is any, we promote the other bound to\n        # any as well, since otherwise the type range does not make sense.\n        self.assert_solve(\n            [self.fx.t],\n            [self.supc(self.fx.t, self.fx.a), self.subc(self.fx.t, self.fx.anyt)],\n            [self.fx.anyt],\n        )\n\n        self.assert_solve(\n            [self.fx.t],\n            [self.supc(self.fx.t, self.fx.anyt), self.subc(self.fx.t, self.fx.a)],\n            [self.fx.anyt],\n        )\n\n    def test_poly_no_constraints(self) -> None:\n        self.assert_solve(\n            [self.fx.t, self.fx.u],\n            [],\n            [self.fx.a_uninhabited, self.fx.a_uninhabited],\n            allow_polymorphic=True,\n        )\n\n    def test_poly_trivial_free(self) -> None:\n        self.assert_solve(\n            [self.fx.t, self.fx.u],\n            [self.subc(self.fx.t, self.fx.a)],\n            [self.fx.a, self.fx.u],\n            [self.fx.u],\n            allow_polymorphic=True,\n        )\n\n    def test_poly_free_pair(self) -> None:\n        self.assert_solve(\n            [self.fx.t, self.fx.u],\n            [self.subc(self.fx.t, self.fx.u)],\n            [self.fx.t, self.fx.t],\n            [self.fx.t],\n            allow_polymorphic=True,\n        )\n\n    def test_poly_free_pair_with_bounds(self) -> None:\n        t_prime = self.fx.t.copy_modified(upper_bound=self.fx.b)\n        self.assert_solve(\n            [self.fx.t, self.fx.ub],\n            [self.subc(self.fx.t, self.fx.ub)],\n            [t_prime, t_prime],\n            [t_prime],\n            allow_polymorphic=True,\n        )\n\n    def test_poly_free_pair_with_bounds_uninhabited(self) -> None:\n        self.assert_solve(\n            [self.fx.ub, self.fx.uc],\n            [self.subc(self.fx.ub, self.fx.uc)],\n            [self.fx.a_uninhabited, self.fx.a_uninhabited],\n            [],\n            allow_polymorphic=True,\n        )\n\n    def test_poly_bounded_chain(self) -> None:\n        # B <: T <: U <: S <: A\n        self.assert_solve(\n            [self.fx.t, self.fx.u, self.fx.s],\n            [\n                self.supc(self.fx.t, self.fx.b),\n                self.subc(self.fx.t, self.fx.u),\n                self.subc(self.fx.u, self.fx.s),\n                self.subc(self.fx.s, self.fx.a),\n            ],\n            [self.fx.b, self.fx.b, self.fx.b],\n            allow_polymorphic=True,\n        )\n\n    def test_poly_reverse_overlapping_chain(self) -> None:\n        # A :> T <: S :> B\n        self.assert_solve(\n            [self.fx.t, self.fx.s],\n            [\n                self.subc(self.fx.t, self.fx.s),\n                self.subc(self.fx.t, self.fx.a),\n                self.supc(self.fx.s, self.fx.b),\n            ],\n            [self.fx.a, self.fx.a],\n            allow_polymorphic=True,\n        )\n\n    def test_poly_reverse_split_chain(self) -> None:\n        # B :> T <: S :> A\n        self.assert_solve(\n            [self.fx.t, self.fx.s],\n            [\n                self.subc(self.fx.t, self.fx.s),\n                self.subc(self.fx.t, self.fx.b),\n                self.supc(self.fx.s, self.fx.a),\n            ],\n            [self.fx.b, self.fx.a],\n            allow_polymorphic=True,\n        )\n\n    def test_poly_unsolvable_chain(self) -> None:\n        # A <: T <: U <: S <: B\n        self.assert_solve(\n            [self.fx.t, self.fx.u, self.fx.s],\n            [\n                self.supc(self.fx.t, self.fx.a),\n                self.subc(self.fx.t, self.fx.u),\n                self.subc(self.fx.u, self.fx.s),\n                self.subc(self.fx.s, self.fx.b),\n            ],\n            [None, None, None],\n            allow_polymorphic=True,\n        )\n\n    def test_simple_chain_closure(self) -> None:\n        self.assert_transitive_closure(\n            [self.fx.t.id, self.fx.s.id],\n            [\n                self.supc(self.fx.t, self.fx.b),\n                self.subc(self.fx.t, self.fx.s),\n                self.subc(self.fx.s, self.fx.a),\n            ],\n            {(self.fx.t.id, self.fx.s.id)},\n            {self.fx.t.id: {self.fx.b}, self.fx.s.id: {self.fx.b}},\n            {self.fx.t.id: {self.fx.a}, self.fx.s.id: {self.fx.a}},\n        )\n\n    def test_reverse_chain_closure(self) -> None:\n        self.assert_transitive_closure(\n            [self.fx.t.id, self.fx.s.id],\n            [\n                self.subc(self.fx.t, self.fx.s),\n                self.subc(self.fx.t, self.fx.a),\n                self.supc(self.fx.s, self.fx.b),\n            ],\n            {(self.fx.t.id, self.fx.s.id)},\n            {self.fx.t.id: set(), self.fx.s.id: {self.fx.b}},\n            {self.fx.t.id: {self.fx.a}, self.fx.s.id: set()},\n        )\n\n    def test_secondary_constraint_closure(self) -> None:\n        self.assert_transitive_closure(\n            [self.fx.t.id, self.fx.s.id],\n            [self.supc(self.fx.s, self.fx.gt), self.subc(self.fx.s, self.fx.ga)],\n            set(),\n            {self.fx.t.id: set(), self.fx.s.id: {self.fx.gt}},\n            {self.fx.t.id: {self.fx.a}, self.fx.s.id: {self.fx.ga}},\n        )\n\n    def assert_solve(\n        self,\n        vars: list[TypeVarLikeType],\n        constraints: list[Constraint],\n        results: list[None | Type],\n        free_vars: list[TypeVarLikeType] | None = None,\n        allow_polymorphic: bool = False,\n    ) -> None:\n        if free_vars is None:\n            free_vars = []\n        actual, actual_free = solve_constraints(\n            vars, constraints, allow_polymorphic=allow_polymorphic\n        )\n        assert_equal(actual, results)\n        assert_equal(actual_free, free_vars)\n\n    def assert_transitive_closure(\n        self,\n        vars: list[TypeVarId],\n        constraints: list[Constraint],\n        graph: Graph,\n        lowers: Bounds,\n        uppers: Bounds,\n    ) -> None:\n        actual_graph, actual_lowers, actual_uppers = transitive_closure(vars, constraints)\n        # Add trivial elements.\n        for v in vars:\n            graph.add((v, v))\n        assert_equal(actual_graph, graph)\n        assert_equal(dict(actual_lowers), lowers)\n        assert_equal(dict(actual_uppers), uppers)\n\n    def supc(self, type_var: TypeVarType, bound: Type) -> Constraint:\n        return Constraint(type_var, SUPERTYPE_OF, bound)\n\n    def subc(self, type_var: TypeVarType, bound: Type) -> Constraint:\n        return Constraint(type_var, SUBTYPE_OF, bound)\n"
  },
  {
    "path": "mypy/test/teststubgen.py",
    "content": "from __future__ import annotations\n\nimport io\nimport os.path\nimport re\nimport shutil\nimport sys\nimport tempfile\nimport unittest\nfrom types import ModuleType\nfrom typing import Any\n\nimport pytest\n\nfrom mypy.errors import CompileError\nfrom mypy.moduleinspect import InspectError, ModuleInspect\nfrom mypy.stubdoc import (\n    ArgSig,\n    FunctionSig,\n    build_signature,\n    find_unique_signatures,\n    infer_arg_sig_from_anon_docstring,\n    infer_prop_type_from_docstring,\n    infer_sig_from_docstring,\n    is_valid_type,\n    parse_all_signatures,\n    parse_signature,\n)\nfrom mypy.stubgen import (\n    Options,\n    collect_build_targets,\n    generate_stubs,\n    is_blacklisted_path,\n    is_non_library_module,\n    mypy_options,\n    parse_options,\n)\nfrom mypy.stubgenc import InspectionStubGenerator, infer_c_method_args\nfrom mypy.stubutil import (\n    ClassInfo,\n    FunctionContext,\n    common_dir_prefix,\n    infer_method_ret_type,\n    remove_misplaced_type_comments,\n    walk_packages,\n)\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_equal, assert_string_arrays_equal, local_sys_path_set\n\n\nclass StubgenCmdLineSuite(unittest.TestCase):\n    \"\"\"Test cases for processing command-line options and finding files.\"\"\"\n\n    @unittest.skipIf(sys.platform == \"win32\", \"clean up fails on Windows\")\n    def test_files_found(self) -> None:\n        current = os.getcwd()\n        with tempfile.TemporaryDirectory() as tmp:\n            try:\n                os.chdir(tmp)\n                os.mkdir(\"subdir\")\n                self.make_file(\"subdir\", \"a.py\")\n                self.make_file(\"subdir\", \"b.py\")\n                os.mkdir(os.path.join(\"subdir\", \"pack\"))\n                self.make_file(\"subdir\", \"pack\", \"__init__.py\")\n                opts = parse_options([\"subdir\"])\n                py_mods, pyi_mods, c_mods = collect_build_targets(opts, mypy_options(opts))\n                assert_equal(pyi_mods, [])\n                assert_equal(c_mods, [])\n                files = {mod.path for mod in py_mods}\n                assert_equal(\n                    files,\n                    {\n                        os.path.join(\"subdir\", \"pack\", \"__init__.py\"),\n                        os.path.join(\"subdir\", \"a.py\"),\n                        os.path.join(\"subdir\", \"b.py\"),\n                    },\n                )\n            finally:\n                os.chdir(current)\n\n    @unittest.skipIf(sys.platform == \"win32\", \"clean up fails on Windows\")\n    def test_packages_found(self) -> None:\n        current = os.getcwd()\n        with tempfile.TemporaryDirectory() as tmp:\n            try:\n                os.chdir(tmp)\n                os.mkdir(\"pack\")\n                self.make_file(\"pack\", \"__init__.py\", content=\"from . import a, b\")\n                self.make_file(\"pack\", \"a.py\")\n                self.make_file(\"pack\", \"b.py\")\n                opts = parse_options([\"-p\", \"pack\"])\n                py_mods, pyi_mods, c_mods = collect_build_targets(opts, mypy_options(opts))\n                assert_equal(pyi_mods, [])\n                assert_equal(c_mods, [])\n                files = {os.path.relpath(mod.path or \"FAIL\") for mod in py_mods}\n                assert_equal(\n                    files,\n                    {\n                        os.path.join(\"pack\", \"__init__.py\"),\n                        os.path.join(\"pack\", \"a.py\"),\n                        os.path.join(\"pack\", \"b.py\"),\n                    },\n                )\n            finally:\n                os.chdir(current)\n\n    @unittest.skipIf(sys.platform == \"win32\", \"clean up fails on Windows\")\n    def test_module_not_found(self) -> None:\n        current = os.getcwd()\n        captured_output = io.StringIO()\n        sys.stdout = captured_output\n        with tempfile.TemporaryDirectory() as tmp:\n            try:\n                os.chdir(tmp)\n                self.make_file(tmp, \"mymodule.py\", content=\"import a\")\n                opts = parse_options([\"-m\", \"mymodule\"])\n                collect_build_targets(opts, mypy_options(opts))\n                assert captured_output.getvalue() == \"\"\n            finally:\n                sys.stdout = sys.__stdout__\n                os.chdir(current)\n\n    def make_file(self, *path: str, content: str = \"\") -> None:\n        file = os.path.join(*path)\n        with open(file, \"w\") as f:\n            f.write(content)\n\n    def run(self, result: Any | None = None) -> Any | None:\n        with local_sys_path_set():\n            return super().run(result)\n\n\nclass StubgenCliParseSuite(unittest.TestCase):\n    def test_walk_packages(self) -> None:\n        with ModuleInspect() as m:\n            assert_equal(set(walk_packages(m, [\"mypy.errors\"])), {\"mypy.errors\"})\n\n            assert_equal(\n                set(walk_packages(m, [\"mypy.errors\", \"mypy.stubgen\"])),\n                {\"mypy.errors\", \"mypy.stubgen\"},\n            )\n\n            all_mypy_packages = set(walk_packages(m, [\"mypy\"]))\n            self.assertTrue(\n                all_mypy_packages.issuperset(\n                    {\"mypy\", \"mypy.errors\", \"mypy.stubgen\", \"mypy.test\", \"mypy.test.helpers\"}\n                )\n            )\n\n\nclass StubgenUtilSuite(unittest.TestCase):\n    \"\"\"Unit tests for stubgen utility functions.\"\"\"\n\n    def test_parse_signature(self) -> None:\n        self.assert_parse_signature(\"func()\", (\"func\", [], []))\n\n    def test_parse_signature_with_args(self) -> None:\n        self.assert_parse_signature(\"func(arg)\", (\"func\", [\"arg\"], []))\n        self.assert_parse_signature(\"do(arg, arg2)\", (\"do\", [\"arg\", \"arg2\"], []))\n\n    def test_parse_signature_with_optional_args(self) -> None:\n        self.assert_parse_signature(\"func([arg])\", (\"func\", [], [\"arg\"]))\n        self.assert_parse_signature(\"func(arg[, arg2])\", (\"func\", [\"arg\"], [\"arg2\"]))\n        self.assert_parse_signature(\"func([arg[, arg2]])\", (\"func\", [], [\"arg\", \"arg2\"]))\n\n    def test_parse_signature_with_default_arg(self) -> None:\n        self.assert_parse_signature(\"func(arg=None)\", (\"func\", [], [\"arg\"]))\n        self.assert_parse_signature(\"func(arg, arg2=None)\", (\"func\", [\"arg\"], [\"arg2\"]))\n        self.assert_parse_signature('func(arg=1, arg2=\"\")', (\"func\", [], [\"arg\", \"arg2\"]))\n\n    def test_parse_signature_with_qualified_function(self) -> None:\n        self.assert_parse_signature(\"ClassName.func(arg)\", (\"func\", [\"arg\"], []))\n\n    def test_parse_signature_with_kw_only_arg(self) -> None:\n        self.assert_parse_signature(\n            \"ClassName.func(arg, *, arg2=1)\", (\"func\", [\"arg\", \"*\"], [\"arg2\"])\n        )\n\n    def test_parse_signature_with_star_arg(self) -> None:\n        self.assert_parse_signature(\"ClassName.func(arg, *args)\", (\"func\", [\"arg\", \"*args\"], []))\n\n    def test_parse_signature_with_star_star_arg(self) -> None:\n        self.assert_parse_signature(\"ClassName.func(arg, **args)\", (\"func\", [\"arg\", \"**args\"], []))\n\n    def assert_parse_signature(self, sig: str, result: tuple[str, list[str], list[str]]) -> None:\n        assert_equal(parse_signature(sig), result)\n\n    def test_build_signature(self) -> None:\n        assert_equal(build_signature([], []), \"()\")\n        assert_equal(build_signature([\"arg\"], []), \"(arg)\")\n        assert_equal(build_signature([\"arg\", \"arg2\"], []), \"(arg, arg2)\")\n        assert_equal(build_signature([\"arg\"], [\"arg2\"]), \"(arg, arg2=...)\")\n        assert_equal(build_signature([\"arg\"], [\"arg2\", \"**x\"]), \"(arg, arg2=..., **x)\")\n\n    def test_parse_all_signatures(self) -> None:\n        assert_equal(\n            parse_all_signatures(\n                [\n                    \"random text\",\n                    \".. function:: fn(arg\",\n                    \".. function:: fn()\",\n                    \"  .. method:: fn2(arg)\",\n                ]\n            ),\n            ([(\"fn\", \"()\"), (\"fn2\", \"(arg)\")], []),\n        )\n\n    def test_find_unique_signatures(self) -> None:\n        assert_equal(\n            find_unique_signatures(\n                [\n                    (\"func\", \"()\"),\n                    (\"func\", \"()\"),\n                    (\"func2\", \"()\"),\n                    (\"func2\", \"(arg)\"),\n                    (\"func3\", \"(arg, arg2)\"),\n                ]\n            ),\n            [(\"func\", \"()\"), (\"func3\", \"(arg, arg2)\")],\n        )\n\n    def test_infer_sig_from_docstring(self) -> None:\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x) - y\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\")], ret_type=\"Any\")],\n        )\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x)\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\")], ret_type=\"Any\")],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x, Y_a=None)\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\",\n                    args=[ArgSig(name=\"x\"), ArgSig(name=\"Y_a\", default=True)],\n                    ret_type=\"Any\",\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x, Y_a=3)\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\",\n                    args=[ArgSig(name=\"x\"), ArgSig(name=\"Y_a\", default=True)],\n                    ret_type=\"Any\",\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x, Y_a=[1, 2, 3])\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\",\n                    args=[ArgSig(name=\"x\"), ArgSig(name=\"Y_a\", default=True)],\n                    ret_type=\"Any\",\n                )\n            ],\n        )\n\n        assert_equal(infer_sig_from_docstring(\"\\nafunc(x) - y\", \"func\"), [])\n        assert_equal(infer_sig_from_docstring(\"\\nfunc(x, y\", \"func\"), [])\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x=z(y))\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\", default=True)], ret_type=\"Any\")],\n        )\n\n        assert_equal(infer_sig_from_docstring(\"\\nfunc x\", \"func\"), [])\n        # Try to infer signature from type annotation.\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x: int)\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\", type=\"int\")], ret_type=\"Any\")],\n        )\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x: int=3)\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\", args=[ArgSig(name=\"x\", type=\"int\", default=True)], ret_type=\"Any\"\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x=3)\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\", args=[ArgSig(name=\"x\", type=None, default=True)], ret_type=\"Any\"\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc() -> int\", \"func\"),\n            [FunctionSig(name=\"func\", args=[], ret_type=\"int\")],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x: int=3) -> int\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\", args=[ArgSig(name=\"x\", type=\"int\", default=True)], ret_type=\"int\"\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x: int=3) -> int   \\n\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\", args=[ArgSig(name=\"x\", type=\"int\", default=True)], ret_type=\"int\"\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x: Tuple[int, str]) -> str\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\", args=[ArgSig(name=\"x\", type=\"Tuple[int,str]\")], ret_type=\"str\"\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\n                \"\\nfunc(x: Tuple[int, Tuple[str, int], str], y: int) -> str\", \"func\"\n            ),\n            [\n                FunctionSig(\n                    name=\"func\",\n                    args=[\n                        ArgSig(name=\"x\", type=\"Tuple[int,Tuple[str,int],str]\"),\n                        ArgSig(name=\"y\", type=\"int\"),\n                    ],\n                    ret_type=\"str\",\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x: foo.bar)\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\", type=\"foo.bar\")], ret_type=\"Any\")],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x: list=[1,2,[3,4]])\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\", args=[ArgSig(name=\"x\", type=\"list\", default=True)], ret_type=\"Any\"\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring('\\nfunc(x: str=\"nasty[\")', \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\", args=[ArgSig(name=\"x\", type=\"str\", default=True)], ret_type=\"Any\"\n                )\n            ],\n        )\n\n        assert_equal(infer_sig_from_docstring(\"\\nfunc[(x: foo.bar, invalid]\", \"func\"), [])\n\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x: invalid::type<with_template>)\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\", type=None)], ret_type=\"Any\")],\n        )\n\n        assert_equal(infer_sig_from_docstring(\"\\nfunc(invalid::type)\", \"func\"), [])\n\n        assert_equal(\n            infer_sig_from_docstring('\\nfunc(x: str=\"\")', \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\", args=[ArgSig(name=\"x\", type=\"str\", default=True)], ret_type=\"Any\"\n                )\n            ],\n        )\n\n    def test_infer_sig_from_docstring_duplicate_args(self) -> None:\n        assert_equal(\n            infer_sig_from_docstring(\"\\nfunc(x, x) -> str\\nfunc(x, y) -> int\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\"), ArgSig(name=\"y\")], ret_type=\"int\")],\n        )\n\n    def test_infer_sig_from_docstring_bad_indentation(self) -> None:\n        assert_equal(\n            infer_sig_from_docstring(\n                \"\"\"\n            x\n              x\n             x\n            \"\"\",\n                \"func\",\n            ),\n            None,\n        )\n\n    def test_infer_sig_from_docstring_args_kwargs(self) -> None:\n        assert_equal(\n            infer_sig_from_docstring(\"func(*args, **kwargs) -> int\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\",\n                    args=[ArgSig(name=\"*args\"), ArgSig(name=\"**kwargs\")],\n                    ret_type=\"int\",\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(*args) -> int\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"*args\")], ret_type=\"int\")],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(**kwargs) -> int\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"**kwargs\")], ret_type=\"int\")],\n        )\n\n    @pytest.mark.xfail(\n        raises=AssertionError, reason=\"Arg and kwarg signature validation not implemented yet\"\n    )\n    def test_infer_sig_from_docstring_args_kwargs_errors(self) -> None:\n        # Double args\n        assert_equal(infer_sig_from_docstring(\"func(*args, *args2) -> int\", \"func\"), [])\n\n        # Double kwargs\n        assert_equal(infer_sig_from_docstring(\"func(**kw, **kw2) -> int\", \"func\"), [])\n\n        # args after kwargs\n        assert_equal(infer_sig_from_docstring(\"func(**kwargs, *args) -> int\", \"func\"), [])\n\n    def test_infer_sig_from_docstring_positional_only_arguments(self) -> None:\n        assert_equal(\n            infer_sig_from_docstring(\"func(self, /) -> str\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"self\")], ret_type=\"str\")],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(self, x, /) -> str\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\", args=[ArgSig(name=\"self\"), ArgSig(name=\"x\")], ret_type=\"str\"\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(x, /, y) -> int\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\"), ArgSig(name=\"y\")], ret_type=\"int\")],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(x, /, *args) -> str\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\", args=[ArgSig(name=\"x\"), ArgSig(name=\"*args\")], ret_type=\"str\"\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(x, /, *, kwonly, **kwargs) -> str\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\",\n                    args=[ArgSig(name=\"x\"), ArgSig(name=\"kwonly\"), ArgSig(name=\"**kwargs\")],\n                    ret_type=\"str\",\n                )\n            ],\n        )\n\n    def test_infer_sig_from_docstring_keyword_only_arguments(self) -> None:\n        assert_equal(\n            infer_sig_from_docstring(\"func(*, x) -> str\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\")], ret_type=\"str\")],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(x, *, y) -> str\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\"), ArgSig(name=\"y\")], ret_type=\"str\")],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(*, x, y) -> str\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\"), ArgSig(name=\"y\")], ret_type=\"str\")],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(x, *, kwonly, **kwargs) -> str\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\",\n                    args=[ArgSig(name=\"x\"), ArgSig(name=\"kwonly\"), ArgSig(\"**kwargs\")],\n                    ret_type=\"str\",\n                )\n            ],\n        )\n\n    def test_infer_sig_from_docstring_pos_only_and_keyword_only_arguments(self) -> None:\n        assert_equal(\n            infer_sig_from_docstring(\"func(x, /, *, y) -> str\", \"func\"),\n            [FunctionSig(name=\"func\", args=[ArgSig(name=\"x\"), ArgSig(name=\"y\")], ret_type=\"str\")],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(x,  /, y,  *, z) -> str\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\",\n                    args=[ArgSig(name=\"x\"), ArgSig(name=\"y\"), ArgSig(name=\"z\")],\n                    ret_type=\"str\",\n                )\n            ],\n        )\n\n        assert_equal(\n            infer_sig_from_docstring(\"func(x,  /, y,  *, z, **kwargs) -> str\", \"func\"),\n            [\n                FunctionSig(\n                    name=\"func\",\n                    args=[\n                        ArgSig(name=\"x\"),\n                        ArgSig(name=\"y\"),\n                        ArgSig(name=\"z\"),\n                        ArgSig(\"**kwargs\"),\n                    ],\n                    ret_type=\"str\",\n                )\n            ],\n        )\n\n    def test_infer_sig_from_docstring_pos_only_and_keyword_only_arguments_errors(self) -> None:\n        # / as first argument\n        assert_equal(infer_sig_from_docstring(\"func(/, x) -> str\", \"func\"), [])\n\n        # * as last argument\n        assert_equal(infer_sig_from_docstring(\"func(x, *) -> str\", \"func\"), [])\n\n        # / after *\n        assert_equal(infer_sig_from_docstring(\"func(x, *, /,  y) -> str\", \"func\"), [])\n\n        # Two /\n        assert_equal(infer_sig_from_docstring(\"func(x, /, /, *,  y) -> str\", \"func\"), [])\n\n        assert_equal(infer_sig_from_docstring(\"func(x, /, y,  /, *,  z) -> str\", \"func\"), [])\n\n        # Two *\n        assert_equal(infer_sig_from_docstring(\"func(x, /, *, *,  y) -> str\", \"func\"), [])\n\n        assert_equal(infer_sig_from_docstring(\"func(x, /, *, y, *,  z) -> str\", \"func\"), [])\n\n        # *args and * are not allowed\n        assert_equal(infer_sig_from_docstring(\"func(*args, *, kwonly) -> str\", \"func\"), [])\n\n    def test_infer_arg_sig_from_anon_docstring(self) -> None:\n        assert_equal(\n            infer_arg_sig_from_anon_docstring(\"(*args, **kwargs)\"),\n            [ArgSig(name=\"*args\"), ArgSig(name=\"**kwargs\")],\n        )\n\n        assert_equal(\n            infer_arg_sig_from_anon_docstring(\n                \"(x: Tuple[int, Tuple[str, int], str]=(1, ('a', 2), 'y'), y: int=4)\"\n            ),\n            [\n                ArgSig(name=\"x\", type=\"Tuple[int,Tuple[str,int],str]\", default=True),\n                ArgSig(name=\"y\", type=\"int\", default=True),\n            ],\n        )\n\n    def test_infer_prop_type_from_docstring(self) -> None:\n        assert_equal(infer_prop_type_from_docstring(\"str: A string.\"), \"str\")\n        assert_equal(infer_prop_type_from_docstring(\"Optional[int]: An int.\"), \"Optional[int]\")\n        assert_equal(\n            infer_prop_type_from_docstring(\"Tuple[int, int]: A tuple.\"), \"Tuple[int, int]\"\n        )\n        assert_equal(infer_prop_type_from_docstring(\"\\nstr: A string.\"), None)\n\n    def test_infer_sig_from_docstring_square_brackets(self) -> None:\n        assert (\n            infer_sig_from_docstring(\"fetch_row([maxrows, how]) -- Fetches stuff\", \"fetch_row\")\n            == []\n        )\n\n    def test_remove_misplaced_type_comments_1(self) -> None:\n        good = \"\"\"\n        \\u1234\n        def f(x):  # type: (int) -> int\n\n        def g(x):\n            # type: (int) -> int\n\n        def h():\n\n            # type: () int\n\n        x = 1  # type: int\n        \"\"\"\n\n        assert_equal(remove_misplaced_type_comments(good), good)\n\n    def test_remove_misplaced_type_comments_2(self) -> None:\n        bad = \"\"\"\n        def f(x):\n            # type: Callable[[int], int]\n            pass\n\n        #  type:  \"foo\"\n        #  type:  'bar'\n        x = 1\n        # type: int\n        \"\"\"\n        bad_fixed = \"\"\"\n        def f(x):\n\n            pass\n\n\n\n        x = 1\n\n        \"\"\"\n        assert_equal(remove_misplaced_type_comments(bad), bad_fixed)\n\n    def test_remove_misplaced_type_comments_3(self) -> None:\n        bad = '''\n        def f(x):\n            \"\"\"docstring\"\"\"\n            # type: (int) -> int\n            pass\n\n        def g(x):\n            \"\"\"docstring\n            \"\"\"\n            # type: (int) -> int\n            pass\n        '''\n        bad_fixed = '''\n        def f(x):\n            \"\"\"docstring\"\"\"\n\n            pass\n\n        def g(x):\n            \"\"\"docstring\n            \"\"\"\n\n            pass\n        '''\n        assert_equal(remove_misplaced_type_comments(bad), bad_fixed)\n\n    def test_remove_misplaced_type_comments_4(self) -> None:\n        bad = \"\"\"\n        def f(x):\n            '''docstring'''\n            # type: (int) -> int\n            pass\n\n        def g(x):\n            '''docstring\n            '''\n            # type: (int) -> int\n            pass\n        \"\"\"\n        bad_fixed = \"\"\"\n        def f(x):\n            '''docstring'''\n\n            pass\n\n        def g(x):\n            '''docstring\n            '''\n\n            pass\n        \"\"\"\n        assert_equal(remove_misplaced_type_comments(bad), bad_fixed)\n\n    def test_remove_misplaced_type_comments_5(self) -> None:\n        bad = \"\"\"\n        def f(x):\n            # type: (int, List[Any],\n            #        float, bool) -> int\n            pass\n\n        def g(x):\n            # type: (int, List[Any])\n            pass\n        \"\"\"\n        bad_fixed = \"\"\"\n        def f(x):\n\n            #        float, bool) -> int\n            pass\n\n        def g(x):\n\n            pass\n        \"\"\"\n        assert_equal(remove_misplaced_type_comments(bad), bad_fixed)\n\n    def test_remove_misplaced_type_comments_bytes(self) -> None:\n        original = b\"\"\"\n        \\xbf\n        def f(x):  # type: (int) -> int\n\n        def g(x):\n            # type: (int) -> int\n            pass\n\n        def h():\n            # type: int\n            pass\n\n        x = 1  # type: int\n        \"\"\"\n\n        dest = b\"\"\"\n        \\xbf\n        def f(x):  # type: (int) -> int\n\n        def g(x):\n            # type: (int) -> int\n            pass\n\n        def h():\n\n            pass\n\n        x = 1  # type: int\n        \"\"\"\n\n        assert_equal(remove_misplaced_type_comments(original), dest)\n\n    @unittest.skipIf(sys.platform == \"win32\", \"Tests building the paths common ancestor on *nix\")\n    def test_common_dir_prefix_unix(self) -> None:\n        assert common_dir_prefix([]) == \".\"\n        assert common_dir_prefix([\"x.pyi\"]) == \".\"\n        assert common_dir_prefix([\"./x.pyi\"]) == \".\"\n        assert common_dir_prefix([\"foo/bar/x.pyi\"]) == \"foo/bar\"\n        assert common_dir_prefix([\"foo/bar/x.pyi\", \"foo/bar/y.pyi\"]) == \"foo/bar\"\n        assert common_dir_prefix([\"foo/bar/x.pyi\", \"foo/y.pyi\"]) == \"foo\"\n        assert common_dir_prefix([\"foo/x.pyi\", \"foo/bar/y.pyi\"]) == \"foo\"\n        assert common_dir_prefix([\"foo/bar/zar/x.pyi\", \"foo/y.pyi\"]) == \"foo\"\n        assert common_dir_prefix([\"foo/x.pyi\", \"foo/bar/zar/y.pyi\"]) == \"foo\"\n        assert common_dir_prefix([\"foo/bar/zar/x.pyi\", \"foo/bar/y.pyi\"]) == \"foo/bar\"\n        assert common_dir_prefix([\"foo/bar/x.pyi\", \"foo/bar/zar/y.pyi\"]) == \"foo/bar\"\n        assert common_dir_prefix([r\"foo/bar\\x.pyi\"]) == \"foo\"\n        assert common_dir_prefix([r\"foo\\bar/x.pyi\"]) == r\"foo\\bar\"\n\n    @unittest.skipIf(\n        sys.platform != \"win32\", \"Tests building the paths common ancestor on Windows\"\n    )\n    def test_common_dir_prefix_win(self) -> None:\n        assert common_dir_prefix([\"x.pyi\"]) == \".\"\n        assert common_dir_prefix([r\".\\x.pyi\"]) == \".\"\n        assert common_dir_prefix([r\"foo\\bar\\x.pyi\"]) == r\"foo\\bar\"\n        assert common_dir_prefix([r\"foo\\bar\\x.pyi\", r\"foo\\bar\\y.pyi\"]) == r\"foo\\bar\"\n        assert common_dir_prefix([r\"foo\\bar\\x.pyi\", r\"foo\\y.pyi\"]) == \"foo\"\n        assert common_dir_prefix([r\"foo\\x.pyi\", r\"foo\\bar\\y.pyi\"]) == \"foo\"\n        assert common_dir_prefix([r\"foo\\bar\\zar\\x.pyi\", r\"foo\\y.pyi\"]) == \"foo\"\n        assert common_dir_prefix([r\"foo\\x.pyi\", r\"foo\\bar\\zar\\y.pyi\"]) == \"foo\"\n        assert common_dir_prefix([r\"foo\\bar\\zar\\x.pyi\", r\"foo\\bar\\y.pyi\"]) == r\"foo\\bar\"\n        assert common_dir_prefix([r\"foo\\bar\\x.pyi\", r\"foo\\bar\\zar\\y.pyi\"]) == r\"foo\\bar\"\n        assert common_dir_prefix([r\"foo/bar\\x.pyi\"]) == r\"foo\\bar\"\n        assert common_dir_prefix([r\"foo\\bar/x.pyi\"]) == r\"foo\\bar\"\n        assert common_dir_prefix([r\"foo/bar/x.pyi\"]) == r\"foo\\bar\"\n\n    def test_function_context_nested_classes(self) -> None:\n        ctx = FunctionContext(\n            module_name=\"spangle\",\n            name=\"foo\",\n            class_info=ClassInfo(\n                name=\"Nested\", self_var=\"self\", parent=ClassInfo(name=\"Parent\", self_var=\"self\")\n            ),\n        )\n        assert ctx.fullname == \"spangle.Parent.Nested.foo\"\n\n\nclass StubgenHelpersSuite(unittest.TestCase):\n    def test_is_blacklisted_path(self) -> None:\n        assert not is_blacklisted_path(\"foo/bar.py\")\n        assert not is_blacklisted_path(\"foo.py\")\n        assert not is_blacklisted_path(\"foo/xvendor/bar.py\")\n        assert not is_blacklisted_path(\"foo/vendorx/bar.py\")\n        assert is_blacklisted_path(\"foo/vendor/bar.py\")\n        assert is_blacklisted_path(\"foo/vendored/bar.py\")\n        assert is_blacklisted_path(\"foo/vendored/bar/thing.py\")\n        assert is_blacklisted_path(\"foo/six.py\")\n\n    def test_is_non_library_module(self) -> None:\n        assert not is_non_library_module(\"foo\")\n        assert not is_non_library_module(\"foo.bar\")\n\n        # The following could be test modules, but we are very conservative and\n        # don't treat them as such since they could plausibly be real modules.\n        assert not is_non_library_module(\"foo.bartest\")\n        assert not is_non_library_module(\"foo.bartests\")\n        assert not is_non_library_module(\"foo.testbar\")\n\n        assert is_non_library_module(\"foo.test\")\n        assert is_non_library_module(\"foo.test.foo\")\n        assert is_non_library_module(\"foo.tests\")\n        assert is_non_library_module(\"foo.tests.foo\")\n        assert is_non_library_module(\"foo.testing.foo\")\n        assert is_non_library_module(\"foo.SelfTest.foo\")\n\n        assert is_non_library_module(\"foo.test_bar\")\n        assert is_non_library_module(\"foo.bar_tests\")\n        assert is_non_library_module(\"foo.testing\")\n        assert is_non_library_module(\"foo.conftest\")\n        assert is_non_library_module(\"foo.bar_test_util\")\n        assert is_non_library_module(\"foo.bar_test_utils\")\n        assert is_non_library_module(\"foo.bar_test_base\")\n\n        assert is_non_library_module(\"foo.setup\")\n\n        assert is_non_library_module(\"foo.__main__\")\n\n\nclass StubgenPythonSuite(DataSuite):\n    \"\"\"Data-driven end-to-end test cases that generate stub files.\n\n    You can use these magic test case name suffixes:\n\n    *_semanal\n        Run semantic analysis (slow as this uses real stubs -- only use\n        when necessary)\n    *_import\n        Import module and perform runtime introspection (in the current\n        process!)\n\n    You can use these magic comments:\n\n    # flags: --some-stubgen-option ...\n        Specify custom stubgen options\n\n    # modules: module1 module2 ...\n        Specify which modules to output (by default only 'main')\n    \"\"\"\n\n    required_out_section = True\n    base_path = \".\"\n    files = [\"stubgen.test\"]\n\n    @unittest.skipIf(sys.platform == \"win32\", \"clean up fails on Windows\")\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        with local_sys_path_set():\n            self.run_case_inner(testcase)\n\n    def run_case_inner(self, testcase: DataDrivenTestCase) -> None:\n        extra = []  # Extra command-line args\n        mods = []  # Module names to process\n        source = \"\\n\".join(testcase.input)\n        for file, content in testcase.files + [(\"./main.py\", source)]:\n            # Strip ./ prefix and .py suffix.\n            mod = file[2:-3].replace(\"/\", \".\")\n            if mod.endswith(\".__init__\"):\n                mod, _, _ = mod.rpartition(\".\")\n            mods.append(mod)\n            if \"-p \" not in source:\n                extra.extend([\"-m\", mod])\n            with open(file, \"w\") as f:\n                f.write(content)\n\n        options = self.parse_flags(source, extra)\n        if sys.version_info < options.pyversion:\n            pytest.skip()\n        modules = self.parse_modules(source)\n        out_dir = \"out\"\n        try:\n            try:\n                if testcase.name.endswith(\"_inspect\"):\n                    options.inspect = True\n                else:\n                    if not testcase.name.endswith(\"_import\"):\n                        options.no_import = True\n                    if not testcase.name.endswith(\"_semanal\"):\n                        options.parse_only = True\n\n                generate_stubs(options)\n                a: list[str] = []\n                for module in modules:\n                    fnam = module_to_path(out_dir, module)\n                    self.add_file(fnam, a, header=len(modules) > 1)\n            except CompileError as e:\n                a = e.messages\n            assert_string_arrays_equal(\n                testcase.output, a, f\"Invalid output ({testcase.file}, line {testcase.line})\"\n            )\n        finally:\n            for mod in mods:\n                if mod in sys.modules:\n                    del sys.modules[mod]\n            shutil.rmtree(out_dir)\n\n    def parse_flags(self, program_text: str, extra: list[str]) -> Options:\n        flags = re.search(\"# flags: (.*)$\", program_text, flags=re.MULTILINE)\n        pyversion = None\n        if flags:\n            flag_list = flags.group(1).split()\n            for i, flag in enumerate(flag_list):\n                if flag.startswith(\"--python-version=\"):\n                    pyversion = flag.split(\"=\", 1)[1]\n                    del flag_list[i]\n                    break\n        else:\n            flag_list = []\n        options = parse_options(flag_list + extra)\n        if pyversion:\n            # A hack to allow testing old python versions with new language constructs\n            # This should be rarely used in general as stubgen output should not be version-specific\n            major, minor = pyversion.split(\".\", 1)\n            options.pyversion = (int(major), int(minor))\n        if \"--verbose\" not in flag_list:\n            options.quiet = True\n        else:\n            options.verbose = True\n        return options\n\n    def parse_modules(self, program_text: str) -> list[str]:\n        modules = re.search(\"# modules: (.*)$\", program_text, flags=re.MULTILINE)\n        if modules:\n            return modules.group(1).split()\n        else:\n            return [\"main\"]\n\n    def add_file(self, path: str, result: list[str], header: bool) -> None:\n        if not os.path.exists(path):\n            result.append(\"<%s was not generated>\" % path.replace(\"\\\\\", \"/\"))\n            return\n        if header:\n            result.append(f\"# {path[4:]}\")\n        with open(path, encoding=\"utf8\") as file:\n            result.extend(file.read().splitlines())\n\n\nself_arg = ArgSig(name=\"self\")\n\n\nclass TestBaseClass:\n    pass\n\n\nclass TestClass(TestBaseClass):\n    pass\n\n\nclass StubgencSuite(unittest.TestCase):\n    \"\"\"Unit tests for stub generation from C modules using introspection.\n\n    Note that these don't cover a lot!\n    \"\"\"\n\n    def test_infer_hash_sig(self) -> None:\n        assert_equal(infer_c_method_args(\"__hash__\"), [self_arg])\n        assert_equal(infer_method_ret_type(\"__hash__\"), \"int\")\n\n    def test_infer_getitem_sig(self) -> None:\n        assert_equal(infer_c_method_args(\"__getitem__\"), [self_arg, ArgSig(name=\"index\")])\n\n    def test_infer_setitem_sig(self) -> None:\n        assert_equal(\n            infer_c_method_args(\"__setitem__\"),\n            [self_arg, ArgSig(name=\"index\"), ArgSig(name=\"object\")],\n        )\n        assert_equal(infer_method_ret_type(\"__setitem__\"), \"None\")\n\n    def test_infer_eq_op_sig(self) -> None:\n        for op in (\"eq\", \"ne\", \"lt\", \"le\", \"gt\", \"ge\"):\n            assert_equal(\n                infer_c_method_args(f\"__{op}__\"), [self_arg, ArgSig(name=\"other\", type=\"object\")]\n            )\n\n    def test_infer_binary_op_sig(self) -> None:\n        for op in (\"add\", \"radd\", \"sub\", \"rsub\", \"mul\", \"rmul\"):\n            assert_equal(infer_c_method_args(f\"__{op}__\"), [self_arg, ArgSig(name=\"other\")])\n\n    def test_infer_equality_op_sig(self) -> None:\n        for op in (\"eq\", \"ne\", \"lt\", \"le\", \"gt\", \"ge\", \"contains\"):\n            assert_equal(infer_method_ret_type(f\"__{op}__\"), \"bool\")\n\n    def test_infer_unary_op_sig(self) -> None:\n        for op in (\"neg\", \"pos\"):\n            assert_equal(infer_c_method_args(f\"__{op}__\"), [self_arg])\n\n    def test_infer_cast_sig(self) -> None:\n        for op in (\"float\", \"bool\", \"bytes\", \"int\"):\n            assert_equal(infer_method_ret_type(f\"__{op}__\"), op)\n\n    def test_generate_class_stub_no_crash_for_object(self) -> None:\n        output: list[str] = []\n        mod = ModuleType(\"module\", \"\")  # any module is fine\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n\n        gen.generate_class_stub(\"alias\", object, output)\n        assert_equal(gen.get_imports().splitlines(), [])\n        assert_equal(output[0], \"class alias:\")\n\n    def test_generate_class_stub_variable_type_annotation(self) -> None:\n        # This class mimics the stubgen unit test 'testClassVariable'\n        class TestClassVariableCls:\n            x = 1\n\n        output: list[str] = []\n        mod = ModuleType(\"module\", \"\")  # any module is fine\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_class_stub(\"C\", TestClassVariableCls, output)\n        assert_equal(gen.get_imports().splitlines(), [\"from typing import ClassVar\"])\n        assert_equal(output, [\"class C:\", \"    x: ClassVar[int] = ...\"])\n\n    def test_generate_c_type_none_default(self) -> None:\n        class TestClass:\n            def test(self, arg0=1, arg1=None) -> None:  # type: ignore[no-untyped-def]\n                pass\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.is_c_module = False\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(\n                self_var=\"self\",\n                cls=TestClass,\n                name=\"TestClass\",\n                docstring=getattr(TestClass, \"__doc__\", None),\n            ),\n        )\n        assert_equal(\n            output, [\"def test(self, arg0: int = ..., arg1: Incomplete | None = ...) -> None: ...\"]\n        )\n\n    def test_non_c_generate_signature_with_kw_only_args(self) -> None:\n        class TestClass:\n            def test(\n                self, arg0: str, *, keyword_only: str, keyword_only_with_default: int = 7\n            ) -> None:\n                pass\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.is_c_module = False\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(\n                self_var=\"self\",\n                cls=TestClass,\n                name=\"TestClass\",\n                docstring=getattr(TestClass, \"__doc__\", None),\n            ),\n        )\n        assert_equal(\n            output,\n            [\n                \"def test(self, arg0: str, *, keyword_only: str, keyword_only_with_default: int = ...) -> None: ...\"\n            ],\n        )\n\n    def test_generate_c_type_inheritance(self) -> None:\n        class TestClass(KeyError):\n            pass\n\n        output: list[str] = []\n        mod = ModuleType(\"module, \")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_class_stub(\"C\", TestClass, output)\n        assert_equal(output, [\"class C(KeyError): ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_type_inheritance_same_module(self) -> None:\n        output: list[str] = []\n        mod = ModuleType(TestBaseClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_class_stub(\"C\", TestClass, output)\n        assert_equal(output, [\"class C(TestBaseClass): ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_type_inheritance_other_module(self) -> None:\n        import argparse\n\n        class TestClass(argparse.Action):\n            pass\n\n        output: list[str] = []\n        mod = ModuleType(\"module\", \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_class_stub(\"C\", TestClass, output)\n        assert_equal(output, [\"class C(argparse.Action): ...\"])\n        assert_equal(gen.get_imports().splitlines(), [\"import argparse\"])\n\n    def test_generate_c_type_inheritance_builtin_type(self) -> None:\n        class TestClass(type):\n            pass\n\n        output: list[str] = []\n        mod = ModuleType(\"module\", \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_class_stub(\"C\", TestClass, output)\n        assert_equal(output, [\"class C(type): ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_type_with_docstring(self) -> None:\n        class TestClass:\n            def test(self, arg0: str) -> None:\n                \"\"\"\n                test(self: TestClass, arg0: int)\n                \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(output, [\"def test(self, arg0: int) -> Any: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_type_with_docstring_no_self_arg(self) -> None:\n        class TestClass:\n            def test(self, arg0: str) -> None:\n                \"\"\"\n                test(arg0: int)\n                \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(output, [\"def test(self, arg0: int) -> Any: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_type_classmethod(self) -> None:\n        class TestClass:\n            @classmethod\n            def test(cls, arg0: str) -> None:\n                pass\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(self_var=\"cls\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(output, [\"@classmethod\", \"def test(cls, *args, **kwargs): ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_type_classmethod_with_overloads(self) -> None:\n        class TestClass:\n            @classmethod\n            def test(cls, arg0: str) -> None:\n                \"\"\"\n                test(cls, arg0: str)\n                test(cls, arg0: int)\n                \"\"\"\n                pass\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(self_var=\"cls\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(\n            output,\n            [\n                \"@overload\",\n                \"@classmethod\",\n                \"def test(cls, arg0: str) -> Any: ...\",\n                \"@overload\",\n                \"@classmethod\",\n                \"def test(cls, arg0: int) -> Any: ...\",\n            ],\n        )\n        assert_equal(gen.get_imports().splitlines(), [\"from typing import overload\"])\n\n    def test_generate_c_type_with_docstring_empty_default(self) -> None:\n        class TestClass:\n            def test(self, arg0: str = \"\") -> None:\n                \"\"\"\n                test(self: TestClass, arg0: str = \"\")\n                \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(output, [\"def test(self, arg0: str = ...) -> Any: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_function_other_module_arg(self) -> None:\n        \"\"\"Test that if argument references type from other module, module will be imported.\"\"\"\n\n        # Provide different type in python spec than in docstring to make sure, that docstring\n        # information is used.\n        def test(arg0: str) -> None:\n            \"\"\"\n            test(arg0: argparse.Action)\n            \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(self.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\"test\", test, output=output)\n        assert_equal(output, [\"def test(arg0: argparse.Action) -> Any: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [\"import argparse\"])\n\n    def test_generate_c_function_same_module(self) -> None:\n        \"\"\"Test that if annotation references type from same module but using full path, no module\n        will be imported, and type specification will be striped to local reference.\n        \"\"\"\n\n        # Provide different type in python spec than in docstring to make sure, that docstring\n        # information is used.\n        def test(arg0: str) -> None:\n            \"\"\"\n            test(arg0: argparse.Action) -> argparse.Action\n            \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(\"argparse\", \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\"test\", test, output=output)\n        assert_equal(output, [\"def test(arg0: Action) -> Action: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_function_other_module(self) -> None:\n        \"\"\"Test that if annotation references type from other module, module will be imported.\"\"\"\n\n        def test(arg0: str) -> None:\n            \"\"\"\n            test(arg0: argparse.Action) -> argparse.Action\n            \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(self.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\"test\", test, output=output)\n        assert_equal(output, [\"def test(arg0: argparse.Action) -> argparse.Action: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [\"import argparse\"])\n\n    def test_generate_c_function_same_module_nested(self) -> None:\n        \"\"\"Test that if annotation references type from same module but using full path, no module\n        will be imported, and type specification will be stripped to local reference.\n        \"\"\"\n\n        # Provide different type in python spec than in docstring to make sure, that docstring\n        # information is used.\n        def test(arg0: str) -> None:\n            \"\"\"\n            test(arg0: list[argparse.Action]) -> list[argparse.Action]\n            \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(\"argparse\", \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\"test\", test, output=output)\n        assert_equal(output, [\"def test(arg0: list[Action]) -> list[Action]: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_function_same_module_compound(self) -> None:\n        \"\"\"Test that if annotation references type from same module but using full path, no module\n        will be imported, and type specification will be stripped to local reference.\n        \"\"\"\n\n        # Provide different type in python spec than in docstring to make sure, that docstring\n        # information is used.\n        def test(arg0: str) -> None:\n            \"\"\"\n            test(arg0: Union[argparse.Action, NoneType]) -> Tuple[argparse.Action, NoneType]\n            \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(\"argparse\", \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\"test\", test, output=output)\n        assert_equal(output, [\"def test(arg0: Union[Action, None]) -> Tuple[Action, None]: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_function_other_module_nested(self) -> None:\n        \"\"\"Test that if annotation references type from other module, module will be imported,\n        and the import will be restricted to one of the known modules.\"\"\"\n\n        def test(arg0: str) -> None:\n            \"\"\"\n            test(arg0: foo.bar.Action) -> other.Thing\n            \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(self.__module__, \"\")\n        gen = InspectionStubGenerator(\n            mod.__name__, known_modules=[\"foo\", \"foo.spangle\", \"bar\"], module=mod\n        )\n        gen.generate_function_stub(\"test\", test, output=output)\n        assert_equal(output, [\"def test(arg0: foo.bar.Action) -> other.Thing: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [\"import foo\", \"import other\"])\n\n    def test_generate_c_function_no_crash_for_non_str_docstring(self) -> None:\n        def test(arg0: str) -> None: ...\n\n        test.__doc__ = property(lambda self: \"test(arg0: str) -> None\")  # type: ignore[assignment]\n\n        output: list[str] = []\n        mod = ModuleType(self.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\"test\", test, output=output)\n        assert_equal(output, [\"def test(*args, **kwargs): ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_property_with_pybind11(self) -> None:\n        \"\"\"Signatures included by PyBind11 inside property.fget are read.\"\"\"\n\n        class TestClass:\n            def get_attribute(self) -> None:\n                \"\"\"\n                (self: TestClass) -> str\n                \"\"\"\n\n            attribute = property(get_attribute, doc=\"\")\n\n        readwrite_properties: list[str] = []\n        readonly_properties: list[str] = []\n        mod = ModuleType(\"module\", \"\")  # any module is fine\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_property_stub(\n            \"attribute\",\n            TestClass.__dict__[\"attribute\"],\n            TestClass.attribute,\n            [],\n            readwrite_properties,\n            readonly_properties,\n        )\n        assert_equal(readwrite_properties, [])\n        assert_equal(readonly_properties, [\"@property\", \"def attribute(self) -> str: ...\"])\n\n    def test_generate_c_property_with_rw_property(self) -> None:\n        class TestClass:\n            def __init__(self) -> None:\n                self._attribute = 0\n\n            @property\n            def attribute(self) -> int:\n                return self._attribute\n\n            @attribute.setter\n            def attribute(self, value: int) -> None:\n                self._attribute = value\n\n        readwrite_properties: list[str] = []\n        readonly_properties: list[str] = []\n        mod = ModuleType(\"module\", \"\")  # any module is fine\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_property_stub(\n            \"attribute\",\n            TestClass.__dict__[\"attribute\"],\n            TestClass.attribute,\n            [],\n            readwrite_properties,\n            readonly_properties,\n        )\n        assert_equal(readwrite_properties, [\"attribute: Incomplete\"])\n        assert_equal(readonly_properties, [])\n\n    def test_generate_c_type_with_single_arg_generic(self) -> None:\n        class TestClass:\n            def test(self, arg0: str) -> None:\n                \"\"\"\n                test(self: TestClass, arg0: List[int])\n                \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(output, [\"def test(self, arg0: List[int]) -> Any: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_type_with_double_arg_generic(self) -> None:\n        class TestClass:\n            def test(self, arg0: str) -> None:\n                \"\"\"\n                test(self: TestClass, arg0: Dict[str, int])\n                \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(output, [\"def test(self, arg0: Dict[str, int]) -> Any: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_type_with_nested_generic(self) -> None:\n        class TestClass:\n            def test(self, arg0: str) -> None:\n                \"\"\"\n                test(self: TestClass, arg0: Dict[str, List[int]])\n                \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(output, [\"def test(self, arg0: Dict[str, List[int]]) -> Any: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [])\n\n    def test_generate_c_type_with_generic_using_other_module_first(self) -> None:\n        class TestClass:\n            def test(self, arg0: str) -> None:\n                \"\"\"\n                test(self: TestClass, arg0: Dict[argparse.Action, int])\n                \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(output, [\"def test(self, arg0: Dict[argparse.Action, int]) -> Any: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [\"import argparse\"])\n\n    def test_generate_c_type_with_generic_using_other_module_last(self) -> None:\n        class TestClass:\n            def test(self, arg0: str) -> None:\n                \"\"\"\n                test(self: TestClass, arg0: Dict[str, argparse.Action])\n                \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"test\",\n            TestClass.test,\n            output=output,\n            class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(output, [\"def test(self, arg0: Dict[str, argparse.Action]) -> Any: ...\"])\n        assert_equal(gen.get_imports().splitlines(), [\"import argparse\"])\n\n    def test_generate_c_type_with_overload_pybind11(self) -> None:\n        class TestClass:\n            def __init__(self, arg0: str) -> None:\n                \"\"\"\n                __init__(*args, **kwargs)\n                Overloaded function.\n\n                1. __init__(self: TestClass, arg0: str) -> None\n\n                2. __init__(self: TestClass, arg0: str, arg1: str) -> None\n                \"\"\"\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"__init__\",\n            TestClass.__init__,\n            output=output,\n            class_info=ClassInfo(self_var=\"self\", cls=TestClass, name=\"TestClass\"),\n        )\n        assert_equal(\n            output,\n            [\n                \"@overload\",\n                \"def __init__(self, arg0: str) -> None: ...\",\n                \"@overload\",\n                \"def __init__(self, arg0: str, arg1: str) -> None: ...\",\n                \"@overload\",\n                \"def __init__(self, *args, **kwargs) -> Any: ...\",\n            ],\n        )\n        assert_equal(gen.get_imports().splitlines(), [\"from typing import overload\"])\n\n    def test_generate_c_type_with_overload_shiboken(self) -> None:\n        class TestClass:\n            \"\"\"\n            TestClass(self: TestClass, arg0: str) -> None\n            TestClass(self: TestClass, arg0: str, arg1: str) -> None\n            \"\"\"\n\n            def __init__(self, arg0: str) -> None:\n                pass\n\n        output: list[str] = []\n        mod = ModuleType(TestClass.__module__, \"\")\n        gen = InspectionStubGenerator(mod.__name__, known_modules=[mod.__name__], module=mod)\n        gen.generate_function_stub(\n            \"__init__\",\n            TestClass.__init__,\n            output=output,\n            class_info=ClassInfo(\n                self_var=\"self\",\n                cls=TestClass,\n                name=\"TestClass\",\n                docstring=getattr(TestClass, \"__doc__\", None),\n            ),\n        )\n        assert_equal(\n            output,\n            [\n                \"@overload\",\n                \"def __init__(self, arg0: str) -> None: ...\",\n                \"@overload\",\n                \"def __init__(self, arg0: str, arg1: str) -> None: ...\",\n            ],\n        )\n        assert_equal(gen.get_imports().splitlines(), [\"from typing import overload\"])\n\n\nclass ArgSigSuite(unittest.TestCase):\n    def test_repr(self) -> None:\n        assert_equal(\n            repr(ArgSig(name='asd\"dsa')), \"ArgSig(name='asd\\\"dsa', type=None, default=False)\"\n        )\n        assert_equal(\n            repr(ArgSig(name=\"asd'dsa\")), 'ArgSig(name=\"asd\\'dsa\", type=None, default=False)'\n        )\n        assert_equal(repr(ArgSig(\"func\", \"str\")), \"ArgSig(name='func', type='str', default=False)\")\n        assert_equal(\n            repr(ArgSig(\"func\", \"str\", default=True)),\n            \"ArgSig(name='func', type='str', default=True)\",\n        )\n\n\nclass IsValidTypeSuite(unittest.TestCase):\n    def test_is_valid_type(self) -> None:\n        assert is_valid_type(\"int\")\n        assert is_valid_type(\"str\")\n        assert is_valid_type(\"Foo_Bar234\")\n        assert is_valid_type(\"foo.bar\")\n        assert is_valid_type(\"List[int]\")\n        assert is_valid_type(\"Dict[str, int]\")\n        assert is_valid_type(\"None\")\n        assert is_valid_type(\"Literal[26]\")\n        assert is_valid_type(\"Literal[0x1A]\")\n        assert is_valid_type('Literal[\"hello world\"]')\n        assert is_valid_type('Literal[b\"hello world\"]')\n        assert is_valid_type('Literal[u\"hello world\"]')\n        assert is_valid_type(\"Literal[True]\")\n        assert is_valid_type(\"Literal[Color.RED]\")\n        assert is_valid_type(\"Literal[None]\")\n        assert is_valid_type(\"str | int\")\n        assert is_valid_type(\"dict[str, int] | int\")\n        assert is_valid_type(\"tuple[str, ...]\")\n        assert is_valid_type(\n            'Literal[26, 0x1A, \"hello world\", b\"hello world\", u\"hello world\", True, Color.RED, None]'\n        )\n        assert not is_valid_type(\"foo-bar\")\n        assert not is_valid_type(\"x->y\")\n        assert not is_valid_type(\"True\")\n        assert not is_valid_type(\"False\")\n        assert not is_valid_type(\"x,y\")\n        assert not is_valid_type(\"x, y\")\n\n\nclass ModuleInspectSuite(unittest.TestCase):\n    def test_python_module(self) -> None:\n        with ModuleInspect() as m:\n            p = m.get_package_properties(\"inspect\")\n            assert p is not None\n            assert p.name == \"inspect\"\n            assert p.file\n            assert p.path is None\n            assert p.is_c_module is False\n            assert p.subpackages == []\n\n    def test_python_package(self) -> None:\n        with ModuleInspect() as m:\n            p = m.get_package_properties(\"unittest\")\n            assert p is not None\n            assert p.name == \"unittest\"\n            assert p.file\n            assert p.path\n            assert p.is_c_module is False\n            assert p.subpackages\n            assert all(sub.startswith(\"unittest.\") for sub in p.subpackages)\n\n    def test_c_module(self) -> None:\n        with ModuleInspect() as m:\n            p = m.get_package_properties(\"_socket\")\n            assert p is not None\n            assert p.name == \"_socket\"\n            assert p.path is None\n            assert p.is_c_module is True\n            assert p.subpackages == []\n\n    def test_non_existent(self) -> None:\n        with ModuleInspect() as m:\n            with self.assertRaises(InspectError) as e:\n                m.get_package_properties(\"foobar-non-existent\")\n            assert str(e.exception) == \"No module named 'foobar-non-existent'\"\n\n\ndef module_to_path(out_dir: str, module: str) -> str:\n    fnam = os.path.join(out_dir, f\"{module.replace('.', '/')}.pyi\")\n    if not os.path.exists(fnam):\n        alt_fnam = fnam.replace(\".pyi\", \"/__init__.pyi\")\n        if os.path.exists(alt_fnam):\n            return alt_fnam\n    return fnam\n"
  },
  {
    "path": "mypy/test/teststubinfo.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypy.stubinfo import (\n    is_module_from_legacy_bundled_package,\n    legacy_bundled_packages,\n    non_bundled_packages_flat,\n    stub_distribution_name,\n)\n\n\nclass TestStubInfo(unittest.TestCase):\n    def test_is_legacy_bundled_packages(self) -> None:\n        assert not is_module_from_legacy_bundled_package(\"foobar_asdf\")\n        assert not is_module_from_legacy_bundled_package(\"PIL\")\n        assert is_module_from_legacy_bundled_package(\"pycurl\")\n        assert is_module_from_legacy_bundled_package(\"dateparser\")\n\n    def test_stub_distribution_name(self) -> None:\n        assert stub_distribution_name(\"foobar_asdf\") is None\n        assert stub_distribution_name(\"pycurl\") == \"types-pycurl\"\n        assert stub_distribution_name(\"psutil\") == \"types-psutil\"\n        assert stub_distribution_name(\"sassutils\") == \"types-libsass\"\n        assert stub_distribution_name(\"google.cloud.ndb\") == \"types-google-cloud-ndb\"\n        assert stub_distribution_name(\"google.cloud.ndb.submodule\") == \"types-google-cloud-ndb\"\n        assert stub_distribution_name(\"google.cloud.unknown\") is None\n        assert stub_distribution_name(\"google.protobuf\") == \"types-protobuf\"\n        assert stub_distribution_name(\"google.protobuf.submodule\") == \"types-protobuf\"\n        assert stub_distribution_name(\"google\") is None\n\n    def test_period_in_top_level(self) -> None:\n        for packages in (non_bundled_packages_flat, legacy_bundled_packages):\n            for top_level_module in packages:\n                assert \".\" not in top_level_module\n"
  },
  {
    "path": "mypy/test/teststubtest.py",
    "content": "from __future__ import annotations\n\nimport contextlib\nimport inspect\nimport io\nimport os\nimport re\nimport sys\nimport tempfile\nimport textwrap\nimport unittest\nfrom collections.abc import Callable, Iterator\nfrom pathlib import Path\nfrom typing import Any\n\nfrom pytest import raises\n\nimport mypy.stubtest\nfrom mypy import build, nodes\nfrom mypy.modulefinder import BuildSource\nfrom mypy.options import Options\nfrom mypy.stubtest import parse_options, test_stubs\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import root_dir\n\n\n@contextlib.contextmanager\ndef use_tmp_dir(mod_name: str) -> Iterator[str]:\n    current = os.getcwd()\n    current_syspath = sys.path.copy()\n    with tempfile.TemporaryDirectory() as tmp:\n        try:\n            os.chdir(tmp)\n            if sys.path[0] != tmp:\n                sys.path.insert(0, tmp)\n            yield tmp\n        finally:\n            sys.path = current_syspath.copy()\n            if mod_name in sys.modules:\n                del sys.modules[mod_name]\n\n            os.chdir(current)\n\n\nTEST_MODULE_NAME = \"test_module\"\n\n\nstubtest_typing_stub = \"\"\"\nAny = object()\n\nclass _SpecialForm:\n    def __getitem__(self, typeargs: Any) -> object: ...\n\nCallable: _SpecialForm = ...\nGeneric: _SpecialForm = ...\nProtocol: _SpecialForm = ...\nUnion: _SpecialForm = ...\nClassVar: _SpecialForm = ...\n\nFinal = 0\nLiteral = 0\nTypedDict = 0\n\nclass TypeVar:\n    def __init__(self, name, covariant: bool = ..., contravariant: bool = ...) -> None: ...\n\nclass ParamSpec:\n    def __init__(self, name: str) -> None: ...\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_K = TypeVar(\"_K\")\n_V = TypeVar(\"_V\")\n_S = TypeVar(\"_S\", contravariant=True)\n_R = TypeVar(\"_R\", covariant=True)\n\nclass Coroutine(Generic[_T_co, _S, _R]): ...\nclass Iterable(Generic[_T_co]): ...\nclass Iterator(Iterable[_T_co]): ...\nclass Mapping(Generic[_K, _V]): ...\nclass Match(Generic[AnyStr]): ...\nclass Sequence(Iterable[_T_co]): ...\nclass Tuple(Sequence[_T_co]): ...\nclass NamedTuple(tuple[Any, ...]): ...\nclass _TypedDict(Mapping[str, object]):\n    __required_keys__: ClassVar[frozenset[str]]\n    __optional_keys__: ClassVar[frozenset[str]]\n    __total__: ClassVar[bool]\n    __readonly_keys__: ClassVar[frozenset[str]]\n    __mutable_keys__: ClassVar[frozenset[str]]\n    __closed__: ClassVar[bool | None]\n    __extra_items__: ClassVar[Any]\ndef overload(func: _T) -> _T: ...\ndef type_check_only(func: _T) -> _T: ...\ndef final(func: _T) -> _T: ...\n\"\"\"\n\nstubtest_builtins_stub = \"\"\"\nfrom typing import Generic, Mapping, Sequence, TypeVar, overload\n\nT = TypeVar('T')\nT_co = TypeVar('T_co', covariant=True)\nKT = TypeVar('KT')\nVT = TypeVar('VT')\n\nclass object:\n    __module__: str\n    def __init__(self) -> None: pass\n    def __repr__(self) -> str: pass\nclass type: ...\n\nclass tuple(Sequence[T_co], Generic[T_co]):\n    def __ge__(self, __other: tuple[T_co, ...]) -> bool: pass\n\nclass dict(Mapping[KT, VT]): ...\n\nclass frozenset(Generic[T]): ...\n\nclass function: pass\nclass ellipsis: pass\n\nclass int: ...\nclass float: ...\nclass bool(int): ...\nclass str: ...\nclass bytes: ...\n\nclass list(Sequence[T]): ...\n\ndef property(f: T) -> T: ...\ndef classmethod(f: T) -> T: ...\ndef staticmethod(f: T) -> T: ...\n\"\"\"\n\nstubtest_enum_stub = \"\"\"\nimport sys\nfrom typing import Any, TypeVar, Iterator\n\n_T = TypeVar('_T')\n\nclass EnumMeta(type):\n    def __len__(self) -> int: pass\n    def __iter__(self: type[_T]) -> Iterator[_T]: pass\n    def __reversed__(self: type[_T]) -> Iterator[_T]: pass\n    def __getitem__(self: type[_T], name: str) -> _T: pass\n\nclass Enum(metaclass=EnumMeta):\n    def __new__(cls: type[_T], value: object) -> _T: pass\n    def __repr__(self) -> str: pass\n    def __str__(self) -> str: pass\n    def __format__(self, format_spec: str) -> str: pass\n    def __hash__(self) -> Any: pass\n    def __reduce_ex__(self, proto: Any) -> Any: pass\n    name: str\n    value: Any\n\nclass Flag(Enum):\n    def __or__(self: _T, other: _T) -> _T: pass\n    def __and__(self: _T, other: _T) -> _T: pass\n    def __xor__(self: _T, other: _T) -> _T: pass\n    def __invert__(self: _T) -> _T: pass\n    if sys.version_info >= (3, 11):\n        __ror__ = __or__\n        __rand__ = __and__\n        __rxor__ = __xor__\n\"\"\"\n\n\ndef build_helper(source: str) -> build.BuildResult:\n    return build.build(\n        sources=[BuildSource(\"main.pyi\", None, textwrap.dedent(source))],\n        options=Options(),\n        alt_lib_path=test_temp_dir,\n    )\n\n\ndef run_stubtest_with_stderr(\n    stub: str,\n    runtime: str,\n    options: list[str],\n    config_file: str | None = None,\n    output: io.StringIO | None = None,\n    outerr: io.StringIO | None = None,\n) -> tuple[str, str]:\n    with use_tmp_dir(TEST_MODULE_NAME) as tmp_dir:\n        with open(\"builtins.pyi\", \"w\") as f:\n            f.write(stubtest_builtins_stub)\n        with open(\"typing.pyi\", \"w\") as f:\n            f.write(stubtest_typing_stub)\n        with open(\"enum.pyi\", \"w\") as f:\n            f.write(stubtest_enum_stub)\n        with open(f\"{TEST_MODULE_NAME}.pyi\", \"w\") as f:\n            f.write(stub)\n        with open(f\"{TEST_MODULE_NAME}.py\", \"w\") as f:\n            f.write(runtime)\n        if config_file:\n            with open(f\"{TEST_MODULE_NAME}_config.ini\", \"w\") as f:\n                f.write(config_file)\n            options = options + [\"--mypy-config-file\", f\"{TEST_MODULE_NAME}_config.ini\"]\n        output = io.StringIO() if output is None else output\n        outerr = io.StringIO() if outerr is None else outerr\n        with contextlib.redirect_stdout(output), contextlib.redirect_stderr(outerr):\n            test_stubs(parse_options([TEST_MODULE_NAME] + options), use_builtins_fixtures=True)\n    filtered_output = remove_color_code(\n        output.getvalue()\n        # remove cwd as it's not available from outside\n        .replace(os.path.realpath(tmp_dir) + os.sep, \"\").replace(tmp_dir + os.sep, \"\")\n    )\n    filtered_outerr = remove_color_code(\n        outerr.getvalue()\n        # remove cwd as it's not available from outside\n        .replace(os.path.realpath(tmp_dir) + os.sep, \"\").replace(tmp_dir + os.sep, \"\")\n    )\n    return filtered_output, filtered_outerr\n\n\ndef run_stubtest(\n    stub: str, runtime: str, options: list[str], config_file: str | None = None\n) -> str:\n    return run_stubtest_with_stderr(stub, runtime, options, config_file)[0]\n\n\nclass Case:\n    def __init__(self, stub: str, runtime: str, error: str | None) -> None:\n        self.stub = stub\n        self.runtime = runtime\n        self.error = error\n\n\ndef collect_cases(fn: Callable[..., Iterator[Case]]) -> Callable[..., None]:\n    \"\"\"run_stubtest used to be slow, so we used this decorator to combine cases.\n\n    If you're reading this and bored, feel free to refactor this and make it more like\n    other mypy tests.\n\n    \"\"\"\n\n    def test(*args: Any, **kwargs: Any) -> None:\n        cases = list(fn(*args, **kwargs))\n        expected_errors = set()\n        for c in cases:\n            if c.error is None:\n                continue\n            expected_error = c.error\n            if expected_error == \"\":\n                expected_error = TEST_MODULE_NAME\n            elif not expected_error.startswith(f\"{TEST_MODULE_NAME}.\"):\n                expected_error = f\"{TEST_MODULE_NAME}.{expected_error}\"\n            assert expected_error not in expected_errors, (\n                \"collect_cases merges cases into a single stubtest invocation; we already \"\n                \"expect an error for {}\".format(expected_error)\n            )\n            expected_errors.add(expected_error)\n        output = run_stubtest(\n            stub=\"\\n\\n\".join(textwrap.dedent(c.stub.lstrip(\"\\n\")) for c in cases),\n            runtime=\"\\n\\n\".join(textwrap.dedent(c.runtime.lstrip(\"\\n\")) for c in cases),\n            options=[\"--generate-allowlist\"],\n        )\n\n        actual_errors = set(output.splitlines())\n        if actual_errors != expected_errors:\n            output = run_stubtest(\n                stub=\"\\n\\n\".join(textwrap.dedent(c.stub.lstrip(\"\\n\")) for c in cases),\n                runtime=\"\\n\\n\".join(textwrap.dedent(c.runtime.lstrip(\"\\n\")) for c in cases),\n                options=[],\n            )\n            assert actual_errors == expected_errors, output\n\n    return test\n\n\nclass StubtestUnit(unittest.TestCase):\n    @collect_cases\n    def test_basic_good(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"def f(number: int, text: str) -> None: ...\",\n            runtime=\"def f(number, text): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class X:\n                def f(self, number: int, text: str) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class X:\n                def f(self, number, text): pass\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_types(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"def mistyped_class() -> None: ...\",\n            runtime=\"class mistyped_class: pass\",\n            error=\"mistyped_class\",\n        )\n        yield Case(\n            stub=\"class mistyped_fn: ...\", runtime=\"def mistyped_fn(): pass\", error=\"mistyped_fn\"\n        )\n        yield Case(\n            stub=\"\"\"\n            class X:\n                def mistyped_var(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class X:\n                mistyped_var = 1\n            \"\"\",\n            error=\"X.mistyped_var\",\n        )\n\n    @collect_cases\n    def test_transparent_type_check_only_subclasses(self) -> Iterator[Case]:\n        # See https://github.com/python/mypy/issues/20223\n        yield Case(\n            stub=\"\"\"\n            from typing import type_check_only\n\n            class UFunc: ...\n\n            @type_check_only\n            class _BinaryUFunc(UFunc): ...\n\n            equal: _BinaryUFunc\n            \"\"\",\n            runtime=\"\"\"\n            class UFunc:\n                pass\n\n            equal = UFunc()\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_coroutines(self) -> Iterator[Case]:\n        yield Case(stub=\"def bar() -> int: ...\", runtime=\"async def bar(): return 5\", error=\"bar\")\n        # Don't error for this one -- we get false positives otherwise\n        yield Case(stub=\"async def foo() -> int: ...\", runtime=\"def foo(): return 5\", error=None)\n        yield Case(stub=\"def baz() -> int: ...\", runtime=\"def baz(): return 5\", error=None)\n        yield Case(\n            stub=\"async def bingo() -> int: ...\", runtime=\"async def bingo(): return 5\", error=None\n        )\n\n    @collect_cases\n    def test_arg_name(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"def bad(number: int, text: str) -> None: ...\",\n            runtime=\"def bad(num, text) -> None: pass\",\n            error=\"bad\",\n        )\n        yield Case(\n            stub=\"def good_posonly(__number: int, text: str) -> None: ...\",\n            runtime=\"def good_posonly(num, /, text): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"def bad_posonly(__number: int, text: str) -> None: ...\",\n            runtime=\"def bad_posonly(flag, /, text): pass\",\n            error=\"bad_posonly\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class BadMethod:\n                def f(self, number: int, text: str) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class BadMethod:\n                def f(self, n, text): pass\n            \"\"\",\n            error=\"BadMethod.f\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class GoodDunder:\n                def __exit__(self, t, v, tb) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class GoodDunder:\n                def __exit__(self, exc_type, exc_val, exc_tb): pass\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"def dunder_name(__x: int) -> None: ...\"\"\",\n            runtime=\"\"\"def dunder_name(__x: int) -> None: ...\"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"def dunder_name_posonly(__x: int, /) -> None: ...\"\"\",\n            runtime=\"\"\"def dunder_name_posonly(__x: int) -> None: ...\"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"def dunder_name_bad(x: int) -> None: ...\"\"\",\n            runtime=\"\"\"def dunder_name_bad(__x: int) -> None: ...\"\"\",\n            error=\"dunder_name_bad\",\n        )\n\n    @collect_cases\n    def test_arg_kind(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"def runtime_kwonly(number: int, text: str) -> None: ...\",\n            runtime=\"def runtime_kwonly(number, *, text): pass\",\n            error=\"runtime_kwonly\",\n        )\n        yield Case(\n            stub=\"def stub_kwonly(number: int, *, text: str) -> None: ...\",\n            runtime=\"def stub_kwonly(number, text): pass\",\n            error=\"stub_kwonly\",\n        )\n        yield Case(\n            stub=\"def stub_posonly(__number: int, text: str) -> None: ...\",\n            runtime=\"def stub_posonly(number, text): pass\",\n            error=\"stub_posonly\",\n        )\n        yield Case(\n            stub=\"def good_posonly(__number: int, text: str) -> None: ...\",\n            runtime=\"def good_posonly(number, /, text): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"def runtime_posonly(number: int, text: str) -> None: ...\",\n            runtime=\"def runtime_posonly(number, /, text): pass\",\n            error=\"runtime_posonly\",\n        )\n        yield Case(\n            stub=\"def stub_posonly_570(number: int, /, text: str) -> None: ...\",\n            runtime=\"def stub_posonly_570(number, text): pass\",\n            error=\"stub_posonly_570\",\n        )\n\n    @collect_cases\n    def test_private_parameters(self) -> Iterator[Case]:\n        # Private parameters can optionally be omitted.\n        yield Case(\n            stub=\"def priv_pos_arg_missing() -> None: ...\",\n            runtime=\"def priv_pos_arg_missing(_p1=None): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"def multi_priv_args() -> None: ...\",\n            runtime=\"def multi_priv_args(_p='', _q=''): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"def priv_kwarg_missing() -> None: ...\",\n            runtime=\"def priv_kwarg_missing(*, _p2=''): pass\",\n            error=None,\n        )\n        # But if they are included, they must be correct.\n        yield Case(\n            stub=\"def priv_pos_arg_wrong(_p: int = ...) -> None: ...\",\n            runtime=\"def priv_pos_arg_wrong(_p=None): pass\",\n            error=\"priv_pos_arg_wrong\",\n        )\n        yield Case(\n            stub=\"def priv_kwarg_wrong(*, _p: int = ...) -> None: ...\",\n            runtime=\"def priv_kwarg_wrong(*, _p=None): pass\",\n            error=\"priv_kwarg_wrong\",\n        )\n        # Private parameters must have a default and start with exactly one\n        # underscore.\n        yield Case(\n            stub=\"def pos_arg_no_default() -> None: ...\",\n            runtime=\"def pos_arg_no_default(_np): pass\",\n            error=\"pos_arg_no_default\",\n        )\n        yield Case(\n            stub=\"def kwarg_no_default() -> None: ...\",\n            runtime=\"def kwarg_no_default(*, _np): pass\",\n            error=\"kwarg_no_default\",\n        )\n        yield Case(\n            stub=\"def double_underscore_pos_arg() -> None: ...\",\n            runtime=\"def double_underscore_pos_arg(__np = None): pass\",\n            error=\"double_underscore_pos_arg\",\n        )\n        yield Case(\n            stub=\"def double_underscore_kwarg() -> None: ...\",\n            runtime=\"def double_underscore_kwarg(*, __np = None): pass\",\n            error=\"double_underscore_kwarg\",\n        )\n        # But spot parameters that are accidentally not marked kw-only and\n        # vice-versa.\n        yield Case(\n            stub=\"def priv_arg_is_kwonly(_p=...) -> None: ...\",\n            runtime=\"def priv_arg_is_kwonly(*, _p=''): pass\",\n            error=\"priv_arg_is_kwonly\",\n        )\n        yield Case(\n            stub=\"def priv_arg_is_positional(*, _p=...) -> None: ...\",\n            runtime=\"def priv_arg_is_positional(_p=''): pass\",\n            error=\"priv_arg_is_positional\",\n        )\n        # Private parameters not at the end of the parameter list must be\n        # included so that users can pass the following arguments using\n        # positional syntax.\n        yield Case(\n            stub=\"def priv_args_not_at_end(*, q='') -> None: ...\",\n            runtime=\"def priv_args_not_at_end(_p='', q=''): pass\",\n            error=\"priv_args_not_at_end\",\n        )\n\n    @collect_cases\n    def test_default_presence(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"def f1(text: str = ...) -> None: ...\",\n            runtime=\"def f1(text = 'asdf'): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"def f2(text: str = ...) -> None: ...\", runtime=\"def f2(text): pass\", error=\"f2\"\n        )\n        yield Case(\n            stub=\"def f3(text: str) -> None: ...\",\n            runtime=\"def f3(text = 'asdf'): pass\",\n            error=\"f3\",\n        )\n        yield Case(\n            stub=\"def f4(text: str = ...) -> None: ...\",\n            runtime=\"def f4(text = None): pass\",\n            error=\"f4\",\n        )\n        yield Case(\n            stub=\"def f5(data: bytes = ...) -> None: ...\",\n            runtime=\"def f5(data = 'asdf'): pass\",\n            error=\"f5\",\n        )\n        yield Case(\n            stub=\"\"\"\n            from typing import TypeVar\n            _T = TypeVar(\"_T\", bound=str)\n            def f6(text: _T = ...) -> None: ...\n            \"\"\",\n            runtime=\"def f6(text = None): pass\",\n            error=\"f6\",\n        )\n\n    @collect_cases\n    def test_default_value(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"def f1(text: str = 'x') -> None: ...\",\n            runtime=\"def f1(text = 'y'): pass\",\n            error=\"f1\",\n        )\n        yield Case(\n            stub='def f2(text: bytes = b\"x\\'\") -> None: ...',\n            runtime='def f2(text = b\"x\\'\"): pass',\n            error=None,\n        )\n        yield Case(\n            stub='def f3(text: bytes = b\"y\\'\") -> None: ...',\n            runtime='def f3(text = b\"x\\'\"): pass',\n            error=\"f3\",\n        )\n        yield Case(\n            stub=\"def f4(text: object = 1) -> None: ...\",\n            runtime=\"def f4(text = 1.0): pass\",\n            error=\"f4\",\n        )\n        yield Case(\n            stub=\"def f5(text: object = True) -> None: ...\",\n            runtime=\"def f5(text = 1): pass\",\n            error=\"f5\",\n        )\n        yield Case(\n            stub=\"def f6(text: object = True) -> None: ...\",\n            runtime=\"def f6(text = True): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"def f7(text: object = not True) -> None: ...\",\n            runtime=\"def f7(text = False): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"def f8(text: object = not True) -> None: ...\",\n            runtime=\"def f8(text = True): pass\",\n            error=\"f8\",\n        )\n        yield Case(\n            stub=\"def f9(text: object = {1: 2}) -> None: ...\",\n            runtime=\"def f9(text = {1: 3}): pass\",\n            error=\"f9\",\n        )\n        yield Case(\n            stub=\"def f10(text: object = [1, 2]) -> None: ...\",\n            runtime=\"def f10(text = [1, 2]): pass\",\n            error=None,\n        )\n\n        # Simulate \"<unrepresentable>\"\n        yield Case(\n            stub=\"def f11() -> None: ...\",\n            runtime=\"\"\"\n            def f11(text=None) -> None: pass\n            f11.__text_signature__ = \"(text=<unrepresentable>)\"\n            \"\"\",\n            error=\"f11\",\n        )\n\n        # Simulate numpy ndarray.__bool__ that raises an error\n        yield Case(\n            stub=\"def f12(x=1): ...\",\n            runtime=\"\"\"\n            class _ndarray:\n                def __eq__(self, obj): return self\n                def __bool__(self): raise ValueError\n            def f12(x=_ndarray()) -> None: pass\n            \"\"\",\n            error=\"f12\",\n        )\n\n    @collect_cases\n    def test_static_class_method(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            class Good:\n                @classmethod\n                def f(cls, number: int, text: str) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Good:\n                @classmethod\n                def f(cls, number, text): pass\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class Bad1:\n                def f(cls, number: int, text: str) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Bad1:\n                @classmethod\n                def f(cls, number, text): pass\n            \"\"\",\n            error=\"Bad1.f\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class Bad2:\n                @classmethod\n                def f(cls, number: int, text: str) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Bad2:\n                @staticmethod\n                def f(self, number, text): pass\n            \"\"\",\n            error=\"Bad2.f\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class Bad3:\n                @staticmethod\n                def f(cls, number: int, text: str) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Bad3:\n                @classmethod\n                def f(self, number, text): pass\n            \"\"\",\n            error=\"Bad3.f\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class GoodNew:\n                def __new__(cls, *args, **kwargs): ...\n            \"\"\",\n            runtime=\"\"\"\n            class GoodNew:\n                def __new__(cls, *args, **kwargs): pass\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_arg_mismatch(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"def f1(a, *, b, c) -> None: ...\", runtime=\"def f1(a, *, b, c): pass\", error=None\n        )\n        yield Case(\n            stub=\"def f2(a, *, b) -> None: ...\", runtime=\"def f2(a, *, b, c): pass\", error=\"f2\"\n        )\n        yield Case(\n            stub=\"def f3(a, *, b, c) -> None: ...\", runtime=\"def f3(a, *, b): pass\", error=\"f3\"\n        )\n        yield Case(\n            stub=\"def f4(a, *, b, c) -> None: ...\", runtime=\"def f4(a, b, *, c): pass\", error=\"f4\"\n        )\n        yield Case(\n            stub=\"def f5(a, b, *, c) -> None: ...\", runtime=\"def f5(a, *, b, c): pass\", error=\"f5\"\n        )\n\n    @collect_cases\n    def test_varargs_varkwargs(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"def f1(*args, **kwargs) -> None: ...\",\n            runtime=\"def f1(*args, **kwargs): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"def f2(*args, **kwargs) -> None: ...\",\n            runtime=\"def f2(**kwargs): pass\",\n            error=\"f2\",\n        )\n        yield Case(\n            stub=\"def g1(a, b, c, d) -> None: ...\", runtime=\"def g1(a, *args): pass\", error=None\n        )\n        yield Case(\n            stub=\"def g2(a, b, c, d, *args) -> None: ...\", runtime=\"def g2(a): pass\", error=\"g2\"\n        )\n        yield Case(\n            stub=\"def g3(a, b, c, d, *args) -> None: ...\",\n            runtime=\"def g3(a, *args): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"def h1(a) -> None: ...\", runtime=\"def h1(a, b, c, d, *args): pass\", error=\"h1\"\n        )\n        yield Case(\n            stub=\"def h2(a, *args) -> None: ...\", runtime=\"def h2(a, b, c, d): pass\", error=\"h2\"\n        )\n        yield Case(\n            stub=\"def h3(a, *args) -> None: ...\",\n            runtime=\"def h3(a, b, c, d, *args): pass\",\n            error=\"h3\",\n        )\n        yield Case(\n            stub=\"def j1(a: int, *args) -> None: ...\", runtime=\"def j1(a): pass\", error=\"j1\"\n        )\n        yield Case(\n            stub=\"def j2(a: int) -> None: ...\", runtime=\"def j2(a, *args): pass\", error=\"j2\"\n        )\n        yield Case(\n            stub=\"def j3(a, b, c) -> None: ...\", runtime=\"def j3(a, *args, c): pass\", error=\"j3\"\n        )\n        yield Case(stub=\"def k1(a, **kwargs) -> None: ...\", runtime=\"def k1(a): pass\", error=\"k1\")\n        yield Case(\n            # In theory an error, but led to worse results in practice\n            stub=\"def k2(a) -> None: ...\",\n            runtime=\"def k2(a, **kwargs): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"def k3(a, b) -> None: ...\", runtime=\"def k3(a, **kwargs): pass\", error=\"k3\"\n        )\n        yield Case(\n            stub=\"def k4(a, *, b) -> None: ...\", runtime=\"def k4(a, **kwargs): pass\", error=None\n        )\n        yield Case(\n            stub=\"def k5(a, *, b) -> None: ...\",\n            runtime=\"def k5(a, *, b, c, **kwargs): pass\",\n            error=\"k5\",\n        )\n        yield Case(\n            stub=\"def k6(a, *, b, **kwargs) -> None: ...\",\n            runtime=\"def k6(a, *, b, c, **kwargs): pass\",\n            error=\"k6\",\n        )\n\n    @collect_cases\n    def test_overload(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            from typing import overload\n\n            @overload\n            def f1(a: int, *, c: int = ...) -> int: ...\n            @overload\n            def f1(a: int, b: int, c: int = ...) -> str: ...\n            \"\"\",\n            runtime=\"def f1(a, b = 0, c = 0): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            @overload\n            def f2(a: int, *, c: int = ...) -> int: ...\n            @overload\n            def f2(a: int, b: int, c: int = ...) -> str: ...\n            \"\"\",\n            runtime=\"def f2(a, b, c = 0): pass\",\n            error=\"f2\",\n        )\n        yield Case(\n            stub=\"\"\"\n            @overload\n            def f3(a: int) -> int: ...\n            @overload\n            def f3(a: int, b: str) -> str: ...\n            \"\"\",\n            runtime=\"def f3(a, b = None): pass\",\n            error=\"f3\",\n        )\n        yield Case(\n            stub=\"\"\"\n            @overload\n            def f4(a: int, *args, b: int, **kwargs) -> int: ...\n            @overload\n            def f4(a: str, *args, b: int, **kwargs) -> str: ...\n            \"\"\",\n            runtime=\"def f4(a, *args, b, **kwargs): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            @overload\n            def f5(__a: int) -> int: ...\n            @overload\n            def f5(__b: str) -> str: ...\n            \"\"\",\n            runtime=\"def f5(x, /): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            from typing import final\n            from typing_extensions import deprecated\n            class Foo:\n                @overload\n                @final\n                def f6(self, __a: int) -> int: ...\n                @overload\n                @deprecated(\"evil\")\n                def f6(self, __b: str) -> str: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Foo:\n                def f6(self, x, /): pass\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            @overload\n            def f7(a: int, /) -> int: ...\n            @overload\n            def f7(b: str, /) -> str: ...\n            \"\"\",\n            runtime=\"def f7(x, /): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            @overload\n            def f8(a: int, c: int = 0, /) -> int: ...\n            @overload\n            def f8(b: str, d: int, /) -> str: ...\n            \"\"\",\n            runtime=\"def f8(x, y, /): pass\",\n            error=\"f8\",\n        )\n        yield Case(\n            stub=\"\"\"\n            @overload\n            def f9(a: int, c: int = 0, /) -> int: ...\n            @overload\n            def f9(b: str, d: int, /) -> str: ...\n            \"\"\",\n            runtime=\"def f9(x, y=0, /): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class Bar:\n                @overload\n                def f1(self) -> int: ...\n                @overload\n                def f1(self, a: int, /) -> int: ...\n\n                @overload\n                def f2(self, a: int, /) -> int: ...\n                @overload\n                def f2(self, a: str, /) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Bar:\n                def f1(self, *a) -> int: ...\n                def f2(self, *a) -> int: ...\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            @overload\n            def f(a: int) -> int: ...\n            @overload\n            def f(a: int, b: str, /) -> str: ...\n            \"\"\",\n            runtime=\"\"\"\n            def f(a, *args): ...\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_decorated_overload(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            from typing import overload\n\n            class _dec1:\n                def __init__(self, func: object) -> None: ...\n                def __call__(self, x: str) -> str: ...\n\n            @overload\n            def good1(x: int) -> int: ...\n            @overload\n            @_dec1\n            def good1(unrelated: int, whatever: str) -> str: ...\n            \"\"\",\n            runtime=\"def good1(x): ...\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class _dec2:\n                def __init__(self, func: object) -> None: ...\n                def __call__(self, x: str, y: int) -> str: ...\n\n            @overload\n            def good2(x: int) -> str: ...\n            @overload\n            @_dec2\n            def good2(unrelated: int, whatever: str) -> str: ...\n            \"\"\",\n            runtime=\"def good2(x, y=...): ...\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class _dec3:\n                def __init__(self, func: object) -> None: ...\n                def __call__(self, x: str, y: int) -> str: ...\n\n            @overload\n            def bad(x: int) -> str: ...\n            @overload\n            @_dec3\n            def bad(unrelated: int, whatever: str) -> str: ...\n            \"\"\",\n            runtime=\"def bad(x): ...\",\n            error=\"bad\",\n        )\n\n    @collect_cases\n    def test_property(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            class Good:\n                @property\n                def read_only_attr(self) -> int: ...\n                read_only_attr_alias = read_only_attr\n            \"\"\",\n            runtime=\"\"\"\n            class Good:\n                @property\n                def read_only_attr(self): return 1\n                read_only_attr_alias = read_only_attr\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class Bad:\n                @property\n                def f(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Bad:\n                def f(self) -> int: return 1\n            \"\"\",\n            error=\"Bad.f\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class GoodReadOnly:\n                @property\n                def f(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class GoodReadOnly:\n                f = 1\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class BadReadOnly:\n                @property\n                def f(self) -> str: ...\n            \"\"\",\n            runtime=\"\"\"\n            class BadReadOnly:\n                f = 1\n            \"\"\",\n            error=\"BadReadOnly.f\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class Y:\n                @property\n                def read_only_attr(self) -> int: ...\n                @read_only_attr.setter\n                def read_only_attr(self, val: int) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Y:\n                @property\n                def read_only_attr(self): return 5\n            \"\"\",\n            error=\"Y.read_only_attr\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class Z:\n                @property\n                def read_write_attr(self) -> int: ...\n                @read_write_attr.setter\n                def read_write_attr(self, val: int) -> None: ...\n                read_write_attr_alias = read_write_attr\n            \"\"\",\n            runtime=\"\"\"\n            class Z:\n                @property\n                def read_write_attr(self): return self._val\n                @read_write_attr.setter\n                def read_write_attr(self, val): self._val = val\n                read_write_attr_alias = read_write_attr\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class FineAndDandy:\n                @property\n                def attr(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class _EvilDescriptor:\n                def __get__(self, instance, ownerclass=None):\n                    if instance is None:\n                        raise AttributeError('no')\n                    return 42\n                def __set__(self, instance, value):\n                    raise AttributeError('no')\n\n            class FineAndDandy:\n                attr = _EvilDescriptor()\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_cached_property(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            from functools import cached_property\n            class Good:\n                @cached_property\n                def read_only_attr(self) -> int: ...\n                @cached_property\n                def read_only_attr2(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            import functools as ft\n            from functools import cached_property\n            class Good:\n                @cached_property\n                def read_only_attr(self): return 1\n                @ft.cached_property\n                def read_only_attr2(self): return 1\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            from functools import cached_property\n            class Bad:\n                @cached_property\n                def f(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Bad:\n                def f(self) -> int: return 1\n            \"\"\",\n            error=\"Bad.f\",\n        )\n        yield Case(\n            stub=\"\"\"\n            from functools import cached_property\n            class GoodCachedAttr:\n                @cached_property\n                def f(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class GoodCachedAttr:\n                f = 1\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            from functools import cached_property\n            class BadCachedAttr:\n                @cached_property\n                def f(self) -> str: ...\n            \"\"\",\n            runtime=\"\"\"\n            class BadCachedAttr:\n                f = 1\n            \"\"\",\n            error=\"BadCachedAttr.f\",\n        )\n        yield Case(\n            stub=\"\"\"\n            from functools import cached_property\n            from typing import final\n            class FinalGood:\n                @cached_property\n                @final\n                def attr(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            from functools import cached_property\n            from typing import final\n            class FinalGood:\n                @cached_property\n                @final\n                def attr(self):\n                    return 1\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            from functools import cached_property\n            class FinalBad:\n                @cached_property\n                def attr(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            from functools import cached_property\n            from typing_extensions import final\n            class FinalBad:\n                @cached_property\n                @final\n                def attr(self):\n                    return 1\n            \"\"\",\n            error=\"FinalBad.attr\",\n        )\n\n    @collect_cases\n    def test_var(self) -> Iterator[Case]:\n        yield Case(stub=\"x1: int\", runtime=\"x1 = 5\", error=None)\n        yield Case(stub=\"x2: str\", runtime=\"x2 = 5\", error=\"x2\")\n        yield Case(\"from typing import Tuple\", \"\", None)  # dummy case\n        yield Case(\n            stub=\"\"\"\n            x3: Tuple[int, int]\n            \"\"\",\n            runtime=\"x3 = (1, 3)\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            x4: Tuple[int, int]\n            \"\"\",\n            runtime=\"x4 = (1, 3, 5)\",\n            error=\"x4\",\n        )\n        yield Case(stub=\"x5: int\", runtime=\"def x5(a, b): pass\", error=\"x5\")\n        yield Case(\n            stub=\"def foo(a: int, b: int) -> None: ...\\nx6 = foo\",\n            runtime=\"def foo(a, b): pass\\ndef x6(c, d): pass\",\n            error=\"x6\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class X:\n                f: int\n            \"\"\",\n            runtime=\"\"\"\n            class X:\n                def __init__(self):\n                    self.f = \"asdf\"\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class Y:\n                read_only_attr: int\n            \"\"\",\n            runtime=\"\"\"\n            class Y:\n                @property\n                def read_only_attr(self): return 5\n            \"\"\",\n            error=\"Y.read_only_attr\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class Z:\n                read_write_attr: int\n            \"\"\",\n            runtime=\"\"\"\n            class Z:\n                @property\n                def read_write_attr(self): return self._val\n                @read_write_attr.setter\n                def read_write_attr(self, val): self._val = val\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            from typing import Final\n            X_FINAL: Final = 2\n            \"\"\",\n            runtime=\"X_FINAL = 1\",\n            error=\"X_FINAL\",\n        )\n        yield Case(\n            stub=\"\"\"\n            from typing import Final\n            X_FINAL_OK: Final = 1\n            \"\"\",\n            runtime=\"X_FINAL_OK = 1\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_type_alias(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            import collections.abc\n            import re\n            import typing\n            from typing import Callable, Dict, Generic, Iterable, List, Match, Tuple, TypeVar, Union\n            \"\"\",\n            runtime=\"\"\"\n            import collections.abc\n            import re\n            from typing import Callable, Dict, Generic, Iterable, List, Match, Tuple, TypeVar, Union\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class X:\n                def f(self) -> None: ...\n            Y = X\n            \"\"\",\n            runtime=\"\"\"\n            class X:\n                def f(self) -> None: ...\n            class Y: ...\n            \"\"\",\n            error=\"Y.f\",\n        )\n        yield Case(stub=\"A = Tuple[int, str]\", runtime=\"A = (int, str)\", error=\"A\")\n        # Error if an alias isn't present at runtime...\n        yield Case(stub=\"B = str\", runtime=\"\", error=\"B\")\n        # ... but only if the alias isn't private\n        yield Case(stub=\"_C = int\", runtime=\"\", error=None)\n        yield Case(\n            stub=\"\"\"\n            D = tuple[str, str]\n            E = Tuple[int, int, int]\n            F = Tuple[str, int]\n            \"\"\",\n            runtime=\"\"\"\n            D = Tuple[str, str]\n            E = Tuple[int, int, int]\n            F = List[str]\n            \"\"\",\n            error=\"F\",\n        )\n        yield Case(\n            stub=\"\"\"\n            G = str | int\n            H = Union[str, bool]\n            I = str | int\n            \"\"\",\n            runtime=\"\"\"\n            G = Union[str, int]\n            H = Union[str, bool]\n            I = str\n            \"\"\",\n            error=\"I\",\n        )\n        yield Case(\n            stub=\"\"\"\n            K = dict[str, str]\n            L = Dict[int, int]\n            KK = collections.abc.Iterable[str]\n            LL = typing.Iterable[str]\n            \"\"\",\n            runtime=\"\"\"\n            K = Dict[str, str]\n            L = Dict[int, int]\n            KK = Iterable[str]\n            LL = Iterable[str]\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            _T = TypeVar(\"_T\")\n            class _Spam(Generic[_T]):\n                def foo(self) -> None: ...\n            IntFood = _Spam[int]\n            \"\"\",\n            runtime=\"\"\"\n            _T = TypeVar(\"_T\")\n            class _Bacon(Generic[_T]):\n                def foo(self, arg): pass\n            IntFood = _Bacon[int]\n            \"\"\",\n            error=\"IntFood.foo\",\n        )\n        yield Case(stub=\"StrList = list[str]\", runtime=\"StrList = ['foo', 'bar']\", error=\"StrList\")\n        yield Case(\n            stub=\"\"\"\n            N = typing.Callable[[str], bool]\n            O = collections.abc.Callable[[int], str]\n            P = typing.Callable[[str], bool]\n            \"\"\",\n            runtime=\"\"\"\n            N = Callable[[str], bool]\n            O = Callable[[int], str]\n            P = int\n            \"\"\",\n            error=\"P\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class Foo:\n                class Bar: ...\n            BarAlias = Foo.Bar\n            \"\"\",\n            runtime=\"\"\"\n            class Foo:\n                class Bar: pass\n            BarAlias = Foo.Bar\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            from io import StringIO\n            StringIOAlias = StringIO\n            \"\"\",\n            runtime=\"\"\"\n            from _io import StringIO\n            StringIOAlias = StringIO\n            \"\"\",\n            error=None,\n        )\n        yield Case(stub=\"M = Match[str]\", runtime=\"M = Match[str]\", error=None)\n        yield Case(\n            stub=\"\"\"\n            class Baz:\n                def fizz(self) -> None: ...\n            BazAlias = Baz\n            \"\"\",\n            runtime=\"\"\"\n            class Baz:\n                def fizz(self): pass\n            BazAlias = Baz\n            Baz.__name__ = Baz.__qualname__ = Baz.__module__ = \"New\"\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class FooBar:\n                __module__: None  # type: ignore\n                def fizz(self) -> None: ...\n            FooBarAlias = FooBar\n            \"\"\",\n            runtime=\"\"\"\n            class FooBar:\n                def fizz(self): pass\n            FooBarAlias = FooBar\n            FooBar.__module__ = None\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            Q = Dict[str, str]\n            R = dict[int, int]\n            S = Tuple[int, int]\n            T = tuple[str, str]\n            U = int | str\n            V = Union[int, str]\n            W = typing.Callable[[str], bool]\n            Z = collections.abc.Callable[[str], bool]\n            QQ = typing.Iterable[str]\n            RR = collections.abc.Iterable[str]\n            MM = typing.Match[str]\n            MMM = re.Match[str]\n            \"\"\",\n            runtime=\"\"\"\n            Q = dict[str, str]\n            R = dict[int, int]\n            S = tuple[int, int]\n            T = tuple[str, str]\n            U = int | str\n            V = int | str\n            W = collections.abc.Callable[[str], bool]\n            Z = collections.abc.Callable[[str], bool]\n            QQ = collections.abc.Iterable[str]\n            RR = collections.abc.Iterable[str]\n            MM = re.Match[str]\n            MMM = re.Match[str]\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_enum(self) -> Iterator[Case]:\n        yield Case(stub=\"import enum\", runtime=\"import enum\", error=None)\n        yield Case(\n            stub=\"\"\"\n            class X(enum.Enum):\n                a = ...\n                b = \"asdf\"\n                c = \"oops\"\n            \"\"\",\n            runtime=\"\"\"\n            class X(enum.Enum):\n                a = 1\n                b = \"asdf\"\n                c = 2\n            \"\"\",\n            error=\"X.c\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class Flags1(enum.Flag):\n                a = ...\n                b = 2\n            def foo(x: Flags1 = ...) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Flags1(enum.Flag):\n                a = 1\n                b = 2\n            def foo(x=Flags1.a|Flags1.b): pass\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class Flags2(enum.Flag):\n                a = ...\n                b = 2\n            def bar(x: Flags2 | None = None) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Flags2(enum.Flag):\n                a = 1\n                b = 2\n            def bar(x=Flags2.a|Flags2.b): pass\n            \"\"\",\n            error=\"bar\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class Flags3(enum.Flag):\n                a = ...\n                b = 2\n            def baz(x: Flags3 | None = ...) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Flags3(enum.Flag):\n                a = 1\n                b = 2\n            def baz(x=Flags3(0)): pass\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            runtime=\"\"\"\n            import enum\n            class SomeObject: ...\n\n            class WeirdEnum(enum.Enum):\n                a = SomeObject()\n                b = SomeObject()\n            \"\"\",\n            stub=\"\"\"\n            import enum\n            class SomeObject: ...\n            class WeirdEnum(enum.Enum):\n                _value_: SomeObject\n                a = ...\n                b = ...\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class Flags4(enum.Flag):\n                a = 1\n                b = 2\n            def spam(x: Flags4 | None = None) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Flags4(enum.Flag):\n                a = 1\n                b = 2\n            def spam(x=Flags4(0)): pass\n            \"\"\",\n            error=\"spam\",\n        )\n        yield Case(\n            stub=\"\"\"\n            import sys\n            from typing import Final, Literal\n            class BytesEnum(bytes, enum.Enum):\n                a = b'foo'\n\n            FOO: Literal[BytesEnum.a]\n            BAR: Final = BytesEnum.a\n            BAZ: BytesEnum\n            EGGS: bytes\n            \"\"\",\n            runtime=\"\"\"\n            class BytesEnum(bytes, enum.Enum):\n                a = b'foo'\n            FOO = BytesEnum.a\n            BAR = BytesEnum.a\n            BAZ = BytesEnum.a\n            EGGS = BytesEnum.a\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class HasSlotsAndNothingElse:\n                __slots__ = (\"x\",)\n                x: int\n\n            class HasInheritedSlots(HasSlotsAndNothingElse):\n                pass\n\n            class HasEmptySlots:\n                __slots__ = ()\n            \"\"\",\n            runtime=\"\"\"\n            class HasSlotsAndNothingElse:\n                __slots__ = (\"x\",)\n                x: int\n\n            class HasInheritedSlots(HasSlotsAndNothingElse):\n                pass\n\n            class HasEmptySlots:\n                __slots__ = ()\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class HasCompatibleValue(enum.Enum):\n                _value_: str\n                FOO = ...\n            \"\"\",\n            runtime=\"\"\"\n            class HasCompatibleValue(enum.Enum):\n                FOO = \"foo\"\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class HasIncompatibleValue(enum.Enum):\n                _value_: int\n                FOO = ...\n            \"\"\",\n            runtime=\"\"\"\n            class HasIncompatibleValue(enum.Enum):\n                FOO = \"foo\"\n            \"\"\",\n            error=\"HasIncompatibleValue.FOO\",\n        )\n\n    @collect_cases\n    def test_decorator(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            from typing import Any, Callable\n            def decorator(f: Callable[[], int]) -> Callable[..., Any]: ...\n            @decorator\n            def f() -> Any: ...\n            \"\"\",\n            runtime=\"\"\"\n            def decorator(f): return f\n            @decorator\n            def f(): return 3\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_proxy_object(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            class LazyObject:\n                def __init__(self, func: object) -> None: ...\n                def __bool__(self) -> bool: ...\n            \"\"\",\n            runtime=\"\"\"\n            class LazyObject:\n                def __init__(self, func):\n                    self.__dict__[\"_wrapped\"] = None\n                    self.__dict__[\"_setupfunc\"] = func\n                def _setup(self):\n                    self.__dict__[\"_wrapped\"] = self._setupfunc()\n                @property\n                def __class__(self):\n                    if self._wrapped is None:\n                        self._setup()\n                    return type(self._wrapped)\n                def __bool__(self):\n                    if self._wrapped is None:\n                        self._setup()\n                    return bool(self._wrapped)\n            \"\"\",\n            error=\"test_module.LazyObject.__class__\",\n        )\n        yield Case(\n            stub=\"\"\"\n            def default_value() -> bool: ...\n\n            DEFAULT_VALUE: bool\n            \"\"\",\n            runtime=\"\"\"\n            def default_value():\n                return True\n\n            DEFAULT_VALUE = LazyObject(default_value)\n            bool(DEFAULT_VALUE)  # evaluate the lazy object\n            \"\"\",\n            error=\"test_module.DEFAULT_VALUE\",\n        )\n\n    @collect_cases\n    def test_all_at_runtime_not_stub(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"Z: int\",\n            runtime=\"\"\"\n            __all__ = []\n            Z = 5\"\"\",\n            error=\"__all__\",\n        )\n\n    @collect_cases\n    def test_all_in_stub_not_at_runtime(self) -> Iterator[Case]:\n        yield Case(stub=\"__all__ = ()\", runtime=\"\", error=\"__all__\")\n\n    @collect_cases\n    def test_all_in_stub_different_to_all_at_runtime(self) -> Iterator[Case]:\n        # We *should* emit an error with the module name itself + __all__,\n        # if the stub *does* define __all__,\n        # but the stub's __all__ is inconsistent with the runtime's __all__\n        yield Case(\n            stub=\"\"\"\n            __all__ = ['foo']\n            foo: str\n            \"\"\",\n            runtime=\"\"\"\n            __all__ = []\n            foo = 'foo'\n            \"\"\",\n            error=\"__all__\",\n        )\n\n    @collect_cases\n    def test_missing(self) -> Iterator[Case]:\n        yield Case(stub=\"x = 5\", runtime=\"\", error=\"x\")\n        yield Case(stub=\"def f(): ...\", runtime=\"\", error=\"f\")\n        yield Case(stub=\"class X: ...\", runtime=\"\", error=\"X\")\n        yield Case(\n            stub=\"\"\"\n            from typing import overload\n            @overload\n            def h(x: int): ...\n            @overload\n            def h(x: str): ...\n            \"\"\",\n            runtime=\"\",\n            error=\"h\",\n        )\n        yield Case(stub=\"\", runtime=\"__all__ = []\", error=\"__all__\")  # dummy case\n        yield Case(stub=\"\", runtime=\"__all__ += ['y']\\ny = 5\", error=\"y\")\n        yield Case(stub=\"\", runtime=\"__all__ += ['g']\\ndef g(): pass\", error=\"g\")\n        # Here we should only check that runtime has B, since the stub explicitly re-exports it\n        yield Case(\n            stub=\"from mystery import A, B as B, C as D  # type: ignore\", runtime=\"\", error=\"B\"\n        )\n        yield Case(\n            stub=\"class Y: ...\",\n            runtime=\"__all__ += ['Y']\\nclass Y:\\n  def __or__(self, other): return self|other\",\n            error=\"Y.__or__\",\n        )\n        yield Case(\n            stub=\"class Z: ...\",\n            runtime=\"__all__ += ['Z']\\nclass Z:\\n  def __reduce__(self): return (Z,)\",\n            error=None,\n        )\n        # __call__ exists on type, so it appears to exist on the class.\n        # This checks that we identify it as missing at runtime anyway.\n        yield Case(\n            stub=\"\"\"\n            class ClassWithMetaclassOverride:\n                def __call__(*args, **kwds): ...\n            \"\"\",\n            runtime=\"class ClassWithMetaclassOverride: ...\",\n            error=\"ClassWithMetaclassOverride.__call__\",\n        )\n        # Test that we ignore object.__setattr__ and object.__delattr__ inheritance\n        yield Case(\n            stub=\"\"\"\n            from typing import Any\n            class FakeSetattrClass:\n                def __setattr__(self, name: str, value: Any, /) -> None: ...\n            \"\"\",\n            runtime=\"class FakeSetattrClass: ...\",\n            error=\"FakeSetattrClass.__setattr__\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class FakeDelattrClass:\n                def __delattr__(self, name: str, /) -> None: ...\n            \"\"\",\n            runtime=\"class FakeDelattrClass: ...\",\n            error=\"FakeDelattrClass.__delattr__\",\n        )\n\n    @collect_cases\n    def test_missing_no_runtime_all(self) -> Iterator[Case]:\n        yield Case(stub=\"\", runtime=\"import sys\", error=None)\n        yield Case(stub=\"\", runtime=\"def g(): ...\", error=\"g\")\n        yield Case(stub=\"\", runtime=\"CONSTANT = 0\", error=\"CONSTANT\")\n        yield Case(stub=\"\", runtime=\"import re; constant = re.compile('foo')\", error=\"constant\")\n        yield Case(stub=\"\", runtime=\"from json.scanner import NUMBER_RE\", error=None)\n        yield Case(stub=\"\", runtime=\"from string import ascii_letters\", error=None)\n\n    @collect_cases\n    def test_missing_no_runtime_all_terrible(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\",\n            runtime=\"\"\"\nimport sys\nimport types\nimport __future__\n_m = types.SimpleNamespace()\n_m.annotations = __future__.annotations\nsys.modules[\"_terrible_stubtest_test_module\"] = _m\n\nfrom _terrible_stubtest_test_module import *\nassert annotations\n\"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_non_public_1(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"__all__: list[str]\", runtime=\"\", error=f\"{TEST_MODULE_NAME}.__all__\"\n        )  # dummy case\n        yield Case(stub=\"_f: int\", runtime=\"def _f(): ...\", error=\"_f\")\n\n    @collect_cases\n    def test_non_public_2(self) -> Iterator[Case]:\n        yield Case(stub=\"__all__: list[str] = ['f']\", runtime=\"__all__ = ['f']\", error=None)\n        yield Case(stub=\"f: int\", runtime=\"def f(): ...\", error=\"f\")\n        yield Case(stub=\"g: int\", runtime=\"def g(): ...\", error=\"g\")\n\n    @collect_cases\n    def test_dunders(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"class A:\\n  def __init__(self, a: int, b: int) -> None: ...\",\n            runtime=\"class A:\\n  def __init__(self, a, bx): pass\",\n            error=\"A.__init__\",\n        )\n        yield Case(\n            stub=\"class B:\\n  def __call__(self, c: int, d: int) -> None: ...\",\n            runtime=\"class B:\\n  def __call__(self, c, dx): pass\",\n            error=\"B.__call__\",\n        )\n        yield Case(\n            stub=(\n                \"class C:\\n\"\n                \"  def __init_subclass__(\\n\"\n                \"    cls, e: int = ..., **kwargs: int\\n\"\n                \"  ) -> None: ...\\n\"\n            ),\n            runtime=\"class C:\\n  def __init_subclass__(cls, e=1, **kwargs): pass\",\n            error=None,\n        )\n        yield Case(\n            stub=\"class D:\\n  def __class_getitem__(cls, type: type) -> type: ...\",\n            runtime=\"class D:\\n  def __class_getitem__(cls, type): ...\",\n            error=None,\n        )\n        yield Case(\n            stub=\"class E:\\n  def __getitem__(self, item: object) -> object: ...\",\n            runtime=\"class E:\\n  def __getitem__(self, item: object, /) -> object: ...\",\n            error=\"E.__getitem__\",\n        )\n        yield Case(\n            stub=\"class F:\\n  def __getitem__(self, item: object, /) -> object: ...\",\n            runtime=\"class F:\\n  def __getitem__(self, item: object) -> object: ...\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_not_subclassable(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"class CanBeSubclassed: ...\", runtime=\"class CanBeSubclassed: ...\", error=None\n        )\n        yield Case(\n            stub=\"class CannotBeSubclassed:\\n  def __init_subclass__(cls) -> None: ...\",\n            runtime=\"class CannotBeSubclassed:\\n  def __init_subclass__(cls): raise TypeError\",\n            error=\"CannotBeSubclassed\",\n        )\n\n    @collect_cases\n    def test_disjoint_base(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            class A: pass\n            \"\"\",\n            runtime=\"\"\"\n            class A: pass\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            from typing_extensions import disjoint_base\n\n            @disjoint_base\n            class B: pass\n            \"\"\",\n            runtime=\"\"\"\n            class B: pass\n            \"\"\",\n            error=\"test_module.B\",\n        )\n        yield Case(\n            stub=\"\"\"\n            from typing_extensions import Self\n\n            class mytakewhile:\n                def __new__(cls, predicate: object, iterable: object, /) -> Self: ...\n                def __iter__(self) -> Self: ...\n                def __next__(self) -> object: ...\n            \"\"\",\n            runtime=\"\"\"\n            from itertools import takewhile as mytakewhile\n            \"\"\",\n            # Should have @disjoint_base\n            error=\"test_module.mytakewhile\",\n        )\n        yield Case(\n            stub=\"\"\"\n            from typing_extensions import disjoint_base, Self\n\n            @disjoint_base\n            class mycorrecttakewhile:\n                def __new__(cls, predicate: object, iterable: object, /) -> Self: ...\n                def __iter__(self) -> Self: ...\n                def __next__(self) -> object: ...\n            \"\"\",\n            runtime=\"\"\"\n            from itertools import takewhile as mycorrecttakewhile\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            runtime=\"\"\"\n            class IsDisjointBaseBecauseItHasSlots:\n                __slots__ = (\"a\",)\n                a: int\n            \"\"\",\n            stub=\"\"\"\n            from typing_extensions import disjoint_base\n\n            @disjoint_base\n            class IsDisjointBaseBecauseItHasSlots:\n                a: int\n            \"\"\",\n            error=\"test_module.IsDisjointBaseBecauseItHasSlots\",\n        )\n        yield Case(\n            runtime=\"\"\"\n            class IsFinalSoDisjointBaseIsRedundant: ...\n            \"\"\",\n            stub=\"\"\"\n            from typing_extensions import disjoint_base, final\n\n            @final\n            @disjoint_base\n            class IsFinalSoDisjointBaseIsRedundant: ...\n            \"\"\",\n            error=\"test_module.IsFinalSoDisjointBaseIsRedundant\",\n        )\n        yield Case(\n            runtime=\"\"\"\n            import enum\n\n            class IsEnumWithMembersSoDisjointBaseIsRedundant(enum.Enum):\n                A = 1\n                B = 2\n            \"\"\",\n            stub=\"\"\"\n            from typing_extensions import disjoint_base\n            import enum\n\n            @disjoint_base\n            class IsEnumWithMembersSoDisjointBaseIsRedundant(enum.Enum):\n                A = 1\n                B = 2\n            \"\"\",\n            error=\"test_module.IsEnumWithMembersSoDisjointBaseIsRedundant\",\n        )\n\n    @collect_cases\n    def test_has_runtime_final_decorator(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"from typing_extensions import final\",\n            runtime=\"\"\"\n            import functools\n            from typing_extensions import final\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            @final\n            class A: ...\n            \"\"\",\n            runtime=\"\"\"\n            @final\n            class A: ...\n            \"\"\",\n            error=None,\n        )\n        yield Case(  # Runtime can miss `@final` decorator\n            stub=\"\"\"\n            @final\n            class B: ...\n            \"\"\",\n            runtime=\"\"\"\n            class B: ...\n            \"\"\",\n            error=None,\n        )\n        yield Case(  # Stub cannot miss `@final` decorator\n            stub=\"\"\"\n            class C: ...\n            \"\"\",\n            runtime=\"\"\"\n            @final\n            class C: ...\n            \"\"\",\n            error=\"C\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class D:\n                @final\n                def foo(self) -> None: ...\n                @final\n                @staticmethod\n                def bar() -> None: ...\n                @staticmethod\n                @final\n                def bar2() -> None: ...\n                @final\n                @classmethod\n                def baz(cls) -> None: ...\n                @classmethod\n                @final\n                def baz2(cls) -> None: ...\n                @property\n                @final\n                def eggs(self) -> int: ...\n                @final\n                @property\n                def eggs2(self) -> int: ...\n                @final\n                def ham(self, obj: int) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class D:\n                @final\n                def foo(self): pass\n                @final\n                @staticmethod\n                def bar(): pass\n                @staticmethod\n                @final\n                def bar2(): pass\n                @final\n                @classmethod\n                def baz(cls): pass\n                @classmethod\n                @final\n                def baz2(cls): pass\n                @property\n                @final\n                def eggs(self): return 42\n                @final\n                @property\n                def eggs2(self): pass\n                @final\n                @functools.lru_cache()\n                def ham(self, obj): return obj * 2\n            \"\"\",\n            error=None,\n        )\n        # Stub methods are allowed to have @final even if the runtime doesn't...\n        yield Case(\n            stub=\"\"\"\n            class E:\n                @final\n                def foo(self) -> None: ...\n                @final\n                @staticmethod\n                def bar() -> None: ...\n                @staticmethod\n                @final\n                def bar2() -> None: ...\n                @final\n                @classmethod\n                def baz(cls) -> None: ...\n                @classmethod\n                @final\n                def baz2(cls) -> None: ...\n                @property\n                @final\n                def eggs(self) -> int: ...\n                @final\n                @property\n                def eggs2(self) -> int: ...\n                @final\n                def ham(self, obj: int) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class E:\n                def foo(self): pass\n                @staticmethod\n                def bar(): pass\n                @staticmethod\n                def bar2(): pass\n                @classmethod\n                def baz(cls): pass\n                @classmethod\n                def baz2(cls): pass\n                @property\n                def eggs(self): return 42\n                @property\n                def eggs2(self): return 42\n                @functools.lru_cache()\n                def ham(self, obj): return obj * 2\n            \"\"\",\n            error=None,\n        )\n        # ...But if the runtime has @final, the stub must have it as well\n        yield Case(\n            stub=\"\"\"\n            class F:\n                def foo(self) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class F:\n                @final\n                def foo(self): pass\n            \"\"\",\n            error=\"F.foo\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class G:\n                @staticmethod\n                def foo() -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class G:\n                @final\n                @staticmethod\n                def foo(): pass\n            \"\"\",\n            error=\"G.foo\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class H:\n                @staticmethod\n                def foo() -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class H:\n                @staticmethod\n                @final\n                def foo(): pass\n            \"\"\",\n            error=\"H.foo\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class I:\n                @classmethod\n                def foo(cls) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class I:\n                @final\n                @classmethod\n                def foo(cls): pass\n            \"\"\",\n            error=\"I.foo\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class J:\n                @classmethod\n                def foo(cls) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class J:\n                @classmethod\n                @final\n                def foo(cls): pass\n            \"\"\",\n            error=\"J.foo\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class K:\n                @property\n                def foo(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class K:\n                @property\n                @final\n                def foo(self): return 42\n            \"\"\",\n            error=\"K.foo\",\n        )\n        # This test wouldn't pass,\n        # because the runtime can't set __final__ on instances of builtins.property,\n        # so stubtest has non way of knowing that the runtime was decorated with @final:\n        #\n        # yield Case(\n        #     stub=\"\"\"\n        #     class K2:\n        #         @property\n        #         def foo(self) -> int: ...\n        #     \"\"\",\n        #     runtime=\"\"\"\n        #     class K2:\n        #         @final\n        #         @property\n        #         def foo(self): return 42\n        #     \"\"\",\n        #     error=\"K2.foo\",\n        # )\n        yield Case(\n            stub=\"\"\"\n            class L:\n                def foo(self, obj: int) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class L:\n                @final\n                @functools.lru_cache()\n                def foo(self, obj): return obj * 2\n            \"\"\",\n            error=\"L.foo\",\n        )\n\n    @collect_cases\n    def test_name_mangling(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            class X:\n                def __mangle_good(self, text: str) -> None: ...\n                def __mangle_bad(self, number: int) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class X:\n                def __mangle_good(self, text): pass\n                def __mangle_bad(self, text): pass\n            \"\"\",\n            error=\"X.__mangle_bad\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class Klass:\n                class __Mangled1:\n                    class __Mangled2:\n                        def __mangle_good(self, text: str) -> None: ...\n                        def __mangle_bad(self, number: int) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class Klass:\n                class __Mangled1:\n                    class __Mangled2:\n                        def __mangle_good(self, text): pass\n                        def __mangle_bad(self, text): pass\n            \"\"\",\n            error=\"Klass.__Mangled1.__Mangled2.__mangle_bad\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class __Dunder__:\n                def __mangle_good(self, text: str) -> None: ...\n                def __mangle_bad(self, number: int) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class __Dunder__:\n                def __mangle_good(self, text): pass\n                def __mangle_bad(self, text): pass\n            \"\"\",\n            error=\"__Dunder__.__mangle_bad\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class _Private:\n                def __mangle_good(self, text: str) -> None: ...\n                def __mangle_bad(self, number: int) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class _Private:\n                def __mangle_good(self, text): pass\n                def __mangle_bad(self, text): pass\n            \"\"\",\n            error=\"_Private.__mangle_bad\",\n        )\n\n    @collect_cases\n    def test_mro(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            class A:\n                def foo(self, x: int) -> None: ...\n            class B(A):\n                pass\n            class C(A):\n                pass\n            \"\"\",\n            runtime=\"\"\"\n            class A:\n                def foo(self, x: int) -> None: ...\n            class B(A):\n                def foo(self, x: int) -> None: ...\n            class C(A):\n                def foo(self, y: int) -> None: ...\n            \"\"\",\n            error=\"C.foo\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class X: ...\n            \"\"\",\n            runtime=\"\"\"\n            class X:\n                def __init__(self, x): pass\n            \"\"\",\n            error=\"X.__init__\",\n        )\n\n    @collect_cases\n    def test_good_literal(self) -> Iterator[Case]:\n        yield Case(\n            stub=r\"\"\"\n            from typing import Literal\n\n            import enum\n            class Color(enum.Enum):\n                RED = ...\n\n            NUM: Literal[1]\n            CHAR: Literal['a']\n            FLAG: Literal[True]\n            NON: Literal[None]\n            BYT1: Literal[b'abc']\n            BYT2: Literal[b'\\x90']\n            ENUM: Literal[Color.RED]\n            \"\"\",\n            runtime=r\"\"\"\n            import enum\n            class Color(enum.Enum):\n                RED = 3\n\n            NUM = 1\n            CHAR = 'a'\n            NON = None\n            FLAG = True\n            BYT1 = b\"abc\"\n            BYT2 = b'\\x90'\n            ENUM = Color.RED\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_bad_literal(self) -> Iterator[Case]:\n        yield Case(\"from typing import Literal\", \"\", None)  # dummy case\n        yield Case(\n            stub=\"INT_FLOAT_MISMATCH: Literal[1]\",\n            runtime=\"INT_FLOAT_MISMATCH = 1.0\",\n            error=\"INT_FLOAT_MISMATCH\",\n        )\n        yield Case(stub=\"WRONG_INT: Literal[1]\", runtime=\"WRONG_INT = 2\", error=\"WRONG_INT\")\n        yield Case(stub=\"WRONG_STR: Literal['a']\", runtime=\"WRONG_STR = 'b'\", error=\"WRONG_STR\")\n        yield Case(\n            stub=\"BYTES_STR_MISMATCH: Literal[b'value']\",\n            runtime=\"BYTES_STR_MISMATCH = 'value'\",\n            error=\"BYTES_STR_MISMATCH\",\n        )\n        yield Case(\n            stub=\"STR_BYTES_MISMATCH: Literal['value']\",\n            runtime=\"STR_BYTES_MISMATCH = b'value'\",\n            error=\"STR_BYTES_MISMATCH\",\n        )\n        yield Case(\n            stub=\"WRONG_BYTES: Literal[b'abc']\",\n            runtime=\"WRONG_BYTES = b'xyz'\",\n            error=\"WRONG_BYTES\",\n        )\n        yield Case(\n            stub=\"WRONG_BOOL_1: Literal[True]\",\n            runtime=\"WRONG_BOOL_1 = False\",\n            error=\"WRONG_BOOL_1\",\n        )\n        yield Case(\n            stub=\"WRONG_BOOL_2: Literal[False]\",\n            runtime=\"WRONG_BOOL_2 = True\",\n            error=\"WRONG_BOOL_2\",\n        )\n\n    @collect_cases\n    def test_special_subtype(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            b1: bool\n            b2: bool\n            b3: bool\n            \"\"\",\n            runtime=\"\"\"\n            b1 = 0\n            b2 = 1\n            b3 = 2\n            \"\"\",\n            error=\"b3\",\n        )\n        yield Case(\n            stub=\"\"\"\n            from typing import TypedDict\n\n            class _Options(TypedDict):\n                a: str\n                b: int\n\n            opt1: _Options\n            opt2: _Options\n            opt3: _Options\n            \"\"\",\n            runtime=\"\"\"\n            opt1 = {\"a\": \"3.\", \"b\": 14}\n            opt2 = {\"some\": \"stuff\"}  # false negative\n            opt3 = 0\n            \"\"\",\n            error=\"opt3\",\n        )\n\n    @collect_cases\n    def test_runtime_typing_objects(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"from typing import Protocol, TypedDict\",\n            runtime=\"from typing import Protocol, TypedDict\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class X(Protocol):\n                bar: int\n                def foo(self, x: int, y: bytes = ...) -> str: ...\n            \"\"\",\n            runtime=\"\"\"\n            class X(Protocol):\n                bar: int\n                def foo(self, x: int, y: bytes = ...) -> str: ...\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class Y(TypedDict):\n                a: int\n            \"\"\",\n            runtime=\"\"\"\n            class Y(TypedDict):\n                a: int\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_named_tuple(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"from typing import NamedTuple\",\n            runtime=\"from typing import NamedTuple\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class X1(NamedTuple):\n                bar: int\n                foo: str = ...\n            \"\"\",\n            runtime=\"\"\"\n            class X1(NamedTuple):\n                bar: int\n                foo: str = 'a'\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class X2(NamedTuple):\n                bar: int\n                foo: str\n            \"\"\",\n            runtime=\"\"\"\n            class X2(NamedTuple):\n                bar: int\n                foo: str = 'a'\n            \"\"\",\n            # `__new__` will miss a default value for a `foo` parameter,\n            # but we don't generate special errors for `foo` missing `...` part.\n            error=\"X2.__new__\",\n        )\n\n    @collect_cases\n    def test_named_tuple_typing_and_collections(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"from typing import NamedTuple\",\n            runtime=\"from collections import namedtuple\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class X1(NamedTuple):\n                bar: int\n                foo: str = ...\n            \"\"\",\n            runtime=\"\"\"\n            X1 = namedtuple('X1', ['bar', 'foo'], defaults=['a'])\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class X2(NamedTuple):\n                bar: int\n                foo: str\n            \"\"\",\n            runtime=\"\"\"\n            X2 = namedtuple('X1', ['bar', 'foo'], defaults=['a'])\n            \"\"\",\n            error=\"X2.__new__\",\n        )\n\n    @collect_cases\n    def test_type_var(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"from typing import TypeVar\", runtime=\"from typing import TypeVar\", error=None\n        )\n        yield Case(stub=\"A = TypeVar('A')\", runtime=\"A = TypeVar('A')\", error=None)\n        yield Case(stub=\"B = TypeVar('B')\", runtime=\"B = 5\", error=\"B\")\n        yield Case(\n            stub=\"from typing import ParamSpec\", runtime=\"from typing import ParamSpec\", error=None\n        )\n        yield Case(stub=\"C = ParamSpec('C')\", runtime=\"C = ParamSpec('C')\", error=None)\n\n    @collect_cases\n    def test_metaclass_match(self) -> Iterator[Case]:\n        yield Case(stub=\"class Meta(type): ...\", runtime=\"class Meta(type): ...\", error=None)\n        yield Case(stub=\"class A0: ...\", runtime=\"class A0: ...\", error=None)\n        yield Case(\n            stub=\"class A1(metaclass=Meta): ...\",\n            runtime=\"class A1(metaclass=Meta): ...\",\n            error=None,\n        )\n        yield Case(stub=\"class A2: ...\", runtime=\"class A2(metaclass=Meta): ...\", error=\"A2\")\n        yield Case(stub=\"class A3(metaclass=Meta): ...\", runtime=\"class A3: ...\", error=\"A3\")\n\n        # Explicit `type` metaclass can always be added in any part:\n        yield Case(\n            stub=\"class T1(metaclass=type): ...\",\n            runtime=\"class T1(metaclass=type): ...\",\n            error=None,\n        )\n        yield Case(stub=\"class T2: ...\", runtime=\"class T2(metaclass=type): ...\", error=None)\n        yield Case(stub=\"class T3(metaclass=type): ...\", runtime=\"class T3: ...\", error=None)\n\n        # Explicit check that `_protected` names are also supported:\n        yield Case(stub=\"class _P1(type): ...\", runtime=\"class _P1(type): ...\", error=None)\n        yield Case(stub=\"class P2: ...\", runtime=\"class P2(metaclass=_P1): ...\", error=\"P2\")\n\n        # With inheritance:\n        yield Case(\n            stub=\"\"\"\n            class I1(metaclass=Meta): ...\n            class S1(I1): ...\n            \"\"\",\n            runtime=\"\"\"\n            class I1(metaclass=Meta): ...\n            class S1(I1): ...\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class I2(metaclass=Meta): ...\n            class S2: ...  # missing inheritance\n            \"\"\",\n            runtime=\"\"\"\n            class I2(metaclass=Meta): ...\n            class S2(I2): ...\n            \"\"\",\n            error=\"S2\",\n        )\n\n    @collect_cases\n    def test_metaclass_abcmeta(self) -> Iterator[Case]:\n        # Handling abstract metaclasses is special:\n        yield Case(stub=\"from abc import ABCMeta\", runtime=\"from abc import ABCMeta\", error=None)\n        yield Case(\n            stub=\"class A1(metaclass=ABCMeta): ...\",\n            runtime=\"class A1(metaclass=ABCMeta): ...\",\n            error=None,\n        )\n        # Stubs cannot miss abstract metaclass:\n        yield Case(stub=\"class A2: ...\", runtime=\"class A2(metaclass=ABCMeta): ...\", error=\"A2\")\n        # But, stubs can add extra abstract metaclass, this might be a typing hack:\n        yield Case(stub=\"class A3(metaclass=ABCMeta): ...\", runtime=\"class A3: ...\", error=None)\n\n    @collect_cases\n    def test_abstract_methods(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            from abc import abstractmethod\n            from typing import overload\n            \"\"\",\n            runtime=\"from abc import abstractmethod\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class A1:\n                def some(self) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class A1:\n                @abstractmethod\n                def some(self) -> None: ...\n            \"\"\",\n            error=\"A1.some\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class A2:\n                @abstractmethod\n                def some(self) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class A2:\n                @abstractmethod\n                def some(self) -> None: ...\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class A3:\n                @overload\n                def some(self, other: int) -> str: ...\n                @overload\n                def some(self, other: str) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class A3:\n                @abstractmethod\n                def some(self, other) -> None: ...\n            \"\"\",\n            error=\"A3.some\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class A4:\n                @overload\n                @abstractmethod\n                def some(self, other: int) -> str: ...\n                @overload\n                @abstractmethod\n                def some(self, other: str) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class A4:\n                @abstractmethod\n                def some(self, other) -> None: ...\n            \"\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            class A5:\n                @abstractmethod\n                @overload\n                def some(self, other: int) -> str: ...\n                @abstractmethod\n                @overload\n                def some(self, other: str) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class A5:\n                @abstractmethod\n                def some(self, other) -> None: ...\n            \"\"\",\n            error=None,\n        )\n        # Runtime can miss `@abstractmethod`:\n        yield Case(\n            stub=\"\"\"\n            class A6:\n                @abstractmethod\n                def some(self) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class A6:\n                def some(self) -> None: ...\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_abstract_properties(self) -> Iterator[Case]:\n        # TODO: test abstract properties with setters\n        yield Case(\n            stub=\"from abc import abstractmethod\",\n            runtime=\"from abc import abstractmethod\",\n            error=None,\n        )\n        # Ensure that `@property` also can be abstract:\n        yield Case(\n            stub=\"\"\"\n            class AP1:\n                @property\n                def some(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class AP1:\n                @property\n                @abstractmethod\n                def some(self) -> int: ...\n            \"\"\",\n            error=\"AP1.some\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class AP1_2:\n                def some(self) -> int: ...  # missing `@property` decorator\n            \"\"\",\n            runtime=\"\"\"\n            class AP1_2:\n                @property\n                @abstractmethod\n                def some(self) -> int: ...\n            \"\"\",\n            error=\"AP1_2.some\",\n        )\n        yield Case(\n            stub=\"\"\"\n            class AP2:\n                @property\n                @abstractmethod\n                def some(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class AP2:\n                @property\n                @abstractmethod\n                def some(self) -> int: ...\n            \"\"\",\n            error=None,\n        )\n        # Runtime can miss `@abstractmethod`:\n        yield Case(\n            stub=\"\"\"\n            class AP3:\n                @property\n                @abstractmethod\n                def some(self) -> int: ...\n            \"\"\",\n            runtime=\"\"\"\n            class AP3:\n                @property\n                def some(self) -> int: ...\n            \"\"\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_type_check_only(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"from typing import type_check_only, overload\",\n            runtime=\"from typing import overload\",\n            error=None,\n        )\n        # You can have public types that are only defined in stubs\n        # with `@type_check_only`:\n        yield Case(\n            stub=\"\"\"\n            @type_check_only\n            class A1: ...\n            \"\"\",\n            runtime=\"\",\n            error=None,\n        )\n        # Having `@type_check_only` on a type that exists at runtime is an error\n        yield Case(\n            stub=\"\"\"\n            @type_check_only\n            class A2: ...\n            \"\"\",\n            runtime=\"class A2: ...\",\n            error=\"A2\",\n        )\n        # The same is true for NamedTuples and TypedDicts:\n        yield Case(\n            stub=\"from typing import NamedTuple, TypedDict\",\n            runtime=\"from typing import NamedTuple, TypedDict\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            @type_check_only\n            class NT1(NamedTuple): ...\n            \"\"\",\n            runtime=\"class NT1(NamedTuple): ...\",\n            error=\"NT1\",\n        )\n        yield Case(\n            stub=\"\"\"\n            @type_check_only\n            class TD1(TypedDict): ...\n            \"\"\",\n            runtime=\"class TD1(TypedDict): ...\",\n            error=\"TD1\",\n        )\n        # The same is true for functions:\n        yield Case(\n            stub=\"\"\"\n            @type_check_only\n            def func1() -> None: ...\n            \"\"\",\n            runtime=\"\",\n            error=None,\n        )\n        yield Case(\n            stub=\"\"\"\n            @type_check_only\n            def func2() -> None: ...\n            \"\"\",\n            runtime=\"def func2() -> None: ...\",\n            error=\"func2\",\n        )\n        # A type that exists at runtime is allowed to alias a type marked\n        # as '@type_check_only' in the stubs.\n        yield Case(\n            stub=\"\"\"\n            @type_check_only\n            class _X1: ...\n            X2 = _X1\n            \"\"\",\n            runtime=\"class X2: ...\",\n            error=None,\n        )\n\n    @collect_cases\n    def test_type_default_protocol(self) -> Iterator[Case]:\n        yield Case(\n            stub=\"\"\"\n            from typing import Protocol\n\n            class _FormatterClass(Protocol):\n                def __call__(self, *, prog: str) -> HelpFormatter: ...\n\n            class ArgumentParser:\n                def __init__(self, formatter_class: _FormatterClass = ...) -> None: ...\n\n            class HelpFormatter:\n                def __init__(self, prog: str, indent_increment: int = 2) -> None: ...\n            \"\"\",\n            runtime=\"\"\"\n            class HelpFormatter:\n                def __init__(self, prog, indent_increment=2) -> None: ...\n\n            class ArgumentParser:\n                def __init__(self, formatter_class=HelpFormatter): ...\n            \"\"\",\n            error=None,\n        )\n\n\ndef remove_color_code(s: str) -> str:\n    return re.sub(\"\\\\x1b.*?m\", \"\", s)  # this works!\n\n\nclass StubtestMiscUnit(unittest.TestCase):\n    def test_output(self) -> None:\n        output = run_stubtest(\n            stub=\"def bad(number: int, text: str) -> None: ...\",\n            runtime=\"def bad(num, text): pass\",\n            options=[],\n        )\n        expected = (\n            f'error: {TEST_MODULE_NAME}.bad is inconsistent, stub parameter \"number\" differs '\n            'from runtime parameter \"num\"\\n'\n            f\"Stub: in file {TEST_MODULE_NAME}.pyi:1\\n\"\n            \"def (number: int, text: str)\\n\"\n            f\"Runtime: in file {TEST_MODULE_NAME}.py:1\\ndef (num, text)\\n\\n\"\n            \"Found 1 error (checked 1 module)\\n\"\n        )\n        assert output == expected\n\n        output = run_stubtest(\n            stub=\"def bad(number: int, text: str) -> None: ...\",\n            runtime=\"def bad(num, text): pass\",\n            options=[\"--concise\"],\n        )\n        expected = (\n            \"{}.bad is inconsistent, \"\n            'stub parameter \"number\" differs from runtime parameter \"num\"\\n'.format(\n                TEST_MODULE_NAME\n            )\n        )\n        assert output == expected\n\n    def test_reexport_reports_import_location(self) -> None:\n        with use_tmp_dir(TEST_MODULE_NAME) as tmp_dir:\n            Path(\"builtins.pyi\").write_text(stubtest_builtins_stub)\n            Path(\"typing.pyi\").write_text(stubtest_typing_stub)\n            Path(\"enum.pyi\").write_text(stubtest_enum_stub)\n\n            os.makedirs(\"test_module\", exist_ok=True)\n            Path(\"test_module/__init__.pyi\").write_text(\"from .mod import f\")\n            Path(\"test_module/__init__.py\").write_text(\"from .mod import f\")\n            Path(\"test_module/mod.pyi\").write_text(\"def f(self) -> None: ...\")\n            Path(\"test_module/mod.py\").write_text(\"def f(self, x): pass\")\n\n            output = io.StringIO()\n            outerr = io.StringIO()\n            with contextlib.redirect_stdout(output), contextlib.redirect_stderr(outerr):\n                test_stubs(parse_options([TEST_MODULE_NAME]), use_builtins_fixtures=True)\n\n            filtered_output = remove_color_code(\n                output.getvalue()\n                .replace(os.path.realpath(tmp_dir) + os.sep, \"\")\n                .replace(tmp_dir + os.sep, \"\")\n            )\n\n        assert filtered_output.count('stub does not have parameter \"x\"') == 1\n        assert \"__init__.pyi\" not in filtered_output\n        assert \"mod.py:1\" in filtered_output\n\n    def test_ignore_flags(self) -> None:\n        output = run_stubtest(\n            stub=\"\", runtime=\"__all__ = ['f']\\ndef f(): pass\", options=[\"--ignore-missing-stub\"]\n        )\n        assert output == \"Success: no issues found in 1 module\\n\"\n\n        output = run_stubtest(stub=\"\", runtime=\"def f(): pass\", options=[\"--ignore-missing-stub\"])\n        assert output == \"Success: no issues found in 1 module\\n\"\n\n        output = run_stubtest(\n            stub=\"def f(__a): ...\", runtime=\"def f(a): pass\", options=[\"--ignore-positional-only\"]\n        )\n        assert output == \"Success: no issues found in 1 module\\n\"\n\n    def test_allowlist(self) -> None:\n        # Can't use this as a context because Windows\n        allowlist = tempfile.NamedTemporaryFile(mode=\"w+\", delete=False)\n        try:\n            with allowlist:\n                allowlist.write(f\"{TEST_MODULE_NAME}.bad  # comment\\n# comment\")\n\n            output = run_stubtest(\n                stub=\"def bad(number: int, text: str) -> None: ...\",\n                runtime=\"def bad(asdf, text): pass\",\n                options=[\"--allowlist\", allowlist.name],\n            )\n            assert output == \"Success: no issues found in 1 module\\n\"\n\n            # test unused entry detection\n            output = run_stubtest(stub=\"\", runtime=\"\", options=[\"--allowlist\", allowlist.name])\n            assert output == (\n                f\"note: unused allowlist entry {TEST_MODULE_NAME}.bad\\n\"\n                \"Found 1 error (checked 1 module)\\n\"\n            )\n\n            output = run_stubtest(\n                stub=\"\",\n                runtime=\"\",\n                options=[\"--allowlist\", allowlist.name, \"--ignore-unused-allowlist\"],\n            )\n            assert output == \"Success: no issues found in 1 module\\n\"\n\n            # test regex matching\n            with open(allowlist.name, mode=\"w+\") as f:\n                f.write(f\"{TEST_MODULE_NAME}.b.*\\n\")\n                f.write(\"(unused_missing)?\\n\")\n                f.write(\"unused.*\\n\")\n\n            output = run_stubtest(\n                stub=textwrap.dedent(\"\"\"\n                    def good() -> None: ...\n                    def bad(number: int) -> None: ...\n                    def also_bad(number: int) -> None: ...\n                    \"\"\".lstrip(\"\\n\")),\n                runtime=textwrap.dedent(\"\"\"\n                    def good(): pass\n                    def bad(asdf): pass\n                    def also_bad(asdf): pass\n                    \"\"\".lstrip(\"\\n\")),\n                options=[\"--allowlist\", allowlist.name, \"--generate-allowlist\"],\n            )\n            assert output == (\n                f\"note: unused allowlist entry unused.*\\n{TEST_MODULE_NAME}.also_bad\\n\"\n            )\n        finally:\n            os.unlink(allowlist.name)\n\n    def test_mypy_build(self) -> None:\n        output = run_stubtest(stub=\"+\", runtime=\"\", options=[])\n        assert output == (\n            \"error: not checking stubs due to failed mypy compile:\\n{}.pyi:1: \"\n            \"error: Invalid syntax  [syntax]\\n\".format(TEST_MODULE_NAME)\n        )\n\n        output = run_stubtest(stub=\"def f(): ...\\ndef f(): ...\", runtime=\"\", options=[])\n        assert output == (\n            \"error: not checking stubs due to mypy build errors:\\n{}.pyi:2: \"\n            'error: Name \"f\" already defined on line 1  [no-redef]\\n'.format(TEST_MODULE_NAME)\n        )\n\n    def test_missing_stubs(self) -> None:\n        output = io.StringIO()\n        with contextlib.redirect_stdout(output):\n            test_stubs(parse_options([\"not_a_module\"]))\n        assert remove_color_code(output.getvalue()) == (\n            \"error: not_a_module failed to find stubs\\n\"\n            \"Stub:\\nMISSING\\nRuntime:\\nN/A\\n\\n\"\n            \"Found 1 error (checked 1 module)\\n\"\n        )\n\n    def test_only_py(self) -> None:\n        # in this case, stubtest will check the py against itself\n        # this is useful to support packages with a mix of stubs and inline types\n        with use_tmp_dir(TEST_MODULE_NAME):\n            with open(f\"{TEST_MODULE_NAME}.py\", \"w\") as f:\n                f.write(\"a = 1\")\n            output = io.StringIO()\n            with contextlib.redirect_stdout(output):\n                test_stubs(parse_options([TEST_MODULE_NAME]))\n            output_str = remove_color_code(output.getvalue())\n            assert output_str == \"Success: no issues found in 1 module\\n\"\n\n    def test_get_typeshed_stdlib_modules(self) -> None:\n        stdlib = mypy.stubtest.get_typeshed_stdlib_modules(None, (3, 7))\n        assert \"builtins\" in stdlib\n        assert \"os\" in stdlib\n        assert \"os.path\" in stdlib\n        assert \"asyncio\" in stdlib\n        assert \"graphlib\" not in stdlib\n        assert \"formatter\" in stdlib\n        assert \"contextvars\" in stdlib  # 3.7+\n        assert \"importlib.metadata\" not in stdlib\n\n        stdlib = mypy.stubtest.get_typeshed_stdlib_modules(None, (3, 10))\n        assert \"graphlib\" in stdlib\n        assert \"formatter\" not in stdlib\n        assert \"importlib.metadata\" in stdlib\n\n    def test_signature(self) -> None:\n        def f(a: int, b: int, *, c: int, d: int = 0, **kwargs: Any) -> None:\n            pass\n\n        assert (\n            str(mypy.stubtest.Signature.from_inspect_signature(inspect.signature(f)))\n            == \"def (a, b, *, c, d = ..., **kwargs)\"\n        )\n\n    def test_builtin_signature_with_unrepresentable_default(self) -> None:\n        sig = mypy.stubtest.safe_inspect_signature(bytes.hex)\n        assert sig is not None\n        assert (\n            str(mypy.stubtest.Signature.from_inspect_signature(sig))\n            == \"def (self, sep = ..., bytes_per_sep = ...)\"\n        )\n\n    def test_overload_signature(self) -> None:\n        # The same argument as both positional-only and pos-or-kw in\n        # different overloads previously produced incorrect signatures\n        source = \"\"\"\n        from typing import overload\n        @overload\n        def myfunction(arg: int) -> None: ...\n        @overload\n        def myfunction(arg: str, /) -> None: ...\n        \"\"\"\n        result = build_helper(source)\n        stub = result.files[\"__main__\"].names[\"myfunction\"].node\n        assert isinstance(stub, nodes.OverloadedFuncDef)\n        sig = mypy.stubtest.Signature.from_overloadedfuncdef(stub)\n        assert str(sig) == \"def (arg: int | str)\"\n\n    def test_config_file(self) -> None:\n        runtime = \"temp = 5\\n\"\n        stub = \"from decimal import Decimal\\ntemp: Decimal\\n\"\n        config_file = f\"[mypy]\\nplugins={root_dir}/test-data/unit/plugins/decimal_to_int.py\\n\"\n        output = run_stubtest(stub=stub, runtime=runtime, options=[])\n        assert output == (\n            f\"error: {TEST_MODULE_NAME}.temp variable differs from runtime type Literal[5]\\n\"\n            f\"Stub: in file {TEST_MODULE_NAME}.pyi:2\\n_decimal.Decimal\\nRuntime:\\n5\\n\\n\"\n            \"Found 1 error (checked 1 module)\\n\"\n        )\n        output = run_stubtest(stub=stub, runtime=runtime, options=[], config_file=config_file)\n        assert output == \"Success: no issues found in 1 module\\n\"\n\n    def test_config_file_error_codes(self) -> None:\n        runtime = \"temp = 5\\n\"\n        stub = \"temp = SOME_GLOBAL_CONST\"\n        output = run_stubtest(stub=stub, runtime=runtime, options=[])\n        assert output == (\n            \"error: not checking stubs due to mypy build errors:\\n\"\n            'test_module.pyi:1: error: Name \"SOME_GLOBAL_CONST\" is not defined  [name-defined]\\n'\n        )\n\n        config_file = \"[mypy]\\ndisable_error_code = name-defined\\n\"\n        output = run_stubtest(stub=stub, runtime=runtime, options=[], config_file=config_file)\n        assert output == \"Success: no issues found in 1 module\\n\"\n\n    def test_config_file_error_codes_invalid(self) -> None:\n        runtime = \"temp = 5\\n\"\n        stub = \"temp: int\\n\"\n        config_file = \"[mypy]\\ndisable_error_code = not-a-valid-name\\n\"\n        output = io.StringIO()\n        outerr = io.StringIO()\n        with raises(SystemExit):\n            run_stubtest_with_stderr(\n                stub=stub,\n                runtime=runtime,\n                options=[],\n                config_file=config_file,\n                output=output,\n                outerr=outerr,\n            )\n\n        assert output.getvalue() == \"error: Invalid error code(s): not-a-valid-name\\n\"\n        assert outerr.getvalue() == \"\"\n\n    def test_config_file_wrong_incomplete_feature(self) -> None:\n        runtime = \"x = 1\\n\"\n        stub = \"x: int\\n\"\n        config_file = \"[mypy]\\nenable_incomplete_feature = Unpack\\n\"\n        output = run_stubtest(stub=stub, runtime=runtime, options=[], config_file=config_file)\n        assert output == (\n            \"warning: Warning: Unpack is already enabled by default\\n\"\n            \"Success: no issues found in 1 module\\n\"\n        )\n\n        config_file = \"[mypy]\\nenable_incomplete_feature = not-a-valid-name\\n\"\n        with self.assertRaises(SystemExit):\n            run_stubtest(stub=stub, runtime=runtime, options=[], config_file=config_file)\n\n    def test_no_modules(self) -> None:\n        output = io.StringIO()\n        with contextlib.redirect_stdout(output):\n            test_stubs(parse_options([]))\n        assert remove_color_code(output.getvalue()) == \"error: no modules to check\\n\"\n\n    def test_module_and_typeshed(self) -> None:\n        output = io.StringIO()\n        with contextlib.redirect_stdout(output):\n            test_stubs(parse_options([\"--check-typeshed\", \"some_module\"]))\n        assert remove_color_code(output.getvalue()) == (\n            \"error: cannot pass both --check-typeshed and a list of modules\\n\"\n        )\n"
  },
  {
    "path": "mypy/test/testsubtypes.py",
    "content": "from __future__ import annotations\n\nfrom mypy.nodes import CONTRAVARIANT, COVARIANT, INVARIANT\nfrom mypy.subtypes import is_subtype\nfrom mypy.test.helpers import Suite\nfrom mypy.test.typefixture import InterfaceTypeFixture, TypeFixture\nfrom mypy.types import Instance, TupleType, Type, UninhabitedType, UnpackType\n\n\nclass SubtypingSuite(Suite):\n    def setUp(self) -> None:\n        self.fx = TypeFixture(INVARIANT)\n        self.fx_contra = TypeFixture(CONTRAVARIANT)\n        self.fx_co = TypeFixture(COVARIANT)\n\n    def test_trivial_cases(self) -> None:\n        for simple in self.fx_co.a, self.fx_co.o, self.fx_co.b:\n            self.assert_subtype(simple, simple)\n\n    def test_instance_subtyping(self) -> None:\n        self.assert_strict_subtype(self.fx.a, self.fx.o)\n        self.assert_strict_subtype(self.fx.b, self.fx.o)\n        self.assert_strict_subtype(self.fx.b, self.fx.a)\n\n        self.assert_not_subtype(self.fx.a, self.fx.d)\n        self.assert_not_subtype(self.fx.b, self.fx.c)\n\n    def test_simple_generic_instance_subtyping_invariant(self) -> None:\n        self.assert_subtype(self.fx.ga, self.fx.ga)\n        self.assert_subtype(self.fx.hab, self.fx.hab)\n\n        self.assert_not_subtype(self.fx.ga, self.fx.g2a)\n        self.assert_not_subtype(self.fx.ga, self.fx.gb)\n        self.assert_not_subtype(self.fx.gb, self.fx.ga)\n\n    def test_simple_generic_instance_subtyping_covariant(self) -> None:\n        self.assert_subtype(self.fx_co.ga, self.fx_co.ga)\n        self.assert_subtype(self.fx_co.hab, self.fx_co.hab)\n\n        self.assert_not_subtype(self.fx_co.ga, self.fx_co.g2a)\n        self.assert_not_subtype(self.fx_co.ga, self.fx_co.gb)\n        self.assert_subtype(self.fx_co.gb, self.fx_co.ga)\n\n    def test_simple_generic_instance_subtyping_contravariant(self) -> None:\n        self.assert_subtype(self.fx_contra.ga, self.fx_contra.ga)\n        self.assert_subtype(self.fx_contra.hab, self.fx_contra.hab)\n\n        self.assert_not_subtype(self.fx_contra.ga, self.fx_contra.g2a)\n        self.assert_subtype(self.fx_contra.ga, self.fx_contra.gb)\n        self.assert_not_subtype(self.fx_contra.gb, self.fx_contra.ga)\n\n    def test_generic_subtyping_with_inheritance_invariant(self) -> None:\n        self.assert_subtype(self.fx.gsab, self.fx.gb)\n        self.assert_not_subtype(self.fx.gsab, self.fx.ga)\n        self.assert_not_subtype(self.fx.gsaa, self.fx.gb)\n\n    def test_generic_subtyping_with_inheritance_covariant(self) -> None:\n        self.assert_subtype(self.fx_co.gsab, self.fx_co.gb)\n        self.assert_subtype(self.fx_co.gsab, self.fx_co.ga)\n        self.assert_not_subtype(self.fx_co.gsaa, self.fx_co.gb)\n\n    def test_generic_subtyping_with_inheritance_contravariant(self) -> None:\n        self.assert_subtype(self.fx_contra.gsab, self.fx_contra.gb)\n        self.assert_not_subtype(self.fx_contra.gsab, self.fx_contra.ga)\n        self.assert_subtype(self.fx_contra.gsaa, self.fx_contra.gb)\n\n    def test_interface_subtyping(self) -> None:\n        self.assert_subtype(self.fx.e, self.fx.f)\n        self.assert_equivalent(self.fx.f, self.fx.f)\n        self.assert_not_subtype(self.fx.a, self.fx.f)\n\n    def test_generic_interface_subtyping(self) -> None:\n        # TODO make this work\n        fx2 = InterfaceTypeFixture()\n\n        self.assert_subtype(fx2.m1, fx2.gfa)\n        self.assert_not_subtype(fx2.m1, fx2.gfb)\n\n        self.assert_equivalent(fx2.gfa, fx2.gfa)\n\n    def test_basic_callable_subtyping(self) -> None:\n        self.assert_strict_subtype(\n            self.fx.callable(self.fx.o, self.fx.d), self.fx.callable(self.fx.a, self.fx.d)\n        )\n        self.assert_strict_subtype(\n            self.fx.callable(self.fx.d, self.fx.b), self.fx.callable(self.fx.d, self.fx.a)\n        )\n\n        self.assert_strict_subtype(\n            self.fx.callable(self.fx.a, UninhabitedType()), self.fx.callable(self.fx.a, self.fx.a)\n        )\n\n        self.assert_unrelated(\n            self.fx.callable(self.fx.a, self.fx.a, self.fx.a),\n            self.fx.callable(self.fx.a, self.fx.a),\n        )\n\n    def test_default_arg_callable_subtyping(self) -> None:\n        self.assert_strict_subtype(\n            self.fx.callable_default(1, self.fx.a, self.fx.d, self.fx.a),\n            self.fx.callable(self.fx.a, self.fx.d, self.fx.a),\n        )\n\n        self.assert_strict_subtype(\n            self.fx.callable_default(1, self.fx.a, self.fx.d, self.fx.a),\n            self.fx.callable(self.fx.a, self.fx.a),\n        )\n\n        self.assert_strict_subtype(\n            self.fx.callable_default(0, self.fx.a, self.fx.d, self.fx.a),\n            self.fx.callable_default(1, self.fx.a, self.fx.d, self.fx.a),\n        )\n\n        self.assert_unrelated(\n            self.fx.callable_default(1, self.fx.a, self.fx.d, self.fx.a),\n            self.fx.callable(self.fx.d, self.fx.d, self.fx.a),\n        )\n\n        self.assert_unrelated(\n            self.fx.callable_default(0, self.fx.a, self.fx.d, self.fx.a),\n            self.fx.callable_default(1, self.fx.a, self.fx.a, self.fx.a),\n        )\n\n        self.assert_unrelated(\n            self.fx.callable_default(1, self.fx.a, self.fx.a),\n            self.fx.callable(self.fx.a, self.fx.a, self.fx.a),\n        )\n\n    def test_var_arg_callable_subtyping_1(self) -> None:\n        self.assert_strict_subtype(\n            self.fx.callable_var_arg(0, self.fx.a, self.fx.a),\n            self.fx.callable_var_arg(0, self.fx.b, self.fx.a),\n        )\n\n    def test_var_arg_callable_subtyping_2(self) -> None:\n        self.assert_strict_subtype(\n            self.fx.callable_var_arg(0, self.fx.a, self.fx.a),\n            self.fx.callable(self.fx.b, self.fx.a),\n        )\n\n    def test_var_arg_callable_subtyping_3(self) -> None:\n        self.assert_strict_subtype(\n            self.fx.callable_var_arg(0, self.fx.a, self.fx.a), self.fx.callable(self.fx.a)\n        )\n\n    def test_var_arg_callable_subtyping_4(self) -> None:\n        self.assert_strict_subtype(\n            self.fx.callable_var_arg(1, self.fx.a, self.fx.d, self.fx.a),\n            self.fx.callable(self.fx.b, self.fx.a),\n        )\n\n    def test_var_arg_callable_subtyping_5(self) -> None:\n        self.assert_strict_subtype(\n            self.fx.callable_var_arg(0, self.fx.a, self.fx.d, self.fx.a),\n            self.fx.callable(self.fx.b, self.fx.a),\n        )\n\n    def test_var_arg_callable_subtyping_6(self) -> None:\n        self.assert_strict_subtype(\n            self.fx.callable_var_arg(0, self.fx.a, self.fx.f, self.fx.d),\n            self.fx.callable_var_arg(0, self.fx.b, self.fx.e, self.fx.d),\n        )\n\n    def test_var_arg_callable_subtyping_7(self) -> None:\n        self.assert_not_subtype(\n            self.fx.callable_var_arg(0, self.fx.b, self.fx.d),\n            self.fx.callable(self.fx.a, self.fx.d),\n        )\n\n    def test_var_arg_callable_subtyping_8(self) -> None:\n        self.assert_not_subtype(\n            self.fx.callable_var_arg(0, self.fx.b, self.fx.d),\n            self.fx.callable_var_arg(0, self.fx.a, self.fx.a, self.fx.d),\n        )\n        self.assert_subtype(\n            self.fx.callable_var_arg(0, self.fx.a, self.fx.d),\n            self.fx.callable_var_arg(0, self.fx.b, self.fx.b, self.fx.d),\n        )\n\n    def test_var_arg_callable_subtyping_9(self) -> None:\n        self.assert_not_subtype(\n            self.fx.callable_var_arg(0, self.fx.b, self.fx.b, self.fx.d),\n            self.fx.callable_var_arg(0, self.fx.a, self.fx.d),\n        )\n        self.assert_subtype(\n            self.fx.callable_var_arg(0, self.fx.a, self.fx.a, self.fx.d),\n            self.fx.callable_var_arg(0, self.fx.b, self.fx.d),\n        )\n\n    def test_type_callable_subtyping(self) -> None:\n        self.assert_subtype(self.fx.callable_type(self.fx.d, self.fx.a), self.fx.type_type)\n\n        self.assert_strict_subtype(\n            self.fx.callable_type(self.fx.d, self.fx.b), self.fx.callable(self.fx.d, self.fx.a)\n        )\n\n        self.assert_strict_subtype(\n            self.fx.callable_type(self.fx.a, self.fx.b), self.fx.callable(self.fx.a, self.fx.b)\n        )\n\n    def test_type_var_tuple(self) -> None:\n        self.assert_subtype(Instance(self.fx.gvi, []), Instance(self.fx.gvi, []))\n        self.assert_subtype(\n            Instance(self.fx.gvi, [self.fx.a, self.fx.b]),\n            Instance(self.fx.gvi, [self.fx.a, self.fx.b]),\n        )\n        self.assert_not_subtype(\n            Instance(self.fx.gvi, [self.fx.a, self.fx.b]),\n            Instance(self.fx.gvi, [self.fx.b, self.fx.a]),\n        )\n        self.assert_not_subtype(\n            Instance(self.fx.gvi, [self.fx.a, self.fx.b]), Instance(self.fx.gvi, [self.fx.a])\n        )\n\n        self.assert_subtype(\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss)]),\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss)]),\n        )\n        self.assert_not_subtype(\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss)]),\n            Instance(self.fx.gvi, [UnpackType(self.fx.us)]),\n        )\n\n        self.assert_not_subtype(\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss)]), Instance(self.fx.gvi, [])\n        )\n        self.assert_not_subtype(\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss)]), Instance(self.fx.gvi, [self.fx.anyt])\n        )\n\n    def test_type_var_tuple_with_prefix_suffix(self) -> None:\n        self.assert_subtype(\n            Instance(self.fx.gvi, [self.fx.a, UnpackType(self.fx.ss)]),\n            Instance(self.fx.gvi, [self.fx.a, UnpackType(self.fx.ss)]),\n        )\n        self.assert_subtype(\n            Instance(self.fx.gvi, [self.fx.a, self.fx.b, UnpackType(self.fx.ss)]),\n            Instance(self.fx.gvi, [self.fx.a, self.fx.b, UnpackType(self.fx.ss)]),\n        )\n        self.assert_not_subtype(\n            Instance(self.fx.gvi, [self.fx.a, UnpackType(self.fx.ss)]),\n            Instance(self.fx.gvi, [self.fx.b, UnpackType(self.fx.ss)]),\n        )\n        self.assert_not_subtype(\n            Instance(self.fx.gvi, [self.fx.a, UnpackType(self.fx.ss)]),\n            Instance(self.fx.gvi, [self.fx.a, self.fx.b, UnpackType(self.fx.ss)]),\n        )\n\n        self.assert_subtype(\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss), self.fx.a]),\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss), self.fx.a]),\n        )\n        self.assert_not_subtype(\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss), self.fx.a]),\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss), self.fx.b]),\n        )\n        self.assert_not_subtype(\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss), self.fx.a]),\n            Instance(self.fx.gvi, [UnpackType(self.fx.ss), self.fx.a, self.fx.b]),\n        )\n\n        self.assert_subtype(\n            Instance(self.fx.gvi, [self.fx.a, self.fx.b, UnpackType(self.fx.ss), self.fx.c]),\n            Instance(self.fx.gvi, [self.fx.a, self.fx.b, UnpackType(self.fx.ss), self.fx.c]),\n        )\n        self.assert_not_subtype(\n            Instance(self.fx.gvi, [self.fx.a, self.fx.b, UnpackType(self.fx.ss), self.fx.c]),\n            Instance(self.fx.gvi, [self.fx.a, UnpackType(self.fx.ss), self.fx.b, self.fx.c]),\n        )\n\n    def test_type_var_tuple_unpacked_variable_length_tuple(self) -> None:\n        self.assert_subtype(\n            Instance(self.fx.gvi, [self.fx.a, self.fx.a]),\n            Instance(self.fx.gvi, [UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))]),\n        )\n\n    def test_fallback_not_subtype_of_tuple(self) -> None:\n        self.assert_not_subtype(self.fx.a, TupleType([self.fx.b], fallback=self.fx.a))\n\n    # IDEA: Maybe add these test cases (they are tested pretty well in type\n    #       checker tests already):\n    #  * more interface subtyping test cases\n    #  * more generic interface subtyping test cases\n    #  * type variables\n    #  * tuple types\n    #  * None type\n    #  * any type\n    #  * generic function types\n\n    def assert_subtype(self, s: Type, t: Type) -> None:\n        assert is_subtype(s, t), f\"{s} not subtype of {t}\"\n\n    def assert_not_subtype(self, s: Type, t: Type) -> None:\n        assert not is_subtype(s, t), f\"{s} subtype of {t}\"\n\n    def assert_strict_subtype(self, s: Type, t: Type) -> None:\n        self.assert_subtype(s, t)\n        self.assert_not_subtype(t, s)\n\n    def assert_equivalent(self, s: Type, t: Type) -> None:\n        self.assert_subtype(s, t)\n        self.assert_subtype(t, s)\n\n    def assert_unrelated(self, s: Type, t: Type) -> None:\n        self.assert_not_subtype(s, t)\n        self.assert_not_subtype(t, s)\n"
  },
  {
    "path": "mypy/test/testtransform.py",
    "content": "\"\"\"Identity AST transform test cases\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.modulefinder import BuildSource\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal, normalize_error_messages, parse_options\nfrom mypy.test.visitors import TypeAssertTransformVisitor\n\n\nclass TransformSuite(DataSuite):\n    required_out_section = True\n    # Reuse semantic analysis test cases.\n    files = [\n        \"semanal-basic.test\",\n        \"semanal-expressions.test\",\n        \"semanal-classes.test\",\n        \"semanal-types.test\",\n        \"semanal-modules.test\",\n        \"semanal-statements.test\",\n        \"semanal-abstractclasses.test\",\n    ]\n    native_sep = True\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        test_transform(testcase)\n\n\ndef test_transform(testcase: DataDrivenTestCase) -> None:\n    \"\"\"Perform an identity transform test case.\"\"\"\n\n    try:\n        src = \"\\n\".join(testcase.input)\n        options = parse_options(src, testcase, 1)\n        options.use_builtins_fixtures = True\n        options.semantic_analysis_only = True\n        options.show_traceback = True\n        options.reveal_verbose_types = True\n        result = build.build(\n            sources=[BuildSource(\"main\", None, src)], options=options, alt_lib_path=test_temp_dir\n        )\n        a = result.errors\n        if a:\n            raise CompileError(a)\n        # Include string representations of the source files in the actual\n        # output.\n        for module in sorted(result.files.keys()):\n            if module in testcase.test_modules:\n                t = TypeAssertTransformVisitor()\n                t.test_only = True\n                file = t.mypyfile(result.files[module])\n                a += file.str_with_options(options).split(\"\\n\")\n    except CompileError as e:\n        a = e.messages\n    if testcase.normalize_output:\n        a = normalize_error_messages(a)\n    assert_string_arrays_equal(\n        testcase.output,\n        a,\n        f\"Invalid semantic analyzer output ({testcase.file}, line {testcase.line})\",\n    )\n"
  },
  {
    "path": "mypy/test/testtypegen.py",
    "content": "\"\"\"Test cases for the type checker: exporting inferred types\"\"\"\n\nfrom __future__ import annotations\n\nimport re\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.modulefinder import BuildSource\nfrom mypy.nodes import NameExpr, TempNode\nfrom mypy.options import Options\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal\nfrom mypy.test.visitors import SkippedNodeSearcher, ignore_node\nfrom mypy.util import short_type\n\n\nclass TypeExportSuite(DataSuite):\n    required_out_section = True\n    files = [\"typexport-basic.test\"]\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        try:\n            line = testcase.input[0]\n            mask = \"\"\n            if line.startswith(\"##\"):\n                mask = \"(\" + line[2:].strip() + \")$\"\n\n            src = \"\\n\".join(testcase.input)\n            options = Options()\n            options.strict_optional = False  # TODO: Enable strict optional checking\n            options.use_builtins_fixtures = True\n            options.show_traceback = True\n            options.export_types = True\n            options.preserve_asts = True\n            options.allow_empty_bodies = True\n            options.reveal_verbose_types = True\n            result = build.build(\n                sources=[BuildSource(\"main\", None, src)],\n                options=options,\n                alt_lib_path=test_temp_dir,\n            )\n            a = result.errors\n            map = result.types\n            nodes = map.keys()\n\n            # Ignore NameExpr nodes of variables with explicit (trivial) types\n            # to simplify output.\n            searcher = SkippedNodeSearcher()\n            for file in result.files.values():\n                searcher.ignore_file = file.fullname not in testcase.test_modules\n                file.accept(searcher)\n            ignored = searcher.nodes\n\n            # Filter nodes that should be included in the output.\n            keys = []\n            for node in nodes:\n                if isinstance(node, TempNode):\n                    continue\n                if node.line != -1 and map[node]:\n                    if ignore_node(node) or node in ignored:\n                        continue\n                    if re.match(mask, short_type(node)) or (\n                        isinstance(node, NameExpr) and re.match(mask, node.name)\n                    ):\n                        # Include node in output.\n                        keys.append(node)\n\n            for key in sorted(\n                keys,\n                key=lambda n: (n.line, short_type(n), str(n) + map[n].str_with_options(options)),\n            ):\n                ts = map[key].str_with_options(options).replace(\"*\", \"\")  # Remove erased tags\n                ts = ts.replace(\"__main__.\", \"\")\n                a.append(f\"{short_type(key)}({key.line}) : {ts}\")\n        except CompileError as e:\n            a = e.messages\n        assert_string_arrays_equal(\n            testcase.output,\n            a,\n            f\"Invalid type checker output ({testcase.file}, line {testcase.line})\",\n        )\n"
  },
  {
    "path": "mypy/test/testtypes.py",
    "content": "\"\"\"Test cases for mypy types and type operations.\"\"\"\n\nfrom __future__ import annotations\n\nimport re\nfrom unittest import TestCase, skipUnless\n\nfrom mypy.erasetype import erase_type, remove_instance_last_known_values\nfrom mypy.indirection import TypeIndirectionVisitor\nfrom mypy.join import join_types\nfrom mypy.meet import meet_types, narrow_declared_type\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_OPT,\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    CONTRAVARIANT,\n    COVARIANT,\n    INVARIANT,\n    ArgKind,\n    CallExpr,\n    Expression,\n    NameExpr,\n)\nfrom mypy.plugins.common import find_shallow_matching_overload_item\nfrom mypy.state import state\nfrom mypy.subtypes import is_more_precise, is_proper_subtype, is_same_type, is_subtype\nfrom mypy.test.helpers import Suite, assert_equal, assert_type, skip\nfrom mypy.test.typefixture import InterfaceTypeFixture, TypeFixture\nfrom mypy.typeops import false_only, make_simplified_union, true_only\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    ProperType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeType,\n    TypeVarId,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    get_proper_type,\n    has_recursive_types,\n)\n\n# Solving the import cycle:\nimport mypy.expandtype  # ruff: isort: skip\n\n\nclass TypesSuite(Suite):\n    def setUp(self) -> None:\n        self.x = UnboundType(\"X\")  # Helpers\n        self.y = UnboundType(\"Y\")\n        self.fx = TypeFixture()\n        self.function = self.fx.function\n\n    def test_any(self) -> None:\n        assert_equal(str(AnyType(TypeOfAny.special_form)), \"Any\")\n\n    def test_simple_unbound_type(self) -> None:\n        u = UnboundType(\"Foo\")\n        assert_equal(str(u), \"Foo?\")\n\n    def test_generic_unbound_type(self) -> None:\n        u = UnboundType(\"Foo\", [UnboundType(\"T\"), AnyType(TypeOfAny.special_form)])\n        assert_equal(str(u), \"Foo?[T?, Any]\")\n\n    def test_callable_type(self) -> None:\n        c = CallableType(\n            [self.x, self.y],\n            [ARG_POS, ARG_POS],\n            [None, None],\n            AnyType(TypeOfAny.special_form),\n            self.function,\n        )\n        assert_equal(str(c), \"def (X?, Y?) -> Any\")\n\n        c2 = CallableType([], [], [], NoneType(), self.fx.function)\n        assert_equal(str(c2), \"def ()\")\n\n    def test_callable_type_with_default_args(self) -> None:\n        c = CallableType(\n            [self.x, self.y],\n            [ARG_POS, ARG_OPT],\n            [None, None],\n            AnyType(TypeOfAny.special_form),\n            self.function,\n        )\n        assert_equal(str(c), \"def (X?, Y? =) -> Any\")\n\n        c2 = CallableType(\n            [self.x, self.y],\n            [ARG_OPT, ARG_OPT],\n            [None, None],\n            AnyType(TypeOfAny.special_form),\n            self.function,\n        )\n        assert_equal(str(c2), \"def (X? =, Y? =) -> Any\")\n\n    def test_callable_type_with_var_args(self) -> None:\n        c = CallableType(\n            [self.x], [ARG_STAR], [None], AnyType(TypeOfAny.special_form), self.function\n        )\n        assert_equal(str(c), \"def (*X?) -> Any\")\n\n        c2 = CallableType(\n            [self.x, self.y],\n            [ARG_POS, ARG_STAR],\n            [None, None],\n            AnyType(TypeOfAny.special_form),\n            self.function,\n        )\n        assert_equal(str(c2), \"def (X?, *Y?) -> Any\")\n\n        c3 = CallableType(\n            [self.x, self.y],\n            [ARG_OPT, ARG_STAR],\n            [None, None],\n            AnyType(TypeOfAny.special_form),\n            self.function,\n        )\n        assert_equal(str(c3), \"def (X? =, *Y?) -> Any\")\n\n    def test_tuple_type_str(self) -> None:\n        t1 = TupleType([], self.fx.std_tuple)\n        assert_equal(str(t1), \"tuple[()]\")\n        t2 = TupleType([self.x], self.fx.std_tuple)\n        assert_equal(str(t2), \"tuple[X?]\")\n        t3 = TupleType([self.x, AnyType(TypeOfAny.special_form)], self.fx.std_tuple)\n        assert_equal(str(t3), \"tuple[X?, Any]\")\n\n    def test_type_variable_binding(self) -> None:\n        assert_equal(\n            str(\n                TypeVarType(\n                    \"X\", \"X\", TypeVarId(1), [], self.fx.o, AnyType(TypeOfAny.from_omitted_generics)\n                )\n            ),\n            \"X\",\n        )\n        assert_equal(\n            str(\n                TypeVarType(\n                    \"X\",\n                    \"X\",\n                    TypeVarId(1),\n                    [self.x, self.y],\n                    self.fx.o,\n                    AnyType(TypeOfAny.from_omitted_generics),\n                )\n            ),\n            \"X\",\n        )\n\n    def test_generic_function_type(self) -> None:\n        c = CallableType(\n            [self.x, self.y],\n            [ARG_POS, ARG_POS],\n            [None, None],\n            self.y,\n            self.function,\n            name=None,\n            variables=[\n                TypeVarType(\n                    \"X\",\n                    \"X\",\n                    TypeVarId(-1),\n                    [],\n                    self.fx.o,\n                    AnyType(TypeOfAny.from_omitted_generics),\n                )\n            ],\n        )\n        assert_equal(str(c), \"def [X] (X?, Y?) -> Y?\")\n\n        v = [\n            TypeVarType(\n                \"Y\", \"Y\", TypeVarId(-1), [], self.fx.o, AnyType(TypeOfAny.from_omitted_generics)\n            ),\n            TypeVarType(\n                \"X\", \"X\", TypeVarId(-2), [], self.fx.o, AnyType(TypeOfAny.from_omitted_generics)\n            ),\n        ]\n        c2 = CallableType([], [], [], NoneType(), self.function, name=None, variables=v)\n        assert_equal(str(c2), \"def [Y, X] ()\")\n\n    def test_type_alias_expand_once(self) -> None:\n        A, target = self.fx.def_alias_1(self.fx.a)\n        assert get_proper_type(target) == target\n        assert get_proper_type(A) == target\n\n        A, target = self.fx.def_alias_2(self.fx.a)\n        assert get_proper_type(target) == target\n        assert get_proper_type(A) == target\n\n    def test_recursive_nested_in_non_recursive(self) -> None:\n        A, _ = self.fx.def_alias_1(self.fx.a)\n        T = TypeVarType(\n            \"T\", \"T\", TypeVarId(-1), [], self.fx.o, AnyType(TypeOfAny.from_omitted_generics)\n        )\n        NA = self.fx.non_rec_alias(Instance(self.fx.gi, [T]), [T], [A])\n        assert not NA.is_recursive\n        assert has_recursive_types(NA)\n\n    def test_indirection_no_infinite_recursion(self) -> None:\n        A, _ = self.fx.def_alias_1(self.fx.a)\n        visitor = TypeIndirectionVisitor()\n        A.accept(visitor)\n        modules = visitor.modules\n        assert modules == {\"__main__\", \"builtins\"}\n\n        A, _ = self.fx.def_alias_2(self.fx.a)\n        visitor = TypeIndirectionVisitor()\n        A.accept(visitor)\n        modules = visitor.modules\n        assert modules == {\"__main__\", \"builtins\"}\n\n\nclass TypeOpsSuite(Suite):\n    def setUp(self) -> None:\n        self.fx = TypeFixture(INVARIANT)\n        self.fx_co = TypeFixture(COVARIANT)\n        self.fx_contra = TypeFixture(CONTRAVARIANT)\n\n    # expand_type\n\n    def test_trivial_expand(self) -> None:\n        for t in (\n            self.fx.a,\n            self.fx.o,\n            self.fx.t,\n            self.fx.nonet,\n            self.tuple(self.fx.a),\n            self.callable([], self.fx.a, self.fx.a),\n            self.fx.anyt,\n        ):\n            self.assert_expand(t, [], t)\n            self.assert_expand(t, [], t)\n            self.assert_expand(t, [], t)\n\n    def test_trivial_expand_recursive(self) -> None:\n        A, _ = self.fx.def_alias_1(self.fx.a)\n        self.assert_expand(A, [], A)\n        A, _ = self.fx.def_alias_2(self.fx.a)\n        self.assert_expand(A, [], A)\n\n    def test_expand_naked_type_var(self) -> None:\n        self.assert_expand(self.fx.t, [(self.fx.t.id, self.fx.a)], self.fx.a)\n        self.assert_expand(self.fx.t, [(self.fx.s.id, self.fx.a)], self.fx.t)\n\n    def test_expand_basic_generic_types(self) -> None:\n        self.assert_expand(self.fx.gt, [(self.fx.t.id, self.fx.a)], self.fx.ga)\n\n    # IDEA: Add test cases for\n    #   tuple types\n    #   callable types\n    #   multiple arguments\n\n    def assert_expand(\n        self, orig: Type, map_items: list[tuple[TypeVarId, Type]], result: Type\n    ) -> None:\n        lower_bounds = {}\n\n        for id, t in map_items:\n            lower_bounds[id] = t\n\n        exp = mypy.expandtype.expand_type(orig, lower_bounds)\n        # Remove erased tags (asterisks).\n        assert_equal(str(exp).replace(\"*\", \"\"), str(result))\n\n    # erase_type\n\n    def test_trivial_erase(self) -> None:\n        for t in (self.fx.a, self.fx.o, self.fx.nonet, self.fx.anyt):\n            self.assert_erase(t, t)\n\n    def test_erase_with_type_variable(self) -> None:\n        self.assert_erase(self.fx.t, self.fx.anyt)\n\n    def test_erase_with_generic_type(self) -> None:\n        self.assert_erase(self.fx.ga, self.fx.gdyn)\n        self.assert_erase(self.fx.hab, Instance(self.fx.hi, [self.fx.anyt, self.fx.anyt]))\n\n    def test_erase_with_generic_type_recursive(self) -> None:\n        tuple_any = Instance(self.fx.std_tuplei, [AnyType(TypeOfAny.explicit)])\n        A, _ = self.fx.def_alias_1(self.fx.a)\n        self.assert_erase(A, tuple_any)\n        A, _ = self.fx.def_alias_2(self.fx.a)\n        self.assert_erase(A, UnionType([self.fx.a, tuple_any]))\n\n    def test_erase_with_tuple_type(self) -> None:\n        self.assert_erase(self.tuple(self.fx.a), self.fx.std_tuple)\n\n    def test_erase_with_function_type(self) -> None:\n        self.assert_erase(\n            self.fx.callable(self.fx.a, self.fx.b),\n            CallableType(\n                arg_types=[self.fx.anyt, self.fx.anyt],\n                arg_kinds=[ARG_STAR, ARG_STAR2],\n                arg_names=[None, None],\n                ret_type=self.fx.anyt,\n                fallback=self.fx.function,\n            ),\n        )\n\n    def test_erase_with_type_object(self) -> None:\n        self.assert_erase(\n            self.fx.callable_type(self.fx.a, self.fx.b),\n            CallableType(\n                arg_types=[self.fx.anyt, self.fx.anyt],\n                arg_kinds=[ARG_STAR, ARG_STAR2],\n                arg_names=[None, None],\n                ret_type=self.fx.anyt,\n                fallback=self.fx.type_type,\n            ),\n        )\n\n    def test_erase_with_type_type(self) -> None:\n        self.assert_erase(self.fx.type_a, self.fx.type_a)\n        self.assert_erase(self.fx.type_t, self.fx.type_any)\n\n    def assert_erase(self, orig: Type, result: Type) -> None:\n        assert_equal(str(erase_type(orig)), str(result))\n\n    # is_more_precise\n\n    def test_is_more_precise(self) -> None:\n        fx = self.fx\n        assert is_more_precise(fx.b, fx.a)\n        assert is_more_precise(fx.b, fx.b)\n        assert is_more_precise(fx.b, fx.b)\n        assert is_more_precise(fx.b, fx.anyt)\n        assert is_more_precise(self.tuple(fx.b, fx.a), self.tuple(fx.b, fx.a))\n        assert is_more_precise(self.tuple(fx.b, fx.b), self.tuple(fx.b, fx.a))\n\n        assert not is_more_precise(fx.a, fx.b)\n        assert not is_more_precise(fx.anyt, fx.b)\n\n    # is_proper_subtype\n\n    def test_is_proper_subtype(self) -> None:\n        fx = self.fx\n\n        assert is_proper_subtype(fx.a, fx.a)\n        assert is_proper_subtype(fx.b, fx.a)\n        assert is_proper_subtype(fx.b, fx.o)\n        assert is_proper_subtype(fx.b, fx.o)\n\n        assert not is_proper_subtype(fx.a, fx.b)\n        assert not is_proper_subtype(fx.o, fx.b)\n\n        assert is_proper_subtype(fx.anyt, fx.anyt)\n        assert not is_proper_subtype(fx.a, fx.anyt)\n        assert not is_proper_subtype(fx.anyt, fx.a)\n\n        assert is_proper_subtype(fx.ga, fx.ga)\n        assert is_proper_subtype(fx.gdyn, fx.gdyn)\n        assert not is_proper_subtype(fx.ga, fx.gdyn)\n        assert not is_proper_subtype(fx.gdyn, fx.ga)\n\n        assert is_proper_subtype(fx.t, fx.t)\n        assert not is_proper_subtype(fx.t, fx.s)\n\n        assert is_proper_subtype(fx.a, UnionType([fx.a, fx.b]))\n        assert is_proper_subtype(UnionType([fx.a, fx.b]), UnionType([fx.a, fx.b, fx.c]))\n        assert not is_proper_subtype(UnionType([fx.a, fx.b]), UnionType([fx.b, fx.c]))\n\n    def test_is_proper_subtype_covariance(self) -> None:\n        fx_co = self.fx_co\n\n        assert is_proper_subtype(fx_co.gsab, fx_co.gb)\n        assert is_proper_subtype(fx_co.gsab, fx_co.ga)\n        assert not is_proper_subtype(fx_co.gsaa, fx_co.gb)\n        assert is_proper_subtype(fx_co.gb, fx_co.ga)\n        assert not is_proper_subtype(fx_co.ga, fx_co.gb)\n\n    def test_is_proper_subtype_contravariance(self) -> None:\n        fx_contra = self.fx_contra\n\n        assert is_proper_subtype(fx_contra.gsab, fx_contra.gb)\n        assert not is_proper_subtype(fx_contra.gsab, fx_contra.ga)\n        assert is_proper_subtype(fx_contra.gsaa, fx_contra.gb)\n        assert not is_proper_subtype(fx_contra.gb, fx_contra.ga)\n        assert is_proper_subtype(fx_contra.ga, fx_contra.gb)\n\n    def test_is_proper_subtype_invariance(self) -> None:\n        fx = self.fx\n\n        assert is_proper_subtype(fx.gsab, fx.gb)\n        assert not is_proper_subtype(fx.gsab, fx.ga)\n        assert not is_proper_subtype(fx.gsaa, fx.gb)\n        assert not is_proper_subtype(fx.gb, fx.ga)\n        assert not is_proper_subtype(fx.ga, fx.gb)\n\n    def test_is_proper_subtype_and_subtype_literal_types(self) -> None:\n        fx = self.fx\n\n        lit1 = fx.lit1\n        lit2 = fx.lit2\n        lit3 = fx.lit3\n\n        assert is_proper_subtype(lit1, fx.a)\n        assert not is_proper_subtype(lit1, fx.d)\n        assert not is_proper_subtype(fx.a, lit1)\n        assert is_proper_subtype(fx.uninhabited, lit1)\n        assert not is_proper_subtype(lit1, fx.uninhabited)\n        assert is_proper_subtype(lit1, lit1)\n        assert not is_proper_subtype(lit1, lit2)\n        assert not is_proper_subtype(lit2, lit3)\n\n        assert is_subtype(lit1, fx.a)\n        assert not is_subtype(lit1, fx.d)\n        assert not is_subtype(fx.a, lit1)\n        assert is_subtype(fx.uninhabited, lit1)\n        assert not is_subtype(lit1, fx.uninhabited)\n        assert is_subtype(lit1, lit1)\n        assert not is_subtype(lit1, lit2)\n        assert not is_subtype(lit2, lit3)\n\n        assert not is_proper_subtype(lit1, fx.anyt)\n        assert not is_proper_subtype(fx.anyt, lit1)\n\n        assert is_subtype(lit1, fx.anyt)\n        assert is_subtype(fx.anyt, lit1)\n\n    def test_subtype_aliases(self) -> None:\n        A1, _ = self.fx.def_alias_1(self.fx.a)\n        AA1, _ = self.fx.def_alias_1(self.fx.a)\n        assert is_subtype(A1, AA1)\n        assert is_subtype(AA1, A1)\n\n        A2, _ = self.fx.def_alias_2(self.fx.a)\n        AA2, _ = self.fx.def_alias_2(self.fx.a)\n        assert is_subtype(A2, AA2)\n        assert is_subtype(AA2, A2)\n\n        B1, _ = self.fx.def_alias_1(self.fx.b)\n        B2, _ = self.fx.def_alias_2(self.fx.b)\n        assert is_subtype(B1, A1)\n        assert is_subtype(B2, A2)\n        assert not is_subtype(A1, B1)\n        assert not is_subtype(A2, B2)\n\n        assert not is_subtype(A2, A1)\n        assert is_subtype(A1, A2)\n\n    # can_be_true / can_be_false\n\n    def test_empty_tuple_always_false(self) -> None:\n        tuple_type = self.tuple()\n        assert tuple_type.can_be_false\n        assert not tuple_type.can_be_true\n\n    def test_nonempty_tuple_always_true(self) -> None:\n        tuple_type = self.tuple(AnyType(TypeOfAny.special_form), AnyType(TypeOfAny.special_form))\n        assert tuple_type.can_be_true\n        assert not tuple_type.can_be_false\n\n    def test_union_can_be_true_if_any_true(self) -> None:\n        union_type = UnionType([self.fx.a, self.tuple()])\n        assert union_type.can_be_true\n\n    def test_union_can_not_be_true_if_none_true(self) -> None:\n        union_type = UnionType([self.tuple(), self.tuple()])\n        assert not union_type.can_be_true\n\n    def test_union_can_be_false_if_any_false(self) -> None:\n        union_type = UnionType([self.fx.a, self.tuple()])\n        assert union_type.can_be_false\n\n    def test_union_can_not_be_false_if_none_false(self) -> None:\n        union_type = UnionType([self.tuple(self.fx.a), self.tuple(self.fx.d)])\n        assert not union_type.can_be_false\n\n    # true_only / false_only\n\n    def test_true_only_of_false_type_is_uninhabited(self) -> None:\n        to = true_only(NoneType())\n        assert_type(UninhabitedType, to)\n\n    def test_true_only_of_true_type_is_idempotent(self) -> None:\n        always_true = self.tuple(AnyType(TypeOfAny.special_form))\n        to = true_only(always_true)\n        assert always_true is to\n\n    def test_true_only_of_instance(self) -> None:\n        to = true_only(self.fx.a)\n        assert_equal(str(to), \"A\")\n        assert to.can_be_true\n        assert not to.can_be_false\n        assert_type(Instance, to)\n        # The original class still can be false\n        assert self.fx.a.can_be_false\n\n    def test_true_only_of_union(self) -> None:\n        tup_type = self.tuple(AnyType(TypeOfAny.special_form))\n        # Union of something that is unknown, something that is always true, something\n        # that is always false\n        union_type = UnionType([self.fx.a, tup_type, self.tuple()])\n        to = true_only(union_type)\n        assert isinstance(to, UnionType)\n        assert_equal(len(to.items), 2)\n        assert to.items[0].can_be_true\n        assert not to.items[0].can_be_false\n        assert to.items[1] is tup_type\n\n    def test_false_only_of_true_type_is_uninhabited(self) -> None:\n        with state.strict_optional_set(True):\n            fo = false_only(self.tuple(AnyType(TypeOfAny.special_form)))\n            assert_type(UninhabitedType, fo)\n\n    def test_false_only_tuple(self) -> None:\n        with state.strict_optional_set(False):\n            fo = false_only(self.tuple(self.fx.a))\n            assert_equal(fo, NoneType())\n        with state.strict_optional_set(True):\n            fo = false_only(self.tuple(self.fx.a))\n            assert_equal(fo, UninhabitedType())\n\n    def test_false_only_of_false_type_is_idempotent(self) -> None:\n        always_false = NoneType()\n        fo = false_only(always_false)\n        assert always_false is fo\n\n    def test_false_only_of_instance(self) -> None:\n        fo = false_only(self.fx.a)\n        assert_equal(str(fo), \"A\")\n        assert not fo.can_be_true\n        assert fo.can_be_false\n        assert_type(Instance, fo)\n        # The original class still can be true\n        assert self.fx.a.can_be_true\n\n    def test_false_only_of_union(self) -> None:\n        with state.strict_optional_set(True):\n            tup_type = self.tuple()\n            # Union of something that is unknown, something that is always true, something\n            # that is always false\n            union_type = UnionType(\n                [self.fx.a, self.tuple(AnyType(TypeOfAny.special_form)), tup_type]\n            )\n            assert_equal(len(union_type.items), 3)\n            fo = false_only(union_type)\n            assert isinstance(fo, UnionType)\n            assert_equal(len(fo.items), 2)\n            assert not fo.items[0].can_be_true\n            assert fo.items[0].can_be_false\n            assert fo.items[1] is tup_type\n\n    def test_simplified_union(self) -> None:\n        fx = self.fx\n\n        self.assert_simplified_union([fx.a, fx.a], fx.a)\n        self.assert_simplified_union([fx.a, fx.b], fx.a)\n        self.assert_simplified_union([fx.a, fx.d], UnionType([fx.a, fx.d]))\n        self.assert_simplified_union([fx.a, fx.uninhabited], fx.a)\n        self.assert_simplified_union([fx.ga, fx.gs2a], fx.ga)\n        self.assert_simplified_union([fx.ga, fx.gsab], UnionType([fx.ga, fx.gsab]))\n        self.assert_simplified_union([fx.ga, fx.gsba], fx.ga)\n        self.assert_simplified_union([fx.a, UnionType([fx.d])], UnionType([fx.a, fx.d]))\n        self.assert_simplified_union([fx.a, UnionType([fx.a])], fx.a)\n        self.assert_simplified_union(\n            [fx.b, UnionType([fx.c, UnionType([fx.d])])], UnionType([fx.b, fx.c, fx.d])\n        )\n\n    def test_simplified_union_with_literals(self) -> None:\n        fx = self.fx\n\n        self.assert_simplified_union([fx.lit1, fx.a], fx.a)\n        self.assert_simplified_union([fx.lit1, fx.lit2, fx.a], fx.a)\n        self.assert_simplified_union([fx.lit1, fx.lit1], fx.lit1)\n        self.assert_simplified_union([fx.lit1, fx.lit2], UnionType([fx.lit1, fx.lit2]))\n        self.assert_simplified_union([fx.lit1, fx.lit3], UnionType([fx.lit1, fx.lit3]))\n        self.assert_simplified_union([fx.lit1, fx.uninhabited], fx.lit1)\n        self.assert_simplified_union([fx.lit1_inst, fx.a], fx.a)\n        self.assert_simplified_union([fx.lit1_inst, fx.lit1_inst], fx.lit1_inst)\n        self.assert_simplified_union(\n            [fx.lit1_inst, fx.lit2_inst], UnionType([fx.lit1_inst, fx.lit2_inst])\n        )\n        self.assert_simplified_union(\n            [fx.lit1_inst, fx.lit3_inst], UnionType([fx.lit1_inst, fx.lit3_inst])\n        )\n        self.assert_simplified_union([fx.lit1_inst, fx.uninhabited], fx.lit1_inst)\n        self.assert_simplified_union([fx.lit1, fx.lit1_inst], fx.lit1)\n        self.assert_simplified_union([fx.lit1, fx.lit2_inst], UnionType([fx.lit1, fx.lit2_inst]))\n        self.assert_simplified_union([fx.lit1, fx.lit3_inst], UnionType([fx.lit1, fx.lit3_inst]))\n\n    def test_simplified_union_with_str_literals(self) -> None:\n        fx = self.fx\n\n        self.assert_simplified_union([fx.lit_str1, fx.lit_str2, fx.str_type], fx.str_type)\n        self.assert_simplified_union([fx.lit_str1, fx.lit_str1, fx.lit_str1], fx.lit_str1)\n        self.assert_simplified_union(\n            [fx.lit_str1, fx.lit_str2, fx.lit_str3],\n            UnionType([fx.lit_str1, fx.lit_str2, fx.lit_str3]),\n        )\n        self.assert_simplified_union(\n            [fx.lit_str1, fx.lit_str2, fx.uninhabited], UnionType([fx.lit_str1, fx.lit_str2])\n        )\n\n    def test_simplify_very_large_union(self) -> None:\n        fx = self.fx\n        literals = []\n        for i in range(5000):\n            literals.append(LiteralType(\"v%d\" % i, fx.str_type))\n        # This shouldn't be very slow, even if the union is big.\n        self.assert_simplified_union([*literals, fx.str_type], fx.str_type)\n\n    def test_simplified_union_with_str_instance_literals(self) -> None:\n        fx = self.fx\n\n        self.assert_simplified_union(\n            [fx.lit_str1_inst, fx.lit_str2_inst, fx.str_type], fx.str_type\n        )\n        self.assert_simplified_union(\n            [fx.lit_str1_inst, fx.lit_str1_inst, fx.lit_str1_inst], fx.lit_str1_inst\n        )\n        self.assert_simplified_union(\n            [fx.lit_str1_inst, fx.lit_str2_inst, fx.lit_str3_inst],\n            UnionType([fx.lit_str1_inst, fx.lit_str2_inst, fx.lit_str3_inst]),\n        )\n        self.assert_simplified_union(\n            [fx.lit_str1_inst, fx.lit_str2_inst, fx.uninhabited],\n            UnionType([fx.lit_str1_inst, fx.lit_str2_inst]),\n        )\n\n    def test_simplified_union_with_mixed_str_literals(self) -> None:\n        fx = self.fx\n\n        self.assert_simplified_union(\n            [fx.lit_str1, fx.lit_str2, fx.lit_str3_inst],\n            UnionType([fx.lit_str1, fx.lit_str2, fx.lit_str3_inst]),\n        )\n        self.assert_simplified_union([fx.lit_str1, fx.lit_str1, fx.lit_str1_inst], fx.lit_str1)\n\n    def assert_simplified_union(self, original: list[Type], union: Type) -> None:\n        assert_equal(make_simplified_union(original), union)\n        assert_equal(make_simplified_union(list(reversed(original))), union)\n\n    # Helpers\n\n    def tuple(self, *a: Type) -> TupleType:\n        return TupleType(list(a), self.fx.std_tuple)\n\n    def callable(self, vars: list[str], *a: Type) -> CallableType:\n        \"\"\"callable(args, a1, ..., an, r) constructs a callable with\n        argument types a1, ... an and return type r and type arguments\n        vars.\n        \"\"\"\n        tv: list[TypeVarType] = []\n        n = -1\n        for v in vars:\n            tv.append(\n                TypeVarType(\n                    v, v, TypeVarId(n), [], self.fx.o, AnyType(TypeOfAny.from_omitted_generics)\n                )\n            )\n            n -= 1\n        return CallableType(\n            list(a[:-1]),\n            [ARG_POS] * (len(a) - 1),\n            [None] * (len(a) - 1),\n            a[-1],\n            self.fx.function,\n            name=None,\n            variables=tv,\n        )\n\n\nclass JoinSuite(Suite):\n    def setUp(self) -> None:\n        self.fx = TypeFixture(INVARIANT)\n        self.fx_co = TypeFixture(COVARIANT)\n        self.fx_contra = TypeFixture(CONTRAVARIANT)\n\n    def test_trivial_cases(self) -> None:\n        for simple in self.fx.a, self.fx.o, self.fx.b:\n            self.assert_join(simple, simple, simple)\n\n    def test_class_subtyping(self) -> None:\n        self.assert_join(self.fx.a, self.fx.o, self.fx.o)\n        self.assert_join(self.fx.b, self.fx.o, self.fx.o)\n        self.assert_join(self.fx.a, self.fx.d, self.fx.o)\n        self.assert_join(self.fx.b, self.fx.c, self.fx.a)\n        self.assert_join(self.fx.b, self.fx.d, self.fx.o)\n\n    def test_tuples(self) -> None:\n        self.assert_join(self.tuple(), self.tuple(), self.tuple())\n        self.assert_join(self.tuple(self.fx.a), self.tuple(self.fx.a), self.tuple(self.fx.a))\n        self.assert_join(\n            self.tuple(self.fx.b, self.fx.c),\n            self.tuple(self.fx.a, self.fx.d),\n            self.tuple(self.fx.a, self.fx.o),\n        )\n\n        self.assert_join(\n            self.tuple(self.fx.a, self.fx.a), self.fx.std_tuple, self.var_tuple(self.fx.anyt)\n        )\n        self.assert_join(\n            self.tuple(self.fx.a), self.tuple(self.fx.a, self.fx.a), self.var_tuple(self.fx.a)\n        )\n        self.assert_join(\n            self.tuple(self.fx.b), self.tuple(self.fx.a, self.fx.c), self.var_tuple(self.fx.a)\n        )\n        self.assert_join(self.tuple(), self.tuple(self.fx.a), self.var_tuple(self.fx.a))\n\n    def test_var_tuples(self) -> None:\n        self.assert_join(\n            self.tuple(self.fx.a), self.var_tuple(self.fx.a), self.var_tuple(self.fx.a)\n        )\n        self.assert_join(\n            self.var_tuple(self.fx.a), self.tuple(self.fx.a), self.var_tuple(self.fx.a)\n        )\n        self.assert_join(self.var_tuple(self.fx.a), self.tuple(), self.var_tuple(self.fx.a))\n\n    def test_function_types(self) -> None:\n        self.assert_join(\n            self.callable(self.fx.a, self.fx.b),\n            self.callable(self.fx.a, self.fx.b),\n            self.callable(self.fx.a, self.fx.b),\n        )\n\n        self.assert_join(\n            self.callable(self.fx.a, self.fx.b),\n            self.callable(self.fx.b, self.fx.b),\n            self.callable(self.fx.b, self.fx.b),\n        )\n        self.assert_join(\n            self.callable(self.fx.a, self.fx.b),\n            self.callable(self.fx.a, self.fx.a),\n            self.callable(self.fx.a, self.fx.a),\n        )\n        self.assert_join(self.callable(self.fx.a, self.fx.b), self.fx.function, self.fx.function)\n        self.assert_join(\n            self.callable(self.fx.a, self.fx.b),\n            self.callable(self.fx.d, self.fx.b),\n            self.fx.function,\n        )\n\n    def test_type_vars(self) -> None:\n        self.assert_join(self.fx.t, self.fx.t, self.fx.t)\n        self.assert_join(self.fx.s, self.fx.s, self.fx.s)\n        self.assert_join(self.fx.t, self.fx.s, self.fx.o)\n\n    def test_none(self) -> None:\n        with state.strict_optional_set(False):\n            # Any type t joined with None results in t.\n            for t in [\n                NoneType(),\n                self.fx.a,\n                self.fx.o,\n                UnboundType(\"x\"),\n                self.fx.t,\n                self.tuple(),\n                self.callable(self.fx.a, self.fx.b),\n                self.fx.anyt,\n            ]:\n                self.assert_join(t, NoneType(), t)\n\n    def test_unbound_type(self) -> None:\n        self.assert_join(UnboundType(\"x\"), UnboundType(\"x\"), self.fx.anyt)\n        self.assert_join(UnboundType(\"x\"), UnboundType(\"y\"), self.fx.anyt)\n\n        # Any type t joined with an unbound type results in dynamic. Unbound\n        # type means that there is an error somewhere in the program, so this\n        # does not affect type safety (whatever the result).\n        for t in [\n            self.fx.a,\n            self.fx.o,\n            self.fx.ga,\n            self.fx.t,\n            self.tuple(),\n            self.callable(self.fx.a, self.fx.b),\n        ]:\n            self.assert_join(t, UnboundType(\"X\"), self.fx.anyt)\n\n    def test_any_type(self) -> None:\n        # Join against 'Any' type always results in 'Any'.\n        with state.strict_optional_set(False):\n            self.assert_join(NoneType(), self.fx.anyt, self.fx.anyt)\n\n        for t in [\n            self.fx.anyt,\n            self.fx.a,\n            self.fx.o,\n            NoneType(),\n            UnboundType(\"x\"),\n            self.fx.t,\n            self.tuple(),\n            self.callable(self.fx.a, self.fx.b),\n        ]:\n            self.assert_join(t, self.fx.anyt, self.fx.anyt)\n\n    def test_mixed_truth_restricted_type_simple(self) -> None:\n        # make_simplified_union against differently restricted truthiness types drops restrictions.\n        true_a = true_only(self.fx.a)\n        false_o = false_only(self.fx.o)\n        u = make_simplified_union([true_a, false_o])\n        assert u.can_be_true\n        assert u.can_be_false\n\n    def test_mixed_truth_restricted_type(self) -> None:\n        # join_types against differently restricted truthiness types drops restrictions.\n        true_any = true_only(AnyType(TypeOfAny.special_form))\n        false_o = false_only(self.fx.o)\n        j = join_types(true_any, false_o)\n        assert j.can_be_true\n        assert j.can_be_false\n\n    def test_other_mixed_types(self) -> None:\n        # In general, joining unrelated types produces object.\n        for t1 in [self.fx.a, self.fx.t, self.tuple(), self.callable(self.fx.a, self.fx.b)]:\n            for t2 in [self.fx.a, self.fx.t, self.tuple(), self.callable(self.fx.a, self.fx.b)]:\n                if str(t1) != str(t2):\n                    self.assert_join(t1, t2, self.fx.o)\n\n    def test_simple_generics(self) -> None:\n        with state.strict_optional_set(False):\n            self.assert_join(self.fx.ga, self.fx.nonet, self.fx.ga)\n        with state.strict_optional_set(True):\n            self.assert_join(self.fx.ga, self.fx.nonet, UnionType([self.fx.ga, NoneType()]))\n\n        self.assert_join(self.fx.ga, self.fx.anyt, self.fx.anyt)\n\n        for t in [\n            self.fx.a,\n            self.fx.o,\n            self.fx.t,\n            self.tuple(),\n            self.callable(self.fx.a, self.fx.b),\n        ]:\n            self.assert_join(t, self.fx.ga, self.fx.o)\n\n    def test_generics_invariant(self) -> None:\n        self.assert_join(self.fx.ga, self.fx.ga, self.fx.ga)\n        self.assert_join(self.fx.ga, self.fx.gb, self.fx.o)\n        self.assert_join(self.fx.ga, self.fx.gd, self.fx.o)\n        self.assert_join(self.fx.ga, self.fx.g2a, self.fx.o)\n\n    def test_generics_covariant(self) -> None:\n        self.assert_join(self.fx_co.ga, self.fx_co.ga, self.fx_co.ga)\n        self.assert_join(self.fx_co.ga, self.fx_co.gb, self.fx_co.ga)\n        self.assert_join(self.fx_co.ga, self.fx_co.gd, self.fx_co.go)\n        self.assert_join(self.fx_co.ga, self.fx_co.g2a, self.fx_co.o)\n\n    def test_generics_contravariant(self) -> None:\n        self.assert_join(self.fx_contra.ga, self.fx_contra.ga, self.fx_contra.ga)\n        # TODO: this can be more precise than \"object\", see a comment in mypy/join.py\n        self.assert_join(self.fx_contra.ga, self.fx_contra.gb, self.fx_contra.o)\n        self.assert_join(self.fx_contra.ga, self.fx_contra.g2a, self.fx_contra.o)\n\n    def test_generics_with_multiple_args(self) -> None:\n        self.assert_join(self.fx_co.hab, self.fx_co.hab, self.fx_co.hab)\n        self.assert_join(self.fx_co.hab, self.fx_co.hbb, self.fx_co.hab)\n        self.assert_join(self.fx_co.had, self.fx_co.haa, self.fx_co.hao)\n\n    def test_generics_with_inheritance(self) -> None:\n        self.assert_join(self.fx_co.gsab, self.fx_co.gb, self.fx_co.gb)\n        self.assert_join(self.fx_co.gsba, self.fx_co.gb, self.fx_co.ga)\n        self.assert_join(self.fx_co.gsab, self.fx_co.gd, self.fx_co.go)\n\n    def test_generics_with_inheritance_and_shared_supertype(self) -> None:\n        self.assert_join(self.fx_co.gsba, self.fx_co.gs2a, self.fx_co.ga)\n        self.assert_join(self.fx_co.gsab, self.fx_co.gs2a, self.fx_co.ga)\n        self.assert_join(self.fx_co.gsab, self.fx_co.gs2d, self.fx_co.go)\n\n    def test_generic_types_and_any(self) -> None:\n        self.assert_join(self.fx.gdyn, self.fx.ga, self.fx.gdyn)\n        self.assert_join(self.fx_co.gdyn, self.fx_co.ga, self.fx_co.gdyn)\n        self.assert_join(self.fx_contra.gdyn, self.fx_contra.ga, self.fx_contra.gdyn)\n\n    def test_callables_with_any(self) -> None:\n        self.assert_join(\n            self.callable(self.fx.a, self.fx.a, self.fx.anyt, self.fx.a),\n            self.callable(self.fx.a, self.fx.anyt, self.fx.a, self.fx.anyt),\n            self.callable(self.fx.a, self.fx.anyt, self.fx.anyt, self.fx.anyt),\n        )\n\n    def test_overloaded(self) -> None:\n        c = self.callable\n\n        def ov(*items: CallableType) -> Overloaded:\n            return Overloaded(list(items))\n\n        fx = self.fx\n        func = fx.function\n        c1 = c(fx.a, fx.a)\n        c2 = c(fx.b, fx.b)\n        c3 = c(fx.c, fx.c)\n        self.assert_join(ov(c1, c2), c1, c1)\n        self.assert_join(ov(c1, c2), c2, c2)\n        self.assert_join(ov(c1, c2), ov(c1, c2), ov(c1, c2))\n        self.assert_join(ov(c1, c2), ov(c1, c3), c1)\n        self.assert_join(ov(c2, c1), ov(c3, c1), c1)\n        self.assert_join(ov(c1, c2), c3, func)\n\n    def test_overloaded_with_any(self) -> None:\n        c = self.callable\n\n        def ov(*items: CallableType) -> Overloaded:\n            return Overloaded(list(items))\n\n        fx = self.fx\n        any = fx.anyt\n        self.assert_join(ov(c(fx.a, fx.a), c(fx.b, fx.b)), c(any, fx.b), c(any, fx.b))\n        self.assert_join(ov(c(fx.a, fx.a), c(any, fx.b)), c(fx.b, fx.b), c(any, fx.b))\n\n    def test_join_interface_types(self) -> None:\n        self.assert_join(self.fx.f, self.fx.f, self.fx.f)\n        self.assert_join(self.fx.f, self.fx.f2, self.fx.o)\n        self.assert_join(self.fx.f, self.fx.f3, self.fx.f)\n\n    def test_join_interface_and_class_types(self) -> None:\n        self.assert_join(self.fx.o, self.fx.f, self.fx.o)\n        self.assert_join(self.fx.a, self.fx.f, self.fx.o)\n\n        self.assert_join(self.fx.e, self.fx.f, self.fx.f)\n\n    @skip\n    def test_join_class_types_with_interface_result(self) -> None:\n        # Unique result\n        self.assert_join(self.fx.e, self.fx.e2, self.fx.f)\n\n        # Ambiguous result\n        self.assert_join(self.fx.e2, self.fx.e3, self.fx.anyt)\n\n    @skip\n    def test_generic_interfaces(self) -> None:\n        fx = InterfaceTypeFixture()\n\n        self.assert_join(fx.gfa, fx.gfa, fx.gfa)\n        self.assert_join(fx.gfa, fx.gfb, fx.o)\n\n        self.assert_join(fx.m1, fx.gfa, fx.gfa)\n\n        self.assert_join(fx.m1, fx.gfb, fx.o)\n\n    def test_simple_type_objects(self) -> None:\n        t1 = self.type_callable(self.fx.a, self.fx.a)\n        t2 = self.type_callable(self.fx.b, self.fx.b)\n        tr = self.type_callable(self.fx.b, self.fx.a)\n\n        self.assert_join(t1, t1, t1)\n        j = join_types(t1, t1)\n        assert isinstance(j, CallableType)\n        assert j.is_type_obj()\n\n        self.assert_join(t1, t2, tr)\n        self.assert_join(t1, self.fx.type_type, self.fx.type_type)\n        self.assert_join(self.fx.type_type, self.fx.type_type, self.fx.type_type)\n\n    def test_type_type(self) -> None:\n        self.assert_join(self.fx.type_a, self.fx.type_b, self.fx.type_a)\n        self.assert_join(self.fx.type_b, self.fx.type_any, self.fx.type_any)\n        self.assert_join(self.fx.type_b, self.fx.type_type, self.fx.type_type)\n        self.assert_join(self.fx.type_b, self.fx.type_c, self.fx.type_a)\n        self.assert_join(self.fx.type_c, self.fx.type_d, TypeType.make_normalized(self.fx.o))\n        self.assert_join(self.fx.type_type, self.fx.type_any, self.fx.type_type)\n        self.assert_join(self.fx.type_b, self.fx.anyt, self.fx.anyt)\n\n    def test_literal_type(self) -> None:\n        a = self.fx.a\n        d = self.fx.d\n        lit1 = self.fx.lit1\n        lit2 = self.fx.lit2\n        lit3 = self.fx.lit3\n\n        self.assert_join(lit1, lit1, lit1)\n        self.assert_join(lit1, a, a)\n        self.assert_join(lit1, d, self.fx.o)\n        self.assert_join(lit1, lit2, a)\n        self.assert_join(lit1, lit3, self.fx.o)\n        self.assert_join(lit1, self.fx.anyt, self.fx.anyt)\n        self.assert_join(UnionType([lit1, lit2]), lit2, UnionType([lit1, lit2]))\n        self.assert_join(UnionType([lit1, lit2]), a, a)\n        self.assert_join(UnionType([lit1, lit3]), a, UnionType([a, lit3]))\n        self.assert_join(UnionType([d, lit3]), lit3, d)\n        self.assert_join(UnionType([d, lit3]), d, UnionType([d, lit3]))\n        self.assert_join(UnionType([a, lit1]), lit1, a)\n        self.assert_join(UnionType([a, lit1]), lit2, a)\n        self.assert_join(UnionType([lit1, lit2]), UnionType([lit1, lit2]), UnionType([lit1, lit2]))\n\n        # The order in which we try joining two unions influences the\n        # ordering of the items in the final produced unions. So, we\n        # manually call 'assert_simple_join' and tune the output\n        # after swapping the arguments here.\n        self.assert_simple_join(\n            UnionType([lit1, lit2]), UnionType([lit2, lit3]), UnionType([lit1, lit2, lit3])\n        )\n        self.assert_simple_join(\n            UnionType([lit2, lit3]), UnionType([lit1, lit2]), UnionType([lit2, lit3, lit1])\n        )\n\n    def test_variadic_tuple_joins(self) -> None:\n        # These tests really test just the \"arity\", to be sure it is handled correctly.\n        self.assert_join(\n            self.tuple(self.fx.a, self.fx.a),\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n            Instance(self.fx.std_tuplei, [self.fx.a]),\n        )\n        self.assert_join(\n            self.tuple(self.fx.a, self.fx.a),\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a),\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a),\n        )\n        self.assert_join(\n            self.tuple(self.fx.a, self.fx.a),\n            self.tuple(self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n            self.tuple(self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n        )\n        self.assert_join(\n            self.tuple(\n                self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a\n            ),\n            self.tuple(\n                self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a\n            ),\n            self.tuple(\n                self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a\n            ),\n        )\n        self.assert_join(\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n            self.tuple(\n                self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a\n            ),\n            Instance(self.fx.std_tuplei, [self.fx.a]),\n        )\n        self.assert_join(\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n            Instance(self.fx.std_tuplei, [self.fx.a]),\n        )\n        self.assert_join(\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a),\n            self.tuple(\n                self.fx.b, UnpackType(Instance(self.fx.std_tuplei, [self.fx.b])), self.fx.b\n            ),\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a),\n        )\n\n    def test_join_type_type_type_var(self) -> None:\n        self.assert_join(self.fx.type_a, self.fx.t, self.fx.o)\n        self.assert_join(self.fx.t, self.fx.type_a, self.fx.o)\n\n    def test_join_type_var_bounds(self) -> None:\n        tvar1 = TypeVarType(\n            \"tvar1\",\n            \"tvar1\",\n            TypeVarId(-100),\n            [],\n            self.fx.o,\n            AnyType(TypeOfAny.from_omitted_generics),\n            INVARIANT,\n        )\n        any_type = AnyType(TypeOfAny.special_form)\n        tvar2 = TypeVarType(\n            \"tvar2\",\n            \"tvar2\",\n            TypeVarId(-101),\n            [],\n            upper_bound=UnionType(\n                [\n                    TupleType([any_type], self.fx.std_tuple),\n                    TupleType([any_type, any_type], self.fx.std_tuple),\n                ]\n            ),\n            default=AnyType(TypeOfAny.from_omitted_generics),\n            variance=INVARIANT,\n        )\n\n        self.assert_join(tvar1, tvar2, self.fx.o)\n        self.assert_join(tvar2, tvar1, self.fx.o)\n\n    # There are additional test cases in check-inference.test.\n\n    # TODO: Function types + varargs and default args.\n\n    def assert_join(self, s: Type, t: Type, join: Type) -> None:\n        self.assert_simple_join(s, t, join)\n        self.assert_simple_join(t, s, join)\n\n    def assert_simple_join(self, s: Type, t: Type, join: Type) -> None:\n        result = join_types(s, t)\n        actual = str(result)\n        expected = str(join)\n        assert_equal(actual, expected, f\"join({s}, {t}) == {{}} ({{}} expected)\")\n        assert is_subtype(s, result), f\"{s} not subtype of {result}\"\n        assert is_subtype(t, result), f\"{t} not subtype of {result}\"\n\n    def tuple(self, *a: Type) -> TupleType:\n        return TupleType(list(a), self.fx.std_tuple)\n\n    def var_tuple(self, t: Type) -> Instance:\n        \"\"\"Construct a variable-length tuple type\"\"\"\n        return Instance(self.fx.std_tuplei, [t])\n\n    def callable(self, *a: Type) -> CallableType:\n        \"\"\"callable(a1, ..., an, r) constructs a callable with argument types\n        a1, ... an and return type r.\n        \"\"\"\n        n = len(a) - 1\n        return CallableType(list(a[:-1]), [ARG_POS] * n, [None] * n, a[-1], self.fx.function)\n\n    def type_callable(self, *a: Type) -> CallableType:\n        \"\"\"type_callable(a1, ..., an, r) constructs a callable with\n        argument types a1, ... an and return type r, and which\n        represents a type.\n        \"\"\"\n        n = len(a) - 1\n        return CallableType(list(a[:-1]), [ARG_POS] * n, [None] * n, a[-1], self.fx.type_type)\n\n\nclass MeetSuite(Suite):\n    def setUp(self) -> None:\n        self.fx = TypeFixture()\n\n    def test_trivial_cases(self) -> None:\n        for simple in self.fx.a, self.fx.o, self.fx.b:\n            self.assert_meet(simple, simple, simple)\n\n    def test_class_subtyping(self) -> None:\n        self.assert_meet(self.fx.a, self.fx.o, self.fx.a)\n        self.assert_meet(self.fx.a, self.fx.b, self.fx.b)\n        self.assert_meet(self.fx.b, self.fx.o, self.fx.b)\n        self.assert_meet(self.fx.a, self.fx.d, UninhabitedType())\n        self.assert_meet(self.fx.b, self.fx.c, UninhabitedType())\n\n    def test_tuples(self) -> None:\n        self.assert_meet(self.tuple(), self.tuple(), self.tuple())\n        self.assert_meet(self.tuple(self.fx.a), self.tuple(self.fx.a), self.tuple(self.fx.a))\n        self.assert_meet(\n            self.tuple(self.fx.b, self.fx.c),\n            self.tuple(self.fx.a, self.fx.d),\n            self.tuple(self.fx.b, UninhabitedType()),\n        )\n\n        self.assert_meet(\n            self.tuple(self.fx.a, self.fx.a), self.fx.std_tuple, self.tuple(self.fx.a, self.fx.a)\n        )\n        self.assert_meet(\n            self.tuple(self.fx.a), self.tuple(self.fx.a, self.fx.a), UninhabitedType()\n        )\n\n    def test_function_types(self) -> None:\n        self.assert_meet(\n            self.callable(self.fx.a, self.fx.b),\n            self.callable(self.fx.a, self.fx.b),\n            self.callable(self.fx.a, self.fx.b),\n        )\n\n        self.assert_meet(\n            self.callable(self.fx.a, self.fx.b),\n            self.callable(self.fx.b, self.fx.b),\n            self.callable(self.fx.a, self.fx.b),\n        )\n        self.assert_meet(\n            self.callable(self.fx.a, self.fx.b),\n            self.callable(self.fx.a, self.fx.a),\n            self.callable(self.fx.a, self.fx.b),\n        )\n\n    def test_type_vars(self) -> None:\n        self.assert_meet(self.fx.t, self.fx.t, self.fx.t)\n        self.assert_meet(self.fx.s, self.fx.s, self.fx.s)\n        self.assert_meet(self.fx.t, self.fx.s, UninhabitedType())\n\n    def test_none(self) -> None:\n        self.assert_meet(NoneType(), NoneType(), NoneType())\n\n        self.assert_meet(NoneType(), self.fx.anyt, NoneType())\n\n        # Any type t joined with None results in None, unless t is Any.\n        with state.strict_optional_set(False):\n            for t in [\n                self.fx.a,\n                self.fx.o,\n                UnboundType(\"x\"),\n                self.fx.t,\n                self.tuple(),\n                self.callable(self.fx.a, self.fx.b),\n            ]:\n                self.assert_meet(t, NoneType(), NoneType())\n\n        with state.strict_optional_set(True):\n            self.assert_meet(self.fx.o, NoneType(), NoneType())\n            for t in [\n                self.fx.a,\n                UnboundType(\"x\"),\n                self.fx.t,\n                self.tuple(),\n                self.callable(self.fx.a, self.fx.b),\n            ]:\n                self.assert_meet(t, NoneType(), UninhabitedType())\n\n    def test_unbound_type(self) -> None:\n        self.assert_meet(UnboundType(\"x\"), UnboundType(\"x\"), self.fx.anyt)\n        self.assert_meet(UnboundType(\"x\"), UnboundType(\"y\"), self.fx.anyt)\n\n        self.assert_meet(UnboundType(\"x\"), self.fx.anyt, UnboundType(\"x\"))\n\n        # The meet of any type t with an unbound type results in dynamic.\n        # Unbound type means that there is an error somewhere in the program,\n        # so this does not affect type safety.\n        for t in [\n            self.fx.a,\n            self.fx.o,\n            self.fx.t,\n            self.tuple(),\n            self.callable(self.fx.a, self.fx.b),\n        ]:\n            self.assert_meet(t, UnboundType(\"X\"), self.fx.anyt)\n\n    def test_dynamic_type(self) -> None:\n        # Meet against dynamic type always results in dynamic.\n        for t in [\n            self.fx.anyt,\n            self.fx.a,\n            self.fx.o,\n            NoneType(),\n            UnboundType(\"x\"),\n            self.fx.t,\n            self.tuple(),\n            self.callable(self.fx.a, self.fx.b),\n        ]:\n            self.assert_meet(t, self.fx.anyt, t)\n\n    def test_simple_generics(self) -> None:\n        self.assert_meet(self.fx.ga, self.fx.ga, self.fx.ga)\n        self.assert_meet(self.fx.ga, self.fx.o, self.fx.ga)\n        self.assert_meet(self.fx.ga, self.fx.gb, self.fx.gb)\n        self.assert_meet(self.fx.ga, self.fx.gd, UninhabitedType())\n        self.assert_meet(self.fx.ga, self.fx.g2a, UninhabitedType())\n\n        self.assert_meet(self.fx.ga, self.fx.nonet, UninhabitedType())\n        self.assert_meet(self.fx.ga, self.fx.anyt, self.fx.ga)\n\n        for t in [self.fx.a, self.fx.t, self.tuple(), self.callable(self.fx.a, self.fx.b)]:\n            self.assert_meet(t, self.fx.ga, UninhabitedType())\n\n    def test_generics_with_multiple_args(self) -> None:\n        self.assert_meet(self.fx.hab, self.fx.hab, self.fx.hab)\n        self.assert_meet(self.fx.hab, self.fx.haa, self.fx.hab)\n        self.assert_meet(self.fx.hab, self.fx.had, UninhabitedType())\n        self.assert_meet(self.fx.hab, self.fx.hbb, self.fx.hbb)\n\n    def test_generics_with_inheritance(self) -> None:\n        self.assert_meet(self.fx.gsab, self.fx.gb, self.fx.gsab)\n        self.assert_meet(self.fx.gsba, self.fx.gb, UninhabitedType())\n\n    def test_generics_with_inheritance_and_shared_supertype(self) -> None:\n        self.assert_meet(self.fx.gsba, self.fx.gs2a, UninhabitedType())\n        self.assert_meet(self.fx.gsab, self.fx.gs2a, UninhabitedType())\n\n    def test_generic_types_and_dynamic(self) -> None:\n        self.assert_meet(self.fx.gdyn, self.fx.ga, self.fx.ga)\n\n    def test_callables_with_dynamic(self) -> None:\n        self.assert_meet(\n            self.callable(self.fx.a, self.fx.a, self.fx.anyt, self.fx.a),\n            self.callable(self.fx.a, self.fx.anyt, self.fx.a, self.fx.anyt),\n            self.callable(self.fx.a, self.fx.anyt, self.fx.anyt, self.fx.anyt),\n        )\n\n    def test_meet_interface_types(self) -> None:\n        self.assert_meet(self.fx.f, self.fx.f, self.fx.f)\n        self.assert_meet(self.fx.f, self.fx.f2, UninhabitedType())\n        self.assert_meet(self.fx.f, self.fx.f3, self.fx.f3)\n\n    def test_meet_interface_and_class_types(self) -> None:\n        self.assert_meet(self.fx.o, self.fx.f, self.fx.f)\n        self.assert_meet(self.fx.a, self.fx.f, UninhabitedType())\n\n        self.assert_meet(self.fx.e, self.fx.f, self.fx.e)\n\n    def test_meet_class_types_with_shared_interfaces(self) -> None:\n        # These have nothing special with respect to meets, unlike joins. These\n        # are for completeness only.\n        self.assert_meet(self.fx.e, self.fx.e2, UninhabitedType())\n        self.assert_meet(self.fx.e2, self.fx.e3, UninhabitedType())\n\n    def test_meet_with_generic_interfaces(self) -> None:\n        fx = InterfaceTypeFixture()\n        self.assert_meet(fx.gfa, fx.m1, fx.m1)\n        self.assert_meet(fx.gfa, fx.gfa, fx.gfa)\n        self.assert_meet(fx.gfb, fx.m1, UninhabitedType())\n\n    def test_type_type(self) -> None:\n        self.assert_meet(self.fx.type_a, self.fx.type_b, self.fx.type_b)\n        self.assert_meet(self.fx.type_b, self.fx.type_any, self.fx.type_b)\n        self.assert_meet(self.fx.type_b, self.fx.type_type, self.fx.type_b)\n        self.assert_meet(self.fx.type_b, self.fx.type_c, self.fx.type_never)\n        self.assert_meet(self.fx.type_c, self.fx.type_d, self.fx.type_never)\n        self.assert_meet(self.fx.type_type, self.fx.type_any, self.fx.type_any)\n        self.assert_meet(self.fx.type_b, self.fx.anyt, self.fx.type_b)\n\n    def test_literal_type(self) -> None:\n        a = self.fx.a\n        lit1 = self.fx.lit1\n        lit2 = self.fx.lit2\n        lit3 = self.fx.lit3\n\n        self.assert_meet(lit1, lit1, lit1)\n        self.assert_meet(lit1, a, lit1)\n        self.assert_meet_uninhabited(lit1, lit3)\n        self.assert_meet_uninhabited(lit1, lit2)\n        self.assert_meet(UnionType([lit1, lit2]), lit1, lit1)\n        self.assert_meet(UnionType([lit1, lit2]), UnionType([lit2, lit3]), lit2)\n        self.assert_meet(UnionType([lit1, lit2]), UnionType([lit1, lit2]), UnionType([lit1, lit2]))\n        self.assert_meet(lit1, self.fx.anyt, lit1)\n        self.assert_meet(lit1, self.fx.o, lit1)\n\n        assert is_same_type(lit1, narrow_declared_type(lit1, a))\n        assert is_same_type(lit2, narrow_declared_type(lit2, a))\n\n    # FIX generic interfaces + ranges\n\n    def assert_meet_uninhabited(self, s: Type, t: Type) -> None:\n        with state.strict_optional_set(False):\n            self.assert_meet(s, t, self.fx.nonet)\n        with state.strict_optional_set(True):\n            self.assert_meet(s, t, self.fx.uninhabited)\n\n    def test_variadic_tuple_meets(self) -> None:\n        # These tests really test just the \"arity\", to be sure it is handled correctly.\n        self.assert_meet(\n            self.tuple(self.fx.a, self.fx.a),\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n            self.tuple(self.fx.a, self.fx.a),\n        )\n        self.assert_meet(\n            self.tuple(self.fx.a, self.fx.a),\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a),\n            self.tuple(self.fx.a, self.fx.a),\n        )\n        self.assert_meet(\n            self.tuple(self.fx.a, self.fx.a),\n            self.tuple(self.fx.a, UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n            self.tuple(self.fx.a, self.fx.a),\n        )\n        self.assert_meet(\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a]))),\n        )\n        self.assert_meet(\n            self.tuple(UnpackType(Instance(self.fx.std_tuplei, [self.fx.a])), self.fx.a),\n            self.tuple(self.fx.b, UnpackType(Instance(self.fx.std_tuplei, [self.fx.b]))),\n            self.tuple(self.fx.b, UnpackType(Instance(self.fx.std_tuplei, [self.fx.b]))),\n        )\n\n    def assert_meet(self, s: Type, t: Type, meet: Type) -> None:\n        self.assert_simple_meet(s, t, meet)\n        self.assert_simple_meet(t, s, meet)\n\n    def assert_simple_meet(self, s: Type, t: Type, meet: Type) -> None:\n        result = meet_types(s, t)\n        actual = str(result)\n        expected = str(meet)\n        assert_equal(actual, expected, f\"meet({s}, {t}) == {{}} ({{}} expected)\")\n        assert is_subtype(result, s), f\"{result} not subtype of {s}\"\n        assert is_subtype(result, t), f\"{result} not subtype of {t}\"\n\n    def tuple(self, *a: Type) -> TupleType:\n        return TupleType(list(a), self.fx.std_tuple)\n\n    def callable(self, *a: Type) -> CallableType:\n        \"\"\"callable(a1, ..., an, r) constructs a callable with argument types\n        a1, ... an and return type r.\n        \"\"\"\n        n = len(a) - 1\n        return CallableType(list(a[:-1]), [ARG_POS] * n, [None] * n, a[-1], self.fx.function)\n\n\nclass SameTypeSuite(Suite):\n    def setUp(self) -> None:\n        self.fx = TypeFixture()\n\n    def test_literal_type(self) -> None:\n        a = self.fx.a\n        b = self.fx.b  # Reminder: b is a subclass of a\n\n        lit1 = self.fx.lit1\n        lit2 = self.fx.lit2\n        lit3 = self.fx.lit3\n\n        self.assert_same(lit1, lit1)\n        self.assert_same(UnionType([lit1, lit2]), UnionType([lit1, lit2]))\n        self.assert_same(UnionType([lit1, lit2]), UnionType([lit2, lit1]))\n        self.assert_same(UnionType([a, b]), UnionType([b, a]))\n        self.assert_not_same(lit1, b)\n        self.assert_not_same(lit1, lit2)\n        self.assert_not_same(lit1, lit3)\n\n        self.assert_not_same(lit1, self.fx.anyt)\n        self.assert_not_same(lit1, self.fx.nonet)\n\n    def assert_same(self, s: Type, t: Type, strict: bool = True) -> None:\n        self.assert_simple_is_same(s, t, expected=True, strict=strict)\n        self.assert_simple_is_same(t, s, expected=True, strict=strict)\n\n    def assert_not_same(self, s: Type, t: Type, strict: bool = True) -> None:\n        self.assert_simple_is_same(s, t, False, strict=strict)\n        self.assert_simple_is_same(t, s, False, strict=strict)\n\n    def assert_simple_is_same(self, s: Type, t: Type, expected: bool, strict: bool) -> None:\n        actual = is_same_type(s, t)\n        assert_equal(actual, expected, f\"is_same_type({s}, {t}) is {{}} ({{}} expected)\")\n\n        if strict:\n            actual2 = s == t\n            assert_equal(actual2, expected, f\"({s} == {t}) is {{}} ({{}} expected)\")\n            assert_equal(\n                hash(s) == hash(t), expected, f\"(hash({s}) == hash({t}) is {{}} ({{}} expected)\"\n            )\n\n\nclass RemoveLastKnownValueSuite(Suite):\n    def setUp(self) -> None:\n        self.fx = TypeFixture()\n\n    def test_optional(self) -> None:\n        t = UnionType.make_union([self.fx.a, self.fx.nonet])\n        self.assert_union_result(t, [self.fx.a, self.fx.nonet])\n\n    def test_two_instances(self) -> None:\n        t = UnionType.make_union([self.fx.a, self.fx.b])\n        self.assert_union_result(t, [self.fx.a, self.fx.b])\n\n    def test_multiple_same_instances(self) -> None:\n        t = UnionType.make_union([self.fx.a, self.fx.a])\n        assert remove_instance_last_known_values(t) == self.fx.a\n        t = UnionType.make_union([self.fx.a, self.fx.a, self.fx.b])\n        self.assert_union_result(t, [self.fx.a, self.fx.b])\n        t = UnionType.make_union([self.fx.a, self.fx.nonet, self.fx.a, self.fx.b])\n        self.assert_union_result(t, [self.fx.a, self.fx.nonet, self.fx.b])\n\n    def test_single_last_known_value(self) -> None:\n        t = UnionType.make_union([self.fx.lit1_inst, self.fx.nonet])\n        self.assert_union_result(t, [self.fx.a, self.fx.nonet])\n\n    def test_last_known_values_with_merge(self) -> None:\n        t = UnionType.make_union([self.fx.lit1_inst, self.fx.lit2_inst, self.fx.lit4_inst])\n        assert remove_instance_last_known_values(t) == self.fx.a\n        t = UnionType.make_union(\n            [self.fx.lit1_inst, self.fx.b, self.fx.lit2_inst, self.fx.lit4_inst]\n        )\n        self.assert_union_result(t, [self.fx.a, self.fx.b])\n\n    def test_generics(self) -> None:\n        t = UnionType.make_union([self.fx.ga, self.fx.gb])\n        self.assert_union_result(t, [self.fx.ga, self.fx.gb])\n\n    def assert_union_result(self, t: ProperType, expected: list[Type]) -> None:\n        t2 = remove_instance_last_known_values(t)\n        assert type(t2) is UnionType\n        assert t2.items == expected\n\n\nclass ShallowOverloadMatchingSuite(Suite):\n    def setUp(self) -> None:\n        self.fx = TypeFixture()\n\n    def test_simple(self) -> None:\n        fx = self.fx\n        ov = self.make_overload([[(\"x\", fx.anyt, ARG_NAMED)], [(\"y\", fx.anyt, ARG_NAMED)]])\n        # Match first only\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"foo\", \"x\")), 0)\n        # Match second only\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"foo\", \"y\")), 1)\n        # No match -- invalid keyword arg name\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"foo\", \"z\")), 1)\n        # No match -- missing arg\n        self.assert_find_shallow_matching_overload_item(ov, make_call(), 1)\n        # No match -- extra arg\n        self.assert_find_shallow_matching_overload_item(\n            ov, make_call((\"foo\", \"x\"), (\"foo\", \"z\")), 1\n        )\n\n    def test_match_using_types(self) -> None:\n        fx = self.fx\n        ov = self.make_overload(\n            [\n                [(\"x\", fx.nonet, ARG_POS)],\n                [(\"x\", fx.lit_false, ARG_POS)],\n                [(\"x\", fx.lit_true, ARG_POS)],\n                [(\"x\", fx.anyt, ARG_POS)],\n            ]\n        )\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"None\", None)), 0)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"builtins.False\", None)), 1)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"builtins.True\", None)), 2)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"foo\", None)), 3)\n\n    def test_none_special_cases(self) -> None:\n        fx = self.fx\n        ov = self.make_overload(\n            [[(\"x\", fx.callable(fx.nonet), ARG_POS)], [(\"x\", fx.nonet, ARG_POS)]]\n        )\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"None\", None)), 1)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"func\", None)), 0)\n        ov = self.make_overload([[(\"x\", fx.str_type, ARG_POS)], [(\"x\", fx.nonet, ARG_POS)]])\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"None\", None)), 1)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"func\", None)), 0)\n        ov = self.make_overload(\n            [[(\"x\", UnionType([fx.str_type, fx.a]), ARG_POS)], [(\"x\", fx.nonet, ARG_POS)]]\n        )\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"None\", None)), 1)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"func\", None)), 0)\n        ov = self.make_overload([[(\"x\", fx.o, ARG_POS)], [(\"x\", fx.nonet, ARG_POS)]])\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"None\", None)), 0)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"func\", None)), 0)\n        ov = self.make_overload(\n            [[(\"x\", UnionType([fx.str_type, fx.nonet]), ARG_POS)], [(\"x\", fx.nonet, ARG_POS)]]\n        )\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"None\", None)), 0)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"func\", None)), 0)\n        ov = self.make_overload([[(\"x\", fx.anyt, ARG_POS)], [(\"x\", fx.nonet, ARG_POS)]])\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"None\", None)), 0)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"func\", None)), 0)\n\n    def test_optional_arg(self) -> None:\n        fx = self.fx\n        ov = self.make_overload(\n            [[(\"x\", fx.anyt, ARG_NAMED)], [(\"y\", fx.anyt, ARG_OPT)], [(\"z\", fx.anyt, ARG_NAMED)]]\n        )\n        self.assert_find_shallow_matching_overload_item(ov, make_call(), 1)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"foo\", \"x\")), 0)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"foo\", \"y\")), 1)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"foo\", \"z\")), 2)\n\n    def test_two_args(self) -> None:\n        fx = self.fx\n        ov = self.make_overload(\n            [\n                [(\"x\", fx.nonet, ARG_OPT), (\"y\", fx.anyt, ARG_OPT)],\n                [(\"x\", fx.anyt, ARG_OPT), (\"y\", fx.anyt, ARG_OPT)],\n            ]\n        )\n        self.assert_find_shallow_matching_overload_item(ov, make_call(), 0)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"None\", \"x\")), 0)\n        self.assert_find_shallow_matching_overload_item(ov, make_call((\"foo\", \"x\")), 1)\n        self.assert_find_shallow_matching_overload_item(\n            ov, make_call((\"foo\", \"y\"), (\"None\", \"x\")), 0\n        )\n        self.assert_find_shallow_matching_overload_item(\n            ov, make_call((\"foo\", \"y\"), (\"bar\", \"x\")), 1\n        )\n\n    def assert_find_shallow_matching_overload_item(\n        self, ov: Overloaded, call: CallExpr, expected_index: int\n    ) -> None:\n        c = find_shallow_matching_overload_item(ov, call)\n        assert c in ov.items\n        assert ov.items.index(c) == expected_index\n\n    def make_overload(self, items: list[list[tuple[str, Type, ArgKind]]]) -> Overloaded:\n        result = []\n        for item in items:\n            arg_types = []\n            arg_names = []\n            arg_kinds = []\n            for name, typ, kind in item:\n                arg_names.append(name)\n                arg_types.append(typ)\n                arg_kinds.append(kind)\n            result.append(\n                CallableType(\n                    arg_types, arg_kinds, arg_names, ret_type=NoneType(), fallback=self.fx.o\n                )\n            )\n        return Overloaded(result)\n\n\ndef make_call(*items: tuple[str, str | None]) -> CallExpr:\n    args: list[Expression] = []\n    arg_names = []\n    arg_kinds = []\n    for arg, name in items:\n        shortname = arg.split(\".\")[-1]\n        n = NameExpr(shortname)\n        n.fullname = arg\n        args.append(n)\n        arg_names.append(name)\n        if name:\n            arg_kinds.append(ARG_NAMED)\n        else:\n            arg_kinds.append(ARG_POS)\n    return CallExpr(NameExpr(\"f\"), args, arg_kinds, arg_names)\n\n\nclass TestExpandTypeLimitGetProperType(TestCase):\n    # WARNING: do not increase this number unless absolutely necessary,\n    # and you understand what you are doing.\n    ALLOWED_GET_PROPER_TYPES = 7\n\n    @skipUnless(mypy.expandtype.__file__.endswith(\".py\"), \"Skip for compiled mypy\")\n    def test_count_get_proper_type(self) -> None:\n        with open(mypy.expandtype.__file__) as f:\n            code = f.read()\n        get_proper_type_count = len(re.findall(r\"get_proper_type\\(\", code))\n        get_proper_type_count -= len(re.findall(r\"get_proper_type\\(\\)\", code))\n        assert get_proper_type_count == self.ALLOWED_GET_PROPER_TYPES\n"
  },
  {
    "path": "mypy/test/testutil.py",
    "content": "from __future__ import annotations\n\nimport os\nfrom unittest import TestCase, mock\n\nfrom mypy.inspections import parse_location\nfrom mypy.util import _generate_junit_contents, get_terminal_width\n\n\nclass TestGetTerminalSize(TestCase):\n    def test_get_terminal_size_in_pty_defaults_to_80(self) -> None:\n        # when run using a pty, `os.get_terminal_size()` returns `0, 0`\n        ret = os.terminal_size((0, 0))\n        mock_environ = os.environ.copy()\n        mock_environ.pop(\"COLUMNS\", None)\n        with mock.patch.object(os, \"get_terminal_size\", return_value=ret):\n            with mock.patch.dict(os.environ, values=mock_environ, clear=True):\n                assert get_terminal_width() == 80\n\n    def test_parse_location_windows(self) -> None:\n        assert parse_location(r\"C:\\test.py:1:1\") == (r\"C:\\test.py\", [1, 1])\n        assert parse_location(r\"C:\\test.py:1:1:1:1\") == (r\"C:\\test.py\", [1, 1, 1, 1])\n\n\nclass TestWriteJunitXml(TestCase):\n    def test_junit_pass(self) -> None:\n        serious = False\n        messages_by_file: dict[str | None, list[str]] = {}\n        expected = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<testsuite errors=\"0\" failures=\"0\" name=\"mypy\" skips=\"0\" tests=\"1\" time=\"1.230\">\n  <testcase classname=\"mypy\" file=\"mypy\" line=\"1\" name=\"mypy-py3.14-test-plat\" time=\"1.230\">\n  </testcase>\n</testsuite>\n\"\"\"\n        result = _generate_junit_contents(\n            dt=1.23,\n            serious=serious,\n            messages_by_file=messages_by_file,\n            version=\"3.14\",\n            platform=\"test-plat\",\n        )\n        assert result == expected\n\n    def test_junit_fail_escape_xml_chars(self) -> None:\n        serious = False\n        messages_by_file: dict[str | None, list[str]] = {\n            \"file1.py\": [\"Test failed\", \"another line < > &\"]\n        }\n        expected = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<testsuite errors=\"0\" failures=\"1\" name=\"mypy\" skips=\"0\" tests=\"1\" time=\"1.230\">\n  <testcase classname=\"mypy\" file=\"file1.py\" line=\"1\" name=\"mypy-py3.14-test-plat file1.py\" time=\"1.230\">\n    <failure message=\"mypy produced messages\">Test failed\nanother line &lt; &gt; &amp;</failure>\n  </testcase>\n</testsuite>\n\"\"\"\n        result = _generate_junit_contents(\n            dt=1.23,\n            serious=serious,\n            messages_by_file=messages_by_file,\n            version=\"3.14\",\n            platform=\"test-plat\",\n        )\n        assert result == expected\n\n    def test_junit_fail_two_files(self) -> None:\n        serious = False\n        messages_by_file: dict[str | None, list[str]] = {\n            \"file1.py\": [\"Test failed\", \"another line\"],\n            \"file2.py\": [\"Another failure\", \"line 2\"],\n        }\n        expected = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<testsuite errors=\"0\" failures=\"2\" name=\"mypy\" skips=\"0\" tests=\"2\" time=\"1.230\">\n  <testcase classname=\"mypy\" file=\"file1.py\" line=\"1\" name=\"mypy-py3.14-test-plat file1.py\" time=\"1.230\">\n    <failure message=\"mypy produced messages\">Test failed\nanother line</failure>\n  </testcase>\n  <testcase classname=\"mypy\" file=\"file2.py\" line=\"1\" name=\"mypy-py3.14-test-plat file2.py\" time=\"1.230\">\n    <failure message=\"mypy produced messages\">Another failure\nline 2</failure>\n  </testcase>\n</testsuite>\n\"\"\"\n        result = _generate_junit_contents(\n            dt=1.23,\n            serious=serious,\n            messages_by_file=messages_by_file,\n            version=\"3.14\",\n            platform=\"test-plat\",\n        )\n        assert result == expected\n\n    def test_serious_error(self) -> None:\n        serious = True\n        messages_by_file: dict[str | None, list[str]] = {None: [\"Error line 1\", \"Error line 2\"]}\n        expected = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<testsuite errors=\"1\" failures=\"0\" name=\"mypy\" skips=\"0\" tests=\"1\" time=\"1.230\">\n  <testcase classname=\"mypy\" file=\"mypy\" line=\"1\" name=\"mypy-py3.14-test-plat\" time=\"1.230\">\n    <failure message=\"mypy produced messages\">Error line 1\nError line 2</failure>\n  </testcase>\n</testsuite>\n\"\"\"\n        result = _generate_junit_contents(\n            dt=1.23,\n            serious=serious,\n            messages_by_file=messages_by_file,\n            version=\"3.14\",\n            platform=\"test-plat\",\n        )\n        assert result == expected\n"
  },
  {
    "path": "mypy/test/typefixture.py",
    "content": "\"\"\"Fixture used in type-related test cases.\n\nIt contains class TypeInfos and Type objects.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import (\n    ARG_OPT,\n    ARG_POS,\n    ARG_STAR,\n    COVARIANT,\n    MDEF,\n    Block,\n    ClassDef,\n    FuncDef,\n    SymbolTable,\n    SymbolTableNode,\n    TypeAlias,\n    TypeInfo,\n)\nfrom mypy.semanal_shared import set_callable_name\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Type,\n    TypeAliasType,\n    TypeOfAny,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UninhabitedType,\n    UnionType,\n)\n\n\nclass TypeFixture:\n    \"\"\"Helper class that is used as a fixture in type-related unit tests.\n\n    The members are initialized to contain various type-related values.\n    \"\"\"\n\n    def __init__(self, variance: int = COVARIANT) -> None:\n        # The 'object' class\n        self.oi = self.make_type_info(\"builtins.object\")  # class object\n        self.o = Instance(self.oi, [])  # object\n\n        # Type variables (these are effectively global)\n\n        def make_type_var(\n            name: str, id: int, values: list[Type], upper_bound: Type, variance: int\n        ) -> TypeVarType:\n            return TypeVarType(\n                name,\n                name,\n                TypeVarId(id),\n                values,\n                upper_bound,\n                AnyType(TypeOfAny.from_omitted_generics),\n                variance,\n            )\n\n        self.t = make_type_var(\"T\", 1, [], self.o, variance)  # T`1 (type variable)\n        self.tf = make_type_var(\"T\", -1, [], self.o, variance)  # T`-1 (type variable)\n        self.tf2 = make_type_var(\"T\", -2, [], self.o, variance)  # T`-2 (type variable)\n        self.s = make_type_var(\"S\", 2, [], self.o, variance)  # S`2 (type variable)\n        self.s1 = make_type_var(\"S\", 1, [], self.o, variance)  # S`1 (type variable)\n        self.sf = make_type_var(\"S\", -2, [], self.o, variance)  # S`-2 (type variable)\n        self.sf1 = make_type_var(\"S\", -1, [], self.o, variance)  # S`-1 (type variable)\n        self.u = make_type_var(\"U\", 3, [], self.o, variance)  # U`3 (type variable)\n\n        # Simple types\n        self.anyt = AnyType(TypeOfAny.special_form)\n        self.nonet = NoneType()\n        self.uninhabited = UninhabitedType()\n        self.a_uninhabited = UninhabitedType()\n        self.a_uninhabited.ambiguous = True\n\n        # Abstract class TypeInfos\n\n        # class F\n        self.fi = self.make_type_info(\"F\", is_abstract=True)\n\n        # class F2\n        self.f2i = self.make_type_info(\"F2\", is_abstract=True)\n\n        # class F3(F)\n        self.f3i = self.make_type_info(\"F3\", is_abstract=True, mro=[self.fi])\n\n        # Class TypeInfos\n        self.std_tuplei = self.make_type_info(\n            \"builtins.tuple\", mro=[self.oi], typevars=[\"T\"], variances=[COVARIANT]\n        )  # class tuple\n        self.type_typei = self.make_type_info(\"builtins.type\")  # class type\n        self.bool_type_info = self.make_type_info(\"builtins.bool\")\n        self.str_type_info = self.make_type_info(\"builtins.str\")\n        self.functioni = self.make_type_info(\"builtins.function\")  # function TODO\n        self.ai = self.make_type_info(\"A\", mro=[self.oi])  # class A\n        self.bi = self.make_type_info(\"B\", mro=[self.ai, self.oi])  # class B(A)\n        self.ci = self.make_type_info(\"C\", mro=[self.ai, self.oi])  # class C(A)\n        self.di = self.make_type_info(\"D\", mro=[self.oi])  # class D\n        # class E(F)\n        self.ei = self.make_type_info(\"E\", mro=[self.fi, self.oi])\n        # class E2(F2, F)\n        self.e2i = self.make_type_info(\"E2\", mro=[self.f2i, self.fi, self.oi])\n        # class E3(F, F2)\n        self.e3i = self.make_type_info(\"E3\", mro=[self.fi, self.f2i, self.oi])\n\n        # Generic class TypeInfos\n        # G[T]\n        self.gi = self.make_type_info(\"G\", mro=[self.oi], typevars=[\"T\"], variances=[variance])\n        # G2[T]\n        self.g2i = self.make_type_info(\"G2\", mro=[self.oi], typevars=[\"T\"], variances=[variance])\n        # H[S, T]\n        self.hi = self.make_type_info(\n            \"H\", mro=[self.oi], typevars=[\"S\", \"T\"], variances=[variance, variance]\n        )\n        # GS[T, S] <: G[S]\n        self.gsi = self.make_type_info(\n            \"GS\",\n            mro=[self.gi, self.oi],\n            typevars=[\"T\", \"S\"],\n            variances=[variance, variance],\n            bases=[Instance(self.gi, [self.s])],\n        )\n        # GS2[S] <: G[S]\n        self.gs2i = self.make_type_info(\n            \"GS2\",\n            mro=[self.gi, self.oi],\n            typevars=[\"S\"],\n            variances=[variance],\n            bases=[Instance(self.gi, [self.s1])],\n        )\n\n        # list[T]\n        self.std_listi = self.make_type_info(\n            \"builtins.list\", mro=[self.oi], typevars=[\"T\"], variances=[variance]\n        )\n\n        # Instance types\n        self.std_tuple = Instance(self.std_tuplei, [self.anyt])  # tuple\n        self.type_type = Instance(self.type_typei, [])  # type\n        self.function = Instance(self.functioni, [])  # function TODO\n        self.str_type = Instance(self.str_type_info, [])\n        self.bool_type = Instance(self.bool_type_info, [])\n        self.a = Instance(self.ai, [])  # A\n        self.b = Instance(self.bi, [])  # B\n        self.c = Instance(self.ci, [])  # C\n        self.d = Instance(self.di, [])  # D\n\n        self.e = Instance(self.ei, [])  # E\n        self.e2 = Instance(self.e2i, [])  # E2\n        self.e3 = Instance(self.e3i, [])  # E3\n\n        self.f = Instance(self.fi, [])  # F\n        self.f2 = Instance(self.f2i, [])  # F2\n        self.f3 = Instance(self.f3i, [])  # F3\n\n        # Generic instance types\n        self.ga = Instance(self.gi, [self.a])  # G[A]\n        self.gb = Instance(self.gi, [self.b])  # G[B]\n        self.gd = Instance(self.gi, [self.d])  # G[D]\n        self.go = Instance(self.gi, [self.o])  # G[object]\n        self.gt = Instance(self.gi, [self.t])  # G[T`1]\n        self.gtf = Instance(self.gi, [self.tf])  # G[T`-1]\n        self.gtf2 = Instance(self.gi, [self.tf2])  # G[T`-2]\n        self.gs = Instance(self.gi, [self.s])  # G[S]\n        self.gdyn = Instance(self.gi, [self.anyt])  # G[Any]\n        self.gn = Instance(self.gi, [NoneType()])  # G[None]\n\n        self.g2a = Instance(self.g2i, [self.a])  # G2[A]\n\n        self.gsaa = Instance(self.gsi, [self.a, self.a])  # GS[A, A]\n        self.gsab = Instance(self.gsi, [self.a, self.b])  # GS[A, B]\n        self.gsba = Instance(self.gsi, [self.b, self.a])  # GS[B, A]\n\n        self.gs2a = Instance(self.gs2i, [self.a])  # GS2[A]\n        self.gs2b = Instance(self.gs2i, [self.b])  # GS2[B]\n        self.gs2d = Instance(self.gs2i, [self.d])  # GS2[D]\n\n        self.hab = Instance(self.hi, [self.a, self.b])  # H[A, B]\n        self.haa = Instance(self.hi, [self.a, self.a])  # H[A, A]\n        self.hbb = Instance(self.hi, [self.b, self.b])  # H[B, B]\n        self.hts = Instance(self.hi, [self.t, self.s])  # H[T, S]\n        self.had = Instance(self.hi, [self.a, self.d])  # H[A, D]\n        self.hao = Instance(self.hi, [self.a, self.o])  # H[A, object]\n\n        self.lsta = Instance(self.std_listi, [self.a])  # List[A]\n        self.lstb = Instance(self.std_listi, [self.b])  # List[B]\n\n        self.lit1 = LiteralType(1, self.a)\n        self.lit2 = LiteralType(2, self.a)\n        self.lit3 = LiteralType(\"foo\", self.d)\n        self.lit4 = LiteralType(4, self.a)\n        self.lit1_inst = Instance(self.ai, [], last_known_value=self.lit1)\n        self.lit2_inst = Instance(self.ai, [], last_known_value=self.lit2)\n        self.lit3_inst = Instance(self.di, [], last_known_value=self.lit3)\n        self.lit4_inst = Instance(self.ai, [], last_known_value=self.lit4)\n\n        self.lit_str1 = LiteralType(\"x\", self.str_type)\n        self.lit_str2 = LiteralType(\"y\", self.str_type)\n        self.lit_str3 = LiteralType(\"z\", self.str_type)\n        self.lit_str1_inst = Instance(self.str_type_info, [], last_known_value=self.lit_str1)\n        self.lit_str2_inst = Instance(self.str_type_info, [], last_known_value=self.lit_str2)\n        self.lit_str3_inst = Instance(self.str_type_info, [], last_known_value=self.lit_str3)\n\n        self.lit_false = LiteralType(False, self.bool_type)\n        self.lit_true = LiteralType(True, self.bool_type)\n\n        self.type_a = TypeType.make_normalized(self.a)\n        self.type_b = TypeType.make_normalized(self.b)\n        self.type_c = TypeType.make_normalized(self.c)\n        self.type_d = TypeType.make_normalized(self.d)\n        self.type_t = TypeType.make_normalized(self.t)\n        self.type_any = TypeType.make_normalized(self.anyt)\n        self.type_never = TypeType.make_normalized(UninhabitedType())\n\n        self._add_bool_dunder(self.bool_type_info)\n        self._add_bool_dunder(self.ai)\n\n        # TypeVars with non-trivial bounds\n        self.ub = make_type_var(\"UB\", 5, [], self.b, variance)  # UB`5 (type variable)\n        self.uc = make_type_var(\"UC\", 6, [], self.c, variance)  # UC`6 (type variable)\n\n        def make_type_var_tuple(name: str, id: int, upper_bound: Type) -> TypeVarTupleType:\n            return TypeVarTupleType(\n                name,\n                name,\n                TypeVarId(id),\n                upper_bound,\n                self.std_tuple,\n                AnyType(TypeOfAny.from_omitted_generics),\n            )\n\n        obj_tuple = self.std_tuple.copy_modified(args=[self.o])\n        self.ts = make_type_var_tuple(\"Ts\", 1, obj_tuple)  # Ts`1 (type var tuple)\n        self.ss = make_type_var_tuple(\"Ss\", 2, obj_tuple)  # Ss`2 (type var tuple)\n        self.us = make_type_var_tuple(\"Us\", 3, obj_tuple)  # Us`3 (type var tuple)\n\n        self.gvi = self.make_type_info(\"GV\", mro=[self.oi], typevars=[\"Ts\"], typevar_tuple_index=0)\n        self.gv2i = self.make_type_info(\n            \"GV2\", mro=[self.oi], typevars=[\"T\", \"Ts\", \"S\"], typevar_tuple_index=1\n        )\n\n    def _add_bool_dunder(self, type_info: TypeInfo) -> None:\n        signature = CallableType([], [], [], Instance(self.bool_type_info, []), self.function)\n        bool_func = FuncDef(\"__bool__\", [], Block([]))\n        bool_func.type = set_callable_name(signature, bool_func)\n        type_info.names[bool_func.name] = SymbolTableNode(MDEF, bool_func)\n\n    # Helper methods\n\n    def callable(self, *a: Type) -> CallableType:\n        \"\"\"callable(a1, ..., an, r) constructs a callable with argument types\n        a1, ... an and return type r.\n        \"\"\"\n        return CallableType(\n            list(a[:-1]), [ARG_POS] * (len(a) - 1), [None] * (len(a) - 1), a[-1], self.function\n        )\n\n    def callable_type(self, *a: Type) -> CallableType:\n        \"\"\"callable_type(a1, ..., an, r) constructs a callable with\n        argument types a1, ... an and return type r, and which\n        represents a type.\n        \"\"\"\n        return CallableType(\n            list(a[:-1]), [ARG_POS] * (len(a) - 1), [None] * (len(a) - 1), a[-1], self.type_type\n        )\n\n    def callable_default(self, min_args: int, *a: Type) -> CallableType:\n        \"\"\"callable_default(min_args, a1, ..., an, r) constructs a\n        callable with argument types a1, ... an and return type r,\n        with min_args mandatory fixed arguments.\n        \"\"\"\n        n = len(a) - 1\n        return CallableType(\n            list(a[:-1]),\n            [ARG_POS] * min_args + [ARG_OPT] * (n - min_args),\n            [None] * n,\n            a[-1],\n            self.function,\n        )\n\n    def callable_var_arg(self, min_args: int, *a: Type) -> CallableType:\n        \"\"\"callable_var_arg(min_args, a1, ..., an, r) constructs a callable\n        with argument types a1, ... *an and return type r.\n        \"\"\"\n        n = len(a) - 1\n        return CallableType(\n            list(a[:-1]),\n            [ARG_POS] * min_args + [ARG_OPT] * (n - 1 - min_args) + [ARG_STAR],\n            [None] * n,\n            a[-1],\n            self.function,\n        )\n\n    def make_type_info(\n        self,\n        name: str,\n        module_name: str | None = None,\n        is_abstract: bool = False,\n        mro: list[TypeInfo] | None = None,\n        bases: list[Instance] | None = None,\n        typevars: list[str] | None = None,\n        typevar_tuple_index: int | None = None,\n        variances: list[int] | None = None,\n    ) -> TypeInfo:\n        \"\"\"Make a TypeInfo suitable for use in unit tests.\"\"\"\n\n        class_def = ClassDef(name, Block([]), None, [])\n        class_def.fullname = name\n\n        if module_name is None:\n            if \".\" in name:\n                module_name = name.rsplit(\".\", 1)[0]\n            else:\n                module_name = \"__main__\"\n\n        if typevars:\n            v: list[TypeVarLikeType] = []\n            for id, n in enumerate(typevars, 1):\n                if typevar_tuple_index is not None and id - 1 == typevar_tuple_index:\n                    v.append(\n                        TypeVarTupleType(\n                            n,\n                            n,\n                            TypeVarId(id),\n                            self.std_tuple.copy_modified(args=[self.o]),\n                            self.std_tuple.copy_modified(args=[self.o]),\n                            AnyType(TypeOfAny.from_omitted_generics),\n                        )\n                    )\n                else:\n                    if variances:\n                        variance = variances[id - 1]\n                    else:\n                        variance = COVARIANT\n                    v.append(\n                        TypeVarType(\n                            n,\n                            n,\n                            TypeVarId(id),\n                            [],\n                            self.o,\n                            AnyType(TypeOfAny.from_omitted_generics),\n                            variance=variance,\n                        )\n                    )\n            class_def.type_vars = v\n\n        info = TypeInfo(SymbolTable(), class_def, module_name)\n        if mro is None:\n            mro = []\n            if name != \"builtins.object\":\n                mro.append(self.oi)\n        info.mro = [info] + mro\n        if bases is None:\n            if mro:\n                # By default, assume that there is a single non-generic base.\n                bases = [Instance(mro[0], [])]\n            else:\n                bases = []\n        info.bases = bases\n\n        return info\n\n    def def_alias_1(self, base: Instance) -> tuple[TypeAliasType, Type]:\n        A = TypeAliasType(None, [])\n        target = Instance(\n            self.std_tuplei, [UnionType([base, A])]\n        )  # A = Tuple[Union[base, A], ...]\n        AN = TypeAlias(target, \"__main__.A\", \"__main__\", -1, -1)\n        A.alias = AN\n        return A, target\n\n    def def_alias_2(self, base: Instance) -> tuple[TypeAliasType, Type]:\n        A = TypeAliasType(None, [])\n        target = UnionType(\n            [base, Instance(self.std_tuplei, [A])]\n        )  # A = Union[base, Tuple[A, ...]]\n        AN = TypeAlias(target, \"__main__.A\", \"__main__\", -1, -1)\n        A.alias = AN\n        return A, target\n\n    def non_rec_alias(\n        self,\n        target: Type,\n        alias_tvars: list[TypeVarLikeType] | None = None,\n        args: list[Type] | None = None,\n    ) -> TypeAliasType:\n        AN = TypeAlias(target, \"__main__.A\", \"__main__\", -1, -1, alias_tvars=alias_tvars)\n        if args is None:\n            args = []\n        return TypeAliasType(AN, args)\n\n\nclass InterfaceTypeFixture(TypeFixture):\n    \"\"\"Extension of TypeFixture that contains additional generic\n    interface types.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__()\n        # GF[T]\n        self.gfi = self.make_type_info(\"GF\", typevars=[\"T\"], is_abstract=True)\n\n        # M1 <: GF[A]\n        self.m1i = self.make_type_info(\n            \"M1\", is_abstract=True, mro=[self.gfi, self.oi], bases=[Instance(self.gfi, [self.a])]\n        )\n\n        self.gfa = Instance(self.gfi, [self.a])  # GF[A]\n        self.gfb = Instance(self.gfi, [self.b])  # GF[B]\n\n        self.m1 = Instance(self.m1i, [])  # M1\n"
  },
  {
    "path": "mypy/test/update_data.py",
    "content": "from __future__ import annotations\n\nimport re\nfrom collections import defaultdict\nfrom collections.abc import Iterator\n\nfrom mypy.test.data import DataDrivenTestCase, DataFileCollector, DataFileFix, parse_test_data\n\n\ndef update_testcase_output(\n    testcase: DataDrivenTestCase, actual: list[str], *, incremental_step: int\n) -> None:\n    if testcase.xfail:\n        return\n    collector = testcase.parent\n    assert isinstance(collector, DataFileCollector)\n    for fix in _iter_fixes(testcase, actual, incremental_step=incremental_step):\n        collector.enqueue_fix(fix)\n\n\ndef _iter_fixes(\n    testcase: DataDrivenTestCase, actual: list[str], *, incremental_step: int\n) -> Iterator[DataFileFix]:\n    reports_by_line: dict[tuple[str, int], list[tuple[str, str]]] = defaultdict(list)\n    for error_line in actual:\n        comment_match = re.match(\n            r\"^(?P<filename>[^:]+):(?P<lineno>\\d+): (?P<severity>error|note|warning): (?P<msg>.+)$\",\n            error_line,\n        )\n        if comment_match:\n            filename = comment_match.group(\"filename\")\n            lineno = int(comment_match.group(\"lineno\"))\n            severity = comment_match.group(\"severity\")\n            msg = comment_match.group(\"msg\")\n            reports_by_line[filename, lineno].append((severity, msg))\n\n    test_items = parse_test_data(testcase.data, testcase.name)\n\n    # If we have [out] and/or [outN], we update just those sections.\n    if any(re.match(r\"^out\\d*$\", test_item.id) for test_item in test_items):\n        for test_item in test_items:\n            if (incremental_step < 2 and test_item.id == \"out\") or (\n                incremental_step >= 2 and test_item.id == f\"out{incremental_step}\"\n            ):\n                yield DataFileFix(\n                    lineno=testcase.line + test_item.line - 1,\n                    end_lineno=testcase.line + test_item.end_line - 1,\n                    lines=actual + [\"\"] * test_item.trimmed_newlines,\n                )\n\n        return\n\n    # Update assertion comments within the sections\n    for test_item in test_items:\n        if test_item.id == \"case\":\n            source_lines = test_item.data\n            file_path = \"main\"\n        elif test_item.id == \"file\":\n            source_lines = test_item.data\n            file_path = f\"tmp/{test_item.arg}\"\n        else:\n            continue  # other sections we don't touch\n\n        fix_lines = []\n        for lineno, source_line in enumerate(source_lines, start=1):\n            reports = reports_by_line.get((file_path, lineno))\n            comment_match = re.search(r\"(?P<indent>\\s+)(?P<comment># [EWN]: .+)$\", source_line)\n            if comment_match:\n                source_line = source_line[: comment_match.start(\"indent\")]  # strip old comment\n            if reports:\n                indent = comment_match.group(\"indent\") if comment_match else \"  \"\n                # multiline comments are on the first line and then on subsequent lines empty lines\n                # with a continuation backslash\n                for j, (severity, msg) in enumerate(reports):\n                    out_l = source_line if j == 0 else \" \" * len(source_line)\n                    is_last = j == len(reports) - 1\n                    severity_char = severity[0].upper()\n                    continuation = \"\" if is_last else \" \\\\\"\n                    fix_lines.append(f\"{out_l}{indent}# {severity_char}: {msg}{continuation}\")\n            else:\n                fix_lines.append(source_line)\n\n        yield DataFileFix(\n            lineno=testcase.line + test_item.line - 1,\n            end_lineno=testcase.line + test_item.end_line - 1,\n            lines=fix_lines + [\"\"] * test_item.trimmed_newlines,\n        )\n"
  },
  {
    "path": "mypy/test/visitors.py",
    "content": "\"\"\"Visitor classes pulled out from different tests\n\nThese are here because we don't currently support having interpreted\nclasses subtype compiled ones but pytest grabs the python file\neven if the test was compiled.\n\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import AssignmentStmt, CallExpr, Expression, IntExpr, NameExpr, Node, TypeVarExpr\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.treetransform import TransformVisitor\nfrom mypy.types import Type\n\n\n# from testtypegen\nclass SkippedNodeSearcher(TraverserVisitor):\n    def __init__(self) -> None:\n        self.nodes: set[Node] = set()\n        self.ignore_file = False\n\n    def visit_assignment_stmt(self, s: AssignmentStmt) -> None:\n        if s.type or ignore_node(s.rvalue):\n            for lvalue in s.lvalues:\n                if isinstance(lvalue, NameExpr):\n                    self.nodes.add(lvalue)\n        super().visit_assignment_stmt(s)\n\n    def visit_name_expr(self, n: NameExpr) -> None:\n        if self.ignore_file:\n            self.nodes.add(n)\n        super().visit_name_expr(n)\n\n    def visit_int_expr(self, n: IntExpr) -> None:\n        if self.ignore_file:\n            self.nodes.add(n)\n        super().visit_int_expr(n)\n\n\ndef ignore_node(node: Expression) -> bool:\n    \"\"\"Return True if node is to be omitted from test case output.\"\"\"\n\n    # We want to get rid of object() expressions in the typing module stub\n    # and also TypeVar(...) expressions. Since detecting whether a node comes\n    # from the typing module is not easy, we just to strip them all away.\n    if isinstance(node, TypeVarExpr):\n        return True\n    if isinstance(node, NameExpr) and node.fullname == \"builtins.object\":\n        return True\n    if isinstance(node, NameExpr) and node.fullname == \"builtins.None\":\n        return True\n    if isinstance(node, CallExpr) and (ignore_node(node.callee) or node.analyzed):\n        return True\n\n    return False\n\n\n# from testtransform\nclass TypeAssertTransformVisitor(TransformVisitor):\n    def type(self, type: Type) -> Type:\n        assert type is not None\n        return type\n"
  },
  {
    "path": "mypy/traverser.py",
    "content": "\"\"\"Generic node traverser visitor\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy_extensions import mypyc_attr, trait\n\nfrom mypy.nodes import (\n    REVEAL_TYPE,\n    AssertStmt,\n    AssertTypeExpr,\n    AssignmentExpr,\n    AssignmentStmt,\n    AwaitExpr,\n    Block,\n    BreakStmt,\n    BytesExpr,\n    CallExpr,\n    CastExpr,\n    ClassDef,\n    ComparisonExpr,\n    ComplexExpr,\n    ConditionalExpr,\n    ContinueStmt,\n    Decorator,\n    DelStmt,\n    DictExpr,\n    DictionaryComprehension,\n    EllipsisExpr,\n    EnumCallExpr,\n    Expression,\n    ExpressionStmt,\n    FloatExpr,\n    ForStmt,\n    FuncBase,\n    FuncDef,\n    FuncItem,\n    GeneratorExpr,\n    GlobalDecl,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    MatchStmt,\n    MemberExpr,\n    MypyFile,\n    NamedTupleExpr,\n    NameExpr,\n    NewTypeExpr,\n    Node,\n    NonlocalDecl,\n    OperatorAssignmentStmt,\n    OpExpr,\n    OverloadedFuncDef,\n    ParamSpecExpr,\n    PassStmt,\n    PromoteExpr,\n    RaiseStmt,\n    ReturnStmt,\n    RevealExpr,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    StrExpr,\n    SuperExpr,\n    TemplateStrExpr,\n    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAlias,\n    TypeAliasExpr,\n    TypeAliasStmt,\n    TypeApplication,\n    TypedDictExpr,\n    TypeFormExpr,\n    TypeVarExpr,\n    TypeVarTupleExpr,\n    UnaryExpr,\n    Var,\n    WhileStmt,\n    WithStmt,\n    YieldExpr,\n    YieldFromExpr,\n)\nfrom mypy.patterns import (\n    AsPattern,\n    ClassPattern,\n    MappingPattern,\n    OrPattern,\n    SequencePattern,\n    SingletonPattern,\n    StarredPattern,\n    ValuePattern,\n)\nfrom mypy.visitor import NodeVisitor\n\n\n@trait\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass TraverserVisitor(NodeVisitor[None]):\n    \"\"\"A parse tree visitor that traverses the parse tree during visiting.\n\n    It does not perform any actions outside the traversal. Subclasses\n    should override visit methods to perform actions during\n    traversal. Calling the superclass method allows reusing the\n    traversal implementation.\n\n    TODO: split this into more limited visitor (e.g. statements-only etc).\n    This will improve performance since in many cases we don't need to recurse\n    all the way down in various visitors that subclass this.\n    \"\"\"\n\n    def __init__(self) -> None:\n        pass\n\n    # Visit methods\n\n    def visit_mypy_file(self, o: MypyFile, /) -> None:\n        for d in o.defs:\n            d.accept(self)\n\n    def visit_block(self, block: Block, /) -> None:\n        for s in block.body:\n            s.accept(self)\n\n    def visit_func(self, o: FuncItem, /) -> None:\n        if o.arguments is not None:\n            for arg in o.arguments:\n                init = arg.initializer\n                if init is not None:\n                    init.accept(self)\n\n            for arg in o.arguments:\n                self.visit_var(arg.variable)\n\n        o.body.accept(self)\n\n    def visit_func_def(self, o: FuncDef, /) -> None:\n        self.visit_func(o)\n\n    def visit_overloaded_func_def(self, o: OverloadedFuncDef, /) -> None:\n        for item in o.items:\n            item.accept(self)\n        if o.impl:\n            o.impl.accept(self)\n\n    def visit_class_def(self, o: ClassDef, /) -> None:\n        for d in o.decorators:\n            d.accept(self)\n        for base in o.base_type_exprs:\n            base.accept(self)\n        if o.metaclass:\n            o.metaclass.accept(self)\n        for v in o.keywords.values():\n            v.accept(self)\n        o.defs.accept(self)\n        if o.analyzed:\n            o.analyzed.accept(self)\n\n    def visit_decorator(self, o: Decorator, /) -> None:\n        o.func.accept(self)\n        o.var.accept(self)\n        for decorator in o.decorators:\n            decorator.accept(self)\n\n    def visit_expression_stmt(self, o: ExpressionStmt, /) -> None:\n        o.expr.accept(self)\n\n    def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None:\n        o.rvalue.accept(self)\n        for l in o.lvalues:\n            l.accept(self)\n\n    def visit_operator_assignment_stmt(self, o: OperatorAssignmentStmt, /) -> None:\n        o.rvalue.accept(self)\n        o.lvalue.accept(self)\n\n    def visit_while_stmt(self, o: WhileStmt, /) -> None:\n        o.expr.accept(self)\n        o.body.accept(self)\n        if o.else_body:\n            o.else_body.accept(self)\n\n    def visit_for_stmt(self, o: ForStmt, /) -> None:\n        o.index.accept(self)\n        o.expr.accept(self)\n        o.body.accept(self)\n        if o.else_body:\n            o.else_body.accept(self)\n\n    def visit_return_stmt(self, o: ReturnStmt, /) -> None:\n        if o.expr is not None:\n            o.expr.accept(self)\n\n    def visit_assert_stmt(self, o: AssertStmt, /) -> None:\n        if o.expr is not None:\n            o.expr.accept(self)\n        if o.msg is not None:\n            o.msg.accept(self)\n\n    def visit_del_stmt(self, o: DelStmt, /) -> None:\n        if o.expr is not None:\n            o.expr.accept(self)\n\n    def visit_if_stmt(self, o: IfStmt, /) -> None:\n        for e in o.expr:\n            e.accept(self)\n        for b in o.body:\n            b.accept(self)\n        if o.else_body:\n            o.else_body.accept(self)\n\n    def visit_raise_stmt(self, o: RaiseStmt, /) -> None:\n        if o.expr is not None:\n            o.expr.accept(self)\n        if o.from_expr is not None:\n            o.from_expr.accept(self)\n\n    def visit_try_stmt(self, o: TryStmt, /) -> None:\n        o.body.accept(self)\n        for i in range(len(o.types)):\n            tp = o.types[i]\n            if tp is not None:\n                tp.accept(self)\n            o.handlers[i].accept(self)\n        for v in o.vars:\n            if v is not None:\n                v.accept(self)\n        if o.else_body is not None:\n            o.else_body.accept(self)\n        if o.finally_body is not None:\n            o.finally_body.accept(self)\n\n    def visit_with_stmt(self, o: WithStmt, /) -> None:\n        for i in range(len(o.expr)):\n            o.expr[i].accept(self)\n            targ = o.target[i]\n            if targ is not None:\n                targ.accept(self)\n        o.body.accept(self)\n\n    def visit_match_stmt(self, o: MatchStmt, /) -> None:\n        o.subject.accept(self)\n        for i in range(len(o.patterns)):\n            o.patterns[i].accept(self)\n            guard = o.guards[i]\n            if guard is not None:\n                guard.accept(self)\n            o.bodies[i].accept(self)\n\n    def visit_type_alias_stmt(self, o: TypeAliasStmt, /) -> None:\n        o.name.accept(self)\n        o.value.accept(self)\n\n    def visit_member_expr(self, o: MemberExpr, /) -> None:\n        o.expr.accept(self)\n\n    def visit_yield_from_expr(self, o: YieldFromExpr, /) -> None:\n        o.expr.accept(self)\n\n    def visit_yield_expr(self, o: YieldExpr, /) -> None:\n        if o.expr:\n            o.expr.accept(self)\n\n    def visit_call_expr(self, o: CallExpr, /) -> None:\n        o.callee.accept(self)\n        for a in o.args:\n            a.accept(self)\n        if o.analyzed:\n            o.analyzed.accept(self)\n\n    def visit_op_expr(self, o: OpExpr, /) -> None:\n        o.left.accept(self)\n        o.right.accept(self)\n        if o.analyzed is not None:\n            o.analyzed.accept(self)\n\n    def visit_comparison_expr(self, o: ComparisonExpr, /) -> None:\n        for operand in o.operands:\n            operand.accept(self)\n\n    def visit_slice_expr(self, o: SliceExpr, /) -> None:\n        if o.begin_index is not None:\n            o.begin_index.accept(self)\n        if o.end_index is not None:\n            o.end_index.accept(self)\n        if o.stride is not None:\n            o.stride.accept(self)\n\n    def visit_cast_expr(self, o: CastExpr, /) -> None:\n        o.expr.accept(self)\n\n    def visit_type_form_expr(self, o: TypeFormExpr, /) -> None:\n        pass\n\n    def visit_assert_type_expr(self, o: AssertTypeExpr, /) -> None:\n        o.expr.accept(self)\n\n    def visit_reveal_expr(self, o: RevealExpr, /) -> None:\n        if o.kind == REVEAL_TYPE:\n            assert o.expr is not None\n            o.expr.accept(self)\n        else:\n            # RevealLocalsExpr doesn't have an inner expression\n            pass\n\n    def visit_assignment_expr(self, o: AssignmentExpr, /) -> None:\n        o.target.accept(self)\n        o.value.accept(self)\n\n    def visit_unary_expr(self, o: UnaryExpr, /) -> None:\n        o.expr.accept(self)\n\n    def visit_list_expr(self, o: ListExpr, /) -> None:\n        for item in o.items:\n            item.accept(self)\n\n    def visit_tuple_expr(self, o: TupleExpr, /) -> None:\n        for item in o.items:\n            item.accept(self)\n\n    def visit_dict_expr(self, o: DictExpr, /) -> None:\n        for k, v in o.items:\n            if k is not None:\n                k.accept(self)\n            v.accept(self)\n\n    def visit_template_str_expr(self, o: TemplateStrExpr, /) -> None:\n        for item in o.items:\n            if isinstance(item, tuple):\n                item[0].accept(self)\n                if item[3] is not None:\n                    item[3].accept(self)\n            else:\n                item.accept(self)\n\n    def visit_set_expr(self, o: SetExpr, /) -> None:\n        for item in o.items:\n            item.accept(self)\n\n    def visit_index_expr(self, o: IndexExpr, /) -> None:\n        o.base.accept(self)\n        o.index.accept(self)\n        if o.analyzed:\n            o.analyzed.accept(self)\n\n    def visit_generator_expr(self, o: GeneratorExpr, /) -> None:\n        for index, sequence, conditions in zip(o.indices, o.sequences, o.condlists):\n            sequence.accept(self)\n            index.accept(self)\n            for cond in conditions:\n                cond.accept(self)\n        o.left_expr.accept(self)\n\n    def visit_dictionary_comprehension(self, o: DictionaryComprehension, /) -> None:\n        for index, sequence, conditions in zip(o.indices, o.sequences, o.condlists):\n            sequence.accept(self)\n            index.accept(self)\n            for cond in conditions:\n                cond.accept(self)\n        o.key.accept(self)\n        o.value.accept(self)\n\n    def visit_list_comprehension(self, o: ListComprehension, /) -> None:\n        o.generator.accept(self)\n\n    def visit_set_comprehension(self, o: SetComprehension, /) -> None:\n        o.generator.accept(self)\n\n    def visit_conditional_expr(self, o: ConditionalExpr, /) -> None:\n        o.cond.accept(self)\n        o.if_expr.accept(self)\n        o.else_expr.accept(self)\n\n    def visit_type_application(self, o: TypeApplication, /) -> None:\n        o.expr.accept(self)\n\n    def visit_lambda_expr(self, o: LambdaExpr, /) -> None:\n        self.visit_func(o)\n\n    def visit_star_expr(self, o: StarExpr, /) -> None:\n        o.expr.accept(self)\n\n    def visit_await_expr(self, o: AwaitExpr, /) -> None:\n        o.expr.accept(self)\n\n    def visit_super_expr(self, o: SuperExpr, /) -> None:\n        o.call.accept(self)\n\n    def visit_as_pattern(self, o: AsPattern, /) -> None:\n        if o.pattern is not None:\n            o.pattern.accept(self)\n        if o.name is not None:\n            o.name.accept(self)\n\n    def visit_or_pattern(self, o: OrPattern, /) -> None:\n        for p in o.patterns:\n            p.accept(self)\n\n    def visit_value_pattern(self, o: ValuePattern, /) -> None:\n        o.expr.accept(self)\n\n    def visit_sequence_pattern(self, o: SequencePattern, /) -> None:\n        for p in o.patterns:\n            p.accept(self)\n\n    def visit_starred_pattern(self, o: StarredPattern, /) -> None:\n        if o.capture is not None:\n            o.capture.accept(self)\n\n    def visit_mapping_pattern(self, o: MappingPattern, /) -> None:\n        for key in o.keys:\n            key.accept(self)\n        for value in o.values:\n            value.accept(self)\n        if o.rest is not None:\n            o.rest.accept(self)\n\n    def visit_class_pattern(self, o: ClassPattern, /) -> None:\n        o.class_ref.accept(self)\n        for p in o.positionals:\n            p.accept(self)\n        for v in o.keyword_values:\n            v.accept(self)\n\n    def visit_import(self, o: Import, /) -> None:\n        for a in o.assignments:\n            a.accept(self)\n\n    def visit_import_from(self, o: ImportFrom, /) -> None:\n        for a in o.assignments:\n            a.accept(self)\n\n    # leaf nodes\n    def visit_name_expr(self, o: NameExpr, /) -> None:\n        return None\n\n    def visit_str_expr(self, o: StrExpr, /) -> None:\n        return None\n\n    def visit_int_expr(self, o: IntExpr, /) -> None:\n        return None\n\n    def visit_float_expr(self, o: FloatExpr, /) -> None:\n        return None\n\n    def visit_bytes_expr(self, o: BytesExpr, /) -> None:\n        return None\n\n    def visit_ellipsis(self, o: EllipsisExpr, /) -> None:\n        return None\n\n    def visit_var(self, o: Var, /) -> None:\n        return None\n\n    def visit_continue_stmt(self, o: ContinueStmt, /) -> None:\n        return None\n\n    def visit_pass_stmt(self, o: PassStmt, /) -> None:\n        return None\n\n    def visit_break_stmt(self, o: BreakStmt, /) -> None:\n        return None\n\n    def visit_temp_node(self, o: TempNode, /) -> None:\n        return None\n\n    def visit_nonlocal_decl(self, o: NonlocalDecl, /) -> None:\n        return None\n\n    def visit_global_decl(self, o: GlobalDecl, /) -> None:\n        return None\n\n    def visit_import_all(self, o: ImportAll, /) -> None:\n        return None\n\n    def visit_type_var_expr(self, o: TypeVarExpr, /) -> None:\n        return None\n\n    def visit_paramspec_expr(self, o: ParamSpecExpr, /) -> None:\n        return None\n\n    def visit_type_var_tuple_expr(self, o: TypeVarTupleExpr, /) -> None:\n        return None\n\n    def visit_type_alias_expr(self, o: TypeAliasExpr, /) -> None:\n        return None\n\n    def visit_type_alias(self, o: TypeAlias, /) -> None:\n        return None\n\n    def visit_namedtuple_expr(self, o: NamedTupleExpr, /) -> None:\n        return None\n\n    def visit_typeddict_expr(self, o: TypedDictExpr, /) -> None:\n        return None\n\n    def visit_newtype_expr(self, o: NewTypeExpr, /) -> None:\n        return None\n\n    def visit__promote_expr(self, o: PromoteExpr, /) -> None:\n        return None\n\n    def visit_complex_expr(self, o: ComplexExpr, /) -> None:\n        return None\n\n    def visit_enum_call_expr(self, o: EnumCallExpr, /) -> None:\n        return None\n\n    def visit_singleton_pattern(self, o: SingletonPattern, /) -> None:\n        return None\n\n\nclass ExtendedTraverserVisitor(TraverserVisitor):\n    \"\"\"This is a more flexible traverser.\n\n    In addition to the base traverser it:\n        * has visit_ methods for leaf nodes\n        * has common method that is called for all nodes\n        * allows skipping recursing into a node\n\n    Note that this traverser still doesn't visit some internal\n    mypy constructs like _promote expression and Var.\n    \"\"\"\n\n    def visit(self, o: Node) -> bool:\n        # If returns True, will continue to nested nodes.\n        return True\n\n    def visit_mypy_file(self, o: MypyFile, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_mypy_file(o)\n\n    # Module structure\n\n    def visit_import(self, o: Import, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_import(o)\n\n    def visit_import_from(self, o: ImportFrom, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_import_from(o)\n\n    def visit_import_all(self, o: ImportAll, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_import_all(o)\n\n    # Definitions\n\n    def visit_func_def(self, o: FuncDef, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_func_def(o)\n\n    def visit_overloaded_func_def(self, o: OverloadedFuncDef, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_overloaded_func_def(o)\n\n    def visit_class_def(self, o: ClassDef, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_class_def(o)\n\n    def visit_global_decl(self, o: GlobalDecl, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_global_decl(o)\n\n    def visit_nonlocal_decl(self, o: NonlocalDecl, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_nonlocal_decl(o)\n\n    def visit_decorator(self, o: Decorator, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_decorator(o)\n\n    def visit_type_alias(self, o: TypeAlias, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_type_alias(o)\n\n    # Statements\n\n    def visit_block(self, block: Block, /) -> None:\n        if not self.visit(block):\n            return\n        super().visit_block(block)\n\n    def visit_expression_stmt(self, o: ExpressionStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_expression_stmt(o)\n\n    def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_assignment_stmt(o)\n\n    def visit_operator_assignment_stmt(self, o: OperatorAssignmentStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_operator_assignment_stmt(o)\n\n    def visit_while_stmt(self, o: WhileStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_while_stmt(o)\n\n    def visit_for_stmt(self, o: ForStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_for_stmt(o)\n\n    def visit_return_stmt(self, o: ReturnStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_return_stmt(o)\n\n    def visit_assert_stmt(self, o: AssertStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_assert_stmt(o)\n\n    def visit_del_stmt(self, o: DelStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_del_stmt(o)\n\n    def visit_if_stmt(self, o: IfStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_if_stmt(o)\n\n    def visit_break_stmt(self, o: BreakStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_break_stmt(o)\n\n    def visit_continue_stmt(self, o: ContinueStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_continue_stmt(o)\n\n    def visit_pass_stmt(self, o: PassStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_pass_stmt(o)\n\n    def visit_raise_stmt(self, o: RaiseStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_raise_stmt(o)\n\n    def visit_try_stmt(self, o: TryStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_try_stmt(o)\n\n    def visit_with_stmt(self, o: WithStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_with_stmt(o)\n\n    def visit_match_stmt(self, o: MatchStmt, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_match_stmt(o)\n\n    # Expressions (default no-op implementation)\n\n    def visit_int_expr(self, o: IntExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_int_expr(o)\n\n    def visit_str_expr(self, o: StrExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_str_expr(o)\n\n    def visit_bytes_expr(self, o: BytesExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_bytes_expr(o)\n\n    def visit_float_expr(self, o: FloatExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_float_expr(o)\n\n    def visit_complex_expr(self, o: ComplexExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_complex_expr(o)\n\n    def visit_ellipsis(self, o: EllipsisExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_ellipsis(o)\n\n    def visit_star_expr(self, o: StarExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_star_expr(o)\n\n    def visit_name_expr(self, o: NameExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_name_expr(o)\n\n    def visit_member_expr(self, o: MemberExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_member_expr(o)\n\n    def visit_yield_from_expr(self, o: YieldFromExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_yield_from_expr(o)\n\n    def visit_yield_expr(self, o: YieldExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_yield_expr(o)\n\n    def visit_call_expr(self, o: CallExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_call_expr(o)\n\n    def visit_op_expr(self, o: OpExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_op_expr(o)\n\n    def visit_comparison_expr(self, o: ComparisonExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_comparison_expr(o)\n\n    def visit_cast_expr(self, o: CastExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_cast_expr(o)\n\n    def visit_type_form_expr(self, o: TypeFormExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_type_form_expr(o)\n\n    def visit_assert_type_expr(self, o: AssertTypeExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_assert_type_expr(o)\n\n    def visit_reveal_expr(self, o: RevealExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_reveal_expr(o)\n\n    def visit_super_expr(self, o: SuperExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_super_expr(o)\n\n    def visit_assignment_expr(self, o: AssignmentExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_assignment_expr(o)\n\n    def visit_unary_expr(self, o: UnaryExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_unary_expr(o)\n\n    def visit_list_expr(self, o: ListExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_list_expr(o)\n\n    def visit_dict_expr(self, o: DictExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_dict_expr(o)\n\n    def visit_template_str_expr(self, o: TemplateStrExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_template_str_expr(o)\n\n    def visit_tuple_expr(self, o: TupleExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_tuple_expr(o)\n\n    def visit_set_expr(self, o: SetExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_set_expr(o)\n\n    def visit_index_expr(self, o: IndexExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_index_expr(o)\n\n    def visit_type_application(self, o: TypeApplication, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_type_application(o)\n\n    def visit_lambda_expr(self, o: LambdaExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_lambda_expr(o)\n\n    def visit_list_comprehension(self, o: ListComprehension, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_list_comprehension(o)\n\n    def visit_set_comprehension(self, o: SetComprehension, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_set_comprehension(o)\n\n    def visit_dictionary_comprehension(self, o: DictionaryComprehension, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_dictionary_comprehension(o)\n\n    def visit_generator_expr(self, o: GeneratorExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_generator_expr(o)\n\n    def visit_slice_expr(self, o: SliceExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_slice_expr(o)\n\n    def visit_conditional_expr(self, o: ConditionalExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_conditional_expr(o)\n\n    def visit_type_var_expr(self, o: TypeVarExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_type_var_expr(o)\n\n    def visit_paramspec_expr(self, o: ParamSpecExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_paramspec_expr(o)\n\n    def visit_type_var_tuple_expr(self, o: TypeVarTupleExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_type_var_tuple_expr(o)\n\n    def visit_type_alias_expr(self, o: TypeAliasExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_type_alias_expr(o)\n\n    def visit_namedtuple_expr(self, o: NamedTupleExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_namedtuple_expr(o)\n\n    def visit_enum_call_expr(self, o: EnumCallExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_enum_call_expr(o)\n\n    def visit_typeddict_expr(self, o: TypedDictExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_typeddict_expr(o)\n\n    def visit_newtype_expr(self, o: NewTypeExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_newtype_expr(o)\n\n    def visit_await_expr(self, o: AwaitExpr, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_await_expr(o)\n\n    # Patterns\n\n    def visit_as_pattern(self, o: AsPattern, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_as_pattern(o)\n\n    def visit_or_pattern(self, o: OrPattern, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_or_pattern(o)\n\n    def visit_value_pattern(self, o: ValuePattern, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_value_pattern(o)\n\n    def visit_singleton_pattern(self, o: SingletonPattern, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_singleton_pattern(o)\n\n    def visit_sequence_pattern(self, o: SequencePattern, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_sequence_pattern(o)\n\n    def visit_starred_pattern(self, o: StarredPattern, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_starred_pattern(o)\n\n    def visit_mapping_pattern(self, o: MappingPattern, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_mapping_pattern(o)\n\n    def visit_class_pattern(self, o: ClassPattern, /) -> None:\n        if not self.visit(o):\n            return\n        super().visit_class_pattern(o)\n\n\nclass ReturnSeeker(TraverserVisitor):\n    def __init__(self) -> None:\n        self.found = False\n\n    def visit_return_stmt(self, o: ReturnStmt) -> None:\n        if o.expr is None or isinstance(o.expr, NameExpr) and o.expr.name == \"None\":\n            return\n        self.found = True\n\n\ndef has_return_statement(fdef: FuncBase) -> bool:\n    \"\"\"Find if a function has a non-trivial return statement.\n\n    Plain 'return' and 'return None' don't count.\n    \"\"\"\n    seeker = ReturnSeeker()\n    fdef.accept(seeker)\n    return seeker.found\n\n\nclass NameAndMemberCollector(TraverserVisitor):\n    def __init__(self) -> None:\n        super().__init__()\n        self.name_exprs: list[NameExpr] = []\n        self.member_exprs: list[MemberExpr] = []\n\n    def visit_name_expr(self, o: NameExpr, /) -> None:\n        self.name_exprs.append(o)\n        super().visit_name_expr(o)\n\n    def visit_member_expr(self, o: MemberExpr, /) -> None:\n        self.member_exprs.append(o)\n        super().visit_member_expr(o)\n\n\ndef all_name_and_member_expressions(node: Expression) -> tuple[list[NameExpr], list[MemberExpr]]:\n    v = NameAndMemberCollector()\n    node.accept(v)\n    return (v.name_exprs, v.member_exprs)\n\n\nclass StringSeeker(TraverserVisitor):\n    def __init__(self) -> None:\n        self.found = False\n\n    def visit_str_expr(self, o: StrExpr, /) -> None:\n        self.found = True\n\n\ndef has_str_expression(node: Expression) -> bool:\n    v = StringSeeker()\n    node.accept(v)\n    return v.found\n\n\nclass FuncCollectorBase(TraverserVisitor):\n    def __init__(self) -> None:\n        self.inside_func = False\n\n    def visit_func_def(self, defn: FuncDef) -> None:\n        if not self.inside_func:\n            self.inside_func = True\n            super().visit_func_def(defn)\n            self.inside_func = False\n\n\nclass YieldSeeker(FuncCollectorBase):\n    def __init__(self) -> None:\n        super().__init__()\n        self.found = False\n\n    def visit_yield_expr(self, o: YieldExpr) -> None:\n        self.found = True\n\n\ndef has_yield_expression(fdef: FuncBase) -> bool:\n    seeker = YieldSeeker()\n    fdef.accept(seeker)\n    return seeker.found\n\n\nclass YieldFromSeeker(FuncCollectorBase):\n    def __init__(self) -> None:\n        super().__init__()\n        self.found = False\n\n    def visit_yield_from_expr(self, o: YieldFromExpr) -> None:\n        self.found = True\n\n\ndef has_yield_from_expression(fdef: FuncBase) -> bool:\n    seeker = YieldFromSeeker()\n    fdef.accept(seeker)\n    return seeker.found\n\n\nclass AwaitSeeker(TraverserVisitor):\n    def __init__(self) -> None:\n        super().__init__()\n        self.found = False\n\n    def visit_await_expr(self, o: AwaitExpr) -> None:\n        self.found = True\n\n\ndef has_await_expression(expr: Expression) -> bool:\n    seeker = AwaitSeeker()\n    expr.accept(seeker)\n    return seeker.found\n\n\nclass ReturnCollector(FuncCollectorBase):\n    def __init__(self) -> None:\n        super().__init__()\n        self.return_statements: list[ReturnStmt] = []\n\n    def visit_return_stmt(self, stmt: ReturnStmt) -> None:\n        self.return_statements.append(stmt)\n\n\ndef all_return_statements(node: Node) -> list[ReturnStmt]:\n    v = ReturnCollector()\n    node.accept(v)\n    return v.return_statements\n\n\nclass YieldCollector(FuncCollectorBase):\n    def __init__(self) -> None:\n        super().__init__()\n        self.in_assignment = False\n        self.yield_expressions: list[tuple[YieldExpr, bool]] = []\n\n    def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None:\n        self.in_assignment = True\n        super().visit_assignment_stmt(stmt)\n        self.in_assignment = False\n\n    def visit_yield_expr(self, expr: YieldExpr) -> None:\n        self.yield_expressions.append((expr, self.in_assignment))\n\n\ndef all_yield_expressions(node: Node) -> list[tuple[YieldExpr, bool]]:\n    v = YieldCollector()\n    node.accept(v)\n    return v.yield_expressions\n\n\nclass YieldFromCollector(FuncCollectorBase):\n    def __init__(self) -> None:\n        super().__init__()\n        self.in_assignment = False\n        self.yield_from_expressions: list[tuple[YieldFromExpr, bool]] = []\n\n    def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None:\n        self.in_assignment = True\n        super().visit_assignment_stmt(stmt)\n        self.in_assignment = False\n\n    def visit_yield_from_expr(self, expr: YieldFromExpr) -> None:\n        self.yield_from_expressions.append((expr, self.in_assignment))\n"
  },
  {
    "path": "mypy/treetransform.py",
    "content": "\"\"\"Base visitor that implements an identity AST transform.\n\nSubclass TransformVisitor to perform non-trivial transformations.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable\nfrom typing import cast\n\nfrom mypy.nodes import (\n    GDEF,\n    REVEAL_TYPE,\n    Argument,\n    AssertStmt,\n    AssertTypeExpr,\n    AssignmentExpr,\n    AssignmentStmt,\n    AwaitExpr,\n    Block,\n    BreakStmt,\n    BytesExpr,\n    CallExpr,\n    CastExpr,\n    ClassDef,\n    ComparisonExpr,\n    ComplexExpr,\n    ConditionalExpr,\n    ContinueStmt,\n    Decorator,\n    DelStmt,\n    DictExpr,\n    DictionaryComprehension,\n    EllipsisExpr,\n    EnumCallExpr,\n    Expression,\n    ExpressionStmt,\n    FloatExpr,\n    ForStmt,\n    FuncDef,\n    FuncItem,\n    GeneratorExpr,\n    GlobalDecl,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    MatchStmt,\n    MemberExpr,\n    MypyFile,\n    NamedTupleExpr,\n    NameExpr,\n    NewTypeExpr,\n    Node,\n    NonlocalDecl,\n    OperatorAssignmentStmt,\n    OpExpr,\n    OverloadedFuncDef,\n    OverloadPart,\n    ParamSpecExpr,\n    PassStmt,\n    PromoteExpr,\n    RaiseStmt,\n    RefExpr,\n    ReturnStmt,\n    RevealExpr,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    Statement,\n    StrExpr,\n    SuperExpr,\n    SymbolTable,\n    TemplateStrExpr,\n    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAliasExpr,\n    TypeApplication,\n    TypedDictExpr,\n    TypeFormExpr,\n    TypeVarExpr,\n    TypeVarTupleExpr,\n    UnaryExpr,\n    Var,\n    WhileStmt,\n    WithStmt,\n    YieldExpr,\n    YieldFromExpr,\n)\nfrom mypy.patterns import (\n    AsPattern,\n    ClassPattern,\n    MappingPattern,\n    OrPattern,\n    Pattern,\n    SequencePattern,\n    SingletonPattern,\n    StarredPattern,\n    ValuePattern,\n)\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.types import FunctionLike, ProperType, Type\nfrom mypy.util import replace_object_state\nfrom mypy.visitor import NodeVisitor\n\n\nclass TransformVisitor(NodeVisitor[Node]):\n    \"\"\"Transform a semantically analyzed AST (or subtree) to an identical copy.\n\n    Use the node() method to transform an AST node.\n\n    Subclass to perform a non-identity transform.\n\n    Notes:\n\n     * This can only be used to transform functions or classes, not top-level\n       statements, and/or modules as a whole.\n     * Do not duplicate TypeInfo nodes. This would generally not be desirable.\n     * Only update some name binding cross-references, but only those that\n       refer to Var, Decorator or FuncDef nodes, not those targeting ClassDef or\n       TypeInfo nodes.\n     * Types are not transformed, but you can override type() to also perform\n       type transformation.\n\n    TODO nested classes and functions have not been tested well enough\n    \"\"\"\n\n    def __init__(self) -> None:\n        # To simplify testing, set this flag to True if you want to transform\n        # all statements in a file (this is prohibited in normal mode).\n        self.test_only = False\n        # There may be multiple references to a Var node. Keep track of\n        # Var translations using a dictionary.\n        self.var_map: dict[Var, Var] = {}\n        # These are uninitialized placeholder nodes used temporarily for nested\n        # functions while we are transforming a top-level function. This maps an\n        # untransformed node to a placeholder (which will later become the\n        # transformed node).\n        self.func_placeholder_map: dict[FuncDef, FuncDef] = {}\n\n    def visit_mypy_file(self, node: MypyFile) -> MypyFile:\n        assert self.test_only, \"This visitor should not be used for whole files.\"\n        # NOTE: The 'names' and 'imports' instance variables will be empty!\n        ignored_lines = {line: codes.copy() for line, codes in node.ignored_lines.items()}\n        new = MypyFile(self.statements(node.defs), [], node.is_bom, ignored_lines=ignored_lines)\n        new._fullname = node._fullname\n        new.path = node.path\n        new.names = SymbolTable()\n        return new\n\n    def visit_import(self, node: Import) -> Import:\n        return Import(node.ids.copy())\n\n    def visit_import_from(self, node: ImportFrom) -> ImportFrom:\n        return ImportFrom(node.id, node.relative, node.names.copy())\n\n    def visit_import_all(self, node: ImportAll) -> ImportAll:\n        return ImportAll(node.id, node.relative)\n\n    def copy_argument(self, argument: Argument) -> Argument:\n        arg = Argument(\n            self.visit_var(argument.variable),\n            argument.type_annotation,\n            argument.initializer,\n            argument.kind,\n        )\n\n        # Refresh lines of the inner things\n        arg.set_line(argument)\n\n        return arg\n\n    def visit_func_def(self, node: FuncDef) -> FuncDef:\n        # Note that a FuncDef must be transformed to a FuncDef.\n\n        # These contortions are needed to handle the case of recursive\n        # references inside the function being transformed.\n        # Set up placeholder nodes for references within this function\n        # to other functions defined inside it.\n        # Don't create an entry for this function itself though,\n        # since we want self-references to point to the original\n        # function if this is the top-level node we are transforming.\n        init = FuncMapInitializer(self)\n        for stmt in node.body.body:\n            stmt.accept(init)\n\n        new = FuncDef(\n            node.name,\n            [self.copy_argument(arg) for arg in node.arguments],\n            self.block(node.body),\n            cast(FunctionLike | None, self.optional_type(node.type)),\n        )\n\n        self.copy_function_attributes(new, node)\n\n        new._fullname = node._fullname\n        new.is_decorated = node.is_decorated\n        new.is_conditional = node.is_conditional\n        new.abstract_status = node.abstract_status\n        new.is_static = node.is_static\n        new.is_class = node.is_class\n        new.is_property = node.is_property\n        new.is_final = node.is_final\n        new.original_def = node.original_def\n\n        if node in self.func_placeholder_map:\n            # There is a placeholder definition for this function. Replace\n            # the attributes of the placeholder with those form the transformed\n            # function. We know that the classes will be identical (otherwise\n            # this wouldn't work).\n            result = self.func_placeholder_map[node]\n            replace_object_state(result, new)\n            return result\n        else:\n            return new\n\n    def visit_lambda_expr(self, node: LambdaExpr) -> LambdaExpr:\n        new = LambdaExpr(\n            [self.copy_argument(arg) for arg in node.arguments],\n            self.block(node.body),\n            cast(FunctionLike | None, self.optional_type(node.type)),\n        )\n        self.copy_function_attributes(new, node)\n        return new\n\n    def copy_function_attributes(self, new: FuncItem, original: FuncItem) -> None:\n        new.info = original.info\n        new.min_args = original.min_args\n        new.max_pos = original.max_pos\n        new.is_overload = original.is_overload\n        new.is_generator = original.is_generator\n        new.is_coroutine = original.is_coroutine\n        new.is_async_generator = original.is_async_generator\n        new.is_awaitable_coroutine = original.is_awaitable_coroutine\n        new.line = original.line\n\n    def visit_overloaded_func_def(self, node: OverloadedFuncDef) -> OverloadedFuncDef:\n        items = [cast(OverloadPart, item.accept(self)) for item in node.items]\n        for newitem, olditem in zip(items, node.items):\n            newitem.line = olditem.line\n        new = OverloadedFuncDef(items)\n        new._fullname = node._fullname\n        new_type = self.optional_type(node.type)\n        assert isinstance(new_type, ProperType)\n        new.type = new_type\n        new.info = node.info\n        new.is_static = node.is_static\n        new.is_class = node.is_class\n        new.is_property = node.is_property\n        new.is_final = node.is_final\n        if node.impl:\n            new.impl = cast(OverloadPart, node.impl.accept(self))\n        return new\n\n    def visit_class_def(self, node: ClassDef) -> ClassDef:\n        keywords = [(key, self.expr(value)) for key, value in node.keywords.items()]\n        new = ClassDef(\n            node.name,\n            self.block(node.defs),\n            node.type_vars,\n            self.expressions(node.base_type_exprs),\n            self.optional_expr(node.metaclass),\n            keywords,\n        )\n        new.fullname = node.fullname\n        new.info = node.info\n        new.decorators = [self.expr(decorator) for decorator in node.decorators]\n        return new\n\n    def visit_global_decl(self, node: GlobalDecl) -> GlobalDecl:\n        return GlobalDecl(node.names.copy())\n\n    def visit_nonlocal_decl(self, node: NonlocalDecl) -> NonlocalDecl:\n        return NonlocalDecl(node.names.copy())\n\n    def visit_block(self, node: Block) -> Block:\n        return Block(self.statements(node.body), is_unreachable=node.is_unreachable)\n\n    def visit_decorator(self, node: Decorator) -> Decorator:\n        # Note that a Decorator must be transformed to a Decorator.\n        func = self.visit_func_def(node.func)\n        func.line = node.func.line\n        new = Decorator(func, self.expressions(node.decorators), self.visit_var(node.var))\n        new.is_overload = node.is_overload\n        return new\n\n    def visit_var(self, node: Var) -> Var:\n        # Note that a Var must be transformed to a Var.\n        if node in self.var_map:\n            return self.var_map[node]\n        new = Var(node.name, self.optional_type(node.type))\n        new.line = node.line\n        new._fullname = node._fullname\n        new.info = node.info\n        new.is_self = node.is_self\n        new.is_ready = node.is_ready\n        new.is_initialized_in_class = node.is_initialized_in_class\n        new.is_staticmethod = node.is_staticmethod\n        new.is_classmethod = node.is_classmethod\n        new.is_property = node.is_property\n        new.is_final = node.is_final\n        new.final_value = node.final_value\n        new.final_unset_in_class = node.final_unset_in_class\n        new.final_set_in_init = node.final_set_in_init\n        new.set_line(node)\n        self.var_map[node] = new\n        return new\n\n    def visit_expression_stmt(self, node: ExpressionStmt) -> ExpressionStmt:\n        return ExpressionStmt(self.expr(node.expr))\n\n    def visit_assignment_stmt(self, node: AssignmentStmt) -> AssignmentStmt:\n        return self.duplicate_assignment(node)\n\n    def duplicate_assignment(self, node: AssignmentStmt) -> AssignmentStmt:\n        new = AssignmentStmt(\n            self.expressions(node.lvalues),\n            self.expr(node.rvalue),\n            self.optional_type(node.unanalyzed_type),\n        )\n        new.line = node.line\n        new.is_final_def = node.is_final_def\n        new.type = self.optional_type(node.type)\n        return new\n\n    def visit_operator_assignment_stmt(\n        self, node: OperatorAssignmentStmt\n    ) -> OperatorAssignmentStmt:\n        return OperatorAssignmentStmt(node.op, self.expr(node.lvalue), self.expr(node.rvalue))\n\n    def visit_while_stmt(self, node: WhileStmt) -> WhileStmt:\n        return WhileStmt(\n            self.expr(node.expr), self.block(node.body), self.optional_block(node.else_body)\n        )\n\n    def visit_for_stmt(self, node: ForStmt) -> ForStmt:\n        new = ForStmt(\n            self.expr(node.index),\n            self.expr(node.expr),\n            self.block(node.body),\n            self.optional_block(node.else_body),\n            self.optional_type(node.unanalyzed_index_type),\n        )\n        new.is_async = node.is_async\n        new.index_type = self.optional_type(node.index_type)\n        return new\n\n    def visit_return_stmt(self, node: ReturnStmt) -> ReturnStmt:\n        return ReturnStmt(self.optional_expr(node.expr))\n\n    def visit_assert_stmt(self, node: AssertStmt) -> AssertStmt:\n        return AssertStmt(self.expr(node.expr), self.optional_expr(node.msg))\n\n    def visit_del_stmt(self, node: DelStmt) -> DelStmt:\n        return DelStmt(self.expr(node.expr))\n\n    def visit_if_stmt(self, node: IfStmt) -> IfStmt:\n        return IfStmt(\n            self.expressions(node.expr),\n            self.blocks(node.body),\n            self.optional_block(node.else_body),\n        )\n\n    def visit_break_stmt(self, node: BreakStmt) -> BreakStmt:\n        return BreakStmt()\n\n    def visit_continue_stmt(self, node: ContinueStmt) -> ContinueStmt:\n        return ContinueStmt()\n\n    def visit_pass_stmt(self, node: PassStmt) -> PassStmt:\n        return PassStmt()\n\n    def visit_raise_stmt(self, node: RaiseStmt) -> RaiseStmt:\n        return RaiseStmt(self.optional_expr(node.expr), self.optional_expr(node.from_expr))\n\n    def visit_try_stmt(self, node: TryStmt) -> TryStmt:\n        new = TryStmt(\n            self.block(node.body),\n            self.optional_names(node.vars),\n            self.optional_expressions(node.types),\n            self.blocks(node.handlers),\n            self.optional_block(node.else_body),\n            self.optional_block(node.finally_body),\n        )\n        new.is_star = node.is_star\n        return new\n\n    def visit_with_stmt(self, node: WithStmt) -> WithStmt:\n        new = WithStmt(\n            self.expressions(node.expr),\n            self.optional_expressions(node.target),\n            self.block(node.body),\n            self.optional_type(node.unanalyzed_type),\n        )\n        new.is_async = node.is_async\n        new.analyzed_types = [self.type(typ) for typ in node.analyzed_types]\n        return new\n\n    def visit_as_pattern(self, p: AsPattern) -> AsPattern:\n        return AsPattern(\n            pattern=self.pattern(p.pattern) if p.pattern is not None else None,\n            name=self.duplicate_name(p.name) if p.name is not None else None,\n        )\n\n    def visit_or_pattern(self, p: OrPattern) -> OrPattern:\n        return OrPattern([self.pattern(pat) for pat in p.patterns])\n\n    def visit_value_pattern(self, p: ValuePattern) -> ValuePattern:\n        return ValuePattern(self.expr(p.expr))\n\n    def visit_singleton_pattern(self, p: SingletonPattern) -> SingletonPattern:\n        return SingletonPattern(p.value)\n\n    def visit_sequence_pattern(self, p: SequencePattern) -> SequencePattern:\n        return SequencePattern([self.pattern(pat) for pat in p.patterns])\n\n    def visit_starred_pattern(self, p: StarredPattern) -> StarredPattern:\n        return StarredPattern(self.duplicate_name(p.capture) if p.capture is not None else None)\n\n    def visit_mapping_pattern(self, p: MappingPattern) -> MappingPattern:\n        return MappingPattern(\n            keys=[self.expr(expr) for expr in p.keys],\n            values=[self.pattern(pat) for pat in p.values],\n            rest=self.duplicate_name(p.rest) if p.rest is not None else None,\n        )\n\n    def visit_class_pattern(self, p: ClassPattern) -> ClassPattern:\n        class_ref = p.class_ref.accept(self)\n        assert isinstance(class_ref, RefExpr)\n        return ClassPattern(\n            class_ref=class_ref,\n            positionals=[self.pattern(pat) for pat in p.positionals],\n            keyword_keys=list(p.keyword_keys),\n            keyword_values=[self.pattern(pat) for pat in p.keyword_values],\n        )\n\n    def visit_match_stmt(self, o: MatchStmt) -> MatchStmt:\n        return MatchStmt(\n            subject=self.expr(o.subject),\n            patterns=[self.pattern(p) for p in o.patterns],\n            guards=self.optional_expressions(o.guards),\n            bodies=self.blocks(o.bodies),\n        )\n\n    def visit_star_expr(self, node: StarExpr) -> StarExpr:\n        return StarExpr(node.expr)\n\n    def visit_int_expr(self, node: IntExpr) -> IntExpr:\n        return IntExpr(node.value)\n\n    def visit_str_expr(self, node: StrExpr) -> StrExpr:\n        return StrExpr(node.value)\n\n    def visit_bytes_expr(self, node: BytesExpr) -> BytesExpr:\n        return BytesExpr(node.value)\n\n    def visit_float_expr(self, node: FloatExpr) -> FloatExpr:\n        return FloatExpr(node.value)\n\n    def visit_complex_expr(self, node: ComplexExpr) -> ComplexExpr:\n        return ComplexExpr(node.value)\n\n    def visit_ellipsis(self, node: EllipsisExpr) -> EllipsisExpr:\n        return EllipsisExpr()\n\n    def visit_name_expr(self, node: NameExpr) -> NameExpr:\n        return self.duplicate_name(node)\n\n    def duplicate_name(self, node: NameExpr) -> NameExpr:\n        # This method is used when the transform result must be a NameExpr.\n        # visit_name_expr() is used when there is no such restriction.\n        new = NameExpr(node.name)\n        self.copy_ref(new, node)\n        new.is_special_form = node.is_special_form\n        return new\n\n    def visit_member_expr(self, node: MemberExpr) -> MemberExpr:\n        member = MemberExpr(self.expr(node.expr), node.name)\n        if node.def_var:\n            # This refers to an attribute and we don't transform attributes by default,\n            # just normal variables.\n            member.def_var = node.def_var\n        self.copy_ref(member, node)\n        return member\n\n    def copy_ref(self, new: RefExpr, original: RefExpr) -> None:\n        new.kind = original.kind\n        new.fullname = original.fullname\n        target = original.node\n        if isinstance(target, Var):\n            # Do not transform references to global variables. See\n            # testGenericFunctionAliasExpand for an example where this is important.\n            if original.kind != GDEF:\n                target = self.visit_var(target)\n        elif isinstance(target, Decorator):\n            target = self.visit_var(target.var)\n        elif isinstance(target, FuncDef):\n            # Use a placeholder node for the function if it exists.\n            target = self.func_placeholder_map.get(target, target)\n        new.node = target\n        new.is_new_def = original.is_new_def\n        new.is_inferred_def = original.is_inferred_def\n\n    def visit_yield_from_expr(self, node: YieldFromExpr) -> YieldFromExpr:\n        return YieldFromExpr(self.expr(node.expr))\n\n    def visit_yield_expr(self, node: YieldExpr) -> YieldExpr:\n        return YieldExpr(self.optional_expr(node.expr))\n\n    def visit_await_expr(self, node: AwaitExpr) -> AwaitExpr:\n        return AwaitExpr(self.expr(node.expr))\n\n    def visit_call_expr(self, node: CallExpr) -> CallExpr:\n        return CallExpr(\n            self.expr(node.callee),\n            self.expressions(node.args),\n            node.arg_kinds.copy(),\n            node.arg_names.copy(),\n            self.optional_expr(node.analyzed),\n        )\n\n    def visit_op_expr(self, node: OpExpr) -> OpExpr:\n        new = OpExpr(\n            node.op,\n            self.expr(node.left),\n            self.expr(node.right),\n            cast(TypeAliasExpr | None, self.optional_expr(node.analyzed)),\n        )\n        new.method_type = self.optional_type(node.method_type)\n        return new\n\n    def visit_comparison_expr(self, node: ComparisonExpr) -> ComparisonExpr:\n        new = ComparisonExpr(node.operators, self.expressions(node.operands))\n        new.method_types = [self.optional_type(t) for t in node.method_types]\n        return new\n\n    def visit_cast_expr(self, node: CastExpr) -> CastExpr:\n        return CastExpr(self.expr(node.expr), self.type(node.type))\n\n    def visit_type_form_expr(self, node: TypeFormExpr) -> TypeFormExpr:\n        return TypeFormExpr(self.type(node.type))\n\n    def visit_assert_type_expr(self, node: AssertTypeExpr) -> AssertTypeExpr:\n        return AssertTypeExpr(self.expr(node.expr), self.type(node.type))\n\n    def visit_reveal_expr(self, node: RevealExpr) -> RevealExpr:\n        if node.kind == REVEAL_TYPE:\n            assert node.expr is not None\n            return RevealExpr(kind=REVEAL_TYPE, expr=self.expr(node.expr))\n        else:\n            # Reveal locals expressions don't have any sub expressions\n            return node\n\n    def visit_super_expr(self, node: SuperExpr) -> SuperExpr:\n        call = self.expr(node.call)\n        assert isinstance(call, CallExpr)\n        new = SuperExpr(node.name, call)\n        new.info = node.info\n        return new\n\n    def visit_assignment_expr(self, node: AssignmentExpr) -> AssignmentExpr:\n        return AssignmentExpr(self.duplicate_name(node.target), self.expr(node.value))\n\n    def visit_unary_expr(self, node: UnaryExpr) -> UnaryExpr:\n        new = UnaryExpr(node.op, self.expr(node.expr))\n        new.method_type = self.optional_type(node.method_type)\n        return new\n\n    def visit_list_expr(self, node: ListExpr) -> ListExpr:\n        return ListExpr(self.expressions(node.items))\n\n    def visit_dict_expr(self, node: DictExpr) -> DictExpr:\n        return DictExpr(\n            [(self.expr(key) if key else None, self.expr(value)) for key, value in node.items]\n        )\n\n    def visit_template_str_expr(self, node: TemplateStrExpr) -> TemplateStrExpr:\n        items: list[Expression | tuple[Expression, str, str | None, Expression | None]] = []\n        for item in node.items:\n            if isinstance(item, tuple):\n                value, source, conversion, format_spec = item\n                items.append(\n                    (self.expr(value), source, conversion, self.optional_expr(format_spec))\n                )\n            else:\n                items.append(self.expr(item))\n        return TemplateStrExpr(items)\n\n    def visit_tuple_expr(self, node: TupleExpr) -> TupleExpr:\n        return TupleExpr(self.expressions(node.items))\n\n    def visit_set_expr(self, node: SetExpr) -> SetExpr:\n        return SetExpr(self.expressions(node.items))\n\n    def visit_index_expr(self, node: IndexExpr) -> IndexExpr:\n        new = IndexExpr(self.expr(node.base), self.expr(node.index))\n        if node.method_type:\n            new.method_type = self.type(node.method_type)\n        if node.analyzed:\n            if isinstance(node.analyzed, TypeApplication):\n                new.analyzed = self.visit_type_application(node.analyzed)\n            else:\n                new.analyzed = self.visit_type_alias_expr(node.analyzed)\n            new.analyzed.set_line(node.analyzed)\n        return new\n\n    def visit_type_application(self, node: TypeApplication) -> TypeApplication:\n        return TypeApplication(self.expr(node.expr), self.types(node.types))\n\n    def visit_list_comprehension(self, node: ListComprehension) -> ListComprehension:\n        generator = self.duplicate_generator(node.generator)\n        generator.set_line(node.generator)\n        return ListComprehension(generator)\n\n    def visit_set_comprehension(self, node: SetComprehension) -> SetComprehension:\n        generator = self.duplicate_generator(node.generator)\n        generator.set_line(node.generator)\n        return SetComprehension(generator)\n\n    def visit_dictionary_comprehension(\n        self, node: DictionaryComprehension\n    ) -> DictionaryComprehension:\n        return DictionaryComprehension(\n            self.expr(node.key),\n            self.expr(node.value),\n            [self.expr(index) for index in node.indices],\n            [self.expr(s) for s in node.sequences],\n            [[self.expr(cond) for cond in conditions] for conditions in node.condlists],\n            node.is_async,\n        )\n\n    def visit_generator_expr(self, node: GeneratorExpr) -> GeneratorExpr:\n        return self.duplicate_generator(node)\n\n    def duplicate_generator(self, node: GeneratorExpr) -> GeneratorExpr:\n        return GeneratorExpr(\n            self.expr(node.left_expr),\n            [self.expr(index) for index in node.indices],\n            [self.expr(s) for s in node.sequences],\n            [[self.expr(cond) for cond in conditions] for conditions in node.condlists],\n            node.is_async,\n        )\n\n    def visit_slice_expr(self, node: SliceExpr) -> SliceExpr:\n        return SliceExpr(\n            self.optional_expr(node.begin_index),\n            self.optional_expr(node.end_index),\n            self.optional_expr(node.stride),\n        )\n\n    def visit_conditional_expr(self, node: ConditionalExpr) -> ConditionalExpr:\n        return ConditionalExpr(\n            self.expr(node.cond), self.expr(node.if_expr), self.expr(node.else_expr)\n        )\n\n    def visit_type_var_expr(self, node: TypeVarExpr) -> TypeVarExpr:\n        return TypeVarExpr(\n            node.name,\n            node.fullname,\n            self.types(node.values),\n            self.type(node.upper_bound),\n            self.type(node.default),\n            variance=node.variance,\n        )\n\n    def visit_paramspec_expr(self, node: ParamSpecExpr) -> ParamSpecExpr:\n        return ParamSpecExpr(\n            node.name,\n            node.fullname,\n            self.type(node.upper_bound),\n            self.type(node.default),\n            variance=node.variance,\n        )\n\n    def visit_type_var_tuple_expr(self, node: TypeVarTupleExpr) -> TypeVarTupleExpr:\n        return TypeVarTupleExpr(\n            node.name,\n            node.fullname,\n            self.type(node.upper_bound),\n            node.tuple_fallback,\n            self.type(node.default),\n            variance=node.variance,\n        )\n\n    def visit_type_alias_expr(self, node: TypeAliasExpr) -> TypeAliasExpr:\n        return TypeAliasExpr(node.node)\n\n    def visit_newtype_expr(self, node: NewTypeExpr) -> NewTypeExpr:\n        res = NewTypeExpr(node.name, node.old_type, line=node.line, column=node.column)\n        res.info = node.info\n        return res\n\n    def visit_namedtuple_expr(self, node: NamedTupleExpr) -> NamedTupleExpr:\n        return NamedTupleExpr(node.info)\n\n    def visit_enum_call_expr(self, node: EnumCallExpr) -> EnumCallExpr:\n        return EnumCallExpr(node.info, node.items, node.values)\n\n    def visit_typeddict_expr(self, node: TypedDictExpr) -> Node:\n        return TypedDictExpr(node.info)\n\n    def visit__promote_expr(self, node: PromoteExpr) -> PromoteExpr:\n        return PromoteExpr(node.type)\n\n    def visit_temp_node(self, node: TempNode) -> TempNode:\n        return TempNode(self.type(node.type))\n\n    def node(self, node: Node) -> Node:\n        new = node.accept(self)\n        new.set_line(node)\n        return new\n\n    def mypyfile(self, node: MypyFile) -> MypyFile:\n        new = node.accept(self)\n        assert isinstance(new, MypyFile)\n        new.set_line(node)\n        return new\n\n    def expr(self, expr: Expression) -> Expression:\n        new = expr.accept(self)\n        assert isinstance(new, Expression)\n        new.set_line(expr)\n        return new\n\n    def stmt(self, stmt: Statement) -> Statement:\n        new = stmt.accept(self)\n        assert isinstance(new, Statement)\n        new.set_line(stmt)\n        return new\n\n    def pattern(self, pattern: Pattern) -> Pattern:\n        new = pattern.accept(self)\n        assert isinstance(new, Pattern)\n        new.set_line(pattern)\n        return new\n\n    # Helpers\n    #\n    # All the node helpers also propagate line numbers.\n\n    def optional_expr(self, expr: Expression | None) -> Expression | None:\n        if expr:\n            return self.expr(expr)\n        else:\n            return None\n\n    def block(self, block: Block) -> Block:\n        new = self.visit_block(block)\n        new.line = block.line\n        return new\n\n    def optional_block(self, block: Block | None) -> Block | None:\n        if block:\n            return self.block(block)\n        else:\n            return None\n\n    def statements(self, statements: list[Statement]) -> list[Statement]:\n        return [self.stmt(stmt) for stmt in statements]\n\n    def expressions(self, expressions: list[Expression]) -> list[Expression]:\n        return [self.expr(expr) for expr in expressions]\n\n    def optional_expressions(\n        self, expressions: Iterable[Expression | None]\n    ) -> list[Expression | None]:\n        return [self.optional_expr(expr) for expr in expressions]\n\n    def blocks(self, blocks: list[Block]) -> list[Block]:\n        return [self.block(block) for block in blocks]\n\n    def names(self, names: list[NameExpr]) -> list[NameExpr]:\n        return [self.duplicate_name(name) for name in names]\n\n    def optional_names(self, names: Iterable[NameExpr | None]) -> list[NameExpr | None]:\n        result: list[NameExpr | None] = []\n        for name in names:\n            if name:\n                result.append(self.duplicate_name(name))\n            else:\n                result.append(None)\n        return result\n\n    def type(self, type: Type) -> Type:\n        # Override this method to transform types.\n        return type\n\n    def optional_type(self, type: Type | None) -> Type | None:\n        if type:\n            return self.type(type)\n        else:\n            return None\n\n    def types(self, types: list[Type]) -> list[Type]:\n        return [self.type(type) for type in types]\n\n\nclass FuncMapInitializer(TraverserVisitor):\n    \"\"\"This traverser creates mappings from nested FuncDefs to placeholder FuncDefs.\n\n    The placeholders will later be replaced with transformed nodes.\n    \"\"\"\n\n    def __init__(self, transformer: TransformVisitor) -> None:\n        self.transformer = transformer\n\n    def visit_func_def(self, node: FuncDef) -> None:\n        if node not in self.transformer.func_placeholder_map:\n            # Haven't seen this FuncDef before, so create a placeholder node.\n            self.transformer.func_placeholder_map[node] = FuncDef(\n                node.name, node.arguments, node.body, None\n            )\n        super().visit_func_def(node)\n"
  },
  {
    "path": "mypy/tvar_scope.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Callable\nfrom typing import TypeAlias as _TypeAlias\n\nfrom mypy.nodes import (\n    Context,\n    ParamSpecExpr,\n    SymbolTableNode,\n    TypeVarExpr,\n    TypeVarLikeExpr,\n    TypeVarTupleExpr,\n)\nfrom mypy.types import (\n    AnyType,\n    ParamSpecFlavor,\n    ParamSpecType,\n    TrivialSyntheticTypeTranslator,\n    Type,\n    TypeAliasType,\n    TypeOfAny,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n)\n\nFailFunc: _TypeAlias = Callable[[str, Context], None]\n\n\nclass TypeVarLikeDefaultFixer(TrivialSyntheticTypeTranslator):\n    \"\"\"Set namespace for all TypeVarLikeTypes types.\"\"\"\n\n    def __init__(\n        self,\n        scope: TypeVarLikeScope,\n        fail_func: FailFunc,\n        source_tv: TypeVarLikeExpr,\n        context: Context,\n    ) -> None:\n        self.scope = scope\n        self.fail_func = fail_func\n        self.source_tv = source_tv\n        self.context = context\n        super().__init__()\n\n    def visit_type_var(self, t: TypeVarType) -> Type:\n        existing = self.scope.get_binding(t.fullname)\n        if existing is None:\n            self._report_unbound_tvar(t)\n            return AnyType(TypeOfAny.from_error)\n        return existing\n\n    def visit_param_spec(self, t: ParamSpecType) -> Type:\n        existing = self.scope.get_binding(t.fullname)\n        if existing is None:\n            self._report_unbound_tvar(t)\n            return AnyType(TypeOfAny.from_error)\n        return existing\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type:\n        existing = self.scope.get_binding(t.fullname)\n        if existing is None:\n            self._report_unbound_tvar(t)\n            return AnyType(TypeOfAny.from_error)\n        return existing\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        return t\n\n    def _report_unbound_tvar(self, tvar: TypeVarLikeType) -> None:\n        self.fail_func(\n            f\"Type variable {tvar.name} referenced in the default\"\n            f\" of {self.source_tv.name} is unbound\",\n            self.context,\n        )\n\n\nclass TypeVarLikeScope:\n    \"\"\"Scope that holds bindings for type variables and parameter specifications.\n\n    Node fullname -> TypeVarLikeType.\n    \"\"\"\n\n    def __init__(\n        self,\n        parent: TypeVarLikeScope | None = None,\n        is_class_scope: bool = False,\n        prohibited: TypeVarLikeScope | None = None,\n        namespace: str = \"\",\n    ) -> None:\n        \"\"\"Initializer for TypeVarLikeScope\n\n        Parameters:\n          parent: the outer scope for this scope\n          is_class_scope: True if this represents a generic class\n          prohibited: Type variables that aren't strictly in scope exactly,\n                      but can't be bound because they're part of an outer class's scope.\n        \"\"\"\n        self.scope: dict[str, TypeVarLikeType] = {}\n        self.parent = parent\n        self.func_id = 0\n        self.class_id = 0\n        self.is_class_scope = is_class_scope\n        self.prohibited = prohibited\n        self.namespace = namespace\n        if parent is not None:\n            self.func_id = parent.func_id\n            self.class_id = parent.class_id\n\n    def get_function_scope(self) -> TypeVarLikeScope | None:\n        \"\"\"Get the nearest parent that's a function scope, not a class scope\"\"\"\n        it: TypeVarLikeScope | None = self\n        while it is not None and it.is_class_scope:\n            it = it.parent\n        return it\n\n    def allow_binding(self, fullname: str) -> bool:\n        if fullname in self.scope:\n            return False\n        elif self.parent and not self.parent.allow_binding(fullname):\n            return False\n        elif self.prohibited and not self.prohibited.allow_binding(fullname):\n            return False\n        return True\n\n    def method_frame(self, namespace: str) -> TypeVarLikeScope:\n        \"\"\"A new scope frame for binding a method\"\"\"\n        return TypeVarLikeScope(self, False, None, namespace=namespace)\n\n    def class_frame(self, namespace: str) -> TypeVarLikeScope:\n        \"\"\"A new scope frame for binding a class. Prohibits *this* class's tvars\"\"\"\n        return TypeVarLikeScope(self.get_function_scope(), True, self, namespace=namespace)\n\n    def new_unique_func_id(self) -> TypeVarId:\n        \"\"\"Used by plugin-like code that needs to make synthetic generic functions.\"\"\"\n        self.func_id -= 1\n        return TypeVarId(self.func_id)\n\n    def bind_new(\n        self, name: str, tvar_expr: TypeVarLikeExpr, fail_func: FailFunc, context: Context\n    ) -> TypeVarLikeType:\n        if self.is_class_scope:\n            self.class_id += 1\n            i = self.class_id\n        else:\n            self.func_id -= 1\n            i = self.func_id\n        namespace = self.namespace\n\n        # Defaults may reference other type variables. That is only valid when the\n        # referenced variable is already in scope (textually precedes the definition we're\n        # processing now).\n        default = tvar_expr.default.accept(\n            TypeVarLikeDefaultFixer(\n                self, fail_func=fail_func, source_tv=tvar_expr, context=context\n            )\n        )\n\n        if isinstance(tvar_expr, TypeVarExpr):\n            tvar_def: TypeVarLikeType = TypeVarType(\n                name=name,\n                fullname=tvar_expr.fullname,\n                id=TypeVarId(i, namespace=namespace),\n                values=tvar_expr.values,\n                upper_bound=tvar_expr.upper_bound,\n                default=default,\n                variance=tvar_expr.variance,\n                line=tvar_expr.line,\n                column=tvar_expr.column,\n            )\n        elif isinstance(tvar_expr, ParamSpecExpr):\n            tvar_def = ParamSpecType(\n                name=name,\n                fullname=tvar_expr.fullname,\n                id=TypeVarId(i, namespace=namespace),\n                flavor=ParamSpecFlavor.BARE,\n                upper_bound=tvar_expr.upper_bound,\n                default=default,\n                line=tvar_expr.line,\n                column=tvar_expr.column,\n            )\n        elif isinstance(tvar_expr, TypeVarTupleExpr):\n            tvar_def = TypeVarTupleType(\n                name=name,\n                fullname=tvar_expr.fullname,\n                id=TypeVarId(i, namespace=namespace),\n                upper_bound=tvar_expr.upper_bound,\n                tuple_fallback=tvar_expr.tuple_fallback,\n                default=default,\n                line=tvar_expr.line,\n                column=tvar_expr.column,\n            )\n        else:\n            assert False\n        self.scope[tvar_expr.fullname] = tvar_def\n        return tvar_def\n\n    def bind_existing(self, tvar_def: TypeVarLikeType) -> None:\n        self.scope[tvar_def.fullname] = tvar_def\n\n    def get_binding(self, item: str | SymbolTableNode) -> TypeVarLikeType | None:\n        fullname = item.fullname if isinstance(item, SymbolTableNode) else item\n        assert fullname\n        if fullname in self.scope:\n            return self.scope[fullname]\n        elif self.parent is not None:\n            return self.parent.get_binding(fullname)\n        else:\n            return None\n\n    def __str__(self) -> str:\n        me = \", \".join(f\"{k}: {v.name}`{v.id}\" for k, v in self.scope.items())\n        if self.parent is None:\n            return me\n        return f\"{self.parent} <- {me}\"\n"
  },
  {
    "path": "mypy/type_visitor.py",
    "content": "\"\"\"Type visitor classes.\n\nThis module defines the type visitors that are intended to be\nsubclassed by other code.  They have been separated out into their own\nmodule to ease converting mypy to run under mypyc, since currently\nmypyc-extension classes can extend interpreted classes but not the\nother way around. Separating them out, then, allows us to compile\ntypes before we can compile everything that uses a TypeVisitor.\n\nThe visitors are all re-exported from mypy.types and that is how\nother modules refer to them.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections.abc import Iterable, Sequence\nfrom typing import Any, Final, Generic, TypeVar, cast\n\nfrom mypy_extensions import mypyc_attr, trait\n\nfrom mypy.types import (\n    AnyType,\n    CallableArgument,\n    CallableType,\n    DeletedType,\n    EllipsisType,\n    ErasedType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    PlaceholderType,\n    RawExpressionType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeList,\n    TypeType,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    get_proper_type,\n)\n\nT = TypeVar(\"T\", covariant=True)\n\n\n@trait\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass TypeVisitor(Generic[T]):\n    \"\"\"Visitor class for types (Type subclasses).\n\n    The parameter T is the return type of the visit methods.\n    \"\"\"\n\n    @abstractmethod\n    def visit_unbound_type(self, t: UnboundType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_any(self, t: AnyType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_none_type(self, t: NoneType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_uninhabited_type(self, t: UninhabitedType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_erased_type(self, t: ErasedType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_deleted_type(self, t: DeletedType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_type_var(self, t: TypeVarType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_param_spec(self, t: ParamSpecType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_parameters(self, t: Parameters, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_instance(self, t: Instance, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_callable_type(self, t: CallableType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_overloaded(self, t: Overloaded, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_tuple_type(self, t: TupleType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_typeddict_type(self, t: TypedDictType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_literal_type(self, t: LiteralType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_union_type(self, t: UnionType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_partial_type(self, t: PartialType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_type_type(self, t: TypeType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_type_alias_type(self, t: TypeAliasType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_unpack_type(self, t: UnpackType, /) -> T:\n        pass\n\n\n@trait\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass SyntheticTypeVisitor(TypeVisitor[T]):\n    \"\"\"A TypeVisitor that also knows how to visit synthetic AST constructs.\n\n    Not just real types.\n    \"\"\"\n\n    @abstractmethod\n    def visit_type_list(self, t: TypeList, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_callable_argument(self, t: CallableArgument, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_ellipsis_type(self, t: EllipsisType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_raw_expression_type(self, t: RawExpressionType, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_placeholder_type(self, t: PlaceholderType, /) -> T:\n        pass\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass TypeTranslator(TypeVisitor[Type]):\n    \"\"\"Identity type transformation.\n\n    Subclass this and override some methods to implement a non-trivial\n    transformation.\n\n    We cache the results of certain translations to avoid\n    massively expanding the sizes of types.\n    \"\"\"\n\n    def __init__(self, cache: dict[Type, Type] | None = None) -> None:\n        # For deduplication of results\n        self.cache = cache\n\n    def get_cached(self, t: Type) -> Type | None:\n        if self.cache is None:\n            return None\n        return self.cache.get(t)\n\n    def set_cached(self, orig: Type, new: Type) -> None:\n        if self.cache is None:\n            # Minor optimization: construct lazily\n            self.cache = {}\n        self.cache[orig] = new\n\n    def visit_unbound_type(self, t: UnboundType, /) -> Type:\n        return t\n\n    def visit_any(self, t: AnyType, /) -> Type:\n        return t\n\n    def visit_none_type(self, t: NoneType, /) -> Type:\n        return t\n\n    def visit_uninhabited_type(self, t: UninhabitedType, /) -> Type:\n        return t\n\n    def visit_erased_type(self, t: ErasedType, /) -> Type:\n        return t\n\n    def visit_deleted_type(self, t: DeletedType, /) -> Type:\n        return t\n\n    def visit_instance(self, t: Instance, /) -> Type:\n        last_known_value: LiteralType | None = None\n        if t.last_known_value is not None:\n            raw_last_known_value = t.last_known_value.accept(self)\n            assert isinstance(raw_last_known_value, LiteralType)  # type: ignore[misc]\n            last_known_value = raw_last_known_value\n        return Instance(\n            typ=t.type,\n            args=self.translate_type_tuple(t.args),\n            line=t.line,\n            column=t.column,\n            last_known_value=last_known_value,\n            extra_attrs=t.extra_attrs,\n        )\n\n    def visit_type_var(self, t: TypeVarType, /) -> Type:\n        return t\n\n    def visit_param_spec(self, t: ParamSpecType, /) -> Type:\n        return t\n\n    def visit_parameters(self, t: Parameters, /) -> Type:\n        return t.copy_modified(arg_types=self.translate_type_list(t.arg_types))\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> Type:\n        return t\n\n    def visit_partial_type(self, t: PartialType, /) -> Type:\n        return t\n\n    def visit_unpack_type(self, t: UnpackType, /) -> Type:\n        return UnpackType(t.type.accept(self))\n\n    def visit_callable_type(self, t: CallableType, /) -> Type:\n        return t.copy_modified(\n            arg_types=self.translate_type_list(t.arg_types),\n            ret_type=t.ret_type.accept(self),\n            variables=self.translate_variables(t.variables),\n        )\n\n    def visit_tuple_type(self, t: TupleType, /) -> Type:\n        return TupleType(\n            self.translate_type_list(t.items),\n            # TODO: This appears to be unsafe.\n            cast(Any, t.partial_fallback.accept(self)),\n            t.line,\n            t.column,\n        )\n\n    def visit_typeddict_type(self, t: TypedDictType, /) -> Type:\n        # Use cache to avoid O(n**2) or worse expansion of types during translation\n        if cached := self.get_cached(t):\n            return cached\n        items = {item_name: item_type.accept(self) for (item_name, item_type) in t.items.items()}\n        result = TypedDictType(\n            items,\n            t.required_keys,\n            t.readonly_keys,\n            # TODO: This appears to be unsafe.\n            cast(Any, t.fallback.accept(self)),\n            t.line,\n            t.column,\n        )\n        self.set_cached(t, result)\n        return result\n\n    def visit_literal_type(self, t: LiteralType, /) -> Type:\n        fallback = t.fallback.accept(self)\n        assert isinstance(fallback, Instance)  # type: ignore[misc]\n        return LiteralType(value=t.value, fallback=fallback, line=t.line, column=t.column)\n\n    def visit_union_type(self, t: UnionType, /) -> Type:\n        # Use cache to avoid O(n**2) or worse expansion of types during translation\n        # (only for large unions, since caching adds overhead)\n        use_cache = len(t.items) > 3\n        if use_cache and (cached := self.get_cached(t)):\n            return cached\n\n        result = UnionType(\n            self.translate_type_list(t.items),\n            t.line,\n            t.column,\n            uses_pep604_syntax=t.uses_pep604_syntax,\n        )\n        if use_cache:\n            self.set_cached(t, result)\n        return result\n\n    def translate_type_list(self, types: list[Type]) -> list[Type]:\n        return [t.accept(self) for t in types]\n\n    def translate_type_tuple(self, types: tuple[Type, ...]) -> tuple[Type, ...]:\n        return tuple(t.accept(self) for t in types)\n\n    def translate_variables(\n        self, variables: Sequence[TypeVarLikeType]\n    ) -> Sequence[TypeVarLikeType]:\n        return variables\n\n    def visit_overloaded(self, t: Overloaded, /) -> Type:\n        items: list[CallableType] = []\n        for item in t.items:\n            new = item.accept(self)\n            assert isinstance(new, CallableType)  # type: ignore[misc]\n            items.append(new)\n        return Overloaded(items=items)\n\n    def visit_type_type(self, t: TypeType, /) -> Type:\n        return TypeType.make_normalized(\n            t.item.accept(self), line=t.line, column=t.column, is_type_form=t.is_type_form\n        )\n\n    @abstractmethod\n    def visit_type_alias_type(self, t: TypeAliasType, /) -> Type:\n        # This method doesn't have a default implementation for type translators,\n        # because type aliases are special: some information is contained in the\n        # TypeAlias node, and we normally don't generate new nodes. Every subclass\n        # must implement this depending on its semantics.\n        pass\n\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass TypeQuery(SyntheticTypeVisitor[T]):\n    \"\"\"Visitor for performing queries of types.\n\n    strategy is used to combine results for a series of types,\n    common use cases involve a boolean query using `any` or `all`.\n\n    Note: this visitor keeps an internal state (tracks type aliases to avoid\n    recursion), so it should *never* be reused for querying different types,\n    create a new visitor instance instead.\n\n    # TODO: check that we don't have existing violations of this rule.\n    \"\"\"\n\n    def __init__(self) -> None:\n        # Keep track of the type aliases already visited. This is needed to avoid\n        # infinite recursion on types like A = Union[int, List[A]].\n        self.seen_aliases: set[TypeAliasType] | None = None\n        # By default, we eagerly expand type aliases, and query also types in the\n        # alias target. In most cases this is a desired behavior, but we may want\n        # to skip targets in some cases (e.g. when collecting type variables).\n        self.skip_alias_target = False\n\n    @abstractmethod\n    def strategy(self, items: list[T]) -> T:\n        raise NotImplementedError\n\n    def visit_unbound_type(self, t: UnboundType, /) -> T:\n        return self.query_types(t.args)\n\n    def visit_type_list(self, t: TypeList, /) -> T:\n        return self.query_types(t.items)\n\n    def visit_callable_argument(self, t: CallableArgument, /) -> T:\n        return t.typ.accept(self)\n\n    def visit_any(self, t: AnyType, /) -> T:\n        return self.strategy([])\n\n    def visit_uninhabited_type(self, t: UninhabitedType, /) -> T:\n        return self.strategy([])\n\n    def visit_none_type(self, t: NoneType, /) -> T:\n        return self.strategy([])\n\n    def visit_erased_type(self, t: ErasedType, /) -> T:\n        return self.strategy([])\n\n    def visit_deleted_type(self, t: DeletedType, /) -> T:\n        return self.strategy([])\n\n    def visit_type_var(self, t: TypeVarType, /) -> T:\n        return self.query_types([t.upper_bound, t.default] + t.values)\n\n    def visit_param_spec(self, t: ParamSpecType, /) -> T:\n        return self.query_types([t.upper_bound, t.default, t.prefix])\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> T:\n        return self.query_types([t.upper_bound, t.default])\n\n    def visit_unpack_type(self, t: UnpackType, /) -> T:\n        return self.query_types([t.type])\n\n    def visit_parameters(self, t: Parameters, /) -> T:\n        return self.query_types(t.arg_types)\n\n    def visit_partial_type(self, t: PartialType, /) -> T:\n        return self.strategy([])\n\n    def visit_instance(self, t: Instance, /) -> T:\n        return self.query_types(t.args)\n\n    def visit_callable_type(self, t: CallableType, /) -> T:\n        # FIX generics\n        return self.query_types(t.arg_types + [t.ret_type])\n\n    def visit_tuple_type(self, t: TupleType, /) -> T:\n        return self.query_types([t.partial_fallback] + t.items)\n\n    def visit_typeddict_type(self, t: TypedDictType, /) -> T:\n        return self.query_types(t.items.values())\n\n    def visit_raw_expression_type(self, t: RawExpressionType, /) -> T:\n        return self.strategy([])\n\n    def visit_literal_type(self, t: LiteralType, /) -> T:\n        return self.strategy([])\n\n    def visit_union_type(self, t: UnionType, /) -> T:\n        return self.query_types(t.items)\n\n    def visit_overloaded(self, t: Overloaded, /) -> T:\n        return self.query_types(t.items)\n\n    def visit_type_type(self, t: TypeType, /) -> T:\n        return t.item.accept(self)\n\n    def visit_ellipsis_type(self, t: EllipsisType, /) -> T:\n        return self.strategy([])\n\n    def visit_placeholder_type(self, t: PlaceholderType, /) -> T:\n        return self.query_types(t.args)\n\n    def visit_type_alias_type(self, t: TypeAliasType, /) -> T:\n        if self.skip_alias_target:\n            return self.query_types(t.args)\n        # Skip type aliases already visited types to avoid infinite recursion\n        # (also use this as a simple-minded cache).\n        if self.seen_aliases is None:\n            self.seen_aliases = set()\n        elif t in self.seen_aliases:\n            return self.strategy([])\n        self.seen_aliases.add(t)\n        return get_proper_type(t).accept(self)\n\n    def query_types(self, types: Iterable[Type]) -> T:\n        \"\"\"Perform a query for a list of types using the strategy to combine the results.\"\"\"\n        return self.strategy([t.accept(self) for t in types])\n\n\n# Return True if at least one type component returns True\nANY_STRATEGY: Final = 0\n# Return True if no type component returns False\nALL_STRATEGY: Final = 1\n\n\nclass BoolTypeQuery(SyntheticTypeVisitor[bool]):\n    \"\"\"Visitor for performing recursive queries of types with a bool result.\n\n    Use TypeQuery if you need non-bool results.\n\n    'strategy' is used to combine results for a series of types. It must\n    be ANY_STRATEGY or ALL_STRATEGY.\n\n    Note: This visitor keeps an internal state (tracks type aliases to avoid\n    recursion), so it should *never* be reused for querying different types\n    unless you call reset() first.\n    \"\"\"\n\n    def __init__(self, strategy: int) -> None:\n        self.strategy = strategy\n        if strategy == ANY_STRATEGY:\n            self.default = False\n        else:\n            assert strategy == ALL_STRATEGY\n            self.default = True\n        # Keep track of the type aliases already visited. This is needed to avoid\n        # infinite recursion on types like A = Union[int, List[A]]. An empty set is\n        # represented as None as a micro-optimization.\n        self.seen_aliases: set[TypeAliasType] | None = None\n        # By default, we eagerly expand type aliases, and query also types in the\n        # alias target. In most cases this is a desired behavior, but we may want\n        # to skip targets in some cases (e.g. when collecting type variables).\n        self.skip_alias_target = False\n\n    def reset(self) -> None:\n        \"\"\"Clear mutable state (but preserve strategy).\n\n        This *must* be called if you want to reuse the visitor.\n        \"\"\"\n        self.seen_aliases = None\n\n    def visit_unbound_type(self, t: UnboundType, /) -> bool:\n        return self.query_types(t.args)\n\n    def visit_type_list(self, t: TypeList, /) -> bool:\n        return self.query_types(t.items)\n\n    def visit_callable_argument(self, t: CallableArgument, /) -> bool:\n        return t.typ.accept(self)\n\n    def visit_any(self, t: AnyType, /) -> bool:\n        return self.default\n\n    def visit_uninhabited_type(self, t: UninhabitedType, /) -> bool:\n        return self.default\n\n    def visit_none_type(self, t: NoneType, /) -> bool:\n        return self.default\n\n    def visit_erased_type(self, t: ErasedType, /) -> bool:\n        return self.default\n\n    def visit_deleted_type(self, t: DeletedType, /) -> bool:\n        return self.default\n\n    def visit_type_var(self, t: TypeVarType, /) -> bool:\n        return self.query_types([t.upper_bound, t.default] + t.values)\n\n    def visit_param_spec(self, t: ParamSpecType, /) -> bool:\n        return self.query_types([t.upper_bound, t.default, t.prefix])\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> bool:\n        return self.query_types([t.upper_bound, t.default])\n\n    def visit_unpack_type(self, t: UnpackType, /) -> bool:\n        return self.query_types([t.type])\n\n    def visit_parameters(self, t: Parameters, /) -> bool:\n        return self.query_types(t.arg_types)\n\n    def visit_partial_type(self, t: PartialType, /) -> bool:\n        return self.default\n\n    def visit_instance(self, t: Instance, /) -> bool:\n        return self.query_types(t.args)\n\n    def visit_callable_type(self, t: CallableType, /) -> bool:\n        # FIX generics\n        # Avoid allocating any objects here as an optimization.\n        args = self.query_types(t.arg_types)\n        ret = t.ret_type.accept(self)\n        if self.strategy == ANY_STRATEGY:\n            return args or ret\n        else:\n            return args and ret\n\n    def visit_tuple_type(self, t: TupleType, /) -> bool:\n        return self.query_types([t.partial_fallback] + t.items)\n\n    def visit_typeddict_type(self, t: TypedDictType, /) -> bool:\n        return self.query_types(list(t.items.values()))\n\n    def visit_raw_expression_type(self, t: RawExpressionType, /) -> bool:\n        return self.default\n\n    def visit_literal_type(self, t: LiteralType, /) -> bool:\n        return self.default\n\n    def visit_union_type(self, t: UnionType, /) -> bool:\n        return self.query_types(t.items)\n\n    def visit_overloaded(self, t: Overloaded, /) -> bool:\n        return self.query_types(t.items)  # type: ignore[arg-type]\n\n    def visit_type_type(self, t: TypeType, /) -> bool:\n        return t.item.accept(self)\n\n    def visit_ellipsis_type(self, t: EllipsisType, /) -> bool:\n        return self.default\n\n    def visit_placeholder_type(self, t: PlaceholderType, /) -> bool:\n        return self.query_types(t.args)\n\n    def visit_type_alias_type(self, t: TypeAliasType, /) -> bool:\n        if self.skip_alias_target:\n            return self.query_types(t.args)\n        # Skip type aliases already visited types to avoid infinite recursion\n        # (also use this as a simple-minded cache).\n        if self.seen_aliases is None:\n            self.seen_aliases = set()\n        elif t in self.seen_aliases:\n            return self.default\n        self.seen_aliases.add(t)\n        return get_proper_type(t).accept(self)\n\n    def query_types(self, types: list[Type] | tuple[Type, ...]) -> bool:\n        \"\"\"Perform a query for a sequence of types using the strategy to combine the results.\"\"\"\n        # Special-case for lists and tuples to allow mypyc to produce better code.\n        if isinstance(types, list):\n            if self.strategy == ANY_STRATEGY:\n                return any(t.accept(self) for t in types)\n            else:\n                return all(t.accept(self) for t in types)\n        else:\n            if self.strategy == ANY_STRATEGY:\n                return any(t.accept(self) for t in types)\n            else:\n                return all(t.accept(self) for t in types)\n"
  },
  {
    "path": "mypy/typeanal.py",
    "content": "\"\"\"Semantic analysis of types\"\"\"\n\nfrom __future__ import annotations\n\nimport itertools\nfrom collections.abc import Callable, Iterable, Iterator, Sequence\nfrom contextlib import contextmanager\nfrom typing import Final, Protocol, TypeVar\n\nfrom mypy import errorcodes as codes, message_registry, nodes\nfrom mypy.errorcodes import ErrorCode\nfrom mypy.errors import ErrorInfo\nfrom mypy.expandtype import expand_type\nfrom mypy.message_registry import (\n    INVALID_PARAM_SPEC_LOCATION,\n    INVALID_PARAM_SPEC_LOCATION_NOTE,\n    TYPEDDICT_OVERRIDE_MERGE,\n)\nfrom mypy.messages import (\n    MessageBuilder,\n    format_type,\n    format_type_bare,\n    quote_type_string,\n    wrong_type_arg_count,\n)\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_NAMED_OPT,\n    ARG_OPT,\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    MISSING_FALLBACK,\n    SYMBOL_FUNCBASE_TYPES,\n    ArgKind,\n    Context,\n    Decorator,\n    ImportFrom,\n    MypyFile,\n    ParamSpecExpr,\n    PlaceholderNode,\n    SymbolTableNode,\n    TypeAlias,\n    TypeInfo,\n    TypeVarExpr,\n    TypeVarLikeExpr,\n    TypeVarTupleExpr,\n    Var,\n    check_arg_kinds,\n    check_param_names,\n)\nfrom mypy.options import INLINE_TYPEDDICT, TYPE_FORM, Options\nfrom mypy.plugin import AnalyzeTypeContext, Plugin, TypeAnalyzerPluginInterface\nfrom mypy.semanal_shared import (\n    SemanticAnalyzerCoreInterface,\n    SemanticAnalyzerInterface,\n    paramspec_args,\n    paramspec_kwargs,\n)\nfrom mypy.state import state\nfrom mypy.tvar_scope import TypeVarLikeScope\nfrom mypy.types import (\n    ANNOTATED_TYPE_NAMES,\n    ANY_STRATEGY,\n    CONCATENATE_TYPE_NAMES,\n    FINAL_TYPE_NAMES,\n    LITERAL_TYPE_NAMES,\n    MYPYC_NATIVE_INT_NAMES,\n    NEVER_NAMES,\n    TUPLE_NAMES,\n    TYPE_ALIAS_NAMES,\n    TYPE_NAMES,\n    UNPACK_TYPE_NAMES,\n    AnyType,\n    BoolTypeQuery,\n    CallableArgument,\n    CallableType,\n    DeletedType,\n    EllipsisType,\n    ErasedType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecFlavor,\n    ParamSpecType,\n    PartialType,\n    PlaceholderType,\n    ProperType,\n    RawExpressionType,\n    ReadOnlyType,\n    RequiredType,\n    SyntheticTypeVisitor,\n    TrivialSyntheticTypeTranslator,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeList,\n    TypeOfAny,\n    TypeQuery,\n    TypeType,\n    TypeVarId,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    callable_with_ellipsis,\n    find_unpack_in_list,\n    flatten_nested_tuples,\n    get_proper_type,\n    has_type_vars,\n)\nfrom mypy.types_utils import get_bad_type_type_item\nfrom mypy.typevars import fill_typevars\n\nT = TypeVar(\"T\")\n\ntype_constructors: Final = {\n    \"typing.Callable\",\n    \"typing.Optional\",\n    \"typing.Tuple\",\n    \"typing.Type\",\n    \"typing.Union\",\n    *LITERAL_TYPE_NAMES,\n    *ANNOTATED_TYPE_NAMES,\n}\n\nARG_KINDS_BY_CONSTRUCTOR: Final = {\n    \"mypy_extensions.Arg\": ARG_POS,\n    \"mypy_extensions.DefaultArg\": ARG_OPT,\n    \"mypy_extensions.NamedArg\": ARG_NAMED,\n    \"mypy_extensions.DefaultNamedArg\": ARG_NAMED_OPT,\n    \"mypy_extensions.VarArg\": ARG_STAR,\n    \"mypy_extensions.KwArg\": ARG_STAR2,\n}\n\nSELF_TYPE_NAMES: Final = {\"typing.Self\", \"typing_extensions.Self\"}\n\n\ndef analyze_type_alias(\n    type: Type,\n    api: SemanticAnalyzerCoreInterface,\n    tvar_scope: TypeVarLikeScope,\n    plugin: Plugin,\n    options: Options,\n    cur_mod_node: MypyFile,\n    is_typeshed_stub: bool,\n    allow_placeholder: bool = False,\n    in_dynamic_func: bool = False,\n    global_scope: bool = True,\n    allowed_alias_tvars: list[TypeVarLikeType] | None = None,\n    alias_type_params_names: list[str] | None = None,\n    python_3_12_type_alias: bool = False,\n) -> tuple[Type, set[str]]:\n    \"\"\"Analyze r.h.s. of a (potential) type alias definition.\n\n    If `node` is valid as a type alias rvalue, return the resulting type and a set of\n    full names of type aliases it depends on (directly or indirectly).\n    'node' must have been semantically analyzed.\n    \"\"\"\n    analyzer = TypeAnalyser(\n        api,\n        tvar_scope,\n        plugin,\n        options,\n        cur_mod_node,\n        is_typeshed_stub,\n        defining_alias=True,\n        allow_placeholder=allow_placeholder,\n        prohibit_self_type=\"type alias target\",\n        allowed_alias_tvars=allowed_alias_tvars,\n        alias_type_params_names=alias_type_params_names,\n        python_3_12_type_alias=python_3_12_type_alias,\n    )\n    analyzer.in_dynamic_func = in_dynamic_func\n    analyzer.global_scope = global_scope\n    res = analyzer.anal_type(type, nested=False)\n    return res, analyzer.aliases_used\n\n\nclass TypeAnalyser(SyntheticTypeVisitor[Type], TypeAnalyzerPluginInterface):\n    \"\"\"Semantic analyzer for types.\n\n    Converts unbound types into bound types. This is a no-op for already\n    bound types.\n\n    If an incomplete reference is encountered, this does a defer. The\n    caller never needs to defer.\n    \"\"\"\n\n    # Is this called from an untyped function definition?\n    in_dynamic_func: bool = False\n    # Is this called from global scope?\n    global_scope: bool = True\n\n    def __init__(\n        self,\n        api: SemanticAnalyzerCoreInterface,\n        tvar_scope: TypeVarLikeScope,\n        plugin: Plugin,\n        options: Options,\n        cur_mod_node: MypyFile,\n        is_typeshed_stub: bool,\n        *,\n        defining_alias: bool = False,\n        python_3_12_type_alias: bool = False,\n        allow_tuple_literal: bool = False,\n        allow_unbound_tvars: bool = False,\n        allow_placeholder: bool = False,\n        allow_typed_dict_special_forms: bool = False,\n        allow_final: bool = True,\n        allow_param_spec_literals: bool = False,\n        allow_unpack: bool = False,\n        report_invalid_types: bool = True,\n        prohibit_self_type: str | None = None,\n        prohibit_special_class_field_types: str | None = None,\n        allowed_alias_tvars: list[TypeVarLikeType] | None = None,\n        allow_type_any: bool = False,\n        alias_type_params_names: list[str] | None = None,\n    ) -> None:\n        self.api = api\n        self.fail_func = api.fail\n        self.note_func = api.note\n        self.tvar_scope = tvar_scope\n        # Are we analysing a type alias definition rvalue?\n        self.defining_alias = defining_alias\n        self.python_3_12_type_alias = python_3_12_type_alias\n        self.allow_tuple_literal = allow_tuple_literal\n        # Positive if we are analyzing arguments of another (outer) type\n        self.nesting_level = 0\n        # Should we allow new type syntax when targeting older Python versions\n        # like 'list[int]' or 'X | Y' (allowed in stubs and with `__future__` import)?\n        self.always_allow_new_syntax = self.api.is_stub_file or self.api.is_future_flag_set(\n            \"annotations\"\n        )\n        # Should we accept unbound type variables? This is currently used for class bases,\n        # and alias right hand sides (before they are analyzed as type aliases).\n        self.allow_unbound_tvars = allow_unbound_tvars\n        if allowed_alias_tvars is None:\n            allowed_alias_tvars = []\n        self.allowed_alias_tvars = allowed_alias_tvars\n        self.alias_type_params_names = alias_type_params_names\n        # If false, record incomplete ref if we generate PlaceholderType.\n        self.allow_placeholder = allow_placeholder\n        # Are we in a context where Required[] is allowed?\n        self.allow_typed_dict_special_forms = allow_typed_dict_special_forms\n        # Set True when we analyze ClassVar else False\n        self.allow_final = allow_final\n        # Are we in a context where ParamSpec literals are allowed?\n        self.allow_param_spec_literals = allow_param_spec_literals\n        # Are we in context where literal \"...\" specifically is allowed?\n        self.allow_ellipsis = False\n        # Should we report an error whenever we encounter a RawExpressionType outside\n        # of a Literal context: e.g. whenever we encounter an invalid type? Normally,\n        # we want to report an error, but the caller may want to do more specialized\n        # error handling.\n        self.report_invalid_types = report_invalid_types\n        self.plugin = plugin\n        self.options = options\n        self.cur_mod_node = cur_mod_node\n        self.is_typeshed_stub = is_typeshed_stub\n        # Names of type aliases encountered while analysing a type will be collected here.\n        self.aliases_used: set[str] = set()\n        self.prohibit_self_type = prohibit_self_type\n        # Set when we analyze TypedDicts or NamedTuples, since they are special:\n        self.prohibit_special_class_field_types = prohibit_special_class_field_types\n        # Allow variables typed as Type[Any] and type (useful for base classes).\n        self.allow_type_any = allow_type_any\n        self.allow_type_var_tuple = False\n        self.allow_unpack = allow_unpack\n\n    def lookup_qualified(\n        self, name: str, ctx: Context, suppress_errors: bool = False\n    ) -> SymbolTableNode | None:\n        return self.api.lookup_qualified(name, ctx, suppress_errors)\n\n    def lookup_fully_qualified(self, fullname: str) -> SymbolTableNode:\n        return self.api.lookup_fully_qualified(fullname)\n\n    def visit_unbound_type(self, t: UnboundType, defining_literal: bool = False) -> Type:\n        typ = self.visit_unbound_type_nonoptional(t, defining_literal)\n        if t.optional:\n            # We don't need to worry about double-wrapping Optionals or\n            # wrapping Anys: Union simplification will take care of that.\n            return make_optional_type(typ)\n        return typ\n\n    def not_declared_in_type_params(self, tvar_name: str) -> bool:\n        return (\n            self.alias_type_params_names is not None\n            and tvar_name not in self.alias_type_params_names\n        )\n\n    def visit_unbound_type_nonoptional(self, t: UnboundType, defining_literal: bool) -> Type:\n        sym = self.lookup_qualified(t.name, t)\n        param_spec_name = None\n        if t.name.endswith((\".args\", \".kwargs\")):\n            param_spec_name = t.name.rsplit(\".\", 1)[0]\n            maybe_param_spec = self.lookup_qualified(param_spec_name, t)\n            if maybe_param_spec and isinstance(maybe_param_spec.node, ParamSpecExpr):\n                sym = maybe_param_spec\n            else:\n                param_spec_name = None\n\n        if sym is not None:\n            node = sym.node\n            if isinstance(node, PlaceholderNode):\n                if node.becomes_typeinfo:\n                    # Reference to placeholder type.\n                    if self.api.final_iteration:\n                        self.cannot_resolve_type(t)\n                        return AnyType(TypeOfAny.from_error)\n                    elif self.allow_placeholder:\n                        self.api.defer()\n                    else:\n                        self.api.record_incomplete_ref()\n                    # Always allow ParamSpec for placeholders, if they are actually not valid,\n                    # they will be reported later, after we resolve placeholders.\n                    return PlaceholderType(\n                        node.fullname,\n                        self.anal_array(\n                            t.args,\n                            allow_param_spec=True,\n                            allow_param_spec_literals=True,\n                            allow_unpack=True,\n                        ),\n                        t.line,\n                    )\n                else:\n                    if self.api.final_iteration:\n                        self.cannot_resolve_type(t)\n                        return AnyType(TypeOfAny.from_error)\n                    else:\n                        # Reference to an unknown placeholder node.\n                        self.api.record_incomplete_ref()\n                        return AnyType(TypeOfAny.special_form)\n            if node is None:\n                self.fail(f\"Internal error (node is None, kind={sym.kind})\", t)\n                return AnyType(TypeOfAny.special_form)\n            fullname = node.fullname\n            hook = self.plugin.get_type_analyze_hook(fullname)\n            if hook is not None:\n                return hook(AnalyzeTypeContext(t, t, self))\n            tvar_def = self.tvar_scope.get_binding(sym)\n            if tvar_def is not None:\n                # We need to cover special-case explained in get_typevarlike_argument() here,\n                # since otherwise the deferral will not be triggered if the type variable is\n                # used in a different module. Using isinstance() should be safe for this purpose.\n                tvar_params = [tvar_def.upper_bound, tvar_def.default]\n                if isinstance(tvar_def, TypeVarType):\n                    tvar_params += tvar_def.values\n                if any(isinstance(tp, PlaceholderType) for tp in tvar_params):\n                    self.api.defer()\n            if isinstance(sym.node, ParamSpecExpr):\n                if tvar_def is None:\n                    if self.allow_unbound_tvars:\n                        return t\n                    name = param_spec_name or t.name\n                    if self.defining_alias and self.not_declared_in_type_params(t.name):\n                        msg = f'ParamSpec \"{name}\" is not included in type_params'\n                    else:\n                        msg = f'ParamSpec \"{name}\" is unbound'\n                    self.fail(msg, t, code=codes.VALID_TYPE)\n                    return AnyType(TypeOfAny.from_error)\n                assert isinstance(tvar_def, ParamSpecType)\n                if len(t.args) > 0:\n                    self.fail(\n                        f'ParamSpec \"{t.name}\" used with arguments', t, code=codes.VALID_TYPE\n                    )\n                if param_spec_name is not None and not self.allow_param_spec_literals:\n                    self.fail(\n                        \"ParamSpec components are not allowed here\", t, code=codes.VALID_TYPE\n                    )\n                    return AnyType(TypeOfAny.from_error)\n                # Change the line number\n                return ParamSpecType(\n                    tvar_def.name,\n                    tvar_def.fullname,\n                    tvar_def.id,\n                    tvar_def.flavor,\n                    tvar_def.upper_bound,\n                    tvar_def.default,\n                    line=t.line,\n                    column=t.column,\n                )\n            if (\n                isinstance(sym.node, TypeVarExpr)\n                and self.defining_alias\n                and not defining_literal\n                and (tvar_def is None or tvar_def not in self.allowed_alias_tvars)\n            ):\n                if self.not_declared_in_type_params(t.name):\n                    if self.python_3_12_type_alias:\n                        msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format(\n                            f'\"{t.name}\"'\n                        )\n                    else:\n                        msg = f'Type variable \"{t.name}\" is not included in type_params'\n                else:\n                    msg = f'Can\\'t use bound type variable \"{t.name}\" to define generic alias'\n                self.fail(msg, t, code=codes.VALID_TYPE)\n                return AnyType(TypeOfAny.from_error)\n            if isinstance(sym.node, TypeVarExpr) and tvar_def is not None:\n                assert isinstance(tvar_def, TypeVarType)\n                if len(t.args) > 0:\n                    self.fail(\n                        f'Type variable \"{t.name}\" used with arguments', t, code=codes.VALID_TYPE\n                    )\n                # Change the line number\n                return tvar_def.copy_modified(line=t.line, column=t.column)\n            if isinstance(sym.node, TypeVarTupleExpr) and (\n                tvar_def is not None\n                and self.defining_alias\n                and tvar_def not in self.allowed_alias_tvars\n            ):\n                if self.not_declared_in_type_params(t.name):\n                    msg = f'Type variable \"{t.name}\" is not included in type_params'\n                else:\n                    msg = f'Can\\'t use bound type variable \"{t.name}\" to define generic alias'\n                self.fail(msg, t, code=codes.VALID_TYPE)\n                return AnyType(TypeOfAny.from_error)\n            if isinstance(sym.node, TypeVarTupleExpr):\n                if tvar_def is None:\n                    if self.allow_unbound_tvars:\n                        return t\n                    if self.defining_alias and self.not_declared_in_type_params(t.name):\n                        if self.python_3_12_type_alias:\n                            msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format(\n                                f'\"{t.name}\"'\n                            )\n                        else:\n                            msg = f'TypeVarTuple \"{t.name}\" is not included in type_params'\n                    else:\n                        msg = f'TypeVarTuple \"{t.name}\" is unbound'\n                    self.fail(msg, t, code=codes.VALID_TYPE)\n                    return AnyType(TypeOfAny.from_error)\n                assert isinstance(tvar_def, TypeVarTupleType)\n                if not self.allow_type_var_tuple:\n                    self.fail(\n                        f'TypeVarTuple \"{t.name}\" is only valid with an unpack',\n                        t,\n                        code=codes.VALID_TYPE,\n                    )\n                    return AnyType(TypeOfAny.from_error)\n                if len(t.args) > 0:\n                    self.fail(\n                        f'Type variable \"{t.name}\" used with arguments', t, code=codes.VALID_TYPE\n                    )\n\n                # Change the line number\n                return TypeVarTupleType(\n                    tvar_def.name,\n                    tvar_def.fullname,\n                    tvar_def.id,\n                    tvar_def.upper_bound,\n                    sym.node.tuple_fallback,\n                    tvar_def.default,\n                    line=t.line,\n                    column=t.column,\n                )\n            special = self.try_analyze_special_unbound_type(t, fullname)\n            if special is not None:\n                return special\n            if isinstance(node, TypeAlias):\n                self.aliases_used.add(fullname)\n                an_args = self.anal_array(\n                    t.args,\n                    allow_param_spec=True,\n                    allow_param_spec_literals=node.has_param_spec_type,\n                    allow_unpack=True,  # Fixed length unpacks can be used for non-variadic aliases.\n                )\n                if node.has_param_spec_type and len(node.alias_tvars) == 1:\n                    an_args = self.pack_paramspec_args(an_args, t.empty_tuple_index)\n\n                disallow_any = self.options.disallow_any_generics and not self.is_typeshed_stub\n                res = instantiate_type_alias(\n                    node,\n                    an_args,\n                    self.fail,\n                    node.no_args,\n                    t,\n                    self.options,\n                    unexpanded_type=t,\n                    disallow_any=disallow_any,\n                    empty_tuple_index=t.empty_tuple_index,\n                )\n                # The only case where instantiate_type_alias() can return an incorrect instance is\n                # when it is top-level instance, so no need to recurse.\n                if (\n                    isinstance(res, ProperType)\n                    and isinstance(res, Instance)\n                    and not (self.defining_alias and self.nesting_level == 0)\n                    and not validate_instance(res, self.fail, t.empty_tuple_index)\n                ):\n                    fix_instance(\n                        res,\n                        self.fail,\n                        self.note,\n                        disallow_any=disallow_any,\n                        options=self.options,\n                        use_generic_error=True,\n                        unexpanded_type=t,\n                    )\n                if node.eager:\n                    res = get_proper_type(res)\n                return res\n            elif isinstance(node, TypeInfo):\n                return self.analyze_type_with_type_info(node, t.args, t, t.empty_tuple_index)\n            elif node.fullname in TYPE_ALIAS_NAMES:\n                return AnyType(TypeOfAny.special_form)\n            # Concatenate is an operator, no need for a proper type\n            elif node.fullname in CONCATENATE_TYPE_NAMES:\n                # We check the return type further up the stack for valid use locations\n                return self.apply_concatenate_operator(t)\n            else:\n                return self.analyze_unbound_type_without_type_info(t, sym, defining_literal)\n        else:  # sym is None\n            return AnyType(TypeOfAny.special_form)\n\n    def pack_paramspec_args(self, an_args: Sequence[Type], empty_tuple_index: bool) -> list[Type]:\n        # \"Aesthetic\" ParamSpec literals for single ParamSpec: C[int, str] -> C[[int, str]].\n        # These do not support mypy_extensions VarArgs, etc. as they were already analyzed\n        # TODO: should these be re-analyzed to get rid of this inconsistency?\n        count = len(an_args)\n        if count == 0 and empty_tuple_index:\n            return [Parameters([], [], [])]\n        elif count == 0:\n            return []\n\n        if count == 1 and isinstance(get_proper_type(an_args[0]), AnyType):\n            # Single Any is interpreted as ..., rather that a single argument with Any type.\n            # I didn't find this in the PEP, but it sounds reasonable.\n            return list(an_args)\n        if any(isinstance(a, (Parameters, ParamSpecType)) for a in an_args):\n            if len(an_args) > 1:\n                first_wrong = next(\n                    arg for arg in an_args if isinstance(arg, (Parameters, ParamSpecType))\n                )\n                self.fail(\n                    \"Nested parameter specifications are not allowed\",\n                    first_wrong,\n                    code=codes.VALID_TYPE,\n                )\n                return [AnyType(TypeOfAny.from_error)]\n            return list(an_args)\n        first = an_args[0]\n        return [\n            Parameters(\n                an_args, [ARG_POS] * count, [None] * count, line=first.line, column=first.column\n            )\n        ]\n\n    def cannot_resolve_type(self, t: UnboundType) -> None:\n        # TODO: Move error message generation to messages.py. We'd first\n        #       need access to MessageBuilder here. Also move the similar\n        #       message generation logic in semanal.py.\n        self.api.fail(f'Cannot resolve name \"{t.name}\" (possible cyclic definition)', t)\n        if self.api.is_func_scope():\n            self.note(\"Recursive types are not allowed at function scope\", t)\n\n    def apply_concatenate_operator(self, t: UnboundType) -> Type:\n        if len(t.args) == 0:\n            self.api.fail(\"Concatenate needs type arguments\", t, code=codes.VALID_TYPE)\n            return AnyType(TypeOfAny.from_error)\n\n        # Last argument has to be ParamSpec or Ellipsis.\n        ps = self.anal_type(t.args[-1], allow_param_spec=True, allow_ellipsis=True)\n        if not isinstance(ps, (ParamSpecType, Parameters)):\n            if isinstance(ps, UnboundType) and self.allow_unbound_tvars:\n                sym = self.lookup_qualified(ps.name, t)\n                if sym is not None and isinstance(sym.node, ParamSpecExpr):\n                    return ps\n            self.api.fail(\n                \"The last parameter to Concatenate needs to be a ParamSpec\",\n                t,\n                code=codes.VALID_TYPE,\n            )\n            return AnyType(TypeOfAny.from_error)\n        elif isinstance(ps, ParamSpecType) and ps.prefix.arg_types:\n            self.api.fail(\"Nested Concatenates are invalid\", t, code=codes.VALID_TYPE)\n\n        args = self.anal_array(t.args[:-1])\n        pre = ps.prefix if isinstance(ps, ParamSpecType) else ps\n\n        # mypy can't infer this :(\n        names: list[str | None] = [None] * len(args)\n\n        pre = Parameters(\n            args + pre.arg_types,\n            [ARG_POS] * len(args) + pre.arg_kinds,\n            names + pre.arg_names,\n            line=t.line,\n            column=t.column,\n        )\n        return ps.copy_modified(prefix=pre) if isinstance(ps, ParamSpecType) else pre\n\n    def try_analyze_special_unbound_type(self, t: UnboundType, fullname: str) -> Type | None:\n        \"\"\"Bind special type that is recognized through magic name such as 'typing.Any'.\n\n        Return the bound type if successful, and return None if the type is a normal type.\n        \"\"\"\n        if fullname == \"builtins.None\":\n            return NoneType()\n        elif fullname == \"typing.Any\":\n            return AnyType(TypeOfAny.explicit, line=t.line, column=t.column)\n        elif fullname in FINAL_TYPE_NAMES:\n            if self.prohibit_special_class_field_types:\n                self.fail(\n                    f\"Final[...] can't be used inside a {self.prohibit_special_class_field_types}\",\n                    t,\n                    code=codes.VALID_TYPE,\n                )\n            else:\n                if not self.allow_final:\n                    self.fail(\n                        \"Final can be only used as an outermost qualifier in a variable annotation\",\n                        t,\n                        code=codes.VALID_TYPE,\n                    )\n            return AnyType(TypeOfAny.from_error)\n        elif fullname in TUPLE_NAMES:\n            # Tuple is special because it is involved in builtin import cycle\n            # and may be not ready when used.\n            sym = self.api.lookup_fully_qualified_or_none(\"builtins.tuple\")\n            if not sym or isinstance(sym.node, PlaceholderNode):\n                if self.api.is_incomplete_namespace(\"builtins\"):\n                    self.api.record_incomplete_ref()\n                else:\n                    self.fail('Name \"tuple\" is not defined', t)\n                return AnyType(TypeOfAny.special_form)\n            if len(t.args) == 0 and not t.empty_tuple_index:\n                # Bare 'Tuple' is same as 'tuple'\n                any_type = self.get_omitted_any(t)\n                return self.named_type(\"builtins.tuple\", [any_type], line=t.line, column=t.column)\n            if len(t.args) == 2 and isinstance(t.args[1], EllipsisType):\n                # Tuple[T, ...] (uniform, variable-length tuple)\n                instance = self.named_type(\"builtins.tuple\", [self.anal_type(t.args[0])])\n                instance.line = t.line\n                return instance\n            return self.tuple_type(\n                self.anal_array(t.args, allow_unpack=True), line=t.line, column=t.column\n            )\n        elif fullname == \"typing.Union\":\n            items = self.anal_array(t.args)\n            return UnionType.make_union(items, line=t.line, column=t.column)\n        elif fullname == \"typing.Optional\":\n            if len(t.args) != 1:\n                self.fail(\n                    \"Optional[...] must have exactly one type argument\", t, code=codes.VALID_TYPE\n                )\n                return AnyType(TypeOfAny.from_error)\n            item = self.anal_type(t.args[0])\n            return make_optional_type(item)\n        elif fullname == \"typing.Callable\":\n            return self.analyze_callable_type(t)\n        elif fullname in TYPE_NAMES:\n            if len(t.args) == 0:\n                if fullname == \"typing.Type\":\n                    any_type = self.get_omitted_any(t)\n                    return TypeType(any_type, line=t.line, column=t.column)\n                else:\n                    # To prevent assignment of 'builtins.type' inferred as 'builtins.object'\n                    # See https://github.com/python/mypy/issues/9476 for more information\n                    return None\n            type_str = \"Type[...]\" if fullname == \"typing.Type\" else \"type[...]\"\n            if len(t.args) != 1:\n                self.fail(\n                    f\"{type_str} must have exactly one type argument\", t, code=codes.VALID_TYPE\n                )\n            item = self.anal_type(t.args[0])\n            bad_item_name = get_bad_type_type_item(item)\n            if bad_item_name:\n                self.fail(f'{type_str} can\\'t contain \"{bad_item_name}\"', t, code=codes.VALID_TYPE)\n                item = AnyType(TypeOfAny.from_error)\n            return TypeType.make_normalized(item, line=t.line, column=t.column)\n        elif fullname in (\"typing_extensions.TypeForm\", \"typing.TypeForm\"):\n            if TYPE_FORM not in self.options.enable_incomplete_feature:\n                self.fail(\n                    \"TypeForm is experimental,\"\n                    \" must be enabled with --enable-incomplete-feature=TypeForm\",\n                    t,\n                )\n            if len(t.args) == 0:\n                any_type = self.get_omitted_any(t)\n                return TypeType(any_type, line=t.line, column=t.column, is_type_form=True)\n            if len(t.args) != 1:\n                type_str = \"TypeForm[...]\"\n                self.fail(\n                    type_str + \" must have exactly one type argument\", t, code=codes.VALID_TYPE\n                )\n            item = self.anal_type(t.args[0])\n            return TypeType.make_normalized(item, line=t.line, column=t.column, is_type_form=True)\n        elif fullname == \"typing.ClassVar\":\n            if self.nesting_level > 0:\n                self.fail(\n                    \"Invalid type: ClassVar nested inside other type\", t, code=codes.VALID_TYPE\n                )\n            if self.prohibit_special_class_field_types:\n                self.fail(\n                    f\"ClassVar[...] can't be used inside a {self.prohibit_special_class_field_types}\",\n                    t,\n                    code=codes.VALID_TYPE,\n                )\n            if self.defining_alias:\n                self.fail(\n                    \"ClassVar[...] can't be used inside a type alias\", t, code=codes.VALID_TYPE\n                )\n            if len(t.args) == 0:\n                return AnyType(TypeOfAny.from_omitted_generics, line=t.line, column=t.column)\n            if len(t.args) != 1:\n                self.fail(\n                    \"ClassVar[...] must have at most one type argument\", t, code=codes.VALID_TYPE\n                )\n                return AnyType(TypeOfAny.from_error)\n            return self.anal_type(t.args[0], allow_final=self.options.python_version >= (3, 13))\n        elif fullname in NEVER_NAMES:\n            return UninhabitedType()\n        elif fullname in LITERAL_TYPE_NAMES:\n            return self.analyze_literal_type(t)\n        elif fullname in ANNOTATED_TYPE_NAMES:\n            if len(t.args) < 2:\n                self.fail(\n                    \"Annotated[...] must have exactly one type argument\"\n                    \" and at least one annotation\",\n                    t,\n                    code=codes.VALID_TYPE,\n                )\n                return AnyType(TypeOfAny.from_error)\n            return self.anal_type(\n                t.args[0], allow_typed_dict_special_forms=self.allow_typed_dict_special_forms\n            )\n        elif fullname in (\"typing_extensions.Required\", \"typing.Required\"):\n            if not self.allow_typed_dict_special_forms:\n                self.fail(\n                    \"Required[] can be only used in a TypedDict definition\",\n                    t,\n                    code=codes.VALID_TYPE,\n                )\n                return AnyType(TypeOfAny.from_error)\n            if len(t.args) != 1:\n                self.fail(\n                    \"Required[] must have exactly one type argument\", t, code=codes.VALID_TYPE\n                )\n                return AnyType(TypeOfAny.from_error)\n            return RequiredType(\n                self.anal_type(t.args[0], allow_typed_dict_special_forms=True), required=True\n            )\n        elif fullname in (\"typing_extensions.NotRequired\", \"typing.NotRequired\"):\n            if not self.allow_typed_dict_special_forms:\n                self.fail(\n                    \"NotRequired[] can be only used in a TypedDict definition\",\n                    t,\n                    code=codes.VALID_TYPE,\n                )\n                return AnyType(TypeOfAny.from_error)\n            if len(t.args) != 1:\n                self.fail(\n                    \"NotRequired[] must have exactly one type argument\", t, code=codes.VALID_TYPE\n                )\n                return AnyType(TypeOfAny.from_error)\n            return RequiredType(\n                self.anal_type(t.args[0], allow_typed_dict_special_forms=True), required=False\n            )\n        elif fullname in (\"typing_extensions.ReadOnly\", \"typing.ReadOnly\"):\n            if not self.allow_typed_dict_special_forms:\n                self.fail(\n                    \"ReadOnly[] can be only used in a TypedDict definition\",\n                    t,\n                    code=codes.VALID_TYPE,\n                )\n                return AnyType(TypeOfAny.from_error)\n            if len(t.args) != 1:\n                self.fail(\n                    '\"ReadOnly[]\" must have exactly one type argument', t, code=codes.VALID_TYPE\n                )\n                return AnyType(TypeOfAny.from_error)\n            return ReadOnlyType(self.anal_type(t.args[0], allow_typed_dict_special_forms=True))\n        elif (\n            self.anal_type_guard_arg(t, fullname) is not None\n            or self.anal_type_is_arg(t, fullname) is not None\n        ):\n            # In most contexts, TypeGuard[...] acts as an alias for bool (ignoring its args)\n            return self.named_type(\"builtins.bool\")\n        elif fullname in UNPACK_TYPE_NAMES:\n            if len(t.args) != 1:\n                self.fail(\"Unpack[...] requires exactly one type argument\", t)\n                return AnyType(TypeOfAny.from_error)\n            if not self.allow_unpack:\n                self.fail(message_registry.INVALID_UNPACK_POSITION, t, code=codes.VALID_TYPE)\n                return AnyType(TypeOfAny.from_error)\n            self.allow_type_var_tuple = True\n            result = UnpackType(self.anal_type(t.args[0]), line=t.line, column=t.column)\n            self.allow_type_var_tuple = False\n            return result\n        elif fullname in SELF_TYPE_NAMES:\n            if t.args:\n                self.fail(\"Self type cannot have type arguments\", t)\n            if self.prohibit_self_type is not None:\n                self.fail(f\"Self type cannot be used in {self.prohibit_self_type}\", t)\n                return AnyType(TypeOfAny.from_error)\n            if self.api.type is None:\n                self.fail(\"Self type is only allowed in annotations within class definition\", t)\n                return AnyType(TypeOfAny.from_error)\n            if self.api.type.has_base(\"builtins.type\"):\n                self.fail(\"Self type cannot be used in a metaclass\", t)\n            if self.api.type.self_type is not None:\n                if self.api.type.is_final or self.api.type.is_enum and self.api.type.enum_members:\n                    return fill_typevars(self.api.type)\n                return self.api.type.self_type.copy_modified(line=t.line, column=t.column)\n            # TODO: verify this is unreachable and replace with an assert?\n            self.fail(\"Unexpected Self type\", t)\n            return AnyType(TypeOfAny.from_error)\n        return None\n\n    def get_omitted_any(self, typ: Type, fullname: str | None = None) -> AnyType:\n        disallow_any = not self.is_typeshed_stub and self.options.disallow_any_generics\n        return get_omitted_any(disallow_any, self.fail, self.note, typ, self.options, fullname)\n\n    def check_and_warn_deprecated(self, info: TypeInfo, ctx: Context) -> None:\n        \"\"\"Similar logic to `TypeChecker.check_deprecated` and `TypeChecker.warn_deprecated.\"\"\"\n\n        if (\n            (deprecated := info.deprecated)\n            and not self.is_typeshed_stub\n            and not (self.api.type and (self.api.type.fullname == info.fullname))\n            and not any(\n                info.fullname == p or info.fullname.startswith(f\"{p}.\")\n                for p in self.options.deprecated_calls_exclude\n            )\n        ):\n            for imp in self.cur_mod_node.imports:\n                if isinstance(imp, ImportFrom) and any(info.name == n[0] for n in imp.names):\n                    break\n            else:\n                warn = self.note if self.options.report_deprecated_as_note else self.fail\n                warn(deprecated, ctx, code=codes.DEPRECATED)\n\n    def analyze_type_with_type_info(\n        self, info: TypeInfo, args: Sequence[Type], ctx: Context, empty_tuple_index: bool\n    ) -> Type:\n        \"\"\"Bind unbound type when were able to find target TypeInfo.\n\n        This handles simple cases like 'int', 'modname.UserClass[str]', etc.\n        \"\"\"\n\n        self.check_and_warn_deprecated(info, ctx)\n\n        if len(args) > 0 and info.fullname == \"builtins.tuple\":\n            fallback = Instance(info, [AnyType(TypeOfAny.special_form)], ctx.line)\n            return TupleType(self.anal_array(args, allow_unpack=True), fallback, ctx.line)\n\n        # Analyze arguments and (usually) construct Instance type. The\n        # number of type arguments and their values are\n        # checked only later, since we do not always know the\n        # valid count at this point. Thus we may construct an\n        # Instance with an invalid number of type arguments.\n        #\n        # We allow ParamSpec literals based on a heuristic: it will be\n        # checked later anyways but the error message may be worse.\n        instance = Instance(\n            info,\n            self.anal_array(\n                args,\n                allow_param_spec=True,\n                allow_param_spec_literals=info.has_param_spec_type,\n                allow_unpack=True,  # Fixed length tuples can be used for non-variadic types.\n            ),\n            ctx.line,\n            ctx.column,\n        )\n        instance.end_line = ctx.end_line\n        instance.end_column = ctx.end_column\n        if len(info.type_vars) == 1 and info.has_param_spec_type:\n            instance.args = tuple(self.pack_paramspec_args(instance.args, empty_tuple_index))\n\n        if info.fullname == \"librt.vecs.vec\" and not check_vec_type_args(\n            instance.args, ctx, self.api\n        ):\n            return AnyType(TypeOfAny.from_error)\n\n        # Check type argument count.\n        instance.args = tuple(flatten_nested_tuples(instance.args))\n        if not (self.defining_alias and self.nesting_level == 0) and not validate_instance(\n            instance, self.fail, empty_tuple_index\n        ):\n            fix_instance(\n                instance,\n                self.fail,\n                self.note,\n                disallow_any=self.options.disallow_any_generics and not self.is_typeshed_stub,\n                options=self.options,\n            )\n\n        tup = info.tuple_type\n        if tup is not None:\n            # The class has a Tuple[...] base class so it will be\n            # represented as a tuple type.\n            if info.special_alias:\n                return instantiate_type_alias(\n                    info.special_alias,\n                    # TODO: should we allow NamedTuples generic in ParamSpec?\n                    self.anal_array(args, allow_unpack=True),\n                    self.fail,\n                    False,\n                    ctx,\n                    self.options,\n                    use_standard_error=True,\n                )\n            return tup.copy_modified(\n                items=self.anal_array(tup.items, allow_unpack=True), fallback=instance\n            )\n        td = info.typeddict_type\n        if td is not None:\n            # The class has a TypedDict[...] base class so it will be\n            # represented as a typeddict type.\n            if info.special_alias:\n                return instantiate_type_alias(\n                    info.special_alias,\n                    # TODO: should we allow TypedDicts generic in ParamSpec?\n                    self.anal_array(args, allow_unpack=True),\n                    self.fail,\n                    False,\n                    ctx,\n                    self.options,\n                    use_standard_error=True,\n                )\n            # Create a named TypedDictType\n            return td.copy_modified(\n                item_types=self.anal_array(list(td.items.values())), fallback=instance\n            )\n\n        if info.fullname == \"types.NoneType\":\n            self.fail(\n                \"NoneType should not be used as a type, please use None instead\",\n                ctx,\n                code=codes.NONETYPE_TYPE,\n            )\n            return NoneType(ctx.line, ctx.column)\n\n        return instance\n\n    def analyze_unbound_type_without_type_info(\n        self, t: UnboundType, sym: SymbolTableNode, defining_literal: bool\n    ) -> Type:\n        \"\"\"Figure out what an unbound type that doesn't refer to a TypeInfo node means.\n\n        This is something unusual. We try our best to find out what it is.\n        \"\"\"\n        name = sym.fullname\n        if name is None:\n            assert sym.node is not None\n            name = sym.node.name\n        # Option 1:\n        # Something with an Any type -- make it an alias for Any in a type\n        # context. This is slightly problematic as it allows using the type 'Any'\n        # as a base class -- however, this will fail soon at runtime so the problem\n        # is pretty minor.\n        if isinstance(sym.node, Var):\n            typ = get_proper_type(sym.node.type)\n            if isinstance(typ, AnyType):\n                return AnyType(\n                    TypeOfAny.from_unimported_type, missing_import_name=typ.missing_import_name\n                )\n            elif self.allow_type_any:\n                if isinstance(typ, Instance) and typ.type.fullname == \"builtins.type\":\n                    return AnyType(TypeOfAny.special_form)\n                if isinstance(typ, TypeType) and isinstance(typ.item, AnyType):\n                    return AnyType(TypeOfAny.from_another_any, source_any=typ.item)\n        # Option 2:\n        # Unbound type variable. Currently these may be still valid,\n        # for example when defining a generic type alias.\n        unbound_tvar = (\n            isinstance(sym.node, (TypeVarExpr, TypeVarTupleExpr))\n            and self.tvar_scope.get_binding(sym) is None\n        )\n        if self.allow_unbound_tvars and unbound_tvar:\n            return t\n\n        # Option 3:\n        # Enum value. Note: we only want to return a LiteralType when\n        # we're using this enum value specifically within context of\n        # a \"Literal[...]\" type. So, if `defining_literal` is not set,\n        # we bail out early with an error.\n        #\n        # If, in the distant future, we decide to permit things like\n        # `def foo(x: Color.RED) -> None: ...`, we can remove that\n        # check entirely.\n        if (\n            isinstance(sym.node, Var)\n            and sym.node.info\n            and sym.node.info.is_enum\n            and sym.node.name in sym.node.info.enum_members\n        ):\n            value = sym.node.name\n            base_enum_short_name = sym.node.info.name\n            if not defining_literal:\n                msg = message_registry.INVALID_TYPE_RAW_ENUM_VALUE.format(\n                    base_enum_short_name, value\n                )\n                self.fail(msg.value, t, code=msg.code)\n                return AnyType(TypeOfAny.from_error)\n            return LiteralType(\n                value=value,\n                fallback=Instance(sym.node.info, [], line=t.line, column=t.column),\n                line=t.line,\n                column=t.column,\n            )\n\n        # None of the above options worked. We parse the args (if there are any)\n        # to make sure there are no remaining semanal-only types, then give up.\n        t = t.copy_modified(args=self.anal_array(t.args))\n        # TODO: Move this message building logic to messages.py.\n        notes: list[str] = []\n        error_code = codes.VALID_TYPE\n        if isinstance(sym.node, Var):\n            notes.append(\n                \"See https://mypy.readthedocs.io/en/\"\n                \"stable/common_issues.html#variables-vs-type-aliases\"\n            )\n            message = 'Variable \"{}\" is not valid as a type'\n        elif isinstance(sym.node, (SYMBOL_FUNCBASE_TYPES, Decorator)):\n            message = 'Function \"{}\" is not valid as a type'\n            if name == \"builtins.any\":\n                notes.append('Perhaps you meant \"typing.Any\" instead of \"any\"?')\n            elif name == \"builtins.callable\":\n                notes.append('Perhaps you meant \"typing.Callable\" instead of \"callable\"?')\n            else:\n                notes.append('Perhaps you need \"Callable[...]\" or a callback protocol?')\n        elif isinstance(sym.node, MypyFile):\n            message = 'Module \"{}\" is not valid as a type'\n            notes.append(\"Perhaps you meant to use a protocol matching the module structure?\")\n        elif unbound_tvar:\n            assert isinstance(sym.node, TypeVarLikeExpr)\n            if sym.node.is_new_style:\n                # PEP 695 type parameters are never considered unbound -- they are undefined\n                # in contexts where they aren't valid, such as in argument default values.\n                message = 'Name \"{}\" is not defined'\n                name = name.split(\".\")[-1]\n                error_code = codes.NAME_DEFINED\n            else:\n                message = 'Type variable \"{}\" is unbound'\n                short = name.split(\".\")[-1]\n                notes.append(\n                    f'(Hint: Use \"Generic[{short}]\" or \"Protocol[{short}]\" base class'\n                    f' to bind \"{short}\" inside a class)'\n                )\n                notes.append(\n                    f'(Hint: Use \"{short}\" in function signature '\n                    f'to bind \"{short}\" inside a function)'\n                )\n        else:\n            message = 'Cannot interpret reference \"{}\" as a type'\n        if not defining_literal:\n            # Literal check already gives a custom error. Avoid duplicating errors.\n            self.fail(message.format(name), t, code=error_code)\n            for note in notes:\n                self.note(note, t, code=error_code)\n\n        # TODO: Would it be better to always return Any instead of UnboundType\n        # in case of an error? On one hand, UnboundType has a name so error messages\n        # are more detailed, on the other hand, some of them may be bogus,\n        # see https://github.com/python/mypy/issues/4987.\n        return t\n\n    def visit_any(self, t: AnyType) -> Type:\n        return t\n\n    def visit_none_type(self, t: NoneType) -> Type:\n        return t\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> Type:\n        return t\n\n    def visit_erased_type(self, t: ErasedType) -> Type:\n        # This type should exist only temporarily during type inference\n        assert False, \"Internal error: Unexpected erased type\"\n\n    def visit_deleted_type(self, t: DeletedType) -> Type:\n        return t\n\n    def visit_type_list(self, t: TypeList) -> Type:\n        # Parameters literal (Z[[int, str, Whatever]])\n        if self.allow_param_spec_literals:\n            params = self.analyze_callable_args(t)\n            if params:\n                ts, kinds, names = params\n                # bind these types\n                return Parameters(self.anal_array(ts), kinds, names, line=t.line, column=t.column)\n            else:\n                return AnyType(TypeOfAny.from_error)\n        else:\n            self.fail(\n                'Bracketed expression \"[...]\" is not valid as a type', t, code=codes.VALID_TYPE\n            )\n            if len(t.items) == 1:\n                self.note('Did you mean \"List[...]\"?', t)\n            return AnyType(TypeOfAny.from_error)\n\n    def visit_callable_argument(self, t: CallableArgument) -> Type:\n        self.fail(\"Invalid type\", t, code=codes.VALID_TYPE)\n        return AnyType(TypeOfAny.from_error)\n\n    def visit_instance(self, t: Instance) -> Type:\n        return t\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        # TODO: should we do something here?\n        return t\n\n    def visit_type_var(self, t: TypeVarType) -> Type:\n        return t\n\n    def visit_param_spec(self, t: ParamSpecType) -> Type:\n        return t\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> Type:\n        return t\n\n    def visit_unpack_type(self, t: UnpackType) -> Type:\n        if not self.allow_unpack:\n            self.fail(message_registry.INVALID_UNPACK_POSITION, t.type, code=codes.VALID_TYPE)\n            return AnyType(TypeOfAny.from_error)\n        self.allow_type_var_tuple = True\n        result = UnpackType(self.anal_type(t.type), from_star_syntax=t.from_star_syntax)\n        self.allow_type_var_tuple = False\n        return result\n\n    def visit_parameters(self, t: Parameters) -> Type:\n        raise NotImplementedError(\"ParamSpec literals cannot have unbound TypeVars\")\n\n    def visit_callable_type(\n        self, t: CallableType, nested: bool = True, namespace: str = \"\"\n    ) -> Type:\n        # Every Callable can bind its own type variables, if they're not in the outer scope\n        # TODO: attach namespace for nested free type variables (these appear in return type only).\n        with self.tvar_scope_frame(namespace=namespace):\n            unpacked_kwargs = t.unpack_kwargs\n            if self.defining_alias:\n                variables = t.variables\n            else:\n                variables, _ = self.bind_function_type_variables(t, t)\n            type_guard = self.anal_type_guard(t.ret_type) if t.type_guard is None else t.type_guard\n            type_is = self.anal_type_is(t.ret_type) if t.type_is is None else t.type_is\n\n            arg_kinds = t.arg_kinds\n            arg_types = []\n            param_spec_with_args = param_spec_with_kwargs = None\n            param_spec_invalid = False\n            for kind, ut in zip(arg_kinds, t.arg_types):\n                if kind == ARG_STAR:\n                    param_spec_with_args, at = self.anal_star_arg_type(ut, kind, nested=nested)\n                elif kind == ARG_STAR2:\n                    param_spec_with_kwargs, at = self.anal_star_arg_type(ut, kind, nested=nested)\n                else:\n                    if param_spec_with_args:\n                        param_spec_invalid = True\n                        self.fail(\n                            \"Arguments not allowed after ParamSpec.args\", t, code=codes.VALID_TYPE\n                        )\n                    at = self.anal_type(ut, nested=nested, allow_unpack=False)\n                arg_types.append(at)\n\n            if nested and arg_types:\n                # If we've got a Callable[[Unpack[SomeTypedDict]], None], make sure\n                # Unpack is interpreted as `**` and not as `*`.\n                last = arg_types[-1]\n                if isinstance(last, UnpackType):\n                    # TODO: it would be better to avoid this get_proper_type() call.\n                    p_at = get_proper_type(last.type)\n                    if isinstance(p_at, TypedDictType) and not last.from_star_syntax:\n                        # Automatically detect Unpack[Foo] in Callable as backwards\n                        # compatible syntax for **Foo, if Foo is a TypedDict.\n                        arg_kinds[-1] = ARG_STAR2\n                        arg_types[-1] = p_at\n                        unpacked_kwargs = True\n                arg_types = self.check_unpacks_in_list(arg_types)\n\n            if not param_spec_invalid and param_spec_with_args != param_spec_with_kwargs:\n                # If already invalid, do not report more errors - definition has\n                # to be fixed anyway\n                name = param_spec_with_args or param_spec_with_kwargs\n                self.fail(\n                    f'ParamSpec must have \"*args\" typed as \"{name}.args\" and \"**kwargs\" typed as \"{name}.kwargs\"',\n                    t,\n                    code=codes.VALID_TYPE,\n                )\n                param_spec_invalid = True\n\n            if param_spec_invalid:\n                if ARG_STAR in arg_kinds:\n                    arg_types[arg_kinds.index(ARG_STAR)] = AnyType(TypeOfAny.from_error)\n                if ARG_STAR2 in arg_kinds:\n                    arg_types[arg_kinds.index(ARG_STAR2)] = AnyType(TypeOfAny.from_error)\n\n            # If there were multiple (invalid) unpacks, the arg types list will become shorter,\n            # we need to trim the kinds/names as well to avoid crashes.\n            arg_kinds = t.arg_kinds[: len(arg_types)]\n            arg_names = t.arg_names[: len(arg_types)]\n\n            ret = t.copy_modified(\n                arg_types=arg_types,\n                arg_kinds=arg_kinds,\n                arg_names=arg_names,\n                ret_type=self.anal_type(t.ret_type, nested=nested),\n                # If the fallback isn't filled in yet,\n                # its type will be the falsey FakeInfo\n                fallback=(t.fallback if t.fallback.type else self.named_type(\"builtins.function\")),\n                variables=self.anal_var_defs(variables),\n                type_guard=type_guard,\n                type_is=type_is,\n                unpack_kwargs=unpacked_kwargs,\n            )\n        return ret\n\n    def anal_type_guard(self, t: Type) -> Type | None:\n        if isinstance(t, UnboundType):\n            sym = self.lookup_qualified(t.name, t)\n            if sym is not None and sym.node is not None:\n                return self.anal_type_guard_arg(t, sym.node.fullname)\n        # TODO: What if it's an Instance? Then use t.type.fullname?\n        return None\n\n    def anal_type_guard_arg(self, t: UnboundType, fullname: str) -> Type | None:\n        if fullname in (\"typing_extensions.TypeGuard\", \"typing.TypeGuard\"):\n            if len(t.args) != 1:\n                self.fail(\n                    \"TypeGuard must have exactly one type argument\", t, code=codes.VALID_TYPE\n                )\n                return AnyType(TypeOfAny.from_error)\n            return self.anal_type(t.args[0])\n        return None\n\n    def anal_type_is(self, t: Type) -> Type | None:\n        if isinstance(t, UnboundType):\n            sym = self.lookup_qualified(t.name, t)\n            if sym is not None and sym.node is not None:\n                return self.anal_type_is_arg(t, sym.node.fullname)\n        # TODO: What if it's an Instance? Then use t.type.fullname?\n        return None\n\n    def anal_type_is_arg(self, t: UnboundType, fullname: str) -> Type | None:\n        if fullname in (\"typing_extensions.TypeIs\", \"typing.TypeIs\"):\n            if len(t.args) != 1:\n                self.fail(\"TypeIs must have exactly one type argument\", t, code=codes.VALID_TYPE)\n                return AnyType(TypeOfAny.from_error)\n            return self.anal_type(t.args[0])\n        return None\n\n    def anal_star_arg_type(self, t: Type, kind: ArgKind, nested: bool) -> tuple[str | None, Type]:\n        \"\"\"Analyze signature argument type for *args and **kwargs argument.\"\"\"\n        if isinstance(t, UnboundType) and t.name and \".\" in t.name and not t.args:\n            components = t.name.split(\".\")\n            tvar_name = \".\".join(components[:-1])\n            sym = self.lookup_qualified(tvar_name, t)\n            if sym is not None and isinstance(sym.node, ParamSpecExpr):\n                tvar_def = self.tvar_scope.get_binding(sym)\n                if isinstance(tvar_def, ParamSpecType):\n                    if kind == ARG_STAR:\n                        make_paramspec = paramspec_args\n                        if components[-1] != \"args\":\n                            self.fail(\n                                f'Use \"{tvar_name}.args\" for variadic \"*\" parameter',\n                                t,\n                                code=codes.VALID_TYPE,\n                            )\n                    elif kind == ARG_STAR2:\n                        make_paramspec = paramspec_kwargs\n                        if components[-1] != \"kwargs\":\n                            self.fail(\n                                f'Use \"{tvar_name}.kwargs\" for variadic \"**\" parameter',\n                                t,\n                                code=codes.VALID_TYPE,\n                            )\n                    else:\n                        assert False, kind\n                    return tvar_name, make_paramspec(\n                        tvar_def.name,\n                        tvar_def.fullname,\n                        tvar_def.id,\n                        named_type_func=self.named_type,\n                        line=t.line,\n                        column=t.column,\n                    )\n        return None, self.anal_type(t, nested=nested, allow_unpack=True)\n\n    def visit_overloaded(self, t: Overloaded) -> Type:\n        # Overloaded types are manually constructed in semanal.py by analyzing the\n        # AST and combining together the Callable types this visitor converts.\n        #\n        # So if we're ever asked to reanalyze an Overloaded type, we know it's\n        # fine to just return it as-is.\n        return t\n\n    def visit_tuple_type(self, t: TupleType) -> Type:\n        # Types such as (t1, t2, ...) only allowed in assignment statements. They'll\n        # generate errors elsewhere, and Tuple[t1, t2, ...] must be used instead.\n        if t.implicit and not self.allow_tuple_literal:\n            self.fail(\"Syntax error in type annotation\", t, code=codes.SYNTAX)\n            if len(t.items) == 0:\n                self.note(\n                    \"Suggestion: Use Tuple[()] instead of () for an empty tuple, or \"\n                    \"None for a function without a return value\",\n                    t,\n                    code=codes.SYNTAX,\n                )\n            elif len(t.items) == 1:\n                self.note(\"Suggestion: Is there a spurious trailing comma?\", t, code=codes.SYNTAX)\n            else:\n                self.note(\n                    \"Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\",\n                    t,\n                    code=codes.SYNTAX,\n                )\n            return AnyType(TypeOfAny.from_error)\n\n        any_type = AnyType(TypeOfAny.special_form)\n        # If the fallback isn't filled in yet, its type will be the falsey FakeInfo\n        fallback = (\n            t.partial_fallback\n            if t.partial_fallback.type\n            else self.named_type(\"builtins.tuple\", [any_type])\n        )\n        return TupleType(self.anal_array(t.items, allow_unpack=True), fallback, t.line)\n\n    def visit_typeddict_type(self, t: TypedDictType) -> Type:\n        req_keys = set()\n        readonly_keys = set()\n        items = {}\n        for item_name, item_type in t.items.items():\n            # TODO: rework\n            analyzed = self.anal_type(item_type, allow_typed_dict_special_forms=True)\n            if isinstance(analyzed, RequiredType):\n                if analyzed.required:\n                    req_keys.add(item_name)\n                analyzed = analyzed.item\n            else:\n                # Keys are required by default.\n                req_keys.add(item_name)\n            if isinstance(analyzed, ReadOnlyType):\n                readonly_keys.add(item_name)\n                analyzed = analyzed.item\n            items[item_name] = analyzed\n        if t.fallback.type is MISSING_FALLBACK:  # anonymous/inline TypedDict\n            if INLINE_TYPEDDICT not in self.options.enable_incomplete_feature:\n                self.fail(\n                    \"Inline TypedDict is experimental,\"\n                    \" must be enabled with --enable-incomplete-feature=InlineTypedDict\",\n                    t,\n                )\n            required_keys = req_keys\n            fallback = self.named_type(\"typing._TypedDict\")\n            for typ in t.extra_items_from:\n                analyzed = self.analyze_type(typ)\n                p_analyzed = get_proper_type(analyzed)\n                if not isinstance(p_analyzed, TypedDictType):\n                    if not isinstance(p_analyzed, (AnyType, PlaceholderType)):\n                        self.fail(\"Can only merge-in other TypedDict\", t, code=codes.VALID_TYPE)\n                    continue\n                for sub_item_name, sub_item_type in p_analyzed.items.items():\n                    if sub_item_name in items:\n                        self.fail(TYPEDDICT_OVERRIDE_MERGE.format(sub_item_name), t)\n                        continue\n                    items[sub_item_name] = sub_item_type\n                    if sub_item_name in p_analyzed.required_keys:\n                        req_keys.add(sub_item_name)\n                    if sub_item_name in p_analyzed.readonly_keys:\n                        readonly_keys.add(sub_item_name)\n        else:\n            required_keys = t.required_keys\n            fallback = t.fallback\n        return TypedDictType(items, required_keys, readonly_keys, fallback, t.line, t.column)\n\n    def visit_raw_expression_type(self, t: RawExpressionType) -> Type:\n        # We should never see a bare Literal. We synthesize these raw literals\n        # in the earlier stages of semantic analysis, but those\n        # \"fake literals\" should always be wrapped in an UnboundType\n        # corresponding to 'Literal'.\n        #\n        # Note: if at some point in the distant future, we decide to\n        # make signatures like \"foo(x: 20) -> None\" legal, we can change\n        # this method so it generates and returns an actual LiteralType\n        # instead.\n\n        if self.report_invalid_types:\n            if t.base_type_name in (\"builtins.int\", \"builtins.bool\"):\n                # The only time it makes sense to use an int or bool is inside of\n                # a literal type.\n                msg = f\"Invalid type: try using Literal[{repr(t.literal_value)}] instead?\"\n            elif t.base_type_name in (\"builtins.float\", \"builtins.complex\"):\n                # We special-case warnings for floats and complex numbers.\n                msg = f\"Invalid type: {t.simple_name()} literals cannot be used as a type\"\n            else:\n                # And in all other cases, we default to a generic error message.\n                # Note: the reason why we use a generic error message for strings\n                # but not ints or bools is because whenever we see an out-of-place\n                # string, it's unclear if the user meant to construct a literal type\n                # or just misspelled a regular type. So we avoid guessing.\n                msg = \"Invalid type comment or annotation\"\n\n            self.fail(msg, t, code=codes.VALID_TYPE)\n            if t.note is not None:\n                self.note(t.note, t, code=codes.VALID_TYPE)\n\n        return AnyType(TypeOfAny.from_error, line=t.line, column=t.column)\n\n    def visit_literal_type(self, t: LiteralType) -> Type:\n        return t\n\n    def visit_union_type(self, t: UnionType) -> Type:\n        if (\n            t.uses_pep604_syntax is True\n            and t.is_evaluated is True\n            and not self.always_allow_new_syntax\n            and not self.options.python_version >= (3, 10)\n        ):\n            self.fail(\"X | Y syntax for unions requires Python 3.10\", t, code=codes.SYNTAX)\n        return UnionType(self.anal_array(t.items), t.line, uses_pep604_syntax=t.uses_pep604_syntax)\n\n    def visit_partial_type(self, t: PartialType) -> Type:\n        assert False, \"Internal error: Unexpected partial type\"\n\n    def visit_ellipsis_type(self, t: EllipsisType) -> Type:\n        if self.allow_ellipsis or self.allow_param_spec_literals:\n            any_type = AnyType(TypeOfAny.explicit)\n            return Parameters(\n                [any_type, any_type], [ARG_STAR, ARG_STAR2], [None, None], is_ellipsis_args=True\n            )\n        else:\n            self.fail('Unexpected \"...\"', t)\n            return AnyType(TypeOfAny.from_error)\n\n    def visit_type_type(self, t: TypeType) -> Type:\n        return TypeType.make_normalized(\n            self.anal_type(t.item), line=t.line, is_type_form=t.is_type_form\n        )\n\n    def visit_placeholder_type(self, t: PlaceholderType) -> Type:\n        n = (\n            None\n            # No dot in fullname indicates we are at function scope, and recursive\n            # types are not supported there anyway, so we just give up.\n            if not t.fullname or \".\" not in t.fullname\n            else self.api.lookup_fully_qualified(t.fullname)\n        )\n        if not n or isinstance(n.node, PlaceholderNode):\n            self.api.defer()  # Still incomplete\n            return t\n        else:\n            # TODO: Handle non-TypeInfo\n            assert isinstance(n.node, TypeInfo)\n            return self.analyze_type_with_type_info(n.node, t.args, t, False)\n\n    def analyze_callable_args_for_paramspec(\n        self, callable_args: Type, ret_type: Type, fallback: Instance\n    ) -> CallableType | None:\n        \"\"\"Construct a 'Callable[P, RET]', where P is ParamSpec, return None if we cannot.\"\"\"\n        if not isinstance(callable_args, UnboundType):\n            return None\n        sym = self.lookup_qualified(callable_args.name, callable_args)\n        if sym is None:\n            return None\n        tvar_def = self.tvar_scope.get_binding(sym)\n        if not isinstance(tvar_def, ParamSpecType):\n            if (\n                tvar_def is None\n                and self.allow_unbound_tvars\n                and isinstance(sym.node, ParamSpecExpr)\n            ):\n                # We are analyzing this type in runtime context (e.g. as type application).\n                # If it is not valid as a type in this position an error will be given later.\n                return callable_with_ellipsis(\n                    AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback\n                )\n            return None\n        elif (\n            self.defining_alias\n            and self.not_declared_in_type_params(tvar_def.name)\n            and tvar_def not in self.allowed_alias_tvars\n        ):\n            if self.python_3_12_type_alias:\n                msg = message_registry.TYPE_PARAMETERS_SHOULD_BE_DECLARED.format(\n                    f'\"{tvar_def.name}\"'\n                )\n            else:\n                msg = f'ParamSpec \"{tvar_def.name}\" is not included in type_params'\n            self.fail(msg, callable_args, code=codes.VALID_TYPE)\n            return callable_with_ellipsis(\n                AnyType(TypeOfAny.special_form), ret_type=ret_type, fallback=fallback\n            )\n\n        return CallableType(\n            [\n                paramspec_args(\n                    tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type\n                ),\n                paramspec_kwargs(\n                    tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type\n                ),\n            ],\n            [nodes.ARG_STAR, nodes.ARG_STAR2],\n            [None, None],\n            ret_type=ret_type,\n            fallback=fallback,\n        )\n\n    def analyze_callable_args_for_concatenate(\n        self, callable_args: Type, ret_type: Type, fallback: Instance\n    ) -> CallableType | AnyType | None:\n        \"\"\"Construct a 'Callable[C, RET]', where C is Concatenate[..., P], returning None if we\n        cannot.\n        \"\"\"\n        if not isinstance(callable_args, UnboundType):\n            return None\n        sym = self.lookup_qualified(callable_args.name, callable_args)\n        if sym is None:\n            return None\n        if sym.node is None:\n            return None\n        if sym.node.fullname not in CONCATENATE_TYPE_NAMES:\n            return None\n\n        tvar_def = self.anal_type(callable_args, allow_param_spec=True)\n        if not isinstance(tvar_def, (ParamSpecType, Parameters)):\n            if self.allow_unbound_tvars and isinstance(tvar_def, UnboundType):\n                sym = self.lookup_qualified(tvar_def.name, callable_args)\n                if sym is not None and isinstance(sym.node, ParamSpecExpr):\n                    # We are analyzing this type in runtime context (e.g. as type application).\n                    # If it is not valid as a type in this position an error will be given later.\n                    return callable_with_ellipsis(\n                        AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback\n                    )\n            # Error was already given, so prevent further errors.\n            return AnyType(TypeOfAny.from_error)\n        if isinstance(tvar_def, Parameters):\n            # This comes from Concatenate[int, ...]\n            return CallableType(\n                arg_types=tvar_def.arg_types,\n                arg_names=tvar_def.arg_names,\n                arg_kinds=tvar_def.arg_kinds,\n                ret_type=ret_type,\n                fallback=fallback,\n                from_concatenate=True,\n            )\n\n        # ick, CallableType should take ParamSpecType\n        prefix = tvar_def.prefix\n        # we don't set the prefix here as generic arguments will get updated at some point\n        # in the future. CallableType.param_spec() accounts for this.\n        return CallableType(\n            [\n                *prefix.arg_types,\n                paramspec_args(\n                    tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type\n                ),\n                paramspec_kwargs(\n                    tvar_def.name, tvar_def.fullname, tvar_def.id, named_type_func=self.named_type\n                ),\n            ],\n            [*prefix.arg_kinds, nodes.ARG_STAR, nodes.ARG_STAR2],\n            [*prefix.arg_names, None, None],\n            ret_type=ret_type,\n            fallback=fallback,\n            from_concatenate=True,\n        )\n\n    def analyze_callable_type(self, t: UnboundType) -> Type:\n        fallback = self.named_type(\"builtins.function\")\n        if len(t.args) == 0:\n            # Callable (bare). Treat as Callable[..., Any].\n            any_type = self.get_omitted_any(t)\n            ret = callable_with_ellipsis(any_type, any_type, fallback)\n        elif len(t.args) == 2:\n            callable_args = t.args[0]\n            ret_type = t.args[1]\n            if isinstance(callable_args, TypeList):\n                # Callable[[ARG, ...], RET] (ordinary callable type)\n                analyzed_args = self.analyze_callable_args(callable_args)\n                if analyzed_args is None:\n                    return AnyType(TypeOfAny.from_error)\n                args, kinds, names = analyzed_args\n                ret = CallableType(args, kinds, names, ret_type=ret_type, fallback=fallback)\n            elif isinstance(callable_args, EllipsisType):\n                # Callable[..., RET] (with literal ellipsis; accept arbitrary arguments)\n                ret = callable_with_ellipsis(\n                    AnyType(TypeOfAny.explicit), ret_type=ret_type, fallback=fallback\n                )\n            else:\n                # Callable[P, RET] (where P is ParamSpec)\n                with self.tvar_scope_frame(namespace=\"\"):\n                    # Temporarily bind ParamSpecs to allow code like this:\n                    #     my_fun: Callable[Q, Foo[Q]]\n                    # We usually do this later in visit_callable_type(), but the analysis\n                    # below happens at very early stage.\n                    variables = []\n                    for name, tvar_expr in self.find_type_var_likes(callable_args):\n                        variables.append(\n                            self.tvar_scope.bind_new(name, tvar_expr, self.fail_func, t)\n                        )\n                    maybe_ret = self.analyze_callable_args_for_paramspec(\n                        callable_args, ret_type, fallback\n                    ) or self.analyze_callable_args_for_concatenate(\n                        callable_args, ret_type, fallback\n                    )\n                    if isinstance(maybe_ret, CallableType):\n                        maybe_ret = maybe_ret.copy_modified(variables=variables)\n                if maybe_ret is None:\n                    # Callable[?, RET] (where ? is something invalid)\n                    self.fail(\n                        \"The first argument to Callable must be a \"\n                        'list of types, parameter specification, or \"...\"',\n                        t,\n                        code=codes.VALID_TYPE,\n                    )\n                    self.note(\n                        \"See https://mypy.readthedocs.io/en/stable/kinds_of_types.html#callable-types-and-lambdas\",\n                        t,\n                    )\n                    return AnyType(TypeOfAny.from_error)\n                elif isinstance(maybe_ret, AnyType):\n                    return maybe_ret\n                ret = maybe_ret\n        else:\n            if self.options.disallow_any_generics:\n                self.fail('Please use \"Callable[[<parameters>], <return type>]\"', t)\n            else:\n                self.fail('Please use \"Callable[[<parameters>], <return type>]\" or \"Callable\"', t)\n            return AnyType(TypeOfAny.from_error)\n        assert isinstance(ret, CallableType)\n        return ret.accept(self)\n\n    def refers_to_full_names(self, arg: UnboundType, names: Sequence[str]) -> bool:\n        sym = self.lookup_qualified(arg.name, arg)\n        if sym is not None:\n            if sym.fullname in names:\n                return True\n        return False\n\n    def analyze_callable_args(\n        self, arglist: TypeList\n    ) -> tuple[list[Type], list[ArgKind], list[str | None]] | None:\n        args: list[Type] = []\n        kinds: list[ArgKind] = []\n        names: list[str | None] = []\n        seen_unpack = False\n        unpack_types: list[Type] = []\n        invalid_unpacks: list[Type] = []\n        second_unpack_last = False\n        for i, arg in enumerate(arglist.items):\n            if isinstance(arg, CallableArgument):\n                args.append(arg.typ)\n                names.append(arg.name)\n                if arg.constructor is None:\n                    return None\n                found = self.lookup_qualified(arg.constructor, arg)\n                if found is None:\n                    # Looking it up already put an error message in\n                    return None\n                elif found.fullname not in ARG_KINDS_BY_CONSTRUCTOR:\n                    self.fail(f'Invalid argument constructor \"{found.fullname}\"', arg)\n                    return None\n                else:\n                    assert found.fullname is not None\n                    kind = ARG_KINDS_BY_CONSTRUCTOR[found.fullname]\n                    kinds.append(kind)\n                    if arg.name is not None and kind.is_star():\n                        self.fail(f\"{arg.constructor} arguments should not have names\", arg)\n                        return None\n            elif (\n                isinstance(arg, UnboundType)\n                and self.refers_to_full_names(arg, UNPACK_TYPE_NAMES)\n                or isinstance(arg, UnpackType)\n            ):\n                if seen_unpack:\n                    # Multiple unpacks, preserve them, so we can give an error later.\n                    if i == len(arglist.items) - 1 and not invalid_unpacks:\n                        # Special case: if there are just two unpacks, and the second one appears\n                        # as last type argument, it can be still valid, if the second unpacked type\n                        # is a TypedDict. This should be checked by the caller.\n                        second_unpack_last = True\n                    invalid_unpacks.append(arg)\n                    continue\n                seen_unpack = True\n                unpack_types.append(arg)\n            else:\n                if seen_unpack:\n                    unpack_types.append(arg)\n                else:\n                    args.append(arg)\n                    kinds.append(ARG_POS)\n                    names.append(None)\n        if seen_unpack:\n            if len(unpack_types) == 1:\n                args.append(unpack_types[0])\n            else:\n                first = unpack_types[0]\n                if isinstance(first, UnpackType):\n                    # UnpackType doesn't have its own line/column numbers,\n                    # so use the unpacked type for error messages.\n                    first = first.type\n                args.append(\n                    UnpackType(self.tuple_type(unpack_types, line=first.line, column=first.column))\n                )\n            kinds.append(ARG_STAR)\n            names.append(None)\n        for arg in invalid_unpacks:\n            args.append(arg)\n            kinds.append(ARG_STAR2 if second_unpack_last else ARG_STAR)\n            names.append(None)\n        # Note that arglist below is only used for error context.\n        check_param_names(names, [arglist] * len(args), self.fail, \"Callable\")\n        check_arg_kinds(kinds, [arglist] * len(args), self.fail)\n        return args, kinds, names\n\n    def analyze_literal_type(self, t: UnboundType) -> Type:\n        if len(t.args) == 0:\n            self.fail(\"Literal[...] must have at least one parameter\", t, code=codes.VALID_TYPE)\n            return AnyType(TypeOfAny.from_error)\n\n        output: list[Type] = []\n        for i, arg in enumerate(t.args):\n            analyzed_types = self.analyze_literal_param(i + 1, arg, t)\n            if analyzed_types is None:\n                return AnyType(TypeOfAny.from_error)\n            else:\n                output.extend(analyzed_types)\n        return UnionType.make_union(output, line=t.line)\n\n    def analyze_literal_param(self, idx: int, arg: Type, ctx: Context) -> list[Type] | None:\n        # This UnboundType was originally defined as a string.\n        if (\n            isinstance(arg, ProperType)\n            and isinstance(arg, (UnboundType, UnionType))\n            and arg.original_str_expr is not None\n        ):\n            assert arg.original_str_fallback is not None\n            return [\n                LiteralType(\n                    value=arg.original_str_expr,\n                    fallback=self.named_type(arg.original_str_fallback),\n                    line=arg.line,\n                    column=arg.column,\n                )\n            ]\n\n        # If arg is an UnboundType that was *not* originally defined as\n        # a string, try expanding it in case it's a type alias or something.\n        if isinstance(arg, UnboundType):\n            self.nesting_level += 1\n            try:\n                arg = self.visit_unbound_type(arg, defining_literal=True)\n            finally:\n                self.nesting_level -= 1\n\n        # Literal[...] cannot contain Any. Give up and add an error message\n        # (if we haven't already).\n        arg = get_proper_type(arg)\n        if isinstance(arg, AnyType):\n            # Note: We can encounter Literals containing 'Any' under three circumstances:\n            #\n            # 1. If the user attempts use an explicit Any as a parameter\n            # 2. If the user is trying to use an enum value imported from a module with\n            #    no type hints, giving it an implicit type of 'Any'\n            # 3. If there's some other underlying problem with the parameter.\n            #\n            # We report an error in only the first two cases. In the third case, we assume\n            # some other region of the code has already reported a more relevant error.\n            #\n            # TODO: Once we start adding support for enums, make sure we report a custom\n            # error for case 2 as well.\n            if arg.type_of_any not in (TypeOfAny.from_error, TypeOfAny.special_form):\n                self.fail(\n                    f'Parameter {idx} of Literal[...] cannot be of type \"Any\"',\n                    ctx,\n                    code=codes.VALID_TYPE,\n                )\n            return None\n        elif isinstance(arg, RawExpressionType):\n            # A raw literal. Convert it directly into a literal if we can.\n            if arg.literal_value is None:\n                name = arg.simple_name()\n                if name in (\"float\", \"complex\"):\n                    msg = f'Parameter {idx} of Literal[...] cannot be of type \"{name}\"'\n                else:\n                    msg = \"Invalid type: Literal[...] cannot contain arbitrary expressions\"\n                self.fail(msg, ctx, code=codes.VALID_TYPE)\n                # Note: we deliberately ignore arg.note here: the extra info might normally be\n                # helpful, but it generally won't make sense in the context of a Literal[...].\n                return None\n\n            # Remap bytes and unicode into the appropriate type for the correct Python version\n            fallback = self.named_type(arg.base_type_name)\n            assert isinstance(fallback, Instance)\n            return [LiteralType(arg.literal_value, fallback, line=arg.line, column=arg.column)]\n        elif isinstance(arg, (NoneType, LiteralType)):\n            # Types that we can just add directly to the literal/potential union of literals.\n            return [arg]\n        elif isinstance(arg, Instance) and arg.last_known_value is not None:\n            # Types generated from declarations like \"var: Final = 4\".\n            return [arg.last_known_value]\n        elif isinstance(arg, UnionType):\n            out = []\n            for union_arg in arg.items:\n                union_result = self.analyze_literal_param(idx, union_arg, ctx)\n                if union_result is None:\n                    return None\n                out.extend(union_result)\n            return out\n        else:\n            self.fail(f\"Parameter {idx} of Literal[...] is invalid\", ctx, code=codes.VALID_TYPE)\n            return None\n\n    def analyze_type(self, typ: Type) -> Type:\n        return typ.accept(self)\n\n    def fail(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:\n        self.fail_func(msg, ctx, code=code)\n\n    def note(self, msg: str, ctx: Context, *, code: ErrorCode | None = None) -> None:\n        self.note_func(msg, ctx, code=code)\n\n    @contextmanager\n    def tvar_scope_frame(self, namespace: str) -> Iterator[None]:\n        old_scope = self.tvar_scope\n        self.tvar_scope = self.tvar_scope.method_frame(namespace)\n        yield\n        self.tvar_scope = old_scope\n\n    def find_type_var_likes(self, t: Type) -> TypeVarLikeList:\n        visitor = FindTypeVarVisitor(self.api, self.tvar_scope)\n        t.accept(visitor)\n        return visitor.type_var_likes\n\n    def infer_type_variables(\n        self, type: CallableType\n    ) -> tuple[list[tuple[str, TypeVarLikeExpr]], bool]:\n        \"\"\"Infer type variables from a callable.\n\n        Return tuple with these items:\n         - list of unique type variables referred to in a callable\n         - whether there is a reference to the Self type\n        \"\"\"\n        visitor = FindTypeVarVisitor(self.api, self.tvar_scope)\n        for arg in type.arg_types:\n            arg.accept(visitor)\n\n        # When finding type variables in the return type of a function, don't\n        # look inside Callable types.  Type variables only appearing in\n        # functions in the return type belong to those functions, not the\n        # function we're currently analyzing.\n        visitor.include_callables = False\n        type.ret_type.accept(visitor)\n\n        return visitor.type_var_likes, visitor.has_self_type\n\n    def bind_function_type_variables(\n        self, fun_type: CallableType, defn: Context\n    ) -> tuple[tuple[TypeVarLikeType, ...], bool]:\n        \"\"\"Find the type variables of the function type and bind them in our tvar_scope\"\"\"\n        has_self_type = False\n        if fun_type.variables:\n            defs = []\n            for var in fun_type.variables:\n                if self.api.type and self.api.type.self_type and var == self.api.type.self_type:\n                    has_self_type = True\n                    continue\n                var_node = self.lookup_qualified(var.name, defn)\n                assert var_node, \"Binding for function type variable not found within function\"\n                var_expr = var_node.node\n                assert isinstance(var_expr, TypeVarLikeExpr)\n                binding = self.tvar_scope.bind_new(var.name, var_expr, self.fail_func, fun_type)\n                defs.append(binding)\n            return tuple(defs), has_self_type\n        typevars, has_self_type = self.infer_type_variables(fun_type)\n        # Do not define a new type variable if already defined in scope.\n        typevars = [\n            (name, tvar) for name, tvar in typevars if not self.is_defined_type_var(name, defn)\n        ]\n        defs = []\n        for name, tvar in typevars:\n            if not self.tvar_scope.allow_binding(tvar.fullname):\n                err_msg = message_registry.TYPE_VAR_REDECLARED_IN_NESTED_CLASS.format(name)\n                self.fail(err_msg.value, defn, code=err_msg.code)\n            binding = self.tvar_scope.bind_new(name, tvar, self.fail_func, fun_type)\n            defs.append(binding)\n\n        return tuple(defs), has_self_type\n\n    def is_defined_type_var(self, tvar: str, context: Context) -> bool:\n        tvar_node = self.lookup_qualified(tvar, context)\n        if not tvar_node:\n            return False\n        return self.tvar_scope.get_binding(tvar_node) is not None\n\n    def anal_array(\n        self,\n        a: Iterable[Type],\n        nested: bool = True,\n        *,\n        allow_param_spec: bool = False,\n        allow_param_spec_literals: bool = False,\n        allow_unpack: bool = False,\n    ) -> list[Type]:\n        old_allow_param_spec_literals = self.allow_param_spec_literals\n        self.allow_param_spec_literals = allow_param_spec_literals\n        res: list[Type] = []\n        for t in a:\n            res.append(\n                self.anal_type(\n                    t, nested, allow_param_spec=allow_param_spec, allow_unpack=allow_unpack\n                )\n            )\n        self.allow_param_spec_literals = old_allow_param_spec_literals\n        return self.check_unpacks_in_list(res)\n\n    def anal_type(\n        self,\n        t: Type,\n        nested: bool = True,\n        *,\n        allow_param_spec: bool = False,\n        allow_unpack: bool = False,\n        allow_ellipsis: bool = False,\n        allow_typed_dict_special_forms: bool = False,\n        allow_final: bool = False,\n    ) -> Type:\n        if nested:\n            self.nesting_level += 1\n        old_allow_typed_dict_special_forms = self.allow_typed_dict_special_forms\n        self.allow_typed_dict_special_forms = allow_typed_dict_special_forms\n        self.allow_final = allow_final\n        old_allow_ellipsis = self.allow_ellipsis\n        self.allow_ellipsis = allow_ellipsis\n        old_allow_unpack = self.allow_unpack\n        self.allow_unpack = allow_unpack\n        try:\n            analyzed = t.accept(self)\n        finally:\n            if nested:\n                self.nesting_level -= 1\n            self.allow_typed_dict_special_forms = old_allow_typed_dict_special_forms\n            self.allow_ellipsis = old_allow_ellipsis\n            self.allow_unpack = old_allow_unpack\n        if (\n            not allow_param_spec\n            and isinstance(analyzed, ParamSpecType)\n            and analyzed.flavor == ParamSpecFlavor.BARE\n        ):\n            if analyzed.prefix.arg_types:\n                self.fail(\"Invalid location for Concatenate\", t, code=codes.VALID_TYPE)\n                self.note(\"You can use Concatenate as the first argument to Callable\", t)\n                analyzed = AnyType(TypeOfAny.from_error)\n            else:\n                self.fail(\n                    INVALID_PARAM_SPEC_LOCATION.format(format_type(analyzed, self.options)),\n                    t,\n                    code=codes.VALID_TYPE,\n                )\n                self.note(\n                    INVALID_PARAM_SPEC_LOCATION_NOTE.format(analyzed.name),\n                    t,\n                    code=codes.VALID_TYPE,\n                )\n                analyzed = AnyType(TypeOfAny.from_error)\n        return analyzed\n\n    def anal_var_def(self, var_def: TypeVarLikeType) -> TypeVarLikeType:\n        if isinstance(var_def, TypeVarType):\n            return TypeVarType(\n                name=var_def.name,\n                fullname=var_def.fullname,\n                id=var_def.id,\n                values=self.anal_array(var_def.values),\n                upper_bound=var_def.upper_bound.accept(self),\n                default=var_def.default.accept(self),\n                variance=var_def.variance,\n                line=var_def.line,\n                column=var_def.column,\n            )\n        else:\n            return var_def\n\n    def anal_var_defs(self, var_defs: Sequence[TypeVarLikeType]) -> list[TypeVarLikeType]:\n        return [self.anal_var_def(vd) for vd in var_defs]\n\n    def named_type(\n        self, fullname: str, args: list[Type] | None = None, line: int = -1, column: int = -1\n    ) -> Instance:\n        node = self.lookup_fully_qualified(fullname)\n        assert isinstance(node.node, TypeInfo)\n        any_type = AnyType(TypeOfAny.special_form)\n        if args is not None:\n            args = self.check_unpacks_in_list(args)\n        return Instance(\n            node.node, args or [any_type] * len(node.node.defn.type_vars), line=line, column=column\n        )\n\n    def check_unpacks_in_list(self, items: list[Type]) -> list[Type]:\n        new_items: list[Type] = []\n        num_unpacks = 0\n        final_unpack = None\n        for item in items:\n            # TODO: handle forward references here, they appear as Unpack[Any].\n            if isinstance(item, UnpackType) and not isinstance(\n                get_proper_type(item.type), TupleType\n            ):\n                if not num_unpacks:\n                    new_items.append(item)\n                num_unpacks += 1\n                final_unpack = item\n            else:\n                new_items.append(item)\n\n        if num_unpacks > 1:\n            assert final_unpack is not None\n            self.fail(\"More than one variadic Unpack in a type is not allowed\", final_unpack.type)\n        return new_items\n\n    def tuple_type(self, items: list[Type], line: int, column: int) -> TupleType:\n        any_type = AnyType(TypeOfAny.special_form)\n        return TupleType(\n            items, fallback=self.named_type(\"builtins.tuple\", [any_type]), line=line, column=column\n        )\n\n\nTypeVarLikeList = list[tuple[str, TypeVarLikeExpr]]\n\n\nclass MsgCallback(Protocol):\n    def __call__(\n        self, __msg: str, __ctx: Context, *, code: ErrorCode | None = None\n    ) -> ErrorInfo | None: ...\n\n\ndef get_omitted_any(\n    disallow_any: bool,\n    fail: MsgCallback,\n    note: MsgCallback,\n    orig_type: Type,\n    options: Options,\n    fullname: str | None = None,\n    unexpanded_type: Type | None = None,\n) -> AnyType:\n    if disallow_any:\n        typ = unexpanded_type or orig_type\n        type_str = typ.name if isinstance(typ, UnboundType) else format_type_bare(typ, options)\n\n        fail(\n            message_registry.BARE_GENERIC.format(quote_type_string(type_str)),\n            typ,\n            code=codes.TYPE_ARG,\n        )\n\n        any_type = AnyType(TypeOfAny.from_error, line=typ.line, column=typ.column)\n    else:\n        any_type = AnyType(\n            TypeOfAny.from_omitted_generics, line=orig_type.line, column=orig_type.column\n        )\n    return any_type\n\n\ndef fix_type_var_tuple_argument(t: Instance) -> None:\n    if t.type.has_type_var_tuple_type:\n        args = list(t.args)\n        assert t.type.type_var_tuple_prefix is not None\n        tvt = t.type.defn.type_vars[t.type.type_var_tuple_prefix]\n        assert isinstance(tvt, TypeVarTupleType)\n        args[t.type.type_var_tuple_prefix] = UnpackType(\n            Instance(tvt.tuple_fallback.type, [args[t.type.type_var_tuple_prefix]])\n        )\n        t.args = tuple(args)\n\n\ndef fix_instance(\n    t: Instance,\n    fail: MsgCallback,\n    note: MsgCallback,\n    disallow_any: bool,\n    options: Options,\n    use_generic_error: bool = False,\n    unexpanded_type: Type | None = None,\n) -> None:\n    \"\"\"Fix a malformed instance by replacing all type arguments with TypeVar default or Any.\n\n    Also emit a suitable error if this is not due to implicit Any's.\n    \"\"\"\n    arg_count = len(t.args)\n    min_tv_count = sum(not tv.has_default() for tv in t.type.defn.type_vars)\n    max_tv_count = len(t.type.type_vars)\n    if arg_count < min_tv_count or arg_count > max_tv_count:\n        # Don't use existing args if arg_count doesn't match\n        if arg_count > max_tv_count:\n            # Already wrong arg count error, don't emit missing type parameters error as well.\n            disallow_any = False\n        t.args = ()\n\n    args: list[Type] = [*(t.args[:max_tv_count])]\n    any_type: AnyType | None = None\n    env: dict[TypeVarId, Type] = {}\n\n    for tv, arg in itertools.zip_longest(t.type.defn.type_vars, t.args, fillvalue=None):\n        if tv is None:\n            continue\n        if arg is None:\n            if tv.has_default():\n                arg = tv.default\n            else:\n                if any_type is None:\n                    fullname = None if use_generic_error else t.type.fullname\n                    any_type = get_omitted_any(\n                        disallow_any, fail, note, t, options, fullname, unexpanded_type\n                    )\n                arg = any_type\n            args.append(arg)\n        env[tv.id] = arg\n    t.args = tuple(args)\n    fix_type_var_tuple_argument(t)\n    if not t.type.has_type_var_tuple_type:\n        with state.strict_optional_set(options.strict_optional):\n            fixed = expand_type(t, env)\n        assert isinstance(fixed, Instance)\n        t.args = fixed.args\n\n\ndef instantiate_type_alias(\n    node: TypeAlias,\n    args: list[Type],\n    fail: MsgCallback,\n    no_args: bool,\n    ctx: Context,\n    options: Options,\n    *,\n    unexpanded_type: Type | None = None,\n    disallow_any: bool = False,\n    use_standard_error: bool = False,\n    empty_tuple_index: bool = False,\n) -> Type:\n    \"\"\"Create an instance of a (generic) type alias from alias node and type arguments.\n\n    We are following the rules outlined in TypeAlias docstring.\n    Here:\n        node: type alias node (definition)\n        args: type arguments (types to be substituted in place of type variables\n              when expanding the alias)\n        fail: error reporter callback\n        no_args: whether original definition used a bare generic `A = List`\n        ctx: context where expansion happens\n        unexpanded_type, disallow_any, use_standard_error: used to customize error messages\n    \"\"\"\n    # Type aliases are special, since they can be expanded during semantic analysis,\n    # so we need to normalize them as soon as possible.\n    # TODO: can this cause an infinite recursion?\n    args = flatten_nested_tuples(args)\n    if any(unknown_unpack(a) for a in args):\n        # This type is not ready to be validated, because of unknown total count.\n        # Note that we keep the kind of Any for consistency.\n        return set_any_tvars(node, [], ctx.line, ctx.column, options, special_form=True)\n\n    if (\n        no_args\n        and isinstance(node.target, ProperType)\n        and isinstance(node.target, Instance)\n        and node.target.type.fullname == \"builtins.tuple\"\n        and len(args)\n    ):\n        no_args = False\n\n    max_tv_count = len(node.alias_tvars)\n    act_len = len(args)\n    if (\n        max_tv_count > 0\n        and act_len == 0\n        and not (empty_tuple_index and node.tvar_tuple_index is not None)\n    ):\n        # Interpret bare Alias same as normal generic, i.e., Alias[Any, Any, ...]\n        return set_any_tvars(\n            node,\n            args,\n            ctx.line,\n            ctx.column,\n            options,\n            disallow_any=disallow_any,\n            fail=fail,\n            unexpanded_type=unexpanded_type,\n        )\n    if max_tv_count == 0 and act_len == 0:\n        if no_args:\n            assert isinstance(node.target, Instance)  # type: ignore[misc]\n            # Note: this is the only case where we use an eager expansion. See more info about\n            # no_args aliases like L = List in the docstring for TypeAlias class.\n            return Instance(node.target.type, [], line=ctx.line, column=ctx.column)\n        return TypeAliasType(node, [], line=ctx.line, column=ctx.column)\n    if (\n        max_tv_count == 0\n        and act_len > 0\n        and isinstance(node.target, Instance)  # type: ignore[misc]\n        and no_args\n    ):\n        tp = Instance(node.target.type, args)\n        tp.line = ctx.line\n        tp.column = ctx.column\n        tp.end_line = ctx.end_line\n        tp.end_column = ctx.end_column\n        return tp\n    if node.tvar_tuple_index is None:\n        if any(isinstance(a, UnpackType) for a in args):\n            # A variadic unpack in fixed size alias (fixed unpacks must be flattened by the caller)\n            fail(message_registry.INVALID_UNPACK_POSITION, ctx, code=codes.VALID_TYPE)\n            return set_any_tvars(node, [], ctx.line, ctx.column, options, from_error=True)\n        min_tv_count = sum(not tv.has_default() for tv in node.alias_tvars)\n        fill_typevars = act_len != max_tv_count\n        correct = min_tv_count <= act_len <= max_tv_count\n    else:\n        min_tv_count = sum(\n            not tv.has_default() and not isinstance(tv, TypeVarTupleType)\n            for tv in node.alias_tvars\n        )\n        correct = act_len >= min_tv_count\n        for a in args:\n            if isinstance(a, UnpackType):\n                unpacked = get_proper_type(a.type)\n                if isinstance(unpacked, Instance) and unpacked.type.fullname == \"builtins.tuple\":\n                    # Variadic tuple is always correct.\n                    correct = True\n        fill_typevars = not correct\n    if fill_typevars:\n        if not correct:\n            if use_standard_error:\n                # This is used if type alias is an internal representation of another type,\n                # for example a generic TypedDict or NamedTuple.\n                msg = wrong_type_arg_count(max_tv_count, max_tv_count, str(act_len), node.name)\n            else:\n                if node.tvar_tuple_index is not None:\n                    msg = (\n                        \"Bad number of arguments for type alias,\"\n                        f\" expected at least {min_tv_count}, given {act_len}\"\n                    )\n                elif min_tv_count != max_tv_count:\n                    msg = (\n                        \"Bad number of arguments for type alias,\"\n                        f\" expected between {min_tv_count} and {max_tv_count}, given {act_len}\"\n                    )\n                else:\n                    msg = (\n                        \"Bad number of arguments for type alias,\"\n                        f\" expected {min_tv_count}, given {act_len}\"\n                    )\n            fail(msg, ctx, code=codes.TYPE_ARG)\n            args = []\n        return set_any_tvars(node, args, ctx.line, ctx.column, options, from_error=True)\n    elif node.tvar_tuple_index is not None:\n        # We also need to check if we are not performing a type variable tuple split.\n        unpack = find_unpack_in_list(args)\n        if unpack is not None:\n            unpack_arg = args[unpack]\n            assert isinstance(unpack_arg, UnpackType)\n            if isinstance(unpack_arg.type, TypeVarTupleType):\n                exp_prefix = node.tvar_tuple_index\n                act_prefix = unpack\n                exp_suffix = len(node.alias_tvars) - node.tvar_tuple_index - 1\n                act_suffix = len(args) - unpack - 1\n                if act_prefix < exp_prefix or act_suffix < exp_suffix:\n                    fail(\"TypeVarTuple cannot be split\", ctx, code=codes.TYPE_ARG)\n                    return set_any_tvars(node, [], ctx.line, ctx.column, options, from_error=True)\n    # TODO: we need to check args validity w.r.t alias.alias_tvars.\n    # Otherwise invalid instantiations will be allowed in runtime context.\n    # Note: in type context, these will be still caught by semanal_typeargs.\n    typ = TypeAliasType(node, args, ctx.line, ctx.column)\n    assert typ.alias is not None\n    # HACK: Implement FlexibleAlias[T, typ] by expanding it to typ here.\n    if (\n        isinstance(typ.alias.target, Instance)  # type: ignore[misc]\n        and typ.alias.target.type.fullname == \"mypy_extensions.FlexibleAlias\"\n    ):\n        exp = get_proper_type(typ)\n        assert isinstance(exp, Instance)\n        return exp.args[-1]\n    return typ\n\n\ndef set_any_tvars(\n    node: TypeAlias,\n    args: list[Type],\n    newline: int,\n    newcolumn: int,\n    options: Options,\n    *,\n    from_error: bool = False,\n    disallow_any: bool = False,\n    special_form: bool = False,\n    fail: MsgCallback | None = None,\n    unexpanded_type: Type | None = None,\n) -> TypeAliasType:\n    if from_error or disallow_any:\n        type_of_any = TypeOfAny.from_error\n    elif special_form:\n        type_of_any = TypeOfAny.special_form\n    else:\n        type_of_any = TypeOfAny.from_omitted_generics\n    any_type = AnyType(type_of_any, line=newline, column=newcolumn)\n\n    env: dict[TypeVarId, Type] = {}\n    used_any_type = False\n    has_type_var_tuple_type = False\n    for tv, arg in itertools.zip_longest(node.alias_tvars, args, fillvalue=None):\n        if tv is None:\n            continue\n        if arg is None:\n            if tv.has_default():\n                arg = tv.default\n            else:\n                arg = any_type\n                used_any_type = True\n            if isinstance(tv, TypeVarTupleType):\n                # TODO Handle TypeVarTuple defaults\n                has_type_var_tuple_type = True\n                arg = UnpackType(Instance(tv.tuple_fallback.type, [any_type]))\n            args.append(arg)\n        env[tv.id] = arg\n    t = TypeAliasType(node, args, newline, newcolumn)\n    if not has_type_var_tuple_type:\n        with state.strict_optional_set(options.strict_optional):\n            fixed = expand_type(t, env)\n        assert isinstance(fixed, TypeAliasType)\n        t.args = fixed.args\n\n    if used_any_type and disallow_any and node.alias_tvars:\n        assert fail is not None\n        if unexpanded_type:\n            type_str = (\n                unexpanded_type.name\n                if isinstance(unexpanded_type, UnboundType)\n                else format_type_bare(unexpanded_type, options)\n            )\n        else:\n            type_str = node.name\n\n        fail(\n            message_registry.BARE_GENERIC.format(quote_type_string(type_str)),\n            Context(newline, newcolumn),\n            code=codes.TYPE_ARG,\n        )\n    return t\n\n\nclass DivergingAliasDetector(TrivialSyntheticTypeTranslator):\n    \"\"\"See docstring of detect_diverging_alias() for details.\"\"\"\n\n    # TODO: this doesn't really need to be a translator, but we don't have a trivial visitor.\n    def __init__(\n        self,\n        seen_nodes: set[TypeAlias],\n        lookup: Callable[[str, Context], SymbolTableNode | None],\n        scope: TypeVarLikeScope,\n    ) -> None:\n        super().__init__()\n        self.seen_nodes = seen_nodes\n        self.lookup = lookup\n        self.scope = scope\n        self.diverging = False\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        assert t.alias is not None, f\"Unfixed type alias {t.type_ref}\"\n        if t.alias in self.seen_nodes:\n            for arg in t.args:\n                if not (\n                    isinstance(arg, TypeVarLikeType)\n                    or isinstance(arg, UnpackType)\n                    and isinstance(arg.type, TypeVarLikeType)\n                ) and has_type_vars(arg):\n                    self.diverging = True\n                    return t\n            # All clear for this expansion chain.\n            return t\n        new_nodes = self.seen_nodes | {t.alias}\n        visitor = DivergingAliasDetector(new_nodes, self.lookup, self.scope)\n        _ = get_proper_type(t).accept(visitor)\n        if visitor.diverging:\n            self.diverging = True\n        return t\n\n\ndef detect_diverging_alias(\n    node: TypeAlias,\n    target: Type,\n    lookup: Callable[[str, Context], SymbolTableNode | None],\n    scope: TypeVarLikeScope,\n) -> bool:\n    \"\"\"This detects type aliases that will diverge during type checking.\n\n    For example F = Something[..., F[List[T]]]. At each expansion step this will produce\n    *new* type aliases: e.g. F[List[int]], F[List[List[int]]], etc. So we can't detect\n    recursion. It is a known problem in the literature, recursive aliases and generic types\n    don't always go well together. It looks like there is no known systematic solution yet.\n\n    # TODO: should we handle such aliases using type_recursion counter and some large limit?\n    They may be handy in rare cases, e.g. to express a union of non-mixed nested lists:\n    Nested = Union[T, Nested[List[T]]] ~> Union[T, List[T], List[List[T]], ...]\n    \"\"\"\n    visitor = DivergingAliasDetector({node}, lookup, scope)\n    _ = target.accept(visitor)\n    return visitor.diverging\n\n\ndef check_for_explicit_any(\n    typ: Type | None,\n    options: Options,\n    is_typeshed_stub: bool,\n    msg: MessageBuilder,\n    context: Context,\n) -> None:\n    if options.disallow_any_explicit and not is_typeshed_stub and typ and has_explicit_any(typ):\n        msg.explicit_any(context)\n\n\ndef has_explicit_any(t: Type) -> bool:\n    \"\"\"\n    Whether this type is or type it contains is an Any coming from explicit type annotation\n    \"\"\"\n    return t.accept(HasExplicitAny())\n\n\nclass HasExplicitAny(BoolTypeQuery):\n    def __init__(self) -> None:\n        super().__init__(ANY_STRATEGY)\n\n    def visit_any(self, t: AnyType) -> bool:\n        return t.type_of_any == TypeOfAny.explicit\n\n    def visit_typeddict_type(self, t: TypedDictType) -> bool:\n        # typeddict is checked during TypedDict declaration, so don't typecheck it here.\n        return False\n\n\ndef has_any_from_unimported_type(t: Type) -> bool:\n    \"\"\"Return true if this type is Any because an import was not followed.\n\n    If type t is such Any type or has type arguments that contain such Any type\n    this function will return true.\n    \"\"\"\n    return t.accept(HasAnyFromUnimportedType())\n\n\nclass HasAnyFromUnimportedType(BoolTypeQuery):\n    def __init__(self) -> None:\n        super().__init__(ANY_STRATEGY)\n\n    def visit_any(self, t: AnyType) -> bool:\n        return t.type_of_any == TypeOfAny.from_unimported_type\n\n    def visit_typeddict_type(self, t: TypedDictType) -> bool:\n        # typeddict is checked during TypedDict declaration, so don't typecheck it here\n        return False\n\n\ndef collect_all_inner_types(t: Type) -> list[Type]:\n    \"\"\"\n    Return all types that `t` contains\n    \"\"\"\n    return t.accept(CollectAllInnerTypesQuery())\n\n\nclass CollectAllInnerTypesQuery(TypeQuery[list[Type]]):\n    def query_types(self, types: Iterable[Type]) -> list[Type]:\n        return self.strategy([t.accept(self) for t in types]) + list(types)\n\n    def strategy(self, items: Iterable[list[Type]]) -> list[Type]:\n        return list(itertools.chain.from_iterable(items))\n\n\ndef make_optional_type(t: Type) -> Type:\n    \"\"\"Return the type corresponding to Optional[t].\n\n    Note that we can't use normal union simplification, since this function\n    is called during semantic analysis and simplification only works during\n    type checking.\n    \"\"\"\n    if isinstance(t, ProperType) and isinstance(t, NoneType):\n        return t\n    elif isinstance(t, ProperType) and isinstance(t, UnionType):\n        # Eagerly expanding aliases is not safe during semantic analysis.\n        items = [item for item in t.items if not isinstance(get_proper_type(item), NoneType)]\n        return UnionType(items + [NoneType()], t.line, t.column)\n    else:\n        return UnionType([t, NoneType()], t.line, t.column)\n\n\ndef validate_instance(t: Instance, fail: MsgCallback, indexed: bool) -> bool:\n    \"\"\"Check if this is a well-formed instance with respect to argument count/positions.\"\"\"\n    # TODO: combine logic with instantiate_type_alias().\n    if any(unknown_unpack(a) for a in t.args):\n        # This type is not ready to be validated, because of unknown total count.\n        # TODO: is it OK to fill with TypeOfAny.from_error instead of special form?\n        return False\n    empty_tuple_index = indexed and not t.args\n    if t.type.has_type_var_tuple_type:\n        min_tv_count = sum(\n            not tv.has_default() and not isinstance(tv, TypeVarTupleType)\n            for tv in t.type.defn.type_vars\n        )\n        correct = len(t.args) >= min_tv_count\n        if any(\n            isinstance(a, UnpackType) and isinstance(get_proper_type(a.type), Instance)\n            for a in t.args\n        ):\n            correct = True\n        if not t.args:\n            if not (empty_tuple_index and len(t.type.type_vars) == 1):\n                # The Any arguments should be set by the caller.\n                if empty_tuple_index and min_tv_count:\n                    fail(\n                        f\"At least {min_tv_count} type argument(s) expected, none given\",\n                        t,\n                        code=codes.TYPE_ARG,\n                    )\n                return False\n        elif not correct:\n            fail(\n                f\"Bad number of arguments, expected: at least {min_tv_count}, given: {len(t.args)}\",\n                t,\n                code=codes.TYPE_ARG,\n            )\n            return False\n        else:\n            # We also need to check if we are not performing a type variable tuple split.\n            unpack = find_unpack_in_list(t.args)\n            if unpack is not None:\n                unpack_arg = t.args[unpack]\n                assert isinstance(unpack_arg, UnpackType)\n                if isinstance(unpack_arg.type, TypeVarTupleType):\n                    assert t.type.type_var_tuple_prefix is not None\n                    assert t.type.type_var_tuple_suffix is not None\n                    exp_prefix = t.type.type_var_tuple_prefix\n                    act_prefix = unpack\n                    exp_suffix = t.type.type_var_tuple_suffix\n                    act_suffix = len(t.args) - unpack - 1\n                    if act_prefix < exp_prefix or act_suffix < exp_suffix:\n                        fail(\"TypeVarTuple cannot be split\", t, code=codes.TYPE_ARG)\n                        return False\n    elif any(isinstance(a, UnpackType) for a in t.args):\n        # A variadic unpack in fixed size instance (fixed unpacks must be flattened by the caller)\n        fail(message_registry.INVALID_UNPACK_POSITION, t, code=codes.VALID_TYPE)\n        t.args = ()\n        return False\n    elif len(t.args) != len(t.type.type_vars):\n        # Invalid number of type parameters.\n        arg_count = len(t.args)\n        min_tv_count = sum(not tv.has_default() for tv in t.type.defn.type_vars)\n        max_tv_count = len(t.type.type_vars)\n        if (arg_count or empty_tuple_index) and (\n            arg_count < min_tv_count or arg_count > max_tv_count\n        ):\n            fail(\n                wrong_type_arg_count(min_tv_count, max_tv_count, str(arg_count), t.type.name),\n                t,\n                code=codes.TYPE_ARG,\n            )\n        return False\n    return True\n\n\ndef find_self_type(typ: Type, lookup: Callable[[str], SymbolTableNode | None]) -> bool:\n    return typ.accept(HasSelfType(lookup))\n\n\nclass HasSelfType(BoolTypeQuery):\n    def __init__(self, lookup: Callable[[str], SymbolTableNode | None]) -> None:\n        self.lookup = lookup\n        super().__init__(ANY_STRATEGY)\n\n    def visit_unbound_type(self, t: UnboundType) -> bool:\n        sym = self.lookup(t.name)\n        if sym and sym.fullname in SELF_TYPE_NAMES:\n            return True\n        return super().visit_unbound_type(t)\n\n\ndef unknown_unpack(t: Type) -> bool:\n    \"\"\"Check if a given type is an unpack of an unknown type.\n\n    Unfortunately, there is no robust way to distinguish forward references from\n    genuine undefined names here. But this worked well so far, although it looks\n    quite fragile.\n    \"\"\"\n    if isinstance(t, UnpackType):\n        unpacked = get_proper_type(t.type)\n        if isinstance(unpacked, AnyType) and unpacked.type_of_any == TypeOfAny.special_form:\n            return True\n    return False\n\n\nclass FindTypeVarVisitor(SyntheticTypeVisitor[None]):\n    \"\"\"Type visitor that looks for type variable types and self types.\"\"\"\n\n    def __init__(self, api: SemanticAnalyzerCoreInterface, scope: TypeVarLikeScope) -> None:\n        self.api = api\n        self.scope = scope\n        self.type_var_likes: list[tuple[str, TypeVarLikeExpr]] = []\n        self.has_self_type = False\n        self.include_callables = True\n\n    def _seems_like_callable(self, type: UnboundType) -> bool:\n        if not type.args:\n            return False\n        return isinstance(type.args[0], (EllipsisType, TypeList, ParamSpecType))\n\n    def visit_unbound_type(self, t: UnboundType) -> None:\n        name = t.name\n        node = self.api.lookup_qualified(name, t)\n        if node and node.fullname in SELF_TYPE_NAMES:\n            self.has_self_type = True\n        if (\n            node\n            and isinstance(node.node, TypeVarLikeExpr)\n            and self.scope.get_binding(node) is None\n        ):\n            if (name, node.node) not in self.type_var_likes:\n                self.type_var_likes.append((name, node.node))\n        elif not self.include_callables and self._seems_like_callable(t):\n            if find_self_type(\n                t, lambda name: self.api.lookup_qualified(name, t, suppress_errors=True)\n            ):\n                self.has_self_type = True\n            return\n        elif node and node.fullname in LITERAL_TYPE_NAMES:\n            return\n        elif node and node.fullname in ANNOTATED_TYPE_NAMES and t.args:\n            # Don't query the second argument to Annotated for TypeVars\n            self.process_types([t.args[0]])\n        elif t.args:\n            self.process_types(t.args)\n\n    def visit_type_list(self, t: TypeList) -> None:\n        self.process_types(t.items)\n\n    def visit_callable_argument(self, t: CallableArgument) -> None:\n        t.typ.accept(self)\n\n    def visit_any(self, t: AnyType) -> None:\n        pass\n\n    def visit_uninhabited_type(self, t: UninhabitedType) -> None:\n        pass\n\n    def visit_none_type(self, t: NoneType) -> None:\n        pass\n\n    def visit_erased_type(self, t: ErasedType) -> None:\n        pass\n\n    def visit_deleted_type(self, t: DeletedType) -> None:\n        pass\n\n    def visit_type_var(self, t: TypeVarType) -> None:\n        self.process_types([t.upper_bound, t.default] + t.values)\n\n    def visit_param_spec(self, t: ParamSpecType) -> None:\n        self.process_types([t.upper_bound, t.default, t.prefix])\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> None:\n        self.process_types([t.upper_bound, t.default])\n\n    def visit_unpack_type(self, t: UnpackType) -> None:\n        self.process_types([t.type])\n\n    def visit_parameters(self, t: Parameters) -> None:\n        self.process_types(t.arg_types)\n\n    def visit_partial_type(self, t: PartialType) -> None:\n        pass\n\n    def visit_instance(self, t: Instance) -> None:\n        self.process_types(t.args)\n\n    def visit_callable_type(self, t: CallableType) -> None:\n        # FIX generics\n        self.process_types(t.arg_types)\n        t.ret_type.accept(self)\n\n    def visit_tuple_type(self, t: TupleType) -> None:\n        self.process_types(t.items)\n\n    def visit_typeddict_type(self, t: TypedDictType) -> None:\n        self.process_types(list(t.items.values()))\n\n    def visit_raw_expression_type(self, t: RawExpressionType) -> None:\n        pass\n\n    def visit_literal_type(self, t: LiteralType) -> None:\n        pass\n\n    def visit_union_type(self, t: UnionType) -> None:\n        self.process_types(t.items)\n\n    def visit_overloaded(self, t: Overloaded) -> None:\n        for it in t.items:\n            it.accept(self)\n\n    def visit_type_type(self, t: TypeType) -> None:\n        t.item.accept(self)\n\n    def visit_ellipsis_type(self, t: EllipsisType) -> None:\n        pass\n\n    def visit_placeholder_type(self, t: PlaceholderType) -> None:\n        return self.process_types(t.args)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> None:\n        self.process_types(t.args)\n\n    def process_types(self, types: list[Type] | tuple[Type, ...]) -> None:\n        # Redundant type check helps mypyc.\n        if isinstance(types, list):\n            for t in types:\n                t.accept(self)\n        else:\n            for t in types:\n                t.accept(self)\n\n\nclass TypeVarDefaultTranslator(TrivialSyntheticTypeTranslator):\n    \"\"\"Type translate visitor that replaces UnboundTypes with in-scope TypeVars.\"\"\"\n\n    def __init__(\n        self, api: SemanticAnalyzerInterface, tvar_expr_name: str, context: Context\n    ) -> None:\n        super().__init__()\n        self.api = api\n        self.tvar_expr_name = tvar_expr_name\n        self.context = context\n\n    def visit_unbound_type(self, t: UnboundType) -> Type:\n        sym = self.api.lookup_qualified(t.name, t, suppress_errors=True)\n        if sym is not None:\n            if type_var := self.api.tvar_scope.get_binding(sym):\n                return type_var\n            if isinstance(sym.node, TypeVarLikeExpr):\n                self.api.fail(\n                    f'Type parameter \"{self.tvar_expr_name}\" has a default type '\n                    \"that refers to one or more type variables that are out of scope\",\n                    self.context,\n                )\n                return AnyType(TypeOfAny.from_error)\n        return super().visit_unbound_type(t)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> Type:\n        # TypeAliasTypes are analyzed separately already, just return it\n        return t\n\n\ndef check_vec_type_args(\n    args: tuple[Type, ...] | list[Type], ctx: Context, api: SemanticAnalyzerCoreInterface\n) -> bool:\n    \"\"\"Report an error if type args for 'vec' are invalid.\n\n    Return False on error.\n    \"\"\"\n    ok = True\n    if len(args) != 1:\n        ok = False\n    else:\n        arg = get_proper_type(args[0])\n        if isinstance(arg, Instance):\n            if arg.type.fullname == \"builtins.int\":\n                # A fixed-width integer such as 'i64' must be used instead of plain 'int'\n                ok = False\n        elif isinstance(arg, UnionType):\n            non_optional = None\n            items = [get_proper_type(item) for item in arg.items]\n            if len(items) != 2:\n                ok = False\n            elif isinstance(items[0], NoneType):\n                if not check_vec_type_args([items[1]], ctx, api):\n                    # Error has already been reported so it's fine to return\n                    return False\n                non_optional = items[1]\n            elif isinstance(items[1], NoneType):\n                if not check_vec_type_args([items[0]], ctx, api):\n                    # Error has already been reported so it's fine to return\n                    return False\n                non_optional = items[0]\n            else:\n                ok = False\n            if isinstance(non_optional, Instance) and (\n                non_optional.type.fullname in MYPYC_NATIVE_INT_NAMES\n                or non_optional.type.fullname\n                in (\"builtins.int\", \"builtins.float\", \"builtins.bool\", \"librt.vecs.vec\")\n            ):\n                ok = False\n        elif isinstance(arg, TypeVarType):\n            # Generic vec types aren't supported in type checked Python code, but\n            # they can be provided in libraries implemented in C (e.g. append).\n            if not api.is_stub_file:\n                ok = False\n        else:\n            ok = False\n    if not ok:\n        api.fail('Invalid item type for \"vec\"', ctx)\n    return ok\n"
  },
  {
    "path": "mypy/typeops.py",
    "content": "\"\"\"Miscellaneous type operations and helpers for use during type checking.\n\nNOTE: These must not be accessed from mypy.nodes or mypy.types to avoid import\n      cycles. These must not be called from the semantic analysis main pass\n      since these may assume that MROs are ready.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport itertools\nfrom collections.abc import Callable, Iterable, Sequence\nfrom typing import Any, TypeVar, cast\n\nfrom mypy.checker_state import checker_state\nfrom mypy.copytype import copy_type\nfrom mypy.expandtype import expand_type, expand_type_by_instance\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.nodes import (\n    ARG_POS,\n    ARG_STAR,\n    ARG_STAR2,\n    SYMBOL_FUNCBASE_TYPES,\n    Decorator,\n    Expression,\n    FuncBase,\n    FuncDef,\n    FuncItem,\n    OverloadedFuncDef,\n    StrExpr,\n    SymbolNode,\n    TypeInfo,\n    Var,\n)\nfrom mypy.state import state\nfrom mypy.types import (\n    ELLIPSIS_TYPE_NAMES,\n    NOT_IMPLEMENTED_TYPE_NAMES,\n    AnyType,\n    CallableType,\n    ExtraAttrs,\n    FormalArgument,\n    FunctionLike,\n    Instance,\n    LiteralType,\n    NoneType,\n    NormalizedCallableType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeOfAny,\n    TypeQuery,\n    TypeType,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    flatten_nested_unions,\n    get_proper_type,\n    get_proper_types,\n    remove_dups,\n)\nfrom mypy.typetraverser import TypeTraverserVisitor\nfrom mypy.typevars import fill_typevars\n\n\ndef is_recursive_pair(s: Type, t: Type) -> bool:\n    \"\"\"Is this a pair of recursive types?\n\n    There may be more cases, and we may be forced to use e.g. has_recursive_types()\n    here, but this function is called in very hot code, so we try to keep it simple\n    and return True only in cases we know may have problems.\n    \"\"\"\n    if isinstance(s, TypeAliasType) and s.is_recursive:\n        return (\n            isinstance(get_proper_type(t), (Instance, UnionType))\n            or isinstance(t, TypeAliasType)\n            and t.is_recursive\n            # Tuple types are special, they can cause an infinite recursion even if\n            # the other type is not recursive, because of the tuple fallback that is\n            # calculated \"on the fly\".\n            or isinstance(get_proper_type(s), TupleType)\n        )\n    if isinstance(t, TypeAliasType) and t.is_recursive:\n        return (\n            isinstance(get_proper_type(s), (Instance, UnionType))\n            or isinstance(s, TypeAliasType)\n            and s.is_recursive\n            # Same as above.\n            or isinstance(get_proper_type(t), TupleType)\n        )\n    return False\n\n\ndef tuple_fallback(typ: TupleType) -> Instance:\n    \"\"\"Return fallback type for a tuple.\"\"\"\n    info = typ.partial_fallback.type\n    if info.fullname != \"builtins.tuple\":\n        return typ.partial_fallback\n    items = []\n    for item in typ.items:\n        if isinstance(item, UnpackType):\n            unpacked_type = get_proper_type(item.type)\n            if isinstance(unpacked_type, TypeVarTupleType):\n                unpacked_type = get_proper_type(unpacked_type.upper_bound)\n            if (\n                isinstance(unpacked_type, Instance)\n                and unpacked_type.type.fullname == \"builtins.tuple\"\n            ):\n                items.append(unpacked_type.args[0])\n            else:\n                raise NotImplementedError\n        else:\n            items.append(item)\n    return Instance(\n        info,\n        # Note: flattening recursive unions is dangerous, since it can fool recursive\n        # types optimization in subtypes.py and go into infinite recursion.\n        [make_simplified_union(items, handle_recursive=False)],\n        extra_attrs=typ.partial_fallback.extra_attrs,\n    )\n\n\ndef get_self_type(func: CallableType, def_info: TypeInfo) -> Type | None:\n    default_self = fill_typevars(def_info)\n    if isinstance(get_proper_type(func.ret_type), UninhabitedType):\n        return func.ret_type\n    elif func.arg_types and func.arg_types[0] != default_self and func.arg_kinds[0] == ARG_POS:\n        return func.arg_types[0]\n    else:\n        return None\n\n\ndef type_object_type(info: TypeInfo, named_type: Callable[[str], Instance]) -> ProperType:\n    \"\"\"Return the type of a type object.\n\n    For a generic type G with type variables T and S the type is generally of form\n\n      Callable[..., G[T, S]]\n\n    where ... are argument types for the __init__/__new__ method (without the self\n    argument). Also, the fallback type will be 'type' instead of 'function'.\n    \"\"\"\n    allow_cache = (\n        checker_state.type_checker is not None\n        and checker_state.type_checker.allow_constructor_cache\n    )\n\n    if info.type_object_type is not None:\n        if allow_cache:\n            return info.type_object_type\n        info.type_object_type = None\n\n    # We take the type from whichever of __init__ and __new__ is first\n    # in the MRO, preferring __init__ if there is a tie.\n    init_method = info.get(\"__init__\")\n    new_method = info.get(\"__new__\")\n    if not init_method or not is_valid_constructor(init_method.node):\n        # Must be an invalid class definition.\n        return AnyType(TypeOfAny.from_error)\n    # There *should* always be a __new__ method except the test stubs\n    # lack it, so just copy init_method in that situation\n    new_method = new_method or init_method\n    if not is_valid_constructor(new_method.node):\n        # Must be an invalid class definition.\n        return AnyType(TypeOfAny.from_error)\n\n    # The two is_valid_constructor() checks ensure this.\n    assert isinstance(new_method.node, (SYMBOL_FUNCBASE_TYPES, Decorator))\n    assert isinstance(init_method.node, (SYMBOL_FUNCBASE_TYPES, Decorator))\n\n    init_index = info.mro.index(init_method.node.info)\n    new_index = info.mro.index(new_method.node.info)\n\n    if info.metaclass_type is not None:\n        fallback = info.metaclass_type\n    elif checker_state.type_checker:\n        # Prefer direct call when it is available. It is faster, and,\n        # unfortunately, some callers provide bogus callback.\n        fallback = checker_state.type_checker.named_type(\"builtins.type\")\n    else:\n        fallback = named_type(\"builtins.type\")\n\n    if init_index < new_index:\n        method: FuncBase | Decorator = init_method.node\n        is_new = False\n    elif init_index > new_index:\n        method = new_method.node\n        is_new = True\n    else:\n        if init_method.node.info.fullname == \"builtins.object\":\n            # Both are defined by object.  But if we've got a bogus\n            # base class, we can't know for sure, so check for that.\n            if info.fallback_to_any:\n                # Construct a universal callable as the prototype.\n                any_type = AnyType(TypeOfAny.special_form)\n                sig = CallableType(\n                    arg_types=[any_type, any_type],\n                    arg_kinds=[ARG_STAR, ARG_STAR2],\n                    arg_names=[\"_args\", \"_kwds\"],\n                    ret_type=any_type,\n                    is_bound=True,\n                    fallback=named_type(\"builtins.function\"),\n                )\n                result: FunctionLike = class_callable(sig, info, fallback, None, is_new=False)\n                if allow_cache and state.strict_optional:\n                    info.type_object_type = result\n                return result\n\n        # Otherwise prefer __init__ in a tie. It isn't clear that this\n        # is the right thing, but __new__ caused problems with\n        # typeshed (#5647).\n        method = init_method.node\n        is_new = False\n    # Construct callable type based on signature of __init__. Adjust\n    # return type and insert type arguments.\n    if isinstance(method, FuncBase):\n        if isinstance(method, OverloadedFuncDef) and not method.type:\n            # Do not cache if the type is not ready. Same logic for decorators is\n            # achieved in early return above because is_valid_constructor() is False.\n            allow_cache = False\n        t = function_type(method, fallback)\n    else:\n        assert isinstance(method.type, ProperType)\n        assert isinstance(method.type, FunctionLike)  # is_valid_constructor() ensures this\n        t = method.type\n    result = type_object_type_from_function(t, info, method.info, fallback, is_new)\n    # Only write cached result is strict_optional=True, otherwise we may get\n    # inconsistent behaviour because of union simplification.\n    if allow_cache and state.strict_optional:\n        info.type_object_type = result\n    return result\n\n\ndef is_valid_constructor(n: SymbolNode | None) -> bool:\n    \"\"\"Does this node represents a valid constructor method?\n\n    This includes normal functions, overloaded functions, and decorators\n    that return a callable type.\n    \"\"\"\n    if isinstance(n, SYMBOL_FUNCBASE_TYPES):\n        return True\n    if isinstance(n, Decorator):\n        return isinstance(get_proper_type(n.type), FunctionLike)\n    return False\n\n\ndef type_object_type_from_function(\n    signature: FunctionLike, info: TypeInfo, def_info: TypeInfo, fallback: Instance, is_new: bool\n) -> FunctionLike:\n    # We first need to record all non-trivial (explicit) self types in __init__,\n    # since they will not be available after we bind them. Note, we use explicit\n    # self-types only in the defining class, similar to __new__ (but not exactly the same,\n    # see comment in class_callable below). This is mostly useful for annotating library\n    # classes such as subprocess.Popen.\n    if not is_new and not info.is_newtype:\n        orig_self_types = [get_self_type(it, def_info) for it in signature.items]\n    else:\n        orig_self_types = [None] * len(signature.items)\n\n    # The __init__ method might come from a generic superclass 'def_info'\n    # with type variables that do not map identically to the type variables of\n    # the class 'info' being constructed. For example:\n    #\n    #   class A(Generic[T]):\n    #       def __init__(self, x: T) -> None: ...\n    #   class B(A[List[T]]):\n    #      ...\n    #\n    # We need to map B's __init__ to the type (List[T]) -> None.\n    signature = bind_self(\n        signature,\n        original_type=fill_typevars(info),\n        is_classmethod=is_new,\n        # Explicit instance self annotations have special handling in class_callable(),\n        # we don't need to bind any type variables in them if they are generic.\n        ignore_instances=True,\n    )\n    signature = cast(FunctionLike, map_type_from_supertype(signature, info, def_info))\n\n    special_sig: str | None = None\n    if def_info.fullname == \"builtins.dict\":\n        # Special signature!\n        special_sig = \"dict\"\n\n    if isinstance(signature, CallableType):\n        return class_callable(signature, info, fallback, special_sig, is_new, orig_self_types[0])\n    else:\n        # Overloaded __init__/__new__.\n        assert isinstance(signature, Overloaded)\n        items: list[CallableType] = []\n        for item, orig_self in zip(signature.items, orig_self_types):\n            items.append(class_callable(item, info, fallback, special_sig, is_new, orig_self))\n        return Overloaded(items)\n\n\ndef class_callable(\n    init_type: CallableType,\n    info: TypeInfo,\n    type_type: Instance,\n    special_sig: str | None,\n    is_new: bool,\n    orig_self_type: Type | None = None,\n) -> CallableType:\n    \"\"\"Create a type object type based on the signature of __init__.\"\"\"\n    variables: list[TypeVarLikeType] = []\n    variables.extend(info.defn.type_vars)\n    variables.extend(init_type.variables)\n\n    from mypy.subtypes import is_subtype\n\n    init_ret_type = get_proper_type(init_type.ret_type)\n    orig_self_type = get_proper_type(orig_self_type)\n    default_ret_type = fill_typevars(info)\n    explicit_type = init_ret_type if is_new else orig_self_type\n    if (\n        isinstance(explicit_type, (Instance, TupleType, UninhabitedType, LiteralType))\n        # We have to skip protocols, because it can be a subtype of a return type\n        # by accident. Like `Hashable` is a subtype of `object`. See #11799\n        and isinstance(default_ret_type, Instance)\n        and not default_ret_type.type.is_protocol\n        # Only use the declared return type from __new__ or declared self in __init__\n        # if it is actually returning a subtype of what we would return otherwise.\n        and is_subtype(explicit_type, default_ret_type, ignore_type_params=True)\n    ):\n        ret_type: Type = explicit_type\n    else:\n        ret_type = default_ret_type\n\n    callable_type = init_type.copy_modified(\n        ret_type=ret_type,\n        fallback=type_type,\n        name=None,\n        variables=variables,\n        special_sig=special_sig,\n    )\n    c = callable_type.with_name(info.name)\n    return c\n\n\ndef map_type_from_supertype(typ: Type, sub_info: TypeInfo, super_info: TypeInfo) -> Type:\n    \"\"\"Map type variables in a type defined in a supertype context to be valid\n    in the subtype context. Assume that the result is unique; if more than\n    one type is possible, return one of the alternatives.\n\n    For example, assume\n\n      class D(Generic[S]): ...\n      class C(D[E[T]], Generic[T]): ...\n\n    Now S in the context of D would be mapped to E[T] in the context of C.\n    \"\"\"\n    # Create the type of self in subtype, of form t[a1, ...].\n    inst_type = fill_typevars(sub_info)\n    if isinstance(inst_type, TupleType):\n        inst_type = tuple_fallback(inst_type)\n    # Map the type of self to supertype. This gets us a description of the\n    # supertype type variables in terms of subtype variables, i.e. t[t1, ...]\n    # so that any type variables in tN are to be interpreted in subtype\n    # context.\n    inst_type = map_instance_to_supertype(inst_type, super_info)\n    # Finally expand the type variables in type with those in the previously\n    # constructed type. Note that both type and inst_type may have type\n    # variables, but in type they are interpreted in supertype context while\n    # in inst_type they are interpreted in subtype context. This works even if\n    # the names of type variables in supertype and subtype overlap.\n    return expand_type_by_instance(typ, inst_type)\n\n\ndef supported_self_type(\n    typ: ProperType, allow_callable: bool = True, allow_instances: bool = True\n) -> bool:\n    \"\"\"Is this a supported kind of explicit self-types?\n\n    Currently, this means an X or Type[X], where X is an instance or\n    a type variable with an instance upper bound.\n    \"\"\"\n    if isinstance(typ, TypeType):\n        return supported_self_type(typ.item)\n    if allow_callable and isinstance(typ, CallableType):\n        # Special case: allow class callable instead of Type[...] as cls annotation,\n        # as well as callable self for callback protocols.\n        return True\n    return isinstance(typ, TypeVarType) or (\n        allow_instances and isinstance(typ, Instance) and typ != fill_typevars(typ.type)\n    )\n\n\nF = TypeVar(\"F\", bound=FunctionLike)\n\n\ndef bind_self(\n    method: F,\n    original_type: Type | None = None,\n    is_classmethod: bool = False,\n    ignore_instances: bool = False,\n) -> F:\n    \"\"\"Return a copy of `method`, with the type of its first parameter (usually\n    self or cls) bound to original_type.\n\n    If the type of `self` is a generic type (T, or Type[T] for classmethods),\n    instantiate every occurrence of type with original_type in the rest of the\n    signature and in the return type.\n\n    original_type is the type of E in the expression E.copy(). It is None in\n    compatibility checks. In this case we treat it as the erasure of the\n    declared type of self.\n\n    This way we can express \"the type of self\". For example:\n\n    T = TypeVar('T', bound='A')\n    class A:\n        def copy(self: T) -> T: ...\n\n    class B(A): pass\n\n    b = B().copy()  # type: B\n\n    \"\"\"\n    if isinstance(method, Overloaded):\n        items = [\n            bind_self(c, original_type, is_classmethod, ignore_instances) for c in method.items\n        ]\n        return cast(F, Overloaded(items))\n    assert isinstance(method, CallableType)\n    func: CallableType = method\n    if not func.arg_types:\n        # Invalid method, return something.\n        return method\n    if func.arg_kinds[0] in (ARG_STAR, ARG_STAR2):\n        # The signature is of the form 'def foo(*args, ...)'.\n        # In this case we shouldn't drop the first arg,\n        # since func will be absorbed by the *args.\n        # TODO: infer bounds on the type of *args?\n\n        # In the case of **kwargs we should probably emit an error, but\n        # for now we simply skip it, to avoid crashes down the line.\n        return method\n    self_param_type = get_proper_type(func.arg_types[0])\n\n    variables: Sequence[TypeVarLikeType]\n    # Having a def __call__(self: Callable[...], ...) can cause infinite recursion. Although\n    # this special-casing looks not very principled, there is nothing meaningful we can infer\n    # from such definition, since it is inherently indefinitely recursive.\n    allow_callable = func.name is None or not func.name.startswith(\"__call__ of\")\n    if func.variables and supported_self_type(\n        self_param_type, allow_callable=allow_callable, allow_instances=not ignore_instances\n    ):\n        from mypy.infer import infer_type_arguments\n\n        if original_type is None:\n            # TODO: type check method override (see #7861).\n            original_type = erase_to_bound(self_param_type)\n        original_type = get_proper_type(original_type)\n\n        # Find which of method type variables appear in the type of \"self\".\n        self_ids = {tv.id for tv in get_all_type_vars(self_param_type)}\n        self_vars = [tv for tv in func.variables if tv.id in self_ids]\n\n        # Solve for these type arguments using the actual class or instance type.\n        typeargs = infer_type_arguments(\n            self_vars, self_param_type, original_type, is_supertype=True\n        )\n        if (\n            is_classmethod\n            and any(isinstance(get_proper_type(t), UninhabitedType) for t in typeargs)\n            and isinstance(original_type, (Instance, TypeVarType, TupleType))\n        ):\n            # In case we call a classmethod through an instance x, fallback to type(x).\n            typeargs = infer_type_arguments(\n                self_vars, self_param_type, TypeType(original_type), is_supertype=True\n            )\n\n        # Update the method signature with the solutions found.\n        # Technically, some constraints might be unsolvable, make them Never.\n        to_apply = [t if t is not None else UninhabitedType() for t in typeargs]\n        func = expand_type(func, {tv.id: arg for tv, arg in zip(self_vars, to_apply)})\n        variables = [v for v in func.variables if v not in self_vars]\n    else:\n        variables = func.variables\n\n    res = func.copy_modified(\n        arg_types=func.arg_types[1:],\n        arg_kinds=func.arg_kinds[1:],\n        arg_names=func.arg_names[1:],\n        variables=variables,\n        is_bound=True,\n    )\n    return cast(F, res)\n\n\ndef erase_to_bound(t: Type) -> Type:\n    # TODO: use value restrictions to produce a union?\n    t = get_proper_type(t)\n    if isinstance(t, TypeVarType):\n        return t.upper_bound\n    if isinstance(t, TypeType):\n        if isinstance(t.item, TypeVarType):\n            return TypeType.make_normalized(t.item.upper_bound, is_type_form=t.is_type_form)\n    return t\n\n\ndef callable_corresponding_argument(\n    typ: NormalizedCallableType | Parameters, model: FormalArgument\n) -> FormalArgument | None:\n    \"\"\"Return the argument of a function that corresponds to `model`\"\"\"\n\n    by_name = typ.argument_by_name(model.name)\n    by_pos = typ.argument_by_position(model.pos)\n    if by_name is None and by_pos is None:\n        return None\n    if by_name is not None and by_pos is not None:\n        if by_name == by_pos:\n            return by_name\n        # If we're dealing with an optional pos-only and an optional\n        # name-only arg, merge them.  This is the case for all functions\n        # taking both *args and **args, or a pair of functions like so:\n\n        # def right(a: int = ...) -> None: ...\n        # def left(x: int = ..., /, *, a: int = ...) -> None: ...\n        from mypy.meet import meet_types\n\n        if (\n            not (by_name.required or by_pos.required)\n            and by_pos.name is None\n            and by_name.pos is None\n            # This is not principled, but prevents a crash. It's weird to have a FormalArgument\n            # that has an UnpackType.\n            and not isinstance(by_name.typ, UnpackType)\n            and not isinstance(by_pos.typ, UnpackType)\n        ):\n            return FormalArgument(\n                by_name.name, by_pos.pos, meet_types(by_name.typ, by_pos.typ), False\n            )\n        return by_name\n\n    return by_name if by_name is not None else by_pos\n\n\ndef simple_literal_type(t: ProperType | None) -> Instance | None:\n    \"\"\"Extract the underlying fallback Instance type for a simple Literal\"\"\"\n    if isinstance(t, Instance) and t.last_known_value is not None:\n        t = t.last_known_value\n    if isinstance(t, LiteralType):\n        return t.fallback\n    return None\n\n\ndef is_simple_literal(t: ProperType) -> bool:\n    if isinstance(t, LiteralType):\n        return t.fallback.type.is_enum or t.fallback.type.fullname == \"builtins.str\"\n    if isinstance(t, Instance):\n        return t.last_known_value is not None and isinstance(t.last_known_value.value, str)\n    return False\n\n\ndef make_simplified_union(\n    items: Sequence[Type],\n    line: int = -1,\n    column: int = -1,\n    *,\n    keep_erased: bool = False,\n    contract_literals: bool = True,\n    handle_recursive: bool = True,\n) -> ProperType:\n    \"\"\"Build union type with redundant union items removed.\n\n    If only a single item remains, this may return a non-union type.\n\n    Examples:\n\n    * [int, str] -> Union[int, str]\n    * [int, object] -> object\n    * [int, int] -> int\n    * [int, Any] -> Union[int, Any] (Any types are not simplified away!)\n    * [Any, Any] -> Any\n    * [int, Union[bytes, str]] -> Union[int, bytes, str]\n\n    Note: This must NOT be used during semantic analysis, since TypeInfos may not\n          be fully initialized.\n\n    The keep_erased flag is used for type inference against union types\n    containing type variables. If set to True, keep all ErasedType items.\n\n    The contract_literals flag indicates whether we need to contract literal types\n    back into a sum type. Set it to False when called by try_expanding_sum_type_\n    to_union().\n    \"\"\"\n    # Step 1: expand all nested unions\n    items = flatten_nested_unions(items, handle_recursive=handle_recursive)\n\n    # Step 2: fast path for single item\n    if len(items) == 1:\n        return get_proper_type(items[0])\n\n    # Step 3: remove redundant unions\n    simplified_set: Sequence[Type] = _remove_redundant_union_items(items, keep_erased)\n\n    # Step 4: If more than one literal exists in the union, try to simplify\n    if (\n        contract_literals\n        and sum(isinstance(get_proper_type(item), LiteralType) for item in simplified_set) > 1\n    ):\n        simplified_set = try_contracting_literals_in_union(simplified_set)\n\n    result = get_proper_type(UnionType.make_union(simplified_set, line, column))\n\n    nitems = len(items)\n    if nitems > 1 and (\n        nitems > 2 or not (type(items[0]) is NoneType or type(items[1]) is NoneType)\n    ):\n        # Step 5: At last, we erase any (inconsistent) extra attributes on instances.\n\n        # Initialize with None instead of an empty set as a micro-optimization. The set\n        # is needed very rarely, so we try to avoid constructing it.\n        extra_attrs_set: set[ExtraAttrs] | None = None\n        for item in items:\n            instance = try_getting_instance_fallback(item)\n            if instance and instance.extra_attrs:\n                if extra_attrs_set is None:\n                    extra_attrs_set = {instance.extra_attrs}\n                else:\n                    extra_attrs_set.add(instance.extra_attrs)\n\n        # Code below is awkward, because we don't want the extra checks to affect\n        # performance in the common case.\n        erase_extra = False\n        if extra_attrs_set is not None:\n            fallback = try_getting_instance_fallback(result)\n            if fallback is None:\n                return result\n            if len(extra_attrs_set) > 1:  # This case is too tricky to handle.\n                erase_extra = True\n            else:\n                # Check that all relevant items have the extra attributes.\n                for item in items:\n                    instance = try_getting_instance_fallback(item)\n                    if instance and instance.type == fallback.type and not instance.extra_attrs:\n                        erase_extra = True\n                        break\n            if erase_extra:\n                fallback.extra_attrs = None\n\n    return result\n\n\ndef _remove_redundant_union_items(items: list[Type], keep_erased: bool) -> list[Type]:\n    from mypy.subtypes import is_proper_subtype\n\n    # The first pass through this loop, we check if later items are subtypes of earlier items.\n    # The second pass through this loop, we check if earlier items are subtypes of later items\n    # (by reversing the remaining items)\n    for _direction in range(2):\n        new_items: list[Type] = []\n        # seen is a map from a type to its index in new_items\n        seen: dict[ProperType, int] = {}\n        unduplicated_literal_fallbacks: set[Instance] | None = None\n        for ti in items:\n            proper_ti = get_proper_type(ti)\n\n            # UninhabitedType is always redundant\n            if isinstance(proper_ti, UninhabitedType):\n                continue\n\n            duplicate_index = -1\n            # Quickly check if we've seen this type\n            if proper_ti in seen:\n                duplicate_index = seen[proper_ti]\n            elif (\n                isinstance(proper_ti, LiteralType)\n                and unduplicated_literal_fallbacks is not None\n                and proper_ti.fallback in unduplicated_literal_fallbacks\n            ):\n                # This is an optimisation for unions with many LiteralType\n                # We've already checked for exact duplicates. This means that any super type of\n                # the LiteralType must be a super type of its fallback. If we've gone through\n                # the expensive loop below and found no super type for a previous LiteralType\n                # with the same fallback, we can skip doing that work again and just add the type\n                # to new_items\n                pass\n            else:\n                # If not, check if we've seen a supertype of this type\n                for j, tj in enumerate(new_items):\n                    proper_tj = get_proper_type(tj)\n                    # If tj is an Instance with a last_known_value, do not remove proper_ti\n                    # (unless it's an instance with the same last_known_value)\n                    if (\n                        isinstance(proper_tj, Instance)\n                        and proper_tj.last_known_value is not None\n                        and not (\n                            isinstance(proper_ti, Instance)\n                            and proper_tj.last_known_value == proper_ti.last_known_value\n                        )\n                    ):\n                        continue\n\n                    if is_proper_subtype(\n                        ti, tj, keep_erased_types=keep_erased, ignore_promotions=True\n                    ):\n                        duplicate_index = j\n                        break\n            if duplicate_index != -1:\n                # If deleted subtypes had more general truthiness, use that\n                orig_item = new_items[duplicate_index]\n                if not orig_item.can_be_true and ti.can_be_true:\n                    new_items[duplicate_index] = true_or_false(orig_item)\n                elif not orig_item.can_be_false and ti.can_be_false:\n                    new_items[duplicate_index] = true_or_false(orig_item)\n            else:\n                # We have a non-duplicate item, add it to new_items\n                seen[proper_ti] = len(new_items)\n                new_items.append(ti)\n                if isinstance(proper_ti, LiteralType):\n                    if unduplicated_literal_fallbacks is None:\n                        unduplicated_literal_fallbacks = set()\n                    unduplicated_literal_fallbacks.add(proper_ti.fallback)\n\n        items = new_items\n        if len(items) <= 1:\n            break\n        items.reverse()\n\n    return items\n\n\ndef _get_type_method_ret_type(t: ProperType, *, name: str) -> Type | None:\n    # For Enum literals the ret_type can change based on the Enum\n    # we need to check the type of the enum rather than the literal\n    if isinstance(t, LiteralType) and t.is_enum_literal():\n        t = t.fallback\n\n    if isinstance(t, Instance):\n        sym = t.type.get(name)\n        if sym:\n            sym_type = get_proper_type(sym.type)\n            if isinstance(sym_type, CallableType):\n                return sym_type.ret_type\n\n    return None\n\n\ndef true_only(t: Type) -> ProperType:\n    \"\"\"\n    Restricted version of t with only True-ish values\n    \"\"\"\n    t = get_proper_type(t)\n\n    if not t.can_be_true:\n        # All values of t are False-ish, so there are no true values in it\n        return UninhabitedType(line=t.line, column=t.column)\n    elif not t.can_be_false:\n        # All values of t are already True-ish, so true_only is idempotent in this case\n        return t\n    elif isinstance(t, UnionType):\n        # The true version of a union type is the union of the true versions of its components\n        new_items = [true_only(item) for item in t.items]\n        can_be_true_items = [item for item in new_items if item.can_be_true]\n        return make_simplified_union(can_be_true_items, line=t.line, column=t.column)\n    else:\n        ret_type = _get_type_method_ret_type(t, name=\"__bool__\") or _get_type_method_ret_type(\n            t, name=\"__len__\"\n        )\n\n        if ret_type and not ret_type.can_be_true:\n            return UninhabitedType(line=t.line, column=t.column)\n\n        new_t = copy_type(t)\n        new_t.can_be_false = False\n        return new_t\n\n\ndef false_only(t: Type) -> ProperType:\n    \"\"\"\n    Restricted version of t with only False-ish values\n    \"\"\"\n    t = get_proper_type(t)\n\n    if not t.can_be_false:\n        if state.strict_optional:\n            # All values of t are True-ish, so there are no false values in it\n            return UninhabitedType(line=t.line)\n        else:\n            # When strict optional checking is disabled, everything can be\n            # False-ish since anything can be None\n            return NoneType(line=t.line)\n    elif not t.can_be_true:\n        # All values of t are already False-ish, so false_only is idempotent in this case\n        return t\n    elif isinstance(t, UnionType):\n        # The false version of a union type is the union of the false versions of its components\n        new_items = [false_only(item) for item in t.items]\n        can_be_false_items = [item for item in new_items if item.can_be_false]\n        return make_simplified_union(can_be_false_items, line=t.line, column=t.column)\n    elif isinstance(t, Instance) and t.type.fullname in (\"builtins.str\", \"builtins.bytes\"):\n        return LiteralType(\"\", fallback=t)\n    elif isinstance(t, Instance) and t.type.fullname == \"builtins.int\":\n        return LiteralType(0, fallback=t)\n    else:\n        ret_type = _get_type_method_ret_type(t, name=\"__bool__\") or _get_type_method_ret_type(\n            t, name=\"__len__\"\n        )\n\n        if ret_type:\n            if not ret_type.can_be_false:\n                return UninhabitedType(line=t.line)\n        elif isinstance(t, Instance):\n            if (t.type.is_final or t.type.is_enum) and state.strict_optional:\n                return UninhabitedType(line=t.line)\n        elif isinstance(t, LiteralType) and t.is_enum_literal() and state.strict_optional:\n            return UninhabitedType(line=t.line)\n\n        new_t = copy_type(t)\n        new_t.can_be_true = False\n        return new_t\n\n\ndef true_or_false(t: Type) -> ProperType:\n    \"\"\"\n    Unrestricted version of t with both True-ish and False-ish values\n    \"\"\"\n    t = get_proper_type(t)\n\n    if isinstance(t, UnionType):\n        new_items = [true_or_false(item) for item in t.items]\n        return make_simplified_union(new_items, line=t.line, column=t.column)\n\n    new_t = copy_type(t)\n    new_t.can_be_true = new_t.can_be_true_default()\n    new_t.can_be_false = new_t.can_be_false_default()\n    return new_t\n\n\ndef erase_def_to_union_or_bound(tdef: TypeVarLikeType) -> Type:\n    # TODO(PEP612): fix for ParamSpecType\n    if isinstance(tdef, ParamSpecType):\n        return AnyType(TypeOfAny.from_error)\n    if isinstance(tdef, TypeVarType) and tdef.values:\n        return make_simplified_union(tdef.values)\n    else:\n        return tdef.upper_bound\n\n\ndef erase_to_union_or_bound(typ: TypeVarType) -> ProperType:\n    if typ.values:\n        return make_simplified_union(typ.values)\n    else:\n        return get_proper_type(typ.upper_bound)\n\n\ndef function_type(func: FuncBase, fallback: Instance) -> FunctionLike:\n    if func.type:\n        assert isinstance(func.type, FunctionLike)\n        return func.type\n    else:\n        # Implicit type signature with dynamic types.\n        if isinstance(func, FuncItem):\n            return callable_type(func, fallback)\n        else:\n            # Either a broken overload, or decorated overload type is not ready.\n            # TODO: make sure the caller defers if possible.\n            assert isinstance(func, OverloadedFuncDef)\n            any_type = AnyType(TypeOfAny.from_error)\n            dummy = CallableType(\n                [any_type, any_type],\n                [ARG_STAR, ARG_STAR2],\n                [None, None],\n                any_type,\n                fallback,\n                line=func.line,\n                is_ellipsis_args=True,\n            )\n            # Return an Overloaded, because some callers may expect that\n            # an OverloadedFuncDef has an Overloaded type.\n            return Overloaded([dummy])\n\n\ndef callable_type(\n    fdef: FuncItem, fallback: Instance, ret_type: Type | None = None\n) -> CallableType:\n    # TODO: somewhat unfortunate duplication with prepare_method_signature in semanal\n    if fdef.info and fdef.has_self_or_cls_argument and fdef.arg_names:\n        self_type: Type = fill_typevars(fdef.info)\n        if fdef.is_class or fdef.name == \"__new__\":\n            self_type = TypeType.make_normalized(self_type)\n        args = [self_type] + [AnyType(TypeOfAny.unannotated)] * (len(fdef.arg_names) - 1)\n    else:\n        args = [AnyType(TypeOfAny.unannotated)] * len(fdef.arg_names)\n\n    return CallableType(\n        args,\n        fdef.arg_kinds,\n        fdef.arg_names,\n        ret_type or AnyType(TypeOfAny.unannotated),\n        fallback,\n        name=fdef.name,\n        line=fdef.line,\n        column=fdef.column,\n        implicit=True,\n        # We need this for better error messages, like missing `self` note:\n        definition=fdef if isinstance(fdef, FuncDef) else None,\n    )\n\n\ndef try_getting_str_literals(expr: Expression, typ: Type) -> list[str] | None:\n    \"\"\"If the given expression or type corresponds to a string literal\n    or a union of string literals, returns a list of the underlying strings.\n    Otherwise, returns None.\n\n    Specifically, this function is guaranteed to return a list with\n    one or more strings if one of the following is true:\n\n    1. 'expr' is a StrExpr\n    2. 'typ' is a LiteralType containing a string\n    3. 'typ' is a UnionType containing only LiteralType of strings\n    \"\"\"\n    if isinstance(expr, StrExpr):\n        return [expr.value]\n\n    # TODO: See if we can eliminate this function and call the below one directly\n    return try_getting_str_literals_from_type(typ)\n\n\ndef try_getting_str_literals_from_type(typ: Type) -> list[str] | None:\n    \"\"\"If the given expression or type corresponds to a string Literal\n    or a union of string Literals, returns a list of the underlying strings.\n    Otherwise, returns None.\n\n    For example, if we had the type 'Literal[\"foo\", \"bar\"]' as input, this function\n    would return a list of strings [\"foo\", \"bar\"].\n    \"\"\"\n    return try_getting_literals_from_type(typ, str, \"builtins.str\")\n\n\ndef try_getting_int_literals_from_type(typ: Type) -> list[int] | None:\n    \"\"\"If the given expression or type corresponds to an int Literal\n    or a union of int Literals, returns a list of the underlying ints.\n    Otherwise, returns None.\n\n    For example, if we had the type 'Literal[1, 2, 3]' as input, this function\n    would return a list of ints [1, 2, 3].\n    \"\"\"\n    return try_getting_literals_from_type(typ, int, \"builtins.int\")\n\n\nT = TypeVar(\"T\")\n\n\ndef try_getting_literals_from_type(\n    typ: Type, target_literal_type: type[T], target_fullname: str\n) -> list[T] | None:\n    \"\"\"If the given expression or type corresponds to a Literal or\n    union of Literals where the underlying values correspond to the given\n    target type, returns a list of those underlying values. Otherwise,\n    returns None.\n    \"\"\"\n    typ = get_proper_type(typ)\n\n    if isinstance(typ, Instance) and typ.last_known_value is not None:\n        possible_literals: list[Type] = [typ.last_known_value]\n    elif isinstance(typ, UnionType):\n        possible_literals = list(typ.items)\n    else:\n        possible_literals = [typ]\n\n    literals: list[T] = []\n    for lit in get_proper_types(possible_literals):\n        if isinstance(lit, LiteralType) and lit.fallback.type.fullname == target_fullname:\n            val = lit.value\n            if isinstance(val, target_literal_type):\n                literals.append(val)\n            else:\n                return None\n        else:\n            return None\n    return literals\n\n\ndef is_literal_type_like(t: Type | None) -> bool:\n    \"\"\"Returns 'true' if the given type context is potentially either a LiteralType,\n    a Union of LiteralType, or something similar.\n    \"\"\"\n    t = get_proper_type(t)\n    if t is None:\n        return False\n    elif isinstance(t, LiteralType):\n        return True\n    elif isinstance(t, UnionType):\n        return any(is_literal_type_like(item) for item in t.items)\n    elif isinstance(t, TypeVarType):\n        return is_literal_type_like(t.upper_bound) or any(\n            is_literal_type_like(item) for item in t.values\n        )\n    else:\n        return False\n\n\ndef is_singleton_identity_type(typ: ProperType) -> bool:\n    \"\"\"\n    Returns True if every value of this type is identical to every other value of this type,\n    as judged by the `is` operator.\n\n    Note that this is not true of certain LiteralType, such as Literal[100001] or Literal[\"string\"]\n    \"\"\"\n    if isinstance(typ, NoneType):\n        return True\n    if isinstance(typ, Instance):\n        return (\n            (typ.type.is_enum and len(typ.type.enum_members) == 1)\n            or (typ.type.fullname in ELLIPSIS_TYPE_NAMES)\n            or (typ.type.fullname in NOT_IMPLEMENTED_TYPE_NAMES)\n        )\n    if isinstance(typ, LiteralType):\n        return typ.is_enum_literal() or isinstance(typ.value, bool)\n    if isinstance(typ, TypeType) and isinstance(typ.item, Instance) and typ.item.type.is_final:\n        return True\n    if isinstance(typ, FunctionLike) and typ.is_type_obj() and typ.type_object().is_final:\n        return True\n    return False\n\n\ndef is_singleton_equality_type(typ: ProperType) -> bool:\n    \"\"\"\n    Returns True if every value of this type compares equal to every other value of this type,\n    as judged by the `==` operator.\n    \"\"\"\n    return isinstance(typ, LiteralType) or is_singleton_identity_type(typ)\n\n\ndef try_expanding_sum_type_to_union(typ: Type, target_fullname: str | None) -> Type:\n    \"\"\"Attempts to recursively expand any enum Instances with the given target_fullname\n    into a Union of all of its component LiteralTypes.\n\n    For example, if we have:\n\n        class Color(Enum):\n            RED = 1\n            BLUE = 2\n            YELLOW = 3\n\n        class Status(Enum):\n            SUCCESS = 1\n            FAILURE = 2\n            UNKNOWN = 3\n\n    ...and if we call `try_expanding_sum_type_to_union(Union[Color, Status], 'module.Color')`,\n    this function will return Literal[Color.RED, Color.BLUE, Color.YELLOW, Status].\n    \"\"\"\n    typ = get_proper_type(typ)\n\n    if isinstance(typ, UnionType):\n        # Non-empty enums cannot subclass each other so simply removing duplicates is enough.\n        items = [\n            try_expanding_sum_type_to_union(item, target_fullname)\n            for item in remove_dups(flatten_nested_unions(typ.relevant_items()))\n        ]\n        return UnionType.make_union(items)\n\n    if isinstance(typ, Instance) and (\n        target_fullname is None or typ.type.fullname == target_fullname\n    ):\n        if typ.type.fullname == \"builtins.bool\":\n            return UnionType([LiteralType(True, typ), LiteralType(False, typ)])\n\n        if typ.type.is_enum:\n            items = [LiteralType(name, typ) for name in typ.type.enum_members]\n            if not items:\n                return typ\n            return UnionType.make_union(items)\n\n    return typ\n\n\ndef try_contracting_literals_in_union(types: Sequence[Type]) -> list[ProperType]:\n    \"\"\"Contracts any literal types back into a sum type if possible.\n\n    Requires a flattened union and does not descend into children.\n\n    Will replace the first instance of the literal with the sum type and\n    remove all others.\n\n    If we call `try_contracting_union(Literal[Color.RED, Color.BLUE, Color.YELLOW])`,\n    this function will return Color.\n\n    We also treat `Literal[True, False]` as `bool`.\n    \"\"\"\n    proper_types = [get_proper_type(typ) for typ in types]\n    sum_types: dict[str, tuple[set[Any], list[int]]] = {}\n    marked_for_deletion = set()\n    for idx, typ in enumerate(proper_types):\n        if isinstance(typ, LiteralType):\n            fullname = typ.fallback.type.fullname\n            if typ.fallback.type.is_enum or isinstance(typ.value, bool):\n                if fullname not in sum_types:\n                    sum_types[fullname] = (\n                        (\n                            set(typ.fallback.type.enum_members)\n                            if typ.fallback.type.is_enum\n                            else {True, False}\n                        ),\n                        [],\n                    )\n                literals, indexes = sum_types[fullname]\n                literals.discard(typ.value)\n                indexes.append(idx)\n                if not literals:\n                    first, *rest = indexes\n                    proper_types[first] = typ.fallback\n                    marked_for_deletion |= set(rest)\n    return list(\n        itertools.compress(\n            proper_types, [(i not in marked_for_deletion) for i in range(len(proper_types))]\n        )\n    )\n\n\ndef coerce_to_literal(typ: Type) -> Type:\n    \"\"\"Recursively converts any Instances that have a last_known_value or are\n    instances of enum types with a single value into the corresponding LiteralType.\n    \"\"\"\n    original_type = typ\n    typ = get_proper_type(typ)\n    if isinstance(typ, UnionType):\n        new_items = [coerce_to_literal(item) for item in typ.items]\n        return UnionType.make_union(new_items)\n    elif isinstance(typ, Instance):\n        if typ.last_known_value:\n            return typ.last_known_value\n        elif typ.type.is_enum:\n            enum_values = typ.type.enum_members\n            if len(enum_values) == 1:\n                return LiteralType(value=enum_values[0], fallback=typ)\n    return original_type\n\n\ndef get_type_vars(tp: Type) -> list[TypeVarType]:\n    return cast(\"list[TypeVarType]\", tp.accept(TypeVarExtractor()))\n\n\ndef get_all_type_vars(tp: Type) -> list[TypeVarLikeType]:\n    # TODO: should we always use this function instead of get_type_vars() above?\n    return tp.accept(TypeVarExtractor(include_all=True))\n\n\nclass TypeVarExtractor(TypeQuery[list[TypeVarLikeType]]):\n    def __init__(self, include_all: bool = False) -> None:\n        super().__init__()\n        self.include_all = include_all\n\n    def strategy(self, items: Iterable[list[TypeVarLikeType]]) -> list[TypeVarLikeType]:\n        out = []\n        for item in items:\n            out.extend(item)\n        return out\n\n    def visit_type_var(self, t: TypeVarType) -> list[TypeVarLikeType]:\n        return [t]\n\n    def visit_param_spec(self, t: ParamSpecType) -> list[TypeVarLikeType]:\n        return [t] if self.include_all else []\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> list[TypeVarLikeType]:\n        return [t] if self.include_all else []\n\n\ndef freeze_all_type_vars(member_type: Type) -> None:\n    member_type.accept(FreezeTypeVarsVisitor())\n\n\nclass FreezeTypeVarsVisitor(TypeTraverserVisitor):\n    def visit_callable_type(self, t: CallableType) -> None:\n        for v in t.variables:\n            v.id.meta_level = 0\n        super().visit_callable_type(t)\n\n\ndef custom_special_method(typ: Type, name: str, check_all: bool = False) -> bool:\n    \"\"\"Does this type have a custom special method such as __format__() or __eq__()?\n\n    If check_all is True ensure all items of a union have a custom method, not just some.\n    \"\"\"\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        method = typ.type.get(name)\n        if method and isinstance(method.node, (SYMBOL_FUNCBASE_TYPES, Decorator, Var)):\n            if method.node.info:\n                return not method.node.info.fullname.startswith((\"builtins.\", \"typing.\"))\n        return False\n    if isinstance(typ, UnionType):\n        if check_all:\n            return all(custom_special_method(t, name, check_all) for t in typ.items)\n        return any(custom_special_method(t, name) for t in typ.items)\n    if isinstance(typ, TupleType):\n        return custom_special_method(tuple_fallback(typ), name, check_all)\n    if isinstance(typ, FunctionLike) and typ.is_type_obj():\n        # Look up __method__ on the metaclass for class objects.\n        return custom_special_method(typ.fallback, name, check_all)\n    if isinstance(typ, TypeType) and isinstance(typ.item, Instance):\n        if typ.item.type.metaclass_type:\n            # Look up __method__ on the metaclass for class objects.\n            return custom_special_method(typ.item.type.metaclass_type, name, check_all)\n    if isinstance(typ, AnyType):\n        # Avoid false positives in uncertain cases.\n        return True\n    # TODO: support other types (see ExpressionChecker.has_member())?\n    return False\n\n\ndef separate_union_literals(t: UnionType) -> tuple[Sequence[LiteralType], Sequence[Type]]:\n    \"\"\"Separate literals from other members in a union type.\"\"\"\n    literal_items = []\n    union_items = []\n\n    for item in t.items:\n        proper = get_proper_type(item)\n        if isinstance(proper, LiteralType):\n            literal_items.append(proper)\n        else:\n            union_items.append(item)\n\n    return literal_items, union_items\n\n\ndef try_getting_instance_fallback(typ: Type) -> Instance | None:\n    \"\"\"Returns the Instance fallback for this type if one exists or None.\"\"\"\n    typ = get_proper_type(typ)\n    if isinstance(typ, Instance):\n        return typ\n    elif isinstance(typ, LiteralType):\n        return typ.fallback\n    elif isinstance(typ, (NoneType, AnyType)):\n        return None  # Fast path for None, which is common\n    elif isinstance(typ, FunctionLike):\n        return typ.fallback\n    elif isinstance(typ, TypeVarType):\n        return try_getting_instance_fallback(typ.upper_bound)\n    elif isinstance(typ, TupleType):\n        return typ.partial_fallback\n    elif isinstance(typ, TypedDictType):\n        return typ.fallback\n    return None\n\n\ndef fixup_partial_type(typ: Type) -> Type:\n    \"\"\"Convert a partial type that we couldn't resolve into something concrete.\n\n    This means, for None we make it Optional[Any], and for anything else we\n    fill in all of the type arguments with Any.\n    \"\"\"\n    if not isinstance(typ, PartialType):\n        return typ\n    if typ.type is None:\n        return UnionType.make_union([AnyType(TypeOfAny.unannotated), NoneType()])\n    else:\n        return Instance(typ.type, [AnyType(TypeOfAny.unannotated)] * len(typ.type.type_vars))\n\n\ndef get_protocol_member(\n    left: Instance, member: str, class_obj: bool, is_lvalue: bool = False\n) -> Type | None:\n    if member == \"__call__\" and class_obj:\n        # Special case: class objects always have __call__ that is just the constructor.\n\n        # TODO: this is wrong, it creates callables that are not recognized as type objects.\n        # Long-term, we should probably get rid of this callback argument altogether.\n        def named_type(fullname: str) -> Instance:\n            return Instance(left.type.mro[-1], [])\n\n        return type_object_type(left.type, named_type)\n\n    if member == \"__call__\" and left.type.is_metaclass(precise=True):\n        # Special case: we want to avoid falling back to metaclass __call__\n        # if constructor signature didn't match, this can cause many false negatives.\n        return None\n\n    from mypy.subtypes import find_member\n\n    subtype = find_member(member, left, left, class_obj=class_obj, is_lvalue=is_lvalue)\n    if isinstance(subtype, PartialType):\n        subtype = (\n            NoneType()\n            if subtype.type is None\n            else Instance(\n                subtype.type, [AnyType(TypeOfAny.unannotated)] * len(subtype.type.type_vars)\n            )\n        )\n    return subtype\n\n\ndef _is_disjoint_base(info: TypeInfo) -> bool:\n    # It either has the @disjoint_base decorator or defines nonempty __slots__.\n    if info.is_disjoint_base:\n        return True\n    if not info.slots:\n        return False\n    own_slots = {\n        slot\n        for slot in info.slots\n        if not any(\n            base_info.type.slots is not None and slot in base_info.type.slots\n            for base_info in info.bases\n        )\n    }\n    return bool(own_slots)\n\n\ndef _get_disjoint_base_of(instance: Instance) -> TypeInfo | None:\n    \"\"\"Returns the disjoint base of the given instance, if it exists.\"\"\"\n    if _is_disjoint_base(instance.type):\n        return instance.type\n    for base in instance.type.mro:\n        if _is_disjoint_base(base):\n            return base\n    return None\n\n\ndef can_have_shared_disjoint_base(instances: list[Instance]) -> bool:\n    \"\"\"Returns whether the given instances can share a disjoint base.\n\n    This means that a child class of these classes can exist at runtime.\n    \"\"\"\n    # Ignore None disjoint bases (which are `object`).\n    disjoint_bases = [\n        base for instance in instances if (base := _get_disjoint_base_of(instance)) is not None\n    ]\n    if not disjoint_bases:\n        # All are `object`.\n        return True\n\n    candidate = disjoint_bases[0]\n    for base in disjoint_bases[1:]:\n        if candidate.has_base(base.fullname):\n            continue\n        elif base.has_base(candidate.fullname):\n            candidate = base\n        else:\n            return False\n    return True\n"
  },
  {
    "path": "mypy/types.py",
    "content": "\"\"\"Classes for representing mypy types.\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nfrom abc import abstractmethod\nfrom collections.abc import Iterable, Sequence\nfrom typing import (\n    Any,\n    ClassVar,\n    Final,\n    NewType,\n    TypeAlias as _TypeAlias,\n    TypeGuard,\n    TypeVar,\n    cast,\n    overload,\n)\nfrom typing_extensions import Self\n\nfrom librt.internal import (\n    read_int as read_int_bare,\n    read_str as read_str_bare,\n    write_int as write_int_bare,\n    write_str as write_str_bare,\n)\n\nimport mypy.nodes\nfrom mypy.bogus_type import Bogus\nfrom mypy.cache import (\n    DICT_STR_GEN,\n    END_TAG,\n    EXTRA_ATTRS,\n    LIST_GEN,\n    LITERAL_NONE,\n    ReadBuffer,\n    Tag,\n    WriteBuffer,\n    read_bool,\n    read_int,\n    read_int_list,\n    read_literal,\n    read_str,\n    read_str_list,\n    read_str_opt,\n    read_str_opt_list,\n    read_tag,\n    write_bool,\n    write_int,\n    write_int_list,\n    write_literal,\n    write_str,\n    write_str_list,\n    write_str_opt,\n    write_str_opt_list,\n    write_tag,\n)\nfrom mypy.nodes import ARG_KINDS, ARG_POS, ARG_STAR, ARG_STAR2, INVARIANT, ArgKind, SymbolNode\nfrom mypy.options import Options\nfrom mypy.state import state\nfrom mypy.util import IdMapper\n\nT = TypeVar(\"T\")\n\nJsonDict: _TypeAlias = dict[str, Any]\n\n# The set of all valid expressions that can currently be contained\n# inside of a Literal[...].\n#\n# Literals can contain bytes and enum-values: we special-case both of these\n# and store the value as a string. We rely on the fallback type that's also\n# stored with the Literal to determine how a string is being used.\n#\n# TODO: confirm that we're happy with representing enums (and the\n# other types) in the manner described above.\n#\n# Note: if we change the set of types included below, we must also\n# make sure to audit the following methods:\n#\n# 1. types.LiteralType's serialize and deserialize methods: this method\n#    needs to make sure it can convert the below types into JSON and back.\n#\n# 2. types.LiteralType's 'value_repr` method: this method is ultimately used\n#    by TypeStrVisitor's visit_literal_type to generate a reasonable\n#    repr-able output.\n#\n# 3. server.astdiff.SnapshotTypeVisitor's visit_literal_type_method: this\n#    method assumes that the following types supports equality checks and\n#    hashability.\n#\n# Note: Although \"Literal[None]\" is a valid type, we internally always convert\n# such a type directly into \"None\". So, \"None\" is not a valid parameter of\n# LiteralType and is omitted from this list.\n#\n# Note: Float values are only used internally. They are not accepted within\n# Literal[...].\nLiteralValue: _TypeAlias = int | str | bool | float\n\n\nTUPLE_NAMES: Final = (\"builtins.tuple\", \"typing.Tuple\")\nTYPE_NAMES: Final = (\"builtins.type\", \"typing.Type\")\n\nTYPE_VAR_LIKE_NAMES: Final = (\n    \"typing.TypeVar\",\n    \"typing_extensions.TypeVar\",\n    \"typing.ParamSpec\",\n    \"typing_extensions.ParamSpec\",\n    \"typing.TypeVarTuple\",\n    \"typing_extensions.TypeVarTuple\",\n)\n\nTYPED_NAMEDTUPLE_NAMES: Final = (\"typing.NamedTuple\", \"typing_extensions.NamedTuple\")\n\n# Supported names of TypedDict type constructors.\nTPDICT_NAMES: Final = (\n    \"typing.TypedDict\",\n    \"typing_extensions.TypedDict\",\n    \"mypy_extensions.TypedDict\",\n)\n\n# Supported fallback instance type names for TypedDict types.\nTPDICT_FB_NAMES: Final = (\n    \"typing._TypedDict\",\n    \"typing_extensions._TypedDict\",\n    \"mypy_extensions._TypedDict\",\n)\n\n# Supported names of Protocol base class.\nPROTOCOL_NAMES: Final = (\"typing.Protocol\", \"typing_extensions.Protocol\")\n\n# Supported TypeAlias names.\nTYPE_ALIAS_NAMES: Final = (\"typing.TypeAlias\", \"typing_extensions.TypeAlias\")\n\n# Supported Final type names.\nFINAL_TYPE_NAMES: Final = (\"typing.Final\", \"typing_extensions.Final\")\n\n# Supported @final decorator names.\nFINAL_DECORATOR_NAMES: Final = (\"typing.final\", \"typing_extensions.final\")\n\n# Supported @type_check_only names.\nTYPE_CHECK_ONLY_NAMES: Final = (\"typing.type_check_only\", \"typing_extensions.type_check_only\")\n\n# Supported Literal type names.\nLITERAL_TYPE_NAMES: Final = (\"typing.Literal\", \"typing_extensions.Literal\")\n\n# Supported Annotated type names.\nANNOTATED_TYPE_NAMES: Final = (\"typing.Annotated\", \"typing_extensions.Annotated\")\n\n# Supported Concatenate type names.\nCONCATENATE_TYPE_NAMES: Final = (\"typing.Concatenate\", \"typing_extensions.Concatenate\")\n\n# Supported Unpack type names.\nUNPACK_TYPE_NAMES: Final = (\"typing.Unpack\", \"typing_extensions.Unpack\")\n\n# Supported @deprecated decorator names\nDEPRECATED_TYPE_NAMES: Final = (\"warnings.deprecated\", \"typing_extensions.deprecated\")\n\n# Supported @disjoint_base decorator names\nDISJOINT_BASE_DECORATOR_NAMES: Final = (\"typing.disjoint_base\", \"typing_extensions.disjoint_base\")\n\n# We use this constant in various places when checking `tuple` subtyping:\nTUPLE_LIKE_INSTANCE_NAMES: Final = (\n    \"builtins.tuple\",\n    \"typing.Iterable\",\n    \"typing.Container\",\n    \"typing.Sequence\",\n    \"typing.Reversible\",\n)\n\nIMPORTED_REVEAL_TYPE_NAMES: Final = (\"typing.reveal_type\", \"typing_extensions.reveal_type\")\nREVEAL_TYPE_NAMES: Final = (\"builtins.reveal_type\", *IMPORTED_REVEAL_TYPE_NAMES)\n\nASSERT_TYPE_NAMES: Final = (\"typing.assert_type\", \"typing_extensions.assert_type\")\n\nOVERLOAD_NAMES: Final = (\"typing.overload\", \"typing_extensions.overload\")\n\nNEVER_NAMES: Final = (\n    \"typing.NoReturn\",\n    \"typing_extensions.NoReturn\",\n    \"mypy_extensions.NoReturn\",\n    \"typing.Never\",\n    \"typing_extensions.Never\",\n)\n\n# Mypyc fixed-width native int types (compatible with builtins.int)\nMYPYC_NATIVE_INT_NAMES: Final = (\n    \"mypy_extensions.i64\",\n    \"mypy_extensions.i32\",\n    \"mypy_extensions.i16\",\n    \"mypy_extensions.u8\",\n)\n\nDATACLASS_TRANSFORM_NAMES: Final = (\n    \"typing.dataclass_transform\",\n    \"typing_extensions.dataclass_transform\",\n)\n# Supported @override decorator names.\nOVERRIDE_DECORATOR_NAMES: Final = (\"typing.override\", \"typing_extensions.override\")\n\nELLIPSIS_TYPE_NAMES: Final = (\"builtins.ellipsis\", \"types.EllipsisType\")\n\nNOT_IMPLEMENTED_TYPE_NAMES: Final = (\"builtins._NotImplementedType\", \"types.NotImplementedType\")\n\n# A placeholder used for Bogus[...] parameters\n_dummy: Final[Any] = object()\n\n# A placeholder for int parameters\n_dummy_int: Final = -999999\n\n\nclass TypeOfAny:\n    \"\"\"\n    This class describes different types of Any. Each 'Any' can be of only one type at a time.\n    \"\"\"\n\n    __slots__ = ()\n\n    # Was this Any type inferred without a type annotation?\n    unannotated: Final = 1\n    # Does this Any come from an explicit type annotation?\n    explicit: Final = 2\n    # Does this come from an unfollowed import? See --disallow-any-unimported option\n    from_unimported_type: Final = 3\n    # Does this Any type come from omitted generics?\n    from_omitted_generics: Final = 4\n    # Does this Any come from an error?\n    from_error: Final = 5\n    # Is this a type that can't be represented in mypy's type system? For instance, type of\n    # call to NewType(...). Even though these types aren't real Anys, we treat them as such.\n    # Also used for variables named '_'.\n    special_form: Final = 6\n    # Does this Any come from interaction with another Any?\n    from_another_any: Final = 7\n    # Does this Any come from an implementation limitation/bug?\n    implementation_artifact: Final = 8\n    # Does this Any come from use in the suggestion engine?  This is\n    # used to ignore Anys inserted by the suggestion engine when\n    # generating constraints.\n    suggestion_engine: Final = 9\n\n\ndef deserialize_type(data: JsonDict | str) -> Type:\n    if isinstance(data, str):\n        return Instance.deserialize(data)\n    classname = data[\".class\"]\n    method = deserialize_map.get(classname)\n    if method is not None:\n        return method(data)\n    raise NotImplementedError(f\"unexpected .class {classname}\")\n\n\nclass Type(mypy.nodes.Context):\n    \"\"\"Abstract base class for all types.\"\"\"\n\n    __slots__ = (\"_can_be_true\", \"_can_be_false\")\n    # 'can_be_true' and 'can_be_false' mean whether the value of the\n    # expression can be true or false in a boolean context. They are useful\n    # when inferring the type of logic expressions like `x and y`.\n    #\n    # For example:\n    #   * the literal `False` can't be true while `True` can.\n    #   * a value with type `bool` can be true or false.\n    #   * `None` can't be true\n    #   * ...\n\n    def __init__(self, line: int = -1, column: int = -1) -> None:\n        super().__init__(line, column)\n        # Value of these can be -1 (use the default, lazy init), 0 (false) or 1 (true)\n        self._can_be_true = -1\n        self._can_be_false = -1\n\n    @property\n    def can_be_true(self) -> bool:\n        if self._can_be_true == -1:  # Lazy init helps mypyc\n            self._can_be_true = self.can_be_true_default()\n        return bool(self._can_be_true)\n\n    @can_be_true.setter\n    def can_be_true(self, v: bool) -> None:\n        self._can_be_true = v\n\n    @property\n    def can_be_false(self) -> bool:\n        if self._can_be_false == -1:  # Lazy init helps mypyc\n            self._can_be_false = self.can_be_false_default()\n        return bool(self._can_be_false)\n\n    @can_be_false.setter\n    def can_be_false(self, v: bool) -> None:\n        self._can_be_false = v\n\n    def can_be_true_default(self) -> bool:\n        return True\n\n    def can_be_false_default(self) -> bool:\n        return True\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        raise RuntimeError(\"Not implemented\", type(self))\n\n    def __repr__(self) -> str:\n        return self.accept(TypeStrVisitor(options=Options()))\n\n    def str_with_options(self, options: Options) -> str:\n        return self.accept(TypeStrVisitor(options=options))\n\n    def serialize(self) -> JsonDict | str:\n        raise NotImplementedError(f\"Cannot serialize {self.__class__.__name__} instance\")\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> Type:\n        raise NotImplementedError(f\"Cannot deserialize {cls.__name__} instance\")\n\n    def write(self, data: WriteBuffer) -> None:\n        raise NotImplementedError(f\"Cannot serialize {self.__class__.__name__} instance\")\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> Type:\n        raise NotImplementedError(f\"Cannot deserialize {cls.__name__} instance\")\n\n\nclass TypeAliasType(Type):\n    \"\"\"A type alias to another type.\n\n    To support recursive type aliases we don't immediately expand a type alias\n    during semantic analysis, but create an instance of this type that records the target alias\n    definition node (mypy.nodes.TypeAlias) and type arguments (for generic aliases).\n\n    This is very similar to how TypeInfo vs Instance interact, where a recursive class-based\n    structure like\n        class Node:\n            value: int\n            children: List[Node]\n    can be represented in a tree-like manner.\n    \"\"\"\n\n    __slots__ = (\"alias\", \"args\", \"type_ref\")\n\n    def __init__(\n        self,\n        alias: mypy.nodes.TypeAlias | None,\n        args: list[Type],\n        line: int = -1,\n        column: int = -1,\n    ) -> None:\n        super().__init__(line, column)\n        self.alias = alias\n        self.args = args\n        self.type_ref: str | None = None\n\n    def _expand_once(self) -> Type:\n        \"\"\"Expand to the target type exactly once.\n\n        This doesn't do full expansion, i.e. the result can contain another\n        (or even this same) type alias. Use this internal helper only when really needed,\n        its public wrapper mypy.types.get_proper_type() is preferred.\n        \"\"\"\n        assert self.alias is not None\n        if self.alias.no_args:\n            # We know that no_args=True aliases like L = List must have an instance\n            # as their target.\n            assert isinstance(self.alias.target, Instance)  # type: ignore[misc]\n            return self.alias.target.copy_modified(args=self.args)\n\n        # TODO: this logic duplicates the one in expand_type_by_instance().\n        if self.alias.tvar_tuple_index is None:\n            mapping: dict[TypeVarId, Type] = {\n                v.id: s for (v, s) in zip(self.alias.alias_tvars, self.args)\n            }\n        else:\n            prefix = self.alias.tvar_tuple_index\n            suffix = len(self.alias.alias_tvars) - self.alias.tvar_tuple_index - 1\n            start, middle, end = split_with_prefix_and_suffix(tuple(self.args), prefix, suffix)\n            tvar = self.alias.alias_tvars[prefix]\n            assert isinstance(tvar, TypeVarTupleType)\n            mapping = {tvar.id: TupleType(list(middle), tvar.tuple_fallback)}\n            for tvar, sub in zip(\n                self.alias.alias_tvars[:prefix] + self.alias.alias_tvars[prefix + 1 :], start + end\n            ):\n                mapping[tvar.id] = sub\n\n        return self.alias.target.accept(InstantiateAliasVisitor(mapping))\n\n    @property\n    def is_recursive(self) -> bool:\n        \"\"\"Whether this type alias is recursive.\n\n        Note this doesn't check generic alias arguments, but only if this alias\n        *definition* is recursive. The property value thus can be cached on the\n        underlying TypeAlias node. If you want to include all nested types, use\n        has_recursive_types() function.\n        \"\"\"\n        assert self.alias is not None, \"Unfixed type alias\"\n        is_recursive = self.alias._is_recursive\n        if is_recursive is None:\n            is_recursive = self.alias in self.alias.target.accept(CollectAliasesVisitor())\n            # We cache the value on the underlying TypeAlias node as an optimization,\n            # since the value is the same for all instances of the same alias.\n            self.alias._is_recursive = is_recursive\n        return is_recursive\n\n    def can_be_true_default(self) -> bool:\n        if self.alias is not None:\n            return self.alias.target.can_be_true\n        return super().can_be_true_default()\n\n    def can_be_false_default(self) -> bool:\n        if self.alias is not None:\n            return self.alias.target.can_be_false\n        return super().can_be_false_default()\n\n    def copy_modified(self, *, args: list[Type] | None = None) -> TypeAliasType:\n        return TypeAliasType(\n            self.alias, args if args is not None else self.args.copy(), self.line, self.column\n        )\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_type_alias_type(self)\n\n    def __hash__(self) -> int:\n        return hash((self.alias, tuple(self.args)))\n\n    def __eq__(self, other: object) -> bool:\n        # Note: never use this to determine subtype relationships, use is_subtype().\n        if not isinstance(other, TypeAliasType):\n            return NotImplemented\n        return self.alias == other.alias and self.args == other.args\n\n    def serialize(self) -> JsonDict:\n        assert self.alias is not None\n        data: JsonDict = {\n            \".class\": \"TypeAliasType\",\n            \"type_ref\": self.alias.fullname,\n            \"args\": [arg.serialize() for arg in self.args],\n        }\n        return data\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypeAliasType:\n        assert data[\".class\"] == \"TypeAliasType\"\n        args: list[Type] = []\n        if \"args\" in data:\n            args_list = data[\"args\"]\n            assert isinstance(args_list, list)\n            args = [deserialize_type(arg) for arg in args_list]\n        alias = TypeAliasType(None, args)\n        alias.type_ref = data[\"type_ref\"]\n        return alias\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, TYPE_ALIAS_TYPE)\n        write_type_list(data, self.args)\n        assert self.alias is not None\n        write_str(data, self.alias.fullname)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> TypeAliasType:\n        alias = TypeAliasType(None, read_type_list(data))\n        alias.type_ref = read_str(data)\n        assert read_tag(data) == END_TAG\n        return alias\n\n\nclass TypeGuardedType(Type):\n    \"\"\"Only used by find_isinstance_check() etc.\"\"\"\n\n    __slots__ = (\"type_guard\",)\n\n    def __init__(self, type_guard: Type) -> None:\n        super().__init__(line=type_guard.line, column=type_guard.column)\n        self.type_guard = type_guard\n\n    def __repr__(self) -> str:\n        return f\"TypeGuard({self.type_guard})\"\n\n    # This may hide some real bugs, but it is convenient for various \"synthetic\"\n    # visitors, similar to RequiredType and ReadOnlyType below.\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return self.type_guard.accept(visitor)\n\n\nclass RequiredType(Type):\n    \"\"\"Required[T] or NotRequired[T]. Only usable at top-level of a TypedDict definition.\"\"\"\n\n    def __init__(self, item: Type, *, required: bool) -> None:\n        super().__init__(line=item.line, column=item.column)\n        self.item = item\n        self.required = required\n\n    def __repr__(self) -> str:\n        if self.required:\n            return f\"Required[{self.item}]\"\n        else:\n            return f\"NotRequired[{self.item}]\"\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return self.item.accept(visitor)\n\n\nclass ReadOnlyType(Type):\n    \"\"\"ReadOnly[T] Only usable at top-level of a TypedDict definition.\"\"\"\n\n    def __init__(self, item: Type) -> None:\n        super().__init__(line=item.line, column=item.column)\n        self.item = item\n\n    def __repr__(self) -> str:\n        return f\"ReadOnly[{self.item}]\"\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return self.item.accept(visitor)\n\n\nclass ProperType(Type):\n    \"\"\"Not a type alias.\n\n    Every type except TypeAliasType must inherit from this type.\n    \"\"\"\n\n    __slots__ = ()\n\n\nclass TypeVarId:\n    # A type variable is uniquely identified by its raw id and meta level.\n\n    # For plain variables (type parameters of generic classes and\n    # functions) raw ids are allocated by semantic analysis, using\n    # positive ids 1, 2, ... for generic class parameters and negative\n    # ids -1, ... for generic function type arguments. A special value 0\n    # is reserved for Self type variable (autogenerated). This convention\n    # is only used to keep type variable ids distinct when allocating\n    # them; the type checker makes no distinction between class and\n    # function type variables.\n\n    # Metavariables are allocated unique ids starting from 1.\n    raw_id: Final[int]\n\n    # Level of the variable in type inference. Currently either 0 for\n    # declared types, or 1 for type inference metavariables.\n    meta_level: int = 0\n\n    # Class variable used for allocating fresh ids for metavariables.\n    next_raw_id: ClassVar[int] = 1\n\n    # Fullname of class or function/method which declares this type\n    # variable (not the fullname of the TypeVar definition!), or ''\n    namespace: str\n\n    def __init__(self, raw_id: int, meta_level: int = 0, *, namespace: str = \"\") -> None:\n        self.raw_id = raw_id\n        self.meta_level = meta_level\n        self.namespace = namespace\n\n    @staticmethod\n    def new(meta_level: int) -> TypeVarId:\n        raw_id = TypeVarId.next_raw_id\n        TypeVarId.next_raw_id += 1\n        return TypeVarId(raw_id, meta_level)\n\n    def __repr__(self) -> str:\n        return self.raw_id.__repr__()\n\n    def __eq__(self, other: object) -> bool:\n        # Although this call is not expensive (like UnionType or TypedDictType),\n        # most of the time we get the same object here, so add a fast path.\n        if self is other:\n            return True\n        return (\n            isinstance(other, TypeVarId)\n            and self.raw_id == other.raw_id\n            and self.meta_level == other.meta_level\n            and self.namespace == other.namespace\n        )\n\n    def __ne__(self, other: object) -> bool:\n        return not (self == other)\n\n    def __hash__(self) -> int:\n        return self.raw_id ^ (self.meta_level << 8) ^ hash(self.namespace)\n\n    def is_meta_var(self) -> bool:\n        return self.meta_level > 0\n\n    def is_self(self) -> bool:\n        # This is a special value indicating typing.Self variable.\n        return self.raw_id == 0\n\n\nclass TypeVarLikeType(ProperType):\n    __slots__ = (\"name\", \"fullname\", \"id\", \"upper_bound\", \"default\")\n\n    name: str  # Name (may be qualified)\n    fullname: str  # Fully qualified name\n    id: TypeVarId\n    upper_bound: Type\n    default: Type\n\n    def __init__(\n        self,\n        name: str,\n        fullname: str,\n        id: TypeVarId,\n        upper_bound: Type,\n        default: Type,\n        line: int = -1,\n        column: int = -1,\n    ) -> None:\n        super().__init__(line, column)\n        self.name = name\n        self.fullname = fullname\n        self.id = id\n        self.upper_bound = upper_bound\n        self.default = default\n\n    def serialize(self) -> JsonDict:\n        raise NotImplementedError\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypeVarLikeType:\n        raise NotImplementedError\n\n    def copy_modified(self, *, id: TypeVarId, **kwargs: Any) -> Self:\n        raise NotImplementedError\n\n    @classmethod\n    def new_unification_variable(cls, old: Self) -> Self:\n        new_id = TypeVarId.new(meta_level=1)\n        return old.copy_modified(id=new_id)\n\n    def has_default(self) -> bool:\n        t = get_proper_type(self.default)\n        return not (isinstance(t, AnyType) and t.type_of_any == TypeOfAny.from_omitted_generics)\n\n    def values_or_bound(self) -> ProperType:\n        if isinstance(self, TypeVarType) and self.values:\n            return UnionType(self.values)\n        return get_proper_type(self.upper_bound)\n\n\nclass TypeVarType(TypeVarLikeType):\n    \"\"\"Type that refers to a type variable.\"\"\"\n\n    __slots__ = (\"values\", \"variance\")\n\n    values: list[Type]  # Value restriction, empty list if no restriction\n    variance: int\n\n    def __init__(\n        self,\n        name: str,\n        fullname: str,\n        id: TypeVarId,\n        values: list[Type],\n        upper_bound: Type,\n        default: Type,\n        variance: int = INVARIANT,\n        line: int = -1,\n        column: int = -1,\n    ) -> None:\n        super().__init__(name, fullname, id, upper_bound, default, line, column)\n        assert values is not None, \"No restrictions must be represented by empty list\"\n        self.values = values\n        self.variance = variance\n\n    def copy_modified(\n        self,\n        *,\n        values: Bogus[list[Type]] = _dummy,\n        upper_bound: Bogus[Type] = _dummy,\n        default: Bogus[Type] = _dummy,\n        id: Bogus[TypeVarId] = _dummy,\n        line: int = _dummy_int,\n        column: int = _dummy_int,\n        **kwargs: Any,\n    ) -> TypeVarType:\n        return TypeVarType(\n            name=self.name,\n            fullname=self.fullname,\n            id=self.id if id is _dummy else id,\n            values=self.values if values is _dummy else values,\n            upper_bound=self.upper_bound if upper_bound is _dummy else upper_bound,\n            default=self.default if default is _dummy else default,\n            variance=self.variance,\n            line=self.line if line == _dummy_int else line,\n            column=self.column if column == _dummy_int else column,\n        )\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_type_var(self)\n\n    def __hash__(self) -> int:\n        return hash((self.id, self.upper_bound, tuple(self.values)))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, TypeVarType):\n            return NotImplemented\n        return (\n            self.id == other.id\n            and self.upper_bound == other.upper_bound\n            and self.values == other.values\n        )\n\n    def serialize(self) -> JsonDict:\n        assert not self.id.is_meta_var()\n        return {\n            \".class\": \"TypeVarType\",\n            \"name\": self.name,\n            \"fullname\": self.fullname,\n            \"id\": self.id.raw_id,\n            \"namespace\": self.id.namespace,\n            \"values\": [v.serialize() for v in self.values],\n            \"upper_bound\": self.upper_bound.serialize(),\n            \"default\": self.default.serialize(),\n            \"variance\": self.variance,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypeVarType:\n        assert data[\".class\"] == \"TypeVarType\"\n        return TypeVarType(\n            name=data[\"name\"],\n            fullname=data[\"fullname\"],\n            id=TypeVarId(data[\"id\"], namespace=data[\"namespace\"]),\n            values=[deserialize_type(v) for v in data[\"values\"]],\n            upper_bound=deserialize_type(data[\"upper_bound\"]),\n            default=deserialize_type(data[\"default\"]),\n            variance=data[\"variance\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, TYPE_VAR_TYPE)\n        write_str(data, self.name)\n        write_str(data, self.fullname)\n        write_int(data, self.id.raw_id)\n        write_str(data, self.id.namespace)\n        write_type_list(data, self.values)\n        self.upper_bound.write(data)\n        self.default.write(data)\n        write_int(data, self.variance)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> TypeVarType:\n        ret = TypeVarType(\n            read_str(data),\n            read_str(data),\n            TypeVarId(read_int(data), namespace=read_str(data)),\n            read_type_list(data),\n            read_type(data),\n            read_type(data),\n            read_int(data),\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass ParamSpecFlavor:\n    # Simple ParamSpec reference such as \"P\"\n    BARE: Final = 0\n    # P.args\n    ARGS: Final = 1\n    # P.kwargs\n    KWARGS: Final = 2\n\n\nclass ParamSpecType(TypeVarLikeType):\n    \"\"\"Type that refers to a ParamSpec.\n\n    A ParamSpec is a type variable that represents the parameter\n    types, names and kinds of a callable (i.e., the signature without\n    the return type).\n\n    This can be one of these forms\n     * P (ParamSpecFlavor.BARE)\n     * P.args (ParamSpecFlavor.ARGS)\n     * P.kwargs (ParamSpecFLavor.KWARGS)\n\n    The upper_bound is really used as a fallback type -- it's shared\n    with TypeVarType for simplicity. It can't be specified by the user\n    and the value is directly derived from the flavor (currently\n    always just 'object').\n    \"\"\"\n\n    __slots__ = (\"flavor\", \"prefix\")\n\n    flavor: int\n    prefix: Parameters\n\n    def __init__(\n        self,\n        name: str,\n        fullname: str,\n        id: TypeVarId,\n        flavor: int,\n        upper_bound: Type,\n        default: Type,\n        *,\n        line: int = -1,\n        column: int = -1,\n        prefix: Parameters | None = None,\n    ) -> None:\n        super().__init__(name, fullname, id, upper_bound, default, line=line, column=column)\n        self.flavor = flavor\n        self.prefix = prefix or Parameters([], [], [])\n\n    def with_flavor(self, flavor: int) -> ParamSpecType:\n        return ParamSpecType(\n            self.name,\n            self.fullname,\n            self.id,\n            flavor,\n            upper_bound=self.upper_bound,\n            default=self.default,\n            prefix=self.prefix,\n        )\n\n    def copy_modified(\n        self,\n        *,\n        id: Bogus[TypeVarId] = _dummy,\n        flavor: int = _dummy_int,\n        prefix: Bogus[Parameters] = _dummy,\n        default: Bogus[Type] = _dummy,\n        **kwargs: Any,\n    ) -> ParamSpecType:\n        return ParamSpecType(\n            self.name,\n            self.fullname,\n            id if id is not _dummy else self.id,\n            flavor if flavor != _dummy_int else self.flavor,\n            self.upper_bound,\n            default=default if default is not _dummy else self.default,\n            line=self.line,\n            column=self.column,\n            prefix=prefix if prefix is not _dummy else self.prefix,\n        )\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_param_spec(self)\n\n    def name_with_suffix(self) -> str:\n        n = self.name\n        if self.flavor == ParamSpecFlavor.ARGS:\n            return f\"{n}.args\"\n        elif self.flavor == ParamSpecFlavor.KWARGS:\n            return f\"{n}.kwargs\"\n        return n\n\n    def __hash__(self) -> int:\n        return hash((self.id, self.flavor, self.prefix))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, ParamSpecType):\n            return NotImplemented\n        # Upper bound can be ignored, since it's determined by flavor.\n        return self.id == other.id and self.flavor == other.flavor and self.prefix == other.prefix\n\n    def serialize(self) -> JsonDict:\n        assert not self.id.is_meta_var()\n        return {\n            \".class\": \"ParamSpecType\",\n            \"name\": self.name,\n            \"fullname\": self.fullname,\n            \"id\": self.id.raw_id,\n            \"namespace\": self.id.namespace,\n            \"flavor\": self.flavor,\n            \"upper_bound\": self.upper_bound.serialize(),\n            \"default\": self.default.serialize(),\n            \"prefix\": self.prefix.serialize(),\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> ParamSpecType:\n        assert data[\".class\"] == \"ParamSpecType\"\n        return ParamSpecType(\n            data[\"name\"],\n            data[\"fullname\"],\n            TypeVarId(data[\"id\"], namespace=data[\"namespace\"]),\n            data[\"flavor\"],\n            deserialize_type(data[\"upper_bound\"]),\n            deserialize_type(data[\"default\"]),\n            prefix=Parameters.deserialize(data[\"prefix\"]),\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, PARAM_SPEC_TYPE)\n        self.prefix.write(data)\n        write_str(data, self.name)\n        write_str(data, self.fullname)\n        write_int(data, self.id.raw_id)\n        write_str(data, self.id.namespace)\n        write_int(data, self.flavor)\n        self.upper_bound.write(data)\n        self.default.write(data)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> ParamSpecType:\n        assert read_tag(data) == PARAMETERS\n        prefix = Parameters.read(data)\n        ret = ParamSpecType(\n            read_str(data),\n            read_str(data),\n            TypeVarId(read_int(data), namespace=read_str(data)),\n            read_int(data),\n            read_type(data),\n            read_type(data),\n            prefix=prefix,\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass TypeVarTupleType(TypeVarLikeType):\n    \"\"\"Type that refers to a TypeVarTuple.\n\n    See PEP646 for more information.\n    \"\"\"\n\n    __slots__ = (\"tuple_fallback\", \"min_len\")\n\n    def __init__(\n        self,\n        name: str,\n        fullname: str,\n        id: TypeVarId,\n        upper_bound: Type,\n        tuple_fallback: Instance,\n        default: Type,\n        *,\n        line: int = -1,\n        column: int = -1,\n        min_len: int = 0,\n    ) -> None:\n        super().__init__(name, fullname, id, upper_bound, default, line=line, column=column)\n        self.tuple_fallback = tuple_fallback\n        # This value is not settable by a user. It is an internal-only thing to support\n        # len()-narrowing of variadic tuples.\n        self.min_len = min_len\n\n    def serialize(self) -> JsonDict:\n        assert not self.id.is_meta_var()\n        return {\n            \".class\": \"TypeVarTupleType\",\n            \"name\": self.name,\n            \"fullname\": self.fullname,\n            \"id\": self.id.raw_id,\n            \"namespace\": self.id.namespace,\n            \"upper_bound\": self.upper_bound.serialize(),\n            \"tuple_fallback\": self.tuple_fallback.serialize(),\n            \"default\": self.default.serialize(),\n            \"min_len\": self.min_len,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypeVarTupleType:\n        assert data[\".class\"] == \"TypeVarTupleType\"\n        return TypeVarTupleType(\n            data[\"name\"],\n            data[\"fullname\"],\n            TypeVarId(data[\"id\"], namespace=data[\"namespace\"]),\n            deserialize_type(data[\"upper_bound\"]),\n            Instance.deserialize(data[\"tuple_fallback\"]),\n            deserialize_type(data[\"default\"]),\n            min_len=data[\"min_len\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, TYPE_VAR_TUPLE_TYPE)\n        self.tuple_fallback.write(data)\n        write_str(data, self.name)\n        write_str(data, self.fullname)\n        write_int(data, self.id.raw_id)\n        write_str(data, self.id.namespace)\n        self.upper_bound.write(data)\n        self.default.write(data)\n        write_int(data, self.min_len)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> TypeVarTupleType:\n        assert read_tag(data) == INSTANCE\n        fallback = Instance.read(data)\n        ret = TypeVarTupleType(\n            read_str(data),\n            read_str(data),\n            TypeVarId(read_int(data), namespace=read_str(data)),\n            read_type(data),\n            fallback,\n            read_type(data),\n            min_len=read_int(data),\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_type_var_tuple(self)\n\n    def __hash__(self) -> int:\n        return hash((self.id, self.min_len))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, TypeVarTupleType):\n            return NotImplemented\n        return self.id == other.id and self.min_len == other.min_len\n\n    def copy_modified(\n        self,\n        *,\n        id: Bogus[TypeVarId] = _dummy,\n        upper_bound: Bogus[Type] = _dummy,\n        default: Bogus[Type] = _dummy,\n        min_len: Bogus[int] = _dummy,\n        **kwargs: Any,\n    ) -> TypeVarTupleType:\n        return TypeVarTupleType(\n            self.name,\n            self.fullname,\n            self.id if id is _dummy else id,\n            self.upper_bound if upper_bound is _dummy else upper_bound,\n            self.tuple_fallback,\n            self.default if default is _dummy else default,\n            line=self.line,\n            column=self.column,\n            min_len=self.min_len if min_len is _dummy else min_len,\n        )\n\n\nclass UnboundType(ProperType):\n    \"\"\"Instance type that has not been bound during semantic analysis.\"\"\"\n\n    __slots__ = (\n        \"name\",\n        \"args\",\n        \"optional\",\n        \"empty_tuple_index\",\n        \"original_str_expr\",\n        \"original_str_fallback\",\n    )\n\n    def __init__(\n        self,\n        name: str,\n        args: Sequence[Type] | None = None,\n        *,\n        line: int = -1,\n        column: int = -1,\n        optional: bool = False,\n        empty_tuple_index: bool = False,\n        original_str_expr: str | None = None,\n        original_str_fallback: str | None = None,\n    ) -> None:\n        super().__init__(line, column)\n        if not args:\n            args = []\n        self.name = name\n        self.args = tuple(args)\n        # Should this type be wrapped in an Optional?\n        self.optional = optional\n        # Special case for X[()]\n        self.empty_tuple_index = empty_tuple_index\n        # If this UnboundType was originally defined as a str or bytes, keep track of\n        # the original contents of that string-like thing. This way, if this UnboundExpr\n        # ever shows up inside of a LiteralType, we can determine whether that\n        # Literal[...] is valid or not. E.g. Literal[foo] is most likely invalid\n        # (unless 'foo' is an alias for another literal or something) and\n        # Literal[\"foo\"] most likely is.\n        #\n        # We keep track of the entire string instead of just using a boolean flag\n        # so we can distinguish between things like Literal[\"foo\"] vs\n        # Literal[\"    foo   \"].\n        #\n        # We also keep track of what the original base fallback type was supposed to be\n        # so we don't have to try and recompute it later\n        self.original_str_expr = original_str_expr\n        self.original_str_fallback = original_str_fallback\n\n    def copy_modified(self, args: Bogus[Sequence[Type] | None] = _dummy) -> UnboundType:\n        if args is _dummy:\n            args = self.args\n        return UnboundType(\n            name=self.name,\n            args=args,\n            line=self.line,\n            column=self.column,\n            optional=self.optional,\n            empty_tuple_index=self.empty_tuple_index,\n            original_str_expr=self.original_str_expr,\n            original_str_fallback=self.original_str_fallback,\n        )\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_unbound_type(self)\n\n    def __hash__(self) -> int:\n        return hash((self.name, self.optional, tuple(self.args), self.original_str_expr))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, UnboundType):\n            return NotImplemented\n        return (\n            self.name == other.name\n            and self.optional == other.optional\n            and self.args == other.args\n            and self.original_str_expr == other.original_str_expr\n            and self.original_str_fallback == other.original_str_fallback\n        )\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"UnboundType\",\n            \"name\": self.name,\n            \"args\": [a.serialize() for a in self.args],\n            \"expr\": self.original_str_expr,\n            \"expr_fallback\": self.original_str_fallback,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> UnboundType:\n        assert data[\".class\"] == \"UnboundType\"\n        return UnboundType(\n            data[\"name\"],\n            [deserialize_type(a) for a in data[\"args\"]],\n            original_str_expr=data[\"expr\"],\n            original_str_fallback=data[\"expr_fallback\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, UNBOUND_TYPE)\n        write_str(data, self.name)\n        write_type_list(data, self.args)\n        write_str_opt(data, self.original_str_expr)\n        write_str_opt(data, self.original_str_fallback)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> UnboundType:\n        ret = UnboundType(\n            read_str(data),\n            read_type_list(data),\n            original_str_expr=read_str_opt(data),\n            original_str_fallback=read_str_opt(data),\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass CallableArgument(ProperType):\n    \"\"\"Represents a Arg(type, 'name') inside a Callable's type list.\n\n    Note that this is a synthetic type for helping parse ASTs, not a real type.\n    \"\"\"\n\n    __slots__ = (\"typ\", \"name\", \"constructor\")\n\n    typ: Type\n    name: str | None\n    constructor: str | None\n\n    def __init__(\n        self,\n        typ: Type,\n        name: str | None,\n        constructor: str | None,\n        line: int = -1,\n        column: int = -1,\n    ) -> None:\n        super().__init__(line, column)\n        self.typ = typ\n        self.name = name\n        self.constructor = constructor\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        assert isinstance(visitor, SyntheticTypeVisitor)\n        ret: T = visitor.visit_callable_argument(self)\n        return ret\n\n    def serialize(self) -> JsonDict:\n        assert False, \"Synthetic types don't serialize\"\n\n\nclass TypeList(ProperType):\n    \"\"\"Information about argument types and names [...].\n\n    This is used for the arguments of a Callable type, i.e. for\n    [arg, ...] in Callable[[arg, ...], ret]. This is not a real type\n    but a syntactic AST construct. UnboundTypes can also have TypeList\n    types before they are processed into Callable types.\n    \"\"\"\n\n    __slots__ = (\"items\",)\n\n    items: list[Type]\n\n    def __init__(self, items: list[Type], line: int = -1, column: int = -1) -> None:\n        super().__init__(line, column)\n        self.items = items\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        assert isinstance(visitor, SyntheticTypeVisitor)\n        ret: T = visitor.visit_type_list(self)\n        return ret\n\n    def serialize(self) -> JsonDict:\n        assert False, \"Synthetic types don't serialize\"\n\n    def __hash__(self) -> int:\n        return hash(tuple(self.items))\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, TypeList) and self.items == other.items\n\n\nclass UnpackType(ProperType):\n    \"\"\"Type operator Unpack from PEP646. Can be either with Unpack[]\n    or unpacking * syntax.\n\n    The inner type should be either a TypeVarTuple, or a variable length tuple.\n    In an exceptional case of callable star argument it can be a fixed length tuple.\n\n    Note: the above restrictions are only guaranteed by normalizations after semantic\n    analysis, if your code needs to handle UnpackType *during* semantic analysis, it is\n    wild west, technically anything can be present in the wrapped type.\n    \"\"\"\n\n    __slots__ = [\"type\", \"from_star_syntax\"]\n\n    def __init__(\n        self, typ: Type, line: int = -1, column: int = -1, from_star_syntax: bool = False\n    ) -> None:\n        super().__init__(line, column)\n        self.type = typ\n        self.from_star_syntax = from_star_syntax\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_unpack_type(self)\n\n    def serialize(self) -> JsonDict:\n        return {\".class\": \"UnpackType\", \"type\": self.type.serialize()}\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, UNPACK_TYPE)\n        self.type.write(data)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> UnpackType:\n        ret = UnpackType(read_type(data))\n        assert read_tag(data) == END_TAG\n        return ret\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> UnpackType:\n        assert data[\".class\"] == \"UnpackType\"\n        typ = data[\"type\"]\n        return UnpackType(deserialize_type(typ))\n\n    def __hash__(self) -> int:\n        return hash(self.type)\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, UnpackType) and self.type == other.type\n\n\nclass AnyType(ProperType):\n    \"\"\"The type 'Any'.\"\"\"\n\n    __slots__ = (\"type_of_any\", \"source_any\", \"missing_import_name\")\n\n    def __init__(\n        self,\n        type_of_any: int,\n        source_any: AnyType | None = None,\n        missing_import_name: str | None = None,\n        line: int = -1,\n        column: int = -1,\n    ) -> None:\n        super().__init__(line, column)\n        self.type_of_any = type_of_any\n        # If this Any was created as a result of interacting with another 'Any', record the source\n        # and use it in reports.\n        self.source_any = source_any\n        if source_any and source_any.source_any:\n            self.source_any = source_any.source_any\n\n        if source_any is None:\n            self.missing_import_name = missing_import_name\n        else:\n            self.missing_import_name = source_any.missing_import_name\n\n        # Only unimported type anys and anys from other anys should have an import name\n        assert missing_import_name is None or type_of_any in (\n            TypeOfAny.from_unimported_type,\n            TypeOfAny.from_another_any,\n        )\n        # Only Anys that come from another Any can have source_any.\n        assert type_of_any != TypeOfAny.from_another_any or source_any is not None\n        # We should not have chains of Anys.\n        assert not self.source_any or self.source_any.type_of_any != TypeOfAny.from_another_any\n\n    @property\n    def is_from_error(self) -> bool:\n        return self.type_of_any == TypeOfAny.from_error\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_any(self)\n\n    def copy_modified(\n        self,\n        # Mark with Bogus because _dummy is just an object (with type Any)\n        type_of_any: int = _dummy_int,\n        original_any: Bogus[AnyType | None] = _dummy,\n        missing_import_name: Bogus[str | None] = _dummy,\n    ) -> AnyType:\n        if type_of_any == _dummy_int:\n            type_of_any = self.type_of_any\n        if original_any is _dummy:\n            original_any = self.source_any\n        if missing_import_name is _dummy:\n            missing_import_name = self.missing_import_name\n        return AnyType(\n            type_of_any=type_of_any,\n            source_any=original_any,\n            missing_import_name=missing_import_name,\n            line=self.line,\n            column=self.column,\n        )\n\n    def __hash__(self) -> int:\n        return hash(AnyType)\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, AnyType)\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"AnyType\",\n            \"type_of_any\": self.type_of_any,\n            \"source_any\": self.source_any.serialize() if self.source_any is not None else None,\n            \"missing_import_name\": self.missing_import_name,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> AnyType:\n        assert data[\".class\"] == \"AnyType\"\n        source = data[\"source_any\"]\n        return AnyType(\n            data[\"type_of_any\"],\n            AnyType.deserialize(source) if source is not None else None,\n            data[\"missing_import_name\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, ANY_TYPE)\n        write_type_opt(data, self.source_any)\n        write_int(data, self.type_of_any)\n        write_str_opt(data, self.missing_import_name)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> AnyType:\n        tag = read_tag(data)\n        if tag != LITERAL_NONE:\n            assert tag == ANY_TYPE\n            source_any = AnyType.read(data)\n        else:\n            source_any = None\n        ret = AnyType(read_int(data), source_any, read_str_opt(data))\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass UninhabitedType(ProperType):\n    \"\"\"This type has no members.\n\n    This type is the bottom type.\n    With strict Optional checking, it is the only common subtype between all\n    other types, which allows `meet` to be well defined.  Without strict\n    Optional checking, NoneType fills this role.\n\n    In general, for any type T:\n        join(UninhabitedType, T) = T\n        meet(UninhabitedType, T) = UninhabitedType\n        is_subtype(UninhabitedType, T) = True\n    \"\"\"\n\n    __slots__ = (\"ambiguous\",)\n\n    ambiguous: bool  # Is this a result of inference for a variable without constraints?\n\n    def __init__(self, line: int = -1, column: int = -1) -> None:\n        super().__init__(line, column)\n        self.ambiguous = False\n\n    def can_be_true_default(self) -> bool:\n        return False\n\n    def can_be_false_default(self) -> bool:\n        return False\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_uninhabited_type(self)\n\n    def __hash__(self) -> int:\n        return hash((UninhabitedType, self.ambiguous))\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, UninhabitedType) and other.ambiguous == self.ambiguous\n\n    def serialize(self) -> JsonDict:\n        return {\".class\": \"UninhabitedType\"}\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> UninhabitedType:\n        assert data[\".class\"] == \"UninhabitedType\"\n        return UninhabitedType()\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, UNINHABITED_TYPE)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> UninhabitedType:\n        assert read_tag(data) == END_TAG\n        return UninhabitedType()\n\n\nclass NoneType(ProperType):\n    \"\"\"The type of 'None'.\n\n    This type can be written by users as 'None'.\n    \"\"\"\n\n    __slots__ = ()\n\n    def __init__(self, line: int = -1, column: int = -1) -> None:\n        super().__init__(line, column)\n\n    def can_be_true_default(self) -> bool:\n        return False\n\n    def __hash__(self) -> int:\n        return hash(NoneType)\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, NoneType)\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_none_type(self)\n\n    def serialize(self) -> JsonDict:\n        return {\".class\": \"NoneType\"}\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> NoneType:\n        assert data[\".class\"] == \"NoneType\"\n        return NoneType()\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, NONE_TYPE)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> NoneType:\n        assert read_tag(data) == END_TAG\n        return NoneType()\n\n\n# NoneType used to be called NoneTyp so to avoid needlessly breaking\n# external plugins we keep that alias here.\nNoneTyp = NoneType\n\n\nclass ErasedType(ProperType):\n    \"\"\"Placeholder for an erased type.\n\n    This is used during type inference. This has the special property that\n    it is ignored during type inference.\n    \"\"\"\n\n    __slots__ = ()\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_erased_type(self)\n\n\nclass DeletedType(ProperType):\n    \"\"\"Type of deleted variables.\n\n    These can be used as lvalues but not rvalues.\n    \"\"\"\n\n    __slots__ = (\"source\",)\n\n    source: str | None  # May be None; name that generated this value\n\n    def __init__(self, source: str | None = None, line: int = -1, column: int = -1) -> None:\n        super().__init__(line, column)\n        self.source = source\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_deleted_type(self)\n\n    def serialize(self) -> JsonDict:\n        return {\".class\": \"DeletedType\", \"source\": self.source}\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> DeletedType:\n        assert data[\".class\"] == \"DeletedType\"\n        return DeletedType(data[\"source\"])\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, DELETED_TYPE)\n        write_str_opt(data, self.source)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> DeletedType:\n        ret = DeletedType(read_str_opt(data))\n        assert read_tag(data) == END_TAG\n        return ret\n\n\n# Fake TypeInfo to be used as a placeholder during Instance de-serialization.\nNOT_READY: Final = mypy.nodes.FakeInfo(\"De-serialization failure: TypeInfo not fixed\")\n\n\nclass ExtraAttrs:\n    \"\"\"Summary of module attributes and types.\n\n    This is used for instances of types.ModuleType, because they can have different\n    attributes per instance, and for type narrowing with hasattr() checks.\n    \"\"\"\n\n    def __init__(\n        self,\n        attrs: dict[str, Type],\n        immutable: set[str] | None = None,\n        mod_name: str | None = None,\n    ) -> None:\n        self.attrs = attrs\n        if immutable is None:\n            immutable = set()\n        self.immutable = immutable\n        self.mod_name = mod_name\n\n    def __hash__(self) -> int:\n        return hash((tuple(self.attrs.items()), tuple(sorted(self.immutable))))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, ExtraAttrs):\n            return NotImplemented\n        return self.attrs == other.attrs and self.immutable == other.immutable\n\n    def copy(self) -> ExtraAttrs:\n        return ExtraAttrs(self.attrs.copy(), self.immutable.copy(), self.mod_name)\n\n    def __repr__(self) -> str:\n        return f\"ExtraAttrs({self.attrs!r}, {self.immutable!r}, {self.mod_name!r})\"\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"ExtraAttrs\",\n            \"attrs\": {k: v.serialize() for k, v in self.attrs.items()},\n            \"immutable\": sorted(self.immutable),\n            \"mod_name\": self.mod_name,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> ExtraAttrs:\n        assert data[\".class\"] == \"ExtraAttrs\"\n        return ExtraAttrs(\n            {k: deserialize_type(v) for k, v in data[\"attrs\"].items()},\n            set(data[\"immutable\"]),\n            data[\"mod_name\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, EXTRA_ATTRS)\n        write_type_map(data, self.attrs)\n        write_str_list(data, sorted(self.immutable))\n        write_str_opt(data, self.mod_name)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> ExtraAttrs:\n        ret = ExtraAttrs(read_type_map(data), set(read_str_list(data)), read_str_opt(data))\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass Instance(ProperType):\n    \"\"\"An instance type of form C[T1, ..., Tn].\n\n    The list of type variables may be empty.\n\n    Several types have fallbacks to `Instance`, because in Python everything is an object\n    and this concept is impossible to express without intersection types. We therefore use\n    fallbacks for all \"non-special\" (like UninhabitedType, ErasedType etc) types.\n    \"\"\"\n\n    __slots__ = (\"type\", \"args\", \"invalid\", \"type_ref\", \"last_known_value\", \"_hash\", \"extra_attrs\")\n\n    def __init__(\n        self,\n        typ: mypy.nodes.TypeInfo,\n        args: Sequence[Type],\n        line: int = -1,\n        column: int = -1,\n        *,\n        last_known_value: LiteralType | None = None,\n        extra_attrs: ExtraAttrs | None = None,\n    ) -> None:\n        super().__init__(line, column)\n        self.type = typ\n        self.args = tuple(args)\n        self.type_ref: str | None = None\n\n        # This field keeps track of the underlying Literal[...] value associated with\n        # this instance, if one is known.\n        #\n        # This field is set whenever possible within expressions, but is erased upon\n        # variable assignment (see erasetype.remove_instance_last_known_values) unless\n        # the variable is declared to be final.\n        #\n        # For example, consider the following program:\n        #\n        #     a = 1\n        #     b: Final[int] = 2\n        #     c: Final = 3\n        #     print(a + b + c + 4)\n        #\n        # The 'Instance' objects associated with the expressions '1', '2', '3', and '4' will\n        # have last_known_values of type Literal[1], Literal[2], Literal[3], and Literal[4]\n        # respectively. However, the Instance object assigned to 'a' and 'b' will have their\n        # last_known_value erased: variable 'a' is mutable; variable 'b' was declared to be\n        # specifically an int.\n        #\n        # Or more broadly, this field lets this Instance \"remember\" its original declaration\n        # when applicable. We want this behavior because we want implicit Final declarations\n        # to act pretty much identically with constants: we should be able to replace any\n        # places where we use some Final variable with the original value and get the same\n        # type-checking behavior. For example, we want this program:\n        #\n        #    def expects_literal(x: Literal[3]) -> None: pass\n        #    var: Final = 3\n        #    expects_literal(var)\n        #\n        # ...to type-check in the exact same way as if we had written the program like this:\n        #\n        #    def expects_literal(x: Literal[3]) -> None: pass\n        #    expects_literal(3)\n        #\n        # In order to make this work (especially with literal types), we need var's type\n        # (an Instance) to remember the \"original\" value.\n        #\n        # Preserving this value within expressions is useful for similar reasons.\n        #\n        # Currently most of mypy will ignore this field and will continue to treat this type like\n        # a regular Instance. We end up using this field only when we are explicitly within a\n        # Literal context.\n        self.last_known_value = last_known_value\n\n        # Cached hash value\n        self._hash = -1\n\n        # Additional attributes defined per instance of this type. For example modules\n        # have different attributes per instance of types.ModuleType.\n        self.extra_attrs = extra_attrs\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_instance(self)\n\n    def __hash__(self) -> int:\n        if self._hash == -1:\n            self._hash = hash((self.type, self.args, self.last_known_value, self.extra_attrs))\n        return self._hash\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Instance):\n            return NotImplemented\n        return (\n            self.type == other.type\n            and self.args == other.args\n            and self.last_known_value == other.last_known_value\n            and self.extra_attrs == other.extra_attrs\n        )\n\n    def serialize(self) -> JsonDict | str:\n        assert self.type is not None\n        type_ref = self.type.fullname\n        if not self.args and not self.last_known_value and not self.extra_attrs:\n            return type_ref\n        data: JsonDict = {\n            \".class\": \"Instance\",\n            \"type_ref\": type_ref,\n            \"args\": [arg.serialize() for arg in self.args],\n        }\n        if self.last_known_value is not None:\n            data[\"last_known_value\"] = self.last_known_value.serialize()\n        data[\"extra_attrs\"] = self.extra_attrs.serialize() if self.extra_attrs else None\n        return data\n\n    @classmethod\n    def deserialize(cls, data: JsonDict | str) -> Instance:\n        if isinstance(data, str):\n            inst = Instance(NOT_READY, [])\n            inst.type_ref = data\n            return inst\n        assert data[\".class\"] == \"Instance\"\n        args: list[Type] = []\n        if \"args\" in data:\n            args_list = data[\"args\"]\n            assert isinstance(args_list, list)\n            args = [deserialize_type(arg) for arg in args_list]\n        inst = Instance(NOT_READY, args)\n        inst.type_ref = data[\"type_ref\"]  # Will be fixed up by fixup.py later.\n        if \"last_known_value\" in data:\n            inst.last_known_value = LiteralType.deserialize(data[\"last_known_value\"])\n        if data.get(\"extra_attrs\") is not None:\n            inst.extra_attrs = ExtraAttrs.deserialize(data[\"extra_attrs\"])\n        return inst\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, INSTANCE)\n        if not self.args and not self.last_known_value and not self.extra_attrs:\n            type_ref = self.type.fullname\n            if type_ref == \"builtins.str\":\n                write_tag(data, INSTANCE_STR)\n            elif type_ref == \"builtins.function\":\n                write_tag(data, INSTANCE_FUNCTION)\n            elif type_ref == \"builtins.int\":\n                write_tag(data, INSTANCE_INT)\n            elif type_ref == \"builtins.bool\":\n                write_tag(data, INSTANCE_BOOL)\n            elif type_ref == \"builtins.object\":\n                write_tag(data, INSTANCE_OBJECT)\n            else:\n                write_tag(data, INSTANCE_SIMPLE)\n                write_str_bare(data, type_ref)\n            return\n        write_tag(data, INSTANCE_GENERIC)\n        write_str(data, self.type.fullname)\n        write_type_list(data, self.args)\n        write_type_opt(data, self.last_known_value)\n        if self.extra_attrs is None:\n            write_tag(data, LITERAL_NONE)\n        else:\n            self.extra_attrs.write(data)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> Instance:\n        tag = read_tag(data)\n        # This is quite verbose, but this is very hot code, so we are not\n        # using dictionary lookups here.\n        if tag == INSTANCE_STR:\n            if instance_cache.str_type is None:\n                instance_cache.str_type = Instance(NOT_READY, [])\n                instance_cache.str_type.type_ref = \"builtins.str\"\n            return instance_cache.str_type\n        if tag == INSTANCE_FUNCTION:\n            if instance_cache.function_type is None:\n                instance_cache.function_type = Instance(NOT_READY, [])\n                instance_cache.function_type.type_ref = \"builtins.function\"\n            return instance_cache.function_type\n        if tag == INSTANCE_INT:\n            if instance_cache.int_type is None:\n                instance_cache.int_type = Instance(NOT_READY, [])\n                instance_cache.int_type.type_ref = \"builtins.int\"\n            return instance_cache.int_type\n        if tag == INSTANCE_BOOL:\n            if instance_cache.bool_type is None:\n                instance_cache.bool_type = Instance(NOT_READY, [])\n                instance_cache.bool_type.type_ref = \"builtins.bool\"\n            return instance_cache.bool_type\n        if tag == INSTANCE_OBJECT:\n            if instance_cache.object_type is None:\n                instance_cache.object_type = Instance(NOT_READY, [])\n                instance_cache.object_type.type_ref = \"builtins.object\"\n            return instance_cache.object_type\n        if tag == INSTANCE_SIMPLE:\n            inst = Instance(NOT_READY, [])\n            inst.type_ref = read_str_bare(data)\n            return inst\n        assert tag == INSTANCE_GENERIC\n        type_ref = read_str(data)\n        inst = Instance(NOT_READY, read_type_list(data))\n        inst.type_ref = type_ref\n        tag = read_tag(data)\n        if tag != LITERAL_NONE:\n            assert tag == LITERAL_TYPE\n            inst.last_known_value = LiteralType.read(data)\n        tag = read_tag(data)\n        if tag != LITERAL_NONE:\n            assert tag == EXTRA_ATTRS\n            inst.extra_attrs = ExtraAttrs.read(data)\n        assert read_tag(data) == END_TAG\n        return inst\n\n    def copy_modified(\n        self,\n        *,\n        args: Bogus[list[Type]] = _dummy,\n        last_known_value: Bogus[LiteralType | None] = _dummy,\n    ) -> Instance:\n        new = Instance(\n            typ=self.type,\n            args=args if args is not _dummy else self.args,\n            line=self.line,\n            column=self.column,\n            last_known_value=(\n                last_known_value if last_known_value is not _dummy else self.last_known_value\n            ),\n            extra_attrs=self.extra_attrs,\n        )\n        new.can_be_true = self.can_be_true\n        new.can_be_false = self.can_be_false\n        return new\n\n    def copy_with_extra_attr(self, name: str, typ: Type) -> Instance:\n        if self.extra_attrs:\n            existing_attrs = self.extra_attrs.copy()\n        else:\n            existing_attrs = ExtraAttrs({}, set(), None)\n        existing_attrs.attrs[name] = typ\n        new = self.copy_modified()\n        new.extra_attrs = existing_attrs\n        return new\n\n\nclass InstanceCache:\n    def __init__(self) -> None:\n        self.str_type: Instance | None = None\n        self.function_type: Instance | None = None\n        self.int_type: Instance | None = None\n        self.bool_type: Instance | None = None\n        self.object_type: Instance | None = None\n\n    def reset(self) -> None:\n        self.str_type = None\n        self.function_type = None\n        self.int_type = None\n        self.bool_type = None\n        self.object_type = None\n\n\ninstance_cache: Final = InstanceCache()\n\n\nclass FunctionLike(ProperType):\n    \"\"\"Abstract base class for function types.\"\"\"\n\n    __slots__ = (\"fallback\",)\n\n    fallback: Instance\n\n    def __init__(self, line: int = -1, column: int = -1) -> None:\n        super().__init__(line, column)\n        self._can_be_false = False\n\n    @abstractmethod\n    def is_type_obj(self) -> bool:\n        pass\n\n    @abstractmethod\n    def type_object(self) -> mypy.nodes.TypeInfo:\n        pass\n\n    @property\n    @abstractmethod\n    def items(self) -> list[CallableType]:\n        pass\n\n    @abstractmethod\n    def with_name(self, name: str) -> FunctionLike:\n        pass\n\n    @abstractmethod\n    def get_name(self) -> str | None:\n        pass\n\n    def bound(self) -> bool:\n        return bool(self.items) and self.items[0].is_bound\n\n\nclass FormalArgument:\n    def __init__(self, name: str | None, pos: int | None, typ: Type, required: bool) -> None:\n        self.name = name\n        self.pos = pos\n        self.typ = typ\n        self.required = required\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, FormalArgument):\n            return NotImplemented\n        return (\n            self.name == other.name\n            and self.pos == other.pos\n            and self.typ == other.typ\n            and self.required == other.required\n        )\n\n    def __hash__(self) -> int:\n        return hash((self.name, self.pos, self.typ, self.required))\n\n\nclass Parameters(ProperType):\n    \"\"\"Type that represents the parameters to a function.\n\n    Used for ParamSpec analysis. Note that by convention we handle this\n    type as a Callable without return type, not as a \"tuple with names\",\n    so that it behaves contravariantly, in particular [x: int] <: [int].\n    \"\"\"\n\n    __slots__ = (\n        \"arg_types\",\n        \"arg_kinds\",\n        \"arg_names\",\n        \"min_args\",\n        \"is_ellipsis_args\",\n        # TODO: variables don't really belong here, but they are used to allow hacky support\n        # for forall . Foo[[x: T], T] by capturing generic callable with ParamSpec, see #15909\n        \"variables\",\n        \"imprecise_arg_kinds\",\n    )\n\n    def __init__(\n        self,\n        arg_types: Sequence[Type],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None],\n        *,\n        variables: Sequence[TypeVarLikeType] | None = None,\n        is_ellipsis_args: bool = False,\n        imprecise_arg_kinds: bool = False,\n        line: int = -1,\n        column: int = -1,\n    ) -> None:\n        super().__init__(line, column)\n        self.arg_types = list(arg_types)\n        self.arg_kinds = arg_kinds\n        self.arg_names = list(arg_names)\n        assert len(arg_types) == len(arg_kinds) == len(arg_names)\n        assert not any(isinstance(t, Parameters) for t in arg_types)\n        self.min_args = arg_kinds.count(ARG_POS)\n        self.is_ellipsis_args = is_ellipsis_args\n        self.variables = variables or []\n        self.imprecise_arg_kinds = imprecise_arg_kinds\n\n    def copy_modified(\n        self,\n        arg_types: Bogus[Sequence[Type]] = _dummy,\n        arg_kinds: Bogus[list[ArgKind]] = _dummy,\n        arg_names: Bogus[Sequence[str | None]] = _dummy,\n        *,\n        variables: Bogus[Sequence[TypeVarLikeType]] = _dummy,\n        is_ellipsis_args: Bogus[bool] = _dummy,\n        imprecise_arg_kinds: Bogus[bool] = _dummy,\n    ) -> Parameters:\n        return Parameters(\n            arg_types=arg_types if arg_types is not _dummy else self.arg_types,\n            arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds,\n            arg_names=arg_names if arg_names is not _dummy else self.arg_names,\n            is_ellipsis_args=(\n                is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args\n            ),\n            variables=variables if variables is not _dummy else self.variables,\n            imprecise_arg_kinds=(\n                imprecise_arg_kinds\n                if imprecise_arg_kinds is not _dummy\n                else self.imprecise_arg_kinds\n            ),\n        )\n\n    # TODO: here is a lot of code duplication with Callable type, fix this.\n    def var_arg(self) -> FormalArgument | None:\n        \"\"\"The formal argument for *args.\"\"\"\n        for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):\n            if kind == ARG_STAR:\n                return FormalArgument(None, position, type, False)\n        return None\n\n    def kw_arg(self) -> FormalArgument | None:\n        \"\"\"The formal argument for **kwargs.\"\"\"\n        for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):\n            if kind == ARG_STAR2:\n                return FormalArgument(None, position, type, False)\n        return None\n\n    def formal_arguments(self, include_star_args: bool = False) -> list[FormalArgument]:\n        \"\"\"Yields the formal arguments corresponding to this callable, ignoring *arg and **kwargs.\n\n        To handle *args and **kwargs, use the 'callable.var_args' and 'callable.kw_args' fields,\n        if they are not None.\n\n        If you really want to include star args in the yielded output, set the\n        'include_star_args' parameter to 'True'.\"\"\"\n        args = []\n        done_with_positional = False\n        for i in range(len(self.arg_types)):\n            kind = self.arg_kinds[i]\n            if kind.is_named() or kind.is_star():\n                done_with_positional = True\n            if not include_star_args and kind.is_star():\n                continue\n\n            required = kind.is_required()\n            pos = None if done_with_positional else i\n            arg = FormalArgument(self.arg_names[i], pos, self.arg_types[i], required)\n            args.append(arg)\n        return args\n\n    def argument_by_name(self, name: str | None) -> FormalArgument | None:\n        if name is None:\n            return None\n        seen_star = False\n        for i, (arg_name, kind, typ) in enumerate(\n            zip(self.arg_names, self.arg_kinds, self.arg_types)\n        ):\n            # No more positional arguments after these.\n            if kind.is_named() or kind.is_star():\n                seen_star = True\n            if kind.is_star():\n                continue\n            if arg_name == name:\n                position = None if seen_star else i\n                return FormalArgument(name, position, typ, kind.is_required())\n        return self.try_synthesizing_arg_from_kwarg(name)\n\n    def argument_by_position(self, position: int | None) -> FormalArgument | None:\n        if position is None:\n            return None\n        if position >= len(self.arg_names):\n            return self.try_synthesizing_arg_from_vararg(position)\n        name, kind, typ = (\n            self.arg_names[position],\n            self.arg_kinds[position],\n            self.arg_types[position],\n        )\n        if kind.is_positional():\n            return FormalArgument(name, position, typ, kind == ARG_POS)\n        else:\n            return self.try_synthesizing_arg_from_vararg(position)\n\n    def try_synthesizing_arg_from_kwarg(self, name: str | None) -> FormalArgument | None:\n        kw_arg = self.kw_arg()\n        if kw_arg is not None:\n            return FormalArgument(name, None, kw_arg.typ, False)\n        else:\n            return None\n\n    def try_synthesizing_arg_from_vararg(self, position: int | None) -> FormalArgument | None:\n        var_arg = self.var_arg()\n        if var_arg is not None:\n            return FormalArgument(None, position, var_arg.typ, False)\n        else:\n            return None\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_parameters(self)\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"Parameters\",\n            \"arg_types\": [t.serialize() for t in self.arg_types],\n            \"arg_kinds\": [int(x.value) for x in self.arg_kinds],\n            \"arg_names\": self.arg_names,\n            \"variables\": [tv.serialize() for tv in self.variables],\n            \"imprecise_arg_kinds\": self.imprecise_arg_kinds,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> Parameters:\n        assert data[\".class\"] == \"Parameters\"\n        return Parameters(\n            [deserialize_type(t) for t in data[\"arg_types\"]],\n            # This is a micro-optimization until mypyc gets dedicated enum support. Otherwise,\n            # we would spend ~20% of types deserialization time in Enum.__call__().\n            [ARG_KINDS[x] for x in data[\"arg_kinds\"]],\n            data[\"arg_names\"],\n            variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data[\"variables\"]],\n            imprecise_arg_kinds=data[\"imprecise_arg_kinds\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, PARAMETERS)\n        write_type_list(data, self.arg_types)\n        write_int_list(data, [int(x.value) for x in self.arg_kinds])\n        write_str_opt_list(data, self.arg_names)\n        write_type_list(data, self.variables)\n        write_bool(data, self.imprecise_arg_kinds)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> Parameters:\n        ret = Parameters(\n            read_type_list(data),\n            # This is a micro-optimization until mypyc gets dedicated enum support. Otherwise,\n            # we would spend ~20% of types deserialization time in Enum.__call__().\n            [ARG_KINDS[ak] for ak in read_int_list(data)],\n            read_str_opt_list(data),\n            variables=read_type_var_likes(data),\n            imprecise_arg_kinds=read_bool(data),\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n    def __hash__(self) -> int:\n        return hash(\n            (\n                self.is_ellipsis_args,\n                tuple(self.arg_types),\n                tuple(self.arg_names),\n                tuple(self.arg_kinds),\n            )\n        )\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, Parameters):\n            return (\n                self.arg_types == other.arg_types\n                and self.arg_names == other.arg_names\n                and self.arg_kinds == other.arg_kinds\n                and self.is_ellipsis_args == other.is_ellipsis_args\n            )\n        else:\n            return NotImplemented\n\n\nCT = TypeVar(\"CT\", bound=\"CallableType\")\n\n\nclass CallableType(FunctionLike):\n    \"\"\"Type of a non-overloaded callable object (such as function).\"\"\"\n\n    __slots__ = (\n        \"arg_types\",  # Types of function arguments\n        \"arg_kinds\",  # ARG_ constants\n        \"arg_names\",  # Argument names; None if not a keyword argument\n        \"min_args\",  # Minimum number of arguments; derived from arg_kinds\n        \"ret_type\",  # Return value type\n        \"name\",  # Name (may be None; for error messages and plugins)\n        \"definition\",  # For error messages.  May be None.\n        \"variables\",  # Type variables for a generic function\n        \"is_ellipsis_args\",  # Is this Callable[..., t] (with literal '...')?\n        \"implicit\",  # Was this type implicitly generated instead of explicitly\n        # specified by the user?\n        \"special_sig\",  # Non-None for signatures that require special handling\n        # (currently only values are 'dict' for a signature similar to\n        # 'dict' and 'partial' for a `functools.partial` evaluation)\n        \"from_type_type\",  # Was this callable generated by analyzing Type[...]\n        # instantiation?\n        \"is_bound\",  # Is this a bound method?\n        \"type_guard\",  # T, if -> TypeGuard[T] (ret_type is bool in this case).\n        \"type_is\",  # T, if -> TypeIs[T] (ret_type is bool in this case).\n        \"from_concatenate\",  # whether this callable is from a concatenate object\n        # (this is used for error messages)\n        \"imprecise_arg_kinds\",\n        \"unpack_kwargs\",  # Was an Unpack[...] with **kwargs used to define this callable?\n    )\n\n    def __init__(\n        self,\n        # maybe this should be refactored to take a Parameters object\n        arg_types: Sequence[Type],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None],\n        ret_type: Type,\n        fallback: Instance,\n        name: str | None = None,\n        definition: SymbolNode | None = None,\n        variables: Sequence[TypeVarLikeType] | None = None,\n        line: int = -1,\n        column: int = -1,\n        is_ellipsis_args: bool = False,\n        implicit: bool = False,\n        special_sig: str | None = None,\n        from_type_type: bool = False,\n        is_bound: bool = False,\n        type_guard: Type | None = None,\n        type_is: Type | None = None,\n        from_concatenate: bool = False,\n        imprecise_arg_kinds: bool = False,\n        unpack_kwargs: bool = False,\n    ) -> None:\n        super().__init__(line, column)\n        assert len(arg_types) == len(arg_kinds) == len(arg_names)\n        self.arg_types = list(arg_types)\n        for t in self.arg_types:\n            if isinstance(t, ParamSpecType):\n                assert not t.prefix.arg_types\n                # TODO: should we assert that only ARG_STAR contain ParamSpecType?\n                # See testParamSpecJoin, that relies on passing e.g `P.args` as plain argument.\n        self.arg_kinds = arg_kinds\n        self.arg_names = list(arg_names)\n        self.min_args = arg_kinds.count(ARG_POS)\n        self.ret_type = ret_type\n        self.fallback = fallback\n        assert not name or \"<bound method\" not in name\n        self.name = name\n        # The rules for what exactly is considered a definition:\n        #   * If it is a non-decorated function, FuncDef is the definition\n        #   * If it is a decorated function, enclosing Decorator is the definition\n        self.definition = definition\n        self.variables: tuple[TypeVarLikeType, ...]\n        if variables is None:\n            self.variables = ()\n        else:\n            self.variables = tuple(variables)\n        self.is_ellipsis_args = is_ellipsis_args\n        self.implicit = implicit\n        self.special_sig = special_sig\n        self.from_type_type = from_type_type\n        self.from_concatenate = from_concatenate\n        self.imprecise_arg_kinds = imprecise_arg_kinds\n        self.is_bound = is_bound\n        self.type_guard = type_guard\n        self.type_is = type_is\n        self.unpack_kwargs = unpack_kwargs\n\n    def copy_modified(\n        self: CT,\n        arg_types: Bogus[Sequence[Type]] = _dummy,\n        arg_kinds: Bogus[list[ArgKind]] = _dummy,\n        arg_names: Bogus[Sequence[str | None]] = _dummy,\n        ret_type: Bogus[Type] = _dummy,\n        fallback: Bogus[Instance] = _dummy,\n        name: Bogus[str | None] = _dummy,\n        definition: Bogus[SymbolNode | None] = _dummy,\n        variables: Bogus[Sequence[TypeVarLikeType]] = _dummy,\n        line: int = _dummy_int,\n        column: int = _dummy_int,\n        is_ellipsis_args: Bogus[bool] = _dummy,\n        implicit: Bogus[bool] = _dummy,\n        special_sig: Bogus[str | None] = _dummy,\n        from_type_type: Bogus[bool] = _dummy,\n        is_bound: Bogus[bool] = _dummy,\n        type_guard: Bogus[Type | None] = _dummy,\n        type_is: Bogus[Type | None] = _dummy,\n        from_concatenate: Bogus[bool] = _dummy,\n        imprecise_arg_kinds: Bogus[bool] = _dummy,\n        unpack_kwargs: Bogus[bool] = _dummy,\n    ) -> CT:\n        modified = CallableType(\n            arg_types=arg_types if arg_types is not _dummy else self.arg_types,\n            arg_kinds=arg_kinds if arg_kinds is not _dummy else self.arg_kinds,\n            arg_names=arg_names if arg_names is not _dummy else self.arg_names,\n            ret_type=ret_type if ret_type is not _dummy else self.ret_type,\n            fallback=fallback if fallback is not _dummy else self.fallback,\n            name=name if name is not _dummy else self.name,\n            definition=definition if definition is not _dummy else self.definition,\n            variables=variables if variables is not _dummy else self.variables,\n            line=line if line != _dummy_int else self.line,\n            column=column if column != _dummy_int else self.column,\n            is_ellipsis_args=(\n                is_ellipsis_args if is_ellipsis_args is not _dummy else self.is_ellipsis_args\n            ),\n            implicit=implicit if implicit is not _dummy else self.implicit,\n            special_sig=special_sig if special_sig is not _dummy else self.special_sig,\n            from_type_type=from_type_type if from_type_type is not _dummy else self.from_type_type,\n            is_bound=is_bound if is_bound is not _dummy else self.is_bound,\n            type_guard=type_guard if type_guard is not _dummy else self.type_guard,\n            type_is=type_is if type_is is not _dummy else self.type_is,\n            from_concatenate=(\n                from_concatenate if from_concatenate is not _dummy else self.from_concatenate\n            ),\n            imprecise_arg_kinds=(\n                imprecise_arg_kinds\n                if imprecise_arg_kinds is not _dummy\n                else self.imprecise_arg_kinds\n            ),\n            unpack_kwargs=unpack_kwargs if unpack_kwargs is not _dummy else self.unpack_kwargs,\n        )\n        # Optimization: Only NewTypes are supported as subtypes since\n        # the class is effectively final, so we can use a cast safely.\n        return cast(CT, modified)\n\n    def var_arg(self) -> FormalArgument | None:\n        \"\"\"The formal argument for *args.\"\"\"\n        for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):\n            if kind == ARG_STAR:\n                return FormalArgument(None, position, type, False)\n        return None\n\n    def kw_arg(self) -> FormalArgument | None:\n        \"\"\"The formal argument for **kwargs.\"\"\"\n        for position, (type, kind) in enumerate(zip(self.arg_types, self.arg_kinds)):\n            if kind == ARG_STAR2:\n                return FormalArgument(None, position, type, False)\n        return None\n\n    @property\n    def is_var_arg(self) -> bool:\n        \"\"\"Does this callable have a *args argument?\"\"\"\n        return ARG_STAR in self.arg_kinds\n\n    @property\n    def is_kw_arg(self) -> bool:\n        \"\"\"Does this callable have a **kwargs argument?\"\"\"\n        return ARG_STAR2 in self.arg_kinds\n\n    def is_type_obj(self) -> bool:\n        return self.fallback.type.is_metaclass() and not isinstance(\n            get_proper_type(self.ret_type), UninhabitedType\n        )\n\n    def type_object(self) -> mypy.nodes.TypeInfo:\n        assert self.is_type_obj()\n        ret = get_proper_type(self.ret_type)\n        if isinstance(ret, TypeVarType):\n            ret = get_proper_type(ret.upper_bound)\n        if isinstance(ret, TupleType):\n            ret = ret.partial_fallback\n        if isinstance(ret, TypedDictType):\n            ret = ret.fallback\n        if isinstance(ret, LiteralType):\n            ret = ret.fallback\n        assert isinstance(ret, Instance)\n        return ret.type\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_callable_type(self)\n\n    def with_name(self, name: str) -> CallableType:\n        \"\"\"Return a copy of this type with the specified name.\"\"\"\n        return self.copy_modified(ret_type=self.ret_type, name=name)\n\n    def get_name(self) -> str | None:\n        return self.name\n\n    def max_possible_positional_args(self) -> int:\n        \"\"\"Returns maximum number of positional arguments this method could possibly accept.\n\n        This takes into account *arg and **kwargs but excludes keyword-only args.\"\"\"\n        if self.is_var_arg or self.is_kw_arg:\n            return sys.maxsize\n        return sum(kind.is_positional() for kind in self.arg_kinds)\n\n    def formal_arguments(self, include_star_args: bool = False) -> list[FormalArgument]:\n        \"\"\"Return a list of the formal arguments of this callable, ignoring *arg and **kwargs.\n\n        To handle *args and **kwargs, use the 'callable.var_args' and 'callable.kw_args' fields,\n        if they are not None.\n\n        If you really want to include star args in the yielded output, set the\n        'include_star_args' parameter to 'True'.\"\"\"\n        args = []\n        done_with_positional = False\n        for i in range(len(self.arg_types)):\n            kind = self.arg_kinds[i]\n            if kind.is_named() or kind.is_star():\n                done_with_positional = True\n            if not include_star_args and kind.is_star():\n                continue\n\n            required = kind.is_required()\n            pos = None if done_with_positional else i\n            arg = FormalArgument(self.arg_names[i], pos, self.arg_types[i], required)\n            args.append(arg)\n        return args\n\n    def argument_by_name(self, name: str | None) -> FormalArgument | None:\n        if name is None:\n            return None\n        seen_star = False\n        for i, (arg_name, kind, typ) in enumerate(\n            zip(self.arg_names, self.arg_kinds, self.arg_types)\n        ):\n            # No more positional arguments after these.\n            if kind.is_named() or kind.is_star():\n                seen_star = True\n            if kind.is_star():\n                continue\n            if arg_name == name:\n                position = None if seen_star else i\n                return FormalArgument(name, position, typ, kind.is_required())\n        return self.try_synthesizing_arg_from_kwarg(name)\n\n    def argument_by_position(self, position: int | None) -> FormalArgument | None:\n        if position is None:\n            return None\n        if position >= len(self.arg_names):\n            return self.try_synthesizing_arg_from_vararg(position)\n        name, kind, typ = (\n            self.arg_names[position],\n            self.arg_kinds[position],\n            self.arg_types[position],\n        )\n        if kind.is_positional():\n            return FormalArgument(name, position, typ, kind == ARG_POS)\n        else:\n            return self.try_synthesizing_arg_from_vararg(position)\n\n    def try_synthesizing_arg_from_kwarg(self, name: str | None) -> FormalArgument | None:\n        kw_arg = self.kw_arg()\n        if kw_arg is not None:\n            return FormalArgument(name, None, kw_arg.typ, False)\n        else:\n            return None\n\n    def try_synthesizing_arg_from_vararg(self, position: int | None) -> FormalArgument | None:\n        var_arg = self.var_arg()\n        if var_arg is not None:\n            return FormalArgument(None, position, var_arg.typ, False)\n        else:\n            return None\n\n    @property\n    def items(self) -> list[CallableType]:\n        return [self]\n\n    def is_generic(self) -> bool:\n        return bool(self.variables)\n\n    def type_var_ids(self) -> list[TypeVarId]:\n        a: list[TypeVarId] = []\n        for tv in self.variables:\n            a.append(tv.id)\n        return a\n\n    def param_spec(self) -> ParamSpecType | None:\n        \"\"\"Return ParamSpec if callable can be called with one.\n\n        A Callable accepting ParamSpec P args (*args, **kwargs) must have the\n        two final parameters like this: *args: P.args, **kwargs: P.kwargs.\n        \"\"\"\n        if len(self.arg_types) < 2:\n            return None\n        if self.arg_kinds[-2] != ARG_STAR or self.arg_kinds[-1] != ARG_STAR2:\n            return None\n        arg_type = self.arg_types[-2]\n        if not isinstance(arg_type, ParamSpecType):\n            return None\n\n        # Prepend prefix for def f(prefix..., *args: P.args, **kwargs: P.kwargs) -> ...\n        # TODO: confirm that all arg kinds are positional\n        prefix = Parameters(self.arg_types[:-2], self.arg_kinds[:-2], self.arg_names[:-2])\n        return arg_type.copy_modified(flavor=ParamSpecFlavor.BARE, prefix=prefix)\n\n    def normalize_trivial_unpack(self) -> None:\n        # Normalize trivial unpack in var args as *args: *tuple[X, ...] -> *args: X in place.\n        if self.is_var_arg:\n            star_index = self.arg_kinds.index(ARG_STAR)\n            star_type = self.arg_types[star_index]\n            if isinstance(star_type, UnpackType):\n                p_type = get_proper_type(star_type.type)\n                if isinstance(p_type, Instance):\n                    assert p_type.type.fullname == \"builtins.tuple\"\n                    self.arg_types[star_index] = p_type.args[0]\n\n    def with_unpacked_kwargs(self) -> NormalizedCallableType:\n        if not self.unpack_kwargs:\n            return cast(NormalizedCallableType, self)\n        last_type = get_proper_type(self.arg_types[-1])\n        assert isinstance(last_type, TypedDictType)\n        extra_kinds = [\n            ArgKind.ARG_NAMED if name in last_type.required_keys else ArgKind.ARG_NAMED_OPT\n            for name in last_type.items\n        ]\n        new_arg_kinds = self.arg_kinds[:-1] + extra_kinds\n        new_arg_names = self.arg_names[:-1] + list(last_type.items)\n        new_arg_types = self.arg_types[:-1] + list(last_type.items.values())\n        return NormalizedCallableType(\n            self.copy_modified(\n                arg_kinds=new_arg_kinds,\n                arg_names=new_arg_names,\n                arg_types=new_arg_types,\n                unpack_kwargs=False,\n            )\n        )\n\n    def with_normalized_var_args(self) -> Self:\n        var_arg = self.var_arg()\n        if not var_arg or not isinstance(var_arg.typ, UnpackType):\n            return self\n        unpacked = get_proper_type(var_arg.typ.type)\n        if not isinstance(unpacked, TupleType):\n            # Note that we don't normalize *args: *tuple[X, ...] -> *args: X,\n            # this should be done once in semanal_typeargs.py for user-defined types,\n            # and we ourselves rarely construct such type.\n            return self\n        unpack_index = find_unpack_in_list(unpacked.items)\n        if unpack_index == 0 and len(unpacked.items) > 1:\n            # Already normalized.\n            return self\n\n        # Boilerplate:\n        var_arg_index = self.arg_kinds.index(ARG_STAR)\n        types_prefix = self.arg_types[:var_arg_index]\n        kinds_prefix = self.arg_kinds[:var_arg_index]\n        names_prefix = self.arg_names[:var_arg_index]\n        types_suffix = self.arg_types[var_arg_index + 1 :]\n        kinds_suffix = self.arg_kinds[var_arg_index + 1 :]\n        names_suffix = self.arg_names[var_arg_index + 1 :]\n        no_name: str | None = None  # to silence mypy\n\n        # Now we have something non-trivial to do.\n        if unpack_index is None:\n            # Plain *Tuple[X, Y, Z] -> replace with ARG_POS completely\n            types_middle = unpacked.items\n            kinds_middle = [ARG_POS] * len(unpacked.items)\n            names_middle = [no_name] * len(unpacked.items)\n        else:\n            # *Tuple[X, *Ts, Y, Z] or *Tuple[X, *tuple[T, ...], X, Z], here\n            # we replace the prefix by ARG_POS (this is how some places expect\n            # Callables to be represented)\n            nested_unpack = unpacked.items[unpack_index]\n            assert isinstance(nested_unpack, UnpackType)\n            nested_unpacked = get_proper_type(nested_unpack.type)\n            if unpack_index == len(unpacked.items) - 1:\n                # Normalize also single item tuples like\n                #   *args: *Tuple[*tuple[X, ...]] -> *args: X\n                #   *args: *Tuple[*Ts] -> *args: *Ts\n                # This may be not strictly necessary, but these are very verbose.\n                if isinstance(nested_unpacked, Instance):\n                    assert nested_unpacked.type.fullname == \"builtins.tuple\"\n                    new_unpack = nested_unpacked.args[0]\n                else:\n                    if not isinstance(nested_unpacked, TypeVarTupleType):\n                        # We found a non-normalized tuple type, this means this method\n                        # is called during semantic analysis (e.g. from get_proper_type())\n                        # there is no point in normalizing callables at this stage.\n                        return self\n                    new_unpack = nested_unpack\n            else:\n                new_unpack = UnpackType(\n                    unpacked.copy_modified(items=unpacked.items[unpack_index:])\n                )\n            types_middle = unpacked.items[:unpack_index] + [new_unpack]\n            kinds_middle = [ARG_POS] * unpack_index + [ARG_STAR]\n            names_middle = [no_name] * unpack_index + [self.arg_names[var_arg_index]]\n        return self.copy_modified(\n            arg_types=types_prefix + types_middle + types_suffix,\n            arg_kinds=kinds_prefix + kinds_middle + kinds_suffix,\n            arg_names=names_prefix + names_middle + names_suffix,\n        )\n\n    def __hash__(self) -> int:\n        return hash(\n            (\n                self.ret_type,\n                self.is_ellipsis_args,\n                self.name,\n                tuple(self.arg_types),\n                tuple(self.arg_names),\n                tuple(self.arg_kinds),\n                self.fallback,\n            )\n        )\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, CallableType):\n            return (\n                self.ret_type == other.ret_type\n                and self.arg_types == other.arg_types\n                and self.arg_names == other.arg_names\n                and self.arg_kinds == other.arg_kinds\n                and self.name == other.name\n                and self.is_ellipsis_args == other.is_ellipsis_args\n                and self.type_guard == other.type_guard\n                and self.type_is == other.type_is\n                and self.fallback == other.fallback\n            )\n        else:\n            return NotImplemented\n\n    def serialize(self) -> JsonDict:\n        # TODO: As an optimization, leave out everything related to\n        # generic functions for non-generic functions.\n        return {\n            \".class\": \"CallableType\",\n            \"arg_types\": [t.serialize() for t in self.arg_types],\n            \"arg_kinds\": [int(x.value) for x in self.arg_kinds],\n            \"arg_names\": self.arg_names,\n            \"ret_type\": self.ret_type.serialize(),\n            \"fallback\": self.fallback.serialize(),\n            \"name\": self.name,\n            # We don't serialize the definition (only used for error messages).\n            \"variables\": [v.serialize() for v in self.variables],\n            \"is_ellipsis_args\": self.is_ellipsis_args,\n            \"implicit\": self.implicit,\n            \"is_bound\": self.is_bound,\n            \"type_guard\": self.type_guard.serialize() if self.type_guard is not None else None,\n            \"type_is\": (self.type_is.serialize() if self.type_is is not None else None),\n            \"from_concatenate\": self.from_concatenate,\n            \"imprecise_arg_kinds\": self.imprecise_arg_kinds,\n            \"unpack_kwargs\": self.unpack_kwargs,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> CallableType:\n        assert data[\".class\"] == \"CallableType\"\n        # The .definition link is set in fixup.py.\n        return CallableType(\n            [deserialize_type(t) for t in data[\"arg_types\"]],\n            [ARG_KINDS[x] for x in data[\"arg_kinds\"]],\n            data[\"arg_names\"],\n            deserialize_type(data[\"ret_type\"]),\n            Instance.deserialize(data[\"fallback\"]),\n            name=data[\"name\"],\n            variables=[cast(TypeVarLikeType, deserialize_type(v)) for v in data[\"variables\"]],\n            is_ellipsis_args=data[\"is_ellipsis_args\"],\n            implicit=data[\"implicit\"],\n            is_bound=data[\"is_bound\"],\n            type_guard=(\n                deserialize_type(data[\"type_guard\"]) if data[\"type_guard\"] is not None else None\n            ),\n            type_is=(deserialize_type(data[\"type_is\"]) if data[\"type_is\"] is not None else None),\n            from_concatenate=data[\"from_concatenate\"],\n            imprecise_arg_kinds=data[\"imprecise_arg_kinds\"],\n            unpack_kwargs=data[\"unpack_kwargs\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, CALLABLE_TYPE)\n        self.fallback.write(data)\n        write_type_list(data, self.arg_types)\n        write_int_list(data, [int(x.value) for x in self.arg_kinds])\n        write_str_opt_list(data, self.arg_names)\n        self.ret_type.write(data)\n        write_str_opt(data, self.name)\n        write_type_list(data, self.variables)\n        write_bool(data, self.is_ellipsis_args)\n        write_bool(data, self.implicit)\n        write_bool(data, self.is_bound)\n        write_type_opt(data, self.type_guard)\n        write_type_opt(data, self.type_is)\n        write_bool(data, self.from_concatenate)\n        write_bool(data, self.imprecise_arg_kinds)\n        write_bool(data, self.unpack_kwargs)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> CallableType:\n        assert read_tag(data) == INSTANCE\n        fallback = Instance.read(data)\n        ret = CallableType(\n            read_type_list(data),\n            [ARG_KINDS[ak] for ak in read_int_list(data)],\n            read_str_opt_list(data),\n            read_type(data),\n            fallback,\n            name=read_str_opt(data),\n            variables=read_type_var_likes(data),\n            is_ellipsis_args=read_bool(data),\n            implicit=read_bool(data),\n            is_bound=read_bool(data),\n            type_guard=read_type_opt(data),\n            type_is=read_type_opt(data),\n            from_concatenate=read_bool(data),\n            imprecise_arg_kinds=read_bool(data),\n            unpack_kwargs=read_bool(data),\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n\n# This is a little safety net to prevent reckless special-casing of callables\n# that can potentially break Unpack[...] with **kwargs.\n# TODO: use this in more places in checkexpr.py etc?\nNormalizedCallableType = NewType(\"NormalizedCallableType\", CallableType)\n\n\nclass Overloaded(FunctionLike):\n    \"\"\"Overloaded function type T1, ... Tn, where each Ti is CallableType.\n\n    The variant to call is chosen based on static argument\n    types. Overloaded function types can only be defined in stub\n    files, and thus there is no explicit runtime dispatch\n    implementation.\n    \"\"\"\n\n    __slots__ = (\"_items\",)\n\n    _items: list[CallableType]  # Must not be empty\n\n    def __init__(self, items: list[CallableType]) -> None:\n        super().__init__(items[0].line, items[0].column)\n        self._items = items\n        self.fallback = items[0].fallback\n\n    @property\n    def items(self) -> list[CallableType]:\n        return self._items\n\n    def name(self) -> str | None:\n        return self.get_name()\n\n    def is_type_obj(self) -> bool:\n        # All the items must have the same type object status, so it's\n        # sufficient to query only (any) one of them.\n        return self._items[0].is_type_obj()\n\n    def type_object(self) -> mypy.nodes.TypeInfo:\n        # All the items must have the same type object, so it's sufficient to\n        # query only (any) one of them.\n        return self._items[0].type_object()\n\n    def with_name(self, name: str) -> Overloaded:\n        ni: list[CallableType] = []\n        for it in self._items:\n            ni.append(it.with_name(name))\n        return Overloaded(ni)\n\n    def get_name(self) -> str | None:\n        return self._items[0].name\n\n    def with_unpacked_kwargs(self) -> Overloaded:\n        if any(i.unpack_kwargs for i in self.items):\n            return Overloaded([i.with_unpacked_kwargs() for i in self.items])\n        return self\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_overloaded(self)\n\n    def __hash__(self) -> int:\n        return hash(tuple(self.items))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Overloaded):\n            return NotImplemented\n        return self.items == other.items\n\n    def serialize(self) -> JsonDict:\n        return {\".class\": \"Overloaded\", \"items\": [t.serialize() for t in self.items]}\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> Overloaded:\n        assert data[\".class\"] == \"Overloaded\"\n        return Overloaded([CallableType.deserialize(t) for t in data[\"items\"]])\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, OVERLOADED)\n        write_type_list(data, self.items)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> Overloaded:\n        items = []\n        assert read_tag(data) == LIST_GEN\n        for _ in range(read_int_bare(data)):\n            assert read_tag(data) == CALLABLE_TYPE\n            items.append(CallableType.read(data))\n        assert read_tag(data) == END_TAG\n        return Overloaded(items)\n\n\nclass TupleType(ProperType):\n    \"\"\"The tuple type Tuple[T1, ..., Tn] (at least one type argument).\n\n    Instance variables:\n        items: Tuple item types\n        partial_fallback: The (imprecise) underlying instance type that is used\n            for non-tuple methods. This is generally builtins.tuple[Any, ...] for\n            regular tuples, but it's different for named tuples and classes with\n            a tuple base class. Use mypy.typeops.tuple_fallback to calculate the\n            precise fallback type derived from item types.\n        implicit: If True, derived from a tuple expression (t,....) instead of Tuple[t, ...]\n    \"\"\"\n\n    __slots__ = (\"items\", \"partial_fallback\", \"implicit\")\n\n    items: list[Type]\n    partial_fallback: Instance\n    implicit: bool\n\n    def __init__(\n        self,\n        items: list[Type],\n        fallback: Instance,\n        line: int = -1,\n        column: int = -1,\n        implicit: bool = False,\n    ) -> None:\n        super().__init__(line, column)\n        self.partial_fallback = fallback\n        self.items = items\n        self.implicit = implicit\n\n    def can_be_true_default(self) -> bool:\n        if self.can_be_any_bool():\n            # Corner case: it is a `NamedTuple` with `__bool__` method defined.\n            # It can be anything: both `True` and `False`.\n            return True\n        return self.length() > 0\n\n    def can_be_false_default(self) -> bool:\n        if self.can_be_any_bool():\n            # Corner case: it is a `NamedTuple` with `__bool__` method defined.\n            # It can be anything: both `True` and `False`.\n            return True\n        if self.length() == 0:\n            return True\n        if self.length() > 1:\n            return False\n        # Special case tuple[*Ts] may or may not be false.\n        item = self.items[0]\n        if not isinstance(item, UnpackType):\n            return False\n        if not isinstance(item.type, TypeVarTupleType):\n            # Non-normalized tuple[int, ...] can be false.\n            return True\n        return item.type.min_len == 0\n\n    def can_be_any_bool(self) -> bool:\n        return bool(\n            self.partial_fallback.type\n            and self.partial_fallback.type.fullname != \"builtins.tuple\"\n            and self.partial_fallback.type.names.get(\"__bool__\")\n        )\n\n    def length(self) -> int:\n        return len(self.items)\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_tuple_type(self)\n\n    def __hash__(self) -> int:\n        return hash((tuple(self.items), self.partial_fallback))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, TupleType):\n            return NotImplemented\n        return self.items == other.items and self.partial_fallback == other.partial_fallback\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"TupleType\",\n            \"items\": [t.serialize() for t in self.items],\n            \"partial_fallback\": self.partial_fallback.serialize(),\n            \"implicit\": self.implicit,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TupleType:\n        assert data[\".class\"] == \"TupleType\"\n        return TupleType(\n            [deserialize_type(t) for t in data[\"items\"]],\n            Instance.deserialize(data[\"partial_fallback\"]),\n            implicit=data[\"implicit\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, TUPLE_TYPE)\n        self.partial_fallback.write(data)\n        write_type_list(data, self.items)\n        write_bool(data, self.implicit)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> TupleType:\n        assert read_tag(data) == INSTANCE\n        fallback = Instance.read(data)\n        ret = TupleType(read_type_list(data), fallback, implicit=read_bool(data))\n        assert read_tag(data) == END_TAG\n        return ret\n\n    def copy_modified(\n        self, *, fallback: Instance | None = None, items: list[Type] | None = None\n    ) -> TupleType:\n        if fallback is None:\n            fallback = self.partial_fallback\n        if items is None:\n            items = self.items\n        return TupleType(items, fallback, self.line, self.column)\n\n    def slice(\n        self, begin: int | None, end: int | None, stride: int | None, *, fallback: Instance | None\n    ) -> TupleType | None:\n        if fallback is None:\n            fallback = self.partial_fallback\n\n        if stride == 0:\n            return None\n\n        if any(isinstance(t, UnpackType) for t in self.items):\n            total = len(self.items)\n            unpack_index = find_unpack_in_list(self.items)\n            assert unpack_index is not None\n            if begin is None and end is None:\n                # We special-case this to support reversing variadic tuples.\n                # General support for slicing is tricky, so we handle only simple cases.\n                if stride == -1:\n                    slice_items = self.items[::-1]\n                elif stride is None or stride == 1:\n                    slice_items = self.items\n                else:\n                    return None\n            elif (begin is None or unpack_index >= begin >= 0) and (\n                end is not None and unpack_index >= end >= 0\n            ):\n                # Start and end are in the prefix, everything works in this case.\n                slice_items = self.items[begin:end:stride]\n            elif (begin is not None and unpack_index - total < begin < 0) and (\n                end is None or unpack_index - total < end < 0\n            ):\n                # Start and end are in the suffix, everything works in this case.\n                slice_items = self.items[begin:end:stride]\n            elif (begin is None or unpack_index >= begin >= 0) and (\n                end is None or unpack_index - total < end < 0\n            ):\n                # Start in the prefix, end in the suffix, we can support only trivial strides.\n                if stride is None or stride == 1:\n                    slice_items = self.items[begin:end:stride]\n                else:\n                    return None\n            elif (begin is not None and unpack_index - total < begin < 0) and (\n                end is not None and unpack_index >= end >= 0\n            ):\n                # Start in the suffix, end in the prefix, we can support only trivial strides.\n                if stride is None or stride == -1:\n                    slice_items = self.items[begin:end:stride]\n                else:\n                    return None\n            else:\n                # TODO: there some additional cases we can support for homogeneous variadic\n                # items, we can \"eat away\" finite number of items.\n                return None\n        else:\n            slice_items = self.items[begin:end:stride]\n        return TupleType(slice_items, fallback, self.line, self.column, self.implicit)\n\n\nclass TypedDictType(ProperType):\n    \"\"\"Type of TypedDict object {'k1': v1, ..., 'kn': vn}.\n\n    A TypedDict object is a dictionary with specific string (literal) keys. Each\n    key has a value with a distinct type that depends on the key. TypedDict objects\n    are normal dict objects at runtime.\n\n    A TypedDictType can be either named or anonymous. If it's anonymous, its\n    fallback will be typing_extensions._TypedDict (Instance). _TypedDict is a subclass\n    of Mapping[str, object] and defines all non-mapping dict methods that TypedDict\n    supports. Some dict methods are unsafe and not supported. _TypedDict isn't defined\n    at runtime.\n\n    If a TypedDict is named, its fallback will be an Instance of the named type\n    (ex: \"Point\") whose TypeInfo has a typeddict_type that is anonymous. This\n    is similar to how named tuples work.\n\n    TODO: The fallback structure is perhaps overly complicated.\n    \"\"\"\n\n    __slots__ = (\n        \"items\",\n        \"required_keys\",\n        \"readonly_keys\",\n        \"fallback\",\n        \"extra_items_from\",\n        \"to_be_mutated\",\n    )\n\n    items: dict[str, Type]  # item_name -> item_type\n    required_keys: set[str]\n    readonly_keys: set[str]\n    fallback: Instance\n\n    extra_items_from: list[ProperType]  # only used during semantic analysis\n    to_be_mutated: bool  # only used in a plugin for `.update`, `|=`, etc\n\n    def __init__(\n        self,\n        items: dict[str, Type],\n        required_keys: set[str],\n        readonly_keys: set[str],\n        fallback: Instance,\n        line: int = -1,\n        column: int = -1,\n    ) -> None:\n        super().__init__(line, column)\n        self.items = items\n        self.required_keys = required_keys\n        self.readonly_keys = readonly_keys\n        self.fallback = fallback\n        self.can_be_true = len(self.items) > 0\n        self.can_be_false = len(self.required_keys) == 0\n        self.extra_items_from = []\n        self.to_be_mutated = False\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_typeddict_type(self)\n\n    def __hash__(self) -> int:\n        return hash(\n            (\n                frozenset(self.items.items()),\n                self.fallback,\n                frozenset(self.required_keys),\n                frozenset(self.readonly_keys),\n            )\n        )\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, TypedDictType):\n            return NotImplemented\n        if self is other:\n            return True\n        return (\n            frozenset(self.items.keys()) == frozenset(other.items.keys())\n            and all(\n                left_item_type == right_item_type\n                for (_, left_item_type, right_item_type) in self.zip(other)\n            )\n            and self.fallback == other.fallback\n            and self.required_keys == other.required_keys\n            and self.readonly_keys == other.readonly_keys\n        )\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"TypedDictType\",\n            \"items\": [[n, t.serialize()] for (n, t) in self.items.items()],\n            \"required_keys\": sorted(self.required_keys),\n            \"readonly_keys\": sorted(self.readonly_keys),\n            \"fallback\": self.fallback.serialize(),\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> TypedDictType:\n        assert data[\".class\"] == \"TypedDictType\"\n        return TypedDictType(\n            {n: deserialize_type(t) for (n, t) in data[\"items\"]},\n            set(data[\"required_keys\"]),\n            set(data[\"readonly_keys\"]),\n            Instance.deserialize(data[\"fallback\"]),\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, TYPED_DICT_TYPE)\n        self.fallback.write(data)\n        write_type_map(data, self.items)\n        write_str_list(data, sorted(self.required_keys))\n        write_str_list(data, sorted(self.readonly_keys))\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> TypedDictType:\n        assert read_tag(data) == INSTANCE\n        fallback = Instance.read(data)\n        ret = TypedDictType(\n            read_type_map(data), set(read_str_list(data)), set(read_str_list(data)), fallback\n        )\n        assert read_tag(data) == END_TAG\n        return ret\n\n    @property\n    def is_final(self) -> bool:\n        return self.fallback.type.is_final\n\n    def is_anonymous(self) -> bool:\n        return self.fallback.type.fullname in TPDICT_FB_NAMES\n\n    def create_anonymous_fallback(self) -> Instance:\n        if self.is_anonymous():\n            return self.fallback\n        assert self.fallback.type.typeddict_type is not None\n        return self.fallback.type.typeddict_type.create_anonymous_fallback()\n\n    def copy_modified(\n        self,\n        *,\n        fallback: Instance | None = None,\n        item_types: list[Type] | None = None,\n        item_names: list[str] | None = None,\n        required_keys: set[str] | None = None,\n        readonly_keys: set[str] | None = None,\n    ) -> TypedDictType:\n        if fallback is None:\n            fallback = self.fallback\n        if item_types is None:\n            items = self.items\n        else:\n            items = dict(zip(self.items, item_types))\n        if required_keys is None:\n            required_keys = self.required_keys\n        if readonly_keys is None:\n            readonly_keys = self.readonly_keys\n        if item_names is not None:\n            items = {k: v for (k, v) in items.items() if k in item_names}\n            required_keys &= set(item_names)\n        return TypedDictType(items, required_keys, readonly_keys, fallback, self.line, self.column)\n\n    def names_are_wider_than(self, other: TypedDictType) -> bool:\n        return len(other.items.keys() - self.items.keys()) == 0\n\n    def zip(self, right: TypedDictType) -> Iterable[tuple[str, Type, Type]]:\n        left = self\n        for item_name, left_item_type in left.items.items():\n            right_item_type = right.items.get(item_name)\n            if right_item_type is not None:\n                yield (item_name, left_item_type, right_item_type)\n\n    def zipall(self, right: TypedDictType) -> Iterable[tuple[str, Type | None, Type | None]]:\n        left = self\n        for item_name, left_item_type in left.items.items():\n            right_item_type = right.items.get(item_name)\n            yield (item_name, left_item_type, right_item_type)\n        for item_name, right_item_type in right.items.items():\n            if item_name in left.items:\n                continue\n            yield (item_name, None, right_item_type)\n\n\nclass RawExpressionType(ProperType):\n    \"\"\"A synthetic type representing some arbitrary expression that does not cleanly\n    translate into a type.\n\n    This synthetic type is only used at the beginning stages of semantic analysis\n    and should be completely removing during the process for mapping UnboundTypes to\n    actual types: we either turn it into a LiteralType or an AnyType.\n\n    For example, suppose `Foo[1]` is initially represented as the following:\n\n        UnboundType(\n            name='Foo',\n            args=[\n                RawExpressionType(value=1, base_type_name='builtins.int'),\n            ],\n        )\n\n    As we perform semantic analysis, this type will transform into one of two\n    possible forms.\n\n    If 'Foo' was an alias for 'Literal' all along, this type is transformed into:\n\n        LiteralType(value=1, fallback=int_instance_here)\n\n    Alternatively, if 'Foo' is an unrelated class, we report an error and instead\n    produce something like this:\n\n        Instance(type=typeinfo_for_foo, args=[AnyType(TypeOfAny.from_error))\n\n    If the \"note\" field is not None, the provided note will be reported alongside the\n    error at this point.\n\n    Note: if \"literal_value\" is None, that means this object is representing some\n    expression that cannot possibly be a parameter of Literal[...]. For example,\n    \"Foo[3j]\" would be represented as:\n\n        UnboundType(\n            name='Foo',\n            args=[\n                RawExpressionType(value=None, base_type_name='builtins.complex'),\n            ],\n        )\n    \"\"\"\n\n    __slots__ = (\"literal_value\", \"base_type_name\", \"note\")\n\n    def __init__(\n        self,\n        literal_value: LiteralValue | None,\n        base_type_name: str,\n        line: int = -1,\n        column: int = -1,\n        note: str | None = None,\n    ) -> None:\n        super().__init__(line, column)\n        self.literal_value = literal_value\n        self.base_type_name = base_type_name\n        self.note = note\n\n    def simple_name(self) -> str:\n        return self.base_type_name.replace(\"builtins.\", \"\")\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        assert isinstance(visitor, SyntheticTypeVisitor)\n        ret: T = visitor.visit_raw_expression_type(self)\n        return ret\n\n    def serialize(self) -> JsonDict:\n        assert False, \"Synthetic types don't serialize\"\n\n    def __hash__(self) -> int:\n        return hash((self.literal_value, self.base_type_name))\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, RawExpressionType):\n            return (\n                self.base_type_name == other.base_type_name\n                and self.literal_value == other.literal_value\n            )\n        else:\n            return NotImplemented\n\n\nclass LiteralType(ProperType):\n    \"\"\"The type of a Literal instance. Literal[Value]\n\n    A Literal always consists of:\n\n    1. A native Python object corresponding to the contained inner value\n    2. A fallback for this Literal. The fallback also corresponds to the\n       parent type this Literal subtypes.\n\n    For example, 'Literal[42]' is represented as\n    'LiteralType(value=42, fallback=instance_of_int)'\n\n    As another example, `Literal[Color.RED]` (where Color is an enum) is\n    represented as `LiteralType(value=\"RED\", fallback=instance_of_color)'.\n    \"\"\"\n\n    __slots__ = (\"value\", \"fallback\", \"_hash\")\n\n    def __init__(\n        self, value: LiteralValue, fallback: Instance, line: int = -1, column: int = -1\n    ) -> None:\n        super().__init__(line, column)\n        self.value = value\n        self.fallback = fallback\n\n    # NOTE: Enum types are always truthy by default, but this can be changed\n    #       in subclasses, so we need to get the truthyness from the Enum\n    #       type rather than base it on the value (which is a non-empty\n    #       string for enums, so always truthy)\n    # TODO: We should consider moving this branch to the `can_be_true`\n    #       `can_be_false` properties instead, so the truthyness only\n    #       needs to be determined once per set of Enum literals.\n    #       However, the same can be said for `TypeAliasType` in some\n    #       cases and we only set the default based on the type it is\n    #       aliasing. So if we decide to change this, we may want to\n    #       change that as well. perf_compare output was inconclusive\n    #       but slightly favored this version, probably because we have\n    #       almost no test cases where we would redundantly compute\n    #       `can_be_false`/`can_be_true`.\n    def can_be_false_default(self) -> bool:\n        if self.fallback.type.is_enum:\n            return self.fallback.can_be_false\n        return not self.value\n\n    def can_be_true_default(self) -> bool:\n        if self.fallback.type.is_enum:\n            return self.fallback.can_be_true\n        return bool(self.value)\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_literal_type(self)\n\n    def __hash__(self) -> int:\n        # Intentionally a subset of __eq__ for perf\n        return hash(self.value)\n\n    def __eq__(self, other: object) -> bool:\n        if isinstance(other, LiteralType):\n            return self.value == other.value and self.fallback == other.fallback\n        else:\n            return NotImplemented\n\n    def is_enum_literal(self) -> bool:\n        return self.fallback.type.is_enum\n\n    def value_repr(self) -> str:\n        \"\"\"Returns the string representation of the underlying type.\n\n        This function is almost equivalent to running `repr(self.value)`,\n        except it includes some additional logic to correctly handle cases\n        where the value is a string, byte string, a unicode string, or an enum.\n        \"\"\"\n        raw = repr(self.value)\n        fallback_name = self.fallback.type.fullname\n\n        # If this is backed by an enum,\n        if self.is_enum_literal():\n            return f\"{fallback_name}.{self.value}\"\n\n        if fallback_name == \"builtins.bytes\":\n            # Note: 'builtins.bytes' only appears in Python 3, so we want to\n            # explicitly prefix with a \"b\"\n            return \"b\" + raw\n        else:\n            # 'builtins.str' could mean either depending on context, but either way\n            # we don't prefix: it's the \"native\" string. And of course, if value is\n            # some other type, we just return that string repr directly.\n            return raw\n\n    def serialize(self) -> JsonDict | str:\n        return {\n            \".class\": \"LiteralType\",\n            \"value\": self.value,\n            \"fallback\": self.fallback.serialize(),\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> LiteralType:\n        assert data[\".class\"] == \"LiteralType\"\n        return LiteralType(value=data[\"value\"], fallback=Instance.deserialize(data[\"fallback\"]))\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, LITERAL_TYPE)\n        self.fallback.write(data)\n        write_literal(data, self.value)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> LiteralType:\n        assert read_tag(data) == INSTANCE\n        fallback = Instance.read(data)\n        tag = read_tag(data)\n        ret = LiteralType(read_literal(data, tag), fallback)\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass UnionType(ProperType):\n    \"\"\"The union type Union[T1, ..., Tn] (at least one type argument).\"\"\"\n\n    __slots__ = (\n        \"items\",\n        \"is_evaluated\",\n        \"uses_pep604_syntax\",\n        \"original_str_expr\",\n        \"original_str_fallback\",\n    )\n\n    def __init__(\n        self,\n        items: Sequence[Type],\n        line: int = -1,\n        column: int = -1,\n        *,\n        is_evaluated: bool = True,\n        uses_pep604_syntax: bool = False,\n    ) -> None:\n        super().__init__(line, column)\n        # We must keep this false to avoid crashes during semantic analysis.\n        # TODO: maybe switch this to True during type-checking pass?\n        self.items = flatten_nested_unions(items, handle_type_alias_type=False)\n        # is_evaluated should be set to false for type comments and string literals\n        self.is_evaluated = is_evaluated\n        # uses_pep604_syntax is True if Union uses OR syntax (X | Y)\n        self.uses_pep604_syntax = uses_pep604_syntax\n        # The meaning of these two is the same as for UnboundType. A UnionType can be\n        # return by type parser from a string \"A|B\", and we need to be able to fall back\n        # to plain string, when such a string appears inside a Literal[...].\n        self.original_str_expr: str | None = None\n        self.original_str_fallback: str | None = None\n\n    def can_be_true_default(self) -> bool:\n        return any(item.can_be_true for item in self.items)\n\n    def can_be_false_default(self) -> bool:\n        return any(item.can_be_false for item in self.items)\n\n    def __hash__(self) -> int:\n        return hash(frozenset(self.items))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, UnionType):\n            return NotImplemented\n        if self is other:\n            return True\n        return frozenset(self.items) == frozenset(other.items)\n\n    @overload\n    @staticmethod\n    def make_union(\n        items: Sequence[ProperType], line: int = -1, column: int = -1\n    ) -> ProperType: ...\n\n    @overload\n    @staticmethod\n    def make_union(items: Sequence[Type], line: int = -1, column: int = -1) -> Type: ...\n\n    @staticmethod\n    def make_union(items: Sequence[Type], line: int = -1, column: int = -1) -> Type:\n        if len(items) > 1:\n            return UnionType(items, line, column)\n        elif len(items) == 1:\n            return items[0]\n        else:\n            return UninhabitedType()\n\n    def length(self) -> int:\n        return len(self.items)\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_union_type(self)\n\n    def relevant_items(self) -> list[Type]:\n        \"\"\"Removes NoneTypes from Unions when strict Optional checking is off.\"\"\"\n        if state.strict_optional:\n            return self.items\n        else:\n            return [i for i in self.items if not isinstance(get_proper_type(i), NoneType)]\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"UnionType\",\n            \"items\": [t.serialize() for t in self.items],\n            \"uses_pep604_syntax\": self.uses_pep604_syntax,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> UnionType:\n        assert data[\".class\"] == \"UnionType\"\n        return UnionType(\n            [deserialize_type(t) for t in data[\"items\"]],\n            uses_pep604_syntax=data[\"uses_pep604_syntax\"],\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, UNION_TYPE)\n        write_type_list(data, self.items)\n        write_bool(data, self.uses_pep604_syntax)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> UnionType:\n        ret = UnionType(read_type_list(data), uses_pep604_syntax=read_bool(data))\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass PartialType(ProperType):\n    \"\"\"Type such as List[?] where type arguments are unknown, or partial None type.\n\n    These are used for inferring types in multiphase initialization such as this:\n\n      x = []       # x gets a partial type List[?], as item type is unknown\n      x.append(1)  # partial type gets replaced with normal type List[int]\n\n    Or with None:\n\n      x = None  # x gets a partial type None\n      if c:\n          x = 1  # Infer actual type int for x\n    \"\"\"\n\n    __slots__ = (\"type\", \"var\", \"value_type\")\n\n    # None for the 'None' partial type; otherwise a generic class\n    type: mypy.nodes.TypeInfo | None\n    var: mypy.nodes.Var\n    # For partial defaultdict[K, V], the type V (K is unknown). If V is generic,\n    # the type argument is Any and will be replaced later.\n    value_type: Instance | None\n\n    def __init__(\n        self,\n        type: mypy.nodes.TypeInfo | None,\n        var: mypy.nodes.Var,\n        value_type: Instance | None = None,\n    ) -> None:\n        super().__init__()\n        self.type = type\n        self.var = var\n        self.value_type = value_type\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_partial_type(self)\n\n\nclass EllipsisType(ProperType):\n    \"\"\"The type ... (ellipsis).\n\n    This is not a real type but a syntactic AST construct, used in Callable[..., T], for example.\n\n    A semantically analyzed type will never have ellipsis types.\n    \"\"\"\n\n    __slots__ = ()\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        assert isinstance(visitor, SyntheticTypeVisitor)\n        ret: T = visitor.visit_ellipsis_type(self)\n        return ret\n\n    def serialize(self) -> JsonDict:\n        assert False, \"Synthetic types don't serialize\"\n\n\nclass TypeType(ProperType):\n    \"\"\"For types like Type[User] or TypeForm[User | None].\n\n    Type[C] annotates variables that are class objects, constrained by\n    the type argument.  See PEP 484 for more details.\n\n    TypeForm[T] annotates variables that hold the result of evaluating\n    a type expression.  See PEP 747 for more details.\n\n    We may encounter expressions whose values are specific classes;\n    those are represented as callables (possibly overloaded)\n    corresponding to the class's constructor's signature and returning\n    an instance of that class.  The difference with Type[C] is that\n    those callables always represent the exact class given as the\n    return type; Type[C] represents any class that's a subclass of C,\n    and C may also be a type variable or a union (or Any).\n\n    Many questions around subtype relationships between Type[C1] and\n    def(...) -> C2 are answered by looking at the subtype\n    relationships between C1 and C2, since Type[] is considered\n    covariant.\n\n    There's an unsolved problem with constructor signatures (also\n    unsolved in PEP 484): calling a variable whose type is Type[C]\n    assumes the constructor signature for C, even though a subclass of\n    C might completely change the constructor signature.  For now we\n    just assume that users of Type[C] are careful not to do that (in\n    the future we might detect when they are violating that\n    assumption).\n    \"\"\"\n\n    __slots__ = (\"item\", \"is_type_form\")\n\n    # This can't be everything, but it can be a class reference,\n    # a generic class instance, a union, Any, a type variable...\n    item: ProperType\n\n    # If True then this TypeType represents a TypeForm[T].\n    # If False then this TypeType represents a Type[C].\n    is_type_form: bool\n\n    def __init__(\n        self,\n        item: Bogus[Instance | AnyType | TypeVarType | TupleType | NoneType | CallableType],\n        *,\n        line: int = -1,\n        column: int = -1,\n        is_type_form: bool = False,\n    ) -> None:\n        \"\"\"To ensure Type[Union[A, B]] is always represented as Union[Type[A], Type[B]], item of\n        type UnionType must be handled through make_normalized static method.\n        \"\"\"\n        super().__init__(line, column)\n        self.item = item\n        self.is_type_form = is_type_form\n\n    @staticmethod\n    def make_normalized(\n        item: Type, *, line: int = -1, column: int = -1, is_type_form: bool = False\n    ) -> ProperType:\n        item = get_proper_type(item)\n        if is_type_form:\n            # Don't convert TypeForm[X | Y] to (TypeForm[X] | TypeForm[Y])\n            pass\n        else:\n            if isinstance(item, UnionType):\n                return UnionType.make_union(\n                    [TypeType.make_normalized(union_item) for union_item in item.items],\n                    line=line,\n                    column=column,\n                )\n        return TypeType(item, line=line, column=column, is_type_form=is_type_form)  # type: ignore[arg-type]\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        return visitor.visit_type_type(self)\n\n    def __hash__(self) -> int:\n        return hash(self.item)\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, TypeType):\n            return NotImplemented\n        return self.item == other.item and self.is_type_form == other.is_type_form\n\n    def serialize(self) -> JsonDict:\n        return {\n            \".class\": \"TypeType\",\n            \"item\": self.item.serialize(),\n            \"is_type_form\": self.is_type_form,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict) -> Type:\n        assert data[\".class\"] == \"TypeType\"\n        return TypeType.make_normalized(\n            deserialize_type(data[\"item\"]), is_type_form=data[\"is_type_form\"]\n        )\n\n    def write(self, data: WriteBuffer) -> None:\n        write_tag(data, TYPE_TYPE)\n        self.item.write(data)\n        write_tag(data, END_TAG)\n\n    @classmethod\n    def read(cls, data: ReadBuffer) -> Type:\n        ret = TypeType.make_normalized(read_type(data))\n        assert read_tag(data) == END_TAG\n        return ret\n\n\nclass PlaceholderType(ProperType):\n    \"\"\"Temporary, yet-unknown type during semantic analysis.\n\n    This is needed when there's a reference to a type before the real symbol\n    table entry of the target type is available (specifically, we use a\n    temporary PlaceholderNode symbol node). Consider this example:\n\n      class str(Sequence[str]): ...\n\n    We use a PlaceholderType for the 'str' in 'Sequence[str]' since we can't create\n    a TypeInfo for 'str' until all base classes have been resolved. We'll soon\n    perform another analysis iteration which replaces the base class with a complete\n    type without any placeholders. After semantic analysis, no placeholder types must\n    exist.\n    \"\"\"\n\n    __slots__ = (\"fullname\", \"args\")\n\n    def __init__(self, fullname: str | None, args: list[Type], line: int) -> None:\n        super().__init__(line)\n        self.fullname = fullname  # Must be a valid full name of an actual node (or None).\n        self.args = args\n\n    def accept(self, visitor: TypeVisitor[T]) -> T:\n        assert isinstance(visitor, SyntheticTypeVisitor)\n        ret: T = visitor.visit_placeholder_type(self)\n        return ret\n\n    def __hash__(self) -> int:\n        return hash((self.fullname, tuple(self.args)))\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, PlaceholderType):\n            return NotImplemented\n        return self.fullname == other.fullname and self.args == other.args\n\n    def serialize(self) -> str:\n        # We should never get here since all placeholders should be replaced\n        # during semantic analysis.\n        assert False, f\"Internal error: unresolved placeholder type {self.fullname}\"\n\n\n@overload\ndef get_proper_type(typ: None) -> None: ...\n\n\n@overload\ndef get_proper_type(typ: Type) -> ProperType: ...\n\n\ndef get_proper_type(typ: Type | None) -> ProperType | None:\n    \"\"\"Get the expansion of a type alias type.\n\n    If the type is already a proper type, this is a no-op. Use this function\n    wherever a decision is made on a call like e.g. 'if isinstance(typ, UnionType): ...',\n    because 'typ' in this case may be an alias to union. Note: if after making the decision\n    on the isinstance() call you pass on the original type (and not one of its components)\n    it is recommended to *always* pass on the unexpanded alias.\n    \"\"\"\n    if typ is None:\n        return None\n    # TODO: this is an ugly hack, remove.\n    if isinstance(typ, TypeGuardedType):\n        typ = typ.type_guard\n    while isinstance(typ, TypeAliasType):\n        typ = typ._expand_once()\n    # TODO: store the name of original type alias on this type, so we can show it in errors.\n    return cast(ProperType, typ)\n\n\n@overload\ndef get_proper_types(types: list[Type] | tuple[Type, ...]) -> list[ProperType]: ...\n\n\n@overload\ndef get_proper_types(\n    types: list[Type | None] | tuple[Type | None, ...],\n) -> list[ProperType | None]: ...\n\n\ndef get_proper_types(\n    types: list[Type] | list[Type | None] | tuple[Type | None, ...],\n) -> list[ProperType] | list[ProperType | None]:\n    if isinstance(types, list):\n        typelist = types\n        # Optimize for the common case so that we don't need to allocate anything\n        if not any(isinstance(t, (TypeAliasType, TypeGuardedType)) for t in typelist):\n            return cast(\"list[ProperType]\", typelist)\n        return [get_proper_type(t) for t in typelist]\n    else:\n        return [get_proper_type(t) for t in types]\n\n\n# We split off the type visitor base classes to another module\n# to make it easier to gradually get modules working with mypyc.\n# Import them here, after the types are defined.\n# This is intended as a re-export also.\nfrom mypy.type_visitor import (\n    ALL_STRATEGY as ALL_STRATEGY,\n    ANY_STRATEGY as ANY_STRATEGY,\n    BoolTypeQuery as BoolTypeQuery,\n    SyntheticTypeVisitor as SyntheticTypeVisitor,\n    TypeQuery as TypeQuery,\n    TypeTranslator as TypeTranslator,\n    TypeVisitor as TypeVisitor,\n)\n\n\nclass TypeStrVisitor(SyntheticTypeVisitor[str]):\n    \"\"\"Visitor for pretty-printing types into strings.\n\n    This is mostly for debugging/testing.\n\n    Do not preserve original formatting.\n\n    Notes:\n     - Represent unbound types as Foo? or Foo?[...].\n     - Represent the NoneType type as None.\n     - Represent Union[x, y] as x | y\n    \"\"\"\n\n    def __init__(self, id_mapper: IdMapper | None = None, *, options: Options) -> None:\n        self.id_mapper = id_mapper\n        self.options = options\n        self.dotted_aliases: set[TypeAliasType] | None = None\n\n    def visit_unbound_type(self, t: UnboundType, /) -> str:\n        s = t.name + \"?\"\n        if t.args:\n            s += f\"[{self.list_str(t.args)}]\"\n        return s\n\n    def visit_type_list(self, t: TypeList, /) -> str:\n        return f\"<TypeList {self.list_str(t.items)}>\"\n\n    def visit_callable_argument(self, t: CallableArgument, /) -> str:\n        typ = t.typ.accept(self)\n        if t.name is None:\n            return f\"{t.constructor}({typ})\"\n        else:\n            return f\"{t.constructor}({typ}, {t.name})\"\n\n    def visit_any(self, t: AnyType, /) -> str:\n        return \"Any\"\n\n    def visit_none_type(self, t: NoneType, /) -> str:\n        return \"None\"\n\n    def visit_uninhabited_type(self, t: UninhabitedType, /) -> str:\n        return \"Never\"\n\n    def visit_erased_type(self, t: ErasedType, /) -> str:\n        return \"<Erased>\"\n\n    def visit_deleted_type(self, t: DeletedType, /) -> str:\n        if t.source is None:\n            return \"<Deleted>\"\n        else:\n            return f\"<Deleted '{t.source}'>\"\n\n    def visit_instance(self, t: Instance, /) -> str:\n        fullname = t.type.fullname\n        if not self.options.reveal_verbose_types and fullname.startswith(\"builtins.\"):\n            fullname = t.type.name\n        if t.last_known_value and not t.args:\n            # Instances with a literal fallback should never be generic. If they are,\n            # something went wrong so we fall back to showing the full Instance repr.\n            s = f\"{t.last_known_value.accept(self)}?\"\n\n        else:\n            s = fullname or t.type.name or \"<???>\"\n\n        if t.args:\n            if t.type.fullname == \"builtins.tuple\":\n                assert len(t.args) == 1\n                s += f\"[{self.list_str(t.args)}, ...]\"\n            else:\n                s += f\"[{self.list_str(t.args)}]\"\n        elif t.type.has_type_var_tuple_type and len(t.type.type_vars) == 1:\n            s += \"[()]\"\n        if self.id_mapper:\n            s += f\"<{self.id_mapper.id(t.type)}>\"\n        return s\n\n    def visit_type_var(self, t: TypeVarType, /) -> str:\n        if not self.options.reveal_verbose_types:\n            s = t.name\n        else:\n            s = f\"{t.name}`{t.id}\"\n        if self.id_mapper and t.upper_bound:\n            s += f\"(upper_bound={t.upper_bound.accept(self)})\"\n        if t.has_default() and self.options.reveal_verbose_types:\n            s += f\" = {t.default.accept(self)}\"\n        # TODO: disambiguate type variables with same name using namespace.\n        # We should reuse find_type_overlaps() and scoped_type_var_name().\n        return s\n\n    def visit_param_spec(self, t: ParamSpecType, /) -> str:\n        # prefixes are displayed as Concatenate\n        s = \"\"\n        if t.prefix.arg_types:\n            s += f\"[{self.list_str(t.prefix.arg_types)}, **\"\n        if not self.options.reveal_verbose_types:\n            s += t.name_with_suffix()\n        else:\n            s += f\"{t.name_with_suffix()}`{t.id}\"\n        if t.prefix.arg_types:\n            s += \"]\"\n        if t.has_default() and self.options.reveal_verbose_types:\n            s += f\" = {t.default.accept(self)}\"\n        return s\n\n    def visit_parameters(self, t: Parameters, /) -> str:\n        # This is copied from visit_callable -- is there a way to decrease duplication?\n        if t.is_ellipsis_args:\n            return \"...\"\n\n        s = \"\"\n        bare_asterisk = False\n        for i in range(len(t.arg_types)):\n            if s != \"\":\n                s += \", \"\n            if t.arg_kinds[i].is_named() and not bare_asterisk:\n                s += \"*, \"\n                bare_asterisk = True\n            if t.arg_kinds[i] == ARG_STAR:\n                s += \"*\"\n            if t.arg_kinds[i] == ARG_STAR2:\n                s += \"**\"\n            name = t.arg_names[i]\n            if name:\n                s += f\"{name}: \"\n            r = t.arg_types[i].accept(self)\n\n            s += r\n\n            if t.arg_kinds[i].is_optional():\n                s += \" =\"\n\n        return f\"[{s}]\"\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> str:\n        if not self.options.reveal_verbose_types:\n            s = t.name\n        else:\n            s = f\"{t.name}`{t.id}\"\n        if t.has_default() and self.options.reveal_verbose_types:\n            s += f\" = {t.default.accept(self)}\"\n        return s\n\n    def visit_callable_type(self, t: CallableType, /) -> str:\n        param_spec = t.param_spec()\n        if param_spec is not None:\n            num_skip = 2\n        else:\n            num_skip = 0\n\n        s = \"\"\n        asterisk = False\n        for i in range(len(t.arg_types) - num_skip):\n            if s != \"\":\n                s += \", \"\n            if t.arg_kinds[i].is_named() and not asterisk:\n                s += \"*, \"\n                asterisk = True\n            if t.arg_kinds[i] == ARG_STAR:\n                s += \"*\"\n                asterisk = True\n            if t.arg_kinds[i] == ARG_STAR2:\n                s += \"**\"\n            name = t.arg_names[i]\n            if not name and not self.options.reveal_verbose_types:\n                # Avoid ambiguous (and weird) formatting for anonymous args/kwargs.\n                if t.arg_kinds[i] == ARG_STAR and isinstance(t.arg_types[i], UnpackType):\n                    name = \"args\"\n                elif t.arg_kinds[i] == ARG_STAR2 and t.unpack_kwargs:\n                    name = \"kwargs\"\n            if name:\n                s += name + \": \"\n            type_str = t.arg_types[i].accept(self)\n            if t.arg_kinds[i] == ARG_STAR2 and t.unpack_kwargs:\n                if not self.options.reveal_verbose_types:\n                    type_str = f\"**{type_str}\"\n                else:\n                    type_str = f\"Unpack[{type_str}]\"\n            s += type_str\n            if t.arg_kinds[i].is_optional():\n                s += \" =\"\n\n        if param_spec is not None:\n            n = param_spec.name\n            if s:\n                s += \", \"\n            s += f\"*{n}.args, **{n}.kwargs\"\n            if param_spec.has_default():\n                s += f\" = {param_spec.default.accept(self)}\"\n\n        s = f\"({s})\"\n\n        if not isinstance(get_proper_type(t.ret_type), NoneType):\n            if t.type_guard is not None:\n                s += f\" -> TypeGuard[{t.type_guard.accept(self)}]\"\n            elif t.type_is is not None:\n                s += f\" -> TypeIs[{t.type_is.accept(self)}]\"\n            else:\n                s += f\" -> {t.ret_type.accept(self)}\"\n\n        if t.variables:\n            vs = []\n            for var in t.variables:\n                if isinstance(var, TypeVarType):\n                    if var.values:\n                        vals = f\"({', '.join(val.accept(self) for val in var.values)})\"\n                        vs.append(f\"{var.name} in {vals}\")\n                    elif not is_named_instance(var.upper_bound, \"builtins.object\"):\n                        vs.append(\n                            f\"{var.name} <: {var.upper_bound.accept(self)}{f' = {var.default.accept(self)}' if var.has_default() else ''}\"\n                        )\n                    else:\n                        vs.append(\n                            f\"{var.name}{f' = {var.default.accept(self)}' if var.has_default()  else ''}\"\n                        )\n                else:\n                    # For other TypeVarLikeTypes, use the name and default\n                    vs.append(\n                        f\"{var.name}{f' = {var.default.accept(self)}' if var.has_default() else ''}\"\n                    )\n            s = f\"[{', '.join(vs)}] {s}\"\n\n        return f\"def {s}\"\n\n    def visit_overloaded(self, t: Overloaded, /) -> str:\n        a = []\n        for i in t.items:\n            a.append(i.accept(self))\n        return f\"Overload({', '.join(a)})\"\n\n    def visit_tuple_type(self, t: TupleType, /) -> str:\n        s = self.list_str(t.items) or \"()\"\n        if t.partial_fallback and t.partial_fallback.type:\n            fallback_name = t.partial_fallback.type.fullname\n            if fallback_name != \"builtins.tuple\":\n                return f\"tuple[{s}, fallback={t.partial_fallback.accept(self)}]\"\n        return f\"tuple[{s}]\"\n\n    def visit_typeddict_type(self, t: TypedDictType, /) -> str:\n        def item_str(name: str, typ: str) -> str:\n            modifier = \"\"\n            if name not in t.required_keys:\n                modifier += \"?\"\n            if name in t.readonly_keys:\n                modifier += \"=\"\n            return f\"{name!r}{modifier}: {typ}\"\n\n        s = (\n            \"{\"\n            + \", \".join(item_str(name, typ.accept(self)) for name, typ in t.items.items())\n            + \"}\"\n        )\n        prefix = \"\"\n        if t.fallback and t.fallback.type:\n            if t.fallback.type.fullname not in TPDICT_FB_NAMES:\n                if not self.options.reveal_verbose_types:\n                    prefix = t.fallback.type.fullname + \", \"\n                else:\n                    prefix = repr(t.fallback.type.fullname) + \", \"\n        return f\"TypedDict({prefix}{s})\"\n\n    def visit_raw_expression_type(self, t: RawExpressionType, /) -> str:\n        # For bytes literals, the value is already escaped, just add quotes and b prefix\n        if t.base_type_name == \"builtins.bytes\":\n            # The value is already escaped (e.g., \"foo\" or \"hello\\\\nworld\")\n            # Just add quotes and b prefix\n            return f\"b'{t.literal_value}'\"\n        return repr(t.literal_value)\n\n    def visit_literal_type(self, t: LiteralType, /) -> str:\n        return f\"Literal[{t.value_repr()}]\"\n\n    def visit_union_type(self, t: UnionType, /) -> str:\n        return self.list_str(t.items, use_or_syntax=True)\n\n    def visit_partial_type(self, t: PartialType, /) -> str:\n        if t.type is None:\n            return \"<partial None>\"\n        else:\n            return \"<partial {}[{}]>\".format(t.type.name, \", \".join([\"?\"] * len(t.type.type_vars)))\n\n    def visit_ellipsis_type(self, t: EllipsisType, /) -> str:\n        return \"...\"\n\n    def visit_type_type(self, t: TypeType, /) -> str:\n        if t.is_type_form:\n            type_name = \"TypeForm\"\n        else:\n            type_name = \"type\"\n        return f\"{type_name}[{t.item.accept(self)}]\"\n\n    def visit_placeholder_type(self, t: PlaceholderType, /) -> str:\n        return f\"<placeholder {t.fullname}>\"\n\n    def visit_type_alias_type(self, t: TypeAliasType, /) -> str:\n        if t.alias is None:\n            return \"<alias (unfixed)>\"\n        if not t.is_recursive:\n            return get_proper_type(t).accept(self)\n        if self.dotted_aliases is None:\n            self.dotted_aliases = set()\n        elif t in self.dotted_aliases:\n            return \"...\"\n        self.dotted_aliases.add(t)\n        type_str = get_proper_type(t).accept(self)\n        self.dotted_aliases.discard(t)\n        return type_str\n\n    def visit_unpack_type(self, t: UnpackType, /) -> str:\n        if not self.options.reveal_verbose_types:\n            return f\"*{t.type.accept(self)}\"\n        return f\"Unpack[{t.type.accept(self)}]\"\n\n    def list_str(self, a: Iterable[Type], *, use_or_syntax: bool = False) -> str:\n        \"\"\"Convert items of an array to strings (pretty-print types)\n        and join the results with commas.\n        \"\"\"\n        res = []\n        for t in a:\n            s = t.accept(self)\n            if use_or_syntax and isinstance(get_proper_type(t), CallableType):\n                res.append(f\"({s})\")\n            else:\n                res.append(s)\n        sep = \", \" if not use_or_syntax else \" | \"\n        return sep.join(res)\n\n\nclass TrivialSyntheticTypeTranslator(TypeTranslator, SyntheticTypeVisitor[Type]):\n    \"\"\"A base class for type translators that need to be run during semantic analysis.\"\"\"\n\n    def visit_placeholder_type(self, t: PlaceholderType, /) -> Type:\n        return t\n\n    def visit_callable_argument(self, t: CallableArgument, /) -> Type:\n        return t\n\n    def visit_ellipsis_type(self, t: EllipsisType, /) -> Type:\n        return t\n\n    def visit_raw_expression_type(self, t: RawExpressionType, /) -> Type:\n        return t\n\n    def visit_type_list(self, t: TypeList, /) -> Type:\n        return t\n\n\nclass CollectAliasesVisitor(TypeQuery[list[mypy.nodes.TypeAlias]]):\n    def __init__(self) -> None:\n        super().__init__()\n        self.seen_alias_nodes: set[mypy.nodes.TypeAlias] = set()\n\n    def strategy(self, items: list[list[mypy.nodes.TypeAlias]]) -> list[mypy.nodes.TypeAlias]:\n        out = []\n        for item in items:\n            out.extend(item)\n        return out\n\n    def visit_type_alias_type(self, t: TypeAliasType, /) -> list[mypy.nodes.TypeAlias]:\n        assert t.alias is not None\n        if t.alias not in self.seen_alias_nodes:\n            self.seen_alias_nodes.add(t.alias)\n            res = [t.alias] + t.alias.target.accept(self)\n        else:\n            res = []\n        for arg in t.args:\n            res.extend(arg.accept(self))\n        return res\n\n\ndef is_named_instance(t: Type, fullnames: str | tuple[str, ...]) -> TypeGuard[Instance]:\n    if not isinstance(fullnames, tuple):\n        fullnames = (fullnames,)\n\n    t = get_proper_type(t)\n    return isinstance(t, Instance) and t.type.fullname in fullnames\n\n\nclass HasTypeVars(BoolTypeQuery):\n    \"\"\"Visitor for querying whether a type has a type variable component.\"\"\"\n\n    def __init__(self) -> None:\n        super().__init__(ANY_STRATEGY)\n        self.skip_alias_target = True\n\n    def visit_type_var(self, t: TypeVarType) -> bool:\n        return True\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType) -> bool:\n        return True\n\n    def visit_param_spec(self, t: ParamSpecType) -> bool:\n        return True\n\n\ndef has_type_vars(typ: Type) -> bool:\n    \"\"\"Check if a type contains any type variables (recursively).\"\"\"\n    return typ.accept(HasTypeVars())\n\n\nclass HasRecursiveType(BoolTypeQuery):\n    def __init__(self) -> None:\n        super().__init__(ANY_STRATEGY)\n\n    def visit_type_alias_type(self, t: TypeAliasType) -> bool:\n        return t.is_recursive or self.query_types(t.args)\n\n\n# Use singleton since this is hot (note: call reset() before using)\n_has_recursive_type: Final = HasRecursiveType()\n\n\ndef has_recursive_types(typ: Type) -> bool:\n    \"\"\"Check if a type contains any recursive aliases (recursively).\"\"\"\n    _has_recursive_type.reset()\n    return typ.accept(_has_recursive_type)\n\n\ndef split_with_prefix_and_suffix(\n    types: tuple[Type, ...], prefix: int, suffix: int\n) -> tuple[tuple[Type, ...], tuple[Type, ...], tuple[Type, ...]]:\n    if len(types) <= prefix + suffix:\n        types = extend_args_for_prefix_and_suffix(types, prefix, suffix)\n    if suffix:\n        return types[:prefix], types[prefix:-suffix], types[-suffix:]\n    else:\n        return types[:prefix], types[prefix:], ()\n\n\ndef extend_args_for_prefix_and_suffix(\n    types: tuple[Type, ...], prefix: int, suffix: int\n) -> tuple[Type, ...]:\n    \"\"\"Extend list of types by eating out from variadic tuple to satisfy prefix and suffix.\"\"\"\n    idx = None\n    item = None\n    for i, t in enumerate(types):\n        if isinstance(t, UnpackType):\n            p_type = get_proper_type(t.type)\n            if isinstance(p_type, Instance) and p_type.type.fullname == \"builtins.tuple\":\n                item = p_type.args[0]\n                idx = i\n                break\n\n    if idx is None:\n        return types\n    assert item is not None\n    if idx < prefix:\n        start = (item,) * (prefix - idx)\n    else:\n        start = ()\n    if len(types) - idx - 1 < suffix:\n        end = (item,) * (suffix - len(types) + idx + 1)\n    else:\n        end = ()\n    return types[:idx] + start + (types[idx],) + end + types[idx + 1 :]\n\n\ndef flatten_nested_unions(\n    types: Sequence[Type], *, handle_type_alias_type: bool = True, handle_recursive: bool = True\n) -> list[Type]:\n    \"\"\"Flatten nested unions in a type list.\"\"\"\n    if not isinstance(types, list):\n        typelist = list(types)\n    else:\n        typelist = cast(\"list[Type]\", types)\n\n    # Fast path: most of the time there is nothing to flatten\n    if not any(isinstance(t, (TypeAliasType, UnionType)) for t in typelist):  # type: ignore[misc]\n        return typelist\n\n    flat_items: list[Type] = []\n    for t in typelist:\n        if handle_type_alias_type and isinstance(t, TypeAliasType):\n            if not handle_recursive and t.is_recursive:\n                tp: Type = t\n            else:\n                tp = get_proper_type(t)\n        else:\n            tp = t\n        if isinstance(tp, ProperType) and isinstance(tp, UnionType):\n            flat_items.extend(\n                flatten_nested_unions(\n                    tp.items,\n                    handle_type_alias_type=handle_type_alias_type,\n                    handle_recursive=handle_recursive,\n                )\n            )\n        else:\n            # Must preserve original aliases when possible.\n            flat_items.append(t)\n    return flat_items\n\n\ndef find_unpack_in_list(items: Sequence[Type]) -> int | None:\n    unpack_index: int | None = None\n    for i, item in enumerate(items):\n        if isinstance(item, UnpackType):\n            # We cannot fail here, so we must check this in an earlier\n            # semanal phase.\n            # Funky code here avoids mypyc narrowing the type of unpack_index.\n            old_index = unpack_index\n            assert old_index is None\n            # Don't return so that we can also sanity check there is only one.\n            unpack_index = i\n    return unpack_index\n\n\ndef flatten_nested_tuples(types: Iterable[Type]) -> list[Type]:\n    \"\"\"Recursively flatten TupleTypes nested with Unpack.\n\n    For example this will transform\n        Tuple[A, Unpack[Tuple[B, Unpack[Tuple[C, D]]]]]\n    into\n        Tuple[A, B, C, D]\n    \"\"\"\n    res = []\n    for typ in types:\n        if not isinstance(typ, UnpackType):\n            res.append(typ)\n            continue\n        p_type = get_proper_type(typ.type)\n        if not isinstance(p_type, TupleType):\n            res.append(typ)\n            continue\n        if isinstance(typ.type, TypeAliasType):\n            items = []\n            for item in p_type.items:\n                if (\n                    isinstance(item, ProperType)\n                    and isinstance(item, Instance)\n                    or isinstance(item, TypeAliasType)\n                ):\n                    if len(item.args) == 0:\n                        item = item.copy_modified()\n                        item.set_line(typ)\n                items.append(item)\n        else:\n            items = p_type.items\n        res.extend(flatten_nested_tuples(items))\n    return res\n\n\ndef is_literal_type(typ: ProperType, fallback_fullname: str, value: LiteralValue) -> bool:\n    \"\"\"Check if this type is a LiteralType with the given fallback type and value.\"\"\"\n    if isinstance(typ, Instance) and typ.last_known_value:\n        typ = typ.last_known_value\n    return (\n        isinstance(typ, LiteralType)\n        and typ.fallback.type.fullname == fallback_fullname\n        and typ.value == value\n    )\n\n\nnames: Final = globals().copy()\nnames.pop(\"NOT_READY\", None)\ndeserialize_map: Final = {\n    key: obj.deserialize\n    for key, obj in names.items()\n    if isinstance(obj, type) and issubclass(obj, Type) and obj is not Type\n}\n\n\ndef callable_with_ellipsis(any_type: AnyType, ret_type: Type, fallback: Instance) -> CallableType:\n    \"\"\"Construct type Callable[..., ret_type].\"\"\"\n    return CallableType(\n        [any_type, any_type],\n        [ARG_STAR, ARG_STAR2],\n        [None, None],\n        ret_type=ret_type,\n        fallback=fallback,\n        is_ellipsis_args=True,\n    )\n\n\ndef remove_dups(types: list[T]) -> list[T]:\n    if len(types) <= 1:\n        return types\n    # Get unique elements in order of appearance\n    all_types: set[T] = set()\n    new_types: list[T] = []\n    for t in types:\n        if t not in all_types:\n            new_types.append(t)\n            all_types.add(t)\n    return new_types\n\n\ndef type_vars_as_args(type_vars: Sequence[TypeVarLikeType]) -> tuple[Type, ...]:\n    \"\"\"Represent type variables as they would appear in a type argument list.\"\"\"\n    args: list[Type] = []\n    for tv in type_vars:\n        if isinstance(tv, TypeVarTupleType):\n            args.append(UnpackType(tv))\n        else:\n            args.append(tv)\n    return tuple(args)\n\n\n# See docstring for mypy/cache.py for reserved tag ranges.\n# Instance-related tags.\nINSTANCE: Final[Tag] = 80\nINSTANCE_SIMPLE: Final[Tag] = 81\nINSTANCE_GENERIC: Final[Tag] = 82\nINSTANCE_STR: Final[Tag] = 83\nINSTANCE_FUNCTION: Final[Tag] = 84\nINSTANCE_INT: Final[Tag] = 85\nINSTANCE_BOOL: Final[Tag] = 86\nINSTANCE_OBJECT: Final[Tag] = 87\n\n# Other type tags.\nTYPE_ALIAS_TYPE: Final[Tag] = 100\nTYPE_VAR_TYPE: Final[Tag] = 101\nPARAM_SPEC_TYPE: Final[Tag] = 102\nTYPE_VAR_TUPLE_TYPE: Final[Tag] = 103\nUNBOUND_TYPE: Final[Tag] = 104\nUNPACK_TYPE: Final[Tag] = 105\nANY_TYPE: Final[Tag] = 106\nUNINHABITED_TYPE: Final[Tag] = 107\nNONE_TYPE: Final[Tag] = 108\nDELETED_TYPE: Final[Tag] = 109\nCALLABLE_TYPE: Final[Tag] = 110\nOVERLOADED: Final[Tag] = 111\nTUPLE_TYPE: Final[Tag] = 112\nTYPED_DICT_TYPE: Final[Tag] = 113\nLITERAL_TYPE: Final[Tag] = 114\nUNION_TYPE: Final[Tag] = 115\nTYPE_TYPE: Final[Tag] = 116\nPARAMETERS: Final[Tag] = 117\nLIST_TYPE: Final[Tag] = 118  # Only valid in serialized ASTs\nELLIPSIS_TYPE: Final[Tag] = 119  # Only valid in serialized ASTs\nRAW_EXPRESSION_TYPE: Final[Tag] = 120  # Only valid in serialized ASTs\nCALL_TYPE: Final[Tag] = 121  # Only valid in serialized ASTs\n\n\ndef read_type(data: ReadBuffer, tag: Tag | None = None) -> Type:\n    if tag is None:\n        tag = read_tag(data)\n    # The branches here are ordered manually by type \"popularity\".\n    if tag == INSTANCE:\n        return Instance.read(data)\n    if tag == ANY_TYPE:\n        return AnyType.read(data)\n    if tag == TYPE_VAR_TYPE:\n        return TypeVarType.read(data)\n    if tag == CALLABLE_TYPE:\n        return CallableType.read(data)\n    if tag == NONE_TYPE:\n        return NoneType.read(data)\n    if tag == UNION_TYPE:\n        return UnionType.read(data)\n    if tag == LITERAL_TYPE:\n        return LiteralType.read(data)\n    if tag == TYPE_ALIAS_TYPE:\n        return TypeAliasType.read(data)\n    if tag == TUPLE_TYPE:\n        return TupleType.read(data)\n    if tag == TYPED_DICT_TYPE:\n        return TypedDictType.read(data)\n    if tag == TYPE_TYPE:\n        return TypeType.read(data)\n    if tag == OVERLOADED:\n        return Overloaded.read(data)\n    if tag == PARAM_SPEC_TYPE:\n        return ParamSpecType.read(data)\n    if tag == TYPE_VAR_TUPLE_TYPE:\n        return TypeVarTupleType.read(data)\n    if tag == UNPACK_TYPE:\n        return UnpackType.read(data)\n    if tag == PARAMETERS:\n        return Parameters.read(data)\n    if tag == UNINHABITED_TYPE:\n        return UninhabitedType.read(data)\n    if tag == UNBOUND_TYPE:\n        return UnboundType.read(data)\n    if tag == DELETED_TYPE:\n        return DeletedType.read(data)\n    assert False, f\"Unknown type tag {tag}\"\n\n\ndef read_function_like(data: ReadBuffer, tag: Tag) -> FunctionLike:\n    if tag == CALLABLE_TYPE:\n        return CallableType.read(data)\n    if tag == OVERLOADED:\n        return Overloaded.read(data)\n    assert False, f\"Invalid type tag for FunctionLike {tag}\"\n\n\ndef read_type_var_likes(data: ReadBuffer) -> list[TypeVarLikeType]:\n    \"\"\"Specialized version of read_type_list() for lists of type variables.\"\"\"\n    assert read_tag(data) == LIST_GEN\n    ret: list[TypeVarLikeType] = []\n    for _ in range(read_int_bare(data)):\n        tag = read_tag(data)\n        if tag == TYPE_VAR_TYPE:\n            ret.append(TypeVarType.read(data))\n        elif tag == PARAM_SPEC_TYPE:\n            ret.append(ParamSpecType.read(data))\n        elif tag == TYPE_VAR_TUPLE_TYPE:\n            ret.append(TypeVarTupleType.read(data))\n        else:\n            assert False, f\"Invalid type tag for TypeVarLikeType {tag}\"\n    return ret\n\n\ndef read_type_opt(data: ReadBuffer) -> Type | None:\n    tag = read_tag(data)\n    if tag == LITERAL_NONE:\n        return None\n    return read_type(data, tag)\n\n\ndef write_type_opt(data: WriteBuffer, value: Type | None) -> None:\n    if value is not None:\n        value.write(data)\n    else:\n        write_tag(data, LITERAL_NONE)\n\n\ndef read_type_list(data: ReadBuffer) -> list[Type]:\n    assert read_tag(data) == LIST_GEN\n    size = read_int_bare(data)\n    return [read_type(data) for _ in range(size)]\n\n\ndef write_type_list(data: WriteBuffer, value: Sequence[Type]) -> None:\n    write_tag(data, LIST_GEN)\n    write_int_bare(data, len(value))\n    for item in value:\n        item.write(data)\n\n\ndef read_type_map(data: ReadBuffer) -> dict[str, Type]:\n    assert read_tag(data) == DICT_STR_GEN\n    size = read_int_bare(data)\n    return {read_str_bare(data): read_type(data) for _ in range(size)}\n\n\ndef write_type_map(data: WriteBuffer, value: dict[str, Type]) -> None:\n    write_tag(data, DICT_STR_GEN)\n    write_int_bare(data, len(value))\n    for key in sorted(value):\n        write_str_bare(data, key)\n        value[key].write(data)\n\n\n# This cyclic import is unfortunate, but to avoid it we would need to move away all uses\n# of get_proper_type() from types.py. Majority of them have been removed, but few remaining\n# are quite tricky to get rid of, but ultimately we want to do it at some point.\nfrom mypy.expandtype import ExpandTypeVisitor\n\n\nclass InstantiateAliasVisitor(ExpandTypeVisitor):\n    def visit_union_type(self, t: UnionType) -> Type:\n        # Unlike regular expand_type(), we don't do any simplification for unions,\n        # not even removing strict duplicates. There are three reasons for this:\n        #   * get_proper_type() is a very hot function, even slightest slow down will\n        #     cause a perf regression\n        #   * We want to preserve this historical behaviour, to avoid possible\n        #     regressions\n        #   * Simplifying unions may (indirectly) call get_proper_type(), causing\n        #     infinite recursion.\n        return TypeTranslator.visit_union_type(self, t)\n"
  },
  {
    "path": "mypy/types_utils.py",
    "content": "\"\"\"\nThis module is for (more basic) type operations that should not depend on is_subtype(),\nmeet_types(), join_types() etc. We don't want to keep them in mypy/types.py for two reasons:\n* Reduce the size of that module.\n* Reduce use of get_proper_type() in types.py to avoid cyclic imports\n  expand_type <-> types, if we move get_proper_type() to the former.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable, Iterable\nfrom typing import cast\n\nfrom mypy.nodes import ARG_STAR, ARG_STAR2, FuncItem, TypeAlias\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    ParamSpecType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypeType,\n    TypeVarType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n    flatten_nested_unions,\n    get_proper_type,\n    get_proper_types,\n)\n\n\ndef flatten_types(types: Iterable[Type]) -> Iterable[Type]:\n    for t in types:\n        tp = get_proper_type(t)\n        if isinstance(tp, UnionType):\n            yield from flatten_types(tp.items)\n        else:\n            yield t\n\n\ndef strip_type(typ: Type) -> Type:\n    \"\"\"Make a copy of type without 'debugging info' (function name).\"\"\"\n    orig_typ = typ\n    typ = get_proper_type(typ)\n    if isinstance(typ, CallableType):\n        return typ.copy_modified(name=None)\n    elif isinstance(typ, Overloaded):\n        return Overloaded([cast(CallableType, strip_type(item)) for item in typ.items])\n    else:\n        return orig_typ\n\n\ndef is_invalid_recursive_alias(seen_nodes: set[TypeAlias], target: Type) -> bool:\n    \"\"\"Flag aliases like A = Union[int, A], T = tuple[int, *T] (and similar mutual aliases).\n\n    Such aliases don't make much sense, and cause problems in later phases.\n    \"\"\"\n    if isinstance(target, TypeAliasType):\n        if target.alias in seen_nodes:\n            return True\n        assert target.alias, f\"Unfixed type alias {target.type_ref}\"\n        return is_invalid_recursive_alias(seen_nodes | {target.alias}, get_proper_type(target))\n    assert isinstance(target, ProperType)\n    if not isinstance(target, (UnionType, TupleType)):\n        return False\n    if isinstance(target, UnionType):\n        return any(is_invalid_recursive_alias(seen_nodes, item) for item in target.items)\n    for item in target.items:\n        if isinstance(item, UnpackType):\n            if is_invalid_recursive_alias(seen_nodes, item.type):\n                return True\n    return False\n\n\ndef get_bad_type_type_item(item: Type) -> str | None:\n    \"\"\"Prohibit types like Type[Type[...]].\n\n    Such types are explicitly prohibited by PEP 484. Also, they cause problems\n    with recursive types like T = Type[T], because internal representation of\n    TypeType item is normalized (i.e. always a proper type).\n\n    Also forbids `Type[Literal[...]]`, because typing spec does not allow it.\n    \"\"\"\n    # TODO: what else cannot be present in `type[...]`?\n    item = get_proper_type(item)\n    if isinstance(item, TypeType):\n        return \"Type[...]\"\n    if isinstance(item, LiteralType):\n        return \"Literal[...]\"\n    if isinstance(item, UnionType):\n        items = [\n            bad_item\n            for typ in flatten_nested_unions(item.items)\n            if (bad_item := get_bad_type_type_item(typ)) is not None\n        ]\n        if not items:\n            return None\n        if len(items) == 1:\n            return items[0]\n        return f\"Union[{', '.join(items)}]\"\n    return None\n\n\ndef is_union_with_any(tp: Type) -> bool:\n    \"\"\"Is this a union with Any or a plain Any type?\"\"\"\n    tp = get_proper_type(tp)\n    if isinstance(tp, AnyType):\n        return True\n    if not isinstance(tp, UnionType):\n        return False\n    return any(is_union_with_any(t) for t in get_proper_types(tp.items))\n\n\ndef is_generic_instance(tp: Type) -> bool:\n    tp = get_proper_type(tp)\n    return isinstance(tp, Instance) and bool(tp.args)\n\n\ndef is_overlapping_none(t: Type) -> bool:\n    t = get_proper_type(t)\n    return isinstance(t, NoneType) or (\n        isinstance(t, UnionType) and any(isinstance(get_proper_type(e), NoneType) for e in t.items)\n    )\n\n\ndef remove_optional(typ: Type) -> Type:\n    typ = get_proper_type(typ)\n    if isinstance(typ, UnionType):\n        return UnionType.make_union(\n            [t for t in typ.items if not isinstance(get_proper_type(t), NoneType)]\n        )\n    elif isinstance(typ, NoneType):\n        return UninhabitedType()\n    else:\n        return typ\n\n\ndef is_self_type_like(typ: Type, *, is_classmethod: bool) -> bool:\n    \"\"\"Does this look like a self-type annotation?\"\"\"\n    typ = get_proper_type(typ)\n    if not is_classmethod:\n        return isinstance(typ, TypeVarType)\n    if not isinstance(typ, TypeType):\n        return False\n    return isinstance(typ.item, TypeVarType)\n\n\ndef store_argument_type(\n    defn: FuncItem, i: int, typ: CallableType, named_type: Callable[[str, list[Type]], Instance]\n) -> None:\n    arg_type = typ.arg_types[i]\n    if typ.arg_kinds[i] == ARG_STAR:\n        if isinstance(arg_type, ParamSpecType):\n            pass\n        elif isinstance(arg_type, UnpackType):\n            unpacked_type = get_proper_type(arg_type.type)\n            if isinstance(unpacked_type, TupleType):\n                # Instead of using Tuple[Unpack[Tuple[...]]], just use Tuple[...]\n                arg_type = unpacked_type\n            elif (\n                isinstance(unpacked_type, Instance)\n                and unpacked_type.type.fullname == \"builtins.tuple\"\n            ):\n                arg_type = unpacked_type\n            else:\n                # TODO: verify that we can only have a TypeVarTuple here.\n                arg_type = TupleType(\n                    [arg_type],\n                    fallback=named_type(\"builtins.tuple\", [named_type(\"builtins.object\", [])]),\n                )\n        else:\n            # builtins.tuple[T] is typing.Tuple[T, ...]\n            arg_type = named_type(\"builtins.tuple\", [arg_type])\n    elif typ.arg_kinds[i] == ARG_STAR2:\n        if not isinstance(arg_type, ParamSpecType) and not typ.unpack_kwargs:\n            arg_type = named_type(\"builtins.dict\", [named_type(\"builtins.str\", []), arg_type])\n    defn.arguments[i].variable.type = arg_type\n"
  },
  {
    "path": "mypy/typeshed/LICENSE",
    "content": "The \"typeshed\" project is licensed under the terms of the Apache license, as\nreproduced below.\n\n= = = = =\n\nApache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n= = = = =\n\nParts of typeshed are licensed under different licenses (like the MIT\nlicense), reproduced below.\n\n= = = = =\n\nThe MIT License\n\nCopyright (c) 2015 Jukka Lehtosalo and contributors\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\n= = = = =\n"
  },
  {
    "path": "mypy/typeshed/stdlib/VERSIONS",
    "content": "# The structure of this file is as follows:\n# - Blank lines and comments starting with `#` are ignored.\n# - Lines contain the name of a module, followed by a colon,\n#   a space, and a version range (for example: `symbol: 3.0-3.9`).\n#\n# Version ranges may be of the form \"X.Y-A.B\" or \"X.Y-\". The\n# first form means that a module was introduced in version X.Y and last\n# available in version A.B. The second form means that the module was\n# introduced in version X.Y and is still available in the latest\n# version of Python.\n#\n# If a submodule is not listed separately, it has the same lifetime as\n# its parent module.\n#\n# Python versions before 3.0 are ignored, so any module that was already\n# present in 3.0 will have \"3.0\" as its minimum version. Version ranges\n# for unsupported versions of Python 3 are generally accurate but we do\n# not guarantee their correctness.\n\n__future__: 3.0-\n__main__: 3.0-\n_ast: 3.0-\n_asyncio: 3.0-\n_bisect: 3.0-\n_blake2: 3.6-\n_bootlocale: 3.4-3.9\n_bz2: 3.3-\n_codecs: 3.0-\n_collections_abc: 3.3-\n_compat_pickle: 3.1-\n_compression: 3.5-3.13\n_contextvars: 3.7-\n_csv: 3.0-\n_ctypes: 3.0-\n_curses: 3.0-\n_curses_panel: 3.0-\n_dbm: 3.0-\n_decimal: 3.3-\n_frozen_importlib: 3.0-\n_frozen_importlib_external: 3.5-\n_gdbm: 3.0-\n_hashlib: 3.0-\n_heapq: 3.0-\n_imp: 3.0-\n_interpchannels: 3.13-\n_interpqueues: 3.13-\n_interpreters: 3.13-\n_io: 3.0-\n_json: 3.0-\n_locale: 3.0-\n_lsprof: 3.0-\n_lzma: 3.3-\n_markupbase: 3.0-\n_msi: 3.0-3.12\n_multibytecodec: 3.0-\n_operator: 3.4-\n_osx_support: 3.0-\n_pickle: 3.0-\n_posixsubprocess: 3.2-\n_py_abc: 3.7-\n_pydecimal: 3.5-\n_queue: 3.7-\n_random: 3.0-\n_sitebuiltins: 3.4-\n_socket: 3.0-  # present in 3.0 at runtime, but not in typeshed\n_sqlite3: 3.0-\n_ssl: 3.0-\n_stat: 3.4-\n_struct: 3.0-\n_thread: 3.0-\n_threading_local: 3.0-\n_tkinter: 3.0-\n_tracemalloc: 3.4-\n_typeshed: 3.0-  # not present at runtime, only for type checking\n_warnings: 3.0-\n_weakref: 3.0-\n_weakrefset: 3.0-\n_winapi: 3.3-\n_zstd: 3.14-\nabc: 3.0-\naifc: 3.0-3.12\nannotationlib: 3.14-\nantigravity: 3.0-\nargparse: 3.0-\narray: 3.0-\nast: 3.0-\nasynchat: 3.0-3.11\nasyncio: 3.4-\nasyncio.exceptions: 3.8-\nasyncio.format_helpers: 3.7-\nasyncio.graph: 3.14-\nasyncio.mixins: 3.10-\nasyncio.runners: 3.7-\nasyncio.staggered: 3.8-\nasyncio.taskgroups: 3.11-\nasyncio.threads: 3.9-\nasyncio.timeouts: 3.11-\nasyncio.tools: 3.14-\nasyncio.trsock: 3.8-\nasyncore: 3.0-3.11\natexit: 3.0-\naudioop: 3.0-3.12\nbase64: 3.0-\nbdb: 3.0-\nbinascii: 3.0-\nbinhex: 3.0-3.10\nbisect: 3.0-\nbuiltins: 3.0-\nbz2: 3.0-\ncProfile: 3.0-\ncalendar: 3.0-\ncgi: 3.0-3.12\ncgitb: 3.0-3.12\nchunk: 3.0-3.12\ncmath: 3.0-\ncmd: 3.0-\ncode: 3.0-\ncodecs: 3.0-\ncodeop: 3.0-\ncollections: 3.0-\ncollections.abc: 3.3-\ncolorsys: 3.0-\ncompileall: 3.0-\ncompression: 3.14-\nconcurrent: 3.2-\nconcurrent.futures.interpreter: 3.14-\nconcurrent.interpreters: 3.14-\nconfigparser: 3.0-\ncontextlib: 3.0-\ncontextvars: 3.7-\ncopy: 3.0-\ncopyreg: 3.0-\ncrypt: 3.0-3.12\ncsv: 3.0-\nctypes: 3.0-\ncurses: 3.0-\ndataclasses: 3.7-\ndatetime: 3.0-\ndbm: 3.0-\ndbm.sqlite3: 3.13-\ndecimal: 3.0-\ndifflib: 3.0-\ndis: 3.0-\ndistutils: 3.0-3.11\ndistutils.command.bdist_msi: 3.0-3.10\ndistutils.command.bdist_wininst: 3.0-3.9\ndoctest: 3.0-\nemail: 3.0-\nencodings: 3.0-\nencodings.cp1125: 3.4-\nencodings.cp273: 3.4-\nencodings.cp858: 3.2-\nencodings.koi8_t: 3.5-\nencodings.kz1048: 3.5-\nensurepip: 3.0-\nenum: 3.4-\nerrno: 3.0-\nfaulthandler: 3.3-\nfcntl: 3.0-\nfilecmp: 3.0-\nfileinput: 3.0-\nfnmatch: 3.0-\nformatter: 3.0-3.9\nfractions: 3.0-\nftplib: 3.0-\nfunctools: 3.0-\ngc: 3.0-\ngenericpath: 3.0-\ngetopt: 3.0-\ngetpass: 3.0-\ngettext: 3.0-\nglob: 3.0-\ngraphlib: 3.9-\ngrp: 3.0-\ngzip: 3.0-\nhashlib: 3.0-\nheapq: 3.0-\nhmac: 3.0-\nhtml: 3.0-\nhttp: 3.0-\nimaplib: 3.0-\nimghdr: 3.0-3.12\nimp: 3.0-3.11\nimportlib: 3.0-\nimportlib._abc: 3.10-\nimportlib._bootstrap: 3.0-\nimportlib._bootstrap_external: 3.5-\nimportlib.metadata: 3.8-\nimportlib.metadata._meta: 3.10-\nimportlib.metadata.diagnose: 3.13-\nimportlib.readers: 3.10-\nimportlib.resources: 3.7-\nimportlib.resources._common: 3.11-\nimportlib.resources._functional: 3.13-\nimportlib.resources.abc: 3.11-\nimportlib.resources.readers: 3.11-\nimportlib.resources.simple: 3.11-\nimportlib.simple: 3.11-\ninspect: 3.0-\nio: 3.0-\nipaddress: 3.3-\nitertools: 3.0-\njson: 3.0-\nkeyword: 3.0-\nlib2to3: 3.0-3.12\nlinecache: 3.0-\nlocale: 3.0-\nlogging: 3.0-\nlzma: 3.3-\nmailbox: 3.0-\nmailcap: 3.0-3.12\nmarshal: 3.0-\nmath: 3.0-\nmimetypes: 3.0-\nmmap: 3.0-\nmodulefinder: 3.0-\nmsilib: 3.0-3.12\nmsvcrt: 3.0-\nmultiprocessing: 3.0-\nmultiprocessing.resource_tracker: 3.8-\nmultiprocessing.shared_memory: 3.8-\nnetrc: 3.0-\nnis: 3.0-3.12\nnntplib: 3.0-3.12\nnt: 3.0-\nntpath: 3.0-\nnturl2path: 3.0-\nnumbers: 3.0-\nopcode: 3.0-\noperator: 3.0-\noptparse: 3.0-\nos: 3.0-\nossaudiodev: 3.0-3.12\nparser: 3.0-3.9\npathlib: 3.4-\npathlib.types: 3.14-\npdb: 3.0-\npickle: 3.0-\npickletools: 3.0-\npipes: 3.0-3.12\npkgutil: 3.0-\nplatform: 3.0-\nplistlib: 3.0-\npoplib: 3.0-\nposix: 3.0-\nposixpath: 3.0-\npprint: 3.0-\nprofile: 3.0-\npstats: 3.0-\npty: 3.0-\npwd: 3.0-\npy_compile: 3.0-\npyclbr: 3.0-\npydoc: 3.0-\npydoc_data: 3.0-\npydoc_data.module_docs: 3.13-\npyexpat: 3.0-\nqueue: 3.0-\nquopri: 3.0-\nrandom: 3.0-\nre: 3.0-\nreadline: 3.0-\nreprlib: 3.0-\nresource: 3.0-\nrlcompleter: 3.0-\nrunpy: 3.0-\nsched: 3.0-\nsecrets: 3.6-\nselect: 3.0-\nselectors: 3.4-\nshelve: 3.0-\nshlex: 3.0-\nshutil: 3.0-\nsignal: 3.0-\nsite: 3.0-\nsmtpd: 3.0-3.11\nsmtplib: 3.0-\nsndhdr: 3.0-3.12\nsocket: 3.0-\nsocketserver: 3.0-\nspwd: 3.0-3.12\nsqlite3: 3.0-\nsre_compile: 3.0-\nsre_constants: 3.0-\nsre_parse: 3.0-\nssl: 3.0-\nstat: 3.0-\nstatistics: 3.4-\nstring: 3.0-\nstring.templatelib: 3.14-\nstringprep: 3.0-\nstruct: 3.0-\nsubprocess: 3.0-\nsunau: 3.0-3.12\nsymbol: 3.0-3.9\nsymtable: 3.0-\nsys: 3.0-\nsys._monitoring: 3.12-  # Doesn't actually exist. See comments in the stub.\nsysconfig: 3.0-\nsyslog: 3.0-\ntabnanny: 3.0-\ntarfile: 3.0-\ntelnetlib: 3.0-3.12\ntempfile: 3.0-\ntermios: 3.0-\ntextwrap: 3.0-\nthis: 3.0-\nthreading: 3.0-\ntime: 3.0-\ntimeit: 3.0-\ntkinter: 3.0-\ntkinter.tix: 3.0-3.12\ntoken: 3.0-\ntokenize: 3.0-\ntomllib: 3.11-\ntrace: 3.0-\ntraceback: 3.0-\ntracemalloc: 3.4-\ntty: 3.0-\nturtle: 3.0-\ntypes: 3.0-\ntyping: 3.5-\ntyping_extensions: 3.0-\nunicodedata: 3.0-\nunittest: 3.0-\nunittest._log: 3.9-\nunittest.async_case: 3.8-\nurllib: 3.0-\nuu: 3.0-3.12\nuuid: 3.0-\nvenv: 3.3-\nwarnings: 3.0-\nwave: 3.0-\nweakref: 3.0-\nwebbrowser: 3.0-\nwinreg: 3.0-\nwinsound: 3.0-\nwsgiref: 3.0-\nwsgiref.types: 3.11-\nxdrlib: 3.0-3.12\nxml: 3.0-\nxmlrpc: 3.0-\nxxlimited: 3.2-\nzipapp: 3.5-\nzipfile: 3.0-\nzipfile._path: 3.12-\nzipimport: 3.0-\nzlib: 3.0-\nzoneinfo: 3.9-\n"
  },
  {
    "path": "mypy/typeshed/stdlib/__future__.pyi",
    "content": "from typing_extensions import TypeAlias\n\n_VersionInfo: TypeAlias = tuple[int, int, int, str, int]\n\nclass _Feature:\n    def __init__(self, optionalRelease: _VersionInfo, mandatoryRelease: _VersionInfo | None, compiler_flag: int) -> None: ...\n    def getOptionalRelease(self) -> _VersionInfo: ...\n    def getMandatoryRelease(self) -> _VersionInfo | None: ...\n    compiler_flag: int\n\nabsolute_import: _Feature\ndivision: _Feature\ngenerators: _Feature\nnested_scopes: _Feature\nprint_function: _Feature\nunicode_literals: _Feature\nwith_statement: _Feature\nbarry_as_FLUFL: _Feature\ngenerator_stop: _Feature\nannotations: _Feature\n\nall_feature_names: list[str]  # undocumented\n\n__all__ = [\n    \"all_feature_names\",\n    \"absolute_import\",\n    \"division\",\n    \"generators\",\n    \"nested_scopes\",\n    \"print_function\",\n    \"unicode_literals\",\n    \"with_statement\",\n    \"barry_as_FLUFL\",\n    \"generator_stop\",\n    \"annotations\",\n]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/__main__.pyi",
    "content": "def __getattr__(name: str): ...  # incomplete module\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_ast.pyi",
    "content": "import sys\nfrom ast import (\n    AST as AST,\n    Add as Add,\n    And as And,\n    AnnAssign as AnnAssign,\n    Assert as Assert,\n    Assign as Assign,\n    AsyncFor as AsyncFor,\n    AsyncFunctionDef as AsyncFunctionDef,\n    AsyncWith as AsyncWith,\n    Attribute as Attribute,\n    AugAssign as AugAssign,\n    Await as Await,\n    BinOp as BinOp,\n    BitAnd as BitAnd,\n    BitOr as BitOr,\n    BitXor as BitXor,\n    BoolOp as BoolOp,\n    Break as Break,\n    Call as Call,\n    ClassDef as ClassDef,\n    Compare as Compare,\n    Constant as Constant,\n    Continue as Continue,\n    Del as Del,\n    Delete as Delete,\n    Dict as Dict,\n    DictComp as DictComp,\n    Div as Div,\n    Eq as Eq,\n    ExceptHandler as ExceptHandler,\n    Expr as Expr,\n    Expression as Expression,\n    FloorDiv as FloorDiv,\n    For as For,\n    FormattedValue as FormattedValue,\n    FunctionDef as FunctionDef,\n    FunctionType as FunctionType,\n    GeneratorExp as GeneratorExp,\n    Global as Global,\n    Gt as Gt,\n    GtE as GtE,\n    If as If,\n    IfExp as IfExp,\n    Import as Import,\n    ImportFrom as ImportFrom,\n    In as In,\n    Interactive as Interactive,\n    Invert as Invert,\n    Is as Is,\n    IsNot as IsNot,\n    JoinedStr as JoinedStr,\n    Lambda as Lambda,\n    List as List,\n    ListComp as ListComp,\n    Load as Load,\n    LShift as LShift,\n    Lt as Lt,\n    LtE as LtE,\n    MatMult as MatMult,\n    Mod as Mod,\n    Module as Module,\n    Mult as Mult,\n    Name as Name,\n    NamedExpr as NamedExpr,\n    Nonlocal as Nonlocal,\n    Not as Not,\n    NotEq as NotEq,\n    NotIn as NotIn,\n    Or as Or,\n    Pass as Pass,\n    Pow as Pow,\n    Raise as Raise,\n    Return as Return,\n    RShift as RShift,\n    Set as Set,\n    SetComp as SetComp,\n    Slice as Slice,\n    Starred as Starred,\n    Store as Store,\n    Sub as Sub,\n    Subscript as Subscript,\n    Try as Try,\n    Tuple as Tuple,\n    TypeIgnore as TypeIgnore,\n    UAdd as UAdd,\n    UnaryOp as UnaryOp,\n    USub as USub,\n    While as While,\n    With as With,\n    Yield as Yield,\n    YieldFrom as YieldFrom,\n    alias as alias,\n    arg as arg,\n    arguments as arguments,\n    boolop as boolop,\n    cmpop as cmpop,\n    comprehension as comprehension,\n    excepthandler as excepthandler,\n    expr as expr,\n    expr_context as expr_context,\n    keyword as keyword,\n    mod as mod,\n    operator as operator,\n    stmt as stmt,\n    type_ignore as type_ignore,\n    unaryop as unaryop,\n    withitem as withitem,\n)\nfrom typing import Final\n\nif sys.version_info >= (3, 12):\n    from ast import (\n        ParamSpec as ParamSpec,\n        TypeAlias as TypeAlias,\n        TypeVar as TypeVar,\n        TypeVarTuple as TypeVarTuple,\n        type_param as type_param,\n    )\n\nif sys.version_info >= (3, 11):\n    from ast import TryStar as TryStar\n\nif sys.version_info >= (3, 10):\n    from ast import (\n        Match as Match,\n        MatchAs as MatchAs,\n        MatchClass as MatchClass,\n        MatchMapping as MatchMapping,\n        MatchOr as MatchOr,\n        MatchSequence as MatchSequence,\n        MatchSingleton as MatchSingleton,\n        MatchStar as MatchStar,\n        MatchValue as MatchValue,\n        match_case as match_case,\n        pattern as pattern,\n    )\n\nPyCF_ALLOW_TOP_LEVEL_AWAIT: Final = 8192\nPyCF_ONLY_AST: Final = 1024\nPyCF_TYPE_COMMENTS: Final = 4096\n\nif sys.version_info >= (3, 13):\n    PyCF_OPTIMIZED_AST: Final = 33792\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_asyncio.pyi",
    "content": "import sys\nfrom asyncio.events import AbstractEventLoop\nfrom collections.abc import Awaitable, Callable, Coroutine, Generator, Iterable\nfrom contextvars import Context\nfrom types import FrameType, GenericAlias\nfrom typing import Any, Literal, TextIO, TypeVar\nfrom typing_extensions import Self, TypeAlias, disjoint_base\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_TaskYieldType: TypeAlias = Future[object] | None\n\n@disjoint_base\nclass Future(Awaitable[_T], Iterable[_T]):\n    _state: str\n    @property\n    def _exception(self) -> BaseException | None: ...\n    _blocking: bool\n    @property\n    def _log_traceback(self) -> bool: ...\n    @_log_traceback.setter\n    def _log_traceback(self, val: Literal[False]) -> None: ...\n    _asyncio_future_blocking: bool  # is a part of duck-typing contract for `Future`\n    def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ...\n    def __del__(self) -> None: ...\n    def get_loop(self) -> AbstractEventLoop: ...\n    @property\n    def _callbacks(self) -> list[tuple[Callable[[Self], Any], Context]]: ...\n    def add_done_callback(self, fn: Callable[[Self], object], /, *, context: Context | None = None) -> None: ...\n    def cancel(self, msg: Any | None = None) -> bool: ...\n    def cancelled(self) -> bool: ...\n    def done(self) -> bool: ...\n    def result(self) -> _T: ...\n    def exception(self) -> BaseException | None: ...\n    def remove_done_callback(self, fn: Callable[[Self], object], /) -> int: ...\n    def set_result(self, result: _T, /) -> None: ...\n    def set_exception(self, exception: type | BaseException, /) -> None: ...\n    def __iter__(self) -> Generator[Any, None, _T]: ...\n    def __await__(self) -> Generator[Any, None, _T]: ...\n    @property\n    def _loop(self) -> AbstractEventLoop: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nif sys.version_info >= (3, 12):\n    _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co]\nelse:\n    _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co]\n\n# mypy and pyright complain that a subclass of an invariant class shouldn't be covariant.\n# While this is true in general, here it's sort-of okay to have a covariant subclass,\n# since the only reason why `asyncio.Future` is invariant is the `set_result()` method,\n# and `asyncio.Task.set_result()` always raises.\n@disjoint_base\nclass Task(Future[_T_co]):  # type: ignore[type-var]  # pyright: ignore[reportInvalidTypeArguments]\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self,\n            coro: _TaskCompatibleCoro[_T_co],\n            *,\n            loop: AbstractEventLoop | None = None,\n            name: str | None = None,\n            context: Context | None = None,\n            eager_start: bool = False,\n        ) -> None: ...\n    elif sys.version_info >= (3, 11):\n        def __init__(\n            self,\n            coro: _TaskCompatibleCoro[_T_co],\n            *,\n            loop: AbstractEventLoop | None = None,\n            name: str | None = None,\n            context: Context | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self, coro: _TaskCompatibleCoro[_T_co], *, loop: AbstractEventLoop | None = None, name: str | None = None\n        ) -> None: ...\n\n    if sys.version_info >= (3, 12):\n        def get_coro(self) -> _TaskCompatibleCoro[_T_co] | None: ...\n    else:\n        def get_coro(self) -> _TaskCompatibleCoro[_T_co]: ...\n\n    def get_name(self) -> str: ...\n    def set_name(self, value: object, /) -> None: ...\n    if sys.version_info >= (3, 12):\n        def get_context(self) -> Context: ...\n\n    def get_stack(self, *, limit: int | None = None) -> list[FrameType]: ...\n    def print_stack(self, *, limit: int | None = None, file: TextIO | None = None) -> None: ...\n    if sys.version_info >= (3, 11):\n        def cancelling(self) -> int: ...\n        def uncancel(self) -> int: ...\n\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\ndef get_event_loop() -> AbstractEventLoop: ...\ndef get_running_loop() -> AbstractEventLoop: ...\ndef _set_running_loop(loop: AbstractEventLoop | None, /) -> None: ...\ndef _get_running_loop() -> AbstractEventLoop: ...\ndef _register_task(task: Task[Any]) -> None: ...\ndef _unregister_task(task: Task[Any]) -> None: ...\ndef _enter_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ...\ndef _leave_task(loop: AbstractEventLoop, task: Task[Any]) -> None: ...\n\nif sys.version_info >= (3, 12):\n    def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: ...\n\nif sys.version_info >= (3, 14):\n    def future_discard_from_awaited_by(future: Future[Any], waiter: Future[Any], /) -> None: ...\n    def future_add_to_awaited_by(future: Future[Any], waiter: Future[Any], /) -> None: ...\n    def all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_bisect.pyi",
    "content": "import sys\nfrom _typeshed import SupportsLenAndGetItem, SupportsRichComparisonT\nfrom collections.abc import Callable, MutableSequence\nfrom typing import TypeVar, overload\n\n_T = TypeVar(\"_T\")\n\nif sys.version_info >= (3, 10):\n    @overload\n    def bisect_left(\n        a: SupportsLenAndGetItem[SupportsRichComparisonT],\n        x: SupportsRichComparisonT,\n        lo: int = 0,\n        hi: int | None = None,\n        *,\n        key: None = None,\n    ) -> int: ...\n    @overload\n    def bisect_left(\n        a: SupportsLenAndGetItem[_T],\n        x: SupportsRichComparisonT,\n        lo: int = 0,\n        hi: int | None = None,\n        *,\n        key: Callable[[_T], SupportsRichComparisonT],\n    ) -> int: ...\n    @overload\n    def bisect_right(\n        a: SupportsLenAndGetItem[SupportsRichComparisonT],\n        x: SupportsRichComparisonT,\n        lo: int = 0,\n        hi: int | None = None,\n        *,\n        key: None = None,\n    ) -> int: ...\n    @overload\n    def bisect_right(\n        a: SupportsLenAndGetItem[_T],\n        x: SupportsRichComparisonT,\n        lo: int = 0,\n        hi: int | None = None,\n        *,\n        key: Callable[[_T], SupportsRichComparisonT],\n    ) -> int: ...\n    @overload\n    def insort_left(\n        a: MutableSequence[SupportsRichComparisonT],\n        x: SupportsRichComparisonT,\n        lo: int = 0,\n        hi: int | None = None,\n        *,\n        key: None = None,\n    ) -> None: ...\n    @overload\n    def insort_left(\n        a: MutableSequence[_T], x: _T, lo: int = 0, hi: int | None = None, *, key: Callable[[_T], SupportsRichComparisonT]\n    ) -> None: ...\n    @overload\n    def insort_right(\n        a: MutableSequence[SupportsRichComparisonT],\n        x: SupportsRichComparisonT,\n        lo: int = 0,\n        hi: int | None = None,\n        *,\n        key: None = None,\n    ) -> None: ...\n    @overload\n    def insort_right(\n        a: MutableSequence[_T], x: _T, lo: int = 0, hi: int | None = None, *, key: Callable[[_T], SupportsRichComparisonT]\n    ) -> None: ...\n\nelse:\n    def bisect_left(\n        a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None\n    ) -> int: ...\n    def bisect_right(\n        a: SupportsLenAndGetItem[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None\n    ) -> int: ...\n    def insort_left(\n        a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None\n    ) -> None: ...\n    def insort_right(\n        a: MutableSequence[SupportsRichComparisonT], x: SupportsRichComparisonT, lo: int = 0, hi: int | None = None\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_blake2.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom typing import ClassVar, Final, final\nfrom typing_extensions import Self\n\nBLAKE2B_MAX_DIGEST_SIZE: Final = 64\nBLAKE2B_MAX_KEY_SIZE: Final = 64\nBLAKE2B_PERSON_SIZE: Final = 16\nBLAKE2B_SALT_SIZE: Final = 16\nBLAKE2S_MAX_DIGEST_SIZE: Final = 32\nBLAKE2S_MAX_KEY_SIZE: Final = 32\nBLAKE2S_PERSON_SIZE: Final = 8\nBLAKE2S_SALT_SIZE: Final = 8\n\n@final\nclass blake2b:\n    MAX_DIGEST_SIZE: ClassVar[int] = 64\n    MAX_KEY_SIZE: ClassVar[int] = 64\n    PERSON_SIZE: ClassVar[int] = 16\n    SALT_SIZE: ClassVar[int] = 16\n    block_size: int\n    digest_size: int\n    name: str\n    if sys.version_info >= (3, 13):\n        def __new__(\n            cls,\n            data: ReadableBuffer = b\"\",\n            *,\n            digest_size: int = 64,\n            key: ReadableBuffer = b\"\",\n            salt: ReadableBuffer = b\"\",\n            person: ReadableBuffer = b\"\",\n            fanout: int = 1,\n            depth: int = 1,\n            leaf_size: int = 0,\n            node_offset: int = 0,\n            node_depth: int = 0,\n            inner_size: int = 0,\n            last_node: bool = False,\n            usedforsecurity: bool = True,\n            string: ReadableBuffer | None = None,\n        ) -> Self: ...\n    else:\n        def __new__(\n            cls,\n            data: ReadableBuffer = b\"\",\n            /,\n            *,\n            digest_size: int = 64,\n            key: ReadableBuffer = b\"\",\n            salt: ReadableBuffer = b\"\",\n            person: ReadableBuffer = b\"\",\n            fanout: int = 1,\n            depth: int = 1,\n            leaf_size: int = 0,\n            node_offset: int = 0,\n            node_depth: int = 0,\n            inner_size: int = 0,\n            last_node: bool = False,\n            usedforsecurity: bool = True,\n        ) -> Self: ...\n\n    def copy(self) -> Self: ...\n    def digest(self) -> bytes: ...\n    def hexdigest(self) -> str: ...\n    def update(self, data: ReadableBuffer, /) -> None: ...\n\n@final\nclass blake2s:\n    MAX_DIGEST_SIZE: ClassVar[int] = 32\n    MAX_KEY_SIZE: ClassVar[int] = 32\n    PERSON_SIZE: ClassVar[int] = 8\n    SALT_SIZE: ClassVar[int] = 8\n    block_size: int\n    digest_size: int\n    name: str\n    if sys.version_info >= (3, 13):\n        def __new__(\n            cls,\n            data: ReadableBuffer = b\"\",\n            *,\n            digest_size: int = 32,\n            key: ReadableBuffer = b\"\",\n            salt: ReadableBuffer = b\"\",\n            person: ReadableBuffer = b\"\",\n            fanout: int = 1,\n            depth: int = 1,\n            leaf_size: int = 0,\n            node_offset: int = 0,\n            node_depth: int = 0,\n            inner_size: int = 0,\n            last_node: bool = False,\n            usedforsecurity: bool = True,\n            string: ReadableBuffer | None = None,\n        ) -> Self: ...\n    else:\n        def __new__(\n            cls,\n            data: ReadableBuffer = b\"\",\n            /,\n            *,\n            digest_size: int = 32,\n            key: ReadableBuffer = b\"\",\n            salt: ReadableBuffer = b\"\",\n            person: ReadableBuffer = b\"\",\n            fanout: int = 1,\n            depth: int = 1,\n            leaf_size: int = 0,\n            node_offset: int = 0,\n            node_depth: int = 0,\n            inner_size: int = 0,\n            last_node: bool = False,\n            usedforsecurity: bool = True,\n        ) -> Self: ...\n\n    def copy(self) -> Self: ...\n    def digest(self) -> bytes: ...\n    def hexdigest(self) -> str: ...\n    def update(self, data: ReadableBuffer, /) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_bootlocale.pyi",
    "content": "def getpreferredencoding(do_setlocale: bool = True) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_bz2.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom typing import final\nfrom typing_extensions import Self\n\n@final\nclass BZ2Compressor:\n    if sys.version_info >= (3, 12):\n        def __new__(cls, compresslevel: int = 9, /) -> Self: ...\n    else:\n        def __init__(self, compresslevel: int = 9, /) -> None: ...\n\n    def compress(self, data: ReadableBuffer, /) -> bytes: ...\n    def flush(self) -> bytes: ...\n\n@final\nclass BZ2Decompressor:\n    def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: ...\n    @property\n    def eof(self) -> bool: ...\n    @property\n    def needs_input(self) -> bool: ...\n    @property\n    def unused_data(self) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_codecs.pyi",
    "content": "import codecs\nimport sys\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Callable\nfrom typing import Literal, final, overload, type_check_only\nfrom typing_extensions import TypeAlias\n\n# This type is not exposed; it is defined in unicodeobject.c\n# At runtime it calls itself builtins.EncodingMap\n@final\n@type_check_only\nclass _EncodingMap:\n    def size(self) -> int: ...\n\n_CharMap: TypeAlias = dict[int, int] | _EncodingMap\n_Handler: TypeAlias = Callable[[UnicodeError], tuple[str | bytes, int]]\n_SearchFunction: TypeAlias = Callable[[str], codecs.CodecInfo | None]\n\ndef register(search_function: _SearchFunction, /) -> None: ...\n\nif sys.version_info >= (3, 10):\n    def unregister(search_function: _SearchFunction, /) -> None: ...\n\ndef register_error(errors: str, handler: _Handler, /) -> None: ...\ndef lookup_error(name: str, /) -> _Handler: ...\n\n# The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300\n# https://docs.python.org/3/library/codecs.html#binary-transforms\n_BytesToBytesEncoding: TypeAlias = Literal[\n    \"base64\",\n    \"base_64\",\n    \"base64_codec\",\n    \"bz2\",\n    \"bz2_codec\",\n    \"hex\",\n    \"hex_codec\",\n    \"quopri\",\n    \"quotedprintable\",\n    \"quoted_printable\",\n    \"quopri_codec\",\n    \"uu\",\n    \"uu_codec\",\n    \"zip\",\n    \"zlib\",\n    \"zlib_codec\",\n]\n# https://docs.python.org/3/library/codecs.html#text-transforms\n_StrToStrEncoding: TypeAlias = Literal[\"rot13\", \"rot_13\"]\n\n@overload\ndef encode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = \"strict\") -> bytes: ...\n@overload\ndef encode(obj: str, encoding: _StrToStrEncoding, errors: str = \"strict\") -> str: ...  # type: ignore[overload-overlap]\n@overload\ndef encode(obj: str, encoding: str = \"utf-8\", errors: str = \"strict\") -> bytes: ...\n@overload\ndef decode(obj: ReadableBuffer, encoding: _BytesToBytesEncoding, errors: str = \"strict\") -> bytes: ...  # type: ignore[overload-overlap]\n@overload\ndef decode(obj: str, encoding: _StrToStrEncoding, errors: str = \"strict\") -> str: ...\n\n# these are documented as text encodings but in practice they also accept str as input\n@overload\ndef decode(\n    obj: str,\n    encoding: Literal[\"unicode_escape\", \"unicode-escape\", \"raw_unicode_escape\", \"raw-unicode-escape\"],\n    errors: str = \"strict\",\n) -> str: ...\n\n# hex is officially documented as a bytes to bytes encoding, but it appears to also work with str\n@overload\ndef decode(obj: str, encoding: Literal[\"hex\", \"hex_codec\"], errors: str = \"strict\") -> bytes: ...\n@overload\ndef decode(obj: ReadableBuffer, encoding: str = \"utf-8\", errors: str = \"strict\") -> str: ...\ndef lookup(encoding: str, /) -> codecs.CodecInfo: ...\ndef charmap_build(map: str, /) -> _CharMap: ...\ndef ascii_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...\ndef ascii_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef charmap_decode(data: ReadableBuffer, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[str, int]: ...\ndef charmap_encode(str: str, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[bytes, int]: ...\ndef escape_decode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...\ndef escape_encode(data: bytes, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef latin_1_decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...\ndef latin_1_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef raw_unicode_escape_decode(\n    data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /\n) -> tuple[str, int]: ...\ndef raw_unicode_escape_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef readbuffer_encode(data: str | ReadableBuffer, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef unicode_escape_decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ...\ndef unicode_escape_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef utf_16_be_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\ndef utf_16_be_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef utf_16_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\ndef utf_16_encode(str: str, errors: str | None = None, byteorder: int = 0, /) -> tuple[bytes, int]: ...\ndef utf_16_ex_decode(\n    data: ReadableBuffer, errors: str | None = None, byteorder: int = 0, final: bool = False, /\n) -> tuple[str, int, int]: ...\ndef utf_16_le_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\ndef utf_16_le_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef utf_32_be_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\ndef utf_32_be_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef utf_32_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\ndef utf_32_encode(str: str, errors: str | None = None, byteorder: int = 0, /) -> tuple[bytes, int]: ...\ndef utf_32_ex_decode(\n    data: ReadableBuffer, errors: str | None = None, byteorder: int = 0, final: bool = False, /\n) -> tuple[str, int, int]: ...\ndef utf_32_le_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\ndef utf_32_le_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef utf_7_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\ndef utf_7_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\ndef utf_8_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\ndef utf_8_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n\nif sys.platform == \"win32\":\n    def mbcs_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n    def mbcs_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n    def code_page_decode(\n        codepage: int, data: ReadableBuffer, errors: str | None = None, final: bool = False, /\n    ) -> tuple[str, int]: ...\n    def code_page_encode(code_page: int, str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n    def oem_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n    def oem_encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_collections_abc.pyi",
    "content": "import sys\nfrom abc import abstractmethod\nfrom types import MappingProxyType\nfrom typing import (  # noqa: Y022,Y038,UP035,Y057,RUF100\n    AbstractSet as Set,\n    AsyncGenerator as AsyncGenerator,\n    AsyncIterable as AsyncIterable,\n    AsyncIterator as AsyncIterator,\n    Awaitable as Awaitable,\n    ByteString as ByteString,\n    Callable as Callable,\n    ClassVar,\n    Collection as Collection,\n    Container as Container,\n    Coroutine as Coroutine,\n    Generator as Generator,\n    Generic,\n    Hashable as Hashable,\n    ItemsView as ItemsView,\n    Iterable as Iterable,\n    Iterator as Iterator,\n    KeysView as KeysView,\n    Mapping as Mapping,\n    MappingView as MappingView,\n    MutableMapping as MutableMapping,\n    MutableSequence as MutableSequence,\n    MutableSet as MutableSet,\n    Protocol,\n    Reversible as Reversible,\n    Sequence as Sequence,\n    Sized as Sized,\n    TypeVar,\n    ValuesView as ValuesView,\n    final,\n    runtime_checkable,\n)\n\n__all__ = [\n    \"Awaitable\",\n    \"Coroutine\",\n    \"AsyncIterable\",\n    \"AsyncIterator\",\n    \"AsyncGenerator\",\n    \"Hashable\",\n    \"Iterable\",\n    \"Iterator\",\n    \"Generator\",\n    \"Reversible\",\n    \"Sized\",\n    \"Container\",\n    \"Callable\",\n    \"Collection\",\n    \"Set\",\n    \"MutableSet\",\n    \"Mapping\",\n    \"MutableMapping\",\n    \"MappingView\",\n    \"KeysView\",\n    \"ItemsView\",\n    \"ValuesView\",\n    \"Sequence\",\n    \"MutableSequence\",\n    \"ByteString\",\n]\nif sys.version_info >= (3, 12):\n    __all__ += [\"Buffer\"]\n\n_KT_co = TypeVar(\"_KT_co\", covariant=True)  # Key type covariant containers.\n_VT_co = TypeVar(\"_VT_co\", covariant=True)  # Value type covariant containers.\n\n@final\nclass dict_keys(KeysView[_KT_co], Generic[_KT_co, _VT_co]):  # undocumented\n    def __eq__(self, value: object, /) -> bool: ...\n    def __reversed__(self) -> Iterator[_KT_co]: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    if sys.version_info >= (3, 13):\n        def isdisjoint(self, other: Iterable[_KT_co], /) -> bool: ...\n    if sys.version_info >= (3, 10):\n        @property\n        def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ...\n\n@final\nclass dict_values(ValuesView[_VT_co], Generic[_KT_co, _VT_co]):  # undocumented\n    def __reversed__(self) -> Iterator[_VT_co]: ...\n    if sys.version_info >= (3, 10):\n        @property\n        def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ...\n\n@final\nclass dict_items(ItemsView[_KT_co, _VT_co]):  # undocumented\n    def __eq__(self, value: object, /) -> bool: ...\n    def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    if sys.version_info >= (3, 13):\n        def isdisjoint(self, other: Iterable[tuple[_KT_co, _VT_co]], /) -> bool: ...\n    if sys.version_info >= (3, 10):\n        @property\n        def mapping(self) -> MappingProxyType[_KT_co, _VT_co]: ...\n\nif sys.version_info >= (3, 12):\n    @runtime_checkable\n    class Buffer(Protocol):\n        __slots__ = ()\n        @abstractmethod\n        def __buffer__(self, flags: int, /) -> memoryview: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_compat_pickle.pyi",
    "content": "from typing import Final\n\nIMPORT_MAPPING: Final[dict[str, str]]\nNAME_MAPPING: Final[dict[tuple[str, str], tuple[str, str]]]\nPYTHON2_EXCEPTIONS: Final[tuple[str, ...]]\nMULTIPROCESSING_EXCEPTIONS: Final[tuple[str, ...]]\nREVERSE_IMPORT_MAPPING: Final[dict[str, str]]\nREVERSE_NAME_MAPPING: Final[dict[tuple[str, str], tuple[str, str]]]\nPYTHON3_OSERROR_EXCEPTIONS: Final[tuple[str, ...]]\nPYTHON3_IMPORTERROR_EXCEPTIONS: Final[tuple[str, ...]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_compression.pyi",
    "content": "# _compression is replaced by compression._common._streams on Python 3.14+ (PEP-784)\n\nfrom _typeshed import ReadableBuffer, WriteableBuffer\nfrom collections.abc import Callable\nfrom io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase\nfrom typing import Any, Protocol, type_check_only\n\nBUFFER_SIZE = DEFAULT_BUFFER_SIZE\n\n@type_check_only\nclass _Reader(Protocol):\n    def read(self, n: int, /) -> bytes: ...\n    def seekable(self) -> bool: ...\n    def seek(self, n: int, /) -> Any: ...\n\n@type_check_only\nclass _Decompressor(Protocol):\n    def decompress(self, data: ReadableBuffer, /, max_length: int = ...) -> bytes: ...\n    @property\n    def unused_data(self) -> bytes: ...\n    @property\n    def eof(self) -> bool: ...\n    # `zlib._Decompress` does not have next property, but `DecompressReader` calls it:\n    # @property\n    # def needs_input(self) -> bool: ...\n\nclass BaseStream(BufferedIOBase): ...\n\nclass DecompressReader(RawIOBase):\n    def __init__(\n        self,\n        fp: _Reader,\n        decomp_factory: Callable[..., _Decompressor],\n        trailing_error: type[Exception] | tuple[type[Exception], ...] = (),\n        **decomp_args: Any,  # These are passed to decomp_factory.\n    ) -> None: ...\n    def readinto(self, b: WriteableBuffer) -> int: ...\n    def read(self, size: int = -1) -> bytes: ...\n    def seek(self, offset: int, whence: int = 0) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_contextvars.pyi",
    "content": "import sys\nfrom collections.abc import Callable, Iterator, Mapping\nfrom types import GenericAlias, TracebackType\nfrom typing import Any, ClassVar, Generic, TypeVar, final, overload\nfrom typing_extensions import ParamSpec, Self\n\n_T = TypeVar(\"_T\")\n_D = TypeVar(\"_D\")\n_P = ParamSpec(\"_P\")\n\n@final\nclass ContextVar(Generic[_T]):\n    @overload\n    def __new__(cls, name: str) -> Self: ...\n    @overload\n    def __new__(cls, name: str, *, default: _T) -> Self: ...\n    def __hash__(self) -> int: ...\n    @property\n    def name(self) -> str: ...\n    @overload\n    def get(self) -> _T: ...\n    @overload\n    def get(self, default: _T, /) -> _T: ...\n    @overload\n    def get(self, default: _D, /) -> _D | _T: ...\n    def set(self, value: _T, /) -> Token[_T]: ...\n    def reset(self, token: Token[_T], /) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@final\nclass Token(Generic[_T]):\n    @property\n    def var(self) -> ContextVar[_T]: ...\n    @property\n    def old_value(self) -> Any: ...  # returns either _T or MISSING, but that's hard to express\n    MISSING: ClassVar[object]\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n    if sys.version_info >= (3, 14):\n        def __enter__(self) -> Self: ...\n        def __exit__(\n            self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /\n        ) -> None: ...\n\ndef copy_context() -> Context: ...\n\n# It doesn't make sense to make this generic, because for most Contexts each ContextVar will have\n# a different value.\n@final\nclass Context(Mapping[ContextVar[Any], Any]):\n    def __init__(self) -> None: ...\n    @overload\n    def get(self, key: ContextVar[_T], default: None = None, /) -> _T | None: ...\n    @overload\n    def get(self, key: ContextVar[_T], default: _T, /) -> _T: ...\n    @overload\n    def get(self, key: ContextVar[_T], default: _D, /) -> _T | _D: ...\n    def run(self, callable: Callable[_P, _T], *args: _P.args, **kwargs: _P.kwargs) -> _T: ...\n    def copy(self) -> Context: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __getitem__(self, key: ContextVar[_T], /) -> _T: ...\n    def __iter__(self) -> Iterator[ContextVar[Any]]: ...\n    def __len__(self) -> int: ...\n    def __eq__(self, value: object, /) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_csv.pyi",
    "content": "import csv\nimport sys\nfrom _typeshed import SupportsWrite\nfrom collections.abc import Iterable\nfrom typing import Any, Final, Literal, type_check_only\nfrom typing_extensions import Self, TypeAlias, disjoint_base\n\n__version__: Final[str]\n\nQUOTE_ALL: Final = 1\nQUOTE_MINIMAL: Final = 0\nQUOTE_NONE: Final = 3\nQUOTE_NONNUMERIC: Final = 2\nif sys.version_info >= (3, 12):\n    QUOTE_STRINGS: Final = 4\n    QUOTE_NOTNULL: Final = 5\n\nif sys.version_info >= (3, 12):\n    _QuotingType: TypeAlias = Literal[0, 1, 2, 3, 4, 5]\nelse:\n    _QuotingType: TypeAlias = Literal[0, 1, 2, 3]\n\nclass Error(Exception): ...\n\n_DialectLike: TypeAlias = str | Dialect | csv.Dialect | type[Dialect | csv.Dialect]\n\n@disjoint_base\nclass Dialect:\n    delimiter: str\n    quotechar: str | None\n    escapechar: str | None\n    doublequote: bool\n    skipinitialspace: bool\n    lineterminator: str\n    quoting: _QuotingType\n    strict: bool\n    def __new__(\n        cls,\n        dialect: _DialectLike | None = None,\n        delimiter: str = \",\",\n        doublequote: bool = True,\n        escapechar: str | None = None,\n        lineterminator: str = \"\\r\\n\",\n        quotechar: str | None = '\"',\n        quoting: _QuotingType = 0,\n        skipinitialspace: bool = False,\n        strict: bool = False,\n    ) -> Self: ...\n\nif sys.version_info >= (3, 10):\n    # This class calls itself _csv.reader.\n    @disjoint_base\n    class Reader:\n        @property\n        def dialect(self) -> Dialect: ...\n        line_num: int\n        def __iter__(self) -> Self: ...\n        def __next__(self) -> list[str]: ...\n\n    # This class calls itself _csv.writer.\n    @disjoint_base\n    class Writer:\n        @property\n        def dialect(self) -> Dialect: ...\n        if sys.version_info >= (3, 13):\n            def writerow(self, row: Iterable[Any], /) -> Any: ...\n            def writerows(self, rows: Iterable[Iterable[Any]], /) -> None: ...\n        else:\n            def writerow(self, row: Iterable[Any]) -> Any: ...\n            def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ...\n\n    # For the return types below.\n    # These aliases can be removed when typeshed drops support for 3.9.\n    _reader = Reader\n    _writer = Writer\nelse:\n    # This class is not exposed. It calls itself _csv.reader.\n    @type_check_only\n    class _reader:\n        @property\n        def dialect(self) -> Dialect: ...\n        line_num: int\n        def __iter__(self) -> Self: ...\n        def __next__(self) -> list[str]: ...\n\n    # This class is not exposed. It calls itself _csv.writer.\n    @type_check_only\n    class _writer:\n        @property\n        def dialect(self) -> Dialect: ...\n        def writerow(self, row: Iterable[Any]) -> Any: ...\n        def writerows(self, rows: Iterable[Iterable[Any]]) -> None: ...\n\ndef writer(\n    fileobj: SupportsWrite[str],\n    /,\n    dialect: _DialectLike = \"excel\",\n    *,\n    delimiter: str = \",\",\n    quotechar: str | None = '\"',\n    escapechar: str | None = None,\n    doublequote: bool = True,\n    skipinitialspace: bool = False,\n    lineterminator: str = \"\\r\\n\",\n    quoting: _QuotingType = 0,\n    strict: bool = False,\n) -> _writer: ...\ndef reader(\n    iterable: Iterable[str],\n    /,\n    dialect: _DialectLike = \"excel\",\n    *,\n    delimiter: str = \",\",\n    quotechar: str | None = '\"',\n    escapechar: str | None = None,\n    doublequote: bool = True,\n    skipinitialspace: bool = False,\n    lineterminator: str = \"\\r\\n\",\n    quoting: _QuotingType = 0,\n    strict: bool = False,\n) -> _reader: ...\ndef register_dialect(\n    name: str,\n    /,\n    dialect: type[Dialect | csv.Dialect] | str = \"excel\",\n    *,\n    delimiter: str = \",\",\n    quotechar: str | None = '\"',\n    escapechar: str | None = None,\n    doublequote: bool = True,\n    skipinitialspace: bool = False,\n    lineterminator: str = \"\\r\\n\",\n    quoting: _QuotingType = 0,\n    strict: bool = False,\n) -> None: ...\ndef unregister_dialect(name: str) -> None: ...\ndef get_dialect(name: str) -> Dialect: ...\ndef list_dialects() -> list[str]: ...\ndef field_size_limit(new_limit: int = ...) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_ctypes.pyi",
    "content": "import _typeshed\nimport builtins\nimport sys\nfrom _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer\nfrom abc import abstractmethod\nfrom collections.abc import Callable, Iterable, Iterator, Mapping, Sequence\nfrom ctypes import CDLL, ArgumentError as ArgumentError, c_void_p\nfrom types import GenericAlias\nfrom typing import Any, ClassVar, Final, Generic, Literal, SupportsIndex, TypeVar, final, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\n_T = TypeVar(\"_T\")\n_CT = TypeVar(\"_CT\", bound=_CData)\n\nFUNCFLAG_CDECL: Final = 0x1\nFUNCFLAG_PYTHONAPI: Final = 0x4\nFUNCFLAG_USE_ERRNO: Final = 0x8\nFUNCFLAG_USE_LASTERROR: Final = 0x10\nRTLD_GLOBAL: Final[int]\nRTLD_LOCAL: Final[int]\n\nif sys.version_info >= (3, 11):\n    CTYPES_MAX_ARGCOUNT: Final[int]\n\nif sys.version_info >= (3, 12):\n    SIZEOF_TIME_T: Final[int]\n\nif sys.platform == \"win32\":\n    # Description, Source, HelpFile, HelpContext, scode\n    _COMError_Details: TypeAlias = tuple[str | None, str | None, str | None, int | None, int | None]\n\n    class COMError(Exception):\n        hresult: int\n        text: str | None\n        details: _COMError_Details\n\n        def __init__(self, hresult: int, text: str | None, details: _COMError_Details) -> None: ...\n\n    def CopyComPointer(src: _PointerLike, dst: _PointerLike | _CArgObject) -> int: ...\n\n    FUNCFLAG_HRESULT: Final = 0x2\n    FUNCFLAG_STDCALL: Final = 0x0\n\n    def FormatError(code: int = ...) -> str: ...\n    def get_last_error() -> int: ...\n    def set_last_error(value: int) -> int: ...\n    def LoadLibrary(name: str, load_flags: int = 0, /) -> int: ...\n    def FreeLibrary(handle: int, /) -> None: ...\n\nelse:\n    def dlclose(handle: int, /) -> None: ...\n    # The default for flag is RTLD_GLOBAL|RTLD_LOCAL, which is platform dependent.\n    def dlopen(name: StrOrBytesPath, flag: int = ..., /) -> int: ...\n    def dlsym(handle: int, name: str, /) -> int: ...\n\nif sys.version_info >= (3, 13):\n    # This class is not exposed. It calls itself _ctypes.CType_Type.\n    @type_check_only\n    class _CType_Type(type):\n        # By default mypy complains about the following two methods, because strictly speaking cls\n        # might not be a Type[_CT]. However this doesn't happen because this is only a\n        # metaclass for subclasses of _CData.\n        def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n        def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n\n    _CTypeBaseType = _CType_Type\n\nelse:\n    _CTypeBaseType = type\n\n# This class is not exposed.\n@type_check_only\nclass _CData:\n    _b_base_: int\n    _b_needsfree_: bool\n    _objects: Mapping[Any, int] | None\n    def __buffer__(self, flags: int, /) -> memoryview: ...\n    def __ctypes_from_outparam__(self, /) -> Self: ...\n    if sys.version_info >= (3, 14):\n        __pointer_type__: type\n\n# this is a union of all the subclasses of _CData, which is useful because of\n# the methods that are present on each of those subclasses which are not present\n# on _CData itself.\n_CDataType: TypeAlias = _SimpleCData[Any] | _Pointer[Any] | CFuncPtr | Union | Structure | Array[Any]\n\n# This class is not exposed. It calls itself _ctypes.PyCSimpleType.\n@type_check_only\nclass _PyCSimpleType(_CTypeBaseType):\n    def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ...\n    def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ...\n    def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ...\n    if sys.version_info < (3, 13):\n        # Inherited from CType_Type starting on 3.13\n        def __mul__(self: type[_CT], value: int, /) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n        def __rmul__(self: type[_CT], value: int, /) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n\nclass _SimpleCData(_CData, Generic[_T], metaclass=_PyCSimpleType):\n    value: _T\n    # The TypeVar can be unsolved here,\n    # but we can't use overloads without creating many, many mypy false-positive errors\n    def __init__(self, value: _T = ...) -> None: ...  # pyright: ignore[reportInvalidTypeVarUse]\n    def __ctypes_from_outparam__(self, /) -> _T: ...  # type: ignore[override]\n\n@type_check_only\nclass _CanCastTo(_CData): ...\n\n@type_check_only\nclass _PointerLike(_CanCastTo): ...\n\n# This type is not exposed. It calls itself _ctypes.PyCPointerType.\n@type_check_only\nclass _PyCPointerType(_CTypeBaseType):\n    def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ...\n    def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ...\n    def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ...\n    def set_type(self, type: _CTypeBaseType, /) -> None: ...\n    if sys.version_info < (3, 13):\n        # Inherited from CType_Type starting on 3.13\n        def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n        def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n\nclass _Pointer(_PointerLike, _CData, Generic[_CT], metaclass=_PyCPointerType):\n    _type_: type[_CT]\n    contents: _CT\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, arg: _CT) -> None: ...\n    @overload\n    def __getitem__(self, key: int, /) -> Any: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Any]: ...\n    def __setitem__(self, key: int, value: Any, /) -> None: ...\n\nif sys.version_info < (3, 14):\n    @overload\n    def POINTER(type: None, /) -> type[c_void_p]: ...\n    @overload\n    def POINTER(type: type[_CT], /) -> type[_Pointer[_CT]]: ...\n    def pointer(obj: _CT, /) -> _Pointer[_CT]: ...\n\n# This class is not exposed. It calls itself _ctypes.CArgObject.\n@final\n@type_check_only\nclass _CArgObject: ...\n\nif sys.version_info >= (3, 14):\n    def byref(obj: _CData | _CDataType, offset: int = 0, /) -> _CArgObject: ...\n\nelse:\n    def byref(obj: _CData | _CDataType, offset: int = 0) -> _CArgObject: ...\n\n_ECT: TypeAlias = Callable[[_CData | _CDataType | None, CFuncPtr, tuple[_CData | _CDataType, ...]], _CDataType]\n_PF: TypeAlias = tuple[int] | tuple[int, str | None] | tuple[int, str | None, Any]\n\n# This class is not exposed. It calls itself _ctypes.PyCFuncPtrType.\n@type_check_only\nclass _PyCFuncPtrType(_CTypeBaseType):\n    def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ...\n    def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ...\n    def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ...\n    if sys.version_info < (3, 13):\n        # Inherited from CType_Type starting on 3.13\n        def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n        def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n\nclass CFuncPtr(_PointerLike, _CData, metaclass=_PyCFuncPtrType):\n    restype: type[_CDataType] | Callable[[int], Any] | None\n    argtypes: Sequence[type[_CDataType]]\n    errcheck: _ECT\n    # Abstract attribute that must be defined on subclasses\n    _flags_: ClassVar[int]\n    @overload\n    def __new__(cls) -> Self: ...\n    @overload\n    def __new__(cls, address: int, /) -> Self: ...\n    @overload\n    def __new__(cls, callable: Callable[..., Any], /) -> Self: ...\n    @overload\n    def __new__(cls, func_spec: tuple[str | int, CDLL], paramflags: tuple[_PF, ...] | None = ..., /) -> Self: ...\n    if sys.platform == \"win32\":\n        @overload\n        def __new__(\n            cls, vtbl_index: int, name: str, paramflags: tuple[_PF, ...] | None = ..., iid: _CData | _CDataType | None = ..., /\n        ) -> Self: ...\n\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n\n_GetT = TypeVar(\"_GetT\")\n_SetT = TypeVar(\"_SetT\")\n\nif sys.version_info >= (3, 14):\n    @final\n    class CField(Generic[_CT, _GetT, _SetT]):\n        offset: int\n        size: int\n        name: str\n        type: builtins.type[_CT]\n        byte_offset: int\n        byte_size: int\n        is_bitfield: bool\n        bit_offset: int\n        bit_size: int\n        is_anonymous: bool\n        @overload\n        def __get__(self, instance: None, owner: builtins.type[Any] | None = None, /) -> Self: ...\n        @overload\n        def __get__(self, instance: Any, owner: builtins.type[Any] | None = None, /) -> _GetT: ...\n        def __set__(self, instance: Any, value: _SetT, /) -> None: ...\n\n    _CField = CField\n\nelse:\n    @final\n    @type_check_only\n    class _CField(Generic[_CT, _GetT, _SetT]):\n        offset: int\n        size: int\n        if sys.version_info >= (3, 10):\n            @overload\n            def __get__(self, instance: None, owner: type[Any] | None = None, /) -> Self: ...\n            @overload\n            def __get__(self, instance: Any, owner: type[Any] | None = None, /) -> _GetT: ...\n        else:\n            @overload\n            def __get__(self, instance: None, owner: type[Any] | None, /) -> Self: ...\n            @overload\n            def __get__(self, instance: Any, owner: type[Any] | None, /) -> _GetT: ...\n\n        def __set__(self, instance: Any, value: _SetT, /) -> None: ...\n\n# This class is not exposed. It calls itself _ctypes.UnionType.\n@type_check_only\nclass _UnionType(_CTypeBaseType):\n    def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ...\n    def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ...\n    def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ...\n    # At runtime, various attributes are created on a Union subclass based\n    # on its _fields_. This method doesn't exist, but represents those\n    # dynamically created attributes.\n    def __getattr__(self, name: str) -> _CField[Any, Any, Any]: ...\n    if sys.version_info < (3, 13):\n        # Inherited from CType_Type starting on 3.13\n        def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n        def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n\nclass Union(_CData, metaclass=_UnionType):\n    _fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]]\n    _pack_: ClassVar[int]\n    _anonymous_: ClassVar[Sequence[str]]\n    if sys.version_info >= (3, 13):\n        _align_: ClassVar[int]\n\n    def __init__(self, *args: Any, **kw: Any) -> None: ...\n    def __getattr__(self, name: str) -> Any: ...\n    def __setattr__(self, name: str, value: Any) -> None: ...\n\n# This class is not exposed. It calls itself _ctypes.PyCStructType.\n@type_check_only\nclass _PyCStructType(_CTypeBaseType):\n    def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ...\n    def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ...\n    def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ...\n    # At runtime, various attributes are created on a Structure subclass based\n    # on its _fields_. This method doesn't exist, but represents those\n    # dynamically created attributes.\n    def __getattr__(self, name: str) -> _CField[Any, Any, Any]: ...\n    if sys.version_info < (3, 13):\n        # Inherited from CType_Type starting on 3.13\n        def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n        def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n\nclass Structure(_CData, metaclass=_PyCStructType):\n    _fields_: ClassVar[Sequence[tuple[str, type[_CDataType]] | tuple[str, type[_CDataType], int]]]\n    _pack_: ClassVar[int]\n    _anonymous_: ClassVar[Sequence[str]]\n    if sys.version_info >= (3, 13):\n        _align_: ClassVar[int]\n\n    if sys.version_info >= (3, 14):\n        # _layout_ can be defined by the user, but is not always present.\n        _layout_: ClassVar[Literal[\"ms\", \"gcc-sysv\"]]\n\n    def __init__(self, *args: Any, **kw: Any) -> None: ...\n    def __getattr__(self, name: str) -> Any: ...\n    def __setattr__(self, name: str, value: Any) -> None: ...\n\n# This class is not exposed. It calls itself _ctypes.PyCArrayType.\n@type_check_only\nclass _PyCArrayType(_CTypeBaseType):\n    def from_address(self: type[_typeshed.Self], value: int, /) -> _typeshed.Self: ...\n    def from_buffer(self: type[_typeshed.Self], obj: WriteableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_buffer_copy(self: type[_typeshed.Self], buffer: ReadableBuffer, offset: int = 0, /) -> _typeshed.Self: ...\n    def from_param(self: type[_typeshed.Self], value: Any, /) -> _typeshed.Self | _CArgObject: ...\n    def in_dll(self: type[_typeshed.Self], dll: CDLL, name: str, /) -> _typeshed.Self: ...\n    if sys.version_info < (3, 13):\n        # Inherited from CType_Type starting on 3.13\n        def __mul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n        def __rmul__(cls: type[_CT], other: int) -> type[Array[_CT]]: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]\n\nclass Array(_CData, Generic[_CT], metaclass=_PyCArrayType):\n    @property\n    @abstractmethod\n    def _length_(self) -> int: ...\n    @_length_.setter\n    def _length_(self, value: int) -> None: ...\n    @property\n    @abstractmethod\n    def _type_(self) -> type[_CT]: ...\n    @_type_.setter\n    def _type_(self, value: type[_CT]) -> None: ...\n    raw: bytes  # Note: only available if _CT == c_char\n    value: Any  # Note: bytes if _CT == c_char, str if _CT == c_wchar, unavailable otherwise\n    # TODO: These methods cannot be annotated correctly at the moment.\n    # All of these \"Any\"s stand for the array's element type, but it's not possible to use _CT\n    # here, because of a special feature of ctypes.\n    # By default, when accessing an element of an Array[_CT], the returned object has type _CT.\n    # However, when _CT is a \"simple type\" like c_int, ctypes automatically \"unboxes\" the object\n    # and converts it to the corresponding Python primitive. For example, when accessing an element\n    # of an Array[c_int], a Python int object is returned, not a c_int.\n    # This behavior does *not* apply to subclasses of \"simple types\".\n    # If MyInt is a subclass of c_int, then accessing an element of an Array[MyInt] returns\n    # a MyInt, not an int.\n    # This special behavior is not easy to model in a stub, so for now all places where\n    # the array element type would belong are annotated with Any instead.\n    def __init__(self, *args: Any) -> None: ...\n    @overload\n    def __getitem__(self, key: int, /) -> Any: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Any]: ...\n    @overload\n    def __setitem__(self, key: int, value: Any, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[Any], /) -> None: ...\n    def __iter__(self) -> Iterator[Any]: ...\n    # Can't inherit from Sized because the metaclass conflict between\n    # Sized and _CData prevents using _CDataMeta.\n    def __len__(self) -> int: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\ndef addressof(obj: _CData | _CDataType, /) -> int: ...\ndef alignment(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> int: ...\ndef get_errno() -> int: ...\ndef resize(obj: _CData | _CDataType, size: int, /) -> None: ...\ndef set_errno(value: int, /) -> int: ...\ndef sizeof(obj_or_type: _CData | _CDataType | type[_CData | _CDataType], /) -> int: ...\ndef PyObj_FromPtr(address: int, /) -> Any: ...\ndef Py_DECREF(o: _T, /) -> _T: ...\ndef Py_INCREF(o: _T, /) -> _T: ...\ndef buffer_info(o: _CData | _CDataType | type[_CData | _CDataType], /) -> tuple[str, int, tuple[int, ...]]: ...\ndef call_cdeclfunction(address: int, arguments: tuple[Any, ...], /) -> Any: ...\ndef call_function(address: int, arguments: tuple[Any, ...], /) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_curses.pyi",
    "content": "import sys\nfrom _typeshed import ReadOnlyBuffer, SupportsRead, SupportsWrite\nfrom curses import _ncurses_version\nfrom typing import Any, Final, final, overload\nfrom typing_extensions import TypeAlias\n\n# NOTE: This module is ordinarily only available on Unix, but the windows-curses\n# package makes it available on Windows as well with the same contents.\n\n# Handled by PyCurses_ConvertToChtype in _cursesmodule.c.\n_ChType: TypeAlias = str | bytes | int\n\n# ACS codes are only initialized after initscr is called\nACS_BBSS: Final[int]\nACS_BLOCK: Final[int]\nACS_BOARD: Final[int]\nACS_BSBS: Final[int]\nACS_BSSB: Final[int]\nACS_BSSS: Final[int]\nACS_BTEE: Final[int]\nACS_BULLET: Final[int]\nACS_CKBOARD: Final[int]\nACS_DARROW: Final[int]\nACS_DEGREE: Final[int]\nACS_DIAMOND: Final[int]\nACS_GEQUAL: Final[int]\nACS_HLINE: Final[int]\nACS_LANTERN: Final[int]\nACS_LARROW: Final[int]\nACS_LEQUAL: Final[int]\nACS_LLCORNER: Final[int]\nACS_LRCORNER: Final[int]\nACS_LTEE: Final[int]\nACS_NEQUAL: Final[int]\nACS_PI: Final[int]\nACS_PLMINUS: Final[int]\nACS_PLUS: Final[int]\nACS_RARROW: Final[int]\nACS_RTEE: Final[int]\nACS_S1: Final[int]\nACS_S3: Final[int]\nACS_S7: Final[int]\nACS_S9: Final[int]\nACS_SBBS: Final[int]\nACS_SBSB: Final[int]\nACS_SBSS: Final[int]\nACS_SSBB: Final[int]\nACS_SSBS: Final[int]\nACS_SSSB: Final[int]\nACS_SSSS: Final[int]\nACS_STERLING: Final[int]\nACS_TTEE: Final[int]\nACS_UARROW: Final[int]\nACS_ULCORNER: Final[int]\nACS_URCORNER: Final[int]\nACS_VLINE: Final[int]\nALL_MOUSE_EVENTS: Final[int]\nA_ALTCHARSET: Final[int]\nA_ATTRIBUTES: Final[int]\nA_BLINK: Final[int]\nA_BOLD: Final[int]\nA_CHARTEXT: Final[int]\nA_COLOR: Final[int]\nA_DIM: Final[int]\nA_HORIZONTAL: Final[int]\nA_INVIS: Final[int]\nA_ITALIC: Final[int]\nA_LEFT: Final[int]\nA_LOW: Final[int]\nA_NORMAL: Final[int]\nA_PROTECT: Final[int]\nA_REVERSE: Final[int]\nA_RIGHT: Final[int]\nA_STANDOUT: Final[int]\nA_TOP: Final[int]\nA_UNDERLINE: Final[int]\nA_VERTICAL: Final[int]\nBUTTON1_CLICKED: Final[int]\nBUTTON1_DOUBLE_CLICKED: Final[int]\nBUTTON1_PRESSED: Final[int]\nBUTTON1_RELEASED: Final[int]\nBUTTON1_TRIPLE_CLICKED: Final[int]\nBUTTON2_CLICKED: Final[int]\nBUTTON2_DOUBLE_CLICKED: Final[int]\nBUTTON2_PRESSED: Final[int]\nBUTTON2_RELEASED: Final[int]\nBUTTON2_TRIPLE_CLICKED: Final[int]\nBUTTON3_CLICKED: Final[int]\nBUTTON3_DOUBLE_CLICKED: Final[int]\nBUTTON3_PRESSED: Final[int]\nBUTTON3_RELEASED: Final[int]\nBUTTON3_TRIPLE_CLICKED: Final[int]\nBUTTON4_CLICKED: Final[int]\nBUTTON4_DOUBLE_CLICKED: Final[int]\nBUTTON4_PRESSED: Final[int]\nBUTTON4_RELEASED: Final[int]\nBUTTON4_TRIPLE_CLICKED: Final[int]\n# Darwin ncurses doesn't provide BUTTON5_* constants prior to 3.12.10 and 3.13.3\nif sys.version_info >= (3, 10):\n    if sys.version_info >= (3, 12) or sys.platform != \"darwin\":\n        BUTTON5_PRESSED: Final[int]\n        BUTTON5_RELEASED: Final[int]\n        BUTTON5_CLICKED: Final[int]\n        BUTTON5_DOUBLE_CLICKED: Final[int]\n        BUTTON5_TRIPLE_CLICKED: Final[int]\nBUTTON_ALT: Final[int]\nBUTTON_CTRL: Final[int]\nBUTTON_SHIFT: Final[int]\nCOLOR_BLACK: Final[int]\nCOLOR_BLUE: Final[int]\nCOLOR_CYAN: Final[int]\nCOLOR_GREEN: Final[int]\nCOLOR_MAGENTA: Final[int]\nCOLOR_RED: Final[int]\nCOLOR_WHITE: Final[int]\nCOLOR_YELLOW: Final[int]\nERR: Final[int]\nKEY_A1: Final[int]\nKEY_A3: Final[int]\nKEY_B2: Final[int]\nKEY_BACKSPACE: Final[int]\nKEY_BEG: Final[int]\nKEY_BREAK: Final[int]\nKEY_BTAB: Final[int]\nKEY_C1: Final[int]\nKEY_C3: Final[int]\nKEY_CANCEL: Final[int]\nKEY_CATAB: Final[int]\nKEY_CLEAR: Final[int]\nKEY_CLOSE: Final[int]\nKEY_COMMAND: Final[int]\nKEY_COPY: Final[int]\nKEY_CREATE: Final[int]\nKEY_CTAB: Final[int]\nKEY_DC: Final[int]\nKEY_DL: Final[int]\nKEY_DOWN: Final[int]\nKEY_EIC: Final[int]\nKEY_END: Final[int]\nKEY_ENTER: Final[int]\nKEY_EOL: Final[int]\nKEY_EOS: Final[int]\nKEY_EXIT: Final[int]\nKEY_F0: Final[int]\nKEY_F1: Final[int]\nKEY_F10: Final[int]\nKEY_F11: Final[int]\nKEY_F12: Final[int]\nKEY_F13: Final[int]\nKEY_F14: Final[int]\nKEY_F15: Final[int]\nKEY_F16: Final[int]\nKEY_F17: Final[int]\nKEY_F18: Final[int]\nKEY_F19: Final[int]\nKEY_F2: Final[int]\nKEY_F20: Final[int]\nKEY_F21: Final[int]\nKEY_F22: Final[int]\nKEY_F23: Final[int]\nKEY_F24: Final[int]\nKEY_F25: Final[int]\nKEY_F26: Final[int]\nKEY_F27: Final[int]\nKEY_F28: Final[int]\nKEY_F29: Final[int]\nKEY_F3: Final[int]\nKEY_F30: Final[int]\nKEY_F31: Final[int]\nKEY_F32: Final[int]\nKEY_F33: Final[int]\nKEY_F34: Final[int]\nKEY_F35: Final[int]\nKEY_F36: Final[int]\nKEY_F37: Final[int]\nKEY_F38: Final[int]\nKEY_F39: Final[int]\nKEY_F4: Final[int]\nKEY_F40: Final[int]\nKEY_F41: Final[int]\nKEY_F42: Final[int]\nKEY_F43: Final[int]\nKEY_F44: Final[int]\nKEY_F45: Final[int]\nKEY_F46: Final[int]\nKEY_F47: Final[int]\nKEY_F48: Final[int]\nKEY_F49: Final[int]\nKEY_F5: Final[int]\nKEY_F50: Final[int]\nKEY_F51: Final[int]\nKEY_F52: Final[int]\nKEY_F53: Final[int]\nKEY_F54: Final[int]\nKEY_F55: Final[int]\nKEY_F56: Final[int]\nKEY_F57: Final[int]\nKEY_F58: Final[int]\nKEY_F59: Final[int]\nKEY_F6: Final[int]\nKEY_F60: Final[int]\nKEY_F61: Final[int]\nKEY_F62: Final[int]\nKEY_F63: Final[int]\nKEY_F7: Final[int]\nKEY_F8: Final[int]\nKEY_F9: Final[int]\nKEY_FIND: Final[int]\nKEY_HELP: Final[int]\nKEY_HOME: Final[int]\nKEY_IC: Final[int]\nKEY_IL: Final[int]\nKEY_LEFT: Final[int]\nKEY_LL: Final[int]\nKEY_MARK: Final[int]\nKEY_MAX: Final[int]\nKEY_MESSAGE: Final[int]\nKEY_MIN: Final[int]\nKEY_MOUSE: Final[int]\nKEY_MOVE: Final[int]\nKEY_NEXT: Final[int]\nKEY_NPAGE: Final[int]\nKEY_OPEN: Final[int]\nKEY_OPTIONS: Final[int]\nKEY_PPAGE: Final[int]\nKEY_PREVIOUS: Final[int]\nKEY_PRINT: Final[int]\nKEY_REDO: Final[int]\nKEY_REFERENCE: Final[int]\nKEY_REFRESH: Final[int]\nKEY_REPLACE: Final[int]\nKEY_RESET: Final[int]\nKEY_RESIZE: Final[int]\nKEY_RESTART: Final[int]\nKEY_RESUME: Final[int]\nKEY_RIGHT: Final[int]\nKEY_SAVE: Final[int]\nKEY_SBEG: Final[int]\nKEY_SCANCEL: Final[int]\nKEY_SCOMMAND: Final[int]\nKEY_SCOPY: Final[int]\nKEY_SCREATE: Final[int]\nKEY_SDC: Final[int]\nKEY_SDL: Final[int]\nKEY_SELECT: Final[int]\nKEY_SEND: Final[int]\nKEY_SEOL: Final[int]\nKEY_SEXIT: Final[int]\nKEY_SF: Final[int]\nKEY_SFIND: Final[int]\nKEY_SHELP: Final[int]\nKEY_SHOME: Final[int]\nKEY_SIC: Final[int]\nKEY_SLEFT: Final[int]\nKEY_SMESSAGE: Final[int]\nKEY_SMOVE: Final[int]\nKEY_SNEXT: Final[int]\nKEY_SOPTIONS: Final[int]\nKEY_SPREVIOUS: Final[int]\nKEY_SPRINT: Final[int]\nKEY_SR: Final[int]\nKEY_SREDO: Final[int]\nKEY_SREPLACE: Final[int]\nKEY_SRESET: Final[int]\nKEY_SRIGHT: Final[int]\nKEY_SRSUME: Final[int]\nKEY_SSAVE: Final[int]\nKEY_SSUSPEND: Final[int]\nKEY_STAB: Final[int]\nKEY_SUNDO: Final[int]\nKEY_SUSPEND: Final[int]\nKEY_UNDO: Final[int]\nKEY_UP: Final[int]\nOK: Final[int]\nREPORT_MOUSE_POSITION: Final[int]\n_C_API: Any\nversion: Final[bytes]\n\ndef baudrate() -> int: ...\ndef beep() -> None: ...\ndef can_change_color() -> bool: ...\ndef cbreak(flag: bool = True, /) -> None: ...\ndef color_content(color_number: int, /) -> tuple[int, int, int]: ...\ndef color_pair(pair_number: int, /) -> int: ...\ndef curs_set(visibility: int, /) -> int: ...\ndef def_prog_mode() -> None: ...\ndef def_shell_mode() -> None: ...\ndef delay_output(ms: int, /) -> None: ...\ndef doupdate() -> None: ...\ndef echo(flag: bool = True, /) -> None: ...\ndef endwin() -> None: ...\ndef erasechar() -> bytes: ...\ndef filter() -> None: ...\ndef flash() -> None: ...\ndef flushinp() -> None: ...\ndef get_escdelay() -> int: ...\ndef get_tabsize() -> int: ...\ndef getmouse() -> tuple[int, int, int, int, int]: ...\ndef getsyx() -> tuple[int, int]: ...\ndef getwin(file: SupportsRead[bytes], /) -> window: ...\ndef halfdelay(tenths: int, /) -> None: ...\ndef has_colors() -> bool: ...\n\nif sys.version_info >= (3, 10):\n    def has_extended_color_support() -> bool: ...\n\nif sys.version_info >= (3, 14):\n    def assume_default_colors(fg: int, bg: int, /) -> None: ...\n\ndef has_ic() -> bool: ...\ndef has_il() -> bool: ...\ndef has_key(key: int, /) -> bool: ...\ndef init_color(color_number: int, r: int, g: int, b: int, /) -> None: ...\ndef init_pair(pair_number: int, fg: int, bg: int, /) -> None: ...\ndef initscr() -> window: ...\ndef intrflush(flag: bool, /) -> None: ...\ndef is_term_resized(nlines: int, ncols: int, /) -> bool: ...\ndef isendwin() -> bool: ...\ndef keyname(key: int, /) -> bytes: ...\ndef killchar() -> bytes: ...\ndef longname() -> bytes: ...\ndef meta(yes: bool, /) -> None: ...\ndef mouseinterval(interval: int, /) -> None: ...\ndef mousemask(newmask: int, /) -> tuple[int, int]: ...\ndef napms(ms: int, /) -> int: ...\ndef newpad(nlines: int, ncols: int, /) -> window: ...\ndef newwin(nlines: int, ncols: int, begin_y: int = 0, begin_x: int = 0, /) -> window: ...\ndef nl(flag: bool = True, /) -> None: ...\ndef nocbreak() -> None: ...\ndef noecho() -> None: ...\ndef nonl() -> None: ...\ndef noqiflush() -> None: ...\ndef noraw() -> None: ...\ndef pair_content(pair_number: int, /) -> tuple[int, int]: ...\ndef pair_number(attr: int, /) -> int: ...\ndef putp(string: ReadOnlyBuffer, /) -> None: ...\ndef qiflush(flag: bool = True, /) -> None: ...\ndef raw(flag: bool = True, /) -> None: ...\ndef reset_prog_mode() -> None: ...\ndef reset_shell_mode() -> None: ...\ndef resetty() -> None: ...\ndef resize_term(nlines: int, ncols: int, /) -> None: ...\ndef resizeterm(nlines: int, ncols: int, /) -> None: ...\ndef savetty() -> None: ...\ndef set_escdelay(ms: int, /) -> None: ...\ndef set_tabsize(size: int, /) -> None: ...\ndef setsyx(y: int, x: int, /) -> None: ...\ndef setupterm(term: str | None = None, fd: int = -1) -> None: ...\ndef start_color() -> None: ...\ndef termattrs() -> int: ...\ndef termname() -> bytes: ...\ndef tigetflag(capname: str, /) -> int: ...\ndef tigetnum(capname: str, /) -> int: ...\ndef tigetstr(capname: str, /) -> bytes | None: ...\ndef tparm(\n    str: ReadOnlyBuffer,\n    i1: int = 0,\n    i2: int = 0,\n    i3: int = 0,\n    i4: int = 0,\n    i5: int = 0,\n    i6: int = 0,\n    i7: int = 0,\n    i8: int = 0,\n    i9: int = 0,\n    /,\n) -> bytes: ...\ndef typeahead(fd: int, /) -> None: ...\ndef unctrl(ch: _ChType, /) -> bytes: ...\ndef unget_wch(ch: int | str, /) -> None: ...\ndef ungetch(ch: _ChType, /) -> None: ...\ndef ungetmouse(id: int, x: int, y: int, z: int, bstate: int, /) -> None: ...\ndef update_lines_cols() -> None: ...\ndef use_default_colors() -> None: ...\ndef use_env(flag: bool, /) -> None: ...\n\nclass error(Exception): ...\n\n@final\nclass window:  # undocumented\n    encoding: str\n    @overload\n    def addch(self, ch: _ChType, attr: int = ...) -> None: ...\n    @overload\n    def addch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ...\n    @overload\n    def addnstr(self, str: str, n: int, attr: int = ...) -> None: ...\n    @overload\n    def addnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ...\n    @overload\n    def addstr(self, str: str, attr: int = ...) -> None: ...\n    @overload\n    def addstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ...\n    def attroff(self, attr: int, /) -> None: ...\n    def attron(self, attr: int, /) -> None: ...\n    def attrset(self, attr: int, /) -> None: ...\n    def bkgd(self, ch: _ChType, attr: int = 0, /) -> None: ...\n    def bkgdset(self, ch: _ChType, attr: int = 0, /) -> None: ...\n    def border(\n        self,\n        ls: _ChType = ...,\n        rs: _ChType = ...,\n        ts: _ChType = ...,\n        bs: _ChType = ...,\n        tl: _ChType = ...,\n        tr: _ChType = ...,\n        bl: _ChType = ...,\n        br: _ChType = ...,\n    ) -> None: ...\n    @overload\n    def box(self) -> None: ...\n    @overload\n    def box(self, vertch: _ChType = 0, horch: _ChType = 0) -> None: ...\n    @overload\n    def chgat(self, attr: int) -> None: ...\n    @overload\n    def chgat(self, num: int, attr: int) -> None: ...\n    @overload\n    def chgat(self, y: int, x: int, attr: int) -> None: ...\n    @overload\n    def chgat(self, y: int, x: int, num: int, attr: int) -> None: ...\n    def clear(self) -> None: ...\n    def clearok(self, yes: int) -> None: ...\n    def clrtobot(self) -> None: ...\n    def clrtoeol(self) -> None: ...\n    def cursyncup(self) -> None: ...\n    @overload\n    def delch(self) -> None: ...\n    @overload\n    def delch(self, y: int, x: int) -> None: ...\n    def deleteln(self) -> None: ...\n    @overload\n    def derwin(self, begin_y: int, begin_x: int) -> window: ...\n    @overload\n    def derwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ...\n    def echochar(self, ch: _ChType, attr: int = 0, /) -> None: ...\n    def enclose(self, y: int, x: int, /) -> bool: ...\n    def erase(self) -> None: ...\n    def getbegyx(self) -> tuple[int, int]: ...\n    def getbkgd(self) -> tuple[int, int]: ...\n    @overload\n    def getch(self) -> int: ...\n    @overload\n    def getch(self, y: int, x: int) -> int: ...\n    @overload\n    def get_wch(self) -> int | str: ...\n    @overload\n    def get_wch(self, y: int, x: int) -> int | str: ...\n    @overload\n    def getkey(self) -> str: ...\n    @overload\n    def getkey(self, y: int, x: int) -> str: ...\n    def getmaxyx(self) -> tuple[int, int]: ...\n    def getparyx(self) -> tuple[int, int]: ...\n    @overload\n    def getstr(self) -> bytes: ...\n    @overload\n    def getstr(self, n: int) -> bytes: ...\n    @overload\n    def getstr(self, y: int, x: int) -> bytes: ...\n    @overload\n    def getstr(self, y: int, x: int, n: int) -> bytes: ...\n    def getyx(self) -> tuple[int, int]: ...\n    @overload\n    def hline(self, ch: _ChType, n: int) -> None: ...\n    @overload\n    def hline(self, y: int, x: int, ch: _ChType, n: int) -> None: ...\n    def idcok(self, flag: bool) -> None: ...\n    def idlok(self, yes: bool) -> None: ...\n    def immedok(self, flag: bool) -> None: ...\n    @overload\n    def inch(self) -> int: ...\n    @overload\n    def inch(self, y: int, x: int) -> int: ...\n    @overload\n    def insch(self, ch: _ChType, attr: int = ...) -> None: ...\n    @overload\n    def insch(self, y: int, x: int, ch: _ChType, attr: int = ...) -> None: ...\n    def insdelln(self, nlines: int) -> None: ...\n    def insertln(self) -> None: ...\n    @overload\n    def insnstr(self, str: str, n: int, attr: int = ...) -> None: ...\n    @overload\n    def insnstr(self, y: int, x: int, str: str, n: int, attr: int = ...) -> None: ...\n    @overload\n    def insstr(self, str: str, attr: int = ...) -> None: ...\n    @overload\n    def insstr(self, y: int, x: int, str: str, attr: int = ...) -> None: ...\n    @overload\n    def instr(self, n: int = 2047) -> bytes: ...\n    @overload\n    def instr(self, y: int, x: int, n: int = 2047) -> bytes: ...\n    def is_linetouched(self, line: int, /) -> bool: ...\n    def is_wintouched(self) -> bool: ...\n    def keypad(self, yes: bool, /) -> None: ...\n    def leaveok(self, yes: bool) -> None: ...\n    def move(self, new_y: int, new_x: int) -> None: ...\n    def mvderwin(self, y: int, x: int) -> None: ...\n    def mvwin(self, new_y: int, new_x: int) -> None: ...\n    def nodelay(self, yes: bool) -> None: ...\n    def notimeout(self, yes: bool) -> None: ...\n    @overload\n    def noutrefresh(self) -> None: ...\n    @overload\n    def noutrefresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ...\n    @overload\n    def overlay(self, destwin: window) -> None: ...\n    @overload\n    def overlay(\n        self, destwin: window, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int\n    ) -> None: ...\n    @overload\n    def overwrite(self, destwin: window) -> None: ...\n    @overload\n    def overwrite(\n        self, destwin: window, sminrow: int, smincol: int, dminrow: int, dmincol: int, dmaxrow: int, dmaxcol: int\n    ) -> None: ...\n    def putwin(self, file: SupportsWrite[bytes], /) -> None: ...\n    def redrawln(self, beg: int, num: int, /) -> None: ...\n    def redrawwin(self) -> None: ...\n    @overload\n    def refresh(self) -> None: ...\n    @overload\n    def refresh(self, pminrow: int, pmincol: int, sminrow: int, smincol: int, smaxrow: int, smaxcol: int) -> None: ...\n    def resize(self, nlines: int, ncols: int) -> None: ...\n    def scroll(self, lines: int = 1) -> None: ...\n    def scrollok(self, flag: bool) -> None: ...\n    def setscrreg(self, top: int, bottom: int, /) -> None: ...\n    def standend(self) -> None: ...\n    def standout(self) -> None: ...\n    @overload\n    def subpad(self, begin_y: int, begin_x: int) -> window: ...\n    @overload\n    def subpad(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ...\n    @overload\n    def subwin(self, begin_y: int, begin_x: int) -> window: ...\n    @overload\n    def subwin(self, nlines: int, ncols: int, begin_y: int, begin_x: int) -> window: ...\n    def syncdown(self) -> None: ...\n    def syncok(self, flag: bool) -> None: ...\n    def syncup(self) -> None: ...\n    def timeout(self, delay: int) -> None: ...\n    def touchline(self, start: int, count: int, changed: bool = True) -> None: ...\n    def touchwin(self) -> None: ...\n    def untouchwin(self) -> None: ...\n    @overload\n    def vline(self, ch: _ChType, n: int) -> None: ...\n    @overload\n    def vline(self, y: int, x: int, ch: _ChType, n: int) -> None: ...\n\nncurses_version: _ncurses_version\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_curses_panel.pyi",
    "content": "from _curses import window\nfrom typing import Final, final\n\n__version__: Final[str]\nversion: Final[str]\n\nclass error(Exception): ...\n\n@final\nclass panel:\n    def above(self) -> panel: ...\n    def below(self) -> panel: ...\n    def bottom(self) -> None: ...\n    def hidden(self) -> bool: ...\n    def hide(self) -> None: ...\n    def move(self, y: int, x: int, /) -> None: ...\n    def replace(self, win: window, /) -> None: ...\n    def set_userptr(self, obj: object, /) -> None: ...\n    def show(self) -> None: ...\n    def top(self) -> None: ...\n    def userptr(self) -> object: ...\n    def window(self) -> window: ...\n\ndef bottom_panel() -> panel: ...\ndef new_panel(win: window, /) -> panel: ...\ndef top_panel() -> panel: ...\ndef update_panels() -> panel: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_dbm.pyi",
    "content": "import sys\nfrom _typeshed import ReadOnlyBuffer, StrOrBytesPath\nfrom types import TracebackType\nfrom typing import Final, TypeVar, final, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\nif sys.platform != \"win32\":\n    _T = TypeVar(\"_T\")\n    _KeyType: TypeAlias = str | ReadOnlyBuffer\n    _ValueType: TypeAlias = str | ReadOnlyBuffer\n\n    class error(OSError): ...\n    library: Final[str]\n\n    # Actual typename dbm, not exposed by the implementation\n    @final\n    @type_check_only\n    class _dbm:\n        def close(self) -> None: ...\n        if sys.version_info >= (3, 13):\n            def clear(self) -> None: ...\n\n        def __getitem__(self, item: _KeyType) -> bytes: ...\n        def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ...\n        def __delitem__(self, key: _KeyType) -> None: ...\n        def __len__(self) -> int: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(\n            self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n        ) -> None: ...\n        @overload\n        def get(self, k: _KeyType, /) -> bytes | None: ...\n        @overload\n        def get(self, k: _KeyType, default: _T, /) -> bytes | _T: ...\n        def keys(self) -> list[bytes]: ...\n        def setdefault(self, k: _KeyType, default: _ValueType = b\"\", /) -> bytes: ...\n        # This isn't true, but the class can't be instantiated. See #13024\n        __new__: None  # type: ignore[assignment]\n        __init__: None  # type: ignore[assignment]\n\n    if sys.version_info >= (3, 11):\n        def open(filename: StrOrBytesPath, flags: str = \"r\", mode: int = 0o666, /) -> _dbm: ...\n    else:\n        def open(filename: str, flags: str = \"r\", mode: int = 0o666, /) -> _dbm: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_decimal.pyi",
    "content": "import sys\nfrom decimal import (\n    Clamped as Clamped,\n    Context as Context,\n    ConversionSyntax as ConversionSyntax,\n    Decimal as Decimal,\n    DecimalException as DecimalException,\n    DecimalTuple as DecimalTuple,\n    DivisionByZero as DivisionByZero,\n    DivisionImpossible as DivisionImpossible,\n    DivisionUndefined as DivisionUndefined,\n    FloatOperation as FloatOperation,\n    Inexact as Inexact,\n    InvalidContext as InvalidContext,\n    InvalidOperation as InvalidOperation,\n    Overflow as Overflow,\n    Rounded as Rounded,\n    Subnormal as Subnormal,\n    Underflow as Underflow,\n    _ContextManager,\n)\nfrom typing import Final\nfrom typing_extensions import TypeAlias\n\n_TrapType: TypeAlias = type[DecimalException]\n\n__version__: Final[str]\n__libmpdec_version__: Final[str]\n\nROUND_DOWN: Final = \"ROUND_DOWN\"\nROUND_HALF_UP: Final = \"ROUND_HALF_UP\"\nROUND_HALF_EVEN: Final = \"ROUND_HALF_EVEN\"\nROUND_CEILING: Final = \"ROUND_CEILING\"\nROUND_FLOOR: Final = \"ROUND_FLOOR\"\nROUND_UP: Final = \"ROUND_UP\"\nROUND_HALF_DOWN: Final = \"ROUND_HALF_DOWN\"\nROUND_05UP: Final = \"ROUND_05UP\"\nHAVE_CONTEXTVAR: Final[bool]\nHAVE_THREADS: Final[bool]\nMAX_EMAX: Final[int]\nMAX_PREC: Final[int]\nMIN_EMIN: Final[int]\nMIN_ETINY: Final[int]\nif sys.version_info >= (3, 14):\n    IEEE_CONTEXT_MAX_BITS: Final[int]\n\ndef setcontext(context: Context, /) -> None: ...\ndef getcontext() -> Context: ...\n\nif sys.version_info >= (3, 11):\n    def localcontext(\n        ctx: Context | None = None,\n        *,\n        prec: int | None = None,\n        rounding: str | None = None,\n        Emin: int | None = None,\n        Emax: int | None = None,\n        capitals: int | None = None,\n        clamp: int | None = None,\n        traps: dict[_TrapType, bool] | None = None,\n        flags: dict[_TrapType, bool] | None = None,\n    ) -> _ContextManager: ...\n\nelse:\n    def localcontext(ctx: Context | None = None) -> _ContextManager: ...\n\nif sys.version_info >= (3, 14):\n    def IEEEContext(bits: int, /) -> Context: ...\n\nDefaultContext: Context\nBasicContext: Context\nExtendedContext: Context\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_frozen_importlib.pyi",
    "content": "import importlib.abc\nimport importlib.machinery\nimport sys\nimport types\nfrom _typeshed.importlib import LoaderProtocol\nfrom collections.abc import Mapping, Sequence\nfrom types import ModuleType\nfrom typing import Any, ClassVar\nfrom typing_extensions import deprecated\n\n# Signature of `builtins.__import__` should be kept identical to `importlib.__import__`\ndef __import__(\n    name: str,\n    globals: Mapping[str, object] | None = None,\n    locals: Mapping[str, object] | None = None,\n    fromlist: Sequence[str] | None = (),\n    level: int = 0,\n) -> ModuleType: ...\ndef spec_from_loader(\n    name: str, loader: LoaderProtocol | None, *, origin: str | None = None, is_package: bool | None = None\n) -> importlib.machinery.ModuleSpec | None: ...\ndef module_from_spec(spec: importlib.machinery.ModuleSpec) -> types.ModuleType: ...\ndef _init_module_attrs(\n    spec: importlib.machinery.ModuleSpec, module: types.ModuleType, *, override: bool = False\n) -> types.ModuleType: ...\n\nclass ModuleSpec:\n    def __init__(\n        self,\n        name: str,\n        loader: importlib.abc.Loader | None,\n        *,\n        origin: str | None = None,\n        loader_state: Any = None,\n        is_package: bool | None = None,\n    ) -> None: ...\n    name: str\n    loader: importlib.abc.Loader | None\n    origin: str | None\n    submodule_search_locations: list[str] | None\n    loader_state: Any\n    cached: str | None\n    @property\n    def parent(self) -> str | None: ...\n    has_location: bool\n    def __eq__(self, other: object) -> bool: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\nclass BuiltinImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):\n    # MetaPathFinder\n    if sys.version_info < (3, 12):\n        @classmethod\n        @deprecated(\"Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.\")\n        def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ...\n\n    @classmethod\n    def find_spec(\n        cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None\n    ) -> ModuleSpec | None: ...\n    # InspectLoader\n    @classmethod\n    def is_package(cls, fullname: str) -> bool: ...\n    @classmethod\n    def load_module(cls, fullname: str) -> types.ModuleType: ...\n    @classmethod\n    def get_code(cls, fullname: str) -> None: ...\n    @classmethod\n    def get_source(cls, fullname: str) -> None: ...\n    # Loader\n    if sys.version_info < (3, 12):\n        @staticmethod\n        @deprecated(\n            \"Deprecated since Python 3.4; removed in Python 3.12. \"\n            \"The module spec is now used by the import machinery to generate a module repr.\"\n        )\n        def module_repr(module: types.ModuleType) -> str: ...\n    if sys.version_info >= (3, 10):\n        @staticmethod\n        def create_module(spec: ModuleSpec) -> types.ModuleType | None: ...\n        @staticmethod\n        def exec_module(module: types.ModuleType) -> None: ...\n    else:\n        @classmethod\n        def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ...\n        @classmethod\n        def exec_module(cls, module: types.ModuleType) -> None: ...\n\nclass FrozenImporter(importlib.abc.MetaPathFinder, importlib.abc.InspectLoader):\n    # MetaPathFinder\n    if sys.version_info < (3, 12):\n        @classmethod\n        @deprecated(\"Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.\")\n        def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ...\n\n    @classmethod\n    def find_spec(\n        cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None\n    ) -> ModuleSpec | None: ...\n    # InspectLoader\n    @classmethod\n    def is_package(cls, fullname: str) -> bool: ...\n    @classmethod\n    def load_module(cls, fullname: str) -> types.ModuleType: ...\n    @classmethod\n    def get_code(cls, fullname: str) -> None: ...\n    @classmethod\n    def get_source(cls, fullname: str) -> None: ...\n    # Loader\n    if sys.version_info < (3, 12):\n        @staticmethod\n        @deprecated(\n            \"Deprecated since Python 3.4; removed in Python 3.12. \"\n            \"The module spec is now used by the import machinery to generate a module repr.\"\n        )\n        def module_repr(m: types.ModuleType) -> str: ...\n    if sys.version_info >= (3, 10):\n        @staticmethod\n        def create_module(spec: ModuleSpec) -> types.ModuleType | None: ...\n    else:\n        @classmethod\n        def create_module(cls, spec: ModuleSpec) -> types.ModuleType | None: ...\n\n    @staticmethod\n    def exec_module(module: types.ModuleType) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_frozen_importlib_external.pyi",
    "content": "import _ast\nimport _io\nimport importlib.abc\nimport importlib.machinery\nimport sys\nimport types\nfrom _typeshed import ReadableBuffer, StrOrBytesPath, StrPath\nfrom _typeshed.importlib import LoaderProtocol\nfrom collections.abc import Callable, Iterable, Iterator, Mapping, MutableSequence, Sequence\nfrom importlib.machinery import ModuleSpec\nfrom importlib.metadata import DistributionFinder, PathDistribution\nfrom typing import Any, Final, Literal, overload\nfrom typing_extensions import Self, deprecated\n\nif sys.version_info >= (3, 10):\n    import importlib.readers\n\nif sys.platform == \"win32\":\n    path_separators: Literal[\"\\\\/\"]\n    path_sep: Literal[\"\\\\\"]\n    path_sep_tuple: tuple[Literal[\"\\\\\"], Literal[\"/\"]]\nelse:\n    path_separators: Literal[\"/\"]\n    path_sep: Literal[\"/\"]\n    path_sep_tuple: tuple[Literal[\"/\"]]\n\nMAGIC_NUMBER: Final[bytes]\n\n@overload\n@deprecated(\n    \"The `debug_override` parameter is deprecated since Python 3.5; will be removed in Python 3.15. Use `optimization` instead.\"\n)\ndef cache_from_source(path: StrPath, debug_override: bool, *, optimization: None = None) -> str: ...\n@overload\ndef cache_from_source(path: StrPath, debug_override: None = None, *, optimization: Any | None = None) -> str: ...\ndef source_from_cache(path: StrPath) -> str: ...\ndef decode_source(source_bytes: ReadableBuffer) -> str: ...\ndef spec_from_file_location(\n    name: str,\n    location: StrOrBytesPath | None = None,\n    *,\n    loader: LoaderProtocol | None = None,\n    submodule_search_locations: list[str] | None = ...,\n) -> importlib.machinery.ModuleSpec | None: ...\n@deprecated(\n    \"Deprecated since Python 3.6. Use site configuration instead. \"\n    \"Future versions of Python may not enable this finder by default.\"\n)\nclass WindowsRegistryFinder(importlib.abc.MetaPathFinder):\n    if sys.version_info < (3, 12):\n        @classmethod\n        @deprecated(\"Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.\")\n        def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ...\n\n    @classmethod\n    def find_spec(\n        cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None\n    ) -> ModuleSpec | None: ...\n\nclass PathFinder(importlib.abc.MetaPathFinder):\n    if sys.version_info >= (3, 10):\n        @staticmethod\n        def invalidate_caches() -> None: ...\n    else:\n        @classmethod\n        def invalidate_caches(cls) -> None: ...\n    if sys.version_info >= (3, 10):\n        @staticmethod\n        def find_distributions(context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ...\n    else:\n        @classmethod\n        def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ...\n\n    @classmethod\n    def find_spec(\n        cls, fullname: str, path: Sequence[str] | None = None, target: types.ModuleType | None = None\n    ) -> ModuleSpec | None: ...\n    if sys.version_info < (3, 12):\n        @classmethod\n        @deprecated(\"Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.\")\n        def find_module(cls, fullname: str, path: Sequence[str] | None = None) -> importlib.abc.Loader | None: ...\n\nSOURCE_SUFFIXES: Final[list[str]]\nDEBUG_BYTECODE_SUFFIXES: Final = [\".pyc\"]\nOPTIMIZED_BYTECODE_SUFFIXES: Final = [\".pyc\"]\nBYTECODE_SUFFIXES: Final = [\".pyc\"]\nEXTENSION_SUFFIXES: Final[list[str]]\n\nclass FileFinder(importlib.abc.PathEntryFinder):\n    path: str\n    def __init__(self, path: str, *loader_details: tuple[type[importlib.abc.Loader], list[str]]) -> None: ...\n    @classmethod\n    def path_hook(\n        cls, *loader_details: tuple[type[importlib.abc.Loader], list[str]]\n    ) -> Callable[[str], importlib.abc.PathEntryFinder]: ...\n\nclass _LoaderBasics:\n    def is_package(self, fullname: str) -> bool: ...\n    def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ...\n    def exec_module(self, module: types.ModuleType) -> None: ...\n    def load_module(self, fullname: str) -> types.ModuleType: ...\n\nclass SourceLoader(_LoaderBasics):\n    def path_mtime(self, path: str) -> float: ...\n    def set_data(self, path: str, data: bytes) -> None: ...\n    def get_source(self, fullname: str) -> str | None: ...\n    def path_stats(self, path: str) -> Mapping[str, Any]: ...\n    def source_to_code(\n        self, data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, path: bytes | StrPath\n    ) -> types.CodeType: ...\n    def get_code(self, fullname: str) -> types.CodeType | None: ...\n\nclass FileLoader:\n    name: str\n    path: str\n    def __init__(self, fullname: str, path: str) -> None: ...\n    def get_data(self, path: str) -> bytes: ...\n    def get_filename(self, fullname: str | None = None) -> str: ...\n    def load_module(self, fullname: str | None = None) -> types.ModuleType: ...\n    if sys.version_info >= (3, 10):\n        def get_resource_reader(self, name: str | None = None) -> importlib.readers.FileReader: ...\n    else:\n        def get_resource_reader(self, name: str | None = None) -> Self | None: ...\n        def open_resource(self, resource: str) -> _io.FileIO: ...\n        def resource_path(self, resource: str) -> str: ...\n        def is_resource(self, name: str) -> bool: ...\n        def contents(self) -> Iterator[str]: ...\n\nclass SourceFileLoader(importlib.abc.FileLoader, FileLoader, importlib.abc.SourceLoader, SourceLoader):  # type: ignore[misc]  # incompatible method arguments in base classes\n    def set_data(self, path: str, data: ReadableBuffer, *, _mode: int = 0o666) -> None: ...\n    def path_stats(self, path: str) -> Mapping[str, Any]: ...\n    def source_to_code(  # type: ignore[override]  # incompatible with InspectLoader.source_to_code\n        self,\n        data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive,\n        path: bytes | StrPath,\n        *,\n        _optimize: int = -1,\n    ) -> types.CodeType: ...\n\nclass SourcelessFileLoader(importlib.abc.FileLoader, FileLoader, _LoaderBasics):\n    def get_code(self, fullname: str) -> types.CodeType | None: ...\n    def get_source(self, fullname: str) -> None: ...\n\nclass ExtensionFileLoader(FileLoader, _LoaderBasics, importlib.abc.ExecutionLoader):\n    def __init__(self, name: str, path: str) -> None: ...\n    def get_filename(self, fullname: str | None = None) -> str: ...\n    def get_source(self, fullname: str) -> None: ...\n    def create_module(self, spec: ModuleSpec) -> types.ModuleType: ...\n    def exec_module(self, module: types.ModuleType) -> None: ...\n    def get_code(self, fullname: str) -> None: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n\nif sys.version_info >= (3, 11):\n    class NamespaceLoader(importlib.abc.InspectLoader):\n        def __init__(\n            self, name: str, path: MutableSequence[str], path_finder: Callable[[str, tuple[str, ...]], ModuleSpec]\n        ) -> None: ...\n        def is_package(self, fullname: str) -> Literal[True]: ...\n        def get_source(self, fullname: str) -> Literal[\"\"]: ...\n        def get_code(self, fullname: str) -> types.CodeType: ...\n        def create_module(self, spec: ModuleSpec) -> None: ...\n        def exec_module(self, module: types.ModuleType) -> None: ...\n        @deprecated(\"Deprecated since Python 3.10; will be removed in Python 3.15. Use `exec_module()` instead.\")\n        def load_module(self, fullname: str) -> types.ModuleType: ...\n        def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ...\n        if sys.version_info < (3, 12):\n            @staticmethod\n            @deprecated(\n                \"Deprecated since Python 3.4; removed in Python 3.12. \"\n                \"The module spec is now used by the import machinery to generate a module repr.\"\n            )\n            def module_repr(module: types.ModuleType) -> str: ...\n\n    _NamespaceLoader = NamespaceLoader\nelse:\n    class _NamespaceLoader:\n        def __init__(\n            self, name: str, path: MutableSequence[str], path_finder: Callable[[str, tuple[str, ...]], ModuleSpec]\n        ) -> None: ...\n        def is_package(self, fullname: str) -> Literal[True]: ...\n        def get_source(self, fullname: str) -> Literal[\"\"]: ...\n        def get_code(self, fullname: str) -> types.CodeType: ...\n        def create_module(self, spec: ModuleSpec) -> None: ...\n        def exec_module(self, module: types.ModuleType) -> None: ...\n        if sys.version_info >= (3, 10):\n            @deprecated(\"Deprecated since Python 3.10; will be removed in Python 3.15. Use `exec_module()` instead.\")\n            def load_module(self, fullname: str) -> types.ModuleType: ...\n            @staticmethod\n            @deprecated(\n                \"Deprecated since Python 3.4; removed in Python 3.12. \"\n                \"The module spec is now used by the import machinery to generate a module repr.\"\n            )\n            def module_repr(module: types.ModuleType) -> str: ...\n            def get_resource_reader(self, module: types.ModuleType) -> importlib.readers.NamespaceReader: ...\n        else:\n            def load_module(self, fullname: str) -> types.ModuleType: ...\n            @classmethod\n            @deprecated(\n                \"Deprecated since Python 3.4; removed in Python 3.12. \"\n                \"The module spec is now used by the import machinery to generate a module repr.\"\n            )\n            def module_repr(cls, module: types.ModuleType) -> str: ...\n\nif sys.version_info >= (3, 13):\n    class AppleFrameworkLoader(ExtensionFileLoader, importlib.abc.ExecutionLoader): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_gdbm.pyi",
    "content": "import sys\nfrom _typeshed import ReadOnlyBuffer, StrOrBytesPath\nfrom types import TracebackType\nfrom typing import TypeVar, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\nif sys.platform != \"win32\":\n    _T = TypeVar(\"_T\")\n    _KeyType: TypeAlias = str | ReadOnlyBuffer\n    _ValueType: TypeAlias = str | ReadOnlyBuffer\n\n    open_flags: str\n\n    class error(OSError): ...\n    # Actual typename gdbm, not exposed by the implementation\n    @type_check_only\n    class _gdbm:\n        def firstkey(self) -> bytes | None: ...\n        def nextkey(self, key: _KeyType) -> bytes | None: ...\n        def reorganize(self) -> None: ...\n        def sync(self) -> None: ...\n        def close(self) -> None: ...\n        if sys.version_info >= (3, 13):\n            def clear(self) -> None: ...\n\n        def __getitem__(self, item: _KeyType) -> bytes: ...\n        def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ...\n        def __delitem__(self, key: _KeyType) -> None: ...\n        def __contains__(self, key: _KeyType) -> bool: ...\n        def __len__(self) -> int: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(\n            self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n        ) -> None: ...\n        @overload\n        def get(self, k: _KeyType) -> bytes | None: ...\n        @overload\n        def get(self, k: _KeyType, default: _T) -> bytes | _T: ...\n        def keys(self) -> list[bytes]: ...\n        def setdefault(self, k: _KeyType, default: _ValueType = ...) -> bytes: ...\n        # Don't exist at runtime\n        __new__: None  # type: ignore[assignment]\n        __init__: None  # type: ignore[assignment]\n\n    if sys.version_info >= (3, 11):\n        def open(filename: StrOrBytesPath, flags: str = \"r\", mode: int = 0o666, /) -> _gdbm: ...\n    else:\n        def open(filename: str, flags: str = \"r\", mode: int = 0o666, /) -> _gdbm: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_hashlib.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Callable\nfrom types import ModuleType\nfrom typing import AnyStr, Protocol, final, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, disjoint_base\n\n_DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType | None\n\nopenssl_md_meth_names: frozenset[str]\n\n@type_check_only\nclass _HashObject(Protocol):\n    @property\n    def digest_size(self) -> int: ...\n    @property\n    def block_size(self) -> int: ...\n    @property\n    def name(self) -> str: ...\n    def copy(self) -> Self: ...\n    def digest(self) -> bytes: ...\n    def hexdigest(self) -> str: ...\n    def update(self, obj: ReadableBuffer, /) -> None: ...\n\n@disjoint_base\nclass HASH:\n    @property\n    def digest_size(self) -> int: ...\n    @property\n    def block_size(self) -> int: ...\n    @property\n    def name(self) -> str: ...\n    def copy(self) -> Self: ...\n    def digest(self) -> bytes: ...\n    def hexdigest(self) -> str: ...\n    def update(self, obj: ReadableBuffer, /) -> None: ...\n\nif sys.version_info >= (3, 10):\n    class UnsupportedDigestmodError(ValueError): ...\n\nclass HASHXOF(HASH):\n    def digest(self, length: int) -> bytes: ...  # type: ignore[override]\n    def hexdigest(self, length: int) -> str: ...  # type: ignore[override]\n\n@final\nclass HMAC:\n    @property\n    def digest_size(self) -> int: ...\n    @property\n    def block_size(self) -> int: ...\n    @property\n    def name(self) -> str: ...\n    def copy(self) -> Self: ...\n    def digest(self) -> bytes: ...\n    def hexdigest(self) -> str: ...\n    def update(self, msg: ReadableBuffer) -> None: ...\n\n@overload\ndef compare_digest(a: ReadableBuffer, b: ReadableBuffer, /) -> bool: ...\n@overload\ndef compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ...\ndef get_fips_mode() -> int: ...\ndef hmac_new(key: bytes | bytearray, msg: ReadableBuffer = b\"\", digestmod: _DigestMod = None) -> HMAC: ...\n\nif sys.version_info >= (3, 13):\n    def new(\n        name: str, data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_md5(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_sha1(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_sha224(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_sha256(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_sha384(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_sha512(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_sha3_224(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_sha3_256(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_sha3_384(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_sha3_512(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASH: ...\n    def openssl_shake_128(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASHXOF: ...\n    def openssl_shake_256(\n        data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True, string: ReadableBuffer | None = None\n    ) -> HASHXOF: ...\n\nelse:\n    def new(name: str, string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_md5(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_sha1(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_sha224(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_sha256(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_sha384(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_sha512(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_sha3_224(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_sha3_256(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_sha3_384(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_sha3_512(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n    def openssl_shake_128(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASHXOF: ...\n    def openssl_shake_256(string: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASHXOF: ...\n\ndef hmac_digest(key: bytes | bytearray, msg: ReadableBuffer, digest: str) -> bytes: ...\ndef pbkdf2_hmac(\n    hash_name: str, password: ReadableBuffer, salt: ReadableBuffer, iterations: int, dklen: int | None = None\n) -> bytes: ...\ndef scrypt(\n    password: ReadableBuffer, *, salt: ReadableBuffer, n: int, r: int, p: int, maxmem: int = 0, dklen: int = 64\n) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_heapq.pyi",
    "content": "import sys\nfrom _typeshed import SupportsRichComparisonT as _T  # All type variable use in this module requires comparability.\nfrom typing import Final\n\n__about__: Final[str]\n\ndef heapify(heap: list[_T], /) -> None: ...\ndef heappop(heap: list[_T], /) -> _T: ...\ndef heappush(heap: list[_T], item: _T, /) -> None: ...\ndef heappushpop(heap: list[_T], item: _T, /) -> _T: ...\ndef heapreplace(heap: list[_T], item: _T, /) -> _T: ...\n\nif sys.version_info >= (3, 14):\n    def heapify_max(heap: list[_T], /) -> None: ...\n    def heappop_max(heap: list[_T], /) -> _T: ...\n    def heappush_max(heap: list[_T], item: _T, /) -> None: ...\n    def heappushpop_max(heap: list[_T], item: _T, /) -> _T: ...\n    def heapreplace_max(heap: list[_T], item: _T, /) -> _T: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_imp.pyi",
    "content": "import sys\nimport types\nfrom _typeshed import ReadableBuffer\nfrom importlib.machinery import ModuleSpec\nfrom typing import Any\n\ncheck_hash_based_pycs: str\nif sys.version_info >= (3, 14):\n    pyc_magic_number_token: int\n\ndef source_hash(key: int, source: ReadableBuffer) -> bytes: ...\ndef create_builtin(spec: ModuleSpec, /) -> types.ModuleType: ...\ndef create_dynamic(spec: ModuleSpec, file: Any = None, /) -> types.ModuleType: ...\ndef acquire_lock() -> None: ...\ndef exec_builtin(mod: types.ModuleType, /) -> int: ...\ndef exec_dynamic(mod: types.ModuleType, /) -> int: ...\ndef extension_suffixes() -> list[str]: ...\ndef init_frozen(name: str, /) -> types.ModuleType: ...\ndef is_builtin(name: str, /) -> int: ...\ndef is_frozen(name: str, /) -> bool: ...\ndef is_frozen_package(name: str, /) -> bool: ...\ndef lock_held() -> bool: ...\ndef release_lock() -> None: ...\n\nif sys.version_info >= (3, 11):\n    def find_frozen(name: str, /, *, withdata: bool = False) -> tuple[memoryview | None, bool, str | None] | None: ...\n    def get_frozen_object(name: str, data: ReadableBuffer | None = None, /) -> types.CodeType: ...\n\nelse:\n    def get_frozen_object(name: str, /) -> types.CodeType: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_interpchannels.pyi",
    "content": "from _typeshed import structseq\nfrom typing import Any, Final, Literal, SupportsIndex, final\nfrom typing_extensions import Buffer, Self\n\nclass ChannelError(RuntimeError): ...\nclass ChannelClosedError(ChannelError): ...\nclass ChannelEmptyError(ChannelError): ...\nclass ChannelNotEmptyError(ChannelError): ...\nclass ChannelNotFoundError(ChannelError): ...\n\n# Mark as final, since instantiating ChannelID is not supported.\n@final\nclass ChannelID:\n    @property\n    def end(self) -> Literal[\"send\", \"recv\", \"both\"]: ...\n    @property\n    def send(self) -> Self: ...\n    @property\n    def recv(self) -> Self: ...\n    def __eq__(self, other: object, /) -> bool: ...\n    def __ge__(self, other: ChannelID, /) -> bool: ...\n    def __gt__(self, other: ChannelID, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __index__(self) -> int: ...\n    def __int__(self) -> int: ...\n    def __le__(self, other: ChannelID, /) -> bool: ...\n    def __lt__(self, other: ChannelID, /) -> bool: ...\n    def __ne__(self, other: object, /) -> bool: ...\n\n@final\nclass ChannelInfo(structseq[int], tuple[bool, bool, bool, int, int, int, int, int]):\n    __match_args__: Final = (\n        \"open\",\n        \"closing\",\n        \"closed\",\n        \"count\",\n        \"num_interp_send\",\n        \"num_interp_send_released\",\n        \"num_interp_recv\",\n        \"num_interp_recv_released\",\n    )\n    @property\n    def open(self) -> bool: ...\n    @property\n    def closing(self) -> bool: ...\n    @property\n    def closed(self) -> bool: ...\n    @property\n    def count(self) -> int: ...  # type: ignore[override]\n    @property\n    def num_interp_send(self) -> int: ...\n    @property\n    def num_interp_send_released(self) -> int: ...\n    @property\n    def num_interp_recv(self) -> int: ...\n    @property\n    def num_interp_recv_released(self) -> int: ...\n    @property\n    def num_interp_both(self) -> int: ...\n    @property\n    def num_interp_both_recv_released(self) -> int: ...\n    @property\n    def num_interp_both_send_released(self) -> int: ...\n    @property\n    def num_interp_both_released(self) -> int: ...\n    @property\n    def recv_associated(self) -> bool: ...\n    @property\n    def recv_released(self) -> bool: ...\n    @property\n    def send_associated(self) -> bool: ...\n    @property\n    def send_released(self) -> bool: ...\n\ndef create(unboundop: Literal[1, 2, 3]) -> ChannelID: ...\ndef destroy(cid: SupportsIndex) -> None: ...\ndef list_all() -> list[ChannelID]: ...\ndef list_interpreters(cid: SupportsIndex, *, send: bool) -> list[int]: ...\ndef send(cid: SupportsIndex, obj: object, *, blocking: bool = True, timeout: float | None = None) -> None: ...\ndef send_buffer(cid: SupportsIndex, obj: Buffer, *, blocking: bool = True, timeout: float | None = None) -> None: ...\ndef recv(cid: SupportsIndex, default: object = ...) -> tuple[Any, Literal[1, 2, 3]]: ...\ndef close(cid: SupportsIndex, *, send: bool = False, recv: bool = False) -> None: ...\ndef get_count(cid: SupportsIndex) -> int: ...\ndef get_info(cid: SupportsIndex) -> ChannelInfo: ...\ndef get_channel_defaults(cid: SupportsIndex) -> Literal[1, 2, 3]: ...\ndef release(cid: SupportsIndex, *, send: bool = False, recv: bool = False, force: bool = False) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_interpqueues.pyi",
    "content": "from typing import Any, Literal, SupportsIndex\nfrom typing_extensions import TypeAlias\n\n_UnboundOp: TypeAlias = Literal[1, 2, 3]\n\nclass QueueError(RuntimeError): ...\nclass QueueNotFoundError(QueueError): ...\n\ndef bind(qid: SupportsIndex) -> None: ...\ndef create(maxsize: SupportsIndex, fmt: SupportsIndex, unboundop: _UnboundOp) -> int: ...\ndef destroy(qid: SupportsIndex) -> None: ...\ndef get(qid: SupportsIndex) -> tuple[Any, int, _UnboundOp | None]: ...\ndef get_count(qid: SupportsIndex) -> int: ...\ndef get_maxsize(qid: SupportsIndex) -> int: ...\ndef get_queue_defaults(qid: SupportsIndex) -> tuple[int, _UnboundOp]: ...\ndef is_full(qid: SupportsIndex) -> bool: ...\ndef list_all() -> list[tuple[int, int, _UnboundOp]]: ...\ndef put(qid: SupportsIndex, obj: Any, fmt: SupportsIndex, unboundop: _UnboundOp) -> None: ...\ndef release(qid: SupportsIndex) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_interpreters.pyi",
    "content": "import types\nfrom collections.abc import Callable\nfrom typing import Any, Final, Literal, SupportsIndex, TypeVar, overload\nfrom typing_extensions import TypeAlias, disjoint_base\n\n_R = TypeVar(\"_R\")\n\n_Configs: TypeAlias = Literal[\"default\", \"isolated\", \"legacy\", \"empty\", \"\"]\n_SharedDict: TypeAlias = dict[str, Any]  # many objects can be shared\n\nclass InterpreterError(Exception): ...\nclass InterpreterNotFoundError(InterpreterError): ...\nclass NotShareableError(ValueError): ...\n\n@disjoint_base\nclass CrossInterpreterBufferView:\n    def __buffer__(self, flags: int, /) -> memoryview: ...\n\ndef new_config(name: _Configs = \"isolated\", /, **overides: object) -> types.SimpleNamespace: ...\ndef create(config: types.SimpleNamespace | _Configs | None = \"isolated\", *, reqrefs: bool = False) -> int: ...\ndef destroy(id: SupportsIndex, *, restrict: bool = False) -> None: ...\ndef list_all(*, require_ready: bool = False) -> list[tuple[int, _Whence]]: ...\ndef get_current() -> tuple[int, _Whence]: ...\ndef get_main() -> tuple[int, _Whence]: ...\ndef is_running(id: SupportsIndex, *, restrict: bool = False) -> bool: ...\ndef get_config(id: SupportsIndex, *, restrict: bool = False) -> types.SimpleNamespace: ...\ndef whence(id: SupportsIndex) -> _Whence: ...\ndef exec(\n    id: SupportsIndex, code: str | types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False\n) -> None | types.SimpleNamespace: ...\ndef call(\n    id: SupportsIndex,\n    callable: Callable[..., _R],\n    args: tuple[Any, ...] = (),\n    kwargs: dict[str, Any] = {},\n    *,\n    preserve_exc: bool = False,\n    restrict: bool = False,\n) -> tuple[_R, types.SimpleNamespace]: ...\ndef run_string(\n    id: SupportsIndex, script: str | types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False\n) -> None: ...\ndef run_func(\n    id: SupportsIndex, func: types.CodeType | Callable[[], object], shared: _SharedDict = {}, *, restrict: bool = False\n) -> None: ...\ndef set___main___attrs(id: SupportsIndex, updates: _SharedDict, *, restrict: bool = False) -> None: ...\ndef incref(id: SupportsIndex, *, implieslink: bool = False, restrict: bool = False) -> None: ...\ndef decref(id: SupportsIndex, *, restrict: bool = False) -> None: ...\ndef is_shareable(obj: object) -> bool: ...\n@overload\ndef capture_exception(exc: BaseException) -> types.SimpleNamespace: ...\n@overload\ndef capture_exception(exc: None = None) -> types.SimpleNamespace | None: ...\n\n_Whence: TypeAlias = Literal[0, 1, 2, 3, 4, 5]\nWHENCE_UNKNOWN: Final = 0\nWHENCE_RUNTIME: Final = 1\nWHENCE_LEGACY_CAPI: Final = 2\nWHENCE_CAPI: Final = 3\nWHENCE_XI: Final = 4\nWHENCE_STDLIB: Final = 5\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_io.pyi",
    "content": "import builtins\nimport codecs\nimport sys\nfrom _typeshed import FileDescriptorOrPath, MaybeNone, ReadableBuffer, WriteableBuffer\nfrom collections.abc import Callable, Iterable, Iterator\nfrom io import BufferedIOBase, RawIOBase, TextIOBase, UnsupportedOperation as UnsupportedOperation\nfrom os import _Opener\nfrom types import TracebackType\nfrom typing import IO, Any, BinaryIO, Final, Generic, Literal, Protocol, TextIO, TypeVar, overload, type_check_only\nfrom typing_extensions import Self, disjoint_base\n\n_T = TypeVar(\"_T\")\n\nif sys.version_info >= (3, 14):\n    DEFAULT_BUFFER_SIZE: Final = 131072\nelse:\n    DEFAULT_BUFFER_SIZE: Final = 8192\n\nopen = builtins.open\n\ndef open_code(path: str) -> IO[bytes]: ...\n\nBlockingIOError = builtins.BlockingIOError\n\nif sys.version_info >= (3, 12):\n    @disjoint_base\n    class _IOBase:\n        def __iter__(self) -> Iterator[bytes]: ...\n        def __next__(self) -> bytes: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(\n            self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n        ) -> None: ...\n        def close(self) -> None: ...\n        def fileno(self) -> int: ...\n        def flush(self) -> None: ...\n        def isatty(self) -> bool: ...\n        def readable(self) -> bool: ...\n        read: Callable[..., Any]\n        def readlines(self, hint: int = -1, /) -> list[bytes]: ...\n        def seek(self, offset: int, whence: int = 0, /) -> int: ...\n        def seekable(self) -> bool: ...\n        def tell(self) -> int: ...\n        def truncate(self, size: int | None = None, /) -> int: ...\n        def writable(self) -> bool: ...\n        write: Callable[..., Any]\n        def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ...\n        def readline(self, size: int | None = -1, /) -> bytes: ...\n        def __del__(self) -> None: ...\n        @property\n        def closed(self) -> bool: ...\n        def _checkClosed(self) -> None: ...  # undocumented\n\nelse:\n    class _IOBase:\n        def __iter__(self) -> Iterator[bytes]: ...\n        def __next__(self) -> bytes: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(\n            self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n        ) -> None: ...\n        def close(self) -> None: ...\n        def fileno(self) -> int: ...\n        def flush(self) -> None: ...\n        def isatty(self) -> bool: ...\n        def readable(self) -> bool: ...\n        read: Callable[..., Any]\n        def readlines(self, hint: int = -1, /) -> list[bytes]: ...\n        def seek(self, offset: int, whence: int = 0, /) -> int: ...\n        def seekable(self) -> bool: ...\n        def tell(self) -> int: ...\n        def truncate(self, size: int | None = None, /) -> int: ...\n        def writable(self) -> bool: ...\n        write: Callable[..., Any]\n        def writelines(self, lines: Iterable[ReadableBuffer], /) -> None: ...\n        def readline(self, size: int | None = -1, /) -> bytes: ...\n        def __del__(self) -> None: ...\n        @property\n        def closed(self) -> bool: ...\n        def _checkClosed(self) -> None: ...  # undocumented\n\nclass _RawIOBase(_IOBase):\n    def readall(self) -> bytes: ...\n    # The following methods can return None if the file is in non-blocking mode\n    # and no data is available.\n    def readinto(self, buffer: WriteableBuffer, /) -> int | MaybeNone: ...\n    def write(self, b: ReadableBuffer, /) -> int | MaybeNone: ...\n    def read(self, size: int = -1, /) -> bytes | MaybeNone: ...\n\nclass _BufferedIOBase(_IOBase):\n    def detach(self) -> RawIOBase: ...\n    def readinto(self, buffer: WriteableBuffer, /) -> int: ...\n    def write(self, buffer: ReadableBuffer, /) -> int: ...\n    def readinto1(self, buffer: WriteableBuffer, /) -> int: ...\n    def read(self, size: int | None = -1, /) -> bytes: ...\n    def read1(self, size: int = -1, /) -> bytes: ...\n\n@disjoint_base\nclass FileIO(RawIOBase, _RawIOBase, BinaryIO):  # type: ignore[misc]  # incompatible definitions of writelines in the base classes\n    mode: str\n    # The type of \"name\" equals the argument passed in to the constructor,\n    # but that can make FileIO incompatible with other I/O types that assume\n    # \"name\" is a str. In the future, making FileIO generic might help.\n    name: Any\n    def __init__(\n        self, file: FileDescriptorOrPath, mode: str = \"r\", closefd: bool = True, opener: _Opener | None = None\n    ) -> None: ...\n    @property\n    def closefd(self) -> bool: ...\n    def seek(self, pos: int, whence: int = 0, /) -> int: ...\n    def read(self, size: int | None = -1, /) -> bytes | MaybeNone: ...\n\n@disjoint_base\nclass BytesIO(BufferedIOBase, _BufferedIOBase, BinaryIO):  # type: ignore[misc]  # incompatible definitions of methods in the base classes\n    def __init__(self, initial_bytes: ReadableBuffer = b\"\") -> None: ...\n    # BytesIO does not contain a \"name\" field. This workaround is necessary\n    # to allow BytesIO sub-classes to add this field, as it is defined\n    # as a read-only property on IO[].\n    name: Any\n    def getvalue(self) -> bytes: ...\n    def getbuffer(self) -> memoryview: ...\n    def read1(self, size: int | None = -1, /) -> bytes: ...\n    def readlines(self, size: int | None = None, /) -> list[bytes]: ...\n    def seek(self, pos: int, whence: int = 0, /) -> int: ...\n\n@type_check_only\nclass _BufferedReaderStream(Protocol):\n    def read(self, n: int = ..., /) -> bytes: ...\n    # Optional: def readall(self) -> bytes: ...\n    def readinto(self, b: memoryview, /) -> int | None: ...\n    def seek(self, pos: int, whence: int, /) -> int: ...\n    def tell(self) -> int: ...\n    def truncate(self, size: int, /) -> int: ...\n    def flush(self) -> object: ...\n    def close(self) -> object: ...\n    @property\n    def closed(self) -> bool: ...\n    def readable(self) -> bool: ...\n    def seekable(self) -> bool: ...\n\n    # The following methods just pass through to the underlying stream. Since\n    # not all streams support them, they are marked as optional here, and will\n    # raise an AttributeError if called on a stream that does not support them.\n\n    # @property\n    # def name(self) -> Any: ...  # Type is inconsistent between the various I/O types.\n    # @property\n    # def mode(self) -> str: ...\n    # def fileno(self) -> int: ...\n    # def isatty(self) -> bool: ...\n\n_BufferedReaderStreamT = TypeVar(\"_BufferedReaderStreamT\", bound=_BufferedReaderStream, default=_BufferedReaderStream)\n\n@disjoint_base\nclass BufferedReader(BufferedIOBase, _BufferedIOBase, BinaryIO, Generic[_BufferedReaderStreamT]):  # type: ignore[misc]  # incompatible definitions of methods in the base classes\n    raw: _BufferedReaderStreamT\n    if sys.version_info >= (3, 14):\n        def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 131072) -> None: ...\n    else:\n        def __init__(self, raw: _BufferedReaderStreamT, buffer_size: int = 8192) -> None: ...\n\n    def peek(self, size: int = 0, /) -> bytes: ...\n    def seek(self, target: int, whence: int = 0, /) -> int: ...\n    def truncate(self, pos: int | None = None, /) -> int: ...\n\n@disjoint_base\nclass BufferedWriter(BufferedIOBase, _BufferedIOBase, BinaryIO):  # type: ignore[misc]  # incompatible definitions of writelines in the base classes\n    raw: RawIOBase\n    if sys.version_info >= (3, 14):\n        def __init__(self, raw: RawIOBase, buffer_size: int = 131072) -> None: ...\n    else:\n        def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ...\n\n    def write(self, buffer: ReadableBuffer, /) -> int: ...\n    def seek(self, target: int, whence: int = 0, /) -> int: ...\n    def truncate(self, pos: int | None = None, /) -> int: ...\n\n@disjoint_base\nclass BufferedRandom(BufferedIOBase, _BufferedIOBase, BinaryIO):  # type: ignore[misc]  # incompatible definitions of methods in the base classes\n    mode: str\n    name: Any\n    raw: RawIOBase\n    if sys.version_info >= (3, 14):\n        def __init__(self, raw: RawIOBase, buffer_size: int = 131072) -> None: ...\n    else:\n        def __init__(self, raw: RawIOBase, buffer_size: int = 8192) -> None: ...\n\n    def seek(self, target: int, whence: int = 0, /) -> int: ...  # stubtest needs this\n    def peek(self, size: int = 0, /) -> bytes: ...\n    def truncate(self, pos: int | None = None, /) -> int: ...\n\n@disjoint_base\nclass BufferedRWPair(BufferedIOBase, _BufferedIOBase, Generic[_BufferedReaderStreamT]):\n    if sys.version_info >= (3, 14):\n        def __init__(self, reader: _BufferedReaderStreamT, writer: RawIOBase, buffer_size: int = 131072, /) -> None: ...\n    else:\n        def __init__(self, reader: _BufferedReaderStreamT, writer: RawIOBase, buffer_size: int = 8192, /) -> None: ...\n\n    def peek(self, size: int = 0, /) -> bytes: ...\n\nclass _TextIOBase(_IOBase):\n    encoding: str\n    errors: str | None\n    newlines: str | tuple[str, ...] | None\n    def __iter__(self) -> Iterator[str]: ...  # type: ignore[override]\n    def __next__(self) -> str: ...  # type: ignore[override]\n    def detach(self) -> BinaryIO: ...\n    def write(self, s: str, /) -> int: ...\n    def writelines(self, lines: Iterable[str], /) -> None: ...  # type: ignore[override]\n    def readline(self, size: int = -1, /) -> str: ...  # type: ignore[override]\n    def readlines(self, hint: int = -1, /) -> list[str]: ...  # type: ignore[override]\n    def read(self, size: int | None = -1, /) -> str: ...\n\n@type_check_only\nclass _WrappedBuffer(Protocol):\n    # \"name\" is wrapped by TextIOWrapper. Its type is inconsistent between\n    # the various I/O types.\n    @property\n    def name(self) -> Any: ...\n    @property\n    def closed(self) -> bool: ...\n    def read(self, size: int = ..., /) -> ReadableBuffer: ...\n    # Optional: def read1(self, size: int, /) -> ReadableBuffer: ...\n    def write(self, b: bytes, /) -> object: ...\n    def flush(self) -> object: ...\n    def close(self) -> object: ...\n    def seekable(self) -> bool: ...\n    def readable(self) -> bool: ...\n    def writable(self) -> bool: ...\n    def truncate(self, size: int, /) -> int: ...\n    def fileno(self) -> int: ...\n    def isatty(self) -> bool: ...\n    # Optional: Only needs to be present if seekable() returns True.\n    # def seek(self, offset: Literal[0], whence: Literal[2]) -> int: ...\n    # def tell(self) -> int: ...\n\n_BufferT_co = TypeVar(\"_BufferT_co\", bound=_WrappedBuffer, default=_WrappedBuffer, covariant=True)\n\n@disjoint_base\nclass TextIOWrapper(TextIOBase, _TextIOBase, TextIO, Generic[_BufferT_co]):  # type: ignore[misc]  # incompatible definitions of write in the base classes\n    def __init__(\n        self,\n        buffer: _BufferT_co,\n        encoding: str | None = None,\n        errors: str | None = None,\n        newline: str | None = None,\n        line_buffering: bool = False,\n        write_through: bool = False,\n    ) -> None: ...\n    # Equals the \"buffer\" argument passed in to the constructor.\n    @property\n    def buffer(self) -> _BufferT_co: ...  # type: ignore[override]\n    @property\n    def line_buffering(self) -> bool: ...\n    @property\n    def write_through(self) -> bool: ...\n    def reconfigure(\n        self,\n        *,\n        encoding: str | None = None,\n        errors: str | None = None,\n        newline: str | None = None,\n        line_buffering: bool | None = None,\n        write_through: bool | None = None,\n    ) -> None: ...\n    def readline(self, size: int = -1, /) -> str: ...  # type: ignore[override]\n    # Equals the \"buffer\" argument passed in to the constructor.\n    def detach(self) -> _BufferT_co: ...  # type: ignore[override]\n    # TextIOWrapper's version of seek only supports a limited subset of\n    # operations.\n    def seek(self, cookie: int, whence: int = 0, /) -> int: ...\n    def truncate(self, pos: int | None = None, /) -> int: ...\n\n@disjoint_base\nclass StringIO(TextIOBase, _TextIOBase, TextIO):  # type: ignore[misc]  # incompatible definitions of write in the base classes\n    def __init__(self, initial_value: str | None = \"\", newline: str | None = \"\\n\") -> None: ...\n    # StringIO does not contain a \"name\" field. This workaround is necessary\n    # to allow StringIO sub-classes to add this field, as it is defined\n    # as a read-only property on IO[].\n    name: Any\n    def getvalue(self) -> str: ...\n    @property\n    def line_buffering(self) -> bool: ...\n    def seek(self, pos: int, whence: int = 0, /) -> int: ...\n    def truncate(self, pos: int | None = None, /) -> int: ...\n\n@disjoint_base\nclass IncrementalNewlineDecoder:\n    def __init__(self, decoder: codecs.IncrementalDecoder | None, translate: bool, errors: str = \"strict\") -> None: ...\n    def decode(self, input: ReadableBuffer | str, final: bool = False) -> str: ...\n    @property\n    def newlines(self) -> str | tuple[str, ...] | None: ...\n    def getstate(self) -> tuple[bytes, int]: ...\n    def reset(self) -> None: ...\n    def setstate(self, state: tuple[bytes, int], /) -> None: ...\n\nif sys.version_info >= (3, 10):\n    @overload\n    def text_encoding(encoding: None, stacklevel: int = 2, /) -> Literal[\"locale\", \"utf-8\"]: ...\n    @overload\n    def text_encoding(encoding: _T, stacklevel: int = 2, /) -> _T: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_json.pyi",
    "content": "from collections.abc import Callable\nfrom typing import Any, final\nfrom typing_extensions import Self\n\n@final\nclass make_encoder:\n    @property\n    def sort_keys(self) -> bool: ...\n    @property\n    def skipkeys(self) -> bool: ...\n    @property\n    def key_separator(self) -> str: ...\n    @property\n    def indent(self) -> str | None: ...\n    @property\n    def markers(self) -> dict[int, Any] | None: ...\n    @property\n    def default(self) -> Callable[[Any], Any]: ...\n    @property\n    def encoder(self) -> Callable[[str], str]: ...\n    @property\n    def item_separator(self) -> str: ...\n    def __new__(\n        cls,\n        markers: dict[int, Any] | None,\n        default: Callable[[Any], Any],\n        encoder: Callable[[str], str],\n        indent: str | None,\n        key_separator: str,\n        item_separator: str,\n        sort_keys: bool,\n        skipkeys: bool,\n        allow_nan: bool,\n    ) -> Self: ...\n    def __call__(self, obj: object, _current_indent_level: int) -> Any: ...\n\n@final\nclass make_scanner:\n    object_hook: Any\n    object_pairs_hook: Any\n    parse_int: Any\n    parse_constant: Any\n    parse_float: Any\n    strict: bool\n    # TODO: 'context' needs the attrs above (ducktype), but not __call__.\n    def __new__(cls, context: make_scanner) -> Self: ...\n    def __call__(self, string: str, index: int) -> tuple[Any, int]: ...\n\ndef encode_basestring(s: str, /) -> str: ...\ndef encode_basestring_ascii(s: str, /) -> str: ...\ndef scanstring(string: str, end: int, strict: bool = True) -> tuple[str, int]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_locale.pyi",
    "content": "import sys\nfrom _typeshed import StrPath\nfrom typing import Final, Literal, TypedDict, type_check_only\n\n@type_check_only\nclass _LocaleConv(TypedDict):\n    decimal_point: str\n    grouping: list[int]\n    thousands_sep: str\n    int_curr_symbol: str\n    currency_symbol: str\n    p_cs_precedes: Literal[0, 1, 127]\n    n_cs_precedes: Literal[0, 1, 127]\n    p_sep_by_space: Literal[0, 1, 127]\n    n_sep_by_space: Literal[0, 1, 127]\n    mon_decimal_point: str\n    frac_digits: int\n    int_frac_digits: int\n    mon_thousands_sep: str\n    mon_grouping: list[int]\n    positive_sign: str\n    negative_sign: str\n    p_sign_posn: Literal[0, 1, 2, 3, 4, 127]\n    n_sign_posn: Literal[0, 1, 2, 3, 4, 127]\n\nLC_CTYPE: Final[int]\nLC_COLLATE: Final[int]\nLC_TIME: Final[int]\nLC_MONETARY: Final[int]\nLC_NUMERIC: Final[int]\nLC_ALL: Final[int]\nCHAR_MAX: Final = 127\n\ndef setlocale(category: int, locale: str | None = None, /) -> str: ...\ndef localeconv() -> _LocaleConv: ...\n\nif sys.version_info >= (3, 11):\n    def getencoding() -> str: ...\n\ndef strcoll(os1: str, os2: str, /) -> int: ...\ndef strxfrm(string: str, /) -> str: ...\n\n# native gettext functions\n# https://docs.python.org/3/library/locale.html#access-to-message-catalogs\n# https://github.com/python/cpython/blob/f4c03484da59049eb62a9bf7777b963e2267d187/Modules/_localemodule.c#L626\nif sys.platform != \"win32\":\n    LC_MESSAGES: int\n\n    ABDAY_1: Final[int]\n    ABDAY_2: Final[int]\n    ABDAY_3: Final[int]\n    ABDAY_4: Final[int]\n    ABDAY_5: Final[int]\n    ABDAY_6: Final[int]\n    ABDAY_7: Final[int]\n\n    ABMON_1: Final[int]\n    ABMON_2: Final[int]\n    ABMON_3: Final[int]\n    ABMON_4: Final[int]\n    ABMON_5: Final[int]\n    ABMON_6: Final[int]\n    ABMON_7: Final[int]\n    ABMON_8: Final[int]\n    ABMON_9: Final[int]\n    ABMON_10: Final[int]\n    ABMON_11: Final[int]\n    ABMON_12: Final[int]\n\n    DAY_1: Final[int]\n    DAY_2: Final[int]\n    DAY_3: Final[int]\n    DAY_4: Final[int]\n    DAY_5: Final[int]\n    DAY_6: Final[int]\n    DAY_7: Final[int]\n\n    ERA: Final[int]\n    ERA_D_T_FMT: Final[int]\n    ERA_D_FMT: Final[int]\n    ERA_T_FMT: Final[int]\n\n    MON_1: Final[int]\n    MON_2: Final[int]\n    MON_3: Final[int]\n    MON_4: Final[int]\n    MON_5: Final[int]\n    MON_6: Final[int]\n    MON_7: Final[int]\n    MON_8: Final[int]\n    MON_9: Final[int]\n    MON_10: Final[int]\n    MON_11: Final[int]\n    MON_12: Final[int]\n\n    CODESET: Final[int]\n    D_T_FMT: Final[int]\n    D_FMT: Final[int]\n    T_FMT: Final[int]\n    T_FMT_AMPM: Final[int]\n    AM_STR: Final[int]\n    PM_STR: Final[int]\n\n    RADIXCHAR: Final[int]\n    THOUSEP: Final[int]\n    YESEXPR: Final[int]\n    NOEXPR: Final[int]\n    CRNCYSTR: Final[int]\n    ALT_DIGITS: Final[int]\n\n    def nl_langinfo(key: int, /) -> str: ...\n\n    # This is dependent on `libintl.h` which is a part of `gettext`\n    # system dependency. These functions might be missing.\n    # But, we always say that they are present.\n    def gettext(msg: str, /) -> str: ...\n    def dgettext(domain: str | None, msg: str, /) -> str: ...\n    def dcgettext(domain: str | None, msg: str, category: int, /) -> str: ...\n    def textdomain(domain: str | None, /) -> str: ...\n    def bindtextdomain(domain: str, dir: StrPath | None, /) -> str: ...\n    def bind_textdomain_codeset(domain: str, codeset: str | None, /) -> str | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_lsprof.pyi",
    "content": "import sys\nfrom _typeshed import structseq\nfrom collections.abc import Callable\nfrom types import CodeType\nfrom typing import Any, Final, final\nfrom typing_extensions import disjoint_base\n\n@disjoint_base\nclass Profiler:\n    def __init__(\n        self, timer: Callable[[], float] | None = None, timeunit: float = 0.0, subcalls: bool = True, builtins: bool = True\n    ) -> None: ...\n    def getstats(self) -> list[profiler_entry]: ...\n    def enable(self, subcalls: bool = True, builtins: bool = True) -> None: ...\n    def disable(self) -> None: ...\n    def clear(self) -> None: ...\n\n@final\nclass profiler_entry(structseq[Any], tuple[CodeType | str, int, int, float, float, list[profiler_subentry]]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"code\", \"callcount\", \"reccallcount\", \"totaltime\", \"inlinetime\", \"calls\")\n    code: CodeType | str\n    callcount: int\n    reccallcount: int\n    totaltime: float\n    inlinetime: float\n    calls: list[profiler_subentry]\n\n@final\nclass profiler_subentry(structseq[Any], tuple[CodeType | str, int, int, float, float]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"code\", \"callcount\", \"reccallcount\", \"totaltime\", \"inlinetime\")\n    code: CodeType | str\n    callcount: int\n    reccallcount: int\n    totaltime: float\n    inlinetime: float\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_lzma.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Mapping, Sequence\nfrom typing import Any, Final, final\nfrom typing_extensions import Self, TypeAlias\n\n_FilterChain: TypeAlias = Sequence[Mapping[str, Any]]\n\nFORMAT_AUTO: Final = 0\nFORMAT_XZ: Final = 1\nFORMAT_ALONE: Final = 2\nFORMAT_RAW: Final = 3\nCHECK_NONE: Final = 0\nCHECK_CRC32: Final = 1\nCHECK_CRC64: Final = 4\nCHECK_SHA256: Final = 10\nCHECK_ID_MAX: Final = 15\nCHECK_UNKNOWN: Final = 16\nFILTER_LZMA1: Final[int]  # v big number\nFILTER_LZMA2: Final = 33\nFILTER_DELTA: Final = 3\nFILTER_X86: Final = 4\nFILTER_IA64: Final = 6\nFILTER_ARM: Final = 7\nFILTER_ARMTHUMB: Final = 8\nFILTER_SPARC: Final = 9\nFILTER_POWERPC: Final = 5\nMF_HC3: Final = 3\nMF_HC4: Final = 4\nMF_BT2: Final = 18\nMF_BT3: Final = 19\nMF_BT4: Final = 20\nMODE_FAST: Final = 1\nMODE_NORMAL: Final = 2\nPRESET_DEFAULT: Final = 6\nPRESET_EXTREME: Final[int]  # v big number\n\n@final\nclass LZMADecompressor:\n    if sys.version_info >= (3, 12):\n        def __new__(cls, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None) -> Self: ...\n    else:\n        def __init__(self, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None) -> None: ...\n\n    def decompress(self, data: ReadableBuffer, max_length: int = -1) -> bytes: ...\n    @property\n    def check(self) -> int: ...\n    @property\n    def eof(self) -> bool: ...\n    @property\n    def unused_data(self) -> bytes: ...\n    @property\n    def needs_input(self) -> bool: ...\n\n@final\nclass LZMACompressor:\n    if sys.version_info >= (3, 12):\n        def __new__(\n            cls, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None\n        ) -> Self: ...\n    else:\n        def __init__(\n            self, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None\n        ) -> None: ...\n\n    def compress(self, data: ReadableBuffer, /) -> bytes: ...\n    def flush(self) -> bytes: ...\n\nclass LZMAError(Exception): ...\n\ndef is_check_supported(check_id: int, /) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_markupbase.pyi",
    "content": "import sys\nfrom typing import Any\n\nclass ParserBase:\n    def reset(self) -> None: ...\n    def getpos(self) -> tuple[int, int]: ...\n    def unknown_decl(self, data: str) -> None: ...\n    def parse_comment(self, i: int, report: bool = True) -> int: ...  # undocumented\n    def parse_declaration(self, i: int) -> int: ...  # undocumented\n    def parse_marked_section(self, i: int, report: bool = True) -> int: ...  # undocumented\n    def updatepos(self, i: int, j: int) -> int: ...  # undocumented\n    if sys.version_info < (3, 10):\n        # Removed from ParserBase: https://bugs.python.org/issue31844\n        def error(self, message: str) -> Any: ...  # undocumented\n    lineno: int  # undocumented\n    offset: int  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_msi.pyi",
    "content": "import sys\nfrom typing import Final, type_check_only\n\nif sys.platform == \"win32\":\n    class MSIError(Exception): ...\n    # Actual typename View, not exposed by the implementation\n    @type_check_only\n    class _View:\n        def Execute(self, params: _Record | None = ...) -> None: ...\n        def GetColumnInfo(self, kind: int) -> _Record: ...\n        def Fetch(self) -> _Record: ...\n        def Modify(self, mode: int, record: _Record) -> None: ...\n        def Close(self) -> None: ...\n        # Don't exist at runtime\n        __new__: None  # type: ignore[assignment]\n        __init__: None  # type: ignore[assignment]\n\n    # Actual typename SummaryInformation, not exposed by the implementation\n    @type_check_only\n    class _SummaryInformation:\n        def GetProperty(self, field: int) -> int | bytes | None: ...\n        def GetPropertyCount(self) -> int: ...\n        def SetProperty(self, field: int, value: int | str) -> None: ...\n        def Persist(self) -> None: ...\n        # Don't exist at runtime\n        __new__: None  # type: ignore[assignment]\n        __init__: None  # type: ignore[assignment]\n\n    # Actual typename Database, not exposed by the implementation\n    @type_check_only\n    class _Database:\n        def OpenView(self, sql: str) -> _View: ...\n        def Commit(self) -> None: ...\n        def GetSummaryInformation(self, updateCount: int) -> _SummaryInformation: ...\n        def Close(self) -> None: ...\n        # Don't exist at runtime\n        __new__: None  # type: ignore[assignment]\n        __init__: None  # type: ignore[assignment]\n\n    # Actual typename Record, not exposed by the implementation\n    @type_check_only\n    class _Record:\n        def GetFieldCount(self) -> int: ...\n        def GetInteger(self, field: int) -> int: ...\n        def GetString(self, field: int) -> str: ...\n        def SetString(self, field: int, str: str) -> None: ...\n        def SetStream(self, field: int, stream: str) -> None: ...\n        def SetInteger(self, field: int, int: int) -> None: ...\n        def ClearData(self) -> None: ...\n        # Don't exist at runtime\n        __new__: None  # type: ignore[assignment]\n        __init__: None  # type: ignore[assignment]\n\n    def UuidCreate() -> str: ...\n    def FCICreate(cabname: str, files: list[str], /) -> None: ...\n    def OpenDatabase(path: str, persist: int, /) -> _Database: ...\n    def CreateRecord(count: int, /) -> _Record: ...\n\n    MSICOLINFO_NAMES: Final[int]\n    MSICOLINFO_TYPES: Final[int]\n    MSIDBOPEN_CREATE: Final[int]\n    MSIDBOPEN_CREATEDIRECT: Final[int]\n    MSIDBOPEN_DIRECT: Final[int]\n    MSIDBOPEN_PATCHFILE: Final[int]\n    MSIDBOPEN_READONLY: Final[int]\n    MSIDBOPEN_TRANSACT: Final[int]\n    MSIMODIFY_ASSIGN: Final[int]\n    MSIMODIFY_DELETE: Final[int]\n    MSIMODIFY_INSERT: Final[int]\n    MSIMODIFY_INSERT_TEMPORARY: Final[int]\n    MSIMODIFY_MERGE: Final[int]\n    MSIMODIFY_REFRESH: Final[int]\n    MSIMODIFY_REPLACE: Final[int]\n    MSIMODIFY_SEEK: Final[int]\n    MSIMODIFY_UPDATE: Final[int]\n    MSIMODIFY_VALIDATE: Final[int]\n    MSIMODIFY_VALIDATE_DELETE: Final[int]\n    MSIMODIFY_VALIDATE_FIELD: Final[int]\n    MSIMODIFY_VALIDATE_NEW: Final[int]\n\n    PID_APPNAME: Final[int]\n    PID_AUTHOR: Final[int]\n    PID_CHARCOUNT: Final[int]\n    PID_CODEPAGE: Final[int]\n    PID_COMMENTS: Final[int]\n    PID_CREATE_DTM: Final[int]\n    PID_KEYWORDS: Final[int]\n    PID_LASTAUTHOR: Final[int]\n    PID_LASTPRINTED: Final[int]\n    PID_LASTSAVE_DTM: Final[int]\n    PID_PAGECOUNT: Final[int]\n    PID_REVNUMBER: Final[int]\n    PID_SECURITY: Final[int]\n    PID_SUBJECT: Final[int]\n    PID_TEMPLATE: Final[int]\n    PID_TITLE: Final[int]\n    PID_WORDCOUNT: Final[int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_multibytecodec.pyi",
    "content": "from _typeshed import ReadableBuffer\nfrom codecs import _ReadableStream, _WritableStream\nfrom collections.abc import Iterable\nfrom typing import final, type_check_only\nfrom typing_extensions import disjoint_base\n\n# This class is not exposed. It calls itself _multibytecodec.MultibyteCodec.\n@final\n@type_check_only\nclass _MultibyteCodec:\n    def decode(self, input: ReadableBuffer, errors: str | None = None) -> str: ...\n    def encode(self, input: str, errors: str | None = None) -> bytes: ...\n\n@disjoint_base\nclass MultibyteIncrementalDecoder:\n    errors: str\n    def __init__(self, errors: str = \"strict\") -> None: ...\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n    def getstate(self) -> tuple[bytes, int]: ...\n    def reset(self) -> None: ...\n    def setstate(self, state: tuple[bytes, int], /) -> None: ...\n\n@disjoint_base\nclass MultibyteIncrementalEncoder:\n    errors: str\n    def __init__(self, errors: str = \"strict\") -> None: ...\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n    def getstate(self) -> int: ...\n    def reset(self) -> None: ...\n    def setstate(self, state: int, /) -> None: ...\n\n@disjoint_base\nclass MultibyteStreamReader:\n    errors: str\n    stream: _ReadableStream\n    def __init__(self, stream: _ReadableStream, errors: str = \"strict\") -> None: ...\n    def read(self, sizeobj: int | None = None, /) -> str: ...\n    def readline(self, sizeobj: int | None = None, /) -> str: ...\n    def readlines(self, sizehintobj: int | None = None, /) -> list[str]: ...\n    def reset(self) -> None: ...\n\n@disjoint_base\nclass MultibyteStreamWriter:\n    errors: str\n    stream: _WritableStream\n    def __init__(self, stream: _WritableStream, errors: str = \"strict\") -> None: ...\n    def reset(self) -> None: ...\n    def write(self, strobj: str, /) -> None: ...\n    def writelines(self, lines: Iterable[str], /) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_operator.pyi",
    "content": "import sys\nfrom _typeshed import SupportsGetItem\nfrom collections.abc import Callable, Container, Iterable, MutableMapping, MutableSequence, Sequence\nfrom operator import attrgetter as attrgetter, itemgetter as itemgetter, methodcaller as methodcaller\nfrom typing import Any, AnyStr, Protocol, SupportsAbs, SupportsIndex, TypeVar, overload, type_check_only\nfrom typing_extensions import ParamSpec, TypeAlias, TypeIs\n\n_R = TypeVar(\"_R\")\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_K = TypeVar(\"_K\")\n_V = TypeVar(\"_V\")\n_P = ParamSpec(\"_P\")\n\n# The following protocols return \"Any\" instead of bool, since the comparison\n# operators can be overloaded to return an arbitrary object. For example,\n# the numpy.array comparison dunders return another numpy.array.\n\n@type_check_only\nclass _SupportsDunderLT(Protocol):\n    def __lt__(self, other: Any, /) -> Any: ...\n\n@type_check_only\nclass _SupportsDunderGT(Protocol):\n    def __gt__(self, other: Any, /) -> Any: ...\n\n@type_check_only\nclass _SupportsDunderLE(Protocol):\n    def __le__(self, other: Any, /) -> Any: ...\n\n@type_check_only\nclass _SupportsDunderGE(Protocol):\n    def __ge__(self, other: Any, /) -> Any: ...\n\n_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT\n\n@type_check_only\nclass _SupportsInversion(Protocol[_T_co]):\n    def __invert__(self) -> _T_co: ...\n\n@type_check_only\nclass _SupportsNeg(Protocol[_T_co]):\n    def __neg__(self) -> _T_co: ...\n\n@type_check_only\nclass _SupportsPos(Protocol[_T_co]):\n    def __pos__(self) -> _T_co: ...\n\n# All four comparison functions must have the same signature, or we get false-positive errors\ndef lt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ...\ndef le(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ...\ndef eq(a: object, b: object, /) -> Any: ...\ndef ne(a: object, b: object, /) -> Any: ...\ndef ge(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ...\ndef gt(a: _SupportsComparison, b: _SupportsComparison, /) -> Any: ...\ndef not_(a: object, /) -> bool: ...\ndef truth(a: object, /) -> bool: ...\ndef is_(a: object, b: object, /) -> bool: ...\ndef is_not(a: object, b: object, /) -> bool: ...\ndef abs(a: SupportsAbs[_T], /) -> _T: ...\ndef add(a: Any, b: Any, /) -> Any: ...\ndef and_(a: Any, b: Any, /) -> Any: ...\ndef floordiv(a: Any, b: Any, /) -> Any: ...\ndef index(a: SupportsIndex, /) -> int: ...\ndef inv(a: _SupportsInversion[_T_co], /) -> _T_co: ...\ndef invert(a: _SupportsInversion[_T_co], /) -> _T_co: ...\ndef lshift(a: Any, b: Any, /) -> Any: ...\ndef mod(a: Any, b: Any, /) -> Any: ...\ndef mul(a: Any, b: Any, /) -> Any: ...\ndef matmul(a: Any, b: Any, /) -> Any: ...\ndef neg(a: _SupportsNeg[_T_co], /) -> _T_co: ...\ndef or_(a: Any, b: Any, /) -> Any: ...\ndef pos(a: _SupportsPos[_T_co], /) -> _T_co: ...\ndef pow(a: Any, b: Any, /) -> Any: ...\ndef rshift(a: Any, b: Any, /) -> Any: ...\ndef sub(a: Any, b: Any, /) -> Any: ...\ndef truediv(a: Any, b: Any, /) -> Any: ...\ndef xor(a: Any, b: Any, /) -> Any: ...\ndef concat(a: Sequence[_T], b: Sequence[_T], /) -> Sequence[_T]: ...\ndef contains(a: Container[object], b: object, /) -> bool: ...\ndef countOf(a: Iterable[object], b: object, /) -> int: ...\n@overload\ndef delitem(a: MutableSequence[Any], b: int, /) -> None: ...\n@overload\ndef delitem(a: MutableSequence[Any], b: slice[int | None], /) -> None: ...\n@overload\ndef delitem(a: MutableMapping[_K, Any], b: _K, /) -> None: ...\n@overload\ndef getitem(a: Sequence[_T], b: slice[int | None], /) -> Sequence[_T]: ...\n@overload\ndef getitem(a: SupportsGetItem[_K, _V], b: _K, /) -> _V: ...\ndef indexOf(a: Iterable[_T], b: _T, /) -> int: ...\n@overload\ndef setitem(a: MutableSequence[_T], b: int, c: _T, /) -> None: ...\n@overload\ndef setitem(a: MutableSequence[_T], b: slice[int | None], c: Sequence[_T], /) -> None: ...\n@overload\ndef setitem(a: MutableMapping[_K, _V], b: _K, c: _V, /) -> None: ...\ndef length_hint(obj: object, default: int = 0, /) -> int: ...\ndef iadd(a: Any, b: Any, /) -> Any: ...\ndef iand(a: Any, b: Any, /) -> Any: ...\ndef iconcat(a: Any, b: Any, /) -> Any: ...\ndef ifloordiv(a: Any, b: Any, /) -> Any: ...\ndef ilshift(a: Any, b: Any, /) -> Any: ...\ndef imod(a: Any, b: Any, /) -> Any: ...\ndef imul(a: Any, b: Any, /) -> Any: ...\ndef imatmul(a: Any, b: Any, /) -> Any: ...\ndef ior(a: Any, b: Any, /) -> Any: ...\ndef ipow(a: Any, b: Any, /) -> Any: ...\ndef irshift(a: Any, b: Any, /) -> Any: ...\ndef isub(a: Any, b: Any, /) -> Any: ...\ndef itruediv(a: Any, b: Any, /) -> Any: ...\ndef ixor(a: Any, b: Any, /) -> Any: ...\n\nif sys.version_info >= (3, 11):\n    def call(obj: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ...\n\ndef _compare_digest(a: AnyStr, b: AnyStr, /) -> bool: ...\n\nif sys.version_info >= (3, 14):\n    def is_none(a: object, /) -> TypeIs[None]: ...\n    def is_not_none(a: _T | None, /) -> TypeIs[_T]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_osx_support.pyi",
    "content": "from collections.abc import Iterable, Sequence\nfrom typing import Final, TypeVar\n\n_T = TypeVar(\"_T\")\n_K = TypeVar(\"_K\")\n_V = TypeVar(\"_V\")\n\n__all__ = [\"compiler_fixup\", \"customize_config_vars\", \"customize_compiler\", \"get_platform_osx\"]\n\n_UNIVERSAL_CONFIG_VARS: Final[tuple[str, ...]]  # undocumented\n_COMPILER_CONFIG_VARS: Final[tuple[str, ...]]  # undocumented\n_INITPRE: Final[str]  # undocumented\n\ndef _find_executable(executable: str, path: str | None = None) -> str | None: ...  # undocumented\ndef _read_output(commandstring: str, capture_stderr: bool = False) -> str | None: ...  # undocumented\ndef _find_build_tool(toolname: str) -> str: ...  # undocumented\n\n_SYSTEM_VERSION: Final[str | None]  # undocumented\n\ndef _get_system_version() -> str: ...  # undocumented\ndef _remove_original_values(_config_vars: dict[str, str]) -> None: ...  # undocumented\ndef _save_modified_value(_config_vars: dict[str, str], cv: str, newvalue: str) -> None: ...  # undocumented\ndef _supports_universal_builds() -> bool: ...  # undocumented\ndef _find_appropriate_compiler(_config_vars: dict[str, str]) -> dict[str, str]: ...  # undocumented\ndef _remove_universal_flags(_config_vars: dict[str, str]) -> dict[str, str]: ...  # undocumented\ndef _remove_unsupported_archs(_config_vars: dict[str, str]) -> dict[str, str]: ...  # undocumented\ndef _override_all_archs(_config_vars: dict[str, str]) -> dict[str, str]: ...  # undocumented\ndef _check_for_unavailable_sdk(_config_vars: dict[str, str]) -> dict[str, str]: ...  # undocumented\ndef compiler_fixup(compiler_so: Iterable[str], cc_args: Sequence[str]) -> list[str]: ...\ndef customize_config_vars(_config_vars: dict[str, str]) -> dict[str, str]: ...\ndef customize_compiler(_config_vars: dict[str, str]) -> dict[str, str]: ...\ndef get_platform_osx(\n    _config_vars: dict[str, str], osname: _T, release: _K, machine: _V\n) -> tuple[str | _T, str | _K, str | _V]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_pickle.pyi",
    "content": "from _typeshed import ReadableBuffer, SupportsWrite\nfrom collections.abc import Callable, Iterable, Iterator, Mapping\nfrom pickle import PickleBuffer as PickleBuffer\nfrom typing import Any, Protocol, type_check_only\nfrom typing_extensions import TypeAlias, disjoint_base\n\n@type_check_only\nclass _ReadableFileobj(Protocol):\n    def read(self, n: int, /) -> bytes: ...\n    def readline(self) -> bytes: ...\n\n_BufferCallback: TypeAlias = Callable[[PickleBuffer], Any] | None\n\n_ReducedType: TypeAlias = (\n    str\n    | tuple[Callable[..., Any], tuple[Any, ...]]\n    | tuple[Callable[..., Any], tuple[Any, ...], Any]\n    | tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None]\n    | tuple[Callable[..., Any], tuple[Any, ...], Any, Iterator[Any] | None, Iterator[Any] | None]\n)\n\ndef dump(\n    obj: Any,\n    file: SupportsWrite[bytes],\n    protocol: int | None = None,\n    *,\n    fix_imports: bool = True,\n    buffer_callback: _BufferCallback = None,\n) -> None: ...\ndef dumps(\n    obj: Any, protocol: int | None = None, *, fix_imports: bool = True, buffer_callback: _BufferCallback = None\n) -> bytes: ...\ndef load(\n    file: _ReadableFileobj,\n    *,\n    fix_imports: bool = True,\n    encoding: str = \"ASCII\",\n    errors: str = \"strict\",\n    buffers: Iterable[Any] | None = (),\n) -> Any: ...\ndef loads(\n    data: ReadableBuffer,\n    /,\n    *,\n    fix_imports: bool = True,\n    encoding: str = \"ASCII\",\n    errors: str = \"strict\",\n    buffers: Iterable[Any] | None = (),\n) -> Any: ...\n\nclass PickleError(Exception): ...\nclass PicklingError(PickleError): ...\nclass UnpicklingError(PickleError): ...\n\n@type_check_only\nclass PicklerMemoProxy:\n    def clear(self, /) -> None: ...\n    def copy(self, /) -> dict[int, tuple[int, Any]]: ...\n\n@disjoint_base\nclass Pickler:\n    fast: bool\n    dispatch_table: Mapping[type, Callable[[Any], _ReducedType]]\n    reducer_override: Callable[[Any], Any]\n    bin: bool  # undocumented\n    def __init__(\n        self,\n        file: SupportsWrite[bytes],\n        protocol: int | None = None,\n        fix_imports: bool = True,\n        buffer_callback: _BufferCallback = None,\n    ) -> None: ...\n    @property\n    def memo(self) -> PicklerMemoProxy: ...\n    @memo.setter\n    def memo(self, value: PicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ...\n    def dump(self, obj: Any, /) -> None: ...\n    def clear_memo(self) -> None: ...\n\n    # this method has no default implementation for Python < 3.13\n    def persistent_id(self, obj: Any, /) -> Any: ...\n\n@type_check_only\nclass UnpicklerMemoProxy:\n    def clear(self, /) -> None: ...\n    def copy(self, /) -> dict[int, tuple[int, Any]]: ...\n\n@disjoint_base\nclass Unpickler:\n    def __init__(\n        self,\n        file: _ReadableFileobj,\n        *,\n        fix_imports: bool = True,\n        encoding: str = \"ASCII\",\n        errors: str = \"strict\",\n        buffers: Iterable[Any] | None = (),\n    ) -> None: ...\n    @property\n    def memo(self) -> UnpicklerMemoProxy: ...\n    @memo.setter\n    def memo(self, value: UnpicklerMemoProxy | dict[int, tuple[int, Any]]) -> None: ...\n    def load(self) -> Any: ...\n    def find_class(self, module_name: str, global_name: str, /) -> Any: ...\n\n    # this method has no default implementation for Python < 3.13\n    def persistent_load(self, pid: Any, /) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_posixsubprocess.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath\nfrom collections.abc import Callable, Sequence\nfrom typing import SupportsIndex\n\nif sys.platform != \"win32\":\n    if sys.version_info >= (3, 14):\n        def fork_exec(\n            args: Sequence[StrOrBytesPath] | None,\n            executable_list: Sequence[bytes],\n            close_fds: bool,\n            pass_fds: tuple[int, ...],\n            cwd: str,\n            env: Sequence[bytes] | None,\n            p2cread: int,\n            p2cwrite: int,\n            c2pread: int,\n            c2pwrite: int,\n            errread: int,\n            errwrite: int,\n            errpipe_read: int,\n            errpipe_write: int,\n            restore_signals: int,\n            call_setsid: int,\n            pgid_to_set: int,\n            gid: SupportsIndex | None,\n            extra_groups: list[int] | None,\n            uid: SupportsIndex | None,\n            child_umask: int,\n            preexec_fn: Callable[[], None],\n            /,\n        ) -> int: ...\n    else:\n        def fork_exec(\n            args: Sequence[StrOrBytesPath] | None,\n            executable_list: Sequence[bytes],\n            close_fds: bool,\n            pass_fds: tuple[int, ...],\n            cwd: str,\n            env: Sequence[bytes] | None,\n            p2cread: int,\n            p2cwrite: int,\n            c2pread: int,\n            c2pwrite: int,\n            errread: int,\n            errwrite: int,\n            errpipe_read: int,\n            errpipe_write: int,\n            restore_signals: bool,\n            call_setsid: bool,\n            pgid_to_set: int,\n            gid: SupportsIndex | None,\n            extra_groups: list[int] | None,\n            uid: SupportsIndex | None,\n            child_umask: int,\n            preexec_fn: Callable[[], None],\n            allow_vfork: bool,\n            /,\n        ) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_py_abc.pyi",
    "content": "import _typeshed\nfrom typing import Any, NewType, TypeVar\n\n_T = TypeVar(\"_T\")\n\n_CacheToken = NewType(\"_CacheToken\", int)\n\ndef get_cache_token() -> _CacheToken: ...\n\nclass ABCMeta(type):\n    def __new__(\n        mcls: type[_typeshed.Self], name: str, bases: tuple[type[Any], ...], namespace: dict[str, Any], /\n    ) -> _typeshed.Self: ...\n    def register(cls, subclass: type[_T]) -> type[_T]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_pydecimal.pyi",
    "content": "# This is a slight lie, the implementations aren't exactly identical\n# However, in all likelihood, the differences are inconsequential\nimport sys\nfrom _decimal import *\n\n__all__ = [\n    \"Decimal\",\n    \"Context\",\n    \"DecimalTuple\",\n    \"DefaultContext\",\n    \"BasicContext\",\n    \"ExtendedContext\",\n    \"DecimalException\",\n    \"Clamped\",\n    \"InvalidOperation\",\n    \"DivisionByZero\",\n    \"Inexact\",\n    \"Rounded\",\n    \"Subnormal\",\n    \"Overflow\",\n    \"Underflow\",\n    \"FloatOperation\",\n    \"DivisionImpossible\",\n    \"InvalidContext\",\n    \"ConversionSyntax\",\n    \"DivisionUndefined\",\n    \"ROUND_DOWN\",\n    \"ROUND_HALF_UP\",\n    \"ROUND_HALF_EVEN\",\n    \"ROUND_CEILING\",\n    \"ROUND_FLOOR\",\n    \"ROUND_UP\",\n    \"ROUND_HALF_DOWN\",\n    \"ROUND_05UP\",\n    \"setcontext\",\n    \"getcontext\",\n    \"localcontext\",\n    \"MAX_PREC\",\n    \"MAX_EMAX\",\n    \"MIN_EMIN\",\n    \"MIN_ETINY\",\n    \"HAVE_THREADS\",\n    \"HAVE_CONTEXTVAR\",\n]\n\nif sys.version_info >= (3, 14):\n    __all__ += [\"IEEEContext\", \"IEEE_CONTEXT_MAX_BITS\"]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_queue.pyi",
    "content": "from types import GenericAlias\nfrom typing import Any, Generic, TypeVar\nfrom typing_extensions import disjoint_base\n\n_T = TypeVar(\"_T\")\n\nclass Empty(Exception): ...\n\n@disjoint_base\nclass SimpleQueue(Generic[_T]):\n    def __init__(self) -> None: ...\n    def empty(self) -> bool: ...\n    def get(self, block: bool = True, timeout: float | None = None) -> _T: ...\n    def get_nowait(self) -> _T: ...\n    def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ...\n    def put_nowait(self, item: _T) -> None: ...\n    def qsize(self) -> int: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_random.pyi",
    "content": "import sys\nfrom typing_extensions import Self, TypeAlias, disjoint_base\n\n# Actually Tuple[(int,) * 625]\n_State: TypeAlias = tuple[int, ...]\n\n@disjoint_base\nclass Random:\n    if sys.version_info >= (3, 10):\n        def __init__(self, seed: object = ..., /) -> None: ...\n    else:\n        def __new__(self, seed: object = ..., /) -> Self: ...\n\n    def seed(self, n: object = None, /) -> None: ...\n    def getstate(self) -> _State: ...\n    def setstate(self, state: _State, /) -> None: ...\n    def random(self) -> float: ...\n    def getrandbits(self, k: int, /) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_sitebuiltins.pyi",
    "content": "import sys\nfrom collections.abc import Iterable\nfrom typing import ClassVar, Literal, NoReturn\n\nclass Quitter:\n    name: str\n    eof: str\n    def __init__(self, name: str, eof: str) -> None: ...\n    def __call__(self, code: sys._ExitCode = None) -> NoReturn: ...\n\nclass _Printer:\n    MAXLINES: ClassVar[Literal[23]]\n    def __init__(self, name: str, data: str, files: Iterable[str] = (), dirs: Iterable[str] = ()) -> None: ...\n    def __call__(self) -> None: ...\n\nclass _Helper:\n    def __call__(self, request: object = ...) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_socket.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer, WriteableBuffer\nfrom collections.abc import Iterable\nfrom socket import error as error, gaierror as gaierror, herror as herror, timeout as timeout\nfrom typing import Any, Final, SupportsIndex, overload\nfrom typing_extensions import CapsuleType, TypeAlias, disjoint_base\n\n_CMSG: TypeAlias = tuple[int, int, bytes]\n_CMSGArg: TypeAlias = tuple[int, int, ReadableBuffer]\n\n# Addresses can be either tuples of varying lengths (AF_INET, AF_INET6,\n# AF_NETLINK, AF_TIPC) or strings/buffers (AF_UNIX).\n# See getsockaddrarg() in socketmodule.c.\n_Address: TypeAlias = tuple[Any, ...] | str | ReadableBuffer\n_RetAddress: TypeAlias = Any\n\n# ===== Constants =====\n# This matches the order in the CPython documentation\n# https://docs.python.org/3/library/socket.html#constants\n\nif sys.platform != \"win32\":\n    AF_UNIX: Final[int]\n\nAF_INET: Final[int]\nAF_INET6: Final[int]\n\nAF_UNSPEC: Final[int]\n\nSOCK_STREAM: Final[int]\nSOCK_DGRAM: Final[int]\nSOCK_RAW: Final[int]\nSOCK_RDM: Final[int]\nSOCK_SEQPACKET: Final[int]\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.27\n    SOCK_CLOEXEC: Final[int]\n    SOCK_NONBLOCK: Final[int]\n\n# --------------------\n# Many constants of these forms, documented in the Unix documentation on\n# sockets and/or the IP protocol, are also defined in the socket module.\n# SO_*\n# socket.SOMAXCONN\n# MSG_*\n# SOL_*\n# SCM_*\n# IPPROTO_*\n# IPPORT_*\n# INADDR_*\n# IP_*\n# IPV6_*\n# EAI_*\n# AI_*\n# NI_*\n# TCP_*\n# --------------------\n\nSO_ACCEPTCONN: Final[int]\nSO_BROADCAST: Final[int]\nSO_DEBUG: Final[int]\nSO_DONTROUTE: Final[int]\nSO_ERROR: Final[int]\nSO_KEEPALIVE: Final[int]\nSO_LINGER: Final[int]\nSO_OOBINLINE: Final[int]\nSO_RCVBUF: Final[int]\nSO_RCVLOWAT: Final[int]\nSO_RCVTIMEO: Final[int]\nSO_REUSEADDR: Final[int]\nSO_SNDBUF: Final[int]\nSO_SNDLOWAT: Final[int]\nSO_SNDTIMEO: Final[int]\nSO_TYPE: Final[int]\nif sys.platform != \"linux\":\n    SO_USELOOPBACK: Final[int]\nif sys.platform == \"win32\":\n    SO_EXCLUSIVEADDRUSE: Final[int]\nif sys.platform != \"win32\":\n    SO_REUSEPORT: Final[int]\n    if sys.platform != \"darwin\" or sys.version_info >= (3, 13):\n        SO_BINDTODEVICE: Final[int]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    SO_DOMAIN: Final[int]\n    SO_MARK: Final[int]\n    SO_PASSCRED: Final[int]\n    SO_PASSSEC: Final[int]\n    SO_PEERCRED: Final[int]\n    SO_PEERSEC: Final[int]\n    SO_PRIORITY: Final[int]\n    SO_PROTOCOL: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    SO_SETFIB: Final[int]\nif sys.platform == \"linux\" and sys.version_info >= (3, 13):\n    SO_BINDTOIFINDEX: Final[int]\n\nSOMAXCONN: Final[int]\n\nMSG_CTRUNC: Final[int]\nMSG_DONTROUTE: Final[int]\nMSG_OOB: Final[int]\nMSG_PEEK: Final[int]\nMSG_TRUNC: Final[int]\nMSG_WAITALL: Final[int]\nif sys.platform != \"win32\":\n    MSG_DONTWAIT: Final[int]\n    MSG_EOR: Final[int]\n    MSG_NOSIGNAL: Final[int]  # Sometimes this exists on darwin, sometimes not\nif sys.platform != \"darwin\":\n    MSG_ERRQUEUE: Final[int]\nif sys.platform == \"win32\":\n    MSG_BCAST: Final[int]\n    MSG_MCAST: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    MSG_CMSG_CLOEXEC: Final[int]\n    MSG_CONFIRM: Final[int]\n    MSG_FASTOPEN: Final[int]\n    MSG_MORE: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    MSG_EOF: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"linux\" and sys.platform != \"darwin\":\n    MSG_NOTIFICATION: Final[int]\n    MSG_BTAG: Final[int]  # Not FreeBSD either\n    MSG_ETAG: Final[int]  # Not FreeBSD either\n\nSOL_IP: Final[int]\nSOL_SOCKET: Final[int]\nSOL_TCP: Final[int]\nSOL_UDP: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    # Defined in socket.h for Linux, but these aren't always present for\n    # some reason.\n    SOL_ATALK: Final[int]\n    SOL_AX25: Final[int]\n    SOL_HCI: Final[int]\n    SOL_IPX: Final[int]\n    SOL_NETROM: Final[int]\n    SOL_ROSE: Final[int]\n\nif sys.platform != \"win32\":\n    SCM_RIGHTS: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    SCM_CREDENTIALS: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    SCM_CREDS: Final[int]\n\nIPPROTO_ICMP: Final[int]\nIPPROTO_IP: Final[int]\nIPPROTO_RAW: Final[int]\nIPPROTO_TCP: Final[int]\nIPPROTO_UDP: Final[int]\nIPPROTO_AH: Final[int]\nIPPROTO_DSTOPTS: Final[int]\nIPPROTO_EGP: Final[int]\nIPPROTO_ESP: Final[int]\nIPPROTO_FRAGMENT: Final[int]\nIPPROTO_HOPOPTS: Final[int]\nIPPROTO_ICMPV6: Final[int]\nIPPROTO_IDP: Final[int]\nIPPROTO_IGMP: Final[int]\nIPPROTO_IPV6: Final[int]\nIPPROTO_NONE: Final[int]\nIPPROTO_PIM: Final[int]\nIPPROTO_PUP: Final[int]\nIPPROTO_ROUTING: Final[int]\nIPPROTO_SCTP: Final[int]\nif sys.platform != \"linux\":\n    IPPROTO_GGP: Final[int]\n    IPPROTO_IPV4: Final[int]\n    IPPROTO_MAX: Final[int]\n    IPPROTO_ND: Final[int]\nif sys.platform == \"win32\":\n    IPPROTO_CBT: Final[int]\n    IPPROTO_ICLFXBM: Final[int]\n    IPPROTO_IGP: Final[int]\n    IPPROTO_L2TP: Final[int]\n    IPPROTO_PGM: Final[int]\n    IPPROTO_RDP: Final[int]\n    IPPROTO_ST: Final[int]\nif sys.platform != \"win32\":\n    IPPROTO_GRE: Final[int]\n    IPPROTO_IPIP: Final[int]\n    IPPROTO_RSVP: Final[int]\n    IPPROTO_TP: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    IPPROTO_EON: Final[int]\n    IPPROTO_HELLO: Final[int]\n    IPPROTO_IPCOMP: Final[int]\n    IPPROTO_XTP: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    IPPROTO_BIP: Final[int]  # Not FreeBSD either\n    IPPROTO_MOBILE: Final[int]  # Not FreeBSD either\n    IPPROTO_VRRP: Final[int]  # Not FreeBSD either\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.20, FreeBSD >= 10.1\n    IPPROTO_UDPLITE: Final[int]\nif sys.version_info >= (3, 10) and sys.platform == \"linux\":\n    IPPROTO_MPTCP: Final[int]\n\nIPPORT_RESERVED: Final[int]\nIPPORT_USERRESERVED: Final[int]\n\nINADDR_ALLHOSTS_GROUP: Final[int]\nINADDR_ANY: Final[int]\nINADDR_BROADCAST: Final[int]\nINADDR_LOOPBACK: Final[int]\nINADDR_MAX_LOCAL_GROUP: Final[int]\nINADDR_NONE: Final[int]\nINADDR_UNSPEC_GROUP: Final[int]\n\nIP_ADD_MEMBERSHIP: Final[int]\nIP_DROP_MEMBERSHIP: Final[int]\nIP_HDRINCL: Final[int]\nIP_MULTICAST_IF: Final[int]\nIP_MULTICAST_LOOP: Final[int]\nIP_MULTICAST_TTL: Final[int]\nIP_OPTIONS: Final[int]\nif sys.platform != \"linux\":\n    IP_RECVDSTADDR: Final[int]\nif sys.version_info >= (3, 10):\n    IP_RECVTOS: Final[int]\nIP_TOS: Final[int]\nIP_TTL: Final[int]\nif sys.platform != \"win32\":\n    IP_DEFAULT_MULTICAST_LOOP: Final[int]\n    IP_DEFAULT_MULTICAST_TTL: Final[int]\n    IP_MAX_MEMBERSHIPS: Final[int]\n    IP_RECVOPTS: Final[int]\n    IP_RECVRETOPTS: Final[int]\n    IP_RETOPTS: Final[int]\nif sys.version_info >= (3, 13) and sys.platform == \"linux\":\n    CAN_RAW_ERR_FILTER: Final[int]\nif sys.version_info >= (3, 14):\n    IP_RECVTTL: Final[int]\n\n    if sys.platform == \"win32\" or sys.platform == \"linux\":\n        IPV6_RECVERR: Final[int]\n        IP_RECVERR: Final[int]\n        SO_ORIGINAL_DST: Final[int]\n\n    if sys.platform == \"win32\":\n        SOL_RFCOMM: Final[int]\n        SO_BTH_ENCRYPT: Final[int]\n        SO_BTH_MTU: Final[int]\n        SO_BTH_MTU_MAX: Final[int]\n        SO_BTH_MTU_MIN: Final[int]\n        TCP_QUICKACK: Final[int]\n\n    if sys.platform == \"linux\":\n        IP_FREEBIND: Final[int]\n        IP_RECVORIGDSTADDR: Final[int]\n        VMADDR_CID_LOCAL: Final[int]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    IP_TRANSPARENT: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.version_info >= (3, 11):\n    IP_BIND_ADDRESS_NO_PORT: Final[int]\nif sys.version_info >= (3, 12):\n    IP_ADD_SOURCE_MEMBERSHIP: Final[int]\n    IP_BLOCK_SOURCE: Final[int]\n    IP_DROP_SOURCE_MEMBERSHIP: Final[int]\n    IP_PKTINFO: Final[int]\n    IP_UNBLOCK_SOURCE: Final[int]\n\nIPV6_CHECKSUM: Final[int]\nIPV6_JOIN_GROUP: Final[int]\nIPV6_LEAVE_GROUP: Final[int]\nIPV6_MULTICAST_HOPS: Final[int]\nIPV6_MULTICAST_IF: Final[int]\nIPV6_MULTICAST_LOOP: Final[int]\nIPV6_RECVTCLASS: Final[int]\nIPV6_TCLASS: Final[int]\nIPV6_UNICAST_HOPS: Final[int]\nIPV6_V6ONLY: Final[int]\nIPV6_DONTFRAG: Final[int]\nIPV6_HOPLIMIT: Final[int]\nIPV6_HOPOPTS: Final[int]\nIPV6_PKTINFO: Final[int]\nIPV6_RECVRTHDR: Final[int]\nIPV6_RTHDR: Final[int]\nif sys.platform != \"win32\":\n    IPV6_RTHDR_TYPE_0: Final[int]\n    IPV6_DSTOPTS: Final[int]\n    IPV6_NEXTHOP: Final[int]\n    IPV6_PATHMTU: Final[int]\n    IPV6_RECVDSTOPTS: Final[int]\n    IPV6_RECVHOPLIMIT: Final[int]\n    IPV6_RECVHOPOPTS: Final[int]\n    IPV6_RECVPATHMTU: Final[int]\n    IPV6_RECVPKTINFO: Final[int]\n    IPV6_RTHDRDSTOPTS: Final[int]\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    IPV6_USE_MIN_MTU: Final[int]\n\nEAI_AGAIN: Final[int]\nEAI_BADFLAGS: Final[int]\nEAI_FAIL: Final[int]\nEAI_FAMILY: Final[int]\nEAI_MEMORY: Final[int]\nEAI_NODATA: Final[int]\nEAI_NONAME: Final[int]\nEAI_SERVICE: Final[int]\nEAI_SOCKTYPE: Final[int]\nif sys.platform != \"win32\":\n    EAI_ADDRFAMILY: Final[int]\n    EAI_OVERFLOW: Final[int]\n    EAI_SYSTEM: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    EAI_BADHINTS: Final[int]\n    EAI_MAX: Final[int]\n    EAI_PROTOCOL: Final[int]\n\nAI_ADDRCONFIG: Final[int]\nAI_ALL: Final[int]\nAI_CANONNAME: Final[int]\nAI_NUMERICHOST: Final[int]\nAI_NUMERICSERV: Final[int]\nAI_PASSIVE: Final[int]\nAI_V4MAPPED: Final[int]\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    AI_DEFAULT: Final[int]\n    AI_MASK: Final[int]\n    AI_V4MAPPED_CFG: Final[int]\n\nNI_DGRAM: Final[int]\nNI_MAXHOST: Final[int]\nNI_MAXSERV: Final[int]\nNI_NAMEREQD: Final[int]\nNI_NOFQDN: Final[int]\nNI_NUMERICHOST: Final[int]\nNI_NUMERICSERV: Final[int]\nif sys.platform == \"linux\" and sys.version_info >= (3, 13):\n    NI_IDN: Final[int]\n\nTCP_FASTOPEN: Final[int]\nTCP_KEEPCNT: Final[int]\nTCP_KEEPINTVL: Final[int]\nTCP_MAXSEG: Final[int]\nTCP_NODELAY: Final[int]\nif sys.platform != \"win32\":\n    TCP_NOTSENT_LOWAT: Final[int]\nif sys.platform != \"darwin\":\n    TCP_KEEPIDLE: Final[int]\nif sys.version_info >= (3, 10) and sys.platform == \"darwin\":\n    TCP_KEEPALIVE: Final[int]\nif sys.version_info >= (3, 11) and sys.platform == \"darwin\":\n    TCP_CONNECTION_INFO: Final[int]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    TCP_CONGESTION: Final[int]\n    TCP_CORK: Final[int]\n    TCP_DEFER_ACCEPT: Final[int]\n    TCP_INFO: Final[int]\n    TCP_LINGER2: Final[int]\n    TCP_QUICKACK: Final[int]\n    TCP_SYNCNT: Final[int]\n    TCP_USER_TIMEOUT: Final[int]\n    TCP_WINDOW_CLAMP: Final[int]\nif sys.platform == \"linux\" and sys.version_info >= (3, 12):\n    TCP_CC_INFO: Final[int]\n    TCP_FASTOPEN_CONNECT: Final[int]\n    TCP_FASTOPEN_KEY: Final[int]\n    TCP_FASTOPEN_NO_COOKIE: Final[int]\n    TCP_INQ: Final[int]\n    TCP_MD5SIG: Final[int]\n    TCP_MD5SIG_EXT: Final[int]\n    TCP_QUEUE_SEQ: Final[int]\n    TCP_REPAIR: Final[int]\n    TCP_REPAIR_OPTIONS: Final[int]\n    TCP_REPAIR_QUEUE: Final[int]\n    TCP_REPAIR_WINDOW: Final[int]\n    TCP_SAVED_SYN: Final[int]\n    TCP_SAVE_SYN: Final[int]\n    TCP_THIN_DUPACK: Final[int]\n    TCP_THIN_LINEAR_TIMEOUTS: Final[int]\n    TCP_TIMESTAMP: Final[int]\n    TCP_TX_DELAY: Final[int]\n    TCP_ULP: Final[int]\n    TCP_ZEROCOPY_RECEIVE: Final[int]\n\n# --------------------\n# Specifically documented constants\n# --------------------\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.25, NetBSD >= 8\n    AF_CAN: Final[int]\n    PF_CAN: Final[int]\n    SOL_CAN_BASE: Final[int]\n    SOL_CAN_RAW: Final[int]\n    CAN_EFF_FLAG: Final[int]\n    CAN_EFF_MASK: Final[int]\n    CAN_ERR_FLAG: Final[int]\n    CAN_ERR_MASK: Final[int]\n    CAN_RAW: Final[int]\n    CAN_RAW_FILTER: Final[int]\n    CAN_RAW_LOOPBACK: Final[int]\n    CAN_RAW_RECV_OWN_MSGS: Final[int]\n    CAN_RTR_FLAG: Final[int]\n    CAN_SFF_MASK: Final[int]\n    if sys.version_info < (3, 11):\n        CAN_RAW_ERR_FILTER: Final[int]\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.25\n    CAN_BCM: Final[int]\n    CAN_BCM_TX_SETUP: Final[int]\n    CAN_BCM_TX_DELETE: Final[int]\n    CAN_BCM_TX_READ: Final[int]\n    CAN_BCM_TX_SEND: Final[int]\n    CAN_BCM_RX_SETUP: Final[int]\n    CAN_BCM_RX_DELETE: Final[int]\n    CAN_BCM_RX_READ: Final[int]\n    CAN_BCM_TX_STATUS: Final[int]\n    CAN_BCM_TX_EXPIRED: Final[int]\n    CAN_BCM_RX_STATUS: Final[int]\n    CAN_BCM_RX_TIMEOUT: Final[int]\n    CAN_BCM_RX_CHANGED: Final[int]\n    CAN_BCM_SETTIMER: Final[int]\n    CAN_BCM_STARTTIMER: Final[int]\n    CAN_BCM_TX_COUNTEVT: Final[int]\n    CAN_BCM_TX_ANNOUNCE: Final[int]\n    CAN_BCM_TX_CP_CAN_ID: Final[int]\n    CAN_BCM_RX_FILTER_ID: Final[int]\n    CAN_BCM_RX_CHECK_DLC: Final[int]\n    CAN_BCM_RX_NO_AUTOTIMER: Final[int]\n    CAN_BCM_RX_ANNOUNCE_RESUME: Final[int]\n    CAN_BCM_TX_RESET_MULTI_IDX: Final[int]\n    CAN_BCM_RX_RTR_FRAME: Final[int]\n    CAN_BCM_CAN_FD_FRAME: Final[int]\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 3.6\n    CAN_RAW_FD_FRAMES: Final[int]\n    # Availability: Linux >= 4.1\n    CAN_RAW_JOIN_FILTERS: Final[int]\n    # Availability: Linux >= 2.6.25\n    CAN_ISOTP: Final[int]\n    # Availability: Linux >= 5.4\n    CAN_J1939: Final[int]\n\n    J1939_MAX_UNICAST_ADDR: Final[int]\n    J1939_IDLE_ADDR: Final[int]\n    J1939_NO_ADDR: Final[int]\n    J1939_NO_NAME: Final[int]\n    J1939_PGN_REQUEST: Final[int]\n    J1939_PGN_ADDRESS_CLAIMED: Final[int]\n    J1939_PGN_ADDRESS_COMMANDED: Final[int]\n    J1939_PGN_PDU1_MAX: Final[int]\n    J1939_PGN_MAX: Final[int]\n    J1939_NO_PGN: Final[int]\n\n    SO_J1939_FILTER: Final[int]\n    SO_J1939_PROMISC: Final[int]\n    SO_J1939_SEND_PRIO: Final[int]\n    SO_J1939_ERRQUEUE: Final[int]\n\n    SCM_J1939_DEST_ADDR: Final[int]\n    SCM_J1939_DEST_NAME: Final[int]\n    SCM_J1939_PRIO: Final[int]\n    SCM_J1939_ERRQUEUE: Final[int]\n\n    J1939_NLA_PAD: Final[int]\n    J1939_NLA_BYTES_ACKED: Final[int]\n    J1939_EE_INFO_NONE: Final[int]\n    J1939_EE_INFO_TX_ABORT: Final[int]\n    J1939_FILTER_MAX: Final[int]\n\nif sys.version_info >= (3, 12) and sys.platform != \"linux\" and sys.platform != \"win32\" and sys.platform != \"darwin\":\n    # Availability: FreeBSD >= 14.0\n    AF_DIVERT: Final[int]\n    PF_DIVERT: Final[int]\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.2\n    AF_PACKET: Final[int]\n    PF_PACKET: Final[int]\n    PACKET_BROADCAST: Final[int]\n    PACKET_FASTROUTE: Final[int]\n    PACKET_HOST: Final[int]\n    PACKET_LOOPBACK: Final[int]\n    PACKET_MULTICAST: Final[int]\n    PACKET_OTHERHOST: Final[int]\n    PACKET_OUTGOING: Final[int]\n\nif sys.version_info >= (3, 12) and sys.platform == \"linux\":\n    ETH_P_ALL: Final[int]\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.30\n    AF_RDS: Final[int]\n    PF_RDS: Final[int]\n    SOL_RDS: Final[int]\n    # These are present in include/linux/rds.h but don't always show up\n    # here.\n    RDS_CANCEL_SENT_TO: Final[int]\n    RDS_CMSG_RDMA_ARGS: Final[int]\n    RDS_CMSG_RDMA_DEST: Final[int]\n    RDS_CMSG_RDMA_MAP: Final[int]\n    RDS_CMSG_RDMA_STATUS: Final[int]\n    RDS_CONG_MONITOR: Final[int]\n    RDS_FREE_MR: Final[int]\n    RDS_GET_MR: Final[int]\n    RDS_GET_MR_FOR_DEST: Final[int]\n    RDS_RDMA_DONTWAIT: Final[int]\n    RDS_RDMA_FENCE: Final[int]\n    RDS_RDMA_INVALIDATE: Final[int]\n    RDS_RDMA_NOTIFY_ME: Final[int]\n    RDS_RDMA_READWRITE: Final[int]\n    RDS_RDMA_SILENT: Final[int]\n    RDS_RDMA_USE_ONCE: Final[int]\n    RDS_RECVERR: Final[int]\n\n    # This is supported by CPython but doesn't seem to be a real thing.\n    # The closest existing constant in rds.h is RDS_CMSG_CONG_UPDATE\n    # RDS_CMSG_RDMA_UPDATE: Final[int]\n\nif sys.platform == \"win32\":\n    SIO_RCVALL: Final[int]\n    SIO_KEEPALIVE_VALS: Final[int]\n    SIO_LOOPBACK_FAST_PATH: Final[int]\n    RCVALL_MAX: Final[int]\n    RCVALL_OFF: Final[int]\n    RCVALL_ON: Final[int]\n    RCVALL_SOCKETLEVELONLY: Final[int]\n\nif sys.platform == \"linux\":\n    AF_TIPC: Final[int]\n    SOL_TIPC: Final[int]\n    TIPC_ADDR_ID: Final[int]\n    TIPC_ADDR_NAME: Final[int]\n    TIPC_ADDR_NAMESEQ: Final[int]\n    TIPC_CFG_SRV: Final[int]\n    TIPC_CLUSTER_SCOPE: Final[int]\n    TIPC_CONN_TIMEOUT: Final[int]\n    TIPC_CRITICAL_IMPORTANCE: Final[int]\n    TIPC_DEST_DROPPABLE: Final[int]\n    TIPC_HIGH_IMPORTANCE: Final[int]\n    TIPC_IMPORTANCE: Final[int]\n    TIPC_LOW_IMPORTANCE: Final[int]\n    TIPC_MEDIUM_IMPORTANCE: Final[int]\n    TIPC_NODE_SCOPE: Final[int]\n    TIPC_PUBLISHED: Final[int]\n    TIPC_SRC_DROPPABLE: Final[int]\n    TIPC_SUBSCR_TIMEOUT: Final[int]\n    TIPC_SUB_CANCEL: Final[int]\n    TIPC_SUB_PORTS: Final[int]\n    TIPC_SUB_SERVICE: Final[int]\n    TIPC_TOP_SRV: Final[int]\n    TIPC_WAIT_FOREVER: Final[int]\n    TIPC_WITHDRAWN: Final[int]\n    TIPC_ZONE_SCOPE: Final[int]\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 2.6.38\n    AF_ALG: Final[int]\n    SOL_ALG: Final[int]\n    ALG_OP_DECRYPT: Final[int]\n    ALG_OP_ENCRYPT: Final[int]\n    ALG_OP_SIGN: Final[int]\n    ALG_OP_VERIFY: Final[int]\n    ALG_SET_AEAD_ASSOCLEN: Final[int]\n    ALG_SET_AEAD_AUTHSIZE: Final[int]\n    ALG_SET_IV: Final[int]\n    ALG_SET_KEY: Final[int]\n    ALG_SET_OP: Final[int]\n    ALG_SET_PUBKEY: Final[int]\n\nif sys.platform == \"linux\":\n    # Availability: Linux >= 4.8 (or maybe 3.9, CPython docs are confusing)\n    AF_VSOCK: Final[int]\n    IOCTL_VM_SOCKETS_GET_LOCAL_CID: Final = 0x7B9\n    VMADDR_CID_ANY: Final = 0xFFFFFFFF\n    VMADDR_CID_HOST: Final = 2\n    VMADDR_PORT_ANY: Final = 0xFFFFFFFF\n    SO_VM_SOCKETS_BUFFER_MAX_SIZE: Final = 2\n    SO_VM_SOCKETS_BUFFER_SIZE: Final = 0\n    SO_VM_SOCKETS_BUFFER_MIN_SIZE: Final = 1\n    VM_SOCKETS_INVALID_VERSION: Final = 0xFFFFFFFF  # undocumented\n\n# Documented as only available on BSD, macOS, but empirically sometimes\n# available on Windows\nif sys.platform != \"linux\":\n    AF_LINK: Final[int]\n\nhas_ipv6: bool\n\nif sys.platform != \"darwin\":\n    BDADDR_ANY: Final = \"00:00:00:00:00:00\"\n    BDADDR_LOCAL: Final = \"00:00:00:FF:FF:FF\"\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    HCI_FILTER: Final[int]  # not in NetBSD or DragonFlyBSD\n    HCI_TIME_STAMP: Final[int]  # not in FreeBSD, NetBSD, or DragonFlyBSD\n    HCI_DATA_DIR: Final[int]  # not in FreeBSD, NetBSD, or DragonFlyBSD\n\nif sys.platform == \"linux\":\n    AF_QIPCRTR: Final[int]  # Availability: Linux >= 4.7\n\nif sys.version_info >= (3, 11) and sys.platform != \"linux\" and sys.platform != \"win32\" and sys.platform != \"darwin\":\n    # FreeBSD\n    SCM_CREDS2: Final[int]\n    LOCAL_CREDS: Final[int]\n    LOCAL_CREDS_PERSISTENT: Final[int]\n\nif sys.version_info >= (3, 11) and sys.platform == \"linux\":\n    SO_INCOMING_CPU: Final[int]  # Availability: Linux >= 3.9\n\nif sys.version_info >= (3, 12) and sys.platform == \"win32\":\n    # Availability: Windows\n    AF_HYPERV: Final[int]\n    HV_PROTOCOL_RAW: Final[int]\n    HVSOCKET_CONNECT_TIMEOUT: Final[int]\n    HVSOCKET_CONNECT_TIMEOUT_MAX: Final[int]\n    HVSOCKET_CONNECTED_SUSPEND: Final[int]\n    HVSOCKET_ADDRESS_FLAG_PASSTHRU: Final[int]\n    HV_GUID_ZERO: Final = \"00000000-0000-0000-0000-000000000000\"\n    HV_GUID_WILDCARD: Final = \"00000000-0000-0000-0000-000000000000\"\n    HV_GUID_BROADCAST: Final = \"FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF\"\n    HV_GUID_CHILDREN: Final = \"90DB8B89-0D35-4F79-8CE9-49EA0AC8B7CD\"\n    HV_GUID_LOOPBACK: Final = \"E0E16197-DD56-4A10-9195-5EE7A155A838\"\n    HV_GUID_PARENT: Final = \"A42E7CDA-D03F-480C-9CC2-A4DE20ABB878\"\n\nif sys.version_info >= (3, 12):\n    if sys.platform != \"win32\":\n        # Availability: Linux, FreeBSD, macOS\n        ETHERTYPE_ARP: Final[int]\n        ETHERTYPE_IP: Final[int]\n        ETHERTYPE_IPV6: Final[int]\n        ETHERTYPE_VLAN: Final[int]\n\n# --------------------\n# Semi-documented constants\n# These are alluded to under the \"Socket families\" section in the docs\n# https://docs.python.org/3/library/socket.html#socket-families\n# --------------------\n\nif sys.platform == \"linux\":\n    # Netlink is defined by Linux\n    AF_NETLINK: Final[int]\n    NETLINK_CRYPTO: Final[int]\n    NETLINK_DNRTMSG: Final[int]\n    NETLINK_FIREWALL: Final[int]\n    NETLINK_IP6_FW: Final[int]\n    NETLINK_NFLOG: Final[int]\n    NETLINK_ROUTE: Final[int]\n    NETLINK_USERSOCK: Final[int]\n    NETLINK_XFRM: Final[int]\n    # Technically still supported by CPython\n    # NETLINK_ARPD: Final[int]  # linux 2.0 to 2.6.12 (EOL August 2005)\n    # NETLINK_ROUTE6: Final[int]  # linux 2.2 to 2.6.12 (EOL August 2005)\n    # NETLINK_SKIP: Final[int]  # linux 2.0 to 2.6.12 (EOL August 2005)\n    # NETLINK_TAPBASE: Final[int]  # linux 2.2 to 2.6.12 (EOL August 2005)\n    # NETLINK_TCPDIAG: Final[int]  # linux 2.6.0 to 2.6.13 (EOL December 2005)\n    # NETLINK_W1: Final[int]  # linux 2.6.13 to 2.6.17 (EOL October 2006)\n\nif sys.platform == \"darwin\":\n    PF_SYSTEM: Final[int]\n    SYSPROTO_CONTROL: Final[int]\n\nif sys.platform != \"darwin\":\n    AF_BLUETOOTH: Final[int]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    # Linux and some BSD support is explicit in the docs\n    # Windows and macOS do not support in practice\n    BTPROTO_HCI: Final[int]\n    BTPROTO_L2CAP: Final[int]\n    BTPROTO_SCO: Final[int]  # not in FreeBSD\nif sys.platform != \"darwin\":\n    BTPROTO_RFCOMM: Final[int]\n\nif sys.platform == \"linux\":\n    UDPLITE_RECV_CSCOV: Final[int]\n    UDPLITE_SEND_CSCOV: Final[int]\n\n# --------------------\n# Documented under socket.shutdown\n# --------------------\nSHUT_RD: Final[int]\nSHUT_RDWR: Final[int]\nSHUT_WR: Final[int]\n\n# --------------------\n# Undocumented constants\n# --------------------\n\n# Undocumented address families\nAF_APPLETALK: Final[int]\nAF_DECnet: Final[int]\nAF_IPX: Final[int]\nAF_SNA: Final[int]\n\nif sys.platform != \"win32\":\n    AF_ROUTE: Final[int]\n\nif sys.platform == \"darwin\":\n    AF_SYSTEM: Final[int]\n\nif sys.platform != \"darwin\":\n    AF_IRDA: Final[int]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    AF_ASH: Final[int]\n    AF_ATMPVC: Final[int]\n    AF_ATMSVC: Final[int]\n    AF_AX25: Final[int]\n    AF_BRIDGE: Final[int]\n    AF_ECONET: Final[int]\n    AF_KEY: Final[int]\n    AF_LLC: Final[int]\n    AF_NETBEUI: Final[int]\n    AF_NETROM: Final[int]\n    AF_PPPOX: Final[int]\n    AF_ROSE: Final[int]\n    AF_SECURITY: Final[int]\n    AF_WANPIPE: Final[int]\n    AF_X25: Final[int]\n\n# Miscellaneous undocumented\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    LOCAL_PEERCRED: Final[int]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    # Defined in linux socket.h, but this isn't always present for\n    # some reason.\n    IPX_TYPE: Final[int]\n\n# ===== Classes =====\n\n@disjoint_base\nclass socket:\n    @property\n    def family(self) -> int: ...\n    @property\n    def type(self) -> int: ...\n    @property\n    def proto(self) -> int: ...\n    # F811: \"Redefinition of unused `timeout`\"\n    @property\n    def timeout(self) -> float | None: ...  # noqa: F811\n    if sys.platform == \"win32\":\n        def __init__(\n            self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | bytes | None = None\n        ) -> None: ...\n    else:\n        def __init__(self, family: int = ..., type: int = ..., proto: int = ..., fileno: SupportsIndex | None = None) -> None: ...\n\n    def bind(self, address: _Address, /) -> None: ...\n    def close(self) -> None: ...\n    def connect(self, address: _Address, /) -> None: ...\n    def connect_ex(self, address: _Address, /) -> int: ...\n    def detach(self) -> int: ...\n    def fileno(self) -> int: ...\n    def getpeername(self) -> _RetAddress: ...\n    def getsockname(self) -> _RetAddress: ...\n    @overload\n    def getsockopt(self, level: int, optname: int, /) -> int: ...\n    @overload\n    def getsockopt(self, level: int, optname: int, buflen: int, /) -> bytes: ...\n    def getblocking(self) -> bool: ...\n    def gettimeout(self) -> float | None: ...\n    if sys.platform == \"win32\":\n        def ioctl(self, control: int, option: int | tuple[int, int, int] | bool, /) -> None: ...\n\n    def listen(self, backlog: int = ..., /) -> None: ...\n    def recv(self, bufsize: int, flags: int = 0, /) -> bytes: ...\n    def recvfrom(self, bufsize: int, flags: int = 0, /) -> tuple[bytes, _RetAddress]: ...\n    if sys.platform != \"win32\":\n        def recvmsg(self, bufsize: int, ancbufsize: int = 0, flags: int = 0, /) -> tuple[bytes, list[_CMSG], int, Any]: ...\n        def recvmsg_into(\n            self, buffers: Iterable[WriteableBuffer], ancbufsize: int = 0, flags: int = 0, /\n        ) -> tuple[int, list[_CMSG], int, Any]: ...\n\n    def recvfrom_into(self, buffer: WriteableBuffer, nbytes: int = 0, flags: int = 0) -> tuple[int, _RetAddress]: ...\n    def recv_into(self, buffer: WriteableBuffer, nbytes: int = 0, flags: int = 0) -> int: ...\n    def send(self, data: ReadableBuffer, flags: int = 0, /) -> int: ...\n    def sendall(self, data: ReadableBuffer, flags: int = 0, /) -> None: ...\n    @overload\n    def sendto(self, data: ReadableBuffer, address: _Address, /) -> int: ...\n    @overload\n    def sendto(self, data: ReadableBuffer, flags: int, address: _Address, /) -> int: ...\n    if sys.platform != \"win32\":\n        def sendmsg(\n            self,\n            buffers: Iterable[ReadableBuffer],\n            ancdata: Iterable[_CMSGArg] = ...,\n            flags: int = 0,\n            address: _Address | None = None,\n            /,\n        ) -> int: ...\n    if sys.platform == \"linux\":\n        def sendmsg_afalg(\n            self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0\n        ) -> int: ...\n\n    def setblocking(self, flag: bool, /) -> None: ...\n    def settimeout(self, value: float | None, /) -> None: ...\n    @overload\n    def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer, /) -> None: ...\n    @overload\n    def setsockopt(self, level: int, optname: int, value: None, optlen: int, /) -> None: ...\n    if sys.platform == \"win32\":\n        def share(self, process_id: int, /) -> bytes: ...\n\n    def shutdown(self, how: int, /) -> None: ...\n\nSocketType = socket\n\n# ===== Functions =====\n\ndef close(fd: SupportsIndex, /) -> None: ...\ndef dup(fd: SupportsIndex, /) -> int: ...\n\n# the 5th tuple item is an address\ndef getaddrinfo(\n    host: bytes | str | None, port: bytes | str | int | None, family: int = ..., type: int = 0, proto: int = 0, flags: int = 0\n) -> list[tuple[int, int, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]]: ...\ndef gethostbyname(hostname: str, /) -> str: ...\ndef gethostbyname_ex(hostname: str, /) -> tuple[str, list[str], list[str]]: ...\ndef gethostname() -> str: ...\ndef gethostbyaddr(ip_address: str, /) -> tuple[str, list[str], list[str]]: ...\ndef getnameinfo(sockaddr: tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes], flags: int, /) -> tuple[str, str]: ...\ndef getprotobyname(protocolname: str, /) -> int: ...\ndef getservbyname(servicename: str, protocolname: str = ..., /) -> int: ...\ndef getservbyport(port: int, protocolname: str = ..., /) -> str: ...\ndef ntohl(x: int, /) -> int: ...  # param & ret val are 32-bit ints\ndef ntohs(x: int, /) -> int: ...  # param & ret val are 16-bit ints\ndef htonl(x: int, /) -> int: ...  # param & ret val are 32-bit ints\ndef htons(x: int, /) -> int: ...  # param & ret val are 16-bit ints\ndef inet_aton(ip_addr: str, /) -> bytes: ...  # ret val 4 bytes in length\ndef inet_ntoa(packed_ip: ReadableBuffer, /) -> str: ...\ndef inet_pton(address_family: int, ip_string: str, /) -> bytes: ...\ndef inet_ntop(address_family: int, packed_ip: ReadableBuffer, /) -> str: ...\ndef getdefaulttimeout() -> float | None: ...\n\n# F811: \"Redefinition of unused `timeout`\"\ndef setdefaulttimeout(timeout: float | None, /) -> None: ...  # noqa: F811\n\nif sys.platform != \"win32\":\n    def sethostname(name: str, /) -> None: ...\n    def CMSG_LEN(length: int, /) -> int: ...\n    def CMSG_SPACE(length: int, /) -> int: ...\n    def socketpair(family: int = ..., type: int = ..., proto: int = 0, /) -> tuple[socket, socket]: ...\n\ndef if_nameindex() -> list[tuple[int, str]]: ...\ndef if_nametoindex(oname: str, /) -> int: ...\n\nif sys.version_info >= (3, 14):\n    def if_indextoname(if_index: int, /) -> str: ...\n\nelse:\n    def if_indextoname(index: int, /) -> str: ...\n\nCAPI: CapsuleType\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_sqlite3.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer, StrOrBytesPath\nfrom collections.abc import Callable\nfrom sqlite3 import (\n    Connection as Connection,\n    Cursor as Cursor,\n    DatabaseError as DatabaseError,\n    DataError as DataError,\n    Error as Error,\n    IntegrityError as IntegrityError,\n    InterfaceError as InterfaceError,\n    InternalError as InternalError,\n    NotSupportedError as NotSupportedError,\n    OperationalError as OperationalError,\n    PrepareProtocol as PrepareProtocol,\n    ProgrammingError as ProgrammingError,\n    Row as Row,\n    Warning as Warning,\n    _IsolationLevel,\n)\nfrom typing import Any, Final, Literal, TypeVar, overload\nfrom typing_extensions import TypeAlias\n\nif sys.version_info >= (3, 11):\n    from sqlite3 import Blob as Blob\n\n_T = TypeVar(\"_T\")\n_ConnectionT = TypeVar(\"_ConnectionT\", bound=Connection)\n_SqliteData: TypeAlias = str | ReadableBuffer | int | float | None\n_Adapter: TypeAlias = Callable[[_T], _SqliteData]\n_Converter: TypeAlias = Callable[[bytes], Any]\n\nPARSE_COLNAMES: Final = 2\nPARSE_DECLTYPES: Final = 1\nSQLITE_ALTER_TABLE: Final = 26\nSQLITE_ANALYZE: Final = 28\nSQLITE_ATTACH: Final = 24\nSQLITE_CREATE_INDEX: Final = 1\nSQLITE_CREATE_TABLE: Final = 2\nSQLITE_CREATE_TEMP_INDEX: Final = 3\nSQLITE_CREATE_TEMP_TABLE: Final = 4\nSQLITE_CREATE_TEMP_TRIGGER: Final = 5\nSQLITE_CREATE_TEMP_VIEW: Final = 6\nSQLITE_CREATE_TRIGGER: Final = 7\nSQLITE_CREATE_VIEW: Final = 8\nSQLITE_CREATE_VTABLE: Final = 29\nSQLITE_DELETE: Final = 9\nSQLITE_DENY: Final = 1\nSQLITE_DETACH: Final = 25\nSQLITE_DONE: Final = 101\nSQLITE_DROP_INDEX: Final = 10\nSQLITE_DROP_TABLE: Final = 11\nSQLITE_DROP_TEMP_INDEX: Final = 12\nSQLITE_DROP_TEMP_TABLE: Final = 13\nSQLITE_DROP_TEMP_TRIGGER: Final = 14\nSQLITE_DROP_TEMP_VIEW: Final = 15\nSQLITE_DROP_TRIGGER: Final = 16\nSQLITE_DROP_VIEW: Final = 17\nSQLITE_DROP_VTABLE: Final = 30\nSQLITE_FUNCTION: Final = 31\nSQLITE_IGNORE: Final = 2\nSQLITE_INSERT: Final = 18\nSQLITE_OK: Final = 0\nSQLITE_PRAGMA: Final = 19\nSQLITE_READ: Final = 20\nSQLITE_RECURSIVE: Final = 33\nSQLITE_REINDEX: Final = 27\nSQLITE_SAVEPOINT: Final = 32\nSQLITE_SELECT: Final = 21\nSQLITE_TRANSACTION: Final = 22\nSQLITE_UPDATE: Final = 23\nadapters: dict[tuple[type[Any], type[Any]], _Adapter[Any]]\nconverters: dict[str, _Converter]\nsqlite_version: str\n\nif sys.version_info < (3, 12):\n    version: str\n\nif sys.version_info >= (3, 12):\n    LEGACY_TRANSACTION_CONTROL: Final = -1\n    SQLITE_DBCONFIG_DEFENSIVE: Final = 1010\n    SQLITE_DBCONFIG_DQS_DDL: Final = 1014\n    SQLITE_DBCONFIG_DQS_DML: Final = 1013\n    SQLITE_DBCONFIG_ENABLE_FKEY: Final = 1002\n    SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER: Final = 1004\n    SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION: Final = 1005\n    SQLITE_DBCONFIG_ENABLE_QPSG: Final = 1007\n    SQLITE_DBCONFIG_ENABLE_TRIGGER: Final = 1003\n    SQLITE_DBCONFIG_ENABLE_VIEW: Final = 1015\n    SQLITE_DBCONFIG_LEGACY_ALTER_TABLE: Final = 1012\n    SQLITE_DBCONFIG_LEGACY_FILE_FORMAT: Final = 1016\n    SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE: Final = 1006\n    SQLITE_DBCONFIG_RESET_DATABASE: Final = 1009\n    SQLITE_DBCONFIG_TRIGGER_EQP: Final = 1008\n    SQLITE_DBCONFIG_TRUSTED_SCHEMA: Final = 1017\n    SQLITE_DBCONFIG_WRITABLE_SCHEMA: Final = 1011\n\nif sys.version_info >= (3, 11):\n    SQLITE_ABORT: Final = 4\n    SQLITE_ABORT_ROLLBACK: Final = 516\n    SQLITE_AUTH: Final = 23\n    SQLITE_AUTH_USER: Final = 279\n    SQLITE_BUSY: Final = 5\n    SQLITE_BUSY_RECOVERY: Final = 261\n    SQLITE_BUSY_SNAPSHOT: Final = 517\n    SQLITE_BUSY_TIMEOUT: Final = 773\n    SQLITE_CANTOPEN: Final = 14\n    SQLITE_CANTOPEN_CONVPATH: Final = 1038\n    SQLITE_CANTOPEN_DIRTYWAL: Final = 1294\n    SQLITE_CANTOPEN_FULLPATH: Final = 782\n    SQLITE_CANTOPEN_ISDIR: Final = 526\n    SQLITE_CANTOPEN_NOTEMPDIR: Final = 270\n    SQLITE_CANTOPEN_SYMLINK: Final = 1550\n    SQLITE_CONSTRAINT: Final = 19\n    SQLITE_CONSTRAINT_CHECK: Final = 275\n    SQLITE_CONSTRAINT_COMMITHOOK: Final = 531\n    SQLITE_CONSTRAINT_FOREIGNKEY: Final = 787\n    SQLITE_CONSTRAINT_FUNCTION: Final = 1043\n    SQLITE_CONSTRAINT_NOTNULL: Final = 1299\n    SQLITE_CONSTRAINT_PINNED: Final = 2835\n    SQLITE_CONSTRAINT_PRIMARYKEY: Final = 1555\n    SQLITE_CONSTRAINT_ROWID: Final = 2579\n    SQLITE_CONSTRAINT_TRIGGER: Final = 1811\n    SQLITE_CONSTRAINT_UNIQUE: Final = 2067\n    SQLITE_CONSTRAINT_VTAB: Final = 2323\n    SQLITE_CORRUPT: Final = 11\n    SQLITE_CORRUPT_INDEX: Final = 779\n    SQLITE_CORRUPT_SEQUENCE: Final = 523\n    SQLITE_CORRUPT_VTAB: Final = 267\n    SQLITE_EMPTY: Final = 16\n    SQLITE_ERROR: Final = 1\n    SQLITE_ERROR_MISSING_COLLSEQ: Final = 257\n    SQLITE_ERROR_RETRY: Final = 513\n    SQLITE_ERROR_SNAPSHOT: Final = 769\n    SQLITE_FORMAT: Final = 24\n    SQLITE_FULL: Final = 13\n    SQLITE_INTERNAL: Final = 2\n    SQLITE_INTERRUPT: Final = 9\n    SQLITE_IOERR: Final = 10\n    SQLITE_IOERR_ACCESS: Final = 3338\n    SQLITE_IOERR_AUTH: Final = 7178\n    SQLITE_IOERR_BEGIN_ATOMIC: Final = 7434\n    SQLITE_IOERR_BLOCKED: Final = 2826\n    SQLITE_IOERR_CHECKRESERVEDLOCK: Final = 3594\n    SQLITE_IOERR_CLOSE: Final = 4106\n    SQLITE_IOERR_COMMIT_ATOMIC: Final = 7690\n    SQLITE_IOERR_CONVPATH: Final = 6666\n    SQLITE_IOERR_CORRUPTFS: Final = 8458\n    SQLITE_IOERR_DATA: Final = 8202\n    SQLITE_IOERR_DELETE: Final = 2570\n    SQLITE_IOERR_DELETE_NOENT: Final = 5898\n    SQLITE_IOERR_DIR_CLOSE: Final = 4362\n    SQLITE_IOERR_DIR_FSYNC: Final = 1290\n    SQLITE_IOERR_FSTAT: Final = 1802\n    SQLITE_IOERR_FSYNC: Final = 1034\n    SQLITE_IOERR_GETTEMPPATH: Final = 6410\n    SQLITE_IOERR_LOCK: Final = 3850\n    SQLITE_IOERR_MMAP: Final = 6154\n    SQLITE_IOERR_NOMEM: Final = 3082\n    SQLITE_IOERR_RDLOCK: Final = 2314\n    SQLITE_IOERR_READ: Final = 266\n    SQLITE_IOERR_ROLLBACK_ATOMIC: Final = 7946\n    SQLITE_IOERR_SEEK: Final = 5642\n    SQLITE_IOERR_SHMLOCK: Final = 5130\n    SQLITE_IOERR_SHMMAP: Final = 5386\n    SQLITE_IOERR_SHMOPEN: Final = 4618\n    SQLITE_IOERR_SHMSIZE: Final = 4874\n    SQLITE_IOERR_SHORT_READ: Final = 522\n    SQLITE_IOERR_TRUNCATE: Final = 1546\n    SQLITE_IOERR_UNLOCK: Final = 2058\n    SQLITE_IOERR_VNODE: Final = 6922\n    SQLITE_IOERR_WRITE: Final = 778\n    SQLITE_LIMIT_ATTACHED: Final = 7\n    SQLITE_LIMIT_COLUMN: Final = 22\n    SQLITE_LIMIT_COMPOUND_SELECT: Final = 4\n    SQLITE_LIMIT_EXPR_DEPTH: Final = 3\n    SQLITE_LIMIT_FUNCTION_ARG: Final = 6\n    SQLITE_LIMIT_LENGTH: Final = 0\n    SQLITE_LIMIT_LIKE_PATTERN_LENGTH: Final = 8\n    SQLITE_LIMIT_SQL_LENGTH: Final = 1\n    SQLITE_LIMIT_TRIGGER_DEPTH: Final = 10\n    SQLITE_LIMIT_VARIABLE_NUMBER: Final = 9\n    SQLITE_LIMIT_VDBE_OP: Final = 5\n    SQLITE_LIMIT_WORKER_THREADS: Final = 11\n    SQLITE_LOCKED: Final = 6\n    SQLITE_LOCKED_SHAREDCACHE: Final = 262\n    SQLITE_LOCKED_VTAB: Final = 518\n    SQLITE_MISMATCH: Final = 20\n    SQLITE_MISUSE: Final = 21\n    SQLITE_NOLFS: Final = 22\n    SQLITE_NOMEM: Final = 7\n    SQLITE_NOTADB: Final = 26\n    SQLITE_NOTFOUND: Final = 12\n    SQLITE_NOTICE: Final = 27\n    SQLITE_NOTICE_RECOVER_ROLLBACK: Final = 539\n    SQLITE_NOTICE_RECOVER_WAL: Final = 283\n    SQLITE_OK_LOAD_PERMANENTLY: Final = 256\n    SQLITE_OK_SYMLINK: Final = 512\n    SQLITE_PERM: Final = 3\n    SQLITE_PROTOCOL: Final = 15\n    SQLITE_RANGE: Final = 25\n    SQLITE_READONLY: Final = 8\n    SQLITE_READONLY_CANTINIT: Final = 1288\n    SQLITE_READONLY_CANTLOCK: Final = 520\n    SQLITE_READONLY_DBMOVED: Final = 1032\n    SQLITE_READONLY_DIRECTORY: Final = 1544\n    SQLITE_READONLY_RECOVERY: Final = 264\n    SQLITE_READONLY_ROLLBACK: Final = 776\n    SQLITE_ROW: Final = 100\n    SQLITE_SCHEMA: Final = 17\n    SQLITE_TOOBIG: Final = 18\n    SQLITE_WARNING: Final = 28\n    SQLITE_WARNING_AUTOINDEX: Final = 284\n    threadsafety: Literal[0, 1, 3]\n\n# Can take or return anything depending on what's in the registry.\n@overload\ndef adapt(obj: Any, proto: Any, /) -> Any: ...\n@overload\ndef adapt(obj: Any, proto: Any, alt: _T, /) -> Any | _T: ...\ndef complete_statement(statement: str) -> bool: ...\n\nif sys.version_info >= (3, 12):\n    @overload\n    def connect(\n        database: StrOrBytesPath,\n        timeout: float = 5.0,\n        detect_types: int = 0,\n        isolation_level: _IsolationLevel = \"DEFERRED\",\n        check_same_thread: bool = True,\n        cached_statements: int = 128,\n        uri: bool = False,\n        *,\n        autocommit: bool = ...,\n    ) -> Connection: ...\n    @overload\n    def connect(\n        database: StrOrBytesPath,\n        timeout: float,\n        detect_types: int,\n        isolation_level: _IsolationLevel,\n        check_same_thread: bool,\n        factory: type[_ConnectionT],\n        cached_statements: int = 128,\n        uri: bool = False,\n        *,\n        autocommit: bool = ...,\n    ) -> _ConnectionT: ...\n    @overload\n    def connect(\n        database: StrOrBytesPath,\n        timeout: float = 5.0,\n        detect_types: int = 0,\n        isolation_level: _IsolationLevel = \"DEFERRED\",\n        check_same_thread: bool = True,\n        *,\n        factory: type[_ConnectionT],\n        cached_statements: int = 128,\n        uri: bool = False,\n        autocommit: bool = ...,\n    ) -> _ConnectionT: ...\n\nelse:\n    @overload\n    def connect(\n        database: StrOrBytesPath,\n        timeout: float = 5.0,\n        detect_types: int = 0,\n        isolation_level: _IsolationLevel = \"DEFERRED\",\n        check_same_thread: bool = True,\n        cached_statements: int = 128,\n        uri: bool = False,\n    ) -> Connection: ...\n    @overload\n    def connect(\n        database: StrOrBytesPath,\n        timeout: float,\n        detect_types: int,\n        isolation_level: _IsolationLevel,\n        check_same_thread: bool,\n        factory: type[_ConnectionT],\n        cached_statements: int = 128,\n        uri: bool = False,\n    ) -> _ConnectionT: ...\n    @overload\n    def connect(\n        database: StrOrBytesPath,\n        timeout: float = 5.0,\n        detect_types: int = 0,\n        isolation_level: _IsolationLevel = \"DEFERRED\",\n        check_same_thread: bool = True,\n        *,\n        factory: type[_ConnectionT],\n        cached_statements: int = 128,\n        uri: bool = False,\n    ) -> _ConnectionT: ...\n\ndef enable_callback_tracebacks(enable: bool, /) -> None: ...\n\nif sys.version_info < (3, 12):\n    # takes a pos-or-keyword argument because there is a C wrapper\n    def enable_shared_cache(do_enable: int) -> None: ...\n\nif sys.version_info >= (3, 10):\n    def register_adapter(type: type[_T], adapter: _Adapter[_T], /) -> None: ...\n    def register_converter(typename: str, converter: _Converter, /) -> None: ...\n\nelse:\n    def register_adapter(type: type[_T], caster: _Adapter[_T], /) -> None: ...\n    def register_converter(name: str, converter: _Converter, /) -> None: ...\n\nif sys.version_info < (3, 10):\n    OptimizedUnicode = str\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_ssl.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer, StrOrBytesPath\nfrom collections.abc import Callable\nfrom ssl import (\n    SSLCertVerificationError as SSLCertVerificationError,\n    SSLContext,\n    SSLEOFError as SSLEOFError,\n    SSLError as SSLError,\n    SSLObject,\n    SSLSyscallError as SSLSyscallError,\n    SSLWantReadError as SSLWantReadError,\n    SSLWantWriteError as SSLWantWriteError,\n    SSLZeroReturnError as SSLZeroReturnError,\n)\nfrom typing import Any, ClassVar, Final, Literal, TypedDict, final, overload, type_check_only\nfrom typing_extensions import NotRequired, Self, TypeAlias, deprecated, disjoint_base\n\n_PasswordType: TypeAlias = Callable[[], str | bytes | bytearray] | str | bytes | bytearray\n_PCTRTT: TypeAlias = tuple[tuple[str, str], ...]\n_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...]\n_PeerCertRetDictType: TypeAlias = dict[str, str | _PCTRTTT | _PCTRTT]\n\n@type_check_only\nclass _Cipher(TypedDict):\n    aead: bool\n    alg_bits: int\n    auth: str\n    description: str\n    digest: str | None\n    id: int\n    kea: str\n    name: str\n    protocol: str\n    strength_bits: int\n    symmetric: str\n\n@type_check_only\nclass _CertInfo(TypedDict):\n    subject: tuple[tuple[tuple[str, str], ...], ...]\n    issuer: tuple[tuple[tuple[str, str], ...], ...]\n    version: int\n    serialNumber: str\n    notBefore: str\n    notAfter: str\n    subjectAltName: NotRequired[tuple[tuple[str, str], ...] | None]\n    OCSP: NotRequired[tuple[str, ...] | None]\n    caIssuers: NotRequired[tuple[str, ...] | None]\n    crlDistributionPoints: NotRequired[tuple[str, ...] | None]\n\ndef RAND_add(string: str | ReadableBuffer, entropy: float, /) -> None: ...\ndef RAND_bytes(n: int, /) -> bytes: ...\n\nif sys.version_info < (3, 12):\n    @deprecated(\"Deprecated since Python 3.6; removed in Python 3.12. Use `ssl.RAND_bytes()` instead.\")\n    def RAND_pseudo_bytes(n: int, /) -> tuple[bytes, bool]: ...\n\nif sys.version_info < (3, 10):\n    def RAND_egd(path: str) -> None: ...\n\ndef RAND_status() -> bool: ...\ndef get_default_verify_paths() -> tuple[str, str, str, str]: ...\n\nif sys.platform == \"win32\":\n    _EnumRetType: TypeAlias = list[tuple[bytes, str, set[str] | bool]]\n    def enum_certificates(store_name: str) -> _EnumRetType: ...\n    def enum_crls(store_name: str) -> _EnumRetType: ...\n\ndef txt2obj(txt: str, name: bool = False) -> tuple[int, str, str, str]: ...\ndef nid2obj(nid: int, /) -> tuple[int, str, str, str]: ...\n@disjoint_base\nclass _SSLContext:\n    check_hostname: bool\n    keylog_filename: str | None\n    maximum_version: int\n    minimum_version: int\n    num_tickets: int\n    options: int\n    post_handshake_auth: bool\n    protocol: int\n    if sys.version_info >= (3, 10):\n        security_level: int\n    sni_callback: Callable[[SSLObject, str, SSLContext], None | int] | None\n    verify_flags: int\n    verify_mode: int\n    def __new__(cls, protocol: int, /) -> Self: ...\n    def cert_store_stats(self) -> dict[str, int]: ...\n    @overload\n    def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: ...\n    @overload\n    def get_ca_certs(self, binary_form: Literal[True]) -> list[bytes]: ...\n    @overload\n    def get_ca_certs(self, binary_form: bool = False) -> Any: ...\n    def get_ciphers(self) -> list[_Cipher]: ...\n    def load_cert_chain(\n        self, certfile: StrOrBytesPath, keyfile: StrOrBytesPath | None = None, password: _PasswordType | None = None\n    ) -> None: ...\n    def load_dh_params(self, path: str, /) -> None: ...\n    def load_verify_locations(\n        self,\n        cafile: StrOrBytesPath | None = None,\n        capath: StrOrBytesPath | None = None,\n        cadata: str | ReadableBuffer | None = None,\n    ) -> None: ...\n    def session_stats(self) -> dict[str, int]: ...\n    def set_ciphers(self, cipherlist: str, /) -> None: ...\n    def set_default_verify_paths(self) -> None: ...\n    def set_ecdh_curve(self, name: str, /) -> None: ...\n    if sys.version_info >= (3, 13):\n        def set_psk_client_callback(self, callback: Callable[[str | None], tuple[str | None, bytes]] | None) -> None: ...\n        def set_psk_server_callback(\n            self, callback: Callable[[str | None], bytes] | None, identity_hint: str | None = None\n        ) -> None: ...\n\n@final\nclass MemoryBIO:\n    eof: bool\n    pending: int\n    def __new__(self) -> Self: ...\n    def read(self, size: int = -1, /) -> bytes: ...\n    def write(self, b: ReadableBuffer, /) -> int: ...\n    def write_eof(self) -> None: ...\n\n@final\nclass SSLSession:\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    @property\n    def has_ticket(self) -> bool: ...\n    @property\n    def id(self) -> bytes: ...\n    @property\n    def ticket_lifetime_hint(self) -> int: ...\n    @property\n    def time(self) -> int: ...\n    @property\n    def timeout(self) -> int: ...\n\n# _ssl.Certificate is weird: it can't be instantiated or subclassed.\n# Instances can only be created via methods of the private _ssl._SSLSocket class,\n# for which the relevant method signatures are:\n#\n# class _SSLSocket:\n#     def get_unverified_chain(self) -> list[Certificate] | None: ...\n#     def get_verified_chain(self) -> list[Certificate] | None: ...\n#\n# You can find a _ssl._SSLSocket object as the _sslobj attribute of a ssl.SSLSocket object\n\nif sys.version_info >= (3, 10):\n    @final\n    class Certificate:\n        def get_info(self) -> _CertInfo: ...\n        @overload\n        def public_bytes(self) -> str: ...\n        @overload\n        def public_bytes(self, format: Literal[1] = 1, /) -> str: ...  # ENCODING_PEM\n        @overload\n        def public_bytes(self, format: Literal[2], /) -> bytes: ...  # ENCODING_DER\n        @overload\n        def public_bytes(self, format: int, /) -> str | bytes: ...\n\nif sys.version_info < (3, 12):\n    err_codes_to_names: dict[tuple[int, int], str]\n    err_names_to_codes: dict[str, tuple[int, int]]\n    lib_codes_to_names: dict[int, str]\n\n_DEFAULT_CIPHERS: Final[str]\n\n# SSL error numbers\nSSL_ERROR_ZERO_RETURN: Final = 6\nSSL_ERROR_WANT_READ: Final = 2\nSSL_ERROR_WANT_WRITE: Final = 3\nSSL_ERROR_WANT_X509_LOOKUP: Final = 4\nSSL_ERROR_SYSCALL: Final = 5\nSSL_ERROR_SSL: Final = 1\nSSL_ERROR_WANT_CONNECT: Final = 7\nSSL_ERROR_EOF: Final = 8\nSSL_ERROR_INVALID_ERROR_CODE: Final = 10\n\n# verify modes\nCERT_NONE: Final = 0\nCERT_OPTIONAL: Final = 1\nCERT_REQUIRED: Final = 2\n\n# verify flags\nVERIFY_DEFAULT: Final = 0\nVERIFY_CRL_CHECK_LEAF: Final = 0x4\nVERIFY_CRL_CHECK_CHAIN: Final = 0x8\nVERIFY_X509_STRICT: Final = 0x20\nVERIFY_X509_TRUSTED_FIRST: Final = 0x8000\nif sys.version_info >= (3, 10):\n    VERIFY_ALLOW_PROXY_CERTS: Final = 0x40\n    VERIFY_X509_PARTIAL_CHAIN: Final = 0x80000\n\n# alert descriptions\nALERT_DESCRIPTION_CLOSE_NOTIFY: Final = 0\nALERT_DESCRIPTION_UNEXPECTED_MESSAGE: Final = 10\nALERT_DESCRIPTION_BAD_RECORD_MAC: Final = 20\nALERT_DESCRIPTION_RECORD_OVERFLOW: Final = 22\nALERT_DESCRIPTION_DECOMPRESSION_FAILURE: Final = 30\nALERT_DESCRIPTION_HANDSHAKE_FAILURE: Final = 40\nALERT_DESCRIPTION_BAD_CERTIFICATE: Final = 42\nALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: Final = 43\nALERT_DESCRIPTION_CERTIFICATE_REVOKED: Final = 44\nALERT_DESCRIPTION_CERTIFICATE_EXPIRED: Final = 45\nALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: Final = 46\nALERT_DESCRIPTION_ILLEGAL_PARAMETER: Final = 47\nALERT_DESCRIPTION_UNKNOWN_CA: Final = 48\nALERT_DESCRIPTION_ACCESS_DENIED: Final = 49\nALERT_DESCRIPTION_DECODE_ERROR: Final = 50\nALERT_DESCRIPTION_DECRYPT_ERROR: Final = 51\nALERT_DESCRIPTION_PROTOCOL_VERSION: Final = 70\nALERT_DESCRIPTION_INSUFFICIENT_SECURITY: Final = 71\nALERT_DESCRIPTION_INTERNAL_ERROR: Final = 80\nALERT_DESCRIPTION_USER_CANCELLED: Final = 90\nALERT_DESCRIPTION_NO_RENEGOTIATION: Final = 100\nALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: Final = 110\nALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: Final = 111\nALERT_DESCRIPTION_UNRECOGNIZED_NAME: Final = 112\nALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: Final = 113\nALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: Final = 114\nALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: Final = 115\n\n# protocol versions\nPROTOCOL_SSLv23: Final = 2\nPROTOCOL_TLS: Final = 2\nPROTOCOL_TLS_CLIENT: Final = 16\nPROTOCOL_TLS_SERVER: Final = 17\nPROTOCOL_TLSv1: Final = 3\nPROTOCOL_TLSv1_1: Final = 4\nPROTOCOL_TLSv1_2: Final = 5\n\n# protocol options\nOP_ALL: Final = 0x80000050\nOP_NO_SSLv2: Final = 0x0\nOP_NO_SSLv3: Final = 0x2000000\nOP_NO_TLSv1: Final = 0x4000000\nOP_NO_TLSv1_1: Final = 0x10000000\nOP_NO_TLSv1_2: Final = 0x8000000\nOP_NO_TLSv1_3: Final = 0x20000000\nOP_CIPHER_SERVER_PREFERENCE: Final = 0x400000\nOP_SINGLE_DH_USE: Final = 0x0\nOP_NO_TICKET: Final = 0x4000\nOP_SINGLE_ECDH_USE: Final = 0x0\nOP_NO_COMPRESSION: Final = 0x20000\nOP_ENABLE_MIDDLEBOX_COMPAT: Final = 0x100000\nOP_NO_RENEGOTIATION: Final = 0x40000000\nif sys.version_info >= (3, 11) or sys.platform == \"linux\":\n    OP_IGNORE_UNEXPECTED_EOF: Final = 0x80\nif sys.version_info >= (3, 12):\n    OP_LEGACY_SERVER_CONNECT: Final = 0x4\n    OP_ENABLE_KTLS: Final = 0x8\n\n# host flags\nHOSTFLAG_ALWAYS_CHECK_SUBJECT: Final = 0x1\nHOSTFLAG_NEVER_CHECK_SUBJECT: Final = 0x20\nHOSTFLAG_NO_WILDCARDS: Final = 0x2\nHOSTFLAG_NO_PARTIAL_WILDCARDS: Final = 0x4\nHOSTFLAG_MULTI_LABEL_WILDCARDS: Final = 0x8\nHOSTFLAG_SINGLE_LABEL_SUBDOMAINS: Final = 0x10\n\nif sys.version_info >= (3, 10):\n    # certificate file types\n    ENCODING_PEM: Final = 1\n    ENCODING_DER: Final = 2\n\n# protocol versions\nPROTO_MINIMUM_SUPPORTED: Final = -2\nPROTO_MAXIMUM_SUPPORTED: Final = -1\nPROTO_SSLv3: Final[int]\nPROTO_TLSv1: Final[int]\nPROTO_TLSv1_1: Final[int]\nPROTO_TLSv1_2: Final[int]\nPROTO_TLSv1_3: Final[int]\n\n# feature support\nHAS_SNI: Final[bool]\nHAS_TLS_UNIQUE: Final[bool]\nHAS_ECDH: Final[bool]\nHAS_NPN: Final[bool]\nif sys.version_info >= (3, 13):\n    HAS_PSK: Final[bool]\nHAS_ALPN: Final[bool]\nHAS_SSLv2: Final[bool]\nHAS_SSLv3: Final[bool]\nHAS_TLSv1: Final[bool]\nHAS_TLSv1_1: Final[bool]\nHAS_TLSv1_2: Final[bool]\nHAS_TLSv1_3: Final[bool]\nif sys.version_info >= (3, 14):\n    HAS_PHA: Final[bool]\n\n# version info\nOPENSSL_VERSION_NUMBER: Final[int]\nOPENSSL_VERSION_INFO: Final[tuple[int, int, int, int, int]]\nOPENSSL_VERSION: Final[str]\n_OPENSSL_API_VERSION: Final[tuple[int, int, int, int, int]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_stat.pyi",
    "content": "import sys\nfrom typing import Final\n\nSF_APPEND: Final = 0x00040000\nSF_ARCHIVED: Final = 0x00010000\nSF_IMMUTABLE: Final = 0x00020000\nSF_NOUNLINK: Final = 0x00100000\nSF_SNAPSHOT: Final = 0x00200000\n\nST_MODE: Final = 0\nST_INO: Final = 1\nST_DEV: Final = 2\nST_NLINK: Final = 3\nST_UID: Final = 4\nST_GID: Final = 5\nST_SIZE: Final = 6\nST_ATIME: Final = 7\nST_MTIME: Final = 8\nST_CTIME: Final = 9\n\nS_IFIFO: Final = 0o010000\nS_IFLNK: Final = 0o120000\nS_IFREG: Final = 0o100000\nS_IFSOCK: Final = 0o140000\nS_IFBLK: Final = 0o060000\nS_IFCHR: Final = 0o020000\nS_IFDIR: Final = 0o040000\n\n# These are 0 on systems that don't support the specific kind of file.\n# Example: Linux doesn't support door files, so S_IFDOOR is 0 on linux.\nS_IFDOOR: Final[int]\nS_IFPORT: Final[int]\nS_IFWHT: Final[int]\n\nS_ISUID: Final = 0o4000\nS_ISGID: Final = 0o2000\nS_ISVTX: Final = 0o1000\n\nS_IRWXU: Final = 0o0700\nS_IRUSR: Final = 0o0400\nS_IWUSR: Final = 0o0200\nS_IXUSR: Final = 0o0100\n\nS_IRWXG: Final = 0o0070\nS_IRGRP: Final = 0o0040\nS_IWGRP: Final = 0o0020\nS_IXGRP: Final = 0o0010\n\nS_IRWXO: Final = 0o0007\nS_IROTH: Final = 0o0004\nS_IWOTH: Final = 0o0002\nS_IXOTH: Final = 0o0001\n\nS_ENFMT: Final = 0o2000\nS_IREAD: Final = 0o0400\nS_IWRITE: Final = 0o0200\nS_IEXEC: Final = 0o0100\n\nUF_APPEND: Final = 0x00000004\nUF_COMPRESSED: Final = 0x00000020  # OS X 10.6+ only\nUF_HIDDEN: Final = 0x00008000  # OX X 10.5+ only\nUF_IMMUTABLE: Final = 0x00000002\nUF_NODUMP: Final = 0x00000001\nUF_NOUNLINK: Final = 0x00000010\nUF_OPAQUE: Final = 0x00000008\n\ndef S_IMODE(mode: int, /) -> int: ...\ndef S_IFMT(mode: int, /) -> int: ...\ndef S_ISBLK(mode: int, /) -> bool: ...\ndef S_ISCHR(mode: int, /) -> bool: ...\ndef S_ISDIR(mode: int, /) -> bool: ...\ndef S_ISDOOR(mode: int, /) -> bool: ...\ndef S_ISFIFO(mode: int, /) -> bool: ...\ndef S_ISLNK(mode: int, /) -> bool: ...\ndef S_ISPORT(mode: int, /) -> bool: ...\ndef S_ISREG(mode: int, /) -> bool: ...\ndef S_ISSOCK(mode: int, /) -> bool: ...\ndef S_ISWHT(mode: int, /) -> bool: ...\ndef filemode(mode: int, /) -> str: ...\n\nif sys.platform == \"win32\":\n    IO_REPARSE_TAG_SYMLINK: Final = 0xA000000C\n    IO_REPARSE_TAG_MOUNT_POINT: Final = 0xA0000003\n    IO_REPARSE_TAG_APPEXECLINK: Final = 0x8000001B\n\nif sys.platform == \"win32\":\n    FILE_ATTRIBUTE_ARCHIVE: Final = 32\n    FILE_ATTRIBUTE_COMPRESSED: Final = 2048\n    FILE_ATTRIBUTE_DEVICE: Final = 64\n    FILE_ATTRIBUTE_DIRECTORY: Final = 16\n    FILE_ATTRIBUTE_ENCRYPTED: Final = 16384\n    FILE_ATTRIBUTE_HIDDEN: Final = 2\n    FILE_ATTRIBUTE_INTEGRITY_STREAM: Final = 32768\n    FILE_ATTRIBUTE_NORMAL: Final = 128\n    FILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Final = 8192\n    FILE_ATTRIBUTE_NO_SCRUB_DATA: Final = 131072\n    FILE_ATTRIBUTE_OFFLINE: Final = 4096\n    FILE_ATTRIBUTE_READONLY: Final = 1\n    FILE_ATTRIBUTE_REPARSE_POINT: Final = 1024\n    FILE_ATTRIBUTE_SPARSE_FILE: Final = 512\n    FILE_ATTRIBUTE_SYSTEM: Final = 4\n    FILE_ATTRIBUTE_TEMPORARY: Final = 256\n    FILE_ATTRIBUTE_VIRTUAL: Final = 65536\n\nif sys.version_info >= (3, 13):\n    # Varies by platform.\n    SF_SETTABLE: Final[int]\n    # https://github.com/python/cpython/issues/114081#issuecomment-2119017790\n    # SF_RESTRICTED: Literal[0x00080000]\n    SF_FIRMLINK: Final = 0x00800000\n    SF_DATALESS: Final = 0x40000000\n\n    if sys.platform == \"darwin\":\n        SF_SUPPORTED: Final = 0x9F0000\n        SF_SYNTHETIC: Final = 0xC0000000\n\n    UF_TRACKED: Final = 0x00000040\n    UF_DATAVAULT: Final = 0x00000080\n    UF_SETTABLE: Final = 0x0000FFFF\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_struct.pyi",
    "content": "from _typeshed import ReadableBuffer, WriteableBuffer\nfrom collections.abc import Iterator\nfrom typing import Any\nfrom typing_extensions import disjoint_base\n\ndef pack(fmt: str | bytes, /, *v: Any) -> bytes: ...\ndef pack_into(fmt: str | bytes, buffer: WriteableBuffer, offset: int, /, *v: Any) -> None: ...\ndef unpack(format: str | bytes, buffer: ReadableBuffer, /) -> tuple[Any, ...]: ...\ndef unpack_from(format: str | bytes, /, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: ...\ndef iter_unpack(format: str | bytes, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: ...\ndef calcsize(format: str | bytes, /) -> int: ...\n@disjoint_base\nclass Struct:\n    @property\n    def format(self) -> str: ...\n    @property\n    def size(self) -> int: ...\n    def __init__(self, format: str | bytes) -> None: ...\n    def pack(self, *v: Any) -> bytes: ...\n    def pack_into(self, buffer: WriteableBuffer, offset: int, *v: Any) -> None: ...\n    def unpack(self, buffer: ReadableBuffer, /) -> tuple[Any, ...]: ...\n    def unpack_from(self, buffer: ReadableBuffer, offset: int = 0) -> tuple[Any, ...]: ...\n    def iter_unpack(self, buffer: ReadableBuffer, /) -> Iterator[tuple[Any, ...]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_thread.pyi",
    "content": "import signal\nimport sys\nfrom _typeshed import structseq\nfrom collections.abc import Callable\nfrom threading import Thread\nfrom types import TracebackType\nfrom typing import Any, Final, NoReturn, final, overload\nfrom typing_extensions import TypeVarTuple, Unpack, deprecated, disjoint_base\n\n_Ts = TypeVarTuple(\"_Ts\")\n\nerror = RuntimeError\n\ndef _count() -> int: ...\n@final\nclass RLock:\n    def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ...\n    def release(self) -> None: ...\n    __enter__ = acquire\n    def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ...\n    if sys.version_info >= (3, 14):\n        def locked(self) -> bool: ...\n\nif sys.version_info >= (3, 13):\n    @final\n    class _ThreadHandle:\n        ident: int\n\n        def join(self, timeout: float | None = None, /) -> None: ...\n        def is_done(self) -> bool: ...\n        def _set_done(self) -> None: ...\n\n    def start_joinable_thread(\n        function: Callable[[], object], handle: _ThreadHandle | None = None, daemon: bool = True\n    ) -> _ThreadHandle: ...\n    @final\n    class lock:\n        def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ...\n        def release(self) -> None: ...\n        def locked(self) -> bool: ...\n        @deprecated(\"Obsolete synonym. Use `acquire()` instead.\")\n        def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: ...  # undocumented\n        @deprecated(\"Obsolete synonym. Use `release()` instead.\")\n        def release_lock(self) -> None: ...  # undocumented\n        @deprecated(\"Obsolete synonym. Use `locked()` instead.\")\n        def locked_lock(self) -> bool: ...  # undocumented\n        def __enter__(self) -> bool: ...\n        def __exit__(\n            self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n        ) -> None: ...\n\n    LockType = lock\nelse:\n    @final\n    class LockType:\n        def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ...\n        def release(self) -> None: ...\n        def locked(self) -> bool: ...\n        @deprecated(\"Obsolete synonym. Use `acquire()` instead.\")\n        def acquire_lock(self, blocking: bool = True, timeout: float = -1) -> bool: ...  # undocumented\n        @deprecated(\"Obsolete synonym. Use `release()` instead.\")\n        def release_lock(self) -> None: ...  # undocumented\n        @deprecated(\"Obsolete synonym. Use `locked()` instead.\")\n        def locked_lock(self) -> bool: ...  # undocumented\n        def __enter__(self) -> bool: ...\n        def __exit__(\n            self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n        ) -> None: ...\n\n@overload\ndef start_new_thread(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: ...\n@overload\ndef start_new_thread(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ...\n@overload\n@deprecated(\"Obsolete synonym. Use `start_new_thread()` instead.\")\ndef start_new(function: Callable[[Unpack[_Ts]], object], args: tuple[Unpack[_Ts]], /) -> int: ...  # undocumented\n@overload\n@deprecated(\"Obsolete synonym. Use `start_new_thread()` instead.\")\ndef start_new(function: Callable[..., object], args: tuple[Any, ...], kwargs: dict[str, Any], /) -> int: ...  # undocumented\n\nif sys.version_info >= (3, 10):\n    def interrupt_main(signum: signal.Signals = signal.SIGINT, /) -> None: ...\n\nelse:\n    def interrupt_main() -> None: ...\n\ndef exit() -> NoReturn: ...\n@deprecated(\"Obsolete synonym. Use `exit()` instead.\")\ndef exit_thread() -> NoReturn: ...  # undocumented\ndef allocate_lock() -> LockType: ...\n@deprecated(\"Obsolete synonym. Use `allocate_lock()` instead.\")\ndef allocate() -> LockType: ...  # undocumented\ndef get_ident() -> int: ...\ndef stack_size(size: int = 0, /) -> int: ...\n\nTIMEOUT_MAX: Final[float]\n\ndef get_native_id() -> int: ...  # only available on some platforms\n@final\nclass _ExceptHookArgs(structseq[Any], tuple[type[BaseException], BaseException | None, TracebackType | None, Thread | None]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"exc_type\", \"exc_value\", \"exc_traceback\", \"thread\")\n\n    @property\n    def exc_type(self) -> type[BaseException]: ...\n    @property\n    def exc_value(self) -> BaseException | None: ...\n    @property\n    def exc_traceback(self) -> TracebackType | None: ...\n    @property\n    def thread(self) -> Thread | None: ...\n\n_excepthook: Callable[[_ExceptHookArgs], Any]\n\nif sys.version_info >= (3, 12):\n    def daemon_threads_allowed() -> bool: ...\n\nif sys.version_info >= (3, 14):\n    def set_name(name: str) -> None: ...\n\n@disjoint_base\nclass _local:\n    def __getattribute__(self, name: str, /) -> Any: ...\n    def __setattr__(self, name: str, value: Any, /) -> None: ...\n    def __delattr__(self, name: str, /) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_threading_local.pyi",
    "content": "from threading import RLock\nfrom typing import Any\nfrom typing_extensions import Self, TypeAlias\nfrom weakref import ReferenceType\n\n__all__ = [\"local\"]\n_LocalDict: TypeAlias = dict[Any, Any]\n\nclass _localimpl:\n    __slots__ = (\"key\", \"dicts\", \"localargs\", \"locallock\", \"__weakref__\")\n    key: str\n    dicts: dict[int, tuple[ReferenceType[Any], _LocalDict]]\n    # Keep localargs in sync with the *args, **kwargs annotation on local.__new__\n    localargs: tuple[list[Any], dict[str, Any]]\n    locallock: RLock\n    def get_dict(self) -> _LocalDict: ...\n    def create_dict(self) -> _LocalDict: ...\n\nclass local:\n    __slots__ = (\"_local__impl\", \"__dict__\")\n    def __new__(cls, /, *args: Any, **kw: Any) -> Self: ...\n    def __getattribute__(self, name: str) -> Any: ...\n    def __setattr__(self, name: str, value: Any) -> None: ...\n    def __delattr__(self, name: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_tkinter.pyi",
    "content": "import sys\nfrom _typeshed import FileDescriptorLike, Incomplete\nfrom collections.abc import Callable\nfrom typing import Any, ClassVar, Final, Literal, final, overload\nfrom typing_extensions import TypeAlias, deprecated\n\n# _tkinter is meant to be only used internally by tkinter, but some tkinter\n# functions e.g. return _tkinter.Tcl_Obj objects. Tcl_Obj represents a Tcl\n# object that hasn't been converted to a string.\n#\n# There are not many ways to get Tcl_Objs from tkinter, and I'm not sure if the\n# only existing ways are supposed to return Tcl_Objs as opposed to returning\n# strings. Here's one of these things that return Tcl_Objs:\n#\n#    >>> import tkinter\n#    >>> text = tkinter.Text()\n#    >>> text.tag_add('foo', '1.0', 'end')\n#    >>> text.tag_ranges('foo')\n#    (<textindex object: '1.0'>, <textindex object: '2.0'>)\n@final\nclass Tcl_Obj:\n    @property\n    def string(self) -> str: ...\n    @property\n    def typename(self) -> str: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __eq__(self, value, /): ...\n    def __ge__(self, value, /): ...\n    def __gt__(self, value, /): ...\n    def __le__(self, value, /): ...\n    def __lt__(self, value, /): ...\n    def __ne__(self, value, /): ...\n\nclass TclError(Exception): ...\n\n_TkinterTraceFunc: TypeAlias = Callable[[tuple[str, ...]], object]\n\n# This class allows running Tcl code. Tkinter uses it internally a lot, and\n# it's often handy to drop a piece of Tcl code into a tkinter program. Example:\n#\n#    >>> import tkinter, _tkinter\n#    >>> tkapp = tkinter.Tk().tk\n#    >>> isinstance(tkapp, _tkinter.TkappType)\n#    True\n#    >>> tkapp.call('set', 'foo', (1,2,3))\n#    (1, 2, 3)\n#    >>> tkapp.eval('return $foo')\n#    '1 2 3'\n#    >>>\n#\n# call args can be pretty much anything. Also, call(some_tuple) is same as call(*some_tuple).\n#\n# eval always returns str because _tkinter_tkapp_eval_impl in _tkinter.c calls\n# Tkapp_UnicodeResult, and it returns a string when it succeeds.\n@final\nclass TkappType:\n    # Please keep in sync with tkinter.Tk\n    def adderrorinfo(self, msg: str, /) -> None: ...\n    def call(self, command: Any, /, *args: Any) -> Any: ...\n    # TODO: Figure out what arguments the following `func` callbacks should accept\n    def createcommand(self, name: str, func: Callable[..., object], /) -> None: ...\n    if sys.platform != \"win32\":\n        def createfilehandler(self, file: FileDescriptorLike, mask: int, func: Callable[..., object], /) -> None: ...\n        def deletefilehandler(self, file: FileDescriptorLike, /) -> None: ...\n\n    def createtimerhandler(self, milliseconds: int, func: Callable[..., object], /): ...\n    def deletecommand(self, name: str, /) -> None: ...\n    def dooneevent(self, flags: int = 0, /) -> int: ...\n    def eval(self, script: str, /) -> str: ...\n    def evalfile(self, fileName: str, /) -> str: ...\n    def exprboolean(self, s: str, /) -> Literal[0, 1]: ...\n    def exprdouble(self, s: str, /) -> float: ...\n    def exprlong(self, s: str, /) -> int: ...\n    def exprstring(self, s: str, /) -> str: ...\n    def getboolean(self, arg, /) -> bool: ...\n    def getdouble(self, arg, /) -> float: ...\n    def getint(self, arg, /) -> int: ...\n    def getvar(self, *args, **kwargs): ...\n    def globalgetvar(self, *args, **kwargs): ...\n    def globalsetvar(self, *args, **kwargs): ...\n    def globalunsetvar(self, *args, **kwargs): ...\n    def interpaddr(self) -> int: ...\n    def loadtk(self) -> None: ...\n    def mainloop(self, threshold: int = 0, /) -> None: ...\n    def quit(self) -> None: ...\n    def record(self, script: str, /) -> str: ...\n    def setvar(self, *ags, **kwargs): ...\n    if sys.version_info < (3, 11):\n        @deprecated(\"Deprecated since Python 3.9; removed in Python 3.11. Use `splitlist()` instead.\")\n        def split(self, arg, /): ...\n\n    def splitlist(self, arg, /) -> tuple[Incomplete, ...]: ...\n    def unsetvar(self, *args, **kwargs): ...\n    if sys.version_info >= (3, 14):\n        @overload\n        def wantobjects(self) -> Literal[0, 1]: ...\n    else:\n        @overload\n        def wantobjects(self) -> bool: ...\n\n    @overload\n    def wantobjects(self, wantobjects: Literal[0, 1] | bool, /) -> None: ...\n    def willdispatch(self) -> None: ...\n    if sys.version_info >= (3, 12):\n        def gettrace(self, /) -> _TkinterTraceFunc | None: ...\n        def settrace(self, func: _TkinterTraceFunc | None, /) -> None: ...\n\n# These should be kept in sync with tkinter.tix constants, except ALL_EVENTS which doesn't match TCL_ALL_EVENTS\nALL_EVENTS: Final = -3\nFILE_EVENTS: Final = 8\nIDLE_EVENTS: Final = 32\nTIMER_EVENTS: Final = 16\nWINDOW_EVENTS: Final = 4\n\nDONT_WAIT: Final = 2\nEXCEPTION: Final = 8\nREADABLE: Final = 2\nWRITABLE: Final = 4\n\nTCL_VERSION: Final[str]\nTK_VERSION: Final[str]\n\n@final\nclass TkttType:\n    def deletetimerhandler(self) -> None: ...\n\nif sys.version_info >= (3, 13):\n    def create(\n        screenName: str | None = None,\n        baseName: str = \"\",\n        className: str = \"Tk\",\n        interactive: bool = False,\n        wantobjects: int = 0,\n        wantTk: bool = True,\n        sync: bool = False,\n        use: str | None = None,\n        /,\n    ) -> TkappType: ...\n\nelse:\n    def create(\n        screenName: str | None = None,\n        baseName: str = \"\",\n        className: str = \"Tk\",\n        interactive: bool = False,\n        wantobjects: bool = False,\n        wantTk: bool = True,\n        sync: bool = False,\n        use: str | None = None,\n        /,\n    ) -> TkappType: ...\n\ndef getbusywaitinterval() -> int: ...\ndef setbusywaitinterval(new_val: int, /) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_tracemalloc.pyi",
    "content": "from collections.abc import Sequence\nfrom tracemalloc import _FrameTuple, _TraceTuple\n\ndef _get_object_traceback(obj: object, /) -> Sequence[_FrameTuple] | None: ...\ndef _get_traces() -> Sequence[_TraceTuple]: ...\ndef clear_traces() -> None: ...\ndef get_traceback_limit() -> int: ...\ndef get_traced_memory() -> tuple[int, int]: ...\ndef get_tracemalloc_memory() -> int: ...\ndef is_tracing() -> bool: ...\ndef reset_peak() -> None: ...\ndef start(nframe: int = 1, /) -> None: ...\ndef stop() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_typeshed/README.md",
    "content": "# Utility types for typeshed\n\nThis package and its submodules contain various common types used by\ntypeshed. It can also be used by packages outside typeshed, but beware\nthe API stability guarantees below.\n\n## Usage\n\nThe `_typeshed` package and its types do not exist at runtime, but can be\nused freely in stubs (`.pyi`) files. To import the types from this package in\nimplementation (`.py`) files, use the following construct:\n\n```python\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n    from _typeshed import ...\n```\n\nTypes can then be used in annotations by either quoting them or\nusing:\n\n```python\nfrom __future__ import annotations\n```\n\n## API Stability\n\nYou can use this package and its submodules outside of typeshed, but we\nguarantee only limited API stability. Items marked as \"stable\" will not be\nremoved or changed in an incompatible way for at least one year.\nBefore making such a change, the \"stable\" moniker will be removed\nand we will mark the type in question as deprecated. No guarantees\nare made about unmarked types.\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_typeshed/__init__.pyi",
    "content": "# Utility types for typeshed\n#\n# See the README.md file in this directory for more information.\n\nimport sys\nfrom collections.abc import Awaitable, Callable, Iterable, Iterator, Sequence, Set as AbstractSet, Sized\nfrom dataclasses import Field\nfrom os import PathLike\nfrom types import FrameType, TracebackType\nfrom typing import (\n    Any,\n    AnyStr,\n    ClassVar,\n    Final,\n    Generic,\n    Literal,\n    Protocol,\n    SupportsFloat,\n    SupportsIndex,\n    SupportsInt,\n    TypeVar,\n    final,\n    overload,\n)\nfrom typing_extensions import Buffer, LiteralString, Self as _Self, TypeAlias\n\n_KT = TypeVar(\"_KT\")\n_KT_co = TypeVar(\"_KT_co\", covariant=True)\n_KT_contra = TypeVar(\"_KT_contra\", contravariant=True)\n_VT = TypeVar(\"_VT\")\n_VT_co = TypeVar(\"_VT_co\", covariant=True)\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_T_contra = TypeVar(\"_T_contra\", contravariant=True)\n\n# Alternative to `typing_extensions.Self`, exclusively for use with `__new__`\n# in metaclasses:\n#     def __new__(cls: type[Self], ...) -> Self: ...\n# In other cases, use `typing_extensions.Self`.\nSelf = TypeVar(\"Self\")  # noqa: Y001\n\n# covariant version of typing.AnyStr, useful for protocols\nAnyStr_co = TypeVar(\"AnyStr_co\", str, bytes, covariant=True)  # noqa: Y001\n\n# For partially known annotations. Usually, fields where type annotations\n# haven't been added are left unannotated, but in some situations this\n# isn't possible or a type is already partially known. In cases like these,\n# use Incomplete instead of Any as a marker. For example, use\n# \"Incomplete | None\" instead of \"Any | None\".\nIncomplete: TypeAlias = Any  # stable\n\n# To describe a function parameter that is unused and will work with anything.\nUnused: TypeAlias = object  # stable\n\n# Marker for return types that include None, but where forcing the user to\n# check for None can be detrimental. Sometimes called \"the Any trick\". See\n# https://typing.python.org/en/latest/guides/writing_stubs.html#the-any-trick\n# for more information.\nMaybeNone: TypeAlias = Any  # stable\n\n# Used to mark arguments that default to a sentinel value. This prevents\n# stubtest from complaining about the default value not matching.\n#\n# def foo(x: int | None = sentinel) -> None: ...\n#\n# In cases where the sentinel object is exported and can be used by user code,\n# a construct like this is better:\n#\n# _SentinelType = NewType(\"_SentinelType\", object)  # does not exist at runtime\n# sentinel: Final[_SentinelType]\n# def foo(x: int | None | _SentinelType = ...) -> None: ...\nsentinel: Any  # stable\n\n# stable\nclass IdentityFunction(Protocol):\n    def __call__(self, x: _T, /) -> _T: ...\n\n# stable\nclass SupportsNext(Protocol[_T_co]):\n    def __next__(self) -> _T_co: ...\n\n# stable\nclass SupportsAnext(Protocol[_T_co]):\n    def __anext__(self) -> Awaitable[_T_co]: ...\n\nclass SupportsBool(Protocol):\n    def __bool__(self) -> bool: ...\n\n# Comparison protocols\nclass SupportsDunderLT(Protocol[_T_contra]):\n    def __lt__(self, other: _T_contra, /) -> SupportsBool: ...\n\nclass SupportsDunderGT(Protocol[_T_contra]):\n    def __gt__(self, other: _T_contra, /) -> SupportsBool: ...\n\nclass SupportsDunderLE(Protocol[_T_contra]):\n    def __le__(self, other: _T_contra, /) -> SupportsBool: ...\n\nclass SupportsDunderGE(Protocol[_T_contra]):\n    def __ge__(self, other: _T_contra, /) -> SupportsBool: ...\n\nclass SupportsAllComparisons(\n    SupportsDunderLT[Any], SupportsDunderGT[Any], SupportsDunderLE[Any], SupportsDunderGE[Any], Protocol\n): ...\n\nSupportsRichComparison: TypeAlias = SupportsDunderLT[Any] | SupportsDunderGT[Any]\nSupportsRichComparisonT = TypeVar(\"SupportsRichComparisonT\", bound=SupportsRichComparison)  # noqa: Y001\n\n# Dunder protocols\n\nclass SupportsAdd(Protocol[_T_contra, _T_co]):\n    def __add__(self, x: _T_contra, /) -> _T_co: ...\n\nclass SupportsRAdd(Protocol[_T_contra, _T_co]):\n    def __radd__(self, x: _T_contra, /) -> _T_co: ...\n\nclass SupportsSub(Protocol[_T_contra, _T_co]):\n    def __sub__(self, x: _T_contra, /) -> _T_co: ...\n\nclass SupportsRSub(Protocol[_T_contra, _T_co]):\n    def __rsub__(self, x: _T_contra, /) -> _T_co: ...\n\nclass SupportsMul(Protocol[_T_contra, _T_co]):\n    def __mul__(self, x: _T_contra, /) -> _T_co: ...\n\nclass SupportsRMul(Protocol[_T_contra, _T_co]):\n    def __rmul__(self, x: _T_contra, /) -> _T_co: ...\n\nclass SupportsDivMod(Protocol[_T_contra, _T_co]):\n    def __divmod__(self, other: _T_contra, /) -> _T_co: ...\n\nclass SupportsRDivMod(Protocol[_T_contra, _T_co]):\n    def __rdivmod__(self, other: _T_contra, /) -> _T_co: ...\n\n# This protocol is generic over the iterator type, while Iterable is\n# generic over the type that is iterated over.\nclass SupportsIter(Protocol[_T_co]):\n    def __iter__(self) -> _T_co: ...\n\n# This protocol is generic over the iterator type, while AsyncIterable is\n# generic over the type that is iterated over.\nclass SupportsAiter(Protocol[_T_co]):\n    def __aiter__(self) -> _T_co: ...\n\nclass SupportsLen(Protocol):\n    def __len__(self) -> int: ...\n\nclass SupportsLenAndGetItem(Protocol[_T_co]):\n    def __len__(self) -> int: ...\n    def __getitem__(self, k: int, /) -> _T_co: ...\n\nclass SupportsTrunc(Protocol):\n    def __trunc__(self) -> int: ...\n\n# Mapping-like protocols\n\n# stable\nclass SupportsItems(Protocol[_KT_co, _VT_co]):\n    def items(self) -> AbstractSet[tuple[_KT_co, _VT_co]]: ...\n\n# stable\nclass SupportsKeysAndGetItem(Protocol[_KT, _VT_co]):\n    def keys(self) -> Iterable[_KT]: ...\n    def __getitem__(self, key: _KT, /) -> _VT_co: ...\n\n# stable\nclass SupportsGetItem(Protocol[_KT_contra, _VT_co]):\n    def __getitem__(self, key: _KT_contra, /) -> _VT_co: ...\n\n# stable\nclass SupportsContainsAndGetItem(Protocol[_KT_contra, _VT_co]):\n    def __contains__(self, x: Any, /) -> bool: ...\n    def __getitem__(self, key: _KT_contra, /) -> _VT_co: ...\n\n# stable\nclass SupportsItemAccess(Protocol[_KT_contra, _VT]):\n    def __contains__(self, x: Any, /) -> bool: ...\n    def __getitem__(self, key: _KT_contra, /) -> _VT: ...\n    def __setitem__(self, key: _KT_contra, value: _VT, /) -> None: ...\n    def __delitem__(self, key: _KT_contra, /) -> None: ...\n\nStrPath: TypeAlias = str | PathLike[str]  # stable\nBytesPath: TypeAlias = bytes | PathLike[bytes]  # stable\nGenericPath: TypeAlias = AnyStr | PathLike[AnyStr]\nStrOrBytesPath: TypeAlias = str | bytes | PathLike[str] | PathLike[bytes]  # stable\n\nOpenTextModeUpdating: TypeAlias = Literal[\n    \"r+\",\n    \"+r\",\n    \"rt+\",\n    \"r+t\",\n    \"+rt\",\n    \"tr+\",\n    \"t+r\",\n    \"+tr\",\n    \"w+\",\n    \"+w\",\n    \"wt+\",\n    \"w+t\",\n    \"+wt\",\n    \"tw+\",\n    \"t+w\",\n    \"+tw\",\n    \"a+\",\n    \"+a\",\n    \"at+\",\n    \"a+t\",\n    \"+at\",\n    \"ta+\",\n    \"t+a\",\n    \"+ta\",\n    \"x+\",\n    \"+x\",\n    \"xt+\",\n    \"x+t\",\n    \"+xt\",\n    \"tx+\",\n    \"t+x\",\n    \"+tx\",\n]\nOpenTextModeWriting: TypeAlias = Literal[\"w\", \"wt\", \"tw\", \"a\", \"at\", \"ta\", \"x\", \"xt\", \"tx\"]\nOpenTextModeReading: TypeAlias = Literal[\"r\", \"rt\", \"tr\", \"U\", \"rU\", \"Ur\", \"rtU\", \"rUt\", \"Urt\", \"trU\", \"tUr\", \"Utr\"]\nOpenTextMode: TypeAlias = OpenTextModeUpdating | OpenTextModeWriting | OpenTextModeReading\nOpenBinaryModeUpdating: TypeAlias = Literal[\n    \"rb+\",\n    \"r+b\",\n    \"+rb\",\n    \"br+\",\n    \"b+r\",\n    \"+br\",\n    \"wb+\",\n    \"w+b\",\n    \"+wb\",\n    \"bw+\",\n    \"b+w\",\n    \"+bw\",\n    \"ab+\",\n    \"a+b\",\n    \"+ab\",\n    \"ba+\",\n    \"b+a\",\n    \"+ba\",\n    \"xb+\",\n    \"x+b\",\n    \"+xb\",\n    \"bx+\",\n    \"b+x\",\n    \"+bx\",\n]\nOpenBinaryModeWriting: TypeAlias = Literal[\"wb\", \"bw\", \"ab\", \"ba\", \"xb\", \"bx\"]\nOpenBinaryModeReading: TypeAlias = Literal[\"rb\", \"br\", \"rbU\", \"rUb\", \"Urb\", \"brU\", \"bUr\", \"Ubr\"]\nOpenBinaryMode: TypeAlias = OpenBinaryModeUpdating | OpenBinaryModeReading | OpenBinaryModeWriting\n\n# stable\nclass HasFileno(Protocol):\n    def fileno(self) -> int: ...\n\nFileDescriptor: TypeAlias = int  # stable\nFileDescriptorLike: TypeAlias = int | HasFileno  # stable\nFileDescriptorOrPath: TypeAlias = int | StrOrBytesPath\n\n# stable\nclass SupportsRead(Protocol[_T_co]):\n    def read(self, length: int = ..., /) -> _T_co: ...\n\n# stable\nclass SupportsReadline(Protocol[_T_co]):\n    def readline(self, length: int = ..., /) -> _T_co: ...\n\n# stable\nclass SupportsNoArgReadline(Protocol[_T_co]):\n    def readline(self) -> _T_co: ...\n\n# stable\nclass SupportsWrite(Protocol[_T_contra]):\n    def write(self, s: _T_contra, /) -> object: ...\n\n# stable\nclass SupportsFlush(Protocol):\n    def flush(self) -> object: ...\n\n# Suitable for dictionary view objects\nclass Viewable(Protocol[_T_co]):\n    def __len__(self) -> int: ...\n    def __iter__(self) -> Iterator[_T_co]: ...\n\nclass SupportsGetItemViewable(Protocol[_KT, _VT_co]):\n    def __len__(self) -> int: ...\n    def __iter__(self) -> Iterator[_KT]: ...\n    def __getitem__(self, key: _KT, /) -> _VT_co: ...\n\n# Unfortunately PEP 688 does not allow us to distinguish read-only\n# from writable buffers. We use these aliases for readability for now.\n# Perhaps a future extension of the buffer protocol will allow us to\n# distinguish these cases in the type system.\nReadOnlyBuffer: TypeAlias = Buffer  # stable\n# Anything that implements the read-write buffer interface.\nWriteableBuffer: TypeAlias = Buffer\n# Same as WriteableBuffer, but also includes read-only buffer types (like bytes).\nReadableBuffer: TypeAlias = Buffer  # stable\n\nclass SliceableBuffer(Buffer, Protocol):\n    def __getitem__(self, slice: slice[SupportsIndex | None], /) -> Sequence[int]: ...\n\nclass IndexableBuffer(Buffer, Protocol):\n    def __getitem__(self, i: int, /) -> int: ...\n\nclass SupportsGetItemBuffer(SliceableBuffer, IndexableBuffer, Protocol):\n    def __contains__(self, x: Any, /) -> bool: ...\n    @overload\n    def __getitem__(self, slice: slice[SupportsIndex | None], /) -> Sequence[int]: ...\n    @overload\n    def __getitem__(self, i: int, /) -> int: ...\n\nclass SizedBuffer(Sized, Buffer, Protocol): ...\n\nExcInfo: TypeAlias = tuple[type[BaseException], BaseException, TracebackType]\nOptExcInfo: TypeAlias = ExcInfo | tuple[None, None, None]\n\n# stable\nif sys.version_info >= (3, 10):\n    from types import NoneType as NoneType\nelse:\n    # Used by type checkers for checks involving None (does not exist at runtime)\n    @final\n    class NoneType:\n        def __bool__(self) -> Literal[False]: ...\n\n# This is an internal CPython type that is like, but subtly different from, a NamedTuple\n# Subclasses of this type are found in multiple modules.\n# In typeshed, `structseq` is only ever used as a mixin in combination with a fixed-length `Tuple`\n# See discussion at #6546 & #6560\n# `structseq` classes are unsubclassable, so are all decorated with `@final`.\nclass structseq(Generic[_T_co]):\n    n_fields: Final[int]\n    n_unnamed_fields: Final[int]\n    n_sequence_fields: Final[int]\n    # The first parameter will generally only take an iterable of a specific length.\n    # E.g. `os.uname_result` takes any iterable of length exactly 5.\n    #\n    # The second parameter will accept a dict of any kind without raising an exception,\n    # but only has any meaning if you supply it a dict where the keys are strings.\n    # https://github.com/python/typeshed/pull/6560#discussion_r767149830\n    def __new__(cls, sequence: Iterable[_T_co], dict: dict[str, Any] = ...) -> _Self: ...\n    if sys.version_info >= (3, 13):\n        def __replace__(self, **kwargs: Any) -> _Self: ...\n\n# Superset of typing.AnyStr that also includes LiteralString\nAnyOrLiteralStr = TypeVar(\"AnyOrLiteralStr\", str, bytes, LiteralString)  # noqa: Y001\n\n# Represents when str or LiteralStr is acceptable. Useful for string processing\n# APIs where literalness of return value depends on literalness of inputs\nStrOrLiteralStr = TypeVar(\"StrOrLiteralStr\", LiteralString, str)  # noqa: Y001\n\n# Objects suitable to be passed to sys.setprofile, threading.setprofile, and similar\nProfileFunction: TypeAlias = Callable[[FrameType, str, Any], object]\n\n# Objects suitable to be passed to sys.settrace, threading.settrace, and similar\nTraceFunction: TypeAlias = Callable[[FrameType, str, Any], TraceFunction | None]\n\n# experimental\n# Might not work as expected for pyright, see\n#   https://github.com/python/typeshed/pull/9362\n#   https://github.com/microsoft/pyright/issues/4339\nclass DataclassInstance(Protocol):\n    __dataclass_fields__: ClassVar[dict[str, Field[Any]]]\n\n# Anything that can be passed to the int/float constructors\nif sys.version_info >= (3, 14):\n    ConvertibleToInt: TypeAlias = str | ReadableBuffer | SupportsInt | SupportsIndex\nelse:\n    ConvertibleToInt: TypeAlias = str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc\nConvertibleToFloat: TypeAlias = str | ReadableBuffer | SupportsFloat | SupportsIndex\n\n# A few classes updated from Foo(str, Enum) to Foo(StrEnum). This is a convenience so these\n# can be accurate on all python versions without getting too wordy\nif sys.version_info >= (3, 11):\n    from enum import StrEnum as StrEnum\nelse:\n    from enum import Enum\n\n    class StrEnum(str, Enum): ...\n\n# Objects that appear in annotations or in type expressions.\n# Similar to PEP 747's TypeForm but a little broader.\nAnnotationForm: TypeAlias = Any\n\nif sys.version_info >= (3, 14):\n    from annotationlib import Format\n\n    # These return annotations, which can be arbitrary objects\n    AnnotateFunc: TypeAlias = Callable[[Format], dict[str, AnnotationForm]]\n    EvaluateFunc: TypeAlias = Callable[[Format], AnnotationForm]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_typeshed/_type_checker_internals.pyi",
    "content": "# Internals used by some type checkers.\n#\n# Don't use this module directly. It is only for type checkers to use.\n\nimport sys\nimport typing_extensions\nfrom _collections_abc import dict_items, dict_keys, dict_values\nfrom abc import ABCMeta\nfrom collections.abc import Awaitable, Generator, Iterable, Mapping\nfrom typing import Any, ClassVar, Generic, TypeVar, overload\nfrom typing_extensions import Never\n\n_T = TypeVar(\"_T\")\n\n# Used for an undocumented mypy feature. Does not exist at runtime.\npromote = object()\n\n# Fallback type providing methods and attributes that appear on all `TypedDict` types.\n# N.B. Keep this mostly in sync with typing_extensions._TypedDict/mypy_extensions._TypedDict\nclass TypedDictFallback(Mapping[str, object], metaclass=ABCMeta):\n    __total__: ClassVar[bool]\n    __required_keys__: ClassVar[frozenset[str]]\n    __optional_keys__: ClassVar[frozenset[str]]\n    # __orig_bases__ sometimes exists on <3.12, but not consistently,\n    # so we only add it to the stub on 3.12+\n    if sys.version_info >= (3, 12):\n        __orig_bases__: ClassVar[tuple[Any, ...]]\n    if sys.version_info >= (3, 13):\n        __readonly_keys__: ClassVar[frozenset[str]]\n        __mutable_keys__: ClassVar[frozenset[str]]\n\n    def copy(self) -> typing_extensions.Self: ...\n    # Using Never so that only calls using mypy plugin hook that specialize the signature\n    # can go through.\n    def setdefault(self, k: Never, default: object) -> object: ...\n    # Mypy plugin hook for 'pop' expects that 'default' has a type variable type.\n    def pop(self, k: Never, default: _T = ...) -> object: ...  # pyright: ignore[reportInvalidTypeVarUse]\n    def update(self, m: typing_extensions.Self, /) -> None: ...\n    def __delitem__(self, k: Never) -> None: ...\n    def items(self) -> dict_items[str, object]: ...\n    def keys(self) -> dict_keys[str, object]: ...\n    def values(self) -> dict_values[str, object]: ...\n    @overload\n    def __or__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ...\n    @overload\n    def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ...\n    @overload\n    def __ror__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ...\n    @overload\n    def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ...\n    # supposedly incompatible definitions of __or__ and __ior__\n    def __ior__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ...  # type: ignore[misc]\n\n# Fallback type providing methods and attributes that appear on all `NamedTuple` types.\nclass NamedTupleFallback(tuple[Any, ...]):\n    _field_defaults: ClassVar[dict[str, Any]]\n    _fields: ClassVar[tuple[str, ...]]\n    # __orig_bases__ sometimes exists on <3.12, but not consistently\n    # So we only add it to the stub on 3.12+.\n    if sys.version_info >= (3, 12):\n        __orig_bases__: ClassVar[tuple[Any, ...]]\n\n    @overload\n    def __init__(self, typename: str, fields: Iterable[tuple[str, Any]], /) -> None: ...\n    @overload\n    @typing_extensions.deprecated(\n        \"Creating a typing.NamedTuple using keyword arguments is deprecated and support will be removed in Python 3.15\"\n    )\n    def __init__(self, typename: str, fields: None = None, /, **kwargs: Any) -> None: ...\n    @classmethod\n    def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ...\n    def _asdict(self) -> dict[str, Any]: ...\n    def _replace(self, **kwargs: Any) -> typing_extensions.Self: ...\n    if sys.version_info >= (3, 13):\n        def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ...\n\n# Non-default variations to accommodate couroutines, and `AwaitableGenerator` having a 4th type parameter.\n_S = TypeVar(\"_S\")\n_YieldT_co = TypeVar(\"_YieldT_co\", covariant=True)\n_SendT_nd_contra = TypeVar(\"_SendT_nd_contra\", contravariant=True)\n_ReturnT_nd_co = TypeVar(\"_ReturnT_nd_co\", covariant=True)\n\n# The parameters correspond to Generator, but the 4th is the original type.\nclass AwaitableGenerator(\n    Awaitable[_ReturnT_nd_co],\n    Generator[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co],\n    Generic[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co, _S],\n    metaclass=ABCMeta,\n): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_typeshed/dbapi.pyi",
    "content": "# PEP 249 Database API 2.0 Types\n# https://www.python.org/dev/peps/pep-0249/\n\nfrom collections.abc import Mapping, Sequence\nfrom typing import Any, Protocol\nfrom typing_extensions import TypeAlias\n\nDBAPITypeCode: TypeAlias = Any | None\n# Strictly speaking, this should be a Sequence, but the type system does\n# not support fixed-length sequences.\nDBAPIColumnDescription: TypeAlias = tuple[str, DBAPITypeCode, int | None, int | None, int | None, int | None, bool | None]\n\nclass DBAPIConnection(Protocol):\n    def close(self) -> object: ...\n    def commit(self) -> object: ...\n    # optional:\n    # def rollback(self) -> Any: ...\n    def cursor(self) -> DBAPICursor: ...\n\nclass DBAPICursor(Protocol):\n    @property\n    def description(self) -> Sequence[DBAPIColumnDescription] | None: ...\n    @property\n    def rowcount(self) -> int: ...\n    # optional:\n    # def callproc(self, procname: str, parameters: Sequence[Any] = ..., /) -> Sequence[Any]: ...\n    def close(self) -> object: ...\n    def execute(self, operation: str, parameters: Sequence[Any] | Mapping[str, Any] = ..., /) -> object: ...\n    def executemany(self, operation: str, seq_of_parameters: Sequence[Sequence[Any]], /) -> object: ...\n    def fetchone(self) -> Sequence[Any] | None: ...\n    def fetchmany(self, size: int = ..., /) -> Sequence[Sequence[Any]]: ...\n    def fetchall(self) -> Sequence[Sequence[Any]]: ...\n    # optional:\n    # def nextset(self) -> None | Literal[True]: ...\n    arraysize: int\n    def setinputsizes(self, sizes: Sequence[DBAPITypeCode | int | None], /) -> object: ...\n    def setoutputsize(self, size: int, column: int = ..., /) -> object: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_typeshed/importlib.pyi",
    "content": "# Implicit protocols used in importlib.\n# We intentionally omit deprecated and optional methods.\n\nfrom collections.abc import Sequence\nfrom importlib.machinery import ModuleSpec\nfrom types import ModuleType\nfrom typing import Protocol\n\n__all__ = [\"LoaderProtocol\", \"MetaPathFinderProtocol\", \"PathEntryFinderProtocol\"]\n\nclass LoaderProtocol(Protocol):\n    def load_module(self, fullname: str, /) -> ModuleType: ...\n\nclass MetaPathFinderProtocol(Protocol):\n    def find_spec(self, fullname: str, path: Sequence[str] | None, target: ModuleType | None = ..., /) -> ModuleSpec | None: ...\n\nclass PathEntryFinderProtocol(Protocol):\n    def find_spec(self, fullname: str, target: ModuleType | None = ..., /) -> ModuleSpec | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_typeshed/wsgi.pyi",
    "content": "# Types to support PEP 3333 (WSGI)\n#\n# Obsolete since Python 3.11: Use wsgiref.types instead.\n#\n# See the README.md file in this directory for more information.\n\nimport sys\nfrom _typeshed import OptExcInfo\nfrom collections.abc import Callable, Iterable, Iterator\nfrom typing import Any, Protocol\nfrom typing_extensions import TypeAlias\n\nclass _Readable(Protocol):\n    def read(self, size: int = ..., /) -> bytes: ...\n    # Optional: def close(self) -> object: ...\n\nif sys.version_info >= (3, 11):\n    from wsgiref.types import *\nelse:\n    # stable\n    class StartResponse(Protocol):\n        def __call__(\n            self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = ..., /\n        ) -> Callable[[bytes], object]: ...\n\n    WSGIEnvironment: TypeAlias = dict[str, Any]  # stable\n    WSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]]  # stable\n\n    # WSGI input streams per PEP 3333, stable\n    class InputStream(Protocol):\n        def read(self, size: int = ..., /) -> bytes: ...\n        def readline(self, size: int = ..., /) -> bytes: ...\n        def readlines(self, hint: int = ..., /) -> list[bytes]: ...\n        def __iter__(self) -> Iterator[bytes]: ...\n\n    # WSGI error streams per PEP 3333, stable\n    class ErrorStream(Protocol):\n        def flush(self) -> object: ...\n        def write(self, s: str, /) -> object: ...\n        def writelines(self, seq: list[str], /) -> object: ...\n\n    # Optional file wrapper in wsgi.file_wrapper\n    class FileWrapper(Protocol):\n        def __call__(self, file: _Readable, block_size: int = ..., /) -> Iterable[bytes]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_typeshed/xml.pyi",
    "content": "# See the README.md file in this directory for more information.\n\nfrom typing import Any, Protocol\n\n# As defined https://docs.python.org/3/library/xml.dom.html#domimplementation-objects\nclass DOMImplementation(Protocol):\n    def hasFeature(self, feature: str, version: str | None, /) -> bool: ...\n    def createDocument(self, namespaceUri: str, qualifiedName: str, doctype: Any | None, /) -> Any: ...\n    def createDocumentType(self, qualifiedName: str, publicId: str, systemId: str, /) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_warnings.pyi",
    "content": "import sys\nfrom typing import Any, overload\n\n_defaultaction: str\n_onceregistry: dict[Any, Any]\nfilters: list[tuple[str, str | None, type[Warning], str | None, int]]\n\nif sys.version_info >= (3, 12):\n    @overload\n    def warn(\n        message: str,\n        category: type[Warning] | None = None,\n        stacklevel: int = 1,\n        source: Any | None = None,\n        *,\n        skip_file_prefixes: tuple[str, ...] = (),\n    ) -> None: ...\n    @overload\n    def warn(\n        message: Warning,\n        category: Any = None,\n        stacklevel: int = 1,\n        source: Any | None = None,\n        *,\n        skip_file_prefixes: tuple[str, ...] = (),\n    ) -> None: ...\n\nelse:\n    @overload\n    def warn(message: str, category: type[Warning] | None = None, stacklevel: int = 1, source: Any | None = None) -> None: ...\n    @overload\n    def warn(message: Warning, category: Any = None, stacklevel: int = 1, source: Any | None = None) -> None: ...\n\n@overload\ndef warn_explicit(\n    message: str,\n    category: type[Warning],\n    filename: str,\n    lineno: int,\n    module: str | None = ...,\n    registry: dict[str | tuple[str, type[Warning], int], int] | None = None,\n    module_globals: dict[str, Any] | None = None,\n    source: Any | None = None,\n) -> None: ...\n@overload\ndef warn_explicit(\n    message: Warning,\n    category: Any,\n    filename: str,\n    lineno: int,\n    module: str | None = None,\n    registry: dict[str | tuple[str, type[Warning], int], int] | None = None,\n    module_globals: dict[str, Any] | None = None,\n    source: Any | None = None,\n) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_weakref.pyi",
    "content": "from collections.abc import Callable\nfrom typing import Any, TypeVar, overload\nfrom weakref import CallableProxyType as CallableProxyType, ProxyType as ProxyType, ReferenceType as ReferenceType, ref as ref\n\n_C = TypeVar(\"_C\", bound=Callable[..., Any])\n_T = TypeVar(\"_T\")\n\ndef getweakrefcount(object: Any, /) -> int: ...\ndef getweakrefs(object: Any, /) -> list[Any]: ...\n\n# Return CallableProxyType if object is callable, ProxyType otherwise\n@overload\ndef proxy(object: _C, callback: Callable[[_C], Any] | None = None, /) -> CallableProxyType[_C]: ...\n@overload\ndef proxy(object: _T, callback: Callable[[_T], Any] | None = None, /) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_weakrefset.pyi",
    "content": "from collections.abc import Iterable, Iterator, MutableSet\nfrom types import GenericAlias\nfrom typing import Any, ClassVar, TypeVar, overload\nfrom typing_extensions import Self\n\n__all__ = [\"WeakSet\"]\n\n_S = TypeVar(\"_S\")\n_T = TypeVar(\"_T\")\n\nclass WeakSet(MutableSet[_T]):\n    @overload\n    def __init__(self, data: None = None) -> None: ...\n    @overload\n    def __init__(self, data: Iterable[_T]) -> None: ...\n    def add(self, item: _T) -> None: ...\n    def discard(self, item: _T) -> None: ...\n    def copy(self) -> Self: ...\n    def remove(self, item: _T) -> None: ...\n    def update(self, other: Iterable[_T]) -> None: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __contains__(self, item: object) -> bool: ...\n    def __len__(self) -> int: ...\n    def __iter__(self) -> Iterator[_T]: ...\n    def __ior__(self, other: Iterable[_T]) -> Self: ...  # type: ignore[override,misc]\n    def difference(self, other: Iterable[_T]) -> Self: ...\n    def __sub__(self, other: Iterable[Any]) -> Self: ...\n    def difference_update(self, other: Iterable[Any]) -> None: ...\n    def __isub__(self, other: Iterable[Any]) -> Self: ...\n    def intersection(self, other: Iterable[_T]) -> Self: ...\n    def __and__(self, other: Iterable[Any]) -> Self: ...\n    def intersection_update(self, other: Iterable[Any]) -> None: ...\n    def __iand__(self, other: Iterable[Any]) -> Self: ...\n    def issubset(self, other: Iterable[_T]) -> bool: ...\n    def __le__(self, other: Iterable[_T]) -> bool: ...\n    def __lt__(self, other: Iterable[_T]) -> bool: ...\n    def issuperset(self, other: Iterable[_T]) -> bool: ...\n    def __ge__(self, other: Iterable[_T]) -> bool: ...\n    def __gt__(self, other: Iterable[_T]) -> bool: ...\n    def __eq__(self, other: object) -> bool: ...\n    def symmetric_difference(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ...\n    def __xor__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ...\n    def symmetric_difference_update(self, other: Iterable[_T]) -> None: ...\n    def __ixor__(self, other: Iterable[_T]) -> Self: ...  # type: ignore[override,misc]\n    def union(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ...\n    def __or__(self, other: Iterable[_S]) -> WeakSet[_S | _T]: ...\n    def isdisjoint(self, other: Iterable[_T]) -> bool: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_winapi.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Sequence\nfrom typing import Any, Final, Literal, NoReturn, final, overload\n\nif sys.platform == \"win32\":\n    ABOVE_NORMAL_PRIORITY_CLASS: Final = 0x8000\n    BELOW_NORMAL_PRIORITY_CLASS: Final = 0x4000\n\n    CREATE_BREAKAWAY_FROM_JOB: Final = 0x1000000\n    CREATE_DEFAULT_ERROR_MODE: Final = 0x4000000\n    CREATE_NO_WINDOW: Final = 0x8000000\n    CREATE_NEW_CONSOLE: Final = 0x10\n    CREATE_NEW_PROCESS_GROUP: Final = 0x200\n\n    DETACHED_PROCESS: Final = 8\n    DUPLICATE_CLOSE_SOURCE: Final = 1\n    DUPLICATE_SAME_ACCESS: Final = 2\n\n    ERROR_ALREADY_EXISTS: Final = 183\n    ERROR_BROKEN_PIPE: Final = 109\n    ERROR_IO_PENDING: Final = 997\n    ERROR_MORE_DATA: Final = 234\n    ERROR_NETNAME_DELETED: Final = 64\n    ERROR_NO_DATA: Final = 232\n    ERROR_NO_SYSTEM_RESOURCES: Final = 1450\n    ERROR_OPERATION_ABORTED: Final = 995\n    ERROR_PIPE_BUSY: Final = 231\n    ERROR_PIPE_CONNECTED: Final = 535\n    ERROR_SEM_TIMEOUT: Final = 121\n\n    FILE_FLAG_FIRST_PIPE_INSTANCE: Final = 0x80000\n    FILE_FLAG_OVERLAPPED: Final = 0x40000000\n\n    FILE_GENERIC_READ: Final = 1179785\n    FILE_GENERIC_WRITE: Final = 1179926\n\n    FILE_MAP_ALL_ACCESS: Final = 983071\n    FILE_MAP_COPY: Final = 1\n    FILE_MAP_EXECUTE: Final = 32\n    FILE_MAP_READ: Final = 4\n    FILE_MAP_WRITE: Final = 2\n\n    FILE_TYPE_CHAR: Final = 2\n    FILE_TYPE_DISK: Final = 1\n    FILE_TYPE_PIPE: Final = 3\n    FILE_TYPE_REMOTE: Final = 32768\n    FILE_TYPE_UNKNOWN: Final = 0\n\n    GENERIC_READ: Final = 0x80000000\n    GENERIC_WRITE: Final = 0x40000000\n    HIGH_PRIORITY_CLASS: Final = 0x80\n    INFINITE: Final = 0xFFFFFFFF\n    # Ignore the Flake8 error -- flake8-pyi assumes\n    # most numbers this long will be implementation details,\n    # but here we can see that it's a power of 2\n    INVALID_HANDLE_VALUE: Final = 0xFFFFFFFFFFFFFFFF  # noqa: Y054\n    IDLE_PRIORITY_CLASS: Final = 0x40\n    NORMAL_PRIORITY_CLASS: Final = 0x20\n    REALTIME_PRIORITY_CLASS: Final = 0x100\n    NMPWAIT_WAIT_FOREVER: Final = 0xFFFFFFFF\n\n    MEM_COMMIT: Final = 0x1000\n    MEM_FREE: Final = 0x10000\n    MEM_IMAGE: Final = 0x1000000\n    MEM_MAPPED: Final = 0x40000\n    MEM_PRIVATE: Final = 0x20000\n    MEM_RESERVE: Final = 0x2000\n\n    NULL: Final = 0\n    OPEN_EXISTING: Final = 3\n\n    PIPE_ACCESS_DUPLEX: Final = 3\n    PIPE_ACCESS_INBOUND: Final = 1\n    PIPE_READMODE_MESSAGE: Final = 2\n    PIPE_TYPE_MESSAGE: Final = 4\n    PIPE_UNLIMITED_INSTANCES: Final = 255\n    PIPE_WAIT: Final = 0\n\n    PAGE_EXECUTE: Final = 0x10\n    PAGE_EXECUTE_READ: Final = 0x20\n    PAGE_EXECUTE_READWRITE: Final = 0x40\n    PAGE_EXECUTE_WRITECOPY: Final = 0x80\n    PAGE_GUARD: Final = 0x100\n    PAGE_NOACCESS: Final = 0x1\n    PAGE_NOCACHE: Final = 0x200\n    PAGE_READONLY: Final = 0x2\n    PAGE_READWRITE: Final = 0x4\n    PAGE_WRITECOMBINE: Final = 0x400\n    PAGE_WRITECOPY: Final = 0x8\n\n    PROCESS_ALL_ACCESS: Final = 0x1FFFFF\n    PROCESS_DUP_HANDLE: Final = 0x40\n\n    SEC_COMMIT: Final = 0x8000000\n    SEC_IMAGE: Final = 0x1000000\n    SEC_LARGE_PAGES: Final = 0x80000000\n    SEC_NOCACHE: Final = 0x10000000\n    SEC_RESERVE: Final = 0x4000000\n    SEC_WRITECOMBINE: Final = 0x40000000\n\n    if sys.version_info >= (3, 13):\n        STARTF_FORCEOFFFEEDBACK: Final = 0x80\n        STARTF_FORCEONFEEDBACK: Final = 0x40\n        STARTF_PREVENTPINNING: Final = 0x2000\n        STARTF_RUNFULLSCREEN: Final = 0x20\n        STARTF_TITLEISAPPID: Final = 0x1000\n        STARTF_TITLEISLINKNAME: Final = 0x800\n        STARTF_UNTRUSTEDSOURCE: Final = 0x8000\n        STARTF_USECOUNTCHARS: Final = 0x8\n        STARTF_USEFILLATTRIBUTE: Final = 0x10\n        STARTF_USEHOTKEY: Final = 0x200\n        STARTF_USEPOSITION: Final = 0x4\n        STARTF_USESIZE: Final = 0x2\n\n    STARTF_USESHOWWINDOW: Final = 0x1\n    STARTF_USESTDHANDLES: Final = 0x100\n\n    STD_ERROR_HANDLE: Final = 0xFFFFFFF4\n    STD_OUTPUT_HANDLE: Final = 0xFFFFFFF5\n    STD_INPUT_HANDLE: Final = 0xFFFFFFF6\n\n    STILL_ACTIVE: Final = 259\n    SW_HIDE: Final = 0\n    SYNCHRONIZE: Final = 0x100000\n    WAIT_ABANDONED_0: Final = 128\n    WAIT_OBJECT_0: Final = 0\n    WAIT_TIMEOUT: Final = 258\n\n    if sys.version_info >= (3, 10):\n        LOCALE_NAME_INVARIANT: Final[str]\n        LOCALE_NAME_MAX_LENGTH: Final[int]\n        LOCALE_NAME_SYSTEM_DEFAULT: Final[str]\n        LOCALE_NAME_USER_DEFAULT: Final[str | None]\n\n        LCMAP_FULLWIDTH: Final[int]\n        LCMAP_HALFWIDTH: Final[int]\n        LCMAP_HIRAGANA: Final[int]\n        LCMAP_KATAKANA: Final[int]\n        LCMAP_LINGUISTIC_CASING: Final[int]\n        LCMAP_LOWERCASE: Final[int]\n        LCMAP_SIMPLIFIED_CHINESE: Final[int]\n        LCMAP_TITLECASE: Final[int]\n        LCMAP_TRADITIONAL_CHINESE: Final[int]\n        LCMAP_UPPERCASE: Final[int]\n\n    if sys.version_info >= (3, 12):\n        COPYFILE2_CALLBACK_CHUNK_STARTED: Final = 1\n        COPYFILE2_CALLBACK_CHUNK_FINISHED: Final = 2\n        COPYFILE2_CALLBACK_STREAM_STARTED: Final = 3\n        COPYFILE2_CALLBACK_STREAM_FINISHED: Final = 4\n        COPYFILE2_CALLBACK_POLL_CONTINUE: Final = 5\n        COPYFILE2_CALLBACK_ERROR: Final = 6\n\n        COPYFILE2_PROGRESS_CONTINUE: Final = 0\n        COPYFILE2_PROGRESS_CANCEL: Final = 1\n        COPYFILE2_PROGRESS_STOP: Final = 2\n        COPYFILE2_PROGRESS_QUIET: Final = 3\n        COPYFILE2_PROGRESS_PAUSE: Final = 4\n\n        COPY_FILE_FAIL_IF_EXISTS: Final = 0x1\n        COPY_FILE_RESTARTABLE: Final = 0x2\n        COPY_FILE_OPEN_SOURCE_FOR_WRITE: Final = 0x4\n        COPY_FILE_ALLOW_DECRYPTED_DESTINATION: Final = 0x8\n        COPY_FILE_COPY_SYMLINK: Final = 0x800\n        COPY_FILE_NO_BUFFERING: Final = 0x1000\n        COPY_FILE_REQUEST_SECURITY_PRIVILEGES: Final = 0x2000\n        COPY_FILE_RESUME_FROM_PAUSE: Final = 0x4000\n        COPY_FILE_NO_OFFLOAD: Final = 0x40000\n        COPY_FILE_REQUEST_COMPRESSED_TRAFFIC: Final = 0x10000000\n\n        ERROR_ACCESS_DENIED: Final = 5\n        ERROR_PRIVILEGE_NOT_HELD: Final = 1314\n\n    if sys.version_info >= (3, 14):\n        COPY_FILE_DIRECTORY: Final = 0x00000080\n\n    def CloseHandle(handle: int, /) -> None: ...\n    @overload\n    def ConnectNamedPipe(handle: int, overlapped: Literal[True]) -> Overlapped: ...\n    @overload\n    def ConnectNamedPipe(handle: int, overlapped: Literal[False] = False) -> None: ...\n    @overload\n    def ConnectNamedPipe(handle: int, overlapped: bool) -> Overlapped | None: ...\n    def CreateFile(\n        file_name: str,\n        desired_access: int,\n        share_mode: int,\n        security_attributes: int,\n        creation_disposition: int,\n        flags_and_attributes: int,\n        template_file: int,\n        /,\n    ) -> int: ...\n    def CreateFileMapping(\n        file_handle: int, security_attributes: int, protect: int, max_size_high: int, max_size_low: int, name: str, /\n    ) -> int: ...\n    def CreateJunction(src_path: str, dst_path: str, /) -> None: ...\n    def CreateNamedPipe(\n        name: str,\n        open_mode: int,\n        pipe_mode: int,\n        max_instances: int,\n        out_buffer_size: int,\n        in_buffer_size: int,\n        default_timeout: int,\n        security_attributes: int,\n        /,\n    ) -> int: ...\n    def CreatePipe(pipe_attrs: Any, size: int, /) -> tuple[int, int]: ...\n    def CreateProcess(\n        application_name: str | None,\n        command_line: str | None,\n        proc_attrs: Any,\n        thread_attrs: Any,\n        inherit_handles: bool,\n        creation_flags: int,\n        env_mapping: dict[str, str],\n        current_directory: str | None,\n        startup_info: Any,\n        /,\n    ) -> tuple[int, int, int, int]: ...\n    def DuplicateHandle(\n        source_process_handle: int,\n        source_handle: int,\n        target_process_handle: int,\n        desired_access: int,\n        inherit_handle: bool,\n        options: int = 0,\n        /,\n    ) -> int: ...\n    def ExitProcess(ExitCode: int, /) -> NoReturn: ...\n    def GetACP() -> int: ...\n    def GetFileType(handle: int) -> int: ...\n    def GetCurrentProcess() -> int: ...\n    def GetExitCodeProcess(process: int, /) -> int: ...\n    def GetLastError() -> int: ...\n    def GetModuleFileName(module_handle: int, /) -> str: ...\n    def GetStdHandle(std_handle: int, /) -> int: ...\n    def GetVersion() -> int: ...\n    def MapViewOfFile(\n        file_map: int, desired_access: int, file_offset_high: int, file_offset_low: int, number_bytes: int, /\n    ) -> int: ...\n    def OpenProcess(desired_access: int, inherit_handle: bool, process_id: int, /) -> int: ...\n    def PeekNamedPipe(handle: int, size: int = 0, /) -> tuple[int, int] | tuple[bytes, int, int]: ...\n    if sys.version_info >= (3, 10):\n        def LCMapStringEx(locale: str, flags: int, src: str) -> str: ...\n        def UnmapViewOfFile(address: int, /) -> None: ...\n\n    @overload\n    def ReadFile(handle: int, size: int, overlapped: Literal[True]) -> tuple[Overlapped, int]: ...\n    @overload\n    def ReadFile(handle: int, size: int, overlapped: Literal[False] = False) -> tuple[bytes, int]: ...\n    @overload\n    def ReadFile(handle: int, size: int, overlapped: int | bool) -> tuple[Any, int]: ...\n    def SetNamedPipeHandleState(\n        named_pipe: int, mode: int | None, max_collection_count: int | None, collect_data_timeout: int | None, /\n    ) -> None: ...\n    def TerminateProcess(handle: int, exit_code: int, /) -> None: ...\n    def VirtualQuerySize(address: int, /) -> int: ...\n    def WaitForMultipleObjects(handle_seq: Sequence[int], wait_flag: bool, milliseconds: int = 0xFFFFFFFF, /) -> int: ...\n    def WaitForSingleObject(handle: int, milliseconds: int, /) -> int: ...\n    def WaitNamedPipe(name: str, timeout: int, /) -> None: ...\n    @overload\n    def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[True]) -> tuple[Overlapped, int]: ...\n    @overload\n    def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: Literal[False] = False) -> tuple[int, int]: ...\n    @overload\n    def WriteFile(handle: int, buffer: ReadableBuffer, overlapped: int | bool) -> tuple[Any, int]: ...\n    @final\n    class Overlapped:\n        event: int\n        def GetOverlappedResult(self, wait: bool, /) -> tuple[int, int]: ...\n        def cancel(self) -> None: ...\n        def getbuffer(self) -> bytes | None: ...\n\n    if sys.version_info >= (3, 13):\n        def BatchedWaitForMultipleObjects(\n            handle_seq: Sequence[int], wait_all: bool, milliseconds: int = 0xFFFFFFFF\n        ) -> list[int]: ...\n        def CreateEventW(security_attributes: int, manual_reset: bool, initial_state: bool, name: str | None) -> int: ...\n        def CreateMutexW(security_attributes: int, initial_owner: bool, name: str) -> int: ...\n        def GetLongPathName(path: str) -> str: ...\n        def GetShortPathName(path: str) -> str: ...\n        def OpenEventW(desired_access: int, inherit_handle: bool, name: str) -> int: ...\n        def OpenMutexW(desired_access: int, inherit_handle: bool, name: str) -> int: ...\n        def ReleaseMutex(mutex: int) -> None: ...\n        def ResetEvent(event: int) -> None: ...\n        def SetEvent(event: int) -> None: ...\n\n    def OpenFileMapping(desired_access: int, inherit_handle: bool, name: str, /) -> int: ...\n\n    if sys.version_info >= (3, 12):\n        def CopyFile2(existing_file_name: str, new_file_name: str, flags: int, progress_routine: int | None = None) -> int: ...\n        def NeedCurrentDirectoryForExePath(exe_name: str, /) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/_zstd.pyi",
    "content": "from _typeshed import ReadableBuffer\nfrom collections.abc import Mapping\nfrom compression.zstd import CompressionParameter, DecompressionParameter\nfrom typing import Final, Literal, final\nfrom typing_extensions import Self, TypeAlias\n\nZSTD_CLEVEL_DEFAULT: Final = 3\nZSTD_DStreamOutSize: Final = 131072\nZSTD_btlazy2: Final = 6\nZSTD_btopt: Final = 7\nZSTD_btultra: Final = 8\nZSTD_btultra2: Final = 9\nZSTD_c_chainLog: Final = 103\nZSTD_c_checksumFlag: Final = 201\nZSTD_c_compressionLevel: Final = 100\nZSTD_c_contentSizeFlag: Final = 200\nZSTD_c_dictIDFlag: Final = 202\nZSTD_c_enableLongDistanceMatching: Final = 160\nZSTD_c_hashLog: Final = 102\nZSTD_c_jobSize: Final = 401\nZSTD_c_ldmBucketSizeLog: Final = 163\nZSTD_c_ldmHashLog: Final = 161\nZSTD_c_ldmHashRateLog: Final = 164\nZSTD_c_ldmMinMatch: Final = 162\nZSTD_c_minMatch: Final = 105\nZSTD_c_nbWorkers: Final = 400\nZSTD_c_overlapLog: Final = 402\nZSTD_c_searchLog: Final = 104\nZSTD_c_strategy: Final = 107\nZSTD_c_targetLength: Final = 106\nZSTD_c_windowLog: Final = 101\nZSTD_d_windowLogMax: Final = 100\nZSTD_dfast: Final = 2\nZSTD_fast: Final = 1\nZSTD_greedy: Final = 3\nZSTD_lazy: Final = 4\nZSTD_lazy2: Final = 5\n\n_ZstdCompressorContinue: TypeAlias = Literal[0]\n_ZstdCompressorFlushBlock: TypeAlias = Literal[1]\n_ZstdCompressorFlushFrame: TypeAlias = Literal[2]\n\n@final\nclass ZstdCompressor:\n    CONTINUE: Final = 0\n    FLUSH_BLOCK: Final = 1\n    FLUSH_FRAME: Final = 2\n    def __new__(\n        cls,\n        level: int | None = None,\n        options: Mapping[int, int] | None = None,\n        zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n    ) -> Self: ...\n    def compress(\n        self, /, data: ReadableBuffer, mode: _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 0\n    ) -> bytes: ...\n    def flush(self, /, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 2) -> bytes: ...\n    def set_pledged_input_size(self, size: int | None, /) -> None: ...\n    @property\n    def last_mode(self) -> _ZstdCompressorContinue | _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame: ...\n\n@final\nclass ZstdDecompressor:\n    def __new__(\n        cls, zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, options: Mapping[int, int] | None = None\n    ) -> Self: ...\n    def decompress(self, /, data: ReadableBuffer, max_length: int = -1) -> bytes: ...\n    @property\n    def eof(self) -> bool: ...\n    @property\n    def needs_input(self) -> bool: ...\n    @property\n    def unused_data(self) -> bytes: ...\n\n@final\nclass ZstdDict:\n    def __new__(cls, dict_content: bytes, /, *, is_raw: bool = False) -> Self: ...\n    def __len__(self, /) -> int: ...\n    @property\n    def as_digested_dict(self) -> tuple[Self, int]: ...\n    @property\n    def as_prefix(self) -> tuple[Self, int]: ...\n    @property\n    def as_undigested_dict(self) -> tuple[Self, int]: ...\n    @property\n    def dict_content(self) -> bytes: ...\n    @property\n    def dict_id(self) -> int: ...\n\nclass ZstdError(Exception): ...\n\ndef finalize_dict(\n    custom_dict_bytes: bytes, samples_bytes: bytes, samples_sizes: tuple[int, ...], dict_size: int, compression_level: int, /\n) -> bytes: ...\ndef get_frame_info(frame_buffer: ReadableBuffer) -> tuple[int, int]: ...\ndef get_frame_size(frame_buffer: ReadableBuffer) -> int: ...\ndef get_param_bounds(parameter: int, is_compress: bool) -> tuple[int, int]: ...\ndef set_parameter_types(c_parameter_type: type[CompressionParameter], d_parameter_type: type[DecompressionParameter]) -> None: ...\ndef train_dict(samples_bytes: bytes, samples_sizes: tuple[int, ...], dict_size: int, /) -> bytes: ...\n\nzstd_version: Final[str]\nzstd_version_number: Final[int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/abc.pyi",
    "content": "import _typeshed\nimport sys\nfrom _typeshed import SupportsWrite\nfrom collections.abc import Callable\nfrom typing import Any, Literal, TypeVar\nfrom typing_extensions import Concatenate, ParamSpec, deprecated\n\n_T = TypeVar(\"_T\")\n_R_co = TypeVar(\"_R_co\", covariant=True)\n_FuncT = TypeVar(\"_FuncT\", bound=Callable[..., Any])\n_P = ParamSpec(\"_P\")\n\n# These definitions have special processing in mypy\nclass ABCMeta(type):\n    __abstractmethods__: frozenset[str]\n    if sys.version_info >= (3, 11):\n        def __new__(\n            mcls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwargs: Any\n        ) -> _typeshed.Self: ...\n    else:\n        def __new__(\n            mcls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], **kwargs: Any\n        ) -> _typeshed.Self: ...\n\n    def __instancecheck__(cls: ABCMeta, instance: Any, /) -> bool: ...\n    def __subclasscheck__(cls: ABCMeta, subclass: type, /) -> bool: ...\n    def _dump_registry(cls: ABCMeta, file: SupportsWrite[str] | None = None) -> None: ...\n    def register(cls: ABCMeta, subclass: type[_T]) -> type[_T]: ...\n\ndef abstractmethod(funcobj: _FuncT) -> _FuncT: ...\n@deprecated(\"Deprecated since Python 3.3. Use `@classmethod` stacked on top of `@abstractmethod` instead.\")\nclass abstractclassmethod(classmethod[_T, _P, _R_co]):\n    __isabstractmethod__: Literal[True]\n    def __init__(self, callable: Callable[Concatenate[type[_T], _P], _R_co]) -> None: ...\n\n@deprecated(\"Deprecated since Python 3.3. Use `@staticmethod` stacked on top of `@abstractmethod` instead.\")\nclass abstractstaticmethod(staticmethod[_P, _R_co]):\n    __isabstractmethod__: Literal[True]\n    def __init__(self, callable: Callable[_P, _R_co]) -> None: ...\n\n@deprecated(\"Deprecated since Python 3.3. Use `@property` stacked on top of `@abstractmethod` instead.\")\nclass abstractproperty(property):\n    __isabstractmethod__: Literal[True]\n\nclass ABC(metaclass=ABCMeta):\n    __slots__ = ()\n\ndef get_cache_token() -> object: ...\n\nif sys.version_info >= (3, 10):\n    def update_abstractmethods(cls: type[_T]) -> type[_T]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/aifc.pyi",
    "content": "from types import TracebackType\nfrom typing import IO, Any, Literal, NamedTuple, overload\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\"Error\", \"open\"]\n\nclass Error(Exception): ...\n\nclass _aifc_params(NamedTuple):\n    nchannels: int\n    sampwidth: int\n    framerate: int\n    nframes: int\n    comptype: bytes\n    compname: bytes\n\n_File: TypeAlias = str | IO[bytes]\n_Marker: TypeAlias = tuple[int, int, bytes]\n\nclass Aifc_read:\n    def __init__(self, f: _File) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n    def initfp(self, file: IO[bytes]) -> None: ...\n    def getfp(self) -> IO[bytes]: ...\n    def rewind(self) -> None: ...\n    def close(self) -> None: ...\n    def tell(self) -> int: ...\n    def getnchannels(self) -> int: ...\n    def getnframes(self) -> int: ...\n    def getsampwidth(self) -> int: ...\n    def getframerate(self) -> int: ...\n    def getcomptype(self) -> bytes: ...\n    def getcompname(self) -> bytes: ...\n    def getparams(self) -> _aifc_params: ...\n    def getmarkers(self) -> list[_Marker] | None: ...\n    def getmark(self, id: int) -> _Marker: ...\n    def setpos(self, pos: int) -> None: ...\n    def readframes(self, nframes: int) -> bytes: ...\n\nclass Aifc_write:\n    def __init__(self, f: _File) -> None: ...\n    def __del__(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n    def initfp(self, file: IO[bytes]) -> None: ...\n    def aiff(self) -> None: ...\n    def aifc(self) -> None: ...\n    def setnchannels(self, nchannels: int) -> None: ...\n    def getnchannels(self) -> int: ...\n    def setsampwidth(self, sampwidth: int) -> None: ...\n    def getsampwidth(self) -> int: ...\n    def setframerate(self, framerate: int) -> None: ...\n    def getframerate(self) -> int: ...\n    def setnframes(self, nframes: int) -> None: ...\n    def getnframes(self) -> int: ...\n    def setcomptype(self, comptype: bytes, compname: bytes) -> None: ...\n    def getcomptype(self) -> bytes: ...\n    def getcompname(self) -> bytes: ...\n    def setparams(self, params: tuple[int, int, int, int, bytes, bytes]) -> None: ...\n    def getparams(self) -> _aifc_params: ...\n    def setmark(self, id: int, pos: int, name: bytes) -> None: ...\n    def getmark(self, id: int) -> _Marker: ...\n    def getmarkers(self) -> list[_Marker] | None: ...\n    def tell(self) -> int: ...\n    def writeframesraw(self, data: Any) -> None: ...  # Actual type for data is Buffer Protocol\n    def writeframes(self, data: Any) -> None: ...\n    def close(self) -> None: ...\n\n@overload\ndef open(f: _File, mode: Literal[\"r\", \"rb\"]) -> Aifc_read: ...\n@overload\ndef open(f: _File, mode: Literal[\"w\", \"wb\"]) -> Aifc_write: ...\n@overload\ndef open(f: _File, mode: str | None = None) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/annotationlib.pyi",
    "content": "import sys\nfrom typing import Literal\n\nif sys.version_info >= (3, 14):\n    import enum\n    import types\n    from _typeshed import AnnotateFunc, AnnotationForm, EvaluateFunc, SupportsItems\n    from collections.abc import Mapping\n    from typing import Any, ParamSpec, TypeVar, TypeVarTuple, final, overload\n    from warnings import deprecated\n\n    __all__ = [\n        \"Format\",\n        \"ForwardRef\",\n        \"call_annotate_function\",\n        \"call_evaluate_function\",\n        \"get_annotate_from_class_namespace\",\n        \"get_annotations\",\n        \"annotations_to_string\",\n        \"type_repr\",\n    ]\n\n    class Format(enum.IntEnum):\n        VALUE = 1\n        VALUE_WITH_FAKE_GLOBALS = 2\n        FORWARDREF = 3\n        STRING = 4\n\n    @final\n    class ForwardRef:\n        __slots__ = (\n            \"__forward_is_argument__\",\n            \"__forward_is_class__\",\n            \"__forward_module__\",\n            \"__weakref__\",\n            \"__arg__\",\n            \"__globals__\",\n            \"__extra_names__\",\n            \"__code__\",\n            \"__ast_node__\",\n            \"__cell__\",\n            \"__owner__\",\n            \"__stringifier_dict__\",\n        )\n        __forward_is_argument__: bool\n        __forward_is_class__: bool\n        __forward_module__: str | None\n        def __init__(\n            self, arg: str, *, module: str | None = None, owner: object = None, is_argument: bool = True, is_class: bool = False\n        ) -> None: ...\n        @overload\n        def evaluate(\n            self,\n            *,\n            globals: dict[str, Any] | None = None,\n            locals: Mapping[str, Any] | None = None,\n            type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None,\n            owner: object = None,\n            format: Literal[Format.STRING],\n        ) -> str: ...\n        @overload\n        def evaluate(\n            self,\n            *,\n            globals: dict[str, Any] | None = None,\n            locals: Mapping[str, Any] | None = None,\n            type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None,\n            owner: object = None,\n            format: Literal[Format.FORWARDREF],\n        ) -> AnnotationForm | ForwardRef: ...\n        @overload\n        def evaluate(\n            self,\n            *,\n            globals: dict[str, Any] | None = None,\n            locals: Mapping[str, Any] | None = None,\n            type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None,\n            owner: object = None,\n            format: Format = Format.VALUE,  # noqa: Y011\n        ) -> AnnotationForm: ...\n        @deprecated(\"Use `ForwardRef.evaluate()` or `typing.evaluate_forward_ref()` instead.\")\n        def _evaluate(\n            self,\n            globalns: dict[str, Any] | None,\n            localns: Mapping[str, Any] | None,\n            type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = ...,\n            *,\n            recursive_guard: frozenset[str],\n        ) -> AnnotationForm: ...\n        @property\n        def __forward_arg__(self) -> str: ...\n        @property\n        def __forward_code__(self) -> types.CodeType: ...\n        def __eq__(self, other: object) -> bool: ...\n        def __hash__(self) -> int: ...\n        def __or__(self, other: Any) -> types.UnionType: ...\n        def __ror__(self, other: Any) -> types.UnionType: ...\n\n    @overload\n    def call_evaluate_function(evaluate: EvaluateFunc, format: Literal[Format.STRING], *, owner: object = None) -> str: ...\n    @overload\n    def call_evaluate_function(\n        evaluate: EvaluateFunc, format: Literal[Format.FORWARDREF], *, owner: object = None\n    ) -> AnnotationForm | ForwardRef: ...\n    @overload\n    def call_evaluate_function(evaluate: EvaluateFunc, format: Format, *, owner: object = None) -> AnnotationForm: ...\n    @overload\n    def call_annotate_function(\n        annotate: AnnotateFunc, format: Literal[Format.STRING], *, owner: object = None\n    ) -> dict[str, str]: ...\n    @overload\n    def call_annotate_function(\n        annotate: AnnotateFunc, format: Literal[Format.FORWARDREF], *, owner: object = None\n    ) -> dict[str, AnnotationForm | ForwardRef]: ...\n    @overload\n    def call_annotate_function(annotate: AnnotateFunc, format: Format, *, owner: object = None) -> dict[str, AnnotationForm]: ...\n    def get_annotate_from_class_namespace(obj: Mapping[str, object]) -> AnnotateFunc | None: ...\n    @overload\n    def get_annotations(\n        obj: Any,  # any object with __annotations__ or __annotate__\n        *,\n        globals: dict[str, object] | None = None,\n        locals: Mapping[str, object] | None = None,\n        eval_str: bool = False,\n        format: Literal[Format.STRING],\n    ) -> dict[str, str]: ...\n    @overload\n    def get_annotations(\n        obj: Any,\n        *,\n        globals: dict[str, object] | None = None,\n        locals: Mapping[str, object] | None = None,\n        eval_str: bool = False,\n        format: Literal[Format.FORWARDREF],\n    ) -> dict[str, AnnotationForm | ForwardRef]: ...\n    @overload\n    def get_annotations(\n        obj: Any,\n        *,\n        globals: dict[str, object] | None = None,\n        locals: Mapping[str, object] | None = None,\n        eval_str: bool = False,\n        format: Format = Format.VALUE,  # noqa: Y011\n    ) -> dict[str, AnnotationForm]: ...\n    def type_repr(value: object) -> str: ...\n    def annotations_to_string(annotations: SupportsItems[str, object]) -> dict[str, str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/antigravity.pyi",
    "content": "from _typeshed import ReadableBuffer\n\ndef geohash(latitude: float, longitude: float, datedow: ReadableBuffer) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/argparse.pyi",
    "content": "import sys\nfrom _typeshed import SupportsWrite, sentinel\nfrom collections.abc import Callable, Generator, Iterable, Sequence\nfrom re import Pattern\nfrom typing import IO, Any, ClassVar, Final, Generic, NewType, NoReturn, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, deprecated\n\n__all__ = [\n    \"ArgumentParser\",\n    \"ArgumentError\",\n    \"ArgumentTypeError\",\n    \"FileType\",\n    \"HelpFormatter\",\n    \"ArgumentDefaultsHelpFormatter\",\n    \"RawDescriptionHelpFormatter\",\n    \"RawTextHelpFormatter\",\n    \"MetavarTypeHelpFormatter\",\n    \"Namespace\",\n    \"Action\",\n    \"BooleanOptionalAction\",\n    \"ONE_OR_MORE\",\n    \"OPTIONAL\",\n    \"PARSER\",\n    \"REMAINDER\",\n    \"SUPPRESS\",\n    \"ZERO_OR_MORE\",\n]\n\n_T = TypeVar(\"_T\")\n_ActionT = TypeVar(\"_ActionT\", bound=Action)\n_ArgumentParserT = TypeVar(\"_ArgumentParserT\", bound=ArgumentParser)\n_N = TypeVar(\"_N\")\n_ActionType: TypeAlias = Callable[[str], Any] | FileType | str\n\nONE_OR_MORE: Final = \"+\"\nOPTIONAL: Final = \"?\"\nPARSER: Final = \"A...\"\nREMAINDER: Final = \"...\"\n_SUPPRESS_T = NewType(\"_SUPPRESS_T\", str)\nSUPPRESS: _SUPPRESS_T | str  # not using Literal because argparse sometimes compares SUPPRESS with is\n# the | str is there so that foo = argparse.SUPPRESS; foo = \"test\" checks out in mypy\nZERO_OR_MORE: Final = \"*\"\n_UNRECOGNIZED_ARGS_ATTR: Final = \"_unrecognized_args\"  # undocumented\n\nclass ArgumentError(Exception):\n    argument_name: str | None\n    message: str\n    def __init__(self, argument: Action | None, message: str) -> None: ...\n\n# undocumented\nclass _AttributeHolder:\n    def _get_kwargs(self) -> list[tuple[str, Any]]: ...\n    def _get_args(self) -> list[Any]: ...\n\n# undocumented\nclass _ActionsContainer:\n    description: str | None\n    prefix_chars: str\n    argument_default: Any\n    conflict_handler: str\n\n    _registries: dict[str, dict[Any, Any]]\n    _actions: list[Action]\n    _option_string_actions: dict[str, Action]\n    _action_groups: list[_ArgumentGroup]\n    _mutually_exclusive_groups: list[_MutuallyExclusiveGroup]\n    _defaults: dict[str, Any]\n    _negative_number_matcher: Pattern[str]\n    _has_negative_number_optionals: list[bool]\n    def __init__(self, description: str | None, prefix_chars: str, argument_default: Any, conflict_handler: str) -> None: ...\n    def register(self, registry_name: str, value: Any, object: Any) -> None: ...\n    def _registry_get(self, registry_name: str, value: Any, default: Any = None) -> Any: ...\n    def set_defaults(self, **kwargs: Any) -> None: ...\n    def get_default(self, dest: str) -> Any: ...\n    def add_argument(\n        self,\n        *name_or_flags: str,\n        # str covers predefined actions (\"store_true\", \"count\", etc.)\n        # and user registered actions via the `register` method.\n        action: str | type[Action] = ...,\n        # more precisely, Literal[\"?\", \"*\", \"+\", \"...\", \"A...\", \"==SUPPRESS==\"],\n        # but using this would make it hard to annotate callers that don't use a\n        # literal argument and for subclasses to override this method.\n        nargs: int | str | _SUPPRESS_T | None = None,\n        const: Any = ...,\n        default: Any = ...,\n        type: _ActionType = ...,\n        choices: Iterable[_T] | None = ...,\n        required: bool = ...,\n        help: str | None = ...,\n        metavar: str | tuple[str, ...] | None = ...,\n        dest: str | None = ...,\n        version: str = ...,\n        **kwargs: Any,\n    ) -> Action: ...\n    if sys.version_info >= (3, 14):\n        @overload\n        def add_argument_group(\n            self,\n            title: str | None = None,\n            description: str | None = None,\n            *,\n            # argument_default's type must be valid for the arguments in the group\n            argument_default: Any = ...,\n            conflict_handler: str = ...,\n        ) -> _ArgumentGroup: ...\n        @overload\n        @deprecated(\"The `prefix_chars` parameter deprecated since Python 3.14.\")\n        def add_argument_group(\n            self,\n            title: str | None = None,\n            description: str | None = None,\n            *,\n            prefix_chars: str,\n            argument_default: Any = ...,\n            conflict_handler: str = ...,\n        ) -> _ArgumentGroup: ...\n    else:\n        def add_argument_group(\n            self,\n            title: str | None = None,\n            description: str | None = None,\n            *,\n            prefix_chars: str = ...,\n            # argument_default's type must be valid for the arguments in the group\n            argument_default: Any = ...,\n            conflict_handler: str = ...,\n        ) -> _ArgumentGroup: ...\n\n    def add_mutually_exclusive_group(self, *, required: bool = False) -> _MutuallyExclusiveGroup: ...\n    def _add_action(self, action: _ActionT) -> _ActionT: ...\n    def _remove_action(self, action: Action) -> None: ...\n    def _add_container_actions(self, container: _ActionsContainer) -> None: ...\n    def _get_positional_kwargs(self, dest: str, **kwargs: Any) -> dict[str, Any]: ...\n    def _get_optional_kwargs(self, *args: Any, **kwargs: Any) -> dict[str, Any]: ...\n    def _pop_action_class(self, kwargs: Any, default: type[Action] | None = None) -> type[Action]: ...\n    def _get_handler(self) -> Callable[[Action, Iterable[tuple[str, Action]]], Any]: ...\n    def _check_conflict(self, action: Action) -> None: ...\n    def _handle_conflict_error(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> NoReturn: ...\n    def _handle_conflict_resolve(self, action: Action, conflicting_actions: Iterable[tuple[str, Action]]) -> None: ...\n\n@type_check_only\nclass _FormatterClass(Protocol):\n    def __call__(self, *, prog: str) -> HelpFormatter: ...\n\nclass ArgumentParser(_AttributeHolder, _ActionsContainer):\n    prog: str\n    usage: str | None\n    epilog: str | None\n    formatter_class: _FormatterClass\n    fromfile_prefix_chars: str | None\n    add_help: bool\n    allow_abbrev: bool\n    exit_on_error: bool\n\n    if sys.version_info >= (3, 14):\n        suggest_on_error: bool\n        color: bool\n\n    # undocumented\n    _positionals: _ArgumentGroup\n    _optionals: _ArgumentGroup\n    _subparsers: _ArgumentGroup | None\n\n    # Note: the constructor arguments are also used in _SubParsersAction.add_parser.\n    if sys.version_info >= (3, 14):\n        def __init__(\n            self,\n            prog: str | None = None,\n            usage: str | None = None,\n            description: str | None = None,\n            epilog: str | None = None,\n            parents: Sequence[ArgumentParser] = [],\n            formatter_class: _FormatterClass = ...,\n            prefix_chars: str = \"-\",\n            fromfile_prefix_chars: str | None = None,\n            argument_default: Any = None,\n            conflict_handler: str = \"error\",\n            add_help: bool = True,\n            allow_abbrev: bool = True,\n            exit_on_error: bool = True,\n            *,\n            suggest_on_error: bool = False,\n            color: bool = True,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            prog: str | None = None,\n            usage: str | None = None,\n            description: str | None = None,\n            epilog: str | None = None,\n            parents: Sequence[ArgumentParser] = [],\n            formatter_class: _FormatterClass = ...,\n            prefix_chars: str = \"-\",\n            fromfile_prefix_chars: str | None = None,\n            argument_default: Any = None,\n            conflict_handler: str = \"error\",\n            add_help: bool = True,\n            allow_abbrev: bool = True,\n            exit_on_error: bool = True,\n        ) -> None: ...\n\n    @overload\n    def parse_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ...\n    @overload\n    def parse_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ...\n    @overload\n    def parse_args(self, *, namespace: _N) -> _N: ...\n    @overload\n    def add_subparsers(\n        self: _ArgumentParserT,\n        *,\n        title: str = \"subcommands\",\n        description: str | None = None,\n        prog: str | None = None,\n        action: type[Action] = ...,\n        option_string: str = ...,\n        dest: str | None = None,\n        required: bool = False,\n        help: str | None = None,\n        metavar: str | None = None,\n    ) -> _SubParsersAction[_ArgumentParserT]: ...\n    @overload\n    def add_subparsers(\n        self,\n        *,\n        title: str = \"subcommands\",\n        description: str | None = None,\n        prog: str | None = None,\n        parser_class: type[_ArgumentParserT],\n        action: type[Action] = ...,\n        option_string: str = ...,\n        dest: str | None = None,\n        required: bool = False,\n        help: str | None = None,\n        metavar: str | None = None,\n    ) -> _SubParsersAction[_ArgumentParserT]: ...\n    def print_usage(self, file: SupportsWrite[str] | None = None) -> None: ...\n    def print_help(self, file: SupportsWrite[str] | None = None) -> None: ...\n    def format_usage(self) -> str: ...\n    def format_help(self) -> str: ...\n    @overload\n    def parse_known_args(self, args: Sequence[str] | None = None, namespace: None = None) -> tuple[Namespace, list[str]]: ...\n    @overload\n    def parse_known_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]: ...\n    @overload\n    def parse_known_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ...\n    def convert_arg_line_to_args(self, arg_line: str) -> list[str]: ...\n    def exit(self, status: int = 0, message: str | None = None) -> NoReturn: ...\n    def error(self, message: str) -> NoReturn: ...\n    @overload\n    def parse_intermixed_args(self, args: Sequence[str] | None = None, namespace: None = None) -> Namespace: ...\n    @overload\n    def parse_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> _N: ...\n    @overload\n    def parse_intermixed_args(self, *, namespace: _N) -> _N: ...\n    @overload\n    def parse_known_intermixed_args(\n        self, args: Sequence[str] | None = None, namespace: None = None\n    ) -> tuple[Namespace, list[str]]: ...\n    @overload\n    def parse_known_intermixed_args(self, args: Sequence[str] | None, namespace: _N) -> tuple[_N, list[str]]: ...\n    @overload\n    def parse_known_intermixed_args(self, *, namespace: _N) -> tuple[_N, list[str]]: ...\n    # undocumented\n    def _get_optional_actions(self) -> list[Action]: ...\n    def _get_positional_actions(self) -> list[Action]: ...\n    if sys.version_info >= (3, 12):\n        def _parse_known_args(\n            self, arg_strings: list[str], namespace: Namespace, intermixed: bool\n        ) -> tuple[Namespace, list[str]]: ...\n    else:\n        def _parse_known_args(self, arg_strings: list[str], namespace: Namespace) -> tuple[Namespace, list[str]]: ...\n\n    def _read_args_from_files(self, arg_strings: list[str]) -> list[str]: ...\n    def _match_argument(self, action: Action, arg_strings_pattern: str) -> int: ...\n    def _match_arguments_partial(self, actions: Sequence[Action], arg_strings_pattern: str) -> list[int]: ...\n    if sys.version_info >= (3, 12):\n        def _parse_optional(self, arg_string: str) -> list[tuple[Action | None, str, str | None, str | None]] | None: ...\n    else:\n        def _parse_optional(self, arg_string: str) -> tuple[Action | None, str, str | None] | None: ...\n\n    def _get_option_tuples(self, option_string: str) -> list[tuple[Action, str, str | None]]: ...\n    def _get_nargs_pattern(self, action: Action) -> str: ...\n    def _get_values(self, action: Action, arg_strings: list[str]) -> Any: ...\n    def _get_value(self, action: Action, arg_string: str) -> Any: ...\n    def _check_value(self, action: Action, value: Any) -> None: ...\n    def _get_formatter(self) -> HelpFormatter: ...\n    def _print_message(self, message: str, file: SupportsWrite[str] | None = None) -> None: ...\n\nclass HelpFormatter:\n    # undocumented\n    _prog: str\n    _indent_increment: int\n    _max_help_position: int\n    _width: int\n    _current_indent: int\n    _level: int\n    _action_max_length: int\n    _root_section: _Section\n    _current_section: _Section\n    _whitespace_matcher: Pattern[str]\n    _long_break_matcher: Pattern[str]\n\n    class _Section:\n        formatter: HelpFormatter\n        heading: str | None\n        parent: Self | None\n        items: list[tuple[Callable[..., str], Iterable[Any]]]\n        def __init__(self, formatter: HelpFormatter, parent: Self | None, heading: str | None = None) -> None: ...\n        def format_help(self) -> str: ...\n\n    if sys.version_info >= (3, 14):\n        def __init__(\n            self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None, color: bool = True\n        ) -> None: ...\n    else:\n        def __init__(\n            self, prog: str, indent_increment: int = 2, max_help_position: int = 24, width: int | None = None\n        ) -> None: ...\n\n    def _indent(self) -> None: ...\n    def _dedent(self) -> None: ...\n    def _add_item(self, func: Callable[..., str], args: Iterable[Any]) -> None: ...\n    def start_section(self, heading: str | None) -> None: ...\n    def end_section(self) -> None: ...\n    def add_text(self, text: str | None) -> None: ...\n    def add_usage(\n        self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None = None\n    ) -> None: ...\n    def add_argument(self, action: Action) -> None: ...\n    def add_arguments(self, actions: Iterable[Action]) -> None: ...\n    def format_help(self) -> str: ...\n    def _join_parts(self, part_strings: Iterable[str]) -> str: ...\n    def _format_usage(\n        self, usage: str | None, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup], prefix: str | None\n    ) -> str: ...\n    if sys.version_info < (3, 14):\n        # Removed in Python 3.14.3\n        def _format_actions_usage(self, actions: Iterable[Action], groups: Iterable[_MutuallyExclusiveGroup]) -> str: ...\n\n    def _format_text(self, text: str) -> str: ...\n    def _format_action(self, action: Action) -> str: ...\n    def _format_action_invocation(self, action: Action) -> str: ...\n    def _metavar_formatter(self, action: Action, default_metavar: str) -> Callable[[int], tuple[str, ...]]: ...\n    def _format_args(self, action: Action, default_metavar: str) -> str: ...\n    def _expand_help(self, action: Action) -> str: ...\n    def _iter_indented_subactions(self, action: Action) -> Generator[Action, None, None]: ...\n    def _split_lines(self, text: str, width: int) -> list[str]: ...\n    def _fill_text(self, text: str, width: int, indent: str) -> str: ...\n    def _get_help_string(self, action: Action) -> str | None: ...\n    def _get_default_metavar_for_optional(self, action: Action) -> str: ...\n    def _get_default_metavar_for_positional(self, action: Action) -> str: ...\n\nclass RawDescriptionHelpFormatter(HelpFormatter): ...\nclass RawTextHelpFormatter(RawDescriptionHelpFormatter): ...\nclass ArgumentDefaultsHelpFormatter(HelpFormatter): ...\nclass MetavarTypeHelpFormatter(HelpFormatter): ...\n\nclass Action(_AttributeHolder):\n    option_strings: Sequence[str]\n    dest: str\n    nargs: int | str | None\n    const: Any\n    default: Any\n    type: _ActionType | None\n    choices: Iterable[Any] | None\n    required: bool\n    help: str | None\n    metavar: str | tuple[str, ...] | None\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            nargs: int | str | None = None,\n            const: _T | None = None,\n            default: _T | str | None = None,\n            type: Callable[[str], _T] | FileType | None = None,\n            choices: Iterable[_T] | None = None,\n            required: bool = False,\n            help: str | None = None,\n            metavar: str | tuple[str, ...] | None = None,\n            deprecated: bool = False,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            nargs: int | str | None = None,\n            const: _T | None = None,\n            default: _T | str | None = None,\n            type: Callable[[str], _T] | FileType | None = None,\n            choices: Iterable[_T] | None = None,\n            required: bool = False,\n            help: str | None = None,\n            metavar: str | tuple[str, ...] | None = None,\n        ) -> None: ...\n\n    def __call__(\n        self, parser: ArgumentParser, namespace: Namespace, values: str | Sequence[Any] | None, option_string: str | None = None\n    ) -> None: ...\n    def format_usage(self) -> str: ...\n\nif sys.version_info >= (3, 12):\n    class BooleanOptionalAction(Action):\n        if sys.version_info >= (3, 14):\n            def __init__(\n                self,\n                option_strings: Sequence[str],\n                dest: str,\n                default: bool | None = None,\n                required: bool = False,\n                help: str | None = None,\n                deprecated: bool = False,\n            ) -> None: ...\n        elif sys.version_info >= (3, 13):\n            @overload\n            def __init__(\n                self,\n                option_strings: Sequence[str],\n                dest: str,\n                default: bool | None = None,\n                *,\n                required: bool = False,\n                help: str | None = None,\n                deprecated: bool = False,\n            ) -> None: ...\n            @overload\n            @deprecated(\"The `type`, `choices`, and `metavar` parameters are ignored and will be removed in Python 3.14.\")\n            def __init__(\n                self,\n                option_strings: Sequence[str],\n                dest: str,\n                default: _T | bool | None = None,\n                type: Callable[[str], _T] | FileType | None = sentinel,\n                choices: Iterable[_T] | None = sentinel,\n                required: bool = False,\n                help: str | None = None,\n                metavar: str | tuple[str, ...] | None = sentinel,\n                deprecated: bool = False,\n            ) -> None: ...\n        else:\n            @overload\n            def __init__(\n                self,\n                option_strings: Sequence[str],\n                dest: str,\n                default: bool | None = None,\n                *,\n                required: bool = False,\n                help: str | None = None,\n            ) -> None: ...\n            @overload\n            @deprecated(\"The `type`, `choices`, and `metavar` parameters are ignored and will be removed in Python 3.14.\")\n            def __init__(\n                self,\n                option_strings: Sequence[str],\n                dest: str,\n                default: _T | bool | None = None,\n                type: Callable[[str], _T] | FileType | None = sentinel,\n                choices: Iterable[_T] | None = sentinel,\n                required: bool = False,\n                help: str | None = None,\n                metavar: str | tuple[str, ...] | None = sentinel,\n            ) -> None: ...\n\nelse:\n    class BooleanOptionalAction(Action):\n        @overload\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            default: bool | None = None,\n            *,\n            required: bool = False,\n            help: str | None = None,\n        ) -> None: ...\n        @overload\n        @deprecated(\"The `type`, `choices`, and `metavar` parameters are ignored and will be removed in Python 3.14.\")\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            default: _T | bool | None = None,\n            type: Callable[[str], _T] | FileType | None = None,\n            choices: Iterable[_T] | None = None,\n            required: bool = False,\n            help: str | None = None,\n            metavar: str | tuple[str, ...] | None = None,\n        ) -> None: ...\n\nclass Namespace(_AttributeHolder):\n    def __init__(self, **kwargs: Any) -> None: ...\n    def __getattr__(self, name: str) -> Any: ...\n    def __setattr__(self, name: str, value: Any, /) -> None: ...\n    def __contains__(self, key: str) -> bool: ...\n    def __eq__(self, other: object) -> bool: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\nif sys.version_info >= (3, 14):\n    @deprecated(\"Deprecated since Python 3.14. Open files after parsing arguments instead.\")\n    class FileType:\n        # undocumented\n        _mode: str\n        _bufsize: int\n        _encoding: str | None\n        _errors: str | None\n        def __init__(\n            self, mode: str = \"r\", bufsize: int = -1, encoding: str | None = None, errors: str | None = None\n        ) -> None: ...\n        def __call__(self, string: str) -> IO[Any]: ...\n\nelse:\n    class FileType:\n        # undocumented\n        _mode: str\n        _bufsize: int\n        _encoding: str | None\n        _errors: str | None\n        def __init__(\n            self, mode: str = \"r\", bufsize: int = -1, encoding: str | None = None, errors: str | None = None\n        ) -> None: ...\n        def __call__(self, string: str) -> IO[Any]: ...\n\n# undocumented\nclass _ArgumentGroup(_ActionsContainer):\n    title: str | None\n    _group_actions: list[Action]\n    if sys.version_info >= (3, 14):\n        @overload\n        def __init__(\n            self,\n            container: _ActionsContainer,\n            title: str | None = None,\n            description: str | None = None,\n            *,\n            argument_default: Any = ...,\n            conflict_handler: str = ...,\n        ) -> None: ...\n        @overload\n        @deprecated(\"Undocumented `prefix_chars` parameter is deprecated since Python 3.14.\")\n        def __init__(\n            self,\n            container: _ActionsContainer,\n            title: str | None = None,\n            description: str | None = None,\n            *,\n            prefix_chars: str,\n            argument_default: Any = ...,\n            conflict_handler: str = ...,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            container: _ActionsContainer,\n            title: str | None = None,\n            description: str | None = None,\n            *,\n            prefix_chars: str = ...,\n            argument_default: Any = ...,\n            conflict_handler: str = ...,\n        ) -> None: ...\n\n# undocumented\nclass _MutuallyExclusiveGroup(_ArgumentGroup):\n    required: bool\n    _container: _ActionsContainer\n    def __init__(self, container: _ActionsContainer, required: bool = False) -> None: ...\n\n# undocumented\nclass _StoreAction(Action): ...\n\n# undocumented\nclass _StoreConstAction(Action):\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            const: Any | None = None,\n            default: Any = None,\n            required: bool = False,\n            help: str | None = None,\n            metavar: str | tuple[str, ...] | None = None,\n            deprecated: bool = False,\n        ) -> None: ...\n    elif sys.version_info >= (3, 11):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            const: Any | None = None,\n            default: Any = None,\n            required: bool = False,\n            help: str | None = None,\n            metavar: str | tuple[str, ...] | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            const: Any,\n            default: Any = None,\n            required: bool = False,\n            help: str | None = None,\n            metavar: str | tuple[str, ...] | None = None,\n        ) -> None: ...\n\n# undocumented\nclass _StoreTrueAction(_StoreConstAction):\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            default: bool = False,\n            required: bool = False,\n            help: str | None = None,\n            deprecated: bool = False,\n        ) -> None: ...\n    else:\n        def __init__(\n            self, option_strings: Sequence[str], dest: str, default: bool = False, required: bool = False, help: str | None = None\n        ) -> None: ...\n\n# undocumented\nclass _StoreFalseAction(_StoreConstAction):\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            default: bool = True,\n            required: bool = False,\n            help: str | None = None,\n            deprecated: bool = False,\n        ) -> None: ...\n    else:\n        def __init__(\n            self, option_strings: Sequence[str], dest: str, default: bool = True, required: bool = False, help: str | None = None\n        ) -> None: ...\n\n# undocumented\nclass _AppendAction(Action): ...\n\n# undocumented\nclass _ExtendAction(_AppendAction): ...\n\n# undocumented\nclass _AppendConstAction(Action):\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            const: Any | None = None,\n            default: Any = None,\n            required: bool = False,\n            help: str | None = None,\n            metavar: str | tuple[str, ...] | None = None,\n            deprecated: bool = False,\n        ) -> None: ...\n    elif sys.version_info >= (3, 11):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            const: Any | None = None,\n            default: Any = None,\n            required: bool = False,\n            help: str | None = None,\n            metavar: str | tuple[str, ...] | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            const: Any,\n            default: Any = None,\n            required: bool = False,\n            help: str | None = None,\n            metavar: str | tuple[str, ...] | None = None,\n        ) -> None: ...\n\n# undocumented\nclass _CountAction(Action):\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str,\n            default: Any = None,\n            required: bool = False,\n            help: str | None = None,\n            deprecated: bool = False,\n        ) -> None: ...\n    else:\n        def __init__(\n            self, option_strings: Sequence[str], dest: str, default: Any = None, required: bool = False, help: str | None = None\n        ) -> None: ...\n\n# undocumented\nclass _HelpAction(Action):\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str = \"==SUPPRESS==\",\n            default: str = \"==SUPPRESS==\",\n            help: str | None = None,\n            deprecated: bool = False,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            dest: str = \"==SUPPRESS==\",\n            default: str = \"==SUPPRESS==\",\n            help: str | None = None,\n        ) -> None: ...\n\n# undocumented\nclass _VersionAction(Action):\n    version: str | None\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            version: str | None = None,\n            dest: str = \"==SUPPRESS==\",\n            default: str = \"==SUPPRESS==\",\n            help: str | None = None,\n            deprecated: bool = False,\n        ) -> None: ...\n    elif sys.version_info >= (3, 11):\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            version: str | None = None,\n            dest: str = \"==SUPPRESS==\",\n            default: str = \"==SUPPRESS==\",\n            help: str | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            option_strings: Sequence[str],\n            version: str | None = None,\n            dest: str = \"==SUPPRESS==\",\n            default: str = \"==SUPPRESS==\",\n            help: str = \"show program's version number and exit\",\n        ) -> None: ...\n\n# undocumented\nclass _SubParsersAction(Action, Generic[_ArgumentParserT]):\n    _ChoicesPseudoAction: type[Any]  # nested class\n    _prog_prefix: str\n    _parser_class: type[_ArgumentParserT]\n    _name_parser_map: dict[str, _ArgumentParserT]\n    choices: dict[str, _ArgumentParserT]\n    _choices_actions: list[Action]\n    def __init__(\n        self,\n        option_strings: Sequence[str],\n        prog: str,\n        parser_class: type[_ArgumentParserT],\n        dest: str = \"==SUPPRESS==\",\n        required: bool = False,\n        help: str | None = None,\n        metavar: str | tuple[str, ...] | None = None,\n    ) -> None: ...\n\n    # Note: `add_parser` accepts all kwargs of `ArgumentParser.__init__`. It also\n    # accepts its own `help` and `aliases` kwargs.\n    if sys.version_info >= (3, 14):\n        def add_parser(\n            self,\n            name: str,\n            *,\n            deprecated: bool = False,\n            help: str | None = ...,\n            aliases: Sequence[str] = ...,\n            # Kwargs from ArgumentParser constructor\n            prog: str | None = ...,\n            usage: str | None = ...,\n            description: str | None = ...,\n            epilog: str | None = ...,\n            parents: Sequence[_ArgumentParserT] = ...,\n            formatter_class: _FormatterClass = ...,\n            prefix_chars: str = ...,\n            fromfile_prefix_chars: str | None = ...,\n            argument_default: Any = ...,\n            conflict_handler: str = ...,\n            add_help: bool = True,\n            allow_abbrev: bool = True,\n            exit_on_error: bool = True,\n            suggest_on_error: bool = False,\n            color: bool = False,\n            **kwargs: Any,  # Accepting any additional kwargs for custom parser classes\n        ) -> _ArgumentParserT: ...\n    elif sys.version_info >= (3, 13):\n        def add_parser(\n            self,\n            name: str,\n            *,\n            deprecated: bool = False,\n            help: str | None = ...,\n            aliases: Sequence[str] = ...,\n            # Kwargs from ArgumentParser constructor\n            prog: str | None = ...,\n            usage: str | None = ...,\n            description: str | None = ...,\n            epilog: str | None = ...,\n            parents: Sequence[_ArgumentParserT] = ...,\n            formatter_class: _FormatterClass = ...,\n            prefix_chars: str = ...,\n            fromfile_prefix_chars: str | None = ...,\n            argument_default: Any = ...,\n            conflict_handler: str = ...,\n            add_help: bool = True,\n            allow_abbrev: bool = True,\n            exit_on_error: bool = True,\n            **kwargs: Any,  # Accepting any additional kwargs for custom parser classes\n        ) -> _ArgumentParserT: ...\n    else:\n        def add_parser(\n            self,\n            name: str,\n            *,\n            help: str | None = ...,\n            aliases: Sequence[str] = ...,\n            # Kwargs from ArgumentParser constructor\n            prog: str | None = ...,\n            usage: str | None = ...,\n            description: str | None = ...,\n            epilog: str | None = ...,\n            parents: Sequence[_ArgumentParserT] = ...,\n            formatter_class: _FormatterClass = ...,\n            prefix_chars: str = ...,\n            fromfile_prefix_chars: str | None = ...,\n            argument_default: Any = ...,\n            conflict_handler: str = ...,\n            add_help: bool = True,\n            allow_abbrev: bool = True,\n            exit_on_error: bool = True,\n            **kwargs: Any,  # Accepting any additional kwargs for custom parser classes\n        ) -> _ArgumentParserT: ...\n\n    def _get_subactions(self) -> list[Action]: ...\n\n# undocumented\nclass ArgumentTypeError(Exception): ...\n\n# undocumented\ndef _get_action_name(argument: Action | None) -> str | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/array.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer, SupportsRead, SupportsWrite\nfrom collections.abc import Iterable, MutableSequence\nfrom types import GenericAlias\nfrom typing import Any, ClassVar, Literal, SupportsIndex, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias, deprecated, disjoint_base\n\n_IntTypeCode: TypeAlias = Literal[\"b\", \"B\", \"h\", \"H\", \"i\", \"I\", \"l\", \"L\", \"q\", \"Q\"]\n_FloatTypeCode: TypeAlias = Literal[\"f\", \"d\"]\nif sys.version_info >= (3, 13):\n    _UnicodeTypeCode: TypeAlias = Literal[\"u\", \"w\"]\nelse:\n    _UnicodeTypeCode: TypeAlias = Literal[\"u\"]\n_TypeCode: TypeAlias = _IntTypeCode | _FloatTypeCode | _UnicodeTypeCode\n\n_T = TypeVar(\"_T\", int, float, str)\n\ntypecodes: str\n\n@disjoint_base\nclass array(MutableSequence[_T]):\n    @property\n    def typecode(self) -> _TypeCode: ...\n    @property\n    def itemsize(self) -> int: ...\n    @overload\n    def __new__(\n        cls: type[array[int]], typecode: _IntTypeCode, initializer: bytes | bytearray | Iterable[int] = ..., /\n    ) -> array[int]: ...\n    @overload\n    def __new__(\n        cls: type[array[float]], typecode: _FloatTypeCode, initializer: bytes | bytearray | Iterable[float] = ..., /\n    ) -> array[float]: ...\n    if sys.version_info >= (3, 13):\n        @overload\n        def __new__(\n            cls: type[array[str]], typecode: Literal[\"w\"], initializer: bytes | bytearray | Iterable[str] = ..., /\n        ) -> array[str]: ...\n        @overload\n        @deprecated(\"Deprecated since Python 3.3; will be removed in Python 3.16. Use 'w' typecode instead.\")\n        def __new__(\n            cls: type[array[str]], typecode: Literal[\"u\"], initializer: bytes | bytearray | Iterable[str] = ..., /\n        ) -> array[str]: ...\n    else:\n        @overload\n        @deprecated(\"Deprecated since Python 3.3; will be removed in Python 3.16.\")\n        def __new__(\n            cls: type[array[str]], typecode: Literal[\"u\"], initializer: bytes | bytearray | Iterable[str] = ..., /\n        ) -> array[str]: ...\n\n    @overload\n    def __new__(cls, typecode: str, initializer: Iterable[_T], /) -> Self: ...\n    @overload\n    def __new__(cls, typecode: str, initializer: bytes | bytearray = ..., /) -> Self: ...\n    def append(self, v: _T, /) -> None: ...\n    def buffer_info(self) -> tuple[int, int]: ...\n    def byteswap(self) -> None: ...\n    def count(self, v: _T, /) -> int: ...\n    def extend(self, bb: Iterable[_T], /) -> None: ...\n    def frombytes(self, buffer: ReadableBuffer, /) -> None: ...\n    def fromfile(self, f: SupportsRead[bytes], n: int, /) -> None: ...\n    def fromlist(self, list: list[_T], /) -> None: ...\n    def fromunicode(self, ustr: str, /) -> None: ...\n    if sys.version_info >= (3, 10):\n        def index(self, v: _T, start: int = 0, stop: int = sys.maxsize, /) -> int: ...\n    else:\n        def index(self, v: _T, /) -> int: ...  # type: ignore[override]\n\n    def insert(self, i: int, v: _T, /) -> None: ...\n    def pop(self, i: int = -1, /) -> _T: ...\n    def remove(self, v: _T, /) -> None: ...\n    def tobytes(self) -> bytes: ...\n    def tofile(self, f: SupportsWrite[bytes], /) -> None: ...\n    def tolist(self) -> list[_T]: ...\n    def tounicode(self) -> str: ...\n\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __contains__(self, value: object, /) -> bool: ...\n    def __len__(self) -> int: ...\n    @overload\n    def __getitem__(self, key: SupportsIndex, /) -> _T: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> array[_T]: ...\n    @overload  # type: ignore[override]\n    def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice[SupportsIndex | None], value: array[_T], /) -> None: ...\n    def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ...\n    def __add__(self, value: array[_T], /) -> array[_T]: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __ge__(self, value: array[_T], /) -> bool: ...\n    def __gt__(self, value: array[_T], /) -> bool: ...\n    def __iadd__(self, value: array[_T], /) -> Self: ...  # type: ignore[override]\n    def __imul__(self, value: int, /) -> Self: ...\n    def __le__(self, value: array[_T], /) -> bool: ...\n    def __lt__(self, value: array[_T], /) -> bool: ...\n    def __mul__(self, value: int, /) -> array[_T]: ...\n    def __rmul__(self, value: int, /) -> array[_T]: ...\n    def __copy__(self) -> array[_T]: ...\n    def __deepcopy__(self, unused: Any, /) -> array[_T]: ...\n    def __buffer__(self, flags: int, /) -> memoryview: ...\n    def __release_buffer__(self, buffer: memoryview, /) -> None: ...\n    if sys.version_info >= (3, 12):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nArrayType = array\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ast.pyi",
    "content": "import ast\nimport builtins\nimport os\nimport sys\nimport typing_extensions\nfrom _ast import (\n    PyCF_ALLOW_TOP_LEVEL_AWAIT as PyCF_ALLOW_TOP_LEVEL_AWAIT,\n    PyCF_ONLY_AST as PyCF_ONLY_AST,\n    PyCF_TYPE_COMMENTS as PyCF_TYPE_COMMENTS,\n)\nfrom _typeshed import ReadableBuffer, Unused\nfrom collections.abc import Iterable, Iterator, Sequence\nfrom typing import Any, ClassVar, Generic, Literal, TypedDict, TypeVar as _TypeVar, overload, type_check_only\nfrom typing_extensions import Self, Unpack, deprecated, disjoint_base\n\nif sys.version_info >= (3, 13):\n    from _ast import PyCF_OPTIMIZED_AST as PyCF_OPTIMIZED_AST\n\n# Used for node end positions in constructor keyword arguments\n_EndPositionT = typing_extensions.TypeVar(\"_EndPositionT\", int, int | None, default=int | None)\n\n# Corresponds to the names in the `_attributes` class variable which is non-empty in certain AST nodes\n@type_check_only\nclass _Attributes(TypedDict, Generic[_EndPositionT], total=False):\n    lineno: int\n    col_offset: int\n    end_lineno: _EndPositionT\n    end_col_offset: _EndPositionT\n\n# The various AST classes are implemented in C, and imported from _ast at runtime,\n# but they consider themselves to live in the ast module,\n# so we'll define the stubs in this file.\nif sys.version_info >= (3, 12):\n    @disjoint_base\n    class AST:\n        __match_args__ = ()\n        _attributes: ClassVar[tuple[str, ...]]\n        _fields: ClassVar[tuple[str, ...]]\n        if sys.version_info >= (3, 13):\n            _field_types: ClassVar[dict[str, Any]]\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self) -> Self: ...\n\nelse:\n    class AST:\n        if sys.version_info >= (3, 10):\n            __match_args__ = ()\n        _attributes: ClassVar[tuple[str, ...]]\n        _fields: ClassVar[tuple[str, ...]]\n\nclass mod(AST): ...\n\nclass Module(mod):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"body\", \"type_ignores\")\n    body: list[stmt]\n    type_ignores: list[TypeIgnore]\n    if sys.version_info >= (3, 13):\n        def __init__(self, body: list[stmt] = ..., type_ignores: list[TypeIgnore] = ...) -> None: ...\n    else:\n        def __init__(self, body: list[stmt], type_ignores: list[TypeIgnore]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, body: list[stmt] = ..., type_ignores: list[TypeIgnore] = ...) -> Self: ...\n\nclass Interactive(mod):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"body\",)\n    body: list[stmt]\n    if sys.version_info >= (3, 13):\n        def __init__(self, body: list[stmt] = ...) -> None: ...\n    else:\n        def __init__(self, body: list[stmt]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, body: list[stmt] = ...) -> Self: ...\n\nclass Expression(mod):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"body\",)\n    body: expr\n    def __init__(self, body: expr) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, body: expr = ...) -> Self: ...\n\nclass FunctionType(mod):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"argtypes\", \"returns\")\n    argtypes: list[expr]\n    returns: expr\n    if sys.version_info >= (3, 13):\n        @overload\n        def __init__(self, argtypes: list[expr], returns: expr) -> None: ...\n        @overload\n        def __init__(self, argtypes: list[expr] = ..., *, returns: expr) -> None: ...\n    else:\n        def __init__(self, argtypes: list[expr], returns: expr) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, argtypes: list[expr] = ..., returns: expr = ...) -> Self: ...\n\nclass stmt(AST):\n    lineno: int\n    col_offset: int\n    end_lineno: int | None\n    end_col_offset: int | None\n    def __init__(self, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass FunctionDef(stmt):\n    if sys.version_info >= (3, 12):\n        __match_args__ = (\"name\", \"args\", \"body\", \"decorator_list\", \"returns\", \"type_comment\", \"type_params\")\n    elif sys.version_info >= (3, 10):\n        __match_args__ = (\"name\", \"args\", \"body\", \"decorator_list\", \"returns\", \"type_comment\")\n    name: str\n    args: arguments\n    body: list[stmt]\n    decorator_list: list[expr]\n    returns: expr | None\n    type_comment: str | None\n    if sys.version_info >= (3, 12):\n        type_params: list[type_param]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            name: str,\n            args: arguments,\n            body: list[stmt] = ...,\n            decorator_list: list[expr] = ...,\n            returns: expr | None = None,\n            type_comment: str | None = None,\n            type_params: list[type_param] = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    elif sys.version_info >= (3, 12):\n        @overload\n        def __init__(\n            self,\n            name: str,\n            args: arguments,\n            body: list[stmt],\n            decorator_list: list[expr],\n            returns: expr | None,\n            type_comment: str | None,\n            type_params: list[type_param],\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            name: str,\n            args: arguments,\n            body: list[stmt],\n            decorator_list: list[expr],\n            returns: expr | None = None,\n            type_comment: str | None = None,\n            *,\n            type_params: list[type_param],\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            name: str,\n            args: arguments,\n            body: list[stmt],\n            decorator_list: list[expr],\n            returns: expr | None = None,\n            type_comment: str | None = None,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            name: str = ...,\n            args: arguments = ...,\n            body: list[stmt] = ...,\n            decorator_list: list[expr] = ...,\n            returns: expr | None = ...,\n            type_comment: str | None = ...,\n            type_params: list[type_param] = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nclass AsyncFunctionDef(stmt):\n    if sys.version_info >= (3, 12):\n        __match_args__ = (\"name\", \"args\", \"body\", \"decorator_list\", \"returns\", \"type_comment\", \"type_params\")\n    elif sys.version_info >= (3, 10):\n        __match_args__ = (\"name\", \"args\", \"body\", \"decorator_list\", \"returns\", \"type_comment\")\n    name: str\n    args: arguments\n    body: list[stmt]\n    decorator_list: list[expr]\n    returns: expr | None\n    type_comment: str | None\n    if sys.version_info >= (3, 12):\n        type_params: list[type_param]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            name: str,\n            args: arguments,\n            body: list[stmt] = ...,\n            decorator_list: list[expr] = ...,\n            returns: expr | None = None,\n            type_comment: str | None = None,\n            type_params: list[type_param] = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    elif sys.version_info >= (3, 12):\n        @overload\n        def __init__(\n            self,\n            name: str,\n            args: arguments,\n            body: list[stmt],\n            decorator_list: list[expr],\n            returns: expr | None,\n            type_comment: str | None,\n            type_params: list[type_param],\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            name: str,\n            args: arguments,\n            body: list[stmt],\n            decorator_list: list[expr],\n            returns: expr | None = None,\n            type_comment: str | None = None,\n            *,\n            type_params: list[type_param],\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            name: str,\n            args: arguments,\n            body: list[stmt],\n            decorator_list: list[expr],\n            returns: expr | None = None,\n            type_comment: str | None = None,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            name: str = ...,\n            args: arguments = ...,\n            body: list[stmt] = ...,\n            decorator_list: list[expr] = ...,\n            returns: expr | None = ...,\n            type_comment: str | None = ...,\n            type_params: list[type_param] = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nclass ClassDef(stmt):\n    if sys.version_info >= (3, 12):\n        __match_args__ = (\"name\", \"bases\", \"keywords\", \"body\", \"decorator_list\", \"type_params\")\n    elif sys.version_info >= (3, 10):\n        __match_args__ = (\"name\", \"bases\", \"keywords\", \"body\", \"decorator_list\")\n    name: str\n    bases: list[expr]\n    keywords: list[keyword]\n    body: list[stmt]\n    decorator_list: list[expr]\n    if sys.version_info >= (3, 12):\n        type_params: list[type_param]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            name: str,\n            bases: list[expr] = ...,\n            keywords: list[keyword] = ...,\n            body: list[stmt] = ...,\n            decorator_list: list[expr] = ...,\n            type_params: list[type_param] = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    elif sys.version_info >= (3, 12):\n        def __init__(\n            self,\n            name: str,\n            bases: list[expr],\n            keywords: list[keyword],\n            body: list[stmt],\n            decorator_list: list[expr],\n            type_params: list[type_param],\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            name: str,\n            bases: list[expr],\n            keywords: list[keyword],\n            body: list[stmt],\n            decorator_list: list[expr],\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            name: str = ...,\n            bases: list[expr] = ...,\n            keywords: list[keyword] = ...,\n            body: list[stmt] = ...,\n            decorator_list: list[expr] = ...,\n            type_params: list[type_param] = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nclass Return(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\",)\n    value: expr | None\n    def __init__(self, value: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, value: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Delete(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"targets\",)\n    targets: list[expr]\n    if sys.version_info >= (3, 13):\n        def __init__(self, targets: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, targets: list[expr], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, targets: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Assign(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"targets\", \"value\", \"type_comment\")\n    targets: list[expr]\n    value: expr\n    type_comment: str | None\n    if sys.version_info >= (3, 13):\n        @overload\n        def __init__(\n            self, targets: list[expr], value: expr, type_comment: str | None = None, **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n        @overload\n        def __init__(\n            self, targets: list[expr] = ..., *, value: expr, type_comment: str | None = None, **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n    else:\n        def __init__(\n            self, targets: list[expr], value: expr, type_comment: str | None = None, **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, targets: list[expr] = ..., value: expr = ..., type_comment: str | None = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nif sys.version_info >= (3, 12):\n    class TypeAlias(stmt):\n        __match_args__ = (\"name\", \"type_params\", \"value\")\n        name: Name\n        type_params: list[type_param]\n        value: expr\n        if sys.version_info >= (3, 13):\n            @overload\n            def __init__(\n                self, name: Name, type_params: list[type_param], value: expr, **kwargs: Unpack[_Attributes[int]]\n            ) -> None: ...\n            @overload\n            def __init__(\n                self, name: Name, type_params: list[type_param] = ..., *, value: expr, **kwargs: Unpack[_Attributes[int]]\n            ) -> None: ...\n        else:\n            def __init__(\n                self, name: Name, type_params: list[type_param], value: expr, **kwargs: Unpack[_Attributes[int]]\n            ) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(  # type: ignore[override]\n                self,\n                *,\n                name: Name = ...,\n                type_params: list[type_param] = ...,\n                value: expr = ...,\n                **kwargs: Unpack[_Attributes[int]],\n            ) -> Self: ...\n\nclass AugAssign(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"target\", \"op\", \"value\")\n    target: Name | Attribute | Subscript\n    op: operator\n    value: expr\n    def __init__(\n        self, target: Name | Attribute | Subscript, op: operator, value: expr, **kwargs: Unpack[_Attributes]\n    ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            target: Name | Attribute | Subscript = ...,\n            op: operator = ...,\n            value: expr = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nclass AnnAssign(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"target\", \"annotation\", \"value\", \"simple\")\n    target: Name | Attribute | Subscript\n    annotation: expr\n    value: expr | None\n    simple: int\n    @overload\n    def __init__(\n        self,\n        target: Name | Attribute | Subscript,\n        annotation: expr,\n        value: expr | None,\n        simple: int,\n        **kwargs: Unpack[_Attributes],\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        target: Name | Attribute | Subscript,\n        annotation: expr,\n        value: expr | None = None,\n        *,\n        simple: int,\n        **kwargs: Unpack[_Attributes],\n    ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            target: Name | Attribute | Subscript = ...,\n            annotation: expr = ...,\n            value: expr | None = ...,\n            simple: int = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nclass For(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"target\", \"iter\", \"body\", \"orelse\", \"type_comment\")\n    target: expr\n    iter: expr\n    body: list[stmt]\n    orelse: list[stmt]\n    type_comment: str | None\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            target: expr,\n            iter: expr,\n            body: list[stmt] = ...,\n            orelse: list[stmt] = ...,\n            type_comment: str | None = None,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            target: expr,\n            iter: expr,\n            body: list[stmt],\n            orelse: list[stmt],\n            type_comment: str | None = None,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            target: expr = ...,\n            iter: expr = ...,\n            body: list[stmt] = ...,\n            orelse: list[stmt] = ...,\n            type_comment: str | None = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nclass AsyncFor(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"target\", \"iter\", \"body\", \"orelse\", \"type_comment\")\n    target: expr\n    iter: expr\n    body: list[stmt]\n    orelse: list[stmt]\n    type_comment: str | None\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            target: expr,\n            iter: expr,\n            body: list[stmt] = ...,\n            orelse: list[stmt] = ...,\n            type_comment: str | None = None,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            target: expr,\n            iter: expr,\n            body: list[stmt],\n            orelse: list[stmt],\n            type_comment: str | None = None,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            target: expr = ...,\n            iter: expr = ...,\n            body: list[stmt] = ...,\n            orelse: list[stmt] = ...,\n            type_comment: str | None = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nclass While(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"test\", \"body\", \"orelse\")\n    test: expr\n    body: list[stmt]\n    orelse: list[stmt]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self, test: expr, body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n    else:\n        def __init__(self, test: expr, body: list[stmt], orelse: list[stmt], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, test: expr = ..., body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass If(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"test\", \"body\", \"orelse\")\n    test: expr\n    body: list[stmt]\n    orelse: list[stmt]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self, test: expr, body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n    else:\n        def __init__(self, test: expr, body: list[stmt], orelse: list[stmt], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, test: expr = ..., body: list[stmt] = ..., orelse: list[stmt] = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass With(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"items\", \"body\", \"type_comment\")\n    items: list[withitem]\n    body: list[stmt]\n    type_comment: str | None\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            items: list[withitem] = ...,\n            body: list[stmt] = ...,\n            type_comment: str | None = None,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    else:\n        def __init__(\n            self, items: list[withitem], body: list[stmt], type_comment: str | None = None, **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            items: list[withitem] = ...,\n            body: list[stmt] = ...,\n            type_comment: str | None = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nclass AsyncWith(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"items\", \"body\", \"type_comment\")\n    items: list[withitem]\n    body: list[stmt]\n    type_comment: str | None\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            items: list[withitem] = ...,\n            body: list[stmt] = ...,\n            type_comment: str | None = None,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    else:\n        def __init__(\n            self, items: list[withitem], body: list[stmt], type_comment: str | None = None, **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            items: list[withitem] = ...,\n            body: list[stmt] = ...,\n            type_comment: str | None = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nclass Raise(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"exc\", \"cause\")\n    exc: expr | None\n    cause: expr | None\n    def __init__(self, exc: expr | None = None, cause: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, exc: expr | None = ..., cause: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Try(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"body\", \"handlers\", \"orelse\", \"finalbody\")\n    body: list[stmt]\n    handlers: list[ExceptHandler]\n    orelse: list[stmt]\n    finalbody: list[stmt]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            body: list[stmt] = ...,\n            handlers: list[ExceptHandler] = ...,\n            orelse: list[stmt] = ...,\n            finalbody: list[stmt] = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            body: list[stmt],\n            handlers: list[ExceptHandler],\n            orelse: list[stmt],\n            finalbody: list[stmt],\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            body: list[stmt] = ...,\n            handlers: list[ExceptHandler] = ...,\n            orelse: list[stmt] = ...,\n            finalbody: list[stmt] = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nif sys.version_info >= (3, 11):\n    class TryStar(stmt):\n        __match_args__ = (\"body\", \"handlers\", \"orelse\", \"finalbody\")\n        body: list[stmt]\n        handlers: list[ExceptHandler]\n        orelse: list[stmt]\n        finalbody: list[stmt]\n        if sys.version_info >= (3, 13):\n            def __init__(\n                self,\n                body: list[stmt] = ...,\n                handlers: list[ExceptHandler] = ...,\n                orelse: list[stmt] = ...,\n                finalbody: list[stmt] = ...,\n                **kwargs: Unpack[_Attributes],\n            ) -> None: ...\n        else:\n            def __init__(\n                self,\n                body: list[stmt],\n                handlers: list[ExceptHandler],\n                orelse: list[stmt],\n                finalbody: list[stmt],\n                **kwargs: Unpack[_Attributes],\n            ) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self,\n                *,\n                body: list[stmt] = ...,\n                handlers: list[ExceptHandler] = ...,\n                orelse: list[stmt] = ...,\n                finalbody: list[stmt] = ...,\n                **kwargs: Unpack[_Attributes],\n            ) -> Self: ...\n\nclass Assert(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"test\", \"msg\")\n    test: expr\n    msg: expr | None\n    def __init__(self, test: expr, msg: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, test: expr = ..., msg: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Import(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"names\",)\n    names: list[alias]\n    if sys.version_info >= (3, 13):\n        def __init__(self, names: list[alias] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, names: list[alias], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, names: list[alias] = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass ImportFrom(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"module\", \"names\", \"level\")\n    module: str | None\n    names: list[alias]\n    level: int\n    if sys.version_info >= (3, 13):\n        @overload\n        def __init__(self, module: str | None, names: list[alias], level: int, **kwargs: Unpack[_Attributes]) -> None: ...\n        @overload\n        def __init__(\n            self, module: str | None = None, names: list[alias] = ..., *, level: int, **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(self, module: str | None, names: list[alias], level: int, **kwargs: Unpack[_Attributes]) -> None: ...\n        @overload\n        def __init__(\n            self, module: str | None = None, *, names: list[alias], level: int, **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, module: str | None = ..., names: list[alias] = ..., level: int = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass Global(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"names\",)\n    names: list[str]\n    if sys.version_info >= (3, 13):\n        def __init__(self, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, names: list[str], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Nonlocal(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"names\",)\n    names: list[str]\n    if sys.version_info >= (3, 13):\n        def __init__(self, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, names: list[str], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, names: list[str] = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Expr(stmt):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\",)\n    value: expr\n    def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Pass(stmt): ...\nclass Break(stmt): ...\nclass Continue(stmt): ...\n\nclass expr(AST):\n    lineno: int\n    col_offset: int\n    end_lineno: int | None\n    end_col_offset: int | None\n    def __init__(self, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass BoolOp(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"op\", \"values\")\n    op: boolop\n    values: list[expr]\n    if sys.version_info >= (3, 13):\n        def __init__(self, op: boolop, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, op: boolop, values: list[expr], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, op: boolop = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass NamedExpr(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"target\", \"value\")\n    target: Name\n    value: expr\n    def __init__(self, target: Name, value: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, target: Name = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass BinOp(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"left\", \"op\", \"right\")\n    left: expr\n    op: operator\n    right: expr\n    def __init__(self, left: expr, op: operator, right: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, left: expr = ..., op: operator = ..., right: expr = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass UnaryOp(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"op\", \"operand\")\n    op: unaryop\n    operand: expr\n    def __init__(self, op: unaryop, operand: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, op: unaryop = ..., operand: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Lambda(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"args\", \"body\")\n    args: arguments\n    body: expr\n    def __init__(self, args: arguments, body: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, args: arguments = ..., body: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass IfExp(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"test\", \"body\", \"orelse\")\n    test: expr\n    body: expr\n    orelse: expr\n    def __init__(self, test: expr, body: expr, orelse: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, test: expr = ..., body: expr = ..., orelse: expr = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass Dict(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"keys\", \"values\")\n    keys: list[expr | None]\n    values: list[expr]\n    if sys.version_info >= (3, 13):\n        def __init__(self, keys: list[expr | None] = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, keys: list[expr | None], values: list[expr], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, keys: list[expr | None] = ..., values: list[expr] = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass Set(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"elts\",)\n    elts: list[expr]\n    if sys.version_info >= (3, 13):\n        def __init__(self, elts: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, elts: list[expr], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, elts: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass ListComp(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"elt\", \"generators\")\n    elt: expr\n    generators: list[comprehension]\n    if sys.version_info >= (3, 13):\n        def __init__(self, elt: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, elt: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass SetComp(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"elt\", \"generators\")\n    elt: expr\n    generators: list[comprehension]\n    if sys.version_info >= (3, 13):\n        def __init__(self, elt: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, elt: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass DictComp(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"key\", \"value\", \"generators\")\n    key: expr\n    value: expr\n    generators: list[comprehension]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self, key: expr, value: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n    else:\n        def __init__(self, key: expr, value: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, key: expr = ..., value: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass GeneratorExp(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"elt\", \"generators\")\n    elt: expr\n    generators: list[comprehension]\n    if sys.version_info >= (3, 13):\n        def __init__(self, elt: expr, generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, elt: expr, generators: list[comprehension], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, elt: expr = ..., generators: list[comprehension] = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass Await(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\",)\n    value: expr\n    def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Yield(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\",)\n    value: expr | None\n    def __init__(self, value: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, value: expr | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass YieldFrom(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\",)\n    value: expr\n    def __init__(self, value: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Compare(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"left\", \"ops\", \"comparators\")\n    left: expr\n    ops: list[cmpop]\n    comparators: list[expr]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self, left: expr, ops: list[cmpop] = ..., comparators: list[expr] = ..., **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n    else:\n        def __init__(self, left: expr, ops: list[cmpop], comparators: list[expr], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, left: expr = ..., ops: list[cmpop] = ..., comparators: list[expr] = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass Call(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"func\", \"args\", \"keywords\")\n    func: expr\n    args: list[expr]\n    keywords: list[keyword]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self, func: expr, args: list[expr] = ..., keywords: list[keyword] = ..., **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n    else:\n        def __init__(self, func: expr, args: list[expr], keywords: list[keyword], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, func: expr = ..., args: list[expr] = ..., keywords: list[keyword] = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass FormattedValue(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\", \"conversion\", \"format_spec\")\n    value: expr\n    conversion: int\n    format_spec: expr | None\n    def __init__(self, value: expr, conversion: int, format_spec: expr | None = None, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, value: expr = ..., conversion: int = ..., format_spec: expr | None = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass JoinedStr(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"values\",)\n    values: list[expr]\n    if sys.version_info >= (3, 13):\n        def __init__(self, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, values: list[expr], **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nif sys.version_info >= (3, 14):\n    class TemplateStr(expr):\n        __match_args__ = (\"values\",)\n        values: list[expr]\n        def __init__(self, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n        def __replace__(self, *, values: list[expr] = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\n    class Interpolation(expr):\n        __match_args__ = (\"value\", \"str\", \"conversion\", \"format_spec\")\n        value: expr\n        str: builtins.str\n        conversion: int\n        format_spec: expr | None = None\n        def __init__(\n            self,\n            value: expr = ...,\n            str: builtins.str = ...,\n            conversion: int = ...,\n            format_spec: expr | None = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> None: ...\n        def __replace__(\n            self,\n            *,\n            value: expr = ...,\n            str: builtins.str = ...,\n            conversion: int = ...,\n            format_spec: expr | None = ...,\n            **kwargs: Unpack[_Attributes],\n        ) -> Self: ...\n\nif sys.version_info >= (3, 10):\n    from types import EllipsisType\n\n    _ConstantValue: typing_extensions.TypeAlias = str | bytes | bool | int | float | complex | None | EllipsisType\nelse:\n    # Rely on builtins.ellipsis\n    _ConstantValue: typing_extensions.TypeAlias = str | bytes | bool | int | float | complex | None | ellipsis  # noqa: F821\n\nclass Constant(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\", \"kind\")\n    value: _ConstantValue\n    kind: str | None\n    if sys.version_info < (3, 14):\n        # Aliases for value, for backwards compatibility\n        @property\n        @deprecated(\"Removed in Python 3.14. Use `value` instead.\")\n        def n(self) -> _ConstantValue: ...\n        @n.setter\n        @deprecated(\"Removed in Python 3.14. Use `value` instead.\")\n        def n(self, value: _ConstantValue) -> None: ...\n        @property\n        @deprecated(\"Removed in Python 3.14. Use `value` instead.\")\n        def s(self) -> _ConstantValue: ...\n        @s.setter\n        @deprecated(\"Removed in Python 3.14. Use `value` instead.\")\n        def s(self, value: _ConstantValue) -> None: ...\n\n    def __init__(self, value: _ConstantValue, kind: str | None = None, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, value: _ConstantValue = ..., kind: str | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Attribute(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\", \"attr\", \"ctx\")\n    value: expr\n    attr: str\n    ctx: expr_context  # Not present in Python < 3.13 if not passed to `__init__`\n    def __init__(self, value: expr, attr: str, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, value: expr = ..., attr: str = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass Subscript(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\", \"slice\", \"ctx\")\n    value: expr\n    slice: expr\n    ctx: expr_context  # Not present in Python < 3.13 if not passed to `__init__`\n    def __init__(self, value: expr, slice: expr, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, value: expr = ..., slice: expr = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass Starred(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"value\", \"ctx\")\n    value: expr\n    ctx: expr_context  # Not present in Python < 3.13 if not passed to `__init__`\n    def __init__(self, value: expr, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, value: expr = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Name(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"id\", \"ctx\")\n    id: str\n    ctx: expr_context  # Not present in Python < 3.13 if not passed to `__init__`\n    def __init__(self, id: str, ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, id: str = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass List(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"elts\", \"ctx\")\n    elts: list[expr]\n    ctx: expr_context  # Not present in Python < 3.13 if not passed to `__init__`\n    if sys.version_info >= (3, 13):\n        def __init__(self, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, elts: list[expr], ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass Tuple(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"elts\", \"ctx\")\n    elts: list[expr]\n    ctx: expr_context  # Not present in Python < 3.13 if not passed to `__init__`\n    dims: list[expr]\n    if sys.version_info >= (3, 13):\n        def __init__(self, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, elts: list[expr], ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, elts: list[expr] = ..., ctx: expr_context = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\n@deprecated(\"Deprecated since Python 3.9.\")\nclass slice(AST): ...\n\nclass Slice(expr):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"lower\", \"upper\", \"step\")\n    lower: expr | None\n    upper: expr | None\n    step: expr | None\n    def __init__(\n        self, lower: expr | None = None, upper: expr | None = None, step: expr | None = None, **kwargs: Unpack[_Attributes]\n    ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, lower: expr | None = ..., upper: expr | None = ..., step: expr | None = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\n@deprecated(\"Deprecated since Python 3.9. Use `ast.Tuple` instead.\")\nclass ExtSlice(slice):\n    def __new__(cls, dims: Iterable[slice] = (), **kwargs: Unpack[_Attributes]) -> Tuple: ...  # type: ignore[misc]\n\n@deprecated(\"Deprecated since Python 3.9. Use the index value directly instead.\")\nclass Index(slice):\n    def __new__(cls, value: expr, **kwargs: Unpack[_Attributes]) -> expr: ...  # type: ignore[misc]\n\nclass expr_context(AST): ...\n\n@deprecated(\"Deprecated since Python 3.9. Unused in Python 3.\")\nclass AugLoad(expr_context): ...\n\n@deprecated(\"Deprecated since Python 3.9. Unused in Python 3.\")\nclass AugStore(expr_context): ...\n\n@deprecated(\"Deprecated since Python 3.9. Unused in Python 3.\")\nclass Param(expr_context): ...\n\n@deprecated(\"Deprecated since Python 3.9. Unused in Python 3.\")\nclass Suite(mod): ...\n\nclass Load(expr_context): ...\nclass Store(expr_context): ...\nclass Del(expr_context): ...\nclass boolop(AST): ...\nclass And(boolop): ...\nclass Or(boolop): ...\nclass operator(AST): ...\nclass Add(operator): ...\nclass Sub(operator): ...\nclass Mult(operator): ...\nclass MatMult(operator): ...\nclass Div(operator): ...\nclass Mod(operator): ...\nclass Pow(operator): ...\nclass LShift(operator): ...\nclass RShift(operator): ...\nclass BitOr(operator): ...\nclass BitXor(operator): ...\nclass BitAnd(operator): ...\nclass FloorDiv(operator): ...\nclass unaryop(AST): ...\nclass Invert(unaryop): ...\nclass Not(unaryop): ...\nclass UAdd(unaryop): ...\nclass USub(unaryop): ...\nclass cmpop(AST): ...\nclass Eq(cmpop): ...\nclass NotEq(cmpop): ...\nclass Lt(cmpop): ...\nclass LtE(cmpop): ...\nclass Gt(cmpop): ...\nclass GtE(cmpop): ...\nclass Is(cmpop): ...\nclass IsNot(cmpop): ...\nclass In(cmpop): ...\nclass NotIn(cmpop): ...\n\nclass comprehension(AST):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"target\", \"iter\", \"ifs\", \"is_async\")\n    target: expr\n    iter: expr\n    ifs: list[expr]\n    is_async: int\n    if sys.version_info >= (3, 13):\n        @overload\n        def __init__(self, target: expr, iter: expr, ifs: list[expr], is_async: int) -> None: ...\n        @overload\n        def __init__(self, target: expr, iter: expr, ifs: list[expr] = ..., *, is_async: int) -> None: ...\n    else:\n        def __init__(self, target: expr, iter: expr, ifs: list[expr], is_async: int) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, target: expr = ..., iter: expr = ..., ifs: list[expr] = ..., is_async: int = ...) -> Self: ...\n\nclass excepthandler(AST):\n    lineno: int\n    col_offset: int\n    end_lineno: int | None\n    end_col_offset: int | None\n    def __init__(self, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int | None = ..., end_col_offset: int | None = ...\n        ) -> Self: ...\n\nclass ExceptHandler(excepthandler):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"type\", \"name\", \"body\")\n    type: expr | None\n    name: str | None\n    body: list[stmt]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self, type: expr | None = None, name: str | None = None, body: list[stmt] = ..., **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(self, type: expr | None, name: str | None, body: list[stmt], **kwargs: Unpack[_Attributes]) -> None: ...\n        @overload\n        def __init__(\n            self, type: expr | None = None, name: str | None = None, *, body: list[stmt], **kwargs: Unpack[_Attributes]\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, type: expr | None = ..., name: str | None = ..., body: list[stmt] = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass arguments(AST):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"posonlyargs\", \"args\", \"vararg\", \"kwonlyargs\", \"kw_defaults\", \"kwarg\", \"defaults\")\n    posonlyargs: list[arg]\n    args: list[arg]\n    vararg: arg | None\n    kwonlyargs: list[arg]\n    kw_defaults: list[expr | None]\n    kwarg: arg | None\n    defaults: list[expr]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            posonlyargs: list[arg] = ...,\n            args: list[arg] = ...,\n            vararg: arg | None = None,\n            kwonlyargs: list[arg] = ...,\n            kw_defaults: list[expr | None] = ...,\n            kwarg: arg | None = None,\n            defaults: list[expr] = ...,\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self,\n            posonlyargs: list[arg],\n            args: list[arg],\n            vararg: arg | None,\n            kwonlyargs: list[arg],\n            kw_defaults: list[expr | None],\n            kwarg: arg | None,\n            defaults: list[expr],\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            posonlyargs: list[arg],\n            args: list[arg],\n            vararg: arg | None,\n            kwonlyargs: list[arg],\n            kw_defaults: list[expr | None],\n            kwarg: arg | None = None,\n            *,\n            defaults: list[expr],\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            posonlyargs: list[arg],\n            args: list[arg],\n            vararg: arg | None = None,\n            *,\n            kwonlyargs: list[arg],\n            kw_defaults: list[expr | None],\n            kwarg: arg | None = None,\n            defaults: list[expr],\n        ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self,\n            *,\n            posonlyargs: list[arg] = ...,\n            args: list[arg] = ...,\n            vararg: arg | None = ...,\n            kwonlyargs: list[arg] = ...,\n            kw_defaults: list[expr | None] = ...,\n            kwarg: arg | None = ...,\n            defaults: list[expr] = ...,\n        ) -> Self: ...\n\nclass arg(AST):\n    lineno: int\n    col_offset: int\n    end_lineno: int | None\n    end_col_offset: int | None\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"arg\", \"annotation\", \"type_comment\")\n    arg: str\n    annotation: expr | None\n    type_comment: str | None\n    def __init__(\n        self, arg: str, annotation: expr | None = None, type_comment: str | None = None, **kwargs: Unpack[_Attributes]\n    ) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(\n            self, *, arg: str = ..., annotation: expr | None = ..., type_comment: str | None = ..., **kwargs: Unpack[_Attributes]\n        ) -> Self: ...\n\nclass keyword(AST):\n    lineno: int\n    col_offset: int\n    end_lineno: int | None\n    end_col_offset: int | None\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"arg\", \"value\")\n    arg: str | None\n    value: expr\n    @overload\n    def __init__(self, arg: str | None, value: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n    @overload\n    def __init__(self, arg: str | None = None, *, value: expr, **kwargs: Unpack[_Attributes]) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, arg: str | None = ..., value: expr = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass alias(AST):\n    name: str\n    asname: str | None\n    if sys.version_info >= (3, 10):\n        lineno: int\n        col_offset: int\n        end_lineno: int | None\n        end_col_offset: int | None\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"name\", \"asname\")\n    if sys.version_info >= (3, 10):\n        def __init__(self, name: str, asname: str | None = None, **kwargs: Unpack[_Attributes]) -> None: ...\n    else:\n        def __init__(self, name: str, asname: str | None = None) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, name: str = ..., asname: str | None = ..., **kwargs: Unpack[_Attributes]) -> Self: ...\n\nclass withitem(AST):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"context_expr\", \"optional_vars\")\n    context_expr: expr\n    optional_vars: expr | None\n    def __init__(self, context_expr: expr, optional_vars: expr | None = None) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, context_expr: expr = ..., optional_vars: expr | None = ...) -> Self: ...\n\nif sys.version_info >= (3, 10):\n    class pattern(AST):\n        lineno: int\n        col_offset: int\n        end_lineno: int\n        end_col_offset: int\n        def __init__(self, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self, *, lineno: int = ..., col_offset: int = ..., end_lineno: int = ..., end_col_offset: int = ...\n            ) -> Self: ...\n\n    class match_case(AST):\n        __match_args__ = (\"pattern\", \"guard\", \"body\")\n        pattern: ast.pattern\n        guard: expr | None\n        body: list[stmt]\n        if sys.version_info >= (3, 13):\n            def __init__(self, pattern: ast.pattern, guard: expr | None = None, body: list[stmt] = ...) -> None: ...\n        elif sys.version_info >= (3, 10):\n            @overload\n            def __init__(self, pattern: ast.pattern, guard: expr | None, body: list[stmt]) -> None: ...\n            @overload\n            def __init__(self, pattern: ast.pattern, guard: expr | None = None, *, body: list[stmt]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self, *, pattern: ast.pattern = ..., guard: expr | None = ..., body: list[stmt] = ...) -> Self: ...\n\n    class Match(stmt):\n        __match_args__ = (\"subject\", \"cases\")\n        subject: expr\n        cases: list[match_case]\n        if sys.version_info >= (3, 13):\n            def __init__(self, subject: expr, cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]) -> None: ...\n        else:\n            def __init__(self, subject: expr, cases: list[match_case], **kwargs: Unpack[_Attributes]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self, *, subject: expr = ..., cases: list[match_case] = ..., **kwargs: Unpack[_Attributes]\n            ) -> Self: ...\n\n    class MatchValue(pattern):\n        __match_args__ = (\"value\",)\n        value: expr\n        def __init__(self, value: expr, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self, *, value: expr = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ...\n\n    class MatchSingleton(pattern):\n        __match_args__ = (\"value\",)\n        value: bool | None\n        def __init__(self, value: bool | None, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self, *, value: bool | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ...\n\n    class MatchSequence(pattern):\n        __match_args__ = (\"patterns\",)\n        patterns: list[pattern]\n        if sys.version_info >= (3, 13):\n            def __init__(self, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> None: ...\n        else:\n            def __init__(self, patterns: list[pattern], **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ...\n\n    class MatchMapping(pattern):\n        __match_args__ = (\"keys\", \"patterns\", \"rest\")\n        keys: list[expr]\n        patterns: list[pattern]\n        rest: str | None\n        if sys.version_info >= (3, 13):\n            def __init__(\n                self,\n                keys: list[expr] = ...,\n                patterns: list[pattern] = ...,\n                rest: str | None = None,\n                **kwargs: Unpack[_Attributes[int]],\n            ) -> None: ...\n        else:\n            def __init__(\n                self, keys: list[expr], patterns: list[pattern], rest: str | None = None, **kwargs: Unpack[_Attributes[int]]\n            ) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self,\n                *,\n                keys: list[expr] = ...,\n                patterns: list[pattern] = ...,\n                rest: str | None = ...,\n                **kwargs: Unpack[_Attributes[int]],\n            ) -> Self: ...\n\n    class MatchClass(pattern):\n        __match_args__ = (\"cls\", \"patterns\", \"kwd_attrs\", \"kwd_patterns\")\n        cls: expr\n        patterns: list[pattern]\n        kwd_attrs: list[str]\n        kwd_patterns: list[pattern]\n        if sys.version_info >= (3, 13):\n            def __init__(\n                self,\n                cls: expr,\n                patterns: list[pattern] = ...,\n                kwd_attrs: list[str] = ...,\n                kwd_patterns: list[pattern] = ...,\n                **kwargs: Unpack[_Attributes[int]],\n            ) -> None: ...\n        else:\n            def __init__(\n                self,\n                cls: expr,\n                patterns: list[pattern],\n                kwd_attrs: list[str],\n                kwd_patterns: list[pattern],\n                **kwargs: Unpack[_Attributes[int]],\n            ) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self,\n                *,\n                cls: expr = ...,\n                patterns: list[pattern] = ...,\n                kwd_attrs: list[str] = ...,\n                kwd_patterns: list[pattern] = ...,\n                **kwargs: Unpack[_Attributes[int]],\n            ) -> Self: ...\n\n    class MatchStar(pattern):\n        __match_args__ = (\"name\",)\n        name: str | None\n        def __init__(self, name: str | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self, *, name: str | None = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ...\n\n    class MatchAs(pattern):\n        __match_args__ = (\"pattern\", \"name\")\n        pattern: ast.pattern | None\n        name: str | None\n        def __init__(\n            self, pattern: ast.pattern | None = None, name: str | None = None, **kwargs: Unpack[_Attributes[int]]\n        ) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self, *, pattern: ast.pattern | None = ..., name: str | None = ..., **kwargs: Unpack[_Attributes[int]]\n            ) -> Self: ...\n\n    class MatchOr(pattern):\n        __match_args__ = (\"patterns\",)\n        patterns: list[pattern]\n        if sys.version_info >= (3, 13):\n            def __init__(self, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> None: ...\n        else:\n            def __init__(self, patterns: list[pattern], **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self, *, patterns: list[pattern] = ..., **kwargs: Unpack[_Attributes[int]]) -> Self: ...\n\nclass type_ignore(AST): ...\n\nclass TypeIgnore(type_ignore):\n    if sys.version_info >= (3, 10):\n        __match_args__ = (\"lineno\", \"tag\")\n    lineno: int\n    tag: str\n    def __init__(self, lineno: int, tag: str) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __replace__(self, *, lineno: int = ..., tag: str = ...) -> Self: ...\n\nif sys.version_info >= (3, 12):\n    class type_param(AST):\n        lineno: int\n        col_offset: int\n        end_lineno: int\n        end_col_offset: int\n        def __init__(self, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(self, **kwargs: Unpack[_Attributes[int]]) -> Self: ...\n\n    class TypeVar(type_param):\n        if sys.version_info >= (3, 13):\n            __match_args__ = (\"name\", \"bound\", \"default_value\")\n        else:\n            __match_args__ = (\"name\", \"bound\")\n        name: str\n        bound: expr | None\n        if sys.version_info >= (3, 13):\n            default_value: expr | None\n            def __init__(\n                self, name: str, bound: expr | None = None, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]]\n            ) -> None: ...\n        else:\n            def __init__(self, name: str, bound: expr | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self,\n                *,\n                name: str = ...,\n                bound: expr | None = ...,\n                default_value: expr | None = ...,\n                **kwargs: Unpack[_Attributes[int]],\n            ) -> Self: ...\n\n    class ParamSpec(type_param):\n        if sys.version_info >= (3, 13):\n            __match_args__ = (\"name\", \"default_value\")\n        else:\n            __match_args__ = (\"name\",)\n        name: str\n        if sys.version_info >= (3, 13):\n            default_value: expr | None\n            def __init__(self, name: str, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n        else:\n            def __init__(self, name: str, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self, *, name: str = ..., default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]]\n            ) -> Self: ...\n\n    class TypeVarTuple(type_param):\n        if sys.version_info >= (3, 13):\n            __match_args__ = (\"name\", \"default_value\")\n        else:\n            __match_args__ = (\"name\",)\n        name: str\n        if sys.version_info >= (3, 13):\n            default_value: expr | None\n            def __init__(self, name: str, default_value: expr | None = None, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n        else:\n            def __init__(self, name: str, **kwargs: Unpack[_Attributes[int]]) -> None: ...\n\n        if sys.version_info >= (3, 14):\n            def __replace__(\n                self, *, name: str = ..., default_value: expr | None = ..., **kwargs: Unpack[_Attributes[int]]\n            ) -> Self: ...\n\nif sys.version_info >= (3, 14):\n    @type_check_only\n    class _ABC(type):\n        def __init__(cls, *args: Unused) -> None: ...\n\nelse:\n    class _ABC(type):\n        def __init__(cls, *args: Unused) -> None: ...\n\nif sys.version_info < (3, 14):\n    @deprecated(\"Removed in Python 3.14. Use `ast.Constant` instead.\")\n    class Num(Constant, metaclass=_ABC):\n        def __new__(cls, n: complex, **kwargs: Unpack[_Attributes]) -> Constant: ...  # type: ignore[misc]  # pyright: ignore[reportInconsistentConstructor]\n\n    @deprecated(\"Removed in Python 3.14. Use `ast.Constant` instead.\")\n    class Str(Constant, metaclass=_ABC):\n        def __new__(cls, s: str, **kwargs: Unpack[_Attributes]) -> Constant: ...  # type: ignore[misc]  # pyright: ignore[reportInconsistentConstructor]\n\n    @deprecated(\"Removed in Python 3.14. Use `ast.Constant` instead.\")\n    class Bytes(Constant, metaclass=_ABC):\n        def __new__(cls, s: bytes, **kwargs: Unpack[_Attributes]) -> Constant: ...  # type: ignore[misc]  # pyright: ignore[reportInconsistentConstructor]\n\n    @deprecated(\"Removed in Python 3.14. Use `ast.Constant` instead.\")\n    class NameConstant(Constant, metaclass=_ABC):\n        def __new__(cls, value: _ConstantValue, kind: str | None, **kwargs: Unpack[_Attributes]) -> Constant: ...  # type: ignore[misc]  # pyright: ignore[reportInconsistentConstructor]\n\n    @deprecated(\"Removed in Python 3.14. Use `ast.Constant` instead.\")\n    class Ellipsis(Constant, metaclass=_ABC):\n        def __new__(cls, **kwargs: Unpack[_Attributes]) -> Constant: ...  # type: ignore[misc]  # pyright: ignore[reportInconsistentConstructor]\n\n# everything below here is defined in ast.py\n\n_T = _TypeVar(\"_T\", bound=AST)\n\nif sys.version_info >= (3, 13):\n    @overload\n    def parse(\n        source: _T,\n        filename: str | bytes | os.PathLike[Any] = \"<unknown>\",\n        mode: Literal[\"exec\", \"eval\", \"func_type\", \"single\"] = \"exec\",\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n        optimize: Literal[-1, 0, 1, 2] = -1,\n    ) -> _T: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | bytes | os.PathLike[Any] = \"<unknown>\",\n        mode: Literal[\"exec\"] = \"exec\",\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n        optimize: Literal[-1, 0, 1, 2] = -1,\n    ) -> Module: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | bytes | os.PathLike[Any],\n        mode: Literal[\"eval\"],\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n        optimize: Literal[-1, 0, 1, 2] = -1,\n    ) -> Expression: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | bytes | os.PathLike[Any],\n        mode: Literal[\"func_type\"],\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n        optimize: Literal[-1, 0, 1, 2] = -1,\n    ) -> FunctionType: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | bytes | os.PathLike[Any],\n        mode: Literal[\"single\"],\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n        optimize: Literal[-1, 0, 1, 2] = -1,\n    ) -> Interactive: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        *,\n        mode: Literal[\"eval\"],\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n        optimize: Literal[-1, 0, 1, 2] = -1,\n    ) -> Expression: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        *,\n        mode: Literal[\"func_type\"],\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n        optimize: Literal[-1, 0, 1, 2] = -1,\n    ) -> FunctionType: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        *,\n        mode: Literal[\"single\"],\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n        optimize: Literal[-1, 0, 1, 2] = -1,\n    ) -> Interactive: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | bytes | os.PathLike[Any] = \"<unknown>\",\n        mode: str = \"exec\",\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n        optimize: Literal[-1, 0, 1, 2] = -1,\n    ) -> mod: ...\n\nelse:\n    @overload\n    def parse(\n        source: _T,\n        filename: str | bytes | os.PathLike[Any] = \"<unknown>\",\n        mode: Literal[\"exec\", \"eval\", \"func_type\", \"single\"] = \"exec\",\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n    ) -> _T: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | bytes | os.PathLike[Any] = \"<unknown>\",\n        mode: Literal[\"exec\"] = \"exec\",\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n    ) -> Module: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | bytes | os.PathLike[Any],\n        mode: Literal[\"eval\"],\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n    ) -> Expression: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | bytes | os.PathLike[Any],\n        mode: Literal[\"func_type\"],\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n    ) -> FunctionType: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | bytes | os.PathLike[Any],\n        mode: Literal[\"single\"],\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n    ) -> Interactive: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        *,\n        mode: Literal[\"eval\"],\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n    ) -> Expression: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        *,\n        mode: Literal[\"func_type\"],\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n    ) -> FunctionType: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        *,\n        mode: Literal[\"single\"],\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n    ) -> Interactive: ...\n    @overload\n    def parse(\n        source: str | ReadableBuffer,\n        filename: str | bytes | os.PathLike[Any] = \"<unknown>\",\n        mode: str = \"exec\",\n        *,\n        type_comments: bool = False,\n        feature_version: None | int | tuple[int, int] = None,\n    ) -> mod: ...\n\ndef literal_eval(node_or_string: str | AST) -> Any: ...\n\nif sys.version_info >= (3, 13):\n    def dump(\n        node: AST,\n        annotate_fields: bool = True,\n        include_attributes: bool = False,\n        *,\n        indent: int | str | None = None,\n        show_empty: bool = False,\n    ) -> str: ...\n\nelse:\n    def dump(\n        node: AST, annotate_fields: bool = True, include_attributes: bool = False, *, indent: int | str | None = None\n    ) -> str: ...\n\ndef copy_location(new_node: _T, old_node: AST) -> _T: ...\ndef fix_missing_locations(node: _T) -> _T: ...\ndef increment_lineno(node: _T, n: int = 1) -> _T: ...\ndef iter_fields(node: AST) -> Iterator[tuple[str, Any]]: ...\ndef iter_child_nodes(node: AST) -> Iterator[AST]: ...\ndef get_docstring(node: AsyncFunctionDef | FunctionDef | ClassDef | Module, clean: bool = True) -> str | None: ...\ndef get_source_segment(source: str, node: AST, *, padded: bool = False) -> str | None: ...\ndef walk(node: AST) -> Iterator[AST]: ...\n\nif sys.version_info >= (3, 14):\n    def compare(left: AST, right: AST, /, *, compare_attributes: bool = False) -> bool: ...\n\nclass NodeVisitor:\n    # All visit methods below can be overwritten by subclasses and return an\n    # arbitrary value, which is passed to the caller.\n    def visit(self, node: AST) -> Any: ...\n    def generic_visit(self, node: AST) -> Any: ...\n    # The following visit methods are not defined on NodeVisitor, but can\n    # be implemented by subclasses and are called during a visit if defined.\n    def visit_Module(self, node: Module) -> Any: ...\n    def visit_Interactive(self, node: Interactive) -> Any: ...\n    def visit_Expression(self, node: Expression) -> Any: ...\n    def visit_FunctionDef(self, node: FunctionDef) -> Any: ...\n    def visit_AsyncFunctionDef(self, node: AsyncFunctionDef) -> Any: ...\n    def visit_ClassDef(self, node: ClassDef) -> Any: ...\n    def visit_Return(self, node: Return) -> Any: ...\n    def visit_Delete(self, node: Delete) -> Any: ...\n    def visit_Assign(self, node: Assign) -> Any: ...\n    def visit_AugAssign(self, node: AugAssign) -> Any: ...\n    def visit_AnnAssign(self, node: AnnAssign) -> Any: ...\n    def visit_For(self, node: For) -> Any: ...\n    def visit_AsyncFor(self, node: AsyncFor) -> Any: ...\n    def visit_While(self, node: While) -> Any: ...\n    def visit_If(self, node: If) -> Any: ...\n    def visit_With(self, node: With) -> Any: ...\n    def visit_AsyncWith(self, node: AsyncWith) -> Any: ...\n    def visit_Raise(self, node: Raise) -> Any: ...\n    def visit_Try(self, node: Try) -> Any: ...\n    def visit_Assert(self, node: Assert) -> Any: ...\n    def visit_Import(self, node: Import) -> Any: ...\n    def visit_ImportFrom(self, node: ImportFrom) -> Any: ...\n    def visit_Global(self, node: Global) -> Any: ...\n    def visit_Nonlocal(self, node: Nonlocal) -> Any: ...\n    def visit_Expr(self, node: Expr) -> Any: ...\n    def visit_Pass(self, node: Pass) -> Any: ...\n    def visit_Break(self, node: Break) -> Any: ...\n    def visit_Continue(self, node: Continue) -> Any: ...\n    def visit_Slice(self, node: Slice) -> Any: ...\n    def visit_BoolOp(self, node: BoolOp) -> Any: ...\n    def visit_BinOp(self, node: BinOp) -> Any: ...\n    def visit_UnaryOp(self, node: UnaryOp) -> Any: ...\n    def visit_Lambda(self, node: Lambda) -> Any: ...\n    def visit_IfExp(self, node: IfExp) -> Any: ...\n    def visit_Dict(self, node: Dict) -> Any: ...\n    def visit_Set(self, node: Set) -> Any: ...\n    def visit_ListComp(self, node: ListComp) -> Any: ...\n    def visit_SetComp(self, node: SetComp) -> Any: ...\n    def visit_DictComp(self, node: DictComp) -> Any: ...\n    def visit_GeneratorExp(self, node: GeneratorExp) -> Any: ...\n    def visit_Await(self, node: Await) -> Any: ...\n    def visit_Yield(self, node: Yield) -> Any: ...\n    def visit_YieldFrom(self, node: YieldFrom) -> Any: ...\n    def visit_Compare(self, node: Compare) -> Any: ...\n    def visit_Call(self, node: Call) -> Any: ...\n    def visit_FormattedValue(self, node: FormattedValue) -> Any: ...\n    def visit_JoinedStr(self, node: JoinedStr) -> Any: ...\n    def visit_Constant(self, node: Constant) -> Any: ...\n    def visit_NamedExpr(self, node: NamedExpr) -> Any: ...\n    def visit_TypeIgnore(self, node: TypeIgnore) -> Any: ...\n    def visit_Attribute(self, node: Attribute) -> Any: ...\n    def visit_Subscript(self, node: Subscript) -> Any: ...\n    def visit_Starred(self, node: Starred) -> Any: ...\n    def visit_Name(self, node: Name) -> Any: ...\n    def visit_List(self, node: List) -> Any: ...\n    def visit_Tuple(self, node: Tuple) -> Any: ...\n    def visit_Del(self, node: Del) -> Any: ...\n    def visit_Load(self, node: Load) -> Any: ...\n    def visit_Store(self, node: Store) -> Any: ...\n    def visit_And(self, node: And) -> Any: ...\n    def visit_Or(self, node: Or) -> Any: ...\n    def visit_Add(self, node: Add) -> Any: ...\n    def visit_BitAnd(self, node: BitAnd) -> Any: ...\n    def visit_BitOr(self, node: BitOr) -> Any: ...\n    def visit_BitXor(self, node: BitXor) -> Any: ...\n    def visit_Div(self, node: Div) -> Any: ...\n    def visit_FloorDiv(self, node: FloorDiv) -> Any: ...\n    def visit_LShift(self, node: LShift) -> Any: ...\n    def visit_Mod(self, node: Mod) -> Any: ...\n    def visit_Mult(self, node: Mult) -> Any: ...\n    def visit_MatMult(self, node: MatMult) -> Any: ...\n    def visit_Pow(self, node: Pow) -> Any: ...\n    def visit_RShift(self, node: RShift) -> Any: ...\n    def visit_Sub(self, node: Sub) -> Any: ...\n    def visit_Invert(self, node: Invert) -> Any: ...\n    def visit_Not(self, node: Not) -> Any: ...\n    def visit_UAdd(self, node: UAdd) -> Any: ...\n    def visit_USub(self, node: USub) -> Any: ...\n    def visit_Eq(self, node: Eq) -> Any: ...\n    def visit_Gt(self, node: Gt) -> Any: ...\n    def visit_GtE(self, node: GtE) -> Any: ...\n    def visit_In(self, node: In) -> Any: ...\n    def visit_Is(self, node: Is) -> Any: ...\n    def visit_IsNot(self, node: IsNot) -> Any: ...\n    def visit_Lt(self, node: Lt) -> Any: ...\n    def visit_LtE(self, node: LtE) -> Any: ...\n    def visit_NotEq(self, node: NotEq) -> Any: ...\n    def visit_NotIn(self, node: NotIn) -> Any: ...\n    def visit_comprehension(self, node: comprehension) -> Any: ...\n    def visit_ExceptHandler(self, node: ExceptHandler) -> Any: ...\n    def visit_arguments(self, node: arguments) -> Any: ...\n    def visit_arg(self, node: arg) -> Any: ...\n    def visit_keyword(self, node: keyword) -> Any: ...\n    def visit_alias(self, node: alias) -> Any: ...\n    def visit_withitem(self, node: withitem) -> Any: ...\n    if sys.version_info >= (3, 10):\n        def visit_Match(self, node: Match) -> Any: ...\n        def visit_match_case(self, node: match_case) -> Any: ...\n        def visit_MatchValue(self, node: MatchValue) -> Any: ...\n        def visit_MatchSequence(self, node: MatchSequence) -> Any: ...\n        def visit_MatchSingleton(self, node: MatchSingleton) -> Any: ...\n        def visit_MatchStar(self, node: MatchStar) -> Any: ...\n        def visit_MatchMapping(self, node: MatchMapping) -> Any: ...\n        def visit_MatchClass(self, node: MatchClass) -> Any: ...\n        def visit_MatchAs(self, node: MatchAs) -> Any: ...\n        def visit_MatchOr(self, node: MatchOr) -> Any: ...\n\n    if sys.version_info >= (3, 11):\n        def visit_TryStar(self, node: TryStar) -> Any: ...\n\n    if sys.version_info >= (3, 12):\n        def visit_TypeVar(self, node: TypeVar) -> Any: ...\n        def visit_ParamSpec(self, node: ParamSpec) -> Any: ...\n        def visit_TypeVarTuple(self, node: TypeVarTuple) -> Any: ...\n        def visit_TypeAlias(self, node: TypeAlias) -> Any: ...\n\n    # visit methods for deprecated nodes\n    def visit_ExtSlice(self, node: ExtSlice) -> Any: ...\n    def visit_Index(self, node: Index) -> Any: ...\n    def visit_Suite(self, node: Suite) -> Any: ...\n    def visit_AugLoad(self, node: AugLoad) -> Any: ...\n    def visit_AugStore(self, node: AugStore) -> Any: ...\n    def visit_Param(self, node: Param) -> Any: ...\n\n    if sys.version_info < (3, 14):\n        @deprecated(\"Removed in Python 3.14. Use `visit_Constant` instead.\")\n        def visit_Num(self, node: Num) -> Any: ...  # type: ignore[deprecated]\n        @deprecated(\"Removed in Python 3.14. Use `visit_Constant` instead.\")\n        def visit_Str(self, node: Str) -> Any: ...  # type: ignore[deprecated]\n        @deprecated(\"Removed in Python 3.14. Use `visit_Constant` instead.\")\n        def visit_Bytes(self, node: Bytes) -> Any: ...  # type: ignore[deprecated]\n        @deprecated(\"Removed in Python 3.14. Use `visit_Constant` instead.\")\n        def visit_NameConstant(self, node: NameConstant) -> Any: ...  # type: ignore[deprecated]\n        @deprecated(\"Removed in Python 3.14. Use `visit_Constant` instead.\")\n        def visit_Ellipsis(self, node: Ellipsis) -> Any: ...  # type: ignore[deprecated]\n\nclass NodeTransformer(NodeVisitor):\n    def generic_visit(self, node: AST) -> AST: ...\n    # TODO: Override the visit_* methods with better return types.\n    #       The usual return type is AST | None, but Iterable[AST]\n    #       is also allowed in some cases -- this needs to be mapped.\n\ndef unparse(ast_obj: AST) -> str: ...\n\nif sys.version_info >= (3, 14):\n    def main(args: Sequence[str] | None = None) -> None: ...\n\nelse:\n    def main() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asynchat.pyi",
    "content": "import asyncore\nfrom abc import abstractmethod\n\nclass simple_producer:\n    def __init__(self, data: bytes, buffer_size: int = 512) -> None: ...\n    def more(self) -> bytes: ...\n\nclass async_chat(asyncore.dispatcher):\n    ac_in_buffer_size: int\n    ac_out_buffer_size: int\n    @abstractmethod\n    def collect_incoming_data(self, data: bytes) -> None: ...\n    @abstractmethod\n    def found_terminator(self) -> None: ...\n    def set_terminator(self, term: bytes | int | None) -> None: ...\n    def get_terminator(self) -> bytes | int | None: ...\n    def push(self, data: bytes) -> None: ...\n    def push_with_producer(self, producer: simple_producer) -> None: ...\n    def close_when_done(self) -> None: ...\n    def initiate_send(self) -> None: ...\n    def discard_buffers(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/__init__.pyi",
    "content": "# This condition is so big, it's clearer to keep to platform condition in two blocks\n# Can't NOQA on a specific line: https://github.com/plinss/flake8-noqa/issues/22\nimport sys\nfrom collections.abc import Awaitable, Coroutine, Generator\nfrom typing import Any, TypeVar\nfrom typing_extensions import TypeAlias\n\n# As at runtime, this depends on all submodules defining __all__ accurately.\nfrom .base_events import *\nfrom .coroutines import *\nfrom .events import *\nfrom .exceptions import *\nfrom .futures import *\nfrom .locks import *\nfrom .protocols import *\nfrom .queues import *\nfrom .runners import *\nfrom .streams import *\nfrom .subprocess import *\nfrom .tasks import *\nfrom .threads import *\nfrom .transports import *\n\nif sys.version_info >= (3, 14):\n    from .graph import *\n\nif sys.version_info >= (3, 11):\n    from .taskgroups import *\n    from .timeouts import *\n\nif sys.platform == \"win32\":\n    from .windows_events import *\nelse:\n    from .unix_events import *\n\nif sys.platform == \"win32\":\n    if sys.version_info >= (3, 14):\n\n        __all__ = (\n            \"BaseEventLoop\",  # from base_events\n            \"Server\",  # from base_events\n            \"iscoroutinefunction\",  # from coroutines\n            \"iscoroutine\",  # from coroutines\n            \"AbstractEventLoop\",  # from events\n            \"AbstractServer\",  # from events\n            \"Handle\",  # from events\n            \"TimerHandle\",  # from events\n            \"get_event_loop_policy\",  # from events\n            \"set_event_loop_policy\",  # from events\n            \"get_event_loop\",  # from events\n            \"set_event_loop\",  # from events\n            \"new_event_loop\",  # from events\n            \"_set_running_loop\",  # from events\n            \"get_running_loop\",  # from events\n            \"_get_running_loop\",  # from events\n            \"BrokenBarrierError\",  # from exceptions\n            \"CancelledError\",  # from exceptions\n            \"InvalidStateError\",  # from exceptions\n            \"TimeoutError\",  # from exceptions\n            \"IncompleteReadError\",  # from exceptions\n            \"LimitOverrunError\",  # from exceptions\n            \"SendfileNotAvailableError\",  # from exceptions\n            \"Future\",  # from futures\n            \"wrap_future\",  # from futures\n            \"isfuture\",  # from futures\n            \"future_discard_from_awaited_by\",  # from futures\n            \"future_add_to_awaited_by\",  # from futures\n            \"capture_call_graph\",  # from graph\n            \"format_call_graph\",  # from graph\n            \"print_call_graph\",  # from graph\n            \"FrameCallGraphEntry\",  # from graph\n            \"FutureCallGraph\",  # from graph\n            \"Lock\",  # from locks\n            \"Event\",  # from locks\n            \"Condition\",  # from locks\n            \"Semaphore\",  # from locks\n            \"BoundedSemaphore\",  # from locks\n            \"Barrier\",  # from locks\n            \"BaseProtocol\",  # from protocols\n            \"Protocol\",  # from protocols\n            \"DatagramProtocol\",  # from protocols\n            \"SubprocessProtocol\",  # from protocols\n            \"BufferedProtocol\",  # from protocols\n            \"Runner\",  # from runners\n            \"run\",  # from runners\n            \"Queue\",  # from queues\n            \"PriorityQueue\",  # from queues\n            \"LifoQueue\",  # from queues\n            \"QueueFull\",  # from queues\n            \"QueueEmpty\",  # from queues\n            \"QueueShutDown\",  # from queues\n            \"StreamReader\",  # from streams\n            \"StreamWriter\",  # from streams\n            \"StreamReaderProtocol\",  # from streams\n            \"open_connection\",  # from streams\n            \"start_server\",  # from streams\n            \"create_subprocess_exec\",  # from subprocess\n            \"create_subprocess_shell\",  # from subprocess\n            \"Task\",  # from tasks\n            \"create_task\",  # from tasks\n            \"FIRST_COMPLETED\",  # from tasks\n            \"FIRST_EXCEPTION\",  # from tasks\n            \"ALL_COMPLETED\",  # from tasks\n            \"wait\",  # from tasks\n            \"wait_for\",  # from tasks\n            \"as_completed\",  # from tasks\n            \"sleep\",  # from tasks\n            \"gather\",  # from tasks\n            \"shield\",  # from tasks\n            \"ensure_future\",  # from tasks\n            \"run_coroutine_threadsafe\",  # from tasks\n            \"current_task\",  # from tasks\n            \"all_tasks\",  # from tasks\n            \"create_eager_task_factory\",  # from tasks\n            \"eager_task_factory\",  # from tasks\n            \"_register_task\",  # from tasks\n            \"_unregister_task\",  # from tasks\n            \"_enter_task\",  # from tasks\n            \"_leave_task\",  # from tasks\n            \"TaskGroup\",  # from taskgroups\n            \"to_thread\",  # from threads\n            \"Timeout\",  # from timeouts\n            \"timeout\",  # from timeouts\n            \"timeout_at\",  # from timeouts\n            \"BaseTransport\",  # from transports\n            \"ReadTransport\",  # from transports\n            \"WriteTransport\",  # from transports\n            \"Transport\",  # from transports\n            \"DatagramTransport\",  # from transports\n            \"SubprocessTransport\",  # from transports\n            \"SelectorEventLoop\",  # from windows_events\n            \"ProactorEventLoop\",  # from windows_events\n            \"IocpProactor\",  # from windows_events\n            \"_DefaultEventLoopPolicy\",  # from windows_events\n            \"_WindowsSelectorEventLoopPolicy\",  # from windows_events\n            \"_WindowsProactorEventLoopPolicy\",  # from windows_events\n            \"EventLoop\",  # from windows_events\n        )\n    elif sys.version_info >= (3, 13):\n        __all__ = (\n            \"BaseEventLoop\",  # from base_events\n            \"Server\",  # from base_events\n            \"iscoroutinefunction\",  # from coroutines\n            \"iscoroutine\",  # from coroutines\n            \"AbstractEventLoopPolicy\",  # from events\n            \"AbstractEventLoop\",  # from events\n            \"AbstractServer\",  # from events\n            \"Handle\",  # from events\n            \"TimerHandle\",  # from events\n            \"get_event_loop_policy\",  # from events\n            \"set_event_loop_policy\",  # from events\n            \"get_event_loop\",  # from events\n            \"set_event_loop\",  # from events\n            \"new_event_loop\",  # from events\n            \"get_child_watcher\",  # from events\n            \"set_child_watcher\",  # from events\n            \"_set_running_loop\",  # from events\n            \"get_running_loop\",  # from events\n            \"_get_running_loop\",  # from events\n            \"BrokenBarrierError\",  # from exceptions\n            \"CancelledError\",  # from exceptions\n            \"InvalidStateError\",  # from exceptions\n            \"TimeoutError\",  # from exceptions\n            \"IncompleteReadError\",  # from exceptions\n            \"LimitOverrunError\",  # from exceptions\n            \"SendfileNotAvailableError\",  # from exceptions\n            \"Future\",  # from futures\n            \"wrap_future\",  # from futures\n            \"isfuture\",  # from futures\n            \"Lock\",  # from locks\n            \"Event\",  # from locks\n            \"Condition\",  # from locks\n            \"Semaphore\",  # from locks\n            \"BoundedSemaphore\",  # from locks\n            \"Barrier\",  # from locks\n            \"BaseProtocol\",  # from protocols\n            \"Protocol\",  # from protocols\n            \"DatagramProtocol\",  # from protocols\n            \"SubprocessProtocol\",  # from protocols\n            \"BufferedProtocol\",  # from protocols\n            \"Runner\",  # from runners\n            \"run\",  # from runners\n            \"Queue\",  # from queues\n            \"PriorityQueue\",  # from queues\n            \"LifoQueue\",  # from queues\n            \"QueueFull\",  # from queues\n            \"QueueEmpty\",  # from queues\n            \"QueueShutDown\",  # from queues\n            \"StreamReader\",  # from streams\n            \"StreamWriter\",  # from streams\n            \"StreamReaderProtocol\",  # from streams\n            \"open_connection\",  # from streams\n            \"start_server\",  # from streams\n            \"create_subprocess_exec\",  # from subprocess\n            \"create_subprocess_shell\",  # from subprocess\n            \"Task\",  # from tasks\n            \"create_task\",  # from tasks\n            \"FIRST_COMPLETED\",  # from tasks\n            \"FIRST_EXCEPTION\",  # from tasks\n            \"ALL_COMPLETED\",  # from tasks\n            \"wait\",  # from tasks\n            \"wait_for\",  # from tasks\n            \"as_completed\",  # from tasks\n            \"sleep\",  # from tasks\n            \"gather\",  # from tasks\n            \"shield\",  # from tasks\n            \"ensure_future\",  # from tasks\n            \"run_coroutine_threadsafe\",  # from tasks\n            \"current_task\",  # from tasks\n            \"all_tasks\",  # from tasks\n            \"create_eager_task_factory\",  # from tasks\n            \"eager_task_factory\",  # from tasks\n            \"_register_task\",  # from tasks\n            \"_unregister_task\",  # from tasks\n            \"_enter_task\",  # from tasks\n            \"_leave_task\",  # from tasks\n            \"TaskGroup\",  # from taskgroups\n            \"to_thread\",  # from threads\n            \"Timeout\",  # from timeouts\n            \"timeout\",  # from timeouts\n            \"timeout_at\",  # from timeouts\n            \"BaseTransport\",  # from transports\n            \"ReadTransport\",  # from transports\n            \"WriteTransport\",  # from transports\n            \"Transport\",  # from transports\n            \"DatagramTransport\",  # from transports\n            \"SubprocessTransport\",  # from transports\n            \"SelectorEventLoop\",  # from windows_events\n            \"ProactorEventLoop\",  # from windows_events\n            \"IocpProactor\",  # from windows_events\n            \"DefaultEventLoopPolicy\",  # from windows_events\n            \"WindowsSelectorEventLoopPolicy\",  # from windows_events\n            \"WindowsProactorEventLoopPolicy\",  # from windows_events\n            \"EventLoop\",  # from windows_events\n        )\n    elif sys.version_info >= (3, 12):\n        __all__ = (\n            \"BaseEventLoop\",  # from base_events\n            \"Server\",  # from base_events\n            \"iscoroutinefunction\",  # from coroutines\n            \"iscoroutine\",  # from coroutines\n            \"AbstractEventLoopPolicy\",  # from events\n            \"AbstractEventLoop\",  # from events\n            \"AbstractServer\",  # from events\n            \"Handle\",  # from events\n            \"TimerHandle\",  # from events\n            \"get_event_loop_policy\",  # from events\n            \"set_event_loop_policy\",  # from events\n            \"get_event_loop\",  # from events\n            \"set_event_loop\",  # from events\n            \"new_event_loop\",  # from events\n            \"get_child_watcher\",  # from events\n            \"set_child_watcher\",  # from events\n            \"_set_running_loop\",  # from events\n            \"get_running_loop\",  # from events\n            \"_get_running_loop\",  # from events\n            \"BrokenBarrierError\",  # from exceptions\n            \"CancelledError\",  # from exceptions\n            \"InvalidStateError\",  # from exceptions\n            \"TimeoutError\",  # from exceptions\n            \"IncompleteReadError\",  # from exceptions\n            \"LimitOverrunError\",  # from exceptions\n            \"SendfileNotAvailableError\",  # from exceptions\n            \"Future\",  # from futures\n            \"wrap_future\",  # from futures\n            \"isfuture\",  # from futures\n            \"Lock\",  # from locks\n            \"Event\",  # from locks\n            \"Condition\",  # from locks\n            \"Semaphore\",  # from locks\n            \"BoundedSemaphore\",  # from locks\n            \"Barrier\",  # from locks\n            \"BaseProtocol\",  # from protocols\n            \"Protocol\",  # from protocols\n            \"DatagramProtocol\",  # from protocols\n            \"SubprocessProtocol\",  # from protocols\n            \"BufferedProtocol\",  # from protocols\n            \"Runner\",  # from runners\n            \"run\",  # from runners\n            \"Queue\",  # from queues\n            \"PriorityQueue\",  # from queues\n            \"LifoQueue\",  # from queues\n            \"QueueFull\",  # from queues\n            \"QueueEmpty\",  # from queues\n            \"StreamReader\",  # from streams\n            \"StreamWriter\",  # from streams\n            \"StreamReaderProtocol\",  # from streams\n            \"open_connection\",  # from streams\n            \"start_server\",  # from streams\n            \"create_subprocess_exec\",  # from subprocess\n            \"create_subprocess_shell\",  # from subprocess\n            \"Task\",  # from tasks\n            \"create_task\",  # from tasks\n            \"FIRST_COMPLETED\",  # from tasks\n            \"FIRST_EXCEPTION\",  # from tasks\n            \"ALL_COMPLETED\",  # from tasks\n            \"wait\",  # from tasks\n            \"wait_for\",  # from tasks\n            \"as_completed\",  # from tasks\n            \"sleep\",  # from tasks\n            \"gather\",  # from tasks\n            \"shield\",  # from tasks\n            \"ensure_future\",  # from tasks\n            \"run_coroutine_threadsafe\",  # from tasks\n            \"current_task\",  # from tasks\n            \"all_tasks\",  # from tasks\n            \"create_eager_task_factory\",  # from tasks\n            \"eager_task_factory\",  # from tasks\n            \"_register_task\",  # from tasks\n            \"_unregister_task\",  # from tasks\n            \"_enter_task\",  # from tasks\n            \"_leave_task\",  # from tasks\n            \"TaskGroup\",  # from taskgroups\n            \"to_thread\",  # from threads\n            \"Timeout\",  # from timeouts\n            \"timeout\",  # from timeouts\n            \"timeout_at\",  # from timeouts\n            \"BaseTransport\",  # from transports\n            \"ReadTransport\",  # from transports\n            \"WriteTransport\",  # from transports\n            \"Transport\",  # from transports\n            \"DatagramTransport\",  # from transports\n            \"SubprocessTransport\",  # from transports\n            \"SelectorEventLoop\",  # from windows_events\n            \"ProactorEventLoop\",  # from windows_events\n            \"IocpProactor\",  # from windows_events\n            \"DefaultEventLoopPolicy\",  # from windows_events\n            \"WindowsSelectorEventLoopPolicy\",  # from windows_events\n            \"WindowsProactorEventLoopPolicy\",  # from windows_events\n        )\n    elif sys.version_info >= (3, 11):\n        __all__ = (\n            \"BaseEventLoop\",  # from base_events\n            \"Server\",  # from base_events\n            \"iscoroutinefunction\",  # from coroutines\n            \"iscoroutine\",  # from coroutines\n            \"AbstractEventLoopPolicy\",  # from events\n            \"AbstractEventLoop\",  # from events\n            \"AbstractServer\",  # from events\n            \"Handle\",  # from events\n            \"TimerHandle\",  # from events\n            \"get_event_loop_policy\",  # from events\n            \"set_event_loop_policy\",  # from events\n            \"get_event_loop\",  # from events\n            \"set_event_loop\",  # from events\n            \"new_event_loop\",  # from events\n            \"get_child_watcher\",  # from events\n            \"set_child_watcher\",  # from events\n            \"_set_running_loop\",  # from events\n            \"get_running_loop\",  # from events\n            \"_get_running_loop\",  # from events\n            \"BrokenBarrierError\",  # from exceptions\n            \"CancelledError\",  # from exceptions\n            \"InvalidStateError\",  # from exceptions\n            \"TimeoutError\",  # from exceptions\n            \"IncompleteReadError\",  # from exceptions\n            \"LimitOverrunError\",  # from exceptions\n            \"SendfileNotAvailableError\",  # from exceptions\n            \"Future\",  # from futures\n            \"wrap_future\",  # from futures\n            \"isfuture\",  # from futures\n            \"Lock\",  # from locks\n            \"Event\",  # from locks\n            \"Condition\",  # from locks\n            \"Semaphore\",  # from locks\n            \"BoundedSemaphore\",  # from locks\n            \"Barrier\",  # from locks\n            \"BaseProtocol\",  # from protocols\n            \"Protocol\",  # from protocols\n            \"DatagramProtocol\",  # from protocols\n            \"SubprocessProtocol\",  # from protocols\n            \"BufferedProtocol\",  # from protocols\n            \"Runner\",  # from runners\n            \"run\",  # from runners\n            \"Queue\",  # from queues\n            \"PriorityQueue\",  # from queues\n            \"LifoQueue\",  # from queues\n            \"QueueFull\",  # from queues\n            \"QueueEmpty\",  # from queues\n            \"StreamReader\",  # from streams\n            \"StreamWriter\",  # from streams\n            \"StreamReaderProtocol\",  # from streams\n            \"open_connection\",  # from streams\n            \"start_server\",  # from streams\n            \"create_subprocess_exec\",  # from subprocess\n            \"create_subprocess_shell\",  # from subprocess\n            \"Task\",  # from tasks\n            \"create_task\",  # from tasks\n            \"FIRST_COMPLETED\",  # from tasks\n            \"FIRST_EXCEPTION\",  # from tasks\n            \"ALL_COMPLETED\",  # from tasks\n            \"wait\",  # from tasks\n            \"wait_for\",  # from tasks\n            \"as_completed\",  # from tasks\n            \"sleep\",  # from tasks\n            \"gather\",  # from tasks\n            \"shield\",  # from tasks\n            \"ensure_future\",  # from tasks\n            \"run_coroutine_threadsafe\",  # from tasks\n            \"current_task\",  # from tasks\n            \"all_tasks\",  # from tasks\n            \"_register_task\",  # from tasks\n            \"_unregister_task\",  # from tasks\n            \"_enter_task\",  # from tasks\n            \"_leave_task\",  # from tasks\n            \"to_thread\",  # from threads\n            \"Timeout\",  # from timeouts\n            \"timeout\",  # from timeouts\n            \"timeout_at\",  # from timeouts\n            \"BaseTransport\",  # from transports\n            \"ReadTransport\",  # from transports\n            \"WriteTransport\",  # from transports\n            \"Transport\",  # from transports\n            \"DatagramTransport\",  # from transports\n            \"SubprocessTransport\",  # from transports\n            \"SelectorEventLoop\",  # from windows_events\n            \"ProactorEventLoop\",  # from windows_events\n            \"IocpProactor\",  # from windows_events\n            \"DefaultEventLoopPolicy\",  # from windows_events\n            \"WindowsSelectorEventLoopPolicy\",  # from windows_events\n            \"WindowsProactorEventLoopPolicy\",  # from windows_events\n        )\n    else:\n        __all__ = (\n            \"BaseEventLoop\",  # from base_events\n            \"Server\",  # from base_events\n            \"coroutine\",  # from coroutines\n            \"iscoroutinefunction\",  # from coroutines\n            \"iscoroutine\",  # from coroutines\n            \"AbstractEventLoopPolicy\",  # from events\n            \"AbstractEventLoop\",  # from events\n            \"AbstractServer\",  # from events\n            \"Handle\",  # from events\n            \"TimerHandle\",  # from events\n            \"get_event_loop_policy\",  # from events\n            \"set_event_loop_policy\",  # from events\n            \"get_event_loop\",  # from events\n            \"set_event_loop\",  # from events\n            \"new_event_loop\",  # from events\n            \"get_child_watcher\",  # from events\n            \"set_child_watcher\",  # from events\n            \"_set_running_loop\",  # from events\n            \"get_running_loop\",  # from events\n            \"_get_running_loop\",  # from events\n            \"CancelledError\",  # from exceptions\n            \"InvalidStateError\",  # from exceptions\n            \"TimeoutError\",  # from exceptions\n            \"IncompleteReadError\",  # from exceptions\n            \"LimitOverrunError\",  # from exceptions\n            \"SendfileNotAvailableError\",  # from exceptions\n            \"Future\",  # from futures\n            \"wrap_future\",  # from futures\n            \"isfuture\",  # from futures\n            \"Lock\",  # from locks\n            \"Event\",  # from locks\n            \"Condition\",  # from locks\n            \"Semaphore\",  # from locks\n            \"BoundedSemaphore\",  # from locks\n            \"BaseProtocol\",  # from protocols\n            \"Protocol\",  # from protocols\n            \"DatagramProtocol\",  # from protocols\n            \"SubprocessProtocol\",  # from protocols\n            \"BufferedProtocol\",  # from protocols\n            \"run\",  # from runners\n            \"Queue\",  # from queues\n            \"PriorityQueue\",  # from queues\n            \"LifoQueue\",  # from queues\n            \"QueueFull\",  # from queues\n            \"QueueEmpty\",  # from queues\n            \"StreamReader\",  # from streams\n            \"StreamWriter\",  # from streams\n            \"StreamReaderProtocol\",  # from streams\n            \"open_connection\",  # from streams\n            \"start_server\",  # from streams\n            \"create_subprocess_exec\",  # from subprocess\n            \"create_subprocess_shell\",  # from subprocess\n            \"Task\",  # from tasks\n            \"create_task\",  # from tasks\n            \"FIRST_COMPLETED\",  # from tasks\n            \"FIRST_EXCEPTION\",  # from tasks\n            \"ALL_COMPLETED\",  # from tasks\n            \"wait\",  # from tasks\n            \"wait_for\",  # from tasks\n            \"as_completed\",  # from tasks\n            \"sleep\",  # from tasks\n            \"gather\",  # from tasks\n            \"shield\",  # from tasks\n            \"ensure_future\",  # from tasks\n            \"run_coroutine_threadsafe\",  # from tasks\n            \"current_task\",  # from tasks\n            \"all_tasks\",  # from tasks\n            \"_register_task\",  # from tasks\n            \"_unregister_task\",  # from tasks\n            \"_enter_task\",  # from tasks\n            \"_leave_task\",  # from tasks\n            \"to_thread\",  # from threads\n            \"BaseTransport\",  # from transports\n            \"ReadTransport\",  # from transports\n            \"WriteTransport\",  # from transports\n            \"Transport\",  # from transports\n            \"DatagramTransport\",  # from transports\n            \"SubprocessTransport\",  # from transports\n            \"SelectorEventLoop\",  # from windows_events\n            \"ProactorEventLoop\",  # from windows_events\n            \"IocpProactor\",  # from windows_events\n            \"DefaultEventLoopPolicy\",  # from windows_events\n            \"WindowsSelectorEventLoopPolicy\",  # from windows_events\n            \"WindowsProactorEventLoopPolicy\",  # from windows_events\n        )\nelse:\n    if sys.version_info >= (3, 14):\n        __all__ = (\n            \"BaseEventLoop\",  # from base_events\n            \"Server\",  # from base_events\n            \"iscoroutinefunction\",  # from coroutines\n            \"iscoroutine\",  # from coroutines\n            \"AbstractEventLoop\",  # from events\n            \"AbstractServer\",  # from events\n            \"Handle\",  # from events\n            \"TimerHandle\",  # from events\n            \"get_event_loop_policy\",  # from events\n            \"set_event_loop_policy\",  # from events\n            \"get_event_loop\",  # from events\n            \"set_event_loop\",  # from events\n            \"new_event_loop\",  # from events\n            \"_set_running_loop\",  # from events\n            \"get_running_loop\",  # from events\n            \"_get_running_loop\",  # from events\n            \"BrokenBarrierError\",  # from exceptions\n            \"CancelledError\",  # from exceptions\n            \"InvalidStateError\",  # from exceptions\n            \"TimeoutError\",  # from exceptions\n            \"IncompleteReadError\",  # from exceptions\n            \"LimitOverrunError\",  # from exceptions\n            \"SendfileNotAvailableError\",  # from exceptions\n            \"Future\",  # from futures\n            \"wrap_future\",  # from futures\n            \"isfuture\",  # from futures\n            \"future_discard_from_awaited_by\",  # from futures\n            \"future_add_to_awaited_by\",  # from futures\n            \"capture_call_graph\",  # from graph\n            \"format_call_graph\",  # from graph\n            \"print_call_graph\",  # from graph\n            \"FrameCallGraphEntry\",  # from graph\n            \"FutureCallGraph\",  # from graph\n            \"Lock\",  # from locks\n            \"Event\",  # from locks\n            \"Condition\",  # from locks\n            \"Semaphore\",  # from locks\n            \"BoundedSemaphore\",  # from locks\n            \"Barrier\",  # from locks\n            \"BaseProtocol\",  # from protocols\n            \"Protocol\",  # from protocols\n            \"DatagramProtocol\",  # from protocols\n            \"SubprocessProtocol\",  # from protocols\n            \"BufferedProtocol\",  # from protocols\n            \"Runner\",  # from runners\n            \"run\",  # from runners\n            \"Queue\",  # from queues\n            \"PriorityQueue\",  # from queues\n            \"LifoQueue\",  # from queues\n            \"QueueFull\",  # from queues\n            \"QueueEmpty\",  # from queues\n            \"QueueShutDown\",  # from queues\n            \"StreamReader\",  # from streams\n            \"StreamWriter\",  # from streams\n            \"StreamReaderProtocol\",  # from streams\n            \"open_connection\",  # from streams\n            \"start_server\",  # from streams\n            \"open_unix_connection\",  # from streams\n            \"start_unix_server\",  # from streams\n            \"create_subprocess_exec\",  # from subprocess\n            \"create_subprocess_shell\",  # from subprocess\n            \"Task\",  # from tasks\n            \"create_task\",  # from tasks\n            \"FIRST_COMPLETED\",  # from tasks\n            \"FIRST_EXCEPTION\",  # from tasks\n            \"ALL_COMPLETED\",  # from tasks\n            \"wait\",  # from tasks\n            \"wait_for\",  # from tasks\n            \"as_completed\",  # from tasks\n            \"sleep\",  # from tasks\n            \"gather\",  # from tasks\n            \"shield\",  # from tasks\n            \"ensure_future\",  # from tasks\n            \"run_coroutine_threadsafe\",  # from tasks\n            \"current_task\",  # from tasks\n            \"all_tasks\",  # from tasks\n            \"create_eager_task_factory\",  # from tasks\n            \"eager_task_factory\",  # from tasks\n            \"_register_task\",  # from tasks\n            \"_unregister_task\",  # from tasks\n            \"_enter_task\",  # from tasks\n            \"_leave_task\",  # from tasks\n            \"TaskGroup\",  # from taskgroups\n            \"to_thread\",  # from threads\n            \"Timeout\",  # from timeouts\n            \"timeout\",  # from timeouts\n            \"timeout_at\",  # from timeouts\n            \"BaseTransport\",  # from transports\n            \"ReadTransport\",  # from transports\n            \"WriteTransport\",  # from transports\n            \"Transport\",  # from transports\n            \"DatagramTransport\",  # from transports\n            \"SubprocessTransport\",  # from transports\n            \"SelectorEventLoop\",  # from unix_events\n            \"EventLoop\",  # from unix_events\n        )\n    elif sys.version_info >= (3, 13):\n        __all__ = (\n            \"BaseEventLoop\",  # from base_events\n            \"Server\",  # from base_events\n            \"iscoroutinefunction\",  # from coroutines\n            \"iscoroutine\",  # from coroutines\n            \"AbstractEventLoopPolicy\",  # from events\n            \"AbstractEventLoop\",  # from events\n            \"AbstractServer\",  # from events\n            \"Handle\",  # from events\n            \"TimerHandle\",  # from events\n            \"get_event_loop_policy\",  # from events\n            \"set_event_loop_policy\",  # from events\n            \"get_event_loop\",  # from events\n            \"set_event_loop\",  # from events\n            \"new_event_loop\",  # from events\n            \"get_child_watcher\",  # from events\n            \"set_child_watcher\",  # from events\n            \"_set_running_loop\",  # from events\n            \"get_running_loop\",  # from events\n            \"_get_running_loop\",  # from events\n            \"BrokenBarrierError\",  # from exceptions\n            \"CancelledError\",  # from exceptions\n            \"InvalidStateError\",  # from exceptions\n            \"TimeoutError\",  # from exceptions\n            \"IncompleteReadError\",  # from exceptions\n            \"LimitOverrunError\",  # from exceptions\n            \"SendfileNotAvailableError\",  # from exceptions\n            \"Future\",  # from futures\n            \"wrap_future\",  # from futures\n            \"isfuture\",  # from futures\n            \"Lock\",  # from locks\n            \"Event\",  # from locks\n            \"Condition\",  # from locks\n            \"Semaphore\",  # from locks\n            \"BoundedSemaphore\",  # from locks\n            \"Barrier\",  # from locks\n            \"BaseProtocol\",  # from protocols\n            \"Protocol\",  # from protocols\n            \"DatagramProtocol\",  # from protocols\n            \"SubprocessProtocol\",  # from protocols\n            \"BufferedProtocol\",  # from protocols\n            \"Runner\",  # from runners\n            \"run\",  # from runners\n            \"Queue\",  # from queues\n            \"PriorityQueue\",  # from queues\n            \"LifoQueue\",  # from queues\n            \"QueueFull\",  # from queues\n            \"QueueEmpty\",  # from queues\n            \"QueueShutDown\",  # from queues\n            \"StreamReader\",  # from streams\n            \"StreamWriter\",  # from streams\n            \"StreamReaderProtocol\",  # from streams\n            \"open_connection\",  # from streams\n            \"start_server\",  # from streams\n            \"open_unix_connection\",  # from streams\n            \"start_unix_server\",  # from streams\n            \"create_subprocess_exec\",  # from subprocess\n            \"create_subprocess_shell\",  # from subprocess\n            \"Task\",  # from tasks\n            \"create_task\",  # from tasks\n            \"FIRST_COMPLETED\",  # from tasks\n            \"FIRST_EXCEPTION\",  # from tasks\n            \"ALL_COMPLETED\",  # from tasks\n            \"wait\",  # from tasks\n            \"wait_for\",  # from tasks\n            \"as_completed\",  # from tasks\n            \"sleep\",  # from tasks\n            \"gather\",  # from tasks\n            \"shield\",  # from tasks\n            \"ensure_future\",  # from tasks\n            \"run_coroutine_threadsafe\",  # from tasks\n            \"current_task\",  # from tasks\n            \"all_tasks\",  # from tasks\n            \"create_eager_task_factory\",  # from tasks\n            \"eager_task_factory\",  # from tasks\n            \"_register_task\",  # from tasks\n            \"_unregister_task\",  # from tasks\n            \"_enter_task\",  # from tasks\n            \"_leave_task\",  # from tasks\n            \"TaskGroup\",  # from taskgroups\n            \"to_thread\",  # from threads\n            \"Timeout\",  # from timeouts\n            \"timeout\",  # from timeouts\n            \"timeout_at\",  # from timeouts\n            \"BaseTransport\",  # from transports\n            \"ReadTransport\",  # from transports\n            \"WriteTransport\",  # from transports\n            \"Transport\",  # from transports\n            \"DatagramTransport\",  # from transports\n            \"SubprocessTransport\",  # from transports\n            \"SelectorEventLoop\",  # from unix_events\n            \"AbstractChildWatcher\",  # from unix_events\n            \"SafeChildWatcher\",  # from unix_events\n            \"FastChildWatcher\",  # from unix_events\n            \"PidfdChildWatcher\",  # from unix_events\n            \"MultiLoopChildWatcher\",  # from unix_events\n            \"ThreadedChildWatcher\",  # from unix_events\n            \"DefaultEventLoopPolicy\",  # from unix_events\n            \"EventLoop\",  # from unix_events\n        )\n    elif sys.version_info >= (3, 12):\n        __all__ = (\n            \"BaseEventLoop\",  # from base_events\n            \"Server\",  # from base_events\n            \"iscoroutinefunction\",  # from coroutines\n            \"iscoroutine\",  # from coroutines\n            \"AbstractEventLoopPolicy\",  # from events\n            \"AbstractEventLoop\",  # from events\n            \"AbstractServer\",  # from events\n            \"Handle\",  # from events\n            \"TimerHandle\",  # from events\n            \"get_event_loop_policy\",  # from events\n            \"set_event_loop_policy\",  # from events\n            \"get_event_loop\",  # from events\n            \"set_event_loop\",  # from events\n            \"new_event_loop\",  # from events\n            \"get_child_watcher\",  # from events\n            \"set_child_watcher\",  # from events\n            \"_set_running_loop\",  # from events\n            \"get_running_loop\",  # from events\n            \"_get_running_loop\",  # from events\n            \"BrokenBarrierError\",  # from exceptions\n            \"CancelledError\",  # from exceptions\n            \"InvalidStateError\",  # from exceptions\n            \"TimeoutError\",  # from exceptions\n            \"IncompleteReadError\",  # from exceptions\n            \"LimitOverrunError\",  # from exceptions\n            \"SendfileNotAvailableError\",  # from exceptions\n            \"Future\",  # from futures\n            \"wrap_future\",  # from futures\n            \"isfuture\",  # from futures\n            \"Lock\",  # from locks\n            \"Event\",  # from locks\n            \"Condition\",  # from locks\n            \"Semaphore\",  # from locks\n            \"BoundedSemaphore\",  # from locks\n            \"Barrier\",  # from locks\n            \"BaseProtocol\",  # from protocols\n            \"Protocol\",  # from protocols\n            \"DatagramProtocol\",  # from protocols\n            \"SubprocessProtocol\",  # from protocols\n            \"BufferedProtocol\",  # from protocols\n            \"Runner\",  # from runners\n            \"run\",  # from runners\n            \"Queue\",  # from queues\n            \"PriorityQueue\",  # from queues\n            \"LifoQueue\",  # from queues\n            \"QueueFull\",  # from queues\n            \"QueueEmpty\",  # from queues\n            \"StreamReader\",  # from streams\n            \"StreamWriter\",  # from streams\n            \"StreamReaderProtocol\",  # from streams\n            \"open_connection\",  # from streams\n            \"start_server\",  # from streams\n            \"open_unix_connection\",  # from streams\n            \"start_unix_server\",  # from streams\n            \"create_subprocess_exec\",  # from subprocess\n            \"create_subprocess_shell\",  # from subprocess\n            \"Task\",  # from tasks\n            \"create_task\",  # from tasks\n            \"FIRST_COMPLETED\",  # from tasks\n            \"FIRST_EXCEPTION\",  # from tasks\n            \"ALL_COMPLETED\",  # from tasks\n            \"wait\",  # from tasks\n            \"wait_for\",  # from tasks\n            \"as_completed\",  # from tasks\n            \"sleep\",  # from tasks\n            \"gather\",  # from tasks\n            \"shield\",  # from tasks\n            \"ensure_future\",  # from tasks\n            \"run_coroutine_threadsafe\",  # from tasks\n            \"current_task\",  # from tasks\n            \"all_tasks\",  # from tasks\n            \"create_eager_task_factory\",  # from tasks\n            \"eager_task_factory\",  # from tasks\n            \"_register_task\",  # from tasks\n            \"_unregister_task\",  # from tasks\n            \"_enter_task\",  # from tasks\n            \"_leave_task\",  # from tasks\n            \"TaskGroup\",  # from taskgroups\n            \"to_thread\",  # from threads\n            \"Timeout\",  # from timeouts\n            \"timeout\",  # from timeouts\n            \"timeout_at\",  # from timeouts\n            \"BaseTransport\",  # from transports\n            \"ReadTransport\",  # from transports\n            \"WriteTransport\",  # from transports\n            \"Transport\",  # from transports\n            \"DatagramTransport\",  # from transports\n            \"SubprocessTransport\",  # from transports\n            \"SelectorEventLoop\",  # from unix_events\n            \"AbstractChildWatcher\",  # from unix_events\n            \"SafeChildWatcher\",  # from unix_events\n            \"FastChildWatcher\",  # from unix_events\n            \"PidfdChildWatcher\",  # from unix_events\n            \"MultiLoopChildWatcher\",  # from unix_events\n            \"ThreadedChildWatcher\",  # from unix_events\n            \"DefaultEventLoopPolicy\",  # from unix_events\n        )\n    elif sys.version_info >= (3, 11):\n        __all__ = (\n            \"BaseEventLoop\",  # from base_events\n            \"Server\",  # from base_events\n            \"iscoroutinefunction\",  # from coroutines\n            \"iscoroutine\",  # from coroutines\n            \"AbstractEventLoopPolicy\",  # from events\n            \"AbstractEventLoop\",  # from events\n            \"AbstractServer\",  # from events\n            \"Handle\",  # from events\n            \"TimerHandle\",  # from events\n            \"get_event_loop_policy\",  # from events\n            \"set_event_loop_policy\",  # from events\n            \"get_event_loop\",  # from events\n            \"set_event_loop\",  # from events\n            \"new_event_loop\",  # from events\n            \"get_child_watcher\",  # from events\n            \"set_child_watcher\",  # from events\n            \"_set_running_loop\",  # from events\n            \"get_running_loop\",  # from events\n            \"_get_running_loop\",  # from events\n            \"BrokenBarrierError\",  # from exceptions\n            \"CancelledError\",  # from exceptions\n            \"InvalidStateError\",  # from exceptions\n            \"TimeoutError\",  # from exceptions\n            \"IncompleteReadError\",  # from exceptions\n            \"LimitOverrunError\",  # from exceptions\n            \"SendfileNotAvailableError\",  # from exceptions\n            \"Future\",  # from futures\n            \"wrap_future\",  # from futures\n            \"isfuture\",  # from futures\n            \"Lock\",  # from locks\n            \"Event\",  # from locks\n            \"Condition\",  # from locks\n            \"Semaphore\",  # from locks\n            \"BoundedSemaphore\",  # from locks\n            \"Barrier\",  # from locks\n            \"BaseProtocol\",  # from protocols\n            \"Protocol\",  # from protocols\n            \"DatagramProtocol\",  # from protocols\n            \"SubprocessProtocol\",  # from protocols\n            \"BufferedProtocol\",  # from protocols\n            \"Runner\",  # from runners\n            \"run\",  # from runners\n            \"Queue\",  # from queues\n            \"PriorityQueue\",  # from queues\n            \"LifoQueue\",  # from queues\n            \"QueueFull\",  # from queues\n            \"QueueEmpty\",  # from queues\n            \"StreamReader\",  # from streams\n            \"StreamWriter\",  # from streams\n            \"StreamReaderProtocol\",  # from streams\n            \"open_connection\",  # from streams\n            \"start_server\",  # from streams\n            \"open_unix_connection\",  # from streams\n            \"start_unix_server\",  # from streams\n            \"create_subprocess_exec\",  # from subprocess\n            \"create_subprocess_shell\",  # from subprocess\n            \"Task\",  # from tasks\n            \"create_task\",  # from tasks\n            \"FIRST_COMPLETED\",  # from tasks\n            \"FIRST_EXCEPTION\",  # from tasks\n            \"ALL_COMPLETED\",  # from tasks\n            \"wait\",  # from tasks\n            \"wait_for\",  # from tasks\n            \"as_completed\",  # from tasks\n            \"sleep\",  # from tasks\n            \"gather\",  # from tasks\n            \"shield\",  # from tasks\n            \"ensure_future\",  # from tasks\n            \"run_coroutine_threadsafe\",  # from tasks\n            \"current_task\",  # from tasks\n            \"all_tasks\",  # from tasks\n            \"_register_task\",  # from tasks\n            \"_unregister_task\",  # from tasks\n            \"_enter_task\",  # from tasks\n            \"_leave_task\",  # from tasks\n            \"to_thread\",  # from threads\n            \"Timeout\",  # from timeouts\n            \"timeout\",  # from timeouts\n            \"timeout_at\",  # from timeouts\n            \"BaseTransport\",  # from transports\n            \"ReadTransport\",  # from transports\n            \"WriteTransport\",  # from transports\n            \"Transport\",  # from transports\n            \"DatagramTransport\",  # from transports\n            \"SubprocessTransport\",  # from transports\n            \"SelectorEventLoop\",  # from unix_events\n            \"AbstractChildWatcher\",  # from unix_events\n            \"SafeChildWatcher\",  # from unix_events\n            \"FastChildWatcher\",  # from unix_events\n            \"PidfdChildWatcher\",  # from unix_events\n            \"MultiLoopChildWatcher\",  # from unix_events\n            \"ThreadedChildWatcher\",  # from unix_events\n            \"DefaultEventLoopPolicy\",  # from unix_events\n        )\n    else:\n        __all__ = (\n            \"BaseEventLoop\",  # from base_events\n            \"Server\",  # from base_events\n            \"coroutine\",  # from coroutines\n            \"iscoroutinefunction\",  # from coroutines\n            \"iscoroutine\",  # from coroutines\n            \"AbstractEventLoopPolicy\",  # from events\n            \"AbstractEventLoop\",  # from events\n            \"AbstractServer\",  # from events\n            \"Handle\",  # from events\n            \"TimerHandle\",  # from events\n            \"get_event_loop_policy\",  # from events\n            \"set_event_loop_policy\",  # from events\n            \"get_event_loop\",  # from events\n            \"set_event_loop\",  # from events\n            \"new_event_loop\",  # from events\n            \"get_child_watcher\",  # from events\n            \"set_child_watcher\",  # from events\n            \"_set_running_loop\",  # from events\n            \"get_running_loop\",  # from events\n            \"_get_running_loop\",  # from events\n            \"CancelledError\",  # from exceptions\n            \"InvalidStateError\",  # from exceptions\n            \"TimeoutError\",  # from exceptions\n            \"IncompleteReadError\",  # from exceptions\n            \"LimitOverrunError\",  # from exceptions\n            \"SendfileNotAvailableError\",  # from exceptions\n            \"Future\",  # from futures\n            \"wrap_future\",  # from futures\n            \"isfuture\",  # from futures\n            \"Lock\",  # from locks\n            \"Event\",  # from locks\n            \"Condition\",  # from locks\n            \"Semaphore\",  # from locks\n            \"BoundedSemaphore\",  # from locks\n            \"BaseProtocol\",  # from protocols\n            \"Protocol\",  # from protocols\n            \"DatagramProtocol\",  # from protocols\n            \"SubprocessProtocol\",  # from protocols\n            \"BufferedProtocol\",  # from protocols\n            \"run\",  # from runners\n            \"Queue\",  # from queues\n            \"PriorityQueue\",  # from queues\n            \"LifoQueue\",  # from queues\n            \"QueueFull\",  # from queues\n            \"QueueEmpty\",  # from queues\n            \"StreamReader\",  # from streams\n            \"StreamWriter\",  # from streams\n            \"StreamReaderProtocol\",  # from streams\n            \"open_connection\",  # from streams\n            \"start_server\",  # from streams\n            \"open_unix_connection\",  # from streams\n            \"start_unix_server\",  # from streams\n            \"create_subprocess_exec\",  # from subprocess\n            \"create_subprocess_shell\",  # from subprocess\n            \"Task\",  # from tasks\n            \"create_task\",  # from tasks\n            \"FIRST_COMPLETED\",  # from tasks\n            \"FIRST_EXCEPTION\",  # from tasks\n            \"ALL_COMPLETED\",  # from tasks\n            \"wait\",  # from tasks\n            \"wait_for\",  # from tasks\n            \"as_completed\",  # from tasks\n            \"sleep\",  # from tasks\n            \"gather\",  # from tasks\n            \"shield\",  # from tasks\n            \"ensure_future\",  # from tasks\n            \"run_coroutine_threadsafe\",  # from tasks\n            \"current_task\",  # from tasks\n            \"all_tasks\",  # from tasks\n            \"_register_task\",  # from tasks\n            \"_unregister_task\",  # from tasks\n            \"_enter_task\",  # from tasks\n            \"_leave_task\",  # from tasks\n            \"to_thread\",  # from threads\n            \"BaseTransport\",  # from transports\n            \"ReadTransport\",  # from transports\n            \"WriteTransport\",  # from transports\n            \"Transport\",  # from transports\n            \"DatagramTransport\",  # from transports\n            \"SubprocessTransport\",  # from transports\n            \"SelectorEventLoop\",  # from unix_events\n            \"AbstractChildWatcher\",  # from unix_events\n            \"SafeChildWatcher\",  # from unix_events\n            \"FastChildWatcher\",  # from unix_events\n            \"PidfdChildWatcher\",  # from unix_events\n            \"MultiLoopChildWatcher\",  # from unix_events\n            \"ThreadedChildWatcher\",  # from unix_events\n            \"DefaultEventLoopPolicy\",  # from unix_events\n        )\n\n_T_co = TypeVar(\"_T_co\", covariant=True)\n\n# Aliases imported by multiple submodules in typeshed\nif sys.version_info >= (3, 12):\n    _AwaitableLike: TypeAlias = Awaitable[_T_co]  # noqa: Y047\n    _CoroutineLike: TypeAlias = Coroutine[Any, Any, _T_co]  # noqa: Y047\nelse:\n    _AwaitableLike: TypeAlias = Generator[Any, None, _T_co] | Awaitable[_T_co]\n    _CoroutineLike: TypeAlias = Generator[Any, None, _T_co] | Coroutine[Any, Any, _T_co]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/base_events.pyi",
    "content": "import ssl\nimport sys\nfrom _typeshed import FileDescriptorLike, ReadableBuffer, WriteableBuffer\nfrom asyncio import _AwaitableLike, _CoroutineLike\nfrom asyncio.events import AbstractEventLoop, AbstractServer, Handle, TimerHandle, _TaskFactory\nfrom asyncio.futures import Future\nfrom asyncio.protocols import BaseProtocol\nfrom asyncio.tasks import Task\nfrom asyncio.transports import BaseTransport, DatagramTransport, ReadTransport, SubprocessTransport, Transport, WriteTransport\nfrom collections.abc import Callable, Iterable, Sequence\nfrom concurrent.futures import Executor, ThreadPoolExecutor\nfrom contextvars import Context\nfrom socket import AddressFamily, AddressInfo, SocketKind, _Address, _RetAddress, socket\nfrom typing import IO, Any, Literal, TypeVar, overload\nfrom typing_extensions import TypeAlias, TypeVarTuple, Unpack\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\n__all__ = (\"BaseEventLoop\", \"Server\")\n\n_T = TypeVar(\"_T\")\n_Ts = TypeVarTuple(\"_Ts\")\n_ProtocolT = TypeVar(\"_ProtocolT\", bound=BaseProtocol)\n_Context: TypeAlias = dict[str, Any]\n_ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], object]\n_ProtocolFactory: TypeAlias = Callable[[], BaseProtocol]\n_SSLContext: TypeAlias = bool | None | ssl.SSLContext\n\nclass Server(AbstractServer):\n    if sys.version_info >= (3, 11):\n        def __init__(\n            self,\n            loop: AbstractEventLoop,\n            sockets: Iterable[socket],\n            protocol_factory: _ProtocolFactory,\n            ssl_context: _SSLContext,\n            backlog: int,\n            ssl_handshake_timeout: float | None,\n            ssl_shutdown_timeout: float | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            loop: AbstractEventLoop,\n            sockets: Iterable[socket],\n            protocol_factory: _ProtocolFactory,\n            ssl_context: _SSLContext,\n            backlog: int,\n            ssl_handshake_timeout: float | None,\n        ) -> None: ...\n\n    if sys.version_info >= (3, 13):\n        def close_clients(self) -> None: ...\n        def abort_clients(self) -> None: ...\n\n    def get_loop(self) -> AbstractEventLoop: ...\n    def is_serving(self) -> bool: ...\n    async def start_serving(self) -> None: ...\n    async def serve_forever(self) -> None: ...\n    @property\n    def sockets(self) -> tuple[socket, ...]: ...\n    def close(self) -> None: ...\n    async def wait_closed(self) -> None: ...\n\nclass BaseEventLoop(AbstractEventLoop):\n    def run_forever(self) -> None: ...\n    def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: ...\n    def stop(self) -> None: ...\n    def is_running(self) -> bool: ...\n    def is_closed(self) -> bool: ...\n    def close(self) -> None: ...\n    async def shutdown_asyncgens(self) -> None: ...\n    # Methods scheduling callbacks.  All these return Handles.\n    def call_soon(\n        self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None\n    ) -> Handle: ...\n    def call_later(\n        self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None\n    ) -> TimerHandle: ...\n    def call_at(\n        self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None\n    ) -> TimerHandle: ...\n    def time(self) -> float: ...\n    # Future methods\n    def create_future(self) -> Future[Any]: ...\n    # Tasks methods\n    if sys.version_info >= (3, 14):\n        def create_task(\n            self,\n            coro: _CoroutineLike[_T],\n            *,\n            name: object = None,\n            context: Context | None = None,\n            eager_start: bool | None = None,\n        ) -> Task[_T]: ...\n    elif sys.version_info >= (3, 11):\n        def create_task(self, coro: _CoroutineLike[_T], *, name: object = None, context: Context | None = None) -> Task[_T]: ...\n    else:\n        def create_task(self, coro: _CoroutineLike[_T], *, name: object = None) -> Task[_T]: ...\n\n    def set_task_factory(self, factory: _TaskFactory | None) -> None: ...\n    def get_task_factory(self) -> _TaskFactory | None: ...\n    # Methods for interacting with threads\n    def call_soon_threadsafe(\n        self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None\n    ) -> Handle: ...\n    def run_in_executor(self, executor: Executor | None, func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts]) -> Future[_T]: ...\n    def set_default_executor(self, executor: ThreadPoolExecutor) -> None: ...  # type: ignore[override]\n    # Network I/O methods returning Futures.\n    async def getaddrinfo(\n        self,\n        host: bytes | str | None,\n        port: bytes | str | int | None,\n        *,\n        family: int = 0,\n        type: int = 0,\n        proto: int = 0,\n        flags: int = 0,\n    ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ...\n    async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = 0) -> tuple[str, str]: ...\n    if sys.version_info >= (3, 12):\n        @overload\n        async def create_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            host: str = ...,\n            port: int = ...,\n            *,\n            ssl: _SSLContext = None,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            sock: None = None,\n            local_addr: tuple[str, int] | None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            happy_eyeballs_delay: float | None = None,\n            interleave: int | None = None,\n            all_errors: bool = False,\n        ) -> tuple[Transport, _ProtocolT]: ...\n        @overload\n        async def create_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            host: None = None,\n            port: None = None,\n            *,\n            ssl: _SSLContext = None,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            sock: socket,\n            local_addr: None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            happy_eyeballs_delay: float | None = None,\n            interleave: int | None = None,\n            all_errors: bool = False,\n        ) -> tuple[Transport, _ProtocolT]: ...\n    elif sys.version_info >= (3, 11):\n        @overload\n        async def create_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            host: str = ...,\n            port: int = ...,\n            *,\n            ssl: _SSLContext = None,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            sock: None = None,\n            local_addr: tuple[str, int] | None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            happy_eyeballs_delay: float | None = None,\n            interleave: int | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n        @overload\n        async def create_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            host: None = None,\n            port: None = None,\n            *,\n            ssl: _SSLContext = None,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            sock: socket,\n            local_addr: None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            happy_eyeballs_delay: float | None = None,\n            interleave: int | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n    else:\n        @overload\n        async def create_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            host: str = ...,\n            port: int = ...,\n            *,\n            ssl: _SSLContext = None,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            sock: None = None,\n            local_addr: tuple[str, int] | None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            happy_eyeballs_delay: float | None = None,\n            interleave: int | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n        @overload\n        async def create_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            host: None = None,\n            port: None = None,\n            *,\n            ssl: _SSLContext = None,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            sock: socket,\n            local_addr: None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            happy_eyeballs_delay: float | None = None,\n            interleave: int | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n\n    if sys.version_info >= (3, 13):\n        # 3.13 added `keep_alive`.\n        @overload\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: str | Sequence[str] | None = None,\n            port: int = ...,\n            *,\n            family: int = 0,\n            flags: int = 1,\n            sock: None = None,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            keep_alive: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n        @overload\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: None = None,\n            port: None = None,\n            *,\n            family: int = 0,\n            flags: int = 1,\n            sock: socket = ...,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            keep_alive: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n    elif sys.version_info >= (3, 11):\n        @overload\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: str | Sequence[str] | None = None,\n            port: int = ...,\n            *,\n            family: int = AddressFamily.AF_UNSPEC,\n            flags: int = AddressInfo.AI_PASSIVE,\n            sock: None = None,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n        @overload\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: None = None,\n            port: None = None,\n            *,\n            family: int = AddressFamily.AF_UNSPEC,\n            flags: int = AddressInfo.AI_PASSIVE,\n            sock: socket = ...,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n    else:\n        @overload\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: str | Sequence[str] | None = None,\n            port: int = ...,\n            *,\n            family: int = AddressFamily.AF_UNSPEC,\n            flags: int = AddressInfo.AI_PASSIVE,\n            sock: None = None,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n        @overload\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: None = None,\n            port: None = None,\n            *,\n            family: int = AddressFamily.AF_UNSPEC,\n            flags: int = AddressInfo.AI_PASSIVE,\n            sock: socket = ...,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n\n    if sys.version_info >= (3, 11):\n        async def start_tls(\n            self,\n            transport: BaseTransport,\n            protocol: BaseProtocol,\n            sslcontext: ssl.SSLContext,\n            *,\n            server_side: bool = False,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n        ) -> Transport | None: ...\n        async def connect_accepted_socket(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            sock: socket,\n            *,\n            ssl: _SSLContext = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n    else:\n        async def start_tls(\n            self,\n            transport: BaseTransport,\n            protocol: BaseProtocol,\n            sslcontext: ssl.SSLContext,\n            *,\n            server_side: bool = False,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n        ) -> Transport | None: ...\n        async def connect_accepted_socket(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            sock: socket,\n            *,\n            ssl: _SSLContext = None,\n            ssl_handshake_timeout: float | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n\n    async def sock_sendfile(\n        self, sock: socket, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool | None = True\n    ) -> int: ...\n    async def sendfile(\n        self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True\n    ) -> int: ...\n    if sys.version_info >= (3, 11):\n        async def create_datagram_endpoint(  # type: ignore[override]\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            local_addr: tuple[str, int] | str | None = None,\n            remote_addr: tuple[str, int] | str | None = None,\n            *,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            reuse_port: bool | None = None,\n            allow_broadcast: bool | None = None,\n            sock: socket | None = None,\n        ) -> tuple[DatagramTransport, _ProtocolT]: ...\n    else:\n        async def create_datagram_endpoint(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            local_addr: tuple[str, int] | str | None = None,\n            remote_addr: tuple[str, int] | str | None = None,\n            *,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            reuse_address: bool | None = ...,\n            reuse_port: bool | None = None,\n            allow_broadcast: bool | None = None,\n            sock: socket | None = None,\n        ) -> tuple[DatagramTransport, _ProtocolT]: ...\n    # Pipes and subprocesses.\n    async def connect_read_pipe(\n        self, protocol_factory: Callable[[], _ProtocolT], pipe: Any\n    ) -> tuple[ReadTransport, _ProtocolT]: ...\n    async def connect_write_pipe(\n        self, protocol_factory: Callable[[], _ProtocolT], pipe: Any\n    ) -> tuple[WriteTransport, _ProtocolT]: ...\n    async def subprocess_shell(\n        self,\n        protocol_factory: Callable[[], _ProtocolT],\n        cmd: bytes | str,\n        *,\n        stdin: int | IO[Any] | None = -1,\n        stdout: int | IO[Any] | None = -1,\n        stderr: int | IO[Any] | None = -1,\n        universal_newlines: Literal[False] = False,\n        shell: Literal[True] = True,\n        bufsize: Literal[0] = 0,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        **kwargs: Any,\n    ) -> tuple[SubprocessTransport, _ProtocolT]: ...\n    async def subprocess_exec(\n        self,\n        protocol_factory: Callable[[], _ProtocolT],\n        program: Any,\n        *args: Any,\n        stdin: int | IO[Any] | None = -1,\n        stdout: int | IO[Any] | None = -1,\n        stderr: int | IO[Any] | None = -1,\n        universal_newlines: Literal[False] = False,\n        shell: Literal[False] = False,\n        bufsize: Literal[0] = 0,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        **kwargs: Any,\n    ) -> tuple[SubprocessTransport, _ProtocolT]: ...\n    def add_reader(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ...\n    def remove_reader(self, fd: FileDescriptorLike) -> bool: ...\n    def add_writer(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ...\n    def remove_writer(self, fd: FileDescriptorLike) -> bool: ...\n    # The sock_* methods (and probably some others) are not actually implemented on\n    # BaseEventLoop, only on subclasses. We list them here for now for convenience.\n    async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ...\n    async def sock_recv_into(self, sock: socket, buf: WriteableBuffer) -> int: ...\n    async def sock_sendall(self, sock: socket, data: ReadableBuffer) -> None: ...\n    async def sock_connect(self, sock: socket, address: _Address) -> None: ...\n    async def sock_accept(self, sock: socket) -> tuple[socket, _RetAddress]: ...\n    if sys.version_info >= (3, 11):\n        async def sock_recvfrom(self, sock: socket, bufsize: int) -> tuple[bytes, _RetAddress]: ...\n        async def sock_recvfrom_into(self, sock: socket, buf: WriteableBuffer, nbytes: int = 0) -> tuple[int, _RetAddress]: ...\n        async def sock_sendto(self, sock: socket, data: ReadableBuffer, address: _Address) -> int: ...\n    # Signal handling.\n    def add_signal_handler(self, sig: int, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ...\n    def remove_signal_handler(self, sig: int) -> bool: ...\n    # Error handlers.\n    def set_exception_handler(self, handler: _ExceptionHandler | None) -> None: ...\n    def get_exception_handler(self) -> _ExceptionHandler | None: ...\n    def default_exception_handler(self, context: _Context) -> None: ...\n    def call_exception_handler(self, context: _Context) -> None: ...\n    # Debug flag management.\n    def get_debug(self) -> bool: ...\n    def set_debug(self, enabled: bool) -> None: ...\n    if sys.version_info >= (3, 12):\n        async def shutdown_default_executor(self, timeout: float | None = None) -> None: ...\n    else:\n        async def shutdown_default_executor(self) -> None: ...\n\n    def __del__(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/base_futures.pyi",
    "content": "from _asyncio import Future\nfrom collections.abc import Callable, Sequence\nfrom contextvars import Context\nfrom typing import Any, Final\nfrom typing_extensions import TypeIs\n\nfrom . import futures\n\n__all__ = ()\n\n_PENDING: Final = \"PENDING\"  # undocumented\n_CANCELLED: Final = \"CANCELLED\"  # undocumented\n_FINISHED: Final = \"FINISHED\"  # undocumented\n\ndef isfuture(obj: object) -> TypeIs[Future[Any]]: ...\ndef _format_callbacks(cb: Sequence[tuple[Callable[[futures.Future[Any]], None], Context]]) -> str: ...  # undocumented\ndef _future_repr_info(future: futures.Future[Any]) -> list[str]: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/base_subprocess.pyi",
    "content": "import subprocess\nfrom collections import deque\nfrom collections.abc import Callable, Sequence\nfrom typing import IO, Any\nfrom typing_extensions import TypeAlias\n\nfrom . import events, futures, protocols, transports\n\n_File: TypeAlias = int | IO[Any] | None\n\nclass BaseSubprocessTransport(transports.SubprocessTransport):\n    _closed: bool  # undocumented\n    _protocol: protocols.SubprocessProtocol  # undocumented\n    _loop: events.AbstractEventLoop  # undocumented\n    _proc: subprocess.Popen[Any] | None  # undocumented\n    _pid: int | None  # undocumented\n    _returncode: int | None  # undocumented\n    _exit_waiters: list[futures.Future[Any]]  # undocumented\n    _pending_calls: deque[tuple[Callable[..., Any], tuple[Any, ...]]]  # undocumented\n    _pipes: dict[int, _File]  # undocumented\n    _finished: bool  # undocumented\n    def __init__(\n        self,\n        loop: events.AbstractEventLoop,\n        protocol: protocols.SubprocessProtocol,\n        args: str | bytes | Sequence[str | bytes],\n        shell: bool,\n        stdin: _File,\n        stdout: _File,\n        stderr: _File,\n        bufsize: int,\n        waiter: futures.Future[Any] | None = None,\n        extra: Any | None = None,\n        **kwargs: Any,\n    ) -> None: ...\n    def _start(\n        self,\n        args: str | bytes | Sequence[str | bytes],\n        shell: bool,\n        stdin: _File,\n        stdout: _File,\n        stderr: _File,\n        bufsize: int,\n        **kwargs: Any,\n    ) -> None: ...  # undocumented\n    def get_pid(self) -> int | None: ...  # type: ignore[override]\n    def get_pipe_transport(self, fd: int) -> _File: ...  # type: ignore[override]\n    def _check_proc(self) -> None: ...  # undocumented\n    def send_signal(self, signal: int) -> None: ...\n    async def _connect_pipes(self, waiter: futures.Future[Any] | None) -> None: ...  # undocumented\n    def _call(self, cb: Callable[..., object], *data: Any) -> None: ...  # undocumented\n    def _pipe_connection_lost(self, fd: int, exc: BaseException | None) -> None: ...  # undocumented\n    def _pipe_data_received(self, fd: int, data: bytes) -> None: ...  # undocumented\n    def _process_exited(self, returncode: int) -> None: ...  # undocumented\n    async def _wait(self) -> int: ...  # undocumented\n    def _try_finish(self) -> None: ...  # undocumented\n    def _call_connection_lost(self, exc: BaseException | None) -> None: ...  # undocumented\n    def __del__(self) -> None: ...\n\nclass WriteSubprocessPipeProto(protocols.BaseProtocol):  # undocumented\n    def __init__(self, proc: BaseSubprocessTransport, fd: int) -> None: ...\n\nclass ReadSubprocessPipeProto(WriteSubprocessPipeProto, protocols.Protocol): ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/base_tasks.pyi",
    "content": "from _typeshed import StrOrBytesPath\nfrom types import FrameType\nfrom typing import Any\n\nfrom . import tasks\n\ndef _task_repr_info(task: tasks.Task[Any]) -> list[str]: ...  # undocumented\ndef _task_get_stack(task: tasks.Task[Any], limit: int | None) -> list[FrameType]: ...  # undocumented\ndef _task_print_stack(task: tasks.Task[Any], limit: int | None, file: StrOrBytesPath) -> None: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/constants.pyi",
    "content": "import enum\nimport sys\nfrom typing import Final\n\nLOG_THRESHOLD_FOR_CONNLOST_WRITES: Final = 5\nACCEPT_RETRY_DELAY: Final = 1\nDEBUG_STACK_DEPTH: Final = 10\nSSL_HANDSHAKE_TIMEOUT: float\nSENDFILE_FALLBACK_READBUFFER_SIZE: Final = 262144\nif sys.version_info >= (3, 11):\n    SSL_SHUTDOWN_TIMEOUT: float\n    FLOW_CONTROL_HIGH_WATER_SSL_READ: Final = 256\n    FLOW_CONTROL_HIGH_WATER_SSL_WRITE: Final = 512\nif sys.version_info >= (3, 12):\n    THREAD_JOIN_TIMEOUT: Final = 300\n\nclass _SendfileMode(enum.Enum):\n    UNSUPPORTED = 1\n    TRY_NATIVE = 2\n    FALLBACK = 3\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/coroutines.pyi",
    "content": "import sys\nfrom collections.abc import Awaitable, Callable, Coroutine\nfrom typing import Any, TypeVar, overload\nfrom typing_extensions import ParamSpec, TypeGuard, TypeIs, deprecated\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.version_info >= (3, 11):\n    __all__ = (\"iscoroutinefunction\", \"iscoroutine\")\nelse:\n    __all__ = (\"coroutine\", \"iscoroutinefunction\", \"iscoroutine\")\n\n_T = TypeVar(\"_T\")\n_FunctionT = TypeVar(\"_FunctionT\", bound=Callable[..., Any])\n_P = ParamSpec(\"_P\")\n\nif sys.version_info < (3, 11):\n    @deprecated(\"Deprecated since Python 3.8; removed in Python 3.11. Use `async def` instead.\")\n    def coroutine(func: _FunctionT) -> _FunctionT: ...\n\ndef iscoroutine(obj: object) -> TypeIs[Coroutine[Any, Any, Any]]: ...\n\nif sys.version_info >= (3, 11):\n    @overload\n    @deprecated(\"Deprecated since Python 3.14. Use `inspect.iscoroutinefunction()` instead.\")\n    def iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ...\n    @overload\n    @deprecated(\"Deprecated since Python 3.14. Use `inspect.iscoroutinefunction()` instead.\")\n    def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ...\n    @overload\n    @deprecated(\"Deprecated since Python 3.14. Use `inspect.iscoroutinefunction()` instead.\")\n    def iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ...\n    @overload\n    @deprecated(\"Deprecated since Python 3.14. Use `inspect.iscoroutinefunction()` instead.\")\n    def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ...\n\nelse:\n    # Sometimes needed in Python < 3.11 due to the fact that it supports @coroutine\n    # which was removed in 3.11 which the inspect version doesn't support.\n\n    @overload\n    def iscoroutinefunction(func: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ...\n    @overload\n    def iscoroutinefunction(func: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, _T]]]: ...\n    @overload\n    def iscoroutinefunction(func: Callable[_P, object]) -> TypeGuard[Callable[_P, Coroutine[Any, Any, Any]]]: ...\n    @overload\n    def iscoroutinefunction(func: object) -> TypeGuard[Callable[..., Coroutine[Any, Any, Any]]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/events.pyi",
    "content": "import ssl\nimport sys\nfrom _asyncio import (\n    _get_running_loop as _get_running_loop,\n    _set_running_loop as _set_running_loop,\n    get_event_loop as get_event_loop,\n    get_running_loop as get_running_loop,\n)\nfrom _typeshed import FileDescriptorLike, ReadableBuffer, StrPath, Unused, WriteableBuffer\nfrom abc import ABCMeta, abstractmethod\nfrom collections.abc import Callable, Sequence\nfrom concurrent.futures import Executor\nfrom contextvars import Context\nfrom socket import AddressFamily, AddressInfo, SocketKind, _Address, _RetAddress, socket\nfrom typing import IO, Any, Literal, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, TypeVarTuple, Unpack, deprecated\n\nfrom . import _AwaitableLike, _CoroutineLike\nfrom .base_events import Server\nfrom .futures import Future\nfrom .protocols import BaseProtocol\nfrom .tasks import Task\nfrom .transports import BaseTransport, DatagramTransport, ReadTransport, SubprocessTransport, Transport, WriteTransport\n\nif sys.version_info < (3, 14):\n    from .unix_events import AbstractChildWatcher\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.version_info >= (3, 14):\n    __all__ = (\n        \"AbstractEventLoop\",\n        \"AbstractServer\",\n        \"Handle\",\n        \"TimerHandle\",\n        \"get_event_loop_policy\",\n        \"set_event_loop_policy\",\n        \"get_event_loop\",\n        \"set_event_loop\",\n        \"new_event_loop\",\n        \"_set_running_loop\",\n        \"get_running_loop\",\n        \"_get_running_loop\",\n    )\nelse:\n    __all__ = (\n        \"AbstractEventLoopPolicy\",\n        \"AbstractEventLoop\",\n        \"AbstractServer\",\n        \"Handle\",\n        \"TimerHandle\",\n        \"get_event_loop_policy\",\n        \"set_event_loop_policy\",\n        \"get_event_loop\",\n        \"set_event_loop\",\n        \"new_event_loop\",\n        \"get_child_watcher\",\n        \"set_child_watcher\",\n        \"_set_running_loop\",\n        \"get_running_loop\",\n        \"_get_running_loop\",\n    )\n\n_T = TypeVar(\"_T\")\n_Ts = TypeVarTuple(\"_Ts\")\n_ProtocolT = TypeVar(\"_ProtocolT\", bound=BaseProtocol)\n_Context: TypeAlias = dict[str, Any]\n_ExceptionHandler: TypeAlias = Callable[[AbstractEventLoop, _Context], object]\n_ProtocolFactory: TypeAlias = Callable[[], BaseProtocol]\n_SSLContext: TypeAlias = bool | None | ssl.SSLContext\n\n@type_check_only\nclass _TaskFactory(Protocol):\n    def __call__(self, loop: AbstractEventLoop, factory: _CoroutineLike[_T], /) -> Future[_T]: ...\n\nclass Handle:\n    __slots__ = (\"_callback\", \"_args\", \"_cancelled\", \"_loop\", \"_source_traceback\", \"_repr\", \"__weakref__\", \"_context\")\n    _cancelled: bool\n    _args: Sequence[Any]\n    def __init__(\n        self, callback: Callable[..., object], args: Sequence[Any], loop: AbstractEventLoop, context: Context | None = None\n    ) -> None: ...\n    def cancel(self) -> None: ...\n    def _run(self) -> None: ...\n    def cancelled(self) -> bool: ...\n    if sys.version_info >= (3, 12):\n        def get_context(self) -> Context: ...\n\nclass TimerHandle(Handle):\n    __slots__ = [\"_scheduled\", \"_when\"]\n    def __init__(\n        self,\n        when: float,\n        callback: Callable[..., object],\n        args: Sequence[Any],\n        loop: AbstractEventLoop,\n        context: Context | None = None,\n    ) -> None: ...\n    def __hash__(self) -> int: ...\n    def when(self) -> float: ...\n    def __lt__(self, other: TimerHandle) -> bool: ...\n    def __le__(self, other: TimerHandle) -> bool: ...\n    def __gt__(self, other: TimerHandle) -> bool: ...\n    def __ge__(self, other: TimerHandle) -> bool: ...\n    def __eq__(self, other: object) -> bool: ...\n\nclass AbstractServer:\n    @abstractmethod\n    def close(self) -> None: ...\n    if sys.version_info >= (3, 13):\n        @abstractmethod\n        def close_clients(self) -> None: ...\n        @abstractmethod\n        def abort_clients(self) -> None: ...\n\n    async def __aenter__(self) -> Self: ...\n    async def __aexit__(self, *exc: Unused) -> None: ...\n    @abstractmethod\n    def get_loop(self) -> AbstractEventLoop: ...\n    @abstractmethod\n    def is_serving(self) -> bool: ...\n    @abstractmethod\n    async def start_serving(self) -> None: ...\n    @abstractmethod\n    async def serve_forever(self) -> None: ...\n    @abstractmethod\n    async def wait_closed(self) -> None: ...\n\nclass AbstractEventLoop:\n    slow_callback_duration: float\n    @abstractmethod\n    def run_forever(self) -> None: ...\n    @abstractmethod\n    def run_until_complete(self, future: _AwaitableLike[_T]) -> _T: ...\n    @abstractmethod\n    def stop(self) -> None: ...\n    @abstractmethod\n    def is_running(self) -> bool: ...\n    @abstractmethod\n    def is_closed(self) -> bool: ...\n    @abstractmethod\n    def close(self) -> None: ...\n    @abstractmethod\n    async def shutdown_asyncgens(self) -> None: ...\n    # Methods scheduling callbacks.  All these return Handles.\n    # \"context\" added in 3.9.10/3.10.2 for call_*\n    @abstractmethod\n    def call_soon(\n        self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None\n    ) -> Handle: ...\n    @abstractmethod\n    def call_later(\n        self, delay: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None\n    ) -> TimerHandle: ...\n    @abstractmethod\n    def call_at(\n        self, when: float, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None\n    ) -> TimerHandle: ...\n    @abstractmethod\n    def time(self) -> float: ...\n    # Future methods\n    @abstractmethod\n    def create_future(self) -> Future[Any]: ...\n    # Tasks methods\n    if sys.version_info >= (3, 14):\n        @abstractmethod\n        def create_task(\n            self,\n            coro: _CoroutineLike[_T],\n            *,\n            name: str | None = None,\n            context: Context | None = None,\n            eager_start: bool | None = None,\n        ) -> Task[_T]: ...\n    elif sys.version_info >= (3, 11):\n        @abstractmethod\n        def create_task(\n            self, coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None\n        ) -> Task[_T]: ...\n    else:\n        @abstractmethod\n        def create_task(self, coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: ...\n\n    @abstractmethod\n    def set_task_factory(self, factory: _TaskFactory | None) -> None: ...\n    @abstractmethod\n    def get_task_factory(self) -> _TaskFactory | None: ...\n    # Methods for interacting with threads\n    # \"context\" added in 3.9.10/3.10.2\n    @abstractmethod\n    def call_soon_threadsafe(\n        self, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts], context: Context | None = None\n    ) -> Handle: ...\n    @abstractmethod\n    def run_in_executor(self, executor: Executor | None, func: Callable[[Unpack[_Ts]], _T], *args: Unpack[_Ts]) -> Future[_T]: ...\n    @abstractmethod\n    def set_default_executor(self, executor: Executor) -> None: ...\n    # Network I/O methods returning Futures.\n    @abstractmethod\n    async def getaddrinfo(\n        self,\n        host: bytes | str | None,\n        port: bytes | str | int | None,\n        *,\n        family: int = 0,\n        type: int = 0,\n        proto: int = 0,\n        flags: int = 0,\n    ) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int]]]: ...\n    @abstractmethod\n    async def getnameinfo(self, sockaddr: tuple[str, int] | tuple[str, int, int, int], flags: int = 0) -> tuple[str, str]: ...\n    if sys.version_info >= (3, 11):\n        @overload\n        @abstractmethod\n        async def create_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            host: str = ...,\n            port: int = ...,\n            *,\n            ssl: _SSLContext = None,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            sock: None = None,\n            local_addr: tuple[str, int] | None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            happy_eyeballs_delay: float | None = None,\n            interleave: int | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n        @overload\n        @abstractmethod\n        async def create_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            host: None = None,\n            port: None = None,\n            *,\n            ssl: _SSLContext = None,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            sock: socket,\n            local_addr: None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            happy_eyeballs_delay: float | None = None,\n            interleave: int | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n    else:\n        @overload\n        @abstractmethod\n        async def create_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            host: str = ...,\n            port: int = ...,\n            *,\n            ssl: _SSLContext = None,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            sock: None = None,\n            local_addr: tuple[str, int] | None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            happy_eyeballs_delay: float | None = None,\n            interleave: int | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n        @overload\n        @abstractmethod\n        async def create_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            host: None = None,\n            port: None = None,\n            *,\n            ssl: _SSLContext = None,\n            family: int = 0,\n            proto: int = 0,\n            flags: int = 0,\n            sock: socket,\n            local_addr: None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            happy_eyeballs_delay: float | None = None,\n            interleave: int | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n\n    if sys.version_info >= (3, 13):\n        # 3.13 added `keep_alive`.\n        @overload\n        @abstractmethod\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: str | Sequence[str] | None = None,\n            port: int = ...,\n            *,\n            family: int = AddressFamily.AF_UNSPEC,\n            flags: int = AddressInfo.AI_PASSIVE,\n            sock: None = None,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            keep_alive: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n        @overload\n        @abstractmethod\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: None = None,\n            port: None = None,\n            *,\n            family: int = AddressFamily.AF_UNSPEC,\n            flags: int = AddressInfo.AI_PASSIVE,\n            sock: socket = ...,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            keep_alive: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n    elif sys.version_info >= (3, 11):\n        @overload\n        @abstractmethod\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: str | Sequence[str] | None = None,\n            port: int = ...,\n            *,\n            family: int = AddressFamily.AF_UNSPEC,\n            flags: int = AddressInfo.AI_PASSIVE,\n            sock: None = None,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n        @overload\n        @abstractmethod\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: None = None,\n            port: None = None,\n            *,\n            family: int = AddressFamily.AF_UNSPEC,\n            flags: int = AddressInfo.AI_PASSIVE,\n            sock: socket = ...,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n    else:\n        @overload\n        @abstractmethod\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: str | Sequence[str] | None = None,\n            port: int = ...,\n            *,\n            family: int = AddressFamily.AF_UNSPEC,\n            flags: int = AddressInfo.AI_PASSIVE,\n            sock: None = None,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n        @overload\n        @abstractmethod\n        async def create_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            host: None = None,\n            port: None = None,\n            *,\n            family: int = AddressFamily.AF_UNSPEC,\n            flags: int = AddressInfo.AI_PASSIVE,\n            sock: socket = ...,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            reuse_address: bool | None = None,\n            reuse_port: bool | None = None,\n            ssl_handshake_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n\n    if sys.version_info >= (3, 11):\n        @abstractmethod\n        async def start_tls(\n            self,\n            transport: WriteTransport,\n            protocol: BaseProtocol,\n            sslcontext: ssl.SSLContext,\n            *,\n            server_side: bool = False,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n        ) -> Transport | None: ...\n        async def create_unix_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            path: StrPath | None = None,\n            *,\n            sock: socket | None = None,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n    else:\n        @abstractmethod\n        async def start_tls(\n            self,\n            transport: BaseTransport,\n            protocol: BaseProtocol,\n            sslcontext: ssl.SSLContext,\n            *,\n            server_side: bool = False,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n        ) -> Transport | None: ...\n        async def create_unix_server(\n            self,\n            protocol_factory: _ProtocolFactory,\n            path: StrPath | None = None,\n            *,\n            sock: socket | None = None,\n            backlog: int = 100,\n            ssl: _SSLContext = None,\n            ssl_handshake_timeout: float | None = None,\n            start_serving: bool = True,\n        ) -> Server: ...\n\n    if sys.version_info >= (3, 11):\n        async def connect_accepted_socket(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            sock: socket,\n            *,\n            ssl: _SSLContext = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n    elif sys.version_info >= (3, 10):\n        async def connect_accepted_socket(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            sock: socket,\n            *,\n            ssl: _SSLContext = None,\n            ssl_handshake_timeout: float | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n    if sys.version_info >= (3, 11):\n        async def create_unix_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            path: str | None = None,\n            *,\n            ssl: _SSLContext = None,\n            sock: socket | None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n    else:\n        async def create_unix_connection(\n            self,\n            protocol_factory: Callable[[], _ProtocolT],\n            path: str | None = None,\n            *,\n            ssl: _SSLContext = None,\n            sock: socket | None = None,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n        ) -> tuple[Transport, _ProtocolT]: ...\n\n    @abstractmethod\n    async def sock_sendfile(\n        self, sock: socket, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool | None = None\n    ) -> int: ...\n    @abstractmethod\n    async def sendfile(\n        self, transport: WriteTransport, file: IO[bytes], offset: int = 0, count: int | None = None, *, fallback: bool = True\n    ) -> int: ...\n    @abstractmethod\n    async def create_datagram_endpoint(\n        self,\n        protocol_factory: Callable[[], _ProtocolT],\n        local_addr: tuple[str, int] | str | None = None,\n        remote_addr: tuple[str, int] | str | None = None,\n        *,\n        family: int = 0,\n        proto: int = 0,\n        flags: int = 0,\n        reuse_address: bool | None = None,\n        reuse_port: bool | None = None,\n        allow_broadcast: bool | None = None,\n        sock: socket | None = None,\n    ) -> tuple[DatagramTransport, _ProtocolT]: ...\n    # Pipes and subprocesses.\n    @abstractmethod\n    async def connect_read_pipe(\n        self, protocol_factory: Callable[[], _ProtocolT], pipe: Any\n    ) -> tuple[ReadTransport, _ProtocolT]: ...\n    @abstractmethod\n    async def connect_write_pipe(\n        self, protocol_factory: Callable[[], _ProtocolT], pipe: Any\n    ) -> tuple[WriteTransport, _ProtocolT]: ...\n    @abstractmethod\n    async def subprocess_shell(\n        self,\n        protocol_factory: Callable[[], _ProtocolT],\n        cmd: bytes | str,\n        *,\n        stdin: int | IO[Any] | None = -1,\n        stdout: int | IO[Any] | None = -1,\n        stderr: int | IO[Any] | None = -1,\n        universal_newlines: Literal[False] = False,\n        shell: Literal[True] = True,\n        bufsize: Literal[0] = 0,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        **kwargs: Any,\n    ) -> tuple[SubprocessTransport, _ProtocolT]: ...\n    @abstractmethod\n    async def subprocess_exec(\n        self,\n        protocol_factory: Callable[[], _ProtocolT],\n        program: Any,\n        *args: Any,\n        stdin: int | IO[Any] | None = -1,\n        stdout: int | IO[Any] | None = -1,\n        stderr: int | IO[Any] | None = -1,\n        universal_newlines: Literal[False] = False,\n        shell: Literal[False] = False,\n        bufsize: Literal[0] = 0,\n        encoding: None = None,\n        errors: None = None,\n        **kwargs: Any,\n    ) -> tuple[SubprocessTransport, _ProtocolT]: ...\n    @abstractmethod\n    def add_reader(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ...\n    @abstractmethod\n    def remove_reader(self, fd: FileDescriptorLike) -> bool: ...\n    @abstractmethod\n    def add_writer(self, fd: FileDescriptorLike, callback: Callable[[Unpack[_Ts]], Any], *args: Unpack[_Ts]) -> None: ...\n    @abstractmethod\n    def remove_writer(self, fd: FileDescriptorLike) -> bool: ...\n    @abstractmethod\n    async def sock_recv(self, sock: socket, nbytes: int) -> bytes: ...\n    @abstractmethod\n    async def sock_recv_into(self, sock: socket, buf: WriteableBuffer) -> int: ...\n    @abstractmethod\n    async def sock_sendall(self, sock: socket, data: ReadableBuffer) -> None: ...\n    @abstractmethod\n    async def sock_connect(self, sock: socket, address: _Address) -> None: ...\n    @abstractmethod\n    async def sock_accept(self, sock: socket) -> tuple[socket, _RetAddress]: ...\n    if sys.version_info >= (3, 11):\n        @abstractmethod\n        async def sock_recvfrom(self, sock: socket, bufsize: int) -> tuple[bytes, _RetAddress]: ...\n        @abstractmethod\n        async def sock_recvfrom_into(self, sock: socket, buf: WriteableBuffer, nbytes: int = 0) -> tuple[int, _RetAddress]: ...\n        @abstractmethod\n        async def sock_sendto(self, sock: socket, data: ReadableBuffer, address: _Address) -> int: ...\n    # Signal handling.\n    @abstractmethod\n    def add_signal_handler(self, sig: int, callback: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> None: ...\n    @abstractmethod\n    def remove_signal_handler(self, sig: int) -> bool: ...\n    # Error handlers.\n    @abstractmethod\n    def set_exception_handler(self, handler: _ExceptionHandler | None) -> None: ...\n    @abstractmethod\n    def get_exception_handler(self) -> _ExceptionHandler | None: ...\n    @abstractmethod\n    def default_exception_handler(self, context: _Context) -> None: ...\n    @abstractmethod\n    def call_exception_handler(self, context: _Context) -> None: ...\n    # Debug flag management.\n    @abstractmethod\n    def get_debug(self) -> bool: ...\n    @abstractmethod\n    def set_debug(self, enabled: bool) -> None: ...\n    @abstractmethod\n    async def shutdown_default_executor(self) -> None: ...\n\nif sys.version_info >= (3, 14):\n    class _AbstractEventLoopPolicy:\n        @abstractmethod\n        def get_event_loop(self) -> AbstractEventLoop: ...\n        @abstractmethod\n        def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ...\n        @abstractmethod\n        def new_event_loop(self) -> AbstractEventLoop: ...\n\nelse:\n    @type_check_only\n    class _AbstractEventLoopPolicy:\n        @abstractmethod\n        def get_event_loop(self) -> AbstractEventLoop: ...\n        @abstractmethod\n        def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ...\n        @abstractmethod\n        def new_event_loop(self) -> AbstractEventLoop: ...\n        # Child processes handling (Unix only).\n        if sys.version_info >= (3, 12):\n            @abstractmethod\n            @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14.\")\n            def get_child_watcher(self) -> AbstractChildWatcher: ...\n            @abstractmethod\n            @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14.\")\n            def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ...\n        else:\n            @abstractmethod\n            def get_child_watcher(self) -> AbstractChildWatcher: ...\n            @abstractmethod\n            def set_child_watcher(self, watcher: AbstractChildWatcher) -> None: ...\n\n    AbstractEventLoopPolicy = _AbstractEventLoopPolicy\n\nif sys.version_info >= (3, 14):\n    class _BaseDefaultEventLoopPolicy(_AbstractEventLoopPolicy, metaclass=ABCMeta):\n        def get_event_loop(self) -> AbstractEventLoop: ...\n        def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ...\n        def new_event_loop(self) -> AbstractEventLoop: ...\n\nelse:\n    class BaseDefaultEventLoopPolicy(_AbstractEventLoopPolicy, metaclass=ABCMeta):\n        def get_event_loop(self) -> AbstractEventLoop: ...\n        def set_event_loop(self, loop: AbstractEventLoop | None) -> None: ...\n        def new_event_loop(self) -> AbstractEventLoop: ...\n\nif sys.version_info >= (3, 14):\n    def _get_event_loop_policy() -> _AbstractEventLoopPolicy: ...\n    def _set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ...\n    @deprecated(\"Deprecated since Python 3.14; will be removed in Python 3.16.\")\n    def get_event_loop_policy() -> _AbstractEventLoopPolicy: ...\n    @deprecated(\"Deprecated since Python 3.14; will be removed in Python 3.16.\")\n    def set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ...\n\nelse:\n    def get_event_loop_policy() -> _AbstractEventLoopPolicy: ...\n    def set_event_loop_policy(policy: _AbstractEventLoopPolicy | None) -> None: ...\n\ndef set_event_loop(loop: AbstractEventLoop | None) -> None: ...\ndef new_event_loop() -> AbstractEventLoop: ...\n\nif sys.version_info < (3, 14):\n    if sys.version_info >= (3, 12):\n        @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14.\")\n        def get_child_watcher() -> AbstractChildWatcher: ...\n        @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14.\")\n        def set_child_watcher(watcher: AbstractChildWatcher) -> None: ...\n\n    else:\n        def get_child_watcher() -> AbstractChildWatcher: ...\n        def set_child_watcher(watcher: AbstractChildWatcher) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/exceptions.pyi",
    "content": "import sys\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.version_info >= (3, 11):\n    __all__ = (\n        \"BrokenBarrierError\",\n        \"CancelledError\",\n        \"InvalidStateError\",\n        \"TimeoutError\",\n        \"IncompleteReadError\",\n        \"LimitOverrunError\",\n        \"SendfileNotAvailableError\",\n    )\nelse:\n    __all__ = (\n        \"CancelledError\",\n        \"InvalidStateError\",\n        \"TimeoutError\",\n        \"IncompleteReadError\",\n        \"LimitOverrunError\",\n        \"SendfileNotAvailableError\",\n    )\n\nclass CancelledError(BaseException): ...\n\nif sys.version_info >= (3, 11):\n    from builtins import TimeoutError as TimeoutError\nelse:\n    class TimeoutError(Exception): ...\n\nclass InvalidStateError(Exception): ...\nclass SendfileNotAvailableError(RuntimeError): ...\n\nclass IncompleteReadError(EOFError):\n    expected: int | None\n    partial: bytes\n    def __init__(self, partial: bytes, expected: int | None) -> None: ...\n\nclass LimitOverrunError(Exception):\n    consumed: int\n    def __init__(self, message: str, consumed: int) -> None: ...\n\nif sys.version_info >= (3, 11):\n    class BrokenBarrierError(RuntimeError): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/format_helpers.pyi",
    "content": "import functools\nimport sys\nimport traceback\nfrom collections.abc import Iterable\nfrom types import FrameType, FunctionType\nfrom typing import Any, overload, type_check_only\nfrom typing_extensions import TypeAlias\n\n@type_check_only\nclass _HasWrapper:\n    __wrapper__: _HasWrapper | FunctionType\n\n_FuncType: TypeAlias = FunctionType | _HasWrapper | functools.partial[Any] | functools.partialmethod[Any]\n\n@overload\ndef _get_function_source(func: _FuncType) -> tuple[str, int]: ...\n@overload\ndef _get_function_source(func: object) -> tuple[str, int] | None: ...\n\nif sys.version_info >= (3, 13):\n    def _format_callback_source(func: object, args: Iterable[Any], *, debug: bool = False) -> str: ...\n    def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, Any], *, debug: bool = False) -> str: ...\n    def _format_callback(\n        func: object, args: Iterable[Any], kwargs: dict[str, Any], *, debug: bool = False, suffix: str = \"\"\n    ) -> str: ...\n\nelse:\n    def _format_callback_source(func: object, args: Iterable[Any]) -> str: ...\n    def _format_args_and_kwargs(args: Iterable[Any], kwargs: dict[str, Any]) -> str: ...\n    def _format_callback(func: object, args: Iterable[Any], kwargs: dict[str, Any], suffix: str = \"\") -> str: ...\n\ndef extract_stack(f: FrameType | None = None, limit: int | None = None) -> traceback.StackSummary: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/futures.pyi",
    "content": "import sys\nfrom _asyncio import Future as Future\nfrom concurrent.futures._base import Future as _ConcurrentFuture\nfrom typing import TypeVar\n\nfrom .base_futures import isfuture as isfuture\nfrom .events import AbstractEventLoop\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.version_info >= (3, 14):\n    from _asyncio import future_add_to_awaited_by, future_discard_from_awaited_by\n\n    __all__ = (\"Future\", \"wrap_future\", \"isfuture\", \"future_discard_from_awaited_by\", \"future_add_to_awaited_by\")\nelse:\n    __all__ = (\"Future\", \"wrap_future\", \"isfuture\")\n\n_T = TypeVar(\"_T\")\n\ndef wrap_future(future: _ConcurrentFuture[_T] | Future[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/graph.pyi",
    "content": "import sys\nfrom _typeshed import SupportsWrite\nfrom asyncio import Future\nfrom dataclasses import dataclass\nfrom types import FrameType\nfrom typing import Any, overload\n\nif sys.version_info >= (3, 14):\n    __all__ = (\"capture_call_graph\", \"format_call_graph\", \"print_call_graph\", \"FrameCallGraphEntry\", \"FutureCallGraph\")\n\n    @dataclass(frozen=True, slots=True)\n    class FrameCallGraphEntry:\n        frame: FrameType\n\n    @dataclass(frozen=True, slots=True)\n    class FutureCallGraph:\n        future: Future[Any]\n        call_stack: tuple[FrameCallGraphEntry, ...]\n        awaited_by: tuple[FutureCallGraph, ...]\n\n    @overload\n    def capture_call_graph(future: None = None, /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ...\n    @overload\n    def capture_call_graph(future: Future[Any], /, *, depth: int = 1, limit: int | None = None) -> FutureCallGraph | None: ...\n    def format_call_graph(future: Future[Any] | None = None, /, *, depth: int = 1, limit: int | None = None) -> str: ...\n    def print_call_graph(\n        future: Future[Any] | None = None, /, *, file: SupportsWrite[str] | None = None, depth: int = 1, limit: int | None = None\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/locks.pyi",
    "content": "import enum\nimport sys\nfrom _typeshed import Unused\nfrom collections import deque\nfrom collections.abc import Callable\nfrom types import TracebackType\nfrom typing import Any, Literal, TypeVar\nfrom typing_extensions import Self\n\nfrom .events import AbstractEventLoop\nfrom .futures import Future\n\nif sys.version_info >= (3, 10):\n    from .mixins import _LoopBoundMixin\nelse:\n    _LoopBoundMixin = object\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.version_info >= (3, 11):\n    __all__ = (\"Lock\", \"Event\", \"Condition\", \"Semaphore\", \"BoundedSemaphore\", \"Barrier\")\nelse:\n    __all__ = (\"Lock\", \"Event\", \"Condition\", \"Semaphore\", \"BoundedSemaphore\")\n\n_T = TypeVar(\"_T\")\n\nclass _ContextManagerMixin:\n    async def __aenter__(self) -> None: ...\n    async def __aexit__(\n        self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None\n    ) -> None: ...\n\nclass Lock(_ContextManagerMixin, _LoopBoundMixin):\n    _waiters: deque[Future[Any]] | None\n    if sys.version_info >= (3, 10):\n        def __init__(self) -> None: ...\n    else:\n        def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ...\n\n    def locked(self) -> bool: ...\n    async def acquire(self) -> Literal[True]: ...\n    def release(self) -> None: ...\n\nclass Event(_LoopBoundMixin):\n    _waiters: deque[Future[Any]]\n    if sys.version_info >= (3, 10):\n        def __init__(self) -> None: ...\n    else:\n        def __init__(self, *, loop: AbstractEventLoop | None = None) -> None: ...\n\n    def is_set(self) -> bool: ...\n    def set(self) -> None: ...\n    def clear(self) -> None: ...\n    async def wait(self) -> Literal[True]: ...\n\nclass Condition(_ContextManagerMixin, _LoopBoundMixin):\n    _waiters: deque[Future[Any]]\n    if sys.version_info >= (3, 10):\n        def __init__(self, lock: Lock | None = None) -> None: ...\n    else:\n        def __init__(self, lock: Lock | None = None, *, loop: AbstractEventLoop | None = None) -> None: ...\n\n    def locked(self) -> bool: ...\n    async def acquire(self) -> Literal[True]: ...\n    def release(self) -> None: ...\n    async def wait(self) -> Literal[True]: ...\n    async def wait_for(self, predicate: Callable[[], _T]) -> _T: ...\n    def notify(self, n: int = 1) -> None: ...\n    def notify_all(self) -> None: ...\n\nclass Semaphore(_ContextManagerMixin, _LoopBoundMixin):\n    _value: int\n    _waiters: deque[Future[Any]] | None\n    if sys.version_info >= (3, 10):\n        def __init__(self, value: int = 1) -> None: ...\n    else:\n        def __init__(self, value: int = 1, *, loop: AbstractEventLoop | None = None) -> None: ...\n\n    def locked(self) -> bool: ...\n    async def acquire(self) -> Literal[True]: ...\n    def release(self) -> None: ...\n    def _wake_up_next(self) -> None: ...\n\nclass BoundedSemaphore(Semaphore): ...\n\nif sys.version_info >= (3, 11):\n    class _BarrierState(enum.Enum):  # undocumented\n        FILLING = \"filling\"\n        DRAINING = \"draining\"\n        RESETTING = \"resetting\"\n        BROKEN = \"broken\"\n\n    class Barrier(_LoopBoundMixin):\n        def __init__(self, parties: int) -> None: ...\n        async def __aenter__(self) -> Self: ...\n        async def __aexit__(self, *args: Unused) -> None: ...\n        async def wait(self) -> int: ...\n        async def abort(self) -> None: ...\n        async def reset(self) -> None: ...\n        @property\n        def parties(self) -> int: ...\n        @property\n        def n_waiting(self) -> int: ...\n        @property\n        def broken(self) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/log.pyi",
    "content": "import logging\n\nlogger: logging.Logger\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/mixins.pyi",
    "content": "import sys\nimport threading\nfrom typing_extensions import Never\n\n_global_lock: threading.Lock\n\nclass _LoopBoundMixin:\n    if sys.version_info < (3, 11):\n        def __init__(self, *, loop: Never = ...) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/proactor_events.pyi",
    "content": "import sys\nfrom collections.abc import Mapping\nfrom socket import socket\nfrom typing import Any, ClassVar, Literal\n\nfrom . import base_events, constants, events, futures, streams, transports\n\n__all__ = (\"BaseProactorEventLoop\",)\n\nclass _ProactorBasePipeTransport(transports._FlowControlMixin, transports.BaseTransport):\n    def __init__(\n        self,\n        loop: events.AbstractEventLoop,\n        sock: socket,\n        protocol: streams.StreamReaderProtocol,\n        waiter: futures.Future[Any] | None = None,\n        extra: Mapping[Any, Any] | None = None,\n        server: events.AbstractServer | None = None,\n    ) -> None: ...\n    def __del__(self) -> None: ...\n\nclass _ProactorReadPipeTransport(_ProactorBasePipeTransport, transports.ReadTransport):\n    if sys.version_info >= (3, 10):\n        def __init__(\n            self,\n            loop: events.AbstractEventLoop,\n            sock: socket,\n            protocol: streams.StreamReaderProtocol,\n            waiter: futures.Future[Any] | None = None,\n            extra: Mapping[Any, Any] | None = None,\n            server: events.AbstractServer | None = None,\n            buffer_size: int = 65536,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            loop: events.AbstractEventLoop,\n            sock: socket,\n            protocol: streams.StreamReaderProtocol,\n            waiter: futures.Future[Any] | None = None,\n            extra: Mapping[Any, Any] | None = None,\n            server: events.AbstractServer | None = None,\n        ) -> None: ...\n\nclass _ProactorBaseWritePipeTransport(_ProactorBasePipeTransport, transports.WriteTransport): ...\nclass _ProactorWritePipeTransport(_ProactorBaseWritePipeTransport): ...\nclass _ProactorDuplexPipeTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport): ...\n\nclass _ProactorSocketTransport(_ProactorReadPipeTransport, _ProactorBaseWritePipeTransport, transports.Transport):\n    _sendfile_compatible: ClassVar[constants._SendfileMode]\n    def __init__(\n        self,\n        loop: events.AbstractEventLoop,\n        sock: socket,\n        protocol: streams.StreamReaderProtocol,\n        waiter: futures.Future[Any] | None = None,\n        extra: Mapping[Any, Any] | None = None,\n        server: events.AbstractServer | None = None,\n    ) -> None: ...\n    def _set_extra(self, sock: socket) -> None: ...\n    def can_write_eof(self) -> Literal[True]: ...\n\nclass BaseProactorEventLoop(base_events.BaseEventLoop):\n    def __init__(self, proactor: Any) -> None: ...\n    async def sock_recv(self, sock: socket, n: int) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/protocols.pyi",
    "content": "from _typeshed import ReadableBuffer\nfrom asyncio import transports\nfrom typing import Any\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\n__all__ = (\"BaseProtocol\", \"Protocol\", \"DatagramProtocol\", \"SubprocessProtocol\", \"BufferedProtocol\")\n\nclass BaseProtocol:\n    __slots__ = ()\n    def connection_made(self, transport: transports.BaseTransport) -> None: ...\n    def connection_lost(self, exc: Exception | None) -> None: ...\n    def pause_writing(self) -> None: ...\n    def resume_writing(self) -> None: ...\n\nclass Protocol(BaseProtocol):\n    # Need annotation or mypy will complain about 'Cannot determine type of \"__slots__\" in base class'\n    __slots__: tuple[str, ...] = ()\n    def data_received(self, data: bytes) -> None: ...\n    def eof_received(self) -> bool | None: ...\n\nclass BufferedProtocol(BaseProtocol):\n    __slots__ = ()\n    def get_buffer(self, sizehint: int) -> ReadableBuffer: ...\n    def buffer_updated(self, nbytes: int) -> None: ...\n    def eof_received(self) -> bool | None: ...\n\nclass DatagramProtocol(BaseProtocol):\n    __slots__ = ()\n    def connection_made(self, transport: transports.DatagramTransport) -> None: ...  # type: ignore[override]\n    # addr can be a tuple[int, int] for some unusual protocols like socket.AF_NETLINK.\n    # Use tuple[str | Any, int] to not cause typechecking issues on most usual cases.\n    # This could be improved by using tuple[AnyOf[str, int], int] if the AnyOf feature is accepted.\n    # See https://github.com/python/typing/issues/566\n    def datagram_received(self, data: bytes, addr: tuple[str | Any, int]) -> None: ...\n    def error_received(self, exc: Exception) -> None: ...\n\nclass SubprocessProtocol(BaseProtocol):\n    __slots__: tuple[str, ...] = ()\n    def pipe_data_received(self, fd: int, data: bytes) -> None: ...\n    def pipe_connection_lost(self, fd: int, exc: Exception | None) -> None: ...\n    def process_exited(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/queues.pyi",
    "content": "import sys\nfrom _typeshed import SupportsRichComparisonT\nfrom asyncio.events import AbstractEventLoop\nfrom types import GenericAlias\nfrom typing import Any, Generic, TypeVar\n\nif sys.version_info >= (3, 10):\n    from .mixins import _LoopBoundMixin\nelse:\n    _LoopBoundMixin = object\n\nclass QueueEmpty(Exception): ...\nclass QueueFull(Exception): ...\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.version_info >= (3, 13):\n    __all__ = (\"Queue\", \"PriorityQueue\", \"LifoQueue\", \"QueueFull\", \"QueueEmpty\", \"QueueShutDown\")\n\nelse:\n    __all__ = (\"Queue\", \"PriorityQueue\", \"LifoQueue\", \"QueueFull\", \"QueueEmpty\")\n\n_T = TypeVar(\"_T\")\n\nif sys.version_info >= (3, 13):\n    class QueueShutDown(Exception): ...\n\n# If Generic[_T] is last and _LoopBoundMixin is object, pyright is unhappy.\n# We can remove the noqa pragma when dropping 3.9 support.\nclass Queue(Generic[_T], _LoopBoundMixin):  # noqa: Y059\n    if sys.version_info >= (3, 10):\n        def __init__(self, maxsize: int = 0) -> None: ...\n    else:\n        def __init__(self, maxsize: int = 0, *, loop: AbstractEventLoop | None = None) -> None: ...\n\n    def _init(self, maxsize: int) -> None: ...\n    def _get(self) -> _T: ...\n    def _put(self, item: _T) -> None: ...\n    def _format(self) -> str: ...\n    def qsize(self) -> int: ...\n    @property\n    def maxsize(self) -> int: ...\n    def empty(self) -> bool: ...\n    def full(self) -> bool: ...\n    async def put(self, item: _T) -> None: ...\n    def put_nowait(self, item: _T) -> None: ...\n    async def get(self) -> _T: ...\n    def get_nowait(self) -> _T: ...\n    async def join(self) -> None: ...\n    def task_done(self) -> None: ...\n    def __class_getitem__(cls, type: Any, /) -> GenericAlias: ...\n    if sys.version_info >= (3, 13):\n        def shutdown(self, immediate: bool = False) -> None: ...\n\nclass PriorityQueue(Queue[SupportsRichComparisonT]): ...\nclass LifoQueue(Queue[_T]): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/runners.pyi",
    "content": "import sys\nfrom _typeshed import Unused\nfrom collections.abc import Awaitable, Callable, Coroutine\nfrom contextvars import Context\nfrom typing import Any, TypeVar, final\nfrom typing_extensions import Self\n\nfrom .events import AbstractEventLoop\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.version_info >= (3, 11):\n    __all__ = (\"Runner\", \"run\")\nelse:\n    __all__ = (\"run\",)\n_T = TypeVar(\"_T\")\n\nif sys.version_info >= (3, 11):\n    @final\n    class Runner:\n        def __init__(self, *, debug: bool | None = None, loop_factory: Callable[[], AbstractEventLoop] | None = None) -> None: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(self, exc_type: Unused, exc_val: Unused, exc_tb: Unused) -> None: ...\n        def close(self) -> None: ...\n        def get_loop(self) -> AbstractEventLoop: ...\n        if sys.version_info >= (3, 14):\n            def run(self, coro: Awaitable[_T], *, context: Context | None = None) -> _T: ...\n        else:\n            def run(self, coro: Coroutine[Any, Any, _T], *, context: Context | None = None) -> _T: ...\n\nif sys.version_info >= (3, 12):\n    def run(\n        main: Coroutine[Any, Any, _T], *, debug: bool | None = None, loop_factory: Callable[[], AbstractEventLoop] | None = None\n    ) -> _T: ...\n\nelse:\n    def run(main: Coroutine[Any, Any, _T], *, debug: bool | None = None) -> _T: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/selector_events.pyi",
    "content": "import selectors\nfrom socket import socket\n\nfrom . import base_events\n\n__all__ = (\"BaseSelectorEventLoop\",)\n\nclass BaseSelectorEventLoop(base_events.BaseEventLoop):\n    def __init__(self, selector: selectors.BaseSelector | None = None) -> None: ...\n    async def sock_recv(self, sock: socket, n: int) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/sslproto.pyi",
    "content": "import ssl\nimport sys\nfrom collections import deque\nfrom collections.abc import Callable\nfrom enum import Enum\nfrom typing import Any, ClassVar, Final, Literal\nfrom typing_extensions import TypeAlias\n\nfrom . import constants, events, futures, protocols, transports\n\ndef _create_transport_context(server_side: bool, server_hostname: str | None) -> ssl.SSLContext: ...\n\nif sys.version_info >= (3, 11):\n    SSLAgainErrors: tuple[type[ssl.SSLWantReadError], type[ssl.SSLSyscallError]]\n\n    class SSLProtocolState(Enum):\n        UNWRAPPED = \"UNWRAPPED\"\n        DO_HANDSHAKE = \"DO_HANDSHAKE\"\n        WRAPPED = \"WRAPPED\"\n        FLUSHING = \"FLUSHING\"\n        SHUTDOWN = \"SHUTDOWN\"\n\n    class AppProtocolState(Enum):\n        STATE_INIT = \"STATE_INIT\"\n        STATE_CON_MADE = \"STATE_CON_MADE\"\n        STATE_EOF = \"STATE_EOF\"\n        STATE_CON_LOST = \"STATE_CON_LOST\"\n\n    def add_flowcontrol_defaults(high: int | None, low: int | None, kb: int) -> tuple[int, int]: ...\n\nelse:\n    _UNWRAPPED: Final = \"UNWRAPPED\"\n    _DO_HANDSHAKE: Final = \"DO_HANDSHAKE\"\n    _WRAPPED: Final = \"WRAPPED\"\n    _SHUTDOWN: Final = \"SHUTDOWN\"\n\nif sys.version_info < (3, 11):\n    class _SSLPipe:\n        max_size: ClassVar[int]\n\n        _context: ssl.SSLContext\n        _server_side: bool\n        _server_hostname: str | None\n        _state: str\n        _incoming: ssl.MemoryBIO\n        _outgoing: ssl.MemoryBIO\n        _sslobj: ssl.SSLObject | None\n        _need_ssldata: bool\n        _handshake_cb: Callable[[BaseException | None], None] | None\n        _shutdown_cb: Callable[[], None] | None\n        def __init__(self, context: ssl.SSLContext, server_side: bool, server_hostname: str | None = None) -> None: ...\n        @property\n        def context(self) -> ssl.SSLContext: ...\n        @property\n        def ssl_object(self) -> ssl.SSLObject | None: ...\n        @property\n        def need_ssldata(self) -> bool: ...\n        @property\n        def wrapped(self) -> bool: ...\n        def do_handshake(self, callback: Callable[[BaseException | None], object] | None = None) -> list[bytes]: ...\n        def shutdown(self, callback: Callable[[], object] | None = None) -> list[bytes]: ...\n        def feed_eof(self) -> None: ...\n        def feed_ssldata(self, data: bytes, only_handshake: bool = False) -> tuple[list[bytes], list[bytes]]: ...\n        def feed_appdata(self, data: bytes, offset: int = 0) -> tuple[list[bytes], int]: ...\n\nclass _SSLProtocolTransport(transports._FlowControlMixin, transports.Transport):\n    _sendfile_compatible: ClassVar[constants._SendfileMode]\n\n    _loop: events.AbstractEventLoop\n    if sys.version_info >= (3, 11):\n        _ssl_protocol: SSLProtocol | None\n    else:\n        _ssl_protocol: SSLProtocol\n    _closed: bool\n    def __init__(self, loop: events.AbstractEventLoop, ssl_protocol: SSLProtocol) -> None: ...\n    def get_extra_info(self, name: str, default: Any | None = None) -> dict[str, Any]: ...\n    @property\n    def _protocol_paused(self) -> bool: ...\n    def write(self, data: bytes | bytearray | memoryview[Any]) -> None: ...  # any memoryview format or shape\n    def can_write_eof(self) -> Literal[False]: ...\n    if sys.version_info >= (3, 11):\n        def get_write_buffer_limits(self) -> tuple[int, int]: ...\n        def get_read_buffer_limits(self) -> tuple[int, int]: ...\n        def set_read_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: ...\n        def get_read_buffer_size(self) -> int: ...\n\n    def __del__(self) -> None: ...\n\nif sys.version_info >= (3, 11):\n    _SSLProtocolBase: TypeAlias = protocols.BufferedProtocol\nelse:\n    _SSLProtocolBase: TypeAlias = protocols.Protocol\n\nclass SSLProtocol(_SSLProtocolBase):\n    _server_side: bool\n    _server_hostname: str | None\n    _sslcontext: ssl.SSLContext\n    _extra: dict[str, Any]\n    _write_backlog: deque[tuple[bytes, int]]\n    _write_buffer_size: int\n    _waiter: futures.Future[Any]\n    _loop: events.AbstractEventLoop\n    _app_transport: _SSLProtocolTransport\n    _transport: transports.BaseTransport | None\n    _ssl_handshake_timeout: int | None\n    _app_protocol: protocols.BaseProtocol\n    _app_protocol_is_buffer: bool\n\n    if sys.version_info >= (3, 11):\n        max_size: ClassVar[int]\n    else:\n        _sslpipe: _SSLPipe | None\n        _session_established: bool\n        _call_connection_made: bool\n        _in_handshake: bool\n        _in_shutdown: bool\n\n    if sys.version_info >= (3, 11):\n        def __init__(\n            self,\n            loop: events.AbstractEventLoop,\n            app_protocol: protocols.BaseProtocol,\n            sslcontext: ssl.SSLContext,\n            waiter: futures.Future[Any],\n            server_side: bool = False,\n            server_hostname: str | None = None,\n            call_connection_made: bool = True,\n            ssl_handshake_timeout: int | None = None,\n            ssl_shutdown_timeout: float | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            loop: events.AbstractEventLoop,\n            app_protocol: protocols.BaseProtocol,\n            sslcontext: ssl.SSLContext,\n            waiter: futures.Future[Any],\n            server_side: bool = False,\n            server_hostname: str | None = None,\n            call_connection_made: bool = True,\n            ssl_handshake_timeout: int | None = None,\n        ) -> None: ...\n\n    def _set_app_protocol(self, app_protocol: protocols.BaseProtocol) -> None: ...\n    def _wakeup_waiter(self, exc: BaseException | None = None) -> None: ...\n    def connection_lost(self, exc: BaseException | None) -> None: ...\n    def eof_received(self) -> None: ...\n    def _get_extra_info(self, name: str, default: Any | None = None) -> Any: ...\n    def _start_shutdown(self) -> None: ...\n    if sys.version_info >= (3, 11):\n        def _write_appdata(self, list_of_data: list[bytes]) -> None: ...\n    else:\n        def _write_appdata(self, data: bytes) -> None: ...\n\n    def _start_handshake(self) -> None: ...\n    def _check_handshake_timeout(self) -> None: ...\n    def _on_handshake_complete(self, handshake_exc: BaseException | None) -> None: ...\n    def _fatal_error(self, exc: BaseException, message: str = \"Fatal error on transport\") -> None: ...\n    if sys.version_info >= (3, 11):\n        def _abort(self, exc: BaseException | None) -> None: ...\n        def get_buffer(self, n: int) -> memoryview: ...\n    else:\n        def _abort(self) -> None: ...\n        def _finalize(self) -> None: ...\n        def _process_write_backlog(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/staggered.pyi",
    "content": "from collections.abc import Awaitable, Callable, Iterable\nfrom typing import Any\n\nfrom . import events\n\n__all__ = (\"staggered_race\",)\n\nasync def staggered_race(\n    coro_fns: Iterable[Callable[[], Awaitable[Any]]], delay: float | None, *, loop: events.AbstractEventLoop | None = None\n) -> tuple[Any, int | None, list[Exception | None]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/streams.pyi",
    "content": "import ssl\nimport sys\nfrom _typeshed import ReadableBuffer, StrPath\nfrom collections.abc import Awaitable, Callable, Iterable, Sequence, Sized\nfrom types import ModuleType\nfrom typing import Any, Protocol, SupportsIndex, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\nfrom . import events, protocols, transports\nfrom .base_events import Server\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.platform == \"win32\":\n    __all__ = (\"StreamReader\", \"StreamWriter\", \"StreamReaderProtocol\", \"open_connection\", \"start_server\")\nelse:\n    __all__ = (\n        \"StreamReader\",\n        \"StreamWriter\",\n        \"StreamReaderProtocol\",\n        \"open_connection\",\n        \"start_server\",\n        \"open_unix_connection\",\n        \"start_unix_server\",\n    )\n\n_ClientConnectedCallback: TypeAlias = Callable[[StreamReader, StreamWriter], Awaitable[None] | None]\n\n@type_check_only\nclass _ReaduntilBuffer(ReadableBuffer, Sized, Protocol): ...\n\nif sys.version_info >= (3, 10):\n    async def open_connection(\n        host: str | None = None,\n        port: int | str | None = None,\n        *,\n        limit: int = 65536,\n        ssl_handshake_timeout: float | None = None,\n        **kwds: Any,\n    ) -> tuple[StreamReader, StreamWriter]: ...\n    async def start_server(\n        client_connected_cb: _ClientConnectedCallback,\n        host: str | Sequence[str] | None = None,\n        port: int | str | None = None,\n        *,\n        limit: int = 65536,\n        ssl_handshake_timeout: float | None = None,\n        **kwds: Any,\n    ) -> Server: ...\n\nelse:\n    async def open_connection(\n        host: str | None = None,\n        port: int | str | None = None,\n        *,\n        loop: events.AbstractEventLoop | None = None,\n        limit: int = 65536,\n        ssl_handshake_timeout: float | None = None,\n        **kwds: Any,\n    ) -> tuple[StreamReader, StreamWriter]: ...\n    async def start_server(\n        client_connected_cb: _ClientConnectedCallback,\n        host: str | None = None,\n        port: int | str | None = None,\n        *,\n        loop: events.AbstractEventLoop | None = None,\n        limit: int = 65536,\n        ssl_handshake_timeout: float | None = None,\n        **kwds: Any,\n    ) -> Server: ...\n\nif sys.platform != \"win32\":\n    if sys.version_info >= (3, 10):\n        async def open_unix_connection(\n            path: StrPath | None = None, *, limit: int = 65536, **kwds: Any\n        ) -> tuple[StreamReader, StreamWriter]: ...\n        async def start_unix_server(\n            client_connected_cb: _ClientConnectedCallback, path: StrPath | None = None, *, limit: int = 65536, **kwds: Any\n        ) -> Server: ...\n    else:\n        async def open_unix_connection(\n            path: StrPath | None = None, *, loop: events.AbstractEventLoop | None = None, limit: int = 65536, **kwds: Any\n        ) -> tuple[StreamReader, StreamWriter]: ...\n        async def start_unix_server(\n            client_connected_cb: _ClientConnectedCallback,\n            path: StrPath | None = None,\n            *,\n            loop: events.AbstractEventLoop | None = None,\n            limit: int = 65536,\n            **kwds: Any,\n        ) -> Server: ...\n\nclass FlowControlMixin(protocols.Protocol):\n    def __init__(self, loop: events.AbstractEventLoop | None = None) -> None: ...\n\nclass StreamReaderProtocol(FlowControlMixin, protocols.Protocol):\n    def __init__(\n        self,\n        stream_reader: StreamReader,\n        client_connected_cb: _ClientConnectedCallback | None = None,\n        loop: events.AbstractEventLoop | None = None,\n    ) -> None: ...\n    def __del__(self) -> None: ...\n\nclass StreamWriter:\n    def __init__(\n        self,\n        transport: transports.WriteTransport,\n        protocol: protocols.BaseProtocol,\n        reader: StreamReader | None,\n        loop: events.AbstractEventLoop,\n    ) -> None: ...\n    @property\n    def transport(self) -> transports.WriteTransport: ...\n    def write(self, data: bytes | bytearray | memoryview) -> None: ...\n    def writelines(self, data: Iterable[bytes | bytearray | memoryview]) -> None: ...\n    def write_eof(self) -> None: ...\n    def can_write_eof(self) -> bool: ...\n    def close(self) -> None: ...\n    def is_closing(self) -> bool: ...\n    async def wait_closed(self) -> None: ...\n    def get_extra_info(self, name: str, default: Any = None) -> Any: ...\n    async def drain(self) -> None: ...\n    if sys.version_info >= (3, 12):\n        async def start_tls(\n            self,\n            sslcontext: ssl.SSLContext,\n            *,\n            server_hostname: str | None = None,\n            ssl_handshake_timeout: float | None = None,\n            ssl_shutdown_timeout: float | None = None,\n        ) -> None: ...\n    elif sys.version_info >= (3, 11):\n        async def start_tls(\n            self, sslcontext: ssl.SSLContext, *, server_hostname: str | None = None, ssl_handshake_timeout: float | None = None\n        ) -> None: ...\n\n    if sys.version_info >= (3, 13):\n        def __del__(self, warnings: ModuleType = ...) -> None: ...\n    elif sys.version_info >= (3, 11):\n        def __del__(self) -> None: ...\n\nclass StreamReader:\n    def __init__(self, limit: int = 65536, loop: events.AbstractEventLoop | None = None) -> None: ...\n    def exception(self) -> Exception: ...\n    def set_exception(self, exc: Exception) -> None: ...\n    def set_transport(self, transport: transports.BaseTransport) -> None: ...\n    def feed_eof(self) -> None: ...\n    def at_eof(self) -> bool: ...\n    def feed_data(self, data: Iterable[SupportsIndex]) -> None: ...\n    async def readline(self) -> bytes: ...\n    if sys.version_info >= (3, 13):\n        async def readuntil(self, separator: _ReaduntilBuffer | tuple[_ReaduntilBuffer, ...] = b\"\\n\") -> bytes: ...\n    else:\n        async def readuntil(self, separator: _ReaduntilBuffer = b\"\\n\") -> bytes: ...\n\n    async def read(self, n: int = -1) -> bytes: ...\n    async def readexactly(self, n: int) -> bytes: ...\n    def __aiter__(self) -> Self: ...\n    async def __anext__(self) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/subprocess.pyi",
    "content": "import subprocess\nimport sys\nfrom _typeshed import StrOrBytesPath\nfrom asyncio import events, protocols, streams, transports\nfrom collections.abc import Callable, Collection\nfrom typing import IO, Any, Literal\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\n__all__ = (\"create_subprocess_exec\", \"create_subprocess_shell\")\n\nPIPE: int\nSTDOUT: int\nDEVNULL: int\n\nclass SubprocessStreamProtocol(streams.FlowControlMixin, protocols.SubprocessProtocol):\n    stdin: streams.StreamWriter | None\n    stdout: streams.StreamReader | None\n    stderr: streams.StreamReader | None\n    def __init__(self, limit: int, loop: events.AbstractEventLoop) -> None: ...\n    def pipe_data_received(self, fd: int, data: bytes | str) -> None: ...\n\nclass Process:\n    stdin: streams.StreamWriter | None\n    stdout: streams.StreamReader | None\n    stderr: streams.StreamReader | None\n    pid: int\n    def __init__(\n        self, transport: transports.BaseTransport, protocol: protocols.BaseProtocol, loop: events.AbstractEventLoop\n    ) -> None: ...\n    @property\n    def returncode(self) -> int | None: ...\n    async def wait(self) -> int: ...\n    def send_signal(self, signal: int) -> None: ...\n    def terminate(self) -> None: ...\n    def kill(self) -> None: ...\n    async def communicate(self, input: bytes | bytearray | memoryview | None = None) -> tuple[bytes, bytes]: ...\n\nif sys.version_info >= (3, 11):\n    async def create_subprocess_shell(\n        cmd: str | bytes,\n        stdin: int | IO[Any] | None = None,\n        stdout: int | IO[Any] | None = None,\n        stderr: int | IO[Any] | None = None,\n        limit: int = 65536,\n        *,\n        # These parameters are forced to these values by BaseEventLoop.subprocess_shell\n        universal_newlines: Literal[False] = False,\n        shell: Literal[True] = True,\n        bufsize: Literal[0] = 0,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        # These parameters are taken by subprocess.Popen, which this ultimately delegates to\n        executable: StrOrBytesPath | None = None,\n        preexec_fn: Callable[[], Any] | None = None,\n        close_fds: bool = True,\n        cwd: StrOrBytesPath | None = None,\n        env: subprocess._ENV | None = None,\n        startupinfo: Any | None = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        group: None | str | int = None,\n        extra_groups: None | Collection[str | int] = None,\n        user: None | str | int = None,\n        umask: int = -1,\n        process_group: int | None = None,\n        pipesize: int = -1,\n    ) -> Process: ...\n    async def create_subprocess_exec(\n        program: StrOrBytesPath,\n        *args: StrOrBytesPath,\n        stdin: int | IO[Any] | None = None,\n        stdout: int | IO[Any] | None = None,\n        stderr: int | IO[Any] | None = None,\n        limit: int = 65536,\n        # These parameters are forced to these values by BaseEventLoop.subprocess_exec\n        universal_newlines: Literal[False] = False,\n        shell: Literal[False] = False,\n        bufsize: Literal[0] = 0,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        # These parameters are taken by subprocess.Popen, which this ultimately delegates to\n        executable: StrOrBytesPath | None = None,\n        preexec_fn: Callable[[], Any] | None = None,\n        close_fds: bool = True,\n        cwd: StrOrBytesPath | None = None,\n        env: subprocess._ENV | None = None,\n        startupinfo: Any | None = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        group: None | str | int = None,\n        extra_groups: None | Collection[str | int] = None,\n        user: None | str | int = None,\n        umask: int = -1,\n        process_group: int | None = None,\n        pipesize: int = -1,\n    ) -> Process: ...\n\nelif sys.version_info >= (3, 10):\n    async def create_subprocess_shell(\n        cmd: str | bytes,\n        stdin: int | IO[Any] | None = None,\n        stdout: int | IO[Any] | None = None,\n        stderr: int | IO[Any] | None = None,\n        limit: int = 65536,\n        *,\n        # These parameters are forced to these values by BaseEventLoop.subprocess_shell\n        universal_newlines: Literal[False] = False,\n        shell: Literal[True] = True,\n        bufsize: Literal[0] = 0,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        # These parameters are taken by subprocess.Popen, which this ultimately delegates to\n        executable: StrOrBytesPath | None = None,\n        preexec_fn: Callable[[], Any] | None = None,\n        close_fds: bool = True,\n        cwd: StrOrBytesPath | None = None,\n        env: subprocess._ENV | None = None,\n        startupinfo: Any | None = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        group: None | str | int = None,\n        extra_groups: None | Collection[str | int] = None,\n        user: None | str | int = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> Process: ...\n    async def create_subprocess_exec(\n        program: StrOrBytesPath,\n        *args: StrOrBytesPath,\n        stdin: int | IO[Any] | None = None,\n        stdout: int | IO[Any] | None = None,\n        stderr: int | IO[Any] | None = None,\n        limit: int = 65536,\n        # These parameters are forced to these values by BaseEventLoop.subprocess_exec\n        universal_newlines: Literal[False] = False,\n        shell: Literal[False] = False,\n        bufsize: Literal[0] = 0,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        # These parameters are taken by subprocess.Popen, which this ultimately delegates to\n        executable: StrOrBytesPath | None = None,\n        preexec_fn: Callable[[], Any] | None = None,\n        close_fds: bool = True,\n        cwd: StrOrBytesPath | None = None,\n        env: subprocess._ENV | None = None,\n        startupinfo: Any | None = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        group: None | str | int = None,\n        extra_groups: None | Collection[str | int] = None,\n        user: None | str | int = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> Process: ...\n\nelse:  # >= 3.9\n    async def create_subprocess_shell(\n        cmd: str | bytes,\n        stdin: int | IO[Any] | None = None,\n        stdout: int | IO[Any] | None = None,\n        stderr: int | IO[Any] | None = None,\n        loop: events.AbstractEventLoop | None = None,\n        limit: int = 65536,\n        *,\n        # These parameters are forced to these values by BaseEventLoop.subprocess_shell\n        universal_newlines: Literal[False] = False,\n        shell: Literal[True] = True,\n        bufsize: Literal[0] = 0,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        # These parameters are taken by subprocess.Popen, which this ultimately delegates to\n        executable: StrOrBytesPath | None = None,\n        preexec_fn: Callable[[], Any] | None = None,\n        close_fds: bool = True,\n        cwd: StrOrBytesPath | None = None,\n        env: subprocess._ENV | None = None,\n        startupinfo: Any | None = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        group: None | str | int = None,\n        extra_groups: None | Collection[str | int] = None,\n        user: None | str | int = None,\n        umask: int = -1,\n    ) -> Process: ...\n    async def create_subprocess_exec(\n        program: StrOrBytesPath,\n        *args: StrOrBytesPath,\n        stdin: int | IO[Any] | None = None,\n        stdout: int | IO[Any] | None = None,\n        stderr: int | IO[Any] | None = None,\n        loop: events.AbstractEventLoop | None = None,\n        limit: int = 65536,\n        # These parameters are forced to these values by BaseEventLoop.subprocess_exec\n        universal_newlines: Literal[False] = False,\n        shell: Literal[False] = False,\n        bufsize: Literal[0] = 0,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        # These parameters are taken by subprocess.Popen, which this ultimately delegates to\n        executable: StrOrBytesPath | None = None,\n        preexec_fn: Callable[[], Any] | None = None,\n        close_fds: bool = True,\n        cwd: StrOrBytesPath | None = None,\n        env: subprocess._ENV | None = None,\n        startupinfo: Any | None = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        group: None | str | int = None,\n        extra_groups: None | Collection[str | int] = None,\n        user: None | str | int = None,\n        umask: int = -1,\n    ) -> Process: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/taskgroups.pyi",
    "content": "import sys\nfrom contextvars import Context\nfrom types import TracebackType\nfrom typing import Any, TypeVar\nfrom typing_extensions import Self\n\nfrom . import _CoroutineLike\nfrom .events import AbstractEventLoop\nfrom .tasks import Task\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.version_info >= (3, 12):\n    __all__ = (\"TaskGroup\",)\nelse:\n    __all__ = [\"TaskGroup\"]\n\n_T = TypeVar(\"_T\")\n\nclass TaskGroup:\n    _loop: AbstractEventLoop | None\n    _tasks: set[Task[Any]]\n\n    async def __aenter__(self) -> Self: ...\n    async def __aexit__(self, et: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ...\n    if sys.version_info >= (3, 14):\n        def create_task(\n            self,\n            coro: _CoroutineLike[_T],\n            *,\n            name: str | None = None,\n            context: Context | None = None,\n            eager_start: bool | None = None,\n        ) -> Task[_T]: ...\n    else:\n        def create_task(\n            self, coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None\n        ) -> Task[_T]: ...\n\n    def _on_task_done(self, task: Task[object]) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/tasks.pyi",
    "content": "import concurrent.futures\nimport sys\nfrom _asyncio import (\n    Task as Task,\n    _enter_task as _enter_task,\n    _leave_task as _leave_task,\n    _register_task as _register_task,\n    _unregister_task as _unregister_task,\n)\nfrom collections.abc import AsyncIterator, Awaitable, Coroutine, Generator, Iterable, Iterator\nfrom typing import Any, Final, Literal, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import TypeAlias\n\nfrom . import _CoroutineLike\nfrom .events import AbstractEventLoop\nfrom .futures import Future\n\nif sys.version_info >= (3, 11):\n    from contextvars import Context\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.version_info >= (3, 12):\n    __all__ = (\n        \"Task\",\n        \"create_task\",\n        \"FIRST_COMPLETED\",\n        \"FIRST_EXCEPTION\",\n        \"ALL_COMPLETED\",\n        \"wait\",\n        \"wait_for\",\n        \"as_completed\",\n        \"sleep\",\n        \"gather\",\n        \"shield\",\n        \"ensure_future\",\n        \"run_coroutine_threadsafe\",\n        \"current_task\",\n        \"all_tasks\",\n        \"create_eager_task_factory\",\n        \"eager_task_factory\",\n        \"_register_task\",\n        \"_unregister_task\",\n        \"_enter_task\",\n        \"_leave_task\",\n    )\nelse:\n    __all__ = (\n        \"Task\",\n        \"create_task\",\n        \"FIRST_COMPLETED\",\n        \"FIRST_EXCEPTION\",\n        \"ALL_COMPLETED\",\n        \"wait\",\n        \"wait_for\",\n        \"as_completed\",\n        \"sleep\",\n        \"gather\",\n        \"shield\",\n        \"ensure_future\",\n        \"run_coroutine_threadsafe\",\n        \"current_task\",\n        \"all_tasks\",\n        \"_register_task\",\n        \"_unregister_task\",\n        \"_enter_task\",\n        \"_leave_task\",\n    )\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n_T3 = TypeVar(\"_T3\")\n_T4 = TypeVar(\"_T4\")\n_T5 = TypeVar(\"_T5\")\n_T6 = TypeVar(\"_T6\")\n_FT = TypeVar(\"_FT\", bound=Future[Any])\nif sys.version_info >= (3, 12):\n    _FutureLike: TypeAlias = Future[_T] | Awaitable[_T]\nelse:\n    _FutureLike: TypeAlias = Future[_T] | Generator[Any, None, _T] | Awaitable[_T]\n\n_TaskYieldType: TypeAlias = Future[object] | None\n\nFIRST_COMPLETED: Final = concurrent.futures.FIRST_COMPLETED\nFIRST_EXCEPTION: Final = concurrent.futures.FIRST_EXCEPTION\nALL_COMPLETED: Final = concurrent.futures.ALL_COMPLETED\n\nif sys.version_info >= (3, 13):\n    @type_check_only\n    class _SyncAndAsyncIterator(Iterator[_T_co], AsyncIterator[_T_co], Protocol[_T_co]): ...\n\n    def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> _SyncAndAsyncIterator[Future[_T]]: ...\n\nelif sys.version_info >= (3, 10):\n    def as_completed(fs: Iterable[_FutureLike[_T]], *, timeout: float | None = None) -> Iterator[Future[_T]]: ...\n\nelse:\n    def as_completed(\n        fs: Iterable[_FutureLike[_T]], *, loop: AbstractEventLoop | None = None, timeout: float | None = None\n    ) -> Iterator[Future[_T]]: ...\n\n@overload\ndef ensure_future(coro_or_future: _FT, *, loop: AbstractEventLoop | None = None) -> _FT: ...  # type: ignore[overload-overlap]\n@overload\ndef ensure_future(coro_or_future: Awaitable[_T], *, loop: AbstractEventLoop | None = None) -> Task[_T]: ...\n\n# `gather()` actually returns a list with length equal to the number\n# of tasks passed; however, Tuple is used similar to the annotation for\n# zip() because typing does not support variadic type variables.  See\n# typing PR #1550 for discussion.\n#\n# N.B. Having overlapping overloads is the only way to get acceptable type inference in all edge cases.\nif sys.version_info >= (3, 10):\n    @overload\n    def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: Literal[False] = False) -> Future[tuple[_T1]]: ...  # type: ignore[overload-overlap]\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: Literal[False] = False\n    ) -> Future[tuple[_T1, _T2]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        /,\n        *,\n        return_exceptions: Literal[False] = False,\n    ) -> Future[tuple[_T1, _T2, _T3]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        /,\n        *,\n        return_exceptions: Literal[False] = False,\n    ) -> Future[tuple[_T1, _T2, _T3, _T4]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        coro_or_future5: _FutureLike[_T5],\n        /,\n        *,\n        return_exceptions: Literal[False] = False,\n    ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        coro_or_future5: _FutureLike[_T5],\n        coro_or_future6: _FutureLike[_T6],\n        /,\n        *,\n        return_exceptions: Literal[False] = False,\n    ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ...\n    @overload\n    def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: Literal[False] = False) -> Future[list[_T]]: ...  # type: ignore[overload-overlap]\n    @overload\n    def gather(coro_or_future1: _FutureLike[_T1], /, *, return_exceptions: bool) -> Future[tuple[_T1 | BaseException]]: ...\n    @overload\n    def gather(\n        coro_or_future1: _FutureLike[_T1], coro_or_future2: _FutureLike[_T2], /, *, return_exceptions: bool\n    ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ...\n    @overload\n    def gather(\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        /,\n        *,\n        return_exceptions: bool,\n    ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ...\n    @overload\n    def gather(\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        /,\n        *,\n        return_exceptions: bool,\n    ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ...\n    @overload\n    def gather(\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        coro_or_future5: _FutureLike[_T5],\n        /,\n        *,\n        return_exceptions: bool,\n    ) -> Future[\n        tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException, _T5 | BaseException]\n    ]: ...\n    @overload\n    def gather(\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        coro_or_future5: _FutureLike[_T5],\n        coro_or_future6: _FutureLike[_T6],\n        /,\n        *,\n        return_exceptions: bool,\n    ) -> Future[\n        tuple[\n            _T1 | BaseException,\n            _T2 | BaseException,\n            _T3 | BaseException,\n            _T4 | BaseException,\n            _T5 | BaseException,\n            _T6 | BaseException,\n        ]\n    ]: ...\n    @overload\n    def gather(*coros_or_futures: _FutureLike[_T], return_exceptions: bool) -> Future[list[_T | BaseException]]: ...\n\nelse:\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1], /, *, loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False\n    ) -> Future[tuple[_T1]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        /,\n        *,\n        loop: AbstractEventLoop | None = None,\n        return_exceptions: Literal[False] = False,\n    ) -> Future[tuple[_T1, _T2]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        /,\n        *,\n        loop: AbstractEventLoop | None = None,\n        return_exceptions: Literal[False] = False,\n    ) -> Future[tuple[_T1, _T2, _T3]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        /,\n        *,\n        loop: AbstractEventLoop | None = None,\n        return_exceptions: Literal[False] = False,\n    ) -> Future[tuple[_T1, _T2, _T3, _T4]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        coro_or_future5: _FutureLike[_T5],\n        /,\n        *,\n        loop: AbstractEventLoop | None = None,\n        return_exceptions: Literal[False] = False,\n    ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        coro_or_future5: _FutureLike[_T5],\n        coro_or_future6: _FutureLike[_T6],\n        /,\n        *,\n        loop: AbstractEventLoop | None = None,\n        return_exceptions: Literal[False] = False,\n    ) -> Future[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        *coros_or_futures: _FutureLike[_T], loop: AbstractEventLoop | None = None, return_exceptions: Literal[False] = False\n    ) -> Future[list[_T]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1], /, *, loop: AbstractEventLoop | None = None, return_exceptions: bool\n    ) -> Future[tuple[_T1 | BaseException]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        /,\n        *,\n        loop: AbstractEventLoop | None = None,\n        return_exceptions: bool,\n    ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        /,\n        *,\n        loop: AbstractEventLoop | None = None,\n        return_exceptions: bool,\n    ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        /,\n        *,\n        loop: AbstractEventLoop | None = None,\n        return_exceptions: bool,\n    ) -> Future[tuple[_T1 | BaseException, _T2 | BaseException, _T3 | BaseException, _T4 | BaseException]]: ...\n    @overload\n    def gather(  # type: ignore[overload-overlap]\n        coro_or_future1: _FutureLike[_T1],\n        coro_or_future2: _FutureLike[_T2],\n        coro_or_future3: _FutureLike[_T3],\n        coro_or_future4: _FutureLike[_T4],\n        coro_or_future5: _FutureLike[_T5],\n        coro_or_future6: _FutureLike[_T6],\n        /,\n        *,\n        loop: AbstractEventLoop | None = None,\n        return_exceptions: bool,\n    ) -> Future[\n        tuple[\n            _T1 | BaseException,\n            _T2 | BaseException,\n            _T3 | BaseException,\n            _T4 | BaseException,\n            _T5 | BaseException,\n            _T6 | BaseException,\n        ]\n    ]: ...\n    @overload\n    def gather(\n        *coros_or_futures: _FutureLike[_T], loop: AbstractEventLoop | None = None, return_exceptions: bool\n    ) -> Future[list[_T | BaseException]]: ...\n\n# unlike some asyncio apis, This does strict runtime checking of actually being a coroutine, not of any future-like.\ndef run_coroutine_threadsafe(coro: Coroutine[Any, Any, _T], loop: AbstractEventLoop) -> concurrent.futures.Future[_T]: ...\n\nif sys.version_info >= (3, 10):\n    def shield(arg: _FutureLike[_T]) -> Future[_T]: ...\n    @overload\n    async def sleep(delay: float) -> None: ...\n    @overload\n    async def sleep(delay: float, result: _T) -> _T: ...\n    async def wait_for(fut: _FutureLike[_T], timeout: float | None) -> _T: ...\n\nelse:\n    def shield(arg: _FutureLike[_T], *, loop: AbstractEventLoop | None = None) -> Future[_T]: ...\n    @overload\n    async def sleep(delay: float, *, loop: AbstractEventLoop | None = None) -> None: ...\n    @overload\n    async def sleep(delay: float, result: _T, *, loop: AbstractEventLoop | None = None) -> _T: ...\n    async def wait_for(fut: _FutureLike[_T], timeout: float | None, *, loop: AbstractEventLoop | None = None) -> _T: ...\n\nif sys.version_info >= (3, 11):\n    async def wait(\n        fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = \"ALL_COMPLETED\"\n    ) -> tuple[set[_FT], set[_FT]]: ...\n\nelif sys.version_info >= (3, 10):\n    @overload\n    async def wait(  # type: ignore[overload-overlap]\n        fs: Iterable[_FT], *, timeout: float | None = None, return_when: str = \"ALL_COMPLETED\"\n    ) -> tuple[set[_FT], set[_FT]]: ...\n    @overload\n    async def wait(\n        fs: Iterable[Awaitable[_T]], *, timeout: float | None = None, return_when: str = \"ALL_COMPLETED\"\n    ) -> tuple[set[Task[_T]], set[Task[_T]]]: ...\n\nelse:\n    @overload\n    async def wait(  # type: ignore[overload-overlap]\n        fs: Iterable[_FT],\n        *,\n        loop: AbstractEventLoop | None = None,\n        timeout: float | None = None,\n        return_when: str = \"ALL_COMPLETED\",\n    ) -> tuple[set[_FT], set[_FT]]: ...\n    @overload\n    async def wait(\n        fs: Iterable[Awaitable[_T]],\n        *,\n        loop: AbstractEventLoop | None = None,\n        timeout: float | None = None,\n        return_when: str = \"ALL_COMPLETED\",\n    ) -> tuple[set[Task[_T]], set[Task[_T]]]: ...\n\nif sys.version_info >= (3, 12):\n    _TaskCompatibleCoro: TypeAlias = Coroutine[Any, Any, _T_co]\nelse:\n    _TaskCompatibleCoro: TypeAlias = Generator[_TaskYieldType, None, _T_co] | Coroutine[Any, Any, _T_co]\n\ndef all_tasks(loop: AbstractEventLoop | None = None) -> set[Task[Any]]: ...\n\nif sys.version_info >= (3, 14):\n    def create_task(\n        coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None, eager_start: bool | None = None\n    ) -> Task[_T]: ...\n\nelif sys.version_info >= (3, 11):\n    def create_task(coro: _CoroutineLike[_T], *, name: str | None = None, context: Context | None = None) -> Task[_T]: ...\n\nelse:\n    def create_task(coro: _CoroutineLike[_T], *, name: str | None = None) -> Task[_T]: ...\n\nif sys.version_info >= (3, 12):\n    from _asyncio import current_task as current_task\nelse:\n    def current_task(loop: AbstractEventLoop | None = None) -> Task[Any] | None: ...\n\nif sys.version_info >= (3, 14):\n    def eager_task_factory(\n        loop: AbstractEventLoop | None,\n        coro: _TaskCompatibleCoro[_T_co],\n        *,\n        name: str | None = None,\n        context: Context | None = None,\n        eager_start: bool = True,\n    ) -> Task[_T_co]: ...\n\nelif sys.version_info >= (3, 12):\n    def eager_task_factory(\n        loop: AbstractEventLoop | None,\n        coro: _TaskCompatibleCoro[_T_co],\n        *,\n        name: str | None = None,\n        context: Context | None = None,\n    ) -> Task[_T_co]: ...\n\nif sys.version_info >= (3, 12):\n    _TaskT_co = TypeVar(\"_TaskT_co\", bound=Task[Any], covariant=True)\n\n    @type_check_only\n    class _CustomTaskConstructor(Protocol[_TaskT_co]):\n        def __call__(\n            self,\n            coro: _TaskCompatibleCoro[Any],\n            /,\n            *,\n            loop: AbstractEventLoop,\n            name: str | None,\n            context: Context | None,\n            eager_start: bool,\n        ) -> _TaskT_co: ...\n\n    @type_check_only\n    class _EagerTaskFactoryType(Protocol[_TaskT_co]):\n        def __call__(\n            self,\n            loop: AbstractEventLoop,\n            coro: _TaskCompatibleCoro[Any],\n            *,\n            name: str | None = None,\n            context: Context | None = None,\n        ) -> _TaskT_co: ...\n\n    def create_eager_task_factory(\n        custom_task_constructor: _CustomTaskConstructor[_TaskT_co],\n    ) -> _EagerTaskFactoryType[_TaskT_co]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/threads.pyi",
    "content": "from collections.abc import Callable\nfrom typing import TypeVar\nfrom typing_extensions import ParamSpec\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\n__all__ = (\"to_thread\",)\n_P = ParamSpec(\"_P\")\n_R = TypeVar(\"_R\")\n\nasync def to_thread(func: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/timeouts.pyi",
    "content": "from types import TracebackType\nfrom typing import final\nfrom typing_extensions import Self\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\n__all__ = (\"Timeout\", \"timeout\", \"timeout_at\")\n\n@final\nclass Timeout:\n    def __init__(self, when: float | None) -> None: ...\n    def when(self) -> float | None: ...\n    def reschedule(self, when: float | None) -> None: ...\n    def expired(self) -> bool: ...\n    async def __aenter__(self) -> Self: ...\n    async def __aexit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n\ndef timeout(delay: float | None) -> Timeout: ...\ndef timeout_at(when: float | None) -> Timeout: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/tools.pyi",
    "content": "import sys\nfrom collections.abc import Iterable\nfrom enum import Enum\nfrom typing import NamedTuple, SupportsIndex, type_check_only\n\n@type_check_only\nclass _AwaitedInfo(NamedTuple):  # AwaitedInfo_Type from _remote_debugging\n    thread_id: int\n    awaited_by: list[_TaskInfo]\n\n@type_check_only\nclass _TaskInfo(NamedTuple):  # TaskInfo_Type from _remote_debugging\n    task_id: int\n    task_name: str\n    coroutine_stack: list[_CoroInfo]\n    awaited_by: list[_CoroInfo]\n\n@type_check_only\nclass _CoroInfo(NamedTuple):  # CoroInfo_Type from _remote_debugging\n    call_stack: list[_FrameInfo]\n    task_name: int | str\n\n@type_check_only\nclass _FrameInfo(NamedTuple):  # FrameInfo_Type from _remote_debugging\n    filename: str\n    lineno: int\n    funcname: str\n\nclass NodeType(Enum):\n    COROUTINE = 1\n    TASK = 2\n\nclass CycleFoundException(Exception):\n    cycles: list[list[int]]\n    id2name: dict[int, str]\n    def __init__(self, cycles: list[list[int]], id2name: dict[int, str]) -> None: ...\n\ndef get_all_awaited_by(pid: SupportsIndex) -> list[_AwaitedInfo]: ...\ndef build_async_tree(result: Iterable[_AwaitedInfo], task_emoji: str = \"(T)\", cor_emoji: str = \"\") -> list[list[str]]: ...\ndef build_task_table(result: Iterable[_AwaitedInfo]) -> list[list[int | str]]: ...\n\nif sys.version_info >= (3, 14):\n    def exit_with_permission_help_text() -> None: ...\n\ndef display_awaited_by_tasks_table(pid: SupportsIndex) -> None: ...\ndef display_awaited_by_tasks_tree(pid: SupportsIndex) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/transports.pyi",
    "content": "from asyncio.events import AbstractEventLoop\nfrom asyncio.protocols import BaseProtocol\nfrom collections.abc import Iterable, Mapping\nfrom socket import _Address\nfrom typing import Any\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\n__all__ = (\"BaseTransport\", \"ReadTransport\", \"WriteTransport\", \"Transport\", \"DatagramTransport\", \"SubprocessTransport\")\n\nclass BaseTransport:\n    __slots__ = (\"_extra\",)\n    def __init__(self, extra: Mapping[str, Any] | None = None) -> None: ...\n    def get_extra_info(self, name: str, default: Any = None) -> Any: ...\n    def is_closing(self) -> bool: ...\n    def close(self) -> None: ...\n    def set_protocol(self, protocol: BaseProtocol) -> None: ...\n    def get_protocol(self) -> BaseProtocol: ...\n\nclass ReadTransport(BaseTransport):\n    __slots__ = ()\n    def is_reading(self) -> bool: ...\n    def pause_reading(self) -> None: ...\n    def resume_reading(self) -> None: ...\n\nclass WriteTransport(BaseTransport):\n    __slots__ = ()\n    def set_write_buffer_limits(self, high: int | None = None, low: int | None = None) -> None: ...\n    def get_write_buffer_size(self) -> int: ...\n    def get_write_buffer_limits(self) -> tuple[int, int]: ...\n    def write(self, data: bytes | bytearray | memoryview[Any]) -> None: ...  # any memoryview format or shape\n    def writelines(\n        self, list_of_data: Iterable[bytes | bytearray | memoryview[Any]]\n    ) -> None: ...  # any memoryview format or shape\n    def write_eof(self) -> None: ...\n    def can_write_eof(self) -> bool: ...\n    def abort(self) -> None: ...\n\nclass Transport(ReadTransport, WriteTransport):\n    __slots__ = ()\n\nclass DatagramTransport(BaseTransport):\n    __slots__ = ()\n    def sendto(self, data: bytes | bytearray | memoryview, addr: _Address | None = None) -> None: ...\n    def abort(self) -> None: ...\n\nclass SubprocessTransport(BaseTransport):\n    __slots__ = ()\n    def get_pid(self) -> int: ...\n    def get_returncode(self) -> int | None: ...\n    def get_pipe_transport(self, fd: int) -> BaseTransport | None: ...\n    def send_signal(self, signal: int) -> None: ...\n    def terminate(self) -> None: ...\n    def kill(self) -> None: ...\n\nclass _FlowControlMixin(Transport):\n    __slots__ = (\"_loop\", \"_protocol_paused\", \"_high_water\", \"_low_water\")\n    def __init__(self, extra: Mapping[str, Any] | None = None, loop: AbstractEventLoop | None = None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/trsock.pyi",
    "content": "import socket\nimport sys\nfrom _typeshed import ReadableBuffer\nfrom builtins import type as Type  # alias to avoid name clashes with property named \"type\"\nfrom collections.abc import Iterable\nfrom types import TracebackType\nfrom typing import Any, BinaryIO, NoReturn, overload\nfrom typing_extensions import TypeAlias, deprecated\n\n# These are based in socket, maybe move them out into _typeshed.pyi or such\n_Address: TypeAlias = socket._Address\n_RetAddress: TypeAlias = Any\n_WriteBuffer: TypeAlias = bytearray | memoryview\n_CMSG: TypeAlias = tuple[int, int, bytes]\n\nclass TransportSocket:\n    __slots__ = (\"_sock\",)\n    def __init__(self, sock: socket.socket) -> None: ...\n    @property\n    def family(self) -> int: ...\n    @property\n    def type(self) -> int: ...\n    @property\n    def proto(self) -> int: ...\n    def __getstate__(self) -> NoReturn: ...\n    def fileno(self) -> int: ...\n    def dup(self) -> socket.socket: ...\n    def get_inheritable(self) -> bool: ...\n    def shutdown(self, how: int) -> None: ...\n    @overload\n    def getsockopt(self, level: int, optname: int) -> int: ...\n    @overload\n    def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ...\n    @overload\n    def setsockopt(self, level: int, optname: int, value: int | ReadableBuffer) -> None: ...\n    @overload\n    def setsockopt(self, level: int, optname: int, value: None, optlen: int) -> None: ...\n    def getpeername(self) -> _RetAddress: ...\n    def getsockname(self) -> _RetAddress: ...\n    def getsockbyname(self) -> NoReturn: ...  # This method doesn't exist on socket, yet is passed through?\n    def settimeout(self, value: float | None) -> None: ...\n    def gettimeout(self) -> float | None: ...\n    def setblocking(self, flag: bool) -> None: ...\n    if sys.version_info < (3, 11):\n        def _na(self, what: str) -> None: ...\n        @deprecated(\"Removed in Python 3.11\")\n        def accept(self) -> tuple[socket.socket, _RetAddress]: ...\n        @deprecated(\"Removed in Python 3.11\")\n        def connect(self, address: _Address) -> None: ...\n        @deprecated(\"Removed in Python 3.11\")\n        def connect_ex(self, address: _Address) -> int: ...\n        @deprecated(\"Removed in Python 3.11\")\n        def bind(self, address: _Address) -> None: ...\n        if sys.platform == \"win32\":\n            @deprecated(\"Removed in Python 3.11\")\n            def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> None: ...\n        else:\n            @deprecated(\"Removed in Python 3.11\")\n            def ioctl(self, control: int, option: int | tuple[int, int, int] | bool) -> NoReturn: ...\n\n        @deprecated(\"Removed in Python 3.11\")\n        def listen(self, backlog: int = ..., /) -> None: ...\n        @deprecated(\"Removed in Python 3.11\")\n        def makefile(self) -> BinaryIO: ...\n        @deprecated(\"Removed in Python 3.11\")\n        def sendfile(self, file: BinaryIO, offset: int = 0, count: int | None = None) -> int: ...\n        @deprecated(\"Removed in Python 3.11\")\n        def close(self) -> None: ...\n        @deprecated(\"Removed in Python 3.11\")\n        def detach(self) -> int: ...\n        if sys.platform == \"linux\":\n            @deprecated(\"Removed in Python 3.11\")\n            def sendmsg_afalg(\n                self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0\n            ) -> int: ...\n        else:\n            @deprecated(\"Removed in Python 3.11.\")\n            def sendmsg_afalg(\n                self, msg: Iterable[ReadableBuffer] = ..., *, op: int, iv: Any = ..., assoclen: int = ..., flags: int = 0\n            ) -> NoReturn: ...\n\n        @deprecated(\"Removed in Python 3.11.\")\n        def sendmsg(\n            self,\n            buffers: Iterable[ReadableBuffer],\n            ancdata: Iterable[_CMSG] = ...,\n            flags: int = 0,\n            address: _Address | None = None,\n            /,\n        ) -> int: ...\n        @overload\n        @deprecated(\"Removed in Python 3.11.\")\n        def sendto(self, data: ReadableBuffer, address: _Address) -> int: ...\n        @overload\n        @deprecated(\"Removed in Python 3.11.\")\n        def sendto(self, data: ReadableBuffer, flags: int, address: _Address) -> int: ...\n        @deprecated(\"Removed in Python 3.11.\")\n        def send(self, data: ReadableBuffer, flags: int = 0) -> int: ...\n        @deprecated(\"Removed in Python 3.11.\")\n        def sendall(self, data: ReadableBuffer, flags: int = 0) -> None: ...\n        @deprecated(\"Removed in Python 3.11.\")\n        def set_inheritable(self, inheritable: bool) -> None: ...\n        if sys.platform == \"win32\":\n            @deprecated(\"Removed in Python 3.11.\")\n            def share(self, process_id: int) -> bytes: ...\n        else:\n            @deprecated(\"Removed in Python 3.11.\")\n            def share(self, process_id: int) -> NoReturn: ...\n\n        @deprecated(\"Removed in Python 3.11.\")\n        def recv_into(self, buffer: _WriteBuffer, nbytes: int = 0, flags: int = 0) -> int: ...\n        @deprecated(\"Removed in Python 3.11.\")\n        def recvfrom_into(self, buffer: _WriteBuffer, nbytes: int = 0, flags: int = 0) -> tuple[int, _RetAddress]: ...\n        @deprecated(\"Removed in Python 3.11.\")\n        def recvmsg_into(\n            self, buffers: Iterable[_WriteBuffer], ancbufsize: int = 0, flags: int = 0, /\n        ) -> tuple[int, list[_CMSG], int, Any]: ...\n        @deprecated(\"Removed in Python 3.11.\")\n        def recvmsg(self, bufsize: int, ancbufsize: int = 0, flags: int = 0, /) -> tuple[bytes, list[_CMSG], int, Any]: ...\n        @deprecated(\"Removed in Python 3.11.\")\n        def recvfrom(self, bufsize: int, flags: int = 0) -> tuple[bytes, _RetAddress]: ...\n        @deprecated(\"Removed in Python 3.11.\")\n        def recv(self, bufsize: int, flags: int = 0) -> bytes: ...\n        @deprecated(\"Removed in Python 3.11.\")\n        def __enter__(self) -> socket.socket: ...\n        @deprecated(\"Removed in Python 3.11.\")\n        def __exit__(\n            self, exc_type: Type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n        ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/unix_events.pyi",
    "content": "import sys\nimport types\nfrom _typeshed import StrPath\nfrom abc import ABCMeta, abstractmethod\nfrom collections.abc import Callable\nfrom socket import socket\nfrom typing import Literal\nfrom typing_extensions import Self, TypeVarTuple, Unpack, deprecated\n\nfrom . import events\nfrom .base_events import Server, _ProtocolFactory, _SSLContext\nfrom .selector_events import BaseSelectorEventLoop\n\n_Ts = TypeVarTuple(\"_Ts\")\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.platform != \"win32\":\n    if sys.version_info >= (3, 14):\n        __all__ = (\"SelectorEventLoop\", \"EventLoop\")\n    elif sys.version_info >= (3, 13):\n        # Adds EventLoop\n        __all__ = (\n            \"SelectorEventLoop\",\n            \"AbstractChildWatcher\",\n            \"SafeChildWatcher\",\n            \"FastChildWatcher\",\n            \"PidfdChildWatcher\",\n            \"MultiLoopChildWatcher\",\n            \"ThreadedChildWatcher\",\n            \"DefaultEventLoopPolicy\",\n            \"EventLoop\",\n        )\n    else:\n        # adds PidfdChildWatcher\n        __all__ = (\n            \"SelectorEventLoop\",\n            \"AbstractChildWatcher\",\n            \"SafeChildWatcher\",\n            \"FastChildWatcher\",\n            \"PidfdChildWatcher\",\n            \"MultiLoopChildWatcher\",\n            \"ThreadedChildWatcher\",\n            \"DefaultEventLoopPolicy\",\n        )\n\n# This is also technically not available on Win,\n# but other parts of typeshed need this definition.\n# So, it is special cased.\nif sys.version_info < (3, 14):\n    if sys.version_info >= (3, 12):\n        @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14.\")\n        class AbstractChildWatcher:\n            @abstractmethod\n            def add_child_handler(\n                self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]\n            ) -> None: ...\n            @abstractmethod\n            def remove_child_handler(self, pid: int) -> bool: ...\n            @abstractmethod\n            def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...\n            @abstractmethod\n            def close(self) -> None: ...\n            @abstractmethod\n            def __enter__(self) -> Self: ...\n            @abstractmethod\n            def __exit__(\n                self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None\n            ) -> None: ...\n            @abstractmethod\n            def is_active(self) -> bool: ...\n\n    else:\n        class AbstractChildWatcher:\n            @abstractmethod\n            def add_child_handler(\n                self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]\n            ) -> None: ...\n            @abstractmethod\n            def remove_child_handler(self, pid: int) -> bool: ...\n            @abstractmethod\n            def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...\n            @abstractmethod\n            def close(self) -> None: ...\n            @abstractmethod\n            def __enter__(self) -> Self: ...\n            @abstractmethod\n            def __exit__(\n                self, typ: type[BaseException] | None, exc: BaseException | None, tb: types.TracebackType | None\n            ) -> None: ...\n            @abstractmethod\n            def is_active(self) -> bool: ...\n\nif sys.platform != \"win32\":\n    if sys.version_info < (3, 14):\n        if sys.version_info >= (3, 12):\n            # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub.\n            # See discussion in #7412\n            class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta):\n                def close(self) -> None: ...\n                def is_active(self) -> bool: ...\n                def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...\n\n            @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14.\")\n            class SafeChildWatcher(BaseChildWatcher):\n                def __enter__(self) -> Self: ...\n                def __exit__(\n                    self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None\n                ) -> None: ...\n                def add_child_handler(\n                    self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]\n                ) -> None: ...\n                def remove_child_handler(self, pid: int) -> bool: ...\n\n            @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14.\")\n            class FastChildWatcher(BaseChildWatcher):\n                def __enter__(self) -> Self: ...\n                def __exit__(\n                    self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None\n                ) -> None: ...\n                def add_child_handler(\n                    self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]\n                ) -> None: ...\n                def remove_child_handler(self, pid: int) -> bool: ...\n\n        else:\n            # Doesn't actually have ABCMeta metaclass at runtime, but mypy complains if we don't have it in the stub.\n            # See discussion in #7412\n            class BaseChildWatcher(AbstractChildWatcher, metaclass=ABCMeta):\n                def close(self) -> None: ...\n                def is_active(self) -> bool: ...\n                def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...\n\n            class SafeChildWatcher(BaseChildWatcher):\n                def __enter__(self) -> Self: ...\n                def __exit__(\n                    self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None\n                ) -> None: ...\n                def add_child_handler(\n                    self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]\n                ) -> None: ...\n                def remove_child_handler(self, pid: int) -> bool: ...\n\n            class FastChildWatcher(BaseChildWatcher):\n                def __enter__(self) -> Self: ...\n                def __exit__(\n                    self, a: type[BaseException] | None, b: BaseException | None, c: types.TracebackType | None\n                ) -> None: ...\n                def add_child_handler(\n                    self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]\n                ) -> None: ...\n                def remove_child_handler(self, pid: int) -> bool: ...\n\n    class _UnixSelectorEventLoop(BaseSelectorEventLoop):\n        if sys.version_info >= (3, 13):\n            async def create_unix_server(\n                self,\n                protocol_factory: _ProtocolFactory,\n                path: StrPath | None = None,\n                *,\n                sock: socket | None = None,\n                backlog: int = 100,\n                ssl: _SSLContext = None,\n                ssl_handshake_timeout: float | None = None,\n                ssl_shutdown_timeout: float | None = None,\n                start_serving: bool = True,\n                cleanup_socket: bool = True,\n            ) -> Server: ...\n\n    if sys.version_info >= (3, 14):\n        class _UnixDefaultEventLoopPolicy(events._BaseDefaultEventLoopPolicy): ...\n    else:\n        class _UnixDefaultEventLoopPolicy(events.BaseDefaultEventLoopPolicy):\n            if sys.version_info >= (3, 12):\n                @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14.\")\n                def get_child_watcher(self) -> AbstractChildWatcher: ...\n                @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14.\")\n                def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ...\n            else:\n                def get_child_watcher(self) -> AbstractChildWatcher: ...\n                def set_child_watcher(self, watcher: AbstractChildWatcher | None) -> None: ...\n\n    SelectorEventLoop = _UnixSelectorEventLoop\n\n    if sys.version_info >= (3, 14):\n        _DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy\n    else:\n        DefaultEventLoopPolicy = _UnixDefaultEventLoopPolicy\n\n    if sys.version_info >= (3, 13):\n        EventLoop = SelectorEventLoop\n\n    if sys.version_info < (3, 14):\n        if sys.version_info >= (3, 12):\n            @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14.\")\n            class MultiLoopChildWatcher(AbstractChildWatcher):\n                def is_active(self) -> bool: ...\n                def close(self) -> None: ...\n                def __enter__(self) -> Self: ...\n                def __exit__(\n                    self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None\n                ) -> None: ...\n                def add_child_handler(\n                    self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]\n                ) -> None: ...\n                def remove_child_handler(self, pid: int) -> bool: ...\n                def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...\n\n        else:\n            class MultiLoopChildWatcher(AbstractChildWatcher):\n                def is_active(self) -> bool: ...\n                def close(self) -> None: ...\n                def __enter__(self) -> Self: ...\n                def __exit__(\n                    self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None\n                ) -> None: ...\n                def add_child_handler(\n                    self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]\n                ) -> None: ...\n                def remove_child_handler(self, pid: int) -> bool: ...\n                def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...\n\n    if sys.version_info < (3, 14):\n        class ThreadedChildWatcher(AbstractChildWatcher):\n            def is_active(self) -> Literal[True]: ...\n            def close(self) -> None: ...\n            def __enter__(self) -> Self: ...\n            def __exit__(\n                self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None\n            ) -> None: ...\n            def __del__(self) -> None: ...\n            def add_child_handler(\n                self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]\n            ) -> None: ...\n            def remove_child_handler(self, pid: int) -> bool: ...\n            def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...\n\n        class PidfdChildWatcher(AbstractChildWatcher):\n            def __enter__(self) -> Self: ...\n            def __exit__(\n                self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None\n            ) -> None: ...\n            def is_active(self) -> bool: ...\n            def close(self) -> None: ...\n            def attach_loop(self, loop: events.AbstractEventLoop | None) -> None: ...\n            def add_child_handler(\n                self, pid: int, callback: Callable[[int, int, Unpack[_Ts]], object], *args: Unpack[_Ts]\n            ) -> None: ...\n            def remove_child_handler(self, pid: int) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/windows_events.pyi",
    "content": "import socket\nimport sys\nfrom _typeshed import Incomplete, ReadableBuffer, WriteableBuffer\nfrom collections.abc import Callable\nfrom typing import IO, Any, ClassVar, Final, NoReturn\n\nfrom . import events, futures, proactor_events, selector_events, streams, windows_utils\n\n# Keep asyncio.__all__ updated with any changes to __all__ here\nif sys.platform == \"win32\":\n    if sys.version_info >= (3, 14):\n        __all__ = (\n            \"SelectorEventLoop\",\n            \"ProactorEventLoop\",\n            \"IocpProactor\",\n            \"_DefaultEventLoopPolicy\",\n            \"_WindowsSelectorEventLoopPolicy\",\n            \"_WindowsProactorEventLoopPolicy\",\n            \"EventLoop\",\n        )\n    elif sys.version_info >= (3, 13):\n        # 3.13 added `EventLoop`.\n        __all__ = (\n            \"SelectorEventLoop\",\n            \"ProactorEventLoop\",\n            \"IocpProactor\",\n            \"DefaultEventLoopPolicy\",\n            \"WindowsSelectorEventLoopPolicy\",\n            \"WindowsProactorEventLoopPolicy\",\n            \"EventLoop\",\n        )\n    else:\n        __all__ = (\n            \"SelectorEventLoop\",\n            \"ProactorEventLoop\",\n            \"IocpProactor\",\n            \"DefaultEventLoopPolicy\",\n            \"WindowsSelectorEventLoopPolicy\",\n            \"WindowsProactorEventLoopPolicy\",\n        )\n\n    NULL: Final = 0\n    INFINITE: Final = 0xFFFFFFFF\n    ERROR_CONNECTION_REFUSED: Final = 1225\n    ERROR_CONNECTION_ABORTED: Final = 1236\n    CONNECT_PIPE_INIT_DELAY: float\n    CONNECT_PIPE_MAX_DELAY: float\n\n    class PipeServer:\n        def __init__(self, address: str) -> None: ...\n        def __del__(self) -> None: ...\n        def closed(self) -> bool: ...\n        def close(self) -> None: ...\n\n    class _WindowsSelectorEventLoop(selector_events.BaseSelectorEventLoop): ...\n\n    class ProactorEventLoop(proactor_events.BaseProactorEventLoop):\n        def __init__(self, proactor: IocpProactor | None = None) -> None: ...\n        async def create_pipe_connection(\n            self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str\n        ) -> tuple[proactor_events._ProactorDuplexPipeTransport, streams.StreamReaderProtocol]: ...\n        async def start_serving_pipe(\n            self, protocol_factory: Callable[[], streams.StreamReaderProtocol], address: str\n        ) -> list[PipeServer]: ...\n\n    class IocpProactor:\n        def __init__(self, concurrency: int = 0xFFFFFFFF) -> None: ...\n        def __del__(self) -> None: ...\n        def set_loop(self, loop: events.AbstractEventLoop) -> None: ...\n        def select(self, timeout: int | None = None) -> list[futures.Future[Any]]: ...\n        def recv(self, conn: socket.socket, nbytes: int, flags: int = 0) -> futures.Future[bytes]: ...\n        def recv_into(self, conn: socket.socket, buf: WriteableBuffer, flags: int = 0) -> futures.Future[Any]: ...\n        def recvfrom(\n            self, conn: socket.socket, nbytes: int, flags: int = 0\n        ) -> futures.Future[tuple[bytes, socket._RetAddress]]: ...\n        def sendto(\n            self, conn: socket.socket, buf: ReadableBuffer, flags: int = 0, addr: socket._Address | None = None\n        ) -> futures.Future[int]: ...\n        def send(self, conn: socket.socket, buf: WriteableBuffer, flags: int = 0) -> futures.Future[Any]: ...\n        def accept(self, listener: socket.socket) -> futures.Future[Any]: ...\n        def connect(\n            self,\n            conn: socket.socket,\n            address: tuple[Incomplete, Incomplete] | tuple[Incomplete, Incomplete, Incomplete, Incomplete],\n        ) -> futures.Future[Any]: ...\n        def sendfile(self, sock: socket.socket, file: IO[bytes], offset: int, count: int) -> futures.Future[Any]: ...\n        def accept_pipe(self, pipe: socket.socket) -> futures.Future[Any]: ...\n        async def connect_pipe(self, address: str) -> windows_utils.PipeHandle: ...\n        def wait_for_handle(self, handle: windows_utils.PipeHandle, timeout: int | None = None) -> bool: ...\n        def close(self) -> None: ...\n        if sys.version_info >= (3, 11):\n            def recvfrom_into(\n                self, conn: socket.socket, buf: WriteableBuffer, flags: int = 0\n            ) -> futures.Future[tuple[int, socket._RetAddress]]: ...\n\n    SelectorEventLoop = _WindowsSelectorEventLoop\n\n    if sys.version_info >= (3, 14):\n        class _WindowsSelectorEventLoopPolicy(events._BaseDefaultEventLoopPolicy):\n            _loop_factory: ClassVar[type[SelectorEventLoop]]\n\n        class _WindowsProactorEventLoopPolicy(events._BaseDefaultEventLoopPolicy):\n            _loop_factory: ClassVar[type[ProactorEventLoop]]\n\n    else:\n        class WindowsSelectorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):\n            _loop_factory: ClassVar[type[SelectorEventLoop]]\n            def get_child_watcher(self) -> NoReturn: ...\n            def set_child_watcher(self, watcher: Any) -> NoReturn: ...\n\n        class WindowsProactorEventLoopPolicy(events.BaseDefaultEventLoopPolicy):\n            _loop_factory: ClassVar[type[ProactorEventLoop]]\n            def get_child_watcher(self) -> NoReturn: ...\n            def set_child_watcher(self, watcher: Any) -> NoReturn: ...\n\n    if sys.version_info >= (3, 14):\n        _DefaultEventLoopPolicy = _WindowsProactorEventLoopPolicy\n    else:\n        DefaultEventLoopPolicy = WindowsProactorEventLoopPolicy\n    if sys.version_info >= (3, 13):\n        EventLoop = ProactorEventLoop\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncio/windows_utils.pyi",
    "content": "import subprocess\nimport sys\nfrom collections.abc import Callable\nfrom types import TracebackType\nfrom typing import Any, AnyStr, Final\nfrom typing_extensions import Self\n\nif sys.platform == \"win32\":\n    __all__ = (\"pipe\", \"Popen\", \"PIPE\", \"PipeHandle\")\n\n    BUFSIZE: Final = 8192\n    PIPE: Final = subprocess.PIPE\n    STDOUT: Final = subprocess.STDOUT\n    def pipe(*, duplex: bool = False, overlapped: tuple[bool, bool] = (True, True), bufsize: int = 8192) -> tuple[int, int]: ...\n\n    class PipeHandle:\n        def __init__(self, handle: int) -> None: ...\n        def __del__(self) -> None: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ...\n        @property\n        def handle(self) -> int: ...\n        def fileno(self) -> int: ...\n        def close(self, *, CloseHandle: Callable[[int], object] = ...) -> None: ...\n\n    class Popen(subprocess.Popen[AnyStr]):\n        stdin: PipeHandle | None  # type: ignore[assignment]\n        stdout: PipeHandle | None  # type: ignore[assignment]\n        stderr: PipeHandle | None  # type: ignore[assignment]\n        # For simplicity we omit the full overloaded __new__ signature of\n        # subprocess.Popen. The arguments are mostly the same, but\n        # subprocess.Popen takes other positional-or-keyword arguments before\n        # stdin.\n        def __new__(\n            cls,\n            args: subprocess._CMD,\n            stdin: subprocess._FILE | None = None,\n            stdout: subprocess._FILE | None = None,\n            stderr: subprocess._FILE | None = None,\n            **kwds: Any,\n        ) -> Self: ...\n        def __init__(\n            self,\n            args: subprocess._CMD,\n            stdin: subprocess._FILE | None = None,\n            stdout: subprocess._FILE | None = None,\n            stderr: subprocess._FILE | None = None,\n            **kwds: Any,\n        ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/asyncore.pyi",
    "content": "import sys\nfrom _typeshed import FileDescriptorLike, ReadableBuffer\nfrom socket import socket\nfrom typing import Any, overload\nfrom typing_extensions import TypeAlias\n\n# cyclic dependence with asynchat\n_MapType: TypeAlias = dict[int, Any]\n_Socket: TypeAlias = socket\n\nsocket_map: _MapType  # undocumented\n\nclass ExitNow(Exception): ...\n\ndef read(obj: Any) -> None: ...\ndef write(obj: Any) -> None: ...\ndef readwrite(obj: Any, flags: int) -> None: ...\ndef poll(timeout: float = 0.0, map: _MapType | None = None) -> None: ...\ndef poll2(timeout: float = 0.0, map: _MapType | None = None) -> None: ...\n\npoll3 = poll2\n\ndef loop(timeout: float = 30.0, use_poll: bool = False, map: _MapType | None = None, count: int | None = None) -> None: ...\n\n# Not really subclass of socket.socket; it's only delegation.\n# It is not covariant to it.\nclass dispatcher:\n    debug: bool\n    connected: bool\n    accepting: bool\n    connecting: bool\n    closing: bool\n    ignore_log_types: frozenset[str]\n    socket: _Socket | None\n    def __init__(self, sock: _Socket | None = None, map: _MapType | None = None) -> None: ...\n    def add_channel(self, map: _MapType | None = None) -> None: ...\n    def del_channel(self, map: _MapType | None = None) -> None: ...\n    def create_socket(self, family: int = ..., type: int = ...) -> None: ...\n    def set_socket(self, sock: _Socket, map: _MapType | None = None) -> None: ...\n    def set_reuse_addr(self) -> None: ...\n    def readable(self) -> bool: ...\n    def writable(self) -> bool: ...\n    def listen(self, num: int) -> None: ...\n    def bind(self, addr: tuple[Any, ...] | str) -> None: ...\n    def connect(self, address: tuple[Any, ...] | str) -> None: ...\n    def accept(self) -> tuple[_Socket, Any] | None: ...\n    def send(self, data: ReadableBuffer) -> int: ...\n    def recv(self, buffer_size: int) -> bytes: ...\n    def close(self) -> None: ...\n    def log(self, message: Any) -> None: ...\n    def log_info(self, message: Any, type: str = \"info\") -> None: ...\n    def handle_read_event(self) -> None: ...\n    def handle_connect_event(self) -> None: ...\n    def handle_write_event(self) -> None: ...\n    def handle_expt_event(self) -> None: ...\n    def handle_error(self) -> None: ...\n    def handle_expt(self) -> None: ...\n    def handle_read(self) -> None: ...\n    def handle_write(self) -> None: ...\n    def handle_connect(self) -> None: ...\n    def handle_accept(self) -> None: ...\n    def handle_close(self) -> None: ...\n\nclass dispatcher_with_send(dispatcher):\n    def initiate_send(self) -> None: ...\n    # incompatible signature:\n    # def send(self, data: bytes) -> int | None: ...\n\ndef compact_traceback() -> tuple[tuple[str, str, str], type, type, str]: ...\ndef close_all(map: _MapType | None = None, ignore_all: bool = False) -> None: ...\n\nif sys.platform != \"win32\":\n    class file_wrapper:\n        fd: int\n        def __init__(self, fd: int) -> None: ...\n        def recv(self, bufsize: int, flags: int = ...) -> bytes: ...\n        def send(self, data: bytes, flags: int = ...) -> int: ...\n        @overload\n        def getsockopt(self, level: int, optname: int, buflen: None = None) -> int: ...\n        @overload\n        def getsockopt(self, level: int, optname: int, buflen: int) -> bytes: ...\n        def read(self, bufsize: int, flags: int = ...) -> bytes: ...\n        def write(self, data: bytes, flags: int = ...) -> int: ...\n        def close(self) -> None: ...\n        def fileno(self) -> int: ...\n        def __del__(self) -> None: ...\n\n    class file_dispatcher(dispatcher):\n        def __init__(self, fd: FileDescriptorLike, map: _MapType | None = None) -> None: ...\n        def set_file(self, fd: int) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/atexit.pyi",
    "content": "from collections.abc import Callable\nfrom typing import TypeVar\nfrom typing_extensions import ParamSpec\n\n_T = TypeVar(\"_T\")\n_P = ParamSpec(\"_P\")\n\ndef _clear() -> None: ...\ndef _ncallbacks() -> int: ...\ndef _run_exitfuncs() -> None: ...\ndef register(func: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Callable[_P, _T]: ...\ndef unregister(func: Callable[..., object], /) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/audioop.pyi",
    "content": "from typing_extensions import Buffer, TypeAlias\n\n_AdpcmState: TypeAlias = tuple[int, int]\n_RatecvState: TypeAlias = tuple[int, tuple[tuple[int, int], ...]]\n\nclass error(Exception): ...\n\ndef add(fragment1: Buffer, fragment2: Buffer, width: int, /) -> bytes: ...\ndef adpcm2lin(fragment: Buffer, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ...\ndef alaw2lin(fragment: Buffer, width: int, /) -> bytes: ...\ndef avg(fragment: Buffer, width: int, /) -> int: ...\ndef avgpp(fragment: Buffer, width: int, /) -> int: ...\ndef bias(fragment: Buffer, width: int, bias: int, /) -> bytes: ...\ndef byteswap(fragment: Buffer, width: int, /) -> bytes: ...\ndef cross(fragment: Buffer, width: int, /) -> int: ...\ndef findfactor(fragment: Buffer, reference: Buffer, /) -> float: ...\ndef findfit(fragment: Buffer, reference: Buffer, /) -> tuple[int, float]: ...\ndef findmax(fragment: Buffer, length: int, /) -> int: ...\ndef getsample(fragment: Buffer, width: int, index: int, /) -> int: ...\ndef lin2adpcm(fragment: Buffer, width: int, state: _AdpcmState | None, /) -> tuple[bytes, _AdpcmState]: ...\ndef lin2alaw(fragment: Buffer, width: int, /) -> bytes: ...\ndef lin2lin(fragment: Buffer, width: int, newwidth: int, /) -> bytes: ...\ndef lin2ulaw(fragment: Buffer, width: int, /) -> bytes: ...\ndef max(fragment: Buffer, width: int, /) -> int: ...\ndef maxpp(fragment: Buffer, width: int, /) -> int: ...\ndef minmax(fragment: Buffer, width: int, /) -> tuple[int, int]: ...\ndef mul(fragment: Buffer, width: int, factor: float, /) -> bytes: ...\ndef ratecv(\n    fragment: Buffer,\n    width: int,\n    nchannels: int,\n    inrate: int,\n    outrate: int,\n    state: _RatecvState | None,\n    weightA: int = 1,\n    weightB: int = 0,\n    /,\n) -> tuple[bytes, _RatecvState]: ...\ndef reverse(fragment: Buffer, width: int, /) -> bytes: ...\ndef rms(fragment: Buffer, width: int, /) -> int: ...\ndef tomono(fragment: Buffer, width: int, lfactor: float, rfactor: float, /) -> bytes: ...\ndef tostereo(fragment: Buffer, width: int, lfactor: float, rfactor: float, /) -> bytes: ...\ndef ulaw2lin(fragment: Buffer, width: int, /) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/base64.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom typing import IO\n\n__all__ = [\n    \"encode\",\n    \"decode\",\n    \"encodebytes\",\n    \"decodebytes\",\n    \"b64encode\",\n    \"b64decode\",\n    \"b32encode\",\n    \"b32decode\",\n    \"b16encode\",\n    \"b16decode\",\n    \"b85encode\",\n    \"b85decode\",\n    \"a85encode\",\n    \"a85decode\",\n    \"standard_b64encode\",\n    \"standard_b64decode\",\n    \"urlsafe_b64encode\",\n    \"urlsafe_b64decode\",\n]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"b32hexencode\", \"b32hexdecode\"]\nif sys.version_info >= (3, 13):\n    __all__ += [\"z85decode\", \"z85encode\"]\n\ndef b64encode(s: ReadableBuffer, altchars: ReadableBuffer | None = None) -> bytes: ...\ndef b64decode(s: str | ReadableBuffer, altchars: str | ReadableBuffer | None = None, validate: bool = False) -> bytes: ...\ndef standard_b64encode(s: ReadableBuffer) -> bytes: ...\ndef standard_b64decode(s: str | ReadableBuffer) -> bytes: ...\ndef urlsafe_b64encode(s: ReadableBuffer) -> bytes: ...\ndef urlsafe_b64decode(s: str | ReadableBuffer) -> bytes: ...\ndef b32encode(s: ReadableBuffer) -> bytes: ...\ndef b32decode(s: str | ReadableBuffer, casefold: bool = False, map01: str | ReadableBuffer | None = None) -> bytes: ...\ndef b16encode(s: ReadableBuffer) -> bytes: ...\ndef b16decode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: ...\n\nif sys.version_info >= (3, 10):\n    def b32hexencode(s: ReadableBuffer) -> bytes: ...\n    def b32hexdecode(s: str | ReadableBuffer, casefold: bool = False) -> bytes: ...\n\ndef a85encode(\n    b: ReadableBuffer, *, foldspaces: bool = False, wrapcol: int = 0, pad: bool = False, adobe: bool = False\n) -> bytes: ...\ndef a85decode(\n    b: str | ReadableBuffer, *, foldspaces: bool = False, adobe: bool = False, ignorechars: bytearray | bytes = b\" \\t\\n\\r\\x0b\"\n) -> bytes: ...\ndef b85encode(b: ReadableBuffer, pad: bool = False) -> bytes: ...\ndef b85decode(b: str | ReadableBuffer) -> bytes: ...\ndef decode(input: IO[bytes], output: IO[bytes]) -> None: ...\ndef encode(input: IO[bytes], output: IO[bytes]) -> None: ...\ndef encodebytes(s: ReadableBuffer) -> bytes: ...\ndef decodebytes(s: ReadableBuffer) -> bytes: ...\n\nif sys.version_info >= (3, 13):\n    def z85encode(s: ReadableBuffer) -> bytes: ...\n    def z85decode(s: str | ReadableBuffer) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/bdb.pyi",
    "content": "import sys\nfrom _typeshed import ExcInfo, TraceFunction, Unused\nfrom collections.abc import Callable, Iterable, Iterator, Mapping\nfrom contextlib import contextmanager\nfrom types import CodeType, FrameType, TracebackType\nfrom typing import IO, Any, Final, Literal, SupportsInt, TypeVar\nfrom typing_extensions import ParamSpec, TypeAlias\n\n__all__ = [\"BdbQuit\", \"Bdb\", \"Breakpoint\"]\n\n_T = TypeVar(\"_T\")\n_P = ParamSpec(\"_P\")\n_Backend: TypeAlias = Literal[\"settrace\", \"monitoring\"]\n\n# A union of code-object flags at runtime.\n# The exact values of code-object flags are implementation details,\n# so we don't include the value of this constant in the stubs.\nGENERATOR_AND_COROUTINE_FLAGS: Final[int]\n\nclass BdbQuit(Exception): ...\n\nclass Bdb:\n    skip: set[str] | None\n    breaks: dict[str, list[int]]\n    fncache: dict[str, str]\n    frame_returning: FrameType | None\n    botframe: FrameType | None\n    quitting: bool\n    stopframe: FrameType | None\n    returnframe: FrameType | None\n    stoplineno: int\n    if sys.version_info >= (3, 14):\n        backend: _Backend\n        def __init__(self, skip: Iterable[str] | None = None, backend: _Backend = \"settrace\") -> None: ...\n    else:\n        def __init__(self, skip: Iterable[str] | None = None) -> None: ...\n\n    def canonic(self, filename: str) -> str: ...\n    def reset(self) -> None: ...\n    if sys.version_info >= (3, 12):\n        @contextmanager\n        def set_enterframe(self, frame: FrameType) -> Iterator[None]: ...\n\n    def trace_dispatch(self, frame: FrameType, event: str, arg: Any) -> TraceFunction: ...\n    def dispatch_line(self, frame: FrameType) -> TraceFunction: ...\n    def dispatch_call(self, frame: FrameType, arg: None) -> TraceFunction: ...\n    def dispatch_return(self, frame: FrameType, arg: Any) -> TraceFunction: ...\n    def dispatch_exception(self, frame: FrameType, arg: ExcInfo) -> TraceFunction: ...\n    if sys.version_info >= (3, 13):\n        def dispatch_opcode(self, frame: FrameType, arg: Unused) -> Callable[[FrameType, str, Any], TraceFunction]: ...\n\n    def is_skipped_module(self, module_name: str) -> bool: ...\n    def stop_here(self, frame: FrameType) -> bool: ...\n    def break_here(self, frame: FrameType) -> bool: ...\n    def do_clear(self, arg: Any) -> bool | None: ...\n    def break_anywhere(self, frame: FrameType) -> bool: ...\n    def user_call(self, frame: FrameType, argument_list: None) -> None: ...\n    def user_line(self, frame: FrameType) -> None: ...\n    def user_return(self, frame: FrameType, return_value: Any) -> None: ...\n    def user_exception(self, frame: FrameType, exc_info: ExcInfo) -> None: ...\n    def set_until(self, frame: FrameType, lineno: int | None = None) -> None: ...\n    if sys.version_info >= (3, 13):\n        def user_opcode(self, frame: FrameType) -> None: ...  # undocumented\n\n    def set_step(self) -> None: ...\n    if sys.version_info >= (3, 13):\n        def set_stepinstr(self) -> None: ...  # undocumented\n\n    def set_next(self, frame: FrameType) -> None: ...\n    def set_return(self, frame: FrameType) -> None: ...\n    def set_trace(self, frame: FrameType | None = None) -> None: ...\n    def set_continue(self) -> None: ...\n    def set_quit(self) -> None: ...\n    def set_break(\n        self, filename: str, lineno: int, temporary: bool = False, cond: str | None = None, funcname: str | None = None\n    ) -> str | None: ...\n    def clear_break(self, filename: str, lineno: int) -> str | None: ...\n    def clear_bpbynumber(self, arg: SupportsInt) -> str | None: ...\n    def clear_all_file_breaks(self, filename: str) -> str | None: ...\n    def clear_all_breaks(self) -> str | None: ...\n    def get_bpbynumber(self, arg: SupportsInt) -> Breakpoint: ...\n    def get_break(self, filename: str, lineno: int) -> bool: ...\n    def get_breaks(self, filename: str, lineno: int) -> list[Breakpoint]: ...\n    def get_file_breaks(self, filename: str) -> list[int]: ...\n    def get_all_breaks(self) -> dict[str, list[int]]: ...\n    def get_stack(self, f: FrameType | None, t: TracebackType | None) -> tuple[list[tuple[FrameType, int]], int]: ...\n    def format_stack_entry(self, frame_lineno: tuple[FrameType, int], lprefix: str = \": \") -> str: ...\n    def run(\n        self, cmd: str | CodeType, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None\n    ) -> None: ...\n    def runeval(self, expr: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> None: ...\n    def runctx(self, cmd: str | CodeType, globals: dict[str, Any] | None, locals: Mapping[str, Any] | None) -> None: ...\n    def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> _T | None: ...\n    if sys.version_info >= (3, 14):\n        def start_trace(self) -> None: ...\n        def stop_trace(self) -> None: ...\n        def disable_current_event(self) -> None: ...\n        def restart_events(self) -> None: ...\n\nclass Breakpoint:\n    next: int\n    bplist: dict[tuple[str, int], list[Breakpoint]]\n    bpbynumber: list[Breakpoint | None]\n\n    funcname: str | None\n    func_first_executable_line: int | None\n    file: str\n    line: int\n    temporary: bool\n    cond: str | None\n    enabled: bool\n    ignore: int\n    hits: int\n    number: int\n    def __init__(\n        self, file: str, line: int, temporary: bool = False, cond: str | None = None, funcname: str | None = None\n    ) -> None: ...\n    if sys.version_info >= (3, 11):\n        @staticmethod\n        def clearBreakpoints() -> None: ...\n\n    def deleteMe(self) -> None: ...\n    def enable(self) -> None: ...\n    def disable(self) -> None: ...\n    def bpprint(self, out: IO[str] | None = None) -> None: ...\n    def bpformat(self) -> str: ...\n\ndef checkfuncname(b: Breakpoint, frame: FrameType) -> bool: ...\ndef effective(file: str, line: int, frame: FrameType) -> tuple[Breakpoint, bool] | tuple[None, None]: ...\ndef set_trace() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/binascii.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom typing_extensions import TypeAlias, deprecated\n\n# Many functions in binascii accept buffer objects\n# or ASCII-only strings.\n_AsciiBuffer: TypeAlias = str | ReadableBuffer\n\ndef a2b_uu(data: _AsciiBuffer, /) -> bytes: ...\ndef b2a_uu(data: ReadableBuffer, /, *, backtick: bool = False) -> bytes: ...\n\nif sys.version_info >= (3, 11):\n    def a2b_base64(data: _AsciiBuffer, /, *, strict_mode: bool = False) -> bytes: ...\n\nelse:\n    def a2b_base64(data: _AsciiBuffer, /) -> bytes: ...\n\ndef b2a_base64(data: ReadableBuffer, /, *, newline: bool = True) -> bytes: ...\ndef a2b_qp(data: _AsciiBuffer, header: bool = False) -> bytes: ...\ndef b2a_qp(data: ReadableBuffer, quotetabs: bool = False, istext: bool = True, header: bool = False) -> bytes: ...\n\nif sys.version_info < (3, 11):\n    @deprecated(\"Deprecated since Python 3.9; removed in Python 3.11.\")\n    def a2b_hqx(data: _AsciiBuffer, /) -> bytes: ...\n    @deprecated(\"Deprecated since Python 3.9; removed in Python 3.11.\")\n    def rledecode_hqx(data: ReadableBuffer, /) -> bytes: ...\n    @deprecated(\"Deprecated since Python 3.9; removed in Python 3.11.\")\n    def rlecode_hqx(data: ReadableBuffer, /) -> bytes: ...\n    @deprecated(\"Deprecated since Python 3.9; removed in Python 3.11.\")\n    def b2a_hqx(data: ReadableBuffer, /) -> bytes: ...\n\ndef crc_hqx(data: ReadableBuffer, crc: int, /) -> int: ...\ndef crc32(data: ReadableBuffer, crc: int = 0, /) -> int: ...\ndef b2a_hex(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes: ...\ndef hexlify(data: ReadableBuffer, sep: str | bytes = ..., bytes_per_sep: int = 1) -> bytes: ...\ndef a2b_hex(hexstr: _AsciiBuffer, /) -> bytes: ...\ndef unhexlify(hexstr: _AsciiBuffer, /) -> bytes: ...\n\nclass Error(ValueError): ...\nclass Incomplete(Exception): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/binhex.pyi",
    "content": "from _typeshed import SizedBuffer\nfrom typing import IO, Any, Final\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"binhex\", \"hexbin\", \"Error\"]\n\nclass Error(Exception): ...\n\nREASONABLY_LARGE: Final = 32768\nLINELEN: Final = 64\nRUNCHAR: Final = b\"\\x90\"\n\nclass FInfo:\n    Type: str\n    Creator: str\n    Flags: int\n\n_FileInfoTuple: TypeAlias = tuple[str, FInfo, int, int]\n_FileHandleUnion: TypeAlias = str | IO[bytes]\n\ndef getfileinfo(name: str) -> _FileInfoTuple: ...\n\nclass openrsrc:\n    def __init__(self, *args: Any) -> None: ...\n    def read(self, *args: Any) -> bytes: ...\n    def write(self, *args: Any) -> None: ...\n    def close(self) -> None: ...\n\nclass BinHex:\n    def __init__(self, name_finfo_dlen_rlen: _FileInfoTuple, ofp: _FileHandleUnion) -> None: ...\n    def write(self, data: SizedBuffer) -> None: ...\n    def close_data(self) -> None: ...\n    def write_rsrc(self, data: SizedBuffer) -> None: ...\n    def close(self) -> None: ...\n\ndef binhex(inp: str, out: str) -> None: ...\n\nclass HexBin:\n    def __init__(self, ifp: _FileHandleUnion) -> None: ...\n    def read(self, *n: int) -> bytes: ...\n    def close_data(self) -> None: ...\n    def read_rsrc(self, *n: int) -> bytes: ...\n    def close(self) -> None: ...\n\ndef hexbin(inp: str, out: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/bisect.pyi",
    "content": "from _bisect import *\n\nbisect = bisect_right\ninsort = insort_right\n"
  },
  {
    "path": "mypy/typeshed/stdlib/builtins.pyi",
    "content": "import _ast\nimport _sitebuiltins\nimport _typeshed\nimport sys\nimport types\nfrom _collections_abc import dict_items, dict_keys, dict_values\nfrom _typeshed import (\n    AnnotationForm,\n    ConvertibleToFloat,\n    ConvertibleToInt,\n    FileDescriptorOrPath,\n    OpenBinaryMode,\n    OpenBinaryModeReading,\n    OpenBinaryModeUpdating,\n    OpenBinaryModeWriting,\n    OpenTextMode,\n    ReadableBuffer,\n    SupportsAdd,\n    SupportsAiter,\n    SupportsAnext,\n    SupportsDivMod,\n    SupportsFlush,\n    SupportsIter,\n    SupportsKeysAndGetItem,\n    SupportsLenAndGetItem,\n    SupportsNext,\n    SupportsRAdd,\n    SupportsRDivMod,\n    SupportsRichComparison,\n    SupportsRichComparisonT,\n    SupportsWrite,\n)\nfrom collections.abc import Awaitable, Callable, Iterable, Iterator, MutableSet, Reversible, Set as AbstractSet, Sized\nfrom io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper\nfrom os import PathLike\nfrom types import CellType, CodeType, GenericAlias, TracebackType\n\n# mypy crashes if any of {ByteString, Sequence, MutableSequence, Mapping, MutableMapping}\n# are imported from collections.abc in builtins.pyi\nfrom typing import (  # noqa: Y022,UP035,RUF100\n    IO,\n    Any,\n    BinaryIO,\n    ClassVar,\n    Final,\n    Generic,\n    Mapping,\n    MutableMapping,\n    MutableSequence,\n    Protocol,\n    Sequence,\n    SupportsAbs,\n    SupportsBytes,\n    SupportsComplex,\n    SupportsFloat,\n    SupportsIndex,\n    TypeVar,\n    final,\n    overload,\n    type_check_only,\n)\n\n# we can't import `Literal` from typing or mypy crashes: see #11247\nfrom typing_extensions import (  # noqa: Y023\n    Concatenate,\n    Literal,\n    ParamSpec,\n    Self,\n    TypeAlias,\n    TypeGuard,\n    TypeIs,\n    TypeVarTuple,\n    deprecated,\n    disjoint_base,\n)\n\nif sys.version_info >= (3, 14):\n    from _typeshed import AnnotateFunc\n\n_T = TypeVar(\"_T\")\n_I = TypeVar(\"_I\", default=int)\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_T_contra = TypeVar(\"_T_contra\", contravariant=True)\n_R_co = TypeVar(\"_R_co\", covariant=True)\n_KT = TypeVar(\"_KT\")\n_VT = TypeVar(\"_VT\")\n_S = TypeVar(\"_S\")\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n_T3 = TypeVar(\"_T3\")\n_T4 = TypeVar(\"_T4\")\n_T5 = TypeVar(\"_T5\")\n_SupportsNextT_co = TypeVar(\"_SupportsNextT_co\", bound=SupportsNext[Any], covariant=True)\n_SupportsAnextT_co = TypeVar(\"_SupportsAnextT_co\", bound=SupportsAnext[Any], covariant=True)\n_AwaitableT = TypeVar(\"_AwaitableT\", bound=Awaitable[Any])\n_AwaitableT_co = TypeVar(\"_AwaitableT_co\", bound=Awaitable[Any], covariant=True)\n_P = ParamSpec(\"_P\")\n\n# Type variables for slice\n_StartT_co = TypeVar(\"_StartT_co\", covariant=True, default=Any)  # slice -> slice[Any, Any, Any]\n_StopT_co = TypeVar(\"_StopT_co\", covariant=True, default=_StartT_co)  #  slice[A] -> slice[A, A, A]\n# NOTE: step could differ from start and stop, (e.g. datetime/timedelta)l\n#   the default (start|stop) is chosen to cater to the most common case of int/index slices.\n# FIXME: https://github.com/python/typing/issues/213 (replace step=start|stop with step=start&stop)\n_StepT_co = TypeVar(\"_StepT_co\", covariant=True, default=_StartT_co | _StopT_co)  #  slice[A,B] -> slice[A, B, A|B]\n\n@disjoint_base\nclass object:\n    __doc__: str | None\n    __dict__: dict[str, Any]\n    __module__: str\n    __annotations__: dict[str, Any]\n    @property\n    def __class__(self) -> type[Self]: ...\n    @__class__.setter\n    def __class__(self, type: type[Self], /) -> None: ...\n    def __init__(self) -> None: ...\n    def __new__(cls) -> Self: ...\n    # N.B. `object.__setattr__` and `object.__delattr__` are heavily special-cased by type checkers.\n    # Overriding them in subclasses has different semantics, even if the override has an identical signature.\n    def __setattr__(self, name: str, value: Any, /) -> None: ...\n    def __delattr__(self, name: str, /) -> None: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __ne__(self, value: object, /) -> bool: ...\n    def __str__(self) -> str: ...  # noqa: Y029\n    def __repr__(self) -> str: ...  # noqa: Y029\n    def __hash__(self) -> int: ...\n    def __format__(self, format_spec: str, /) -> str: ...\n    def __getattribute__(self, name: str, /) -> Any: ...\n    def __sizeof__(self) -> int: ...\n    # return type of pickle methods is rather hard to express in the current type system\n    # see #6661 and https://docs.python.org/3/library/pickle.html#object.__reduce__\n    def __reduce__(self) -> str | tuple[Any, ...]: ...\n    def __reduce_ex__(self, protocol: SupportsIndex, /) -> str | tuple[Any, ...]: ...\n    if sys.version_info >= (3, 11):\n        def __getstate__(self) -> object: ...\n\n    def __dir__(self) -> Iterable[str]: ...\n    def __init_subclass__(cls) -> None: ...\n    @classmethod\n    def __subclasshook__(cls, subclass: type, /) -> bool: ...\n\n@disjoint_base\nclass staticmethod(Generic[_P, _R_co]):\n    @property\n    def __func__(self) -> Callable[_P, _R_co]: ...\n    @property\n    def __isabstractmethod__(self) -> bool: ...\n    def __init__(self, f: Callable[_P, _R_co], /) -> None: ...\n    @overload\n    def __get__(self, instance: None, owner: type, /) -> Callable[_P, _R_co]: ...\n    @overload\n    def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ...\n    if sys.version_info >= (3, 10):\n        __name__: str\n        __qualname__: str\n        @property\n        def __wrapped__(self) -> Callable[_P, _R_co]: ...\n        def __call__(self, *args: _P.args, **kwargs: _P.kwargs) -> _R_co: ...\n    if sys.version_info >= (3, 14):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n        __annotate__: AnnotateFunc | None\n\n@disjoint_base\nclass classmethod(Generic[_T, _P, _R_co]):\n    @property\n    def __func__(self) -> Callable[Concatenate[type[_T], _P], _R_co]: ...\n    @property\n    def __isabstractmethod__(self) -> bool: ...\n    def __init__(self, f: Callable[Concatenate[type[_T], _P], _R_co], /) -> None: ...\n    @overload\n    def __get__(self, instance: _T, owner: type[_T] | None = None, /) -> Callable[_P, _R_co]: ...\n    @overload\n    def __get__(self, instance: None, owner: type[_T], /) -> Callable[_P, _R_co]: ...\n    if sys.version_info >= (3, 10):\n        __name__: str\n        __qualname__: str\n        @property\n        def __wrapped__(self) -> Callable[Concatenate[type[_T], _P], _R_co]: ...\n    if sys.version_info >= (3, 14):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n        __annotate__: AnnotateFunc | None\n\n@disjoint_base\nclass type:\n    # object.__base__ is None. Otherwise, it would be a type.\n    @property\n    def __base__(self) -> type | None: ...\n    __bases__: tuple[type, ...]\n    @property\n    def __basicsize__(self) -> int: ...\n    # type.__dict__ is read-only at runtime, but that can't be expressed currently.\n    # See https://github.com/python/typeshed/issues/11033 for a discussion.\n    __dict__: Final[types.MappingProxyType[str, Any]]  # type: ignore[assignment]\n    @property\n    def __dictoffset__(self) -> int: ...\n    @property\n    def __flags__(self) -> int: ...\n    @property\n    def __itemsize__(self) -> int: ...\n    __module__: str\n    @property\n    def __mro__(self) -> tuple[type, ...]: ...\n    __name__: str\n    __qualname__: str\n    @property\n    def __text_signature__(self) -> str | None: ...\n    @property\n    def __weakrefoffset__(self) -> int: ...\n    @overload\n    def __init__(self, o: object, /) -> None: ...\n    @overload\n    def __init__(self, name: str, bases: tuple[type, ...], dict: dict[str, Any], /, **kwds: Any) -> None: ...\n    @overload\n    def __new__(cls, o: object, /) -> type: ...\n    @overload\n    def __new__(\n        cls: type[_typeshed.Self], name: str, bases: tuple[type, ...], namespace: dict[str, Any], /, **kwds: Any\n    ) -> _typeshed.Self: ...\n    def __call__(self, *args: Any, **kwds: Any) -> Any: ...\n    def __subclasses__(self: _typeshed.Self) -> list[_typeshed.Self]: ...\n    # Note: the documentation doesn't specify what the return type is, the standard\n    # implementation seems to be returning a list.\n    def mro(self) -> list[type]: ...\n    def __instancecheck__(self, instance: Any, /) -> bool: ...\n    def __subclasscheck__(self, subclass: type, /) -> bool: ...\n    @classmethod\n    def __prepare__(metacls, name: str, bases: tuple[type, ...], /, **kwds: Any) -> MutableMapping[str, object]: ...\n    if sys.version_info >= (3, 10):\n        # `int | str` produces an instance of `UnionType`, but `int | int` produces an instance of `type`,\n        # and `abc.ABC | abc.ABC` produces an instance of `abc.ABCMeta`.\n        def __or__(self: _typeshed.Self, value: Any, /) -> types.UnionType | _typeshed.Self: ...\n        def __ror__(self: _typeshed.Self, value: Any, /) -> types.UnionType | _typeshed.Self: ...\n    if sys.version_info >= (3, 12):\n        __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...]\n    __annotations__: dict[str, AnnotationForm]\n    if sys.version_info >= (3, 14):\n        __annotate__: AnnotateFunc | None\n\n@disjoint_base\nclass super:\n    @overload\n    def __init__(self, t: Any, obj: Any, /) -> None: ...\n    @overload\n    def __init__(self, t: Any, /) -> None: ...\n    @overload\n    def __init__(self) -> None: ...\n\n_PositiveInteger: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]\n_NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20]\n_LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0]  # noqa: Y026  # TODO: Use TypeAlias once mypy bugs are fixed\n\n@disjoint_base\nclass int:\n    @overload\n    def __new__(cls, x: ConvertibleToInt = 0, /) -> Self: ...\n    @overload\n    def __new__(cls, x: str | bytes | bytearray, /, base: SupportsIndex) -> Self: ...\n    def as_integer_ratio(self) -> tuple[int, Literal[1]]: ...\n    @property\n    def real(self) -> int: ...\n    @property\n    def imag(self) -> Literal[0]: ...\n    @property\n    def numerator(self) -> int: ...\n    @property\n    def denominator(self) -> Literal[1]: ...\n    def conjugate(self) -> int: ...\n    def bit_length(self) -> int: ...\n    if sys.version_info >= (3, 10):\n        def bit_count(self) -> int: ...\n\n    if sys.version_info >= (3, 11):\n        def to_bytes(\n            self, length: SupportsIndex = 1, byteorder: Literal[\"little\", \"big\"] = \"big\", *, signed: bool = False\n        ) -> bytes: ...\n        @classmethod\n        def from_bytes(\n            cls,\n            bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n            byteorder: Literal[\"little\", \"big\"] = \"big\",\n            *,\n            signed: bool = False,\n        ) -> Self: ...\n    else:\n        def to_bytes(self, length: SupportsIndex, byteorder: Literal[\"little\", \"big\"], *, signed: bool = False) -> bytes: ...\n        @classmethod\n        def from_bytes(\n            cls,\n            bytes: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer,\n            byteorder: Literal[\"little\", \"big\"],\n            *,\n            signed: bool = False,\n        ) -> Self: ...\n\n    if sys.version_info >= (3, 12):\n        def is_integer(self) -> Literal[True]: ...\n\n    def __add__(self, value: int, /) -> int: ...\n    def __sub__(self, value: int, /) -> int: ...\n    def __mul__(self, value: int, /) -> int: ...\n    def __floordiv__(self, value: int, /) -> int: ...\n    def __truediv__(self, value: int, /) -> float: ...\n    def __mod__(self, value: int, /) -> int: ...\n    def __divmod__(self, value: int, /) -> tuple[int, int]: ...\n    def __radd__(self, value: int, /) -> int: ...\n    def __rsub__(self, value: int, /) -> int: ...\n    def __rmul__(self, value: int, /) -> int: ...\n    def __rfloordiv__(self, value: int, /) -> int: ...\n    def __rtruediv__(self, value: int, /) -> float: ...\n    def __rmod__(self, value: int, /) -> int: ...\n    def __rdivmod__(self, value: int, /) -> tuple[int, int]: ...\n    @overload\n    def __pow__(self, x: Literal[0], /) -> Literal[1]: ...\n    @overload\n    def __pow__(self, value: Literal[0], mod: None, /) -> Literal[1]: ...\n    @overload\n    def __pow__(self, value: _PositiveInteger, mod: None = None, /) -> int: ...\n    @overload\n    def __pow__(self, value: _NegativeInteger, mod: None = None, /) -> float: ...\n    # positive __value -> int; negative __value -> float\n    # return type must be Any as `int | float` causes too many false-positive errors\n    @overload\n    def __pow__(self, value: int, mod: None = None, /) -> Any: ...\n    @overload\n    def __pow__(self, value: int, mod: int, /) -> int: ...\n    def __rpow__(self, value: int, mod: int | None = None, /) -> Any: ...\n    def __and__(self, value: int, /) -> int: ...\n    def __or__(self, value: int, /) -> int: ...\n    def __xor__(self, value: int, /) -> int: ...\n    def __lshift__(self, value: int, /) -> int: ...\n    def __rshift__(self, value: int, /) -> int: ...\n    def __rand__(self, value: int, /) -> int: ...\n    def __ror__(self, value: int, /) -> int: ...\n    def __rxor__(self, value: int, /) -> int: ...\n    def __rlshift__(self, value: int, /) -> int: ...\n    def __rrshift__(self, value: int, /) -> int: ...\n    def __neg__(self) -> int: ...\n    def __pos__(self) -> int: ...\n    def __invert__(self) -> int: ...\n    def __trunc__(self) -> int: ...\n    def __ceil__(self) -> int: ...\n    def __floor__(self) -> int: ...\n    if sys.version_info >= (3, 14):\n        def __round__(self, ndigits: SupportsIndex | None = None, /) -> int: ...\n    else:\n        def __round__(self, ndigits: SupportsIndex = ..., /) -> int: ...\n\n    def __getnewargs__(self) -> tuple[int]: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __ne__(self, value: object, /) -> bool: ...\n    def __lt__(self, value: int, /) -> bool: ...\n    def __le__(self, value: int, /) -> bool: ...\n    def __gt__(self, value: int, /) -> bool: ...\n    def __ge__(self, value: int, /) -> bool: ...\n    def __float__(self) -> float: ...\n    def __int__(self) -> int: ...\n    def __abs__(self) -> int: ...\n    def __hash__(self) -> int: ...\n    def __bool__(self) -> bool: ...\n    def __index__(self) -> int: ...\n    def __format__(self, format_spec: str, /) -> str: ...\n\n@disjoint_base\nclass float:\n    def __new__(cls, x: ConvertibleToFloat = 0, /) -> Self: ...\n    def as_integer_ratio(self) -> tuple[int, int]: ...\n    def hex(self) -> str: ...\n    def is_integer(self) -> bool: ...\n    @classmethod\n    def fromhex(cls, string: str, /) -> Self: ...\n    @property\n    def real(self) -> float: ...\n    @property\n    def imag(self) -> float: ...\n    def conjugate(self) -> float: ...\n    def __add__(self, value: float, /) -> float: ...\n    def __sub__(self, value: float, /) -> float: ...\n    def __mul__(self, value: float, /) -> float: ...\n    def __floordiv__(self, value: float, /) -> float: ...\n    def __truediv__(self, value: float, /) -> float: ...\n    def __mod__(self, value: float, /) -> float: ...\n    def __divmod__(self, value: float, /) -> tuple[float, float]: ...\n    @overload\n    def __pow__(self, value: int, mod: None = None, /) -> float: ...\n    # positive __value -> float; negative __value -> complex\n    # return type must be Any as `float | complex` causes too many false-positive errors\n    @overload\n    def __pow__(self, value: float, mod: None = None, /) -> Any: ...\n    def __radd__(self, value: float, /) -> float: ...\n    def __rsub__(self, value: float, /) -> float: ...\n    def __rmul__(self, value: float, /) -> float: ...\n    def __rfloordiv__(self, value: float, /) -> float: ...\n    def __rtruediv__(self, value: float, /) -> float: ...\n    def __rmod__(self, value: float, /) -> float: ...\n    def __rdivmod__(self, value: float, /) -> tuple[float, float]: ...\n    @overload\n    def __rpow__(self, value: _PositiveInteger, mod: None = None, /) -> float: ...\n    @overload\n    def __rpow__(self, value: _NegativeInteger, mod: None = None, /) -> complex: ...\n    # Returning `complex` for the general case gives too many false-positive errors.\n    @overload\n    def __rpow__(self, value: float, mod: None = None, /) -> Any: ...\n    def __getnewargs__(self) -> tuple[float]: ...\n    def __trunc__(self) -> int: ...\n    def __ceil__(self) -> int: ...\n    def __floor__(self) -> int: ...\n    @overload\n    def __round__(self, ndigits: None = None, /) -> int: ...\n    @overload\n    def __round__(self, ndigits: SupportsIndex, /) -> float: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __ne__(self, value: object, /) -> bool: ...\n    def __lt__(self, value: float, /) -> bool: ...\n    def __le__(self, value: float, /) -> bool: ...\n    def __gt__(self, value: float, /) -> bool: ...\n    def __ge__(self, value: float, /) -> bool: ...\n    def __neg__(self) -> float: ...\n    def __pos__(self) -> float: ...\n    def __int__(self) -> int: ...\n    def __float__(self) -> float: ...\n    def __abs__(self) -> float: ...\n    def __hash__(self) -> int: ...\n    def __bool__(self) -> bool: ...\n    def __format__(self, format_spec: str, /) -> str: ...\n    if sys.version_info >= (3, 14):\n        @classmethod\n        def from_number(cls, number: float | SupportsIndex | SupportsFloat, /) -> Self: ...\n\n@disjoint_base\nclass complex:\n    # Python doesn't currently accept SupportsComplex for the second argument\n    @overload\n    def __new__(\n        cls,\n        real: complex | SupportsComplex | SupportsFloat | SupportsIndex = 0,\n        imag: complex | SupportsFloat | SupportsIndex = 0,\n    ) -> Self: ...\n    @overload\n    def __new__(cls, real: str | SupportsComplex | SupportsFloat | SupportsIndex | complex) -> Self: ...\n    @property\n    def real(self) -> float: ...\n    @property\n    def imag(self) -> float: ...\n    def conjugate(self) -> complex: ...\n    def __add__(self, value: complex, /) -> complex: ...\n    def __sub__(self, value: complex, /) -> complex: ...\n    def __mul__(self, value: complex, /) -> complex: ...\n    def __pow__(self, value: complex, mod: None = None, /) -> complex: ...\n    def __truediv__(self, value: complex, /) -> complex: ...\n    def __radd__(self, value: complex, /) -> complex: ...\n    def __rsub__(self, value: complex, /) -> complex: ...\n    def __rmul__(self, value: complex, /) -> complex: ...\n    def __rpow__(self, value: complex, mod: None = None, /) -> complex: ...\n    def __rtruediv__(self, value: complex, /) -> complex: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __ne__(self, value: object, /) -> bool: ...\n    def __neg__(self) -> complex: ...\n    def __pos__(self) -> complex: ...\n    def __abs__(self) -> float: ...\n    def __hash__(self) -> int: ...\n    def __bool__(self) -> bool: ...\n    def __format__(self, format_spec: str, /) -> str: ...\n    if sys.version_info >= (3, 11):\n        def __complex__(self) -> complex: ...\n    if sys.version_info >= (3, 14):\n        @classmethod\n        def from_number(cls, number: complex | SupportsComplex | SupportsFloat | SupportsIndex, /) -> Self: ...\n\n@type_check_only\nclass _FormatMapMapping(Protocol):\n    def __getitem__(self, key: str, /) -> Any: ...\n\n@type_check_only\nclass _TranslateTable(Protocol):\n    def __getitem__(self, key: int, /) -> str | int | None: ...\n\n@disjoint_base\nclass str(Sequence[str]):\n    @overload\n    def __new__(cls, object: object = \"\") -> Self: ...\n    @overload\n    def __new__(cls, object: ReadableBuffer, encoding: str = \"utf-8\", errors: str = \"strict\") -> Self: ...\n    def capitalize(self) -> str: ...  # type: ignore[misc]\n    def casefold(self) -> str: ...  # type: ignore[misc]\n    def center(self, width: SupportsIndex, fillchar: str = \" \", /) -> str: ...  # type: ignore[misc]\n    def count(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ...\n    def encode(self, encoding: str = \"utf-8\", errors: str = \"strict\") -> bytes: ...\n    def endswith(\n        self, suffix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> bool: ...\n    def expandtabs(self, tabsize: SupportsIndex = 8) -> str: ...  # type: ignore[misc]\n    def find(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ...\n    def format(self, *args: object, **kwargs: object) -> str: ...\n    def format_map(self, mapping: _FormatMapMapping, /) -> str: ...\n    def index(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ...\n    def isalnum(self) -> bool: ...\n    def isalpha(self) -> bool: ...\n    def isascii(self) -> bool: ...\n    def isdecimal(self) -> bool: ...\n    def isdigit(self) -> bool: ...\n    def isidentifier(self) -> bool: ...\n    def islower(self) -> bool: ...\n    def isnumeric(self) -> bool: ...\n    def isprintable(self) -> bool: ...\n    def isspace(self) -> bool: ...\n    def istitle(self) -> bool: ...\n    def isupper(self) -> bool: ...\n    def join(self, iterable: Iterable[str], /) -> str: ...  # type: ignore[misc]\n    def ljust(self, width: SupportsIndex, fillchar: str = \" \", /) -> str: ...  # type: ignore[misc]\n    def lower(self) -> str: ...  # type: ignore[misc]\n    def lstrip(self, chars: str | None = None, /) -> str: ...  # type: ignore[misc]\n    def partition(self, sep: str, /) -> tuple[str, str, str]: ...  # type: ignore[misc]\n    if sys.version_info >= (3, 13):\n        def replace(self, old: str, new: str, /, count: SupportsIndex = -1) -> str: ...  # type: ignore[misc]\n    else:\n        def replace(self, old: str, new: str, count: SupportsIndex = -1, /) -> str: ...  # type: ignore[misc]\n\n    def removeprefix(self, prefix: str, /) -> str: ...  # type: ignore[misc]\n    def removesuffix(self, suffix: str, /) -> str: ...  # type: ignore[misc]\n    def rfind(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ...\n    def rindex(self, sub: str, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /) -> int: ...\n    def rjust(self, width: SupportsIndex, fillchar: str = \" \", /) -> str: ...  # type: ignore[misc]\n    def rpartition(self, sep: str, /) -> tuple[str, str, str]: ...  # type: ignore[misc]\n    def rsplit(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ...  # type: ignore[misc]\n    def rstrip(self, chars: str | None = None, /) -> str: ...  # type: ignore[misc]\n    def split(self, sep: str | None = None, maxsplit: SupportsIndex = -1) -> list[str]: ...  # type: ignore[misc]\n    def splitlines(self, keepends: bool = False) -> list[str]: ...  # type: ignore[misc]\n    def startswith(\n        self, prefix: str | tuple[str, ...], start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> bool: ...\n    def strip(self, chars: str | None = None, /) -> str: ...  # type: ignore[misc]\n    def swapcase(self) -> str: ...  # type: ignore[misc]\n    def title(self) -> str: ...  # type: ignore[misc]\n    def translate(self, table: _TranslateTable, /) -> str: ...\n    def upper(self) -> str: ...  # type: ignore[misc]\n    def zfill(self, width: SupportsIndex, /) -> str: ...  # type: ignore[misc]\n    @staticmethod\n    @overload\n    def maketrans(x: dict[int, _T] | dict[str, _T] | dict[str | int, _T], /) -> dict[int, _T]: ...\n    @staticmethod\n    @overload\n    def maketrans(x: str, y: str, /) -> dict[int, int]: ...\n    @staticmethod\n    @overload\n    def maketrans(x: str, y: str, z: str, /) -> dict[int, int | None]: ...\n    def __add__(self, value: str, /) -> str: ...  # type: ignore[misc]\n    # Incompatible with Sequence.__contains__\n    def __contains__(self, key: str, /) -> bool: ...  # type: ignore[override]\n    def __eq__(self, value: object, /) -> bool: ...\n    def __ge__(self, value: str, /) -> bool: ...\n    def __getitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> str: ...  # type: ignore[misc]\n    def __gt__(self, value: str, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __iter__(self) -> Iterator[str]: ...  # type: ignore[misc]\n    def __le__(self, value: str, /) -> bool: ...\n    def __len__(self) -> int: ...\n    def __lt__(self, value: str, /) -> bool: ...\n    def __mod__(self, value: Any, /) -> str: ...\n    def __mul__(self, value: SupportsIndex, /) -> str: ...  # type: ignore[misc]\n    def __ne__(self, value: object, /) -> bool: ...\n    def __rmul__(self, value: SupportsIndex, /) -> str: ...  # type: ignore[misc]\n    def __getnewargs__(self) -> tuple[str]: ...\n    def __format__(self, format_spec: str, /) -> str: ...\n\n@disjoint_base\nclass bytes(Sequence[int]):\n    @overload\n    def __new__(cls, o: Iterable[SupportsIndex] | SupportsIndex | SupportsBytes | ReadableBuffer, /) -> Self: ...\n    @overload\n    def __new__(cls, string: str, /, encoding: str, errors: str = \"strict\") -> Self: ...\n    @overload\n    def __new__(cls) -> Self: ...\n    def capitalize(self) -> bytes: ...\n    def center(self, width: SupportsIndex, fillchar: bytes = b\" \", /) -> bytes: ...\n    def count(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> int: ...\n    def decode(self, encoding: str = \"utf-8\", errors: str = \"strict\") -> str: ...\n    def endswith(\n        self,\n        suffix: ReadableBuffer | tuple[ReadableBuffer, ...],\n        start: SupportsIndex | None = None,\n        end: SupportsIndex | None = None,\n        /,\n    ) -> bool: ...\n    def expandtabs(self, tabsize: SupportsIndex = 8) -> bytes: ...\n    def find(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> int: ...\n    def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = 1) -> str: ...\n    def index(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> int: ...\n    def isalnum(self) -> bool: ...\n    def isalpha(self) -> bool: ...\n    def isascii(self) -> bool: ...\n    def isdigit(self) -> bool: ...\n    def islower(self) -> bool: ...\n    def isspace(self) -> bool: ...\n    def istitle(self) -> bool: ...\n    def isupper(self) -> bool: ...\n    def join(self, iterable_of_bytes: Iterable[ReadableBuffer], /) -> bytes: ...\n    def ljust(self, width: SupportsIndex, fillchar: bytes | bytearray = b\" \", /) -> bytes: ...\n    def lower(self) -> bytes: ...\n    def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ...\n    def partition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: ...\n    def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytes: ...\n    def removeprefix(self, prefix: ReadableBuffer, /) -> bytes: ...\n    def removesuffix(self, suffix: ReadableBuffer, /) -> bytes: ...\n    def rfind(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> int: ...\n    def rindex(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> int: ...\n    def rjust(self, width: SupportsIndex, fillchar: bytes | bytearray = b\" \", /) -> bytes: ...\n    def rpartition(self, sep: ReadableBuffer, /) -> tuple[bytes, bytes, bytes]: ...\n    def rsplit(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytes]: ...\n    def rstrip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ...\n    def split(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytes]: ...\n    def splitlines(self, keepends: bool = False) -> list[bytes]: ...\n    def startswith(\n        self,\n        prefix: ReadableBuffer | tuple[ReadableBuffer, ...],\n        start: SupportsIndex | None = None,\n        end: SupportsIndex | None = None,\n        /,\n    ) -> bool: ...\n    def strip(self, bytes: ReadableBuffer | None = None, /) -> bytes: ...\n    def swapcase(self) -> bytes: ...\n    def title(self) -> bytes: ...\n    def translate(self, table: ReadableBuffer | None, /, delete: ReadableBuffer = b\"\") -> bytes: ...\n    def upper(self) -> bytes: ...\n    def zfill(self, width: SupportsIndex, /) -> bytes: ...\n    if sys.version_info >= (3, 14):\n        @classmethod\n        def fromhex(cls, string: str | ReadableBuffer, /) -> Self: ...\n    else:\n        @classmethod\n        def fromhex(cls, string: str, /) -> Self: ...\n\n    @staticmethod\n    def maketrans(frm: ReadableBuffer, to: ReadableBuffer, /) -> bytes: ...\n    def __len__(self) -> int: ...\n    def __iter__(self) -> Iterator[int]: ...\n    def __hash__(self) -> int: ...\n    @overload\n    def __getitem__(self, key: SupportsIndex, /) -> int: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytes: ...\n    def __add__(self, value: ReadableBuffer, /) -> bytes: ...\n    def __mul__(self, value: SupportsIndex, /) -> bytes: ...\n    def __rmul__(self, value: SupportsIndex, /) -> bytes: ...\n    def __mod__(self, value: Any, /) -> bytes: ...\n    # Incompatible with Sequence.__contains__\n    def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: ...  # type: ignore[override]\n    def __eq__(self, value: object, /) -> bool: ...\n    def __ne__(self, value: object, /) -> bool: ...\n    def __lt__(self, value: bytes, /) -> bool: ...\n    def __le__(self, value: bytes, /) -> bool: ...\n    def __gt__(self, value: bytes, /) -> bool: ...\n    def __ge__(self, value: bytes, /) -> bool: ...\n    def __getnewargs__(self) -> tuple[bytes]: ...\n    if sys.version_info >= (3, 11):\n        def __bytes__(self) -> bytes: ...\n\n    def __buffer__(self, flags: int, /) -> memoryview: ...\n\n@disjoint_base\nclass bytearray(MutableSequence[int]):\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, ints: Iterable[SupportsIndex] | SupportsIndex | ReadableBuffer, /) -> None: ...\n    @overload\n    def __init__(self, string: str, /, encoding: str, errors: str = \"strict\") -> None: ...\n    def append(self, item: SupportsIndex, /) -> None: ...\n    def capitalize(self) -> bytearray: ...\n    def center(self, width: SupportsIndex, fillchar: bytes = b\" \", /) -> bytearray: ...\n    def count(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> int: ...\n    def copy(self) -> bytearray: ...\n    def decode(self, encoding: str = \"utf-8\", errors: str = \"strict\") -> str: ...\n    def endswith(\n        self,\n        suffix: ReadableBuffer | tuple[ReadableBuffer, ...],\n        start: SupportsIndex | None = None,\n        end: SupportsIndex | None = None,\n        /,\n    ) -> bool: ...\n    def expandtabs(self, tabsize: SupportsIndex = 8) -> bytearray: ...\n    def extend(self, iterable_of_ints: Iterable[SupportsIndex], /) -> None: ...\n    def find(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> int: ...\n    def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = 1) -> str: ...\n    def index(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> int: ...\n    def insert(self, index: SupportsIndex, item: SupportsIndex, /) -> None: ...\n    def isalnum(self) -> bool: ...\n    def isalpha(self) -> bool: ...\n    def isascii(self) -> bool: ...\n    def isdigit(self) -> bool: ...\n    def islower(self) -> bool: ...\n    def isspace(self) -> bool: ...\n    def istitle(self) -> bool: ...\n    def isupper(self) -> bool: ...\n    def join(self, iterable_of_bytes: Iterable[ReadableBuffer], /) -> bytearray: ...\n    def ljust(self, width: SupportsIndex, fillchar: bytes | bytearray = b\" \", /) -> bytearray: ...\n    def lower(self) -> bytearray: ...\n    def lstrip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ...\n    def partition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: ...\n    def pop(self, index: int = -1, /) -> int: ...\n    def remove(self, value: int, /) -> None: ...\n    def removeprefix(self, prefix: ReadableBuffer, /) -> bytearray: ...\n    def removesuffix(self, suffix: ReadableBuffer, /) -> bytearray: ...\n    def replace(self, old: ReadableBuffer, new: ReadableBuffer, count: SupportsIndex = -1, /) -> bytearray: ...\n    def rfind(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> int: ...\n    def rindex(\n        self, sub: ReadableBuffer | SupportsIndex, start: SupportsIndex | None = None, end: SupportsIndex | None = None, /\n    ) -> int: ...\n    def rjust(self, width: SupportsIndex, fillchar: bytes | bytearray = b\" \", /) -> bytearray: ...\n    def rpartition(self, sep: ReadableBuffer, /) -> tuple[bytearray, bytearray, bytearray]: ...\n    def rsplit(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytearray]: ...\n    def rstrip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ...\n    def split(self, sep: ReadableBuffer | None = None, maxsplit: SupportsIndex = -1) -> list[bytearray]: ...\n    def splitlines(self, keepends: bool = False) -> list[bytearray]: ...\n    def startswith(\n        self,\n        prefix: ReadableBuffer | tuple[ReadableBuffer, ...],\n        start: SupportsIndex | None = None,\n        end: SupportsIndex | None = None,\n        /,\n    ) -> bool: ...\n    def strip(self, bytes: ReadableBuffer | None = None, /) -> bytearray: ...\n    def swapcase(self) -> bytearray: ...\n    def title(self) -> bytearray: ...\n    def translate(self, table: ReadableBuffer | None, /, delete: bytes = b\"\") -> bytearray: ...\n    def upper(self) -> bytearray: ...\n    def zfill(self, width: SupportsIndex, /) -> bytearray: ...\n    if sys.version_info >= (3, 14):\n        @classmethod\n        def fromhex(cls, string: str | ReadableBuffer, /) -> Self: ...\n    else:\n        @classmethod\n        def fromhex(cls, string: str, /) -> Self: ...\n\n    @staticmethod\n    def maketrans(frm: ReadableBuffer, to: ReadableBuffer, /) -> bytes: ...\n    def __len__(self) -> int: ...\n    def __iter__(self) -> Iterator[int]: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    @overload\n    def __getitem__(self, key: SupportsIndex, /) -> int: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytearray: ...\n    @overload\n    def __setitem__(self, key: SupportsIndex, value: SupportsIndex, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[SupportsIndex] | bytes, /) -> None: ...\n    def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ...\n    def __add__(self, value: ReadableBuffer, /) -> bytearray: ...\n    # The superclass wants us to accept Iterable[int], but that fails at runtime.\n    def __iadd__(self, value: ReadableBuffer, /) -> Self: ...  # type: ignore[override]\n    def __mul__(self, value: SupportsIndex, /) -> bytearray: ...\n    def __rmul__(self, value: SupportsIndex, /) -> bytearray: ...\n    def __imul__(self, value: SupportsIndex, /) -> Self: ...\n    def __mod__(self, value: Any, /) -> bytes: ...\n    # Incompatible with Sequence.__contains__\n    def __contains__(self, key: SupportsIndex | ReadableBuffer, /) -> bool: ...  # type: ignore[override]\n    def __eq__(self, value: object, /) -> bool: ...\n    def __ne__(self, value: object, /) -> bool: ...\n    def __lt__(self, value: ReadableBuffer, /) -> bool: ...\n    def __le__(self, value: ReadableBuffer, /) -> bool: ...\n    def __gt__(self, value: ReadableBuffer, /) -> bool: ...\n    def __ge__(self, value: ReadableBuffer, /) -> bool: ...\n    def __alloc__(self) -> int: ...\n    def __buffer__(self, flags: int, /) -> memoryview: ...\n    def __release_buffer__(self, buffer: memoryview, /) -> None: ...\n    if sys.version_info >= (3, 14):\n        def resize(self, size: int, /) -> None: ...\n\n_IntegerFormats: TypeAlias = Literal[\n    \"b\", \"B\", \"@b\", \"@B\", \"h\", \"H\", \"@h\", \"@H\", \"i\", \"I\", \"@i\", \"@I\", \"l\", \"L\", \"@l\", \"@L\", \"q\", \"Q\", \"@q\", \"@Q\", \"P\", \"@P\"\n]\n\n@final\nclass memoryview(Sequence[_I]):\n    @property\n    def format(self) -> str: ...\n    @property\n    def itemsize(self) -> int: ...\n    @property\n    def shape(self) -> tuple[int, ...] | None: ...\n    @property\n    def strides(self) -> tuple[int, ...] | None: ...\n    @property\n    def suboffsets(self) -> tuple[int, ...] | None: ...\n    @property\n    def readonly(self) -> bool: ...\n    @property\n    def ndim(self) -> int: ...\n    @property\n    def obj(self) -> ReadableBuffer: ...\n    @property\n    def c_contiguous(self) -> bool: ...\n    @property\n    def f_contiguous(self) -> bool: ...\n    @property\n    def contiguous(self) -> bool: ...\n    @property\n    def nbytes(self) -> int: ...\n    def __new__(cls, obj: ReadableBuffer) -> Self: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self,\n        exc_type: type[BaseException] | None,  # noqa: PYI036 # This is the module declaring BaseException\n        exc_val: BaseException | None,\n        exc_tb: TracebackType | None,\n        /,\n    ) -> None: ...\n    @overload\n    def cast(self, format: Literal[\"c\", \"@c\"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[bytes]: ...\n    @overload\n    def cast(self, format: Literal[\"f\", \"@f\", \"d\", \"@d\"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[float]: ...\n    @overload\n    def cast(self, format: Literal[\"?\"], shape: list[int] | tuple[int, ...] = ...) -> memoryview[bool]: ...\n    @overload\n    def cast(self, format: _IntegerFormats, shape: list[int] | tuple[int, ...] = ...) -> memoryview: ...\n    @overload\n    def __getitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], /) -> _I: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> memoryview[_I]: ...\n    def __contains__(self, x: object, /) -> bool: ...\n    def __iter__(self) -> Iterator[_I]: ...\n    def __len__(self) -> int: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    @overload\n    def __setitem__(self, key: slice[SupportsIndex | None], value: ReadableBuffer, /) -> None: ...\n    @overload\n    def __setitem__(self, key: SupportsIndex | tuple[SupportsIndex, ...], value: _I, /) -> None: ...\n    if sys.version_info >= (3, 10):\n        def tobytes(self, order: Literal[\"C\", \"F\", \"A\"] | None = \"C\") -> bytes: ...\n    else:\n        def tobytes(self, order: Literal[\"C\", \"F\", \"A\"] | None = None) -> bytes: ...\n\n    def tolist(self) -> list[int]: ...\n    def toreadonly(self) -> memoryview: ...\n    def release(self) -> None: ...\n    def hex(self, sep: str | bytes = ..., bytes_per_sep: SupportsIndex = 1) -> str: ...\n    def __buffer__(self, flags: int, /) -> memoryview: ...\n    def __release_buffer__(self, buffer: memoryview, /) -> None: ...\n    if sys.version_info >= (3, 14):\n        def index(self, value: object, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ...\n        def count(self, value: object, /) -> int: ...\n    else:\n        # These are inherited from the Sequence ABC, but don't actually exist on memoryview.\n        # See https://github.com/python/cpython/issues/125420\n        index: ClassVar[None]  # type: ignore[assignment]\n        count: ClassVar[None]  # type: ignore[assignment]\n\n    if sys.version_info >= (3, 14):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@final\nclass bool(int):\n    def __new__(cls, o: object = False, /) -> Self: ...\n    # The following overloads could be represented more elegantly with a TypeVar(\"_B\", bool, int),\n    # however mypy has a bug regarding TypeVar constraints (https://github.com/python/mypy/issues/11880).\n    @overload\n    def __and__(self, value: bool, /) -> bool: ...\n    @overload\n    def __and__(self, value: int, /) -> int: ...\n    @overload\n    def __or__(self, value: bool, /) -> bool: ...\n    @overload\n    def __or__(self, value: int, /) -> int: ...\n    @overload\n    def __xor__(self, value: bool, /) -> bool: ...\n    @overload\n    def __xor__(self, value: int, /) -> int: ...\n    @overload\n    def __rand__(self, value: bool, /) -> bool: ...\n    @overload\n    def __rand__(self, value: int, /) -> int: ...\n    @overload\n    def __ror__(self, value: bool, /) -> bool: ...\n    @overload\n    def __ror__(self, value: int, /) -> int: ...\n    @overload\n    def __rxor__(self, value: bool, /) -> bool: ...\n    @overload\n    def __rxor__(self, value: int, /) -> int: ...\n    def __getnewargs__(self) -> tuple[int]: ...\n    @deprecated(\"Will throw an error in Python 3.16. Use `not` for logical negation of bools instead.\")\n    def __invert__(self) -> int: ...\n\n@final\nclass slice(Generic[_StartT_co, _StopT_co, _StepT_co]):\n    @property\n    def start(self) -> _StartT_co: ...\n    @property\n    def step(self) -> _StepT_co: ...\n    @property\n    def stop(self) -> _StopT_co: ...\n    # Note: __new__ overloads map `None` to `Any`, since users expect slice(x, None)\n    #  to be compatible with slice(None, x).\n    # generic slice --------------------------------------------------------------------\n    @overload\n    def __new__(cls, start: None, stop: None = None, step: None = None, /) -> slice[Any, Any, Any]: ...\n    # unary overloads ------------------------------------------------------------------\n    @overload\n    def __new__(cls, stop: _T2, /) -> slice[Any, _T2, Any]: ...\n    # binary overloads -----------------------------------------------------------------\n    @overload\n    def __new__(cls, start: _T1, stop: None, step: None = None, /) -> slice[_T1, Any, Any]: ...\n    @overload\n    def __new__(cls, start: None, stop: _T2, step: None = None, /) -> slice[Any, _T2, Any]: ...\n    @overload\n    def __new__(cls, start: _T1, stop: _T2, step: None = None, /) -> slice[_T1, _T2, Any]: ...\n    # ternary overloads ----------------------------------------------------------------\n    @overload\n    def __new__(cls, start: None, stop: None, step: _T3, /) -> slice[Any, Any, _T3]: ...\n    @overload\n    def __new__(cls, start: _T1, stop: None, step: _T3, /) -> slice[_T1, Any, _T3]: ...\n    @overload\n    def __new__(cls, start: None, stop: _T2, step: _T3, /) -> slice[Any, _T2, _T3]: ...\n    @overload\n    def __new__(cls, start: _T1, stop: _T2, step: _T3, /) -> slice[_T1, _T2, _T3]: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    if sys.version_info >= (3, 12):\n        def __hash__(self) -> int: ...\n    else:\n        __hash__: ClassVar[None]  # type: ignore[assignment]\n\n    def indices(self, len: SupportsIndex, /) -> tuple[int, int, int]: ...\n\n@disjoint_base\nclass tuple(Sequence[_T_co]):\n    def __new__(cls, iterable: Iterable[_T_co] = (), /) -> Self: ...\n    def __len__(self) -> int: ...\n    def __contains__(self, key: object, /) -> bool: ...\n    @overload\n    def __getitem__(self, key: SupportsIndex, /) -> _T_co: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> tuple[_T_co, ...]: ...\n    def __iter__(self) -> Iterator[_T_co]: ...\n    def __lt__(self, value: tuple[_T_co, ...], /) -> bool: ...\n    def __le__(self, value: tuple[_T_co, ...], /) -> bool: ...\n    def __gt__(self, value: tuple[_T_co, ...], /) -> bool: ...\n    def __ge__(self, value: tuple[_T_co, ...], /) -> bool: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    @overload\n    def __add__(self, value: tuple[_T_co, ...], /) -> tuple[_T_co, ...]: ...\n    @overload\n    def __add__(self, value: tuple[_T, ...], /) -> tuple[_T_co | _T, ...]: ...\n    def __mul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ...\n    def __rmul__(self, value: SupportsIndex, /) -> tuple[_T_co, ...]: ...\n    def count(self, value: Any, /) -> int: ...\n    def index(self, value: Any, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n# Doesn't exist at runtime, but deleting this breaks mypy and pyright. See:\n# https://github.com/python/typeshed/issues/7580\n# https://github.com/python/mypy/issues/8240\n# Obsolete, use types.FunctionType instead.\n@final\n@type_check_only\nclass function:\n    # Make sure this class definition stays roughly in line with `types.FunctionType`\n    @property\n    def __closure__(self) -> tuple[CellType, ...] | None: ...\n    __code__: CodeType\n    __defaults__: tuple[Any, ...] | None\n    __dict__: dict[str, Any]\n    @property\n    def __globals__(self) -> dict[str, Any]: ...\n    __name__: str\n    __qualname__: str\n    __annotations__: dict[str, AnnotationForm]\n    if sys.version_info >= (3, 14):\n        __annotate__: AnnotateFunc | None\n    __kwdefaults__: dict[str, Any] | None\n    if sys.version_info >= (3, 10):\n        @property\n        def __builtins__(self) -> dict[str, Any]: ...\n    if sys.version_info >= (3, 12):\n        __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...]\n\n    __module__: str\n    if sys.version_info >= (3, 13):\n        def __new__(\n            cls,\n            code: CodeType,\n            globals: dict[str, Any],\n            name: str | None = None,\n            argdefs: tuple[object, ...] | None = None,\n            closure: tuple[CellType, ...] | None = None,\n            kwdefaults: dict[str, object] | None = None,\n        ) -> Self: ...\n    else:\n        def __new__(\n            cls,\n            code: CodeType,\n            globals: dict[str, Any],\n            name: str | None = None,\n            argdefs: tuple[object, ...] | None = None,\n            closure: tuple[CellType, ...] | None = None,\n        ) -> Self: ...\n\n    # mypy uses `builtins.function.__get__` to represent methods, properties, and getset_descriptors so we type the return as Any.\n    def __get__(self, instance: object, owner: type | None = None, /) -> Any: ...\n\n@disjoint_base\nclass list(MutableSequence[_T]):\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, iterable: Iterable[_T], /) -> None: ...\n    def copy(self) -> list[_T]: ...\n    def append(self, object: _T, /) -> None: ...\n    def extend(self, iterable: Iterable[_T], /) -> None: ...\n    def pop(self, index: SupportsIndex = -1, /) -> _T: ...\n    # Signature of `list.index` should be kept in line with `collections.UserList.index()`\n    # and multiprocessing.managers.ListProxy.index()\n    def index(self, value: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ...\n    def count(self, value: _T, /) -> int: ...\n    def insert(self, index: SupportsIndex, object: _T, /) -> None: ...\n    def remove(self, value: _T, /) -> None: ...\n    # Signature of `list.sort` should be kept inline with `collections.UserList.sort()`\n    # and multiprocessing.managers.ListProxy.sort()\n    #\n    # Use list[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison]\n    # to work around invariance\n    @overload\n    def sort(self: list[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ...\n    @overload\n    def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ...\n    def __len__(self) -> int: ...\n    def __iter__(self) -> Iterator[_T]: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    @overload\n    def __getitem__(self, i: SupportsIndex, /) -> _T: ...\n    @overload\n    def __getitem__(self, s: slice[SupportsIndex | None], /) -> list[_T]: ...\n    @overload\n    def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[_T], /) -> None: ...\n    def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> None: ...\n    # Overloading looks unnecessary, but is needed to work around complex mypy problems\n    @overload\n    def __add__(self, value: list[_T], /) -> list[_T]: ...\n    @overload\n    def __add__(self, value: list[_S], /) -> list[_S | _T]: ...\n    def __iadd__(self, value: Iterable[_T], /) -> Self: ...  # type: ignore[misc]\n    def __mul__(self, value: SupportsIndex, /) -> list[_T]: ...\n    def __rmul__(self, value: SupportsIndex, /) -> list[_T]: ...\n    def __imul__(self, value: SupportsIndex, /) -> Self: ...\n    def __contains__(self, key: object, /) -> bool: ...\n    def __reversed__(self) -> Iterator[_T]: ...\n    def __gt__(self, value: list[_T], /) -> bool: ...\n    def __ge__(self, value: list[_T], /) -> bool: ...\n    def __lt__(self, value: list[_T], /) -> bool: ...\n    def __le__(self, value: list[_T], /) -> bool: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@disjoint_base\nclass dict(MutableMapping[_KT, _VT]):\n    # __init__ should be kept roughly in line with `collections.UserDict.__init__`, which has similar semantics\n    # Also multiprocessing.managers.SyncManager.dict()\n    @overload\n    def __init__(self, /) -> None: ...\n    @overload\n    def __init__(self: dict[str, _VT], /, **kwargs: _VT) -> None: ...  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n    @overload\n    def __init__(self, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ...\n    @overload\n    def __init__(\n        self: dict[str, _VT],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        map: SupportsKeysAndGetItem[str, _VT],\n        /,\n        **kwargs: _VT,\n    ) -> None: ...\n    @overload\n    def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ...\n    @overload\n    def __init__(\n        self: dict[str, _VT],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        iterable: Iterable[tuple[str, _VT]],\n        /,\n        **kwargs: _VT,\n    ) -> None: ...\n    # Next two overloads are for dict(string.split(sep) for string in iterable)\n    # Cannot be Iterable[Sequence[_T]] or otherwise dict([\"foo\", \"bar\", \"baz\"]) is not an error\n    @overload\n    def __init__(self: dict[str, str], iterable: Iterable[list[str]], /) -> None: ...\n    @overload\n    def __init__(self: dict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ...\n    def __new__(cls, /, *args: Any, **kwargs: Any) -> Self: ...\n    def copy(self) -> dict[_KT, _VT]: ...\n    def keys(self) -> dict_keys[_KT, _VT]: ...\n    def values(self) -> dict_values[_KT, _VT]: ...\n    def items(self) -> dict_items[_KT, _VT]: ...\n    # Signature of `dict.fromkeys` should be kept identical to\n    # `fromkeys` methods of `OrderedDict`/`ChainMap`/`UserDict` in `collections`\n    # TODO: the true signature of `dict.fromkeys` is not expressible in the current type system.\n    # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963.\n    @classmethod\n    @overload\n    def fromkeys(cls, iterable: Iterable[_T], value: None = None, /) -> dict[_T, Any | None]: ...\n    @classmethod\n    @overload\n    def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> dict[_T, _S]: ...\n    # Positional-only in dict, but not in MutableMapping\n    @overload  # type: ignore[override]\n    def get(self, key: _KT, default: None = None, /) -> _VT | None: ...\n    @overload\n    def get(self, key: _KT, default: _VT, /) -> _VT: ...\n    @overload\n    def get(self, key: _KT, default: _T, /) -> _VT | _T: ...\n    @overload\n    def pop(self, key: _KT, /) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _VT, /) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _T, /) -> _VT | _T: ...\n    def __len__(self) -> int: ...\n    def __getitem__(self, key: _KT, /) -> _VT: ...\n    def __setitem__(self, key: _KT, value: _VT, /) -> None: ...\n    def __delitem__(self, key: _KT, /) -> None: ...\n    def __iter__(self) -> Iterator[_KT]: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __reversed__(self) -> Iterator[_KT]: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n    @overload\n    def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ...\n    @overload\n    def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ...\n    @overload\n    def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ...\n    @overload\n    def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ...\n    # dict.__ior__ should be kept roughly in line with MutableMapping.update()\n    @overload  # type: ignore[misc]\n    def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ...\n    @overload\n    def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ...\n\n@disjoint_base\nclass set(MutableSet[_T]):\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, iterable: Iterable[_T], /) -> None: ...\n    def add(self, element: _T, /) -> None: ...\n    def copy(self) -> set[_T]: ...\n    def difference(self, *s: Iterable[Any]) -> set[_T]: ...\n    def difference_update(self, *s: Iterable[Any]) -> None: ...\n    def discard(self, element: _T, /) -> None: ...\n    def intersection(self, *s: Iterable[Any]) -> set[_T]: ...\n    def intersection_update(self, *s: Iterable[Any]) -> None: ...\n    def isdisjoint(self, s: Iterable[Any], /) -> bool: ...\n    def issubset(self, s: Iterable[Any], /) -> bool: ...\n    def issuperset(self, s: Iterable[Any], /) -> bool: ...\n    def remove(self, element: _T, /) -> None: ...\n    def symmetric_difference(self, s: Iterable[_T], /) -> set[_T]: ...\n    def symmetric_difference_update(self, s: Iterable[_T], /) -> None: ...\n    def union(self, *s: Iterable[_S]) -> set[_T | _S]: ...\n    def update(self, *s: Iterable[_T]) -> None: ...\n    def __len__(self) -> int: ...\n    def __contains__(self, o: object, /) -> bool: ...\n    def __iter__(self) -> Iterator[_T]: ...\n    def __and__(self, value: AbstractSet[object], /) -> set[_T]: ...\n    def __iand__(self, value: AbstractSet[object], /) -> Self: ...\n    def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ...\n    def __ior__(self, value: AbstractSet[_T], /) -> Self: ...  # type: ignore[override,misc]\n    def __sub__(self, value: AbstractSet[object], /) -> set[_T]: ...\n    def __isub__(self, value: AbstractSet[object], /) -> Self: ...\n    def __xor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ...\n    def __ixor__(self, value: AbstractSet[_T], /) -> Self: ...  # type: ignore[override,misc]\n    def __le__(self, value: AbstractSet[object], /) -> bool: ...\n    def __lt__(self, value: AbstractSet[object], /) -> bool: ...\n    def __ge__(self, value: AbstractSet[object], /) -> bool: ...\n    def __gt__(self, value: AbstractSet[object], /) -> bool: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@disjoint_base\nclass frozenset(AbstractSet[_T_co]):\n    @overload\n    def __new__(cls) -> Self: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T_co], /) -> Self: ...\n    def copy(self) -> frozenset[_T_co]: ...\n    def difference(self, *s: Iterable[object]) -> frozenset[_T_co]: ...\n    def intersection(self, *s: Iterable[object]) -> frozenset[_T_co]: ...\n    def isdisjoint(self, s: Iterable[_T_co], /) -> bool: ...\n    def issubset(self, s: Iterable[object], /) -> bool: ...\n    def issuperset(self, s: Iterable[object], /) -> bool: ...\n    def symmetric_difference(self, s: Iterable[_T_co], /) -> frozenset[_T_co]: ...\n    def union(self, *s: Iterable[_S]) -> frozenset[_T_co | _S]: ...\n    def __len__(self) -> int: ...\n    def __contains__(self, o: object, /) -> bool: ...\n    def __iter__(self) -> Iterator[_T_co]: ...\n    def __and__(self, value: AbstractSet[_T_co], /) -> frozenset[_T_co]: ...\n    def __or__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ...\n    def __sub__(self, value: AbstractSet[object], /) -> frozenset[_T_co]: ...\n    def __xor__(self, value: AbstractSet[_S], /) -> frozenset[_T_co | _S]: ...\n    def __le__(self, value: AbstractSet[object], /) -> bool: ...\n    def __lt__(self, value: AbstractSet[object], /) -> bool: ...\n    def __ge__(self, value: AbstractSet[object], /) -> bool: ...\n    def __gt__(self, value: AbstractSet[object], /) -> bool: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@disjoint_base\nclass enumerate(Iterator[tuple[int, _T]]):\n    def __new__(cls, iterable: Iterable[_T], start: int = 0) -> Self: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> tuple[int, _T]: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@final\nclass range(Sequence[int]):\n    @property\n    def start(self) -> int: ...\n    @property\n    def stop(self) -> int: ...\n    @property\n    def step(self) -> int: ...\n    @overload\n    def __new__(cls, stop: SupportsIndex, /) -> Self: ...\n    @overload\n    def __new__(cls, start: SupportsIndex, stop: SupportsIndex, step: SupportsIndex = 1, /) -> Self: ...\n    def count(self, value: int, /) -> int: ...\n    def index(self, value: int, /) -> int: ...  # type: ignore[override]\n    def __len__(self) -> int: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __contains__(self, key: object, /) -> bool: ...\n    def __iter__(self) -> Iterator[int]: ...\n    @overload\n    def __getitem__(self, key: SupportsIndex, /) -> int: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> range: ...\n    def __reversed__(self) -> Iterator[int]: ...\n\n@disjoint_base\nclass property:\n    fget: Callable[[Any], Any] | None\n    fset: Callable[[Any, Any], None] | None\n    fdel: Callable[[Any], None] | None\n    __isabstractmethod__: bool\n    if sys.version_info >= (3, 13):\n        __name__: str\n\n    def __init__(\n        self,\n        fget: Callable[[Any], Any] | None = None,\n        fset: Callable[[Any, Any], None] | None = None,\n        fdel: Callable[[Any], None] | None = None,\n        doc: str | None = None,\n    ) -> None: ...\n    def getter(self, fget: Callable[[Any], Any], /) -> property: ...\n    def setter(self, fset: Callable[[Any, Any], None], /) -> property: ...\n    def deleter(self, fdel: Callable[[Any], None], /) -> property: ...\n    @overload\n    def __get__(self, instance: None, owner: type, /) -> Self: ...\n    @overload\n    def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ...\n    def __set__(self, instance: Any, value: Any, /) -> None: ...\n    def __delete__(self, instance: Any, /) -> None: ...\n\ndef abs(x: SupportsAbs[_T], /) -> _T: ...\ndef all(iterable: Iterable[object], /) -> bool: ...\ndef any(iterable: Iterable[object], /) -> bool: ...\ndef ascii(obj: object, /) -> str: ...\ndef bin(number: SupportsIndex, /) -> str: ...\ndef breakpoint(*args: Any, **kws: Any) -> None: ...\ndef callable(obj: object, /) -> TypeIs[Callable[..., object]]: ...\ndef chr(i: SupportsIndex, /) -> str: ...\n\nif sys.version_info >= (3, 10):\n    def aiter(async_iterable: SupportsAiter[_SupportsAnextT_co], /) -> _SupportsAnextT_co: ...\n    @type_check_only\n    class _SupportsSynchronousAnext(Protocol[_AwaitableT_co]):\n        def __anext__(self) -> _AwaitableT_co: ...\n\n    @overload\n    # `anext` is not, in fact, an async function. When default is not provided\n    # `anext` is just a passthrough for `obj.__anext__`\n    # See discussion in #7491 and pure-Python implementation of `anext` at https://github.com/python/cpython/blob/ea786a882b9ed4261eafabad6011bc7ef3b5bf94/Lib/test/test_asyncgen.py#L52-L80\n    def anext(i: _SupportsSynchronousAnext[_AwaitableT], /) -> _AwaitableT: ...\n    @overload\n    async def anext(i: SupportsAnext[_T], default: _VT, /) -> _T | _VT: ...\n\n# compile() returns a CodeType, unless the flags argument includes PyCF_ONLY_AST (=1024),\n# in which case it returns ast.AST. We have overloads for flag 0 (the default) and for\n# explicitly passing PyCF_ONLY_AST. We fall back to Any for other values of flags.\n@overload\ndef compile(\n    source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive,\n    filename: str | bytes | PathLike[Any],\n    mode: str,\n    flags: Literal[0],\n    dont_inherit: bool = False,\n    optimize: int = -1,\n    *,\n    _feature_version: int = -1,\n) -> CodeType: ...\n@overload\ndef compile(\n    source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive,\n    filename: str | bytes | PathLike[Any],\n    mode: str,\n    *,\n    dont_inherit: bool = False,\n    optimize: int = -1,\n    _feature_version: int = -1,\n) -> CodeType: ...\n@overload\ndef compile(\n    source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive,\n    filename: str | bytes | PathLike[Any],\n    mode: str,\n    flags: Literal[1024],\n    dont_inherit: bool = False,\n    optimize: int = -1,\n    *,\n    _feature_version: int = -1,\n) -> _ast.AST: ...\n@overload\ndef compile(\n    source: str | ReadableBuffer | _ast.Module | _ast.Expression | _ast.Interactive,\n    filename: str | bytes | PathLike[Any],\n    mode: str,\n    flags: int,\n    dont_inherit: bool = False,\n    optimize: int = -1,\n    *,\n    _feature_version: int = -1,\n) -> Any: ...\n\ncopyright: _sitebuiltins._Printer\ncredits: _sitebuiltins._Printer\n\ndef delattr(obj: object, name: str, /) -> None: ...\ndef dir(o: object = ..., /) -> list[str]: ...\n@overload\ndef divmod(x: SupportsDivMod[_T_contra, _T_co], y: _T_contra, /) -> _T_co: ...\n@overload\ndef divmod(x: _T_contra, y: SupportsRDivMod[_T_contra, _T_co], /) -> _T_co: ...\n\n# The `globals` argument to `eval` has to be `dict[str, Any]` rather than `dict[str, object]` due to invariance.\n# (The `globals` argument has to be a \"real dict\", rather than any old mapping, unlike the `locals` argument.)\nif sys.version_info >= (3, 13):\n    def eval(\n        source: str | ReadableBuffer | CodeType,\n        /,\n        globals: dict[str, Any] | None = None,\n        locals: Mapping[str, object] | None = None,\n    ) -> Any: ...\n\nelse:\n    def eval(\n        source: str | ReadableBuffer | CodeType,\n        globals: dict[str, Any] | None = None,\n        locals: Mapping[str, object] | None = None,\n        /,\n    ) -> Any: ...\n\n# Comment above regarding `eval` applies to `exec` as well\nif sys.version_info >= (3, 13):\n    def exec(\n        source: str | ReadableBuffer | CodeType,\n        /,\n        globals: dict[str, Any] | None = None,\n        locals: Mapping[str, object] | None = None,\n        *,\n        closure: tuple[CellType, ...] | None = None,\n    ) -> None: ...\n\nelif sys.version_info >= (3, 11):\n    def exec(\n        source: str | ReadableBuffer | CodeType,\n        globals: dict[str, Any] | None = None,\n        locals: Mapping[str, object] | None = None,\n        /,\n        *,\n        closure: tuple[CellType, ...] | None = None,\n    ) -> None: ...\n\nelse:\n    def exec(\n        source: str | ReadableBuffer | CodeType,\n        globals: dict[str, Any] | None = None,\n        locals: Mapping[str, object] | None = None,\n        /,\n    ) -> None: ...\n\nexit: _sitebuiltins.Quitter\n\n@disjoint_base\nclass filter(Iterator[_T]):\n    @overload\n    def __new__(cls, function: None, iterable: Iterable[_T | None], /) -> Self: ...\n    @overload\n    def __new__(cls, function: Callable[[_S], TypeGuard[_T]], iterable: Iterable[_S], /) -> Self: ...\n    @overload\n    def __new__(cls, function: Callable[[_S], TypeIs[_T]], iterable: Iterable[_S], /) -> Self: ...\n    @overload\n    def __new__(cls, function: Callable[[_T], Any], iterable: Iterable[_T], /) -> Self: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T: ...\n\ndef format(value: object, format_spec: str = \"\", /) -> str: ...\n@overload\ndef getattr(o: object, name: str, /) -> Any: ...\n\n# While technically covered by the last overload, spelling out the types for None, bool\n# and basic containers help mypy out in some tricky situations involving type context\n# (aka bidirectional inference)\n@overload\ndef getattr(o: object, name: str, default: None, /) -> Any | None: ...\n@overload\ndef getattr(o: object, name: str, default: bool, /) -> Any | bool: ...\n@overload\ndef getattr(o: object, name: str, default: list[Any], /) -> Any | list[Any]: ...\n@overload\ndef getattr(o: object, name: str, default: dict[Any, Any], /) -> Any | dict[Any, Any]: ...\n@overload\ndef getattr(o: object, name: str, default: _T, /) -> Any | _T: ...\ndef globals() -> dict[str, Any]: ...\ndef hasattr(obj: object, name: str, /) -> bool: ...\ndef hash(obj: object, /) -> int: ...\n\nhelp: _sitebuiltins._Helper\n\ndef hex(number: SupportsIndex, /) -> str: ...\ndef id(obj: object, /) -> int: ...\ndef input(prompt: object = \"\", /) -> str: ...\n@type_check_only\nclass _GetItemIterable(Protocol[_T_co]):\n    def __getitem__(self, i: int, /) -> _T_co: ...\n\n@overload\ndef iter(object: SupportsIter[_SupportsNextT_co], /) -> _SupportsNextT_co: ...\n@overload\ndef iter(object: _GetItemIterable[_T], /) -> Iterator[_T]: ...\n@overload\ndef iter(object: Callable[[], _T | None], sentinel: None, /) -> Iterator[_T]: ...\n@overload\ndef iter(object: Callable[[], _T], sentinel: object, /) -> Iterator[_T]: ...\n\nif sys.version_info >= (3, 10):\n    _ClassInfo: TypeAlias = type | types.UnionType | tuple[_ClassInfo, ...]\nelse:\n    _ClassInfo: TypeAlias = type | tuple[_ClassInfo, ...]\n\ndef isinstance(obj: object, class_or_tuple: _ClassInfo, /) -> bool: ...\ndef issubclass(cls: type, class_or_tuple: _ClassInfo, /) -> bool: ...\ndef len(obj: Sized, /) -> int: ...\n\nlicense: _sitebuiltins._Printer\n\ndef locals() -> dict[str, Any]: ...\n@disjoint_base\nclass map(Iterator[_S]):\n    # 3.14 adds `strict` argument.\n    if sys.version_info >= (3, 14):\n        @overload\n        def __new__(cls, func: Callable[[_T1], _S], iterable: Iterable[_T1], /, *, strict: bool = False) -> Self: ...\n        @overload\n        def __new__(\n            cls, func: Callable[[_T1, _T2], _S], iterable: Iterable[_T1], iter2: Iterable[_T2], /, *, strict: bool = False\n        ) -> Self: ...\n        @overload\n        def __new__(\n            cls,\n            func: Callable[[_T1, _T2, _T3], _S],\n            iterable: Iterable[_T1],\n            iter2: Iterable[_T2],\n            iter3: Iterable[_T3],\n            /,\n            *,\n            strict: bool = False,\n        ) -> Self: ...\n        @overload\n        def __new__(\n            cls,\n            func: Callable[[_T1, _T2, _T3, _T4], _S],\n            iterable: Iterable[_T1],\n            iter2: Iterable[_T2],\n            iter3: Iterable[_T3],\n            iter4: Iterable[_T4],\n            /,\n            *,\n            strict: bool = False,\n        ) -> Self: ...\n        @overload\n        def __new__(\n            cls,\n            func: Callable[[_T1, _T2, _T3, _T4, _T5], _S],\n            iterable: Iterable[_T1],\n            iter2: Iterable[_T2],\n            iter3: Iterable[_T3],\n            iter4: Iterable[_T4],\n            iter5: Iterable[_T5],\n            /,\n            *,\n            strict: bool = False,\n        ) -> Self: ...\n        @overload\n        def __new__(\n            cls,\n            func: Callable[..., _S],\n            iterable: Iterable[Any],\n            iter2: Iterable[Any],\n            iter3: Iterable[Any],\n            iter4: Iterable[Any],\n            iter5: Iterable[Any],\n            iter6: Iterable[Any],\n            /,\n            *iterables: Iterable[Any],\n            strict: bool = False,\n        ) -> Self: ...\n    else:\n        @overload\n        def __new__(cls, func: Callable[[_T1], _S], iterable: Iterable[_T1], /) -> Self: ...\n        @overload\n        def __new__(cls, func: Callable[[_T1, _T2], _S], iterable: Iterable[_T1], iter2: Iterable[_T2], /) -> Self: ...\n        @overload\n        def __new__(\n            cls, func: Callable[[_T1, _T2, _T3], _S], iterable: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /\n        ) -> Self: ...\n        @overload\n        def __new__(\n            cls,\n            func: Callable[[_T1, _T2, _T3, _T4], _S],\n            iterable: Iterable[_T1],\n            iter2: Iterable[_T2],\n            iter3: Iterable[_T3],\n            iter4: Iterable[_T4],\n            /,\n        ) -> Self: ...\n        @overload\n        def __new__(\n            cls,\n            func: Callable[[_T1, _T2, _T3, _T4, _T5], _S],\n            iterable: Iterable[_T1],\n            iter2: Iterable[_T2],\n            iter3: Iterable[_T3],\n            iter4: Iterable[_T4],\n            iter5: Iterable[_T5],\n            /,\n        ) -> Self: ...\n        @overload\n        def __new__(\n            cls,\n            func: Callable[..., _S],\n            iterable: Iterable[Any],\n            iter2: Iterable[Any],\n            iter3: Iterable[Any],\n            iter4: Iterable[Any],\n            iter5: Iterable[Any],\n            iter6: Iterable[Any],\n            /,\n            *iterables: Iterable[Any],\n        ) -> Self: ...\n\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _S: ...\n\n@overload\ndef max(\n    arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None\n) -> SupportsRichComparisonT: ...\n@overload\ndef max(arg1: _T, arg2: _T, /, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ...\n@overload\ndef max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None) -> SupportsRichComparisonT: ...\n@overload\ndef max(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison]) -> _T: ...\n@overload\ndef max(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ...\n@overload\ndef max(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ...\n@overload\ndef min(\n    arg1: SupportsRichComparisonT, arg2: SupportsRichComparisonT, /, *_args: SupportsRichComparisonT, key: None = None\n) -> SupportsRichComparisonT: ...\n@overload\ndef min(arg1: _T, arg2: _T, /, *_args: _T, key: Callable[[_T], SupportsRichComparison]) -> _T: ...\n@overload\ndef min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None) -> SupportsRichComparisonT: ...\n@overload\ndef min(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison]) -> _T: ...\n@overload\ndef min(iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, default: _T) -> SupportsRichComparisonT | _T: ...\n@overload\ndef min(iterable: Iterable[_T1], /, *, key: Callable[[_T1], SupportsRichComparison], default: _T2) -> _T1 | _T2: ...\n@overload\ndef next(i: SupportsNext[_T], /) -> _T: ...\n@overload\ndef next(i: SupportsNext[_T], default: _VT, /) -> _T | _VT: ...\ndef oct(number: SupportsIndex, /) -> str: ...\n\n_Opener: TypeAlias = Callable[[str, int], int]\n\n# Text mode: always returns a TextIOWrapper\n@overload\ndef open(\n    file: FileDescriptorOrPath,\n    mode: OpenTextMode = \"r\",\n    buffering: int = -1,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> TextIOWrapper: ...\n\n# Unbuffered binary mode: returns a FileIO\n@overload\ndef open(\n    file: FileDescriptorOrPath,\n    mode: OpenBinaryMode,\n    buffering: Literal[0],\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> FileIO: ...\n\n# Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter\n@overload\ndef open(\n    file: FileDescriptorOrPath,\n    mode: OpenBinaryModeUpdating,\n    buffering: Literal[-1, 1] = -1,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> BufferedRandom: ...\n@overload\ndef open(\n    file: FileDescriptorOrPath,\n    mode: OpenBinaryModeWriting,\n    buffering: Literal[-1, 1] = -1,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> BufferedWriter: ...\n@overload\ndef open(\n    file: FileDescriptorOrPath,\n    mode: OpenBinaryModeReading,\n    buffering: Literal[-1, 1] = -1,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> BufferedReader: ...\n\n# Buffering cannot be determined: fall back to BinaryIO\n@overload\ndef open(\n    file: FileDescriptorOrPath,\n    mode: OpenBinaryMode,\n    buffering: int = -1,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> BinaryIO: ...\n\n# Fallback if mode is not specified\n@overload\ndef open(\n    file: FileDescriptorOrPath,\n    mode: str,\n    buffering: int = -1,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> IO[Any]: ...\ndef ord(c: str | bytes | bytearray, /) -> int: ...\n@type_check_only\nclass _SupportsWriteAndFlush(SupportsWrite[_T_contra], SupportsFlush, Protocol[_T_contra]): ...\n\n@overload\ndef print(\n    *values: object,\n    sep: str | None = \" \",\n    end: str | None = \"\\n\",\n    file: SupportsWrite[str] | None = None,\n    flush: Literal[False] = False,\n) -> None: ...\n@overload\ndef print(\n    *values: object, sep: str | None = \" \", end: str | None = \"\\n\", file: _SupportsWriteAndFlush[str] | None = None, flush: bool\n) -> None: ...\n\n_E_contra = TypeVar(\"_E_contra\", contravariant=True)\n_M_contra = TypeVar(\"_M_contra\", contravariant=True)\n\n@type_check_only\nclass _SupportsPow2(Protocol[_E_contra, _T_co]):\n    def __pow__(self, other: _E_contra, /) -> _T_co: ...\n\n@type_check_only\nclass _SupportsPow3NoneOnly(Protocol[_E_contra, _T_co]):\n    def __pow__(self, other: _E_contra, modulo: None = None, /) -> _T_co: ...\n\n@type_check_only\nclass _SupportsPow3(Protocol[_E_contra, _M_contra, _T_co]):\n    def __pow__(self, other: _E_contra, modulo: _M_contra, /) -> _T_co: ...\n\n_SupportsSomeKindOfPow = (  # noqa: Y026  # TODO: Use TypeAlias once mypy bugs are fixed\n    _SupportsPow2[Any, Any] | _SupportsPow3NoneOnly[Any, Any] | _SupportsPow3[Any, Any, Any]\n)\n\n# TODO: `pow(int, int, Literal[0])` fails at runtime,\n# but adding a `NoReturn` overload isn't a good solution for expressing that (see #8566).\n@overload\ndef pow(base: int, exp: int, mod: int) -> int: ...\n@overload\ndef pow(base: int, exp: Literal[0], mod: None = None) -> Literal[1]: ...\n@overload\ndef pow(base: int, exp: _PositiveInteger, mod: None = None) -> int: ...\n@overload\ndef pow(base: int, exp: _NegativeInteger, mod: None = None) -> float: ...\n\n# int base & positive-int exp -> int; int base & negative-int exp -> float\n# return type must be Any as `int | float` causes too many false-positive errors\n@overload\ndef pow(base: int, exp: int, mod: None = None) -> Any: ...\n@overload\ndef pow(base: _PositiveInteger, exp: float, mod: None = None) -> float: ...\n@overload\ndef pow(base: _NegativeInteger, exp: float, mod: None = None) -> complex: ...\n@overload\ndef pow(base: float, exp: int, mod: None = None) -> float: ...\n\n# float base & float exp could return float or complex\n# return type must be Any (same as complex base, complex exp),\n# as `float | complex` causes too many false-positive errors\n@overload\ndef pow(base: float, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> Any: ...\n@overload\ndef pow(base: complex, exp: complex | _SupportsSomeKindOfPow, mod: None = None) -> complex: ...\n@overload\ndef pow(base: _SupportsPow2[_E_contra, _T_co], exp: _E_contra, mod: None = None) -> _T_co: ...  # type: ignore[overload-overlap]\n@overload\ndef pow(base: _SupportsPow3NoneOnly[_E_contra, _T_co], exp: _E_contra, mod: None = None) -> _T_co: ...  # type: ignore[overload-overlap]\n@overload\ndef pow(base: _SupportsPow3[_E_contra, _M_contra, _T_co], exp: _E_contra, mod: _M_contra) -> _T_co: ...\n@overload\ndef pow(base: _SupportsSomeKindOfPow, exp: float, mod: None = None) -> Any: ...\n@overload\ndef pow(base: _SupportsSomeKindOfPow, exp: complex, mod: None = None) -> complex: ...\n\nquit: _sitebuiltins.Quitter\n\n@disjoint_base\nclass reversed(Iterator[_T]):\n    @overload\n    def __new__(cls, sequence: Reversible[_T], /) -> Iterator[_T]: ...  # type: ignore[misc]\n    @overload\n    def __new__(cls, sequence: SupportsLenAndGetItem[_T], /) -> Iterator[_T]: ...  # type: ignore[misc]\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T: ...\n    def __length_hint__(self) -> int: ...\n\ndef repr(obj: object, /) -> str: ...\n\n# See https://github.com/python/typeshed/pull/9141\n# and https://github.com/python/typeshed/pull/9151\n# on why we don't use `SupportsRound` from `typing.pyi`\n\n@type_check_only\nclass _SupportsRound1(Protocol[_T_co]):\n    def __round__(self) -> _T_co: ...\n\n@type_check_only\nclass _SupportsRound2(Protocol[_T_co]):\n    def __round__(self, ndigits: int, /) -> _T_co: ...\n\n@overload\ndef round(number: _SupportsRound1[_T], ndigits: None = None) -> _T: ...\n@overload\ndef round(number: _SupportsRound2[_T], ndigits: SupportsIndex) -> _T: ...\n\n# See https://github.com/python/typeshed/pull/6292#discussion_r748875189\n# for why arg 3 of `setattr` should be annotated with `Any` and not `object`\ndef setattr(obj: object, name: str, value: Any, /) -> None: ...\n@overload\ndef sorted(\n    iterable: Iterable[SupportsRichComparisonT], /, *, key: None = None, reverse: bool = False\n) -> list[SupportsRichComparisonT]: ...\n@overload\ndef sorted(iterable: Iterable[_T], /, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> list[_T]: ...\n\n_AddableT1 = TypeVar(\"_AddableT1\", bound=SupportsAdd[Any, Any])\n_AddableT2 = TypeVar(\"_AddableT2\", bound=SupportsAdd[Any, Any])\n\n@type_check_only\nclass _SupportsSumWithNoDefaultGiven(SupportsAdd[Any, Any], SupportsRAdd[int, Any], Protocol): ...\n\n_SupportsSumNoDefaultT = TypeVar(\"_SupportsSumNoDefaultT\", bound=_SupportsSumWithNoDefaultGiven)\n\n# In general, the return type of `x + x` is *not* guaranteed to be the same type as x.\n# However, we can't express that in the stub for `sum()`\n# without creating many false-positive errors (see #7578).\n# Instead, we special-case the most common examples of this: bool and literal integers.\n@overload\ndef sum(iterable: Iterable[bool], /, start: int = 0) -> int: ...\n@overload\ndef sum(iterable: Iterable[_SupportsSumNoDefaultT], /) -> _SupportsSumNoDefaultT | Literal[0]: ...\n@overload\ndef sum(iterable: Iterable[_AddableT1], /, start: _AddableT2) -> _AddableT1 | _AddableT2: ...\n\n# The argument to `vars()` has to have a `__dict__` attribute, so the second overload can't be annotated with `object`\n# (A \"SupportsDunderDict\" protocol doesn't work)\n@overload\ndef vars(object: type, /) -> types.MappingProxyType[str, Any]: ...\n@overload\ndef vars(object: Any = ..., /) -> dict[str, Any]: ...\n@disjoint_base\nclass zip(Iterator[_T_co]):\n    if sys.version_info >= (3, 10):\n        @overload\n        def __new__(cls, *, strict: bool = False) -> zip[Any]: ...\n        @overload\n        def __new__(cls, iter1: Iterable[_T1], /, *, strict: bool = False) -> zip[tuple[_T1]]: ...\n        @overload\n        def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, strict: bool = False) -> zip[tuple[_T1, _T2]]: ...\n        @overload\n        def __new__(\n            cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, strict: bool = False\n        ) -> zip[tuple[_T1, _T2, _T3]]: ...\n        @overload\n        def __new__(\n            cls,\n            iter1: Iterable[_T1],\n            iter2: Iterable[_T2],\n            iter3: Iterable[_T3],\n            iter4: Iterable[_T4],\n            /,\n            *,\n            strict: bool = False,\n        ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ...\n        @overload\n        def __new__(\n            cls,\n            iter1: Iterable[_T1],\n            iter2: Iterable[_T2],\n            iter3: Iterable[_T3],\n            iter4: Iterable[_T4],\n            iter5: Iterable[_T5],\n            /,\n            *,\n            strict: bool = False,\n        ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ...\n        @overload\n        def __new__(\n            cls,\n            iter1: Iterable[Any],\n            iter2: Iterable[Any],\n            iter3: Iterable[Any],\n            iter4: Iterable[Any],\n            iter5: Iterable[Any],\n            iter6: Iterable[Any],\n            /,\n            *iterables: Iterable[Any],\n            strict: bool = False,\n        ) -> zip[tuple[Any, ...]]: ...\n    else:\n        @overload\n        def __new__(cls) -> zip[Any]: ...\n        @overload\n        def __new__(cls, iter1: Iterable[_T1], /) -> zip[tuple[_T1]]: ...\n        @overload\n        def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> zip[tuple[_T1, _T2]]: ...\n        @overload\n        def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /) -> zip[tuple[_T1, _T2, _T3]]: ...\n        @overload\n        def __new__(\n            cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /\n        ) -> zip[tuple[_T1, _T2, _T3, _T4]]: ...\n        @overload\n        def __new__(\n            cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], /\n        ) -> zip[tuple[_T1, _T2, _T3, _T4, _T5]]: ...\n        @overload\n        def __new__(\n            cls,\n            iter1: Iterable[Any],\n            iter2: Iterable[Any],\n            iter3: Iterable[Any],\n            iter4: Iterable[Any],\n            iter5: Iterable[Any],\n            iter6: Iterable[Any],\n            /,\n            *iterables: Iterable[Any],\n        ) -> zip[tuple[Any, ...]]: ...\n\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T_co: ...\n\n# Signature of `builtins.__import__` should be kept identical to `importlib.__import__`\n# Return type of `__import__` should be kept the same as return type of `importlib.import_module`\ndef __import__(\n    name: str,\n    globals: Mapping[str, object] | None = None,\n    locals: Mapping[str, object] | None = None,\n    fromlist: Sequence[str] | None = (),\n    level: int = 0,\n) -> types.ModuleType: ...\ndef __build_class__(func: Callable[[], CellType | Any], name: str, /, *bases: Any, metaclass: Any = ..., **kwds: Any) -> Any: ...\n\nif sys.version_info >= (3, 10):\n    from types import EllipsisType, NotImplementedType\n\n    # Backwards compatibility hack for folks who relied on the ellipsis type\n    # existing in typeshed in Python 3.9 and earlier.\n    ellipsis = EllipsisType\n\n    Ellipsis: EllipsisType\n    NotImplemented: NotImplementedType\nelse:\n    # Actually the type of Ellipsis is <type 'ellipsis'>, but since it's\n    # not exposed anywhere under that name, we make it private here.\n    @final\n    @type_check_only\n    class ellipsis: ...\n\n    Ellipsis: ellipsis\n\n    @final\n    @type_check_only\n    class _NotImplementedType(Any): ...\n\n    NotImplemented: _NotImplementedType\n\n@disjoint_base\nclass BaseException:\n    args: tuple[Any, ...]\n    __cause__: BaseException | None\n    __context__: BaseException | None\n    __suppress_context__: bool\n    __traceback__: TracebackType | None\n    def __init__(self, *args: object) -> None: ...\n    def __new__(cls, *args: Any, **kwds: Any) -> Self: ...\n    def __setstate__(self, state: dict[str, Any] | None, /) -> None: ...\n    def with_traceback(self, tb: TracebackType | None, /) -> Self: ...\n    # Necessary for security-focused static analyzers (e.g, pysa)\n    # See https://github.com/python/typeshed/pull/14900\n    def __str__(self) -> str: ...  # noqa: Y029\n    def __repr__(self) -> str: ...  # noqa: Y029\n    if sys.version_info >= (3, 11):\n        # only present after add_note() is called\n        __notes__: list[str]\n        def add_note(self, note: str, /) -> None: ...\n\nclass GeneratorExit(BaseException): ...\nclass KeyboardInterrupt(BaseException): ...\n\n@disjoint_base\nclass SystemExit(BaseException):\n    code: sys._ExitCode\n\nclass Exception(BaseException): ...\n\n@disjoint_base\nclass StopIteration(Exception):\n    value: Any\n\n@disjoint_base\nclass OSError(Exception):\n    errno: int | None\n    strerror: str | None\n    # filename, filename2 are actually str | bytes | None\n    filename: Any\n    filename2: Any\n    if sys.platform == \"win32\":\n        winerror: int\n\nEnvironmentError = OSError\nIOError = OSError\nif sys.platform == \"win32\":\n    WindowsError = OSError\n\nclass ArithmeticError(Exception): ...\nclass AssertionError(Exception): ...\n\nif sys.version_info >= (3, 10):\n    @disjoint_base\n    class AttributeError(Exception):\n        def __init__(self, *args: object, name: str | None = None, obj: object = None) -> None: ...\n        name: str | None\n        obj: object\n\nelse:\n    class AttributeError(Exception): ...\n\nclass BufferError(Exception): ...\nclass EOFError(Exception): ...\n\n@disjoint_base\nclass ImportError(Exception):\n    def __init__(self, *args: object, name: str | None = None, path: str | None = None) -> None: ...\n    name: str | None\n    path: str | None\n    msg: str  # undocumented\n    if sys.version_info >= (3, 12):\n        name_from: str | None  # undocumented\n\nclass LookupError(Exception): ...\nclass MemoryError(Exception): ...\n\nif sys.version_info >= (3, 10):\n    @disjoint_base\n    class NameError(Exception):\n        def __init__(self, *args: object, name: str | None = None) -> None: ...\n        name: str | None\n\nelse:\n    class NameError(Exception): ...\n\nclass ReferenceError(Exception): ...\nclass RuntimeError(Exception): ...\nclass StopAsyncIteration(Exception): ...\n\n@disjoint_base\nclass SyntaxError(Exception):\n    msg: str\n    filename: str | None\n    lineno: int | None\n    offset: int | None\n    text: str | None\n    # Errors are displayed differently if this attribute exists on the exception.\n    # The value is always None.\n    print_file_and_line: None\n    if sys.version_info >= (3, 10):\n        end_lineno: int | None\n        end_offset: int | None\n\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, msg: object, /) -> None: ...\n    # Second argument is the tuple (filename, lineno, offset, text)\n    @overload\n    def __init__(self, msg: str, info: tuple[str | None, int | None, int | None, str | None], /) -> None: ...\n    if sys.version_info >= (3, 10):\n        # end_lineno and end_offset must both be provided if one is.\n        @overload\n        def __init__(\n            self, msg: str, info: tuple[str | None, int | None, int | None, str | None, int | None, int | None], /\n        ) -> None: ...\n    # If you provide more than two arguments, it still creates the SyntaxError, but\n    # the arguments from the info tuple are not parsed. This form is omitted.\n\nclass SystemError(Exception): ...\nclass TypeError(Exception): ...\nclass ValueError(Exception): ...\nclass FloatingPointError(ArithmeticError): ...\nclass OverflowError(ArithmeticError): ...\nclass ZeroDivisionError(ArithmeticError): ...\nclass ModuleNotFoundError(ImportError): ...\nclass IndexError(LookupError): ...\nclass KeyError(LookupError): ...\nclass UnboundLocalError(NameError): ...\n\nclass BlockingIOError(OSError):\n    characters_written: int\n\nclass ChildProcessError(OSError): ...\nclass ConnectionError(OSError): ...\nclass BrokenPipeError(ConnectionError): ...\nclass ConnectionAbortedError(ConnectionError): ...\nclass ConnectionRefusedError(ConnectionError): ...\nclass ConnectionResetError(ConnectionError): ...\nclass FileExistsError(OSError): ...\nclass FileNotFoundError(OSError): ...\nclass InterruptedError(OSError): ...\nclass IsADirectoryError(OSError): ...\nclass NotADirectoryError(OSError): ...\nclass PermissionError(OSError): ...\nclass ProcessLookupError(OSError): ...\nclass TimeoutError(OSError): ...\nclass NotImplementedError(RuntimeError): ...\nclass RecursionError(RuntimeError): ...\nclass IndentationError(SyntaxError): ...\nclass TabError(IndentationError): ...\nclass UnicodeError(ValueError): ...\n\n@disjoint_base\nclass UnicodeDecodeError(UnicodeError):\n    encoding: str\n    object: bytes\n    start: int\n    end: int\n    reason: str\n    def __init__(self, encoding: str, object: ReadableBuffer, start: int, end: int, reason: str, /) -> None: ...\n\n@disjoint_base\nclass UnicodeEncodeError(UnicodeError):\n    encoding: str\n    object: str\n    start: int\n    end: int\n    reason: str\n    def __init__(self, encoding: str, object: str, start: int, end: int, reason: str, /) -> None: ...\n\n@disjoint_base\nclass UnicodeTranslateError(UnicodeError):\n    encoding: None\n    object: str\n    start: int\n    end: int\n    reason: str\n    def __init__(self, object: str, start: int, end: int, reason: str, /) -> None: ...\n\nclass Warning(Exception): ...\nclass UserWarning(Warning): ...\nclass DeprecationWarning(Warning): ...\nclass SyntaxWarning(Warning): ...\nclass RuntimeWarning(Warning): ...\nclass FutureWarning(Warning): ...\nclass PendingDeprecationWarning(Warning): ...\nclass ImportWarning(Warning): ...\nclass UnicodeWarning(Warning): ...\nclass BytesWarning(Warning): ...\nclass ResourceWarning(Warning): ...\n\nif sys.version_info >= (3, 10):\n    class EncodingWarning(Warning): ...\n\nif sys.version_info >= (3, 11):\n    _BaseExceptionT_co = TypeVar(\"_BaseExceptionT_co\", bound=BaseException, covariant=True, default=BaseException)\n    _BaseExceptionT = TypeVar(\"_BaseExceptionT\", bound=BaseException)\n    _ExceptionT_co = TypeVar(\"_ExceptionT_co\", bound=Exception, covariant=True, default=Exception)\n    _ExceptionT = TypeVar(\"_ExceptionT\", bound=Exception)\n\n    # See `check_exception_group.py` for use-cases and comments.\n    @disjoint_base\n    class BaseExceptionGroup(BaseException, Generic[_BaseExceptionT_co]):\n        def __new__(cls, message: str, exceptions: Sequence[_BaseExceptionT_co], /) -> Self: ...\n        def __init__(self, message: str, exceptions: Sequence[_BaseExceptionT_co], /) -> None: ...\n        @property\n        def message(self) -> str: ...\n        @property\n        def exceptions(self) -> tuple[_BaseExceptionT_co | BaseExceptionGroup[_BaseExceptionT_co], ...]: ...\n        @overload\n        def subgroup(\n            self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], /\n        ) -> ExceptionGroup[_ExceptionT] | None: ...\n        @overload\n        def subgroup(\n            self, matcher_value: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...], /\n        ) -> BaseExceptionGroup[_BaseExceptionT] | None: ...\n        @overload\n        def subgroup(\n            self, matcher_value: Callable[[_BaseExceptionT_co | Self], bool], /\n        ) -> BaseExceptionGroup[_BaseExceptionT_co] | None: ...\n        @overload\n        def split(\n            self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], /\n        ) -> tuple[ExceptionGroup[_ExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ...\n        @overload\n        def split(\n            self, matcher_value: type[_BaseExceptionT] | tuple[type[_BaseExceptionT], ...], /\n        ) -> tuple[BaseExceptionGroup[_BaseExceptionT] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ...\n        @overload\n        def split(\n            self, matcher_value: Callable[[_BaseExceptionT_co | Self], bool], /\n        ) -> tuple[BaseExceptionGroup[_BaseExceptionT_co] | None, BaseExceptionGroup[_BaseExceptionT_co] | None]: ...\n        # In reality it is `NonEmptySequence`:\n        @overload\n        def derive(self, excs: Sequence[_ExceptionT], /) -> ExceptionGroup[_ExceptionT]: ...\n        @overload\n        def derive(self, excs: Sequence[_BaseExceptionT], /) -> BaseExceptionGroup[_BaseExceptionT]: ...\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n    class ExceptionGroup(BaseExceptionGroup[_ExceptionT_co], Exception):\n        def __new__(cls, message: str, exceptions: Sequence[_ExceptionT_co], /) -> Self: ...\n        def __init__(self, message: str, exceptions: Sequence[_ExceptionT_co], /) -> None: ...\n        @property\n        def exceptions(self) -> tuple[_ExceptionT_co | ExceptionGroup[_ExceptionT_co], ...]: ...\n        # We accept a narrower type, but that's OK.\n        @overload  # type: ignore[override]\n        def subgroup(\n            self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], /\n        ) -> ExceptionGroup[_ExceptionT] | None: ...\n        @overload\n        def subgroup(\n            self, matcher_value: Callable[[_ExceptionT_co | Self], bool], /\n        ) -> ExceptionGroup[_ExceptionT_co] | None: ...\n        @overload  # type: ignore[override]\n        def split(\n            self, matcher_value: type[_ExceptionT] | tuple[type[_ExceptionT], ...], /\n        ) -> tuple[ExceptionGroup[_ExceptionT] | None, ExceptionGroup[_ExceptionT_co] | None]: ...\n        @overload\n        def split(\n            self, matcher_value: Callable[[_ExceptionT_co | Self], bool], /\n        ) -> tuple[ExceptionGroup[_ExceptionT_co] | None, ExceptionGroup[_ExceptionT_co] | None]: ...\n\nif sys.version_info >= (3, 13):\n    class PythonFinalizationError(RuntimeError): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/bz2.pyi",
    "content": "import sys\nfrom _bz2 import BZ2Compressor as BZ2Compressor, BZ2Decompressor as BZ2Decompressor\nfrom _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer\nfrom collections.abc import Iterable\nfrom io import TextIOWrapper\nfrom typing import IO, Literal, Protocol, SupportsIndex, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 14):\n    from compression._common._streams import BaseStream, _Reader\nelse:\n    from _compression import BaseStream, _Reader\n\n__all__ = [\"BZ2File\", \"BZ2Compressor\", \"BZ2Decompressor\", \"open\", \"compress\", \"decompress\"]\n\n# The following attributes and methods are optional:\n# def fileno(self) -> int: ...\n# def close(self) -> object: ...\n@type_check_only\nclass _ReadableFileobj(_Reader, Protocol): ...\n\n@type_check_only\nclass _WritableFileobj(Protocol):\n    def write(self, b: bytes, /) -> object: ...\n    # The following attributes and methods are optional:\n    # def fileno(self) -> int: ...\n    # def close(self) -> object: ...\n\ndef compress(data: ReadableBuffer, compresslevel: int = 9) -> bytes: ...\ndef decompress(data: ReadableBuffer) -> bytes: ...\n\n_ReadBinaryMode: TypeAlias = Literal[\"\", \"r\", \"rb\"]\n_WriteBinaryMode: TypeAlias = Literal[\"w\", \"wb\", \"x\", \"xb\", \"a\", \"ab\"]\n_ReadTextMode: TypeAlias = Literal[\"rt\"]\n_WriteTextMode: TypeAlias = Literal[\"wt\", \"xt\", \"at\"]\n\n@overload\ndef open(\n    filename: _ReadableFileobj,\n    mode: _ReadBinaryMode = \"rb\",\n    compresslevel: int = 9,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n) -> BZ2File: ...\n@overload\ndef open(\n    filename: _ReadableFileobj,\n    mode: _ReadTextMode,\n    compresslevel: int = 9,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> TextIOWrapper: ...\n@overload\ndef open(\n    filename: _WritableFileobj,\n    mode: _WriteBinaryMode,\n    compresslevel: int = 9,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n) -> BZ2File: ...\n@overload\ndef open(\n    filename: _WritableFileobj,\n    mode: _WriteTextMode,\n    compresslevel: int = 9,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> TextIOWrapper: ...\n@overload\ndef open(\n    filename: StrOrBytesPath,\n    mode: _ReadBinaryMode | _WriteBinaryMode = \"rb\",\n    compresslevel: int = 9,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n) -> BZ2File: ...\n@overload\ndef open(\n    filename: StrOrBytesPath,\n    mode: _ReadTextMode | _WriteTextMode,\n    compresslevel: int = 9,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> TextIOWrapper: ...\n@overload\ndef open(\n    filename: StrOrBytesPath | _ReadableFileobj | _WritableFileobj,\n    mode: str,\n    compresslevel: int = 9,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> BZ2File | TextIOWrapper: ...\n\nclass BZ2File(BaseStream, IO[bytes]):\n    def __enter__(self) -> Self: ...\n    @overload\n    def __init__(self, filename: _WritableFileobj, mode: _WriteBinaryMode, *, compresslevel: int = 9) -> None: ...\n    @overload\n    def __init__(self, filename: _ReadableFileobj, mode: _ReadBinaryMode = \"r\", *, compresslevel: int = 9) -> None: ...\n    @overload\n    def __init__(\n        self, filename: StrOrBytesPath, mode: _ReadBinaryMode | _WriteBinaryMode = \"r\", *, compresslevel: int = 9\n    ) -> None: ...\n    def read(self, size: int | None = -1) -> bytes: ...\n    def read1(self, size: int = -1) -> bytes: ...\n    def readline(self, size: SupportsIndex = -1) -> bytes: ...  # type: ignore[override]\n    def readinto(self, b: WriteableBuffer) -> int: ...\n    def readlines(self, size: SupportsIndex = -1) -> list[bytes]: ...\n    def peek(self, n: int = 0) -> bytes: ...\n    def seek(self, offset: int, whence: int = 0) -> int: ...\n    def write(self, data: ReadableBuffer) -> int: ...\n    def writelines(self, seq: Iterable[ReadableBuffer]) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/cProfile.pyi",
    "content": "import _lsprof\nfrom _typeshed import StrOrBytesPath, Unused\nfrom collections.abc import Callable, Mapping\nfrom types import CodeType\nfrom typing import Any, TypeVar\nfrom typing_extensions import ParamSpec, Self, TypeAlias\n\n__all__ = [\"run\", \"runctx\", \"Profile\"]\n\ndef run(statement: str, filename: str | None = None, sort: str | int = -1) -> None: ...\ndef runctx(\n    statement: str, globals: dict[str, Any], locals: Mapping[str, Any], filename: str | None = None, sort: str | int = -1\n) -> None: ...\n\n_T = TypeVar(\"_T\")\n_P = ParamSpec(\"_P\")\n_Label: TypeAlias = tuple[str, int, str]\n\nclass Profile(_lsprof.Profiler):\n    stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]]  # undocumented\n    def print_stats(self, sort: str | int = -1) -> None: ...\n    def dump_stats(self, file: StrOrBytesPath) -> None: ...\n    def create_stats(self) -> None: ...\n    def snapshot_stats(self) -> None: ...\n    def run(self, cmd: str) -> Self: ...\n    def runctx(self, cmd: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> Self: ...\n    def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *exc_info: Unused) -> None: ...\n\ndef label(code: str | CodeType) -> _Label: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/calendar.pyi",
    "content": "import datetime\nimport enum\nimport sys\nfrom _typeshed import Unused\nfrom collections.abc import Iterable, Sequence\nfrom time import struct_time\nfrom typing import ClassVar, Final\nfrom typing_extensions import TypeAlias\n\n__all__ = [\n    \"IllegalMonthError\",\n    \"IllegalWeekdayError\",\n    \"setfirstweekday\",\n    \"firstweekday\",\n    \"isleap\",\n    \"leapdays\",\n    \"weekday\",\n    \"monthrange\",\n    \"monthcalendar\",\n    \"prmonth\",\n    \"month\",\n    \"prcal\",\n    \"calendar\",\n    \"timegm\",\n    \"month_name\",\n    \"month_abbr\",\n    \"day_name\",\n    \"day_abbr\",\n    \"Calendar\",\n    \"TextCalendar\",\n    \"HTMLCalendar\",\n    \"LocaleTextCalendar\",\n    \"LocaleHTMLCalendar\",\n    \"weekheader\",\n]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"FRIDAY\", \"MONDAY\", \"SATURDAY\", \"SUNDAY\", \"THURSDAY\", \"TUESDAY\", \"WEDNESDAY\"]\nif sys.version_info >= (3, 12):\n    __all__ += [\n        \"Day\",\n        \"Month\",\n        \"JANUARY\",\n        \"FEBRUARY\",\n        \"MARCH\",\n        \"APRIL\",\n        \"MAY\",\n        \"JUNE\",\n        \"JULY\",\n        \"AUGUST\",\n        \"SEPTEMBER\",\n        \"OCTOBER\",\n        \"NOVEMBER\",\n        \"DECEMBER\",\n    ]\n\n_LocaleType: TypeAlias = tuple[str | None, str | None]\n\nclass IllegalMonthError(ValueError, IndexError):\n    month: int\n    def __init__(self, month: int) -> None: ...\n\nclass IllegalWeekdayError(ValueError):\n    weekday: int\n    def __init__(self, weekday: int) -> None: ...\n\ndef isleap(year: int) -> bool: ...\ndef leapdays(y1: int, y2: int) -> int: ...\ndef weekday(year: int, month: int, day: int) -> int: ...\ndef monthrange(year: int, month: int) -> tuple[int, int]: ...\n\nclass Calendar:\n    firstweekday: int\n    def __init__(self, firstweekday: int = 0) -> None: ...\n    def getfirstweekday(self) -> int: ...\n    def setfirstweekday(self, firstweekday: int) -> None: ...\n    def iterweekdays(self) -> Iterable[int]: ...\n    def itermonthdates(self, year: int, month: int) -> Iterable[datetime.date]: ...\n    def itermonthdays2(self, year: int, month: int) -> Iterable[tuple[int, int]]: ...\n    def itermonthdays(self, year: int, month: int) -> Iterable[int]: ...\n    def monthdatescalendar(self, year: int, month: int) -> list[list[datetime.date]]: ...\n    def monthdays2calendar(self, year: int, month: int) -> list[list[tuple[int, int]]]: ...\n    def monthdayscalendar(self, year: int, month: int) -> list[list[int]]: ...\n    def yeardatescalendar(self, year: int, width: int = 3) -> list[list[list[list[datetime.date]]]]: ...\n    def yeardays2calendar(self, year: int, width: int = 3) -> list[list[list[list[tuple[int, int]]]]]: ...\n    def yeardayscalendar(self, year: int, width: int = 3) -> list[list[list[list[int]]]]: ...\n    def itermonthdays3(self, year: int, month: int) -> Iterable[tuple[int, int, int]]: ...\n    def itermonthdays4(self, year: int, month: int) -> Iterable[tuple[int, int, int, int]]: ...\n\nclass TextCalendar(Calendar):\n    def prweek(self, theweek: int, width: int) -> None: ...\n    def formatday(self, day: int, weekday: int, width: int) -> str: ...\n    def formatweek(self, theweek: int, width: int) -> str: ...\n    def formatweekday(self, day: int, width: int) -> str: ...\n    def formatweekheader(self, width: int) -> str: ...\n    def formatmonthname(self, theyear: int, themonth: int, width: int, withyear: bool = True) -> str: ...\n    def prmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> None: ...\n    def formatmonth(self, theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: ...\n    def formatyear(self, theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ...\n    def pryear(self, theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None: ...\n\ndef firstweekday() -> int: ...\ndef monthcalendar(year: int, month: int) -> list[list[int]]: ...\ndef prweek(theweek: int, width: int) -> None: ...\ndef week(theweek: int, width: int) -> str: ...\ndef weekheader(width: int) -> str: ...\ndef prmonth(theyear: int, themonth: int, w: int = 0, l: int = 0) -> None: ...\ndef month(theyear: int, themonth: int, w: int = 0, l: int = 0) -> str: ...\ndef calendar(theyear: int, w: int = 2, l: int = 1, c: int = 6, m: int = 3) -> str: ...\ndef prcal(theyear: int, w: int = 0, l: int = 0, c: int = 6, m: int = 3) -> None: ...\n\nclass HTMLCalendar(Calendar):\n    cssclasses: ClassVar[list[str]]\n    cssclass_noday: ClassVar[str]\n    cssclasses_weekday_head: ClassVar[list[str]]\n    cssclass_month_head: ClassVar[str]\n    cssclass_month: ClassVar[str]\n    cssclass_year: ClassVar[str]\n    cssclass_year_head: ClassVar[str]\n    def formatday(self, day: int, weekday: int) -> str: ...\n    def formatweek(self, theweek: int) -> str: ...\n    def formatweekday(self, day: int) -> str: ...\n    def formatweekheader(self) -> str: ...\n    def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ...\n    def formatmonth(self, theyear: int, themonth: int, withyear: bool = True) -> str: ...\n    def formatyear(self, theyear: int, width: int = 3) -> str: ...\n    def formatyearpage(\n        self, theyear: int, width: int = 3, css: str | None = \"calendar.css\", encoding: str | None = None\n    ) -> bytes: ...\n\nclass different_locale:\n    def __init__(self, locale: _LocaleType) -> None: ...\n    def __enter__(self) -> None: ...\n    def __exit__(self, *args: Unused) -> None: ...\n\nclass LocaleTextCalendar(TextCalendar):\n    def __init__(self, firstweekday: int = 0, locale: _LocaleType | None = None) -> None: ...\n\nclass LocaleHTMLCalendar(HTMLCalendar):\n    def __init__(self, firstweekday: int = 0, locale: _LocaleType | None = None) -> None: ...\n    def formatweekday(self, day: int) -> str: ...\n    def formatmonthname(self, theyear: int, themonth: int, withyear: bool = True) -> str: ...\n\nc: TextCalendar\n\ndef setfirstweekday(firstweekday: int) -> None: ...\ndef format(cols: int, colwidth: int = 20, spacing: int = 6) -> str: ...\ndef formatstring(cols: int, colwidth: int = 20, spacing: int = 6) -> str: ...\ndef timegm(tuple: tuple[int, ...] | struct_time) -> int: ...\n\n# Data attributes\nday_name: Sequence[str]\nday_abbr: Sequence[str]\nmonth_name: Sequence[str]\nmonth_abbr: Sequence[str]\n\nif sys.version_info >= (3, 12):\n    class Month(enum.IntEnum):\n        JANUARY = 1\n        FEBRUARY = 2\n        MARCH = 3\n        APRIL = 4\n        MAY = 5\n        JUNE = 6\n        JULY = 7\n        AUGUST = 8\n        SEPTEMBER = 9\n        OCTOBER = 10\n        NOVEMBER = 11\n        DECEMBER = 12\n\n    JANUARY: Final = Month.JANUARY\n    FEBRUARY: Final = Month.FEBRUARY\n    MARCH: Final = Month.MARCH\n    APRIL: Final = Month.APRIL\n    MAY: Final = Month.MAY\n    JUNE: Final = Month.JUNE\n    JULY: Final = Month.JULY\n    AUGUST: Final = Month.AUGUST\n    SEPTEMBER: Final = Month.SEPTEMBER\n    OCTOBER: Final = Month.OCTOBER\n    NOVEMBER: Final = Month.NOVEMBER\n    DECEMBER: Final = Month.DECEMBER\n\n    class Day(enum.IntEnum):\n        MONDAY = 0\n        TUESDAY = 1\n        WEDNESDAY = 2\n        THURSDAY = 3\n        FRIDAY = 4\n        SATURDAY = 5\n        SUNDAY = 6\n\n    MONDAY: Final = Day.MONDAY\n    TUESDAY: Final = Day.TUESDAY\n    WEDNESDAY: Final = Day.WEDNESDAY\n    THURSDAY: Final = Day.THURSDAY\n    FRIDAY: Final = Day.FRIDAY\n    SATURDAY: Final = Day.SATURDAY\n    SUNDAY: Final = Day.SUNDAY\nelse:\n    MONDAY: Final = 0\n    TUESDAY: Final = 1\n    WEDNESDAY: Final = 2\n    THURSDAY: Final = 3\n    FRIDAY: Final = 4\n    SATURDAY: Final = 5\n    SUNDAY: Final = 6\n\nEPOCH: Final = 1970\n"
  },
  {
    "path": "mypy/typeshed/stdlib/cgi.pyi",
    "content": "import os\nfrom _typeshed import SupportsContainsAndGetItem, SupportsGetItem, SupportsItemAccess, Unused\nfrom builtins import list as _list, type as _type\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom email.message import Message\nfrom types import TracebackType\nfrom typing import IO, Any, Protocol, type_check_only\nfrom typing_extensions import Self\n\n__all__ = [\n    \"MiniFieldStorage\",\n    \"FieldStorage\",\n    \"parse\",\n    \"parse_multipart\",\n    \"parse_header\",\n    \"test\",\n    \"print_exception\",\n    \"print_environ\",\n    \"print_form\",\n    \"print_directory\",\n    \"print_arguments\",\n    \"print_environ_usage\",\n]\n\ndef parse(\n    fp: IO[Any] | None = None,\n    environ: SupportsItemAccess[str, str] = os.environ,\n    keep_blank_values: bool = ...,\n    strict_parsing: bool = ...,\n    separator: str = \"&\",\n) -> dict[str, list[str]]: ...\ndef parse_multipart(\n    fp: IO[Any], pdict: SupportsGetItem[str, bytes], encoding: str = \"utf-8\", errors: str = \"replace\", separator: str = \"&\"\n) -> dict[str, list[Any]]: ...\n@type_check_only\nclass _Environ(Protocol):\n    def __getitem__(self, k: str, /) -> str: ...\n    def keys(self) -> Iterable[str]: ...\n\ndef parse_header(line: str) -> tuple[str, dict[str, str]]: ...\ndef test(environ: _Environ = os.environ) -> None: ...\ndef print_environ(environ: _Environ = os.environ) -> None: ...\ndef print_form(form: dict[str, Any]) -> None: ...\ndef print_directory() -> None: ...\ndef print_environ_usage() -> None: ...\n\nclass MiniFieldStorage:\n    # The first five \"Any\" attributes here are always None, but mypy doesn't support that\n    filename: Any\n    list: Any\n    type: Any\n    file: IO[bytes] | None\n    type_options: dict[Any, Any]\n    disposition: Any\n    disposition_options: dict[Any, Any]\n    headers: dict[Any, Any]\n    name: Any\n    value: Any\n    def __init__(self, name: Any, value: Any) -> None: ...\n\nclass FieldStorage:\n    FieldStorageClass: _type | None\n    keep_blank_values: int\n    strict_parsing: int\n    qs_on_post: str | None\n    headers: Mapping[str, str] | Message\n    fp: IO[bytes]\n    encoding: str\n    errors: str\n    outerboundary: bytes\n    bytes_read: int\n    limit: int | None\n    disposition: str\n    disposition_options: dict[str, str]\n    filename: str | None\n    file: IO[bytes] | None\n    type: str\n    type_options: dict[str, str]\n    innerboundary: bytes\n    length: int\n    done: int\n    list: _list[Any] | None\n    value: None | bytes | _list[Any]\n    def __init__(\n        self,\n        fp: IO[Any] | None = None,\n        headers: Mapping[str, str] | Message | None = None,\n        outerboundary: bytes = b\"\",\n        environ: SupportsContainsAndGetItem[str, str] = os.environ,\n        keep_blank_values: int = 0,\n        strict_parsing: int = 0,\n        limit: int | None = None,\n        encoding: str = \"utf-8\",\n        errors: str = \"replace\",\n        max_num_fields: int | None = None,\n        separator: str = \"&\",\n    ) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n    def __iter__(self) -> Iterator[str]: ...\n    def __getitem__(self, key: str) -> Any: ...\n    def getvalue(self, key: str, default: Any = None) -> Any: ...\n    def getfirst(self, key: str, default: Any = None) -> Any: ...\n    def getlist(self, key: str) -> _list[Any]: ...\n    def keys(self) -> _list[str]: ...\n    def __contains__(self, key: str) -> bool: ...\n    def __len__(self) -> int: ...\n    def __bool__(self) -> bool: ...\n    def __del__(self) -> None: ...\n    # Returns bytes or str IO depending on an internal flag\n    def make_file(self) -> IO[Any]: ...\n\ndef print_exception(\n    type: type[BaseException] | None = None,\n    value: BaseException | None = None,\n    tb: TracebackType | None = None,\n    limit: int | None = None,\n) -> None: ...\ndef print_arguments() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/cgitb.pyi",
    "content": "from _typeshed import OptExcInfo, StrOrBytesPath\nfrom collections.abc import Callable\nfrom types import FrameType, TracebackType\nfrom typing import IO, Any, Final\n\n__UNDEF__: Final[object]  # undocumented sentinel\n\ndef reset() -> str: ...  # undocumented\ndef small(text: str) -> str: ...  # undocumented\ndef strong(text: str) -> str: ...  # undocumented\ndef grey(text: str) -> str: ...  # undocumented\ndef lookup(name: str, frame: FrameType, locals: dict[str, Any]) -> tuple[str | None, Any]: ...  # undocumented\ndef scanvars(\n    reader: Callable[[], bytes], frame: FrameType, locals: dict[str, Any]\n) -> list[tuple[str, str | None, Any]]: ...  # undocumented\ndef html(einfo: OptExcInfo, context: int = 5) -> str: ...\ndef text(einfo: OptExcInfo, context: int = 5) -> str: ...\n\nclass Hook:  # undocumented\n    def __init__(\n        self,\n        display: int = 1,\n        logdir: StrOrBytesPath | None = None,\n        context: int = 5,\n        file: IO[str] | None = None,\n        format: str = \"html\",\n    ) -> None: ...\n    def __call__(self, etype: type[BaseException] | None, evalue: BaseException | None, etb: TracebackType | None) -> None: ...\n    def handle(self, info: OptExcInfo | None = None) -> None: ...\n\ndef handler(info: OptExcInfo | None = None) -> None: ...\ndef enable(display: int = 1, logdir: StrOrBytesPath | None = None, context: int = 5, format: str = \"html\") -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/chunk.pyi",
    "content": "from typing import IO\n\nclass Chunk:\n    closed: bool\n    align: bool\n    file: IO[bytes]\n    chunkname: bytes\n    chunksize: int\n    size_read: int\n    offset: int\n    seekable: bool\n    def __init__(self, file: IO[bytes], align: bool = True, bigendian: bool = True, inclheader: bool = False) -> None: ...\n    def getname(self) -> bytes: ...\n    def getsize(self) -> int: ...\n    def close(self) -> None: ...\n    def isatty(self) -> bool: ...\n    def seek(self, pos: int, whence: int = 0) -> None: ...\n    def tell(self) -> int: ...\n    def read(self, size: int = -1) -> bytes: ...\n    def skip(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/cmath.pyi",
    "content": "from typing import Final, SupportsComplex, SupportsFloat, SupportsIndex\nfrom typing_extensions import TypeAlias\n\ne: Final[float]\npi: Final[float]\ninf: Final[float]\ninfj: Final[complex]\nnan: Final[float]\nnanj: Final[complex]\ntau: Final[float]\n\n_F: TypeAlias = SupportsFloat | SupportsIndex\n_C: TypeAlias = SupportsFloat | SupportsComplex | SupportsIndex | complex\n\ndef acos(z: _C, /) -> complex: ...\ndef acosh(z: _C, /) -> complex: ...\ndef asin(z: _C, /) -> complex: ...\ndef asinh(z: _C, /) -> complex: ...\ndef atan(z: _C, /) -> complex: ...\ndef atanh(z: _C, /) -> complex: ...\ndef cos(z: _C, /) -> complex: ...\ndef cosh(z: _C, /) -> complex: ...\ndef exp(z: _C, /) -> complex: ...\ndef isclose(a: _C, b: _C, *, rel_tol: SupportsFloat = 1e-09, abs_tol: SupportsFloat = 0.0) -> bool: ...\ndef isinf(z: _C, /) -> bool: ...\ndef isnan(z: _C, /) -> bool: ...\ndef log(z: _C, base: _C = ..., /) -> complex: ...\ndef log10(z: _C, /) -> complex: ...\ndef phase(z: _C, /) -> float: ...\ndef polar(z: _C, /) -> tuple[float, float]: ...\ndef rect(r: _F, phi: _F, /) -> complex: ...\ndef sin(z: _C, /) -> complex: ...\ndef sinh(z: _C, /) -> complex: ...\ndef sqrt(z: _C, /) -> complex: ...\ndef tan(z: _C, /) -> complex: ...\ndef tanh(z: _C, /) -> complex: ...\ndef isfinite(z: _C, /) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/cmd.pyi",
    "content": "from collections.abc import Callable\nfrom typing import IO, Any, Final\nfrom typing_extensions import LiteralString\n\n__all__ = [\"Cmd\"]\n\nPROMPT: Final = \"(Cmd) \"\nIDENTCHARS: Final[LiteralString]  # Too big to be `Literal`\n\nclass Cmd:\n    prompt: str\n    identchars: str\n    ruler: str\n    lastcmd: str\n    intro: Any | None\n    doc_leader: str\n    doc_header: str\n    misc_header: str\n    undoc_header: str\n    nohelp: str\n    use_rawinput: bool\n    stdin: IO[str]\n    stdout: IO[str]\n    cmdqueue: list[str]\n    completekey: str\n    def __init__(self, completekey: str = \"tab\", stdin: IO[str] | None = None, stdout: IO[str] | None = None) -> None: ...\n    old_completer: Callable[[str, int], str | None] | None\n    def cmdloop(self, intro: Any | None = None) -> None: ...\n    def precmd(self, line: str) -> str: ...\n    def postcmd(self, stop: bool, line: str) -> bool: ...\n    def preloop(self) -> None: ...\n    def postloop(self) -> None: ...\n    def parseline(self, line: str) -> tuple[str | None, str | None, str]: ...\n    def onecmd(self, line: str) -> bool: ...\n    def emptyline(self) -> bool: ...\n    def default(self, line: str) -> None: ...\n    def completedefault(self, *ignored: Any) -> list[str]: ...\n    def completenames(self, text: str, *ignored: Any) -> list[str]: ...\n    completion_matches: list[str] | None\n    def complete(self, text: str, state: int) -> list[str] | None: ...\n    def get_names(self) -> list[str]: ...\n    # Only the first element of args matters.\n    def complete_help(self, *args: Any) -> list[str]: ...\n    def do_help(self, arg: str) -> bool | None: ...\n    def print_topics(self, header: str, cmds: list[str] | None, cmdlen: Any, maxcol: int) -> None: ...\n    def columnize(self, list: list[str] | None, displaywidth: int = 80) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/code.pyi",
    "content": "import sys\nfrom codeop import CommandCompiler, compile_command as compile_command\nfrom collections.abc import Callable\nfrom types import CodeType\nfrom typing import Any\n\n__all__ = [\"InteractiveInterpreter\", \"InteractiveConsole\", \"interact\", \"compile_command\"]\n\nclass InteractiveInterpreter:\n    locals: dict[str, Any]  # undocumented\n    compile: CommandCompiler  # undocumented\n    def __init__(self, locals: dict[str, Any] | None = None) -> None: ...\n    def runsource(self, source: str, filename: str = \"<input>\", symbol: str = \"single\") -> bool: ...\n    def runcode(self, code: CodeType) -> None: ...\n    if sys.version_info >= (3, 13):\n        def showsyntaxerror(self, filename: str | None = None, *, source: str = \"\") -> None: ...\n    else:\n        def showsyntaxerror(self, filename: str | None = None) -> None: ...\n\n    def showtraceback(self) -> None: ...\n    def write(self, data: str) -> None: ...\n\nclass InteractiveConsole(InteractiveInterpreter):\n    buffer: list[str]  # undocumented\n    filename: str  # undocumented\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self, locals: dict[str, Any] | None = None, filename: str = \"<console>\", *, local_exit: bool = False\n        ) -> None: ...\n        def push(self, line: str, filename: str | None = None) -> bool: ...\n    else:\n        def __init__(self, locals: dict[str, Any] | None = None, filename: str = \"<console>\") -> None: ...\n        def push(self, line: str) -> bool: ...\n\n    def interact(self, banner: str | None = None, exitmsg: str | None = None) -> None: ...\n    def resetbuffer(self) -> None: ...\n    def raw_input(self, prompt: str = \"\") -> str: ...\n\nif sys.version_info >= (3, 13):\n    def interact(\n        banner: str | None = None,\n        readfunc: Callable[[str], str] | None = None,\n        local: dict[str, Any] | None = None,\n        exitmsg: str | None = None,\n        local_exit: bool = False,\n    ) -> None: ...\n\nelse:\n    def interact(\n        banner: str | None = None,\n        readfunc: Callable[[str], str] | None = None,\n        local: dict[str, Any] | None = None,\n        exitmsg: str | None = None,\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/codecs.pyi",
    "content": "import sys\nimport types\nfrom _codecs import *\nfrom _typeshed import ReadableBuffer\nfrom abc import abstractmethod\nfrom collections.abc import Callable, Generator, Iterable\nfrom typing import Any, BinaryIO, ClassVar, Final, Literal, Protocol, TextIO, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, deprecated, disjoint_base\n\n__all__ = [\n    \"register\",\n    \"lookup\",\n    \"open\",\n    \"EncodedFile\",\n    \"BOM\",\n    \"BOM_BE\",\n    \"BOM_LE\",\n    \"BOM32_BE\",\n    \"BOM32_LE\",\n    \"BOM64_BE\",\n    \"BOM64_LE\",\n    \"BOM_UTF8\",\n    \"BOM_UTF16\",\n    \"BOM_UTF16_LE\",\n    \"BOM_UTF16_BE\",\n    \"BOM_UTF32\",\n    \"BOM_UTF32_LE\",\n    \"BOM_UTF32_BE\",\n    \"CodecInfo\",\n    \"Codec\",\n    \"IncrementalEncoder\",\n    \"IncrementalDecoder\",\n    \"StreamReader\",\n    \"StreamWriter\",\n    \"StreamReaderWriter\",\n    \"StreamRecoder\",\n    \"getencoder\",\n    \"getdecoder\",\n    \"getincrementalencoder\",\n    \"getincrementaldecoder\",\n    \"getreader\",\n    \"getwriter\",\n    \"encode\",\n    \"decode\",\n    \"iterencode\",\n    \"iterdecode\",\n    \"strict_errors\",\n    \"ignore_errors\",\n    \"replace_errors\",\n    \"xmlcharrefreplace_errors\",\n    \"backslashreplace_errors\",\n    \"namereplace_errors\",\n    \"register_error\",\n    \"lookup_error\",\n]\n\nBOM32_BE: Final = b\"\\xfe\\xff\"\nBOM32_LE: Final = b\"\\xff\\xfe\"\nBOM64_BE: Final = b\"\\x00\\x00\\xfe\\xff\"\nBOM64_LE: Final = b\"\\xff\\xfe\\x00\\x00\"\n\n_BufferedEncoding: TypeAlias = Literal[\n    \"idna\",\n    \"raw-unicode-escape\",\n    \"unicode-escape\",\n    \"utf-16\",\n    \"utf-16-be\",\n    \"utf-16-le\",\n    \"utf-32\",\n    \"utf-32-be\",\n    \"utf-32-le\",\n    \"utf-7\",\n    \"utf-8\",\n    \"utf-8-sig\",\n]\n\n@type_check_only\nclass _WritableStream(Protocol):\n    def write(self, data: bytes, /) -> object: ...\n    def seek(self, offset: int, whence: int, /) -> object: ...\n    def close(self) -> object: ...\n\n@type_check_only\nclass _ReadableStream(Protocol):\n    def read(self, size: int = ..., /) -> bytes: ...\n    def seek(self, offset: int, whence: int, /) -> object: ...\n    def close(self) -> object: ...\n\n@type_check_only\nclass _Stream(_WritableStream, _ReadableStream, Protocol): ...\n\n# TODO: this only satisfies the most common interface, where\n# bytes is the raw form and str is the cooked form.\n# In the long run, both should become template parameters maybe?\n# There *are* bytes->bytes and str->str encodings in the standard library.\n# They were much more common in Python 2 than in Python 3.\n\n@type_check_only\nclass _Encoder(Protocol):\n    def __call__(self, input: str, errors: str = ..., /) -> tuple[bytes, int]: ...  # signature of Codec().encode\n\n@type_check_only\nclass _Decoder(Protocol):\n    def __call__(self, input: ReadableBuffer, errors: str = ..., /) -> tuple[str, int]: ...  # signature of Codec().decode\n\n@type_check_only\nclass _StreamReader(Protocol):\n    def __call__(self, stream: _ReadableStream, errors: str = ..., /) -> StreamReader: ...\n\n@type_check_only\nclass _StreamWriter(Protocol):\n    def __call__(self, stream: _WritableStream, errors: str = ..., /) -> StreamWriter: ...\n\n@type_check_only\nclass _IncrementalEncoder(Protocol):\n    def __call__(self, errors: str = ...) -> IncrementalEncoder: ...\n\n@type_check_only\nclass _IncrementalDecoder(Protocol):\n    def __call__(self, errors: str = ...) -> IncrementalDecoder: ...\n\n@type_check_only\nclass _BufferedIncrementalDecoder(Protocol):\n    def __call__(self, errors: str = ...) -> BufferedIncrementalDecoder: ...\n\nif sys.version_info >= (3, 12):\n    class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]):\n        _is_text_encoding: bool\n        @property\n        def encode(self) -> _Encoder: ...\n        @property\n        def decode(self) -> _Decoder: ...\n        @property\n        def streamreader(self) -> _StreamReader: ...\n        @property\n        def streamwriter(self) -> _StreamWriter: ...\n        @property\n        def incrementalencoder(self) -> _IncrementalEncoder: ...\n        @property\n        def incrementaldecoder(self) -> _IncrementalDecoder: ...\n        name: str\n        def __new__(\n            cls,\n            encode: _Encoder,\n            decode: _Decoder,\n            streamreader: _StreamReader | None = None,\n            streamwriter: _StreamWriter | None = None,\n            incrementalencoder: _IncrementalEncoder | None = None,\n            incrementaldecoder: _IncrementalDecoder | None = None,\n            name: str | None = None,\n            *,\n            _is_text_encoding: bool | None = None,\n        ) -> Self: ...\n\nelse:\n    @disjoint_base\n    class CodecInfo(tuple[_Encoder, _Decoder, _StreamReader, _StreamWriter]):\n        _is_text_encoding: bool\n        @property\n        def encode(self) -> _Encoder: ...\n        @property\n        def decode(self) -> _Decoder: ...\n        @property\n        def streamreader(self) -> _StreamReader: ...\n        @property\n        def streamwriter(self) -> _StreamWriter: ...\n        @property\n        def incrementalencoder(self) -> _IncrementalEncoder: ...\n        @property\n        def incrementaldecoder(self) -> _IncrementalDecoder: ...\n        name: str\n        def __new__(\n            cls,\n            encode: _Encoder,\n            decode: _Decoder,\n            streamreader: _StreamReader | None = None,\n            streamwriter: _StreamWriter | None = None,\n            incrementalencoder: _IncrementalEncoder | None = None,\n            incrementaldecoder: _IncrementalDecoder | None = None,\n            name: str | None = None,\n            *,\n            _is_text_encoding: bool | None = None,\n        ) -> Self: ...\n\ndef getencoder(encoding: str) -> _Encoder: ...\ndef getdecoder(encoding: str) -> _Decoder: ...\ndef getincrementalencoder(encoding: str) -> _IncrementalEncoder: ...\n@overload\ndef getincrementaldecoder(encoding: _BufferedEncoding) -> _BufferedIncrementalDecoder: ...\n@overload\ndef getincrementaldecoder(encoding: str) -> _IncrementalDecoder: ...\ndef getreader(encoding: str) -> _StreamReader: ...\ndef getwriter(encoding: str) -> _StreamWriter: ...\n@deprecated(\"Deprecated since Python 3.14. Use `open()` instead.\")\ndef open(\n    filename: str, mode: str = \"r\", encoding: str | None = None, errors: str = \"strict\", buffering: int = -1\n) -> StreamReaderWriter: ...\ndef EncodedFile(file: _Stream, data_encoding: str, file_encoding: str | None = None, errors: str = \"strict\") -> StreamRecoder: ...\ndef iterencode(iterator: Iterable[str], encoding: str, errors: str = \"strict\") -> Generator[bytes, None, None]: ...\ndef iterdecode(iterator: Iterable[bytes], encoding: str, errors: str = \"strict\") -> Generator[str, None, None]: ...\n\nBOM: Final[Literal[b\"\\xff\\xfe\", b\"\\xfe\\xff\"]]  # depends on `sys.byteorder`\nBOM_BE: Final = b\"\\xfe\\xff\"\nBOM_LE: Final = b\"\\xff\\xfe\"\nBOM_UTF8: Final = b\"\\xef\\xbb\\xbf\"\nBOM_UTF16: Final[Literal[b\"\\xff\\xfe\", b\"\\xfe\\xff\"]]  # depends on `sys.byteorder`\nBOM_UTF16_BE: Final = b\"\\xfe\\xff\"\nBOM_UTF16_LE: Final = b\"\\xff\\xfe\"\nBOM_UTF32: Final[Literal[b\"\\xff\\xfe\\x00\\x00\", b\"\\x00\\x00\\xfe\\xff\"]]  # depends on `sys.byteorder`\nBOM_UTF32_BE: Final = b\"\\x00\\x00\\xfe\\xff\"\nBOM_UTF32_LE: Final = b\"\\xff\\xfe\\x00\\x00\"\n\ndef strict_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ...\ndef replace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ...\ndef ignore_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ...\ndef xmlcharrefreplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ...\ndef backslashreplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ...\ndef namereplace_errors(exception: UnicodeError, /) -> tuple[str | bytes, int]: ...\n\nclass Codec:\n    # These are sort of @abstractmethod but sort of not.\n    # The StreamReader and StreamWriter subclasses only implement one.\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder:\n    errors: str\n    def __init__(self, errors: str = \"strict\") -> None: ...\n    @abstractmethod\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n    def reset(self) -> None: ...\n    # documentation says int but str is needed for the subclass.\n    def getstate(self) -> int | str: ...\n    def setstate(self, state: int | str) -> None: ...\n\nclass IncrementalDecoder:\n    errors: str\n    def __init__(self, errors: str = \"strict\") -> None: ...\n    @abstractmethod\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n    def reset(self) -> None: ...\n    def getstate(self) -> tuple[bytes, int]: ...\n    def setstate(self, state: tuple[bytes, int]) -> None: ...\n\n# These are not documented but used in encodings/*.py implementations.\nclass BufferedIncrementalEncoder(IncrementalEncoder):\n    buffer: str\n    def __init__(self, errors: str = \"strict\") -> None: ...\n    @abstractmethod\n    def _buffer_encode(self, input: str, errors: str, final: bool) -> tuple[bytes, int]: ...\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass BufferedIncrementalDecoder(IncrementalDecoder):\n    buffer: bytes\n    def __init__(self, errors: str = \"strict\") -> None: ...\n    @abstractmethod\n    def _buffer_decode(self, input: ReadableBuffer, errors: str, final: bool) -> tuple[str, int]: ...\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\n# TODO: it is not possible to specify the requirement that all other\n# attributes and methods are passed-through from the stream.\nclass StreamWriter(Codec):\n    stream: _WritableStream\n    errors: str\n    def __init__(self, stream: _WritableStream, errors: str = \"strict\") -> None: ...\n    def write(self, object: str) -> None: ...\n    def writelines(self, list: Iterable[str]) -> None: ...\n    def reset(self) -> None: ...\n    def seek(self, offset: int, whence: int = 0) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ...\n    def __getattr__(self, name: str, getattr: Callable[[Any, str], Any] = ...) -> Any: ...\n\nclass StreamReader(Codec):\n    stream: _ReadableStream\n    errors: str\n    # This is set to str, but some subclasses set to bytes instead.\n    charbuffertype: ClassVar[type] = ...\n    def __init__(self, stream: _ReadableStream, errors: str = \"strict\") -> None: ...\n    def read(self, size: int = -1, chars: int = -1, firstline: bool = False) -> str: ...\n    def readline(self, size: int | None = None, keepends: bool = True) -> str: ...\n    def readlines(self, sizehint: int | None = None, keepends: bool = True) -> list[str]: ...\n    def reset(self) -> None: ...\n    def seek(self, offset: int, whence: int = 0) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> str: ...\n    def __getattr__(self, name: str, getattr: Callable[[Any, str], Any] = ...) -> Any: ...\n\n# Doesn't actually inherit from TextIO, but wraps a BinaryIO to provide text reading and writing\n# and delegates attributes to the underlying binary stream with __getattr__.\nclass StreamReaderWriter(TextIO):\n    stream: _Stream\n    def __init__(self, stream: _Stream, Reader: _StreamReader, Writer: _StreamWriter, errors: str = \"strict\") -> None: ...\n    def read(self, size: int = -1) -> str: ...\n    def readline(self, size: int | None = None) -> str: ...\n    def readlines(self, sizehint: int | None = None) -> list[str]: ...\n    def __next__(self) -> str: ...\n    def __iter__(self) -> Self: ...\n    def write(self, data: str) -> None: ...  # type: ignore[override]\n    def writelines(self, list: Iterable[str]) -> None: ...\n    def reset(self) -> None: ...\n    def seek(self, offset: int, whence: int = 0) -> None: ...  # type: ignore[override]\n    def __enter__(self) -> Self: ...\n    def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ...\n    def __getattr__(self, name: str) -> Any: ...\n    # These methods don't actually exist directly, but they are needed to satisfy the TextIO\n    # interface. At runtime, they are delegated through __getattr__.\n    def close(self) -> None: ...\n    def fileno(self) -> int: ...\n    def flush(self) -> None: ...\n    def isatty(self) -> bool: ...\n    def readable(self) -> bool: ...\n    def truncate(self, size: int | None = ...) -> int: ...\n    def seekable(self) -> bool: ...\n    def tell(self) -> int: ...\n    def writable(self) -> bool: ...\n\nclass StreamRecoder(BinaryIO):\n    data_encoding: str\n    file_encoding: str\n    def __init__(\n        self,\n        stream: _Stream,\n        encode: _Encoder,\n        decode: _Decoder,\n        Reader: _StreamReader,\n        Writer: _StreamWriter,\n        errors: str = \"strict\",\n    ) -> None: ...\n    def read(self, size: int = -1) -> bytes: ...\n    def readline(self, size: int | None = None) -> bytes: ...\n    def readlines(self, sizehint: int | None = None) -> list[bytes]: ...\n    def __next__(self) -> bytes: ...\n    def __iter__(self) -> Self: ...\n    # Base class accepts more types than just bytes\n    def write(self, data: bytes) -> None: ...  # type: ignore[override]\n    def writelines(self, list: Iterable[bytes]) -> None: ...  # type: ignore[override]\n    def reset(self) -> None: ...\n    def __getattr__(self, name: str) -> Any: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, type: type[BaseException] | None, value: BaseException | None, tb: types.TracebackType | None) -> None: ...\n    def seek(self, offset: int, whence: int = 0) -> None: ...  # type: ignore[override]\n    # These methods don't actually exist directly, but they are needed to satisfy the BinaryIO\n    # interface. At runtime, they are delegated through __getattr__.\n    def close(self) -> None: ...\n    def fileno(self) -> int: ...\n    def flush(self) -> None: ...\n    def isatty(self) -> bool: ...\n    def readable(self) -> bool: ...\n    def truncate(self, size: int | None = ...) -> int: ...\n    def seekable(self) -> bool: ...\n    def tell(self) -> int: ...\n    def writable(self) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/codeop.pyi",
    "content": "import sys\nfrom types import CodeType\n\n__all__ = [\"compile_command\", \"Compile\", \"CommandCompiler\"]\n\nif sys.version_info >= (3, 14):\n    def compile_command(source: str, filename: str = \"<input>\", symbol: str = \"single\", flags: int = 0) -> CodeType | None: ...\n\nelse:\n    def compile_command(source: str, filename: str = \"<input>\", symbol: str = \"single\") -> CodeType | None: ...\n\nclass Compile:\n    flags: int\n    if sys.version_info >= (3, 13):\n        def __call__(self, source: str, filename: str, symbol: str, flags: int = 0) -> CodeType: ...\n    else:\n        def __call__(self, source: str, filename: str, symbol: str) -> CodeType: ...\n\nclass CommandCompiler:\n    compiler: Compile\n    def __call__(self, source: str, filename: str = \"<input>\", symbol: str = \"single\") -> CodeType | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/collections/__init__.pyi",
    "content": "import sys\nfrom _collections_abc import dict_items, dict_keys, dict_values\nfrom _typeshed import SupportsItems, SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT\nfrom types import GenericAlias\nfrom typing import Any, ClassVar, Generic, NoReturn, SupportsIndex, TypeVar, final, overload, type_check_only\nfrom typing_extensions import Self, disjoint_base\n\nif sys.version_info >= (3, 10):\n    from collections.abc import (\n        Callable,\n        ItemsView,\n        Iterable,\n        Iterator,\n        KeysView,\n        Mapping,\n        MutableMapping,\n        MutableSequence,\n        Sequence,\n        ValuesView,\n    )\nelse:\n    from _collections_abc import *\n\n__all__ = [\"ChainMap\", \"Counter\", \"OrderedDict\", \"UserDict\", \"UserList\", \"UserString\", \"defaultdict\", \"deque\", \"namedtuple\"]\n\n_S = TypeVar(\"_S\")\n_T = TypeVar(\"_T\")\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n_KT = TypeVar(\"_KT\")\n_VT = TypeVar(\"_VT\")\n_KT_co = TypeVar(\"_KT_co\", covariant=True)\n_VT_co = TypeVar(\"_VT_co\", covariant=True)\n\n# namedtuple is special-cased in the type checker; the initializer is ignored.\ndef namedtuple(\n    typename: str,\n    field_names: str | Iterable[str],\n    *,\n    rename: bool = False,\n    module: str | None = None,\n    defaults: Iterable[Any] | None = None,\n) -> type[tuple[Any, ...]]: ...\n\nclass UserDict(MutableMapping[_KT, _VT]):\n    data: dict[_KT, _VT]\n    # __init__ should be kept roughly in line with `dict.__init__`, which has the same semantics\n    @overload\n    def __init__(self, dict: None = None, /) -> None: ...\n    @overload\n    def __init__(\n        self: UserDict[str, _VT], dict: None = None, /, **kwargs: _VT  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n    ) -> None: ...\n    @overload\n    def __init__(self, dict: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ...\n    @overload\n    def __init__(\n        self: UserDict[str, _VT],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        dict: SupportsKeysAndGetItem[str, _VT],\n        /,\n        **kwargs: _VT,\n    ) -> None: ...\n    @overload\n    def __init__(self, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ...\n    @overload\n    def __init__(\n        self: UserDict[str, _VT],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        iterable: Iterable[tuple[str, _VT]],\n        /,\n        **kwargs: _VT,\n    ) -> None: ...\n    @overload\n    def __init__(self: UserDict[str, str], iterable: Iterable[list[str]], /) -> None: ...\n    @overload\n    def __init__(self: UserDict[bytes, bytes], iterable: Iterable[list[bytes]], /) -> None: ...\n    def __len__(self) -> int: ...\n    def __getitem__(self, key: _KT) -> _VT: ...\n    def __setitem__(self, key: _KT, item: _VT) -> None: ...\n    def __delitem__(self, key: _KT) -> None: ...\n    def __iter__(self) -> Iterator[_KT]: ...\n    def __contains__(self, key: object) -> bool: ...\n    def copy(self) -> Self: ...\n    def __copy__(self) -> Self: ...\n\n    # `UserDict.fromkeys` has the same semantics as `dict.fromkeys`, so should be kept in line with `dict.fromkeys`.\n    # TODO: Much like `dict.fromkeys`, the true signature of `UserDict.fromkeys` is inexpressible in the current type system.\n    # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963.\n    @classmethod\n    @overload\n    def fromkeys(cls, iterable: Iterable[_T], value: None = None) -> UserDict[_T, Any | None]: ...\n    @classmethod\n    @overload\n    def fromkeys(cls, iterable: Iterable[_T], value: _S) -> UserDict[_T, _S]: ...\n    @overload\n    def __or__(self, other: UserDict[_KT, _VT] | dict[_KT, _VT]) -> Self: ...\n    @overload\n    def __or__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ...\n    @overload\n    def __ror__(self, other: UserDict[_KT, _VT] | dict[_KT, _VT]) -> Self: ...\n    @overload\n    def __ror__(self, other: UserDict[_T1, _T2] | dict[_T1, _T2]) -> UserDict[_KT | _T1, _VT | _T2]: ...\n    # UserDict.__ior__ should be kept roughly in line with MutableMapping.update()\n    @overload  # type: ignore[misc]\n    def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ...\n    @overload\n    def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ...\n    if sys.version_info >= (3, 12):\n        @overload\n        def get(self, key: _KT, default: None = None) -> _VT | None: ...\n        @overload\n        def get(self, key: _KT, default: _VT) -> _VT: ...\n        @overload\n        def get(self, key: _KT, default: _T) -> _VT | _T: ...\n\nclass UserList(MutableSequence[_T]):\n    data: list[_T]\n    @overload\n    def __init__(self, initlist: None = None) -> None: ...\n    @overload\n    def __init__(self, initlist: Iterable[_T]) -> None: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __lt__(self, other: list[_T] | UserList[_T]) -> bool: ...\n    def __le__(self, other: list[_T] | UserList[_T]) -> bool: ...\n    def __gt__(self, other: list[_T] | UserList[_T]) -> bool: ...\n    def __ge__(self, other: list[_T] | UserList[_T]) -> bool: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __contains__(self, item: object) -> bool: ...\n    def __len__(self) -> int: ...\n    @overload\n    def __getitem__(self, i: SupportsIndex) -> _T: ...\n    @overload\n    def __getitem__(self, i: slice[SupportsIndex | None]) -> Self: ...\n    @overload\n    def __setitem__(self, i: SupportsIndex, item: _T) -> None: ...\n    @overload\n    def __setitem__(self, i: slice[SupportsIndex | None], item: Iterable[_T]) -> None: ...\n    def __delitem__(self, i: SupportsIndex | slice[SupportsIndex | None]) -> None: ...\n    def __add__(self, other: Iterable[_T]) -> Self: ...\n    def __radd__(self, other: Iterable[_T]) -> Self: ...\n    def __iadd__(self, other: Iterable[_T]) -> Self: ...\n    def __mul__(self, n: int) -> Self: ...\n    def __rmul__(self, n: int) -> Self: ...\n    def __imul__(self, n: int) -> Self: ...\n    def append(self, item: _T) -> None: ...\n    def insert(self, i: int, item: _T) -> None: ...\n    def pop(self, i: int = -1) -> _T: ...\n    def remove(self, item: _T) -> None: ...\n    def copy(self) -> Self: ...\n    def __copy__(self) -> Self: ...\n    def count(self, item: _T) -> int: ...\n    # The runtime signature is \"item, *args\", and the arguments are then passed\n    # to `list.index`. In order to give more precise types, we pretend that the\n    # `item` argument is positional-only.\n    def index(self, item: _T, start: SupportsIndex = 0, stop: SupportsIndex = sys.maxsize, /) -> int: ...\n    # All arguments are passed to `list.sort` at runtime, so the signature should be kept in line with `list.sort`.\n    @overload\n    def sort(self: UserList[SupportsRichComparisonT], *, key: None = None, reverse: bool = False) -> None: ...\n    @overload\n    def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = False) -> None: ...\n    def extend(self, other: Iterable[_T]) -> None: ...\n\nclass UserString(Sequence[UserString]):\n    data: str\n    def __init__(self, seq: object) -> None: ...\n    def __int__(self) -> int: ...\n    def __float__(self) -> float: ...\n    def __complex__(self) -> complex: ...\n    def __getnewargs__(self) -> tuple[str]: ...\n    def __lt__(self, string: str | UserString) -> bool: ...\n    def __le__(self, string: str | UserString) -> bool: ...\n    def __gt__(self, string: str | UserString) -> bool: ...\n    def __ge__(self, string: str | UserString) -> bool: ...\n    def __eq__(self, string: object) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __contains__(self, char: object) -> bool: ...\n    def __len__(self) -> int: ...\n    def __getitem__(self, index: SupportsIndex | slice[SupportsIndex | None]) -> Self: ...\n    def __iter__(self) -> Iterator[Self]: ...\n    def __reversed__(self) -> Iterator[Self]: ...\n    def __add__(self, other: object) -> Self: ...\n    def __radd__(self, other: object) -> Self: ...\n    def __mul__(self, n: int) -> Self: ...\n    def __rmul__(self, n: int) -> Self: ...\n    def __mod__(self, args: Any) -> Self: ...\n    def __rmod__(self, template: object) -> Self: ...\n    def capitalize(self) -> Self: ...\n    def casefold(self) -> Self: ...\n    def center(self, width: int, *args: Any) -> Self: ...\n    def count(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ...\n    def encode(self: UserString, encoding: str | None = \"utf-8\", errors: str | None = \"strict\") -> bytes: ...\n    def endswith(self, suffix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ...\n    def expandtabs(self, tabsize: int = 8) -> Self: ...\n    def find(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ...\n    def format(self, *args: Any, **kwds: Any) -> str: ...\n    def format_map(self, mapping: Mapping[str, Any]) -> str: ...\n    def index(self, sub: str, start: int = 0, end: int = sys.maxsize) -> int: ...\n    def isalpha(self) -> bool: ...\n    def isalnum(self) -> bool: ...\n    def isdecimal(self) -> bool: ...\n    def isdigit(self) -> bool: ...\n    def isidentifier(self) -> bool: ...\n    def islower(self) -> bool: ...\n    def isnumeric(self) -> bool: ...\n    def isprintable(self) -> bool: ...\n    def isspace(self) -> bool: ...\n    def istitle(self) -> bool: ...\n    def isupper(self) -> bool: ...\n    def isascii(self) -> bool: ...\n    def join(self, seq: Iterable[str]) -> str: ...\n    def ljust(self, width: int, *args: Any) -> Self: ...\n    def lower(self) -> Self: ...\n    def lstrip(self, chars: str | None = None) -> Self: ...\n    maketrans = str.maketrans\n    def partition(self, sep: str) -> tuple[str, str, str]: ...\n    def removeprefix(self, prefix: str | UserString, /) -> Self: ...\n    def removesuffix(self, suffix: str | UserString, /) -> Self: ...\n    def replace(self, old: str | UserString, new: str | UserString, maxsplit: int = -1) -> Self: ...\n    def rfind(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ...\n    def rindex(self, sub: str | UserString, start: int = 0, end: int = sys.maxsize) -> int: ...\n    def rjust(self, width: int, *args: Any) -> Self: ...\n    def rpartition(self, sep: str) -> tuple[str, str, str]: ...\n    def rstrip(self, chars: str | None = None) -> Self: ...\n    def split(self, sep: str | None = None, maxsplit: int = -1) -> list[str]: ...\n    def rsplit(self, sep: str | None = None, maxsplit: int = -1) -> list[str]: ...\n    def splitlines(self, keepends: bool = False) -> list[str]: ...\n    def startswith(self, prefix: str | tuple[str, ...], start: int | None = 0, end: int | None = sys.maxsize) -> bool: ...\n    def strip(self, chars: str | None = None) -> Self: ...\n    def swapcase(self) -> Self: ...\n    def title(self) -> Self: ...\n    def translate(self, *args: Any) -> Self: ...\n    def upper(self) -> Self: ...\n    def zfill(self, width: int) -> Self: ...\n\n@disjoint_base\nclass deque(MutableSequence[_T]):\n    @property\n    def maxlen(self) -> int | None: ...\n    @overload\n    def __init__(self, *, maxlen: int | None = None) -> None: ...\n    @overload\n    def __init__(self, iterable: Iterable[_T], maxlen: int | None = None) -> None: ...\n    def append(self, x: _T, /) -> None: ...\n    def appendleft(self, x: _T, /) -> None: ...\n    def copy(self) -> Self: ...\n    def count(self, x: _T, /) -> int: ...\n    def extend(self, iterable: Iterable[_T], /) -> None: ...\n    def extendleft(self, iterable: Iterable[_T], /) -> None: ...\n    def insert(self, i: int, x: _T, /) -> None: ...\n    def index(self, x: _T, start: int = 0, stop: int = ..., /) -> int: ...\n    def pop(self) -> _T: ...  # type: ignore[override]\n    def popleft(self) -> _T: ...\n    def remove(self, value: _T, /) -> None: ...\n    def rotate(self, n: int = 1, /) -> None: ...\n    def __copy__(self) -> Self: ...\n    def __len__(self) -> int: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    # These methods of deque don't take slices, unlike MutableSequence, hence the type: ignores\n    def __getitem__(self, key: SupportsIndex, /) -> _T: ...  # type: ignore[override]\n    def __setitem__(self, key: SupportsIndex, value: _T, /) -> None: ...  # type: ignore[override]\n    def __delitem__(self, key: SupportsIndex, /) -> None: ...  # type: ignore[override]\n    def __contains__(self, key: object, /) -> bool: ...\n    def __reduce__(self) -> tuple[type[Self], tuple[()], None, Iterator[_T]]: ...\n    def __iadd__(self, value: Iterable[_T], /) -> Self: ...\n    def __add__(self, value: Self, /) -> Self: ...\n    def __mul__(self, value: int, /) -> Self: ...\n    def __imul__(self, value: int, /) -> Self: ...\n    def __lt__(self, value: deque[_T], /) -> bool: ...\n    def __le__(self, value: deque[_T], /) -> bool: ...\n    def __gt__(self, value: deque[_T], /) -> bool: ...\n    def __ge__(self, value: deque[_T], /) -> bool: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass Counter(dict[_T, int], Generic[_T]):\n    @overload\n    def __init__(self, iterable: None = None, /) -> None: ...\n    @overload\n    def __init__(self: Counter[str], iterable: None = None, /, **kwargs: int) -> None: ...\n    @overload\n    def __init__(self, mapping: SupportsKeysAndGetItem[_T, int], /) -> None: ...\n    @overload\n    def __init__(self, iterable: Iterable[_T], /) -> None: ...\n    def copy(self) -> Self: ...\n    def elements(self) -> Iterator[_T]: ...\n    def most_common(self, n: int | None = None) -> list[tuple[_T, int]]: ...\n    @classmethod\n    def fromkeys(cls, iterable: Any, v: int | None = None) -> NoReturn: ...  # type: ignore[override]\n    @overload\n    def subtract(self, iterable: None = None, /) -> None: ...\n    @overload\n    def subtract(self, mapping: Mapping[_T, int], /) -> None: ...\n    @overload\n    def subtract(self, iterable: Iterable[_T], /) -> None: ...\n    # Unlike dict.update(), use Mapping instead of SupportsKeysAndGetItem for the first overload\n    # (source code does an `isinstance(other, Mapping)` check)\n    #\n    # The second overload is also deliberately different to dict.update()\n    # (if it were `Iterable[_T] | Iterable[tuple[_T, int]]`,\n    # the tuples would be added as keys, breaking type safety)\n    @overload  # type: ignore[override]\n    def update(self, m: Mapping[_T, int], /, **kwargs: int) -> None: ...\n    @overload\n    def update(self, iterable: Iterable[_T], /, **kwargs: int) -> None: ...\n    @overload\n    def update(self, iterable: None = None, /, **kwargs: int) -> None: ...\n    def __missing__(self, key: _T) -> int: ...\n    def __delitem__(self, elem: object) -> None: ...\n    if sys.version_info >= (3, 10):\n        def __eq__(self, other: object) -> bool: ...\n        def __ne__(self, other: object) -> bool: ...\n\n    def __add__(self, other: Counter[_S]) -> Counter[_T | _S]: ...\n    def __sub__(self, other: Counter[_T]) -> Counter[_T]: ...\n    def __and__(self, other: Counter[_T]) -> Counter[_T]: ...\n    def __or__(self, other: Counter[_S]) -> Counter[_T | _S]: ...  # type: ignore[override]\n    def __pos__(self) -> Counter[_T]: ...\n    def __neg__(self) -> Counter[_T]: ...\n    # several type: ignores because __iadd__ is supposedly incompatible with __add__, etc.\n    def __iadd__(self, other: SupportsItems[_T, int]) -> Self: ...  # type: ignore[misc]\n    def __isub__(self, other: SupportsItems[_T, int]) -> Self: ...\n    def __iand__(self, other: SupportsItems[_T, int]) -> Self: ...\n    def __ior__(self, other: SupportsItems[_T, int]) -> Self: ...  # type: ignore[override,misc]\n    if sys.version_info >= (3, 10):\n        def total(self) -> int: ...\n        def __le__(self, other: Counter[Any]) -> bool: ...\n        def __lt__(self, other: Counter[Any]) -> bool: ...\n        def __ge__(self, other: Counter[Any]) -> bool: ...\n        def __gt__(self, other: Counter[Any]) -> bool: ...\n\n# The pure-Python implementations of the \"views\" classes\n# These are exposed at runtime in `collections/__init__.py`\nclass _OrderedDictKeysView(KeysView[_KT_co]):\n    def __reversed__(self) -> Iterator[_KT_co]: ...\n\nclass _OrderedDictItemsView(ItemsView[_KT_co, _VT_co]):\n    def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ...\n\nclass _OrderedDictValuesView(ValuesView[_VT_co]):\n    def __reversed__(self) -> Iterator[_VT_co]: ...\n\n# The C implementations of the \"views\" classes\n# (At runtime, these are called `odict_keys`, `odict_items` and `odict_values`,\n# but they are not exposed anywhere)\n# pyright doesn't have a specific error code for subclassing error!\n@final\n@type_check_only\nclass _odict_keys(dict_keys[_KT_co, _VT_co]):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    def __reversed__(self) -> Iterator[_KT_co]: ...\n\n@final\n@type_check_only\nclass _odict_items(dict_items[_KT_co, _VT_co]):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    def __reversed__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ...\n\n@final\n@type_check_only\nclass _odict_values(dict_values[_KT_co, _VT_co]):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    def __reversed__(self) -> Iterator[_VT_co]: ...\n\n@disjoint_base\nclass OrderedDict(dict[_KT, _VT]):\n    def popitem(self, last: bool = True) -> tuple[_KT, _VT]: ...\n    def move_to_end(self, key: _KT, last: bool = True) -> None: ...\n    def copy(self) -> Self: ...\n    def __reversed__(self) -> Iterator[_KT]: ...\n    def keys(self) -> _odict_keys[_KT, _VT]: ...\n    def items(self) -> _odict_items[_KT, _VT]: ...\n    def values(self) -> _odict_values[_KT, _VT]: ...\n    # The signature of OrderedDict.fromkeys should be kept in line with `dict.fromkeys`, modulo positional-only differences.\n    # Like dict.fromkeys, its true signature is not expressible in the current type system.\n    # See #3800 & https://github.com/python/typing/issues/548#issuecomment-683336963.\n    @classmethod\n    @overload\n    def fromkeys(cls, iterable: Iterable[_T], value: None = None) -> OrderedDict[_T, Any | None]: ...\n    @classmethod\n    @overload\n    def fromkeys(cls, iterable: Iterable[_T], value: _S) -> OrderedDict[_T, _S]: ...\n    # Keep OrderedDict.setdefault in line with MutableMapping.setdefault, modulo positional-only differences.\n    @overload\n    def setdefault(self: OrderedDict[_KT, _T | None], key: _KT, default: None = None) -> _T | None: ...\n    @overload\n    def setdefault(self, key: _KT, default: _VT) -> _VT: ...\n    # Same as dict.pop, but accepts keyword arguments\n    @overload\n    def pop(self, key: _KT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _VT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _T) -> _VT | _T: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    @overload\n    def __or__(self, value: dict[_KT, _VT], /) -> Self: ...\n    @overload\n    def __or__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ...\n    @overload\n    def __ror__(self, value: dict[_KT, _VT], /) -> Self: ...\n    @overload\n    def __ror__(self, value: dict[_T1, _T2], /) -> OrderedDict[_KT | _T1, _VT | _T2]: ...  # type: ignore[misc]\n\n@disjoint_base\nclass defaultdict(dict[_KT, _VT]):\n    default_factory: Callable[[], _VT] | None\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self: defaultdict[str, _VT], **kwargs: _VT) -> None: ...  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n    @overload\n    def __init__(self, default_factory: Callable[[], _VT] | None, /) -> None: ...\n    @overload\n    def __init__(\n        self: defaultdict[str, _VT],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        default_factory: Callable[[], _VT] | None,\n        /,\n        **kwargs: _VT,\n    ) -> None: ...\n    @overload\n    def __init__(self, default_factory: Callable[[], _VT] | None, map: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ...\n    @overload\n    def __init__(\n        self: defaultdict[str, _VT],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        default_factory: Callable[[], _VT] | None,\n        map: SupportsKeysAndGetItem[str, _VT],\n        /,\n        **kwargs: _VT,\n    ) -> None: ...\n    @overload\n    def __init__(self, default_factory: Callable[[], _VT] | None, iterable: Iterable[tuple[_KT, _VT]], /) -> None: ...\n    @overload\n    def __init__(\n        self: defaultdict[str, _VT],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        default_factory: Callable[[], _VT] | None,\n        iterable: Iterable[tuple[str, _VT]],\n        /,\n        **kwargs: _VT,\n    ) -> None: ...\n    def __missing__(self, key: _KT, /) -> _VT: ...\n    def __copy__(self) -> Self: ...\n    def copy(self) -> Self: ...\n    @overload\n    def __or__(self, value: dict[_KT, _VT], /) -> Self: ...\n    @overload\n    def __or__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ...\n    @overload\n    def __ror__(self, value: dict[_KT, _VT], /) -> Self: ...\n    @overload\n    def __ror__(self, value: dict[_T1, _T2], /) -> defaultdict[_KT | _T1, _VT | _T2]: ...  # type: ignore[misc]\n\nclass ChainMap(MutableMapping[_KT, _VT]):\n    maps: list[MutableMapping[_KT, _VT]]\n    def __init__(self, *maps: MutableMapping[_KT, _VT]) -> None: ...\n    def new_child(self, m: MutableMapping[_KT, _VT] | None = None) -> Self: ...\n    @property\n    def parents(self) -> Self: ...\n    def __setitem__(self, key: _KT, value: _VT) -> None: ...\n    def __delitem__(self, key: _KT) -> None: ...\n    def __getitem__(self, key: _KT) -> _VT: ...\n    def __iter__(self) -> Iterator[_KT]: ...\n    def __len__(self) -> int: ...\n    def __contains__(self, key: object) -> bool: ...\n    @overload\n    def get(self, key: _KT, default: None = None) -> _VT | None: ...\n    @overload\n    def get(self, key: _KT, default: _VT) -> _VT: ...\n    @overload\n    def get(self, key: _KT, default: _T) -> _VT | _T: ...\n    def __missing__(self, key: _KT) -> _VT: ...  # undocumented\n    def __bool__(self) -> bool: ...\n    # Keep ChainMap.setdefault in line with MutableMapping.setdefault, modulo positional-only differences.\n    @overload\n    def setdefault(self: ChainMap[_KT, _T | None], key: _KT, default: None = None) -> _T | None: ...\n    @overload\n    def setdefault(self, key: _KT, default: _VT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _VT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _T) -> _VT | _T: ...\n    def copy(self) -> Self: ...\n    __copy__ = copy\n    # All arguments to `fromkeys` are passed to `dict.fromkeys` at runtime,\n    # so the signature should be kept in line with `dict.fromkeys`.\n    if sys.version_info >= (3, 13):\n        @classmethod\n        @overload\n        def fromkeys(cls, iterable: Iterable[_T], /) -> ChainMap[_T, Any | None]: ...\n    else:\n        @classmethod\n        @overload\n        def fromkeys(cls, iterable: Iterable[_T]) -> ChainMap[_T, Any | None]: ...\n\n    @classmethod\n    @overload\n    # Special-case None: the user probably wants to add non-None values later.\n    def fromkeys(cls, iterable: Iterable[_T], value: None, /) -> ChainMap[_T, Any | None]: ...\n    @classmethod\n    @overload\n    def fromkeys(cls, iterable: Iterable[_T], value: _S, /) -> ChainMap[_T, _S]: ...\n    @overload\n    def __or__(self, other: Mapping[_KT, _VT]) -> Self: ...\n    @overload\n    def __or__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ...\n    @overload\n    def __ror__(self, other: Mapping[_KT, _VT]) -> Self: ...\n    @overload\n    def __ror__(self, other: Mapping[_T1, _T2]) -> ChainMap[_KT | _T1, _VT | _T2]: ...\n    # ChainMap.__ior__ should be kept roughly in line with MutableMapping.update()\n    @overload  # type: ignore[misc]\n    def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ...\n    @overload\n    def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/collections/abc.pyi",
    "content": "from _collections_abc import *\nfrom _collections_abc import __all__ as __all__\n"
  },
  {
    "path": "mypy/typeshed/stdlib/colorsys.pyi",
    "content": "from typing import Final\n\n__all__ = [\"rgb_to_yiq\", \"yiq_to_rgb\", \"rgb_to_hls\", \"hls_to_rgb\", \"rgb_to_hsv\", \"hsv_to_rgb\"]\n\ndef rgb_to_yiq(r: float, g: float, b: float) -> tuple[float, float, float]: ...\ndef yiq_to_rgb(y: float, i: float, q: float) -> tuple[float, float, float]: ...\ndef rgb_to_hls(r: float, g: float, b: float) -> tuple[float, float, float]: ...\ndef hls_to_rgb(h: float, l: float, s: float) -> tuple[float, float, float]: ...\ndef rgb_to_hsv(r: float, g: float, b: float) -> tuple[float, float, float]: ...\ndef hsv_to_rgb(h: float, s: float, v: float) -> tuple[float, float, float]: ...\n\n# TODO: undocumented\nONE_SIXTH: Final[float]\nONE_THIRD: Final[float]\nTWO_THIRD: Final[float]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/compileall.pyi",
    "content": "import sys\nfrom _typeshed import StrPath\nfrom py_compile import PycInvalidationMode\nfrom typing import Any, Protocol, type_check_only\n\n__all__ = [\"compile_dir\", \"compile_file\", \"compile_path\"]\n\n@type_check_only\nclass _SupportsSearch(Protocol):\n    def search(self, string: str, /) -> Any: ...\n\nif sys.version_info >= (3, 10):\n    def compile_dir(\n        dir: StrPath,\n        maxlevels: int | None = None,\n        ddir: StrPath | None = None,\n        force: bool = False,\n        rx: _SupportsSearch | None = None,\n        quiet: int = 0,\n        legacy: bool = False,\n        optimize: int = -1,\n        workers: int = 1,\n        invalidation_mode: PycInvalidationMode | None = None,\n        *,\n        stripdir: StrPath | None = None,\n        prependdir: StrPath | None = None,\n        limit_sl_dest: StrPath | None = None,\n        hardlink_dupes: bool = False,\n    ) -> bool: ...\n    def compile_file(\n        fullname: StrPath,\n        ddir: StrPath | None = None,\n        force: bool = False,\n        rx: _SupportsSearch | None = None,\n        quiet: int = 0,\n        legacy: bool = False,\n        optimize: int = -1,\n        invalidation_mode: PycInvalidationMode | None = None,\n        *,\n        stripdir: StrPath | None = None,\n        prependdir: StrPath | None = None,\n        limit_sl_dest: StrPath | None = None,\n        hardlink_dupes: bool = False,\n    ) -> bool: ...\n\nelse:\n    def compile_dir(\n        dir: StrPath,\n        maxlevels: int | None = None,\n        ddir: StrPath | None = None,\n        force: bool = False,\n        rx: _SupportsSearch | None = None,\n        quiet: int = 0,\n        legacy: bool = False,\n        optimize: int = -1,\n        workers: int = 1,\n        invalidation_mode: PycInvalidationMode | None = None,\n        *,\n        stripdir: str | None = None,  # https://bugs.python.org/issue40447\n        prependdir: StrPath | None = None,\n        limit_sl_dest: StrPath | None = None,\n        hardlink_dupes: bool = False,\n    ) -> bool: ...\n    def compile_file(\n        fullname: StrPath,\n        ddir: StrPath | None = None,\n        force: bool = False,\n        rx: _SupportsSearch | None = None,\n        quiet: int = 0,\n        legacy: bool = False,\n        optimize: int = -1,\n        invalidation_mode: PycInvalidationMode | None = None,\n        *,\n        stripdir: str | None = None,  # https://bugs.python.org/issue40447\n        prependdir: StrPath | None = None,\n        limit_sl_dest: StrPath | None = None,\n        hardlink_dupes: bool = False,\n    ) -> bool: ...\n\ndef compile_path(\n    skip_curdir: bool = ...,\n    maxlevels: int = 0,\n    force: bool = False,\n    quiet: int = 0,\n    legacy: bool = False,\n    optimize: int = -1,\n    invalidation_mode: PycInvalidationMode | None = None,\n) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/compression/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/compression/_common/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/compression/_common/_streams.pyi",
    "content": "from _typeshed import ReadableBuffer, WriteableBuffer\nfrom collections.abc import Callable\nfrom io import DEFAULT_BUFFER_SIZE, BufferedIOBase, RawIOBase\nfrom typing import Any, Protocol, type_check_only\n\nBUFFER_SIZE = DEFAULT_BUFFER_SIZE\n\n@type_check_only\nclass _Reader(Protocol):\n    def read(self, n: int, /) -> bytes: ...\n    def seekable(self) -> bool: ...\n    def seek(self, n: int, /) -> Any: ...\n\n@type_check_only\nclass _Decompressor(Protocol):\n    def decompress(self, data: ReadableBuffer, /, max_length: int = ...) -> bytes: ...\n    @property\n    def unused_data(self) -> bytes: ...\n    @property\n    def eof(self) -> bool: ...\n    # `zlib._Decompress` does not have next property, but `DecompressReader` calls it:\n    # @property\n    # def needs_input(self) -> bool: ...\n\nclass BaseStream(BufferedIOBase): ...\n\nclass DecompressReader(RawIOBase):\n    def __init__(\n        self,\n        fp: _Reader,\n        decomp_factory: Callable[..., _Decompressor],  # Consider backporting changes to _compression\n        trailing_error: type[Exception] | tuple[type[Exception], ...] = (),\n        **decomp_args: Any,  # These are passed to decomp_factory.\n    ) -> None: ...\n    def readinto(self, b: WriteableBuffer) -> int: ...\n    def read(self, size: int = -1) -> bytes: ...\n    def seek(self, offset: int, whence: int = 0) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/compression/bz2.pyi",
    "content": "from bz2 import *\n"
  },
  {
    "path": "mypy/typeshed/stdlib/compression/gzip.pyi",
    "content": "from gzip import *\n"
  },
  {
    "path": "mypy/typeshed/stdlib/compression/lzma.pyi",
    "content": "from lzma import *\n"
  },
  {
    "path": "mypy/typeshed/stdlib/compression/zlib.pyi",
    "content": "from zlib import *\n"
  },
  {
    "path": "mypy/typeshed/stdlib/compression/zstd/__init__.pyi",
    "content": "import enum\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Iterable, Mapping\nfrom compression.zstd._zstdfile import ZstdFile, open\nfrom typing import Final, final\n\nimport _zstd\nfrom _zstd import ZstdCompressor, ZstdDecompressor, ZstdDict, ZstdError, get_frame_size, zstd_version\n\n__all__ = (\n    # compression.zstd\n    \"COMPRESSION_LEVEL_DEFAULT\",\n    \"compress\",\n    \"CompressionParameter\",\n    \"decompress\",\n    \"DecompressionParameter\",\n    \"finalize_dict\",\n    \"get_frame_info\",\n    \"Strategy\",\n    \"train_dict\",\n    # compression.zstd._zstdfile\n    \"open\",\n    \"ZstdFile\",\n    # _zstd\n    \"get_frame_size\",\n    \"zstd_version\",\n    \"zstd_version_info\",\n    \"ZstdCompressor\",\n    \"ZstdDecompressor\",\n    \"ZstdDict\",\n    \"ZstdError\",\n)\n\nzstd_version_info: Final[tuple[int, int, int]]\nCOMPRESSION_LEVEL_DEFAULT: Final = _zstd.ZSTD_CLEVEL_DEFAULT\n\nclass FrameInfo:\n    __slots__ = (\"decompressed_size\", \"dictionary_id\")\n    decompressed_size: int\n    dictionary_id: int\n    def __init__(self, decompressed_size: int, dictionary_id: int) -> None: ...\n\ndef get_frame_info(frame_buffer: ReadableBuffer) -> FrameInfo: ...\ndef train_dict(samples: Iterable[ReadableBuffer], dict_size: int) -> ZstdDict: ...\ndef finalize_dict(zstd_dict: ZstdDict, /, samples: Iterable[ReadableBuffer], dict_size: int, level: int) -> ZstdDict: ...\ndef compress(\n    data: ReadableBuffer,\n    level: int | None = None,\n    options: Mapping[int, int] | None = None,\n    zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n) -> bytes: ...\ndef decompress(\n    data: ReadableBuffer, zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None, options: Mapping[int, int] | None = None\n) -> bytes: ...\n@final\nclass CompressionParameter(enum.IntEnum):\n    compression_level = _zstd.ZSTD_c_compressionLevel\n    window_log = _zstd.ZSTD_c_windowLog\n    hash_log = _zstd.ZSTD_c_hashLog\n    chain_log = _zstd.ZSTD_c_chainLog\n    search_log = _zstd.ZSTD_c_searchLog\n    min_match = _zstd.ZSTD_c_minMatch\n    target_length = _zstd.ZSTD_c_targetLength\n    strategy = _zstd.ZSTD_c_strategy\n    enable_long_distance_matching = _zstd.ZSTD_c_enableLongDistanceMatching\n    ldm_hash_log = _zstd.ZSTD_c_ldmHashLog\n    ldm_min_match = _zstd.ZSTD_c_ldmMinMatch\n    ldm_bucket_size_log = _zstd.ZSTD_c_ldmBucketSizeLog\n    ldm_hash_rate_log = _zstd.ZSTD_c_ldmHashRateLog\n    content_size_flag = _zstd.ZSTD_c_contentSizeFlag\n    checksum_flag = _zstd.ZSTD_c_checksumFlag\n    dict_id_flag = _zstd.ZSTD_c_dictIDFlag\n    nb_workers = _zstd.ZSTD_c_nbWorkers\n    job_size = _zstd.ZSTD_c_jobSize\n    overlap_log = _zstd.ZSTD_c_overlapLog\n    def bounds(self) -> tuple[int, int]: ...\n\n@final\nclass DecompressionParameter(enum.IntEnum):\n    window_log_max = _zstd.ZSTD_d_windowLogMax\n    def bounds(self) -> tuple[int, int]: ...\n\n@final\nclass Strategy(enum.IntEnum):\n    fast = _zstd.ZSTD_fast\n    dfast = _zstd.ZSTD_dfast\n    greedy = _zstd.ZSTD_greedy\n    lazy = _zstd.ZSTD_lazy\n    lazy2 = _zstd.ZSTD_lazy2\n    btlazy2 = _zstd.ZSTD_btlazy2\n    btopt = _zstd.ZSTD_btopt\n    btultra = _zstd.ZSTD_btultra\n    btultra2 = _zstd.ZSTD_btultra2\n"
  },
  {
    "path": "mypy/typeshed/stdlib/compression/zstd/_zstdfile.pyi",
    "content": "from _typeshed import ReadableBuffer, StrOrBytesPath, SupportsWrite, WriteableBuffer\nfrom collections.abc import Mapping\nfrom compression._common import _streams\nfrom compression.zstd import ZstdDict\nfrom io import TextIOWrapper, _WrappedBuffer\nfrom typing import Literal, Protocol, overload, type_check_only\nfrom typing_extensions import TypeAlias\n\nfrom _zstd import ZstdCompressor, _ZstdCompressorFlushBlock, _ZstdCompressorFlushFrame\n\n__all__ = (\"ZstdFile\", \"open\")\n\n_ReadBinaryMode: TypeAlias = Literal[\"r\", \"rb\"]\n_WriteBinaryMode: TypeAlias = Literal[\"w\", \"wb\", \"x\", \"xb\", \"a\", \"ab\"]\n_ReadTextMode: TypeAlias = Literal[\"rt\"]\n_WriteTextMode: TypeAlias = Literal[\"wt\", \"xt\", \"at\"]\n\n@type_check_only\nclass _FileBinaryRead(_streams._Reader, Protocol):\n    def close(self) -> None: ...\n\n@type_check_only\nclass _FileBinaryWrite(SupportsWrite[bytes], Protocol):\n    def close(self) -> None: ...\n\nclass ZstdFile(_streams.BaseStream):\n    FLUSH_BLOCK = ZstdCompressor.FLUSH_BLOCK\n    FLUSH_FRAME = ZstdCompressor.FLUSH_FRAME\n\n    @overload\n    def __init__(\n        self,\n        file: StrOrBytesPath | _FileBinaryRead,\n        /,\n        mode: _ReadBinaryMode = \"r\",\n        *,\n        level: None = None,\n        options: Mapping[int, int] | None = None,\n        zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        file: StrOrBytesPath | _FileBinaryWrite,\n        /,\n        mode: _WriteBinaryMode,\n        *,\n        level: int | None = None,\n        options: Mapping[int, int] | None = None,\n        zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n    ) -> None: ...\n    def write(self, data: ReadableBuffer, /) -> int: ...\n    def flush(self, mode: _ZstdCompressorFlushBlock | _ZstdCompressorFlushFrame = 1) -> bytes: ...  # type: ignore[override]\n    def read(self, size: int | None = -1) -> bytes: ...\n    def read1(self, size: int | None = -1) -> bytes: ...\n    def readinto(self, b: WriteableBuffer) -> int: ...\n    def readinto1(self, b: WriteableBuffer) -> int: ...\n    def readline(self, size: int | None = -1) -> bytes: ...\n    def seek(self, offset: int, whence: int = 0) -> int: ...\n    def peek(self, size: int = -1) -> bytes: ...\n    @property\n    def name(self) -> str | bytes: ...\n    @property\n    def mode(self) -> Literal[\"rb\", \"wb\"]: ...\n\n@overload\ndef open(\n    file: StrOrBytesPath | _FileBinaryRead,\n    /,\n    mode: _ReadBinaryMode = \"rb\",\n    *,\n    level: None = None,\n    options: Mapping[int, int] | None = None,\n    zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> ZstdFile: ...\n@overload\ndef open(\n    file: StrOrBytesPath | _FileBinaryWrite,\n    /,\n    mode: _WriteBinaryMode,\n    *,\n    level: int | None = None,\n    options: Mapping[int, int] | None = None,\n    zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> ZstdFile: ...\n@overload\ndef open(\n    file: StrOrBytesPath | _WrappedBuffer,\n    /,\n    mode: _ReadTextMode,\n    *,\n    level: None = None,\n    options: Mapping[int, int] | None = None,\n    zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> TextIOWrapper: ...\n@overload\ndef open(\n    file: StrOrBytesPath | _WrappedBuffer,\n    /,\n    mode: _WriteTextMode,\n    *,\n    level: int | None = None,\n    options: Mapping[int, int] | None = None,\n    zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> TextIOWrapper: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/concurrent/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/concurrent/futures/__init__.pyi",
    "content": "import sys\n\nfrom ._base import (\n    ALL_COMPLETED as ALL_COMPLETED,\n    FIRST_COMPLETED as FIRST_COMPLETED,\n    FIRST_EXCEPTION as FIRST_EXCEPTION,\n    BrokenExecutor as BrokenExecutor,\n    CancelledError as CancelledError,\n    Executor as Executor,\n    Future as Future,\n    InvalidStateError as InvalidStateError,\n    TimeoutError as TimeoutError,\n    as_completed as as_completed,\n    wait as wait,\n)\nfrom .process import ProcessPoolExecutor as ProcessPoolExecutor\nfrom .thread import ThreadPoolExecutor as ThreadPoolExecutor\n\nif sys.version_info >= (3, 14):\n    from .interpreter import InterpreterPoolExecutor as InterpreterPoolExecutor\n\n    __all__ = [\n        \"FIRST_COMPLETED\",\n        \"FIRST_EXCEPTION\",\n        \"ALL_COMPLETED\",\n        \"CancelledError\",\n        \"TimeoutError\",\n        \"InvalidStateError\",\n        \"BrokenExecutor\",\n        \"Future\",\n        \"Executor\",\n        \"wait\",\n        \"as_completed\",\n        \"ProcessPoolExecutor\",\n        \"ThreadPoolExecutor\",\n        \"InterpreterPoolExecutor\",\n    ]\n\nelif sys.version_info >= (3, 13):\n    __all__ = (\n        \"FIRST_COMPLETED\",\n        \"FIRST_EXCEPTION\",\n        \"ALL_COMPLETED\",\n        \"CancelledError\",\n        \"TimeoutError\",\n        \"InvalidStateError\",\n        \"BrokenExecutor\",\n        \"Future\",\n        \"Executor\",\n        \"wait\",\n        \"as_completed\",\n        \"ProcessPoolExecutor\",\n        \"ThreadPoolExecutor\",\n    )\nelse:\n    __all__ = (\n        \"FIRST_COMPLETED\",\n        \"FIRST_EXCEPTION\",\n        \"ALL_COMPLETED\",\n        \"CancelledError\",\n        \"TimeoutError\",\n        \"BrokenExecutor\",\n        \"Future\",\n        \"Executor\",\n        \"wait\",\n        \"as_completed\",\n        \"ProcessPoolExecutor\",\n        \"ThreadPoolExecutor\",\n    )\n\ndef __dir__() -> tuple[str, ...]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/concurrent/futures/_base.pyi",
    "content": "import sys\nimport threading\nfrom _typeshed import Unused\nfrom collections.abc import Callable, Iterable, Iterator\nfrom logging import Logger\nfrom types import GenericAlias, TracebackType\nfrom typing import Any, Final, Generic, NamedTuple, Protocol, TypeVar, type_check_only\nfrom typing_extensions import ParamSpec, Self\n\nFIRST_COMPLETED: Final = \"FIRST_COMPLETED\"\nFIRST_EXCEPTION: Final = \"FIRST_EXCEPTION\"\nALL_COMPLETED: Final = \"ALL_COMPLETED\"\nPENDING: Final = \"PENDING\"\nRUNNING: Final = \"RUNNING\"\nCANCELLED: Final = \"CANCELLED\"\nCANCELLED_AND_NOTIFIED: Final = \"CANCELLED_AND_NOTIFIED\"\nFINISHED: Final = \"FINISHED\"\n_STATE_TO_DESCRIPTION_MAP: Final[dict[str, str]]\nLOGGER: Logger\n\nclass Error(Exception): ...\nclass CancelledError(Error): ...\n\nif sys.version_info >= (3, 11):\n    from builtins import TimeoutError as TimeoutError\nelse:\n    class TimeoutError(Error): ...\n\nclass InvalidStateError(Error): ...\nclass BrokenExecutor(RuntimeError): ...\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_P = ParamSpec(\"_P\")\n\nclass Future(Generic[_T]):\n    _condition: threading.Condition\n    _state: str\n    _result: _T | None\n    _exception: BaseException | None\n    _waiters: list[_Waiter]\n    def cancel(self) -> bool: ...\n    def cancelled(self) -> bool: ...\n    def running(self) -> bool: ...\n    def done(self) -> bool: ...\n    def add_done_callback(self, fn: Callable[[Future[_T]], object]) -> None: ...\n    def result(self, timeout: float | None = None) -> _T: ...\n    def set_running_or_notify_cancel(self) -> bool: ...\n    def set_result(self, result: _T) -> None: ...\n    def exception(self, timeout: float | None = None) -> BaseException | None: ...\n    def set_exception(self, exception: BaseException | None) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass Executor:\n    def submit(self, fn: Callable[_P, _T], /, *args: _P.args, **kwargs: _P.kwargs) -> Future[_T]: ...\n    if sys.version_info >= (3, 14):\n        def map(\n            self,\n            fn: Callable[..., _T],\n            *iterables: Iterable[Any],\n            timeout: float | None = None,\n            chunksize: int = 1,\n            buffersize: int | None = None,\n        ) -> Iterator[_T]: ...\n    else:\n        def map(\n            self, fn: Callable[..., _T], *iterables: Iterable[Any], timeout: float | None = None, chunksize: int = 1\n        ) -> Iterator[_T]: ...\n\n    def shutdown(self, wait: bool = True, *, cancel_futures: bool = False) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> bool | None: ...\n\n@type_check_only\nclass _AsCompletedFuture(Protocol[_T_co]):\n    # as_completed only mutates non-generic aspects of passed Futures and does not do any nominal\n    # checks. Therefore, we can use a Protocol here to allow as_completed to act covariantly.\n    # See the tests for concurrent.futures\n    _condition: threading.Condition\n    _state: str\n    _waiters: list[_Waiter]\n    # Not used by as_completed, but needed to propagate the generic type\n    def result(self, timeout: float | None = None) -> _T_co: ...\n\ndef as_completed(fs: Iterable[_AsCompletedFuture[_T]], timeout: float | None = None) -> Iterator[Future[_T]]: ...\n\nclass DoneAndNotDoneFutures(NamedTuple, Generic[_T]):\n    done: set[Future[_T]]\n    not_done: set[Future[_T]]\n\ndef wait(\n    fs: Iterable[Future[_T]], timeout: float | None = None, return_when: str = \"ALL_COMPLETED\"\n) -> DoneAndNotDoneFutures[_T]: ...\n\nclass _Waiter:\n    event: threading.Event\n    finished_futures: list[Future[Any]]\n    def add_result(self, future: Future[Any]) -> None: ...\n    def add_exception(self, future: Future[Any]) -> None: ...\n    def add_cancelled(self, future: Future[Any]) -> None: ...\n\nclass _AsCompletedWaiter(_Waiter):\n    lock: threading.Lock\n\nclass _FirstCompletedWaiter(_Waiter): ...\n\nclass _AllCompletedWaiter(_Waiter):\n    num_pending_calls: int\n    stop_on_exception: bool\n    lock: threading.Lock\n    def __init__(self, num_pending_calls: int, stop_on_exception: bool) -> None: ...\n\nclass _AcquireFutures:\n    futures: Iterable[Future[Any]]\n    def __init__(self, futures: Iterable[Future[Any]]) -> None: ...\n    def __enter__(self) -> None: ...\n    def __exit__(self, *args: Unused) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/concurrent/futures/interpreter.pyi",
    "content": "import sys\nfrom collections.abc import Callable\nfrom concurrent.futures import ThreadPoolExecutor\nfrom typing import Any, Literal, Protocol, overload, type_check_only\nfrom typing_extensions import ParamSpec, Self, TypeAlias, TypeVar, TypeVarTuple, Unpack\n\n_Task: TypeAlias = tuple[bytes, Literal[\"function\", \"script\"]]\n_Ts = TypeVarTuple(\"_Ts\")\n_P = ParamSpec(\"_P\")\n_R = TypeVar(\"_R\")\n\n@type_check_only\nclass _TaskFunc(Protocol):\n    @overload\n    def __call__(self, fn: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> tuple[bytes, Literal[\"function\"]]: ...\n    @overload\n    def __call__(self, fn: str) -> tuple[bytes, Literal[\"script\"]]: ...\n\nif sys.version_info >= (3, 14):\n    from concurrent.futures.thread import BrokenThreadPool, WorkerContext as ThreadWorkerContext\n    from concurrent.interpreters import Interpreter, Queue\n\n    def do_call(results: Queue, func: Callable[..., _R], args: tuple[Any, ...], kwargs: dict[str, Any]) -> _R: ...\n\n    class WorkerContext(ThreadWorkerContext):\n        interp: Interpreter | None\n        results: Queue | None\n        @overload  # type: ignore[override]\n        @classmethod\n        def prepare(\n            cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]]\n        ) -> tuple[Callable[[], Self], _TaskFunc]: ...\n        @overload\n        @classmethod\n        def prepare(cls, initializer: Callable[[], object], initargs: tuple[()]) -> tuple[Callable[[], Self], _TaskFunc]: ...\n        def __init__(self, initdata: _Task) -> None: ...\n        def __del__(self) -> None: ...\n        def run(self, task: _Task) -> None: ...  # type: ignore[override]\n\n    class BrokenInterpreterPool(BrokenThreadPool): ...\n\n    class InterpreterPoolExecutor(ThreadPoolExecutor):\n        BROKEN: type[BrokenInterpreterPool]\n\n        @overload  # type: ignore[override]\n        @classmethod\n        def prepare_context(\n            cls, initializer: Callable[[], object], initargs: tuple[()]\n        ) -> tuple[Callable[[], WorkerContext], _TaskFunc]: ...\n        @overload\n        @classmethod\n        def prepare_context(\n            cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]]\n        ) -> tuple[Callable[[], WorkerContext], _TaskFunc]: ...\n        @overload\n        def __init__(\n            self,\n            max_workers: int | None = None,\n            thread_name_prefix: str = \"\",\n            initializer: Callable[[], object] | None = None,\n            initargs: tuple[()] = (),\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            max_workers: int | None = None,\n            thread_name_prefix: str = \"\",\n            *,\n            initializer: Callable[[Unpack[_Ts]], object],\n            initargs: tuple[Unpack[_Ts]],\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            max_workers: int | None,\n            thread_name_prefix: str,\n            initializer: Callable[[Unpack[_Ts]], object],\n            initargs: tuple[Unpack[_Ts]],\n        ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/concurrent/futures/process.pyi",
    "content": "import sys\nfrom collections.abc import Callable, Generator, Iterable, Mapping, MutableMapping, MutableSequence\nfrom multiprocessing.connection import Connection\nfrom multiprocessing.context import BaseContext, Process\nfrom multiprocessing.queues import Queue, SimpleQueue\nfrom threading import Lock, Semaphore, Thread\nfrom types import TracebackType\nfrom typing import Any, Final, Generic, TypeVar, overload\nfrom typing_extensions import TypeVarTuple, Unpack\nfrom weakref import ref\n\nfrom ._base import BrokenExecutor, Executor, Future\n\n_T = TypeVar(\"_T\")\n_Ts = TypeVarTuple(\"_Ts\")\n\n_threads_wakeups: MutableMapping[Any, Any]\n_global_shutdown: bool\n\nclass _ThreadWakeup:\n    _closed: bool\n    # Any: Unused send and recv methods\n    _reader: Connection[Any, Any]\n    _writer: Connection[Any, Any]\n    def close(self) -> None: ...\n    def wakeup(self) -> None: ...\n    def clear(self) -> None: ...\n\ndef _python_exit() -> None: ...\n\nEXTRA_QUEUED_CALLS: Final = 1\n\n_MAX_WINDOWS_WORKERS: Final = 61\n\nclass _RemoteTraceback(Exception):\n    tb: str\n    def __init__(self, tb: TracebackType) -> None: ...\n\nclass _ExceptionWithTraceback:\n    exc: BaseException\n    tb: TracebackType\n    def __init__(self, exc: BaseException, tb: TracebackType) -> None: ...\n    def __reduce__(self) -> str | tuple[Any, ...]: ...\n\ndef _rebuild_exc(exc: Exception, tb: str) -> Exception: ...\n\nclass _WorkItem(Generic[_T]):\n    future: Future[_T]\n    fn: Callable[..., _T]\n    args: Iterable[Any]\n    kwargs: Mapping[str, Any]\n    def __init__(self, future: Future[_T], fn: Callable[..., _T], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ...\n\nclass _ResultItem:\n    work_id: int\n    exception: Exception\n    result: Any\n    if sys.version_info >= (3, 11):\n        exit_pid: int | None\n        def __init__(\n            self, work_id: int, exception: Exception | None = None, result: Any | None = None, exit_pid: int | None = None\n        ) -> None: ...\n    else:\n        def __init__(self, work_id: int, exception: Exception | None = None, result: Any | None = None) -> None: ...\n\nclass _CallItem:\n    work_id: int\n    fn: Callable[..., Any]\n    args: Iterable[Any]\n    kwargs: Mapping[str, Any]\n    def __init__(self, work_id: int, fn: Callable[..., Any], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ...\n\nclass _SafeQueue(Queue[Future[Any]]):\n    pending_work_items: dict[int, _WorkItem[Any]]\n    if sys.version_info < (3, 12):\n        shutdown_lock: Lock\n    thread_wakeup: _ThreadWakeup\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self,\n            max_size: int | None = 0,\n            *,\n            ctx: BaseContext,\n            pending_work_items: dict[int, _WorkItem[Any]],\n            thread_wakeup: _ThreadWakeup,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            max_size: int | None = 0,\n            *,\n            ctx: BaseContext,\n            pending_work_items: dict[int, _WorkItem[Any]],\n            shutdown_lock: Lock,\n            thread_wakeup: _ThreadWakeup,\n        ) -> None: ...\n\n    def _on_queue_feeder_error(self, e: Exception, obj: _CallItem) -> None: ...\n\ndef _get_chunks(*iterables: Any, chunksize: int) -> Generator[tuple[Any, ...], None, None]: ...\ndef _process_chunk(fn: Callable[..., _T], chunk: Iterable[tuple[Any, ...]]) -> list[_T]: ...\n\nif sys.version_info >= (3, 11):\n    def _sendback_result(\n        result_queue: SimpleQueue[_WorkItem[Any]],\n        work_id: int,\n        result: Any | None = None,\n        exception: Exception | None = None,\n        exit_pid: int | None = None,\n    ) -> None: ...\n\nelse:\n    def _sendback_result(\n        result_queue: SimpleQueue[_WorkItem[Any]], work_id: int, result: Any | None = None, exception: Exception | None = None\n    ) -> None: ...\n\nif sys.version_info >= (3, 11):\n    def _process_worker(\n        call_queue: Queue[_CallItem],\n        result_queue: SimpleQueue[_ResultItem],\n        initializer: Callable[[Unpack[_Ts]], object] | None,\n        initargs: tuple[Unpack[_Ts]],\n        max_tasks: int | None = None,\n    ) -> None: ...\n\nelse:\n    def _process_worker(\n        call_queue: Queue[_CallItem],\n        result_queue: SimpleQueue[_ResultItem],\n        initializer: Callable[[Unpack[_Ts]], object] | None,\n        initargs: tuple[Unpack[_Ts]],\n    ) -> None: ...\n\nclass _ExecutorManagerThread(Thread):\n    thread_wakeup: _ThreadWakeup\n    shutdown_lock: Lock\n    executor_reference: ref[Any]\n    processes: MutableMapping[int, Process]\n    call_queue: Queue[_CallItem]\n    result_queue: SimpleQueue[_ResultItem]\n    work_ids_queue: Queue[int]\n    pending_work_items: dict[int, _WorkItem[Any]]\n    def __init__(self, executor: ProcessPoolExecutor) -> None: ...\n    def run(self) -> None: ...\n    def add_call_item_to_queue(self) -> None: ...\n    def wait_result_broken_or_wakeup(self) -> tuple[Any, bool, str]: ...\n    def process_result_item(self, result_item: int | _ResultItem) -> None: ...\n    def is_shutting_down(self) -> bool: ...\n    def terminate_broken(self, cause: str) -> None: ...\n    def flag_executor_shutting_down(self) -> None: ...\n    def shutdown_workers(self) -> None: ...\n    def join_executor_internals(self) -> None: ...\n    def get_n_children_alive(self) -> int: ...\n\n_system_limits_checked: bool\n_system_limited: bool | None\n\ndef _check_system_limits() -> None: ...\ndef _chain_from_iterable_of_lists(iterable: Iterable[MutableSequence[Any]]) -> Any: ...\n\nclass BrokenProcessPool(BrokenExecutor): ...\n\nclass ProcessPoolExecutor(Executor):\n    _mp_context: BaseContext | None\n    _initializer: Callable[..., None] | None\n    _initargs: tuple[Any, ...]\n    _executor_manager_thread: _ThreadWakeup\n    _processes: MutableMapping[int, Process]\n    _shutdown_thread: bool\n    _shutdown_lock: Lock\n    _idle_worker_semaphore: Semaphore\n    _broken: bool\n    _queue_count: int\n    _pending_work_items: dict[int, _WorkItem[Any]]\n    _cancel_pending_futures: bool\n    _executor_manager_thread_wakeup: _ThreadWakeup\n    _result_queue: SimpleQueue[Any]\n    _work_ids: Queue[Any]\n    if sys.version_info >= (3, 11):\n        @overload\n        def __init__(\n            self,\n            max_workers: int | None = None,\n            mp_context: BaseContext | None = None,\n            initializer: Callable[[], object] | None = None,\n            initargs: tuple[()] = (),\n            *,\n            max_tasks_per_child: int | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            max_workers: int | None = None,\n            mp_context: BaseContext | None = None,\n            *,\n            initializer: Callable[[Unpack[_Ts]], object],\n            initargs: tuple[Unpack[_Ts]],\n            max_tasks_per_child: int | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            max_workers: int | None,\n            mp_context: BaseContext | None,\n            initializer: Callable[[Unpack[_Ts]], object],\n            initargs: tuple[Unpack[_Ts]],\n            *,\n            max_tasks_per_child: int | None = None,\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self,\n            max_workers: int | None = None,\n            mp_context: BaseContext | None = None,\n            initializer: Callable[[], object] | None = None,\n            initargs: tuple[()] = (),\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            max_workers: int | None = None,\n            mp_context: BaseContext | None = None,\n            *,\n            initializer: Callable[[Unpack[_Ts]], object],\n            initargs: tuple[Unpack[_Ts]],\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            max_workers: int | None,\n            mp_context: BaseContext | None,\n            initializer: Callable[[Unpack[_Ts]], object],\n            initargs: tuple[Unpack[_Ts]],\n        ) -> None: ...\n\n    def _start_executor_manager_thread(self) -> None: ...\n    def _adjust_process_count(self) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def kill_workers(self) -> None: ...\n        def terminate_workers(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/concurrent/futures/thread.pyi",
    "content": "import queue\nimport sys\nfrom collections.abc import Callable, Iterable, Mapping, Set as AbstractSet\nfrom threading import Lock, Semaphore, Thread\nfrom types import GenericAlias\nfrom typing import Any, Generic, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, TypeVarTuple, Unpack\nfrom weakref import ref\n\nfrom ._base import BrokenExecutor, Executor, Future\n\n_Ts = TypeVarTuple(\"_Ts\")\n\n_threads_queues: Mapping[Any, Any]\n_shutdown: bool\n_global_shutdown_lock: Lock\n\ndef _python_exit() -> None: ...\n\n_S = TypeVar(\"_S\")\n\n_Task: TypeAlias = tuple[Callable[..., Any], tuple[Any, ...], dict[str, Any]]\n\n_C = TypeVar(\"_C\", bound=Callable[..., object])\n_KT = TypeVar(\"_KT\", bound=str)\n_VT = TypeVar(\"_VT\")\n\n@type_check_only\nclass _ResolveTaskFunc(Protocol):\n    def __call__(\n        self, func: _C, args: tuple[Unpack[_Ts]], kwargs: dict[_KT, _VT]\n    ) -> tuple[_C, tuple[Unpack[_Ts]], dict[_KT, _VT]]: ...\n\nif sys.version_info >= (3, 14):\n    class WorkerContext:\n        @overload\n        @classmethod\n        def prepare(\n            cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]]\n        ) -> tuple[Callable[[], Self], _ResolveTaskFunc]: ...\n        @overload\n        @classmethod\n        def prepare(\n            cls, initializer: Callable[[], object], initargs: tuple[()]\n        ) -> tuple[Callable[[], Self], _ResolveTaskFunc]: ...\n        @overload\n        def __init__(self, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]]) -> None: ...\n        @overload\n        def __init__(self, initializer: Callable[[], object], initargs: tuple[()]) -> None: ...\n        def initialize(self) -> None: ...\n        def finalize(self) -> None: ...\n        def run(self, task: _Task) -> None: ...\n\nif sys.version_info >= (3, 14):\n    class _WorkItem(Generic[_S]):\n        future: Future[Any]\n        task: _Task\n        def __init__(self, future: Future[Any], task: _Task) -> None: ...\n        def run(self, ctx: WorkerContext) -> None: ...\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n    def _worker(executor_reference: ref[Any], ctx: WorkerContext, work_queue: queue.SimpleQueue[Any]) -> None: ...\n\nelse:\n    class _WorkItem(Generic[_S]):\n        future: Future[_S]\n        fn: Callable[..., _S]\n        args: Iterable[Any]\n        kwargs: Mapping[str, Any]\n        def __init__(self, future: Future[_S], fn: Callable[..., _S], args: Iterable[Any], kwargs: Mapping[str, Any]) -> None: ...\n        def run(self) -> None: ...\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n    def _worker(\n        executor_reference: ref[Any],\n        work_queue: queue.SimpleQueue[Any],\n        initializer: Callable[[Unpack[_Ts]], object],\n        initargs: tuple[Unpack[_Ts]],\n    ) -> None: ...\n\nclass BrokenThreadPool(BrokenExecutor): ...\n\nclass ThreadPoolExecutor(Executor):\n    if sys.version_info >= (3, 14):\n        BROKEN: type[BrokenThreadPool]\n\n    _max_workers: int\n    _idle_semaphore: Semaphore\n    _threads: AbstractSet[Thread]\n    _broken: bool\n    _shutdown: bool\n    _shutdown_lock: Lock\n    _thread_name_prefix: str | None\n    if sys.version_info >= (3, 14):\n        _create_worker_context: Callable[[], WorkerContext]\n        _resolve_work_item_task: _ResolveTaskFunc\n    else:\n        _initializer: Callable[..., None] | None\n        _initargs: tuple[Any, ...]\n    _work_queue: queue.SimpleQueue[_WorkItem[Any]]\n\n    if sys.version_info >= (3, 14):\n        @overload\n        @classmethod\n        def prepare_context(\n            cls, initializer: Callable[[], object], initargs: tuple[()]\n        ) -> tuple[Callable[[], WorkerContext], _ResolveTaskFunc]: ...\n        @overload\n        @classmethod\n        def prepare_context(\n            cls, initializer: Callable[[Unpack[_Ts]], object], initargs: tuple[Unpack[_Ts]]\n        ) -> tuple[Callable[[], WorkerContext], _ResolveTaskFunc]: ...\n\n    @overload\n    def __init__(\n        self,\n        max_workers: int | None = None,\n        thread_name_prefix: str = \"\",\n        initializer: Callable[[], object] | None = None,\n        initargs: tuple[()] = (),\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        max_workers: int | None = None,\n        thread_name_prefix: str = \"\",\n        *,\n        initializer: Callable[[Unpack[_Ts]], object],\n        initargs: tuple[Unpack[_Ts]],\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        max_workers: int | None,\n        thread_name_prefix: str,\n        initializer: Callable[[Unpack[_Ts]], object],\n        initargs: tuple[Unpack[_Ts]],\n    ) -> None: ...\n    def _adjust_thread_count(self) -> None: ...\n    def _initializer_failed(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/concurrent/interpreters/__init__.pyi",
    "content": "import sys\nimport threading\nimport types\nfrom collections.abc import Callable\nfrom typing import Any, Literal, TypeVar\nfrom typing_extensions import ParamSpec, Self\n\nif sys.version_info >= (3, 13):  # needed to satisfy pyright checks for Python <3.13\n    from _interpreters import (\n        InterpreterError as InterpreterError,\n        InterpreterNotFoundError as InterpreterNotFoundError,\n        NotShareableError as NotShareableError,\n        _SharedDict,\n        _Whence,\n        is_shareable as is_shareable,\n    )\n\n    from ._queues import Queue as Queue, QueueEmpty as QueueEmpty, QueueFull as QueueFull, create as create_queue\n\n    __all__ = [\n        \"ExecutionFailed\",\n        \"Interpreter\",\n        \"InterpreterError\",\n        \"InterpreterNotFoundError\",\n        \"NotShareableError\",\n        \"Queue\",\n        \"QueueEmpty\",\n        \"QueueFull\",\n        \"create\",\n        \"create_queue\",\n        \"get_current\",\n        \"get_main\",\n        \"is_shareable\",\n        \"list_all\",\n    ]\n\n    _R = TypeVar(\"_R\")\n    _P = ParamSpec(\"_P\")\n\n    class ExecutionFailed(InterpreterError):\n        excinfo: types.SimpleNamespace\n\n        def __init__(self, excinfo: types.SimpleNamespace) -> None: ...\n\n    def create() -> Interpreter: ...\n    def list_all() -> list[Interpreter]: ...\n    def get_current() -> Interpreter: ...\n    def get_main() -> Interpreter: ...\n\n    class Interpreter:\n        def __new__(cls, id: int, /, _whence: _Whence | None = None, _ownsref: bool | None = None) -> Self: ...\n        def __reduce__(self) -> tuple[type[Self], int]: ...\n        def __hash__(self) -> int: ...\n        def __del__(self) -> None: ...\n        @property\n        def id(self) -> int: ...\n        @property\n        def whence(\n            self,\n        ) -> Literal[\"unknown\", \"runtime init\", \"legacy C-API\", \"C-API\", \"cross-interpreter C-API\", \"_interpreters module\"]: ...\n        def is_running(self) -> bool: ...\n        def close(self) -> None: ...\n        def prepare_main(\n            self, ns: _SharedDict | None = None, /, **kwargs: Any\n        ) -> None: ...  # kwargs has same value restrictions as _SharedDict\n        def exec(self, code: str | types.CodeType | Callable[[], object], /) -> None: ...\n        def call(self, callable: Callable[_P, _R], /, *args: _P.args, **kwargs: _P.kwargs) -> _R: ...\n        def call_in_thread(self, callable: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> threading.Thread: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/concurrent/interpreters/_crossinterp.pyi",
    "content": "import sys\nfrom collections.abc import Callable\nfrom typing import Final, NewType\nfrom typing_extensions import Never, Self, TypeAlias\n\nif sys.version_info >= (3, 13):  # needed to satisfy pyright checks for Python <3.13\n    from _interpqueues import _UnboundOp\n\n    class ItemInterpreterDestroyed(Exception): ...\n    # Actually a descriptor that behaves similarly to classmethod but prevents\n    # access from instances.\n    classonly = classmethod\n\n    class UnboundItem:\n        __slots__ = ()\n        def __new__(cls) -> Never: ...\n        @classonly\n        def singleton(cls, kind: str, module: str, name: str = \"UNBOUND\") -> Self: ...\n\n    # Sentinel types and alias that don't exist at runtime.\n    _UnboundErrorType = NewType(\"_UnboundErrorType\", object)\n    _UnboundRemoveType = NewType(\"_UnboundRemoveType\", object)\n    _AnyUnbound: TypeAlias = _UnboundErrorType | _UnboundRemoveType | UnboundItem\n\n    UNBOUND_ERROR: Final[_UnboundErrorType]\n    UNBOUND_REMOVE: Final[_UnboundRemoveType]\n    UNBOUND: Final[UnboundItem]  # analogous to UNBOUND_REPLACE in C\n\n    def serialize_unbound(unbound: _AnyUnbound) -> tuple[_UnboundOp]: ...\n    def resolve_unbound(flag: _UnboundOp, exctype_destroyed: Callable[[str], BaseException]) -> UnboundItem: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/concurrent/interpreters/_queues.pyi",
    "content": "import queue\nimport sys\nfrom typing import Final, SupportsIndex\nfrom typing_extensions import Self\n\nif sys.version_info >= (3, 13):  # needed to satisfy pyright checks for Python <3.13\n    from _interpqueues import QueueError as QueueError, QueueNotFoundError as QueueNotFoundError\n\n    from . import _crossinterp\n    from ._crossinterp import UNBOUND_ERROR as UNBOUND_ERROR, UNBOUND_REMOVE as UNBOUND_REMOVE, UnboundItem, _AnyUnbound\n\n    __all__ = [\n        \"UNBOUND\",\n        \"UNBOUND_ERROR\",\n        \"UNBOUND_REMOVE\",\n        \"ItemInterpreterDestroyed\",\n        \"Queue\",\n        \"QueueEmpty\",\n        \"QueueError\",\n        \"QueueFull\",\n        \"QueueNotFoundError\",\n        \"create\",\n        \"list_all\",\n    ]\n\n    class QueueEmpty(QueueError, queue.Empty): ...\n    class QueueFull(QueueError, queue.Full): ...\n    class ItemInterpreterDestroyed(QueueError, _crossinterp.ItemInterpreterDestroyed): ...\n    UNBOUND: Final[UnboundItem]\n\n    def create(maxsize: int = 0, *, unbounditems: _AnyUnbound = ...) -> Queue: ...\n    def list_all() -> list[Queue]: ...\n\n    class Queue:\n        def __new__(cls, id: int, /) -> Self: ...\n        def __del__(self) -> None: ...\n        def __hash__(self) -> int: ...\n        def __reduce__(self) -> tuple[type[Self], int]: ...\n        @property\n        def id(self) -> int: ...\n        @property\n        def unbounditems(self) -> _AnyUnbound: ...\n        @property\n        def maxsize(self) -> int: ...\n        def empty(self) -> bool: ...\n        def full(self) -> bool: ...\n        def qsize(self) -> int: ...\n        if sys.version_info >= (3, 14):\n            def put(\n                self,\n                obj: object,\n                block: bool = True,\n                timeout: SupportsIndex | None = None,\n                *,\n                unbounditems: _AnyUnbound | None = None,\n                _delay: float = 0.01,\n            ) -> None: ...\n        else:\n            def put(\n                self,\n                obj: object,\n                timeout: SupportsIndex | None = None,\n                *,\n                unbounditems: _AnyUnbound | None = None,\n                _delay: float = 0.01,\n            ) -> None: ...\n\n        def put_nowait(self, obj: object, *, unbounditems: _AnyUnbound | None = None) -> None: ...\n        if sys.version_info >= (3, 14):\n            def get(self, block: bool = True, timeout: SupportsIndex | None = None, *, _delay: float = 0.01) -> object: ...\n        else:\n            def get(self, timeout: SupportsIndex | None = None, *, _delay: float = 0.01) -> object: ...\n\n        def get_nowait(self) -> object: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/configparser.pyi",
    "content": "import sys\nfrom _typeshed import MaybeNone, StrOrBytesPath, SupportsWrite\nfrom collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping, MutableMapping, Sequence\nfrom re import Pattern\nfrom typing import Any, ClassVar, Final, Literal, TypeVar, overload, type_check_only\nfrom typing_extensions import TypeAlias, deprecated\n\nif sys.version_info >= (3, 14):\n    __all__ = (\n        \"NoSectionError\",\n        \"DuplicateOptionError\",\n        \"DuplicateSectionError\",\n        \"NoOptionError\",\n        \"InterpolationError\",\n        \"InterpolationDepthError\",\n        \"InterpolationMissingOptionError\",\n        \"InterpolationSyntaxError\",\n        \"ParsingError\",\n        \"MissingSectionHeaderError\",\n        \"MultilineContinuationError\",\n        \"UnnamedSectionDisabledError\",\n        \"InvalidWriteError\",\n        \"ConfigParser\",\n        \"RawConfigParser\",\n        \"Interpolation\",\n        \"BasicInterpolation\",\n        \"ExtendedInterpolation\",\n        \"SectionProxy\",\n        \"ConverterMapping\",\n        \"DEFAULTSECT\",\n        \"MAX_INTERPOLATION_DEPTH\",\n        \"UNNAMED_SECTION\",\n    )\nelif sys.version_info >= (3, 13):\n    __all__ = (\n        \"NoSectionError\",\n        \"DuplicateOptionError\",\n        \"DuplicateSectionError\",\n        \"NoOptionError\",\n        \"InterpolationError\",\n        \"InterpolationDepthError\",\n        \"InterpolationMissingOptionError\",\n        \"InterpolationSyntaxError\",\n        \"ParsingError\",\n        \"MissingSectionHeaderError\",\n        \"ConfigParser\",\n        \"RawConfigParser\",\n        \"Interpolation\",\n        \"BasicInterpolation\",\n        \"ExtendedInterpolation\",\n        \"SectionProxy\",\n        \"ConverterMapping\",\n        \"DEFAULTSECT\",\n        \"MAX_INTERPOLATION_DEPTH\",\n        \"UNNAMED_SECTION\",\n        \"MultilineContinuationError\",\n    )\nelif sys.version_info >= (3, 12):\n    __all__ = (\n        \"NoSectionError\",\n        \"DuplicateOptionError\",\n        \"DuplicateSectionError\",\n        \"NoOptionError\",\n        \"InterpolationError\",\n        \"InterpolationDepthError\",\n        \"InterpolationMissingOptionError\",\n        \"InterpolationSyntaxError\",\n        \"ParsingError\",\n        \"MissingSectionHeaderError\",\n        \"ConfigParser\",\n        \"RawConfigParser\",\n        \"Interpolation\",\n        \"BasicInterpolation\",\n        \"ExtendedInterpolation\",\n        \"LegacyInterpolation\",\n        \"SectionProxy\",\n        \"ConverterMapping\",\n        \"DEFAULTSECT\",\n        \"MAX_INTERPOLATION_DEPTH\",\n    )\nelse:\n    __all__ = [\n        \"NoSectionError\",\n        \"DuplicateOptionError\",\n        \"DuplicateSectionError\",\n        \"NoOptionError\",\n        \"InterpolationError\",\n        \"InterpolationDepthError\",\n        \"InterpolationMissingOptionError\",\n        \"InterpolationSyntaxError\",\n        \"ParsingError\",\n        \"MissingSectionHeaderError\",\n        \"ConfigParser\",\n        \"SafeConfigParser\",\n        \"RawConfigParser\",\n        \"Interpolation\",\n        \"BasicInterpolation\",\n        \"ExtendedInterpolation\",\n        \"LegacyInterpolation\",\n        \"SectionProxy\",\n        \"ConverterMapping\",\n        \"DEFAULTSECT\",\n        \"MAX_INTERPOLATION_DEPTH\",\n    ]\n\nif sys.version_info >= (3, 13):\n    @type_check_only\n    class _UNNAMED_SECTION: ...\n\n    UNNAMED_SECTION: _UNNAMED_SECTION\n\n    _SectionName: TypeAlias = str | _UNNAMED_SECTION\n    # A list of sections can only include an unnamed section if the parser was initialized with\n    # allow_unnamed_section=True. Any prevents users from having to use explicit\n    # type checks if allow_unnamed_section is False (the default).\n    _SectionNameList: TypeAlias = list[Any]\nelse:\n    _SectionName: TypeAlias = str\n    _SectionNameList: TypeAlias = list[str]\n\n_Section: TypeAlias = Mapping[str, str]\n_Parser: TypeAlias = MutableMapping[str, _Section]\n_ConverterCallback: TypeAlias = Callable[[str], Any]\n_ConvertersMap: TypeAlias = dict[str, _ConverterCallback]\n_T = TypeVar(\"_T\")\n\nDEFAULTSECT: Final = \"DEFAULT\"\nMAX_INTERPOLATION_DEPTH: Final = 10\n\nclass Interpolation:\n    def before_get(self, parser: _Parser, section: _SectionName, option: str, value: str, defaults: _Section) -> str: ...\n    def before_set(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ...\n    def before_read(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ...\n    def before_write(self, parser: _Parser, section: _SectionName, option: str, value: str) -> str: ...\n\nclass BasicInterpolation(Interpolation): ...\nclass ExtendedInterpolation(Interpolation): ...\n\nif sys.version_info < (3, 13):\n    @deprecated(\n        \"Deprecated since Python 3.2; removed in Python 3.13. Use `BasicInterpolation` or `ExtendedInterpolation` instead.\"\n    )\n    class LegacyInterpolation(Interpolation):\n        def before_get(self, parser: _Parser, section: _SectionName, option: str, value: str, vars: _Section) -> str: ...\n\nclass RawConfigParser(_Parser):\n    _SECT_TMPL: ClassVar[str]  # undocumented\n    _OPT_TMPL: ClassVar[str]  # undocumented\n    _OPT_NV_TMPL: ClassVar[str]  # undocumented\n\n    SECTCRE: Pattern[str]\n    OPTCRE: ClassVar[Pattern[str]]\n    OPTCRE_NV: ClassVar[Pattern[str]]  # undocumented\n    NONSPACECRE: ClassVar[Pattern[str]]  # undocumented\n\n    BOOLEAN_STATES: ClassVar[Mapping[str, bool]]  # undocumented\n    default_section: str\n    if sys.version_info >= (3, 13):\n        @overload\n        def __init__(\n            self,\n            defaults: Mapping[str, str | None] | None = None,\n            dict_type: type[Mapping[str, str]] = ...,\n            *,\n            allow_no_value: Literal[True],\n            delimiters: Sequence[str] = (\"=\", \":\"),\n            comment_prefixes: Sequence[str] = (\"#\", \";\"),\n            inline_comment_prefixes: Sequence[str] | None = None,\n            strict: bool = True,\n            empty_lines_in_values: bool = True,\n            default_section: str = \"DEFAULT\",\n            interpolation: Interpolation | None = ...,\n            converters: _ConvertersMap = ...,\n            allow_unnamed_section: bool = False,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            defaults: Mapping[str, str | None] | None,\n            dict_type: type[Mapping[str, str]],\n            allow_no_value: Literal[True],\n            *,\n            delimiters: Sequence[str] = (\"=\", \":\"),\n            comment_prefixes: Sequence[str] = (\"#\", \";\"),\n            inline_comment_prefixes: Sequence[str] | None = None,\n            strict: bool = True,\n            empty_lines_in_values: bool = True,\n            default_section: str = \"DEFAULT\",\n            interpolation: Interpolation | None = ...,\n            converters: _ConvertersMap = ...,\n            allow_unnamed_section: bool = False,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            defaults: _Section | None = None,\n            dict_type: type[Mapping[str, str]] = ...,\n            allow_no_value: bool = False,\n            *,\n            delimiters: Sequence[str] = (\"=\", \":\"),\n            comment_prefixes: Sequence[str] = (\"#\", \";\"),\n            inline_comment_prefixes: Sequence[str] | None = None,\n            strict: bool = True,\n            empty_lines_in_values: bool = True,\n            default_section: str = \"DEFAULT\",\n            interpolation: Interpolation | None = ...,\n            converters: _ConvertersMap = ...,\n            allow_unnamed_section: bool = False,\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self,\n            defaults: Mapping[str, str | None] | None = None,\n            dict_type: type[Mapping[str, str]] = ...,\n            *,\n            allow_no_value: Literal[True],\n            delimiters: Sequence[str] = (\"=\", \":\"),\n            comment_prefixes: Sequence[str] = (\"#\", \";\"),\n            inline_comment_prefixes: Sequence[str] | None = None,\n            strict: bool = True,\n            empty_lines_in_values: bool = True,\n            default_section: str = \"DEFAULT\",\n            interpolation: Interpolation | None = ...,\n            converters: _ConvertersMap = ...,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            defaults: Mapping[str, str | None] | None,\n            dict_type: type[Mapping[str, str]],\n            allow_no_value: Literal[True],\n            *,\n            delimiters: Sequence[str] = (\"=\", \":\"),\n            comment_prefixes: Sequence[str] = (\"#\", \";\"),\n            inline_comment_prefixes: Sequence[str] | None = None,\n            strict: bool = True,\n            empty_lines_in_values: bool = True,\n            default_section: str = \"DEFAULT\",\n            interpolation: Interpolation | None = ...,\n            converters: _ConvertersMap = ...,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            defaults: _Section | None = None,\n            dict_type: type[Mapping[str, str]] = ...,\n            allow_no_value: bool = False,\n            *,\n            delimiters: Sequence[str] = (\"=\", \":\"),\n            comment_prefixes: Sequence[str] = (\"#\", \";\"),\n            inline_comment_prefixes: Sequence[str] | None = None,\n            strict: bool = True,\n            empty_lines_in_values: bool = True,\n            default_section: str = \"DEFAULT\",\n            interpolation: Interpolation | None = ...,\n            converters: _ConvertersMap = ...,\n        ) -> None: ...\n\n    def __len__(self) -> int: ...\n    def __getitem__(self, key: _SectionName) -> SectionProxy: ...\n    def __setitem__(self, key: _SectionName, value: _Section) -> None: ...\n    def __delitem__(self, key: _SectionName) -> None: ...\n    def __iter__(self) -> Iterator[str]: ...\n    def __contains__(self, key: object) -> bool: ...\n    def defaults(self) -> _Section: ...\n    def sections(self) -> _SectionNameList: ...\n    def add_section(self, section: _SectionName) -> None: ...\n    def has_section(self, section: _SectionName) -> bool: ...\n    def options(self, section: _SectionName) -> list[str]: ...\n    def has_option(self, section: _SectionName, option: str) -> bool: ...\n    def read(self, filenames: StrOrBytesPath | Iterable[StrOrBytesPath], encoding: str | None = None) -> list[str]: ...\n    def read_file(self, f: Iterable[str], source: str | None = None) -> None: ...\n    def read_string(self, string: str, source: str = \"<string>\") -> None: ...\n    def read_dict(self, dictionary: Mapping[str, Mapping[str, Any]], source: str = \"<dict>\") -> None: ...\n    if sys.version_info < (3, 12):\n        @deprecated(\"Deprecated since Python 3.2; removed in Python 3.12. Use `parser.read_file()` instead.\")\n        def readfp(self, fp: Iterable[str], filename: str | None = None) -> None: ...\n    # These get* methods are partially applied (with the same names) in\n    # SectionProxy; the stubs should be kept updated together\n    @overload\n    def getint(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> int: ...\n    @overload\n    def getint(\n        self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T = ...\n    ) -> int | _T: ...\n    @overload\n    def getfloat(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> float: ...\n    @overload\n    def getfloat(\n        self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T = ...\n    ) -> float | _T: ...\n    @overload\n    def getboolean(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool: ...\n    @overload\n    def getboolean(\n        self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T = ...\n    ) -> bool | _T: ...\n    def _get_conv(\n        self,\n        section: _SectionName,\n        option: str,\n        conv: Callable[[str], _T],\n        *,\n        raw: bool = False,\n        vars: _Section | None = None,\n        fallback: _T = ...,\n    ) -> _T: ...\n    # This is incompatible with MutableMapping so we ignore the type\n    @overload  # type: ignore[override]\n    def get(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> str | MaybeNone: ...\n    @overload\n    def get(\n        self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T\n    ) -> str | _T | MaybeNone: ...\n    @overload\n    def items(self, *, raw: bool = False, vars: _Section | None = None) -> ItemsView[str, SectionProxy]: ...\n    @overload\n    def items(self, section: _SectionName, raw: bool = False, vars: _Section | None = None) -> list[tuple[str, str]]: ...\n    def set(self, section: _SectionName, option: str, value: str | None = None) -> None: ...\n    def write(self, fp: SupportsWrite[str], space_around_delimiters: bool = True) -> None: ...\n    def remove_option(self, section: _SectionName, option: str) -> bool: ...\n    def remove_section(self, section: _SectionName) -> bool: ...\n    def optionxform(self, optionstr: str) -> str: ...\n    @property\n    def converters(self) -> ConverterMapping: ...\n\nclass ConfigParser(RawConfigParser):\n    # This is incompatible with MutableMapping so we ignore the type\n    @overload  # type: ignore[override]\n    def get(self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None) -> str: ...\n    @overload\n    def get(\n        self, section: _SectionName, option: str, *, raw: bool = False, vars: _Section | None = None, fallback: _T\n    ) -> str | _T: ...\n\nif sys.version_info < (3, 12):\n    @deprecated(\"Deprecated since Python 3.2; removed in Python 3.12. Use `ConfigParser` instead.\")\n    class SafeConfigParser(ConfigParser): ...\n\nclass SectionProxy(MutableMapping[str, str]):\n    def __init__(self, parser: RawConfigParser, name: str) -> None: ...\n    def __getitem__(self, key: str) -> str: ...\n    def __setitem__(self, key: str, value: str) -> None: ...\n    def __delitem__(self, key: str) -> None: ...\n    def __contains__(self, key: object) -> bool: ...\n    def __len__(self) -> int: ...\n    def __iter__(self) -> Iterator[str]: ...\n    @property\n    def parser(self) -> RawConfigParser: ...\n    @property\n    def name(self) -> str: ...\n    # This is incompatible with MutableMapping so we ignore the type\n    @overload  # type: ignore[override]\n    def get(\n        self,\n        option: str,\n        fallback: None = None,\n        *,\n        raw: bool = False,\n        vars: _Section | None = None,\n        _impl: Any | None = None,\n        **kwargs: Any,  # passed to the underlying parser's get() method\n    ) -> str | None: ...\n    @overload\n    def get(\n        self,\n        option: str,\n        fallback: _T,\n        *,\n        raw: bool = False,\n        vars: _Section | None = None,\n        _impl: Any | None = None,\n        **kwargs: Any,  # passed to the underlying parser's get() method\n    ) -> str | _T: ...\n    # These are partially-applied version of the methods with the same names in\n    # RawConfigParser; the stubs should be kept updated together\n    @overload\n    def getint(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> int | None: ...\n    @overload\n    def getint(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> int | _T: ...\n    @overload\n    def getfloat(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> float | None: ...\n    @overload\n    def getfloat(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> float | _T: ...\n    @overload\n    def getboolean(self, option: str, *, raw: bool = False, vars: _Section | None = None) -> bool | None: ...\n    @overload\n    def getboolean(self, option: str, fallback: _T = ..., *, raw: bool = False, vars: _Section | None = None) -> bool | _T: ...\n    # SectionProxy can have arbitrary attributes when custom converters are used\n    def __getattr__(self, key: str) -> Callable[..., Any]: ...\n\nclass ConverterMapping(MutableMapping[str, _ConverterCallback | None]):\n    GETTERCRE: ClassVar[Pattern[Any]]\n    def __init__(self, parser: RawConfigParser) -> None: ...\n    def __getitem__(self, key: str) -> _ConverterCallback: ...\n    def __setitem__(self, key: str, value: _ConverterCallback | None) -> None: ...\n    def __delitem__(self, key: str) -> None: ...\n    def __iter__(self) -> Iterator[str]: ...\n    def __len__(self) -> int: ...\n\nclass Error(Exception):\n    message: str\n    def __init__(self, msg: str = \"\") -> None: ...\n\nclass NoSectionError(Error):\n    section: _SectionName\n    def __init__(self, section: _SectionName) -> None: ...\n\nclass DuplicateSectionError(Error):\n    section: _SectionName\n    source: str | None\n    lineno: int | None\n    def __init__(self, section: _SectionName, source: str | None = None, lineno: int | None = None) -> None: ...\n\nclass DuplicateOptionError(Error):\n    section: _SectionName\n    option: str\n    source: str | None\n    lineno: int | None\n    def __init__(self, section: _SectionName, option: str, source: str | None = None, lineno: int | None = None) -> None: ...\n\nclass NoOptionError(Error):\n    section: _SectionName\n    option: str\n    def __init__(self, option: str, section: _SectionName) -> None: ...\n\nclass InterpolationError(Error):\n    section: _SectionName\n    option: str\n    def __init__(self, option: str, section: _SectionName, msg: str) -> None: ...\n\nclass InterpolationDepthError(InterpolationError):\n    def __init__(self, option: str, section: _SectionName, rawval: object) -> None: ...\n\nclass InterpolationMissingOptionError(InterpolationError):\n    reference: str\n    def __init__(self, option: str, section: _SectionName, rawval: object, reference: str) -> None: ...\n\nclass InterpolationSyntaxError(InterpolationError): ...\n\nclass ParsingError(Error):\n    source: str\n    errors: list[tuple[int, str]]\n    if sys.version_info >= (3, 13):\n        def __init__(self, source: str, *args: object) -> None: ...\n        def combine(self, others: Iterable[ParsingError]) -> ParsingError: ...\n    elif sys.version_info >= (3, 12):\n        def __init__(self, source: str) -> None: ...\n    else:\n        @overload\n        def __init__(self, source: str) -> None: ...\n        @overload\n        @deprecated(\"The `filename` parameter removed in Python 3.12. Use `source` instead.\")\n        def __init__(self, source: None, filename: str | None) -> None: ...\n        @overload\n        @deprecated(\"The `filename` parameter removed in Python 3.12. Use `source` instead.\")\n        def __init__(self, source: None = None, *, filename: str | None) -> None: ...\n\n    def append(self, lineno: int, line: str) -> None: ...\n\n    if sys.version_info < (3, 12):\n        @property\n        @deprecated(\"Deprecated since Python 3.2; removed in Python 3.12. Use `source` instead.\")\n        def filename(self) -> str: ...\n        @filename.setter\n        @deprecated(\"Deprecated since Python 3.2; removed in Python 3.12. Use `source` instead.\")\n        def filename(self, value: str) -> None: ...\n\nclass MissingSectionHeaderError(ParsingError):\n    lineno: int\n    line: str\n    def __init__(self, filename: str, lineno: int, line: str) -> None: ...\n\nif sys.version_info >= (3, 13):\n    class MultilineContinuationError(ParsingError):\n        lineno: int\n        line: str\n        def __init__(self, filename: str, lineno: int, line: str) -> None: ...\n\nif sys.version_info >= (3, 14):\n    class UnnamedSectionDisabledError(Error):\n        msg: Final = \"Support for UNNAMED_SECTION is disabled.\"\n        def __init__(self) -> None: ...\n\n    class InvalidWriteError(Error): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/contextlib.pyi",
    "content": "import abc\nimport sys\nfrom _typeshed import FileDescriptorOrPath, Unused\nfrom abc import ABC, abstractmethod\nfrom collections.abc import AsyncGenerator, AsyncIterator, Awaitable, Callable, Generator, Iterator\nfrom types import TracebackType\nfrom typing import Any, Generic, Protocol, TypeVar, overload, runtime_checkable, type_check_only\nfrom typing_extensions import ParamSpec, Self, TypeAlias\n\n__all__ = [\n    \"contextmanager\",\n    \"closing\",\n    \"AbstractContextManager\",\n    \"ContextDecorator\",\n    \"ExitStack\",\n    \"redirect_stdout\",\n    \"redirect_stderr\",\n    \"suppress\",\n    \"AbstractAsyncContextManager\",\n    \"AsyncExitStack\",\n    \"asynccontextmanager\",\n    \"nullcontext\",\n]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"aclosing\"]\n\nif sys.version_info >= (3, 11):\n    __all__ += [\"chdir\"]\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_ExitT_co = TypeVar(\"_ExitT_co\", covariant=True, bound=bool | None, default=bool | None)\n_F = TypeVar(\"_F\", bound=Callable[..., Any])\n_G_co = TypeVar(\"_G_co\", bound=Generator[Any, Any, Any] | AsyncGenerator[Any, Any], covariant=True)\n_P = ParamSpec(\"_P\")\n\n_SendT_contra = TypeVar(\"_SendT_contra\", contravariant=True, default=None)\n_ReturnT_co = TypeVar(\"_ReturnT_co\", covariant=True, default=None)\n\n_ExitFunc: TypeAlias = Callable[[type[BaseException] | None, BaseException | None, TracebackType | None], bool | None]\n_CM_EF = TypeVar(\"_CM_EF\", bound=AbstractContextManager[Any, Any] | _ExitFunc)\n\n# mypy and pyright object to this being both ABC and Protocol.\n# At runtime it inherits from ABC and is not a Protocol, but it is on the\n# allowlist for use as a Protocol.\n@runtime_checkable\nclass AbstractContextManager(ABC, Protocol[_T_co, _ExitT_co]):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    __slots__ = ()\n    def __enter__(self) -> _T_co: ...\n    @abstractmethod\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /\n    ) -> _ExitT_co: ...\n\n# mypy and pyright object to this being both ABC and Protocol.\n# At runtime it inherits from ABC and is not a Protocol, but it is on the\n# allowlist for use as a Protocol.\n@runtime_checkable\nclass AbstractAsyncContextManager(ABC, Protocol[_T_co, _ExitT_co]):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    __slots__ = ()\n    async def __aenter__(self) -> _T_co: ...\n    @abstractmethod\n    async def __aexit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /\n    ) -> _ExitT_co: ...\n\nclass ContextDecorator:\n    def _recreate_cm(self) -> Self: ...\n    def __call__(self, func: _F) -> _F: ...\n\nclass _GeneratorContextManagerBase(Generic[_G_co]):\n    # Ideally this would use ParamSpec, but that requires (*args, **kwargs), which this isn't. see #6676\n    def __init__(self, func: Callable[..., _G_co], args: tuple[Any, ...], kwds: dict[str, Any]) -> None: ...\n    gen: _G_co\n    func: Callable[..., _G_co]\n    args: tuple[Any, ...]\n    kwds: dict[str, Any]\n\nclass _GeneratorContextManager(\n    _GeneratorContextManagerBase[Generator[_T_co, _SendT_contra, _ReturnT_co]],\n    AbstractContextManager[_T_co, bool | None],\n    ContextDecorator,\n):\n    def __exit__(\n        self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n    ) -> bool | None: ...\n\ndef contextmanager(func: Callable[_P, Iterator[_T_co]]) -> Callable[_P, _GeneratorContextManager[_T_co]]: ...\n\nif sys.version_info >= (3, 10):\n    _AF = TypeVar(\"_AF\", bound=Callable[..., Awaitable[Any]])\n\n    class AsyncContextDecorator:\n        def _recreate_cm(self) -> Self: ...\n        def __call__(self, func: _AF) -> _AF: ...\n\n    class _AsyncGeneratorContextManager(\n        _GeneratorContextManagerBase[AsyncGenerator[_T_co, _SendT_contra]],\n        AbstractAsyncContextManager[_T_co, bool | None],\n        AsyncContextDecorator,\n    ):\n        async def __aexit__(\n            self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n        ) -> bool | None: ...\n\nelse:\n    class _AsyncGeneratorContextManager(\n        _GeneratorContextManagerBase[AsyncGenerator[_T_co, _SendT_contra]], AbstractAsyncContextManager[_T_co, bool | None]\n    ):\n        async def __aexit__(\n            self, typ: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n        ) -> bool | None: ...\n\ndef asynccontextmanager(func: Callable[_P, AsyncIterator[_T_co]]) -> Callable[_P, _AsyncGeneratorContextManager[_T_co]]: ...\n@type_check_only\nclass _SupportsClose(Protocol):\n    def close(self) -> object: ...\n\n_SupportsCloseT = TypeVar(\"_SupportsCloseT\", bound=_SupportsClose)\n\nclass closing(AbstractContextManager[_SupportsCloseT, None]):\n    def __init__(self, thing: _SupportsCloseT) -> None: ...\n    def __exit__(self, *exc_info: Unused) -> None: ...\n\nif sys.version_info >= (3, 10):\n    @type_check_only\n    class _SupportsAclose(Protocol):\n        def aclose(self) -> Awaitable[object]: ...\n\n    _SupportsAcloseT = TypeVar(\"_SupportsAcloseT\", bound=_SupportsAclose)\n\n    class aclosing(AbstractAsyncContextManager[_SupportsAcloseT, None]):\n        def __init__(self, thing: _SupportsAcloseT) -> None: ...\n        async def __aexit__(self, *exc_info: Unused) -> None: ...\n\nclass suppress(AbstractContextManager[None, bool]):\n    def __init__(self, *exceptions: type[BaseException]) -> None: ...\n    def __exit__(\n        self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None\n    ) -> bool: ...\n\n# This is trying to describe what is needed for (most?) uses\n# of `redirect_stdout` and `redirect_stderr`.\n# https://github.com/python/typeshed/issues/14903\n@type_check_only\nclass _SupportsRedirect(Protocol):\n    def write(self, s: str, /) -> int: ...\n    def flush(self) -> None: ...\n\n_SupportsRedirectT = TypeVar(\"_SupportsRedirectT\", bound=_SupportsRedirect | None)\n\nclass _RedirectStream(AbstractContextManager[_SupportsRedirectT, None]):\n    def __init__(self, new_target: _SupportsRedirectT) -> None: ...\n    def __exit__(\n        self, exctype: type[BaseException] | None, excinst: BaseException | None, exctb: TracebackType | None\n    ) -> None: ...\n\nclass redirect_stdout(_RedirectStream[_SupportsRedirectT]): ...\nclass redirect_stderr(_RedirectStream[_SupportsRedirectT]): ...\n\nclass _BaseExitStack(Generic[_ExitT_co]):\n    def enter_context(self, cm: AbstractContextManager[_T, _ExitT_co]) -> _T: ...\n    def push(self, exit: _CM_EF) -> _CM_EF: ...\n    def callback(self, callback: Callable[_P, _T], /, *args: _P.args, **kwds: _P.kwargs) -> Callable[_P, _T]: ...\n    def pop_all(self) -> Self: ...\n\n# In reality this is a subclass of `AbstractContextManager`;\n# see #7961 for why we don't do that in the stub\nclass ExitStack(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta):\n    def close(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /\n    ) -> _ExitT_co: ...\n\n_ExitCoroFunc: TypeAlias = Callable[\n    [type[BaseException] | None, BaseException | None, TracebackType | None], Awaitable[bool | None]\n]\n_ACM_EF = TypeVar(\"_ACM_EF\", bound=AbstractAsyncContextManager[Any, Any] | _ExitCoroFunc)\n\n# In reality this is a subclass of `AbstractAsyncContextManager`;\n# see #7961 for why we don't do that in the stub\nclass AsyncExitStack(_BaseExitStack[_ExitT_co], metaclass=abc.ABCMeta):\n    async def enter_async_context(self, cm: AbstractAsyncContextManager[_T, _ExitT_co]) -> _T: ...\n    def push_async_exit(self, exit: _ACM_EF) -> _ACM_EF: ...\n    def push_async_callback(\n        self, callback: Callable[_P, Awaitable[_T]], /, *args: _P.args, **kwds: _P.kwargs\n    ) -> Callable[_P, Awaitable[_T]]: ...\n    async def aclose(self) -> None: ...\n    async def __aenter__(self) -> Self: ...\n    async def __aexit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /\n    ) -> _ExitT_co: ...\n\nif sys.version_info >= (3, 10):\n    class nullcontext(AbstractContextManager[_T, None], AbstractAsyncContextManager[_T, None]):\n        enter_result: _T\n        @overload\n        def __init__(self: nullcontext[None], enter_result: None = None) -> None: ...\n        @overload\n        def __init__(self: nullcontext[_T], enter_result: _T) -> None: ...  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        def __enter__(self) -> _T: ...\n        def __exit__(self, *exctype: Unused) -> None: ...\n        async def __aenter__(self) -> _T: ...\n        async def __aexit__(self, *exctype: Unused) -> None: ...\n\nelse:\n    class nullcontext(AbstractContextManager[_T, None]):\n        enter_result: _T\n        @overload\n        def __init__(self: nullcontext[None], enter_result: None = None) -> None: ...\n        @overload\n        def __init__(self: nullcontext[_T], enter_result: _T) -> None: ...  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        def __enter__(self) -> _T: ...\n        def __exit__(self, *exctype: Unused) -> None: ...\n\nif sys.version_info >= (3, 11):\n    _T_fd_or_any_path = TypeVar(\"_T_fd_or_any_path\", bound=FileDescriptorOrPath)\n\n    class chdir(AbstractContextManager[None, None], Generic[_T_fd_or_any_path]):\n        path: _T_fd_or_any_path\n        def __init__(self, path: _T_fd_or_any_path) -> None: ...\n        def __enter__(self) -> None: ...\n        def __exit__(self, *excinfo: Unused) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/contextvars.pyi",
    "content": "from _contextvars import Context as Context, ContextVar as ContextVar, Token as Token, copy_context as copy_context\n\n__all__ = (\"Context\", \"ContextVar\", \"Token\", \"copy_context\")\n"
  },
  {
    "path": "mypy/typeshed/stdlib/copy.pyi",
    "content": "import sys\nfrom typing import Any, Protocol, TypeVar, type_check_only\n\n__all__ = [\"Error\", \"copy\", \"deepcopy\"]\n\n_T = TypeVar(\"_T\")\n_RT_co = TypeVar(\"_RT_co\", covariant=True)\n\n@type_check_only\nclass _SupportsReplace(Protocol[_RT_co]):\n    # In reality doesn't support args, but there's no great way to express this.\n    def __replace__(self, /, *_: Any, **changes: Any) -> _RT_co: ...\n\n# None in CPython but non-None in Jython\nPyStringMap: Any\n\n# Note: memo and _nil are internal kwargs.\ndef deepcopy(x: _T, memo: dict[int, Any] | None = None, _nil: Any = []) -> _T: ...\ndef copy(x: _T) -> _T: ...\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"replace\"]\n    # The types accepted by `**changes` match those of `obj.__replace__`.\n    def replace(obj: _SupportsReplace[_RT_co], /, **changes: Any) -> _RT_co: ...\n\nclass Error(Exception): ...\n\nerror = Error\n"
  },
  {
    "path": "mypy/typeshed/stdlib/copyreg.pyi",
    "content": "from collections.abc import Callable, Hashable\nfrom typing import Any, SupportsInt, TypeVar\nfrom typing_extensions import TypeAlias\n\n_T = TypeVar(\"_T\")\n_Reduce: TypeAlias = tuple[Callable[..., _T], tuple[Any, ...]] | tuple[Callable[..., _T], tuple[Any, ...], Any | None]\n\n__all__ = [\"pickle\", \"constructor\", \"add_extension\", \"remove_extension\", \"clear_extension_cache\"]\n\ndef pickle(\n    ob_type: type[_T],\n    pickle_function: Callable[[_T], str | _Reduce[_T]],\n    constructor_ob: Callable[[_Reduce[_T]], _T] | None = None,\n) -> None: ...\ndef constructor(object: Callable[[_Reduce[_T]], _T]) -> None: ...\ndef add_extension(module: Hashable, name: Hashable, code: SupportsInt) -> None: ...\ndef remove_extension(module: Hashable, name: Hashable, code: int) -> None: ...\ndef clear_extension_cache() -> None: ...\n\n_DispatchTableType: TypeAlias = dict[type, Callable[[Any], str | _Reduce[Any]]]  # imported by multiprocessing.reduction\ndispatch_table: _DispatchTableType  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/crypt.pyi",
    "content": "import sys\nfrom typing import Final, NamedTuple, type_check_only\nfrom typing_extensions import disjoint_base\n\nif sys.platform != \"win32\":\n    @type_check_only\n    class _MethodBase(NamedTuple):\n        name: str\n        ident: str | None\n        salt_chars: int\n        total_size: int\n\n    if sys.version_info >= (3, 12):\n        class _Method(_MethodBase): ...\n    else:\n        @disjoint_base\n        class _Method(_MethodBase): ...\n\n    METHOD_CRYPT: Final[_Method]\n    METHOD_MD5: Final[_Method]\n    METHOD_SHA256: Final[_Method]\n    METHOD_SHA512: Final[_Method]\n    METHOD_BLOWFISH: Final[_Method]\n    methods: list[_Method]\n    def mksalt(method: _Method | None = None, *, rounds: int | None = None) -> str: ...\n    def crypt(word: str, salt: str | _Method | None = None) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/csv.pyi",
    "content": "import sys\nfrom _csv import (\n    QUOTE_ALL as QUOTE_ALL,\n    QUOTE_MINIMAL as QUOTE_MINIMAL,\n    QUOTE_NONE as QUOTE_NONE,\n    QUOTE_NONNUMERIC as QUOTE_NONNUMERIC,\n    Error as Error,\n    __version__ as __version__,\n    _DialectLike,\n    _QuotingType,\n    field_size_limit as field_size_limit,\n    get_dialect as get_dialect,\n    list_dialects as list_dialects,\n    reader as reader,\n    register_dialect as register_dialect,\n    unregister_dialect as unregister_dialect,\n    writer as writer,\n)\n\nif sys.version_info >= (3, 12):\n    from _csv import QUOTE_NOTNULL as QUOTE_NOTNULL, QUOTE_STRINGS as QUOTE_STRINGS\nif sys.version_info >= (3, 10):\n    from _csv import Reader, Writer\nelse:\n    from _csv import _reader as Reader, _writer as Writer\n\nfrom _typeshed import SupportsWrite\nfrom collections.abc import Collection, Iterable, Iterator, Mapping, Sequence\nfrom types import GenericAlias\nfrom typing import Any, Generic, Literal, TypeVar, overload\nfrom typing_extensions import Self\n\n__all__ = [\n    \"QUOTE_MINIMAL\",\n    \"QUOTE_ALL\",\n    \"QUOTE_NONNUMERIC\",\n    \"QUOTE_NONE\",\n    \"Error\",\n    \"Dialect\",\n    \"excel\",\n    \"excel_tab\",\n    \"field_size_limit\",\n    \"reader\",\n    \"writer\",\n    \"register_dialect\",\n    \"get_dialect\",\n    \"list_dialects\",\n    \"Sniffer\",\n    \"unregister_dialect\",\n    \"DictReader\",\n    \"DictWriter\",\n    \"unix_dialect\",\n]\nif sys.version_info >= (3, 12):\n    __all__ += [\"QUOTE_STRINGS\", \"QUOTE_NOTNULL\"]\nif sys.version_info < (3, 13):\n    __all__ += [\"__doc__\", \"__version__\"]\n\n_T = TypeVar(\"_T\")\n\nclass Dialect:\n    delimiter: str\n    quotechar: str | None\n    escapechar: str | None\n    doublequote: bool\n    skipinitialspace: bool\n    lineterminator: str\n    quoting: _QuotingType\n    strict: bool\n    def __init__(self) -> None: ...\n\nclass excel(Dialect): ...\nclass excel_tab(excel): ...\nclass unix_dialect(Dialect): ...\n\nclass DictReader(Iterator[dict[_T | Any, str | Any]], Generic[_T]):\n    fieldnames: Sequence[_T] | None\n    restkey: _T | None\n    restval: str | Any | None\n    reader: Reader\n    dialect: _DialectLike\n    line_num: int\n    @overload\n    def __init__(\n        self,\n        f: Iterable[str],\n        fieldnames: Sequence[_T],\n        restkey: _T | None = None,\n        restval: str | Any | None = None,\n        dialect: _DialectLike = \"excel\",\n        *,\n        delimiter: str = \",\",\n        quotechar: str | None = '\"',\n        escapechar: str | None = None,\n        doublequote: bool = True,\n        skipinitialspace: bool = False,\n        lineterminator: str = \"\\r\\n\",\n        quoting: _QuotingType = 0,\n        strict: bool = False,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self: DictReader[str],\n        f: Iterable[str],\n        fieldnames: Sequence[str] | None = None,\n        restkey: str | None = None,\n        restval: str | None = None,\n        dialect: _DialectLike = \"excel\",\n        *,\n        delimiter: str = \",\",\n        quotechar: str | None = '\"',\n        escapechar: str | None = None,\n        doublequote: bool = True,\n        skipinitialspace: bool = False,\n        lineterminator: str = \"\\r\\n\",\n        quoting: _QuotingType = 0,\n        strict: bool = False,\n    ) -> None: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> dict[_T | Any, str | Any]: ...\n    if sys.version_info >= (3, 12):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass DictWriter(Generic[_T]):\n    fieldnames: Collection[_T]\n    restval: Any | None\n    extrasaction: Literal[\"raise\", \"ignore\"]\n    writer: Writer\n    def __init__(\n        self,\n        f: SupportsWrite[str],\n        fieldnames: Collection[_T],\n        restval: Any | None = \"\",\n        extrasaction: Literal[\"raise\", \"ignore\"] = \"raise\",\n        dialect: _DialectLike = \"excel\",\n        *,\n        delimiter: str = \",\",\n        quotechar: str | None = '\"',\n        escapechar: str | None = None,\n        doublequote: bool = True,\n        skipinitialspace: bool = False,\n        lineterminator: str = \"\\r\\n\",\n        quoting: _QuotingType = 0,\n        strict: bool = False,\n    ) -> None: ...\n    def writeheader(self) -> Any: ...\n    def writerow(self, rowdict: Mapping[_T, Any]) -> Any: ...\n    def writerows(self, rowdicts: Iterable[Mapping[_T, Any]]) -> None: ...\n    if sys.version_info >= (3, 12):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass Sniffer:\n    preferred: list[str]\n    def sniff(self, sample: str, delimiters: str | None = None) -> type[Dialect]: ...\n    def has_header(self, sample: str) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ctypes/__init__.pyi",
    "content": "import sys\nfrom _ctypes import (\n    RTLD_GLOBAL as RTLD_GLOBAL,\n    RTLD_LOCAL as RTLD_LOCAL,\n    Array as Array,\n    CFuncPtr as _CFuncPtr,\n    Structure as Structure,\n    Union as Union,\n    _CanCastTo as _CanCastTo,\n    _CArgObject as _CArgObject,\n    _CData as _CData,\n    _CDataType as _CDataType,\n    _CField as _CField,\n    _CTypeBaseType,\n    _Pointer as _Pointer,\n    _PointerLike as _PointerLike,\n    _SimpleCData as _SimpleCData,\n    addressof as addressof,\n    alignment as alignment,\n    byref as byref,\n    get_errno as get_errno,\n    resize as resize,\n    set_errno as set_errno,\n    sizeof as sizeof,\n)\nfrom _typeshed import StrPath, SupportsBool, SupportsLen\nfrom ctypes._endian import BigEndianStructure as BigEndianStructure, LittleEndianStructure as LittleEndianStructure\nfrom types import GenericAlias\nfrom typing import Any, ClassVar, Final, Generic, Literal, TypeVar, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, deprecated\n\nif sys.platform == \"win32\":\n    from _ctypes import FormatError as FormatError, get_last_error as get_last_error, set_last_error as set_last_error\n\n    if sys.version_info >= (3, 14):\n        from _ctypes import COMError as COMError, CopyComPointer as CopyComPointer\n\nif sys.version_info >= (3, 11):\n    from ctypes._endian import BigEndianUnion as BigEndianUnion, LittleEndianUnion as LittleEndianUnion\n\n_CT = TypeVar(\"_CT\", bound=_CData)\n_T = TypeVar(\"_T\", default=Any)\n_DLLT = TypeVar(\"_DLLT\", bound=CDLL)\n\nif sys.version_info >= (3, 14):\n    @overload\n    @deprecated(\"ctypes.POINTER with string\")\n    def POINTER(cls: str) -> type[Any]: ...\n    @overload\n    def POINTER(cls: None) -> type[c_void_p]: ...\n    @overload\n    def POINTER(cls: type[_CT]) -> type[_Pointer[_CT]]: ...\n    def pointer(obj: _CT) -> _Pointer[_CT]: ...\n\nelse:\n    from _ctypes import POINTER as POINTER, pointer as pointer\n\nif sys.version_info >= (3, 14):\n    CField = _CField\n\nDEFAULT_MODE: Final[int]\n\nclass ArgumentError(Exception): ...\n\n# defined within CDLL.__init__\n# Runtime name is ctypes.CDLL.__init__.<locals>._FuncPtr\n@type_check_only\nclass _CDLLFuncPointer(_CFuncPtr):\n    _flags_: ClassVar[int]\n    _restype_: ClassVar[type[_CDataType]]\n\n# Not a real class; _CDLLFuncPointer with a __name__ set on it.\n@type_check_only\nclass _NamedFuncPointer(_CDLLFuncPointer):\n    __name__: str\n\nif sys.version_info >= (3, 12):\n    _NameTypes: TypeAlias = StrPath | None\nelse:\n    _NameTypes: TypeAlias = str | None\n\nclass CDLL:\n    _func_flags_: ClassVar[int]\n    _func_restype_: ClassVar[type[_CDataType]]\n    _name: str\n    _handle: int\n    _FuncPtr: type[_CDLLFuncPointer]\n    def __init__(\n        self,\n        name: _NameTypes,\n        mode: int = ...,\n        handle: int | None = None,\n        use_errno: bool = False,\n        use_last_error: bool = False,\n        winmode: int | None = None,\n    ) -> None: ...\n    def __getattr__(self, name: str) -> _NamedFuncPointer: ...\n    def __getitem__(self, name_or_ordinal: str) -> _NamedFuncPointer: ...\n\nif sys.platform == \"win32\":\n    class OleDLL(CDLL): ...\n    class WinDLL(CDLL): ...\n\nclass PyDLL(CDLL): ...\n\nclass LibraryLoader(Generic[_DLLT]):\n    def __init__(self, dlltype: type[_DLLT]) -> None: ...\n    def __getattr__(self, name: str) -> _DLLT: ...\n    def __getitem__(self, name: str) -> _DLLT: ...\n    def LoadLibrary(self, name: str) -> _DLLT: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\ncdll: LibraryLoader[CDLL]\nif sys.platform == \"win32\":\n    windll: LibraryLoader[WinDLL]\n    oledll: LibraryLoader[OleDLL]\npydll: LibraryLoader[PyDLL]\npythonapi: PyDLL\n\n# Class definition within CFUNCTYPE / WINFUNCTYPE / PYFUNCTYPE\n# Names at runtime are\n# ctypes.CFUNCTYPE.<locals>.CFunctionType\n# ctypes.WINFUNCTYPE.<locals>.WinFunctionType\n# ctypes.PYFUNCTYPE.<locals>.CFunctionType\n@type_check_only\nclass _CFunctionType(_CFuncPtr):\n    _argtypes_: ClassVar[list[type[_CData | _CDataType]]]\n    _restype_: ClassVar[type[_CData | _CDataType] | None]\n    _flags_: ClassVar[int]\n\n# Alias for either function pointer type\n_FuncPointer: TypeAlias = _CDLLFuncPointer | _CFunctionType  # noqa: Y047  # not used here\n\ndef CFUNCTYPE(\n    restype: type[_CData | _CDataType] | None,\n    *argtypes: type[_CData | _CDataType],\n    use_errno: bool = False,\n    use_last_error: bool = False,\n) -> type[_CFunctionType]: ...\n\nif sys.platform == \"win32\":\n    def WINFUNCTYPE(\n        restype: type[_CData | _CDataType] | None,\n        *argtypes: type[_CData | _CDataType],\n        use_errno: bool = False,\n        use_last_error: bool = False,\n    ) -> type[_CFunctionType]: ...\n\ndef PYFUNCTYPE(restype: type[_CData | _CDataType] | None, *argtypes: type[_CData | _CDataType]) -> type[_CFunctionType]: ...\n\n# Any type that can be implicitly converted to c_void_p when passed as a C function argument.\n# (bytes is not included here, see below.)\n_CVoidPLike: TypeAlias = _PointerLike | Array[Any] | _CArgObject | int\n# Same as above, but including types known to be read-only (i. e. bytes).\n# This distinction is not strictly necessary (ctypes doesn't differentiate between const\n# and non-const pointers), but it catches errors like memmove(b'foo', buf, 4)\n# when memmove(buf, b'foo', 4) was intended.\n_CVoidConstPLike: TypeAlias = _CVoidPLike | bytes\n\n_CastT = TypeVar(\"_CastT\", bound=_CanCastTo)\n\ndef cast(obj: _CData | _CDataType | _CArgObject | int, typ: type[_CastT]) -> _CastT: ...\ndef create_string_buffer(init: int | bytes, size: int | None = None) -> Array[c_char]: ...\n\nc_buffer = create_string_buffer\n\ndef create_unicode_buffer(init: int | str, size: int | None = None) -> Array[c_wchar]: ...\n\nif sys.version_info >= (3, 13):\n    @deprecated(\"Deprecated since Python 3.13; will be removed in Python 3.15.\")\n    def SetPointerType(pointer: type[_Pointer[Any]], cls: _CTypeBaseType) -> None: ...\n    @deprecated(\"Soft deprecated since Python 3.13. Use multiplication instead.\")\n    def ARRAY(typ: _CT, len: int) -> Array[_CT]: ...\n\nelse:\n    def SetPointerType(pointer: type[_Pointer[Any]], cls: _CTypeBaseType) -> None: ...\n    def ARRAY(typ: _CT, len: int) -> Array[_CT]: ...\n\nif sys.platform == \"win32\":\n    def DllCanUnloadNow() -> int: ...\n    def DllGetClassObject(rclsid: Any, riid: Any, ppv: Any) -> int: ...  # TODO: not documented\n\n    # Actually just an instance of _NamedFuncPointer (aka _CDLLFuncPointer),\n    # but we want to set a more specific __call__\n    @type_check_only\n    class _GetLastErrorFunctionType(_NamedFuncPointer):\n        def __call__(self) -> int: ...\n\n    GetLastError: _GetLastErrorFunctionType\n\n# Actually just an instance of _CFunctionType, but we want to set a more\n# specific __call__.\n@type_check_only\nclass _MemmoveFunctionType(_CFunctionType):\n    def __call__(self, dst: _CVoidPLike, src: _CVoidConstPLike, count: int) -> int: ...\n\nmemmove: _MemmoveFunctionType\n\n# Actually just an instance of _CFunctionType, but we want to set a more\n# specific __call__.\n@type_check_only\nclass _MemsetFunctionType(_CFunctionType):\n    def __call__(self, dst: _CVoidPLike, c: int, count: int) -> int: ...\n\nmemset: _MemsetFunctionType\n\ndef string_at(ptr: _CVoidConstPLike, size: int = -1) -> bytes: ...\n\nif sys.platform == \"win32\":\n    def WinError(code: int | None = None, descr: str | None = None) -> OSError: ...\n\ndef wstring_at(ptr: _CVoidConstPLike, size: int = -1) -> str: ...\n\nif sys.version_info >= (3, 14):\n    def memoryview_at(ptr: _CVoidConstPLike, size: int, readonly: bool = False) -> memoryview: ...\n\nclass py_object(_CanCastTo, _SimpleCData[_T]):\n    _type_: ClassVar[Literal[\"O\"]]\n    if sys.version_info >= (3, 14):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass c_bool(_SimpleCData[bool]):\n    _type_: ClassVar[Literal[\"?\"]]\n    def __init__(self, value: SupportsBool | SupportsLen | None = ...) -> None: ...\n\nclass c_byte(_SimpleCData[int]):\n    _type_: ClassVar[Literal[\"b\"]]\n\nclass c_ubyte(_SimpleCData[int]):\n    _type_: ClassVar[Literal[\"B\"]]\n\nclass c_short(_SimpleCData[int]):\n    _type_: ClassVar[Literal[\"h\"]]\n\nclass c_ushort(_SimpleCData[int]):\n    _type_: ClassVar[Literal[\"H\"]]\n\nclass c_long(_SimpleCData[int]):\n    _type_: ClassVar[Literal[\"l\"]]\n\nclass c_ulong(_SimpleCData[int]):\n    _type_: ClassVar[Literal[\"L\"]]\n\nclass c_int(_SimpleCData[int]):  # can be an alias for c_long\n    _type_: ClassVar[Literal[\"i\", \"l\"]]\n\nclass c_uint(_SimpleCData[int]):  # can be an alias for c_ulong\n    _type_: ClassVar[Literal[\"I\", \"L\"]]\n\nclass c_longlong(_SimpleCData[int]):  # can be an alias for c_long\n    _type_: ClassVar[Literal[\"q\", \"l\"]]\n\nclass c_ulonglong(_SimpleCData[int]):  # can be an alias for c_ulong\n    _type_: ClassVar[Literal[\"Q\", \"L\"]]\n\nc_int8 = c_byte\nc_uint8 = c_ubyte\n\nclass c_int16(_SimpleCData[int]):  # can be an alias for c_short or c_int\n    _type_: ClassVar[Literal[\"h\", \"i\"]]\n\nclass c_uint16(_SimpleCData[int]):  # can be an alias for c_ushort or c_uint\n    _type_: ClassVar[Literal[\"H\", \"I\"]]\n\nclass c_int32(_SimpleCData[int]):  # can be an alias for c_int or c_long\n    _type_: ClassVar[Literal[\"i\", \"l\"]]\n\nclass c_uint32(_SimpleCData[int]):  # can be an alias for c_uint or c_ulong\n    _type_: ClassVar[Literal[\"I\", \"L\"]]\n\nclass c_int64(_SimpleCData[int]):  # can be an alias for c_long or c_longlong\n    _type_: ClassVar[Literal[\"l\", \"q\"]]\n\nclass c_uint64(_SimpleCData[int]):  # can be an alias for c_ulong or c_ulonglong\n    _type_: ClassVar[Literal[\"L\", \"Q\"]]\n\nclass c_ssize_t(_SimpleCData[int]):  # alias for c_int, c_long, or c_longlong\n    _type_: ClassVar[Literal[\"i\", \"l\", \"q\"]]\n\nclass c_size_t(_SimpleCData[int]):  # alias for c_uint, c_ulong, or c_ulonglong\n    _type_: ClassVar[Literal[\"I\", \"L\", \"Q\"]]\n\nclass c_float(_SimpleCData[float]):\n    _type_: ClassVar[Literal[\"f\"]]\n\nclass c_double(_SimpleCData[float]):\n    _type_: ClassVar[Literal[\"d\"]]\n\nclass c_longdouble(_SimpleCData[float]):  # can be an alias for c_double\n    _type_: ClassVar[Literal[\"d\", \"g\"]]\n\nif sys.version_info >= (3, 14) and sys.platform != \"win32\":\n    class c_double_complex(_SimpleCData[complex]):\n        _type_: ClassVar[Literal[\"D\"]]\n\n    class c_float_complex(_SimpleCData[complex]):\n        _type_: ClassVar[Literal[\"F\"]]\n\n    class c_longdouble_complex(_SimpleCData[complex]):\n        _type_: ClassVar[Literal[\"G\"]]\n\nclass c_char(_SimpleCData[bytes]):\n    _type_: ClassVar[Literal[\"c\"]]\n    def __init__(self, value: int | bytes | bytearray = ...) -> None: ...\n\nclass c_char_p(_PointerLike, _SimpleCData[bytes | None]):\n    _type_: ClassVar[Literal[\"z\"]]\n    def __init__(self, value: int | bytes | None = ...) -> None: ...\n    @classmethod\n    def from_param(cls, value: Any, /) -> Self | _CArgObject: ...\n\nclass c_void_p(_PointerLike, _SimpleCData[int | None]):\n    _type_: ClassVar[Literal[\"P\"]]\n    @classmethod\n    def from_param(cls, value: Any, /) -> Self | _CArgObject: ...\n\nc_voidp = c_void_p  # backwards compatibility (to a bug)\n\nclass c_wchar(_SimpleCData[str]):\n    _type_: ClassVar[Literal[\"u\"]]\n\nclass c_wchar_p(_PointerLike, _SimpleCData[str | None]):\n    _type_: ClassVar[Literal[\"Z\"]]\n    def __init__(self, value: int | str | None = ...) -> None: ...\n    @classmethod\n    def from_param(cls, value: Any, /) -> Self | _CArgObject: ...\n\nif sys.platform == \"win32\":\n    class HRESULT(_SimpleCData[int]):  # TODO: undocumented\n        _type_: ClassVar[Literal[\"l\"]]\n\nif sys.version_info >= (3, 12):\n    # At runtime, this is an alias for either c_int32 or c_int64,\n    # which are themselves an alias for one of c_int, c_long, or c_longlong\n    # This covers all our bases.\n    c_time_t: type[c_int32 | c_int64 | c_int | c_long | c_longlong]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ctypes/_endian.pyi",
    "content": "import sys\nfrom ctypes import Structure, Union\n\n# At runtime, the native endianness is an alias for Structure,\n# while the other is a subclass with a metaclass added in.\nclass BigEndianStructure(Structure):\n    __slots__ = ()\n\nclass LittleEndianStructure(Structure): ...\n\n# Same thing for these: one is an alias of Union at runtime\nif sys.version_info >= (3, 11):\n    class BigEndianUnion(Union):\n        __slots__ = ()\n\n    class LittleEndianUnion(Union): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ctypes/macholib/__init__.pyi",
    "content": "from typing import Final\n\n__version__: Final[str]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ctypes/macholib/dyld.pyi",
    "content": "from collections.abc import Mapping\nfrom ctypes.macholib.dylib import dylib_info as dylib_info\nfrom ctypes.macholib.framework import framework_info as framework_info\n\n__all__ = [\"dyld_find\", \"framework_find\", \"framework_info\", \"dylib_info\"]\n\ndef dyld_find(name: str, executable_path: str | None = None, env: Mapping[str, str] | None = None) -> str: ...\ndef framework_find(fn: str, executable_path: str | None = None, env: Mapping[str, str] | None = None) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ctypes/macholib/dylib.pyi",
    "content": "from typing import TypedDict, type_check_only\n\n__all__ = [\"dylib_info\"]\n\n# Actual result is produced by re.match.groupdict()\n@type_check_only\nclass _DylibInfo(TypedDict):\n    location: str\n    name: str\n    shortname: str\n    version: str | None\n    suffix: str | None\n\ndef dylib_info(filename: str) -> _DylibInfo | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ctypes/macholib/framework.pyi",
    "content": "from typing import TypedDict, type_check_only\n\n__all__ = [\"framework_info\"]\n\n# Actual result is produced by re.match.groupdict()\n@type_check_only\nclass _FrameworkInfo(TypedDict):\n    location: str\n    name: str\n    shortname: str\n    version: str | None\n    suffix: str | None\n\ndef framework_info(filename: str) -> _FrameworkInfo | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ctypes/util.pyi",
    "content": "import sys\n\ndef find_library(name: str) -> str | None: ...\n\nif sys.platform == \"win32\":\n    def find_msvcrt() -> str | None: ...\n\nif sys.version_info >= (3, 14):\n    def dllist() -> list[str]: ...\n\ndef test() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ctypes/wintypes.pyi",
    "content": "import sys\nfrom _ctypes import _CArgObject, _CField\nfrom ctypes import (\n    Array,\n    Structure,\n    _Pointer,\n    _SimpleCData,\n    c_char,\n    c_char_p,\n    c_double,\n    c_float,\n    c_int,\n    c_long,\n    c_longlong,\n    c_short,\n    c_uint,\n    c_ulong,\n    c_ulonglong,\n    c_ushort,\n    c_void_p,\n    c_wchar,\n    c_wchar_p,\n)\nfrom typing import Any, Final, TypeVar\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 12):\n    from ctypes import c_ubyte\n\n    BYTE = c_ubyte\nelse:\n    from ctypes import c_byte\n\n    BYTE = c_byte\n\nWORD = c_ushort\nDWORD = c_ulong\nCHAR = c_char\nWCHAR = c_wchar\nUINT = c_uint\nINT = c_int\nDOUBLE = c_double\nFLOAT = c_float\nBOOLEAN = BYTE\nBOOL = c_long\n\nclass VARIANT_BOOL(_SimpleCData[bool]): ...\n\nULONG = c_ulong\nLONG = c_long\nUSHORT = c_ushort\nSHORT = c_short\nLARGE_INTEGER = c_longlong\n_LARGE_INTEGER = c_longlong\nULARGE_INTEGER = c_ulonglong\n_ULARGE_INTEGER = c_ulonglong\n\nOLESTR = c_wchar_p\nLPOLESTR = c_wchar_p\nLPCOLESTR = c_wchar_p\nLPWSTR = c_wchar_p\nLPCWSTR = c_wchar_p\nLPSTR = c_char_p\nLPCSTR = c_char_p\nLPVOID = c_void_p\nLPCVOID = c_void_p\n\n# These two types are pointer-sized unsigned and signed ints, respectively.\n# At runtime, they are either c_[u]long or c_[u]longlong, depending on the host's pointer size\n# (they are not really separate classes).\nclass WPARAM(_SimpleCData[int]): ...\nclass LPARAM(_SimpleCData[int]): ...\n\nATOM = WORD\nLANGID = WORD\nCOLORREF = DWORD\nLGRPID = DWORD\nLCTYPE = DWORD\nLCID = DWORD\n\nHANDLE = c_void_p\nHACCEL = HANDLE\nHBITMAP = HANDLE\nHBRUSH = HANDLE\nHCOLORSPACE = HANDLE\nif sys.version_info >= (3, 14):\n    HCONV = HANDLE\n    HCONVLIST = HANDLE\n    HCURSOR = HANDLE\n    HDDEDATA = HANDLE\n    HDROP = HANDLE\n    HFILE = INT\n    HRESULT = LONG\n    HSZ = HANDLE\nHDC = HANDLE\nHDESK = HANDLE\nHDWP = HANDLE\nHENHMETAFILE = HANDLE\nHFONT = HANDLE\nHGDIOBJ = HANDLE\nHGLOBAL = HANDLE\nHHOOK = HANDLE\nHICON = HANDLE\nHINSTANCE = HANDLE\nHKEY = HANDLE\nHKL = HANDLE\nHLOCAL = HANDLE\nHMENU = HANDLE\nHMETAFILE = HANDLE\nHMODULE = HANDLE\nHMONITOR = HANDLE\nHPALETTE = HANDLE\nHPEN = HANDLE\nHRGN = HANDLE\nHRSRC = HANDLE\nHSTR = HANDLE\nHTASK = HANDLE\nHWINSTA = HANDLE\nHWND = HANDLE\nSC_HANDLE = HANDLE\nSERVICE_STATUS_HANDLE = HANDLE\n\n_CIntLikeT = TypeVar(\"_CIntLikeT\", bound=_SimpleCData[int])\n_CIntLikeField: TypeAlias = _CField[_CIntLikeT, int, _CIntLikeT | int]\n\nclass RECT(Structure):\n    left: _CIntLikeField[LONG]\n    top: _CIntLikeField[LONG]\n    right: _CIntLikeField[LONG]\n    bottom: _CIntLikeField[LONG]\n\nRECTL = RECT\n_RECTL = RECT\ntagRECT = RECT\n\nclass _SMALL_RECT(Structure):\n    Left: _CIntLikeField[SHORT]\n    Top: _CIntLikeField[SHORT]\n    Right: _CIntLikeField[SHORT]\n    Bottom: _CIntLikeField[SHORT]\n\nSMALL_RECT = _SMALL_RECT\n\nclass _COORD(Structure):\n    X: _CIntLikeField[SHORT]\n    Y: _CIntLikeField[SHORT]\n\nclass POINT(Structure):\n    x: _CIntLikeField[LONG]\n    y: _CIntLikeField[LONG]\n\nPOINTL = POINT\n_POINTL = POINT\ntagPOINT = POINT\n\nclass SIZE(Structure):\n    cx: _CIntLikeField[LONG]\n    cy: _CIntLikeField[LONG]\n\nSIZEL = SIZE\ntagSIZE = SIZE\n\ndef RGB(red: int, green: int, blue: int) -> int: ...\n\nclass FILETIME(Structure):\n    dwLowDateTime: _CIntLikeField[DWORD]\n    dwHighDateTime: _CIntLikeField[DWORD]\n\n_FILETIME = FILETIME\n\nclass MSG(Structure):\n    hWnd: _CField[HWND, int | None, HWND | int | None]\n    message: _CIntLikeField[UINT]\n    wParam: _CIntLikeField[WPARAM]\n    lParam: _CIntLikeField[LPARAM]\n    time: _CIntLikeField[DWORD]\n    pt: _CField[POINT, POINT, POINT]\n\ntagMSG = MSG\nMAX_PATH: Final = 260\n\nclass WIN32_FIND_DATAA(Structure):\n    dwFileAttributes: _CIntLikeField[DWORD]\n    ftCreationTime: _CField[FILETIME, FILETIME, FILETIME]\n    ftLastAccessTime: _CField[FILETIME, FILETIME, FILETIME]\n    ftLastWriteTime: _CField[FILETIME, FILETIME, FILETIME]\n    nFileSizeHigh: _CIntLikeField[DWORD]\n    nFileSizeLow: _CIntLikeField[DWORD]\n    dwReserved0: _CIntLikeField[DWORD]\n    dwReserved1: _CIntLikeField[DWORD]\n    cFileName: _CField[Array[CHAR], bytes, bytes]\n    cAlternateFileName: _CField[Array[CHAR], bytes, bytes]\n\nclass WIN32_FIND_DATAW(Structure):\n    dwFileAttributes: _CIntLikeField[DWORD]\n    ftCreationTime: _CField[FILETIME, FILETIME, FILETIME]\n    ftLastAccessTime: _CField[FILETIME, FILETIME, FILETIME]\n    ftLastWriteTime: _CField[FILETIME, FILETIME, FILETIME]\n    nFileSizeHigh: _CIntLikeField[DWORD]\n    nFileSizeLow: _CIntLikeField[DWORD]\n    dwReserved0: _CIntLikeField[DWORD]\n    dwReserved1: _CIntLikeField[DWORD]\n    cFileName: _CField[Array[WCHAR], str, str]\n    cAlternateFileName: _CField[Array[WCHAR], str, str]\n\n# These are all defined with the POINTER() function, which keeps a cache and will\n# return a previously created class if it can. The self-reported __name__\n# of these classes is f\"LP_{typ.__name__}\", where typ is the original class\n# passed in to the POINTER() function.\n\n# LP_c_short\nclass PSHORT(_Pointer[SHORT]): ...\n\n# LP_c_ushort\nclass PUSHORT(_Pointer[USHORT]): ...\n\nPWORD = PUSHORT\nLPWORD = PUSHORT\n\n# LP_c_long\nclass PLONG(_Pointer[LONG]): ...\n\nLPLONG = PLONG\nPBOOL = PLONG\nLPBOOL = PLONG\n\n# LP_c_ulong\nclass PULONG(_Pointer[ULONG]): ...\n\nPDWORD = PULONG\nLPDWORD = PDWORD\nLPCOLORREF = PDWORD\nPLCID = PDWORD\n\n# LP_c_int (or LP_c_long if int and long have the same size)\nclass PINT(_Pointer[INT]): ...\n\nLPINT = PINT\n\n# LP_c_uint (or LP_c_ulong if int and long have the same size)\nclass PUINT(_Pointer[UINT]): ...\n\nLPUINT = PUINT\n\n# LP_c_float\nclass PFLOAT(_Pointer[FLOAT]): ...\n\n# LP_c_longlong (or LP_c_long if long and long long have the same size)\nclass PLARGE_INTEGER(_Pointer[LARGE_INTEGER]): ...\n\n# LP_c_ulonglong (or LP_c_ulong if long and long long have the same size)\nclass PULARGE_INTEGER(_Pointer[ULARGE_INTEGER]): ...\n\n# LP_c_byte types\nclass PBYTE(_Pointer[BYTE]): ...\n\nLPBYTE = PBYTE\nPBOOLEAN = PBYTE\n\n# LP_c_char\nclass PCHAR(_Pointer[CHAR]):\n    # this is inherited from ctypes.c_char_p, kind of.\n    @classmethod\n    def from_param(cls, value: Any, /) -> Self | _CArgObject: ...\n\n# LP_c_wchar\nclass PWCHAR(_Pointer[WCHAR]):\n    # inherited from ctypes.c_wchar_p, kind of\n    @classmethod\n    def from_param(cls, value: Any, /) -> Self | _CArgObject: ...\n\n# LP_c_void_p\nclass PHANDLE(_Pointer[HANDLE]): ...\n\nLPHANDLE = PHANDLE\nPHKEY = PHANDLE\nLPHKL = PHANDLE\nLPSC_HANDLE = PHANDLE\n\n# LP_FILETIME\nclass PFILETIME(_Pointer[FILETIME]): ...\n\nLPFILETIME = PFILETIME\n\n# LP_MSG\nclass PMSG(_Pointer[MSG]): ...\n\nLPMSG = PMSG\n\n# LP_POINT\nclass PPOINT(_Pointer[POINT]): ...\n\nLPPOINT = PPOINT\nPPOINTL = PPOINT\n\n# LP_RECT\nclass PRECT(_Pointer[RECT]): ...\n\nLPRECT = PRECT\nPRECTL = PRECT\nLPRECTL = PRECT\n\n# LP_SIZE\nclass PSIZE(_Pointer[SIZE]): ...\n\nLPSIZE = PSIZE\nPSIZEL = PSIZE\nLPSIZEL = PSIZE\n\n# LP__SMALL_RECT\nclass PSMALL_RECT(_Pointer[SMALL_RECT]): ...\n\n# LP_WIN32_FIND_DATAA\nclass PWIN32_FIND_DATAA(_Pointer[WIN32_FIND_DATAA]): ...\n\nLPWIN32_FIND_DATAA = PWIN32_FIND_DATAA\n\n# LP_WIN32_FIND_DATAW\nclass PWIN32_FIND_DATAW(_Pointer[WIN32_FIND_DATAW]): ...\n\nLPWIN32_FIND_DATAW = PWIN32_FIND_DATAW\n"
  },
  {
    "path": "mypy/typeshed/stdlib/curses/__init__.pyi",
    "content": "import sys\nfrom _curses import *\nfrom _curses import window as window\nfrom _typeshed import structseq\nfrom collections.abc import Callable\nfrom typing import Final, TypeVar, final, type_check_only\nfrom typing_extensions import Concatenate, ParamSpec\n\n# NOTE: The _curses module is ordinarily only available on Unix, but the\n# windows-curses package makes it available on Windows as well with the same\n# contents.\n\n_T = TypeVar(\"_T\")\n_P = ParamSpec(\"_P\")\n\n# available after calling `curses.initscr()`\n# not `Final` as it can change during the terminal resize:\nLINES: int\nCOLS: int\n\n# available after calling `curses.start_color()`\nCOLORS: Final[int]\nCOLOR_PAIRS: Final[int]\n\ndef wrapper(func: Callable[Concatenate[window, _P], _T], /, *arg: _P.args, **kwds: _P.kwargs) -> _T: ...\n\n# At runtime this class is unexposed and calls itself curses.ncurses_version.\n# That name would conflict with the actual curses.ncurses_version, which is\n# an instance of this class.\n@final\n@type_check_only\nclass _ncurses_version(structseq[int], tuple[int, int, int]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"major\", \"minor\", \"patch\")\n\n    @property\n    def major(self) -> int: ...\n    @property\n    def minor(self) -> int: ...\n    @property\n    def patch(self) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/curses/ascii.pyi",
    "content": "from typing import Final, TypeVar\n\n_CharT = TypeVar(\"_CharT\", str, int)\n\nNUL: Final = 0x00\nSOH: Final = 0x01\nSTX: Final = 0x02\nETX: Final = 0x03\nEOT: Final = 0x04\nENQ: Final = 0x05\nACK: Final = 0x06\nBEL: Final = 0x07\nBS: Final = 0x08\nTAB: Final = 0x09\nHT: Final = 0x09\nLF: Final = 0x0A\nNL: Final = 0x0A\nVT: Final = 0x0B\nFF: Final = 0x0C\nCR: Final = 0x0D\nSO: Final = 0x0E\nSI: Final = 0x0F\nDLE: Final = 0x10\nDC1: Final = 0x11\nDC2: Final = 0x12\nDC3: Final = 0x13\nDC4: Final = 0x14\nNAK: Final = 0x15\nSYN: Final = 0x16\nETB: Final = 0x17\nCAN: Final = 0x18\nEM: Final = 0x19\nSUB: Final = 0x1A\nESC: Final = 0x1B\nFS: Final = 0x1C\nGS: Final = 0x1D\nRS: Final = 0x1E\nUS: Final = 0x1F\nSP: Final = 0x20\nDEL: Final = 0x7F\n\ncontrolnames: Final[list[int]]\n\ndef isalnum(c: str | int) -> bool: ...\ndef isalpha(c: str | int) -> bool: ...\ndef isascii(c: str | int) -> bool: ...\ndef isblank(c: str | int) -> bool: ...\ndef iscntrl(c: str | int) -> bool: ...\ndef isdigit(c: str | int) -> bool: ...\ndef isgraph(c: str | int) -> bool: ...\ndef islower(c: str | int) -> bool: ...\ndef isprint(c: str | int) -> bool: ...\ndef ispunct(c: str | int) -> bool: ...\ndef isspace(c: str | int) -> bool: ...\ndef isupper(c: str | int) -> bool: ...\ndef isxdigit(c: str | int) -> bool: ...\ndef isctrl(c: str | int) -> bool: ...\ndef ismeta(c: str | int) -> bool: ...\ndef ascii(c: _CharT) -> _CharT: ...\ndef ctrl(c: _CharT) -> _CharT: ...\ndef alt(c: _CharT) -> _CharT: ...\ndef unctrl(c: str | int) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/curses/has_key.pyi",
    "content": "def has_key(ch: int | str) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/curses/panel.pyi",
    "content": "from _curses_panel import *\n"
  },
  {
    "path": "mypy/typeshed/stdlib/curses/textpad.pyi",
    "content": "from _curses import window\nfrom collections.abc import Callable\n\ndef rectangle(win: window, uly: int, ulx: int, lry: int, lrx: int) -> None: ...\n\nclass Textbox:\n    stripspaces: bool\n    def __init__(self, win: window, insert_mode: bool = False) -> None: ...\n    def edit(self, validate: Callable[[int], int] | None = None) -> str: ...\n    def do_command(self, ch: str | int) -> None: ...\n    def gather(self) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/dataclasses.pyi",
    "content": "import enum\nimport sys\nimport types\nfrom _typeshed import DataclassInstance\nfrom builtins import type as Type  # alias to avoid name clashes with fields named \"type\"\nfrom collections.abc import Callable, Iterable, Mapping\nfrom types import GenericAlias\nfrom typing import Any, Final, Generic, Literal, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import Never, TypeIs\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n\n__all__ = [\n    \"dataclass\",\n    \"field\",\n    \"Field\",\n    \"FrozenInstanceError\",\n    \"InitVar\",\n    \"MISSING\",\n    \"fields\",\n    \"asdict\",\n    \"astuple\",\n    \"make_dataclass\",\n    \"replace\",\n    \"is_dataclass\",\n]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"KW_ONLY\"]\n\n_DataclassT = TypeVar(\"_DataclassT\", bound=DataclassInstance)\n\n@type_check_only\nclass _DataclassFactory(Protocol):\n    def __call__(\n        self,\n        cls: type[_T],\n        /,\n        *,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n        match_args: bool = True,\n        kw_only: bool = False,\n        slots: bool = False,\n        weakref_slot: bool = False,\n    ) -> type[_T]: ...\n\n# define _MISSING_TYPE as an enum within the type stubs,\n# even though that is not really its type at runtime\n# this allows us to use Literal[_MISSING_TYPE.MISSING]\n# for background, see:\n#   https://github.com/python/typeshed/pull/5900#issuecomment-895513797\nclass _MISSING_TYPE(enum.Enum):\n    MISSING = enum.auto()\n\nMISSING: Final = _MISSING_TYPE.MISSING\n\nif sys.version_info >= (3, 10):\n    class KW_ONLY: ...\n\n@overload\ndef asdict(obj: DataclassInstance) -> dict[str, Any]: ...\n@overload\ndef asdict(obj: DataclassInstance, *, dict_factory: Callable[[list[tuple[str, Any]]], _T]) -> _T: ...\n@overload\ndef astuple(obj: DataclassInstance) -> tuple[Any, ...]: ...\n@overload\ndef astuple(obj: DataclassInstance, *, tuple_factory: Callable[[list[Any]], _T]) -> _T: ...\n\nif sys.version_info >= (3, 11):\n    @overload\n    def dataclass(\n        cls: type[_T],\n        /,\n        *,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n        match_args: bool = True,\n        kw_only: bool = False,\n        slots: bool = False,\n        weakref_slot: bool = False,\n    ) -> type[_T]: ...\n    @overload\n    def dataclass(\n        cls: None = None,\n        /,\n        *,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n        match_args: bool = True,\n        kw_only: bool = False,\n        slots: bool = False,\n        weakref_slot: bool = False,\n    ) -> Callable[[type[_T]], type[_T]]: ...\n\nelif sys.version_info >= (3, 10):\n    @overload\n    def dataclass(\n        cls: type[_T],\n        /,\n        *,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n        match_args: bool = True,\n        kw_only: bool = False,\n        slots: bool = False,\n    ) -> type[_T]: ...\n    @overload\n    def dataclass(\n        cls: None = None,\n        /,\n        *,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n        match_args: bool = True,\n        kw_only: bool = False,\n        slots: bool = False,\n    ) -> Callable[[type[_T]], type[_T]]: ...\n\nelse:\n    @overload\n    def dataclass(\n        cls: type[_T],\n        /,\n        *,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n    ) -> type[_T]: ...\n    @overload\n    def dataclass(\n        cls: None = None,\n        /,\n        *,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n    ) -> Callable[[type[_T]], type[_T]]: ...\n\n# See https://github.com/python/mypy/issues/10750\n@type_check_only\nclass _DefaultFactory(Protocol[_T_co]):\n    def __call__(self) -> _T_co: ...\n\nclass Field(Generic[_T]):\n    if sys.version_info >= (3, 14):\n        __slots__ = (\n            \"name\",\n            \"type\",\n            \"default\",\n            \"default_factory\",\n            \"repr\",\n            \"hash\",\n            \"init\",\n            \"compare\",\n            \"metadata\",\n            \"kw_only\",\n            \"doc\",\n            \"_field_type\",\n        )\n    elif sys.version_info >= (3, 10):\n        __slots__ = (\n            \"name\",\n            \"type\",\n            \"default\",\n            \"default_factory\",\n            \"repr\",\n            \"hash\",\n            \"init\",\n            \"compare\",\n            \"metadata\",\n            \"kw_only\",\n            \"_field_type\",\n        )\n    else:\n        __slots__ = (\"name\", \"type\", \"default\", \"default_factory\", \"repr\", \"hash\", \"init\", \"compare\", \"metadata\", \"_field_type\")\n    name: str\n    type: Type[_T] | str | Any\n    default: _T | Literal[_MISSING_TYPE.MISSING]\n    default_factory: _DefaultFactory[_T] | Literal[_MISSING_TYPE.MISSING]\n    repr: bool\n    hash: bool | None\n    init: bool\n    compare: bool\n    metadata: types.MappingProxyType[Any, Any]\n\n    if sys.version_info >= (3, 14):\n        doc: str | None\n\n    if sys.version_info >= (3, 10):\n        kw_only: bool | Literal[_MISSING_TYPE.MISSING]\n\n    if sys.version_info >= (3, 14):\n        def __init__(\n            self,\n            default: _T,\n            default_factory: Callable[[], _T],\n            init: bool,\n            repr: bool,\n            hash: bool | None,\n            compare: bool,\n            metadata: Mapping[Any, Any],\n            kw_only: bool,\n            doc: str | None,\n        ) -> None: ...\n    elif sys.version_info >= (3, 10):\n        def __init__(\n            self,\n            default: _T,\n            default_factory: Callable[[], _T],\n            init: bool,\n            repr: bool,\n            hash: bool | None,\n            compare: bool,\n            metadata: Mapping[Any, Any],\n            kw_only: bool,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            default: _T,\n            default_factory: Callable[[], _T],\n            init: bool,\n            repr: bool,\n            hash: bool | None,\n            compare: bool,\n            metadata: Mapping[Any, Any],\n        ) -> None: ...\n\n    def __set_name__(self, owner: Type[Any], name: str) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n# NOTE: Actual return type is 'Field[_T]', but we want to help type checkers\n# to understand the magic that happens at runtime.\nif sys.version_info >= (3, 14):\n    @overload  # `default` and `default_factory` are optional and mutually exclusive.\n    def field(\n        *,\n        default: _T,\n        default_factory: Literal[_MISSING_TYPE.MISSING] = ...,\n        init: bool = True,\n        repr: bool = True,\n        hash: bool | None = None,\n        compare: bool = True,\n        metadata: Mapping[Any, Any] | None = None,\n        kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ...,\n        doc: str | None = None,\n    ) -> _T: ...\n    @overload\n    def field(\n        *,\n        default: Literal[_MISSING_TYPE.MISSING] = ...,\n        default_factory: Callable[[], _T],\n        init: bool = True,\n        repr: bool = True,\n        hash: bool | None = None,\n        compare: bool = True,\n        metadata: Mapping[Any, Any] | None = None,\n        kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ...,\n        doc: str | None = None,\n    ) -> _T: ...\n    @overload\n    def field(\n        *,\n        default: Literal[_MISSING_TYPE.MISSING] = ...,\n        default_factory: Literal[_MISSING_TYPE.MISSING] = ...,\n        init: bool = True,\n        repr: bool = True,\n        hash: bool | None = None,\n        compare: bool = True,\n        metadata: Mapping[Any, Any] | None = None,\n        kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ...,\n        doc: str | None = None,\n    ) -> Any: ...\n\nelif sys.version_info >= (3, 10):\n    @overload  # `default` and `default_factory` are optional and mutually exclusive.\n    def field(\n        *,\n        default: _T,\n        default_factory: Literal[_MISSING_TYPE.MISSING] = ...,\n        init: bool = True,\n        repr: bool = True,\n        hash: bool | None = None,\n        compare: bool = True,\n        metadata: Mapping[Any, Any] | None = None,\n        kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ...,\n    ) -> _T: ...\n    @overload\n    def field(\n        *,\n        default: Literal[_MISSING_TYPE.MISSING] = ...,\n        default_factory: Callable[[], _T],\n        init: bool = True,\n        repr: bool = True,\n        hash: bool | None = None,\n        compare: bool = True,\n        metadata: Mapping[Any, Any] | None = None,\n        kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ...,\n    ) -> _T: ...\n    @overload\n    def field(\n        *,\n        default: Literal[_MISSING_TYPE.MISSING] = ...,\n        default_factory: Literal[_MISSING_TYPE.MISSING] = ...,\n        init: bool = True,\n        repr: bool = True,\n        hash: bool | None = None,\n        compare: bool = True,\n        metadata: Mapping[Any, Any] | None = None,\n        kw_only: bool | Literal[_MISSING_TYPE.MISSING] = ...,\n    ) -> Any: ...\n\nelse:\n    @overload  # `default` and `default_factory` are optional and mutually exclusive.\n    def field(\n        *,\n        default: _T,\n        default_factory: Literal[_MISSING_TYPE.MISSING] = ...,\n        init: bool = True,\n        repr: bool = True,\n        hash: bool | None = None,\n        compare: bool = True,\n        metadata: Mapping[Any, Any] | None = None,\n    ) -> _T: ...\n    @overload\n    def field(\n        *,\n        default: Literal[_MISSING_TYPE.MISSING] = ...,\n        default_factory: Callable[[], _T],\n        init: bool = True,\n        repr: bool = True,\n        hash: bool | None = None,\n        compare: bool = True,\n        metadata: Mapping[Any, Any] | None = None,\n    ) -> _T: ...\n    @overload\n    def field(\n        *,\n        default: Literal[_MISSING_TYPE.MISSING] = ...,\n        default_factory: Literal[_MISSING_TYPE.MISSING] = ...,\n        init: bool = True,\n        repr: bool = True,\n        hash: bool | None = None,\n        compare: bool = True,\n        metadata: Mapping[Any, Any] | None = None,\n    ) -> Any: ...\n\ndef fields(class_or_instance: DataclassInstance | type[DataclassInstance]) -> tuple[Field[Any], ...]: ...\n\n# HACK: `obj: Never` typing matches if object argument is using `Any` type.\n@overload\ndef is_dataclass(obj: Never) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ...  # type: ignore[narrowed-type-not-subtype]  # pyright: ignore[reportGeneralTypeIssues]\n@overload\ndef is_dataclass(obj: type) -> TypeIs[type[DataclassInstance]]: ...\n@overload\ndef is_dataclass(obj: object) -> TypeIs[DataclassInstance | type[DataclassInstance]]: ...\n\nclass FrozenInstanceError(AttributeError): ...\n\nclass InitVar(Generic[_T]):\n    __slots__ = (\"type\",)\n    type: Type[_T]\n    def __init__(self, type: Type[_T]) -> None: ...\n    @overload\n    def __class_getitem__(cls, type: Type[_T]) -> InitVar[_T]: ...  # pyright: ignore[reportInvalidTypeForm]\n    @overload\n    def __class_getitem__(cls, type: Any) -> InitVar[Any]: ...  # pyright: ignore[reportInvalidTypeForm]\n\nif sys.version_info >= (3, 14):\n    def make_dataclass(\n        cls_name: str,\n        fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]],\n        *,\n        bases: tuple[type, ...] = (),\n        namespace: dict[str, Any] | None = None,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n        match_args: bool = True,\n        kw_only: bool = False,\n        slots: bool = False,\n        weakref_slot: bool = False,\n        module: str | None = None,\n        decorator: _DataclassFactory = ...,\n    ) -> type: ...\n\nelif sys.version_info >= (3, 12):\n    def make_dataclass(\n        cls_name: str,\n        fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]],\n        *,\n        bases: tuple[type, ...] = (),\n        namespace: dict[str, Any] | None = None,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n        match_args: bool = True,\n        kw_only: bool = False,\n        slots: bool = False,\n        weakref_slot: bool = False,\n        module: str | None = None,\n    ) -> type: ...\n\nelif sys.version_info >= (3, 11):\n    def make_dataclass(\n        cls_name: str,\n        fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]],\n        *,\n        bases: tuple[type, ...] = (),\n        namespace: dict[str, Any] | None = None,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n        match_args: bool = True,\n        kw_only: bool = False,\n        slots: bool = False,\n        weakref_slot: bool = False,\n    ) -> type: ...\n\nelif sys.version_info >= (3, 10):\n    def make_dataclass(\n        cls_name: str,\n        fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]],\n        *,\n        bases: tuple[type, ...] = (),\n        namespace: dict[str, Any] | None = None,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n        match_args: bool = True,\n        kw_only: bool = False,\n        slots: bool = False,\n    ) -> type: ...\n\nelse:\n    def make_dataclass(\n        cls_name: str,\n        fields: Iterable[str | tuple[str, Any] | tuple[str, Any, Any]],\n        *,\n        bases: tuple[type, ...] = (),\n        namespace: dict[str, Any] | None = None,\n        init: bool = True,\n        repr: bool = True,\n        eq: bool = True,\n        order: bool = False,\n        unsafe_hash: bool = False,\n        frozen: bool = False,\n    ) -> type: ...\n\ndef replace(obj: _DataclassT, /, **changes: Any) -> _DataclassT: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/datetime.pyi",
    "content": "import sys\nfrom abc import abstractmethod\nfrom time import struct_time\nfrom typing import ClassVar, Final, NoReturn, SupportsIndex, final, overload, type_check_only\nfrom typing_extensions import CapsuleType, Self, TypeAlias, deprecated, disjoint_base\n\nif sys.version_info >= (3, 11):\n    __all__ = (\"date\", \"datetime\", \"time\", \"timedelta\", \"timezone\", \"tzinfo\", \"MINYEAR\", \"MAXYEAR\", \"UTC\")\nelse:\n    __all__ = (\"date\", \"datetime\", \"time\", \"timedelta\", \"timezone\", \"tzinfo\", \"MINYEAR\", \"MAXYEAR\")\n\nMINYEAR: Final = 1\nMAXYEAR: Final = 9999\n\nclass tzinfo:\n    @abstractmethod\n    def tzname(self, dt: datetime | None, /) -> str | None: ...\n    @abstractmethod\n    def utcoffset(self, dt: datetime | None, /) -> timedelta | None: ...\n    @abstractmethod\n    def dst(self, dt: datetime | None, /) -> timedelta | None: ...\n    def fromutc(self, dt: datetime, /) -> datetime: ...\n\n# Alias required to avoid name conflicts with date(time).tzinfo.\n_TzInfo: TypeAlias = tzinfo\n\n@final\nclass timezone(tzinfo):\n    utc: ClassVar[timezone]\n    min: ClassVar[timezone]\n    max: ClassVar[timezone]\n    def __new__(cls, offset: timedelta, name: str = ...) -> Self: ...\n    def tzname(self, dt: datetime | None, /) -> str: ...\n    def utcoffset(self, dt: datetime | None, /) -> timedelta: ...\n    def dst(self, dt: datetime | None, /) -> None: ...\n    def __hash__(self) -> int: ...\n    def __eq__(self, value: object, /) -> bool: ...\n\nif sys.version_info >= (3, 11):\n    UTC: timezone\n\n# This class calls itself datetime.IsoCalendarDate. It's neither\n# NamedTuple nor structseq.\n@final\n@type_check_only\nclass _IsoCalendarDate(tuple[int, int, int]):\n    @property\n    def year(self) -> int: ...\n    @property\n    def week(self) -> int: ...\n    @property\n    def weekday(self) -> int: ...\n\n@disjoint_base\nclass date:\n    min: ClassVar[date]\n    max: ClassVar[date]\n    resolution: ClassVar[timedelta]\n    def __new__(cls, year: SupportsIndex, month: SupportsIndex, day: SupportsIndex) -> Self: ...\n    @classmethod\n    def fromtimestamp(cls, timestamp: float, /) -> Self: ...\n    @classmethod\n    def today(cls) -> Self: ...\n    @classmethod\n    def fromordinal(cls, n: int, /) -> Self: ...\n    @classmethod\n    def fromisoformat(cls, date_string: str, /) -> Self: ...\n    @classmethod\n    def fromisocalendar(cls, year: int, week: int, day: int) -> Self: ...\n    @property\n    def year(self) -> int: ...\n    @property\n    def month(self) -> int: ...\n    @property\n    def day(self) -> int: ...\n    def ctime(self) -> str: ...\n\n    if sys.version_info >= (3, 14):\n        @classmethod\n        def strptime(cls, date_string: str, format: str, /) -> Self: ...\n\n    # On <3.12, the name of the parameter in the pure-Python implementation\n    # didn't match the name in the C implementation,\n    # meaning it is only *safe* to pass it as a keyword argument on 3.12+\n    if sys.version_info >= (3, 12):\n        def strftime(self, format: str) -> str: ...\n    else:\n        def strftime(self, format: str, /) -> str: ...\n\n    def __format__(self, fmt: str, /) -> str: ...\n    def isoformat(self) -> str: ...\n    def timetuple(self) -> struct_time: ...\n    def toordinal(self) -> int: ...\n    if sys.version_info >= (3, 13):\n        def __replace__(self, /, *, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ...\n\n    def replace(self, year: SupportsIndex = ..., month: SupportsIndex = ..., day: SupportsIndex = ...) -> Self: ...\n    def __le__(self, value: date, /) -> bool: ...\n    def __lt__(self, value: date, /) -> bool: ...\n    def __ge__(self, value: date, /) -> bool: ...\n    def __gt__(self, value: date, /) -> bool: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __add__(self, value: timedelta, /) -> Self: ...\n    def __radd__(self, value: timedelta, /) -> Self: ...\n    @overload\n    def __sub__(self, value: datetime, /) -> NoReturn: ...\n    @overload\n    def __sub__(self, value: Self, /) -> timedelta: ...\n    @overload\n    def __sub__(self, value: timedelta, /) -> Self: ...\n    def __hash__(self) -> int: ...\n    def weekday(self) -> int: ...\n    def isoweekday(self) -> int: ...\n    def isocalendar(self) -> _IsoCalendarDate: ...\n\n@disjoint_base\nclass time:\n    min: ClassVar[time]\n    max: ClassVar[time]\n    resolution: ClassVar[timedelta]\n    def __new__(\n        cls,\n        hour: SupportsIndex = 0,\n        minute: SupportsIndex = 0,\n        second: SupportsIndex = 0,\n        microsecond: SupportsIndex = 0,\n        tzinfo: _TzInfo | None = None,\n        *,\n        fold: int = 0,\n    ) -> Self: ...\n    @property\n    def hour(self) -> int: ...\n    @property\n    def minute(self) -> int: ...\n    @property\n    def second(self) -> int: ...\n    @property\n    def microsecond(self) -> int: ...\n    @property\n    def tzinfo(self) -> _TzInfo | None: ...\n    @property\n    def fold(self) -> int: ...\n    def __le__(self, value: time, /) -> bool: ...\n    def __lt__(self, value: time, /) -> bool: ...\n    def __ge__(self, value: time, /) -> bool: ...\n    def __gt__(self, value: time, /) -> bool: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    def isoformat(self, timespec: str = \"auto\") -> str: ...\n    @classmethod\n    def fromisoformat(cls, time_string: str, /) -> Self: ...\n\n    if sys.version_info >= (3, 14):\n        @classmethod\n        def strptime(cls, date_string: str, format: str, /) -> Self: ...\n\n    # On <3.12, the name of the parameter in the pure-Python implementation\n    # didn't match the name in the C implementation,\n    # meaning it is only *safe* to pass it as a keyword argument on 3.12+\n    if sys.version_info >= (3, 12):\n        def strftime(self, format: str) -> str: ...\n    else:\n        def strftime(self, format: str, /) -> str: ...\n\n    def __format__(self, fmt: str, /) -> str: ...\n    def utcoffset(self) -> timedelta | None: ...\n    def tzname(self) -> str | None: ...\n    def dst(self) -> timedelta | None: ...\n    if sys.version_info >= (3, 13):\n        def __replace__(\n            self,\n            /,\n            *,\n            hour: SupportsIndex = ...,\n            minute: SupportsIndex = ...,\n            second: SupportsIndex = ...,\n            microsecond: SupportsIndex = ...,\n            tzinfo: _TzInfo | None = ...,\n            fold: int = ...,\n        ) -> Self: ...\n\n    def replace(\n        self,\n        hour: SupportsIndex = ...,\n        minute: SupportsIndex = ...,\n        second: SupportsIndex = ...,\n        microsecond: SupportsIndex = ...,\n        tzinfo: _TzInfo | None = ...,\n        *,\n        fold: int = ...,\n    ) -> Self: ...\n\n_Date: TypeAlias = date\n_Time: TypeAlias = time\n\n@disjoint_base\nclass timedelta:\n    min: ClassVar[timedelta]\n    max: ClassVar[timedelta]\n    resolution: ClassVar[timedelta]\n    def __new__(\n        cls,\n        days: float = 0,\n        seconds: float = 0,\n        microseconds: float = 0,\n        milliseconds: float = 0,\n        minutes: float = 0,\n        hours: float = 0,\n        weeks: float = 0,\n    ) -> Self: ...\n    @property\n    def days(self) -> int: ...\n    @property\n    def seconds(self) -> int: ...\n    @property\n    def microseconds(self) -> int: ...\n    def total_seconds(self) -> float: ...\n    def __add__(self, value: timedelta, /) -> timedelta: ...\n    def __radd__(self, value: timedelta, /) -> timedelta: ...\n    def __sub__(self, value: timedelta, /) -> timedelta: ...\n    def __rsub__(self, value: timedelta, /) -> timedelta: ...\n    def __neg__(self) -> timedelta: ...\n    def __pos__(self) -> timedelta: ...\n    def __abs__(self) -> timedelta: ...\n    def __mul__(self, value: float, /) -> timedelta: ...\n    def __rmul__(self, value: float, /) -> timedelta: ...\n    @overload\n    def __floordiv__(self, value: timedelta, /) -> int: ...\n    @overload\n    def __floordiv__(self, value: int, /) -> timedelta: ...\n    @overload\n    def __truediv__(self, value: timedelta, /) -> float: ...\n    @overload\n    def __truediv__(self, value: float, /) -> timedelta: ...\n    def __mod__(self, value: timedelta, /) -> timedelta: ...\n    def __divmod__(self, value: timedelta, /) -> tuple[int, timedelta]: ...\n    def __le__(self, value: timedelta, /) -> bool: ...\n    def __lt__(self, value: timedelta, /) -> bool: ...\n    def __ge__(self, value: timedelta, /) -> bool: ...\n    def __gt__(self, value: timedelta, /) -> bool: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __bool__(self) -> bool: ...\n    def __hash__(self) -> int: ...\n\n@disjoint_base\nclass datetime(date):\n    min: ClassVar[datetime]\n    max: ClassVar[datetime]\n    def __new__(\n        cls,\n        year: SupportsIndex,\n        month: SupportsIndex,\n        day: SupportsIndex,\n        hour: SupportsIndex = 0,\n        minute: SupportsIndex = 0,\n        second: SupportsIndex = 0,\n        microsecond: SupportsIndex = 0,\n        tzinfo: _TzInfo | None = None,\n        *,\n        fold: int = 0,\n    ) -> Self: ...\n    @property\n    def hour(self) -> int: ...\n    @property\n    def minute(self) -> int: ...\n    @property\n    def second(self) -> int: ...\n    @property\n    def microsecond(self) -> int: ...\n    @property\n    def tzinfo(self) -> _TzInfo | None: ...\n    @property\n    def fold(self) -> int: ...\n    # On <3.12, the name of the first parameter in the pure-Python implementation\n    # didn't match the name in the C implementation,\n    # meaning it is only *safe* to pass it as a keyword argument on 3.12+\n    if sys.version_info >= (3, 12):\n        @classmethod\n        def fromtimestamp(cls, timestamp: float, tz: _TzInfo | None = None) -> Self: ...\n    else:\n        @classmethod\n        def fromtimestamp(cls, timestamp: float, /, tz: _TzInfo | None = None) -> Self: ...\n\n    @classmethod\n    @deprecated(\"Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .fromtimestamp(datetime.timezone.utc)\")\n    def utcfromtimestamp(cls, t: float, /) -> Self: ...\n    @classmethod\n    def now(cls, tz: _TzInfo | None = None) -> Self: ...\n    @classmethod\n    @deprecated(\"Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.timezone.utc)\")\n    def utcnow(cls) -> Self: ...\n    @classmethod\n    def combine(cls, date: _Date, time: _Time, tzinfo: _TzInfo | None = ...) -> Self: ...\n    def timestamp(self) -> float: ...\n    def utctimetuple(self) -> struct_time: ...\n    def date(self) -> _Date: ...\n    def time(self) -> _Time: ...\n    def timetz(self) -> _Time: ...\n    if sys.version_info >= (3, 13):\n        def __replace__(\n            self,\n            /,\n            *,\n            year: SupportsIndex = ...,\n            month: SupportsIndex = ...,\n            day: SupportsIndex = ...,\n            hour: SupportsIndex = ...,\n            minute: SupportsIndex = ...,\n            second: SupportsIndex = ...,\n            microsecond: SupportsIndex = ...,\n            tzinfo: _TzInfo | None = ...,\n            fold: int = ...,\n        ) -> Self: ...\n\n    def replace(\n        self,\n        year: SupportsIndex = ...,\n        month: SupportsIndex = ...,\n        day: SupportsIndex = ...,\n        hour: SupportsIndex = ...,\n        minute: SupportsIndex = ...,\n        second: SupportsIndex = ...,\n        microsecond: SupportsIndex = ...,\n        tzinfo: _TzInfo | None = ...,\n        *,\n        fold: int = ...,\n    ) -> Self: ...\n    def astimezone(self, tz: _TzInfo | None = None) -> Self: ...\n    def isoformat(self, sep: str = \"T\", timespec: str = \"auto\") -> str: ...\n    @classmethod\n    def strptime(cls, date_string: str, format: str, /) -> Self: ...\n    def utcoffset(self) -> timedelta | None: ...\n    def tzname(self) -> str | None: ...\n    def dst(self) -> timedelta | None: ...\n    def __le__(self, value: datetime, /) -> bool: ...  # type: ignore[override]\n    def __lt__(self, value: datetime, /) -> bool: ...  # type: ignore[override]\n    def __ge__(self, value: datetime, /) -> bool: ...  # type: ignore[override]\n    def __gt__(self, value: datetime, /) -> bool: ...  # type: ignore[override]\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    @overload  # type: ignore[override]\n    def __sub__(self, value: Self, /) -> timedelta: ...\n    @overload\n    def __sub__(self, value: timedelta, /) -> Self: ...\n\ndatetime_CAPI: CapsuleType\n"
  },
  {
    "path": "mypy/typeshed/stdlib/dbm/__init__.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath\nfrom collections.abc import Iterator, MutableMapping\nfrom types import TracebackType\nfrom typing import Literal, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\"open\", \"whichdb\", \"error\"]\n\n_KeyType: TypeAlias = str | bytes\n_ValueType: TypeAlias = str | bytes | bytearray\n_TFlags: TypeAlias = Literal[\n    \"r\",\n    \"w\",\n    \"c\",\n    \"n\",\n    \"rf\",\n    \"wf\",\n    \"cf\",\n    \"nf\",\n    \"rs\",\n    \"ws\",\n    \"cs\",\n    \"ns\",\n    \"ru\",\n    \"wu\",\n    \"cu\",\n    \"nu\",\n    \"rfs\",\n    \"wfs\",\n    \"cfs\",\n    \"nfs\",\n    \"rfu\",\n    \"wfu\",\n    \"cfu\",\n    \"nfu\",\n    \"rsf\",\n    \"wsf\",\n    \"csf\",\n    \"nsf\",\n    \"rsu\",\n    \"wsu\",\n    \"csu\",\n    \"nsu\",\n    \"ruf\",\n    \"wuf\",\n    \"cuf\",\n    \"nuf\",\n    \"rus\",\n    \"wus\",\n    \"cus\",\n    \"nus\",\n    \"rfsu\",\n    \"wfsu\",\n    \"cfsu\",\n    \"nfsu\",\n    \"rfus\",\n    \"wfus\",\n    \"cfus\",\n    \"nfus\",\n    \"rsfu\",\n    \"wsfu\",\n    \"csfu\",\n    \"nsfu\",\n    \"rsuf\",\n    \"wsuf\",\n    \"csuf\",\n    \"nsuf\",\n    \"rufs\",\n    \"wufs\",\n    \"cufs\",\n    \"nufs\",\n    \"rusf\",\n    \"wusf\",\n    \"cusf\",\n    \"nusf\",\n]\n\n@type_check_only\nclass _Database(MutableMapping[_KeyType, bytes]):\n    def close(self) -> None: ...\n    def __getitem__(self, key: _KeyType) -> bytes: ...\n    def __setitem__(self, key: _KeyType, value: _ValueType) -> None: ...\n    def __delitem__(self, key: _KeyType) -> None: ...\n    def __iter__(self) -> Iterator[bytes]: ...\n    def __len__(self) -> int: ...\n    def __del__(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n\n# This class is not exposed. It calls itself dbm.error.\n@type_check_only\nclass _error(Exception): ...\n\nerror: tuple[type[_error], type[OSError]]\n\nif sys.version_info >= (3, 11):\n    def whichdb(filename: StrOrBytesPath) -> str | None: ...\n    def open(file: StrOrBytesPath, flag: _TFlags = \"r\", mode: int = 0o666) -> _Database: ...\n\nelse:\n    def whichdb(filename: str) -> str | None: ...\n    def open(file: str, flag: _TFlags = \"r\", mode: int = 0o666) -> _Database: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/dbm/dumb.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath\nfrom collections.abc import Iterator, MutableMapping\nfrom types import TracebackType\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\"error\", \"open\"]\n\n_KeyType: TypeAlias = str | bytes\n_ValueType: TypeAlias = str | bytes\n\nerror = OSError\n\n# This class doesn't exist at runtime. open() can return an instance of\n# any of the three implementations of dbm (dumb, gnu, ndbm), and this\n# class is intended to represent the common interface supported by all three.\nclass _Database(MutableMapping[_KeyType, bytes]):\n    def __init__(self, filebasename: str, mode: str, flag: str = \"c\") -> None: ...\n    def sync(self) -> None: ...\n    def iterkeys(self) -> Iterator[bytes]: ...  # undocumented\n    def close(self) -> None: ...\n    def __getitem__(self, key: _KeyType) -> bytes: ...\n    def __setitem__(self, key: _KeyType, val: _ValueType) -> None: ...\n    def __delitem__(self, key: _KeyType) -> None: ...\n    def __iter__(self) -> Iterator[bytes]: ...\n    def __len__(self) -> int: ...\n    def __del__(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n\nif sys.version_info >= (3, 11):\n    def open(file: StrOrBytesPath, flag: str = \"c\", mode: int = 0o666) -> _Database: ...\n\nelse:\n    def open(file: str, flag: str = \"c\", mode: int = 0o666) -> _Database: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/dbm/gnu.pyi",
    "content": "from _gdbm import *\n"
  },
  {
    "path": "mypy/typeshed/stdlib/dbm/ndbm.pyi",
    "content": "from _dbm import *\n"
  },
  {
    "path": "mypy/typeshed/stdlib/dbm/sqlite3.pyi",
    "content": "from _typeshed import ReadableBuffer, StrOrBytesPath, Unused\nfrom collections.abc import Generator, MutableMapping\nfrom typing import Final, Literal\nfrom typing_extensions import LiteralString, Self, TypeAlias\n\nBUILD_TABLE: Final[LiteralString]\nGET_SIZE: Final[LiteralString]\nLOOKUP_KEY: Final[LiteralString]\nSTORE_KV: Final[LiteralString]\nDELETE_KEY: Final[LiteralString]\nITER_KEYS: Final[LiteralString]\n\n_SqliteData: TypeAlias = str | ReadableBuffer | int | float\n\nclass error(OSError): ...\n\nclass _Database(MutableMapping[bytes, bytes]):\n    def __init__(self, path: StrOrBytesPath, /, *, flag: Literal[\"r\", \"w\", \"c\", \"n\"], mode: int) -> None: ...\n    def __len__(self) -> int: ...\n    def __getitem__(self, key: _SqliteData) -> bytes: ...\n    def __setitem__(self, key: _SqliteData, value: _SqliteData) -> None: ...\n    def __delitem__(self, key: _SqliteData) -> None: ...\n    def __iter__(self) -> Generator[bytes]: ...\n    def close(self) -> None: ...\n    def keys(self) -> list[bytes]: ...  # type: ignore[override]\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n\ndef open(filename: StrOrBytesPath, /, flag: Literal[\"r\", \"w\", \"c\", \"n\"] = \"r\", mode: int = 0o666) -> _Database: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/decimal.pyi",
    "content": "import numbers\nimport sys\nfrom _decimal import (\n    HAVE_CONTEXTVAR as HAVE_CONTEXTVAR,\n    HAVE_THREADS as HAVE_THREADS,\n    MAX_EMAX as MAX_EMAX,\n    MAX_PREC as MAX_PREC,\n    MIN_EMIN as MIN_EMIN,\n    MIN_ETINY as MIN_ETINY,\n    ROUND_05UP as ROUND_05UP,\n    ROUND_CEILING as ROUND_CEILING,\n    ROUND_DOWN as ROUND_DOWN,\n    ROUND_FLOOR as ROUND_FLOOR,\n    ROUND_HALF_DOWN as ROUND_HALF_DOWN,\n    ROUND_HALF_EVEN as ROUND_HALF_EVEN,\n    ROUND_HALF_UP as ROUND_HALF_UP,\n    ROUND_UP as ROUND_UP,\n    BasicContext as BasicContext,\n    DefaultContext as DefaultContext,\n    ExtendedContext as ExtendedContext,\n    __libmpdec_version__ as __libmpdec_version__,\n    __version__ as __version__,\n    getcontext as getcontext,\n    localcontext as localcontext,\n    setcontext as setcontext,\n)\nfrom collections.abc import Container, Sequence\nfrom types import TracebackType\nfrom typing import Any, ClassVar, Literal, NamedTuple, final, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, disjoint_base\n\nif sys.version_info >= (3, 14):\n    from _decimal import IEEE_CONTEXT_MAX_BITS as IEEE_CONTEXT_MAX_BITS, IEEEContext as IEEEContext\n\n_Decimal: TypeAlias = Decimal | int\n_DecimalNew: TypeAlias = Decimal | float | str | tuple[int, Sequence[int], int]\n_ComparableNum: TypeAlias = Decimal | float | numbers.Rational\n_TrapType: TypeAlias = type[DecimalException]\n\n# At runtime, these classes are implemented in C as part of \"_decimal\".\n# However, they consider themselves to live in \"decimal\", so we'll put them here.\n\n# This type isn't exposed at runtime. It calls itself decimal.ContextManager\n@final\n@type_check_only\nclass _ContextManager:\n    def __init__(self, new_context: Context) -> None: ...\n    def __enter__(self) -> Context: ...\n    def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ...\n\nclass DecimalTuple(NamedTuple):\n    sign: int\n    digits: tuple[int, ...]\n    exponent: int | Literal[\"n\", \"N\", \"F\"]\n\nclass DecimalException(ArithmeticError): ...\nclass Clamped(DecimalException): ...\nclass InvalidOperation(DecimalException): ...\nclass ConversionSyntax(InvalidOperation): ...\nclass DivisionByZero(DecimalException, ZeroDivisionError): ...\nclass DivisionImpossible(InvalidOperation): ...\nclass DivisionUndefined(InvalidOperation, ZeroDivisionError): ...\nclass Inexact(DecimalException): ...\nclass InvalidContext(InvalidOperation): ...\nclass Rounded(DecimalException): ...\nclass Subnormal(DecimalException): ...\nclass Overflow(Inexact, Rounded): ...\nclass Underflow(Inexact, Rounded, Subnormal): ...\nclass FloatOperation(DecimalException, TypeError): ...\n\n@disjoint_base\nclass Decimal:\n    def __new__(cls, value: _DecimalNew = \"0\", context: Context | None = None) -> Self: ...\n    if sys.version_info >= (3, 14):\n        @classmethod\n        def from_number(cls, number: Decimal | float, /) -> Self: ...\n\n    @classmethod\n    def from_float(cls, f: float, /) -> Self: ...\n    def __bool__(self) -> bool: ...\n    def compare(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def __hash__(self) -> int: ...\n    def as_tuple(self) -> DecimalTuple: ...\n    def as_integer_ratio(self) -> tuple[int, int]: ...\n    def to_eng_string(self, context: Context | None = None) -> str: ...\n    def __abs__(self) -> Decimal: ...\n    def __add__(self, value: _Decimal, /) -> Decimal: ...\n    def __divmod__(self, value: _Decimal, /) -> tuple[Decimal, Decimal]: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __floordiv__(self, value: _Decimal, /) -> Decimal: ...\n    def __ge__(self, value: _ComparableNum, /) -> bool: ...\n    def __gt__(self, value: _ComparableNum, /) -> bool: ...\n    def __le__(self, value: _ComparableNum, /) -> bool: ...\n    def __lt__(self, value: _ComparableNum, /) -> bool: ...\n    def __mod__(self, value: _Decimal, /) -> Decimal: ...\n    def __mul__(self, value: _Decimal, /) -> Decimal: ...\n    def __neg__(self) -> Decimal: ...\n    def __pos__(self) -> Decimal: ...\n    def __pow__(self, value: _Decimal, mod: _Decimal | None = None, /) -> Decimal: ...\n    def __radd__(self, value: _Decimal, /) -> Decimal: ...\n    def __rdivmod__(self, value: _Decimal, /) -> tuple[Decimal, Decimal]: ...\n    def __rfloordiv__(self, value: _Decimal, /) -> Decimal: ...\n    def __rmod__(self, value: _Decimal, /) -> Decimal: ...\n    def __rmul__(self, value: _Decimal, /) -> Decimal: ...\n    def __rsub__(self, value: _Decimal, /) -> Decimal: ...\n    def __rtruediv__(self, value: _Decimal, /) -> Decimal: ...\n    def __sub__(self, value: _Decimal, /) -> Decimal: ...\n    def __truediv__(self, value: _Decimal, /) -> Decimal: ...\n    def remainder_near(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def __float__(self) -> float: ...\n    def __int__(self) -> int: ...\n    def __trunc__(self) -> int: ...\n    @property\n    def real(self) -> Decimal: ...\n    @property\n    def imag(self) -> Decimal: ...\n    def conjugate(self) -> Decimal: ...\n    def __complex__(self) -> complex: ...\n    @overload\n    def __round__(self) -> int: ...\n    @overload\n    def __round__(self, ndigits: int, /) -> Decimal: ...\n    def __floor__(self) -> int: ...\n    def __ceil__(self) -> int: ...\n    def fma(self, other: _Decimal, third: _Decimal, context: Context | None = None) -> Decimal: ...\n    def __rpow__(self, value: _Decimal, mod: Context | None = None, /) -> Decimal: ...\n    def normalize(self, context: Context | None = None) -> Decimal: ...\n    def quantize(self, exp: _Decimal, rounding: str | None = None, context: Context | None = None) -> Decimal: ...\n    def same_quantum(self, other: _Decimal, context: Context | None = None) -> bool: ...\n    def to_integral_exact(self, rounding: str | None = None, context: Context | None = None) -> Decimal: ...\n    def to_integral_value(self, rounding: str | None = None, context: Context | None = None) -> Decimal: ...\n    def to_integral(self, rounding: str | None = None, context: Context | None = None) -> Decimal: ...\n    def sqrt(self, context: Context | None = None) -> Decimal: ...\n    def max(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def min(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def adjusted(self) -> int: ...\n    def canonical(self) -> Decimal: ...\n    def compare_signal(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def compare_total(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def compare_total_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def copy_abs(self) -> Decimal: ...\n    def copy_negate(self) -> Decimal: ...\n    def copy_sign(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def exp(self, context: Context | None = None) -> Decimal: ...\n    def is_canonical(self) -> bool: ...\n    def is_finite(self) -> bool: ...\n    def is_infinite(self) -> bool: ...\n    def is_nan(self) -> bool: ...\n    def is_normal(self, context: Context | None = None) -> bool: ...\n    def is_qnan(self) -> bool: ...\n    def is_signed(self) -> bool: ...\n    def is_snan(self) -> bool: ...\n    def is_subnormal(self, context: Context | None = None) -> bool: ...\n    def is_zero(self) -> bool: ...\n    def ln(self, context: Context | None = None) -> Decimal: ...\n    def log10(self, context: Context | None = None) -> Decimal: ...\n    def logb(self, context: Context | None = None) -> Decimal: ...\n    def logical_and(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def logical_invert(self, context: Context | None = None) -> Decimal: ...\n    def logical_or(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def logical_xor(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def max_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def min_mag(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def next_minus(self, context: Context | None = None) -> Decimal: ...\n    def next_plus(self, context: Context | None = None) -> Decimal: ...\n    def next_toward(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def number_class(self, context: Context | None = None) -> str: ...\n    def radix(self) -> Decimal: ...\n    def rotate(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def scaleb(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def shift(self, other: _Decimal, context: Context | None = None) -> Decimal: ...\n    def __reduce__(self) -> tuple[type[Self], tuple[str]]: ...\n    def __copy__(self) -> Self: ...\n    def __deepcopy__(self, memo: Any, /) -> Self: ...\n    def __format__(self, specifier: str, context: Context | None = None, /) -> str: ...\n\n@disjoint_base\nclass Context:\n    # TODO: Context doesn't allow you to delete *any* attributes from instances of the class at runtime,\n    # even settable attributes like `prec` and `rounding`,\n    # but that's inexpressible in the stub.\n    # Type checkers either ignore it or misinterpret it\n    # if you add a `def __delattr__(self, name: str, /) -> NoReturn` method to the stub\n    prec: int\n    rounding: str\n    Emin: int\n    Emax: int\n    capitals: int\n    clamp: int\n    traps: dict[_TrapType, bool]\n    flags: dict[_TrapType, bool]\n    def __init__(\n        self,\n        prec: int | None = None,\n        rounding: str | None = None,\n        Emin: int | None = None,\n        Emax: int | None = None,\n        capitals: int | None = None,\n        clamp: int | None = None,\n        flags: dict[_TrapType, bool] | Container[_TrapType] | None = None,\n        traps: dict[_TrapType, bool] | Container[_TrapType] | None = None,\n    ) -> None: ...\n    def __reduce__(self) -> tuple[type[Self], tuple[Any, ...]]: ...\n    def clear_flags(self) -> None: ...\n    def clear_traps(self) -> None: ...\n    def copy(self) -> Context: ...\n    def __copy__(self) -> Context: ...\n    # see https://github.com/python/cpython/issues/94107\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def Etiny(self) -> int: ...\n    def Etop(self) -> int: ...\n    def create_decimal(self, num: _DecimalNew = \"0\", /) -> Decimal: ...\n    def create_decimal_from_float(self, f: float, /) -> Decimal: ...\n    def abs(self, x: _Decimal, /) -> Decimal: ...\n    def add(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def canonical(self, x: Decimal, /) -> Decimal: ...\n    def compare(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def compare_signal(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def compare_total(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def compare_total_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def copy_abs(self, x: _Decimal, /) -> Decimal: ...\n    def copy_decimal(self, x: _Decimal, /) -> Decimal: ...\n    def copy_negate(self, x: _Decimal, /) -> Decimal: ...\n    def copy_sign(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def divide(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def divide_int(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def divmod(self, x: _Decimal, y: _Decimal, /) -> tuple[Decimal, Decimal]: ...\n    def exp(self, x: _Decimal, /) -> Decimal: ...\n    def fma(self, x: _Decimal, y: _Decimal, z: _Decimal, /) -> Decimal: ...\n    def is_canonical(self, x: _Decimal, /) -> bool: ...\n    def is_finite(self, x: _Decimal, /) -> bool: ...\n    def is_infinite(self, x: _Decimal, /) -> bool: ...\n    def is_nan(self, x: _Decimal, /) -> bool: ...\n    def is_normal(self, x: _Decimal, /) -> bool: ...\n    def is_qnan(self, x: _Decimal, /) -> bool: ...\n    def is_signed(self, x: _Decimal, /) -> bool: ...\n    def is_snan(self, x: _Decimal, /) -> bool: ...\n    def is_subnormal(self, x: _Decimal, /) -> bool: ...\n    def is_zero(self, x: _Decimal, /) -> bool: ...\n    def ln(self, x: _Decimal, /) -> Decimal: ...\n    def log10(self, x: _Decimal, /) -> Decimal: ...\n    def logb(self, x: _Decimal, /) -> Decimal: ...\n    def logical_and(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def logical_invert(self, x: _Decimal, /) -> Decimal: ...\n    def logical_or(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def logical_xor(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def max(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def max_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def min(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def min_mag(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def minus(self, x: _Decimal, /) -> Decimal: ...\n    def multiply(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def next_minus(self, x: _Decimal, /) -> Decimal: ...\n    def next_plus(self, x: _Decimal, /) -> Decimal: ...\n    def next_toward(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def normalize(self, x: _Decimal, /) -> Decimal: ...\n    def number_class(self, x: _Decimal, /) -> str: ...\n    def plus(self, x: _Decimal, /) -> Decimal: ...\n    def power(self, a: _Decimal, b: _Decimal, modulo: _Decimal | None = None) -> Decimal: ...\n    def quantize(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def radix(self) -> Decimal: ...\n    def remainder(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def remainder_near(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def rotate(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def same_quantum(self, x: _Decimal, y: _Decimal, /) -> bool: ...\n    def scaleb(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def shift(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def sqrt(self, x: _Decimal, /) -> Decimal: ...\n    def subtract(self, x: _Decimal, y: _Decimal, /) -> Decimal: ...\n    def to_eng_string(self, x: _Decimal, /) -> str: ...\n    def to_sci_string(self, x: _Decimal, /) -> str: ...\n    def to_integral_exact(self, x: _Decimal, /) -> Decimal: ...\n    def to_integral_value(self, x: _Decimal, /) -> Decimal: ...\n    def to_integral(self, x: _Decimal, /) -> Decimal: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/difflib.pyi",
    "content": "import re\nimport sys\nfrom collections.abc import Callable, Iterable, Iterator, Sequence\nfrom types import GenericAlias\nfrom typing import Any, AnyStr, Generic, Literal, NamedTuple, TypeVar, overload\n\n__all__ = [\n    \"get_close_matches\",\n    \"ndiff\",\n    \"restore\",\n    \"SequenceMatcher\",\n    \"Differ\",\n    \"IS_CHARACTER_JUNK\",\n    \"IS_LINE_JUNK\",\n    \"context_diff\",\n    \"unified_diff\",\n    \"diff_bytes\",\n    \"HtmlDiff\",\n    \"Match\",\n]\n\n_T = TypeVar(\"_T\")\n\nclass Match(NamedTuple):\n    a: int\n    b: int\n    size: int\n\nclass SequenceMatcher(Generic[_T]):\n    @overload\n    def __init__(self, isjunk: Callable[[_T], bool] | None, a: Sequence[_T], b: Sequence[_T], autojunk: bool = True) -> None: ...\n    @overload\n    def __init__(self, *, a: Sequence[_T], b: Sequence[_T], autojunk: bool = True) -> None: ...\n    @overload\n    def __init__(\n        self: SequenceMatcher[str],\n        isjunk: Callable[[str], bool] | None = None,\n        a: Sequence[str] = \"\",\n        b: Sequence[str] = \"\",\n        autojunk: bool = True,\n    ) -> None: ...\n    def set_seqs(self, a: Sequence[_T], b: Sequence[_T]) -> None: ...\n    def set_seq1(self, a: Sequence[_T]) -> None: ...\n    def set_seq2(self, b: Sequence[_T]) -> None: ...\n    def find_longest_match(self, alo: int = 0, ahi: int | None = None, blo: int = 0, bhi: int | None = None) -> Match: ...\n    def get_matching_blocks(self) -> list[Match]: ...\n    def get_opcodes(self) -> list[tuple[Literal[\"replace\", \"delete\", \"insert\", \"equal\"], int, int, int, int]]: ...\n    def get_grouped_opcodes(self, n: int = 3) -> Iterable[list[tuple[str, int, int, int, int]]]: ...\n    def ratio(self) -> float: ...\n    def quick_ratio(self) -> float: ...\n    def real_quick_ratio(self) -> float: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@overload\ndef get_close_matches(word: AnyStr, possibilities: Iterable[AnyStr], n: int = 3, cutoff: float = 0.6) -> list[AnyStr]: ...\n@overload\ndef get_close_matches(\n    word: Sequence[_T], possibilities: Iterable[Sequence[_T]], n: int = 3, cutoff: float = 0.6\n) -> list[Sequence[_T]]: ...\n\nclass Differ:\n    def __init__(self, linejunk: Callable[[str], bool] | None = None, charjunk: Callable[[str], bool] | None = None) -> None: ...\n    def compare(self, a: Sequence[str], b: Sequence[str]) -> Iterator[str]: ...\n\nif sys.version_info >= (3, 14):\n    def IS_LINE_JUNK(line: str, pat: Callable[[str], re.Match[str] | None] | None = None) -> bool: ...\n\nelse:\n    def IS_LINE_JUNK(line: str, pat: Callable[[str], re.Match[str] | None] = ...) -> bool: ...\n\ndef IS_CHARACTER_JUNK(ch: str, ws: str = \" \\t\") -> bool: ...  # ws is undocumented\ndef unified_diff(\n    a: Sequence[str],\n    b: Sequence[str],\n    fromfile: str = \"\",\n    tofile: str = \"\",\n    fromfiledate: str = \"\",\n    tofiledate: str = \"\",\n    n: int = 3,\n    lineterm: str = \"\\n\",\n) -> Iterator[str]: ...\ndef context_diff(\n    a: Sequence[str],\n    b: Sequence[str],\n    fromfile: str = \"\",\n    tofile: str = \"\",\n    fromfiledate: str = \"\",\n    tofiledate: str = \"\",\n    n: int = 3,\n    lineterm: str = \"\\n\",\n) -> Iterator[str]: ...\ndef ndiff(\n    a: Sequence[str],\n    b: Sequence[str],\n    linejunk: Callable[[str], bool] | None = None,\n    charjunk: Callable[[str], bool] | None = ...,\n) -> Iterator[str]: ...\n\nclass HtmlDiff:\n    def __init__(\n        self,\n        tabsize: int = 8,\n        wrapcolumn: int | None = None,\n        linejunk: Callable[[str], bool] | None = None,\n        charjunk: Callable[[str], bool] | None = ...,\n    ) -> None: ...\n    def make_file(\n        self,\n        fromlines: Sequence[str],\n        tolines: Sequence[str],\n        fromdesc: str = \"\",\n        todesc: str = \"\",\n        context: bool = False,\n        numlines: int = 5,\n        *,\n        charset: str = \"utf-8\",\n    ) -> str: ...\n    def make_table(\n        self,\n        fromlines: Sequence[str],\n        tolines: Sequence[str],\n        fromdesc: str = \"\",\n        todesc: str = \"\",\n        context: bool = False,\n        numlines: int = 5,\n    ) -> str: ...\n\ndef restore(delta: Iterable[str], which: int) -> Iterator[str]: ...\ndef diff_bytes(\n    dfunc: Callable[[Sequence[str], Sequence[str], str, str, str, str, int, str], Iterator[str]],\n    a: Iterable[bytes | bytearray],\n    b: Iterable[bytes | bytearray],\n    fromfile: bytes | bytearray = b\"\",\n    tofile: bytes | bytearray = b\"\",\n    fromfiledate: bytes | bytearray = b\"\",\n    tofiledate: bytes | bytearray = b\"\",\n    n: int = 3,\n    lineterm: bytes | bytearray = b\"\\n\",\n) -> Iterator[bytes]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/dis.pyi",
    "content": "import sys\nimport types\nfrom collections.abc import Callable, Iterator\nfrom opcode import *  # `dis` re-exports it as a part of public API\nfrom typing import IO, Any, Final, NamedTuple, overload\nfrom typing_extensions import Self, TypeAlias, deprecated, disjoint_base\n\n__all__ = [\n    \"code_info\",\n    \"dis\",\n    \"disassemble\",\n    \"distb\",\n    \"disco\",\n    \"findlinestarts\",\n    \"findlabels\",\n    \"show_code\",\n    \"get_instructions\",\n    \"Instruction\",\n    \"Bytecode\",\n    \"cmp_op\",\n    \"hasconst\",\n    \"hasname\",\n    \"hasjrel\",\n    \"hasjabs\",\n    \"haslocal\",\n    \"hascompare\",\n    \"hasfree\",\n    \"opname\",\n    \"opmap\",\n    \"HAVE_ARGUMENT\",\n    \"EXTENDED_ARG\",\n    \"stack_effect\",\n]\nif sys.version_info >= (3, 13):\n    __all__ += [\"hasjump\"]\n\nif sys.version_info >= (3, 12):\n    __all__ += [\"hasarg\", \"hasexc\"]\nelse:\n    __all__ += [\"hasnargs\"]\n\n# Strictly this should not have to include Callable, but mypy doesn't use FunctionType\n# for functions (python/mypy#3171)\n_HaveCodeType: TypeAlias = types.MethodType | types.FunctionType | types.CodeType | type | Callable[..., Any]\n\nif sys.version_info >= (3, 11):\n    class Positions(NamedTuple):\n        lineno: int | None = None\n        end_lineno: int | None = None\n        col_offset: int | None = None\n        end_col_offset: int | None = None\n\nif sys.version_info >= (3, 13):\n    class _Instruction(NamedTuple):\n        opname: str\n        opcode: int\n        arg: int | None\n        argval: Any\n        argrepr: str\n        offset: int\n        start_offset: int\n        starts_line: bool\n        line_number: int | None\n        label: int | None = None\n        positions: Positions | None = None\n        cache_info: list[tuple[str, int, Any]] | None = None\n\nelif sys.version_info >= (3, 11):\n    class _Instruction(NamedTuple):\n        opname: str\n        opcode: int\n        arg: int | None\n        argval: Any\n        argrepr: str\n        offset: int\n        starts_line: int | None\n        is_jump_target: bool\n        positions: Positions | None = None\n\nelse:\n    class _Instruction(NamedTuple):\n        opname: str\n        opcode: int\n        arg: int | None\n        argval: Any\n        argrepr: str\n        offset: int\n        starts_line: int | None\n        is_jump_target: bool\n\nif sys.version_info >= (3, 12):\n    class Instruction(_Instruction):\n        if sys.version_info < (3, 13):\n            def _disassemble(self, lineno_width: int = 3, mark_as_current: bool = False, offset_width: int = 4) -> str: ...\n        if sys.version_info >= (3, 13):\n            @property\n            def oparg(self) -> int: ...\n            @property\n            def baseopcode(self) -> int: ...\n            @property\n            def baseopname(self) -> str: ...\n            @property\n            def cache_offset(self) -> int: ...\n            @property\n            def end_offset(self) -> int: ...\n            @property\n            def jump_target(self) -> int: ...\n            @property\n            def is_jump_target(self) -> bool: ...\n        if sys.version_info >= (3, 14):\n            @staticmethod\n            def make(\n                opname: str,\n                arg: int | None,\n                argval: Any,\n                argrepr: str,\n                offset: int,\n                start_offset: int,\n                starts_line: bool,\n                line_number: int | None,\n                label: int | None = None,\n                positions: Positions | None = None,\n                cache_info: list[tuple[str, int, Any]] | None = None,\n            ) -> Instruction: ...\n\nelse:\n    @disjoint_base\n    class Instruction(_Instruction):\n        def _disassemble(self, lineno_width: int = 3, mark_as_current: bool = False, offset_width: int = 4) -> str: ...\n\nclass Bytecode:\n    codeobj: types.CodeType\n    first_line: int\n    if sys.version_info >= (3, 14):\n        show_positions: bool\n        # 3.14 added `show_positions`\n        def __init__(\n            self,\n            x: _HaveCodeType | str,\n            *,\n            first_line: int | None = None,\n            current_offset: int | None = None,\n            show_caches: bool = False,\n            adaptive: bool = False,\n            show_offsets: bool = False,\n            show_positions: bool = False,\n        ) -> None: ...\n    elif sys.version_info >= (3, 13):\n        show_offsets: bool\n        # 3.13 added `show_offsets`\n        def __init__(\n            self,\n            x: _HaveCodeType | str,\n            *,\n            first_line: int | None = None,\n            current_offset: int | None = None,\n            show_caches: bool = False,\n            adaptive: bool = False,\n            show_offsets: bool = False,\n        ) -> None: ...\n    elif sys.version_info >= (3, 11):\n        def __init__(\n            self,\n            x: _HaveCodeType | str,\n            *,\n            first_line: int | None = None,\n            current_offset: int | None = None,\n            show_caches: bool = False,\n            adaptive: bool = False,\n        ) -> None: ...\n    else:\n        def __init__(\n            self, x: _HaveCodeType | str, *, first_line: int | None = None, current_offset: int | None = None\n        ) -> None: ...\n\n    if sys.version_info >= (3, 11):\n        @classmethod\n        def from_traceback(cls, tb: types.TracebackType, *, show_caches: bool = False, adaptive: bool = False) -> Self: ...\n    else:\n        @classmethod\n        def from_traceback(cls, tb: types.TracebackType) -> Self: ...\n\n    def __iter__(self) -> Iterator[Instruction]: ...\n    def info(self) -> str: ...\n    def dis(self) -> str: ...\n\nCOMPILER_FLAG_NAMES: Final[dict[int, str]]\n\ndef findlabels(code: _HaveCodeType) -> list[int]: ...\ndef findlinestarts(code: _HaveCodeType) -> Iterator[tuple[int, int]]: ...\ndef pretty_flags(flags: int) -> str: ...\ndef code_info(x: _HaveCodeType | str) -> str: ...\n\nif sys.version_info >= (3, 14):\n    # 3.14 added `show_positions`\n    def dis(\n        x: _HaveCodeType | str | bytes | bytearray | None = None,\n        *,\n        file: IO[str] | None = None,\n        depth: int | None = None,\n        show_caches: bool = False,\n        adaptive: bool = False,\n        show_offsets: bool = False,\n        show_positions: bool = False,\n    ) -> None: ...\n    def disassemble(\n        co: _HaveCodeType,\n        lasti: int = -1,\n        *,\n        file: IO[str] | None = None,\n        show_caches: bool = False,\n        adaptive: bool = False,\n        show_offsets: bool = False,\n        show_positions: bool = False,\n    ) -> None: ...\n    def distb(\n        tb: types.TracebackType | None = None,\n        *,\n        file: IO[str] | None = None,\n        show_caches: bool = False,\n        adaptive: bool = False,\n        show_offsets: bool = False,\n        show_positions: bool = False,\n    ) -> None: ...\n\nelif sys.version_info >= (3, 13):\n    # 3.13 added `show_offsets`\n    def dis(\n        x: _HaveCodeType | str | bytes | bytearray | None = None,\n        *,\n        file: IO[str] | None = None,\n        depth: int | None = None,\n        show_caches: bool = False,\n        adaptive: bool = False,\n        show_offsets: bool = False,\n    ) -> None: ...\n    def disassemble(\n        co: _HaveCodeType,\n        lasti: int = -1,\n        *,\n        file: IO[str] | None = None,\n        show_caches: bool = False,\n        adaptive: bool = False,\n        show_offsets: bool = False,\n    ) -> None: ...\n    def distb(\n        tb: types.TracebackType | None = None,\n        *,\n        file: IO[str] | None = None,\n        show_caches: bool = False,\n        adaptive: bool = False,\n        show_offsets: bool = False,\n    ) -> None: ...\n\nelif sys.version_info >= (3, 11):\n    # 3.11 added `show_caches` and `adaptive`\n    def dis(\n        x: _HaveCodeType | str | bytes | bytearray | None = None,\n        *,\n        file: IO[str] | None = None,\n        depth: int | None = None,\n        show_caches: bool = False,\n        adaptive: bool = False,\n    ) -> None: ...\n    def disassemble(\n        co: _HaveCodeType, lasti: int = -1, *, file: IO[str] | None = None, show_caches: bool = False, adaptive: bool = False\n    ) -> None: ...\n    def distb(\n        tb: types.TracebackType | None = None, *, file: IO[str] | None = None, show_caches: bool = False, adaptive: bool = False\n    ) -> None: ...\n\nelse:\n    def dis(\n        x: _HaveCodeType | str | bytes | bytearray | None = None, *, file: IO[str] | None = None, depth: int | None = None\n    ) -> None: ...\n    def disassemble(co: _HaveCodeType, lasti: int = -1, *, file: IO[str] | None = None) -> None: ...\n    def distb(tb: types.TracebackType | None = None, *, file: IO[str] | None = None) -> None: ...\n\nif sys.version_info >= (3, 13):\n    # 3.13 made `show_caches` `None` by default and has no effect\n    @overload\n    def get_instructions(x: _HaveCodeType, *, first_line: int | None = None, adaptive: bool = False) -> Iterator[Instruction]: ...\n    @overload\n    @deprecated(\n        \"The `show_caches` parameter is deprecated since Python 3.13. \"\n        \"The iterator generates the `Instruction` instances with the `cache_info` field populated.\"\n    )\n    def get_instructions(\n        x: _HaveCodeType, *, first_line: int | None = None, show_caches: bool | None = None, adaptive: bool = False\n    ) -> Iterator[Instruction]: ...\n\nelif sys.version_info >= (3, 11):\n    def get_instructions(\n        x: _HaveCodeType, *, first_line: int | None = None, show_caches: bool = False, adaptive: bool = False\n    ) -> Iterator[Instruction]: ...\n\nelse:\n    def get_instructions(x: _HaveCodeType, *, first_line: int | None = None) -> Iterator[Instruction]: ...\n\ndef show_code(co: _HaveCodeType, *, file: IO[str] | None = None) -> None: ...\n\ndisco = disassemble\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/__init__.pyi",
    "content": "# Attempts to improve these stubs are probably not the best use of time:\n# - distutils is deleted in Python 3.12 and newer\n# - Most users already do not use stdlib distutils, due to setuptools monkeypatching\n# - We have very little quality assurance on these stubs, since due to the two above issues\n#   we allowlist all distutils errors in stubtest.\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/_msvccompiler.pyi",
    "content": "from _typeshed import Incomplete\nfrom distutils.ccompiler import CCompiler\nfrom typing import ClassVar, Final\n\nPLAT_SPEC_TO_RUNTIME: Final[dict[str, str]]\nPLAT_TO_VCVARS: Final[dict[str, str]]\n\nclass MSVCCompiler(CCompiler):\n    compiler_type: ClassVar[str]\n    executables: ClassVar[dict[Incomplete, Incomplete]]\n    res_extension: ClassVar[str]\n    initialized: bool\n    def initialize(self, plat_name: str | None = None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/archive_util.pyi",
    "content": "from _typeshed import StrOrBytesPath, StrPath\nfrom typing import Literal, overload\n\n@overload\ndef make_archive(\n    base_name: str,\n    format: str,\n    root_dir: StrOrBytesPath | None = None,\n    base_dir: str | None = None,\n    verbose: bool | Literal[0, 1] = 0,\n    dry_run: bool | Literal[0, 1] = 0,\n    owner: str | None = None,\n    group: str | None = None,\n) -> str: ...\n@overload\ndef make_archive(\n    base_name: StrPath,\n    format: str,\n    root_dir: StrOrBytesPath,\n    base_dir: str | None = None,\n    verbose: bool | Literal[0, 1] = 0,\n    dry_run: bool | Literal[0, 1] = 0,\n    owner: str | None = None,\n    group: str | None = None,\n) -> str: ...\ndef make_tarball(\n    base_name: str,\n    base_dir: StrPath,\n    compress: str | None = \"gzip\",\n    verbose: bool | Literal[0, 1] = 0,\n    dry_run: bool | Literal[0, 1] = 0,\n    owner: str | None = None,\n    group: str | None = None,\n) -> str: ...\ndef make_zipfile(base_name: str, base_dir: str, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/bcppcompiler.pyi",
    "content": "from distutils.ccompiler import CCompiler\n\nclass BCPPCompiler(CCompiler): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/ccompiler.pyi",
    "content": "from _typeshed import BytesPath, StrPath, Unused\nfrom collections.abc import Callable, Iterable, Sequence\nfrom distutils.file_util import _BytesPathT, _StrPathT\nfrom typing import Literal, overload\nfrom typing_extensions import TypeAlias, TypeVarTuple, Unpack\n\n_Macro: TypeAlias = tuple[str] | tuple[str, str | None]\n_Ts = TypeVarTuple(\"_Ts\")\n\ndef gen_lib_options(\n    compiler: CCompiler, library_dirs: list[str], runtime_library_dirs: list[str], libraries: list[str]\n) -> list[str]: ...\ndef gen_preprocess_options(macros: list[_Macro], include_dirs: list[str]) -> list[str]: ...\ndef get_default_compiler(osname: str | None = None, platform: str | None = None) -> str: ...\ndef new_compiler(\n    plat: str | None = None,\n    compiler: str | None = None,\n    verbose: bool | Literal[0, 1] = 0,\n    dry_run: bool | Literal[0, 1] = 0,\n    force: bool | Literal[0, 1] = 0,\n) -> CCompiler: ...\ndef show_compilers() -> None: ...\n\nclass CCompiler:\n    dry_run: bool\n    force: bool\n    verbose: bool\n    output_dir: str | None\n    macros: list[_Macro]\n    include_dirs: list[str]\n    libraries: list[str]\n    library_dirs: list[str]\n    runtime_library_dirs: list[str]\n    objects: list[str]\n    def __init__(\n        self, verbose: bool | Literal[0, 1] = 0, dry_run: bool | Literal[0, 1] = 0, force: bool | Literal[0, 1] = 0\n    ) -> None: ...\n    def add_include_dir(self, dir: str) -> None: ...\n    def set_include_dirs(self, dirs: list[str]) -> None: ...\n    def add_library(self, libname: str) -> None: ...\n    def set_libraries(self, libnames: list[str]) -> None: ...\n    def add_library_dir(self, dir: str) -> None: ...\n    def set_library_dirs(self, dirs: list[str]) -> None: ...\n    def add_runtime_library_dir(self, dir: str) -> None: ...\n    def set_runtime_library_dirs(self, dirs: list[str]) -> None: ...\n    def define_macro(self, name: str, value: str | None = None) -> None: ...\n    def undefine_macro(self, name: str) -> None: ...\n    def add_link_object(self, object: str) -> None: ...\n    def set_link_objects(self, objects: list[str]) -> None: ...\n    def detect_language(self, sources: str | list[str]) -> str | None: ...\n    def find_library_file(self, dirs: list[str], lib: str, debug: bool | Literal[0, 1] = 0) -> str | None: ...\n    def has_function(\n        self,\n        funcname: str,\n        includes: list[str] | None = None,\n        include_dirs: list[str] | None = None,\n        libraries: list[str] | None = None,\n        library_dirs: list[str] | None = None,\n    ) -> bool: ...\n    def library_dir_option(self, dir: str) -> str: ...\n    def library_option(self, lib: str) -> str: ...\n    def runtime_library_dir_option(self, dir: str) -> str: ...\n    def set_executables(self, **args: str) -> None: ...\n    def compile(\n        self,\n        sources: Sequence[StrPath],\n        output_dir: str | None = None,\n        macros: list[_Macro] | None = None,\n        include_dirs: list[str] | None = None,\n        debug: bool | Literal[0, 1] = 0,\n        extra_preargs: list[str] | None = None,\n        extra_postargs: list[str] | None = None,\n        depends: list[str] | None = None,\n    ) -> list[str]: ...\n    def create_static_lib(\n        self,\n        objects: list[str],\n        output_libname: str,\n        output_dir: str | None = None,\n        debug: bool | Literal[0, 1] = 0,\n        target_lang: str | None = None,\n    ) -> None: ...\n    def link(\n        self,\n        target_desc: str,\n        objects: list[str],\n        output_filename: str,\n        output_dir: str | None = None,\n        libraries: list[str] | None = None,\n        library_dirs: list[str] | None = None,\n        runtime_library_dirs: list[str] | None = None,\n        export_symbols: list[str] | None = None,\n        debug: bool | Literal[0, 1] = 0,\n        extra_preargs: list[str] | None = None,\n        extra_postargs: list[str] | None = None,\n        build_temp: str | None = None,\n        target_lang: str | None = None,\n    ) -> None: ...\n    def link_executable(\n        self,\n        objects: list[str],\n        output_progname: str,\n        output_dir: str | None = None,\n        libraries: list[str] | None = None,\n        library_dirs: list[str] | None = None,\n        runtime_library_dirs: list[str] | None = None,\n        debug: bool | Literal[0, 1] = 0,\n        extra_preargs: list[str] | None = None,\n        extra_postargs: list[str] | None = None,\n        target_lang: str | None = None,\n    ) -> None: ...\n    def link_shared_lib(\n        self,\n        objects: list[str],\n        output_libname: str,\n        output_dir: str | None = None,\n        libraries: list[str] | None = None,\n        library_dirs: list[str] | None = None,\n        runtime_library_dirs: list[str] | None = None,\n        export_symbols: list[str] | None = None,\n        debug: bool | Literal[0, 1] = 0,\n        extra_preargs: list[str] | None = None,\n        extra_postargs: list[str] | None = None,\n        build_temp: str | None = None,\n        target_lang: str | None = None,\n    ) -> None: ...\n    def link_shared_object(\n        self,\n        objects: list[str],\n        output_filename: str,\n        output_dir: str | None = None,\n        libraries: list[str] | None = None,\n        library_dirs: list[str] | None = None,\n        runtime_library_dirs: list[str] | None = None,\n        export_symbols: list[str] | None = None,\n        debug: bool | Literal[0, 1] = 0,\n        extra_preargs: list[str] | None = None,\n        extra_postargs: list[str] | None = None,\n        build_temp: str | None = None,\n        target_lang: str | None = None,\n    ) -> None: ...\n    def preprocess(\n        self,\n        source: str,\n        output_file: str | None = None,\n        macros: list[_Macro] | None = None,\n        include_dirs: list[str] | None = None,\n        extra_preargs: list[str] | None = None,\n        extra_postargs: list[str] | None = None,\n    ) -> None: ...\n    @overload\n    def executable_filename(self, basename: str, strip_dir: Literal[0, False] = 0, output_dir: StrPath = \"\") -> str: ...\n    @overload\n    def executable_filename(self, basename: StrPath, strip_dir: Literal[1, True], output_dir: StrPath = \"\") -> str: ...\n    def library_filename(\n        self, libname: str, lib_type: str = \"static\", strip_dir: bool | Literal[0, 1] = 0, output_dir: StrPath = \"\"\n    ) -> str: ...\n    def object_filenames(\n        self, source_filenames: Iterable[StrPath], strip_dir: bool | Literal[0, 1] = 0, output_dir: StrPath | None = \"\"\n    ) -> list[str]: ...\n    @overload\n    def shared_object_filename(self, basename: str, strip_dir: Literal[0, False] = 0, output_dir: StrPath = \"\") -> str: ...\n    @overload\n    def shared_object_filename(self, basename: StrPath, strip_dir: Literal[1, True], output_dir: StrPath = \"\") -> str: ...\n    def execute(\n        self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1\n    ) -> None: ...\n    def spawn(self, cmd: Iterable[str]) -> None: ...\n    def mkpath(self, name: str, mode: int = 0o777) -> None: ...\n    @overload\n    def move_file(self, src: StrPath, dst: _StrPathT) -> _StrPathT | str: ...\n    @overload\n    def move_file(self, src: BytesPath, dst: _BytesPathT) -> _BytesPathT | bytes: ...\n    def announce(self, msg: str, level: int = 1) -> None: ...\n    def warn(self, msg: str) -> None: ...\n    def debug_print(self, msg: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/cmd.pyi",
    "content": "from _typeshed import BytesPath, StrOrBytesPath, StrPath, Unused\nfrom abc import abstractmethod\nfrom collections.abc import Callable, Iterable\nfrom distutils.command.bdist import bdist\nfrom distutils.command.bdist_dumb import bdist_dumb\nfrom distutils.command.bdist_rpm import bdist_rpm\nfrom distutils.command.build import build\nfrom distutils.command.build_clib import build_clib\nfrom distutils.command.build_ext import build_ext\nfrom distutils.command.build_py import build_py\nfrom distutils.command.build_scripts import build_scripts\nfrom distutils.command.check import check\nfrom distutils.command.clean import clean\nfrom distutils.command.config import config\nfrom distutils.command.install import install\nfrom distutils.command.install_data import install_data\nfrom distutils.command.install_egg_info import install_egg_info\nfrom distutils.command.install_headers import install_headers\nfrom distutils.command.install_lib import install_lib\nfrom distutils.command.install_scripts import install_scripts\nfrom distutils.command.register import register\nfrom distutils.command.sdist import sdist\nfrom distutils.command.upload import upload\nfrom distutils.dist import Distribution\nfrom distutils.file_util import _BytesPathT, _StrPathT\nfrom typing import Any, ClassVar, Literal, TypeVar, overload\nfrom typing_extensions import TypeVarTuple, Unpack\n\n_CommandT = TypeVar(\"_CommandT\", bound=Command)\n_Ts = TypeVarTuple(\"_Ts\")\n\nclass Command:\n    dry_run: bool | Literal[0, 1]  # Exposed from __getattr_. Same as Distribution.dry_run\n    distribution: Distribution\n    # Any to work around variance issues\n    sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]]\n    def __init__(self, dist: Distribution) -> None: ...\n    @abstractmethod\n    def initialize_options(self) -> None: ...\n    @abstractmethod\n    def finalize_options(self) -> None: ...\n    @abstractmethod\n    def run(self) -> None: ...\n    def announce(self, msg: str, level: int = 1) -> None: ...\n    def debug_print(self, msg: str) -> None: ...\n    def ensure_string(self, option: str, default: str | None = None) -> None: ...\n    def ensure_string_list(self, option: str) -> None: ...\n    def ensure_filename(self, option: str) -> None: ...\n    def ensure_dirname(self, option: str) -> None: ...\n    def get_command_name(self) -> str: ...\n    def set_undefined_options(self, src_cmd: str, *option_pairs: tuple[str, str]) -> None: ...\n    # NOTE: This list comes directly from the distutils/command folder. Minus bdist_msi and bdist_wininst.\n    @overload\n    def get_finalized_command(self, command: Literal[\"bdist\"], create: bool | Literal[0, 1] = 1) -> bdist: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"bdist_dumb\"], create: bool | Literal[0, 1] = 1) -> bdist_dumb: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"bdist_rpm\"], create: bool | Literal[0, 1] = 1) -> bdist_rpm: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"build\"], create: bool | Literal[0, 1] = 1) -> build: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"build_clib\"], create: bool | Literal[0, 1] = 1) -> build_clib: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"build_ext\"], create: bool | Literal[0, 1] = 1) -> build_ext: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"build_py\"], create: bool | Literal[0, 1] = 1) -> build_py: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"build_scripts\"], create: bool | Literal[0, 1] = 1) -> build_scripts: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"check\"], create: bool | Literal[0, 1] = 1) -> check: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"clean\"], create: bool | Literal[0, 1] = 1) -> clean: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"config\"], create: bool | Literal[0, 1] = 1) -> config: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"install\"], create: bool | Literal[0, 1] = 1) -> install: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"install_data\"], create: bool | Literal[0, 1] = 1) -> install_data: ...\n    @overload\n    def get_finalized_command(\n        self, command: Literal[\"install_egg_info\"], create: bool | Literal[0, 1] = 1\n    ) -> install_egg_info: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"install_headers\"], create: bool | Literal[0, 1] = 1) -> install_headers: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"install_lib\"], create: bool | Literal[0, 1] = 1) -> install_lib: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"install_scripts\"], create: bool | Literal[0, 1] = 1) -> install_scripts: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"register\"], create: bool | Literal[0, 1] = 1) -> register: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"sdist\"], create: bool | Literal[0, 1] = 1) -> sdist: ...\n    @overload\n    def get_finalized_command(self, command: Literal[\"upload\"], create: bool | Literal[0, 1] = 1) -> upload: ...\n    @overload\n    def get_finalized_command(self, command: str, create: bool | Literal[0, 1] = 1) -> Command: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"bdist\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> bdist: ...\n    @overload\n    def reinitialize_command(\n        self, command: Literal[\"bdist_dumb\"], reinit_subcommands: bool | Literal[0, 1] = 0\n    ) -> bdist_dumb: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"bdist_rpm\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> bdist_rpm: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"build\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> build: ...\n    @overload\n    def reinitialize_command(\n        self, command: Literal[\"build_clib\"], reinit_subcommands: bool | Literal[0, 1] = 0\n    ) -> build_clib: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"build_ext\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> build_ext: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"build_py\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> build_py: ...\n    @overload\n    def reinitialize_command(\n        self, command: Literal[\"build_scripts\"], reinit_subcommands: bool | Literal[0, 1] = 0\n    ) -> build_scripts: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"check\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> check: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"clean\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> clean: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"config\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> config: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"install\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> install: ...\n    @overload\n    def reinitialize_command(\n        self, command: Literal[\"install_data\"], reinit_subcommands: bool | Literal[0, 1] = 0\n    ) -> install_data: ...\n    @overload\n    def reinitialize_command(\n        self, command: Literal[\"install_egg_info\"], reinit_subcommands: bool | Literal[0, 1] = 0\n    ) -> install_egg_info: ...\n    @overload\n    def reinitialize_command(\n        self, command: Literal[\"install_headers\"], reinit_subcommands: bool | Literal[0, 1] = 0\n    ) -> install_headers: ...\n    @overload\n    def reinitialize_command(\n        self, command: Literal[\"install_lib\"], reinit_subcommands: bool | Literal[0, 1] = 0\n    ) -> install_lib: ...\n    @overload\n    def reinitialize_command(\n        self, command: Literal[\"install_scripts\"], reinit_subcommands: bool | Literal[0, 1] = 0\n    ) -> install_scripts: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"register\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> register: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"sdist\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> sdist: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"upload\"], reinit_subcommands: bool | Literal[0, 1] = 0) -> upload: ...\n    @overload\n    def reinitialize_command(self, command: str, reinit_subcommands: bool | Literal[0, 1] = 0) -> Command: ...\n    @overload\n    def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool | Literal[0, 1] = 0) -> _CommandT: ...\n    def run_command(self, command: str) -> None: ...\n    def get_sub_commands(self) -> list[str]: ...\n    def warn(self, msg: str) -> None: ...\n    def execute(\n        self, func: Callable[[Unpack[_Ts]], Unused], args: tuple[Unpack[_Ts]], msg: str | None = None, level: int = 1\n    ) -> None: ...\n    def mkpath(self, name: str, mode: int = 0o777) -> None: ...\n    @overload\n    def copy_file(\n        self,\n        infile: StrPath,\n        outfile: _StrPathT,\n        preserve_mode: bool | Literal[0, 1] = 1,\n        preserve_times: bool | Literal[0, 1] = 1,\n        link: str | None = None,\n        level: Unused = 1,\n    ) -> tuple[_StrPathT | str, bool]: ...\n    @overload\n    def copy_file(\n        self,\n        infile: BytesPath,\n        outfile: _BytesPathT,\n        preserve_mode: bool | Literal[0, 1] = 1,\n        preserve_times: bool | Literal[0, 1] = 1,\n        link: str | None = None,\n        level: Unused = 1,\n    ) -> tuple[_BytesPathT | bytes, bool]: ...\n    def copy_tree(\n        self,\n        infile: StrPath,\n        outfile: str,\n        preserve_mode: bool | Literal[0, 1] = 1,\n        preserve_times: bool | Literal[0, 1] = 1,\n        preserve_symlinks: bool | Literal[0, 1] = 0,\n        level: Unused = 1,\n    ) -> list[str]: ...\n    @overload\n    def move_file(self, src: StrPath, dst: _StrPathT, level: Unused = 1) -> _StrPathT | str: ...\n    @overload\n    def move_file(self, src: BytesPath, dst: _BytesPathT, level: Unused = 1) -> _BytesPathT | bytes: ...\n    def spawn(self, cmd: Iterable[str], search_path: bool | Literal[0, 1] = 1, level: Unused = 1) -> None: ...\n    @overload\n    def make_archive(\n        self,\n        base_name: str,\n        format: str,\n        root_dir: StrOrBytesPath | None = None,\n        base_dir: str | None = None,\n        owner: str | None = None,\n        group: str | None = None,\n    ) -> str: ...\n    @overload\n    def make_archive(\n        self,\n        base_name: StrPath,\n        format: str,\n        root_dir: StrOrBytesPath,\n        base_dir: str | None = None,\n        owner: str | None = None,\n        group: str | None = None,\n    ) -> str: ...\n    def make_file(\n        self,\n        infiles: str | list[str] | tuple[str, ...],\n        outfile: StrOrBytesPath,\n        func: Callable[[Unpack[_Ts]], Unused],\n        args: tuple[Unpack[_Ts]],\n        exec_msg: str | None = None,\n        skip_msg: str | None = None,\n        level: Unused = 1,\n    ) -> None: ...\n    def ensure_finalized(self) -> None: ...\n    def dump_options(self, header=None, indent: str = \"\") -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/__init__.pyi",
    "content": "import sys\n\nfrom . import (\n    bdist,\n    bdist_dumb,\n    bdist_rpm,\n    build,\n    build_clib,\n    build_ext,\n    build_py,\n    build_scripts,\n    check,\n    clean,\n    install,\n    install_data,\n    install_headers,\n    install_lib,\n    install_scripts,\n    register,\n    sdist,\n    upload,\n)\n\n__all__ = [\n    \"build\",\n    \"build_py\",\n    \"build_ext\",\n    \"build_clib\",\n    \"build_scripts\",\n    \"clean\",\n    \"install\",\n    \"install_lib\",\n    \"install_headers\",\n    \"install_scripts\",\n    \"install_data\",\n    \"sdist\",\n    \"register\",\n    \"bdist\",\n    \"bdist_dumb\",\n    \"bdist_rpm\",\n    \"check\",\n    \"upload\",\n]\n\nif sys.version_info < (3, 10):\n    from . import bdist_wininst\n\n    __all__ += [\"bdist_wininst\"]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/bdist.pyi",
    "content": "from _typeshed import Incomplete, Unused\nfrom collections.abc import Callable\nfrom typing import ClassVar\n\nfrom ..cmd import Command\n\ndef show_formats() -> None: ...\n\nclass bdist(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]]\n    no_format_option: ClassVar[tuple[str, ...]]\n    default_format: ClassVar[dict[str, str]]\n    format_commands: ClassVar[list[str]]\n    format_command: ClassVar[dict[str, tuple[str, str]]]\n    bdist_base: Incomplete\n    plat_name: Incomplete\n    formats: Incomplete\n    dist_dir: Incomplete\n    skip_build: int\n    group: Incomplete\n    owner: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/bdist_dumb.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar\n\nfrom ..cmd import Command\n\nclass bdist_dumb(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    default_format: ClassVar[dict[str, str]]\n    bdist_dir: Incomplete\n    plat_name: Incomplete\n    format: Incomplete\n    keep_temp: int\n    dist_dir: Incomplete\n    skip_build: Incomplete\n    relative: int\n    owner: Incomplete\n    group: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/bdist_msi.pyi",
    "content": "import sys\nfrom _typeshed import Incomplete\nfrom typing import ClassVar, Literal\n\nfrom ..cmd import Command\n\nif sys.platform == \"win32\":\n    from msilib import Control, Dialog\n\n    class PyDialog(Dialog):\n        def __init__(self, *args, **kw) -> None: ...\n        def title(self, title) -> None: ...\n        def back(self, title, next, name: str = \"Back\", active: bool | Literal[0, 1] = 1) -> Control: ...\n        def cancel(self, title, next, name: str = \"Cancel\", active: bool | Literal[0, 1] = 1) -> Control: ...\n        def next(self, title, next, name: str = \"Next\", active: bool | Literal[0, 1] = 1) -> Control: ...\n        def xbutton(self, name, title, next, xpos) -> Control: ...\n\n    class bdist_msi(Command):\n        description: str\n        user_options: ClassVar[list[tuple[str, str | None, str]]]\n        boolean_options: ClassVar[list[str]]\n        all_versions: Incomplete\n        other_version: str\n        def __init__(self, *args, **kw) -> None: ...\n        bdist_dir: Incomplete\n        plat_name: Incomplete\n        keep_temp: int\n        no_target_compile: int\n        no_target_optimize: int\n        target_version: Incomplete\n        dist_dir: Incomplete\n        skip_build: Incomplete\n        install_script: Incomplete\n        pre_install_script: Incomplete\n        versions: Incomplete\n        def initialize_options(self) -> None: ...\n        install_script_key: Incomplete\n        def finalize_options(self) -> None: ...\n        db: Incomplete\n        def run(self) -> None: ...\n        def add_files(self) -> None: ...\n        def add_find_python(self) -> None: ...\n        def add_scripts(self) -> None: ...\n        def add_ui(self) -> None: ...\n        def get_installer_filename(self, fullname): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/bdist_packager.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/bdist_rpm.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar\n\nfrom ..cmd import Command\n\nclass bdist_rpm(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    negative_opt: ClassVar[dict[str, str]]\n    bdist_base: Incomplete\n    rpm_base: Incomplete\n    dist_dir: Incomplete\n    python: Incomplete\n    fix_python: Incomplete\n    spec_only: Incomplete\n    binary_only: Incomplete\n    source_only: Incomplete\n    use_bzip2: Incomplete\n    distribution_name: Incomplete\n    group: Incomplete\n    release: Incomplete\n    serial: Incomplete\n    vendor: Incomplete\n    packager: Incomplete\n    doc_files: Incomplete\n    changelog: Incomplete\n    icon: Incomplete\n    prep_script: Incomplete\n    build_script: Incomplete\n    install_script: Incomplete\n    clean_script: Incomplete\n    verify_script: Incomplete\n    pre_install: Incomplete\n    post_install: Incomplete\n    pre_uninstall: Incomplete\n    post_uninstall: Incomplete\n    prep: Incomplete\n    provides: Incomplete\n    requires: Incomplete\n    conflicts: Incomplete\n    build_requires: Incomplete\n    obsoletes: Incomplete\n    keep_temp: int\n    use_rpm_opt_flags: int\n    rpm3_mode: int\n    no_autoreq: int\n    force_arch: Incomplete\n    quiet: int\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def finalize_package_data(self) -> None: ...\n    def run(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/bdist_wininst.pyi",
    "content": "from _typeshed import StrOrBytesPath\nfrom distutils.cmd import Command\nfrom typing import ClassVar\n\nclass bdist_wininst(Command):\n    description: ClassVar[str]\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def get_inidata(self) -> str: ...\n    def create_exe(self, arcname: StrOrBytesPath, fullname: str, bitmap: StrOrBytesPath | None = None) -> None: ...\n    def get_installer_filename(self, fullname: str) -> str: ...\n    def get_exe_bytes(self) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/build.pyi",
    "content": "from _typeshed import Incomplete, Unused\nfrom collections.abc import Callable\nfrom typing import Any, ClassVar\n\nfrom ..cmd import Command\n\ndef show_compilers() -> None: ...\n\nclass build(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]]\n    build_base: str\n    build_purelib: Incomplete\n    build_platlib: Incomplete\n    build_lib: Incomplete\n    build_temp: Incomplete\n    build_scripts: Incomplete\n    compiler: Incomplete\n    plat_name: Incomplete\n    debug: Incomplete\n    force: int\n    executable: Incomplete\n    parallel: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def has_pure_modules(self): ...\n    def has_c_libraries(self): ...\n    def has_ext_modules(self): ...\n    def has_scripts(self): ...\n    # Any to work around variance issues\n    sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/build_clib.pyi",
    "content": "from _typeshed import Incomplete, Unused\nfrom collections.abc import Callable\nfrom typing import ClassVar\n\nfrom ..cmd import Command\n\ndef show_compilers() -> None: ...\n\nclass build_clib(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str, str]]]\n    boolean_options: ClassVar[list[str]]\n    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]]\n    build_clib: Incomplete\n    build_temp: Incomplete\n    libraries: Incomplete\n    include_dirs: Incomplete\n    define: Incomplete\n    undef: Incomplete\n    debug: Incomplete\n    force: int\n    compiler: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def check_library_list(self, libraries) -> None: ...\n    def get_library_names(self): ...\n    def get_source_files(self): ...\n    def build_libraries(self, libraries) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/build_ext.pyi",
    "content": "from _typeshed import Incomplete, Unused\nfrom collections.abc import Callable\nfrom typing import ClassVar\n\nfrom ..cmd import Command\n\nextension_name_re: Incomplete\n\ndef show_compilers() -> None: ...\n\nclass build_ext(Command):\n    description: str\n    sep_by: Incomplete\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]]\n    extensions: Incomplete\n    build_lib: Incomplete\n    plat_name: Incomplete\n    build_temp: Incomplete\n    inplace: int\n    package: Incomplete\n    include_dirs: Incomplete\n    define: Incomplete\n    undef: Incomplete\n    libraries: Incomplete\n    library_dirs: Incomplete\n    rpath: Incomplete\n    link_objects: Incomplete\n    debug: Incomplete\n    force: Incomplete\n    compiler: Incomplete\n    swig: Incomplete\n    swig_cpp: Incomplete\n    swig_opts: Incomplete\n    user: Incomplete\n    parallel: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def check_extensions_list(self, extensions) -> None: ...\n    def get_source_files(self): ...\n    def get_outputs(self): ...\n    def build_extensions(self) -> None: ...\n    def build_extension(self, ext) -> None: ...\n    def swig_sources(self, sources, extension): ...\n    def find_swig(self): ...\n    def get_ext_fullpath(self, ext_name: str) -> str: ...\n    def get_ext_fullname(self, ext_name: str) -> str: ...\n    def get_ext_filename(self, ext_name: str) -> str: ...\n    def get_export_symbols(self, ext): ...\n    def get_libraries(self, ext): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/build_py.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar, Literal\n\nfrom ..cmd import Command\nfrom ..util import Mixin2to3 as Mixin2to3\n\nclass build_py(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    negative_opt: ClassVar[dict[str, str]]\n    build_lib: Incomplete\n    py_modules: Incomplete\n    package: Incomplete\n    package_data: Incomplete\n    package_dir: Incomplete\n    compile: int\n    optimize: int\n    force: Incomplete\n    def initialize_options(self) -> None: ...\n    packages: Incomplete\n    data_files: Incomplete\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def get_data_files(self): ...\n    def find_data_files(self, package, src_dir): ...\n    def build_package_data(self) -> None: ...\n    def get_package_dir(self, package): ...\n    def check_package(self, package, package_dir): ...\n    def check_module(self, module, module_file): ...\n    def find_package_modules(self, package, package_dir): ...\n    def find_modules(self): ...\n    def find_all_modules(self): ...\n    def get_source_files(self): ...\n    def get_module_outfile(self, build_dir, package, module): ...\n    def get_outputs(self, include_bytecode: bool | Literal[0, 1] = 1) -> list[str]: ...\n    def build_module(self, module, module_file, package): ...\n    def build_modules(self) -> None: ...\n    def build_packages(self) -> None: ...\n    def byte_compile(self, files) -> None: ...\n\nclass build_py_2to3(build_py, Mixin2to3):\n    updated_files: Incomplete\n    def run(self) -> None: ...\n    def build_module(self, module, module_file, package): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/build_scripts.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar\n\nfrom ..cmd import Command\nfrom ..util import Mixin2to3 as Mixin2to3\n\nfirst_line_re: Incomplete\n\nclass build_scripts(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str, str]]]\n    boolean_options: ClassVar[list[str]]\n    build_dir: Incomplete\n    scripts: Incomplete\n    force: Incomplete\n    executable: Incomplete\n    outfiles: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def get_source_files(self): ...\n    def run(self) -> None: ...\n    def copy_scripts(self): ...\n\nclass build_scripts_2to3(build_scripts, Mixin2to3):\n    def copy_scripts(self): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/check.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import Any, ClassVar, Final, Literal\nfrom typing_extensions import TypeAlias\n\nfrom ..cmd import Command\n\n_Reporter: TypeAlias = Any  # really docutils.utils.Reporter\n\n# Only defined if docutils is installed.\n# Depends on a third-party stub. Since distutils is deprecated anyway,\n# it's easier to just suppress the \"any subclassing\" error.\nclass SilentReporter(_Reporter):\n    messages: Incomplete\n    def __init__(\n        self,\n        source,\n        report_level,\n        halt_level,\n        stream: Incomplete | None = ...,\n        debug: bool | Literal[0, 1] = 0,\n        encoding: str = ...,\n        error_handler: str = ...,\n    ) -> None: ...\n    def system_message(self, level, message, *children, **kwargs): ...\n\nHAS_DOCUTILS: Final[bool]\n\nclass check(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str, str]]]\n    boolean_options: ClassVar[list[str]]\n    restructuredtext: int\n    metadata: int\n    strict: int\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def warn(self, msg): ...\n    def run(self) -> None: ...\n    def check_metadata(self) -> None: ...\n    def check_restructuredtext(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/clean.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar\n\nfrom ..cmd import Command\n\nclass clean(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    build_base: Incomplete\n    build_lib: Incomplete\n    build_temp: Incomplete\n    build_scripts: Incomplete\n    bdist_base: Incomplete\n    all: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/config.pyi",
    "content": "from _typeshed import StrOrBytesPath\nfrom collections.abc import Sequence\nfrom re import Pattern\nfrom typing import ClassVar, Final, Literal\n\nfrom ..ccompiler import CCompiler\nfrom ..cmd import Command\n\nLANG_EXT: Final[dict[str, str]]\n\nclass config(Command):\n    description: str\n    # Tuple is full name, short name, description\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    compiler: str | CCompiler\n    cc: str | None\n    include_dirs: Sequence[str] | None\n    libraries: Sequence[str] | None\n    library_dirs: Sequence[str] | None\n    noisy: int\n    dump_source: int\n    temp_files: Sequence[str]\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def try_cpp(\n        self,\n        body: str | None = None,\n        headers: Sequence[str] | None = None,\n        include_dirs: Sequence[str] | None = None,\n        lang: str = \"c\",\n    ) -> bool: ...\n    def search_cpp(\n        self,\n        pattern: Pattern[str] | str,\n        body: str | None = None,\n        headers: Sequence[str] | None = None,\n        include_dirs: Sequence[str] | None = None,\n        lang: str = \"c\",\n    ) -> bool: ...\n    def try_compile(\n        self, body: str, headers: Sequence[str] | None = None, include_dirs: Sequence[str] | None = None, lang: str = \"c\"\n    ) -> bool: ...\n    def try_link(\n        self,\n        body: str,\n        headers: Sequence[str] | None = None,\n        include_dirs: Sequence[str] | None = None,\n        libraries: Sequence[str] | None = None,\n        library_dirs: Sequence[str] | None = None,\n        lang: str = \"c\",\n    ) -> bool: ...\n    def try_run(\n        self,\n        body: str,\n        headers: Sequence[str] | None = None,\n        include_dirs: Sequence[str] | None = None,\n        libraries: Sequence[str] | None = None,\n        library_dirs: Sequence[str] | None = None,\n        lang: str = \"c\",\n    ) -> bool: ...\n    def check_func(\n        self,\n        func: str,\n        headers: Sequence[str] | None = None,\n        include_dirs: Sequence[str] | None = None,\n        libraries: Sequence[str] | None = None,\n        library_dirs: Sequence[str] | None = None,\n        decl: bool | Literal[0, 1] = 0,\n        call: bool | Literal[0, 1] = 0,\n    ) -> bool: ...\n    def check_lib(\n        self,\n        library: str,\n        library_dirs: Sequence[str] | None = None,\n        headers: Sequence[str] | None = None,\n        include_dirs: Sequence[str] | None = None,\n        other_libraries: list[str] = [],\n    ) -> bool: ...\n    def check_header(\n        self, header: str, include_dirs: Sequence[str] | None = None, library_dirs: Sequence[str] | None = None, lang: str = \"c\"\n    ) -> bool: ...\n\ndef dump_file(filename: StrOrBytesPath, head=None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/install.pyi",
    "content": "import sys\nfrom _typeshed import Incomplete\nfrom collections.abc import Callable\nfrom typing import Any, ClassVar, Final, Literal\n\nfrom ..cmd import Command\n\nHAS_USER_SITE: Final[bool]\n\nSCHEME_KEYS: Final[tuple[Literal[\"purelib\"], Literal[\"platlib\"], Literal[\"headers\"], Literal[\"scripts\"], Literal[\"data\"]]]\nINSTALL_SCHEMES: Final[dict[str, dict[str, str]]]\n\nif sys.version_info < (3, 10):\n    WINDOWS_SCHEME: Final[dict[str, str]]\n\nclass install(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    negative_opt: ClassVar[dict[str, str]]\n    prefix: str | None\n    exec_prefix: Incomplete\n    home: str | None\n    user: bool\n    install_base: Incomplete\n    install_platbase: Incomplete\n    root: str | None\n    install_purelib: Incomplete\n    install_platlib: Incomplete\n    install_headers: Incomplete\n    install_lib: str | None\n    install_scripts: Incomplete\n    install_data: Incomplete\n    install_userbase: Incomplete\n    install_usersite: Incomplete\n    compile: Incomplete\n    optimize: Incomplete\n    extra_path: Incomplete\n    install_path_file: int\n    force: int\n    skip_build: int\n    warn_dir: int\n    build_base: Incomplete\n    build_lib: Incomplete\n    record: Incomplete\n    def initialize_options(self) -> None: ...\n    config_vars: Incomplete\n    install_libbase: Incomplete\n    def finalize_options(self) -> None: ...\n    def dump_dirs(self, msg) -> None: ...\n    def finalize_unix(self) -> None: ...\n    def finalize_other(self) -> None: ...\n    def select_scheme(self, name) -> None: ...\n    def expand_basedirs(self) -> None: ...\n    def expand_dirs(self) -> None: ...\n    def convert_paths(self, *names) -> None: ...\n    path_file: Incomplete\n    extra_dirs: Incomplete\n    def handle_extra_path(self) -> None: ...\n    def change_roots(self, *names) -> None: ...\n    def create_home_path(self) -> None: ...\n    def run(self) -> None: ...\n    def create_path_file(self) -> None: ...\n    def get_outputs(self): ...\n    def get_inputs(self): ...\n    def has_lib(self): ...\n    def has_headers(self): ...\n    def has_scripts(self): ...\n    def has_data(self): ...\n    # Any to work around variance issues\n    sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/install_data.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar\n\nfrom ..cmd import Command\n\nclass install_data(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    install_dir: Incomplete\n    outfiles: Incomplete\n    root: Incomplete\n    force: int\n    data_files: Incomplete\n    warn_dir: int\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def get_inputs(self): ...\n    def get_outputs(self): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/install_egg_info.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar\n\nfrom ..cmd import Command\n\nclass install_egg_info(Command):\n    description: ClassVar[str]\n    user_options: ClassVar[list[tuple[str, str, str]]]\n    install_dir: Incomplete\n    def initialize_options(self) -> None: ...\n    target: Incomplete\n    outputs: Incomplete\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def get_outputs(self) -> list[str]: ...\n\ndef safe_name(name): ...\ndef safe_version(version): ...\ndef to_filename(name): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/install_headers.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar\n\nfrom ..cmd import Command\n\nclass install_headers(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str, str]]]\n    boolean_options: ClassVar[list[str]]\n    install_dir: Incomplete\n    force: int\n    outfiles: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def get_inputs(self): ...\n    def get_outputs(self): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/install_lib.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar, Final\n\nfrom ..cmd import Command\n\nPYTHON_SOURCE_EXTENSION: Final = \".py\"\n\nclass install_lib(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    negative_opt: ClassVar[dict[str, str]]\n    install_dir: Incomplete\n    build_dir: Incomplete\n    force: int\n    compile: Incomplete\n    optimize: Incomplete\n    skip_build: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def build(self) -> None: ...\n    def install(self): ...\n    def byte_compile(self, files) -> None: ...\n    def get_outputs(self): ...\n    def get_inputs(self): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/install_scripts.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar\n\nfrom ..cmd import Command\n\nclass install_scripts(Command):\n    description: str\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    install_dir: Incomplete\n    force: int\n    build_dir: Incomplete\n    skip_build: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    outfiles: Incomplete\n    def run(self) -> None: ...\n    def get_inputs(self): ...\n    def get_outputs(self): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/register.pyi",
    "content": "from collections.abc import Callable\nfrom typing import Any, ClassVar\n\nfrom ..config import PyPIRCCommand\n\nclass register(PyPIRCCommand):\n    description: str\n    # Any to work around variance issues\n    sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]]\n    list_classifiers: int\n    strict: int\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def check_metadata(self) -> None: ...\n    def classifiers(self) -> None: ...\n    def verify_metadata(self) -> None: ...\n    def send_metadata(self) -> None: ...\n    def build_post_data(self, action): ...\n    def post_to_server(self, data, auth=None): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/sdist.pyi",
    "content": "from _typeshed import Incomplete, Unused\nfrom collections.abc import Callable\nfrom typing import Any, ClassVar\n\nfrom ..cmd import Command\n\ndef show_formats() -> None: ...\n\nclass sdist(Command):\n    description: str\n    def checking_metadata(self): ...\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    help_options: ClassVar[list[tuple[str, str | None, str, Callable[[], Unused]]]]\n    negative_opt: ClassVar[dict[str, str]]\n    # Any to work around variance issues\n    sub_commands: ClassVar[list[tuple[str, Callable[[Any], bool] | None]]]\n    READMES: ClassVar[tuple[str, ...]]\n    template: Incomplete\n    manifest: Incomplete\n    use_defaults: int\n    prune: int\n    manifest_only: int\n    force_manifest: int\n    formats: Incomplete\n    keep_temp: int\n    dist_dir: Incomplete\n    archive_files: Incomplete\n    metadata_check: int\n    owner: Incomplete\n    group: Incomplete\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    filelist: Incomplete\n    def run(self) -> None: ...\n    def check_metadata(self) -> None: ...\n    def get_file_list(self) -> None: ...\n    def add_defaults(self) -> None: ...\n    def read_template(self) -> None: ...\n    def prune_file_list(self) -> None: ...\n    def write_manifest(self) -> None: ...\n    def read_manifest(self) -> None: ...\n    def make_release_tree(self, base_dir, files) -> None: ...\n    def make_distribution(self) -> None: ...\n    def get_archive_files(self): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/command/upload.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar\n\nfrom ..config import PyPIRCCommand\n\nclass upload(PyPIRCCommand):\n    description: ClassVar[str]\n    username: str\n    password: str\n    show_response: int\n    sign: bool\n    identity: Incomplete\n    def initialize_options(self) -> None: ...\n    repository: Incomplete\n    realm: Incomplete\n    def finalize_options(self) -> None: ...\n    def run(self) -> None: ...\n    def upload_file(self, command: str, pyversion: str, filename: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/config.pyi",
    "content": "from abc import abstractmethod\nfrom distutils.cmd import Command\nfrom typing import ClassVar\n\nDEFAULT_PYPIRC: str\n\nclass PyPIRCCommand(Command):\n    DEFAULT_REPOSITORY: ClassVar[str]\n    DEFAULT_REALM: ClassVar[str]\n    repository: None\n    realm: None\n    user_options: ClassVar[list[tuple[str, str | None, str]]]\n    boolean_options: ClassVar[list[str]]\n    def initialize_options(self) -> None: ...\n    def finalize_options(self) -> None: ...\n    @abstractmethod\n    def run(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/core.pyi",
    "content": "from _typeshed import Incomplete, StrOrBytesPath\nfrom collections.abc import Mapping\nfrom distutils.cmd import Command as Command\nfrom distutils.dist import Distribution as Distribution\nfrom distutils.extension import Extension as Extension\nfrom typing import Any, Final, Literal\n\nUSAGE: Final[str]\n\ndef gen_usage(script_name: StrOrBytesPath) -> str: ...\n\nsetup_keywords: tuple[str, ...]\nextension_keywords: tuple[str, ...]\n\ndef setup(\n    *,\n    name: str = ...,\n    version: str = ...,\n    description: str = ...,\n    long_description: str = ...,\n    author: str = ...,\n    author_email: str = ...,\n    maintainer: str = ...,\n    maintainer_email: str = ...,\n    url: str = ...,\n    download_url: str = ...,\n    packages: list[str] = ...,\n    py_modules: list[str] = ...,\n    scripts: list[str] = ...,\n    ext_modules: list[Extension] = ...,\n    classifiers: list[str] = ...,\n    distclass: type[Distribution] = ...,\n    script_name: str = ...,\n    script_args: list[str] = ...,\n    options: Mapping[str, Incomplete] = ...,\n    license: str = ...,\n    keywords: list[str] | str = ...,\n    platforms: list[str] | str = ...,\n    cmdclass: Mapping[str, type[Command]] = ...,\n    data_files: list[tuple[str, list[str]]] = ...,\n    package_dir: Mapping[str, str] = ...,\n    obsoletes: list[str] = ...,\n    provides: list[str] = ...,\n    requires: list[str] = ...,\n    command_packages: list[str] = ...,\n    command_options: Mapping[str, Mapping[str, tuple[Incomplete, Incomplete]]] = ...,\n    package_data: Mapping[str, list[str]] = ...,\n    include_package_data: bool | Literal[0, 1] = ...,\n    libraries: list[str] = ...,\n    headers: list[str] = ...,\n    ext_package: str = ...,\n    include_dirs: list[str] = ...,\n    password: str = ...,\n    fullname: str = ...,\n    # Custom Distributions could accept more params\n    **attrs: Any,\n) -> Distribution: ...\ndef run_setup(script_name: str, script_args: list[str] | None = None, stop_after: str = \"run\") -> Distribution: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/cygwinccompiler.pyi",
    "content": "from distutils.unixccompiler import UnixCCompiler\nfrom distutils.version import LooseVersion\nfrom re import Pattern\nfrom typing import Final, Literal\n\ndef get_msvcr() -> list[str] | None: ...\n\nclass CygwinCCompiler(UnixCCompiler): ...\nclass Mingw32CCompiler(CygwinCCompiler): ...\n\nCONFIG_H_OK: Final = \"ok\"\nCONFIG_H_NOTOK: Final = \"not ok\"\nCONFIG_H_UNCERTAIN: Final = \"uncertain\"\n\ndef check_config_h() -> tuple[Literal[\"ok\", \"not ok\", \"uncertain\"], str]: ...\n\nRE_VERSION: Final[Pattern[bytes]]\n\ndef get_versions() -> tuple[LooseVersion | None, ...]: ...\ndef is_cygwingcc() -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/debug.pyi",
    "content": "from typing import Final\n\nDEBUG: Final[str | None]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/dep_util.pyi",
    "content": "from _typeshed import StrOrBytesPath, SupportsLenAndGetItem\nfrom collections.abc import Iterable\nfrom typing import Literal, TypeVar\n\n_SourcesT = TypeVar(\"_SourcesT\", bound=StrOrBytesPath)\n_TargetsT = TypeVar(\"_TargetsT\", bound=StrOrBytesPath)\n\ndef newer(source: StrOrBytesPath, target: StrOrBytesPath) -> bool | Literal[1]: ...\ndef newer_pairwise(\n    sources: SupportsLenAndGetItem[_SourcesT], targets: SupportsLenAndGetItem[_TargetsT]\n) -> tuple[list[_SourcesT], list[_TargetsT]]: ...\ndef newer_group(\n    sources: Iterable[StrOrBytesPath], target: StrOrBytesPath, missing: Literal[\"error\", \"ignore\", \"newer\"] = \"error\"\n) -> Literal[0, 1]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/dir_util.pyi",
    "content": "from _typeshed import StrOrBytesPath, StrPath\nfrom collections.abc import Iterable\nfrom typing import Literal\n\ndef mkpath(name: str, mode: int = 0o777, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0) -> list[str]: ...\ndef create_tree(\n    base_dir: StrPath,\n    files: Iterable[StrPath],\n    mode: int = 0o777,\n    verbose: bool | Literal[0, 1] = 1,\n    dry_run: bool | Literal[0, 1] = 0,\n) -> None: ...\ndef copy_tree(\n    src: StrPath,\n    dst: str,\n    preserve_mode: bool | Literal[0, 1] = 1,\n    preserve_times: bool | Literal[0, 1] = 1,\n    preserve_symlinks: bool | Literal[0, 1] = 0,\n    update: bool | Literal[0, 1] = 0,\n    verbose: bool | Literal[0, 1] = 1,\n    dry_run: bool | Literal[0, 1] = 0,\n) -> list[str]: ...\ndef remove_tree(directory: StrOrBytesPath, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/dist.pyi",
    "content": "from _typeshed import Incomplete, StrOrBytesPath, StrPath, SupportsWrite\nfrom collections.abc import Iterable, MutableMapping\nfrom distutils.cmd import Command\nfrom distutils.command.bdist import bdist\nfrom distutils.command.bdist_dumb import bdist_dumb\nfrom distutils.command.bdist_rpm import bdist_rpm\nfrom distutils.command.build import build\nfrom distutils.command.build_clib import build_clib\nfrom distutils.command.build_ext import build_ext\nfrom distutils.command.build_py import build_py\nfrom distutils.command.build_scripts import build_scripts\nfrom distutils.command.check import check\nfrom distutils.command.clean import clean\nfrom distutils.command.config import config\nfrom distutils.command.install import install\nfrom distutils.command.install_data import install_data\nfrom distutils.command.install_egg_info import install_egg_info\nfrom distutils.command.install_headers import install_headers\nfrom distutils.command.install_lib import install_lib\nfrom distutils.command.install_scripts import install_scripts\nfrom distutils.command.register import register\nfrom distutils.command.sdist import sdist\nfrom distutils.command.upload import upload\nfrom re import Pattern\nfrom typing import IO, ClassVar, Literal, TypeVar, overload\nfrom typing_extensions import TypeAlias\n\ncommand_re: Pattern[str]\n\n_OptionsList: TypeAlias = list[tuple[str, str | None, str, int] | tuple[str, str | None, str]]\n_CommandT = TypeVar(\"_CommandT\", bound=Command)\n\nclass DistributionMetadata:\n    def __init__(self, path: StrOrBytesPath | None = None) -> None: ...\n    name: str | None\n    version: str | None\n    author: str | None\n    author_email: str | None\n    maintainer: str | None\n    maintainer_email: str | None\n    url: str | None\n    license: str | None\n    description: str | None\n    long_description: str | None\n    keywords: str | list[str] | None\n    platforms: str | list[str] | None\n    classifiers: str | list[str] | None\n    download_url: str | None\n    provides: list[str] | None\n    requires: list[str] | None\n    obsoletes: list[str] | None\n    def read_pkg_file(self, file: IO[str]) -> None: ...\n    def write_pkg_info(self, base_dir: StrPath) -> None: ...\n    def write_pkg_file(self, file: SupportsWrite[str]) -> None: ...\n    def get_name(self) -> str: ...\n    def get_version(self) -> str: ...\n    def get_fullname(self) -> str: ...\n    def get_author(self) -> str: ...\n    def get_author_email(self) -> str: ...\n    def get_maintainer(self) -> str: ...\n    def get_maintainer_email(self) -> str: ...\n    def get_contact(self) -> str: ...\n    def get_contact_email(self) -> str: ...\n    def get_url(self) -> str: ...\n    def get_license(self) -> str: ...\n    def get_licence(self) -> str: ...\n    def get_description(self) -> str: ...\n    def get_long_description(self) -> str: ...\n    def get_keywords(self) -> str | list[str]: ...\n    def get_platforms(self) -> str | list[str]: ...\n    def get_classifiers(self) -> str | list[str]: ...\n    def get_download_url(self) -> str: ...\n    def get_requires(self) -> list[str]: ...\n    def set_requires(self, value: Iterable[str]) -> None: ...\n    def get_provides(self) -> list[str]: ...\n    def set_provides(self, value: Iterable[str]) -> None: ...\n    def get_obsoletes(self) -> list[str]: ...\n    def set_obsoletes(self, value: Iterable[str]) -> None: ...\n\nclass Distribution:\n    cmdclass: dict[str, type[Command]]\n    metadata: DistributionMetadata\n    def __init__(self, attrs: MutableMapping[str, Incomplete] | None = None) -> None: ...\n    def get_option_dict(self, command: str) -> dict[str, tuple[str, str]]: ...\n    def parse_config_files(self, filenames: Iterable[str] | None = None) -> None: ...\n    global_options: ClassVar[_OptionsList]\n    common_usage: ClassVar[str]\n    display_options: ClassVar[_OptionsList]\n    display_option_names: ClassVar[list[str]]\n    negative_opt: ClassVar[dict[str, str]]\n    verbose: bool | Literal[0, 1]\n    dry_run: bool | Literal[0, 1]\n    help: bool | Literal[0, 1]\n    command_packages: list[str] | None\n    script_name: str | None\n    script_args: list[str] | None\n    command_options: dict[str, dict[str, tuple[str, str]]]\n    dist_files: list[tuple[str, str, str]]\n    packages: Incomplete\n    package_data: dict[str, list[str]]\n    package_dir: Incomplete\n    py_modules: Incomplete\n    libraries: Incomplete\n    headers: Incomplete\n    ext_modules: Incomplete\n    ext_package: Incomplete\n    include_dirs: Incomplete\n    extra_path: Incomplete\n    scripts: Incomplete\n    data_files: Incomplete\n    password: str\n    command_obj: Incomplete\n    have_run: Incomplete\n    want_user_cfg: bool\n    def dump_option_dicts(self, header=None, commands=None, indent: str = \"\") -> None: ...\n    def find_config_files(self): ...\n    commands: Incomplete\n    def parse_command_line(self): ...\n    def finalize_options(self) -> None: ...\n    def handle_display_options(self, option_order): ...\n    def print_command_list(self, commands, header, max_length) -> None: ...\n    def print_commands(self) -> None: ...\n    def get_command_list(self): ...\n    def get_command_packages(self): ...\n    # NOTE: This list comes directly from the distutils/command folder. Minus bdist_msi and bdist_wininst.\n    @overload\n    def get_command_obj(self, command: Literal[\"bdist\"], create: Literal[1, True] = 1) -> bdist: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"bdist_dumb\"], create: Literal[1, True] = 1) -> bdist_dumb: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"bdist_rpm\"], create: Literal[1, True] = 1) -> bdist_rpm: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"build\"], create: Literal[1, True] = 1) -> build: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"build_clib\"], create: Literal[1, True] = 1) -> build_clib: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"build_ext\"], create: Literal[1, True] = 1) -> build_ext: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"build_py\"], create: Literal[1, True] = 1) -> build_py: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"build_scripts\"], create: Literal[1, True] = 1) -> build_scripts: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"check\"], create: Literal[1, True] = 1) -> check: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"clean\"], create: Literal[1, True] = 1) -> clean: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"config\"], create: Literal[1, True] = 1) -> config: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"install\"], create: Literal[1, True] = 1) -> install: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"install_data\"], create: Literal[1, True] = 1) -> install_data: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"install_egg_info\"], create: Literal[1, True] = 1) -> install_egg_info: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"install_headers\"], create: Literal[1, True] = 1) -> install_headers: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"install_lib\"], create: Literal[1, True] = 1) -> install_lib: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"install_scripts\"], create: Literal[1, True] = 1) -> install_scripts: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"register\"], create: Literal[1, True] = 1) -> register: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"sdist\"], create: Literal[1, True] = 1) -> sdist: ...\n    @overload\n    def get_command_obj(self, command: Literal[\"upload\"], create: Literal[1, True] = 1) -> upload: ...\n    @overload\n    def get_command_obj(self, command: str, create: Literal[1, True] = 1) -> Command: ...\n    # Not replicating the overloads for \"Command | None\", user may use \"isinstance\"\n    @overload\n    def get_command_obj(self, command: str, create: Literal[0, False]) -> Command | None: ...\n    @overload\n    def get_command_class(self, command: Literal[\"bdist\"]) -> type[bdist]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"bdist_dumb\"]) -> type[bdist_dumb]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"bdist_rpm\"]) -> type[bdist_rpm]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"build\"]) -> type[build]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"build_clib\"]) -> type[build_clib]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"build_ext\"]) -> type[build_ext]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"build_py\"]) -> type[build_py]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"build_scripts\"]) -> type[build_scripts]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"check\"]) -> type[check]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"clean\"]) -> type[clean]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"config\"]) -> type[config]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"install\"]) -> type[install]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"install_data\"]) -> type[install_data]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"install_egg_info\"]) -> type[install_egg_info]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"install_headers\"]) -> type[install_headers]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"install_lib\"]) -> type[install_lib]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"install_scripts\"]) -> type[install_scripts]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"register\"]) -> type[register]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"sdist\"]) -> type[sdist]: ...\n    @overload\n    def get_command_class(self, command: Literal[\"upload\"]) -> type[upload]: ...\n    @overload\n    def get_command_class(self, command: str) -> type[Command]: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"bdist\"], reinit_subcommands: bool = False) -> bdist: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"bdist_dumb\"], reinit_subcommands: bool = False) -> bdist_dumb: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"bdist_rpm\"], reinit_subcommands: bool = False) -> bdist_rpm: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"build\"], reinit_subcommands: bool = False) -> build: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"build_clib\"], reinit_subcommands: bool = False) -> build_clib: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"build_ext\"], reinit_subcommands: bool = False) -> build_ext: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"build_py\"], reinit_subcommands: bool = False) -> build_py: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"build_scripts\"], reinit_subcommands: bool = False) -> build_scripts: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"check\"], reinit_subcommands: bool = False) -> check: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"clean\"], reinit_subcommands: bool = False) -> clean: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"config\"], reinit_subcommands: bool = False) -> config: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"install\"], reinit_subcommands: bool = False) -> install: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"install_data\"], reinit_subcommands: bool = False) -> install_data: ...\n    @overload\n    def reinitialize_command(\n        self, command: Literal[\"install_egg_info\"], reinit_subcommands: bool = False\n    ) -> install_egg_info: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"install_headers\"], reinit_subcommands: bool = False) -> install_headers: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"install_lib\"], reinit_subcommands: bool = False) -> install_lib: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"install_scripts\"], reinit_subcommands: bool = False) -> install_scripts: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"register\"], reinit_subcommands: bool = False) -> register: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"sdist\"], reinit_subcommands: bool = False) -> sdist: ...\n    @overload\n    def reinitialize_command(self, command: Literal[\"upload\"], reinit_subcommands: bool = False) -> upload: ...\n    @overload\n    def reinitialize_command(self, command: str, reinit_subcommands: bool = False) -> Command: ...\n    @overload\n    def reinitialize_command(self, command: _CommandT, reinit_subcommands: bool = False) -> _CommandT: ...\n    def announce(self, msg, level: int = 2) -> None: ...\n    def run_commands(self) -> None: ...\n    def run_command(self, command: str) -> None: ...\n    def has_pure_modules(self) -> bool: ...\n    def has_ext_modules(self) -> bool: ...\n    def has_c_libraries(self) -> bool: ...\n    def has_modules(self) -> bool: ...\n    def has_headers(self) -> bool: ...\n    def has_scripts(self) -> bool: ...\n    def has_data_files(self) -> bool: ...\n    def is_pure(self) -> bool: ...\n\n    # Default getter methods generated in __init__ from self.metadata._METHOD_BASENAMES\n    def get_name(self) -> str: ...\n    def get_version(self) -> str: ...\n    def get_fullname(self) -> str: ...\n    def get_author(self) -> str: ...\n    def get_author_email(self) -> str: ...\n    def get_maintainer(self) -> str: ...\n    def get_maintainer_email(self) -> str: ...\n    def get_contact(self) -> str: ...\n    def get_contact_email(self) -> str: ...\n    def get_url(self) -> str: ...\n    def get_license(self) -> str: ...\n    def get_licence(self) -> str: ...\n    def get_description(self) -> str: ...\n    def get_long_description(self) -> str: ...\n    def get_keywords(self) -> str | list[str]: ...\n    def get_platforms(self) -> str | list[str]: ...\n    def get_classifiers(self) -> str | list[str]: ...\n    def get_download_url(self) -> str: ...\n    def get_requires(self) -> list[str]: ...\n    def get_provides(self) -> list[str]: ...\n    def get_obsoletes(self) -> list[str]: ...\n\n    # Default attributes generated in __init__ from self.display_option_names\n    help_commands: bool | Literal[0]\n    name: str | Literal[0]\n    version: str | Literal[0]\n    fullname: str | Literal[0]\n    author: str | Literal[0]\n    author_email: str | Literal[0]\n    maintainer: str | Literal[0]\n    maintainer_email: str | Literal[0]\n    contact: str | Literal[0]\n    contact_email: str | Literal[0]\n    url: str | Literal[0]\n    license: str | Literal[0]\n    licence: str | Literal[0]\n    description: str | Literal[0]\n    long_description: str | Literal[0]\n    platforms: str | list[str] | Literal[0]\n    classifiers: str | list[str] | Literal[0]\n    keywords: str | list[str] | Literal[0]\n    provides: list[str] | Literal[0]\n    requires: list[str] | Literal[0]\n    obsoletes: list[str] | Literal[0]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/errors.pyi",
    "content": "class DistutilsError(Exception): ...\nclass DistutilsModuleError(DistutilsError): ...\nclass DistutilsClassError(DistutilsError): ...\nclass DistutilsGetoptError(DistutilsError): ...\nclass DistutilsArgError(DistutilsError): ...\nclass DistutilsFileError(DistutilsError): ...\nclass DistutilsOptionError(DistutilsError): ...\nclass DistutilsSetupError(DistutilsError): ...\nclass DistutilsPlatformError(DistutilsError): ...\nclass DistutilsExecError(DistutilsError): ...\nclass DistutilsInternalError(DistutilsError): ...\nclass DistutilsTemplateError(DistutilsError): ...\nclass DistutilsByteCompileError(DistutilsError): ...\nclass CCompilerError(Exception): ...\nclass PreprocessError(CCompilerError): ...\nclass CompileError(CCompilerError): ...\nclass LibError(CCompilerError): ...\nclass LinkError(CCompilerError): ...\nclass UnknownFileError(CCompilerError): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/extension.pyi",
    "content": "class Extension:\n    name: str\n    sources: list[str]\n    include_dirs: list[str]\n    define_macros: list[tuple[str, str | None]]\n    undef_macros: list[str]\n    library_dirs: list[str]\n    libraries: list[str]\n    runtime_library_dirs: list[str]\n    extra_objects: list[str]\n    extra_compile_args: list[str]\n    extra_link_args: list[str]\n    export_symbols: list[str]\n    swig_opts: list[str]\n    depends: list[str]\n    language: str | None\n    optional: bool | None\n    def __init__(\n        self,\n        name: str,\n        sources: list[str],\n        include_dirs: list[str] | None = None,\n        define_macros: list[tuple[str, str | None]] | None = None,\n        undef_macros: list[str] | None = None,\n        library_dirs: list[str] | None = None,\n        libraries: list[str] | None = None,\n        runtime_library_dirs: list[str] | None = None,\n        extra_objects: list[str] | None = None,\n        extra_compile_args: list[str] | None = None,\n        extra_link_args: list[str] | None = None,\n        export_symbols: list[str] | None = None,\n        swig_opts: list[str] | None = None,\n        depends: list[str] | None = None,\n        language: str | None = None,\n        optional: bool | None = None,\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/fancy_getopt.pyi",
    "content": "from collections.abc import Iterable, Mapping\nfrom getopt import _SliceableT, _StrSequenceT_co\nfrom re import Pattern\nfrom typing import Any, Final, overload\nfrom typing_extensions import TypeAlias\n\n_Option: TypeAlias = tuple[str, str | None, str]\n\nlongopt_pat: Final = r\"[a-zA-Z](?:[a-zA-Z0-9-]*)\"\nlongopt_re: Final[Pattern[str]]\nneg_alias_re: Final[Pattern[str]]\nlongopt_xlate: Final[dict[int, int]]\n\nclass FancyGetopt:\n    def __init__(self, option_table: list[_Option] | None = None) -> None: ...\n    # TODO: kinda wrong, `getopt(object=object())` is invalid\n    @overload\n    def getopt(\n        self, args: _SliceableT[_StrSequenceT_co] | None = None, object: None = None\n    ) -> tuple[_StrSequenceT_co, OptionDummy]: ...\n    @overload\n    def getopt(\n        self, args: _SliceableT[_StrSequenceT_co] | None, object: Any\n    ) -> _StrSequenceT_co: ...  # object is an arbitrary non-slotted object\n    def get_option_order(self) -> list[tuple[str, str]]: ...\n    def generate_help(self, header: str | None = None) -> list[str]: ...\n\n# Same note as FancyGetopt.getopt\n@overload\ndef fancy_getopt(\n    options: list[_Option], negative_opt: Mapping[_Option, _Option], object: None, args: _SliceableT[_StrSequenceT_co] | None\n) -> tuple[_StrSequenceT_co, OptionDummy]: ...\n@overload\ndef fancy_getopt(\n    options: list[_Option], negative_opt: Mapping[_Option, _Option], object: Any, args: _SliceableT[_StrSequenceT_co] | None\n) -> _StrSequenceT_co: ...\n\nWS_TRANS: Final[dict[int, str]]\n\ndef wrap_text(text: str, width: int) -> list[str]: ...\ndef translate_longopt(opt: str) -> str: ...\n\nclass OptionDummy:\n    def __init__(self, options: Iterable[str] = []) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/file_util.pyi",
    "content": "from _typeshed import BytesPath, StrOrBytesPath, StrPath\nfrom collections.abc import Iterable\nfrom typing import Literal, TypeVar, overload\n\n_StrPathT = TypeVar(\"_StrPathT\", bound=StrPath)\n_BytesPathT = TypeVar(\"_BytesPathT\", bound=BytesPath)\n\n@overload\ndef copy_file(\n    src: StrPath,\n    dst: _StrPathT,\n    preserve_mode: bool | Literal[0, 1] = 1,\n    preserve_times: bool | Literal[0, 1] = 1,\n    update: bool | Literal[0, 1] = 0,\n    link: str | None = None,\n    verbose: bool | Literal[0, 1] = 1,\n    dry_run: bool | Literal[0, 1] = 0,\n) -> tuple[_StrPathT | str, bool]: ...\n@overload\ndef copy_file(\n    src: BytesPath,\n    dst: _BytesPathT,\n    preserve_mode: bool | Literal[0, 1] = 1,\n    preserve_times: bool | Literal[0, 1] = 1,\n    update: bool | Literal[0, 1] = 0,\n    link: str | None = None,\n    verbose: bool | Literal[0, 1] = 1,\n    dry_run: bool | Literal[0, 1] = 0,\n) -> tuple[_BytesPathT | bytes, bool]: ...\n@overload\ndef move_file(\n    src: StrPath, dst: _StrPathT, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0\n) -> _StrPathT | str: ...\n@overload\ndef move_file(\n    src: BytesPath, dst: _BytesPathT, verbose: bool | Literal[0, 1] = 1, dry_run: bool | Literal[0, 1] = 0\n) -> _BytesPathT | bytes: ...\ndef write_file(filename: StrOrBytesPath, contents: Iterable[str]) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/filelist.pyi",
    "content": "from collections.abc import Iterable\nfrom re import Pattern\nfrom typing import Literal, overload\n\n# class is entirely undocumented\nclass FileList:\n    allfiles: Iterable[str] | None\n    files: list[str]\n    def __init__(self, warn: None = None, debug_print: None = None) -> None: ...\n    def set_allfiles(self, allfiles: Iterable[str]) -> None: ...\n    def findall(self, dir: str = \".\") -> None: ...\n    def debug_print(self, msg: str) -> None: ...\n    def append(self, item: str) -> None: ...\n    def extend(self, items: Iterable[str]) -> None: ...\n    def sort(self) -> None: ...\n    def remove_duplicates(self) -> None: ...\n    def process_template_line(self, line: str) -> None: ...\n    @overload\n    def include_pattern(\n        self, pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[0, False] = 0\n    ) -> bool: ...\n    @overload\n    def include_pattern(self, pattern: str | Pattern[str], *, is_regex: Literal[True, 1]) -> bool: ...\n    @overload\n    def include_pattern(\n        self,\n        pattern: str | Pattern[str],\n        anchor: bool | Literal[0, 1] = 1,\n        prefix: str | None = None,\n        is_regex: bool | Literal[0, 1] = 0,\n    ) -> bool: ...\n    @overload\n    def exclude_pattern(\n        self, pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[0, False] = 0\n    ) -> bool: ...\n    @overload\n    def exclude_pattern(self, pattern: str | Pattern[str], *, is_regex: Literal[True, 1]) -> bool: ...\n    @overload\n    def exclude_pattern(\n        self,\n        pattern: str | Pattern[str],\n        anchor: bool | Literal[0, 1] = 1,\n        prefix: str | None = None,\n        is_regex: bool | Literal[0, 1] = 0,\n    ) -> bool: ...\n\ndef findall(dir: str = \".\") -> list[str]: ...\ndef glob_to_re(pattern: str) -> str: ...\n@overload\ndef translate_pattern(\n    pattern: str, anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: Literal[False, 0] = 0\n) -> Pattern[str]: ...\n@overload\ndef translate_pattern(pattern: str | Pattern[str], *, is_regex: Literal[True, 1]) -> Pattern[str]: ...\n@overload\ndef translate_pattern(\n    pattern: str | Pattern[str], anchor: bool | Literal[0, 1] = 1, prefix: str | None = None, is_regex: bool | Literal[0, 1] = 0\n) -> Pattern[str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/log.pyi",
    "content": "from typing import Any, Final\n\nDEBUG: Final = 1\nINFO: Final = 2\nWARN: Final = 3\nERROR: Final = 4\nFATAL: Final = 5\n\nclass Log:\n    def __init__(self, threshold: int = 3) -> None: ...\n    # Arbitrary msg args' type depends on the format method\n    def log(self, level: int, msg: str, *args: Any) -> None: ...\n    def debug(self, msg: str, *args: Any) -> None: ...\n    def info(self, msg: str, *args: Any) -> None: ...\n    def warn(self, msg: str, *args: Any) -> None: ...\n    def error(self, msg: str, *args: Any) -> None: ...\n    def fatal(self, msg: str, *args: Any) -> None: ...\n\ndef log(level: int, msg: str, *args: Any) -> None: ...\ndef debug(msg: str, *args: Any) -> None: ...\ndef info(msg: str, *args: Any) -> None: ...\ndef warn(msg: str, *args: Any) -> None: ...\ndef error(msg: str, *args: Any) -> None: ...\ndef fatal(msg: str, *args: Any) -> None: ...\ndef set_threshold(level: int) -> int: ...\ndef set_verbosity(v: int) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/msvccompiler.pyi",
    "content": "from distutils.ccompiler import CCompiler\n\nclass MSVCCompiler(CCompiler): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/spawn.pyi",
    "content": "from collections.abc import Iterable\nfrom typing import Literal\n\ndef spawn(\n    cmd: Iterable[str],\n    search_path: bool | Literal[0, 1] = 1,\n    verbose: bool | Literal[0, 1] = 0,\n    dry_run: bool | Literal[0, 1] = 0,\n) -> None: ...\ndef find_executable(executable: str, path: str | None = None) -> str | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/sysconfig.pyi",
    "content": "import sys\nfrom collections.abc import Mapping\nfrom distutils.ccompiler import CCompiler\nfrom typing import Final, Literal, overload\nfrom typing_extensions import deprecated\n\nPREFIX: Final[str]\nEXEC_PREFIX: Final[str]\nBASE_PREFIX: Final[str]\nBASE_EXEC_PREFIX: Final[str]\nproject_base: Final[str]\npython_build: Final[bool]\n\ndef expand_makefile_vars(s: str, vars: Mapping[str, str]) -> str: ...\n@overload\n@deprecated(\"SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11\")\ndef get_config_var(name: Literal[\"SO\"]) -> int | str | None: ...\n@overload\ndef get_config_var(name: str) -> int | str | None: ...\n@overload\ndef get_config_vars() -> dict[str, str | int]: ...\n@overload\ndef get_config_vars(arg: str, /, *args: str) -> list[str | int]: ...\ndef get_config_h_filename() -> str: ...\ndef get_makefile_filename() -> str: ...\ndef get_python_inc(plat_specific: bool | Literal[0, 1] = 0, prefix: str | None = None) -> str: ...\ndef get_python_lib(\n    plat_specific: bool | Literal[0, 1] = 0, standard_lib: bool | Literal[0, 1] = 0, prefix: str | None = None\n) -> str: ...\ndef customize_compiler(compiler: CCompiler) -> None: ...\n\nif sys.version_info < (3, 10):\n    def get_python_version() -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/text_file.pyi",
    "content": "from typing import IO, Literal\n\nclass TextFile:\n    def __init__(\n        self,\n        filename: str | None = None,\n        file: IO[str] | None = None,\n        *,\n        strip_comments: bool | Literal[0, 1] = ...,\n        lstrip_ws: bool | Literal[0, 1] = ...,\n        rstrip_ws: bool | Literal[0, 1] = ...,\n        skip_blanks: bool | Literal[0, 1] = ...,\n        join_lines: bool | Literal[0, 1] = ...,\n        collapse_join: bool | Literal[0, 1] = ...,\n    ) -> None: ...\n    def open(self, filename: str) -> None: ...\n    def close(self) -> None: ...\n    def warn(self, msg: str, line: list[int] | tuple[int, int] | int | None = None) -> None: ...\n    def readline(self) -> str | None: ...\n    def readlines(self) -> list[str]: ...\n    def unreadline(self, line: str) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/unixccompiler.pyi",
    "content": "from distutils.ccompiler import CCompiler\n\nclass UnixCCompiler(CCompiler): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/util.pyi",
    "content": "from _typeshed import StrPath, Unused\nfrom collections.abc import Callable, Container, Iterable, Mapping\nfrom typing import Any, Literal\nfrom typing_extensions import TypeVarTuple, Unpack\n\n_Ts = TypeVarTuple(\"_Ts\")\n\ndef get_host_platform() -> str: ...\ndef get_platform() -> str: ...\ndef convert_path(pathname: str) -> str: ...\ndef change_root(new_root: StrPath, pathname: StrPath) -> str: ...\ndef check_environ() -> None: ...\ndef subst_vars(s: str, local_vars: Mapping[str, str]) -> None: ...\ndef split_quoted(s: str) -> list[str]: ...\ndef execute(\n    func: Callable[[Unpack[_Ts]], Unused],\n    args: tuple[Unpack[_Ts]],\n    msg: str | None = None,\n    verbose: bool | Literal[0, 1] = 0,\n    dry_run: bool | Literal[0, 1] = 0,\n) -> None: ...\ndef strtobool(val: str) -> Literal[0, 1]: ...\ndef byte_compile(\n    py_files: list[str],\n    optimize: int = 0,\n    force: bool | Literal[0, 1] = 0,\n    prefix: str | None = None,\n    base_dir: str | None = None,\n    verbose: bool | Literal[0, 1] = 1,\n    dry_run: bool | Literal[0, 1] = 0,\n    direct: bool | None = None,\n) -> None: ...\ndef rfc822_escape(header: str) -> str: ...\ndef run_2to3(\n    files: Iterable[str],\n    fixer_names: Iterable[str] | None = None,\n    options: Mapping[str, Any] | None = None,\n    explicit: Unused = None,\n) -> None: ...\ndef copydir_run_2to3(\n    src: StrPath,\n    dest: StrPath,\n    template: str | None = None,\n    fixer_names: Iterable[str] | None = None,\n    options: Mapping[str, Any] | None = None,\n    explicit: Container[str] | None = None,\n) -> list[str]: ...\n\nclass Mixin2to3:\n    fixer_names: Iterable[str] | None\n    options: Mapping[str, Any] | None\n    explicit: Container[str] | None\n    def run_2to3(self, files: Iterable[str]) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/distutils/version.pyi",
    "content": "from abc import abstractmethod\nfrom re import Pattern\nfrom typing_extensions import Self\n\nclass Version:\n    def __eq__(self, other: object) -> bool: ...\n    def __lt__(self, other: Self | str) -> bool: ...\n    def __le__(self, other: Self | str) -> bool: ...\n    def __gt__(self, other: Self | str) -> bool: ...\n    def __ge__(self, other: Self | str) -> bool: ...\n    @abstractmethod\n    def __init__(self, vstring: str | None = None) -> None: ...\n    @abstractmethod\n    def parse(self, vstring: str) -> Self: ...\n    @abstractmethod\n    def __str__(self) -> str: ...\n    @abstractmethod\n    def _cmp(self, other: Self | str) -> bool: ...\n\nclass StrictVersion(Version):\n    version_re: Pattern[str]\n    version: tuple[int, int, int]\n    prerelease: tuple[str, int] | None\n    def __init__(self, vstring: str | None = None) -> None: ...\n    def parse(self, vstring: str) -> Self: ...\n    def __str__(self) -> str: ...  # noqa: Y029\n    def _cmp(self, other: Self | str) -> bool: ...\n\nclass LooseVersion(Version):\n    component_re: Pattern[str]\n    vstring: str\n    version: tuple[str | int, ...]\n    def __init__(self, vstring: str | None = None) -> None: ...\n    def parse(self, vstring: str) -> Self: ...\n    def __str__(self) -> str: ...  # noqa: Y029\n    def _cmp(self, other: Self | str) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/doctest.pyi",
    "content": "import sys\nimport types\nimport unittest\nfrom _typeshed import ExcInfo\nfrom collections.abc import Callable\nfrom typing import Any, Final, NamedTuple, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\n    \"register_optionflag\",\n    \"DONT_ACCEPT_TRUE_FOR_1\",\n    \"DONT_ACCEPT_BLANKLINE\",\n    \"NORMALIZE_WHITESPACE\",\n    \"ELLIPSIS\",\n    \"SKIP\",\n    \"IGNORE_EXCEPTION_DETAIL\",\n    \"COMPARISON_FLAGS\",\n    \"REPORT_UDIFF\",\n    \"REPORT_CDIFF\",\n    \"REPORT_NDIFF\",\n    \"REPORT_ONLY_FIRST_FAILURE\",\n    \"REPORTING_FLAGS\",\n    \"FAIL_FAST\",\n    \"Example\",\n    \"DocTest\",\n    \"DocTestParser\",\n    \"DocTestFinder\",\n    \"DocTestRunner\",\n    \"OutputChecker\",\n    \"DocTestFailure\",\n    \"UnexpectedException\",\n    \"DebugRunner\",\n    \"testmod\",\n    \"testfile\",\n    \"run_docstring_examples\",\n    \"DocTestSuite\",\n    \"DocFileSuite\",\n    \"set_unittest_reportflags\",\n    \"script_from_examples\",\n    \"testsource\",\n    \"debug_src\",\n    \"debug\",\n]\n\nif sys.version_info >= (3, 13):\n    @type_check_only\n    class _TestResultsBase(NamedTuple):\n        failed: int\n        attempted: int\n\n    class TestResults(_TestResultsBase):\n        def __new__(cls, failed: int, attempted: int, *, skipped: int = 0) -> Self: ...\n        skipped: int\n\nelse:\n    class TestResults(NamedTuple):\n        failed: int\n        attempted: int\n\nOPTIONFLAGS_BY_NAME: Final[dict[str, int]]\n\ndef register_optionflag(name: str) -> int: ...\n\nDONT_ACCEPT_TRUE_FOR_1: Final = 1\nDONT_ACCEPT_BLANKLINE: Final = 2\nNORMALIZE_WHITESPACE: Final = 4\nELLIPSIS: Final = 8\nSKIP: Final = 16\nIGNORE_EXCEPTION_DETAIL: Final = 32\n\nCOMPARISON_FLAGS: Final = 63\n\nREPORT_UDIFF: Final = 64\nREPORT_CDIFF: Final = 128\nREPORT_NDIFF: Final = 256\nREPORT_ONLY_FIRST_FAILURE: Final = 512\nFAIL_FAST: Final = 1024\n\nREPORTING_FLAGS: Final = 1984\n\nBLANKLINE_MARKER: Final = \"<BLANKLINE>\"\nELLIPSIS_MARKER: Final = \"...\"\n\nclass Example:\n    source: str\n    want: str\n    exc_msg: str | None\n    lineno: int\n    indent: int\n    options: dict[int, bool]\n    def __init__(\n        self,\n        source: str,\n        want: str,\n        exc_msg: str | None = None,\n        lineno: int = 0,\n        indent: int = 0,\n        options: dict[int, bool] | None = None,\n    ) -> None: ...\n    def __hash__(self) -> int: ...\n    def __eq__(self, other: object) -> bool: ...\n\nclass DocTest:\n    examples: list[Example]\n    globs: dict[str, Any]\n    name: str\n    filename: str | None\n    lineno: int | None\n    docstring: str | None\n    def __init__(\n        self,\n        examples: list[Example],\n        globs: dict[str, Any],\n        name: str,\n        filename: str | None,\n        lineno: int | None,\n        docstring: str | None,\n    ) -> None: ...\n    def __hash__(self) -> int: ...\n    def __lt__(self, other: DocTest) -> bool: ...\n    def __eq__(self, other: object) -> bool: ...\n\nclass DocTestParser:\n    def parse(self, string: str, name: str = \"<string>\") -> list[str | Example]: ...\n    def get_doctest(self, string: str, globs: dict[str, Any], name: str, filename: str | None, lineno: int | None) -> DocTest: ...\n    def get_examples(self, string: str, name: str = \"<string>\") -> list[Example]: ...\n\nclass DocTestFinder:\n    def __init__(\n        self, verbose: bool = False, parser: DocTestParser = ..., recurse: bool = True, exclude_empty: bool = True\n    ) -> None: ...\n    def find(\n        self,\n        obj: object,\n        name: str | None = None,\n        module: None | bool | types.ModuleType = None,\n        globs: dict[str, Any] | None = None,\n        extraglobs: dict[str, Any] | None = None,\n    ) -> list[DocTest]: ...\n\n_Out: TypeAlias = Callable[[str], object]\n\nclass DocTestRunner:\n    DIVIDER: str\n    optionflags: int\n    original_optionflags: int\n    tries: int\n    failures: int\n    if sys.version_info >= (3, 13):\n        skips: int\n    test: DocTest\n    def __init__(self, checker: OutputChecker | None = None, verbose: bool | None = None, optionflags: int = 0) -> None: ...\n    def report_start(self, out: _Out, test: DocTest, example: Example) -> None: ...\n    def report_success(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ...\n    def report_failure(self, out: _Out, test: DocTest, example: Example, got: str) -> None: ...\n    def report_unexpected_exception(self, out: _Out, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ...\n    def run(\n        self, test: DocTest, compileflags: int | None = None, out: _Out | None = None, clear_globs: bool = True\n    ) -> TestResults: ...\n    def summarize(self, verbose: bool | None = None) -> TestResults: ...\n    def merge(self, other: DocTestRunner) -> None: ...\n\nclass OutputChecker:\n    def check_output(self, want: str, got: str, optionflags: int) -> bool: ...\n    def output_difference(self, example: Example, got: str, optionflags: int) -> str: ...\n\nclass DocTestFailure(Exception):\n    test: DocTest\n    example: Example\n    got: str\n    def __init__(self, test: DocTest, example: Example, got: str) -> None: ...\n\nclass UnexpectedException(Exception):\n    test: DocTest\n    example: Example\n    exc_info: ExcInfo\n    def __init__(self, test: DocTest, example: Example, exc_info: ExcInfo) -> None: ...\n\nclass DebugRunner(DocTestRunner): ...\n\nmaster: DocTestRunner | None\n\ndef testmod(\n    m: types.ModuleType | None = None,\n    name: str | None = None,\n    globs: dict[str, Any] | None = None,\n    verbose: bool | None = None,\n    report: bool = True,\n    optionflags: int = 0,\n    extraglobs: dict[str, Any] | None = None,\n    raise_on_error: bool = False,\n    exclude_empty: bool = False,\n) -> TestResults: ...\ndef testfile(\n    filename: str,\n    module_relative: bool = True,\n    name: str | None = None,\n    package: None | str | types.ModuleType = None,\n    globs: dict[str, Any] | None = None,\n    verbose: bool | None = None,\n    report: bool = True,\n    optionflags: int = 0,\n    extraglobs: dict[str, Any] | None = None,\n    raise_on_error: bool = False,\n    parser: DocTestParser = ...,\n    encoding: str | None = None,\n) -> TestResults: ...\ndef run_docstring_examples(\n    f: object,\n    globs: dict[str, Any],\n    verbose: bool = False,\n    name: str = \"NoName\",\n    compileflags: int | None = None,\n    optionflags: int = 0,\n) -> None: ...\ndef set_unittest_reportflags(flags: int) -> int: ...\n\nclass DocTestCase(unittest.TestCase):\n    def __init__(\n        self,\n        test: DocTest,\n        optionflags: int = 0,\n        setUp: Callable[[DocTest], object] | None = None,\n        tearDown: Callable[[DocTest], object] | None = None,\n        checker: OutputChecker | None = None,\n    ) -> None: ...\n    def runTest(self) -> None: ...\n    def format_failure(self, err: str) -> str: ...\n    def __hash__(self) -> int: ...\n    def __eq__(self, other: object) -> bool: ...\n\nclass SkipDocTestCase(DocTestCase):\n    def __init__(self, module: types.ModuleType) -> None: ...\n    def test_skip(self) -> None: ...\n\nclass _DocTestSuite(unittest.TestSuite): ...\n\ndef DocTestSuite(\n    module: None | str | types.ModuleType = None,\n    globs: dict[str, Any] | None = None,\n    extraglobs: dict[str, Any] | None = None,\n    test_finder: DocTestFinder | None = None,\n    **options: Any,\n) -> _DocTestSuite: ...\n\nclass DocFileCase(DocTestCase): ...\n\ndef DocFileTest(\n    path: str,\n    module_relative: bool = True,\n    package: None | str | types.ModuleType = None,\n    globs: dict[str, Any] | None = None,\n    parser: DocTestParser = ...,\n    encoding: str | None = None,\n    **options: Any,\n) -> DocFileCase: ...\ndef DocFileSuite(*paths: str, **kw: Any) -> _DocTestSuite: ...\ndef script_from_examples(s: str) -> str: ...\ndef testsource(module: None | str | types.ModuleType, name: str) -> str: ...\ndef debug_src(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: ...\ndef debug_script(src: str, pm: bool = False, globs: dict[str, Any] | None = None) -> None: ...\ndef debug(module: None | str | types.ModuleType, name: str, pm: bool = False) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/__init__.pyi",
    "content": "from collections.abc import Callable\nfrom email._policybase import _MessageT\nfrom email.message import Message\nfrom email.policy import Policy\nfrom typing import IO, overload\nfrom typing_extensions import TypeAlias\n\n# At runtime, listing submodules in __all__ without them being imported is\n# valid, and causes them to be included in a star import. See #6523\n\n__all__ = [  # noqa: F822  # Undefined names in __all__\n    \"base64mime\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"charset\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"encoders\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"errors\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"feedparser\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"generator\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"header\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"iterators\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"message\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"message_from_file\",\n    \"message_from_binary_file\",\n    \"message_from_string\",\n    \"message_from_bytes\",\n    \"mime\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"parser\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"quoprimime\",  # pyright: ignore[reportUnsupportedDunderAll]\n    \"utils\",  # pyright: ignore[reportUnsupportedDunderAll]\n]\n\n# Definitions imported by multiple submodules in typeshed\n_ParamType: TypeAlias = str | tuple[str | None, str | None, str]  # noqa: Y047\n_ParamsType: TypeAlias = str | None | tuple[str, str | None, str]  # noqa: Y047\n\n@overload\ndef message_from_string(s: str) -> Message: ...\n@overload\ndef message_from_string(s: str, _class: Callable[[], _MessageT]) -> _MessageT: ...\n@overload\ndef message_from_string(s: str, _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ...\n@overload\ndef message_from_bytes(s: bytes | bytearray) -> Message: ...\n@overload\ndef message_from_bytes(s: bytes | bytearray, _class: Callable[[], _MessageT]) -> _MessageT: ...\n@overload\ndef message_from_bytes(\n    s: bytes | bytearray, _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]\n) -> _MessageT: ...\n@overload\ndef message_from_file(fp: IO[str]) -> Message: ...\n@overload\ndef message_from_file(fp: IO[str], _class: Callable[[], _MessageT]) -> _MessageT: ...\n@overload\ndef message_from_file(fp: IO[str], _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ...\n@overload\ndef message_from_binary_file(fp: IO[bytes]) -> Message: ...\n@overload\ndef message_from_binary_file(fp: IO[bytes], _class: Callable[[], _MessageT]) -> _MessageT: ...\n@overload\ndef message_from_binary_file(fp: IO[bytes], _class: Callable[[], _MessageT] = ..., *, policy: Policy[_MessageT]) -> _MessageT: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/_header_value_parser.pyi",
    "content": "import sys\nfrom collections.abc import Iterable, Iterator\nfrom email.errors import HeaderParseError, MessageDefect\nfrom email.policy import Policy\nfrom re import Pattern\nfrom typing import Any, Final\nfrom typing_extensions import Self\n\nWSP: Final[set[str]]\nCFWS_LEADER: Final[set[str]]\nSPECIALS: Final[set[str]]\nATOM_ENDS: Final[set[str]]\nDOT_ATOM_ENDS: Final[set[str]]\nPHRASE_ENDS: Final[set[str]]\nTSPECIALS: Final[set[str]]\nTOKEN_ENDS: Final[set[str]]\nASPECIALS: Final[set[str]]\nATTRIBUTE_ENDS: Final[set[str]]\nEXTENDED_ATTRIBUTE_ENDS: Final[set[str]]\n# Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\nNLSET: Final[set[str]]\n# Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\nSPECIALSNL: Final[set[str]]\n\n# Added in Python 3.9.23, 3.10.17, 3.11.12, 3.12.9, 3.13.2\ndef make_quoted_pairs(value: Any) -> str: ...\ndef quote_string(value: Any) -> str: ...\n\nif sys.version_info >= (3, 13):\n    # Added in Python 3.13.12, 3.14.3\n    def make_parenthesis_pairs(value: Any) -> str: ...\n\nrfc2047_matcher: Final[Pattern[str]]\n\nclass TokenList(list[TokenList | Terminal]):\n    token_type: str | None\n    syntactic_break: bool\n    ew_combine_allowed: bool\n    defects: list[MessageDefect]\n    def __init__(self, *args: Any, **kw: Any) -> None: ...\n    @property\n    def value(self) -> str: ...\n    @property\n    def all_defects(self) -> list[MessageDefect]: ...\n    def startswith_fws(self) -> bool: ...\n    @property\n    def as_ew_allowed(self) -> bool: ...\n    @property\n    def comments(self) -> list[str]: ...\n    def fold(self, *, policy: Policy) -> str: ...\n    def pprint(self, indent: str = \"\") -> None: ...\n    def ppstr(self, indent: str = \"\") -> str: ...\n\nclass WhiteSpaceTokenList(TokenList): ...\n\nclass UnstructuredTokenList(TokenList):\n    token_type: str\n\nclass Phrase(TokenList):\n    token_type: str\n\nclass Word(TokenList):\n    token_type: str\n\nclass CFWSList(WhiteSpaceTokenList):\n    token_type: str\n\nclass Atom(TokenList):\n    token_type: str\n\nclass Token(TokenList):\n    token_type: str\n    encode_as_ew: bool\n\nclass EncodedWord(TokenList):\n    token_type: str\n    cte: str | None\n    charset: str | None\n    lang: str | None\n\nclass QuotedString(TokenList):\n    token_type: str\n    @property\n    def content(self) -> str: ...\n    @property\n    def quoted_value(self) -> str: ...\n    @property\n    def stripped_value(self) -> str: ...\n\nclass BareQuotedString(QuotedString):\n    token_type: str\n\nclass Comment(WhiteSpaceTokenList):\n    token_type: str\n    def quote(self, value: Any) -> str: ...\n    @property\n    def content(self) -> str: ...\n\nclass AddressList(TokenList):\n    token_type: str\n    @property\n    def addresses(self) -> list[Address]: ...\n    @property\n    def mailboxes(self) -> list[Mailbox]: ...\n    @property\n    def all_mailboxes(self) -> list[Mailbox]: ...\n\nclass Address(TokenList):\n    token_type: str\n    @property\n    def display_name(self) -> str: ...\n    @property\n    def mailboxes(self) -> list[Mailbox]: ...\n    @property\n    def all_mailboxes(self) -> list[Mailbox]: ...\n\nclass MailboxList(TokenList):\n    token_type: str\n    @property\n    def mailboxes(self) -> list[Mailbox]: ...\n    @property\n    def all_mailboxes(self) -> list[Mailbox]: ...\n\nclass GroupList(TokenList):\n    token_type: str\n    @property\n    def mailboxes(self) -> list[Mailbox]: ...\n    @property\n    def all_mailboxes(self) -> list[Mailbox]: ...\n\nclass Group(TokenList):\n    token_type: str\n    @property\n    def mailboxes(self) -> list[Mailbox]: ...\n    @property\n    def all_mailboxes(self) -> list[Mailbox]: ...\n    @property\n    def display_name(self) -> str: ...\n\nclass NameAddr(TokenList):\n    token_type: str\n    @property\n    def display_name(self) -> str: ...\n    @property\n    def local_part(self) -> str: ...\n    @property\n    def domain(self) -> str: ...\n    @property\n    def route(self) -> list[Domain] | None: ...\n    @property\n    def addr_spec(self) -> str: ...\n\nclass AngleAddr(TokenList):\n    token_type: str\n    @property\n    def local_part(self) -> str: ...\n    @property\n    def domain(self) -> str: ...\n    @property\n    def route(self) -> list[Domain] | None: ...\n    @property\n    def addr_spec(self) -> str: ...\n\nclass ObsRoute(TokenList):\n    token_type: str\n    @property\n    def domains(self) -> list[Domain]: ...\n\nclass Mailbox(TokenList):\n    token_type: str\n    @property\n    def display_name(self) -> str: ...\n    @property\n    def local_part(self) -> str: ...\n    @property\n    def domain(self) -> str: ...\n    @property\n    def route(self) -> list[str]: ...\n    @property\n    def addr_spec(self) -> str: ...\n\nclass InvalidMailbox(TokenList):\n    token_type: str\n    @property\n    def display_name(self) -> None: ...\n    @property\n    def local_part(self) -> None: ...\n    @property\n    def domain(self) -> None: ...\n    @property\n    def route(self) -> None: ...\n    @property\n    def addr_spec(self) -> None: ...\n\nclass Domain(TokenList):\n    token_type: str\n    as_ew_allowed: bool\n    @property\n    def domain(self) -> str: ...\n\nclass DotAtom(TokenList):\n    token_type: str\n\nclass DotAtomText(TokenList):\n    token_type: str\n    as_ew_allowed: bool\n\nclass NoFoldLiteral(TokenList):\n    token_type: str\n    as_ew_allowed: bool\n\nclass AddrSpec(TokenList):\n    token_type: str\n    as_ew_allowed: bool\n    @property\n    def local_part(self) -> str: ...\n    @property\n    def domain(self) -> str: ...\n    @property\n    def addr_spec(self) -> str: ...\n\nclass ObsLocalPart(TokenList):\n    token_type: str\n    as_ew_allowed: bool\n\nclass DisplayName(Phrase):\n    token_type: str\n    @property\n    def display_name(self) -> str: ...\n\nclass LocalPart(TokenList):\n    token_type: str\n    as_ew_allowed: bool\n    @property\n    def local_part(self) -> str: ...\n\nclass DomainLiteral(TokenList):\n    token_type: str\n    as_ew_allowed: bool\n    @property\n    def domain(self) -> str: ...\n    @property\n    def ip(self) -> str: ...\n\nclass MIMEVersion(TokenList):\n    token_type: str\n    major: int | None\n    minor: int | None\n\nclass Parameter(TokenList):\n    token_type: str\n    sectioned: bool\n    extended: bool\n    charset: str\n    @property\n    def section_number(self) -> int: ...\n    @property\n    def param_value(self) -> str: ...\n\nclass InvalidParameter(Parameter):\n    token_type: str\n\nclass Attribute(TokenList):\n    token_type: str\n    @property\n    def stripped_value(self) -> str: ...\n\nclass Section(TokenList):\n    token_type: str\n    number: int | None\n\nclass Value(TokenList):\n    token_type: str\n    @property\n    def stripped_value(self) -> str: ...\n\nclass MimeParameters(TokenList):\n    token_type: str\n    syntactic_break: bool\n    @property\n    def params(self) -> Iterator[tuple[str, str]]: ...\n\nclass ParameterizedHeaderValue(TokenList):\n    syntactic_break: bool\n    @property\n    def params(self) -> Iterable[tuple[str, str]]: ...\n\nclass ContentType(ParameterizedHeaderValue):\n    token_type: str\n    as_ew_allowed: bool\n    maintype: str\n    subtype: str\n\nclass ContentDisposition(ParameterizedHeaderValue):\n    token_type: str\n    as_ew_allowed: bool\n    content_disposition: Any\n\nclass ContentTransferEncoding(TokenList):\n    token_type: str\n    as_ew_allowed: bool\n    cte: str\n\nclass HeaderLabel(TokenList):\n    token_type: str\n    as_ew_allowed: bool\n\nclass MsgID(TokenList):\n    token_type: str\n    as_ew_allowed: bool\n    def fold(self, policy: Policy) -> str: ...\n\nclass MessageID(MsgID):\n    token_type: str\n\nclass InvalidMessageID(MessageID):\n    token_type: str\n\nif sys.version_info >= (3, 13):\n    # Added in Python 3.13.12, 3.14.3\n    class MessageIDList(TokenList):\n        token_type: str\n        @property\n        def message_ids(self) -> list[MsgID | Terminal]: ...\n\nclass Header(TokenList):\n    token_type: str\n\nclass Terminal(str):\n    as_ew_allowed: bool\n    ew_combine_allowed: bool\n    syntactic_break: bool\n    token_type: str\n    defects: list[MessageDefect]\n    def __new__(cls, value: str, token_type: str) -> Self: ...\n    def pprint(self) -> None: ...\n    @property\n    def all_defects(self) -> list[MessageDefect]: ...\n    def pop_trailing_ws(self) -> None: ...\n    @property\n    def comments(self) -> list[str]: ...\n    def __getnewargs__(self) -> tuple[str, str]: ...  # type: ignore[override]\n\nclass WhiteSpaceTerminal(Terminal):\n    @property\n    def value(self) -> str: ...\n    def startswith_fws(self) -> bool: ...\n\nclass ValueTerminal(Terminal):\n    @property\n    def value(self) -> ValueTerminal: ...\n    def startswith_fws(self) -> bool: ...\n\nclass EWWhiteSpaceTerminal(WhiteSpaceTerminal): ...\nclass _InvalidEwError(HeaderParseError): ...\n\nDOT: Final[ValueTerminal]\nListSeparator: Final[ValueTerminal]\nRouteComponentMarker: Final[ValueTerminal]\n\ndef get_fws(value: str) -> tuple[WhiteSpaceTerminal, str]: ...\ndef get_encoded_word(value: str, terminal_type: str = \"vtext\") -> tuple[EncodedWord, str]: ...\ndef get_unstructured(value: str) -> UnstructuredTokenList: ...\ndef get_qp_ctext(value: str) -> tuple[WhiteSpaceTerminal, str]: ...\ndef get_qcontent(value: str) -> tuple[ValueTerminal, str]: ...\ndef get_atext(value: str) -> tuple[ValueTerminal, str]: ...\ndef get_bare_quoted_string(value: str) -> tuple[BareQuotedString, str]: ...\ndef get_comment(value: str) -> tuple[Comment, str]: ...\ndef get_cfws(value: str) -> tuple[CFWSList, str]: ...\ndef get_quoted_string(value: str) -> tuple[QuotedString, str]: ...\ndef get_atom(value: str) -> tuple[Atom, str]: ...\ndef get_dot_atom_text(value: str) -> tuple[DotAtomText, str]: ...\ndef get_dot_atom(value: str) -> tuple[DotAtom, str]: ...\ndef get_word(value: str) -> tuple[Any, str]: ...\ndef get_phrase(value: str) -> tuple[Phrase, str]: ...\ndef get_local_part(value: str) -> tuple[LocalPart, str]: ...\ndef get_obs_local_part(value: str) -> tuple[ObsLocalPart, str]: ...\ndef get_dtext(value: str) -> tuple[ValueTerminal, str]: ...\ndef get_domain_literal(value: str) -> tuple[DomainLiteral, str]: ...\ndef get_domain(value: str) -> tuple[Domain, str]: ...\ndef get_addr_spec(value: str) -> tuple[AddrSpec, str]: ...\ndef get_obs_route(value: str) -> tuple[ObsRoute, str]: ...\ndef get_angle_addr(value: str) -> tuple[AngleAddr, str]: ...\ndef get_display_name(value: str) -> tuple[DisplayName, str]: ...\ndef get_name_addr(value: str) -> tuple[NameAddr, str]: ...\ndef get_mailbox(value: str) -> tuple[Mailbox, str]: ...\ndef get_invalid_mailbox(value: str, endchars: str) -> tuple[InvalidMailbox, str]: ...\ndef get_mailbox_list(value: str) -> tuple[MailboxList, str]: ...\ndef get_group_list(value: str) -> tuple[GroupList, str]: ...\ndef get_group(value: str) -> tuple[Group, str]: ...\ndef get_address(value: str) -> tuple[Address, str]: ...\ndef get_address_list(value: str) -> tuple[AddressList, str]: ...\ndef get_no_fold_literal(value: str) -> tuple[NoFoldLiteral, str]: ...\ndef get_msg_id(value: str) -> tuple[MsgID, str]: ...\ndef parse_message_id(value: str) -> MessageID: ...\n\nif sys.version_info >= (3, 13):\n    # Added in Python 3.13.12, 3.14.3\n    def parse_message_ids(value: str) -> MessageIDList: ...\n\ndef parse_mime_version(value: str) -> MIMEVersion: ...\ndef get_invalid_parameter(value: str) -> tuple[InvalidParameter, str]: ...\ndef get_ttext(value: str) -> tuple[ValueTerminal, str]: ...\ndef get_token(value: str) -> tuple[Token, str]: ...\ndef get_attrtext(value: str) -> tuple[ValueTerminal, str]: ...\ndef get_attribute(value: str) -> tuple[Attribute, str]: ...\ndef get_extended_attrtext(value: str) -> tuple[ValueTerminal, str]: ...\ndef get_extended_attribute(value: str) -> tuple[Attribute, str]: ...\ndef get_section(value: str) -> tuple[Section, str]: ...\ndef get_value(value: str) -> tuple[Value, str]: ...\ndef get_parameter(value: str) -> tuple[Parameter, str]: ...\ndef parse_mime_parameters(value: str) -> MimeParameters: ...\ndef parse_content_type_header(value: str) -> ContentType: ...\ndef parse_content_disposition_header(value: str) -> ContentDisposition: ...\ndef parse_content_transfer_encoding_header(value: str) -> ContentTransferEncoding: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/_policybase.pyi",
    "content": "from abc import ABCMeta, abstractmethod\nfrom email.errors import MessageDefect\nfrom email.header import Header\nfrom email.message import Message\nfrom typing import Any, Generic, Protocol, TypeVar, type_check_only\nfrom typing_extensions import Self\n\n__all__ = [\"Policy\", \"Compat32\", \"compat32\"]\n\n_MessageT = TypeVar(\"_MessageT\", bound=Message[Any, Any], default=Message[str, str])\n_MessageT_co = TypeVar(\"_MessageT_co\", covariant=True, bound=Message[Any, Any], default=Message[str, str])\n\n@type_check_only\nclass _MessageFactory(Protocol[_MessageT]):\n    def __call__(self, policy: Policy[_MessageT]) -> _MessageT: ...\n\n# Policy below is the only known direct subclass of _PolicyBase. We therefore\n# assume that the __init__ arguments and attributes of _PolicyBase are\n# the same as those of Policy.\nclass _PolicyBase(Generic[_MessageT_co]):\n    max_line_length: int | None\n    linesep: str\n    cte_type: str\n    raise_on_defect: bool\n    mangle_from_: bool\n    message_factory: _MessageFactory[_MessageT_co] | None\n    # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\n    verify_generated_headers: bool\n\n    def __init__(\n        self,\n        *,\n        max_line_length: int | None = 78,\n        linesep: str = \"\\n\",\n        cte_type: str = \"8bit\",\n        raise_on_defect: bool = False,\n        mangle_from_: bool = ...,  # default depends on sub-class\n        message_factory: _MessageFactory[_MessageT_co] | None = None,\n        # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\n        verify_generated_headers: bool = True,\n    ) -> None: ...\n    def clone(\n        self,\n        *,\n        max_line_length: int | None = ...,\n        linesep: str = ...,\n        cte_type: str = ...,\n        raise_on_defect: bool = ...,\n        mangle_from_: bool = ...,\n        message_factory: _MessageFactory[_MessageT_co] | None = ...,\n        # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\n        verify_generated_headers: bool = ...,\n    ) -> Self: ...\n    def __add__(self, other: Policy) -> Self: ...\n\nclass Policy(_PolicyBase[_MessageT_co], metaclass=ABCMeta):\n    # Every Message object has a `defects` attribute, so the following\n    # methods will work for any Message object.\n    def handle_defect(self, obj: Message[Any, Any], defect: MessageDefect) -> None: ...\n    def register_defect(self, obj: Message[Any, Any], defect: MessageDefect) -> None: ...\n    def header_max_count(self, name: str) -> int | None: ...\n    @abstractmethod\n    def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ...\n    @abstractmethod\n    def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ...\n    @abstractmethod\n    def header_fetch_parse(self, name: str, value: str) -> str: ...\n    @abstractmethod\n    def fold(self, name: str, value: str) -> str: ...\n    @abstractmethod\n    def fold_binary(self, name: str, value: str) -> bytes: ...\n\nclass Compat32(Policy[_MessageT_co]):\n    def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ...\n    def header_store_parse(self, name: str, value: str) -> tuple[str, str]: ...\n    def header_fetch_parse(self, name: str, value: str) -> str | Header: ...  # type: ignore[override]\n    def fold(self, name: str, value: str) -> str: ...\n    def fold_binary(self, name: str, value: str) -> bytes: ...\n\ncompat32: Compat32[Message[str, str]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/base64mime.pyi",
    "content": "__all__ = [\"body_decode\", \"body_encode\", \"decode\", \"decodestring\", \"header_encode\", \"header_length\"]\n\nfrom _typeshed import ReadableBuffer\n\ndef header_length(bytearray: str | bytes | bytearray) -> int: ...\ndef header_encode(header_bytes: str | ReadableBuffer, charset: str = \"iso-8859-1\") -> str: ...\n\n# First argument should be a buffer that supports slicing and len().\ndef body_encode(s: bytes | bytearray, maxlinelen: int = 76, eol: str = \"\\n\") -> str: ...\ndef decode(string: str | ReadableBuffer) -> bytes: ...\n\nbody_decode = decode\ndecodestring = decode\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/charset.pyi",
    "content": "from collections.abc import Callable, Iterator\nfrom email.message import Message\nfrom typing import ClassVar, Final, overload\n\n__all__ = [\"Charset\", \"add_alias\", \"add_charset\", \"add_codec\"]\n\nQP: Final = 1  # undocumented\nBASE64: Final = 2  # undocumented\nSHORTEST: Final = 3  # undocumented\nRFC2047_CHROME_LEN: Final = 7  # undocumented\nDEFAULT_CHARSET: Final = \"us-ascii\"  # undocumented\nUNKNOWN8BIT: Final = \"unknown-8bit\"  # undocumented\nEMPTYSTRING: Final = \"\"  # undocumented\nCHARSETS: Final[dict[str, tuple[int | None, int | None, str | None]]]\nALIASES: Final[dict[str, str]]\nCODEC_MAP: Final[dict[str, str | None]]  # undocumented\n\nclass Charset:\n    input_charset: str\n    header_encoding: int\n    body_encoding: int\n    output_charset: str | None\n    input_codec: str | None\n    output_codec: str | None\n    def __init__(self, input_charset: str = \"us-ascii\") -> None: ...\n    def get_body_encoding(self) -> str | Callable[[Message], None]: ...\n    def get_output_charset(self) -> str | None: ...\n    def header_encode(self, string: str) -> str: ...\n    def header_encode_lines(self, string: str, maxlengths: Iterator[int]) -> list[str | None]: ...\n    @overload\n    def body_encode(self, string: None) -> None: ...\n    @overload\n    def body_encode(self, string: str | bytes) -> str: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __eq__(self, other: object) -> bool: ...\n    def __ne__(self, value: object, /) -> bool: ...\n\ndef add_charset(\n    charset: str, header_enc: int | None = None, body_enc: int | None = None, output_charset: str | None = None\n) -> None: ...\ndef add_alias(alias: str, canonical: str) -> None: ...\ndef add_codec(charset: str, codecname: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/contentmanager.pyi",
    "content": "from collections.abc import Callable\nfrom email.message import Message\nfrom typing import Any\n\nclass ContentManager:\n    def get_content(self, msg: Message, *args: Any, **kw: Any) -> Any: ...\n    def set_content(self, msg: Message, obj: Any, *args: Any, **kw: Any) -> Any: ...\n    def add_get_handler(self, key: str, handler: Callable[..., Any]) -> None: ...\n    def add_set_handler(self, typekey: type, handler: Callable[..., Any]) -> None: ...\n\nraw_data_manager: ContentManager\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/encoders.pyi",
    "content": "from email.message import Message\n\n__all__ = [\"encode_7or8bit\", \"encode_base64\", \"encode_noop\", \"encode_quopri\"]\n\ndef encode_base64(msg: Message) -> None: ...\ndef encode_quopri(msg: Message) -> None: ...\ndef encode_7or8bit(msg: Message) -> None: ...\ndef encode_noop(msg: Message) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/errors.pyi",
    "content": "import sys\n\nclass MessageError(Exception): ...\nclass MessageParseError(MessageError): ...\nclass HeaderParseError(MessageParseError): ...\nclass BoundaryError(MessageParseError): ...\nclass MultipartConversionError(MessageError, TypeError): ...\nclass CharsetError(MessageError): ...\n\n# Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\nclass HeaderWriteError(MessageError): ...\n\nclass MessageDefect(ValueError):\n    def __init__(self, line: str | None = None) -> None: ...\n\nclass NoBoundaryInMultipartDefect(MessageDefect): ...\nclass StartBoundaryNotFoundDefect(MessageDefect): ...\nclass FirstHeaderLineIsContinuationDefect(MessageDefect): ...\nclass MisplacedEnvelopeHeaderDefect(MessageDefect): ...\nclass MultipartInvariantViolationDefect(MessageDefect): ...\nclass InvalidMultipartContentTransferEncodingDefect(MessageDefect): ...\nclass UndecodableBytesDefect(MessageDefect): ...\nclass InvalidBase64PaddingDefect(MessageDefect): ...\nclass InvalidBase64CharactersDefect(MessageDefect): ...\nclass InvalidBase64LengthDefect(MessageDefect): ...\nclass CloseBoundaryNotFoundDefect(MessageDefect): ...\nclass MissingHeaderBodySeparatorDefect(MessageDefect): ...\n\nMalformedHeaderDefect = MissingHeaderBodySeparatorDefect\n\nclass HeaderDefect(MessageDefect): ...\nclass InvalidHeaderDefect(HeaderDefect): ...\nclass HeaderMissingRequiredValue(HeaderDefect): ...\n\nclass NonPrintableDefect(HeaderDefect):\n    def __init__(self, non_printables: str | None) -> None: ...\n\nclass ObsoleteHeaderDefect(HeaderDefect): ...\nclass NonASCIILocalPartDefect(HeaderDefect): ...\n\nif sys.version_info >= (3, 10):\n    class InvalidDateDefect(HeaderDefect): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/feedparser.pyi",
    "content": "from collections.abc import Callable\nfrom email._policybase import _MessageT\nfrom email.message import Message\nfrom email.policy import Policy\nfrom typing import Generic, overload\n\n__all__ = [\"FeedParser\", \"BytesFeedParser\"]\n\nclass FeedParser(Generic[_MessageT]):\n    @overload\n    def __init__(self: FeedParser[Message], _factory: None = None, *, policy: Policy[Message] = ...) -> None: ...\n    @overload\n    def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ...\n    def feed(self, data: str) -> None: ...\n    def close(self) -> _MessageT: ...\n\nclass BytesFeedParser(FeedParser[_MessageT]):\n    @overload\n    def __init__(self: BytesFeedParser[Message], _factory: None = None, *, policy: Policy[Message] = ...) -> None: ...\n    @overload\n    def __init__(self, _factory: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ...\n    def feed(self, data: bytes | bytearray) -> None: ...  # type: ignore[override]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/generator.pyi",
    "content": "from _typeshed import SupportsWrite\nfrom email.message import Message\nfrom email.policy import Policy\nfrom typing import Any, Generic, TypeVar, overload\nfrom typing_extensions import Self\n\n__all__ = [\"Generator\", \"DecodedGenerator\", \"BytesGenerator\"]\n\n# By default, generators do not have a message policy.\n_MessageT = TypeVar(\"_MessageT\", bound=Message[Any, Any], default=Any)\n\nclass Generator(Generic[_MessageT]):\n    maxheaderlen: int | None\n    policy: Policy[_MessageT] | None\n    @overload\n    def __init__(\n        self: Generator[Any],  # The Policy of the message is used.\n        outfp: SupportsWrite[str],\n        mangle_from_: bool | None = None,\n        maxheaderlen: int | None = None,\n        *,\n        policy: None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        outfp: SupportsWrite[str],\n        mangle_from_: bool | None = None,\n        maxheaderlen: int | None = None,\n        *,\n        policy: Policy[_MessageT],\n    ) -> None: ...\n    def write(self, s: str) -> None: ...\n    def flatten(self, msg: _MessageT, unixfrom: bool = False, linesep: str | None = None) -> None: ...\n    def clone(self, fp: SupportsWrite[str]) -> Self: ...\n\nclass BytesGenerator(Generator[_MessageT]):\n    @overload\n    def __init__(\n        self: BytesGenerator[Any],  # The Policy of the message is used.\n        outfp: SupportsWrite[bytes],\n        mangle_from_: bool | None = None,\n        maxheaderlen: int | None = None,\n        *,\n        policy: None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        outfp: SupportsWrite[bytes],\n        mangle_from_: bool | None = None,\n        maxheaderlen: int | None = None,\n        *,\n        policy: Policy[_MessageT],\n    ) -> None: ...\n\nclass DecodedGenerator(Generator[_MessageT]):\n    @overload\n    def __init__(\n        self: DecodedGenerator[Any],  # The Policy of the message is used.\n        outfp: SupportsWrite[str],\n        mangle_from_: bool | None = None,\n        maxheaderlen: int | None = None,\n        fmt: str | None = None,\n        *,\n        policy: None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        outfp: SupportsWrite[str],\n        mangle_from_: bool | None = None,\n        maxheaderlen: int | None = None,\n        fmt: str | None = None,\n        *,\n        policy: Policy[_MessageT],\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/header.pyi",
    "content": "from collections.abc import Iterable\nfrom email.charset import Charset\nfrom typing import Any, ClassVar\n\n__all__ = [\"Header\", \"decode_header\", \"make_header\"]\n\nclass Header:\n    def __init__(\n        self,\n        s: bytes | bytearray | str | None = None,\n        charset: Charset | str | None = None,\n        maxlinelen: int | None = None,\n        header_name: str | None = None,\n        continuation_ws: str = \" \",\n        errors: str = \"strict\",\n    ) -> None: ...\n    def append(self, s: bytes | bytearray | str, charset: Charset | str | None = None, errors: str = \"strict\") -> None: ...\n    def encode(self, splitchars: str = \";, \\t\", maxlinelen: int | None = None, linesep: str = \"\\n\") -> str: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __eq__(self, other: object) -> bool: ...\n    def __ne__(self, value: object, /) -> bool: ...\n\n# decode_header() either returns list[tuple[str, None]] if the header\n# contains no encoded parts, or list[tuple[bytes, str | None]] if the header\n# contains at least one encoded part.\ndef decode_header(header: Header | str) -> list[tuple[Any, Any | None]]: ...\ndef make_header(\n    decoded_seq: Iterable[tuple[bytes | bytearray | str, str | None]],\n    maxlinelen: int | None = None,\n    header_name: str | None = None,\n    continuation_ws: str = \" \",\n) -> Header: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/headerregistry.pyi",
    "content": "import sys\nimport types\nfrom collections.abc import Iterable, Mapping\nfrom datetime import datetime as _datetime\nfrom email._header_value_parser import (\n    AddressList,\n    ContentDisposition,\n    ContentTransferEncoding,\n    ContentType,\n    MessageID,\n    MIMEVersion,\n    TokenList,\n    UnstructuredTokenList,\n)\nfrom email.errors import MessageDefect\nfrom email.policy import Policy\nfrom typing import Any, ClassVar, Literal, Protocol, type_check_only\nfrom typing_extensions import Self\n\nclass BaseHeader(str):\n    # max_count is actually more of an abstract ClassVar (not defined on the base class, but expected to be defined in subclasses)\n    max_count: ClassVar[Literal[1] | None]\n    @property\n    def name(self) -> str: ...\n    @property\n    def defects(self) -> tuple[MessageDefect, ...]: ...\n    def __new__(cls, name: str, value: Any) -> Self: ...\n    def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect]) -> None: ...\n    def fold(self, *, policy: Policy) -> str: ...\n\nclass UnstructuredHeader:\n    max_count: ClassVar[Literal[1] | None]\n    @staticmethod\n    def value_parser(value: str) -> UnstructuredTokenList: ...\n    @classmethod\n    def parse(cls, value: str, kwds: dict[str, Any]) -> None: ...\n\nclass UniqueUnstructuredHeader(UnstructuredHeader):\n    max_count: ClassVar[Literal[1]]\n\nclass DateHeader:\n    max_count: ClassVar[Literal[1] | None]\n    def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], datetime: _datetime) -> None: ...\n    @property\n    def datetime(self) -> _datetime | None: ...\n    @staticmethod\n    def value_parser(value: str) -> UnstructuredTokenList: ...\n    @classmethod\n    def parse(cls, value: str | _datetime, kwds: dict[str, Any]) -> None: ...\n\nclass UniqueDateHeader(DateHeader):\n    max_count: ClassVar[Literal[1]]\n\nclass AddressHeader:\n    max_count: ClassVar[Literal[1] | None]\n    def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], groups: Iterable[Group]) -> None: ...\n    @property\n    def groups(self) -> tuple[Group, ...]: ...\n    @property\n    def addresses(self) -> tuple[Address, ...]: ...\n    @staticmethod\n    def value_parser(value: str) -> AddressList: ...\n    @classmethod\n    def parse(cls, value: str, kwds: dict[str, Any]) -> None: ...\n\nclass UniqueAddressHeader(AddressHeader):\n    max_count: ClassVar[Literal[1]]\n\nclass SingleAddressHeader(AddressHeader):\n    @property\n    def address(self) -> Address: ...\n\nclass UniqueSingleAddressHeader(SingleAddressHeader):\n    max_count: ClassVar[Literal[1]]\n\nclass MIMEVersionHeader:\n    max_count: ClassVar[Literal[1]]\n    def init(\n        self,\n        name: str,\n        *,\n        parse_tree: TokenList,\n        defects: Iterable[MessageDefect],\n        version: str | None,\n        major: int | None,\n        minor: int | None,\n    ) -> None: ...\n    @property\n    def version(self) -> str | None: ...\n    @property\n    def major(self) -> int | None: ...\n    @property\n    def minor(self) -> int | None: ...\n    @staticmethod\n    def value_parser(value: str) -> MIMEVersion: ...\n    @classmethod\n    def parse(cls, value: str, kwds: dict[str, Any]) -> None: ...\n\nclass ParameterizedMIMEHeader:\n    max_count: ClassVar[Literal[1]]\n    def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect], params: Mapping[str, Any]) -> None: ...\n    @property\n    def params(self) -> types.MappingProxyType[str, Any]: ...\n    @classmethod\n    def parse(cls, value: str, kwds: dict[str, Any]) -> None: ...\n\nclass ContentTypeHeader(ParameterizedMIMEHeader):\n    @property\n    def content_type(self) -> str: ...\n    @property\n    def maintype(self) -> str: ...\n    @property\n    def subtype(self) -> str: ...\n    @staticmethod\n    def value_parser(value: str) -> ContentType: ...\n\nclass ContentDispositionHeader(ParameterizedMIMEHeader):\n    # init is redefined but has the same signature as parent class, so is omitted from the stub\n    @property\n    def content_disposition(self) -> str | None: ...\n    @staticmethod\n    def value_parser(value: str) -> ContentDisposition: ...\n\nclass ContentTransferEncodingHeader:\n    max_count: ClassVar[Literal[1]]\n    def init(self, name: str, *, parse_tree: TokenList, defects: Iterable[MessageDefect]) -> None: ...\n    @property\n    def cte(self) -> str: ...\n    @classmethod\n    def parse(cls, value: str, kwds: dict[str, Any]) -> None: ...\n    @staticmethod\n    def value_parser(value: str) -> ContentTransferEncoding: ...\n\nclass MessageIDHeader:\n    max_count: ClassVar[Literal[1]]\n    @classmethod\n    def parse(cls, value: str, kwds: dict[str, Any]) -> None: ...\n    @staticmethod\n    def value_parser(value: str) -> MessageID: ...\n\nif sys.version_info >= (3, 13):\n    from email._header_value_parser import MessageIDList\n\n    # Added in Python 3.13.12, 3.14.3\n    class ReferencesHeader:\n        max_count: ClassVar[Literal[1]]\n        @classmethod\n        def parse(cls, value: str, kwds: dict[str, Any]) -> None: ...\n        @staticmethod\n        def value_parser(value: str) -> MessageIDList: ...\n\n@type_check_only\nclass _HeaderParser(Protocol):\n    max_count: ClassVar[Literal[1] | None]\n    @staticmethod\n    def value_parser(value: str, /) -> TokenList: ...\n    @classmethod\n    def parse(cls, value: str, kwds: dict[str, Any], /) -> None: ...\n\nclass HeaderRegistry:\n    registry: dict[str, type[_HeaderParser]]\n    base_class: type[BaseHeader]\n    default_class: type[_HeaderParser]\n    def __init__(\n        self, base_class: type[BaseHeader] = ..., default_class: type[_HeaderParser] = ..., use_default_map: bool = True\n    ) -> None: ...\n    def map_to_type(self, name: str, cls: type[BaseHeader]) -> None: ...\n    def __getitem__(self, name: str) -> type[BaseHeader]: ...\n    def __call__(self, name: str, value: Any) -> BaseHeader: ...\n\nclass Address:\n    @property\n    def display_name(self) -> str: ...\n    @property\n    def username(self) -> str: ...\n    @property\n    def domain(self) -> str: ...\n    @property\n    def addr_spec(self) -> str: ...\n    def __init__(\n        self, display_name: str = \"\", username: str | None = \"\", domain: str | None = \"\", addr_spec: str | None = None\n    ) -> None: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __eq__(self, other: object) -> bool: ...\n\nclass Group:\n    @property\n    def display_name(self) -> str | None: ...\n    @property\n    def addresses(self) -> tuple[Address, ...]: ...\n    def __init__(self, display_name: str | None = None, addresses: Iterable[Address] | None = None) -> None: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __eq__(self, other: object) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/iterators.pyi",
    "content": "from _typeshed import SupportsWrite\nfrom collections.abc import Iterator\nfrom email.message import Message\n\n__all__ = [\"body_line_iterator\", \"typed_subpart_iterator\", \"walk\"]\n\ndef body_line_iterator(msg: Message, decode: bool = False) -> Iterator[str]: ...\ndef typed_subpart_iterator(msg: Message, maintype: str = \"text\", subtype: str | None = None) -> Iterator[str]: ...\ndef walk(self: Message) -> Iterator[Message]: ...\n\n# We include the seemingly private function because it is documented in the stdlib documentation.\ndef _structure(msg: Message, fp: SupportsWrite[str] | None = None, level: int = 0, include_default: bool = False) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/message.pyi",
    "content": "from _typeshed import MaybeNone\nfrom collections.abc import Generator, Iterator, Sequence\nfrom email import _ParamsType, _ParamType\nfrom email.charset import Charset\nfrom email.contentmanager import ContentManager\nfrom email.errors import MessageDefect\nfrom email.policy import Policy\nfrom typing import Any, Generic, Literal, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\"Message\", \"EmailMessage\"]\n\n_T = TypeVar(\"_T\")\n# Type returned by Policy.header_fetch_parse, often str or Header.\n_HeaderT_co = TypeVar(\"_HeaderT_co\", covariant=True, default=str)\n_HeaderParamT_contra = TypeVar(\"_HeaderParamT_contra\", contravariant=True, default=str)\n# Represents headers constructed by HeaderRegistry. Those are sub-classes\n# of BaseHeader and another header type.\n_HeaderRegistryT_co = TypeVar(\"_HeaderRegistryT_co\", covariant=True, default=Any)\n_HeaderRegistryParamT_contra = TypeVar(\"_HeaderRegistryParamT_contra\", contravariant=True, default=Any)\n\n_PayloadType: TypeAlias = Message | str\n_EncodedPayloadType: TypeAlias = Message | bytes\n_MultipartPayloadType: TypeAlias = list[_PayloadType]\n_CharsetType: TypeAlias = Charset | str | None\n\n@type_check_only\nclass _SupportsEncodeToPayload(Protocol):\n    def encode(self, encoding: str, /) -> _PayloadType | _MultipartPayloadType | _SupportsDecodeToPayload: ...\n\n@type_check_only\nclass _SupportsDecodeToPayload(Protocol):\n    def decode(self, encoding: str, errors: str, /) -> _PayloadType | _MultipartPayloadType: ...\n\nclass Message(Generic[_HeaderT_co, _HeaderParamT_contra]):\n    # The policy attributes and arguments in this class and its subclasses\n    # would ideally use Policy[Self], but this is not possible.\n    policy: Policy[Any]  # undocumented\n    preamble: str | None\n    epilogue: str | None\n    defects: list[MessageDefect]\n    def __init__(self, policy: Policy[Any] = ...) -> None: ...\n    def is_multipart(self) -> bool: ...\n    def set_unixfrom(self, unixfrom: str) -> None: ...\n    def get_unixfrom(self) -> str | None: ...\n    def attach(self, payload: _PayloadType) -> None: ...\n    # `i: int` without a multipart payload results in an error\n    # `| MaybeNone` acts like `| Any`: can be None for cleared or unset payload, but annoying to check\n    @overload  # multipart\n    def get_payload(self, i: int, decode: Literal[True]) -> None: ...\n    @overload  # multipart\n    def get_payload(self, i: int, decode: Literal[False] = False) -> _PayloadType | MaybeNone: ...\n    @overload  # either\n    def get_payload(self, i: None = None, decode: Literal[False] = False) -> _PayloadType | _MultipartPayloadType | MaybeNone: ...\n    @overload  # not multipart\n    def get_payload(self, i: None = None, *, decode: Literal[True]) -> _EncodedPayloadType | MaybeNone: ...\n    @overload  # not multipart, IDEM but w/o kwarg\n    def get_payload(self, i: None, decode: Literal[True]) -> _EncodedPayloadType | MaybeNone: ...\n    # If `charset=None` and payload supports both `encode` AND `decode`,\n    # then an invalid payload could be passed, but this is unlikely\n    # Not[_SupportsEncodeToPayload]\n    @overload\n    def set_payload(\n        self, payload: _SupportsDecodeToPayload | _PayloadType | _MultipartPayloadType, charset: None = None\n    ) -> None: ...\n    @overload\n    def set_payload(\n        self,\n        payload: _SupportsEncodeToPayload | _SupportsDecodeToPayload | _PayloadType | _MultipartPayloadType,\n        charset: Charset | str,\n    ) -> None: ...\n    def set_charset(self, charset: _CharsetType) -> None: ...\n    def get_charset(self) -> _CharsetType: ...\n    def __len__(self) -> int: ...\n    def __contains__(self, name: str) -> bool: ...\n    def __iter__(self) -> Iterator[str]: ...\n    # Same as `get` with `failobj=None`, but with the expectation that it won't return None in most scenarios\n    # This is important for protocols using __getitem__, like SupportsKeysAndGetItem\n    # Morally, the return type should be `AnyOf[_HeaderType, None]`,\n    # so using \"the Any trick\" instead.\n    def __getitem__(self, name: str) -> _HeaderT_co | MaybeNone: ...\n    def __setitem__(self, name: str, val: _HeaderParamT_contra) -> None: ...\n    def __delitem__(self, name: str) -> None: ...\n    def keys(self) -> list[str]: ...\n    def values(self) -> list[_HeaderT_co]: ...\n    def items(self) -> list[tuple[str, _HeaderT_co]]: ...\n    @overload\n    def get(self, name: str, failobj: None = None) -> _HeaderT_co | None: ...\n    @overload\n    def get(self, name: str, failobj: _T) -> _HeaderT_co | _T: ...\n    @overload\n    def get_all(self, name: str, failobj: None = None) -> list[_HeaderT_co] | None: ...\n    @overload\n    def get_all(self, name: str, failobj: _T) -> list[_HeaderT_co] | _T: ...\n    def add_header(self, _name: str, _value: str, **_params: _ParamsType) -> None: ...\n    def replace_header(self, _name: str, _value: _HeaderParamT_contra) -> None: ...\n    def get_content_type(self) -> str: ...\n    def get_content_maintype(self) -> str: ...\n    def get_content_subtype(self) -> str: ...\n    def get_default_type(self) -> str: ...\n    def set_default_type(self, ctype: str) -> None: ...\n    @overload\n    def get_params(\n        self, failobj: None = None, header: str = \"content-type\", unquote: bool = True\n    ) -> list[tuple[str, str]] | None: ...\n    @overload\n    def get_params(self, failobj: _T, header: str = \"content-type\", unquote: bool = True) -> list[tuple[str, str]] | _T: ...\n    @overload\n    def get_param(\n        self, param: str, failobj: None = None, header: str = \"content-type\", unquote: bool = True\n    ) -> _ParamType | None: ...\n    @overload\n    def get_param(self, param: str, failobj: _T, header: str = \"content-type\", unquote: bool = True) -> _ParamType | _T: ...\n    def del_param(self, param: str, header: str = \"content-type\", requote: bool = True) -> None: ...\n    def set_type(self, type: str, header: str = \"Content-Type\", requote: bool = True) -> None: ...\n    @overload\n    def get_filename(self, failobj: None = None) -> str | None: ...\n    @overload\n    def get_filename(self, failobj: _T) -> str | _T: ...\n    @overload\n    def get_boundary(self, failobj: None = None) -> str | None: ...\n    @overload\n    def get_boundary(self, failobj: _T) -> str | _T: ...\n    def set_boundary(self, boundary: str) -> None: ...\n    @overload\n    def get_content_charset(self) -> str | None: ...\n    @overload\n    def get_content_charset(self, failobj: _T) -> str | _T: ...\n    @overload\n    def get_charsets(self, failobj: None = None) -> list[str | None]: ...\n    @overload\n    def get_charsets(self, failobj: _T) -> list[str | _T]: ...\n    def walk(self) -> Generator[Self, None, None]: ...\n    def get_content_disposition(self) -> str | None: ...\n    def as_string(self, unixfrom: bool = False, maxheaderlen: int = 0, policy: Policy[Any] | None = None) -> str: ...\n    def as_bytes(self, unixfrom: bool = False, policy: Policy[Any] | None = None) -> bytes: ...\n    def __bytes__(self) -> bytes: ...\n    def set_param(\n        self,\n        param: str,\n        value: str,\n        header: str = \"Content-Type\",\n        requote: bool = True,\n        charset: str | None = None,\n        language: str = \"\",\n        replace: bool = False,\n    ) -> None: ...\n    # The following two methods are undocumented, but a source code comment states that they are public API\n    def set_raw(self, name: str, value: _HeaderParamT_contra) -> None: ...\n    def raw_items(self) -> Iterator[tuple[str, _HeaderT_co]]: ...\n\nclass MIMEPart(Message[_HeaderRegistryT_co, _HeaderRegistryParamT_contra]):\n    def __init__(self, policy: Policy[Any] | None = None) -> None: ...\n    def get_body(self, preferencelist: Sequence[str] = (\"related\", \"html\", \"plain\")) -> MIMEPart[_HeaderRegistryT_co] | None: ...\n    def attach(self, payload: Self) -> None: ...  # type: ignore[override]\n    # The attachments are created via type(self) in the attach method. It's theoretically\n    # possible to sneak other attachment types into a MIMEPart instance, but could cause\n    # cause unforseen consequences.\n    def iter_attachments(self) -> Iterator[Self]: ...\n    def iter_parts(self) -> Iterator[MIMEPart[_HeaderRegistryT_co]]: ...\n    def get_content(self, *args: Any, content_manager: ContentManager | None = None, **kw: Any) -> Any: ...\n    def set_content(self, *args: Any, content_manager: ContentManager | None = None, **kw: Any) -> None: ...\n    def make_related(self, boundary: str | None = None) -> None: ...\n    def make_alternative(self, boundary: str | None = None) -> None: ...\n    def make_mixed(self, boundary: str | None = None) -> None: ...\n    def add_related(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> None: ...\n    def add_alternative(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> None: ...\n    def add_attachment(self, *args: Any, content_manager: ContentManager | None = ..., **kw: Any) -> None: ...\n    def clear(self) -> None: ...\n    def clear_content(self) -> None: ...\n    def as_string(self, unixfrom: bool = False, maxheaderlen: int | None = None, policy: Policy[Any] | None = None) -> str: ...\n    def is_attachment(self) -> bool: ...\n\nclass EmailMessage(MIMEPart): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/mime/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/email/mime/application.pyi",
    "content": "from collections.abc import Callable\nfrom email import _ParamsType\nfrom email.mime.nonmultipart import MIMENonMultipart\nfrom email.policy import Policy\n\n__all__ = [\"MIMEApplication\"]\n\nclass MIMEApplication(MIMENonMultipart):\n    def __init__(\n        self,\n        _data: str | bytes | bytearray,\n        _subtype: str = \"octet-stream\",\n        _encoder: Callable[[MIMEApplication], object] = ...,\n        *,\n        policy: Policy | None = None,\n        **_params: _ParamsType,\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/mime/audio.pyi",
    "content": "from collections.abc import Callable\nfrom email import _ParamsType\nfrom email.mime.nonmultipart import MIMENonMultipart\nfrom email.policy import Policy\n\n__all__ = [\"MIMEAudio\"]\n\nclass MIMEAudio(MIMENonMultipart):\n    def __init__(\n        self,\n        _audiodata: str | bytes | bytearray,\n        _subtype: str | None = None,\n        _encoder: Callable[[MIMEAudio], object] = ...,\n        *,\n        policy: Policy | None = None,\n        **_params: _ParamsType,\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/mime/base.pyi",
    "content": "import email.message\nfrom email import _ParamsType\nfrom email.policy import Policy\n\n__all__ = [\"MIMEBase\"]\n\nclass MIMEBase(email.message.Message):\n    def __init__(self, _maintype: str, _subtype: str, *, policy: Policy | None = None, **_params: _ParamsType) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/mime/image.pyi",
    "content": "from collections.abc import Callable\nfrom email import _ParamsType\nfrom email.mime.nonmultipart import MIMENonMultipart\nfrom email.policy import Policy\n\n__all__ = [\"MIMEImage\"]\n\nclass MIMEImage(MIMENonMultipart):\n    def __init__(\n        self,\n        _imagedata: str | bytes | bytearray,\n        _subtype: str | None = None,\n        _encoder: Callable[[MIMEImage], object] = ...,\n        *,\n        policy: Policy | None = None,\n        **_params: _ParamsType,\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/mime/message.pyi",
    "content": "from email._policybase import _MessageT\nfrom email.mime.nonmultipart import MIMENonMultipart\nfrom email.policy import Policy\n\n__all__ = [\"MIMEMessage\"]\n\nclass MIMEMessage(MIMENonMultipart):\n    def __init__(self, _msg: _MessageT, _subtype: str = \"rfc822\", *, policy: Policy[_MessageT] | None = None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/mime/multipart.pyi",
    "content": "from collections.abc import Sequence\nfrom email import _ParamsType\nfrom email._policybase import _MessageT\nfrom email.mime.base import MIMEBase\nfrom email.policy import Policy\n\n__all__ = [\"MIMEMultipart\"]\n\nclass MIMEMultipart(MIMEBase):\n    def __init__(\n        self,\n        _subtype: str = \"mixed\",\n        boundary: str | None = None,\n        _subparts: Sequence[_MessageT] | None = None,\n        *,\n        policy: Policy[_MessageT] | None = None,\n        **_params: _ParamsType,\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/mime/nonmultipart.pyi",
    "content": "from email.mime.base import MIMEBase\n\n__all__ = [\"MIMENonMultipart\"]\n\nclass MIMENonMultipart(MIMEBase): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/mime/text.pyi",
    "content": "from email._policybase import Policy\nfrom email.mime.nonmultipart import MIMENonMultipart\n\n__all__ = [\"MIMEText\"]\n\nclass MIMEText(MIMENonMultipart):\n    def __init__(\n        self, _text: str, _subtype: str = \"plain\", _charset: str | None = None, *, policy: Policy | None = None\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/parser.pyi",
    "content": "from _typeshed import SupportsRead\nfrom collections.abc import Callable\nfrom email._policybase import _MessageT\nfrom email.feedparser import BytesFeedParser as BytesFeedParser, FeedParser as FeedParser\nfrom email.message import Message\nfrom email.policy import Policy\nfrom io import _WrappedBuffer\nfrom typing import Generic, overload\n\n__all__ = [\"Parser\", \"HeaderParser\", \"BytesParser\", \"BytesHeaderParser\", \"FeedParser\", \"BytesFeedParser\"]\n\nclass Parser(Generic[_MessageT]):\n    @overload\n    def __init__(self: Parser[Message[str, str]], _class: None = None) -> None: ...\n    @overload\n    def __init__(self, _class: None = None, *, policy: Policy[_MessageT]) -> None: ...\n    @overload\n    def __init__(self, _class: Callable[[], _MessageT] | None, *, policy: Policy[_MessageT] = ...) -> None: ...\n    def parse(self, fp: SupportsRead[str], headersonly: bool = False) -> _MessageT: ...\n    def parsestr(self, text: str, headersonly: bool = False) -> _MessageT: ...\n\nclass HeaderParser(Parser[_MessageT]):\n    def parse(self, fp: SupportsRead[str], headersonly: bool = True) -> _MessageT: ...\n    def parsestr(self, text: str, headersonly: bool = True) -> _MessageT: ...\n\nclass BytesParser(Generic[_MessageT]):\n    parser: Parser[_MessageT]\n    @overload\n    def __init__(self: BytesParser[Message[str, str]], _class: None = None) -> None: ...\n    @overload\n    def __init__(self, _class: None = None, *, policy: Policy[_MessageT]) -> None: ...\n    @overload\n    def __init__(self, _class: Callable[[], _MessageT], *, policy: Policy[_MessageT] = ...) -> None: ...\n    def parse(self, fp: _WrappedBuffer, headersonly: bool = False) -> _MessageT: ...\n    def parsebytes(self, text: bytes | bytearray, headersonly: bool = False) -> _MessageT: ...\n\nclass BytesHeaderParser(BytesParser[_MessageT]):\n    def parse(self, fp: _WrappedBuffer, headersonly: bool = True) -> _MessageT: ...\n    def parsebytes(self, text: bytes | bytearray, headersonly: bool = True) -> _MessageT: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/policy.pyi",
    "content": "from collections.abc import Callable\nfrom email._policybase import Compat32 as Compat32, Policy as Policy, _MessageFactory, _MessageT, compat32 as compat32\nfrom email.contentmanager import ContentManager\nfrom email.message import EmailMessage\nfrom typing import Any, overload\nfrom typing_extensions import Self\n\n__all__ = [\"Compat32\", \"compat32\", \"Policy\", \"EmailPolicy\", \"default\", \"strict\", \"SMTP\", \"HTTP\"]\n\nclass EmailPolicy(Policy[_MessageT]):\n    utf8: bool\n    refold_source: str\n    header_factory: Callable[[str, Any], Any]\n    content_manager: ContentManager\n    @overload\n    def __init__(\n        self: EmailPolicy[EmailMessage],\n        *,\n        max_line_length: int | None = ...,\n        linesep: str = ...,\n        cte_type: str = ...,\n        raise_on_defect: bool = ...,\n        mangle_from_: bool = ...,\n        message_factory: None = None,\n        # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\n        verify_generated_headers: bool = ...,\n        utf8: bool = ...,\n        refold_source: str = ...,\n        header_factory: Callable[[str, str], str] = ...,\n        content_manager: ContentManager = ...,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        *,\n        max_line_length: int | None = ...,\n        linesep: str = ...,\n        cte_type: str = ...,\n        raise_on_defect: bool = ...,\n        mangle_from_: bool = ...,\n        message_factory: _MessageFactory[_MessageT] | None = ...,\n        # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\n        verify_generated_headers: bool = ...,\n        utf8: bool = ...,\n        refold_source: str = ...,\n        header_factory: Callable[[str, str], str] = ...,\n        content_manager: ContentManager = ...,\n    ) -> None: ...\n    def header_source_parse(self, sourcelines: list[str]) -> tuple[str, str]: ...\n    def header_store_parse(self, name: str, value: Any) -> tuple[str, Any]: ...\n    def header_fetch_parse(self, name: str, value: str) -> Any: ...\n    def fold(self, name: str, value: str) -> Any: ...\n    def fold_binary(self, name: str, value: str) -> bytes: ...\n    def clone(\n        self,\n        *,\n        max_line_length: int | None = ...,\n        linesep: str = ...,\n        cte_type: str = ...,\n        raise_on_defect: bool = ...,\n        mangle_from_: bool = ...,\n        message_factory: _MessageFactory[_MessageT] | None = ...,\n        # Added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\n        verify_generated_headers: bool = ...,\n        utf8: bool = ...,\n        refold_source: str = ...,\n        header_factory: Callable[[str, str], str] = ...,\n        content_manager: ContentManager = ...,\n    ) -> Self: ...\n\ndefault: EmailPolicy[EmailMessage]\nSMTP: EmailPolicy[EmailMessage]\nSMTPUTF8: EmailPolicy[EmailMessage]\nHTTP: EmailPolicy[EmailMessage]\nstrict: EmailPolicy[EmailMessage]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/quoprimime.pyi",
    "content": "from collections.abc import Iterable\n\n__all__ = [\n    \"body_decode\",\n    \"body_encode\",\n    \"body_length\",\n    \"decode\",\n    \"decodestring\",\n    \"header_decode\",\n    \"header_encode\",\n    \"header_length\",\n    \"quote\",\n    \"unquote\",\n]\n\ndef header_check(octet: int) -> bool: ...\ndef body_check(octet: int) -> bool: ...\ndef header_length(bytearray: Iterable[int]) -> int: ...\ndef body_length(bytearray: Iterable[int]) -> int: ...\ndef unquote(s: str | bytes | bytearray) -> str: ...\ndef quote(c: str | bytes | bytearray) -> str: ...\ndef header_encode(header_bytes: bytes | bytearray, charset: str = \"iso-8859-1\") -> str: ...\ndef body_encode(body: str, maxlinelen: int = 76, eol: str = \"\\n\") -> str: ...\ndef decode(encoded: str, eol: str = \"\\n\") -> str: ...\ndef header_decode(s: str) -> str: ...\n\nbody_decode = decode\ndecodestring = decode\n"
  },
  {
    "path": "mypy/typeshed/stdlib/email/utils.pyi",
    "content": "import datetime\nimport sys\nfrom _typeshed import Unused\nfrom collections.abc import Iterable\nfrom email import _ParamType\nfrom email.charset import Charset\nfrom typing import overload\nfrom typing_extensions import TypeAlias, deprecated\n\n__all__ = [\n    \"collapse_rfc2231_value\",\n    \"decode_params\",\n    \"decode_rfc2231\",\n    \"encode_rfc2231\",\n    \"formataddr\",\n    \"formatdate\",\n    \"format_datetime\",\n    \"getaddresses\",\n    \"make_msgid\",\n    \"mktime_tz\",\n    \"parseaddr\",\n    \"parsedate\",\n    \"parsedate_tz\",\n    \"parsedate_to_datetime\",\n    \"unquote\",\n]\n\n_PDTZ: TypeAlias = tuple[int, int, int, int, int, int, int, int, int, int | None]\n\ndef quote(str: str) -> str: ...\ndef unquote(str: str) -> str: ...\n\n# `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\ndef parseaddr(addr: str | list[str], *, strict: bool = True) -> tuple[str, str]: ...\ndef formataddr(pair: tuple[str | None, str], charset: str | Charset = \"utf-8\") -> str: ...\n\n# `strict` parameter added in Python 3.9.20, 3.10.15, 3.11.10, 3.12.5\ndef getaddresses(fieldvalues: Iterable[str], *, strict: bool = True) -> list[tuple[str, str]]: ...\n@overload\ndef parsedate(data: None) -> None: ...\n@overload\ndef parsedate(data: str) -> tuple[int, int, int, int, int, int, int, int, int] | None: ...\n@overload\ndef parsedate_tz(data: None) -> None: ...\n@overload\ndef parsedate_tz(data: str) -> _PDTZ | None: ...\ndef parsedate_to_datetime(data: str) -> datetime.datetime: ...\ndef mktime_tz(data: _PDTZ) -> int: ...\ndef formatdate(timeval: float | None = None, localtime: bool = False, usegmt: bool = False) -> str: ...\ndef format_datetime(dt: datetime.datetime, usegmt: bool = False) -> str: ...\n\nif sys.version_info >= (3, 14):\n    def localtime(dt: datetime.datetime | None = None) -> datetime.datetime: ...\n\nelif sys.version_info >= (3, 12):\n    @overload\n    def localtime(dt: datetime.datetime | None = None) -> datetime.datetime: ...\n    @overload\n    @deprecated(\"The `isdst` parameter does nothing and will be removed in Python 3.14.\")\n    def localtime(dt: datetime.datetime | None = None, isdst: Unused = None) -> datetime.datetime: ...\n\nelse:\n    def localtime(dt: datetime.datetime | None = None, isdst: int = -1) -> datetime.datetime: ...\n\ndef make_msgid(idstring: str | None = None, domain: str | None = None) -> str: ...\ndef decode_rfc2231(s: str) -> tuple[str | None, str | None, str]: ...  # May return list[str]. See issue #10431 for details.\ndef encode_rfc2231(s: str, charset: str | None = None, language: str | None = None) -> str: ...\ndef collapse_rfc2231_value(value: _ParamType, errors: str = \"replace\", fallback_charset: str = \"us-ascii\") -> str: ...\ndef decode_params(params: list[tuple[str, str]]) -> list[tuple[str, _ParamType]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/__init__.pyi",
    "content": "import sys\nfrom codecs import CodecInfo\n\nclass CodecRegistryError(LookupError, SystemError): ...\n\ndef normalize_encoding(encoding: str | bytes) -> str: ...\ndef search_function(encoding: str) -> CodecInfo | None: ...\n\nif sys.version_info >= (3, 14) and sys.platform == \"win32\":\n    def win32_code_page_search_function(encoding: str) -> CodecInfo | None: ...\n\n# Needed for submodules\ndef __getattr__(name: str): ...  # incomplete module\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/aliases.pyi",
    "content": "aliases: dict[str, str]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/ascii.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    # At runtime, this is codecs.ascii_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n    # At runtime, this is codecs.ascii_decode\n    @staticmethod\n    def decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\n# Note: encode being a decode function and decode being an encode function is accurate to runtime.\nclass StreamConverter(StreamWriter, StreamReader):  # type: ignore[misc]  # incompatible methods in base classes\n    # At runtime, this is codecs.ascii_decode\n    @staticmethod\n    def encode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...  # type: ignore[override]\n    # At runtime, this is codecs.ascii_encode\n    @staticmethod\n    def decode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...  # type: ignore[override]\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/base64_codec.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\nfrom typing import ClassVar\n\n# This codec is bytes to bytes.\n\ndef base64_encode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\ndef base64_decode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\n\nclass Codec(codecs.Codec):\n    def encode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n    def decode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass StreamWriter(Codec, codecs.StreamWriter):\n    charbuffertype: ClassVar[type] = ...\n\nclass StreamReader(Codec, codecs.StreamReader):\n    charbuffertype: ClassVar[type] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/big5.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/big5hkscs.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/bz2_codec.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\nfrom typing import ClassVar\n\n# This codec is bytes to bytes.\n\ndef bz2_encode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\ndef bz2_decode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\n\nclass Codec(codecs.Codec):\n    def encode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n    def decode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass StreamWriter(Codec, codecs.StreamWriter):\n    charbuffertype: ClassVar[type] = ...\n\nclass StreamReader(Codec, codecs.StreamReader):\n    charbuffertype: ClassVar[type] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/charmap.pyi",
    "content": "import codecs\nfrom _codecs import _CharMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    # At runtime, this is codecs.charmap_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[bytes, int]: ...\n    # At runtime, this is codecs.charmap_decode\n    @staticmethod\n    def decode(data: ReadableBuffer, errors: str | None = None, mapping: _CharMap | None = None, /) -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    mapping: _CharMap | None\n    def __init__(self, errors: str = \"strict\", mapping: _CharMap | None = None) -> None: ...\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    mapping: _CharMap | None\n    def __init__(self, errors: str = \"strict\", mapping: _CharMap | None = None) -> None: ...\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter):\n    mapping: _CharMap | None\n    def __init__(self, stream: codecs._WritableStream, errors: str = \"strict\", mapping: _CharMap | None = None) -> None: ...\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n\nclass StreamReader(Codec, codecs.StreamReader):\n    mapping: _CharMap | None\n    def __init__(self, stream: codecs._ReadableStream, errors: str = \"strict\", mapping: _CharMap | None = None) -> None: ...\n    def decode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[str, int]: ...  # type: ignore[override]\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp037.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1006.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1026.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1125.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1140.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1250.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1251.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1252.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1253.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1254.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1255.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1256.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1257.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp1258.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp273.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp424.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp437.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp500.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp720.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp737.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp775.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp850.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp852.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp855.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp856.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp857.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp858.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp860.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp861.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp862.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp863.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp864.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp865.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp866.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp869.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp874.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp875.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp932.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp949.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/cp950.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/euc_jis_2004.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/euc_jisx0213.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/euc_jp.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/euc_kr.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/gb18030.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/gb2312.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/gbk.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/hex_codec.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\nfrom typing import ClassVar\n\n# This codec is bytes to bytes.\n\ndef hex_encode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\ndef hex_decode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\n\nclass Codec(codecs.Codec):\n    def encode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n    def decode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass StreamWriter(Codec, codecs.StreamWriter):\n    charbuffertype: ClassVar[type] = ...\n\nclass StreamReader(Codec, codecs.StreamReader):\n    charbuffertype: ClassVar[type] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/hp_roman8.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/hz.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/idna.pyi",
    "content": "import codecs\nimport re\nfrom _typeshed import ReadableBuffer\n\ndots: re.Pattern[str]\nace_prefix: bytes\nsace_prefix: str\n\ndef nameprep(label: str) -> str: ...\ndef ToASCII(label: str) -> bytes: ...\ndef ToUnicode(label: bytes | str) -> str: ...\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: ReadableBuffer | str, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.BufferedIncrementalEncoder):\n    def _buffer_encode(self, input: str, errors: str, final: bool) -> tuple[bytes, int]: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    def _buffer_decode(self, input: ReadableBuffer | str, errors: str, final: bool) -> tuple[str, int]: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso2022_jp.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso2022_jp_1.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso2022_jp_2.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso2022_jp_2004.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso2022_jp_3.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso2022_jp_ext.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso2022_kr.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_1.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_10.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_11.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_13.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_14.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_15.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_16.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_2.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_3.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_4.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_5.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_6.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_7.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_8.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/iso8859_9.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/johab.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/koi8_r.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/koi8_t.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/koi8_u.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/kz1048.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/latin_1.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    # At runtime, this is codecs.latin_1_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n    # At runtime, this is codecs.latin_1_decode\n    @staticmethod\n    def decode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\n# Note: encode being a decode function and decode being an encode function is accurate to runtime.\nclass StreamConverter(StreamWriter, StreamReader):  # type: ignore[misc]  # incompatible methods in base classes\n    # At runtime, this is codecs.latin_1_decode\n    @staticmethod\n    def encode(data: ReadableBuffer, errors: str | None = None, /) -> tuple[str, int]: ...  # type: ignore[override]\n    # At runtime, this is codecs.latin_1_encode\n    @staticmethod\n    def decode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...  # type: ignore[override]\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mac_arabic.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_map: dict[int, int | None]\ndecoding_table: str\nencoding_map: dict[int, int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mac_croatian.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mac_cyrillic.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mac_farsi.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mac_greek.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mac_iceland.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mac_latin2.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mac_roman.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mac_romanian.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mac_turkish.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/mbcs.pyi",
    "content": "import codecs\nimport sys\nfrom _typeshed import ReadableBuffer\n\nif sys.platform == \"win32\":\n    encode = codecs.mbcs_encode\n\n    def decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\n    class IncrementalEncoder(codecs.IncrementalEncoder):\n        def encode(self, input: str, final: bool = False) -> bytes: ...\n\n    class IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n        # At runtime, this is codecs.mbcs_decode\n        @staticmethod\n        def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\n    class StreamWriter(codecs.StreamWriter):\n        # At runtime, this is codecs.mbcs_encode\n        @staticmethod\n        def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n\n    class StreamReader(codecs.StreamReader):\n        # At runtime, this is codecs.mbcs_decode\n        @staticmethod\n        def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\n    def getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/oem.pyi",
    "content": "import codecs\nimport sys\nfrom _typeshed import ReadableBuffer\n\nif sys.platform == \"win32\":\n    encode = codecs.oem_encode\n\n    def decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\n    class IncrementalEncoder(codecs.IncrementalEncoder):\n        def encode(self, input: str, final: bool = False) -> bytes: ...\n\n    class IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n        # At runtime, this is codecs.oem_decode\n        @staticmethod\n        def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\n    class StreamWriter(codecs.StreamWriter):\n        # At runtime, this is codecs.oem_encode\n        @staticmethod\n        def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n\n    class StreamReader(codecs.StreamReader):\n        # At runtime, this is codecs.oem_decode\n        @staticmethod\n        def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\n    def getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/palmos.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/ptcp154.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/punycode.pyi",
    "content": "import codecs\nfrom typing import Literal\n\ndef segregate(str: str) -> tuple[bytes, list[int]]: ...\ndef selective_len(str: str, max: int) -> int: ...\ndef selective_find(str: str, char: str, index: int, pos: int) -> tuple[int, int]: ...\ndef insertion_unsort(str: str, extended: list[int]) -> list[int]: ...\ndef T(j: int, bias: int) -> int: ...\n\ndigits: Literal[b\"abcdefghijklmnopqrstuvwxyz0123456789\"]\n\ndef generate_generalized_integer(N: int, bias: int) -> bytes: ...\ndef adapt(delta: int, first: bool, numchars: int) -> int: ...\ndef generate_integers(baselen: int, deltas: list[int]) -> bytes: ...\ndef punycode_encode(text: str) -> bytes: ...\ndef decode_generalized_number(extended: bytes, extpos: int, bias: int, errors: str) -> tuple[int, int | None]: ...\ndef insertion_sort(base: str, extended: bytes, errors: str) -> str: ...\ndef punycode_decode(text: memoryview | bytes | bytearray | str, errors: str) -> str: ...\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: memoryview | bytes | bytearray | str, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: memoryview | bytes | bytearray | str, final: bool = False) -> str: ...  # type: ignore[override]\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/quopri_codec.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\nfrom typing import ClassVar\n\n# This codec is bytes to bytes.\n\ndef quopri_encode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\ndef quopri_decode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\n\nclass Codec(codecs.Codec):\n    def encode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n    def decode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass StreamWriter(Codec, codecs.StreamWriter):\n    charbuffertype: ClassVar[type] = ...\n\nclass StreamReader(Codec, codecs.StreamReader):\n    charbuffertype: ClassVar[type] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/raw_unicode_escape.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    # At runtime, this is codecs.raw_unicode_escape_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n    # At runtime, this is codecs.raw_unicode_escape_decode\n    @staticmethod\n    def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\n\nclass StreamReader(Codec, codecs.StreamReader):\n    def decode(self, input: str | ReadableBuffer, errors: str = \"strict\") -> tuple[str, int]: ...  # type: ignore[override]\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/rot_13.pyi",
    "content": "import codecs\nfrom _typeshed import SupportsRead, SupportsWrite\n\n# This codec is string to string.\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[str, int]: ...  # type: ignore[override]\n    def decode(self, input: str, errors: str = \"strict\") -> tuple[str, int]: ...  # type: ignore[override]\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> str: ...  # type: ignore[override]\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: str, final: bool = False) -> str: ...  # type: ignore[override]\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\nrot13_map: dict[int, int]\n\ndef rot13(infile: SupportsRead[str], outfile: SupportsWrite[str]) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/shift_jis.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/shift_jis_2004.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/shift_jisx0213.pyi",
    "content": "import _multibytecodec as mbc\nimport codecs\nfrom typing import ClassVar\n\ncodec: mbc._MultibyteCodec\n\nclass Codec(codecs.Codec):\n    encode = codec.encode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n    decode = codec.decode  # type: ignore[assignment]  # pyright: ignore[reportAssignmentType]\n\nclass IncrementalEncoder(mbc.MultibyteIncrementalEncoder, codecs.IncrementalEncoder):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass IncrementalDecoder(mbc.MultibyteIncrementalDecoder, codecs.IncrementalDecoder):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamReader(Codec, mbc.MultibyteStreamReader, codecs.StreamReader):  # type: ignore[misc]\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\nclass StreamWriter(Codec, mbc.MultibyteStreamWriter, codecs.StreamWriter):\n    codec: ClassVar[mbc._MultibyteCodec] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/tis_620.pyi",
    "content": "import codecs\nfrom _codecs import _EncodingMap\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: bytes, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n\ndecoding_table: str\nencoding_table: _EncodingMap\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/undefined.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\n# These return types are just to match the base types. In reality, these always\n# raise an error.\n\nclass Codec(codecs.Codec):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n    def decode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> str: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\nclass StreamReader(Codec, codecs.StreamReader): ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/unicode_escape.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass Codec(codecs.Codec):\n    # At runtime, this is codecs.unicode_escape_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n    # At runtime, this is codecs.unicode_escape_decode\n    @staticmethod\n    def decode(data: str | ReadableBuffer, errors: str | None = None, final: bool = True, /) -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    def _buffer_decode(self, input: str | ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ...\n\nclass StreamWriter(Codec, codecs.StreamWriter): ...\n\nclass StreamReader(Codec, codecs.StreamReader):\n    def decode(self, input: str | ReadableBuffer, errors: str = \"strict\") -> tuple[str, int]: ...  # type: ignore[override]\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/utf_16.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nencode = codecs.utf_16_encode\n\ndef decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    def _buffer_decode(self, input: ReadableBuffer, errors: str, final: bool) -> tuple[str, int]: ...\n\nclass StreamWriter(codecs.StreamWriter):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n\nclass StreamReader(codecs.StreamReader):\n    def decode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[str, int]: ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/utf_16_be.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nencode = codecs.utf_16_be_encode\n\ndef decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    # At runtime, this is codecs.utf_16_be_decode\n    @staticmethod\n    def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\nclass StreamWriter(codecs.StreamWriter):\n    # At runtime, this is codecs.utf_16_be_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n\nclass StreamReader(codecs.StreamReader):\n    # At runtime, this is codecs.utf_16_be_decode\n    @staticmethod\n    def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/utf_16_le.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nencode = codecs.utf_16_le_encode\n\ndef decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    # At runtime, this is codecs.utf_16_le_decode\n    @staticmethod\n    def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\nclass StreamWriter(codecs.StreamWriter):\n    # At runtime, this is codecs.utf_16_le_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n\nclass StreamReader(codecs.StreamReader):\n    # At runtime, this is codecs.utf_16_le_decode\n    @staticmethod\n    def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/utf_32.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nencode = codecs.utf_32_encode\n\ndef decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    def _buffer_decode(self, input: ReadableBuffer, errors: str, final: bool) -> tuple[str, int]: ...\n\nclass StreamWriter(codecs.StreamWriter):\n    def encode(self, input: str, errors: str = \"strict\") -> tuple[bytes, int]: ...\n\nclass StreamReader(codecs.StreamReader):\n    def decode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[str, int]: ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/utf_32_be.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nencode = codecs.utf_32_be_encode\n\ndef decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    # At runtime, this is codecs.utf_32_be_decode\n    @staticmethod\n    def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\nclass StreamWriter(codecs.StreamWriter):\n    # At runtime, this is codecs.utf_32_be_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n\nclass StreamReader(codecs.StreamReader):\n    # At runtime, this is codecs.utf_32_be_decode\n    @staticmethod\n    def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/utf_32_le.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nencode = codecs.utf_32_le_encode\n\ndef decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    # At runtime, this is codecs.utf_32_le_decode\n    @staticmethod\n    def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\nclass StreamWriter(codecs.StreamWriter):\n    # At runtime, this is codecs.utf_32_le_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n\nclass StreamReader(codecs.StreamReader):\n    # At runtime, this is codecs.utf_32_le_decode\n    @staticmethod\n    def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/utf_7.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nencode = codecs.utf_7_encode\n\ndef decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    # At runtime, this is codecs.utf_7_decode\n    @staticmethod\n    def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\nclass StreamWriter(codecs.StreamWriter):\n    # At runtime, this is codecs.utf_7_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n\nclass StreamReader(codecs.StreamReader):\n    # At runtime, this is codecs.utf_7_decode\n    @staticmethod\n    def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/utf_8.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nencode = codecs.utf_8_encode\n\ndef decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    # At runtime, this is codecs.utf_8_decode\n    @staticmethod\n    def _buffer_decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\nclass StreamWriter(codecs.StreamWriter):\n    # At runtime, this is codecs.utf_8_encode\n    @staticmethod\n    def encode(str: str, errors: str | None = None, /) -> tuple[bytes, int]: ...\n\nclass StreamReader(codecs.StreamReader):\n    # At runtime, this is codecs.utf_8_decode\n    @staticmethod\n    def decode(data: ReadableBuffer, errors: str | None = None, final: bool = False, /) -> tuple[str, int]: ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/utf_8_sig.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def __init__(self, errors: str = \"strict\") -> None: ...\n    def encode(self, input: str, final: bool = False) -> bytes: ...\n    def getstate(self) -> int: ...\n    def setstate(self, state: int) -> None: ...  # type: ignore[override]\n\nclass IncrementalDecoder(codecs.BufferedIncrementalDecoder):\n    def __init__(self, errors: str = \"strict\") -> None: ...\n    def _buffer_decode(self, input: ReadableBuffer, errors: str | None, final: bool) -> tuple[str, int]: ...\n\nclass StreamWriter(codecs.StreamWriter):\n    def encode(self, input: str, errors: str | None = \"strict\") -> tuple[bytes, int]: ...\n\nclass StreamReader(codecs.StreamReader):\n    def decode(self, input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n\ndef getregentry() -> codecs.CodecInfo: ...\ndef encode(input: str, errors: str | None = \"strict\") -> tuple[bytes, int]: ...\ndef decode(input: ReadableBuffer, errors: str | None = \"strict\") -> tuple[str, int]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/uu_codec.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\nfrom typing import ClassVar\n\n# This codec is bytes to bytes.\n\ndef uu_encode(\n    input: ReadableBuffer, errors: str = \"strict\", filename: str = \"<data>\", mode: int = 0o666\n) -> tuple[bytes, int]: ...\ndef uu_decode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\n\nclass Codec(codecs.Codec):\n    def encode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n    def decode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass StreamWriter(Codec, codecs.StreamWriter):\n    charbuffertype: ClassVar[type] = ...\n\nclass StreamReader(Codec, codecs.StreamReader):\n    charbuffertype: ClassVar[type] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/encodings/zlib_codec.pyi",
    "content": "import codecs\nfrom _typeshed import ReadableBuffer\nfrom typing import ClassVar\n\n# This codec is bytes to bytes.\n\ndef zlib_encode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\ndef zlib_decode(input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...\n\nclass Codec(codecs.Codec):\n    def encode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n    def decode(self, input: ReadableBuffer, errors: str = \"strict\") -> tuple[bytes, int]: ...  # type: ignore[override]\n\nclass IncrementalEncoder(codecs.IncrementalEncoder):\n    def encode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass IncrementalDecoder(codecs.IncrementalDecoder):\n    def decode(self, input: ReadableBuffer, final: bool = False) -> bytes: ...  # type: ignore[override]\n\nclass StreamWriter(Codec, codecs.StreamWriter):\n    charbuffertype: ClassVar[type] = ...\n\nclass StreamReader(Codec, codecs.StreamReader):\n    charbuffertype: ClassVar[type] = ...\n\ndef getregentry() -> codecs.CodecInfo: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ensurepip/__init__.pyi",
    "content": "__all__ = [\"version\", \"bootstrap\"]\n\ndef version() -> str: ...\ndef bootstrap(\n    *,\n    root: str | None = None,\n    upgrade: bool = False,\n    user: bool = False,\n    altinstall: bool = False,\n    default_pip: bool = False,\n    verbosity: int = 0,\n) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/enum.pyi",
    "content": "import _typeshed\nimport sys\nimport types\nfrom _typeshed import SupportsKeysAndGetItem, Unused\nfrom builtins import property as _builtins_property\nfrom collections.abc import Callable, Iterable, Iterator, Mapping\nfrom typing import Any, Final, Generic, Literal, SupportsIndex, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias, disjoint_base\n\n__all__ = [\"EnumMeta\", \"Enum\", \"IntEnum\", \"Flag\", \"IntFlag\", \"auto\", \"unique\"]\n\nif sys.version_info >= (3, 11):\n    __all__ += [\n        \"CONFORM\",\n        \"CONTINUOUS\",\n        \"EJECT\",\n        \"EnumCheck\",\n        \"EnumType\",\n        \"FlagBoundary\",\n        \"KEEP\",\n        \"NAMED_FLAGS\",\n        \"ReprEnum\",\n        \"STRICT\",\n        \"StrEnum\",\n        \"UNIQUE\",\n        \"global_enum\",\n        \"global_enum_repr\",\n        \"global_flag_repr\",\n        \"global_str\",\n        \"member\",\n        \"nonmember\",\n        \"property\",\n        \"verify\",\n        \"pickle_by_enum_name\",\n        \"pickle_by_global_name\",\n    ]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"EnumDict\"]\n\n_EnumMemberT = TypeVar(\"_EnumMemberT\")\n_EnumerationT = TypeVar(\"_EnumerationT\", bound=type[Enum])\n\n# The following all work:\n# >>> from enum import Enum\n# >>> from string import ascii_lowercase\n# >>> Enum('Foo', names='RED YELLOW GREEN')\n# <enum 'Foo'>\n# >>> Enum('Foo', names=[('RED', 1), ('YELLOW, 2)])\n# <enum 'Foo'>\n# >>> Enum('Foo', names=((x for x in (ascii_lowercase[i], i)) for i in range(5)))\n# <enum 'Foo'>\n# >>> Enum('Foo', names={'RED': 1, 'YELLOW': 2})\n# <enum 'Foo'>\n_EnumNames: TypeAlias = str | Iterable[str] | Iterable[Iterable[str | Any]] | Mapping[str, Any]\n_Signature: TypeAlias = Any  # TODO: Unable to import Signature from inspect module\n\nif sys.version_info >= (3, 11):\n    class nonmember(Generic[_EnumMemberT]):\n        value: _EnumMemberT\n        def __init__(self, value: _EnumMemberT) -> None: ...\n\n    class member(Generic[_EnumMemberT]):\n        value: _EnumMemberT\n        def __init__(self, value: _EnumMemberT) -> None: ...\n\nclass _EnumDict(dict[str, Any]):\n    if sys.version_info >= (3, 13):\n        def __init__(self, cls_name: str | None = None) -> None: ...\n    else:\n        def __init__(self) -> None: ...\n\n    def __setitem__(self, key: str, value: Any) -> None: ...\n    if sys.version_info >= (3, 11):\n        # See comment above `typing.MutableMapping.update`\n        # for why overloads are preferable to a Union here\n        #\n        # Unlike with MutableMapping.update(), the first argument is required,\n        # hence the type: ignore\n        @overload  # type: ignore[override]\n        def update(self, members: SupportsKeysAndGetItem[str, Any], **more_members: Any) -> None: ...\n        @overload\n        def update(self, members: Iterable[tuple[str, Any]], **more_members: Any) -> None: ...\n    if sys.version_info >= (3, 13):\n        @property\n        def member_names(self) -> list[str]: ...\n\nif sys.version_info >= (3, 13):\n    EnumDict = _EnumDict\n\n# Structurally: Iterable[T], Reversible[T], Container[T] where T is the enum itself\nclass EnumMeta(type):\n    if sys.version_info >= (3, 11):\n        def __new__(\n            metacls: type[_typeshed.Self],\n            cls: str,\n            bases: tuple[type, ...],\n            classdict: _EnumDict,\n            *,\n            boundary: FlagBoundary | None = None,\n            _simple: bool = False,\n            **kwds: Any,\n        ) -> _typeshed.Self: ...\n    else:\n        def __new__(\n            metacls: type[_typeshed.Self], cls: str, bases: tuple[type, ...], classdict: _EnumDict, **kwds: Any\n        ) -> _typeshed.Self: ...\n\n    @classmethod\n    def __prepare__(metacls, cls: str, bases: tuple[type, ...], **kwds: Any) -> _EnumDict: ...  # type: ignore[override]\n    def __iter__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: ...\n    def __reversed__(self: type[_EnumMemberT]) -> Iterator[_EnumMemberT]: ...\n    if sys.version_info >= (3, 12):\n        def __contains__(self: type[Any], value: object) -> bool: ...\n    elif sys.version_info >= (3, 11):\n        def __contains__(self: type[Any], member: object) -> bool: ...\n    elif sys.version_info >= (3, 10):\n        def __contains__(self: type[Any], obj: object) -> bool: ...\n    else:\n        def __contains__(self: type[Any], member: object) -> bool: ...\n\n    def __getitem__(self: type[_EnumMemberT], name: str) -> _EnumMemberT: ...\n    @_builtins_property\n    def __members__(self: type[_EnumMemberT]) -> types.MappingProxyType[str, _EnumMemberT]: ...\n    def __len__(self) -> int: ...\n    def __bool__(self) -> Literal[True]: ...\n    def __dir__(self) -> list[str]: ...\n\n    # Overload 1: Value lookup on an already existing enum class (simple case)\n    @overload\n    def __call__(cls: type[_EnumMemberT], value: Any, names: None = None) -> _EnumMemberT: ...\n\n    # Overload 2: Functional API for constructing new enum classes.\n    if sys.version_info >= (3, 11):\n        @overload\n        def __call__(\n            cls,\n            value: str,\n            names: _EnumNames,\n            *,\n            module: str | None = None,\n            qualname: str | None = None,\n            type: type | None = None,\n            start: int = 1,\n            boundary: FlagBoundary | None = None,\n        ) -> type[Enum]: ...\n    else:\n        @overload\n        def __call__(\n            cls,\n            value: str,\n            names: _EnumNames,\n            *,\n            module: str | None = None,\n            qualname: str | None = None,\n            type: type | None = None,\n            start: int = 1,\n        ) -> type[Enum]: ...\n\n    # Overload 3 (py312+ only): Value lookup on an already existing enum class (complex case)\n    #\n    # >>> class Foo(enum.Enum):\n    # ...     X = 1, 2, 3\n    # >>> Foo(1, 2, 3)\n    # <Foo.X: (1, 2, 3)>\n    #\n    if sys.version_info >= (3, 12):\n        @overload\n        def __call__(cls: type[_EnumMemberT], value: Any, *values: Any) -> _EnumMemberT: ...\n    if sys.version_info >= (3, 14):\n        @property\n        def __signature__(cls) -> _Signature: ...\n\n    _member_names_: list[str]  # undocumented\n    _member_map_: dict[str, Enum]  # undocumented\n    _value2member_map_: dict[Any, Enum]  # undocumented\n\nif sys.version_info >= (3, 11):\n    # In 3.11 `EnumMeta` metaclass is renamed to `EnumType`, but old name also exists.\n    EnumType = EnumMeta\n\n    class property(types.DynamicClassAttribute):\n        def __set_name__(self, ownerclass: type[Enum], name: str) -> None: ...\n        name: str\n        clsname: str\n        member: Enum | None\n\n    _magic_enum_attr = property\nelse:\n    _magic_enum_attr = types.DynamicClassAttribute\n\nclass Enum(metaclass=EnumMeta):\n    @_magic_enum_attr\n    def name(self) -> str: ...\n    @_magic_enum_attr\n    def value(self) -> Any: ...\n    _name_: str\n    _value_: Any\n    _ignore_: str | list[str]\n    _order_: str\n    __order__: str\n    @classmethod\n    def _missing_(cls, value: object) -> Any: ...\n    @staticmethod\n    def _generate_next_value_(name: str, start: int, count: int, last_values: list[Any]) -> Any: ...\n    # It's not true that `__new__` will accept any argument type,\n    # so ideally we'd use `Any` to indicate that the argument type is inexpressible.\n    # However, using `Any` causes too many false-positives for those using mypy's `--disallow-any-expr`\n    # (see #7752, #2539, mypy/#5788),\n    # and in practice using `object` here has the same effect as using `Any`.\n    def __new__(cls, value: object) -> Self: ...\n    def __dir__(self) -> list[str]: ...\n    def __hash__(self) -> int: ...\n    def __format__(self, format_spec: str) -> str: ...\n    def __reduce_ex__(self, proto: Unused) -> tuple[Any, ...]: ...\n    if sys.version_info >= (3, 11):\n        def __copy__(self) -> Self: ...\n        def __deepcopy__(self, memo: Any) -> Self: ...\n    if sys.version_info >= (3, 12) and sys.version_info < (3, 14):\n        @classmethod\n        def __signature__(cls) -> str: ...\n    if sys.version_info >= (3, 13):\n        # Value may be any type, even in special enums. Enabling Enum parsing from\n        # multiple value types\n        def _add_value_alias_(self, value: Any) -> None: ...\n        def _add_alias_(self, name: str) -> None: ...\n\nif sys.version_info >= (3, 11):\n    class ReprEnum(Enum): ...\n\nif sys.version_info >= (3, 12):\n    class IntEnum(int, ReprEnum):\n        _value_: int\n        @_magic_enum_attr\n        def value(self) -> int: ...\n        def __new__(cls, value: int) -> Self: ...\n\nelse:\n    if sys.version_info >= (3, 11):\n        _IntEnumBase = ReprEnum\n    else:\n        _IntEnumBase = Enum\n\n    @disjoint_base\n    class IntEnum(int, _IntEnumBase):\n        _value_: int\n        @_magic_enum_attr\n        def value(self) -> int: ...\n        def __new__(cls, value: int) -> Self: ...\n\ndef unique(enumeration: _EnumerationT) -> _EnumerationT: ...\n\n_auto_null: Any\n\nclass Flag(Enum):\n    _name_: str | None  # type: ignore[assignment]\n    _value_: int\n    _numeric_repr_: Callable[[int], str]\n    @_magic_enum_attr\n    def name(self) -> str | None: ...  # type: ignore[override]\n    @_magic_enum_attr\n    def value(self) -> int: ...\n    def __contains__(self, other: Self) -> bool: ...\n    def __bool__(self) -> bool: ...\n    def __or__(self, other: Self) -> Self: ...\n    def __and__(self, other: Self) -> Self: ...\n    def __xor__(self, other: Self) -> Self: ...\n    def __invert__(self) -> Self: ...\n    if sys.version_info >= (3, 11):\n        def __iter__(self) -> Iterator[Self]: ...\n        def __len__(self) -> int: ...\n        __ror__ = __or__\n        __rand__ = __and__\n        __rxor__ = __xor__\n\nif sys.version_info >= (3, 11):\n    class StrEnum(str, ReprEnum):\n        def __new__(cls, value: str) -> Self: ...\n        _value_: str\n        @_magic_enum_attr\n        def value(self) -> str: ...\n        @staticmethod\n        def _generate_next_value_(name: str, start: int, count: int, last_values: list[str]) -> str: ...\n\n    class EnumCheck(StrEnum):\n        CONTINUOUS = \"no skipped integer values\"\n        NAMED_FLAGS = \"multi-flag aliases may not contain unnamed flags\"\n        UNIQUE = \"one name per value\"\n\n    CONTINUOUS: Final = EnumCheck.CONTINUOUS\n    NAMED_FLAGS: Final = EnumCheck.NAMED_FLAGS\n    UNIQUE: Final = EnumCheck.UNIQUE\n\n    class verify:\n        def __init__(self, *checks: EnumCheck) -> None: ...\n        def __call__(self, enumeration: _EnumerationT) -> _EnumerationT: ...\n\n    class FlagBoundary(StrEnum):\n        STRICT = \"strict\"\n        CONFORM = \"conform\"\n        EJECT = \"eject\"\n        KEEP = \"keep\"\n\n    STRICT: Final = FlagBoundary.STRICT\n    CONFORM: Final = FlagBoundary.CONFORM\n    EJECT: Final = FlagBoundary.EJECT\n    KEEP: Final = FlagBoundary.KEEP\n\n    def global_str(self: Enum) -> str: ...\n    def global_enum(cls: _EnumerationT, update_str: bool = False) -> _EnumerationT: ...\n    def global_enum_repr(self: Enum) -> str: ...\n    def global_flag_repr(self: Flag) -> str: ...\n    def show_flag_values(value: int) -> list[int]: ...\n    def bin(num: SupportsIndex, max_bits: int | None = None) -> str: ...\n\nif sys.version_info >= (3, 12):\n    # The body of the class is the same, but the base classes are different.\n    class IntFlag(int, ReprEnum, Flag, boundary=KEEP):  # type: ignore[misc]  # complaints about incompatible bases\n        def __new__(cls, value: int) -> Self: ...\n        def __or__(self, other: int) -> Self: ...\n        def __and__(self, other: int) -> Self: ...\n        def __xor__(self, other: int) -> Self: ...\n        def __invert__(self) -> Self: ...\n        __ror__ = __or__\n        __rand__ = __and__\n        __rxor__ = __xor__\n\nelif sys.version_info >= (3, 11):\n    # The body of the class is the same, but the base classes are different.\n    @disjoint_base\n    class IntFlag(int, ReprEnum, Flag, boundary=KEEP):  # type: ignore[misc]  # complaints about incompatible bases\n        def __new__(cls, value: int) -> Self: ...\n        def __or__(self, other: int) -> Self: ...\n        def __and__(self, other: int) -> Self: ...\n        def __xor__(self, other: int) -> Self: ...\n        def __invert__(self) -> Self: ...\n        __ror__ = __or__\n        __rand__ = __and__\n        __rxor__ = __xor__\n\nelse:\n    @disjoint_base\n    class IntFlag(int, Flag):  # type: ignore[misc]  # complaints about incompatible bases\n        def __new__(cls, value: int) -> Self: ...\n        def __or__(self, other: int) -> Self: ...\n        def __and__(self, other: int) -> Self: ...\n        def __xor__(self, other: int) -> Self: ...\n        def __invert__(self) -> Self: ...\n        __ror__ = __or__\n        __rand__ = __and__\n        __rxor__ = __xor__\n\nclass auto:\n    _value_: Any\n    @_magic_enum_attr\n    def value(self) -> Any: ...\n    def __new__(cls) -> Self: ...\n\n    # These don't exist, but auto is basically immediately replaced with\n    # either an int or a str depending on the type of the enum. StrEnum's auto\n    # shouldn't have these, but they're needed for int versions of auto (mostly the __or__).\n    # Ideally type checkers would special case auto enough to handle this,\n    # but until then this is a slightly inaccurate helping hand.\n    def __or__(self, other: int | Self) -> Self: ...\n    def __and__(self, other: int | Self) -> Self: ...\n    def __xor__(self, other: int | Self) -> Self: ...\n    __ror__ = __or__\n    __rand__ = __and__\n    __rxor__ = __xor__\n\nif sys.version_info >= (3, 11):\n    def pickle_by_global_name(self: Enum, proto: int) -> str: ...\n    def pickle_by_enum_name(self: _EnumMemberT, proto: int) -> tuple[Callable[..., Any], tuple[type[_EnumMemberT], str]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/errno.pyi",
    "content": "import sys\nfrom collections.abc import Mapping\nfrom typing import Final\n\nerrorcode: Mapping[int, str]\n\nEPERM: Final[int]\nENOENT: Final[int]\nESRCH: Final[int]\nEINTR: Final[int]\nEIO: Final[int]\nENXIO: Final[int]\nE2BIG: Final[int]\nENOEXEC: Final[int]\nEBADF: Final[int]\nECHILD: Final[int]\nEAGAIN: Final[int]\nENOMEM: Final[int]\nEACCES: Final[int]\nEFAULT: Final[int]\nEBUSY: Final[int]\nEEXIST: Final[int]\nEXDEV: Final[int]\nENODEV: Final[int]\nENOTDIR: Final[int]\nEISDIR: Final[int]\nEINVAL: Final[int]\nENFILE: Final[int]\nEMFILE: Final[int]\nENOTTY: Final[int]\nETXTBSY: Final[int]\nEFBIG: Final[int]\nENOSPC: Final[int]\nESPIPE: Final[int]\nEROFS: Final[int]\nEMLINK: Final[int]\nEPIPE: Final[int]\nEDOM: Final[int]\nERANGE: Final[int]\nEDEADLK: Final[int]\nENAMETOOLONG: Final[int]\nENOLCK: Final[int]\nENOSYS: Final[int]\nENOTEMPTY: Final[int]\nELOOP: Final[int]\nEWOULDBLOCK: Final[int]\nENOMSG: Final[int]\nEIDRM: Final[int]\nENOSTR: Final[int]\nENODATA: Final[int]\nETIME: Final[int]\nENOSR: Final[int]\nEREMOTE: Final[int]\nENOLINK: Final[int]\nEPROTO: Final[int]\nEBADMSG: Final[int]\nEOVERFLOW: Final[int]\nEILSEQ: Final[int]\nEUSERS: Final[int]\nENOTSOCK: Final[int]\nEDESTADDRREQ: Final[int]\nEMSGSIZE: Final[int]\nEPROTOTYPE: Final[int]\nENOPROTOOPT: Final[int]\nEPROTONOSUPPORT: Final[int]\nESOCKTNOSUPPORT: Final[int]\nENOTSUP: Final[int]\nEOPNOTSUPP: Final[int]\nEPFNOSUPPORT: Final[int]\nEAFNOSUPPORT: Final[int]\nEADDRINUSE: Final[int]\nEADDRNOTAVAIL: Final[int]\nENETDOWN: Final[int]\nENETUNREACH: Final[int]\nENETRESET: Final[int]\nECONNABORTED: Final[int]\nECONNRESET: Final[int]\nENOBUFS: Final[int]\nEISCONN: Final[int]\nENOTCONN: Final[int]\nESHUTDOWN: Final[int]\nETOOMANYREFS: Final[int]\nETIMEDOUT: Final[int]\nECONNREFUSED: Final[int]\nEHOSTDOWN: Final[int]\nEHOSTUNREACH: Final[int]\nEALREADY: Final[int]\nEINPROGRESS: Final[int]\nESTALE: Final[int]\nEDQUOT: Final[int]\nECANCELED: Final[int]  # undocumented\nENOTRECOVERABLE: Final[int]  # undocumented\nEOWNERDEAD: Final[int]  # undocumented\n\nif sys.platform == \"sunos5\" or sys.platform == \"solaris\":  # noqa: Y008\n    ELOCKUNMAPPED: Final[int]\n    ENOTACTIVE: Final[int]\n\nif sys.platform != \"win32\":\n    ENOTBLK: Final[int]\n    EMULTIHOP: Final[int]\n\nif sys.platform == \"darwin\":\n    # All of the below are undocumented\n    EAUTH: Final[int]\n    EBADARCH: Final[int]\n    EBADEXEC: Final[int]\n    EBADMACHO: Final[int]\n    EBADRPC: Final[int]\n    EDEVERR: Final[int]\n    EFTYPE: Final[int]\n    ENEEDAUTH: Final[int]\n    ENOATTR: Final[int]\n    ENOPOLICY: Final[int]\n    EPROCLIM: Final[int]\n    EPROCUNAVAIL: Final[int]\n    EPROGMISMATCH: Final[int]\n    EPROGUNAVAIL: Final[int]\n    EPWROFF: Final[int]\n    ERPCMISMATCH: Final[int]\n    ESHLIBVERS: Final[int]\n    if sys.version_info >= (3, 11):\n        EQFULL: Final[int]\n        ENOTCAPABLE: Final[int]  # available starting with 3.11.1\n\nif sys.platform != \"darwin\":\n    EDEADLOCK: Final[int]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    ECHRNG: Final[int]\n    EL2NSYNC: Final[int]\n    EL3HLT: Final[int]\n    EL3RST: Final[int]\n    ELNRNG: Final[int]\n    EUNATCH: Final[int]\n    ENOCSI: Final[int]\n    EL2HLT: Final[int]\n    EBADE: Final[int]\n    EBADR: Final[int]\n    EXFULL: Final[int]\n    ENOANO: Final[int]\n    EBADRQC: Final[int]\n    EBADSLT: Final[int]\n    EBFONT: Final[int]\n    ENONET: Final[int]\n    ENOPKG: Final[int]\n    EADV: Final[int]\n    ESRMNT: Final[int]\n    ECOMM: Final[int]\n    EDOTDOT: Final[int]\n    ENOTUNIQ: Final[int]\n    EBADFD: Final[int]\n    EREMCHG: Final[int]\n    ELIBACC: Final[int]\n    ELIBBAD: Final[int]\n    ELIBSCN: Final[int]\n    ELIBMAX: Final[int]\n    ELIBEXEC: Final[int]\n    ERESTART: Final[int]\n    ESTRPIPE: Final[int]\n    EUCLEAN: Final[int]\n    ENOTNAM: Final[int]\n    ENAVAIL: Final[int]\n    EISNAM: Final[int]\n    EREMOTEIO: Final[int]\n    # All of the below are undocumented\n    EKEYEXPIRED: Final[int]\n    EKEYREJECTED: Final[int]\n    EKEYREVOKED: Final[int]\n    EMEDIUMTYPE: Final[int]\n    ENOKEY: Final[int]\n    ENOMEDIUM: Final[int]\n    ERFKILL: Final[int]\n\n    if sys.version_info >= (3, 14):\n        EHWPOISON: Final[int]\n\nif sys.platform == \"win32\":\n    # All of these are undocumented\n    WSABASEERR: Final[int]\n    WSAEACCES: Final[int]\n    WSAEADDRINUSE: Final[int]\n    WSAEADDRNOTAVAIL: Final[int]\n    WSAEAFNOSUPPORT: Final[int]\n    WSAEALREADY: Final[int]\n    WSAEBADF: Final[int]\n    WSAECONNABORTED: Final[int]\n    WSAECONNREFUSED: Final[int]\n    WSAECONNRESET: Final[int]\n    WSAEDESTADDRREQ: Final[int]\n    WSAEDISCON: Final[int]\n    WSAEDQUOT: Final[int]\n    WSAEFAULT: Final[int]\n    WSAEHOSTDOWN: Final[int]\n    WSAEHOSTUNREACH: Final[int]\n    WSAEINPROGRESS: Final[int]\n    WSAEINTR: Final[int]\n    WSAEINVAL: Final[int]\n    WSAEISCONN: Final[int]\n    WSAELOOP: Final[int]\n    WSAEMFILE: Final[int]\n    WSAEMSGSIZE: Final[int]\n    WSAENAMETOOLONG: Final[int]\n    WSAENETDOWN: Final[int]\n    WSAENETRESET: Final[int]\n    WSAENETUNREACH: Final[int]\n    WSAENOBUFS: Final[int]\n    WSAENOPROTOOPT: Final[int]\n    WSAENOTCONN: Final[int]\n    WSAENOTEMPTY: Final[int]\n    WSAENOTSOCK: Final[int]\n    WSAEOPNOTSUPP: Final[int]\n    WSAEPFNOSUPPORT: Final[int]\n    WSAEPROCLIM: Final[int]\n    WSAEPROTONOSUPPORT: Final[int]\n    WSAEPROTOTYPE: Final[int]\n    WSAEREMOTE: Final[int]\n    WSAESHUTDOWN: Final[int]\n    WSAESOCKTNOSUPPORT: Final[int]\n    WSAESTALE: Final[int]\n    WSAETIMEDOUT: Final[int]\n    WSAETOOMANYREFS: Final[int]\n    WSAEUSERS: Final[int]\n    WSAEWOULDBLOCK: Final[int]\n    WSANOTINITIALISED: Final[int]\n    WSASYSNOTREADY: Final[int]\n    WSAVERNOTSUPPORTED: Final[int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/faulthandler.pyi",
    "content": "import sys\nfrom _typeshed import FileDescriptorLike\n\ndef cancel_dump_traceback_later() -> None: ...\ndef disable() -> None: ...\ndef dump_traceback(file: FileDescriptorLike = sys.stderr, all_threads: bool = True) -> None: ...\n\nif sys.version_info >= (3, 14):\n    def dump_c_stack(file: FileDescriptorLike = sys.stderr) -> None: ...\n\ndef dump_traceback_later(\n    timeout: float, repeat: bool = False, file: FileDescriptorLike = sys.stderr, exit: bool = False\n) -> None: ...\n\nif sys.version_info >= (3, 14):\n    def enable(file: FileDescriptorLike = sys.stderr, all_threads: bool = True, c_stack: bool = True) -> None: ...\n\nelse:\n    def enable(file: FileDescriptorLike = sys.stderr, all_threads: bool = True) -> None: ...\n\ndef is_enabled() -> bool: ...\n\nif sys.platform != \"win32\":\n    def register(signum: int, file: FileDescriptorLike = sys.stderr, all_threads: bool = True, chain: bool = False) -> None: ...\n    def unregister(signum: int, /) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/fcntl.pyi",
    "content": "import sys\nfrom _typeshed import FileDescriptorLike, ReadOnlyBuffer, WriteableBuffer\nfrom typing import Any, Final, Literal, overload\nfrom typing_extensions import Buffer\n\nif sys.platform != \"win32\":\n    FASYNC: Final[int]\n    FD_CLOEXEC: Final[int]\n    F_DUPFD: Final[int]\n    F_DUPFD_CLOEXEC: Final[int]\n    F_GETFD: Final[int]\n    F_GETFL: Final[int]\n    F_GETLK: Final[int]\n    F_GETOWN: Final[int]\n    F_RDLCK: Final[int]\n    F_SETFD: Final[int]\n    F_SETFL: Final[int]\n    F_SETLK: Final[int]\n    F_SETLKW: Final[int]\n    F_SETOWN: Final[int]\n    F_UNLCK: Final[int]\n    F_WRLCK: Final[int]\n\n    F_GETLEASE: Final[int]\n    F_SETLEASE: Final[int]\n    if sys.platform == \"darwin\":\n        F_FULLFSYNC: Final[int]\n        F_NOCACHE: Final[int]\n        F_GETPATH: Final[int]\n    if sys.platform == \"linux\":\n        F_SETLKW64: Final[int]\n        F_SETSIG: Final[int]\n        F_SHLCK: Final[int]\n        F_SETLK64: Final[int]\n        F_GETSIG: Final[int]\n        F_NOTIFY: Final[int]\n        F_EXLCK: Final[int]\n        F_GETLK64: Final[int]\n        F_ADD_SEALS: Final[int]\n        F_GET_SEALS: Final[int]\n        F_SEAL_GROW: Final[int]\n        F_SEAL_SEAL: Final[int]\n        F_SEAL_SHRINK: Final[int]\n        F_SEAL_WRITE: Final[int]\n        F_OFD_GETLK: Final[int]\n        F_OFD_SETLK: Final[int]\n        F_OFD_SETLKW: Final[int]\n\n        if sys.version_info >= (3, 10):\n            F_GETPIPE_SZ: Final[int]\n            F_SETPIPE_SZ: Final[int]\n\n        DN_ACCESS: Final[int]\n        DN_ATTRIB: Final[int]\n        DN_CREATE: Final[int]\n        DN_DELETE: Final[int]\n        DN_MODIFY: Final[int]\n        DN_MULTISHOT: Final[int]\n        DN_RENAME: Final[int]\n\n    LOCK_EX: Final[int]\n    LOCK_NB: Final[int]\n    LOCK_SH: Final[int]\n    LOCK_UN: Final[int]\n    if sys.platform == \"linux\":\n        LOCK_MAND: Final[int]\n        LOCK_READ: Final[int]\n        LOCK_RW: Final[int]\n        LOCK_WRITE: Final[int]\n\n    if sys.platform == \"linux\":\n        # Constants for the POSIX STREAMS interface. Present in glibc until 2.29 (released February 2019).\n        # Never implemented on BSD, and considered \"obsolescent\" starting in POSIX 2008.\n        # Probably still used on Solaris.\n        I_ATMARK: Final[int]\n        I_CANPUT: Final[int]\n        I_CKBAND: Final[int]\n        I_FDINSERT: Final[int]\n        I_FIND: Final[int]\n        I_FLUSH: Final[int]\n        I_FLUSHBAND: Final[int]\n        I_GETBAND: Final[int]\n        I_GETCLTIME: Final[int]\n        I_GETSIG: Final[int]\n        I_GRDOPT: Final[int]\n        I_GWROPT: Final[int]\n        I_LINK: Final[int]\n        I_LIST: Final[int]\n        I_LOOK: Final[int]\n        I_NREAD: Final[int]\n        I_PEEK: Final[int]\n        I_PLINK: Final[int]\n        I_POP: Final[int]\n        I_PUNLINK: Final[int]\n        I_PUSH: Final[int]\n        I_RECVFD: Final[int]\n        I_SENDFD: Final[int]\n        I_SETCLTIME: Final[int]\n        I_SETSIG: Final[int]\n        I_SRDOPT: Final[int]\n        I_STR: Final[int]\n        I_SWROPT: Final[int]\n        I_UNLINK: Final[int]\n\n    if sys.version_info >= (3, 12) and sys.platform == \"linux\":\n        FICLONE: Final[int]\n        FICLONERANGE: Final[int]\n\n    if sys.version_info >= (3, 13) and sys.platform == \"linux\":\n        F_OWNER_TID: Final = 0\n        F_OWNER_PID: Final = 1\n        F_OWNER_PGRP: Final = 2\n        F_SETOWN_EX: Final = 15\n        F_GETOWN_EX: Final = 16\n        F_SEAL_FUTURE_WRITE: Final = 16\n        F_GET_RW_HINT: Final = 1035\n        F_SET_RW_HINT: Final = 1036\n        F_GET_FILE_RW_HINT: Final = 1037\n        F_SET_FILE_RW_HINT: Final = 1038\n        RWH_WRITE_LIFE_NOT_SET: Final = 0\n        RWH_WRITE_LIFE_NONE: Final = 1\n        RWH_WRITE_LIFE_SHORT: Final = 2\n        RWH_WRITE_LIFE_MEDIUM: Final = 3\n        RWH_WRITE_LIFE_LONG: Final = 4\n        RWH_WRITE_LIFE_EXTREME: Final = 5\n\n    if sys.version_info >= (3, 11) and sys.platform == \"darwin\":\n        F_OFD_SETLK: Final = 90\n        F_OFD_SETLKW: Final = 91\n        F_OFD_GETLK: Final = 92\n\n    if sys.version_info >= (3, 13) and sys.platform != \"linux\":\n        # OSx and NetBSD\n        F_GETNOSIGPIPE: Final[int]\n        F_SETNOSIGPIPE: Final[int]\n        # OSx and FreeBSD\n        F_RDAHEAD: Final[int]\n\n    @overload\n    def fcntl(fd: FileDescriptorLike, cmd: int, arg: int = 0, /) -> int: ...\n    @overload\n    def fcntl(fd: FileDescriptorLike, cmd: int, arg: str | ReadOnlyBuffer, /) -> bytes: ...\n    # If arg is an int, return int\n    @overload\n    def ioctl(fd: FileDescriptorLike, request: int, arg: int = 0, mutate_flag: bool = True, /) -> int: ...\n    # The return type works as follows:\n    # - If arg is a read-write buffer, return int if mutate_flag is True, otherwise bytes\n    # - If arg is a read-only buffer, return bytes (and ignore the value of mutate_flag)\n    # We can't represent that precisely as we can't distinguish between read-write and read-only\n    # buffers, so we add overloads for a few unambiguous cases and use Any for the rest.\n    @overload\n    def ioctl(fd: FileDescriptorLike, request: int, arg: bytes, mutate_flag: bool = True, /) -> bytes: ...\n    @overload\n    def ioctl(fd: FileDescriptorLike, request: int, arg: WriteableBuffer, mutate_flag: Literal[False], /) -> bytes: ...\n    @overload\n    def ioctl(fd: FileDescriptorLike, request: int, arg: Buffer, mutate_flag: bool = True, /) -> Any: ...\n    def flock(fd: FileDescriptorLike, operation: int, /) -> None: ...\n    def lockf(fd: FileDescriptorLike, cmd: int, len: int = 0, start: int = 0, whence: int = 0, /) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/filecmp.pyi",
    "content": "import sys\nfrom _typeshed import GenericPath, StrOrBytesPath\nfrom collections.abc import Callable, Iterable, Sequence\nfrom types import GenericAlias\nfrom typing import Any, AnyStr, Final, Generic, Literal\n\n__all__ = [\"clear_cache\", \"cmp\", \"dircmp\", \"cmpfiles\", \"DEFAULT_IGNORES\"]\n\nDEFAULT_IGNORES: Final[list[str]]\nBUFSIZE: Final = 8192\n\ndef cmp(f1: StrOrBytesPath, f2: StrOrBytesPath, shallow: bool | Literal[0, 1] = True) -> bool: ...\ndef cmpfiles(\n    a: GenericPath[AnyStr], b: GenericPath[AnyStr], common: Iterable[GenericPath[AnyStr]], shallow: bool | Literal[0, 1] = True\n) -> tuple[list[AnyStr], list[AnyStr], list[AnyStr]]: ...\n\nclass dircmp(Generic[AnyStr]):\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            a: GenericPath[AnyStr],\n            b: GenericPath[AnyStr],\n            ignore: Sequence[AnyStr] | None = None,\n            hide: Sequence[AnyStr] | None = None,\n            *,\n            shallow: bool = True,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            a: GenericPath[AnyStr],\n            b: GenericPath[AnyStr],\n            ignore: Sequence[AnyStr] | None = None,\n            hide: Sequence[AnyStr] | None = None,\n        ) -> None: ...\n    left: AnyStr\n    right: AnyStr\n    hide: Sequence[AnyStr]\n    ignore: Sequence[AnyStr]\n    # These properties are created at runtime by __getattr__\n    subdirs: dict[AnyStr, dircmp[AnyStr]]\n    same_files: list[AnyStr]\n    diff_files: list[AnyStr]\n    funny_files: list[AnyStr]\n    common_dirs: list[AnyStr]\n    common_files: list[AnyStr]\n    common_funny: list[AnyStr]\n    common: list[AnyStr]\n    left_only: list[AnyStr]\n    right_only: list[AnyStr]\n    left_list: list[AnyStr]\n    right_list: list[AnyStr]\n    def report(self) -> None: ...\n    def report_partial_closure(self) -> None: ...\n    def report_full_closure(self) -> None: ...\n    methodmap: dict[str, Callable[[], None]]\n    def phase0(self) -> None: ...\n    def phase1(self) -> None: ...\n    def phase2(self) -> None: ...\n    def phase3(self) -> None: ...\n    def phase4(self) -> None: ...\n    def phase4_closure(self) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\ndef clear_cache() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/fileinput.pyi",
    "content": "import sys\nfrom _typeshed import AnyStr_co, StrOrBytesPath\nfrom collections.abc import Callable, Iterable, Iterator\nfrom types import GenericAlias, TracebackType\nfrom typing import IO, Any, AnyStr, Literal, Protocol, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, deprecated\n\n__all__ = [\n    \"input\",\n    \"close\",\n    \"nextfile\",\n    \"filename\",\n    \"lineno\",\n    \"filelineno\",\n    \"fileno\",\n    \"isfirstline\",\n    \"isstdin\",\n    \"FileInput\",\n    \"hook_compressed\",\n    \"hook_encoded\",\n]\n\nif sys.version_info >= (3, 11):\n    _TextMode: TypeAlias = Literal[\"r\"]\nelse:\n    _TextMode: TypeAlias = Literal[\"r\", \"rU\", \"U\"]\n\n@type_check_only\nclass _HasReadlineAndFileno(Protocol[AnyStr_co]):\n    def readline(self) -> AnyStr_co: ...\n    def fileno(self) -> int: ...\n\nif sys.version_info >= (3, 10):\n    # encoding and errors are added\n    @overload\n    def input(\n        files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n        inplace: bool = False,\n        backup: str = \"\",\n        *,\n        mode: _TextMode = \"r\",\n        openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n    ) -> FileInput[str]: ...\n    @overload\n    def input(\n        files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n        inplace: bool = False,\n        backup: str = \"\",\n        *,\n        mode: Literal[\"rb\"],\n        openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None,\n        encoding: None = None,\n        errors: None = None,\n    ) -> FileInput[bytes]: ...\n    @overload\n    def input(\n        files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n        inplace: bool = False,\n        backup: str = \"\",\n        *,\n        mode: str,\n        openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n    ) -> FileInput[Any]: ...\n\nelse:\n    # bufsize is dropped and mode and openhook become keyword-only\n    @overload\n    def input(\n        files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n        inplace: bool = False,\n        backup: str = \"\",\n        *,\n        mode: _TextMode = \"r\",\n        openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None,\n    ) -> FileInput[str]: ...\n    @overload\n    def input(\n        files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n        inplace: bool = False,\n        backup: str = \"\",\n        *,\n        mode: Literal[\"rb\"],\n        openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None,\n    ) -> FileInput[bytes]: ...\n    @overload\n    def input(\n        files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n        inplace: bool = False,\n        backup: str = \"\",\n        *,\n        mode: str,\n        openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None,\n    ) -> FileInput[Any]: ...\n\ndef close() -> None: ...\ndef nextfile() -> None: ...\ndef filename() -> str: ...\ndef lineno() -> int: ...\ndef filelineno() -> int: ...\ndef fileno() -> int: ...\ndef isfirstline() -> bool: ...\ndef isstdin() -> bool: ...\n\nclass FileInput(Iterator[AnyStr]):\n    if sys.version_info >= (3, 10):\n        # encoding and errors are added\n        @overload\n        def __init__(\n            self: FileInput[str],\n            files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n            inplace: bool = False,\n            backup: str = \"\",\n            *,\n            mode: _TextMode = \"r\",\n            openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None,\n            encoding: str | None = None,\n            errors: str | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: FileInput[bytes],\n            files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n            inplace: bool = False,\n            backup: str = \"\",\n            *,\n            mode: Literal[\"rb\"],\n            openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None,\n            encoding: None = None,\n            errors: None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: FileInput[Any],\n            files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n            inplace: bool = False,\n            backup: str = \"\",\n            *,\n            mode: str,\n            openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None,\n            encoding: str | None = None,\n            errors: str | None = None,\n        ) -> None: ...\n\n    else:\n        # bufsize is dropped and mode and openhook become keyword-only\n        @overload\n        def __init__(\n            self: FileInput[str],\n            files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n            inplace: bool = False,\n            backup: str = \"\",\n            *,\n            mode: _TextMode = \"r\",\n            openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[str]] | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: FileInput[bytes],\n            files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n            inplace: bool = False,\n            backup: str = \"\",\n            *,\n            mode: Literal[\"rb\"],\n            openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[bytes]] | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: FileInput[Any],\n            files: StrOrBytesPath | Iterable[StrOrBytesPath] | None = None,\n            inplace: bool = False,\n            backup: str = \"\",\n            *,\n            mode: str,\n            openhook: Callable[[StrOrBytesPath, str], _HasReadlineAndFileno[Any]] | None = None,\n        ) -> None: ...\n\n    def __del__(self) -> None: ...\n    def close(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n    ) -> None: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> AnyStr: ...\n    if sys.version_info < (3, 11):\n        def __getitem__(self, i: int) -> AnyStr: ...\n\n    def nextfile(self) -> None: ...\n    def readline(self) -> AnyStr: ...\n    def filename(self) -> str: ...\n    def lineno(self) -> int: ...\n    def filelineno(self) -> int: ...\n    def fileno(self) -> int: ...\n    def isfirstline(self) -> bool: ...\n    def isstdin(self) -> bool: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nif sys.version_info >= (3, 10):\n    def hook_compressed(\n        filename: StrOrBytesPath, mode: str, *, encoding: str | None = None, errors: str | None = None\n    ) -> IO[Any]: ...\n\nelse:\n    def hook_compressed(filename: StrOrBytesPath, mode: str) -> IO[Any]: ...\n\nif sys.version_info >= (3, 10):\n    @deprecated(\"Deprecated since Python 3.10. Use `fileinput.input` or `fileinput.FileInput` instead.\")\n    def hook_encoded(encoding: str, errors: str | None = None) -> Callable[[StrOrBytesPath, str], IO[Any]]: ...\n\nelse:\n    def hook_encoded(encoding: str, errors: str | None = None) -> Callable[[StrOrBytesPath, str], IO[Any]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/fnmatch.pyi",
    "content": "import sys\nfrom collections.abc import Iterable\nfrom typing import AnyStr\n\n__all__ = [\"filter\", \"fnmatch\", \"fnmatchcase\", \"translate\"]\nif sys.version_info >= (3, 14):\n    __all__ += [\"filterfalse\"]\n\ndef fnmatch(name: AnyStr, pat: AnyStr) -> bool: ...\ndef fnmatchcase(name: AnyStr, pat: AnyStr) -> bool: ...\ndef filter(names: Iterable[AnyStr], pat: AnyStr) -> list[AnyStr]: ...\ndef translate(pat: str) -> str: ...\n\nif sys.version_info >= (3, 14):\n    def filterfalse(names: Iterable[AnyStr], pat: AnyStr) -> list[AnyStr]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/formatter.pyi",
    "content": "from collections.abc import Iterable\nfrom typing import IO, Any\nfrom typing_extensions import TypeAlias\n\nAS_IS: None\n_FontType: TypeAlias = tuple[str, bool, bool, bool]\n_StylesType: TypeAlias = tuple[Any, ...]\n\nclass NullFormatter:\n    writer: NullWriter | None\n    def __init__(self, writer: NullWriter | None = None) -> None: ...\n    def end_paragraph(self, blankline: int) -> None: ...\n    def add_line_break(self) -> None: ...\n    def add_hor_rule(self, *args: Any, **kw: Any) -> None: ...\n    def add_label_data(self, format: str, counter: int, blankline: int | None = None) -> None: ...\n    def add_flowing_data(self, data: str) -> None: ...\n    def add_literal_data(self, data: str) -> None: ...\n    def flush_softspace(self) -> None: ...\n    def push_alignment(self, align: str | None) -> None: ...\n    def pop_alignment(self) -> None: ...\n    def push_font(self, x: _FontType) -> None: ...\n    def pop_font(self) -> None: ...\n    def push_margin(self, margin: int) -> None: ...\n    def pop_margin(self) -> None: ...\n    def set_spacing(self, spacing: str | None) -> None: ...\n    def push_style(self, *styles: _StylesType) -> None: ...\n    def pop_style(self, n: int = 1) -> None: ...\n    def assert_line_data(self, flag: int = 1) -> None: ...\n\nclass AbstractFormatter:\n    writer: NullWriter\n    align: str | None\n    align_stack: list[str | None]\n    font_stack: list[_FontType]\n    margin_stack: list[int]\n    spacing: str | None\n    style_stack: Any\n    nospace: int\n    softspace: int\n    para_end: int\n    parskip: int\n    hard_break: int\n    have_label: int\n    def __init__(self, writer: NullWriter) -> None: ...\n    def end_paragraph(self, blankline: int) -> None: ...\n    def add_line_break(self) -> None: ...\n    def add_hor_rule(self, *args: Any, **kw: Any) -> None: ...\n    def add_label_data(self, format: str, counter: int, blankline: int | None = None) -> None: ...\n    def format_counter(self, format: Iterable[str], counter: int) -> str: ...\n    def format_letter(self, case: str, counter: int) -> str: ...\n    def format_roman(self, case: str, counter: int) -> str: ...\n    def add_flowing_data(self, data: str) -> None: ...\n    def add_literal_data(self, data: str) -> None: ...\n    def flush_softspace(self) -> None: ...\n    def push_alignment(self, align: str | None) -> None: ...\n    def pop_alignment(self) -> None: ...\n    def push_font(self, font: _FontType) -> None: ...\n    def pop_font(self) -> None: ...\n    def push_margin(self, margin: int) -> None: ...\n    def pop_margin(self) -> None: ...\n    def set_spacing(self, spacing: str | None) -> None: ...\n    def push_style(self, *styles: _StylesType) -> None: ...\n    def pop_style(self, n: int = 1) -> None: ...\n    def assert_line_data(self, flag: int = 1) -> None: ...\n\nclass NullWriter:\n    def flush(self) -> None: ...\n    def new_alignment(self, align: str | None) -> None: ...\n    def new_font(self, font: _FontType) -> None: ...\n    def new_margin(self, margin: int, level: int) -> None: ...\n    def new_spacing(self, spacing: str | None) -> None: ...\n    def new_styles(self, styles: tuple[Any, ...]) -> None: ...\n    def send_paragraph(self, blankline: int) -> None: ...\n    def send_line_break(self) -> None: ...\n    def send_hor_rule(self, *args: Any, **kw: Any) -> None: ...\n    def send_label_data(self, data: str) -> None: ...\n    def send_flowing_data(self, data: str) -> None: ...\n    def send_literal_data(self, data: str) -> None: ...\n\nclass AbstractWriter(NullWriter): ...\n\nclass DumbWriter(NullWriter):\n    file: IO[str]\n    maxcol: int\n    def __init__(self, file: IO[str] | None = None, maxcol: int = 72) -> None: ...\n    def reset(self) -> None: ...\n\ndef test(file: str | None = None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/fractions.pyi",
    "content": "import sys\nfrom collections.abc import Callable\nfrom decimal import Decimal\nfrom numbers import Rational, Real\nfrom typing import Any, Literal, Protocol, SupportsIndex, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\n_ComparableNum: TypeAlias = int | float | Decimal | Real\n\n__all__ = [\"Fraction\"]\n\n@type_check_only\nclass _ConvertibleToIntegerRatio(Protocol):\n    def as_integer_ratio(self) -> tuple[int | Rational, int | Rational]: ...\n\nclass Fraction(Rational):\n    __slots__ = (\"_numerator\", \"_denominator\")\n    @overload\n    def __new__(cls, numerator: int | Rational = 0, denominator: int | Rational | None = None) -> Self: ...\n    @overload\n    def __new__(cls, numerator: float | Decimal | str) -> Self: ...\n\n    if sys.version_info >= (3, 14):\n        @overload\n        def __new__(cls, numerator: _ConvertibleToIntegerRatio) -> Self: ...\n\n    @classmethod\n    def from_float(cls, f: float) -> Self: ...\n    @classmethod\n    def from_decimal(cls, dec: Decimal) -> Self: ...\n    def limit_denominator(self, max_denominator: int = 1000000) -> Fraction: ...\n    def as_integer_ratio(self) -> tuple[int, int]: ...\n    if sys.version_info >= (3, 12):\n        def is_integer(self) -> bool: ...\n\n    @property\n    def numerator(a) -> int: ...\n    @property\n    def denominator(a) -> int: ...\n    @overload\n    def __add__(a, b: int | Fraction) -> Fraction: ...\n    @overload\n    def __add__(a, b: float) -> float: ...\n    @overload\n    def __add__(a, b: complex) -> complex: ...\n    @overload\n    def __radd__(b, a: int | Fraction) -> Fraction: ...\n    @overload\n    def __radd__(b, a: float) -> float: ...\n    @overload\n    def __radd__(b, a: complex) -> complex: ...\n    @overload\n    def __sub__(a, b: int | Fraction) -> Fraction: ...\n    @overload\n    def __sub__(a, b: float) -> float: ...\n    @overload\n    def __sub__(a, b: complex) -> complex: ...\n    @overload\n    def __rsub__(b, a: int | Fraction) -> Fraction: ...\n    @overload\n    def __rsub__(b, a: float) -> float: ...\n    @overload\n    def __rsub__(b, a: complex) -> complex: ...\n    @overload\n    def __mul__(a, b: int | Fraction) -> Fraction: ...\n    @overload\n    def __mul__(a, b: float) -> float: ...\n    @overload\n    def __mul__(a, b: complex) -> complex: ...\n    @overload\n    def __rmul__(b, a: int | Fraction) -> Fraction: ...\n    @overload\n    def __rmul__(b, a: float) -> float: ...\n    @overload\n    def __rmul__(b, a: complex) -> complex: ...\n    @overload\n    def __truediv__(a, b: int | Fraction) -> Fraction: ...\n    @overload\n    def __truediv__(a, b: float) -> float: ...\n    @overload\n    def __truediv__(a, b: complex) -> complex: ...\n    @overload\n    def __rtruediv__(b, a: int | Fraction) -> Fraction: ...\n    @overload\n    def __rtruediv__(b, a: float) -> float: ...\n    @overload\n    def __rtruediv__(b, a: complex) -> complex: ...\n    @overload\n    def __floordiv__(a, b: int | Fraction) -> int: ...\n    @overload\n    def __floordiv__(a, b: float) -> float: ...\n    @overload\n    def __rfloordiv__(b, a: int | Fraction) -> int: ...\n    @overload\n    def __rfloordiv__(b, a: float) -> float: ...\n    @overload\n    def __mod__(a, b: int | Fraction) -> Fraction: ...\n    @overload\n    def __mod__(a, b: float) -> float: ...\n    @overload\n    def __rmod__(b, a: int | Fraction) -> Fraction: ...\n    @overload\n    def __rmod__(b, a: float) -> float: ...\n    @overload\n    def __divmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ...\n    @overload\n    def __divmod__(a, b: float) -> tuple[float, Fraction]: ...\n    @overload\n    def __rdivmod__(a, b: int | Fraction) -> tuple[int, Fraction]: ...\n    @overload\n    def __rdivmod__(a, b: float) -> tuple[float, Fraction]: ...\n    if sys.version_info >= (3, 14):\n        @overload\n        def __pow__(a, b: int, modulo: None = None) -> Fraction: ...\n        @overload\n        def __pow__(a, b: float | Fraction, modulo: None = None) -> float: ...\n        @overload\n        def __pow__(a, b: complex, modulo: None = None) -> complex: ...\n    else:\n        @overload\n        def __pow__(a, b: int) -> Fraction: ...\n        @overload\n        def __pow__(a, b: float | Fraction) -> float: ...\n        @overload\n        def __pow__(a, b: complex) -> complex: ...\n    if sys.version_info >= (3, 14):\n        @overload\n        def __rpow__(b, a: float | Fraction, modulo: None = None) -> float: ...\n        @overload\n        def __rpow__(b, a: complex, modulo: None = None) -> complex: ...\n    else:\n        @overload\n        def __rpow__(b, a: float | Fraction) -> float: ...\n        @overload\n        def __rpow__(b, a: complex) -> complex: ...\n\n    def __pos__(a) -> Fraction: ...\n    def __neg__(a) -> Fraction: ...\n    def __abs__(a) -> Fraction: ...\n    def __trunc__(a) -> int: ...\n    def __floor__(a) -> int: ...\n    def __ceil__(a) -> int: ...\n    @overload\n    def __round__(self, ndigits: None = None) -> int: ...\n    @overload\n    def __round__(self, ndigits: int) -> Fraction: ...\n    def __hash__(self) -> int: ...  # type: ignore[override]\n    def __eq__(a, b: object) -> bool: ...\n    def __lt__(a, b: _ComparableNum) -> bool: ...\n    def __gt__(a, b: _ComparableNum) -> bool: ...\n    def __le__(a, b: _ComparableNum) -> bool: ...\n    def __ge__(a, b: _ComparableNum) -> bool: ...\n    def __bool__(a) -> bool: ...\n    def __copy__(self) -> Self: ...\n    def __deepcopy__(self, memo: Any) -> Self: ...\n    if sys.version_info >= (3, 11):\n        def __int__(a, _index: Callable[[SupportsIndex], int] = ...) -> int: ...\n    # Not actually defined within fractions.py, but provides more useful\n    # overrides\n    @property\n    def real(self) -> Fraction: ...\n    @property\n    def imag(self) -> Literal[0]: ...\n    def conjugate(self) -> Fraction: ...\n    if sys.version_info >= (3, 14):\n        @classmethod\n        def from_number(cls, number: float | Rational | _ConvertibleToIntegerRatio) -> Self: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ftplib.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath, SupportsRead, SupportsReadline\nfrom collections.abc import Callable, Iterable, Iterator\nfrom socket import socket\nfrom ssl import SSLContext\nfrom types import TracebackType\nfrom typing import Any, Final, Literal, TextIO, overload\nfrom typing_extensions import Self, deprecated\n\n__all__ = [\"FTP\", \"error_reply\", \"error_temp\", \"error_perm\", \"error_proto\", \"all_errors\", \"FTP_TLS\"]\n\nMSG_OOB: Final = 1\nFTP_PORT: Final = 21\nMAXLINE: Final = 8192\nCRLF: Final = \"\\r\\n\"\nB_CRLF: Final = b\"\\r\\n\"\n\nclass Error(Exception): ...\nclass error_reply(Error): ...\nclass error_temp(Error): ...\nclass error_perm(Error): ...\nclass error_proto(Error): ...\n\nall_errors: tuple[type[Exception], ...]\n\nclass FTP:\n    debugging: int\n    host: str\n    port: int\n    maxline: int\n    sock: socket | None\n    welcome: str | None\n    passiveserver: int\n    timeout: float | None\n    af: int\n    lastresp: str\n    file: TextIO | None\n    encoding: str\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n    source_address: tuple[str, int] | None\n    def __init__(\n        self,\n        host: str = \"\",\n        user: str = \"\",\n        passwd: str = \"\",\n        acct: str = \"\",\n        timeout: float | None = ...,\n        source_address: tuple[str, int] | None = None,\n        *,\n        encoding: str = \"utf-8\",\n    ) -> None: ...\n    def connect(\n        self, host: str = \"\", port: int = 0, timeout: float = -999, source_address: tuple[str, int] | None = None\n    ) -> str: ...\n    def getwelcome(self) -> str: ...\n    def set_debuglevel(self, level: int) -> None: ...\n    def debug(self, level: int) -> None: ...\n    def set_pasv(self, val: bool | Literal[0, 1]) -> None: ...\n    def sanitize(self, s: str) -> str: ...\n    def putline(self, line: str) -> None: ...\n    def putcmd(self, line: str) -> None: ...\n    def getline(self) -> str: ...\n    def getmultiline(self) -> str: ...\n    def getresp(self) -> str: ...\n    def voidresp(self) -> str: ...\n    def abort(self) -> str: ...\n    def sendcmd(self, cmd: str) -> str: ...\n    def voidcmd(self, cmd: str) -> str: ...\n    def sendport(self, host: str, port: int) -> str: ...\n    def sendeprt(self, host: str, port: int) -> str: ...\n    def makeport(self) -> socket: ...\n    def makepasv(self) -> tuple[str, int]: ...\n    def login(self, user: str = \"\", passwd: str = \"\", acct: str = \"\") -> str: ...\n    # In practice, `rest` can actually be anything whose str() is an integer sequence, so to make it simple we allow integers\n    def ntransfercmd(self, cmd: str, rest: int | str | None = None) -> tuple[socket, int | None]: ...\n    def transfercmd(self, cmd: str, rest: int | str | None = None) -> socket: ...\n    def retrbinary(\n        self, cmd: str, callback: Callable[[bytes], object], blocksize: int = 8192, rest: int | str | None = None\n    ) -> str: ...\n    def storbinary(\n        self,\n        cmd: str,\n        fp: SupportsRead[bytes],\n        blocksize: int = 8192,\n        callback: Callable[[bytes], object] | None = None,\n        rest: int | str | None = None,\n    ) -> str: ...\n    def retrlines(self, cmd: str, callback: Callable[[str], object] | None = None) -> str: ...\n    def storlines(self, cmd: str, fp: SupportsReadline[bytes], callback: Callable[[bytes], object] | None = None) -> str: ...\n    def acct(self, password: str) -> str: ...\n    def nlst(self, *args: str) -> list[str]: ...\n    # Technically only the last arg can be a Callable but ...\n    def dir(self, *args: str | Callable[[str], object]) -> None: ...\n    def mlsd(self, path: str = \"\", facts: Iterable[str] = []) -> Iterator[tuple[str, dict[str, str]]]: ...\n    def rename(self, fromname: str, toname: str) -> str: ...\n    def delete(self, filename: str) -> str: ...\n    def cwd(self, dirname: str) -> str: ...\n    def size(self, filename: str) -> int | None: ...\n    def mkd(self, dirname: str) -> str: ...\n    def rmd(self, dirname: str) -> str: ...\n    def pwd(self) -> str: ...\n    def quit(self) -> str: ...\n    def close(self) -> None: ...\n\nclass FTP_TLS(FTP):\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self,\n            host: str = \"\",\n            user: str = \"\",\n            passwd: str = \"\",\n            acct: str = \"\",\n            *,\n            context: SSLContext | None = None,\n            timeout: float | None = ...,\n            source_address: tuple[str, int] | None = None,\n            encoding: str = \"utf-8\",\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self,\n            host: str = \"\",\n            user: str = \"\",\n            passwd: str = \"\",\n            acct: str = \"\",\n            keyfile: None = None,\n            certfile: None = None,\n            context: SSLContext | None = None,\n            timeout: float | None = ...,\n            source_address: tuple[str, int] | None = None,\n            *,\n            encoding: str = \"utf-8\",\n        ) -> None: ...\n        @overload\n        @deprecated(\n            \"The `keyfile`, `certfile` parameters are deprecated since Python 3.6; \"\n            \"removed in Python 3.12. Use `context` parameter instead.\"\n        )\n        def __init__(\n            self,\n            host: str = \"\",\n            user: str = \"\",\n            passwd: str = \"\",\n            acct: str = \"\",\n            keyfile: StrOrBytesPath | None = None,\n            certfile: StrOrBytesPath | None = None,\n            context: None = None,\n            timeout: float | None = ...,\n            source_address: tuple[str, int] | None = None,\n            *,\n            encoding: str = \"utf-8\",\n        ) -> None: ...\n        ssl_version: int\n        keyfile: StrOrBytesPath | None\n        certfile: StrOrBytesPath | None\n    context: SSLContext\n    def login(self, user: str = \"\", passwd: str = \"\", acct: str = \"\", secure: bool = True) -> str: ...\n    def auth(self) -> str: ...\n    def prot_p(self) -> str: ...\n    def prot_c(self) -> str: ...\n    def ccc(self) -> str: ...\n\ndef parse150(resp: str) -> int | None: ...  # undocumented\ndef parse227(resp: str) -> tuple[str, int]: ...  # undocumented\ndef parse229(resp: str, peer: Any) -> tuple[str, int]: ...  # undocumented\ndef parse257(resp: str) -> str: ...  # undocumented\ndef ftpcp(\n    source: FTP, sourcename: str, target: FTP, targetname: str = \"\", type: Literal[\"A\", \"I\"] = \"I\"\n) -> None: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/functools.pyi",
    "content": "import sys\nimport types\nfrom _typeshed import SupportsAllComparisons, SupportsItems\nfrom collections.abc import Callable, Hashable, Iterable, Sized\nfrom types import GenericAlias\nfrom typing import Any, Final, Generic, Literal, NamedTuple, TypedDict, TypeVar, final, overload, type_check_only\nfrom typing_extensions import ParamSpec, Self, TypeAlias, disjoint_base\n\n__all__ = [\n    \"update_wrapper\",\n    \"wraps\",\n    \"WRAPPER_ASSIGNMENTS\",\n    \"WRAPPER_UPDATES\",\n    \"total_ordering\",\n    \"cmp_to_key\",\n    \"lru_cache\",\n    \"reduce\",\n    \"partial\",\n    \"partialmethod\",\n    \"singledispatch\",\n    \"cached_property\",\n    \"singledispatchmethod\",\n    \"cache\",\n]\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_S = TypeVar(\"_S\")\n_PWrapped = ParamSpec(\"_PWrapped\")\n_RWrapped = TypeVar(\"_RWrapped\")\n_PWrapper = ParamSpec(\"_PWrapper\")\n_RWrapper = TypeVar(\"_RWrapper\")\n\nif sys.version_info >= (3, 14):\n    @overload\n    def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], /, initial: _T) -> _T: ...\n\nelse:\n    @overload\n    def reduce(function: Callable[[_T, _S], _T], iterable: Iterable[_S], initial: _T, /) -> _T: ...\n\n@overload\ndef reduce(function: Callable[[_T, _T], _T], iterable: Iterable[_T], /) -> _T: ...\n\nclass _CacheInfo(NamedTuple):\n    hits: int\n    misses: int\n    maxsize: int | None\n    currsize: int\n\n@type_check_only\nclass _CacheParameters(TypedDict):\n    maxsize: int\n    typed: bool\n\n@final\nclass _lru_cache_wrapper(Generic[_T_co]):\n    __wrapped__: Callable[..., _T_co]\n    def __call__(self, *args: Hashable, **kwargs: Hashable) -> _T_co: ...\n    def cache_info(self) -> _CacheInfo: ...\n    def cache_clear(self) -> None: ...\n    def cache_parameters(self) -> _CacheParameters: ...\n    def __copy__(self) -> _lru_cache_wrapper[_T_co]: ...\n    def __deepcopy__(self, memo: Any, /) -> _lru_cache_wrapper[_T_co]: ...\n\n    # as with ``Callable``, we'll assume that these attributes exist\n    __name__: str\n    __qualname__: str\n\n@overload\ndef lru_cache(maxsize: int | None = 128, typed: bool = False) -> Callable[[Callable[..., _T]], _lru_cache_wrapper[_T]]: ...\n@overload\ndef lru_cache(maxsize: Callable[..., _T], typed: bool = False) -> _lru_cache_wrapper[_T]: ...\n\nif sys.version_info >= (3, 14):\n    WRAPPER_ASSIGNMENTS: Final[\n        tuple[\n            Literal[\"__module__\"],\n            Literal[\"__name__\"],\n            Literal[\"__qualname__\"],\n            Literal[\"__doc__\"],\n            Literal[\"__annotate__\"],\n            Literal[\"__type_params__\"],\n        ]\n    ]\nelif sys.version_info >= (3, 12):\n    WRAPPER_ASSIGNMENTS: Final[\n        tuple[\n            Literal[\"__module__\"],\n            Literal[\"__name__\"],\n            Literal[\"__qualname__\"],\n            Literal[\"__doc__\"],\n            Literal[\"__annotations__\"],\n            Literal[\"__type_params__\"],\n        ]\n    ]\nelse:\n    WRAPPER_ASSIGNMENTS: Final[\n        tuple[Literal[\"__module__\"], Literal[\"__name__\"], Literal[\"__qualname__\"], Literal[\"__doc__\"], Literal[\"__annotations__\"]]\n    ]\n\nWRAPPER_UPDATES: Final[tuple[Literal[\"__dict__\"]]]\n\n@type_check_only\nclass _Wrapped(Generic[_PWrapped, _RWrapped, _PWrapper, _RWrapper]):\n    __wrapped__: Callable[_PWrapped, _RWrapped]\n    def __call__(self, *args: _PWrapper.args, **kwargs: _PWrapper.kwargs) -> _RWrapper: ...\n    # as with ``Callable``, we'll assume that these attributes exist\n    __name__: str\n    __qualname__: str\n\n@type_check_only\nclass _Wrapper(Generic[_PWrapped, _RWrapped]):\n    def __call__(self, f: Callable[_PWrapper, _RWrapper]) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ...\n\nif sys.version_info >= (3, 14):\n    def update_wrapper(\n        wrapper: Callable[_PWrapper, _RWrapper],\n        wrapped: Callable[_PWrapped, _RWrapped],\n        assigned: Iterable[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotate__\", \"__type_params__\"),\n        updated: Iterable[str] = (\"__dict__\",),\n    ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ...\n    def wraps(\n        wrapped: Callable[_PWrapped, _RWrapped],\n        assigned: Iterable[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotate__\", \"__type_params__\"),\n        updated: Iterable[str] = (\"__dict__\",),\n    ) -> _Wrapper[_PWrapped, _RWrapped]: ...\n\nelif sys.version_info >= (3, 12):\n    def update_wrapper(\n        wrapper: Callable[_PWrapper, _RWrapper],\n        wrapped: Callable[_PWrapped, _RWrapped],\n        assigned: Iterable[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\", \"__type_params__\"),\n        updated: Iterable[str] = (\"__dict__\",),\n    ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ...\n    def wraps(\n        wrapped: Callable[_PWrapped, _RWrapped],\n        assigned: Iterable[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\", \"__type_params__\"),\n        updated: Iterable[str] = (\"__dict__\",),\n    ) -> _Wrapper[_PWrapped, _RWrapped]: ...\n\nelse:\n    def update_wrapper(\n        wrapper: Callable[_PWrapper, _RWrapper],\n        wrapped: Callable[_PWrapped, _RWrapped],\n        assigned: Iterable[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\"),\n        updated: Iterable[str] = (\"__dict__\",),\n    ) -> _Wrapped[_PWrapped, _RWrapped, _PWrapper, _RWrapper]: ...\n    def wraps(\n        wrapped: Callable[_PWrapped, _RWrapped],\n        assigned: Iterable[str] = (\"__module__\", \"__name__\", \"__qualname__\", \"__doc__\", \"__annotations__\"),\n        updated: Iterable[str] = (\"__dict__\",),\n    ) -> _Wrapper[_PWrapped, _RWrapped]: ...\n\ndef total_ordering(cls: type[_T]) -> type[_T]: ...\ndef cmp_to_key(mycmp: Callable[[_T, _T], int]) -> Callable[[_T], SupportsAllComparisons]: ...\n@disjoint_base\nclass partial(Generic[_T]):\n    @property\n    def func(self) -> Callable[..., _T]: ...\n    @property\n    def args(self) -> tuple[Any, ...]: ...\n    @property\n    def keywords(self) -> dict[str, Any]: ...\n    def __new__(cls, func: Callable[..., _T], /, *args: Any, **kwargs: Any) -> Self: ...\n    def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n# With protocols, this could change into a generic protocol that defines __get__ and returns _T\n_Descriptor: TypeAlias = Any\n\nclass partialmethod(Generic[_T]):\n    func: Callable[..., _T] | _Descriptor\n    args: tuple[Any, ...]\n    keywords: dict[str, Any]\n    if sys.version_info >= (3, 14):\n        @overload\n        def __new__(self, func: Callable[..., _T], /, *args: Any, **keywords: Any) -> Self: ...\n        @overload\n        def __new__(self, func: _Descriptor, /, *args: Any, **keywords: Any) -> Self: ...\n    else:\n        @overload\n        def __init__(self, func: Callable[..., _T], /, *args: Any, **keywords: Any) -> None: ...\n        @overload\n        def __init__(self, func: _Descriptor, /, *args: Any, **keywords: Any) -> None: ...\n\n    def __get__(self, obj: Any, cls: type[Any] | None = None) -> Callable[..., _T]: ...\n    @property\n    def __isabstractmethod__(self) -> bool: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nif sys.version_info >= (3, 11):\n    _RegType: TypeAlias = type[Any] | types.UnionType\nelse:\n    _RegType: TypeAlias = type[Any]\n\n@type_check_only\nclass _SingleDispatchCallable(Generic[_T]):\n    registry: types.MappingProxyType[Any, Callable[..., _T]]\n    def dispatch(self, cls: Any) -> Callable[..., _T]: ...\n    # @fun.register(complex)\n    # def _(arg, verbose=False): ...\n    @overload\n    def register(self, cls: _RegType, func: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ...\n    # @fun.register\n    # def _(arg: int, verbose=False):\n    @overload\n    def register(self, cls: Callable[..., _T], func: None = None) -> Callable[..., _T]: ...\n    # fun.register(int, lambda x: x)\n    @overload\n    def register(self, cls: _RegType, func: Callable[..., _T]) -> Callable[..., _T]: ...\n    def _clear_cache(self) -> None: ...\n    def __call__(self, /, *args: Any, **kwargs: Any) -> _T: ...\n\ndef singledispatch(func: Callable[..., _T]) -> _SingleDispatchCallable[_T]: ...\n\nclass singledispatchmethod(Generic[_T]):\n    dispatcher: _SingleDispatchCallable[_T]\n    func: Callable[..., _T]\n    def __init__(self, func: Callable[..., _T]) -> None: ...\n    @property\n    def __isabstractmethod__(self) -> bool: ...\n    @overload\n    def register(self, cls: _RegType, method: None = None) -> Callable[[Callable[..., _T]], Callable[..., _T]]: ...\n    @overload\n    def register(self, cls: Callable[..., _T], method: None = None) -> Callable[..., _T]: ...\n    @overload\n    def register(self, cls: _RegType, method: Callable[..., _T]) -> Callable[..., _T]: ...\n    def __get__(self, obj: _S, cls: type[_S] | None = None) -> Callable[..., _T]: ...\n\nclass cached_property(Generic[_T_co]):\n    func: Callable[[Any], _T_co]\n    attrname: str | None\n    def __init__(self, func: Callable[[Any], _T_co]) -> None: ...\n    @overload\n    def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ...\n    @overload\n    def __get__(self, instance: object, owner: type[Any] | None = None) -> _T_co: ...\n    def __set_name__(self, owner: type[Any], name: str) -> None: ...\n    # __set__ is not defined at runtime, but @cached_property is designed to be settable\n    def __set__(self, instance: object, value: _T_co) -> None: ...  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\ndef cache(user_function: Callable[..., _T], /) -> _lru_cache_wrapper[_T]: ...\ndef _make_key(\n    args: tuple[Hashable, ...],\n    kwds: SupportsItems[Any, Any],\n    typed: bool,\n    kwd_mark: tuple[object, ...] = ...,\n    fasttypes: set[type] = ...,\n    tuple: type = ...,\n    type: Any = ...,\n    len: Callable[[Sized], int] = ...,\n) -> Hashable: ...\n\nif sys.version_info >= (3, 14):\n    @final\n    class _PlaceholderType: ...\n\n    Placeholder: Final[_PlaceholderType]\n\n    __all__ += [\"Placeholder\"]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/gc.pyi",
    "content": "from collections.abc import Callable\nfrom typing import Any, Final, Literal\nfrom typing_extensions import TypeAlias\n\nDEBUG_COLLECTABLE: Final = 2\nDEBUG_LEAK: Final = 38\nDEBUG_SAVEALL: Final = 32\nDEBUG_STATS: Final = 1\nDEBUG_UNCOLLECTABLE: Final = 4\n\n_CallbackType: TypeAlias = Callable[[Literal[\"start\", \"stop\"], dict[str, int]], object]\n\ncallbacks: list[_CallbackType]\ngarbage: list[Any]\n\ndef collect(generation: int = 2) -> int: ...\ndef disable() -> None: ...\ndef enable() -> None: ...\ndef get_count() -> tuple[int, int, int]: ...\ndef get_debug() -> int: ...\ndef get_objects(generation: int | None = None) -> list[Any]: ...\ndef freeze() -> None: ...\ndef unfreeze() -> None: ...\ndef get_freeze_count() -> int: ...\ndef get_referents(*objs: Any) -> list[Any]: ...\ndef get_referrers(*objs: Any) -> list[Any]: ...\ndef get_stats() -> list[dict[str, Any]]: ...\ndef get_threshold() -> tuple[int, int, int]: ...\ndef is_tracked(obj: Any, /) -> bool: ...\ndef is_finalized(obj: Any, /) -> bool: ...\ndef isenabled() -> bool: ...\ndef set_debug(flags: int, /) -> None: ...\ndef set_threshold(threshold0: int, threshold1: int = 0, threshold2: int = 0, /) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/genericpath.pyi",
    "content": "import os\nimport sys\nfrom _typeshed import BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath, SupportsRichComparisonT\nfrom collections.abc import Sequence\nfrom typing import Literal, NewType, overload\nfrom typing_extensions import LiteralString\n\n__all__ = [\n    \"commonprefix\",\n    \"exists\",\n    \"getatime\",\n    \"getctime\",\n    \"getmtime\",\n    \"getsize\",\n    \"isdir\",\n    \"isfile\",\n    \"samefile\",\n    \"sameopenfile\",\n    \"samestat\",\n    \"ALLOW_MISSING\",\n]\nif sys.version_info >= (3, 12):\n    __all__ += [\"islink\"]\nif sys.version_info >= (3, 13):\n    __all__ += [\"isjunction\", \"isdevdrive\", \"lexists\"]\n\n# All overloads can return empty string. Ideally, Literal[\"\"] would be a valid\n# Iterable[T], so that list[T] | Literal[\"\"] could be used as a return\n# type. But because this only works when T is str, we need Sequence[T] instead.\n@overload\ndef commonprefix(m: Sequence[LiteralString]) -> LiteralString: ...\n@overload\ndef commonprefix(m: Sequence[StrPath]) -> str: ...\n@overload\ndef commonprefix(m: Sequence[BytesPath]) -> bytes | Literal[\"\"]: ...\n@overload\ndef commonprefix(m: Sequence[list[SupportsRichComparisonT]]) -> Sequence[SupportsRichComparisonT]: ...\n@overload\ndef commonprefix(m: Sequence[tuple[SupportsRichComparisonT, ...]]) -> Sequence[SupportsRichComparisonT]: ...\ndef exists(path: FileDescriptorOrPath) -> bool: ...\ndef getsize(filename: FileDescriptorOrPath) -> int: ...\ndef isfile(path: FileDescriptorOrPath) -> bool: ...\ndef isdir(s: FileDescriptorOrPath) -> bool: ...\n\nif sys.version_info >= (3, 12):\n    def islink(path: StrOrBytesPath) -> bool: ...\n\n# These return float if os.stat_float_times() == True,\n# but int is a subclass of float.\ndef getatime(filename: FileDescriptorOrPath) -> float: ...\ndef getmtime(filename: FileDescriptorOrPath) -> float: ...\ndef getctime(filename: FileDescriptorOrPath) -> float: ...\ndef samefile(f1: FileDescriptorOrPath, f2: FileDescriptorOrPath) -> bool: ...\ndef sameopenfile(fp1: int, fp2: int) -> bool: ...\ndef samestat(s1: os.stat_result, s2: os.stat_result) -> bool: ...\n\nif sys.version_info >= (3, 13):\n    def isjunction(path: StrOrBytesPath) -> bool: ...\n    def isdevdrive(path: StrOrBytesPath) -> bool: ...\n    def lexists(path: StrOrBytesPath) -> bool: ...\n\n# Added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.4\n_AllowMissingType = NewType(\"_AllowMissingType\", object)\nALLOW_MISSING: _AllowMissingType\n"
  },
  {
    "path": "mypy/typeshed/stdlib/getopt.pyi",
    "content": "from collections.abc import Iterable, Sequence\nfrom typing import Protocol, TypeVar, overload, type_check_only\n\n_StrSequenceT_co = TypeVar(\"_StrSequenceT_co\", covariant=True, bound=Sequence[str])\n\n@type_check_only\nclass _SliceableT(Protocol[_StrSequenceT_co]):\n    @overload\n    def __getitem__(self, key: int, /) -> str: ...\n    @overload\n    def __getitem__(self, key: slice, /) -> _StrSequenceT_co: ...\n\n__all__ = [\"GetoptError\", \"error\", \"getopt\", \"gnu_getopt\"]\n\ndef getopt(\n    args: _SliceableT[_StrSequenceT_co], shortopts: str, longopts: Iterable[str] | str = []\n) -> tuple[list[tuple[str, str]], _StrSequenceT_co]: ...\ndef gnu_getopt(\n    args: Sequence[str], shortopts: str, longopts: Iterable[str] | str = []\n) -> tuple[list[tuple[str, str]], list[str]]: ...\n\nclass GetoptError(Exception):\n    msg: str\n    opt: str\n    def __init__(self, msg: str, opt: str = \"\") -> None: ...\n\nerror = GetoptError\n"
  },
  {
    "path": "mypy/typeshed/stdlib/getpass.pyi",
    "content": "import sys\nfrom typing import TextIO\n\n__all__ = [\"getpass\", \"getuser\", \"GetPassWarning\"]\n\nif sys.version_info >= (3, 14):\n    def getpass(prompt: str = \"Password: \", stream: TextIO | None = None, *, echo_char: str | None = None) -> str: ...\n\nelse:\n    def getpass(prompt: str = \"Password: \", stream: TextIO | None = None) -> str: ...\n\ndef getuser() -> str: ...\n\nclass GetPassWarning(UserWarning): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/gettext.pyi",
    "content": "import io\nimport sys\nfrom _typeshed import StrPath\nfrom collections.abc import Callable, Container, Iterable, Sequence\nfrom typing import Any, Final, Literal, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import deprecated\n\n__all__ = [\n    \"NullTranslations\",\n    \"GNUTranslations\",\n    \"Catalog\",\n    \"find\",\n    \"translation\",\n    \"install\",\n    \"textdomain\",\n    \"bindtextdomain\",\n    \"dgettext\",\n    \"dngettext\",\n    \"gettext\",\n    \"ngettext\",\n    \"dnpgettext\",\n    \"dpgettext\",\n    \"npgettext\",\n    \"pgettext\",\n]\n\nif sys.version_info < (3, 11):\n    __all__ += [\"bind_textdomain_codeset\", \"ldgettext\", \"ldngettext\", \"lgettext\", \"lngettext\"]\n\n@type_check_only\nclass _TranslationsReader(Protocol):\n    def read(self) -> bytes: ...\n    # optional:\n    # name: str\n\nclass NullTranslations:\n    def __init__(self, fp: _TranslationsReader | None = None) -> None: ...\n    def _parse(self, fp: _TranslationsReader) -> None: ...\n    def add_fallback(self, fallback: NullTranslations) -> None: ...\n    def gettext(self, message: str) -> str: ...\n    def ngettext(self, msgid1: str, msgid2: str, n: int) -> str: ...\n    def pgettext(self, context: str, message: str) -> str: ...\n    def npgettext(self, context: str, msgid1: str, msgid2: str, n: int) -> str: ...\n    def info(self) -> dict[str, str]: ...\n    def charset(self) -> str | None: ...\n    if sys.version_info < (3, 11):\n        @deprecated(\"Deprecated since Python 3.8; removed in Python 3.11.\")\n        def output_charset(self) -> str | None: ...\n        @deprecated(\"Deprecated since Python 3.8; removed in Python 3.11.\")\n        def set_output_charset(self, charset: str) -> None: ...\n        @deprecated(\"Deprecated since Python 3.8; removed in Python 3.11. Use `gettext()` instead.\")\n        def lgettext(self, message: str) -> str: ...\n        @deprecated(\"Deprecated since Python 3.8; removed in Python 3.11. Use `ngettext()` instead.\")\n        def lngettext(self, msgid1: str, msgid2: str, n: int) -> str: ...\n\n    def install(self, names: Container[str] | None = None) -> None: ...\n\nclass GNUTranslations(NullTranslations):\n    LE_MAGIC: Final[int]\n    BE_MAGIC: Final[int]\n    CONTEXT: str\n    VERSIONS: Sequence[int]\n\n@overload\ndef find(\n    domain: str, localedir: StrPath | None = None, languages: Iterable[str] | None = None, all: Literal[False] = False\n) -> str | None: ...\n@overload\ndef find(\n    domain: str, localedir: StrPath | None = None, languages: Iterable[str] | None = None, *, all: Literal[True]\n) -> list[str]: ...\n@overload\ndef find(domain: str, localedir: StrPath | None, languages: Iterable[str] | None, all: Literal[True]) -> list[str]: ...\n@overload\ndef find(domain: str, localedir: StrPath | None = None, languages: Iterable[str] | None = None, all: bool = False) -> Any: ...\n\n_NullTranslationsT = TypeVar(\"_NullTranslationsT\", bound=NullTranslations)\n\nif sys.version_info >= (3, 11):\n    @overload\n    def translation(\n        domain: str,\n        localedir: StrPath | None = None,\n        languages: Iterable[str] | None = None,\n        class_: None = None,\n        fallback: Literal[False] = False,\n    ) -> GNUTranslations: ...\n    @overload\n    def translation(\n        domain: str,\n        localedir: StrPath | None = None,\n        languages: Iterable[str] | None = None,\n        *,\n        class_: Callable[[io.BufferedReader], _NullTranslationsT],\n        fallback: Literal[False] = False,\n    ) -> _NullTranslationsT: ...\n    @overload\n    def translation(\n        domain: str,\n        localedir: StrPath | None,\n        languages: Iterable[str] | None,\n        class_: Callable[[io.BufferedReader], _NullTranslationsT],\n        fallback: Literal[False] = False,\n    ) -> _NullTranslationsT: ...\n    @overload\n    def translation(\n        domain: str,\n        localedir: StrPath | None = None,\n        languages: Iterable[str] | None = None,\n        class_: Callable[[io.BufferedReader], NullTranslations] | None = None,\n        fallback: bool = False,\n    ) -> NullTranslations: ...\n    def install(domain: str, localedir: StrPath | None = None, *, names: Container[str] | None = None) -> None: ...\n\nelse:\n    @overload\n    def translation(\n        domain: str,\n        localedir: StrPath | None = None,\n        languages: Iterable[str] | None = None,\n        class_: None = None,\n        fallback: Literal[False] = False,\n        codeset: str | None = ...,\n    ) -> GNUTranslations: ...\n    @overload\n    def translation(\n        domain: str,\n        localedir: StrPath | None = None,\n        languages: Iterable[str] | None = None,\n        *,\n        class_: Callable[[io.BufferedReader], _NullTranslationsT],\n        fallback: Literal[False] = False,\n        codeset: str | None = ...,\n    ) -> _NullTranslationsT: ...\n    @overload\n    def translation(\n        domain: str,\n        localedir: StrPath | None,\n        languages: Iterable[str] | None,\n        class_: Callable[[io.BufferedReader], _NullTranslationsT],\n        fallback: Literal[False] = False,\n        codeset: str | None = ...,\n    ) -> _NullTranslationsT: ...\n    @overload\n    def translation(\n        domain: str,\n        localedir: StrPath | None = None,\n        languages: Iterable[str] | None = None,\n        class_: Callable[[io.BufferedReader], NullTranslations] | None = None,\n        fallback: bool = False,\n        codeset: str | None = ...,\n    ) -> NullTranslations: ...\n    @overload\n    def install(domain: str, localedir: StrPath | None = None, names: Container[str] | None = None) -> None: ...\n    @overload\n    @deprecated(\"The `codeset` parameter is deprecated since Python 3.8; removed in Python 3.11.\")\n    def install(domain: str, localedir: StrPath | None, codeset: str | None, /, names: Container[str] | None = None) -> None: ...\n    @overload\n    @deprecated(\"The `codeset` parameter is deprecated since Python 3.8; removed in Python 3.11.\")\n    def install(\n        domain: str, localedir: StrPath | None = None, *, codeset: str | None, names: Container[str] | None = None\n    ) -> None: ...\n\ndef textdomain(domain: str | None = None) -> str: ...\ndef bindtextdomain(domain: str, localedir: StrPath | None = None) -> str: ...\ndef dgettext(domain: str, message: str) -> str: ...\ndef dngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ...\ndef gettext(message: str) -> str: ...\ndef ngettext(msgid1: str, msgid2: str, n: int) -> str: ...\ndef pgettext(context: str, message: str) -> str: ...\ndef dpgettext(domain: str, context: str, message: str) -> str: ...\ndef npgettext(context: str, msgid1: str, msgid2: str, n: int) -> str: ...\ndef dnpgettext(domain: str, context: str, msgid1: str, msgid2: str, n: int) -> str: ...\n\nif sys.version_info < (3, 11):\n    @deprecated(\"Deprecated since Python 3.8; removed in Python 3.11. Use `gettext()` instead.\")\n    def lgettext(message: str) -> str: ...\n    @deprecated(\"Deprecated since Python 3.8; removed in Python 3.11. Use `dgettext()` instead.\")\n    def ldgettext(domain: str, message: str) -> str: ...\n    @deprecated(\"Deprecated since Python 3.8; removed in Python 3.11. Use `ngettext()` instead.\")\n    def lngettext(msgid1: str, msgid2: str, n: int) -> str: ...\n    @deprecated(\"Deprecated since Python 3.8; removed in Python 3.11. Use `dngettext()` instead.\")\n    def ldngettext(domain: str, msgid1: str, msgid2: str, n: int) -> str: ...\n    @deprecated(\"Deprecated since Python 3.8; removed in Python 3.11. Use `bindtextdomain()` instead.\")\n    def bind_textdomain_codeset(domain: str, codeset: str | None = None) -> str: ...\n\nCatalog = translation\n\ndef c2py(plural: str) -> Callable[[int], int]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/glob.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath\nfrom collections.abc import Iterator, Sequence\nfrom typing import AnyStr\nfrom typing_extensions import deprecated\n\n__all__ = [\"escape\", \"glob\", \"iglob\"]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"translate\"]\n\nif sys.version_info >= (3, 10):\n    @deprecated(\n        \"Deprecated since Python 3.10; will be removed in Python 3.15. Use `glob.glob()` with the *root_dir* argument instead.\"\n    )\n    def glob0(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ...\n    @deprecated(\n        \"Deprecated since Python 3.10; will be removed in Python 3.15. Use `glob.glob()` with the *root_dir* argument instead.\"\n    )\n    def glob1(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ...\n\nelse:\n    def glob0(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ...\n    def glob1(dirname: AnyStr, pattern: AnyStr) -> list[AnyStr]: ...\n\nif sys.version_info >= (3, 11):\n    def glob(\n        pathname: AnyStr,\n        *,\n        root_dir: StrOrBytesPath | None = None,\n        dir_fd: int | None = None,\n        recursive: bool = False,\n        include_hidden: bool = False,\n    ) -> list[AnyStr]: ...\n    def iglob(\n        pathname: AnyStr,\n        *,\n        root_dir: StrOrBytesPath | None = None,\n        dir_fd: int | None = None,\n        recursive: bool = False,\n        include_hidden: bool = False,\n    ) -> Iterator[AnyStr]: ...\n\nelif sys.version_info >= (3, 10):\n    def glob(\n        pathname: AnyStr, *, root_dir: StrOrBytesPath | None = None, dir_fd: int | None = None, recursive: bool = False\n    ) -> list[AnyStr]: ...\n    def iglob(\n        pathname: AnyStr, *, root_dir: StrOrBytesPath | None = None, dir_fd: int | None = None, recursive: bool = False\n    ) -> Iterator[AnyStr]: ...\n\nelse:\n    def glob(pathname: AnyStr, *, recursive: bool = False) -> list[AnyStr]: ...\n    def iglob(pathname: AnyStr, *, recursive: bool = False) -> Iterator[AnyStr]: ...\n\ndef escape(pathname: AnyStr) -> AnyStr: ...\ndef has_magic(s: str | bytes) -> bool: ...  # undocumented\n\nif sys.version_info >= (3, 13):\n    def translate(\n        pat: str, *, recursive: bool = False, include_hidden: bool = False, seps: Sequence[str] | None = None\n    ) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/graphlib.pyi",
    "content": "import sys\nfrom _typeshed import SupportsItems\nfrom collections.abc import Iterable\nfrom typing import Any, Generic, TypeVar, overload\n\n__all__ = [\"TopologicalSorter\", \"CycleError\"]\n\n_T = TypeVar(\"_T\")\n\nif sys.version_info >= (3, 11):\n    from types import GenericAlias\n\nclass TopologicalSorter(Generic[_T]):\n    @overload\n    def __init__(self, graph: None = None) -> None: ...\n    @overload\n    def __init__(self, graph: SupportsItems[_T, Iterable[_T]]) -> None: ...\n    def add(self, node: _T, *predecessors: _T) -> None: ...\n    def prepare(self) -> None: ...\n    def is_active(self) -> bool: ...\n    def __bool__(self) -> bool: ...\n    def done(self, *nodes: _T) -> None: ...\n    def get_ready(self) -> tuple[_T, ...]: ...\n    def static_order(self) -> Iterable[_T]: ...\n    if sys.version_info >= (3, 11):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass CycleError(ValueError): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/grp.pyi",
    "content": "import sys\nfrom _typeshed import structseq\nfrom typing import Any, Final, final\n\nif sys.platform != \"win32\":\n    @final\n    class struct_group(structseq[Any], tuple[str, str | None, int, list[str]]):\n        if sys.version_info >= (3, 10):\n            __match_args__: Final = (\"gr_name\", \"gr_passwd\", \"gr_gid\", \"gr_mem\")\n\n        @property\n        def gr_name(self) -> str: ...\n        @property\n        def gr_passwd(self) -> str | None: ...\n        @property\n        def gr_gid(self) -> int: ...\n        @property\n        def gr_mem(self) -> list[str]: ...\n\n    def getgrall() -> list[struct_group]: ...\n    def getgrgid(id: int) -> struct_group: ...\n    def getgrnam(name: str) -> struct_group: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/gzip.pyi",
    "content": "import sys\nimport zlib\nfrom _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath, WriteableBuffer\nfrom io import FileIO, TextIOWrapper\nfrom typing import Final, Literal, Protocol, overload, type_check_only\nfrom typing_extensions import TypeAlias, deprecated\n\nif sys.version_info >= (3, 14):\n    from compression._common._streams import BaseStream, DecompressReader\nelse:\n    from _compression import BaseStream, DecompressReader\n\n__all__ = [\"BadGzipFile\", \"GzipFile\", \"open\", \"compress\", \"decompress\"]\n\n_ReadBinaryMode: TypeAlias = Literal[\"r\", \"rb\"]\n_WriteBinaryMode: TypeAlias = Literal[\"a\", \"ab\", \"w\", \"wb\", \"x\", \"xb\"]\n_OpenTextMode: TypeAlias = Literal[\"rt\", \"at\", \"wt\", \"xt\"]\n\nREAD: Final[object]  # undocumented\nWRITE: Final[object]  # undocumented\n\nFTEXT: Final[int]  # actually Literal[1] # undocumented\nFHCRC: Final[int]  # actually Literal[2] # undocumented\nFEXTRA: Final[int]  # actually Literal[4] # undocumented\nFNAME: Final[int]  # actually Literal[8] # undocumented\nFCOMMENT: Final[int]  # actually Literal[16] # undocumented\n\n@type_check_only\nclass _ReadableFileobj(Protocol):\n    def read(self, n: int, /) -> bytes: ...\n    def seek(self, n: int, /) -> object: ...\n    # The following attributes and methods are optional:\n    # name: str\n    # mode: str\n    # def fileno() -> int: ...\n\n@type_check_only\nclass _WritableFileobj(Protocol):\n    def write(self, b: bytes, /) -> object: ...\n    def flush(self) -> object: ...\n    # The following attributes and methods are optional:\n    # name: str\n    # mode: str\n    # def fileno() -> int: ...\n\n@overload\ndef open(\n    filename: StrOrBytesPath | _ReadableFileobj,\n    mode: _ReadBinaryMode = \"rb\",\n    compresslevel: int = 9,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n) -> GzipFile: ...\n@overload\ndef open(\n    filename: StrOrBytesPath | _WritableFileobj,\n    mode: _WriteBinaryMode,\n    compresslevel: int = 9,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n) -> GzipFile: ...\n@overload\ndef open(\n    filename: StrOrBytesPath | _ReadableFileobj | _WritableFileobj,\n    mode: _OpenTextMode,\n    compresslevel: int = 9,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> TextIOWrapper: ...\n@overload\ndef open(\n    filename: StrOrBytesPath | _ReadableFileobj | _WritableFileobj,\n    mode: str,\n    compresslevel: int = 9,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> GzipFile | TextIOWrapper: ...\n\nclass _PaddedFile:\n    file: _ReadableFileobj\n    def __init__(self, f: _ReadableFileobj, prepend: bytes = b\"\") -> None: ...\n    def read(self, size: int) -> bytes: ...\n    def prepend(self, prepend: bytes = b\"\") -> None: ...\n    def seek(self, off: int) -> int: ...\n    def seekable(self) -> bool: ...\n\nclass BadGzipFile(OSError): ...\n\nclass GzipFile(BaseStream):\n    myfileobj: FileIO | None\n    mode: object\n    name: str\n    compress: zlib._Compress\n    fileobj: _ReadableFileobj | _WritableFileobj\n    @overload\n    def __init__(\n        self,\n        filename: StrOrBytesPath | None,\n        mode: _ReadBinaryMode,\n        compresslevel: int = 9,\n        fileobj: _ReadableFileobj | None = None,\n        mtime: float | None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        *,\n        mode: _ReadBinaryMode,\n        compresslevel: int = 9,\n        fileobj: _ReadableFileobj | None = None,\n        mtime: float | None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        filename: StrOrBytesPath | None,\n        mode: _WriteBinaryMode,\n        compresslevel: int = 9,\n        fileobj: _WritableFileobj | None = None,\n        mtime: float | None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        *,\n        mode: _WriteBinaryMode,\n        compresslevel: int = 9,\n        fileobj: _WritableFileobj | None = None,\n        mtime: float | None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        filename: StrOrBytesPath | None = None,\n        mode: str | None = None,\n        compresslevel: int = 9,\n        fileobj: _ReadableFileobj | _WritableFileobj | None = None,\n        mtime: float | None = None,\n    ) -> None: ...\n    if sys.version_info < (3, 12):\n        @property\n        @deprecated(\"Deprecated since Python 2.6; removed in Python 3.12. Use `name` attribute instead.\")\n        def filename(self) -> str: ...\n\n    @property\n    def mtime(self) -> int | None: ...\n    crc: int\n    def write(self, data: ReadableBuffer) -> int: ...\n    def read(self, size: int | None = -1) -> bytes: ...\n    def read1(self, size: int = -1) -> bytes: ...\n    def peek(self, n: int) -> bytes: ...\n    def close(self) -> None: ...\n    def flush(self, zlib_mode: int = 2) -> None: ...\n    def fileno(self) -> int: ...\n    def rewind(self) -> None: ...\n    def seek(self, offset: int, whence: int = 0) -> int: ...\n    def readline(self, size: int | None = -1) -> bytes: ...\n\n    if sys.version_info >= (3, 14):\n        def readinto(self, b: WriteableBuffer) -> int: ...\n        def readinto1(self, b: WriteableBuffer) -> int: ...\n\nclass _GzipReader(DecompressReader):\n    def __init__(self, fp: _ReadableFileobj) -> None: ...\n\nif sys.version_info >= (3, 14):\n    def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float = 0) -> bytes: ...\n\nelse:\n    def compress(data: SizedBuffer, compresslevel: int = 9, *, mtime: float | None = None) -> bytes: ...\n\ndef decompress(data: ReadableBuffer) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/hashlib.pyi",
    "content": "import sys\nfrom _blake2 import blake2b as blake2b, blake2s as blake2s\nfrom _hashlib import (\n    HASH,\n    _HashObject,\n    openssl_md5 as md5,\n    openssl_sha1 as sha1,\n    openssl_sha3_224 as sha3_224,\n    openssl_sha3_256 as sha3_256,\n    openssl_sha3_384 as sha3_384,\n    openssl_sha3_512 as sha3_512,\n    openssl_sha224 as sha224,\n    openssl_sha256 as sha256,\n    openssl_sha384 as sha384,\n    openssl_sha512 as sha512,\n    openssl_shake_128 as shake_128,\n    openssl_shake_256 as shake_256,\n    pbkdf2_hmac as pbkdf2_hmac,\n    scrypt as scrypt,\n)\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Callable, Set as AbstractSet\nfrom typing import Protocol, type_check_only\n\nif sys.version_info >= (3, 11):\n    __all__ = (\n        \"md5\",\n        \"sha1\",\n        \"sha224\",\n        \"sha256\",\n        \"sha384\",\n        \"sha512\",\n        \"blake2b\",\n        \"blake2s\",\n        \"sha3_224\",\n        \"sha3_256\",\n        \"sha3_384\",\n        \"sha3_512\",\n        \"shake_128\",\n        \"shake_256\",\n        \"new\",\n        \"algorithms_guaranteed\",\n        \"algorithms_available\",\n        \"pbkdf2_hmac\",\n        \"file_digest\",\n    )\nelse:\n    __all__ = (\n        \"md5\",\n        \"sha1\",\n        \"sha224\",\n        \"sha256\",\n        \"sha384\",\n        \"sha512\",\n        \"blake2b\",\n        \"blake2s\",\n        \"sha3_224\",\n        \"sha3_256\",\n        \"sha3_384\",\n        \"sha3_512\",\n        \"shake_128\",\n        \"shake_256\",\n        \"new\",\n        \"algorithms_guaranteed\",\n        \"algorithms_available\",\n        \"pbkdf2_hmac\",\n    )\n\ndef new(name: str, data: ReadableBuffer = b\"\", *, usedforsecurity: bool = True) -> HASH: ...\n\nalgorithms_guaranteed: AbstractSet[str]\nalgorithms_available: AbstractSet[str]\n\nif sys.version_info >= (3, 11):\n    @type_check_only\n    class _BytesIOLike(Protocol):\n        def getbuffer(self) -> ReadableBuffer: ...\n\n    @type_check_only\n    class _FileDigestFileObj(Protocol):\n        def readinto(self, buf: bytearray, /) -> int: ...\n        def readable(self) -> bool: ...\n\n    def file_digest(\n        fileobj: _BytesIOLike | _FileDigestFileObj, digest: str | Callable[[], _HashObject], /, *, _bufsize: int = 262144\n    ) -> HASH: ...\n\n# Legacy typing-only alias\n_Hash = HASH\n"
  },
  {
    "path": "mypy/typeshed/stdlib/heapq.pyi",
    "content": "import sys\nfrom _heapq import *\nfrom _typeshed import SupportsRichComparison\nfrom collections.abc import Callable, Generator, Iterable\nfrom typing import Any, Final, TypeVar\n\n__all__ = [\"heappush\", \"heappop\", \"heapify\", \"heapreplace\", \"merge\", \"nlargest\", \"nsmallest\", \"heappushpop\"]\n\nif sys.version_info >= (3, 14):\n    # Added to __all__ in 3.14.1\n    __all__ += [\"heapify_max\", \"heappop_max\", \"heappush_max\", \"heappushpop_max\", \"heapreplace_max\"]\n\n_S = TypeVar(\"_S\")\n\n__about__: Final[str]\n\ndef merge(\n    *iterables: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None, reverse: bool = False\n) -> Generator[_S]: ...\ndef nlargest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]: ...\ndef nsmallest(n: int, iterable: Iterable[_S], key: Callable[[_S], SupportsRichComparison] | None = None) -> list[_S]: ...\ndef _heapify_max(heap: list[Any], /) -> None: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/hmac.pyi",
    "content": "from _hashlib import _HashObject, compare_digest as compare_digest\nfrom _typeshed import ReadableBuffer, SizedBuffer\nfrom collections.abc import Callable\nfrom types import ModuleType\nfrom typing import overload\nfrom typing_extensions import TypeAlias\n\n_DigestMod: TypeAlias = str | Callable[[], _HashObject] | ModuleType\n\ntrans_5C: bytes\ntrans_36: bytes\n\ndigest_size: None\n\n# In reality digestmod has a default value, but the function always throws an error\n# if the argument is not given, so we pretend it is a required argument.\n@overload\ndef new(key: bytes | bytearray, msg: ReadableBuffer | None, digestmod: _DigestMod) -> HMAC: ...\n@overload\ndef new(key: bytes | bytearray, *, digestmod: _DigestMod) -> HMAC: ...\n\nclass HMAC:\n    __slots__ = (\"_hmac\", \"_inner\", \"_outer\", \"block_size\", \"digest_size\")\n    digest_size: int\n    block_size: int\n    @property\n    def name(self) -> str: ...\n    def __init__(self, key: bytes | bytearray, msg: ReadableBuffer | None = None, digestmod: _DigestMod = \"\") -> None: ...\n    def update(self, msg: ReadableBuffer) -> None: ...\n    def digest(self) -> bytes: ...\n    def hexdigest(self) -> str: ...\n    def copy(self) -> HMAC: ...\n\ndef digest(key: SizedBuffer, msg: ReadableBuffer, digest: _DigestMod) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/html/__init__.pyi",
    "content": "from typing import AnyStr\n\n__all__ = [\"escape\", \"unescape\"]\n\ndef escape(s: AnyStr, quote: bool = True) -> AnyStr: ...\ndef unescape(s: AnyStr) -> AnyStr: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/html/entities.pyi",
    "content": "from typing import Final\n\n__all__ = [\"html5\", \"name2codepoint\", \"codepoint2name\", \"entitydefs\"]\n\nname2codepoint: Final[dict[str, int]]\nhtml5: Final[dict[str, str]]\ncodepoint2name: Final[dict[int, str]]\nentitydefs: Final[dict[str, str]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/html/parser.pyi",
    "content": "from _markupbase import ParserBase\nfrom re import Pattern\nfrom typing import Final\n\n__all__ = [\"HTMLParser\"]\n\nclass HTMLParser(ParserBase):\n    CDATA_CONTENT_ELEMENTS: Final[tuple[str, ...]]\n    # Added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.6\n    RCDATA_CONTENT_ELEMENTS: Final[tuple[str, ...]]\n\n    # `scripting` parameter added in Python 3.9.25, 3.10.20, 3.11.15, 3.12.13, 3.13.10, 3.14.1\n    def __init__(self, *, convert_charrefs: bool = True, scripting: bool = False) -> None: ...\n    def feed(self, data: str) -> None: ...\n    def close(self) -> None: ...\n    def get_starttag_text(self) -> str | None: ...\n    def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: ...\n    def handle_endtag(self, tag: str) -> None: ...\n    def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: ...\n    def handle_data(self, data: str) -> None: ...\n    def handle_entityref(self, name: str) -> None: ...\n    def handle_charref(self, name: str) -> None: ...\n    def handle_comment(self, data: str) -> None: ...\n    def handle_decl(self, decl: str) -> None: ...\n    def handle_pi(self, data: str) -> None: ...\n    def check_for_whole_start_tag(self, i: int) -> int: ...  # undocumented\n    def clear_cdata_mode(self) -> None: ...  # undocumented\n    def goahead(self, end: bool) -> None: ...  # undocumented\n    def parse_bogus_comment(self, i: int, report: bool = True) -> int: ...  # undocumented\n    def parse_endtag(self, i: int) -> int: ...  # undocumented\n    def parse_html_declaration(self, i: int) -> int: ...  # undocumented\n    def parse_pi(self, i: int) -> int: ...  # undocumented\n    def parse_starttag(self, i: int) -> int: ...  # undocumented\n    # `escapable` parameter added in Python 3.9.23, 3.10.18, 3.11.13, 3.12.11, 3.13.6\n    def set_cdata_mode(self, elem: str, *, escapable: bool = False) -> None: ...  # undocumented\n    rawdata: str  # undocumented\n    cdata_elem: str | None  # undocumented\n    convert_charrefs: bool  # undocumented\n    interesting: Pattern[str]  # undocumented\n    lasttag: str  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/http/__init__.pyi",
    "content": "import sys\nfrom enum import IntEnum\n\nif sys.version_info >= (3, 11):\n    from enum import StrEnum\n\nif sys.version_info >= (3, 11):\n    __all__ = [\"HTTPStatus\", \"HTTPMethod\"]\nelse:\n    __all__ = [\"HTTPStatus\"]\n\nclass HTTPStatus(IntEnum):\n    @property\n    def phrase(self) -> str: ...\n    @property\n    def description(self) -> str: ...\n\n    # Keep these synced with the global constants in http/client.pyi.\n    CONTINUE = 100\n    SWITCHING_PROTOCOLS = 101\n    PROCESSING = 102\n    EARLY_HINTS = 103\n\n    OK = 200\n    CREATED = 201\n    ACCEPTED = 202\n    NON_AUTHORITATIVE_INFORMATION = 203\n    NO_CONTENT = 204\n    RESET_CONTENT = 205\n    PARTIAL_CONTENT = 206\n    MULTI_STATUS = 207\n    ALREADY_REPORTED = 208\n    IM_USED = 226\n\n    MULTIPLE_CHOICES = 300\n    MOVED_PERMANENTLY = 301\n    FOUND = 302\n    SEE_OTHER = 303\n    NOT_MODIFIED = 304\n    USE_PROXY = 305\n    TEMPORARY_REDIRECT = 307\n    PERMANENT_REDIRECT = 308\n\n    BAD_REQUEST = 400\n    UNAUTHORIZED = 401\n    PAYMENT_REQUIRED = 402\n    FORBIDDEN = 403\n    NOT_FOUND = 404\n    METHOD_NOT_ALLOWED = 405\n    NOT_ACCEPTABLE = 406\n    PROXY_AUTHENTICATION_REQUIRED = 407\n    REQUEST_TIMEOUT = 408\n    CONFLICT = 409\n    GONE = 410\n    LENGTH_REQUIRED = 411\n    PRECONDITION_FAILED = 412\n    if sys.version_info >= (3, 13):\n        CONTENT_TOO_LARGE = 413\n    REQUEST_ENTITY_TOO_LARGE = 413\n    if sys.version_info >= (3, 13):\n        URI_TOO_LONG = 414\n    REQUEST_URI_TOO_LONG = 414\n    UNSUPPORTED_MEDIA_TYPE = 415\n    if sys.version_info >= (3, 13):\n        RANGE_NOT_SATISFIABLE = 416\n    REQUESTED_RANGE_NOT_SATISFIABLE = 416\n    EXPECTATION_FAILED = 417\n    IM_A_TEAPOT = 418\n    MISDIRECTED_REQUEST = 421\n    if sys.version_info >= (3, 13):\n        UNPROCESSABLE_CONTENT = 422\n    UNPROCESSABLE_ENTITY = 422\n    LOCKED = 423\n    FAILED_DEPENDENCY = 424\n    TOO_EARLY = 425\n    UPGRADE_REQUIRED = 426\n    PRECONDITION_REQUIRED = 428\n    TOO_MANY_REQUESTS = 429\n    REQUEST_HEADER_FIELDS_TOO_LARGE = 431\n    UNAVAILABLE_FOR_LEGAL_REASONS = 451\n\n    INTERNAL_SERVER_ERROR = 500\n    NOT_IMPLEMENTED = 501\n    BAD_GATEWAY = 502\n    SERVICE_UNAVAILABLE = 503\n    GATEWAY_TIMEOUT = 504\n    HTTP_VERSION_NOT_SUPPORTED = 505\n    VARIANT_ALSO_NEGOTIATES = 506\n    INSUFFICIENT_STORAGE = 507\n    LOOP_DETECTED = 508\n    NOT_EXTENDED = 510\n    NETWORK_AUTHENTICATION_REQUIRED = 511\n\n    if sys.version_info >= (3, 12):\n        @property\n        def is_informational(self) -> bool: ...\n        @property\n        def is_success(self) -> bool: ...\n        @property\n        def is_redirection(self) -> bool: ...\n        @property\n        def is_client_error(self) -> bool: ...\n        @property\n        def is_server_error(self) -> bool: ...\n\nif sys.version_info >= (3, 11):\n    class HTTPMethod(StrEnum):\n        @property\n        def description(self) -> str: ...\n        CONNECT = \"CONNECT\"\n        DELETE = \"DELETE\"\n        GET = \"GET\"\n        HEAD = \"HEAD\"\n        OPTIONS = \"OPTIONS\"\n        PATCH = \"PATCH\"\n        POST = \"POST\"\n        PUT = \"PUT\"\n        TRACE = \"TRACE\"\n"
  },
  {
    "path": "mypy/typeshed/stdlib/http/client.pyi",
    "content": "import email.message\nimport io\nimport ssl\nimport sys\nimport types\nfrom _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath, SupportsRead, SupportsReadline, WriteableBuffer\nfrom collections.abc import Callable, Iterable, Iterator, Mapping\nfrom email._policybase import _MessageT\nfrom socket import socket\nfrom typing import BinaryIO, Final, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias, deprecated\n\n__all__ = [\n    \"HTTPResponse\",\n    \"HTTPConnection\",\n    \"HTTPException\",\n    \"NotConnected\",\n    \"UnknownProtocol\",\n    \"UnknownTransferEncoding\",\n    \"UnimplementedFileMode\",\n    \"IncompleteRead\",\n    \"InvalidURL\",\n    \"ImproperConnectionState\",\n    \"CannotSendRequest\",\n    \"CannotSendHeader\",\n    \"ResponseNotReady\",\n    \"BadStatusLine\",\n    \"LineTooLong\",\n    \"RemoteDisconnected\",\n    \"error\",\n    \"responses\",\n    \"HTTPSConnection\",\n]\n\n_DataType: TypeAlias = SupportsRead[bytes] | Iterable[ReadableBuffer] | ReadableBuffer\n_T = TypeVar(\"_T\")\n_HeaderValue: TypeAlias = ReadableBuffer | str | int\n\nHTTP_PORT: Final = 80\nHTTPS_PORT: Final = 443\n\n# Keep these global constants in sync with http.HTTPStatus (http/__init__.pyi).\n# They are present for backward compatibility reasons.\nCONTINUE: Final = 100\nSWITCHING_PROTOCOLS: Final = 101\nPROCESSING: Final = 102\nEARLY_HINTS: Final = 103\n\nOK: Final = 200\nCREATED: Final = 201\nACCEPTED: Final = 202\nNON_AUTHORITATIVE_INFORMATION: Final = 203\nNO_CONTENT: Final = 204\nRESET_CONTENT: Final = 205\nPARTIAL_CONTENT: Final = 206\nMULTI_STATUS: Final = 207\nALREADY_REPORTED: Final = 208\nIM_USED: Final = 226\n\nMULTIPLE_CHOICES: Final = 300\nMOVED_PERMANENTLY: Final = 301\nFOUND: Final = 302\nSEE_OTHER: Final = 303\nNOT_MODIFIED: Final = 304\nUSE_PROXY: Final = 305\nTEMPORARY_REDIRECT: Final = 307\nPERMANENT_REDIRECT: Final = 308\n\nBAD_REQUEST: Final = 400\nUNAUTHORIZED: Final = 401\nPAYMENT_REQUIRED: Final = 402\nFORBIDDEN: Final = 403\nNOT_FOUND: Final = 404\nMETHOD_NOT_ALLOWED: Final = 405\nNOT_ACCEPTABLE: Final = 406\nPROXY_AUTHENTICATION_REQUIRED: Final = 407\nREQUEST_TIMEOUT: Final = 408\nCONFLICT: Final = 409\nGONE: Final = 410\nLENGTH_REQUIRED: Final = 411\nPRECONDITION_FAILED: Final = 412\nif sys.version_info >= (3, 13):\n    CONTENT_TOO_LARGE: Final = 413\nREQUEST_ENTITY_TOO_LARGE: Final = 413\nif sys.version_info >= (3, 13):\n    URI_TOO_LONG: Final = 414\nREQUEST_URI_TOO_LONG: Final = 414\nUNSUPPORTED_MEDIA_TYPE: Final = 415\nif sys.version_info >= (3, 13):\n    RANGE_NOT_SATISFIABLE: Final = 416\nREQUESTED_RANGE_NOT_SATISFIABLE: Final = 416\nEXPECTATION_FAILED: Final = 417\nIM_A_TEAPOT: Final = 418\nMISDIRECTED_REQUEST: Final = 421\nif sys.version_info >= (3, 13):\n    UNPROCESSABLE_CONTENT: Final = 422\nUNPROCESSABLE_ENTITY: Final = 422\nLOCKED: Final = 423\nFAILED_DEPENDENCY: Final = 424\nTOO_EARLY: Final = 425\nUPGRADE_REQUIRED: Final = 426\nPRECONDITION_REQUIRED: Final = 428\nTOO_MANY_REQUESTS: Final = 429\nREQUEST_HEADER_FIELDS_TOO_LARGE: Final = 431\nUNAVAILABLE_FOR_LEGAL_REASONS: Final = 451\n\nINTERNAL_SERVER_ERROR: Final = 500\nNOT_IMPLEMENTED: Final = 501\nBAD_GATEWAY: Final = 502\nSERVICE_UNAVAILABLE: Final = 503\nGATEWAY_TIMEOUT: Final = 504\nHTTP_VERSION_NOT_SUPPORTED: Final = 505\nVARIANT_ALSO_NEGOTIATES: Final = 506\nINSUFFICIENT_STORAGE: Final = 507\nLOOP_DETECTED: Final = 508\nNOT_EXTENDED: Final = 510\nNETWORK_AUTHENTICATION_REQUIRED: Final = 511\n\nresponses: dict[int, str]\n\nclass HTTPMessage(email.message.Message[str, str]):\n    def getallmatchingheaders(self, name: str) -> list[str]: ...  # undocumented\n\n@overload\ndef parse_headers(fp: SupportsReadline[bytes], _class: Callable[[], _MessageT]) -> _MessageT: ...\n@overload\ndef parse_headers(fp: SupportsReadline[bytes]) -> HTTPMessage: ...\n\nclass HTTPResponse(io.BufferedIOBase, BinaryIO):  # type: ignore[misc]  # incompatible method definitions in the base classes\n    msg: HTTPMessage\n    headers: HTTPMessage\n    version: int\n    debuglevel: int\n    fp: io.BufferedReader\n    closed: bool\n    status: int\n    reason: str\n    chunked: bool\n    chunk_left: int | None\n    length: int | None\n    will_close: bool\n    # url is set on instances of the class in urllib.request.AbstractHTTPHandler.do_open\n    # to match urllib.response.addinfourl's interface.\n    # It's not set in HTTPResponse.__init__ or any other method on the class\n    url: str\n    def __init__(self, sock: socket, debuglevel: int = 0, method: str | None = None, url: str | None = None) -> None: ...\n    def peek(self, n: int = -1) -> bytes: ...\n    def read(self, amt: int | None = None) -> bytes: ...\n    def read1(self, n: int = -1) -> bytes: ...\n    def readinto(self, b: WriteableBuffer) -> int: ...\n    def readline(self, limit: int = -1) -> bytes: ...  # type: ignore[override]\n    @overload\n    def getheader(self, name: str) -> str | None: ...\n    @overload\n    def getheader(self, name: str, default: _T) -> str | _T: ...\n    def getheaders(self) -> list[tuple[str, str]]: ...\n    def isclosed(self) -> bool: ...\n    def __iter__(self) -> Iterator[bytes]: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None\n    ) -> None: ...\n    @deprecated(\"Deprecated since Python 3.9. Use `HTTPResponse.headers` attribute instead.\")\n    def info(self) -> HTTPMessage: ...\n    @deprecated(\"Deprecated since Python 3.9. Use `HTTPResponse.url` attribute instead.\")\n    def geturl(self) -> str: ...\n    @deprecated(\"Deprecated since Python 3.9. Use `HTTPResponse.status` attribute instead.\")\n    def getcode(self) -> int: ...\n    def begin(self) -> None: ...\n\nclass HTTPConnection:\n    blocksize: int\n    auto_open: int  # undocumented\n    debuglevel: int\n    default_port: int  # undocumented\n    response_class: type[HTTPResponse]  # undocumented\n    timeout: float | None\n    host: str\n    port: int\n    sock: socket | MaybeNone  # can be `None` if `.connect()` was not called\n    def __init__(\n        self,\n        host: str,\n        port: int | None = None,\n        timeout: float | None = ...,\n        source_address: tuple[str, int] | None = None,\n        blocksize: int = 8192,\n    ) -> None: ...\n    def request(\n        self,\n        method: str,\n        url: str,\n        body: _DataType | str | None = None,\n        headers: Mapping[str, _HeaderValue] = {},\n        *,\n        encode_chunked: bool = False,\n    ) -> None: ...\n    def getresponse(self) -> HTTPResponse: ...\n    def set_debuglevel(self, level: int) -> None: ...\n    if sys.version_info >= (3, 12):\n        def get_proxy_response_headers(self) -> HTTPMessage | None: ...\n\n    def set_tunnel(self, host: str, port: int | None = None, headers: Mapping[str, str] | None = None) -> None: ...\n    def connect(self) -> None: ...\n    def close(self) -> None: ...\n    def putrequest(self, method: str, url: str, skip_host: bool = False, skip_accept_encoding: bool = False) -> None: ...\n    def putheader(self, header: str | bytes, *values: _HeaderValue) -> None: ...\n    def endheaders(self, message_body: _DataType | None = None, *, encode_chunked: bool = False) -> None: ...\n    def send(self, data: _DataType | str) -> None: ...\n\nclass HTTPSConnection(HTTPConnection):\n    # Can be `None` if `.connect()` was not called:\n    sock: ssl.SSLSocket | MaybeNone\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self,\n            host: str,\n            port: int | None = None,\n            *,\n            timeout: float | None = ...,\n            source_address: tuple[str, int] | None = None,\n            context: ssl.SSLContext | None = None,\n            blocksize: int = 8192,\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self,\n            host: str,\n            port: int | None = None,\n            key_file: None = None,\n            cert_file: None = None,\n            timeout: float | None = ...,\n            source_address: tuple[str, int] | None = None,\n            *,\n            context: ssl.SSLContext | None = None,\n            check_hostname: None = None,\n            blocksize: int = 8192,\n        ) -> None: ...\n        @overload\n        @deprecated(\n            \"The `key_file`, `cert_file`, `check_hostname` parameters are deprecated since Python 3.6; \"\n            \"removed in Python 3.12. Use `context` parameter instead.\"\n        )\n        def __init__(\n            self,\n            host: str,\n            port: int | None = None,\n            key_file: StrOrBytesPath | None = None,\n            cert_file: StrOrBytesPath | None = None,\n            timeout: float | None = ...,\n            source_address: tuple[str, int] | None = None,\n            *,\n            context: ssl.SSLContext | None = None,\n            check_hostname: bool | None = None,\n            blocksize: int = 8192,\n        ) -> None: ...\n        key_file: StrOrBytesPath | None\n        cert_file: StrOrBytesPath | None\n\nclass HTTPException(Exception): ...\n\nerror = HTTPException\n\nclass NotConnected(HTTPException): ...\nclass InvalidURL(HTTPException): ...\n\nclass UnknownProtocol(HTTPException):\n    def __init__(self, version: str) -> None: ...\n\nclass UnknownTransferEncoding(HTTPException): ...\nclass UnimplementedFileMode(HTTPException): ...\n\nclass IncompleteRead(HTTPException):\n    def __init__(self, partial: bytes, expected: int | None = None) -> None: ...\n    partial: bytes\n    expected: int | None\n\nclass ImproperConnectionState(HTTPException): ...\nclass CannotSendRequest(ImproperConnectionState): ...\nclass CannotSendHeader(ImproperConnectionState): ...\nclass ResponseNotReady(ImproperConnectionState): ...\n\nclass BadStatusLine(HTTPException):\n    def __init__(self, line: str) -> None: ...\n\nclass LineTooLong(HTTPException):\n    def __init__(self, line_type: str) -> None: ...\n\nclass RemoteDisconnected(ConnectionResetError, BadStatusLine): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/http/cookiejar.pyi",
    "content": "import sys\nfrom _typeshed import StrPath\nfrom collections.abc import Iterator, Sequence\nfrom http.client import HTTPResponse\nfrom re import Pattern\nfrom typing import ClassVar, TypeVar, overload\nfrom urllib.request import Request\n\n__all__ = [\n    \"Cookie\",\n    \"CookieJar\",\n    \"CookiePolicy\",\n    \"DefaultCookiePolicy\",\n    \"FileCookieJar\",\n    \"LWPCookieJar\",\n    \"LoadError\",\n    \"MozillaCookieJar\",\n]\n\n_T = TypeVar(\"_T\")\n\nclass LoadError(OSError): ...\n\nclass CookieJar:\n    non_word_re: ClassVar[Pattern[str]]  # undocumented\n    quote_re: ClassVar[Pattern[str]]  # undocumented\n    strict_domain_re: ClassVar[Pattern[str]]  # undocumented\n    domain_re: ClassVar[Pattern[str]]  # undocumented\n    dots_re: ClassVar[Pattern[str]]  # undocumented\n    magic_re: ClassVar[Pattern[str]]  # undocumented\n    def __init__(self, policy: CookiePolicy | None = None) -> None: ...\n    def add_cookie_header(self, request: Request) -> None: ...\n    def extract_cookies(self, response: HTTPResponse, request: Request) -> None: ...\n    def set_policy(self, policy: CookiePolicy) -> None: ...\n    def make_cookies(self, response: HTTPResponse, request: Request) -> Sequence[Cookie]: ...\n    def set_cookie(self, cookie: Cookie) -> None: ...\n    def set_cookie_if_ok(self, cookie: Cookie, request: Request) -> None: ...\n    def clear(self, domain: str | None = None, path: str | None = None, name: str | None = None) -> None: ...\n    def clear_session_cookies(self) -> None: ...\n    def clear_expired_cookies(self) -> None: ...  # undocumented\n    def __iter__(self) -> Iterator[Cookie]: ...\n    def __len__(self) -> int: ...\n\nclass FileCookieJar(CookieJar):\n    filename: str | None\n    delayload: bool\n    def __init__(self, filename: StrPath | None = None, delayload: bool = False, policy: CookiePolicy | None = None) -> None: ...\n    def save(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ...\n    def load(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ...\n    def revert(self, filename: str | None = None, ignore_discard: bool = False, ignore_expires: bool = False) -> None: ...\n\nclass MozillaCookieJar(FileCookieJar):\n    if sys.version_info < (3, 10):\n        header: ClassVar[str]  # undocumented\n\nclass LWPCookieJar(FileCookieJar):\n    def as_lwp_str(self, ignore_discard: bool = True, ignore_expires: bool = True) -> str: ...  # undocumented\n\nclass CookiePolicy:\n    netscape: bool\n    rfc2965: bool\n    hide_cookie2: bool\n    def set_ok(self, cookie: Cookie, request: Request) -> bool: ...\n    def return_ok(self, cookie: Cookie, request: Request) -> bool: ...\n    def domain_return_ok(self, domain: str, request: Request) -> bool: ...\n    def path_return_ok(self, path: str, request: Request) -> bool: ...\n\nclass DefaultCookiePolicy(CookiePolicy):\n    rfc2109_as_netscape: bool\n    strict_domain: bool\n    strict_rfc2965_unverifiable: bool\n    strict_ns_unverifiable: bool\n    strict_ns_domain: int\n    strict_ns_set_initial_dollar: bool\n    strict_ns_set_path: bool\n    DomainStrictNoDots: ClassVar[int]\n    DomainStrictNonDomain: ClassVar[int]\n    DomainRFC2965Match: ClassVar[int]\n    DomainLiberal: ClassVar[int]\n    DomainStrict: ClassVar[int]\n    def __init__(\n        self,\n        blocked_domains: Sequence[str] | None = None,\n        allowed_domains: Sequence[str] | None = None,\n        netscape: bool = True,\n        rfc2965: bool = False,\n        rfc2109_as_netscape: bool | None = None,\n        hide_cookie2: bool = False,\n        strict_domain: bool = False,\n        strict_rfc2965_unverifiable: bool = True,\n        strict_ns_unverifiable: bool = False,\n        strict_ns_domain: int = 0,\n        strict_ns_set_initial_dollar: bool = False,\n        strict_ns_set_path: bool = False,\n        secure_protocols: Sequence[str] = (\"https\", \"wss\"),\n    ) -> None: ...\n    def blocked_domains(self) -> tuple[str, ...]: ...\n    def set_blocked_domains(self, blocked_domains: Sequence[str]) -> None: ...\n    def is_blocked(self, domain: str) -> bool: ...\n    def allowed_domains(self) -> tuple[str, ...] | None: ...\n    def set_allowed_domains(self, allowed_domains: Sequence[str] | None) -> None: ...\n    def is_not_allowed(self, domain: str) -> bool: ...\n    def set_ok_version(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def set_ok_verifiability(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def set_ok_name(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def set_ok_path(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def set_ok_domain(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def set_ok_port(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def return_ok_version(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def return_ok_verifiability(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def return_ok_secure(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def return_ok_expires(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def return_ok_port(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n    def return_ok_domain(self, cookie: Cookie, request: Request) -> bool: ...  # undocumented\n\nclass Cookie:\n    version: int | None\n    name: str\n    value: str | None\n    port: str | None\n    path: str\n    path_specified: bool\n    secure: bool\n    expires: int | None\n    discard: bool\n    comment: str | None\n    comment_url: str | None\n    rfc2109: bool\n    port_specified: bool\n    domain: str  # undocumented\n    domain_specified: bool\n    domain_initial_dot: bool\n    def __init__(\n        self,\n        version: int | None,\n        name: str,\n        value: str | None,  # undocumented\n        port: str | None,\n        port_specified: bool,\n        domain: str,\n        domain_specified: bool,\n        domain_initial_dot: bool,\n        path: str,\n        path_specified: bool,\n        secure: bool,\n        expires: int | None,\n        discard: bool,\n        comment: str | None,\n        comment_url: str | None,\n        rest: dict[str, str],\n        rfc2109: bool = False,\n    ) -> None: ...\n    def has_nonstandard_attr(self, name: str) -> bool: ...\n    @overload\n    def get_nonstandard_attr(self, name: str) -> str | None: ...\n    @overload\n    def get_nonstandard_attr(self, name: str, default: _T) -> str | _T: ...\n    def set_nonstandard_attr(self, name: str, value: str) -> None: ...\n    def is_expired(self, now: int | None = None) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/http/cookies.pyi",
    "content": "from _typeshed import MaybeNone\nfrom collections.abc import Iterable, Mapping\nfrom types import GenericAlias\nfrom typing import Any, Generic, TypeVar, overload\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"CookieError\", \"BaseCookie\", \"SimpleCookie\"]\n\n_DataType: TypeAlias = str | Mapping[str, str | Morsel[Any]]\n_T = TypeVar(\"_T\")\n\n@overload\ndef _quote(str: None) -> None: ...\n@overload\ndef _quote(str: str) -> str: ...\n@overload\ndef _unquote(str: None) -> None: ...\n@overload\ndef _unquote(str: str) -> str: ...\n\nclass CookieError(Exception): ...\n\nclass Morsel(dict[str, Any], Generic[_T]):\n    @property\n    def value(self) -> str | MaybeNone: ...\n    @property\n    def coded_value(self) -> _T | MaybeNone: ...\n    @property\n    def key(self) -> str | MaybeNone: ...\n    def __init__(self) -> None: ...\n    def set(self, key: str, val: str, coded_val: _T) -> None: ...\n    def setdefault(self, key: str, val: str | None = None) -> str: ...\n    # The dict update can also get a keywords argument so this is incompatible\n    @overload  # type: ignore[override]\n    def update(self, values: Mapping[str, str]) -> None: ...\n    @overload\n    def update(self, values: Iterable[tuple[str, str]]) -> None: ...\n    def isReservedKey(self, K: str) -> bool: ...\n    def output(self, attrs: list[str] | None = None, header: str = \"Set-Cookie:\") -> str: ...\n    __str__ = output\n    def js_output(self, attrs: list[str] | None = None) -> str: ...\n    def OutputString(self, attrs: list[str] | None = None) -> str: ...\n    def __eq__(self, morsel: object) -> bool: ...\n    def __setitem__(self, K: str, V: Any) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass BaseCookie(dict[str, Morsel[_T]], Generic[_T]):\n    def __init__(self, input: _DataType | None = None) -> None: ...\n    def value_decode(self, val: str) -> tuple[_T, str]: ...\n    def value_encode(self, val: _T) -> tuple[str, str]: ...\n    def output(self, attrs: list[str] | None = None, header: str = \"Set-Cookie:\", sep: str = \"\\r\\n\") -> str: ...\n    __str__ = output\n    def js_output(self, attrs: list[str] | None = None) -> str: ...\n    def load(self, rawdata: _DataType) -> None: ...\n    def __setitem__(self, key: str, value: str | Morsel[_T]) -> None: ...\n\nclass SimpleCookie(BaseCookie[str]): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/http/server.pyi",
    "content": "import _socket\nimport email.message\nimport io\nimport socketserver\nimport sys\nfrom _ssl import _PasswordType\nfrom _typeshed import ReadableBuffer, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite\nfrom collections.abc import Callable, Iterable, Mapping, Sequence\nfrom ssl import Purpose, SSLContext\nfrom typing import Any, AnyStr, BinaryIO, ClassVar, Protocol, type_check_only\nfrom typing_extensions import Self, deprecated\n\nif sys.version_info >= (3, 14):\n    __all__ = [\n        \"HTTPServer\",\n        \"ThreadingHTTPServer\",\n        \"HTTPSServer\",\n        \"ThreadingHTTPSServer\",\n        \"BaseHTTPRequestHandler\",\n        \"SimpleHTTPRequestHandler\",\n        \"CGIHTTPRequestHandler\",\n    ]\nelse:\n    __all__ = [\"HTTPServer\", \"ThreadingHTTPServer\", \"BaseHTTPRequestHandler\", \"SimpleHTTPRequestHandler\", \"CGIHTTPRequestHandler\"]\n\nclass HTTPServer(socketserver.TCPServer):\n    server_name: str\n    server_port: int\n\nclass ThreadingHTTPServer(socketserver.ThreadingMixIn, HTTPServer): ...\n\nif sys.version_info >= (3, 14):\n    @type_check_only\n    class _SSLModule(Protocol):\n        @staticmethod\n        def create_default_context(\n            purpose: Purpose = ...,\n            *,\n            cafile: StrOrBytesPath | None = None,\n            capath: StrOrBytesPath | None = None,\n            cadata: str | ReadableBuffer | None = None,\n        ) -> SSLContext: ...\n\n    class HTTPSServer(HTTPServer):\n        ssl: _SSLModule\n        certfile: StrOrBytesPath\n        keyfile: StrOrBytesPath | None\n        password: _PasswordType | None\n        alpn_protocols: Iterable[str]\n        def __init__(\n            self,\n            server_address: socketserver._AfInetAddress,\n            RequestHandlerClass: Callable[[Any, _socket._RetAddress, Self], socketserver.BaseRequestHandler],\n            bind_and_activate: bool = True,\n            *,\n            certfile: StrOrBytesPath,\n            keyfile: StrOrBytesPath | None = None,\n            password: _PasswordType | None = None,\n            alpn_protocols: Iterable[str] | None = None,\n        ) -> None: ...\n        def server_activate(self) -> None: ...\n\n    class ThreadingHTTPSServer(socketserver.ThreadingMixIn, HTTPSServer): ...\n\nclass BaseHTTPRequestHandler(socketserver.StreamRequestHandler):\n    client_address: tuple[str, int]\n    close_connection: bool\n    requestline: str\n    command: str\n    path: str\n    request_version: str\n    headers: email.message.Message\n    server_version: str\n    sys_version: str\n    error_message_format: str\n    error_content_type: str\n    protocol_version: str\n    MessageClass: type\n    responses: Mapping[int, tuple[str, str]]\n    default_request_version: str  # undocumented\n    weekdayname: ClassVar[Sequence[str]]  # undocumented\n    monthname: ClassVar[Sequence[str | None]]  # undocumented\n    def handle_one_request(self) -> None: ...\n    def handle_expect_100(self) -> bool: ...\n    def send_error(self, code: int, message: str | None = None, explain: str | None = None) -> None: ...\n    def send_response(self, code: int, message: str | None = None) -> None: ...\n    def send_header(self, keyword: str, value: str) -> None: ...\n    def send_response_only(self, code: int, message: str | None = None) -> None: ...\n    def end_headers(self) -> None: ...\n    def flush_headers(self) -> None: ...\n    def log_request(self, code: int | str = \"-\", size: int | str = \"-\") -> None: ...\n    def log_error(self, format: str, *args: Any) -> None: ...\n    def log_message(self, format: str, *args: Any) -> None: ...\n    def version_string(self) -> str: ...\n    def date_time_string(self, timestamp: float | None = None) -> str: ...\n    def log_date_time_string(self) -> str: ...\n    def address_string(self) -> str: ...\n    def parse_request(self) -> bool: ...  # undocumented\n\nclass SimpleHTTPRequestHandler(BaseHTTPRequestHandler):\n    extensions_map: dict[str, str]\n    if sys.version_info >= (3, 12):\n        index_pages: ClassVar[tuple[str, ...]]\n    directory: str\n    def __init__(\n        self,\n        request: socketserver._RequestType,\n        client_address: _socket._RetAddress,\n        server: socketserver.BaseServer,\n        *,\n        directory: StrPath | None = None,\n    ) -> None: ...\n    def do_GET(self) -> None: ...\n    def do_HEAD(self) -> None: ...\n    def send_head(self) -> io.BytesIO | BinaryIO | None: ...  # undocumented\n    def list_directory(self, path: StrPath) -> io.BytesIO | None: ...  # undocumented\n    def translate_path(self, path: str) -> str: ...  # undocumented\n    def copyfile(self, source: SupportsRead[AnyStr], outputfile: SupportsWrite[AnyStr]) -> None: ...  # undocumented\n    def guess_type(self, path: StrPath) -> str: ...  # undocumented\n\ndef executable(path: StrPath) -> bool: ...  # undocumented\n\nif sys.version_info >= (3, 13):\n    @deprecated(\"Deprecated since Python 3.13; will be removed in Python 3.15.\")\n    class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):\n        cgi_directories: list[str]\n        have_fork: bool  # undocumented\n        def do_POST(self) -> None: ...\n        def is_cgi(self) -> bool: ...  # undocumented\n        def is_executable(self, path: StrPath) -> bool: ...  # undocumented\n        def is_python(self, path: StrPath) -> bool: ...  # undocumented\n        def run_cgi(self) -> None: ...  # undocumented\n\nelse:\n    class CGIHTTPRequestHandler(SimpleHTTPRequestHandler):\n        cgi_directories: list[str]\n        have_fork: bool  # undocumented\n        def do_POST(self) -> None: ...\n        def is_cgi(self) -> bool: ...  # undocumented\n        def is_executable(self, path: StrPath) -> bool: ...  # undocumented\n        def is_python(self, path: StrPath) -> bool: ...  # undocumented\n        def run_cgi(self) -> None: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/imaplib.pyi",
    "content": "import subprocess\nimport sys\nimport time\nfrom _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath, Unused\nfrom builtins import list as _list  # conflicts with a method named \"list\"\nfrom collections.abc import Callable, Generator\nfrom datetime import datetime\nfrom re import Pattern\nfrom socket import socket as _socket\nfrom ssl import SSLContext, SSLSocket\nfrom types import TracebackType\nfrom typing import IO, Any, Literal, SupportsAbs, SupportsInt, overload\nfrom typing_extensions import Self, TypeAlias, deprecated\n\n__all__ = [\"IMAP4\", \"IMAP4_stream\", \"Internaldate2tuple\", \"Int2AP\", \"ParseFlags\", \"Time2Internaldate\", \"IMAP4_SSL\"]\n\n# TODO: Commands should use their actual return types, not this type alias.\n#       E.g. Tuple[Literal[\"OK\"], List[bytes]]\n_CommandResults: TypeAlias = tuple[str, list[Any]]\n\n_AnyResponseData: TypeAlias = list[None] | list[bytes | tuple[bytes, bytes]]\n\nCommands: dict[str, tuple[str, ...]]\n\nclass IMAP4:\n    class error(Exception): ...\n    class abort(error): ...\n    class readonly(abort): ...\n    utf8_enabled: bool\n    mustquote: Pattern[str]\n    debug: int\n    state: str\n    literal: str | None\n    tagged_commands: dict[bytes, _list[bytes] | None]\n    untagged_responses: dict[str, _list[bytes | tuple[bytes, bytes]]]\n    continuation_response: str\n    is_readonly: bool\n    tagnum: int\n    tagpre: str\n    tagre: Pattern[str]\n    welcome: bytes\n    capabilities: tuple[str, ...]\n    PROTOCOL_VERSION: str\n    def __init__(self, host: str = \"\", port: int = 143, timeout: float | None = None) -> None: ...\n    def open(self, host: str = \"\", port: int = 143, timeout: float | None = None) -> None: ...\n    if sys.version_info >= (3, 14):\n        @property\n        @deprecated(\"IMAP4.file is unsupported, can cause errors, and may be removed.\")\n        def file(self) -> IO[str] | IO[bytes]: ...\n    else:\n        file: IO[str] | IO[bytes]\n\n    def __getattr__(self, attr: str) -> Any: ...\n    host: str\n    port: int\n    sock: _socket\n    def read(self, size: int) -> bytes: ...\n    def readline(self) -> bytes: ...\n    def send(self, data: ReadableBuffer) -> None: ...\n    def shutdown(self) -> None: ...\n    def socket(self) -> _socket: ...\n    def recent(self) -> _CommandResults: ...\n    def response(self, code: str) -> _CommandResults: ...\n    def append(\n        self, mailbox: str | None, flags: str | None, date_time: _TimeLike | None, message: ReadableBuffer\n    ) -> tuple[str, _list[bytes]]: ...\n    def authenticate(self, mechanism: str, authobject: Callable[[bytes], bytes | None]) -> tuple[str, str]: ...\n    def capability(self) -> _CommandResults: ...\n    def check(self) -> _CommandResults: ...\n    def close(self) -> _CommandResults: ...\n    def copy(self, message_set: str, new_mailbox: str) -> _CommandResults: ...\n    def create(self, mailbox: str) -> _CommandResults: ...\n    def delete(self, mailbox: str) -> _CommandResults: ...\n    def deleteacl(self, mailbox: str, who: str) -> _CommandResults: ...\n    def enable(self, capability: str) -> _CommandResults: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ...\n    def expunge(self) -> _CommandResults: ...\n    def fetch(self, message_set: str, message_parts: str) -> tuple[str, _AnyResponseData]: ...\n    def getacl(self, mailbox: str) -> _CommandResults: ...\n    def getannotation(self, mailbox: str, entry: str, attribute: str) -> _CommandResults: ...\n    def getquota(self, root: str) -> _CommandResults: ...\n    def getquotaroot(self, mailbox: str) -> _CommandResults: ...\n    if sys.version_info >= (3, 14):\n        def idle(self, duration: float | None = None) -> Idler: ...\n\n    def list(self, directory: str = '\"\"', pattern: str = \"*\") -> tuple[str, _AnyResponseData]: ...\n    def login(self, user: str, password: str) -> tuple[Literal[\"OK\"], _list[bytes]]: ...\n    def login_cram_md5(self, user: str, password: str) -> _CommandResults: ...\n    def logout(self) -> tuple[str, _AnyResponseData]: ...\n    def lsub(self, directory: str = '\"\"', pattern: str = \"*\") -> _CommandResults: ...\n    def myrights(self, mailbox: str) -> _CommandResults: ...\n    def namespace(self) -> _CommandResults: ...\n    def noop(self) -> tuple[str, _list[bytes]]: ...\n    def partial(self, message_num: str, message_part: str, start: str, length: str) -> _CommandResults: ...\n    def proxyauth(self, user: str) -> _CommandResults: ...\n    def rename(self, oldmailbox: str, newmailbox: str) -> _CommandResults: ...\n    def search(self, charset: str | None, *criteria: str) -> _CommandResults: ...\n    def select(self, mailbox: str = \"INBOX\", readonly: bool = False) -> tuple[str, _list[bytes | None]]: ...\n    def setacl(self, mailbox: str, who: str, what: str) -> _CommandResults: ...\n    def setannotation(self, *args: str) -> _CommandResults: ...\n    def setquota(self, root: str, limits: str) -> _CommandResults: ...\n    def sort(self, sort_criteria: str, charset: str, *search_criteria: str) -> _CommandResults: ...\n    def starttls(self, ssl_context: Any | None = None) -> tuple[Literal[\"OK\"], _list[None]]: ...\n    def status(self, mailbox: str, names: str) -> _CommandResults: ...\n    def store(self, message_set: str, command: str, flags: str) -> _CommandResults: ...\n    def subscribe(self, mailbox: str) -> _CommandResults: ...\n    def thread(self, threading_algorithm: str, charset: str, *search_criteria: str) -> _CommandResults: ...\n    def uid(self, command: str, *args: str) -> _CommandResults: ...\n    def unsubscribe(self, mailbox: str) -> _CommandResults: ...\n    def unselect(self) -> _CommandResults: ...\n    def xatom(self, name: str, *args: str) -> _CommandResults: ...\n    def print_log(self) -> None: ...\n\nif sys.version_info >= (3, 14):\n    class Idler:\n        def __init__(self, imap: IMAP4, duration: float | None = None) -> None: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(self, exc_type: object, exc_val: Unused, exc_tb: Unused) -> Literal[False]: ...\n        def __iter__(self) -> Self: ...\n        def __next__(self) -> tuple[str, float | None]: ...\n        def burst(self, interval: float = 0.1) -> Generator[tuple[str, float | None]]: ...\n\nclass IMAP4_SSL(IMAP4):\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self, host: str = \"\", port: int = 993, *, ssl_context: SSLContext | None = None, timeout: float | None = None\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self,\n            host: str = \"\",\n            port: int = 993,\n            keyfile: None = None,\n            certfile: None = None,\n            ssl_context: SSLContext | None = None,\n            timeout: float | None = None,\n        ) -> None: ...\n        @overload\n        @deprecated(\n            \"The `keyfile`, `certfile` parameters are deprecated since Python 3.6; \"\n            \"removed in Python 3.12. Use `ssl_context` parameter instead.\"\n        )\n        def __init__(\n            self,\n            host: str = \"\",\n            port: int = 993,\n            keyfile: StrOrBytesPath | None = None,\n            certfile: StrOrBytesPath | None = None,\n            ssl_context: None = None,\n            timeout: float | None = None,\n        ) -> None: ...\n        keyfile: StrOrBytesPath | None\n        certfile: StrOrBytesPath | None\n    sslobj: SSLSocket\n    if sys.version_info >= (3, 14):\n        @property\n        @deprecated(\"IMAP4_SSL.file is unsupported, can cause errors, and may be removed.\")\n        def file(self) -> IO[Any]: ...\n    else:\n        file: IO[Any]\n\n    def open(self, host: str = \"\", port: int | None = 993, timeout: float | None = None) -> None: ...\n    def ssl(self) -> SSLSocket: ...\n\nclass IMAP4_stream(IMAP4):\n    command: str\n    def __init__(self, command: str) -> None: ...\n    if sys.version_info >= (3, 14):\n        @property\n        @deprecated(\"IMAP4_stream.file is unsupported, can cause errors, and may be removed.\")\n        def file(self) -> IO[Any]: ...\n    else:\n        file: IO[Any]\n    process: subprocess.Popen[bytes]\n    writefile: IO[Any]\n    readfile: IO[Any]\n    def open(self, host: str | None = None, port: int | None = None, timeout: float | None = None) -> None: ...\n\nclass _Authenticator:\n    mech: Callable[[bytes], bytes | bytearray | memoryview | str | None]\n    def __init__(self, mechinst: Callable[[bytes], bytes | bytearray | memoryview | str | None]) -> None: ...\n    def process(self, data: str) -> str: ...\n    def encode(self, inp: bytes | bytearray | memoryview) -> str: ...\n    def decode(self, inp: str | SizedBuffer) -> bytes: ...\n\ndef Internaldate2tuple(resp: ReadableBuffer) -> time.struct_time | None: ...\ndef Int2AP(num: SupportsAbs[SupportsInt]) -> bytes: ...\ndef ParseFlags(resp: ReadableBuffer) -> tuple[bytes, ...]: ...\n\n_TimeLike: TypeAlias = float | time.struct_time | time._TimeTuple | datetime | str\n\ndef Time2Internaldate(date_time: _TimeLike) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/imghdr.pyi",
    "content": "from _typeshed import StrPath\nfrom collections.abc import Callable\nfrom typing import Any, BinaryIO, Protocol, overload, type_check_only\n\n__all__ = [\"what\"]\n\n@type_check_only\nclass _ReadableBinary(Protocol):\n    def tell(self) -> int: ...\n    def read(self, size: int, /) -> bytes: ...\n    def seek(self, offset: int, /) -> Any: ...\n\n@overload\ndef what(file: StrPath | _ReadableBinary, h: None = None) -> str | None: ...\n@overload\ndef what(file: Any, h: bytes) -> str | None: ...\n\ntests: list[Callable[[bytes, BinaryIO | None], str | None]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/imp.pyi",
    "content": "import types\nfrom _imp import (\n    acquire_lock as acquire_lock,\n    create_dynamic as create_dynamic,\n    get_frozen_object as get_frozen_object,\n    init_frozen as init_frozen,\n    is_builtin as is_builtin,\n    is_frozen as is_frozen,\n    is_frozen_package as is_frozen_package,\n    lock_held as lock_held,\n    release_lock as release_lock,\n)\nfrom _typeshed import StrPath\nfrom os import PathLike\nfrom types import TracebackType\nfrom typing import IO, Any, Final, Protocol, type_check_only\n\nSEARCH_ERROR: Final = 0\nPY_SOURCE: Final = 1\nPY_COMPILED: Final = 2\nC_EXTENSION: Final = 3\nPY_RESOURCE: Final = 4\nPKG_DIRECTORY: Final = 5\nC_BUILTIN: Final = 6\nPY_FROZEN: Final = 7\nPY_CODERESOURCE: Final = 8\nIMP_HOOK: Final = 9\n\ndef new_module(name: str) -> types.ModuleType: ...\ndef get_magic() -> bytes: ...\ndef get_tag() -> str: ...\ndef cache_from_source(path: StrPath, debug_override: bool | None = None) -> str: ...\ndef source_from_cache(path: StrPath) -> str: ...\ndef get_suffixes() -> list[tuple[str, str, int]]: ...\n\nclass NullImporter:\n    def __init__(self, path: StrPath) -> None: ...\n    def find_module(self, fullname: Any) -> None: ...\n\n# Technically, a text file has to support a slightly different set of operations than a binary file,\n# but we ignore that here.\n@type_check_only\nclass _FileLike(Protocol):\n    closed: bool\n    mode: str\n    def read(self) -> str | bytes: ...\n    def close(self) -> Any: ...\n    def __enter__(self) -> Any: ...\n    def __exit__(self, typ: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None, /) -> Any: ...\n\n# PathLike doesn't work for the pathname argument here\ndef load_source(name: str, pathname: str, file: _FileLike | None = None) -> types.ModuleType: ...\ndef load_compiled(name: str, pathname: str, file: _FileLike | None = None) -> types.ModuleType: ...\ndef load_package(name: str, path: StrPath) -> types.ModuleType: ...\ndef load_module(name: str, file: _FileLike | None, filename: str, details: tuple[str, str, int]) -> types.ModuleType: ...\n\n# IO[Any] is a TextIOWrapper if name is a .py file, and a FileIO otherwise.\ndef find_module(\n    name: str, path: None | list[str] | list[PathLike[str]] | list[StrPath] = None\n) -> tuple[IO[Any], str, tuple[str, str, int]]: ...\ndef reload(module: types.ModuleType) -> types.ModuleType: ...\ndef init_builtin(name: str) -> types.ModuleType | None: ...\ndef load_dynamic(name: str, path: str, file: Any = None) -> types.ModuleType: ...  # file argument is ignored\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/__init__.pyi",
    "content": "import sys\nfrom importlib._bootstrap import __import__ as __import__\nfrom importlib.abc import Loader\nfrom types import ModuleType\nfrom typing_extensions import deprecated\n\n__all__ = [\"__import__\", \"import_module\", \"invalidate_caches\", \"reload\"]\n\n# `importlib.import_module` return type should be kept the same as `builtins.__import__`\ndef import_module(name: str, package: str | None = None) -> ModuleType: ...\n\nif sys.version_info < (3, 12):\n    @deprecated(\"Deprecated since Python 3.4; removed in Python 3.12. Use `importlib.util.find_spec()` instead.\")\n    def find_loader(name: str, path: str | None = None) -> Loader | None: ...\n\ndef invalidate_caches() -> None: ...\ndef reload(module: ModuleType) -> ModuleType: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/_abc.pyi",
    "content": "import sys\nimport types\nfrom abc import ABCMeta\nfrom importlib.machinery import ModuleSpec\nfrom typing_extensions import deprecated\n\nif sys.version_info >= (3, 10):\n    class Loader(metaclass=ABCMeta):\n        def load_module(self, fullname: str) -> types.ModuleType: ...\n        if sys.version_info < (3, 12):\n            @deprecated(\n                \"Deprecated since Python 3.4; removed in Python 3.12. \"\n                \"The module spec is now used by the import machinery to generate a module repr.\"\n            )\n            def module_repr(self, module: types.ModuleType) -> str: ...\n\n        def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ...\n        # Not defined on the actual class for backwards-compatibility reasons,\n        # but expected in new code.\n        def exec_module(self, module: types.ModuleType) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/_bootstrap.pyi",
    "content": "from _frozen_importlib import *\nfrom _frozen_importlib import __import__ as __import__, _init_module_attrs as _init_module_attrs\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/_bootstrap_external.pyi",
    "content": "from _frozen_importlib_external import *\nfrom _frozen_importlib_external import _NamespaceLoader as _NamespaceLoader\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/abc.pyi",
    "content": "import _ast\nimport sys\nimport types\nfrom _typeshed import ReadableBuffer, StrPath\nfrom abc import ABCMeta, abstractmethod\nfrom collections.abc import Iterator, Mapping, Sequence\nfrom importlib import _bootstrap_external\nfrom importlib.machinery import ModuleSpec\nfrom io import BufferedReader\nfrom typing import IO, Any, Literal, Protocol, overload, runtime_checkable\nfrom typing_extensions import deprecated\n\nif sys.version_info >= (3, 11):\n    __all__ = [\n        \"Loader\",\n        \"MetaPathFinder\",\n        \"PathEntryFinder\",\n        \"ResourceLoader\",\n        \"InspectLoader\",\n        \"ExecutionLoader\",\n        \"FileLoader\",\n        \"SourceLoader\",\n    ]\n\n    if sys.version_info < (3, 12):\n        __all__ += [\"Finder\", \"ResourceReader\", \"Traversable\", \"TraversableResources\"]\n\nif sys.version_info >= (3, 10):\n    from importlib._abc import Loader as Loader\nelse:\n    class Loader(metaclass=ABCMeta):\n        def load_module(self, fullname: str) -> types.ModuleType: ...\n        def module_repr(self, module: types.ModuleType) -> str: ...\n        def create_module(self, spec: ModuleSpec) -> types.ModuleType | None: ...\n        # Not defined on the actual class for backwards-compatibility reasons,\n        # but expected in new code.\n        def exec_module(self, module: types.ModuleType) -> None: ...\n\nif sys.version_info < (3, 12):\n    @deprecated(\"Deprecated since Python 3.3; removed in Python 3.12. Use `MetaPathFinder` or `PathEntryFinder` instead.\")\n    class Finder(metaclass=ABCMeta): ...\n\n@deprecated(\"Deprecated since Python 3.7. Use `importlib.resources.abc.TraversableResources` instead.\")\nclass ResourceLoader(Loader):\n    @abstractmethod\n    def get_data(self, path: str) -> bytes: ...\n\nclass InspectLoader(Loader):\n    def is_package(self, fullname: str) -> bool: ...\n    def get_code(self, fullname: str) -> types.CodeType | None: ...\n    @abstractmethod\n    def get_source(self, fullname: str) -> str | None: ...\n    def exec_module(self, module: types.ModuleType) -> None: ...\n    @staticmethod\n    def source_to_code(\n        data: ReadableBuffer | str | _ast.Module | _ast.Expression | _ast.Interactive, path: bytes | StrPath = \"<string>\"\n    ) -> types.CodeType: ...\n\nclass ExecutionLoader(InspectLoader):\n    @abstractmethod\n    def get_filename(self, fullname: str) -> str: ...\n\nclass SourceLoader(_bootstrap_external.SourceLoader, ResourceLoader, ExecutionLoader, metaclass=ABCMeta):  # type: ignore[misc]  # incompatible definitions of source_to_code in the base classes\n    @deprecated(\"Deprecated since Python 3.3. Use `importlib.resources.abc.SourceLoader.path_stats` instead.\")\n    def path_mtime(self, path: str) -> float: ...\n    def set_data(self, path: str, data: bytes) -> None: ...\n    def get_source(self, fullname: str) -> str | None: ...\n    def path_stats(self, path: str) -> Mapping[str, Any]: ...\n\n# The base classes differ starting in 3.10:\nif sys.version_info >= (3, 10):\n    # Please keep in sync with _typeshed.importlib.MetaPathFinderProtocol\n    class MetaPathFinder(metaclass=ABCMeta):\n        if sys.version_info < (3, 12):\n            @deprecated(\"Deprecated since Python 3.4; removed in Python 3.12. Use `MetaPathFinder.find_spec()` instead.\")\n            def find_module(self, fullname: str, path: Sequence[str] | None) -> Loader | None: ...\n\n        def invalidate_caches(self) -> None: ...\n        # Not defined on the actual class, but expected to exist.\n        def find_spec(\n            self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ..., /\n        ) -> ModuleSpec | None: ...\n\n    class PathEntryFinder(metaclass=ABCMeta):\n        if sys.version_info < (3, 12):\n            @deprecated(\"Deprecated since Python 3.4; removed in Python 3.12. Use `PathEntryFinder.find_spec()` instead.\")\n            def find_module(self, fullname: str) -> Loader | None: ...\n            @deprecated(\"Deprecated since Python 3.4; removed in Python 3.12. Use `find_spec()` instead.\")\n            def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[str]]: ...\n\n        def invalidate_caches(self) -> None: ...\n        # Not defined on the actual class, but expected to exist.\n        def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ...\n\nelse:\n    # Please keep in sync with _typeshed.importlib.MetaPathFinderProtocol\n    class MetaPathFinder(Finder):\n        def find_module(self, fullname: str, path: Sequence[str] | None) -> Loader | None: ...\n        def invalidate_caches(self) -> None: ...\n        # Not defined on the actual class, but expected to exist.\n        def find_spec(\n            self, fullname: str, path: Sequence[str] | None, target: types.ModuleType | None = ..., /\n        ) -> ModuleSpec | None: ...\n\n    class PathEntryFinder(Finder):\n        def find_module(self, fullname: str) -> Loader | None: ...\n        def find_loader(self, fullname: str) -> tuple[Loader | None, Sequence[str]]: ...\n        def invalidate_caches(self) -> None: ...\n        # Not defined on the actual class, but expected to exist.\n        def find_spec(self, fullname: str, target: types.ModuleType | None = ...) -> ModuleSpec | None: ...\n\nclass FileLoader(_bootstrap_external.FileLoader, ResourceLoader, ExecutionLoader, metaclass=ABCMeta):\n    name: str\n    path: str\n    def __init__(self, fullname: str, path: str) -> None: ...\n    def get_data(self, path: str) -> bytes: ...\n    def get_filename(self, fullname: str | None = None) -> str: ...\n    def load_module(self, fullname: str | None = None) -> types.ModuleType: ...\n\nif sys.version_info < (3, 11):\n    class ResourceReader(metaclass=ABCMeta):\n        @abstractmethod\n        def open_resource(self, resource: str) -> IO[bytes]: ...\n        @abstractmethod\n        def resource_path(self, resource: str) -> str: ...\n        if sys.version_info >= (3, 10):\n            @abstractmethod\n            def is_resource(self, path: str) -> bool: ...\n        else:\n            @abstractmethod\n            def is_resource(self, name: str) -> bool: ...\n\n        @abstractmethod\n        def contents(self) -> Iterator[str]: ...\n\n    @runtime_checkable\n    class Traversable(Protocol):\n        @abstractmethod\n        def is_dir(self) -> bool: ...\n        @abstractmethod\n        def is_file(self) -> bool: ...\n        @abstractmethod\n        def iterdir(self) -> Iterator[Traversable]: ...\n        if sys.version_info >= (3, 11):\n            @abstractmethod\n            def joinpath(self, *descendants: str) -> Traversable: ...\n        else:\n            @abstractmethod\n            def joinpath(self, child: str, /) -> Traversable: ...\n\n        # The documentation and runtime protocol allows *args, **kwargs arguments,\n        # but this would mean that all implementers would have to support them,\n        # which is not the case.\n        @overload\n        @abstractmethod\n        def open(self, mode: Literal[\"r\"] = \"r\", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: ...\n        @overload\n        @abstractmethod\n        def open(self, mode: Literal[\"rb\"]) -> IO[bytes]: ...\n        @property\n        @abstractmethod\n        def name(self) -> str: ...\n        if sys.version_info >= (3, 10):\n            def __truediv__(self, child: str, /) -> Traversable: ...\n        else:\n            @abstractmethod\n            def __truediv__(self, child: str, /) -> Traversable: ...\n\n        @abstractmethod\n        def read_bytes(self) -> bytes: ...\n        @abstractmethod\n        def read_text(self, encoding: str | None = None) -> str: ...\n\n    class TraversableResources(ResourceReader):\n        @abstractmethod\n        def files(self) -> Traversable: ...\n        def open_resource(self, resource: str) -> BufferedReader: ...\n        def resource_path(self, resource: Any) -> str: ...\n        def is_resource(self, path: str) -> bool: ...\n        def contents(self) -> Iterator[str]: ...\n\nelif sys.version_info < (3, 14):\n    from importlib.resources.abc import (\n        ResourceReader as ResourceReader,\n        Traversable as Traversable,\n        TraversableResources as TraversableResources,\n    )\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/machinery.pyi",
    "content": "import sys\nfrom importlib._bootstrap import BuiltinImporter as BuiltinImporter, FrozenImporter as FrozenImporter, ModuleSpec as ModuleSpec\nfrom importlib._bootstrap_external import (\n    BYTECODE_SUFFIXES as BYTECODE_SUFFIXES,\n    DEBUG_BYTECODE_SUFFIXES as DEBUG_BYTECODE_SUFFIXES,\n    EXTENSION_SUFFIXES as EXTENSION_SUFFIXES,\n    OPTIMIZED_BYTECODE_SUFFIXES as OPTIMIZED_BYTECODE_SUFFIXES,\n    SOURCE_SUFFIXES as SOURCE_SUFFIXES,\n    ExtensionFileLoader as ExtensionFileLoader,\n    FileFinder as FileFinder,\n    PathFinder as PathFinder,\n    SourceFileLoader as SourceFileLoader,\n    SourcelessFileLoader as SourcelessFileLoader,\n    WindowsRegistryFinder as WindowsRegistryFinder,\n)\n\nif sys.version_info >= (3, 11):\n    from importlib._bootstrap_external import NamespaceLoader as NamespaceLoader\nif sys.version_info >= (3, 14):\n    from importlib._bootstrap_external import AppleFrameworkLoader as AppleFrameworkLoader\n\ndef all_suffixes() -> list[str]: ...\n\nif sys.version_info >= (3, 14):\n    __all__ = [\n        \"AppleFrameworkLoader\",\n        \"BYTECODE_SUFFIXES\",\n        \"BuiltinImporter\",\n        \"DEBUG_BYTECODE_SUFFIXES\",\n        \"EXTENSION_SUFFIXES\",\n        \"ExtensionFileLoader\",\n        \"FileFinder\",\n        \"FrozenImporter\",\n        \"ModuleSpec\",\n        \"NamespaceLoader\",\n        \"OPTIMIZED_BYTECODE_SUFFIXES\",\n        \"PathFinder\",\n        \"SOURCE_SUFFIXES\",\n        \"SourceFileLoader\",\n        \"SourcelessFileLoader\",\n        \"WindowsRegistryFinder\",\n        \"all_suffixes\",\n    ]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/metadata/__init__.pyi",
    "content": "import abc\nimport pathlib\nimport sys\nimport types\nfrom _collections_abc import dict_keys, dict_values\nfrom _typeshed import StrPath\nfrom collections.abc import Iterable, Iterator, Mapping\nfrom email.message import Message\nfrom importlib.abc import MetaPathFinder\nfrom os import PathLike\nfrom pathlib import Path\nfrom re import Pattern\nfrom typing import Any, ClassVar, Generic, NamedTuple, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias, deprecated, disjoint_base\n\n_T = TypeVar(\"_T\")\n_KT = TypeVar(\"_KT\")\n_VT = TypeVar(\"_VT\")\n\n__all__ = [\n    \"Distribution\",\n    \"DistributionFinder\",\n    \"PackageNotFoundError\",\n    \"distribution\",\n    \"distributions\",\n    \"entry_points\",\n    \"files\",\n    \"metadata\",\n    \"requires\",\n    \"version\",\n]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"PackageMetadata\", \"packages_distributions\"]\n\nif sys.version_info >= (3, 10):\n    from importlib.metadata._meta import PackageMetadata as PackageMetadata, SimplePath\n    def packages_distributions() -> Mapping[str, list[str]]: ...\n\n    _SimplePath: TypeAlias = SimplePath\n\nelse:\n    _SimplePath: TypeAlias = Path\n\nclass PackageNotFoundError(ModuleNotFoundError):\n    @property\n    def name(self) -> str: ...  # type: ignore[override]\n\nif sys.version_info >= (3, 13):\n    _EntryPointBase = object\nelif sys.version_info >= (3, 11):\n    class DeprecatedTuple:\n        def __getitem__(self, item: int) -> str: ...\n\n    _EntryPointBase = DeprecatedTuple\nelse:\n    class _EntryPointBase(NamedTuple):\n        name: str\n        value: str\n        group: str\n\nif sys.version_info >= (3, 11):\n    class EntryPoint(_EntryPointBase):\n        pattern: ClassVar[Pattern[str]]\n        name: str\n        value: str\n        group: str\n\n        def __init__(self, name: str, value: str, group: str) -> None: ...\n        def load(self) -> Any: ...  # Callable[[], Any] or an importable module\n        @property\n        def extras(self) -> list[str]: ...\n        @property\n        def module(self) -> str: ...\n        @property\n        def attr(self) -> str: ...\n        dist: ClassVar[Distribution | None]\n        def matches(\n            self,\n            *,\n            name: str = ...,\n            value: str = ...,\n            group: str = ...,\n            module: str = ...,\n            attr: str = ...,\n            extras: list[str] = ...,\n        ) -> bool: ...  # undocumented\n        def __hash__(self) -> int: ...\n        def __eq__(self, other: object) -> bool: ...\n        def __lt__(self, other: object) -> bool: ...\n        if sys.version_info < (3, 12):\n            def __iter__(self) -> Iterator[Any]: ...  # result of iter((str, Self)), really\n\nelse:\n    @disjoint_base\n    class EntryPoint(_EntryPointBase):\n        pattern: ClassVar[Pattern[str]]\n\n        def load(self) -> Any: ...  # Callable[[], Any] or an importable module\n        @property\n        def extras(self) -> list[str]: ...\n        @property\n        def module(self) -> str: ...\n        @property\n        def attr(self) -> str: ...\n        if sys.version_info >= (3, 10):\n            dist: ClassVar[Distribution | None]\n            def matches(\n                self,\n                *,\n                name: str = ...,\n                value: str = ...,\n                group: str = ...,\n                module: str = ...,\n                attr: str = ...,\n                extras: list[str] = ...,\n            ) -> bool: ...  # undocumented\n\n        def __hash__(self) -> int: ...\n        def __iter__(self) -> Iterator[Any]: ...  # result of iter((str, Self)), really\n\nif sys.version_info >= (3, 12):\n    class EntryPoints(tuple[EntryPoint, ...]):\n        __slots__ = ()\n        def __getitem__(self, name: str) -> EntryPoint: ...  # type: ignore[override]\n        def select(\n            self,\n            *,\n            name: str = ...,\n            value: str = ...,\n            group: str = ...,\n            module: str = ...,\n            attr: str = ...,\n            extras: list[str] = ...,\n        ) -> EntryPoints: ...\n        @property\n        def names(self) -> set[str]: ...\n        @property\n        def groups(self) -> set[str]: ...\n\nelif sys.version_info >= (3, 10):\n    class DeprecatedList(list[_T]):\n        __slots__ = ()\n\n    class EntryPoints(DeprecatedList[EntryPoint]):  # use as list is deprecated since 3.10\n        # int argument is deprecated since 3.10\n        __slots__ = ()\n        def __getitem__(self, name: int | str) -> EntryPoint: ...  # type: ignore[override]\n        def select(\n            self,\n            *,\n            name: str = ...,\n            value: str = ...,\n            group: str = ...,\n            module: str = ...,\n            attr: str = ...,\n            extras: list[str] = ...,\n        ) -> EntryPoints: ...\n        @property\n        def names(self) -> set[str]: ...\n        @property\n        def groups(self) -> set[str]: ...\n\nif sys.version_info >= (3, 10) and sys.version_info < (3, 12):\n    class Deprecated(Generic[_KT, _VT]):\n        def __getitem__(self, name: _KT) -> _VT: ...\n        @overload\n        def get(self, name: _KT, default: None = None) -> _VT | None: ...\n        @overload\n        def get(self, name: _KT, default: _VT) -> _VT: ...\n        @overload\n        def get(self, name: _KT, default: _T) -> _VT | _T: ...\n        def __iter__(self) -> Iterator[_KT]: ...\n        def __contains__(self, *args: object) -> bool: ...\n        def keys(self) -> dict_keys[_KT, _VT]: ...\n        def values(self) -> dict_values[_KT, _VT]: ...\n\n    @deprecated(\"Deprecated since Python 3.10; removed in Python 3.12. Use `select` instead.\")\n    class SelectableGroups(Deprecated[str, EntryPoints], dict[str, EntryPoints]):  # use as dict is deprecated since 3.10\n        @classmethod\n        def load(cls, eps: Iterable[EntryPoint]) -> Self: ...\n        @property\n        def groups(self) -> set[str]: ...\n        @property\n        def names(self) -> set[str]: ...\n        @overload\n        def select(self) -> Self: ...\n        @overload\n        def select(\n            self,\n            *,\n            name: str = ...,\n            value: str = ...,\n            group: str = ...,\n            module: str = ...,\n            attr: str = ...,\n            extras: list[str] = ...,\n        ) -> EntryPoints: ...\n\nclass PackagePath(pathlib.PurePosixPath):\n    def read_text(self, encoding: str = \"utf-8\") -> str: ...\n    def read_binary(self) -> bytes: ...\n    def locate(self) -> PathLike[str]: ...\n    # The following attributes are not defined on PackagePath, but are dynamically added by Distribution.files:\n    hash: FileHash | None\n    size: int | None\n    dist: Distribution\n\nclass FileHash:\n    mode: str\n    value: str\n    def __init__(self, spec: str) -> None: ...\n\nif sys.version_info >= (3, 12):\n    class DeprecatedNonAbstract: ...\n    _distribution_parent = DeprecatedNonAbstract\nelse:\n    _distribution_parent = object\n\nclass Distribution(_distribution_parent):\n    @abc.abstractmethod\n    def read_text(self, filename: str) -> str | None: ...\n    @abc.abstractmethod\n    def locate_file(self, path: StrPath) -> _SimplePath: ...\n    @classmethod\n    def from_name(cls, name: str) -> Distribution: ...\n    @overload\n    @classmethod\n    def discover(cls, *, context: DistributionFinder.Context) -> Iterable[Distribution]: ...\n    @overload\n    @classmethod\n    def discover(\n        cls, *, context: None = None, name: str | None = ..., path: list[str] = ..., **kwargs: Any\n    ) -> Iterable[Distribution]: ...\n    @staticmethod\n    def at(path: StrPath) -> PathDistribution: ...\n\n    if sys.version_info >= (3, 10):\n        @property\n        def metadata(self) -> PackageMetadata: ...\n        @property\n        def entry_points(self) -> EntryPoints: ...\n    else:\n        @property\n        def metadata(self) -> Message: ...\n        @property\n        def entry_points(self) -> list[EntryPoint]: ...\n\n    @property\n    def version(self) -> str: ...\n    @property\n    def files(self) -> list[PackagePath] | None: ...\n    @property\n    def requires(self) -> list[str] | None: ...\n    if sys.version_info >= (3, 10):\n        @property\n        def name(self) -> str: ...\n    if sys.version_info >= (3, 13):\n        @property\n        def origin(self) -> types.SimpleNamespace | None: ...\n\nclass DistributionFinder(MetaPathFinder):\n    class Context:\n        name: str | None\n        def __init__(self, *, name: str | None = ..., path: list[str] = ..., **kwargs: Any) -> None: ...\n        @property\n        def path(self) -> list[str]: ...\n\n    @abc.abstractmethod\n    def find_distributions(self, context: DistributionFinder.Context = ...) -> Iterable[Distribution]: ...\n\nclass MetadataPathFinder(DistributionFinder):\n    @classmethod\n    def find_distributions(cls, context: DistributionFinder.Context = ...) -> Iterable[PathDistribution]: ...\n    if sys.version_info >= (3, 11):\n        @classmethod\n        def invalidate_caches(cls) -> None: ...\n    elif sys.version_info >= (3, 10):\n        # Yes, this is an instance method that has a parameter named \"cls\"\n        def invalidate_caches(cls) -> None: ...\n\nclass PathDistribution(Distribution):\n    _path: _SimplePath\n    def __init__(self, path: _SimplePath) -> None: ...\n    def read_text(self, filename: StrPath) -> str | None: ...\n    def locate_file(self, path: StrPath) -> _SimplePath: ...\n\ndef distribution(distribution_name: str) -> Distribution: ...\n@overload\ndef distributions(*, context: DistributionFinder.Context) -> Iterable[Distribution]: ...\n@overload\ndef distributions(\n    *, context: None = None, name: str | None = ..., path: list[str] = ..., **kwargs: Any\n) -> Iterable[Distribution]: ...\n\nif sys.version_info >= (3, 10):\n    def metadata(distribution_name: str) -> PackageMetadata: ...\n\nelse:\n    def metadata(distribution_name: str) -> Message: ...\n\nif sys.version_info >= (3, 12):\n    def entry_points(\n        *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ...\n    ) -> EntryPoints: ...\n\nelif sys.version_info >= (3, 10):\n    @overload\n    def entry_points() -> SelectableGroups: ...\n    @overload\n    def entry_points(\n        *, name: str = ..., value: str = ..., group: str = ..., module: str = ..., attr: str = ..., extras: list[str] = ...\n    ) -> EntryPoints: ...\n\nelse:\n    def entry_points() -> dict[str, list[EntryPoint]]: ...\n\ndef version(distribution_name: str) -> str: ...\ndef files(distribution_name: str) -> list[PackagePath] | None: ...\ndef requires(distribution_name: str) -> list[str] | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/metadata/_meta.pyi",
    "content": "import sys\nfrom _typeshed import StrPath\nfrom collections.abc import Iterator\nfrom os import PathLike\nfrom typing import Any, Protocol, overload\nfrom typing_extensions import TypeVar\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True, default=Any)\n\nclass PackageMetadata(Protocol):\n    def __len__(self) -> int: ...\n    def __contains__(self, item: str) -> bool: ...\n    def __getitem__(self, key: str) -> str: ...\n    def __iter__(self) -> Iterator[str]: ...\n    @property\n    def json(self) -> dict[str, str | list[str]]: ...\n    @overload\n    def get_all(self, name: str, failobj: None = None) -> list[Any] | None: ...\n    @overload\n    def get_all(self, name: str, failobj: _T) -> list[Any] | _T: ...\n    if sys.version_info >= (3, 12):\n        @overload\n        def get(self, name: str, failobj: None = None) -> str | None: ...\n        @overload\n        def get(self, name: str, failobj: _T) -> _T | str: ...\n\nif sys.version_info >= (3, 13):\n    class SimplePath(Protocol):\n        def joinpath(self, other: StrPath, /) -> SimplePath: ...\n        def __truediv__(self, other: StrPath, /) -> SimplePath: ...\n        # Incorrect at runtime\n        @property\n        def parent(self) -> PathLike[str]: ...\n        def read_text(self, encoding: str | None = None) -> str: ...\n        def read_bytes(self) -> bytes: ...\n        def exists(self) -> bool: ...\n\nelif sys.version_info >= (3, 12):\n    class SimplePath(Protocol[_T_co]):\n        # At runtime this is defined as taking `str | _T`, but that causes trouble.\n        # See #11436.\n        def joinpath(self, other: str, /) -> _T_co: ...\n        @property\n        def parent(self) -> _T_co: ...\n        def read_text(self) -> str: ...\n        # As with joinpath(), this is annotated as taking `str | _T` at runtime.\n        def __truediv__(self, other: str, /) -> _T_co: ...\n\nelse:\n    class SimplePath(Protocol):\n        # Actually takes only self at runtime, but that's clearly wrong\n        def joinpath(self, other: Any, /) -> SimplePath: ...\n        # Not defined as a property at runtime, but it should be\n        @property\n        def parent(self) -> Any: ...\n        def read_text(self) -> str: ...\n        # There was a bug in `SimplePath` definition in cpython, see #8451\n        #  Strictly speaking `__div__` was defined in 3.10, not __truediv__,\n        # but it should have always been `__truediv__`.\n        # Also, the runtime defines this method as taking no arguments,\n        # which is obviously wrong.\n        def __truediv__(self, other: Any, /) -> SimplePath: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/metadata/diagnose.pyi",
    "content": "def inspect(path: str) -> None: ...\ndef run() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/readers.pyi",
    "content": "# On py311+, things are actually defined in importlib.resources.readers,\n# and re-exported here,\n# but doing it this way leads to less code duplication for us\n\nimport pathlib\nimport sys\nimport zipfile\nfrom _typeshed import StrPath\nfrom collections.abc import Iterable, Iterator\nfrom io import BufferedReader\nfrom typing import Literal, NoReturn, TypeVar\nfrom typing_extensions import Never\n\nif sys.version_info >= (3, 10):\n    from importlib._bootstrap_external import FileLoader\n    from zipimport import zipimporter\n\nif sys.version_info >= (3, 11):\n    from importlib.resources import abc\nelse:\n    from importlib import abc\n\nif sys.version_info >= (3, 10):\n    if sys.version_info >= (3, 11):\n        __all__ = [\"FileReader\", \"ZipReader\", \"MultiplexedPath\", \"NamespaceReader\"]\n\n    if sys.version_info < (3, 11):\n        _T = TypeVar(\"_T\")\n\n        def remove_duplicates(items: Iterable[_T]) -> Iterator[_T]: ...\n\n    class FileReader(abc.TraversableResources):\n        path: pathlib.Path\n        def __init__(self, loader: FileLoader) -> None: ...\n        def resource_path(self, resource: StrPath) -> str: ...\n        def files(self) -> pathlib.Path: ...\n\n    class ZipReader(abc.TraversableResources):\n        prefix: str\n        archive: str\n        def __init__(self, loader: zipimporter, module: str) -> None: ...\n        def open_resource(self, resource: str) -> BufferedReader: ...\n        def is_resource(self, path: StrPath) -> bool: ...\n        def files(self) -> zipfile.Path: ...\n\n    class MultiplexedPath(abc.Traversable):\n        def __init__(self, *paths: abc.Traversable) -> None: ...\n        def iterdir(self) -> Iterator[abc.Traversable]: ...\n        def read_bytes(self) -> NoReturn: ...\n        def read_text(self, *args: Never, **kwargs: Never) -> NoReturn: ...  # type: ignore[override]\n        def is_dir(self) -> Literal[True]: ...\n        def is_file(self) -> Literal[False]: ...\n\n        if sys.version_info >= (3, 12):\n            def joinpath(self, *descendants: StrPath) -> abc.Traversable: ...\n        elif sys.version_info >= (3, 11):\n            def joinpath(self, child: StrPath) -> abc.Traversable: ...  # type: ignore[override]\n        else:\n            def joinpath(self, child: str) -> abc.Traversable: ...\n\n        if sys.version_info < (3, 12):\n            __truediv__ = joinpath\n\n        def open(self, *args: Never, **kwargs: Never) -> NoReturn: ...  # type: ignore[override]\n        @property\n        def name(self) -> str: ...\n\n    class NamespaceReader(abc.TraversableResources):\n        path: MultiplexedPath\n        def __init__(self, namespace_path: Iterable[str]) -> None: ...\n        def resource_path(self, resource: str) -> str: ...\n        def files(self) -> MultiplexedPath: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/resources/__init__.pyi",
    "content": "import os\nimport sys\nfrom collections.abc import Iterator\nfrom contextlib import AbstractContextManager\nfrom pathlib import Path\nfrom types import ModuleType\nfrom typing import Any, BinaryIO, Literal, TextIO\nfrom typing_extensions import TypeAlias, deprecated\n\nif sys.version_info >= (3, 11):\n    from importlib.resources.abc import Traversable\nelse:\n    from importlib.abc import Traversable\n\nif sys.version_info >= (3, 11):\n    from importlib.resources._common import Package as Package\nelse:\n    Package: TypeAlias = str | ModuleType\n\n__all__ = [\n    \"Package\",\n    \"as_file\",\n    \"contents\",\n    \"files\",\n    \"is_resource\",\n    \"open_binary\",\n    \"open_text\",\n    \"path\",\n    \"read_binary\",\n    \"read_text\",\n]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"ResourceReader\"]\n\nif sys.version_info < (3, 13):\n    __all__ += [\"Resource\"]\n\nif sys.version_info < (3, 11):\n    Resource: TypeAlias = str | os.PathLike[Any]\nelif sys.version_info < (3, 13):\n    Resource: TypeAlias = str\n\nif sys.version_info >= (3, 12):\n    from importlib.resources._common import Anchor as Anchor\n\n    __all__ += [\"Anchor\"]\n\nif sys.version_info >= (3, 13):\n    from importlib.resources._functional import (\n        contents as contents,\n        is_resource as is_resource,\n        open_binary as open_binary,\n        open_text as open_text,\n        path as path,\n        read_binary as read_binary,\n        read_text as read_text,\n    )\n\nelse:\n    def open_binary(package: Package, resource: Resource) -> BinaryIO: ...\n    def open_text(package: Package, resource: Resource, encoding: str = \"utf-8\", errors: str = \"strict\") -> TextIO: ...\n    def read_binary(package: Package, resource: Resource) -> bytes: ...\n    def read_text(package: Package, resource: Resource, encoding: str = \"utf-8\", errors: str = \"strict\") -> str: ...\n    def path(package: Package, resource: Resource) -> AbstractContextManager[Path, Literal[False]]: ...\n    def is_resource(package: Package, name: str) -> bool: ...\n    if sys.version_info >= (3, 11):\n        @deprecated(\"Deprecated since Python 3.11. Use `files(anchor).iterdir()`.\")\n        def contents(package: Package) -> Iterator[str]: ...\n    else:\n        def contents(package: Package) -> Iterator[str]: ...\n\nif sys.version_info >= (3, 11):\n    from importlib.resources._common import as_file as as_file\nelse:\n    def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: ...\n\nif sys.version_info >= (3, 11):\n    from importlib.resources._common import files as files\nelse:\n    def files(package: Package) -> Traversable: ...\n\nif sys.version_info >= (3, 11):\n    from importlib.resources.abc import ResourceReader as ResourceReader\nelif sys.version_info >= (3, 10):\n    from importlib.abc import ResourceReader as ResourceReader\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/resources/_common.pyi",
    "content": "import sys\n\n# Even though this file is 3.11+ only, Pyright will complain in stubtest for older versions.\nif sys.version_info >= (3, 11):\n    import types\n    from collections.abc import Callable\n    from contextlib import AbstractContextManager\n    from importlib.resources.abc import ResourceReader, Traversable\n    from pathlib import Path\n    from typing import Literal, overload\n    from typing_extensions import TypeAlias, deprecated\n\n    Package: TypeAlias = str | types.ModuleType\n\n    if sys.version_info >= (3, 12):\n        Anchor: TypeAlias = Package\n\n        def package_to_anchor(\n            func: Callable[[Anchor | None], Traversable],\n        ) -> Callable[[Anchor | None, Anchor | None], Traversable]: ...\n        @overload\n        def files(anchor: Anchor | None = None) -> Traversable: ...\n        @overload\n        @deprecated(\"Deprecated since Python 3.12; will be removed in Python 3.15. Use `anchor` parameter instead.\")\n        def files(package: Anchor | None = None) -> Traversable: ...\n\n    else:\n        def files(package: Package) -> Traversable: ...\n\n    def get_resource_reader(package: types.ModuleType) -> ResourceReader | None: ...\n\n    if sys.version_info >= (3, 12):\n        def resolve(cand: Anchor | None) -> types.ModuleType: ...\n\n    else:\n        def resolve(cand: Package) -> types.ModuleType: ...\n\n    if sys.version_info < (3, 12):\n        def get_package(package: Package) -> types.ModuleType: ...\n\n    def from_package(package: types.ModuleType) -> Traversable: ...\n    def as_file(path: Traversable) -> AbstractContextManager[Path, Literal[False]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/resources/_functional.pyi",
    "content": "import sys\n\n# Even though this file is 3.13+ only, Pyright will complain in stubtest for older versions.\nif sys.version_info >= (3, 13):\n    from _typeshed import StrPath\n    from collections.abc import Iterator\n    from contextlib import AbstractContextManager\n    from importlib.resources._common import Anchor\n    from io import TextIOWrapper\n    from pathlib import Path\n    from typing import BinaryIO, Literal, overload\n    from typing_extensions import Unpack, deprecated\n\n    def open_binary(anchor: Anchor, *path_names: StrPath) -> BinaryIO: ...\n    @overload\n    def open_text(\n        anchor: Anchor, *path_names: Unpack[tuple[StrPath]], encoding: str | None = \"utf-8\", errors: str | None = \"strict\"\n    ) -> TextIOWrapper: ...\n    @overload\n    def open_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = \"strict\") -> TextIOWrapper: ...\n    def read_binary(anchor: Anchor, *path_names: StrPath) -> bytes: ...\n    @overload\n    def read_text(\n        anchor: Anchor, *path_names: Unpack[tuple[StrPath]], encoding: str | None = \"utf-8\", errors: str | None = \"strict\"\n    ) -> str: ...\n    @overload\n    def read_text(anchor: Anchor, *path_names: StrPath, encoding: str | None, errors: str | None = \"strict\") -> str: ...\n    def path(anchor: Anchor, *path_names: StrPath) -> AbstractContextManager[Path, Literal[False]]: ...\n    def is_resource(anchor: Anchor, *path_names: StrPath) -> bool: ...\n    @deprecated(\"Deprecated since Python 3.11. Use `files(anchor).iterdir()`.\")\n    def contents(anchor: Anchor, *path_names: StrPath) -> Iterator[str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/resources/abc.pyi",
    "content": "import sys\nfrom _typeshed import StrPath\nfrom abc import ABCMeta, abstractmethod\nfrom collections.abc import Iterator\nfrom io import BufferedReader\nfrom typing import IO, Any, Literal, Protocol, overload, runtime_checkable\nfrom typing_extensions import deprecated\n\nif sys.version_info >= (3, 11):\n    @deprecated(\"Deprecated since Python 3.12. Use `importlib.resources.abc.TraversableResources` instead.\")\n    class ResourceReader(metaclass=ABCMeta):\n        @abstractmethod\n        def open_resource(self, resource: str) -> IO[bytes]: ...\n        @abstractmethod\n        def resource_path(self, resource: str) -> str: ...\n        @abstractmethod\n        def is_resource(self, path: str) -> bool: ...\n        @abstractmethod\n        def contents(self) -> Iterator[str]: ...\n\n    @runtime_checkable\n    class Traversable(Protocol):\n        @abstractmethod\n        def is_dir(self) -> bool: ...\n        @abstractmethod\n        def is_file(self) -> bool: ...\n        @abstractmethod\n        def iterdir(self) -> Iterator[Traversable]: ...\n        @abstractmethod\n        def joinpath(self, *descendants: StrPath) -> Traversable: ...\n\n        # The documentation and runtime protocol allows *args, **kwargs arguments,\n        # but this would mean that all implementers would have to support them,\n        # which is not the case.\n        @overload\n        @abstractmethod\n        def open(self, mode: Literal[\"r\"] = \"r\", *, encoding: str | None = None, errors: str | None = None) -> IO[str]: ...\n        @overload\n        @abstractmethod\n        def open(self, mode: Literal[\"rb\"]) -> IO[bytes]: ...\n        @property\n        @abstractmethod\n        def name(self) -> str: ...\n        def __truediv__(self, child: StrPath, /) -> Traversable: ...\n        @abstractmethod\n        def read_bytes(self) -> bytes: ...\n        @abstractmethod\n        def read_text(self, encoding: str | None = None) -> str: ...\n\n    class TraversableResources(ResourceReader):\n        @abstractmethod\n        def files(self) -> Traversable: ...\n        def open_resource(self, resource: str) -> BufferedReader: ...\n        def resource_path(self, resource: Any) -> str: ...\n        def is_resource(self, path: str) -> bool: ...\n        def contents(self) -> Iterator[str]: ...\n\n    __all__ = [\"ResourceReader\", \"Traversable\", \"TraversableResources\"]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/resources/readers.pyi",
    "content": "# On py311+, things are actually defined here\n# and re-exported from importlib.readers,\n# but doing it this way leads to less code duplication for us\n\nimport sys\nfrom collections.abc import Iterable, Iterator\nfrom typing import TypeVar\n\nif sys.version_info >= (3, 11):\n    from importlib.readers import *\n\n    _T = TypeVar(\"_T\")\n\n    def remove_duplicates(items: Iterable[_T]) -> Iterator[_T]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/resources/simple.pyi",
    "content": "import abc\nimport sys\nfrom _typeshed import StrPath\nfrom collections.abc import Iterator\nfrom io import TextIOWrapper\nfrom typing import IO, Any, BinaryIO, Literal, NoReturn, overload\nfrom typing_extensions import Never\n\nif sys.version_info >= (3, 11):\n    from .abc import Traversable, TraversableResources\n\n    class SimpleReader(abc.ABC):\n        @property\n        @abc.abstractmethod\n        def package(self) -> str: ...\n        @abc.abstractmethod\n        def children(self) -> list[SimpleReader]: ...\n        @abc.abstractmethod\n        def resources(self) -> list[str]: ...\n        @abc.abstractmethod\n        def open_binary(self, resource: str) -> BinaryIO: ...\n        @property\n        def name(self) -> str: ...\n\n    class ResourceHandle(Traversable, metaclass=abc.ABCMeta):\n        parent: ResourceContainer\n        def __init__(self, parent: ResourceContainer, name: str) -> None: ...\n        def is_file(self) -> Literal[True]: ...\n        def is_dir(self) -> Literal[False]: ...\n        @overload\n        def open(\n            self,\n            mode: Literal[\"r\"] = \"r\",\n            encoding: str | None = None,\n            errors: str | None = None,\n            newline: str | None = None,\n            line_buffering: bool = False,\n            write_through: bool = False,\n        ) -> TextIOWrapper: ...\n        @overload\n        def open(self, mode: Literal[\"rb\"]) -> BinaryIO: ...\n        @overload\n        def open(self, mode: str) -> IO[Any]: ...\n        def joinpath(self, name: Never) -> NoReturn: ...  # type: ignore[override]\n\n    class ResourceContainer(Traversable, metaclass=abc.ABCMeta):\n        reader: SimpleReader\n        def __init__(self, reader: SimpleReader) -> None: ...\n        def is_dir(self) -> Literal[True]: ...\n        def is_file(self) -> Literal[False]: ...\n        def iterdir(self) -> Iterator[ResourceHandle | ResourceContainer]: ...\n        def open(self, *args: Never, **kwargs: Never) -> NoReturn: ...  # type: ignore[override]\n        if sys.version_info < (3, 12):\n            def joinpath(self, *descendants: StrPath) -> Traversable: ...\n\n    class TraversableReader(TraversableResources, SimpleReader, metaclass=abc.ABCMeta):\n        def files(self) -> ResourceContainer: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/simple.pyi",
    "content": "import sys\n\nif sys.version_info >= (3, 11):\n    from .resources.simple import (\n        ResourceContainer as ResourceContainer,\n        ResourceHandle as ResourceHandle,\n        SimpleReader as SimpleReader,\n        TraversableReader as TraversableReader,\n    )\n\n    __all__ = [\"SimpleReader\", \"ResourceHandle\", \"ResourceContainer\", \"TraversableReader\"]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/importlib/util.pyi",
    "content": "import importlib.machinery\nimport sys\nimport types\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Callable\nfrom importlib._bootstrap import module_from_spec as module_from_spec, spec_from_loader as spec_from_loader\nfrom importlib._bootstrap_external import (\n    MAGIC_NUMBER as MAGIC_NUMBER,\n    cache_from_source as cache_from_source,\n    decode_source as decode_source,\n    source_from_cache as source_from_cache,\n    spec_from_file_location as spec_from_file_location,\n)\nfrom importlib.abc import Loader\nfrom types import TracebackType\nfrom typing import Literal\nfrom typing_extensions import ParamSpec, Self, deprecated\n\n_P = ParamSpec(\"_P\")\n\nif sys.version_info < (3, 12):\n    @deprecated(\n        \"Deprecated since Python 3.4; removed in Python 3.12. \"\n        \"`__name__`, `__package__` and `__loader__` are now set automatically.\"\n    )\n    def module_for_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ...\n    @deprecated(\n        \"Deprecated since Python 3.4; removed in Python 3.12. \"\n        \"`__name__`, `__package__` and `__loader__` are now set automatically.\"\n    )\n    def set_loader(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ...\n    @deprecated(\n        \"Deprecated since Python 3.4; removed in Python 3.12. \"\n        \"`__name__`, `__package__` and `__loader__` are now set automatically.\"\n    )\n    def set_package(fxn: Callable[_P, types.ModuleType]) -> Callable[_P, types.ModuleType]: ...\n\ndef resolve_name(name: str, package: str | None) -> str: ...\ndef find_spec(name: str, package: str | None = None) -> importlib.machinery.ModuleSpec | None: ...\n\nclass LazyLoader(Loader):\n    def __init__(self, loader: Loader) -> None: ...\n    @classmethod\n    def factory(cls, loader: Loader) -> Callable[..., LazyLoader]: ...\n    def exec_module(self, module: types.ModuleType) -> None: ...\n\ndef source_hash(source_bytes: ReadableBuffer) -> bytes: ...\n\nif sys.version_info >= (3, 12):\n    class _incompatible_extension_module_restrictions:\n        def __init__(self, *, disable_check: bool) -> None: ...\n        disable_check: bool\n        old: Literal[-1, 0, 1]  # exists only while entered\n        def __enter__(self) -> Self: ...\n        def __exit__(\n            self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n        ) -> None: ...\n        @property\n        def override(self) -> Literal[-1, 1]: ...  # undocumented\n\nif sys.version_info >= (3, 14):\n    __all__ = [\n        \"LazyLoader\",\n        \"Loader\",\n        \"MAGIC_NUMBER\",\n        \"cache_from_source\",\n        \"decode_source\",\n        \"find_spec\",\n        \"module_from_spec\",\n        \"resolve_name\",\n        \"source_from_cache\",\n        \"source_hash\",\n        \"spec_from_file_location\",\n        \"spec_from_loader\",\n    ]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/inspect.pyi",
    "content": "import dis\nimport enum\nimport sys\nimport types\nfrom _typeshed import AnnotationForm, StrPath\nfrom collections import OrderedDict\nfrom collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine, Generator, Mapping, Sequence, Set as AbstractSet\nfrom types import (\n    AsyncGeneratorType,\n    BuiltinFunctionType,\n    BuiltinMethodType,\n    ClassMethodDescriptorType,\n    CodeType,\n    CoroutineType,\n    FrameType,\n    FunctionType,\n    GeneratorType,\n    GetSetDescriptorType,\n    LambdaType,\n    MemberDescriptorType,\n    MethodDescriptorType,\n    MethodType,\n    MethodWrapperType,\n    ModuleType,\n    TracebackType,\n    WrapperDescriptorType,\n)\nfrom typing import Any, ClassVar, Final, Literal, NamedTuple, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import ParamSpec, Self, TypeAlias, TypeGuard, TypeIs, deprecated, disjoint_base\n\nif sys.version_info >= (3, 14):\n    from annotationlib import Format\n\nif sys.version_info >= (3, 11):\n    __all__ = [\n        \"ArgInfo\",\n        \"Arguments\",\n        \"Attribute\",\n        \"BlockFinder\",\n        \"BoundArguments\",\n        \"CORO_CLOSED\",\n        \"CORO_CREATED\",\n        \"CORO_RUNNING\",\n        \"CORO_SUSPENDED\",\n        \"CO_ASYNC_GENERATOR\",\n        \"CO_COROUTINE\",\n        \"CO_GENERATOR\",\n        \"CO_ITERABLE_COROUTINE\",\n        \"CO_NESTED\",\n        \"CO_NEWLOCALS\",\n        \"CO_NOFREE\",\n        \"CO_OPTIMIZED\",\n        \"CO_VARARGS\",\n        \"CO_VARKEYWORDS\",\n        \"ClassFoundException\",\n        \"ClosureVars\",\n        \"EndOfBlock\",\n        \"FrameInfo\",\n        \"FullArgSpec\",\n        \"GEN_CLOSED\",\n        \"GEN_CREATED\",\n        \"GEN_RUNNING\",\n        \"GEN_SUSPENDED\",\n        \"Parameter\",\n        \"Signature\",\n        \"TPFLAGS_IS_ABSTRACT\",\n        \"Traceback\",\n        \"classify_class_attrs\",\n        \"cleandoc\",\n        \"currentframe\",\n        \"findsource\",\n        \"formatannotation\",\n        \"formatannotationrelativeto\",\n        \"formatargvalues\",\n        \"get_annotations\",\n        \"getabsfile\",\n        \"getargs\",\n        \"getargvalues\",\n        \"getattr_static\",\n        \"getblock\",\n        \"getcallargs\",\n        \"getclasstree\",\n        \"getclosurevars\",\n        \"getcomments\",\n        \"getcoroutinelocals\",\n        \"getcoroutinestate\",\n        \"getdoc\",\n        \"getfile\",\n        \"getframeinfo\",\n        \"getfullargspec\",\n        \"getgeneratorlocals\",\n        \"getgeneratorstate\",\n        \"getinnerframes\",\n        \"getlineno\",\n        \"getmembers\",\n        \"getmembers_static\",\n        \"getmodule\",\n        \"getmodulename\",\n        \"getmro\",\n        \"getouterframes\",\n        \"getsource\",\n        \"getsourcefile\",\n        \"getsourcelines\",\n        \"indentsize\",\n        \"isabstract\",\n        \"isasyncgen\",\n        \"isasyncgenfunction\",\n        \"isawaitable\",\n        \"isbuiltin\",\n        \"isclass\",\n        \"iscode\",\n        \"iscoroutine\",\n        \"iscoroutinefunction\",\n        \"isdatadescriptor\",\n        \"isframe\",\n        \"isfunction\",\n        \"isgenerator\",\n        \"isgeneratorfunction\",\n        \"isgetsetdescriptor\",\n        \"ismemberdescriptor\",\n        \"ismethod\",\n        \"ismethoddescriptor\",\n        \"ismethodwrapper\",\n        \"ismodule\",\n        \"isroutine\",\n        \"istraceback\",\n        \"signature\",\n        \"stack\",\n        \"trace\",\n        \"unwrap\",\n        \"walktree\",\n    ]\n\n    if sys.version_info >= (3, 12):\n        __all__ += [\n            \"markcoroutinefunction\",\n            \"AGEN_CLOSED\",\n            \"AGEN_CREATED\",\n            \"AGEN_RUNNING\",\n            \"AGEN_SUSPENDED\",\n            \"getasyncgenlocals\",\n            \"getasyncgenstate\",\n            \"BufferFlags\",\n        ]\n    if sys.version_info >= (3, 14):\n        __all__ += [\"CO_HAS_DOCSTRING\", \"CO_METHOD\", \"ispackage\"]\n\n_P = ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\n_F = TypeVar(\"_F\", bound=Callable[..., Any])\n_T_contra = TypeVar(\"_T_contra\", contravariant=True)\n_V_contra = TypeVar(\"_V_contra\", contravariant=True)\n\n#\n# Types and members\n#\nclass EndOfBlock(Exception): ...\n\nclass BlockFinder:\n    indent: int\n    islambda: bool\n    started: bool\n    passline: bool\n    indecorator: bool\n    decoratorhasargs: bool\n    last: int\n    def tokeneater(self, type: int, token: str, srowcol: tuple[int, int], erowcol: tuple[int, int], line: str) -> None: ...\n\nCO_OPTIMIZED: Final = 1\nCO_NEWLOCALS: Final = 2\nCO_VARARGS: Final = 4\nCO_VARKEYWORDS: Final = 8\nCO_NESTED: Final = 16\nCO_GENERATOR: Final = 32\nCO_NOFREE: Final = 64\nCO_COROUTINE: Final = 128\nCO_ITERABLE_COROUTINE: Final = 256\nCO_ASYNC_GENERATOR: Final = 512\nTPFLAGS_IS_ABSTRACT: Final = 1048576\nif sys.version_info >= (3, 14):\n    CO_HAS_DOCSTRING: Final = 67108864\n    CO_METHOD: Final = 134217728\n\nmodulesbyfile: dict[str, Any]\n\n_GetMembersPredicateTypeGuard: TypeAlias = Callable[[Any], TypeGuard[_T]]\n_GetMembersPredicateTypeIs: TypeAlias = Callable[[Any], TypeIs[_T]]\n_GetMembersPredicate: TypeAlias = Callable[[Any], bool]\n_GetMembersReturn: TypeAlias = list[tuple[str, _T]]\n\n@overload\ndef getmembers(object: object, predicate: _GetMembersPredicateTypeGuard[_T]) -> _GetMembersReturn[_T]: ...\n@overload\ndef getmembers(object: object, predicate: _GetMembersPredicateTypeIs[_T]) -> _GetMembersReturn[_T]: ...\n@overload\ndef getmembers(object: object, predicate: _GetMembersPredicate | None = None) -> _GetMembersReturn[Any]: ...\n\nif sys.version_info >= (3, 11):\n    @overload\n    def getmembers_static(object: object, predicate: _GetMembersPredicateTypeGuard[_T]) -> _GetMembersReturn[_T]: ...\n    @overload\n    def getmembers_static(object: object, predicate: _GetMembersPredicateTypeIs[_T]) -> _GetMembersReturn[_T]: ...\n    @overload\n    def getmembers_static(object: object, predicate: _GetMembersPredicate | None = None) -> _GetMembersReturn[Any]: ...\n\ndef getmodulename(path: StrPath) -> str | None: ...\ndef ismodule(object: object) -> TypeIs[ModuleType]: ...\ndef isclass(object: object) -> TypeIs[type[Any]]: ...\ndef ismethod(object: object) -> TypeIs[MethodType]: ...\n\nif sys.version_info >= (3, 14):\n    # Not TypeIs because it does not return True for all modules\n    def ispackage(object: object) -> TypeGuard[ModuleType]: ...\n\ndef isfunction(object: object) -> TypeIs[FunctionType]: ...\n\nif sys.version_info >= (3, 12):\n    def markcoroutinefunction(func: _F) -> _F: ...\n\n@overload\ndef isgeneratorfunction(obj: Callable[..., Generator[Any, Any, Any]]) -> bool: ...\n@overload\ndef isgeneratorfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, GeneratorType[Any, Any, Any]]]: ...\n@overload\ndef isgeneratorfunction(obj: object) -> TypeGuard[Callable[..., GeneratorType[Any, Any, Any]]]: ...\n@overload\ndef iscoroutinefunction(obj: Callable[..., Coroutine[Any, Any, Any]]) -> bool: ...\n@overload\ndef iscoroutinefunction(obj: Callable[_P, Awaitable[_T]]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, _T]]]: ...\n@overload\ndef iscoroutinefunction(obj: Callable[_P, object]) -> TypeGuard[Callable[_P, CoroutineType[Any, Any, Any]]]: ...\n@overload\ndef iscoroutinefunction(obj: object) -> TypeGuard[Callable[..., CoroutineType[Any, Any, Any]]]: ...\ndef isgenerator(object: object) -> TypeIs[GeneratorType[Any, Any, Any]]: ...\ndef iscoroutine(object: object) -> TypeIs[CoroutineType[Any, Any, Any]]: ...\ndef isawaitable(object: object) -> TypeIs[Awaitable[Any]]: ...\n@overload\ndef isasyncgenfunction(obj: Callable[..., AsyncGenerator[Any, Any]]) -> bool: ...\n@overload\ndef isasyncgenfunction(obj: Callable[_P, Any]) -> TypeGuard[Callable[_P, AsyncGeneratorType[Any, Any]]]: ...\n@overload\ndef isasyncgenfunction(obj: object) -> TypeGuard[Callable[..., AsyncGeneratorType[Any, Any]]]: ...\n@type_check_only\nclass _SupportsSet(Protocol[_T_contra, _V_contra]):\n    def __set__(self, instance: _T_contra, value: _V_contra, /) -> None: ...\n\n@type_check_only\nclass _SupportsDelete(Protocol[_T_contra]):\n    def __delete__(self, instance: _T_contra, /) -> None: ...\n\ndef isasyncgen(object: object) -> TypeIs[AsyncGeneratorType[Any, Any]]: ...\ndef istraceback(object: object) -> TypeIs[TracebackType]: ...\ndef isframe(object: object) -> TypeIs[FrameType]: ...\ndef iscode(object: object) -> TypeIs[CodeType]: ...\ndef isbuiltin(object: object) -> TypeIs[BuiltinFunctionType]: ...\n\nif sys.version_info >= (3, 11):\n    def ismethodwrapper(object: object) -> TypeIs[MethodWrapperType]: ...\n\ndef isroutine(\n    object: object,\n) -> TypeIs[\n    FunctionType\n    | LambdaType\n    | MethodType\n    | BuiltinFunctionType\n    | BuiltinMethodType\n    | WrapperDescriptorType\n    | MethodDescriptorType\n    | ClassMethodDescriptorType\n]: ...\ndef ismethoddescriptor(object: object) -> TypeIs[MethodDescriptorType]: ...\ndef ismemberdescriptor(object: object) -> TypeIs[MemberDescriptorType]: ...\ndef isabstract(object: object) -> bool: ...\ndef isgetsetdescriptor(object: object) -> TypeIs[GetSetDescriptorType]: ...\ndef isdatadescriptor(object: object) -> TypeIs[_SupportsSet[Any, Any] | _SupportsDelete[Any]]: ...\n\n#\n# Retrieving source code\n#\n_SourceObjectType: TypeAlias = (\n    ModuleType | type[Any] | MethodType | FunctionType | TracebackType | FrameType | CodeType | Callable[..., Any]\n)\n\ndef findsource(object: _SourceObjectType) -> tuple[list[str], int]: ...\ndef getabsfile(object: _SourceObjectType, _filename: str | None = None) -> str: ...\n\n# Special-case the two most common input types here\n# to avoid the annoyingly vague `Sequence[str]` return type\n@overload\ndef getblock(lines: list[str]) -> list[str]: ...\n@overload\ndef getblock(lines: tuple[str, ...]) -> tuple[str, ...]: ...\n@overload\ndef getblock(lines: Sequence[str]) -> Sequence[str]: ...\ndef getdoc(object: object) -> str | None: ...\ndef getcomments(object: object) -> str | None: ...\ndef getfile(object: _SourceObjectType) -> str: ...\ndef getmodule(object: object, _filename: str | None = None) -> ModuleType | None: ...\ndef getsourcefile(object: _SourceObjectType) -> str | None: ...\ndef getsourcelines(object: _SourceObjectType) -> tuple[list[str], int]: ...\ndef getsource(object: _SourceObjectType) -> str: ...\ndef cleandoc(doc: str) -> str: ...\ndef indentsize(line: str) -> int: ...\n\n_IntrospectableCallable: TypeAlias = Callable[..., Any]\n\n#\n# Introspecting callables with the Signature object\n#\nif sys.version_info >= (3, 14):\n    def signature(\n        obj: _IntrospectableCallable,\n        *,\n        follow_wrapped: bool = True,\n        globals: Mapping[str, Any] | None = None,\n        locals: Mapping[str, Any] | None = None,\n        eval_str: bool = False,\n        annotation_format: Format = Format.VALUE,  # noqa: Y011\n    ) -> Signature: ...\n\nelif sys.version_info >= (3, 10):\n    def signature(\n        obj: _IntrospectableCallable,\n        *,\n        follow_wrapped: bool = True,\n        globals: Mapping[str, Any] | None = None,\n        locals: Mapping[str, Any] | None = None,\n        eval_str: bool = False,\n    ) -> Signature: ...\n\nelse:\n    def signature(obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Signature: ...\n\nclass _void: ...\nclass _empty: ...\n\nclass Signature:\n    __slots__ = (\"_return_annotation\", \"_parameters\")\n    def __init__(\n        self, parameters: Sequence[Parameter] | None = None, *, return_annotation: Any = ..., __validate_parameters__: bool = True\n    ) -> None: ...\n    empty = _empty\n    @property\n    def parameters(self) -> types.MappingProxyType[str, Parameter]: ...\n    @property\n    def return_annotation(self) -> Any: ...\n    def bind(self, *args: Any, **kwargs: Any) -> BoundArguments: ...\n    def bind_partial(self, *args: Any, **kwargs: Any) -> BoundArguments: ...\n    def replace(self, *, parameters: Sequence[Parameter] | type[_void] | None = ..., return_annotation: Any = ...) -> Self: ...\n    __replace__ = replace\n    if sys.version_info >= (3, 14):\n        @classmethod\n        def from_callable(\n            cls,\n            obj: _IntrospectableCallable,\n            *,\n            follow_wrapped: bool = True,\n            globals: Mapping[str, Any] | None = None,\n            locals: Mapping[str, Any] | None = None,\n            eval_str: bool = False,\n            annotation_format: Format = Format.VALUE,  # noqa: Y011\n        ) -> Self: ...\n    elif sys.version_info >= (3, 10):\n        @classmethod\n        def from_callable(\n            cls,\n            obj: _IntrospectableCallable,\n            *,\n            follow_wrapped: bool = True,\n            globals: Mapping[str, Any] | None = None,\n            locals: Mapping[str, Any] | None = None,\n            eval_str: bool = False,\n        ) -> Self: ...\n    else:\n        @classmethod\n        def from_callable(cls, obj: _IntrospectableCallable, *, follow_wrapped: bool = True) -> Self: ...\n    if sys.version_info >= (3, 14):\n        def format(self, *, max_width: int | None = None, quote_annotation_strings: bool = True) -> str: ...\n    elif sys.version_info >= (3, 13):\n        def format(self, *, max_width: int | None = None) -> str: ...\n\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n\nif sys.version_info >= (3, 14):\n    from annotationlib import get_annotations as get_annotations\nelif sys.version_info >= (3, 10):\n    def get_annotations(\n        obj: Callable[..., object] | type[object] | ModuleType,  # any callable, class, or module\n        *,\n        globals: Mapping[str, Any] | None = None,  # value types depend on the key\n        locals: Mapping[str, Any] | None = None,  # value types depend on the key\n        eval_str: bool = False,\n    ) -> dict[str, AnnotationForm]: ...  # values are type expressions\n\n# The name is the same as the enum's name in CPython\nclass _ParameterKind(enum.IntEnum):\n    POSITIONAL_ONLY = 0\n    POSITIONAL_OR_KEYWORD = 1\n    VAR_POSITIONAL = 2\n    KEYWORD_ONLY = 3\n    VAR_KEYWORD = 4\n\n    @property\n    def description(self) -> str: ...\n\nif sys.version_info >= (3, 12):\n    AGEN_CREATED: Final = \"AGEN_CREATED\"\n    AGEN_RUNNING: Final = \"AGEN_RUNNING\"\n    AGEN_SUSPENDED: Final = \"AGEN_SUSPENDED\"\n    AGEN_CLOSED: Final = \"AGEN_CLOSED\"\n\n    def getasyncgenstate(\n        agen: AsyncGenerator[Any, Any],\n    ) -> Literal[\"AGEN_CREATED\", \"AGEN_RUNNING\", \"AGEN_SUSPENDED\", \"AGEN_CLOSED\"]: ...\n    def getasyncgenlocals(agen: AsyncGeneratorType[Any, Any]) -> dict[str, Any]: ...\n\nclass Parameter:\n    __slots__ = (\"_name\", \"_kind\", \"_default\", \"_annotation\")\n    def __init__(self, name: str, kind: _ParameterKind, *, default: Any = ..., annotation: Any = ...) -> None: ...\n    empty = _empty\n\n    POSITIONAL_ONLY: ClassVar[Literal[_ParameterKind.POSITIONAL_ONLY]]\n    POSITIONAL_OR_KEYWORD: ClassVar[Literal[_ParameterKind.POSITIONAL_OR_KEYWORD]]\n    VAR_POSITIONAL: ClassVar[Literal[_ParameterKind.VAR_POSITIONAL]]\n    KEYWORD_ONLY: ClassVar[Literal[_ParameterKind.KEYWORD_ONLY]]\n    VAR_KEYWORD: ClassVar[Literal[_ParameterKind.VAR_KEYWORD]]\n    @property\n    def name(self) -> str: ...\n    @property\n    def default(self) -> Any: ...\n    @property\n    def kind(self) -> _ParameterKind: ...\n    @property\n    def annotation(self) -> Any: ...\n    def replace(\n        self,\n        *,\n        name: str | type[_void] = ...,\n        kind: _ParameterKind | type[_void] = ...,\n        default: Any = ...,\n        annotation: Any = ...,\n    ) -> Self: ...\n    if sys.version_info >= (3, 13):\n        __replace__ = replace\n\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n\nclass BoundArguments:\n    __slots__ = (\"arguments\", \"_signature\", \"__weakref__\")\n    arguments: OrderedDict[str, Any]\n    @property\n    def args(self) -> tuple[Any, ...]: ...\n    @property\n    def kwargs(self) -> dict[str, Any]: ...\n    @property\n    def signature(self) -> Signature: ...\n    def __init__(self, signature: Signature, arguments: OrderedDict[str, Any]) -> None: ...\n    def apply_defaults(self) -> None: ...\n    def __eq__(self, other: object) -> bool: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\n#\n# Classes and functions\n#\n\n_ClassTreeItem: TypeAlias = list[tuple[type, ...]] | list[_ClassTreeItem]\n\ndef getclasstree(classes: list[type], unique: bool = False) -> _ClassTreeItem: ...\ndef walktree(classes: list[type], children: Mapping[type[Any], list[type]], parent: type[Any] | None) -> _ClassTreeItem: ...\n\nclass Arguments(NamedTuple):\n    args: list[str]\n    varargs: str | None\n    varkw: str | None\n\ndef getargs(co: CodeType) -> Arguments: ...\n\nif sys.version_info < (3, 11):\n    @deprecated(\"Deprecated since Python 3.0; removed in Python 3.11.\")\n    class ArgSpec(NamedTuple):\n        args: list[str]\n        varargs: str | None\n        keywords: str | None\n        defaults: tuple[Any, ...]\n\n    @deprecated(\"Deprecated since Python 3.0; removed in Python 3.11. Use `inspect.signature()` instead.\")\n    def getargspec(func: object) -> ArgSpec: ...\n\nclass FullArgSpec(NamedTuple):\n    args: list[str]\n    varargs: str | None\n    varkw: str | None\n    defaults: tuple[Any, ...] | None\n    kwonlyargs: list[str]\n    kwonlydefaults: dict[str, Any] | None\n    annotations: dict[str, Any]\n\ndef getfullargspec(func: object) -> FullArgSpec: ...\n\nclass ArgInfo(NamedTuple):\n    args: list[str]\n    varargs: str | None\n    keywords: str | None\n    locals: dict[str, Any]\n\ndef getargvalues(frame: FrameType) -> ArgInfo: ...\n\nif sys.version_info >= (3, 14):\n    def formatannotation(annotation: object, base_module: str | None = None, *, quote_annotation_strings: bool = True) -> str: ...\n\nelse:\n    def formatannotation(annotation: object, base_module: str | None = None) -> str: ...\n\ndef formatannotationrelativeto(object: object) -> Callable[[object], str]: ...\n\nif sys.version_info < (3, 11):\n    @deprecated(\n        \"Deprecated since Python 3.5; removed in Python 3.11. Use `inspect.signature()` and the `Signature` class instead.\"\n    )\n    def formatargspec(\n        args: list[str],\n        varargs: str | None = None,\n        varkw: str | None = None,\n        defaults: tuple[Any, ...] | None = None,\n        kwonlyargs: Sequence[str] | None = (),\n        kwonlydefaults: Mapping[str, Any] | None = {},\n        annotations: Mapping[str, Any] = {},\n        formatarg: Callable[[str], str] = ...,\n        formatvarargs: Callable[[str], str] = ...,\n        formatvarkw: Callable[[str], str] = ...,\n        formatvalue: Callable[[Any], str] = ...,\n        formatreturns: Callable[[Any], str] = ...,\n        formatannotation: Callable[[Any], str] = ...,\n    ) -> str: ...\n\ndef formatargvalues(\n    args: list[str],\n    varargs: str | None,\n    varkw: str | None,\n    locals: Mapping[str, Any] | None,\n    formatarg: Callable[[str], str] | None = ...,\n    formatvarargs: Callable[[str], str] | None = ...,\n    formatvarkw: Callable[[str], str] | None = ...,\n    formatvalue: Callable[[Any], str] | None = ...,\n) -> str: ...\ndef getmro(cls: type) -> tuple[type, ...]: ...\n@deprecated(\"Deprecated since Python 3.5. Use `Signature.bind` and `Signature.bind_partial` instead.\")\ndef getcallargs(func: Callable[_P, Any], /, *args: _P.args, **kwds: _P.kwargs) -> dict[str, Any]: ...\n\nclass ClosureVars(NamedTuple):\n    nonlocals: Mapping[str, Any]\n    globals: Mapping[str, Any]\n    builtins: Mapping[str, Any]\n    unbound: AbstractSet[str]\n\ndef getclosurevars(func: _IntrospectableCallable) -> ClosureVars: ...\ndef unwrap(func: Callable[..., Any], *, stop: Callable[[Callable[..., Any]], Any] | None = None) -> Any: ...\n\n#\n# The interpreter stack\n#\n\nif sys.version_info >= (3, 11):\n    class _Traceback(NamedTuple):\n        filename: str\n        lineno: int\n        function: str\n        code_context: list[str] | None\n        index: int | None  # type: ignore[assignment]\n\n    class _FrameInfo(NamedTuple):\n        frame: FrameType\n        filename: str\n        lineno: int\n        function: str\n        code_context: list[str] | None\n        index: int | None  # type: ignore[assignment]\n\n    if sys.version_info >= (3, 12):\n        class Traceback(_Traceback):\n            positions: dis.Positions | None\n            def __new__(\n                cls,\n                filename: str,\n                lineno: int,\n                function: str,\n                code_context: list[str] | None,\n                index: int | None,\n                *,\n                positions: dis.Positions | None = None,\n            ) -> Self: ...\n\n        class FrameInfo(_FrameInfo):\n            positions: dis.Positions | None\n            def __new__(\n                cls,\n                frame: FrameType,\n                filename: str,\n                lineno: int,\n                function: str,\n                code_context: list[str] | None,\n                index: int | None,\n                *,\n                positions: dis.Positions | None = None,\n            ) -> Self: ...\n\n    else:\n        @disjoint_base\n        class Traceback(_Traceback):\n            positions: dis.Positions | None\n            def __new__(\n                cls,\n                filename: str,\n                lineno: int,\n                function: str,\n                code_context: list[str] | None,\n                index: int | None,\n                *,\n                positions: dis.Positions | None = None,\n            ) -> Self: ...\n\n        @disjoint_base\n        class FrameInfo(_FrameInfo):\n            positions: dis.Positions | None\n            def __new__(\n                cls,\n                frame: FrameType,\n                filename: str,\n                lineno: int,\n                function: str,\n                code_context: list[str] | None,\n                index: int | None,\n                *,\n                positions: dis.Positions | None = None,\n            ) -> Self: ...\n\nelse:\n    class Traceback(NamedTuple):\n        filename: str\n        lineno: int\n        function: str\n        code_context: list[str] | None\n        index: int | None  # type: ignore[assignment]\n\n    class FrameInfo(NamedTuple):\n        frame: FrameType\n        filename: str\n        lineno: int\n        function: str\n        code_context: list[str] | None\n        index: int | None  # type: ignore[assignment]\n\ndef getframeinfo(frame: FrameType | TracebackType, context: int = 1) -> Traceback: ...\ndef getouterframes(frame: Any, context: int = 1) -> list[FrameInfo]: ...\ndef getinnerframes(tb: TracebackType, context: int = 1) -> list[FrameInfo]: ...\ndef getlineno(frame: FrameType) -> int: ...\ndef currentframe() -> FrameType | None: ...\ndef stack(context: int = 1) -> list[FrameInfo]: ...\ndef trace(context: int = 1) -> list[FrameInfo]: ...\n\n#\n# Fetching attributes statically\n#\n\ndef getattr_static(obj: object, attr: str, default: Any | None = ...) -> Any: ...\n\n#\n# Current State of Generators and Coroutines\n#\n\nGEN_CREATED: Final = \"GEN_CREATED\"\nGEN_RUNNING: Final = \"GEN_RUNNING\"\nGEN_SUSPENDED: Final = \"GEN_SUSPENDED\"\nGEN_CLOSED: Final = \"GEN_CLOSED\"\n\ndef getgeneratorstate(\n    generator: Generator[Any, Any, Any],\n) -> Literal[\"GEN_CREATED\", \"GEN_RUNNING\", \"GEN_SUSPENDED\", \"GEN_CLOSED\"]: ...\n\nCORO_CREATED: Final = \"CORO_CREATED\"\nCORO_RUNNING: Final = \"CORO_RUNNING\"\nCORO_SUSPENDED: Final = \"CORO_SUSPENDED\"\nCORO_CLOSED: Final = \"CORO_CLOSED\"\n\ndef getcoroutinestate(\n    coroutine: Coroutine[Any, Any, Any],\n) -> Literal[\"CORO_CREATED\", \"CORO_RUNNING\", \"CORO_SUSPENDED\", \"CORO_CLOSED\"]: ...\ndef getgeneratorlocals(generator: Generator[Any, Any, Any]) -> dict[str, Any]: ...\ndef getcoroutinelocals(coroutine: Coroutine[Any, Any, Any]) -> dict[str, Any]: ...\n\n# Create private type alias to avoid conflict with symbol of same\n# name created in Attribute class.\n_Object: TypeAlias = object\n\nclass Attribute(NamedTuple):\n    name: str\n    kind: Literal[\"class method\", \"static method\", \"property\", \"method\", \"data\"]\n    defining_class: type\n    object: _Object\n\ndef classify_class_attrs(cls: type) -> list[Attribute]: ...\n\nclass ClassFoundException(Exception): ...\n\nif sys.version_info >= (3, 12):\n    class BufferFlags(enum.IntFlag):\n        SIMPLE = 0\n        WRITABLE = 1\n        FORMAT = 4\n        ND = 8\n        STRIDES = 24\n        C_CONTIGUOUS = 56\n        F_CONTIGUOUS = 88\n        ANY_CONTIGUOUS = 152\n        INDIRECT = 280\n        CONTIG = 9\n        CONTIG_RO = 8\n        STRIDED = 25\n        STRIDED_RO = 24\n        RECORDS = 29\n        RECORDS_RO = 28\n        FULL = 285\n        FULL_RO = 284\n        READ = 256\n        WRITE = 512\n"
  },
  {
    "path": "mypy/typeshed/stdlib/io.pyi",
    "content": "import abc\nimport sys\nfrom _io import (\n    DEFAULT_BUFFER_SIZE as DEFAULT_BUFFER_SIZE,\n    BlockingIOError as BlockingIOError,\n    BufferedRandom as BufferedRandom,\n    BufferedReader as BufferedReader,\n    BufferedRWPair as BufferedRWPair,\n    BufferedWriter as BufferedWriter,\n    BytesIO as BytesIO,\n    FileIO as FileIO,\n    IncrementalNewlineDecoder as IncrementalNewlineDecoder,\n    StringIO as StringIO,\n    TextIOWrapper as TextIOWrapper,\n    _BufferedIOBase,\n    _IOBase,\n    _RawIOBase,\n    _TextIOBase,\n    _WrappedBuffer as _WrappedBuffer,  # used elsewhere in typeshed\n    open as open,\n    open_code as open_code,\n)\nfrom typing import Final, Protocol, TypeVar\n\n__all__ = [\n    \"BlockingIOError\",\n    \"open\",\n    \"open_code\",\n    \"IOBase\",\n    \"RawIOBase\",\n    \"FileIO\",\n    \"BytesIO\",\n    \"StringIO\",\n    \"BufferedIOBase\",\n    \"BufferedReader\",\n    \"BufferedWriter\",\n    \"BufferedRWPair\",\n    \"BufferedRandom\",\n    \"TextIOBase\",\n    \"TextIOWrapper\",\n    \"UnsupportedOperation\",\n    \"SEEK_SET\",\n    \"SEEK_CUR\",\n    \"SEEK_END\",\n]\n\nif sys.version_info >= (3, 14):\n    __all__ += [\"Reader\", \"Writer\"]\n\nif sys.version_info >= (3, 11):\n    from _io import text_encoding as text_encoding\n\n    __all__ += [\"DEFAULT_BUFFER_SIZE\", \"IncrementalNewlineDecoder\", \"text_encoding\"]\n\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_T_contra = TypeVar(\"_T_contra\", contravariant=True)\n\nSEEK_SET: Final = 0\nSEEK_CUR: Final = 1\nSEEK_END: Final = 2\n\nclass UnsupportedOperation(OSError, ValueError): ...\nclass IOBase(_IOBase, metaclass=abc.ABCMeta): ...\nclass RawIOBase(_RawIOBase, IOBase): ...\nclass BufferedIOBase(_BufferedIOBase, IOBase): ...\nclass TextIOBase(_TextIOBase, IOBase): ...\n\nif sys.version_info >= (3, 14):\n    class Reader(Protocol[_T_co]):\n        __slots__ = ()\n        def read(self, size: int = ..., /) -> _T_co: ...\n\n    class Writer(Protocol[_T_contra]):\n        __slots__ = ()\n        def write(self, data: _T_contra, /) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ipaddress.pyi",
    "content": "import sys\nfrom collections.abc import Iterable, Iterator\nfrom typing import Any, Final, Generic, Literal, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias\n\n# Undocumented length constants\nIPV4LENGTH: Final = 32\nIPV6LENGTH: Final = 128\n\n_A = TypeVar(\"_A\", IPv4Address, IPv6Address)\n_N = TypeVar(\"_N\", IPv4Network, IPv6Network)\n\n_RawIPAddress: TypeAlias = int | str | bytes | IPv4Address | IPv6Address\n_RawNetworkPart: TypeAlias = IPv4Network | IPv6Network | IPv4Interface | IPv6Interface\n\ndef ip_address(address: _RawIPAddress) -> IPv4Address | IPv6Address: ...\ndef ip_network(\n    address: _RawIPAddress | _RawNetworkPart | tuple[_RawIPAddress] | tuple[_RawIPAddress, int], strict: bool = True\n) -> IPv4Network | IPv6Network: ...\ndef ip_interface(\n    address: _RawIPAddress | _RawNetworkPart | tuple[_RawIPAddress] | tuple[_RawIPAddress, int],\n) -> IPv4Interface | IPv6Interface: ...\n\nclass _IPAddressBase:\n    __slots__ = ()\n    @property\n    def compressed(self) -> str: ...\n    @property\n    def exploded(self) -> str: ...\n    @property\n    def reverse_pointer(self) -> str: ...\n    if sys.version_info < (3, 14):\n        @property\n        def version(self) -> int: ...\n\nclass _BaseAddress(_IPAddressBase):\n    __slots__ = ()\n    def __add__(self, other: int) -> Self: ...\n    def __hash__(self) -> int: ...\n    def __int__(self) -> int: ...\n    def __sub__(self, other: int) -> Self: ...\n    def __format__(self, fmt: str) -> str: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __lt__(self, other: Self) -> bool: ...\n    if sys.version_info >= (3, 11):\n        def __ge__(self, other: Self) -> bool: ...\n        def __gt__(self, other: Self) -> bool: ...\n        def __le__(self, other: Self) -> bool: ...\n    else:\n        def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool: ...\n        def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool: ...\n        def __le__(self, other: Self, NotImplemented: Any = ...) -> bool: ...\n\nclass _BaseNetwork(_IPAddressBase, Generic[_A]):\n    network_address: _A\n    netmask: _A\n    def __contains__(self, other: Any) -> bool: ...\n    def __getitem__(self, n: int) -> _A: ...\n    def __iter__(self) -> Iterator[_A]: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __lt__(self, other: Self) -> bool: ...\n    if sys.version_info >= (3, 11):\n        def __ge__(self, other: Self) -> bool: ...\n        def __gt__(self, other: Self) -> bool: ...\n        def __le__(self, other: Self) -> bool: ...\n    else:\n        def __ge__(self, other: Self, NotImplemented: Any = ...) -> bool: ...\n        def __gt__(self, other: Self, NotImplemented: Any = ...) -> bool: ...\n        def __le__(self, other: Self, NotImplemented: Any = ...) -> bool: ...\n\n    def address_exclude(self, other: Self) -> Iterator[Self]: ...\n    @property\n    def broadcast_address(self) -> _A: ...\n    def compare_networks(self, other: Self) -> int: ...\n    def hosts(self) -> Iterator[_A]: ...\n    @property\n    def is_global(self) -> bool: ...\n    @property\n    def is_link_local(self) -> bool: ...\n    @property\n    def is_loopback(self) -> bool: ...\n    @property\n    def is_multicast(self) -> bool: ...\n    @property\n    def is_private(self) -> bool: ...\n    @property\n    def is_reserved(self) -> bool: ...\n    @property\n    def is_unspecified(self) -> bool: ...\n    @property\n    def num_addresses(self) -> int: ...\n    def overlaps(self, other: _BaseNetwork[IPv4Address] | _BaseNetwork[IPv6Address]) -> bool: ...\n    @property\n    def prefixlen(self) -> int: ...\n    def subnet_of(self, other: Self) -> bool: ...\n    def supernet_of(self, other: Self) -> bool: ...\n    def subnets(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> Iterator[Self]: ...\n    def supernet(self, prefixlen_diff: int = 1, new_prefix: int | None = None) -> Self: ...\n    @property\n    def with_hostmask(self) -> str: ...\n    @property\n    def with_netmask(self) -> str: ...\n    @property\n    def with_prefixlen(self) -> str: ...\n    @property\n    def hostmask(self) -> _A: ...\n\nclass _BaseV4:\n    __slots__ = ()\n    if sys.version_info >= (3, 14):\n        version: Final = 4\n        max_prefixlen: Final = 32\n    else:\n        @property\n        def version(self) -> Literal[4]: ...\n        @property\n        def max_prefixlen(self) -> Literal[32]: ...\n\nclass IPv4Address(_BaseV4, _BaseAddress):\n    __slots__ = (\"_ip\", \"__weakref__\")\n    def __init__(self, address: object) -> None: ...\n    @property\n    def is_global(self) -> bool: ...\n    @property\n    def is_link_local(self) -> bool: ...\n    @property\n    def is_loopback(self) -> bool: ...\n    @property\n    def is_multicast(self) -> bool: ...\n    @property\n    def is_private(self) -> bool: ...\n    @property\n    def is_reserved(self) -> bool: ...\n    @property\n    def is_unspecified(self) -> bool: ...\n    @property\n    def packed(self) -> bytes: ...\n    if sys.version_info >= (3, 13):\n        @property\n        def ipv6_mapped(self) -> IPv6Address: ...\n\nclass IPv4Network(_BaseV4, _BaseNetwork[IPv4Address]):\n    def __init__(self, address: object, strict: bool = True) -> None: ...\n\nclass IPv4Interface(IPv4Address):\n    netmask: IPv4Address\n    network: IPv4Network\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n    @property\n    def hostmask(self) -> IPv4Address: ...\n    @property\n    def ip(self) -> IPv4Address: ...\n    @property\n    def with_hostmask(self) -> str: ...\n    @property\n    def with_netmask(self) -> str: ...\n    @property\n    def with_prefixlen(self) -> str: ...\n\nclass _BaseV6:\n    __slots__ = ()\n    if sys.version_info >= (3, 14):\n        version: Final = 6\n        max_prefixlen: Final = 128\n    else:\n        @property\n        def version(self) -> Literal[6]: ...\n        @property\n        def max_prefixlen(self) -> Literal[128]: ...\n\nclass IPv6Address(_BaseV6, _BaseAddress):\n    __slots__ = (\"_ip\", \"_scope_id\", \"__weakref__\")\n    def __init__(self, address: object) -> None: ...\n    @property\n    def is_global(self) -> bool: ...\n    @property\n    def is_link_local(self) -> bool: ...\n    @property\n    def is_loopback(self) -> bool: ...\n    @property\n    def is_multicast(self) -> bool: ...\n    @property\n    def is_private(self) -> bool: ...\n    @property\n    def is_reserved(self) -> bool: ...\n    @property\n    def is_unspecified(self) -> bool: ...\n    @property\n    def packed(self) -> bytes: ...\n    @property\n    def ipv4_mapped(self) -> IPv4Address | None: ...\n    @property\n    def is_site_local(self) -> bool: ...\n    @property\n    def sixtofour(self) -> IPv4Address | None: ...\n    @property\n    def teredo(self) -> tuple[IPv4Address, IPv4Address] | None: ...\n    @property\n    def scope_id(self) -> str | None: ...\n    def __hash__(self) -> int: ...\n    def __eq__(self, other: object) -> bool: ...\n\nclass IPv6Network(_BaseV6, _BaseNetwork[IPv6Address]):\n    def __init__(self, address: object, strict: bool = True) -> None: ...\n    @property\n    def is_site_local(self) -> bool: ...\n\nclass IPv6Interface(IPv6Address):\n    netmask: IPv6Address\n    network: IPv6Network\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n    @property\n    def hostmask(self) -> IPv6Address: ...\n    @property\n    def ip(self) -> IPv6Address: ...\n    @property\n    def with_hostmask(self) -> str: ...\n    @property\n    def with_netmask(self) -> str: ...\n    @property\n    def with_prefixlen(self) -> str: ...\n\ndef v4_int_to_packed(address: int) -> bytes: ...\ndef v6_int_to_packed(address: int) -> bytes: ...\n\n# Third overload is technically incorrect, but convenient when first and last are return values of ip_address()\n@overload\ndef summarize_address_range(first: IPv4Address, last: IPv4Address) -> Iterator[IPv4Network]: ...\n@overload\ndef summarize_address_range(first: IPv6Address, last: IPv6Address) -> Iterator[IPv6Network]: ...\n@overload\ndef summarize_address_range(\n    first: IPv4Address | IPv6Address, last: IPv4Address | IPv6Address\n) -> Iterator[IPv4Network] | Iterator[IPv6Network]: ...\ndef collapse_addresses(addresses: Iterable[_N]) -> Iterator[_N]: ...\n@overload\ndef get_mixed_type_key(obj: _A) -> tuple[int, _A]: ...\n@overload\ndef get_mixed_type_key(obj: IPv4Network) -> tuple[int, IPv4Address, IPv4Address]: ...\n@overload\ndef get_mixed_type_key(obj: IPv6Network) -> tuple[int, IPv6Address, IPv6Address]: ...\n\nclass AddressValueError(ValueError): ...\nclass NetmaskValueError(ValueError): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/itertools.pyi",
    "content": "import sys\nfrom _typeshed import MaybeNone\nfrom collections.abc import Callable, Iterable, Iterator\nfrom types import GenericAlias\nfrom typing import Any, Generic, Literal, SupportsComplex, SupportsFloat, SupportsIndex, SupportsInt, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias, disjoint_base\n\n_T = TypeVar(\"_T\")\n_S = TypeVar(\"_S\")\n_N = TypeVar(\"_N\", int, float, SupportsFloat, SupportsInt, SupportsIndex, SupportsComplex)\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_S_co = TypeVar(\"_S_co\", covariant=True)\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n_T3 = TypeVar(\"_T3\")\n_T4 = TypeVar(\"_T4\")\n_T5 = TypeVar(\"_T5\")\n_T6 = TypeVar(\"_T6\")\n_T7 = TypeVar(\"_T7\")\n_T8 = TypeVar(\"_T8\")\n_T9 = TypeVar(\"_T9\")\n_T10 = TypeVar(\"_T10\")\n\n_Step: TypeAlias = SupportsFloat | SupportsInt | SupportsIndex | SupportsComplex\n\n_Predicate: TypeAlias = Callable[[_T], object]\n\n# Technically count can take anything that implements a number protocol and has an add method\n# but we can't enforce the add method\n@disjoint_base\nclass count(Iterator[_N]):\n    @overload\n    def __new__(cls) -> count[int]: ...\n    @overload\n    def __new__(cls, start: _N, step: _Step = 1) -> count[_N]: ...\n    @overload\n    def __new__(cls, *, step: _N) -> count[_N]: ...\n    def __next__(self) -> _N: ...\n    def __iter__(self) -> Self: ...\n\n@disjoint_base\nclass cycle(Iterator[_T]):\n    def __new__(cls, iterable: Iterable[_T], /) -> Self: ...\n    def __next__(self) -> _T: ...\n    def __iter__(self) -> Self: ...\n\n@disjoint_base\nclass repeat(Iterator[_T]):\n    @overload\n    def __new__(cls, object: _T) -> Self: ...\n    @overload\n    def __new__(cls, object: _T, times: int) -> Self: ...\n    def __next__(self) -> _T: ...\n    def __iter__(self) -> Self: ...\n    def __length_hint__(self) -> int: ...\n\n@disjoint_base\nclass accumulate(Iterator[_T]):\n    @overload\n    def __new__(cls, iterable: Iterable[_T], func: None = None, *, initial: _T | None = None) -> Self: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_S], func: Callable[[_T, _S], _T], *, initial: _T | None = None) -> Self: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T: ...\n\n@disjoint_base\nclass chain(Iterator[_T]):\n    def __new__(cls, *iterables: Iterable[_T]) -> Self: ...\n    def __next__(self) -> _T: ...\n    def __iter__(self) -> Self: ...\n    @classmethod\n    # We use type[Any] and not type[_S] to not lose the type inference from __iterable\n    def from_iterable(cls: type[Any], iterable: Iterable[Iterable[_S]], /) -> chain[_S]: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@disjoint_base\nclass compress(Iterator[_T]):\n    def __new__(cls, data: Iterable[_T], selectors: Iterable[Any]) -> Self: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T: ...\n\n@disjoint_base\nclass dropwhile(Iterator[_T]):\n    def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T: ...\n\n@disjoint_base\nclass filterfalse(Iterator[_T]):\n    def __new__(cls, function: _Predicate[_T] | None, iterable: Iterable[_T], /) -> Self: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T: ...\n\n@disjoint_base\nclass groupby(Iterator[tuple[_T_co, Iterator[_S_co]]], Generic[_T_co, _S_co]):\n    @overload\n    def __new__(cls, iterable: Iterable[_T1], key: None = None) -> groupby[_T1, _T1]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T1], key: Callable[[_T1], _T2]) -> groupby[_T2, _T1]: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> tuple[_T_co, Iterator[_S_co]]: ...\n\n@disjoint_base\nclass islice(Iterator[_T]):\n    @overload\n    def __new__(cls, iterable: Iterable[_T], stop: int | None, /) -> Self: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], start: int | None, stop: int | None, step: int | None = 1, /) -> Self: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T: ...\n\n@disjoint_base\nclass starmap(Iterator[_T_co]):\n    def __new__(cls, function: Callable[..., _T], iterable: Iterable[Iterable[Any]], /) -> starmap[_T]: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T_co: ...\n\n@disjoint_base\nclass takewhile(Iterator[_T]):\n    def __new__(cls, predicate: _Predicate[_T], iterable: Iterable[_T], /) -> Self: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T: ...\n\ndef tee(iterable: Iterable[_T], n: int = 2, /) -> tuple[Iterator[_T], ...]: ...\n@disjoint_base\nclass zip_longest(Iterator[_T_co]):\n    # one iterable (fillvalue doesn't matter)\n    @overload\n    def __new__(cls, iter1: Iterable[_T1], /, *, fillvalue: object = None) -> zip_longest[tuple[_T1]]: ...\n    # two iterables\n    @overload\n    # In the overloads without fillvalue, all of the tuple members could theoretically be None,\n    # but we return Any instead to avoid false positives for code where we know one of the iterables\n    # is longer.\n    def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone]]: ...\n    @overload\n    def __new__(\n        cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /, *, fillvalue: _T\n    ) -> zip_longest[tuple[_T1 | _T, _T2 | _T]]: ...\n    # three iterables\n    @overload\n    def __new__(\n        cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /\n    ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone]]: ...\n    @overload\n    def __new__(\n        cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /, *, fillvalue: _T\n    ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T]]: ...\n    # four iterables\n    @overload\n    def __new__(\n        cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /\n    ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone, _T4 | MaybeNone]]: ...\n    @overload\n    def __new__(\n        cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /, *, fillvalue: _T\n    ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T, _T4 | _T]]: ...\n    # five iterables\n    @overload\n    def __new__(\n        cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], /\n    ) -> zip_longest[tuple[_T1 | MaybeNone, _T2 | MaybeNone, _T3 | MaybeNone, _T4 | MaybeNone, _T5 | MaybeNone]]: ...\n    @overload\n    def __new__(\n        cls,\n        iter1: Iterable[_T1],\n        iter2: Iterable[_T2],\n        iter3: Iterable[_T3],\n        iter4: Iterable[_T4],\n        iter5: Iterable[_T5],\n        /,\n        *,\n        fillvalue: _T,\n    ) -> zip_longest[tuple[_T1 | _T, _T2 | _T, _T3 | _T, _T4 | _T, _T5 | _T]]: ...\n    # six or more iterables\n    @overload\n    def __new__(\n        cls,\n        iter1: Iterable[_T],\n        iter2: Iterable[_T],\n        iter3: Iterable[_T],\n        iter4: Iterable[_T],\n        iter5: Iterable[_T],\n        iter6: Iterable[_T],\n        /,\n        *iterables: Iterable[_T],\n    ) -> zip_longest[tuple[_T | MaybeNone, ...]]: ...\n    @overload\n    def __new__(\n        cls,\n        iter1: Iterable[_T],\n        iter2: Iterable[_T],\n        iter3: Iterable[_T],\n        iter4: Iterable[_T],\n        iter5: Iterable[_T],\n        iter6: Iterable[_T],\n        /,\n        *iterables: Iterable[_T],\n        fillvalue: _T,\n    ) -> zip_longest[tuple[_T, ...]]: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T_co: ...\n\n@disjoint_base\nclass product(Iterator[_T_co]):\n    @overload\n    def __new__(cls, iter1: Iterable[_T1], /) -> product[tuple[_T1]]: ...\n    @overload\n    def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], /) -> product[tuple[_T1, _T2]]: ...\n    @overload\n    def __new__(cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], /) -> product[tuple[_T1, _T2, _T3]]: ...\n    @overload\n    def __new__(\n        cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], /\n    ) -> product[tuple[_T1, _T2, _T3, _T4]]: ...\n    @overload\n    def __new__(\n        cls, iter1: Iterable[_T1], iter2: Iterable[_T2], iter3: Iterable[_T3], iter4: Iterable[_T4], iter5: Iterable[_T5], /\n    ) -> product[tuple[_T1, _T2, _T3, _T4, _T5]]: ...\n    @overload\n    def __new__(\n        cls,\n        iter1: Iterable[_T1],\n        iter2: Iterable[_T2],\n        iter3: Iterable[_T3],\n        iter4: Iterable[_T4],\n        iter5: Iterable[_T5],\n        iter6: Iterable[_T6],\n        /,\n    ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6]]: ...\n    @overload\n    def __new__(\n        cls,\n        iter1: Iterable[_T1],\n        iter2: Iterable[_T2],\n        iter3: Iterable[_T3],\n        iter4: Iterable[_T4],\n        iter5: Iterable[_T5],\n        iter6: Iterable[_T6],\n        iter7: Iterable[_T7],\n        /,\n    ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7]]: ...\n    @overload\n    def __new__(\n        cls,\n        iter1: Iterable[_T1],\n        iter2: Iterable[_T2],\n        iter3: Iterable[_T3],\n        iter4: Iterable[_T4],\n        iter5: Iterable[_T5],\n        iter6: Iterable[_T6],\n        iter7: Iterable[_T7],\n        iter8: Iterable[_T8],\n        /,\n    ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8]]: ...\n    @overload\n    def __new__(\n        cls,\n        iter1: Iterable[_T1],\n        iter2: Iterable[_T2],\n        iter3: Iterable[_T3],\n        iter4: Iterable[_T4],\n        iter5: Iterable[_T5],\n        iter6: Iterable[_T6],\n        iter7: Iterable[_T7],\n        iter8: Iterable[_T8],\n        iter9: Iterable[_T9],\n        /,\n    ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9]]: ...\n    @overload\n    def __new__(\n        cls,\n        iter1: Iterable[_T1],\n        iter2: Iterable[_T2],\n        iter3: Iterable[_T3],\n        iter4: Iterable[_T4],\n        iter5: Iterable[_T5],\n        iter6: Iterable[_T6],\n        iter7: Iterable[_T7],\n        iter8: Iterable[_T8],\n        iter9: Iterable[_T9],\n        iter10: Iterable[_T10],\n        /,\n    ) -> product[tuple[_T1, _T2, _T3, _T4, _T5, _T6, _T7, _T8, _T9, _T10]]: ...\n    @overload\n    def __new__(cls, *iterables: Iterable[_T1], repeat: int = 1) -> product[tuple[_T1, ...]]: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T_co: ...\n\n@disjoint_base\nclass permutations(Iterator[_T_co]):\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> permutations[tuple[_T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[3]) -> permutations[tuple[_T, _T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[4]) -> permutations[tuple[_T, _T, _T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> permutations[tuple[_T, _T, _T, _T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: int | None = None) -> permutations[tuple[_T, ...]]: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T_co: ...\n\n@disjoint_base\nclass combinations(Iterator[_T_co]):\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations[tuple[_T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[3]) -> combinations[tuple[_T, _T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[4]) -> combinations[tuple[_T, _T, _T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> combinations[tuple[_T, _T, _T, _T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: int) -> combinations[tuple[_T, ...]]: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T_co: ...\n\n@disjoint_base\nclass combinations_with_replacement(Iterator[_T_co]):\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[2]) -> combinations_with_replacement[tuple[_T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[3]) -> combinations_with_replacement[tuple[_T, _T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[4]) -> combinations_with_replacement[tuple[_T, _T, _T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: Literal[5]) -> combinations_with_replacement[tuple[_T, _T, _T, _T, _T]]: ...\n    @overload\n    def __new__(cls, iterable: Iterable[_T], r: int) -> combinations_with_replacement[tuple[_T, ...]]: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T_co: ...\n\nif sys.version_info >= (3, 10):\n    @disjoint_base\n    class pairwise(Iterator[_T_co]):\n        def __new__(cls, iterable: Iterable[_T], /) -> pairwise[tuple[_T, _T]]: ...\n        def __iter__(self) -> Self: ...\n        def __next__(self) -> _T_co: ...\n\nif sys.version_info >= (3, 12):\n    @disjoint_base\n    class batched(Iterator[_T_co], Generic[_T_co]):\n        if sys.version_info >= (3, 13):\n            @overload\n            def __new__(cls, iterable: Iterable[_T], n: Literal[1], *, strict: Literal[True]) -> batched[tuple[_T]]: ...\n            @overload\n            def __new__(cls, iterable: Iterable[_T], n: Literal[2], *, strict: Literal[True]) -> batched[tuple[_T, _T]]: ...\n            @overload\n            def __new__(cls, iterable: Iterable[_T], n: Literal[3], *, strict: Literal[True]) -> batched[tuple[_T, _T, _T]]: ...\n            @overload\n            def __new__(\n                cls, iterable: Iterable[_T], n: Literal[4], *, strict: Literal[True]\n            ) -> batched[tuple[_T, _T, _T, _T]]: ...\n            @overload\n            def __new__(\n                cls, iterable: Iterable[_T], n: Literal[5], *, strict: Literal[True]\n            ) -> batched[tuple[_T, _T, _T, _T, _T]]: ...\n            @overload\n            def __new__(cls, iterable: Iterable[_T], n: int, *, strict: bool = False) -> batched[tuple[_T, ...]]: ...\n        else:\n            def __new__(cls, iterable: Iterable[_T], n: int) -> batched[tuple[_T, ...]]: ...\n\n        def __iter__(self) -> Self: ...\n        def __next__(self) -> _T_co: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/json/__init__.pyi",
    "content": "from _typeshed import SupportsRead, SupportsWrite\nfrom collections.abc import Callable\nfrom typing import Any\n\nfrom .decoder import JSONDecodeError as JSONDecodeError, JSONDecoder as JSONDecoder\nfrom .encoder import JSONEncoder as JSONEncoder\n\n__all__ = [\"dump\", \"dumps\", \"load\", \"loads\", \"JSONDecoder\", \"JSONDecodeError\", \"JSONEncoder\"]\n\ndef dumps(\n    obj: Any,\n    *,\n    skipkeys: bool = False,\n    ensure_ascii: bool = True,\n    check_circular: bool = True,\n    allow_nan: bool = True,\n    cls: type[JSONEncoder] | None = None,\n    indent: None | int | str = None,\n    separators: tuple[str, str] | None = None,\n    default: Callable[[Any], Any] | None = None,\n    sort_keys: bool = False,\n    **kwds: Any,\n) -> str: ...\ndef dump(\n    obj: Any,\n    fp: SupportsWrite[str],\n    *,\n    skipkeys: bool = False,\n    ensure_ascii: bool = True,\n    check_circular: bool = True,\n    allow_nan: bool = True,\n    cls: type[JSONEncoder] | None = None,\n    indent: None | int | str = None,\n    separators: tuple[str, str] | None = None,\n    default: Callable[[Any], Any] | None = None,\n    sort_keys: bool = False,\n    **kwds: Any,\n) -> None: ...\ndef loads(\n    s: str | bytes | bytearray,\n    *,\n    cls: type[JSONDecoder] | None = None,\n    object_hook: Callable[[dict[Any, Any]], Any] | None = None,\n    parse_float: Callable[[str], Any] | None = None,\n    parse_int: Callable[[str], Any] | None = None,\n    parse_constant: Callable[[str], Any] | None = None,\n    object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None,\n    **kwds: Any,\n) -> Any: ...\ndef load(\n    fp: SupportsRead[str | bytes],\n    *,\n    cls: type[JSONDecoder] | None = None,\n    object_hook: Callable[[dict[Any, Any]], Any] | None = None,\n    parse_float: Callable[[str], Any] | None = None,\n    parse_int: Callable[[str], Any] | None = None,\n    parse_constant: Callable[[str], Any] | None = None,\n    object_pairs_hook: Callable[[list[tuple[Any, Any]]], Any] | None = None,\n    **kwds: Any,\n) -> Any: ...\ndef detect_encoding(b: bytes | bytearray) -> str: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/json/decoder.pyi",
    "content": "from collections.abc import Callable\nfrom typing import Any\n\n__all__ = [\"JSONDecoder\", \"JSONDecodeError\"]\n\nclass JSONDecodeError(ValueError):\n    msg: str\n    doc: str\n    pos: int\n    lineno: int\n    colno: int\n    def __init__(self, msg: str, doc: str, pos: int) -> None: ...\n\nclass JSONDecoder:\n    object_hook: Callable[[dict[str, Any]], Any]\n    parse_float: Callable[[str], Any]\n    parse_int: Callable[[str], Any]\n    parse_constant: Callable[[str], Any]\n    strict: bool\n    object_pairs_hook: Callable[[list[tuple[str, Any]]], Any]\n    def __init__(\n        self,\n        *,\n        object_hook: Callable[[dict[str, Any]], Any] | None = None,\n        parse_float: Callable[[str], Any] | None = None,\n        parse_int: Callable[[str], Any] | None = None,\n        parse_constant: Callable[[str], Any] | None = None,\n        strict: bool = True,\n        object_pairs_hook: Callable[[list[tuple[str, Any]]], Any] | None = None,\n    ) -> None: ...\n    def decode(self, s: str, _w: Callable[..., Any] = ...) -> Any: ...  # _w is undocumented\n    def raw_decode(self, s: str, idx: int = 0) -> tuple[Any, int]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/json/encoder.pyi",
    "content": "from collections.abc import Callable, Iterator\nfrom re import Pattern\nfrom typing import Any, Final\n\nESCAPE: Final[Pattern[str]]  # undocumented\nESCAPE_ASCII: Final[Pattern[str]]  # undocumented\nHAS_UTF8: Final[Pattern[bytes]]  # undocumented\nESCAPE_DCT: Final[dict[str, str]]  # undocumented\nINFINITY: Final[float]  # undocumented\n\ndef py_encode_basestring(s: str) -> str: ...  # undocumented\ndef py_encode_basestring_ascii(s: str) -> str: ...  # undocumented\ndef encode_basestring(s: str, /) -> str: ...  # undocumented\ndef encode_basestring_ascii(s: str, /) -> str: ...  # undocumented\n\nclass JSONEncoder:\n    item_separator: str\n    key_separator: str\n\n    skipkeys: bool\n    ensure_ascii: bool\n    check_circular: bool\n    allow_nan: bool\n    sort_keys: bool\n    indent: int | str\n    def __init__(\n        self,\n        *,\n        skipkeys: bool = False,\n        ensure_ascii: bool = True,\n        check_circular: bool = True,\n        allow_nan: bool = True,\n        sort_keys: bool = False,\n        indent: int | str | None = None,\n        separators: tuple[str, str] | None = None,\n        default: Callable[..., Any] | None = None,\n    ) -> None: ...\n    def default(self, o: Any) -> Any: ...\n    def encode(self, o: Any) -> str: ...\n    def iterencode(self, o: Any, _one_shot: bool = False) -> Iterator[str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/json/scanner.pyi",
    "content": "from _json import make_scanner as make_scanner\nfrom re import Pattern\nfrom typing import Final\n\n__all__ = [\"make_scanner\"]\n\nNUMBER_RE: Final[Pattern[str]]  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/json/tool.pyi",
    "content": "def main() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/keyword.pyi",
    "content": "from collections.abc import Sequence\nfrom typing import Final\n\n__all__ = [\"iskeyword\", \"issoftkeyword\", \"kwlist\", \"softkwlist\"]\n\ndef iskeyword(s: str, /) -> bool: ...\n\n# a list at runtime, but you're not meant to mutate it;\n# type it as a sequence\nkwlist: Final[Sequence[str]]\n\ndef issoftkeyword(s: str, /) -> bool: ...\n\n# a list at runtime, but you're not meant to mutate it;\n# type it as a sequence\nsoftkwlist: Final[Sequence[str]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/btm_matcher.pyi",
    "content": "from _typeshed import Incomplete, SupportsGetItem\nfrom collections import defaultdict\nfrom collections.abc import Iterable\n\nfrom .fixer_base import BaseFix\nfrom .pytree import Leaf, Node\n\nclass BMNode:\n    count: Incomplete\n    transition_table: Incomplete\n    fixers: Incomplete\n    id: Incomplete\n    content: str\n    def __init__(self) -> None: ...\n\nclass BottomMatcher:\n    match: Incomplete\n    root: Incomplete\n    nodes: Incomplete\n    fixers: Incomplete\n    logger: Incomplete\n    def __init__(self) -> None: ...\n    def add_fixer(self, fixer: BaseFix) -> None: ...\n    def add(self, pattern: SupportsGetItem[int | slice, Incomplete] | None, start: BMNode) -> list[BMNode]: ...\n    def run(self, leaves: Iterable[Leaf]) -> defaultdict[BaseFix, list[Node | Leaf]]: ...\n    def print_ac(self) -> None: ...\n\ndef type_repr(type_num: int) -> str | int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixer_base.pyi",
    "content": "from _typeshed import Incomplete, StrPath\nfrom abc import ABCMeta, abstractmethod\nfrom collections.abc import MutableMapping\nfrom typing import ClassVar, Literal, TypeVar\n\nfrom .pytree import Base, Leaf, Node\n\n_N = TypeVar(\"_N\", bound=Base)\n\nclass BaseFix:\n    PATTERN: ClassVar[str | None]\n    pattern: Incomplete | None\n    pattern_tree: Incomplete | None\n    options: Incomplete | None\n    filename: Incomplete | None\n    numbers: Incomplete\n    used_names: Incomplete\n    order: ClassVar[Literal[\"post\", \"pre\"]]\n    explicit: ClassVar[bool]\n    run_order: ClassVar[int]\n    keep_line_order: ClassVar[bool]\n    BM_compatible: ClassVar[bool]\n    syms: Incomplete\n    log: Incomplete\n    def __init__(self, options: MutableMapping[str, Incomplete], log: list[str]) -> None: ...\n    def compile_pattern(self) -> None: ...\n    def set_filename(self, filename: StrPath) -> None: ...\n    def match(self, node: _N) -> Literal[False] | dict[str, _N]: ...\n    @abstractmethod\n    def transform(self, node: Base, results: dict[str, Base]) -> Node | Leaf | None: ...\n    def new_name(self, template: str = \"xxx_todo_changeme\") -> str: ...\n    first_log: bool\n    def log_message(self, message: str) -> None: ...\n    def cannot_convert(self, node: Base, reason: str | None = None) -> None: ...\n    def warning(self, node: Base, reason: str) -> None: ...\n    def start_tree(self, tree: Node, filename: StrPath) -> None: ...\n    def finish_tree(self, tree: Node, filename: StrPath) -> None: ...\n\nclass ConditionalFix(BaseFix, metaclass=ABCMeta):\n    skip_on: ClassVar[str | None]\n    def start_tree(self, tree: Node, filename: StrPath, /) -> None: ...\n    def should_skip(self, node: Base) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_apply.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixApply(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_asserts.pyi",
    "content": "from typing import ClassVar, Final, Literal\n\nfrom ..fixer_base import BaseFix\n\nNAMES: Final[dict[str, str]]\n\nclass FixAsserts(BaseFix):\n    BM_compatible: ClassVar[Literal[False]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_basestring.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixBasestring(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[Literal[\"'basestring'\"]]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_buffer.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixBuffer(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_dict.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\niter_exempt: set[str]\n\nclass FixDict(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n    P1: ClassVar[str]\n    p1: ClassVar[Incomplete]\n    P2: ClassVar[str]\n    p2: ClassVar[Incomplete]\n    def in_special_context(self, node, isiter): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_except.pyi",
    "content": "from collections.abc import Generator, Iterable\nfrom typing import ClassVar, Literal, TypeVar\n\nfrom .. import fixer_base\nfrom ..pytree import Base\n\n_N = TypeVar(\"_N\", bound=Base)\n\ndef find_excepts(nodes: Iterable[_N]) -> Generator[tuple[_N, _N], None, None]: ...\n\nclass FixExcept(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_exec.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixExec(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_execfile.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixExecfile(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_exitfunc.pyi",
    "content": "from _typeshed import Incomplete, StrPath\nfrom lib2to3 import fixer_base\nfrom typing import ClassVar, Literal\n\nfrom ..pytree import Node\n\nclass FixExitfunc(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def __init__(self, *args) -> None: ...\n    sys_import: Incomplete | None\n    def start_tree(self, tree: Node, filename: StrPath) -> None: ...\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_filter.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixFilter(fixer_base.ConditionalFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    skip_on: ClassVar[Literal[\"future_builtins.filter\"]]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_funcattrs.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixFuncattrs(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_future.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixFuture(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_getcwdu.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixGetcwdu(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_has_key.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixHasKey(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_idioms.pyi",
    "content": "from typing import ClassVar, Final, Literal\n\nfrom .. import fixer_base\n\nCMP: Final[str]\nTYPE: Final[str]\n\nclass FixIdioms(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[False]]\n    PATTERN: ClassVar[str]\n    def match(self, node): ...\n    def transform(self, node, results): ...\n    def transform_isinstance(self, node, results): ...\n    def transform_while(self, node, results) -> None: ...\n    def transform_sort(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_import.pyi",
    "content": "from _typeshed import StrPath\nfrom collections.abc import Generator\nfrom typing import ClassVar, Literal\n\nfrom .. import fixer_base\nfrom ..pytree import Node\n\ndef traverse_imports(names) -> Generator[str, None, None]: ...\n\nclass FixImport(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    skip: bool\n    def start_tree(self, tree: Node, name: StrPath) -> None: ...\n    def transform(self, node, results): ...\n    def probably_a_local_import(self, imp_name): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_imports.pyi",
    "content": "from _typeshed import StrPath\nfrom collections.abc import Generator\nfrom typing import ClassVar, Final, Literal\n\nfrom .. import fixer_base\nfrom ..pytree import Node\n\nMAPPING: Final[dict[str, str]]\n\ndef alternates(members): ...\ndef build_pattern(mapping=...) -> Generator[str, None, None]: ...\n\nclass FixImports(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    mapping = MAPPING\n    def build_pattern(self): ...\n    def compile_pattern(self) -> None: ...\n    def match(self, node): ...\n    replace: dict[str, str]\n    def start_tree(self, tree: Node, filename: StrPath) -> None: ...\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_imports2.pyi",
    "content": "from typing import Final\n\nfrom . import fix_imports\n\nMAPPING: Final[dict[str, str]]\n\nclass FixImports2(fix_imports.FixImports):\n    mapping = MAPPING\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_input.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\ncontext: Incomplete\n\nclass FixInput(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_intern.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixIntern(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    order: ClassVar[Literal[\"pre\"]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_isinstance.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixIsinstance(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixItertools(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    it_funcs: str\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_itertools_imports.pyi",
    "content": "from lib2to3 import fixer_base\nfrom typing import ClassVar, Literal\n\nclass FixItertoolsImports(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_long.pyi",
    "content": "from lib2to3 import fixer_base\nfrom typing import ClassVar, Literal\n\nclass FixLong(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[Literal[\"'long'\"]]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_map.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixMap(fixer_base.ConditionalFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    skip_on: ClassVar[Literal[\"future_builtins.map\"]]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_metaclass.pyi",
    "content": "from collections.abc import Generator\nfrom typing import ClassVar, Literal\n\nfrom .. import fixer_base\nfrom ..pytree import Base\n\ndef has_metaclass(parent): ...\ndef fixup_parse_tree(cls_node) -> None: ...\ndef fixup_simple_stmt(parent, i, stmt_node) -> None: ...\ndef remove_trailing_newline(node) -> None: ...\ndef find_metas(cls_node) -> Generator[tuple[Base, int, Base], None, None]: ...\ndef fixup_indent(suite) -> None: ...\n\nclass FixMetaclass(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_methodattrs.pyi",
    "content": "from typing import ClassVar, Final, Literal\n\nfrom .. import fixer_base\n\nMAP: Final[dict[str, str]]\n\nclass FixMethodattrs(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_ne.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixNe(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[False]]\n    def match(self, node): ...\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_next.pyi",
    "content": "from _typeshed import StrPath\nfrom typing import ClassVar, Literal\n\nfrom .. import fixer_base\nfrom ..pytree import Node\n\nbind_warning: str\n\nclass FixNext(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    order: ClassVar[Literal[\"pre\"]]\n    shadowed_next: bool\n    def start_tree(self, tree: Node, filename: StrPath) -> None: ...\n    def transform(self, node, results) -> None: ...\n\ndef is_assign_target(node): ...\ndef find_assign(node): ...\ndef is_subtree(root, node): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_nonzero.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixNonzero(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_numliterals.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixNumliterals(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[False]]\n    def match(self, node): ...\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_operator.pyi",
    "content": "from lib2to3 import fixer_base\nfrom typing import ClassVar, Literal\n\ndef invocation(s): ...\n\nclass FixOperator(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    order: ClassVar[Literal[\"pre\"]]\n    methods: str\n    obj: str\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_paren.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixParen(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_print.pyi",
    "content": "from _typeshed import Incomplete\nfrom typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nparend_expr: Incomplete\n\nclass FixPrint(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n    def add_kwarg(self, l_nodes, s_kwd, n_expr) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_raise.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixRaise(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_raw_input.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixRawInput(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_reduce.pyi",
    "content": "from lib2to3 import fixer_base\nfrom typing import ClassVar, Literal\n\nclass FixReduce(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    order: ClassVar[Literal[\"pre\"]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_reload.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixReload(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    order: ClassVar[Literal[\"pre\"]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_renames.pyi",
    "content": "from collections.abc import Generator\nfrom typing import ClassVar, Final, Literal\n\nfrom .. import fixer_base\n\nMAPPING: Final[dict[str, dict[str, str]]]\nLOOKUP: Final[dict[tuple[str, str], str]]\n\ndef alternates(members): ...\ndef build_pattern() -> Generator[str, None, None]: ...\n\nclass FixRenames(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    order: ClassVar[Literal[\"pre\"]]\n    PATTERN: ClassVar[str]\n    def match(self, node): ...\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_repr.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixRepr(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_set_literal.pyi",
    "content": "from lib2to3 import fixer_base\nfrom typing import ClassVar, Literal\n\nclass FixSetLiteral(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_standarderror.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixStandarderror(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_sys_exc.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixSysExc(fixer_base.BaseFix):\n    exc_info: ClassVar[list[str]]\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_throw.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixThrow(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_tuple_params.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\ndef is_docstring(stmt): ...\n\nclass FixTupleParams(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n    def transform_lambda(self, node, results) -> None: ...\n\ndef simplify_args(node): ...\ndef find_params(node): ...\ndef map_to_index(param_list, prefix=[], d=None): ...\ndef tuple_name(param_list): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_types.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixTypes(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_unicode.pyi",
    "content": "from _typeshed import StrPath\nfrom typing import ClassVar, Literal\n\nfrom .. import fixer_base\nfrom ..pytree import Node\n\nclass FixUnicode(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    unicode_literals: bool\n    def start_tree(self, tree: Node, filename: StrPath) -> None: ...\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_urllib.pyi",
    "content": "from collections.abc import Generator\nfrom typing import Final, Literal\n\nfrom .fix_imports import FixImports\n\nMAPPING: Final[dict[str, list[tuple[Literal[\"urllib.request\", \"urllib.parse\", \"urllib.error\"], list[str]]]]]\n\ndef build_pattern() -> Generator[str, None, None]: ...\n\nclass FixUrllib(FixImports):\n    def build_pattern(self): ...\n    def transform_import(self, node, results) -> None: ...\n    def transform_member(self, node, results): ...\n    def transform_dot(self, node, results) -> None: ...\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_ws_comma.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\nfrom ..pytree import Leaf\n\nclass FixWsComma(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[False]]\n    PATTERN: ClassVar[str]\n    COMMA: Leaf\n    COLON: Leaf\n    SEPS: tuple[Leaf, Leaf]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_xrange.pyi",
    "content": "from _typeshed import Incomplete, StrPath\nfrom typing import ClassVar, Literal\n\nfrom .. import fixer_base\nfrom ..pytree import Node\n\nclass FixXrange(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    transformed_xranges: set[Incomplete] | None\n    def start_tree(self, tree: Node, filename: StrPath) -> None: ...\n    def finish_tree(self, tree: Node, filename: StrPath) -> None: ...\n    def transform(self, node, results): ...\n    def transform_xrange(self, node, results) -> None: ...\n    def transform_range(self, node, results): ...\n    P1: ClassVar[str]\n    p1: ClassVar[Incomplete]\n    P2: ClassVar[str]\n    p2: ClassVar[Incomplete]\n    def in_special_context(self, node): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_xreadlines.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixXreadlines(fixer_base.BaseFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    def transform(self, node, results) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/fixes/fix_zip.pyi",
    "content": "from typing import ClassVar, Literal\n\nfrom .. import fixer_base\n\nclass FixZip(fixer_base.ConditionalFix):\n    BM_compatible: ClassVar[Literal[True]]\n    PATTERN: ClassVar[str]\n    skip_on: ClassVar[Literal[\"future_builtins.zip\"]]\n    def transform(self, node, results): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/main.pyi",
    "content": "from _typeshed import FileDescriptorOrPath\nfrom collections.abc import Container, Iterable, Iterator, Mapping, Sequence\nfrom logging import _ExcInfoType\nfrom typing import AnyStr, Literal\n\nfrom . import refactor as refactor\n\ndef diff_texts(a: str, b: str, filename: str) -> Iterator[str]: ...\n\nclass StdoutRefactoringTool(refactor.MultiprocessRefactoringTool):\n    nobackups: bool\n    show_diffs: bool\n    def __init__(\n        self,\n        fixers: Iterable[str],\n        options: Mapping[str, object] | None,\n        explicit: Container[str] | None,\n        nobackups: bool,\n        show_diffs: bool,\n        input_base_dir: str = \"\",\n        output_dir: str = \"\",\n        append_suffix: str = \"\",\n    ) -> None: ...\n    # Same as super.log_error and Logger.error\n    def log_error(  # type: ignore[override]\n        self,\n        msg: str,\n        *args: Iterable[str],\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n    ) -> None: ...\n    # Same as super.write_file but without default values\n    def write_file(  # type: ignore[override]\n        self, new_text: str, filename: FileDescriptorOrPath, old_text: str, encoding: str | None\n    ) -> None: ...\n    # filename has to be str\n    def print_output(self, old: str, new: str, filename: str, equal: bool) -> None: ...  # type: ignore[override]\n\ndef warn(msg: object) -> None: ...\ndef main(fixer_pkg: str, args: Sequence[AnyStr] | None = None) -> Literal[0, 1, 2]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/pgen2/__init__.pyi",
    "content": "from collections.abc import Callable\nfrom typing import Any\nfrom typing_extensions import TypeAlias\n\nfrom ..pytree import _RawNode\nfrom .grammar import Grammar\n\n# This is imported in several lib2to3/pgen2 submodules\n_Convert: TypeAlias = Callable[[Grammar, _RawNode], Any]  # noqa: Y047\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/pgen2/driver.pyi",
    "content": "from _typeshed import StrPath\nfrom collections.abc import Iterable\nfrom logging import Logger\nfrom typing import IO\n\nfrom ..pytree import _NL\nfrom . import _Convert\nfrom .grammar import Grammar\n\n__all__ = [\"Driver\", \"load_grammar\"]\n\nclass Driver:\n    grammar: Grammar\n    logger: Logger\n    convert: _Convert\n    def __init__(self, grammar: Grammar, convert: _Convert | None = None, logger: Logger | None = None) -> None: ...\n    def parse_tokens(\n        self, tokens: Iterable[tuple[int, str, tuple[int, int], tuple[int, int], str]], debug: bool = False\n    ) -> _NL: ...\n    def parse_stream_raw(self, stream: IO[str], debug: bool = False) -> _NL: ...\n    def parse_stream(self, stream: IO[str], debug: bool = False) -> _NL: ...\n    def parse_file(self, filename: StrPath, encoding: str | None = None, debug: bool = False) -> _NL: ...\n    def parse_string(self, text: str, debug: bool = False) -> _NL: ...\n\ndef load_grammar(\n    gt: str = \"Grammar.txt\", gp: str | None = None, save: bool = True, force: bool = False, logger: Logger | None = None\n) -> Grammar: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/pgen2/grammar.pyi",
    "content": "from _typeshed import StrPath\nfrom typing_extensions import Self, TypeAlias\n\n_Label: TypeAlias = tuple[int, str | None]\n_DFA: TypeAlias = list[list[tuple[int, int]]]\n_DFAS: TypeAlias = tuple[_DFA, dict[int, int]]\n\nclass Grammar:\n    symbol2number: dict[str, int]\n    number2symbol: dict[int, str]\n    states: list[_DFA]\n    dfas: dict[int, _DFAS]\n    labels: list[_Label]\n    keywords: dict[str, int]\n    tokens: dict[int, int]\n    symbol2label: dict[str, int]\n    start: int\n    def dump(self, filename: StrPath) -> None: ...\n    def load(self, filename: StrPath) -> None: ...\n    def copy(self) -> Self: ...\n    def report(self) -> None: ...\n\nopmap_raw: str\nopmap: dict[str, str]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/pgen2/literals.pyi",
    "content": "from re import Match\n\nsimple_escapes: dict[str, str]\n\ndef escape(m: Match[str]) -> str: ...\ndef evalString(s: str) -> str: ...\ndef test() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/pgen2/parse.pyi",
    "content": "from _typeshed import Incomplete\nfrom collections.abc import Sequence\nfrom typing_extensions import TypeAlias\n\nfrom ..pytree import _NL, _RawNode\nfrom . import _Convert\nfrom .grammar import _DFAS, Grammar\n\n_Context: TypeAlias = Sequence[Incomplete]\n\nclass ParseError(Exception):\n    msg: str\n    type: int\n    value: str | None\n    context: _Context\n    def __init__(self, msg: str, type: int, value: str | None, context: _Context) -> None: ...\n\nclass Parser:\n    grammar: Grammar\n    convert: _Convert\n    stack: list[tuple[_DFAS, int, _RawNode]]\n    rootnode: _NL | None\n    used_names: set[str]\n    def __init__(self, grammar: Grammar, convert: _Convert | None = None) -> None: ...\n    def setup(self, start: int | None = None) -> None: ...\n    def addtoken(self, type: int, value: str | None, context: _Context) -> bool: ...\n    def classify(self, type: int, value: str | None, context: _Context) -> int: ...\n    def shift(self, type: int, value: str | None, newstate: int, context: _Context) -> None: ...\n    def push(self, type: int, newdfa: _DFAS, newstate: int, context: _Context) -> None: ...\n    def pop(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/pgen2/pgen.pyi",
    "content": "from _typeshed import Incomplete, StrPath\nfrom collections.abc import Iterable, Iterator\nfrom typing import IO, ClassVar, NoReturn, overload\n\nfrom . import grammar\nfrom .tokenize import _TokenInfo\n\nclass PgenGrammar(grammar.Grammar): ...\n\nclass ParserGenerator:\n    filename: StrPath\n    stream: IO[str]\n    generator: Iterator[_TokenInfo]\n    first: dict[str, dict[str, int]]\n    def __init__(self, filename: StrPath, stream: IO[str] | None = None) -> None: ...\n    def make_grammar(self) -> PgenGrammar: ...\n    def make_first(self, c: PgenGrammar, name: str) -> dict[int, int]: ...\n    def make_label(self, c: PgenGrammar, label: str) -> int: ...\n    def addfirstsets(self) -> None: ...\n    def calcfirst(self, name: str) -> None: ...\n    def parse(self) -> tuple[dict[str, list[DFAState]], str]: ...\n    def make_dfa(self, start: NFAState, finish: NFAState) -> list[DFAState]: ...\n    def dump_nfa(self, name: str, start: NFAState, finish: NFAState) -> list[DFAState]: ...\n    def dump_dfa(self, name: str, dfa: Iterable[DFAState]) -> None: ...\n    def simplify_dfa(self, dfa: list[DFAState]) -> None: ...\n    def parse_rhs(self) -> tuple[NFAState, NFAState]: ...\n    def parse_alt(self) -> tuple[NFAState, NFAState]: ...\n    def parse_item(self) -> tuple[NFAState, NFAState]: ...\n    def parse_atom(self) -> tuple[NFAState, NFAState]: ...\n    def expect(self, type: int, value: str | None = None) -> str: ...\n    def gettoken(self) -> None: ...\n    @overload\n    def raise_error(self, msg: object) -> NoReturn: ...\n    @overload\n    def raise_error(self, msg: str, *args: object) -> NoReturn: ...\n\nclass NFAState:\n    arcs: list[tuple[str | None, NFAState]]\n    def addarc(self, next: NFAState, label: str | None = None) -> None: ...\n\nclass DFAState:\n    nfaset: dict[NFAState, Incomplete]\n    isfinal: bool\n    arcs: dict[str, DFAState]\n    def __init__(self, nfaset: dict[NFAState, Incomplete], final: NFAState) -> None: ...\n    def addarc(self, next: DFAState, label: str) -> None: ...\n    def unifystate(self, old: DFAState, new: DFAState) -> None: ...\n    def __eq__(self, other: DFAState) -> bool: ...  # type: ignore[override]\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\ndef generate_grammar(filename: StrPath = \"Grammar.txt\") -> PgenGrammar: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/pgen2/token.pyi",
    "content": "from typing import Final\n\nENDMARKER: Final[int]\nNAME: Final[int]\nNUMBER: Final[int]\nSTRING: Final[int]\nNEWLINE: Final[int]\nINDENT: Final[int]\nDEDENT: Final[int]\nLPAR: Final[int]\nRPAR: Final[int]\nLSQB: Final[int]\nRSQB: Final[int]\nCOLON: Final[int]\nCOMMA: Final[int]\nSEMI: Final[int]\nPLUS: Final[int]\nMINUS: Final[int]\nSTAR: Final[int]\nSLASH: Final[int]\nVBAR: Final[int]\nAMPER: Final[int]\nLESS: Final[int]\nGREATER: Final[int]\nEQUAL: Final[int]\nDOT: Final[int]\nPERCENT: Final[int]\nBACKQUOTE: Final[int]\nLBRACE: Final[int]\nRBRACE: Final[int]\nEQEQUAL: Final[int]\nNOTEQUAL: Final[int]\nLESSEQUAL: Final[int]\nGREATEREQUAL: Final[int]\nTILDE: Final[int]\nCIRCUMFLEX: Final[int]\nLEFTSHIFT: Final[int]\nRIGHTSHIFT: Final[int]\nDOUBLESTAR: Final[int]\nPLUSEQUAL: Final[int]\nMINEQUAL: Final[int]\nSTAREQUAL: Final[int]\nSLASHEQUAL: Final[int]\nPERCENTEQUAL: Final[int]\nAMPEREQUAL: Final[int]\nVBAREQUAL: Final[int]\nCIRCUMFLEXEQUAL: Final[int]\nLEFTSHIFTEQUAL: Final[int]\nRIGHTSHIFTEQUAL: Final[int]\nDOUBLESTAREQUAL: Final[int]\nDOUBLESLASH: Final[int]\nDOUBLESLASHEQUAL: Final[int]\nOP: Final[int]\nCOMMENT: Final[int]\nNL: Final[int]\nRARROW: Final[int]\nAT: Final[int]\nATEQUAL: Final[int]\nAWAIT: Final[int]\nASYNC: Final[int]\nERRORTOKEN: Final[int]\nCOLONEQUAL: Final[int]\nN_TOKENS: Final[int]\nNT_OFFSET: Final[int]\ntok_name: dict[int, str]\n\ndef ISTERMINAL(x: int) -> bool: ...\ndef ISNONTERMINAL(x: int) -> bool: ...\ndef ISEOF(x: int) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/pgen2/tokenize.pyi",
    "content": "from collections.abc import Callable, Iterable, Iterator\nfrom typing_extensions import TypeAlias\n\nfrom .token import *\n\n__all__ = [\n    \"AMPER\",\n    \"AMPEREQUAL\",\n    \"ASYNC\",\n    \"AT\",\n    \"ATEQUAL\",\n    \"AWAIT\",\n    \"BACKQUOTE\",\n    \"CIRCUMFLEX\",\n    \"CIRCUMFLEXEQUAL\",\n    \"COLON\",\n    \"COMMA\",\n    \"COMMENT\",\n    \"DEDENT\",\n    \"DOT\",\n    \"DOUBLESLASH\",\n    \"DOUBLESLASHEQUAL\",\n    \"DOUBLESTAR\",\n    \"DOUBLESTAREQUAL\",\n    \"ENDMARKER\",\n    \"EQEQUAL\",\n    \"EQUAL\",\n    \"ERRORTOKEN\",\n    \"GREATER\",\n    \"GREATEREQUAL\",\n    \"INDENT\",\n    \"ISEOF\",\n    \"ISNONTERMINAL\",\n    \"ISTERMINAL\",\n    \"LBRACE\",\n    \"LEFTSHIFT\",\n    \"LEFTSHIFTEQUAL\",\n    \"LESS\",\n    \"LESSEQUAL\",\n    \"LPAR\",\n    \"LSQB\",\n    \"MINEQUAL\",\n    \"MINUS\",\n    \"NAME\",\n    \"NEWLINE\",\n    \"NL\",\n    \"NOTEQUAL\",\n    \"NT_OFFSET\",\n    \"NUMBER\",\n    \"N_TOKENS\",\n    \"OP\",\n    \"PERCENT\",\n    \"PERCENTEQUAL\",\n    \"PLUS\",\n    \"PLUSEQUAL\",\n    \"RARROW\",\n    \"RBRACE\",\n    \"RIGHTSHIFT\",\n    \"RIGHTSHIFTEQUAL\",\n    \"RPAR\",\n    \"RSQB\",\n    \"SEMI\",\n    \"SLASH\",\n    \"SLASHEQUAL\",\n    \"STAR\",\n    \"STAREQUAL\",\n    \"STRING\",\n    \"TILDE\",\n    \"VBAR\",\n    \"VBAREQUAL\",\n    \"tok_name\",\n    \"tokenize\",\n    \"generate_tokens\",\n    \"untokenize\",\n    \"COLONEQUAL\",\n]\n\n_Coord: TypeAlias = tuple[int, int]\n_TokenEater: TypeAlias = Callable[[int, str, _Coord, _Coord, str], object]\n_TokenInfo: TypeAlias = tuple[int, str, _Coord, _Coord, str]\n\nclass TokenError(Exception): ...\nclass StopTokenizing(Exception): ...\n\ndef tokenize(readline: Callable[[], str], tokeneater: _TokenEater = ...) -> None: ...\n\nclass Untokenizer:\n    tokens: list[str]\n    prev_row: int\n    prev_col: int\n    def add_whitespace(self, start: _Coord) -> None: ...\n    def untokenize(self, iterable: Iterable[_TokenInfo]) -> str: ...\n    def compat(self, token: tuple[int, str], iterable: Iterable[_TokenInfo]) -> None: ...\n\ndef untokenize(iterable: Iterable[_TokenInfo]) -> str: ...\ndef generate_tokens(readline: Callable[[], str]) -> Iterator[_TokenInfo]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/pygram.pyi",
    "content": "from .pgen2.grammar import Grammar\n\nclass Symbols:\n    def __init__(self, grammar: Grammar) -> None: ...\n\nclass python_symbols(Symbols):\n    and_expr: int\n    and_test: int\n    annassign: int\n    arglist: int\n    argument: int\n    arith_expr: int\n    assert_stmt: int\n    async_funcdef: int\n    async_stmt: int\n    atom: int\n    augassign: int\n    break_stmt: int\n    classdef: int\n    comp_for: int\n    comp_if: int\n    comp_iter: int\n    comp_op: int\n    comparison: int\n    compound_stmt: int\n    continue_stmt: int\n    decorated: int\n    decorator: int\n    decorators: int\n    del_stmt: int\n    dictsetmaker: int\n    dotted_as_name: int\n    dotted_as_names: int\n    dotted_name: int\n    encoding_decl: int\n    eval_input: int\n    except_clause: int\n    exec_stmt: int\n    expr: int\n    expr_stmt: int\n    exprlist: int\n    factor: int\n    file_input: int\n    flow_stmt: int\n    for_stmt: int\n    funcdef: int\n    global_stmt: int\n    if_stmt: int\n    import_as_name: int\n    import_as_names: int\n    import_from: int\n    import_name: int\n    import_stmt: int\n    lambdef: int\n    listmaker: int\n    not_test: int\n    old_lambdef: int\n    old_test: int\n    or_test: int\n    parameters: int\n    pass_stmt: int\n    power: int\n    print_stmt: int\n    raise_stmt: int\n    return_stmt: int\n    shift_expr: int\n    simple_stmt: int\n    single_input: int\n    sliceop: int\n    small_stmt: int\n    star_expr: int\n    stmt: int\n    subscript: int\n    subscriptlist: int\n    suite: int\n    term: int\n    test: int\n    testlist: int\n    testlist1: int\n    testlist_gexp: int\n    testlist_safe: int\n    testlist_star_expr: int\n    tfpdef: int\n    tfplist: int\n    tname: int\n    trailer: int\n    try_stmt: int\n    typedargslist: int\n    varargslist: int\n    vfpdef: int\n    vfplist: int\n    vname: int\n    while_stmt: int\n    with_item: int\n    with_stmt: int\n    with_var: int\n    xor_expr: int\n    yield_arg: int\n    yield_expr: int\n    yield_stmt: int\n\nclass pattern_symbols(Symbols):\n    Alternative: int\n    Alternatives: int\n    Details: int\n    Matcher: int\n    NegatedUnit: int\n    Repeater: int\n    Unit: int\n\npython_grammar: Grammar\npython_grammar_no_print_statement: Grammar\npython_grammar_no_print_and_exec_statement: Grammar\npattern_grammar: Grammar\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/pytree.pyi",
    "content": "from _typeshed import Incomplete, SupportsGetItem, SupportsLenAndGetItem, Unused\nfrom abc import abstractmethod\nfrom collections.abc import Iterable, Iterator, MutableSequence\nfrom typing import ClassVar, Final\nfrom typing_extensions import Self, TypeAlias\n\nfrom .fixer_base import BaseFix\nfrom .pgen2.grammar import Grammar\n\n_NL: TypeAlias = Node | Leaf\n_Context: TypeAlias = tuple[str, int, int]\n_Results: TypeAlias = dict[str, _NL]\n_RawNode: TypeAlias = tuple[int, str, _Context, list[_NL] | None]\n\nHUGE: Final = 0x7FFFFFFF\n\ndef type_repr(type_num: int) -> str | int: ...\n\nclass Base:\n    type: int\n    parent: Node | None\n    prefix: str\n    children: list[_NL]\n    was_changed: bool\n    was_checked: bool\n    def __eq__(self, other: object) -> bool: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    @abstractmethod\n    def _eq(self, other: Base) -> bool: ...\n    @abstractmethod\n    def clone(self) -> Self: ...\n    @abstractmethod\n    def post_order(self) -> Iterator[Self]: ...\n    @abstractmethod\n    def pre_order(self) -> Iterator[Self]: ...\n    def replace(self, new: _NL | list[_NL]) -> None: ...\n    def get_lineno(self) -> int: ...\n    def changed(self) -> None: ...\n    def remove(self) -> int | None: ...\n    @property\n    def next_sibling(self) -> _NL | None: ...\n    @property\n    def prev_sibling(self) -> _NL | None: ...\n    def leaves(self) -> Iterator[Leaf]: ...\n    def depth(self) -> int: ...\n    def get_suffix(self) -> str: ...\n\nclass Node(Base):\n    fixers_applied: MutableSequence[BaseFix] | None\n    # Is Unbound until set in refactor.RefactoringTool\n    future_features: frozenset[Incomplete]\n    # Is Unbound until set in pgen2.parse.Parser.pop\n    used_names: set[str]\n    def __init__(\n        self,\n        type: int,\n        children: Iterable[_NL],\n        context: Unused = None,\n        prefix: str | None = None,\n        fixers_applied: MutableSequence[BaseFix] | None = None,\n    ) -> None: ...\n    def _eq(self, other: Base) -> bool: ...\n    def clone(self) -> Node: ...\n    def post_order(self) -> Iterator[Self]: ...\n    def pre_order(self) -> Iterator[Self]: ...\n    def set_child(self, i: int, child: _NL) -> None: ...\n    def insert_child(self, i: int, child: _NL) -> None: ...\n    def append_child(self, child: _NL) -> None: ...\n    def __unicode__(self) -> str: ...\n\nclass Leaf(Base):\n    lineno: int\n    column: int\n    value: str\n    fixers_applied: MutableSequence[BaseFix]\n    def __init__(\n        self,\n        type: int,\n        value: str,\n        context: _Context | None = None,\n        prefix: str | None = None,\n        fixers_applied: MutableSequence[BaseFix] = [],\n    ) -> None: ...\n    def _eq(self, other: Base) -> bool: ...\n    def clone(self) -> Leaf: ...\n    def post_order(self) -> Iterator[Self]: ...\n    def pre_order(self) -> Iterator[Self]: ...\n    def __unicode__(self) -> str: ...\n\ndef convert(gr: Grammar, raw_node: _RawNode) -> _NL: ...\n\nclass BasePattern:\n    type: int\n    content: str | None\n    name: str | None\n    def optimize(self) -> BasePattern: ...  # sic, subclasses are free to optimize themselves into different patterns\n    def match(self, node: _NL, results: _Results | None = None) -> bool: ...\n    def match_seq(self, nodes: SupportsLenAndGetItem[_NL], results: _Results | None = None) -> bool: ...\n    def generate_matches(self, nodes: SupportsGetItem[int, _NL]) -> Iterator[tuple[int, _Results]]: ...\n\nclass LeafPattern(BasePattern):\n    def __init__(self, type: int | None = None, content: str | None = None, name: str | None = None) -> None: ...\n\nclass NodePattern(BasePattern):\n    wildcards: bool\n    def __init__(self, type: int | None = None, content: str | None = None, name: str | None = None) -> None: ...\n\nclass WildcardPattern(BasePattern):\n    min: int\n    max: int\n    def __init__(self, content: str | None = None, min: int = 0, max: int = 0x7FFFFFFF, name: str | None = None) -> None: ...\n\nclass NegatedPattern(BasePattern):\n    def __init__(self, content: str | None = None) -> None: ...\n\ndef generate_matches(\n    patterns: SupportsGetItem[int | slice, BasePattern] | None, nodes: SupportsGetItem[int | slice, _NL]\n) -> Iterator[tuple[int, _Results]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lib2to3/refactor.pyi",
    "content": "from _typeshed import FileDescriptorOrPath, StrPath, SupportsGetItem\nfrom collections.abc import Container, Generator, Iterable, Mapping\nfrom logging import Logger, _ExcInfoType\nfrom multiprocessing import JoinableQueue\nfrom multiprocessing.synchronize import Lock\nfrom typing import Any, ClassVar, Final, NoReturn, overload\n\nfrom .btm_matcher import BottomMatcher\nfrom .fixer_base import BaseFix\nfrom .pgen2.driver import Driver\nfrom .pgen2.grammar import Grammar\nfrom .pytree import Node\n\ndef get_all_fix_names(fixer_pkg: str, remove_prefix: bool = True) -> list[str]: ...\ndef get_fixers_from_package(pkg_name: str) -> list[str]: ...\n\nclass FixerError(Exception): ...\n\nclass RefactoringTool:\n    CLASS_PREFIX: ClassVar[str]\n    FILE_PREFIX: ClassVar[str]\n    fixers: Iterable[str]\n    explicit: Container[str]\n    options: dict[str, Any]\n    grammar: Grammar\n    write_unchanged_files: bool\n    errors: list[tuple[str, Iterable[str], dict[str, _ExcInfoType]]]\n    logger: Logger\n    fixer_log: list[str]\n    wrote: bool\n    driver: Driver\n    pre_order: list[BaseFix]\n    post_order: list[BaseFix]\n    files: list[StrPath]\n    BM: BottomMatcher\n    bmi_pre_order: list[BaseFix]\n    bmi_post_order: list[BaseFix]\n    def __init__(\n        self, fixer_names: Iterable[str], options: Mapping[str, object] | None = None, explicit: Container[str] | None = None\n    ) -> None: ...\n    def get_fixers(self) -> tuple[list[BaseFix], list[BaseFix]]: ...\n    def log_error(self, msg: str, *args: Iterable[str], **kwargs: _ExcInfoType) -> NoReturn: ...\n    @overload\n    def log_message(self, msg: object) -> None: ...\n    @overload\n    def log_message(self, msg: str, *args: object) -> None: ...\n    @overload\n    def log_debug(self, msg: object) -> None: ...\n    @overload\n    def log_debug(self, msg: str, *args: object) -> None: ...\n    def print_output(self, old_text: str, new_text: str, filename: StrPath, equal: bool) -> None: ...\n    def refactor(self, items: Iterable[str], write: bool = False, doctests_only: bool = False) -> None: ...\n    def refactor_dir(self, dir_name: str, write: bool = False, doctests_only: bool = False) -> None: ...\n    def _read_python_source(self, filename: FileDescriptorOrPath) -> tuple[str, str]: ...\n    def refactor_file(self, filename: StrPath, write: bool = False, doctests_only: bool = False) -> None: ...\n    def refactor_string(self, data: str, name: str) -> Node | None: ...\n    def refactor_stdin(self, doctests_only: bool = False) -> None: ...\n    def refactor_tree(self, tree: Node, name: str) -> bool: ...\n    def traverse_by(self, fixers: SupportsGetItem[int, Iterable[BaseFix]] | None, traversal: Iterable[Node]) -> None: ...\n    def processed_file(\n        self, new_text: str, filename: StrPath, old_text: str | None = None, write: bool = False, encoding: str | None = None\n    ) -> None: ...\n    def write_file(self, new_text: str, filename: FileDescriptorOrPath, old_text: str, encoding: str | None = None) -> None: ...\n    PS1: Final = \">>> \"\n    PS2: Final = \"... \"\n    def refactor_docstring(self, input: str, filename: StrPath) -> str: ...\n    def refactor_doctest(self, block: list[str], lineno: int, indent: int, filename: StrPath) -> list[str]: ...\n    def summarize(self) -> None: ...\n    def parse_block(self, block: Iterable[str], lineno: int, indent: int) -> Node: ...\n    def wrap_toks(\n        self, block: Iterable[str], lineno: int, indent: int\n    ) -> Generator[tuple[int, str, tuple[int, int], tuple[int, int], str], None, None]: ...\n    def gen_lines(self, block: Iterable[str], indent: int) -> Generator[str, None, None]: ...\n\nclass MultiprocessingUnsupported(Exception): ...\n\nclass MultiprocessRefactoringTool(RefactoringTool):\n    queue: JoinableQueue[None | tuple[Iterable[str], bool | int]] | None\n    output_lock: Lock | None\n    def refactor(\n        self, items: Iterable[str], write: bool = False, doctests_only: bool = False, num_processes: int = 1\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/linecache.pyi",
    "content": "from collections.abc import Callable\nfrom typing import Any\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"getline\", \"clearcache\", \"checkcache\", \"lazycache\"]\n\n_ModuleGlobals: TypeAlias = dict[str, Any]\n_ModuleMetadata: TypeAlias = tuple[int, float | None, list[str], str]\n\n_SourceLoader: TypeAlias = tuple[Callable[[], str | None]]\n\ncache: dict[str, _SourceLoader | _ModuleMetadata]  # undocumented\n\ndef getline(filename: str, lineno: int, module_globals: _ModuleGlobals | None = None) -> str: ...\ndef clearcache() -> None: ...\ndef getlines(filename: str, module_globals: _ModuleGlobals | None = None) -> list[str]: ...\ndef checkcache(filename: str | None = None) -> None: ...\ndef updatecache(filename: str, module_globals: _ModuleGlobals | None = None) -> list[str]: ...\ndef lazycache(filename: str, module_globals: _ModuleGlobals) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/locale.pyi",
    "content": "import sys\nfrom _locale import (\n    CHAR_MAX as CHAR_MAX,\n    LC_ALL as LC_ALL,\n    LC_COLLATE as LC_COLLATE,\n    LC_CTYPE as LC_CTYPE,\n    LC_MONETARY as LC_MONETARY,\n    LC_NUMERIC as LC_NUMERIC,\n    LC_TIME as LC_TIME,\n    localeconv as localeconv,\n    strcoll as strcoll,\n    strxfrm as strxfrm,\n)\n\n# This module defines a function \"str()\", which is why \"str\" can't be used\n# as a type annotation or type alias.\nfrom builtins import str as _str\nfrom collections.abc import Callable, Iterable\nfrom decimal import Decimal\nfrom typing import Any\nfrom typing_extensions import deprecated\n\nif sys.version_info >= (3, 11):\n    from _locale import getencoding as getencoding\n\n# Some parts of the `_locale` module are platform-specific:\nif sys.platform != \"win32\":\n    from _locale import (\n        ABDAY_1 as ABDAY_1,\n        ABDAY_2 as ABDAY_2,\n        ABDAY_3 as ABDAY_3,\n        ABDAY_4 as ABDAY_4,\n        ABDAY_5 as ABDAY_5,\n        ABDAY_6 as ABDAY_6,\n        ABDAY_7 as ABDAY_7,\n        ABMON_1 as ABMON_1,\n        ABMON_2 as ABMON_2,\n        ABMON_3 as ABMON_3,\n        ABMON_4 as ABMON_4,\n        ABMON_5 as ABMON_5,\n        ABMON_6 as ABMON_6,\n        ABMON_7 as ABMON_7,\n        ABMON_8 as ABMON_8,\n        ABMON_9 as ABMON_9,\n        ABMON_10 as ABMON_10,\n        ABMON_11 as ABMON_11,\n        ABMON_12 as ABMON_12,\n        ALT_DIGITS as ALT_DIGITS,\n        AM_STR as AM_STR,\n        CODESET as CODESET,\n        CRNCYSTR as CRNCYSTR,\n        D_FMT as D_FMT,\n        D_T_FMT as D_T_FMT,\n        DAY_1 as DAY_1,\n        DAY_2 as DAY_2,\n        DAY_3 as DAY_3,\n        DAY_4 as DAY_4,\n        DAY_5 as DAY_5,\n        DAY_6 as DAY_6,\n        DAY_7 as DAY_7,\n        ERA as ERA,\n        ERA_D_FMT as ERA_D_FMT,\n        ERA_D_T_FMT as ERA_D_T_FMT,\n        ERA_T_FMT as ERA_T_FMT,\n        LC_MESSAGES as LC_MESSAGES,\n        MON_1 as MON_1,\n        MON_2 as MON_2,\n        MON_3 as MON_3,\n        MON_4 as MON_4,\n        MON_5 as MON_5,\n        MON_6 as MON_6,\n        MON_7 as MON_7,\n        MON_8 as MON_8,\n        MON_9 as MON_9,\n        MON_10 as MON_10,\n        MON_11 as MON_11,\n        MON_12 as MON_12,\n        NOEXPR as NOEXPR,\n        PM_STR as PM_STR,\n        RADIXCHAR as RADIXCHAR,\n        T_FMT as T_FMT,\n        T_FMT_AMPM as T_FMT_AMPM,\n        THOUSEP as THOUSEP,\n        YESEXPR as YESEXPR,\n        bind_textdomain_codeset as bind_textdomain_codeset,\n        bindtextdomain as bindtextdomain,\n        dcgettext as dcgettext,\n        dgettext as dgettext,\n        gettext as gettext,\n        nl_langinfo as nl_langinfo,\n        textdomain as textdomain,\n    )\n\n__all__ = [\n    \"getlocale\",\n    \"getdefaultlocale\",\n    \"getpreferredencoding\",\n    \"Error\",\n    \"setlocale\",\n    \"localeconv\",\n    \"strcoll\",\n    \"strxfrm\",\n    \"str\",\n    \"atof\",\n    \"atoi\",\n    \"format_string\",\n    \"currency\",\n    \"normalize\",\n    \"LC_CTYPE\",\n    \"LC_COLLATE\",\n    \"LC_TIME\",\n    \"LC_MONETARY\",\n    \"LC_NUMERIC\",\n    \"LC_ALL\",\n    \"CHAR_MAX\",\n]\n\nif sys.version_info >= (3, 11):\n    __all__ += [\"getencoding\"]\n\nif sys.version_info < (3, 12):\n    __all__ += [\"format\"]\n\nif sys.version_info < (3, 13):\n    __all__ += [\"resetlocale\"]\n\nif sys.platform != \"win32\":\n    __all__ += [\"LC_MESSAGES\"]\n\nclass Error(Exception): ...\n\ndef getdefaultlocale(\n    envvars: tuple[_str, ...] = (\"LC_ALL\", \"LC_CTYPE\", \"LANG\", \"LANGUAGE\")\n) -> tuple[_str | None, _str | None]: ...\ndef getlocale(category: int = ...) -> tuple[_str | None, _str | None]: ...\ndef setlocale(category: int, locale: _str | Iterable[_str | None] | None = None) -> _str: ...\ndef getpreferredencoding(do_setlocale: bool = True) -> _str: ...\ndef normalize(localename: _str) -> _str: ...\n\nif sys.version_info < (3, 13):\n    if sys.version_info >= (3, 11):\n        @deprecated(\"Deprecated since Python 3.11; removed in Python 3.13. Use `locale.setlocale(locale.LC_ALL, '')` instead.\")\n        def resetlocale(category: int = ...) -> None: ...\n    else:\n        def resetlocale(category: int = ...) -> None: ...\n\nif sys.version_info < (3, 12):\n    @deprecated(\"Deprecated since Python 3.7; removed in Python 3.12. Use `locale.format_string()` instead.\")\n    def format(\n        percent: _str, value: float | Decimal, grouping: bool = False, monetary: bool = False, *additional: Any\n    ) -> _str: ...\n\ndef format_string(f: _str, val: Any, grouping: bool = False, monetary: bool = False) -> _str: ...\ndef currency(val: float | Decimal, symbol: bool = True, grouping: bool = False, international: bool = False) -> _str: ...\ndef delocalize(string: _str) -> _str: ...\n\nif sys.version_info >= (3, 10):\n    def localize(string: _str, grouping: bool = False, monetary: bool = False) -> _str: ...\n\ndef atof(string: _str, func: Callable[[_str], float] = ...) -> float: ...\ndef atoi(string: _str) -> int: ...\ndef str(val: float) -> _str: ...\n\nlocale_alias: dict[_str, _str]  # undocumented\nlocale_encoding_alias: dict[_str, _str]  # undocumented\nwindows_locale: dict[int, _str]  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/logging/__init__.pyi",
    "content": "import sys\nimport threading\nfrom _typeshed import StrPath, SupportsWrite\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom io import TextIOWrapper\nfrom re import Pattern\nfrom string import Template\nfrom time import struct_time\nfrom types import FrameType, GenericAlias, TracebackType\nfrom typing import Any, ClassVar, Final, Generic, Literal, Protocol, TextIO, TypeVar, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, deprecated\n\n__all__ = [\n    \"BASIC_FORMAT\",\n    \"BufferingFormatter\",\n    \"CRITICAL\",\n    \"DEBUG\",\n    \"ERROR\",\n    \"FATAL\",\n    \"FileHandler\",\n    \"Filter\",\n    \"Formatter\",\n    \"Handler\",\n    \"INFO\",\n    \"LogRecord\",\n    \"Logger\",\n    \"LoggerAdapter\",\n    \"NOTSET\",\n    \"NullHandler\",\n    \"StreamHandler\",\n    \"WARN\",\n    \"WARNING\",\n    \"addLevelName\",\n    \"basicConfig\",\n    \"captureWarnings\",\n    \"critical\",\n    \"debug\",\n    \"disable\",\n    \"error\",\n    \"exception\",\n    \"fatal\",\n    \"getLevelName\",\n    \"getLogger\",\n    \"getLoggerClass\",\n    \"info\",\n    \"log\",\n    \"makeLogRecord\",\n    \"setLoggerClass\",\n    \"shutdown\",\n    \"warning\",\n    \"getLogRecordFactory\",\n    \"setLogRecordFactory\",\n    \"lastResort\",\n    \"raiseExceptions\",\n    \"warn\",\n]\n\nif sys.version_info >= (3, 11):\n    __all__ += [\"getLevelNamesMapping\"]\nif sys.version_info >= (3, 12):\n    __all__ += [\"getHandlerByName\", \"getHandlerNames\"]\n\n_SysExcInfoType: TypeAlias = tuple[type[BaseException], BaseException, TracebackType | None] | tuple[None, None, None]\n_ExcInfoType: TypeAlias = None | bool | _SysExcInfoType | BaseException\n_ArgsType: TypeAlias = tuple[object, ...] | Mapping[str, object]\n_Level: TypeAlias = int | str\n_FormatStyle: TypeAlias = Literal[\"%\", \"{\", \"$\"]\n\nif sys.version_info >= (3, 12):\n    @type_check_only\n    class _SupportsFilter(Protocol):\n        def filter(self, record: LogRecord, /) -> bool | LogRecord: ...\n\n    _FilterType: TypeAlias = Filter | Callable[[LogRecord], bool | LogRecord] | _SupportsFilter\nelse:\n    @type_check_only\n    class _SupportsFilter(Protocol):\n        def filter(self, record: LogRecord, /) -> bool: ...\n\n    _FilterType: TypeAlias = Filter | Callable[[LogRecord], bool] | _SupportsFilter\n\nraiseExceptions: bool\nlogThreads: bool\nlogMultiprocessing: bool\nlogProcesses: bool\n_srcfile: str | None\n\ndef currentframe() -> FrameType: ...\n\n_levelToName: dict[int, str]\n_nameToLevel: dict[str, int]\n\nclass Filterer:\n    filters: list[_FilterType]\n    def addFilter(self, filter: _FilterType) -> None: ...\n    def removeFilter(self, filter: _FilterType) -> None: ...\n    if sys.version_info >= (3, 12):\n        def filter(self, record: LogRecord) -> bool | LogRecord: ...\n    else:\n        def filter(self, record: LogRecord) -> bool: ...\n\nclass Manager:  # undocumented\n    root: RootLogger\n    disable: int\n    emittedNoHandlerWarning: bool\n    loggerDict: dict[str, Logger | PlaceHolder]\n    loggerClass: type[Logger] | None\n    logRecordFactory: Callable[..., LogRecord] | None\n    def __init__(self, rootnode: RootLogger) -> None: ...\n    def getLogger(self, name: str) -> Logger: ...\n    def setLoggerClass(self, klass: type[Logger]) -> None: ...\n    def setLogRecordFactory(self, factory: Callable[..., LogRecord]) -> None: ...\n\nclass Logger(Filterer):\n    name: str  # undocumented\n    level: int  # undocumented\n    parent: Logger | None  # undocumented\n    propagate: bool\n    handlers: list[Handler]  # undocumented\n    disabled: bool  # undocumented\n    root: ClassVar[RootLogger]  # undocumented\n    manager: Manager  # undocumented\n    def __init__(self, name: str, level: _Level = 0) -> None: ...\n    def setLevel(self, level: _Level) -> None: ...\n    def isEnabledFor(self, level: int) -> bool: ...\n    def getEffectiveLevel(self) -> int: ...\n    def getChild(self, suffix: str) -> Self: ...  # see python/typing#980\n    if sys.version_info >= (3, 12):\n        def getChildren(self) -> set[Logger]: ...\n\n    def debug(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n    ) -> None: ...\n    def info(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n    ) -> None: ...\n    def warning(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n    ) -> None: ...\n    @deprecated(\"Deprecated since Python 3.3. Use `Logger.warning()` instead.\")\n    def warn(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n    ) -> None: ...\n    def error(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n    ) -> None: ...\n    def exception(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = True,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n    ) -> None: ...\n    def critical(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n    ) -> None: ...\n    def log(\n        self,\n        level: int,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n    ) -> None: ...\n    def _log(\n        self,\n        level: int,\n        msg: object,\n        args: _ArgsType,\n        exc_info: _ExcInfoType | None = None,\n        extra: Mapping[str, object] | None = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n    ) -> None: ...  # undocumented\n    fatal = critical\n    def addHandler(self, hdlr: Handler) -> None: ...\n    def removeHandler(self, hdlr: Handler) -> None: ...\n    def findCaller(self, stack_info: bool = False, stacklevel: int = 1) -> tuple[str, int, str, str | None]: ...\n    def handle(self, record: LogRecord) -> None: ...\n    def makeRecord(\n        self,\n        name: str,\n        level: int,\n        fn: str,\n        lno: int,\n        msg: object,\n        args: _ArgsType,\n        exc_info: _SysExcInfoType | None,\n        func: str | None = None,\n        extra: Mapping[str, object] | None = None,\n        sinfo: str | None = None,\n    ) -> LogRecord: ...\n    def hasHandlers(self) -> bool: ...\n    def callHandlers(self, record: LogRecord) -> None: ...  # undocumented\n\nCRITICAL: Final = 50\nFATAL: Final = CRITICAL\nERROR: Final = 40\nWARNING: Final = 30\nWARN: Final = WARNING\nINFO: Final = 20\nDEBUG: Final = 10\nNOTSET: Final = 0\n\nclass Handler(Filterer):\n    level: int  # undocumented\n    formatter: Formatter | None  # undocumented\n    lock: threading.Lock | None  # undocumented\n    name: str | None  # undocumented\n    def __init__(self, level: _Level = 0) -> None: ...\n    def get_name(self) -> str: ...  # undocumented\n    def set_name(self, name: str) -> None: ...  # undocumented\n    def createLock(self) -> None: ...\n    def acquire(self) -> None: ...\n    def release(self) -> None: ...\n    def setLevel(self, level: _Level) -> None: ...\n    def setFormatter(self, fmt: Formatter | None) -> None: ...\n    def flush(self) -> None: ...\n    def close(self) -> None: ...\n    def handle(self, record: LogRecord) -> bool: ...\n    def handleError(self, record: LogRecord) -> None: ...\n    def format(self, record: LogRecord) -> str: ...\n    def emit(self, record: LogRecord) -> None: ...\n\nif sys.version_info >= (3, 12):\n    def getHandlerByName(name: str) -> Handler | None: ...\n    def getHandlerNames() -> frozenset[str]: ...\n\nclass Formatter:\n    converter: Callable[[float | None], struct_time]\n    _fmt: str | None  # undocumented\n    datefmt: str | None  # undocumented\n    _style: PercentStyle  # undocumented\n    default_time_format: str\n    default_msec_format: str | None\n\n    if sys.version_info >= (3, 10):\n        def __init__(\n            self,\n            fmt: str | None = None,\n            datefmt: str | None = None,\n            style: _FormatStyle = \"%\",\n            validate: bool = True,\n            *,\n            defaults: Mapping[str, Any] | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self, fmt: str | None = None, datefmt: str | None = None, style: _FormatStyle = \"%\", validate: bool = True\n        ) -> None: ...\n\n    def format(self, record: LogRecord) -> str: ...\n    def formatTime(self, record: LogRecord, datefmt: str | None = None) -> str: ...\n    def formatException(self, ei: _SysExcInfoType) -> str: ...\n    def formatMessage(self, record: LogRecord) -> str: ...  # undocumented\n    def formatStack(self, stack_info: str) -> str: ...\n    def usesTime(self) -> bool: ...  # undocumented\n\nclass BufferingFormatter:\n    linefmt: Formatter\n    def __init__(self, linefmt: Formatter | None = None) -> None: ...\n    def formatHeader(self, records: Sequence[LogRecord]) -> str: ...\n    def formatFooter(self, records: Sequence[LogRecord]) -> str: ...\n    def format(self, records: Sequence[LogRecord]) -> str: ...\n\nclass Filter:\n    name: str  # undocumented\n    nlen: int  # undocumented\n    def __init__(self, name: str = \"\") -> None: ...\n    if sys.version_info >= (3, 12):\n        def filter(self, record: LogRecord) -> bool | LogRecord: ...\n    else:\n        def filter(self, record: LogRecord) -> bool: ...\n\nclass LogRecord:\n    # args can be set to None by logging.handlers.QueueHandler\n    # (see https://bugs.python.org/issue44473)\n    args: _ArgsType | None\n    asctime: str\n    created: float\n    exc_info: _SysExcInfoType | None\n    exc_text: str | None\n    filename: str\n    funcName: str\n    levelname: str\n    levelno: int\n    lineno: int\n    module: str\n    msecs: float\n    # Only created when logging.Formatter.format is called. See #6132.\n    message: str\n    msg: str | Any  # The runtime accepts any object, but will be a str in 99% of cases\n    name: str\n    pathname: str\n    process: int | None\n    processName: str | None\n    relativeCreated: float\n    stack_info: str | None\n    thread: int | None\n    threadName: str | None\n    if sys.version_info >= (3, 12):\n        taskName: str | None\n\n    def __init__(\n        self,\n        name: str,\n        level: int,\n        pathname: str,\n        lineno: int,\n        msg: object,\n        args: _ArgsType | None,\n        exc_info: _SysExcInfoType | None,\n        func: str | None = None,\n        sinfo: str | None = None,\n    ) -> None: ...\n    def getMessage(self) -> str: ...\n    # Allows setting contextual information on LogRecord objects as per the docs, see #7833\n    def __setattr__(self, name: str, value: Any, /) -> None: ...\n\n_L = TypeVar(\"_L\", bound=Logger | LoggerAdapter[Any])\n\nclass LoggerAdapter(Generic[_L]):\n    logger: _L\n    manager: Manager  # undocumented\n\n    if sys.version_info >= (3, 13):\n        def __init__(self, logger: _L, extra: Mapping[str, object] | None = None, merge_extra: bool = False) -> None: ...\n    elif sys.version_info >= (3, 10):\n        def __init__(self, logger: _L, extra: Mapping[str, object] | None = None) -> None: ...\n    else:\n        def __init__(self, logger: _L, extra: Mapping[str, object]) -> None: ...\n\n    if sys.version_info >= (3, 10):\n        extra: Mapping[str, object] | None\n    else:\n        extra: Mapping[str, object]\n\n    if sys.version_info >= (3, 13):\n        merge_extra: bool\n\n    def process(self, msg: Any, kwargs: MutableMapping[str, Any]) -> tuple[Any, MutableMapping[str, Any]]: ...\n    def debug(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n        **kwargs: object,\n    ) -> None: ...\n    def info(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n        **kwargs: object,\n    ) -> None: ...\n    def warning(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n        **kwargs: object,\n    ) -> None: ...\n    @deprecated(\"Deprecated since Python 3.3. Use `LoggerAdapter.warning()` instead.\")\n    def warn(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n        **kwargs: object,\n    ) -> None: ...\n    def error(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n        **kwargs: object,\n    ) -> None: ...\n    def exception(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = True,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n        **kwargs: object,\n    ) -> None: ...\n    def critical(\n        self,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n        **kwargs: object,\n    ) -> None: ...\n    def log(\n        self,\n        level: int,\n        msg: object,\n        *args: object,\n        exc_info: _ExcInfoType = None,\n        stack_info: bool = False,\n        stacklevel: int = 1,\n        extra: Mapping[str, object] | None = None,\n        **kwargs: object,\n    ) -> None: ...\n    def isEnabledFor(self, level: int) -> bool: ...\n    def getEffectiveLevel(self) -> int: ...\n    def setLevel(self, level: _Level) -> None: ...\n    def hasHandlers(self) -> bool: ...\n    if sys.version_info >= (3, 11):\n        def _log(\n            self,\n            level: int,\n            msg: object,\n            args: _ArgsType,\n            *,\n            exc_info: _ExcInfoType | None = None,\n            extra: Mapping[str, object] | None = None,\n            stack_info: bool = False,\n        ) -> None: ...  # undocumented\n    else:\n        def _log(\n            self,\n            level: int,\n            msg: object,\n            args: _ArgsType,\n            exc_info: _ExcInfoType | None = None,\n            extra: Mapping[str, object] | None = None,\n            stack_info: bool = False,\n        ) -> None: ...  # undocumented\n\n    @property\n    def name(self) -> str: ...  # undocumented\n    if sys.version_info >= (3, 11):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\ndef getLogger(name: str | None = None) -> Logger: ...\ndef getLoggerClass() -> type[Logger]: ...\ndef getLogRecordFactory() -> Callable[..., LogRecord]: ...\ndef debug(\n    msg: object,\n    *args: object,\n    exc_info: _ExcInfoType = None,\n    stack_info: bool = False,\n    stacklevel: int = 1,\n    extra: Mapping[str, object] | None = None,\n) -> None: ...\ndef info(\n    msg: object,\n    *args: object,\n    exc_info: _ExcInfoType = None,\n    stack_info: bool = False,\n    stacklevel: int = 1,\n    extra: Mapping[str, object] | None = None,\n) -> None: ...\ndef warning(\n    msg: object,\n    *args: object,\n    exc_info: _ExcInfoType = None,\n    stack_info: bool = False,\n    stacklevel: int = 1,\n    extra: Mapping[str, object] | None = None,\n) -> None: ...\n@deprecated(\"Deprecated since Python 3.3. Use `warning()` instead.\")\ndef warn(\n    msg: object,\n    *args: object,\n    exc_info: _ExcInfoType = None,\n    stack_info: bool = False,\n    stacklevel: int = 1,\n    extra: Mapping[str, object] | None = None,\n) -> None: ...\ndef error(\n    msg: object,\n    *args: object,\n    exc_info: _ExcInfoType = None,\n    stack_info: bool = False,\n    stacklevel: int = 1,\n    extra: Mapping[str, object] | None = None,\n) -> None: ...\ndef critical(\n    msg: object,\n    *args: object,\n    exc_info: _ExcInfoType = None,\n    stack_info: bool = False,\n    stacklevel: int = 1,\n    extra: Mapping[str, object] | None = None,\n) -> None: ...\ndef exception(\n    msg: object,\n    *args: object,\n    exc_info: _ExcInfoType = True,\n    stack_info: bool = False,\n    stacklevel: int = 1,\n    extra: Mapping[str, object] | None = None,\n) -> None: ...\ndef log(\n    level: int,\n    msg: object,\n    *args: object,\n    exc_info: _ExcInfoType = None,\n    stack_info: bool = False,\n    stacklevel: int = 1,\n    extra: Mapping[str, object] | None = None,\n) -> None: ...\n\nfatal = critical\n\ndef disable(level: int = 50) -> None: ...\ndef addLevelName(level: int, levelName: str) -> None: ...\n@overload\ndef getLevelName(level: int) -> str: ...\n@overload\n@deprecated(\"The str -> int case is considered a mistake.\")\ndef getLevelName(level: str) -> Any: ...\n\nif sys.version_info >= (3, 11):\n    def getLevelNamesMapping() -> dict[str, int]: ...\n\ndef makeLogRecord(dict: Mapping[str, object]) -> LogRecord: ...\n@overload  # handlers is non-None\ndef basicConfig(\n    *,\n    format: str = ...,  # default value depends on the value of `style`\n    datefmt: str | None = None,\n    style: _FormatStyle = \"%\",\n    level: _Level | None = None,\n    handlers: Iterable[Handler],\n    force: bool | None = False,\n) -> None: ...\n@overload  # handlers is None, filename is passed (but possibly None)\ndef basicConfig(\n    *,\n    filename: StrPath | None,\n    filemode: str = \"a\",\n    format: str = ...,  # default value depends on the value of `style`\n    datefmt: str | None = None,\n    style: _FormatStyle = \"%\",\n    level: _Level | None = None,\n    handlers: None = None,\n    force: bool | None = False,\n    encoding: str | None = None,\n    errors: str | None = \"backslashreplace\",\n) -> None: ...\n@overload  # handlers is None, filename is not passed\ndef basicConfig(\n    *,\n    format: str = ...,  # default value depends on the value of `style`\n    datefmt: str | None = None,\n    style: _FormatStyle = \"%\",\n    level: _Level | None = None,\n    stream: SupportsWrite[str] | None = None,\n    handlers: None = None,\n    force: bool | None = False,\n) -> None: ...\ndef shutdown(handlerList: Sequence[Any] = ...) -> None: ...  # handlerList is undocumented\ndef setLoggerClass(klass: type[Logger]) -> None: ...\ndef captureWarnings(capture: bool) -> None: ...\ndef setLogRecordFactory(factory: Callable[..., LogRecord]) -> None: ...\n\nlastResort: Handler | None\n\n_StreamT = TypeVar(\"_StreamT\", bound=SupportsWrite[str])\n\nclass StreamHandler(Handler, Generic[_StreamT]):\n    stream: _StreamT  # undocumented\n    terminator: str\n    @overload\n    def __init__(self: StreamHandler[TextIO], stream: None = None) -> None: ...\n    @overload\n    def __init__(self: StreamHandler[_StreamT], stream: _StreamT) -> None: ...  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n    def setStream(self, stream: _StreamT) -> _StreamT | None: ...\n    if sys.version_info >= (3, 11):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass FileHandler(StreamHandler[TextIOWrapper]):\n    baseFilename: str  # undocumented\n    mode: str  # undocumented\n    encoding: str | None  # undocumented\n    delay: bool  # undocumented\n    errors: str | None  # undocumented\n    stream: TextIOWrapper | None  # type: ignore[assignment]  # None when delay=True or after close()\n    def __init__(\n        self, filename: StrPath, mode: str = \"a\", encoding: str | None = None, delay: bool = False, errors: str | None = None\n    ) -> None: ...\n    def _open(self) -> TextIOWrapper: ...  # undocumented\n\nclass NullHandler(Handler): ...\n\nclass PlaceHolder:  # undocumented\n    loggerMap: dict[Logger, None]\n    def __init__(self, alogger: Logger) -> None: ...\n    def append(self, alogger: Logger) -> None: ...\n\n# Below aren't in module docs but still visible\n\nclass RootLogger(Logger):\n    def __init__(self, level: int) -> None: ...\n\nroot: RootLogger\n\nclass PercentStyle:  # undocumented\n    default_format: str\n    asctime_format: str\n    asctime_search: str\n    validation_pattern: Pattern[str]\n    _fmt: str\n    if sys.version_info >= (3, 10):\n        def __init__(self, fmt: str, *, defaults: Mapping[str, Any] | None = None) -> None: ...\n    else:\n        def __init__(self, fmt: str) -> None: ...\n\n    def usesTime(self) -> bool: ...\n    def validate(self) -> None: ...\n    def format(self, record: Any) -> str: ...\n\nclass StrFormatStyle(PercentStyle):  # undocumented\n    fmt_spec: Pattern[str]\n    field_spec: Pattern[str]\n\nclass StringTemplateStyle(PercentStyle):  # undocumented\n    _tpl: Template\n\n_STYLES: Final[dict[str, tuple[PercentStyle, str]]]\n\nBASIC_FORMAT: Final = \"%(levelname)s:%(name)s:%(message)s\"\n"
  },
  {
    "path": "mypy/typeshed/stdlib/logging/config.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath\nfrom collections.abc import Callable, Hashable, Iterable, Mapping, Sequence\nfrom configparser import RawConfigParser\nfrom re import Pattern\nfrom threading import Thread\nfrom typing import IO, Any, Final, Literal, SupportsIndex, TypedDict, overload, type_check_only\nfrom typing_extensions import Required, TypeAlias, disjoint_base\n\nfrom . import Filter, Filterer, Formatter, Handler, Logger, _FilterType, _FormatStyle, _Level\n\nDEFAULT_LOGGING_CONFIG_PORT: Final = 9030\nRESET_ERROR: Final[int]  # undocumented\nIDENTIFIER: Final[Pattern[str]]  # undocumented\n\nif sys.version_info >= (3, 11):\n    @type_check_only\n    class _RootLoggerConfiguration(TypedDict, total=False):\n        level: _Level\n        filters: Sequence[str | _FilterType]\n        handlers: Sequence[str]\n\nelse:\n    @type_check_only\n    class _RootLoggerConfiguration(TypedDict, total=False):\n        level: _Level\n        filters: Sequence[str]\n        handlers: Sequence[str]\n\n@type_check_only\nclass _LoggerConfiguration(_RootLoggerConfiguration, TypedDict, total=False):\n    propagate: bool\n\n_FormatterConfigurationTypedDict = TypedDict(\n    \"_FormatterConfigurationTypedDict\", {\"class\": str, \"format\": str, \"datefmt\": str, \"style\": _FormatStyle}, total=False\n)\n\n@type_check_only\nclass _FilterConfigurationTypedDict(TypedDict):\n    name: str\n\n# Formatter and filter configs can specify custom factories via the special `()` key.\n# If that is the case, the dictionary can contain any additional keys\n# https://docs.python.org/3/library/logging.config.html#user-defined-objects\n_FormatterConfiguration: TypeAlias = _FormatterConfigurationTypedDict | dict[str, Any]\n_FilterConfiguration: TypeAlias = _FilterConfigurationTypedDict | dict[str, Any]\n# Handler config can have additional keys even when not providing a custom factory so we just use `dict`.\n_HandlerConfiguration: TypeAlias = dict[str, Any]\n\n@type_check_only\nclass _DictConfigArgs(TypedDict, total=False):\n    version: Required[Literal[1]]\n    formatters: dict[str, _FormatterConfiguration]\n    filters: dict[str, _FilterConfiguration]\n    handlers: dict[str, _HandlerConfiguration]\n    loggers: dict[str, _LoggerConfiguration]\n    root: _RootLoggerConfiguration\n    incremental: bool\n    disable_existing_loggers: bool\n\n# Accept dict[str, Any] to avoid false positives if called with a dict\n# type, since dict types are not compatible with TypedDicts.\n#\n# Also accept a TypedDict type, to allow callers to use TypedDict\n# types, and for somewhat stricter type checking of dict literals.\ndef dictConfig(config: _DictConfigArgs | dict[str, Any]) -> None: ...\n\nif sys.version_info >= (3, 10):\n    def fileConfig(\n        fname: StrOrBytesPath | IO[str] | RawConfigParser,\n        defaults: Mapping[str, str] | None = None,\n        disable_existing_loggers: bool = True,\n        encoding: str | None = None,\n    ) -> None: ...\n\nelse:\n    def fileConfig(\n        fname: StrOrBytesPath | IO[str] | RawConfigParser,\n        defaults: Mapping[str, str] | None = None,\n        disable_existing_loggers: bool = True,\n    ) -> None: ...\n\ndef valid_ident(s: str) -> Literal[True]: ...  # undocumented\ndef listen(port: int = 9030, verify: Callable[[bytes], bytes | None] | None = None) -> Thread: ...\ndef stopListening() -> None: ...\n\nclass ConvertingMixin:  # undocumented\n    def convert_with_key(self, key: Any, value: Any, replace: bool = True) -> Any: ...\n    def convert(self, value: Any) -> Any: ...\n\nclass ConvertingDict(dict[Hashable, Any], ConvertingMixin):  # undocumented\n    def __getitem__(self, key: Hashable) -> Any: ...\n    def get(self, key: Hashable, default: Any = None) -> Any: ...\n    def pop(self, key: Hashable, default: Any = None) -> Any: ...\n\nclass ConvertingList(list[Any], ConvertingMixin):  # undocumented\n    @overload\n    def __getitem__(self, key: SupportsIndex) -> Any: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None]) -> Any: ...\n    def pop(self, idx: SupportsIndex = -1) -> Any: ...\n\nif sys.version_info >= (3, 12):\n    class ConvertingTuple(tuple[Any, ...], ConvertingMixin):  # undocumented\n        @overload\n        def __getitem__(self, key: SupportsIndex) -> Any: ...\n        @overload\n        def __getitem__(self, key: slice[SupportsIndex | None]) -> Any: ...\n\nelse:\n    @disjoint_base\n    class ConvertingTuple(tuple[Any, ...], ConvertingMixin):  # undocumented\n        @overload\n        def __getitem__(self, key: SupportsIndex) -> Any: ...\n        @overload\n        def __getitem__(self, key: slice[SupportsIndex | None]) -> Any: ...\n\nclass BaseConfigurator:\n    CONVERT_PATTERN: Pattern[str]\n    WORD_PATTERN: Pattern[str]\n    DOT_PATTERN: Pattern[str]\n    INDEX_PATTERN: Pattern[str]\n    DIGIT_PATTERN: Pattern[str]\n    value_converters: dict[str, str]\n    importer: Callable[..., Any]\n\n    config: dict[str, Any]  # undocumented\n\n    def __init__(self, config: _DictConfigArgs | dict[str, Any]) -> None: ...\n    def resolve(self, s: str) -> Any: ...\n    def ext_convert(self, value: str) -> Any: ...\n    def cfg_convert(self, value: str) -> Any: ...\n    def convert(self, value: Any) -> Any: ...\n    def configure_custom(self, config: dict[str, Any]) -> Any: ...\n    def as_tuple(self, value: list[Any] | tuple[Any, ...]) -> tuple[Any, ...]: ...\n\nclass DictConfigurator(BaseConfigurator):\n    def configure(self) -> None: ...  # undocumented\n    def configure_formatter(self, config: _FormatterConfiguration) -> Formatter | Any: ...  # undocumented\n    def configure_filter(self, config: _FilterConfiguration) -> Filter | Any: ...  # undocumented\n    def add_filters(self, filterer: Filterer, filters: Iterable[_FilterType]) -> None: ...  # undocumented\n    def configure_handler(self, config: _HandlerConfiguration) -> Handler | Any: ...  # undocumented\n    def add_handlers(self, logger: Logger, handlers: Iterable[str]) -> None: ...  # undocumented\n    def common_logger_config(\n        self, logger: Logger, config: _LoggerConfiguration, incremental: bool = False\n    ) -> None: ...  # undocumented\n    def configure_logger(self, name: str, config: _LoggerConfiguration, incremental: bool = False) -> None: ...  # undocumented\n    def configure_root(self, config: _LoggerConfiguration, incremental: bool = False) -> None: ...  # undocumented\n\ndictConfigClass = DictConfigurator\n"
  },
  {
    "path": "mypy/typeshed/stdlib/logging/handlers.pyi",
    "content": "import datetime\nimport http.client\nimport ssl\nimport sys\nfrom _typeshed import ReadableBuffer, StrPath\nfrom collections.abc import Callable\nfrom logging import FileHandler, Handler, LogRecord\nfrom re import Pattern\nfrom socket import SocketKind, socket\nfrom threading import Thread\nfrom types import TracebackType\nfrom typing import Any, ClassVar, Final, Protocol, TypeVar, type_check_only\nfrom typing_extensions import Self\n\n_T = TypeVar(\"_T\")\n\nDEFAULT_TCP_LOGGING_PORT: Final = 9020\nDEFAULT_UDP_LOGGING_PORT: Final = 9021\nDEFAULT_HTTP_LOGGING_PORT: Final = 9022\nDEFAULT_SOAP_LOGGING_PORT: Final = 9023\nSYSLOG_UDP_PORT: Final = 514\nSYSLOG_TCP_PORT: Final = 514\n\nclass WatchedFileHandler(FileHandler):\n    dev: int  # undocumented\n    ino: int  # undocumented\n    def __init__(\n        self, filename: StrPath, mode: str = \"a\", encoding: str | None = None, delay: bool = False, errors: str | None = None\n    ) -> None: ...\n    def _statstream(self) -> None: ...  # undocumented\n    def reopenIfNeeded(self) -> None: ...\n\nclass BaseRotatingHandler(FileHandler):\n    namer: Callable[[str], str] | None\n    rotator: Callable[[str, str], None] | None\n    def __init__(\n        self, filename: StrPath, mode: str, encoding: str | None = None, delay: bool = False, errors: str | None = None\n    ) -> None: ...\n    def rotation_filename(self, default_name: str) -> str: ...\n    def rotate(self, source: str, dest: str) -> None: ...\n\nclass RotatingFileHandler(BaseRotatingHandler):\n    maxBytes: int  # undocumented\n    backupCount: int  # undocumented\n    def __init__(\n        self,\n        filename: StrPath,\n        mode: str = \"a\",\n        maxBytes: int = 0,\n        backupCount: int = 0,\n        encoding: str | None = None,\n        delay: bool = False,\n        errors: str | None = None,\n    ) -> None: ...\n    def doRollover(self) -> None: ...\n    def shouldRollover(self, record: LogRecord) -> int: ...  # undocumented\n\nclass TimedRotatingFileHandler(BaseRotatingHandler):\n    when: str  # undocumented\n    backupCount: int  # undocumented\n    utc: bool  # undocumented\n    atTime: datetime.time | None  # undocumented\n    interval: int  # undocumented\n    suffix: str  # undocumented\n    dayOfWeek: int  # undocumented\n    rolloverAt: int  # undocumented\n    extMatch: Pattern[str]  # undocumented\n    def __init__(\n        self,\n        filename: StrPath,\n        when: str = \"h\",\n        interval: int = 1,\n        backupCount: int = 0,\n        encoding: str | None = None,\n        delay: bool = False,\n        utc: bool = False,\n        atTime: datetime.time | None = None,\n        errors: str | None = None,\n    ) -> None: ...\n    def doRollover(self) -> None: ...\n    def shouldRollover(self, record: LogRecord) -> int: ...  # undocumented\n    def computeRollover(self, currentTime: int) -> int: ...  # undocumented\n    def getFilesToDelete(self) -> list[str]: ...  # undocumented\n\nclass SocketHandler(Handler):\n    host: str  # undocumented\n    port: int | None  # undocumented\n    address: tuple[str, int] | str  # undocumented\n    sock: socket | None  # undocumented\n    closeOnError: bool  # undocumented\n    retryTime: float | None  # undocumented\n    retryStart: float  # undocumented\n    retryFactor: float  # undocumented\n    retryMax: float  # undocumented\n    def __init__(self, host: str, port: int | None) -> None: ...\n    def makeSocket(self, timeout: float = 1) -> socket: ...  # timeout is undocumented\n    def makePickle(self, record: LogRecord) -> bytes: ...\n    def send(self, s: ReadableBuffer) -> None: ...\n    def createSocket(self) -> None: ...\n\nclass DatagramHandler(SocketHandler):\n    def makeSocket(self) -> socket: ...  # type: ignore[override]\n\nclass SysLogHandler(Handler):\n    LOG_EMERG: int\n    LOG_ALERT: int\n    LOG_CRIT: int\n    LOG_ERR: int\n    LOG_WARNING: int\n    LOG_NOTICE: int\n    LOG_INFO: int\n    LOG_DEBUG: int\n\n    LOG_KERN: int\n    LOG_USER: int\n    LOG_MAIL: int\n    LOG_DAEMON: int\n    LOG_AUTH: int\n    LOG_SYSLOG: int\n    LOG_LPR: int\n    LOG_NEWS: int\n    LOG_UUCP: int\n    LOG_CRON: int\n    LOG_AUTHPRIV: int\n    LOG_FTP: int\n    LOG_NTP: int\n    LOG_SECURITY: int\n    LOG_CONSOLE: int\n    LOG_SOLCRON: int\n    LOG_LOCAL0: int\n    LOG_LOCAL1: int\n    LOG_LOCAL2: int\n    LOG_LOCAL3: int\n    LOG_LOCAL4: int\n    LOG_LOCAL5: int\n    LOG_LOCAL6: int\n    LOG_LOCAL7: int\n    address: tuple[str, int] | str  # undocumented\n    unixsocket: bool  # undocumented\n    socktype: SocketKind  # undocumented\n    ident: str  # undocumented\n    append_nul: bool  # undocumented\n    facility: int  # undocumented\n    priority_names: ClassVar[dict[str, int]]  # undocumented\n    facility_names: ClassVar[dict[str, int]]  # undocumented\n    priority_map: ClassVar[dict[str, str]]  # undocumented\n    if sys.version_info >= (3, 14):\n        timeout: float | None\n        def __init__(\n            self,\n            address: tuple[str, int] | str = (\"localhost\", 514),\n            facility: str | int = 1,\n            socktype: SocketKind | None = None,\n            timeout: float | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self, address: tuple[str, int] | str = (\"localhost\", 514), facility: str | int = 1, socktype: SocketKind | None = None\n        ) -> None: ...\n    if sys.version_info >= (3, 11):\n        def createSocket(self) -> None: ...\n\n    def encodePriority(self, facility: int | str, priority: int | str) -> int: ...\n    def mapPriority(self, levelName: str) -> str: ...\n\nclass NTEventLogHandler(Handler):\n    def __init__(self, appname: str, dllname: str | None = None, logtype: str = \"Application\") -> None: ...\n    def getEventCategory(self, record: LogRecord) -> int: ...\n    # TODO: correct return value?\n    def getEventType(self, record: LogRecord) -> int: ...\n    def getMessageID(self, record: LogRecord) -> int: ...\n\nclass SMTPHandler(Handler):\n    mailhost: str  # undocumented\n    mailport: int | None  # undocumented\n    username: str | None  # undocumented\n    # password only exists as an attribute if passed credentials is a tuple or list\n    password: str  # undocumented\n    fromaddr: str  # undocumented\n    toaddrs: list[str]  # undocumented\n    subject: str  # undocumented\n    secure: tuple[()] | tuple[str] | tuple[str, str] | None  # undocumented\n    timeout: float  # undocumented\n    def __init__(\n        self,\n        mailhost: str | tuple[str, int],\n        fromaddr: str,\n        toaddrs: str | list[str],\n        subject: str,\n        credentials: tuple[str, str] | None = None,\n        secure: tuple[()] | tuple[str] | tuple[str, str] | None = None,\n        timeout: float = 5.0,\n    ) -> None: ...\n    def getSubject(self, record: LogRecord) -> str: ...\n\nclass BufferingHandler(Handler):\n    capacity: int  # undocumented\n    buffer: list[LogRecord]  # undocumented\n    def __init__(self, capacity: int) -> None: ...\n    def shouldFlush(self, record: LogRecord) -> bool: ...\n\nclass MemoryHandler(BufferingHandler):\n    flushLevel: int  # undocumented\n    target: Handler | None  # undocumented\n    flushOnClose: bool  # undocumented\n    def __init__(self, capacity: int, flushLevel: int = 40, target: Handler | None = None, flushOnClose: bool = True) -> None: ...\n    def setTarget(self, target: Handler | None) -> None: ...\n\nclass HTTPHandler(Handler):\n    host: str  # undocumented\n    url: str  # undocumented\n    method: str  # undocumented\n    secure: bool  # undocumented\n    credentials: tuple[str, str] | None  # undocumented\n    context: ssl.SSLContext | None  # undocumented\n    def __init__(\n        self,\n        host: str,\n        url: str,\n        method: str = \"GET\",\n        secure: bool = False,\n        credentials: tuple[str, str] | None = None,\n        context: ssl.SSLContext | None = None,\n    ) -> None: ...\n    def mapLogRecord(self, record: LogRecord) -> dict[str, Any]: ...\n    def getConnection(self, host: str, secure: bool) -> http.client.HTTPConnection: ...  # undocumented\n\n@type_check_only\nclass _QueueLike(Protocol[_T]):\n    def get(self) -> _T: ...\n    def put_nowait(self, item: _T, /) -> None: ...\n\nclass QueueHandler(Handler):\n    queue: _QueueLike[Any]\n    def __init__(self, queue: _QueueLike[Any]) -> None: ...\n    def prepare(self, record: LogRecord) -> Any: ...\n    def enqueue(self, record: LogRecord) -> None: ...\n    if sys.version_info >= (3, 12):\n        listener: QueueListener | None\n\nclass QueueListener:\n    handlers: tuple[Handler, ...]  # undocumented\n    respect_handler_level: bool  # undocumented\n    queue: _QueueLike[Any]  # undocumented\n    _thread: Thread | None  # undocumented\n    def __init__(self, queue: _QueueLike[Any], *handlers: Handler, respect_handler_level: bool = False) -> None: ...\n    def dequeue(self, block: bool) -> LogRecord: ...\n    def prepare(self, record: LogRecord) -> Any: ...\n    def start(self) -> None: ...\n    def stop(self) -> None: ...\n    def enqueue_sentinel(self) -> None: ...\n    def handle(self, record: LogRecord) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def __enter__(self) -> Self: ...\n        def __exit__(\n            self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None\n        ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/lzma.pyi",
    "content": "import sys\nfrom _lzma import (\n    CHECK_CRC32 as CHECK_CRC32,\n    CHECK_CRC64 as CHECK_CRC64,\n    CHECK_ID_MAX as CHECK_ID_MAX,\n    CHECK_NONE as CHECK_NONE,\n    CHECK_SHA256 as CHECK_SHA256,\n    CHECK_UNKNOWN as CHECK_UNKNOWN,\n    FILTER_ARM as FILTER_ARM,\n    FILTER_ARMTHUMB as FILTER_ARMTHUMB,\n    FILTER_DELTA as FILTER_DELTA,\n    FILTER_IA64 as FILTER_IA64,\n    FILTER_LZMA1 as FILTER_LZMA1,\n    FILTER_LZMA2 as FILTER_LZMA2,\n    FILTER_POWERPC as FILTER_POWERPC,\n    FILTER_SPARC as FILTER_SPARC,\n    FILTER_X86 as FILTER_X86,\n    FORMAT_ALONE as FORMAT_ALONE,\n    FORMAT_AUTO as FORMAT_AUTO,\n    FORMAT_RAW as FORMAT_RAW,\n    FORMAT_XZ as FORMAT_XZ,\n    MF_BT2 as MF_BT2,\n    MF_BT3 as MF_BT3,\n    MF_BT4 as MF_BT4,\n    MF_HC3 as MF_HC3,\n    MF_HC4 as MF_HC4,\n    MODE_FAST as MODE_FAST,\n    MODE_NORMAL as MODE_NORMAL,\n    PRESET_DEFAULT as PRESET_DEFAULT,\n    PRESET_EXTREME as PRESET_EXTREME,\n    LZMACompressor as LZMACompressor,\n    LZMADecompressor as LZMADecompressor,\n    LZMAError as LZMAError,\n    _FilterChain,\n    is_check_supported as is_check_supported,\n)\nfrom _typeshed import ReadableBuffer, StrOrBytesPath\nfrom io import TextIOWrapper\nfrom typing import IO, Literal, overload\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 14):\n    from compression._common._streams import BaseStream\nelse:\n    from _compression import BaseStream\n\n__all__ = [\n    \"CHECK_NONE\",\n    \"CHECK_CRC32\",\n    \"CHECK_CRC64\",\n    \"CHECK_SHA256\",\n    \"CHECK_ID_MAX\",\n    \"CHECK_UNKNOWN\",\n    \"FILTER_LZMA1\",\n    \"FILTER_LZMA2\",\n    \"FILTER_DELTA\",\n    \"FILTER_X86\",\n    \"FILTER_IA64\",\n    \"FILTER_ARM\",\n    \"FILTER_ARMTHUMB\",\n    \"FILTER_POWERPC\",\n    \"FILTER_SPARC\",\n    \"FORMAT_AUTO\",\n    \"FORMAT_XZ\",\n    \"FORMAT_ALONE\",\n    \"FORMAT_RAW\",\n    \"MF_HC3\",\n    \"MF_HC4\",\n    \"MF_BT2\",\n    \"MF_BT3\",\n    \"MF_BT4\",\n    \"MODE_FAST\",\n    \"MODE_NORMAL\",\n    \"PRESET_DEFAULT\",\n    \"PRESET_EXTREME\",\n    \"LZMACompressor\",\n    \"LZMADecompressor\",\n    \"LZMAFile\",\n    \"LZMAError\",\n    \"open\",\n    \"compress\",\n    \"decompress\",\n    \"is_check_supported\",\n]\n\n_OpenBinaryWritingMode: TypeAlias = Literal[\"w\", \"wb\", \"x\", \"xb\", \"a\", \"ab\"]\n_OpenTextWritingMode: TypeAlias = Literal[\"wt\", \"xt\", \"at\"]\n\n_PathOrFile: TypeAlias = StrOrBytesPath | IO[bytes]\n\nclass LZMAFile(BaseStream, IO[bytes]):  # type: ignore[misc]  # incompatible definitions of writelines in the base classes\n    def __init__(\n        self,\n        filename: _PathOrFile | None = None,\n        mode: str = \"r\",\n        *,\n        format: int | None = None,\n        check: int = -1,\n        preset: int | None = None,\n        filters: _FilterChain | None = None,\n    ) -> None: ...\n    def __enter__(self) -> Self: ...\n    def peek(self, size: int = -1) -> bytes: ...\n    def read(self, size: int | None = -1) -> bytes: ...\n    def read1(self, size: int = -1) -> bytes: ...\n    def readline(self, size: int | None = -1) -> bytes: ...\n    def write(self, data: ReadableBuffer) -> int: ...\n    def seek(self, offset: int, whence: int = 0) -> int: ...\n\n@overload\ndef open(\n    filename: _PathOrFile,\n    mode: Literal[\"r\", \"rb\"] = \"rb\",\n    *,\n    format: int | None = None,\n    check: Literal[-1] = -1,\n    preset: None = None,\n    filters: _FilterChain | None = None,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n) -> LZMAFile: ...\n@overload\ndef open(\n    filename: _PathOrFile,\n    mode: _OpenBinaryWritingMode,\n    *,\n    format: int | None = None,\n    check: int = -1,\n    preset: int | None = None,\n    filters: _FilterChain | None = None,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n) -> LZMAFile: ...\n@overload\ndef open(\n    filename: StrOrBytesPath,\n    mode: Literal[\"rt\"],\n    *,\n    format: int | None = None,\n    check: Literal[-1] = -1,\n    preset: None = None,\n    filters: _FilterChain | None = None,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> TextIOWrapper: ...\n@overload\ndef open(\n    filename: StrOrBytesPath,\n    mode: _OpenTextWritingMode,\n    *,\n    format: int | None = None,\n    check: int = -1,\n    preset: int | None = None,\n    filters: _FilterChain | None = None,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> TextIOWrapper: ...\n@overload\ndef open(\n    filename: _PathOrFile,\n    mode: str,\n    *,\n    format: int | None = None,\n    check: int = -1,\n    preset: int | None = None,\n    filters: _FilterChain | None = None,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n) -> LZMAFile | TextIOWrapper: ...\ndef compress(\n    data: ReadableBuffer, format: int = 1, check: int = -1, preset: int | None = None, filters: _FilterChain | None = None\n) -> bytes: ...\ndef decompress(\n    data: ReadableBuffer, format: int = 0, memlimit: int | None = None, filters: _FilterChain | None = None\n) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/mailbox.pyi",
    "content": "import email.message\nimport io\nimport sys\nfrom _typeshed import StrPath, SupportsNoArgReadline, SupportsRead\nfrom abc import ABCMeta, abstractmethod\nfrom collections.abc import Callable, Iterable, Iterator, Mapping, Sequence\nfrom email._policybase import _MessageT\nfrom types import GenericAlias, TracebackType\nfrom typing import IO, Any, AnyStr, Generic, Literal, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\n    \"Mailbox\",\n    \"Maildir\",\n    \"mbox\",\n    \"MH\",\n    \"Babyl\",\n    \"MMDF\",\n    \"Message\",\n    \"MaildirMessage\",\n    \"mboxMessage\",\n    \"MHMessage\",\n    \"BabylMessage\",\n    \"MMDFMessage\",\n    \"Error\",\n    \"NoSuchMailboxError\",\n    \"NotEmptyError\",\n    \"ExternalClashError\",\n    \"FormatError\",\n]\n\n_T = TypeVar(\"_T\")\n\n@type_check_only\nclass _SupportsReadAndReadline(SupportsRead[bytes], SupportsNoArgReadline[bytes], Protocol): ...\n\n_MessageData: TypeAlias = email.message.Message | bytes | str | io.StringIO | _SupportsReadAndReadline\n\n@type_check_only\nclass _HasIteritems(Protocol):\n    def iteritems(self) -> Iterator[tuple[str, _MessageData]]: ...\n\n@type_check_only\nclass _HasItems(Protocol):\n    def items(self) -> Iterator[tuple[str, _MessageData]]: ...\n\nlinesep: bytes\n\nclass Mailbox(Generic[_MessageT]):\n    _path: str  # undocumented\n    _factory: Callable[[IO[Any]], _MessageT] | None  # undocumented\n    @overload\n    def __init__(self, path: StrPath, factory: Callable[[IO[Any]], _MessageT], create: bool = True) -> None: ...\n    @overload\n    def __init__(self, path: StrPath, factory: None = None, create: bool = True) -> None: ...\n    @abstractmethod\n    def add(self, message: _MessageData) -> str: ...\n    @abstractmethod\n    def remove(self, key: str) -> None: ...\n    def __delitem__(self, key: str) -> None: ...\n    def discard(self, key: str) -> None: ...\n    @abstractmethod\n    def __setitem__(self, key: str, message: _MessageData) -> None: ...\n    @overload\n    def get(self, key: str, default: None = None) -> _MessageT | None: ...\n    @overload\n    def get(self, key: str, default: _T) -> _MessageT | _T: ...\n    def __getitem__(self, key: str) -> _MessageT: ...\n    @abstractmethod\n    def get_message(self, key: str) -> _MessageT: ...\n    def get_string(self, key: str) -> str: ...\n    @abstractmethod\n    def get_bytes(self, key: str) -> bytes: ...\n    # As '_ProxyFile' doesn't implement the full IO spec, and BytesIO is incompatible with it, get_file return is Any here\n    @abstractmethod\n    def get_file(self, key: str) -> Any: ...\n    @abstractmethod\n    def iterkeys(self) -> Iterator[str]: ...\n    def keys(self) -> list[str]: ...\n    def itervalues(self) -> Iterator[_MessageT]: ...\n    def __iter__(self) -> Iterator[_MessageT]: ...\n    def values(self) -> list[_MessageT]: ...\n    def iteritems(self) -> Iterator[tuple[str, _MessageT]]: ...\n    def items(self) -> list[tuple[str, _MessageT]]: ...\n    @abstractmethod\n    def __contains__(self, key: str) -> bool: ...\n    @abstractmethod\n    def __len__(self) -> int: ...\n    def clear(self) -> None: ...\n    @overload\n    def pop(self, key: str, default: None = None) -> _MessageT | None: ...\n    @overload\n    def pop(self, key: str, default: _T) -> _MessageT | _T: ...\n    def popitem(self) -> tuple[str, _MessageT]: ...\n    def update(self, arg: _HasIteritems | _HasItems | Iterable[tuple[str, _MessageData]] | None = None) -> None: ...\n    @abstractmethod\n    def flush(self) -> None: ...\n    @abstractmethod\n    def lock(self) -> None: ...\n    @abstractmethod\n    def unlock(self) -> None: ...\n    @abstractmethod\n    def close(self) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass Maildir(Mailbox[MaildirMessage]):\n    colon: str\n    def __init__(\n        self, dirname: StrPath, factory: Callable[[IO[Any]], MaildirMessage] | None = None, create: bool = True\n    ) -> None: ...\n    def add(self, message: _MessageData) -> str: ...\n    def remove(self, key: str) -> None: ...\n    def __setitem__(self, key: str, message: _MessageData) -> None: ...\n    def get_message(self, key: str) -> MaildirMessage: ...\n    def get_bytes(self, key: str) -> bytes: ...\n    def get_file(self, key: str) -> _ProxyFile[bytes]: ...\n    if sys.version_info >= (3, 13):\n        def get_info(self, key: str) -> str: ...\n        def set_info(self, key: str, info: str) -> None: ...\n        def get_flags(self, key: str) -> str: ...\n        def set_flags(self, key: str, flags: str) -> None: ...\n        def add_flag(self, key: str, flag: str) -> None: ...\n        def remove_flag(self, key: str, flag: str) -> None: ...\n\n    def iterkeys(self) -> Iterator[str]: ...\n    def __contains__(self, key: str) -> bool: ...\n    def __len__(self) -> int: ...\n    def flush(self) -> None: ...\n    def lock(self) -> None: ...\n    def unlock(self) -> None: ...\n    def close(self) -> None: ...\n    def list_folders(self) -> list[str]: ...\n    def get_folder(self, folder: str) -> Maildir: ...\n    def add_folder(self, folder: str) -> Maildir: ...\n    def remove_folder(self, folder: str) -> None: ...\n    def clean(self) -> None: ...\n    def next(self) -> str | None: ...\n\nclass _singlefileMailbox(Mailbox[_MessageT], metaclass=ABCMeta):\n    def add(self, message: _MessageData) -> str: ...\n    def remove(self, key: str) -> None: ...\n    def __setitem__(self, key: str, message: _MessageData) -> None: ...\n    def iterkeys(self) -> Iterator[str]: ...\n    def __contains__(self, key: str) -> bool: ...\n    def __len__(self) -> int: ...\n    def lock(self) -> None: ...\n    def unlock(self) -> None: ...\n    def flush(self) -> None: ...\n    def close(self) -> None: ...\n\nclass _mboxMMDF(_singlefileMailbox[_MessageT]):\n    def get_message(self, key: str) -> _MessageT: ...\n    def get_file(self, key: str, from_: bool = False) -> _PartialFile[bytes]: ...\n    def get_bytes(self, key: str, from_: bool = False) -> bytes: ...\n    def get_string(self, key: str, from_: bool = False) -> str: ...\n\nclass mbox(_mboxMMDF[mboxMessage]):\n    def __init__(self, path: StrPath, factory: Callable[[IO[Any]], mboxMessage] | None = None, create: bool = True) -> None: ...\n\nclass MMDF(_mboxMMDF[MMDFMessage]):\n    def __init__(self, path: StrPath, factory: Callable[[IO[Any]], MMDFMessage] | None = None, create: bool = True) -> None: ...\n\nclass MH(Mailbox[MHMessage]):\n    def __init__(self, path: StrPath, factory: Callable[[IO[Any]], MHMessage] | None = None, create: bool = True) -> None: ...\n    def add(self, message: _MessageData) -> str: ...\n    def remove(self, key: str) -> None: ...\n    def __setitem__(self, key: str, message: _MessageData) -> None: ...\n    def get_message(self, key: str) -> MHMessage: ...\n    def get_bytes(self, key: str) -> bytes: ...\n    def get_file(self, key: str) -> _ProxyFile[bytes]: ...\n    def iterkeys(self) -> Iterator[str]: ...\n    def __contains__(self, key: str) -> bool: ...\n    def __len__(self) -> int: ...\n    def flush(self) -> None: ...\n    def lock(self) -> None: ...\n    def unlock(self) -> None: ...\n    def close(self) -> None: ...\n    def list_folders(self) -> list[str]: ...\n    def get_folder(self, folder: StrPath) -> MH: ...\n    def add_folder(self, folder: StrPath) -> MH: ...\n    def remove_folder(self, folder: StrPath) -> None: ...\n    def get_sequences(self) -> dict[str, list[int]]: ...\n    def set_sequences(self, sequences: Mapping[str, Sequence[int]]) -> None: ...\n    def pack(self) -> None: ...\n\nclass Babyl(_singlefileMailbox[BabylMessage]):\n    def __init__(self, path: StrPath, factory: Callable[[IO[Any]], BabylMessage] | None = None, create: bool = True) -> None: ...\n    def get_message(self, key: str) -> BabylMessage: ...\n    def get_bytes(self, key: str) -> bytes: ...\n    def get_file(self, key: str) -> IO[bytes]: ...\n    def get_labels(self) -> list[str]: ...\n\nclass Message(email.message.Message):\n    def __init__(self, message: _MessageData | None = None) -> None: ...\n\nclass MaildirMessage(Message):\n    def get_subdir(self) -> str: ...\n    def set_subdir(self, subdir: Literal[\"new\", \"cur\"]) -> None: ...\n    def get_flags(self) -> str: ...\n    def set_flags(self, flags: Iterable[str]) -> None: ...\n    def add_flag(self, flag: str) -> None: ...\n    def remove_flag(self, flag: str) -> None: ...\n    def get_date(self) -> int: ...\n    def set_date(self, date: float) -> None: ...\n    def get_info(self) -> str: ...\n    def set_info(self, info: str) -> None: ...\n\nclass _mboxMMDFMessage(Message):\n    def get_from(self) -> str: ...\n    def set_from(self, from_: str, time_: bool | tuple[int, int, int, int, int, int, int, int, int] | None = None) -> None: ...\n    def get_flags(self) -> str: ...\n    def set_flags(self, flags: Iterable[str]) -> None: ...\n    def add_flag(self, flag: str) -> None: ...\n    def remove_flag(self, flag: str) -> None: ...\n\nclass mboxMessage(_mboxMMDFMessage): ...\n\nclass MHMessage(Message):\n    def get_sequences(self) -> list[str]: ...\n    def set_sequences(self, sequences: Iterable[str]) -> None: ...\n    def add_sequence(self, sequence: str) -> None: ...\n    def remove_sequence(self, sequence: str) -> None: ...\n\nclass BabylMessage(Message):\n    def get_labels(self) -> list[str]: ...\n    def set_labels(self, labels: Iterable[str]) -> None: ...\n    def add_label(self, label: str) -> None: ...\n    def remove_label(self, label: str) -> None: ...\n    def get_visible(self) -> Message: ...\n    def set_visible(self, visible: _MessageData) -> None: ...\n    def update_visible(self) -> None: ...\n\nclass MMDFMessage(_mboxMMDFMessage): ...\n\nclass _ProxyFile(Generic[AnyStr]):\n    def __init__(self, f: IO[AnyStr], pos: int | None = None) -> None: ...\n    def read(self, size: int | None = None) -> AnyStr: ...\n    def read1(self, size: int | None = None) -> AnyStr: ...\n    def readline(self, size: int | None = None) -> AnyStr: ...\n    def readlines(self, sizehint: int | None = None) -> list[AnyStr]: ...\n    def __iter__(self) -> Iterator[AnyStr]: ...\n    def tell(self) -> int: ...\n    def seek(self, offset: int, whence: int = 0) -> None: ...\n    def close(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, exc_type: type[BaseException] | None, exc: BaseException | None, tb: TracebackType | None) -> None: ...\n    def readable(self) -> bool: ...\n    def writable(self) -> bool: ...\n    def seekable(self) -> bool: ...\n    def flush(self) -> None: ...\n    @property\n    def closed(self) -> bool: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass _PartialFile(_ProxyFile[AnyStr]):\n    def __init__(self, f: IO[AnyStr], start: int | None = None, stop: int | None = None) -> None: ...\n\nclass Error(Exception): ...\nclass NoSuchMailboxError(Error): ...\nclass NotEmptyError(Error): ...\nclass ExternalClashError(Error): ...\nclass FormatError(Error): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/mailcap.pyi",
    "content": "from collections.abc import Mapping, Sequence\nfrom typing_extensions import TypeAlias\n\n_Cap: TypeAlias = dict[str, str | int]\n\n__all__ = [\"getcaps\", \"findmatch\"]\n\ndef findmatch(\n    caps: Mapping[str, list[_Cap]], MIMEtype: str, key: str = \"view\", filename: str = \"/dev/null\", plist: Sequence[str] = []\n) -> tuple[str | None, _Cap | None]: ...\ndef getcaps() -> dict[str, list[_Cap]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/marshal.pyi",
    "content": "import builtins\nimport sys\nimport types\nfrom _typeshed import ReadableBuffer, SupportsRead, SupportsWrite\nfrom typing import Any, Final\nfrom typing_extensions import TypeAlias\n\nversion: Final[int]\n\n_Marshallable: TypeAlias = (\n    # handled in w_object() in marshal.c\n    None\n    | type[StopIteration]\n    | builtins.ellipsis\n    | bool\n    # handled in w_complex_object() in marshal.c\n    | int\n    | float\n    | complex\n    | bytes\n    | str\n    | tuple[_Marshallable, ...]\n    | list[Any]\n    | dict[Any, Any]\n    | set[Any]\n    | frozenset[_Marshallable]\n    | types.CodeType\n    | ReadableBuffer\n)\n\nif sys.version_info >= (3, 14):\n    def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 5, /, *, allow_code: bool = True) -> None: ...\n    def dumps(value: _Marshallable, version: int = 5, /, *, allow_code: bool = True) -> bytes: ...\n\nelif sys.version_info >= (3, 13):\n    def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /, *, allow_code: bool = True) -> None: ...\n    def dumps(value: _Marshallable, version: int = 4, /, *, allow_code: bool = True) -> bytes: ...\n\nelse:\n    def dump(value: _Marshallable, file: SupportsWrite[bytes], version: int = 4, /) -> None: ...\n    def dumps(value: _Marshallable, version: int = 4, /) -> bytes: ...\n\nif sys.version_info >= (3, 13):\n    def load(file: SupportsRead[bytes], /, *, allow_code: bool = True) -> Any: ...\n    def loads(bytes: ReadableBuffer, /, *, allow_code: bool = True) -> Any: ...\n\nelse:\n    def load(file: SupportsRead[bytes], /) -> Any: ...\n    def loads(bytes: ReadableBuffer, /) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/math.pyi",
    "content": "import sys\nfrom _typeshed import SupportsMul, SupportsRMul\nfrom collections.abc import Iterable\nfrom typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, TypeVar, overload, type_check_only\nfrom typing_extensions import TypeAlias\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n\n_SupportsFloatOrIndex: TypeAlias = SupportsFloat | SupportsIndex\n\ne: Final[float]\npi: Final[float]\ninf: Final[float]\nnan: Final[float]\ntau: Final[float]\n\ndef acos(x: _SupportsFloatOrIndex, /) -> float: ...\ndef acosh(x: _SupportsFloatOrIndex, /) -> float: ...\ndef asin(x: _SupportsFloatOrIndex, /) -> float: ...\ndef asinh(x: _SupportsFloatOrIndex, /) -> float: ...\ndef atan(x: _SupportsFloatOrIndex, /) -> float: ...\ndef atan2(y: _SupportsFloatOrIndex, x: _SupportsFloatOrIndex, /) -> float: ...\ndef atanh(x: _SupportsFloatOrIndex, /) -> float: ...\n\nif sys.version_info >= (3, 11):\n    def cbrt(x: _SupportsFloatOrIndex, /) -> float: ...\n\n@type_check_only\nclass _SupportsCeil(Protocol[_T_co]):\n    def __ceil__(self) -> _T_co: ...\n\n@overload\ndef ceil(x: _SupportsCeil[_T], /) -> _T: ...\n@overload\ndef ceil(x: _SupportsFloatOrIndex, /) -> int: ...\ndef comb(n: SupportsIndex, k: SupportsIndex, /) -> int: ...\ndef copysign(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ...\ndef cos(x: _SupportsFloatOrIndex, /) -> float: ...\ndef cosh(x: _SupportsFloatOrIndex, /) -> float: ...\ndef degrees(x: _SupportsFloatOrIndex, /) -> float: ...\ndef dist(p: Iterable[_SupportsFloatOrIndex], q: Iterable[_SupportsFloatOrIndex], /) -> float: ...\ndef erf(x: _SupportsFloatOrIndex, /) -> float: ...\ndef erfc(x: _SupportsFloatOrIndex, /) -> float: ...\ndef exp(x: _SupportsFloatOrIndex, /) -> float: ...\n\nif sys.version_info >= (3, 11):\n    def exp2(x: _SupportsFloatOrIndex, /) -> float: ...\n\ndef expm1(x: _SupportsFloatOrIndex, /) -> float: ...\ndef fabs(x: _SupportsFloatOrIndex, /) -> float: ...\ndef factorial(x: SupportsIndex, /) -> int: ...\n@type_check_only\nclass _SupportsFloor(Protocol[_T_co]):\n    def __floor__(self) -> _T_co: ...\n\n@overload\ndef floor(x: _SupportsFloor[_T], /) -> _T: ...\n@overload\ndef floor(x: _SupportsFloatOrIndex, /) -> int: ...\ndef fmod(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ...\ndef frexp(x: _SupportsFloatOrIndex, /) -> tuple[float, int]: ...\ndef fsum(seq: Iterable[_SupportsFloatOrIndex], /) -> float: ...\ndef gamma(x: _SupportsFloatOrIndex, /) -> float: ...\ndef gcd(*integers: SupportsIndex) -> int: ...\ndef hypot(*coordinates: _SupportsFloatOrIndex) -> float: ...\ndef isclose(\n    a: _SupportsFloatOrIndex,\n    b: _SupportsFloatOrIndex,\n    *,\n    rel_tol: _SupportsFloatOrIndex = 1e-09,\n    abs_tol: _SupportsFloatOrIndex = 0.0,\n) -> bool: ...\ndef isinf(x: _SupportsFloatOrIndex, /) -> bool: ...\ndef isfinite(x: _SupportsFloatOrIndex, /) -> bool: ...\ndef isnan(x: _SupportsFloatOrIndex, /) -> bool: ...\ndef isqrt(n: SupportsIndex, /) -> int: ...\ndef lcm(*integers: SupportsIndex) -> int: ...\ndef ldexp(x: _SupportsFloatOrIndex, i: int, /) -> float: ...\ndef lgamma(x: _SupportsFloatOrIndex, /) -> float: ...\ndef log(x: _SupportsFloatOrIndex, base: _SupportsFloatOrIndex = ...) -> float: ...\ndef log10(x: _SupportsFloatOrIndex, /) -> float: ...\ndef log1p(x: _SupportsFloatOrIndex, /) -> float: ...\ndef log2(x: _SupportsFloatOrIndex, /) -> float: ...\ndef modf(x: _SupportsFloatOrIndex, /) -> tuple[float, float]: ...\n\nif sys.version_info >= (3, 12):\n    def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /, *, steps: SupportsIndex | None = None) -> float: ...\n\nelse:\n    def nextafter(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ...\n\ndef perm(n: SupportsIndex, k: SupportsIndex | None = None, /) -> int: ...\ndef pow(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ...\n\n_PositiveInteger: TypeAlias = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25]\n_NegativeInteger: TypeAlias = Literal[-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, -13, -14, -15, -16, -17, -18, -19, -20]\n_LiteralInteger = _PositiveInteger | _NegativeInteger | Literal[0]  # noqa: Y026  # TODO: Use TypeAlias once mypy bugs are fixed\n\n_MultiplicableT1 = TypeVar(\"_MultiplicableT1\", bound=SupportsMul[Any, Any])\n_MultiplicableT2 = TypeVar(\"_MultiplicableT2\", bound=SupportsMul[Any, Any])\n\n@type_check_only\nclass _SupportsProdWithNoDefaultGiven(SupportsMul[Any, Any], SupportsRMul[int, Any], Protocol): ...\n\n_SupportsProdNoDefaultT = TypeVar(\"_SupportsProdNoDefaultT\", bound=_SupportsProdWithNoDefaultGiven)\n\n# This stub is based on the type stub for `builtins.sum`.\n# Like `builtins.sum`, it cannot be precisely represented in a type stub\n# without introducing many false positives.\n# For more details on its limitations and false positives, see #13572.\n# Instead, just like `builtins.sum`, we explicitly handle several useful cases.\n@overload\ndef prod(iterable: Iterable[bool | _LiteralInteger], /, *, start: int = 1) -> int: ...  # type: ignore[overload-overlap]\n@overload\ndef prod(iterable: Iterable[_SupportsProdNoDefaultT], /) -> _SupportsProdNoDefaultT | Literal[1]: ...\n@overload\ndef prod(iterable: Iterable[_MultiplicableT1], /, *, start: _MultiplicableT2) -> _MultiplicableT1 | _MultiplicableT2: ...\ndef radians(x: _SupportsFloatOrIndex, /) -> float: ...\ndef remainder(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, /) -> float: ...\ndef sin(x: _SupportsFloatOrIndex, /) -> float: ...\ndef sinh(x: _SupportsFloatOrIndex, /) -> float: ...\n\nif sys.version_info >= (3, 12):\n    def sumprod(p: Iterable[float], q: Iterable[float], /) -> float: ...\n\ndef sqrt(x: _SupportsFloatOrIndex, /) -> float: ...\ndef tan(x: _SupportsFloatOrIndex, /) -> float: ...\ndef tanh(x: _SupportsFloatOrIndex, /) -> float: ...\n\n# Is different from `_typeshed.SupportsTrunc`, which is not generic\n@type_check_only\nclass _SupportsTrunc(Protocol[_T_co]):\n    def __trunc__(self) -> _T_co: ...\n\ndef trunc(x: _SupportsTrunc[_T], /) -> _T: ...\ndef ulp(x: _SupportsFloatOrIndex, /) -> float: ...\n\nif sys.version_info >= (3, 13):\n    def fma(x: _SupportsFloatOrIndex, y: _SupportsFloatOrIndex, z: _SupportsFloatOrIndex, /) -> float: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/mimetypes.pyi",
    "content": "import sys\nfrom _typeshed import StrPath\nfrom collections.abc import Iterable\nfrom typing import IO\n\n__all__ = [\n    \"knownfiles\",\n    \"inited\",\n    \"MimeTypes\",\n    \"guess_type\",\n    \"guess_all_extensions\",\n    \"guess_extension\",\n    \"add_type\",\n    \"init\",\n    \"read_mime_types\",\n    \"suffix_map\",\n    \"encodings_map\",\n    \"types_map\",\n    \"common_types\",\n]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"guess_file_type\"]\n\ndef guess_type(url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: ...\ndef guess_all_extensions(type: str, strict: bool = True) -> list[str]: ...\ndef guess_extension(type: str, strict: bool = True) -> str | None: ...\ndef init(files: Iterable[StrPath] | None = None) -> None: ...\ndef read_mime_types(file: StrPath) -> dict[str, str] | None: ...\ndef add_type(type: str, ext: str, strict: bool = True) -> None: ...\n\nif sys.version_info >= (3, 13):\n    def guess_file_type(path: StrPath, *, strict: bool = True) -> tuple[str | None, str | None]: ...\n\ninited: bool\nknownfiles: list[StrPath]\nsuffix_map: dict[str, str]\nencodings_map: dict[str, str]\ntypes_map: dict[str, str]\ncommon_types: dict[str, str]\n\nclass MimeTypes:\n    suffix_map: dict[str, str]\n    encodings_map: dict[str, str]\n    types_map: tuple[dict[str, str], dict[str, str]]\n    types_map_inv: tuple[dict[str, str], dict[str, str]]\n    def __init__(self, filenames: Iterable[StrPath] = (), strict: bool = True) -> None: ...\n    def add_type(self, type: str, ext: str, strict: bool = True) -> None: ...\n    def guess_extension(self, type: str, strict: bool = True) -> str | None: ...\n    def guess_type(self, url: StrPath, strict: bool = True) -> tuple[str | None, str | None]: ...\n    def guess_all_extensions(self, type: str, strict: bool = True) -> list[str]: ...\n    def read(self, filename: StrPath, strict: bool = True) -> None: ...\n    def readfp(self, fp: IO[str], strict: bool = True) -> None: ...\n    def read_windows_registry(self, strict: bool = True) -> None: ...\n    if sys.version_info >= (3, 13):\n        def guess_file_type(self, path: StrPath, *, strict: bool = True) -> tuple[str | None, str | None]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/mmap.pyi",
    "content": "import os\nimport sys\nfrom _typeshed import ReadableBuffer, Unused\nfrom collections.abc import Iterator\nfrom typing import Final, Literal, NoReturn, SupportsIndex, overload\nfrom typing_extensions import Self, disjoint_base\n\nACCESS_DEFAULT: Final = 0\nACCESS_READ: Final = 1\nACCESS_WRITE: Final = 2\nACCESS_COPY: Final = 3\n\nALLOCATIONGRANULARITY: Final[int]\n\nif sys.platform == \"linux\":\n    MAP_DENYWRITE: Final[int]\n    MAP_EXECUTABLE: Final[int]\n    if sys.version_info >= (3, 10):\n        MAP_POPULATE: Final[int]\nif sys.version_info >= (3, 11) and sys.platform != \"win32\" and sys.platform != \"darwin\":\n    MAP_STACK: Final[int]\n\nif sys.platform != \"win32\":\n    MAP_ANON: Final[int]\n    MAP_ANONYMOUS: Final[int]\n    MAP_PRIVATE: Final[int]\n    MAP_SHARED: Final[int]\n    PROT_EXEC: Final[int]\n    PROT_READ: Final[int]\n    PROT_WRITE: Final[int]\n\nPAGESIZE: Final[int]\n\n@disjoint_base\nclass mmap:\n    if sys.platform == \"win32\":\n        def __new__(self, fileno: int, length: int, tagname: str | None = None, access: int = 0, offset: int = 0) -> Self: ...\n    else:\n        if sys.version_info >= (3, 13):\n            def __new__(\n                cls,\n                fileno: int,\n                length: int,\n                flags: int = ...,\n                prot: int = ...,\n                access: int = 0,\n                offset: int = 0,\n                *,\n                trackfd: bool = True,\n            ) -> Self: ...\n        else:\n            def __new__(\n                cls, fileno: int, length: int, flags: int = ..., prot: int = ..., access: int = 0, offset: int = 0\n            ) -> Self: ...\n\n    def close(self) -> None: ...\n    def flush(self, offset: int = 0, size: int = ..., /) -> None: ...\n    def move(self, dest: int, src: int, count: int, /) -> None: ...\n    def read_byte(self) -> int: ...\n    def readline(self) -> bytes: ...\n    def resize(self, newsize: int, /) -> None: ...\n    if sys.platform != \"win32\":\n        def seek(self, pos: int, whence: Literal[0, 1, 2, 3, 4] = os.SEEK_SET, /) -> None: ...\n    else:\n        def seek(self, pos: int, whence: Literal[0, 1, 2] = os.SEEK_SET, /) -> None: ...\n\n    def size(self) -> int: ...\n    def tell(self) -> int: ...\n    def write_byte(self, byte: int, /) -> None: ...\n    def __len__(self) -> int: ...\n    closed: bool\n    if sys.platform != \"win32\":\n        def madvise(self, option: int, start: int = 0, length: int = ..., /) -> None: ...\n\n    def find(self, view: ReadableBuffer, start: int = ..., end: int = ..., /) -> int: ...\n    def rfind(self, view: ReadableBuffer, start: int = ..., end: int = ..., /) -> int: ...\n    def read(self, n: int | None = None, /) -> bytes: ...\n    def write(self, bytes: ReadableBuffer, /) -> int: ...\n    @overload\n    def __getitem__(self, key: SupportsIndex, /) -> int: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> bytes: ...\n    def __delitem__(self, key: SupportsIndex | slice[SupportsIndex | None], /) -> NoReturn: ...\n    @overload\n    def __setitem__(self, key: SupportsIndex, value: int, /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice[SupportsIndex | None], value: ReadableBuffer, /) -> None: ...\n    # Doesn't actually exist, but the object actually supports \"in\" because it has __getitem__,\n    # so we claim that there is also a __contains__ to help type checkers.\n    def __contains__(self, o: object, /) -> bool: ...\n    # Doesn't actually exist, but the object is actually iterable because it has __getitem__ and __len__,\n    # so we claim that there is also an __iter__ to help type checkers.\n    def __iter__(self) -> Iterator[int]: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, exc_type: Unused, exc_value: Unused, traceback: Unused, /) -> None: ...\n    def __buffer__(self, flags: int, /) -> memoryview: ...\n    def __release_buffer__(self, buffer: memoryview, /) -> None: ...\n    if sys.version_info >= (3, 13):\n        def seekable(self) -> Literal[True]: ...\n\nif sys.platform != \"win32\":\n    MADV_NORMAL: Final[int]\n    MADV_RANDOM: Final[int]\n    MADV_SEQUENTIAL: Final[int]\n    MADV_WILLNEED: Final[int]\n    MADV_DONTNEED: Final[int]\n    MADV_FREE: Final[int]\n\nif sys.platform == \"linux\":\n    MADV_REMOVE: Final[int]\n    MADV_DONTFORK: Final[int]\n    MADV_DOFORK: Final[int]\n    MADV_HWPOISON: Final[int]\n    MADV_MERGEABLE: Final[int]\n    MADV_UNMERGEABLE: Final[int]\n    # Seems like this constant is not defined in glibc.\n    # See https://github.com/python/typeshed/pull/5360 for details\n    # MADV_SOFT_OFFLINE: Final[int]\n    MADV_HUGEPAGE: Final[int]\n    MADV_NOHUGEPAGE: Final[int]\n    MADV_DONTDUMP: Final[int]\n    MADV_DODUMP: Final[int]\n\n# This Values are defined for FreeBSD but type checkers do not support conditions for these\nif sys.platform != \"linux\" and sys.platform != \"darwin\" and sys.platform != \"win32\":\n    MADV_NOSYNC: Final[int]\n    MADV_AUTOSYNC: Final[int]\n    MADV_NOCORE: Final[int]\n    MADV_CORE: Final[int]\n    MADV_PROTECT: Final[int]\n\nif sys.version_info >= (3, 10) and sys.platform == \"darwin\":\n    MADV_FREE_REUSABLE: Final[int]\n    MADV_FREE_REUSE: Final[int]\n\nif sys.version_info >= (3, 13) and sys.platform != \"win32\":\n    MAP_32BIT: Final[int]\n\nif sys.version_info >= (3, 13) and sys.platform == \"darwin\":\n    MAP_NORESERVE: Final = 64\n    MAP_NOEXTEND: Final = 256\n    MAP_HASSEMAPHORE: Final = 512\n    MAP_NOCACHE: Final = 1024\n    MAP_JIT: Final = 2048\n    MAP_RESILIENT_CODESIGN: Final = 8192\n    MAP_RESILIENT_MEDIA: Final = 16384\n    MAP_TRANSLATED_ALLOW_EXECUTE: Final = 131072\n    MAP_UNIX03: Final = 262144\n    MAP_TPRO: Final = 524288\n\nif sys.version_info >= (3, 13) and sys.platform == \"linux\":\n    MAP_NORESERVE: Final = 16384\n"
  },
  {
    "path": "mypy/typeshed/stdlib/modulefinder.pyi",
    "content": "import sys\nfrom collections.abc import Container, Iterable, Iterator, Sequence\nfrom types import CodeType\nfrom typing import IO, Any, Final\n\nif sys.version_info < (3, 11):\n    LOAD_CONST: Final[int]  # undocumented\n    IMPORT_NAME: Final[int]  # undocumented\n    STORE_NAME: Final[int]  # undocumented\n    STORE_GLOBAL: Final[int]  # undocumented\n    STORE_OPS: Final[tuple[int, int]]  # undocumented\n    EXTENDED_ARG: Final[int]  # undocumented\n\npackagePathMap: dict[str, list[str]]  # undocumented\n\ndef AddPackagePath(packagename: str, path: str) -> None: ...\n\nreplacePackageMap: dict[str, str]  # undocumented\n\ndef ReplacePackage(oldname: str, newname: str) -> None: ...\n\nclass Module:  # undocumented\n    def __init__(self, name: str, file: str | None = None, path: str | None = None) -> None: ...\n\nclass ModuleFinder:\n    modules: dict[str, Module]\n    path: list[str]  # undocumented\n    badmodules: dict[str, dict[str, int]]  # undocumented\n    debug: int  # undocumented\n    indent: int  # undocumented\n    excludes: Container[str]  # undocumented\n    replace_paths: Sequence[tuple[str, str]]  # undocumented\n\n    def __init__(\n        self,\n        path: list[str] | None = None,\n        debug: int = 0,\n        excludes: Container[str] | None = None,\n        replace_paths: Sequence[tuple[str, str]] | None = None,\n    ) -> None: ...\n    def msg(self, level: int, str: str, *args: Any) -> None: ...  # undocumented\n    def msgin(self, *args: Any) -> None: ...  # undocumented\n    def msgout(self, *args: Any) -> None: ...  # undocumented\n    def run_script(self, pathname: str) -> None: ...\n    def load_file(self, pathname: str) -> None: ...  # undocumented\n    def import_hook(\n        self, name: str, caller: Module | None = None, fromlist: list[str] | None = None, level: int = -1\n    ) -> Module | None: ...  # undocumented\n    def determine_parent(self, caller: Module | None, level: int = -1) -> Module | None: ...  # undocumented\n    def find_head_package(self, parent: Module, name: str) -> tuple[Module, str]: ...  # undocumented\n    def load_tail(self, q: Module, tail: str) -> Module: ...  # undocumented\n    def ensure_fromlist(self, m: Module, fromlist: Iterable[str], recursive: int = 0) -> None: ...  # undocumented\n    def find_all_submodules(self, m: Module) -> Iterable[str]: ...  # undocumented\n    def import_module(self, partname: str, fqname: str, parent: Module) -> Module | None: ...  # undocumented\n    def load_module(self, fqname: str, fp: IO[str], pathname: str, file_info: tuple[str, str, str]) -> Module: ...  # undocumented\n    def scan_opcodes(self, co: CodeType) -> Iterator[tuple[str, tuple[Any, ...]]]: ...  # undocumented\n    def scan_code(self, co: CodeType, m: Module) -> None: ...  # undocumented\n    def load_package(self, fqname: str, pathname: str) -> Module: ...  # undocumented\n    def add_module(self, fqname: str) -> Module: ...  # undocumented\n    def find_module(\n        self, name: str, path: str | None, parent: Module | None = None\n    ) -> tuple[IO[Any] | None, str | None, tuple[str, str, int]]: ...  # undocumented\n    def report(self) -> None: ...\n    def any_missing(self) -> list[str]: ...  # undocumented\n    def any_missing_maybe(self) -> tuple[list[str], list[str]]: ...  # undocumented\n    def replace_paths_in_code(self, co: CodeType) -> CodeType: ...  # undocumented\n\ndef test() -> ModuleFinder | None: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/msilib/__init__.pyi",
    "content": "import sys\nfrom collections.abc import Container, Iterable, Sequence\nfrom types import ModuleType\nfrom typing import Any, Final\n\nif sys.platform == \"win32\":\n    from _msi import *\n    from _msi import _Database\n\n    AMD64: Final[bool]\n    Win64: Final[bool]\n\n    datasizemask: Final = 0x00FF\n    type_valid: Final = 0x0100\n    type_localizable: Final = 0x0200\n    typemask: Final = 0x0C00\n    type_long: Final = 0x0000\n    type_short: Final = 0x0400\n    type_string: Final = 0x0C00\n    type_binary: Final = 0x0800\n    type_nullable: Final = 0x1000\n    type_key: Final = 0x2000\n    knownbits: Final = 0x3FFF\n\n    class Table:\n        name: str\n        fields: list[tuple[int, str, int]]\n        def __init__(self, name: str) -> None: ...\n        def add_field(self, index: int, name: str, type: int) -> None: ...\n        def sql(self) -> str: ...\n        def create(self, db: _Database) -> None: ...\n\n    class _Unspecified: ...\n\n    def change_sequence(\n        seq: Sequence[tuple[str, str | None, int]],\n        action: str,\n        seqno: int | type[_Unspecified] = ...,\n        cond: str | type[_Unspecified] = ...,\n    ) -> None: ...\n    def add_data(db: _Database, table: str, values: Iterable[tuple[Any, ...]]) -> None: ...\n    def add_stream(db: _Database, name: str, path: str) -> None: ...\n    def init_database(\n        name: str, schema: ModuleType, ProductName: str, ProductCode: str, ProductVersion: str, Manufacturer: str\n    ) -> _Database: ...\n    def add_tables(db: _Database, module: ModuleType) -> None: ...\n    def make_id(str: str) -> str: ...\n    def gen_uuid() -> str: ...\n\n    class CAB:\n        name: str\n        files: list[tuple[str, str]]\n        filenames: set[str]\n        index: int\n        def __init__(self, name: str) -> None: ...\n        def gen_id(self, file: str) -> str: ...\n        def append(self, full: str, file: str, logical: str) -> tuple[int, str]: ...\n        def commit(self, db: _Database) -> None: ...\n\n    _directories: set[str]\n\n    class Directory:\n        db: _Database\n        cab: CAB\n        basedir: str\n        physical: str\n        logical: str\n        component: str | None\n        short_names: set[str]\n        ids: set[str]\n        keyfiles: dict[str, str]\n        componentflags: int | None\n        absolute: str\n        def __init__(\n            self,\n            db: _Database,\n            cab: CAB,\n            basedir: str,\n            physical: str,\n            _logical: str,\n            default: str,\n            componentflags: int | None = None,\n        ) -> None: ...\n        def start_component(\n            self,\n            component: str | None = None,\n            feature: Feature | None = None,\n            flags: int | None = None,\n            keyfile: str | None = None,\n            uuid: str | None = None,\n        ) -> None: ...\n        def make_short(self, file: str) -> str: ...\n        def add_file(self, file: str, src: str | None = None, version: str | None = None, language: str | None = None) -> str: ...\n        def glob(self, pattern: str, exclude: Container[str] | None = None) -> list[str]: ...\n        def remove_pyc(self) -> None: ...\n\n    class Binary:\n        name: str\n        def __init__(self, fname: str) -> None: ...\n\n    class Feature:\n        id: str\n        def __init__(\n            self,\n            db: _Database,\n            id: str,\n            title: str,\n            desc: str,\n            display: int,\n            level: int = 1,\n            parent: Feature | None = None,\n            directory: str | None = None,\n            attributes: int = 0,\n        ) -> None: ...\n        def set_current(self) -> None: ...\n\n    class Control:\n        dlg: Dialog\n        name: str\n        def __init__(self, dlg: Dialog, name: str) -> None: ...\n        def event(self, event: str, argument: str, condition: str = \"1\", ordering: int | None = None) -> None: ...\n        def mapping(self, event: str, attribute: str) -> None: ...\n        def condition(self, action: str, condition: str) -> None: ...\n\n    class RadioButtonGroup(Control):\n        property: str\n        index: int\n        def __init__(self, dlg: Dialog, name: str, property: str) -> None: ...\n        def add(self, name: str, x: int, y: int, w: int, h: int, text: str, value: str | None = None) -> None: ...\n\n    class Dialog:\n        db: _Database\n        name: str\n        x: int\n        y: int\n        w: int\n        h: int\n        def __init__(\n            self,\n            db: _Database,\n            name: str,\n            x: int,\n            y: int,\n            w: int,\n            h: int,\n            attr: int,\n            title: str,\n            first: str,\n            default: str,\n            cancel: str,\n        ) -> None: ...\n        def control(\n            self,\n            name: str,\n            type: str,\n            x: int,\n            y: int,\n            w: int,\n            h: int,\n            attr: int,\n            prop: str | None,\n            text: str | None,\n            next: str | None,\n            help: str | None,\n        ) -> Control: ...\n        def text(self, name: str, x: int, y: int, w: int, h: int, attr: int, text: str | None) -> Control: ...\n        def bitmap(self, name: str, x: int, y: int, w: int, h: int, text: str | None) -> Control: ...\n        def line(self, name: str, x: int, y: int, w: int, h: int) -> Control: ...\n        def pushbutton(\n            self, name: str, x: int, y: int, w: int, h: int, attr: int, text: str | None, next: str | None\n        ) -> Control: ...\n        def radiogroup(\n            self, name: str, x: int, y: int, w: int, h: int, attr: int, prop: str | None, text: str | None, next: str | None\n        ) -> RadioButtonGroup: ...\n        def checkbox(\n            self, name: str, x: int, y: int, w: int, h: int, attr: int, prop: str | None, text: str | None, next: str | None\n        ) -> Control: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/msilib/schema.pyi",
    "content": "import sys\nfrom typing import Final\n\nif sys.platform == \"win32\":\n    from . import Table\n\n    _Validation: Table\n    ActionText: Table\n    AdminExecuteSequence: Table\n    Condition: Table\n    AdminUISequence: Table\n    AdvtExecuteSequence: Table\n    AdvtUISequence: Table\n    AppId: Table\n    AppSearch: Table\n    Property: Table\n    BBControl: Table\n    Billboard: Table\n    Feature: Table\n    Binary: Table\n    BindImage: Table\n    File: Table\n    CCPSearch: Table\n    CheckBox: Table\n    Class: Table\n    Component: Table\n    Icon: Table\n    ProgId: Table\n    ComboBox: Table\n    CompLocator: Table\n    Complus: Table\n    Directory: Table\n    Control: Table\n    Dialog: Table\n    ControlCondition: Table\n    ControlEvent: Table\n    CreateFolder: Table\n    CustomAction: Table\n    DrLocator: Table\n    DuplicateFile: Table\n    Environment: Table\n    Error: Table\n    EventMapping: Table\n    Extension: Table\n    MIME: Table\n    FeatureComponents: Table\n    FileSFPCatalog: Table\n    SFPCatalog: Table\n    Font: Table\n    IniFile: Table\n    IniLocator: Table\n    InstallExecuteSequence: Table\n    InstallUISequence: Table\n    IsolatedComponent: Table\n    LaunchCondition: Table\n    ListBox: Table\n    ListView: Table\n    LockPermissions: Table\n    Media: Table\n    MoveFile: Table\n    MsiAssembly: Table\n    MsiAssemblyName: Table\n    MsiDigitalCertificate: Table\n    MsiDigitalSignature: Table\n    MsiFileHash: Table\n    MsiPatchHeaders: Table\n    ODBCAttribute: Table\n    ODBCDriver: Table\n    ODBCDataSource: Table\n    ODBCSourceAttribute: Table\n    ODBCTranslator: Table\n    Patch: Table\n    PatchPackage: Table\n    PublishComponent: Table\n    RadioButton: Table\n    Registry: Table\n    RegLocator: Table\n    RemoveFile: Table\n    RemoveIniFile: Table\n    RemoveRegistry: Table\n    ReserveCost: Table\n    SelfReg: Table\n    ServiceControl: Table\n    ServiceInstall: Table\n    Shortcut: Table\n    Signature: Table\n    TextStyle: Table\n    TypeLib: Table\n    UIText: Table\n    Upgrade: Table\n    Verb: Table\n\n    tables: Final[list[Table]]\n\n    _Validation_records: list[tuple[str, str, str, int | None, int | None, str | None, int | None, str | None, str | None, str]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/msilib/sequence.pyi",
    "content": "import sys\nfrom typing import Final\nfrom typing_extensions import TypeAlias\n\nif sys.platform == \"win32\":\n    _SequenceType: TypeAlias = list[tuple[str, str | None, int]]\n\n    AdminExecuteSequence: Final[_SequenceType]\n    AdminUISequence: Final[_SequenceType]\n    AdvtExecuteSequence: Final[_SequenceType]\n    InstallExecuteSequence: Final[_SequenceType]\n    InstallUISequence: Final[_SequenceType]\n\n    tables: Final[list[str]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/msilib/text.pyi",
    "content": "import sys\nfrom typing import Final\n\nif sys.platform == \"win32\":\n    ActionText: Final[list[tuple[str, str, str | None]]]\n    UIText: Final[list[tuple[str, str | None]]]\n    dirname: str\n    tables: Final[list[str]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/msvcrt.pyi",
    "content": "import sys\nfrom typing import Final\n\n# This module is only available on Windows\nif sys.platform == \"win32\":\n    CRT_ASSEMBLY_VERSION: Final[str]\n    LK_UNLCK: Final = 0\n    LK_LOCK: Final = 1\n    LK_NBLCK: Final = 2\n    LK_RLCK: Final = 3\n    LK_NBRLCK: Final = 4\n    SEM_FAILCRITICALERRORS: Final = 0x0001\n    SEM_NOALIGNMENTFAULTEXCEPT: Final = 0x0004\n    SEM_NOGPFAULTERRORBOX: Final = 0x0002\n    SEM_NOOPENFILEERRORBOX: Final = 0x8000\n    def locking(fd: int, mode: int, nbytes: int, /) -> None: ...\n    def setmode(fd: int, mode: int, /) -> int: ...\n    def open_osfhandle(handle: int, flags: int, /) -> int: ...\n    def get_osfhandle(fd: int, /) -> int: ...\n    def kbhit() -> bool: ...\n    def getch() -> bytes: ...\n    def getwch() -> str: ...\n    def getche() -> bytes: ...\n    def getwche() -> str: ...\n    def putch(char: bytes | bytearray, /) -> None: ...\n    def putwch(unicode_char: str, /) -> None: ...\n    def ungetch(char: bytes | bytearray, /) -> None: ...\n    def ungetwch(unicode_char: str, /) -> None: ...\n    def heapmin() -> None: ...\n    def SetErrorMode(mode: int, /) -> int: ...\n    if sys.version_info >= (3, 10):\n        def GetErrorMode() -> int: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/__init__.pyi",
    "content": "from multiprocessing import context, reduction as reducer\nfrom multiprocessing.context import (\n    AuthenticationError as AuthenticationError,\n    BufferTooShort as BufferTooShort,\n    Process as Process,\n    ProcessError as ProcessError,\n    TimeoutError as TimeoutError,\n)\nfrom multiprocessing.process import (\n    active_children as active_children,\n    current_process as current_process,\n    parent_process as parent_process,\n)\n\n# These are technically functions that return instances of these Queue classes.\n# The stub here doesn't reflect reality exactly --\n# while e.g. `multiprocessing.queues.Queue` is a class,\n# `multiprocessing.Queue` is actually a function at runtime.\n# Avoid using `multiprocessing.Queue` as a type annotation;\n# use imports from multiprocessing.queues instead.\n# See #4266 and #8450 for discussion.\nfrom multiprocessing.queues import JoinableQueue as JoinableQueue, Queue as Queue, SimpleQueue as SimpleQueue\nfrom multiprocessing.spawn import freeze_support as freeze_support\n\n__all__ = [\n    \"Array\",\n    \"AuthenticationError\",\n    \"Barrier\",\n    \"BoundedSemaphore\",\n    \"BufferTooShort\",\n    \"Condition\",\n    \"Event\",\n    \"JoinableQueue\",\n    \"Lock\",\n    \"Manager\",\n    \"Pipe\",\n    \"Pool\",\n    \"Process\",\n    \"ProcessError\",\n    \"Queue\",\n    \"RLock\",\n    \"RawArray\",\n    \"RawValue\",\n    \"Semaphore\",\n    \"SimpleQueue\",\n    \"TimeoutError\",\n    \"Value\",\n    \"active_children\",\n    \"allow_connection_pickling\",\n    \"cpu_count\",\n    \"current_process\",\n    \"freeze_support\",\n    \"get_all_start_methods\",\n    \"get_context\",\n    \"get_logger\",\n    \"get_start_method\",\n    \"log_to_stderr\",\n    \"parent_process\",\n    \"reducer\",\n    \"set_executable\",\n    \"set_forkserver_preload\",\n    \"set_start_method\",\n]\n\n# These functions (really bound methods)\n# are all autogenerated at runtime here: https://github.com/python/cpython/blob/600c65c094b0b48704d8ec2416930648052ba715/Lib/multiprocessing/__init__.py#L23\nRawValue = context._default_context.RawValue\nRawArray = context._default_context.RawArray\nValue = context._default_context.Value\nArray = context._default_context.Array\nBarrier = context._default_context.Barrier\nBoundedSemaphore = context._default_context.BoundedSemaphore\nCondition = context._default_context.Condition\nEvent = context._default_context.Event\nLock = context._default_context.Lock\nRLock = context._default_context.RLock\nSemaphore = context._default_context.Semaphore\nPipe = context._default_context.Pipe\nPool = context._default_context.Pool\nallow_connection_pickling = context._default_context.allow_connection_pickling\ncpu_count = context._default_context.cpu_count\nget_logger = context._default_context.get_logger\nlog_to_stderr = context._default_context.log_to_stderr\nManager = context._default_context.Manager\nset_executable = context._default_context.set_executable\nset_forkserver_preload = context._default_context.set_forkserver_preload\nget_all_start_methods = context._default_context.get_all_start_methods\nget_start_method = context._default_context.get_start_method\nset_start_method = context._default_context.set_start_method\nget_context = context._default_context.get_context\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/connection.pyi",
    "content": "import socket\nimport sys\nfrom _typeshed import Incomplete, ReadableBuffer\nfrom collections.abc import Iterable\nfrom types import TracebackType\nfrom typing import Any, Generic, SupportsIndex, TypeVar\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\"Client\", \"Listener\", \"Pipe\", \"wait\"]\n\n# https://docs.python.org/3/library/multiprocessing.html#address-formats\n_Address: TypeAlias = str | tuple[str, int]\n\n# Defaulting to Any to avoid forcing generics on a lot of pre-existing code\n_SendT_contra = TypeVar(\"_SendT_contra\", contravariant=True, default=Any)\n_RecvT_co = TypeVar(\"_RecvT_co\", covariant=True, default=Any)\n\nclass _ConnectionBase(Generic[_SendT_contra, _RecvT_co]):\n    def __init__(self, handle: SupportsIndex, readable: bool = True, writable: bool = True) -> None: ...\n    @property\n    def closed(self) -> bool: ...  # undocumented\n    @property\n    def readable(self) -> bool: ...  # undocumented\n    @property\n    def writable(self) -> bool: ...  # undocumented\n    def fileno(self) -> int: ...\n    def close(self) -> None: ...\n    def send_bytes(self, buf: ReadableBuffer, offset: int = 0, size: int | None = None) -> None: ...\n    def send(self, obj: _SendT_contra) -> None: ...\n    def recv_bytes(self, maxlength: int | None = None) -> bytes: ...\n    def recv_bytes_into(self, buf: Any, offset: int = 0) -> int: ...\n    def recv(self) -> _RecvT_co: ...\n    def poll(self, timeout: float | None = 0.0) -> bool: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n    def __del__(self) -> None: ...\n\nclass Connection(_ConnectionBase[_SendT_contra, _RecvT_co]): ...\n\nif sys.platform == \"win32\":\n    class PipeConnection(_ConnectionBase[_SendT_contra, _RecvT_co]): ...\n\nclass Listener:\n    def __init__(\n        self, address: _Address | None = None, family: str | None = None, backlog: int = 1, authkey: bytes | None = None\n    ) -> None: ...\n    def accept(self) -> Connection[Incomplete, Incomplete]: ...\n    def close(self) -> None: ...\n    @property\n    def address(self) -> _Address: ...\n    @property\n    def last_accepted(self) -> _Address | None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n\n# Any: send and recv methods unused\nif sys.version_info >= (3, 12):\n    def deliver_challenge(connection: Connection[Any, Any], authkey: bytes, digest_name: str = \"sha256\") -> None: ...\n\nelse:\n    def deliver_challenge(connection: Connection[Any, Any], authkey: bytes) -> None: ...\n\ndef answer_challenge(connection: Connection[Any, Any], authkey: bytes) -> None: ...\ndef wait(\n    object_list: Iterable[Connection[_SendT_contra, _RecvT_co] | socket.socket | int], timeout: float | None = None\n) -> list[Connection[_SendT_contra, _RecvT_co] | socket.socket | int]: ...\ndef Client(address: _Address, family: str | None = None, authkey: bytes | None = None) -> Connection[Any, Any]: ...\n\n# N.B. Keep this in sync with multiprocessing.context.BaseContext.Pipe.\n# _ConnectionBase is the common base class of Connection and PipeConnection\n# and can be used in cross-platform code.\n#\n# The two connections should have the same generic types but inverted (Connection[_T1, _T2], Connection[_T2, _T1]).\n# However, TypeVars scoped entirely within a return annotation is unspecified in the spec.\nif sys.platform != \"win32\":\n    def Pipe(duplex: bool = True) -> tuple[Connection[Any, Any], Connection[Any, Any]]: ...\n\nelse:\n    def Pipe(duplex: bool = True) -> tuple[PipeConnection[Any, Any], PipeConnection[Any, Any]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/context.pyi",
    "content": "import ctypes\nimport sys\nfrom _ctypes import _CData\nfrom collections.abc import Callable, Iterable, Sequence\nfrom ctypes import _SimpleCData, c_char\nfrom logging import Logger, _Level as _LoggingLevel\nfrom multiprocessing import popen_fork, popen_forkserver, popen_spawn_posix, popen_spawn_win32, queues, synchronize\nfrom multiprocessing.managers import SyncManager\nfrom multiprocessing.pool import Pool as _Pool\nfrom multiprocessing.process import BaseProcess\nfrom multiprocessing.sharedctypes import Synchronized, SynchronizedArray, SynchronizedString\nfrom typing import Any, ClassVar, Literal, TypeVar, overload\nfrom typing_extensions import TypeAlias\n\nif sys.platform != \"win32\":\n    from multiprocessing.connection import Connection\nelse:\n    from multiprocessing.connection import PipeConnection\n\n__all__ = ()\n\n_LockLike: TypeAlias = synchronize.Lock | synchronize.RLock\n_T = TypeVar(\"_T\")\n_CT = TypeVar(\"_CT\", bound=_CData)\n\nclass ProcessError(Exception): ...\nclass BufferTooShort(ProcessError): ...\nclass TimeoutError(ProcessError): ...\nclass AuthenticationError(ProcessError): ...\n\nclass BaseContext:\n    ProcessError: ClassVar[type[ProcessError]]\n    BufferTooShort: ClassVar[type[BufferTooShort]]\n    TimeoutError: ClassVar[type[TimeoutError]]\n    AuthenticationError: ClassVar[type[AuthenticationError]]\n\n    # N.B. The methods below are applied at runtime to generate\n    # multiprocessing.*, so the signatures should be identical (modulo self).\n    @staticmethod\n    def current_process() -> BaseProcess: ...\n    @staticmethod\n    def parent_process() -> BaseProcess | None: ...\n    @staticmethod\n    def active_children() -> list[BaseProcess]: ...\n    def cpu_count(self) -> int: ...\n    def Manager(self) -> SyncManager: ...\n\n    # N.B. Keep this in sync with multiprocessing.connection.Pipe.\n    # _ConnectionBase is the common base class of Connection and PipeConnection\n    # and can be used in cross-platform code.\n    #\n    # The two connections should have the same generic types but inverted (Connection[_T1, _T2], Connection[_T2, _T1]).\n    # However, TypeVars scoped entirely within a return annotation is unspecified in the spec.\n    if sys.platform != \"win32\":\n        def Pipe(self, duplex: bool = True) -> tuple[Connection[Any, Any], Connection[Any, Any]]: ...\n    else:\n        def Pipe(self, duplex: bool = True) -> tuple[PipeConnection[Any, Any], PipeConnection[Any, Any]]: ...\n\n    def Barrier(\n        self, parties: int, action: Callable[..., object] | None = None, timeout: float | None = None\n    ) -> synchronize.Barrier: ...\n    def BoundedSemaphore(self, value: int = 1) -> synchronize.BoundedSemaphore: ...\n    def Condition(self, lock: _LockLike | None = None) -> synchronize.Condition: ...\n    def Event(self) -> synchronize.Event: ...\n    def Lock(self) -> synchronize.Lock: ...\n    def RLock(self) -> synchronize.RLock: ...\n    def Semaphore(self, value: int = 1) -> synchronize.Semaphore: ...\n    def Queue(self, maxsize: int = 0) -> queues.Queue[Any]: ...\n    def JoinableQueue(self, maxsize: int = 0) -> queues.JoinableQueue[Any]: ...\n    def SimpleQueue(self) -> queues.SimpleQueue[Any]: ...\n    def Pool(\n        self,\n        processes: int | None = None,\n        initializer: Callable[..., object] | None = None,\n        initargs: Iterable[Any] = (),\n        maxtasksperchild: int | None = None,\n    ) -> _Pool: ...\n    @overload\n    def RawValue(self, typecode_or_type: type[_CT], *args: Any) -> _CT: ...\n    @overload\n    def RawValue(self, typecode_or_type: str, *args: Any) -> Any: ...\n    @overload\n    def RawArray(self, typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ...\n    @overload\n    def RawArray(self, typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ...\n    @overload\n    def Value(\n        self, typecode_or_type: type[_SimpleCData[_T]], *args: Any, lock: Literal[True] | _LockLike = True\n    ) -> Synchronized[_T]: ...\n    @overload\n    def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[False]) -> Synchronized[_CT]: ...\n    @overload\n    def Value(self, typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike = True) -> Synchronized[_CT]: ...\n    @overload\n    def Value(self, typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike = True) -> Synchronized[Any]: ...\n    @overload\n    def Value(self, typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True) -> Any: ...\n    @overload\n    def Array(\n        self, typecode_or_type: type[_SimpleCData[_T]], size_or_initializer: int | Sequence[Any], *, lock: Literal[False]\n    ) -> SynchronizedArray[_T]: ...\n    @overload\n    def Array(\n        self, typecode_or_type: type[c_char], size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True\n    ) -> SynchronizedString: ...\n    @overload\n    def Array(\n        self,\n        typecode_or_type: type[_SimpleCData[_T]],\n        size_or_initializer: int | Sequence[Any],\n        *,\n        lock: Literal[True] | _LockLike = True,\n    ) -> SynchronizedArray[_T]: ...\n    @overload\n    def Array(\n        self, typecode_or_type: str, size_or_initializer: int | Sequence[Any], *, lock: Literal[True] | _LockLike = True\n    ) -> SynchronizedArray[Any]: ...\n    @overload\n    def Array(\n        self, typecode_or_type: str | type[_CData], size_or_initializer: int | Sequence[Any], *, lock: bool | _LockLike = True\n    ) -> Any: ...\n    def freeze_support(self) -> None: ...\n    def get_logger(self) -> Logger: ...\n    def log_to_stderr(self, level: _LoggingLevel | None = None) -> Logger: ...\n    def allow_connection_pickling(self) -> None: ...\n    def set_executable(self, executable: str) -> None: ...\n    def set_forkserver_preload(self, module_names: list[str]) -> None: ...\n    if sys.platform != \"win32\":\n        @overload\n        def get_context(self, method: None = None) -> DefaultContext: ...\n        @overload\n        def get_context(self, method: Literal[\"spawn\"]) -> SpawnContext: ...\n        @overload\n        def get_context(self, method: Literal[\"fork\"]) -> ForkContext: ...\n        @overload\n        def get_context(self, method: Literal[\"forkserver\"]) -> ForkServerContext: ...\n        @overload\n        def get_context(self, method: str) -> BaseContext: ...\n    else:\n        @overload\n        def get_context(self, method: None = None) -> DefaultContext: ...\n        @overload\n        def get_context(self, method: Literal[\"spawn\"]) -> SpawnContext: ...\n        @overload\n        def get_context(self, method: str) -> BaseContext: ...\n\n    @overload\n    def get_start_method(self, allow_none: Literal[False] = False) -> str: ...\n    @overload\n    def get_start_method(self, allow_none: bool) -> str | None: ...\n    def set_start_method(self, method: str | None, force: bool = False) -> None: ...\n    @property\n    def reducer(self) -> str: ...\n    @reducer.setter\n    def reducer(self, reduction: str) -> None: ...\n    def _check_available(self) -> None: ...\n\nclass Process(BaseProcess):\n    _start_method: str | None\n    @staticmethod\n    def _Popen(process_obj: BaseProcess) -> DefaultContext: ...\n\nclass DefaultContext(BaseContext):\n    Process: ClassVar[type[Process]]\n    def __init__(self, context: BaseContext) -> None: ...\n    def get_start_method(self, allow_none: bool = False) -> str: ...\n    def get_all_start_methods(self) -> list[str]: ...\n\n_default_context: DefaultContext\n\nclass SpawnProcess(BaseProcess):\n    _start_method: str\n    if sys.platform != \"win32\":\n        @staticmethod\n        def _Popen(process_obj: BaseProcess) -> popen_spawn_posix.Popen: ...\n    else:\n        @staticmethod\n        def _Popen(process_obj: BaseProcess) -> popen_spawn_win32.Popen: ...\n\nclass SpawnContext(BaseContext):\n    _name: str\n    Process: ClassVar[type[SpawnProcess]]\n\nif sys.platform != \"win32\":\n    class ForkProcess(BaseProcess):\n        _start_method: str\n        @staticmethod\n        def _Popen(process_obj: BaseProcess) -> popen_fork.Popen: ...\n\n    class ForkServerProcess(BaseProcess):\n        _start_method: str\n        @staticmethod\n        def _Popen(process_obj: BaseProcess) -> popen_forkserver.Popen: ...\n\n    class ForkContext(BaseContext):\n        _name: str\n        Process: ClassVar[type[ForkProcess]]\n\n    class ForkServerContext(BaseContext):\n        _name: str\n        Process: ClassVar[type[ForkServerProcess]]\n\ndef _force_start_method(method: str) -> None: ...\ndef get_spawning_popen() -> Any | None: ...\ndef set_spawning_popen(popen: Any) -> None: ...\ndef assert_spawning(obj: Any) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/dummy/__init__.pyi",
    "content": "import array\nimport sys\nimport threading\nimport weakref\nfrom collections.abc import Callable, Iterable, Mapping, Sequence\nfrom queue import Queue as Queue\nfrom threading import (\n    Barrier as Barrier,\n    BoundedSemaphore as BoundedSemaphore,\n    Condition as Condition,\n    Event as Event,\n    Lock as Lock,\n    RLock as RLock,\n    Semaphore as Semaphore,\n)\nfrom typing import Any, Literal\n\nfrom .connection import Pipe as Pipe\n\n__all__ = [\n    \"Process\",\n    \"current_process\",\n    \"active_children\",\n    \"freeze_support\",\n    \"Lock\",\n    \"RLock\",\n    \"Semaphore\",\n    \"BoundedSemaphore\",\n    \"Condition\",\n    \"Event\",\n    \"Barrier\",\n    \"Queue\",\n    \"Manager\",\n    \"Pipe\",\n    \"Pool\",\n    \"JoinableQueue\",\n]\n\nJoinableQueue = Queue\n\nclass DummyProcess(threading.Thread):\n    _children: weakref.WeakKeyDictionary[Any, Any]\n    _parent: threading.Thread\n    _pid: None\n    _start_called: int\n    @property\n    def exitcode(self) -> Literal[0] | None: ...\n    if sys.version_info >= (3, 14):\n        # Default changed in Python 3.14.1\n        def __init__(\n            self,\n            group: Any = None,\n            target: Callable[..., object] | None = None,\n            name: str | None = None,\n            args: Iterable[Any] = (),\n            kwargs: Mapping[str, Any] | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            group: Any = None,\n            target: Callable[..., object] | None = None,\n            name: str | None = None,\n            args: Iterable[Any] = (),\n            kwargs: Mapping[str, Any] | None = {},\n        ) -> None: ...\n\nProcess = DummyProcess\n\nclass Namespace:\n    def __init__(self, **kwds: Any) -> None: ...\n    def __getattr__(self, name: str, /) -> Any: ...\n    def __setattr__(self, name: str, value: Any, /) -> None: ...\n\nclass Value:\n    _typecode: Any\n    _value: Any\n    value: Any\n    def __init__(self, typecode: Any, value: Any, lock: Any = True) -> None: ...\n\ndef Array(typecode: Any, sequence: Sequence[Any], lock: Any = True) -> array.array[Any]: ...\ndef Manager() -> Any: ...\ndef Pool(processes: int | None = None, initializer: Callable[..., object] | None = None, initargs: Iterable[Any] = ()) -> Any: ...\ndef active_children() -> list[Any]: ...\n\ncurrent_process = threading.current_thread\n\ndef freeze_support() -> None: ...\ndef shutdown() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/dummy/connection.pyi",
    "content": "from multiprocessing.connection import _Address\nfrom queue import Queue\nfrom types import TracebackType\nfrom typing import Any\nfrom typing_extensions import Self\n\n__all__ = [\"Client\", \"Listener\", \"Pipe\"]\n\nfamilies: list[None]\n\nclass Connection:\n    _in: Any\n    _out: Any\n    recv: Any\n    recv_bytes: Any\n    send: Any\n    send_bytes: Any\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n    def __init__(self, _in: Any, _out: Any) -> None: ...\n    def close(self) -> None: ...\n    def poll(self, timeout: float = 0.0) -> bool: ...\n\nclass Listener:\n    _backlog_queue: Queue[Any] | None\n    @property\n    def address(self) -> Queue[Any] | None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n    def __init__(self, address: _Address | None = None, family: int | None = None, backlog: int = 1) -> None: ...\n    def accept(self) -> Connection: ...\n    def close(self) -> None: ...\n\ndef Client(address: _Address) -> Connection: ...\ndef Pipe(duplex: bool = True) -> tuple[Connection, Connection]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/forkserver.pyi",
    "content": "import sys\nfrom _typeshed import FileDescriptorLike, Unused\nfrom collections.abc import Sequence\nfrom struct import Struct\nfrom typing import Any, Final\n\n__all__ = [\"ensure_running\", \"get_inherited_fds\", \"connect_to_new_process\", \"set_forkserver_preload\"]\n\nMAXFDS_TO_SEND: Final = 256\nSIGNED_STRUCT: Final[Struct]\n\nclass ForkServer:\n    def set_forkserver_preload(self, modules_names: list[str]) -> None: ...\n    def get_inherited_fds(self) -> list[int] | None: ...\n    def connect_to_new_process(self, fds: Sequence[int]) -> tuple[int, int]: ...\n    def ensure_running(self) -> None: ...\n\nif sys.version_info >= (3, 14):\n    # `sys_argv` parameter added in Python 3.14.3\n    def main(\n        listener_fd: int | None,\n        alive_r: FileDescriptorLike,\n        preload: Sequence[str],\n        main_path: str | None = None,\n        sys_path: list[str] | None = None,\n        *,\n        sys_argv: list[str] | None = None,\n        authkey_r: int | None = None,\n    ) -> None: ...\n\nelif sys.version_info >= (3, 13):\n    # `sys_argv` parameter added in Python 3.13.12\n    def main(\n        listener_fd: int | None,\n        alive_r: FileDescriptorLike,\n        preload: Sequence[str],\n        main_path: str | None = None,\n        sys_path: list[str] | None = None,\n        *,\n        sys_argv: list[str] | None = None,\n    ) -> None: ...\n\nelse:\n    def main(\n        listener_fd: int | None,\n        alive_r: FileDescriptorLike,\n        preload: Sequence[str],\n        main_path: str | None = None,\n        sys_path: Unused = None,\n    ) -> None: ...\n\ndef read_signed(fd: int) -> Any: ...\ndef write_signed(fd: int, n: int) -> None: ...\n\n_forkserver: ForkServer\nensure_running = _forkserver.ensure_running\nget_inherited_fds = _forkserver.get_inherited_fds\nconnect_to_new_process = _forkserver.connect_to_new_process\nset_forkserver_preload = _forkserver.set_forkserver_preload\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/heap.pyi",
    "content": "import sys\nfrom _typeshed import Incomplete\nfrom collections.abc import Callable\nfrom mmap import mmap\nfrom typing import Protocol, type_check_only\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"BufferWrapper\"]\n\nclass Arena:\n    size: int\n    buffer: mmap\n    if sys.platform == \"win32\":\n        name: str\n        def __init__(self, size: int) -> None: ...\n    else:\n        fd: int\n        def __init__(self, size: int, fd: int = -1) -> None: ...\n\n_Block: TypeAlias = tuple[Arena, int, int]\n\nif sys.platform != \"win32\":\n    @type_check_only\n    class _SupportsDetach(Protocol):\n        def detach(self) -> int: ...\n\n    def reduce_arena(a: Arena) -> tuple[Callable[[int, _SupportsDetach], Arena], tuple[int, Incomplete]]: ...\n    def rebuild_arena(size: int, dupfd: _SupportsDetach) -> Arena: ...\n\nclass Heap:\n    def __init__(self, size: int = ...) -> None: ...\n    def free(self, block: _Block) -> None: ...\n    def malloc(self, size: int) -> _Block: ...\n\nclass BufferWrapper:\n    def __init__(self, size: int) -> None: ...\n    def create_memoryview(self) -> memoryview: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/managers.pyi",
    "content": "import queue\nimport sys\nimport threading\nfrom _typeshed import SupportsKeysAndGetItem, SupportsRichComparison, SupportsRichComparisonT\nfrom collections.abc import (\n    Callable,\n    Iterable,\n    Iterator,\n    Mapping,\n    MutableMapping,\n    MutableSequence,\n    MutableSet,\n    Sequence,\n    Set as AbstractSet,\n)\nfrom types import GenericAlias, TracebackType\nfrom typing import Any, AnyStr, ClassVar, Generic, SupportsIndex, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias\n\nfrom . import pool\nfrom .connection import Connection, _Address\nfrom .context import BaseContext\nfrom .shared_memory import _SLT, ShareableList as _ShareableList, SharedMemory as _SharedMemory\nfrom .util import Finalize as _Finalize\n\n__all__ = [\"BaseManager\", \"SyncManager\", \"BaseProxy\", \"Token\", \"SharedMemoryManager\"]\n\n_T = TypeVar(\"_T\")\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n_KT = TypeVar(\"_KT\")\n_VT = TypeVar(\"_VT\")\n_S = TypeVar(\"_S\")\n\nclass Namespace:\n    def __init__(self, **kwds: Any) -> None: ...\n    def __getattr__(self, name: str, /) -> Any: ...\n    def __setattr__(self, name: str, value: Any, /) -> None: ...\n\n_Namespace: TypeAlias = Namespace\n\nclass Token:\n    __slots__ = (\"typeid\", \"address\", \"id\")\n    typeid: str | bytes | None\n    address: _Address | None\n    id: str | bytes | int | None\n    def __init__(self, typeid: bytes | str | None, address: _Address | None, id: str | bytes | int | None) -> None: ...\n    def __getstate__(self) -> tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]: ...\n    def __setstate__(self, state: tuple[str | bytes | None, tuple[str | bytes, int], str | bytes | int | None]) -> None: ...\n\nclass BaseProxy:\n    _address_to_local: dict[_Address, Any]\n    _mutex: Any\n    def __init__(\n        self,\n        token: Any,\n        serializer: str,\n        manager: Any = None,\n        authkey: AnyStr | None = None,\n        exposed: Any = None,\n        incref: bool = True,\n        manager_owned: bool = False,\n    ) -> None: ...\n    def __deepcopy__(self, memo: Any | None) -> Any: ...\n    def _callmethod(self, methodname: str, args: tuple[Any, ...] = (), kwds: dict[Any, Any] = {}) -> None: ...\n    def _getvalue(self) -> Any: ...\n    def __reduce__(self) -> tuple[Any, tuple[Any, Any, str, dict[Any, Any]]]: ...\n\nclass ValueProxy(BaseProxy, Generic[_T]):\n    def get(self) -> _T: ...\n    def set(self, value: _T) -> None: ...\n    value: _T\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nif sys.version_info >= (3, 13):\n    class _BaseDictProxy(BaseProxy, MutableMapping[_KT, _VT]):\n        __builtins__: ClassVar[dict[str, Any]]\n        def __len__(self) -> int: ...\n        def __getitem__(self, key: _KT, /) -> _VT: ...\n        def __setitem__(self, key: _KT, value: _VT, /) -> None: ...\n        def __delitem__(self, key: _KT, /) -> None: ...\n        def __iter__(self) -> Iterator[_KT]: ...\n        def copy(self) -> dict[_KT, _VT]: ...\n        @overload  # type: ignore[override]\n        def get(self, key: _KT, /) -> _VT | None: ...\n        @overload\n        def get(self, key: _KT, default: _VT, /) -> _VT: ...\n        @overload\n        def get(self, key: _KT, default: _T, /) -> _VT | _T: ...\n        @overload\n        def pop(self, key: _KT, /) -> _VT: ...\n        @overload\n        def pop(self, key: _KT, default: _VT, /) -> _VT: ...\n        @overload\n        def pop(self, key: _KT, default: _T, /) -> _VT | _T: ...\n        def keys(self) -> list[_KT]: ...  # type: ignore[override]\n        def items(self) -> list[tuple[_KT, _VT]]: ...  # type: ignore[override]\n        def values(self) -> list[_VT]: ...  # type: ignore[override]\n        if sys.version_info >= (3, 14):\n            # Next methods are copied from builtins.dict\n            @overload\n            def fromkeys(self, iterable: Iterable[_T], value: None = None, /) -> dict[_T, Any | None]: ...\n            @overload\n            def fromkeys(self, iterable: Iterable[_T], value: _S, /) -> dict[_T, _S]: ...\n            def __reversed__(self) -> Iterator[_KT]: ...\n            @overload\n            def __or__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ...\n            @overload\n            def __or__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ...\n            @overload\n            def __ror__(self, value: dict[_KT, _VT], /) -> dict[_KT, _VT]: ...\n            @overload\n            def __ror__(self, value: dict[_T1, _T2], /) -> dict[_KT | _T1, _VT | _T2]: ...\n            @overload  # type: ignore[misc]\n            def __ior__(self, value: SupportsKeysAndGetItem[_KT, _VT], /) -> Self: ...\n            @overload\n            def __ior__(self, value: Iterable[tuple[_KT, _VT]], /) -> Self: ...\n\n    class DictProxy(_BaseDictProxy[_KT, _VT]):\n        def __class_getitem__(cls, args: Any, /) -> GenericAlias: ...\n\nelse:\n    class DictProxy(BaseProxy, MutableMapping[_KT, _VT]):\n        __builtins__: ClassVar[dict[str, Any]]\n        def __len__(self) -> int: ...\n        def __getitem__(self, key: _KT, /) -> _VT: ...\n        def __setitem__(self, key: _KT, value: _VT, /) -> None: ...\n        def __delitem__(self, key: _KT, /) -> None: ...\n        def __iter__(self) -> Iterator[_KT]: ...\n        def copy(self) -> dict[_KT, _VT]: ...\n        @overload  # type: ignore[override]\n        def get(self, key: _KT, /) -> _VT | None: ...\n        @overload\n        def get(self, key: _KT, default: _VT, /) -> _VT: ...\n        @overload\n        def get(self, key: _KT, default: _T, /) -> _VT | _T: ...\n        @overload\n        def pop(self, key: _KT, /) -> _VT: ...\n        @overload\n        def pop(self, key: _KT, default: _VT, /) -> _VT: ...\n        @overload\n        def pop(self, key: _KT, default: _T, /) -> _VT | _T: ...\n        def keys(self) -> list[_KT]: ...  # type: ignore[override]\n        def items(self) -> list[tuple[_KT, _VT]]: ...  # type: ignore[override]\n        def values(self) -> list[_VT]: ...  # type: ignore[override]\n\nif sys.version_info >= (3, 14):\n    class _BaseSetProxy(BaseProxy, MutableSet[_T]):\n        __builtins__: ClassVar[dict[str, Any]]\n        # Copied from builtins.set\n        def add(self, element: _T, /) -> None: ...\n        def copy(self) -> set[_T]: ...\n        def clear(self) -> None: ...\n        def difference(self, *s: Iterable[Any]) -> set[_T]: ...\n        def difference_update(self, *s: Iterable[Any]) -> None: ...\n        def discard(self, element: _T, /) -> None: ...\n        def intersection(self, *s: Iterable[Any]) -> set[_T]: ...\n        def intersection_update(self, *s: Iterable[Any]) -> None: ...\n        def isdisjoint(self, s: Iterable[Any], /) -> bool: ...\n        def issubset(self, s: Iterable[Any], /) -> bool: ...\n        def issuperset(self, s: Iterable[Any], /) -> bool: ...\n        def pop(self) -> _T: ...\n        def remove(self, element: _T, /) -> None: ...\n        def symmetric_difference(self, s: Iterable[_T], /) -> set[_T]: ...\n        def symmetric_difference_update(self, s: Iterable[_T], /) -> None: ...\n        def union(self, *s: Iterable[_S]) -> set[_T | _S]: ...\n        def update(self, *s: Iterable[_T]) -> None: ...\n        def __len__(self) -> int: ...\n        def __contains__(self, o: object, /) -> bool: ...\n        def __iter__(self) -> Iterator[_T]: ...\n        def __and__(self, value: AbstractSet[object], /) -> set[_T]: ...\n        def __iand__(self, value: AbstractSet[object], /) -> Self: ...\n        def __or__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ...\n        def __ior__(self, value: AbstractSet[_T], /) -> Self: ...  # type: ignore[override,misc]\n        def __sub__(self, value: AbstractSet[_T | None], /) -> set[_T]: ...\n        def __isub__(self, value: AbstractSet[object], /) -> Self: ...\n        def __xor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ...\n        def __ixor__(self, value: AbstractSet[_T], /) -> Self: ...  # type: ignore[override,misc]\n        def __le__(self, value: AbstractSet[object], /) -> bool: ...\n        def __lt__(self, value: AbstractSet[object], /) -> bool: ...\n        def __ge__(self, value: AbstractSet[object], /) -> bool: ...\n        def __gt__(self, value: AbstractSet[object], /) -> bool: ...\n        def __eq__(self, value: object, /) -> bool: ...\n        def __rand__(self, value: AbstractSet[object], /) -> set[_T]: ...\n        def __ror__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ...  # type: ignore[misc]\n        def __rsub__(self, value: AbstractSet[_T], /) -> set[_T]: ...\n        def __rxor__(self, value: AbstractSet[_S], /) -> set[_T | _S]: ...  # type: ignore[misc]\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n    class SetProxy(_BaseSetProxy[_T]): ...\n\nclass BaseListProxy(BaseProxy, MutableSequence[_T]):\n    __builtins__: ClassVar[dict[str, Any]]\n    def __len__(self) -> int: ...\n    def __add__(self, x: list[_T], /) -> list[_T]: ...\n    def __delitem__(self, i: SupportsIndex | slice[SupportsIndex | None], /) -> None: ...\n    @overload\n    def __getitem__(self, i: SupportsIndex, /) -> _T: ...\n    @overload\n    def __getitem__(self, s: slice[SupportsIndex | None], /) -> list[_T]: ...\n    @overload\n    def __setitem__(self, i: SupportsIndex, o: _T, /) -> None: ...\n    @overload\n    def __setitem__(self, s: slice[SupportsIndex | None], o: Iterable[_T], /) -> None: ...\n    def __mul__(self, n: SupportsIndex, /) -> list[_T]: ...\n    def __rmul__(self, n: SupportsIndex, /) -> list[_T]: ...\n    def __imul__(self, value: SupportsIndex, /) -> Self: ...\n    def __reversed__(self) -> Iterator[_T]: ...\n    def append(self, object: _T, /) -> None: ...\n    def extend(self, iterable: Iterable[_T], /) -> None: ...\n    def pop(self, index: SupportsIndex = ..., /) -> _T: ...\n    def index(self, value: _T, start: SupportsIndex = ..., stop: SupportsIndex = ..., /) -> int: ...\n    def count(self, value: _T, /) -> int: ...\n    def insert(self, index: SupportsIndex, object: _T, /) -> None: ...\n    def remove(self, value: _T, /) -> None: ...\n    if sys.version_info >= (3, 14):\n        # Next methods are copied from builtins.list\n        def clear(self) -> None: ...\n        def copy(self) -> list[_T]: ...\n    # Use BaseListProxy[SupportsRichComparisonT] for the first overload rather than [SupportsRichComparison]\n    # to work around invariance\n    @overload\n    def sort(self: BaseListProxy[SupportsRichComparisonT], *, key: None = None, reverse: bool = ...) -> None: ...\n    @overload\n    def sort(self, *, key: Callable[[_T], SupportsRichComparison], reverse: bool = ...) -> None: ...\n\nclass ListProxy(BaseListProxy[_T]):\n    def __iadd__(self, value: Iterable[_T], /) -> Self: ...  # type: ignore[override]\n    def __imul__(self, value: SupportsIndex, /) -> Self: ...  # type: ignore[override]\n    if sys.version_info >= (3, 13):\n        def __class_getitem__(cls, args: Any, /) -> Any: ...\n\n# Send is (kind, result)\n# Receive is (id, methodname, args, kwds)\n_ServerConnection: TypeAlias = Connection[tuple[str, Any], tuple[str, str, Iterable[Any], Mapping[str, Any]]]\n\n# Returned by BaseManager.get_server()\nclass Server:\n    address: _Address | None\n    id_to_obj: dict[str, tuple[Any, set[str], dict[str, str]]]\n    fallback_mapping: dict[str, Callable[[_ServerConnection, str, Any], Any]]\n    public: list[str]\n    # Registry values are (callable, exposed, method_to_typeid, proxytype)\n    def __init__(\n        self,\n        registry: dict[str, tuple[Callable[..., Any], Iterable[str], dict[str, str], Any]],\n        address: _Address | None,\n        authkey: bytes,\n        serializer: str,\n    ) -> None: ...\n    def serve_forever(self) -> None: ...\n    def accepter(self) -> None: ...\n    if sys.version_info >= (3, 10):\n        def handle_request(self, conn: _ServerConnection) -> None: ...\n    else:\n        def handle_request(self, c: _ServerConnection) -> None: ...\n\n    def serve_client(self, conn: _ServerConnection) -> None: ...\n    def fallback_getvalue(self, conn: _ServerConnection, ident: str, obj: _T) -> _T: ...\n    def fallback_str(self, conn: _ServerConnection, ident: str, obj: Any) -> str: ...\n    def fallback_repr(self, conn: _ServerConnection, ident: str, obj: Any) -> str: ...\n    def dummy(self, c: _ServerConnection) -> None: ...\n    def debug_info(self, c: _ServerConnection) -> str: ...\n    def number_of_objects(self, c: _ServerConnection) -> int: ...\n    def shutdown(self, c: _ServerConnection) -> None: ...\n    def create(self, c: _ServerConnection, typeid: str, /, *args: Any, **kwds: Any) -> tuple[str, tuple[str, ...]]: ...\n    def get_methods(self, c: _ServerConnection, token: Token) -> set[str]: ...\n    def accept_connection(self, c: _ServerConnection, name: str) -> None: ...\n    def incref(self, c: _ServerConnection, ident: str) -> None: ...\n    def decref(self, c: _ServerConnection, ident: str) -> None: ...\n\nclass BaseManager:\n    if sys.version_info >= (3, 11):\n        def __init__(\n            self,\n            address: _Address | None = None,\n            authkey: bytes | None = None,\n            serializer: str = \"pickle\",\n            ctx: BaseContext | None = None,\n            *,\n            shutdown_timeout: float = 1.0,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            address: _Address | None = None,\n            authkey: bytes | None = None,\n            serializer: str = \"pickle\",\n            ctx: BaseContext | None = None,\n        ) -> None: ...\n\n    def get_server(self) -> Server: ...\n    def connect(self) -> None: ...\n    def start(self, initializer: Callable[..., object] | None = None, initargs: Iterable[Any] = ()) -> None: ...\n    shutdown: _Finalize  # only available after start() was called\n    def join(self, timeout: float | None = None) -> None: ...  # undocumented\n    @property\n    def address(self) -> _Address | None: ...\n    @classmethod\n    def register(\n        cls,\n        typeid: str,\n        callable: Callable[..., object] | None = None,\n        proxytype: Any = None,\n        exposed: Sequence[str] | None = None,\n        method_to_typeid: Mapping[str, str] | None = None,\n        create_method: bool = True,\n    ) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n\nclass SyncManager(BaseManager):\n    def Barrier(\n        self, parties: int, action: Callable[[], None] | None = None, timeout: float | None = None\n    ) -> threading.Barrier: ...\n    def BoundedSemaphore(self, value: int = 1) -> threading.BoundedSemaphore: ...\n    def Condition(self, lock: threading.Lock | threading._RLock | None = None) -> threading.Condition: ...\n    def Event(self) -> threading.Event: ...\n    def Lock(self) -> threading.Lock: ...\n    def Namespace(self) -> _Namespace: ...\n    def Pool(\n        self,\n        processes: int | None = None,\n        initializer: Callable[..., object] | None = None,\n        initargs: Iterable[Any] = (),\n        maxtasksperchild: int | None = None,\n        context: Any | None = None,\n    ) -> pool.Pool: ...\n    def Queue(self, maxsize: int = ...) -> queue.Queue[Any]: ...\n    def JoinableQueue(self, maxsize: int = ...) -> queue.Queue[Any]: ...\n    def RLock(self) -> threading.RLock: ...\n    def Semaphore(self, value: int = 1) -> threading.Semaphore: ...\n    def Array(self, typecode: Any, sequence: Sequence[_T]) -> Sequence[_T]: ...\n    def Value(self, typecode: Any, value: _T) -> ValueProxy[_T]: ...\n    # Overloads are copied from builtins.dict.__init__\n    @overload\n    def dict(self) -> DictProxy[Any, Any]: ...\n    @overload\n    def dict(self, **kwargs: _VT) -> DictProxy[str, _VT]: ...\n    @overload\n    def dict(self, map: SupportsKeysAndGetItem[_KT, _VT], /) -> DictProxy[_KT, _VT]: ...\n    @overload\n    def dict(self, map: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> DictProxy[str, _VT]: ...\n    @overload\n    def dict(self, iterable: Iterable[tuple[_KT, _VT]], /) -> DictProxy[_KT, _VT]: ...\n    @overload\n    def dict(self, iterable: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> DictProxy[str, _VT]: ...\n    @overload\n    def dict(self, iterable: Iterable[list[str]], /) -> DictProxy[str, str]: ...\n    @overload\n    def dict(self, iterable: Iterable[list[bytes]], /) -> DictProxy[bytes, bytes]: ...\n    # Overloads are copied from builtins.list.__init__\n    @overload\n    def list(self, iterable: Iterable[_T], /) -> ListProxy[_T]: ...\n    @overload\n    def list(self) -> ListProxy[Any]: ...\n    if sys.version_info >= (3, 14):\n        @overload\n        def set(self, iterable: Iterable[_T], /) -> SetProxy[_T]: ...\n        @overload\n        def set(self) -> SetProxy[Any]: ...\n\nclass RemoteError(Exception): ...\n\nclass SharedMemoryServer(Server):\n    def track_segment(self, c: _ServerConnection, segment_name: str) -> None: ...\n    def release_segment(self, c: _ServerConnection, segment_name: str) -> None: ...\n    def list_segments(self, c: _ServerConnection) -> list[str]: ...\n\nclass SharedMemoryManager(BaseManager):\n    def get_server(self) -> SharedMemoryServer: ...\n    def SharedMemory(self, size: int) -> _SharedMemory: ...\n    def ShareableList(self, sequence: Iterable[_SLT] | None) -> _ShareableList[_SLT]: ...\n    def __del__(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/pool.pyi",
    "content": "from collections.abc import Callable, Iterable, Iterator, Mapping\nfrom multiprocessing.context import DefaultContext, Process\nfrom types import GenericAlias, TracebackType\nfrom typing import Any, Final, Generic, TypeVar\nfrom typing_extensions import Self\n\n__all__ = [\"Pool\", \"ThreadPool\"]\n\n_S = TypeVar(\"_S\")\n_T = TypeVar(\"_T\")\n\nclass ApplyResult(Generic[_T]):\n    def __init__(\n        self, pool: Pool, callback: Callable[[_T], object] | None, error_callback: Callable[[BaseException], object] | None\n    ) -> None: ...\n    def get(self, timeout: float | None = None) -> _T: ...\n    def wait(self, timeout: float | None = None) -> None: ...\n    def ready(self) -> bool: ...\n    def successful(self) -> bool: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n# alias created during issue #17805\nAsyncResult = ApplyResult\n\nclass MapResult(ApplyResult[list[_T]]):\n    def __init__(\n        self,\n        pool: Pool,\n        chunksize: int,\n        length: int,\n        callback: Callable[[list[_T]], object] | None,\n        error_callback: Callable[[BaseException], object] | None,\n    ) -> None: ...\n\nclass IMapIterator(Iterator[_T]):\n    def __init__(self, pool: Pool) -> None: ...\n    def __iter__(self) -> Self: ...\n    def next(self, timeout: float | None = None) -> _T: ...\n    def __next__(self, timeout: float | None = None) -> _T: ...\n\nclass IMapUnorderedIterator(IMapIterator[_T]): ...\n\nclass Pool:\n    def __init__(\n        self,\n        processes: int | None = None,\n        initializer: Callable[..., object] | None = None,\n        initargs: Iterable[Any] = (),\n        maxtasksperchild: int | None = None,\n        context: Any | None = None,\n    ) -> None: ...\n    @staticmethod\n    def Process(ctx: DefaultContext, *args: Any, **kwds: Any) -> Process: ...\n    def apply(self, func: Callable[..., _T], args: Iterable[Any] = (), kwds: Mapping[str, Any] = {}) -> _T: ...\n    def apply_async(\n        self,\n        func: Callable[..., _T],\n        args: Iterable[Any] = (),\n        kwds: Mapping[str, Any] = {},\n        callback: Callable[[_T], object] | None = None,\n        error_callback: Callable[[BaseException], object] | None = None,\n    ) -> AsyncResult[_T]: ...\n    def map(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = None) -> list[_T]: ...\n    def map_async(\n        self,\n        func: Callable[[_S], _T],\n        iterable: Iterable[_S],\n        chunksize: int | None = None,\n        callback: Callable[[list[_T]], object] | None = None,\n        error_callback: Callable[[BaseException], object] | None = None,\n    ) -> MapResult[_T]: ...\n    def imap(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = 1) -> IMapIterator[_T]: ...\n    def imap_unordered(self, func: Callable[[_S], _T], iterable: Iterable[_S], chunksize: int | None = 1) -> IMapIterator[_T]: ...\n    def starmap(self, func: Callable[..., _T], iterable: Iterable[Iterable[Any]], chunksize: int | None = None) -> list[_T]: ...\n    def starmap_async(\n        self,\n        func: Callable[..., _T],\n        iterable: Iterable[Iterable[Any]],\n        chunksize: int | None = None,\n        callback: Callable[[list[_T]], object] | None = None,\n        error_callback: Callable[[BaseException], object] | None = None,\n    ) -> AsyncResult[list[_T]]: ...\n    def close(self) -> None: ...\n    def terminate(self) -> None: ...\n    def join(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n    def __del__(self) -> None: ...\n\nclass ThreadPool(Pool):\n    def __init__(\n        self, processes: int | None = None, initializer: Callable[..., object] | None = None, initargs: Iterable[Any] = ()\n    ) -> None: ...\n\n# undocumented\nINIT: Final = \"INIT\"\nRUN: Final = \"RUN\"\nCLOSE: Final = \"CLOSE\"\nTERMINATE: Final = \"TERMINATE\"\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/popen_fork.pyi",
    "content": "import sys\nfrom typing import ClassVar\n\nfrom .process import BaseProcess\nfrom .util import Finalize\n\nif sys.platform != \"win32\":\n    __all__ = [\"Popen\"]\n\n    class Popen:\n        finalizer: Finalize | None\n        method: ClassVar[str]\n        pid: int\n        returncode: int | None\n        sentinel: int  # doesn't exist if os.fork in _launch returns 0\n\n        def __init__(self, process_obj: BaseProcess) -> None: ...\n        def duplicate_for_child(self, fd: int) -> int: ...\n        def poll(self, flag: int = 1) -> int | None: ...\n        def wait(self, timeout: float | None = None) -> int | None: ...\n        if sys.version_info >= (3, 14):\n            def interrupt(self) -> None: ...\n\n        def terminate(self) -> None: ...\n        def kill(self) -> None: ...\n        def close(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/popen_forkserver.pyi",
    "content": "import sys\nfrom typing import ClassVar\n\nfrom . import popen_fork\nfrom .util import Finalize\n\nif sys.platform != \"win32\":\n    __all__ = [\"Popen\"]\n\n    class _DupFd:\n        def __init__(self, ind: int) -> None: ...\n        def detach(self) -> int: ...\n\n    class Popen(popen_fork.Popen):\n        DupFd: ClassVar[type[_DupFd]]\n        finalizer: Finalize\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/popen_spawn_posix.pyi",
    "content": "import sys\nfrom typing import ClassVar\n\nfrom . import popen_fork\nfrom .util import Finalize\n\nif sys.platform != \"win32\":\n    __all__ = [\"Popen\"]\n\n    class _DupFd:\n        fd: int\n\n        def __init__(self, fd: int) -> None: ...\n        def detach(self) -> int: ...\n\n    class Popen(popen_fork.Popen):\n        DupFd: ClassVar[type[_DupFd]]\n        finalizer: Finalize\n        pid: int  # may not exist if _launch raises in second try / except\n        sentinel: int  # may not exist if _launch raises in second try / except\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/popen_spawn_win32.pyi",
    "content": "import sys\nfrom multiprocessing.process import BaseProcess\nfrom typing import ClassVar, Final\n\nfrom .util import Finalize\n\nif sys.platform == \"win32\":\n    __all__ = [\"Popen\"]\n\n    TERMINATE: Final[int]\n    WINEXE: Final[bool]\n    WINSERVICE: Final[bool]\n    WINENV: Final[bool]\n\n    class Popen:\n        finalizer: Finalize\n        method: ClassVar[str]\n        pid: int\n        returncode: int | None\n        sentinel: int\n\n        def __init__(self, process_obj: BaseProcess) -> None: ...\n        def duplicate_for_child(self, handle: int) -> int: ...\n        def wait(self, timeout: float | None = None) -> int | None: ...\n        def poll(self) -> int | None: ...\n        def terminate(self) -> None: ...\n\n        kill = terminate\n\n        def close(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/process.pyi",
    "content": "import sys\nfrom collections.abc import Callable, Iterable, Mapping\nfrom typing import Any\n\n__all__ = [\"BaseProcess\", \"current_process\", \"active_children\", \"parent_process\"]\n\nclass BaseProcess:\n    name: str\n    daemon: bool\n    authkey: bytes\n    _identity: tuple[int, ...]  # undocumented\n    def __init__(\n        self,\n        group: None = None,\n        target: Callable[..., object] | None = None,\n        name: str | None = None,\n        args: Iterable[Any] = (),\n        kwargs: Mapping[str, Any] = {},\n        *,\n        daemon: bool | None = None,\n    ) -> None: ...\n    def run(self) -> None: ...\n    def start(self) -> None: ...\n    if sys.version_info >= (3, 14):\n        def interrupt(self) -> None: ...\n\n    def terminate(self) -> None: ...\n    def kill(self) -> None: ...\n    def close(self) -> None: ...\n    def join(self, timeout: float | None = None) -> None: ...\n    def is_alive(self) -> bool: ...\n    @property\n    def exitcode(self) -> int | None: ...\n    @property\n    def ident(self) -> int | None: ...\n    @property\n    def pid(self) -> int | None: ...\n    @property\n    def sentinel(self) -> int: ...\n\ndef current_process() -> BaseProcess: ...\ndef active_children() -> list[BaseProcess]: ...\ndef parent_process() -> BaseProcess | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/queues.pyi",
    "content": "import sys\nfrom types import GenericAlias\nfrom typing import Any, Generic, NewType, TypeVar\n\n__all__ = [\"Queue\", \"SimpleQueue\", \"JoinableQueue\"]\n\n_T = TypeVar(\"_T\")\n\n_QueueState = NewType(\"_QueueState\", object)\n_JoinableQueueState = NewType(\"_JoinableQueueState\", object)\n_SimpleQueueState = NewType(\"_SimpleQueueState\", object)\n\nclass Queue(Generic[_T]):\n    # FIXME: `ctx` is a circular dependency and it's not actually optional.\n    # It's marked as such to be able to use the generic Queue in __init__.pyi.\n    def __init__(self, maxsize: int = 0, *, ctx: Any = ...) -> None: ...\n    def __getstate__(self) -> _QueueState: ...\n    def __setstate__(self, state: _QueueState) -> None: ...\n    def put(self, obj: _T, block: bool = True, timeout: float | None = None) -> None: ...\n    def get(self, block: bool = True, timeout: float | None = None) -> _T: ...\n    def qsize(self) -> int: ...\n    def empty(self) -> bool: ...\n    def full(self) -> bool: ...\n    def get_nowait(self) -> _T: ...\n    def put_nowait(self, obj: _T) -> None: ...\n    def close(self) -> None: ...\n    def join_thread(self) -> None: ...\n    def cancel_join_thread(self) -> None: ...\n    if sys.version_info >= (3, 12):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass JoinableQueue(Queue[_T]):\n    def __getstate__(self) -> _JoinableQueueState: ...  # type: ignore[override]\n    def __setstate__(self, state: _JoinableQueueState) -> None: ...  # type: ignore[override]\n    def task_done(self) -> None: ...\n    def join(self) -> None: ...\n\nclass SimpleQueue(Generic[_T]):\n    def __init__(self, *, ctx: Any = ...) -> None: ...\n    def close(self) -> None: ...\n    def empty(self) -> bool: ...\n    def __getstate__(self) -> _SimpleQueueState: ...\n    def __setstate__(self, state: _SimpleQueueState) -> None: ...\n    def get(self) -> _T: ...\n    def put(self, obj: _T) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/reduction.pyi",
    "content": "import pickle\nimport sys\nfrom _pickle import _BufferCallback, _ReducedType\nfrom _typeshed import HasFileno, SupportsWrite, Unused\nfrom abc import ABCMeta\nfrom builtins import type as Type  # alias to avoid name clash\nfrom collections.abc import Callable\nfrom copyreg import _DispatchTableType\nfrom multiprocessing import connection\nfrom socket import socket\nfrom typing import Any, Final\n\nif sys.platform == \"win32\":\n    __all__ = [\"send_handle\", \"recv_handle\", \"ForkingPickler\", \"register\", \"dump\", \"DupHandle\", \"duplicate\", \"steal_handle\"]\nelse:\n    __all__ = [\"send_handle\", \"recv_handle\", \"ForkingPickler\", \"register\", \"dump\", \"DupFd\", \"sendfds\", \"recvfds\"]\n\nHAVE_SEND_HANDLE: Final[bool]\n\nclass ForkingPickler(pickle.Pickler):\n    dispatch_table: _DispatchTableType\n    def __init__(\n        self,\n        file: SupportsWrite[bytes],\n        protocol: int | None = None,\n        fix_imports: bool = True,\n        buffer_callback: _BufferCallback = None,\n        /,\n    ) -> None: ...\n    @classmethod\n    def register(cls, type: Type, reduce: Callable[[Any], _ReducedType]) -> None: ...\n    @classmethod\n    def dumps(cls, obj: Any, protocol: int | None = None) -> memoryview: ...\n    loads = pickle.loads\n\nregister = ForkingPickler.register\n\ndef dump(obj: Any, file: SupportsWrite[bytes], protocol: int | None = None) -> None: ...\n\nif sys.platform == \"win32\":\n    def duplicate(\n        handle: int, target_process: int | None = None, inheritable: bool = False, *, source_process: int | None = None\n    ) -> int: ...\n    def steal_handle(source_pid: int, handle: int) -> int: ...\n    def send_handle(conn: connection.PipeConnection[DupHandle, Any], handle: int, destination_pid: int) -> None: ...\n    def recv_handle(conn: connection.PipeConnection[Any, DupHandle]) -> int: ...\n\n    class DupHandle:\n        def __init__(self, handle: int, access: int, pid: int | None = None) -> None: ...\n        def detach(self) -> int: ...\n\nelse:\n    if sys.version_info < (3, 14):\n        ACKNOWLEDGE: Final[bool]\n\n    def recvfds(sock: socket, size: int) -> list[int]: ...\n    def send_handle(conn: HasFileno, handle: int, destination_pid: Unused) -> None: ...\n    def recv_handle(conn: HasFileno) -> int: ...\n    def sendfds(sock: socket, fds: list[int]) -> None: ...\n    def DupFd(fd: int) -> Any: ...  # Return type is really hard to get right\n\n# These aliases are to work around pyright complaints.\n# Pyright doesn't like it when a class object is defined as an alias\n# of a global object with the same name.\n_ForkingPickler = ForkingPickler\n_register = register\n_dump = dump\n_send_handle = send_handle\n_recv_handle = recv_handle\n\nif sys.platform == \"win32\":\n    _steal_handle = steal_handle\n    _duplicate = duplicate\n    _DupHandle = DupHandle\nelse:\n    _sendfds = sendfds\n    _recvfds = recvfds\n    _DupFd = DupFd\n\nclass AbstractReducer(metaclass=ABCMeta):\n    ForkingPickler = _ForkingPickler\n    register = _register\n    dump = _dump\n    send_handle = _send_handle\n    recv_handle = _recv_handle\n    if sys.platform == \"win32\":\n        steal_handle = _steal_handle\n        duplicate = _duplicate\n        DupHandle = _DupHandle\n    else:\n        sendfds = _sendfds\n        recvfds = _recvfds\n        DupFd = _DupFd\n\n    def __init__(self, *args: Unused) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/resource_sharer.pyi",
    "content": "import sys\nfrom socket import socket\n\n__all__ = [\"stop\"]\n\nif sys.platform == \"win32\":\n    __all__ += [\"DupSocket\"]\n\n    class DupSocket:\n        def __init__(self, sock: socket) -> None: ...\n        def detach(self) -> socket: ...\n\nelse:\n    __all__ += [\"DupFd\"]\n\n    class DupFd:\n        def __init__(self, fd: int) -> None: ...\n        def detach(self) -> int: ...\n\ndef stop(timeout: float | None = None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/resource_tracker.pyi",
    "content": "import sys\nfrom _typeshed import FileDescriptorOrPath\nfrom collections.abc import Sized\n\n__all__ = [\"ensure_running\", \"register\", \"unregister\"]\n\nclass ResourceTracker:\n    def getfd(self) -> int | None: ...\n    def ensure_running(self) -> None: ...\n    def register(self, name: Sized, rtype: str) -> None: ...\n    def unregister(self, name: Sized, rtype: str) -> None: ...\n    if sys.version_info >= (3, 12):\n        def __del__(self) -> None: ...\n\n_resource_tracker: ResourceTracker\nensure_running = _resource_tracker.ensure_running\nregister = _resource_tracker.register\nunregister = _resource_tracker.unregister\ngetfd = _resource_tracker.getfd\n\ndef main(fd: FileDescriptorOrPath) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/shared_memory.pyi",
    "content": "import sys\nfrom collections.abc import Iterable\nfrom types import GenericAlias\nfrom typing import Any, Generic, TypeVar, overload\nfrom typing_extensions import Self\n\n__all__ = [\"SharedMemory\", \"ShareableList\"]\n\n_SLT = TypeVar(\"_SLT\", int, float, bool, str, bytes, None)\n\nclass SharedMemory:\n    if sys.version_info >= (3, 13):\n        def __init__(self, name: str | None = None, create: bool = False, size: int = 0, *, track: bool = True) -> None: ...\n    else:\n        def __init__(self, name: str | None = None, create: bool = False, size: int = 0) -> None: ...\n\n    @property\n    def buf(self) -> memoryview | None: ...\n    @property\n    def name(self) -> str: ...\n    @property\n    def size(self) -> int: ...\n    def close(self) -> None: ...\n    def unlink(self) -> None: ...\n    def __del__(self) -> None: ...\n\nclass ShareableList(Generic[_SLT]):\n    shm: SharedMemory\n    @overload\n    def __init__(self, sequence: None = None, *, name: str | None = None) -> None: ...\n    @overload\n    def __init__(self, sequence: Iterable[_SLT], *, name: str | None = None) -> None: ...\n    def __getitem__(self, position: int) -> _SLT: ...\n    def __setitem__(self, position: int, value: _SLT) -> None: ...\n    def __reduce__(self) -> tuple[Self, tuple[_SLT, ...]]: ...\n    def __len__(self) -> int: ...\n    @property\n    def format(self) -> str: ...\n    def count(self, value: _SLT) -> int: ...\n    def index(self, value: _SLT) -> int: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/sharedctypes.pyi",
    "content": "import ctypes\nfrom _ctypes import _CData\nfrom collections.abc import Callable, Iterable, Sequence\nfrom ctypes import _SimpleCData, c_char\nfrom multiprocessing.context import BaseContext\nfrom multiprocessing.synchronize import _LockLike\nfrom types import TracebackType\nfrom typing import Any, Generic, Literal, Protocol, SupportsIndex, TypeVar, overload, type_check_only\n\n__all__ = [\"RawValue\", \"RawArray\", \"Value\", \"Array\", \"copy\", \"synchronized\"]\n\n_T = TypeVar(\"_T\")\n_CT = TypeVar(\"_CT\", bound=_CData)\n\n@overload\ndef RawValue(typecode_or_type: type[_CT], *args: Any) -> _CT: ...\n@overload\ndef RawValue(typecode_or_type: str, *args: Any) -> Any: ...\n@overload\ndef RawArray(typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any]) -> ctypes.Array[_CT]: ...\n@overload\ndef RawArray(typecode_or_type: str, size_or_initializer: int | Sequence[Any]) -> Any: ...\n@overload\ndef Value(typecode_or_type: type[_CT], *args: Any, lock: Literal[False], ctx: BaseContext | None = None) -> _CT: ...\n@overload\ndef Value(\n    typecode_or_type: type[_CT], *args: Any, lock: Literal[True] | _LockLike = True, ctx: BaseContext | None = None\n) -> SynchronizedBase[_CT]: ...\n@overload\ndef Value(\n    typecode_or_type: str, *args: Any, lock: Literal[True] | _LockLike = True, ctx: BaseContext | None = None\n) -> SynchronizedBase[Any]: ...\n@overload\ndef Value(\n    typecode_or_type: str | type[_CData], *args: Any, lock: bool | _LockLike = True, ctx: BaseContext | None = None\n) -> Any: ...\n@overload\ndef Array(\n    typecode_or_type: type[_CT], size_or_initializer: int | Sequence[Any], *, lock: Literal[False], ctx: BaseContext | None = None\n) -> _CT: ...\n@overload\ndef Array(\n    typecode_or_type: type[c_char],\n    size_or_initializer: int | Sequence[Any],\n    *,\n    lock: Literal[True] | _LockLike = True,\n    ctx: BaseContext | None = None,\n) -> SynchronizedString: ...\n@overload\ndef Array(\n    typecode_or_type: type[_SimpleCData[_T]],\n    size_or_initializer: int | Sequence[Any],\n    *,\n    lock: Literal[True] | _LockLike = True,\n    ctx: BaseContext | None = None,\n) -> SynchronizedArray[_T]: ...\n@overload\ndef Array(\n    typecode_or_type: str,\n    size_or_initializer: int | Sequence[Any],\n    *,\n    lock: Literal[True] | _LockLike = True,\n    ctx: BaseContext | None = None,\n) -> SynchronizedArray[Any]: ...\n@overload\ndef Array(\n    typecode_or_type: str | type[_CData],\n    size_or_initializer: int | Sequence[Any],\n    *,\n    lock: bool | _LockLike = True,\n    ctx: BaseContext | None = None,\n) -> Any: ...\ndef copy(obj: _CT) -> _CT: ...\n@overload\ndef synchronized(obj: _SimpleCData[_T], lock: _LockLike | None = None, ctx: Any | None = None) -> Synchronized[_T]: ...\n@overload\ndef synchronized(obj: ctypes.Array[c_char], lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedString: ...\n@overload\ndef synchronized(\n    obj: ctypes.Array[_SimpleCData[_T]], lock: _LockLike | None = None, ctx: Any | None = None\n) -> SynchronizedArray[_T]: ...\n@overload\ndef synchronized(obj: _CT, lock: _LockLike | None = None, ctx: Any | None = None) -> SynchronizedBase[_CT]: ...\n@type_check_only\nclass _AcquireFunc(Protocol):\n    def __call__(self, block: bool = ..., timeout: float | None = ..., /) -> bool: ...\n\nclass SynchronizedBase(Generic[_CT]):\n    acquire: _AcquireFunc\n    release: Callable[[], None]\n    def __init__(self, obj: Any, lock: _LockLike | None = None, ctx: Any | None = None) -> None: ...\n    def __reduce__(self) -> tuple[Callable[[Any, _LockLike], SynchronizedBase[Any]], tuple[Any, _LockLike]]: ...\n    def get_obj(self) -> _CT: ...\n    def get_lock(self) -> _LockLike: ...\n    def __enter__(self) -> bool: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, /\n    ) -> None: ...\n\nclass Synchronized(SynchronizedBase[_SimpleCData[_T]], Generic[_T]):\n    value: _T\n\nclass SynchronizedArray(SynchronizedBase[ctypes.Array[_SimpleCData[_T]]], Generic[_T]):\n    def __len__(self) -> int: ...\n    @overload\n    def __getitem__(self, i: slice[SupportsIndex | None]) -> list[_T]: ...\n    @overload\n    def __getitem__(self, i: SupportsIndex) -> _T: ...\n    @overload\n    def __setitem__(self, i: slice[SupportsIndex | None], value: Iterable[_T]) -> None: ...\n    @overload\n    def __setitem__(self, i: SupportsIndex, value: _T) -> None: ...\n    def __getslice__(self, start: SupportsIndex, stop: SupportsIndex) -> list[_T]: ...\n    def __setslice__(self, start: SupportsIndex, stop: SupportsIndex, values: Iterable[_T]) -> None: ...\n\nclass SynchronizedString(SynchronizedArray[bytes]):\n    @overload  # type: ignore[override]\n    def __getitem__(self, i: slice[SupportsIndex | None]) -> bytes: ...\n    @overload\n    def __getitem__(self, i: SupportsIndex) -> bytes: ...\n    @overload  # type: ignore[override]\n    def __setitem__(self, i: slice[SupportsIndex | None], value: bytes) -> None: ...\n    @overload\n    def __setitem__(self, i: SupportsIndex, value: bytes) -> None: ...\n    def __getslice__(self, start: SupportsIndex, stop: SupportsIndex) -> bytes: ...  # type: ignore[override]\n    def __setslice__(self, start: SupportsIndex, stop: SupportsIndex, values: bytes) -> None: ...  # type: ignore[override]\n\n    value: bytes\n    raw: bytes\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/spawn.pyi",
    "content": "from collections.abc import Mapping, Sequence\nfrom types import ModuleType\nfrom typing import Any, Final\n\n__all__ = [\n    \"_main\",\n    \"freeze_support\",\n    \"set_executable\",\n    \"get_executable\",\n    \"get_preparation_data\",\n    \"get_command_line\",\n    \"import_main_path\",\n]\n\nWINEXE: Final[bool]\nWINSERVICE: Final[bool]\n\ndef set_executable(exe: str) -> None: ...\ndef get_executable() -> str: ...\ndef is_forking(argv: Sequence[str]) -> bool: ...\ndef freeze_support() -> None: ...\ndef get_command_line(**kwds: Any) -> list[str]: ...\ndef spawn_main(pipe_handle: int, parent_pid: int | None = None, tracker_fd: int | None = None) -> None: ...\n\n# undocumented\ndef _main(fd: int, parent_sentinel: int) -> int: ...\ndef get_preparation_data(name: str) -> dict[str, Any]: ...\n\nold_main_modules: list[ModuleType]\n\ndef prepare(data: Mapping[str, Any]) -> None: ...\ndef import_main_path(main_path: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/synchronize.pyi",
    "content": "import sys\nimport threading\nfrom collections.abc import Callable\nfrom multiprocessing.context import BaseContext\nfrom types import TracebackType\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"Lock\", \"RLock\", \"Semaphore\", \"BoundedSemaphore\", \"Condition\", \"Event\"]\n\n_LockLike: TypeAlias = Lock | RLock\n\nclass Barrier(threading.Barrier):\n    def __init__(\n        self, parties: int, action: Callable[[], object] | None = None, timeout: float | None = None, *, ctx: BaseContext\n    ) -> None: ...\n\nclass Condition:\n    def __init__(self, lock: _LockLike | None = None, *, ctx: BaseContext) -> None: ...\n    def notify(self, n: int = 1) -> None: ...\n    def notify_all(self) -> None: ...\n    def wait(self, timeout: float | None = None) -> bool: ...\n    def wait_for(self, predicate: Callable[[], bool], timeout: float | None = None) -> bool: ...\n    def __enter__(self) -> bool: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, /\n    ) -> None: ...\n    # These methods are copied from the lock passed to the constructor, or an\n    # instance of ctx.RLock() if lock was None.\n    def acquire(self, block: bool = True, timeout: float | None = None) -> bool: ...\n    def release(self) -> None: ...\n\nclass Event:\n    def __init__(self, *, ctx: BaseContext) -> None: ...\n    def is_set(self) -> bool: ...\n    def set(self) -> None: ...\n    def clear(self) -> None: ...\n    def wait(self, timeout: float | None = None) -> bool: ...\n\n# Not part of public API\nclass SemLock:\n    def __init__(self, kind: int, value: int, maxvalue: int, *, ctx: BaseContext | None) -> None: ...\n    def __enter__(self) -> bool: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None, /\n    ) -> None: ...\n    # These methods are copied from the wrapped _multiprocessing.SemLock object\n    def acquire(self, block: bool = True, timeout: float | None = None) -> bool: ...\n    def release(self) -> None: ...\n    if sys.version_info >= (3, 14):\n        def locked(self) -> bool: ...\n\nclass Lock(SemLock):\n    def __init__(self, *, ctx: BaseContext) -> None: ...\n\nclass RLock(SemLock):\n    def __init__(self, *, ctx: BaseContext) -> None: ...\n\nclass Semaphore(SemLock):\n    def __init__(self, value: int = 1, *, ctx: BaseContext) -> None: ...\n    def get_value(self) -> int: ...\n\nclass BoundedSemaphore(Semaphore):\n    def __init__(self, value: int = 1, *, ctx: BaseContext) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/multiprocessing/util.pyi",
    "content": "import sys\nimport threading\nfrom _typeshed import ConvertibleToInt, Incomplete, Unused\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom logging import Logger, _Level as _LoggingLevel\nfrom typing import Any, Final, Generic, TypeVar, overload\n\n__all__ = [\n    \"sub_debug\",\n    \"debug\",\n    \"info\",\n    \"sub_warning\",\n    \"get_logger\",\n    \"log_to_stderr\",\n    \"get_temp_dir\",\n    \"register_after_fork\",\n    \"is_exiting\",\n    \"Finalize\",\n    \"ForkAwareThreadLock\",\n    \"ForkAwareLocal\",\n    \"close_all_fds_except\",\n    \"SUBDEBUG\",\n    \"SUBWARNING\",\n]\n\nif sys.version_info >= (3, 14):\n    __all__ += [\"warn\"]\n\n_T = TypeVar(\"_T\")\n_R_co = TypeVar(\"_R_co\", default=Any, covariant=True)\n\nNOTSET: Final = 0\nSUBDEBUG: Final = 5\nDEBUG: Final = 10\nINFO: Final = 20\nSUBWARNING: Final = 25\nif sys.version_info >= (3, 14):\n    WARNING: Final = 30\n\nLOGGER_NAME: Final[str]\nDEFAULT_LOGGING_FORMAT: Final[str]\n\ndef sub_debug(msg: object, *args: object) -> None: ...\ndef debug(msg: object, *args: object) -> None: ...\ndef info(msg: object, *args: object) -> None: ...\n\nif sys.version_info >= (3, 14):\n    def warn(msg: object, *args: object) -> None: ...\n\ndef sub_warning(msg: object, *args: object) -> None: ...\ndef get_logger() -> Logger: ...\ndef log_to_stderr(level: _LoggingLevel | None = None) -> Logger: ...\ndef is_abstract_socket_namespace(address: str | bytes | None) -> bool: ...\n\nabstract_sockets_supported: Final[bool]\n\ndef get_temp_dir() -> str: ...\ndef register_after_fork(obj: _T, func: Callable[[_T], object]) -> None: ...\n\nclass Finalize(Generic[_R_co]):\n    # \"args\" and \"kwargs\" are passed as arguments to \"callback\".\n    @overload\n    def __init__(\n        self,\n        obj: None,\n        callback: Callable[..., _R_co],\n        *,\n        args: Sequence[Any] = (),\n        kwargs: Mapping[str, Any] | None = None,\n        exitpriority: int,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self, obj: None, callback: Callable[..., _R_co], args: Sequence[Any], kwargs: Mapping[str, Any] | None, exitpriority: int\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        obj: Any,\n        callback: Callable[..., _R_co],\n        args: Sequence[Any] = (),\n        kwargs: Mapping[str, Any] | None = None,\n        exitpriority: int | None = None,\n    ) -> None: ...\n    def __call__(\n        self,\n        wr: Unused = None,\n        _finalizer_registry: MutableMapping[Incomplete, Incomplete] = {},\n        sub_debug: Callable[..., object] = ...,\n        getpid: Callable[[], int] = ...,\n    ) -> _R_co: ...\n    def cancel(self) -> None: ...\n    def still_active(self) -> bool: ...\n\ndef is_exiting() -> bool: ...\n\nclass ForkAwareThreadLock:\n    acquire: Callable[[bool, float], bool]\n    release: Callable[[], None]\n    def __enter__(self) -> bool: ...\n    def __exit__(self, *args: Unused) -> None: ...\n\nclass ForkAwareLocal(threading.local): ...\n\nMAXFD: Final[int]\n\ndef close_all_fds_except(fds: Iterable[int]) -> None: ...\ndef spawnv_passfds(path: bytes, args: Sequence[ConvertibleToInt], passfds: Sequence[int]) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/netrc.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"netrc\", \"NetrcParseError\"]\n\nclass NetrcParseError(Exception):\n    filename: str | None\n    lineno: int | None\n    msg: str\n    def __init__(self, msg: str, filename: StrOrBytesPath | None = None, lineno: int | None = None) -> None: ...\n\n# (login, account, password) tuple\nif sys.version_info >= (3, 11):\n    _NetrcTuple: TypeAlias = tuple[str, str, str]\nelse:\n    _NetrcTuple: TypeAlias = tuple[str, str | None, str | None]\n\nclass netrc:\n    hosts: dict[str, _NetrcTuple]\n    macros: dict[str, list[str]]\n    def __init__(self, file: StrOrBytesPath | None = None) -> None: ...\n    def authenticators(self, host: str) -> _NetrcTuple | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/nis.pyi",
    "content": "import sys\n\nif sys.platform != \"win32\":\n    def cat(map: str, domain: str = ...) -> dict[str, str]: ...\n    def get_default_domain() -> str: ...\n    def maps(domain: str = ...) -> list[str]: ...\n    def match(key: str, map: str, domain: str = ...) -> str: ...\n\n    class error(Exception): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/nntplib.pyi",
    "content": "import datetime\nimport socket\nimport ssl\nfrom _typeshed import Unused\nfrom builtins import list as _list  # conflicts with a method named \"list\"\nfrom collections.abc import Iterable\nfrom typing import IO, Any, Final, NamedTuple\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\n    \"NNTP\",\n    \"NNTPError\",\n    \"NNTPReplyError\",\n    \"NNTPTemporaryError\",\n    \"NNTPPermanentError\",\n    \"NNTPProtocolError\",\n    \"NNTPDataError\",\n    \"decode_header\",\n    \"NNTP_SSL\",\n]\n\n_File: TypeAlias = IO[bytes] | bytes | str | None\n\nclass NNTPError(Exception):\n    response: str\n\nclass NNTPReplyError(NNTPError): ...\nclass NNTPTemporaryError(NNTPError): ...\nclass NNTPPermanentError(NNTPError): ...\nclass NNTPProtocolError(NNTPError): ...\nclass NNTPDataError(NNTPError): ...\n\nNNTP_PORT: Final = 119\nNNTP_SSL_PORT: Final = 563\n\nclass GroupInfo(NamedTuple):\n    group: str\n    last: str\n    first: str\n    flag: str\n\nclass ArticleInfo(NamedTuple):\n    number: int\n    message_id: str\n    lines: list[bytes]\n\ndef decode_header(header_str: str) -> str: ...\n\nclass NNTP:\n    encoding: str\n    errors: str\n\n    host: str\n    port: int\n    sock: socket.socket\n    file: IO[bytes]\n    debugging: int\n    welcome: str\n    readermode_afterauth: bool\n    tls_on: bool\n    authenticated: bool\n    nntp_implementation: str\n    nntp_version: int\n    def __init__(\n        self,\n        host: str,\n        port: int = 119,\n        user: str | None = None,\n        password: str | None = None,\n        readermode: bool | None = None,\n        usenetrc: bool = False,\n        timeout: float = ...,\n    ) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n    def getwelcome(self) -> str: ...\n    def getcapabilities(self) -> dict[str, _list[str]]: ...\n    def set_debuglevel(self, level: int) -> None: ...\n    def debug(self, level: int) -> None: ...\n    def capabilities(self) -> tuple[str, dict[str, _list[str]]]: ...\n    def newgroups(self, date: datetime.date | datetime.datetime, *, file: _File = None) -> tuple[str, _list[str]]: ...\n    def newnews(self, group: str, date: datetime.date | datetime.datetime, *, file: _File = None) -> tuple[str, _list[str]]: ...\n    def list(self, group_pattern: str | None = None, *, file: _File = None) -> tuple[str, _list[str]]: ...\n    def description(self, group: str) -> str: ...\n    def descriptions(self, group_pattern: str) -> tuple[str, dict[str, str]]: ...\n    def group(self, name: str) -> tuple[str, int, int, int, str]: ...\n    def help(self, *, file: _File = None) -> tuple[str, _list[str]]: ...\n    def stat(self, message_spec: Any = None) -> tuple[str, int, str]: ...\n    def next(self) -> tuple[str, int, str]: ...\n    def last(self) -> tuple[str, int, str]: ...\n    def head(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: ...\n    def body(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: ...\n    def article(self, message_spec: Any = None, *, file: _File = None) -> tuple[str, ArticleInfo]: ...\n    def slave(self) -> str: ...\n    def xhdr(self, hdr: str, str: Any, *, file: _File = None) -> tuple[str, _list[str]]: ...\n    def xover(self, start: int, end: int, *, file: _File = None) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ...\n    def over(\n        self, message_spec: None | str | _list[Any] | tuple[Any, ...], *, file: _File = None\n    ) -> tuple[str, _list[tuple[int, dict[str, str]]]]: ...\n    def date(self) -> tuple[str, datetime.datetime]: ...\n    def post(self, data: bytes | Iterable[bytes]) -> str: ...\n    def ihave(self, message_id: Any, data: bytes | Iterable[bytes]) -> str: ...\n    def quit(self) -> str: ...\n    def login(self, user: str | None = None, password: str | None = None, usenetrc: bool = True) -> None: ...\n    def starttls(self, context: ssl.SSLContext | None = None) -> None: ...\n\nclass NNTP_SSL(NNTP):\n    ssl_context: ssl.SSLContext | None\n    sock: ssl.SSLSocket\n    def __init__(\n        self,\n        host: str,\n        port: int = 563,\n        user: str | None = None,\n        password: str | None = None,\n        ssl_context: ssl.SSLContext | None = None,\n        readermode: bool | None = None,\n        usenetrc: bool = False,\n        timeout: float = ...,\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/nt.pyi",
    "content": "import sys\n\nif sys.platform == \"win32\":\n    # Actually defined here and re-exported from os at runtime,\n    # but this leads to less code duplication\n    from os import (\n        F_OK as F_OK,\n        O_APPEND as O_APPEND,\n        O_BINARY as O_BINARY,\n        O_CREAT as O_CREAT,\n        O_EXCL as O_EXCL,\n        O_NOINHERIT as O_NOINHERIT,\n        O_RANDOM as O_RANDOM,\n        O_RDONLY as O_RDONLY,\n        O_RDWR as O_RDWR,\n        O_SEQUENTIAL as O_SEQUENTIAL,\n        O_SHORT_LIVED as O_SHORT_LIVED,\n        O_TEMPORARY as O_TEMPORARY,\n        O_TEXT as O_TEXT,\n        O_TRUNC as O_TRUNC,\n        O_WRONLY as O_WRONLY,\n        P_DETACH as P_DETACH,\n        P_NOWAIT as P_NOWAIT,\n        P_NOWAITO as P_NOWAITO,\n        P_OVERLAY as P_OVERLAY,\n        P_WAIT as P_WAIT,\n        R_OK as R_OK,\n        TMP_MAX as TMP_MAX,\n        W_OK as W_OK,\n        X_OK as X_OK,\n        DirEntry as DirEntry,\n        abort as abort,\n        access as access,\n        chdir as chdir,\n        chmod as chmod,\n        close as close,\n        closerange as closerange,\n        cpu_count as cpu_count,\n        device_encoding as device_encoding,\n        dup as dup,\n        dup2 as dup2,\n        error as error,\n        execv as execv,\n        execve as execve,\n        fspath as fspath,\n        fstat as fstat,\n        fsync as fsync,\n        ftruncate as ftruncate,\n        get_handle_inheritable as get_handle_inheritable,\n        get_inheritable as get_inheritable,\n        get_terminal_size as get_terminal_size,\n        getcwd as getcwd,\n        getcwdb as getcwdb,\n        getlogin as getlogin,\n        getpid as getpid,\n        getppid as getppid,\n        isatty as isatty,\n        kill as kill,\n        link as link,\n        listdir as listdir,\n        lseek as lseek,\n        lstat as lstat,\n        mkdir as mkdir,\n        open as open,\n        pipe as pipe,\n        putenv as putenv,\n        read as read,\n        readlink as readlink,\n        remove as remove,\n        rename as rename,\n        replace as replace,\n        rmdir as rmdir,\n        scandir as scandir,\n        set_handle_inheritable as set_handle_inheritable,\n        set_inheritable as set_inheritable,\n        spawnv as spawnv,\n        spawnve as spawnve,\n        startfile as startfile,\n        stat as stat,\n        stat_result as stat_result,\n        statvfs_result as statvfs_result,\n        strerror as strerror,\n        symlink as symlink,\n        system as system,\n        terminal_size as terminal_size,\n        times as times,\n        times_result as times_result,\n        truncate as truncate,\n        umask as umask,\n        uname_result as uname_result,\n        unlink as unlink,\n        unsetenv as unsetenv,\n        urandom as urandom,\n        utime as utime,\n        waitpid as waitpid,\n        waitstatus_to_exitcode as waitstatus_to_exitcode,\n        write as write,\n    )\n\n    if sys.version_info >= (3, 11):\n        from os import EX_OK as EX_OK\n    if sys.version_info >= (3, 12):\n        from os import (\n            get_blocking as get_blocking,\n            listdrives as listdrives,\n            listmounts as listmounts,\n            listvolumes as listvolumes,\n            set_blocking as set_blocking,\n        )\n    if sys.version_info >= (3, 13):\n        from os import fchmod as fchmod, lchmod as lchmod\n\n    if sys.version_info >= (3, 14):\n        from os import readinto as readinto\n\n    environ: dict[str, str]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ntpath.pyi",
    "content": "import sys\nfrom _typeshed import BytesPath, StrOrBytesPath, StrPath\nfrom genericpath import (\n    ALLOW_MISSING as ALLOW_MISSING,\n    _AllowMissingType,\n    commonprefix as commonprefix,\n    exists as exists,\n    getatime as getatime,\n    getctime as getctime,\n    getmtime as getmtime,\n    getsize as getsize,\n    isdir as isdir,\n    isfile as isfile,\n    samefile as samefile,\n    sameopenfile as sameopenfile,\n    samestat as samestat,\n)\nfrom os import PathLike\n\n# Re-export common definitions from posixpath to reduce duplication\nfrom posixpath import (\n    abspath as abspath,\n    basename as basename,\n    commonpath as commonpath,\n    curdir as curdir,\n    defpath as defpath,\n    devnull as devnull,\n    dirname as dirname,\n    expanduser as expanduser,\n    expandvars as expandvars,\n    extsep as extsep,\n    isabs as isabs,\n    islink as islink,\n    ismount as ismount,\n    lexists as lexists,\n    normcase as normcase,\n    normpath as normpath,\n    pardir as pardir,\n    pathsep as pathsep,\n    relpath as relpath,\n    sep as sep,\n    split as split,\n    splitdrive as splitdrive,\n    splitext as splitext,\n    supports_unicode_filenames as supports_unicode_filenames,\n)\nfrom typing import AnyStr, overload\nfrom typing_extensions import LiteralString\n\nif sys.version_info >= (3, 12):\n    from posixpath import isjunction as isjunction, splitroot as splitroot\nif sys.version_info >= (3, 13):\n    from genericpath import isdevdrive as isdevdrive\n\n__all__ = [\n    \"normcase\",\n    \"isabs\",\n    \"join\",\n    \"splitdrive\",\n    \"split\",\n    \"splitext\",\n    \"basename\",\n    \"dirname\",\n    \"commonprefix\",\n    \"getsize\",\n    \"getmtime\",\n    \"getatime\",\n    \"getctime\",\n    \"islink\",\n    \"exists\",\n    \"lexists\",\n    \"isdir\",\n    \"isfile\",\n    \"ismount\",\n    \"expanduser\",\n    \"expandvars\",\n    \"normpath\",\n    \"abspath\",\n    \"curdir\",\n    \"pardir\",\n    \"sep\",\n    \"pathsep\",\n    \"defpath\",\n    \"altsep\",\n    \"extsep\",\n    \"devnull\",\n    \"realpath\",\n    \"supports_unicode_filenames\",\n    \"relpath\",\n    \"samefile\",\n    \"sameopenfile\",\n    \"samestat\",\n    \"commonpath\",\n    \"ALLOW_MISSING\",\n]\nif sys.version_info >= (3, 12):\n    __all__ += [\"isjunction\", \"splitroot\"]\nif sys.version_info >= (3, 13):\n    __all__ += [\"isdevdrive\", \"isreserved\"]\n\naltsep: LiteralString\n\n# First parameter is not actually pos-only,\n# but must be defined as pos-only in the stub or cross-platform code doesn't type-check,\n# as the parameter name is different in posixpath.join()\n@overload\ndef join(path: LiteralString, /, *paths: LiteralString) -> LiteralString: ...\n@overload\ndef join(path: StrPath, /, *paths: StrPath) -> str: ...\n@overload\ndef join(path: BytesPath, /, *paths: BytesPath) -> bytes: ...\n\nif sys.platform == \"win32\":\n    @overload\n    def realpath(path: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: ...\n    @overload\n    def realpath(path: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ...\n\nelse:\n    realpath = abspath\n\nif sys.version_info >= (3, 13):\n    def isreserved(path: StrOrBytesPath) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/nturl2path.pyi",
    "content": "import sys\nfrom typing_extensions import deprecated\n\nif sys.version_info >= (3, 14):\n    @deprecated(\"The `nturl2path` module is deprecated since Python 3.14.\")\n    def url2pathname(url: str) -> str: ...\n    @deprecated(\"The `nturl2path` module is deprecated since Python 3.14.\")\n    def pathname2url(p: str) -> str: ...\n\nelse:\n    def url2pathname(url: str) -> str: ...\n    def pathname2url(p: str) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/numbers.pyi",
    "content": "# Note: these stubs are incomplete. The more complex type\n# signatures are currently omitted.\n#\n# Use _ComplexLike, _RealLike and _IntegralLike for return types in this module\n# rather than `numbers.Complex`, `numbers.Real` and `numbers.Integral`,\n# to avoid an excessive number of `type: ignore`s in subclasses of these ABCs\n# (since type checkers don't see `complex` as a subtype of `numbers.Complex`,\n# nor `float` as a subtype of `numbers.Real`, etc.)\n\nfrom abc import ABCMeta, abstractmethod\nfrom typing import ClassVar, Literal, Protocol, overload, type_check_only\n\n__all__ = [\"Number\", \"Complex\", \"Real\", \"Rational\", \"Integral\"]\n\n############################\n# Protocols for return types\n############################\n\n# `_ComplexLike` is a structural-typing approximation\n# of the `Complex` ABC, which is not (and cannot be) a protocol\n#\n# NOTE: We can't include `__complex__` here,\n# as we want `int` to be seen as a subtype of `_ComplexLike`,\n# and `int.__complex__` does not exist :(\n@type_check_only\nclass _ComplexLike(Protocol):\n    def __neg__(self) -> _ComplexLike: ...\n    def __pos__(self) -> _ComplexLike: ...\n    def __abs__(self) -> _RealLike: ...\n\n# _RealLike is a structural-typing approximation\n# of the `Real` ABC, which is not (and cannot be) a protocol\n@type_check_only\nclass _RealLike(_ComplexLike, Protocol):\n    def __trunc__(self) -> _IntegralLike: ...\n    def __floor__(self) -> _IntegralLike: ...\n    def __ceil__(self) -> _IntegralLike: ...\n    def __float__(self) -> float: ...\n    # Overridden from `_ComplexLike`\n    # for a more precise return type:\n    def __neg__(self) -> _RealLike: ...\n    def __pos__(self) -> _RealLike: ...\n\n# _IntegralLike is a structural-typing approximation\n# of the `Integral` ABC, which is not (and cannot be) a protocol\n@type_check_only\nclass _IntegralLike(_RealLike, Protocol):\n    def __invert__(self) -> _IntegralLike: ...\n    def __int__(self) -> int: ...\n    def __index__(self) -> int: ...\n    # Overridden from `_ComplexLike`\n    # for a more precise return type:\n    def __abs__(self) -> _IntegralLike: ...\n    # Overridden from `RealLike`\n    # for a more precise return type:\n    def __neg__(self) -> _IntegralLike: ...\n    def __pos__(self) -> _IntegralLike: ...\n\n#################\n# Module \"proper\"\n#################\n\nclass Number(metaclass=ABCMeta):\n    __slots__ = ()\n    @abstractmethod\n    def __hash__(self) -> int: ...\n\n# See comment at the top of the file\n# for why some of these return types are purposefully vague\nclass Complex(Number, _ComplexLike):\n    __slots__ = ()\n    @abstractmethod\n    def __complex__(self) -> complex: ...\n    def __bool__(self) -> bool: ...\n    @property\n    @abstractmethod\n    def real(self) -> _RealLike: ...\n    @property\n    @abstractmethod\n    def imag(self) -> _RealLike: ...\n    @abstractmethod\n    def __add__(self, other) -> _ComplexLike: ...\n    @abstractmethod\n    def __radd__(self, other) -> _ComplexLike: ...\n    @abstractmethod\n    def __neg__(self) -> _ComplexLike: ...\n    @abstractmethod\n    def __pos__(self) -> _ComplexLike: ...\n    def __sub__(self, other) -> _ComplexLike: ...\n    def __rsub__(self, other) -> _ComplexLike: ...\n    @abstractmethod\n    def __mul__(self, other) -> _ComplexLike: ...\n    @abstractmethod\n    def __rmul__(self, other) -> _ComplexLike: ...\n    @abstractmethod\n    def __truediv__(self, other) -> _ComplexLike: ...\n    @abstractmethod\n    def __rtruediv__(self, other) -> _ComplexLike: ...\n    @abstractmethod\n    def __pow__(self, exponent) -> _ComplexLike: ...\n    @abstractmethod\n    def __rpow__(self, base) -> _ComplexLike: ...\n    @abstractmethod\n    def __abs__(self) -> _RealLike: ...\n    @abstractmethod\n    def conjugate(self) -> _ComplexLike: ...\n    @abstractmethod\n    def __eq__(self, other: object) -> bool: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\n# See comment at the top of the file\n# for why some of these return types are purposefully vague\nclass Real(Complex, _RealLike):\n    __slots__ = ()\n    @abstractmethod\n    def __float__(self) -> float: ...\n    @abstractmethod\n    def __trunc__(self) -> _IntegralLike: ...\n    @abstractmethod\n    def __floor__(self) -> _IntegralLike: ...\n    @abstractmethod\n    def __ceil__(self) -> _IntegralLike: ...\n    @abstractmethod\n    @overload\n    def __round__(self, ndigits: None = None) -> _IntegralLike: ...\n    @abstractmethod\n    @overload\n    def __round__(self, ndigits: int) -> _RealLike: ...\n    def __divmod__(self, other) -> tuple[_RealLike, _RealLike]: ...\n    def __rdivmod__(self, other) -> tuple[_RealLike, _RealLike]: ...\n    @abstractmethod\n    def __floordiv__(self, other) -> _RealLike: ...\n    @abstractmethod\n    def __rfloordiv__(self, other) -> _RealLike: ...\n    @abstractmethod\n    def __mod__(self, other) -> _RealLike: ...\n    @abstractmethod\n    def __rmod__(self, other) -> _RealLike: ...\n    @abstractmethod\n    def __lt__(self, other) -> bool: ...\n    @abstractmethod\n    def __le__(self, other) -> bool: ...\n    def __complex__(self) -> complex: ...\n    @property\n    def real(self) -> _RealLike: ...\n    @property\n    def imag(self) -> Literal[0]: ...\n    def conjugate(self) -> _RealLike: ...\n    # Not actually overridden at runtime,\n    # but we override these in the stub to give them more precise return types:\n    @abstractmethod\n    def __pos__(self) -> _RealLike: ...\n    @abstractmethod\n    def __neg__(self) -> _RealLike: ...\n\n# See comment at the top of the file\n# for why some of these return types are purposefully vague\nclass Rational(Real):\n    __slots__ = ()\n    @property\n    @abstractmethod\n    def numerator(self) -> _IntegralLike: ...\n    @property\n    @abstractmethod\n    def denominator(self) -> _IntegralLike: ...\n    def __float__(self) -> float: ...\n\n# See comment at the top of the file\n# for why some of these return types are purposefully vague\nclass Integral(Rational, _IntegralLike):\n    __slots__ = ()\n    @abstractmethod\n    def __int__(self) -> int: ...\n    def __index__(self) -> int: ...\n    @abstractmethod\n    def __pow__(self, exponent, modulus=None) -> _IntegralLike: ...\n    @abstractmethod\n    def __lshift__(self, other) -> _IntegralLike: ...\n    @abstractmethod\n    def __rlshift__(self, other) -> _IntegralLike: ...\n    @abstractmethod\n    def __rshift__(self, other) -> _IntegralLike: ...\n    @abstractmethod\n    def __rrshift__(self, other) -> _IntegralLike: ...\n    @abstractmethod\n    def __and__(self, other) -> _IntegralLike: ...\n    @abstractmethod\n    def __rand__(self, other) -> _IntegralLike: ...\n    @abstractmethod\n    def __xor__(self, other) -> _IntegralLike: ...\n    @abstractmethod\n    def __rxor__(self, other) -> _IntegralLike: ...\n    @abstractmethod\n    def __or__(self, other) -> _IntegralLike: ...\n    @abstractmethod\n    def __ror__(self, other) -> _IntegralLike: ...\n    @abstractmethod\n    def __invert__(self) -> _IntegralLike: ...\n    def __float__(self) -> float: ...\n    @property\n    def numerator(self) -> _IntegralLike: ...\n    @property\n    def denominator(self) -> Literal[1]: ...\n    # Not actually overridden at runtime,\n    # but we override these in the stub to give them more precise return types:\n    @abstractmethod\n    def __pos__(self) -> _IntegralLike: ...\n    @abstractmethod\n    def __neg__(self) -> _IntegralLike: ...\n    @abstractmethod\n    def __abs__(self) -> _IntegralLike: ...\n    @abstractmethod\n    @overload\n    def __round__(self, ndigits: None = None) -> _IntegralLike: ...\n    @abstractmethod\n    @overload\n    def __round__(self, ndigits: int) -> _IntegralLike: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/opcode.pyi",
    "content": "import sys\nfrom typing import Final, Literal\n\n__all__ = [\n    \"cmp_op\",\n    \"hasconst\",\n    \"hasname\",\n    \"hasjrel\",\n    \"hasjabs\",\n    \"haslocal\",\n    \"hascompare\",\n    \"hasfree\",\n    \"opname\",\n    \"opmap\",\n    \"HAVE_ARGUMENT\",\n    \"EXTENDED_ARG\",\n    \"stack_effect\",\n]\nif sys.version_info >= (3, 12):\n    __all__ += [\"hasarg\", \"hasexc\"]\nelse:\n    __all__ += [\"hasnargs\"]\nif sys.version_info >= (3, 13):\n    __all__ += [\"hasjump\"]\n\ncmp_op: tuple[Literal[\"<\"], Literal[\"<=\"], Literal[\"==\"], Literal[\"!=\"], Literal[\">\"], Literal[\">=\"]]\nhasconst: Final[list[int]]\nhasname: Final[list[int]]\nhasjrel: Final[list[int]]\nhasjabs: Final[list[int]]\nhaslocal: Final[list[int]]\nhascompare: Final[list[int]]\nhasfree: Final[list[int]]\nif sys.version_info >= (3, 12):\n    hasarg: Final[list[int]]\n    hasexc: Final[list[int]]\nelse:\n    hasnargs: Final[list[int]]\nif sys.version_info >= (3, 13):\n    hasjump: Final[list[int]]\nopname: Final[list[str]]\n\nopmap: Final[dict[str, int]]\nHAVE_ARGUMENT: Final[int]\nEXTENDED_ARG: Final[int]\n\ndef stack_effect(opcode: int, oparg: int | None = None, /, *, jump: bool | None = None) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/operator.pyi",
    "content": "import sys\nfrom _operator import (\n    abs as abs,\n    add as add,\n    and_ as and_,\n    concat as concat,\n    contains as contains,\n    countOf as countOf,\n    delitem as delitem,\n    eq as eq,\n    floordiv as floordiv,\n    ge as ge,\n    getitem as getitem,\n    gt as gt,\n    iadd as iadd,\n    iand as iand,\n    iconcat as iconcat,\n    ifloordiv as ifloordiv,\n    ilshift as ilshift,\n    imatmul as imatmul,\n    imod as imod,\n    imul as imul,\n    index as index,\n    indexOf as indexOf,\n    inv as inv,\n    invert as invert,\n    ior as ior,\n    ipow as ipow,\n    irshift as irshift,\n    is_ as is_,\n    is_not as is_not,\n    isub as isub,\n    itruediv as itruediv,\n    ixor as ixor,\n    le as le,\n    length_hint as length_hint,\n    lshift as lshift,\n    lt as lt,\n    matmul as matmul,\n    mod as mod,\n    mul as mul,\n    ne as ne,\n    neg as neg,\n    not_ as not_,\n    or_ as or_,\n    pos as pos,\n    pow as pow,\n    rshift as rshift,\n    setitem as setitem,\n    sub as sub,\n    truediv as truediv,\n    truth as truth,\n    xor as xor,\n)\nfrom _typeshed import SupportsGetItem\nfrom typing import Any, Generic, TypeVar, final, overload\nfrom typing_extensions import Self, TypeVarTuple, Unpack\n\n_T = TypeVar(\"_T\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n_Ts = TypeVarTuple(\"_Ts\")\n\n__all__ = [\n    \"abs\",\n    \"add\",\n    \"and_\",\n    \"attrgetter\",\n    \"concat\",\n    \"contains\",\n    \"countOf\",\n    \"delitem\",\n    \"eq\",\n    \"floordiv\",\n    \"ge\",\n    \"getitem\",\n    \"gt\",\n    \"iadd\",\n    \"iand\",\n    \"iconcat\",\n    \"ifloordiv\",\n    \"ilshift\",\n    \"imatmul\",\n    \"imod\",\n    \"imul\",\n    \"index\",\n    \"indexOf\",\n    \"inv\",\n    \"invert\",\n    \"ior\",\n    \"ipow\",\n    \"irshift\",\n    \"is_\",\n    \"is_not\",\n    \"isub\",\n    \"itemgetter\",\n    \"itruediv\",\n    \"ixor\",\n    \"le\",\n    \"length_hint\",\n    \"lshift\",\n    \"lt\",\n    \"matmul\",\n    \"methodcaller\",\n    \"mod\",\n    \"mul\",\n    \"ne\",\n    \"neg\",\n    \"not_\",\n    \"or_\",\n    \"pos\",\n    \"pow\",\n    \"rshift\",\n    \"setitem\",\n    \"sub\",\n    \"truediv\",\n    \"truth\",\n    \"xor\",\n]\n\nif sys.version_info >= (3, 11):\n    from _operator import call as call\n\n    __all__ += [\"call\"]\n\nif sys.version_info >= (3, 14):\n    from _operator import is_none as is_none, is_not_none as is_not_none\n\n    __all__ += [\"is_none\", \"is_not_none\"]\n\n__lt__ = lt\n__le__ = le\n__eq__ = eq\n__ne__ = ne\n__ge__ = ge\n__gt__ = gt\n__not__ = not_\n__abs__ = abs\n__add__ = add\n__and__ = and_\n__floordiv__ = floordiv\n__index__ = index\n__inv__ = inv\n__invert__ = invert\n__lshift__ = lshift\n__mod__ = mod\n__mul__ = mul\n__matmul__ = matmul\n__neg__ = neg\n__or__ = or_\n__pos__ = pos\n__pow__ = pow\n__rshift__ = rshift\n__sub__ = sub\n__truediv__ = truediv\n__xor__ = xor\n__concat__ = concat\n__contains__ = contains\n__delitem__ = delitem\n__getitem__ = getitem\n__setitem__ = setitem\n__iadd__ = iadd\n__iand__ = iand\n__iconcat__ = iconcat\n__ifloordiv__ = ifloordiv\n__ilshift__ = ilshift\n__imod__ = imod\n__imul__ = imul\n__imatmul__ = imatmul\n__ior__ = ior\n__ipow__ = ipow\n__irshift__ = irshift\n__isub__ = isub\n__itruediv__ = itruediv\n__ixor__ = ixor\nif sys.version_info >= (3, 11):\n    __call__ = call\n\n# At runtime, these classes are implemented in C as part of the _operator module\n# However, they consider themselves to live in the operator module, so we'll put\n# them here.\n@final\nclass attrgetter(Generic[_T_co]):\n    @overload\n    def __new__(cls, attr: str, /) -> attrgetter[Any]: ...\n    @overload\n    def __new__(cls, attr: str, attr2: str, /) -> attrgetter[tuple[Any, Any]]: ...\n    @overload\n    def __new__(cls, attr: str, attr2: str, attr3: str, /) -> attrgetter[tuple[Any, Any, Any]]: ...\n    @overload\n    def __new__(cls, attr: str, attr2: str, attr3: str, attr4: str, /) -> attrgetter[tuple[Any, Any, Any, Any]]: ...\n    @overload\n    def __new__(cls, attr: str, /, *attrs: str) -> attrgetter[tuple[Any, ...]]: ...\n    def __call__(self, obj: Any, /) -> _T_co: ...\n\n@final\nclass itemgetter(Generic[_T_co]):\n    @overload\n    def __new__(cls, item: _T, /) -> itemgetter[_T]: ...\n    @overload\n    def __new__(cls, item1: _T1, item2: _T2, /, *items: Unpack[_Ts]) -> itemgetter[tuple[_T1, _T2, Unpack[_Ts]]]: ...\n    # __key: _KT_contra in SupportsGetItem seems to be causing variance issues, ie:\n    # TypeVar \"_KT_contra@SupportsGetItem\" is contravariant\n    #   \"tuple[int, int]\" is incompatible with protocol \"SupportsIndex\"\n    # preventing [_T_co, ...] instead of [Any, ...]\n    #\n    # If we can't infer a literal key from __new__ (ie: `itemgetter[Literal[0]]` for `itemgetter(0)`),\n    # then we can't annotate __call__'s return type or it'll break on tuples\n    #\n    # These issues are best demonstrated by the `itertools.check_itertools_recipes.unique_justseen` test.\n    def __call__(self, obj: SupportsGetItem[Any, Any]) -> Any: ...\n\n@final\nclass methodcaller:\n    def __new__(cls, name: str, /, *args: Any, **kwargs: Any) -> Self: ...\n    def __call__(self, obj: Any) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/optparse.pyi",
    "content": "import builtins\nfrom _typeshed import MaybeNone, SupportsWrite\nfrom abc import abstractmethod\nfrom collections.abc import Callable, Iterable, Mapping, Sequence\nfrom typing import Any, ClassVar, Final, Literal, NoReturn, overload\nfrom typing_extensions import Self\n\n__all__ = [\n    \"Option\",\n    \"make_option\",\n    \"SUPPRESS_HELP\",\n    \"SUPPRESS_USAGE\",\n    \"Values\",\n    \"OptionContainer\",\n    \"OptionGroup\",\n    \"OptionParser\",\n    \"HelpFormatter\",\n    \"IndentedHelpFormatter\",\n    \"TitledHelpFormatter\",\n    \"OptParseError\",\n    \"OptionError\",\n    \"OptionConflictError\",\n    \"OptionValueError\",\n    \"BadOptionError\",\n    \"check_choice\",\n]\nNO_DEFAULT: Final = (\"NO\", \"DEFAULT\")\nSUPPRESS_HELP: Final = \"SUPPRESSHELP\"\nSUPPRESS_USAGE: Final = \"SUPPRESSUSAGE\"\n\n# Can return complex, float, or int depending on the option's type\ndef check_builtin(option: Option, opt: str, value: str) -> complex: ...\ndef check_choice(option: Option, opt: str, value: str) -> str: ...\n\nclass OptParseError(Exception):\n    msg: str\n    def __init__(self, msg: str) -> None: ...\n\nclass BadOptionError(OptParseError):\n    opt_str: str\n    def __init__(self, opt_str: str) -> None: ...\n\nclass AmbiguousOptionError(BadOptionError):\n    possibilities: Iterable[str]\n    def __init__(self, opt_str: str, possibilities: Sequence[str]) -> None: ...\n\nclass OptionError(OptParseError):\n    option_id: str\n    def __init__(self, msg: str, option: Option) -> None: ...\n\nclass OptionConflictError(OptionError): ...\nclass OptionValueError(OptParseError): ...\n\nclass HelpFormatter:\n    NO_DEFAULT_VALUE: str\n    _long_opt_fmt: str\n    _short_opt_fmt: str\n    current_indent: int\n    default_tag: str\n    help_position: int\n    help_width: int | MaybeNone  # initialized as None and computed later as int when storing option strings\n    indent_increment: int\n    level: int\n    max_help_position: int\n    option_strings: dict[Option, str]\n    parser: OptionParser\n    short_first: bool | Literal[0, 1]\n    width: int\n    def __init__(\n        self, indent_increment: int, max_help_position: int, width: int | None, short_first: bool | Literal[0, 1]\n    ) -> None: ...\n    def dedent(self) -> None: ...\n    def expand_default(self, option: Option) -> str: ...\n    def format_description(self, description: str | None) -> str: ...\n    def format_epilog(self, epilog: str | None) -> str: ...\n    @abstractmethod\n    def format_heading(self, heading: str) -> str: ...\n    def format_option(self, option: Option) -> str: ...\n    def format_option_strings(self, option: Option) -> str: ...\n    @abstractmethod\n    def format_usage(self, usage: str) -> str: ...\n    def indent(self) -> None: ...\n    def set_long_opt_delimiter(self, delim: str) -> None: ...\n    def set_parser(self, parser: OptionParser) -> None: ...\n    def set_short_opt_delimiter(self, delim: str) -> None: ...\n    def store_option_strings(self, parser: OptionParser) -> None: ...\n\nclass IndentedHelpFormatter(HelpFormatter):\n    def __init__(\n        self,\n        indent_increment: int = 2,\n        max_help_position: int = 24,\n        width: int | None = None,\n        short_first: bool | Literal[0, 1] = 1,\n    ) -> None: ...\n    def format_heading(self, heading: str) -> str: ...\n    def format_usage(self, usage: str) -> str: ...\n\nclass TitledHelpFormatter(HelpFormatter):\n    def __init__(\n        self,\n        indent_increment: int = 0,\n        max_help_position: int = 24,\n        width: int | None = None,\n        short_first: bool | Literal[0, 1] = 0,\n    ) -> None: ...\n    def format_heading(self, heading: str) -> str: ...\n    def format_usage(self, usage: str) -> str: ...\n\nclass Option:\n    ACTIONS: tuple[str, ...]\n    ALWAYS_TYPED_ACTIONS: tuple[str, ...]\n    ATTRS: list[str]\n    CHECK_METHODS: list[Callable[[Self], object]] | None\n    CONST_ACTIONS: tuple[str, ...]\n    STORE_ACTIONS: tuple[str, ...]\n    TYPED_ACTIONS: tuple[str, ...]\n    TYPES: tuple[str, ...]\n    TYPE_CHECKER: dict[str, Callable[[Option, str, str], object]]\n    _long_opts: list[str]\n    _short_opts: list[str]\n    action: str\n    type: str | None\n    dest: str | None\n    default: Any  # default can be \"any\" type\n    nargs: int\n    const: Any | None  # const can be \"any\" type\n    choices: list[str] | tuple[str, ...] | None\n    # Callback args and kwargs cannot be expressed in Python's type system.\n    # Revisit if ParamSpec is ever changed to work with packed args/kwargs.\n    callback: Callable[..., object] | None\n    callback_args: tuple[Any, ...] | None\n    callback_kwargs: dict[str, Any] | None\n    help: str | None\n    metavar: str | None\n    def __init__(\n        self,\n        *opts: str | None,\n        # The following keywords are handled by the _set_attrs method. All default to\n        # `None` except for `default`, which defaults to `NO_DEFAULT`.\n        action: str | None = None,\n        type: str | builtins.type | None = None,\n        dest: str | None = None,\n        default: Any = ...,  # = NO_DEFAULT\n        nargs: int | None = None,\n        const: Any | None = None,\n        choices: list[str] | tuple[str, ...] | None = None,\n        callback: Callable[..., object] | None = None,\n        callback_args: tuple[Any, ...] | None = None,\n        callback_kwargs: dict[str, Any] | None = None,\n        help: str | None = None,\n        metavar: str | None = None,\n    ) -> None: ...\n    def _check_action(self) -> None: ...\n    def _check_callback(self) -> None: ...\n    def _check_choice(self) -> None: ...\n    def _check_const(self) -> None: ...\n    def _check_dest(self) -> None: ...\n    def _check_nargs(self) -> None: ...\n    def _check_opt_strings(self, opts: Iterable[str | None]) -> list[str]: ...\n    def _check_type(self) -> None: ...\n    def _set_attrs(self, attrs: dict[str, Any]) -> None: ...  # accepted attrs depend on the ATTRS attribute\n    def _set_opt_strings(self, opts: Iterable[str]) -> None: ...\n    def check_value(self, opt: str, value: str) -> Any: ...  # return type cannot be known statically\n    def convert_value(self, opt: str, value: str | tuple[str, ...] | None) -> Any: ...  # return type cannot be known statically\n    def get_opt_string(self) -> str: ...\n    def process(self, opt: str, value: str | tuple[str, ...] | None, values: Values, parser: OptionParser) -> int: ...\n    # value of take_action can be \"any\" type\n    def take_action(self, action: str, dest: str, opt: str, value: Any, values: Values, parser: OptionParser) -> int: ...\n    def takes_value(self) -> bool: ...\n\nmake_option = Option\n\nclass OptionContainer:\n    _long_opt: dict[str, Option]\n    _short_opt: dict[str, Option]\n    conflict_handler: str\n    defaults: dict[str, Any]  # default values can be \"any\" type\n    description: str | None\n    option_class: type[Option]\n    def __init__(\n        self, option_class: type[Option], conflict_handler: Literal[\"error\", \"resolve\"], description: str | None\n    ) -> None: ...\n    def _check_conflict(self, option: Option) -> None: ...\n    def _create_option_mappings(self) -> None: ...\n    def _share_option_mappings(self, parser: OptionParser) -> None: ...\n    @overload\n    def add_option(self, opt: Option, /) -> Option: ...\n    @overload\n    def add_option(\n        self,\n        opt_str: str,\n        /,\n        *opts: str | None,\n        action: str | None = None,\n        type: str | builtins.type | None = None,\n        dest: str | None = None,\n        default: Any = ...,  # = NO_DEFAULT\n        nargs: int | None = None,\n        const: Any | None = None,\n        choices: list[str] | tuple[str, ...] | None = None,\n        callback: Callable[..., object] | None = None,\n        callback_args: tuple[Any, ...] | None = None,\n        callback_kwargs: dict[str, Any] | None = None,\n        help: str | None = None,\n        metavar: str | None = None,\n        **kwargs: Any,  # Allow arbitrary keyword arguments for user defined option_class\n    ) -> Option: ...\n    def add_options(self, option_list: Iterable[Option]) -> None: ...\n    def destroy(self) -> None: ...\n    def format_option_help(self, formatter: HelpFormatter) -> str: ...\n    def format_description(self, formatter: HelpFormatter) -> str: ...\n    def format_help(self, formatter: HelpFormatter) -> str: ...\n    def get_description(self) -> str | None: ...\n    def get_option(self, opt_str: str) -> Option | None: ...\n    def has_option(self, opt_str: str) -> bool: ...\n    def remove_option(self, opt_str: str) -> None: ...\n    def set_conflict_handler(self, handler: Literal[\"error\", \"resolve\"]) -> None: ...\n    def set_description(self, description: str | None) -> None: ...\n\nclass OptionGroup(OptionContainer):\n    option_list: list[Option]\n    parser: OptionParser\n    title: str\n    def __init__(self, parser: OptionParser, title: str, description: str | None = None) -> None: ...\n    def _create_option_list(self) -> None: ...\n    def set_title(self, title: str) -> None: ...\n\nclass Values:\n    def __init__(self, defaults: Mapping[str, object] | None = None) -> None: ...\n    def _update(self, dict: Mapping[str, object], mode: Literal[\"careful\", \"loose\"]) -> None: ...\n    def _update_careful(self, dict: Mapping[str, object]) -> None: ...\n    def _update_loose(self, dict: Mapping[str, object]) -> None: ...\n    def ensure_value(self, attr: str, value: object) -> Any: ...  # return type cannot be known statically\n    def read_file(self, filename: str, mode: Literal[\"careful\", \"loose\"] = \"careful\") -> None: ...\n    def read_module(self, modname: str, mode: Literal[\"careful\", \"loose\"] = \"careful\") -> None: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    # __getattr__ doesn't exist, but anything passed as a default to __init__\n    # is set on the instance.\n    def __getattr__(self, name: str) -> Any: ...\n    # TODO: mypy infers -> object for __getattr__ if __setattr__ has `value: object`\n    def __setattr__(self, name: str, value: Any, /) -> None: ...\n    def __eq__(self, other: object) -> bool: ...\n\nclass OptionParser(OptionContainer):\n    allow_interspersed_args: bool\n    epilog: str | None\n    formatter: HelpFormatter\n    largs: list[str] | None\n    option_groups: list[OptionGroup]\n    option_list: list[Option]\n    process_default_values: bool\n    prog: str | None\n    rargs: list[str] | None\n    standard_option_list: list[Option]\n    usage: str | None\n    values: Values | None\n    version: str\n    def __init__(\n        self,\n        usage: str | None = None,\n        option_list: Iterable[Option] | None = None,\n        option_class: type[Option] = ...,\n        version: str | None = None,\n        conflict_handler: str = \"error\",\n        description: str | None = None,\n        formatter: HelpFormatter | None = None,\n        add_help_option: bool = True,\n        prog: str | None = None,\n        epilog: str | None = None,\n    ) -> None: ...\n    def _add_help_option(self) -> None: ...\n    def _add_version_option(self) -> None: ...\n    def _create_option_list(self) -> None: ...\n    def _get_all_options(self) -> list[Option]: ...\n    def _get_args(self, args: list[str] | None) -> list[str]: ...\n    def _init_parsing_state(self) -> None: ...\n    def _match_long_opt(self, opt: str) -> str: ...\n    def _populate_option_list(self, option_list: Iterable[Option] | None, add_help: bool = True) -> None: ...\n    def _process_args(self, largs: list[str], rargs: list[str], values: Values) -> None: ...\n    def _process_long_opt(self, rargs: list[str], values: Values) -> None: ...\n    def _process_short_opts(self, rargs: list[str], values: Values) -> None: ...\n    @overload\n    def add_option_group(self, opt_group: OptionGroup, /) -> OptionGroup: ...\n    @overload\n    def add_option_group(self, title: str, /, description: str | None = None) -> OptionGroup: ...\n    def check_values(self, values: Values, args: list[str]) -> tuple[Values, list[str]]: ...\n    def disable_interspersed_args(self) -> None: ...\n    def enable_interspersed_args(self) -> None: ...\n    def error(self, msg: str) -> NoReturn: ...\n    def exit(self, status: int = 0, msg: str | None = None) -> NoReturn: ...\n    def expand_prog_name(self, s: str) -> str: ...\n    def format_epilog(self, formatter: HelpFormatter) -> str: ...\n    def format_help(self, formatter: HelpFormatter | None = None) -> str: ...\n    def format_option_help(self, formatter: HelpFormatter | None = None) -> str: ...\n    def get_default_values(self) -> Values: ...\n    def get_option_group(self, opt_str: str) -> OptionGroup | None: ...\n    def get_prog_name(self) -> str: ...\n    def get_usage(self) -> str: ...\n    def get_version(self) -> str: ...\n    def parse_args(self, args: list[str] | None = None, values: Values | None = None) -> tuple[Values, list[str]]: ...\n    def print_usage(self, file: SupportsWrite[str] | None = None) -> None: ...\n    def print_help(self, file: SupportsWrite[str] | None = None) -> None: ...\n    def print_version(self, file: SupportsWrite[str] | None = None) -> None: ...\n    def set_default(self, dest: str, value: Any) -> None: ...  # default value can be \"any\" type\n    def set_defaults(self, **kwargs: Any) -> None: ...  # default values can be \"any\" type\n    def set_process_default_values(self, process: bool) -> None: ...\n    def set_usage(self, usage: str | None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/os/__init__.pyi",
    "content": "import sys\nfrom _typeshed import (\n    AnyStr_co,\n    BytesPath,\n    FileDescriptor,\n    FileDescriptorLike,\n    FileDescriptorOrPath,\n    GenericPath,\n    OpenBinaryMode,\n    OpenBinaryModeReading,\n    OpenBinaryModeUpdating,\n    OpenBinaryModeWriting,\n    OpenTextMode,\n    ReadableBuffer,\n    StrOrBytesPath,\n    StrPath,\n    SupportsLenAndGetItem,\n    Unused,\n    WriteableBuffer,\n    structseq,\n)\nfrom abc import ABC, abstractmethod\nfrom builtins import OSError\nfrom collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping, Sequence\nfrom io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper\nfrom subprocess import Popen\nfrom types import GenericAlias, TracebackType\nfrom typing import (\n    IO,\n    Any,\n    AnyStr,\n    BinaryIO,\n    Final,\n    Generic,\n    Literal,\n    NoReturn,\n    Protocol,\n    TypeVar,\n    final,\n    overload,\n    runtime_checkable,\n    type_check_only,\n)\nfrom typing_extensions import LiteralString, Self, TypeAlias, Unpack, deprecated\n\nfrom . import path as _path\n\n# Re-export common definitions from os.path to reduce duplication\nfrom .path import (\n    altsep as altsep,\n    curdir as curdir,\n    defpath as defpath,\n    devnull as devnull,\n    extsep as extsep,\n    pardir as pardir,\n    pathsep as pathsep,\n    sep as sep,\n)\n\n__all__ = [\n    \"F_OK\",\n    \"O_APPEND\",\n    \"O_CREAT\",\n    \"O_EXCL\",\n    \"O_RDONLY\",\n    \"O_RDWR\",\n    \"O_TRUNC\",\n    \"O_WRONLY\",\n    \"P_NOWAIT\",\n    \"P_NOWAITO\",\n    \"P_WAIT\",\n    \"R_OK\",\n    \"SEEK_CUR\",\n    \"SEEK_END\",\n    \"SEEK_SET\",\n    \"TMP_MAX\",\n    \"W_OK\",\n    \"X_OK\",\n    \"DirEntry\",\n    \"_exit\",\n    \"abort\",\n    \"access\",\n    \"altsep\",\n    \"chdir\",\n    \"chmod\",\n    \"close\",\n    \"closerange\",\n    \"cpu_count\",\n    \"curdir\",\n    \"defpath\",\n    \"device_encoding\",\n    \"devnull\",\n    \"dup\",\n    \"dup2\",\n    \"environ\",\n    \"error\",\n    \"execl\",\n    \"execle\",\n    \"execlp\",\n    \"execlpe\",\n    \"execv\",\n    \"execve\",\n    \"execvp\",\n    \"execvpe\",\n    \"extsep\",\n    \"fdopen\",\n    \"fsdecode\",\n    \"fsencode\",\n    \"fspath\",\n    \"fstat\",\n    \"fsync\",\n    \"ftruncate\",\n    \"get_exec_path\",\n    \"get_inheritable\",\n    \"get_terminal_size\",\n    \"getcwd\",\n    \"getcwdb\",\n    \"getenv\",\n    \"getlogin\",\n    \"getpid\",\n    \"getppid\",\n    \"isatty\",\n    \"kill\",\n    \"linesep\",\n    \"link\",\n    \"listdir\",\n    \"lseek\",\n    \"lstat\",\n    \"makedirs\",\n    \"mkdir\",\n    \"name\",\n    \"open\",\n    \"pardir\",\n    \"path\",\n    \"pathsep\",\n    \"pipe\",\n    \"popen\",\n    \"putenv\",\n    \"read\",\n    \"readlink\",\n    \"remove\",\n    \"removedirs\",\n    \"rename\",\n    \"renames\",\n    \"replace\",\n    \"rmdir\",\n    \"scandir\",\n    \"sep\",\n    \"set_inheritable\",\n    \"spawnl\",\n    \"spawnle\",\n    \"spawnv\",\n    \"spawnve\",\n    \"stat\",\n    \"stat_result\",\n    \"statvfs_result\",\n    \"strerror\",\n    \"supports_bytes_environ\",\n    \"symlink\",\n    \"system\",\n    \"terminal_size\",\n    \"times\",\n    \"times_result\",\n    \"truncate\",\n    \"umask\",\n    \"uname_result\",\n    \"unlink\",\n    \"unsetenv\",\n    \"urandom\",\n    \"utime\",\n    \"waitpid\",\n    \"waitstatus_to_exitcode\",\n    \"walk\",\n    \"write\",\n]\nif sys.version_info >= (3, 14):\n    # reload_environ was added to __all__ in Python 3.14.1\n    __all__ += [\"readinto\", \"reload_environ\"]\nif sys.platform == \"darwin\" and sys.version_info >= (3, 12):\n    __all__ += [\"PRIO_DARWIN_BG\", \"PRIO_DARWIN_NONUI\", \"PRIO_DARWIN_PROCESS\", \"PRIO_DARWIN_THREAD\"]\nif sys.platform == \"darwin\" and sys.version_info >= (3, 10):\n    __all__ += [\"O_EVTONLY\", \"O_NOFOLLOW_ANY\", \"O_SYMLINK\"]\nif sys.platform == \"linux\":\n    __all__ += [\n        \"GRND_NONBLOCK\",\n        \"GRND_RANDOM\",\n        \"MFD_ALLOW_SEALING\",\n        \"MFD_CLOEXEC\",\n        \"MFD_HUGETLB\",\n        \"MFD_HUGE_16GB\",\n        \"MFD_HUGE_16MB\",\n        \"MFD_HUGE_1GB\",\n        \"MFD_HUGE_1MB\",\n        \"MFD_HUGE_256MB\",\n        \"MFD_HUGE_2GB\",\n        \"MFD_HUGE_2MB\",\n        \"MFD_HUGE_32MB\",\n        \"MFD_HUGE_512KB\",\n        \"MFD_HUGE_512MB\",\n        \"MFD_HUGE_64KB\",\n        \"MFD_HUGE_8MB\",\n        \"MFD_HUGE_MASK\",\n        \"MFD_HUGE_SHIFT\",\n        \"O_DIRECT\",\n        \"O_LARGEFILE\",\n        \"O_NOATIME\",\n        \"O_PATH\",\n        \"O_RSYNC\",\n        \"O_TMPFILE\",\n        \"P_PIDFD\",\n        \"RTLD_DEEPBIND\",\n        \"SCHED_BATCH\",\n        \"SCHED_IDLE\",\n        \"SCHED_RESET_ON_FORK\",\n        \"XATTR_CREATE\",\n        \"XATTR_REPLACE\",\n        \"XATTR_SIZE_MAX\",\n        \"copy_file_range\",\n        \"getrandom\",\n        \"getxattr\",\n        \"listxattr\",\n        \"memfd_create\",\n        \"pidfd_open\",\n        \"removexattr\",\n        \"setxattr\",\n    ]\nif sys.platform == \"linux\" and sys.version_info >= (3, 14):\n    __all__ += [\"SCHED_DEADLINE\", \"SCHED_NORMAL\"]\nif sys.platform == \"linux\" and sys.version_info >= (3, 13):\n    __all__ += [\n        \"POSIX_SPAWN_CLOSEFROM\",\n        \"TFD_CLOEXEC\",\n        \"TFD_NONBLOCK\",\n        \"TFD_TIMER_ABSTIME\",\n        \"TFD_TIMER_CANCEL_ON_SET\",\n        \"timerfd_create\",\n        \"timerfd_gettime\",\n        \"timerfd_gettime_ns\",\n        \"timerfd_settime\",\n        \"timerfd_settime_ns\",\n    ]\nif sys.platform == \"linux\" and sys.version_info >= (3, 12):\n    __all__ += [\n        \"CLONE_FILES\",\n        \"CLONE_FS\",\n        \"CLONE_NEWCGROUP\",\n        \"CLONE_NEWIPC\",\n        \"CLONE_NEWNET\",\n        \"CLONE_NEWNS\",\n        \"CLONE_NEWPID\",\n        \"CLONE_NEWTIME\",\n        \"CLONE_NEWUSER\",\n        \"CLONE_NEWUTS\",\n        \"CLONE_SIGHAND\",\n        \"CLONE_SYSVSEM\",\n        \"CLONE_THREAD\",\n        \"CLONE_VM\",\n        \"setns\",\n        \"unshare\",\n        \"PIDFD_NONBLOCK\",\n    ]\nif sys.platform == \"linux\" and sys.version_info >= (3, 10):\n    __all__ += [\n        \"EFD_CLOEXEC\",\n        \"EFD_NONBLOCK\",\n        \"EFD_SEMAPHORE\",\n        \"RWF_APPEND\",\n        \"SPLICE_F_MORE\",\n        \"SPLICE_F_MOVE\",\n        \"SPLICE_F_NONBLOCK\",\n        \"eventfd\",\n        \"eventfd_read\",\n        \"eventfd_write\",\n        \"splice\",\n    ]\nif sys.platform == \"win32\":\n    __all__ += [\n        \"O_BINARY\",\n        \"O_NOINHERIT\",\n        \"O_RANDOM\",\n        \"O_SEQUENTIAL\",\n        \"O_SHORT_LIVED\",\n        \"O_TEMPORARY\",\n        \"O_TEXT\",\n        \"P_DETACH\",\n        \"P_OVERLAY\",\n        \"get_handle_inheritable\",\n        \"set_handle_inheritable\",\n        \"startfile\",\n    ]\nif sys.platform == \"win32\" and sys.version_info >= (3, 12):\n    __all__ += [\"listdrives\", \"listmounts\", \"listvolumes\"]\nif sys.platform != \"win32\":\n    __all__ += [\n        \"CLD_CONTINUED\",\n        \"CLD_DUMPED\",\n        \"CLD_EXITED\",\n        \"CLD_KILLED\",\n        \"CLD_STOPPED\",\n        \"CLD_TRAPPED\",\n        \"EX_CANTCREAT\",\n        \"EX_CONFIG\",\n        \"EX_DATAERR\",\n        \"EX_IOERR\",\n        \"EX_NOHOST\",\n        \"EX_NOINPUT\",\n        \"EX_NOPERM\",\n        \"EX_NOUSER\",\n        \"EX_OSERR\",\n        \"EX_OSFILE\",\n        \"EX_PROTOCOL\",\n        \"EX_SOFTWARE\",\n        \"EX_TEMPFAIL\",\n        \"EX_UNAVAILABLE\",\n        \"EX_USAGE\",\n        \"F_LOCK\",\n        \"F_TEST\",\n        \"F_TLOCK\",\n        \"F_ULOCK\",\n        \"NGROUPS_MAX\",\n        \"O_ACCMODE\",\n        \"O_ASYNC\",\n        \"O_CLOEXEC\",\n        \"O_DIRECTORY\",\n        \"O_DSYNC\",\n        \"O_NDELAY\",\n        \"O_NOCTTY\",\n        \"O_NOFOLLOW\",\n        \"O_NONBLOCK\",\n        \"O_SYNC\",\n        \"POSIX_SPAWN_CLOSE\",\n        \"POSIX_SPAWN_DUP2\",\n        \"POSIX_SPAWN_OPEN\",\n        \"PRIO_PGRP\",\n        \"PRIO_PROCESS\",\n        \"PRIO_USER\",\n        \"P_ALL\",\n        \"P_PGID\",\n        \"P_PID\",\n        \"RTLD_GLOBAL\",\n        \"RTLD_LAZY\",\n        \"RTLD_LOCAL\",\n        \"RTLD_NODELETE\",\n        \"RTLD_NOLOAD\",\n        \"RTLD_NOW\",\n        \"SCHED_FIFO\",\n        \"SCHED_OTHER\",\n        \"SCHED_RR\",\n        \"SEEK_DATA\",\n        \"SEEK_HOLE\",\n        \"ST_NOSUID\",\n        \"ST_RDONLY\",\n        \"WCONTINUED\",\n        \"WCOREDUMP\",\n        \"WEXITED\",\n        \"WEXITSTATUS\",\n        \"WIFCONTINUED\",\n        \"WIFEXITED\",\n        \"WIFSIGNALED\",\n        \"WIFSTOPPED\",\n        \"WNOHANG\",\n        \"WNOWAIT\",\n        \"WSTOPPED\",\n        \"WSTOPSIG\",\n        \"WTERMSIG\",\n        \"WUNTRACED\",\n        \"chown\",\n        \"chroot\",\n        \"confstr\",\n        \"confstr_names\",\n        \"ctermid\",\n        \"environb\",\n        \"fchdir\",\n        \"fchown\",\n        \"fork\",\n        \"forkpty\",\n        \"fpathconf\",\n        \"fstatvfs\",\n        \"fwalk\",\n        \"getegid\",\n        \"getenvb\",\n        \"geteuid\",\n        \"getgid\",\n        \"getgrouplist\",\n        \"getgroups\",\n        \"getloadavg\",\n        \"getpgid\",\n        \"getpgrp\",\n        \"getpriority\",\n        \"getsid\",\n        \"getuid\",\n        \"initgroups\",\n        \"killpg\",\n        \"lchown\",\n        \"lockf\",\n        \"major\",\n        \"makedev\",\n        \"minor\",\n        \"mkfifo\",\n        \"mknod\",\n        \"nice\",\n        \"openpty\",\n        \"pathconf\",\n        \"pathconf_names\",\n        \"posix_spawn\",\n        \"posix_spawnp\",\n        \"pread\",\n        \"preadv\",\n        \"pwrite\",\n        \"pwritev\",\n        \"readv\",\n        \"register_at_fork\",\n        \"sched_get_priority_max\",\n        \"sched_get_priority_min\",\n        \"sched_yield\",\n        \"sendfile\",\n        \"setegid\",\n        \"seteuid\",\n        \"setgid\",\n        \"setgroups\",\n        \"setpgid\",\n        \"setpgrp\",\n        \"setpriority\",\n        \"setregid\",\n        \"setreuid\",\n        \"setsid\",\n        \"setuid\",\n        \"spawnlp\",\n        \"spawnlpe\",\n        \"spawnvp\",\n        \"spawnvpe\",\n        \"statvfs\",\n        \"sync\",\n        \"sysconf\",\n        \"sysconf_names\",\n        \"tcgetpgrp\",\n        \"tcsetpgrp\",\n        \"ttyname\",\n        \"uname\",\n        \"wait\",\n        \"wait3\",\n        \"wait4\",\n        \"writev\",\n    ]\nif sys.platform != \"win32\" and sys.version_info >= (3, 13):\n    __all__ += [\"grantpt\", \"posix_openpt\", \"ptsname\", \"unlockpt\"]\nif sys.platform != \"win32\" and sys.version_info >= (3, 11):\n    __all__ += [\"login_tty\"]\nif sys.platform != \"win32\" and sys.version_info >= (3, 10):\n    __all__ += [\"O_FSYNC\"]\nif sys.platform != \"darwin\" and sys.platform != \"win32\":\n    __all__ += [\n        \"POSIX_FADV_DONTNEED\",\n        \"POSIX_FADV_NOREUSE\",\n        \"POSIX_FADV_NORMAL\",\n        \"POSIX_FADV_RANDOM\",\n        \"POSIX_FADV_SEQUENTIAL\",\n        \"POSIX_FADV_WILLNEED\",\n        \"RWF_DSYNC\",\n        \"RWF_HIPRI\",\n        \"RWF_NOWAIT\",\n        \"RWF_SYNC\",\n        \"ST_APPEND\",\n        \"ST_MANDLOCK\",\n        \"ST_NOATIME\",\n        \"ST_NODEV\",\n        \"ST_NODIRATIME\",\n        \"ST_NOEXEC\",\n        \"ST_RELATIME\",\n        \"ST_SYNCHRONOUS\",\n        \"ST_WRITE\",\n        \"fdatasync\",\n        \"getresgid\",\n        \"getresuid\",\n        \"pipe2\",\n        \"posix_fadvise\",\n        \"posix_fallocate\",\n        \"sched_getaffinity\",\n        \"sched_getparam\",\n        \"sched_getscheduler\",\n        \"sched_param\",\n        \"sched_rr_get_interval\",\n        \"sched_setaffinity\",\n        \"sched_setparam\",\n        \"sched_setscheduler\",\n        \"setresgid\",\n        \"setresuid\",\n    ]\nif sys.platform != \"linux\" and sys.platform != \"win32\":\n    __all__ += [\"O_EXLOCK\", \"O_SHLOCK\", \"chflags\", \"lchflags\"]\nif sys.platform != \"linux\" and sys.platform != \"win32\" and sys.version_info >= (3, 13):\n    __all__ += [\"O_EXEC\", \"O_SEARCH\"]\nif sys.platform != \"darwin\" or sys.version_info >= (3, 13):\n    if sys.platform != \"win32\":\n        __all__ += [\"waitid\", \"waitid_result\"]\nif sys.platform != \"win32\" or sys.version_info >= (3, 13):\n    __all__ += [\"fchmod\"]\n    if sys.platform != \"linux\":\n        __all__ += [\"lchmod\"]\nif sys.platform != \"win32\" or sys.version_info >= (3, 12):\n    __all__ += [\"get_blocking\", \"set_blocking\"]\nif sys.platform != \"win32\" or sys.version_info >= (3, 11):\n    __all__ += [\"EX_OK\"]\n\n# This unnecessary alias is to work around various errors\npath = _path\n\n_T = TypeVar(\"_T\")\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n\n# ----- os variables -----\n\nerror = OSError\n\nsupports_bytes_environ: bool\n\nsupports_dir_fd: set[Callable[..., Any]]\nsupports_fd: set[Callable[..., Any]]\nsupports_effective_ids: set[Callable[..., Any]]\nsupports_follow_symlinks: set[Callable[..., Any]]\n\nif sys.platform != \"win32\":\n    # Unix only\n    PRIO_PROCESS: Final[int]\n    PRIO_PGRP: Final[int]\n    PRIO_USER: Final[int]\n\n    F_LOCK: Final[int]\n    F_TLOCK: Final[int]\n    F_ULOCK: Final[int]\n    F_TEST: Final[int]\n\n    if sys.platform != \"darwin\":\n        POSIX_FADV_NORMAL: Final[int]\n        POSIX_FADV_SEQUENTIAL: Final[int]\n        POSIX_FADV_RANDOM: Final[int]\n        POSIX_FADV_NOREUSE: Final[int]\n        POSIX_FADV_WILLNEED: Final[int]\n        POSIX_FADV_DONTNEED: Final[int]\n\n    if sys.platform != \"linux\" and sys.platform != \"darwin\":\n        # In the os-module docs, these are marked as being available\n        # on \"Unix, not Emscripten, not WASI.\"\n        # However, in the source code, a comment indicates they're \"FreeBSD constants\".\n        # sys.platform could have one of many values on a FreeBSD Python build,\n        # so the sys-module docs recommend doing `if sys.platform.startswith('freebsd')`\n        # to detect FreeBSD builds. Unfortunately that would be too dynamic\n        # for type checkers, however.\n        SF_NODISKIO: Final[int]\n        SF_MNOWAIT: Final[int]\n        SF_SYNC: Final[int]\n\n        if sys.version_info >= (3, 11):\n            SF_NOCACHE: Final[int]\n\n    if sys.platform == \"linux\":\n        XATTR_SIZE_MAX: Final[int]\n        XATTR_CREATE: Final[int]\n        XATTR_REPLACE: Final[int]\n\n    P_PID: Final[int]\n    P_PGID: Final[int]\n    P_ALL: Final[int]\n\n    if sys.platform == \"linux\":\n        P_PIDFD: Final[int]\n\n    WEXITED: Final[int]\n    WSTOPPED: Final[int]\n    WNOWAIT: Final[int]\n\n    CLD_EXITED: Final[int]\n    CLD_DUMPED: Final[int]\n    CLD_TRAPPED: Final[int]\n    CLD_CONTINUED: Final[int]\n    CLD_KILLED: Final[int]\n    CLD_STOPPED: Final[int]\n\n    SCHED_OTHER: Final[int]\n    SCHED_FIFO: Final[int]\n    SCHED_RR: Final[int]\n    if sys.platform != \"darwin\" and sys.platform != \"linux\":\n        SCHED_SPORADIC: Final[int]\n\nif sys.platform == \"linux\":\n    SCHED_BATCH: Final[int]\n    SCHED_IDLE: Final[int]\n    SCHED_RESET_ON_FORK: Final[int]\n\nif sys.version_info >= (3, 14) and sys.platform == \"linux\":\n    SCHED_DEADLINE: Final[int]\n    SCHED_NORMAL: Final[int]\n\nif sys.platform != \"win32\":\n    RTLD_LAZY: Final[int]\n    RTLD_NOW: Final[int]\n    RTLD_GLOBAL: Final[int]\n    RTLD_LOCAL: Final[int]\n    RTLD_NODELETE: Final[int]\n    RTLD_NOLOAD: Final[int]\n\nif sys.platform == \"linux\":\n    RTLD_DEEPBIND: Final[int]\n    GRND_NONBLOCK: Final[int]\n    GRND_RANDOM: Final[int]\n\nif sys.platform == \"darwin\" and sys.version_info >= (3, 12):\n    PRIO_DARWIN_BG: Final[int]\n    PRIO_DARWIN_NONUI: Final[int]\n    PRIO_DARWIN_PROCESS: Final[int]\n    PRIO_DARWIN_THREAD: Final[int]\n\nSEEK_SET: Final = 0\nSEEK_CUR: Final = 1\nSEEK_END: Final = 2\nif sys.platform != \"win32\":\n    SEEK_DATA: Final = 3\n    SEEK_HOLE: Final = 4\n\nO_RDONLY: Final[int]\nO_WRONLY: Final[int]\nO_RDWR: Final[int]\nO_APPEND: Final[int]\nO_CREAT: Final[int]\nO_EXCL: Final[int]\nO_TRUNC: Final[int]\nif sys.platform == \"win32\":\n    O_BINARY: Final[int]\n    O_NOINHERIT: Final[int]\n    O_SHORT_LIVED: Final[int]\n    O_TEMPORARY: Final[int]\n    O_RANDOM: Final[int]\n    O_SEQUENTIAL: Final[int]\n    O_TEXT: Final[int]\n\nif sys.platform != \"win32\":\n    O_DSYNC: Final[int]\n    O_SYNC: Final[int]\n    O_NDELAY: Final[int]\n    O_NONBLOCK: Final[int]\n    O_NOCTTY: Final[int]\n    O_CLOEXEC: Final[int]\n    O_ASYNC: Final[int]  # Gnu extension if in C library\n    O_DIRECTORY: Final[int]  # Gnu extension if in C library\n    O_NOFOLLOW: Final[int]  # Gnu extension if in C library\n    O_ACCMODE: Final[int]  # TODO: when does this exist?\n\nif sys.platform == \"linux\":\n    O_RSYNC: Final[int]\n    O_DIRECT: Final[int]  # Gnu extension if in C library\n    O_NOATIME: Final[int]  # Gnu extension if in C library\n    O_PATH: Final[int]  # Gnu extension if in C library\n    O_TMPFILE: Final[int]  # Gnu extension if in C library\n    O_LARGEFILE: Final[int]  # Gnu extension if in C library\n\nif sys.platform != \"linux\" and sys.platform != \"win32\":\n    O_SHLOCK: Final[int]\n    O_EXLOCK: Final[int]\n\nif sys.platform == \"darwin\" and sys.version_info >= (3, 10):\n    O_EVTONLY: Final[int]\n    O_NOFOLLOW_ANY: Final[int]\n    O_SYMLINK: Final[int]\n\nif sys.platform != \"win32\" and sys.version_info >= (3, 10):\n    O_FSYNC: Final[int]\n\nif sys.platform != \"linux\" and sys.platform != \"win32\" and sys.version_info >= (3, 13):\n    O_EXEC: Final[int]\n    O_SEARCH: Final[int]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    # posix, but apparently missing on macos\n    ST_APPEND: Final[int]\n    ST_MANDLOCK: Final[int]\n    ST_NOATIME: Final[int]\n    ST_NODEV: Final[int]\n    ST_NODIRATIME: Final[int]\n    ST_NOEXEC: Final[int]\n    ST_RELATIME: Final[int]\n    ST_SYNCHRONOUS: Final[int]\n    ST_WRITE: Final[int]\n\nif sys.platform != \"win32\":\n    NGROUPS_MAX: Final[int]\n    ST_NOSUID: Final[int]\n    ST_RDONLY: Final[int]\n\nlinesep: Literal[\"\\n\", \"\\r\\n\"]\nname: LiteralString\n\nF_OK: Final = 0\nR_OK: Final = 4\nW_OK: Final = 2\nX_OK: Final = 1\n\n_EnvironCodeFunc: TypeAlias = Callable[[AnyStr], AnyStr]\n\nclass _Environ(MutableMapping[AnyStr, AnyStr], Generic[AnyStr]):\n    encodekey: _EnvironCodeFunc[AnyStr]\n    decodekey: _EnvironCodeFunc[AnyStr]\n    encodevalue: _EnvironCodeFunc[AnyStr]\n    decodevalue: _EnvironCodeFunc[AnyStr]\n    def __init__(\n        self,\n        data: MutableMapping[AnyStr, AnyStr],\n        encodekey: _EnvironCodeFunc[AnyStr],\n        decodekey: _EnvironCodeFunc[AnyStr],\n        encodevalue: _EnvironCodeFunc[AnyStr],\n        decodevalue: _EnvironCodeFunc[AnyStr],\n    ) -> None: ...\n    @overload\n    def get(self, key: AnyStr, default: None = None) -> AnyStr | None: ...\n    @overload\n    def get(self, key: AnyStr, default: AnyStr) -> AnyStr: ...\n    @overload\n    def get(self, key: AnyStr, default: _T) -> AnyStr | _T: ...\n    @overload\n    def pop(self, key: AnyStr) -> AnyStr: ...\n    @overload\n    def pop(self, key: AnyStr, default: AnyStr) -> AnyStr: ...\n    @overload\n    def pop(self, key: AnyStr, default: _T) -> AnyStr | _T: ...\n    def setdefault(self, key: AnyStr, value: AnyStr) -> AnyStr: ...\n    def copy(self) -> dict[AnyStr, AnyStr]: ...\n    def __delitem__(self, key: AnyStr) -> None: ...\n    def __getitem__(self, key: AnyStr) -> AnyStr: ...\n    def __setitem__(self, key: AnyStr, value: AnyStr) -> None: ...\n    def __iter__(self) -> Iterator[AnyStr]: ...\n    def __len__(self) -> int: ...\n    def __or__(self, other: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ...\n    def __ror__(self, other: Mapping[_T1, _T2]) -> dict[AnyStr | _T1, AnyStr | _T2]: ...\n    # We use @overload instead of a Union for reasons similar to those given for\n    # overloading MutableMapping.update in stdlib/typing.pyi\n    # The type: ignore is needed due to incompatible __or__/__ior__ signatures\n    @overload  # type: ignore[misc]\n    def __ior__(self, other: Mapping[AnyStr, AnyStr]) -> Self: ...\n    @overload\n    def __ior__(self, other: Iterable[tuple[AnyStr, AnyStr]]) -> Self: ...\n\nenviron: _Environ[str]\nif sys.platform != \"win32\":\n    environb: _Environ[bytes]\n\nif sys.version_info >= (3, 14):\n    def reload_environ() -> None: ...\n\nif sys.version_info >= (3, 11) or sys.platform != \"win32\":\n    EX_OK: Final[int]\n\nif sys.platform != \"win32\":\n    confstr_names: dict[str, int]\n    pathconf_names: dict[str, int]\n    sysconf_names: dict[str, int]\n\n    EX_USAGE: Final[int]\n    EX_DATAERR: Final[int]\n    EX_NOINPUT: Final[int]\n    EX_NOUSER: Final[int]\n    EX_NOHOST: Final[int]\n    EX_UNAVAILABLE: Final[int]\n    EX_SOFTWARE: Final[int]\n    EX_OSERR: Final[int]\n    EX_OSFILE: Final[int]\n    EX_CANTCREAT: Final[int]\n    EX_IOERR: Final[int]\n    EX_TEMPFAIL: Final[int]\n    EX_PROTOCOL: Final[int]\n    EX_NOPERM: Final[int]\n    EX_CONFIG: Final[int]\n\n# Exists on some Unix platforms, e.g. Solaris.\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    EX_NOTFOUND: Final[int]\n\nP_NOWAIT: Final[int]\nP_NOWAITO: Final[int]\nP_WAIT: Final[int]\nif sys.platform == \"win32\":\n    P_DETACH: Final[int]\n    P_OVERLAY: Final[int]\n\n# wait()/waitpid() options\nif sys.platform != \"win32\":\n    WNOHANG: Final[int]  # Unix only\n    WCONTINUED: Final[int]  # some Unix systems\n    WUNTRACED: Final[int]  # Unix only\n\nTMP_MAX: Final[int]  # Undocumented, but used by tempfile\n\n# ----- os classes (structures) -----\n@final\nclass stat_result(structseq[float], tuple[int, int, int, int, int, int, int, float, float, float]):\n    # The constructor of this class takes an iterable of variable length (though it must be at least 10).\n    #\n    # However, this class behaves like a tuple of 10 elements,\n    # no matter how long the iterable supplied to the constructor is.\n    # https://github.com/python/typeshed/pull/6560#discussion_r767162532\n    #\n    # The 10 elements always present are st_mode, st_ino, st_dev, st_nlink,\n    # st_uid, st_gid, st_size, st_atime, st_mtime, st_ctime.\n    #\n    # More items may be added at the end by some implementations.\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"st_mode\", \"st_ino\", \"st_dev\", \"st_nlink\", \"st_uid\", \"st_gid\", \"st_size\")\n\n    @property\n    def st_mode(self) -> int: ...  # protection bits,\n    @property\n    def st_ino(self) -> int: ...  # inode number,\n    @property\n    def st_dev(self) -> int: ...  # device,\n    @property\n    def st_nlink(self) -> int: ...  # number of hard links,\n    @property\n    def st_uid(self) -> int: ...  # user id of owner,\n    @property\n    def st_gid(self) -> int: ...  # group id of owner,\n    @property\n    def st_size(self) -> int: ...  # size of file, in bytes,\n    @property\n    def st_atime(self) -> float: ...  # time of most recent access,\n    @property\n    def st_mtime(self) -> float: ...  # time of most recent content modification,\n    # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows)\n    if sys.version_info >= (3, 12) and sys.platform == \"win32\":\n        @property\n        @deprecated(\n            \"\"\"\\\nUse st_birthtime instead to retrieve the file creation time. \\\nIn the future, this property will contain the last metadata change time.\"\"\"\n        )\n        def st_ctime(self) -> float: ...\n    else:\n        @property\n        def st_ctime(self) -> float: ...\n\n    @property\n    def st_atime_ns(self) -> int: ...  # time of most recent access, in nanoseconds\n    @property\n    def st_mtime_ns(self) -> int: ...  # time of most recent content modification in nanoseconds\n    # platform dependent (time of most recent metadata change on Unix, or the time of creation on Windows) in nanoseconds\n    @property\n    def st_ctime_ns(self) -> int: ...\n    if sys.platform == \"win32\":\n        @property\n        def st_file_attributes(self) -> int: ...\n        @property\n        def st_reparse_tag(self) -> int: ...\n        if sys.version_info >= (3, 12):\n            @property\n            def st_birthtime(self) -> float: ...  # time of file creation in seconds\n            @property\n            def st_birthtime_ns(self) -> int: ...  # time of file creation in nanoseconds\n    else:\n        @property\n        def st_blocks(self) -> int: ...  # number of blocks allocated for file\n        @property\n        def st_blksize(self) -> int: ...  # filesystem blocksize\n        @property\n        def st_rdev(self) -> int: ...  # type of device if an inode device\n        if sys.platform != \"linux\":\n            # These properties are available on MacOS, but not Ubuntu.\n            # On other Unix systems (such as FreeBSD), the following attributes may be\n            # available (but may be only filled out if root tries to use them):\n            @property\n            def st_gen(self) -> int: ...  # file generation number\n            @property\n            def st_birthtime(self) -> float: ...  # time of file creation in seconds\n    if sys.platform == \"darwin\":\n        @property\n        def st_flags(self) -> int: ...  # user defined flags for file\n    # Attributes documented as sometimes appearing, but deliberately omitted from the stub: `st_creator`, `st_rsize`, `st_type`.\n    # See https://github.com/python/typeshed/pull/6560#issuecomment-991253327\n\n# mypy and pyright object to this being both ABC and Protocol.\n# At runtime it inherits from ABC and is not a Protocol, but it will be\n# on the allowlist for use as a Protocol starting in 3.14.\n@runtime_checkable\nclass PathLike(ABC, Protocol[AnyStr_co]):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    __slots__ = ()\n    @abstractmethod\n    def __fspath__(self) -> AnyStr_co: ...\n\n@overload\ndef listdir(path: StrPath | None = None) -> list[str]: ...\n@overload\ndef listdir(path: BytesPath) -> list[bytes]: ...\n@overload\ndef listdir(path: int) -> list[str]: ...\n@final\nclass DirEntry(Generic[AnyStr]):\n    # This is what the scandir iterator yields\n    # The constructor is hidden\n\n    @property\n    def name(self) -> AnyStr: ...\n    @property\n    def path(self) -> AnyStr: ...\n    def inode(self) -> int: ...\n    def is_dir(self, *, follow_symlinks: bool = True) -> bool: ...\n    def is_file(self, *, follow_symlinks: bool = True) -> bool: ...\n    def is_symlink(self) -> bool: ...\n    def stat(self, *, follow_symlinks: bool = True) -> stat_result: ...\n    def __fspath__(self) -> AnyStr: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n    if sys.version_info >= (3, 12):\n        def is_junction(self) -> bool: ...\n\n@final\nclass statvfs_result(structseq[int], tuple[int, int, int, int, int, int, int, int, int, int, int]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\n            \"f_bsize\",\n            \"f_frsize\",\n            \"f_blocks\",\n            \"f_bfree\",\n            \"f_bavail\",\n            \"f_files\",\n            \"f_ffree\",\n            \"f_favail\",\n            \"f_flag\",\n            \"f_namemax\",\n        )\n\n    @property\n    def f_bsize(self) -> int: ...\n    @property\n    def f_frsize(self) -> int: ...\n    @property\n    def f_blocks(self) -> int: ...\n    @property\n    def f_bfree(self) -> int: ...\n    @property\n    def f_bavail(self) -> int: ...\n    @property\n    def f_files(self) -> int: ...\n    @property\n    def f_ffree(self) -> int: ...\n    @property\n    def f_favail(self) -> int: ...\n    @property\n    def f_flag(self) -> int: ...\n    @property\n    def f_namemax(self) -> int: ...\n    @property\n    def f_fsid(self) -> int: ...\n\n# ----- os function stubs -----\ndef fsencode(filename: StrOrBytesPath) -> bytes: ...\ndef fsdecode(filename: StrOrBytesPath) -> str: ...\n@overload\ndef fspath(path: str) -> str: ...\n@overload\ndef fspath(path: bytes) -> bytes: ...\n@overload\ndef fspath(path: PathLike[AnyStr]) -> AnyStr: ...\ndef get_exec_path(env: Mapping[str, str] | None = None) -> list[str]: ...\ndef getlogin() -> str: ...\ndef getpid() -> int: ...\ndef getppid() -> int: ...\ndef strerror(code: int, /) -> str: ...\ndef umask(mask: int, /) -> int: ...\n@final\nclass uname_result(structseq[str], tuple[str, str, str, str, str]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"sysname\", \"nodename\", \"release\", \"version\", \"machine\")\n\n    @property\n    def sysname(self) -> str: ...\n    @property\n    def nodename(self) -> str: ...\n    @property\n    def release(self) -> str: ...\n    @property\n    def version(self) -> str: ...\n    @property\n    def machine(self) -> str: ...\n\nif sys.platform != \"win32\":\n    def ctermid() -> str: ...\n    def getegid() -> int: ...\n    def geteuid() -> int: ...\n    def getgid() -> int: ...\n    def getgrouplist(user: str, group: int, /) -> list[int]: ...\n    def getgroups() -> list[int]: ...  # Unix only, behaves differently on Mac\n    def initgroups(username: str, gid: int, /) -> None: ...\n    def getpgid(pid: int) -> int: ...\n    def getpgrp() -> int: ...\n    def getpriority(which: int, who: int) -> int: ...\n    def setpriority(which: int, who: int, priority: int) -> None: ...\n    if sys.platform != \"darwin\":\n        def getresuid() -> tuple[int, int, int]: ...\n        def getresgid() -> tuple[int, int, int]: ...\n\n    def getuid() -> int: ...\n    def setegid(egid: int, /) -> None: ...\n    def seteuid(euid: int, /) -> None: ...\n    def setgid(gid: int, /) -> None: ...\n    def setgroups(groups: Sequence[int], /) -> None: ...\n    def setpgrp() -> None: ...\n    def setpgid(pid: int, pgrp: int, /) -> None: ...\n    def setregid(rgid: int, egid: int, /) -> None: ...\n    if sys.platform != \"darwin\":\n        def setresgid(rgid: int, egid: int, sgid: int, /) -> None: ...\n        def setresuid(ruid: int, euid: int, suid: int, /) -> None: ...\n\n    def setreuid(ruid: int, euid: int, /) -> None: ...\n    def getsid(pid: int, /) -> int: ...\n    def setsid() -> None: ...\n    def setuid(uid: int, /) -> None: ...\n    def uname() -> uname_result: ...\n\n@overload\ndef getenv(key: str) -> str | None: ...\n@overload\ndef getenv(key: str, default: _T) -> str | _T: ...\n\nif sys.platform != \"win32\":\n    @overload\n    def getenvb(key: bytes) -> bytes | None: ...\n    @overload\n    def getenvb(key: bytes, default: _T) -> bytes | _T: ...\n    def putenv(name: StrOrBytesPath, value: StrOrBytesPath, /) -> None: ...\n    def unsetenv(name: StrOrBytesPath, /) -> None: ...\n\nelse:\n    def putenv(name: str, value: str, /) -> None: ...\n    def unsetenv(name: str, /) -> None: ...\n\n_Opener: TypeAlias = Callable[[str, int], int]\n\n@overload\ndef fdopen(\n    fd: int,\n    mode: OpenTextMode = \"r\",\n    buffering: int = -1,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> TextIOWrapper: ...\n@overload\ndef fdopen(\n    fd: int,\n    mode: OpenBinaryMode,\n    buffering: Literal[0],\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> FileIO: ...\n@overload\ndef fdopen(\n    fd: int,\n    mode: OpenBinaryModeUpdating,\n    buffering: Literal[-1, 1] = -1,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> BufferedRandom: ...\n@overload\ndef fdopen(\n    fd: int,\n    mode: OpenBinaryModeWriting,\n    buffering: Literal[-1, 1] = -1,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> BufferedWriter: ...\n@overload\ndef fdopen(\n    fd: int,\n    mode: OpenBinaryModeReading,\n    buffering: Literal[-1, 1] = -1,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> BufferedReader: ...\n@overload\ndef fdopen(\n    fd: int,\n    mode: OpenBinaryMode,\n    buffering: int = -1,\n    encoding: None = None,\n    errors: None = None,\n    newline: None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> BinaryIO: ...\n@overload\ndef fdopen(\n    fd: int,\n    mode: str,\n    buffering: int = -1,\n    encoding: str | None = None,\n    errors: str | None = None,\n    newline: str | None = None,\n    closefd: bool = True,\n    opener: _Opener | None = None,\n) -> IO[Any]: ...\ndef close(fd: int) -> None: ...\ndef closerange(fd_low: int, fd_high: int, /) -> None: ...\ndef device_encoding(fd: int) -> str | None: ...\ndef dup(fd: int, /) -> int: ...\ndef dup2(fd: int, fd2: int, inheritable: bool = True) -> int: ...\ndef fstat(fd: int) -> stat_result: ...\ndef ftruncate(fd: int, length: int, /) -> None: ...\ndef fsync(fd: FileDescriptorLike) -> None: ...\ndef isatty(fd: int, /) -> bool: ...\n\nif sys.platform != \"win32\" and sys.version_info >= (3, 11):\n    def login_tty(fd: int, /) -> None: ...\n\nif sys.version_info >= (3, 11):\n    def lseek(fd: int, position: int, whence: int, /) -> int: ...\n\nelse:\n    def lseek(fd: int, position: int, how: int, /) -> int: ...\n\ndef open(path: StrOrBytesPath, flags: int, mode: int = 0o777, *, dir_fd: int | None = None) -> int: ...\ndef pipe() -> tuple[int, int]: ...\ndef read(fd: int, length: int, /) -> bytes: ...\n\nif sys.version_info >= (3, 12) or sys.platform != \"win32\":\n    def get_blocking(fd: int, /) -> bool: ...\n    def set_blocking(fd: int, blocking: bool, /) -> None: ...\n\nif sys.platform != \"win32\":\n    def fchown(fd: int, uid: int, gid: int) -> None: ...\n    def fpathconf(fd: int, name: str | int, /) -> int: ...\n    def fstatvfs(fd: int, /) -> statvfs_result: ...\n    def lockf(fd: int, command: int, length: int, /) -> None: ...\n    def openpty() -> tuple[int, int]: ...  # some flavors of Unix\n    if sys.platform != \"darwin\":\n        def fdatasync(fd: FileDescriptorLike) -> None: ...\n        def pipe2(flags: int, /) -> tuple[int, int]: ...  # some flavors of Unix\n        def posix_fallocate(fd: int, offset: int, length: int, /) -> None: ...\n        def posix_fadvise(fd: int, offset: int, length: int, advice: int, /) -> None: ...\n\n    def pread(fd: int, length: int, offset: int, /) -> bytes: ...\n    def pwrite(fd: int, buffer: ReadableBuffer, offset: int, /) -> int: ...\n    # In CI, stubtest sometimes reports that these are available on MacOS, sometimes not\n    def preadv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], offset: int, flags: int = 0, /) -> int: ...\n    def pwritev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], offset: int, flags: int = 0, /) -> int: ...\n    if sys.platform != \"darwin\":\n        if sys.version_info >= (3, 10):\n            RWF_APPEND: Final[int]  # docs say available on 3.7+, stubtest says otherwise\n        RWF_DSYNC: Final[int]\n        RWF_SYNC: Final[int]\n        RWF_HIPRI: Final[int]\n        RWF_NOWAIT: Final[int]\n\n    if sys.platform == \"linux\":\n        def sendfile(out_fd: FileDescriptor, in_fd: FileDescriptor, offset: int | None, count: int) -> int: ...\n    else:\n        def sendfile(\n            out_fd: FileDescriptor,\n            in_fd: FileDescriptor,\n            offset: int,\n            count: int,\n            headers: Sequence[ReadableBuffer] = (),\n            trailers: Sequence[ReadableBuffer] = (),\n            flags: int = 0,\n        ) -> int: ...  # FreeBSD and Mac OS X only\n\n    def readv(fd: int, buffers: SupportsLenAndGetItem[WriteableBuffer], /) -> int: ...\n    def writev(fd: int, buffers: SupportsLenAndGetItem[ReadableBuffer], /) -> int: ...\n\nif sys.version_info >= (3, 14):\n    def readinto(fd: int, buffer: ReadableBuffer, /) -> int: ...\n\n@final\nclass terminal_size(structseq[int], tuple[int, int]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"columns\", \"lines\")\n\n    @property\n    def columns(self) -> int: ...\n    @property\n    def lines(self) -> int: ...\n\ndef get_terminal_size(fd: int = ..., /) -> terminal_size: ...\ndef get_inheritable(fd: int, /) -> bool: ...\ndef set_inheritable(fd: int, inheritable: bool, /) -> None: ...\n\nif sys.platform == \"win32\":\n    def get_handle_inheritable(handle: int, /) -> bool: ...\n    def set_handle_inheritable(handle: int, inheritable: bool, /) -> None: ...\n\nif sys.platform != \"win32\":\n    # Unix only\n    def tcgetpgrp(fd: int, /) -> int: ...\n    def tcsetpgrp(fd: int, pgid: int, /) -> None: ...\n    def ttyname(fd: int, /) -> str: ...\n\ndef write(fd: int, data: ReadableBuffer, /) -> int: ...\ndef access(\n    path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, effective_ids: bool = False, follow_symlinks: bool = True\n) -> bool: ...\ndef chdir(path: FileDescriptorOrPath) -> None: ...\n\nif sys.platform != \"win32\":\n    def fchdir(fd: FileDescriptorLike) -> None: ...\n\ndef getcwd() -> str: ...\ndef getcwdb() -> bytes: ...\ndef chmod(path: FileDescriptorOrPath, mode: int, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> None: ...\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    def chflags(path: StrOrBytesPath, flags: int, follow_symlinks: bool = True) -> None: ...  # some flavors of Unix\n    def lchflags(path: StrOrBytesPath, flags: int) -> None: ...\n\nif sys.platform != \"win32\":\n    def chroot(path: StrOrBytesPath) -> None: ...\n    def chown(\n        path: FileDescriptorOrPath, uid: int, gid: int, *, dir_fd: int | None = None, follow_symlinks: bool = True\n    ) -> None: ...\n    def lchown(path: StrOrBytesPath, uid: int, gid: int) -> None: ...\n\ndef link(\n    src: StrOrBytesPath,\n    dst: StrOrBytesPath,\n    *,\n    src_dir_fd: int | None = None,\n    dst_dir_fd: int | None = None,\n    follow_symlinks: bool = True,\n) -> None: ...\ndef lstat(path: StrOrBytesPath, *, dir_fd: int | None = None) -> stat_result: ...\ndef mkdir(path: StrOrBytesPath, mode: int = 0o777, *, dir_fd: int | None = None) -> None: ...\n\nif sys.platform != \"win32\":\n    def mkfifo(path: StrOrBytesPath, mode: int = 0o666, *, dir_fd: int | None = None) -> None: ...  # Unix only\n\ndef makedirs(name: StrOrBytesPath, mode: int = 0o777, exist_ok: bool = False) -> None: ...\n\nif sys.platform != \"win32\":\n    def mknod(path: StrOrBytesPath, mode: int = 0o600, device: int = 0, *, dir_fd: int | None = None) -> None: ...\n    def major(device: int, /) -> int: ...\n    def minor(device: int, /) -> int: ...\n    def makedev(major: int, minor: int, /) -> int: ...\n    def pathconf(path: FileDescriptorOrPath, name: str | int) -> int: ...  # Unix only\n\ndef readlink(path: GenericPath[AnyStr], *, dir_fd: int | None = None) -> AnyStr: ...\ndef remove(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ...\ndef removedirs(name: StrOrBytesPath) -> None: ...\ndef rename(src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = None, dst_dir_fd: int | None = None) -> None: ...\ndef renames(old: StrOrBytesPath, new: StrOrBytesPath) -> None: ...\ndef replace(\n    src: StrOrBytesPath, dst: StrOrBytesPath, *, src_dir_fd: int | None = None, dst_dir_fd: int | None = None\n) -> None: ...\ndef rmdir(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ...\n@final\n@type_check_only\nclass _ScandirIterator(Generic[AnyStr]):\n    def __del__(self) -> None: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> DirEntry[AnyStr]: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n    def close(self) -> None: ...\n\n@overload\ndef scandir(path: None = None) -> _ScandirIterator[str]: ...\n@overload\ndef scandir(path: int) -> _ScandirIterator[str]: ...\n@overload\ndef scandir(path: GenericPath[AnyStr]) -> _ScandirIterator[AnyStr]: ...\ndef stat(path: FileDescriptorOrPath, *, dir_fd: int | None = None, follow_symlinks: bool = True) -> stat_result: ...\n\nif sys.platform != \"win32\":\n    def statvfs(path: FileDescriptorOrPath) -> statvfs_result: ...  # Unix only\n\ndef symlink(\n    src: StrOrBytesPath, dst: StrOrBytesPath, target_is_directory: bool = False, *, dir_fd: int | None = None\n) -> None: ...\n\nif sys.platform != \"win32\":\n    def sync() -> None: ...  # Unix only\n\ndef truncate(path: FileDescriptorOrPath, length: int) -> None: ...  # Unix only up to version 3.4\ndef unlink(path: StrOrBytesPath, *, dir_fd: int | None = None) -> None: ...\ndef utime(\n    path: FileDescriptorOrPath,\n    times: tuple[int, int] | tuple[float, float] | None = None,\n    *,\n    ns: tuple[int, int] = ...,\n    dir_fd: int | None = None,\n    follow_symlinks: bool = True,\n) -> None: ...\n\n_OnError: TypeAlias = Callable[[OSError], object]\n\ndef walk(\n    top: GenericPath[AnyStr], topdown: bool = True, onerror: _OnError | None = None, followlinks: bool = False\n) -> Iterator[tuple[AnyStr, list[AnyStr], list[AnyStr]]]: ...\n\nif sys.platform != \"win32\":\n    @overload\n    def fwalk(\n        top: StrPath = \".\",\n        topdown: bool = True,\n        onerror: _OnError | None = None,\n        *,\n        follow_symlinks: bool = False,\n        dir_fd: int | None = None,\n    ) -> Iterator[tuple[str, list[str], list[str], int]]: ...\n    @overload\n    def fwalk(\n        top: BytesPath,\n        topdown: bool = True,\n        onerror: _OnError | None = None,\n        *,\n        follow_symlinks: bool = False,\n        dir_fd: int | None = None,\n    ) -> Iterator[tuple[bytes, list[bytes], list[bytes], int]]: ...\n    if sys.platform == \"linux\":\n        def getxattr(path: FileDescriptorOrPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = True) -> bytes: ...\n        def listxattr(path: FileDescriptorOrPath | None = None, *, follow_symlinks: bool = True) -> list[str]: ...\n        def removexattr(path: FileDescriptorOrPath, attribute: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ...\n        def setxattr(\n            path: FileDescriptorOrPath,\n            attribute: StrOrBytesPath,\n            value: ReadableBuffer,\n            flags: int = 0,\n            *,\n            follow_symlinks: bool = True,\n        ) -> None: ...\n\ndef abort() -> NoReturn: ...\n\n# These are defined as execl(file, *args) but the first *arg is mandatory.\ndef execl(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> NoReturn: ...\ndef execlp(file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]]]]) -> NoReturn: ...\n\n# These are: execle(file, *args, env) but env is pulled from the last element of the args.\ndef execle(\n    file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]], _ExecEnv]]\n) -> NoReturn: ...\ndef execlpe(\n    file: StrOrBytesPath, *args: Unpack[tuple[StrOrBytesPath, Unpack[tuple[StrOrBytesPath, ...]], _ExecEnv]]\n) -> NoReturn: ...\n\n# The docs say `args: tuple or list of strings`\n# The implementation enforces tuple or list so we can't use Sequence.\n# Not separating out PathLike[str] and PathLike[bytes] here because it doesn't make much difference\n# in practice, and doing so would explode the number of combinations in this already long union.\n# All these combinations are necessary due to list being invariant.\n_ExecVArgs: TypeAlias = (\n    tuple[StrOrBytesPath, ...]\n    | list[bytes]\n    | list[str]\n    | list[PathLike[Any]]\n    | list[bytes | str]\n    | list[bytes | PathLike[Any]]\n    | list[str | PathLike[Any]]\n    | list[bytes | str | PathLike[Any]]\n)\n# Depending on the OS, the keys and values are passed either to\n# PyUnicode_FSDecoder (which accepts str | ReadableBuffer) or to\n# PyUnicode_FSConverter (which accepts StrOrBytesPath). For simplicity,\n# we limit to str | bytes.\n_ExecEnv: TypeAlias = Mapping[bytes, bytes | str] | Mapping[str, bytes | str]\n\ndef execv(path: StrOrBytesPath, argv: _ExecVArgs, /) -> NoReturn: ...\ndef execve(path: FileDescriptorOrPath, argv: _ExecVArgs, env: _ExecEnv) -> NoReturn: ...\ndef execvp(file: StrOrBytesPath, args: _ExecVArgs) -> NoReturn: ...\ndef execvpe(file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> NoReturn: ...\ndef _exit(status: int) -> NoReturn: ...\ndef kill(pid: int, signal: int, /) -> None: ...\n\nif sys.platform != \"win32\":\n    # Unix only\n    def fork() -> int: ...\n    def forkpty() -> tuple[int, int]: ...  # some flavors of Unix\n    def killpg(pgid: int, signal: int, /) -> None: ...\n    def nice(increment: int, /) -> int: ...\n    if sys.platform != \"darwin\" and sys.platform != \"linux\":\n        def plock(op: int, /) -> None: ...\n\nclass _wrap_close:\n    def __init__(self, stream: TextIOWrapper, proc: Popen[str]) -> None: ...\n    def close(self) -> int | None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n    def __iter__(self) -> Iterator[str]: ...\n    # Methods below here don't exist directly on the _wrap_close object, but\n    # are copied from the wrapped TextIOWrapper object via __getattr__.\n    # The full set of TextIOWrapper methods are technically available this way,\n    # but undocumented. Only a subset are currently included here.\n    def read(self, size: int | None = -1, /) -> str: ...\n    def readable(self) -> bool: ...\n    def readline(self, size: int = -1, /) -> str: ...\n    def readlines(self, hint: int = -1, /) -> list[str]: ...\n    def writable(self) -> bool: ...\n    def write(self, s: str, /) -> int: ...\n    def writelines(self, lines: Iterable[str], /) -> None: ...\n\nif sys.version_info >= (3, 14):\n    @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n    def popen(cmd: str, mode: str = \"r\", buffering: int = -1) -> _wrap_close: ...\n    @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n    def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ...\n    @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n    def spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ...  # Imprecise sig\n\nelse:\n    def popen(cmd: str, mode: str = \"r\", buffering: int = -1) -> _wrap_close: ...\n    def spawnl(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ...\n    def spawnle(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ...  # Imprecise sig\n\nif sys.platform != \"win32\":\n    if sys.version_info >= (3, 14):\n        @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n        def spawnv(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ...\n        @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n        def spawnve(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ...\n\n    else:\n        def spawnv(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ...\n        def spawnve(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ...\n\nelse:\n    if sys.version_info >= (3, 14):\n        @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n        def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: ...\n        @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n        def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: ...\n\n    else:\n        def spawnv(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, /) -> int: ...\n        def spawnve(mode: int, path: StrOrBytesPath, argv: _ExecVArgs, env: _ExecEnv, /) -> int: ...\n\nif sys.version_info >= (3, 14):\n    @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n    def system(command: StrOrBytesPath) -> int: ...\n\nelse:\n    def system(command: StrOrBytesPath) -> int: ...\n\n@final\nclass times_result(structseq[float], tuple[float, float, float, float, float]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"user\", \"system\", \"children_user\", \"children_system\", \"elapsed\")\n\n    @property\n    def user(self) -> float: ...\n    @property\n    def system(self) -> float: ...\n    @property\n    def children_user(self) -> float: ...\n    @property\n    def children_system(self) -> float: ...\n    @property\n    def elapsed(self) -> float: ...\n\ndef times() -> times_result: ...\ndef waitpid(pid: int, options: int, /) -> tuple[int, int]: ...\n\nif sys.platform == \"win32\":\n    if sys.version_info >= (3, 10):\n        def startfile(\n            filepath: StrOrBytesPath,\n            operation: str = ...,\n            arguments: str = \"\",\n            cwd: StrOrBytesPath | None = None,\n            show_cmd: int = 1,\n        ) -> None: ...\n    else:\n        def startfile(filepath: StrOrBytesPath, operation: str = ...) -> None: ...\n\nelse:\n    if sys.version_info >= (3, 14):\n        @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n        def spawnlp(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ...\n        @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n        def spawnlpe(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ...  # Imprecise signature\n        @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n        def spawnvp(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ...\n        @deprecated(\"Soft deprecated. Use the subprocess module instead.\")\n        def spawnvpe(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ...\n\n    else:\n        def spawnlp(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: StrOrBytesPath) -> int: ...\n        def spawnlpe(mode: int, file: StrOrBytesPath, arg0: StrOrBytesPath, *args: Any) -> int: ...  # Imprecise signature\n        def spawnvp(mode: int, file: StrOrBytesPath, args: _ExecVArgs) -> int: ...\n        def spawnvpe(mode: int, file: StrOrBytesPath, args: _ExecVArgs, env: _ExecEnv) -> int: ...\n\n    def wait() -> tuple[int, int]: ...  # Unix only\n    # Added to MacOS in 3.13\n    if sys.platform != \"darwin\" or sys.version_info >= (3, 13):\n        @final\n        class waitid_result(structseq[int], tuple[int, int, int, int, int]):\n            if sys.version_info >= (3, 10):\n                __match_args__: Final = (\"si_pid\", \"si_uid\", \"si_signo\", \"si_status\", \"si_code\")\n\n            @property\n            def si_pid(self) -> int: ...\n            @property\n            def si_uid(self) -> int: ...\n            @property\n            def si_signo(self) -> int: ...\n            @property\n            def si_status(self) -> int: ...\n            @property\n            def si_code(self) -> int: ...\n\n        def waitid(idtype: int, ident: int, options: int, /) -> waitid_result | None: ...\n\n    from resource import struct_rusage\n\n    def wait3(options: int) -> tuple[int, int, struct_rusage]: ...\n    def wait4(pid: int, options: int) -> tuple[int, int, struct_rusage]: ...\n    def WCOREDUMP(status: int, /) -> bool: ...\n    def WIFCONTINUED(status: int) -> bool: ...\n    def WIFSTOPPED(status: int) -> bool: ...\n    def WIFSIGNALED(status: int) -> bool: ...\n    def WIFEXITED(status: int) -> bool: ...\n    def WEXITSTATUS(status: int) -> int: ...\n    def WSTOPSIG(status: int) -> int: ...\n    def WTERMSIG(status: int) -> int: ...\n\n    if sys.version_info >= (3, 13):\n        def posix_spawn(\n            path: StrOrBytesPath,\n            argv: _ExecVArgs,\n            env: _ExecEnv | None,  # None allowed starting in 3.13\n            /,\n            *,\n            file_actions: Sequence[tuple[Any, ...]] | None = (),\n            setpgroup: int = ...,\n            resetids: bool = False,\n            setsid: bool = False,\n            setsigmask: Iterable[int] = (),\n            setsigdef: Iterable[int] = (),\n            scheduler: tuple[Any, sched_param] = ...,\n        ) -> int: ...\n        def posix_spawnp(\n            path: StrOrBytesPath,\n            argv: _ExecVArgs,\n            env: _ExecEnv | None,  # None allowed starting in 3.13\n            /,\n            *,\n            file_actions: Sequence[tuple[Any, ...]] | None = (),\n            setpgroup: int = ...,\n            resetids: bool = False,\n            setsid: bool = False,\n            setsigmask: Iterable[int] = (),\n            setsigdef: Iterable[int] = (),\n            scheduler: tuple[Any, sched_param] = ...,\n        ) -> int: ...\n    else:\n        def posix_spawn(\n            path: StrOrBytesPath,\n            argv: _ExecVArgs,\n            env: _ExecEnv,\n            /,\n            *,\n            file_actions: Sequence[tuple[Any, ...]] | None = (),\n            setpgroup: int = ...,\n            resetids: bool = False,\n            setsid: bool = False,\n            setsigmask: Iterable[int] = (),\n            setsigdef: Iterable[int] = (),\n            scheduler: tuple[Any, sched_param] = ...,\n        ) -> int: ...\n        def posix_spawnp(\n            path: StrOrBytesPath,\n            argv: _ExecVArgs,\n            env: _ExecEnv,\n            /,\n            *,\n            file_actions: Sequence[tuple[Any, ...]] | None = (),\n            setpgroup: int = ...,\n            resetids: bool = False,\n            setsid: bool = False,\n            setsigmask: Iterable[int] = (),\n            setsigdef: Iterable[int] = (),\n            scheduler: tuple[Any, sched_param] = ...,\n        ) -> int: ...\n\n    POSIX_SPAWN_OPEN: Final = 0\n    POSIX_SPAWN_CLOSE: Final = 1\n    POSIX_SPAWN_DUP2: Final = 2\n\nif sys.platform != \"win32\":\n    @final\n    class sched_param(structseq[int], tuple[int]):\n        if sys.version_info >= (3, 10):\n            __match_args__: Final = (\"sched_priority\",)\n\n        def __new__(cls, sched_priority: int) -> Self: ...\n        @property\n        def sched_priority(self) -> int: ...\n\n    def sched_get_priority_min(policy: int) -> int: ...  # some flavors of Unix\n    def sched_get_priority_max(policy: int) -> int: ...  # some flavors of Unix\n    def sched_yield() -> None: ...  # some flavors of Unix\n    if sys.platform != \"darwin\":\n        def sched_setscheduler(pid: int, policy: int, param: sched_param, /) -> None: ...  # some flavors of Unix\n        def sched_getscheduler(pid: int, /) -> int: ...  # some flavors of Unix\n        def sched_rr_get_interval(pid: int, /) -> float: ...  # some flavors of Unix\n        def sched_setparam(pid: int, param: sched_param, /) -> None: ...  # some flavors of Unix\n        def sched_getparam(pid: int, /) -> sched_param: ...  # some flavors of Unix\n        def sched_setaffinity(pid: int, mask: Iterable[int], /) -> None: ...  # some flavors of Unix\n        def sched_getaffinity(pid: int, /) -> set[int]: ...  # some flavors of Unix\n\ndef cpu_count() -> int | None: ...\n\nif sys.version_info >= (3, 13):\n    # Documented to return `int | None`, but falls back to `len(sched_getaffinity(0))` when\n    # available. See https://github.com/python/cpython/blob/417c130/Lib/os.py#L1175-L1186.\n    if sys.platform != \"win32\" and sys.platform != \"darwin\":\n        def process_cpu_count() -> int: ...\n    else:\n        def process_cpu_count() -> int | None: ...\n\nif sys.platform != \"win32\":\n    # Unix only\n    def confstr(name: str | int, /) -> str | None: ...\n    def getloadavg() -> tuple[float, float, float]: ...\n    def sysconf(name: str | int, /) -> int: ...\n\nif sys.platform == \"linux\":\n    def getrandom(size: int, flags: int = 0) -> bytes: ...\n\ndef urandom(size: int, /) -> bytes: ...\n\nif sys.platform != \"win32\":\n    def register_at_fork(\n        *,\n        before: Callable[..., Any] | None = ...,\n        after_in_parent: Callable[..., Any] | None = ...,\n        after_in_child: Callable[..., Any] | None = ...,\n    ) -> None: ...\n\nif sys.platform == \"win32\":\n    class _AddedDllDirectory:\n        path: str | None\n        def __init__(self, path: str | None, cookie: _T, remove_dll_directory: Callable[[_T], object]) -> None: ...\n        def close(self) -> None: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(self, *args: Unused) -> None: ...\n\n    def add_dll_directory(path: str) -> _AddedDllDirectory: ...\n\nif sys.platform == \"linux\":\n    MFD_CLOEXEC: Final[int]\n    MFD_ALLOW_SEALING: Final[int]\n    MFD_HUGETLB: Final[int]\n    MFD_HUGE_SHIFT: Final[int]\n    MFD_HUGE_MASK: Final[int]\n    MFD_HUGE_64KB: Final[int]\n    MFD_HUGE_512KB: Final[int]\n    MFD_HUGE_1MB: Final[int]\n    MFD_HUGE_2MB: Final[int]\n    MFD_HUGE_8MB: Final[int]\n    MFD_HUGE_16MB: Final[int]\n    MFD_HUGE_32MB: Final[int]\n    MFD_HUGE_256MB: Final[int]\n    MFD_HUGE_512MB: Final[int]\n    MFD_HUGE_1GB: Final[int]\n    MFD_HUGE_2GB: Final[int]\n    MFD_HUGE_16GB: Final[int]\n    def memfd_create(name: str, flags: int = ...) -> int: ...\n    def copy_file_range(src: int, dst: int, count: int, offset_src: int | None = None, offset_dst: int | None = None) -> int: ...\n\ndef waitstatus_to_exitcode(status: int) -> int: ...\n\nif sys.platform == \"linux\":\n    def pidfd_open(pid: int, flags: int = 0) -> int: ...\n\nif sys.version_info >= (3, 12) and sys.platform == \"linux\":\n    PIDFD_NONBLOCK: Final = 2048\n\nif sys.version_info >= (3, 12) and sys.platform == \"win32\":\n    def listdrives() -> list[str]: ...\n    def listmounts(volume: str) -> list[str]: ...\n    def listvolumes() -> list[str]: ...\n\nif sys.version_info >= (3, 10) and sys.platform == \"linux\":\n    EFD_CLOEXEC: Final[int]\n    EFD_NONBLOCK: Final[int]\n    EFD_SEMAPHORE: Final[int]\n    SPLICE_F_MORE: Final[int]\n    SPLICE_F_MOVE: Final[int]\n    SPLICE_F_NONBLOCK: Final[int]\n    def eventfd(initval: int, flags: int = 524288) -> FileDescriptor: ...\n    def eventfd_read(fd: FileDescriptor) -> int: ...\n    def eventfd_write(fd: FileDescriptor, value: int) -> None: ...\n    def splice(\n        src: FileDescriptor,\n        dst: FileDescriptor,\n        count: int,\n        offset_src: int | None = None,\n        offset_dst: int | None = None,\n        flags: int = 0,\n    ) -> int: ...\n\nif sys.version_info >= (3, 12) and sys.platform == \"linux\":\n    CLONE_FILES: Final[int]\n    CLONE_FS: Final[int]\n    CLONE_NEWCGROUP: Final[int]  # Linux 4.6+\n    CLONE_NEWIPC: Final[int]  # Linux 2.6.19+\n    CLONE_NEWNET: Final[int]  # Linux 2.6.24+\n    CLONE_NEWNS: Final[int]\n    CLONE_NEWPID: Final[int]  # Linux 3.8+\n    CLONE_NEWTIME: Final[int]  # Linux 5.6+\n    CLONE_NEWUSER: Final[int]  # Linux 3.8+\n    CLONE_NEWUTS: Final[int]  # Linux 2.6.19+\n    CLONE_SIGHAND: Final[int]\n    CLONE_SYSVSEM: Final[int]  # Linux 2.6.26+\n    CLONE_THREAD: Final[int]\n    CLONE_VM: Final[int]\n    def unshare(flags: int) -> None: ...\n    def setns(fd: FileDescriptorLike, nstype: int = 0) -> None: ...\n\nif sys.version_info >= (3, 13) and sys.platform != \"win32\":\n    def posix_openpt(oflag: int, /) -> int: ...\n    def grantpt(fd: FileDescriptorLike, /) -> None: ...\n    def unlockpt(fd: FileDescriptorLike, /) -> None: ...\n    def ptsname(fd: FileDescriptorLike, /) -> str: ...\n\nif sys.version_info >= (3, 13) and sys.platform == \"linux\":\n    TFD_TIMER_ABSTIME: Final = 1\n    TFD_TIMER_CANCEL_ON_SET: Final = 2\n    TFD_NONBLOCK: Final[int]\n    TFD_CLOEXEC: Final[int]\n    POSIX_SPAWN_CLOSEFROM: Final[int]\n\n    def timerfd_create(clockid: int, /, *, flags: int = 0) -> int: ...\n    def timerfd_settime(\n        fd: FileDescriptor, /, *, flags: int = 0, initial: float = 0.0, interval: float = 0.0\n    ) -> tuple[float, float]: ...\n    def timerfd_settime_ns(fd: FileDescriptor, /, *, flags: int = 0, initial: int = 0, interval: int = 0) -> tuple[int, int]: ...\n    def timerfd_gettime(fd: FileDescriptor, /) -> tuple[float, float]: ...\n    def timerfd_gettime_ns(fd: FileDescriptor, /) -> tuple[int, int]: ...\n\nif sys.version_info >= (3, 13) or sys.platform != \"win32\":\n    # Added to Windows in 3.13.\n    def fchmod(fd: int, mode: int) -> None: ...\n\nif sys.platform != \"linux\":\n    if sys.version_info >= (3, 13) or sys.platform != \"win32\":\n        # Added to Windows in 3.13.\n        def lchmod(path: StrOrBytesPath, mode: int) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/os/path.pyi",
    "content": "import sys\n\nif sys.platform == \"win32\":\n    from ntpath import *\n    from ntpath import __all__ as __all__\nelse:\n    from posixpath import *\n    from posixpath import __all__ as __all__\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ossaudiodev.pyi",
    "content": "import sys\nfrom typing import Any, Final, Literal, overload\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    # Depends on soundcard.h\n    AFMT_AC3: Final[int]\n    AFMT_A_LAW: Final[int]\n    AFMT_IMA_ADPCM: Final[int]\n    AFMT_MPEG: Final[int]\n    AFMT_MU_LAW: Final[int]\n    AFMT_QUERY: Final[int]\n    AFMT_S16_BE: Final[int]\n    AFMT_S16_LE: Final[int]\n    AFMT_S16_NE: Final[int]\n    AFMT_S8: Final[int]\n    AFMT_U16_BE: Final[int]\n    AFMT_U16_LE: Final[int]\n    AFMT_U8: Final[int]\n    SNDCTL_COPR_HALT: Final[int]\n    SNDCTL_COPR_LOAD: Final[int]\n    SNDCTL_COPR_RCODE: Final[int]\n    SNDCTL_COPR_RCVMSG: Final[int]\n    SNDCTL_COPR_RDATA: Final[int]\n    SNDCTL_COPR_RESET: Final[int]\n    SNDCTL_COPR_RUN: Final[int]\n    SNDCTL_COPR_SENDMSG: Final[int]\n    SNDCTL_COPR_WCODE: Final[int]\n    SNDCTL_COPR_WDATA: Final[int]\n    SNDCTL_DSP_BIND_CHANNEL: Final[int]\n    SNDCTL_DSP_CHANNELS: Final[int]\n    SNDCTL_DSP_GETBLKSIZE: Final[int]\n    SNDCTL_DSP_GETCAPS: Final[int]\n    SNDCTL_DSP_GETCHANNELMASK: Final[int]\n    SNDCTL_DSP_GETFMTS: Final[int]\n    SNDCTL_DSP_GETIPTR: Final[int]\n    SNDCTL_DSP_GETISPACE: Final[int]\n    SNDCTL_DSP_GETODELAY: Final[int]\n    SNDCTL_DSP_GETOPTR: Final[int]\n    SNDCTL_DSP_GETOSPACE: Final[int]\n    SNDCTL_DSP_GETSPDIF: Final[int]\n    SNDCTL_DSP_GETTRIGGER: Final[int]\n    SNDCTL_DSP_MAPINBUF: Final[int]\n    SNDCTL_DSP_MAPOUTBUF: Final[int]\n    SNDCTL_DSP_NONBLOCK: Final[int]\n    SNDCTL_DSP_POST: Final[int]\n    SNDCTL_DSP_PROFILE: Final[int]\n    SNDCTL_DSP_RESET: Final[int]\n    SNDCTL_DSP_SAMPLESIZE: Final[int]\n    SNDCTL_DSP_SETDUPLEX: Final[int]\n    SNDCTL_DSP_SETFMT: Final[int]\n    SNDCTL_DSP_SETFRAGMENT: Final[int]\n    SNDCTL_DSP_SETSPDIF: Final[int]\n    SNDCTL_DSP_SETSYNCRO: Final[int]\n    SNDCTL_DSP_SETTRIGGER: Final[int]\n    SNDCTL_DSP_SPEED: Final[int]\n    SNDCTL_DSP_STEREO: Final[int]\n    SNDCTL_DSP_SUBDIVIDE: Final[int]\n    SNDCTL_DSP_SYNC: Final[int]\n    SNDCTL_FM_4OP_ENABLE: Final[int]\n    SNDCTL_FM_LOAD_INSTR: Final[int]\n    SNDCTL_MIDI_INFO: Final[int]\n    SNDCTL_MIDI_MPUCMD: Final[int]\n    SNDCTL_MIDI_MPUMODE: Final[int]\n    SNDCTL_MIDI_PRETIME: Final[int]\n    SNDCTL_SEQ_CTRLRATE: Final[int]\n    SNDCTL_SEQ_GETINCOUNT: Final[int]\n    SNDCTL_SEQ_GETOUTCOUNT: Final[int]\n    SNDCTL_SEQ_GETTIME: Final[int]\n    SNDCTL_SEQ_NRMIDIS: Final[int]\n    SNDCTL_SEQ_NRSYNTHS: Final[int]\n    SNDCTL_SEQ_OUTOFBAND: Final[int]\n    SNDCTL_SEQ_PANIC: Final[int]\n    SNDCTL_SEQ_PERCMODE: Final[int]\n    SNDCTL_SEQ_RESET: Final[int]\n    SNDCTL_SEQ_RESETSAMPLES: Final[int]\n    SNDCTL_SEQ_SYNC: Final[int]\n    SNDCTL_SEQ_TESTMIDI: Final[int]\n    SNDCTL_SEQ_THRESHOLD: Final[int]\n    SNDCTL_SYNTH_CONTROL: Final[int]\n    SNDCTL_SYNTH_ID: Final[int]\n    SNDCTL_SYNTH_INFO: Final[int]\n    SNDCTL_SYNTH_MEMAVL: Final[int]\n    SNDCTL_SYNTH_REMOVESAMPLE: Final[int]\n    SNDCTL_TMR_CONTINUE: Final[int]\n    SNDCTL_TMR_METRONOME: Final[int]\n    SNDCTL_TMR_SELECT: Final[int]\n    SNDCTL_TMR_SOURCE: Final[int]\n    SNDCTL_TMR_START: Final[int]\n    SNDCTL_TMR_STOP: Final[int]\n    SNDCTL_TMR_TEMPO: Final[int]\n    SNDCTL_TMR_TIMEBASE: Final[int]\n    SOUND_MIXER_ALTPCM: Final[int]\n    SOUND_MIXER_BASS: Final[int]\n    SOUND_MIXER_CD: Final[int]\n    SOUND_MIXER_DIGITAL1: Final[int]\n    SOUND_MIXER_DIGITAL2: Final[int]\n    SOUND_MIXER_DIGITAL3: Final[int]\n    SOUND_MIXER_IGAIN: Final[int]\n    SOUND_MIXER_IMIX: Final[int]\n    SOUND_MIXER_LINE: Final[int]\n    SOUND_MIXER_LINE1: Final[int]\n    SOUND_MIXER_LINE2: Final[int]\n    SOUND_MIXER_LINE3: Final[int]\n    SOUND_MIXER_MIC: Final[int]\n    SOUND_MIXER_MONITOR: Final[int]\n    SOUND_MIXER_NRDEVICES: Final[int]\n    SOUND_MIXER_OGAIN: Final[int]\n    SOUND_MIXER_PCM: Final[int]\n    SOUND_MIXER_PHONEIN: Final[int]\n    SOUND_MIXER_PHONEOUT: Final[int]\n    SOUND_MIXER_RADIO: Final[int]\n    SOUND_MIXER_RECLEV: Final[int]\n    SOUND_MIXER_SPEAKER: Final[int]\n    SOUND_MIXER_SYNTH: Final[int]\n    SOUND_MIXER_TREBLE: Final[int]\n    SOUND_MIXER_VIDEO: Final[int]\n    SOUND_MIXER_VOLUME: Final[int]\n\n    control_labels: list[str]\n    control_names: list[str]\n\n    # TODO: oss_audio_device return type\n    @overload\n    def open(mode: Literal[\"r\", \"w\", \"rw\"]) -> Any: ...\n    @overload\n    def open(device: str, mode: Literal[\"r\", \"w\", \"rw\"]) -> Any: ...\n\n    # TODO: oss_mixer_device return type\n    def openmixer(device: str = ...) -> Any: ...\n\n    class OSSAudioError(Exception): ...\n    error = OSSAudioError\n"
  },
  {
    "path": "mypy/typeshed/stdlib/parser.pyi",
    "content": "from _typeshed import StrOrBytesPath\nfrom collections.abc import Sequence\nfrom types import CodeType\nfrom typing import Any, ClassVar, final\n\ndef expr(source: str) -> STType: ...\ndef suite(source: str) -> STType: ...\ndef sequence2st(sequence: Sequence[Any]) -> STType: ...\ndef tuple2st(sequence: Sequence[Any]) -> STType: ...\ndef st2list(st: STType, line_info: bool = False, col_info: bool = False) -> list[Any]: ...\ndef st2tuple(st: STType, line_info: bool = False, col_info: bool = False) -> tuple[Any, ...]: ...\ndef compilest(st: STType, filename: StrOrBytesPath = ...) -> CodeType: ...\ndef isexpr(st: STType) -> bool: ...\ndef issuite(st: STType) -> bool: ...\n\nclass ParserError(Exception): ...\n\n@final\nclass STType:\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def compile(self, filename: StrOrBytesPath = ...) -> CodeType: ...\n    def isexpr(self) -> bool: ...\n    def issuite(self) -> bool: ...\n    def tolist(self, line_info: bool = False, col_info: bool = False) -> list[Any]: ...\n    def totuple(self, line_info: bool = False, col_info: bool = False) -> tuple[Any, ...]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pathlib/__init__.pyi",
    "content": "import sys\nimport types\nfrom _typeshed import (\n    OpenBinaryMode,\n    OpenBinaryModeReading,\n    OpenBinaryModeUpdating,\n    OpenBinaryModeWriting,\n    OpenTextMode,\n    ReadableBuffer,\n    StrOrBytesPath,\n    StrPath,\n    Unused,\n)\nfrom collections.abc import Callable, Generator, Iterator, Sequence\nfrom io import BufferedRandom, BufferedReader, BufferedWriter, FileIO, TextIOWrapper\nfrom os import PathLike, stat_result\nfrom types import GenericAlias, TracebackType\nfrom typing import IO, Any, BinaryIO, ClassVar, Literal, TypeVar, overload\nfrom typing_extensions import Never, Self, deprecated\n\n_PathT = TypeVar(\"_PathT\", bound=PurePath)\n\n__all__ = [\"PurePath\", \"PurePosixPath\", \"PureWindowsPath\", \"Path\", \"PosixPath\", \"WindowsPath\"]\n\nif sys.version_info >= (3, 14):\n    from pathlib.types import PathInfo\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"UnsupportedOperation\"]\n\nclass PurePath(PathLike[str]):\n    if sys.version_info >= (3, 13):\n        __slots__ = (\n            \"_raw_paths\",\n            \"_drv\",\n            \"_root\",\n            \"_tail_cached\",\n            \"_str\",\n            \"_str_normcase_cached\",\n            \"_parts_normcase_cached\",\n            \"_hash\",\n        )\n    elif sys.version_info >= (3, 12):\n        __slots__ = (\n            \"_raw_paths\",\n            \"_drv\",\n            \"_root\",\n            \"_tail_cached\",\n            \"_str\",\n            \"_str_normcase_cached\",\n            \"_parts_normcase_cached\",\n            \"_lines_cached\",\n            \"_hash\",\n        )\n    else:\n        __slots__ = (\"_drv\", \"_root\", \"_parts\", \"_str\", \"_hash\", \"_pparts\", \"_cached_cparts\")\n    if sys.version_info >= (3, 13):\n        parser: ClassVar[types.ModuleType]\n        def full_match(self, pattern: StrPath, *, case_sensitive: bool | None = None) -> bool: ...\n\n    @property\n    def parts(self) -> tuple[str, ...]: ...\n    @property\n    def drive(self) -> str: ...\n    @property\n    def root(self) -> str: ...\n    @property\n    def anchor(self) -> str: ...\n    @property\n    def name(self) -> str: ...\n    @property\n    def suffix(self) -> str: ...\n    @property\n    def suffixes(self) -> list[str]: ...\n    @property\n    def stem(self) -> str: ...\n    if sys.version_info >= (3, 12):\n        def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ...\n        def __init__(self, *args: StrPath) -> None: ...  # pyright: ignore[reportInconsistentConstructor]\n    else:\n        def __new__(cls, *args: StrPath) -> Self: ...\n\n    def __hash__(self) -> int: ...\n    def __fspath__(self) -> str: ...\n    def __lt__(self, other: PurePath) -> bool: ...\n    def __le__(self, other: PurePath) -> bool: ...\n    def __gt__(self, other: PurePath) -> bool: ...\n    def __ge__(self, other: PurePath) -> bool: ...\n    def __truediv__(self, key: StrPath) -> Self: ...\n    def __rtruediv__(self, key: StrPath) -> Self: ...\n    def __bytes__(self) -> bytes: ...\n    def as_posix(self) -> str: ...\n    @deprecated(\"Deprecated since Python 3.14; will be removed in Python 3.19. Use `Path.as_uri()` instead.\")\n    def as_uri(self) -> str: ...\n    def is_absolute(self) -> bool: ...\n    if sys.version_info >= (3, 13):\n        @deprecated(\n            \"Deprecated since Python 3.13; will be removed in Python 3.15. \"\n            \"Use `os.path.isreserved()` to detect reserved paths on Windows.\"\n        )\n        def is_reserved(self) -> bool: ...\n    else:\n        def is_reserved(self) -> bool: ...\n    if sys.version_info >= (3, 14):\n        def is_relative_to(self, other: StrPath) -> bool: ...\n    elif sys.version_info >= (3, 12):\n        @overload\n        def is_relative_to(self, other: StrPath, /) -> bool: ...\n        @overload\n        @deprecated(\"Passing additional arguments is deprecated since Python 3.12; removed in Python 3.14.\")\n        def is_relative_to(self, other: StrPath, /, *_deprecated: StrPath) -> bool: ...\n    else:\n        def is_relative_to(self, *other: StrPath) -> bool: ...\n\n    if sys.version_info >= (3, 12):\n        def match(self, path_pattern: str, *, case_sensitive: bool | None = None) -> bool: ...\n    else:\n        def match(self, path_pattern: str) -> bool: ...\n\n    if sys.version_info >= (3, 14):\n        def relative_to(self, other: StrPath, *, walk_up: bool = False) -> Self: ...\n    elif sys.version_info >= (3, 12):\n        @overload\n        def relative_to(self, other: StrPath, /, *, walk_up: bool = False) -> Self: ...\n        @overload\n        @deprecated(\"Passing additional arguments is deprecated since Python 3.12; removed in Python 3.14.\")\n        def relative_to(self, other: StrPath, /, *_deprecated: StrPath, walk_up: bool = False) -> Self: ...\n    else:\n        def relative_to(self, *other: StrPath) -> Self: ...\n\n    def with_name(self, name: str) -> Self: ...\n    def with_stem(self, stem: str) -> Self: ...\n    def with_suffix(self, suffix: str) -> Self: ...\n    def joinpath(self, *other: StrPath) -> Self: ...\n    @property\n    def parents(self) -> Sequence[Self]: ...\n    @property\n    def parent(self) -> Self: ...\n    if sys.version_info < (3, 11):\n        def __class_getitem__(cls, type: Any) -> GenericAlias: ...\n\n    if sys.version_info >= (3, 12):\n        def with_segments(self, *args: StrPath) -> Self: ...\n\nclass PurePosixPath(PurePath):\n    __slots__ = ()\n\nclass PureWindowsPath(PurePath):\n    __slots__ = ()\n\nclass Path(PurePath):\n    if sys.version_info >= (3, 14):\n        __slots__ = (\"_info\",)\n    elif sys.version_info >= (3, 10):\n        __slots__ = ()\n    else:\n        __slots__ = (\"_accessor\",)\n\n    if sys.version_info >= (3, 12):\n        def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ...  # pyright: ignore[reportInconsistentConstructor]\n    else:\n        def __new__(cls, *args: StrPath, **kwargs: Unused) -> Self: ...\n\n    @classmethod\n    def cwd(cls) -> Self: ...\n    if sys.version_info >= (3, 10):\n        def stat(self, *, follow_symlinks: bool = True) -> stat_result: ...\n        def chmod(self, mode: int, *, follow_symlinks: bool = True) -> None: ...\n    else:\n        def stat(self) -> stat_result: ...\n        def chmod(self, mode: int) -> None: ...\n\n    if sys.version_info >= (3, 13):\n        @classmethod\n        def from_uri(cls, uri: str) -> Self: ...\n        def is_dir(self, *, follow_symlinks: bool = True) -> bool: ...\n        def is_file(self, *, follow_symlinks: bool = True) -> bool: ...\n        def read_text(self, encoding: str | None = None, errors: str | None = None, newline: str | None = None) -> str: ...\n    else:\n        def __enter__(self) -> Self: ...\n        def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ...\n        def is_dir(self) -> bool: ...\n        def is_file(self) -> bool: ...\n        def read_text(self, encoding: str | None = None, errors: str | None = None) -> str: ...\n\n    if sys.version_info >= (3, 13):\n        def glob(self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False) -> Iterator[Self]: ...\n        def rglob(\n            self, pattern: str, *, case_sensitive: bool | None = None, recurse_symlinks: bool = False\n        ) -> Iterator[Self]: ...\n    elif sys.version_info >= (3, 12):\n        def glob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ...\n        def rglob(self, pattern: str, *, case_sensitive: bool | None = None) -> Generator[Self, None, None]: ...\n    else:\n        def glob(self, pattern: str) -> Generator[Self, None, None]: ...\n        def rglob(self, pattern: str) -> Generator[Self, None, None]: ...\n\n    if sys.version_info >= (3, 12):\n        def exists(self, *, follow_symlinks: bool = True) -> bool: ...\n    else:\n        def exists(self) -> bool: ...\n\n    def is_symlink(self) -> bool: ...\n    def is_socket(self) -> bool: ...\n    def is_fifo(self) -> bool: ...\n    def is_block_device(self) -> bool: ...\n    def is_char_device(self) -> bool: ...\n    if sys.version_info >= (3, 12):\n        def is_junction(self) -> bool: ...\n\n    def iterdir(self) -> Generator[Self, None, None]: ...\n    def lchmod(self, mode: int) -> None: ...\n    def lstat(self) -> stat_result: ...\n    def mkdir(self, mode: int = 0o777, parents: bool = False, exist_ok: bool = False) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        @property\n        def info(self) -> PathInfo: ...\n        @overload\n        def move_into(self, target_dir: _PathT) -> _PathT: ...  # type: ignore[overload-overlap]\n        @overload\n        def move_into(self, target_dir: StrPath) -> Self: ...  # type: ignore[overload-overlap]\n        @overload\n        def move(self, target: _PathT) -> _PathT: ...  # type: ignore[overload-overlap]\n        @overload\n        def move(self, target: StrPath) -> Self: ...  # type: ignore[overload-overlap]\n        @overload\n        def copy_into(self, target_dir: _PathT, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> _PathT: ...  # type: ignore[overload-overlap]\n        @overload\n        def copy_into(self, target_dir: StrPath, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> Self: ...  # type: ignore[overload-overlap]\n        @overload\n        def copy(self, target: _PathT, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> _PathT: ...  # type: ignore[overload-overlap]\n        @overload\n        def copy(self, target: StrPath, *, follow_symlinks: bool = True, preserve_metadata: bool = False) -> Self: ...  # type: ignore[overload-overlap]\n\n    # Adapted from builtins.open\n    # Text mode: always returns a TextIOWrapper\n    # The Traversable .open in stdlib/importlib/abc.pyi should be kept in sync with this.\n    @overload\n    def open(\n        self,\n        mode: OpenTextMode = \"r\",\n        buffering: int = -1,\n        encoding: str | None = None,\n        errors: str | None = None,\n        newline: str | None = None,\n    ) -> TextIOWrapper: ...\n    # Unbuffered binary mode: returns a FileIO\n    @overload\n    def open(\n        self, mode: OpenBinaryMode, buffering: Literal[0], encoding: None = None, errors: None = None, newline: None = None\n    ) -> FileIO: ...\n    # Buffering is on: return BufferedRandom, BufferedReader, or BufferedWriter\n    @overload\n    def open(\n        self,\n        mode: OpenBinaryModeUpdating,\n        buffering: Literal[-1, 1] = -1,\n        encoding: None = None,\n        errors: None = None,\n        newline: None = None,\n    ) -> BufferedRandom: ...\n    @overload\n    def open(\n        self,\n        mode: OpenBinaryModeWriting,\n        buffering: Literal[-1, 1] = -1,\n        encoding: None = None,\n        errors: None = None,\n        newline: None = None,\n    ) -> BufferedWriter: ...\n    @overload\n    def open(\n        self,\n        mode: OpenBinaryModeReading,\n        buffering: Literal[-1, 1] = -1,\n        encoding: None = None,\n        errors: None = None,\n        newline: None = None,\n    ) -> BufferedReader: ...\n    # Buffering cannot be determined: fall back to BinaryIO\n    @overload\n    def open(\n        self, mode: OpenBinaryMode, buffering: int = -1, encoding: None = None, errors: None = None, newline: None = None\n    ) -> BinaryIO: ...\n    # Fallback if mode is not specified\n    @overload\n    def open(\n        self, mode: str, buffering: int = -1, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n    ) -> IO[Any]: ...\n\n    # These methods do \"exist\" on Windows, but they always raise NotImplementedError.\n    if sys.platform == \"win32\":\n        if sys.version_info >= (3, 13):\n            # raises UnsupportedOperation:\n            def owner(self: Never, *, follow_symlinks: bool = True) -> str: ...  # type: ignore[misc]\n            def group(self: Never, *, follow_symlinks: bool = True) -> str: ...  # type: ignore[misc]\n        else:\n            def owner(self: Never) -> str: ...  # type: ignore[misc]\n            def group(self: Never) -> str: ...  # type: ignore[misc]\n    else:\n        if sys.version_info >= (3, 13):\n            def owner(self, *, follow_symlinks: bool = True) -> str: ...\n            def group(self, *, follow_symlinks: bool = True) -> str: ...\n        else:\n            def owner(self) -> str: ...\n            def group(self) -> str: ...\n\n    # This method does \"exist\" on Windows on <3.12, but always raises NotImplementedError\n    # On py312+, it works properly on Windows, as with all other platforms\n    if sys.platform == \"win32\" and sys.version_info < (3, 12):\n        def is_mount(self: Never) -> bool: ...  # type: ignore[misc]\n    else:\n        def is_mount(self) -> bool: ...\n\n    def readlink(self) -> Self: ...\n\n    if sys.version_info >= (3, 10):\n        def rename(self, target: StrPath) -> Self: ...\n        def replace(self, target: StrPath) -> Self: ...\n    else:\n        def rename(self, target: str | PurePath) -> Self: ...\n        def replace(self, target: str | PurePath) -> Self: ...\n\n    def resolve(self, strict: bool = False) -> Self: ...\n    def rmdir(self) -> None: ...\n    def symlink_to(self, target: StrOrBytesPath, target_is_directory: bool = False) -> None: ...\n    if sys.version_info >= (3, 10):\n        def hardlink_to(self, target: StrOrBytesPath) -> None: ...\n\n    def touch(self, mode: int = 0o666, exist_ok: bool = True) -> None: ...\n    def unlink(self, missing_ok: bool = False) -> None: ...\n    @classmethod\n    def home(cls) -> Self: ...\n    def absolute(self) -> Self: ...\n    def expanduser(self) -> Self: ...\n    def read_bytes(self) -> bytes: ...\n    def samefile(self, other_path: StrPath) -> bool: ...\n    def write_bytes(self, data: ReadableBuffer) -> int: ...\n    if sys.version_info >= (3, 10):\n        def write_text(\n            self, data: str, encoding: str | None = None, errors: str | None = None, newline: str | None = None\n        ) -> int: ...\n    else:\n        def write_text(self, data: str, encoding: str | None = None, errors: str | None = None) -> int: ...\n    if sys.version_info < (3, 12):\n        if sys.version_info >= (3, 10):\n            @deprecated(\"Deprecated since Python 3.10; removed in Python 3.12. Use `hardlink_to()` instead.\")\n            def link_to(self, target: StrOrBytesPath) -> None: ...\n        else:\n            def link_to(self, target: StrOrBytesPath) -> None: ...\n    if sys.version_info >= (3, 12):\n        def walk(\n            self, top_down: bool = True, on_error: Callable[[OSError], object] | None = None, follow_symlinks: bool = False\n        ) -> Iterator[tuple[Self, list[str], list[str]]]: ...\n\n    def as_uri(self) -> str: ...\n\nclass PosixPath(Path, PurePosixPath):\n    __slots__ = ()\n\nclass WindowsPath(Path, PureWindowsPath):\n    __slots__ = ()\n\nif sys.version_info >= (3, 13):\n    class UnsupportedOperation(NotImplementedError): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pathlib/types.pyi",
    "content": "from typing import Protocol, runtime_checkable\n\n@runtime_checkable\nclass PathInfo(Protocol):\n    def exists(self, *, follow_symlinks: bool = True) -> bool: ...\n    def is_dir(self, *, follow_symlinks: bool = True) -> bool: ...\n    def is_file(self, *, follow_symlinks: bool = True) -> bool: ...\n    def is_symlink(self) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pdb.pyi",
    "content": "import signal\nimport sys\nfrom bdb import Bdb, _Backend\nfrom cmd import Cmd\nfrom collections.abc import Callable, Iterable, Mapping, Sequence\nfrom inspect import _SourceObjectType\nfrom linecache import _ModuleGlobals\nfrom rlcompleter import Completer\nfrom types import CodeType, FrameType, TracebackType\nfrom typing import IO, Any, ClassVar, Final, Literal, TypeVar\nfrom typing_extensions import ParamSpec, Self, TypeAlias, deprecated\n\n__all__ = [\"run\", \"pm\", \"Pdb\", \"runeval\", \"runctx\", \"runcall\", \"set_trace\", \"post_mortem\", \"help\"]\nif sys.version_info >= (3, 14):\n    __all__ += [\"set_default_backend\", \"get_default_backend\"]\n\n_T = TypeVar(\"_T\")\n_P = ParamSpec(\"_P\")\n_Mode: TypeAlias = Literal[\"inline\", \"cli\"]\n\nline_prefix: Final[str]  # undocumented\n\nclass Restart(Exception): ...\n\ndef run(statement: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> None: ...\ndef runeval(expression: str, globals: dict[str, Any] | None = None, locals: Mapping[str, Any] | None = None) -> Any: ...\ndef runctx(statement: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> None: ...\ndef runcall(func: Callable[_P, _T], *args: _P.args, **kwds: _P.kwargs) -> _T | None: ...\n\nif sys.version_info >= (3, 14):\n    def set_default_backend(backend: _Backend) -> None: ...\n    def get_default_backend() -> _Backend: ...\n    def set_trace(*, header: str | None = None, commands: Iterable[str] | None = None) -> None: ...\n    async def set_trace_async(*, header: str | None = None, commands: Iterable[str] | None = None) -> None: ...\n\nelse:\n    def set_trace(*, header: str | None = None) -> None: ...\n\ndef post_mortem(t: TracebackType | None = None) -> None: ...\ndef pm() -> None: ...\n\nclass Pdb(Bdb, Cmd):\n    # Everything here is undocumented, except for __init__\n\n    commands_resuming: ClassVar[list[str]]\n\n    if sys.version_info >= (3, 13):\n        MAX_CHAINED_EXCEPTION_DEPTH: Final = 999\n\n    aliases: dict[str, str]\n    mainpyfile: str\n    _wait_for_mainpyfile: bool\n    rcLines: list[str]\n    commands: dict[int, list[str]]\n    commands_doprompt: dict[int, bool]\n    commands_silent: dict[int, bool]\n    commands_defining: bool\n    commands_bnum: int | None\n    lineno: int | None\n    stack: list[tuple[FrameType, int]]\n    curindex: int\n    curframe: FrameType | None\n    if sys.version_info >= (3, 13):\n        @property\n        @deprecated(\"The frame locals reference is no longer cached. Use 'curframe.f_locals' instead.\")\n        def curframe_locals(self) -> Mapping[str, Any]: ...\n        @curframe_locals.setter\n        @deprecated(\n            \"Setting 'curframe_locals' no longer has any effect as of 3.14. Update the contents of 'curframe.f_locals' instead.\"\n        )\n        def curframe_locals(self, value: Mapping[str, Any]) -> None: ...\n    else:\n        curframe_locals: Mapping[str, Any]\n    if sys.version_info >= (3, 14):\n        mode: _Mode | None\n        colorize: bool\n        def __init__(\n            self,\n            completekey: str = \"tab\",\n            stdin: IO[str] | None = None,\n            stdout: IO[str] | None = None,\n            skip: Iterable[str] | None = None,\n            nosigint: bool = False,\n            readrc: bool = True,\n            mode: _Mode | None = None,\n            backend: _Backend | None = None,\n            colorize: bool = False,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            completekey: str = \"tab\",\n            stdin: IO[str] | None = None,\n            stdout: IO[str] | None = None,\n            skip: Iterable[str] | None = None,\n            nosigint: bool = False,\n            readrc: bool = True,\n        ) -> None: ...\n    if sys.version_info >= (3, 14):\n        def set_trace(self, frame: FrameType | None = None, *, commands: Iterable[str] | None = None) -> None: ...\n        async def set_trace_async(self, frame: FrameType | None = None, *, commands: Iterable[str] | None = None) -> None: ...\n\n    def forget(self) -> None: ...\n    def setup(self, f: FrameType | None, tb: TracebackType | None) -> None: ...\n    if sys.version_info < (3, 11):\n        def execRcLines(self) -> None: ...\n\n    if sys.version_info >= (3, 13):\n        user_opcode = Bdb.user_line\n\n    def bp_commands(self, frame: FrameType) -> bool: ...\n\n    if sys.version_info >= (3, 13):\n        def interaction(self, frame: FrameType | None, tb_or_exc: TracebackType | BaseException | None) -> None: ...\n    else:\n        def interaction(self, frame: FrameType | None, traceback: TracebackType | None) -> None: ...\n\n    def displayhook(self, obj: object) -> None: ...\n    def handle_command_def(self, line: str) -> bool: ...\n    def defaultFile(self) -> str: ...\n    def lineinfo(self, identifier: str) -> tuple[None, None, None] | tuple[str, str, int]: ...\n    if sys.version_info >= (3, 14):\n        def checkline(self, filename: str, lineno: int, module_globals: _ModuleGlobals | None = None) -> int: ...\n    else:\n        def checkline(self, filename: str, lineno: int) -> int: ...\n\n    def _getval(self, arg: str) -> object: ...\n    if sys.version_info >= (3, 14):\n        def print_stack_trace(self, count: int | None = None) -> None: ...\n    else:\n        def print_stack_trace(self) -> None: ...\n\n    def print_stack_entry(self, frame_lineno: tuple[FrameType, int], prompt_prefix: str = \"\\n-> \") -> None: ...\n    def lookupmodule(self, filename: str) -> str | None: ...\n    if sys.version_info < (3, 11):\n        def _runscript(self, filename: str) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def complete_multiline_names(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ...\n\n    if sys.version_info >= (3, 13):\n        def completedefault(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ...\n\n    def do_commands(self, arg: str) -> bool | None: ...\n    if sys.version_info >= (3, 14):\n        def do_break(self, arg: str, temporary: bool = False) -> bool | None: ...\n    else:\n        def do_break(self, arg: str, temporary: bool | Literal[0, 1] = 0) -> bool | None: ...\n\n    def do_tbreak(self, arg: str) -> bool | None: ...\n    def do_enable(self, arg: str) -> bool | None: ...\n    def do_disable(self, arg: str) -> bool | None: ...\n    def do_condition(self, arg: str) -> bool | None: ...\n    def do_ignore(self, arg: str) -> bool | None: ...\n    def do_clear(self, arg: str) -> bool | None: ...\n    def do_where(self, arg: str) -> bool | None: ...\n    if sys.version_info >= (3, 13):\n        def do_exceptions(self, arg: str) -> bool | None: ...\n\n    def do_up(self, arg: str) -> bool | None: ...\n    def do_down(self, arg: str) -> bool | None: ...\n    def do_until(self, arg: str) -> bool | None: ...\n    def do_step(self, arg: str) -> bool | None: ...\n    def do_next(self, arg: str) -> bool | None: ...\n    def do_run(self, arg: str) -> bool | None: ...\n    def do_return(self, arg: str) -> bool | None: ...\n    def do_continue(self, arg: str) -> bool | None: ...\n    def do_jump(self, arg: str) -> bool | None: ...\n    def do_debug(self, arg: str) -> bool | None: ...\n    def do_quit(self, arg: str) -> bool | None: ...\n    def do_EOF(self, arg: str) -> bool | None: ...\n    def do_args(self, arg: str) -> bool | None: ...\n    def do_retval(self, arg: str) -> bool | None: ...\n    def do_p(self, arg: str) -> bool | None: ...\n    def do_pp(self, arg: str) -> bool | None: ...\n    def do_list(self, arg: str) -> bool | None: ...\n    def do_whatis(self, arg: str) -> bool | None: ...\n    def do_alias(self, arg: str) -> bool | None: ...\n    def do_unalias(self, arg: str) -> bool | None: ...\n    def do_help(self, arg: str) -> bool | None: ...\n    do_b = do_break\n    do_cl = do_clear\n    do_w = do_where\n    do_bt = do_where\n    do_u = do_up\n    do_d = do_down\n    do_unt = do_until\n    do_s = do_step\n    do_n = do_next\n    do_restart = do_run\n    do_r = do_return\n    do_c = do_continue\n    do_cont = do_continue\n    do_j = do_jump\n    do_q = do_quit\n    do_exit = do_quit\n    do_a = do_args\n    do_rv = do_retval\n    do_l = do_list\n    do_h = do_help\n    def help_exec(self) -> None: ...\n    def help_pdb(self) -> None: ...\n    def sigint_handler(self, signum: signal.Signals, frame: FrameType) -> None: ...\n    if sys.version_info >= (3, 13):\n        def message(self, msg: str, end: str = \"\\n\") -> None: ...\n    else:\n        def message(self, msg: str) -> None: ...\n\n    def error(self, msg: str) -> None: ...\n    if sys.version_info >= (3, 13):\n        def completenames(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ...  # type: ignore[override]\n    if sys.version_info >= (3, 12):\n        def set_convenience_variable(self, frame: FrameType, name: str, value: Any) -> None: ...\n    if sys.version_info >= (3, 13):\n        # Added in 3.13.8 and 3.14.1\n        @property\n        def rlcompleter(self) -> type[Completer]: ...\n\n    def _select_frame(self, number: int) -> None: ...\n    def _getval_except(self, arg: str, frame: FrameType | None = None) -> object: ...\n    def _print_lines(\n        self, lines: Sequence[str], start: int, breaks: Sequence[int] = (), frame: FrameType | None = None\n    ) -> None: ...\n    def _cmdloop(self) -> None: ...\n    def do_display(self, arg: str) -> bool | None: ...\n    def do_interact(self, arg: str) -> bool | None: ...\n    def do_longlist(self, arg: str) -> bool | None: ...\n    def do_source(self, arg: str) -> bool | None: ...\n    def do_undisplay(self, arg: str) -> bool | None: ...\n    do_ll = do_longlist\n    def _complete_location(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ...\n    def _complete_bpnumber(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ...\n    def _complete_expression(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ...\n    def complete_undisplay(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ...\n    def complete_unalias(self, text: str, line: str, begidx: int, endidx: int) -> list[str]: ...\n    complete_commands = _complete_bpnumber\n    complete_break = _complete_location\n    complete_b = _complete_location\n    complete_tbreak = _complete_location\n    complete_enable = _complete_bpnumber\n    complete_disable = _complete_bpnumber\n    complete_condition = _complete_bpnumber\n    complete_ignore = _complete_bpnumber\n    complete_clear = _complete_location\n    complete_cl = _complete_location\n    complete_debug = _complete_expression\n    complete_print = _complete_expression\n    complete_p = _complete_expression\n    complete_pp = _complete_expression\n    complete_source = _complete_expression\n    complete_whatis = _complete_expression\n    complete_display = _complete_expression\n\n    if sys.version_info < (3, 11):\n        def _runmodule(self, module_name: str) -> None: ...\n\n# undocumented\n\ndef find_function(funcname: str, filename: str) -> tuple[str, str, int] | None: ...\ndef main() -> None: ...\ndef help() -> None: ...\n\nif sys.version_info < (3, 10):\n    def getsourcelines(obj: _SourceObjectType) -> tuple[list[str], int]: ...\n\ndef lasti2lineno(code: CodeType, lasti: int) -> int: ...\n\nclass _rstr(str):\n    def __repr__(self) -> Self: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pickle.pyi",
    "content": "import sys\nfrom _pickle import (\n    PickleError as PickleError,\n    Pickler as Pickler,\n    PicklingError as PicklingError,\n    Unpickler as Unpickler,\n    UnpicklingError as UnpicklingError,\n    _BufferCallback,\n    _ReadableFileobj,\n    _ReducedType,\n    dump as dump,\n    dumps as dumps,\n    load as load,\n    loads as loads,\n)\nfrom _typeshed import ReadableBuffer, SupportsWrite\nfrom collections.abc import Callable, Iterable, Mapping\nfrom typing import Any, ClassVar, Final, SupportsBytes, SupportsIndex, final\nfrom typing_extensions import Self\n\n__all__ = [\n    \"PickleBuffer\",\n    \"PickleError\",\n    \"PicklingError\",\n    \"UnpicklingError\",\n    \"Pickler\",\n    \"Unpickler\",\n    \"dump\",\n    \"dumps\",\n    \"load\",\n    \"loads\",\n    \"ADDITEMS\",\n    \"APPEND\",\n    \"APPENDS\",\n    \"BINBYTES\",\n    \"BINBYTES8\",\n    \"BINFLOAT\",\n    \"BINGET\",\n    \"BININT\",\n    \"BININT1\",\n    \"BININT2\",\n    \"BINPERSID\",\n    \"BINPUT\",\n    \"BINSTRING\",\n    \"BINUNICODE\",\n    \"BINUNICODE8\",\n    \"BUILD\",\n    \"BYTEARRAY8\",\n    \"DEFAULT_PROTOCOL\",\n    \"DICT\",\n    \"DUP\",\n    \"EMPTY_DICT\",\n    \"EMPTY_LIST\",\n    \"EMPTY_SET\",\n    \"EMPTY_TUPLE\",\n    \"EXT1\",\n    \"EXT2\",\n    \"EXT4\",\n    \"FALSE\",\n    \"FLOAT\",\n    \"FRAME\",\n    \"FROZENSET\",\n    \"GET\",\n    \"GLOBAL\",\n    \"HIGHEST_PROTOCOL\",\n    \"INST\",\n    \"INT\",\n    \"LIST\",\n    \"LONG\",\n    \"LONG1\",\n    \"LONG4\",\n    \"LONG_BINGET\",\n    \"LONG_BINPUT\",\n    \"MARK\",\n    \"MEMOIZE\",\n    \"NEWFALSE\",\n    \"NEWOBJ\",\n    \"NEWOBJ_EX\",\n    \"NEWTRUE\",\n    \"NEXT_BUFFER\",\n    \"NONE\",\n    \"OBJ\",\n    \"PERSID\",\n    \"POP\",\n    \"POP_MARK\",\n    \"PROTO\",\n    \"PUT\",\n    \"READONLY_BUFFER\",\n    \"REDUCE\",\n    \"SETITEM\",\n    \"SETITEMS\",\n    \"SHORT_BINBYTES\",\n    \"SHORT_BINSTRING\",\n    \"SHORT_BINUNICODE\",\n    \"STACK_GLOBAL\",\n    \"STOP\",\n    \"STRING\",\n    \"TRUE\",\n    \"TUPLE\",\n    \"TUPLE1\",\n    \"TUPLE2\",\n    \"TUPLE3\",\n    \"UNICODE\",\n]\n\nHIGHEST_PROTOCOL: Final = 5\nif sys.version_info >= (3, 14):\n    DEFAULT_PROTOCOL: Final = 5\nelse:\n    DEFAULT_PROTOCOL: Final = 4\n\nbytes_types: tuple[type[Any], ...]  # undocumented\n\n@final\nclass PickleBuffer:\n    def __new__(cls, buffer: ReadableBuffer) -> Self: ...\n    def raw(self) -> memoryview: ...\n    def release(self) -> None: ...\n    def __buffer__(self, flags: int, /) -> memoryview: ...\n    def __release_buffer__(self, buffer: memoryview, /) -> None: ...\n\nMARK: Final = b\"(\"\nSTOP: Final = b\".\"\nPOP: Final = b\"0\"\nPOP_MARK: Final = b\"1\"\nDUP: Final = b\"2\"\nFLOAT: Final = b\"F\"\nINT: Final = b\"I\"\nBININT: Final = b\"J\"\nBININT1: Final = b\"K\"\nLONG: Final = b\"L\"\nBININT2: Final = b\"M\"\nNONE: Final = b\"N\"\nPERSID: Final = b\"P\"\nBINPERSID: Final = b\"Q\"\nREDUCE: Final = b\"R\"\nSTRING: Final = b\"S\"\nBINSTRING: Final = b\"T\"\nSHORT_BINSTRING: Final = b\"U\"\nUNICODE: Final = b\"V\"\nBINUNICODE: Final = b\"X\"\nAPPEND: Final = b\"a\"\nBUILD: Final = b\"b\"\nGLOBAL: Final = b\"c\"\nDICT: Final = b\"d\"\nEMPTY_DICT: Final = b\"}\"\nAPPENDS: Final = b\"e\"\nGET: Final = b\"g\"\nBINGET: Final = b\"h\"\nINST: Final = b\"i\"\nLONG_BINGET: Final = b\"j\"\nLIST: Final = b\"l\"\nEMPTY_LIST: Final = b\"]\"\nOBJ: Final = b\"o\"\nPUT: Final = b\"p\"\nBINPUT: Final = b\"q\"\nLONG_BINPUT: Final = b\"r\"\nSETITEM: Final = b\"s\"\nTUPLE: Final = b\"t\"\nEMPTY_TUPLE: Final = b\")\"\nSETITEMS: Final = b\"u\"\nBINFLOAT: Final = b\"G\"\n\nTRUE: Final = b\"I01\\n\"\nFALSE: Final = b\"I00\\n\"\n\n# protocol 2\nPROTO: Final = b\"\\x80\"\nNEWOBJ: Final = b\"\\x81\"\nEXT1: Final = b\"\\x82\"\nEXT2: Final = b\"\\x83\"\nEXT4: Final = b\"\\x84\"\nTUPLE1: Final = b\"\\x85\"\nTUPLE2: Final = b\"\\x86\"\nTUPLE3: Final = b\"\\x87\"\nNEWTRUE: Final = b\"\\x88\"\nNEWFALSE: Final = b\"\\x89\"\nLONG1: Final = b\"\\x8a\"\nLONG4: Final = b\"\\x8b\"\n\n# protocol 3\nBINBYTES: Final = b\"B\"\nSHORT_BINBYTES: Final = b\"C\"\n\n# protocol 4\nSHORT_BINUNICODE: Final = b\"\\x8c\"\nBINUNICODE8: Final = b\"\\x8d\"\nBINBYTES8: Final = b\"\\x8e\"\nEMPTY_SET: Final = b\"\\x8f\"\nADDITEMS: Final = b\"\\x90\"\nFROZENSET: Final = b\"\\x91\"\nNEWOBJ_EX: Final = b\"\\x92\"\nSTACK_GLOBAL: Final = b\"\\x93\"\nMEMOIZE: Final = b\"\\x94\"\nFRAME: Final = b\"\\x95\"\n\n# protocol 5\nBYTEARRAY8: Final = b\"\\x96\"\nNEXT_BUFFER: Final = b\"\\x97\"\nREADONLY_BUFFER: Final = b\"\\x98\"\n\ndef encode_long(x: int) -> bytes: ...  # undocumented\ndef decode_long(data: Iterable[SupportsIndex] | SupportsBytes | ReadableBuffer) -> int: ...  # undocumented\n\n# undocumented pure-Python implementations\nclass _Pickler:\n    fast: bool\n    dispatch_table: Mapping[type, Callable[[Any], _ReducedType]]\n    bin: bool  # undocumented\n    dispatch: ClassVar[dict[type, Callable[[Unpickler, Any], None]]]  # undocumented, _Pickler only\n    reducer_override: Callable[[Any], Any]\n    def __init__(\n        self,\n        file: SupportsWrite[bytes],\n        protocol: int | None = None,\n        *,\n        fix_imports: bool = True,\n        buffer_callback: _BufferCallback = None,\n    ) -> None: ...\n    def dump(self, obj: Any) -> None: ...\n    def clear_memo(self) -> None: ...\n    def persistent_id(self, obj: Any) -> Any: ...\n\nclass _Unpickler:\n    dispatch: ClassVar[dict[int, Callable[[Unpickler], None]]]  # undocumented, _Unpickler only\n    def __init__(\n        self,\n        file: _ReadableFileobj,\n        *,\n        fix_imports: bool = True,\n        encoding: str = \"ASCII\",\n        errors: str = \"strict\",\n        buffers: Iterable[Any] | None = None,\n    ) -> None: ...\n    def load(self) -> Any: ...\n    def find_class(self, module: str, name: str) -> Any: ...\n    def persistent_load(self, pid: Any) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pickletools.pyi",
    "content": "import sys\nfrom collections.abc import Callable, Iterator, MutableMapping\nfrom typing import IO, Any, Final\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"dis\", \"genops\", \"optimize\"]\n\n_Reader: TypeAlias = Callable[[IO[bytes]], Any]\nbytes_types: tuple[type[Any], ...]\n\nUP_TO_NEWLINE: Final = -1\nTAKEN_FROM_ARGUMENT1: Final = -2\nTAKEN_FROM_ARGUMENT4: Final = -3\nTAKEN_FROM_ARGUMENT4U: Final = -4\nTAKEN_FROM_ARGUMENT8U: Final = -5\n\nclass ArgumentDescriptor:\n    __slots__ = (\"name\", \"n\", \"reader\", \"doc\")\n    name: str\n    n: int\n    reader: _Reader\n    doc: str\n    def __init__(self, name: str, n: int, reader: _Reader, doc: str) -> None: ...\n\ndef read_uint1(f: IO[bytes]) -> int: ...\n\nuint1: ArgumentDescriptor\n\ndef read_uint2(f: IO[bytes]) -> int: ...\n\nuint2: ArgumentDescriptor\n\ndef read_int4(f: IO[bytes]) -> int: ...\n\nint4: ArgumentDescriptor\n\ndef read_uint4(f: IO[bytes]) -> int: ...\n\nuint4: ArgumentDescriptor\n\ndef read_uint8(f: IO[bytes]) -> int: ...\n\nuint8: ArgumentDescriptor\n\nif sys.version_info >= (3, 12):\n    def read_stringnl(\n        f: IO[bytes], decode: bool = True, stripquotes: bool = True, *, encoding: str = \"latin-1\"\n    ) -> bytes | str: ...\n\nelse:\n    def read_stringnl(f: IO[bytes], decode: bool = True, stripquotes: bool = True) -> bytes | str: ...\n\nstringnl: ArgumentDescriptor\n\ndef read_stringnl_noescape(f: IO[bytes]) -> str: ...\n\nstringnl_noescape: ArgumentDescriptor\n\ndef read_stringnl_noescape_pair(f: IO[bytes]) -> str: ...\n\nstringnl_noescape_pair: ArgumentDescriptor\n\ndef read_string1(f: IO[bytes]) -> str: ...\n\nstring1: ArgumentDescriptor\n\ndef read_string4(f: IO[bytes]) -> str: ...\n\nstring4: ArgumentDescriptor\n\ndef read_bytes1(f: IO[bytes]) -> bytes: ...\n\nbytes1: ArgumentDescriptor\n\ndef read_bytes4(f: IO[bytes]) -> bytes: ...\n\nbytes4: ArgumentDescriptor\n\ndef read_bytes8(f: IO[bytes]) -> bytes: ...\n\nbytes8: ArgumentDescriptor\n\ndef read_unicodestringnl(f: IO[bytes]) -> str: ...\n\nunicodestringnl: ArgumentDescriptor\n\ndef read_unicodestring1(f: IO[bytes]) -> str: ...\n\nunicodestring1: ArgumentDescriptor\n\ndef read_unicodestring4(f: IO[bytes]) -> str: ...\n\nunicodestring4: ArgumentDescriptor\n\ndef read_unicodestring8(f: IO[bytes]) -> str: ...\n\nunicodestring8: ArgumentDescriptor\n\ndef read_decimalnl_short(f: IO[bytes]) -> int: ...\ndef read_decimalnl_long(f: IO[bytes]) -> int: ...\n\ndecimalnl_short: ArgumentDescriptor\ndecimalnl_long: ArgumentDescriptor\n\ndef read_floatnl(f: IO[bytes]) -> float: ...\n\nfloatnl: ArgumentDescriptor\n\ndef read_float8(f: IO[bytes]) -> float: ...\n\nfloat8: ArgumentDescriptor\n\ndef read_long1(f: IO[bytes]) -> int: ...\n\nlong1: ArgumentDescriptor\n\ndef read_long4(f: IO[bytes]) -> int: ...\n\nlong4: ArgumentDescriptor\n\nclass StackObject:\n    __slots__ = (\"name\", \"obtype\", \"doc\")\n    name: str\n    obtype: type[Any] | tuple[type[Any], ...]\n    doc: str\n    def __init__(self, name: str, obtype: type[Any] | tuple[type[Any], ...], doc: str) -> None: ...\n\npyint: StackObject\npylong: StackObject\npyinteger_or_bool: StackObject\npybool: StackObject\npyfloat: StackObject\npybytes_or_str: StackObject\npystring: StackObject\npybytes: StackObject\npyunicode: StackObject\npynone: StackObject\npytuple: StackObject\npylist: StackObject\npydict: StackObject\npyset: StackObject\npyfrozenset: StackObject\nanyobject: StackObject\nmarkobject: StackObject\nstackslice: StackObject\n\nclass OpcodeInfo:\n    __slots__ = (\"name\", \"code\", \"arg\", \"stack_before\", \"stack_after\", \"proto\", \"doc\")\n    name: str\n    code: str\n    arg: ArgumentDescriptor | None\n    stack_before: list[StackObject]\n    stack_after: list[StackObject]\n    proto: int\n    doc: str\n    def __init__(\n        self,\n        name: str,\n        code: str,\n        arg: ArgumentDescriptor | None,\n        stack_before: list[StackObject],\n        stack_after: list[StackObject],\n        proto: int,\n        doc: str,\n    ) -> None: ...\n\nopcodes: list[OpcodeInfo]\n\ndef genops(pickle: bytes | bytearray | IO[bytes]) -> Iterator[tuple[OpcodeInfo, Any | None, int | None]]: ...\ndef optimize(p: bytes | bytearray | IO[bytes]) -> bytes: ...\ndef dis(\n    pickle: bytes | bytearray | IO[bytes],\n    out: IO[str] | None = None,\n    memo: MutableMapping[int, Any] | None = None,\n    indentlevel: int = 4,\n    annotate: int = 0,\n) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pipes.pyi",
    "content": "import os\n\n__all__ = [\"Template\"]\n\nclass Template:\n    def reset(self) -> None: ...\n    def clone(self) -> Template: ...\n    def debug(self, flag: bool) -> None: ...\n    def append(self, cmd: str, kind: str) -> None: ...\n    def prepend(self, cmd: str, kind: str) -> None: ...\n    def open(self, file: str, rw: str) -> os._wrap_close: ...\n    def copy(self, infile: str, outfile: str) -> int: ...\n\n# Not documented, but widely used.\n# Documented as shlex.quote since 3.3.\ndef quote(s: str) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pkgutil.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath, SupportsRead\nfrom _typeshed.importlib import LoaderProtocol, MetaPathFinderProtocol, PathEntryFinderProtocol\nfrom collections.abc import Callable, Iterable, Iterator\nfrom typing import IO, Any, NamedTuple, TypeVar\nfrom typing_extensions import deprecated\n\n__all__ = [\n    \"get_importer\",\n    \"iter_importers\",\n    \"walk_packages\",\n    \"iter_modules\",\n    \"get_data\",\n    \"read_code\",\n    \"extend_path\",\n    \"ModuleInfo\",\n]\nif sys.version_info < (3, 14):\n    __all__ += [\"get_loader\", \"find_loader\"]\nif sys.version_info < (3, 12):\n    __all__ += [\"ImpImporter\", \"ImpLoader\"]\n\n_PathT = TypeVar(\"_PathT\", bound=Iterable[str])\n\nclass ModuleInfo(NamedTuple):\n    module_finder: MetaPathFinderProtocol | PathEntryFinderProtocol\n    name: str\n    ispkg: bool\n\ndef extend_path(path: _PathT, name: str) -> _PathT: ...\n\nif sys.version_info < (3, 12):\n    @deprecated(\"Deprecated since Python 3.3; removed in Python 3.12. Use the `importlib` module instead.\")\n    class ImpImporter:\n        def __init__(self, path: StrOrBytesPath | None = None) -> None: ...\n\n    @deprecated(\"Deprecated since Python 3.3; removed in Python 3.12. Use the `importlib` module instead.\")\n    class ImpLoader:\n        def __init__(self, fullname: str, file: IO[str], filename: StrOrBytesPath, etc: tuple[str, str, int]) -> None: ...\n\nif sys.version_info < (3, 14):\n    if sys.version_info >= (3, 12):\n        @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14. Use `importlib.util.find_spec()` instead.\")\n        def find_loader(fullname: str) -> LoaderProtocol | None: ...\n        @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14. Use `importlib.util.find_spec()` instead.\")\n        def get_loader(module_or_name: str) -> LoaderProtocol | None: ...\n    else:\n        def find_loader(fullname: str) -> LoaderProtocol | None: ...\n        def get_loader(module_or_name: str) -> LoaderProtocol | None: ...\n\ndef get_importer(path_item: StrOrBytesPath) -> PathEntryFinderProtocol | None: ...\ndef iter_importers(fullname: str = \"\") -> Iterator[MetaPathFinderProtocol | PathEntryFinderProtocol]: ...\ndef iter_modules(path: Iterable[StrOrBytesPath] | None = None, prefix: str = \"\") -> Iterator[ModuleInfo]: ...\ndef read_code(stream: SupportsRead[bytes]) -> Any: ...  # undocumented\ndef walk_packages(\n    path: Iterable[StrOrBytesPath] | None = None, prefix: str = \"\", onerror: Callable[[str], object] | None = None\n) -> Iterator[ModuleInfo]: ...\ndef get_data(package: str, resource: str) -> bytes | None: ...\ndef resolve_name(name: str) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/platform.pyi",
    "content": "import sys\nfrom typing import NamedTuple, type_check_only\nfrom typing_extensions import Self, deprecated, disjoint_base\n\ndef libc_ver(executable: str | None = None, lib: str = \"\", version: str = \"\", chunksize: int = 16384) -> tuple[str, str]: ...\ndef win32_ver(release: str = \"\", version: str = \"\", csd: str = \"\", ptype: str = \"\") -> tuple[str, str, str, str]: ...\ndef win32_edition() -> str: ...\ndef win32_is_iot() -> bool: ...\ndef mac_ver(\n    release: str = \"\", versioninfo: tuple[str, str, str] = (\"\", \"\", \"\"), machine: str = \"\"\n) -> tuple[str, tuple[str, str, str], str]: ...\n\nif sys.version_info >= (3, 13):\n    @deprecated(\"Deprecated since Python 3.13; will be removed in Python 3.15.\")\n    def java_ver(\n        release: str = \"\",\n        vendor: str = \"\",\n        vminfo: tuple[str, str, str] = (\"\", \"\", \"\"),\n        osinfo: tuple[str, str, str] = (\"\", \"\", \"\"),\n    ) -> tuple[str, str, tuple[str, str, str], tuple[str, str, str]]: ...\n\nelse:\n    def java_ver(\n        release: str = \"\",\n        vendor: str = \"\",\n        vminfo: tuple[str, str, str] = (\"\", \"\", \"\"),\n        osinfo: tuple[str, str, str] = (\"\", \"\", \"\"),\n    ) -> tuple[str, str, tuple[str, str, str], tuple[str, str, str]]: ...\n\ndef system_alias(system: str, release: str, version: str) -> tuple[str, str, str]: ...\ndef architecture(executable: str = sys.executable, bits: str = \"\", linkage: str = \"\") -> tuple[str, str]: ...\n\n# This class is not exposed. It calls itself platform.uname_result_base.\n# At runtime it only has 5 fields.\n@type_check_only\nclass _uname_result_base(NamedTuple):\n    system: str\n    node: str\n    release: str\n    version: str\n    machine: str\n    # This base class doesn't have this field at runtime, but claiming it\n    # does is the least bad way to handle the situation. Nobody really\n    # sees this class anyway. See #13068\n    processor: str\n\n# uname_result emulates a 6-field named tuple, but the processor field\n# is lazily evaluated rather than being passed in to the constructor.\nif sys.version_info >= (3, 12):\n    class uname_result(_uname_result_base):\n        __match_args__ = (\"system\", \"node\", \"release\", \"version\", \"machine\")  # pyright: ignore[reportAssignmentType]\n\n        def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ...\n        @property\n        def processor(self) -> str: ...\n\nelse:\n    @disjoint_base\n    class uname_result(_uname_result_base):\n        if sys.version_info >= (3, 10):\n            __match_args__ = (\"system\", \"node\", \"release\", \"version\", \"machine\")  # pyright: ignore[reportAssignmentType]\n\n        def __new__(_cls, system: str, node: str, release: str, version: str, machine: str) -> Self: ...\n        @property\n        def processor(self) -> str: ...\n\ndef uname() -> uname_result: ...\ndef system() -> str: ...\ndef node() -> str: ...\ndef release() -> str: ...\ndef version() -> str: ...\ndef machine() -> str: ...\ndef processor() -> str: ...\ndef python_implementation() -> str: ...\ndef python_version() -> str: ...\ndef python_version_tuple() -> tuple[str, str, str]: ...\ndef python_branch() -> str: ...\ndef python_revision() -> str: ...\ndef python_build() -> tuple[str, str]: ...\ndef python_compiler() -> str: ...\ndef platform(aliased: bool = False, terse: bool = False) -> str: ...\n\nif sys.version_info >= (3, 10):\n    def freedesktop_os_release() -> dict[str, str]: ...\n\nif sys.version_info >= (3, 13):\n    class AndroidVer(NamedTuple):\n        release: str\n        api_level: int\n        manufacturer: str\n        model: str\n        device: str\n        is_emulator: bool\n\n    class IOSVersionInfo(NamedTuple):\n        system: str\n        release: str\n        model: str\n        is_simulator: bool\n\n    def android_ver(\n        release: str = \"\",\n        api_level: int = 0,\n        manufacturer: str = \"\",\n        model: str = \"\",\n        device: str = \"\",\n        is_emulator: bool = False,\n    ) -> AndroidVer: ...\n    def ios_ver(system: str = \"\", release: str = \"\", model: str = \"\", is_simulator: bool = False) -> IOSVersionInfo: ...\n\nif sys.version_info >= (3, 14):\n    def invalidate_caches() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/plistlib.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Mapping, MutableMapping\nfrom datetime import datetime\nfrom enum import Enum\nfrom typing import IO, Any, Final\nfrom typing_extensions import Self\n\n__all__ = [\"InvalidFileException\", \"FMT_XML\", \"FMT_BINARY\", \"load\", \"dump\", \"loads\", \"dumps\", \"UID\"]\n\nclass PlistFormat(Enum):\n    FMT_XML = 1\n    FMT_BINARY = 2\n\nFMT_XML: Final = PlistFormat.FMT_XML\nFMT_BINARY: Final = PlistFormat.FMT_BINARY\nif sys.version_info >= (3, 13):\n    def load(\n        fp: IO[bytes],\n        *,\n        fmt: PlistFormat | None = None,\n        dict_type: type[MutableMapping[str, Any]] = ...,\n        aware_datetime: bool = False,\n    ) -> Any: ...\n    def loads(\n        value: ReadableBuffer | str,\n        *,\n        fmt: PlistFormat | None = None,\n        dict_type: type[MutableMapping[str, Any]] = ...,\n        aware_datetime: bool = False,\n    ) -> Any: ...\n\nelse:\n    def load(fp: IO[bytes], *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ...) -> Any: ...\n    def loads(\n        value: ReadableBuffer, *, fmt: PlistFormat | None = None, dict_type: type[MutableMapping[str, Any]] = ...\n    ) -> Any: ...\n\nif sys.version_info >= (3, 13):\n    def dump(\n        value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime,\n        fp: IO[bytes],\n        *,\n        fmt: PlistFormat = ...,\n        sort_keys: bool = True,\n        skipkeys: bool = False,\n        aware_datetime: bool = False,\n    ) -> None: ...\n    def dumps(\n        value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime,\n        *,\n        fmt: PlistFormat = ...,\n        skipkeys: bool = False,\n        sort_keys: bool = True,\n        aware_datetime: bool = False,\n    ) -> bytes: ...\n\nelse:\n    def dump(\n        value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime,\n        fp: IO[bytes],\n        *,\n        fmt: PlistFormat = ...,\n        sort_keys: bool = True,\n        skipkeys: bool = False,\n    ) -> None: ...\n    def dumps(\n        value: Mapping[str, Any] | list[Any] | tuple[Any, ...] | str | bool | float | bytes | bytearray | datetime,\n        *,\n        fmt: PlistFormat = ...,\n        skipkeys: bool = False,\n        sort_keys: bool = True,\n    ) -> bytes: ...\n\nclass UID:\n    data: int\n    def __init__(self, data: int) -> None: ...\n    def __index__(self) -> int: ...\n    def __reduce__(self) -> tuple[type[Self], tuple[int]]: ...\n    def __hash__(self) -> int: ...\n    def __eq__(self, other: object) -> bool: ...\n\nclass InvalidFileException(ValueError):\n    def __init__(self, message: str = \"Invalid file\") -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/poplib.pyi",
    "content": "import socket\nimport ssl\nimport sys\nfrom _typeshed import StrOrBytesPath\nfrom builtins import list as _list  # conflicts with a method named \"list\"\nfrom re import Pattern\nfrom typing import Any, BinaryIO, Final, NoReturn, overload\nfrom typing_extensions import TypeAlias, deprecated\n\n__all__ = [\"POP3\", \"error_proto\", \"POP3_SSL\"]\n\n_LongResp: TypeAlias = tuple[bytes, list[bytes], int]\n\nclass error_proto(Exception): ...\n\nPOP3_PORT: Final = 110\nPOP3_SSL_PORT: Final = 995\nCR: Final = b\"\\r\"\nLF: Final = b\"\\n\"\nCRLF: Final = b\"\\r\\n\"\nHAVE_SSL: Final[bool]\n\nclass POP3:\n    encoding: str\n    host: str\n    port: int\n    sock: socket.socket\n    file: BinaryIO\n    welcome: bytes\n    def __init__(self, host: str, port: int = 110, timeout: float = ...) -> None: ...\n    def getwelcome(self) -> bytes: ...\n    def set_debuglevel(self, level: int) -> None: ...\n    def user(self, user: str) -> bytes: ...\n    def pass_(self, pswd: str) -> bytes: ...\n    def stat(self) -> tuple[int, int]: ...\n    def list(self, which: Any | None = None) -> _LongResp: ...\n    def retr(self, which: Any) -> _LongResp: ...\n    def dele(self, which: Any) -> bytes: ...\n    def noop(self) -> bytes: ...\n    def rset(self) -> bytes: ...\n    def quit(self) -> bytes: ...\n    def close(self) -> None: ...\n    def rpop(self, user: str) -> bytes: ...\n    timestamp: Pattern[str]\n    def apop(self, user: str, password: str) -> bytes: ...\n    def top(self, which: Any, howmuch: int) -> _LongResp: ...\n    @overload\n    def uidl(self) -> _LongResp: ...\n    @overload\n    def uidl(self, which: Any) -> bytes: ...\n    def utf8(self) -> bytes: ...\n    def capa(self) -> dict[str, _list[str]]: ...\n    def stls(self, context: ssl.SSLContext | None = None) -> bytes: ...\n\nclass POP3_SSL(POP3):\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self, host: str, port: int = 995, *, timeout: float = ..., context: ssl.SSLContext | None = None\n        ) -> None: ...\n        def stls(self, context: Any = None) -> NoReturn: ...\n    else:\n        @overload\n        def __init__(\n            self,\n            host: str,\n            port: int = 995,\n            keyfile: None = None,\n            certfile: None = None,\n            timeout: float = ...,\n            context: ssl.SSLContext | None = None,\n        ) -> None: ...\n        @overload\n        @deprecated(\n            \"The `keyfile`, `certfile` parameters are deprecated since Python 3.6; \"\n            \"removed in Python 3.12. Use `context` parameter instead.\"\n        )\n        def __init__(\n            self,\n            host: str,\n            port: int = 995,\n            keyfile: StrOrBytesPath | None = None,\n            certfile: StrOrBytesPath | None = None,\n            timeout: float = ...,\n            context: None = None,\n        ) -> None: ...\n        keyfile: StrOrBytesPath | None\n        certfile: StrOrBytesPath | None\n        # \"context\" is actually the last argument,\n        # but that breaks LSP and it doesn't really matter because all the arguments are ignored\n        def stls(self, context: Any = None, keyfile: Any = None, certfile: Any = None) -> NoReturn: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/posix.pyi",
    "content": "import sys\n\nif sys.platform != \"win32\":\n    # Actually defined here, but defining in os allows sharing code with windows\n    from os import (\n        CLD_CONTINUED as CLD_CONTINUED,\n        CLD_DUMPED as CLD_DUMPED,\n        CLD_EXITED as CLD_EXITED,\n        CLD_KILLED as CLD_KILLED,\n        CLD_STOPPED as CLD_STOPPED,\n        CLD_TRAPPED as CLD_TRAPPED,\n        EX_CANTCREAT as EX_CANTCREAT,\n        EX_CONFIG as EX_CONFIG,\n        EX_DATAERR as EX_DATAERR,\n        EX_IOERR as EX_IOERR,\n        EX_NOHOST as EX_NOHOST,\n        EX_NOINPUT as EX_NOINPUT,\n        EX_NOPERM as EX_NOPERM,\n        EX_NOUSER as EX_NOUSER,\n        EX_OK as EX_OK,\n        EX_OSERR as EX_OSERR,\n        EX_OSFILE as EX_OSFILE,\n        EX_PROTOCOL as EX_PROTOCOL,\n        EX_SOFTWARE as EX_SOFTWARE,\n        EX_TEMPFAIL as EX_TEMPFAIL,\n        EX_UNAVAILABLE as EX_UNAVAILABLE,\n        EX_USAGE as EX_USAGE,\n        F_LOCK as F_LOCK,\n        F_OK as F_OK,\n        F_TEST as F_TEST,\n        F_TLOCK as F_TLOCK,\n        F_ULOCK as F_ULOCK,\n        NGROUPS_MAX as NGROUPS_MAX,\n        O_ACCMODE as O_ACCMODE,\n        O_APPEND as O_APPEND,\n        O_ASYNC as O_ASYNC,\n        O_CLOEXEC as O_CLOEXEC,\n        O_CREAT as O_CREAT,\n        O_DIRECTORY as O_DIRECTORY,\n        O_DSYNC as O_DSYNC,\n        O_EXCL as O_EXCL,\n        O_NDELAY as O_NDELAY,\n        O_NOCTTY as O_NOCTTY,\n        O_NOFOLLOW as O_NOFOLLOW,\n        O_NONBLOCK as O_NONBLOCK,\n        O_RDONLY as O_RDONLY,\n        O_RDWR as O_RDWR,\n        O_SYNC as O_SYNC,\n        O_TRUNC as O_TRUNC,\n        O_WRONLY as O_WRONLY,\n        P_ALL as P_ALL,\n        P_PGID as P_PGID,\n        P_PID as P_PID,\n        POSIX_SPAWN_CLOSE as POSIX_SPAWN_CLOSE,\n        POSIX_SPAWN_DUP2 as POSIX_SPAWN_DUP2,\n        POSIX_SPAWN_OPEN as POSIX_SPAWN_OPEN,\n        PRIO_PGRP as PRIO_PGRP,\n        PRIO_PROCESS as PRIO_PROCESS,\n        PRIO_USER as PRIO_USER,\n        R_OK as R_OK,\n        RTLD_GLOBAL as RTLD_GLOBAL,\n        RTLD_LAZY as RTLD_LAZY,\n        RTLD_LOCAL as RTLD_LOCAL,\n        RTLD_NODELETE as RTLD_NODELETE,\n        RTLD_NOLOAD as RTLD_NOLOAD,\n        RTLD_NOW as RTLD_NOW,\n        SCHED_FIFO as SCHED_FIFO,\n        SCHED_OTHER as SCHED_OTHER,\n        SCHED_RR as SCHED_RR,\n        SEEK_DATA as SEEK_DATA,\n        SEEK_HOLE as SEEK_HOLE,\n        ST_NOSUID as ST_NOSUID,\n        ST_RDONLY as ST_RDONLY,\n        TMP_MAX as TMP_MAX,\n        W_OK as W_OK,\n        WCONTINUED as WCONTINUED,\n        WCOREDUMP as WCOREDUMP,\n        WEXITED as WEXITED,\n        WEXITSTATUS as WEXITSTATUS,\n        WIFCONTINUED as WIFCONTINUED,\n        WIFEXITED as WIFEXITED,\n        WIFSIGNALED as WIFSIGNALED,\n        WIFSTOPPED as WIFSTOPPED,\n        WNOHANG as WNOHANG,\n        WNOWAIT as WNOWAIT,\n        WSTOPPED as WSTOPPED,\n        WSTOPSIG as WSTOPSIG,\n        WTERMSIG as WTERMSIG,\n        WUNTRACED as WUNTRACED,\n        X_OK as X_OK,\n        DirEntry as DirEntry,\n        _exit as _exit,\n        abort as abort,\n        access as access,\n        chdir as chdir,\n        chmod as chmod,\n        chown as chown,\n        chroot as chroot,\n        close as close,\n        closerange as closerange,\n        confstr as confstr,\n        confstr_names as confstr_names,\n        cpu_count as cpu_count,\n        ctermid as ctermid,\n        device_encoding as device_encoding,\n        dup as dup,\n        dup2 as dup2,\n        error as error,\n        execv as execv,\n        execve as execve,\n        fchdir as fchdir,\n        fchmod as fchmod,\n        fchown as fchown,\n        fork as fork,\n        forkpty as forkpty,\n        fpathconf as fpathconf,\n        fspath as fspath,\n        fstat as fstat,\n        fstatvfs as fstatvfs,\n        fsync as fsync,\n        ftruncate as ftruncate,\n        get_blocking as get_blocking,\n        get_inheritable as get_inheritable,\n        get_terminal_size as get_terminal_size,\n        getcwd as getcwd,\n        getcwdb as getcwdb,\n        getegid as getegid,\n        geteuid as geteuid,\n        getgid as getgid,\n        getgrouplist as getgrouplist,\n        getgroups as getgroups,\n        getloadavg as getloadavg,\n        getlogin as getlogin,\n        getpgid as getpgid,\n        getpgrp as getpgrp,\n        getpid as getpid,\n        getppid as getppid,\n        getpriority as getpriority,\n        getsid as getsid,\n        getuid as getuid,\n        initgroups as initgroups,\n        isatty as isatty,\n        kill as kill,\n        killpg as killpg,\n        lchown as lchown,\n        link as link,\n        listdir as listdir,\n        lockf as lockf,\n        lseek as lseek,\n        lstat as lstat,\n        major as major,\n        makedev as makedev,\n        minor as minor,\n        mkdir as mkdir,\n        mkfifo as mkfifo,\n        mknod as mknod,\n        nice as nice,\n        open as open,\n        openpty as openpty,\n        pathconf as pathconf,\n        pathconf_names as pathconf_names,\n        pipe as pipe,\n        posix_spawn as posix_spawn,\n        posix_spawnp as posix_spawnp,\n        pread as pread,\n        preadv as preadv,\n        putenv as putenv,\n        pwrite as pwrite,\n        pwritev as pwritev,\n        read as read,\n        readlink as readlink,\n        readv as readv,\n        register_at_fork as register_at_fork,\n        remove as remove,\n        rename as rename,\n        replace as replace,\n        rmdir as rmdir,\n        scandir as scandir,\n        sched_get_priority_max as sched_get_priority_max,\n        sched_get_priority_min as sched_get_priority_min,\n        sched_param as sched_param,\n        sched_yield as sched_yield,\n        sendfile as sendfile,\n        set_blocking as set_blocking,\n        set_inheritable as set_inheritable,\n        setegid as setegid,\n        seteuid as seteuid,\n        setgid as setgid,\n        setgroups as setgroups,\n        setpgid as setpgid,\n        setpgrp as setpgrp,\n        setpriority as setpriority,\n        setregid as setregid,\n        setreuid as setreuid,\n        setsid as setsid,\n        setuid as setuid,\n        stat as stat,\n        stat_result as stat_result,\n        statvfs as statvfs,\n        statvfs_result as statvfs_result,\n        strerror as strerror,\n        symlink as symlink,\n        sync as sync,\n        sysconf as sysconf,\n        sysconf_names as sysconf_names,\n        system as system,\n        tcgetpgrp as tcgetpgrp,\n        tcsetpgrp as tcsetpgrp,\n        terminal_size as terminal_size,\n        times as times,\n        times_result as times_result,\n        truncate as truncate,\n        ttyname as ttyname,\n        umask as umask,\n        uname as uname,\n        uname_result as uname_result,\n        unlink as unlink,\n        unsetenv as unsetenv,\n        urandom as urandom,\n        utime as utime,\n        wait as wait,\n        wait3 as wait3,\n        wait4 as wait4,\n        waitpid as waitpid,\n        waitstatus_to_exitcode as waitstatus_to_exitcode,\n        write as write,\n        writev as writev,\n    )\n\n    if sys.version_info >= (3, 10):\n        from os import O_FSYNC as O_FSYNC\n\n    if sys.version_info >= (3, 11):\n        from os import login_tty as login_tty\n\n    if sys.version_info >= (3, 13):\n        from os import grantpt as grantpt, posix_openpt as posix_openpt, ptsname as ptsname, unlockpt as unlockpt\n\n    if sys.version_info >= (3, 13) and sys.platform == \"linux\":\n        from os import (\n            POSIX_SPAWN_CLOSEFROM as POSIX_SPAWN_CLOSEFROM,\n            TFD_CLOEXEC as TFD_CLOEXEC,\n            TFD_NONBLOCK as TFD_NONBLOCK,\n            TFD_TIMER_ABSTIME as TFD_TIMER_ABSTIME,\n            TFD_TIMER_CANCEL_ON_SET as TFD_TIMER_CANCEL_ON_SET,\n            timerfd_create as timerfd_create,\n            timerfd_gettime as timerfd_gettime,\n            timerfd_gettime_ns as timerfd_gettime_ns,\n            timerfd_settime as timerfd_settime,\n            timerfd_settime_ns as timerfd_settime_ns,\n        )\n\n    if sys.version_info >= (3, 14):\n        from os import readinto as readinto\n\n    if sys.version_info >= (3, 14) and sys.platform == \"linux\":\n        from os import SCHED_DEADLINE as SCHED_DEADLINE, SCHED_NORMAL as SCHED_NORMAL\n\n    if sys.platform != \"linux\":\n        from os import O_EXLOCK as O_EXLOCK, O_SHLOCK as O_SHLOCK, chflags as chflags, lchflags as lchflags, lchmod as lchmod\n\n    if sys.platform != \"linux\" and sys.platform != \"darwin\":\n        from os import EX_NOTFOUND as EX_NOTFOUND, SCHED_SPORADIC as SCHED_SPORADIC\n\n    if sys.platform != \"linux\" and sys.version_info >= (3, 13):\n        from os import O_EXEC as O_EXEC, O_SEARCH as O_SEARCH\n\n    if sys.platform != \"darwin\":\n        from os import (\n            POSIX_FADV_DONTNEED as POSIX_FADV_DONTNEED,\n            POSIX_FADV_NOREUSE as POSIX_FADV_NOREUSE,\n            POSIX_FADV_NORMAL as POSIX_FADV_NORMAL,\n            POSIX_FADV_RANDOM as POSIX_FADV_RANDOM,\n            POSIX_FADV_SEQUENTIAL as POSIX_FADV_SEQUENTIAL,\n            POSIX_FADV_WILLNEED as POSIX_FADV_WILLNEED,\n            RWF_DSYNC as RWF_DSYNC,\n            RWF_HIPRI as RWF_HIPRI,\n            RWF_NOWAIT as RWF_NOWAIT,\n            RWF_SYNC as RWF_SYNC,\n            ST_APPEND as ST_APPEND,\n            ST_MANDLOCK as ST_MANDLOCK,\n            ST_NOATIME as ST_NOATIME,\n            ST_NODEV as ST_NODEV,\n            ST_NODIRATIME as ST_NODIRATIME,\n            ST_NOEXEC as ST_NOEXEC,\n            ST_RELATIME as ST_RELATIME,\n            ST_SYNCHRONOUS as ST_SYNCHRONOUS,\n            ST_WRITE as ST_WRITE,\n            fdatasync as fdatasync,\n            getresgid as getresgid,\n            getresuid as getresuid,\n            pipe2 as pipe2,\n            posix_fadvise as posix_fadvise,\n            posix_fallocate as posix_fallocate,\n            sched_getaffinity as sched_getaffinity,\n            sched_getparam as sched_getparam,\n            sched_getscheduler as sched_getscheduler,\n            sched_rr_get_interval as sched_rr_get_interval,\n            sched_setaffinity as sched_setaffinity,\n            sched_setparam as sched_setparam,\n            sched_setscheduler as sched_setscheduler,\n            setresgid as setresgid,\n            setresuid as setresuid,\n        )\n\n        if sys.version_info >= (3, 10):\n            from os import RWF_APPEND as RWF_APPEND\n\n    if sys.platform != \"darwin\" or sys.version_info >= (3, 13):\n        from os import waitid as waitid, waitid_result as waitid_result\n\n    if sys.platform == \"linux\":\n        from os import (\n            GRND_NONBLOCK as GRND_NONBLOCK,\n            GRND_RANDOM as GRND_RANDOM,\n            MFD_ALLOW_SEALING as MFD_ALLOW_SEALING,\n            MFD_CLOEXEC as MFD_CLOEXEC,\n            MFD_HUGE_1GB as MFD_HUGE_1GB,\n            MFD_HUGE_1MB as MFD_HUGE_1MB,\n            MFD_HUGE_2GB as MFD_HUGE_2GB,\n            MFD_HUGE_2MB as MFD_HUGE_2MB,\n            MFD_HUGE_8MB as MFD_HUGE_8MB,\n            MFD_HUGE_16GB as MFD_HUGE_16GB,\n            MFD_HUGE_16MB as MFD_HUGE_16MB,\n            MFD_HUGE_32MB as MFD_HUGE_32MB,\n            MFD_HUGE_64KB as MFD_HUGE_64KB,\n            MFD_HUGE_256MB as MFD_HUGE_256MB,\n            MFD_HUGE_512KB as MFD_HUGE_512KB,\n            MFD_HUGE_512MB as MFD_HUGE_512MB,\n            MFD_HUGE_MASK as MFD_HUGE_MASK,\n            MFD_HUGE_SHIFT as MFD_HUGE_SHIFT,\n            MFD_HUGETLB as MFD_HUGETLB,\n            O_DIRECT as O_DIRECT,\n            O_LARGEFILE as O_LARGEFILE,\n            O_NOATIME as O_NOATIME,\n            O_PATH as O_PATH,\n            O_RSYNC as O_RSYNC,\n            O_TMPFILE as O_TMPFILE,\n            P_PIDFD as P_PIDFD,\n            RTLD_DEEPBIND as RTLD_DEEPBIND,\n            SCHED_BATCH as SCHED_BATCH,\n            SCHED_IDLE as SCHED_IDLE,\n            SCHED_RESET_ON_FORK as SCHED_RESET_ON_FORK,\n            XATTR_CREATE as XATTR_CREATE,\n            XATTR_REPLACE as XATTR_REPLACE,\n            XATTR_SIZE_MAX as XATTR_SIZE_MAX,\n            copy_file_range as copy_file_range,\n            getrandom as getrandom,\n            getxattr as getxattr,\n            listxattr as listxattr,\n            memfd_create as memfd_create,\n            pidfd_open as pidfd_open,\n            removexattr as removexattr,\n            setxattr as setxattr,\n        )\n\n        if sys.version_info >= (3, 10):\n            from os import (\n                EFD_CLOEXEC as EFD_CLOEXEC,\n                EFD_NONBLOCK as EFD_NONBLOCK,\n                EFD_SEMAPHORE as EFD_SEMAPHORE,\n                SPLICE_F_MORE as SPLICE_F_MORE,\n                SPLICE_F_MOVE as SPLICE_F_MOVE,\n                SPLICE_F_NONBLOCK as SPLICE_F_NONBLOCK,\n                eventfd as eventfd,\n                eventfd_read as eventfd_read,\n                eventfd_write as eventfd_write,\n                splice as splice,\n            )\n\n        if sys.version_info >= (3, 12):\n            from os import (\n                CLONE_FILES as CLONE_FILES,\n                CLONE_FS as CLONE_FS,\n                CLONE_NEWCGROUP as CLONE_NEWCGROUP,\n                CLONE_NEWIPC as CLONE_NEWIPC,\n                CLONE_NEWNET as CLONE_NEWNET,\n                CLONE_NEWNS as CLONE_NEWNS,\n                CLONE_NEWPID as CLONE_NEWPID,\n                CLONE_NEWTIME as CLONE_NEWTIME,\n                CLONE_NEWUSER as CLONE_NEWUSER,\n                CLONE_NEWUTS as CLONE_NEWUTS,\n                CLONE_SIGHAND as CLONE_SIGHAND,\n                CLONE_SYSVSEM as CLONE_SYSVSEM,\n                CLONE_THREAD as CLONE_THREAD,\n                CLONE_VM as CLONE_VM,\n                PIDFD_NONBLOCK as PIDFD_NONBLOCK,\n                setns as setns,\n                unshare as unshare,\n            )\n\n    if sys.platform == \"darwin\":\n        if sys.version_info >= (3, 12):\n            from os import (\n                PRIO_DARWIN_BG as PRIO_DARWIN_BG,\n                PRIO_DARWIN_NONUI as PRIO_DARWIN_NONUI,\n                PRIO_DARWIN_PROCESS as PRIO_DARWIN_PROCESS,\n                PRIO_DARWIN_THREAD as PRIO_DARWIN_THREAD,\n            )\n    if sys.platform == \"darwin\" and sys.version_info >= (3, 10):\n        from os import O_EVTONLY as O_EVTONLY, O_NOFOLLOW_ANY as O_NOFOLLOW_ANY, O_SYMLINK as O_SYMLINK\n\n    # Not same as os.environ or os.environb\n    # Because of this variable, we can't do \"from posix import *\" in os/__init__.pyi\n    environ: dict[bytes, bytes]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/posixpath.pyi",
    "content": "import sys\nfrom _typeshed import AnyOrLiteralStr, BytesPath, FileDescriptorOrPath, StrOrBytesPath, StrPath\nfrom collections.abc import Iterable\nfrom genericpath import (\n    ALLOW_MISSING as ALLOW_MISSING,\n    _AllowMissingType,\n    commonprefix as commonprefix,\n    exists as exists,\n    getatime as getatime,\n    getctime as getctime,\n    getmtime as getmtime,\n    getsize as getsize,\n    isdir as isdir,\n    isfile as isfile,\n    samefile as samefile,\n    sameopenfile as sameopenfile,\n    samestat as samestat,\n)\n\nif sys.version_info >= (3, 13):\n    from genericpath import isdevdrive as isdevdrive\nfrom os import PathLike\nfrom typing import AnyStr, overload\nfrom typing_extensions import LiteralString\n\n__all__ = [\n    \"normcase\",\n    \"isabs\",\n    \"join\",\n    \"splitdrive\",\n    \"split\",\n    \"splitext\",\n    \"basename\",\n    \"dirname\",\n    \"commonprefix\",\n    \"getsize\",\n    \"getmtime\",\n    \"getatime\",\n    \"getctime\",\n    \"islink\",\n    \"exists\",\n    \"lexists\",\n    \"isdir\",\n    \"isfile\",\n    \"ismount\",\n    \"expanduser\",\n    \"expandvars\",\n    \"normpath\",\n    \"abspath\",\n    \"samefile\",\n    \"sameopenfile\",\n    \"samestat\",\n    \"curdir\",\n    \"pardir\",\n    \"sep\",\n    \"pathsep\",\n    \"defpath\",\n    \"altsep\",\n    \"extsep\",\n    \"devnull\",\n    \"realpath\",\n    \"supports_unicode_filenames\",\n    \"relpath\",\n    \"commonpath\",\n]\n__all__ += [\"ALLOW_MISSING\"]\nif sys.version_info >= (3, 12):\n    __all__ += [\"isjunction\", \"splitroot\"]\nif sys.version_info >= (3, 13):\n    __all__ += [\"isdevdrive\"]\n\nsupports_unicode_filenames: bool\n# aliases (also in os)\ncurdir: LiteralString\npardir: LiteralString\nsep: LiteralString\naltsep: LiteralString | None\nextsep: LiteralString\npathsep: LiteralString\ndefpath: LiteralString\ndevnull: LiteralString\n\n# Overloads are necessary to work around python/mypy#17952 & python/mypy#11880\n@overload\ndef abspath(path: PathLike[AnyStr]) -> AnyStr: ...\n@overload\ndef abspath(path: AnyStr) -> AnyStr: ...\n@overload\ndef basename(p: PathLike[AnyStr]) -> AnyStr: ...\n@overload\ndef basename(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ...\n@overload\ndef dirname(p: PathLike[AnyStr]) -> AnyStr: ...\n@overload\ndef dirname(p: AnyOrLiteralStr) -> AnyOrLiteralStr: ...\n@overload\ndef expanduser(path: PathLike[AnyStr]) -> AnyStr: ...\n@overload\ndef expanduser(path: AnyStr) -> AnyStr: ...\n@overload\ndef expandvars(path: PathLike[AnyStr]) -> AnyStr: ...\n@overload\ndef expandvars(path: AnyStr) -> AnyStr: ...\n@overload\ndef normcase(s: PathLike[AnyStr]) -> AnyStr: ...\n@overload\ndef normcase(s: AnyOrLiteralStr) -> AnyOrLiteralStr: ...\n@overload\ndef normpath(path: PathLike[AnyStr]) -> AnyStr: ...\n@overload\ndef normpath(path: AnyOrLiteralStr) -> AnyOrLiteralStr: ...\n@overload\ndef commonpath(paths: Iterable[LiteralString]) -> LiteralString: ...\n@overload\ndef commonpath(paths: Iterable[StrPath]) -> str: ...\n@overload\ndef commonpath(paths: Iterable[BytesPath]) -> bytes: ...\n\n# First parameter is not actually pos-only,\n# but must be defined as pos-only in the stub or cross-platform code doesn't type-check,\n# as the parameter name is different in ntpath.join()\n@overload\ndef join(a: LiteralString, /, *paths: LiteralString) -> LiteralString: ...\n@overload\ndef join(a: StrPath, /, *paths: StrPath) -> str: ...\n@overload\ndef join(a: BytesPath, /, *paths: BytesPath) -> bytes: ...\n@overload\ndef realpath(filename: PathLike[AnyStr], *, strict: bool | _AllowMissingType = False) -> AnyStr: ...\n@overload\ndef realpath(filename: AnyStr, *, strict: bool | _AllowMissingType = False) -> AnyStr: ...\n@overload\ndef relpath(path: LiteralString, start: LiteralString | None = None) -> LiteralString: ...\n@overload\ndef relpath(path: BytesPath, start: BytesPath | None = None) -> bytes: ...\n@overload\ndef relpath(path: StrPath, start: StrPath | None = None) -> str: ...\n@overload\ndef split(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ...\n@overload\ndef split(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ...\n@overload\ndef splitdrive(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ...\n@overload\ndef splitdrive(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ...\n@overload\ndef splitext(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr]: ...\n@overload\ndef splitext(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr]: ...\ndef isabs(s: StrOrBytesPath) -> bool: ...\ndef islink(path: FileDescriptorOrPath) -> bool: ...\ndef ismount(path: FileDescriptorOrPath) -> bool: ...\ndef lexists(path: FileDescriptorOrPath) -> bool: ...\n\nif sys.version_info >= (3, 12):\n    def isjunction(path: StrOrBytesPath) -> bool: ...\n    @overload\n    def splitroot(p: AnyOrLiteralStr) -> tuple[AnyOrLiteralStr, AnyOrLiteralStr, AnyOrLiteralStr]: ...\n    @overload\n    def splitroot(p: PathLike[AnyStr]) -> tuple[AnyStr, AnyStr, AnyStr]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pprint.pyi",
    "content": "import sys\nfrom _typeshed import SupportsWrite\nfrom collections import deque\nfrom typing import IO\n\n__all__ = [\"pprint\", \"pformat\", \"isreadable\", \"isrecursive\", \"saferepr\", \"PrettyPrinter\", \"pp\"]\n\nif sys.version_info >= (3, 10):\n    def pformat(\n        object: object,\n        indent: int = 1,\n        width: int = 80,\n        depth: int | None = None,\n        *,\n        compact: bool = False,\n        sort_dicts: bool = True,\n        underscore_numbers: bool = False,\n    ) -> str: ...\n\nelse:\n    def pformat(\n        object: object,\n        indent: int = 1,\n        width: int = 80,\n        depth: int | None = None,\n        *,\n        compact: bool = False,\n        sort_dicts: bool = True,\n    ) -> str: ...\n\nif sys.version_info >= (3, 10):\n    def pp(\n        object: object,\n        stream: IO[str] | None = None,\n        indent: int = 1,\n        width: int = 80,\n        depth: int | None = None,\n        *,\n        compact: bool = False,\n        sort_dicts: bool = False,\n        underscore_numbers: bool = False,\n    ) -> None: ...\n\nelse:\n    def pp(\n        object: object,\n        stream: IO[str] | None = None,\n        indent: int = 1,\n        width: int = 80,\n        depth: int | None = None,\n        *,\n        compact: bool = False,\n        sort_dicts: bool = False,\n    ) -> None: ...\n\nif sys.version_info >= (3, 10):\n    def pprint(\n        object: object,\n        stream: IO[str] | None = None,\n        indent: int = 1,\n        width: int = 80,\n        depth: int | None = None,\n        *,\n        compact: bool = False,\n        sort_dicts: bool = True,\n        underscore_numbers: bool = False,\n    ) -> None: ...\n\nelse:\n    def pprint(\n        object: object,\n        stream: IO[str] | None = None,\n        indent: int = 1,\n        width: int = 80,\n        depth: int | None = None,\n        *,\n        compact: bool = False,\n        sort_dicts: bool = True,\n    ) -> None: ...\n\ndef isreadable(object: object) -> bool: ...\ndef isrecursive(object: object) -> bool: ...\ndef saferepr(object: object) -> str: ...\n\nclass PrettyPrinter:\n    if sys.version_info >= (3, 10):\n        def __init__(\n            self,\n            indent: int = 1,\n            width: int = 80,\n            depth: int | None = None,\n            stream: IO[str] | None = None,\n            *,\n            compact: bool = False,\n            sort_dicts: bool = True,\n            underscore_numbers: bool = False,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            indent: int = 1,\n            width: int = 80,\n            depth: int | None = None,\n            stream: IO[str] | None = None,\n            *,\n            compact: bool = False,\n            sort_dicts: bool = True,\n        ) -> None: ...\n\n    def pformat(self, object: object) -> str: ...\n    def pprint(self, object: object) -> None: ...\n    def isreadable(self, object: object) -> bool: ...\n    def isrecursive(self, object: object) -> bool: ...\n    def format(self, object: object, context: dict[int, int], maxlevels: int, level: int) -> tuple[str, bool, bool]: ...\n    def _format(\n        self, object: object, stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int\n    ) -> None: ...\n    def _pprint_dict(\n        self,\n        object: dict[object, object],\n        stream: SupportsWrite[str],\n        indent: int,\n        allowance: int,\n        context: dict[int, int],\n        level: int,\n    ) -> None: ...\n    def _pprint_list(\n        self, object: list[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int\n    ) -> None: ...\n    def _pprint_tuple(\n        self,\n        object: tuple[object, ...],\n        stream: SupportsWrite[str],\n        indent: int,\n        allowance: int,\n        context: dict[int, int],\n        level: int,\n    ) -> None: ...\n    def _pprint_set(\n        self, object: set[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int\n    ) -> None: ...\n    def _pprint_deque(\n        self, object: deque[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int\n    ) -> None: ...\n    def _format_dict_items(\n        self,\n        items: list[tuple[object, object]],\n        stream: SupportsWrite[str],\n        indent: int,\n        allowance: int,\n        context: dict[int, int],\n        level: int,\n    ) -> None: ...\n    def _format_items(\n        self, items: list[object], stream: SupportsWrite[str], indent: int, allowance: int, context: dict[int, int], level: int\n    ) -> None: ...\n    def _repr(self, object: object, context: dict[int, int], level: int) -> str: ...\n    if sys.version_info >= (3, 10):\n        def _safe_repr(self, object: object, context: dict[int, int], maxlevels: int, level: int) -> tuple[str, bool, bool]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/profile.pyi",
    "content": "from _typeshed import StrOrBytesPath\nfrom collections.abc import Callable, Mapping\nfrom typing import Any, TypeVar\nfrom typing_extensions import ParamSpec, Self, TypeAlias\n\n__all__ = [\"run\", \"runctx\", \"Profile\"]\n\ndef run(statement: str, filename: str | None = None, sort: str | int = -1) -> None: ...\ndef runctx(\n    statement: str, globals: dict[str, Any], locals: Mapping[str, Any], filename: str | None = None, sort: str | int = -1\n) -> None: ...\n\n_T = TypeVar(\"_T\")\n_P = ParamSpec(\"_P\")\n_Label: TypeAlias = tuple[str, int, str]\n\nclass Profile:\n    bias: int\n    stats: dict[_Label, tuple[int, int, int, int, dict[_Label, tuple[int, int, int, int]]]]  # undocumented\n    def __init__(self, timer: Callable[[], float] | None = None, bias: int | None = None) -> None: ...\n    def set_cmd(self, cmd: str) -> None: ...\n    def simulate_call(self, name: str) -> None: ...\n    def simulate_cmd_complete(self) -> None: ...\n    def print_stats(self, sort: str | int = -1) -> None: ...\n    def dump_stats(self, file: StrOrBytesPath) -> None: ...\n    def create_stats(self) -> None: ...\n    def snapshot_stats(self) -> None: ...\n    def run(self, cmd: str) -> Self: ...\n    def runctx(self, cmd: str, globals: dict[str, Any], locals: Mapping[str, Any]) -> Self: ...\n    def runcall(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ...\n    def calibrate(self, m: int, verbose: int = 0) -> float: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pstats.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath\nfrom collections.abc import Iterable\nfrom cProfile import Profile as _cProfile\nfrom dataclasses import dataclass\nfrom profile import Profile\nfrom typing import IO, Any, Literal, overload\nfrom typing_extensions import Self, TypeAlias\n\nif sys.version_info >= (3, 11):\n    from enum import StrEnum\nelse:\n    from enum import Enum\n\n__all__ = [\"Stats\", \"SortKey\", \"FunctionProfile\", \"StatsProfile\"]\n\n_Selector: TypeAlias = str | float | int\n\nif sys.version_info >= (3, 11):\n    class SortKey(StrEnum):\n        CALLS = \"calls\"\n        CUMULATIVE = \"cumulative\"\n        FILENAME = \"filename\"\n        LINE = \"line\"\n        NAME = \"name\"\n        NFL = \"nfl\"\n        PCALLS = \"pcalls\"\n        STDNAME = \"stdname\"\n        TIME = \"time\"\n\nelse:\n    class SortKey(str, Enum):\n        CALLS = \"calls\"\n        CUMULATIVE = \"cumulative\"\n        FILENAME = \"filename\"\n        LINE = \"line\"\n        NAME = \"name\"\n        NFL = \"nfl\"\n        PCALLS = \"pcalls\"\n        STDNAME = \"stdname\"\n        TIME = \"time\"\n\n@dataclass(unsafe_hash=True)\nclass FunctionProfile:\n    ncalls: str\n    tottime: float\n    percall_tottime: float\n    cumtime: float\n    percall_cumtime: float\n    file_name: str\n    line_number: int\n\n@dataclass(unsafe_hash=True)\nclass StatsProfile:\n    total_tt: float\n    func_profiles: dict[str, FunctionProfile]\n\n_SortArgDict: TypeAlias = dict[str, tuple[tuple[tuple[int, int], ...], str]]\n\nclass Stats:\n    sort_arg_dict_default: _SortArgDict\n    def __init__(\n        self,\n        arg: None | str | Profile | _cProfile = None,\n        /,\n        *args: None | str | Profile | _cProfile | Self,\n        stream: IO[Any] | None = None,\n    ) -> None: ...\n    def init(self, arg: None | str | Profile | _cProfile) -> None: ...\n    def load_stats(self, arg: None | str | Profile | _cProfile) -> None: ...\n    def get_top_level_stats(self) -> None: ...\n    def add(self, *arg_list: None | str | Profile | _cProfile | Self) -> Self: ...\n    def dump_stats(self, filename: StrOrBytesPath) -> None: ...\n    def get_sort_arg_defs(self) -> _SortArgDict: ...\n    @overload\n    def sort_stats(self, field: Literal[-1, 0, 1, 2]) -> Self: ...\n    @overload\n    def sort_stats(self, *field: str) -> Self: ...\n    def reverse_order(self) -> Self: ...\n    def strip_dirs(self) -> Self: ...\n    def calc_callees(self) -> None: ...\n    def eval_print_amount(self, sel: _Selector, list: list[str], msg: str) -> tuple[list[str], str]: ...\n    def get_stats_profile(self) -> StatsProfile: ...\n    def get_print_list(self, sel_list: Iterable[_Selector]) -> tuple[int, list[str]]: ...\n    def print_stats(self, *amount: _Selector) -> Self: ...\n    def print_callees(self, *amount: _Selector) -> Self: ...\n    def print_callers(self, *amount: _Selector) -> Self: ...\n    def print_call_heading(self, name_size: int, column_title: str) -> None: ...\n    def print_call_line(self, name_size: int, source: str, call_dict: dict[str, Any], arrow: str = \"->\") -> None: ...\n    def print_title(self) -> None: ...\n    def print_line(self, func: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pty.pyi",
    "content": "import sys\nfrom collections.abc import Callable, Iterable\nfrom typing import Final\nfrom typing_extensions import TypeAlias, deprecated\n\nif sys.platform != \"win32\":\n    __all__ = [\"openpty\", \"fork\", \"spawn\"]\n    _Reader: TypeAlias = Callable[[int], bytes]\n\n    STDIN_FILENO: Final = 0\n    STDOUT_FILENO: Final = 1\n    STDERR_FILENO: Final = 2\n\n    CHILD: Final = 0\n    def openpty() -> tuple[int, int]: ...\n\n    if sys.version_info < (3, 14):\n        if sys.version_info >= (3, 12):\n            @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14. Use `openpty()` instead.\")\n            def master_open() -> tuple[int, str]: ...\n            @deprecated(\"Deprecated since Python 3.12; removed in Python 3.14. Use `openpty()` instead.\")\n            def slave_open(tty_name: str) -> int: ...\n        else:\n            def master_open() -> tuple[int, str]: ...\n            def slave_open(tty_name: str) -> int: ...\n\n    def fork() -> tuple[int, int]: ...\n    def spawn(argv: str | Iterable[str], master_read: _Reader = ..., stdin_read: _Reader = ...) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pwd.pyi",
    "content": "import sys\nfrom _typeshed import structseq\nfrom typing import Any, Final, final\n\nif sys.platform != \"win32\":\n    @final\n    class struct_passwd(structseq[Any], tuple[str, str, int, int, str, str, str]):\n        if sys.version_info >= (3, 10):\n            __match_args__: Final = (\"pw_name\", \"pw_passwd\", \"pw_uid\", \"pw_gid\", \"pw_gecos\", \"pw_dir\", \"pw_shell\")\n\n        @property\n        def pw_name(self) -> str: ...\n        @property\n        def pw_passwd(self) -> str: ...\n        @property\n        def pw_uid(self) -> int: ...\n        @property\n        def pw_gid(self) -> int: ...\n        @property\n        def pw_gecos(self) -> str: ...\n        @property\n        def pw_dir(self) -> str: ...\n        @property\n        def pw_shell(self) -> str: ...\n\n    def getpwall() -> list[struct_passwd]: ...\n    def getpwuid(uid: int, /) -> struct_passwd: ...\n    def getpwnam(name: str, /) -> struct_passwd: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/py_compile.pyi",
    "content": "import enum\nimport sys\nfrom typing import AnyStr\n\n__all__ = [\"compile\", \"main\", \"PyCompileError\", \"PycInvalidationMode\"]\n\nclass PyCompileError(Exception):\n    exc_type_name: str\n    exc_value: BaseException\n    file: str\n    msg: str\n    def __init__(self, exc_type: type[BaseException], exc_value: BaseException, file: str, msg: str = \"\") -> None: ...\n\nclass PycInvalidationMode(enum.Enum):\n    TIMESTAMP = 1\n    CHECKED_HASH = 2\n    UNCHECKED_HASH = 3\n\ndef _get_default_invalidation_mode() -> PycInvalidationMode: ...\ndef compile(\n    file: AnyStr,\n    cfile: AnyStr | None = None,\n    dfile: AnyStr | None = None,\n    doraise: bool = False,\n    optimize: int = -1,\n    invalidation_mode: PycInvalidationMode | None = None,\n    quiet: int = 0,\n) -> AnyStr | None: ...\n\nif sys.version_info >= (3, 10):\n    def main() -> None: ...\n\nelse:\n    def main(args: list[str] | None = None) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pyclbr.pyi",
    "content": "import sys\nfrom collections.abc import Mapping, Sequence\n\n__all__ = [\"readmodule\", \"readmodule_ex\", \"Class\", \"Function\"]\n\nclass _Object:\n    module: str\n    name: str\n    file: int\n    lineno: int\n\n    if sys.version_info >= (3, 10):\n        end_lineno: int | None\n\n    parent: _Object | None\n\n    # This is a dict at runtime, but we're typing it as Mapping to\n    # avoid variance issues in the subclasses\n    children: Mapping[str, _Object]\n\n    if sys.version_info >= (3, 10):\n        def __init__(\n            self, module: str, name: str, file: str, lineno: int, end_lineno: int | None, parent: _Object | None\n        ) -> None: ...\n    else:\n        def __init__(self, module: str, name: str, file: str, lineno: int, parent: _Object | None) -> None: ...\n\nclass Function(_Object):\n    if sys.version_info >= (3, 10):\n        is_async: bool\n\n    parent: Function | Class | None\n    children: dict[str, Class | Function]\n\n    if sys.version_info >= (3, 10):\n        def __init__(\n            self,\n            module: str,\n            name: str,\n            file: str,\n            lineno: int,\n            parent: Function | Class | None = None,\n            is_async: bool = False,\n            *,\n            end_lineno: int | None = None,\n        ) -> None: ...\n    else:\n        def __init__(self, module: str, name: str, file: str, lineno: int, parent: Function | Class | None = None) -> None: ...\n\nclass Class(_Object):\n    super: list[Class | str] | None\n    methods: dict[str, int]\n    parent: Class | None\n    children: dict[str, Class | Function]\n\n    if sys.version_info >= (3, 10):\n        def __init__(\n            self,\n            module: str,\n            name: str,\n            super_: list[Class | str] | None,\n            file: str,\n            lineno: int,\n            parent: Class | None = None,\n            *,\n            end_lineno: int | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self, module: str, name: str, super: list[Class | str] | None, file: str, lineno: int, parent: Class | None = None\n        ) -> None: ...\n\ndef readmodule(module: str, path: Sequence[str] | None = None) -> dict[str, Class]: ...\ndef readmodule_ex(module: str, path: Sequence[str] | None = None) -> dict[str, Class | Function | list[str]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pydoc.pyi",
    "content": "import sys\nfrom _typeshed import OptExcInfo, SupportsWrite, Unused\nfrom abc import abstractmethod\nfrom builtins import list as _list  # \"list\" conflicts with method name\nfrom collections.abc import Callable, Container, Mapping, MutableMapping\nfrom reprlib import Repr\nfrom types import MethodType, ModuleType, TracebackType\nfrom typing import IO, Any, AnyStr, Final, NoReturn, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import TypeGuard, deprecated\n\n__all__ = [\"help\"]\n\n_T = TypeVar(\"_T\")\n\n__author__: Final[str]\n__date__: Final[str]\n__version__: Final[str]\n__credits__: Final[str]\n\n@type_check_only\nclass _Pager(Protocol):\n    def __call__(self, text: str, title: str = \"\") -> None: ...\n\ndef pathdirs() -> list[str]: ...\ndef getdoc(object: object) -> str: ...\ndef splitdoc(doc: AnyStr) -> tuple[AnyStr, AnyStr]: ...\ndef classname(object: object, modname: str) -> str: ...\ndef isdata(object: object) -> bool: ...\ndef replace(text: AnyStr, *pairs: AnyStr) -> AnyStr: ...\ndef cram(text: str, maxlen: int) -> str: ...\ndef stripid(text: str) -> str: ...\ndef allmethods(cl: type) -> MutableMapping[str, MethodType]: ...\ndef visiblename(name: str, all: Container[str] | None = None, obj: object = None) -> bool: ...\ndef classify_class_attrs(object: object) -> list[tuple[str, str, type, str]]: ...\n\nif sys.version_info >= (3, 13):\n    @deprecated(\"Deprecated since Python 3.13.\")\n    def ispackage(path: str) -> bool: ...  # undocumented\n\nelse:\n    def ispackage(path: str) -> bool: ...  # undocumented\n\ndef source_synopsis(file: IO[AnyStr]) -> AnyStr | None: ...\ndef synopsis(filename: str, cache: MutableMapping[str, tuple[int, str]] = {}) -> str | None: ...\n\nclass ErrorDuringImport(Exception):\n    filename: str\n    exc: type[BaseException] | None\n    value: BaseException | None\n    tb: TracebackType | None\n    if sys.version_info >= (3, 12):\n        @overload\n        def __init__(self, filename: str, exc_info: BaseException) -> None: ...\n        @overload\n        @deprecated(\"A tuple value for `exc_info` parameter is deprecated since Python 3.12. Use an exception instance.\")\n        def __init__(self, filename: str, exc_info: OptExcInfo) -> None: ...\n    else:\n        def __init__(self, filename: str, exc_info: OptExcInfo) -> None: ...\n\ndef importfile(path: str) -> ModuleType: ...\ndef safeimport(path: str, forceload: bool = ..., cache: MutableMapping[str, ModuleType] = {}) -> ModuleType | None: ...\n\nclass Doc:\n    PYTHONDOCS: str\n    def document(self, object: object, name: str | None = None, *args: Any) -> str: ...\n    def fail(self, object: object, name: str | None = None, *args: Any) -> NoReturn: ...\n    @abstractmethod\n    def docmodule(self, object: object, name: str | None = None, *args: Any) -> str: ...\n    @abstractmethod\n    def docclass(self, object: object, name: str | None = None, *args: Any) -> str: ...\n    @abstractmethod\n    def docroutine(self, object: object, name: str | None = None, *args: Any) -> str: ...\n    @abstractmethod\n    def docother(self, object: object, name: str | None = None, *args: Any) -> str: ...\n    @abstractmethod\n    def docproperty(self, object: object, name: str | None = None, *args: Any) -> str: ...\n    @abstractmethod\n    def docdata(self, object: object, name: str | None = None, *args: Any) -> str: ...\n    def getdocloc(self, object: object, basedir: str = ...) -> str | None: ...\n\nclass HTMLRepr(Repr):\n    def __init__(self) -> None: ...\n    def escape(self, text: str) -> str: ...\n    def repr(self, object: object) -> str: ...\n    def repr1(self, x: object, level: complex) -> str: ...\n    def repr_string(self, x: str, level: complex) -> str: ...\n    def repr_str(self, x: str, level: complex) -> str: ...\n    def repr_instance(self, x: object, level: complex) -> str: ...\n    def repr_unicode(self, x: AnyStr, level: complex) -> str: ...\n\nclass HTMLDoc(Doc):\n    _repr_instance: HTMLRepr\n    repr = _repr_instance.repr\n    escape = _repr_instance.escape\n    def page(self, title: str, contents: str) -> str: ...\n    if sys.version_info >= (3, 11):\n        def heading(self, title: str, extras: str = \"\") -> str: ...\n        def section(\n            self,\n            title: str,\n            cls: str,\n            contents: str,\n            width: int = 6,\n            prelude: str = \"\",\n            marginalia: str | None = None,\n            gap: str = \"&nbsp;\",\n        ) -> str: ...\n        def multicolumn(self, list: list[_T], format: Callable[[_T], str]) -> str: ...\n    else:\n        def heading(self, title: str, fgcol: str, bgcol: str, extras: str = \"\") -> str: ...\n        def section(\n            self,\n            title: str,\n            fgcol: str,\n            bgcol: str,\n            contents: str,\n            width: int = 6,\n            prelude: str = \"\",\n            marginalia: str | None = None,\n            gap: str = \"&nbsp;\",\n        ) -> str: ...\n        def multicolumn(self, list: list[_T], format: Callable[[_T], str], cols: int = 4) -> str: ...\n\n    def bigsection(self, title: str, *args: Any) -> str: ...\n    def preformat(self, text: str) -> str: ...\n    def grey(self, text: str) -> str: ...\n    def namelink(self, name: str, *dicts: MutableMapping[str, str]) -> str: ...\n    def classlink(self, object: object, modname: str) -> str: ...\n    def modulelink(self, object: object) -> str: ...\n    def modpkglink(self, modpkginfo: tuple[str, str, bool, bool]) -> str: ...\n    def markup(\n        self,\n        text: str,\n        escape: Callable[[str], str] | None = None,\n        funcs: Mapping[str, str] = {},\n        classes: Mapping[str, str] = {},\n        methods: Mapping[str, str] = {},\n    ) -> str: ...\n    def formattree(\n        self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = None\n    ) -> str: ...\n    def docmodule(self, object: object, name: str | None = None, mod: str | None = None, *ignored: Unused) -> str: ...\n    def docclass(\n        self,\n        object: object,\n        name: str | None = None,\n        mod: str | None = None,\n        funcs: Mapping[str, str] = {},\n        classes: Mapping[str, str] = {},\n        *ignored: Unused,\n    ) -> str: ...\n    def formatvalue(self, object: object) -> str: ...\n    def docother(self, object: object, name: str | None = None, mod: Any | None = None, *ignored: Unused) -> str: ...\n    if sys.version_info >= (3, 11):\n        def docroutine(  # type: ignore[override]\n            self,\n            object: object,\n            name: str | None = None,\n            mod: str | None = None,\n            funcs: Mapping[str, str] = {},\n            classes: Mapping[str, str] = {},\n            methods: Mapping[str, str] = {},\n            cl: type | None = None,\n            homecls: type | None = None,\n        ) -> str: ...\n        def docproperty(\n            self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None, *ignored: Unused\n        ) -> str: ...\n        def docdata(\n            self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None, *ignored: Unused\n        ) -> str: ...\n    else:\n        def docroutine(  # type: ignore[override]\n            self,\n            object: object,\n            name: str | None = None,\n            mod: str | None = None,\n            funcs: Mapping[str, str] = {},\n            classes: Mapping[str, str] = {},\n            methods: Mapping[str, str] = {},\n            cl: type | None = None,\n        ) -> str: ...\n        def docproperty(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: ...  # type: ignore[override]\n        def docdata(self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None) -> str: ...  # type: ignore[override]\n    if sys.version_info >= (3, 11):\n        def parentlink(self, object: type | ModuleType, modname: str) -> str: ...\n\n    def index(self, dir: str, shadowed: MutableMapping[str, bool] | None = None) -> str: ...\n    def filelink(self, url: str, path: str) -> str: ...\n\nclass TextRepr(Repr):\n    def __init__(self) -> None: ...\n    def repr1(self, x: object, level: complex) -> str: ...\n    def repr_string(self, x: str, level: complex) -> str: ...\n    def repr_str(self, x: str, level: complex) -> str: ...\n    def repr_instance(self, x: object, level: complex) -> str: ...\n\nclass TextDoc(Doc):\n    _repr_instance: TextRepr\n    repr = _repr_instance.repr\n    def bold(self, text: str) -> str: ...\n    def indent(self, text: str, prefix: str = \"    \") -> str: ...\n    def section(self, title: str, contents: str) -> str: ...\n    def formattree(\n        self, tree: list[tuple[type, tuple[type, ...]] | list[Any]], modname: str, parent: type | None = None, prefix: str = \"\"\n    ) -> str: ...\n    def docclass(self, object: object, name: str | None = None, mod: str | None = None, *ignored: Unused) -> str: ...\n    def formatvalue(self, object: object) -> str: ...\n    if sys.version_info >= (3, 11):\n        def docroutine(  # type: ignore[override]\n            self,\n            object: object,\n            name: str | None = None,\n            mod: str | None = None,\n            cl: Any | None = None,\n            homecls: Any | None = None,\n        ) -> str: ...\n        def docmodule(self, object: object, name: str | None = None, mod: Any | None = None, *ignored: Unused) -> str: ...\n        def docproperty(\n            self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None, *ignored: Unused\n        ) -> str: ...\n        def docdata(\n            self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None, *ignored: Unused\n        ) -> str: ...\n        def docother(\n            self,\n            object: object,\n            name: str | None = None,\n            mod: str | None = None,\n            parent: str | None = None,\n            *ignored: Unused,\n            maxlen: int | None = None,\n            doc: Any | None = None,\n        ) -> str: ...\n    else:\n        def docroutine(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: ...  # type: ignore[override]\n        def docmodule(self, object: object, name: str | None = None, mod: Any | None = None) -> str: ...  # type: ignore[override]\n        def docproperty(self, object: object, name: str | None = None, mod: Any | None = None, cl: Any | None = None) -> str: ...  # type: ignore[override]\n        def docdata(self, object: object, name: str | None = None, mod: str | None = None, cl: Any | None = None) -> str: ...  # type: ignore[override]\n        def docother(  # type: ignore[override]\n            self,\n            object: object,\n            name: str | None = None,\n            mod: str | None = None,\n            parent: str | None = None,\n            maxlen: int | None = None,\n            doc: Any | None = None,\n        ) -> str: ...\n\nif sys.version_info >= (3, 13):\n    def pager(text: str, title: str = \"\") -> None: ...\n\nelse:\n    def pager(text: str) -> None: ...\n\ndef plain(text: str) -> str: ...\ndef describe(thing: Any) -> str: ...\ndef locate(path: str, forceload: bool = ...) -> object: ...\n\nif sys.version_info >= (3, 13):\n    def get_pager() -> _Pager: ...\n    def pipe_pager(text: str, cmd: str, title: str = \"\") -> None: ...\n    def tempfile_pager(text: str, cmd: str, title: str = \"\") -> None: ...\n    def tty_pager(text: str, title: str = \"\") -> None: ...\n    def plain_pager(text: str, title: str = \"\") -> None: ...\n\n    # For backwards compatibility.\n    getpager = get_pager\n    pipepager = pipe_pager\n    tempfilepager = tempfile_pager\n    ttypager = tty_pager\n    plainpager = plain_pager\nelse:\n    def getpager() -> Callable[[str], None]: ...\n    def pipepager(text: str, cmd: str) -> None: ...\n    def tempfilepager(text: str, cmd: str) -> None: ...\n    def ttypager(text: str) -> None: ...\n    def plainpager(text: str) -> None: ...\n\ntext: TextDoc\nhtml: HTMLDoc\n\ndef resolve(thing: str | object, forceload: bool = ...) -> tuple[object, str] | None: ...\ndef render_doc(\n    thing: str | object, title: str = \"Python Library Documentation: %s\", forceload: bool = ..., renderer: Doc | None = None\n) -> str: ...\n\nif sys.version_info >= (3, 11):\n    def doc(\n        thing: str | object,\n        title: str = \"Python Library Documentation: %s\",\n        forceload: bool = ...,\n        output: SupportsWrite[str] | None = None,\n        is_cli: bool = False,\n    ) -> None: ...\n\nelse:\n    def doc(\n        thing: str | object,\n        title: str = \"Python Library Documentation: %s\",\n        forceload: bool = ...,\n        output: SupportsWrite[str] | None = None,\n    ) -> None: ...\n\ndef writedoc(thing: str | object, forceload: bool = ...) -> None: ...\ndef writedocs(dir: str, pkgpath: str = \"\", done: Any | None = None) -> None: ...\n\nclass Helper:\n    keywords: dict[str, str | tuple[str, str]]\n    symbols: dict[str, str]\n    topics: dict[str, str | tuple[str, ...]]\n    def __init__(self, input: IO[str] | None = None, output: IO[str] | None = None) -> None: ...\n    @property\n    def input(self) -> IO[str]: ...\n    @property\n    def output(self) -> IO[str]: ...\n    def __call__(self, request: str | Helper | object = ...) -> None: ...\n    def interact(self) -> None: ...\n    def getline(self, prompt: str) -> str: ...\n    if sys.version_info >= (3, 11):\n        def help(self, request: Any, is_cli: bool = False) -> None: ...\n    else:\n        def help(self, request: Any) -> None: ...\n\n    def intro(self) -> None: ...\n    def list(self, items: _list[str], columns: int = 4, width: int = 80) -> None: ...\n    def listkeywords(self) -> None: ...\n    def listsymbols(self) -> None: ...\n    def listtopics(self) -> None: ...\n    def showtopic(self, topic: str, more_xrefs: str = \"\") -> None: ...\n    def showsymbol(self, symbol: str) -> None: ...\n    def listmodules(self, key: str = \"\") -> None: ...\n\nhelp: Helper\n\nclass ModuleScanner:\n    quit: bool\n    def run(\n        self,\n        callback: Callable[[str | None, str, str], object],\n        key: str | None = None,\n        completer: Callable[[], object] | None = None,\n        onerror: Callable[[str], object] | None = None,\n    ) -> None: ...\n\ndef apropos(key: str) -> None: ...\ndef ispath(x: object) -> TypeGuard[str]: ...\ndef cli() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pydoc_data/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/pydoc_data/module_docs.pyi",
    "content": "from typing import Final\n\nmodule_docs: Final[dict[str, str]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pydoc_data/topics.pyi",
    "content": "from typing import Final\n\ntopics: Final[dict[str, str]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pyexpat/__init__.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer, SupportsRead\nfrom collections.abc import Callable\nfrom pyexpat import errors as errors, model as model\nfrom typing import Any, Final, final\nfrom typing_extensions import CapsuleType, TypeAlias\nfrom xml.parsers.expat import ExpatError as ExpatError\n\nEXPAT_VERSION: Final[str]  # undocumented\nversion_info: tuple[int, int, int]  # undocumented\nnative_encoding: str  # undocumented\nfeatures: list[tuple[str, int]]  # undocumented\n\nerror = ExpatError\nXML_PARAM_ENTITY_PARSING_NEVER: Final = 0\nXML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE: Final = 1\nXML_PARAM_ENTITY_PARSING_ALWAYS: Final = 2\n\n_Model: TypeAlias = tuple[int, int, str | None, tuple[Any, ...]]\n\n@final\nclass XMLParserType:\n    def Parse(self, data: str | ReadableBuffer, isfinal: bool = False, /) -> int: ...\n    def ParseFile(self, file: SupportsRead[bytes], /) -> int: ...\n    def SetBase(self, base: str, /) -> None: ...\n    def GetBase(self) -> str | None: ...\n    def GetInputContext(self) -> bytes | None: ...\n    def ExternalEntityParserCreate(self, context: str | None, encoding: str = ..., /) -> XMLParserType: ...\n    def SetParamEntityParsing(self, flag: int, /) -> int: ...\n    def UseForeignDTD(self, flag: bool = True, /) -> None: ...\n    def GetReparseDeferralEnabled(self) -> bool: ...\n    def SetReparseDeferralEnabled(self, enabled: bool, /) -> None: ...\n    if sys.version_info >= (3, 10):\n        # Added in Python 3.10.20, 3.11.15, 3.12.3, 3.13.10, 3.14.1\n        def SetAllocTrackerActivationThreshold(self, threshold: int, /) -> None: ...\n        def SetAllocTrackerMaximumAmplification(self, max_factor: float, /) -> None: ...\n\n    @property\n    def intern(self) -> dict[str, str]: ...\n    buffer_size: int\n    buffer_text: bool\n    buffer_used: int\n    namespace_prefixes: bool  # undocumented\n    ordered_attributes: bool\n    specified_attributes: bool\n    ErrorByteIndex: int\n    ErrorCode: int\n    ErrorColumnNumber: int\n    ErrorLineNumber: int\n    CurrentByteIndex: int\n    CurrentColumnNumber: int\n    CurrentLineNumber: int\n    XmlDeclHandler: Callable[[str, str | None, int], Any] | None\n    StartDoctypeDeclHandler: Callable[[str, str | None, str | None, bool], Any] | None\n    EndDoctypeDeclHandler: Callable[[], Any] | None\n    ElementDeclHandler: Callable[[str, _Model], Any] | None\n    AttlistDeclHandler: Callable[[str, str, str, str | None, bool], Any] | None\n    StartElementHandler: (\n        Callable[[str, dict[str, str]], Any]\n        | Callable[[str, list[str]], Any]\n        | Callable[[str, dict[str, str], list[str]], Any]\n        | None\n    )\n    EndElementHandler: Callable[[str], Any] | None\n    ProcessingInstructionHandler: Callable[[str, str], Any] | None\n    CharacterDataHandler: Callable[[str], Any] | None\n    UnparsedEntityDeclHandler: Callable[[str, str | None, str, str | None, str], Any] | None\n    EntityDeclHandler: Callable[[str, bool, str | None, str | None, str, str | None, str | None], Any] | None\n    NotationDeclHandler: Callable[[str, str | None, str, str | None], Any] | None\n    StartNamespaceDeclHandler: Callable[[str, str], Any] | None\n    EndNamespaceDeclHandler: Callable[[str], Any] | None\n    CommentHandler: Callable[[str], Any] | None\n    StartCdataSectionHandler: Callable[[], Any] | None\n    EndCdataSectionHandler: Callable[[], Any] | None\n    DefaultHandler: Callable[[str], Any] | None\n    DefaultHandlerExpand: Callable[[str], Any] | None\n    NotStandaloneHandler: Callable[[], int] | None\n    ExternalEntityRefHandler: Callable[[str, str | None, str | None, str | None], int] | None\n    SkippedEntityHandler: Callable[[str, bool], Any] | None\n\ndef ErrorString(code: int, /) -> str: ...\n\n# intern is undocumented\ndef ParserCreate(\n    encoding: str | None = None, namespace_separator: str | None = None, intern: dict[str, Any] | None = None\n) -> XMLParserType: ...\n\nexpat_CAPI: CapsuleType\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pyexpat/errors.pyi",
    "content": "import sys\nfrom typing import Final\nfrom typing_extensions import LiteralString\n\ncodes: dict[str, int]\nmessages: dict[int, str]\n\nXML_ERROR_ABORTED: Final[LiteralString]\nXML_ERROR_ASYNC_ENTITY: Final[LiteralString]\nXML_ERROR_ATTRIBUTE_EXTERNAL_ENTITY_REF: Final[LiteralString]\nXML_ERROR_BAD_CHAR_REF: Final[LiteralString]\nXML_ERROR_BINARY_ENTITY_REF: Final[LiteralString]\nXML_ERROR_CANT_CHANGE_FEATURE_ONCE_PARSING: Final[LiteralString]\nXML_ERROR_DUPLICATE_ATTRIBUTE: Final[LiteralString]\nXML_ERROR_ENTITY_DECLARED_IN_PE: Final[LiteralString]\nXML_ERROR_EXTERNAL_ENTITY_HANDLING: Final[LiteralString]\nXML_ERROR_FEATURE_REQUIRES_XML_DTD: Final[LiteralString]\nXML_ERROR_FINISHED: Final[LiteralString]\nXML_ERROR_INCOMPLETE_PE: Final[LiteralString]\nXML_ERROR_INCORRECT_ENCODING: Final[LiteralString]\nXML_ERROR_INVALID_TOKEN: Final[LiteralString]\nXML_ERROR_JUNK_AFTER_DOC_ELEMENT: Final[LiteralString]\nXML_ERROR_MISPLACED_XML_PI: Final[LiteralString]\nXML_ERROR_NOT_STANDALONE: Final[LiteralString]\nXML_ERROR_NOT_SUSPENDED: Final[LiteralString]\nXML_ERROR_NO_ELEMENTS: Final[LiteralString]\nXML_ERROR_NO_MEMORY: Final[LiteralString]\nXML_ERROR_PARAM_ENTITY_REF: Final[LiteralString]\nXML_ERROR_PARTIAL_CHAR: Final[LiteralString]\nXML_ERROR_PUBLICID: Final[LiteralString]\nXML_ERROR_RECURSIVE_ENTITY_REF: Final[LiteralString]\nXML_ERROR_SUSPENDED: Final[LiteralString]\nXML_ERROR_SUSPEND_PE: Final[LiteralString]\nXML_ERROR_SYNTAX: Final[LiteralString]\nXML_ERROR_TAG_MISMATCH: Final[LiteralString]\nXML_ERROR_TEXT_DECL: Final[LiteralString]\nXML_ERROR_UNBOUND_PREFIX: Final[LiteralString]\nXML_ERROR_UNCLOSED_CDATA_SECTION: Final[LiteralString]\nXML_ERROR_UNCLOSED_TOKEN: Final[LiteralString]\nXML_ERROR_UNDECLARING_PREFIX: Final[LiteralString]\nXML_ERROR_UNDEFINED_ENTITY: Final[LiteralString]\nXML_ERROR_UNEXPECTED_STATE: Final[LiteralString]\nXML_ERROR_UNKNOWN_ENCODING: Final[LiteralString]\nXML_ERROR_XML_DECL: Final[LiteralString]\nif sys.version_info >= (3, 11):\n    XML_ERROR_RESERVED_PREFIX_XML: Final[LiteralString]\n    XML_ERROR_RESERVED_PREFIX_XMLNS: Final[LiteralString]\n    XML_ERROR_RESERVED_NAMESPACE_URI: Final[LiteralString]\n    XML_ERROR_INVALID_ARGUMENT: Final[LiteralString]\n    XML_ERROR_NO_BUFFER: Final[LiteralString]\n    XML_ERROR_AMPLIFICATION_LIMIT_BREACH: Final[LiteralString]\nif sys.version_info >= (3, 14):\n    XML_ERROR_NOT_STARTED: Final[LiteralString]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/pyexpat/model.pyi",
    "content": "from typing import Final\n\nXML_CTYPE_ANY: Final = 2\nXML_CTYPE_EMPTY: Final = 1\nXML_CTYPE_MIXED: Final = 3\nXML_CTYPE_NAME: Final = 4\nXML_CTYPE_CHOICE: Final = 5\nXML_CTYPE_SEQ: Final = 6\n\nXML_CQUANT_NONE: Final = 0\nXML_CQUANT_OPT: Final = 1\nXML_CQUANT_REP: Final = 2\nXML_CQUANT_PLUS: Final = 3\n"
  },
  {
    "path": "mypy/typeshed/stdlib/queue.pyi",
    "content": "import sys\nfrom _queue import Empty as Empty, SimpleQueue as SimpleQueue\nfrom _typeshed import SupportsRichComparisonT\nfrom threading import Condition, Lock\nfrom types import GenericAlias\nfrom typing import Any, Generic, TypeVar\n\n__all__ = [\"Empty\", \"Full\", \"Queue\", \"PriorityQueue\", \"LifoQueue\", \"SimpleQueue\"]\nif sys.version_info >= (3, 13):\n    __all__ += [\"ShutDown\"]\n\n_T = TypeVar(\"_T\")\n\nclass Full(Exception): ...\n\nif sys.version_info >= (3, 13):\n    class ShutDown(Exception): ...\n\nclass Queue(Generic[_T]):\n    maxsize: int\n\n    mutex: Lock  # undocumented\n    not_empty: Condition  # undocumented\n    not_full: Condition  # undocumented\n    all_tasks_done: Condition  # undocumented\n    unfinished_tasks: int  # undocumented\n    if sys.version_info >= (3, 13):\n        is_shutdown: bool  # undocumented\n    # Despite the fact that `queue` has `deque` type,\n    # we treat it as `Any` to allow different implementations in subtypes.\n    queue: Any  # undocumented\n    def __init__(self, maxsize: int = 0) -> None: ...\n    def _init(self, maxsize: int) -> None: ...\n    def empty(self) -> bool: ...\n    def full(self) -> bool: ...\n    def get(self, block: bool = True, timeout: float | None = None) -> _T: ...\n    def get_nowait(self) -> _T: ...\n    if sys.version_info >= (3, 13):\n        def shutdown(self, immediate: bool = False) -> None: ...\n\n    def _get(self) -> _T: ...\n    def put(self, item: _T, block: bool = True, timeout: float | None = None) -> None: ...\n    def put_nowait(self, item: _T) -> None: ...\n    def _put(self, item: _T) -> None: ...\n    def join(self) -> None: ...\n    def qsize(self) -> int: ...\n    def _qsize(self) -> int: ...\n    def task_done(self) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass PriorityQueue(Queue[SupportsRichComparisonT]):\n    queue: list[SupportsRichComparisonT]\n\nclass LifoQueue(Queue[_T]):\n    queue: list[_T]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/quopri.pyi",
    "content": "from _typeshed import ReadableBuffer, SupportsNoArgReadline, SupportsRead, SupportsWrite\nfrom typing import Protocol, type_check_only\n\n__all__ = [\"encode\", \"decode\", \"encodestring\", \"decodestring\"]\n\n@type_check_only\nclass _Input(SupportsRead[bytes], SupportsNoArgReadline[bytes], Protocol): ...\n\ndef encode(input: _Input, output: SupportsWrite[bytes], quotetabs: int, header: bool = False) -> None: ...\ndef encodestring(s: ReadableBuffer, quotetabs: bool = False, header: bool = False) -> bytes: ...\ndef decode(input: _Input, output: SupportsWrite[bytes], header: bool = False) -> None: ...\ndef decodestring(s: str | ReadableBuffer, header: bool = False) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/random.pyi",
    "content": "import _random\nimport sys\nfrom _typeshed import SupportsLenAndGetItem\nfrom collections.abc import Callable, Iterable, MutableSequence, Sequence, Set as AbstractSet\nfrom fractions import Fraction\nfrom typing import Any, ClassVar, NoReturn, TypeVar, overload\nfrom typing_extensions import Self, deprecated\n\n__all__ = [\n    \"Random\",\n    \"seed\",\n    \"random\",\n    \"uniform\",\n    \"randint\",\n    \"choice\",\n    \"sample\",\n    \"randrange\",\n    \"shuffle\",\n    \"normalvariate\",\n    \"lognormvariate\",\n    \"expovariate\",\n    \"vonmisesvariate\",\n    \"gammavariate\",\n    \"triangular\",\n    \"gauss\",\n    \"betavariate\",\n    \"paretovariate\",\n    \"weibullvariate\",\n    \"getstate\",\n    \"setstate\",\n    \"getrandbits\",\n    \"choices\",\n    \"SystemRandom\",\n    \"randbytes\",\n]\n\nif sys.version_info >= (3, 12):\n    __all__ += [\"binomialvariate\"]\n\n_T = TypeVar(\"_T\")\n\nclass Random(_random.Random):\n    VERSION: ClassVar[int]\n    def __init__(self, x: int | float | str | bytes | bytearray | None = None) -> None: ...  # noqa: Y041\n    # Using other `seed` types is deprecated since 3.9 and removed in 3.11\n    # Ignore Y041, since random.seed doesn't treat int like a float subtype. Having an explicit\n    # int better documents conventional usage of random.seed.\n    if sys.version_info < (3, 10):\n        # this is a workaround for pyright correctly flagging an inconsistent inherited constructor, see #14624\n        def __new__(cls, x: int | float | str | bytes | bytearray | None = None) -> Self: ...  # noqa: Y041\n\n    def seed(self, a: int | float | str | bytes | bytearray | None = None, version: int = 2) -> None: ...  # type: ignore[override]  # noqa: Y041\n    def getstate(self) -> tuple[Any, ...]: ...\n    def setstate(self, state: tuple[Any, ...]) -> None: ...\n    def randrange(self, start: int, stop: int | None = None, step: int = 1) -> int: ...\n    def randint(self, a: int, b: int) -> int: ...\n    def randbytes(self, n: int) -> bytes: ...\n    def choice(self, seq: SupportsLenAndGetItem[_T]) -> _T: ...\n    def choices(\n        self,\n        population: SupportsLenAndGetItem[_T],\n        weights: Sequence[float | Fraction] | None = None,\n        *,\n        cum_weights: Sequence[float | Fraction] | None = None,\n        k: int = 1,\n    ) -> list[_T]: ...\n    if sys.version_info >= (3, 11):\n        def shuffle(self, x: MutableSequence[Any]) -> None: ...\n    else:\n        @overload\n        def shuffle(self, x: MutableSequence[Any]) -> None: ...\n        @overload\n        @deprecated(\"The `random` parameter is deprecated since Python 3.9; removed in Python 3.11.\")\n        def shuffle(self, x: MutableSequence[Any], random: Callable[[], float] | None = None) -> None: ...\n    if sys.version_info >= (3, 11):\n        def sample(self, population: Sequence[_T], k: int, *, counts: Iterable[int] | None = None) -> list[_T]: ...\n    else:\n        def sample(\n            self, population: Sequence[_T] | AbstractSet[_T], k: int, *, counts: Iterable[int] | None = None\n        ) -> list[_T]: ...\n\n    def uniform(self, a: float, b: float) -> float: ...\n    def triangular(self, low: float = 0.0, high: float = 1.0, mode: float | None = None) -> float: ...\n    if sys.version_info >= (3, 12):\n        def binomialvariate(self, n: int = 1, p: float = 0.5) -> int: ...\n\n    def betavariate(self, alpha: float, beta: float) -> float: ...\n    if sys.version_info >= (3, 12):\n        def expovariate(self, lambd: float = 1.0) -> float: ...\n    else:\n        def expovariate(self, lambd: float) -> float: ...\n\n    def gammavariate(self, alpha: float, beta: float) -> float: ...\n    if sys.version_info >= (3, 11):\n        def gauss(self, mu: float = 0.0, sigma: float = 1.0) -> float: ...\n        def normalvariate(self, mu: float = 0.0, sigma: float = 1.0) -> float: ...\n    else:\n        def gauss(self, mu: float, sigma: float) -> float: ...\n        def normalvariate(self, mu: float, sigma: float) -> float: ...\n\n    def lognormvariate(self, mu: float, sigma: float) -> float: ...\n    def vonmisesvariate(self, mu: float, kappa: float) -> float: ...\n    def paretovariate(self, alpha: float) -> float: ...\n    def weibullvariate(self, alpha: float, beta: float) -> float: ...\n\n# SystemRandom is not implemented for all OS's; good on Windows & Linux\nclass SystemRandom(Random):\n    def getrandbits(self, k: int) -> int: ...  # k can be passed by keyword\n    def getstate(self, *args: Any, **kwds: Any) -> NoReturn: ...\n    def setstate(self, *args: Any, **kwds: Any) -> NoReturn: ...\n\n_inst: Random\nseed = _inst.seed\nrandom = _inst.random\nuniform = _inst.uniform\ntriangular = _inst.triangular\nrandint = _inst.randint\nchoice = _inst.choice\nrandrange = _inst.randrange\nsample = _inst.sample\nshuffle = _inst.shuffle\nchoices = _inst.choices\nnormalvariate = _inst.normalvariate\nlognormvariate = _inst.lognormvariate\nexpovariate = _inst.expovariate\nvonmisesvariate = _inst.vonmisesvariate\ngammavariate = _inst.gammavariate\ngauss = _inst.gauss\nif sys.version_info >= (3, 12):\n    binomialvariate = _inst.binomialvariate\nbetavariate = _inst.betavariate\nparetovariate = _inst.paretovariate\nweibullvariate = _inst.weibullvariate\ngetstate = _inst.getstate\nsetstate = _inst.setstate\ngetrandbits = _inst.getrandbits\nrandbytes = _inst.randbytes\n"
  },
  {
    "path": "mypy/typeshed/stdlib/re.pyi",
    "content": "import enum\nimport sre_compile\nimport sre_constants\nimport sys\nfrom _typeshed import MaybeNone, ReadableBuffer\nfrom collections.abc import Callable, Iterator, Mapping\nfrom types import GenericAlias\nfrom typing import Any, AnyStr, Final, Generic, Literal, TypeVar, final, overload\nfrom typing_extensions import TypeAlias, deprecated\n\n__all__ = [\n    \"match\",\n    \"fullmatch\",\n    \"search\",\n    \"sub\",\n    \"subn\",\n    \"split\",\n    \"findall\",\n    \"finditer\",\n    \"compile\",\n    \"purge\",\n    \"escape\",\n    \"error\",\n    \"A\",\n    \"I\",\n    \"L\",\n    \"M\",\n    \"S\",\n    \"X\",\n    \"U\",\n    \"ASCII\",\n    \"IGNORECASE\",\n    \"LOCALE\",\n    \"MULTILINE\",\n    \"DOTALL\",\n    \"VERBOSE\",\n    \"UNICODE\",\n    \"Match\",\n    \"Pattern\",\n]\nif sys.version_info < (3, 13):\n    __all__ += [\"template\"]\n\nif sys.version_info >= (3, 11):\n    __all__ += [\"NOFLAG\", \"RegexFlag\"]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"PatternError\"]\n\n    PatternError = sre_constants.error\n\n_T = TypeVar(\"_T\")\n\n# The implementation defines this in re._constants (version_info >= 3, 11) or\n# sre_constants. Typeshed has it here because its __module__ attribute is set to \"re\".\nclass error(Exception):\n    msg: str\n    pattern: str | bytes | None\n    pos: int | None\n    lineno: int\n    colno: int\n    def __init__(self, msg: str, pattern: str | bytes | None = None, pos: int | None = None) -> None: ...\n\n@final\nclass Match(Generic[AnyStr]):\n    @property\n    def pos(self) -> int: ...\n    @property\n    def endpos(self) -> int: ...\n    @property\n    def lastindex(self) -> int | None: ...\n    @property\n    def lastgroup(self) -> str | None: ...\n    @property\n    def string(self) -> AnyStr: ...\n\n    # The regular expression object whose match() or search() method produced\n    # this match instance.\n    @property\n    def re(self) -> Pattern[AnyStr]: ...\n    @overload\n    def expand(self: Match[str], template: str) -> str: ...\n    @overload\n    def expand(self: Match[bytes], template: ReadableBuffer) -> bytes: ...\n    @overload\n    def expand(self, template: AnyStr) -> AnyStr: ...\n    # group() returns \"AnyStr\" or \"AnyStr | None\", depending on the pattern.\n    @overload\n    def group(self, group: Literal[0] = 0, /) -> AnyStr: ...\n    @overload\n    def group(self, group: str | int, /) -> AnyStr | MaybeNone: ...\n    @overload\n    def group(self, group1: str | int, group2: str | int, /, *groups: str | int) -> tuple[AnyStr | MaybeNone, ...]: ...\n    # Each item of groups()'s return tuple is either \"AnyStr\" or\n    # \"AnyStr | None\", depending on the pattern.\n    @overload\n    def groups(self) -> tuple[AnyStr | MaybeNone, ...]: ...\n    @overload\n    def groups(self, default: _T) -> tuple[AnyStr | _T, ...]: ...\n    # Each value in groupdict()'s return dict is either \"AnyStr\" or\n    # \"AnyStr | None\", depending on the pattern.\n    @overload\n    def groupdict(self) -> dict[str, AnyStr | MaybeNone]: ...\n    @overload\n    def groupdict(self, default: _T) -> dict[str, AnyStr | _T]: ...\n    def start(self, group: int | str = 0, /) -> int: ...\n    def end(self, group: int | str = 0, /) -> int: ...\n    def span(self, group: int | str = 0, /) -> tuple[int, int]: ...\n    @property\n    def regs(self) -> tuple[tuple[int, int], ...]: ...  # undocumented\n    # __getitem__() returns \"AnyStr\" or \"AnyStr | None\", depending on the pattern.\n    @overload\n    def __getitem__(self, key: Literal[0], /) -> AnyStr: ...\n    @overload\n    def __getitem__(self, key: int | str, /) -> AnyStr | MaybeNone: ...\n    def __copy__(self) -> Match[AnyStr]: ...\n    def __deepcopy__(self, memo: Any, /) -> Match[AnyStr]: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@final\nclass Pattern(Generic[AnyStr]):\n    @property\n    def flags(self) -> int: ...\n    @property\n    def groupindex(self) -> Mapping[str, int]: ...\n    @property\n    def groups(self) -> int: ...\n    @property\n    def pattern(self) -> AnyStr: ...\n    @overload\n    def search(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ...\n    @overload\n    def search(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> Match[bytes] | None: ...\n    @overload\n    def search(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ...\n    @overload\n    def match(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ...\n    @overload\n    def match(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> Match[bytes] | None: ...\n    @overload\n    def match(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ...\n    @overload\n    def fullmatch(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Match[str] | None: ...\n    @overload\n    def fullmatch(\n        self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize\n    ) -> Match[bytes] | None: ...\n    @overload\n    def fullmatch(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Match[AnyStr] | None: ...\n    @overload\n    def split(self: Pattern[str], string: str, maxsplit: int = 0) -> list[str | MaybeNone]: ...\n    @overload\n    def split(self: Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0) -> list[bytes | MaybeNone]: ...\n    @overload\n    def split(self, string: AnyStr, maxsplit: int = 0) -> list[AnyStr | MaybeNone]: ...\n    # return type depends on the number of groups in the pattern\n    @overload\n    def findall(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ...\n    @overload\n    def findall(self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize) -> list[Any]: ...\n    @overload\n    def findall(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> list[AnyStr]: ...\n    @overload\n    def finditer(self: Pattern[str], string: str, pos: int = 0, endpos: int = sys.maxsize) -> Iterator[Match[str]]: ...\n    @overload\n    def finditer(\n        self: Pattern[bytes], string: ReadableBuffer, pos: int = 0, endpos: int = sys.maxsize\n    ) -> Iterator[Match[bytes]]: ...\n    @overload\n    def finditer(self, string: AnyStr, pos: int = 0, endpos: int = sys.maxsize) -> Iterator[Match[AnyStr]]: ...\n    @overload\n    def sub(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0) -> str: ...\n    @overload\n    def sub(\n        self: Pattern[bytes],\n        repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer],\n        string: ReadableBuffer,\n        count: int = 0,\n    ) -> bytes: ...\n    @overload\n    def sub(self, repl: AnyStr | Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = 0) -> AnyStr: ...\n    @overload\n    def subn(self: Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0) -> tuple[str, int]: ...\n    @overload\n    def subn(\n        self: Pattern[bytes],\n        repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer],\n        string: ReadableBuffer,\n        count: int = 0,\n    ) -> tuple[bytes, int]: ...\n    @overload\n    def subn(self, repl: AnyStr | Callable[[Match[AnyStr]], AnyStr], string: AnyStr, count: int = 0) -> tuple[AnyStr, int]: ...\n    def __copy__(self) -> Pattern[AnyStr]: ...\n    def __deepcopy__(self, memo: Any, /) -> Pattern[AnyStr]: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n# ----- re variables and constants -----\n\nclass RegexFlag(enum.IntFlag):\n    A = sre_compile.SRE_FLAG_ASCII\n    ASCII = A\n    DEBUG = sre_compile.SRE_FLAG_DEBUG\n    I = sre_compile.SRE_FLAG_IGNORECASE\n    IGNORECASE = I\n    L = sre_compile.SRE_FLAG_LOCALE\n    LOCALE = L\n    M = sre_compile.SRE_FLAG_MULTILINE\n    MULTILINE = M\n    S = sre_compile.SRE_FLAG_DOTALL\n    DOTALL = S\n    X = sre_compile.SRE_FLAG_VERBOSE\n    VERBOSE = X\n    U = sre_compile.SRE_FLAG_UNICODE\n    UNICODE = U\n    if sys.version_info < (3, 13):\n        T = sre_compile.SRE_FLAG_TEMPLATE\n        TEMPLATE = T\n    if sys.version_info >= (3, 11):\n        NOFLAG = 0\n\nA: Final = RegexFlag.A\nASCII: Final = RegexFlag.ASCII\nDEBUG: Final = RegexFlag.DEBUG\nI: Final = RegexFlag.I\nIGNORECASE: Final = RegexFlag.IGNORECASE\nL: Final = RegexFlag.L\nLOCALE: Final = RegexFlag.LOCALE\nM: Final = RegexFlag.M\nMULTILINE: Final = RegexFlag.MULTILINE\nS: Final = RegexFlag.S\nDOTALL: Final = RegexFlag.DOTALL\nX: Final = RegexFlag.X\nVERBOSE: Final = RegexFlag.VERBOSE\nU: Final = RegexFlag.U\nUNICODE: Final = RegexFlag.UNICODE\nif sys.version_info < (3, 13):\n    T: Final = RegexFlag.T\n    TEMPLATE: Final = RegexFlag.TEMPLATE\nif sys.version_info >= (3, 11):\n    NOFLAG: Final = RegexFlag.NOFLAG\n_FlagsType: TypeAlias = int | RegexFlag\n\n# Type-wise the compile() overloads are unnecessary, they could also be modeled using\n# unions in the parameter types. However mypy has a bug regarding TypeVar\n# constraints (https://github.com/python/mypy/issues/11880),\n# which limits us here because AnyStr is a constrained TypeVar.\n\n# pattern arguments do *not* accept arbitrary buffers such as bytearray,\n# because the pattern must be hashable.\n@overload\ndef compile(pattern: AnyStr, flags: _FlagsType = 0) -> Pattern[AnyStr]: ...\n@overload\ndef compile(pattern: Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ...\n@overload\ndef search(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ...\n@overload\ndef search(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ...\n@overload\ndef match(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ...\n@overload\ndef match(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ...\n@overload\ndef fullmatch(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Match[str] | None: ...\n@overload\ndef fullmatch(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Match[bytes] | None: ...\n@overload\ndef split(pattern: str | Pattern[str], string: str, maxsplit: int = 0, flags: _FlagsType = 0) -> list[str | MaybeNone]: ...\n@overload\ndef split(\n    pattern: bytes | Pattern[bytes], string: ReadableBuffer, maxsplit: int = 0, flags: _FlagsType = 0\n) -> list[bytes | MaybeNone]: ...\n@overload\ndef findall(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> list[Any]: ...\n@overload\ndef findall(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> list[Any]: ...\n@overload\ndef finditer(pattern: str | Pattern[str], string: str, flags: _FlagsType = 0) -> Iterator[Match[str]]: ...\n@overload\ndef finditer(pattern: bytes | Pattern[bytes], string: ReadableBuffer, flags: _FlagsType = 0) -> Iterator[Match[bytes]]: ...\n@overload\ndef sub(\n    pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0, flags: _FlagsType = 0\n) -> str: ...\n@overload\ndef sub(\n    pattern: bytes | Pattern[bytes],\n    repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer],\n    string: ReadableBuffer,\n    count: int = 0,\n    flags: _FlagsType = 0,\n) -> bytes: ...\n@overload\ndef subn(\n    pattern: str | Pattern[str], repl: str | Callable[[Match[str]], str], string: str, count: int = 0, flags: _FlagsType = 0\n) -> tuple[str, int]: ...\n@overload\ndef subn(\n    pattern: bytes | Pattern[bytes],\n    repl: ReadableBuffer | Callable[[Match[bytes]], ReadableBuffer],\n    string: ReadableBuffer,\n    count: int = 0,\n    flags: _FlagsType = 0,\n) -> tuple[bytes, int]: ...\ndef escape(pattern: AnyStr) -> AnyStr: ...\ndef purge() -> None: ...\n\nif sys.version_info < (3, 13):\n    if sys.version_info >= (3, 11):\n        @deprecated(\"Deprecated since Python 3.11; removed in Python 3.13. Use `re.compile()` instead.\")\n        def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ...  # undocumented\n    else:\n        def template(pattern: AnyStr | Pattern[AnyStr], flags: _FlagsType = 0) -> Pattern[AnyStr]: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/readline.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath\nfrom collections.abc import Callable, Sequence\nfrom typing import Literal\nfrom typing_extensions import TypeAlias\n\nif sys.platform != \"win32\":\n    _Completer: TypeAlias = Callable[[str, int], str | None]\n    _CompDisp: TypeAlias = Callable[[str, Sequence[str], int], None]\n\n    def parse_and_bind(string: str, /) -> None: ...\n    def read_init_file(filename: StrOrBytesPath | None = None, /) -> None: ...\n    def get_line_buffer() -> str: ...\n    def insert_text(string: str, /) -> None: ...\n    def redisplay() -> None: ...\n    def read_history_file(filename: StrOrBytesPath | None = None, /) -> None: ...\n    def write_history_file(filename: StrOrBytesPath | None = None, /) -> None: ...\n    def append_history_file(nelements: int, filename: StrOrBytesPath | None = None, /) -> None: ...\n    def get_history_length() -> int: ...\n    def set_history_length(length: int, /) -> None: ...\n    def clear_history() -> None: ...\n    def get_current_history_length() -> int: ...\n    def get_history_item(index: int, /) -> str: ...\n    def remove_history_item(pos: int, /) -> None: ...\n    def replace_history_item(pos: int, line: str, /) -> None: ...\n    def add_history(string: str, /) -> None: ...\n    def set_auto_history(enabled: bool, /) -> None: ...\n    def set_startup_hook(function: Callable[[], object] | None = None, /) -> None: ...\n    def set_pre_input_hook(function: Callable[[], object] | None = None, /) -> None: ...\n    def set_completer(function: _Completer | None = None, /) -> None: ...\n    def get_completer() -> _Completer | None: ...\n    def get_completion_type() -> int: ...\n    def get_begidx() -> int: ...\n    def get_endidx() -> int: ...\n    def set_completer_delims(string: str, /) -> None: ...\n    def get_completer_delims() -> str: ...\n    def set_completion_display_matches_hook(function: _CompDisp | None = None, /) -> None: ...\n\n    if sys.version_info >= (3, 13):\n        backend: Literal[\"readline\", \"editline\"]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/reprlib.pyi",
    "content": "import sys\nfrom array import array\nfrom collections import deque\nfrom collections.abc import Callable\nfrom typing import Any\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"Repr\", \"repr\", \"recursive_repr\"]\n\n_ReprFunc: TypeAlias = Callable[[Any], str]\n\ndef recursive_repr(fillvalue: str = \"...\") -> Callable[[_ReprFunc], _ReprFunc]: ...\n\nclass Repr:\n    maxlevel: int\n    maxdict: int\n    maxlist: int\n    maxtuple: int\n    maxset: int\n    maxfrozenset: int\n    maxdeque: int\n    maxarray: int\n    maxlong: int\n    maxstring: int\n    maxother: int\n    if sys.version_info >= (3, 11):\n        fillvalue: str\n    if sys.version_info >= (3, 12):\n        indent: str | int | None\n\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self,\n            *,\n            maxlevel: int = 6,\n            maxtuple: int = 6,\n            maxlist: int = 6,\n            maxarray: int = 5,\n            maxdict: int = 4,\n            maxset: int = 6,\n            maxfrozenset: int = 6,\n            maxdeque: int = 6,\n            maxstring: int = 30,\n            maxlong: int = 40,\n            maxother: int = 30,\n            fillvalue: str = \"...\",\n            indent: str | int | None = None,\n        ) -> None: ...\n\n    def repr(self, x: Any) -> str: ...\n    def repr1(self, x: Any, level: int) -> str: ...\n    def repr_tuple(self, x: tuple[Any, ...], level: int) -> str: ...\n    def repr_list(self, x: list[Any], level: int) -> str: ...\n    def repr_array(self, x: array[Any], level: int) -> str: ...\n    def repr_set(self, x: set[Any], level: int) -> str: ...\n    def repr_frozenset(self, x: frozenset[Any], level: int) -> str: ...\n    def repr_deque(self, x: deque[Any], level: int) -> str: ...\n    def repr_dict(self, x: dict[Any, Any], level: int) -> str: ...\n    def repr_str(self, x: str, level: int) -> str: ...\n    def repr_int(self, x: int, level: int) -> str: ...\n    def repr_instance(self, x: Any, level: int) -> str: ...\n\naRepr: Repr\n\ndef repr(x: object) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/resource.pyi",
    "content": "import sys\nfrom _typeshed import structseq\nfrom typing import Final, final\n\nif sys.platform != \"win32\":\n    # Depends on resource.h\n    RLIMIT_AS: Final[int]\n    RLIMIT_CORE: Final[int]\n    RLIMIT_CPU: Final[int]\n    RLIMIT_DATA: Final[int]\n    RLIMIT_FSIZE: Final[int]\n    RLIMIT_MEMLOCK: Final[int]\n    RLIMIT_NOFILE: Final[int]\n    RLIMIT_NPROC: Final[int]\n    RLIMIT_RSS: Final[int]\n    RLIMIT_STACK: Final[int]\n    RLIM_INFINITY: Final[int]\n    RUSAGE_CHILDREN: Final[int]\n    RUSAGE_SELF: Final[int]\n    if sys.platform == \"linux\":\n        RLIMIT_MSGQUEUE: Final[int]\n        RLIMIT_NICE: Final[int]\n        RLIMIT_OFILE: Final[int]\n        RLIMIT_RTPRIO: Final[int]\n        RLIMIT_RTTIME: Final[int]\n        RLIMIT_SIGPENDING: Final[int]\n        RUSAGE_THREAD: Final[int]\n\n    @final\n    class struct_rusage(\n        structseq[float], tuple[float, float, int, int, int, int, int, int, int, int, int, int, int, int, int, int]\n    ):\n        if sys.version_info >= (3, 10):\n            __match_args__: Final = (\n                \"ru_utime\",\n                \"ru_stime\",\n                \"ru_maxrss\",\n                \"ru_ixrss\",\n                \"ru_idrss\",\n                \"ru_isrss\",\n                \"ru_minflt\",\n                \"ru_majflt\",\n                \"ru_nswap\",\n                \"ru_inblock\",\n                \"ru_oublock\",\n                \"ru_msgsnd\",\n                \"ru_msgrcv\",\n                \"ru_nsignals\",\n                \"ru_nvcsw\",\n                \"ru_nivcsw\",\n            )\n\n        @property\n        def ru_utime(self) -> float: ...\n        @property\n        def ru_stime(self) -> float: ...\n        @property\n        def ru_maxrss(self) -> int: ...\n        @property\n        def ru_ixrss(self) -> int: ...\n        @property\n        def ru_idrss(self) -> int: ...\n        @property\n        def ru_isrss(self) -> int: ...\n        @property\n        def ru_minflt(self) -> int: ...\n        @property\n        def ru_majflt(self) -> int: ...\n        @property\n        def ru_nswap(self) -> int: ...\n        @property\n        def ru_inblock(self) -> int: ...\n        @property\n        def ru_oublock(self) -> int: ...\n        @property\n        def ru_msgsnd(self) -> int: ...\n        @property\n        def ru_msgrcv(self) -> int: ...\n        @property\n        def ru_nsignals(self) -> int: ...\n        @property\n        def ru_nvcsw(self) -> int: ...\n        @property\n        def ru_nivcsw(self) -> int: ...\n\n    def getpagesize() -> int: ...\n    def getrlimit(resource: int, /) -> tuple[int, int]: ...\n    def getrusage(who: int, /) -> struct_rusage: ...\n    def setrlimit(resource: int, limits: tuple[int, int], /) -> None: ...\n    if sys.platform == \"linux\":\n        if sys.version_info >= (3, 12):\n            def prlimit(pid: int, resource: int, limits: tuple[int, int] | None = None, /) -> tuple[int, int]: ...\n        else:\n            def prlimit(pid: int, resource: int, limits: tuple[int, int] = ..., /) -> tuple[int, int]: ...\n    error = OSError\n"
  },
  {
    "path": "mypy/typeshed/stdlib/rlcompleter.pyi",
    "content": "from typing import Any\n\n__all__ = [\"Completer\"]\n\nclass Completer:\n    def __init__(self, namespace: dict[str, Any] | None = None) -> None: ...\n    def complete(self, text: str, state: int) -> str | None: ...\n    def attr_matches(self, text: str) -> list[str]: ...\n    def global_matches(self, text: str) -> list[str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/runpy.pyi",
    "content": "from _typeshed import Unused\nfrom types import ModuleType\nfrom typing import Any\nfrom typing_extensions import Self\n\n__all__ = [\"run_module\", \"run_path\"]\n\nclass _TempModule:\n    mod_name: str\n    module: ModuleType\n    def __init__(self, mod_name: str) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n\nclass _ModifiedArgv0:\n    value: Any\n    def __init__(self, value: Any) -> None: ...\n    def __enter__(self) -> None: ...\n    def __exit__(self, *args: Unused) -> None: ...\n\ndef run_module(\n    mod_name: str, init_globals: dict[str, Any] | None = None, run_name: str | None = None, alter_sys: bool = False\n) -> dict[str, Any]: ...\ndef run_path(path_name: str, init_globals: dict[str, Any] | None = None, run_name: str | None = None) -> dict[str, Any]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sched.pyi",
    "content": "import sys\nimport time\nfrom collections.abc import Callable\nfrom typing import Any, ClassVar, NamedTuple, type_check_only\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"scheduler\"]\n\n_ActionCallback: TypeAlias = Callable[..., Any]\n\nif sys.version_info >= (3, 10):\n    class Event(NamedTuple):\n        time: float\n        priority: Any\n        sequence: int\n        action: _ActionCallback\n        argument: tuple[Any, ...]\n        kwargs: dict[str, Any]\n\nelse:\n    @type_check_only\n    class _EventBase(NamedTuple):\n        time: float\n        priority: Any\n        action: _ActionCallback\n        argument: tuple[Any, ...]\n        kwargs: dict[str, Any]\n\n    class Event(_EventBase):\n        __hash__: ClassVar[None]  # type: ignore[assignment]\n\nclass scheduler:\n    timefunc: Callable[[], float]\n    delayfunc: Callable[[float], object]\n\n    def __init__(\n        self, timefunc: Callable[[], float] = time.monotonic, delayfunc: Callable[[float], object] = time.sleep\n    ) -> None: ...\n    def enterabs(\n        self, time: float, priority: Any, action: _ActionCallback, argument: tuple[Any, ...] = (), kwargs: dict[str, Any] = ...\n    ) -> Event: ...\n    def enter(\n        self, delay: float, priority: Any, action: _ActionCallback, argument: tuple[Any, ...] = (), kwargs: dict[str, Any] = ...\n    ) -> Event: ...\n    def run(self, blocking: bool = True) -> float | None: ...\n    def cancel(self, event: Event) -> None: ...\n    def empty(self) -> bool: ...\n    @property\n    def queue(self) -> list[Event]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/secrets.pyi",
    "content": "from _typeshed import SupportsLenAndGetItem\nfrom hmac import compare_digest as compare_digest\nfrom random import SystemRandom as SystemRandom\nfrom typing import Final, TypeVar\n\n__all__ = [\"choice\", \"randbelow\", \"randbits\", \"SystemRandom\", \"token_bytes\", \"token_hex\", \"token_urlsafe\", \"compare_digest\"]\n\n_T = TypeVar(\"_T\")\n\nDEFAULT_ENTROPY: Final[int]\n\ndef randbelow(exclusive_upper_bound: int) -> int: ...\ndef randbits(k: int) -> int: ...\ndef choice(seq: SupportsLenAndGetItem[_T]) -> _T: ...\ndef token_bytes(nbytes: int | None = None) -> bytes: ...\ndef token_hex(nbytes: int | None = None) -> str: ...\ndef token_urlsafe(nbytes: int | None = None) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/select.pyi",
    "content": "import sys\nfrom _typeshed import FileDescriptorLike\nfrom collections.abc import Iterable\nfrom types import TracebackType\nfrom typing import Any, ClassVar, Final, TypeVar, final, overload\nfrom typing_extensions import Never, Self, deprecated\n\nif sys.platform != \"win32\":\n    PIPE_BUF: Final[int]\n    POLLERR: Final[int]\n    POLLHUP: Final[int]\n    POLLIN: Final[int]\n    if sys.platform == \"linux\":\n        POLLMSG: Final[int]\n    POLLNVAL: Final[int]\n    POLLOUT: Final[int]\n    POLLPRI: Final[int]\n    POLLRDBAND: Final[int]\n    if sys.platform == \"linux\":\n        POLLRDHUP: Final[int]\n    POLLRDNORM: Final[int]\n    POLLWRBAND: Final[int]\n    POLLWRNORM: Final[int]\n\n    # This is actually a function that returns an instance of a class.\n    # The class is not accessible directly, and also calls itself select.poll.\n    class poll:\n        # default value is select.POLLIN | select.POLLPRI | select.POLLOUT\n        def register(self, fd: FileDescriptorLike, eventmask: int = 7, /) -> None: ...\n        def modify(self, fd: FileDescriptorLike, eventmask: int, /) -> None: ...\n        def unregister(self, fd: FileDescriptorLike, /) -> None: ...\n        def poll(self, timeout: float | None = None, /) -> list[tuple[int, int]]: ...\n\n_R = TypeVar(\"_R\", default=Never)\n_W = TypeVar(\"_W\", default=Never)\n_X = TypeVar(\"_X\", default=Never)\n\ndef select(\n    rlist: Iterable[_R], wlist: Iterable[_W], xlist: Iterable[_X], timeout: float | None = None, /\n) -> tuple[list[_R], list[_W], list[_X]]: ...\n\nerror = OSError\n\nif sys.platform != \"linux\" and sys.platform != \"win32\":\n    # BSD only\n    @final\n    class kevent:\n        data: Any\n        fflags: int\n        filter: int\n        flags: int\n        ident: int\n        udata: Any\n        def __init__(\n            self, ident: FileDescriptorLike, filter: int = ..., flags: int = ..., fflags: int = 0, data: Any = 0, udata: Any = 0\n        ) -> None: ...\n        __hash__: ClassVar[None]  # type: ignore[assignment]\n\n    # BSD only\n    @final\n    class kqueue:\n        closed: bool\n        def __init__(self) -> None: ...\n        def close(self) -> None: ...\n        def control(\n            self, changelist: Iterable[kevent] | None, maxevents: int, timeout: float | None = None, /\n        ) -> list[kevent]: ...\n        def fileno(self) -> int: ...\n        @classmethod\n        def fromfd(cls, fd: FileDescriptorLike, /) -> kqueue: ...\n\n    KQ_EV_ADD: Final[int]\n    KQ_EV_CLEAR: Final[int]\n    KQ_EV_DELETE: Final[int]\n    KQ_EV_DISABLE: Final[int]\n    KQ_EV_ENABLE: Final[int]\n    KQ_EV_EOF: Final[int]\n    KQ_EV_ERROR: Final[int]\n    KQ_EV_FLAG1: Final[int]\n    KQ_EV_ONESHOT: Final[int]\n    KQ_EV_SYSFLAGS: Final[int]\n    KQ_FILTER_AIO: Final[int]\n    if sys.platform != \"darwin\":\n        KQ_FILTER_NETDEV: Final[int]\n    KQ_FILTER_PROC: Final[int]\n    KQ_FILTER_READ: Final[int]\n    KQ_FILTER_SIGNAL: Final[int]\n    KQ_FILTER_TIMER: Final[int]\n    KQ_FILTER_VNODE: Final[int]\n    KQ_FILTER_WRITE: Final[int]\n    KQ_NOTE_ATTRIB: Final[int]\n    KQ_NOTE_CHILD: Final[int]\n    KQ_NOTE_DELETE: Final[int]\n    KQ_NOTE_EXEC: Final[int]\n    KQ_NOTE_EXIT: Final[int]\n    KQ_NOTE_EXTEND: Final[int]\n    KQ_NOTE_FORK: Final[int]\n    KQ_NOTE_LINK: Final[int]\n    if sys.platform != \"darwin\":\n        KQ_NOTE_LINKDOWN: Final[int]\n        KQ_NOTE_LINKINV: Final[int]\n        KQ_NOTE_LINKUP: Final[int]\n    KQ_NOTE_LOWAT: Final[int]\n    KQ_NOTE_PCTRLMASK: Final[int]\n    KQ_NOTE_PDATAMASK: Final[int]\n    KQ_NOTE_RENAME: Final[int]\n    KQ_NOTE_REVOKE: Final[int]\n    KQ_NOTE_TRACK: Final[int]\n    KQ_NOTE_TRACKERR: Final[int]\n    KQ_NOTE_WRITE: Final[int]\n\nif sys.platform == \"linux\":\n    @final\n    class epoll:\n        @overload\n        def __new__(self, sizehint: int = -1) -> Self: ...\n        @overload\n        @deprecated(\n            \"The `flags` parameter is deprecated since Python 3.4. \"\n            \"Use `os.set_inheritable()` to make the file descriptor inheritable.\"\n        )\n        def __new__(self, sizehint: int = -1, flags: int = 0) -> Self: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(\n            self,\n            exc_type: type[BaseException] | None = None,\n            exc_value: BaseException | None = None,\n            exc_tb: TracebackType | None = None,\n            /,\n        ) -> None: ...\n        def close(self) -> None: ...\n        closed: bool\n        def fileno(self) -> int: ...\n        def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ...\n        def modify(self, fd: FileDescriptorLike, eventmask: int) -> None: ...\n        def unregister(self, fd: FileDescriptorLike) -> None: ...\n        def poll(self, timeout: float | None = None, maxevents: int = -1) -> list[tuple[int, int]]: ...\n        @classmethod\n        def fromfd(cls, fd: FileDescriptorLike, /) -> epoll: ...\n\n    EPOLLERR: Final[int]\n    EPOLLEXCLUSIVE: Final[int]\n    EPOLLET: Final[int]\n    EPOLLHUP: Final[int]\n    EPOLLIN: Final[int]\n    EPOLLMSG: Final[int]\n    EPOLLONESHOT: Final[int]\n    EPOLLOUT: Final[int]\n    EPOLLPRI: Final[int]\n    EPOLLRDBAND: Final[int]\n    EPOLLRDHUP: Final[int]\n    EPOLLRDNORM: Final[int]\n    EPOLLWRBAND: Final[int]\n    EPOLLWRNORM: Final[int]\n    EPOLL_CLOEXEC: Final[int]\n    if sys.version_info >= (3, 14):\n        EPOLLWAKEUP: Final[int]\n\nif sys.platform != \"linux\" and sys.platform != \"darwin\" and sys.platform != \"win32\":\n    # Solaris only\n    class devpoll:\n        def close(self) -> None: ...\n        closed: bool\n        def fileno(self) -> int: ...\n        def register(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ...\n        def modify(self, fd: FileDescriptorLike, eventmask: int = ...) -> None: ...\n        def unregister(self, fd: FileDescriptorLike) -> None: ...\n        def poll(self, timeout: float | None = None) -> list[tuple[int, int]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/selectors.pyi",
    "content": "import sys\nfrom _typeshed import FileDescriptor, FileDescriptorLike, Unused\nfrom abc import ABCMeta, abstractmethod\nfrom collections.abc import Mapping\nfrom typing import Any, Final, NamedTuple\nfrom typing_extensions import Self, TypeAlias\n\n_EventMask: TypeAlias = int\n\nEVENT_READ: Final = 1\nEVENT_WRITE: Final = 2\n\nclass SelectorKey(NamedTuple):\n    fileobj: FileDescriptorLike\n    fd: FileDescriptor\n    events: _EventMask\n    data: Any\n\nclass BaseSelector(metaclass=ABCMeta):\n    @abstractmethod\n    def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: ...\n    @abstractmethod\n    def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ...\n    def modify(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: ...\n    @abstractmethod\n    def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ...\n    def close(self) -> None: ...\n    def get_key(self, fileobj: FileDescriptorLike) -> SelectorKey: ...\n    @abstractmethod\n    def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n\nclass _BaseSelectorImpl(BaseSelector, metaclass=ABCMeta):\n    def register(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: ...\n    def unregister(self, fileobj: FileDescriptorLike) -> SelectorKey: ...\n    def modify(self, fileobj: FileDescriptorLike, events: _EventMask, data: Any = None) -> SelectorKey: ...\n    def get_map(self) -> Mapping[FileDescriptorLike, SelectorKey]: ...\n\nclass SelectSelector(_BaseSelectorImpl):\n    def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ...\n\nclass _PollLikeSelector(_BaseSelectorImpl):\n    def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ...\n\nif sys.platform != \"win32\":\n    class PollSelector(_PollLikeSelector): ...\n\nif sys.platform == \"linux\":\n    class EpollSelector(_PollLikeSelector):\n        def fileno(self) -> int: ...\n\nif sys.platform != \"linux\" and sys.platform != \"darwin\" and sys.platform != \"win32\":\n    # Solaris only\n    class DevpollSelector(_PollLikeSelector):\n        def fileno(self) -> int: ...\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    class KqueueSelector(_BaseSelectorImpl):\n        def fileno(self) -> int: ...\n        def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ...\n\n# Not a real class at runtime, it is just a conditional alias to other real selectors.\n# The runtime logic is more fine-grained than a `sys.platform` check;\n# not really expressible in the stubs\nclass DefaultSelector(_BaseSelectorImpl):\n    def select(self, timeout: float | None = None) -> list[tuple[SelectorKey, _EventMask]]: ...\n    if sys.platform != \"win32\":\n        def fileno(self) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/shelve.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath\nfrom collections.abc import Iterator, MutableMapping\nfrom dbm import _TFlags\nfrom types import TracebackType\nfrom typing import Any, TypeVar, overload\nfrom typing_extensions import Self\n\n__all__ = [\"Shelf\", \"BsdDbShelf\", \"DbfilenameShelf\", \"open\"]\n\n_T = TypeVar(\"_T\")\n_VT = TypeVar(\"_VT\")\n\nclass Shelf(MutableMapping[str, _VT]):\n    def __init__(\n        self, dict: MutableMapping[bytes, bytes], protocol: int | None = None, writeback: bool = False, keyencoding: str = \"utf-8\"\n    ) -> None: ...\n    def __iter__(self) -> Iterator[str]: ...\n    def __len__(self) -> int: ...\n    @overload  # type: ignore[override]\n    def get(self, key: str, default: None = None) -> _VT | None: ...\n    @overload\n    def get(self, key: str, default: _VT) -> _VT: ...\n    @overload\n    def get(self, key: str, default: _T) -> _VT | _T: ...\n    def __getitem__(self, key: str) -> _VT: ...\n    def __setitem__(self, key: str, value: _VT) -> None: ...\n    def __delitem__(self, key: str) -> None: ...\n    def __contains__(self, key: str) -> bool: ...  # type: ignore[override]\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n    ) -> None: ...\n    def __del__(self) -> None: ...\n    def close(self) -> None: ...\n    def sync(self) -> None: ...\n\nclass BsdDbShelf(Shelf[_VT]):\n    def set_location(self, key: str) -> tuple[str, _VT]: ...\n    def next(self) -> tuple[str, _VT]: ...\n    def previous(self) -> tuple[str, _VT]: ...\n    def first(self) -> tuple[str, _VT]: ...\n    def last(self) -> tuple[str, _VT]: ...\n\nclass DbfilenameShelf(Shelf[_VT]):\n    if sys.version_info >= (3, 11):\n        def __init__(\n            self, filename: StrOrBytesPath, flag: _TFlags = \"c\", protocol: int | None = None, writeback: bool = False\n        ) -> None: ...\n    else:\n        def __init__(self, filename: str, flag: _TFlags = \"c\", protocol: int | None = None, writeback: bool = False) -> None: ...\n\nif sys.version_info >= (3, 11):\n    def open(\n        filename: StrOrBytesPath, flag: _TFlags = \"c\", protocol: int | None = None, writeback: bool = False\n    ) -> Shelf[Any]: ...\n\nelse:\n    def open(filename: str, flag: _TFlags = \"c\", protocol: int | None = None, writeback: bool = False) -> Shelf[Any]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/shlex.pyi",
    "content": "import sys\nfrom collections import deque\nfrom collections.abc import Iterable\nfrom io import TextIOWrapper\nfrom typing import Literal, Protocol, overload, type_check_only\nfrom typing_extensions import Self, deprecated\n\n__all__ = [\"shlex\", \"split\", \"quote\", \"join\"]\n\n@type_check_only\nclass _ShlexInstream(Protocol):\n    def read(self, size: Literal[1], /) -> str: ...\n    def readline(self) -> object: ...\n    def close(self) -> object: ...\n\nif sys.version_info >= (3, 12):\n    def split(s: str | _ShlexInstream, comments: bool = False, posix: bool = True) -> list[str]: ...\n\nelse:\n    @overload\n    def split(s: str | _ShlexInstream, comments: bool = False, posix: bool = True) -> list[str]: ...\n    @overload\n    @deprecated(\"Passing None for 's' to shlex.split() is deprecated and will raise an error in Python 3.12.\")\n    def split(s: None, comments: bool = False, posix: bool = True) -> list[str]: ...\n\ndef join(split_command: Iterable[str]) -> str: ...\ndef quote(s: str) -> str: ...\n\n# TODO: Make generic over infile once PEP 696 is implemented.\nclass shlex:\n    commenters: str\n    wordchars: str\n    whitespace: str\n    escape: str\n    quotes: str\n    escapedquotes: str\n    whitespace_split: bool\n    infile: str | None\n    instream: _ShlexInstream\n    source: str\n    debug: int\n    lineno: int\n    token: str\n    filestack: deque[tuple[str | None, _ShlexInstream, int]]\n    eof: str | None\n    @property\n    def punctuation_chars(self) -> str: ...\n    def __init__(\n        self,\n        instream: str | _ShlexInstream | None = None,\n        infile: str | None = None,\n        posix: bool = False,\n        punctuation_chars: bool | str = False,\n    ) -> None: ...\n    def get_token(self) -> str | None: ...\n    def push_token(self, tok: str) -> None: ...\n    def read_token(self) -> str | None: ...\n    def sourcehook(self, newfile: str) -> tuple[str, TextIOWrapper] | None: ...\n    def push_source(self, newstream: str | _ShlexInstream, newfile: str | None = None) -> None: ...\n    def pop_source(self) -> None: ...\n    def error_leader(self, infile: str | None = None, lineno: int | None = None) -> str: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/shutil.pyi",
    "content": "import os\nimport sys\nfrom _typeshed import BytesPath, ExcInfo, FileDescriptorOrPath, MaybeNone, StrOrBytesPath, StrPath, SupportsRead, SupportsWrite\nfrom collections.abc import Callable, Iterable, Sequence\nfrom tarfile import _TarfileFilter\nfrom typing import Any, AnyStr, NamedTuple, NoReturn, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import TypeAlias, deprecated\n\n__all__ = [\n    \"copyfileobj\",\n    \"copyfile\",\n    \"copymode\",\n    \"copystat\",\n    \"copy\",\n    \"copy2\",\n    \"copytree\",\n    \"move\",\n    \"rmtree\",\n    \"Error\",\n    \"SpecialFileError\",\n    \"make_archive\",\n    \"get_archive_formats\",\n    \"register_archive_format\",\n    \"unregister_archive_format\",\n    \"get_unpack_formats\",\n    \"register_unpack_format\",\n    \"unregister_unpack_format\",\n    \"unpack_archive\",\n    \"ignore_patterns\",\n    \"chown\",\n    \"which\",\n    \"get_terminal_size\",\n    \"SameFileError\",\n    \"disk_usage\",\n]\nif sys.version_info < (3, 14):\n    __all__ += [\"ExecError\"]\n\n_StrOrBytesPathT = TypeVar(\"_StrOrBytesPathT\", bound=StrOrBytesPath)\n_StrPathT = TypeVar(\"_StrPathT\", bound=StrPath)\n_BytesPathT = TypeVar(\"_BytesPathT\", bound=BytesPath)\n\nclass Error(OSError): ...\nclass SameFileError(Error): ...\nclass SpecialFileError(OSError): ...\n\nif sys.version_info >= (3, 14):\n    ExecError = RuntimeError  # Deprecated in Python 3.14; removal scheduled for Python 3.16\n\nelse:\n    class ExecError(OSError): ...\n\nclass ReadError(OSError): ...\nclass RegistryError(Exception): ...\n\ndef copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr], length: int = 0) -> None: ...\ndef copyfile(src: StrOrBytesPath, dst: _StrOrBytesPathT, *, follow_symlinks: bool = True) -> _StrOrBytesPathT: ...\ndef copymode(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ...\ndef copystat(src: StrOrBytesPath, dst: StrOrBytesPath, *, follow_symlinks: bool = True) -> None: ...\n@overload\ndef copy(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: ...\n@overload\ndef copy(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ...\n@overload\ndef copy2(src: StrPath, dst: _StrPathT, *, follow_symlinks: bool = True) -> _StrPathT | str: ...\n@overload\ndef copy2(src: BytesPath, dst: _BytesPathT, *, follow_symlinks: bool = True) -> _BytesPathT | bytes: ...\ndef ignore_patterns(*patterns: StrPath) -> Callable[[Any, list[str]], set[str]]: ...\ndef copytree(\n    src: StrPath,\n    dst: _StrPathT,\n    symlinks: bool = False,\n    ignore: None | Callable[[str, list[str]], Iterable[str]] | Callable[[StrPath, list[str]], Iterable[str]] = None,\n    copy_function: Callable[[str, str], object] = ...,\n    ignore_dangling_symlinks: bool = False,\n    dirs_exist_ok: bool = False,\n) -> _StrPathT: ...\n\n_OnErrorCallback: TypeAlias = Callable[[Callable[..., Any], str, ExcInfo], object]\n_OnExcCallback: TypeAlias = Callable[[Callable[..., Any], str, BaseException], object]\n\n@type_check_only\nclass _RmtreeType(Protocol):\n    avoids_symlink_attacks: bool\n    if sys.version_info >= (3, 12):\n        @overload\n        @deprecated(\"The `onerror` parameter is deprecated. Use `onexc` instead.\")\n        def __call__(\n            self,\n            path: StrOrBytesPath,\n            ignore_errors: bool,\n            onerror: _OnErrorCallback | None,\n            *,\n            onexc: None = None,\n            dir_fd: int | None = None,\n        ) -> None: ...\n        @overload\n        @deprecated(\"The `onerror` parameter is deprecated. Use `onexc` instead.\")\n        def __call__(\n            self,\n            path: StrOrBytesPath,\n            ignore_errors: bool = False,\n            *,\n            onerror: _OnErrorCallback | None,\n            onexc: None = None,\n            dir_fd: int | None = None,\n        ) -> None: ...\n        @overload\n        def __call__(\n            self,\n            path: StrOrBytesPath,\n            ignore_errors: bool = False,\n            *,\n            onexc: _OnExcCallback | None = None,\n            dir_fd: int | None = None,\n        ) -> None: ...\n    elif sys.version_info >= (3, 11):\n        def __call__(\n            self,\n            path: StrOrBytesPath,\n            ignore_errors: bool = False,\n            onerror: _OnErrorCallback | None = None,\n            *,\n            dir_fd: int | None = None,\n        ) -> None: ...\n\n    else:\n        def __call__(\n            self, path: StrOrBytesPath, ignore_errors: bool = False, onerror: _OnErrorCallback | None = None\n        ) -> None: ...\n\nrmtree: _RmtreeType\n\n_CopyFn: TypeAlias = Callable[[str, str], object] | Callable[[StrPath, StrPath], object]\n\n# N.B. shutil.move appears to take bytes arguments, however,\n# this does not work when dst is (or is within) an existing directory.\n# (#6832)\ndef move(src: StrPath, dst: _StrPathT, copy_function: _CopyFn = ...) -> _StrPathT | str | MaybeNone: ...\n\nclass _ntuple_diskusage(NamedTuple):\n    total: int\n    used: int\n    free: int\n\ndef disk_usage(path: FileDescriptorOrPath) -> _ntuple_diskusage: ...\n\n# While chown can be imported on Windows, it doesn't actually work;\n# see https://bugs.python.org/issue33140. We keep it here because it's\n# in __all__.\nif sys.version_info >= (3, 13):\n    @overload\n    def chown(\n        path: FileDescriptorOrPath,\n        user: str | int,\n        group: None = None,\n        *,\n        dir_fd: int | None = None,\n        follow_symlinks: bool = True,\n    ) -> None: ...\n    @overload\n    def chown(\n        path: FileDescriptorOrPath,\n        user: None = None,\n        *,\n        group: str | int,\n        dir_fd: int | None = None,\n        follow_symlinks: bool = True,\n    ) -> None: ...\n    @overload\n    def chown(\n        path: FileDescriptorOrPath, user: None, group: str | int, *, dir_fd: int | None = None, follow_symlinks: bool = True\n    ) -> None: ...\n    @overload\n    def chown(\n        path: FileDescriptorOrPath, user: str | int, group: str | int, *, dir_fd: int | None = None, follow_symlinks: bool = True\n    ) -> None: ...\n\nelse:\n    @overload\n    def chown(path: FileDescriptorOrPath, user: str | int, group: None = None) -> None: ...\n    @overload\n    def chown(path: FileDescriptorOrPath, user: None = None, *, group: str | int) -> None: ...\n    @overload\n    def chown(path: FileDescriptorOrPath, user: None, group: str | int) -> None: ...\n    @overload\n    def chown(path: FileDescriptorOrPath, user: str | int, group: str | int) -> None: ...\n\nif sys.platform == \"win32\" and sys.version_info < (3, 12):\n    @overload\n    @deprecated(\"On Windows before Python 3.12, using a PathLike as `cmd` would always fail or return `None`.\")\n    def which(cmd: os.PathLike[str], mode: int = 1, path: StrPath | None = None) -> NoReturn: ...\n\n@overload\ndef which(cmd: StrPath, mode: int = 1, path: StrPath | None = None) -> str | None: ...\n@overload\ndef which(cmd: bytes, mode: int = 1, path: StrPath | None = None) -> bytes | None: ...\ndef make_archive(\n    base_name: str,\n    format: str,\n    root_dir: StrPath | None = None,\n    base_dir: StrPath | None = None,\n    verbose: bool = ...,\n    dry_run: bool = ...,\n    owner: str | None = None,\n    group: str | None = None,\n    logger: Any | None = None,\n) -> str: ...\ndef get_archive_formats() -> list[tuple[str, str]]: ...\n@overload\ndef register_archive_format(\n    name: str, function: Callable[..., object], extra_args: Sequence[tuple[str, Any] | list[Any]], description: str = \"\"\n) -> None: ...\n@overload\ndef register_archive_format(\n    name: str, function: Callable[[str, str], object], extra_args: None = None, description: str = \"\"\n) -> None: ...\ndef unregister_archive_format(name: str) -> None: ...\ndef unpack_archive(\n    filename: StrPath, extract_dir: StrPath | None = None, format: str | None = None, *, filter: _TarfileFilter | None = None\n) -> None: ...\n@overload\ndef register_unpack_format(\n    name: str,\n    extensions: list[str],\n    function: Callable[..., object],\n    extra_args: Sequence[tuple[str, Any]],\n    description: str = \"\",\n) -> None: ...\n@overload\ndef register_unpack_format(\n    name: str, extensions: list[str], function: Callable[[str, str], object], extra_args: None = None, description: str = \"\"\n) -> None: ...\ndef unregister_unpack_format(name: str) -> None: ...\ndef get_unpack_formats() -> list[tuple[str, list[str], str]]: ...\ndef get_terminal_size(fallback: tuple[int, int] = (80, 24)) -> os.terminal_size: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/signal.pyi",
    "content": "import sys\nfrom _typeshed import structseq\nfrom collections.abc import Callable, Iterable\nfrom enum import IntEnum\nfrom types import FrameType\nfrom typing import Any, Final, final\nfrom typing_extensions import Never, TypeAlias\n\nNSIG: int\n\nclass Signals(IntEnum):\n    SIGABRT = 6\n    SIGFPE = 8\n    SIGILL = 4\n    SIGINT = 2\n    SIGSEGV = 11\n    SIGTERM = 15\n\n    if sys.platform == \"win32\":\n        SIGBREAK = 21\n        CTRL_C_EVENT = 0\n        CTRL_BREAK_EVENT = 1\n    else:\n        SIGALRM = 14\n        SIGBUS = 7\n        SIGCHLD = 17\n        SIGCONT = 18\n        SIGHUP = 1\n        SIGIO = 29\n        SIGIOT = 6\n        SIGKILL = 9\n        SIGPIPE = 13\n        SIGPROF = 27\n        SIGQUIT = 3\n        SIGSTOP = 19\n        SIGSYS = 31\n        SIGTRAP = 5\n        SIGTSTP = 20\n        SIGTTIN = 21\n        SIGTTOU = 22\n        SIGURG = 23\n        SIGUSR1 = 10\n        SIGUSR2 = 12\n        SIGVTALRM = 26\n        SIGWINCH = 28\n        SIGXCPU = 24\n        SIGXFSZ = 25\n        if sys.platform != \"linux\":\n            SIGEMT = 7\n            SIGINFO = 29\n        if sys.platform != \"darwin\":\n            SIGCLD = 17\n            SIGPOLL = 29\n            SIGPWR = 30\n            SIGRTMAX = 64\n            SIGRTMIN = 34\n            if sys.version_info >= (3, 11):\n                SIGSTKFLT = 16\n\nclass Handlers(IntEnum):\n    SIG_DFL = 0\n    SIG_IGN = 1\n\nSIG_DFL: Final = Handlers.SIG_DFL\nSIG_IGN: Final = Handlers.SIG_IGN\n\n_SIGNUM: TypeAlias = int | Signals\n_HANDLER: TypeAlias = Callable[[int, FrameType | None], Any] | int | Handlers | None\n\ndef default_int_handler(signalnum: int, frame: FrameType | None, /) -> Never: ...\n\nif sys.version_info >= (3, 10):  # arguments changed in 3.10.2\n    def getsignal(signalnum: _SIGNUM) -> _HANDLER: ...\n    def signal(signalnum: _SIGNUM, handler: _HANDLER) -> _HANDLER: ...\n\nelse:\n    def getsignal(signalnum: _SIGNUM, /) -> _HANDLER: ...\n    def signal(signalnum: _SIGNUM, handler: _HANDLER, /) -> _HANDLER: ...\n\nSIGABRT: Final = Signals.SIGABRT\nSIGFPE: Final = Signals.SIGFPE\nSIGILL: Final = Signals.SIGILL\nSIGINT: Final = Signals.SIGINT\nSIGSEGV: Final = Signals.SIGSEGV\nSIGTERM: Final = Signals.SIGTERM\n\nif sys.platform == \"win32\":\n    SIGBREAK: Final = Signals.SIGBREAK\n    CTRL_C_EVENT: Final = Signals.CTRL_C_EVENT\n    CTRL_BREAK_EVENT: Final = Signals.CTRL_BREAK_EVENT\nelse:\n    if sys.platform != \"linux\":\n        SIGINFO: Final = Signals.SIGINFO\n        SIGEMT: Final = Signals.SIGEMT\n    SIGALRM: Final = Signals.SIGALRM\n    SIGBUS: Final = Signals.SIGBUS\n    SIGCHLD: Final = Signals.SIGCHLD\n    SIGCONT: Final = Signals.SIGCONT\n    SIGHUP: Final = Signals.SIGHUP\n    SIGIO: Final = Signals.SIGIO\n    SIGIOT: Final = Signals.SIGABRT  # alias\n    SIGKILL: Final = Signals.SIGKILL\n    SIGPIPE: Final = Signals.SIGPIPE\n    SIGPROF: Final = Signals.SIGPROF\n    SIGQUIT: Final = Signals.SIGQUIT\n    SIGSTOP: Final = Signals.SIGSTOP\n    SIGSYS: Final = Signals.SIGSYS\n    SIGTRAP: Final = Signals.SIGTRAP\n    SIGTSTP: Final = Signals.SIGTSTP\n    SIGTTIN: Final = Signals.SIGTTIN\n    SIGTTOU: Final = Signals.SIGTTOU\n    SIGURG: Final = Signals.SIGURG\n    SIGUSR1: Final = Signals.SIGUSR1\n    SIGUSR2: Final = Signals.SIGUSR2\n    SIGVTALRM: Final = Signals.SIGVTALRM\n    SIGWINCH: Final = Signals.SIGWINCH\n    SIGXCPU: Final = Signals.SIGXCPU\n    SIGXFSZ: Final = Signals.SIGXFSZ\n\n    class ItimerError(OSError): ...\n    ITIMER_PROF: int\n    ITIMER_REAL: int\n    ITIMER_VIRTUAL: int\n\n    class Sigmasks(IntEnum):\n        SIG_BLOCK = 0\n        SIG_UNBLOCK = 1\n        SIG_SETMASK = 2\n\n    SIG_BLOCK: Final = Sigmasks.SIG_BLOCK\n    SIG_UNBLOCK: Final = Sigmasks.SIG_UNBLOCK\n    SIG_SETMASK: Final = Sigmasks.SIG_SETMASK\n    def alarm(seconds: int, /) -> int: ...\n    def getitimer(which: int, /) -> tuple[float, float]: ...\n    def pause() -> None: ...\n    def pthread_kill(thread_id: int, signalnum: int, /) -> None: ...\n    if sys.version_info >= (3, 10):  # arguments changed in 3.10.2\n        def pthread_sigmask(how: int, mask: Iterable[int]) -> set[_SIGNUM]: ...\n    else:\n        def pthread_sigmask(how: int, mask: Iterable[int], /) -> set[_SIGNUM]: ...\n\n    def setitimer(which: int, seconds: float, interval: float = 0.0, /) -> tuple[float, float]: ...\n    def siginterrupt(signalnum: int, flag: bool, /) -> None: ...\n    def sigpending() -> Any: ...\n    if sys.version_info >= (3, 10):  # argument changed in 3.10.2\n        def sigwait(sigset: Iterable[int]) -> _SIGNUM: ...\n    else:\n        def sigwait(sigset: Iterable[int], /) -> _SIGNUM: ...\n    if sys.platform != \"darwin\":\n        SIGCLD: Final = Signals.SIGCHLD  # alias\n        SIGPOLL: Final = Signals.SIGIO  # alias\n        SIGPWR: Final = Signals.SIGPWR\n        SIGRTMAX: Final = Signals.SIGRTMAX\n        SIGRTMIN: Final = Signals.SIGRTMIN\n        if sys.version_info >= (3, 11):\n            SIGSTKFLT: Final = Signals.SIGSTKFLT\n\n        @final\n        class struct_siginfo(structseq[int], tuple[int, int, int, int, int, int, int]):\n            if sys.version_info >= (3, 10):\n                __match_args__: Final = (\"si_signo\", \"si_code\", \"si_errno\", \"si_pid\", \"si_uid\", \"si_status\", \"si_band\")\n\n            @property\n            def si_signo(self) -> int: ...\n            @property\n            def si_code(self) -> int: ...\n            @property\n            def si_errno(self) -> int: ...\n            @property\n            def si_pid(self) -> int: ...\n            @property\n            def si_uid(self) -> int: ...\n            @property\n            def si_status(self) -> int: ...\n            @property\n            def si_band(self) -> int: ...\n\n        def sigtimedwait(sigset: Iterable[int], timeout: float, /) -> struct_siginfo | None: ...\n        def sigwaitinfo(sigset: Iterable[int], /) -> struct_siginfo: ...\n\ndef strsignal(signalnum: _SIGNUM, /) -> str | None: ...\ndef valid_signals() -> set[Signals]: ...\ndef raise_signal(signalnum: _SIGNUM, /) -> None: ...\ndef set_wakeup_fd(fd: int, /, *, warn_on_full_buffer: bool = True) -> int: ...\n\nif sys.platform == \"linux\":\n    def pidfd_send_signal(pidfd: int, sig: int, siginfo: None = None, flags: int = 0, /) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/site.pyi",
    "content": "import sys\nfrom _typeshed import StrPath\nfrom collections.abc import Iterable\n\nPREFIXES: list[str]\nENABLE_USER_SITE: bool | None\nUSER_SITE: str | None\nUSER_BASE: str | None\n\ndef main() -> None: ...\ndef abs_paths() -> None: ...  # undocumented\ndef addpackage(sitedir: StrPath, name: StrPath, known_paths: set[str] | None) -> set[str] | None: ...  # undocumented\ndef addsitedir(sitedir: str, known_paths: set[str] | None = None) -> None: ...\ndef addsitepackages(known_paths: set[str] | None, prefixes: Iterable[str] | None = None) -> set[str] | None: ...  # undocumented\ndef addusersitepackages(known_paths: set[str] | None) -> set[str] | None: ...  # undocumented\ndef check_enableusersite() -> bool | None: ...  # undocumented\n\nif sys.version_info >= (3, 13):\n    def gethistoryfile() -> str: ...  # undocumented\n\ndef enablerlcompleter() -> None: ...  # undocumented\n\nif sys.version_info >= (3, 13):\n    def register_readline() -> None: ...  # undocumented\n\ndef execsitecustomize() -> None: ...  # undocumented\ndef execusercustomize() -> None: ...  # undocumented\ndef getsitepackages(prefixes: Iterable[str] | None = None) -> list[str]: ...\ndef getuserbase() -> str: ...\ndef getusersitepackages() -> str: ...\ndef makepath(*paths: StrPath) -> tuple[str, str]: ...  # undocumented\ndef removeduppaths() -> set[str]: ...  # undocumented\ndef setcopyright() -> None: ...  # undocumented\ndef sethelper() -> None: ...  # undocumented\ndef setquit() -> None: ...  # undocumented\ndef venv(known_paths: set[str] | None) -> set[str] | None: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/smtpd.pyi",
    "content": "import asynchat\nimport asyncore\nimport socket\nimport sys\nfrom collections import defaultdict\nfrom typing import Any\nfrom typing_extensions import TypeAlias, deprecated\n\nif sys.version_info >= (3, 11):\n    __all__ = [\"SMTPChannel\", \"SMTPServer\", \"DebuggingServer\", \"PureProxy\"]\nelse:\n    __all__ = [\"SMTPChannel\", \"SMTPServer\", \"DebuggingServer\", \"PureProxy\", \"MailmanProxy\"]\n\n_Address: TypeAlias = tuple[str, int]  # (host, port)\n\nclass SMTPChannel(asynchat.async_chat):\n    COMMAND: int\n    DATA: int\n\n    command_size_limits: defaultdict[str, int]\n    smtp_server: SMTPServer\n    conn: socket.socket\n    addr: Any\n    received_lines: list[str]\n    smtp_state: int\n    seen_greeting: str\n    mailfrom: str\n    rcpttos: list[str]\n    received_data: str\n    fqdn: str\n    peer: str\n\n    command_size_limit: int\n    data_size_limit: int\n\n    enable_SMTPUTF8: bool\n    @property\n    def max_command_size_limit(self) -> int: ...\n    def __init__(\n        self,\n        server: SMTPServer,\n        conn: socket.socket,\n        addr: Any,\n        data_size_limit: int = 33554432,\n        map: asyncore._MapType | None = None,\n        enable_SMTPUTF8: bool = False,\n        decode_data: bool = False,\n    ) -> None: ...\n    # base asynchat.async_chat.push() accepts bytes\n    def push(self, msg: str) -> None: ...  # type: ignore[override]\n    def collect_incoming_data(self, data: bytes) -> None: ...\n    def found_terminator(self) -> None: ...\n    def smtp_HELO(self, arg: str) -> None: ...\n    def smtp_NOOP(self, arg: str) -> None: ...\n    def smtp_QUIT(self, arg: str) -> None: ...\n    def smtp_MAIL(self, arg: str) -> None: ...\n    def smtp_RCPT(self, arg: str) -> None: ...\n    def smtp_RSET(self, arg: str) -> None: ...\n    def smtp_DATA(self, arg: str) -> None: ...\n    def smtp_EHLO(self, arg: str) -> None: ...\n    def smtp_HELP(self, arg: str) -> None: ...\n    def smtp_VRFY(self, arg: str) -> None: ...\n    def smtp_EXPN(self, arg: str) -> None: ...\n\nclass SMTPServer(asyncore.dispatcher):\n    channel_class: type[SMTPChannel]\n\n    data_size_limit: int\n    enable_SMTPUTF8: bool\n    def __init__(\n        self,\n        localaddr: _Address,\n        remoteaddr: _Address,\n        data_size_limit: int = 33554432,\n        map: asyncore._MapType | None = None,\n        enable_SMTPUTF8: bool = False,\n        decode_data: bool = False,\n    ) -> None: ...\n    def handle_accepted(self, conn: socket.socket, addr: Any) -> None: ...\n    def process_message(\n        self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str, **kwargs: Any\n    ) -> str | None: ...\n\nclass DebuggingServer(SMTPServer): ...\n\nclass PureProxy(SMTPServer):\n    def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ...  # type: ignore[override]\n\nif sys.version_info < (3, 11):\n    @deprecated(\"Deprecated since Python 3.9; removed in Python 3.11.\")\n    class MailmanProxy(PureProxy):\n        def process_message(self, peer: _Address, mailfrom: str, rcpttos: list[str], data: bytes | str) -> str | None: ...  # type: ignore[override]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/smtplib.pyi",
    "content": "import sys\nfrom _socket import _Address as _SourceAddress\nfrom _typeshed import ReadableBuffer, SizedBuffer, StrOrBytesPath\nfrom collections.abc import Sequence\nfrom email.message import Message as _Message\nfrom re import Pattern\nfrom socket import socket\nfrom ssl import SSLContext\nfrom types import TracebackType\nfrom typing import Any, Final, Protocol, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, deprecated\n\n__all__ = [\n    \"SMTPException\",\n    \"SMTPServerDisconnected\",\n    \"SMTPResponseException\",\n    \"SMTPSenderRefused\",\n    \"SMTPRecipientsRefused\",\n    \"SMTPDataError\",\n    \"SMTPConnectError\",\n    \"SMTPHeloError\",\n    \"SMTPAuthenticationError\",\n    \"quoteaddr\",\n    \"quotedata\",\n    \"SMTP\",\n    \"SMTP_SSL\",\n    \"SMTPNotSupportedError\",\n]\n\n_Reply: TypeAlias = tuple[int, bytes]\n_SendErrs: TypeAlias = dict[str, _Reply]\n\nSMTP_PORT: Final = 25\nSMTP_SSL_PORT: Final = 465\nCRLF: Final[str]\nbCRLF: Final[bytes]\n\nOLDSTYLE_AUTH: Final[Pattern[str]]\n\nclass SMTPException(OSError): ...\nclass SMTPNotSupportedError(SMTPException): ...\nclass SMTPServerDisconnected(SMTPException): ...\n\nclass SMTPResponseException(SMTPException):\n    smtp_code: int\n    smtp_error: bytes | str\n    args: tuple[int, bytes | str] | tuple[int, bytes, str]\n    def __init__(self, code: int, msg: bytes | str) -> None: ...\n\nclass SMTPSenderRefused(SMTPResponseException):\n    smtp_error: bytes\n    sender: str\n    args: tuple[int, bytes, str]\n    def __init__(self, code: int, msg: bytes, sender: str) -> None: ...\n\nclass SMTPRecipientsRefused(SMTPException):\n    recipients: _SendErrs\n    args: tuple[_SendErrs]\n    def __init__(self, recipients: _SendErrs) -> None: ...\n\nclass SMTPDataError(SMTPResponseException): ...\nclass SMTPConnectError(SMTPResponseException): ...\nclass SMTPHeloError(SMTPResponseException): ...\nclass SMTPAuthenticationError(SMTPResponseException): ...\n\ndef quoteaddr(addrstring: str) -> str: ...\ndef quotedata(data: str) -> str: ...\n@type_check_only\nclass _AuthObject(Protocol):\n    @overload\n    def __call__(self, challenge: None = None, /) -> str | None: ...\n    @overload\n    def __call__(self, challenge: bytes, /) -> str: ...\n\nclass SMTP:\n    debuglevel: int\n    sock: socket | None\n    # Type of file should match what socket.makefile() returns\n    file: Any | None\n    helo_resp: bytes | None\n    ehlo_msg: str\n    ehlo_resp: bytes | None\n    does_esmtp: bool\n    default_port: int\n    timeout: float\n    esmtp_features: dict[str, str]\n    command_encoding: str\n    source_address: _SourceAddress | None\n    local_hostname: str\n    def __init__(\n        self,\n        host: str = \"\",\n        port: int = 0,\n        local_hostname: str | None = None,\n        timeout: float = ...,\n        source_address: _SourceAddress | None = None,\n    ) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None\n    ) -> None: ...\n    def set_debuglevel(self, debuglevel: int) -> None: ...\n    def connect(self, host: str = \"localhost\", port: int = 0, source_address: _SourceAddress | None = None) -> _Reply: ...\n    def send(self, s: ReadableBuffer | str) -> None: ...\n    def putcmd(self, cmd: str, args: str = \"\") -> None: ...\n    def getreply(self) -> _Reply: ...\n    def docmd(self, cmd: str, args: str = \"\") -> _Reply: ...\n    def helo(self, name: str = \"\") -> _Reply: ...\n    def ehlo(self, name: str = \"\") -> _Reply: ...\n    def has_extn(self, opt: str) -> bool: ...\n    def help(self, args: str = \"\") -> bytes: ...\n    def rset(self) -> _Reply: ...\n    def noop(self) -> _Reply: ...\n    def mail(self, sender: str, options: Sequence[str] = ()) -> _Reply: ...\n    def rcpt(self, recip: str, options: Sequence[str] = ()) -> _Reply: ...\n    def data(self, msg: ReadableBuffer | str) -> _Reply: ...\n    def verify(self, address: str) -> _Reply: ...\n    vrfy = verify\n    def expn(self, address: str) -> _Reply: ...\n    def ehlo_or_helo_if_needed(self) -> None: ...\n    user: str\n    password: str\n    def auth(self, mechanism: str, authobject: _AuthObject, *, initial_response_ok: bool = True) -> _Reply: ...\n    @overload\n    def auth_cram_md5(self, challenge: None = None) -> None: ...\n    @overload\n    def auth_cram_md5(self, challenge: ReadableBuffer) -> str: ...\n    def auth_plain(self, challenge: ReadableBuffer | None = None) -> str: ...\n    def auth_login(self, challenge: ReadableBuffer | None = None) -> str: ...\n    def login(self, user: str, password: str, *, initial_response_ok: bool = True) -> _Reply: ...\n    if sys.version_info >= (3, 12):\n        def starttls(self, *, context: SSLContext | None = None) -> _Reply: ...\n    else:\n        @overload\n        def starttls(self, keyfile: None = None, certfile: None = None, context: SSLContext | None = None) -> _Reply: ...\n        @overload\n        @deprecated(\n            \"The `keyfile`, `certfile` parameters are deprecated since Python 3.6; \"\n            \"removed in Python 3.12. Use `context` parameter instead.\"\n        )\n        def starttls(\n            self, keyfile: StrOrBytesPath | None = None, certfile: StrOrBytesPath | None = None, context: None = None\n        ) -> _Reply: ...\n\n    def sendmail(\n        self,\n        from_addr: str,\n        to_addrs: str | Sequence[str],\n        msg: SizedBuffer | str,\n        mail_options: Sequence[str] = (),\n        rcpt_options: Sequence[str] = (),\n    ) -> _SendErrs: ...\n    def send_message(\n        self,\n        msg: _Message,\n        from_addr: str | None = None,\n        to_addrs: str | Sequence[str] | None = None,\n        mail_options: Sequence[str] = (),\n        rcpt_options: Sequence[str] = (),\n    ) -> _SendErrs: ...\n    def close(self) -> None: ...\n    def quit(self) -> _Reply: ...\n\nclass SMTP_SSL(SMTP):\n    context: SSLContext\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self,\n            host: str = \"\",\n            port: int = 0,\n            local_hostname: str | None = None,\n            *,\n            timeout: float = ...,\n            source_address: _SourceAddress | None = None,\n            context: SSLContext | None = None,\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self,\n            host: str = \"\",\n            port: int = 0,\n            local_hostname: str | None = None,\n            keyfile: None = None,\n            certfile: None = None,\n            timeout: float = ...,\n            source_address: _SourceAddress | None = None,\n            context: SSLContext | None = None,\n        ) -> None: ...\n        @overload\n        @deprecated(\n            \"The `keyfile`, `certfile` parameters are deprecated since Python 3.6; \"\n            \"removed in Python 3.12. Use `context` parameter instead.\"\n        )\n        def __init__(\n            self,\n            host: str = \"\",\n            port: int = 0,\n            local_hostname: str | None = None,\n            keyfile: StrOrBytesPath | None = None,\n            certfile: StrOrBytesPath | None = None,\n            timeout: float = ...,\n            source_address: _SourceAddress | None = None,\n            context: None = None,\n        ) -> None: ...\n        keyfile: StrOrBytesPath | None\n        certfile: StrOrBytesPath | None\n\nLMTP_PORT: Final = 2003\n\nclass LMTP(SMTP):\n    def __init__(\n        self,\n        host: str = \"\",\n        port: int = 2003,\n        local_hostname: str | None = None,\n        source_address: _SourceAddress | None = None,\n        timeout: float = ...,\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sndhdr.pyi",
    "content": "from _typeshed import StrOrBytesPath\nfrom typing import NamedTuple\n\n__all__ = [\"what\", \"whathdr\"]\n\nclass SndHeaders(NamedTuple):\n    filetype: str\n    framerate: int\n    nchannels: int\n    nframes: int\n    sampwidth: int | str\n\ndef what(filename: StrOrBytesPath) -> SndHeaders | None: ...\ndef whathdr(filename: StrOrBytesPath) -> SndHeaders | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/socket.pyi",
    "content": "# Ideally, we'd just do \"from _socket import *\". Unfortunately, socket\n# overrides some definitions from _socket incompatibly. mypy incorrectly\n# prefers the definitions from _socket over those defined here.\nimport _socket\nimport sys\nfrom _socket import (\n    CAPI as CAPI,\n    EAI_AGAIN as EAI_AGAIN,\n    EAI_BADFLAGS as EAI_BADFLAGS,\n    EAI_FAIL as EAI_FAIL,\n    EAI_FAMILY as EAI_FAMILY,\n    EAI_MEMORY as EAI_MEMORY,\n    EAI_NODATA as EAI_NODATA,\n    EAI_NONAME as EAI_NONAME,\n    EAI_SERVICE as EAI_SERVICE,\n    EAI_SOCKTYPE as EAI_SOCKTYPE,\n    INADDR_ALLHOSTS_GROUP as INADDR_ALLHOSTS_GROUP,\n    INADDR_ANY as INADDR_ANY,\n    INADDR_BROADCAST as INADDR_BROADCAST,\n    INADDR_LOOPBACK as INADDR_LOOPBACK,\n    INADDR_MAX_LOCAL_GROUP as INADDR_MAX_LOCAL_GROUP,\n    INADDR_NONE as INADDR_NONE,\n    INADDR_UNSPEC_GROUP as INADDR_UNSPEC_GROUP,\n    IP_ADD_MEMBERSHIP as IP_ADD_MEMBERSHIP,\n    IP_DROP_MEMBERSHIP as IP_DROP_MEMBERSHIP,\n    IP_HDRINCL as IP_HDRINCL,\n    IP_MULTICAST_IF as IP_MULTICAST_IF,\n    IP_MULTICAST_LOOP as IP_MULTICAST_LOOP,\n    IP_MULTICAST_TTL as IP_MULTICAST_TTL,\n    IP_OPTIONS as IP_OPTIONS,\n    IP_TOS as IP_TOS,\n    IP_TTL as IP_TTL,\n    IPPORT_RESERVED as IPPORT_RESERVED,\n    IPPORT_USERRESERVED as IPPORT_USERRESERVED,\n    IPPROTO_AH as IPPROTO_AH,\n    IPPROTO_DSTOPTS as IPPROTO_DSTOPTS,\n    IPPROTO_EGP as IPPROTO_EGP,\n    IPPROTO_ESP as IPPROTO_ESP,\n    IPPROTO_FRAGMENT as IPPROTO_FRAGMENT,\n    IPPROTO_HOPOPTS as IPPROTO_HOPOPTS,\n    IPPROTO_ICMP as IPPROTO_ICMP,\n    IPPROTO_ICMPV6 as IPPROTO_ICMPV6,\n    IPPROTO_IDP as IPPROTO_IDP,\n    IPPROTO_IGMP as IPPROTO_IGMP,\n    IPPROTO_IP as IPPROTO_IP,\n    IPPROTO_IPV6 as IPPROTO_IPV6,\n    IPPROTO_NONE as IPPROTO_NONE,\n    IPPROTO_PIM as IPPROTO_PIM,\n    IPPROTO_PUP as IPPROTO_PUP,\n    IPPROTO_RAW as IPPROTO_RAW,\n    IPPROTO_ROUTING as IPPROTO_ROUTING,\n    IPPROTO_SCTP as IPPROTO_SCTP,\n    IPPROTO_TCP as IPPROTO_TCP,\n    IPPROTO_UDP as IPPROTO_UDP,\n    IPV6_CHECKSUM as IPV6_CHECKSUM,\n    IPV6_DONTFRAG as IPV6_DONTFRAG,\n    IPV6_HOPLIMIT as IPV6_HOPLIMIT,\n    IPV6_HOPOPTS as IPV6_HOPOPTS,\n    IPV6_JOIN_GROUP as IPV6_JOIN_GROUP,\n    IPV6_LEAVE_GROUP as IPV6_LEAVE_GROUP,\n    IPV6_MULTICAST_HOPS as IPV6_MULTICAST_HOPS,\n    IPV6_MULTICAST_IF as IPV6_MULTICAST_IF,\n    IPV6_MULTICAST_LOOP as IPV6_MULTICAST_LOOP,\n    IPV6_PKTINFO as IPV6_PKTINFO,\n    IPV6_RECVRTHDR as IPV6_RECVRTHDR,\n    IPV6_RECVTCLASS as IPV6_RECVTCLASS,\n    IPV6_RTHDR as IPV6_RTHDR,\n    IPV6_TCLASS as IPV6_TCLASS,\n    IPV6_UNICAST_HOPS as IPV6_UNICAST_HOPS,\n    IPV6_V6ONLY as IPV6_V6ONLY,\n    NI_DGRAM as NI_DGRAM,\n    NI_MAXHOST as NI_MAXHOST,\n    NI_MAXSERV as NI_MAXSERV,\n    NI_NAMEREQD as NI_NAMEREQD,\n    NI_NOFQDN as NI_NOFQDN,\n    NI_NUMERICHOST as NI_NUMERICHOST,\n    NI_NUMERICSERV as NI_NUMERICSERV,\n    SHUT_RD as SHUT_RD,\n    SHUT_RDWR as SHUT_RDWR,\n    SHUT_WR as SHUT_WR,\n    SO_ACCEPTCONN as SO_ACCEPTCONN,\n    SO_BROADCAST as SO_BROADCAST,\n    SO_DEBUG as SO_DEBUG,\n    SO_DONTROUTE as SO_DONTROUTE,\n    SO_ERROR as SO_ERROR,\n    SO_KEEPALIVE as SO_KEEPALIVE,\n    SO_LINGER as SO_LINGER,\n    SO_OOBINLINE as SO_OOBINLINE,\n    SO_RCVBUF as SO_RCVBUF,\n    SO_RCVLOWAT as SO_RCVLOWAT,\n    SO_RCVTIMEO as SO_RCVTIMEO,\n    SO_REUSEADDR as SO_REUSEADDR,\n    SO_SNDBUF as SO_SNDBUF,\n    SO_SNDLOWAT as SO_SNDLOWAT,\n    SO_SNDTIMEO as SO_SNDTIMEO,\n    SO_TYPE as SO_TYPE,\n    SOL_IP as SOL_IP,\n    SOL_SOCKET as SOL_SOCKET,\n    SOL_TCP as SOL_TCP,\n    SOL_UDP as SOL_UDP,\n    SOMAXCONN as SOMAXCONN,\n    TCP_FASTOPEN as TCP_FASTOPEN,\n    TCP_KEEPCNT as TCP_KEEPCNT,\n    TCP_KEEPINTVL as TCP_KEEPINTVL,\n    TCP_MAXSEG as TCP_MAXSEG,\n    TCP_NODELAY as TCP_NODELAY,\n    SocketType as SocketType,\n    _Address as _Address,\n    _RetAddress as _RetAddress,\n    close as close,\n    dup as dup,\n    getdefaulttimeout as getdefaulttimeout,\n    gethostbyaddr as gethostbyaddr,\n    gethostbyname as gethostbyname,\n    gethostbyname_ex as gethostbyname_ex,\n    gethostname as gethostname,\n    getnameinfo as getnameinfo,\n    getprotobyname as getprotobyname,\n    getservbyname as getservbyname,\n    getservbyport as getservbyport,\n    has_ipv6 as has_ipv6,\n    htonl as htonl,\n    htons as htons,\n    if_indextoname as if_indextoname,\n    if_nameindex as if_nameindex,\n    if_nametoindex as if_nametoindex,\n    inet_aton as inet_aton,\n    inet_ntoa as inet_ntoa,\n    inet_ntop as inet_ntop,\n    inet_pton as inet_pton,\n    ntohl as ntohl,\n    ntohs as ntohs,\n    setdefaulttimeout as setdefaulttimeout,\n)\nfrom _typeshed import ReadableBuffer, Unused, WriteableBuffer\nfrom collections.abc import Iterable\nfrom enum import IntEnum, IntFlag\nfrom io import BufferedReader, BufferedRWPair, BufferedWriter, IOBase, RawIOBase, TextIOWrapper\nfrom typing import Any, Final, Literal, Protocol, SupportsIndex, overload, type_check_only\nfrom typing_extensions import Self\n\n__all__ = [\n    \"fromfd\",\n    \"getfqdn\",\n    \"create_connection\",\n    \"create_server\",\n    \"has_dualstack_ipv6\",\n    \"AddressFamily\",\n    \"SocketKind\",\n    \"AF_APPLETALK\",\n    \"AF_DECnet\",\n    \"AF_INET\",\n    \"AF_INET6\",\n    \"AF_IPX\",\n    \"AF_SNA\",\n    \"AF_UNSPEC\",\n    \"AI_ADDRCONFIG\",\n    \"AI_ALL\",\n    \"AI_CANONNAME\",\n    \"AI_NUMERICHOST\",\n    \"AI_NUMERICSERV\",\n    \"AI_PASSIVE\",\n    \"AI_V4MAPPED\",\n    \"CAPI\",\n    \"EAI_AGAIN\",\n    \"EAI_BADFLAGS\",\n    \"EAI_FAIL\",\n    \"EAI_FAMILY\",\n    \"EAI_MEMORY\",\n    \"EAI_NODATA\",\n    \"EAI_NONAME\",\n    \"EAI_SERVICE\",\n    \"EAI_SOCKTYPE\",\n    \"INADDR_ALLHOSTS_GROUP\",\n    \"INADDR_ANY\",\n    \"INADDR_BROADCAST\",\n    \"INADDR_LOOPBACK\",\n    \"INADDR_MAX_LOCAL_GROUP\",\n    \"INADDR_NONE\",\n    \"INADDR_UNSPEC_GROUP\",\n    \"IPPORT_RESERVED\",\n    \"IPPORT_USERRESERVED\",\n    \"IPPROTO_AH\",\n    \"IPPROTO_DSTOPTS\",\n    \"IPPROTO_EGP\",\n    \"IPPROTO_ESP\",\n    \"IPPROTO_FRAGMENT\",\n    \"IPPROTO_HOPOPTS\",\n    \"IPPROTO_ICMP\",\n    \"IPPROTO_ICMPV6\",\n    \"IPPROTO_IDP\",\n    \"IPPROTO_IGMP\",\n    \"IPPROTO_IP\",\n    \"IPPROTO_IPV6\",\n    \"IPPROTO_NONE\",\n    \"IPPROTO_PIM\",\n    \"IPPROTO_PUP\",\n    \"IPPROTO_RAW\",\n    \"IPPROTO_ROUTING\",\n    \"IPPROTO_SCTP\",\n    \"IPPROTO_TCP\",\n    \"IPPROTO_UDP\",\n    \"IPV6_CHECKSUM\",\n    \"IPV6_DONTFRAG\",\n    \"IPV6_HOPLIMIT\",\n    \"IPV6_HOPOPTS\",\n    \"IPV6_JOIN_GROUP\",\n    \"IPV6_LEAVE_GROUP\",\n    \"IPV6_MULTICAST_HOPS\",\n    \"IPV6_MULTICAST_IF\",\n    \"IPV6_MULTICAST_LOOP\",\n    \"IPV6_PKTINFO\",\n    \"IPV6_RECVRTHDR\",\n    \"IPV6_RECVTCLASS\",\n    \"IPV6_RTHDR\",\n    \"IPV6_TCLASS\",\n    \"IPV6_UNICAST_HOPS\",\n    \"IPV6_V6ONLY\",\n    \"IP_ADD_MEMBERSHIP\",\n    \"IP_DROP_MEMBERSHIP\",\n    \"IP_HDRINCL\",\n    \"IP_MULTICAST_IF\",\n    \"IP_MULTICAST_LOOP\",\n    \"IP_MULTICAST_TTL\",\n    \"IP_OPTIONS\",\n    \"IP_TOS\",\n    \"IP_TTL\",\n    \"MSG_CTRUNC\",\n    \"MSG_DONTROUTE\",\n    \"MSG_OOB\",\n    \"MSG_PEEK\",\n    \"MSG_TRUNC\",\n    \"MSG_WAITALL\",\n    \"NI_DGRAM\",\n    \"NI_MAXHOST\",\n    \"NI_MAXSERV\",\n    \"NI_NAMEREQD\",\n    \"NI_NOFQDN\",\n    \"NI_NUMERICHOST\",\n    \"NI_NUMERICSERV\",\n    \"SHUT_RD\",\n    \"SHUT_RDWR\",\n    \"SHUT_WR\",\n    \"SOCK_DGRAM\",\n    \"SOCK_RAW\",\n    \"SOCK_RDM\",\n    \"SOCK_SEQPACKET\",\n    \"SOCK_STREAM\",\n    \"SOL_IP\",\n    \"SOL_SOCKET\",\n    \"SOL_TCP\",\n    \"SOL_UDP\",\n    \"SOMAXCONN\",\n    \"SO_ACCEPTCONN\",\n    \"SO_BROADCAST\",\n    \"SO_DEBUG\",\n    \"SO_DONTROUTE\",\n    \"SO_ERROR\",\n    \"SO_KEEPALIVE\",\n    \"SO_LINGER\",\n    \"SO_OOBINLINE\",\n    \"SO_RCVBUF\",\n    \"SO_RCVLOWAT\",\n    \"SO_RCVTIMEO\",\n    \"SO_REUSEADDR\",\n    \"SO_SNDBUF\",\n    \"SO_SNDLOWAT\",\n    \"SO_SNDTIMEO\",\n    \"SO_TYPE\",\n    \"SocketType\",\n    \"TCP_FASTOPEN\",\n    \"TCP_KEEPCNT\",\n    \"TCP_KEEPINTVL\",\n    \"TCP_MAXSEG\",\n    \"TCP_NODELAY\",\n    \"close\",\n    \"dup\",\n    \"error\",\n    \"gaierror\",\n    \"getaddrinfo\",\n    \"getdefaulttimeout\",\n    \"gethostbyaddr\",\n    \"gethostbyname\",\n    \"gethostbyname_ex\",\n    \"gethostname\",\n    \"getnameinfo\",\n    \"getprotobyname\",\n    \"getservbyname\",\n    \"getservbyport\",\n    \"has_ipv6\",\n    \"herror\",\n    \"htonl\",\n    \"htons\",\n    \"if_indextoname\",\n    \"if_nameindex\",\n    \"if_nametoindex\",\n    \"inet_aton\",\n    \"inet_ntoa\",\n    \"inet_ntop\",\n    \"inet_pton\",\n    \"ntohl\",\n    \"ntohs\",\n    \"setdefaulttimeout\",\n    \"socket\",\n    \"socketpair\",\n    \"timeout\",\n]\n\nif sys.platform == \"win32\":\n    from _socket import (\n        IPPROTO_CBT as IPPROTO_CBT,\n        IPPROTO_ICLFXBM as IPPROTO_ICLFXBM,\n        IPPROTO_IGP as IPPROTO_IGP,\n        IPPROTO_L2TP as IPPROTO_L2TP,\n        IPPROTO_PGM as IPPROTO_PGM,\n        IPPROTO_RDP as IPPROTO_RDP,\n        IPPROTO_ST as IPPROTO_ST,\n        RCVALL_MAX as RCVALL_MAX,\n        RCVALL_OFF as RCVALL_OFF,\n        RCVALL_ON as RCVALL_ON,\n        RCVALL_SOCKETLEVELONLY as RCVALL_SOCKETLEVELONLY,\n        SIO_KEEPALIVE_VALS as SIO_KEEPALIVE_VALS,\n        SIO_LOOPBACK_FAST_PATH as SIO_LOOPBACK_FAST_PATH,\n        SIO_RCVALL as SIO_RCVALL,\n        SO_EXCLUSIVEADDRUSE as SO_EXCLUSIVEADDRUSE,\n    )\n\n    __all__ += [\n        \"IPPROTO_CBT\",\n        \"IPPROTO_ICLFXBM\",\n        \"IPPROTO_IGP\",\n        \"IPPROTO_L2TP\",\n        \"IPPROTO_PGM\",\n        \"IPPROTO_RDP\",\n        \"IPPROTO_ST\",\n        \"RCVALL_MAX\",\n        \"RCVALL_OFF\",\n        \"RCVALL_ON\",\n        \"RCVALL_SOCKETLEVELONLY\",\n        \"SIO_KEEPALIVE_VALS\",\n        \"SIO_LOOPBACK_FAST_PATH\",\n        \"SIO_RCVALL\",\n        \"SO_EXCLUSIVEADDRUSE\",\n        \"fromshare\",\n        \"errorTab\",\n        \"MSG_BCAST\",\n        \"MSG_MCAST\",\n    ]\n\nif sys.platform == \"darwin\":\n    from _socket import PF_SYSTEM as PF_SYSTEM, SYSPROTO_CONTROL as SYSPROTO_CONTROL\n\n    __all__ += [\"PF_SYSTEM\", \"SYSPROTO_CONTROL\", \"AF_SYSTEM\"]\n\nif sys.platform != \"darwin\":\n    from _socket import TCP_KEEPIDLE as TCP_KEEPIDLE\n\n    __all__ += [\"TCP_KEEPIDLE\", \"AF_IRDA\", \"MSG_ERRQUEUE\"]\n\nif sys.version_info >= (3, 10):\n    from _socket import IP_RECVTOS as IP_RECVTOS\n\n    __all__ += [\"IP_RECVTOS\"]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    from _socket import (\n        IP_TRANSPARENT as IP_TRANSPARENT,\n        IPX_TYPE as IPX_TYPE,\n        SCM_CREDENTIALS as SCM_CREDENTIALS,\n        SO_DOMAIN as SO_DOMAIN,\n        SO_MARK as SO_MARK,\n        SO_PASSCRED as SO_PASSCRED,\n        SO_PASSSEC as SO_PASSSEC,\n        SO_PEERCRED as SO_PEERCRED,\n        SO_PEERSEC as SO_PEERSEC,\n        SO_PRIORITY as SO_PRIORITY,\n        SO_PROTOCOL as SO_PROTOCOL,\n        SOL_ATALK as SOL_ATALK,\n        SOL_AX25 as SOL_AX25,\n        SOL_HCI as SOL_HCI,\n        SOL_IPX as SOL_IPX,\n        SOL_NETROM as SOL_NETROM,\n        SOL_ROSE as SOL_ROSE,\n        TCP_CONGESTION as TCP_CONGESTION,\n        TCP_CORK as TCP_CORK,\n        TCP_DEFER_ACCEPT as TCP_DEFER_ACCEPT,\n        TCP_INFO as TCP_INFO,\n        TCP_LINGER2 as TCP_LINGER2,\n        TCP_QUICKACK as TCP_QUICKACK,\n        TCP_SYNCNT as TCP_SYNCNT,\n        TCP_USER_TIMEOUT as TCP_USER_TIMEOUT,\n        TCP_WINDOW_CLAMP as TCP_WINDOW_CLAMP,\n    )\n\n    __all__ += [\n        \"IP_TRANSPARENT\",\n        \"SCM_CREDENTIALS\",\n        \"SO_DOMAIN\",\n        \"SO_MARK\",\n        \"SO_PASSCRED\",\n        \"SO_PASSSEC\",\n        \"SO_PEERCRED\",\n        \"SO_PEERSEC\",\n        \"SO_PRIORITY\",\n        \"SO_PROTOCOL\",\n        \"TCP_CONGESTION\",\n        \"TCP_CORK\",\n        \"TCP_DEFER_ACCEPT\",\n        \"TCP_INFO\",\n        \"TCP_LINGER2\",\n        \"TCP_QUICKACK\",\n        \"TCP_SYNCNT\",\n        \"TCP_USER_TIMEOUT\",\n        \"TCP_WINDOW_CLAMP\",\n        \"AF_ASH\",\n        \"AF_ATMPVC\",\n        \"AF_ATMSVC\",\n        \"AF_AX25\",\n        \"AF_BRIDGE\",\n        \"AF_ECONET\",\n        \"AF_KEY\",\n        \"AF_LLC\",\n        \"AF_NETBEUI\",\n        \"AF_NETROM\",\n        \"AF_PPPOX\",\n        \"AF_ROSE\",\n        \"AF_SECURITY\",\n        \"AF_WANPIPE\",\n        \"AF_X25\",\n        \"MSG_CMSG_CLOEXEC\",\n        \"MSG_CONFIRM\",\n        \"MSG_FASTOPEN\",\n        \"MSG_MORE\",\n    ]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.version_info >= (3, 11):\n    from _socket import IP_BIND_ADDRESS_NO_PORT as IP_BIND_ADDRESS_NO_PORT\n\n    __all__ += [\"IP_BIND_ADDRESS_NO_PORT\"]\n\nif sys.platform != \"win32\":\n    from _socket import (\n        CMSG_LEN as CMSG_LEN,\n        CMSG_SPACE as CMSG_SPACE,\n        EAI_ADDRFAMILY as EAI_ADDRFAMILY,\n        EAI_OVERFLOW as EAI_OVERFLOW,\n        EAI_SYSTEM as EAI_SYSTEM,\n        IP_DEFAULT_MULTICAST_LOOP as IP_DEFAULT_MULTICAST_LOOP,\n        IP_DEFAULT_MULTICAST_TTL as IP_DEFAULT_MULTICAST_TTL,\n        IP_MAX_MEMBERSHIPS as IP_MAX_MEMBERSHIPS,\n        IP_RECVOPTS as IP_RECVOPTS,\n        IP_RECVRETOPTS as IP_RECVRETOPTS,\n        IP_RETOPTS as IP_RETOPTS,\n        IPPROTO_GRE as IPPROTO_GRE,\n        IPPROTO_IPIP as IPPROTO_IPIP,\n        IPPROTO_RSVP as IPPROTO_RSVP,\n        IPPROTO_TP as IPPROTO_TP,\n        IPV6_RTHDR_TYPE_0 as IPV6_RTHDR_TYPE_0,\n        SCM_RIGHTS as SCM_RIGHTS,\n        SO_REUSEPORT as SO_REUSEPORT,\n        TCP_NOTSENT_LOWAT as TCP_NOTSENT_LOWAT,\n        sethostname as sethostname,\n    )\n\n    __all__ += [\n        \"CMSG_LEN\",\n        \"CMSG_SPACE\",\n        \"EAI_ADDRFAMILY\",\n        \"EAI_OVERFLOW\",\n        \"EAI_SYSTEM\",\n        \"IP_DEFAULT_MULTICAST_LOOP\",\n        \"IP_DEFAULT_MULTICAST_TTL\",\n        \"IP_MAX_MEMBERSHIPS\",\n        \"IP_RECVOPTS\",\n        \"IP_RECVRETOPTS\",\n        \"IP_RETOPTS\",\n        \"IPPROTO_GRE\",\n        \"IPPROTO_IPIP\",\n        \"IPPROTO_RSVP\",\n        \"IPPROTO_TP\",\n        \"IPV6_RTHDR_TYPE_0\",\n        \"SCM_RIGHTS\",\n        \"SO_REUSEPORT\",\n        \"TCP_NOTSENT_LOWAT\",\n        \"sethostname\",\n        \"AF_ROUTE\",\n        \"AF_UNIX\",\n        \"MSG_DONTWAIT\",\n        \"MSG_EOR\",\n        \"MSG_NOSIGNAL\",\n    ]\n\n    from _socket import (\n        IPV6_DSTOPTS as IPV6_DSTOPTS,\n        IPV6_NEXTHOP as IPV6_NEXTHOP,\n        IPV6_PATHMTU as IPV6_PATHMTU,\n        IPV6_RECVDSTOPTS as IPV6_RECVDSTOPTS,\n        IPV6_RECVHOPLIMIT as IPV6_RECVHOPLIMIT,\n        IPV6_RECVHOPOPTS as IPV6_RECVHOPOPTS,\n        IPV6_RECVPATHMTU as IPV6_RECVPATHMTU,\n        IPV6_RECVPKTINFO as IPV6_RECVPKTINFO,\n        IPV6_RTHDRDSTOPTS as IPV6_RTHDRDSTOPTS,\n    )\n\n    __all__ += [\n        \"IPV6_DSTOPTS\",\n        \"IPV6_NEXTHOP\",\n        \"IPV6_PATHMTU\",\n        \"IPV6_RECVDSTOPTS\",\n        \"IPV6_RECVHOPLIMIT\",\n        \"IPV6_RECVHOPOPTS\",\n        \"IPV6_RECVPATHMTU\",\n        \"IPV6_RECVPKTINFO\",\n        \"IPV6_RTHDRDSTOPTS\",\n    ]\n\n    if sys.platform != \"darwin\" or sys.version_info >= (3, 13):\n        from _socket import SO_BINDTODEVICE as SO_BINDTODEVICE\n\n        __all__ += [\"SO_BINDTODEVICE\"]\n\nif sys.platform != \"darwin\":\n    from _socket import BDADDR_ANY as BDADDR_ANY, BDADDR_LOCAL as BDADDR_LOCAL, BTPROTO_RFCOMM as BTPROTO_RFCOMM\n\nif sys.platform != \"darwin\" and sys.platform != \"linux\":\n    __all__ += [\"BDADDR_ANY\", \"BDADDR_LOCAL\", \"BTPROTO_RFCOMM\"]\n\nif sys.platform == \"darwin\" and sys.version_info >= (3, 10):\n    from _socket import TCP_KEEPALIVE as TCP_KEEPALIVE\n\n    __all__ += [\"TCP_KEEPALIVE\"]\n\nif sys.platform == \"darwin\" and sys.version_info >= (3, 11):\n    from _socket import TCP_CONNECTION_INFO as TCP_CONNECTION_INFO\n\n    __all__ += [\"TCP_CONNECTION_INFO\"]\n\nif sys.platform == \"linux\":\n    from _socket import (\n        ALG_OP_DECRYPT as ALG_OP_DECRYPT,\n        ALG_OP_ENCRYPT as ALG_OP_ENCRYPT,\n        ALG_OP_SIGN as ALG_OP_SIGN,\n        ALG_OP_VERIFY as ALG_OP_VERIFY,\n        ALG_SET_AEAD_ASSOCLEN as ALG_SET_AEAD_ASSOCLEN,\n        ALG_SET_AEAD_AUTHSIZE as ALG_SET_AEAD_AUTHSIZE,\n        ALG_SET_IV as ALG_SET_IV,\n        ALG_SET_KEY as ALG_SET_KEY,\n        ALG_SET_OP as ALG_SET_OP,\n        ALG_SET_PUBKEY as ALG_SET_PUBKEY,\n        CAN_BCM as CAN_BCM,\n        CAN_BCM_CAN_FD_FRAME as CAN_BCM_CAN_FD_FRAME,\n        CAN_BCM_RX_ANNOUNCE_RESUME as CAN_BCM_RX_ANNOUNCE_RESUME,\n        CAN_BCM_RX_CHANGED as CAN_BCM_RX_CHANGED,\n        CAN_BCM_RX_CHECK_DLC as CAN_BCM_RX_CHECK_DLC,\n        CAN_BCM_RX_DELETE as CAN_BCM_RX_DELETE,\n        CAN_BCM_RX_FILTER_ID as CAN_BCM_RX_FILTER_ID,\n        CAN_BCM_RX_NO_AUTOTIMER as CAN_BCM_RX_NO_AUTOTIMER,\n        CAN_BCM_RX_READ as CAN_BCM_RX_READ,\n        CAN_BCM_RX_RTR_FRAME as CAN_BCM_RX_RTR_FRAME,\n        CAN_BCM_RX_SETUP as CAN_BCM_RX_SETUP,\n        CAN_BCM_RX_STATUS as CAN_BCM_RX_STATUS,\n        CAN_BCM_RX_TIMEOUT as CAN_BCM_RX_TIMEOUT,\n        CAN_BCM_SETTIMER as CAN_BCM_SETTIMER,\n        CAN_BCM_STARTTIMER as CAN_BCM_STARTTIMER,\n        CAN_BCM_TX_ANNOUNCE as CAN_BCM_TX_ANNOUNCE,\n        CAN_BCM_TX_COUNTEVT as CAN_BCM_TX_COUNTEVT,\n        CAN_BCM_TX_CP_CAN_ID as CAN_BCM_TX_CP_CAN_ID,\n        CAN_BCM_TX_DELETE as CAN_BCM_TX_DELETE,\n        CAN_BCM_TX_EXPIRED as CAN_BCM_TX_EXPIRED,\n        CAN_BCM_TX_READ as CAN_BCM_TX_READ,\n        CAN_BCM_TX_RESET_MULTI_IDX as CAN_BCM_TX_RESET_MULTI_IDX,\n        CAN_BCM_TX_SEND as CAN_BCM_TX_SEND,\n        CAN_BCM_TX_SETUP as CAN_BCM_TX_SETUP,\n        CAN_BCM_TX_STATUS as CAN_BCM_TX_STATUS,\n        CAN_EFF_FLAG as CAN_EFF_FLAG,\n        CAN_EFF_MASK as CAN_EFF_MASK,\n        CAN_ERR_FLAG as CAN_ERR_FLAG,\n        CAN_ERR_MASK as CAN_ERR_MASK,\n        CAN_ISOTP as CAN_ISOTP,\n        CAN_RAW as CAN_RAW,\n        CAN_RAW_FD_FRAMES as CAN_RAW_FD_FRAMES,\n        CAN_RAW_FILTER as CAN_RAW_FILTER,\n        CAN_RAW_LOOPBACK as CAN_RAW_LOOPBACK,\n        CAN_RAW_RECV_OWN_MSGS as CAN_RAW_RECV_OWN_MSGS,\n        CAN_RTR_FLAG as CAN_RTR_FLAG,\n        CAN_SFF_MASK as CAN_SFF_MASK,\n        IOCTL_VM_SOCKETS_GET_LOCAL_CID as IOCTL_VM_SOCKETS_GET_LOCAL_CID,\n        NETLINK_CRYPTO as NETLINK_CRYPTO,\n        NETLINK_DNRTMSG as NETLINK_DNRTMSG,\n        NETLINK_FIREWALL as NETLINK_FIREWALL,\n        NETLINK_IP6_FW as NETLINK_IP6_FW,\n        NETLINK_NFLOG as NETLINK_NFLOG,\n        NETLINK_ROUTE as NETLINK_ROUTE,\n        NETLINK_USERSOCK as NETLINK_USERSOCK,\n        NETLINK_XFRM as NETLINK_XFRM,\n        PACKET_BROADCAST as PACKET_BROADCAST,\n        PACKET_FASTROUTE as PACKET_FASTROUTE,\n        PACKET_HOST as PACKET_HOST,\n        PACKET_LOOPBACK as PACKET_LOOPBACK,\n        PACKET_MULTICAST as PACKET_MULTICAST,\n        PACKET_OTHERHOST as PACKET_OTHERHOST,\n        PACKET_OUTGOING as PACKET_OUTGOING,\n        PF_CAN as PF_CAN,\n        PF_PACKET as PF_PACKET,\n        PF_RDS as PF_RDS,\n        RDS_CANCEL_SENT_TO as RDS_CANCEL_SENT_TO,\n        RDS_CMSG_RDMA_ARGS as RDS_CMSG_RDMA_ARGS,\n        RDS_CMSG_RDMA_DEST as RDS_CMSG_RDMA_DEST,\n        RDS_CMSG_RDMA_MAP as RDS_CMSG_RDMA_MAP,\n        RDS_CMSG_RDMA_STATUS as RDS_CMSG_RDMA_STATUS,\n        RDS_CONG_MONITOR as RDS_CONG_MONITOR,\n        RDS_FREE_MR as RDS_FREE_MR,\n        RDS_GET_MR as RDS_GET_MR,\n        RDS_GET_MR_FOR_DEST as RDS_GET_MR_FOR_DEST,\n        RDS_RDMA_DONTWAIT as RDS_RDMA_DONTWAIT,\n        RDS_RDMA_FENCE as RDS_RDMA_FENCE,\n        RDS_RDMA_INVALIDATE as RDS_RDMA_INVALIDATE,\n        RDS_RDMA_NOTIFY_ME as RDS_RDMA_NOTIFY_ME,\n        RDS_RDMA_READWRITE as RDS_RDMA_READWRITE,\n        RDS_RDMA_SILENT as RDS_RDMA_SILENT,\n        RDS_RDMA_USE_ONCE as RDS_RDMA_USE_ONCE,\n        RDS_RECVERR as RDS_RECVERR,\n        SO_VM_SOCKETS_BUFFER_MAX_SIZE as SO_VM_SOCKETS_BUFFER_MAX_SIZE,\n        SO_VM_SOCKETS_BUFFER_MIN_SIZE as SO_VM_SOCKETS_BUFFER_MIN_SIZE,\n        SO_VM_SOCKETS_BUFFER_SIZE as SO_VM_SOCKETS_BUFFER_SIZE,\n        SOL_ALG as SOL_ALG,\n        SOL_CAN_BASE as SOL_CAN_BASE,\n        SOL_CAN_RAW as SOL_CAN_RAW,\n        SOL_RDS as SOL_RDS,\n        SOL_TIPC as SOL_TIPC,\n        TIPC_ADDR_ID as TIPC_ADDR_ID,\n        TIPC_ADDR_NAME as TIPC_ADDR_NAME,\n        TIPC_ADDR_NAMESEQ as TIPC_ADDR_NAMESEQ,\n        TIPC_CFG_SRV as TIPC_CFG_SRV,\n        TIPC_CLUSTER_SCOPE as TIPC_CLUSTER_SCOPE,\n        TIPC_CONN_TIMEOUT as TIPC_CONN_TIMEOUT,\n        TIPC_CRITICAL_IMPORTANCE as TIPC_CRITICAL_IMPORTANCE,\n        TIPC_DEST_DROPPABLE as TIPC_DEST_DROPPABLE,\n        TIPC_HIGH_IMPORTANCE as TIPC_HIGH_IMPORTANCE,\n        TIPC_IMPORTANCE as TIPC_IMPORTANCE,\n        TIPC_LOW_IMPORTANCE as TIPC_LOW_IMPORTANCE,\n        TIPC_MEDIUM_IMPORTANCE as TIPC_MEDIUM_IMPORTANCE,\n        TIPC_NODE_SCOPE as TIPC_NODE_SCOPE,\n        TIPC_PUBLISHED as TIPC_PUBLISHED,\n        TIPC_SRC_DROPPABLE as TIPC_SRC_DROPPABLE,\n        TIPC_SUB_CANCEL as TIPC_SUB_CANCEL,\n        TIPC_SUB_PORTS as TIPC_SUB_PORTS,\n        TIPC_SUB_SERVICE as TIPC_SUB_SERVICE,\n        TIPC_SUBSCR_TIMEOUT as TIPC_SUBSCR_TIMEOUT,\n        TIPC_TOP_SRV as TIPC_TOP_SRV,\n        TIPC_WAIT_FOREVER as TIPC_WAIT_FOREVER,\n        TIPC_WITHDRAWN as TIPC_WITHDRAWN,\n        TIPC_ZONE_SCOPE as TIPC_ZONE_SCOPE,\n        VM_SOCKETS_INVALID_VERSION as VM_SOCKETS_INVALID_VERSION,\n        VMADDR_CID_ANY as VMADDR_CID_ANY,\n        VMADDR_CID_HOST as VMADDR_CID_HOST,\n        VMADDR_PORT_ANY as VMADDR_PORT_ANY,\n    )\n\n    __all__ += [\n        \"ALG_OP_DECRYPT\",\n        \"ALG_OP_ENCRYPT\",\n        \"ALG_OP_SIGN\",\n        \"ALG_OP_VERIFY\",\n        \"ALG_SET_AEAD_ASSOCLEN\",\n        \"ALG_SET_AEAD_AUTHSIZE\",\n        \"ALG_SET_IV\",\n        \"ALG_SET_KEY\",\n        \"ALG_SET_OP\",\n        \"ALG_SET_PUBKEY\",\n        \"CAN_BCM\",\n        \"CAN_BCM_CAN_FD_FRAME\",\n        \"CAN_BCM_RX_ANNOUNCE_RESUME\",\n        \"CAN_BCM_RX_CHANGED\",\n        \"CAN_BCM_RX_CHECK_DLC\",\n        \"CAN_BCM_RX_DELETE\",\n        \"CAN_BCM_RX_FILTER_ID\",\n        \"CAN_BCM_RX_NO_AUTOTIMER\",\n        \"CAN_BCM_RX_READ\",\n        \"CAN_BCM_RX_RTR_FRAME\",\n        \"CAN_BCM_RX_SETUP\",\n        \"CAN_BCM_RX_STATUS\",\n        \"CAN_BCM_RX_TIMEOUT\",\n        \"CAN_BCM_SETTIMER\",\n        \"CAN_BCM_STARTTIMER\",\n        \"CAN_BCM_TX_ANNOUNCE\",\n        \"CAN_BCM_TX_COUNTEVT\",\n        \"CAN_BCM_TX_CP_CAN_ID\",\n        \"CAN_BCM_TX_DELETE\",\n        \"CAN_BCM_TX_EXPIRED\",\n        \"CAN_BCM_TX_READ\",\n        \"CAN_BCM_TX_RESET_MULTI_IDX\",\n        \"CAN_BCM_TX_SEND\",\n        \"CAN_BCM_TX_SETUP\",\n        \"CAN_BCM_TX_STATUS\",\n        \"CAN_EFF_FLAG\",\n        \"CAN_EFF_MASK\",\n        \"CAN_ERR_FLAG\",\n        \"CAN_ERR_MASK\",\n        \"CAN_ISOTP\",\n        \"CAN_RAW\",\n        \"CAN_RAW_FD_FRAMES\",\n        \"CAN_RAW_FILTER\",\n        \"CAN_RAW_LOOPBACK\",\n        \"CAN_RAW_RECV_OWN_MSGS\",\n        \"CAN_RTR_FLAG\",\n        \"CAN_SFF_MASK\",\n        \"IOCTL_VM_SOCKETS_GET_LOCAL_CID\",\n        \"NETLINK_CRYPTO\",\n        \"NETLINK_DNRTMSG\",\n        \"NETLINK_FIREWALL\",\n        \"NETLINK_IP6_FW\",\n        \"NETLINK_NFLOG\",\n        \"NETLINK_ROUTE\",\n        \"NETLINK_USERSOCK\",\n        \"NETLINK_XFRM\",\n        \"PACKET_BROADCAST\",\n        \"PACKET_FASTROUTE\",\n        \"PACKET_HOST\",\n        \"PACKET_LOOPBACK\",\n        \"PACKET_MULTICAST\",\n        \"PACKET_OTHERHOST\",\n        \"PACKET_OUTGOING\",\n        \"PF_CAN\",\n        \"PF_PACKET\",\n        \"PF_RDS\",\n        \"SO_VM_SOCKETS_BUFFER_MAX_SIZE\",\n        \"SO_VM_SOCKETS_BUFFER_MIN_SIZE\",\n        \"SO_VM_SOCKETS_BUFFER_SIZE\",\n        \"SOL_ALG\",\n        \"SOL_CAN_BASE\",\n        \"SOL_CAN_RAW\",\n        \"SOL_RDS\",\n        \"SOL_TIPC\",\n        \"TIPC_ADDR_ID\",\n        \"TIPC_ADDR_NAME\",\n        \"TIPC_ADDR_NAMESEQ\",\n        \"TIPC_CFG_SRV\",\n        \"TIPC_CLUSTER_SCOPE\",\n        \"TIPC_CONN_TIMEOUT\",\n        \"TIPC_CRITICAL_IMPORTANCE\",\n        \"TIPC_DEST_DROPPABLE\",\n        \"TIPC_HIGH_IMPORTANCE\",\n        \"TIPC_IMPORTANCE\",\n        \"TIPC_LOW_IMPORTANCE\",\n        \"TIPC_MEDIUM_IMPORTANCE\",\n        \"TIPC_NODE_SCOPE\",\n        \"TIPC_PUBLISHED\",\n        \"TIPC_SRC_DROPPABLE\",\n        \"TIPC_SUB_CANCEL\",\n        \"TIPC_SUB_PORTS\",\n        \"TIPC_SUB_SERVICE\",\n        \"TIPC_SUBSCR_TIMEOUT\",\n        \"TIPC_TOP_SRV\",\n        \"TIPC_WAIT_FOREVER\",\n        \"TIPC_WITHDRAWN\",\n        \"TIPC_ZONE_SCOPE\",\n        \"VM_SOCKETS_INVALID_VERSION\",\n        \"VMADDR_CID_ANY\",\n        \"VMADDR_CID_HOST\",\n        \"VMADDR_PORT_ANY\",\n        \"AF_CAN\",\n        \"AF_PACKET\",\n        \"AF_RDS\",\n        \"AF_TIPC\",\n        \"AF_ALG\",\n        \"AF_NETLINK\",\n        \"AF_VSOCK\",\n        \"AF_QIPCRTR\",\n        \"SOCK_CLOEXEC\",\n        \"SOCK_NONBLOCK\",\n    ]\n\n    if sys.version_info < (3, 11):\n        from _socket import CAN_RAW_ERR_FILTER as CAN_RAW_ERR_FILTER\n\n        __all__ += [\"CAN_RAW_ERR_FILTER\"]\n    if sys.version_info >= (3, 13):\n        from _socket import CAN_RAW_ERR_FILTER as CAN_RAW_ERR_FILTER\n\n        __all__ += [\"CAN_RAW_ERR_FILTER\"]\n\nif sys.platform == \"linux\":\n    from _socket import (\n        CAN_J1939 as CAN_J1939,\n        CAN_RAW_JOIN_FILTERS as CAN_RAW_JOIN_FILTERS,\n        IPPROTO_UDPLITE as IPPROTO_UDPLITE,\n        J1939_EE_INFO_NONE as J1939_EE_INFO_NONE,\n        J1939_EE_INFO_TX_ABORT as J1939_EE_INFO_TX_ABORT,\n        J1939_FILTER_MAX as J1939_FILTER_MAX,\n        J1939_IDLE_ADDR as J1939_IDLE_ADDR,\n        J1939_MAX_UNICAST_ADDR as J1939_MAX_UNICAST_ADDR,\n        J1939_NLA_BYTES_ACKED as J1939_NLA_BYTES_ACKED,\n        J1939_NLA_PAD as J1939_NLA_PAD,\n        J1939_NO_ADDR as J1939_NO_ADDR,\n        J1939_NO_NAME as J1939_NO_NAME,\n        J1939_NO_PGN as J1939_NO_PGN,\n        J1939_PGN_ADDRESS_CLAIMED as J1939_PGN_ADDRESS_CLAIMED,\n        J1939_PGN_ADDRESS_COMMANDED as J1939_PGN_ADDRESS_COMMANDED,\n        J1939_PGN_MAX as J1939_PGN_MAX,\n        J1939_PGN_PDU1_MAX as J1939_PGN_PDU1_MAX,\n        J1939_PGN_REQUEST as J1939_PGN_REQUEST,\n        SCM_J1939_DEST_ADDR as SCM_J1939_DEST_ADDR,\n        SCM_J1939_DEST_NAME as SCM_J1939_DEST_NAME,\n        SCM_J1939_ERRQUEUE as SCM_J1939_ERRQUEUE,\n        SCM_J1939_PRIO as SCM_J1939_PRIO,\n        SO_J1939_ERRQUEUE as SO_J1939_ERRQUEUE,\n        SO_J1939_FILTER as SO_J1939_FILTER,\n        SO_J1939_PROMISC as SO_J1939_PROMISC,\n        SO_J1939_SEND_PRIO as SO_J1939_SEND_PRIO,\n        UDPLITE_RECV_CSCOV as UDPLITE_RECV_CSCOV,\n        UDPLITE_SEND_CSCOV as UDPLITE_SEND_CSCOV,\n    )\n\n    __all__ += [\n        \"CAN_J1939\",\n        \"CAN_RAW_JOIN_FILTERS\",\n        \"IPPROTO_UDPLITE\",\n        \"J1939_EE_INFO_NONE\",\n        \"J1939_EE_INFO_TX_ABORT\",\n        \"J1939_FILTER_MAX\",\n        \"J1939_IDLE_ADDR\",\n        \"J1939_MAX_UNICAST_ADDR\",\n        \"J1939_NLA_BYTES_ACKED\",\n        \"J1939_NLA_PAD\",\n        \"J1939_NO_ADDR\",\n        \"J1939_NO_NAME\",\n        \"J1939_NO_PGN\",\n        \"J1939_PGN_ADDRESS_CLAIMED\",\n        \"J1939_PGN_ADDRESS_COMMANDED\",\n        \"J1939_PGN_MAX\",\n        \"J1939_PGN_PDU1_MAX\",\n        \"J1939_PGN_REQUEST\",\n        \"SCM_J1939_DEST_ADDR\",\n        \"SCM_J1939_DEST_NAME\",\n        \"SCM_J1939_ERRQUEUE\",\n        \"SCM_J1939_PRIO\",\n        \"SO_J1939_ERRQUEUE\",\n        \"SO_J1939_FILTER\",\n        \"SO_J1939_PROMISC\",\n        \"SO_J1939_SEND_PRIO\",\n        \"UDPLITE_RECV_CSCOV\",\n        \"UDPLITE_SEND_CSCOV\",\n    ]\nif sys.platform == \"linux\" and sys.version_info >= (3, 10):\n    from _socket import IPPROTO_MPTCP as IPPROTO_MPTCP\n\n    __all__ += [\"IPPROTO_MPTCP\"]\nif sys.platform == \"linux\" and sys.version_info >= (3, 11):\n    from _socket import SO_INCOMING_CPU as SO_INCOMING_CPU\n\n    __all__ += [\"SO_INCOMING_CPU\"]\nif sys.platform == \"linux\" and sys.version_info >= (3, 12):\n    from _socket import (\n        TCP_CC_INFO as TCP_CC_INFO,\n        TCP_FASTOPEN_CONNECT as TCP_FASTOPEN_CONNECT,\n        TCP_FASTOPEN_KEY as TCP_FASTOPEN_KEY,\n        TCP_FASTOPEN_NO_COOKIE as TCP_FASTOPEN_NO_COOKIE,\n        TCP_INQ as TCP_INQ,\n        TCP_MD5SIG as TCP_MD5SIG,\n        TCP_MD5SIG_EXT as TCP_MD5SIG_EXT,\n        TCP_QUEUE_SEQ as TCP_QUEUE_SEQ,\n        TCP_REPAIR as TCP_REPAIR,\n        TCP_REPAIR_OPTIONS as TCP_REPAIR_OPTIONS,\n        TCP_REPAIR_QUEUE as TCP_REPAIR_QUEUE,\n        TCP_REPAIR_WINDOW as TCP_REPAIR_WINDOW,\n        TCP_SAVE_SYN as TCP_SAVE_SYN,\n        TCP_SAVED_SYN as TCP_SAVED_SYN,\n        TCP_THIN_DUPACK as TCP_THIN_DUPACK,\n        TCP_THIN_LINEAR_TIMEOUTS as TCP_THIN_LINEAR_TIMEOUTS,\n        TCP_TIMESTAMP as TCP_TIMESTAMP,\n        TCP_TX_DELAY as TCP_TX_DELAY,\n        TCP_ULP as TCP_ULP,\n        TCP_ZEROCOPY_RECEIVE as TCP_ZEROCOPY_RECEIVE,\n    )\n\n    __all__ += [\n        \"TCP_CC_INFO\",\n        \"TCP_FASTOPEN_CONNECT\",\n        \"TCP_FASTOPEN_KEY\",\n        \"TCP_FASTOPEN_NO_COOKIE\",\n        \"TCP_INQ\",\n        \"TCP_MD5SIG\",\n        \"TCP_MD5SIG_EXT\",\n        \"TCP_QUEUE_SEQ\",\n        \"TCP_REPAIR\",\n        \"TCP_REPAIR_OPTIONS\",\n        \"TCP_REPAIR_QUEUE\",\n        \"TCP_REPAIR_WINDOW\",\n        \"TCP_SAVED_SYN\",\n        \"TCP_SAVE_SYN\",\n        \"TCP_THIN_DUPACK\",\n        \"TCP_THIN_LINEAR_TIMEOUTS\",\n        \"TCP_TIMESTAMP\",\n        \"TCP_TX_DELAY\",\n        \"TCP_ULP\",\n        \"TCP_ZEROCOPY_RECEIVE\",\n    ]\n\nif sys.platform == \"linux\" and sys.version_info >= (3, 13):\n    from _socket import NI_IDN as NI_IDN, SO_BINDTOIFINDEX as SO_BINDTOIFINDEX\n\n    __all__ += [\"NI_IDN\", \"SO_BINDTOIFINDEX\"]\n\nif sys.version_info >= (3, 12):\n    from _socket import (\n        IP_ADD_SOURCE_MEMBERSHIP as IP_ADD_SOURCE_MEMBERSHIP,\n        IP_BLOCK_SOURCE as IP_BLOCK_SOURCE,\n        IP_DROP_SOURCE_MEMBERSHIP as IP_DROP_SOURCE_MEMBERSHIP,\n        IP_PKTINFO as IP_PKTINFO,\n        IP_UNBLOCK_SOURCE as IP_UNBLOCK_SOURCE,\n    )\n\n    __all__ += [\"IP_ADD_SOURCE_MEMBERSHIP\", \"IP_BLOCK_SOURCE\", \"IP_DROP_SOURCE_MEMBERSHIP\", \"IP_PKTINFO\", \"IP_UNBLOCK_SOURCE\"]\n\n    if sys.platform == \"win32\":\n        from _socket import (\n            HV_GUID_BROADCAST as HV_GUID_BROADCAST,\n            HV_GUID_CHILDREN as HV_GUID_CHILDREN,\n            HV_GUID_LOOPBACK as HV_GUID_LOOPBACK,\n            HV_GUID_PARENT as HV_GUID_PARENT,\n            HV_GUID_WILDCARD as HV_GUID_WILDCARD,\n            HV_GUID_ZERO as HV_GUID_ZERO,\n            HV_PROTOCOL_RAW as HV_PROTOCOL_RAW,\n            HVSOCKET_ADDRESS_FLAG_PASSTHRU as HVSOCKET_ADDRESS_FLAG_PASSTHRU,\n            HVSOCKET_CONNECT_TIMEOUT as HVSOCKET_CONNECT_TIMEOUT,\n            HVSOCKET_CONNECT_TIMEOUT_MAX as HVSOCKET_CONNECT_TIMEOUT_MAX,\n            HVSOCKET_CONNECTED_SUSPEND as HVSOCKET_CONNECTED_SUSPEND,\n        )\n\n        __all__ += [\n            \"HV_GUID_BROADCAST\",\n            \"HV_GUID_CHILDREN\",\n            \"HV_GUID_LOOPBACK\",\n            \"HV_GUID_PARENT\",\n            \"HV_GUID_WILDCARD\",\n            \"HV_GUID_ZERO\",\n            \"HV_PROTOCOL_RAW\",\n            \"HVSOCKET_ADDRESS_FLAG_PASSTHRU\",\n            \"HVSOCKET_CONNECT_TIMEOUT\",\n            \"HVSOCKET_CONNECT_TIMEOUT_MAX\",\n            \"HVSOCKET_CONNECTED_SUSPEND\",\n        ]\n    else:\n        from _socket import (\n            ETHERTYPE_ARP as ETHERTYPE_ARP,\n            ETHERTYPE_IP as ETHERTYPE_IP,\n            ETHERTYPE_IPV6 as ETHERTYPE_IPV6,\n            ETHERTYPE_VLAN as ETHERTYPE_VLAN,\n        )\n\n        __all__ += [\"ETHERTYPE_ARP\", \"ETHERTYPE_IP\", \"ETHERTYPE_IPV6\", \"ETHERTYPE_VLAN\"]\n\n    if sys.platform == \"linux\":\n        from _socket import ETH_P_ALL as ETH_P_ALL\n\n        __all__ += [\"ETH_P_ALL\"]\n\n    if sys.platform != \"linux\" and sys.platform != \"win32\" and sys.platform != \"darwin\":\n        # FreeBSD >= 14.0\n        from _socket import PF_DIVERT as PF_DIVERT\n\n        __all__ += [\"PF_DIVERT\", \"AF_DIVERT\"]\n\nif sys.platform != \"win32\":\n    __all__ += [\"send_fds\", \"recv_fds\"]\n\nif sys.platform != \"linux\":\n    __all__ += [\"AF_LINK\"]\nif sys.platform != \"darwin\" and sys.platform != \"linux\":\n    __all__ += [\"AF_BLUETOOTH\"]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    from _socket import BTPROTO_HCI as BTPROTO_HCI, BTPROTO_L2CAP as BTPROTO_L2CAP, BTPROTO_SCO as BTPROTO_SCO\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    __all__ += [\"BTPROTO_HCI\", \"BTPROTO_L2CAP\", \"BTPROTO_SCO\"]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    from _socket import HCI_DATA_DIR as HCI_DATA_DIR, HCI_FILTER as HCI_FILTER, HCI_TIME_STAMP as HCI_TIME_STAMP\n\n    __all__ += [\"HCI_FILTER\", \"HCI_TIME_STAMP\", \"HCI_DATA_DIR\"]\n\nif sys.version_info >= (3, 11) and sys.platform != \"linux\" and sys.platform != \"win32\" and sys.platform != \"darwin\":\n    from _socket import LOCAL_CREDS as LOCAL_CREDS, LOCAL_CREDS_PERSISTENT as LOCAL_CREDS_PERSISTENT, SCM_CREDS2 as SCM_CREDS2\n\n    __all__ += [\"SCM_CREDS2\", \"LOCAL_CREDS\", \"LOCAL_CREDS_PERSISTENT\"]\n\nif sys.platform == \"win32\" and sys.version_info >= (3, 12):\n    __all__ += [\"AF_HYPERV\"]\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    from _socket import (\n        EAI_BADHINTS as EAI_BADHINTS,\n        EAI_MAX as EAI_MAX,\n        EAI_PROTOCOL as EAI_PROTOCOL,\n        IPPROTO_EON as IPPROTO_EON,\n        IPPROTO_HELLO as IPPROTO_HELLO,\n        IPPROTO_IPCOMP as IPPROTO_IPCOMP,\n        IPPROTO_XTP as IPPROTO_XTP,\n        IPV6_USE_MIN_MTU as IPV6_USE_MIN_MTU,\n        LOCAL_PEERCRED as LOCAL_PEERCRED,\n        SCM_CREDS as SCM_CREDS,\n    )\n\n    __all__ += [\n        \"EAI_BADHINTS\",\n        \"EAI_MAX\",\n        \"EAI_PROTOCOL\",\n        \"IPPROTO_EON\",\n        \"IPPROTO_HELLO\",\n        \"IPPROTO_IPCOMP\",\n        \"IPPROTO_XTP\",\n        \"IPV6_USE_MIN_MTU\",\n        \"LOCAL_PEERCRED\",\n        \"SCM_CREDS\",\n        \"AI_DEFAULT\",\n        \"AI_MASK\",\n        \"AI_V4MAPPED_CFG\",\n        \"MSG_EOF\",\n    ]\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    from _socket import (\n        IPPROTO_BIP as IPPROTO_BIP,\n        IPPROTO_MOBILE as IPPROTO_MOBILE,\n        IPPROTO_VRRP as IPPROTO_VRRP,\n        MSG_BTAG as MSG_BTAG,\n        MSG_ETAG as MSG_ETAG,\n        SO_SETFIB as SO_SETFIB,\n    )\n\n    __all__ += [\"SO_SETFIB\", \"MSG_BTAG\", \"MSG_ETAG\", \"IPPROTO_BIP\", \"IPPROTO_MOBILE\", \"IPPROTO_VRRP\", \"MSG_NOTIFICATION\"]\n\nif sys.platform != \"linux\":\n    from _socket import (\n        IP_RECVDSTADDR as IP_RECVDSTADDR,\n        IPPROTO_GGP as IPPROTO_GGP,\n        IPPROTO_IPV4 as IPPROTO_IPV4,\n        IPPROTO_MAX as IPPROTO_MAX,\n        IPPROTO_ND as IPPROTO_ND,\n        SO_USELOOPBACK as SO_USELOOPBACK,\n    )\n\n    __all__ += [\"IPPROTO_GGP\", \"IPPROTO_IPV4\", \"IPPROTO_MAX\", \"IPPROTO_ND\", \"IP_RECVDSTADDR\", \"SO_USELOOPBACK\"]\n\nif sys.version_info >= (3, 14):\n    from _socket import IP_RECVTTL as IP_RECVTTL\n\n    __all__ += [\"IP_RECVTTL\"]\n\n    if sys.platform == \"win32\" or sys.platform == \"linux\":\n        from _socket import IP_RECVERR as IP_RECVERR, IPV6_RECVERR as IPV6_RECVERR, SO_ORIGINAL_DST as SO_ORIGINAL_DST\n\n        __all__ += [\"IP_RECVERR\", \"IPV6_RECVERR\", \"SO_ORIGINAL_DST\"]\n\n    if sys.platform == \"win32\":\n        from _socket import (\n            SO_BTH_ENCRYPT as SO_BTH_ENCRYPT,\n            SO_BTH_MTU as SO_BTH_MTU,\n            SO_BTH_MTU_MAX as SO_BTH_MTU_MAX,\n            SO_BTH_MTU_MIN as SO_BTH_MTU_MIN,\n            SOL_RFCOMM as SOL_RFCOMM,\n            TCP_QUICKACK as TCP_QUICKACK,\n        )\n\n        __all__ += [\"SOL_RFCOMM\", \"SO_BTH_ENCRYPT\", \"SO_BTH_MTU\", \"SO_BTH_MTU_MAX\", \"SO_BTH_MTU_MIN\", \"TCP_QUICKACK\"]\n\n    if sys.platform == \"linux\":\n        from _socket import (\n            IP_FREEBIND as IP_FREEBIND,\n            IP_RECVORIGDSTADDR as IP_RECVORIGDSTADDR,\n            VMADDR_CID_LOCAL as VMADDR_CID_LOCAL,\n        )\n\n        __all__ += [\"IP_FREEBIND\", \"IP_RECVORIGDSTADDR\", \"VMADDR_CID_LOCAL\"]\n\n# Re-exported from errno\nEBADF: Final[int]\nEAGAIN: Final[int]\nEWOULDBLOCK: Final[int]\n\n# These errors are implemented in _socket at runtime\n# but they consider themselves to live in socket so we'll put them here.\nerror = OSError\n\nclass herror(error): ...\nclass gaierror(error): ...\n\nif sys.version_info >= (3, 10):\n    timeout = TimeoutError\nelse:\n    class timeout(error): ...\n\nclass AddressFamily(IntEnum):\n    AF_INET = 2\n    AF_INET6 = 10\n    AF_APPLETALK = 5\n    AF_IPX = 4\n    AF_SNA = 22\n    AF_UNSPEC = 0\n    if sys.platform != \"darwin\":\n        AF_IRDA = 23\n    if sys.platform != \"win32\":\n        AF_ROUTE = 16\n        AF_UNIX = 1\n    if sys.platform == \"darwin\":\n        AF_SYSTEM = 32\n    if sys.platform != \"win32\" and sys.platform != \"darwin\":\n        AF_ASH = 18\n        AF_ATMPVC = 8\n        AF_ATMSVC = 20\n        AF_AX25 = 3\n        AF_BRIDGE = 7\n        AF_ECONET = 19\n        AF_KEY = 15\n        AF_LLC = 26\n        AF_NETBEUI = 13\n        AF_NETROM = 6\n        AF_PPPOX = 24\n        AF_ROSE = 11\n        AF_SECURITY = 14\n        AF_WANPIPE = 25\n        AF_X25 = 9\n    if sys.platform == \"linux\":\n        AF_CAN = 29\n        AF_PACKET = 17\n        AF_RDS = 21\n        AF_TIPC = 30\n        AF_ALG = 38\n        AF_NETLINK = 16\n        AF_VSOCK = 40\n        AF_QIPCRTR = 42\n    if sys.platform != \"linux\":\n        AF_LINK = 33\n    if sys.platform != \"darwin\":\n        AF_BLUETOOTH = 32\n    if sys.platform == \"win32\" and sys.version_info >= (3, 12):\n        AF_HYPERV = 34\n    if sys.platform != \"linux\" and sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.version_info >= (3, 12):\n        # FreeBSD >= 14.0\n        AF_DIVERT = 44\n\nAF_INET: Final = AddressFamily.AF_INET\nAF_INET6: Final = AddressFamily.AF_INET6\nAF_APPLETALK: Final = AddressFamily.AF_APPLETALK\nAF_DECnet: Final = 12\nAF_IPX: Final = AddressFamily.AF_IPX\nAF_SNA: Final = AddressFamily.AF_SNA\nAF_UNSPEC: Final = AddressFamily.AF_UNSPEC\n\nif sys.platform != \"darwin\":\n    AF_IRDA: Final = AddressFamily.AF_IRDA\n\nif sys.platform != \"win32\":\n    AF_ROUTE: Final = AddressFamily.AF_ROUTE\n    AF_UNIX: Final = AddressFamily.AF_UNIX\n\nif sys.platform == \"darwin\":\n    AF_SYSTEM: Final = AddressFamily.AF_SYSTEM\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    AF_ASH: Final = AddressFamily.AF_ASH\n    AF_ATMPVC: Final = AddressFamily.AF_ATMPVC\n    AF_ATMSVC: Final = AddressFamily.AF_ATMSVC\n    AF_AX25: Final = AddressFamily.AF_AX25\n    AF_BRIDGE: Final = AddressFamily.AF_BRIDGE\n    AF_ECONET: Final = AddressFamily.AF_ECONET\n    AF_KEY: Final = AddressFamily.AF_KEY\n    AF_LLC: Final = AddressFamily.AF_LLC\n    AF_NETBEUI: Final = AddressFamily.AF_NETBEUI\n    AF_NETROM: Final = AddressFamily.AF_NETROM\n    AF_PPPOX: Final = AddressFamily.AF_PPPOX\n    AF_ROSE: Final = AddressFamily.AF_ROSE\n    AF_SECURITY: Final = AddressFamily.AF_SECURITY\n    AF_WANPIPE: Final = AddressFamily.AF_WANPIPE\n    AF_X25: Final = AddressFamily.AF_X25\n\nif sys.platform == \"linux\":\n    AF_CAN: Final = AddressFamily.AF_CAN\n    AF_PACKET: Final = AddressFamily.AF_PACKET\n    AF_RDS: Final = AddressFamily.AF_RDS\n    AF_TIPC: Final = AddressFamily.AF_TIPC\n    AF_ALG: Final = AddressFamily.AF_ALG\n    AF_NETLINK: Final = AddressFamily.AF_NETLINK\n    AF_VSOCK: Final = AddressFamily.AF_VSOCK\n    AF_QIPCRTR: Final = AddressFamily.AF_QIPCRTR\n\nif sys.platform != \"linux\":\n    AF_LINK: Final = AddressFamily.AF_LINK\nif sys.platform != \"darwin\":\n    AF_BLUETOOTH: Final = AddressFamily.AF_BLUETOOTH\nif sys.platform == \"win32\" and sys.version_info >= (3, 12):\n    AF_HYPERV: Final = AddressFamily.AF_HYPERV\nif sys.platform != \"linux\" and sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.version_info >= (3, 12):\n    # FreeBSD >= 14.0\n    AF_DIVERT: Final = AddressFamily.AF_DIVERT\n\nclass SocketKind(IntEnum):\n    SOCK_STREAM = 1\n    SOCK_DGRAM = 2\n    SOCK_RAW = 3\n    SOCK_RDM = 4\n    SOCK_SEQPACKET = 5\n    if sys.platform == \"linux\":\n        SOCK_CLOEXEC = 524288\n        SOCK_NONBLOCK = 2048\n\nSOCK_STREAM: Final = SocketKind.SOCK_STREAM\nSOCK_DGRAM: Final = SocketKind.SOCK_DGRAM\nSOCK_RAW: Final = SocketKind.SOCK_RAW\nSOCK_RDM: Final = SocketKind.SOCK_RDM\nSOCK_SEQPACKET: Final = SocketKind.SOCK_SEQPACKET\nif sys.platform == \"linux\":\n    SOCK_CLOEXEC: Final = SocketKind.SOCK_CLOEXEC\n    SOCK_NONBLOCK: Final = SocketKind.SOCK_NONBLOCK\n\nclass MsgFlag(IntFlag):\n    MSG_CTRUNC = 8\n    MSG_DONTROUTE = 4\n    MSG_OOB = 1\n    MSG_PEEK = 2\n    MSG_TRUNC = 32\n    MSG_WAITALL = 256\n    if sys.platform == \"win32\":\n        MSG_BCAST = 1024\n        MSG_MCAST = 2048\n\n    if sys.platform != \"darwin\":\n        MSG_ERRQUEUE = 8192\n\n    if sys.platform != \"win32\" and sys.platform != \"darwin\":\n        MSG_CMSG_CLOEXEC = 1073741821\n        MSG_CONFIRM = 2048\n        MSG_FASTOPEN = 536870912\n        MSG_MORE = 32768\n\n    if sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n        MSG_NOTIFICATION = 8192\n\n    if sys.platform != \"win32\":\n        MSG_DONTWAIT = 64\n        MSG_EOR = 128\n        MSG_NOSIGNAL = 16384  # sometimes this exists on darwin, sometimes not\n    if sys.platform != \"win32\" and sys.platform != \"linux\":\n        MSG_EOF = 256\n\nMSG_CTRUNC: Final = MsgFlag.MSG_CTRUNC\nMSG_DONTROUTE: Final = MsgFlag.MSG_DONTROUTE\nMSG_OOB: Final = MsgFlag.MSG_OOB\nMSG_PEEK: Final = MsgFlag.MSG_PEEK\nMSG_TRUNC: Final = MsgFlag.MSG_TRUNC\nMSG_WAITALL: Final = MsgFlag.MSG_WAITALL\n\nif sys.platform == \"win32\":\n    MSG_BCAST: Final = MsgFlag.MSG_BCAST\n    MSG_MCAST: Final = MsgFlag.MSG_MCAST\n\nif sys.platform != \"darwin\":\n    MSG_ERRQUEUE: Final = MsgFlag.MSG_ERRQUEUE\n\nif sys.platform != \"win32\":\n    MSG_DONTWAIT: Final = MsgFlag.MSG_DONTWAIT\n    MSG_EOR: Final = MsgFlag.MSG_EOR\n    MSG_NOSIGNAL: Final = MsgFlag.MSG_NOSIGNAL  # Sometimes this exists on darwin, sometimes not\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\":\n    MSG_CMSG_CLOEXEC: Final = MsgFlag.MSG_CMSG_CLOEXEC\n    MSG_CONFIRM: Final = MsgFlag.MSG_CONFIRM\n    MSG_FASTOPEN: Final = MsgFlag.MSG_FASTOPEN\n    MSG_MORE: Final = MsgFlag.MSG_MORE\n\nif sys.platform != \"win32\" and sys.platform != \"darwin\" and sys.platform != \"linux\":\n    MSG_NOTIFICATION: Final = MsgFlag.MSG_NOTIFICATION\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    MSG_EOF: Final = MsgFlag.MSG_EOF\n\nclass AddressInfo(IntFlag):\n    AI_ADDRCONFIG = 32\n    AI_ALL = 16\n    AI_CANONNAME = 2\n    AI_NUMERICHOST = 4\n    AI_NUMERICSERV = 1024\n    AI_PASSIVE = 1\n    AI_V4MAPPED = 8\n    if sys.platform != \"win32\" and sys.platform != \"linux\":\n        AI_DEFAULT = 1536\n        AI_MASK = 5127\n        AI_V4MAPPED_CFG = 512\n\nAI_ADDRCONFIG: Final = AddressInfo.AI_ADDRCONFIG\nAI_ALL: Final = AddressInfo.AI_ALL\nAI_CANONNAME: Final = AddressInfo.AI_CANONNAME\nAI_NUMERICHOST: Final = AddressInfo.AI_NUMERICHOST\nAI_NUMERICSERV: Final = AddressInfo.AI_NUMERICSERV\nAI_PASSIVE: Final = AddressInfo.AI_PASSIVE\nAI_V4MAPPED: Final = AddressInfo.AI_V4MAPPED\n\nif sys.platform != \"win32\" and sys.platform != \"linux\":\n    AI_DEFAULT: Final = AddressInfo.AI_DEFAULT\n    AI_MASK: Final = AddressInfo.AI_MASK\n    AI_V4MAPPED_CFG: Final = AddressInfo.AI_V4MAPPED_CFG\n\nif sys.platform == \"win32\":\n    errorTab: dict[int, str]  # undocumented\n\n@type_check_only\nclass _SendableFile(Protocol):\n    def read(self, size: int, /) -> bytes: ...\n    def seek(self, offset: int, /) -> object: ...\n\n    # optional fields:\n    #\n    # @property\n    # def mode(self) -> str: ...\n    # def fileno(self) -> int: ...\n\nclass socket(_socket.socket):\n    __slots__ = [\"__weakref__\", \"_io_refs\", \"_closed\"]\n    def __init__(\n        self, family: AddressFamily | int = -1, type: SocketKind | int = -1, proto: int = -1, fileno: int | None = None\n    ) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n    def dup(self) -> Self: ...\n    def accept(self) -> tuple[socket, _RetAddress]: ...\n    # Note that the makefile's documented windows-specific behavior is not represented\n    # mode strings with duplicates are intentionally excluded\n    @overload\n    def makefile(\n        self,\n        mode: Literal[\"b\", \"rb\", \"br\", \"wb\", \"bw\", \"rwb\", \"rbw\", \"wrb\", \"wbr\", \"brw\", \"bwr\"],\n        buffering: Literal[0],\n        *,\n        encoding: str | None = None,\n        errors: str | None = None,\n        newline: str | None = None,\n    ) -> SocketIO: ...\n    @overload\n    def makefile(\n        self,\n        mode: Literal[\"rwb\", \"rbw\", \"wrb\", \"wbr\", \"brw\", \"bwr\"],\n        buffering: Literal[-1, 1] | None = None,\n        *,\n        encoding: str | None = None,\n        errors: str | None = None,\n        newline: str | None = None,\n    ) -> BufferedRWPair: ...\n    @overload\n    def makefile(\n        self,\n        mode: Literal[\"rb\", \"br\"],\n        buffering: Literal[-1, 1] | None = None,\n        *,\n        encoding: str | None = None,\n        errors: str | None = None,\n        newline: str | None = None,\n    ) -> BufferedReader: ...\n    @overload\n    def makefile(\n        self,\n        mode: Literal[\"wb\", \"bw\"],\n        buffering: Literal[-1, 1] | None = None,\n        *,\n        encoding: str | None = None,\n        errors: str | None = None,\n        newline: str | None = None,\n    ) -> BufferedWriter: ...\n    @overload\n    def makefile(\n        self,\n        mode: Literal[\"b\", \"rb\", \"br\", \"wb\", \"bw\", \"rwb\", \"rbw\", \"wrb\", \"wbr\", \"brw\", \"bwr\"],\n        buffering: int,\n        *,\n        encoding: str | None = None,\n        errors: str | None = None,\n        newline: str | None = None,\n    ) -> IOBase: ...\n    @overload\n    def makefile(\n        self,\n        mode: Literal[\"r\", \"w\", \"rw\", \"wr\", \"\"] = \"r\",\n        buffering: int | None = None,\n        *,\n        encoding: str | None = None,\n        errors: str | None = None,\n        newline: str | None = None,\n    ) -> TextIOWrapper: ...\n    def sendfile(self, file: _SendableFile, offset: int = 0, count: int | None = None) -> int: ...\n    @property\n    def family(self) -> AddressFamily: ...\n    @property\n    def type(self) -> SocketKind: ...\n    def get_inheritable(self) -> bool: ...\n    def set_inheritable(self, inheritable: bool) -> None: ...\n\ndef fromfd(fd: SupportsIndex, family: AddressFamily | int, type: SocketKind | int, proto: int = 0) -> socket: ...\n\nif sys.platform != \"win32\":\n    def send_fds(\n        sock: socket, buffers: Iterable[ReadableBuffer], fds: Iterable[int], flags: Unused = 0, address: Unused = None\n    ) -> int: ...\n    def recv_fds(sock: socket, bufsize: int, maxfds: int, flags: int = 0) -> tuple[bytes, list[int], int, Any]: ...\n\nif sys.platform == \"win32\":\n    def fromshare(info: bytes) -> socket: ...\n\nif sys.platform == \"win32\":\n    def socketpair(family: int = ..., type: int = ..., proto: int = 0) -> tuple[socket, socket]: ...\n\nelse:\n    def socketpair(\n        family: int | AddressFamily | None = None, type: SocketKind | int = ..., proto: int = 0\n    ) -> tuple[socket, socket]: ...\n\nclass SocketIO(RawIOBase):\n    def __init__(self, sock: socket, mode: Literal[\"r\", \"w\", \"rw\", \"rb\", \"wb\", \"rwb\"]) -> None: ...\n    def readinto(self, b: WriteableBuffer) -> int | None: ...\n    def write(self, b: ReadableBuffer) -> int | None: ...\n    @property\n    def name(self) -> int: ...  # return value is really \"int\"\n    @property\n    def mode(self) -> Literal[\"rb\", \"wb\", \"rwb\"]: ...\n\ndef getfqdn(name: str = \"\") -> str: ...\n\nif sys.version_info >= (3, 11):\n    def create_connection(\n        address: tuple[str | None, bytes | str | int | None],\n        timeout: float | None = ...,\n        source_address: _Address | None = None,\n        *,\n        all_errors: bool = False,\n    ) -> socket: ...\n\nelse:\n    def create_connection(\n        address: tuple[str | None, int], timeout: float | None = ..., source_address: _Address | None = None\n    ) -> socket: ...\n\ndef has_dualstack_ipv6() -> bool: ...\ndef create_server(\n    address: _Address, *, family: int = ..., backlog: int | None = None, reuse_port: bool = False, dualstack_ipv6: bool = False\n) -> socket: ...\n\n# The 5th tuple item is the socket address, for IP4, IP6, or IP6 if Python is compiled with --disable-ipv6, respectively.\ndef getaddrinfo(\n    host: bytes | str | None, port: bytes | str | int | None, family: int = 0, type: int = 0, proto: int = 0, flags: int = 0\n) -> list[tuple[AddressFamily, SocketKind, int, str, tuple[str, int] | tuple[str, int, int, int] | tuple[int, bytes]]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/socketserver.pyi",
    "content": "import sys\nimport types\nfrom _socket import _Address, _RetAddress\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Callable\nfrom io import BufferedIOBase\nfrom socket import socket as _socket\nfrom typing import Any, ClassVar\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\n    \"BaseServer\",\n    \"TCPServer\",\n    \"UDPServer\",\n    \"ThreadingUDPServer\",\n    \"ThreadingTCPServer\",\n    \"BaseRequestHandler\",\n    \"StreamRequestHandler\",\n    \"DatagramRequestHandler\",\n    \"ThreadingMixIn\",\n]\nif sys.platform != \"win32\":\n    __all__ += [\n        \"ForkingMixIn\",\n        \"ForkingTCPServer\",\n        \"ForkingUDPServer\",\n        \"ThreadingUnixDatagramServer\",\n        \"ThreadingUnixStreamServer\",\n        \"UnixDatagramServer\",\n        \"UnixStreamServer\",\n    ]\n    if sys.version_info >= (3, 12):\n        __all__ += [\"ForkingUnixStreamServer\", \"ForkingUnixDatagramServer\"]\n\n_RequestType: TypeAlias = _socket | tuple[bytes, _socket]\n_AfUnixAddress: TypeAlias = str | ReadableBuffer  # address acceptable for an AF_UNIX socket\n_AfInetAddress: TypeAlias = tuple[str | bytes | bytearray, int]  # address acceptable for an AF_INET socket\n_AfInet6Address: TypeAlias = tuple[str | bytes | bytearray, int, int, int]  # address acceptable for an AF_INET6 socket\n\n# This can possibly be generic at some point:\nclass BaseServer:\n    server_address: _Address\n    timeout: float | None\n    RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler]\n    def __init__(\n        self, server_address: _Address, RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler]\n    ) -> None: ...\n    def handle_request(self) -> None: ...\n    def serve_forever(self, poll_interval: float = 0.5) -> None: ...\n    def shutdown(self) -> None: ...\n    def server_close(self) -> None: ...\n    def finish_request(self, request: _RequestType, client_address: _RetAddress) -> None: ...\n    def get_request(self) -> tuple[Any, Any]: ...  # Not implemented here, but expected to exist on subclasses\n    def handle_error(self, request: _RequestType, client_address: _RetAddress) -> None: ...\n    def handle_timeout(self) -> None: ...\n    def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: ...\n    def server_activate(self) -> None: ...\n    def verify_request(self, request: _RequestType, client_address: _RetAddress) -> bool: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: types.TracebackType | None\n    ) -> None: ...\n    def service_actions(self) -> None: ...\n    def shutdown_request(self, request: _RequestType) -> None: ...  # undocumented\n    def close_request(self, request: _RequestType) -> None: ...  # undocumented\n\nclass TCPServer(BaseServer):\n    address_family: int\n    socket: _socket\n    allow_reuse_address: bool\n    request_queue_size: int\n    socket_type: int\n    if sys.version_info >= (3, 11):\n        allow_reuse_port: bool\n    server_address: _AfInetAddress | _AfInet6Address\n    def __init__(\n        self,\n        server_address: _AfInetAddress | _AfInet6Address,\n        RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler],\n        bind_and_activate: bool = True,\n    ) -> None: ...\n    def fileno(self) -> int: ...\n    def get_request(self) -> tuple[_socket, _RetAddress]: ...\n    def server_bind(self) -> None: ...\n\nclass UDPServer(TCPServer):\n    max_packet_size: ClassVar[int]\n    def get_request(self) -> tuple[tuple[bytes, _socket], _RetAddress]: ...  # type: ignore[override]\n\nif sys.platform != \"win32\":\n    class UnixStreamServer(TCPServer):\n        server_address: _AfUnixAddress  # type: ignore[assignment]\n        def __init__(\n            self,\n            server_address: _AfUnixAddress,\n            RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler],\n            bind_and_activate: bool = True,\n        ) -> None: ...\n\n    class UnixDatagramServer(UDPServer):\n        server_address: _AfUnixAddress  # type: ignore[assignment]\n        def __init__(\n            self,\n            server_address: _AfUnixAddress,\n            RequestHandlerClass: Callable[[Any, _RetAddress, Self], BaseRequestHandler],\n            bind_and_activate: bool = True,\n        ) -> None: ...\n\nif sys.platform != \"win32\":\n    class ForkingMixIn:\n        timeout: float | None  # undocumented\n        active_children: set[int] | None  # undocumented\n        max_children: int  # undocumented\n        block_on_close: bool\n        def collect_children(self, *, blocking: bool = False) -> None: ...  # undocumented\n        def handle_timeout(self) -> None: ...  # undocumented\n        def service_actions(self) -> None: ...  # undocumented\n        def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: ...\n        def server_close(self) -> None: ...\n\nclass ThreadingMixIn:\n    daemon_threads: bool\n    block_on_close: bool\n    def process_request_thread(self, request: _RequestType, client_address: _RetAddress) -> None: ...  # undocumented\n    def process_request(self, request: _RequestType, client_address: _RetAddress) -> None: ...\n    def server_close(self) -> None: ...\n\nif sys.platform != \"win32\":\n    class ForkingTCPServer(ForkingMixIn, TCPServer): ...\n    class ForkingUDPServer(ForkingMixIn, UDPServer): ...\n    if sys.version_info >= (3, 12):\n        class ForkingUnixStreamServer(ForkingMixIn, UnixStreamServer): ...\n        class ForkingUnixDatagramServer(ForkingMixIn, UnixDatagramServer): ...\n\nclass ThreadingTCPServer(ThreadingMixIn, TCPServer): ...\nclass ThreadingUDPServer(ThreadingMixIn, UDPServer): ...\n\nif sys.platform != \"win32\":\n    class ThreadingUnixStreamServer(ThreadingMixIn, UnixStreamServer): ...\n    class ThreadingUnixDatagramServer(ThreadingMixIn, UnixDatagramServer): ...\n\nclass BaseRequestHandler:\n    # `request` is technically of type _RequestType,\n    # but there are some concerns that having a union here would cause\n    # too much inconvenience to people using it (see\n    # https://github.com/python/typeshed/pull/384#issuecomment-234649696)\n    #\n    # Note also that _RetAddress is also just an alias for `Any`\n    request: Any\n    client_address: _RetAddress\n    server: BaseServer\n    def __init__(self, request: _RequestType, client_address: _RetAddress, server: BaseServer) -> None: ...\n    def setup(self) -> None: ...\n    def handle(self) -> None: ...\n    def finish(self) -> None: ...\n\nclass StreamRequestHandler(BaseRequestHandler):\n    rbufsize: ClassVar[int]  # undocumented\n    wbufsize: ClassVar[int]  # undocumented\n    timeout: ClassVar[float | None]  # undocumented\n    disable_nagle_algorithm: ClassVar[bool]  # undocumented\n    connection: Any  # undocumented\n    rfile: BufferedIOBase\n    wfile: BufferedIOBase\n\nclass DatagramRequestHandler(BaseRequestHandler):\n    packet: bytes  # undocumented\n    socket: _socket  # undocumented\n    rfile: BufferedIOBase\n    wfile: BufferedIOBase\n"
  },
  {
    "path": "mypy/typeshed/stdlib/spwd.pyi",
    "content": "import sys\nfrom _typeshed import structseq\nfrom typing import Any, Final, final\n\nif sys.platform != \"win32\":\n    @final\n    class struct_spwd(structseq[Any], tuple[str, str, int, int, int, int, int, int, int]):\n        if sys.version_info >= (3, 10):\n            __match_args__: Final = (\n                \"sp_namp\",\n                \"sp_pwdp\",\n                \"sp_lstchg\",\n                \"sp_min\",\n                \"sp_max\",\n                \"sp_warn\",\n                \"sp_inact\",\n                \"sp_expire\",\n                \"sp_flag\",\n            )\n\n        @property\n        def sp_namp(self) -> str: ...\n        @property\n        def sp_pwdp(self) -> str: ...\n        @property\n        def sp_lstchg(self) -> int: ...\n        @property\n        def sp_min(self) -> int: ...\n        @property\n        def sp_max(self) -> int: ...\n        @property\n        def sp_warn(self) -> int: ...\n        @property\n        def sp_inact(self) -> int: ...\n        @property\n        def sp_expire(self) -> int: ...\n        @property\n        def sp_flag(self) -> int: ...\n        # Deprecated aliases below.\n        @property\n        def sp_nam(self) -> str: ...\n        @property\n        def sp_pwd(self) -> str: ...\n\n    def getspall() -> list[struct_spwd]: ...\n    def getspnam(arg: str, /) -> struct_spwd: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sqlite3/__init__.pyi",
    "content": "import sys\nfrom _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath, SupportsLenAndGetItem, Unused\nfrom collections.abc import Callable, Generator, Iterable, Iterator, Mapping, Sequence\nfrom sqlite3.dbapi2 import (\n    PARSE_COLNAMES as PARSE_COLNAMES,\n    PARSE_DECLTYPES as PARSE_DECLTYPES,\n    SQLITE_ALTER_TABLE as SQLITE_ALTER_TABLE,\n    SQLITE_ANALYZE as SQLITE_ANALYZE,\n    SQLITE_ATTACH as SQLITE_ATTACH,\n    SQLITE_CREATE_INDEX as SQLITE_CREATE_INDEX,\n    SQLITE_CREATE_TABLE as SQLITE_CREATE_TABLE,\n    SQLITE_CREATE_TEMP_INDEX as SQLITE_CREATE_TEMP_INDEX,\n    SQLITE_CREATE_TEMP_TABLE as SQLITE_CREATE_TEMP_TABLE,\n    SQLITE_CREATE_TEMP_TRIGGER as SQLITE_CREATE_TEMP_TRIGGER,\n    SQLITE_CREATE_TEMP_VIEW as SQLITE_CREATE_TEMP_VIEW,\n    SQLITE_CREATE_TRIGGER as SQLITE_CREATE_TRIGGER,\n    SQLITE_CREATE_VIEW as SQLITE_CREATE_VIEW,\n    SQLITE_CREATE_VTABLE as SQLITE_CREATE_VTABLE,\n    SQLITE_DELETE as SQLITE_DELETE,\n    SQLITE_DENY as SQLITE_DENY,\n    SQLITE_DETACH as SQLITE_DETACH,\n    SQLITE_DONE as SQLITE_DONE,\n    SQLITE_DROP_INDEX as SQLITE_DROP_INDEX,\n    SQLITE_DROP_TABLE as SQLITE_DROP_TABLE,\n    SQLITE_DROP_TEMP_INDEX as SQLITE_DROP_TEMP_INDEX,\n    SQLITE_DROP_TEMP_TABLE as SQLITE_DROP_TEMP_TABLE,\n    SQLITE_DROP_TEMP_TRIGGER as SQLITE_DROP_TEMP_TRIGGER,\n    SQLITE_DROP_TEMP_VIEW as SQLITE_DROP_TEMP_VIEW,\n    SQLITE_DROP_TRIGGER as SQLITE_DROP_TRIGGER,\n    SQLITE_DROP_VIEW as SQLITE_DROP_VIEW,\n    SQLITE_DROP_VTABLE as SQLITE_DROP_VTABLE,\n    SQLITE_FUNCTION as SQLITE_FUNCTION,\n    SQLITE_IGNORE as SQLITE_IGNORE,\n    SQLITE_INSERT as SQLITE_INSERT,\n    SQLITE_OK as SQLITE_OK,\n    SQLITE_PRAGMA as SQLITE_PRAGMA,\n    SQLITE_READ as SQLITE_READ,\n    SQLITE_RECURSIVE as SQLITE_RECURSIVE,\n    SQLITE_REINDEX as SQLITE_REINDEX,\n    SQLITE_SAVEPOINT as SQLITE_SAVEPOINT,\n    SQLITE_SELECT as SQLITE_SELECT,\n    SQLITE_TRANSACTION as SQLITE_TRANSACTION,\n    SQLITE_UPDATE as SQLITE_UPDATE,\n    Binary as Binary,\n    Date as Date,\n    DateFromTicks as DateFromTicks,\n    Time as Time,\n    TimeFromTicks as TimeFromTicks,\n    TimestampFromTicks as TimestampFromTicks,\n    adapt as adapt,\n    adapters as adapters,\n    apilevel as apilevel,\n    complete_statement as complete_statement,\n    connect as connect,\n    converters as converters,\n    enable_callback_tracebacks as enable_callback_tracebacks,\n    paramstyle as paramstyle,\n    register_adapter as register_adapter,\n    register_converter as register_converter,\n    sqlite_version as sqlite_version,\n    sqlite_version_info as sqlite_version_info,\n    threadsafety as threadsafety,\n)\nfrom types import TracebackType\nfrom typing import Any, Literal, Protocol, SupportsIndex, TypeVar, final, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, disjoint_base\n\nif sys.version_info < (3, 14):\n    from sqlite3.dbapi2 import version_info as version_info\n\nif sys.version_info >= (3, 12):\n    from sqlite3.dbapi2 import (\n        LEGACY_TRANSACTION_CONTROL as LEGACY_TRANSACTION_CONTROL,\n        SQLITE_DBCONFIG_DEFENSIVE as SQLITE_DBCONFIG_DEFENSIVE,\n        SQLITE_DBCONFIG_DQS_DDL as SQLITE_DBCONFIG_DQS_DDL,\n        SQLITE_DBCONFIG_DQS_DML as SQLITE_DBCONFIG_DQS_DML,\n        SQLITE_DBCONFIG_ENABLE_FKEY as SQLITE_DBCONFIG_ENABLE_FKEY,\n        SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER as SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,\n        SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION as SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION,\n        SQLITE_DBCONFIG_ENABLE_QPSG as SQLITE_DBCONFIG_ENABLE_QPSG,\n        SQLITE_DBCONFIG_ENABLE_TRIGGER as SQLITE_DBCONFIG_ENABLE_TRIGGER,\n        SQLITE_DBCONFIG_ENABLE_VIEW as SQLITE_DBCONFIG_ENABLE_VIEW,\n        SQLITE_DBCONFIG_LEGACY_ALTER_TABLE as SQLITE_DBCONFIG_LEGACY_ALTER_TABLE,\n        SQLITE_DBCONFIG_LEGACY_FILE_FORMAT as SQLITE_DBCONFIG_LEGACY_FILE_FORMAT,\n        SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE as SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,\n        SQLITE_DBCONFIG_RESET_DATABASE as SQLITE_DBCONFIG_RESET_DATABASE,\n        SQLITE_DBCONFIG_TRIGGER_EQP as SQLITE_DBCONFIG_TRIGGER_EQP,\n        SQLITE_DBCONFIG_TRUSTED_SCHEMA as SQLITE_DBCONFIG_TRUSTED_SCHEMA,\n        SQLITE_DBCONFIG_WRITABLE_SCHEMA as SQLITE_DBCONFIG_WRITABLE_SCHEMA,\n    )\n\nif sys.version_info >= (3, 11):\n    from sqlite3.dbapi2 import (\n        SQLITE_ABORT as SQLITE_ABORT,\n        SQLITE_ABORT_ROLLBACK as SQLITE_ABORT_ROLLBACK,\n        SQLITE_AUTH as SQLITE_AUTH,\n        SQLITE_AUTH_USER as SQLITE_AUTH_USER,\n        SQLITE_BUSY as SQLITE_BUSY,\n        SQLITE_BUSY_RECOVERY as SQLITE_BUSY_RECOVERY,\n        SQLITE_BUSY_SNAPSHOT as SQLITE_BUSY_SNAPSHOT,\n        SQLITE_BUSY_TIMEOUT as SQLITE_BUSY_TIMEOUT,\n        SQLITE_CANTOPEN as SQLITE_CANTOPEN,\n        SQLITE_CANTOPEN_CONVPATH as SQLITE_CANTOPEN_CONVPATH,\n        SQLITE_CANTOPEN_DIRTYWAL as SQLITE_CANTOPEN_DIRTYWAL,\n        SQLITE_CANTOPEN_FULLPATH as SQLITE_CANTOPEN_FULLPATH,\n        SQLITE_CANTOPEN_ISDIR as SQLITE_CANTOPEN_ISDIR,\n        SQLITE_CANTOPEN_NOTEMPDIR as SQLITE_CANTOPEN_NOTEMPDIR,\n        SQLITE_CANTOPEN_SYMLINK as SQLITE_CANTOPEN_SYMLINK,\n        SQLITE_CONSTRAINT as SQLITE_CONSTRAINT,\n        SQLITE_CONSTRAINT_CHECK as SQLITE_CONSTRAINT_CHECK,\n        SQLITE_CONSTRAINT_COMMITHOOK as SQLITE_CONSTRAINT_COMMITHOOK,\n        SQLITE_CONSTRAINT_FOREIGNKEY as SQLITE_CONSTRAINT_FOREIGNKEY,\n        SQLITE_CONSTRAINT_FUNCTION as SQLITE_CONSTRAINT_FUNCTION,\n        SQLITE_CONSTRAINT_NOTNULL as SQLITE_CONSTRAINT_NOTNULL,\n        SQLITE_CONSTRAINT_PINNED as SQLITE_CONSTRAINT_PINNED,\n        SQLITE_CONSTRAINT_PRIMARYKEY as SQLITE_CONSTRAINT_PRIMARYKEY,\n        SQLITE_CONSTRAINT_ROWID as SQLITE_CONSTRAINT_ROWID,\n        SQLITE_CONSTRAINT_TRIGGER as SQLITE_CONSTRAINT_TRIGGER,\n        SQLITE_CONSTRAINT_UNIQUE as SQLITE_CONSTRAINT_UNIQUE,\n        SQLITE_CONSTRAINT_VTAB as SQLITE_CONSTRAINT_VTAB,\n        SQLITE_CORRUPT as SQLITE_CORRUPT,\n        SQLITE_CORRUPT_INDEX as SQLITE_CORRUPT_INDEX,\n        SQLITE_CORRUPT_SEQUENCE as SQLITE_CORRUPT_SEQUENCE,\n        SQLITE_CORRUPT_VTAB as SQLITE_CORRUPT_VTAB,\n        SQLITE_EMPTY as SQLITE_EMPTY,\n        SQLITE_ERROR as SQLITE_ERROR,\n        SQLITE_ERROR_MISSING_COLLSEQ as SQLITE_ERROR_MISSING_COLLSEQ,\n        SQLITE_ERROR_RETRY as SQLITE_ERROR_RETRY,\n        SQLITE_ERROR_SNAPSHOT as SQLITE_ERROR_SNAPSHOT,\n        SQLITE_FORMAT as SQLITE_FORMAT,\n        SQLITE_FULL as SQLITE_FULL,\n        SQLITE_INTERNAL as SQLITE_INTERNAL,\n        SQLITE_INTERRUPT as SQLITE_INTERRUPT,\n        SQLITE_IOERR as SQLITE_IOERR,\n        SQLITE_IOERR_ACCESS as SQLITE_IOERR_ACCESS,\n        SQLITE_IOERR_AUTH as SQLITE_IOERR_AUTH,\n        SQLITE_IOERR_BEGIN_ATOMIC as SQLITE_IOERR_BEGIN_ATOMIC,\n        SQLITE_IOERR_BLOCKED as SQLITE_IOERR_BLOCKED,\n        SQLITE_IOERR_CHECKRESERVEDLOCK as SQLITE_IOERR_CHECKRESERVEDLOCK,\n        SQLITE_IOERR_CLOSE as SQLITE_IOERR_CLOSE,\n        SQLITE_IOERR_COMMIT_ATOMIC as SQLITE_IOERR_COMMIT_ATOMIC,\n        SQLITE_IOERR_CONVPATH as SQLITE_IOERR_CONVPATH,\n        SQLITE_IOERR_CORRUPTFS as SQLITE_IOERR_CORRUPTFS,\n        SQLITE_IOERR_DATA as SQLITE_IOERR_DATA,\n        SQLITE_IOERR_DELETE as SQLITE_IOERR_DELETE,\n        SQLITE_IOERR_DELETE_NOENT as SQLITE_IOERR_DELETE_NOENT,\n        SQLITE_IOERR_DIR_CLOSE as SQLITE_IOERR_DIR_CLOSE,\n        SQLITE_IOERR_DIR_FSYNC as SQLITE_IOERR_DIR_FSYNC,\n        SQLITE_IOERR_FSTAT as SQLITE_IOERR_FSTAT,\n        SQLITE_IOERR_FSYNC as SQLITE_IOERR_FSYNC,\n        SQLITE_IOERR_GETTEMPPATH as SQLITE_IOERR_GETTEMPPATH,\n        SQLITE_IOERR_LOCK as SQLITE_IOERR_LOCK,\n        SQLITE_IOERR_MMAP as SQLITE_IOERR_MMAP,\n        SQLITE_IOERR_NOMEM as SQLITE_IOERR_NOMEM,\n        SQLITE_IOERR_RDLOCK as SQLITE_IOERR_RDLOCK,\n        SQLITE_IOERR_READ as SQLITE_IOERR_READ,\n        SQLITE_IOERR_ROLLBACK_ATOMIC as SQLITE_IOERR_ROLLBACK_ATOMIC,\n        SQLITE_IOERR_SEEK as SQLITE_IOERR_SEEK,\n        SQLITE_IOERR_SHMLOCK as SQLITE_IOERR_SHMLOCK,\n        SQLITE_IOERR_SHMMAP as SQLITE_IOERR_SHMMAP,\n        SQLITE_IOERR_SHMOPEN as SQLITE_IOERR_SHMOPEN,\n        SQLITE_IOERR_SHMSIZE as SQLITE_IOERR_SHMSIZE,\n        SQLITE_IOERR_SHORT_READ as SQLITE_IOERR_SHORT_READ,\n        SQLITE_IOERR_TRUNCATE as SQLITE_IOERR_TRUNCATE,\n        SQLITE_IOERR_UNLOCK as SQLITE_IOERR_UNLOCK,\n        SQLITE_IOERR_VNODE as SQLITE_IOERR_VNODE,\n        SQLITE_IOERR_WRITE as SQLITE_IOERR_WRITE,\n        SQLITE_LIMIT_ATTACHED as SQLITE_LIMIT_ATTACHED,\n        SQLITE_LIMIT_COLUMN as SQLITE_LIMIT_COLUMN,\n        SQLITE_LIMIT_COMPOUND_SELECT as SQLITE_LIMIT_COMPOUND_SELECT,\n        SQLITE_LIMIT_EXPR_DEPTH as SQLITE_LIMIT_EXPR_DEPTH,\n        SQLITE_LIMIT_FUNCTION_ARG as SQLITE_LIMIT_FUNCTION_ARG,\n        SQLITE_LIMIT_LENGTH as SQLITE_LIMIT_LENGTH,\n        SQLITE_LIMIT_LIKE_PATTERN_LENGTH as SQLITE_LIMIT_LIKE_PATTERN_LENGTH,\n        SQLITE_LIMIT_SQL_LENGTH as SQLITE_LIMIT_SQL_LENGTH,\n        SQLITE_LIMIT_TRIGGER_DEPTH as SQLITE_LIMIT_TRIGGER_DEPTH,\n        SQLITE_LIMIT_VARIABLE_NUMBER as SQLITE_LIMIT_VARIABLE_NUMBER,\n        SQLITE_LIMIT_VDBE_OP as SQLITE_LIMIT_VDBE_OP,\n        SQLITE_LIMIT_WORKER_THREADS as SQLITE_LIMIT_WORKER_THREADS,\n        SQLITE_LOCKED as SQLITE_LOCKED,\n        SQLITE_LOCKED_SHAREDCACHE as SQLITE_LOCKED_SHAREDCACHE,\n        SQLITE_LOCKED_VTAB as SQLITE_LOCKED_VTAB,\n        SQLITE_MISMATCH as SQLITE_MISMATCH,\n        SQLITE_MISUSE as SQLITE_MISUSE,\n        SQLITE_NOLFS as SQLITE_NOLFS,\n        SQLITE_NOMEM as SQLITE_NOMEM,\n        SQLITE_NOTADB as SQLITE_NOTADB,\n        SQLITE_NOTFOUND as SQLITE_NOTFOUND,\n        SQLITE_NOTICE as SQLITE_NOTICE,\n        SQLITE_NOTICE_RECOVER_ROLLBACK as SQLITE_NOTICE_RECOVER_ROLLBACK,\n        SQLITE_NOTICE_RECOVER_WAL as SQLITE_NOTICE_RECOVER_WAL,\n        SQLITE_OK_LOAD_PERMANENTLY as SQLITE_OK_LOAD_PERMANENTLY,\n        SQLITE_OK_SYMLINK as SQLITE_OK_SYMLINK,\n        SQLITE_PERM as SQLITE_PERM,\n        SQLITE_PROTOCOL as SQLITE_PROTOCOL,\n        SQLITE_RANGE as SQLITE_RANGE,\n        SQLITE_READONLY as SQLITE_READONLY,\n        SQLITE_READONLY_CANTINIT as SQLITE_READONLY_CANTINIT,\n        SQLITE_READONLY_CANTLOCK as SQLITE_READONLY_CANTLOCK,\n        SQLITE_READONLY_DBMOVED as SQLITE_READONLY_DBMOVED,\n        SQLITE_READONLY_DIRECTORY as SQLITE_READONLY_DIRECTORY,\n        SQLITE_READONLY_RECOVERY as SQLITE_READONLY_RECOVERY,\n        SQLITE_READONLY_ROLLBACK as SQLITE_READONLY_ROLLBACK,\n        SQLITE_ROW as SQLITE_ROW,\n        SQLITE_SCHEMA as SQLITE_SCHEMA,\n        SQLITE_TOOBIG as SQLITE_TOOBIG,\n        SQLITE_WARNING as SQLITE_WARNING,\n        SQLITE_WARNING_AUTOINDEX as SQLITE_WARNING_AUTOINDEX,\n    )\n\nif sys.version_info < (3, 12):\n    from sqlite3.dbapi2 import enable_shared_cache as enable_shared_cache, version as version\n\nif sys.version_info < (3, 10):\n    from sqlite3.dbapi2 import OptimizedUnicode as OptimizedUnicode\n\n_CursorT = TypeVar(\"_CursorT\", bound=Cursor)\n_SqliteData: TypeAlias = str | ReadableBuffer | int | float | None\n# Data that is passed through adapters can be of any type accepted by an adapter.\n_AdaptedInputData: TypeAlias = _SqliteData | Any\n# The Mapping must really be a dict, but making it invariant is too annoying.\n_Parameters: TypeAlias = SupportsLenAndGetItem[_AdaptedInputData] | Mapping[str, _AdaptedInputData]\n# Controls the legacy transaction handling mode of sqlite3.\n_IsolationLevel: TypeAlias = Literal[\"DEFERRED\", \"EXCLUSIVE\", \"IMMEDIATE\"] | None\n_RowFactoryOptions: TypeAlias = type[Row] | Callable[[Cursor, tuple[Any, ...]], object] | None\n\n@type_check_only\nclass _AnyParamWindowAggregateClass(Protocol):\n    def step(self, *args: Any) -> object: ...\n    def inverse(self, *args: Any) -> object: ...\n    def value(self) -> _SqliteData: ...\n    def finalize(self) -> _SqliteData: ...\n\n@type_check_only\nclass _WindowAggregateClass(Protocol):\n    step: Callable[..., object]\n    inverse: Callable[..., object]\n    def value(self) -> _SqliteData: ...\n    def finalize(self) -> _SqliteData: ...\n\n@type_check_only\nclass _AggregateProtocol(Protocol):\n    def step(self, value: int, /) -> object: ...\n    def finalize(self) -> int: ...\n\n@type_check_only\nclass _SingleParamWindowAggregateClass(Protocol):\n    def step(self, param: Any, /) -> object: ...\n    def inverse(self, param: Any, /) -> object: ...\n    def value(self) -> _SqliteData: ...\n    def finalize(self) -> _SqliteData: ...\n\n# These classes are implemented in the C module _sqlite3. At runtime, they're imported\n# from there into sqlite3.dbapi2 and from that module to here. However, they\n# consider themselves to live in the sqlite3.* namespace, so we'll define them here.\n\nclass Error(Exception):\n    if sys.version_info >= (3, 11):\n        sqlite_errorcode: int\n        sqlite_errorname: str\n\nclass DatabaseError(Error): ...\nclass DataError(DatabaseError): ...\nclass IntegrityError(DatabaseError): ...\nclass InterfaceError(Error): ...\nclass InternalError(DatabaseError): ...\nclass NotSupportedError(DatabaseError): ...\nclass OperationalError(DatabaseError): ...\nclass ProgrammingError(DatabaseError): ...\nclass Warning(Exception): ...\n\n@disjoint_base\nclass Connection:\n    @property\n    def DataError(self) -> type[DataError]: ...\n    @property\n    def DatabaseError(self) -> type[DatabaseError]: ...\n    @property\n    def Error(self) -> type[Error]: ...\n    @property\n    def IntegrityError(self) -> type[IntegrityError]: ...\n    @property\n    def InterfaceError(self) -> type[InterfaceError]: ...\n    @property\n    def InternalError(self) -> type[InternalError]: ...\n    @property\n    def NotSupportedError(self) -> type[NotSupportedError]: ...\n    @property\n    def OperationalError(self) -> type[OperationalError]: ...\n    @property\n    def ProgrammingError(self) -> type[ProgrammingError]: ...\n    @property\n    def Warning(self) -> type[Warning]: ...\n    @property\n    def in_transaction(self) -> bool: ...\n    isolation_level: _IsolationLevel\n    @property\n    def total_changes(self) -> int: ...\n    if sys.version_info >= (3, 12):\n        @property\n        def autocommit(self) -> int: ...\n        @autocommit.setter\n        def autocommit(self, val: int) -> None: ...\n    row_factory: _RowFactoryOptions\n    text_factory: Any\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self,\n            database: StrOrBytesPath,\n            timeout: float = 5.0,\n            detect_types: int = 0,\n            isolation_level: _IsolationLevel = \"DEFERRED\",\n            check_same_thread: bool = True,\n            factory: type[Connection] | None = ...,\n            cached_statements: int = 128,\n            uri: bool = False,\n            autocommit: bool = ...,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            database: StrOrBytesPath,\n            timeout: float = 5.0,\n            detect_types: int = 0,\n            isolation_level: _IsolationLevel = \"DEFERRED\",\n            check_same_thread: bool = True,\n            factory: type[Connection] | None = ...,\n            cached_statements: int = 128,\n            uri: bool = False,\n        ) -> None: ...\n\n    def close(self) -> None: ...\n    if sys.version_info >= (3, 11):\n        def blobopen(self, table: str, column: str, row: int, /, *, readonly: bool = False, name: str = \"main\") -> Blob: ...\n\n    def commit(self) -> None: ...\n    def create_aggregate(self, name: str, n_arg: int, aggregate_class: Callable[[], _AggregateProtocol]) -> None: ...\n    if sys.version_info >= (3, 11):\n        # num_params determines how many params will be passed to the aggregate class. We provide an overload\n        # for the case where num_params = 1, which is expected to be the common case.\n        @overload\n        def create_window_function(\n            self, name: str, num_params: Literal[1], aggregate_class: Callable[[], _SingleParamWindowAggregateClass] | None, /\n        ) -> None: ...\n        # And for num_params = -1, which means the aggregate must accept any number of parameters.\n        @overload\n        def create_window_function(\n            self, name: str, num_params: Literal[-1], aggregate_class: Callable[[], _AnyParamWindowAggregateClass] | None, /\n        ) -> None: ...\n        @overload\n        def create_window_function(\n            self, name: str, num_params: int, aggregate_class: Callable[[], _WindowAggregateClass] | None, /\n        ) -> None: ...\n\n    def create_collation(self, name: str, callback: Callable[[str, str], SupportsIndex] | None, /) -> None: ...\n    def create_function(\n        self, name: str, narg: int, func: Callable[..., _SqliteData] | None, *, deterministic: bool = False\n    ) -> None: ...\n    @overload\n    def cursor(self, factory: None = None) -> Cursor: ...\n    @overload\n    def cursor(self, factory: Callable[[Connection], _CursorT]) -> _CursorT: ...\n    def execute(self, sql: str, parameters: _Parameters = ..., /) -> Cursor: ...\n    def executemany(self, sql: str, parameters: Iterable[_Parameters], /) -> Cursor: ...\n    def executescript(self, sql_script: str, /) -> Cursor: ...\n    def interrupt(self) -> None: ...\n    if sys.version_info >= (3, 13):\n        def iterdump(self, *, filter: str | None = None) -> Generator[str, None, None]: ...\n    else:\n        def iterdump(self) -> Generator[str, None, None]: ...\n\n    def rollback(self) -> None: ...\n    def set_authorizer(\n        self, authorizer_callback: Callable[[int, str | None, str | None, str | None, str | None], int] | None\n    ) -> None: ...\n    def set_progress_handler(self, progress_handler: Callable[[], int | None] | None, n: int) -> None: ...\n    def set_trace_callback(self, trace_callback: Callable[[str], object] | None) -> None: ...\n    # enable_load_extension and load_extension is not available on python distributions compiled\n    # without sqlite3 loadable extension support. see footnotes https://docs.python.org/3/library/sqlite3.html#f1\n    def enable_load_extension(self, enable: bool, /) -> None: ...\n    if sys.version_info >= (3, 12):\n        def load_extension(self, name: str, /, *, entrypoint: str | None = None) -> None: ...\n    else:\n        def load_extension(self, name: str, /) -> None: ...\n\n    def backup(\n        self,\n        target: Connection,\n        *,\n        pages: int = -1,\n        progress: Callable[[int, int, int], object] | None = None,\n        name: str = \"main\",\n        sleep: float = 0.25,\n    ) -> None: ...\n    if sys.version_info >= (3, 11):\n        def setlimit(self, category: int, limit: int, /) -> int: ...\n        def getlimit(self, category: int, /) -> int: ...\n        def serialize(self, *, name: str = \"main\") -> bytes: ...\n        def deserialize(self, data: ReadableBuffer, /, *, name: str = \"main\") -> None: ...\n    if sys.version_info >= (3, 12):\n        def getconfig(self, op: int, /) -> bool: ...\n        def setconfig(self, op: int, enable: bool = True, /) -> bool: ...\n\n    def __call__(self, sql: str, /) -> _Statement: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, /\n    ) -> Literal[False]: ...\n\n@disjoint_base\nclass Cursor(Iterator[Any]):\n    arraysize: int\n    @property\n    def connection(self) -> Connection: ...\n    # May be None, but using `| MaybeNone` (`| Any`) instead to avoid slightly annoying false positives.\n    @property\n    def description(self) -> tuple[tuple[str, None, None, None, None, None, None], ...] | MaybeNone: ...\n    @property\n    def lastrowid(self) -> int | None: ...\n    row_factory: _RowFactoryOptions\n    @property\n    def rowcount(self) -> int: ...\n    def __init__(self, cursor: Connection, /) -> None: ...\n    def close(self) -> None: ...\n    def execute(self, sql: str, parameters: _Parameters = (), /) -> Self: ...\n    def executemany(self, sql: str, seq_of_parameters: Iterable[_Parameters], /) -> Self: ...\n    def executescript(self, sql_script: str, /) -> Cursor: ...\n    def fetchall(self) -> list[Any]: ...\n    def fetchmany(self, size: int | None = 1) -> list[Any]: ...\n    # Returns either a row (as created by the row_factory) or None, but\n    # putting None in the return annotation causes annoying false positives.\n    def fetchone(self) -> Any: ...\n    def setinputsizes(self, sizes: Unused, /) -> None: ...  # does nothing\n    def setoutputsize(self, size: Unused, column: Unused = None, /) -> None: ...  # does nothing\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> Any: ...\n\n@final\nclass PrepareProtocol:\n    def __init__(self, *args: object, **kwargs: object) -> None: ...\n\n@disjoint_base\nclass Row(Sequence[Any]):\n    def __new__(cls, cursor: Cursor, data: tuple[Any, ...], /) -> Self: ...\n    def keys(self) -> list[str]: ...\n    @overload  # Note: really needs int instead of SupportsIndex\n    def __getitem__(self, key: int | str, /) -> Any: ...\n    @overload  # Note: SupportsIndex does work within slices.\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> tuple[Any, ...]: ...\n    def __hash__(self) -> int: ...\n    def __iter__(self) -> Iterator[Any]: ...\n    def __len__(self) -> int: ...\n    # These return NotImplemented for anything that is not a Row.\n    def __eq__(self, value: object, /) -> bool: ...\n    def __ge__(self, value: object, /) -> bool: ...\n    def __gt__(self, value: object, /) -> bool: ...\n    def __le__(self, value: object, /) -> bool: ...\n    def __lt__(self, value: object, /) -> bool: ...\n    def __ne__(self, value: object, /) -> bool: ...\n\n# This class is not exposed. It calls itself sqlite3.Statement.\n@final\n@type_check_only\nclass _Statement: ...\n\nif sys.version_info >= (3, 11):\n    @final\n    class Blob:\n        def close(self) -> None: ...\n        def read(self, length: int = -1, /) -> bytes: ...\n        def write(self, data: ReadableBuffer, /) -> None: ...\n        def tell(self) -> int: ...\n        # whence must be one of os.SEEK_SET, os.SEEK_CUR, os.SEEK_END\n        def seek(self, offset: int, origin: int = 0, /) -> None: ...\n        def __len__(self) -> int: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(self, type: object, val: object, tb: object, /) -> Literal[False]: ...\n        def __getitem__(self, key: SupportsIndex | slice, /) -> int: ...\n        def __setitem__(self, key: SupportsIndex | slice, value: int, /) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sqlite3/dbapi2.pyi",
    "content": "import sys\nfrom _sqlite3 import (\n    PARSE_COLNAMES as PARSE_COLNAMES,\n    PARSE_DECLTYPES as PARSE_DECLTYPES,\n    SQLITE_ALTER_TABLE as SQLITE_ALTER_TABLE,\n    SQLITE_ANALYZE as SQLITE_ANALYZE,\n    SQLITE_ATTACH as SQLITE_ATTACH,\n    SQLITE_CREATE_INDEX as SQLITE_CREATE_INDEX,\n    SQLITE_CREATE_TABLE as SQLITE_CREATE_TABLE,\n    SQLITE_CREATE_TEMP_INDEX as SQLITE_CREATE_TEMP_INDEX,\n    SQLITE_CREATE_TEMP_TABLE as SQLITE_CREATE_TEMP_TABLE,\n    SQLITE_CREATE_TEMP_TRIGGER as SQLITE_CREATE_TEMP_TRIGGER,\n    SQLITE_CREATE_TEMP_VIEW as SQLITE_CREATE_TEMP_VIEW,\n    SQLITE_CREATE_TRIGGER as SQLITE_CREATE_TRIGGER,\n    SQLITE_CREATE_VIEW as SQLITE_CREATE_VIEW,\n    SQLITE_CREATE_VTABLE as SQLITE_CREATE_VTABLE,\n    SQLITE_DELETE as SQLITE_DELETE,\n    SQLITE_DENY as SQLITE_DENY,\n    SQLITE_DETACH as SQLITE_DETACH,\n    SQLITE_DONE as SQLITE_DONE,\n    SQLITE_DROP_INDEX as SQLITE_DROP_INDEX,\n    SQLITE_DROP_TABLE as SQLITE_DROP_TABLE,\n    SQLITE_DROP_TEMP_INDEX as SQLITE_DROP_TEMP_INDEX,\n    SQLITE_DROP_TEMP_TABLE as SQLITE_DROP_TEMP_TABLE,\n    SQLITE_DROP_TEMP_TRIGGER as SQLITE_DROP_TEMP_TRIGGER,\n    SQLITE_DROP_TEMP_VIEW as SQLITE_DROP_TEMP_VIEW,\n    SQLITE_DROP_TRIGGER as SQLITE_DROP_TRIGGER,\n    SQLITE_DROP_VIEW as SQLITE_DROP_VIEW,\n    SQLITE_DROP_VTABLE as SQLITE_DROP_VTABLE,\n    SQLITE_FUNCTION as SQLITE_FUNCTION,\n    SQLITE_IGNORE as SQLITE_IGNORE,\n    SQLITE_INSERT as SQLITE_INSERT,\n    SQLITE_OK as SQLITE_OK,\n    SQLITE_PRAGMA as SQLITE_PRAGMA,\n    SQLITE_READ as SQLITE_READ,\n    SQLITE_RECURSIVE as SQLITE_RECURSIVE,\n    SQLITE_REINDEX as SQLITE_REINDEX,\n    SQLITE_SAVEPOINT as SQLITE_SAVEPOINT,\n    SQLITE_SELECT as SQLITE_SELECT,\n    SQLITE_TRANSACTION as SQLITE_TRANSACTION,\n    SQLITE_UPDATE as SQLITE_UPDATE,\n    adapt as adapt,\n    adapters as adapters,\n    complete_statement as complete_statement,\n    connect as connect,\n    converters as converters,\n    enable_callback_tracebacks as enable_callback_tracebacks,\n    register_adapter as register_adapter,\n    register_converter as register_converter,\n    sqlite_version as sqlite_version,\n)\nfrom datetime import date, datetime, time\nfrom sqlite3 import (\n    Connection as Connection,\n    Cursor as Cursor,\n    DatabaseError as DatabaseError,\n    DataError as DataError,\n    Error as Error,\n    IntegrityError as IntegrityError,\n    InterfaceError as InterfaceError,\n    InternalError as InternalError,\n    NotSupportedError as NotSupportedError,\n    OperationalError as OperationalError,\n    PrepareProtocol as PrepareProtocol,\n    ProgrammingError as ProgrammingError,\n    Row as Row,\n    Warning as Warning,\n)\nfrom typing import Final, Literal\nfrom typing_extensions import deprecated\n\nif sys.version_info >= (3, 12):\n    from _sqlite3 import (\n        LEGACY_TRANSACTION_CONTROL as LEGACY_TRANSACTION_CONTROL,\n        SQLITE_DBCONFIG_DEFENSIVE as SQLITE_DBCONFIG_DEFENSIVE,\n        SQLITE_DBCONFIG_DQS_DDL as SQLITE_DBCONFIG_DQS_DDL,\n        SQLITE_DBCONFIG_DQS_DML as SQLITE_DBCONFIG_DQS_DML,\n        SQLITE_DBCONFIG_ENABLE_FKEY as SQLITE_DBCONFIG_ENABLE_FKEY,\n        SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER as SQLITE_DBCONFIG_ENABLE_FTS3_TOKENIZER,\n        SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION as SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION,\n        SQLITE_DBCONFIG_ENABLE_QPSG as SQLITE_DBCONFIG_ENABLE_QPSG,\n        SQLITE_DBCONFIG_ENABLE_TRIGGER as SQLITE_DBCONFIG_ENABLE_TRIGGER,\n        SQLITE_DBCONFIG_ENABLE_VIEW as SQLITE_DBCONFIG_ENABLE_VIEW,\n        SQLITE_DBCONFIG_LEGACY_ALTER_TABLE as SQLITE_DBCONFIG_LEGACY_ALTER_TABLE,\n        SQLITE_DBCONFIG_LEGACY_FILE_FORMAT as SQLITE_DBCONFIG_LEGACY_FILE_FORMAT,\n        SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE as SQLITE_DBCONFIG_NO_CKPT_ON_CLOSE,\n        SQLITE_DBCONFIG_RESET_DATABASE as SQLITE_DBCONFIG_RESET_DATABASE,\n        SQLITE_DBCONFIG_TRIGGER_EQP as SQLITE_DBCONFIG_TRIGGER_EQP,\n        SQLITE_DBCONFIG_TRUSTED_SCHEMA as SQLITE_DBCONFIG_TRUSTED_SCHEMA,\n        SQLITE_DBCONFIG_WRITABLE_SCHEMA as SQLITE_DBCONFIG_WRITABLE_SCHEMA,\n    )\n\nif sys.version_info >= (3, 11):\n    from _sqlite3 import (\n        SQLITE_ABORT as SQLITE_ABORT,\n        SQLITE_ABORT_ROLLBACK as SQLITE_ABORT_ROLLBACK,\n        SQLITE_AUTH as SQLITE_AUTH,\n        SQLITE_AUTH_USER as SQLITE_AUTH_USER,\n        SQLITE_BUSY as SQLITE_BUSY,\n        SQLITE_BUSY_RECOVERY as SQLITE_BUSY_RECOVERY,\n        SQLITE_BUSY_SNAPSHOT as SQLITE_BUSY_SNAPSHOT,\n        SQLITE_BUSY_TIMEOUT as SQLITE_BUSY_TIMEOUT,\n        SQLITE_CANTOPEN as SQLITE_CANTOPEN,\n        SQLITE_CANTOPEN_CONVPATH as SQLITE_CANTOPEN_CONVPATH,\n        SQLITE_CANTOPEN_DIRTYWAL as SQLITE_CANTOPEN_DIRTYWAL,\n        SQLITE_CANTOPEN_FULLPATH as SQLITE_CANTOPEN_FULLPATH,\n        SQLITE_CANTOPEN_ISDIR as SQLITE_CANTOPEN_ISDIR,\n        SQLITE_CANTOPEN_NOTEMPDIR as SQLITE_CANTOPEN_NOTEMPDIR,\n        SQLITE_CANTOPEN_SYMLINK as SQLITE_CANTOPEN_SYMLINK,\n        SQLITE_CONSTRAINT as SQLITE_CONSTRAINT,\n        SQLITE_CONSTRAINT_CHECK as SQLITE_CONSTRAINT_CHECK,\n        SQLITE_CONSTRAINT_COMMITHOOK as SQLITE_CONSTRAINT_COMMITHOOK,\n        SQLITE_CONSTRAINT_FOREIGNKEY as SQLITE_CONSTRAINT_FOREIGNKEY,\n        SQLITE_CONSTRAINT_FUNCTION as SQLITE_CONSTRAINT_FUNCTION,\n        SQLITE_CONSTRAINT_NOTNULL as SQLITE_CONSTRAINT_NOTNULL,\n        SQLITE_CONSTRAINT_PINNED as SQLITE_CONSTRAINT_PINNED,\n        SQLITE_CONSTRAINT_PRIMARYKEY as SQLITE_CONSTRAINT_PRIMARYKEY,\n        SQLITE_CONSTRAINT_ROWID as SQLITE_CONSTRAINT_ROWID,\n        SQLITE_CONSTRAINT_TRIGGER as SQLITE_CONSTRAINT_TRIGGER,\n        SQLITE_CONSTRAINT_UNIQUE as SQLITE_CONSTRAINT_UNIQUE,\n        SQLITE_CONSTRAINT_VTAB as SQLITE_CONSTRAINT_VTAB,\n        SQLITE_CORRUPT as SQLITE_CORRUPT,\n        SQLITE_CORRUPT_INDEX as SQLITE_CORRUPT_INDEX,\n        SQLITE_CORRUPT_SEQUENCE as SQLITE_CORRUPT_SEQUENCE,\n        SQLITE_CORRUPT_VTAB as SQLITE_CORRUPT_VTAB,\n        SQLITE_EMPTY as SQLITE_EMPTY,\n        SQLITE_ERROR as SQLITE_ERROR,\n        SQLITE_ERROR_MISSING_COLLSEQ as SQLITE_ERROR_MISSING_COLLSEQ,\n        SQLITE_ERROR_RETRY as SQLITE_ERROR_RETRY,\n        SQLITE_ERROR_SNAPSHOT as SQLITE_ERROR_SNAPSHOT,\n        SQLITE_FORMAT as SQLITE_FORMAT,\n        SQLITE_FULL as SQLITE_FULL,\n        SQLITE_INTERNAL as SQLITE_INTERNAL,\n        SQLITE_INTERRUPT as SQLITE_INTERRUPT,\n        SQLITE_IOERR as SQLITE_IOERR,\n        SQLITE_IOERR_ACCESS as SQLITE_IOERR_ACCESS,\n        SQLITE_IOERR_AUTH as SQLITE_IOERR_AUTH,\n        SQLITE_IOERR_BEGIN_ATOMIC as SQLITE_IOERR_BEGIN_ATOMIC,\n        SQLITE_IOERR_BLOCKED as SQLITE_IOERR_BLOCKED,\n        SQLITE_IOERR_CHECKRESERVEDLOCK as SQLITE_IOERR_CHECKRESERVEDLOCK,\n        SQLITE_IOERR_CLOSE as SQLITE_IOERR_CLOSE,\n        SQLITE_IOERR_COMMIT_ATOMIC as SQLITE_IOERR_COMMIT_ATOMIC,\n        SQLITE_IOERR_CONVPATH as SQLITE_IOERR_CONVPATH,\n        SQLITE_IOERR_CORRUPTFS as SQLITE_IOERR_CORRUPTFS,\n        SQLITE_IOERR_DATA as SQLITE_IOERR_DATA,\n        SQLITE_IOERR_DELETE as SQLITE_IOERR_DELETE,\n        SQLITE_IOERR_DELETE_NOENT as SQLITE_IOERR_DELETE_NOENT,\n        SQLITE_IOERR_DIR_CLOSE as SQLITE_IOERR_DIR_CLOSE,\n        SQLITE_IOERR_DIR_FSYNC as SQLITE_IOERR_DIR_FSYNC,\n        SQLITE_IOERR_FSTAT as SQLITE_IOERR_FSTAT,\n        SQLITE_IOERR_FSYNC as SQLITE_IOERR_FSYNC,\n        SQLITE_IOERR_GETTEMPPATH as SQLITE_IOERR_GETTEMPPATH,\n        SQLITE_IOERR_LOCK as SQLITE_IOERR_LOCK,\n        SQLITE_IOERR_MMAP as SQLITE_IOERR_MMAP,\n        SQLITE_IOERR_NOMEM as SQLITE_IOERR_NOMEM,\n        SQLITE_IOERR_RDLOCK as SQLITE_IOERR_RDLOCK,\n        SQLITE_IOERR_READ as SQLITE_IOERR_READ,\n        SQLITE_IOERR_ROLLBACK_ATOMIC as SQLITE_IOERR_ROLLBACK_ATOMIC,\n        SQLITE_IOERR_SEEK as SQLITE_IOERR_SEEK,\n        SQLITE_IOERR_SHMLOCK as SQLITE_IOERR_SHMLOCK,\n        SQLITE_IOERR_SHMMAP as SQLITE_IOERR_SHMMAP,\n        SQLITE_IOERR_SHMOPEN as SQLITE_IOERR_SHMOPEN,\n        SQLITE_IOERR_SHMSIZE as SQLITE_IOERR_SHMSIZE,\n        SQLITE_IOERR_SHORT_READ as SQLITE_IOERR_SHORT_READ,\n        SQLITE_IOERR_TRUNCATE as SQLITE_IOERR_TRUNCATE,\n        SQLITE_IOERR_UNLOCK as SQLITE_IOERR_UNLOCK,\n        SQLITE_IOERR_VNODE as SQLITE_IOERR_VNODE,\n        SQLITE_IOERR_WRITE as SQLITE_IOERR_WRITE,\n        SQLITE_LIMIT_ATTACHED as SQLITE_LIMIT_ATTACHED,\n        SQLITE_LIMIT_COLUMN as SQLITE_LIMIT_COLUMN,\n        SQLITE_LIMIT_COMPOUND_SELECT as SQLITE_LIMIT_COMPOUND_SELECT,\n        SQLITE_LIMIT_EXPR_DEPTH as SQLITE_LIMIT_EXPR_DEPTH,\n        SQLITE_LIMIT_FUNCTION_ARG as SQLITE_LIMIT_FUNCTION_ARG,\n        SQLITE_LIMIT_LENGTH as SQLITE_LIMIT_LENGTH,\n        SQLITE_LIMIT_LIKE_PATTERN_LENGTH as SQLITE_LIMIT_LIKE_PATTERN_LENGTH,\n        SQLITE_LIMIT_SQL_LENGTH as SQLITE_LIMIT_SQL_LENGTH,\n        SQLITE_LIMIT_TRIGGER_DEPTH as SQLITE_LIMIT_TRIGGER_DEPTH,\n        SQLITE_LIMIT_VARIABLE_NUMBER as SQLITE_LIMIT_VARIABLE_NUMBER,\n        SQLITE_LIMIT_VDBE_OP as SQLITE_LIMIT_VDBE_OP,\n        SQLITE_LIMIT_WORKER_THREADS as SQLITE_LIMIT_WORKER_THREADS,\n        SQLITE_LOCKED as SQLITE_LOCKED,\n        SQLITE_LOCKED_SHAREDCACHE as SQLITE_LOCKED_SHAREDCACHE,\n        SQLITE_LOCKED_VTAB as SQLITE_LOCKED_VTAB,\n        SQLITE_MISMATCH as SQLITE_MISMATCH,\n        SQLITE_MISUSE as SQLITE_MISUSE,\n        SQLITE_NOLFS as SQLITE_NOLFS,\n        SQLITE_NOMEM as SQLITE_NOMEM,\n        SQLITE_NOTADB as SQLITE_NOTADB,\n        SQLITE_NOTFOUND as SQLITE_NOTFOUND,\n        SQLITE_NOTICE as SQLITE_NOTICE,\n        SQLITE_NOTICE_RECOVER_ROLLBACK as SQLITE_NOTICE_RECOVER_ROLLBACK,\n        SQLITE_NOTICE_RECOVER_WAL as SQLITE_NOTICE_RECOVER_WAL,\n        SQLITE_OK_LOAD_PERMANENTLY as SQLITE_OK_LOAD_PERMANENTLY,\n        SQLITE_OK_SYMLINK as SQLITE_OK_SYMLINK,\n        SQLITE_PERM as SQLITE_PERM,\n        SQLITE_PROTOCOL as SQLITE_PROTOCOL,\n        SQLITE_RANGE as SQLITE_RANGE,\n        SQLITE_READONLY as SQLITE_READONLY,\n        SQLITE_READONLY_CANTINIT as SQLITE_READONLY_CANTINIT,\n        SQLITE_READONLY_CANTLOCK as SQLITE_READONLY_CANTLOCK,\n        SQLITE_READONLY_DBMOVED as SQLITE_READONLY_DBMOVED,\n        SQLITE_READONLY_DIRECTORY as SQLITE_READONLY_DIRECTORY,\n        SQLITE_READONLY_RECOVERY as SQLITE_READONLY_RECOVERY,\n        SQLITE_READONLY_ROLLBACK as SQLITE_READONLY_ROLLBACK,\n        SQLITE_ROW as SQLITE_ROW,\n        SQLITE_SCHEMA as SQLITE_SCHEMA,\n        SQLITE_TOOBIG as SQLITE_TOOBIG,\n        SQLITE_WARNING as SQLITE_WARNING,\n        SQLITE_WARNING_AUTOINDEX as SQLITE_WARNING_AUTOINDEX,\n    )\n    from sqlite3 import Blob as Blob\n\nif sys.version_info < (3, 14):\n    # Deprecated and removed from _sqlite3 in 3.12, but removed from here in 3.14.\n    version: Final[str]\n\nif sys.version_info < (3, 12):\n    if sys.version_info >= (3, 10):\n        # deprecation wrapper that has a different name for the argument...\n        @deprecated(\n            \"Deprecated since Python 3.10; removed in Python 3.12. \"\n            \"Open database in URI mode using `cache=shared` parameter instead.\"\n        )\n        def enable_shared_cache(enable: int) -> None: ...\n    else:\n        from _sqlite3 import enable_shared_cache as enable_shared_cache\n\nif sys.version_info < (3, 10):\n    from _sqlite3 import OptimizedUnicode as OptimizedUnicode\n\nparamstyle: Final = \"qmark\"\nthreadsafety: Literal[0, 1, 3]\napilevel: Final[str]\nDate = date\nTime = time\nTimestamp = datetime\n\ndef DateFromTicks(ticks: float) -> Date: ...\ndef TimeFromTicks(ticks: float) -> Time: ...\ndef TimestampFromTicks(ticks: float) -> Timestamp: ...\n\nif sys.version_info < (3, 14):\n    # Deprecated in 3.12, removed in 3.14.\n    version_info: Final[tuple[int, int, int]]\n\nsqlite_version_info: Final[tuple[int, int, int]]\nBinary = memoryview\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sqlite3/dump.pyi",
    "content": "# This file is intentionally empty. The runtime module contains only\n# private functions.\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sre_compile.pyi",
    "content": "from re import Pattern\nfrom sre_constants import *\nfrom sre_constants import _NamedIntConstant\nfrom sre_parse import SubPattern\nfrom typing import Any, Final\nfrom typing_extensions import TypeIs\n\nMAXCODE: Final[int]\n\ndef dis(code: list[_NamedIntConstant]) -> None: ...\ndef isstring(obj: object) -> TypeIs[str | bytes]: ...\ndef compile(p: str | bytes | SubPattern, flags: int = 0) -> Pattern[Any]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sre_constants.pyi",
    "content": "import sys\nfrom re import error as error\nfrom typing import Final\nfrom typing_extensions import Self, disjoint_base\n\nMAXGROUPS: Final[int]\n\nMAGIC: Final[int]\n\nif sys.version_info >= (3, 12):\n    class _NamedIntConstant(int):\n        name: str\n        def __new__(cls, value: int, name: str) -> Self: ...\n\nelse:\n    @disjoint_base\n    class _NamedIntConstant(int):\n        name: str\n        def __new__(cls, value: int, name: str) -> Self: ...\n\nMAXREPEAT: Final[_NamedIntConstant]\nOPCODES: list[_NamedIntConstant]\nATCODES: list[_NamedIntConstant]\nCHCODES: list[_NamedIntConstant]\nOP_IGNORE: dict[_NamedIntConstant, _NamedIntConstant]\nOP_LOCALE_IGNORE: dict[_NamedIntConstant, _NamedIntConstant]\nOP_UNICODE_IGNORE: dict[_NamedIntConstant, _NamedIntConstant]\nAT_MULTILINE: dict[_NamedIntConstant, _NamedIntConstant]\nAT_LOCALE: dict[_NamedIntConstant, _NamedIntConstant]\nAT_UNICODE: dict[_NamedIntConstant, _NamedIntConstant]\nCH_LOCALE: dict[_NamedIntConstant, _NamedIntConstant]\nCH_UNICODE: dict[_NamedIntConstant, _NamedIntConstant]\nif sys.version_info >= (3, 14):\n    CH_NEGATE: dict[_NamedIntConstant, _NamedIntConstant]\n# flags\nif sys.version_info < (3, 13):\n    SRE_FLAG_TEMPLATE: Final = 1\nSRE_FLAG_IGNORECASE: Final = 2\nSRE_FLAG_LOCALE: Final = 4\nSRE_FLAG_MULTILINE: Final = 8\nSRE_FLAG_DOTALL: Final = 16\nSRE_FLAG_UNICODE: Final = 32\nSRE_FLAG_VERBOSE: Final = 64\nSRE_FLAG_DEBUG: Final = 128\nSRE_FLAG_ASCII: Final = 256\n# flags for INFO primitive\nSRE_INFO_PREFIX: Final = 1\nSRE_INFO_LITERAL: Final = 2\nSRE_INFO_CHARSET: Final = 4\n\n# Stubgen above; manually defined constants below (dynamic at runtime)\n\n# from OPCODES\nFAILURE: Final[_NamedIntConstant]\nSUCCESS: Final[_NamedIntConstant]\nANY: Final[_NamedIntConstant]\nANY_ALL: Final[_NamedIntConstant]\nASSERT: Final[_NamedIntConstant]\nASSERT_NOT: Final[_NamedIntConstant]\nAT: Final[_NamedIntConstant]\nBRANCH: Final[_NamedIntConstant]\nif sys.version_info < (3, 11):\n    CALL: Final[_NamedIntConstant]\nCATEGORY: Final[_NamedIntConstant]\nCHARSET: Final[_NamedIntConstant]\nBIGCHARSET: Final[_NamedIntConstant]\nGROUPREF: Final[_NamedIntConstant]\nGROUPREF_EXISTS: Final[_NamedIntConstant]\nGROUPREF_IGNORE: Final[_NamedIntConstant]\nIN: Final[_NamedIntConstant]\nIN_IGNORE: Final[_NamedIntConstant]\nINFO: Final[_NamedIntConstant]\nJUMP: Final[_NamedIntConstant]\nLITERAL: Final[_NamedIntConstant]\nLITERAL_IGNORE: Final[_NamedIntConstant]\nMARK: Final[_NamedIntConstant]\nMAX_UNTIL: Final[_NamedIntConstant]\nMIN_UNTIL: Final[_NamedIntConstant]\nNOT_LITERAL: Final[_NamedIntConstant]\nNOT_LITERAL_IGNORE: Final[_NamedIntConstant]\nNEGATE: Final[_NamedIntConstant]\nRANGE: Final[_NamedIntConstant]\nREPEAT: Final[_NamedIntConstant]\nREPEAT_ONE: Final[_NamedIntConstant]\nSUBPATTERN: Final[_NamedIntConstant]\nMIN_REPEAT_ONE: Final[_NamedIntConstant]\nif sys.version_info >= (3, 11):\n    ATOMIC_GROUP: Final[_NamedIntConstant]\n    POSSESSIVE_REPEAT: Final[_NamedIntConstant]\n    POSSESSIVE_REPEAT_ONE: Final[_NamedIntConstant]\nRANGE_UNI_IGNORE: Final[_NamedIntConstant]\nGROUPREF_LOC_IGNORE: Final[_NamedIntConstant]\nGROUPREF_UNI_IGNORE: Final[_NamedIntConstant]\nIN_LOC_IGNORE: Final[_NamedIntConstant]\nIN_UNI_IGNORE: Final[_NamedIntConstant]\nLITERAL_LOC_IGNORE: Final[_NamedIntConstant]\nLITERAL_UNI_IGNORE: Final[_NamedIntConstant]\nNOT_LITERAL_LOC_IGNORE: Final[_NamedIntConstant]\nNOT_LITERAL_UNI_IGNORE: Final[_NamedIntConstant]\nMIN_REPEAT: Final[_NamedIntConstant]\nMAX_REPEAT: Final[_NamedIntConstant]\n\n# from ATCODES\nAT_BEGINNING: Final[_NamedIntConstant]\nAT_BEGINNING_LINE: Final[_NamedIntConstant]\nAT_BEGINNING_STRING: Final[_NamedIntConstant]\nAT_BOUNDARY: Final[_NamedIntConstant]\nAT_NON_BOUNDARY: Final[_NamedIntConstant]\nAT_END: Final[_NamedIntConstant]\nAT_END_LINE: Final[_NamedIntConstant]\nAT_END_STRING: Final[_NamedIntConstant]\nAT_LOC_BOUNDARY: Final[_NamedIntConstant]\nAT_LOC_NON_BOUNDARY: Final[_NamedIntConstant]\nAT_UNI_BOUNDARY: Final[_NamedIntConstant]\nAT_UNI_NON_BOUNDARY: Final[_NamedIntConstant]\n\n# from CHCODES\nCATEGORY_DIGIT: Final[_NamedIntConstant]\nCATEGORY_NOT_DIGIT: Final[_NamedIntConstant]\nCATEGORY_SPACE: Final[_NamedIntConstant]\nCATEGORY_NOT_SPACE: Final[_NamedIntConstant]\nCATEGORY_WORD: Final[_NamedIntConstant]\nCATEGORY_NOT_WORD: Final[_NamedIntConstant]\nCATEGORY_LINEBREAK: Final[_NamedIntConstant]\nCATEGORY_NOT_LINEBREAK: Final[_NamedIntConstant]\nCATEGORY_LOC_WORD: Final[_NamedIntConstant]\nCATEGORY_LOC_NOT_WORD: Final[_NamedIntConstant]\nCATEGORY_UNI_DIGIT: Final[_NamedIntConstant]\nCATEGORY_UNI_NOT_DIGIT: Final[_NamedIntConstant]\nCATEGORY_UNI_SPACE: Final[_NamedIntConstant]\nCATEGORY_UNI_NOT_SPACE: Final[_NamedIntConstant]\nCATEGORY_UNI_WORD: Final[_NamedIntConstant]\nCATEGORY_UNI_NOT_WORD: Final[_NamedIntConstant]\nCATEGORY_UNI_LINEBREAK: Final[_NamedIntConstant]\nCATEGORY_UNI_NOT_LINEBREAK: Final[_NamedIntConstant]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sre_parse.pyi",
    "content": "import sys\nfrom collections.abc import Iterable\nfrom re import Match, Pattern as _Pattern\nfrom sre_constants import *\nfrom sre_constants import _NamedIntConstant as _NIC, error as _Error\nfrom typing import Any, Final, overload\nfrom typing_extensions import TypeAlias\n\nSPECIAL_CHARS: Final = \".\\\\[{()*+?^$|\"\nREPEAT_CHARS: Final = \"*+?{\"\nDIGITS: Final[frozenset[str]]\nOCTDIGITS: Final[frozenset[str]]\nHEXDIGITS: Final[frozenset[str]]\nASCIILETTERS: Final[frozenset[str]]\nWHITESPACE: Final[frozenset[str]]\nESCAPES: Final[dict[str, tuple[_NIC, int]]]\nCATEGORIES: Final[dict[str, tuple[_NIC, _NIC] | tuple[_NIC, list[tuple[_NIC, _NIC]]]]]\nFLAGS: Final[dict[str, int]]\nTYPE_FLAGS: Final[int]\nGLOBAL_FLAGS: Final[int]\n\nif sys.version_info >= (3, 11):\n    MAXWIDTH: Final[int]\n\nif sys.version_info < (3, 11):\n    class Verbose(Exception): ...\n\n_OpSubpatternType: TypeAlias = tuple[int | None, int, int, SubPattern]\n_OpGroupRefExistsType: TypeAlias = tuple[int, SubPattern, SubPattern]\n_OpInType: TypeAlias = list[tuple[_NIC, int]]\n_OpBranchType: TypeAlias = tuple[None, list[SubPattern]]\n_AvType: TypeAlias = _OpInType | _OpBranchType | Iterable[SubPattern] | _OpGroupRefExistsType | _OpSubpatternType\n_CodeType: TypeAlias = tuple[_NIC, _AvType]\n\nclass State:\n    flags: int\n    groupdict: dict[str, int]\n    groupwidths: list[int | None]\n    lookbehindgroups: int | None\n    @property\n    def groups(self) -> int: ...\n    def opengroup(self, name: str | None = None) -> int: ...\n    def closegroup(self, gid: int, p: SubPattern) -> None: ...\n    def checkgroup(self, gid: int) -> bool: ...\n    def checklookbehindgroup(self, gid: int, source: Tokenizer) -> None: ...\n\nclass SubPattern:\n    data: list[_CodeType]\n    width: int | None\n    state: State\n\n    def __init__(self, state: State, data: list[_CodeType] | None = None) -> None: ...\n    def dump(self, level: int = 0) -> None: ...\n    def __len__(self) -> int: ...\n    def __delitem__(self, index: int | slice) -> None: ...\n    def __getitem__(self, index: int | slice) -> SubPattern | _CodeType: ...\n    def __setitem__(self, index: int | slice, code: _CodeType) -> None: ...\n    def insert(self, index: int, code: _CodeType) -> None: ...\n    def append(self, code: _CodeType) -> None: ...\n    def getwidth(self) -> tuple[int, int]: ...\n\nclass Tokenizer:\n    istext: bool\n    string: Any\n    decoded_string: str\n    index: int\n    next: str | None\n    def __init__(self, string: Any) -> None: ...\n    def match(self, char: str) -> bool: ...\n    def get(self) -> str | None: ...\n    def getwhile(self, n: int, charset: Iterable[str]) -> str: ...\n    def getuntil(self, terminator: str, name: str) -> str: ...\n    @property\n    def pos(self) -> int: ...\n    def tell(self) -> int: ...\n    def seek(self, index: int) -> None: ...\n    def error(self, msg: str, offset: int = 0) -> _Error: ...\n\n    if sys.version_info >= (3, 12):\n        def checkgroupname(self, name: str, offset: int) -> None: ...\n    elif sys.version_info >= (3, 11):\n        def checkgroupname(self, name: str, offset: int, nested: int) -> None: ...\n\ndef fix_flags(src: str | bytes, flags: int) -> int: ...\n\n_TemplateType: TypeAlias = tuple[list[tuple[int, int]], list[str | None]]\n_TemplateByteType: TypeAlias = tuple[list[tuple[int, int]], list[bytes | None]]\n\nif sys.version_info >= (3, 12):\n    @overload\n    def parse_template(source: str, pattern: _Pattern[Any]) -> _TemplateType: ...\n    @overload\n    def parse_template(source: bytes, pattern: _Pattern[Any]) -> _TemplateByteType: ...\n\nelse:\n    @overload\n    def parse_template(source: str, state: _Pattern[Any]) -> _TemplateType: ...\n    @overload\n    def parse_template(source: bytes, state: _Pattern[Any]) -> _TemplateByteType: ...\n\ndef parse(str: str, flags: int = 0, state: State | None = None) -> SubPattern: ...\n\nif sys.version_info < (3, 12):\n    def expand_template(template: _TemplateType, match: Match[Any]) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/ssl.pyi",
    "content": "import enum\nimport socket\nimport sys\nfrom _ssl import (\n    _DEFAULT_CIPHERS as _DEFAULT_CIPHERS,\n    _OPENSSL_API_VERSION as _OPENSSL_API_VERSION,\n    HAS_ALPN as HAS_ALPN,\n    HAS_ECDH as HAS_ECDH,\n    HAS_NPN as HAS_NPN,\n    HAS_SNI as HAS_SNI,\n    OPENSSL_VERSION as OPENSSL_VERSION,\n    OPENSSL_VERSION_INFO as OPENSSL_VERSION_INFO,\n    OPENSSL_VERSION_NUMBER as OPENSSL_VERSION_NUMBER,\n    HAS_SSLv2 as HAS_SSLv2,\n    HAS_SSLv3 as HAS_SSLv3,\n    HAS_TLSv1 as HAS_TLSv1,\n    HAS_TLSv1_1 as HAS_TLSv1_1,\n    HAS_TLSv1_2 as HAS_TLSv1_2,\n    HAS_TLSv1_3 as HAS_TLSv1_3,\n    MemoryBIO as MemoryBIO,\n    RAND_add as RAND_add,\n    RAND_bytes as RAND_bytes,\n    RAND_status as RAND_status,\n    SSLSession as SSLSession,\n    _PasswordType as _PasswordType,  # typeshed only, but re-export for other type stubs to use\n    _SSLContext,\n)\nfrom _typeshed import ReadableBuffer, StrOrBytesPath, WriteableBuffer\nfrom collections.abc import Callable, Iterable\nfrom typing import Any, Final, Literal, NamedTuple, TypedDict, overload, type_check_only\nfrom typing_extensions import Never, Self, TypeAlias, deprecated\n\nif sys.version_info >= (3, 13):\n    from _ssl import HAS_PSK as HAS_PSK\n\nif sys.version_info >= (3, 14):\n    from _ssl import HAS_PHA as HAS_PHA\n\nif sys.version_info < (3, 12):\n    from _ssl import RAND_pseudo_bytes as RAND_pseudo_bytes\n\nif sys.version_info < (3, 10):\n    from _ssl import RAND_egd as RAND_egd\n\nif sys.platform == \"win32\":\n    from _ssl import enum_certificates as enum_certificates, enum_crls as enum_crls\n\n_PCTRTT: TypeAlias = tuple[tuple[str, str], ...]\n_PCTRTTT: TypeAlias = tuple[_PCTRTT, ...]\n_PeerCertRetDictType: TypeAlias = dict[str, str | _PCTRTTT | _PCTRTT]\n_PeerCertRetType: TypeAlias = _PeerCertRetDictType | bytes | None\n_SrvnmeCbType: TypeAlias = Callable[[SSLSocket | SSLObject, str | None, SSLSocket], int | None]\n\nsocket_error = OSError\n\n@type_check_only\nclass _Cipher(TypedDict):\n    aead: bool\n    alg_bits: int\n    auth: str\n    description: str\n    digest: str | None\n    id: int\n    kea: str\n    name: str\n    protocol: str\n    strength_bits: int\n    symmetric: str\n\nclass SSLError(OSError):\n    library: str\n    reason: str\n\nclass SSLZeroReturnError(SSLError): ...\nclass SSLWantReadError(SSLError): ...\nclass SSLWantWriteError(SSLError): ...\nclass SSLSyscallError(SSLError): ...\nclass SSLEOFError(SSLError): ...\n\nclass SSLCertVerificationError(SSLError, ValueError):\n    verify_code: int\n    verify_message: str\n\nCertificateError = SSLCertVerificationError\n\nclass DefaultVerifyPaths(NamedTuple):\n    cafile: str\n    capath: str\n    openssl_cafile_env: str\n    openssl_cafile: str\n    openssl_capath_env: str\n    openssl_capath: str\n\ndef get_default_verify_paths() -> DefaultVerifyPaths: ...\n\nclass VerifyMode(enum.IntEnum):\n    CERT_NONE = 0\n    CERT_OPTIONAL = 1\n    CERT_REQUIRED = 2\n\nCERT_NONE: Final = VerifyMode.CERT_NONE\nCERT_OPTIONAL: Final = VerifyMode.CERT_OPTIONAL\nCERT_REQUIRED: Final = VerifyMode.CERT_REQUIRED\n\nclass VerifyFlags(enum.IntFlag):\n    VERIFY_DEFAULT = 0\n    VERIFY_CRL_CHECK_LEAF = 4\n    VERIFY_CRL_CHECK_CHAIN = 12\n    VERIFY_X509_STRICT = 32\n    VERIFY_X509_TRUSTED_FIRST = 32768\n    if sys.version_info >= (3, 10):\n        VERIFY_ALLOW_PROXY_CERTS = 64\n        VERIFY_X509_PARTIAL_CHAIN = 524288\n\nVERIFY_DEFAULT: Final = VerifyFlags.VERIFY_DEFAULT\nVERIFY_CRL_CHECK_LEAF: Final = VerifyFlags.VERIFY_CRL_CHECK_LEAF\nVERIFY_CRL_CHECK_CHAIN: Final = VerifyFlags.VERIFY_CRL_CHECK_CHAIN\nVERIFY_X509_STRICT: Final = VerifyFlags.VERIFY_X509_STRICT\nVERIFY_X509_TRUSTED_FIRST: Final = VerifyFlags.VERIFY_X509_TRUSTED_FIRST\n\nif sys.version_info >= (3, 10):\n    VERIFY_ALLOW_PROXY_CERTS: Final = VerifyFlags.VERIFY_ALLOW_PROXY_CERTS\n    VERIFY_X509_PARTIAL_CHAIN: Final = VerifyFlags.VERIFY_X509_PARTIAL_CHAIN\n\nclass _SSLMethod(enum.IntEnum):\n    PROTOCOL_SSLv23 = 2\n    PROTOCOL_SSLv2 = ...\n    PROTOCOL_SSLv3 = ...\n    PROTOCOL_TLSv1 = 3\n    PROTOCOL_TLSv1_1 = 4\n    PROTOCOL_TLSv1_2 = 5\n    PROTOCOL_TLS = 2\n    PROTOCOL_TLS_CLIENT = 16\n    PROTOCOL_TLS_SERVER = 17\n\nPROTOCOL_SSLv23: Final = _SSLMethod.PROTOCOL_SSLv23\nPROTOCOL_SSLv2: Final = _SSLMethod.PROTOCOL_SSLv2\nPROTOCOL_SSLv3: Final = _SSLMethod.PROTOCOL_SSLv3\nPROTOCOL_TLSv1: Final = _SSLMethod.PROTOCOL_TLSv1\nPROTOCOL_TLSv1_1: Final = _SSLMethod.PROTOCOL_TLSv1_1\nPROTOCOL_TLSv1_2: Final = _SSLMethod.PROTOCOL_TLSv1_2\nPROTOCOL_TLS: Final = _SSLMethod.PROTOCOL_TLS\nPROTOCOL_TLS_CLIENT: Final = _SSLMethod.PROTOCOL_TLS_CLIENT\nPROTOCOL_TLS_SERVER: Final = _SSLMethod.PROTOCOL_TLS_SERVER\n\nclass Options(enum.IntFlag):\n    OP_ALL = 2147483728\n    OP_NO_SSLv2 = 0\n    OP_NO_SSLv3 = 33554432\n    OP_NO_TLSv1 = 67108864\n    OP_NO_TLSv1_1 = 268435456\n    OP_NO_TLSv1_2 = 134217728\n    OP_NO_TLSv1_3 = 536870912\n    OP_CIPHER_SERVER_PREFERENCE = 4194304\n    OP_SINGLE_DH_USE = 0\n    OP_SINGLE_ECDH_USE = 0\n    OP_NO_COMPRESSION = 131072\n    OP_NO_TICKET = 16384\n    OP_NO_RENEGOTIATION = 1073741824\n    OP_ENABLE_MIDDLEBOX_COMPAT = 1048576\n    if sys.version_info >= (3, 12):\n        OP_LEGACY_SERVER_CONNECT = 4\n        OP_ENABLE_KTLS = 8\n    if sys.version_info >= (3, 11) or sys.platform == \"linux\":\n        OP_IGNORE_UNEXPECTED_EOF = 128\n\nOP_ALL: Final = Options.OP_ALL\nOP_NO_SSLv2: Final = Options.OP_NO_SSLv2\nOP_NO_SSLv3: Final = Options.OP_NO_SSLv3\nOP_NO_TLSv1: Final = Options.OP_NO_TLSv1\nOP_NO_TLSv1_1: Final = Options.OP_NO_TLSv1_1\nOP_NO_TLSv1_2: Final = Options.OP_NO_TLSv1_2\nOP_NO_TLSv1_3: Final = Options.OP_NO_TLSv1_3\nOP_CIPHER_SERVER_PREFERENCE: Final = Options.OP_CIPHER_SERVER_PREFERENCE\nOP_SINGLE_DH_USE: Final = Options.OP_SINGLE_DH_USE\nOP_SINGLE_ECDH_USE: Final = Options.OP_SINGLE_ECDH_USE\nOP_NO_COMPRESSION: Final = Options.OP_NO_COMPRESSION\nOP_NO_TICKET: Final = Options.OP_NO_TICKET\nOP_NO_RENEGOTIATION: Final = Options.OP_NO_RENEGOTIATION\nOP_ENABLE_MIDDLEBOX_COMPAT: Final = Options.OP_ENABLE_MIDDLEBOX_COMPAT\nif sys.version_info >= (3, 12):\n    OP_LEGACY_SERVER_CONNECT: Final = Options.OP_LEGACY_SERVER_CONNECT\n    OP_ENABLE_KTLS: Final = Options.OP_ENABLE_KTLS\nif sys.version_info >= (3, 11) or sys.platform == \"linux\":\n    OP_IGNORE_UNEXPECTED_EOF: Final = Options.OP_IGNORE_UNEXPECTED_EOF\n\nHAS_NEVER_CHECK_COMMON_NAME: Final[bool]\n\nCHANNEL_BINDING_TYPES: Final[list[str]]\n\nclass AlertDescription(enum.IntEnum):\n    ALERT_DESCRIPTION_ACCESS_DENIED = 49\n    ALERT_DESCRIPTION_BAD_CERTIFICATE = 42\n    ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE = 114\n    ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE = 113\n    ALERT_DESCRIPTION_BAD_RECORD_MAC = 20\n    ALERT_DESCRIPTION_CERTIFICATE_EXPIRED = 45\n    ALERT_DESCRIPTION_CERTIFICATE_REVOKED = 44\n    ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN = 46\n    ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE = 111\n    ALERT_DESCRIPTION_CLOSE_NOTIFY = 0\n    ALERT_DESCRIPTION_DECODE_ERROR = 50\n    ALERT_DESCRIPTION_DECOMPRESSION_FAILURE = 30\n    ALERT_DESCRIPTION_DECRYPT_ERROR = 51\n    ALERT_DESCRIPTION_HANDSHAKE_FAILURE = 40\n    ALERT_DESCRIPTION_ILLEGAL_PARAMETER = 47\n    ALERT_DESCRIPTION_INSUFFICIENT_SECURITY = 71\n    ALERT_DESCRIPTION_INTERNAL_ERROR = 80\n    ALERT_DESCRIPTION_NO_RENEGOTIATION = 100\n    ALERT_DESCRIPTION_PROTOCOL_VERSION = 70\n    ALERT_DESCRIPTION_RECORD_OVERFLOW = 22\n    ALERT_DESCRIPTION_UNEXPECTED_MESSAGE = 10\n    ALERT_DESCRIPTION_UNKNOWN_CA = 48\n    ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY = 115\n    ALERT_DESCRIPTION_UNRECOGNIZED_NAME = 112\n    ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE = 43\n    ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION = 110\n    ALERT_DESCRIPTION_USER_CANCELLED = 90\n\nALERT_DESCRIPTION_HANDSHAKE_FAILURE: Final = AlertDescription.ALERT_DESCRIPTION_HANDSHAKE_FAILURE\nALERT_DESCRIPTION_INTERNAL_ERROR: Final = AlertDescription.ALERT_DESCRIPTION_INTERNAL_ERROR\nALERT_DESCRIPTION_ACCESS_DENIED: Final = AlertDescription.ALERT_DESCRIPTION_ACCESS_DENIED\nALERT_DESCRIPTION_BAD_CERTIFICATE: Final = AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE\nALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE: Final = AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE_HASH_VALUE\nALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE: Final = AlertDescription.ALERT_DESCRIPTION_BAD_CERTIFICATE_STATUS_RESPONSE\nALERT_DESCRIPTION_BAD_RECORD_MAC: Final = AlertDescription.ALERT_DESCRIPTION_BAD_RECORD_MAC\nALERT_DESCRIPTION_CERTIFICATE_EXPIRED: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_EXPIRED\nALERT_DESCRIPTION_CERTIFICATE_REVOKED: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_REVOKED\nALERT_DESCRIPTION_CERTIFICATE_UNKNOWN: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_UNKNOWN\nALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE: Final = AlertDescription.ALERT_DESCRIPTION_CERTIFICATE_UNOBTAINABLE\nALERT_DESCRIPTION_CLOSE_NOTIFY: Final = AlertDescription.ALERT_DESCRIPTION_CLOSE_NOTIFY\nALERT_DESCRIPTION_DECODE_ERROR: Final = AlertDescription.ALERT_DESCRIPTION_DECODE_ERROR\nALERT_DESCRIPTION_DECOMPRESSION_FAILURE: Final = AlertDescription.ALERT_DESCRIPTION_DECOMPRESSION_FAILURE\nALERT_DESCRIPTION_DECRYPT_ERROR: Final = AlertDescription.ALERT_DESCRIPTION_DECRYPT_ERROR\nALERT_DESCRIPTION_ILLEGAL_PARAMETER: Final = AlertDescription.ALERT_DESCRIPTION_ILLEGAL_PARAMETER\nALERT_DESCRIPTION_INSUFFICIENT_SECURITY: Final = AlertDescription.ALERT_DESCRIPTION_INSUFFICIENT_SECURITY\nALERT_DESCRIPTION_NO_RENEGOTIATION: Final = AlertDescription.ALERT_DESCRIPTION_NO_RENEGOTIATION\nALERT_DESCRIPTION_PROTOCOL_VERSION: Final = AlertDescription.ALERT_DESCRIPTION_PROTOCOL_VERSION\nALERT_DESCRIPTION_RECORD_OVERFLOW: Final = AlertDescription.ALERT_DESCRIPTION_RECORD_OVERFLOW\nALERT_DESCRIPTION_UNEXPECTED_MESSAGE: Final = AlertDescription.ALERT_DESCRIPTION_UNEXPECTED_MESSAGE\nALERT_DESCRIPTION_UNKNOWN_CA: Final = AlertDescription.ALERT_DESCRIPTION_UNKNOWN_CA\nALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY: Final = AlertDescription.ALERT_DESCRIPTION_UNKNOWN_PSK_IDENTITY\nALERT_DESCRIPTION_UNRECOGNIZED_NAME: Final = AlertDescription.ALERT_DESCRIPTION_UNRECOGNIZED_NAME\nALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE: Final = AlertDescription.ALERT_DESCRIPTION_UNSUPPORTED_CERTIFICATE\nALERT_DESCRIPTION_UNSUPPORTED_EXTENSION: Final = AlertDescription.ALERT_DESCRIPTION_UNSUPPORTED_EXTENSION\nALERT_DESCRIPTION_USER_CANCELLED: Final = AlertDescription.ALERT_DESCRIPTION_USER_CANCELLED\n\n# This class is not exposed. It calls itself ssl._ASN1Object.\n@type_check_only\nclass _ASN1ObjectBase(NamedTuple):\n    nid: int\n    shortname: str\n    longname: str\n    oid: str\n\nclass _ASN1Object(_ASN1ObjectBase):\n    def __new__(cls, oid: str) -> Self: ...\n    @classmethod\n    def fromnid(cls, nid: int) -> Self: ...\n    @classmethod\n    def fromname(cls, name: str) -> Self: ...\n\nclass Purpose(_ASN1Object, enum.Enum):\n    # Normally this class would inherit __new__ from _ASN1Object, but\n    # because this is an enum, the inherited __new__ is replaced at runtime with\n    # Enum.__new__.\n    def __new__(cls, value: object) -> Self: ...\n    SERVER_AUTH = (129, \"serverAuth\", \"TLS Web Server Authentication\", \"1.3.6.1.5.5.7.3.2\")  # pyright: ignore[reportCallIssue]\n    CLIENT_AUTH = (130, \"clientAuth\", \"TLS Web Client Authentication\", \"1.3.6.1.5.5.7.3.1\")  # pyright: ignore[reportCallIssue]\n\nclass SSLSocket(socket.socket):\n    context: SSLContext\n    server_side: bool\n    server_hostname: str | None\n    session: SSLSession | None\n    @property\n    def session_reused(self) -> bool | None: ...\n    def __init__(self, *args: Any, **kwargs: Any) -> None: ...\n    def connect(self, addr: socket._Address) -> None: ...\n    def connect_ex(self, addr: socket._Address) -> int: ...\n    def recv(self, buflen: int = 1024, flags: int = 0) -> bytes: ...\n    def recv_into(self, buffer: WriteableBuffer, nbytes: int | None = None, flags: int = 0) -> int: ...\n    def recvfrom(self, buflen: int = 1024, flags: int = 0) -> tuple[bytes, socket._RetAddress]: ...\n    def recvfrom_into(\n        self, buffer: WriteableBuffer, nbytes: int | None = None, flags: int = 0\n    ) -> tuple[int, socket._RetAddress]: ...\n    def send(self, data: ReadableBuffer, flags: int = 0) -> int: ...\n    def sendall(self, data: ReadableBuffer, flags: int = 0) -> None: ...\n    @overload\n    def sendto(self, data: ReadableBuffer, flags_or_addr: socket._Address, addr: None = None) -> int: ...\n    @overload\n    def sendto(self, data: ReadableBuffer, flags_or_addr: int, addr: socket._Address) -> int: ...\n    def shutdown(self, how: int) -> None: ...\n    @deprecated(\"Deprecated since Python 3.6. Use `SSLSocket.recv` method instead.\")\n    def read(self, len: int = 1024, buffer: bytearray | None = None) -> bytes: ...\n    @deprecated(\"Deprecated since Python 3.6. Use `SSLSocket.send` method instead.\")\n    def write(self, data: ReadableBuffer) -> int: ...\n    def do_handshake(self, block: bool = False) -> None: ...  # block is undocumented\n    @overload\n    def getpeercert(self, binary_form: Literal[False] = False) -> _PeerCertRetDictType | None: ...\n    @overload\n    def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ...\n    @overload\n    def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ...\n    def cipher(self) -> tuple[str, str, int] | None: ...\n    def shared_ciphers(self) -> list[tuple[str, str, int]] | None: ...\n    def compression(self) -> str | None: ...\n    def get_channel_binding(self, cb_type: str = \"tls-unique\") -> bytes | None: ...\n    def selected_alpn_protocol(self) -> str | None: ...\n    if sys.version_info >= (3, 10):\n        @deprecated(\"Deprecated since Python 3.10. Use ALPN instead.\")\n        def selected_npn_protocol(self) -> str | None: ...\n    else:\n        def selected_npn_protocol(self) -> str | None: ...\n\n    def accept(self) -> tuple[SSLSocket, socket._RetAddress]: ...\n    def unwrap(self) -> socket.socket: ...\n    def version(self) -> str | None: ...\n    def pending(self) -> int: ...\n    def verify_client_post_handshake(self) -> None: ...\n    # These methods always raise `NotImplementedError`:\n    def recvmsg(self, *args: Never, **kwargs: Never) -> Never: ...  # type: ignore[override]\n    def recvmsg_into(self, *args: Never, **kwargs: Never) -> Never: ...  # type: ignore[override]\n    def sendmsg(self, *args: Never, **kwargs: Never) -> Never: ...  # type: ignore[override]\n    if sys.version_info >= (3, 13):\n        def get_verified_chain(self) -> list[bytes]: ...\n        def get_unverified_chain(self) -> list[bytes]: ...\n\nif sys.version_info < (3, 12):\n    @deprecated(\"Deprecated since Python 3.7; removed in Python 3.12. Use `SSLContext.wrap_socket()` instead.\")\n    def wrap_socket(\n        sock: socket.socket,\n        keyfile: StrOrBytesPath | None = None,\n        certfile: StrOrBytesPath | None = None,\n        server_side: bool = False,\n        cert_reqs: int = VerifyMode.CERT_NONE,\n        ssl_version: int = _SSLMethod.PROTOCOL_TLS,\n        ca_certs: str | None = None,\n        do_handshake_on_connect: bool = True,\n        suppress_ragged_eofs: bool = True,\n        ciphers: str | None = None,\n    ) -> SSLSocket: ...\n    @deprecated(\"Deprecated since Python 3.7; removed in Python 3.12.\")\n    def match_hostname(cert: _PeerCertRetDictType, hostname: str) -> None: ...\n\ndef cert_time_to_seconds(cert_time: str) -> int: ...\ndef DER_cert_to_PEM_cert(der_cert_bytes: ReadableBuffer) -> str: ...\ndef PEM_cert_to_DER_cert(pem_cert_string: str) -> bytes: ...\n\nif sys.version_info >= (3, 10):\n    def get_server_certificate(\n        addr: tuple[str, int],\n        ssl_version: int = _SSLMethod.PROTOCOL_TLS_CLIENT,\n        ca_certs: str | None = None,\n        timeout: float = ...,\n    ) -> str: ...\n\nelse:\n    def get_server_certificate(\n        addr: tuple[str, int], ssl_version: int = _SSLMethod.PROTOCOL_TLS_CLIENT, ca_certs: str | None = None\n    ) -> str: ...\n\nclass TLSVersion(enum.IntEnum):\n    MINIMUM_SUPPORTED = -2\n    MAXIMUM_SUPPORTED = -1\n    SSLv3 = 768\n    TLSv1 = 769\n    TLSv1_1 = 770\n    TLSv1_2 = 771\n    TLSv1_3 = 772\n\nclass SSLContext(_SSLContext):\n    options: Options\n    verify_flags: VerifyFlags\n    verify_mode: VerifyMode\n    @property\n    def protocol(self) -> _SSLMethod: ...  # type: ignore[override]\n    hostname_checks_common_name: bool\n    maximum_version: TLSVersion\n    minimum_version: TLSVersion\n    # The following two attributes have class-level defaults.\n    # However, the docs explicitly state that it's OK to override these attributes on instances,\n    # so making these ClassVars wouldn't be appropriate\n    sslobject_class: type[SSLObject]\n    sslsocket_class: type[SSLSocket]\n    keylog_filename: str\n    post_handshake_auth: bool\n    if sys.version_info >= (3, 10):\n        security_level: int\n    if sys.version_info >= (3, 10):\n        @overload\n        def __new__(cls, protocol: int, *args: Any, **kwargs: Any) -> Self: ...\n        @overload\n        @deprecated(\"Deprecated since Python 3.10. Use a specific version of the SSL protocol.\")\n        def __new__(cls, protocol: None = None, *args: Any, **kwargs: Any) -> Self: ...\n    else:\n        def __new__(cls, protocol: int = ..., *args: Any, **kwargs: Any) -> Self: ...\n\n    def load_default_certs(self, purpose: Purpose = Purpose.SERVER_AUTH) -> None: ...\n    def load_verify_locations(\n        self,\n        cafile: StrOrBytesPath | None = None,\n        capath: StrOrBytesPath | None = None,\n        cadata: str | ReadableBuffer | None = None,\n    ) -> None: ...\n    @overload\n    def get_ca_certs(self, binary_form: Literal[False] = False) -> list[_PeerCertRetDictType]: ...\n    @overload\n    def get_ca_certs(self, binary_form: Literal[True]) -> list[bytes]: ...\n    @overload\n    def get_ca_certs(self, binary_form: bool = False) -> Any: ...\n    def get_ciphers(self) -> list[_Cipher]: ...\n    def set_default_verify_paths(self) -> None: ...\n    def set_ciphers(self, cipherlist: str, /) -> None: ...\n    def set_alpn_protocols(self, alpn_protocols: Iterable[str]) -> None: ...\n    if sys.version_info >= (3, 10):\n        @deprecated(\"Deprecated since Python 3.10. Use ALPN instead.\")\n        def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ...\n    else:\n        def set_npn_protocols(self, npn_protocols: Iterable[str]) -> None: ...\n\n    def set_servername_callback(self, server_name_callback: _SrvnmeCbType | None) -> None: ...\n    def load_dh_params(self, path: str, /) -> None: ...\n    def set_ecdh_curve(self, name: str, /) -> None: ...\n    def wrap_socket(\n        self,\n        sock: socket.socket,\n        server_side: bool = False,\n        do_handshake_on_connect: bool = True,\n        suppress_ragged_eofs: bool = True,\n        server_hostname: str | bytes | None = None,\n        session: SSLSession | None = None,\n    ) -> SSLSocket: ...\n    def wrap_bio(\n        self,\n        incoming: MemoryBIO,\n        outgoing: MemoryBIO,\n        server_side: bool = False,\n        server_hostname: str | bytes | None = None,\n        session: SSLSession | None = None,\n    ) -> SSLObject: ...\n\ndef create_default_context(\n    purpose: Purpose = Purpose.SERVER_AUTH,\n    *,\n    cafile: StrOrBytesPath | None = None,\n    capath: StrOrBytesPath | None = None,\n    cadata: str | ReadableBuffer | None = None,\n) -> SSLContext: ...\n\nif sys.version_info >= (3, 10):\n    def _create_unverified_context(\n        protocol: int | None = None,\n        *,\n        cert_reqs: int = VerifyMode.CERT_NONE,\n        check_hostname: bool = False,\n        purpose: Purpose = Purpose.SERVER_AUTH,\n        certfile: StrOrBytesPath | None = None,\n        keyfile: StrOrBytesPath | None = None,\n        cafile: StrOrBytesPath | None = None,\n        capath: StrOrBytesPath | None = None,\n        cadata: str | ReadableBuffer | None = None,\n    ) -> SSLContext: ...\n\nelse:\n    def _create_unverified_context(\n        protocol: int = ...,\n        *,\n        cert_reqs: int = VerifyMode.CERT_NONE,\n        check_hostname: bool = False,\n        purpose: Purpose = Purpose.SERVER_AUTH,\n        certfile: StrOrBytesPath | None = None,\n        keyfile: StrOrBytesPath | None = None,\n        cafile: StrOrBytesPath | None = None,\n        capath: StrOrBytesPath | None = None,\n        cadata: str | ReadableBuffer | None = None,\n    ) -> SSLContext: ...\n\n_create_default_https_context = create_default_context\n\nclass SSLObject:\n    context: SSLContext\n    @property\n    def server_side(self) -> bool: ...\n    @property\n    def server_hostname(self) -> str | None: ...\n    session: SSLSession | None\n    @property\n    def session_reused(self) -> bool: ...\n    def __init__(self, *args: Any, **kwargs: Any) -> None: ...\n    def read(self, len: int = 1024, buffer: bytearray | None = None) -> bytes: ...\n    def write(self, data: ReadableBuffer) -> int: ...\n    @overload\n    def getpeercert(self, binary_form: Literal[False] = False) -> _PeerCertRetDictType | None: ...\n    @overload\n    def getpeercert(self, binary_form: Literal[True]) -> bytes | None: ...\n    @overload\n    def getpeercert(self, binary_form: bool) -> _PeerCertRetType: ...\n    def selected_alpn_protocol(self) -> str | None: ...\n    if sys.version_info >= (3, 10):\n        @deprecated(\"Deprecated since Python 3.10. Use ALPN instead.\")\n        def selected_npn_protocol(self) -> str | None: ...\n    else:\n        def selected_npn_protocol(self) -> str | None: ...\n\n    def cipher(self) -> tuple[str, str, int] | None: ...\n    def shared_ciphers(self) -> list[tuple[str, str, int]] | None: ...\n    def compression(self) -> str | None: ...\n    def pending(self) -> int: ...\n    def do_handshake(self) -> None: ...\n    def unwrap(self) -> None: ...\n    def version(self) -> str | None: ...\n    def get_channel_binding(self, cb_type: str = \"tls-unique\") -> bytes | None: ...\n    def verify_client_post_handshake(self) -> None: ...\n    if sys.version_info >= (3, 13):\n        def get_verified_chain(self) -> list[bytes]: ...\n        def get_unverified_chain(self) -> list[bytes]: ...\n\nclass SSLErrorNumber(enum.IntEnum):\n    SSL_ERROR_EOF = 8\n    SSL_ERROR_INVALID_ERROR_CODE = 10\n    SSL_ERROR_SSL = 1\n    SSL_ERROR_SYSCALL = 5\n    SSL_ERROR_WANT_CONNECT = 7\n    SSL_ERROR_WANT_READ = 2\n    SSL_ERROR_WANT_WRITE = 3\n    SSL_ERROR_WANT_X509_LOOKUP = 4\n    SSL_ERROR_ZERO_RETURN = 6\n\nSSL_ERROR_EOF: Final = SSLErrorNumber.SSL_ERROR_EOF  # undocumented\nSSL_ERROR_INVALID_ERROR_CODE: Final = SSLErrorNumber.SSL_ERROR_INVALID_ERROR_CODE  # undocumented\nSSL_ERROR_SSL: Final = SSLErrorNumber.SSL_ERROR_SSL  # undocumented\nSSL_ERROR_SYSCALL: Final = SSLErrorNumber.SSL_ERROR_SYSCALL  # undocumented\nSSL_ERROR_WANT_CONNECT: Final = SSLErrorNumber.SSL_ERROR_WANT_CONNECT  # undocumented\nSSL_ERROR_WANT_READ: Final = SSLErrorNumber.SSL_ERROR_WANT_READ  # undocumented\nSSL_ERROR_WANT_WRITE: Final = SSLErrorNumber.SSL_ERROR_WANT_WRITE  # undocumented\nSSL_ERROR_WANT_X509_LOOKUP: Final = SSLErrorNumber.SSL_ERROR_WANT_X509_LOOKUP  # undocumented\nSSL_ERROR_ZERO_RETURN: Final = SSLErrorNumber.SSL_ERROR_ZERO_RETURN  # undocumented\n\ndef get_protocol_name(protocol_code: int) -> str: ...\n\nPEM_FOOTER: Final[str]\nPEM_HEADER: Final[str]\nSOCK_STREAM: Final = socket.SOCK_STREAM\nSOL_SOCKET: Final = socket.SOL_SOCKET\nSO_TYPE: Final = socket.SO_TYPE\n"
  },
  {
    "path": "mypy/typeshed/stdlib/stat.pyi",
    "content": "import sys\nfrom _stat import (\n    S_ENFMT as S_ENFMT,\n    S_IEXEC as S_IEXEC,\n    S_IFBLK as S_IFBLK,\n    S_IFCHR as S_IFCHR,\n    S_IFDIR as S_IFDIR,\n    S_IFDOOR as S_IFDOOR,\n    S_IFIFO as S_IFIFO,\n    S_IFLNK as S_IFLNK,\n    S_IFMT as S_IFMT,\n    S_IFPORT as S_IFPORT,\n    S_IFREG as S_IFREG,\n    S_IFSOCK as S_IFSOCK,\n    S_IFWHT as S_IFWHT,\n    S_IMODE as S_IMODE,\n    S_IREAD as S_IREAD,\n    S_IRGRP as S_IRGRP,\n    S_IROTH as S_IROTH,\n    S_IRUSR as S_IRUSR,\n    S_IRWXG as S_IRWXG,\n    S_IRWXO as S_IRWXO,\n    S_IRWXU as S_IRWXU,\n    S_ISBLK as S_ISBLK,\n    S_ISCHR as S_ISCHR,\n    S_ISDIR as S_ISDIR,\n    S_ISDOOR as S_ISDOOR,\n    S_ISFIFO as S_ISFIFO,\n    S_ISGID as S_ISGID,\n    S_ISLNK as S_ISLNK,\n    S_ISPORT as S_ISPORT,\n    S_ISREG as S_ISREG,\n    S_ISSOCK as S_ISSOCK,\n    S_ISUID as S_ISUID,\n    S_ISVTX as S_ISVTX,\n    S_ISWHT as S_ISWHT,\n    S_IWGRP as S_IWGRP,\n    S_IWOTH as S_IWOTH,\n    S_IWRITE as S_IWRITE,\n    S_IWUSR as S_IWUSR,\n    S_IXGRP as S_IXGRP,\n    S_IXOTH as S_IXOTH,\n    S_IXUSR as S_IXUSR,\n    SF_APPEND as SF_APPEND,\n    SF_ARCHIVED as SF_ARCHIVED,\n    SF_IMMUTABLE as SF_IMMUTABLE,\n    SF_NOUNLINK as SF_NOUNLINK,\n    SF_SNAPSHOT as SF_SNAPSHOT,\n    ST_ATIME as ST_ATIME,\n    ST_CTIME as ST_CTIME,\n    ST_DEV as ST_DEV,\n    ST_GID as ST_GID,\n    ST_INO as ST_INO,\n    ST_MODE as ST_MODE,\n    ST_MTIME as ST_MTIME,\n    ST_NLINK as ST_NLINK,\n    ST_SIZE as ST_SIZE,\n    ST_UID as ST_UID,\n    UF_APPEND as UF_APPEND,\n    UF_COMPRESSED as UF_COMPRESSED,\n    UF_HIDDEN as UF_HIDDEN,\n    UF_IMMUTABLE as UF_IMMUTABLE,\n    UF_NODUMP as UF_NODUMP,\n    UF_NOUNLINK as UF_NOUNLINK,\n    UF_OPAQUE as UF_OPAQUE,\n    filemode as filemode,\n)\nfrom typing import Final\n\nif sys.platform == \"win32\":\n    from _stat import (\n        IO_REPARSE_TAG_APPEXECLINK as IO_REPARSE_TAG_APPEXECLINK,\n        IO_REPARSE_TAG_MOUNT_POINT as IO_REPARSE_TAG_MOUNT_POINT,\n        IO_REPARSE_TAG_SYMLINK as IO_REPARSE_TAG_SYMLINK,\n    )\n\nif sys.version_info >= (3, 13):\n    from _stat import (\n        SF_DATALESS as SF_DATALESS,\n        SF_FIRMLINK as SF_FIRMLINK,\n        SF_SETTABLE as SF_SETTABLE,\n        UF_DATAVAULT as UF_DATAVAULT,\n        UF_SETTABLE as UF_SETTABLE,\n        UF_TRACKED as UF_TRACKED,\n    )\n\n    if sys.platform == \"darwin\":\n        from _stat import SF_SUPPORTED as SF_SUPPORTED, SF_SYNTHETIC as SF_SYNTHETIC\n\n# _stat.c defines FILE_ATTRIBUTE_* constants conditionally,\n# making them available only at runtime on Windows.\n# stat.py unconditionally redefines the same FILE_ATTRIBUTE_* constants\n# on all platforms.\nFILE_ATTRIBUTE_ARCHIVE: Final = 32\nFILE_ATTRIBUTE_COMPRESSED: Final = 2048\nFILE_ATTRIBUTE_DEVICE: Final = 64\nFILE_ATTRIBUTE_DIRECTORY: Final = 16\nFILE_ATTRIBUTE_ENCRYPTED: Final = 16384\nFILE_ATTRIBUTE_HIDDEN: Final = 2\nFILE_ATTRIBUTE_INTEGRITY_STREAM: Final = 32768\nFILE_ATTRIBUTE_NORMAL: Final = 128\nFILE_ATTRIBUTE_NOT_CONTENT_INDEXED: Final = 8192\nFILE_ATTRIBUTE_NO_SCRUB_DATA: Final = 131072\nFILE_ATTRIBUTE_OFFLINE: Final = 4096\nFILE_ATTRIBUTE_READONLY: Final = 1\nFILE_ATTRIBUTE_REPARSE_POINT: Final = 1024\nFILE_ATTRIBUTE_SPARSE_FILE: Final = 512\nFILE_ATTRIBUTE_SYSTEM: Final = 4\nFILE_ATTRIBUTE_TEMPORARY: Final = 256\nFILE_ATTRIBUTE_VIRTUAL: Final = 65536\n\nif sys.version_info >= (3, 13):\n    # https://github.com/python/cpython/issues/114081#issuecomment-2119017790\n    SF_RESTRICTED: Final = 0x00080000\n"
  },
  {
    "path": "mypy/typeshed/stdlib/statistics.pyi",
    "content": "import sys\nfrom _typeshed import SupportsRichComparisonT\nfrom collections.abc import Callable, Hashable, Iterable, Sequence, Sized\nfrom decimal import Decimal\nfrom fractions import Fraction\nfrom typing import Literal, NamedTuple, Protocol, SupportsFloat, SupportsIndex, TypeVar\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\n    \"StatisticsError\",\n    \"fmean\",\n    \"geometric_mean\",\n    \"mean\",\n    \"harmonic_mean\",\n    \"pstdev\",\n    \"pvariance\",\n    \"stdev\",\n    \"variance\",\n    \"median\",\n    \"median_low\",\n    \"median_high\",\n    \"median_grouped\",\n    \"mode\",\n    \"multimode\",\n    \"NormalDist\",\n    \"quantiles\",\n]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"covariance\", \"correlation\", \"linear_regression\"]\nif sys.version_info >= (3, 13):\n    __all__ += [\"kde\", \"kde_random\"]\n\n# Most functions in this module accept homogeneous collections of one of these types\n_Number: TypeAlias = float | Decimal | Fraction\n_NumberT = TypeVar(\"_NumberT\", float, Decimal, Fraction)\n\n# Used in mode, multimode\n_HashableT = TypeVar(\"_HashableT\", bound=Hashable)\n\n# Used in NormalDist.samples and kde_random\n_Seed: TypeAlias = int | float | str | bytes | bytearray  # noqa: Y041\n\n# Used in linear_regression\n_T_co = TypeVar(\"_T_co\", covariant=True)\n\nclass _SizedIterable(Iterable[_T_co], Sized, Protocol[_T_co]): ...\nclass StatisticsError(ValueError): ...\n\nif sys.version_info >= (3, 11):\n    def fmean(data: Iterable[SupportsFloat], weights: Iterable[SupportsFloat] | None = None) -> float: ...\n\nelse:\n    def fmean(data: Iterable[SupportsFloat]) -> float: ...\n\ndef geometric_mean(data: Iterable[SupportsFloat]) -> float: ...\ndef mean(data: Iterable[_NumberT]) -> _NumberT: ...\n\nif sys.version_info >= (3, 10):\n    def harmonic_mean(data: Iterable[_NumberT], weights: Iterable[_Number] | None = None) -> _NumberT: ...\n\nelse:\n    def harmonic_mean(data: Iterable[_NumberT]) -> _NumberT: ...\n\ndef median(data: Iterable[_NumberT]) -> _NumberT: ...\ndef median_low(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ...\ndef median_high(data: Iterable[SupportsRichComparisonT]) -> SupportsRichComparisonT: ...\n\nif sys.version_info >= (3, 11):\n    def median_grouped(data: Iterable[SupportsFloat], interval: SupportsFloat = 1.0) -> float: ...\n\nelse:\n    def median_grouped(data: Iterable[_NumberT], interval: _NumberT | float = 1) -> _NumberT | float: ...\n\ndef mode(data: Iterable[_HashableT]) -> _HashableT: ...\ndef multimode(data: Iterable[_HashableT]) -> list[_HashableT]: ...\ndef pstdev(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: ...\ndef pvariance(data: Iterable[_NumberT], mu: _NumberT | None = None) -> _NumberT: ...\ndef quantiles(\n    data: Iterable[_NumberT], *, n: int = 4, method: Literal[\"inclusive\", \"exclusive\"] = \"exclusive\"\n) -> list[_NumberT]: ...\ndef stdev(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: ...\ndef variance(data: Iterable[_NumberT], xbar: _NumberT | None = None) -> _NumberT: ...\n\nclass NormalDist:\n    __slots__ = {\"_mu\": \"Arithmetic mean of a normal distribution\", \"_sigma\": \"Standard deviation of a normal distribution\"}\n    def __init__(self, mu: float = 0.0, sigma: float = 1.0) -> None: ...\n    @property\n    def mean(self) -> float: ...\n    @property\n    def median(self) -> float: ...\n    @property\n    def mode(self) -> float: ...\n    @property\n    def stdev(self) -> float: ...\n    @property\n    def variance(self) -> float: ...\n    @classmethod\n    def from_samples(cls, data: Iterable[SupportsFloat]) -> Self: ...\n    def samples(self, n: SupportsIndex, *, seed: _Seed | None = None) -> list[float]: ...\n    def pdf(self, x: float) -> float: ...\n    def cdf(self, x: float) -> float: ...\n    def inv_cdf(self, p: float) -> float: ...\n    def overlap(self, other: NormalDist) -> float: ...\n    def quantiles(self, n: int = 4) -> list[float]: ...\n    def zscore(self, x: float) -> float: ...\n    def __eq__(x1, x2: object) -> bool: ...\n    def __add__(x1, x2: float | NormalDist) -> NormalDist: ...\n    def __sub__(x1, x2: float | NormalDist) -> NormalDist: ...\n    def __mul__(x1, x2: float) -> NormalDist: ...\n    def __truediv__(x1, x2: float) -> NormalDist: ...\n    def __pos__(x1) -> NormalDist: ...\n    def __neg__(x1) -> NormalDist: ...\n    __radd__ = __add__\n    def __rsub__(x1, x2: float | NormalDist) -> NormalDist: ...\n    __rmul__ = __mul__\n    def __hash__(self) -> int: ...\n\nif sys.version_info >= (3, 12):\n    def correlation(\n        x: Sequence[_Number], y: Sequence[_Number], /, *, method: Literal[\"linear\", \"ranked\"] = \"linear\"\n    ) -> float: ...\n\nelif sys.version_info >= (3, 10):\n    def correlation(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ...\n\nif sys.version_info >= (3, 10):\n    def covariance(x: Sequence[_Number], y: Sequence[_Number], /) -> float: ...\n\n    class LinearRegression(NamedTuple):\n        slope: float\n        intercept: float\n\nif sys.version_info >= (3, 11):\n    def linear_regression(\n        regressor: _SizedIterable[_Number], dependent_variable: _SizedIterable[_Number], /, *, proportional: bool = False\n    ) -> LinearRegression: ...\n\nelif sys.version_info >= (3, 10):\n    def linear_regression(\n        regressor: _SizedIterable[_Number], dependent_variable: _SizedIterable[_Number], /\n    ) -> LinearRegression: ...\n\nif sys.version_info >= (3, 13):\n    _Kernel: TypeAlias = Literal[\n        \"normal\",\n        \"gauss\",\n        \"logistic\",\n        \"sigmoid\",\n        \"rectangular\",\n        \"uniform\",\n        \"triangular\",\n        \"parabolic\",\n        \"epanechnikov\",\n        \"quartic\",\n        \"biweight\",\n        \"triweight\",\n        \"cosine\",\n    ]\n    def kde(\n        data: Sequence[float], h: float, kernel: _Kernel = \"normal\", *, cumulative: bool = False\n    ) -> Callable[[float], float]: ...\n    def kde_random(\n        data: Sequence[float], h: float, kernel: _Kernel = \"normal\", *, seed: _Seed | None = None\n    ) -> Callable[[], float]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/string/__init__.pyi",
    "content": "import sys\nfrom _typeshed import StrOrLiteralStr\nfrom collections.abc import Iterable, Mapping, Sequence\nfrom re import Pattern, RegexFlag\nfrom typing import Any, ClassVar, Final, overload\nfrom typing_extensions import LiteralString\n\n__all__ = [\n    \"ascii_letters\",\n    \"ascii_lowercase\",\n    \"ascii_uppercase\",\n    \"capwords\",\n    \"digits\",\n    \"hexdigits\",\n    \"octdigits\",\n    \"printable\",\n    \"punctuation\",\n    \"whitespace\",\n    \"Formatter\",\n    \"Template\",\n]\n\nwhitespace: Final = \" \\t\\n\\r\\v\\f\"\nascii_lowercase: Final = \"abcdefghijklmnopqrstuvwxyz\"\nascii_uppercase: Final = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\nascii_letters: Final[LiteralString]  # string too long\ndigits: Final = \"0123456789\"\nhexdigits: Final = \"0123456789abcdefABCDEF\"\noctdigits: Final = \"01234567\"\npunctuation: Final = r\"\"\"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~\"\"\"\nprintable: Final[LiteralString]  # string too long\n\ndef capwords(s: StrOrLiteralStr, sep: StrOrLiteralStr | None = None) -> StrOrLiteralStr: ...\n\nclass Template:\n    template: str\n    delimiter: ClassVar[str]\n    idpattern: ClassVar[str]\n    braceidpattern: ClassVar[str | None]\n    if sys.version_info >= (3, 14):\n        flags: ClassVar[RegexFlag | None]\n    else:\n        flags: ClassVar[RegexFlag]\n    pattern: ClassVar[Pattern[str]]\n    def __init__(self, template: str) -> None: ...\n    def substitute(self, mapping: Mapping[str, object] = {}, /, **kwds: object) -> str: ...\n    def safe_substitute(self, mapping: Mapping[str, object] = {}, /, **kwds: object) -> str: ...\n    if sys.version_info >= (3, 11):\n        def get_identifiers(self) -> list[str]: ...\n        def is_valid(self) -> bool: ...\n\nclass Formatter:\n    @overload\n    def format(self, format_string: LiteralString, /, *args: LiteralString, **kwargs: LiteralString) -> LiteralString: ...\n    @overload\n    def format(self, format_string: str, /, *args: Any, **kwargs: Any) -> str: ...\n    @overload\n    def vformat(\n        self, format_string: LiteralString, args: Sequence[LiteralString], kwargs: Mapping[LiteralString, LiteralString]\n    ) -> LiteralString: ...\n    @overload\n    def vformat(self, format_string: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> str: ...\n    def _vformat(  # undocumented\n        self,\n        format_string: str,\n        args: Sequence[Any],\n        kwargs: Mapping[str, Any],\n        used_args: set[int | str],\n        recursion_depth: int,\n        auto_arg_index: int = 0,\n    ) -> tuple[str, int]: ...\n    def parse(\n        self, format_string: StrOrLiteralStr\n    ) -> Iterable[tuple[StrOrLiteralStr, StrOrLiteralStr | None, StrOrLiteralStr | None, StrOrLiteralStr | None]]: ...\n    def get_field(self, field_name: str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ...\n    def get_value(self, key: int | str, args: Sequence[Any], kwargs: Mapping[str, Any]) -> Any: ...\n    def check_unused_args(self, used_args: set[int | str], args: Sequence[Any], kwargs: Mapping[str, Any]) -> None: ...\n    def format_field(self, value: Any, format_spec: str) -> Any: ...\n    def convert_field(self, value: Any, conversion: str | None) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/string/templatelib.pyi",
    "content": "from collections.abc import Iterator\nfrom types import GenericAlias\nfrom typing import Any, Literal, TypeVar, final, overload\n\n_T = TypeVar(\"_T\")\n\n@final\nclass Template:  # TODO: consider making `Template` generic on `TypeVarTuple`\n    strings: tuple[str, ...]\n    interpolations: tuple[Interpolation, ...]\n\n    def __new__(cls, *args: str | Interpolation) -> Template: ...\n    def __iter__(self) -> Iterator[str | Interpolation]: ...\n    def __add__(self, other: Template, /) -> Template: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n    @property\n    def values(self) -> tuple[Any, ...]: ...  # Tuple of interpolation values, which can have any type\n\n@final\nclass Interpolation:\n    value: Any  # TODO: consider making `Interpolation` generic in runtime\n    expression: str\n    conversion: Literal[\"a\", \"r\", \"s\"] | None\n    format_spec: str\n\n    __match_args__ = (\"value\", \"expression\", \"conversion\", \"format_spec\")\n\n    def __new__(\n        cls, value: Any, expression: str = \"\", conversion: Literal[\"a\", \"r\", \"s\"] | None = None, format_spec: str = \"\"\n    ) -> Interpolation: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n@overload\ndef convert(obj: _T, /, conversion: None) -> _T: ...\n@overload\ndef convert(obj: object, /, conversion: Literal[\"r\", \"s\", \"a\"]) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/stringprep.pyi",
    "content": "from typing import Final\n\nb1_set: Final[set[int]]\nb3_exceptions: Final[dict[int, str]]\nc22_specials: Final[set[int]]\nc6_set: Final[set[int]]\nc7_set: Final[set[int]]\nc8_set: Final[set[int]]\nc9_set: Final[set[int]]\n\ndef in_table_a1(code: str) -> bool: ...\ndef in_table_b1(code: str) -> bool: ...\ndef map_table_b3(code: str) -> str: ...\ndef map_table_b2(a: str) -> str: ...\ndef in_table_c11(code: str) -> bool: ...\ndef in_table_c12(code: str) -> bool: ...\ndef in_table_c11_c12(code: str) -> bool: ...\ndef in_table_c21(code: str) -> bool: ...\ndef in_table_c22(code: str) -> bool: ...\ndef in_table_c21_c22(code: str) -> bool: ...\ndef in_table_c3(code: str) -> bool: ...\ndef in_table_c4(code: str) -> bool: ...\ndef in_table_c5(code: str) -> bool: ...\ndef in_table_c6(code: str) -> bool: ...\ndef in_table_c7(code: str) -> bool: ...\ndef in_table_c8(code: str) -> bool: ...\ndef in_table_c9(code: str) -> bool: ...\ndef in_table_d1(code: str) -> bool: ...\ndef in_table_d2(code: str) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/struct.pyi",
    "content": "from _struct import *\n\n__all__ = [\"calcsize\", \"pack\", \"pack_into\", \"unpack\", \"unpack_from\", \"iter_unpack\", \"Struct\", \"error\"]\n\nclass error(Exception): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/subprocess.pyi",
    "content": "import sys\nfrom _typeshed import MaybeNone, ReadableBuffer, StrOrBytesPath\nfrom collections.abc import Callable, Collection, Iterable, Mapping, Sequence\nfrom types import GenericAlias, TracebackType\nfrom typing import IO, Any, AnyStr, Final, Generic, Literal, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\n    \"Popen\",\n    \"PIPE\",\n    \"STDOUT\",\n    \"call\",\n    \"check_call\",\n    \"getstatusoutput\",\n    \"getoutput\",\n    \"check_output\",\n    \"run\",\n    \"CalledProcessError\",\n    \"DEVNULL\",\n    \"SubprocessError\",\n    \"TimeoutExpired\",\n    \"CompletedProcess\",\n]\n\nif sys.platform == \"win32\":\n    __all__ += [\n        \"CREATE_NEW_CONSOLE\",\n        \"CREATE_NEW_PROCESS_GROUP\",\n        \"STARTF_USESHOWWINDOW\",\n        \"STARTF_USESTDHANDLES\",\n        \"STARTUPINFO\",\n        \"STD_ERROR_HANDLE\",\n        \"STD_INPUT_HANDLE\",\n        \"STD_OUTPUT_HANDLE\",\n        \"SW_HIDE\",\n        \"ABOVE_NORMAL_PRIORITY_CLASS\",\n        \"BELOW_NORMAL_PRIORITY_CLASS\",\n        \"CREATE_BREAKAWAY_FROM_JOB\",\n        \"CREATE_DEFAULT_ERROR_MODE\",\n        \"CREATE_NO_WINDOW\",\n        \"DETACHED_PROCESS\",\n        \"HIGH_PRIORITY_CLASS\",\n        \"IDLE_PRIORITY_CLASS\",\n        \"NORMAL_PRIORITY_CLASS\",\n        \"REALTIME_PRIORITY_CLASS\",\n    ]\n\n# We prefer to annotate inputs to methods (eg subprocess.check_call) with these\n# union types.\n# For outputs we use laborious literal based overloads to try to determine\n# which specific return types to use, and prefer to fall back to Any when\n# this does not work, so the caller does not have to use an assertion to confirm\n# which type.\n#\n# For example:\n#\n# try:\n#    x = subprocess.check_output([\"ls\", \"-l\"])\n#    reveal_type(x)  # bytes, based on the overloads\n# except TimeoutError as e:\n#    reveal_type(e.cmd)  # Any, but morally is _CMD\n_FILE: TypeAlias = None | int | IO[Any]\n_InputString: TypeAlias = ReadableBuffer | str\n_CMD: TypeAlias = StrOrBytesPath | Sequence[StrOrBytesPath]\nif sys.platform == \"win32\":\n    _ENV: TypeAlias = Mapping[str, str]\nelse:\n    _ENV: TypeAlias = Mapping[bytes, StrOrBytesPath] | Mapping[str, StrOrBytesPath]\n\n_T = TypeVar(\"_T\")\n\n# These two are private but documented\nif sys.version_info >= (3, 11):\n    _USE_VFORK: Final[bool]\n_USE_POSIX_SPAWN: Final[bool]\n\nclass CompletedProcess(Generic[_T]):\n    # morally: _CMD\n    args: Any\n    returncode: int\n    # These can both be None, but requiring checks for None would be tedious\n    # and writing all the overloads would be horrific.\n    stdout: _T\n    stderr: _T\n    def __init__(self, args: _CMD, returncode: int, stdout: _T | None = None, stderr: _T | None = None) -> None: ...\n    def check_returncode(self) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nif sys.version_info >= (3, 11):\n    # 3.11 adds \"process_group\" argument\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str | None = None,\n        input: str | None = None,\n        text: Literal[True],\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str,\n        errors: str | None = None,\n        input: str | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str,\n        input: str | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        *,\n        universal_newlines: Literal[True],\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        # where the *real* keyword only args start\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str | None = None,\n        input: str | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: Literal[False] | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: None = None,\n        errors: None = None,\n        input: ReadableBuffer | None = None,\n        text: Literal[False] | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> CompletedProcess[bytes]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str | None = None,\n        input: _InputString | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> CompletedProcess[Any]: ...\n\nelif sys.version_info >= (3, 10):\n    # 3.10 adds \"pipesize\" argument\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str | None = None,\n        input: str | None = None,\n        text: Literal[True],\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str,\n        errors: str | None = None,\n        input: str | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str,\n        input: str | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        *,\n        universal_newlines: Literal[True],\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        # where the *real* keyword only args start\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str | None = None,\n        input: str | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: Literal[False] | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: None = None,\n        errors: None = None,\n        input: ReadableBuffer | None = None,\n        text: Literal[False] | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> CompletedProcess[bytes]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str | None = None,\n        input: _InputString | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> CompletedProcess[Any]: ...\n\nelse:\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str | None = None,\n        input: str | None = None,\n        text: Literal[True],\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str,\n        errors: str | None = None,\n        input: str | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str,\n        input: str | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        *,\n        universal_newlines: Literal[True],\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        # where the *real* keyword only args start\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str | None = None,\n        input: str | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> CompletedProcess[str]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: Literal[False] | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: None = None,\n        errors: None = None,\n        input: ReadableBuffer | None = None,\n        text: Literal[False] | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> CompletedProcess[bytes]: ...\n    @overload\n    def run(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        capture_output: bool = False,\n        check: bool = False,\n        encoding: str | None = None,\n        errors: str | None = None,\n        input: _InputString | None = None,\n        text: bool | None = None,\n        timeout: float | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> CompletedProcess[Any]: ...\n\n# Same args as Popen.__init__\nif sys.version_info >= (3, 11):\n    # 3.11 adds \"process_group\" argument\n    def call(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        encoding: str | None = None,\n        timeout: float | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> int: ...\n\nelif sys.version_info >= (3, 10):\n    # 3.10 adds \"pipesize\" argument\n    def call(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        encoding: str | None = None,\n        timeout: float | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> int: ...\n\nelse:\n    def call(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        encoding: str | None = None,\n        timeout: float | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> int: ...\n\n# Same args as Popen.__init__\nif sys.version_info >= (3, 11):\n    # 3.11 adds \"process_group\" argument\n    def check_call(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        timeout: float | None = None,\n        *,\n        encoding: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> int: ...\n\nelif sys.version_info >= (3, 10):\n    # 3.10 adds \"pipesize\" argument\n    def check_call(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        timeout: float | None = None,\n        *,\n        encoding: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> int: ...\n\nelse:\n    def check_call(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stdout: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        timeout: float | None = None,\n        *,\n        encoding: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> int: ...\n\nif sys.version_info >= (3, 11):\n    # 3.11 adds \"process_group\" argument\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: Literal[True],\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str,\n        errors: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        *,\n        universal_newlines: Literal[True],\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        # where the real keyword only ones start\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: Literal[False] | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> bytes: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n        process_group: int | None = None,\n    ) -> Any: ...  # morally: -> str | bytes\n\nelif sys.version_info >= (3, 10):\n    # 3.10 adds \"pipesize\" argument\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: Literal[True],\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str,\n        errors: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        *,\n        universal_newlines: Literal[True],\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        # where the real keyword only ones start\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: Literal[False] | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> bytes: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n        pipesize: int = -1,\n    ) -> Any: ...  # morally: -> str | bytes\n\nelse:\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: Literal[True],\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str,\n        errors: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        *,\n        universal_newlines: Literal[True],\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        # where the real keyword only ones start\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> str: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: Literal[False] | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: None = None,\n        errors: None = None,\n        text: Literal[False] | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> bytes: ...\n    @overload\n    def check_output(\n        args: _CMD,\n        bufsize: int = -1,\n        executable: StrOrBytesPath | None = None,\n        stdin: _FILE = None,\n        stderr: _FILE = None,\n        preexec_fn: Callable[[], object] | None = None,\n        close_fds: bool = True,\n        shell: bool = False,\n        cwd: StrOrBytesPath | None = None,\n        env: _ENV | None = None,\n        universal_newlines: bool | None = None,\n        startupinfo: Any = None,\n        creationflags: int = 0,\n        restore_signals: bool = True,\n        start_new_session: bool = False,\n        pass_fds: Collection[int] = (),\n        *,\n        timeout: float | None = None,\n        input: _InputString | None = None,\n        encoding: str | None = None,\n        errors: str | None = None,\n        text: bool | None = None,\n        user: str | int | None = None,\n        group: str | int | None = None,\n        extra_groups: Iterable[str | int] | None = None,\n        umask: int = -1,\n    ) -> Any: ...  # morally: -> str | bytes\n\nPIPE: Final[int]\nSTDOUT: Final[int]\nDEVNULL: Final[int]\n\nclass SubprocessError(Exception): ...\n\nclass TimeoutExpired(SubprocessError):\n    def __init__(\n        self, cmd: _CMD, timeout: float, output: str | bytes | None = None, stderr: str | bytes | None = None\n    ) -> None: ...\n    # morally: _CMD\n    cmd: Any\n    timeout: float\n    # morally: str | bytes | None\n    output: Any\n    stdout: bytes | None\n    stderr: bytes | None\n\nclass CalledProcessError(SubprocessError):\n    returncode: int\n    # morally: _CMD\n    cmd: Any\n    # morally: str | bytes | None\n    output: Any\n\n    # morally: str | bytes | None\n    stdout: Any\n    stderr: Any\n    def __init__(\n        self, returncode: int, cmd: _CMD, output: str | bytes | None = None, stderr: str | bytes | None = None\n    ) -> None: ...\n\nclass Popen(Generic[AnyStr]):\n    args: _CMD\n    stdin: IO[AnyStr] | None\n    stdout: IO[AnyStr] | None\n    stderr: IO[AnyStr] | None\n    pid: int\n    returncode: int | MaybeNone\n    universal_newlines: bool\n\n    if sys.version_info >= (3, 11):\n        # process_group is added in 3.11\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: bool | None = None,\n            encoding: str,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n            process_group: int | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: bool | None = None,\n            encoding: str | None = None,\n            errors: str,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n            process_group: int | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            *,\n            universal_newlines: Literal[True],\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            # where the *real* keyword only args start\n            text: bool | None = None,\n            encoding: str | None = None,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n            process_group: int | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: Literal[True],\n            encoding: str | None = None,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n            process_group: int | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[bytes],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: Literal[False] | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: Literal[False] | None = None,\n            encoding: None = None,\n            errors: None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n            process_group: int | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[Any],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: bool | None = None,\n            encoding: str | None = None,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n            process_group: int | None = None,\n        ) -> None: ...\n    elif sys.version_info >= (3, 10):\n        # pipesize is added in 3.10\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: bool | None = None,\n            encoding: str,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: bool | None = None,\n            encoding: str | None = None,\n            errors: str,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            *,\n            universal_newlines: Literal[True],\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            # where the *real* keyword only args start\n            text: bool | None = None,\n            encoding: str | None = None,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: Literal[True],\n            encoding: str | None = None,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[bytes],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: Literal[False] | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: Literal[False] | None = None,\n            encoding: None = None,\n            errors: None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[Any],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: bool | None = None,\n            encoding: str | None = None,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n            pipesize: int = -1,\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: bool | None = None,\n            encoding: str,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: bool | None = None,\n            encoding: str | None = None,\n            errors: str,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            *,\n            universal_newlines: Literal[True],\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            # where the *real* keyword only args start\n            text: bool | None = None,\n            encoding: str | None = None,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[str],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: Literal[True],\n            encoding: str | None = None,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[bytes],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: Literal[False] | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: Literal[False] | None = None,\n            encoding: None = None,\n            errors: None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: Popen[Any],\n            args: _CMD,\n            bufsize: int = -1,\n            executable: StrOrBytesPath | None = None,\n            stdin: _FILE | None = None,\n            stdout: _FILE | None = None,\n            stderr: _FILE | None = None,\n            preexec_fn: Callable[[], object] | None = None,\n            close_fds: bool = True,\n            shell: bool = False,\n            cwd: StrOrBytesPath | None = None,\n            env: _ENV | None = None,\n            universal_newlines: bool | None = None,\n            startupinfo: Any | None = None,\n            creationflags: int = 0,\n            restore_signals: bool = True,\n            start_new_session: bool = False,\n            pass_fds: Collection[int] = (),\n            *,\n            text: bool | None = None,\n            encoding: str | None = None,\n            errors: str | None = None,\n            user: str | int | None = None,\n            group: str | int | None = None,\n            extra_groups: Iterable[str | int] | None = None,\n            umask: int = -1,\n        ) -> None: ...\n\n    def poll(self) -> int | None: ...\n    def wait(self, timeout: float | None = None) -> int: ...\n    # morally the members of the returned tuple should be optional\n    # TODO: this should allow ReadableBuffer for Popen[bytes], but adding\n    # overloads for that runs into a mypy bug (python/mypy#14070).\n    def communicate(self, input: AnyStr | None = None, timeout: float | None = None) -> tuple[AnyStr, AnyStr]: ...\n    def send_signal(self, sig: int) -> None: ...\n    def terminate(self) -> None: ...\n    def kill(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n    ) -> None: ...\n    def __del__(self) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n# The result really is always a str.\nif sys.version_info >= (3, 11):\n    def getstatusoutput(cmd: _CMD, *, encoding: str | None = None, errors: str | None = None) -> tuple[int, str]: ...\n    def getoutput(cmd: _CMD, *, encoding: str | None = None, errors: str | None = None) -> str: ...\n\nelse:\n    def getstatusoutput(cmd: _CMD) -> tuple[int, str]: ...\n    def getoutput(cmd: _CMD) -> str: ...\n\ndef list2cmdline(seq: Iterable[StrOrBytesPath]) -> str: ...  # undocumented\n\nif sys.platform == \"win32\":\n    if sys.version_info >= (3, 13):\n        from _winapi import STARTF_FORCEOFFFEEDBACK, STARTF_FORCEONFEEDBACK\n\n        __all__ += [\"STARTF_FORCEOFFFEEDBACK\", \"STARTF_FORCEONFEEDBACK\"]\n\n    class STARTUPINFO:\n        def __init__(\n            self,\n            *,\n            dwFlags: int = 0,\n            hStdInput: Any | None = None,\n            hStdOutput: Any | None = None,\n            hStdError: Any | None = None,\n            wShowWindow: int = 0,\n            lpAttributeList: Mapping[str, Any] | None = None,\n        ) -> None: ...\n        dwFlags: int\n        hStdInput: Any | None\n        hStdOutput: Any | None\n        hStdError: Any | None\n        wShowWindow: int\n        lpAttributeList: Mapping[str, Any]\n        def copy(self) -> STARTUPINFO: ...\n\n    from _winapi import (\n        ABOVE_NORMAL_PRIORITY_CLASS as ABOVE_NORMAL_PRIORITY_CLASS,\n        BELOW_NORMAL_PRIORITY_CLASS as BELOW_NORMAL_PRIORITY_CLASS,\n        CREATE_BREAKAWAY_FROM_JOB as CREATE_BREAKAWAY_FROM_JOB,\n        CREATE_DEFAULT_ERROR_MODE as CREATE_DEFAULT_ERROR_MODE,\n        CREATE_NEW_CONSOLE as CREATE_NEW_CONSOLE,\n        CREATE_NEW_PROCESS_GROUP as CREATE_NEW_PROCESS_GROUP,\n        CREATE_NO_WINDOW as CREATE_NO_WINDOW,\n        DETACHED_PROCESS as DETACHED_PROCESS,\n        HIGH_PRIORITY_CLASS as HIGH_PRIORITY_CLASS,\n        IDLE_PRIORITY_CLASS as IDLE_PRIORITY_CLASS,\n        NORMAL_PRIORITY_CLASS as NORMAL_PRIORITY_CLASS,\n        REALTIME_PRIORITY_CLASS as REALTIME_PRIORITY_CLASS,\n        STARTF_USESHOWWINDOW as STARTF_USESHOWWINDOW,\n        STARTF_USESTDHANDLES as STARTF_USESTDHANDLES,\n        STD_ERROR_HANDLE as STD_ERROR_HANDLE,\n        STD_INPUT_HANDLE as STD_INPUT_HANDLE,\n        STD_OUTPUT_HANDLE as STD_OUTPUT_HANDLE,\n        SW_HIDE as SW_HIDE,\n    )\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sunau.pyi",
    "content": "from _typeshed import Unused\nfrom typing import IO, Any, Final, Literal, NamedTuple, NoReturn, overload\nfrom typing_extensions import Self, TypeAlias\n\n_File: TypeAlias = str | IO[bytes]\n\nclass Error(Exception): ...\n\nAUDIO_FILE_MAGIC: Final = 0x2E736E64\nAUDIO_FILE_ENCODING_MULAW_8: Final = 1\nAUDIO_FILE_ENCODING_LINEAR_8: Final = 2\nAUDIO_FILE_ENCODING_LINEAR_16: Final = 3\nAUDIO_FILE_ENCODING_LINEAR_24: Final = 4\nAUDIO_FILE_ENCODING_LINEAR_32: Final = 5\nAUDIO_FILE_ENCODING_FLOAT: Final = 6\nAUDIO_FILE_ENCODING_DOUBLE: Final = 7\nAUDIO_FILE_ENCODING_ADPCM_G721: Final = 23\nAUDIO_FILE_ENCODING_ADPCM_G722: Final = 24\nAUDIO_FILE_ENCODING_ADPCM_G723_3: Final = 25\nAUDIO_FILE_ENCODING_ADPCM_G723_5: Final = 26\nAUDIO_FILE_ENCODING_ALAW_8: Final = 27\nAUDIO_UNKNOWN_SIZE: Final = 0xFFFFFFFF\n\nclass _sunau_params(NamedTuple):\n    nchannels: int\n    sampwidth: int\n    framerate: int\n    nframes: int\n    comptype: str\n    compname: str\n\nclass Au_read:\n    def __init__(self, f: _File) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n    def __del__(self) -> None: ...\n    def getfp(self) -> IO[bytes] | None: ...\n    def rewind(self) -> None: ...\n    def close(self) -> None: ...\n    def tell(self) -> int: ...\n    def getnchannels(self) -> int: ...\n    def getnframes(self) -> int: ...\n    def getsampwidth(self) -> int: ...\n    def getframerate(self) -> int: ...\n    def getcomptype(self) -> str: ...\n    def getcompname(self) -> str: ...\n    def getparams(self) -> _sunau_params: ...\n    def getmarkers(self) -> None: ...\n    def getmark(self, id: Any) -> NoReturn: ...\n    def setpos(self, pos: int) -> None: ...\n    def readframes(self, nframes: int) -> bytes | None: ...\n\nclass Au_write:\n    def __init__(self, f: _File) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n    def __del__(self) -> None: ...\n    def setnchannels(self, nchannels: int) -> None: ...\n    def getnchannels(self) -> int: ...\n    def setsampwidth(self, sampwidth: int) -> None: ...\n    def getsampwidth(self) -> int: ...\n    def setframerate(self, framerate: float) -> None: ...\n    def getframerate(self) -> int: ...\n    def setnframes(self, nframes: int) -> None: ...\n    def getnframes(self) -> int: ...\n    def setcomptype(self, type: str, name: str) -> None: ...\n    def getcomptype(self) -> str: ...\n    def getcompname(self) -> str: ...\n    def setparams(self, params: _sunau_params) -> None: ...\n    def getparams(self) -> _sunau_params: ...\n    def tell(self) -> int: ...\n    # should be any bytes-like object after 3.4, but we don't have a type for that\n    def writeframesraw(self, data: bytes) -> None: ...\n    def writeframes(self, data: bytes) -> None: ...\n    def close(self) -> None: ...\n\n@overload\ndef open(f: _File, mode: Literal[\"r\", \"rb\"]) -> Au_read: ...\n@overload\ndef open(f: _File, mode: Literal[\"w\", \"wb\"]) -> Au_write: ...\n@overload\ndef open(f: _File, mode: str | None = None) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/symbol.pyi",
    "content": "from typing import Final\n\nsingle_input: Final[int]\nfile_input: Final[int]\neval_input: Final[int]\ndecorator: Final[int]\ndecorators: Final[int]\ndecorated: Final[int]\nasync_funcdef: Final[int]\nfuncdef: Final[int]\nparameters: Final[int]\ntypedargslist: Final[int]\ntfpdef: Final[int]\nvarargslist: Final[int]\nvfpdef: Final[int]\nstmt: Final[int]\nsimple_stmt: Final[int]\nsmall_stmt: Final[int]\nexpr_stmt: Final[int]\nannassign: Final[int]\ntestlist_star_expr: Final[int]\naugassign: Final[int]\ndel_stmt: Final[int]\npass_stmt: Final[int]\nflow_stmt: Final[int]\nbreak_stmt: Final[int]\ncontinue_stmt: Final[int]\nreturn_stmt: Final[int]\nyield_stmt: Final[int]\nraise_stmt: Final[int]\nimport_stmt: Final[int]\nimport_name: Final[int]\nimport_from: Final[int]\nimport_as_name: Final[int]\ndotted_as_name: Final[int]\nimport_as_names: Final[int]\ndotted_as_names: Final[int]\ndotted_name: Final[int]\nglobal_stmt: Final[int]\nnonlocal_stmt: Final[int]\nassert_stmt: Final[int]\ncompound_stmt: Final[int]\nasync_stmt: Final[int]\nif_stmt: Final[int]\nwhile_stmt: Final[int]\nfor_stmt: Final[int]\ntry_stmt: Final[int]\nwith_stmt: Final[int]\nwith_item: Final[int]\nexcept_clause: Final[int]\nsuite: Final[int]\ntest: Final[int]\ntest_nocond: Final[int]\nlambdef: Final[int]\nlambdef_nocond: Final[int]\nor_test: Final[int]\nand_test: Final[int]\nnot_test: Final[int]\ncomparison: Final[int]\ncomp_op: Final[int]\nstar_expr: Final[int]\nexpr: Final[int]\nxor_expr: Final[int]\nand_expr: Final[int]\nshift_expr: Final[int]\narith_expr: Final[int]\nterm: Final[int]\nfactor: Final[int]\npower: Final[int]\natom_expr: Final[int]\natom: Final[int]\ntestlist_comp: Final[int]\ntrailer: Final[int]\nsubscriptlist: Final[int]\nsubscript: Final[int]\nsliceop: Final[int]\nexprlist: Final[int]\ntestlist: Final[int]\ndictorsetmaker: Final[int]\nclassdef: Final[int]\narglist: Final[int]\nargument: Final[int]\ncomp_iter: Final[int]\ncomp_for: Final[int]\ncomp_if: Final[int]\nencoding_decl: Final[int]\nyield_expr: Final[int]\nyield_arg: Final[int]\nsync_comp_for: Final[int]\nfunc_body_suite: Final[int]\nfunc_type: Final[int]\nfunc_type_input: Final[int]\nnamedexpr_test: Final[int]\ntypelist: Final[int]\nsym_name: Final[dict[int, str]]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/symtable.pyi",
    "content": "import sys\nfrom _collections_abc import dict_keys\nfrom collections.abc import Sequence\nfrom typing import Any\nfrom typing_extensions import deprecated\n\n__all__ = [\"symtable\", \"SymbolTable\", \"Class\", \"Function\", \"Symbol\"]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"SymbolTableType\"]\n\ndef symtable(code: str, filename: str, compile_type: str) -> SymbolTable: ...\n\nif sys.version_info >= (3, 13):\n    from enum import StrEnum\n\n    class SymbolTableType(StrEnum):\n        MODULE = \"module\"\n        FUNCTION = \"function\"\n        CLASS = \"class\"\n        ANNOTATION = \"annotation\"\n        TYPE_ALIAS = \"type alias\"\n        TYPE_PARAMETERS = \"type parameters\"\n        TYPE_VARIABLE = \"type variable\"\n\nclass SymbolTable:\n    def __init__(self, raw_table: Any, filename: str) -> None: ...\n    if sys.version_info >= (3, 13):\n        def get_type(self) -> SymbolTableType: ...\n    else:\n        def get_type(self) -> str: ...\n\n    def get_id(self) -> int: ...\n    def get_name(self) -> str: ...\n    def get_lineno(self) -> int: ...\n    def is_optimized(self) -> bool: ...\n    def is_nested(self) -> bool: ...\n    def has_children(self) -> bool: ...\n    def get_identifiers(self) -> dict_keys[str, int]: ...\n    def lookup(self, name: str) -> Symbol: ...\n    def get_symbols(self) -> list[Symbol]: ...\n    def get_children(self) -> list[SymbolTable]: ...\n\nclass Function(SymbolTable):\n    def get_parameters(self) -> tuple[str, ...]: ...\n    def get_locals(self) -> tuple[str, ...]: ...\n    def get_globals(self) -> tuple[str, ...]: ...\n    def get_frees(self) -> tuple[str, ...]: ...\n    def get_nonlocals(self) -> tuple[str, ...]: ...\n\nclass Class(SymbolTable):\n    if sys.version_info >= (3, 14):\n        @deprecated(\"Deprecated since Python 3.14; will be removed in Python 3.16.\")\n        def get_methods(self) -> tuple[str, ...]: ...\n    else:\n        def get_methods(self) -> tuple[str, ...]: ...\n\nclass Symbol:\n    def __init__(\n        self, name: str, flags: int, namespaces: Sequence[SymbolTable] | None = None, *, module_scope: bool = False\n    ) -> None: ...\n    def is_nonlocal(self) -> bool: ...\n    def get_name(self) -> str: ...\n    def is_referenced(self) -> bool: ...\n    def is_parameter(self) -> bool: ...\n    if sys.version_info >= (3, 14):\n        def is_type_parameter(self) -> bool: ...\n\n    def is_global(self) -> bool: ...\n    def is_declared_global(self) -> bool: ...\n    def is_local(self) -> bool: ...\n    def is_annotated(self) -> bool: ...\n    def is_free(self) -> bool: ...\n    if sys.version_info >= (3, 14):\n        def is_free_class(self) -> bool: ...\n\n    def is_imported(self) -> bool: ...\n    def is_assigned(self) -> bool: ...\n    if sys.version_info >= (3, 14):\n        def is_comp_iter(self) -> bool: ...\n        def is_comp_cell(self) -> bool: ...\n\n    def is_namespace(self) -> bool: ...\n    def get_namespaces(self) -> Sequence[SymbolTable]: ...\n    def get_namespace(self) -> SymbolTable: ...\n\nclass SymbolTableFactory:\n    def new(self, table: Any, filename: str) -> SymbolTable: ...\n    def __call__(self, table: Any, filename: str) -> SymbolTable: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sys/__init__.pyi",
    "content": "import sys\nfrom _typeshed import MaybeNone, OptExcInfo, ProfileFunction, StrOrBytesPath, TraceFunction, structseq\nfrom _typeshed.importlib import MetaPathFinderProtocol, PathEntryFinderProtocol\nfrom builtins import object as _object\nfrom collections.abc import AsyncGenerator, Callable, Sequence\nfrom io import TextIOWrapper\nfrom types import FrameType, ModuleType, TracebackType\nfrom typing import Any, Final, Literal, NoReturn, Protocol, TextIO, TypeVar, final, overload, type_check_only\nfrom typing_extensions import LiteralString, TypeAlias, deprecated\n\n_T = TypeVar(\"_T\")\n\n# see https://github.com/python/typeshed/issues/8513#issue-1333671093 for the rationale behind this alias\n_ExitCode: TypeAlias = str | int | None\n\n# ----- sys variables -----\nif sys.platform != \"win32\":\n    abiflags: str\nargv: list[str]\nbase_exec_prefix: str\nbase_prefix: str\nbyteorder: Literal[\"little\", \"big\"]\nbuiltin_module_names: Sequence[str]  # actually a tuple of strings\ncopyright: str\nif sys.platform == \"win32\":\n    dllhandle: int\ndont_write_bytecode: bool\ndisplayhook: Callable[[object], Any]\nexcepthook: Callable[[type[BaseException], BaseException, TracebackType | None], Any]\nexec_prefix: str\nexecutable: str\nfloat_repr_style: Literal[\"short\", \"legacy\"]\nhexversion: int\nlast_type: type[BaseException] | None\nlast_value: BaseException | None\nlast_traceback: TracebackType | None\nif sys.version_info >= (3, 12):\n    last_exc: BaseException  # or undefined.\nmaxsize: int\nmaxunicode: int\nmeta_path: list[MetaPathFinderProtocol]\nmodules: dict[str, ModuleType]\nif sys.version_info >= (3, 10):\n    orig_argv: list[str]\npath: list[str]\npath_hooks: list[Callable[[str], PathEntryFinderProtocol]]\npath_importer_cache: dict[str, PathEntryFinderProtocol | None]\nplatform: LiteralString\nplatlibdir: str\nprefix: str\npycache_prefix: str | None\nps1: object\nps2: object\n\n# TextIO is used instead of more specific types for the standard streams,\n# since they are often monkeypatched at runtime. At startup, the objects\n# are initialized to instances of TextIOWrapper, but can also be None under\n# some circumstances.\n#\n# To use methods from TextIOWrapper, use an isinstance check to ensure that\n# the streams have not been overridden:\n#\n# if isinstance(sys.stdout, io.TextIOWrapper):\n#    sys.stdout.reconfigure(...)\nstdin: TextIO | MaybeNone\nstdout: TextIO | MaybeNone\nstderr: TextIO | MaybeNone\n\nif sys.version_info >= (3, 10):\n    stdlib_module_names: frozenset[str]\n\n__stdin__: Final[TextIOWrapper | None]  # Contains the original value of stdin\n__stdout__: Final[TextIOWrapper | None]  # Contains the original value of stdout\n__stderr__: Final[TextIOWrapper | None]  # Contains the original value of stderr\ntracebacklimit: int | None\nversion: str\napi_version: int\nwarnoptions: Any\n#  Each entry is a tuple of the form (action, message, category, module,\n#    lineno)\nif sys.platform == \"win32\":\n    winver: str\n_xoptions: dict[Any, Any]\n\n# Type alias used as a mixin for structseq classes that cannot be instantiated at runtime\n# This can't be represented in the type system, so we just use `structseq[Any]`\n_UninstantiableStructseq: TypeAlias = structseq[Any]\n\nflags: _flags\n\n# This class is not exposed at runtime. It calls itself sys.flags.\n# As a tuple, it can have a length between 15 and 18. We don't model\n# the exact length here because that varies by patch version due to\n# the backported security fix int_max_str_digits. The exact length shouldn't\n# be relied upon. See #13031\n# This can be re-visited when typeshed drops support for 3.10,\n# at which point all supported versions will include int_max_str_digits\n# in all patch versions.\n# 3.9 is 15 or 16-tuple\n# 3.10 is 16 or 17-tuple\n# 3.11+ is an 18-tuple.\n@final\n@type_check_only\nclass _flags(_UninstantiableStructseq, tuple[int, ...]):\n    # `safe_path` was added in py311\n    if sys.version_info >= (3, 11):\n        __match_args__: Final = (\n            \"debug\",\n            \"inspect\",\n            \"interactive\",\n            \"optimize\",\n            \"dont_write_bytecode\",\n            \"no_user_site\",\n            \"no_site\",\n            \"ignore_environment\",\n            \"verbose\",\n            \"bytes_warning\",\n            \"quiet\",\n            \"hash_randomization\",\n            \"isolated\",\n            \"dev_mode\",\n            \"utf8_mode\",\n            \"warn_default_encoding\",\n            \"safe_path\",\n            \"int_max_str_digits\",\n        )\n    elif sys.version_info >= (3, 10):\n        __match_args__: Final = (\n            \"debug\",\n            \"inspect\",\n            \"interactive\",\n            \"optimize\",\n            \"dont_write_bytecode\",\n            \"no_user_site\",\n            \"no_site\",\n            \"ignore_environment\",\n            \"verbose\",\n            \"bytes_warning\",\n            \"quiet\",\n            \"hash_randomization\",\n            \"isolated\",\n            \"dev_mode\",\n            \"utf8_mode\",\n            \"warn_default_encoding\",\n            \"int_max_str_digits\",\n        )\n\n    @property\n    def debug(self) -> int: ...\n    @property\n    def inspect(self) -> int: ...\n    @property\n    def interactive(self) -> int: ...\n    @property\n    def optimize(self) -> int: ...\n    @property\n    def dont_write_bytecode(self) -> int: ...\n    @property\n    def no_user_site(self) -> int: ...\n    @property\n    def no_site(self) -> int: ...\n    @property\n    def ignore_environment(self) -> int: ...\n    @property\n    def verbose(self) -> int: ...\n    @property\n    def bytes_warning(self) -> int: ...\n    @property\n    def quiet(self) -> int: ...\n    @property\n    def hash_randomization(self) -> int: ...\n    @property\n    def isolated(self) -> int: ...\n    @property\n    def dev_mode(self) -> bool: ...\n    @property\n    def utf8_mode(self) -> int: ...\n    if sys.version_info >= (3, 10):\n        @property\n        def warn_default_encoding(self) -> int: ...\n    if sys.version_info >= (3, 11):\n        @property\n        def safe_path(self) -> bool: ...\n    if sys.version_info >= (3, 13):\n        @property\n        def gil(self) -> Literal[0, 1]: ...\n    if sys.version_info >= (3, 14):\n        @property\n        def thread_inherit_context(self) -> Literal[0, 1]: ...\n        @property\n        def context_aware_warnings(self) -> Literal[0, 1]: ...\n    # Whether or not this exists on lower versions of Python\n    # may depend on which patch release you're using\n    # (it was backported to all Python versions on 3.8+ as a security fix)\n    # Added in: 3.9.14, 3.10.7\n    # and present in all versions of 3.11 and later.\n    @property\n    def int_max_str_digits(self) -> int: ...\n\nfloat_info: _float_info\n\n# This class is not exposed at runtime. It calls itself sys.float_info.\n@final\n@type_check_only\nclass _float_info(structseq[float], tuple[float, int, int, float, int, int, int, int, float, int, int]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\n            \"max\",\n            \"max_exp\",\n            \"max_10_exp\",\n            \"min\",\n            \"min_exp\",\n            \"min_10_exp\",\n            \"dig\",\n            \"mant_dig\",\n            \"epsilon\",\n            \"radix\",\n            \"rounds\",\n        )\n\n    @property\n    def max(self) -> float: ...  # DBL_MAX\n    @property\n    def max_exp(self) -> int: ...  # DBL_MAX_EXP\n    @property\n    def max_10_exp(self) -> int: ...  # DBL_MAX_10_EXP\n    @property\n    def min(self) -> float: ...  # DBL_MIN\n    @property\n    def min_exp(self) -> int: ...  # DBL_MIN_EXP\n    @property\n    def min_10_exp(self) -> int: ...  # DBL_MIN_10_EXP\n    @property\n    def dig(self) -> int: ...  # DBL_DIG\n    @property\n    def mant_dig(self) -> int: ...  # DBL_MANT_DIG\n    @property\n    def epsilon(self) -> float: ...  # DBL_EPSILON\n    @property\n    def radix(self) -> int: ...  # FLT_RADIX\n    @property\n    def rounds(self) -> int: ...  # FLT_ROUNDS\n\nhash_info: _hash_info\n\n# This class is not exposed at runtime. It calls itself sys.hash_info.\n@final\n@type_check_only\nclass _hash_info(structseq[Any | int], tuple[int, int, int, int, int, str, int, int, int]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"width\", \"modulus\", \"inf\", \"nan\", \"imag\", \"algorithm\", \"hash_bits\", \"seed_bits\", \"cutoff\")\n\n    @property\n    def width(self) -> int: ...\n    @property\n    def modulus(self) -> int: ...\n    @property\n    def inf(self) -> int: ...\n    @property\n    def nan(self) -> int: ...\n    @property\n    def imag(self) -> int: ...\n    @property\n    def algorithm(self) -> str: ...\n    @property\n    def hash_bits(self) -> int: ...\n    @property\n    def seed_bits(self) -> int: ...\n    @property\n    def cutoff(self) -> int: ...  # undocumented\n\nimplementation: _implementation\n\n# This class isn't really a thing. At runtime, implementation is an instance\n# of types.SimpleNamespace. This allows for better typing.\n@type_check_only\nclass _implementation:\n    name: str\n    version: _version_info\n    hexversion: int\n    cache_tag: str\n    # Define __getattr__, as the documentation states:\n    # > sys.implementation may contain additional attributes specific to the Python implementation.\n    # > These non-standard attributes must start with an underscore, and are not described here.\n    def __getattr__(self, name: str) -> Any: ...\n\nint_info: _int_info\n\n# This class is not exposed at runtime. It calls itself sys.int_info.\n@final\n@type_check_only\nclass _int_info(structseq[int], tuple[int, int, int, int]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"bits_per_digit\", \"sizeof_digit\", \"default_max_str_digits\", \"str_digits_check_threshold\")\n\n    @property\n    def bits_per_digit(self) -> int: ...\n    @property\n    def sizeof_digit(self) -> int: ...\n    @property\n    def default_max_str_digits(self) -> int: ...\n    @property\n    def str_digits_check_threshold(self) -> int: ...\n\n_ThreadInfoName: TypeAlias = Literal[\"nt\", \"pthread\", \"pthread-stubs\", \"solaris\"]\n_ThreadInfoLock: TypeAlias = Literal[\"semaphore\", \"mutex+cond\"] | None\n\n# This class is not exposed at runtime. It calls itself sys.thread_info.\n@final\n@type_check_only\nclass _thread_info(_UninstantiableStructseq, tuple[_ThreadInfoName, _ThreadInfoLock, str | None]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"name\", \"lock\", \"version\")\n\n    @property\n    def name(self) -> _ThreadInfoName: ...\n    @property\n    def lock(self) -> _ThreadInfoLock: ...\n    @property\n    def version(self) -> str | None: ...\n\nthread_info: _thread_info\n_ReleaseLevel: TypeAlias = Literal[\"alpha\", \"beta\", \"candidate\", \"final\"]\n\n# This class is not exposed at runtime. It calls itself sys.version_info.\n@final\n@type_check_only\nclass _version_info(_UninstantiableStructseq, tuple[int, int, int, _ReleaseLevel, int]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"major\", \"minor\", \"micro\", \"releaselevel\", \"serial\")\n\n    @property\n    def major(self) -> int: ...\n    @property\n    def minor(self) -> int: ...\n    @property\n    def micro(self) -> int: ...\n    @property\n    def releaselevel(self) -> _ReleaseLevel: ...\n    @property\n    def serial(self) -> int: ...\n\nversion_info: _version_info\n\ndef call_tracing(func: Callable[..., _T], args: Any, /) -> _T: ...\n\nif sys.version_info >= (3, 13):\n    @deprecated(\"Deprecated since Python 3.13. Use `_clear_internal_caches()` instead.\")\n    def _clear_type_cache() -> None: ...\n\nelse:\n    def _clear_type_cache() -> None: ...\n\ndef _current_frames() -> dict[int, FrameType]: ...\ndef _getframe(depth: int = 0, /) -> FrameType: ...\n\n# documented -- see https://docs.python.org/3/library/sys.html#sys._current_exceptions\nif sys.version_info >= (3, 12):\n    def _current_exceptions() -> dict[int, BaseException | None]: ...\n\nelse:\n    def _current_exceptions() -> dict[int, OptExcInfo]: ...\n\nif sys.version_info >= (3, 12):\n    def _getframemodulename(depth: int = 0) -> str | None: ...\n\ndef _debugmallocstats() -> None: ...\ndef __displayhook__(object: object, /) -> None: ...\ndef __excepthook__(exctype: type[BaseException], value: BaseException, traceback: TracebackType | None, /) -> None: ...\ndef exc_info() -> OptExcInfo: ...\n\nif sys.version_info >= (3, 11):\n    def exception() -> BaseException | None: ...\n\ndef exit(status: _ExitCode = None, /) -> NoReturn: ...\n\nif sys.platform == \"android\":  # noqa: Y008\n    def getandroidapilevel() -> int: ...\n\ndef getallocatedblocks() -> int: ...\ndef getdefaultencoding() -> Literal[\"utf-8\"]: ...\n\nif sys.platform != \"win32\":\n    def getdlopenflags() -> int: ...\n\ndef getfilesystemencoding() -> LiteralString: ...\ndef getfilesystemencodeerrors() -> LiteralString: ...\ndef getrefcount(object: Any, /) -> int: ...\ndef getrecursionlimit() -> int: ...\ndef getsizeof(obj: object, default: int = ...) -> int: ...\ndef getswitchinterval() -> float: ...\ndef getprofile() -> ProfileFunction | None: ...\ndef setprofile(function: ProfileFunction | None, /) -> None: ...\ndef gettrace() -> TraceFunction | None: ...\ndef settrace(function: TraceFunction | None, /) -> None: ...\n\nif sys.platform == \"win32\":\n    # A tuple of length 5, even though it has more than 5 attributes.\n    @final\n    @type_check_only\n    class _WinVersion(_UninstantiableStructseq, tuple[int, int, int, int, str]):\n        @property\n        def major(self) -> int: ...\n        @property\n        def minor(self) -> int: ...\n        @property\n        def build(self) -> int: ...\n        @property\n        def platform(self) -> int: ...\n        @property\n        def service_pack(self) -> str: ...\n        @property\n        def service_pack_minor(self) -> int: ...\n        @property\n        def service_pack_major(self) -> int: ...\n        @property\n        def suite_mask(self) -> int: ...\n        @property\n        def product_type(self) -> int: ...\n        @property\n        def platform_version(self) -> tuple[int, int, int]: ...\n\n    def getwindowsversion() -> _WinVersion: ...\n\n@overload\ndef intern(string: LiteralString, /) -> LiteralString: ...\n@overload\ndef intern(string: str, /) -> str: ...  # type: ignore[misc]\n\n__interactivehook__: Callable[[], object]\n\nif sys.version_info >= (3, 13):\n    def _is_gil_enabled() -> bool: ...\n    def _clear_internal_caches() -> None: ...\n    def _is_interned(string: str, /) -> bool: ...\n\ndef is_finalizing() -> bool: ...\ndef breakpointhook(*args: Any, **kwargs: Any) -> Any: ...\n\n__breakpointhook__ = breakpointhook  # Contains the original value of breakpointhook\n\nif sys.platform != \"win32\":\n    def setdlopenflags(flags: int, /) -> None: ...\n\ndef setrecursionlimit(limit: int, /) -> None: ...\ndef setswitchinterval(interval: float, /) -> None: ...\ndef gettotalrefcount() -> int: ...  # Debug builds only\n\n# Doesn't exist at runtime, but exported in the stubs so pytest etc. can annotate their code more easily.\n@type_check_only\nclass UnraisableHookArgs(Protocol):\n    exc_type: type[BaseException]\n    exc_value: BaseException | None\n    exc_traceback: TracebackType | None\n    err_msg: str | None\n    object: _object\n\nunraisablehook: Callable[[UnraisableHookArgs], Any]\n\ndef __unraisablehook__(unraisable: UnraisableHookArgs, /) -> Any: ...\ndef addaudithook(hook: Callable[[str, tuple[Any, ...]], Any]) -> None: ...\ndef audit(event: str, /, *args: Any) -> None: ...\n\n_AsyncgenHook: TypeAlias = Callable[[AsyncGenerator[Any, Any]], None] | None\n\n# This class is not exposed at runtime. It calls itself builtins.asyncgen_hooks.\n@final\n@type_check_only\nclass _asyncgen_hooks(structseq[_AsyncgenHook], tuple[_AsyncgenHook, _AsyncgenHook]):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"firstiter\", \"finalizer\")\n\n    @property\n    def firstiter(self) -> _AsyncgenHook: ...\n    @property\n    def finalizer(self) -> _AsyncgenHook: ...\n\ndef get_asyncgen_hooks() -> _asyncgen_hooks: ...\ndef set_asyncgen_hooks(firstiter: _AsyncgenHook = ..., finalizer: _AsyncgenHook = ...) -> None: ...\n\nif sys.platform == \"win32\":\n    if sys.version_info >= (3, 13):\n        @deprecated(\n            \"Deprecated since Python 3.13; will be removed in Python 3.16. \"\n            \"Use the `PYTHONLEGACYWINDOWSFSENCODING` environment variable instead.\"\n        )\n        def _enablelegacywindowsfsencoding() -> None: ...\n    else:\n        def _enablelegacywindowsfsencoding() -> None: ...\n\ndef get_coroutine_origin_tracking_depth() -> int: ...\ndef set_coroutine_origin_tracking_depth(depth: int) -> None: ...\n\n# The following two functions were added in 3.11.0, 3.10.7, and 3.9.14,\n# as part of the response to CVE-2020-10735\ndef set_int_max_str_digits(maxdigits: int) -> None: ...\ndef get_int_max_str_digits() -> int: ...\n\nif sys.version_info >= (3, 12):\n    if sys.version_info >= (3, 13):\n        def getunicodeinternedsize(*, _only_immortal: bool = False) -> int: ...\n    else:\n        def getunicodeinternedsize() -> int: ...\n\n    def deactivate_stack_trampoline() -> None: ...\n    def is_stack_trampoline_active() -> bool: ...\n    # It always exists, but raises on non-linux platforms:\n    if sys.platform == \"linux\":\n        def activate_stack_trampoline(backend: str, /) -> None: ...\n    else:\n        def activate_stack_trampoline(backend: str, /) -> NoReturn: ...\n\n    from . import _monitoring\n\n    monitoring = _monitoring\n\nif sys.version_info >= (3, 14):\n    def is_remote_debug_enabled() -> bool: ...\n    def remote_exec(pid: int, script: StrOrBytesPath) -> None: ...\n    def _is_immortal(op: object, /) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sys/_monitoring.pyi",
    "content": "# This py312+ module provides annotations for `sys.monitoring`.\n# It's named `sys._monitoring` in typeshed,\n# because trying to import `sys.monitoring` will fail at runtime!\n# At runtime, `sys.monitoring` has the unique status\n# of being a `types.ModuleType` instance that cannot be directly imported,\n# and exists in the `sys`-module namespace despite `sys` not being a package.\n\nimport sys\nfrom collections.abc import Callable\nfrom types import CodeType\nfrom typing import Any, Final, type_check_only\nfrom typing_extensions import deprecated\n\nDEBUGGER_ID: Final = 0\nCOVERAGE_ID: Final = 1\nPROFILER_ID: Final = 2\nOPTIMIZER_ID: Final = 5\n\ndef use_tool_id(tool_id: int, name: str, /) -> None: ...\n\nif sys.version_info >= (3, 14):\n    def clear_tool_id(tool_id: int, /) -> None: ...\n\ndef free_tool_id(tool_id: int, /) -> None: ...\ndef get_tool(tool_id: int, /) -> str | None: ...\n\nevents: Final[_events]\n\n@type_check_only\nclass _events:\n    CALL: Final[int]\n    C_RAISE: Final[int]\n    C_RETURN: Final[int]\n    EXCEPTION_HANDLED: Final[int]\n    INSTRUCTION: Final[int]\n    JUMP: Final[int]\n    LINE: Final[int]\n    NO_EVENTS: Final[int]\n    PY_RESUME: Final[int]\n    PY_RETURN: Final[int]\n    PY_START: Final[int]\n    PY_THROW: Final[int]\n    PY_UNWIND: Final[int]\n    PY_YIELD: Final[int]\n    RAISE: Final[int]\n    RERAISE: Final[int]\n    STOP_ITERATION: Final[int]\n    if sys.version_info >= (3, 14):\n        BRANCH_LEFT: Final[int]\n        BRANCH_RIGHT: Final[int]\n\n        @property\n        @deprecated(\"Deprecated since Python 3.14. Use `BRANCH_LEFT` or `BRANCH_RIGHT` instead.\")\n        def BRANCH(self) -> int: ...\n\n    else:\n        BRANCH: Final[int]\n\ndef get_events(tool_id: int, /) -> int: ...\ndef set_events(tool_id: int, event_set: int, /) -> None: ...\ndef get_local_events(tool_id: int, code: CodeType, /) -> int: ...\ndef set_local_events(tool_id: int, code: CodeType, event_set: int, /) -> None: ...\ndef restart_events() -> None: ...\n\nDISABLE: Final[object]\nMISSING: Final[object]\n\ndef register_callback(tool_id: int, event: int, func: Callable[..., object] | None, /) -> Callable[..., Any] | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/sysconfig.pyi",
    "content": "import sys\nfrom typing import IO, Any, Literal, overload\nfrom typing_extensions import LiteralString, deprecated\n\n__all__ = [\n    \"get_config_h_filename\",\n    \"get_config_var\",\n    \"get_config_vars\",\n    \"get_makefile_filename\",\n    \"get_path\",\n    \"get_path_names\",\n    \"get_paths\",\n    \"get_platform\",\n    \"get_python_version\",\n    \"get_scheme_names\",\n    \"parse_config_h\",\n]\n\n@overload\n@deprecated(\"SO is deprecated, use EXT_SUFFIX. Support is removed in Python 3.11\")\ndef get_config_var(name: Literal[\"SO\"]) -> Any: ...\n@overload\ndef get_config_var(name: str) -> Any: ...\n@overload\ndef get_config_vars() -> dict[str, Any]: ...\n@overload\ndef get_config_vars(arg: str, /, *args: str) -> list[Any]: ...\ndef get_scheme_names() -> tuple[str, ...]: ...\n\nif sys.version_info >= (3, 10):\n    def get_default_scheme() -> LiteralString: ...\n    def get_preferred_scheme(key: Literal[\"prefix\", \"home\", \"user\"]) -> LiteralString: ...\n    # Documented -- see https://docs.python.org/3/library/sysconfig.html#sysconfig._get_preferred_schemes\n    def _get_preferred_schemes() -> dict[Literal[\"prefix\", \"home\", \"user\"], LiteralString]: ...\n\ndef get_path_names() -> tuple[str, ...]: ...\ndef get_path(name: str, scheme: str = ..., vars: dict[str, Any] | None = None, expand: bool = True) -> str: ...\ndef get_paths(scheme: str = ..., vars: dict[str, Any] | None = None, expand: bool = True) -> dict[str, str]: ...\ndef get_python_version() -> str: ...\ndef get_platform() -> str: ...\n\nif sys.version_info >= (3, 12):\n    @overload\n    def is_python_build() -> bool: ...\n    @overload\n    @deprecated(\"The `check_home` parameter is deprecated since Python 3.12; removed in Python 3.15.\")\n    def is_python_build(check_home: object = None) -> bool: ...\n\nelif sys.version_info >= (3, 11):\n    def is_python_build(check_home: object = None) -> bool: ...\n\nelse:\n    def is_python_build(check_home: bool = False) -> bool: ...\n\ndef parse_config_h(fp: IO[Any], vars: dict[str, Any] | None = None) -> dict[str, Any]: ...\ndef get_config_h_filename() -> str: ...\ndef get_makefile_filename() -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/syslog.pyi",
    "content": "import sys\nfrom typing import Final, overload\n\nif sys.platform != \"win32\":\n    LOG_ALERT: Final = 1\n    LOG_AUTH: Final = 32\n    LOG_AUTHPRIV: Final = 80\n    LOG_CONS: Final = 2\n    LOG_CRIT: Final = 2\n    LOG_CRON: Final = 72\n    LOG_DAEMON: Final = 24\n    LOG_DEBUG: Final = 7\n    LOG_EMERG: Final = 0\n    LOG_ERR: Final = 3\n    LOG_INFO: Final = 6\n    LOG_KERN: Final = 0\n    LOG_LOCAL0: Final = 128\n    LOG_LOCAL1: Final = 136\n    LOG_LOCAL2: Final = 144\n    LOG_LOCAL3: Final = 152\n    LOG_LOCAL4: Final = 160\n    LOG_LOCAL5: Final = 168\n    LOG_LOCAL6: Final = 176\n    LOG_LOCAL7: Final = 184\n    LOG_LPR: Final = 48\n    LOG_MAIL: Final = 16\n    LOG_NDELAY: Final = 8\n    LOG_NEWS: Final = 56\n    LOG_NOTICE: Final = 5\n    LOG_NOWAIT: Final = 16\n    LOG_ODELAY: Final = 4\n    LOG_PERROR: Final = 32\n    LOG_PID: Final = 1\n    LOG_SYSLOG: Final = 40\n    LOG_USER: Final = 8\n    LOG_UUCP: Final = 64\n    LOG_WARNING: Final = 4\n\n    if sys.version_info >= (3, 13):\n        LOG_FTP: Final = 88\n\n        if sys.platform == \"darwin\":\n            LOG_INSTALL: Final = 112\n            LOG_LAUNCHD: Final = 192\n            LOG_NETINFO: Final = 96\n            LOG_RAS: Final = 120\n            LOG_REMOTEAUTH: Final = 104\n\n    def LOG_MASK(pri: int, /) -> int: ...\n    def LOG_UPTO(pri: int, /) -> int: ...\n    def closelog() -> None: ...\n    def openlog(ident: str = ..., logoption: int = 0, facility: int = ...) -> None: ...\n    def setlogmask(maskpri: int, /) -> int: ...\n    @overload\n    def syslog(priority: int, message: str) -> None: ...\n    @overload\n    def syslog(message: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tabnanny.pyi",
    "content": "from _typeshed import StrOrBytesPath\nfrom collections.abc import Iterable\n\n__all__ = [\"check\", \"NannyNag\", \"process_tokens\"]\n\nverbose: int\nfilename_only: int\n\nclass NannyNag(Exception):\n    def __init__(self, lineno: int, msg: str, line: str) -> None: ...\n    def get_lineno(self) -> int: ...\n    def get_msg(self) -> str: ...\n    def get_line(self) -> str: ...\n\ndef check(file: StrOrBytesPath) -> None: ...\ndef process_tokens(tokens: Iterable[tuple[int, str, tuple[int, int], tuple[int, int], str]]) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tarfile.pyi",
    "content": "import bz2\nimport io\nimport sys\nfrom _typeshed import ReadableBuffer, StrOrBytesPath, StrPath, SupportsRead, WriteableBuffer\nfrom builtins import list as _list  # aliases to avoid name clashes with fields named \"type\" or \"list\"\nfrom collections.abc import Callable, Iterable, Iterator, Mapping\nfrom gzip import _ReadableFileobj as _GzipReadableFileobj, _WritableFileobj as _GzipWritableFileobj\nfrom types import TracebackType\nfrom typing import IO, ClassVar, Final, Literal, Protocol, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, deprecated\n\nif sys.version_info >= (3, 14):\n    from compression.zstd import ZstdDict\n\n__all__ = [\n    \"TarFile\",\n    \"TarInfo\",\n    \"is_tarfile\",\n    \"TarError\",\n    \"ReadError\",\n    \"CompressionError\",\n    \"StreamError\",\n    \"ExtractError\",\n    \"HeaderError\",\n    \"ENCODING\",\n    \"USTAR_FORMAT\",\n    \"GNU_FORMAT\",\n    \"PAX_FORMAT\",\n    \"DEFAULT_FORMAT\",\n    \"open\",\n]\nif sys.version_info >= (3, 12):\n    __all__ += [\n        \"fully_trusted_filter\",\n        \"data_filter\",\n        \"tar_filter\",\n        \"FilterError\",\n        \"AbsoluteLinkError\",\n        \"OutsideDestinationError\",\n        \"SpecialFileError\",\n        \"AbsolutePathError\",\n        \"LinkOutsideDestinationError\",\n    ]\nif sys.version_info >= (3, 13):\n    __all__ += [\"LinkFallbackError\"]\n\n_FilterFunction: TypeAlias = Callable[[TarInfo, str], TarInfo | None]\n_TarfileFilter: TypeAlias = Literal[\"fully_trusted\", \"tar\", \"data\"] | _FilterFunction\n\n@type_check_only\nclass _Fileobj(Protocol):\n    def read(self, size: int, /) -> bytes: ...\n    def write(self, b: bytes, /) -> object: ...\n    def tell(self) -> int: ...\n    def seek(self, pos: int, /) -> object: ...\n    def close(self) -> object: ...\n    # Optional fields:\n    # name: str | bytes\n    # mode: Literal[\"rb\", \"r+b\", \"wb\", \"xb\"]\n\n@type_check_only\nclass _Bz2ReadableFileobj(bz2._ReadableFileobj):\n    def close(self) -> object: ...\n\n@type_check_only\nclass _Bz2WritableFileobj(bz2._WritableFileobj):\n    def close(self) -> object: ...\n\n# tar constants\nNUL: Final = b\"\\0\"\nBLOCKSIZE: Final = 512\nRECORDSIZE: Final = 10240\nGNU_MAGIC: Final = b\"ustar  \\0\"\nPOSIX_MAGIC: Final = b\"ustar\\x0000\"\n\nLENGTH_NAME: Final = 100\nLENGTH_LINK: Final = 100\nLENGTH_PREFIX: Final = 155\n\nREGTYPE: Final = b\"0\"\nAREGTYPE: Final = b\"\\0\"\nLNKTYPE: Final = b\"1\"\nSYMTYPE: Final = b\"2\"\nCHRTYPE: Final = b\"3\"\nBLKTYPE: Final = b\"4\"\nDIRTYPE: Final = b\"5\"\nFIFOTYPE: Final = b\"6\"\nCONTTYPE: Final = b\"7\"\n\nGNUTYPE_LONGNAME: Final = b\"L\"\nGNUTYPE_LONGLINK: Final = b\"K\"\nGNUTYPE_SPARSE: Final = b\"S\"\n\nXHDTYPE: Final = b\"x\"\nXGLTYPE: Final = b\"g\"\nSOLARIS_XHDTYPE: Final = b\"X\"\n\n_TarFormat: TypeAlias = Literal[0, 1, 2]  # does not exist at runtime\nUSTAR_FORMAT: Final = 0\nGNU_FORMAT: Final = 1\nPAX_FORMAT: Final = 2\nDEFAULT_FORMAT: Final = PAX_FORMAT\n\n# tarfile constants\n\nSUPPORTED_TYPES: Final[tuple[bytes, ...]]\nREGULAR_TYPES: Final[tuple[bytes, ...]]\nGNU_TYPES: Final[tuple[bytes, ...]]\nPAX_FIELDS: Final[tuple[str, ...]]\nPAX_NUMBER_FIELDS: Final[dict[str, type]]\nPAX_NAME_FIELDS: Final[set[str]]\n\nENCODING: Final[str]\n\nclass ExFileObject(io.BufferedReader):  # undocumented\n    def __init__(self, tarfile: TarFile, tarinfo: TarInfo) -> None: ...\n\nclass TarFile:\n    OPEN_METH: ClassVar[Mapping[str, str]]\n    name: StrOrBytesPath | None\n    mode: Literal[\"r\", \"a\", \"w\", \"x\"]\n    fileobj: _Fileobj\n    format: _TarFormat\n    tarinfo: type[TarInfo]\n    dereference: bool\n    ignore_zeros: bool\n    encoding: str\n    errors: str\n    fileobject: type[ExFileObject]  # undocumented\n    pax_headers: Mapping[str, str]\n    debug: int\n    errorlevel: int\n    offset: int  # undocumented\n    extraction_filter: _FilterFunction | None\n    if sys.version_info >= (3, 13):\n        stream: bool\n        def __init__(\n            self,\n            name: StrOrBytesPath | None = None,\n            mode: Literal[\"r\", \"a\", \"w\", \"x\"] = \"r\",\n            fileobj: _Fileobj | None = None,\n            format: int | None = None,\n            tarinfo: type[TarInfo] | None = None,\n            dereference: bool | None = None,\n            ignore_zeros: bool | None = None,\n            encoding: str | None = None,\n            errors: str = \"surrogateescape\",\n            pax_headers: Mapping[str, str] | None = None,\n            debug: int | None = None,\n            errorlevel: int | None = None,\n            copybufsize: int | None = None,  # undocumented\n            stream: bool = False,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            name: StrOrBytesPath | None = None,\n            mode: Literal[\"r\", \"a\", \"w\", \"x\"] = \"r\",\n            fileobj: _Fileobj | None = None,\n            format: int | None = None,\n            tarinfo: type[TarInfo] | None = None,\n            dereference: bool | None = None,\n            ignore_zeros: bool | None = None,\n            encoding: str | None = None,\n            errors: str = \"surrogateescape\",\n            pax_headers: Mapping[str, str] | None = None,\n            debug: int | None = None,\n            errorlevel: int | None = None,\n            copybufsize: int | None = None,  # undocumented\n        ) -> None: ...\n\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n    ) -> None: ...\n    def __iter__(self) -> Iterator[TarInfo]: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | None = None,\n        mode: Literal[\"r\", \"r:*\", \"r:\", \"r:gz\", \"r:bz2\", \"r:xz\"] = \"r\",\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    if sys.version_info >= (3, 14):\n        @overload\n        @classmethod\n        def open(\n            cls,\n            name: StrOrBytesPath | None,\n            mode: Literal[\"r:zst\"],\n            fileobj: _Fileobj | None = None,\n            bufsize: int = 10240,\n            *,\n            format: int | None = ...,\n            tarinfo: type[TarInfo] | None = ...,\n            dereference: bool | None = ...,\n            ignore_zeros: bool | None = ...,\n            encoding: str | None = ...,\n            errors: str = ...,\n            pax_headers: Mapping[str, str] | None = ...,\n            debug: int | None = ...,\n            errorlevel: int | None = ...,\n            level: None = None,\n            options: Mapping[int, int] | None = None,\n            zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n        ) -> Self: ...\n\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | None,\n        mode: Literal[\"x\", \"x:\", \"a\", \"a:\", \"w\", \"w:\", \"w:tar\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | None = None,\n        *,\n        mode: Literal[\"x\", \"x:\", \"a\", \"a:\", \"w\", \"w:\", \"w:tar\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | None,\n        mode: Literal[\"x:gz\", \"x:bz2\", \"w:gz\", \"w:bz2\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n        compresslevel: int = 9,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | None = None,\n        *,\n        mode: Literal[\"x:gz\", \"x:bz2\", \"w:gz\", \"w:bz2\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n        compresslevel: int = 9,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | None,\n        mode: Literal[\"x:xz\", \"w:xz\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n        preset: Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | None = None,\n        *,\n        mode: Literal[\"x:xz\", \"w:xz\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n        preset: Literal[0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | None = ...,\n    ) -> Self: ...\n    if sys.version_info >= (3, 14):\n        @overload\n        @classmethod\n        def open(\n            cls,\n            name: StrOrBytesPath | None,\n            mode: Literal[\"x:zst\", \"w:zst\"],\n            fileobj: _Fileobj | None = None,\n            bufsize: int = 10240,\n            *,\n            format: int | None = ...,\n            tarinfo: type[TarInfo] | None = ...,\n            dereference: bool | None = ...,\n            ignore_zeros: bool | None = ...,\n            encoding: str | None = ...,\n            errors: str = ...,\n            pax_headers: Mapping[str, str] | None = ...,\n            debug: int | None = ...,\n            errorlevel: int | None = ...,\n            options: Mapping[int, int] | None = None,\n            zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n        ) -> Self: ...\n        @overload\n        @classmethod\n        def open(\n            cls,\n            name: StrOrBytesPath | None = None,\n            *,\n            mode: Literal[\"x:zst\", \"w:zst\"],\n            fileobj: _Fileobj | None = None,\n            bufsize: int = 10240,\n            format: int | None = ...,\n            tarinfo: type[TarInfo] | None = ...,\n            dereference: bool | None = ...,\n            ignore_zeros: bool | None = ...,\n            encoding: str | None = ...,\n            errors: str = ...,\n            pax_headers: Mapping[str, str] | None = ...,\n            debug: int | None = ...,\n            errorlevel: int | None = ...,\n            options: Mapping[int, int] | None = None,\n            zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n        ) -> Self: ...\n\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | ReadableBuffer | None,\n        mode: Literal[\"r|*\", \"r|\", \"r|gz\", \"r|bz2\", \"r|xz\", \"r|zst\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | ReadableBuffer | None = None,\n        *,\n        mode: Literal[\"r|*\", \"r|\", \"r|gz\", \"r|bz2\", \"r|xz\", \"r|zst\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | WriteableBuffer | None,\n        mode: Literal[\"w|\", \"w|xz\", \"w|zst\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | WriteableBuffer | None = None,\n        *,\n        mode: Literal[\"w|\", \"w|xz\", \"w|zst\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | WriteableBuffer | None,\n        mode: Literal[\"w|gz\", \"w|bz2\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n        compresslevel: int = 9,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def open(\n        cls,\n        name: StrOrBytesPath | WriteableBuffer | None = None,\n        *,\n        mode: Literal[\"w|gz\", \"w|bz2\"],\n        fileobj: _Fileobj | None = None,\n        bufsize: int = 10240,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        errors: str = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n        compresslevel: int = 9,\n    ) -> Self: ...\n    @classmethod\n    def taropen(\n        cls,\n        name: StrOrBytesPath | None,\n        mode: Literal[\"r\", \"a\", \"w\", \"x\"] = \"r\",\n        fileobj: _Fileobj | None = None,\n        *,\n        compresslevel: int = ...,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def gzopen(\n        cls,\n        name: StrOrBytesPath | None,\n        mode: Literal[\"r\"] = \"r\",\n        fileobj: _GzipReadableFileobj | None = None,\n        compresslevel: int = 9,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def gzopen(\n        cls,\n        name: StrOrBytesPath | None,\n        mode: Literal[\"w\", \"x\"],\n        fileobj: _GzipWritableFileobj | None = None,\n        compresslevel: int = 9,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def bz2open(\n        cls,\n        name: StrOrBytesPath | None,\n        mode: Literal[\"w\", \"x\"],\n        fileobj: _Bz2WritableFileobj | None = None,\n        compresslevel: int = 9,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @overload\n    @classmethod\n    def bz2open(\n        cls,\n        name: StrOrBytesPath | None,\n        mode: Literal[\"r\"] = \"r\",\n        fileobj: _Bz2ReadableFileobj | None = None,\n        compresslevel: int = 9,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    @classmethod\n    def xzopen(\n        cls,\n        name: StrOrBytesPath | None,\n        mode: Literal[\"r\", \"w\", \"x\"] = \"r\",\n        fileobj: IO[bytes] | None = None,\n        preset: int | None = None,\n        *,\n        format: int | None = ...,\n        tarinfo: type[TarInfo] | None = ...,\n        dereference: bool | None = ...,\n        ignore_zeros: bool | None = ...,\n        encoding: str | None = ...,\n        pax_headers: Mapping[str, str] | None = ...,\n        debug: int | None = ...,\n        errorlevel: int | None = ...,\n    ) -> Self: ...\n    if sys.version_info >= (3, 14):\n        @overload\n        @classmethod\n        def zstopen(\n            cls,\n            name: StrOrBytesPath | None,\n            mode: Literal[\"r\"] = \"r\",\n            fileobj: IO[bytes] | None = None,\n            level: None = None,\n            options: Mapping[int, int] | None = None,\n            zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n            *,\n            format: int | None = ...,\n            tarinfo: type[TarInfo] | None = ...,\n            dereference: bool | None = ...,\n            ignore_zeros: bool | None = ...,\n            encoding: str | None = ...,\n            pax_headers: Mapping[str, str] | None = ...,\n            debug: int | None = ...,\n            errorlevel: int | None = ...,\n        ) -> Self: ...\n        @overload\n        @classmethod\n        def zstopen(\n            cls,\n            name: StrOrBytesPath | None,\n            mode: Literal[\"w\", \"x\"],\n            fileobj: IO[bytes] | None = None,\n            level: int | None = None,\n            options: Mapping[int, int] | None = None,\n            zstd_dict: ZstdDict | tuple[ZstdDict, int] | None = None,\n            *,\n            format: int | None = ...,\n            tarinfo: type[TarInfo] | None = ...,\n            dereference: bool | None = ...,\n            ignore_zeros: bool | None = ...,\n            encoding: str | None = ...,\n            pax_headers: Mapping[str, str] | None = ...,\n            debug: int | None = ...,\n            errorlevel: int | None = ...,\n        ) -> Self: ...\n\n    def getmember(self, name: str) -> TarInfo: ...\n    def getmembers(self) -> _list[TarInfo]: ...\n    def getnames(self) -> _list[str]: ...\n    def list(self, verbose: bool = True, *, members: Iterable[TarInfo] | None = None) -> None: ...\n    def next(self) -> TarInfo | None: ...\n    # Calling this method without `filter` is deprecated, but it may be set either on the class or in an\n    # individual call, so we can't mark it as @deprecated here.\n    def extractall(\n        self,\n        path: StrOrBytesPath = \".\",\n        members: Iterable[TarInfo] | None = None,\n        *,\n        numeric_owner: bool = False,\n        filter: _TarfileFilter | None = None,\n    ) -> None: ...\n    # Same situation as for `extractall`.\n    def extract(\n        self,\n        member: str | TarInfo,\n        path: StrOrBytesPath = \"\",\n        set_attrs: bool = True,\n        *,\n        numeric_owner: bool = False,\n        filter: _TarfileFilter | None = None,\n    ) -> None: ...\n    def _extract_member(\n        self,\n        tarinfo: TarInfo,\n        targetpath: str,\n        set_attrs: bool = True,\n        numeric_owner: bool = False,\n        *,\n        filter_function: _FilterFunction | None = None,\n        extraction_root: str | None = None,\n    ) -> None: ...  # undocumented\n    def extractfile(self, member: str | TarInfo) -> IO[bytes] | None: ...\n    def makedir(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ...  # undocumented\n    def makefile(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ...  # undocumented\n    def makeunknown(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ...  # undocumented\n    def makefifo(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ...  # undocumented\n    def makedev(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ...  # undocumented\n    def makelink(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ...  # undocumented\n    def makelink_with_filter(\n        self, tarinfo: TarInfo, targetpath: StrOrBytesPath, filter_function: _FilterFunction, extraction_root: str\n    ) -> None: ...  # undocumented\n    def chown(self, tarinfo: TarInfo, targetpath: StrOrBytesPath, numeric_owner: bool) -> None: ...  # undocumented\n    def chmod(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ...  # undocumented\n    def utime(self, tarinfo: TarInfo, targetpath: StrOrBytesPath) -> None: ...  # undocumented\n    def add(\n        self,\n        name: StrPath,\n        arcname: StrPath | None = None,\n        recursive: bool = True,\n        *,\n        filter: Callable[[TarInfo], TarInfo | None] | None = None,\n    ) -> None: ...\n    def addfile(self, tarinfo: TarInfo, fileobj: SupportsRead[bytes] | None = None) -> None: ...\n    def gettarinfo(\n        self, name: StrOrBytesPath | None = None, arcname: str | None = None, fileobj: IO[bytes] | None = None\n    ) -> TarInfo: ...\n    def close(self) -> None: ...\n\nopen = TarFile.open\n\ndef is_tarfile(name: StrOrBytesPath | IO[bytes]) -> bool: ...\n\nclass TarError(Exception): ...\nclass ReadError(TarError): ...\nclass CompressionError(TarError): ...\nclass StreamError(TarError): ...\nclass ExtractError(TarError): ...\nclass HeaderError(TarError): ...\n\nclass FilterError(TarError):\n    # This attribute is only set directly on the subclasses, but the documentation guarantees\n    # that it is always present on FilterError.\n    tarinfo: TarInfo\n\nclass AbsolutePathError(FilterError):\n    def __init__(self, tarinfo: TarInfo) -> None: ...\n\nclass OutsideDestinationError(FilterError):\n    def __init__(self, tarinfo: TarInfo, path: str) -> None: ...\n\nclass SpecialFileError(FilterError):\n    def __init__(self, tarinfo: TarInfo) -> None: ...\n\nclass AbsoluteLinkError(FilterError):\n    def __init__(self, tarinfo: TarInfo) -> None: ...\n\nclass LinkOutsideDestinationError(FilterError):\n    def __init__(self, tarinfo: TarInfo, path: str) -> None: ...\n\nclass LinkFallbackError(FilterError):\n    def __init__(self, tarinfo: TarInfo, path: str) -> None: ...\n\ndef fully_trusted_filter(member: TarInfo, dest_path: str) -> TarInfo: ...\ndef tar_filter(member: TarInfo, dest_path: str) -> TarInfo: ...\ndef data_filter(member: TarInfo, dest_path: str) -> TarInfo: ...\n\nclass TarInfo:\n    __slots__ = (\n        \"name\",\n        \"mode\",\n        \"uid\",\n        \"gid\",\n        \"size\",\n        \"mtime\",\n        \"chksum\",\n        \"type\",\n        \"linkname\",\n        \"uname\",\n        \"gname\",\n        \"devmajor\",\n        \"devminor\",\n        \"offset\",\n        \"offset_data\",\n        \"pax_headers\",\n        \"sparse\",\n        \"_tarfile\",\n        \"_sparse_structs\",\n        \"_link_target\",\n    )\n    name: str\n    path: str\n    size: int\n    mtime: int | float\n    chksum: int\n    devmajor: int\n    devminor: int\n    offset: int\n    offset_data: int\n    sparse: bytes | None\n    mode: int\n    type: bytes  # usually one of the TYPE constants, but could be an arbitrary byte\n    linkname: str\n    uid: int\n    gid: int\n    uname: str\n    gname: str\n    pax_headers: Mapping[str, str]\n    def __init__(self, name: str = \"\") -> None: ...\n    if sys.version_info >= (3, 13):\n        @property\n        @deprecated(\"Deprecated since Python 3.13; will be removed in Python 3.16.\")\n        def tarfile(self) -> TarFile | None: ...\n        @tarfile.setter\n        @deprecated(\"Deprecated since Python 3.13; will be removed in Python 3.16.\")\n        def tarfile(self, tarfile: TarFile | None) -> None: ...\n    else:\n        tarfile: TarFile | None\n\n    @classmethod\n    def frombuf(cls, buf: bytes | bytearray, encoding: str, errors: str) -> Self: ...\n    @classmethod\n    def fromtarfile(cls, tarfile: TarFile) -> Self: ...\n    @property\n    def linkpath(self) -> str: ...\n    @linkpath.setter\n    def linkpath(self, linkname: str) -> None: ...\n    def replace(\n        self,\n        *,\n        name: str = ...,\n        mtime: float = ...,\n        mode: int = ...,\n        linkname: str = ...,\n        uid: int = ...,\n        gid: int = ...,\n        uname: str = ...,\n        gname: str = ...,\n        deep: bool = True,\n    ) -> Self: ...\n    def get_info(self) -> Mapping[str, str | int | bytes | Mapping[str, str]]: ...\n    def tobuf(self, format: _TarFormat | None = 2, encoding: str | None = \"utf-8\", errors: str = \"surrogateescape\") -> bytes: ...\n    def create_ustar_header(\n        self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str, errors: str\n    ) -> bytes: ...\n    def create_gnu_header(\n        self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str, errors: str\n    ) -> bytes: ...\n    def create_pax_header(self, info: Mapping[str, str | int | bytes | Mapping[str, str]], encoding: str) -> bytes: ...\n    @classmethod\n    def create_pax_global_header(cls, pax_headers: Mapping[str, str]) -> bytes: ...\n    def isfile(self) -> bool: ...\n    def isreg(self) -> bool: ...\n    def issparse(self) -> bool: ...\n    def isdir(self) -> bool: ...\n    def issym(self) -> bool: ...\n    def islnk(self) -> bool: ...\n    def ischr(self) -> bool: ...\n    def isblk(self) -> bool: ...\n    def isfifo(self) -> bool: ...\n    def isdev(self) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/telnetlib.pyi",
    "content": "import socket\nfrom collections.abc import Callable, MutableSequence, Sequence\nfrom re import Match, Pattern\nfrom types import TracebackType\nfrom typing import Any, Final\nfrom typing_extensions import Self\n\n__all__ = [\"Telnet\"]\n\nDEBUGLEVEL: Final = 0\nTELNET_PORT: Final = 23\n\nIAC: Final = b\"\\xff\"\nDONT: Final = b\"\\xfe\"\nDO: Final = b\"\\xfd\"\nWONT: Final = b\"\\xfc\"\nWILL: Final = b\"\\xfb\"\ntheNULL: Final = b\"\\x00\"\n\nSE: Final = b\"\\xf0\"\nNOP: Final = b\"\\xf1\"\nDM: Final = b\"\\xf2\"\nBRK: Final = b\"\\xf3\"\nIP: Final = b\"\\xf4\"\nAO: Final = b\"\\xf5\"\nAYT: Final = b\"\\xf6\"\nEC: Final = b\"\\xf7\"\nEL: Final = b\"\\xf8\"\nGA: Final = b\"\\xf9\"\nSB: Final = b\"\\xfa\"\n\nBINARY: Final = b\"\\x00\"\nECHO: Final = b\"\\x01\"\nRCP: Final = b\"\\x02\"\nSGA: Final = b\"\\x03\"\nNAMS: Final = b\"\\x04\"\nSTATUS: Final = b\"\\x05\"\nTM: Final = b\"\\x06\"\nRCTE: Final = b\"\\x07\"\nNAOL: Final = b\"\\x08\"\nNAOP: Final = b\"\\t\"\nNAOCRD: Final = b\"\\n\"\nNAOHTS: Final = b\"\\x0b\"\nNAOHTD: Final = b\"\\x0c\"\nNAOFFD: Final = b\"\\r\"\nNAOVTS: Final = b\"\\x0e\"\nNAOVTD: Final = b\"\\x0f\"\nNAOLFD: Final = b\"\\x10\"\nXASCII: Final = b\"\\x11\"\nLOGOUT: Final = b\"\\x12\"\nBM: Final = b\"\\x13\"\nDET: Final = b\"\\x14\"\nSUPDUP: Final = b\"\\x15\"\nSUPDUPOUTPUT: Final = b\"\\x16\"\nSNDLOC: Final = b\"\\x17\"\nTTYPE: Final = b\"\\x18\"\nEOR: Final = b\"\\x19\"\nTUID: Final = b\"\\x1a\"\nOUTMRK: Final = b\"\\x1b\"\nTTYLOC: Final = b\"\\x1c\"\nVT3270REGIME: Final = b\"\\x1d\"\nX3PAD: Final = b\"\\x1e\"\nNAWS: Final = b\"\\x1f\"\nTSPEED: Final = b\" \"\nLFLOW: Final = b\"!\"\nLINEMODE: Final = b'\"'\nXDISPLOC: Final = b\"#\"\nOLD_ENVIRON: Final = b\"$\"\nAUTHENTICATION: Final = b\"%\"\nENCRYPT: Final = b\"&\"\nNEW_ENVIRON: Final = b\"'\"\n\nTN3270E: Final = b\"(\"\nXAUTH: Final = b\")\"\nCHARSET: Final = b\"*\"\nRSP: Final = b\"+\"\nCOM_PORT_OPTION: Final = b\",\"\nSUPPRESS_LOCAL_ECHO: Final = b\"-\"\nTLS: Final = b\".\"\nKERMIT: Final = b\"/\"\nSEND_URL: Final = b\"0\"\nFORWARD_X: Final = b\"1\"\nPRAGMA_LOGON: Final = b\"\\x8a\"\nSSPI_LOGON: Final = b\"\\x8b\"\nPRAGMA_HEARTBEAT: Final = b\"\\x8c\"\nEXOPL: Final = b\"\\xff\"\nNOOPT: Final = b\"\\x00\"\n\nclass Telnet:\n    host: str | None  # undocumented\n    sock: socket.socket | None  # undocumented\n    def __init__(self, host: str | None = None, port: int = 0, timeout: float = ...) -> None: ...\n    def open(self, host: str, port: int = 0, timeout: float = ...) -> None: ...\n    def msg(self, msg: str, *args: Any) -> None: ...\n    def set_debuglevel(self, debuglevel: int) -> None: ...\n    def close(self) -> None: ...\n    def get_socket(self) -> socket.socket: ...\n    def fileno(self) -> int: ...\n    def write(self, buffer: bytes) -> None: ...\n    def read_until(self, match: bytes, timeout: float | None = None) -> bytes: ...\n    def read_all(self) -> bytes: ...\n    def read_some(self) -> bytes: ...\n    def read_very_eager(self) -> bytes: ...\n    def read_eager(self) -> bytes: ...\n    def read_lazy(self) -> bytes: ...\n    def read_very_lazy(self) -> bytes: ...\n    def read_sb_data(self) -> bytes: ...\n    def set_option_negotiation_callback(self, callback: Callable[[socket.socket, bytes, bytes], object] | None) -> None: ...\n    def process_rawq(self) -> None: ...\n    def rawq_getchar(self) -> bytes: ...\n    def fill_rawq(self) -> None: ...\n    def sock_avail(self) -> bool: ...\n    def interact(self) -> None: ...\n    def mt_interact(self) -> None: ...\n    def listener(self) -> None: ...\n    def expect(\n        self, list: MutableSequence[Pattern[bytes] | bytes] | Sequence[Pattern[bytes]], timeout: float | None = None\n    ) -> tuple[int, Match[bytes] | None, bytes]: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n    ) -> None: ...\n    def __del__(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tempfile.pyi",
    "content": "import io\nimport sys\nfrom _typeshed import (\n    BytesPath,\n    GenericPath,\n    OpenBinaryMode,\n    OpenBinaryModeReading,\n    OpenBinaryModeUpdating,\n    OpenBinaryModeWriting,\n    OpenTextMode,\n    ReadableBuffer,\n    StrPath,\n    WriteableBuffer,\n)\nfrom collections.abc import Iterable, Iterator\nfrom types import GenericAlias, TracebackType\nfrom typing import IO, Any, AnyStr, Final, Generic, Literal, overload\nfrom typing_extensions import Self, deprecated\n\n__all__ = [\n    \"NamedTemporaryFile\",\n    \"TemporaryFile\",\n    \"SpooledTemporaryFile\",\n    \"TemporaryDirectory\",\n    \"mkstemp\",\n    \"mkdtemp\",\n    \"mktemp\",\n    \"TMP_MAX\",\n    \"gettempprefix\",\n    \"tempdir\",\n    \"gettempdir\",\n    \"gettempprefixb\",\n    \"gettempdirb\",\n]\n\n# global variables\nTMP_MAX: Final[int]\ntempdir: str | None\ntemplate: str\n\nif sys.version_info >= (3, 12):\n    @overload\n    def NamedTemporaryFile(\n        mode: OpenTextMode,\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        delete: bool = True,\n        *,\n        errors: str | None = None,\n        delete_on_close: bool = True,\n    ) -> _TemporaryFileWrapper[str]: ...\n    @overload\n    def NamedTemporaryFile(\n        mode: OpenBinaryMode = \"w+b\",\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        delete: bool = True,\n        *,\n        errors: str | None = None,\n        delete_on_close: bool = True,\n    ) -> _TemporaryFileWrapper[bytes]: ...\n    @overload\n    def NamedTemporaryFile(\n        mode: str = \"w+b\",\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        delete: bool = True,\n        *,\n        errors: str | None = None,\n        delete_on_close: bool = True,\n    ) -> _TemporaryFileWrapper[Any]: ...\n\nelse:\n    @overload\n    def NamedTemporaryFile(\n        mode: OpenTextMode,\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        delete: bool = True,\n        *,\n        errors: str | None = None,\n    ) -> _TemporaryFileWrapper[str]: ...\n    @overload\n    def NamedTemporaryFile(\n        mode: OpenBinaryMode = \"w+b\",\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        delete: bool = True,\n        *,\n        errors: str | None = None,\n    ) -> _TemporaryFileWrapper[bytes]: ...\n    @overload\n    def NamedTemporaryFile(\n        mode: str = \"w+b\",\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        delete: bool = True,\n        *,\n        errors: str | None = None,\n    ) -> _TemporaryFileWrapper[Any]: ...\n\nif sys.platform == \"win32\":\n    TemporaryFile = NamedTemporaryFile\nelse:\n    # See the comments for builtins.open() for an explanation of the overloads.\n    @overload\n    def TemporaryFile(\n        mode: OpenTextMode,\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        *,\n        errors: str | None = None,\n    ) -> io.TextIOWrapper: ...\n    @overload\n    def TemporaryFile(\n        mode: OpenBinaryMode,\n        buffering: Literal[0],\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        *,\n        errors: str | None = None,\n    ) -> io.FileIO: ...\n    @overload\n    def TemporaryFile(\n        *,\n        buffering: Literal[0],\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        errors: str | None = None,\n    ) -> io.FileIO: ...\n    @overload\n    def TemporaryFile(\n        mode: OpenBinaryModeWriting,\n        buffering: Literal[-1, 1] = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        *,\n        errors: str | None = None,\n    ) -> io.BufferedWriter: ...\n    @overload\n    def TemporaryFile(\n        mode: OpenBinaryModeReading,\n        buffering: Literal[-1, 1] = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        *,\n        errors: str | None = None,\n    ) -> io.BufferedReader: ...\n    @overload\n    def TemporaryFile(\n        mode: OpenBinaryModeUpdating = \"w+b\",\n        buffering: Literal[-1, 1] = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        *,\n        errors: str | None = None,\n    ) -> io.BufferedRandom: ...\n    @overload\n    def TemporaryFile(\n        mode: str = \"w+b\",\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: AnyStr | None = None,\n        prefix: AnyStr | None = None,\n        dir: GenericPath[AnyStr] | None = None,\n        *,\n        errors: str | None = None,\n    ) -> IO[Any]: ...\n\nclass _TemporaryFileWrapper(IO[AnyStr]):\n    file: IO[AnyStr]  # io.TextIOWrapper, io.BufferedReader or io.BufferedWriter\n    name: str\n    delete: bool\n    if sys.version_info >= (3, 12):\n        def __init__(self, file: IO[AnyStr], name: str, delete: bool = True, delete_on_close: bool = True) -> None: ...\n    else:\n        def __init__(self, file: IO[AnyStr], name: str, delete: bool = True) -> None: ...\n\n    def __enter__(self) -> Self: ...\n    def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ...\n    def __getattr__(self, name: str) -> Any: ...\n    def close(self) -> None: ...\n    # These methods don't exist directly on this object, but\n    # are delegated to the underlying IO object through __getattr__.\n    # We need to add them here so that this class is concrete.\n    def __iter__(self) -> Iterator[AnyStr]: ...\n    # FIXME: __next__ doesn't actually exist on this class and should be removed:\n    #        see also https://github.com/python/typeshed/pull/5456#discussion_r633068648\n    # >>> import tempfile\n    # >>> ntf=tempfile.NamedTemporaryFile()\n    # >>> next(ntf)\n    # Traceback (most recent call last):\n    #   File \"<stdin>\", line 1, in <module>\n    # TypeError: '_TemporaryFileWrapper' object is not an iterator\n    def __next__(self) -> AnyStr: ...\n    def fileno(self) -> int: ...\n    def flush(self) -> None: ...\n    def isatty(self) -> bool: ...\n    def read(self, n: int = ...) -> AnyStr: ...\n    def readable(self) -> bool: ...\n    def readline(self, limit: int = ...) -> AnyStr: ...\n    def readlines(self, hint: int = ...) -> list[AnyStr]: ...\n    def seek(self, offset: int, whence: int = ...) -> int: ...\n    def seekable(self) -> bool: ...\n    def tell(self) -> int: ...\n    def truncate(self, size: int | None = ...) -> int: ...\n    def writable(self) -> bool: ...\n    @overload\n    def write(self: _TemporaryFileWrapper[str], s: str, /) -> int: ...\n    @overload\n    def write(self: _TemporaryFileWrapper[bytes], s: ReadableBuffer, /) -> int: ...\n    @overload\n    def write(self, s: AnyStr, /) -> int: ...\n    @overload\n    def writelines(self: _TemporaryFileWrapper[str], lines: Iterable[str]) -> None: ...\n    @overload\n    def writelines(self: _TemporaryFileWrapper[bytes], lines: Iterable[ReadableBuffer]) -> None: ...\n    @overload\n    def writelines(self, lines: Iterable[AnyStr]) -> None: ...\n    @property\n    def closed(self) -> bool: ...\n\nif sys.version_info >= (3, 11):\n    _SpooledTemporaryFileBase = io.IOBase\nelse:\n    _SpooledTemporaryFileBase = object\n\n# It does not actually derive from IO[AnyStr], but it does mostly behave\n# like one.\nclass SpooledTemporaryFile(IO[AnyStr], _SpooledTemporaryFileBase):\n    _file: IO[AnyStr]\n    @property\n    def encoding(self) -> str: ...  # undocumented\n    @property\n    def newlines(self) -> str | tuple[str, ...] | None: ...  # undocumented\n    # bytes needs to go first, as default mode is to open as bytes\n    @overload\n    def __init__(\n        self: SpooledTemporaryFile[bytes],\n        max_size: int = 0,\n        mode: OpenBinaryMode = \"w+b\",\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: str | None = None,\n        prefix: str | None = None,\n        dir: str | None = None,\n        *,\n        errors: str | None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self: SpooledTemporaryFile[str],\n        max_size: int,\n        mode: OpenTextMode,\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: str | None = None,\n        prefix: str | None = None,\n        dir: str | None = None,\n        *,\n        errors: str | None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self: SpooledTemporaryFile[str],\n        max_size: int = 0,\n        *,\n        mode: OpenTextMode,\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: str | None = None,\n        prefix: str | None = None,\n        dir: str | None = None,\n        errors: str | None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        max_size: int,\n        mode: str,\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: str | None = None,\n        prefix: str | None = None,\n        dir: str | None = None,\n        *,\n        errors: str | None = None,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        max_size: int = 0,\n        *,\n        mode: str,\n        buffering: int = -1,\n        encoding: str | None = None,\n        newline: str | None = None,\n        suffix: str | None = None,\n        prefix: str | None = None,\n        dir: str | None = None,\n        errors: str | None = None,\n    ) -> None: ...\n    @property\n    def errors(self) -> str | None: ...\n    def rollover(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ...\n    # These methods are copied from the abstract methods of IO, because\n    # SpooledTemporaryFile implements IO.\n    # See also https://github.com/python/typeshed/pull/2452#issuecomment-420657918.\n    def close(self) -> None: ...\n    def fileno(self) -> int: ...\n    def flush(self) -> None: ...\n    def isatty(self) -> bool: ...\n    if sys.version_info >= (3, 11):\n        # These three work only if the SpooledTemporaryFile is opened in binary mode,\n        # because the underlying object in text mode does not have these methods.\n        def read1(self, size: int = ..., /) -> AnyStr: ...\n        def readinto(self, b: WriteableBuffer) -> int: ...\n        def readinto1(self, b: WriteableBuffer) -> int: ...\n        def detach(self) -> io.RawIOBase: ...\n\n    def read(self, n: int = ..., /) -> AnyStr: ...\n    def readline(self, limit: int | None = ..., /) -> AnyStr: ...  # type: ignore[override]\n    def readlines(self, hint: int = ..., /) -> list[AnyStr]: ...  # type: ignore[override]\n    def seek(self, offset: int, whence: int = ...) -> int: ...\n    def tell(self) -> int: ...\n    if sys.version_info >= (3, 11):\n        def truncate(self, size: int | None = None) -> int: ...\n    else:\n        def truncate(self, size: int | None = None) -> None: ...  # type: ignore[override]\n\n    @overload\n    def write(self: SpooledTemporaryFile[str], s: str) -> int: ...\n    @overload\n    def write(self: SpooledTemporaryFile[bytes], s: ReadableBuffer) -> int: ...\n    @overload\n    def write(self, s: AnyStr) -> int: ...\n    @overload  # type: ignore[override]\n    def writelines(self: SpooledTemporaryFile[str], iterable: Iterable[str]) -> None: ...\n    @overload\n    def writelines(self: SpooledTemporaryFile[bytes], iterable: Iterable[ReadableBuffer]) -> None: ...\n    @overload\n    def writelines(self, iterable: Iterable[AnyStr]) -> None: ...\n    def __iter__(self) -> Iterator[AnyStr]: ...  # type: ignore[override]\n    # These exist at runtime only on 3.11+.\n    def readable(self) -> bool: ...\n    def seekable(self) -> bool: ...\n    def writable(self) -> bool: ...\n    def __next__(self) -> AnyStr: ...  # type: ignore[override]\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass TemporaryDirectory(Generic[AnyStr]):\n    name: AnyStr\n    if sys.version_info >= (3, 12):\n        @overload\n        def __init__(\n            self: TemporaryDirectory[str],\n            suffix: str | None = None,\n            prefix: str | None = None,\n            dir: StrPath | None = None,\n            ignore_cleanup_errors: bool = False,\n            *,\n            delete: bool = True,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: TemporaryDirectory[bytes],\n            suffix: bytes | None = None,\n            prefix: bytes | None = None,\n            dir: BytesPath | None = None,\n            ignore_cleanup_errors: bool = False,\n            *,\n            delete: bool = True,\n        ) -> None: ...\n    elif sys.version_info >= (3, 10):\n        @overload\n        def __init__(\n            self: TemporaryDirectory[str],\n            suffix: str | None = None,\n            prefix: str | None = None,\n            dir: StrPath | None = None,\n            ignore_cleanup_errors: bool = False,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: TemporaryDirectory[bytes],\n            suffix: bytes | None = None,\n            prefix: bytes | None = None,\n            dir: BytesPath | None = None,\n            ignore_cleanup_errors: bool = False,\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self: TemporaryDirectory[str], suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: TemporaryDirectory[bytes],\n            suffix: bytes | None = None,\n            prefix: bytes | None = None,\n            dir: BytesPath | None = None,\n        ) -> None: ...\n\n    def cleanup(self) -> None: ...\n    def __enter__(self) -> AnyStr: ...\n    def __exit__(self, exc: type[BaseException] | None, value: BaseException | None, tb: TracebackType | None) -> None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n# The overloads overlap, but they should still work fine.\n@overload\ndef mkstemp(\n    suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None, text: bool = False\n) -> tuple[int, str]: ...\n@overload\ndef mkstemp(\n    suffix: bytes | None = None, prefix: bytes | None = None, dir: BytesPath | None = None, text: bool = False\n) -> tuple[int, bytes]: ...\n\n# The overloads overlap, but they should still work fine.\n@overload\ndef mkdtemp(suffix: str | None = None, prefix: str | None = None, dir: StrPath | None = None) -> str: ...\n@overload\ndef mkdtemp(suffix: bytes | None = None, prefix: bytes | None = None, dir: BytesPath | None = None) -> bytes: ...\n@deprecated(\"Deprecated since Python 2.3. Use `mkstemp()` or `NamedTemporaryFile(delete=False)` instead.\")\ndef mktemp(suffix: str = \"\", prefix: str = \"tmp\", dir: StrPath | None = None) -> str: ...\ndef gettempdirb() -> bytes: ...\ndef gettempprefixb() -> bytes: ...\ndef gettempdir() -> str: ...\ndef gettempprefix() -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/termios.pyi",
    "content": "import sys\nfrom _typeshed import FileDescriptorLike\nfrom typing import Any, Final\nfrom typing_extensions import TypeAlias\n\n# Must be a list of length 7, containing 6 ints and a list of NCCS 1-character bytes or ints.\n_Attr: TypeAlias = list[int | list[bytes | int]] | list[int | list[bytes]] | list[int | list[int]]\n# Same as _Attr for return types; we use Any to avoid a union.\n_AttrReturn: TypeAlias = list[Any]\n\nif sys.platform != \"win32\":\n    # Values depends on the platform\n    B0: Final[int]\n    B110: Final[int]\n    B115200: Final[int]\n    B1200: Final[int]\n    B134: Final[int]\n    B150: Final[int]\n    B1800: Final[int]\n    B19200: Final[int]\n    B200: Final[int]\n    B230400: Final[int]\n    B2400: Final[int]\n    B300: Final[int]\n    B38400: Final[int]\n    B4800: Final[int]\n    B50: Final[int]\n    B57600: Final[int]\n    B600: Final[int]\n    B75: Final[int]\n    B9600: Final[int]\n    BRKINT: Final[int]\n    BS0: Final[int]\n    BS1: Final[int]\n    BSDLY: Final[int]\n    CDSUSP: Final[int]\n    CEOF: Final[int]\n    CEOL: Final[int]\n    CEOT: Final[int]\n    CERASE: Final[int]\n    CFLUSH: Final[int]\n    CINTR: Final[int]\n    CKILL: Final[int]\n    CLNEXT: Final[int]\n    CLOCAL: Final[int]\n    CQUIT: Final[int]\n    CR0: Final[int]\n    CR1: Final[int]\n    CR2: Final[int]\n    CR3: Final[int]\n    CRDLY: Final[int]\n    CREAD: Final[int]\n    CRPRNT: Final[int]\n    CRTSCTS: Final[int]\n    CS5: Final[int]\n    CS6: Final[int]\n    CS7: Final[int]\n    CS8: Final[int]\n    CSIZE: Final[int]\n    CSTART: Final[int]\n    CSTOP: Final[int]\n    CSTOPB: Final[int]\n    CSUSP: Final[int]\n    CWERASE: Final[int]\n    ECHO: Final[int]\n    ECHOCTL: Final[int]\n    ECHOE: Final[int]\n    ECHOK: Final[int]\n    ECHOKE: Final[int]\n    ECHONL: Final[int]\n    ECHOPRT: Final[int]\n    EXTA: Final[int]\n    EXTB: Final[int]\n    FF0: Final[int]\n    FF1: Final[int]\n    FFDLY: Final[int]\n    FIOASYNC: Final[int]\n    FIOCLEX: Final[int]\n    FIONBIO: Final[int]\n    FIONCLEX: Final[int]\n    FIONREAD: Final[int]\n    FLUSHO: Final[int]\n    HUPCL: Final[int]\n    ICANON: Final[int]\n    ICRNL: Final[int]\n    IEXTEN: Final[int]\n    IGNBRK: Final[int]\n    IGNCR: Final[int]\n    IGNPAR: Final[int]\n    IMAXBEL: Final[int]\n    INLCR: Final[int]\n    INPCK: Final[int]\n    ISIG: Final[int]\n    ISTRIP: Final[int]\n    IXANY: Final[int]\n    IXOFF: Final[int]\n    IXON: Final[int]\n    NCCS: Final[int]\n    NL0: Final[int]\n    NL1: Final[int]\n    NLDLY: Final[int]\n    NOFLSH: Final[int]\n    OCRNL: Final[int]\n    OFDEL: Final[int]\n    OFILL: Final[int]\n    ONLCR: Final[int]\n    ONLRET: Final[int]\n    ONOCR: Final[int]\n    OPOST: Final[int]\n    PARENB: Final[int]\n    PARMRK: Final[int]\n    PARODD: Final[int]\n    PENDIN: Final[int]\n    TAB0: Final[int]\n    TAB1: Final[int]\n    TAB2: Final[int]\n    TAB3: Final[int]\n    TABDLY: Final[int]\n    TCIFLUSH: Final[int]\n    TCIOFF: Final[int]\n    TCIOFLUSH: Final[int]\n    TCION: Final[int]\n    TCOFLUSH: Final[int]\n    TCOOFF: Final[int]\n    TCOON: Final[int]\n    TCSADRAIN: Final[int]\n    TCSAFLUSH: Final[int]\n    TCSANOW: Final[int]\n    TIOCCONS: Final[int]\n    TIOCEXCL: Final[int]\n    TIOCGETD: Final[int]\n    TIOCGPGRP: Final[int]\n    TIOCGWINSZ: Final[int]\n    TIOCM_CAR: Final[int]\n    TIOCM_CD: Final[int]\n    TIOCM_CTS: Final[int]\n    TIOCM_DSR: Final[int]\n    TIOCM_DTR: Final[int]\n    TIOCM_LE: Final[int]\n    TIOCM_RI: Final[int]\n    TIOCM_RNG: Final[int]\n    TIOCM_RTS: Final[int]\n    TIOCM_SR: Final[int]\n    TIOCM_ST: Final[int]\n    TIOCMBIC: Final[int]\n    TIOCMBIS: Final[int]\n    TIOCMGET: Final[int]\n    TIOCMSET: Final[int]\n    TIOCNOTTY: Final[int]\n    TIOCNXCL: Final[int]\n    TIOCOUTQ: Final[int]\n    TIOCPKT_DATA: Final[int]\n    TIOCPKT_DOSTOP: Final[int]\n    TIOCPKT_FLUSHREAD: Final[int]\n    TIOCPKT_FLUSHWRITE: Final[int]\n    TIOCPKT_NOSTOP: Final[int]\n    TIOCPKT_START: Final[int]\n    TIOCPKT_STOP: Final[int]\n    TIOCPKT: Final[int]\n    TIOCSCTTY: Final[int]\n    TIOCSETD: Final[int]\n    TIOCSPGRP: Final[int]\n    TIOCSTI: Final[int]\n    TIOCSWINSZ: Final[int]\n    TOSTOP: Final[int]\n    VDISCARD: Final[int]\n    VEOF: Final[int]\n    VEOL: Final[int]\n    VEOL2: Final[int]\n    VERASE: Final[int]\n    VINTR: Final[int]\n    VKILL: Final[int]\n    VLNEXT: Final[int]\n    VMIN: Final[int]\n    VQUIT: Final[int]\n    VREPRINT: Final[int]\n    VSTART: Final[int]\n    VSTOP: Final[int]\n    VSUSP: Final[int]\n    VT0: Final[int]\n    VT1: Final[int]\n    VTDLY: Final[int]\n    VTIME: Final[int]\n    VWERASE: Final[int]\n\n    if sys.version_info >= (3, 13):\n        EXTPROC: Final[int]\n        IUTF8: Final[int]\n\n    if sys.platform == \"darwin\" and sys.version_info >= (3, 13):\n        ALTWERASE: Final[int]\n        B14400: Final[int]\n        B28800: Final[int]\n        B7200: Final[int]\n        B76800: Final[int]\n        CCAR_OFLOW: Final[int]\n        CCTS_OFLOW: Final[int]\n        CDSR_OFLOW: Final[int]\n        CDTR_IFLOW: Final[int]\n        CIGNORE: Final[int]\n        CRTS_IFLOW: Final[int]\n        MDMBUF: Final[int]\n        NL2: Final[int]\n        NL3: Final[int]\n        NOKERNINFO: Final[int]\n        ONOEOT: Final[int]\n        OXTABS: Final[int]\n        VDSUSP: Final[int]\n        VSTATUS: Final[int]\n\n    if sys.platform == \"darwin\" and sys.version_info >= (3, 11):\n        TIOCGSIZE: Final[int]\n        TIOCSSIZE: Final[int]\n\n    if sys.platform == \"linux\":\n        B1152000: Final[int]\n        B576000: Final[int]\n        CBAUD: Final[int]\n        CBAUDEX: Final[int]\n        CIBAUD: Final[int]\n        IOCSIZE_MASK: Final[int]\n        IOCSIZE_SHIFT: Final[int]\n        IUCLC: Final[int]\n        N_MOUSE: Final[int]\n        N_PPP: Final[int]\n        N_SLIP: Final[int]\n        N_STRIP: Final[int]\n        N_TTY: Final[int]\n        NCC: Final[int]\n        OLCUC: Final[int]\n        TCFLSH: Final[int]\n        TCGETA: Final[int]\n        TCGETS: Final[int]\n        TCSBRK: Final[int]\n        TCSBRKP: Final[int]\n        TCSETA: Final[int]\n        TCSETAF: Final[int]\n        TCSETAW: Final[int]\n        TCSETS: Final[int]\n        TCSETSF: Final[int]\n        TCSETSW: Final[int]\n        TCXONC: Final[int]\n        TIOCGICOUNT: Final[int]\n        TIOCGLCKTRMIOS: Final[int]\n        TIOCGSERIAL: Final[int]\n        TIOCGSOFTCAR: Final[int]\n        TIOCINQ: Final[int]\n        TIOCLINUX: Final[int]\n        TIOCMIWAIT: Final[int]\n        TIOCTTYGSTRUCT: Final[int]\n        TIOCSER_TEMT: Final[int]\n        TIOCSERCONFIG: Final[int]\n        TIOCSERGETLSR: Final[int]\n        TIOCSERGETMULTI: Final[int]\n        TIOCSERGSTRUCT: Final[int]\n        TIOCSERGWILD: Final[int]\n        TIOCSERSETMULTI: Final[int]\n        TIOCSERSWILD: Final[int]\n        TIOCSLCKTRMIOS: Final[int]\n        TIOCSSERIAL: Final[int]\n        TIOCSSOFTCAR: Final[int]\n        VSWTC: Final[int]\n        VSWTCH: Final[int]\n        XCASE: Final[int]\n        XTABS: Final[int]\n\n    if sys.platform != \"darwin\":\n        B1000000: Final[int]\n        B1500000: Final[int]\n        B2000000: Final[int]\n        B2500000: Final[int]\n        B3000000: Final[int]\n        B3500000: Final[int]\n        B4000000: Final[int]\n        B460800: Final[int]\n        B500000: Final[int]\n        B921600: Final[int]\n\n    if sys.platform != \"linux\":\n        TCSASOFT: Final[int]\n\n    if sys.platform != \"darwin\" and sys.platform != \"linux\":\n        # not available on FreeBSD either.\n        CDEL: Final[int]\n        CEOL2: Final[int]\n        CESC: Final[int]\n        CNUL: Final[int]\n        COMMON: Final[int]\n        CSWTCH: Final[int]\n        IBSHIFT: Final[int]\n        INIT_C_CC: Final[int]\n        NSWTCH: Final[int]\n\n    def tcgetattr(fd: FileDescriptorLike, /) -> _AttrReturn: ...\n    def tcsetattr(fd: FileDescriptorLike, when: int, attributes: _Attr, /) -> None: ...\n    def tcsendbreak(fd: FileDescriptorLike, duration: int, /) -> None: ...\n    def tcdrain(fd: FileDescriptorLike, /) -> None: ...\n    def tcflush(fd: FileDescriptorLike, queue: int, /) -> None: ...\n    def tcflow(fd: FileDescriptorLike, action: int, /) -> None: ...\n    if sys.version_info >= (3, 11):\n        def tcgetwinsize(fd: FileDescriptorLike, /) -> tuple[int, int]: ...\n        def tcsetwinsize(fd: FileDescriptorLike, winsize: tuple[int, int], /) -> None: ...\n\n    class error(Exception): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/textwrap.pyi",
    "content": "from collections.abc import Callable\nfrom re import Pattern\n\n__all__ = [\"TextWrapper\", \"wrap\", \"fill\", \"dedent\", \"indent\", \"shorten\"]\n\nclass TextWrapper:\n    width: int\n    initial_indent: str\n    subsequent_indent: str\n    expand_tabs: bool\n    replace_whitespace: bool\n    fix_sentence_endings: bool\n    drop_whitespace: bool\n    break_long_words: bool\n    break_on_hyphens: bool\n    tabsize: int\n    max_lines: int | None\n    placeholder: str\n\n    # Attributes not present in documentation\n    sentence_end_re: Pattern[str]\n    wordsep_re: Pattern[str]\n    wordsep_simple_re: Pattern[str]\n    whitespace_trans: str\n    unicode_whitespace_trans: dict[int, int]\n    uspace: int\n    x: str  # leaked loop variable\n    def __init__(\n        self,\n        width: int = 70,\n        initial_indent: str = \"\",\n        subsequent_indent: str = \"\",\n        expand_tabs: bool = True,\n        replace_whitespace: bool = True,\n        fix_sentence_endings: bool = False,\n        break_long_words: bool = True,\n        drop_whitespace: bool = True,\n        break_on_hyphens: bool = True,\n        tabsize: int = 8,\n        *,\n        max_lines: int | None = None,\n        placeholder: str = \" [...]\",\n    ) -> None: ...\n    # Private methods *are* part of the documented API for subclasses.\n    def _munge_whitespace(self, text: str) -> str: ...\n    def _split(self, text: str) -> list[str]: ...\n    def _fix_sentence_endings(self, chunks: list[str]) -> None: ...\n    def _handle_long_word(self, reversed_chunks: list[str], cur_line: list[str], cur_len: int, width: int) -> None: ...\n    def _wrap_chunks(self, chunks: list[str]) -> list[str]: ...\n    def _split_chunks(self, text: str) -> list[str]: ...\n    def wrap(self, text: str) -> list[str]: ...\n    def fill(self, text: str) -> str: ...\n\ndef wrap(\n    text: str,\n    width: int = 70,\n    *,\n    initial_indent: str = \"\",\n    subsequent_indent: str = \"\",\n    expand_tabs: bool = True,\n    tabsize: int = 8,\n    replace_whitespace: bool = True,\n    fix_sentence_endings: bool = False,\n    break_long_words: bool = True,\n    break_on_hyphens: bool = True,\n    drop_whitespace: bool = True,\n    max_lines: int | None = None,\n    placeholder: str = \" [...]\",\n) -> list[str]: ...\ndef fill(\n    text: str,\n    width: int = 70,\n    *,\n    initial_indent: str = \"\",\n    subsequent_indent: str = \"\",\n    expand_tabs: bool = True,\n    tabsize: int = 8,\n    replace_whitespace: bool = True,\n    fix_sentence_endings: bool = False,\n    break_long_words: bool = True,\n    break_on_hyphens: bool = True,\n    drop_whitespace: bool = True,\n    max_lines: int | None = None,\n    placeholder: str = \" [...]\",\n) -> str: ...\ndef shorten(\n    text: str,\n    width: int,\n    *,\n    initial_indent: str = \"\",\n    subsequent_indent: str = \"\",\n    expand_tabs: bool = True,\n    tabsize: int = 8,\n    replace_whitespace: bool = True,\n    fix_sentence_endings: bool = False,\n    break_long_words: bool = True,\n    break_on_hyphens: bool = True,\n    drop_whitespace: bool = True,\n    # Omit `max_lines: int = None`, it is forced to 1 here.\n    placeholder: str = \" [...]\",\n) -> str: ...\ndef dedent(text: str) -> str: ...\ndef indent(text: str, prefix: str, predicate: Callable[[str], bool] | None = None) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/this.pyi",
    "content": "s: str\nd: dict[str, str]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/threading.pyi",
    "content": "import _thread\nimport sys\nfrom _thread import _ExceptHookArgs, get_native_id as get_native_id\nfrom _typeshed import ProfileFunction, TraceFunction\nfrom collections.abc import Callable, Iterable, Mapping\nfrom contextvars import ContextVar\nfrom types import TracebackType\nfrom typing import Any, Final, TypeVar, final\nfrom typing_extensions import deprecated\n\n_T = TypeVar(\"_T\")\n\n__all__ = [\n    \"get_ident\",\n    \"active_count\",\n    \"Condition\",\n    \"current_thread\",\n    \"enumerate\",\n    \"main_thread\",\n    \"TIMEOUT_MAX\",\n    \"Event\",\n    \"Lock\",\n    \"RLock\",\n    \"Semaphore\",\n    \"BoundedSemaphore\",\n    \"Thread\",\n    \"Barrier\",\n    \"BrokenBarrierError\",\n    \"Timer\",\n    \"ThreadError\",\n    \"ExceptHookArgs\",\n    \"setprofile\",\n    \"settrace\",\n    \"local\",\n    \"stack_size\",\n    \"excepthook\",\n    \"get_native_id\",\n]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"getprofile\", \"gettrace\"]\n\nif sys.version_info >= (3, 12):\n    __all__ += [\"setprofile_all_threads\", \"settrace_all_threads\"]\n\n_profile_hook: ProfileFunction | None\n\ndef active_count() -> int: ...\n@deprecated(\"Deprecated since Python 3.10. Use `active_count()` instead.\")\ndef activeCount() -> int: ...\ndef current_thread() -> Thread: ...\n@deprecated(\"Deprecated since Python 3.10. Use `current_thread()` instead.\")\ndef currentThread() -> Thread: ...\ndef get_ident() -> int: ...\ndef enumerate() -> list[Thread]: ...\ndef main_thread() -> Thread: ...\ndef settrace(func: TraceFunction | None) -> None: ...\ndef setprofile(func: ProfileFunction | None) -> None: ...\n\nif sys.version_info >= (3, 12):\n    def setprofile_all_threads(func: ProfileFunction | None) -> None: ...\n    def settrace_all_threads(func: TraceFunction | None) -> None: ...\n\nif sys.version_info >= (3, 10):\n    def gettrace() -> TraceFunction | None: ...\n    def getprofile() -> ProfileFunction | None: ...\n\ndef stack_size(size: int = 0, /) -> int: ...\n\nTIMEOUT_MAX: Final[float]\n\nThreadError = _thread.error\nlocal = _thread._local\n\nclass Thread:\n    name: str\n    @property\n    def ident(self) -> int | None: ...\n    daemon: bool\n    if sys.version_info >= (3, 14):\n        def __init__(\n            self,\n            group: None = None,\n            target: Callable[..., object] | None = None,\n            name: str | None = None,\n            args: Iterable[Any] = (),\n            kwargs: Mapping[str, Any] | None = None,\n            *,\n            daemon: bool | None = None,\n            context: ContextVar[Any] | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            group: None = None,\n            target: Callable[..., object] | None = None,\n            name: str | None = None,\n            args: Iterable[Any] = (),\n            kwargs: Mapping[str, Any] | None = None,\n            *,\n            daemon: bool | None = None,\n        ) -> None: ...\n\n    def start(self) -> None: ...\n    def run(self) -> None: ...\n    def join(self, timeout: float | None = None) -> None: ...\n    @property\n    def native_id(self) -> int | None: ...  # only available on some platforms\n    def is_alive(self) -> bool: ...\n    @deprecated(\"Deprecated since Python 3.10. Read the `daemon` attribute instead.\")\n    def isDaemon(self) -> bool: ...\n    @deprecated(\"Deprecated since Python 3.10. Set the `daemon` attribute instead.\")\n    def setDaemon(self, daemonic: bool) -> None: ...\n    @deprecated(\"Deprecated since Python 3.10. Read the `name` attribute instead.\")\n    def getName(self) -> str: ...\n    @deprecated(\"Deprecated since Python 3.10. Set the `name` attribute instead.\")\n    def setName(self, name: str) -> None: ...\n\nclass _DummyThread(Thread):\n    def __init__(self) -> None: ...\n\n# This is actually the function _thread.allocate_lock for <= 3.12\nLock = _thread.LockType\n\n# Python implementation of RLock.\n@final\nclass _RLock:\n    _count: int\n    def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ...\n    def release(self) -> None: ...\n    __enter__ = acquire\n    def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def locked(self) -> bool: ...\n\nRLock = _thread.RLock  # Actually a function at runtime.\n\nclass Condition:\n    def __init__(self, lock: Lock | _RLock | RLock | None = None) -> None: ...\n    def __enter__(self) -> bool: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n    def acquire(self, blocking: bool = True, timeout: float = -1) -> bool: ...\n    def release(self) -> None: ...\n    if sys.version_info >= (3, 14):\n        def locked(self) -> bool: ...\n\n    def wait(self, timeout: float | None = None) -> bool: ...\n    def wait_for(self, predicate: Callable[[], _T], timeout: float | None = None) -> _T: ...\n    def notify(self, n: int = 1) -> None: ...\n    def notify_all(self) -> None: ...\n    @deprecated(\"Deprecated since Python 3.10. Use `notify_all()` instead.\")\n    def notifyAll(self) -> None: ...\n\nclass Semaphore:\n    _value: int\n    def __init__(self, value: int = 1) -> None: ...\n    def __exit__(self, t: type[BaseException] | None, v: BaseException | None, tb: TracebackType | None) -> None: ...\n    def acquire(self, blocking: bool = True, timeout: float | None = None) -> bool: ...\n    def __enter__(self, blocking: bool = True, timeout: float | None = None) -> bool: ...\n    def release(self, n: int = 1) -> None: ...\n\nclass BoundedSemaphore(Semaphore): ...\n\nclass Event:\n    def is_set(self) -> bool: ...\n    @deprecated(\"Deprecated since Python 3.10. Use `is_set()` instead.\")\n    def isSet(self) -> bool: ...\n    def set(self) -> None: ...\n    def clear(self) -> None: ...\n    def wait(self, timeout: float | None = None) -> bool: ...\n\nexcepthook: Callable[[_ExceptHookArgs], object]\nif sys.version_info >= (3, 10):\n    __excepthook__: Callable[[_ExceptHookArgs], object]\nExceptHookArgs = _ExceptHookArgs\n\nclass Timer(Thread):\n    args: Iterable[Any]  # undocumented\n    finished: Event  # undocumented\n    function: Callable[..., Any]  # undocumented\n    interval: float  # undocumented\n    kwargs: Mapping[str, Any]  # undocumented\n\n    def __init__(\n        self,\n        interval: float,\n        function: Callable[..., object],\n        args: Iterable[Any] | None = None,\n        kwargs: Mapping[str, Any] | None = None,\n    ) -> None: ...\n    def cancel(self) -> None: ...\n\nclass Barrier:\n    @property\n    def parties(self) -> int: ...\n    @property\n    def n_waiting(self) -> int: ...\n    @property\n    def broken(self) -> bool: ...\n    def __init__(self, parties: int, action: Callable[[], None] | None = None, timeout: float | None = None) -> None: ...\n    def wait(self, timeout: float | None = None) -> int: ...\n    def reset(self) -> None: ...\n    def abort(self) -> None: ...\n\nclass BrokenBarrierError(RuntimeError): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/time.pyi",
    "content": "import sys\nfrom _typeshed import structseq\nfrom typing import Any, Final, Literal, Protocol, SupportsFloat, SupportsIndex, Union, final, type_check_only\nfrom typing_extensions import TypeAlias\n\n_TimeTuple: TypeAlias = tuple[int, int, int, int, int, int, int, int, int]\n\nif sys.version_info >= (3, 15):\n    # anticipate on https://github.com/python/cpython/pull/139224\n    _SupportsFloatOrIndex: TypeAlias = Union[SupportsFloat, SupportsIndex]\nelse:\n    # before, time functions only accept (subclass of) float, *not* SupportsFloat\n    _SupportsFloatOrIndex: TypeAlias = Union[float, SupportsIndex]\n\naltzone: int\ndaylight: int\ntimezone: int\ntzname: tuple[str, str]\n\nif sys.platform == \"linux\":\n    CLOCK_BOOTTIME: Final[int]\nif sys.platform != \"linux\" and sys.platform != \"win32\" and sys.platform != \"darwin\":\n    CLOCK_PROF: Final[int]  # FreeBSD, NetBSD, OpenBSD\n    CLOCK_UPTIME: Final[int]  # FreeBSD, OpenBSD\n\nif sys.platform != \"win32\":\n    CLOCK_MONOTONIC: Final[int]\n    CLOCK_MONOTONIC_RAW: Final[int]\n    CLOCK_PROCESS_CPUTIME_ID: Final[int]\n    CLOCK_REALTIME: Final[int]\n    CLOCK_THREAD_CPUTIME_ID: Final[int]\n    if sys.platform != \"linux\" and sys.platform != \"darwin\":\n        CLOCK_HIGHRES: Final[int]  # Solaris only\n\nif sys.platform == \"darwin\":\n    CLOCK_UPTIME_RAW: Final[int]\n    if sys.version_info >= (3, 13):\n        CLOCK_UPTIME_RAW_APPROX: Final[int]\n        CLOCK_MONOTONIC_RAW_APPROX: Final[int]\n\nif sys.platform == \"linux\":\n    CLOCK_TAI: Final[int]\n\n# Constructor takes an iterable of any type, of length between 9 and 11 elements.\n# However, it always *behaves* like a tuple of 9 elements,\n# even if an iterable with length >9 is passed.\n# https://github.com/python/typeshed/pull/6560#discussion_r767162532\n@final\nclass struct_time(structseq[Any | int], _TimeTuple):\n    if sys.version_info >= (3, 10):\n        __match_args__: Final = (\"tm_year\", \"tm_mon\", \"tm_mday\", \"tm_hour\", \"tm_min\", \"tm_sec\", \"tm_wday\", \"tm_yday\", \"tm_isdst\")\n\n    @property\n    def tm_year(self) -> int: ...\n    @property\n    def tm_mon(self) -> int: ...\n    @property\n    def tm_mday(self) -> int: ...\n    @property\n    def tm_hour(self) -> int: ...\n    @property\n    def tm_min(self) -> int: ...\n    @property\n    def tm_sec(self) -> int: ...\n    @property\n    def tm_wday(self) -> int: ...\n    @property\n    def tm_yday(self) -> int: ...\n    @property\n    def tm_isdst(self) -> int: ...\n    # These final two properties only exist if a 10- or 11-item sequence was passed to the constructor.\n    @property\n    def tm_zone(self) -> str: ...\n    @property\n    def tm_gmtoff(self) -> int: ...\n\ndef asctime(time_tuple: _TimeTuple | struct_time = ..., /) -> str: ...\ndef ctime(seconds: _SupportsFloatOrIndex | None = None, /) -> str: ...\ndef gmtime(seconds: _SupportsFloatOrIndex | None = None, /) -> struct_time: ...\ndef localtime(seconds: _SupportsFloatOrIndex | None = None, /) -> struct_time: ...\ndef mktime(time_tuple: _TimeTuple | struct_time, /) -> float: ...\ndef sleep(seconds: _SupportsFloatOrIndex, /) -> None: ...\ndef strftime(format: str, time_tuple: _TimeTuple | struct_time = ..., /) -> str: ...\ndef strptime(data_string: str, format: str = \"%a %b %d %H:%M:%S %Y\", /) -> struct_time: ...\ndef time() -> float: ...\n\nif sys.platform != \"win32\":\n    def tzset() -> None: ...  # Unix only\n\n@type_check_only\nclass _ClockInfo(Protocol):\n    adjustable: bool\n    implementation: str\n    monotonic: bool\n    resolution: float\n\ndef get_clock_info(name: Literal[\"monotonic\", \"perf_counter\", \"process_time\", \"time\", \"thread_time\"], /) -> _ClockInfo: ...\ndef monotonic() -> float: ...\ndef perf_counter() -> float: ...\ndef process_time() -> float: ...\n\nif sys.platform != \"win32\":\n    def clock_getres(clk_id: int, /) -> float: ...  # Unix only\n    def clock_gettime(clk_id: int, /) -> float: ...  # Unix only\n    def clock_settime(clk_id: int, time: float, /) -> None: ...  # Unix only\n\nif sys.platform != \"win32\":\n    def clock_gettime_ns(clk_id: int, /) -> int: ...\n    def clock_settime_ns(clock_id: int, time: int, /) -> int: ...\n\nif sys.platform == \"linux\":\n    def pthread_getcpuclockid(thread_id: int, /) -> int: ...\n\ndef monotonic_ns() -> int: ...\ndef perf_counter_ns() -> int: ...\ndef process_time_ns() -> int: ...\ndef time_ns() -> int: ...\ndef thread_time() -> float: ...\ndef thread_time_ns() -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/timeit.pyi",
    "content": "import time\nfrom collections.abc import Callable, Sequence\nfrom typing import IO, Any\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"Timer\", \"timeit\", \"repeat\", \"default_timer\"]\n\n_Timer: TypeAlias = Callable[[], float]\n_Stmt: TypeAlias = str | Callable[[], object]\n\ndefault_timer: _Timer\n\nclass Timer:\n    def __init__(\n        self,\n        stmt: _Stmt = \"pass\",\n        setup: _Stmt = \"pass\",\n        timer: _Timer = time.perf_counter,\n        globals: dict[str, Any] | None = None,\n    ) -> None: ...\n    def print_exc(self, file: IO[str] | None = None) -> None: ...\n    def timeit(self, number: int = 1000000) -> float: ...\n    def repeat(self, repeat: int = 5, number: int = 1000000) -> list[float]: ...\n    def autorange(self, callback: Callable[[int, float], object] | None = None) -> tuple[int, float]: ...\n\ndef timeit(\n    stmt: _Stmt = \"pass\",\n    setup: _Stmt = \"pass\",\n    timer: _Timer = time.perf_counter,\n    number: int = 1000000,\n    globals: dict[str, Any] | None = None,\n) -> float: ...\ndef repeat(\n    stmt: _Stmt = \"pass\",\n    setup: _Stmt = \"pass\",\n    timer: _Timer = time.perf_counter,\n    repeat: int = 5,\n    number: int = 1000000,\n    globals: dict[str, Any] | None = None,\n) -> list[float]: ...\ndef main(args: Sequence[str] | None = None, *, _wrap_timer: Callable[[_Timer], _Timer] | None = None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/__init__.pyi",
    "content": "import _tkinter\nimport sys\nfrom _typeshed import FileDescriptorLike, Incomplete, MaybeNone, StrOrBytesPath\nfrom collections.abc import Callable, Iterable, Mapping, Sequence\nfrom tkinter.constants import *\nfrom tkinter.font import _FontDescription\nfrom types import GenericAlias, TracebackType\nfrom typing import Any, ClassVar, Final, Generic, Literal, NamedTuple, Protocol, TypedDict, TypeVar, overload, type_check_only\nfrom typing_extensions import TypeAlias, TypeVarTuple, Unpack, deprecated, disjoint_base\n\nif sys.version_info >= (3, 11):\n    from enum import StrEnum\nelse:\n    from enum import Enum\n\n__all__ = [\n    \"TclError\",\n    \"NO\",\n    \"FALSE\",\n    \"OFF\",\n    \"YES\",\n    \"TRUE\",\n    \"ON\",\n    \"N\",\n    \"S\",\n    \"W\",\n    \"E\",\n    \"NW\",\n    \"SW\",\n    \"NE\",\n    \"SE\",\n    \"NS\",\n    \"EW\",\n    \"NSEW\",\n    \"CENTER\",\n    \"NONE\",\n    \"X\",\n    \"Y\",\n    \"BOTH\",\n    \"LEFT\",\n    \"TOP\",\n    \"RIGHT\",\n    \"BOTTOM\",\n    \"RAISED\",\n    \"SUNKEN\",\n    \"FLAT\",\n    \"RIDGE\",\n    \"GROOVE\",\n    \"SOLID\",\n    \"HORIZONTAL\",\n    \"VERTICAL\",\n    \"NUMERIC\",\n    \"CHAR\",\n    \"WORD\",\n    \"BASELINE\",\n    \"INSIDE\",\n    \"OUTSIDE\",\n    \"SEL\",\n    \"SEL_FIRST\",\n    \"SEL_LAST\",\n    \"END\",\n    \"INSERT\",\n    \"CURRENT\",\n    \"ANCHOR\",\n    \"ALL\",\n    \"NORMAL\",\n    \"DISABLED\",\n    \"ACTIVE\",\n    \"HIDDEN\",\n    \"CASCADE\",\n    \"CHECKBUTTON\",\n    \"COMMAND\",\n    \"RADIOBUTTON\",\n    \"SEPARATOR\",\n    \"SINGLE\",\n    \"BROWSE\",\n    \"MULTIPLE\",\n    \"EXTENDED\",\n    \"DOTBOX\",\n    \"UNDERLINE\",\n    \"PIESLICE\",\n    \"CHORD\",\n    \"ARC\",\n    \"FIRST\",\n    \"LAST\",\n    \"BUTT\",\n    \"PROJECTING\",\n    \"ROUND\",\n    \"BEVEL\",\n    \"MITER\",\n    \"MOVETO\",\n    \"SCROLL\",\n    \"UNITS\",\n    \"PAGES\",\n    \"TkVersion\",\n    \"TclVersion\",\n    \"READABLE\",\n    \"WRITABLE\",\n    \"EXCEPTION\",\n    \"EventType\",\n    \"Event\",\n    \"NoDefaultRoot\",\n    \"Variable\",\n    \"StringVar\",\n    \"IntVar\",\n    \"DoubleVar\",\n    \"BooleanVar\",\n    \"mainloop\",\n    \"getint\",\n    \"getdouble\",\n    \"getboolean\",\n    \"Misc\",\n    \"CallWrapper\",\n    \"XView\",\n    \"YView\",\n    \"Wm\",\n    \"Tk\",\n    \"Tcl\",\n    \"Pack\",\n    \"Place\",\n    \"Grid\",\n    \"BaseWidget\",\n    \"Widget\",\n    \"Toplevel\",\n    \"Button\",\n    \"Canvas\",\n    \"Checkbutton\",\n    \"Entry\",\n    \"Frame\",\n    \"Label\",\n    \"Listbox\",\n    \"Menu\",\n    \"Menubutton\",\n    \"Message\",\n    \"Radiobutton\",\n    \"Scale\",\n    \"Scrollbar\",\n    \"Text\",\n    \"OptionMenu\",\n    \"Image\",\n    \"PhotoImage\",\n    \"BitmapImage\",\n    \"image_names\",\n    \"image_types\",\n    \"Spinbox\",\n    \"LabelFrame\",\n    \"PanedWindow\",\n]\n\n# Using anything from tkinter.font in this file means that 'import tkinter'\n# seems to also load tkinter.font. That's not how it actually works, but\n# unfortunately not much can be done about it. https://github.com/python/typeshed/pull/4346\n\nTclError = _tkinter.TclError\nwantobjects: int\nTkVersion: Final[float]\nTclVersion: Final[float]\nREADABLE: Final = _tkinter.READABLE\nWRITABLE: Final = _tkinter.WRITABLE\nEXCEPTION: Final = _tkinter.EXCEPTION\n\n# Quick guide for figuring out which widget class to choose:\n#   - Misc: any widget (don't use BaseWidget because Tk doesn't inherit from BaseWidget)\n#   - Widget: anything that is meant to be put into another widget with e.g. pack or grid\n#\n# Don't trust tkinter's docstrings, because they have been created by copy/pasting from\n# Tk's manual pages more than 10 years ago. Use the latest manual pages instead:\n#\n#    $ sudo apt install tk-doc tcl-doc\n#    $ man 3tk label        # tkinter.Label\n#    $ man 3tk ttk_label    # tkinter.ttk.Label\n#    $ man 3tcl after       # tkinter.Misc.after\n#\n# You can also read the manual pages online: https://www.tcl.tk/doc/\n\n# manual page: Tk_GetCursor\n_Cursor: TypeAlias = str | tuple[str] | tuple[str, str] | tuple[str, str, str] | tuple[str, str, str, str]\n\nif sys.version_info >= (3, 11):\n    @type_check_only\n    class _VersionInfoTypeBase(NamedTuple):\n        major: int\n        minor: int\n        micro: int\n        releaselevel: str\n        serial: int\n\n    if sys.version_info >= (3, 12):\n        class _VersionInfoType(_VersionInfoTypeBase): ...\n    else:\n        @disjoint_base\n        class _VersionInfoType(_VersionInfoTypeBase): ...\n\nif sys.version_info >= (3, 11):\n    class EventType(StrEnum):\n        Activate = \"36\"\n        ButtonPress = \"4\"\n        Button = ButtonPress\n        ButtonRelease = \"5\"\n        Circulate = \"26\"\n        CirculateRequest = \"27\"\n        ClientMessage = \"33\"\n        Colormap = \"32\"\n        Configure = \"22\"\n        ConfigureRequest = \"23\"\n        Create = \"16\"\n        Deactivate = \"37\"\n        Destroy = \"17\"\n        Enter = \"7\"\n        Expose = \"12\"\n        FocusIn = \"9\"\n        FocusOut = \"10\"\n        GraphicsExpose = \"13\"\n        Gravity = \"24\"\n        KeyPress = \"2\"\n        Key = \"2\"\n        KeyRelease = \"3\"\n        Keymap = \"11\"\n        Leave = \"8\"\n        Map = \"19\"\n        MapRequest = \"20\"\n        Mapping = \"34\"\n        Motion = \"6\"\n        MouseWheel = \"38\"\n        NoExpose = \"14\"\n        Property = \"28\"\n        Reparent = \"21\"\n        ResizeRequest = \"25\"\n        Selection = \"31\"\n        SelectionClear = \"29\"\n        SelectionRequest = \"30\"\n        Unmap = \"18\"\n        VirtualEvent = \"35\"\n        Visibility = \"15\"\n\nelse:\n    class EventType(str, Enum):\n        Activate = \"36\"\n        ButtonPress = \"4\"\n        Button = ButtonPress\n        ButtonRelease = \"5\"\n        Circulate = \"26\"\n        CirculateRequest = \"27\"\n        ClientMessage = \"33\"\n        Colormap = \"32\"\n        Configure = \"22\"\n        ConfigureRequest = \"23\"\n        Create = \"16\"\n        Deactivate = \"37\"\n        Destroy = \"17\"\n        Enter = \"7\"\n        Expose = \"12\"\n        FocusIn = \"9\"\n        FocusOut = \"10\"\n        GraphicsExpose = \"13\"\n        Gravity = \"24\"\n        KeyPress = \"2\"\n        Key = KeyPress\n        KeyRelease = \"3\"\n        Keymap = \"11\"\n        Leave = \"8\"\n        Map = \"19\"\n        MapRequest = \"20\"\n        Mapping = \"34\"\n        Motion = \"6\"\n        MouseWheel = \"38\"\n        NoExpose = \"14\"\n        Property = \"28\"\n        Reparent = \"21\"\n        ResizeRequest = \"25\"\n        Selection = \"31\"\n        SelectionClear = \"29\"\n        SelectionRequest = \"30\"\n        Unmap = \"18\"\n        VirtualEvent = \"35\"\n        Visibility = \"15\"\n\n_W = TypeVar(\"_W\", bound=Misc)\n# Events considered covariant because you should never assign to event.widget.\n_W_co = TypeVar(\"_W_co\", covariant=True, bound=Misc, default=Misc)\n\nclass Event(Generic[_W_co]):\n    serial: int\n    num: int\n    focus: bool\n    height: int\n    width: int\n    keycode: int\n    state: int | str\n    time: int\n    x: int\n    y: int\n    x_root: int\n    y_root: int\n    char: str\n    send_event: bool\n    keysym: str\n    keysym_num: int\n    type: EventType\n    widget: _W_co\n    delta: int\n    if sys.version_info >= (3, 14):\n        def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\ndef NoDefaultRoot() -> None: ...\n\nclass Variable:\n    def __init__(self, master: Misc | None = None, value=None, name: str | None = None) -> None: ...\n    def set(self, value) -> None: ...\n    initialize = set\n    def get(self): ...\n    def trace_add(self, mode: Literal[\"array\", \"read\", \"write\", \"unset\"], callback: Callable[[str, str, str], object]) -> str: ...\n    def trace_remove(self, mode: Literal[\"array\", \"read\", \"write\", \"unset\"], cbname: str) -> None: ...\n    def trace_info(self) -> list[tuple[tuple[Literal[\"array\", \"read\", \"write\", \"unset\"], ...], str]]: ...\n    if sys.version_info >= (3, 14):\n        @deprecated(\"Deprecated since Python 3.14. Use `trace_add()` instead.\")\n        def trace(self, mode, callback) -> str: ...\n        @deprecated(\"Deprecated since Python 3.14. Use `trace_add()` instead.\")\n        def trace_variable(self, mode, callback) -> str: ...\n        @deprecated(\"Deprecated since Python 3.14. Use `trace_remove()` instead.\")\n        def trace_vdelete(self, mode, cbname) -> None: ...\n        @deprecated(\"Deprecated since Python 3.14. Use `trace_info()` instead.\")\n        def trace_vinfo(self) -> list[Incomplete]: ...\n    else:\n        def trace(self, mode, callback) -> str: ...\n        def trace_variable(self, mode, callback) -> str: ...\n        def trace_vdelete(self, mode, cbname) -> None: ...\n        def trace_vinfo(self) -> list[Incomplete]: ...\n\n    def __eq__(self, other: object) -> bool: ...\n    def __del__(self) -> None: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\nclass StringVar(Variable):\n    def __init__(self, master: Misc | None = None, value: str | None = None, name: str | None = None) -> None: ...\n    def set(self, value: str) -> None: ...\n    initialize = set\n    def get(self) -> str: ...\n\nclass IntVar(Variable):\n    def __init__(self, master: Misc | None = None, value: int | None = None, name: str | None = None) -> None: ...\n    def set(self, value: int) -> None: ...\n    initialize = set\n    def get(self) -> int: ...\n\nclass DoubleVar(Variable):\n    def __init__(self, master: Misc | None = None, value: float | None = None, name: str | None = None) -> None: ...\n    def set(self, value: float) -> None: ...\n    initialize = set\n    def get(self) -> float: ...\n\nclass BooleanVar(Variable):\n    def __init__(self, master: Misc | None = None, value: bool | None = None, name: str | None = None) -> None: ...\n    def set(self, value: bool) -> None: ...\n    initialize = set\n    def get(self) -> bool: ...\n\ndef mainloop(n: int = 0) -> None: ...\n\ngetint = int\ngetdouble = float\n\ndef getboolean(s) -> bool: ...\n\n_Ts = TypeVarTuple(\"_Ts\")\n\n@type_check_only\nclass _GridIndexInfo(TypedDict, total=False):\n    minsize: float | str\n    pad: float | str\n    uniform: str | None\n    weight: int\n\n@type_check_only\nclass _BusyInfo(TypedDict):\n    cursor: _Cursor\n\nclass Misc:\n    master: Misc | None\n    tk: _tkinter.TkappType\n    children: dict[str, Widget]\n    def destroy(self) -> None: ...\n    def deletecommand(self, name: str) -> None: ...\n    def tk_strictMotif(self, boolean=None): ...\n    def tk_bisque(self) -> None: ...\n    def tk_setPalette(self, *args, **kw) -> None: ...\n    def wait_variable(self, name: str | Variable = \"PY_VAR\") -> None: ...\n    waitvar = wait_variable\n    def wait_window(self, window: Misc | None = None) -> None: ...\n    def wait_visibility(self, window: Misc | None = None) -> None: ...\n    def setvar(self, name: str = \"PY_VAR\", value: str = \"1\") -> None: ...\n    def getvar(self, name: str = \"PY_VAR\"): ...\n    def getint(self, s) -> int: ...\n    def getdouble(self, s) -> float: ...\n    def getboolean(self, s) -> bool: ...\n    def focus_set(self) -> None: ...\n    focus = focus_set\n    def focus_force(self) -> None: ...\n    def focus_get(self) -> Misc | None: ...\n    def focus_displayof(self) -> Misc | None: ...\n    def focus_lastfor(self) -> Misc | None: ...\n    def tk_focusFollowsMouse(self) -> None: ...\n    def tk_focusNext(self) -> Misc | None: ...\n    def tk_focusPrev(self) -> Misc | None: ...\n    # .after() can be called without the \"func\" argument, but it is basically never what you want.\n    # It behaves like time.sleep() and freezes the GUI app.\n    def after(self, ms: int | Literal[\"idle\"], func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: ...\n    # after_idle is essentially partialmethod(after, \"idle\")\n    def after_idle(self, func: Callable[[Unpack[_Ts]], object], *args: Unpack[_Ts]) -> str: ...\n    def after_cancel(self, id: str) -> None: ...\n    if sys.version_info >= (3, 13):\n        def after_info(self, id: str | None = None) -> tuple[str, ...]: ...\n\n    def bell(self, displayof: Literal[0] | Misc | None = 0) -> None: ...\n    if sys.version_info >= (3, 13):\n        # Supports options from `_BusyInfo``\n        def tk_busy_cget(self, option: Literal[\"cursor\"]) -> _Cursor: ...\n        busy_cget = tk_busy_cget\n        def tk_busy_configure(self, cnf: Any = None, **kw: Any) -> Any: ...\n        tk_busy_config = tk_busy_configure\n        busy_configure = tk_busy_configure\n        busy_config = tk_busy_configure\n        def tk_busy_current(self, pattern: str | None = None) -> list[Misc]: ...\n        busy_current = tk_busy_current\n        def tk_busy_forget(self) -> None: ...\n        busy_forget = tk_busy_forget\n        def tk_busy_hold(self, **kw: Unpack[_BusyInfo]) -> None: ...\n        tk_busy = tk_busy_hold\n        busy_hold = tk_busy_hold\n        busy = tk_busy_hold\n        def tk_busy_status(self) -> bool: ...\n        busy_status = tk_busy_status\n\n    def clipboard_get(self, *, displayof: Misc = ..., type: str = ...) -> str: ...\n    def clipboard_clear(self, *, displayof: Misc = ...) -> None: ...\n    def clipboard_append(self, string: str, *, displayof: Misc = ..., format: str = ..., type: str = ...) -> None: ...\n    def grab_current(self): ...\n    def grab_release(self) -> None: ...\n    def grab_set(self) -> None: ...\n    def grab_set_global(self) -> None: ...\n    def grab_status(self) -> Literal[\"local\", \"global\"] | None: ...\n    def option_add(\n        self, pattern, value, priority: int | Literal[\"widgetDefault\", \"startupFile\", \"userDefault\", \"interactive\"] | None = None\n    ) -> None: ...\n    def option_clear(self) -> None: ...\n    def option_get(self, name, className): ...\n    def option_readfile(self, fileName, priority=None) -> None: ...\n    def selection_clear(self, **kw) -> None: ...\n    def selection_get(self, **kw): ...\n    def selection_handle(self, command, **kw) -> None: ...\n    def selection_own(self, **kw) -> None: ...\n    def selection_own_get(self, **kw): ...\n    def send(self, interp, cmd, *args): ...\n    def lower(self, belowThis=None) -> None: ...\n    def tkraise(self, aboveThis=None) -> None: ...\n    lift = tkraise\n    if sys.version_info >= (3, 11):\n        def info_patchlevel(self) -> _VersionInfoType: ...\n\n    def winfo_atom(self, name: str, displayof: Literal[0] | Misc | None = 0) -> int: ...\n    def winfo_atomname(self, id: int, displayof: Literal[0] | Misc | None = 0) -> str: ...\n    def winfo_cells(self) -> int: ...\n    def winfo_children(self) -> list[Widget | Toplevel]: ...\n    def winfo_class(self) -> str: ...\n    def winfo_colormapfull(self) -> bool: ...\n    def winfo_containing(self, rootX: int, rootY: int, displayof: Literal[0] | Misc | None = 0) -> Misc | None: ...\n    def winfo_depth(self) -> int: ...\n    def winfo_exists(self) -> bool: ...\n    def winfo_fpixels(self, number: float | str) -> float: ...\n    def winfo_geometry(self) -> str: ...\n    def winfo_height(self) -> int: ...\n    def winfo_id(self) -> int: ...\n    def winfo_interps(self, displayof: Literal[0] | Misc | None = 0) -> tuple[str, ...]: ...\n    def winfo_ismapped(self) -> bool: ...\n    def winfo_manager(self) -> str: ...\n    def winfo_name(self) -> str: ...\n    def winfo_parent(self) -> str: ...  # return value needs nametowidget()\n    def winfo_pathname(self, id: int, displayof: Literal[0] | Misc | None = 0): ...\n    def winfo_pixels(self, number: float | str) -> int: ...\n    def winfo_pointerx(self) -> int: ...\n    def winfo_pointerxy(self) -> tuple[int, int]: ...\n    def winfo_pointery(self) -> int: ...\n    def winfo_reqheight(self) -> int: ...\n    def winfo_reqwidth(self) -> int: ...\n    def winfo_rgb(self, color: str) -> tuple[int, int, int]: ...\n    def winfo_rootx(self) -> int: ...\n    def winfo_rooty(self) -> int: ...\n    def winfo_screen(self) -> str: ...\n    def winfo_screencells(self) -> int: ...\n    def winfo_screendepth(self) -> int: ...\n    def winfo_screenheight(self) -> int: ...\n    def winfo_screenmmheight(self) -> int: ...\n    def winfo_screenmmwidth(self) -> int: ...\n    def winfo_screenvisual(self) -> str: ...\n    def winfo_screenwidth(self) -> int: ...\n    def winfo_server(self) -> str: ...\n    def winfo_toplevel(self) -> Tk | Toplevel: ...\n    def winfo_viewable(self) -> bool: ...\n    def winfo_visual(self) -> str: ...\n    def winfo_visualid(self) -> str: ...\n    def winfo_visualsavailable(self, includeids: bool = False) -> list[tuple[str, int]]: ...\n    def winfo_vrootheight(self) -> int: ...\n    def winfo_vrootwidth(self) -> int: ...\n    def winfo_vrootx(self) -> int: ...\n    def winfo_vrooty(self) -> int: ...\n    def winfo_width(self) -> int: ...\n    def winfo_x(self) -> int: ...\n    def winfo_y(self) -> int: ...\n    def update(self) -> None: ...\n    def update_idletasks(self) -> None: ...\n    @overload\n    def bindtags(self, tagList: None = None) -> tuple[str, ...]: ...\n    @overload\n    def bindtags(self, tagList: list[str] | tuple[str, ...]) -> None: ...\n    # bind with isinstance(func, str) doesn't return anything, but all other\n    # binds do. The default value of func is not str.\n    @overload\n    def bind(\n        self,\n        sequence: str | None = None,\n        func: Callable[[Event[Misc]], object] | None = None,\n        add: Literal[\"\", \"+\"] | bool | None = None,\n    ) -> str: ...\n    @overload\n    def bind(self, sequence: str | None, func: str, add: Literal[\"\", \"+\"] | bool | None = None) -> None: ...\n    @overload\n    def bind(self, *, func: str, add: Literal[\"\", \"+\"] | bool | None = None) -> None: ...\n    # There's no way to know what type of widget bind_all and bind_class\n    # callbacks will get, so those are Misc.\n    @overload\n    def bind_all(\n        self,\n        sequence: str | None = None,\n        func: Callable[[Event[Misc]], object] | None = None,\n        add: Literal[\"\", \"+\"] | bool | None = None,\n    ) -> str: ...\n    @overload\n    def bind_all(self, sequence: str | None, func: str, add: Literal[\"\", \"+\"] | bool | None = None) -> None: ...\n    @overload\n    def bind_all(self, *, func: str, add: Literal[\"\", \"+\"] | bool | None = None) -> None: ...\n    @overload\n    def bind_class(\n        self,\n        className: str,\n        sequence: str | None = None,\n        func: Callable[[Event[Misc]], object] | None = None,\n        add: Literal[\"\", \"+\"] | bool | None = None,\n    ) -> str: ...\n    @overload\n    def bind_class(self, className: str, sequence: str | None, func: str, add: Literal[\"\", \"+\"] | bool | None = None) -> None: ...\n    @overload\n    def bind_class(self, className: str, *, func: str, add: Literal[\"\", \"+\"] | bool | None = None) -> None: ...\n    def unbind(self, sequence: str, funcid: str | None = None) -> None: ...\n    def unbind_all(self, sequence: str) -> None: ...\n    def unbind_class(self, className: str, sequence: str) -> None: ...\n    def mainloop(self, n: int = 0) -> None: ...\n    def quit(self) -> None: ...\n    @property\n    def _windowingsystem(self) -> Literal[\"win32\", \"aqua\", \"x11\"]: ...\n    def nametowidget(self, name: str | Misc | _tkinter.Tcl_Obj) -> Any: ...\n    def register(\n        self, func: Callable[..., object], subst: Callable[..., Sequence[Any]] | None = None, needcleanup: int = 1\n    ) -> str: ...\n    def keys(self) -> list[str]: ...\n    @overload\n    def pack_propagate(self, flag: bool) -> bool | None: ...\n    @overload\n    def pack_propagate(self) -> None: ...\n    propagate = pack_propagate\n    def grid_anchor(self, anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] | None = None) -> None: ...\n    anchor = grid_anchor\n    @overload\n    def grid_bbox(\n        self, column: None = None, row: None = None, col2: None = None, row2: None = None\n    ) -> tuple[int, int, int, int] | None: ...\n    @overload\n    def grid_bbox(self, column: int, row: int, col2: None = None, row2: None = None) -> tuple[int, int, int, int] | None: ...\n    @overload\n    def grid_bbox(self, column: int, row: int, col2: int, row2: int) -> tuple[int, int, int, int] | None: ...\n    bbox = grid_bbox\n    def grid_columnconfigure(\n        self,\n        index: int | str | list[int] | tuple[int, ...],\n        cnf: _GridIndexInfo = {},\n        *,\n        minsize: float | str = ...,\n        pad: float | str = ...,\n        uniform: str = ...,\n        weight: int = ...,\n    ) -> _GridIndexInfo | MaybeNone: ...  # can be None but annoying to check\n    def grid_rowconfigure(\n        self,\n        index: int | str | list[int] | tuple[int, ...],\n        cnf: _GridIndexInfo = {},\n        *,\n        minsize: float | str = ...,\n        pad: float | str = ...,\n        uniform: str = ...,\n        weight: int = ...,\n    ) -> _GridIndexInfo | MaybeNone: ...  # can be None but annoying to check\n    columnconfigure = grid_columnconfigure\n    rowconfigure = grid_rowconfigure\n    def grid_location(self, x: float | str, y: float | str) -> tuple[int, int]: ...\n    @overload\n    def grid_propagate(self, flag: bool) -> None: ...\n    @overload\n    def grid_propagate(self) -> bool: ...\n    def grid_size(self) -> tuple[int, int]: ...\n    size = grid_size\n    # Widget because Toplevel or Tk is never a slave\n    def pack_slaves(self) -> list[Widget]: ...\n    def grid_slaves(self, row: int | None = None, column: int | None = None) -> list[Widget]: ...\n    def place_slaves(self) -> list[Widget]: ...\n    slaves = pack_slaves\n    def event_add(self, virtual: str, *sequences: str) -> None: ...\n    def event_delete(self, virtual: str, *sequences: str) -> None: ...\n    def event_generate(\n        self,\n        sequence: str,\n        *,\n        above: Misc | int = ...,\n        borderwidth: float | str = ...,\n        button: int = ...,\n        count: int = ...,\n        data: Any = ...,  # anything with usable str() value\n        delta: int = ...,\n        detail: str = ...,\n        focus: bool = ...,\n        height: float | str = ...,\n        keycode: int = ...,\n        keysym: str = ...,\n        mode: str = ...,\n        override: bool = ...,\n        place: Literal[\"PlaceOnTop\", \"PlaceOnBottom\"] = ...,\n        root: Misc | int = ...,\n        rootx: float | str = ...,\n        rooty: float | str = ...,\n        sendevent: bool = ...,\n        serial: int = ...,\n        state: int | str = ...,\n        subwindow: Misc | int = ...,\n        time: int = ...,\n        warp: bool = ...,\n        width: float | str = ...,\n        when: Literal[\"now\", \"tail\", \"head\", \"mark\"] = ...,\n        x: float | str = ...,\n        y: float | str = ...,\n    ) -> None: ...\n    def event_info(self, virtual: str | None = None) -> tuple[str, ...]: ...\n    def image_names(self) -> tuple[str, ...]: ...\n    def image_types(self) -> tuple[str, ...]: ...\n    # See #4363 and #4891\n    def __setitem__(self, key: str, value: Any) -> None: ...\n    def __getitem__(self, key: str) -> Any: ...\n    def cget(self, key: str) -> Any: ...\n    def configure(self, cnf: Any = None) -> Any: ...\n    # TODO: config is an alias of configure, but adding that here creates\n    # conflict with the type of config in the subclasses. See #13149\n\nclass CallWrapper:\n    func: Incomplete\n    subst: Incomplete\n    widget: Incomplete\n    def __init__(self, func, subst, widget) -> None: ...\n    def __call__(self, *args): ...\n\nclass XView:\n    @overload\n    def xview(self) -> tuple[float, float]: ...\n    @overload\n    def xview(self, *args) -> None: ...\n    def xview_moveto(self, fraction: float) -> None: ...\n    @overload\n    def xview_scroll(self, number: int, what: Literal[\"units\", \"pages\"]) -> None: ...\n    @overload\n    def xview_scroll(self, number: float | str, what: Literal[\"pixels\"]) -> None: ...\n\nclass YView:\n    @overload\n    def yview(self) -> tuple[float, float]: ...\n    @overload\n    def yview(self, *args) -> None: ...\n    def yview_moveto(self, fraction: float) -> None: ...\n    @overload\n    def yview_scroll(self, number: int, what: Literal[\"units\", \"pages\"]) -> None: ...\n    @overload\n    def yview_scroll(self, number: float | str, what: Literal[\"pixels\"]) -> None: ...\n\nif sys.platform == \"darwin\":\n    @type_check_only\n    class _WmAttributes(TypedDict):\n        alpha: float\n        fullscreen: bool\n        modified: bool\n        notify: bool\n        titlepath: str\n        topmost: bool\n        transparent: bool\n        type: str  # Present, but not actually used on darwin\n\nelif sys.platform == \"win32\":\n    @type_check_only\n    class _WmAttributes(TypedDict):\n        alpha: float\n        transparentcolor: str\n        disabled: bool\n        fullscreen: bool\n        toolwindow: bool\n        topmost: bool\n\nelse:\n    # X11\n    @type_check_only\n    class _WmAttributes(TypedDict):\n        alpha: float\n        topmost: bool\n        zoomed: bool\n        fullscreen: bool\n        type: str\n\nclass Wm:\n    @overload\n    def wm_aspect(self, minNumer: int, minDenom: int, maxNumer: int, maxDenom: int) -> None: ...\n    @overload\n    def wm_aspect(\n        self, minNumer: None = None, minDenom: None = None, maxNumer: None = None, maxDenom: None = None\n    ) -> tuple[int, int, int, int] | None: ...\n    aspect = wm_aspect\n    if sys.version_info >= (3, 13):\n        @overload\n        def wm_attributes(self, *, return_python_dict: Literal[False] = False) -> tuple[Any, ...]: ...\n        @overload\n        def wm_attributes(self, *, return_python_dict: Literal[True]) -> _WmAttributes: ...\n\n    else:\n        @overload\n        def wm_attributes(self) -> tuple[Any, ...]: ...\n\n    @overload\n    def wm_attributes(self, option: Literal[\"-alpha\"], /) -> float: ...\n    @overload\n    def wm_attributes(self, option: Literal[\"-fullscreen\"], /) -> bool: ...\n    @overload\n    def wm_attributes(self, option: Literal[\"-topmost\"], /) -> bool: ...\n    if sys.platform == \"darwin\":\n        @overload\n        def wm_attributes(self, option: Literal[\"-modified\"], /) -> bool: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-notify\"], /) -> bool: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-titlepath\"], /) -> str: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-transparent\"], /) -> bool: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-type\"], /) -> str: ...\n    elif sys.platform == \"win32\":\n        @overload\n        def wm_attributes(self, option: Literal[\"-transparentcolor\"], /) -> str: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-disabled\"], /) -> bool: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-toolwindow\"], /) -> bool: ...\n    else:\n        # X11\n        @overload\n        def wm_attributes(self, option: Literal[\"-zoomed\"], /) -> bool: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-type\"], /) -> str: ...\n    if sys.version_info >= (3, 13):\n        @overload\n        def wm_attributes(self, option: Literal[\"alpha\"], /) -> float: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"fullscreen\"], /) -> bool: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"topmost\"], /) -> bool: ...\n        if sys.platform == \"darwin\":\n            @overload\n            def wm_attributes(self, option: Literal[\"modified\"], /) -> bool: ...\n            @overload\n            def wm_attributes(self, option: Literal[\"notify\"], /) -> bool: ...\n            @overload\n            def wm_attributes(self, option: Literal[\"titlepath\"], /) -> str: ...\n            @overload\n            def wm_attributes(self, option: Literal[\"transparent\"], /) -> bool: ...\n            @overload\n            def wm_attributes(self, option: Literal[\"type\"], /) -> str: ...\n        elif sys.platform == \"win32\":\n            @overload\n            def wm_attributes(self, option: Literal[\"transparentcolor\"], /) -> str: ...\n            @overload\n            def wm_attributes(self, option: Literal[\"disabled\"], /) -> bool: ...\n            @overload\n            def wm_attributes(self, option: Literal[\"toolwindow\"], /) -> bool: ...\n        else:\n            # X11\n            @overload\n            def wm_attributes(self, option: Literal[\"zoomed\"], /) -> bool: ...\n            @overload\n            def wm_attributes(self, option: Literal[\"type\"], /) -> str: ...\n\n    @overload\n    def wm_attributes(self, option: str, /): ...\n    @overload\n    def wm_attributes(self, option: Literal[\"-alpha\"], value: float, /) -> Literal[\"\"]: ...\n    @overload\n    def wm_attributes(self, option: Literal[\"-fullscreen\"], value: bool, /) -> Literal[\"\"]: ...\n    @overload\n    def wm_attributes(self, option: Literal[\"-topmost\"], value: bool, /) -> Literal[\"\"]: ...\n    if sys.platform == \"darwin\":\n        @overload\n        def wm_attributes(self, option: Literal[\"-modified\"], value: bool, /) -> Literal[\"\"]: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-notify\"], value: bool, /) -> Literal[\"\"]: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-titlepath\"], value: str, /) -> Literal[\"\"]: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-transparent\"], value: bool, /) -> Literal[\"\"]: ...\n    elif sys.platform == \"win32\":\n        @overload\n        def wm_attributes(self, option: Literal[\"-transparentcolor\"], value: str, /) -> Literal[\"\"]: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-disabled\"], value: bool, /) -> Literal[\"\"]: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-toolwindow\"], value: bool, /) -> Literal[\"\"]: ...\n    else:\n        # X11\n        @overload\n        def wm_attributes(self, option: Literal[\"-zoomed\"], value: bool, /) -> Literal[\"\"]: ...\n        @overload\n        def wm_attributes(self, option: Literal[\"-type\"], value: str, /) -> Literal[\"\"]: ...\n\n    @overload\n    def wm_attributes(self, option: str, value, /, *__other_option_value_pairs: Any) -> Literal[\"\"]: ...\n    if sys.version_info >= (3, 13):\n        if sys.platform == \"darwin\":\n            @overload\n            def wm_attributes(\n                self,\n                *,\n                alpha: float = ...,\n                fullscreen: bool = ...,\n                modified: bool = ...,\n                notify: bool = ...,\n                titlepath: str = ...,\n                topmost: bool = ...,\n                transparent: bool = ...,\n            ) -> None: ...\n        elif sys.platform == \"win32\":\n            @overload\n            def wm_attributes(\n                self,\n                *,\n                alpha: float = ...,\n                transparentcolor: str = ...,\n                disabled: bool = ...,\n                fullscreen: bool = ...,\n                toolwindow: bool = ...,\n                topmost: bool = ...,\n            ) -> None: ...\n        else:\n            # X11\n            @overload\n            def wm_attributes(\n                self, *, alpha: float = ..., topmost: bool = ..., zoomed: bool = ..., fullscreen: bool = ..., type: str = ...\n            ) -> None: ...\n\n    attributes = wm_attributes\n    def wm_client(self, name: str | None = None) -> str: ...\n    client = wm_client\n    @overload\n    def wm_colormapwindows(self) -> list[Misc]: ...\n    @overload\n    def wm_colormapwindows(self, wlist: list[Misc] | tuple[Misc, ...], /) -> None: ...\n    @overload\n    def wm_colormapwindows(self, first_wlist_item: Misc, /, *other_wlist_items: Misc) -> None: ...\n    colormapwindows = wm_colormapwindows\n    def wm_command(self, value: str | None = None) -> str: ...\n    command = wm_command\n    # Some of these always return empty string, but return type is set to None to prevent accidentally using it\n    def wm_deiconify(self) -> None: ...\n    deiconify = wm_deiconify\n    def wm_focusmodel(self, model: Literal[\"active\", \"passive\"] | None = None) -> Literal[\"active\", \"passive\", \"\"]: ...\n    focusmodel = wm_focusmodel\n    def wm_forget(self, window: Wm) -> None: ...\n    forget = wm_forget\n    def wm_frame(self) -> str: ...\n    frame = wm_frame\n    @overload\n    def wm_geometry(self, newGeometry: None = None) -> str: ...\n    @overload\n    def wm_geometry(self, newGeometry: str) -> None: ...\n    geometry = wm_geometry\n    def wm_grid(self, baseWidth=None, baseHeight=None, widthInc=None, heightInc=None): ...\n    grid = wm_grid\n    def wm_group(self, pathName=None): ...\n    group = wm_group\n    def wm_iconbitmap(self, bitmap=None, default=None): ...\n    iconbitmap = wm_iconbitmap\n    def wm_iconify(self) -> None: ...\n    iconify = wm_iconify\n    def wm_iconmask(self, bitmap=None): ...\n    iconmask = wm_iconmask\n    def wm_iconname(self, newName=None) -> str: ...\n    iconname = wm_iconname\n    def wm_iconphoto(self, default: bool, image1: _PhotoImageLike | str, /, *args: _PhotoImageLike | str) -> None: ...\n    iconphoto = wm_iconphoto\n    def wm_iconposition(self, x: int | None = None, y: int | None = None) -> tuple[int, int] | None: ...\n    iconposition = wm_iconposition\n    def wm_iconwindow(self, pathName=None): ...\n    iconwindow = wm_iconwindow\n    def wm_manage(self, widget) -> None: ...\n    manage = wm_manage\n    @overload\n    def wm_maxsize(self, width: None = None, height: None = None) -> tuple[int, int]: ...\n    @overload\n    def wm_maxsize(self, width: int, height: int) -> None: ...\n    maxsize = wm_maxsize\n    @overload\n    def wm_minsize(self, width: None = None, height: None = None) -> tuple[int, int]: ...\n    @overload\n    def wm_minsize(self, width: int, height: int) -> None: ...\n    minsize = wm_minsize\n    @overload\n    def wm_overrideredirect(self, boolean: None = None) -> bool | None: ...  # returns True or None\n    @overload\n    def wm_overrideredirect(self, boolean: bool) -> None: ...\n    overrideredirect = wm_overrideredirect\n    def wm_positionfrom(self, who: Literal[\"program\", \"user\"] | None = None) -> Literal[\"\", \"program\", \"user\"]: ...\n    positionfrom = wm_positionfrom\n    @overload\n    def wm_protocol(self, name: str, func: Callable[[], object] | str) -> None: ...\n    @overload\n    def wm_protocol(self, name: str, func: None = None) -> str: ...\n    @overload\n    def wm_protocol(self, name: None = None, func: None = None) -> tuple[str, ...]: ...\n    protocol = wm_protocol\n    @overload\n    def wm_resizable(self, width: None = None, height: None = None) -> tuple[bool, bool]: ...\n    @overload\n    def wm_resizable(self, width: bool, height: bool) -> None: ...\n    resizable = wm_resizable\n    def wm_sizefrom(self, who: Literal[\"program\", \"user\"] | None = None) -> Literal[\"\", \"program\", \"user\"]: ...\n    sizefrom = wm_sizefrom\n    @overload\n    def wm_state(self, newstate: None = None) -> str: ...\n    @overload\n    def wm_state(self, newstate: str) -> None: ...\n    state = wm_state\n    @overload\n    def wm_title(self, string: None = None) -> str: ...\n    @overload\n    def wm_title(self, string: str) -> None: ...\n    title = wm_title\n    @overload\n    def wm_transient(self, master: None = None) -> _tkinter.Tcl_Obj: ...\n    @overload\n    def wm_transient(self, master: Wm | _tkinter.Tcl_Obj) -> None: ...\n    transient = wm_transient\n    def wm_withdraw(self) -> None: ...\n    withdraw = wm_withdraw\n\nclass Tk(Misc, Wm):\n    master: None\n    def __init__(\n        # Make sure to keep in sync with other functions that use the same\n        # args.\n        # use `git grep screenName` to find them\n        self,\n        screenName: str | None = None,\n        baseName: str | None = None,\n        className: str = \"Tk\",\n        useTk: bool = True,\n        sync: bool = False,\n        use: str | None = None,\n    ) -> None: ...\n    # Keep this in sync with ttktheme.ThemedTk. See issue #13858\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        menu: Menu = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        width: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def destroy(self) -> None: ...\n    def readprofile(self, baseName: str, className: str) -> None: ...\n    report_callback_exception: Callable[[type[BaseException], BaseException, TracebackType | None], object]\n    # Tk has __getattr__ so that tk_instance.foo falls back to tk_instance.tk.foo\n    # Please keep in sync with _tkinter.TkappType.\n    # Some methods are intentionally missing because they are inherited from Misc instead.\n    def adderrorinfo(self, msg: str, /) -> None: ...\n    def call(self, command: Any, /, *args: Any) -> Any: ...\n    # TODO: Figure out what arguments the following `func` callbacks should accept\n    def createcommand(self, name: str, func: Callable[..., object], /) -> None: ...\n    if sys.platform != \"win32\":\n        def createfilehandler(self, file: FileDescriptorLike, mask: int, func: Callable[..., object], /) -> None: ...\n        def deletefilehandler(self, file: FileDescriptorLike, /) -> None: ...\n\n    def createtimerhandler(self, milliseconds: int, func: Callable[..., object], /): ...\n    def dooneevent(self, flags: int = 0, /) -> int: ...\n    def eval(self, script: str, /) -> str: ...\n    def evalfile(self, fileName: str, /) -> str: ...\n    def exprboolean(self, s: str, /) -> Literal[0, 1]: ...\n    def exprdouble(self, s: str, /) -> float: ...\n    def exprlong(self, s: str, /) -> int: ...\n    def exprstring(self, s: str, /) -> str: ...\n    def globalgetvar(self, *args, **kwargs): ...\n    def globalsetvar(self, *args, **kwargs): ...\n    def globalunsetvar(self, *args, **kwargs): ...\n    def interpaddr(self) -> int: ...\n    def loadtk(self) -> None: ...\n    def record(self, script: str, /) -> str: ...\n    if sys.version_info < (3, 11):\n        @deprecated(\"Deprecated since Python 3.9; removed in Python 3.11. Use `splitlist()` instead.\")\n        def split(self, arg, /): ...\n\n    def splitlist(self, arg, /) -> tuple[Incomplete, ...]: ...\n    def unsetvar(self, *args, **kwargs): ...\n    if sys.version_info >= (3, 14):\n        @overload\n        def wantobjects(self) -> Literal[0, 1]: ...\n    else:\n        @overload\n        def wantobjects(self) -> bool: ...\n\n    @overload\n    def wantobjects(self, wantobjects: Literal[0, 1] | bool, /) -> None: ...\n    def willdispatch(self) -> None: ...\n\ndef Tcl(screenName: str | None = None, baseName: str | None = None, className: str = \"Tk\", useTk: bool = False) -> Tk: ...\n\n_InMiscTotal = TypedDict(\"_InMiscTotal\", {\"in\": Misc})\n_InMiscNonTotal = TypedDict(\"_InMiscNonTotal\", {\"in\": Misc}, total=False)\n\n@type_check_only\nclass _PackInfo(_InMiscTotal):\n    # 'before' and 'after' never appear in _PackInfo\n    anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"]\n    expand: bool\n    fill: Literal[\"none\", \"x\", \"y\", \"both\"]\n    side: Literal[\"left\", \"right\", \"top\", \"bottom\"]\n    # Paddings come out as int or tuple of int, even though any screen units\n    # can be specified in pack().\n    ipadx: int\n    ipady: int\n    padx: int | tuple[int, int]\n    pady: int | tuple[int, int]\n\nclass Pack:\n    # _PackInfo is not the valid type for cnf because pad stuff accepts any\n    # screen units instead of int only. I didn't bother to create another\n    # TypedDict for cnf because it appears to be a legacy thing that was\n    # replaced by **kwargs.\n    def pack_configure(\n        self,\n        cnf: Mapping[str, Any] | None = {},\n        *,\n        after: Misc = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        before: Misc = ...,\n        expand: bool | Literal[0, 1] = 0,\n        fill: Literal[\"none\", \"x\", \"y\", \"both\"] = ...,\n        side: Literal[\"left\", \"right\", \"top\", \"bottom\"] = ...,\n        ipadx: float | str = ...,\n        ipady: float | str = ...,\n        padx: float | str | tuple[float | str, float | str] = ...,\n        pady: float | str | tuple[float | str, float | str] = ...,\n        in_: Misc = ...,\n        **kw: Any,  # allow keyword argument named 'in', see #4836\n    ) -> None: ...\n    def pack_forget(self) -> None: ...\n    def pack_info(self) -> _PackInfo: ...  # errors if widget hasn't been packed\n    pack = pack_configure\n    forget = pack_forget\n    propagate = Misc.pack_propagate\n\n@type_check_only\nclass _PlaceInfo(_InMiscNonTotal):  # empty dict if widget hasn't been placed\n    anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"]\n    bordermode: Literal[\"inside\", \"outside\", \"ignore\"]\n    width: str  # can be int()ed (even after e.g. widget.place(height='2.3c') or similar)\n    height: str  # can be int()ed\n    x: str  # can be int()ed\n    y: str  # can be int()ed\n    relheight: str  # can be float()ed if not empty string\n    relwidth: str  # can be float()ed if not empty string\n    relx: str  # can be float()ed if not empty string\n    rely: str  # can be float()ed if not empty string\n\nclass Place:\n    def place_configure(\n        self,\n        cnf: Mapping[str, Any] | None = {},\n        *,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        bordermode: Literal[\"inside\", \"outside\", \"ignore\"] = ...,\n        width: float | str = ...,\n        height: float | str = ...,\n        x: float | str = ...,\n        y: float | str = ...,\n        # str allowed for compatibility with place_info()\n        relheight: str | float = ...,\n        relwidth: str | float = ...,\n        relx: str | float = ...,\n        rely: str | float = ...,\n        in_: Misc = ...,\n        **kw: Any,  # allow keyword argument named 'in', see #4836\n    ) -> None: ...\n    def place_forget(self) -> None: ...\n    def place_info(self) -> _PlaceInfo: ...\n    place = place_configure\n    info = place_info\n\n@type_check_only\nclass _GridInfo(_InMiscNonTotal):  # empty dict if widget hasn't been gridded\n    column: int\n    columnspan: int\n    row: int\n    rowspan: int\n    ipadx: int\n    ipady: int\n    padx: int | tuple[int, int]\n    pady: int | tuple[int, int]\n    sticky: str  # consists of letters 'n', 's', 'w', 'e', no repeats, may be empty\n\nclass Grid:\n    def grid_configure(\n        self,\n        cnf: Mapping[str, Any] | None = {},\n        *,\n        column: int = ...,\n        columnspan: int = ...,\n        row: int = ...,\n        rowspan: int = ...,\n        ipadx: float | str = ...,\n        ipady: float | str = ...,\n        padx: float | str | tuple[float | str, float | str] = ...,\n        pady: float | str | tuple[float | str, float | str] = ...,\n        sticky: str = ...,  # consists of letters 'n', 's', 'w', 'e', may contain repeats, may be empty\n        in_: Misc = ...,\n        **kw: Any,  # allow keyword argument named 'in', see #4836\n    ) -> None: ...\n    def grid_forget(self) -> None: ...\n    def grid_remove(self) -> None: ...\n    def grid_info(self) -> _GridInfo: ...\n    grid = grid_configure\n    location = Misc.grid_location\n    size = Misc.grid_size\n\nclass BaseWidget(Misc):\n    master: Misc\n    widgetName: str\n    def __init__(self, master, widgetName: str, cnf={}, kw={}, extra=()) -> None: ...\n    def destroy(self) -> None: ...\n\n# This class represents any widget except Toplevel or Tk.\nclass Widget(BaseWidget, Pack, Place, Grid):\n    # Allow bind callbacks to take e.g. Event[Label] instead of Event[Misc].\n    # Tk and Toplevel get notified for their child widgets' events, but other\n    # widgets don't.\n    @overload\n    def bind(\n        self: _W,\n        sequence: str | None = None,\n        func: Callable[[Event[_W]], object] | None = None,\n        add: Literal[\"\", \"+\"] | bool | None = None,\n    ) -> str: ...\n    @overload\n    def bind(self, sequence: str | None, func: str, add: Literal[\"\", \"+\"] | bool | None = None) -> None: ...\n    @overload\n    def bind(self, *, func: str, add: Literal[\"\", \"+\"] | bool | None = None) -> None: ...\n\nclass Toplevel(BaseWidget, Wm):\n    # Toplevel and Tk have the same options because they correspond to the same\n    # Tcl/Tk toplevel widget. For some reason, config and configure must be\n    # copy/pasted here instead of aliasing as 'config = Tk.config'.\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        background: str = ...,\n        bd: float | str = 0,\n        bg: str = ...,\n        border: float | str = 0,\n        borderwidth: float | str = 0,\n        class_: str = \"Toplevel\",\n        colormap: Literal[\"new\", \"\"] | Misc = \"\",\n        container: bool = False,\n        cursor: _Cursor = \"\",\n        height: float | str = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = 0,\n        menu: Menu = ...,\n        name: str = ...,\n        padx: float | str = 0,\n        pady: float | str = 0,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        screen: str = \"\",  # can't be changed after creating widget\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = 0,\n        use: int = ...,\n        visual: str | tuple[str, int] = \"\",\n        width: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        menu: Menu = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        width: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass Button(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = \"center\",\n        background: str = ...,\n        bd: float | str = ...,  # same as borderwidth\n        bg: str = ...,  # same as background\n        bitmap: str = \"\",\n        border: float | str = ...,  # same as borderwidth\n        borderwidth: float | str = ...,\n        command: str | Callable[[], Any] = \"\",\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = \"none\",\n        cursor: _Cursor = \"\",\n        default: Literal[\"normal\", \"active\", \"disabled\"] = \"disabled\",\n        disabledforeground: str = ...,\n        fg: str = ...,  # same as foreground\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        # width and height must be int for buttons containing just text, but\n        # buttons with an image accept any screen units.\n        height: float | str = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = 1,\n        image: _Image | str = \"\",\n        justify: Literal[\"left\", \"center\", \"right\"] = \"center\",\n        name: str = ...,\n        overrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\", \"\"] = \"\",\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        repeatdelay: int = ...,\n        repeatinterval: int = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        text: float | str = \"\",\n        # We allow the textvariable to be any Variable, not necessarily\n        # StringVar. This is useful for e.g. a button that displays the value\n        # of an IntVar.\n        textvariable: Variable = ...,\n        underline: int = -1,\n        width: float | str = 0,\n        wraplength: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        bitmap: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        command: str | Callable[[], Any] = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        cursor: _Cursor = ...,\n        default: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        image: _Image | str = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        overrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\", \"\"] = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        repeatdelay: int = ...,\n        repeatinterval: int = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        underline: int = ...,\n        width: float | str = ...,\n        wraplength: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def flash(self) -> None: ...\n    def invoke(self) -> Any: ...\n\nclass Canvas(Widget, XView, YView):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        background: str = ...,\n        bd: float | str = 0,\n        bg: str = ...,\n        border: float | str = 0,\n        borderwidth: float | str = 0,\n        closeenough: float = 1.0,\n        confine: bool = True,\n        cursor: _Cursor = \"\",\n        height: float | str = ...,  # see COORDINATES in canvas manual page\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        insertbackground: str = ...,\n        insertborderwidth: float | str = 0,\n        insertofftime: int = 300,\n        insertontime: int = 600,\n        insertwidth: float | str = 2,\n        name: str = ...,\n        offset=...,  # undocumented\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        # Setting scrollregion to None doesn't reset it back to empty,\n        # but setting it to () does.\n        scrollregion: tuple[float | str, float | str, float | str, float | str] | tuple[()] = (),\n        selectbackground: str = ...,\n        selectborderwidth: float | str = 1,\n        selectforeground: str = ...,\n        # man page says that state can be 'hidden', but it can't\n        state: Literal[\"normal\", \"disabled\"] = \"normal\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        width: float | str = ...,\n        xscrollcommand: str | Callable[[float, float], object] = \"\",\n        xscrollincrement: float | str = 0,\n        yscrollcommand: str | Callable[[float, float], object] = \"\",\n        yscrollincrement: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        closeenough: float = ...,\n        confine: bool = ...,\n        cursor: _Cursor = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        insertbackground: str = ...,\n        insertborderwidth: float | str = ...,\n        insertofftime: int = ...,\n        insertontime: int = ...,\n        insertwidth: float | str = ...,\n        offset=...,  # undocumented\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        scrollregion: tuple[float | str, float | str, float | str, float | str] | tuple[()] = ...,\n        selectbackground: str = ...,\n        selectborderwidth: float | str = ...,\n        selectforeground: str = ...,\n        state: Literal[\"normal\", \"disabled\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        width: float | str = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n        xscrollincrement: float | str = ...,\n        yscrollcommand: str | Callable[[float, float], object] = ...,\n        yscrollincrement: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def addtag(self, *args): ...  # internal method\n    def addtag_above(self, newtag: str, tagOrId: str | int) -> None: ...\n    def addtag_all(self, newtag: str) -> None: ...\n    def addtag_below(self, newtag: str, tagOrId: str | int) -> None: ...\n    def addtag_closest(\n        self, newtag: str, x: float | str, y: float | str, halo: float | str | None = None, start: str | int | None = None\n    ) -> None: ...\n    def addtag_enclosed(self, newtag: str, x1: float | str, y1: float | str, x2: float | str, y2: float | str) -> None: ...\n    def addtag_overlapping(self, newtag: str, x1: float | str, y1: float | str, x2: float | str, y2: float | str) -> None: ...\n    def addtag_withtag(self, newtag: str, tagOrId: str | int) -> None: ...\n    def find(self, *args): ...  # internal method\n    def find_above(self, tagOrId: str | int) -> tuple[int, ...]: ...\n    def find_all(self) -> tuple[int, ...]: ...\n    def find_below(self, tagOrId: str | int) -> tuple[int, ...]: ...\n    def find_closest(\n        self, x: float | str, y: float | str, halo: float | str | None = None, start: str | int | None = None\n    ) -> tuple[int, ...]: ...\n    def find_enclosed(self, x1: float | str, y1: float | str, x2: float | str, y2: float | str) -> tuple[int, ...]: ...\n    def find_overlapping(self, x1: float | str, y1: float | str, x2: float | str, y2: float) -> tuple[int, ...]: ...\n    def find_withtag(self, tagOrId: str | int) -> tuple[int, ...]: ...\n    # Incompatible with Misc.bbox(), tkinter violates LSP\n    def bbox(self, *args: str | int) -> tuple[int, int, int, int]: ...  # type: ignore[override]\n    @overload\n    def tag_bind(\n        self,\n        tagOrId: str | int,\n        sequence: str | None = None,\n        func: Callable[[Event[Canvas]], object] | None = None,\n        add: Literal[\"\", \"+\"] | bool | None = None,\n    ) -> str: ...\n    @overload\n    def tag_bind(\n        self, tagOrId: str | int, sequence: str | None, func: str, add: Literal[\"\", \"+\"] | bool | None = None\n    ) -> None: ...\n    @overload\n    def tag_bind(self, tagOrId: str | int, *, func: str, add: Literal[\"\", \"+\"] | bool | None = None) -> None: ...\n    def tag_unbind(self, tagOrId: str | int, sequence: str, funcid: str | None = None) -> None: ...\n    def canvasx(self, screenx, gridspacing=None): ...\n    def canvasy(self, screeny, gridspacing=None): ...\n    @overload\n    def coords(self, tagOrId: str | int, /) -> list[float]: ...\n    @overload\n    def coords(self, tagOrId: str | int, args: list[int] | list[float] | tuple[float, ...], /) -> None: ...\n    @overload\n    def coords(self, tagOrId: str | int, x1: float, y1: float, /, *args: float) -> None: ...\n    # create_foo() methods accept coords as a list or tuple, or as separate arguments.\n    # Lists and tuples can be flat as in [1, 2, 3, 4], or nested as in [(1, 2), (3, 4)].\n    # Keyword arguments should be the same in all overloads of each method.\n    def create_arc(self, *args, **kw) -> int: ...\n    def create_bitmap(self, *args, **kw) -> int: ...\n    def create_image(self, *args, **kw) -> int: ...\n    @overload\n    def create_line(\n        self,\n        x0: float,\n        y0: float,\n        x1: float,\n        y1: float,\n        /,\n        *,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        arrow: Literal[\"first\", \"last\", \"both\"] = ...,\n        arrowshape: tuple[float, float, float] = ...,\n        capstyle: Literal[\"round\", \"projecting\", \"butt\"] = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: float | str = ...,\n        smooth: bool = ...,\n        splinesteps: float = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_line(\n        self,\n        xy_pair_0: tuple[float, float],\n        xy_pair_1: tuple[float, float],\n        /,\n        *,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        arrow: Literal[\"first\", \"last\", \"both\"] = ...,\n        arrowshape: tuple[float, float, float] = ...,\n        capstyle: Literal[\"round\", \"projecting\", \"butt\"] = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: float | str = ...,\n        smooth: bool = ...,\n        splinesteps: float = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_line(\n        self,\n        coords: (\n            tuple[float, float, float, float]\n            | tuple[tuple[float, float], tuple[float, float]]\n            | list[int]\n            | list[float]\n            | list[tuple[int, int]]\n            | list[tuple[float, float]]\n        ),\n        /,\n        *,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        arrow: Literal[\"first\", \"last\", \"both\"] = ...,\n        arrowshape: tuple[float, float, float] = ...,\n        capstyle: Literal[\"round\", \"projecting\", \"butt\"] = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: float | str = ...,\n        smooth: bool = ...,\n        splinesteps: float = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_oval(\n        self,\n        x0: float,\n        y0: float,\n        x1: float,\n        y1: float,\n        /,\n        *,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activeoutline: str = ...,\n        activeoutlinestipple: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        offset: float | str = ...,\n        outline: str = ...,\n        outlineoffset: float | str = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_oval(\n        self,\n        xy_pair_0: tuple[float, float],\n        xy_pair_1: tuple[float, float],\n        /,\n        *,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activeoutline: str = ...,\n        activeoutlinestipple: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        offset: float | str = ...,\n        outline: str = ...,\n        outlineoffset: float | str = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_oval(\n        self,\n        coords: (\n            tuple[float, float, float, float]\n            | tuple[tuple[float, float], tuple[float, float]]\n            | list[int]\n            | list[float]\n            | list[tuple[int, int]]\n            | list[tuple[float, float]]\n        ),\n        /,\n        *,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activeoutline: str = ...,\n        activeoutlinestipple: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        offset: float | str = ...,\n        outline: str = ...,\n        outlineoffset: float | str = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_polygon(\n        self,\n        x0: float,\n        y0: float,\n        x1: float,\n        y1: float,\n        /,\n        *xy_pairs: float,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activeoutline: str = ...,\n        activeoutlinestipple: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: float | str = ...,\n        outline: str = ...,\n        outlineoffset: float | str = ...,\n        outlinestipple: str = ...,\n        smooth: bool = ...,\n        splinesteps: float = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_polygon(\n        self,\n        xy_pair_0: tuple[float, float],\n        xy_pair_1: tuple[float, float],\n        /,\n        *xy_pairs: tuple[float, float],\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activeoutline: str = ...,\n        activeoutlinestipple: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: float | str = ...,\n        outline: str = ...,\n        outlineoffset: float | str = ...,\n        outlinestipple: str = ...,\n        smooth: bool = ...,\n        splinesteps: float = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_polygon(\n        self,\n        coords: (\n            tuple[float, ...]\n            | tuple[tuple[float, float], ...]\n            | list[int]\n            | list[float]\n            | list[tuple[int, int]]\n            | list[tuple[float, float]]\n        ),\n        /,\n        *,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activeoutline: str = ...,\n        activeoutlinestipple: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        joinstyle: Literal[\"round\", \"bevel\", \"miter\"] = ...,\n        offset: float | str = ...,\n        outline: str = ...,\n        outlineoffset: float | str = ...,\n        outlinestipple: str = ...,\n        smooth: bool = ...,\n        splinesteps: float = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_rectangle(\n        self,\n        x0: float,\n        y0: float,\n        x1: float,\n        y1: float,\n        /,\n        *,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activeoutline: str = ...,\n        activeoutlinestipple: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        offset: float | str = ...,\n        outline: str = ...,\n        outlineoffset: float | str = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_rectangle(\n        self,\n        xy_pair_0: tuple[float, float],\n        xy_pair_1: tuple[float, float],\n        /,\n        *,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activeoutline: str = ...,\n        activeoutlinestipple: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        offset: float | str = ...,\n        outline: str = ...,\n        outlineoffset: float | str = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_rectangle(\n        self,\n        coords: (\n            tuple[float, float, float, float]\n            | tuple[tuple[float, float], tuple[float, float]]\n            | list[int]\n            | list[float]\n            | list[tuple[int, int]]\n            | list[tuple[float, float]]\n        ),\n        /,\n        *,\n        activedash: str | int | list[int] | tuple[int, ...] = ...,\n        activefill: str = ...,\n        activeoutline: str = ...,\n        activeoutlinestipple: str = ...,\n        activestipple: str = ...,\n        activewidth: float | str = ...,\n        dash: str | int | list[int] | tuple[int, ...] = ...,\n        dashoffset: float | str = ...,\n        disableddash: str | int | list[int] | tuple[int, ...] = ...,\n        disabledfill: str = ...,\n        disabledoutline: str = ...,\n        disabledoutlinestipple: str = ...,\n        disabledstipple: str = ...,\n        disabledwidth: float | str = ...,\n        fill: str = ...,\n        offset: float | str = ...,\n        outline: str = ...,\n        outlineoffset: float | str = ...,\n        outlinestipple: str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_text(\n        self,\n        x: float,\n        y: float,\n        /,\n        *,\n        activefill: str = ...,\n        activestipple: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        angle: float | str = ...,\n        disabledfill: str = ...,\n        disabledstipple: str = ...,\n        fill: str = ...,\n        font: _FontDescription = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        offset: float | str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        text: float | str = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_text(\n        self,\n        coords: tuple[float, float] | list[int] | list[float],\n        /,\n        *,\n        activefill: str = ...,\n        activestipple: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        angle: float | str = ...,\n        disabledfill: str = ...,\n        disabledstipple: str = ...,\n        fill: str = ...,\n        font: _FontDescription = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        offset: float | str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        stipple: str = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        text: float | str = ...,\n        width: float | str = ...,\n    ) -> int: ...\n    @overload\n    def create_window(\n        self,\n        x: float,\n        y: float,\n        /,\n        *,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        height: float | str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n        window: Widget = ...,\n    ) -> int: ...\n    @overload\n    def create_window(\n        self,\n        coords: tuple[float, float] | list[int] | list[float],\n        /,\n        *,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        height: float | str = ...,\n        state: Literal[\"normal\", \"hidden\", \"disabled\"] = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n        width: float | str = ...,\n        window: Widget = ...,\n    ) -> int: ...\n    def dchars(self, *args) -> None: ...\n    def delete(self, *tagsOrCanvasIds: str | int) -> None: ...\n    @overload\n    def dtag(self, tag: str, tag_to_delete: str | None = ..., /) -> None: ...\n    @overload\n    def dtag(self, id: int, tag_to_delete: str, /) -> None: ...\n    def focus(self, *args): ...\n    def gettags(self, tagOrId: str | int, /) -> tuple[str, ...]: ...\n    def icursor(self, *args) -> None: ...\n    def index(self, *args): ...\n    def insert(self, *args) -> None: ...\n    def itemcget(self, tagOrId, option): ...\n    # itemconfigure kwargs depend on item type, which is not known when type checking\n    def itemconfigure(\n        self, tagOrId: str | int, cnf: dict[str, Any] | None = None, **kw: Any\n    ) -> dict[str, tuple[str, str, str, str, str]] | None: ...\n    itemconfig = itemconfigure\n    def move(self, *args) -> None: ...\n    def moveto(self, tagOrId: str | int, x: Literal[\"\"] | float = \"\", y: Literal[\"\"] | float = \"\") -> None: ...\n    def postscript(self, cnf={}, **kw): ...\n    # tkinter does:\n    #    lower = tag_lower\n    #    lift = tkraise = tag_raise\n    #\n    # But mypy doesn't like aliasing here (maybe because Misc defines the same names)\n    def tag_lower(self, first: str | int, second: str | int | None = ..., /) -> None: ...\n    def lower(self, first: str | int, second: str | int | None = ..., /) -> None: ...  # type: ignore[override]\n    def tag_raise(self, first: str | int, second: str | int | None = ..., /) -> None: ...\n    def tkraise(self, first: str | int, second: str | int | None = ..., /) -> None: ...  # type: ignore[override]\n    def lift(self, first: str | int, second: str | int | None = ..., /) -> None: ...  # type: ignore[override]\n    def scale(self, tagOrId: str | int, xOrigin: float | str, yOrigin: float | str, xScale: float, yScale: float, /) -> None: ...\n    def scan_mark(self, x, y) -> None: ...\n    def scan_dragto(self, x, y, gain: int = 10) -> None: ...\n    def select_adjust(self, tagOrId, index) -> None: ...\n    def select_clear(self) -> None: ...\n    def select_from(self, tagOrId, index) -> None: ...\n    def select_item(self): ...\n    def select_to(self, tagOrId, index) -> None: ...\n    def type(self, tagOrId: str | int) -> int | None: ...\n\nclass Checkbutton(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = \"center\",\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        bitmap: str = \"\",\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        command: str | Callable[[], Any] = \"\",\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = \"none\",\n        cursor: _Cursor = \"\",\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        height: float | str = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = 1,\n        image: _Image | str = \"\",\n        indicatoron: bool = True,\n        justify: Literal[\"left\", \"center\", \"right\"] = \"center\",\n        name: str = ...,\n        offrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        # The checkbutton puts a value to its variable when it's checked or\n        # unchecked. We don't restrict the type of that value here, so\n        # Any-typing is fine.\n        #\n        # I think Checkbutton shouldn't be generic, because then specifying\n        # \"any checkbutton regardless of what variable it uses\" would be\n        # difficult, and we might run into issues just like how list[float]\n        # and list[int] are incompatible. Also, we would need a way to\n        # specify \"Checkbutton not associated with any variable\", which is\n        # done by setting variable to empty string (the default).\n        offvalue: Any = 0,\n        onvalue: Any = 1,\n        overrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\", \"\"] = \"\",\n        padx: float | str = 1,\n        pady: float | str = 1,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        selectcolor: str = ...,\n        selectimage: _Image | str = \"\",\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        text: float | str = \"\",\n        textvariable: Variable = ...,\n        tristateimage: _Image | str = \"\",\n        tristatevalue: Any = \"\",\n        underline: int = -1,\n        variable: Variable | Literal[\"\"] = ...,\n        width: float | str = 0,\n        wraplength: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        bitmap: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        command: str | Callable[[], Any] = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        cursor: _Cursor = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        image: _Image | str = ...,\n        indicatoron: bool = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        offrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        offvalue: Any = ...,\n        onvalue: Any = ...,\n        overrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\", \"\"] = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        selectcolor: str = ...,\n        selectimage: _Image | str = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        tristateimage: _Image | str = ...,\n        tristatevalue: Any = ...,\n        underline: int = ...,\n        variable: Variable | Literal[\"\"] = ...,\n        width: float | str = ...,\n        wraplength: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def deselect(self) -> None: ...\n    def flash(self) -> None: ...\n    def invoke(self) -> Any: ...\n    def select(self) -> None: ...\n    def toggle(self) -> None: ...\n\nclass Entry(Widget, XView):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = \"xterm\",\n        disabledbackground: str = ...,\n        disabledforeground: str = ...,\n        exportselection: bool = True,\n        fg: str = ...,\n        font: _FontDescription = \"TkTextFont\",\n        foreground: str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        insertbackground: str = ...,\n        insertborderwidth: float | str = 0,\n        insertofftime: int = 300,\n        insertontime: int = 600,\n        insertwidth: float | str = ...,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",\n        invcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",  # same as invalidcommand\n        justify: Literal[\"left\", \"center\", \"right\"] = \"left\",\n        name: str = ...,\n        readonlybackground: str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"sunken\",\n        selectbackground: str = ...,\n        selectborderwidth: float | str = ...,\n        selectforeground: str = ...,\n        show: str = \"\",\n        state: Literal[\"normal\", \"disabled\", \"readonly\"] = \"normal\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        textvariable: Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = \"none\",\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",\n        vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",  # same as validatecommand\n        width: int = 20,\n        xscrollcommand: str | Callable[[float, float], object] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = ...,\n        disabledbackground: str = ...,\n        disabledforeground: str = ...,\n        exportselection: bool = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        insertbackground: str = ...,\n        insertborderwidth: float | str = ...,\n        insertofftime: int = ...,\n        insertontime: int = ...,\n        insertwidth: float | str = ...,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        invcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        readonlybackground: str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        selectbackground: str = ...,\n        selectborderwidth: float | str = ...,\n        selectforeground: str = ...,\n        show: str = ...,\n        state: Literal[\"normal\", \"disabled\", \"readonly\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        textvariable: Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        width: int = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def delete(self, first: str | int, last: str | int | None = None) -> None: ...\n    def get(self) -> str: ...\n    def icursor(self, index: str | int) -> None: ...\n    def index(self, index: str | int) -> int: ...\n    def insert(self, index: str | int, string: str) -> None: ...\n    def scan_mark(self, x) -> None: ...\n    def scan_dragto(self, x) -> None: ...\n    def selection_adjust(self, index: str | int) -> None: ...\n    def selection_clear(self) -> None: ...  # type: ignore[override]\n    def selection_from(self, index: str | int) -> None: ...\n    def selection_present(self) -> bool: ...\n    def selection_range(self, start: str | int, end: str | int) -> None: ...\n    def selection_to(self, index: str | int) -> None: ...\n    select_adjust = selection_adjust\n    select_clear = selection_clear\n    select_from = selection_from\n    select_present = selection_present\n    select_range = selection_range\n    select_to = selection_to\n\nclass Frame(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        background: str = ...,\n        bd: float | str = 0,\n        bg: str = ...,\n        border: float | str = 0,\n        borderwidth: float | str = 0,\n        class_: str = \"Frame\",  # can't be changed with configure()\n        colormap: Literal[\"new\", \"\"] | Misc = \"\",  # can't be changed with configure()\n        container: bool = False,  # can't be changed with configure()\n        cursor: _Cursor = \"\",\n        height: float | str = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = 0,\n        name: str = ...,\n        padx: float | str = 0,\n        pady: float | str = 0,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = 0,\n        visual: str | tuple[str, int] = \"\",  # can't be changed with configure()\n        width: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        width: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass Label(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = \"center\",\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        bitmap: str = \"\",\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = \"none\",\n        cursor: _Cursor = \"\",\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        height: float | str = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = 0,\n        image: _Image | str = \"\",\n        justify: Literal[\"left\", \"center\", \"right\"] = \"center\",\n        name: str = ...,\n        padx: float | str = 1,\n        pady: float | str = 1,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = 0,\n        text: float | str = \"\",\n        textvariable: Variable = ...,\n        underline: int = -1,\n        width: float | str = 0,\n        wraplength: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        bitmap: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        cursor: _Cursor = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        image: _Image | str = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        underline: int = ...,\n        width: float | str = ...,\n        wraplength: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass Listbox(Widget, XView, YView):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        activestyle: Literal[\"dotbox\", \"none\", \"underline\"] = ...,\n        background: str = ...,\n        bd: float | str = 1,\n        bg: str = ...,\n        border: float | str = 1,\n        borderwidth: float | str = 1,\n        cursor: _Cursor = \"\",\n        disabledforeground: str = ...,\n        exportselection: bool | Literal[0, 1] = 1,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: int = 10,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = \"left\",\n        # There's no tkinter.ListVar, but seems like bare tkinter.Variable\n        # actually works for this:\n        #\n        #    >>> import tkinter\n        #    >>> lb = tkinter.Listbox()\n        #    >>> var = lb['listvariable'] = tkinter.Variable()\n        #    >>> var.set(['foo', 'bar', 'baz'])\n        #    >>> lb.get(0, 'end')\n        #    ('foo', 'bar', 'baz')\n        listvariable: Variable = ...,\n        name: str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        selectbackground: str = ...,\n        selectborderwidth: float | str = 0,\n        selectforeground: str = ...,\n        # from listbox man page: \"The value of the [selectmode] option may be\n        # arbitrary, but the default bindings expect it to be either single,\n        # browse, multiple, or extended\"\n        #\n        # I have never seen anyone setting this to something else than what\n        # \"the default bindings expect\", but let's support it anyway.\n        selectmode: str | Literal[\"single\", \"browse\", \"multiple\", \"extended\"] = \"browse\",  # noqa: Y051\n        setgrid: bool = False,\n        state: Literal[\"normal\", \"disabled\"] = \"normal\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        width: int = 20,\n        xscrollcommand: str | Callable[[float, float], object] = \"\",\n        yscrollcommand: str | Callable[[float, float], object] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activestyle: Literal[\"dotbox\", \"none\", \"underline\"] = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = ...,\n        disabledforeground: str = ...,\n        exportselection: bool = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: int = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        listvariable: Variable = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        selectbackground: str = ...,\n        selectborderwidth: float | str = ...,\n        selectforeground: str = ...,\n        selectmode: str | Literal[\"single\", \"browse\", \"multiple\", \"extended\"] = ...,  # noqa: Y051\n        setgrid: bool = ...,\n        state: Literal[\"normal\", \"disabled\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        width: int = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n        yscrollcommand: str | Callable[[float, float], object] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def activate(self, index: str | int) -> None: ...\n    def bbox(self, index: str | int) -> tuple[int, int, int, int] | None: ...  # type: ignore[override]\n    def curselection(self): ...\n    def delete(self, first: str | int, last: str | int | None = None) -> None: ...\n    def get(self, first: str | int, last: str | int | None = None): ...\n    def index(self, index: str | int) -> int: ...\n    def insert(self, index: str | int, *elements: str | float) -> None: ...\n    def nearest(self, y): ...\n    def scan_mark(self, x, y) -> None: ...\n    def scan_dragto(self, x, y) -> None: ...\n    def see(self, index: str | int) -> None: ...\n    def selection_anchor(self, index: str | int) -> None: ...\n    select_anchor = selection_anchor\n    def selection_clear(self, first: str | int, last: str | int | None = None) -> None: ...  # type: ignore[override]\n    select_clear = selection_clear\n    def selection_includes(self, index: str | int): ...\n    select_includes = selection_includes\n    def selection_set(self, first: str | int, last: str | int | None = None) -> None: ...\n    select_set = selection_set\n    def size(self) -> int: ...  # type: ignore[override]\n    def itemcget(self, index: str | int, option): ...\n    def itemconfigure(self, index: str | int, cnf=None, **kw): ...\n    itemconfig = itemconfigure\n\nclass Menu(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        activebackground: str = ...,\n        activeborderwidth: float | str = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = \"arrow\",\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        name: str = ...,\n        postcommand: Callable[[], object] | str = \"\",\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        selectcolor: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = 0,\n        tearoff: bool | Literal[0, 1] = 1,\n        # I guess tearoffcommand arguments are supposed to be widget objects,\n        # but they are widget name strings. Use nametowidget() to handle the\n        # arguments of tearoffcommand.\n        tearoffcommand: Callable[[str, str], object] | str = \"\",\n        title: str = \"\",\n        type: Literal[\"menubar\", \"tearoff\", \"normal\"] = \"normal\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activebackground: str = ...,\n        activeborderwidth: float | str = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        postcommand: Callable[[], object] | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        selectcolor: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        tearoff: bool = ...,\n        tearoffcommand: Callable[[str, str], object] | str = ...,\n        title: str = ...,\n        type: Literal[\"menubar\", \"tearoff\", \"normal\"] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def tk_popup(self, x: int, y: int, entry: str | int = \"\") -> None: ...\n    def activate(self, index: str | int) -> None: ...\n    def add(self, itemType, cnf={}, **kw): ...  # docstring says \"Internal function.\"\n    def insert(self, index, itemType, cnf={}, **kw): ...  # docstring says \"Internal function.\"\n    def add_cascade(\n        self,\n        cnf: dict[str, Any] | None = {},\n        *,\n        accelerator: str = ...,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bitmap: str = ...,\n        columnbreak: int = ...,\n        command: Callable[[], object] | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _Image | str = ...,\n        label: str = ...,\n        menu: Menu = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        underline: int = ...,\n    ) -> None: ...\n    def add_checkbutton(\n        self,\n        cnf: dict[str, Any] | None = {},\n        *,\n        accelerator: str = ...,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bitmap: str = ...,\n        columnbreak: int = ...,\n        command: Callable[[], object] | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _Image | str = ...,\n        indicatoron: bool = ...,\n        label: str = ...,\n        offvalue: Any = ...,\n        onvalue: Any = ...,\n        selectcolor: str = ...,\n        selectimage: _Image | str = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        underline: int = ...,\n        variable: Variable = ...,\n    ) -> None: ...\n    def add_command(\n        self,\n        cnf: dict[str, Any] | None = {},\n        *,\n        accelerator: str = ...,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bitmap: str = ...,\n        columnbreak: int = ...,\n        command: Callable[[], object] | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _Image | str = ...,\n        label: str = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        underline: int = ...,\n    ) -> None: ...\n    def add_radiobutton(\n        self,\n        cnf: dict[str, Any] | None = {},\n        *,\n        accelerator: str = ...,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bitmap: str = ...,\n        columnbreak: int = ...,\n        command: Callable[[], object] | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _Image | str = ...,\n        indicatoron: bool = ...,\n        label: str = ...,\n        selectcolor: str = ...,\n        selectimage: _Image | str = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        underline: int = ...,\n        value: Any = ...,\n        variable: Variable = ...,\n    ) -> None: ...\n    def add_separator(self, cnf: dict[str, Any] | None = {}, *, background: str = ...) -> None: ...\n    def insert_cascade(\n        self,\n        index: str | int,\n        cnf: dict[str, Any] | None = {},\n        *,\n        accelerator: str = ...,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bitmap: str = ...,\n        columnbreak: int = ...,\n        command: Callable[[], object] | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _Image | str = ...,\n        label: str = ...,\n        menu: Menu = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        underline: int = ...,\n    ) -> None: ...\n    def insert_checkbutton(\n        self,\n        index: str | int,\n        cnf: dict[str, Any] | None = {},\n        *,\n        accelerator: str = ...,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bitmap: str = ...,\n        columnbreak: int = ...,\n        command: Callable[[], object] | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _Image | str = ...,\n        indicatoron: bool = ...,\n        label: str = ...,\n        offvalue: Any = ...,\n        onvalue: Any = ...,\n        selectcolor: str = ...,\n        selectimage: _Image | str = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        underline: int = ...,\n        variable: Variable = ...,\n    ) -> None: ...\n    def insert_command(\n        self,\n        index: str | int,\n        cnf: dict[str, Any] | None = {},\n        *,\n        accelerator: str = ...,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bitmap: str = ...,\n        columnbreak: int = ...,\n        command: Callable[[], object] | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _Image | str = ...,\n        label: str = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        underline: int = ...,\n    ) -> None: ...\n    def insert_radiobutton(\n        self,\n        index: str | int,\n        cnf: dict[str, Any] | None = {},\n        *,\n        accelerator: str = ...,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        background: str = ...,\n        bitmap: str = ...,\n        columnbreak: int = ...,\n        command: Callable[[], object] | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        hidemargin: bool = ...,\n        image: _Image | str = ...,\n        indicatoron: bool = ...,\n        label: str = ...,\n        selectcolor: str = ...,\n        selectimage: _Image | str = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        underline: int = ...,\n        value: Any = ...,\n        variable: Variable = ...,\n    ) -> None: ...\n    def insert_separator(self, index: str | int, cnf: dict[str, Any] | None = {}, *, background: str = ...) -> None: ...\n    def delete(self, index1: str | int, index2: str | int | None = None) -> None: ...\n    def entrycget(self, index: str | int, option: str) -> Any: ...\n    def entryconfigure(\n        self, index: str | int, cnf: dict[str, Any] | None = None, **kw: Any\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    entryconfig = entryconfigure\n    def index(self, index: str | int) -> int | None: ...\n    def invoke(self, index: str | int) -> Any: ...\n    def post(self, x: int, y: int) -> None: ...\n    def type(self, index: str | int) -> Literal[\"cascade\", \"checkbutton\", \"command\", \"radiobutton\", \"separator\"]: ...\n    def unpost(self) -> None: ...\n    def xposition(self, index: str | int) -> int: ...\n    def yposition(self, index: str | int) -> int: ...\n\nclass Menubutton(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        bitmap: str = \"\",\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = \"none\",\n        cursor: _Cursor = \"\",\n        direction: Literal[\"above\", \"below\", \"left\", \"right\", \"flush\"] = \"below\",\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        height: float | str = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = 0,\n        image: _Image | str = \"\",\n        indicatoron: bool = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        menu: Menu = ...,\n        name: str = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = 0,\n        text: float | str = \"\",\n        textvariable: Variable = ...,\n        underline: int = -1,\n        width: float | str = 0,\n        wraplength: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        bitmap: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        cursor: _Cursor = ...,\n        direction: Literal[\"above\", \"below\", \"left\", \"right\", \"flush\"] = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        image: _Image | str = ...,\n        indicatoron: bool = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        menu: Menu = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        underline: int = ...,\n        width: float | str = ...,\n        wraplength: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass Message(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = \"center\",\n        aspect: int = 150,\n        background: str = ...,\n        bd: float | str = 1,\n        bg: str = ...,\n        border: float | str = 1,\n        borderwidth: float | str = 1,\n        cursor: _Cursor = \"\",\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = 0,\n        justify: Literal[\"left\", \"center\", \"right\"] = \"left\",\n        name: str = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = 0,\n        text: float | str = \"\",\n        textvariable: Variable = ...,\n        # there's width but no height\n        width: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        aspect: int = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        width: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass Radiobutton(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = \"center\",\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        bitmap: str = \"\",\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        command: str | Callable[[], Any] = \"\",\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = \"none\",\n        cursor: _Cursor = \"\",\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        height: float | str = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = 1,\n        image: _Image | str = \"\",\n        indicatoron: bool = True,\n        justify: Literal[\"left\", \"center\", \"right\"] = \"center\",\n        name: str = ...,\n        offrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        overrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\", \"\"] = \"\",\n        padx: float | str = 1,\n        pady: float | str = 1,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        selectcolor: str = ...,\n        selectimage: _Image | str = \"\",\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        text: float | str = \"\",\n        textvariable: Variable = ...,\n        tristateimage: _Image | str = \"\",\n        tristatevalue: Any = \"\",\n        underline: int = -1,\n        value: Any = \"\",\n        variable: Variable | Literal[\"\"] = ...,\n        width: float | str = 0,\n        wraplength: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activebackground: str = ...,\n        activeforeground: str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        bitmap: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        command: str | Callable[[], Any] = ...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        cursor: _Cursor = ...,\n        disabledforeground: str = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        image: _Image | str = ...,\n        indicatoron: bool = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        offrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        overrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\", \"\"] = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        selectcolor: str = ...,\n        selectimage: _Image | str = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: Variable = ...,\n        tristateimage: _Image | str = ...,\n        tristatevalue: Any = ...,\n        underline: int = ...,\n        value: Any = ...,\n        variable: Variable | Literal[\"\"] = ...,\n        width: float | str = ...,\n        wraplength: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def deselect(self) -> None: ...\n    def flash(self) -> None: ...\n    def invoke(self) -> Any: ...\n    def select(self) -> None: ...\n\nclass Scale(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        activebackground: str = ...,\n        background: str = ...,\n        bd: float | str = 1,\n        bg: str = ...,\n        bigincrement: float = 0.0,\n        border: float | str = 1,\n        borderwidth: float | str = 1,\n        # don't know why the callback gets string instead of float\n        command: str | Callable[[str], object] = \"\",\n        cursor: _Cursor = \"\",\n        digits: int = 0,\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        from_: float = 0.0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        label: str = \"\",\n        length: float | str = 100,\n        name: str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"vertical\",\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        repeatdelay: int = 300,\n        repeatinterval: int = 100,\n        resolution: float = 1.0,\n        showvalue: bool = True,\n        sliderlength: float | str = 30,\n        sliderrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"raised\",\n        state: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        tickinterval: float = 0.0,\n        to: float = 100.0,\n        troughcolor: str = ...,\n        variable: IntVar | DoubleVar = ...,\n        width: float | str = 15,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activebackground: str = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        bigincrement: float = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        command: str | Callable[[str], object] = ...,\n        cursor: _Cursor = ...,\n        digits: int = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        from_: float = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        label: str = ...,\n        length: float | str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        repeatdelay: int = ...,\n        repeatinterval: int = ...,\n        resolution: float = ...,\n        showvalue: bool = ...,\n        sliderlength: float | str = ...,\n        sliderrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        state: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        tickinterval: float = ...,\n        to: float = ...,\n        troughcolor: str = ...,\n        variable: IntVar | DoubleVar = ...,\n        width: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def get(self) -> float: ...\n    def set(self, value) -> None: ...\n    def coords(self, value: float | None = None) -> tuple[int, int]: ...\n    def identify(self, x, y) -> Literal[\"\", \"slider\", \"trough1\", \"trough2\"]: ...\n\nclass Scrollbar(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        activebackground: str = ...,\n        activerelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"raised\",\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        # There are many ways how the command may get called. Search for\n        # 'SCROLLING COMMANDS' in scrollbar man page. There doesn't seem to\n        # be any way to specify an overloaded callback function, so we say\n        # that it can take any args while it can't in reality.\n        command: Callable[..., tuple[float, float] | None] | str = \"\",\n        cursor: _Cursor = \"\",\n        elementborderwidth: float | str = -1,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = 0,\n        jump: bool = False,\n        name: str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"vertical\",\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        repeatdelay: int = 300,\n        repeatinterval: int = 100,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        troughcolor: str = ...,\n        width: float | str = ...,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activebackground: str = ...,\n        activerelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        command: Callable[..., tuple[float, float] | None] | str = ...,\n        cursor: _Cursor = ...,\n        elementborderwidth: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        jump: bool = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        repeatdelay: int = ...,\n        repeatinterval: int = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        troughcolor: str = ...,\n        width: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def activate(self, index=None): ...\n    def delta(self, deltax: int, deltay: int) -> float: ...\n    def fraction(self, x: int, y: int) -> float: ...\n    def identify(self, x: int, y: int) -> Literal[\"arrow1\", \"arrow2\", \"slider\", \"trough1\", \"trough2\", \"\"]: ...\n    def get(self) -> tuple[float, float, float, float] | tuple[float, float]: ...\n    def set(self, first: float | str, last: float | str) -> None: ...\n\n_WhatToCount: TypeAlias = Literal[\n    \"chars\", \"displaychars\", \"displayindices\", \"displaylines\", \"indices\", \"lines\", \"xpixels\", \"ypixels\"\n]\n\nclass Text(Widget, XView, YView):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        autoseparators: bool = True,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        blockcursor: bool = False,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = \"xterm\",\n        endline: int | Literal[\"\"] = \"\",\n        exportselection: bool = True,\n        fg: str = ...,\n        font: _FontDescription = \"TkFixedFont\",\n        foreground: str = ...,\n        # width is always int, but height is allowed to be screen units.\n        # This doesn't make any sense to me, and this isn't documented.\n        # The docs seem to say that both should be integers.\n        height: float | str = 24,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        inactiveselectbackground: str = ...,\n        insertbackground: str = ...,\n        insertborderwidth: float | str = 0,\n        insertofftime: int = 300,\n        insertontime: int = 600,\n        insertunfocussed: Literal[\"none\", \"hollow\", \"solid\"] = \"none\",\n        insertwidth: float | str = ...,\n        maxundo: int = 0,\n        name: str = ...,\n        padx: float | str = 1,\n        pady: float | str = 1,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        selectbackground: str = ...,\n        selectborderwidth: float | str = ...,\n        selectforeground: str = ...,\n        setgrid: bool = False,\n        spacing1: float | str = 0,\n        spacing2: float | str = 0,\n        spacing3: float | str = 0,\n        startline: int | Literal[\"\"] = \"\",\n        state: Literal[\"normal\", \"disabled\"] = \"normal\",\n        # Literal inside Tuple doesn't actually work\n        tabs: float | str | tuple[float | str, ...] = \"\",\n        tabstyle: Literal[\"tabular\", \"wordprocessor\"] = \"tabular\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        undo: bool = False,\n        width: int = 80,\n        wrap: Literal[\"none\", \"char\", \"word\"] = \"char\",\n        xscrollcommand: str | Callable[[float, float], object] = \"\",\n        yscrollcommand: str | Callable[[float, float], object] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        autoseparators: bool = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        blockcursor: bool = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = ...,\n        endline: int | Literal[\"\"] = ...,\n        exportselection: bool = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        inactiveselectbackground: str = ...,\n        insertbackground: str = ...,\n        insertborderwidth: float | str = ...,\n        insertofftime: int = ...,\n        insertontime: int = ...,\n        insertunfocussed: Literal[\"none\", \"hollow\", \"solid\"] = ...,\n        insertwidth: float | str = ...,\n        maxundo: int = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        selectbackground: str = ...,\n        selectborderwidth: float | str = ...,\n        selectforeground: str = ...,\n        setgrid: bool = ...,\n        spacing1: float | str = ...,\n        spacing2: float | str = ...,\n        spacing3: float | str = ...,\n        startline: int | Literal[\"\"] = ...,\n        state: Literal[\"normal\", \"disabled\"] = ...,\n        tabs: float | str | tuple[float | str, ...] = ...,\n        tabstyle: Literal[\"tabular\", \"wordprocessor\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        undo: bool = ...,\n        width: int = ...,\n        wrap: Literal[\"none\", \"char\", \"word\"] = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n        yscrollcommand: str | Callable[[float, float], object] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def bbox(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> tuple[int, int, int, int] | None: ...  # type: ignore[override]\n    def compare(\n        self,\n        index1: str | float | _tkinter.Tcl_Obj | Widget,\n        op: Literal[\"<\", \"<=\", \"==\", \">=\", \">\", \"!=\"],\n        index2: str | float | _tkinter.Tcl_Obj | Widget,\n    ) -> bool: ...\n    if sys.version_info >= (3, 13):\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            *,\n            return_ints: Literal[True],\n        ) -> int: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg: _WhatToCount | Literal[\"update\"],\n            /,\n            *,\n            return_ints: Literal[True],\n        ) -> int: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: Literal[\"update\"],\n            arg2: _WhatToCount,\n            /,\n            *,\n            return_ints: Literal[True],\n        ) -> int: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: _WhatToCount,\n            arg2: Literal[\"update\"],\n            /,\n            *,\n            return_ints: Literal[True],\n        ) -> int: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: _WhatToCount,\n            arg2: _WhatToCount,\n            /,\n            *,\n            return_ints: Literal[True],\n        ) -> tuple[int, int]: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: _WhatToCount | Literal[\"update\"],\n            arg2: _WhatToCount | Literal[\"update\"],\n            arg3: _WhatToCount | Literal[\"update\"],\n            /,\n            *args: _WhatToCount | Literal[\"update\"],\n            return_ints: Literal[True],\n        ) -> tuple[int, ...]: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            *,\n            return_ints: Literal[False] = False,\n        ) -> tuple[int] | None: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg: _WhatToCount | Literal[\"update\"],\n            /,\n            *,\n            return_ints: Literal[False] = False,\n        ) -> tuple[int] | None: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: Literal[\"update\"],\n            arg2: _WhatToCount,\n            /,\n            *,\n            return_ints: Literal[False] = False,\n        ) -> int | None: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: _WhatToCount,\n            arg2: Literal[\"update\"],\n            /,\n            *,\n            return_ints: Literal[False] = False,\n        ) -> int | None: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: _WhatToCount,\n            arg2: _WhatToCount,\n            /,\n            *,\n            return_ints: Literal[False] = False,\n        ) -> tuple[int, int]: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: _WhatToCount | Literal[\"update\"],\n            arg2: _WhatToCount | Literal[\"update\"],\n            arg3: _WhatToCount | Literal[\"update\"],\n            /,\n            *args: _WhatToCount | Literal[\"update\"],\n            return_ints: Literal[False] = False,\n        ) -> tuple[int, ...]: ...\n    else:\n        @overload\n        def count(\n            self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget\n        ) -> tuple[int] | None: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg: _WhatToCount | Literal[\"update\"],\n            /,\n        ) -> tuple[int] | None: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: Literal[\"update\"],\n            arg2: _WhatToCount,\n            /,\n        ) -> int | None: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: _WhatToCount,\n            arg2: Literal[\"update\"],\n            /,\n        ) -> int | None: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: _WhatToCount,\n            arg2: _WhatToCount,\n            /,\n        ) -> tuple[int, int]: ...\n        @overload\n        def count(\n            self,\n            index1: str | float | _tkinter.Tcl_Obj | Widget,\n            index2: str | float | _tkinter.Tcl_Obj | Widget,\n            arg1: _WhatToCount | Literal[\"update\"],\n            arg2: _WhatToCount | Literal[\"update\"],\n            arg3: _WhatToCount | Literal[\"update\"],\n            /,\n            *args: _WhatToCount | Literal[\"update\"],\n        ) -> tuple[int, ...]: ...\n\n    @overload\n    def debug(self, boolean: None = None) -> bool: ...\n    @overload\n    def debug(self, boolean: bool) -> None: ...\n    def delete(\n        self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget | None = None\n    ) -> None: ...\n    def dlineinfo(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> tuple[int, int, int, int, int] | None: ...\n    @overload\n    def dump(\n        self,\n        index1: str | float | _tkinter.Tcl_Obj | Widget,\n        index2: str | float | _tkinter.Tcl_Obj | Widget | None = None,\n        command: None = None,\n        *,\n        all: bool = ...,\n        image: bool = ...,\n        mark: bool = ...,\n        tag: bool = ...,\n        text: bool = ...,\n        window: bool = ...,\n    ) -> list[tuple[str, str, str]]: ...\n    @overload\n    def dump(\n        self,\n        index1: str | float | _tkinter.Tcl_Obj | Widget,\n        index2: str | float | _tkinter.Tcl_Obj | Widget | None,\n        command: Callable[[str, str, str], object] | str,\n        *,\n        all: bool = ...,\n        image: bool = ...,\n        mark: bool = ...,\n        tag: bool = ...,\n        text: bool = ...,\n        window: bool = ...,\n    ) -> None: ...\n    @overload\n    def dump(\n        self,\n        index1: str | float | _tkinter.Tcl_Obj | Widget,\n        index2: str | float | _tkinter.Tcl_Obj | Widget | None = None,\n        *,\n        command: Callable[[str, str, str], object] | str,\n        all: bool = ...,\n        image: bool = ...,\n        mark: bool = ...,\n        tag: bool = ...,\n        text: bool = ...,\n        window: bool = ...,\n    ) -> None: ...\n    def edit(self, *args): ...  # docstring says \"Internal method\"\n    @overload\n    def edit_modified(self, arg: None = None) -> bool: ...  # actually returns Literal[0, 1]\n    @overload\n    def edit_modified(self, arg: bool) -> None: ...  # actually returns empty string\n    def edit_redo(self) -> None: ...  # actually returns empty string\n    def edit_reset(self) -> None: ...  # actually returns empty string\n    def edit_separator(self) -> None: ...  # actually returns empty string\n    def edit_undo(self) -> None: ...  # actually returns empty string\n    def get(\n        self, index1: str | float | _tkinter.Tcl_Obj | Widget, index2: str | float | _tkinter.Tcl_Obj | Widget | None = None\n    ) -> str: ...\n    @overload\n    def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal[\"image\", \"name\"]) -> str: ...\n    @overload\n    def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal[\"padx\", \"pady\"]) -> int: ...\n    @overload\n    def image_cget(\n        self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal[\"align\"]\n    ) -> Literal[\"baseline\", \"bottom\", \"center\", \"top\"]: ...\n    @overload\n    def image_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: str) -> Any: ...\n    @overload\n    def image_configure(\n        self, index: str | float | _tkinter.Tcl_Obj | Widget, cnf: str\n    ) -> tuple[str, str, str, str, str | int]: ...\n    @overload\n    def image_configure(\n        self,\n        index: str | float | _tkinter.Tcl_Obj | Widget,\n        cnf: dict[str, Any] | None = None,\n        *,\n        align: Literal[\"baseline\", \"bottom\", \"center\", \"top\"] = ...,\n        image: _Image | str = ...,\n        name: str = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, str, str | int]] | None: ...\n    def image_create(\n        self,\n        index: str | float | _tkinter.Tcl_Obj | Widget,\n        cnf: dict[str, Any] | None = {},\n        *,\n        align: Literal[\"baseline\", \"bottom\", \"center\", \"top\"] = ...,\n        image: _Image | str = ...,\n        name: str = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n    ) -> str: ...\n    def image_names(self) -> tuple[str, ...]: ...\n    def index(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> str: ...\n    def insert(\n        self, index: str | float | _tkinter.Tcl_Obj | Widget, chars: str, *args: str | list[str] | tuple[str, ...]\n    ) -> None: ...\n    @overload\n    def mark_gravity(self, markName: str, direction: None = None) -> Literal[\"left\", \"right\"]: ...\n    @overload\n    def mark_gravity(self, markName: str, direction: Literal[\"left\", \"right\"]) -> None: ...  # actually returns empty string\n    def mark_names(self) -> tuple[str, ...]: ...\n    def mark_set(self, markName: str, index: str | float | _tkinter.Tcl_Obj | Widget) -> None: ...\n    def mark_unset(self, *markNames: str) -> None: ...\n    def mark_next(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> str | None: ...\n    def mark_previous(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> str | None: ...\n    # **kw of peer_create is same as the kwargs of Text.__init__\n    def peer_create(self, newPathName: str | Text, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def peer_names(self) -> tuple[_tkinter.Tcl_Obj, ...]: ...\n    def replace(\n        self,\n        index1: str | float | _tkinter.Tcl_Obj | Widget,\n        index2: str | float | _tkinter.Tcl_Obj | Widget,\n        chars: str,\n        *args: str | list[str] | tuple[str, ...],\n    ) -> None: ...\n    def scan_mark(self, x: int, y: int) -> None: ...\n    def scan_dragto(self, x: int, y: int) -> None: ...\n    def search(\n        self,\n        pattern: str,\n        index: str | float | _tkinter.Tcl_Obj | Widget,\n        stopindex: str | float | _tkinter.Tcl_Obj | Widget | None = None,\n        forwards: bool | None = None,\n        backwards: bool | None = None,\n        exact: bool | None = None,\n        regexp: bool | None = None,\n        nocase: bool | None = None,\n        count: Variable | None = None,\n        elide: bool | None = None,\n    ) -> str: ...  # returns empty string for not found\n    def see(self, index: str | float | _tkinter.Tcl_Obj | Widget) -> None: ...\n    def tag_add(\n        self, tagName: str, index1: str | float | _tkinter.Tcl_Obj | Widget, *args: str | float | _tkinter.Tcl_Obj | Widget\n    ) -> None: ...\n    # tag_bind stuff is very similar to Canvas\n    @overload\n    def tag_bind(\n        self,\n        tagName: str,\n        sequence: str | None,\n        func: Callable[[Event[Text]], object] | None,\n        add: Literal[\"\", \"+\"] | bool | None = None,\n    ) -> str: ...\n    @overload\n    def tag_bind(self, tagName: str, sequence: str | None, func: str, add: Literal[\"\", \"+\"] | bool | None = None) -> None: ...\n    def tag_unbind(self, tagName: str, sequence: str, funcid: str | None = None) -> None: ...\n    # allowing any string for cget instead of just Literals because there's no other way to look up tag options\n    def tag_cget(self, tagName: str, option: str): ...\n    @overload\n    def tag_configure(\n        self,\n        tagName: str,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bgstipple: str = ...,\n        borderwidth: float | str = ...,\n        border: float | str = ...,  # alias for borderwidth\n        elide: bool = ...,\n        fgstipple: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        justify: Literal[\"left\", \"right\", \"center\"] = ...,\n        lmargin1: float | str = ...,\n        lmargin2: float | str = ...,\n        lmargincolor: str = ...,\n        offset: float | str = ...,\n        overstrike: bool = ...,\n        overstrikefg: str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        rmargin: float | str = ...,\n        rmargincolor: str = ...,\n        selectbackground: str = ...,\n        selectforeground: str = ...,\n        spacing1: float | str = ...,\n        spacing2: float | str = ...,\n        spacing3: float | str = ...,\n        tabs: Any = ...,  # the exact type is kind of complicated, see manual page\n        tabstyle: Literal[\"tabular\", \"wordprocessor\"] = ...,\n        underline: bool = ...,\n        underlinefg: str = ...,\n        wrap: Literal[\"none\", \"char\", \"word\"] = ...,  # be careful with \"none\" vs None\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def tag_configure(self, tagName: str, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    tag_config = tag_configure\n    def tag_delete(self, first_tag_name: str, /, *tagNames: str) -> None: ...  # error if no tag names given\n    def tag_lower(self, tagName: str, belowThis: str | None = None) -> None: ...\n    def tag_names(self, index: str | float | _tkinter.Tcl_Obj | Widget | None = None) -> tuple[str, ...]: ...\n    def tag_nextrange(\n        self,\n        tagName: str,\n        index1: str | float | _tkinter.Tcl_Obj | Widget,\n        index2: str | float | _tkinter.Tcl_Obj | Widget | None = None,\n    ) -> tuple[str, str] | tuple[()]: ...\n    def tag_prevrange(\n        self,\n        tagName: str,\n        index1: str | float | _tkinter.Tcl_Obj | Widget,\n        index2: str | float | _tkinter.Tcl_Obj | Widget | None = None,\n    ) -> tuple[str, str] | tuple[()]: ...\n    def tag_raise(self, tagName: str, aboveThis: str | None = None) -> None: ...\n    def tag_ranges(self, tagName: str) -> tuple[_tkinter.Tcl_Obj, ...]: ...\n    # tag_remove and tag_delete are different\n    def tag_remove(\n        self,\n        tagName: str,\n        index1: str | float | _tkinter.Tcl_Obj | Widget,\n        index2: str | float | _tkinter.Tcl_Obj | Widget | None = None,\n    ) -> None: ...\n    @overload\n    def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal[\"padx\", \"pady\"]) -> int: ...\n    @overload\n    def window_cget(\n        self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal[\"stretch\"]\n    ) -> bool: ...  # actually returns Literal[0, 1]\n    @overload\n    def window_cget(\n        self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal[\"align\"]\n    ) -> Literal[\"baseline\", \"bottom\", \"center\", \"top\"]: ...\n    @overload  # window is set to a widget, but read as the string name.\n    def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: Literal[\"create\", \"window\"]) -> str: ...\n    @overload\n    def window_cget(self, index: str | float | _tkinter.Tcl_Obj | Widget, option: str) -> Any: ...\n    @overload\n    def window_configure(\n        self, index: str | float | _tkinter.Tcl_Obj | Widget, cnf: str\n    ) -> tuple[str, str, str, str, str | int]: ...\n    @overload\n    def window_configure(\n        self,\n        index: str | float | _tkinter.Tcl_Obj | Widget,\n        cnf: dict[str, Any] | None = None,\n        *,\n        align: Literal[\"baseline\", \"bottom\", \"center\", \"top\"] = ...,\n        create: str = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        stretch: bool | Literal[0, 1] = ...,\n        window: Misc | str = ...,\n    ) -> dict[str, tuple[str, str, str, str, str | int]] | None: ...\n    window_config = window_configure\n    def window_create(\n        self,\n        index: str | float | _tkinter.Tcl_Obj | Widget,\n        cnf: dict[str, Any] | None = {},\n        *,\n        align: Literal[\"baseline\", \"bottom\", \"center\", \"top\"] = ...,\n        create: str = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        stretch: bool | Literal[0, 1] = ...,\n        window: Misc | str = ...,\n    ) -> None: ...\n    def window_names(self) -> tuple[str, ...]: ...\n    def yview_pickplace(self, *what): ...  # deprecated\n\nclass _setit:\n    def __init__(self, var, value, callback=None) -> None: ...\n    def __call__(self, *args) -> None: ...\n\n# manual page: tk_optionMenu\nclass OptionMenu(Menubutton):\n    menuname: Incomplete\n    def __init__(\n        # differs from other widgets\n        self,\n        master: Misc | None,\n        variable: StringVar,\n        value: str,\n        *values: str,\n        # kwarg only from now on\n        command: Callable[[StringVar], object] | None = ...,\n    ) -> None: ...\n    # configure, config, cget are inherited from Menubutton\n    # destroy and __getitem__ are overridden, signature does not change\n\n# This matches tkinter's image classes (PhotoImage and BitmapImage)\n# and PIL's tkinter-compatible class (PIL.ImageTk.PhotoImage),\n# but not a plain PIL image that isn't tkinter compatible.\n# The reason is that PIL has width and height attributes, not methods.\n@type_check_only\nclass _Image(Protocol):\n    def width(self) -> int: ...\n    def height(self) -> int: ...\n\n@type_check_only\nclass _BitmapImageLike(_Image): ...\n\n@type_check_only\nclass _PhotoImageLike(_Image): ...\n\nclass Image(_Image):\n    name: Incomplete\n    tk: _tkinter.TkappType\n    def __init__(self, imgtype, name=None, cnf={}, master: Misc | _tkinter.TkappType | None = None, **kw) -> None: ...\n    def __del__(self) -> None: ...\n    def __setitem__(self, key, value) -> None: ...\n    def __getitem__(self, key): ...\n    configure: Incomplete\n    config: Incomplete\n    def type(self): ...\n\nclass PhotoImage(Image, _PhotoImageLike):\n    # This should be kept in sync with PIL.ImageTK.PhotoImage.__init__()\n    def __init__(\n        self,\n        name: str | None = None,\n        cnf: dict[str, Any] = {},\n        master: Misc | _tkinter.TkappType | None = None,\n        *,\n        data: str | bytes = ...,  # not same as data argument of put()\n        format: str = ...,\n        file: StrOrBytesPath = ...,\n        gamma: float = ...,\n        height: int = ...,\n        palette: int | str = ...,\n        width: int = ...,\n    ) -> None: ...\n    def configure(\n        self,\n        *,\n        data: str | bytes = ...,\n        format: str = ...,\n        file: StrOrBytesPath = ...,\n        gamma: float = ...,\n        height: int = ...,\n        palette: int | str = ...,\n        width: int = ...,\n    ) -> None: ...\n    config = configure\n    def blank(self) -> None: ...\n    def cget(self, option: str) -> str: ...\n    def __getitem__(self, key: str) -> str: ...  # always string: image['height'] can be '0'\n    if sys.version_info >= (3, 13):\n        def copy(\n            self,\n            *,\n            from_coords: Iterable[int] | None = None,\n            zoom: int | tuple[int, int] | list[int] | None = None,\n            subsample: int | tuple[int, int] | list[int] | None = None,\n        ) -> PhotoImage: ...\n        def subsample(self, x: int, y: Literal[\"\"] = \"\", *, from_coords: Iterable[int] | None = None) -> PhotoImage: ...\n        def zoom(self, x: int, y: Literal[\"\"] = \"\", *, from_coords: Iterable[int] | None = None) -> PhotoImage: ...\n        def copy_replace(\n            self,\n            sourceImage: PhotoImage | str,\n            *,\n            from_coords: Iterable[int] | None = None,\n            to: Iterable[int] | None = None,\n            shrink: bool = False,\n            zoom: int | tuple[int, int] | list[int] | None = None,\n            subsample: int | tuple[int, int] | list[int] | None = None,\n            # `None` defaults to overlay.\n            compositingrule: Literal[\"overlay\", \"set\"] | None = None,\n        ) -> None: ...\n    else:\n        def copy(self) -> PhotoImage: ...\n        def zoom(self, x: int, y: int | Literal[\"\"] = \"\") -> PhotoImage: ...\n        def subsample(self, x: int, y: int | Literal[\"\"] = \"\") -> PhotoImage: ...\n\n    def get(self, x: int, y: int) -> tuple[int, int, int]: ...\n    def put(\n        self,\n        data: (\n            str\n            | bytes\n            | list[str]\n            | list[list[str]]\n            | list[tuple[str, ...]]\n            | tuple[str, ...]\n            | tuple[list[str], ...]\n            | tuple[tuple[str, ...], ...]\n        ),\n        to: tuple[int, int] | tuple[int, int, int, int] | None = None,\n    ) -> None: ...\n    if sys.version_info >= (3, 13):\n        def read(\n            self,\n            filename: StrOrBytesPath,\n            format: str | None = None,\n            *,\n            from_coords: Iterable[int] | None = None,\n            to: Iterable[int] | None = None,\n            shrink: bool = False,\n        ) -> None: ...\n        def write(\n            self,\n            filename: StrOrBytesPath,\n            format: str | None = None,\n            from_coords: Iterable[int] | None = None,\n            *,\n            background: str | None = None,\n            grayscale: bool = False,\n        ) -> None: ...\n        @overload\n        def data(\n            self, format: str, *, from_coords: Iterable[int] | None = None, background: str | None = None, grayscale: bool = False\n        ) -> bytes: ...\n        @overload\n        def data(\n            self,\n            format: None = None,\n            *,\n            from_coords: Iterable[int] | None = None,\n            background: str | None = None,\n            grayscale: bool = False,\n        ) -> tuple[str, ...]: ...\n\n    else:\n        def write(\n            self, filename: StrOrBytesPath, format: str | None = None, from_coords: tuple[int, int] | None = None\n        ) -> None: ...\n\n    def transparency_get(self, x: int, y: int) -> bool: ...\n    def transparency_set(self, x: int, y: int, boolean: bool) -> None: ...\n\nclass BitmapImage(Image, _BitmapImageLike):\n    # This should be kept in sync with PIL.ImageTK.BitmapImage.__init__()\n    def __init__(\n        self,\n        name=None,\n        cnf: dict[str, Any] = {},\n        master: Misc | _tkinter.TkappType | None = None,\n        *,\n        background: str = ...,\n        data: str | bytes = ...,\n        file: StrOrBytesPath = ...,\n        foreground: str = ...,\n        maskdata: str = ...,\n        maskfile: StrOrBytesPath = ...,\n    ) -> None: ...\n\ndef image_names() -> tuple[str, ...]: ...\ndef image_types() -> tuple[str, ...]: ...\n\nclass Spinbox(Widget, XView):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        activebackground: str = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        buttonbackground: str = ...,\n        buttoncursor: _Cursor = \"\",\n        buttondownrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        buttonuprelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        # percent substitutions don't seem to be supported, it's similar to Entry's validation stuff\n        command: Callable[[], object] | str | list[str] | tuple[str, ...] = \"\",\n        cursor: _Cursor = \"xterm\",\n        disabledbackground: str = ...,\n        disabledforeground: str = ...,\n        exportselection: bool = True,\n        fg: str = ...,\n        font: _FontDescription = \"TkTextFont\",\n        foreground: str = ...,\n        format: str = \"\",\n        from_: float = 0.0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        increment: float = 1.0,\n        insertbackground: str = ...,\n        insertborderwidth: float | str = 0,\n        insertofftime: int = 300,\n        insertontime: int = 600,\n        insertwidth: float | str = ...,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",\n        invcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",\n        justify: Literal[\"left\", \"center\", \"right\"] = \"left\",\n        name: str = ...,\n        readonlybackground: str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"sunken\",\n        repeatdelay: int = 400,\n        repeatinterval: int = 100,\n        selectbackground: str = ...,\n        selectborderwidth: float | str = ...,\n        selectforeground: str = ...,\n        state: Literal[\"normal\", \"disabled\", \"readonly\"] = \"normal\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        textvariable: Variable = ...,\n        to: float = 0.0,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = \"none\",\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",\n        vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = 20,\n        wrap: bool = False,\n        xscrollcommand: str | Callable[[float, float], object] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        activebackground: str = ...,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        buttonbackground: str = ...,\n        buttoncursor: _Cursor = ...,\n        buttondownrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        buttonuprelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        command: Callable[[], object] | str | list[str] | tuple[str, ...] = ...,\n        cursor: _Cursor = ...,\n        disabledbackground: str = ...,\n        disabledforeground: str = ...,\n        exportselection: bool = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        format: str = ...,\n        from_: float = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        increment: float = ...,\n        insertbackground: str = ...,\n        insertborderwidth: float | str = ...,\n        insertofftime: int = ...,\n        insertontime: int = ...,\n        insertwidth: float | str = ...,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        invcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        readonlybackground: str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        repeatdelay: int = ...,\n        repeatinterval: int = ...,\n        selectbackground: str = ...,\n        selectborderwidth: float | str = ...,\n        selectforeground: str = ...,\n        state: Literal[\"normal\", \"disabled\", \"readonly\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        textvariable: Variable = ...,\n        to: float = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        vcmd: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = ...,\n        wrap: bool = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def bbox(self, index) -> tuple[int, int, int, int] | None: ...  # type: ignore[override]\n    def delete(self, first, last=None) -> Literal[\"\"]: ...\n    def get(self) -> str: ...\n    def icursor(self, index): ...\n    def identify(self, x: int, y: int) -> Literal[\"\", \"buttondown\", \"buttonup\", \"entry\"]: ...\n    def index(self, index: str | int) -> int: ...\n    def insert(self, index: str | int, s: str) -> Literal[\"\"]: ...\n    # spinbox.invoke(\"asdf\") gives error mentioning .invoke(\"none\"), but it's not documented\n    def invoke(self, element: Literal[\"none\", \"buttonup\", \"buttondown\"]) -> Literal[\"\"]: ...\n    def scan(self, *args): ...\n    def scan_mark(self, x): ...\n    def scan_dragto(self, x): ...\n    def selection(self, *args) -> tuple[int, ...]: ...\n    def selection_adjust(self, index): ...\n    def selection_clear(self): ...  # type: ignore[override]\n    def selection_element(self, element=None): ...\n    def selection_from(self, index: int) -> None: ...\n    def selection_present(self) -> None: ...\n    def selection_range(self, start: int, end: int) -> None: ...\n    def selection_to(self, index: int) -> None: ...\n\nclass LabelFrame(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        background: str = ...,\n        bd: float | str = 2,\n        bg: str = ...,\n        border: float | str = 2,\n        borderwidth: float | str = 2,\n        class_: str = \"Labelframe\",  # can't be changed with configure()\n        colormap: Literal[\"new\", \"\"] | Misc = \"\",  # can't be changed with configure()\n        container: bool = False,  # undocumented, can't be changed with configure()\n        cursor: _Cursor = \"\",\n        fg: str = ...,\n        font: _FontDescription = \"TkDefaultFont\",\n        foreground: str = ...,\n        height: float | str = 0,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = 0,\n        # 'ne' and 'en' are valid labelanchors, but only 'ne' is a valid _Anchor.\n        labelanchor: Literal[\"nw\", \"n\", \"ne\", \"en\", \"e\", \"es\", \"se\", \"s\", \"sw\", \"ws\", \"w\", \"wn\"] = \"nw\",\n        labelwidget: Misc = ...,\n        name: str = ...,\n        padx: float | str = 0,\n        pady: float | str = 0,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"groove\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = 0,\n        text: float | str = \"\",\n        visual: str | tuple[str, int] = \"\",  # can't be changed with configure()\n        width: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = ...,\n        fg: str = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: float | str = ...,\n        highlightbackground: str = ...,\n        highlightcolor: str = ...,\n        highlightthickness: float | str = ...,\n        labelanchor: Literal[\"nw\", \"n\", \"ne\", \"en\", \"e\", \"es\", \"se\", \"s\", \"sw\", \"ws\", \"w\", \"wn\"] = ...,\n        labelwidget: Misc = ...,\n        padx: float | str = ...,\n        pady: float | str = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        width: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass PanedWindow(Widget):\n    def __init__(\n        self,\n        master: Misc | None = None,\n        cnf: dict[str, Any] | None = {},\n        *,\n        background: str = ...,\n        bd: float | str = 1,\n        bg: str = ...,\n        border: float | str = 1,\n        borderwidth: float | str = 1,\n        cursor: _Cursor = \"\",\n        handlepad: float | str = 8,\n        handlesize: float | str = 8,\n        height: float | str = \"\",\n        name: str = ...,\n        opaqueresize: bool = True,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"horizontal\",\n        proxybackground: str = \"\",\n        proxyborderwidth: float | str = 2,\n        proxyrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        sashcursor: _Cursor = \"\",\n        sashpad: float | str = 0,\n        sashrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = \"flat\",\n        sashwidth: float | str = 3,\n        showhandle: bool = False,\n        width: float | str = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        bd: float | str = ...,\n        bg: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: _Cursor = ...,\n        handlepad: float | str = ...,\n        handlesize: float | str = ...,\n        height: float | str = ...,\n        opaqueresize: bool = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        proxybackground: str = ...,\n        proxyborderwidth: float | str = ...,\n        proxyrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        sashcursor: _Cursor = ...,\n        sashpad: float | str = ...,\n        sashrelief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        sashwidth: float | str = ...,\n        showhandle: bool = ...,\n        width: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def add(self, child: Widget, **kw) -> None: ...\n    def remove(self, child) -> None: ...\n    forget = remove  # type: ignore[assignment]\n    def identify(self, x: int, y: int): ...\n    def proxy(self, *args) -> tuple[Incomplete, ...]: ...\n    def proxy_coord(self) -> tuple[Incomplete, ...]: ...\n    def proxy_forget(self) -> tuple[Incomplete, ...]: ...\n    def proxy_place(self, x, y) -> tuple[Incomplete, ...]: ...\n    def sash(self, *args) -> tuple[Incomplete, ...]: ...\n    def sash_coord(self, index) -> tuple[Incomplete, ...]: ...\n    def sash_mark(self, index) -> tuple[Incomplete, ...]: ...\n    def sash_place(self, index, x, y) -> tuple[Incomplete, ...]: ...\n    def panecget(self, child, option): ...\n    def paneconfigure(self, tagOrId, cnf=None, **kw): ...\n    paneconfig = paneconfigure\n    def panes(self): ...\n\ndef _test() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/colorchooser.pyi",
    "content": "from tkinter import Misc\nfrom tkinter.commondialog import Dialog\nfrom typing import ClassVar\n\n__all__ = [\"Chooser\", \"askcolor\"]\n\nclass Chooser(Dialog):\n    command: ClassVar[str]\n\ndef askcolor(\n    color: str | bytes | None = None, *, initialcolor: str = ..., parent: Misc = ..., title: str = ...\n) -> tuple[None, None] | tuple[tuple[int, int, int], str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/commondialog.pyi",
    "content": "from collections.abc import Mapping\nfrom tkinter import Misc\nfrom typing import Any, ClassVar\n\n__all__ = [\"Dialog\"]\n\nclass Dialog:\n    command: ClassVar[str | None]\n    master: Misc | None\n    # Types of options are very dynamic. They depend on the command and are\n    # sometimes changed to a different type.\n    options: Mapping[str, Any]\n    def __init__(self, master: Misc | None = None, **options: Any) -> None: ...\n    def show(self, **options: Any) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/constants.pyi",
    "content": "from typing import Final\n\n# These are not actually bools. See #4669\nYES: Final = True\nNO: Final = False\nTRUE: Final = True\nFALSE: Final = False\nON: Final = True\nOFF: Final = False\nN: Final = \"n\"\nS: Final = \"s\"\nW: Final = \"w\"\nE: Final = \"e\"\nNW: Final = \"nw\"\nSW: Final = \"sw\"\nNE: Final = \"ne\"\nSE: Final = \"se\"\nNS: Final = \"ns\"\nEW: Final = \"ew\"\nNSEW: Final = \"nsew\"\nCENTER: Final = \"center\"\nNONE: Final = \"none\"\nX: Final = \"x\"\nY: Final = \"y\"\nBOTH: Final = \"both\"\nLEFT: Final = \"left\"\nTOP: Final = \"top\"\nRIGHT: Final = \"right\"\nBOTTOM: Final = \"bottom\"\nRAISED: Final = \"raised\"\nSUNKEN: Final = \"sunken\"\nFLAT: Final = \"flat\"\nRIDGE: Final = \"ridge\"\nGROOVE: Final = \"groove\"\nSOLID: Final = \"solid\"\nHORIZONTAL: Final = \"horizontal\"\nVERTICAL: Final = \"vertical\"\nNUMERIC: Final = \"numeric\"\nCHAR: Final = \"char\"\nWORD: Final = \"word\"\nBASELINE: Final = \"baseline\"\nINSIDE: Final = \"inside\"\nOUTSIDE: Final = \"outside\"\nSEL: Final = \"sel\"\nSEL_FIRST: Final = \"sel.first\"\nSEL_LAST: Final = \"sel.last\"\nEND: Final = \"end\"\nINSERT: Final = \"insert\"\nCURRENT: Final = \"current\"\nANCHOR: Final = \"anchor\"\nALL: Final = \"all\"\nNORMAL: Final = \"normal\"\nDISABLED: Final = \"disabled\"\nACTIVE: Final = \"active\"\nHIDDEN: Final = \"hidden\"\nCASCADE: Final = \"cascade\"\nCHECKBUTTON: Final = \"checkbutton\"\nCOMMAND: Final = \"command\"\nRADIOBUTTON: Final = \"radiobutton\"\nSEPARATOR: Final = \"separator\"\nSINGLE: Final = \"single\"\nBROWSE: Final = \"browse\"\nMULTIPLE: Final = \"multiple\"\nEXTENDED: Final = \"extended\"\nDOTBOX: Final = \"dotbox\"\nUNDERLINE: Final = \"underline\"\nPIESLICE: Final = \"pieslice\"\nCHORD: Final = \"chord\"\nARC: Final = \"arc\"\nFIRST: Final = \"first\"\nLAST: Final = \"last\"\nBUTT: Final = \"butt\"\nPROJECTING: Final = \"projecting\"\nROUND: Final = \"round\"\nBEVEL: Final = \"bevel\"\nMITER: Final = \"miter\"\nMOVETO: Final = \"moveto\"\nSCROLL: Final = \"scroll\"\nUNITS: Final = \"units\"\nPAGES: Final = \"pages\"\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/dialog.pyi",
    "content": "from collections.abc import Mapping\nfrom tkinter import Widget\nfrom typing import Any, Final\n\n__all__ = [\"Dialog\"]\n\nDIALOG_ICON: Final = \"questhead\"\n\nclass Dialog(Widget):\n    widgetName: str\n    num: int\n    def __init__(self, master=None, cnf: Mapping[str, Any] = {}, **kw) -> None: ...\n    def destroy(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/dnd.pyi",
    "content": "from tkinter import Event, Misc, Tk, Widget\nfrom typing import ClassVar, Protocol, type_check_only\n\n__all__ = [\"dnd_start\", \"DndHandler\"]\n\n@type_check_only\nclass _DndSource(Protocol):\n    def dnd_end(self, target: Widget | None, event: Event[Misc] | None, /) -> None: ...\n\nclass DndHandler:\n    root: ClassVar[Tk | None]\n    def __init__(self, source: _DndSource, event: Event[Misc]) -> None: ...\n    def cancel(self, event: Event[Misc] | None = None) -> None: ...\n    def finish(self, event: Event[Misc] | None, commit: int = 0) -> None: ...\n    def on_motion(self, event: Event[Misc]) -> None: ...\n    def on_release(self, event: Event[Misc]) -> None: ...\n    def __del__(self) -> None: ...\n\ndef dnd_start(source: _DndSource, event: Event[Misc]) -> DndHandler | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/filedialog.pyi",
    "content": "from _typeshed import Incomplete, StrOrBytesPath, StrPath\nfrom collections.abc import Hashable, Iterable\nfrom tkinter import Button, Entry, Event, Frame, Listbox, Misc, Scrollbar, StringVar, Toplevel, commondialog\nfrom typing import IO, ClassVar, Literal\n\n__all__ = [\n    \"FileDialog\",\n    \"LoadFileDialog\",\n    \"SaveFileDialog\",\n    \"Open\",\n    \"SaveAs\",\n    \"Directory\",\n    \"askopenfilename\",\n    \"asksaveasfilename\",\n    \"askopenfilenames\",\n    \"askopenfile\",\n    \"askopenfiles\",\n    \"asksaveasfile\",\n    \"askdirectory\",\n]\n\ndialogstates: dict[Hashable, tuple[str, str]]\n\nclass FileDialog:\n    title: str\n    master: Misc\n    directory: str | None\n    top: Toplevel\n    botframe: Frame\n    selection: Entry\n    filter: Entry\n    midframe: Entry\n    filesbar: Scrollbar\n    files: Listbox\n    dirsbar: Scrollbar\n    dirs: Listbox\n    ok_button: Button\n    filter_button: Button\n    cancel_button: Button\n    def __init__(\n        self, master: Misc, title: str | None = None\n    ) -> None: ...  # title is usually a str or None, but e.g. int doesn't raise en exception either\n    how: str | None\n    def go(self, dir_or_file: StrPath = \".\", pattern: StrPath = \"*\", default: StrPath = \"\", key: Hashable | None = None): ...\n    def quit(self, how: str | None = None) -> None: ...\n    def dirs_double_event(self, event: Event) -> None: ...\n    def dirs_select_event(self, event: Event) -> None: ...\n    def files_double_event(self, event: Event) -> None: ...\n    def files_select_event(self, event: Event) -> None: ...\n    def ok_event(self, event: Event) -> None: ...\n    def ok_command(self) -> None: ...\n    def filter_command(self, event: Event | None = None) -> None: ...\n    def get_filter(self) -> tuple[str, str]: ...\n    def get_selection(self) -> str: ...\n    def cancel_command(self, event: Event | None = None) -> None: ...\n    def set_filter(self, dir: StrPath, pat: StrPath) -> None: ...\n    def set_selection(self, file: StrPath) -> None: ...\n\nclass LoadFileDialog(FileDialog):\n    title: str\n    def ok_command(self) -> None: ...\n\nclass SaveFileDialog(FileDialog):\n    title: str\n    def ok_command(self) -> None: ...\n\nclass _Dialog(commondialog.Dialog): ...\n\nclass Open(_Dialog):\n    command: ClassVar[str]\n\nclass SaveAs(_Dialog):\n    command: ClassVar[str]\n\nclass Directory(commondialog.Dialog):\n    command: ClassVar[str]\n\n# TODO: command kwarg available on macos\ndef asksaveasfilename(\n    *,\n    confirmoverwrite: bool | None = True,\n    defaultextension: str | None = \"\",\n    filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ...,\n    initialdir: StrOrBytesPath | None = ...,\n    initialfile: StrOrBytesPath | None = ...,\n    parent: Misc | None = ...,\n    title: str | None = ...,\n    typevariable: StringVar | str | None = ...,\n) -> str: ...  # can be empty string\ndef askopenfilename(\n    *,\n    defaultextension: str | None = \"\",\n    filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ...,\n    initialdir: StrOrBytesPath | None = ...,\n    initialfile: StrOrBytesPath | None = ...,\n    parent: Misc | None = ...,\n    title: str | None = ...,\n    typevariable: StringVar | str | None = ...,\n) -> str: ...  # can be empty string\ndef askopenfilenames(\n    *,\n    defaultextension: str | None = \"\",\n    filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ...,\n    initialdir: StrOrBytesPath | None = ...,\n    initialfile: StrOrBytesPath | None = ...,\n    parent: Misc | None = ...,\n    title: str | None = ...,\n    typevariable: StringVar | str | None = ...,\n) -> Literal[\"\"] | tuple[str, ...]: ...\ndef askdirectory(\n    *, initialdir: StrOrBytesPath | None = ..., mustexist: bool | None = False, parent: Misc | None = ..., title: str | None = ...\n) -> str: ...  # can be empty string\n\n# TODO: If someone actually uses these, overload to have the actual return type of open(..., mode)\ndef asksaveasfile(\n    mode: str = \"w\",\n    *,\n    confirmoverwrite: bool | None = True,\n    defaultextension: str | None = \"\",\n    filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ...,\n    initialdir: StrOrBytesPath | None = ...,\n    initialfile: StrOrBytesPath | None = ...,\n    parent: Misc | None = ...,\n    title: str | None = ...,\n    typevariable: StringVar | str | None = ...,\n) -> IO[Incomplete] | None: ...\ndef askopenfile(\n    mode: str = \"r\",\n    *,\n    defaultextension: str | None = \"\",\n    filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ...,\n    initialdir: StrOrBytesPath | None = ...,\n    initialfile: StrOrBytesPath | None = ...,\n    parent: Misc | None = ...,\n    title: str | None = ...,\n    typevariable: StringVar | str | None = ...,\n) -> IO[Incomplete] | None: ...\ndef askopenfiles(\n    mode: str = \"r\",\n    *,\n    defaultextension: str | None = \"\",\n    filetypes: Iterable[tuple[str, str | list[str] | tuple[str, ...]]] | None = ...,\n    initialdir: StrOrBytesPath | None = ...,\n    initialfile: StrOrBytesPath | None = ...,\n    parent: Misc | None = ...,\n    title: str | None = ...,\n    typevariable: StringVar | str | None = ...,\n) -> tuple[IO[Incomplete], ...]: ...  # can be empty tuple\ndef test() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/font.pyi",
    "content": "import _tkinter\nimport itertools\nimport sys\nimport tkinter\nfrom typing import Any, ClassVar, Final, Literal, TypedDict, overload, type_check_only\nfrom typing_extensions import TypeAlias, Unpack\n\n__all__ = [\"NORMAL\", \"ROMAN\", \"BOLD\", \"ITALIC\", \"nametofont\", \"Font\", \"families\", \"names\"]\n\nNORMAL: Final = \"normal\"\nROMAN: Final = \"roman\"\nBOLD: Final = \"bold\"\nITALIC: Final = \"italic\"\n\n_FontDescription: TypeAlias = (\n    str  # \"Helvetica 12\"\n    | Font  # A font object constructed in Python\n    | list[Any]  # [\"Helvetica\", 12, BOLD]\n    | tuple[str]  # (\"Liberation Sans\",) needs wrapping in tuple/list to handle spaces\n    # (\"Liberation Sans\", 12) or (\"Liberation Sans\", 12, \"bold\", \"italic\", \"underline\")\n    | tuple[str, int, Unpack[tuple[str, ...]]]  # Any number of trailing options is permitted\n    | tuple[str, int, list[str] | tuple[str, ...]]  # Options can also be passed as list/tuple\n    | _tkinter.Tcl_Obj  # A font object constructed in Tcl\n)\n\n@type_check_only\nclass _FontDict(TypedDict):\n    family: str\n    size: int\n    weight: Literal[\"normal\", \"bold\"]\n    slant: Literal[\"roman\", \"italic\"]\n    underline: bool\n    overstrike: bool\n\n@type_check_only\nclass _MetricsDict(TypedDict):\n    ascent: int\n    descent: int\n    linespace: int\n    fixed: bool\n\nclass Font:\n    name: str\n    delete_font: bool\n    counter: ClassVar[itertools.count[int]]  # undocumented\n    def __init__(\n        self,\n        # In tkinter, 'root' refers to tkinter.Tk by convention, but the code\n        # actually works with any tkinter widget so we use tkinter.Misc.\n        root: tkinter.Misc | None = None,\n        font: _FontDescription | None = None,\n        name: str | None = None,\n        exists: bool = False,\n        *,\n        family: str = ...,\n        size: int = ...,\n        weight: Literal[\"normal\", \"bold\"] = ...,\n        slant: Literal[\"roman\", \"italic\"] = ...,\n        underline: bool = ...,\n        overstrike: bool = ...,\n    ) -> None: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __setitem__(self, key: str, value: Any) -> None: ...\n    @overload\n    def cget(self, option: Literal[\"family\"]) -> str: ...\n    @overload\n    def cget(self, option: Literal[\"size\"]) -> int: ...\n    @overload\n    def cget(self, option: Literal[\"weight\"]) -> Literal[\"normal\", \"bold\"]: ...\n    @overload\n    def cget(self, option: Literal[\"slant\"]) -> Literal[\"roman\", \"italic\"]: ...\n    @overload\n    def cget(self, option: Literal[\"underline\", \"overstrike\"]) -> bool: ...\n    @overload\n    def cget(self, option: str) -> Any: ...\n    __getitem__ = cget\n    @overload\n    def actual(self, option: Literal[\"family\"], displayof: tkinter.Misc | None = None) -> str: ...\n    @overload\n    def actual(self, option: Literal[\"size\"], displayof: tkinter.Misc | None = None) -> int: ...\n    @overload\n    def actual(self, option: Literal[\"weight\"], displayof: tkinter.Misc | None = None) -> Literal[\"normal\", \"bold\"]: ...\n    @overload\n    def actual(self, option: Literal[\"slant\"], displayof: tkinter.Misc | None = None) -> Literal[\"roman\", \"italic\"]: ...\n    @overload\n    def actual(self, option: Literal[\"underline\", \"overstrike\"], displayof: tkinter.Misc | None = None) -> bool: ...\n    @overload\n    def actual(self, option: None, displayof: tkinter.Misc | None = None) -> _FontDict: ...\n    @overload\n    def actual(self, *, displayof: tkinter.Misc | None = None) -> _FontDict: ...\n    def config(\n        self,\n        *,\n        family: str = ...,\n        size: int = ...,\n        weight: Literal[\"normal\", \"bold\"] = ...,\n        slant: Literal[\"roman\", \"italic\"] = ...,\n        underline: bool = ...,\n        overstrike: bool = ...,\n    ) -> _FontDict | None: ...\n    configure = config\n    def copy(self) -> Font: ...\n    @overload\n    def metrics(self, option: Literal[\"ascent\", \"descent\", \"linespace\"], /, *, displayof: tkinter.Misc | None = ...) -> int: ...\n    @overload\n    def metrics(self, option: Literal[\"fixed\"], /, *, displayof: tkinter.Misc | None = ...) -> bool: ...\n    @overload\n    def metrics(self, *, displayof: tkinter.Misc | None = ...) -> _MetricsDict: ...\n    def measure(self, text: str, displayof: tkinter.Misc | None = None) -> int: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __del__(self) -> None: ...\n\ndef families(root: tkinter.Misc | None = None, displayof: tkinter.Misc | None = None) -> tuple[str, ...]: ...\ndef names(root: tkinter.Misc | None = None) -> tuple[str, ...]: ...\n\nif sys.version_info >= (3, 10):\n    def nametofont(name: str, root: tkinter.Misc | None = None) -> Font: ...\n\nelse:\n    def nametofont(name: str) -> Font: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/messagebox.pyi",
    "content": "from tkinter import Misc\nfrom tkinter.commondialog import Dialog\nfrom typing import ClassVar, Final, Literal\n\n__all__ = [\"showinfo\", \"showwarning\", \"showerror\", \"askquestion\", \"askokcancel\", \"askyesno\", \"askyesnocancel\", \"askretrycancel\"]\n\nERROR: Final = \"error\"\nINFO: Final = \"info\"\nQUESTION: Final = \"question\"\nWARNING: Final = \"warning\"\nABORTRETRYIGNORE: Final = \"abortretryignore\"\nOK: Final = \"ok\"\nOKCANCEL: Final = \"okcancel\"\nRETRYCANCEL: Final = \"retrycancel\"\nYESNO: Final = \"yesno\"\nYESNOCANCEL: Final = \"yesnocancel\"\nABORT: Final = \"abort\"\nRETRY: Final = \"retry\"\nIGNORE: Final = \"ignore\"\nCANCEL: Final = \"cancel\"\nYES: Final = \"yes\"\nNO: Final = \"no\"\n\nclass Message(Dialog):\n    command: ClassVar[str]\n\ndef showinfo(\n    title: str | None = None,\n    message: str | None = None,\n    *,\n    detail: str = ...,\n    icon: Literal[\"error\", \"info\", \"question\", \"warning\"] = ...,\n    default: Literal[\"ok\"] = \"ok\",\n    parent: Misc = ...,\n) -> str: ...\ndef showwarning(\n    title: str | None = None,\n    message: str | None = None,\n    *,\n    detail: str = ...,\n    icon: Literal[\"error\", \"info\", \"question\", \"warning\"] = ...,\n    default: Literal[\"ok\"] = \"ok\",\n    parent: Misc = ...,\n) -> str: ...\ndef showerror(\n    title: str | None = None,\n    message: str | None = None,\n    *,\n    detail: str = ...,\n    icon: Literal[\"error\", \"info\", \"question\", \"warning\"] = ...,\n    default: Literal[\"ok\"] = \"ok\",\n    parent: Misc = ...,\n) -> str: ...\ndef askquestion(\n    title: str | None = None,\n    message: str | None = None,\n    *,\n    detail: str = ...,\n    icon: Literal[\"error\", \"info\", \"question\", \"warning\"] = ...,\n    default: Literal[\"yes\", \"no\"] = ...,\n    parent: Misc = ...,\n) -> str: ...\ndef askokcancel(\n    title: str | None = None,\n    message: str | None = None,\n    *,\n    detail: str = ...,\n    icon: Literal[\"error\", \"info\", \"question\", \"warning\"] = ...,\n    default: Literal[\"ok\", \"cancel\"] = ...,\n    parent: Misc = ...,\n) -> bool: ...\ndef askyesno(\n    title: str | None = None,\n    message: str | None = None,\n    *,\n    detail: str = ...,\n    icon: Literal[\"error\", \"info\", \"question\", \"warning\"] = ...,\n    default: Literal[\"yes\", \"no\"] = ...,\n    parent: Misc = ...,\n) -> bool: ...\ndef askyesnocancel(\n    title: str | None = None,\n    message: str | None = None,\n    *,\n    detail: str = ...,\n    icon: Literal[\"error\", \"info\", \"question\", \"warning\"] = ...,\n    default: Literal[\"cancel\", \"yes\", \"no\"] = ...,\n    parent: Misc = ...,\n) -> bool | None: ...\ndef askretrycancel(\n    title: str | None = None,\n    message: str | None = None,\n    *,\n    detail: str = ...,\n    icon: Literal[\"error\", \"info\", \"question\", \"warning\"] = ...,\n    default: Literal[\"retry\", \"cancel\"] = ...,\n    parent: Misc = ...,\n) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/scrolledtext.pyi",
    "content": "from tkinter import Frame, Misc, Scrollbar, Text\n\n__all__ = [\"ScrolledText\"]\n\n# The methods from Pack, Place, and Grid are dynamically added over the parent's impls\nclass ScrolledText(Text):\n    frame: Frame\n    vbar: Scrollbar\n    def __init__(self, master: Misc | None = None, **kwargs) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/simpledialog.pyi",
    "content": "from tkinter import Event, Frame, Misc, Toplevel\n\nclass Dialog(Toplevel):\n    def __init__(self, parent: Misc | None, title: str | None = None) -> None: ...\n    def body(self, master: Frame) -> Misc | None: ...\n    def buttonbox(self) -> None: ...\n    def ok(self, event: Event[Misc] | None = None) -> None: ...\n    def cancel(self, event: Event[Misc] | None = None) -> None: ...\n    def validate(self) -> bool: ...\n    def apply(self) -> None: ...\n\nclass SimpleDialog:\n    def __init__(\n        self,\n        master: Misc | None,\n        text: str = \"\",\n        buttons: list[str] = [],\n        default: int | None = None,\n        cancel: int | None = None,\n        title: str | None = None,\n        class_: str | None = None,\n    ) -> None: ...\n    def go(self) -> int | None: ...\n    def return_event(self, event: Event[Misc]) -> None: ...\n    def wm_delete_window(self) -> None: ...\n    def done(self, num: int) -> None: ...\n\ndef askfloat(\n    title: str | None,\n    prompt: str,\n    *,\n    initialvalue: float | None = ...,\n    minvalue: float | None = ...,\n    maxvalue: float | None = ...,\n    parent: Misc | None = ...,\n) -> float | None: ...\ndef askinteger(\n    title: str | None,\n    prompt: str,\n    *,\n    initialvalue: int | None = ...,\n    minvalue: int | None = ...,\n    maxvalue: int | None = ...,\n    parent: Misc | None = ...,\n) -> int | None: ...\ndef askstring(\n    title: str | None,\n    prompt: str,\n    *,\n    initialvalue: str | None = ...,\n    show: str | None = ...,\n    # minvalue/maxvalue is accepted but not useful.\n    parent: Misc | None = ...,\n) -> str | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/tix.pyi",
    "content": "import tkinter\nfrom _typeshed import Incomplete\nfrom typing import Any, Final\n\nWINDOW: Final = \"window\"\nTEXT: Final = \"text\"\nSTATUS: Final = \"status\"\nIMMEDIATE: Final = \"immediate\"\nIMAGE: Final = \"image\"\nIMAGETEXT: Final = \"imagetext\"\nBALLOON: Final = \"balloon\"\nAUTO: Final = \"auto\"\nACROSSTOP: Final = \"acrosstop\"\n\nASCII: Final = \"ascii\"\nCELL: Final = \"cell\"\nCOLUMN: Final = \"column\"\nDECREASING: Final = \"decreasing\"\nINCREASING: Final = \"increasing\"\nINTEGER: Final = \"integer\"\nMAIN: Final = \"main\"\nMAX: Final = \"max\"\nREAL: Final = \"real\"\nROW: Final = \"row\"\nS_REGION: Final = \"s-region\"\nX_REGION: Final = \"x-region\"\nY_REGION: Final = \"y-region\"\n\n# These should be kept in sync with _tkinter constants, except TCL_ALL_EVENTS which doesn't match ALL_EVENTS\nTCL_DONT_WAIT: Final = 2\nTCL_WINDOW_EVENTS: Final = 4\nTCL_FILE_EVENTS: Final = 8\nTCL_TIMER_EVENTS: Final = 16\nTCL_IDLE_EVENTS: Final = 32\nTCL_ALL_EVENTS: Final = 0\n\nclass tixCommand:\n    def tix_addbitmapdir(self, directory: str) -> None: ...\n    def tix_cget(self, option: str) -> Any: ...\n    def tix_configure(self, cnf: dict[str, Any] | None = None, **kw: Any) -> Any: ...\n    def tix_filedialog(self, dlgclass: str | None = None) -> str: ...\n    def tix_getbitmap(self, name: str) -> str: ...\n    def tix_getimage(self, name: str) -> str: ...\n    def tix_option_get(self, name: str) -> Any: ...\n    def tix_resetoptions(self, newScheme: str, newFontSet: str, newScmPrio: str | None = None) -> None: ...\n\nclass Tk(tkinter.Tk, tixCommand):\n    def __init__(self, screenName: str | None = None, baseName: str | None = None, className: str = \"Tix\") -> None: ...\n\nclass TixWidget(tkinter.Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        widgetName: str | None = None,\n        static_options: list[str] | None = None,\n        cnf: dict[str, Any] = {},\n        kw: dict[str, Any] = {},\n    ) -> None: ...\n    def __getattr__(self, name: str): ...\n    def set_silent(self, value: str) -> None: ...\n    def subwidget(self, name: str) -> tkinter.Widget: ...\n    def subwidgets_all(self) -> list[tkinter.Widget]: ...\n    def config_all(self, option: Any, value: Any) -> None: ...\n    def image_create(self, imgtype: str, cnf: dict[str, Any] = {}, master: tkinter.Widget | None = None, **kw) -> None: ...\n    def image_delete(self, imgname: str) -> None: ...\n\nclass TixSubWidget(TixWidget):\n    def __init__(self, master: tkinter.Widget, name: str, destroy_physically: int = 1, check_intermediate: int = 1) -> None: ...\n\nclass DisplayStyle:\n    def __init__(self, itemtype: str, cnf: dict[str, Any] = {}, *, master: tkinter.Widget | None = None, **kw) -> None: ...\n    def __getitem__(self, key: str): ...\n    def __setitem__(self, key: str, value: Any) -> None: ...\n    def delete(self) -> None: ...\n    def config(self, cnf: dict[str, Any] = {}, **kw): ...\n\nclass Balloon(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def bind_widget(self, widget: tkinter.Widget, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def unbind_widget(self, widget: tkinter.Widget) -> None: ...\n\nclass ButtonBox(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ...\n    def invoke(self, name: str) -> None: ...\n\nclass ComboBox(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def add_history(self, str: str) -> None: ...\n    def append_history(self, str: str) -> None: ...\n    def insert(self, index: int, str: str) -> None: ...\n    def pick(self, index: int) -> None: ...\n\nclass Control(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def decrement(self) -> None: ...\n    def increment(self) -> None: ...\n    def invoke(self) -> None: ...\n\nclass LabelEntry(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n\nclass LabelFrame(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n\nclass Meter(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n\nclass OptionMenu(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def add_command(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def add_separator(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def delete(self, name: str) -> None: ...\n    def disable(self, name: str) -> None: ...\n    def enable(self, name: str) -> None: ...\n\nclass PopupMenu(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def bind_widget(self, widget: tkinter.Widget) -> None: ...\n    def unbind_widget(self, widget: tkinter.Widget) -> None: ...\n    def post_widget(self, widget: tkinter.Widget, x: int, y: int) -> None: ...\n\nclass Select(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ...\n    def invoke(self, name: str) -> None: ...\n\nclass StdButtonBox(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def invoke(self, name: str) -> None: ...\n\nclass DirList(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def chdir(self, dir: str) -> None: ...\n\nclass DirTree(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def chdir(self, dir: str) -> None: ...\n\nclass DirSelectDialog(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def popup(self) -> None: ...\n    def popdown(self) -> None: ...\n\nclass DirSelectBox(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n\nclass ExFileSelectBox(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def filter(self) -> None: ...\n    def invoke(self) -> None: ...\n\nclass FileSelectBox(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def apply_filter(self) -> None: ...\n    def invoke(self) -> None: ...\n\nclass FileEntry(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def invoke(self) -> None: ...\n    def file_dialog(self) -> None: ...\n\nclass HList(TixWidget, tkinter.XView, tkinter.YView):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def add(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ...\n    def add_child(self, parent: str | None = None, cnf: dict[str, Any] = {}, **kw) -> tkinter.Widget: ...\n    def anchor_set(self, entry: str) -> None: ...\n    def anchor_clear(self) -> None: ...\n    # FIXME: Overload, certain combos return, others don't\n    def column_width(self, col: int = 0, width: int | None = None, chars: int | None = None) -> int | None: ...\n    def delete_all(self) -> None: ...\n    def delete_entry(self, entry: str) -> None: ...\n    def delete_offsprings(self, entry: str) -> None: ...\n    def delete_siblings(self, entry: str) -> None: ...\n    def dragsite_set(self, index: int) -> None: ...\n    def dragsite_clear(self) -> None: ...\n    def dropsite_set(self, index: int) -> None: ...\n    def dropsite_clear(self) -> None: ...\n    def header_create(self, col: int, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def header_configure(self, col: int, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ...\n    def header_cget(self, col: int, opt): ...\n    def header_exists(self, col: int) -> bool: ...\n    def header_exist(self, col: int) -> bool: ...\n    def header_delete(self, col: int) -> None: ...\n    def header_size(self, col: int) -> int: ...\n    def hide_entry(self, entry: str) -> None: ...\n    def indicator_create(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def indicator_configure(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ...\n    def indicator_cget(self, entry: str, opt): ...\n    def indicator_exists(self, entry: str) -> bool: ...\n    def indicator_delete(self, entry: str) -> None: ...\n    def indicator_size(self, entry: str) -> int: ...\n    def info_anchor(self) -> str: ...\n    def info_bbox(self, entry: str) -> tuple[int, int, int, int]: ...\n    def info_children(self, entry: str | None = None) -> tuple[str, ...]: ...\n    def info_data(self, entry: str) -> Any: ...\n    def info_dragsite(self) -> str: ...\n    def info_dropsite(self) -> str: ...\n    def info_exists(self, entry: str) -> bool: ...\n    def info_hidden(self, entry: str) -> bool: ...\n    def info_next(self, entry: str) -> str: ...\n    def info_parent(self, entry: str) -> str: ...\n    def info_prev(self, entry: str) -> str: ...\n    def info_selection(self) -> tuple[str, ...]: ...\n    def item_cget(self, entry: str, col: int, opt): ...\n    def item_configure(self, entry: str, col: int, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ...\n    def item_create(self, entry: str, col: int, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def item_exists(self, entry: str, col: int) -> bool: ...\n    def item_delete(self, entry: str, col: int) -> None: ...\n    def entrycget(self, entry: str, opt): ...\n    def entryconfigure(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ...\n    def nearest(self, y: int) -> str: ...\n    def see(self, entry: str) -> None: ...\n    def selection_clear(self, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def selection_includes(self, entry: str) -> bool: ...\n    def selection_set(self, first: str, last: str | None = None) -> None: ...\n    def show_entry(self, entry: str) -> None: ...\n\nclass CheckList(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def autosetmode(self) -> None: ...\n    def close(self, entrypath: str) -> None: ...\n    def getmode(self, entrypath: str) -> str: ...\n    def open(self, entrypath: str) -> None: ...\n    def getselection(self, mode: str = \"on\") -> tuple[str, ...]: ...\n    def getstatus(self, entrypath: str) -> str: ...\n    def setstatus(self, entrypath: str, mode: str = \"on\") -> None: ...\n\nclass Tree(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def autosetmode(self) -> None: ...\n    def close(self, entrypath: str) -> None: ...\n    def getmode(self, entrypath: str) -> str: ...\n    def open(self, entrypath: str) -> None: ...\n    def setmode(self, entrypath: str, mode: str = \"none\") -> None: ...\n\nclass TList(TixWidget, tkinter.XView, tkinter.YView):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def active_set(self, index: int) -> None: ...\n    def active_clear(self) -> None: ...\n    def anchor_set(self, index: int) -> None: ...\n    def anchor_clear(self) -> None: ...\n    def delete(self, from_: int, to: int | None = None) -> None: ...\n    def dragsite_set(self, index: int) -> None: ...\n    def dragsite_clear(self) -> None: ...\n    def dropsite_set(self, index: int) -> None: ...\n    def dropsite_clear(self) -> None: ...\n    def insert(self, index: int, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def info_active(self) -> int: ...\n    def info_anchor(self) -> int: ...\n    def info_down(self, index: int) -> int: ...\n    def info_left(self, index: int) -> int: ...\n    def info_right(self, index: int) -> int: ...\n    def info_selection(self) -> tuple[int, ...]: ...\n    def info_size(self) -> int: ...\n    def info_up(self, index: int) -> int: ...\n    def nearest(self, x: int, y: int) -> int: ...\n    def see(self, index: int) -> None: ...\n    def selection_clear(self, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def selection_includes(self, index: int) -> bool: ...\n    def selection_set(self, first: int, last: int | None = None) -> None: ...\n\nclass PanedWindow(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def delete(self, name: str) -> None: ...\n    def forget(self, name: str) -> None: ...  # type: ignore[override]\n    def panecget(self, entry: str, opt): ...\n    def paneconfigure(self, entry: str, cnf: dict[str, Any] = {}, **kw) -> Incomplete | None: ...\n    def panes(self) -> list[tkinter.Widget]: ...\n\nclass ListNoteBook(TixWidget):\n    def __init__(self, master: tkinter.Widget | None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def page(self, name: str) -> tkinter.Widget: ...\n    def pages(self) -> list[tkinter.Widget]: ...\n    def raise_page(self, name: str) -> None: ...\n\nclass NoteBook(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def add(self, name: str, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def delete(self, name: str) -> None: ...\n    def page(self, name: str) -> tkinter.Widget: ...\n    def pages(self) -> list[tkinter.Widget]: ...\n    def raise_page(self, name: str) -> None: ...\n    def raised(self) -> bool: ...\n\nclass InputOnly(TixWidget):\n    def __init__(self, master: tkinter.Widget | None = None, cnf: dict[str, Any] = {}, **kw) -> None: ...\n\nclass Form:\n    def __setitem__(self, key: str, value: Any) -> None: ...\n    def config(self, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def form(self, cnf: dict[str, Any] = {}, **kw) -> None: ...\n    def check(self) -> bool: ...\n    def forget(self) -> None: ...\n    def grid(self, xsize: int = 0, ysize: int = 0) -> tuple[int, int] | None: ...\n    def info(self, option: str | None = None): ...\n    def slaves(self) -> list[tkinter.Widget]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tkinter/ttk.pyi",
    "content": "import _tkinter\nimport sys\nimport tkinter\nfrom _typeshed import MaybeNone\nfrom collections.abc import Callable, Iterable, Sequence\nfrom tkinter.font import _FontDescription\nfrom typing import Any, Literal, TypedDict, TypeVar, overload, type_check_only\nfrom typing_extensions import Never, ParamSpec, TypeAlias, Unpack\n\n__all__ = [\n    \"Button\",\n    \"Checkbutton\",\n    \"Combobox\",\n    \"Entry\",\n    \"Frame\",\n    \"Label\",\n    \"Labelframe\",\n    \"LabelFrame\",\n    \"Menubutton\",\n    \"Notebook\",\n    \"Panedwindow\",\n    \"PanedWindow\",\n    \"Progressbar\",\n    \"Radiobutton\",\n    \"Scale\",\n    \"Scrollbar\",\n    \"Separator\",\n    \"Sizegrip\",\n    \"Style\",\n    \"Treeview\",\n    \"LabeledScale\",\n    \"OptionMenu\",\n    \"tclobjs_to_py\",\n    \"setup_master\",\n    \"Spinbox\",\n]\n\ndef tclobjs_to_py(adict: dict[Any, Any]) -> dict[Any, Any]: ...\ndef setup_master(master: tkinter.Misc | None = None): ...\n\n_Padding: TypeAlias = (\n    float\n    | str\n    | tuple[float | str]\n    | tuple[float | str, float | str]\n    | tuple[float | str, float | str, float | str]\n    | tuple[float | str, float | str, float | str, float | str]\n)\n\n# Last item (option value to apply) varies between different options so use Any.\n# It could also be any iterable with items matching the tuple, but that case\n# hasn't been added here for consistency with _Padding above.\n_Statespec: TypeAlias = tuple[Unpack[tuple[str, ...]], Any]\n_ImageStatespec: TypeAlias = tuple[Unpack[tuple[str, ...]], tkinter._Image | str]\n_VsapiStatespec: TypeAlias = tuple[Unpack[tuple[str, ...]], int]\n\n_P = ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\n\nclass _Layout(TypedDict, total=False):\n    side: Literal[\"left\", \"right\", \"top\", \"bottom\"]\n    sticky: str  # consists of letters 'n', 's', 'w', 'e', may contain repeats, may be empty\n    unit: Literal[0, 1] | bool\n    children: _LayoutSpec\n    # Note: there seem to be some other undocumented keys sometimes\n\n# This could be any sequence when passed as a parameter but will always be a list when returned.\n_LayoutSpec: TypeAlias = list[tuple[str, _Layout | None]]\n\n# Keep these in sync with the appropriate methods in Style\nclass _ElementCreateImageKwargs(TypedDict, total=False):\n    border: _Padding\n    height: float | str\n    padding: _Padding\n    sticky: str\n    width: float | str\n\n_ElementCreateArgsCrossPlatform: TypeAlias = (\n    # Could be any sequence here but types are not homogenous so just type it as tuple\n    tuple[Literal[\"image\"], tkinter._Image | str, Unpack[tuple[_ImageStatespec, ...]], _ElementCreateImageKwargs]\n    | tuple[Literal[\"from\"], str, str]\n    | tuple[Literal[\"from\"], str]  # (fromelement is optional)\n)\nif sys.platform == \"win32\" and sys.version_info >= (3, 13):\n    class _ElementCreateVsapiKwargsPadding(TypedDict, total=False):\n        padding: _Padding\n\n    class _ElementCreateVsapiKwargsMargin(TypedDict, total=False):\n        padding: _Padding\n\n    class _ElementCreateVsapiKwargsSize(TypedDict):\n        width: float | str\n        height: float | str\n\n    _ElementCreateVsapiKwargsDict: TypeAlias = (\n        _ElementCreateVsapiKwargsPadding | _ElementCreateVsapiKwargsMargin | _ElementCreateVsapiKwargsSize\n    )\n    _ElementCreateArgs: TypeAlias = (  # noqa: Y047  # It doesn't recognise the usage below for whatever reason\n        _ElementCreateArgsCrossPlatform\n        | tuple[Literal[\"vsapi\"], str, int, _ElementCreateVsapiKwargsDict]\n        | tuple[Literal[\"vsapi\"], str, int, _VsapiStatespec, _ElementCreateVsapiKwargsDict]\n    )\nelse:\n    _ElementCreateArgs: TypeAlias = _ElementCreateArgsCrossPlatform\n_ThemeSettingsValue = TypedDict(\n    \"_ThemeSettingsValue\",\n    {\n        \"configure\": dict[str, Any],\n        \"map\": dict[str, Iterable[_Statespec]],\n        \"layout\": _LayoutSpec,\n        \"element create\": _ElementCreateArgs,\n    },\n    total=False,\n)\n_ThemeSettings: TypeAlias = dict[str, _ThemeSettingsValue]\n\nclass Style:\n    master: tkinter.Misc\n    tk: _tkinter.TkappType\n    def __init__(self, master: tkinter.Misc | None = None) -> None: ...\n    # For these methods, values given vary between options. Returned values\n    # seem to be str, but this might not always be the case.\n    @overload\n    def configure(self, style: str) -> dict[str, Any] | None: ...  # Returns None if no configuration.\n    @overload\n    def configure(self, style: str, query_opt: str, **kw: Any) -> Any: ...\n    @overload\n    def configure(self, style: str, query_opt: None = None, **kw: Any) -> None: ...\n    @overload\n    def map(self, style: str, query_opt: str) -> _Statespec: ...\n    @overload\n    def map(self, style: str, query_opt: None = None, **kw: Iterable[_Statespec]) -> dict[str, _Statespec]: ...\n    def lookup(self, style: str, option: str, state: Iterable[str] | None = None, default: Any | None = None) -> Any: ...\n    @overload\n    def layout(self, style: str, layoutspec: _LayoutSpec) -> list[Never]: ...  # Always seems to return an empty list\n    @overload\n    def layout(self, style: str, layoutspec: None = None) -> _LayoutSpec: ...\n    @overload\n    def element_create(\n        self,\n        elementname: str,\n        etype: Literal[\"image\"],\n        default_image: tkinter._Image | str,\n        /,\n        *imagespec: _ImageStatespec,\n        border: _Padding = ...,\n        height: float | str = ...,\n        padding: _Padding = ...,\n        sticky: str = ...,\n        width: float | str = ...,\n    ) -> None: ...\n    @overload\n    def element_create(self, elementname: str, etype: Literal[\"from\"], themename: str, fromelement: str = ..., /) -> None: ...\n    if sys.platform == \"win32\" and sys.version_info >= (3, 13):  # and tk version >= 8.6\n        # margin, padding, and (width + height) are mutually exclusive. width\n        # and height must either both be present or not present at all. Note:\n        # There are other undocumented options if you look at ttk's source code.\n        @overload\n        def element_create(\n            self,\n            elementname: str,\n            etype: Literal[\"vsapi\"],\n            class_: str,\n            part: int,\n            vs_statespec: _VsapiStatespec = ...,\n            /,\n            *,\n            padding: _Padding = ...,\n        ) -> None: ...\n        @overload\n        def element_create(\n            self,\n            elementname: str,\n            etype: Literal[\"vsapi\"],\n            class_: str,\n            part: int,\n            vs_statespec: _VsapiStatespec = ...,\n            /,\n            *,\n            margin: _Padding = ...,\n        ) -> None: ...\n        @overload\n        def element_create(\n            self,\n            elementname: str,\n            etype: Literal[\"vsapi\"],\n            class_: str,\n            part: int,\n            vs_statespec: _VsapiStatespec = ...,\n            /,\n            *,\n            width: float | str,\n            height: float | str,\n        ) -> None: ...\n\n    def element_names(self) -> tuple[str, ...]: ...\n    def element_options(self, elementname: str) -> tuple[str, ...]: ...\n    def theme_create(self, themename: str, parent: str | None = None, settings: _ThemeSettings | None = None) -> None: ...\n    def theme_settings(self, themename: str, settings: _ThemeSettings) -> None: ...\n    def theme_names(self) -> tuple[str, ...]: ...\n    @overload\n    def theme_use(self, themename: str) -> None: ...\n    @overload\n    def theme_use(self, themename: None = None) -> str: ...\n\nclass Widget(tkinter.Widget):\n    def __init__(self, master: tkinter.Misc | None, widgetname: str | None, kw: dict[str, Any] | None = None) -> None: ...\n    def identify(self, x: int, y: int) -> str: ...\n    @overload\n    def instate(self, statespec: Sequence[str], callback: None = None) -> bool: ...\n    @overload\n    def instate(\n        self, statespec: Sequence[str], callback: Callable[_P, _T], *args: _P.args, **kw: _P.kwargs\n    ) -> Literal[False] | _T: ...\n    def state(self, statespec: Sequence[str] | None = None) -> tuple[str, ...]: ...\n\nclass Button(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        command: str | Callable[[], Any] = \"\",\n        compound: Literal[\"\", \"text\", \"image\", \"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = \"\",\n        cursor: tkinter._Cursor = \"\",\n        default: Literal[\"normal\", \"active\", \"disabled\"] = \"normal\",\n        image: tkinter._Image | str = \"\",\n        name: str = ...,\n        padding=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = \"\",\n        textvariable: tkinter.Variable = ...,\n        underline: int = -1,\n        width: int | Literal[\"\"] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        command: str | Callable[[], Any] = ...,\n        compound: Literal[\"\", \"text\", \"image\", \"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        cursor: tkinter._Cursor = ...,\n        default: Literal[\"normal\", \"active\", \"disabled\"] = ...,\n        image: tkinter._Image | str = ...,\n        padding=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: tkinter.Variable = ...,\n        underline: int = ...,\n        width: int | Literal[\"\"] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def invoke(self) -> Any: ...\n\nclass Checkbutton(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        command: str | Callable[[], Any] = \"\",\n        compound: Literal[\"\", \"text\", \"image\", \"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = \"\",\n        cursor: tkinter._Cursor = \"\",\n        image: tkinter._Image | str = \"\",\n        name: str = ...,\n        offvalue: Any = 0,\n        onvalue: Any = 1,\n        padding=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = \"\",\n        textvariable: tkinter.Variable = ...,\n        underline: int = -1,\n        # Seems like variable can be empty string, but actually setting it to\n        # empty string segfaults before Tcl 8.6.9. Search for ttk::checkbutton\n        # here: https://sourceforge.net/projects/tcl/files/Tcl/8.6.9/tcltk-release-notes-8.6.9.txt/view\n        variable: tkinter.Variable = ...,\n        width: int | Literal[\"\"] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        command: str | Callable[[], Any] = ...,\n        compound: Literal[\"\", \"text\", \"image\", \"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        cursor: tkinter._Cursor = ...,\n        image: tkinter._Image | str = ...,\n        offvalue: Any = ...,\n        onvalue: Any = ...,\n        padding=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: tkinter.Variable = ...,\n        underline: int = ...,\n        variable: tkinter.Variable = ...,\n        width: int | Literal[\"\"] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def invoke(self) -> Any: ...\n\nclass Entry(Widget, tkinter.Entry):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        widget: str | None = None,\n        *,\n        background: str = ...,  # undocumented\n        class_: str = \"\",\n        cursor: tkinter._Cursor = ...,\n        exportselection: bool = True,\n        font: _FontDescription = \"TkTextFont\",\n        foreground: str = \"\",\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",\n        justify: Literal[\"left\", \"center\", \"right\"] = \"left\",\n        name: str = ...,\n        show: str = \"\",\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = \"none\",\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",\n        width: int = 20,\n        xscrollcommand: str | Callable[[float, float], object] = \"\",\n    ) -> None: ...\n    @overload  # type: ignore[override]\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        cursor: tkinter._Cursor = ...,\n        exportselection: bool = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        show: str = ...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        width: int = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    # config must be copy/pasted, otherwise ttk.Entry().config is mypy error (don't know why)\n    @overload  # type: ignore[override]\n    def config(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        cursor: tkinter._Cursor = ...,\n        exportselection: bool = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        show: str = ...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        width: int = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    def bbox(self, index) -> tuple[int, int, int, int]: ...  # type: ignore[override]\n    def identify(self, x: int, y: int) -> str: ...\n    def validate(self): ...\n\nclass Combobox(Entry):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        background: str = ...,  # undocumented\n        class_: str = \"\",\n        cursor: tkinter._Cursor = \"\",\n        exportselection: bool = True,\n        font: _FontDescription = ...,  # undocumented\n        foreground: str = ...,  # undocumented\n        height: int = 10,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,  # undocumented\n        justify: Literal[\"left\", \"center\", \"right\"] = \"left\",\n        name: str = ...,\n        postcommand: Callable[[], object] | str = \"\",\n        show=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,  # undocumented\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,  # undocumented\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = 20,\n        xscrollcommand: str | Callable[[float, float], object] = ...,  # undocumented\n    ) -> None: ...\n    @overload  # type: ignore[override]\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        cursor: tkinter._Cursor = ...,\n        exportselection: bool = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: int = ...,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        postcommand: Callable[[], object] | str = ...,\n        show=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    # config must be copy/pasted, otherwise ttk.Combobox().config is mypy error (don't know why)\n    @overload  # type: ignore[override]\n    def config(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        cursor: tkinter._Cursor = ...,\n        exportselection: bool = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        height: int = ...,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        postcommand: Callable[[], object] | str = ...,\n        show=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        textvariable: tkinter.Variable = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    def current(self, newindex: int | None = None) -> int: ...\n    def set(self, value: Any) -> None: ...\n\nclass Frame(Widget):\n    # This should be kept in sync with tkinter.ttk.LabeledScale.__init__()\n    # (all of these keyword-only arguments are also present there)\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        class_: str = \"\",\n        cursor: tkinter._Cursor = \"\",\n        height: float | str = 0,\n        name: str = ...,\n        padding: _Padding = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        width: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: tkinter._Cursor = ...,\n        height: float | str = ...,\n        padding: _Padding = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        width: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass Label(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        background: str = \"\",\n        border: float | str = ...,  # alias for borderwidth\n        borderwidth: float | str = ...,  # undocumented\n        class_: str = \"\",\n        compound: Literal[\"\", \"text\", \"image\", \"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = \"\",\n        cursor: tkinter._Cursor = \"\",\n        font: _FontDescription = ...,\n        foreground: str = \"\",\n        image: tkinter._Image | str = \"\",\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        name: str = ...,\n        padding: _Padding = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        text: float | str = \"\",\n        textvariable: tkinter.Variable = ...,\n        underline: int = -1,\n        width: int | Literal[\"\"] = \"\",\n        wraplength: float | str = ...,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        background: str = ...,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        compound: Literal[\"\", \"text\", \"image\", \"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        cursor: tkinter._Cursor = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        image: tkinter._Image | str = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        padding: _Padding = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: tkinter.Variable = ...,\n        underline: int = ...,\n        width: int | Literal[\"\"] = ...,\n        wraplength: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass Labelframe(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        border: float | str = ...,\n        borderwidth: float | str = ...,  # undocumented\n        class_: str = \"\",\n        cursor: tkinter._Cursor = \"\",\n        height: float | str = 0,\n        labelanchor: Literal[\"nw\", \"n\", \"ne\", \"en\", \"e\", \"es\", \"se\", \"s\", \"sw\", \"ws\", \"w\", \"wn\"] = ...,\n        labelwidget: tkinter.Misc = ...,\n        name: str = ...,\n        padding: _Padding = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,  # undocumented\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        text: float | str = \"\",\n        underline: int = -1,\n        width: float | str = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        cursor: tkinter._Cursor = ...,\n        height: float | str = ...,\n        labelanchor: Literal[\"nw\", \"n\", \"ne\", \"en\", \"e\", \"es\", \"se\", \"s\", \"sw\", \"ws\", \"w\", \"wn\"] = ...,\n        labelwidget: tkinter.Misc = ...,\n        padding: _Padding = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        underline: int = ...,\n        width: float | str = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nLabelFrame = Labelframe\n\nclass Menubutton(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        compound: Literal[\"\", \"text\", \"image\", \"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = \"\",\n        cursor: tkinter._Cursor = \"\",\n        direction: Literal[\"above\", \"below\", \"left\", \"right\", \"flush\"] = \"below\",\n        image: tkinter._Image | str = \"\",\n        menu: tkinter.Menu = ...,\n        name: str = ...,\n        padding=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = \"\",\n        textvariable: tkinter.Variable = ...,\n        underline: int = -1,\n        width: int | Literal[\"\"] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        compound: Literal[\"\", \"text\", \"image\", \"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        cursor: tkinter._Cursor = ...,\n        direction: Literal[\"above\", \"below\", \"left\", \"right\", \"flush\"] = ...,\n        image: tkinter._Image | str = ...,\n        menu: tkinter.Menu = ...,\n        padding=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: tkinter.Variable = ...,\n        underline: int = ...,\n        width: int | Literal[\"\"] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass Notebook(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        cursor: tkinter._Cursor = \"\",\n        height: int = 0,\n        name: str = ...,\n        padding: _Padding = ...,\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        width: int = 0,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        cursor: tkinter._Cursor = ...,\n        height: int = ...,\n        padding: _Padding = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        width: int = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def add(\n        self,\n        child: tkinter.Widget,\n        *,\n        state: Literal[\"normal\", \"disabled\", \"hidden\"] = ...,\n        sticky: str = ...,  # consists of letters 'n', 's', 'w', 'e', no repeats, may be empty\n        padding: _Padding = ...,\n        text: str = ...,\n        # `image` is a sequence of an image name, followed by zero or more\n        # (sequences of one or more state names followed by an image name)\n        image=...,\n        compound: Literal[\"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        underline: int = ...,\n    ) -> None: ...\n    def forget(self, tab_id) -> None: ...  # type: ignore[override]\n    def hide(self, tab_id) -> None: ...\n    def identify(self, x: int, y: int) -> str: ...\n    def index(self, tab_id): ...\n    def insert(self, pos, child, **kw) -> None: ...\n    def select(self, tab_id=None): ...\n    def tab(self, tab_id, option=None, **kw): ...\n    def tabs(self): ...\n    def enable_traversal(self) -> None: ...\n\nclass Panedwindow(Widget, tkinter.PanedWindow):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        cursor: tkinter._Cursor = \"\",\n        # width and height for tkinter.ttk.Panedwindow are int but for tkinter.PanedWindow they are screen units\n        height: int = 0,\n        name: str = ...,\n        orient: Literal[\"vertical\", \"horizontal\"] = \"vertical\",  # can't be changed with configure()\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        width: int = 0,\n    ) -> None: ...\n    def add(self, child: tkinter.Widget, *, weight: int = ..., **kw) -> None: ...\n    @overload  # type: ignore[override]\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        cursor: tkinter._Cursor = ...,\n        height: int = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        width: int = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    # config must be copy/pasted, otherwise ttk.Panedwindow().config is mypy error (don't know why)\n    @overload  # type: ignore[override]\n    def config(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        cursor: tkinter._Cursor = ...,\n        height: int = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        width: int = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    forget = tkinter.PanedWindow.forget\n    def insert(self, pos, child, **kw) -> None: ...\n    def pane(self, pane, option=None, **kw): ...\n    def sashpos(self, index, newpos=None): ...\n\nPanedWindow = Panedwindow\n\nclass Progressbar(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        cursor: tkinter._Cursor = \"\",\n        length: float | str = 100,\n        maximum: float = 100,\n        mode: Literal[\"determinate\", \"indeterminate\"] = \"determinate\",\n        name: str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"horizontal\",\n        phase: int = 0,  # docs say read-only but assigning int to this works\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        value: float = 0.0,\n        variable: tkinter.IntVar | tkinter.DoubleVar = ...,\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        cursor: tkinter._Cursor = ...,\n        length: float | str = ...,\n        maximum: float = ...,\n        mode: Literal[\"determinate\", \"indeterminate\"] = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        phase: int = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        value: float = ...,\n        variable: tkinter.IntVar | tkinter.DoubleVar = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def start(self, interval: Literal[\"idle\"] | int | None = None) -> None: ...\n    def step(self, amount: float | None = None) -> None: ...\n    def stop(self) -> None: ...\n\nclass Radiobutton(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        command: str | Callable[[], Any] = \"\",\n        compound: Literal[\"\", \"text\", \"image\", \"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = \"\",\n        cursor: tkinter._Cursor = \"\",\n        image: tkinter._Image | str = \"\",\n        name: str = ...,\n        padding=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = \"\",\n        textvariable: tkinter.Variable = ...,\n        underline: int = -1,\n        value: Any = \"1\",\n        variable: tkinter.Variable | Literal[\"\"] = ...,\n        width: int | Literal[\"\"] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        command: str | Callable[[], Any] = ...,\n        compound: Literal[\"\", \"text\", \"image\", \"top\", \"left\", \"center\", \"right\", \"bottom\", \"none\"] = ...,\n        cursor: tkinter._Cursor = ...,\n        image: tkinter._Image | str = ...,\n        padding=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        text: float | str = ...,\n        textvariable: tkinter.Variable = ...,\n        underline: int = ...,\n        value: Any = ...,\n        variable: tkinter.Variable | Literal[\"\"] = ...,\n        width: int | Literal[\"\"] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def invoke(self) -> Any: ...\n\n# type ignore, because identify() methods of Widget and tkinter.Scale are incompatible\nclass Scale(Widget, tkinter.Scale):  # type: ignore[misc]\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        command: str | Callable[[str], object] = \"\",\n        cursor: tkinter._Cursor = \"\",\n        from_: float = 0,\n        length: float | str = 100,\n        name: str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"horizontal\",\n        state: str = ...,  # undocumented\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        to: float = 1.0,\n        value: float = 0,\n        variable: tkinter.IntVar | tkinter.DoubleVar = ...,\n    ) -> None: ...\n    @overload  # type: ignore[override]\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        command: str | Callable[[str], object] = ...,\n        cursor: tkinter._Cursor = ...,\n        from_: float = ...,\n        length: float | str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        to: float = ...,\n        value: float = ...,\n        variable: tkinter.IntVar | tkinter.DoubleVar = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    # config must be copy/pasted, otherwise ttk.Scale().config is mypy error (don't know why)\n    @overload  # type: ignore[override]\n    def config(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        command: str | Callable[[str], object] = ...,\n        cursor: tkinter._Cursor = ...,\n        from_: float = ...,\n        length: float | str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        to: float = ...,\n        value: float = ...,\n        variable: tkinter.IntVar | tkinter.DoubleVar = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    def get(self, x: int | None = None, y: int | None = None) -> float: ...\n\n# type ignore, because identify() methods of Widget and tkinter.Scale are incompatible\nclass Scrollbar(Widget, tkinter.Scrollbar):  # type: ignore[misc]\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        command: Callable[..., tuple[float, float] | None] | str = \"\",\n        cursor: tkinter._Cursor = \"\",\n        name: str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"vertical\",\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n    ) -> None: ...\n    @overload  # type: ignore[override]\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        command: Callable[..., tuple[float, float] | None] | str = ...,\n        cursor: tkinter._Cursor = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    # config must be copy/pasted, otherwise ttk.Scrollbar().config is mypy error (don't know why)\n    @overload  # type: ignore[override]\n    def config(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        command: Callable[..., tuple[float, float] | None] | str = ...,\n        cursor: tkinter._Cursor = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def config(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n\nclass Separator(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        cursor: tkinter._Cursor = \"\",\n        name: str = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = \"horizontal\",\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        cursor: tkinter._Cursor = ...,\n        orient: Literal[\"horizontal\", \"vertical\"] = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass Sizegrip(Widget):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        cursor: tkinter._Cursor = ...,\n        name: str = ...,\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        cursor: tkinter._Cursor = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n\nclass Spinbox(Entry):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        background: str = ...,  # undocumented\n        class_: str = \"\",\n        command: Callable[[], object] | str | list[str] | tuple[str, ...] = \"\",\n        cursor: tkinter._Cursor = \"\",\n        exportselection: bool = ...,  # undocumented\n        font: _FontDescription = ...,  # undocumented\n        foreground: str = ...,  # undocumented\n        format: str = \"\",\n        from_: float = 0,\n        increment: float = 1,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,  # undocumented\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,  # undocumented\n        name: str = ...,\n        show=...,  # undocumented\n        state: str = \"normal\",\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        textvariable: tkinter.Variable = ...,  # undocumented\n        to: float = 0,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = \"none\",\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = \"\",\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = ...,  # undocumented\n        wrap: bool = False,\n        xscrollcommand: str | Callable[[float, float], object] = \"\",\n    ) -> None: ...\n    @overload  # type: ignore[override]\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        background: str = ...,\n        command: Callable[[], object] | str | list[str] | tuple[str, ...] = ...,\n        cursor: tkinter._Cursor = ...,\n        exportselection: bool = ...,\n        font: _FontDescription = ...,\n        foreground: str = ...,\n        format: str = ...,\n        from_: float = ...,\n        increment: float = ...,\n        invalidcommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        justify: Literal[\"left\", \"center\", \"right\"] = ...,\n        show=...,\n        state: str = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        textvariable: tkinter.Variable = ...,\n        to: float = ...,\n        validate: Literal[\"none\", \"focus\", \"focusin\", \"focusout\", \"key\", \"all\"] = ...,\n        validatecommand: str | list[str] | tuple[str, ...] | Callable[[], bool] = ...,\n        values: list[str] | tuple[str, ...] = ...,\n        width: int = ...,\n        wrap: bool = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure  # type: ignore[assignment]\n    def set(self, value: Any) -> None: ...\n\n@type_check_only\nclass _TreeviewItemDict(TypedDict):\n    text: str\n    image: list[str] | Literal[\"\"]  # no idea why it's wrapped in list\n    values: list[Any] | Literal[\"\"]\n    open: bool  # actually 0 or 1\n    tags: list[str] | Literal[\"\"]\n\n@type_check_only\nclass _TreeviewTagDict(TypedDict):\n    # There is also 'text' and 'anchor', but they don't seem to do anything, using them is likely a bug\n    foreground: str\n    background: str\n    font: _FontDescription\n    image: str  # not wrapped in list :D\n\n@type_check_only\nclass _TreeviewHeaderDict(TypedDict):\n    text: str\n    image: list[str] | Literal[\"\"]\n    anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"]\n    command: str\n    state: str  # Doesn't seem to appear anywhere else than in these dicts\n\n@type_check_only\nclass _TreeviewColumnDict(TypedDict):\n    width: int\n    minwidth: int\n    stretch: bool  # actually 0 or 1\n    anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"]\n    id: str\n\nclass Treeview(Widget, tkinter.XView, tkinter.YView):\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        *,\n        class_: str = \"\",\n        columns: str | list[str] | list[int] | list[str | int] | tuple[str | int, ...] = \"\",\n        cursor: tkinter._Cursor = \"\",\n        displaycolumns: str | int | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] = (\"#all\",),\n        height: int = 10,\n        name: str = ...,\n        padding: _Padding = ...,\n        selectmode: Literal[\"extended\", \"browse\", \"none\"] = \"extended\",\n        # list/tuple of Literal don't actually work in mypy\n        #\n        # 'tree headings' is same as ['tree', 'headings'], and I wouldn't be\n        # surprised if someone is using it.\n        show: Literal[\"tree\", \"headings\", \"tree headings\", \"\"] | list[str] | tuple[str, ...] = (\"tree\", \"headings\"),\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        xscrollcommand: str | Callable[[float, float], object] = \"\",\n        yscrollcommand: str | Callable[[float, float], object] = \"\",\n    ) -> None: ...\n    @overload\n    def configure(\n        self,\n        cnf: dict[str, Any] | None = None,\n        *,\n        columns: str | list[str] | list[int] | list[str | int] | tuple[str | int, ...] = ...,\n        cursor: tkinter._Cursor = ...,\n        displaycolumns: str | int | list[str] | tuple[str, ...] | list[int] | tuple[int, ...] = ...,\n        height: int = ...,\n        padding: _Padding = ...,\n        selectmode: Literal[\"extended\", \"browse\", \"none\"] = ...,\n        show: Literal[\"tree\", \"headings\", \"tree headings\", \"\"] | list[str] | tuple[str, ...] = ...,\n        style: str = ...,\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = ...,\n        xscrollcommand: str | Callable[[float, float], object] = ...,\n        yscrollcommand: str | Callable[[float, float], object] = ...,\n    ) -> dict[str, tuple[str, str, str, Any, Any]] | None: ...\n    @overload\n    def configure(self, cnf: str) -> tuple[str, str, str, Any, Any]: ...\n    config = configure\n    def bbox(self, item: str | int, column: str | int | None = None) -> tuple[int, int, int, int] | Literal[\"\"]: ...  # type: ignore[override]\n    def get_children(self, item: str | int | None = None) -> tuple[str, ...]: ...\n    def set_children(self, item: str | int, *newchildren: str | int) -> None: ...\n    @overload\n    def column(self, column: str | int, option: Literal[\"width\", \"minwidth\"]) -> int: ...\n    @overload\n    def column(self, column: str | int, option: Literal[\"stretch\"]) -> bool: ...  # actually 0 or 1\n    @overload\n    def column(self, column: str | int, option: Literal[\"anchor\"]) -> _tkinter.Tcl_Obj: ...\n    @overload\n    def column(self, column: str | int, option: Literal[\"id\"]) -> str: ...\n    @overload\n    def column(self, column: str | int, option: str) -> Any: ...\n    @overload\n    def column(\n        self,\n        column: str | int,\n        option: None = None,\n        *,\n        width: int = ...,\n        minwidth: int = ...,\n        stretch: bool = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        # id is read-only\n    ) -> _TreeviewColumnDict | None: ...\n    def delete(self, *items: str | int) -> None: ...\n    def detach(self, *items: str | int) -> None: ...\n    def exists(self, item: str | int) -> bool: ...\n    @overload  # type: ignore[override]\n    def focus(self, item: None = None) -> str: ...  # can return empty string\n    @overload\n    def focus(self, item: str | int) -> Literal[\"\"]: ...\n    @overload\n    def heading(self, column: str | int, option: Literal[\"text\"]) -> str: ...\n    @overload\n    def heading(self, column: str | int, option: Literal[\"image\"]) -> tuple[str] | str: ...\n    @overload\n    def heading(self, column: str | int, option: Literal[\"anchor\"]) -> _tkinter.Tcl_Obj: ...\n    @overload\n    def heading(self, column: str | int, option: Literal[\"command\"]) -> str: ...\n    @overload\n    def heading(self, column: str | int, option: str) -> Any: ...\n    @overload\n    def heading(self, column: str | int, option: None = None) -> _TreeviewHeaderDict: ...\n    @overload\n    def heading(\n        self,\n        column: str | int,\n        option: None = None,\n        *,\n        text: str = ...,\n        image: tkinter._Image | str = ...,\n        anchor: Literal[\"nw\", \"n\", \"ne\", \"w\", \"center\", \"e\", \"sw\", \"s\", \"se\"] = ...,\n        command: str | Callable[[], object] = ...,\n    ) -> None: ...\n    # Internal Method. Leave untyped:\n    def identify(self, component, x, y): ...  # type: ignore[override]\n    def identify_row(self, y: int) -> str: ...\n    def identify_column(self, x: int) -> str: ...\n    def identify_region(self, x: int, y: int) -> Literal[\"heading\", \"separator\", \"tree\", \"cell\", \"nothing\"]: ...\n    def identify_element(self, x: int, y: int) -> str: ...  # don't know what possible return values are\n    def index(self, item: str | int) -> int: ...\n    def insert(\n        self,\n        parent: str,\n        index: int | Literal[\"end\"],\n        iid: str | int | None = None,\n        *,\n        id: str | int = ...,  # same as iid\n        text: str = ...,\n        image: tkinter._Image | str = ...,\n        values: list[Any] | tuple[Any, ...] = ...,\n        open: bool = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n    ) -> str: ...\n    @overload\n    def item(self, item: str | int, option: Literal[\"text\"]) -> str: ...\n    @overload\n    def item(self, item: str | int, option: Literal[\"image\"]) -> tuple[str] | Literal[\"\"]: ...\n    @overload\n    def item(self, item: str | int, option: Literal[\"values\"]) -> tuple[Any, ...] | Literal[\"\"]: ...\n    @overload\n    def item(self, item: str | int, option: Literal[\"open\"]) -> bool: ...  # actually 0 or 1\n    @overload\n    def item(self, item: str | int, option: Literal[\"tags\"]) -> tuple[str, ...] | Literal[\"\"]: ...\n    @overload\n    def item(self, item: str | int, option: str) -> Any: ...\n    @overload\n    def item(self, item: str | int, option: None = None) -> _TreeviewItemDict: ...\n    @overload\n    def item(\n        self,\n        item: str | int,\n        option: None = None,\n        *,\n        text: str = ...,\n        image: tkinter._Image | str = ...,\n        values: list[Any] | tuple[Any, ...] | Literal[\"\"] = ...,\n        open: bool = ...,\n        tags: str | list[str] | tuple[str, ...] = ...,\n    ) -> None: ...\n    def move(self, item: str | int, parent: str, index: int | Literal[\"end\"]) -> None: ...\n    reattach = move\n    def next(self, item: str | int) -> str: ...  # returning empty string means last item\n    def parent(self, item: str | int) -> str: ...\n    def prev(self, item: str | int) -> str: ...  # returning empty string means first item\n    def see(self, item: str | int) -> None: ...\n    def selection(self) -> tuple[str, ...]: ...\n    @overload\n    def selection_set(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ...\n    @overload\n    def selection_set(self, *items: str | int) -> None: ...\n    @overload\n    def selection_add(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ...\n    @overload\n    def selection_add(self, *items: str | int) -> None: ...\n    @overload\n    def selection_remove(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ...\n    @overload\n    def selection_remove(self, *items: str | int) -> None: ...\n    @overload\n    def selection_toggle(self, items: list[str] | tuple[str, ...] | list[int] | tuple[int, ...], /) -> None: ...\n    @overload\n    def selection_toggle(self, *items: str | int) -> None: ...\n    @overload\n    def set(self, item: str | int, column: None = None, value: None = None) -> dict[str, Any]: ...\n    @overload\n    def set(self, item: str | int, column: str | int, value: None = None) -> Any: ...\n    @overload\n    def set(self, item: str | int, column: str | int, value: Any) -> Literal[\"\"]: ...\n    # There's no tag_unbind() or 'add' argument for whatever reason.\n    # Also, it's 'callback' instead of 'func' here.\n    @overload\n    def tag_bind(\n        self, tagname: str, sequence: str | None = None, callback: Callable[[tkinter.Event[Treeview]], object] | None = None\n    ) -> str: ...\n    @overload\n    def tag_bind(self, tagname: str, sequence: str | None, callback: str) -> None: ...\n    @overload\n    def tag_bind(self, tagname: str, *, callback: str) -> None: ...\n    @overload\n    def tag_configure(self, tagname: str, option: Literal[\"foreground\", \"background\"]) -> str: ...\n    @overload\n    def tag_configure(self, tagname: str, option: Literal[\"font\"]) -> _FontDescription: ...\n    @overload\n    def tag_configure(self, tagname: str, option: Literal[\"image\"]) -> str: ...\n    @overload\n    def tag_configure(\n        self,\n        tagname: str,\n        option: None = None,\n        *,\n        # There is also 'text' and 'anchor', but they don't seem to do anything, using them is likely a bug\n        foreground: str = ...,\n        background: str = ...,\n        font: _FontDescription = ...,\n        image: tkinter._Image | str = ...,\n    ) -> _TreeviewTagDict | MaybeNone: ...  # can be None but annoying to check\n    @overload\n    def tag_has(self, tagname: str, item: None = None) -> tuple[str, ...]: ...\n    @overload\n    def tag_has(self, tagname: str, item: str | int) -> bool: ...\n\nclass LabeledScale(Frame):\n    label: Label\n    scale: Scale\n    # This should be kept in sync with tkinter.ttk.Frame.__init__()\n    # (all the keyword-only args except compound are from there)\n    def __init__(\n        self,\n        master: tkinter.Misc | None = None,\n        variable: tkinter.IntVar | tkinter.DoubleVar | None = None,\n        from_: float = 0,\n        to: float = 10,\n        *,\n        border: float | str = ...,\n        borderwidth: float | str = ...,\n        class_: str = \"\",\n        compound: Literal[\"top\", \"bottom\"] = \"top\",\n        cursor: tkinter._Cursor = \"\",\n        height: float | str = 0,\n        name: str = ...,\n        padding: _Padding = ...,\n        relief: Literal[\"raised\", \"sunken\", \"flat\", \"ridge\", \"solid\", \"groove\"] = ...,\n        style: str = \"\",\n        takefocus: bool | Literal[0, 1, \"\"] | Callable[[str], bool | None] = \"\",\n        width: float | str = 0,\n    ) -> None: ...\n    # destroy is overridden, signature does not change\n    value: Any\n\nclass OptionMenu(Menubutton):\n    def __init__(\n        self,\n        master: tkinter.Misc | None,\n        variable: tkinter.StringVar,\n        default: str | None = None,\n        *values: str,\n        # rest of these are keyword-only because *args syntax used above\n        style: str = \"\",\n        direction: Literal[\"above\", \"below\", \"left\", \"right\", \"flush\"] = \"below\",\n        command: Callable[[tkinter.StringVar], object] | None = None,\n    ) -> None: ...\n    # configure, config, cget, destroy are inherited from Menubutton\n    # destroy and __setitem__ are overridden, signature does not change\n    def set_menu(self, default: str | None = None, *values: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/token.pyi",
    "content": "import sys\nfrom typing import Final\n\n__all__ = [\n    \"AMPER\",\n    \"AMPEREQUAL\",\n    \"AT\",\n    \"ATEQUAL\",\n    \"CIRCUMFLEX\",\n    \"CIRCUMFLEXEQUAL\",\n    \"COLON\",\n    \"COLONEQUAL\",\n    \"COMMA\",\n    \"DEDENT\",\n    \"DOT\",\n    \"DOUBLESLASH\",\n    \"DOUBLESLASHEQUAL\",\n    \"DOUBLESTAR\",\n    \"DOUBLESTAREQUAL\",\n    \"ELLIPSIS\",\n    \"ENDMARKER\",\n    \"EQEQUAL\",\n    \"EQUAL\",\n    \"ERRORTOKEN\",\n    \"GREATER\",\n    \"GREATEREQUAL\",\n    \"INDENT\",\n    \"ISEOF\",\n    \"ISNONTERMINAL\",\n    \"ISTERMINAL\",\n    \"LBRACE\",\n    \"LEFTSHIFT\",\n    \"LEFTSHIFTEQUAL\",\n    \"LESS\",\n    \"LESSEQUAL\",\n    \"LPAR\",\n    \"LSQB\",\n    \"MINEQUAL\",\n    \"MINUS\",\n    \"NAME\",\n    \"NEWLINE\",\n    \"NOTEQUAL\",\n    \"NT_OFFSET\",\n    \"NUMBER\",\n    \"N_TOKENS\",\n    \"OP\",\n    \"PERCENT\",\n    \"PERCENTEQUAL\",\n    \"PLUS\",\n    \"PLUSEQUAL\",\n    \"RARROW\",\n    \"RBRACE\",\n    \"RIGHTSHIFT\",\n    \"RIGHTSHIFTEQUAL\",\n    \"RPAR\",\n    \"RSQB\",\n    \"SEMI\",\n    \"SLASH\",\n    \"SLASHEQUAL\",\n    \"STAR\",\n    \"STAREQUAL\",\n    \"STRING\",\n    \"TILDE\",\n    \"TYPE_COMMENT\",\n    \"TYPE_IGNORE\",\n    \"VBAR\",\n    \"VBAREQUAL\",\n    \"tok_name\",\n    \"ENCODING\",\n    \"NL\",\n    \"COMMENT\",\n]\nif sys.version_info < (3, 13):\n    __all__ += [\"ASYNC\", \"AWAIT\"]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"SOFT_KEYWORD\"]\n\nif sys.version_info >= (3, 12):\n    __all__ += [\"EXCLAMATION\", \"FSTRING_END\", \"FSTRING_MIDDLE\", \"FSTRING_START\", \"EXACT_TOKEN_TYPES\"]\n\nif sys.version_info >= (3, 14):\n    __all__ += [\"TSTRING_START\", \"TSTRING_MIDDLE\", \"TSTRING_END\"]\n\nENDMARKER: Final[int]\nNAME: Final[int]\nNUMBER: Final[int]\nSTRING: Final[int]\nNEWLINE: Final[int]\nINDENT: Final[int]\nDEDENT: Final[int]\nLPAR: Final[int]\nRPAR: Final[int]\nLSQB: Final[int]\nRSQB: Final[int]\nCOLON: Final[int]\nCOMMA: Final[int]\nSEMI: Final[int]\nPLUS: Final[int]\nMINUS: Final[int]\nSTAR: Final[int]\nSLASH: Final[int]\nVBAR: Final[int]\nAMPER: Final[int]\nLESS: Final[int]\nGREATER: Final[int]\nEQUAL: Final[int]\nDOT: Final[int]\nPERCENT: Final[int]\nLBRACE: Final[int]\nRBRACE: Final[int]\nEQEQUAL: Final[int]\nNOTEQUAL: Final[int]\nLESSEQUAL: Final[int]\nGREATEREQUAL: Final[int]\nTILDE: Final[int]\nCIRCUMFLEX: Final[int]\nLEFTSHIFT: Final[int]\nRIGHTSHIFT: Final[int]\nDOUBLESTAR: Final[int]\nPLUSEQUAL: Final[int]\nMINEQUAL: Final[int]\nSTAREQUAL: Final[int]\nSLASHEQUAL: Final[int]\nPERCENTEQUAL: Final[int]\nAMPEREQUAL: Final[int]\nVBAREQUAL: Final[int]\nCIRCUMFLEXEQUAL: Final[int]\nLEFTSHIFTEQUAL: Final[int]\nRIGHTSHIFTEQUAL: Final[int]\nDOUBLESTAREQUAL: Final[int]\nDOUBLESLASH: Final[int]\nDOUBLESLASHEQUAL: Final[int]\nAT: Final[int]\nRARROW: Final[int]\nELLIPSIS: Final[int]\nATEQUAL: Final[int]\nif sys.version_info < (3, 13):\n    AWAIT: Final[int]\n    ASYNC: Final[int]\nOP: Final[int]\nERRORTOKEN: Final[int]\nN_TOKENS: Final[int]\nNT_OFFSET: Final[int]\ntok_name: Final[dict[int, str]]\nCOMMENT: Final[int]\nNL: Final[int]\nENCODING: Final[int]\nTYPE_COMMENT: Final[int]\nTYPE_IGNORE: Final[int]\nCOLONEQUAL: Final[int]\nEXACT_TOKEN_TYPES: Final[dict[str, int]]\nif sys.version_info >= (3, 10):\n    SOFT_KEYWORD: Final[int]\n\nif sys.version_info >= (3, 12):\n    EXCLAMATION: Final[int]\n    FSTRING_END: Final[int]\n    FSTRING_MIDDLE: Final[int]\n    FSTRING_START: Final[int]\n\nif sys.version_info >= (3, 14):\n    TSTRING_START: Final[int]\n    TSTRING_MIDDLE: Final[int]\n    TSTRING_END: Final[int]\n\ndef ISTERMINAL(x: int) -> bool: ...\ndef ISNONTERMINAL(x: int) -> bool: ...\ndef ISEOF(x: int) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tokenize.pyi",
    "content": "import sys\nfrom _typeshed import FileDescriptorOrPath\nfrom collections.abc import Callable, Generator, Iterable, Sequence\nfrom re import Pattern\nfrom token import *\nfrom typing import Any, Final, NamedTuple, TextIO, type_check_only\nfrom typing_extensions import TypeAlias, disjoint_base\n\nif sys.version_info < (3, 12):\n    # Avoid double assignment to Final name by imports, which pyright objects to.\n    # EXACT_TOKEN_TYPES is already defined by 'from token import *' above\n    # in Python 3.12+.\n    from token import EXACT_TOKEN_TYPES as EXACT_TOKEN_TYPES\n\n__all__ = [\n    \"AMPER\",\n    \"AMPEREQUAL\",\n    \"AT\",\n    \"ATEQUAL\",\n    \"CIRCUMFLEX\",\n    \"CIRCUMFLEXEQUAL\",\n    \"COLON\",\n    \"COLONEQUAL\",\n    \"COMMA\",\n    \"COMMENT\",\n    \"DEDENT\",\n    \"DOT\",\n    \"DOUBLESLASH\",\n    \"DOUBLESLASHEQUAL\",\n    \"DOUBLESTAR\",\n    \"DOUBLESTAREQUAL\",\n    \"ELLIPSIS\",\n    \"ENCODING\",\n    \"ENDMARKER\",\n    \"EQEQUAL\",\n    \"EQUAL\",\n    \"ERRORTOKEN\",\n    \"GREATER\",\n    \"GREATEREQUAL\",\n    \"INDENT\",\n    \"ISEOF\",\n    \"ISNONTERMINAL\",\n    \"ISTERMINAL\",\n    \"LBRACE\",\n    \"LEFTSHIFT\",\n    \"LEFTSHIFTEQUAL\",\n    \"LESS\",\n    \"LESSEQUAL\",\n    \"LPAR\",\n    \"LSQB\",\n    \"MINEQUAL\",\n    \"MINUS\",\n    \"NAME\",\n    \"NEWLINE\",\n    \"NL\",\n    \"NOTEQUAL\",\n    \"NT_OFFSET\",\n    \"NUMBER\",\n    \"N_TOKENS\",\n    \"OP\",\n    \"PERCENT\",\n    \"PERCENTEQUAL\",\n    \"PLUS\",\n    \"PLUSEQUAL\",\n    \"RARROW\",\n    \"RBRACE\",\n    \"RIGHTSHIFT\",\n    \"RIGHTSHIFTEQUAL\",\n    \"RPAR\",\n    \"RSQB\",\n    \"SEMI\",\n    \"SLASH\",\n    \"SLASHEQUAL\",\n    \"STAR\",\n    \"STAREQUAL\",\n    \"STRING\",\n    \"TILDE\",\n    \"TYPE_COMMENT\",\n    \"TYPE_IGNORE\",\n    \"TokenInfo\",\n    \"VBAR\",\n    \"VBAREQUAL\",\n    \"detect_encoding\",\n    \"generate_tokens\",\n    \"tok_name\",\n    \"tokenize\",\n    \"untokenize\",\n]\nif sys.version_info < (3, 13):\n    __all__ += [\"ASYNC\", \"AWAIT\"]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"SOFT_KEYWORD\"]\n\nif sys.version_info >= (3, 12):\n    __all__ += [\"EXCLAMATION\", \"FSTRING_END\", \"FSTRING_MIDDLE\", \"FSTRING_START\", \"EXACT_TOKEN_TYPES\"]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"TokenError\", \"open\"]\n\nif sys.version_info >= (3, 14):\n    __all__ += [\"TSTRING_START\", \"TSTRING_MIDDLE\", \"TSTRING_END\"]\n\ncookie_re: Final[Pattern[str]]\nblank_re: Final[Pattern[bytes]]\n\n_Position: TypeAlias = tuple[int, int]\n\n# This class is not exposed. It calls itself tokenize.TokenInfo.\n@type_check_only\nclass _TokenInfo(NamedTuple):\n    type: int\n    string: str\n    start: _Position\n    end: _Position\n    line: str\n\nif sys.version_info >= (3, 12):\n    class TokenInfo(_TokenInfo):\n        @property\n        def exact_type(self) -> int: ...\n\nelse:\n    @disjoint_base\n    class TokenInfo(_TokenInfo):\n        @property\n        def exact_type(self) -> int: ...\n\n# Backwards compatible tokens can be sequences of a shorter length too\n_Token: TypeAlias = TokenInfo | Sequence[int | str | _Position]\n\nclass TokenError(Exception): ...\n\nif sys.version_info < (3, 13):\n    class StopTokenizing(Exception): ...  # undocumented\n\nclass Untokenizer:\n    tokens: list[str]\n    prev_row: int\n    prev_col: int\n    encoding: str | None\n    def add_whitespace(self, start: _Position) -> None: ...\n    if sys.version_info >= (3, 12):\n        def add_backslash_continuation(self, start: _Position) -> None: ...\n\n    def untokenize(self, iterable: Iterable[_Token]) -> str: ...\n    def compat(self, token: Sequence[int | str], iterable: Iterable[_Token]) -> None: ...\n    if sys.version_info >= (3, 12):\n        def escape_brackets(self, token: str) -> str: ...\n\n# Returns str, unless the ENCODING token is present, in which case it returns bytes.\ndef untokenize(iterable: Iterable[_Token]) -> str | Any: ...\ndef detect_encoding(readline: Callable[[], bytes | bytearray]) -> tuple[str, Sequence[bytes]]: ...\ndef tokenize(readline: Callable[[], bytes | bytearray]) -> Generator[TokenInfo, None, None]: ...\ndef generate_tokens(readline: Callable[[], str]) -> Generator[TokenInfo, None, None]: ...\ndef open(filename: FileDescriptorOrPath) -> TextIO: ...\ndef group(*choices: str) -> str: ...  # undocumented\ndef any(*choices: str) -> str: ...  # undocumented\ndef maybe(*choices: str) -> str: ...  # undocumented\n\nWhitespace: Final[str]  # undocumented\nComment: Final[str]  # undocumented\nIgnore: Final[str]  # undocumented\nName: Final[str]  # undocumented\n\nHexnumber: Final[str]  # undocumented\nBinnumber: Final[str]  # undocumented\nOctnumber: Final[str]  # undocumented\nDecnumber: Final[str]  # undocumented\nIntnumber: Final[str]  # undocumented\nExponent: Final[str]  # undocumented\nPointfloat: Final[str]  # undocumented\nExpfloat: Final[str]  # undocumented\nFloatnumber: Final[str]  # undocumented\nImagnumber: Final[str]  # undocumented\nNumber: Final[str]  # undocumented\n\ndef _all_string_prefixes() -> set[str]: ...  # undocumented\n\nStringPrefix: Final[str]  # undocumented\n\nSingle: Final[str]  # undocumented\nDouble: Final[str]  # undocumented\nSingle3: Final[str]  # undocumented\nDouble3: Final[str]  # undocumented\nTriple: Final[str]  # undocumented\nString: Final[str]  # undocumented\n\nSpecial: Final[str]  # undocumented\nFunny: Final[str]  # undocumented\n\nPlainToken: Final[str]  # undocumented\nToken: Final[str]  # undocumented\n\nContStr: Final[str]  # undocumented\nPseudoExtras: Final[str]  # undocumented\nPseudoToken: Final[str]  # undocumented\n\nendpats: Final[dict[str, str]]  # undocumented\nsingle_quoted: Final[set[str]]  # undocumented\ntriple_quoted: Final[set[str]]  # undocumented\n\ntabsize: Final = 8  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tomllib.pyi",
    "content": "import sys\nfrom _typeshed import SupportsRead\nfrom collections.abc import Callable\nfrom typing import Any, overload\nfrom typing_extensions import deprecated\n\n__all__ = (\"loads\", \"load\", \"TOMLDecodeError\")\n\nif sys.version_info >= (3, 14):\n    class TOMLDecodeError(ValueError):\n        msg: str\n        doc: str\n        pos: int\n        lineno: int\n        colno: int\n        @overload\n        def __init__(self, msg: str, doc: str, pos: int) -> None: ...\n        @overload\n        @deprecated(\"Deprecated since Python 3.14. Set the 'msg', 'doc' and 'pos' arguments only.\")\n        def __init__(self, msg: str | type = ..., doc: str | type = ..., pos: int | type = ..., *args: Any) -> None: ...\n\nelse:\n    class TOMLDecodeError(ValueError): ...\n\ndef load(fp: SupportsRead[bytes], /, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ...\ndef loads(s: str, /, *, parse_float: Callable[[str], Any] = ...) -> dict[str, Any]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/trace.pyi",
    "content": "import sys\nimport types\nfrom _typeshed import Incomplete, StrPath, TraceFunction\nfrom collections.abc import Callable, Iterable, Mapping, Sequence\nfrom typing import Any, TypeVar\nfrom typing_extensions import ParamSpec, TypeAlias\n\n__all__ = [\"Trace\", \"CoverageResults\"]\n\n_T = TypeVar(\"_T\")\n_P = ParamSpec(\"_P\")\n_FileModuleFunction: TypeAlias = tuple[str, str | None, str]\n\nclass CoverageResults:\n    counts: dict[tuple[str, int], int]\n    counter: dict[tuple[str, int], int]\n    calledfuncs: dict[_FileModuleFunction, int]\n    callers: dict[tuple[_FileModuleFunction, _FileModuleFunction], int]\n    inifile: StrPath | None\n    outfile: StrPath | None\n    def __init__(\n        self,\n        counts: dict[tuple[str, int], int] | None = None,\n        calledfuncs: dict[_FileModuleFunction, int] | None = None,\n        infile: StrPath | None = None,\n        callers: dict[tuple[_FileModuleFunction, _FileModuleFunction], int] | None = None,\n        outfile: StrPath | None = None,\n    ) -> None: ...  # undocumented\n    def update(self, other: CoverageResults) -> None: ...\n    if sys.version_info >= (3, 13):\n        def write_results(\n            self,\n            show_missing: bool = True,\n            summary: bool = False,\n            coverdir: StrPath | None = None,\n            *,\n            ignore_missing_files: bool = False,\n        ) -> None: ...\n    else:\n        def write_results(self, show_missing: bool = True, summary: bool = False, coverdir: StrPath | None = None) -> None: ...\n\n    def write_results_file(\n        self, path: StrPath, lines: Sequence[str], lnotab: Any, lines_hit: Mapping[int, int], encoding: str | None = None\n    ) -> tuple[int, int]: ...\n    def is_ignored_filename(self, filename: str) -> bool: ...  # undocumented\n\nclass _Ignore:\n    def __init__(self, modules: Iterable[str] | None = None, dirs: Iterable[StrPath] | None = None) -> None: ...\n    def names(self, filename: str, modulename: str) -> int: ...\n\nclass Trace:\n    inifile: StrPath | None\n    outfile: StrPath | None\n    ignore: _Ignore\n    counts: dict[str, int]\n    pathtobasename: dict[Incomplete, Incomplete]\n    donothing: int\n    trace: int\n    start_time: int | None\n    globaltrace: TraceFunction\n    localtrace: TraceFunction\n    def __init__(\n        self,\n        count: int = 1,\n        trace: int = 1,\n        countfuncs: int = 0,\n        countcallers: int = 0,\n        ignoremods: Sequence[str] = (),\n        ignoredirs: Sequence[str] = (),\n        infile: StrPath | None = None,\n        outfile: StrPath | None = None,\n        timing: bool = False,\n    ) -> None: ...\n    def run(self, cmd: str | types.CodeType) -> None: ...\n    def runctx(\n        self, cmd: str | types.CodeType, globals: Mapping[str, Any] | None = None, locals: Mapping[str, Any] | None = None\n    ) -> None: ...\n    def runfunc(self, func: Callable[_P, _T], /, *args: _P.args, **kw: _P.kwargs) -> _T: ...\n    def file_module_function_of(self, frame: types.FrameType) -> _FileModuleFunction: ...\n    def globaltrace_trackcallers(self, frame: types.FrameType, why: str, arg: Any) -> None: ...\n    def globaltrace_countfuncs(self, frame: types.FrameType, why: str, arg: Any) -> None: ...\n    def globaltrace_lt(self, frame: types.FrameType, why: str, arg: Any) -> None: ...\n    def localtrace_trace_and_count(self, frame: types.FrameType, why: str, arg: Any) -> TraceFunction: ...\n    def localtrace_trace(self, frame: types.FrameType, why: str, arg: Any) -> TraceFunction: ...\n    def localtrace_count(self, frame: types.FrameType, why: str, arg: Any) -> TraceFunction: ...\n    def results(self) -> CoverageResults: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/traceback.pyi",
    "content": "import sys\nfrom _typeshed import SupportsWrite, Unused\nfrom collections.abc import Generator, Iterable, Iterator, Mapping\nfrom types import FrameType, TracebackType\nfrom typing import Any, ClassVar, Literal, SupportsIndex, overload\nfrom typing_extensions import Self, TypeAlias, deprecated\n\n__all__ = [\n    \"extract_stack\",\n    \"extract_tb\",\n    \"format_exception\",\n    \"format_exception_only\",\n    \"format_list\",\n    \"format_stack\",\n    \"format_tb\",\n    \"print_exc\",\n    \"format_exc\",\n    \"print_exception\",\n    \"print_last\",\n    \"print_stack\",\n    \"print_tb\",\n    \"clear_frames\",\n    \"FrameSummary\",\n    \"StackSummary\",\n    \"TracebackException\",\n    \"walk_stack\",\n    \"walk_tb\",\n]\n\nif sys.version_info >= (3, 14):\n    __all__ += [\"print_list\"]\n\n_FrameSummaryTuple: TypeAlias = tuple[str, int, str, str | None]\n\ndef print_tb(tb: TracebackType | None, limit: int | None = None, file: SupportsWrite[str] | None = None) -> None: ...\n\nif sys.version_info >= (3, 10):\n    @overload\n    def print_exception(\n        exc: type[BaseException] | None,\n        /,\n        value: BaseException | None = ...,\n        tb: TracebackType | None = ...,\n        limit: int | None = None,\n        file: SupportsWrite[str] | None = None,\n        chain: bool = True,\n    ) -> None: ...\n    @overload\n    def print_exception(\n        exc: BaseException, /, *, limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True\n    ) -> None: ...\n    @overload\n    def format_exception(\n        exc: type[BaseException] | None,\n        /,\n        value: BaseException | None = ...,\n        tb: TracebackType | None = ...,\n        limit: int | None = None,\n        chain: bool = True,\n    ) -> list[str]: ...\n    @overload\n    def format_exception(exc: BaseException, /, *, limit: int | None = None, chain: bool = True) -> list[str]: ...\n\nelse:\n    def print_exception(\n        etype: type[BaseException] | None,\n        value: BaseException | None,\n        tb: TracebackType | None,\n        limit: int | None = None,\n        file: SupportsWrite[str] | None = None,\n        chain: bool = True,\n    ) -> None: ...\n    def format_exception(\n        etype: type[BaseException] | None,\n        value: BaseException | None,\n        tb: TracebackType | None,\n        limit: int | None = None,\n        chain: bool = True,\n    ) -> list[str]: ...\n\ndef print_exc(limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ...\ndef print_last(limit: int | None = None, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ...\ndef print_stack(f: FrameType | None = None, limit: int | None = None, file: SupportsWrite[str] | None = None) -> None: ...\ndef extract_tb(tb: TracebackType | None, limit: int | None = None) -> StackSummary: ...\ndef extract_stack(f: FrameType | None = None, limit: int | None = None) -> StackSummary: ...\ndef format_list(extracted_list: Iterable[FrameSummary | _FrameSummaryTuple]) -> list[str]: ...\ndef print_list(extracted_list: Iterable[FrameSummary | _FrameSummaryTuple], file: SupportsWrite[str] | None = None) -> None: ...\n\nif sys.version_info >= (3, 13):\n    @overload\n    def format_exception_only(exc: BaseException | None, /, *, show_group: bool = False) -> list[str]: ...\n    @overload\n    def format_exception_only(exc: Unused, /, value: BaseException | None, *, show_group: bool = False) -> list[str]: ...\n\nelif sys.version_info >= (3, 10):\n    @overload\n    def format_exception_only(exc: BaseException | None, /) -> list[str]: ...\n    @overload\n    def format_exception_only(exc: Unused, /, value: BaseException | None) -> list[str]: ...\n\nelse:\n    def format_exception_only(etype: type[BaseException] | None, value: BaseException | None) -> list[str]: ...\n\ndef format_exc(limit: int | None = None, chain: bool = True) -> str: ...\ndef format_tb(tb: TracebackType | None, limit: int | None = None) -> list[str]: ...\ndef format_stack(f: FrameType | None = None, limit: int | None = None) -> list[str]: ...\ndef clear_frames(tb: TracebackType | None) -> None: ...\ndef walk_stack(f: FrameType | None) -> Iterator[tuple[FrameType, int]]: ...\ndef walk_tb(tb: TracebackType | None) -> Iterator[tuple[FrameType, int]]: ...\n\nif sys.version_info >= (3, 11):\n    class _ExceptionPrintContext:\n        def indent(self) -> str: ...\n        def emit(self, text_gen: str | Iterable[str], margin_char: str | None = None) -> Generator[str, None, None]: ...\n\nclass TracebackException:\n    __cause__: TracebackException | None\n    __context__: TracebackException | None\n    if sys.version_info >= (3, 11):\n        exceptions: list[TracebackException] | None\n    __suppress_context__: bool\n    if sys.version_info >= (3, 11):\n        __notes__: list[str] | None\n    stack: StackSummary\n\n    # These fields only exist for `SyntaxError`s, but there is no way to express that in the type system.\n    filename: str\n    lineno: str | None\n    if sys.version_info >= (3, 10):\n        end_lineno: str | None\n    text: str\n    offset: int\n    if sys.version_info >= (3, 10):\n        end_offset: int | None\n    msg: str\n\n    if sys.version_info >= (3, 13):\n        @property\n        def exc_type_str(self) -> str: ...\n        @property\n        @deprecated(\"Deprecated since Python 3.13. Use `exc_type_str` instead.\")\n        def exc_type(self) -> type[BaseException] | None: ...\n    else:\n        exc_type: type[BaseException]\n    if sys.version_info >= (3, 13):\n        def __init__(\n            self,\n            exc_type: type[BaseException],\n            exc_value: BaseException,\n            exc_traceback: TracebackType | None,\n            *,\n            limit: int | None = None,\n            lookup_lines: bool = True,\n            capture_locals: bool = False,\n            compact: bool = False,\n            max_group_width: int = 15,\n            max_group_depth: int = 10,\n            save_exc_type: bool = True,\n            _seen: set[int] | None = None,\n        ) -> None: ...\n    elif sys.version_info >= (3, 11):\n        def __init__(\n            self,\n            exc_type: type[BaseException],\n            exc_value: BaseException,\n            exc_traceback: TracebackType | None,\n            *,\n            limit: int | None = None,\n            lookup_lines: bool = True,\n            capture_locals: bool = False,\n            compact: bool = False,\n            max_group_width: int = 15,\n            max_group_depth: int = 10,\n            _seen: set[int] | None = None,\n        ) -> None: ...\n    elif sys.version_info >= (3, 10):\n        def __init__(\n            self,\n            exc_type: type[BaseException],\n            exc_value: BaseException,\n            exc_traceback: TracebackType | None,\n            *,\n            limit: int | None = None,\n            lookup_lines: bool = True,\n            capture_locals: bool = False,\n            compact: bool = False,\n            _seen: set[int] | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            exc_type: type[BaseException],\n            exc_value: BaseException,\n            exc_traceback: TracebackType | None,\n            *,\n            limit: int | None = None,\n            lookup_lines: bool = True,\n            capture_locals: bool = False,\n            _seen: set[int] | None = None,\n        ) -> None: ...\n\n    if sys.version_info >= (3, 11):\n        @classmethod\n        def from_exception(\n            cls,\n            exc: BaseException,\n            *,\n            limit: int | None = None,\n            lookup_lines: bool = True,\n            capture_locals: bool = False,\n            compact: bool = False,\n            max_group_width: int = 15,\n            max_group_depth: int = 10,\n        ) -> Self: ...\n    elif sys.version_info >= (3, 10):\n        @classmethod\n        def from_exception(\n            cls,\n            exc: BaseException,\n            *,\n            limit: int | None = None,\n            lookup_lines: bool = True,\n            capture_locals: bool = False,\n            compact: bool = False,\n        ) -> Self: ...\n    else:\n        @classmethod\n        def from_exception(\n            cls, exc: BaseException, *, limit: int | None = None, lookup_lines: bool = True, capture_locals: bool = False\n        ) -> Self: ...\n\n    def __eq__(self, other: object) -> bool: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    if sys.version_info >= (3, 11):\n        def format(self, *, chain: bool = True, _ctx: _ExceptionPrintContext | None = None) -> Generator[str, None, None]: ...\n    else:\n        def format(self, *, chain: bool = True) -> Generator[str, None, None]: ...\n\n    if sys.version_info >= (3, 13):\n        def format_exception_only(self, *, show_group: bool = False, _depth: int = 0) -> Generator[str, None, None]: ...\n    else:\n        def format_exception_only(self) -> Generator[str, None, None]: ...\n\n    if sys.version_info >= (3, 11):\n        def print(self, *, file: SupportsWrite[str] | None = None, chain: bool = True) -> None: ...\n\nclass FrameSummary:\n    if sys.version_info >= (3, 13):\n        __slots__ = (\n            \"filename\",\n            \"lineno\",\n            \"end_lineno\",\n            \"colno\",\n            \"end_colno\",\n            \"name\",\n            \"_lines\",\n            \"_lines_dedented\",\n            \"locals\",\n            \"_code\",\n        )\n    elif sys.version_info >= (3, 11):\n        __slots__ = (\"filename\", \"lineno\", \"end_lineno\", \"colno\", \"end_colno\", \"name\", \"_line\", \"locals\")\n    else:\n        __slots__ = (\"filename\", \"lineno\", \"name\", \"_line\", \"locals\")\n    if sys.version_info >= (3, 11):\n        def __init__(\n            self,\n            filename: str,\n            lineno: int | None,\n            name: str,\n            *,\n            lookup_line: bool = True,\n            locals: Mapping[str, str] | None = None,\n            line: str | None = None,\n            end_lineno: int | None = None,\n            colno: int | None = None,\n            end_colno: int | None = None,\n        ) -> None: ...\n        end_lineno: int | None\n        colno: int | None\n        end_colno: int | None\n    else:\n        def __init__(\n            self,\n            filename: str,\n            lineno: int | None,\n            name: str,\n            *,\n            lookup_line: bool = True,\n            locals: Mapping[str, str] | None = None,\n            line: str | None = None,\n        ) -> None: ...\n    filename: str\n    lineno: int | None\n    name: str\n    locals: dict[str, str] | None\n    @property\n    def line(self) -> str | None: ...\n    @overload\n    def __getitem__(self, pos: Literal[0]) -> str: ...\n    @overload\n    def __getitem__(self, pos: Literal[1]) -> int: ...\n    @overload\n    def __getitem__(self, pos: Literal[2]) -> str: ...\n    @overload\n    def __getitem__(self, pos: Literal[3]) -> str | None: ...\n    @overload\n    def __getitem__(self, pos: SupportsIndex) -> Any: ...\n    @overload\n    def __getitem__(self, pos: slice[SupportsIndex | None]) -> tuple[Any, ...]: ...\n    def __iter__(self) -> Iterator[Any]: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __len__(self) -> Literal[4]: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\nclass StackSummary(list[FrameSummary]):\n    @classmethod\n    def extract(\n        cls,\n        frame_gen: Iterable[tuple[FrameType, int]],\n        *,\n        limit: int | None = None,\n        lookup_lines: bool = True,\n        capture_locals: bool = False,\n    ) -> StackSummary: ...\n    @classmethod\n    def from_list(cls, a_list: Iterable[FrameSummary | _FrameSummaryTuple]) -> StackSummary: ...\n    if sys.version_info >= (3, 11):\n        def format_frame_summary(self, frame_summary: FrameSummary) -> str: ...\n\n    def format(self) -> list[str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tracemalloc.pyi",
    "content": "import sys\nfrom _tracemalloc import *\nfrom collections.abc import Sequence\nfrom typing import Any, SupportsIndex, overload\nfrom typing_extensions import TypeAlias\n\ndef get_object_traceback(obj: object) -> Traceback | None: ...\ndef take_snapshot() -> Snapshot: ...\n\nclass BaseFilter:\n    inclusive: bool\n    def __init__(self, inclusive: bool) -> None: ...\n\nclass DomainFilter(BaseFilter):\n    @property\n    def domain(self) -> int: ...\n    def __init__(self, inclusive: bool, domain: int) -> None: ...\n\nclass Filter(BaseFilter):\n    domain: int | None\n    lineno: int | None\n    @property\n    def filename_pattern(self) -> str: ...\n    all_frames: bool\n    def __init__(\n        self,\n        inclusive: bool,\n        filename_pattern: str,\n        lineno: int | None = None,\n        all_frames: bool = False,\n        domain: int | None = None,\n    ) -> None: ...\n\nclass Statistic:\n    __slots__ = (\"traceback\", \"size\", \"count\")\n    count: int\n    size: int\n    traceback: Traceback\n    def __init__(self, traceback: Traceback, size: int, count: int) -> None: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n\nclass StatisticDiff:\n    __slots__ = (\"traceback\", \"size\", \"size_diff\", \"count\", \"count_diff\")\n    count: int\n    count_diff: int\n    size: int\n    size_diff: int\n    traceback: Traceback\n    def __init__(self, traceback: Traceback, size: int, size_diff: int, count: int, count_diff: int) -> None: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n\n_FrameTuple: TypeAlias = tuple[str, int]\n\nclass Frame:\n    __slots__ = (\"_frame\",)\n    @property\n    def filename(self) -> str: ...\n    @property\n    def lineno(self) -> int: ...\n    def __init__(self, frame: _FrameTuple) -> None: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __lt__(self, other: Frame) -> bool: ...\n    if sys.version_info >= (3, 11):\n        def __gt__(self, other: Frame) -> bool: ...\n        def __ge__(self, other: Frame) -> bool: ...\n        def __le__(self, other: Frame) -> bool: ...\n    else:\n        def __gt__(self, other: Frame, NotImplemented: Any = ...) -> bool: ...\n        def __ge__(self, other: Frame, NotImplemented: Any = ...) -> bool: ...\n        def __le__(self, other: Frame, NotImplemented: Any = ...) -> bool: ...\n\n_TraceTuple: TypeAlias = tuple[int, int, Sequence[_FrameTuple], int | None] | tuple[int, int, Sequence[_FrameTuple]]\n\nclass Trace:\n    __slots__ = (\"_trace\",)\n    @property\n    def domain(self) -> int: ...\n    @property\n    def size(self) -> int: ...\n    @property\n    def traceback(self) -> Traceback: ...\n    def __init__(self, trace: _TraceTuple) -> None: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n\nclass Traceback(Sequence[Frame]):\n    __slots__ = (\"_frames\", \"_total_nframe\")\n    @property\n    def total_nframe(self) -> int | None: ...\n    def __init__(self, frames: Sequence[_FrameTuple], total_nframe: int | None = None) -> None: ...\n    def format(self, limit: int | None = None, most_recent_first: bool = False) -> list[str]: ...\n    @overload\n    def __getitem__(self, index: SupportsIndex) -> Frame: ...\n    @overload\n    def __getitem__(self, index: slice[SupportsIndex | None]) -> Sequence[Frame]: ...\n    def __contains__(self, frame: Frame) -> bool: ...  # type: ignore[override]\n    def __len__(self) -> int: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __lt__(self, other: Traceback) -> bool: ...\n    if sys.version_info >= (3, 11):\n        def __gt__(self, other: Traceback) -> bool: ...\n        def __ge__(self, other: Traceback) -> bool: ...\n        def __le__(self, other: Traceback) -> bool: ...\n    else:\n        def __gt__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ...\n        def __ge__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ...\n        def __le__(self, other: Traceback, NotImplemented: Any = ...) -> bool: ...\n\nclass Snapshot:\n    def __init__(self, traces: Sequence[_TraceTuple], traceback_limit: int) -> None: ...\n    def compare_to(self, old_snapshot: Snapshot, key_type: str, cumulative: bool = False) -> list[StatisticDiff]: ...\n    def dump(self, filename: str) -> None: ...\n    def filter_traces(self, filters: Sequence[DomainFilter | Filter]) -> Snapshot: ...\n    @staticmethod\n    def load(filename: str) -> Snapshot: ...\n    def statistics(self, key_type: str, cumulative: bool = False) -> list[Statistic]: ...\n    traceback_limit: int\n    traces: Sequence[Trace]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/tty.pyi",
    "content": "import sys\nimport termios\nfrom typing import IO, Final\nfrom typing_extensions import TypeAlias\n\nif sys.platform != \"win32\":\n    __all__ = [\"setraw\", \"setcbreak\"]\n    if sys.version_info >= (3, 12):\n        __all__ += [\"cfmakeraw\", \"cfmakecbreak\"]\n\n        _ModeSetterReturn: TypeAlias = termios._AttrReturn\n    else:\n        _ModeSetterReturn: TypeAlias = None\n\n    _FD: TypeAlias = int | IO[str]\n\n    # XXX: Undocumented integer constants\n    IFLAG: Final = 0\n    OFLAG: Final = 1\n    CFLAG: Final = 2\n    LFLAG: Final = 3\n    ISPEED: Final = 4\n    OSPEED: Final = 5\n    CC: Final = 6\n    def setraw(fd: _FD, when: int = 2) -> _ModeSetterReturn: ...\n    def setcbreak(fd: _FD, when: int = 2) -> _ModeSetterReturn: ...\n\n    if sys.version_info >= (3, 12):\n        def cfmakeraw(mode: termios._Attr) -> None: ...\n        def cfmakecbreak(mode: termios._Attr) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/turtle.pyi",
    "content": "import sys\nfrom _typeshed import StrPath\nfrom collections.abc import Callable, Generator, Sequence\nfrom contextlib import contextmanager\nfrom tkinter import Canvas, Frame, Misc, PhotoImage, Scrollbar\nfrom typing import Any, ClassVar, Literal, TypedDict, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias, deprecated, disjoint_base\n\n__all__ = [\n    \"ScrolledCanvas\",\n    \"TurtleScreen\",\n    \"Screen\",\n    \"RawTurtle\",\n    \"Turtle\",\n    \"RawPen\",\n    \"Pen\",\n    \"Shape\",\n    \"Vec2D\",\n    \"addshape\",\n    \"bgcolor\",\n    \"bgpic\",\n    \"bye\",\n    \"clearscreen\",\n    \"colormode\",\n    \"delay\",\n    \"exitonclick\",\n    \"getcanvas\",\n    \"getshapes\",\n    \"listen\",\n    \"mainloop\",\n    \"mode\",\n    \"numinput\",\n    \"onkey\",\n    \"onkeypress\",\n    \"onkeyrelease\",\n    \"onscreenclick\",\n    \"ontimer\",\n    \"register_shape\",\n    \"resetscreen\",\n    \"screensize\",\n    \"setup\",\n    \"setworldcoordinates\",\n    \"textinput\",\n    \"title\",\n    \"tracer\",\n    \"turtles\",\n    \"update\",\n    \"window_height\",\n    \"window_width\",\n    \"back\",\n    \"backward\",\n    \"begin_fill\",\n    \"begin_poly\",\n    \"bk\",\n    \"circle\",\n    \"clear\",\n    \"clearstamp\",\n    \"clearstamps\",\n    \"clone\",\n    \"color\",\n    \"degrees\",\n    \"distance\",\n    \"dot\",\n    \"down\",\n    \"end_fill\",\n    \"end_poly\",\n    \"fd\",\n    \"fillcolor\",\n    \"filling\",\n    \"forward\",\n    \"get_poly\",\n    \"getpen\",\n    \"getscreen\",\n    \"get_shapepoly\",\n    \"getturtle\",\n    \"goto\",\n    \"heading\",\n    \"hideturtle\",\n    \"home\",\n    \"ht\",\n    \"isdown\",\n    \"isvisible\",\n    \"left\",\n    \"lt\",\n    \"onclick\",\n    \"ondrag\",\n    \"onrelease\",\n    \"pd\",\n    \"pen\",\n    \"pencolor\",\n    \"pendown\",\n    \"pensize\",\n    \"penup\",\n    \"pos\",\n    \"position\",\n    \"pu\",\n    \"radians\",\n    \"right\",\n    \"reset\",\n    \"resizemode\",\n    \"rt\",\n    \"seth\",\n    \"setheading\",\n    \"setpos\",\n    \"setposition\",\n    \"setundobuffer\",\n    \"setx\",\n    \"sety\",\n    \"shape\",\n    \"shapesize\",\n    \"shapetransform\",\n    \"shearfactor\",\n    \"showturtle\",\n    \"speed\",\n    \"st\",\n    \"stamp\",\n    \"tilt\",\n    \"tiltangle\",\n    \"towards\",\n    \"turtlesize\",\n    \"undo\",\n    \"undobufferentries\",\n    \"up\",\n    \"width\",\n    \"write\",\n    \"xcor\",\n    \"ycor\",\n    \"write_docstringdict\",\n    \"done\",\n    \"Terminator\",\n]\n\nif sys.version_info >= (3, 14):\n    __all__ += [\"fill\", \"no_animation\", \"poly\", \"save\"]\n\nif sys.version_info >= (3, 12):\n    __all__ += [\"teleport\"]\n\nif sys.version_info < (3, 13):\n    __all__ += [\"settiltangle\"]\n\n# Note: '_Color' is the alias we use for arguments and _AnyColor is the\n# alias we use for return types. Really, these two aliases should be the\n# same, but as per the \"no union returns\" typeshed policy, we'll return\n# Any instead.\n_Color: TypeAlias = str | tuple[float, float, float]\n_AnyColor: TypeAlias = Any\n\n@type_check_only\nclass _PenState(TypedDict):\n    shown: bool\n    pendown: bool\n    pencolor: _Color\n    fillcolor: _Color\n    pensize: int\n    speed: int\n    resizemode: Literal[\"auto\", \"user\", \"noresize\"]\n    stretchfactor: tuple[float, float]\n    shearfactor: float\n    outline: int\n    tilt: float\n\n_Speed: TypeAlias = str | float\n_PolygonCoords: TypeAlias = Sequence[tuple[float, float]]\n\nif sys.version_info >= (3, 12):\n    class Vec2D(tuple[float, float]):\n        def __new__(cls, x: float, y: float) -> Self: ...\n        def __add__(self, other: tuple[float, float]) -> Vec2D: ...  # type: ignore[override]\n        @overload  # type: ignore[override]\n        def __mul__(self, other: Vec2D) -> float: ...\n        @overload\n        def __mul__(self, other: float) -> Vec2D: ...\n        def __rmul__(self, other: float) -> Vec2D: ...  # type: ignore[override]\n        def __sub__(self, other: tuple[float, float]) -> Vec2D: ...\n        def __neg__(self) -> Vec2D: ...\n        def __abs__(self) -> float: ...\n        def rotate(self, angle: float) -> Vec2D: ...\n\nelse:\n    @disjoint_base\n    class Vec2D(tuple[float, float]):\n        def __new__(cls, x: float, y: float) -> Self: ...\n        def __add__(self, other: tuple[float, float]) -> Vec2D: ...  # type: ignore[override]\n        @overload  # type: ignore[override]\n        def __mul__(self, other: Vec2D) -> float: ...\n        @overload\n        def __mul__(self, other: float) -> Vec2D: ...\n        def __rmul__(self, other: float) -> Vec2D: ...  # type: ignore[override]\n        def __sub__(self, other: tuple[float, float]) -> Vec2D: ...\n        def __neg__(self) -> Vec2D: ...\n        def __abs__(self) -> float: ...\n        def rotate(self, angle: float) -> Vec2D: ...\n\n# Does not actually inherit from Canvas, but dynamically gets all methods of Canvas\nclass ScrolledCanvas(Canvas, Frame):  # type: ignore[misc]\n    bg: str\n    hscroll: Scrollbar\n    vscroll: Scrollbar\n    def __init__(\n        self, master: Misc | None, width: int = 500, height: int = 350, canvwidth: int = 600, canvheight: int = 500\n    ) -> None: ...\n    canvwidth: int\n    canvheight: int\n    def reset(self, canvwidth: int | None = None, canvheight: int | None = None, bg: str | None = None) -> None: ...\n\nclass TurtleScreenBase:\n    cv: Canvas\n    canvwidth: int\n    canvheight: int\n    xscale: float\n    yscale: float\n    def __init__(self, cv: Canvas) -> None: ...\n    def mainloop(self) -> None: ...\n    def textinput(self, title: str, prompt: str) -> str | None: ...\n    def numinput(\n        self, title: str, prompt: str, default: float | None = None, minval: float | None = None, maxval: float | None = None\n    ) -> float | None: ...\n\nclass Terminator(Exception): ...\nclass TurtleGraphicsError(Exception): ...\n\nclass Shape:\n    def __init__(\n        self, type_: Literal[\"polygon\", \"image\", \"compound\"], data: _PolygonCoords | PhotoImage | None = None\n    ) -> None: ...\n    def addcomponent(self, poly: _PolygonCoords, fill: _Color, outline: _Color | None = None) -> None: ...\n\nclass TurtleScreen(TurtleScreenBase):\n    def __init__(\n        self, cv: Canvas, mode: Literal[\"standard\", \"logo\", \"world\"] = \"standard\", colormode: float = 1.0, delay: int = 10\n    ) -> None: ...\n    def clear(self) -> None: ...\n    @overload\n    def mode(self, mode: None = None) -> str: ...\n    @overload\n    def mode(self, mode: Literal[\"standard\", \"logo\", \"world\"]) -> None: ...\n    def setworldcoordinates(self, llx: float, lly: float, urx: float, ury: float) -> None: ...\n    def register_shape(self, name: str, shape: _PolygonCoords | Shape | None = None) -> None: ...\n    @overload\n    def colormode(self, cmode: None = None) -> float: ...\n    @overload\n    def colormode(self, cmode: float) -> None: ...\n    def reset(self) -> None: ...\n    def turtles(self) -> list[Turtle]: ...\n    @overload\n    def bgcolor(self) -> _AnyColor: ...\n    @overload\n    def bgcolor(self, color: _Color) -> None: ...\n    @overload\n    def bgcolor(self, r: float, g: float, b: float) -> None: ...\n    @overload\n    def tracer(self, n: None = None) -> int: ...\n    @overload\n    def tracer(self, n: int, delay: int | None = None) -> None: ...\n    @overload\n    def delay(self, delay: None = None) -> int: ...\n    @overload\n    def delay(self, delay: int) -> None: ...\n    if sys.version_info >= (3, 14):\n        @contextmanager\n        def no_animation(self) -> Generator[None]: ...\n\n    def update(self) -> None: ...\n    def window_width(self) -> int: ...\n    def window_height(self) -> int: ...\n    def getcanvas(self) -> Canvas: ...\n    def getshapes(self) -> list[str]: ...\n    def onclick(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ...\n    def onkey(self, fun: Callable[[], object], key: str) -> None: ...\n    def listen(self, xdummy: float | None = None, ydummy: float | None = None) -> None: ...\n    def ontimer(self, fun: Callable[[], object], t: int = 0) -> None: ...\n    @overload\n    def bgpic(self, picname: None = None) -> str: ...\n    @overload\n    def bgpic(self, picname: str) -> None: ...\n    @overload\n    def screensize(self, canvwidth: None = None, canvheight: None = None, bg: None = None) -> tuple[int, int]: ...\n    # Looks like if self.cv is not a ScrolledCanvas, this could return a tuple as well\n    @overload\n    def screensize(self, canvwidth: int, canvheight: int, bg: _Color | None = None) -> None: ...\n    if sys.version_info >= (3, 14):\n        def save(self, filename: StrPath, *, overwrite: bool = False) -> None: ...\n    onscreenclick = onclick\n    resetscreen = reset\n    clearscreen = clear\n    addshape = register_shape\n    def onkeypress(self, fun: Callable[[], object], key: str | None = None) -> None: ...\n    onkeyrelease = onkey\n\nclass TNavigator:\n    START_ORIENTATION: dict[str, Vec2D]\n    DEFAULT_MODE: str\n    DEFAULT_ANGLEOFFSET: int\n    DEFAULT_ANGLEORIENT: int\n    def __init__(self, mode: Literal[\"standard\", \"logo\", \"world\"] = \"standard\") -> None: ...\n    def reset(self) -> None: ...\n    def degrees(self, fullcircle: float = 360.0) -> None: ...\n    def radians(self) -> None: ...\n    if sys.version_info >= (3, 12):\n        def teleport(self, x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ...\n\n    def forward(self, distance: float) -> None: ...\n    def back(self, distance: float) -> None: ...\n    def right(self, angle: float) -> None: ...\n    def left(self, angle: float) -> None: ...\n    def pos(self) -> Vec2D: ...\n    def xcor(self) -> float: ...\n    def ycor(self) -> float: ...\n    @overload\n    def goto(self, x: tuple[float, float], y: None = None) -> None: ...\n    @overload\n    def goto(self, x: float, y: float) -> None: ...\n    def home(self) -> None: ...\n    def setx(self, x: float) -> None: ...\n    def sety(self, y: float) -> None: ...\n    @overload\n    def distance(self, x: TNavigator | tuple[float, float], y: None = None) -> float: ...\n    @overload\n    def distance(self, x: float, y: float) -> float: ...\n    @overload\n    def towards(self, x: TNavigator | tuple[float, float], y: None = None) -> float: ...\n    @overload\n    def towards(self, x: float, y: float) -> float: ...\n    def heading(self) -> float: ...\n    def setheading(self, to_angle: float) -> None: ...\n    def circle(self, radius: float, extent: float | None = None, steps: int | None = None) -> None: ...\n    def speed(self, s: int | None = 0) -> int | None: ...\n    fd = forward\n    bk = back\n    backward = back\n    rt = right\n    lt = left\n    position = pos\n    setpos = goto\n    setposition = goto\n    seth = setheading\n\nclass TPen:\n    def __init__(self, resizemode: Literal[\"auto\", \"user\", \"noresize\"] = \"noresize\") -> None: ...\n    @overload\n    def resizemode(self, rmode: None = None) -> str: ...\n    @overload\n    def resizemode(self, rmode: Literal[\"auto\", \"user\", \"noresize\"]) -> None: ...\n    @overload\n    def pensize(self, width: None = None) -> int: ...\n    @overload\n    def pensize(self, width: int) -> None: ...\n    def penup(self) -> None: ...\n    def pendown(self) -> None: ...\n    def isdown(self) -> bool: ...\n    @overload\n    def speed(self, speed: None = None) -> int: ...\n    @overload\n    def speed(self, speed: _Speed) -> None: ...\n    @overload\n    def pencolor(self) -> _AnyColor: ...\n    @overload\n    def pencolor(self, color: _Color) -> None: ...\n    @overload\n    def pencolor(self, r: float, g: float, b: float) -> None: ...\n    @overload\n    def fillcolor(self) -> _AnyColor: ...\n    @overload\n    def fillcolor(self, color: _Color) -> None: ...\n    @overload\n    def fillcolor(self, r: float, g: float, b: float) -> None: ...\n    @overload\n    def color(self) -> tuple[_AnyColor, _AnyColor]: ...\n    @overload\n    def color(self, color: _Color) -> None: ...\n    @overload\n    def color(self, r: float, g: float, b: float) -> None: ...\n    @overload\n    def color(self, color1: _Color, color2: _Color) -> None: ...\n    if sys.version_info >= (3, 12):\n        def teleport(self, x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ...\n\n    def showturtle(self) -> None: ...\n    def hideturtle(self) -> None: ...\n    def isvisible(self) -> bool: ...\n    # Note: signatures 1 and 2 overlap unsafely when no arguments are provided\n    @overload\n    def pen(self) -> _PenState: ...\n    @overload\n    def pen(\n        self,\n        pen: _PenState | None = None,\n        *,\n        shown: bool = ...,\n        pendown: bool = ...,\n        pencolor: _Color = ...,\n        fillcolor: _Color = ...,\n        pensize: int = ...,\n        speed: int = ...,\n        resizemode: Literal[\"auto\", \"user\", \"noresize\"] = ...,\n        stretchfactor: tuple[float, float] = ...,\n        outline: int = ...,\n        tilt: float = ...,\n    ) -> None: ...\n    width = pensize\n    up = penup\n    pu = penup\n    pd = pendown\n    down = pendown\n    st = showturtle\n    ht = hideturtle\n\nclass RawTurtle(TPen, TNavigator):  # type: ignore[misc]  # Conflicting methods in base classes\n    screen: TurtleScreen\n    screens: ClassVar[list[TurtleScreen]]\n    def __init__(\n        self,\n        canvas: Canvas | TurtleScreen | None = None,\n        shape: str = \"classic\",\n        undobuffersize: int = 1000,\n        visible: bool = True,\n    ) -> None: ...\n    def reset(self) -> None: ...\n    def setundobuffer(self, size: int | None) -> None: ...\n    def undobufferentries(self) -> int: ...\n    def clear(self) -> None: ...\n    def clone(self) -> Self: ...\n    @overload\n    def shape(self, name: None = None) -> str: ...\n    @overload\n    def shape(self, name: str) -> None: ...\n    # Unsafely overlaps when no arguments are provided\n    @overload\n    def shapesize(self) -> tuple[float, float, float]: ...\n    @overload\n    def shapesize(\n        self, stretch_wid: float | None = None, stretch_len: float | None = None, outline: float | None = None\n    ) -> None: ...\n    @overload\n    def shearfactor(self, shear: None = None) -> float: ...\n    @overload\n    def shearfactor(self, shear: float) -> None: ...\n    # Unsafely overlaps when no arguments are provided\n    @overload\n    def shapetransform(self) -> tuple[float, float, float, float]: ...\n    @overload\n    def shapetransform(\n        self, t11: float | None = None, t12: float | None = None, t21: float | None = None, t22: float | None = None\n    ) -> None: ...\n    def get_shapepoly(self) -> _PolygonCoords | None: ...\n\n    if sys.version_info < (3, 13):\n        @deprecated(\"Deprecated since Python 3.1; removed in Python 3.13. Use `tiltangle()` instead.\")\n        def settiltangle(self, angle: float) -> None: ...\n\n    @overload\n    def tiltangle(self, angle: None = None) -> float: ...\n    @overload\n    def tiltangle(self, angle: float) -> None: ...\n    def tilt(self, angle: float) -> None: ...\n    # Can return either 'int' or Tuple[int, ...] based on if the stamp is\n    # a compound stamp or not. So, as per the \"no Union return\" policy,\n    # we return Any.\n    def stamp(self) -> Any: ...\n    def clearstamp(self, stampid: int | tuple[int, ...]) -> None: ...\n    def clearstamps(self, n: int | None = None) -> None: ...\n    def filling(self) -> bool: ...\n    if sys.version_info >= (3, 14):\n        @contextmanager\n        def fill(self) -> Generator[None]: ...\n\n    def begin_fill(self) -> None: ...\n    def end_fill(self) -> None: ...\n    @overload\n    def dot(self, size: int | _Color | None = None) -> None: ...\n    @overload\n    def dot(self, size: int | None, color: _Color, /) -> None: ...\n    @overload\n    def dot(self, size: int | None, r: float, g: float, b: float, /) -> None: ...\n    def write(\n        self, arg: object, move: bool = False, align: str = \"left\", font: tuple[str, int, str] = (\"Arial\", 8, \"normal\")\n    ) -> None: ...\n    if sys.version_info >= (3, 14):\n        @contextmanager\n        def poly(self) -> Generator[None]: ...\n\n    def begin_poly(self) -> None: ...\n    def end_poly(self) -> None: ...\n    def get_poly(self) -> _PolygonCoords | None: ...\n    def getscreen(self) -> TurtleScreen: ...\n    def getturtle(self) -> Self: ...\n    getpen = getturtle\n    def onclick(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ...\n    def onrelease(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ...\n    def ondrag(self, fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ...\n    def undo(self) -> None: ...\n    turtlesize = shapesize\n\nclass _Screen(TurtleScreen):\n    def __init__(self) -> None: ...\n    # Note int and float are interpreted differently, hence the Union instead of just float\n    def setup(\n        self,\n        width: int | float = 0.5,  # noqa: Y041\n        height: int | float = 0.75,  # noqa: Y041\n        startx: int | None = None,\n        starty: int | None = None,\n    ) -> None: ...\n    def title(self, titlestring: str) -> None: ...\n    def bye(self) -> None: ...\n    def exitonclick(self) -> None: ...\n\nclass Turtle(RawTurtle):\n    def __init__(self, shape: str = \"classic\", undobuffersize: int = 1000, visible: bool = True) -> None: ...\n\nRawPen = RawTurtle\nPen = Turtle\n\ndef write_docstringdict(filename: str = \"turtle_docstringdict\") -> None: ...\n\n# Functions copied from TurtleScreenBase:\n\ndef mainloop() -> None: ...\ndef textinput(title: str, prompt: str) -> str | None: ...\ndef numinput(\n    title: str, prompt: str, default: float | None = None, minval: float | None = None, maxval: float | None = None\n) -> float | None: ...\n\n# Functions copied from TurtleScreen:\n\ndef clear() -> None: ...\n@overload\ndef mode(mode: None = None) -> str: ...\n@overload\ndef mode(mode: Literal[\"standard\", \"logo\", \"world\"]) -> None: ...\ndef setworldcoordinates(llx: float, lly: float, urx: float, ury: float) -> None: ...\ndef register_shape(name: str, shape: _PolygonCoords | Shape | None = None) -> None: ...\n@overload\ndef colormode(cmode: None = None) -> float: ...\n@overload\ndef colormode(cmode: float) -> None: ...\ndef reset() -> None: ...\ndef turtles() -> list[Turtle]: ...\n@overload\ndef bgcolor() -> _AnyColor: ...\n@overload\ndef bgcolor(color: _Color) -> None: ...\n@overload\ndef bgcolor(r: float, g: float, b: float) -> None: ...\n@overload\ndef tracer(n: None = None) -> int: ...\n@overload\ndef tracer(n: int, delay: int | None = None) -> None: ...\n@overload\ndef delay(delay: None = None) -> int: ...\n@overload\ndef delay(delay: int) -> None: ...\n\nif sys.version_info >= (3, 14):\n    @contextmanager\n    def no_animation() -> Generator[None]: ...\n\ndef update() -> None: ...\ndef window_width() -> int: ...\ndef window_height() -> int: ...\ndef getcanvas() -> Canvas: ...\ndef getshapes() -> list[str]: ...\ndef onclick(fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ...\ndef onkey(fun: Callable[[], object], key: str) -> None: ...\ndef listen(xdummy: float | None = None, ydummy: float | None = None) -> None: ...\ndef ontimer(fun: Callable[[], object], t: int = 0) -> None: ...\n@overload\ndef bgpic(picname: None = None) -> str: ...\n@overload\ndef bgpic(picname: str) -> None: ...\n@overload\ndef screensize(canvwidth: None = None, canvheight: None = None, bg: None = None) -> tuple[int, int]: ...\n@overload\ndef screensize(canvwidth: int, canvheight: int, bg: _Color | None = None) -> None: ...\n\nif sys.version_info >= (3, 14):\n    def save(filename: StrPath, *, overwrite: bool = False) -> None: ...\n\nonscreenclick = onclick\nresetscreen = reset\nclearscreen = clear\naddshape = register_shape\n\ndef onkeypress(fun: Callable[[], object], key: str | None = None) -> None: ...\n\nonkeyrelease = onkey\n\n# Functions copied from _Screen:\n\ndef setup(width: float = 0.5, height: float = 0.75, startx: int | None = None, starty: int | None = None) -> None: ...\ndef title(titlestring: str) -> None: ...\ndef bye() -> None: ...\ndef exitonclick() -> None: ...\ndef Screen() -> _Screen: ...\n\n# Functions copied from TNavigator:\n\ndef degrees(fullcircle: float = 360.0) -> None: ...\ndef radians() -> None: ...\ndef forward(distance: float) -> None: ...\ndef back(distance: float) -> None: ...\ndef right(angle: float) -> None: ...\ndef left(angle: float) -> None: ...\ndef pos() -> Vec2D: ...\ndef xcor() -> float: ...\ndef ycor() -> float: ...\n@overload\ndef goto(x: tuple[float, float], y: None = None) -> None: ...\n@overload\ndef goto(x: float, y: float) -> None: ...\ndef home() -> None: ...\ndef setx(x: float) -> None: ...\ndef sety(y: float) -> None: ...\n@overload\ndef distance(x: TNavigator | tuple[float, float], y: None = None) -> float: ...\n@overload\ndef distance(x: float, y: float) -> float: ...\n@overload\ndef towards(x: TNavigator | tuple[float, float], y: None = None) -> float: ...\n@overload\ndef towards(x: float, y: float) -> float: ...\ndef heading() -> float: ...\ndef setheading(to_angle: float) -> None: ...\ndef circle(radius: float, extent: float | None = None, steps: int | None = None) -> None: ...\n\nfd = forward\nbk = back\nbackward = back\nrt = right\nlt = left\nposition = pos\nsetpos = goto\nsetposition = goto\nseth = setheading\n\n# Functions copied from TPen:\n@overload\ndef resizemode(rmode: None = None) -> str: ...\n@overload\ndef resizemode(rmode: Literal[\"auto\", \"user\", \"noresize\"]) -> None: ...\n@overload\ndef pensize(width: None = None) -> int: ...\n@overload\ndef pensize(width: int) -> None: ...\ndef penup() -> None: ...\ndef pendown() -> None: ...\ndef isdown() -> bool: ...\n@overload\ndef speed(speed: None = None) -> int: ...\n@overload\ndef speed(speed: _Speed) -> None: ...\n@overload\ndef pencolor() -> _AnyColor: ...\n@overload\ndef pencolor(color: _Color) -> None: ...\n@overload\ndef pencolor(r: float, g: float, b: float) -> None: ...\n@overload\ndef fillcolor() -> _AnyColor: ...\n@overload\ndef fillcolor(color: _Color) -> None: ...\n@overload\ndef fillcolor(r: float, g: float, b: float) -> None: ...\n@overload\ndef color() -> tuple[_AnyColor, _AnyColor]: ...\n@overload\ndef color(color: _Color) -> None: ...\n@overload\ndef color(r: float, g: float, b: float) -> None: ...\n@overload\ndef color(color1: _Color, color2: _Color) -> None: ...\ndef showturtle() -> None: ...\ndef hideturtle() -> None: ...\ndef isvisible() -> bool: ...\n\n# Note: signatures 1 and 2 overlap unsafely when no arguments are provided\n@overload\ndef pen() -> _PenState: ...\n@overload\ndef pen(\n    pen: _PenState | None = None,\n    *,\n    shown: bool = ...,\n    pendown: bool = ...,\n    pencolor: _Color = ...,\n    fillcolor: _Color = ...,\n    pensize: int = ...,\n    speed: int = ...,\n    resizemode: Literal[\"auto\", \"user\", \"noresize\"] = ...,\n    stretchfactor: tuple[float, float] = ...,\n    outline: int = ...,\n    tilt: float = ...,\n) -> None: ...\n\nwidth = pensize\nup = penup\npu = penup\npd = pendown\ndown = pendown\nst = showturtle\nht = hideturtle\n\n# Functions copied from RawTurtle:\n\ndef setundobuffer(size: int | None) -> None: ...\ndef undobufferentries() -> int: ...\n@overload\ndef shape(name: None = None) -> str: ...\n@overload\ndef shape(name: str) -> None: ...\n\nif sys.version_info >= (3, 12):\n    def teleport(x: float | None = None, y: float | None = None, *, fill_gap: bool = False) -> None: ...\n\n# Unsafely overlaps when no arguments are provided\n@overload\ndef shapesize() -> tuple[float, float, float]: ...\n@overload\ndef shapesize(stretch_wid: float | None = None, stretch_len: float | None = None, outline: float | None = None) -> None: ...\n@overload\ndef shearfactor(shear: None = None) -> float: ...\n@overload\ndef shearfactor(shear: float) -> None: ...\n\n# Unsafely overlaps when no arguments are provided\n@overload\ndef shapetransform() -> tuple[float, float, float, float]: ...\n@overload\ndef shapetransform(\n    t11: float | None = None, t12: float | None = None, t21: float | None = None, t22: float | None = None\n) -> None: ...\ndef get_shapepoly() -> _PolygonCoords | None: ...\n\nif sys.version_info < (3, 13):\n    @deprecated(\"Deprecated since Python 3.1; removed in Python 3.13. Use `tiltangle()` instead.\")\n    def settiltangle(angle: float) -> None: ...\n\n@overload\ndef tiltangle(angle: None = None) -> float: ...\n@overload\ndef tiltangle(angle: float) -> None: ...\ndef tilt(angle: float) -> None: ...\n\n# Can return either 'int' or Tuple[int, ...] based on if the stamp is\n# a compound stamp or not. So, as per the \"no Union return\" policy,\n# we return Any.\ndef stamp() -> Any: ...\ndef clearstamp(stampid: int | tuple[int, ...]) -> None: ...\ndef clearstamps(n: int | None = None) -> None: ...\ndef filling() -> bool: ...\n\nif sys.version_info >= (3, 14):\n    @contextmanager\n    def fill() -> Generator[None]: ...\n\ndef begin_fill() -> None: ...\ndef end_fill() -> None: ...\n@overload\ndef dot(size: int | _Color | None = None) -> None: ...\n@overload\ndef dot(size: int | None, color: _Color, /) -> None: ...\n@overload\ndef dot(size: int | None, r: float, g: float, b: float, /) -> None: ...\ndef write(arg: object, move: bool = False, align: str = \"left\", font: tuple[str, int, str] = (\"Arial\", 8, \"normal\")) -> None: ...\n\nif sys.version_info >= (3, 14):\n    @contextmanager\n    def poly() -> Generator[None]: ...\n\ndef begin_poly() -> None: ...\ndef end_poly() -> None: ...\ndef get_poly() -> _PolygonCoords | None: ...\ndef getscreen() -> TurtleScreen: ...\ndef getturtle() -> Turtle: ...\n\ngetpen = getturtle\n\ndef onrelease(fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ...\ndef ondrag(fun: Callable[[float, float], object], btn: int = 1, add: bool | None = None) -> None: ...\ndef undo() -> None: ...\n\nturtlesize = shapesize\n\n# Functions copied from RawTurtle with a few tweaks:\n\ndef clone() -> Turtle: ...\n\n# Extra functions present only in the global scope:\n\ndone = mainloop\n"
  },
  {
    "path": "mypy/typeshed/stdlib/types.pyi",
    "content": "import sys\nfrom _typeshed import AnnotationForm, MaybeNone, SupportsKeysAndGetItem\nfrom _typeshed.importlib import LoaderProtocol\nfrom collections.abc import (\n    AsyncGenerator,\n    Awaitable,\n    Callable,\n    Coroutine,\n    Generator,\n    ItemsView,\n    Iterable,\n    Iterator,\n    KeysView,\n    Mapping,\n    MutableSequence,\n    ValuesView,\n)\nfrom importlib.machinery import ModuleSpec\nfrom typing import Any, ClassVar, Literal, TypeVar, final, overload\nfrom typing_extensions import ParamSpec, Self, TypeAliasType, TypeVarTuple, deprecated, disjoint_base\n\nif sys.version_info >= (3, 14):\n    from _typeshed import AnnotateFunc\n\n__all__ = [\n    \"FunctionType\",\n    \"LambdaType\",\n    \"CodeType\",\n    \"MappingProxyType\",\n    \"SimpleNamespace\",\n    \"GeneratorType\",\n    \"CoroutineType\",\n    \"AsyncGeneratorType\",\n    \"MethodType\",\n    \"BuiltinFunctionType\",\n    \"ModuleType\",\n    \"TracebackType\",\n    \"FrameType\",\n    \"GetSetDescriptorType\",\n    \"MemberDescriptorType\",\n    \"new_class\",\n    \"prepare_class\",\n    \"DynamicClassAttribute\",\n    \"coroutine\",\n    \"BuiltinMethodType\",\n    \"ClassMethodDescriptorType\",\n    \"MethodDescriptorType\",\n    \"MethodWrapperType\",\n    \"WrapperDescriptorType\",\n    \"resolve_bases\",\n    \"CellType\",\n    \"GenericAlias\",\n]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"EllipsisType\", \"NoneType\", \"NotImplementedType\", \"UnionType\"]\n\nif sys.version_info >= (3, 12):\n    __all__ += [\"get_original_bases\"]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"CapsuleType\"]\n\n# Note, all classes \"defined\" here require special handling.\n\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n_KT_co = TypeVar(\"_KT_co\", covariant=True)\n_VT_co = TypeVar(\"_VT_co\", covariant=True)\n\n# Make sure this class definition stays roughly in line with `builtins.function`\n@final\nclass FunctionType:\n    @property\n    def __closure__(self) -> tuple[CellType, ...] | None: ...\n    __code__: CodeType\n    __defaults__: tuple[Any, ...] | None\n    __dict__: dict[str, Any]\n    @property\n    def __globals__(self) -> dict[str, Any]: ...\n    __name__: str\n    __qualname__: str\n    __annotations__: dict[str, AnnotationForm]\n    if sys.version_info >= (3, 14):\n        __annotate__: AnnotateFunc | None\n    __kwdefaults__: dict[str, Any] | None\n    if sys.version_info >= (3, 10):\n        @property\n        def __builtins__(self) -> dict[str, Any]: ...\n    if sys.version_info >= (3, 12):\n        __type_params__: tuple[TypeVar | ParamSpec | TypeVarTuple, ...]\n\n    __module__: str\n    if sys.version_info >= (3, 13):\n        def __new__(\n            cls,\n            code: CodeType,\n            globals: dict[str, Any],\n            name: str | None = None,\n            argdefs: tuple[object, ...] | None = None,\n            closure: tuple[CellType, ...] | None = None,\n            kwdefaults: dict[str, object] | None = None,\n        ) -> Self: ...\n    else:\n        def __new__(\n            cls,\n            code: CodeType,\n            globals: dict[str, Any],\n            name: str | None = None,\n            argdefs: tuple[object, ...] | None = None,\n            closure: tuple[CellType, ...] | None = None,\n        ) -> Self: ...\n\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n    @overload\n    def __get__(self, instance: None, owner: type, /) -> FunctionType: ...\n    @overload\n    def __get__(self, instance: object, owner: type | None = None, /) -> MethodType: ...\n\nLambdaType = FunctionType\n\n@final\nclass CodeType:\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    @property\n    def co_argcount(self) -> int: ...\n    @property\n    def co_posonlyargcount(self) -> int: ...\n    @property\n    def co_kwonlyargcount(self) -> int: ...\n    @property\n    def co_nlocals(self) -> int: ...\n    @property\n    def co_stacksize(self) -> int: ...\n    @property\n    def co_flags(self) -> int: ...\n    @property\n    def co_code(self) -> bytes: ...\n    @property\n    def co_consts(self) -> tuple[Any, ...]: ...\n    @property\n    def co_names(self) -> tuple[str, ...]: ...\n    @property\n    def co_varnames(self) -> tuple[str, ...]: ...\n    @property\n    def co_filename(self) -> str: ...\n    @property\n    def co_name(self) -> str: ...\n    @property\n    def co_firstlineno(self) -> int: ...\n    if sys.version_info >= (3, 10):\n        @property\n        @deprecated(\"Deprecated since Python 3.10; will be removed in Python 3.15. Use `CodeType.co_lines()` instead.\")\n        def co_lnotab(self) -> bytes: ...\n    else:\n        @property\n        def co_lnotab(self) -> bytes: ...\n\n    @property\n    def co_freevars(self) -> tuple[str, ...]: ...\n    @property\n    def co_cellvars(self) -> tuple[str, ...]: ...\n    if sys.version_info >= (3, 10):\n        @property\n        def co_linetable(self) -> bytes: ...\n        def co_lines(self) -> Iterator[tuple[int, int, int | None]]: ...\n    if sys.version_info >= (3, 11):\n        @property\n        def co_exceptiontable(self) -> bytes: ...\n        @property\n        def co_qualname(self) -> str: ...\n        def co_positions(self) -> Iterable[tuple[int | None, int | None, int | None, int | None]]: ...\n    if sys.version_info >= (3, 14):\n        def co_branches(self) -> Iterator[tuple[int, int, int]]: ...\n\n    if sys.version_info >= (3, 11):\n        def __new__(\n            cls,\n            argcount: int,\n            posonlyargcount: int,\n            kwonlyargcount: int,\n            nlocals: int,\n            stacksize: int,\n            flags: int,\n            codestring: bytes,\n            constants: tuple[object, ...],\n            names: tuple[str, ...],\n            varnames: tuple[str, ...],\n            filename: str,\n            name: str,\n            qualname: str,\n            firstlineno: int,\n            linetable: bytes,\n            exceptiontable: bytes,\n            freevars: tuple[str, ...] = ...,\n            cellvars: tuple[str, ...] = ...,\n            /,\n        ) -> Self: ...\n    elif sys.version_info >= (3, 10):\n        def __new__(\n            cls,\n            argcount: int,\n            posonlyargcount: int,\n            kwonlyargcount: int,\n            nlocals: int,\n            stacksize: int,\n            flags: int,\n            codestring: bytes,\n            constants: tuple[object, ...],\n            names: tuple[str, ...],\n            varnames: tuple[str, ...],\n            filename: str,\n            name: str,\n            firstlineno: int,\n            linetable: bytes,\n            freevars: tuple[str, ...] = ...,\n            cellvars: tuple[str, ...] = ...,\n            /,\n        ) -> Self: ...\n    else:\n        def __new__(\n            cls,\n            argcount: int,\n            posonlyargcount: int,\n            kwonlyargcount: int,\n            nlocals: int,\n            stacksize: int,\n            flags: int,\n            codestring: bytes,\n            constants: tuple[object, ...],\n            names: tuple[str, ...],\n            varnames: tuple[str, ...],\n            filename: str,\n            name: str,\n            firstlineno: int,\n            lnotab: bytes,\n            freevars: tuple[str, ...] = ...,\n            cellvars: tuple[str, ...] = ...,\n            /,\n        ) -> Self: ...\n    if sys.version_info >= (3, 11):\n        def replace(\n            self,\n            *,\n            co_argcount: int = -1,\n            co_posonlyargcount: int = -1,\n            co_kwonlyargcount: int = -1,\n            co_nlocals: int = -1,\n            co_stacksize: int = -1,\n            co_flags: int = -1,\n            co_firstlineno: int = -1,\n            co_code: bytes = ...,\n            co_consts: tuple[object, ...] = ...,\n            co_names: tuple[str, ...] = ...,\n            co_varnames: tuple[str, ...] = ...,\n            co_freevars: tuple[str, ...] = ...,\n            co_cellvars: tuple[str, ...] = ...,\n            co_filename: str = ...,\n            co_name: str = ...,\n            co_qualname: str = ...,\n            co_linetable: bytes = ...,\n            co_exceptiontable: bytes = ...,\n        ) -> Self: ...\n    elif sys.version_info >= (3, 10):\n        def replace(\n            self,\n            *,\n            co_argcount: int = -1,\n            co_posonlyargcount: int = -1,\n            co_kwonlyargcount: int = -1,\n            co_nlocals: int = -1,\n            co_stacksize: int = -1,\n            co_flags: int = -1,\n            co_firstlineno: int = -1,\n            co_code: bytes = ...,\n            co_consts: tuple[object, ...] = ...,\n            co_names: tuple[str, ...] = ...,\n            co_varnames: tuple[str, ...] = ...,\n            co_freevars: tuple[str, ...] = ...,\n            co_cellvars: tuple[str, ...] = ...,\n            co_filename: str = ...,\n            co_name: str = ...,\n            co_linetable: bytes = ...,\n        ) -> Self: ...\n    else:\n        def replace(\n            self,\n            *,\n            co_argcount: int = -1,\n            co_posonlyargcount: int = -1,\n            co_kwonlyargcount: int = -1,\n            co_nlocals: int = -1,\n            co_stacksize: int = -1,\n            co_flags: int = -1,\n            co_firstlineno: int = -1,\n            co_code: bytes = ...,\n            co_consts: tuple[object, ...] = ...,\n            co_names: tuple[str, ...] = ...,\n            co_varnames: tuple[str, ...] = ...,\n            co_freevars: tuple[str, ...] = ...,\n            co_cellvars: tuple[str, ...] = ...,\n            co_filename: str = ...,\n            co_name: str = ...,\n            co_lnotab: bytes = ...,\n        ) -> Self: ...\n\n    if sys.version_info >= (3, 13):\n        __replace__ = replace\n\n@final\nclass MappingProxyType(Mapping[_KT_co, _VT_co]):  # type: ignore[type-var]  # pyright: ignore[reportInvalidTypeArguments]\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __new__(cls, mapping: SupportsKeysAndGetItem[_KT_co, _VT_co]) -> Self: ...\n    def __getitem__(self, key: _KT_co, /) -> _VT_co: ...  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    def __iter__(self) -> Iterator[_KT_co]: ...\n    def __len__(self) -> int: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def copy(self) -> dict[_KT_co, _VT_co]: ...\n    def keys(self) -> KeysView[_KT_co]: ...\n    def values(self) -> ValuesView[_VT_co]: ...\n    def items(self) -> ItemsView[_KT_co, _VT_co]: ...\n    @overload\n    def get(self, key: _KT_co, /) -> _VT_co | None: ...  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter\n    @overload\n    def get(self, key: _KT_co, default: _VT_co, /) -> _VT_co: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter\n    @overload\n    def get(self, key: _KT_co, default: _T2, /) -> _VT_co | _T2: ...  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n    def __reversed__(self) -> Iterator[_KT_co]: ...\n    def __or__(self, value: Mapping[_T1, _T2], /) -> dict[_KT_co | _T1, _VT_co | _T2]: ...\n    def __ror__(self, value: Mapping[_T1, _T2], /) -> dict[_KT_co | _T1, _VT_co | _T2]: ...\n\nif sys.version_info >= (3, 12):\n    @disjoint_base\n    class SimpleNamespace:\n        __hash__: ClassVar[None]  # type: ignore[assignment]\n        if sys.version_info >= (3, 13):\n            def __init__(\n                self, mapping_or_iterable: Mapping[str, Any] | Iterable[tuple[str, Any]] = (), /, **kwargs: Any\n            ) -> None: ...\n        else:\n            def __init__(self, **kwargs: Any) -> None: ...\n\n        def __eq__(self, value: object, /) -> bool: ...\n        def __getattribute__(self, name: str, /) -> Any: ...\n        def __setattr__(self, name: str, value: Any, /) -> None: ...\n        def __delattr__(self, name: str, /) -> None: ...\n        if sys.version_info >= (3, 13):\n            def __replace__(self, **kwargs: Any) -> Self: ...\n\nelse:\n    class SimpleNamespace:\n        __hash__: ClassVar[None]  # type: ignore[assignment]\n        def __init__(self, **kwargs: Any) -> None: ...\n        def __eq__(self, value: object, /) -> bool: ...\n        def __getattribute__(self, name: str, /) -> Any: ...\n        def __setattr__(self, name: str, value: Any, /) -> None: ...\n        def __delattr__(self, name: str, /) -> None: ...\n\n@disjoint_base\nclass ModuleType:\n    __name__: str\n    __file__: str | None\n    @property\n    def __dict__(self) -> dict[str, Any]: ...  # type: ignore[override]\n    __loader__: LoaderProtocol | None\n    __package__: str | None\n    __path__: MutableSequence[str]\n    __spec__: ModuleSpec | None\n    # N.B. Although this is the same type as `builtins.object.__doc__`,\n    # it is deliberately redeclared here. Most symbols declared in the namespace\n    # of `types.ModuleType` are available as \"implicit globals\" within a module's\n    # namespace, but this is not true for symbols declared in the namespace of `builtins.object`.\n    # Redeclaring `__doc__` here helps some type checkers understand that `__doc__` is available\n    # as an implicit global in all modules, similar to `__name__`, `__file__`, `__spec__`, etc.\n    __doc__: str | None\n    __annotations__: dict[str, AnnotationForm]\n    if sys.version_info >= (3, 14):\n        __annotate__: AnnotateFunc | None\n\n    def __init__(self, name: str, doc: str | None = ...) -> None: ...\n    # __getattr__ doesn't exist at runtime,\n    # but having it here in typeshed makes dynamic imports\n    # using `builtins.__import__` or `importlib.import_module` less painful\n    def __getattr__(self, name: str) -> Any: ...\n\n@final\nclass CellType:\n    def __new__(cls, contents: object = ..., /) -> Self: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    cell_contents: Any\n\n_YieldT_co = TypeVar(\"_YieldT_co\", covariant=True)\n_SendT_contra = TypeVar(\"_SendT_contra\", contravariant=True, default=None)\n_ReturnT_co = TypeVar(\"_ReturnT_co\", covariant=True, default=None)\n\n@final\nclass GeneratorType(Generator[_YieldT_co, _SendT_contra, _ReturnT_co]):\n    @property\n    def gi_code(self) -> CodeType: ...\n    @property\n    def gi_frame(self) -> FrameType | None: ...\n    @property\n    def gi_running(self) -> bool: ...\n    @property\n    def gi_yieldfrom(self) -> Iterator[_YieldT_co] | None: ...\n    if sys.version_info >= (3, 11):\n        @property\n        def gi_suspended(self) -> bool: ...\n    __name__: str\n    __qualname__: str\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _YieldT_co: ...\n    def send(self, arg: _SendT_contra, /) -> _YieldT_co: ...\n    @overload\n    def throw(\n        self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., /\n    ) -> _YieldT_co: ...\n    @overload\n    def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ...\n    if sys.version_info >= (3, 13):\n        def __class_getitem__(cls, item: Any, /) -> Any: ...\n\n@final\nclass AsyncGeneratorType(AsyncGenerator[_YieldT_co, _SendT_contra]):\n    @property\n    def ag_await(self) -> Awaitable[Any] | None: ...\n    @property\n    def ag_code(self) -> CodeType: ...\n    @property\n    def ag_frame(self) -> FrameType | None: ...\n    @property\n    def ag_running(self) -> bool: ...\n    __name__: str\n    __qualname__: str\n    if sys.version_info >= (3, 12):\n        @property\n        def ag_suspended(self) -> bool: ...\n\n    def __aiter__(self) -> Self: ...\n    def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: ...\n    def asend(self, val: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: ...\n    @overload\n    async def athrow(\n        self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., /\n    ) -> _YieldT_co: ...\n    @overload\n    async def athrow(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ...\n    def aclose(self) -> Coroutine[Any, Any, None]: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\n# Non-default variations to accommodate coroutines\n_SendT_nd_contra = TypeVar(\"_SendT_nd_contra\", contravariant=True)\n_ReturnT_nd_co = TypeVar(\"_ReturnT_nd_co\", covariant=True)\n\n@final\nclass CoroutineType(Coroutine[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co]):\n    __name__: str\n    __qualname__: str\n    @property\n    def cr_await(self) -> Any | None: ...\n    @property\n    def cr_code(self) -> CodeType: ...\n    @property\n    def cr_frame(self) -> FrameType | None: ...\n    @property\n    def cr_running(self) -> bool: ...\n    @property\n    def cr_origin(self) -> tuple[tuple[str, int, str], ...] | None: ...\n    if sys.version_info >= (3, 11):\n        @property\n        def cr_suspended(self) -> bool: ...\n\n    def close(self) -> None: ...\n    def __await__(self) -> Generator[Any, None, _ReturnT_nd_co]: ...\n    def send(self, arg: _SendT_nd_contra, /) -> _YieldT_co: ...\n    @overload\n    def throw(\n        self, typ: type[BaseException], val: BaseException | object = ..., tb: TracebackType | None = ..., /\n    ) -> _YieldT_co: ...\n    @overload\n    def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = ..., /) -> _YieldT_co: ...\n    if sys.version_info >= (3, 13):\n        def __class_getitem__(cls, item: Any, /) -> Any: ...\n\n@final\nclass MethodType:\n    @property\n    def __closure__(self) -> tuple[CellType, ...] | None: ...  # inherited from the added function\n    @property\n    def __code__(self) -> CodeType: ...  # inherited from the added function\n    @property\n    def __defaults__(self) -> tuple[Any, ...] | None: ...  # inherited from the added function\n    @property\n    def __func__(self) -> Callable[..., Any]: ...\n    @property\n    def __self__(self) -> object: ...\n    @property\n    def __name__(self) -> str: ...  # inherited from the added function\n    @property\n    def __qualname__(self) -> str: ...  # inherited from the added function\n    def __new__(cls, func: Callable[..., Any], instance: object, /) -> Self: ...\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n\n    if sys.version_info >= (3, 13):\n        def __get__(self, instance: object, owner: type | None = None, /) -> Self: ...\n\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n\n@final\nclass BuiltinFunctionType:\n    @property\n    def __self__(self) -> object | ModuleType: ...\n    @property\n    def __name__(self) -> str: ...\n    @property\n    def __qualname__(self) -> str: ...\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n\nBuiltinMethodType = BuiltinFunctionType\n\n@final\nclass WrapperDescriptorType:\n    @property\n    def __name__(self) -> str: ...\n    @property\n    def __qualname__(self) -> str: ...\n    @property\n    def __objclass__(self) -> type: ...\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n    def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ...\n\n@final\nclass MethodWrapperType:\n    @property\n    def __self__(self) -> object: ...\n    @property\n    def __name__(self) -> str: ...\n    @property\n    def __qualname__(self) -> str: ...\n    @property\n    def __objclass__(self) -> type: ...\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __ne__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n\n@final\nclass MethodDescriptorType:\n    @property\n    def __name__(self) -> str: ...\n    @property\n    def __qualname__(self) -> str: ...\n    @property\n    def __objclass__(self) -> type: ...\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n    def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ...\n\n@final\nclass ClassMethodDescriptorType:\n    @property\n    def __name__(self) -> str: ...\n    @property\n    def __qualname__(self) -> str: ...\n    @property\n    def __objclass__(self) -> type: ...\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n    def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ...\n\n@final\nclass TracebackType:\n    def __new__(cls, tb_next: TracebackType | None, tb_frame: FrameType, tb_lasti: int, tb_lineno: int) -> Self: ...\n    tb_next: TracebackType | None\n    # the rest are read-only\n    @property\n    def tb_frame(self) -> FrameType: ...\n    @property\n    def tb_lasti(self) -> int: ...\n    @property\n    def tb_lineno(self) -> int: ...\n\n@final\nclass FrameType:\n    @property\n    def f_back(self) -> FrameType | None: ...\n    @property\n    def f_builtins(self) -> dict[str, Any]: ...\n    @property\n    def f_code(self) -> CodeType: ...\n    @property\n    def f_globals(self) -> dict[str, Any]: ...\n    @property\n    def f_lasti(self) -> int: ...\n    # see discussion in #6769: f_lineno *can* sometimes be None,\n    # but you should probably file a bug report with CPython if you encounter it being None in the wild.\n    # An `int | None` annotation here causes too many false-positive errors, so applying `int | Any`.\n    @property\n    def f_lineno(self) -> int | MaybeNone: ...\n    @property\n    def f_locals(self) -> dict[str, Any]: ...\n    f_trace: Callable[[FrameType, str, Any], Any] | None\n    f_trace_lines: bool\n    f_trace_opcodes: bool\n    def clear(self) -> None: ...\n    if sys.version_info >= (3, 14):\n        @property\n        def f_generator(self) -> GeneratorType[Any, Any, Any] | CoroutineType[Any, Any, Any] | None: ...\n\n@final\nclass GetSetDescriptorType:\n    @property\n    def __name__(self) -> str: ...\n    @property\n    def __qualname__(self) -> str: ...\n    @property\n    def __objclass__(self) -> type: ...\n    def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ...\n    def __set__(self, instance: Any, value: Any, /) -> None: ...\n    def __delete__(self, instance: Any, /) -> None: ...\n\n@final\nclass MemberDescriptorType:\n    @property\n    def __name__(self) -> str: ...\n    @property\n    def __qualname__(self) -> str: ...\n    @property\n    def __objclass__(self) -> type: ...\n    def __get__(self, instance: Any, owner: type | None = None, /) -> Any: ...\n    def __set__(self, instance: Any, value: Any, /) -> None: ...\n    def __delete__(self, instance: Any, /) -> None: ...\n\ndef new_class(\n    name: str,\n    bases: Iterable[object] = (),\n    kwds: dict[str, Any] | None = None,\n    exec_body: Callable[[dict[str, Any]], object] | None = None,\n) -> type: ...\ndef resolve_bases(bases: Iterable[object]) -> tuple[Any, ...]: ...\ndef prepare_class(\n    name: str, bases: tuple[type, ...] = (), kwds: dict[str, Any] | None = None\n) -> tuple[type, dict[str, Any], dict[str, Any]]: ...\n\nif sys.version_info >= (3, 12):\n    def get_original_bases(cls: type, /) -> tuple[Any, ...]: ...\n\n# Does not actually inherit from property, but saying it does makes sure that\n# pyright handles this class correctly.\nclass DynamicClassAttribute(property):\n    fget: Callable[[Any], Any] | None\n    fset: Callable[[Any, Any], object] | None  # type: ignore[assignment]\n    fdel: Callable[[Any], object] | None  # type: ignore[assignment]\n    overwrite_doc: bool\n    __isabstractmethod__: bool\n    def __init__(\n        self,\n        fget: Callable[[Any], Any] | None = None,\n        fset: Callable[[Any, Any], object] | None = None,\n        fdel: Callable[[Any], object] | None = None,\n        doc: str | None = None,\n    ) -> None: ...\n    def __get__(self, instance: Any, ownerclass: type | None = None) -> Any: ...\n    def __set__(self, instance: Any, value: Any) -> None: ...\n    def __delete__(self, instance: Any) -> None: ...\n    def getter(self, fget: Callable[[Any], Any]) -> DynamicClassAttribute: ...\n    def setter(self, fset: Callable[[Any, Any], object]) -> DynamicClassAttribute: ...\n    def deleter(self, fdel: Callable[[Any], object]) -> DynamicClassAttribute: ...\n\n_Fn = TypeVar(\"_Fn\", bound=Callable[..., object])\n_R = TypeVar(\"_R\")\n_P = ParamSpec(\"_P\")\n\n# it's not really an Awaitable, but can be used in an await expression. Real type: Generator & Awaitable\n@overload\ndef coroutine(func: Callable[_P, Generator[Any, Any, _R]]) -> Callable[_P, Awaitable[_R]]: ...\n@overload\ndef coroutine(func: _Fn) -> _Fn: ...\n@disjoint_base\nclass GenericAlias:\n    @property\n    def __origin__(self) -> type | TypeAliasType: ...\n    @property\n    def __args__(self) -> tuple[Any, ...]: ...\n    @property\n    def __parameters__(self) -> tuple[Any, ...]: ...\n    def __new__(cls, origin: type, args: Any, /) -> Self: ...\n    def __getitem__(self, typeargs: Any, /) -> GenericAlias: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __mro_entries__(self, bases: Iterable[object], /) -> tuple[type, ...]: ...\n    if sys.version_info >= (3, 11):\n        @property\n        def __unpacked__(self) -> bool: ...\n        @property\n        def __typing_unpacked_tuple_args__(self) -> tuple[Any, ...] | None: ...\n    if sys.version_info >= (3, 10):\n        def __or__(self, value: Any, /) -> UnionType: ...\n        def __ror__(self, value: Any, /) -> UnionType: ...\n\n    # GenericAlias delegates attr access to `__origin__`\n    def __getattr__(self, name: str) -> Any: ...\n\nif sys.version_info >= (3, 10):\n    @final\n    class NoneType:\n        def __bool__(self) -> Literal[False]: ...\n\n    @final\n    class EllipsisType: ...\n\n    @final\n    class NotImplementedType(Any): ...\n\n    @final\n    class UnionType:\n        @property\n        def __args__(self) -> tuple[Any, ...]: ...\n        @property\n        def __parameters__(self) -> tuple[Any, ...]: ...\n        # `(int | str) | Literal[\"foo\"]` returns a generic alias to an instance of `_SpecialForm` (`Union`).\n        # Normally we'd express this using the return type of `_SpecialForm.__ror__`,\n        # but because `UnionType.__or__` accepts `Any`, type checkers will use\n        # the return type of `UnionType.__or__` to infer the result of this operation\n        # rather than `_SpecialForm.__ror__`. To mitigate this, we use `| Any`\n        # in the return type of `UnionType.__(r)or__`.\n        def __or__(self, value: Any, /) -> UnionType | Any: ...\n        def __ror__(self, value: Any, /) -> UnionType | Any: ...\n        def __eq__(self, value: object, /) -> bool: ...\n        def __hash__(self) -> int: ...\n        # you can only subscript a `UnionType` instance if at least one of the elements\n        # in the union is a generic alias instance that has a non-empty `__parameters__`\n        def __getitem__(self, parameters: Any, /) -> object: ...\n\nif sys.version_info >= (3, 13):\n    @final\n    class CapsuleType: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/typing.pyi",
    "content": "# Since this module defines \"overload\" it is not recognized by Ruff as typing.overload\n# TODO: The collections import is required, otherwise mypy crashes.\n# https://github.com/python/mypy/issues/16744\nimport collections  # noqa: F401  # pyright: ignore[reportUnusedImport]\nimport sys\nimport typing_extensions\nfrom _collections_abc import dict_items, dict_keys, dict_values\nfrom _typeshed import IdentityFunction, ReadableBuffer, SupportsGetItem, SupportsGetItemViewable, SupportsKeysAndGetItem, Viewable\nfrom abc import ABCMeta, abstractmethod\nfrom re import Match as Match, Pattern as Pattern\nfrom types import (\n    BuiltinFunctionType,\n    CodeType,\n    FunctionType,\n    GenericAlias,\n    MethodDescriptorType,\n    MethodType,\n    MethodWrapperType,\n    ModuleType,\n    TracebackType,\n    WrapperDescriptorType,\n)\nfrom typing_extensions import Never as _Never, ParamSpec as _ParamSpec, deprecated\n\nif sys.version_info >= (3, 14):\n    from _typeshed import EvaluateFunc\n\n    from annotationlib import Format\n\nif sys.version_info >= (3, 10):\n    from types import UnionType\n\n__all__ = [\n    \"AbstractSet\",\n    \"Annotated\",\n    \"Any\",\n    \"AnyStr\",\n    \"AsyncContextManager\",\n    \"AsyncGenerator\",\n    \"AsyncIterable\",\n    \"AsyncIterator\",\n    \"Awaitable\",\n    \"BinaryIO\",\n    \"ByteString\",\n    \"Callable\",\n    \"ChainMap\",\n    \"ClassVar\",\n    \"Collection\",\n    \"Container\",\n    \"ContextManager\",\n    \"Coroutine\",\n    \"Counter\",\n    \"DefaultDict\",\n    \"Deque\",\n    \"Dict\",\n    \"Final\",\n    \"ForwardRef\",\n    \"FrozenSet\",\n    \"Generator\",\n    \"Generic\",\n    \"Hashable\",\n    \"IO\",\n    \"ItemsView\",\n    \"Iterable\",\n    \"Iterator\",\n    \"KeysView\",\n    \"List\",\n    \"Literal\",\n    \"Mapping\",\n    \"MappingView\",\n    \"Match\",\n    \"MutableMapping\",\n    \"MutableSequence\",\n    \"MutableSet\",\n    \"NamedTuple\",\n    \"NewType\",\n    \"NoReturn\",\n    \"Optional\",\n    \"OrderedDict\",\n    \"Pattern\",\n    \"Protocol\",\n    \"Reversible\",\n    \"Sequence\",\n    \"Set\",\n    \"Sized\",\n    \"SupportsAbs\",\n    \"SupportsBytes\",\n    \"SupportsComplex\",\n    \"SupportsFloat\",\n    \"SupportsIndex\",\n    \"SupportsInt\",\n    \"SupportsRound\",\n    \"Text\",\n    \"TextIO\",\n    \"Tuple\",\n    \"Type\",\n    \"TypeVar\",\n    \"TypedDict\",\n    \"Union\",\n    \"ValuesView\",\n    \"TYPE_CHECKING\",\n    \"cast\",\n    \"final\",\n    \"get_args\",\n    \"get_origin\",\n    \"get_type_hints\",\n    \"no_type_check\",\n    \"no_type_check_decorator\",\n    \"overload\",\n    \"runtime_checkable\",\n]\n\nif sys.version_info >= (3, 14):\n    __all__ += [\"evaluate_forward_ref\"]\n\nif sys.version_info >= (3, 10):\n    __all__ += [\"Concatenate\", \"ParamSpec\", \"ParamSpecArgs\", \"ParamSpecKwargs\", \"TypeAlias\", \"TypeGuard\", \"is_typeddict\"]\n\nif sys.version_info >= (3, 11):\n    __all__ += [\n        \"LiteralString\",\n        \"Never\",\n        \"NotRequired\",\n        \"Required\",\n        \"Self\",\n        \"TypeVarTuple\",\n        \"Unpack\",\n        \"assert_never\",\n        \"assert_type\",\n        \"clear_overloads\",\n        \"dataclass_transform\",\n        \"get_overloads\",\n        \"reveal_type\",\n    ]\n\nif sys.version_info >= (3, 12):\n    __all__ += [\"TypeAliasType\", \"override\"]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"get_protocol_members\", \"is_protocol\", \"NoDefault\", \"TypeIs\", \"ReadOnly\"]\n\n# We can't use this name here because it leads to issues with mypy, likely\n# due to an import cycle. Below instead we use Any with a comment.\n# from _typeshed import AnnotationForm\n\nclass Any: ...\n\nclass _Final:\n    __slots__ = (\"__weakref__\",)\n\ndef final(f: _T) -> _T: ...\n@final\nclass TypeVar:\n    @property\n    def __name__(self) -> str: ...\n    @property\n    def __bound__(self) -> Any | None: ...  # AnnotationForm\n    @property\n    def __constraints__(self) -> tuple[Any, ...]: ...  # AnnotationForm\n    @property\n    def __covariant__(self) -> bool: ...\n    @property\n    def __contravariant__(self) -> bool: ...\n    if sys.version_info >= (3, 12):\n        @property\n        def __infer_variance__(self) -> bool: ...\n    if sys.version_info >= (3, 13):\n        @property\n        def __default__(self) -> Any: ...  # AnnotationForm\n    if sys.version_info >= (3, 13):\n        def __new__(\n            cls,\n            name: str,\n            *constraints: Any,  # AnnotationForm\n            bound: Any | None = None,  # AnnotationForm\n            contravariant: bool = False,\n            covariant: bool = False,\n            infer_variance: bool = False,\n            default: Any = ...,  # AnnotationForm\n        ) -> Self: ...\n    elif sys.version_info >= (3, 12):\n        def __new__(\n            cls,\n            name: str,\n            *constraints: Any,  # AnnotationForm\n            bound: Any | None = None,  # AnnotationForm\n            covariant: bool = False,\n            contravariant: bool = False,\n            infer_variance: bool = False,\n        ) -> Self: ...\n    elif sys.version_info >= (3, 11):\n        def __new__(\n            cls,\n            name: str,\n            *constraints: Any,  # AnnotationForm\n            bound: Any | None = None,  # AnnotationForm\n            covariant: bool = False,\n            contravariant: bool = False,\n        ) -> Self: ...\n    else:\n        def __init__(\n            self,\n            name: str,\n            *constraints: Any,  # AnnotationForm\n            bound: Any | None = None,  # AnnotationForm\n            covariant: bool = False,\n            contravariant: bool = False,\n        ) -> None: ...\n    if sys.version_info >= (3, 10):\n        def __or__(self, right: Any, /) -> _SpecialForm: ...  # AnnotationForm\n        def __ror__(self, left: Any, /) -> _SpecialForm: ...  # AnnotationForm\n    if sys.version_info >= (3, 11):\n        def __typing_subst__(self, arg: Any, /) -> Any: ...\n    if sys.version_info >= (3, 13):\n        def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ...\n        def has_default(self) -> bool: ...\n    if sys.version_info >= (3, 14):\n        @property\n        def evaluate_bound(self) -> EvaluateFunc | None: ...\n        @property\n        def evaluate_constraints(self) -> EvaluateFunc | None: ...\n        @property\n        def evaluate_default(self) -> EvaluateFunc | None: ...\n\n# N.B. Keep this definition in sync with typing_extensions._SpecialForm\n@final\nclass _SpecialForm(_Final):\n    __slots__ = (\"_name\", \"__doc__\", \"_getitem\")\n    def __getitem__(self, parameters: Any) -> object: ...\n    if sys.version_info >= (3, 10):\n        def __or__(self, other: Any) -> _SpecialForm: ...\n        def __ror__(self, other: Any) -> _SpecialForm: ...\n\nUnion: _SpecialForm\nProtocol: _SpecialForm\nCallable: _SpecialForm\nType: _SpecialForm\nNoReturn: _SpecialForm\nClassVar: _SpecialForm\n\nOptional: _SpecialForm\nTuple: _SpecialForm\nFinal: _SpecialForm\n\nLiteral: _SpecialForm\nTypedDict: _SpecialForm\n\nif sys.version_info >= (3, 11):\n    Self: _SpecialForm\n    Never: _SpecialForm\n    Unpack: _SpecialForm\n    Required: _SpecialForm\n    NotRequired: _SpecialForm\n    LiteralString: _SpecialForm\n\n    @final\n    class TypeVarTuple:\n        @property\n        def __name__(self) -> str: ...\n        if sys.version_info >= (3, 13):\n            @property\n            def __default__(self) -> Any: ...  # AnnotationForm\n            def has_default(self) -> bool: ...\n        if sys.version_info >= (3, 13):\n            def __new__(cls, name: str, *, default: Any = ...) -> Self: ...  # AnnotationForm\n        elif sys.version_info >= (3, 12):\n            def __new__(cls, name: str) -> Self: ...\n        else:\n            def __init__(self, name: str) -> None: ...\n\n        def __iter__(self) -> Any: ...\n        def __typing_subst__(self, arg: Never, /) -> Never: ...\n        def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ...\n        if sys.version_info >= (3, 14):\n            @property\n            def evaluate_default(self) -> EvaluateFunc | None: ...\n\nif sys.version_info >= (3, 10):\n    @final\n    class ParamSpecArgs:\n        @property\n        def __origin__(self) -> ParamSpec: ...\n        if sys.version_info >= (3, 12):\n            def __new__(cls, origin: ParamSpec) -> Self: ...\n        else:\n            def __init__(self, origin: ParamSpec) -> None: ...\n\n        def __eq__(self, other: object, /) -> bool: ...\n        __hash__: ClassVar[None]  # type: ignore[assignment]\n\n    @final\n    class ParamSpecKwargs:\n        @property\n        def __origin__(self) -> ParamSpec: ...\n        if sys.version_info >= (3, 12):\n            def __new__(cls, origin: ParamSpec) -> Self: ...\n        else:\n            def __init__(self, origin: ParamSpec) -> None: ...\n\n        def __eq__(self, other: object, /) -> bool: ...\n        __hash__: ClassVar[None]  # type: ignore[assignment]\n\n    @final\n    class ParamSpec:\n        @property\n        def __name__(self) -> str: ...\n        @property\n        def __bound__(self) -> Any | None: ...  # AnnotationForm\n        @property\n        def __covariant__(self) -> bool: ...\n        @property\n        def __contravariant__(self) -> bool: ...\n        if sys.version_info >= (3, 12):\n            @property\n            def __infer_variance__(self) -> bool: ...\n        if sys.version_info >= (3, 13):\n            @property\n            def __default__(self) -> Any: ...  # AnnotationForm\n        if sys.version_info >= (3, 13):\n            def __new__(\n                cls,\n                name: str,\n                *,\n                bound: Any | None = None,  # AnnotationForm\n                contravariant: bool = False,\n                covariant: bool = False,\n                infer_variance: bool = False,\n                default: Any = ...,  # AnnotationForm\n            ) -> Self: ...\n        elif sys.version_info >= (3, 12):\n            def __new__(\n                cls,\n                name: str,\n                *,\n                bound: Any | None = None,  # AnnotationForm\n                contravariant: bool = False,\n                covariant: bool = False,\n                infer_variance: bool = False,\n            ) -> Self: ...\n        elif sys.version_info >= (3, 11):\n            def __new__(\n                cls,\n                name: str,\n                *,\n                bound: Any | None = None,  # AnnotationForm\n                contravariant: bool = False,\n                covariant: bool = False,\n            ) -> Self: ...\n        else:\n            def __init__(\n                self,\n                name: str,\n                *,\n                bound: Any | None = None,  # AnnotationForm\n                contravariant: bool = False,\n                covariant: bool = False,\n            ) -> None: ...\n\n        @property\n        def args(self) -> ParamSpecArgs: ...\n        @property\n        def kwargs(self) -> ParamSpecKwargs: ...\n        if sys.version_info >= (3, 11):\n            def __typing_subst__(self, arg: Any, /) -> Any: ...\n            def __typing_prepare_subst__(self, alias: Any, args: Any, /) -> tuple[Any, ...]: ...\n\n        def __or__(self, right: Any, /) -> _SpecialForm: ...\n        def __ror__(self, left: Any, /) -> _SpecialForm: ...\n        if sys.version_info >= (3, 13):\n            def has_default(self) -> bool: ...\n        if sys.version_info >= (3, 14):\n            @property\n            def evaluate_default(self) -> EvaluateFunc | None: ...\n\n    Concatenate: _SpecialForm\n    TypeAlias: _SpecialForm\n    TypeGuard: _SpecialForm\n\n    class NewType:\n        def __init__(self, name: str, tp: Any) -> None: ...  # AnnotationForm\n        if sys.version_info >= (3, 11):\n            @staticmethod\n            def __call__(x: _T, /) -> _T: ...\n        else:\n            def __call__(self, x: _T) -> _T: ...\n\n        def __or__(self, other: Any) -> _SpecialForm: ...\n        def __ror__(self, other: Any) -> _SpecialForm: ...\n        __supertype__: type | NewType\n        __name__: str\n\nelse:\n    def NewType(name: str, tp: Any) -> Any: ...\n\n_F = TypeVar(\"_F\", bound=Callable[..., Any])\n_P = _ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\n\n_FT = TypeVar(\"_FT\", bound=Callable[..., Any] | type)\n\n# These type variables are used by the container types.\n_S = TypeVar(\"_S\")\n_KT = TypeVar(\"_KT\")  # Key type.\n_VT = TypeVar(\"_VT\")  # Value type.\n_T_co = TypeVar(\"_T_co\", covariant=True)  # Any type covariant containers.\n_KT_co = TypeVar(\"_KT_co\", covariant=True)  # Key type covariant containers.\n_VT_co = TypeVar(\"_VT_co\", covariant=True)  # Value type covariant containers.\n_TC = TypeVar(\"_TC\", bound=type[object])\n\ndef overload(func: _F) -> _F: ...\ndef no_type_check(arg: _F) -> _F: ...\n\nif sys.version_info >= (3, 13):\n    @deprecated(\"Deprecated since Python 3.13; removed in Python 3.15.\")\n    def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ...\n\nelse:\n    def no_type_check_decorator(decorator: Callable[_P, _T]) -> Callable[_P, _T]: ...\n\n# This itself is only available during type checking\ndef type_check_only(func_or_cls: _FT) -> _FT: ...\n\n# Type aliases and type constructors\n\n@type_check_only\nclass _Alias:\n    # Class for defining generic aliases for library types.\n    def __getitem__(self, typeargs: Any) -> Any: ...\n\nList = _Alias()\nDict = _Alias()\nDefaultDict = _Alias()\nSet = _Alias()\nFrozenSet = _Alias()\nCounter = _Alias()\nDeque = _Alias()\nChainMap = _Alias()\n\nOrderedDict = _Alias()\n\nAnnotated: _SpecialForm\n\n# Predefined type variables.\nAnyStr = TypeVar(\"AnyStr\", str, bytes)  # noqa: Y001\n\n@type_check_only\nclass _Generic:\n    if sys.version_info < (3, 12):\n        __slots__ = ()\n\n    if sys.version_info >= (3, 10):\n        @classmethod\n        def __class_getitem__(cls, args: TypeVar | ParamSpec | tuple[TypeVar | ParamSpec, ...]) -> _Final: ...\n    else:\n        @classmethod\n        def __class_getitem__(cls, args: TypeVar | tuple[TypeVar, ...]) -> _Final: ...\n\nGeneric: type[_Generic]\n\nclass _ProtocolMeta(ABCMeta):\n    if sys.version_info >= (3, 12):\n        def __init__(cls, *args: Any, **kwargs: Any) -> None: ...\n\n# Abstract base classes.\n\ndef runtime_checkable(cls: _TC) -> _TC: ...\n@runtime_checkable\nclass SupportsInt(Protocol, metaclass=ABCMeta):\n    __slots__ = ()\n    @abstractmethod\n    def __int__(self) -> int: ...\n\n@runtime_checkable\nclass SupportsFloat(Protocol, metaclass=ABCMeta):\n    __slots__ = ()\n    @abstractmethod\n    def __float__(self) -> float: ...\n\n@runtime_checkable\nclass SupportsComplex(Protocol, metaclass=ABCMeta):\n    __slots__ = ()\n    @abstractmethod\n    def __complex__(self) -> complex: ...\n\n@runtime_checkable\nclass SupportsBytes(Protocol, metaclass=ABCMeta):\n    __slots__ = ()\n    @abstractmethod\n    def __bytes__(self) -> bytes: ...\n\n@runtime_checkable\nclass SupportsIndex(Protocol, metaclass=ABCMeta):\n    __slots__ = ()\n    @abstractmethod\n    def __index__(self) -> int: ...\n\n@runtime_checkable\nclass SupportsAbs(Protocol[_T_co]):\n    __slots__ = ()\n    @abstractmethod\n    def __abs__(self) -> _T_co: ...\n\n@runtime_checkable\nclass SupportsRound(Protocol[_T_co]):\n    __slots__ = ()\n    @overload\n    @abstractmethod\n    def __round__(self) -> int: ...\n    @overload\n    @abstractmethod\n    def __round__(self, ndigits: int, /) -> _T_co: ...\n\n@runtime_checkable\nclass Sized(Protocol, metaclass=ABCMeta):\n    @abstractmethod\n    def __len__(self) -> int: ...\n\n@runtime_checkable\nclass Hashable(Protocol, metaclass=ABCMeta):\n    # TODO: This is special, in that a subclass of a hashable class may not be hashable\n    #   (for example, list vs. object). It's not obvious how to represent this. This class\n    #   is currently mostly useless for static checking.\n    @abstractmethod\n    def __hash__(self) -> int: ...\n\n@runtime_checkable\nclass Iterable(Protocol[_T_co]):\n    @abstractmethod\n    def __iter__(self) -> Iterator[_T_co]: ...\n\n@runtime_checkable\nclass Iterator(Iterable[_T_co], Protocol[_T_co]):\n    @abstractmethod\n    def __next__(self) -> _T_co: ...\n    def __iter__(self) -> Iterator[_T_co]: ...\n\n@runtime_checkable\nclass Reversible(Iterable[_T_co], Protocol[_T_co]):\n    @abstractmethod\n    def __reversed__(self) -> Iterator[_T_co]: ...\n\n_YieldT_co = TypeVar(\"_YieldT_co\", covariant=True)\n_SendT_contra = TypeVar(\"_SendT_contra\", contravariant=True, default=None)\n_ReturnT_co = TypeVar(\"_ReturnT_co\", covariant=True, default=None)\n\n@runtime_checkable\nclass Generator(Iterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra, _ReturnT_co]):\n    def __next__(self) -> _YieldT_co: ...\n    @abstractmethod\n    def send(self, value: _SendT_contra, /) -> _YieldT_co: ...\n    @overload\n    @abstractmethod\n    def throw(\n        self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, /\n    ) -> _YieldT_co: ...\n    @overload\n    @abstractmethod\n    def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ...\n    if sys.version_info >= (3, 13):\n        def close(self) -> _ReturnT_co | None: ...\n    else:\n        def close(self) -> None: ...\n\n    def __iter__(self) -> Generator[_YieldT_co, _SendT_contra, _ReturnT_co]: ...\n\n# NOTE: Prior to Python 3.13 these aliases are lacking the second _ExitT_co parameter\nif sys.version_info >= (3, 13):\n    from contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager\nelse:\n    from contextlib import AbstractAsyncContextManager, AbstractContextManager\n\n    @runtime_checkable\n    class ContextManager(AbstractContextManager[_T_co, bool | None], Protocol[_T_co]): ...\n\n    @runtime_checkable\n    class AsyncContextManager(AbstractAsyncContextManager[_T_co, bool | None], Protocol[_T_co]): ...\n\n@runtime_checkable\nclass Awaitable(Protocol[_T_co]):\n    @abstractmethod\n    def __await__(self) -> Generator[Any, Any, _T_co]: ...\n\n# Non-default variations to accommodate coroutines, and `AwaitableGenerator` having a 4th type parameter.\n_SendT_nd_contra = TypeVar(\"_SendT_nd_contra\", contravariant=True)\n_ReturnT_nd_co = TypeVar(\"_ReturnT_nd_co\", covariant=True)\n\nclass Coroutine(Awaitable[_ReturnT_nd_co], Generic[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co]):\n    __name__: str\n    __qualname__: str\n\n    @abstractmethod\n    def send(self, value: _SendT_nd_contra, /) -> _YieldT_co: ...\n    @overload\n    @abstractmethod\n    def throw(\n        self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, /\n    ) -> _YieldT_co: ...\n    @overload\n    @abstractmethod\n    def throw(self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /) -> _YieldT_co: ...\n    @abstractmethod\n    def close(self) -> None: ...\n\n# NOTE: This type does not exist in typing.py or PEP 484 but mypy needs it to exist.\n# The parameters correspond to Generator, but the 4th is the original type.\n# Obsolete, use _typeshed._type_checker_internals.AwaitableGenerator instead.\n@type_check_only\nclass AwaitableGenerator(\n    Awaitable[_ReturnT_nd_co],\n    Generator[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co],\n    Generic[_YieldT_co, _SendT_nd_contra, _ReturnT_nd_co, _S],\n    metaclass=ABCMeta,\n): ...\n\n@runtime_checkable\nclass AsyncIterable(Protocol[_T_co]):\n    @abstractmethod\n    def __aiter__(self) -> AsyncIterator[_T_co]: ...\n\n@runtime_checkable\nclass AsyncIterator(AsyncIterable[_T_co], Protocol[_T_co]):\n    @abstractmethod\n    def __anext__(self) -> Awaitable[_T_co]: ...\n    def __aiter__(self) -> AsyncIterator[_T_co]: ...\n\n@runtime_checkable\nclass AsyncGenerator(AsyncIterator[_YieldT_co], Protocol[_YieldT_co, _SendT_contra]):\n    def __anext__(self) -> Coroutine[Any, Any, _YieldT_co]: ...\n    @abstractmethod\n    def asend(self, value: _SendT_contra, /) -> Coroutine[Any, Any, _YieldT_co]: ...\n    @overload\n    @abstractmethod\n    def athrow(\n        self, typ: type[BaseException], val: BaseException | object = None, tb: TracebackType | None = None, /\n    ) -> Coroutine[Any, Any, _YieldT_co]: ...\n    @overload\n    @abstractmethod\n    def athrow(\n        self, typ: BaseException, val: None = None, tb: TracebackType | None = None, /\n    ) -> Coroutine[Any, Any, _YieldT_co]: ...\n    def aclose(self) -> Coroutine[Any, Any, None]: ...\n\n@runtime_checkable\nclass Container(Protocol[_T_co]):\n    # This is generic more on vibes than anything else\n    @abstractmethod\n    def __contains__(self, x: object, /) -> bool: ...\n\n@runtime_checkable\nclass Collection(Iterable[_T_co], Container[_T_co], Protocol[_T_co]):\n    # Implement Sized (but don't have it as a base class).\n    @abstractmethod\n    def __len__(self) -> int: ...\n\nclass Sequence(Reversible[_T_co], Collection[_T_co]):\n    @overload\n    @abstractmethod\n    def __getitem__(self, index: int, /) -> _T_co: ...\n    @overload\n    @abstractmethod\n    def __getitem__(self, index: slice[int | None], /) -> Sequence[_T_co]: ...\n    # Mixin methods\n    def index(self, value: Any, start: int = 0, stop: int = ..., /) -> int: ...\n    def count(self, value: Any, /) -> int: ...\n    def __contains__(self, value: object, /) -> bool: ...\n    def __iter__(self) -> Iterator[_T_co]: ...\n    def __reversed__(self) -> Iterator[_T_co]: ...\n\nclass MutableSequence(Sequence[_T]):\n    @abstractmethod\n    def insert(self, index: int, value: _T, /) -> None: ...\n    @overload\n    @abstractmethod\n    def __getitem__(self, index: int, /) -> _T: ...\n    @overload\n    @abstractmethod\n    def __getitem__(self, index: slice[int | None], /) -> MutableSequence[_T]: ...\n    @overload\n    @abstractmethod\n    def __setitem__(self, index: int, value: _T, /) -> None: ...\n    @overload\n    @abstractmethod\n    def __setitem__(self, index: slice[int | None], value: Iterable[_T], /) -> None: ...\n    @overload\n    @abstractmethod\n    def __delitem__(self, index: int, /) -> None: ...\n    @overload\n    @abstractmethod\n    def __delitem__(self, index: slice[int | None], /) -> None: ...\n    # Mixin methods\n    def append(self, value: _T, /) -> None: ...\n    def clear(self) -> None: ...\n    def extend(self, values: Iterable[_T], /) -> None: ...\n    def reverse(self) -> None: ...\n    def pop(self, index: int = -1, /) -> _T: ...\n    def remove(self, value: _T, /) -> None: ...\n    def __iadd__(self, values: Iterable[_T], /) -> typing_extensions.Self: ...\n\nclass AbstractSet(Collection[_T_co]):\n    @abstractmethod\n    def __contains__(self, x: object, /) -> bool: ...\n    def _hash(self) -> int: ...\n    # Mixin methods\n    @classmethod\n    def _from_iterable(cls, it: Iterable[_S], /) -> AbstractSet[_S]: ...\n    def __le__(self, other: AbstractSet[Any], /) -> bool: ...\n    def __lt__(self, other: AbstractSet[Any], /) -> bool: ...\n    def __gt__(self, other: AbstractSet[Any], /) -> bool: ...\n    def __ge__(self, other: AbstractSet[Any], /) -> bool: ...\n    def __and__(self, other: AbstractSet[Any], /) -> AbstractSet[_T_co]: ...\n    def __or__(self, other: AbstractSet[_T], /) -> AbstractSet[_T_co | _T]: ...\n    def __sub__(self, other: AbstractSet[Any], /) -> AbstractSet[_T_co]: ...\n    def __xor__(self, other: AbstractSet[_T], /) -> AbstractSet[_T_co | _T]: ...\n    def __eq__(self, other: object, /) -> bool: ...\n    def isdisjoint(self, other: Iterable[Any], /) -> bool: ...\n\nclass MutableSet(AbstractSet[_T]):\n    @abstractmethod\n    def add(self, value: _T, /) -> None: ...\n    @abstractmethod\n    def discard(self, value: _T, /) -> None: ...\n    # Mixin methods\n    def clear(self) -> None: ...\n    def pop(self) -> _T: ...\n    def remove(self, value: _T, /) -> None: ...\n    def __ior__(self, it: AbstractSet[_T], /) -> typing_extensions.Self: ...  # type: ignore[override,misc]\n    def __iand__(self, it: AbstractSet[Any], /) -> typing_extensions.Self: ...\n    def __ixor__(self, it: AbstractSet[_T], /) -> typing_extensions.Self: ...  # type: ignore[override,misc]\n    def __isub__(self, it: AbstractSet[Any], /) -> typing_extensions.Self: ...\n\nclass MappingView(Sized):\n    __slots__ = (\"_mapping\",)\n    def __init__(self, mapping: Sized) -> None: ...  # undocumented\n    def __len__(self) -> int: ...\n\nclass ItemsView(MappingView, AbstractSet[tuple[_KT_co, _VT_co]], Generic[_KT_co, _VT_co]):\n    def __init__(self, mapping: SupportsGetItemViewable[_KT_co, _VT_co]) -> None: ...  # undocumented\n    @classmethod\n    def _from_iterable(cls, it: Iterable[_S], /) -> set[_S]: ...\n    def __and__(self, other: Iterable[Any], /) -> set[tuple[_KT_co, _VT_co]]: ...\n    def __rand__(self, other: Iterable[_T], /) -> set[_T]: ...\n    def __contains__(self, item: tuple[object, object], /) -> bool: ...  # type: ignore[override]\n    def __iter__(self) -> Iterator[tuple[_KT_co, _VT_co]]: ...\n    def __or__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ...\n    def __ror__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ...\n    def __sub__(self, other: Iterable[Any], /) -> set[tuple[_KT_co, _VT_co]]: ...\n    def __rsub__(self, other: Iterable[_T], /) -> set[_T]: ...\n    def __xor__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ...\n    def __rxor__(self, other: Iterable[_T], /) -> set[tuple[_KT_co, _VT_co] | _T]: ...\n\nclass KeysView(MappingView, AbstractSet[_KT_co]):\n    def __init__(self, mapping: Viewable[_KT_co]) -> None: ...  # undocumented\n    @classmethod\n    def _from_iterable(cls, it: Iterable[_S], /) -> set[_S]: ...\n    def __and__(self, other: Iterable[Any], /) -> set[_KT_co]: ...\n    def __rand__(self, other: Iterable[_T], /) -> set[_T]: ...\n    def __contains__(self, key: object, /) -> bool: ...\n    def __iter__(self) -> Iterator[_KT_co]: ...\n    def __or__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ...\n    def __ror__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ...\n    def __sub__(self, other: Iterable[Any], /) -> set[_KT_co]: ...\n    def __rsub__(self, other: Iterable[_T], /) -> set[_T]: ...\n    def __xor__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ...\n    def __rxor__(self, other: Iterable[_T], /) -> set[_KT_co | _T]: ...\n\nclass ValuesView(MappingView, Collection[_VT_co]):\n    def __init__(self, mapping: SupportsGetItemViewable[Any, _VT_co]) -> None: ...  # undocumented\n    def __contains__(self, value: object, /) -> bool: ...\n    def __iter__(self) -> Iterator[_VT_co]: ...\n\n# note for Mapping.get and MutableMapping.pop and MutableMapping.setdefault\n# In _collections_abc.py the parameters are positional-or-keyword,\n# but dict and types.MappingProxyType (the vast majority of Mapping types)\n# don't allow keyword arguments.\n\nclass Mapping(Collection[_KT], Generic[_KT, _VT_co]):\n    # TODO: We wish the key type could also be covariant, but that doesn't work,\n    # see discussion in https://github.com/python/typing/pull/273.\n    @abstractmethod\n    def __getitem__(self, key: _KT, /) -> _VT_co: ...\n    # Mixin methods\n    @overload\n    def get(self, key: _KT, /) -> _VT_co | None: ...\n    @overload\n    def get(self, key: _KT, default: _VT_co, /) -> _VT_co: ...  # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues] # Covariant type as parameter\n    @overload\n    def get(self, key: _KT, default: _T, /) -> _VT_co | _T: ...\n    def items(self) -> ItemsView[_KT, _VT_co]: ...\n    def keys(self) -> KeysView[_KT]: ...\n    def values(self) -> ValuesView[_VT_co]: ...\n    def __contains__(self, key: object, /) -> bool: ...\n    def __eq__(self, other: object, /) -> bool: ...\n\nclass MutableMapping(Mapping[_KT, _VT]):\n    @abstractmethod\n    def __setitem__(self, key: _KT, value: _VT, /) -> None: ...\n    @abstractmethod\n    def __delitem__(self, key: _KT, /) -> None: ...\n    def clear(self) -> None: ...\n    @overload\n    def pop(self, key: _KT, /) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _VT, /) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _T, /) -> _VT | _T: ...\n    def popitem(self) -> tuple[_KT, _VT]: ...\n    # This overload should be allowed only if the value type is compatible with None.\n    #\n    # Keep the following methods in line with MutableMapping.setdefault, modulo positional-only differences:\n    # -- collections.OrderedDict.setdefault\n    # -- collections.ChainMap.setdefault\n    # -- weakref.WeakKeyDictionary.setdefault\n    @overload\n    def setdefault(self: MutableMapping[_KT, _T | None], key: _KT, default: None = None, /) -> _T | None: ...\n    @overload\n    def setdefault(self, key: _KT, default: _VT, /) -> _VT: ...\n    # 'update' used to take a Union, but using overloading is better.\n    # The second overloaded type here is a bit too general, because\n    # Mapping[tuple[_KT, _VT], W] is a subclass of Iterable[tuple[_KT, _VT]],\n    # but will always have the behavior of the first overloaded type\n    # at runtime, leading to keys of a mix of types _KT and tuple[_KT, _VT].\n    # We don't currently have any way of forcing all Mappings to use\n    # the first overload, but by using overloading rather than a Union,\n    # mypy will commit to using the first overload when the argument is\n    # known to be a Mapping with unknown type parameters, which is closer\n    # to the behavior we want. See mypy issue  #1430.\n    #\n    # Various mapping classes have __ior__ methods that should be kept roughly in line with .update():\n    # -- dict.__ior__\n    # -- os._Environ.__ior__\n    # -- collections.UserDict.__ior__\n    # -- collections.ChainMap.__ior__\n    # -- peewee.attrdict.__add__\n    # -- peewee.attrdict.__iadd__\n    # -- weakref.WeakValueDictionary.__ior__\n    # -- weakref.WeakKeyDictionary.__ior__\n    @overload\n    def update(self, m: SupportsKeysAndGetItem[_KT, _VT], /) -> None: ...\n    @overload\n    def update(self: SupportsGetItem[str, _VT], m: SupportsKeysAndGetItem[str, _VT], /, **kwargs: _VT) -> None: ...\n    @overload\n    def update(self, m: Iterable[tuple[_KT, _VT]], /) -> None: ...\n    @overload\n    def update(self: SupportsGetItem[str, _VT], m: Iterable[tuple[str, _VT]], /, **kwargs: _VT) -> None: ...\n    @overload\n    def update(self: SupportsGetItem[str, _VT], /, **kwargs: _VT) -> None: ...\n\nText = str\n\nTYPE_CHECKING: Final[bool]\n\n# In stubs, the arguments of the IO class are marked as positional-only.\n# This differs from runtime, but better reflects the fact that in reality\n# classes deriving from IO use different names for the arguments.\nclass IO(Generic[AnyStr]):\n    # At runtime these are all abstract properties,\n    # but making them abstract in the stub is hugely disruptive, for not much gain.\n    # See #8726\n    __slots__ = ()\n    @property\n    def mode(self) -> str: ...\n    # Usually str, but may be bytes if a bytes path was passed to open(). See #10737.\n    # If PEP 696 becomes available, we may want to use a defaulted TypeVar here.\n    @property\n    def name(self) -> str | Any: ...\n    @abstractmethod\n    def close(self) -> None: ...\n    @property\n    def closed(self) -> bool: ...\n    @abstractmethod\n    def fileno(self) -> int: ...\n    @abstractmethod\n    def flush(self) -> None: ...\n    @abstractmethod\n    def isatty(self) -> bool: ...\n    @abstractmethod\n    def read(self, n: int = -1, /) -> AnyStr: ...\n    @abstractmethod\n    def readable(self) -> bool: ...\n    @abstractmethod\n    def readline(self, limit: int = -1, /) -> AnyStr: ...\n    @abstractmethod\n    def readlines(self, hint: int = -1, /) -> list[AnyStr]: ...\n    @abstractmethod\n    def seek(self, offset: int, whence: int = 0, /) -> int: ...\n    @abstractmethod\n    def seekable(self) -> bool: ...\n    @abstractmethod\n    def tell(self) -> int: ...\n    @abstractmethod\n    def truncate(self, size: int | None = None, /) -> int: ...\n    @abstractmethod\n    def writable(self) -> bool: ...\n    @abstractmethod\n    @overload\n    def write(self: IO[bytes], s: ReadableBuffer, /) -> int: ...\n    @abstractmethod\n    @overload\n    def write(self, s: AnyStr, /) -> int: ...\n    @abstractmethod\n    @overload\n    def writelines(self: IO[bytes], lines: Iterable[ReadableBuffer], /) -> None: ...\n    @abstractmethod\n    @overload\n    def writelines(self, lines: Iterable[AnyStr], /) -> None: ...\n    @abstractmethod\n    def __next__(self) -> AnyStr: ...\n    @abstractmethod\n    def __iter__(self) -> Iterator[AnyStr]: ...\n    @abstractmethod\n    def __enter__(self) -> IO[AnyStr]: ...\n    @abstractmethod\n    def __exit__(\n        self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None, /\n    ) -> None: ...\n\nclass BinaryIO(IO[bytes]):\n    __slots__ = ()\n    @abstractmethod\n    def __enter__(self) -> BinaryIO: ...\n\nclass TextIO(IO[str]):\n    # See comment regarding the @properties in the `IO` class\n    __slots__ = ()\n    @property\n    def buffer(self) -> BinaryIO: ...\n    @property\n    def encoding(self) -> str: ...\n    @property\n    def errors(self) -> str | None: ...\n    @property\n    def line_buffering(self) -> int: ...  # int on PyPy, bool on CPython\n    @property\n    def newlines(self) -> Any: ...  # None, str or tuple\n    @abstractmethod\n    def __enter__(self) -> TextIO: ...\n\nByteString: typing_extensions.TypeAlias = bytes | bytearray | memoryview\n\n# Functions\n\n_get_type_hints_obj_allowed_types: typing_extensions.TypeAlias = (  # noqa: Y042\n    object\n    | Callable[..., Any]\n    | FunctionType\n    | BuiltinFunctionType\n    | MethodType\n    | ModuleType\n    | WrapperDescriptorType\n    | MethodWrapperType\n    | MethodDescriptorType\n)\n\nif sys.version_info >= (3, 14):\n    def get_type_hints(\n        obj: _get_type_hints_obj_allowed_types,\n        globalns: dict[str, Any] | None = None,\n        localns: Mapping[str, Any] | None = None,\n        include_extras: bool = False,\n        *,\n        format: Format | None = None,  # Default: Format.VALUE\n    ) -> dict[str, Any]: ...  # AnnotationForm\n\nelse:\n    def get_type_hints(\n        obj: _get_type_hints_obj_allowed_types,\n        globalns: dict[str, Any] | None = None,\n        localns: Mapping[str, Any] | None = None,\n        include_extras: bool = False,\n    ) -> dict[str, Any]: ...  # AnnotationForm\n\ndef get_args(tp: Any) -> tuple[Any, ...]: ...  # AnnotationForm\n\nif sys.version_info >= (3, 10):\n    @overload\n    def get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ...\n    @overload\n    def get_origin(tp: UnionType) -> type[UnionType]: ...\n\n@overload\ndef get_origin(tp: GenericAlias) -> type: ...\n@overload\ndef get_origin(tp: Any) -> Any | None: ...  # AnnotationForm\n@overload\ndef cast(typ: type[_T], val: Any) -> _T: ...\n@overload\ndef cast(typ: str, val: Any) -> Any: ...\n@overload\ndef cast(typ: object, val: Any) -> Any: ...\n\nif sys.version_info >= (3, 11):\n    def reveal_type(obj: _T, /) -> _T: ...\n    def assert_never(arg: Never, /) -> Never: ...\n    def assert_type(val: _T, typ: Any, /) -> _T: ...  # AnnotationForm\n    def clear_overloads() -> None: ...\n    def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ...\n    def dataclass_transform(\n        *,\n        eq_default: bool = True,\n        order_default: bool = False,\n        kw_only_default: bool = False,\n        frozen_default: bool = False,  # on 3.11, runtime accepts it as part of kwargs\n        field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (),\n        **kwargs: Any,\n    ) -> IdentityFunction: ...\n\n# Type constructors\n\n# Obsolete, will be changed to a function. Use _typeshed._type_checker_internals.NamedTupleFallback instead.\nclass NamedTuple(tuple[Any, ...]):\n    _field_defaults: ClassVar[dict[str, Any]]\n    _fields: ClassVar[tuple[str, ...]]\n    # __orig_bases__ sometimes exists on <3.12, but not consistently\n    # So we only add it to the stub on 3.12+.\n    if sys.version_info >= (3, 12):\n        __orig_bases__: ClassVar[tuple[Any, ...]]\n\n    @overload\n    def __init__(self, typename: str, fields: Iterable[tuple[str, Any]], /) -> None: ...\n    @overload\n    @deprecated(\"Creating a typing.NamedTuple using keyword arguments is deprecated and support will be removed in Python 3.15\")\n    def __init__(self, typename: str, fields: None = None, /, **kwargs: Any) -> None: ...\n    @classmethod\n    def _make(cls, iterable: Iterable[Any]) -> typing_extensions.Self: ...\n    def _asdict(self) -> dict[str, Any]: ...\n    def _replace(self, **kwargs: Any) -> typing_extensions.Self: ...\n    if sys.version_info >= (3, 13):\n        def __replace__(self, **kwargs: Any) -> typing_extensions.Self: ...\n\n# Internal mypy fallback type for all typed dicts (does not exist at runtime)\n# N.B. Keep this mostly in sync with typing_extensions._TypedDict/mypy_extensions._TypedDict\n# Obsolete, use _typeshed._type_checker_internals.TypedDictFallback instead.\n@type_check_only\nclass _TypedDict(Mapping[str, object], metaclass=ABCMeta):\n    __total__: ClassVar[bool]\n    __required_keys__: ClassVar[frozenset[str]]\n    __optional_keys__: ClassVar[frozenset[str]]\n    # __orig_bases__ sometimes exists on <3.12, but not consistently,\n    # so we only add it to the stub on 3.12+\n    if sys.version_info >= (3, 12):\n        __orig_bases__: ClassVar[tuple[Any, ...]]\n    if sys.version_info >= (3, 13):\n        __readonly_keys__: ClassVar[frozenset[str]]\n        __mutable_keys__: ClassVar[frozenset[str]]\n\n    def copy(self) -> typing_extensions.Self: ...\n    # Using Never so that only calls using mypy plugin hook that specialize the signature\n    # can go through.\n    def setdefault(self, k: _Never, default: object) -> object: ...\n    # Mypy plugin hook for 'pop' expects that 'default' has a type variable type.\n    def pop(self, k: _Never, default: _T = ...) -> object: ...  # pyright: ignore[reportInvalidTypeVarUse]\n    def update(self, m: typing_extensions.Self, /) -> None: ...\n    def __delitem__(self, k: _Never) -> None: ...\n    def items(self) -> dict_items[str, object]: ...\n    def keys(self) -> dict_keys[str, object]: ...\n    def values(self) -> dict_values[str, object]: ...\n    @overload\n    def __or__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ...\n    @overload\n    def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ...\n    @overload\n    def __ror__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ...\n    @overload\n    def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ...\n    # supposedly incompatible definitions of __or__ and __ior__\n    def __ior__(self, value: typing_extensions.Self, /) -> typing_extensions.Self: ...  # type: ignore[misc]\n\nif sys.version_info >= (3, 14):\n    from annotationlib import ForwardRef as ForwardRef\n\n    def evaluate_forward_ref(\n        forward_ref: ForwardRef,\n        *,\n        owner: object = None,\n        globals: dict[str, Any] | None = None,\n        locals: Mapping[str, Any] | None = None,\n        type_params: tuple[TypeVar, ParamSpec, TypeVarTuple] | None = None,\n        format: Format | None = None,\n    ) -> Any: ...  # AnnotationForm\n\nelse:\n    @final\n    class ForwardRef(_Final):\n        __slots__ = (\n            \"__forward_arg__\",\n            \"__forward_code__\",\n            \"__forward_evaluated__\",\n            \"__forward_value__\",\n            \"__forward_is_argument__\",\n            \"__forward_is_class__\",\n            \"__forward_module__\",\n        )\n        __forward_arg__: str\n        __forward_code__: CodeType\n        __forward_evaluated__: bool\n        __forward_value__: Any | None  # AnnotationForm\n        __forward_is_argument__: bool\n        __forward_is_class__: bool\n        __forward_module__: Any | None\n\n        def __init__(self, arg: str, is_argument: bool = True, module: Any | None = None, *, is_class: bool = False) -> None: ...\n\n        if sys.version_info >= (3, 13):\n            @overload\n            @deprecated(\n                \"Failing to pass a value to the 'type_params' parameter of ForwardRef._evaluate() is deprecated, \"\n                \"as it leads to incorrect behaviour when evaluating a stringified annotation \"\n                \"that references a PEP 695 type parameter. It will be disallowed in Python 3.15.\"\n            )\n            def _evaluate(\n                self, globalns: dict[str, Any] | None, localns: Mapping[str, Any] | None, *, recursive_guard: frozenset[str]\n            ) -> Any | None: ...  # AnnotationForm\n            @overload\n            def _evaluate(\n                self,\n                globalns: dict[str, Any] | None,\n                localns: Mapping[str, Any] | None,\n                type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...],\n                *,\n                recursive_guard: frozenset[str],\n            ) -> Any | None: ...  # AnnotationForm\n        elif sys.version_info >= (3, 12):\n            def _evaluate(\n                self,\n                globalns: dict[str, Any] | None,\n                localns: Mapping[str, Any] | None,\n                type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] | None = None,\n                *,\n                recursive_guard: frozenset[str],\n            ) -> Any | None: ...  # AnnotationForm\n        else:\n            def _evaluate(\n                self, globalns: dict[str, Any] | None, localns: Mapping[str, Any] | None, recursive_guard: frozenset[str]\n            ) -> Any | None: ...  # AnnotationForm\n\n        def __eq__(self, other: object) -> bool: ...\n        def __hash__(self) -> int: ...\n        if sys.version_info >= (3, 11):\n            def __or__(self, other: Any) -> _SpecialForm: ...\n            def __ror__(self, other: Any) -> _SpecialForm: ...\n\nif sys.version_info >= (3, 10):\n    def is_typeddict(tp: object) -> bool: ...\n\ndef _type_repr(obj: object) -> str: ...\n\nif sys.version_info >= (3, 12):\n    _TypeParameter: typing_extensions.TypeAlias = (\n        TypeVar\n        | typing_extensions.TypeVar\n        | ParamSpec\n        | typing_extensions.ParamSpec\n        | TypeVarTuple\n        | typing_extensions.TypeVarTuple\n    )\n\n    def override(method: _F, /) -> _F: ...\n    @final\n    class TypeAliasType:\n        def __new__(cls, name: str, value: Any, *, type_params: tuple[_TypeParameter, ...] = ()) -> Self: ...\n        @property\n        def __value__(self) -> Any: ...  # AnnotationForm\n        @property\n        def __type_params__(self) -> tuple[_TypeParameter, ...]: ...\n        @property\n        def __parameters__(self) -> tuple[Any, ...]: ...  # AnnotationForm\n        @property\n        def __name__(self) -> str: ...\n        # It's writable on types, but not on instances of TypeAliasType.\n        @property\n        def __module__(self) -> str | None: ...  # type: ignore[override]\n        def __getitem__(self, parameters: Any, /) -> GenericAlias: ...  # AnnotationForm\n        def __or__(self, right: Any, /) -> _SpecialForm: ...\n        def __ror__(self, left: Any, /) -> _SpecialForm: ...\n        if sys.version_info >= (3, 14):\n            @property\n            def evaluate_value(self) -> EvaluateFunc: ...\n\nif sys.version_info >= (3, 13):\n    def is_protocol(tp: type, /) -> bool: ...\n    def get_protocol_members(tp: type, /) -> frozenset[str]: ...\n    @final\n    @type_check_only\n    class _NoDefaultType: ...\n\n    NoDefault: _NoDefaultType\n    TypeIs: _SpecialForm\n    ReadOnly: _SpecialForm\n"
  },
  {
    "path": "mypy/typeshed/stdlib/typing_extensions.pyi",
    "content": "import abc\nimport enum\nimport sys\nfrom _collections_abc import dict_items, dict_keys, dict_values\nfrom _typeshed import AnnotationForm, IdentityFunction, Incomplete, Unused\nfrom collections.abc import (\n    AsyncGenerator as AsyncGenerator,\n    AsyncIterable as AsyncIterable,\n    AsyncIterator as AsyncIterator,\n    Awaitable as Awaitable,\n    Collection as Collection,\n    Container as Container,\n    Coroutine as Coroutine,\n    Generator as Generator,\n    Hashable as Hashable,\n    ItemsView as ItemsView,\n    Iterable as Iterable,\n    Iterator as Iterator,\n    KeysView as KeysView,\n    Mapping as Mapping,\n    MappingView as MappingView,\n    MutableMapping as MutableMapping,\n    MutableSequence as MutableSequence,\n    MutableSet as MutableSet,\n    Reversible as Reversible,\n    Sequence as Sequence,\n    Sized as Sized,\n    ValuesView as ValuesView,\n)\nfrom contextlib import AbstractAsyncContextManager as AsyncContextManager, AbstractContextManager as ContextManager\nfrom re import Match as Match, Pattern as Pattern\nfrom types import GenericAlias, ModuleType\nfrom typing import (  # noqa: Y022,Y037,Y038,Y039,UP035,RUF100\n    IO as IO,\n    TYPE_CHECKING as TYPE_CHECKING,\n    AbstractSet as AbstractSet,\n    Any as Any,\n    AnyStr as AnyStr,\n    BinaryIO as BinaryIO,\n    Callable as Callable,\n    ChainMap as ChainMap,\n    ClassVar as ClassVar,\n    Counter as Counter,\n    DefaultDict as DefaultDict,\n    Deque as Deque,\n    Dict as Dict,\n    ForwardRef as ForwardRef,\n    FrozenSet as FrozenSet,\n    Generic as Generic,\n    List as List,\n    NoReturn as NoReturn,\n    Optional as Optional,\n    Set as Set,\n    Text as Text,\n    TextIO as TextIO,\n    Tuple as Tuple,\n    Type as Type,\n    TypedDict as TypedDict,\n    TypeVar as _TypeVar,\n    Union as Union,\n    _Alias,\n    _SpecialForm,\n    cast as cast,\n    no_type_check as no_type_check,\n    no_type_check_decorator as no_type_check_decorator,\n    overload as overload,\n    type_check_only,\n)\n\nif sys.version_info >= (3, 10):\n    from types import UnionType\n\n# Please keep order the same as at runtime.\n__all__ = [\n    # Super-special typing primitives.\n    \"Any\",\n    \"ClassVar\",\n    \"Concatenate\",\n    \"Final\",\n    \"LiteralString\",\n    \"ParamSpec\",\n    \"ParamSpecArgs\",\n    \"ParamSpecKwargs\",\n    \"Self\",\n    \"Type\",\n    \"TypeVar\",\n    \"TypeVarTuple\",\n    \"Unpack\",\n    # ABCs (from collections.abc).\n    \"Awaitable\",\n    \"AsyncIterator\",\n    \"AsyncIterable\",\n    \"Coroutine\",\n    \"AsyncGenerator\",\n    \"AsyncContextManager\",\n    \"Buffer\",\n    \"ChainMap\",\n    # Concrete collection types.\n    \"ContextManager\",\n    \"Counter\",\n    \"Deque\",\n    \"DefaultDict\",\n    \"NamedTuple\",\n    \"OrderedDict\",\n    \"TypedDict\",\n    # Structural checks, a.k.a. protocols.\n    \"SupportsAbs\",\n    \"SupportsBytes\",\n    \"SupportsComplex\",\n    \"SupportsFloat\",\n    \"SupportsIndex\",\n    \"SupportsInt\",\n    \"SupportsRound\",\n    \"Reader\",\n    \"Writer\",\n    # One-off things.\n    \"Annotated\",\n    \"assert_never\",\n    \"assert_type\",\n    \"clear_overloads\",\n    \"dataclass_transform\",\n    \"deprecated\",\n    \"disjoint_base\",\n    \"Doc\",\n    \"evaluate_forward_ref\",\n    \"get_overloads\",\n    \"final\",\n    \"Format\",\n    \"get_annotations\",\n    \"get_args\",\n    \"get_origin\",\n    \"get_original_bases\",\n    \"get_protocol_members\",\n    \"get_type_hints\",\n    \"IntVar\",\n    \"is_protocol\",\n    \"is_typeddict\",\n    \"Literal\",\n    \"NewType\",\n    \"overload\",\n    \"override\",\n    \"Protocol\",\n    \"Sentinel\",\n    \"reveal_type\",\n    \"runtime\",\n    \"runtime_checkable\",\n    \"Text\",\n    \"TypeAlias\",\n    \"TypeAliasType\",\n    \"TypeForm\",\n    \"TypeGuard\",\n    \"TypeIs\",\n    \"TYPE_CHECKING\",\n    \"type_repr\",\n    \"Never\",\n    \"NoReturn\",\n    \"ReadOnly\",\n    \"Required\",\n    \"NotRequired\",\n    \"NoDefault\",\n    \"NoExtraItems\",\n    # Pure aliases, have always been in typing\n    \"AbstractSet\",\n    \"AnyStr\",\n    \"BinaryIO\",\n    \"Callable\",\n    \"Collection\",\n    \"Container\",\n    \"Dict\",\n    \"ForwardRef\",\n    \"FrozenSet\",\n    \"Generator\",\n    \"Generic\",\n    \"Hashable\",\n    \"IO\",\n    \"ItemsView\",\n    \"Iterable\",\n    \"Iterator\",\n    \"KeysView\",\n    \"List\",\n    \"Mapping\",\n    \"MappingView\",\n    \"Match\",\n    \"MutableMapping\",\n    \"MutableSequence\",\n    \"MutableSet\",\n    \"Optional\",\n    \"Pattern\",\n    \"Reversible\",\n    \"Sequence\",\n    \"Set\",\n    \"Sized\",\n    \"TextIO\",\n    \"Tuple\",\n    \"Union\",\n    \"ValuesView\",\n    \"cast\",\n    \"no_type_check\",\n    \"no_type_check_decorator\",\n    # Added dynamically\n    \"CapsuleType\",\n]\n\n_T = _TypeVar(\"_T\")\n_F = _TypeVar(\"_F\", bound=Callable[..., Any])\n_TC = _TypeVar(\"_TC\", bound=type[object])\n_T_co = _TypeVar(\"_T_co\", covariant=True)  # Any type covariant containers.\n_T_contra = _TypeVar(\"_T_contra\", contravariant=True)\n\n# Do not import (and re-export) Protocol or runtime_checkable from\n# typing module because type checkers need to be able to distinguish\n# typing.Protocol and typing_extensions.Protocol so they can properly\n# warn users about potential runtime exceptions when using typing.Protocol\n# on older versions of Python.\nProtocol: _SpecialForm\n\ndef runtime_checkable(cls: _TC) -> _TC: ...\n\n# This alias for above is kept here for backwards compatibility.\nruntime = runtime_checkable\nFinal: _SpecialForm\n\ndef final(f: _F) -> _F: ...\ndef disjoint_base(cls: _TC) -> _TC: ...\n\nLiteral: _SpecialForm\n\ndef IntVar(name: str) -> Any: ...  # returns a new TypeVar\n\n# Internal mypy fallback type for all typed dicts (does not exist at runtime)\n# N.B. Keep this mostly in sync with typing._TypedDict/mypy_extensions._TypedDict\n@type_check_only\nclass _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta):\n    __required_keys__: ClassVar[frozenset[str]]\n    __optional_keys__: ClassVar[frozenset[str]]\n    __total__: ClassVar[bool]\n    __orig_bases__: ClassVar[tuple[Any, ...]]\n    # PEP 705\n    __readonly_keys__: ClassVar[frozenset[str]]\n    __mutable_keys__: ClassVar[frozenset[str]]\n    # PEP 728\n    __closed__: ClassVar[bool | None]\n    __extra_items__: ClassVar[AnnotationForm]\n    def copy(self) -> Self: ...\n    # Using Never so that only calls using mypy plugin hook that specialize the signature\n    # can go through.\n    def setdefault(self, k: Never, default: object) -> object: ...\n    # Mypy plugin hook for 'pop' expects that 'default' has a type variable type.\n    def pop(self, k: Never, default: _T = ...) -> object: ...  # pyright: ignore[reportInvalidTypeVarUse]\n    def update(self, m: Self, /) -> None: ...\n    def items(self) -> dict_items[str, object]: ...\n    def keys(self) -> dict_keys[str, object]: ...\n    def values(self) -> dict_values[str, object]: ...\n    def __delitem__(self, k: Never) -> None: ...\n    @overload\n    def __or__(self, value: Self, /) -> Self: ...\n    @overload\n    def __or__(self, value: dict[str, Any], /) -> dict[str, object]: ...\n    @overload\n    def __ror__(self, value: Self, /) -> Self: ...\n    @overload\n    def __ror__(self, value: dict[str, Any], /) -> dict[str, object]: ...\n    # supposedly incompatible definitions of `__ior__` and `__or__`:\n    # Since this module defines \"Self\" it is not recognized by Ruff as typing_extensions.Self\n    def __ior__(self, value: Self, /) -> Self: ...  # type: ignore[misc]\n\nOrderedDict = _Alias()\n\nif sys.version_info >= (3, 13):\n    from typing import get_type_hints as get_type_hints\nelse:\n    def get_type_hints(\n        obj: Any, globalns: dict[str, Any] | None = None, localns: Mapping[str, Any] | None = None, include_extras: bool = False\n    ) -> dict[str, AnnotationForm]: ...\n\ndef get_args(tp: AnnotationForm) -> tuple[AnnotationForm, ...]: ...\n\nif sys.version_info >= (3, 10):\n    @overload\n    def get_origin(tp: UnionType) -> type[UnionType]: ...\n\n@overload\ndef get_origin(tp: GenericAlias) -> type: ...\n@overload\ndef get_origin(tp: ParamSpecArgs | ParamSpecKwargs) -> ParamSpec: ...\n@overload\ndef get_origin(tp: AnnotationForm) -> AnnotationForm | None: ...\n\nAnnotated: _SpecialForm\n_AnnotatedAlias: Any  # undocumented\n\n# New and changed things in 3.10\nif sys.version_info >= (3, 10):\n    from typing import (\n        Concatenate as Concatenate,\n        ParamSpecArgs as ParamSpecArgs,\n        ParamSpecKwargs as ParamSpecKwargs,\n        TypeAlias as TypeAlias,\n        TypeGuard as TypeGuard,\n        is_typeddict as is_typeddict,\n    )\nelse:\n    @final\n    class ParamSpecArgs:\n        @property\n        def __origin__(self) -> ParamSpec: ...\n        def __init__(self, origin: ParamSpec) -> None: ...\n\n    @final\n    class ParamSpecKwargs:\n        @property\n        def __origin__(self) -> ParamSpec: ...\n        def __init__(self, origin: ParamSpec) -> None: ...\n\n    Concatenate: _SpecialForm\n    TypeAlias: _SpecialForm\n    TypeGuard: _SpecialForm\n    def is_typeddict(tp: object) -> bool: ...\n\n# New and changed things in 3.11\nif sys.version_info >= (3, 11):\n    from typing import (\n        LiteralString as LiteralString,\n        NamedTuple as NamedTuple,\n        Never as Never,\n        NewType as NewType,\n        NotRequired as NotRequired,\n        Required as Required,\n        Self as Self,\n        Unpack as Unpack,\n        assert_never as assert_never,\n        assert_type as assert_type,\n        clear_overloads as clear_overloads,\n        dataclass_transform as dataclass_transform,\n        get_overloads as get_overloads,\n        reveal_type as reveal_type,\n    )\nelse:\n    Self: _SpecialForm\n    Never: _SpecialForm\n    def reveal_type(obj: _T, /) -> _T: ...\n    def assert_never(arg: Never, /) -> Never: ...\n    def assert_type(val: _T, typ: AnnotationForm, /) -> _T: ...\n    def clear_overloads() -> None: ...\n    def get_overloads(func: Callable[..., object]) -> Sequence[Callable[..., object]]: ...\n\n    Required: _SpecialForm\n    NotRequired: _SpecialForm\n    LiteralString: _SpecialForm\n    Unpack: _SpecialForm\n\n    def dataclass_transform(\n        *,\n        eq_default: bool = True,\n        order_default: bool = False,\n        kw_only_default: bool = False,\n        frozen_default: bool = False,\n        field_specifiers: tuple[type[Any] | Callable[..., Any], ...] = (),\n        **kwargs: object,\n    ) -> IdentityFunction: ...\n\n    class NamedTuple(tuple[Any, ...]):\n        _field_defaults: ClassVar[dict[str, Any]]\n        _fields: ClassVar[tuple[str, ...]]\n        __orig_bases__: ClassVar[tuple[Any, ...]]\n        @overload\n        def __init__(self, typename: str, fields: Iterable[tuple[str, Any]] = ...) -> None: ...\n        @overload\n        def __init__(self, typename: str, fields: None = None, **kwargs: Any) -> None: ...\n        @classmethod\n        def _make(cls, iterable: Iterable[Any]) -> Self: ...\n        def _asdict(self) -> dict[str, Any]: ...\n        def _replace(self, **kwargs: Any) -> Self: ...\n\n    class NewType:\n        def __init__(self, name: str, tp: AnnotationForm) -> None: ...\n        def __call__(self, obj: _T, /) -> _T: ...\n        __supertype__: type | NewType\n        __name__: str\n        if sys.version_info >= (3, 10):\n            def __or__(self, other: Any) -> _SpecialForm: ...\n            def __ror__(self, other: Any) -> _SpecialForm: ...\n\nif sys.version_info >= (3, 12):\n    from collections.abc import Buffer as Buffer\n    from types import get_original_bases as get_original_bases\n    from typing import (\n        SupportsAbs as SupportsAbs,\n        SupportsBytes as SupportsBytes,\n        SupportsComplex as SupportsComplex,\n        SupportsFloat as SupportsFloat,\n        SupportsIndex as SupportsIndex,\n        SupportsInt as SupportsInt,\n        SupportsRound as SupportsRound,\n        override as override,\n    )\nelse:\n    def override(arg: _F, /) -> _F: ...\n    def get_original_bases(cls: type, /) -> tuple[Any, ...]: ...\n\n    # mypy and pyright object to this being both ABC and Protocol.\n    # At runtime it inherits from ABC and is not a Protocol, but it is on the\n    # allowlist for use as a Protocol.\n    @runtime_checkable\n    class Buffer(Protocol, abc.ABC):  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n        # Not actually a Protocol at runtime; see\n        # https://github.com/python/typeshed/issues/10224 for why we're defining it this way\n        def __buffer__(self, flags: int, /) -> memoryview: ...\n\n    @runtime_checkable\n    class SupportsInt(Protocol, metaclass=abc.ABCMeta):\n        __slots__ = ()\n        @abc.abstractmethod\n        def __int__(self) -> int: ...\n\n    @runtime_checkable\n    class SupportsFloat(Protocol, metaclass=abc.ABCMeta):\n        __slots__ = ()\n        @abc.abstractmethod\n        def __float__(self) -> float: ...\n\n    @runtime_checkable\n    class SupportsComplex(Protocol, metaclass=abc.ABCMeta):\n        __slots__ = ()\n        @abc.abstractmethod\n        def __complex__(self) -> complex: ...\n\n    @runtime_checkable\n    class SupportsBytes(Protocol, metaclass=abc.ABCMeta):\n        __slots__ = ()\n        @abc.abstractmethod\n        def __bytes__(self) -> bytes: ...\n\n    @runtime_checkable\n    class SupportsIndex(Protocol, metaclass=abc.ABCMeta):\n        __slots__ = ()\n        @abc.abstractmethod\n        def __index__(self) -> int: ...\n\n    @runtime_checkable\n    class SupportsAbs(Protocol[_T_co]):\n        __slots__ = ()\n        @abc.abstractmethod\n        def __abs__(self) -> _T_co: ...\n\n    @runtime_checkable\n    class SupportsRound(Protocol[_T_co]):\n        __slots__ = ()\n        @overload\n        @abc.abstractmethod\n        def __round__(self) -> int: ...\n        @overload\n        @abc.abstractmethod\n        def __round__(self, ndigits: int, /) -> _T_co: ...\n\nif sys.version_info >= (3, 14):\n    from io import Reader as Reader, Writer as Writer\nelse:\n    @runtime_checkable\n    class Reader(Protocol[_T_co]):\n        __slots__ = ()\n        @abc.abstractmethod\n        def read(self, size: int = ..., /) -> _T_co: ...\n\n    @runtime_checkable\n    class Writer(Protocol[_T_contra]):\n        __slots__ = ()\n        @abc.abstractmethod\n        def write(self, data: _T_contra, /) -> int: ...\n\nif sys.version_info >= (3, 13):\n    from types import CapsuleType as CapsuleType\n    from typing import (\n        NoDefault as NoDefault,\n        ParamSpec as ParamSpec,\n        ReadOnly as ReadOnly,\n        TypeIs as TypeIs,\n        TypeVar as TypeVar,\n        TypeVarTuple as TypeVarTuple,\n        get_protocol_members as get_protocol_members,\n        is_protocol as is_protocol,\n    )\n    from warnings import deprecated as deprecated\nelse:\n    def is_protocol(tp: type, /) -> bool: ...\n    def get_protocol_members(tp: type, /) -> frozenset[str]: ...\n    @final\n    @type_check_only\n    class _NoDefaultType: ...\n\n    NoDefault: _NoDefaultType\n    @final\n    class CapsuleType: ...\n\n    class deprecated:\n        message: LiteralString\n        category: type[Warning] | None\n        stacklevel: int\n        def __init__(self, message: LiteralString, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ...\n        def __call__(self, arg: _T, /) -> _T: ...\n\n    @final\n    class TypeVar:\n        @property\n        def __name__(self) -> str: ...\n        @property\n        def __bound__(self) -> AnnotationForm | None: ...\n        @property\n        def __constraints__(self) -> tuple[AnnotationForm, ...]: ...\n        @property\n        def __covariant__(self) -> bool: ...\n        @property\n        def __contravariant__(self) -> bool: ...\n        @property\n        def __infer_variance__(self) -> bool: ...\n        @property\n        def __default__(self) -> AnnotationForm: ...\n        def __init__(\n            self,\n            name: str,\n            *constraints: AnnotationForm,\n            bound: AnnotationForm | None = None,\n            covariant: bool = False,\n            contravariant: bool = False,\n            default: AnnotationForm = ...,\n            infer_variance: bool = False,\n        ) -> None: ...\n        def has_default(self) -> bool: ...\n        def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ...\n        if sys.version_info >= (3, 10):\n            def __or__(self, right: Any) -> _SpecialForm: ...\n            def __ror__(self, left: Any) -> _SpecialForm: ...\n        if sys.version_info >= (3, 11):\n            def __typing_subst__(self, arg: Any) -> Any: ...\n\n    @final\n    class ParamSpec:\n        @property\n        def __name__(self) -> str: ...\n        @property\n        def __bound__(self) -> AnnotationForm | None: ...\n        @property\n        def __covariant__(self) -> bool: ...\n        @property\n        def __contravariant__(self) -> bool: ...\n        @property\n        def __infer_variance__(self) -> bool: ...\n        @property\n        def __default__(self) -> AnnotationForm: ...\n        def __init__(\n            self,\n            name: str,\n            *,\n            bound: None | AnnotationForm | str = None,\n            contravariant: bool = False,\n            covariant: bool = False,\n            default: AnnotationForm = ...,\n        ) -> None: ...\n        @property\n        def args(self) -> ParamSpecArgs: ...\n        @property\n        def kwargs(self) -> ParamSpecKwargs: ...\n        def has_default(self) -> bool: ...\n        def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ...\n        if sys.version_info >= (3, 10):\n            def __or__(self, right: Any) -> _SpecialForm: ...\n            def __ror__(self, left: Any) -> _SpecialForm: ...\n\n    @final\n    class TypeVarTuple:\n        @property\n        def __name__(self) -> str: ...\n        @property\n        def __default__(self) -> AnnotationForm: ...\n        def __init__(self, name: str, *, default: AnnotationForm = ...) -> None: ...\n        def __iter__(self) -> Any: ...  # Unpack[Self]\n        def has_default(self) -> bool: ...\n        def __typing_prepare_subst__(self, alias: Any, args: Any) -> tuple[Any, ...]: ...\n\n    ReadOnly: _SpecialForm\n    TypeIs: _SpecialForm\n\n# TypeAliasType was added in Python 3.12, but had significant changes in 3.14.\nif sys.version_info >= (3, 14):\n    from typing import TypeAliasType as TypeAliasType\nelse:\n    @final\n    class TypeAliasType:\n        def __init__(\n            self, name: str, value: AnnotationForm, *, type_params: tuple[TypeVar | ParamSpec | TypeVarTuple, ...] = ()\n        ) -> None: ...\n        @property\n        def __value__(self) -> AnnotationForm: ...\n        @property\n        def __type_params__(self) -> tuple[TypeVar | ParamSpec | TypeVarTuple, ...]: ...\n        @property\n        # `__parameters__` can include special forms if a `TypeVarTuple` was\n        # passed as a `type_params` element to the constructor method.\n        def __parameters__(self) -> tuple[TypeVar | ParamSpec | AnnotationForm, ...]: ...\n        @property\n        def __name__(self) -> str: ...\n        # It's writable on types, but not on instances of TypeAliasType.\n        @property\n        def __module__(self) -> str | None: ...  # type: ignore[override]\n        # Returns typing._GenericAlias, which isn't stubbed.\n        def __getitem__(self, parameters: Incomplete | tuple[Incomplete, ...]) -> AnnotationForm: ...\n        def __init_subclass__(cls, *args: Unused, **kwargs: Unused) -> NoReturn: ...\n        if sys.version_info >= (3, 10):\n            def __or__(self, right: Any, /) -> _SpecialForm: ...\n            def __ror__(self, left: Any, /) -> _SpecialForm: ...\n\n# PEP 727\nclass Doc:\n    documentation: str\n    def __init__(self, documentation: str, /) -> None: ...\n    def __hash__(self) -> int: ...\n    def __eq__(self, other: object) -> bool: ...\n\n# PEP 728\n@type_check_only\nclass _NoExtraItemsType: ...\n\nNoExtraItems: _NoExtraItemsType\n\n# PEP 747\nTypeForm: _SpecialForm\n\n# PEP 649/749\nif sys.version_info >= (3, 14):\n    from typing import evaluate_forward_ref as evaluate_forward_ref\n\n    from annotationlib import Format as Format, get_annotations as get_annotations, type_repr as type_repr\nelse:\n    class Format(enum.IntEnum):\n        VALUE = 1\n        VALUE_WITH_FAKE_GLOBALS = 2\n        FORWARDREF = 3\n        STRING = 4\n\n    @overload\n    def get_annotations(\n        obj: Any,  # any object with __annotations__ or __annotate__\n        *,\n        globals: Mapping[str, Any] | None = None,  # value types depend on the key\n        locals: Mapping[str, Any] | None = None,  # value types depend on the key\n        eval_str: bool = False,\n        format: Literal[Format.STRING],\n    ) -> dict[str, str]: ...\n    @overload\n    def get_annotations(\n        obj: Any,  # any object with __annotations__ or __annotate__\n        *,\n        globals: Mapping[str, Any] | None = None,  # value types depend on the key\n        locals: Mapping[str, Any] | None = None,  # value types depend on the key\n        eval_str: bool = False,\n        format: Literal[Format.FORWARDREF],\n    ) -> dict[str, AnnotationForm | ForwardRef]: ...\n    @overload\n    def get_annotations(\n        obj: Any,  # any object with __annotations__ or __annotate__\n        *,\n        globals: Mapping[str, Any] | None = None,  # value types depend on the key\n        locals: Mapping[str, Any] | None = None,  # value types depend on the key\n        eval_str: bool = False,\n        format: Format = Format.VALUE,  # noqa: Y011\n    ) -> dict[str, AnnotationForm]: ...\n    @overload\n    def evaluate_forward_ref(\n        forward_ref: ForwardRef,\n        *,\n        owner: Callable[..., object] | type[object] | ModuleType | None = None,  # any callable, class, or module\n        globals: Mapping[str, Any] | None = None,  # value types depend on the key\n        locals: Mapping[str, Any] | None = None,  # value types depend on the key\n        type_params: Iterable[TypeVar | ParamSpec | TypeVarTuple] | None = None,\n        format: Literal[Format.STRING],\n        _recursive_guard: Container[str] = ...,\n    ) -> str: ...\n    @overload\n    def evaluate_forward_ref(\n        forward_ref: ForwardRef,\n        *,\n        owner: Callable[..., object] | type[object] | ModuleType | None = None,  # any callable, class, or module\n        globals: Mapping[str, Any] | None = None,  # value types depend on the key\n        locals: Mapping[str, Any] | None = None,  # value types depend on the key\n        type_params: Iterable[TypeVar | ParamSpec | TypeVarTuple] | None = None,\n        format: Literal[Format.FORWARDREF],\n        _recursive_guard: Container[str] = ...,\n    ) -> AnnotationForm | ForwardRef: ...\n    @overload\n    def evaluate_forward_ref(\n        forward_ref: ForwardRef,\n        *,\n        owner: Callable[..., object] | type[object] | ModuleType | None = None,  # any callable, class, or module\n        globals: Mapping[str, Any] | None = None,  # value types depend on the key\n        locals: Mapping[str, Any] | None = None,  # value types depend on the key\n        type_params: Iterable[TypeVar | ParamSpec | TypeVarTuple] | None = None,\n        format: Format | None = None,\n        _recursive_guard: Container[str] = ...,\n    ) -> AnnotationForm: ...\n    def type_repr(value: object) -> str: ...\n\n# PEP 661\nclass Sentinel:\n    def __init__(self, name: str, repr: str | None = None) -> None: ...\n    if sys.version_info >= (3, 14):\n        def __or__(self, other: Any) -> UnionType: ...  # other can be any type form legal for unions\n        def __ror__(self, other: Any) -> UnionType: ...  # other can be any type form legal for unions\n    elif sys.version_info >= (3, 10):\n        def __or__(self, other: Any) -> _SpecialForm: ...  # other can be any type form legal for unions\n        def __ror__(self, other: Any) -> _SpecialForm: ...  # other can be any type form legal for unions\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unicodedata.pyi",
    "content": "import sys\nfrom _typeshed import ReadOnlyBuffer\nfrom typing import Any, Final, Literal, TypeVar, final, overload\nfrom typing_extensions import TypeAlias\n\nucd_3_2_0: UCD\nunidata_version: Final[str]\n\nif sys.version_info < (3, 10):\n    ucnhash_CAPI: Any\n\n_T = TypeVar(\"_T\")\n\n_NormalizationForm: TypeAlias = Literal[\"NFC\", \"NFD\", \"NFKC\", \"NFKD\"]\n\ndef bidirectional(chr: str, /) -> str: ...\ndef category(chr: str, /) -> str: ...\ndef combining(chr: str, /) -> int: ...\n@overload\ndef decimal(chr: str, /) -> int: ...\n@overload\ndef decimal(chr: str, default: _T, /) -> int | _T: ...\ndef decomposition(chr: str, /) -> str: ...\n@overload\ndef digit(chr: str, /) -> int: ...\n@overload\ndef digit(chr: str, default: _T, /) -> int | _T: ...\n\n_EastAsianWidth: TypeAlias = Literal[\"F\", \"H\", \"W\", \"Na\", \"A\", \"N\"]\n\ndef east_asian_width(chr: str, /) -> _EastAsianWidth: ...\ndef is_normalized(form: _NormalizationForm, unistr: str, /) -> bool: ...\ndef lookup(name: str | ReadOnlyBuffer, /) -> str: ...\ndef mirrored(chr: str, /) -> int: ...\n@overload\ndef name(chr: str, /) -> str: ...\n@overload\ndef name(chr: str, default: _T, /) -> str | _T: ...\ndef normalize(form: _NormalizationForm, unistr: str, /) -> str: ...\n@overload\ndef numeric(chr: str, /) -> float: ...\n@overload\ndef numeric(chr: str, default: _T, /) -> float | _T: ...\n@final\nclass UCD:\n    # The methods below are constructed from the same array in C\n    # (unicodedata_functions) and hence identical to the functions above.\n    unidata_version: str\n    def bidirectional(self, chr: str, /) -> str: ...\n    def category(self, chr: str, /) -> str: ...\n    def combining(self, chr: str, /) -> int: ...\n    @overload\n    def decimal(self, chr: str, /) -> int: ...\n    @overload\n    def decimal(self, chr: str, default: _T, /) -> int | _T: ...\n    def decomposition(self, chr: str, /) -> str: ...\n    @overload\n    def digit(self, chr: str, /) -> int: ...\n    @overload\n    def digit(self, chr: str, default: _T, /) -> int | _T: ...\n    def east_asian_width(self, chr: str, /) -> _EastAsianWidth: ...\n    def is_normalized(self, form: _NormalizationForm, unistr: str, /) -> bool: ...\n    def lookup(self, name: str | ReadOnlyBuffer, /) -> str: ...\n    def mirrored(self, chr: str, /) -> int: ...\n    @overload\n    def name(self, chr: str, /) -> str: ...\n    @overload\n    def name(self, chr: str, default: _T, /) -> str | _T: ...\n    def normalize(self, form: _NormalizationForm, unistr: str, /) -> str: ...\n    @overload\n    def numeric(self, chr: str, /) -> float: ...\n    @overload\n    def numeric(self, chr: str, default: _T, /) -> float | _T: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/__init__.pyi",
    "content": "import sys\nfrom unittest.async_case import *\n\nfrom .case import (\n    FunctionTestCase as FunctionTestCase,\n    SkipTest as SkipTest,\n    TestCase as TestCase,\n    addModuleCleanup as addModuleCleanup,\n    expectedFailure as expectedFailure,\n    skip as skip,\n    skipIf as skipIf,\n    skipUnless as skipUnless,\n)\nfrom .loader import TestLoader as TestLoader, defaultTestLoader as defaultTestLoader\nfrom .main import TestProgram as TestProgram, main as main\nfrom .result import TestResult as TestResult\nfrom .runner import TextTestResult as TextTestResult, TextTestRunner as TextTestRunner\nfrom .signals import (\n    installHandler as installHandler,\n    registerResult as registerResult,\n    removeHandler as removeHandler,\n    removeResult as removeResult,\n)\nfrom .suite import BaseTestSuite as BaseTestSuite, TestSuite as TestSuite\n\nif sys.version_info >= (3, 11):\n    from .case import doModuleCleanups as doModuleCleanups, enterModuleContext as enterModuleContext\n\n__all__ = [\n    \"IsolatedAsyncioTestCase\",\n    \"TestResult\",\n    \"TestCase\",\n    \"TestSuite\",\n    \"TextTestRunner\",\n    \"TestLoader\",\n    \"FunctionTestCase\",\n    \"main\",\n    \"defaultTestLoader\",\n    \"SkipTest\",\n    \"skip\",\n    \"skipIf\",\n    \"skipUnless\",\n    \"expectedFailure\",\n    \"TextTestResult\",\n    \"installHandler\",\n    \"registerResult\",\n    \"removeResult\",\n    \"removeHandler\",\n    \"addModuleCleanup\",\n]\n\nif sys.version_info < (3, 13):\n    from .loader import findTestCases as findTestCases, getTestCaseNames as getTestCaseNames, makeSuite as makeSuite\n\n    __all__ += [\"getTestCaseNames\", \"makeSuite\", \"findTestCases\"]\n\nif sys.version_info >= (3, 11):\n    __all__ += [\"enterModuleContext\", \"doModuleCleanups\"]\n\nif sys.version_info < (3, 12):\n    def load_tests(loader: TestLoader, tests: TestSuite, pattern: str | None) -> TestSuite: ...\n\ndef __dir__() -> set[str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/_log.pyi",
    "content": "import logging\nimport sys\nfrom types import TracebackType\nfrom typing import ClassVar, Generic, NamedTuple, TypeVar\nfrom unittest.case import TestCase, _BaseTestCaseContext\n\n_L = TypeVar(\"_L\", None, _LoggingWatcher)\n\nclass _LoggingWatcher(NamedTuple):\n    records: list[logging.LogRecord]\n    output: list[str]\n\nclass _AssertLogsContext(_BaseTestCaseContext, Generic[_L]):\n    LOGGING_FORMAT: ClassVar[str]\n    logger_name: str\n    level: int\n    msg: None\n    if sys.version_info >= (3, 10):\n        def __init__(self, test_case: TestCase, logger_name: str, level: int, no_logs: bool) -> None: ...\n        no_logs: bool\n    else:\n        def __init__(self, test_case: TestCase, logger_name: str, level: int) -> None: ...\n\n    def __enter__(self) -> _L: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None\n    ) -> bool | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/async_case.pyi",
    "content": "import sys\nfrom asyncio.events import AbstractEventLoop\nfrom collections.abc import Awaitable, Callable\nfrom typing import TypeVar\nfrom typing_extensions import ParamSpec\n\nfrom .case import TestCase\n\nif sys.version_info >= (3, 11):\n    from contextlib import AbstractAsyncContextManager\n\n_T = TypeVar(\"_T\")\n_P = ParamSpec(\"_P\")\n\nclass IsolatedAsyncioTestCase(TestCase):\n    if sys.version_info >= (3, 13):\n        loop_factory: Callable[[], AbstractEventLoop] | None = None\n\n    async def asyncSetUp(self) -> None: ...\n    async def asyncTearDown(self) -> None: ...\n    def addAsyncCleanup(self, func: Callable[_P, Awaitable[object]], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ...\n    if sys.version_info >= (3, 11):\n        async def enterAsyncContext(self, cm: AbstractAsyncContextManager[_T]) -> _T: ...\n\n    def __del__(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/case.pyi",
    "content": "import logging\nimport sys\nimport unittest.result\nfrom _typeshed import SupportsDunderGE, SupportsDunderGT, SupportsDunderLE, SupportsDunderLT, SupportsRSub, SupportsSub\nfrom builtins import _ClassInfo\nfrom collections.abc import Callable, Container, Iterable, Mapping, Sequence, Set as AbstractSet\nfrom contextlib import AbstractContextManager\nfrom re import Pattern\nfrom types import GenericAlias, TracebackType\nfrom typing import Any, AnyStr, Final, Generic, NoReturn, Protocol, SupportsAbs, SupportsRound, TypeVar, overload, type_check_only\nfrom typing_extensions import Never, ParamSpec, Self\nfrom unittest._log import _AssertLogsContext, _LoggingWatcher\nfrom warnings import WarningMessage\n\n_T = TypeVar(\"_T\")\n_S = TypeVar(\"_S\", bound=SupportsSub[Any, Any])\n_E = TypeVar(\"_E\", bound=BaseException)\n_FT = TypeVar(\"_FT\", bound=Callable[..., Any])\n_SB = TypeVar(\"_SB\", str, bytes, bytearray)\n_P = ParamSpec(\"_P\")\n\nDIFF_OMITTED: Final[str]\n\nclass _BaseTestCaseContext:\n    test_case: TestCase\n    def __init__(self, test_case: TestCase) -> None: ...\n\nclass _AssertRaisesBaseContext(_BaseTestCaseContext):\n    expected: type[BaseException] | tuple[type[BaseException], ...]\n    expected_regex: Pattern[str] | None\n    obj_name: str | None\n    msg: str | None\n\n    def __init__(\n        self,\n        expected: type[BaseException] | tuple[type[BaseException], ...],\n        test_case: TestCase,\n        expected_regex: str | Pattern[str] | None = None,\n    ) -> None: ...\n\n    # This returns Self if args is the empty list, and None otherwise.\n    # but it's not possible to construct an overload which expresses that\n    def handle(self, name: str, args: list[Any], kwargs: dict[str, Any]) -> Any: ...\n\ndef addModuleCleanup(function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ...\ndef doModuleCleanups() -> None: ...\n\nif sys.version_info >= (3, 11):\n    def enterModuleContext(cm: AbstractContextManager[_T]) -> _T: ...\n\ndef expectedFailure(test_item: _FT) -> _FT: ...\ndef skip(reason: str) -> Callable[[_FT], _FT]: ...\ndef skipIf(condition: object, reason: str) -> Callable[[_FT], _FT]: ...\ndef skipUnless(condition: object, reason: str) -> Callable[[_FT], _FT]: ...\n\nclass SkipTest(Exception):\n    def __init__(self, reason: str) -> None: ...\n\n@type_check_only\nclass _SupportsAbsAndDunderGE(SupportsDunderGE[Any], SupportsAbs[Any], Protocol): ...\n\nclass TestCase:\n    failureException: type[BaseException]\n    longMessage: bool\n    maxDiff: int | None\n    # undocumented\n    _testMethodName: str\n    # undocumented\n    _testMethodDoc: str\n    def __init__(self, methodName: str = \"runTest\") -> None: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n    def setUp(self) -> None: ...\n    def tearDown(self) -> None: ...\n    @classmethod\n    def setUpClass(cls) -> None: ...\n    @classmethod\n    def tearDownClass(cls) -> None: ...\n    def run(self, result: unittest.result.TestResult | None = None) -> unittest.result.TestResult | None: ...\n    def __call__(self, result: unittest.result.TestResult | None = ...) -> unittest.result.TestResult | None: ...\n    def skipTest(self, reason: Any) -> NoReturn: ...\n    def subTest(self, msg: Any = ..., **params: Any) -> AbstractContextManager[None]: ...\n    def debug(self) -> None: ...\n    if sys.version_info < (3, 11):\n        def _addSkip(self, result: unittest.result.TestResult, test_case: TestCase, reason: str) -> None: ...\n\n    def assertEqual(self, first: Any, second: Any, msg: Any = None) -> None: ...\n    def assertNotEqual(self, first: Any, second: Any, msg: Any = None) -> None: ...\n    def assertTrue(self, expr: Any, msg: Any = None) -> None: ...\n    def assertFalse(self, expr: Any, msg: Any = None) -> None: ...\n    def assertIs(self, expr1: object, expr2: object, msg: Any = None) -> None: ...\n    def assertIsNot(self, expr1: object, expr2: object, msg: Any = None) -> None: ...\n    def assertIsNone(self, obj: object, msg: Any = None) -> None: ...\n    def assertIsNotNone(self, obj: object, msg: Any = None) -> None: ...\n    def assertIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ...\n    def assertNotIn(self, member: Any, container: Iterable[Any] | Container[Any], msg: Any = None) -> None: ...\n    def assertIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ...\n    def assertNotIsInstance(self, obj: object, cls: _ClassInfo, msg: Any = None) -> None: ...\n    @overload\n    def assertGreater(self, a: SupportsDunderGT[_T], b: _T, msg: Any = None) -> None: ...\n    @overload\n    def assertGreater(self, a: _T, b: SupportsDunderLT[_T], msg: Any = None) -> None: ...\n    @overload\n    def assertGreaterEqual(self, a: SupportsDunderGE[_T], b: _T, msg: Any = None) -> None: ...\n    @overload\n    def assertGreaterEqual(self, a: _T, b: SupportsDunderLE[_T], msg: Any = None) -> None: ...\n    @overload\n    def assertLess(self, a: SupportsDunderLT[_T], b: _T, msg: Any = None) -> None: ...\n    @overload\n    def assertLess(self, a: _T, b: SupportsDunderGT[_T], msg: Any = None) -> None: ...\n    @overload\n    def assertLessEqual(self, a: SupportsDunderLE[_T], b: _T, msg: Any = None) -> None: ...\n    @overload\n    def assertLessEqual(self, a: _T, b: SupportsDunderGE[_T], msg: Any = None) -> None: ...\n    # `assertRaises`, `assertRaisesRegex`, and `assertRaisesRegexp`\n    # are not using `ParamSpec` intentionally,\n    # because they might be used with explicitly wrong arg types to raise some error in tests.\n    @overload\n    def assertRaises(\n        self,\n        expected_exception: type[BaseException] | tuple[type[BaseException], ...],\n        callable: Callable[..., object],\n        *args: Any,\n        **kwargs: Any,\n    ) -> None: ...\n    @overload\n    def assertRaises(\n        self, expected_exception: type[_E] | tuple[type[_E], ...], *, msg: Any = ...\n    ) -> _AssertRaisesContext[_E]: ...\n    @overload\n    def assertRaisesRegex(\n        self,\n        expected_exception: type[BaseException] | tuple[type[BaseException], ...],\n        expected_regex: str | Pattern[str],\n        callable: Callable[..., object],\n        *args: Any,\n        **kwargs: Any,\n    ) -> None: ...\n    @overload\n    def assertRaisesRegex(\n        self, expected_exception: type[_E] | tuple[type[_E], ...], expected_regex: str | Pattern[str], *, msg: Any = ...\n    ) -> _AssertRaisesContext[_E]: ...\n    @overload\n    def assertWarns(\n        self,\n        expected_warning: type[Warning] | tuple[type[Warning], ...],\n        callable: Callable[_P, object],\n        *args: _P.args,\n        **kwargs: _P.kwargs,\n    ) -> None: ...\n    @overload\n    def assertWarns(\n        self, expected_warning: type[Warning] | tuple[type[Warning], ...], *, msg: Any = ...\n    ) -> _AssertWarnsContext: ...\n    @overload\n    def assertWarnsRegex(\n        self,\n        expected_warning: type[Warning] | tuple[type[Warning], ...],\n        expected_regex: str | Pattern[str],\n        callable: Callable[_P, object],\n        *args: _P.args,\n        **kwargs: _P.kwargs,\n    ) -> None: ...\n    @overload\n    def assertWarnsRegex(\n        self, expected_warning: type[Warning] | tuple[type[Warning], ...], expected_regex: str | Pattern[str], *, msg: Any = ...\n    ) -> _AssertWarnsContext: ...\n    def assertLogs(\n        self, logger: str | logging.Logger | None = None, level: int | str | None = None\n    ) -> _AssertLogsContext[_LoggingWatcher]: ...\n    if sys.version_info >= (3, 10):\n        def assertNoLogs(\n            self, logger: str | logging.Logger | None = None, level: int | str | None = None\n        ) -> _AssertLogsContext[None]: ...\n\n    @overload\n    def assertAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ...\n    @overload\n    def assertAlmostEqual(\n        self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE\n    ) -> None: ...\n    @overload\n    def assertAlmostEqual(\n        self,\n        first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]],\n        second: _T,\n        places: int | None = None,\n        msg: Any = None,\n        delta: None = None,\n    ) -> None: ...\n    @overload\n    def assertAlmostEqual(\n        self,\n        first: _T,\n        second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]],\n        places: int | None = None,\n        msg: Any = None,\n        delta: None = None,\n    ) -> None: ...\n    @overload\n    def assertNotAlmostEqual(self, first: _S, second: _S, places: None, msg: Any, delta: _SupportsAbsAndDunderGE) -> None: ...\n    @overload\n    def assertNotAlmostEqual(\n        self, first: _S, second: _S, places: None = None, msg: Any = None, *, delta: _SupportsAbsAndDunderGE\n    ) -> None: ...\n    @overload\n    def assertNotAlmostEqual(\n        self,\n        first: SupportsSub[_T, SupportsAbs[SupportsRound[object]]],\n        second: _T,\n        places: int | None = None,\n        msg: Any = None,\n        delta: None = None,\n    ) -> None: ...\n    @overload\n    def assertNotAlmostEqual(\n        self,\n        first: _T,\n        second: SupportsRSub[_T, SupportsAbs[SupportsRound[object]]],\n        places: int | None = None,\n        msg: Any = None,\n        delta: None = None,\n    ) -> None: ...\n    def assertRegex(self, text: AnyStr, expected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ...\n    def assertNotRegex(self, text: AnyStr, unexpected_regex: AnyStr | Pattern[AnyStr], msg: Any = None) -> None: ...\n    def assertCountEqual(self, first: Iterable[Any], second: Iterable[Any], msg: Any = None) -> None: ...\n    def addTypeEqualityFunc(self, typeobj: type[Any], function: Callable[..., None]) -> None: ...\n    def assertMultiLineEqual(self, first: str, second: str, msg: Any = None) -> None: ...\n    def assertSequenceEqual(\n        self, seq1: Sequence[Any], seq2: Sequence[Any], msg: Any = None, seq_type: type[Sequence[Any]] | None = None\n    ) -> None: ...\n    def assertListEqual(self, list1: list[Any], list2: list[Any], msg: Any = None) -> None: ...\n    def assertTupleEqual(self, tuple1: tuple[Any, ...], tuple2: tuple[Any, ...], msg: Any = None) -> None: ...\n    def assertSetEqual(self, set1: AbstractSet[object], set2: AbstractSet[object], msg: Any = None) -> None: ...\n    # assertDictEqual accepts only true dict instances. We can't use that here, since that would make\n    # assertDictEqual incompatible with TypedDict.\n    def assertDictEqual(self, d1: Mapping[Any, object], d2: Mapping[Any, object], msg: Any = None) -> None: ...\n    def fail(self, msg: Any = None) -> NoReturn: ...\n    def countTestCases(self) -> int: ...\n    def defaultTestResult(self) -> unittest.result.TestResult: ...\n    def id(self) -> str: ...\n    def shortDescription(self) -> str | None: ...\n    def addCleanup(self, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ...\n\n    if sys.version_info >= (3, 11):\n        def enterContext(self, cm: AbstractContextManager[_T]) -> _T: ...\n\n    def doCleanups(self) -> None: ...\n    @classmethod\n    def addClassCleanup(cls, function: Callable[_P, object], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ...\n    @classmethod\n    def doClassCleanups(cls) -> None: ...\n\n    if sys.version_info >= (3, 11):\n        @classmethod\n        def enterClassContext(cls, cm: AbstractContextManager[_T]) -> _T: ...\n\n    def _formatMessage(self, msg: str | None, standardMsg: str) -> str: ...  # undocumented\n    def _getAssertEqualityFunc(self, first: Any, second: Any) -> Callable[..., None]: ...  # undocumented\n    if sys.version_info < (3, 12):\n        failUnlessEqual = assertEqual\n        assertEquals = assertEqual\n        failIfEqual = assertNotEqual\n        assertNotEquals = assertNotEqual\n        failUnless = assertTrue\n        assert_ = assertTrue\n        failIf = assertFalse\n        failUnlessRaises = assertRaises\n        failUnlessAlmostEqual = assertAlmostEqual\n        assertAlmostEquals = assertAlmostEqual\n        failIfAlmostEqual = assertNotAlmostEqual\n        assertNotAlmostEquals = assertNotAlmostEqual\n        assertRegexpMatches = assertRegex\n        assertNotRegexpMatches = assertNotRegex\n        assertRaisesRegexp = assertRaisesRegex\n        def assertDictContainsSubset(\n            self, subset: Mapping[Any, Any], dictionary: Mapping[Any, Any], msg: object = None\n        ) -> None: ...\n\n    if sys.version_info >= (3, 10):\n        # Runtime has *args, **kwargs, but will error if any are supplied\n        def __init_subclass__(cls, *args: Never, **kwargs: Never) -> None: ...\n\n    if sys.version_info >= (3, 14):\n        def assertIsSubclass(self, cls: type, superclass: type | tuple[type, ...], msg: Any = None) -> None: ...\n        def assertNotIsSubclass(self, cls: type, superclass: type | tuple[type, ...], msg: Any = None) -> None: ...\n        def assertHasAttr(self, obj: object, name: str, msg: Any = None) -> None: ...\n        def assertNotHasAttr(self, obj: object, name: str, msg: Any = None) -> None: ...\n        def assertStartsWith(self, s: _SB, prefix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ...\n        def assertNotStartsWith(self, s: _SB, prefix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ...\n        def assertEndsWith(self, s: _SB, suffix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ...\n        def assertNotEndsWith(self, s: _SB, suffix: _SB | tuple[_SB, ...], msg: Any = None) -> None: ...\n\nclass FunctionTestCase(TestCase):\n    def __init__(\n        self,\n        testFunc: Callable[[], object],\n        setUp: Callable[[], object] | None = None,\n        tearDown: Callable[[], object] | None = None,\n        description: str | None = None,\n    ) -> None: ...\n    def runTest(self) -> None: ...\n    def __hash__(self) -> int: ...\n    def __eq__(self, other: object) -> bool: ...\n\nclass _AssertRaisesContext(_AssertRaisesBaseContext, Generic[_E]):\n    exception: _E\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None\n    ) -> bool: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass _AssertWarnsContext(_AssertRaisesBaseContext):\n    warning: WarningMessage\n    filename: str\n    lineno: int\n    warnings: list[WarningMessage]\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, tb: TracebackType | None\n    ) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/loader.pyi",
    "content": "import sys\nimport unittest.case\nimport unittest.suite\nfrom collections.abc import Callable, Sequence\nfrom re import Pattern\nfrom types import ModuleType\nfrom typing import Any, Final\nfrom typing_extensions import TypeAlias, deprecated\n\n_SortComparisonMethod: TypeAlias = Callable[[str, str], int]\n_SuiteClass: TypeAlias = Callable[[list[unittest.case.TestCase]], unittest.suite.TestSuite]\n\nVALID_MODULE_NAME: Final[Pattern[str]]\n\nclass TestLoader:\n    errors: list[type[BaseException]]\n    testMethodPrefix: str\n    sortTestMethodsUsing: _SortComparisonMethod\n    testNamePatterns: list[str] | None\n    suiteClass: _SuiteClass\n    def loadTestsFromTestCase(self, testCaseClass: type[unittest.case.TestCase]) -> unittest.suite.TestSuite: ...\n    if sys.version_info >= (3, 12):\n        def loadTestsFromModule(self, module: ModuleType, *, pattern: str | None = None) -> unittest.suite.TestSuite: ...\n    else:\n        def loadTestsFromModule(self, module: ModuleType, *args: Any, pattern: str | None = None) -> unittest.suite.TestSuite: ...\n\n    def loadTestsFromName(self, name: str, module: ModuleType | None = None) -> unittest.suite.TestSuite: ...\n    def loadTestsFromNames(self, names: Sequence[str], module: ModuleType | None = None) -> unittest.suite.TestSuite: ...\n    def getTestCaseNames(self, testCaseClass: type[unittest.case.TestCase]) -> Sequence[str]: ...\n    def discover(\n        self, start_dir: str, pattern: str = \"test*.py\", top_level_dir: str | None = None\n    ) -> unittest.suite.TestSuite: ...\n    def _match_path(self, path: str, full_path: str, pattern: str) -> bool: ...\n\ndefaultTestLoader: TestLoader\n\nif sys.version_info < (3, 13):\n    if sys.version_info >= (3, 11):\n        @deprecated(\"Deprecated since Python 3.11; removed in Python 3.13.\")\n        def getTestCaseNames(\n            testCaseClass: type[unittest.case.TestCase],\n            prefix: str,\n            sortUsing: _SortComparisonMethod = ...,\n            testNamePatterns: list[str] | None = None,\n        ) -> Sequence[str]: ...\n        @deprecated(\"Deprecated since Python 3.11; removed in Python 3.13.\")\n        def makeSuite(\n            testCaseClass: type[unittest.case.TestCase],\n            prefix: str = \"test\",\n            sortUsing: _SortComparisonMethod = ...,\n            suiteClass: _SuiteClass = ...,\n        ) -> unittest.suite.TestSuite: ...\n        @deprecated(\"Deprecated since Python 3.11; removed in Python 3.13.\")\n        def findTestCases(\n            module: ModuleType, prefix: str = \"test\", sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ...\n        ) -> unittest.suite.TestSuite: ...\n    else:\n        def getTestCaseNames(\n            testCaseClass: type[unittest.case.TestCase],\n            prefix: str,\n            sortUsing: _SortComparisonMethod = ...,\n            testNamePatterns: list[str] | None = None,\n        ) -> Sequence[str]: ...\n        def makeSuite(\n            testCaseClass: type[unittest.case.TestCase],\n            prefix: str = \"test\",\n            sortUsing: _SortComparisonMethod = ...,\n            suiteClass: _SuiteClass = ...,\n        ) -> unittest.suite.TestSuite: ...\n        def findTestCases(\n            module: ModuleType, prefix: str = \"test\", sortUsing: _SortComparisonMethod = ..., suiteClass: _SuiteClass = ...\n        ) -> unittest.suite.TestSuite: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/main.pyi",
    "content": "import sys\nimport unittest.case\nimport unittest.loader\nimport unittest.result\nimport unittest.suite\nfrom collections.abc import Iterable\nfrom types import ModuleType\nfrom typing import Any, Final, Protocol, type_check_only\nfrom typing_extensions import deprecated\n\nMAIN_EXAMPLES: Final[str]\nMODULE_EXAMPLES: Final[str]\n\n@type_check_only\nclass _TestRunner(Protocol):\n    def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase, /) -> unittest.result.TestResult: ...\n\n# not really documented\nclass TestProgram:\n    result: unittest.result.TestResult\n    module: None | str | ModuleType\n    verbosity: int\n    failfast: bool | None\n    catchbreak: bool | None\n    buffer: bool | None\n    progName: str | None\n    warnings: str | None\n    testNamePatterns: list[str] | None\n    if sys.version_info >= (3, 12):\n        durations: unittest.result._DurationsType | None\n        def __init__(\n            self,\n            module: None | str | ModuleType = \"__main__\",\n            defaultTest: str | Iterable[str] | None = None,\n            argv: list[str] | None = None,\n            testRunner: type[_TestRunner] | _TestRunner | None = None,\n            testLoader: unittest.loader.TestLoader = ...,\n            exit: bool = True,\n            verbosity: int = 1,\n            failfast: bool | None = None,\n            catchbreak: bool | None = None,\n            buffer: bool | None = None,\n            warnings: str | None = None,\n            *,\n            tb_locals: bool = False,\n            durations: unittest.result._DurationsType | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            module: None | str | ModuleType = \"__main__\",\n            defaultTest: str | Iterable[str] | None = None,\n            argv: list[str] | None = None,\n            testRunner: type[_TestRunner] | _TestRunner | None = None,\n            testLoader: unittest.loader.TestLoader = ...,\n            exit: bool = True,\n            verbosity: int = 1,\n            failfast: bool | None = None,\n            catchbreak: bool | None = None,\n            buffer: bool | None = None,\n            warnings: str | None = None,\n            *,\n            tb_locals: bool = False,\n        ) -> None: ...\n\n    if sys.version_info < (3, 13):\n        if sys.version_info >= (3, 11):\n            @deprecated(\"Deprecated since Python 3.11; removed in Python 3.13.\")\n            def usageExit(self, msg: Any = None) -> None: ...\n        else:\n            def usageExit(self, msg: Any = None) -> None: ...\n\n    def parseArgs(self, argv: list[str]) -> None: ...\n    def createTests(self, from_discovery: bool = False, Loader: unittest.loader.TestLoader | None = None) -> None: ...\n    def runTests(self) -> None: ...  # undocumented\n\nmain = TestProgram\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/mock.pyi",
    "content": "import sys\nfrom _typeshed import MaybeNone\nfrom collections.abc import Awaitable, Callable, Coroutine, Iterable, Mapping, Sequence\nfrom contextlib import _GeneratorContextManager\nfrom types import TracebackType\nfrom typing import Any, ClassVar, Final, Generic, Literal, TypeVar, overload, type_check_only\nfrom typing_extensions import ParamSpec, Self, TypeAlias, disjoint_base\n\n_T = TypeVar(\"_T\")\n_TT = TypeVar(\"_TT\", bound=type[Any])\n_R = TypeVar(\"_R\")\n_F = TypeVar(\"_F\", bound=Callable[..., Any])\n_AF = TypeVar(\"_AF\", bound=Callable[..., Coroutine[Any, Any, Any]])\n_P = ParamSpec(\"_P\")\n\nif sys.version_info >= (3, 13):\n    # ThreadingMock added in 3.13\n    __all__ = (\n        \"Mock\",\n        \"MagicMock\",\n        \"patch\",\n        \"sentinel\",\n        \"DEFAULT\",\n        \"ANY\",\n        \"call\",\n        \"create_autospec\",\n        \"ThreadingMock\",\n        \"AsyncMock\",\n        \"FILTER_DIR\",\n        \"NonCallableMock\",\n        \"NonCallableMagicMock\",\n        \"mock_open\",\n        \"PropertyMock\",\n        \"seal\",\n    )\nelse:\n    __all__ = (\n        \"Mock\",\n        \"MagicMock\",\n        \"patch\",\n        \"sentinel\",\n        \"DEFAULT\",\n        \"ANY\",\n        \"call\",\n        \"create_autospec\",\n        \"AsyncMock\",\n        \"FILTER_DIR\",\n        \"NonCallableMock\",\n        \"NonCallableMagicMock\",\n        \"mock_open\",\n        \"PropertyMock\",\n        \"seal\",\n    )\n\nFILTER_DIR: bool  # controls the way mock objects respond to `dir` function\n\nclass _SentinelObject:\n    name: Any\n    def __init__(self, name: Any) -> None: ...\n\nclass _Sentinel:\n    def __getattr__(self, name: str) -> Any: ...\n\nsentinel: _Sentinel\nDEFAULT: Any\n\n_ArgsKwargs: TypeAlias = tuple[tuple[Any, ...], Mapping[str, Any]]\n_NameArgsKwargs: TypeAlias = tuple[str, tuple[Any, ...], Mapping[str, Any]]\n_CallValue: TypeAlias = str | tuple[Any, ...] | Mapping[str, Any] | _ArgsKwargs | _NameArgsKwargs\n\nif sys.version_info >= (3, 12):\n    class _Call(tuple[Any, ...]):\n        def __new__(\n            cls,\n            value: _CallValue = (),\n            name: str | None = \"\",\n            parent: _Call | None = None,\n            two: bool = False,\n            from_kall: bool = True,\n        ) -> Self: ...\n        def __init__(\n            self,\n            value: _CallValue = (),\n            name: str | None = None,\n            parent: _Call | None = None,\n            two: bool = False,\n            from_kall: bool = True,\n        ) -> None: ...\n        __hash__: ClassVar[None]  # type: ignore[assignment]\n        def __eq__(self, other: object) -> bool: ...\n        def __ne__(self, value: object, /) -> bool: ...\n        def __call__(self, *args: Any, **kwargs: Any) -> _Call: ...\n        def __getattr__(self, attr: str) -> Any: ...\n        def __getattribute__(self, attr: str) -> Any: ...\n        @property\n        def args(self) -> tuple[Any, ...]: ...\n        @property\n        def kwargs(self) -> Mapping[str, Any]: ...\n        def call_list(self) -> Any: ...\n\nelse:\n    @disjoint_base\n    class _Call(tuple[Any, ...]):\n        def __new__(\n            cls,\n            value: _CallValue = (),\n            name: str | None = \"\",\n            parent: _Call | None = None,\n            two: bool = False,\n            from_kall: bool = True,\n        ) -> Self: ...\n        def __init__(\n            self,\n            value: _CallValue = (),\n            name: str | None = None,\n            parent: _Call | None = None,\n            two: bool = False,\n            from_kall: bool = True,\n        ) -> None: ...\n        __hash__: ClassVar[None]  # type: ignore[assignment]\n        def __eq__(self, other: object) -> bool: ...\n        def __ne__(self, value: object, /) -> bool: ...\n        def __call__(self, *args: Any, **kwargs: Any) -> _Call: ...\n        def __getattr__(self, attr: str) -> Any: ...\n        def __getattribute__(self, attr: str) -> Any: ...\n        @property\n        def args(self) -> tuple[Any, ...]: ...\n        @property\n        def kwargs(self) -> Mapping[str, Any]: ...\n        def call_list(self) -> Any: ...\n\ncall: _Call\n\nclass _CallList(list[_Call]):\n    def __contains__(self, value: Any) -> bool: ...\n\nclass Base:\n    def __init__(self, *args: Any, **kwargs: Any) -> None: ...\n\n# We subclass with \"Any\" because mocks are explicitly designed to stand in for other types,\n# something that can't be expressed with our static type system.\nclass NonCallableMock(Base, Any):\n    if sys.version_info >= (3, 12):\n        def __new__(\n            cls,\n            spec: list[str] | object | type[object] | None = None,\n            wraps: Any | None = None,\n            name: str | None = None,\n            spec_set: list[str] | object | type[object] | None = None,\n            parent: NonCallableMock | None = None,\n            _spec_state: Any | None = None,\n            _new_name: str = \"\",\n            _new_parent: NonCallableMock | None = None,\n            _spec_as_instance: bool = False,\n            _eat_self: bool | None = None,\n            unsafe: bool = False,\n            **kwargs: Any,\n        ) -> Self: ...\n    else:\n        def __new__(cls, /, *args: Any, **kw: Any) -> Self: ...\n\n    def __init__(\n        self,\n        spec: list[str] | object | type[object] | None = None,\n        wraps: Any | None = None,\n        name: str | None = None,\n        spec_set: list[str] | object | type[object] | None = None,\n        parent: NonCallableMock | None = None,\n        _spec_state: Any | None = None,\n        _new_name: str = \"\",\n        _new_parent: NonCallableMock | None = None,\n        _spec_as_instance: bool = False,\n        _eat_self: bool | None = None,\n        unsafe: bool = False,\n        **kwargs: Any,\n    ) -> None: ...\n    def __getattr__(self, name: str) -> Any: ...\n    def __delattr__(self, name: str) -> None: ...\n    def __setattr__(self, name: str, value: Any) -> None: ...\n    def __dir__(self) -> list[str]: ...\n    def assert_called_with(self, *args: Any, **kwargs: Any) -> None: ...\n    def assert_not_called(self) -> None: ...\n    def assert_called_once_with(self, *args: Any, **kwargs: Any) -> None: ...\n    def _format_mock_failure_message(self, args: Any, kwargs: Any, action: str = \"call\") -> str: ...\n    def assert_called(self) -> None: ...\n    def assert_called_once(self) -> None: ...\n    def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ...\n    def _extract_mock_name(self) -> str: ...\n    def _get_call_signature_from_name(self, name: str) -> Any: ...\n    def assert_any_call(self, *args: Any, **kwargs: Any) -> None: ...\n    def assert_has_calls(self, calls: Sequence[_Call], any_order: bool = False) -> None: ...\n    def mock_add_spec(self, spec: Any, spec_set: bool = False) -> None: ...\n    def _mock_add_spec(self, spec: Any, spec_set: bool, _spec_as_instance: bool = False, _eat_self: bool = False) -> None: ...\n    def attach_mock(self, mock: NonCallableMock, attribute: str) -> None: ...\n    def configure_mock(self, **kwargs: Any) -> None: ...\n    return_value: Any\n    side_effect: Any\n    called: bool\n    call_count: int\n    call_args: _Call | MaybeNone\n    call_args_list: _CallList\n    method_calls: _CallList\n    mock_calls: _CallList\n    def _format_mock_call_signature(self, args: Any, kwargs: Any) -> str: ...\n    def _call_matcher(self, _call: tuple[_Call, ...]) -> _Call: ...\n    def _get_child_mock(self, **kw: Any) -> NonCallableMock: ...\n    if sys.version_info >= (3, 13):\n        def _calls_repr(self) -> str: ...\n    else:\n        def _calls_repr(self, prefix: str = \"Calls\") -> str: ...\n\nclass CallableMixin(Base):\n    side_effect: Any\n    def __init__(\n        self,\n        spec: Any | None = None,\n        side_effect: Any | None = None,\n        return_value: Any = ...,\n        wraps: Any | None = None,\n        name: Any | None = None,\n        spec_set: Any | None = None,\n        parent: Any | None = None,\n        _spec_state: Any | None = None,\n        _new_name: Any = \"\",\n        _new_parent: Any | None = None,\n        **kwargs: Any,\n    ) -> None: ...\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n\nclass Mock(CallableMixin, NonCallableMock): ...\n\nclass _patch(Generic[_T]):\n    attribute_name: Any\n    getter: Callable[[], Any]\n    attribute: str\n    new: _T\n    new_callable: Any\n    spec: Any\n    create: bool\n    has_local: Any\n    spec_set: Any\n    autospec: Any\n    kwargs: Mapping[str, Any]\n    additional_patchers: Any\n    # If new==DEFAULT, self is _patch[Any]. Ideally we'd be able to add an overload for it so that self is _patch[MagicMock],\n    # but that's impossible with the current type system.\n    if sys.version_info >= (3, 10):\n        def __init__(\n            self: _patch[_T],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n            getter: Callable[[], Any],\n            attribute: str,\n            new: _T,\n            spec: Any | None,\n            create: bool,\n            spec_set: Any | None,\n            autospec: Any | None,\n            new_callable: Any | None,\n            kwargs: Mapping[str, Any],\n            *,\n            unsafe: bool = False,\n        ) -> None: ...\n    else:\n        def __init__(\n            self: _patch[_T],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n            getter: Callable[[], Any],\n            attribute: str,\n            new: _T,\n            spec: Any | None,\n            create: bool,\n            spec_set: Any | None,\n            autospec: Any | None,\n            new_callable: Any | None,\n            kwargs: Mapping[str, Any],\n        ) -> None: ...\n\n    def copy(self) -> _patch[_T]: ...\n    @overload\n    def __call__(self, func: _TT) -> _TT: ...\n    # If new==DEFAULT, this should add a MagicMock parameter to the function\n    # arguments. See the _patch_default_new class below for this functionality.\n    @overload\n    def __call__(self, func: Callable[_P, _R]) -> Callable[_P, _R]: ...\n    def decoration_helper(\n        self, patched: _patch[Any], args: Sequence[Any], keywargs: Any\n    ) -> _GeneratorContextManager[tuple[Sequence[Any], Any]]: ...\n    def decorate_class(self, klass: _TT) -> _TT: ...\n    def decorate_callable(self, func: Callable[..., _R]) -> Callable[..., _R]: ...\n    def decorate_async_callable(self, func: Callable[..., Awaitable[_R]]) -> Callable[..., Awaitable[_R]]: ...\n    def get_original(self) -> tuple[Any, bool]: ...\n    target: Any\n    temp_original: Any\n    is_local: bool\n    def __enter__(self) -> _T: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /\n    ) -> None: ...\n    def start(self) -> _T: ...\n    def stop(self) -> None: ...\n\n# This class does not exist at runtime, it's a hack to make this work:\n#     @patch(\"foo\")\n#     def bar(..., mock: MagicMock) -> None: ...\n@type_check_only\nclass _patch_pass_arg(_patch[_T]):\n    @overload\n    def __call__(self, func: _TT) -> _TT: ...\n    # Can't use the following as ParamSpec is only allowed as last parameter:\n    #   def __call__(self, func: Callable[_P, _R]) -> Callable[Concatenate[_P, MagicMock], _R]: ...\n    @overload\n    def __call__(self, func: Callable[..., _R]) -> Callable[..., _R]: ...\n\nclass _patch_dict:\n    in_dict: Any\n    values: Any\n    clear: Any\n    def __init__(self, in_dict: Any, values: Any = (), clear: Any = False, **kwargs: Any) -> None: ...\n    def __call__(self, f: Any) -> Any: ...\n    if sys.version_info >= (3, 10):\n        def decorate_callable(self, f: _F) -> _F: ...\n        def decorate_async_callable(self, f: _AF) -> _AF: ...\n\n    def decorate_class(self, klass: Any) -> Any: ...\n    def __enter__(self) -> Any: ...\n    def __exit__(self, *args: object) -> Any: ...\n    start: Any\n    stop: Any\n\n# This class does not exist at runtime, it's a hack to add methods to the\n# patch() function.\n@type_check_only\nclass _patcher:\n    TEST_PREFIX: str\n    dict: type[_patch_dict]\n    # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any].\n    # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock],\n    # but that's impossible with the current type system.\n    @overload\n    def __call__(  # type: ignore[overload-overlap]\n        self,\n        target: str,\n        new: _T,\n        spec: Literal[False] | None = None,\n        create: bool = False,\n        spec_set: Literal[False] | None = None,\n        autospec: Literal[False] | None = None,\n        new_callable: None = None,\n        *,\n        unsafe: bool = False,\n    ) -> _patch[_T]: ...\n    @overload\n    def __call__(\n        self,\n        target: str,\n        *,\n        # If not False or None, this is passed to new_callable\n        spec: Any | Literal[False] | None = None,\n        create: bool = False,\n        # If not False or None, this is passed to new_callable\n        spec_set: Any | Literal[False] | None = None,\n        autospec: Literal[False] | None = None,\n        new_callable: Callable[..., _T],\n        unsafe: bool = False,\n        # kwargs are passed to new_callable\n        **kwargs: Any,\n    ) -> _patch_pass_arg[_T]: ...\n    @overload\n    def __call__(\n        self,\n        target: str,\n        *,\n        spec: Any | bool | None = None,\n        create: bool = False,\n        spec_set: Any | bool | None = None,\n        autospec: Any | bool | None = None,\n        new_callable: None = None,\n        unsafe: bool = False,\n        # kwargs are passed to the MagicMock/AsyncMock constructor\n        **kwargs: Any,\n    ) -> _patch_pass_arg[MagicMock | AsyncMock]: ...\n    # This overload also covers the case, where new==DEFAULT. In this case, the return type is _patch[Any].\n    # Ideally we'd be able to add an overload for it so that the return type is _patch[MagicMock],\n    # but that's impossible with the current type system.\n    @overload\n    @staticmethod\n    def object(\n        target: Any,\n        attribute: str,\n        new: _T,\n        spec: Literal[False] | None = None,\n        create: bool = False,\n        spec_set: Literal[False] | None = None,\n        autospec: Literal[False] | None = None,\n        new_callable: None = None,\n        *,\n        unsafe: bool = False,\n    ) -> _patch[_T]: ...\n    @overload\n    @staticmethod\n    def object(\n        target: Any,\n        attribute: str,\n        *,\n        # If not False or None, this is passed to new_callable\n        spec: Any | Literal[False] | None = None,\n        create: bool = False,\n        # If not False or None, this is passed to new_callable\n        spec_set: Any | Literal[False] | None = None,\n        autospec: Literal[False] | None = None,\n        new_callable: Callable[..., _T],\n        unsafe: bool = False,\n        # kwargs are passed to new_callable\n        **kwargs: Any,\n    ) -> _patch_pass_arg[_T]: ...\n    @overload\n    @staticmethod\n    def object(\n        target: Any,\n        attribute: str,\n        *,\n        spec: Any | bool | None = None,\n        create: bool = False,\n        spec_set: Any | bool | None = None,\n        autospec: Any | bool | None = None,\n        new_callable: None = None,\n        unsafe: bool = False,\n        # kwargs are passed to the MagicMock/AsyncMock constructor\n        **kwargs: Any,\n    ) -> _patch_pass_arg[MagicMock | AsyncMock]: ...\n    @overload\n    @staticmethod\n    def multiple(\n        target: Any | str,\n        # If not False or None, this is passed to new_callable\n        spec: Any | Literal[False] | None = None,\n        create: bool = False,\n        # If not False or None, this is passed to new_callable\n        spec_set: Any | Literal[False] | None = None,\n        autospec: Literal[False] | None = None,\n        *,\n        new_callable: Callable[..., _T],\n        # The kwargs must be DEFAULT\n        **kwargs: Any,\n    ) -> _patch_pass_arg[_T]: ...\n    @overload\n    @staticmethod\n    def multiple(\n        target: Any | str,\n        # If not False or None, this is passed to new_callable\n        spec: Any | Literal[False] | None,\n        create: bool,\n        # If not False or None, this is passed to new_callable\n        spec_set: Any | Literal[False] | None,\n        autospec: Literal[False] | None,\n        new_callable: Callable[..., _T],\n        # The kwargs must be DEFAULT\n        **kwargs: Any,\n    ) -> _patch_pass_arg[_T]: ...\n    @overload\n    @staticmethod\n    def multiple(\n        target: Any | str,\n        spec: Any | bool | None = None,\n        create: bool = False,\n        spec_set: Any | bool | None = None,\n        autospec: Any | bool | None = None,\n        new_callable: None = None,\n        # The kwargs are the mock objects or DEFAULT\n        **kwargs: Any,\n    ) -> _patch[Any]: ...\n    @staticmethod\n    def stopall() -> None: ...\n\npatch: _patcher\n\nclass MagicMixin(Base):\n    def __init__(self, *args: Any, **kw: Any) -> None: ...\n\nclass NonCallableMagicMock(MagicMixin, NonCallableMock): ...\nclass MagicMock(MagicMixin, Mock): ...\n\nclass AsyncMockMixin(Base):\n    def __init__(self, *args: Any, **kwargs: Any) -> None: ...\n    async def _execute_mock_call(self, *args: Any, **kwargs: Any) -> Any: ...\n    def assert_awaited(self) -> None: ...\n    def assert_awaited_once(self) -> None: ...\n    def assert_awaited_with(self, *args: Any, **kwargs: Any) -> None: ...\n    def assert_awaited_once_with(self, *args: Any, **kwargs: Any) -> None: ...\n    def assert_any_await(self, *args: Any, **kwargs: Any) -> None: ...\n    def assert_has_awaits(self, calls: Iterable[_Call], any_order: bool = False) -> None: ...\n    def assert_not_awaited(self) -> None: ...\n    def reset_mock(self, *args: Any, **kwargs: Any) -> None: ...\n    await_count: int\n    await_args: _Call | None\n    await_args_list: _CallList\n\nclass AsyncMagicMixin(MagicMixin):\n    def __init__(self, *args: Any, **kw: Any) -> None: ...\n\nclass AsyncMock(AsyncMockMixin, AsyncMagicMixin, Mock):\n    # Improving the `reset_mock` signature.\n    # It is defined on `AsyncMockMixin` with `*args, **kwargs`, which is not ideal.\n    # But, `NonCallableMock` super-class has the better version.\n    def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ...\n\nclass MagicProxy(Base):\n    name: str\n    parent: Any\n    def __init__(self, name: str, parent: Any) -> None: ...\n    def create_mock(self) -> Any: ...\n    def __get__(self, obj: Any, _type: Any | None = None) -> Any: ...\n\n# See https://github.com/python/typeshed/issues/14701\nclass _ANY(Any):\n    def __eq__(self, other: object) -> Literal[True]: ...\n    def __ne__(self, other: object) -> Literal[False]: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\nANY: _ANY\n\nif sys.version_info >= (3, 10):\n    def create_autospec(\n        spec: Any,\n        spec_set: Any = False,\n        instance: Any = False,\n        _parent: Any | None = None,\n        _name: Any | None = None,\n        *,\n        unsafe: bool = False,\n        **kwargs: Any,\n    ) -> Any: ...\n\nelse:\n    def create_autospec(\n        spec: Any,\n        spec_set: Any = False,\n        instance: Any = False,\n        _parent: Any | None = None,\n        _name: Any | None = None,\n        **kwargs: Any,\n    ) -> Any: ...\n\nclass _SpecState:\n    spec: Any\n    ids: Any\n    spec_set: Any\n    parent: Any\n    instance: Any\n    name: Any\n    def __init__(\n        self,\n        spec: Any,\n        spec_set: Any = False,\n        parent: Any | None = None,\n        name: Any | None = None,\n        ids: Any | None = None,\n        instance: Any = False,\n    ) -> None: ...\n\ndef mock_open(mock: Any | None = None, read_data: Any = \"\") -> Any: ...\n\nclass PropertyMock(Mock):\n    def __get__(self, obj: _T, obj_type: type[_T] | None = None) -> Self: ...\n    def __set__(self, obj: Any, val: Any) -> None: ...\n\nif sys.version_info >= (3, 13):\n    class ThreadingMixin(Base):\n        DEFAULT_TIMEOUT: Final[float | None] = None\n\n        def __init__(self, /, *args: Any, timeout: float | None | _SentinelObject = ..., **kwargs: Any) -> None: ...\n        # Same as `NonCallableMock.reset_mock.`\n        def reset_mock(self, visited: Any = None, *, return_value: bool = False, side_effect: bool = False) -> None: ...\n        def wait_until_called(self, *, timeout: float | None | _SentinelObject = ...) -> None: ...\n        def wait_until_any_call_with(self, *args: Any, **kwargs: Any) -> None: ...\n\n    class ThreadingMock(ThreadingMixin, MagicMixin, Mock): ...\n\ndef seal(mock: Any) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/result.pyi",
    "content": "import sys\nimport unittest.case\nfrom _typeshed import OptExcInfo\nfrom collections.abc import Callable\nfrom typing import Any, Final, TextIO, TypeVar\nfrom typing_extensions import TypeAlias\n\n_F = TypeVar(\"_F\", bound=Callable[..., Any])\n_DurationsType: TypeAlias = list[tuple[str, float]]\n\nSTDOUT_LINE: Final[str]\nSTDERR_LINE: Final[str]\n\n# undocumented\ndef failfast(method: _F) -> _F: ...\n\nclass TestResult:\n    errors: list[tuple[unittest.case.TestCase, str]]\n    failures: list[tuple[unittest.case.TestCase, str]]\n    skipped: list[tuple[unittest.case.TestCase, str]]\n    expectedFailures: list[tuple[unittest.case.TestCase, str]]\n    unexpectedSuccesses: list[unittest.case.TestCase]\n    shouldStop: bool\n    testsRun: int\n    buffer: bool\n    failfast: bool\n    tb_locals: bool\n    if sys.version_info >= (3, 12):\n        collectedDurations: _DurationsType\n\n    def __init__(self, stream: TextIO | None = None, descriptions: bool | None = None, verbosity: int | None = None) -> None: ...\n    def printErrors(self) -> None: ...\n    def wasSuccessful(self) -> bool: ...\n    def stop(self) -> None: ...\n    def startTest(self, test: unittest.case.TestCase) -> None: ...\n    def stopTest(self, test: unittest.case.TestCase) -> None: ...\n    def startTestRun(self) -> None: ...\n    def stopTestRun(self) -> None: ...\n    def addError(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ...\n    def addFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ...\n    def addSuccess(self, test: unittest.case.TestCase) -> None: ...\n    def addSkip(self, test: unittest.case.TestCase, reason: str) -> None: ...\n    def addExpectedFailure(self, test: unittest.case.TestCase, err: OptExcInfo) -> None: ...\n    def addUnexpectedSuccess(self, test: unittest.case.TestCase) -> None: ...\n    def addSubTest(self, test: unittest.case.TestCase, subtest: unittest.case.TestCase, err: OptExcInfo | None) -> None: ...\n    if sys.version_info >= (3, 12):\n        def addDuration(self, test: unittest.case.TestCase, elapsed: float) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/runner.pyi",
    "content": "import sys\nimport unittest.case\nimport unittest.result\nimport unittest.suite\nfrom _typeshed import SupportsFlush, SupportsWrite\nfrom collections.abc import Callable, Iterable\nfrom typing import Any, Generic, Protocol, TypeVar, type_check_only\nfrom typing_extensions import Never, TypeAlias\nfrom warnings import _ActionKind\n\n_ResultClassType: TypeAlias = Callable[[_TextTestStream, bool, int], TextTestResult[Any]]\n\n@type_check_only\nclass _SupportsWriteAndFlush(SupportsWrite[str], SupportsFlush, Protocol): ...\n\n# All methods used by unittest.runner.TextTestResult's stream\n@type_check_only\nclass _TextTestStream(_SupportsWriteAndFlush, Protocol):\n    def writeln(self, arg: str | None = None, /) -> None: ...\n\n# _WritelnDecorator should have all the same attrs as its stream param.\n# But that's not feasible to do Generically\n# We can expand the attributes if requested\nclass _WritelnDecorator:\n    def __init__(self, stream: _SupportsWriteAndFlush) -> None: ...\n    def writeln(self, arg: str | None = None) -> None: ...\n    def __getattr__(self, attr: str) -> Any: ...  # Any attribute from the stream type passed to __init__\n    # These attributes are prevented by __getattr__\n    stream: Never\n    __getstate__: Never\n    # Methods proxied from the wrapped stream object via __getattr__\n    def flush(self) -> object: ...\n    def write(self, s: str, /) -> object: ...\n\n_StreamT = TypeVar(\"_StreamT\", bound=_TextTestStream, default=_WritelnDecorator)\n\nclass TextTestResult(unittest.result.TestResult, Generic[_StreamT]):\n    descriptions: bool  # undocumented\n    dots: bool  # undocumented\n    separator1: str\n    separator2: str\n    showAll: bool  # undocumented\n    stream: _StreamT  # undocumented\n    if sys.version_info >= (3, 12):\n        durations: int | None\n        def __init__(self, stream: _StreamT, descriptions: bool, verbosity: int, *, durations: int | None = None) -> None: ...\n    else:\n        def __init__(self, stream: _StreamT, descriptions: bool, verbosity: int) -> None: ...\n\n    def getDescription(self, test: unittest.case.TestCase) -> str: ...\n    def printErrorList(self, flavour: str, errors: Iterable[tuple[unittest.case.TestCase, str]]) -> None: ...\n\nclass TextTestRunner:\n    resultclass: _ResultClassType\n    stream: _WritelnDecorator\n    descriptions: bool\n    verbosity: int\n    failfast: bool\n    buffer: bool\n    warnings: _ActionKind | None\n    tb_locals: bool\n\n    if sys.version_info >= (3, 12):\n        durations: int | None\n        def __init__(\n            self,\n            stream: _SupportsWriteAndFlush | None = None,\n            descriptions: bool = True,\n            verbosity: int = 1,\n            failfast: bool = False,\n            buffer: bool = False,\n            resultclass: _ResultClassType | None = None,\n            warnings: _ActionKind | None = None,\n            *,\n            tb_locals: bool = False,\n            durations: int | None = None,\n        ) -> None: ...\n    else:\n        def __init__(\n            self,\n            stream: _SupportsWriteAndFlush | None = None,\n            descriptions: bool = True,\n            verbosity: int = 1,\n            failfast: bool = False,\n            buffer: bool = False,\n            resultclass: _ResultClassType | None = None,\n            warnings: str | None = None,\n            *,\n            tb_locals: bool = False,\n        ) -> None: ...\n\n    def _makeResult(self) -> TextTestResult: ...\n    def run(self, test: unittest.suite.TestSuite | unittest.case.TestCase) -> TextTestResult: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/signals.pyi",
    "content": "import unittest.result\nfrom collections.abc import Callable\nfrom typing import TypeVar, overload\nfrom typing_extensions import ParamSpec\n\n_P = ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\n\ndef installHandler() -> None: ...\ndef registerResult(result: unittest.result.TestResult) -> None: ...\ndef removeResult(result: unittest.result.TestResult) -> bool: ...\n@overload\ndef removeHandler(method: None = None) -> None: ...\n@overload\ndef removeHandler(method: Callable[_P, _T]) -> Callable[_P, _T]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/suite.pyi",
    "content": "import unittest.case\nimport unittest.result\nfrom collections.abc import Iterable, Iterator\nfrom typing import ClassVar\nfrom typing_extensions import TypeAlias\n\n_TestType: TypeAlias = unittest.case.TestCase | TestSuite\n\nclass BaseTestSuite:\n    _tests: list[unittest.case.TestCase]\n    _removed_tests: int\n    def __init__(self, tests: Iterable[_TestType] = ()) -> None: ...\n    def __call__(self, result: unittest.result.TestResult) -> unittest.result.TestResult: ...\n    def addTest(self, test: _TestType) -> None: ...\n    def addTests(self, tests: Iterable[_TestType]) -> None: ...\n    def run(self, result: unittest.result.TestResult) -> unittest.result.TestResult: ...\n    def debug(self) -> None: ...\n    def countTestCases(self) -> int: ...\n    def __iter__(self) -> Iterator[_TestType]: ...\n    def __eq__(self, other: object) -> bool: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\nclass TestSuite(BaseTestSuite):\n    def run(self, result: unittest.result.TestResult, debug: bool = False) -> unittest.result.TestResult: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/unittest/util.pyi",
    "content": "from collections.abc import MutableSequence, Sequence\nfrom typing import Any, Final, Literal, Protocol, TypeVar, type_check_only\nfrom typing_extensions import TypeAlias\n\n@type_check_only\nclass _SupportsDunderLT(Protocol):\n    def __lt__(self, other: Any, /) -> bool: ...\n\n@type_check_only\nclass _SupportsDunderGT(Protocol):\n    def __gt__(self, other: Any, /) -> bool: ...\n\n@type_check_only\nclass _SupportsDunderLE(Protocol):\n    def __le__(self, other: Any, /) -> bool: ...\n\n@type_check_only\nclass _SupportsDunderGE(Protocol):\n    def __ge__(self, other: Any, /) -> bool: ...\n\n_T = TypeVar(\"_T\")\n_Mismatch: TypeAlias = tuple[_T, _T, int]\n_SupportsComparison: TypeAlias = _SupportsDunderLE | _SupportsDunderGE | _SupportsDunderGT | _SupportsDunderLT\n\n_MAX_LENGTH: Final = 80\n_PLACEHOLDER_LEN: Final = 12\n_MIN_BEGIN_LEN: Final = 5\n_MIN_END_LEN: Final = 5\n_MIN_COMMON_LEN: Final = 5\n_MIN_DIFF_LEN: Final = 41\n\ndef _shorten(s: str, prefixlen: int, suffixlen: int) -> str: ...\ndef _common_shorten_repr(*args: str) -> tuple[str, ...]: ...\ndef safe_repr(obj: object, short: bool = False) -> str: ...\ndef strclass(cls: type) -> str: ...\ndef sorted_list_difference(expected: Sequence[_T], actual: Sequence[_T]) -> tuple[list[_T], list[_T]]: ...\ndef unorderable_list_difference(expected: MutableSequence[_T], actual: MutableSequence[_T]) -> tuple[list[_T], list[_T]]: ...\ndef three_way_cmp(x: _SupportsComparison, y: _SupportsComparison) -> Literal[-1, 0, 1]: ...\ndef _count_diff_all_purpose(actual: Sequence[_T], expected: Sequence[_T]) -> list[_Mismatch[_T]]: ...\ndef _count_diff_hashable(actual: Sequence[_T], expected: Sequence[_T]) -> list[_Mismatch[_T]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/urllib/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/urllib/error.pyi",
    "content": "from email.message import Message\nfrom typing import IO\nfrom urllib.response import addinfourl\n\n__all__ = [\"URLError\", \"HTTPError\", \"ContentTooShortError\"]\n\nclass URLError(OSError):\n    reason: str | BaseException\n    # The `filename` attribute only exists if it was provided to `__init__` and wasn't `None`.\n    filename: str\n    def __init__(self, reason: str | BaseException, filename: str | None = None) -> None: ...\n\nclass HTTPError(URLError, addinfourl):\n    @property\n    def headers(self) -> Message: ...\n    @headers.setter\n    def headers(self, headers: Message) -> None: ...\n    @property\n    def reason(self) -> str: ...  # type: ignore[override]\n    code: int\n    msg: str\n    hdrs: Message\n    fp: IO[bytes]\n    def __init__(self, url: str, code: int, msg: str, hdrs: Message, fp: IO[bytes] | None) -> None: ...\n\nclass ContentTooShortError(URLError):\n    content: tuple[str, Message]\n    def __init__(self, message: str, content: tuple[str, Message]) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/urllib/parse.pyi",
    "content": "import sys\nfrom collections.abc import Iterable, Mapping, Sequence\nfrom types import GenericAlias\nfrom typing import Any, AnyStr, Final, Generic, Literal, NamedTuple, Protocol, overload, type_check_only\nfrom typing_extensions import TypeAlias\n\n__all__ = [\n    \"urlparse\",\n    \"urlunparse\",\n    \"urljoin\",\n    \"urldefrag\",\n    \"urlsplit\",\n    \"urlunsplit\",\n    \"urlencode\",\n    \"parse_qs\",\n    \"parse_qsl\",\n    \"quote\",\n    \"quote_plus\",\n    \"quote_from_bytes\",\n    \"unquote\",\n    \"unquote_plus\",\n    \"unquote_to_bytes\",\n    \"DefragResult\",\n    \"ParseResult\",\n    \"SplitResult\",\n    \"DefragResultBytes\",\n    \"ParseResultBytes\",\n    \"SplitResultBytes\",\n]\n\nuses_relative: Final[list[str]]\nuses_netloc: Final[list[str]]\nuses_params: Final[list[str]]\nnon_hierarchical: Final[list[str]]\nuses_query: Final[list[str]]\nuses_fragment: Final[list[str]]\nscheme_chars: Final[str]\nif sys.version_info < (3, 11):\n    MAX_CACHE_SIZE: Final[int]\n\nclass _ResultMixinStr:\n    __slots__ = ()\n    def encode(self, encoding: str = \"ascii\", errors: str = \"strict\") -> _ResultMixinBytes: ...\n\nclass _ResultMixinBytes:\n    __slots__ = ()\n    def decode(self, encoding: str = \"ascii\", errors: str = \"strict\") -> _ResultMixinStr: ...\n\nclass _NetlocResultMixinBase(Generic[AnyStr]):\n    __slots__ = ()\n    @property\n    def username(self) -> AnyStr | None: ...\n    @property\n    def password(self) -> AnyStr | None: ...\n    @property\n    def hostname(self) -> AnyStr | None: ...\n    @property\n    def port(self) -> int | None: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nclass _NetlocResultMixinStr(_NetlocResultMixinBase[str], _ResultMixinStr):\n    __slots__ = ()\n\nclass _NetlocResultMixinBytes(_NetlocResultMixinBase[bytes], _ResultMixinBytes):\n    __slots__ = ()\n\nclass _DefragResultBase(NamedTuple, Generic[AnyStr]):\n    url: AnyStr\n    fragment: AnyStr\n\nclass _SplitResultBase(NamedTuple, Generic[AnyStr]):\n    scheme: AnyStr\n    netloc: AnyStr\n    path: AnyStr\n    query: AnyStr\n    fragment: AnyStr\n\nclass _ParseResultBase(NamedTuple, Generic[AnyStr]):\n    scheme: AnyStr\n    netloc: AnyStr\n    path: AnyStr\n    params: AnyStr\n    query: AnyStr\n    fragment: AnyStr\n\n# Structured result objects for string data\nclass DefragResult(_DefragResultBase[str], _ResultMixinStr):\n    def geturl(self) -> str: ...\n\nclass SplitResult(_SplitResultBase[str], _NetlocResultMixinStr):\n    def geturl(self) -> str: ...\n\nclass ParseResult(_ParseResultBase[str], _NetlocResultMixinStr):\n    def geturl(self) -> str: ...\n\n# Structured result objects for bytes data\nclass DefragResultBytes(_DefragResultBase[bytes], _ResultMixinBytes):\n    def geturl(self) -> bytes: ...\n\nclass SplitResultBytes(_SplitResultBase[bytes], _NetlocResultMixinBytes):\n    def geturl(self) -> bytes: ...\n\nclass ParseResultBytes(_ParseResultBase[bytes], _NetlocResultMixinBytes):\n    def geturl(self) -> bytes: ...\n\ndef parse_qs(\n    qs: AnyStr | None,\n    keep_blank_values: bool = False,\n    strict_parsing: bool = False,\n    encoding: str = \"utf-8\",\n    errors: str = \"replace\",\n    max_num_fields: int | None = None,\n    separator: str = \"&\",\n) -> dict[AnyStr, list[AnyStr]]: ...\ndef parse_qsl(\n    qs: AnyStr | None,\n    keep_blank_values: bool = False,\n    strict_parsing: bool = False,\n    encoding: str = \"utf-8\",\n    errors: str = \"replace\",\n    max_num_fields: int | None = None,\n    separator: str = \"&\",\n) -> list[tuple[AnyStr, AnyStr]]: ...\n@overload\ndef quote(string: str, safe: str | Iterable[int] = \"/\", encoding: str | None = None, errors: str | None = None) -> str: ...\n@overload\ndef quote(string: bytes | bytearray, safe: str | Iterable[int] = \"/\") -> str: ...\ndef quote_from_bytes(bs: bytes | bytearray, safe: str | Iterable[int] = \"/\") -> str: ...\n@overload\ndef quote_plus(string: str, safe: str | Iterable[int] = \"\", encoding: str | None = None, errors: str | None = None) -> str: ...\n@overload\ndef quote_plus(string: bytes | bytearray, safe: str | Iterable[int] = \"\") -> str: ...\ndef unquote(string: str | bytes, encoding: str = \"utf-8\", errors: str = \"replace\") -> str: ...\ndef unquote_to_bytes(string: str | bytes | bytearray) -> bytes: ...\ndef unquote_plus(string: str, encoding: str = \"utf-8\", errors: str = \"replace\") -> str: ...\n@overload\ndef urldefrag(url: str) -> DefragResult: ...\n@overload\ndef urldefrag(url: bytes | bytearray | None) -> DefragResultBytes: ...\n\n# The values are passed through `str()` (unless they are bytes), so anything is valid.\n_QueryType: TypeAlias = (\n    Mapping[str, object]\n    | Mapping[bytes, object]\n    | Mapping[str | bytes, object]\n    | Mapping[str, Sequence[object]]\n    | Mapping[bytes, Sequence[object]]\n    | Mapping[str | bytes, Sequence[object]]\n    | Sequence[tuple[str | bytes, object]]\n    | Sequence[tuple[str | bytes, Sequence[object]]]\n)\n\n@type_check_only\nclass _QuoteVia(Protocol):\n    @overload\n    def __call__(self, string: str, safe: str | bytes, encoding: str, errors: str, /) -> str: ...\n    @overload\n    def __call__(self, string: bytes, safe: str | bytes, /) -> str: ...\n\ndef urlencode(\n    query: _QueryType,\n    doseq: bool = False,\n    safe: str | bytes = \"\",\n    encoding: str | None = None,\n    errors: str | None = None,\n    quote_via: _QuoteVia = ...,\n) -> str: ...\ndef urljoin(base: AnyStr, url: AnyStr | None, allow_fragments: bool = True) -> AnyStr: ...\n@overload\ndef urlparse(url: str, scheme: str = \"\", allow_fragments: bool = True) -> ParseResult: ...\n@overload\ndef urlparse(\n    url: bytes | bytearray | None, scheme: bytes | bytearray | None | Literal[\"\"] = \"\", allow_fragments: bool = True\n) -> ParseResultBytes: ...\n@overload\ndef urlsplit(url: str, scheme: str = \"\", allow_fragments: bool = True) -> SplitResult: ...\n\nif sys.version_info >= (3, 11):\n    @overload\n    def urlsplit(\n        url: bytes | None, scheme: bytes | None | Literal[\"\"] = \"\", allow_fragments: bool = True\n    ) -> SplitResultBytes: ...\n\nelse:\n    @overload\n    def urlsplit(\n        url: bytes | bytearray | None, scheme: bytes | bytearray | None | Literal[\"\"] = \"\", allow_fragments: bool = True\n    ) -> SplitResultBytes: ...\n\n# Requires an iterable of length 6\n@overload\ndef urlunparse(components: Iterable[None]) -> Literal[b\"\"]: ...  # type: ignore[overload-overlap]\n@overload\ndef urlunparse(components: Iterable[AnyStr | None]) -> AnyStr: ...\n\n# Requires an iterable of length 5\n@overload\ndef urlunsplit(components: Iterable[None]) -> Literal[b\"\"]: ...  # type: ignore[overload-overlap]\n@overload\ndef urlunsplit(components: Iterable[AnyStr | None]) -> AnyStr: ...\ndef unwrap(url: str) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/urllib/request.pyi",
    "content": "import ssl\nimport sys\nfrom _typeshed import ReadableBuffer, StrOrBytesPath, SupportsRead\nfrom collections.abc import Callable, Iterable, Mapping, MutableMapping, Sequence\nfrom email.message import Message\nfrom http.client import HTTPConnection, HTTPMessage, HTTPResponse\nfrom http.cookiejar import CookieJar\nfrom re import Pattern\nfrom typing import IO, Any, ClassVar, Literal, NoReturn, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import TypeAlias, deprecated\nfrom urllib.error import HTTPError as HTTPError\nfrom urllib.response import addclosehook, addinfourl\n\n__all__ = [\n    \"Request\",\n    \"OpenerDirector\",\n    \"BaseHandler\",\n    \"HTTPDefaultErrorHandler\",\n    \"HTTPRedirectHandler\",\n    \"HTTPCookieProcessor\",\n    \"ProxyHandler\",\n    \"HTTPPasswordMgr\",\n    \"HTTPPasswordMgrWithDefaultRealm\",\n    \"HTTPPasswordMgrWithPriorAuth\",\n    \"AbstractBasicAuthHandler\",\n    \"HTTPBasicAuthHandler\",\n    \"ProxyBasicAuthHandler\",\n    \"AbstractDigestAuthHandler\",\n    \"HTTPDigestAuthHandler\",\n    \"ProxyDigestAuthHandler\",\n    \"HTTPHandler\",\n    \"FileHandler\",\n    \"FTPHandler\",\n    \"CacheFTPHandler\",\n    \"DataHandler\",\n    \"UnknownHandler\",\n    \"HTTPErrorProcessor\",\n    \"urlopen\",\n    \"install_opener\",\n    \"build_opener\",\n    \"pathname2url\",\n    \"url2pathname\",\n    \"getproxies\",\n    \"urlretrieve\",\n    \"urlcleanup\",\n    \"HTTPSHandler\",\n]\nif sys.version_info < (3, 14):\n    __all__ += [\"URLopener\", \"FancyURLopener\"]\n\n_T = TypeVar(\"_T\")\n\n# The actual type is `addinfourl | HTTPResponse`, but users would need to use `typing.cast` or `isinstance` to narrow the type,\n# so we use `Any` instead.\n# See\n# - https://github.com/python/typeshed/pull/15042\n# - https://github.com/python/typing/issues/566\n_UrlopenRet: TypeAlias = Any\n\n_DataType: TypeAlias = ReadableBuffer | SupportsRead[bytes] | Iterable[bytes] | None\n\nif sys.version_info >= (3, 13):\n    def urlopen(\n        url: str | Request, data: _DataType | None = None, timeout: float | None = ..., *, context: ssl.SSLContext | None = None\n    ) -> _UrlopenRet: ...\n\nelse:\n    @overload\n    def urlopen(\n        url: str | Request,\n        data: _DataType | None = None,\n        timeout: float | None = ...,\n        *,\n        cafile: None = None,\n        capath: None = None,\n        cadefault: Literal[False] = False,\n        context: ssl.SSLContext | None = None,\n    ) -> _UrlopenRet: ...\n    @overload\n    @deprecated(\n        \"The `cafile`, `capath`, `cadefault` parameters are deprecated since Python 3.6; \"\n        \"removed in Python 3.13. Use `context` parameter instead.\"\n    )\n    def urlopen(\n        url: str | Request,\n        data: _DataType | None = None,\n        timeout: float | None = ...,\n        *,\n        cafile: StrOrBytesPath | None = None,\n        capath: StrOrBytesPath | None = None,\n        cadefault: bool = False,\n        context: None = None,\n    ) -> _UrlopenRet: ...\n\ndef install_opener(opener: OpenerDirector) -> None: ...\ndef build_opener(*handlers: BaseHandler | Callable[[], BaseHandler]) -> OpenerDirector: ...\n\nif sys.version_info >= (3, 14):\n    def url2pathname(url: str, *, require_scheme: bool = False, resolve_host: bool = False) -> str: ...\n    def pathname2url(pathname: str, *, add_scheme: bool = False) -> str: ...\n\nelse:\n    if sys.platform == \"win32\":\n        from nturl2path import pathname2url as pathname2url, url2pathname as url2pathname\n    else:\n        def url2pathname(pathname: str) -> str: ...\n        def pathname2url(pathname: str) -> str: ...\n\ndef getproxies() -> dict[str, str]: ...\ndef getproxies_environment() -> dict[str, str]: ...\ndef parse_http_list(s: str) -> list[str]: ...\ndef parse_keqv_list(l: list[str]) -> dict[str, str]: ...\n\nif sys.platform == \"win32\" or sys.platform == \"darwin\":\n    def proxy_bypass(host: str) -> Any: ...  # undocumented\n\nelse:\n    def proxy_bypass(host: str, proxies: Mapping[str, str] | None = None) -> Any: ...  # undocumented\n\nclass Request:\n    @property\n    def full_url(self) -> str: ...\n    @full_url.setter\n    def full_url(self, value: str) -> None: ...\n    @full_url.deleter\n    def full_url(self) -> None: ...\n    type: str\n    host: str\n    origin_req_host: str\n    selector: str\n    data: _DataType\n    headers: MutableMapping[str, str]\n    unredirected_hdrs: dict[str, str]\n    unverifiable: bool\n    method: str | None\n    timeout: float | None  # Undocumented, only set after __init__() by OpenerDirector.open()\n    def __init__(\n        self,\n        url: str,\n        data: _DataType = None,\n        headers: MutableMapping[str, str] = {},\n        origin_req_host: str | None = None,\n        unverifiable: bool = False,\n        method: str | None = None,\n    ) -> None: ...\n    def get_method(self) -> str: ...\n    def add_header(self, key: str, val: str) -> None: ...\n    def add_unredirected_header(self, key: str, val: str) -> None: ...\n    def has_header(self, header_name: str) -> bool: ...\n    def remove_header(self, header_name: str) -> None: ...\n    def get_full_url(self) -> str: ...\n    def set_proxy(self, host: str, type: str) -> None: ...\n    @overload\n    def get_header(self, header_name: str) -> str | None: ...\n    @overload\n    def get_header(self, header_name: str, default: _T) -> str | _T: ...\n    def header_items(self) -> list[tuple[str, str]]: ...\n    def has_proxy(self) -> bool: ...\n\nclass OpenerDirector:\n    addheaders: list[tuple[str, str]]\n    def add_handler(self, handler: BaseHandler) -> None: ...\n    def open(self, fullurl: str | Request, data: _DataType = None, timeout: float | None = ...) -> _UrlopenRet: ...\n    def error(self, proto: str, *args: Any) -> _UrlopenRet: ...\n    def close(self) -> None: ...\n\nclass BaseHandler:\n    handler_order: ClassVar[int]\n    parent: OpenerDirector\n    def add_parent(self, parent: OpenerDirector) -> None: ...\n    def close(self) -> None: ...\n    def __lt__(self, other: object) -> bool: ...\n\nclass HTTPDefaultErrorHandler(BaseHandler):\n    def http_error_default(\n        self, req: Request, fp: IO[bytes], code: int, msg: str, hdrs: HTTPMessage\n    ) -> HTTPError: ...  # undocumented\n\nclass HTTPRedirectHandler(BaseHandler):\n    max_redirections: ClassVar[int]  # undocumented\n    max_repeats: ClassVar[int]  # undocumented\n    inf_msg: ClassVar[str]  # undocumented\n    def redirect_request(\n        self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage, newurl: str\n    ) -> Request | None: ...\n    def http_error_301(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ...\n    def http_error_302(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ...\n    def http_error_303(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ...\n    def http_error_307(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ...\n    if sys.version_info >= (3, 11):\n        def http_error_308(\n            self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage\n        ) -> _UrlopenRet | None: ...\n\nclass HTTPCookieProcessor(BaseHandler):\n    cookiejar: CookieJar\n    def __init__(self, cookiejar: CookieJar | None = None) -> None: ...\n    def http_request(self, request: Request) -> Request: ...  # undocumented\n    def http_response(self, request: Request, response: HTTPResponse) -> HTTPResponse: ...  # undocumented\n    def https_request(self, request: Request) -> Request: ...  # undocumented\n    def https_response(self, request: Request, response: HTTPResponse) -> HTTPResponse: ...  # undocumented\n\nclass ProxyHandler(BaseHandler):\n    def __init__(self, proxies: dict[str, str] | None = None) -> None: ...\n    def proxy_open(self, req: Request, proxy: str, type: str) -> _UrlopenRet | None: ...  # undocumented\n    # TODO: add a method for every (common) proxy protocol\n\nclass HTTPPasswordMgr:\n    def add_password(self, realm: str, uri: str | Sequence[str], user: str, passwd: str) -> None: ...\n    def find_user_password(self, realm: str, authuri: str) -> tuple[str | None, str | None]: ...\n    def is_suburi(self, base: str, test: str) -> bool: ...  # undocumented\n    def reduce_uri(self, uri: str, default_port: bool = True) -> tuple[str, str]: ...  # undocumented\n\nclass HTTPPasswordMgrWithDefaultRealm(HTTPPasswordMgr):\n    def add_password(self, realm: str | None, uri: str | Sequence[str], user: str, passwd: str) -> None: ...\n    def find_user_password(self, realm: str | None, authuri: str) -> tuple[str | None, str | None]: ...\n\nclass HTTPPasswordMgrWithPriorAuth(HTTPPasswordMgrWithDefaultRealm):\n    def add_password(\n        self, realm: str | None, uri: str | Sequence[str], user: str, passwd: str, is_authenticated: bool = False\n    ) -> None: ...\n    def update_authenticated(self, uri: str | Sequence[str], is_authenticated: bool = False) -> None: ...\n    def is_authenticated(self, authuri: str) -> bool | None: ...\n\nclass AbstractBasicAuthHandler:\n    rx: ClassVar[Pattern[str]]  # undocumented\n    passwd: HTTPPasswordMgr\n    add_password: Callable[[str, str | Sequence[str], str, str], None]\n    def __init__(self, password_mgr: HTTPPasswordMgr | None = None) -> None: ...\n    def http_error_auth_reqed(self, authreq: str, host: str, req: Request, headers: HTTPMessage) -> None: ...\n    def http_request(self, req: Request) -> Request: ...  # undocumented\n    def http_response(self, req: Request, response: HTTPResponse) -> HTTPResponse: ...  # undocumented\n    def https_request(self, req: Request) -> Request: ...  # undocumented\n    def https_response(self, req: Request, response: HTTPResponse) -> HTTPResponse: ...  # undocumented\n    def retry_http_basic_auth(self, host: str, req: Request, realm: str) -> _UrlopenRet | None: ...  # undocumented\n\nclass HTTPBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):\n    auth_header: ClassVar[str]  # undocumented\n    def http_error_401(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ...\n\nclass ProxyBasicAuthHandler(AbstractBasicAuthHandler, BaseHandler):\n    auth_header: ClassVar[str]\n    def http_error_407(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ...\n\nclass AbstractDigestAuthHandler:\n    def __init__(self, passwd: HTTPPasswordMgr | None = None) -> None: ...\n    def reset_retry_count(self) -> None: ...\n    def http_error_auth_reqed(self, auth_header: str, host: str, req: Request, headers: HTTPMessage) -> None: ...\n    def retry_http_digest_auth(self, req: Request, auth: str) -> _UrlopenRet | None: ...\n    def get_cnonce(self, nonce: str) -> str: ...\n    def get_authorization(self, req: Request, chal: Mapping[str, str]) -> str | None: ...\n    def get_algorithm_impls(self, algorithm: str) -> tuple[Callable[[str], str], Callable[[str, str], str]]: ...\n    def get_entity_digest(self, data: ReadableBuffer | None, chal: Mapping[str, str]) -> str | None: ...\n\nclass HTTPDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):\n    auth_header: ClassVar[str]  # undocumented\n    def http_error_401(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ...\n\nclass ProxyDigestAuthHandler(BaseHandler, AbstractDigestAuthHandler):\n    auth_header: ClassVar[str]  # undocumented\n    def http_error_407(self, req: Request, fp: IO[bytes], code: int, msg: str, headers: HTTPMessage) -> _UrlopenRet | None: ...\n\n@type_check_only\nclass _HTTPConnectionProtocol(Protocol):\n    def __call__(\n        self,\n        host: str,\n        /,\n        *,\n        port: int | None = ...,\n        timeout: float = ...,\n        source_address: tuple[str, int] | None = ...,\n        blocksize: int = ...,\n    ) -> HTTPConnection: ...\n\nclass AbstractHTTPHandler(BaseHandler):  # undocumented\n    if sys.version_info >= (3, 12):\n        def __init__(self, debuglevel: int | None = None) -> None: ...\n    else:\n        def __init__(self, debuglevel: int = 0) -> None: ...\n\n    def set_http_debuglevel(self, level: int) -> None: ...\n    def do_request_(self, request: Request) -> Request: ...\n    def do_open(self, http_class: _HTTPConnectionProtocol, req: Request, **http_conn_args: Any) -> HTTPResponse: ...\n\nclass HTTPHandler(AbstractHTTPHandler):\n    def http_open(self, req: Request) -> HTTPResponse: ...\n    def http_request(self, request: Request) -> Request: ...  # undocumented\n\nclass HTTPSHandler(AbstractHTTPHandler):\n    if sys.version_info >= (3, 12):\n        def __init__(\n            self, debuglevel: int | None = None, context: ssl.SSLContext | None = None, check_hostname: bool | None = None\n        ) -> None: ...\n    else:\n        def __init__(\n            self, debuglevel: int = 0, context: ssl.SSLContext | None = None, check_hostname: bool | None = None\n        ) -> None: ...\n\n    def https_open(self, req: Request) -> HTTPResponse: ...\n    def https_request(self, request: Request) -> Request: ...  # undocumented\n\nclass FileHandler(BaseHandler):\n    names: ClassVar[tuple[str, ...] | None]  # undocumented\n    def file_open(self, req: Request) -> addinfourl: ...\n    def get_names(self) -> tuple[str, ...]: ...  # undocumented\n    def open_local_file(self, req: Request) -> addinfourl: ...  # undocumented\n\nclass DataHandler(BaseHandler):\n    def data_open(self, req: Request) -> addinfourl: ...\n\nclass ftpwrapper:  # undocumented\n    def __init__(\n        self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: float | None = None, persistent: bool = True\n    ) -> None: ...\n    def close(self) -> None: ...\n    def endtransfer(self) -> None: ...\n    def file_close(self) -> None: ...\n    def init(self) -> None: ...\n    def real_close(self) -> None: ...\n    def retrfile(self, file: str, type: str) -> tuple[addclosehook, int | None]: ...\n\nclass FTPHandler(BaseHandler):\n    def ftp_open(self, req: Request) -> addinfourl: ...\n    def connect_ftp(\n        self, user: str, passwd: str, host: str, port: int, dirs: str, timeout: float\n    ) -> ftpwrapper: ...  # undocumented\n\nclass CacheFTPHandler(FTPHandler):\n    def setTimeout(self, t: float) -> None: ...\n    def setMaxConns(self, m: int) -> None: ...\n    def check_cache(self) -> None: ...  # undocumented\n    def clear_cache(self) -> None: ...  # undocumented\n\nclass UnknownHandler(BaseHandler):\n    def unknown_open(self, req: Request) -> NoReturn: ...\n\nclass HTTPErrorProcessor(BaseHandler):\n    def http_response(self, request: Request, response: HTTPResponse) -> _UrlopenRet: ...\n    def https_response(self, request: Request, response: HTTPResponse) -> _UrlopenRet: ...\n\ndef urlretrieve(\n    url: str,\n    filename: StrOrBytesPath | None = None,\n    reporthook: Callable[[int, int, int], object] | None = None,\n    data: _DataType = None,\n) -> tuple[str, HTTPMessage]: ...\ndef urlcleanup() -> None: ...\n\nif sys.version_info < (3, 14):\n    @deprecated(\"Deprecated since Python 3.3; removed in Python 3.14. Use newer `urlopen` functions and methods.\")\n    class URLopener:\n        version: ClassVar[str]\n        def __init__(self, proxies: dict[str, str] | None = None, **x509: str) -> None: ...\n        def open(self, fullurl: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ...\n        def open_unknown(self, fullurl: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ...\n        def retrieve(\n            self,\n            url: str,\n            filename: str | None = None,\n            reporthook: Callable[[int, int, int], object] | None = None,\n            data: ReadableBuffer | None = None,\n        ) -> tuple[str, Message | None]: ...\n        def addheader(self, *args: tuple[str, str]) -> None: ...  # undocumented\n        def cleanup(self) -> None: ...  # undocumented\n        def close(self) -> None: ...  # undocumented\n        def http_error(\n            self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: bytes | None = None\n        ) -> _UrlopenRet: ...  # undocumented\n        def http_error_default(\n            self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage\n        ) -> _UrlopenRet: ...  # undocumented\n        def open_data(self, url: str, data: ReadableBuffer | None = None) -> addinfourl: ...  # undocumented\n        def open_file(self, url: str) -> addinfourl: ...  # undocumented\n        def open_ftp(self, url: str) -> addinfourl: ...  # undocumented\n        def open_http(self, url: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ...  # undocumented\n        def open_https(self, url: str, data: ReadableBuffer | None = None) -> _UrlopenRet: ...  # undocumented\n        def open_local_file(self, url: str) -> addinfourl: ...  # undocumented\n        def open_unknown_proxy(self, proxy: str, fullurl: str, data: ReadableBuffer | None = None) -> None: ...  # undocumented\n        def __del__(self) -> None: ...\n\n    @deprecated(\"Deprecated since Python 3.3; removed in Python 3.14. Use newer `urlopen` functions and methods.\")\n    class FancyURLopener(URLopener):\n        def prompt_user_passwd(self, host: str, realm: str) -> tuple[str, str]: ...\n        def get_user_passwd(self, host: str, realm: str, clear_cache: int = 0) -> tuple[str, str]: ...  # undocumented\n        def http_error_301(\n            self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None\n        ) -> _UrlopenRet | addinfourl | None: ...  # undocumented\n        def http_error_302(\n            self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None\n        ) -> _UrlopenRet | addinfourl | None: ...  # undocumented\n        def http_error_303(\n            self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None\n        ) -> _UrlopenRet | addinfourl | None: ...  # undocumented\n        def http_error_307(\n            self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None\n        ) -> _UrlopenRet | addinfourl | None: ...  # undocumented\n        if sys.version_info >= (3, 11):\n            def http_error_308(\n                self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None = None\n            ) -> _UrlopenRet | addinfourl | None: ...  # undocumented\n\n        def http_error_401(\n            self,\n            url: str,\n            fp: IO[bytes],\n            errcode: int,\n            errmsg: str,\n            headers: HTTPMessage,\n            data: ReadableBuffer | None = None,\n            retry: bool = False,\n        ) -> _UrlopenRet | None: ...  # undocumented\n        def http_error_407(\n            self,\n            url: str,\n            fp: IO[bytes],\n            errcode: int,\n            errmsg: str,\n            headers: HTTPMessage,\n            data: ReadableBuffer | None = None,\n            retry: bool = False,\n        ) -> _UrlopenRet | None: ...  # undocumented\n        def http_error_default(\n            self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage\n        ) -> addinfourl: ...  # undocumented\n        def redirect_internal(\n            self, url: str, fp: IO[bytes], errcode: int, errmsg: str, headers: HTTPMessage, data: ReadableBuffer | None\n        ) -> _UrlopenRet | None: ...  # undocumented\n        def retry_http_basic_auth(\n            self, url: str, realm: str, data: ReadableBuffer | None = None\n        ) -> _UrlopenRet | None: ...  # undocumented\n        def retry_https_basic_auth(\n            self, url: str, realm: str, data: ReadableBuffer | None = None\n        ) -> _UrlopenRet | None: ...  # undocumented\n        def retry_proxy_http_basic_auth(\n            self, url: str, realm: str, data: ReadableBuffer | None = None\n        ) -> _UrlopenRet | None: ...  # undocumented\n        def retry_proxy_https_basic_auth(\n            self, url: str, realm: str, data: ReadableBuffer | None = None\n        ) -> _UrlopenRet | None: ...  # undocumented\n"
  },
  {
    "path": "mypy/typeshed/stdlib/urllib/response.pyi",
    "content": "import tempfile\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Callable, Iterable\nfrom email.message import Message\nfrom types import TracebackType\nfrom typing import IO, Any\nfrom typing_extensions import deprecated\n\n__all__ = [\"addbase\", \"addclosehook\", \"addinfo\", \"addinfourl\"]\n\nclass addbase(tempfile._TemporaryFileWrapper[bytes]):\n    fp: IO[bytes]\n    def __init__(self, fp: IO[bytes]) -> None: ...\n    def __exit__(\n        self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n    ) -> None: ...\n    # These methods don't actually exist, but the class inherits at runtime from\n    # tempfile._TemporaryFileWrapper, which uses __getattr__ to delegate to the\n    # underlying file object. To satisfy the BinaryIO interface, we pretend that this\n    # class has these additional methods.\n    def write(self, s: ReadableBuffer) -> int: ...\n    def writelines(self, lines: Iterable[ReadableBuffer]) -> None: ...\n\nclass addclosehook(addbase):\n    closehook: Callable[..., object]\n    hookargs: tuple[Any, ...]\n    def __init__(self, fp: IO[bytes], closehook: Callable[..., object], *hookargs: Any) -> None: ...\n\nclass addinfo(addbase):\n    headers: Message\n    def __init__(self, fp: IO[bytes], headers: Message) -> None: ...\n    def info(self) -> Message: ...\n\nclass addinfourl(addinfo):\n    url: str\n    code: int | None  # Deprecated since Python 3.9. Use `addinfourl.status` attribute instead.\n    @property\n    def status(self) -> int | None: ...\n    def __init__(self, fp: IO[bytes], headers: Message, url: str, code: int | None = None) -> None: ...\n    @deprecated(\"Deprecated since Python 3.9. Use `addinfourl.url` attribute instead.\")\n    def geturl(self) -> str: ...\n    @deprecated(\"Deprecated since Python 3.9. Use `addinfourl.headers` attribute instead.\")\n    def info(self) -> Message: ...\n    @deprecated(\"Deprecated since Python 3.9. Use `addinfourl.status` attribute instead.\")\n    def getcode(self) -> int | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/urllib/robotparser.pyi",
    "content": "from collections.abc import Iterable\nfrom typing import NamedTuple\n\n__all__ = [\"RobotFileParser\"]\n\nclass RequestRate(NamedTuple):\n    requests: int\n    seconds: int\n\nclass RobotFileParser:\n    def __init__(self, url: str = \"\") -> None: ...\n    def set_url(self, url: str) -> None: ...\n    def read(self) -> None: ...\n    def parse(self, lines: Iterable[str]) -> None: ...\n    def can_fetch(self, useragent: str, url: str) -> bool: ...\n    def mtime(self) -> int: ...\n    def modified(self) -> None: ...\n    def crawl_delay(self, useragent: str) -> str | None: ...\n    def request_rate(self, useragent: str) -> RequestRate | None: ...\n    def site_maps(self) -> list[str] | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/uu.pyi",
    "content": "from typing import BinaryIO\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"Error\", \"encode\", \"decode\"]\n\n_File: TypeAlias = str | BinaryIO\n\nclass Error(Exception): ...\n\ndef encode(\n    in_file: _File, out_file: _File, name: str | None = None, mode: int | None = None, *, backtick: bool = False\n) -> None: ...\ndef decode(in_file: _File, out_file: _File | None = None, mode: int | None = None, quiet: bool = False) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/uuid.pyi",
    "content": "import builtins\nimport sys\nfrom _typeshed import Unused\nfrom enum import Enum\nfrom typing import Final, NoReturn\nfrom typing_extensions import LiteralString, TypeAlias\n\n_FieldsType: TypeAlias = tuple[int, int, int, int, int, int]\n\nclass SafeUUID(Enum):\n    safe = 0\n    unsafe = -1\n    unknown = None\n\nclass UUID:\n    __slots__ = (\"int\", \"is_safe\", \"__weakref__\")\n    is_safe: Final[SafeUUID]\n    int: Final[builtins.int]\n\n    def __init__(\n        self,\n        hex: str | None = None,\n        bytes: builtins.bytes | None = None,\n        bytes_le: builtins.bytes | None = None,\n        fields: _FieldsType | None = None,\n        int: builtins.int | None = None,\n        version: builtins.int | None = None,\n        *,\n        is_safe: SafeUUID = SafeUUID.unknown,\n    ) -> None: ...\n    @property\n    def bytes(self) -> builtins.bytes: ...\n    @property\n    def bytes_le(self) -> builtins.bytes: ...\n    @property\n    def clock_seq(self) -> builtins.int: ...\n    @property\n    def clock_seq_hi_variant(self) -> builtins.int: ...\n    @property\n    def clock_seq_low(self) -> builtins.int: ...\n    @property\n    def fields(self) -> _FieldsType: ...\n    @property\n    def hex(self) -> str: ...\n    @property\n    def node(self) -> builtins.int: ...\n    @property\n    def time(self) -> builtins.int: ...\n    @property\n    def time_hi_version(self) -> builtins.int: ...\n    @property\n    def time_low(self) -> builtins.int: ...\n    @property\n    def time_mid(self) -> builtins.int: ...\n    @property\n    def urn(self) -> str: ...\n    @property\n    def variant(self) -> str: ...\n    @property\n    def version(self) -> builtins.int | None: ...\n    def __int__(self) -> builtins.int: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __lt__(self, other: UUID) -> bool: ...\n    def __le__(self, other: UUID) -> bool: ...\n    def __gt__(self, other: UUID) -> bool: ...\n    def __ge__(self, other: UUID) -> bool: ...\n    def __hash__(self) -> builtins.int: ...\n    def __setattr__(self, name: Unused, value: Unused) -> NoReturn: ...\n\ndef getnode() -> int: ...\ndef uuid1(node: int | None = None, clock_seq: int | None = None) -> UUID: ...\n\nif sys.version_info >= (3, 14):\n    def uuid6(node: int | None = None, clock_seq: int | None = None) -> UUID: ...\n    def uuid7() -> UUID: ...\n    def uuid8(a: int | None = None, b: int | None = None, c: int | None = None) -> UUID: ...\n\nif sys.version_info >= (3, 12):\n    def uuid3(namespace: UUID, name: str | bytes) -> UUID: ...\n\nelse:\n    def uuid3(namespace: UUID, name: str) -> UUID: ...\n\ndef uuid4() -> UUID: ...\n\nif sys.version_info >= (3, 12):\n    def uuid5(namespace: UUID, name: str | bytes) -> UUID: ...\n\nelse:\n    def uuid5(namespace: UUID, name: str) -> UUID: ...\n\nif sys.version_info >= (3, 14):\n    NIL: Final[UUID]\n    MAX: Final[UUID]\n\nNAMESPACE_DNS: Final[UUID]\nNAMESPACE_URL: Final[UUID]\nNAMESPACE_OID: Final[UUID]\nNAMESPACE_X500: Final[UUID]\nRESERVED_NCS: Final[LiteralString]\nRFC_4122: Final[LiteralString]\nRESERVED_MICROSOFT: Final[LiteralString]\nRESERVED_FUTURE: Final[LiteralString]\n\nif sys.version_info >= (3, 12):\n    def main() -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/warnings.pyi",
    "content": "import re\nimport sys\nfrom _warnings import warn as warn, warn_explicit as warn_explicit\nfrom collections.abc import Sequence\nfrom types import ModuleType, TracebackType\nfrom typing import Any, Generic, Literal, TextIO, overload\nfrom typing_extensions import LiteralString, TypeAlias, TypeVar\n\n__all__ = [\n    \"warn\",\n    \"warn_explicit\",\n    \"showwarning\",\n    \"formatwarning\",\n    \"filterwarnings\",\n    \"simplefilter\",\n    \"resetwarnings\",\n    \"catch_warnings\",\n]\n\nif sys.version_info >= (3, 13):\n    __all__ += [\"deprecated\"]\n\n_T = TypeVar(\"_T\")\n_W_co = TypeVar(\"_W_co\", bound=list[WarningMessage] | None, default=list[WarningMessage] | None, covariant=True)\n\nif sys.version_info >= (3, 14):\n    _ActionKind: TypeAlias = Literal[\"default\", \"error\", \"ignore\", \"always\", \"module\", \"once\"]\nelse:\n    _ActionKind: TypeAlias = Literal[\"default\", \"error\", \"ignore\", \"always\", \"all\", \"module\", \"once\"]\nfilters: Sequence[tuple[str, re.Pattern[str] | None, type[Warning], re.Pattern[str] | None, int]]  # undocumented, do not mutate\n\ndef showwarning(\n    message: Warning | str,\n    category: type[Warning],\n    filename: str,\n    lineno: int,\n    file: TextIO | None = None,\n    line: str | None = None,\n) -> None: ...\ndef formatwarning(\n    message: Warning | str, category: type[Warning], filename: str, lineno: int, line: str | None = None\n) -> str: ...\ndef filterwarnings(\n    action: _ActionKind, message: str = \"\", category: type[Warning] = ..., module: str = \"\", lineno: int = 0, append: bool = False\n) -> None: ...\ndef simplefilter(action: _ActionKind, category: type[Warning] = ..., lineno: int = 0, append: bool = False) -> None: ...\ndef resetwarnings() -> None: ...\n\nclass _OptionError(Exception): ...\n\nclass WarningMessage:\n    message: Warning | str\n    category: type[Warning]\n    filename: str\n    lineno: int\n    file: TextIO | None\n    line: str | None\n    source: Any | None\n    def __init__(\n        self,\n        message: Warning | str,\n        category: type[Warning],\n        filename: str,\n        lineno: int,\n        file: TextIO | None = None,\n        line: str | None = None,\n        source: Any | None = None,\n    ) -> None: ...\n\nclass catch_warnings(Generic[_W_co]):\n    if sys.version_info >= (3, 11):\n        @overload\n        def __init__(\n            self: catch_warnings[None],\n            *,\n            record: Literal[False] = False,\n            module: ModuleType | None = None,\n            action: _ActionKind | None = None,\n            category: type[Warning] = ...,\n            lineno: int = 0,\n            append: bool = False,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self: catch_warnings[list[WarningMessage]],\n            *,\n            record: Literal[True],\n            module: ModuleType | None = None,\n            action: _ActionKind | None = None,\n            category: type[Warning] = ...,\n            lineno: int = 0,\n            append: bool = False,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            *,\n            record: bool,\n            module: ModuleType | None = None,\n            action: _ActionKind | None = None,\n            category: type[Warning] = ...,\n            lineno: int = 0,\n            append: bool = False,\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(self: catch_warnings[None], *, record: Literal[False] = False, module: ModuleType | None = None) -> None: ...\n        @overload\n        def __init__(\n            self: catch_warnings[list[WarningMessage]], *, record: Literal[True], module: ModuleType | None = None\n        ) -> None: ...\n        @overload\n        def __init__(self, *, record: bool, module: ModuleType | None = None) -> None: ...\n\n    def __enter__(self) -> _W_co: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n\nif sys.version_info >= (3, 13):\n    class deprecated:\n        message: LiteralString\n        category: type[Warning] | None\n        stacklevel: int\n        def __init__(self, message: LiteralString, /, *, category: type[Warning] | None = ..., stacklevel: int = 1) -> None: ...\n        def __call__(self, arg: _T, /) -> _T: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/wave.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer, Unused\nfrom typing import IO, Any, BinaryIO, Final, Literal, NamedTuple, NoReturn, overload\nfrom typing_extensions import Self, TypeAlias, deprecated\n\n__all__ = [\"open\", \"Error\", \"Wave_read\", \"Wave_write\"]\n\n_File: TypeAlias = str | IO[bytes]\n\nclass Error(Exception): ...\n\nWAVE_FORMAT_PCM: Final = 0x0001\n\nclass _wave_params(NamedTuple):\n    nchannels: int\n    sampwidth: int\n    framerate: int\n    nframes: int\n    comptype: str\n    compname: str\n\nclass Wave_read:\n    def __init__(self, f: _File) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n    def __del__(self) -> None: ...\n    def getfp(self) -> BinaryIO | None: ...\n    def rewind(self) -> None: ...\n    def close(self) -> None: ...\n    def tell(self) -> int: ...\n    def getnchannels(self) -> int: ...\n    def getnframes(self) -> int: ...\n    def getsampwidth(self) -> int: ...\n    def getframerate(self) -> int: ...\n    def getcomptype(self) -> str: ...\n    def getcompname(self) -> str: ...\n    def getparams(self) -> _wave_params: ...\n    if sys.version_info >= (3, 13):\n        @deprecated(\"Deprecated since Python 3.13; will be removed in Python 3.15.\")\n        def getmarkers(self) -> None: ...\n        @deprecated(\"Deprecated since Python 3.13; will be removed in Python 3.15.\")\n        def getmark(self, id: Any) -> NoReturn: ...\n    else:\n        def getmarkers(self) -> None: ...\n        def getmark(self, id: Any) -> NoReturn: ...\n\n    def setpos(self, pos: int) -> None: ...\n    def readframes(self, nframes: int) -> bytes: ...\n\nclass Wave_write:\n    def __init__(self, f: _File) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, *args: Unused) -> None: ...\n    def __del__(self) -> None: ...\n    def setnchannels(self, nchannels: int) -> None: ...\n    def getnchannels(self) -> int: ...\n    def setsampwidth(self, sampwidth: int) -> None: ...\n    def getsampwidth(self) -> int: ...\n    def setframerate(self, framerate: float) -> None: ...\n    def getframerate(self) -> int: ...\n    def setnframes(self, nframes: int) -> None: ...\n    def getnframes(self) -> int: ...\n    def setcomptype(self, comptype: str, compname: str) -> None: ...\n    def getcomptype(self) -> str: ...\n    def getcompname(self) -> str: ...\n    def setparams(self, params: _wave_params | tuple[int, int, int, int, str, str]) -> None: ...\n    def getparams(self) -> _wave_params: ...\n    if sys.version_info >= (3, 13):\n        @deprecated(\"Deprecated since Python 3.13; will be removed in Python 3.15.\")\n        def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ...\n        @deprecated(\"Deprecated since Python 3.13; will be removed in Python 3.15.\")\n        def getmark(self, id: Any) -> NoReturn: ...\n        @deprecated(\"Deprecated since Python 3.13; will be removed in Python 3.15.\")\n        def getmarkers(self) -> None: ...\n    else:\n        def setmark(self, id: Any, pos: Any, name: Any) -> NoReturn: ...\n        def getmark(self, id: Any) -> NoReturn: ...\n        def getmarkers(self) -> None: ...\n\n    def tell(self) -> int: ...\n    def writeframesraw(self, data: ReadableBuffer) -> None: ...\n    def writeframes(self, data: ReadableBuffer) -> None: ...\n    def close(self) -> None: ...\n\n@overload\ndef open(f: _File, mode: Literal[\"r\", \"rb\"]) -> Wave_read: ...\n@overload\ndef open(f: _File, mode: Literal[\"w\", \"wb\"]) -> Wave_write: ...\n@overload\ndef open(f: _File, mode: str | None = None) -> Any: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/weakref.pyi",
    "content": "from _typeshed import SupportsKeysAndGetItem\nfrom _weakref import getweakrefcount as getweakrefcount, getweakrefs as getweakrefs, proxy as proxy\nfrom _weakrefset import WeakSet as WeakSet\nfrom collections.abc import Callable, Iterable, Iterator, Mapping, MutableMapping\nfrom types import GenericAlias\nfrom typing import Any, ClassVar, Generic, TypeVar, final, overload\nfrom typing_extensions import ParamSpec, Self, disjoint_base\n\n__all__ = [\n    \"ref\",\n    \"proxy\",\n    \"getweakrefcount\",\n    \"getweakrefs\",\n    \"WeakKeyDictionary\",\n    \"ReferenceType\",\n    \"ProxyType\",\n    \"CallableProxyType\",\n    \"ProxyTypes\",\n    \"WeakValueDictionary\",\n    \"WeakSet\",\n    \"WeakMethod\",\n    \"finalize\",\n]\n\n_T = TypeVar(\"_T\")\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n_KT = TypeVar(\"_KT\")\n_VT = TypeVar(\"_VT\")\n_CallableT = TypeVar(\"_CallableT\", bound=Callable[..., Any])\n_P = ParamSpec(\"_P\")\n\nProxyTypes: tuple[type[Any], ...]\n\n# These classes are implemented in C and imported from _weakref at runtime. However,\n# they consider themselves to live in the weakref module for sys.version_info >= (3, 11),\n# so defining their stubs here means we match their __module__ value.\n# Prior to 3.11 they did not declare a module for themselves and ended up looking like they\n# came from the builtin module at runtime, which was just wrong, and we won't attempt to\n# duplicate that.\n\n@final\nclass CallableProxyType(Generic[_CallableT]):  # \"weakcallableproxy\"\n    def __eq__(self, value: object, /) -> bool: ...\n    def __getattr__(self, attr: str) -> Any: ...\n    __call__: _CallableT\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\n@final\nclass ProxyType(Generic[_T]):  # \"weakproxy\"\n    def __eq__(self, value: object, /) -> bool: ...\n    def __getattr__(self, attr: str) -> Any: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\n@disjoint_base\nclass ReferenceType(Generic[_T]):  # \"weakref\"\n    __callback__: Callable[[Self], Any]\n    def __new__(cls, o: _T, callback: Callable[[Self], Any] | None = ..., /) -> Self: ...\n    def __call__(self) -> _T | None: ...\n    def __eq__(self, value: object, /) -> bool: ...\n    def __hash__(self) -> int: ...\n    def __class_getitem__(cls, item: Any, /) -> GenericAlias: ...\n\nref = ReferenceType\n\n# everything below here is implemented in weakref.py\n\nclass WeakMethod(ref[_CallableT]):\n    __slots__ = (\"_func_ref\", \"_meth_type\", \"_alive\", \"__weakref__\")\n    def __new__(cls, meth: _CallableT, callback: Callable[[Self], Any] | None = None) -> Self: ...\n    def __call__(self) -> _CallableT | None: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __ne__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n\nclass WeakValueDictionary(MutableMapping[_KT, _VT]):\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(\n        self: WeakValueDictionary[_KT, _VT],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        other: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]],\n        /,\n    ) -> None: ...\n    @overload\n    def __init__(\n        self: WeakValueDictionary[str, _VT],  # pyright: ignore[reportInvalidTypeVarUse]  #11780\n        other: Mapping[str, _VT] | Iterable[tuple[str, _VT]] = (),\n        /,\n        **kwargs: _VT,\n    ) -> None: ...\n    def __len__(self) -> int: ...\n    def __getitem__(self, key: _KT) -> _VT: ...\n    def __setitem__(self, key: _KT, value: _VT) -> None: ...\n    def __delitem__(self, key: _KT) -> None: ...\n    def __contains__(self, key: object) -> bool: ...\n    def __iter__(self) -> Iterator[_KT]: ...\n    def copy(self) -> WeakValueDictionary[_KT, _VT]: ...\n    __copy__ = copy\n    def __deepcopy__(self, memo: Any) -> Self: ...\n    @overload\n    def get(self, key: _KT, default: None = None) -> _VT | None: ...\n    @overload\n    def get(self, key: _KT, default: _VT) -> _VT: ...\n    @overload\n    def get(self, key: _KT, default: _T) -> _VT | _T: ...\n    # These are incompatible with Mapping\n    def keys(self) -> Iterator[_KT]: ...  # type: ignore[override]\n    def values(self) -> Iterator[_VT]: ...  # type: ignore[override]\n    def items(self) -> Iterator[tuple[_KT, _VT]]: ...  # type: ignore[override]\n    def itervaluerefs(self) -> Iterator[KeyedRef[_KT, _VT]]: ...\n    def valuerefs(self) -> list[KeyedRef[_KT, _VT]]: ...\n    def setdefault(self, key: _KT, default: _VT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _VT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _T) -> _VT | _T: ...\n    @overload\n    def update(self, other: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ...\n    @overload\n    def update(self, other: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ...\n    @overload\n    def update(self, other: None = None, /, **kwargs: _VT) -> None: ...\n    def __or__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ...\n    def __ror__(self, other: Mapping[_T1, _T2]) -> WeakValueDictionary[_KT | _T1, _VT | _T2]: ...\n    # WeakValueDictionary.__ior__ should be kept roughly in line with MutableMapping.update()\n    @overload  # type: ignore[misc]\n    def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ...\n    @overload\n    def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ...\n\nclass KeyedRef(ref[_T], Generic[_KT, _T]):\n    __slots__ = (\"key\",)\n    key: _KT\n    def __new__(type, ob: _T, callback: Callable[[Self], Any], key: _KT) -> Self: ...\n    def __init__(self, ob: _T, callback: Callable[[Self], Any], key: _KT) -> None: ...\n\nclass WeakKeyDictionary(MutableMapping[_KT, _VT]):\n    @overload\n    def __init__(self, dict: None = None) -> None: ...\n    @overload\n    def __init__(self, dict: Mapping[_KT, _VT] | Iterable[tuple[_KT, _VT]]) -> None: ...\n    def __len__(self) -> int: ...\n    def __getitem__(self, key: _KT) -> _VT: ...\n    def __setitem__(self, key: _KT, value: _VT) -> None: ...\n    def __delitem__(self, key: _KT) -> None: ...\n    def __contains__(self, key: object) -> bool: ...\n    def __iter__(self) -> Iterator[_KT]: ...\n    def copy(self) -> WeakKeyDictionary[_KT, _VT]: ...\n    __copy__ = copy\n    def __deepcopy__(self, memo: Any) -> Self: ...\n    @overload\n    def get(self, key: _KT, default: None = None) -> _VT | None: ...\n    @overload\n    def get(self, key: _KT, default: _VT) -> _VT: ...\n    @overload\n    def get(self, key: _KT, default: _T) -> _VT | _T: ...\n    # These are incompatible with Mapping\n    def keys(self) -> Iterator[_KT]: ...  # type: ignore[override]\n    def values(self) -> Iterator[_VT]: ...  # type: ignore[override]\n    def items(self) -> Iterator[tuple[_KT, _VT]]: ...  # type: ignore[override]\n    def keyrefs(self) -> list[ref[_KT]]: ...\n    # Keep WeakKeyDictionary.setdefault in line with MutableMapping.setdefault, modulo positional-only differences\n    @overload\n    def setdefault(self: WeakKeyDictionary[_KT, _VT | None], key: _KT, default: None = None) -> _VT: ...\n    @overload\n    def setdefault(self, key: _KT, default: _VT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _VT) -> _VT: ...\n    @overload\n    def pop(self, key: _KT, default: _T) -> _VT | _T: ...\n    @overload\n    def update(self, dict: SupportsKeysAndGetItem[_KT, _VT], /, **kwargs: _VT) -> None: ...\n    @overload\n    def update(self, dict: Iterable[tuple[_KT, _VT]], /, **kwargs: _VT) -> None: ...\n    @overload\n    def update(self, dict: None = None, /, **kwargs: _VT) -> None: ...\n    def __or__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ...\n    def __ror__(self, other: Mapping[_T1, _T2]) -> WeakKeyDictionary[_KT | _T1, _VT | _T2]: ...\n    # WeakKeyDictionary.__ior__ should be kept roughly in line with MutableMapping.update()\n    @overload  # type: ignore[misc]\n    def __ior__(self, other: SupportsKeysAndGetItem[_KT, _VT]) -> Self: ...\n    @overload\n    def __ior__(self, other: Iterable[tuple[_KT, _VT]]) -> Self: ...\n\nclass finalize(Generic[_P, _T]):\n    __slots__ = ()\n    def __init__(self, obj: _T, func: Callable[_P, Any], /, *args: _P.args, **kwargs: _P.kwargs) -> None: ...\n    def __call__(self, _: Any = None) -> Any | None: ...\n    def detach(self) -> tuple[_T, Callable[_P, Any], tuple[Any, ...], dict[str, Any]] | None: ...\n    def peek(self) -> tuple[_T, Callable[_P, Any], tuple[Any, ...], dict[str, Any]] | None: ...\n    @property\n    def alive(self) -> bool: ...\n    atexit: bool\n"
  },
  {
    "path": "mypy/typeshed/stdlib/webbrowser.pyi",
    "content": "import sys\nfrom abc import abstractmethod\nfrom collections.abc import Callable, Sequence\nfrom typing import Literal\nfrom typing_extensions import deprecated\n\n__all__ = [\"Error\", \"open\", \"open_new\", \"open_new_tab\", \"get\", \"register\"]\n\nclass Error(Exception): ...\n\ndef register(\n    name: str, klass: Callable[[], BaseBrowser] | None, instance: BaseBrowser | None = None, *, preferred: bool = False\n) -> None: ...\ndef get(using: str | None = None) -> BaseBrowser: ...\ndef open(url: str, new: int = 0, autoraise: bool = True) -> bool: ...\ndef open_new(url: str) -> bool: ...\ndef open_new_tab(url: str) -> bool: ...\n\nclass BaseBrowser:\n    args: list[str]\n    name: str\n    basename: str\n    def __init__(self, name: str = \"\") -> None: ...\n    @abstractmethod\n    def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ...\n    def open_new(self, url: str) -> bool: ...\n    def open_new_tab(self, url: str) -> bool: ...\n\nclass GenericBrowser(BaseBrowser):\n    def __init__(self, name: str | Sequence[str]) -> None: ...\n    def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ...\n\nclass BackgroundBrowser(GenericBrowser): ...\n\nclass UnixBrowser(BaseBrowser):\n    def open(self, url: str, new: Literal[0, 1, 2] = 0, autoraise: bool = True) -> bool: ...  # type: ignore[override]\n    raise_opts: list[str] | None\n    background: bool\n    redirect_stdout: bool\n    remote_args: list[str]\n    remote_action: str\n    remote_action_newwin: str\n    remote_action_newtab: str\n\nclass Mozilla(UnixBrowser): ...\n\nif sys.version_info < (3, 12):\n    class Galeon(UnixBrowser):\n        raise_opts: list[str]\n\n    class Grail(BaseBrowser):\n        def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ...\n\nclass Chrome(UnixBrowser): ...\nclass Opera(UnixBrowser): ...\nclass Elinks(UnixBrowser): ...\n\nclass Konqueror(BaseBrowser):\n    def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ...\n\nif sys.platform == \"win32\":\n    class WindowsDefault(BaseBrowser):\n        def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ...\n\nif sys.platform == \"darwin\":\n    if sys.version_info < (3, 13):\n        if sys.version_info >= (3, 11):\n            @deprecated(\"Deprecated since Python 3.11; removed in Python 3.13.\")\n            class MacOSX(BaseBrowser):\n                def __init__(self, name: str) -> None: ...\n                def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ...\n\n        else:\n            class MacOSX(BaseBrowser):\n                def __init__(self, name: str) -> None: ...\n                def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ...\n\n    class MacOSXOSAScript(BaseBrowser):  # In runtime this class does not have `name` and `basename`\n        if sys.version_info >= (3, 11):\n            def __init__(self, name: str = \"default\") -> None: ...\n        else:\n            def __init__(self, name: str) -> None: ...\n\n        def open(self, url: str, new: int = 0, autoraise: bool = True) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/winreg.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer, Unused\nfrom types import TracebackType\nfrom typing import Any, Final, Literal, final, overload\nfrom typing_extensions import Self, TypeAlias\n\nif sys.platform == \"win32\":\n    _KeyType: TypeAlias = HKEYType | int\n    def CloseKey(hkey: _KeyType, /) -> None: ...\n    def ConnectRegistry(computer_name: str | None, key: _KeyType, /) -> HKEYType: ...\n    def CreateKey(key: _KeyType, sub_key: str | None, /) -> HKEYType: ...\n    def CreateKeyEx(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131078) -> HKEYType: ...\n    def DeleteKey(key: _KeyType, sub_key: str, /) -> None: ...\n    def DeleteKeyEx(key: _KeyType, sub_key: str, access: int = 256, reserved: int = 0) -> None: ...\n    def DeleteValue(key: _KeyType, value: str, /) -> None: ...\n    def EnumKey(key: _KeyType, index: int, /) -> str: ...\n    def EnumValue(key: _KeyType, index: int, /) -> tuple[str, Any, int]: ...\n    def ExpandEnvironmentStrings(string: str, /) -> str: ...\n    def FlushKey(key: _KeyType, /) -> None: ...\n    def LoadKey(key: _KeyType, sub_key: str, file_name: str, /) -> None: ...\n    def OpenKey(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131097) -> HKEYType: ...\n    def OpenKeyEx(key: _KeyType, sub_key: str | None, reserved: int = 0, access: int = 131097) -> HKEYType: ...\n    def QueryInfoKey(key: _KeyType, /) -> tuple[int, int, int]: ...\n    def QueryValue(key: _KeyType, sub_key: str | None, /) -> str: ...\n    def QueryValueEx(key: _KeyType, name: str, /) -> tuple[Any, int]: ...\n    def SaveKey(key: _KeyType, file_name: str, /) -> None: ...\n    def SetValue(key: _KeyType, sub_key: str | None, type: int, value: str, /) -> None: ...\n    @overload  # type=REG_DWORD|REG_QWORD\n    def SetValueEx(\n        key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[4, 5], value: int | None, /\n    ) -> None: ...\n    @overload  # type=REG_SZ|REG_EXPAND_SZ\n    def SetValueEx(\n        key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[1, 2], value: str | None, /\n    ) -> None: ...\n    @overload  # type=REG_MULTI_SZ\n    def SetValueEx(\n        key: _KeyType, value_name: str | None, reserved: Unused, type: Literal[7], value: list[str] | None, /\n    ) -> None: ...\n    @overload  # type=REG_BINARY and everything else\n    def SetValueEx(\n        key: _KeyType,\n        value_name: str | None,\n        reserved: Unused,\n        type: Literal[0, 3, 8, 9, 10, 11],\n        value: ReadableBuffer | None,\n        /,\n    ) -> None: ...\n    @overload  # Unknown or undocumented\n    def SetValueEx(\n        key: _KeyType,\n        value_name: str | None,\n        reserved: Unused,\n        type: int,\n        value: int | str | list[str] | ReadableBuffer | None,\n        /,\n    ) -> None: ...\n    def DisableReflectionKey(key: _KeyType, /) -> None: ...\n    def EnableReflectionKey(key: _KeyType, /) -> None: ...\n    def QueryReflectionKey(key: _KeyType, /) -> bool: ...\n\n    HKEY_CLASSES_ROOT: Final[int]\n    HKEY_CURRENT_USER: Final[int]\n    HKEY_LOCAL_MACHINE: Final[int]\n    HKEY_USERS: Final[int]\n    HKEY_PERFORMANCE_DATA: Final[int]\n    HKEY_CURRENT_CONFIG: Final[int]\n    HKEY_DYN_DATA: Final[int]\n\n    KEY_ALL_ACCESS: Final = 983103\n    KEY_WRITE: Final = 131078\n    KEY_READ: Final = 131097\n    KEY_EXECUTE: Final = 131097\n    KEY_QUERY_VALUE: Final = 1\n    KEY_SET_VALUE: Final = 2\n    KEY_CREATE_SUB_KEY: Final = 4\n    KEY_ENUMERATE_SUB_KEYS: Final = 8\n    KEY_NOTIFY: Final = 16\n    KEY_CREATE_LINK: Final = 32\n\n    KEY_WOW64_64KEY: Final = 256\n    KEY_WOW64_32KEY: Final = 512\n\n    REG_BINARY: Final = 3\n    REG_DWORD: Final = 4\n    REG_DWORD_LITTLE_ENDIAN: Final = 4\n    REG_DWORD_BIG_ENDIAN: Final = 5\n    REG_EXPAND_SZ: Final = 2\n    REG_LINK: Final = 6\n    REG_MULTI_SZ: Final = 7\n    REG_NONE: Final = 0\n    REG_QWORD: Final = 11\n    REG_QWORD_LITTLE_ENDIAN: Final = 11\n    REG_RESOURCE_LIST: Final = 8\n    REG_FULL_RESOURCE_DESCRIPTOR: Final = 9\n    REG_RESOURCE_REQUIREMENTS_LIST: Final = 10\n    REG_SZ: Final = 1\n\n    REG_CREATED_NEW_KEY: Final = 1  # undocumented\n    REG_LEGAL_CHANGE_FILTER: Final = 268435471  # undocumented\n    REG_LEGAL_OPTION: Final = 31  # undocumented\n    REG_NOTIFY_CHANGE_ATTRIBUTES: Final = 2  # undocumented\n    REG_NOTIFY_CHANGE_LAST_SET: Final = 4  # undocumented\n    REG_NOTIFY_CHANGE_NAME: Final = 1  # undocumented\n    REG_NOTIFY_CHANGE_SECURITY: Final = 8  # undocumented\n    REG_NO_LAZY_FLUSH: Final = 4  # undocumented\n    REG_OPENED_EXISTING_KEY: Final = 2  # undocumented\n    REG_OPTION_BACKUP_RESTORE: Final = 4  # undocumented\n    REG_OPTION_CREATE_LINK: Final = 2  # undocumented\n    REG_OPTION_NON_VOLATILE: Final = 0  # undocumented\n    REG_OPTION_OPEN_LINK: Final = 8  # undocumented\n    REG_OPTION_RESERVED: Final = 0  # undocumented\n    REG_OPTION_VOLATILE: Final = 1  # undocumented\n    REG_REFRESH_HIVE: Final = 2  # undocumented\n    REG_WHOLE_HIVE_VOLATILE: Final = 1  # undocumented\n\n    error = OSError\n\n    # Though this class has a __name__ of PyHKEY, it's exposed as HKEYType for some reason\n    @final\n    class HKEYType:\n        def __bool__(self) -> bool: ...\n        def __int__(self) -> int: ...\n        def __enter__(self) -> Self: ...\n        def __exit__(\n            self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, /\n        ) -> bool | None: ...\n        def Close(self) -> None: ...\n        def Detach(self) -> int: ...\n        def __hash__(self) -> int: ...\n        @property\n        def handle(self) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/winsound.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom typing import Final, Literal, overload\n\nif sys.platform == \"win32\":\n    SND_APPLICATION: Final = 128\n    SND_FILENAME: Final = 131072\n    SND_ALIAS: Final = 65536\n    SND_LOOP: Final = 8\n    SND_MEMORY: Final = 4\n    SND_PURGE: Final = 64\n    SND_ASYNC: Final = 1\n    SND_NODEFAULT: Final = 2\n    SND_NOSTOP: Final = 16\n    SND_NOWAIT: Final = 8192\n    if sys.version_info >= (3, 14):\n        SND_SENTRY: Final = 524288\n        SND_SYNC: Final = 0\n        SND_SYSTEM: Final = 2097152\n\n    MB_ICONASTERISK: Final = 64\n    MB_ICONEXCLAMATION: Final = 48\n    MB_ICONHAND: Final = 16\n    MB_ICONQUESTION: Final = 32\n    MB_OK: Final = 0\n    if sys.version_info >= (3, 14):\n        MB_ICONERROR: Final = 16\n        MB_ICONINFORMATION: Final = 64\n        MB_ICONSTOP: Final = 16\n        MB_ICONWARNING: Final = 48\n\n    def Beep(frequency: int, duration: int) -> None: ...\n    # Can actually accept anything ORed with 4, and if not it's definitely str, but that's inexpressible\n    @overload\n    def PlaySound(sound: ReadableBuffer | None, flags: Literal[4]) -> None: ...\n    @overload\n    def PlaySound(sound: str | ReadableBuffer | None, flags: int) -> None: ...\n    def MessageBeep(type: int = 0) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/wsgiref/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/wsgiref/handlers.pyi",
    "content": "from _typeshed import OptExcInfo\nfrom _typeshed.wsgi import ErrorStream, InputStream, StartResponse, WSGIApplication, WSGIEnvironment\nfrom abc import abstractmethod\nfrom collections.abc import Callable, MutableMapping\nfrom typing import IO\n\nfrom .headers import Headers\nfrom .util import FileWrapper\n\n__all__ = [\"BaseHandler\", \"SimpleHandler\", \"BaseCGIHandler\", \"CGIHandler\", \"IISCGIHandler\", \"read_environ\"]\n\ndef format_date_time(timestamp: float | None) -> str: ...  # undocumented\ndef read_environ() -> dict[str, str]: ...\n\nclass BaseHandler:\n    wsgi_version: tuple[int, int]  # undocumented\n    wsgi_multithread: bool\n    wsgi_multiprocess: bool\n    wsgi_run_once: bool\n\n    origin_server: bool\n    http_version: str\n    server_software: str | None\n\n    os_environ: MutableMapping[str, str]\n\n    wsgi_file_wrapper: type[FileWrapper] | None\n    headers_class: type[Headers]  # undocumented\n\n    traceback_limit: int | None\n    error_status: str\n    error_headers: list[tuple[str, str]]\n    error_body: bytes\n    def run(self, application: WSGIApplication) -> None: ...\n    def setup_environ(self) -> None: ...\n    def finish_response(self) -> None: ...\n    def get_scheme(self) -> str: ...\n    def set_content_length(self) -> None: ...\n    def cleanup_headers(self) -> None: ...\n    def start_response(\n        self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = None\n    ) -> Callable[[bytes], None]: ...\n    def send_preamble(self) -> None: ...\n    def write(self, data: bytes) -> None: ...\n    def sendfile(self) -> bool: ...\n    def finish_content(self) -> None: ...\n    def close(self) -> None: ...\n    def send_headers(self) -> None: ...\n    def result_is_file(self) -> bool: ...\n    def client_is_modern(self) -> bool: ...\n    def log_exception(self, exc_info: OptExcInfo) -> None: ...\n    def handle_error(self) -> None: ...\n    def error_output(self, environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: ...\n    @abstractmethod\n    def _write(self, data: bytes) -> None: ...\n    @abstractmethod\n    def _flush(self) -> None: ...\n    @abstractmethod\n    def get_stdin(self) -> InputStream: ...\n    @abstractmethod\n    def get_stderr(self) -> ErrorStream: ...\n    @abstractmethod\n    def add_cgi_vars(self) -> None: ...\n\nclass SimpleHandler(BaseHandler):\n    stdin: InputStream\n    stdout: IO[bytes]\n    stderr: ErrorStream\n    base_env: MutableMapping[str, str]\n    def __init__(\n        self,\n        stdin: InputStream,\n        stdout: IO[bytes],\n        stderr: ErrorStream,\n        environ: MutableMapping[str, str],\n        multithread: bool = True,\n        multiprocess: bool = False,\n    ) -> None: ...\n    def get_stdin(self) -> InputStream: ...\n    def get_stderr(self) -> ErrorStream: ...\n    def add_cgi_vars(self) -> None: ...\n    def _write(self, data: bytes) -> None: ...\n    def _flush(self) -> None: ...\n\nclass BaseCGIHandler(SimpleHandler): ...\n\nclass CGIHandler(BaseCGIHandler):\n    def __init__(self) -> None: ...\n\nclass IISCGIHandler(BaseCGIHandler):\n    def __init__(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/wsgiref/headers.pyi",
    "content": "from re import Pattern\nfrom typing import Final, overload\nfrom typing_extensions import TypeAlias\n\n_HeaderList: TypeAlias = list[tuple[str, str]]\n\ntspecials: Final[Pattern[str]]  # undocumented\n\nclass Headers:\n    def __init__(self, headers: _HeaderList | None = None) -> None: ...\n    def __len__(self) -> int: ...\n    def __setitem__(self, name: str, val: str) -> None: ...\n    def __delitem__(self, name: str) -> None: ...\n    def __getitem__(self, name: str) -> str | None: ...\n    def __contains__(self, name: str) -> bool: ...\n    def get_all(self, name: str) -> list[str]: ...\n    @overload\n    def get(self, name: str, default: str) -> str: ...\n    @overload\n    def get(self, name: str, default: str | None = None) -> str | None: ...\n    def keys(self) -> list[str]: ...\n    def values(self) -> list[str]: ...\n    def items(self) -> _HeaderList: ...\n    def __bytes__(self) -> bytes: ...\n    def setdefault(self, name: str, value: str) -> str: ...\n    def add_header(self, _name: str, _value: str | None, **_params: str | None) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/wsgiref/simple_server.pyi",
    "content": "from _typeshed.wsgi import ErrorStream, StartResponse, WSGIApplication, WSGIEnvironment\nfrom http.server import BaseHTTPRequestHandler, HTTPServer\nfrom typing import Final, TypeVar, overload\n\nfrom .handlers import SimpleHandler\n\n__all__ = [\"WSGIServer\", \"WSGIRequestHandler\", \"demo_app\", \"make_server\"]\n\nserver_version: Final[str]  # undocumented\nsys_version: Final[str]  # undocumented\nsoftware_version: Final[str]  # undocumented\n\nclass ServerHandler(SimpleHandler):  # undocumented\n    server_software: str\n\nclass WSGIServer(HTTPServer):\n    application: WSGIApplication | None\n    base_environ: WSGIEnvironment  # only available after call to setup_environ()\n    def setup_environ(self) -> None: ...\n    def get_app(self) -> WSGIApplication | None: ...\n    def set_app(self, application: WSGIApplication | None) -> None: ...\n\nclass WSGIRequestHandler(BaseHTTPRequestHandler):\n    server_version: str\n    def get_environ(self) -> WSGIEnvironment: ...\n    def get_stderr(self) -> ErrorStream: ...\n\ndef demo_app(environ: WSGIEnvironment, start_response: StartResponse) -> list[bytes]: ...\n\n_S = TypeVar(\"_S\", bound=WSGIServer)\n\n@overload\ndef make_server(host: str, port: int, app: WSGIApplication, *, handler_class: type[WSGIRequestHandler] = ...) -> WSGIServer: ...\n@overload\ndef make_server(\n    host: str, port: int, app: WSGIApplication, server_class: type[_S], handler_class: type[WSGIRequestHandler] = ...\n) -> _S: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/wsgiref/types.pyi",
    "content": "from _typeshed import OptExcInfo\nfrom collections.abc import Callable, Iterable, Iterator\nfrom typing import Any, Protocol\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"StartResponse\", \"WSGIEnvironment\", \"WSGIApplication\", \"InputStream\", \"ErrorStream\", \"FileWrapper\"]\n\nclass StartResponse(Protocol):\n    def __call__(\n        self, status: str, headers: list[tuple[str, str]], exc_info: OptExcInfo | None = ..., /\n    ) -> Callable[[bytes], object]: ...\n\nWSGIEnvironment: TypeAlias = dict[str, Any]\nWSGIApplication: TypeAlias = Callable[[WSGIEnvironment, StartResponse], Iterable[bytes]]\n\nclass InputStream(Protocol):\n    def read(self, size: int = ..., /) -> bytes: ...\n    def readline(self, size: int = ..., /) -> bytes: ...\n    def readlines(self, hint: int = ..., /) -> list[bytes]: ...\n    def __iter__(self) -> Iterator[bytes]: ...\n\nclass ErrorStream(Protocol):\n    def flush(self) -> object: ...\n    def write(self, s: str, /) -> object: ...\n    def writelines(self, seq: list[str], /) -> object: ...\n\nclass _Readable(Protocol):\n    def read(self, size: int = ..., /) -> bytes: ...\n    # Optional: def close(self) -> object: ...\n\nclass FileWrapper(Protocol):\n    def __call__(self, file: _Readable, block_size: int = ..., /) -> Iterable[bytes]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/wsgiref/util.pyi",
    "content": "import sys\nfrom _typeshed.wsgi import WSGIEnvironment\nfrom collections.abc import Callable\nfrom typing import IO, Any\n\n__all__ = [\"FileWrapper\", \"guess_scheme\", \"application_uri\", \"request_uri\", \"shift_path_info\", \"setup_testing_defaults\"]\nif sys.version_info >= (3, 13):\n    __all__ += [\"is_hop_by_hop\"]\n\nclass FileWrapper:\n    filelike: IO[bytes]\n    blksize: int\n    close: Callable[[], None]  # only exists if filelike.close exists\n    def __init__(self, filelike: IO[bytes], blksize: int = 8192) -> None: ...\n    if sys.version_info < (3, 11):\n        def __getitem__(self, key: Any) -> bytes: ...\n\n    def __iter__(self) -> FileWrapper: ...\n    def __next__(self) -> bytes: ...\n\ndef guess_scheme(environ: WSGIEnvironment) -> str: ...\ndef application_uri(environ: WSGIEnvironment) -> str: ...\ndef request_uri(environ: WSGIEnvironment, include_query: bool = True) -> str: ...\ndef shift_path_info(environ: WSGIEnvironment) -> str | None: ...\ndef setup_testing_defaults(environ: WSGIEnvironment) -> None: ...\ndef is_hop_by_hop(header_name: str) -> bool: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/wsgiref/validate.pyi",
    "content": "from _typeshed.wsgi import ErrorStream, InputStream, WSGIApplication\nfrom collections.abc import Callable, Iterable, Iterator\nfrom typing import Any, NoReturn\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"validator\"]\n\nclass WSGIWarning(Warning): ...\n\ndef validator(application: WSGIApplication) -> WSGIApplication: ...\n\nclass InputWrapper:\n    input: InputStream\n    def __init__(self, wsgi_input: InputStream) -> None: ...\n    def read(self, size: int) -> bytes: ...\n    def readline(self, size: int = ...) -> bytes: ...\n    def readlines(self, hint: int = ...) -> bytes: ...\n    def __iter__(self) -> Iterator[bytes]: ...\n    def close(self) -> NoReturn: ...\n\nclass ErrorWrapper:\n    errors: ErrorStream\n    def __init__(self, wsgi_errors: ErrorStream) -> None: ...\n    def write(self, s: str) -> None: ...\n    def flush(self) -> None: ...\n    def writelines(self, seq: Iterable[str]) -> None: ...\n    def close(self) -> NoReturn: ...\n\n_WriterCallback: TypeAlias = Callable[[bytes], Any]\n\nclass WriteWrapper:\n    writer: _WriterCallback\n    def __init__(self, wsgi_writer: _WriterCallback) -> None: ...\n    def __call__(self, s: bytes) -> None: ...\n\nclass PartialIteratorWrapper:\n    iterator: Iterator[bytes]\n    def __init__(self, wsgi_iterator: Iterator[bytes]) -> None: ...\n    def __iter__(self) -> IteratorWrapper: ...\n\nclass IteratorWrapper:\n    original_iterator: Iterator[bytes]\n    iterator: Iterator[bytes]\n    closed: bool\n    check_start_response: bool | None\n    def __init__(self, wsgi_iterator: Iterator[bytes], check_start_response: bool | None) -> None: ...\n    def __iter__(self) -> IteratorWrapper: ...\n    def __next__(self) -> bytes: ...\n    def close(self) -> None: ...\n    def __del__(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xdrlib.pyi",
    "content": "from collections.abc import Callable, Sequence\nfrom typing import TypeVar\n\n__all__ = [\"Error\", \"Packer\", \"Unpacker\", \"ConversionError\"]\n\n_T = TypeVar(\"_T\")\n\nclass Error(Exception):\n    msg: str\n    def __init__(self, msg: str) -> None: ...\n\nclass ConversionError(Error): ...\n\nclass Packer:\n    def reset(self) -> None: ...\n    def get_buffer(self) -> bytes: ...\n    def get_buf(self) -> bytes: ...\n    def pack_uint(self, x: int) -> None: ...\n    def pack_int(self, x: int) -> None: ...\n    def pack_enum(self, x: int) -> None: ...\n    def pack_bool(self, x: bool) -> None: ...\n    def pack_uhyper(self, x: int) -> None: ...\n    def pack_hyper(self, x: int) -> None: ...\n    def pack_float(self, x: float) -> None: ...\n    def pack_double(self, x: float) -> None: ...\n    def pack_fstring(self, n: int, s: bytes) -> None: ...\n    def pack_fopaque(self, n: int, s: bytes) -> None: ...\n    def pack_string(self, s: bytes) -> None: ...\n    def pack_opaque(self, s: bytes) -> None: ...\n    def pack_bytes(self, s: bytes) -> None: ...\n    def pack_list(self, list: Sequence[_T], pack_item: Callable[[_T], object]) -> None: ...\n    def pack_farray(self, n: int, list: Sequence[_T], pack_item: Callable[[_T], object]) -> None: ...\n    def pack_array(self, list: Sequence[_T], pack_item: Callable[[_T], object]) -> None: ...\n\nclass Unpacker:\n    def __init__(self, data: bytes) -> None: ...\n    def reset(self, data: bytes) -> None: ...\n    def get_position(self) -> int: ...\n    def set_position(self, position: int) -> None: ...\n    def get_buffer(self) -> bytes: ...\n    def done(self) -> None: ...\n    def unpack_uint(self) -> int: ...\n    def unpack_int(self) -> int: ...\n    def unpack_enum(self) -> int: ...\n    def unpack_bool(self) -> bool: ...\n    def unpack_uhyper(self) -> int: ...\n    def unpack_hyper(self) -> int: ...\n    def unpack_float(self) -> float: ...\n    def unpack_double(self) -> float: ...\n    def unpack_fstring(self, n: int) -> bytes: ...\n    def unpack_fopaque(self, n: int) -> bytes: ...\n    def unpack_string(self) -> bytes: ...\n    def unpack_opaque(self) -> bytes: ...\n    def unpack_bytes(self) -> bytes: ...\n    def unpack_list(self, unpack_item: Callable[[], _T]) -> list[_T]: ...\n    def unpack_farray(self, n: int, unpack_item: Callable[[], _T]) -> list[_T]: ...\n    def unpack_array(self, unpack_item: Callable[[], _T]) -> list[_T]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/__init__.pyi",
    "content": "# At runtime, listing submodules in __all__ without them being imported is\n# valid, and causes them to be included in a star import. See #6523\n__all__ = [\"dom\", \"parsers\", \"sax\", \"etree\"]  # noqa: F822  # pyright: ignore[reportUnsupportedDunderAll]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/dom/NodeFilter.pyi",
    "content": "from typing import Final\nfrom xml.dom.minidom import Node\n\nclass NodeFilter:\n    FILTER_ACCEPT: Final = 1\n    FILTER_REJECT: Final = 2\n    FILTER_SKIP: Final = 3\n\n    SHOW_ALL: Final = 0xFFFFFFFF\n    SHOW_ELEMENT: Final = 0x00000001\n    SHOW_ATTRIBUTE: Final = 0x00000002\n    SHOW_TEXT: Final = 0x00000004\n    SHOW_CDATA_SECTION: Final = 0x00000008\n    SHOW_ENTITY_REFERENCE: Final = 0x00000010\n    SHOW_ENTITY: Final = 0x00000020\n    SHOW_PROCESSING_INSTRUCTION: Final = 0x00000040\n    SHOW_COMMENT: Final = 0x00000080\n    SHOW_DOCUMENT: Final = 0x00000100\n    SHOW_DOCUMENT_TYPE: Final = 0x00000200\n    SHOW_DOCUMENT_FRAGMENT: Final = 0x00000400\n    SHOW_NOTATION: Final = 0x00000800\n    def acceptNode(self, node: Node) -> int: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/dom/__init__.pyi",
    "content": "from typing import Any, Final, Literal\n\nfrom .domreg import getDOMImplementation as getDOMImplementation, registerDOMImplementation as registerDOMImplementation\n\nclass Node:\n    __slots__ = ()\n    ELEMENT_NODE: Final = 1\n    ATTRIBUTE_NODE: Final = 2\n    TEXT_NODE: Final = 3\n    CDATA_SECTION_NODE: Final = 4\n    ENTITY_REFERENCE_NODE: Final = 5\n    ENTITY_NODE: Final = 6\n    PROCESSING_INSTRUCTION_NODE: Final = 7\n    COMMENT_NODE: Final = 8\n    DOCUMENT_NODE: Final = 9\n    DOCUMENT_TYPE_NODE: Final = 10\n    DOCUMENT_FRAGMENT_NODE: Final = 11\n    NOTATION_NODE: Final = 12\n\n# ExceptionCode\nINDEX_SIZE_ERR: Final = 1\nDOMSTRING_SIZE_ERR: Final = 2\nHIERARCHY_REQUEST_ERR: Final = 3\nWRONG_DOCUMENT_ERR: Final = 4\nINVALID_CHARACTER_ERR: Final = 5\nNO_DATA_ALLOWED_ERR: Final = 6\nNO_MODIFICATION_ALLOWED_ERR: Final = 7\nNOT_FOUND_ERR: Final = 8\nNOT_SUPPORTED_ERR: Final = 9\nINUSE_ATTRIBUTE_ERR: Final = 10\nINVALID_STATE_ERR: Final = 11\nSYNTAX_ERR: Final = 12\nINVALID_MODIFICATION_ERR: Final = 13\nNAMESPACE_ERR: Final = 14\nINVALID_ACCESS_ERR: Final = 15\nVALIDATION_ERR: Final = 16\n\nclass DOMException(Exception):\n    code: int\n    def __init__(self, *args: Any, **kw: Any) -> None: ...\n    def _get_code(self) -> int: ...\n\nclass IndexSizeErr(DOMException):\n    code: Literal[1]\n\nclass DomstringSizeErr(DOMException):\n    code: Literal[2]\n\nclass HierarchyRequestErr(DOMException):\n    code: Literal[3]\n\nclass WrongDocumentErr(DOMException):\n    code: Literal[4]\n\nclass InvalidCharacterErr(DOMException):\n    code: Literal[5]\n\nclass NoDataAllowedErr(DOMException):\n    code: Literal[6]\n\nclass NoModificationAllowedErr(DOMException):\n    code: Literal[7]\n\nclass NotFoundErr(DOMException):\n    code: Literal[8]\n\nclass NotSupportedErr(DOMException):\n    code: Literal[9]\n\nclass InuseAttributeErr(DOMException):\n    code: Literal[10]\n\nclass InvalidStateErr(DOMException):\n    code: Literal[11]\n\nclass SyntaxErr(DOMException):\n    code: Literal[12]\n\nclass InvalidModificationErr(DOMException):\n    code: Literal[13]\n\nclass NamespaceErr(DOMException):\n    code: Literal[14]\n\nclass InvalidAccessErr(DOMException):\n    code: Literal[15]\n\nclass ValidationErr(DOMException):\n    code: Literal[16]\n\nclass UserDataHandler:\n    NODE_CLONED: Final = 1\n    NODE_IMPORTED: Final = 2\n    NODE_DELETED: Final = 3\n    NODE_RENAMED: Final = 4\n\nXML_NAMESPACE: Final = \"http://www.w3.org/XML/1998/namespace\"\nXMLNS_NAMESPACE: Final = \"http://www.w3.org/2000/xmlns/\"\nXHTML_NAMESPACE: Final = \"http://www.w3.org/1999/xhtml\"\nEMPTY_NAMESPACE: Final[None]\nEMPTY_PREFIX: Final[None]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/dom/domreg.pyi",
    "content": "from _typeshed.xml import DOMImplementation\nfrom collections.abc import Callable, Iterable\n\nwell_known_implementations: dict[str, str]\nregistered: dict[str, Callable[[], DOMImplementation]]\n\ndef registerDOMImplementation(name: str, factory: Callable[[], DOMImplementation]) -> None: ...\ndef getDOMImplementation(name: str | None = None, features: str | Iterable[tuple[str, str | None]] = ()) -> DOMImplementation: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/dom/expatbuilder.pyi",
    "content": "from _typeshed import ReadableBuffer, SupportsRead\nfrom typing import Any, Final, NoReturn\nfrom typing_extensions import TypeAlias\nfrom xml.dom.minidom import Document, DocumentFragment, DOMImplementation, Element, Node, TypeInfo\nfrom xml.dom.xmlbuilder import DOMBuilderFilter, Options\nfrom xml.parsers.expat import XMLParserType\n\n_Model: TypeAlias = tuple[int, int, str | None, tuple[Any, ...]]  # same as in pyexpat\n\nTEXT_NODE: Final = Node.TEXT_NODE\nCDATA_SECTION_NODE: Final = Node.CDATA_SECTION_NODE\nDOCUMENT_NODE: Final = Node.DOCUMENT_NODE\nFILTER_ACCEPT: Final = DOMBuilderFilter.FILTER_ACCEPT\nFILTER_REJECT: Final = DOMBuilderFilter.FILTER_REJECT\nFILTER_SKIP: Final = DOMBuilderFilter.FILTER_SKIP\nFILTER_INTERRUPT: Final = DOMBuilderFilter.FILTER_INTERRUPT\ntheDOMImplementation: DOMImplementation\n\nclass ElementInfo:\n    __slots__ = (\"_attr_info\", \"_model\", \"tagName\")\n    tagName: str\n    def __init__(self, tagName: str, model: _Model | None = None) -> None: ...\n    def getAttributeType(self, aname: str) -> TypeInfo: ...\n    def getAttributeTypeNS(self, namespaceURI: str | None, localName: str) -> TypeInfo: ...\n    def isElementContent(self) -> bool: ...\n    def isEmpty(self) -> bool: ...\n    def isId(self, aname: str) -> bool: ...\n    def isIdNS(self, euri: str, ename: str, auri: str, aname: str) -> bool: ...\n\nclass ExpatBuilder:\n    document: Document  # Created in self.reset()\n    curNode: DocumentFragment | Element | Document  # Created in self.reset()\n    def __init__(self, options: Options | None = None) -> None: ...\n    def createParser(self) -> XMLParserType: ...\n    def getParser(self) -> XMLParserType: ...\n    def reset(self) -> None: ...\n    def install(self, parser: XMLParserType) -> None: ...\n    def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> Document: ...\n    def parseString(self, string: str | ReadableBuffer) -> Document: ...\n    def start_doctype_decl_handler(\n        self, doctypeName: str, systemId: str | None, publicId: str | None, has_internal_subset: bool\n    ) -> None: ...\n    def end_doctype_decl_handler(self) -> None: ...\n    def pi_handler(self, target: str, data: str) -> None: ...\n    def character_data_handler_cdata(self, data: str) -> None: ...\n    def character_data_handler(self, data: str) -> None: ...\n    def start_cdata_section_handler(self) -> None: ...\n    def end_cdata_section_handler(self) -> None: ...\n    def entity_decl_handler(\n        self,\n        entityName: str,\n        is_parameter_entity: bool,\n        value: str | None,\n        base: str | None,\n        systemId: str,\n        publicId: str | None,\n        notationName: str | None,\n    ) -> None: ...\n    def notation_decl_handler(self, notationName: str, base: str | None, systemId: str, publicId: str | None) -> None: ...\n    def comment_handler(self, data: str) -> None: ...\n    def external_entity_ref_handler(self, context: str, base: str | None, systemId: str | None, publicId: str | None) -> int: ...\n    def first_element_handler(self, name: str, attributes: list[str]) -> None: ...\n    def start_element_handler(self, name: str, attributes: list[str]) -> None: ...\n    def end_element_handler(self, name: str) -> None: ...\n    def element_decl_handler(self, name: str, model: _Model) -> None: ...\n    def attlist_decl_handler(self, elem: str, name: str, type: str, default: str | None, required: bool) -> None: ...\n    def xml_decl_handler(self, version: str, encoding: str | None, standalone: int) -> None: ...\n\nclass FilterVisibilityController:\n    __slots__ = (\"filter\",)\n    filter: DOMBuilderFilter\n    def __init__(self, filter: DOMBuilderFilter) -> None: ...\n    def startContainer(self, node: Node) -> int: ...\n    def acceptNode(self, node: Node) -> int: ...\n\nclass FilterCrutch:\n    __slots__ = (\"_builder\", \"_level\", \"_old_start\", \"_old_end\")\n    def __init__(self, builder: ExpatBuilder) -> None: ...\n\nclass Rejecter(FilterCrutch):\n    __slots__ = ()\n    def start_element_handler(self, *args: Any) -> None: ...\n    def end_element_handler(self, *args: Any) -> None: ...\n\nclass Skipper(FilterCrutch):\n    __slots__ = ()\n    def start_element_handler(self, *args: Any) -> None: ...\n    def end_element_handler(self, *args: Any) -> None: ...\n\nclass FragmentBuilder(ExpatBuilder):\n    fragment: DocumentFragment | None\n    originalDocument: Document\n    context: Node\n    def __init__(self, context: Node, options: Options | None = None) -> None: ...\n    def reset(self) -> None: ...\n    def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> DocumentFragment: ...  # type: ignore[override]\n    def parseString(self, string: ReadableBuffer | str) -> DocumentFragment: ...  # type: ignore[override]\n    def external_entity_ref_handler(self, context: str, base: str | None, systemId: str | None, publicId: str | None) -> int: ...\n\nclass Namespaces:\n    def createParser(self) -> XMLParserType: ...\n    def install(self, parser: XMLParserType) -> None: ...\n    def start_namespace_decl_handler(self, prefix: str | None, uri: str) -> None: ...\n    def start_element_handler(self, name: str, attributes: list[str]) -> None: ...\n    def end_element_handler(self, name: str) -> None: ...  # only exists if __debug__\n\nclass ExpatBuilderNS(Namespaces, ExpatBuilder): ...\nclass FragmentBuilderNS(Namespaces, FragmentBuilder): ...\nclass ParseEscape(Exception): ...\n\nclass InternalSubsetExtractor(ExpatBuilder):\n    subset: str | list[str] | None = None\n    def getSubset(self) -> str: ...\n    def parseFile(self, file: SupportsRead[ReadableBuffer | str]) -> None: ...  # type: ignore[override]\n    def parseString(self, string: str | ReadableBuffer) -> None: ...  # type: ignore[override]\n    def start_doctype_decl_handler(  # type: ignore[override]\n        self, name: str, publicId: str | None, systemId: str | None, has_internal_subset: bool\n    ) -> None: ...\n    def end_doctype_decl_handler(self) -> NoReturn: ...\n    def start_element_handler(self, name: str, attrs: list[str]) -> NoReturn: ...\n\ndef parse(file: str | SupportsRead[ReadableBuffer | str], namespaces: bool = True) -> Document: ...\ndef parseString(string: str | ReadableBuffer, namespaces: bool = True) -> Document: ...\ndef parseFragment(file: str | SupportsRead[ReadableBuffer | str], context: Node, namespaces: bool = True) -> DocumentFragment: ...\ndef parseFragmentString(string: str | ReadableBuffer, context: Node, namespaces: bool = True) -> DocumentFragment: ...\ndef makeBuilder(options: Options) -> ExpatBuilderNS | ExpatBuilder: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/dom/minicompat.pyi",
    "content": "from collections.abc import Iterable\nfrom typing import Any, Literal, TypeVar\n\n__all__ = [\"NodeList\", \"EmptyNodeList\", \"StringTypes\", \"defproperty\"]\n\n_T = TypeVar(\"_T\")\n\nStringTypes: tuple[type[str]]\n\nclass NodeList(list[_T]):\n    __slots__ = ()\n    @property\n    def length(self) -> int: ...\n    def item(self, index: int) -> _T | None: ...\n\nclass EmptyNodeList(tuple[()]):\n    __slots__ = ()\n    @property\n    def length(self) -> Literal[0]: ...\n    def item(self, index: int) -> None: ...\n    def __add__(self, other: Iterable[_T]) -> NodeList[_T]: ...  # type: ignore[override]\n    def __radd__(self, other: Iterable[_T]) -> NodeList[_T]: ...\n\ndef defproperty(klass: type[Any], name: str, doc: str) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/dom/minidom.pyi",
    "content": "import xml.dom\nfrom _collections_abc import dict_keys, dict_values\nfrom _typeshed import Incomplete, ReadableBuffer, SupportsRead, SupportsWrite\nfrom collections.abc import Iterable, Sequence\nfrom types import TracebackType\nfrom typing import Any, ClassVar, Generic, Literal, NoReturn, Protocol, TypeVar, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\nfrom xml.dom.minicompat import EmptyNodeList, NodeList\nfrom xml.dom.xmlbuilder import DocumentLS, DOMImplementationLS\nfrom xml.sax.xmlreader import XMLReader\n\n_NSName: TypeAlias = tuple[str | None, str]\n\n# Entity can also have children, but it's not implemented the same way as the\n# others, so is deliberately omitted here.\n_NodesWithChildren: TypeAlias = DocumentFragment | Attr | Element | Document\n_NodesThatAreChildren: TypeAlias = CDATASection | Comment | DocumentType | Element | Notation | ProcessingInstruction | Text\n\n_AttrChildren: TypeAlias = Text  # Also EntityReference, but we don't implement it\n_ElementChildren: TypeAlias = Element | ProcessingInstruction | Comment | Text | CDATASection\n_EntityChildren: TypeAlias = Text  # I think; documentation is a little unclear\n_DocumentFragmentChildren: TypeAlias = Element | Text | CDATASection | ProcessingInstruction | Comment | Notation\n_DocumentChildren: TypeAlias = Comment | DocumentType | Element | ProcessingInstruction\n\n_N = TypeVar(\"_N\", bound=Node)\n_ChildNodeVar = TypeVar(\"_ChildNodeVar\", bound=_NodesThatAreChildren)\n_ChildNodePlusFragmentVar = TypeVar(\"_ChildNodePlusFragmentVar\", bound=_NodesThatAreChildren | DocumentFragment)\n_DocumentChildrenVar = TypeVar(\"_DocumentChildrenVar\", bound=_DocumentChildren)\n_ImportableNodeVar = TypeVar(\n    \"_ImportableNodeVar\",\n    bound=DocumentFragment\n    | Attr\n    | Element\n    | ProcessingInstruction\n    | CharacterData\n    | Text\n    | Comment\n    | CDATASection\n    | Entity\n    | Notation,\n)\n\n@type_check_only\nclass _DOMErrorHandler(Protocol):\n    def handleError(self, error: Exception) -> bool: ...\n\n@type_check_only\nclass _UserDataHandler(Protocol):\n    def handle(self, operation: int, key: str, data: Any, src: Node, dst: Node) -> None: ...\n\ndef parse(\n    file: str | SupportsRead[ReadableBuffer | str], parser: XMLReader | None = None, bufsize: int | None = None\n) -> Document: ...\ndef parseString(string: str | ReadableBuffer, parser: XMLReader | None = None) -> Document: ...\n@overload\ndef getDOMImplementation(features: None = None) -> DOMImplementation: ...\n@overload\ndef getDOMImplementation(features: str | Iterable[tuple[str, str | None]]) -> DOMImplementation | None: ...\n\nclass Node(xml.dom.Node):\n    parentNode: _NodesWithChildren | Entity | None\n    ownerDocument: Document | None\n    nextSibling: _NodesThatAreChildren | None\n    previousSibling: _NodesThatAreChildren | None\n    namespaceURI: str | None  # non-null only for Element and Attr\n    prefix: str | None  # non-null only for NS Element and Attr\n\n    # These aren't defined on Node, but they exist on all Node subclasses\n    # and various methods of Node require them to exist.\n    childNodes: (\n        NodeList[_DocumentFragmentChildren]\n        | NodeList[_AttrChildren]\n        | NodeList[_ElementChildren]\n        | NodeList[_DocumentChildren]\n        | NodeList[_EntityChildren]\n        | EmptyNodeList\n    )\n    nodeType: ClassVar[Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]\n    nodeName: str | None  # only possibly None on DocumentType\n\n    # Not defined on Node, but exist on all Node subclasses.\n    nodeValue: str | None  # non-null for Attr, ProcessingInstruction, Text, Comment, and CDATASection\n    attributes: NamedNodeMap | None  # non-null only for Element\n\n    @property\n    def firstChild(self) -> _NodesThatAreChildren | None: ...\n    @property\n    def lastChild(self) -> _NodesThatAreChildren | None: ...\n    @property\n    def localName(self) -> str | None: ...  # non-null only for Element and Attr\n    def __bool__(self) -> Literal[True]: ...\n    @overload\n    def toxml(self, encoding: str, standalone: bool | None = None) -> bytes: ...\n    @overload\n    def toxml(self, encoding: None = None, standalone: bool | None = None) -> str: ...\n    @overload\n    def toprettyxml(\n        self,\n        indent: str = \"\\t\",\n        newl: str = \"\\n\",\n        # Handle any case where encoding is not provided or where it is passed with None\n        encoding: None = None,\n        standalone: bool | None = None,\n    ) -> str: ...\n    @overload\n    def toprettyxml(\n        self,\n        indent: str,\n        newl: str,\n        # Handle cases where encoding is passed as str *positionally*\n        encoding: str,\n        standalone: bool | None = None,\n    ) -> bytes: ...\n    @overload\n    def toprettyxml(\n        self,\n        indent: str = \"\\t\",\n        newl: str = \"\\n\",\n        # Handle all cases where encoding is passed as a keyword argument; because standalone\n        # comes after, it will also have to be a keyword arg if encoding is\n        *,\n        encoding: str,\n        standalone: bool | None = None,\n    ) -> bytes: ...\n    def hasChildNodes(self) -> bool: ...\n    def insertBefore(  # type: ignore[misc]\n        self: _NodesWithChildren,  # pyright: ignore[reportGeneralTypeIssues]\n        newChild: _ChildNodePlusFragmentVar,\n        refChild: _NodesThatAreChildren | None,\n    ) -> _ChildNodePlusFragmentVar: ...\n    def appendChild(  # type: ignore[misc]\n        self: _NodesWithChildren, node: _ChildNodePlusFragmentVar  # pyright: ignore[reportGeneralTypeIssues]\n    ) -> _ChildNodePlusFragmentVar: ...\n    @overload\n    def replaceChild(  # type: ignore[misc]\n        self: _NodesWithChildren, newChild: DocumentFragment, oldChild: _ChildNodeVar\n    ) -> _ChildNodeVar | DocumentFragment: ...\n    @overload\n    def replaceChild(  # type: ignore[misc]\n        self: _NodesWithChildren, newChild: _NodesThatAreChildren, oldChild: _ChildNodeVar\n    ) -> _ChildNodeVar | None: ...\n    def removeChild(self: _NodesWithChildren, oldChild: _ChildNodeVar) -> _ChildNodeVar: ...  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    def normalize(self: _NodesWithChildren) -> None: ...  # type: ignore[misc]  # pyright: ignore[reportGeneralTypeIssues]\n    def cloneNode(self, deep: bool) -> Self | None: ...\n    def isSupported(self, feature: str, version: str | None) -> bool: ...\n    def isSameNode(self, other: Node) -> bool: ...\n    def getInterface(self, feature: str) -> Self | None: ...\n    def getUserData(self, key: str) -> Any | None: ...\n    def setUserData(self, key: str, data: Any, handler: _UserDataHandler) -> Any: ...\n    def unlink(self) -> None: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(self, et: type[BaseException] | None, ev: BaseException | None, tb: TracebackType | None) -> None: ...\n\n_DFChildrenVar = TypeVar(\"_DFChildrenVar\", bound=_DocumentFragmentChildren)\n_DFChildrenPlusFragment = TypeVar(\"_DFChildrenPlusFragment\", bound=_DocumentFragmentChildren | DocumentFragment)\n\nclass DocumentFragment(Node):\n    nodeType: ClassVar[Literal[11]]\n    nodeName: Literal[\"#document-fragment\"]\n    nodeValue: None\n    attributes: None\n\n    parentNode: None\n    nextSibling: None\n    previousSibling: None\n    childNodes: NodeList[_DocumentFragmentChildren]\n    @property\n    def firstChild(self) -> _DocumentFragmentChildren | None: ...\n    @property\n    def lastChild(self) -> _DocumentFragmentChildren | None: ...\n\n    namespaceURI: None\n    prefix: None\n    @property\n    def localName(self) -> None: ...\n    def __init__(self) -> None: ...\n    def insertBefore(  # type: ignore[override]\n        self, newChild: _DFChildrenPlusFragment, refChild: _DocumentFragmentChildren | None\n    ) -> _DFChildrenPlusFragment: ...\n    def appendChild(self, node: _DFChildrenPlusFragment) -> _DFChildrenPlusFragment: ...  # type: ignore[override]\n    @overload  # type: ignore[override]\n    def replaceChild(self, newChild: DocumentFragment, oldChild: _DFChildrenVar) -> _DFChildrenVar | DocumentFragment: ...\n    @overload\n    def replaceChild(self, newChild: _DocumentFragmentChildren, oldChild: _DFChildrenVar) -> _DFChildrenVar | None: ...  # type: ignore[override]\n    def removeChild(self, oldChild: _DFChildrenVar) -> _DFChildrenVar: ...  # type: ignore[override]\n\n_AttrChildrenVar = TypeVar(\"_AttrChildrenVar\", bound=_AttrChildren)\n_AttrChildrenPlusFragment = TypeVar(\"_AttrChildrenPlusFragment\", bound=_AttrChildren | DocumentFragment)\n\nclass Attr(Node):\n    __slots__ = (\"_name\", \"_value\", \"namespaceURI\", \"_prefix\", \"childNodes\", \"_localName\", \"ownerDocument\", \"ownerElement\")\n    nodeType: ClassVar[Literal[2]]\n    nodeName: str  # same as Attr.name\n    nodeValue: str  # same as Attr.value\n    attributes: None\n\n    parentNode: None\n    nextSibling: None\n    previousSibling: None\n    childNodes: NodeList[_AttrChildren]\n    @property\n    def firstChild(self) -> _AttrChildren | None: ...\n    @property\n    def lastChild(self) -> _AttrChildren | None: ...\n\n    namespaceURI: str | None\n    prefix: str | None\n    @property\n    def localName(self) -> str: ...\n\n    name: str\n    value: str\n    specified: bool\n    ownerElement: Element | None\n\n    def __init__(\n        self, qName: str, namespaceURI: str | None = None, localName: str | None = None, prefix: str | None = None\n    ) -> None: ...\n    def unlink(self) -> None: ...\n    @property\n    def isId(self) -> bool: ...\n    @property\n    def schemaType(self) -> TypeInfo: ...\n    def insertBefore(self, newChild: _AttrChildrenPlusFragment, refChild: _AttrChildren | None) -> _AttrChildrenPlusFragment: ...  # type: ignore[override]\n    def appendChild(self, node: _AttrChildrenPlusFragment) -> _AttrChildrenPlusFragment: ...  # type: ignore[override]\n    @overload  # type: ignore[override]\n    def replaceChild(self, newChild: DocumentFragment, oldChild: _AttrChildrenVar) -> _AttrChildrenVar | DocumentFragment: ...\n    @overload\n    def replaceChild(self, newChild: _AttrChildren, oldChild: _AttrChildrenVar) -> _AttrChildrenVar | None: ...  # type: ignore[override]\n    def removeChild(self, oldChild: _AttrChildrenVar) -> _AttrChildrenVar: ...  # type: ignore[override]\n\n# In the DOM, this interface isn't specific to Attr, but our implementation is\n# because that's the only place we use it.\nclass NamedNodeMap:\n    __slots__ = (\"_attrs\", \"_attrsNS\", \"_ownerElement\")\n    def __init__(self, attrs: dict[str, Attr], attrsNS: dict[_NSName, Attr], ownerElement: Element) -> None: ...\n    @property\n    def length(self) -> int: ...\n    def item(self, index: int) -> Node | None: ...\n    def items(self) -> list[tuple[str, str]]: ...\n    def itemsNS(self) -> list[tuple[_NSName, str]]: ...\n    def __contains__(self, key: str | _NSName) -> bool: ...\n    def keys(self) -> dict_keys[str, Attr]: ...\n    def keysNS(self) -> dict_keys[_NSName, Attr]: ...\n    def values(self) -> dict_values[str, Attr]: ...\n    def get(self, name: str, value: Attr | None = None) -> Attr | None: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __len__(self) -> int: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __ge__(self, other: NamedNodeMap) -> bool: ...\n    def __gt__(self, other: NamedNodeMap) -> bool: ...\n    def __le__(self, other: NamedNodeMap) -> bool: ...\n    def __lt__(self, other: NamedNodeMap) -> bool: ...\n    def __getitem__(self, attname_or_tuple: _NSName | str) -> Attr: ...\n    def __setitem__(self, attname: str, value: Attr | str) -> None: ...\n    def getNamedItem(self, name: str) -> Attr | None: ...\n    def getNamedItemNS(self, namespaceURI: str | None, localName: str) -> Attr | None: ...\n    def removeNamedItem(self, name: str) -> Attr: ...\n    def removeNamedItemNS(self, namespaceURI: str | None, localName: str) -> Attr: ...\n    def setNamedItem(self, node: Attr) -> Attr | None: ...\n    def setNamedItemNS(self, node: Attr) -> Attr | None: ...\n    def __delitem__(self, attname_or_tuple: _NSName | str) -> None: ...\n\nAttributeList = NamedNodeMap\n\nclass TypeInfo:\n    __slots__ = (\"namespace\", \"name\")\n    namespace: str | None\n    name: str | None\n    def __init__(self, namespace: Incomplete | None, name: str | None) -> None: ...\n\n_ElementChildrenVar = TypeVar(\"_ElementChildrenVar\", bound=_ElementChildren)\n_ElementChildrenPlusFragment = TypeVar(\"_ElementChildrenPlusFragment\", bound=_ElementChildren | DocumentFragment)\n\nclass Element(Node):\n    __slots__ = (\n        \"ownerDocument\",\n        \"parentNode\",\n        \"tagName\",\n        \"nodeName\",\n        \"prefix\",\n        \"namespaceURI\",\n        \"_localName\",\n        \"childNodes\",\n        \"_attrs\",\n        \"_attrsNS\",\n        \"nextSibling\",\n        \"previousSibling\",\n    )\n    nodeType: ClassVar[Literal[1]]\n    nodeName: str  # same as Element.tagName\n    nodeValue: None\n    @property\n    def attributes(self) -> NamedNodeMap: ...  # type: ignore[override]\n\n    parentNode: Document | Element | DocumentFragment | None\n    nextSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None\n    previousSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None\n    childNodes: NodeList[_ElementChildren]\n    @property\n    def firstChild(self) -> _ElementChildren | None: ...\n    @property\n    def lastChild(self) -> _ElementChildren | None: ...\n\n    namespaceURI: str | None\n    prefix: str | None\n    @property\n    def localName(self) -> str: ...\n\n    schemaType: TypeInfo\n    tagName: str\n\n    def __init__(\n        self, tagName: str, namespaceURI: str | None = None, prefix: str | None = None, localName: str | None = None\n    ) -> None: ...\n    def unlink(self) -> None: ...\n    def getAttribute(self, attname: str) -> str: ...\n    def getAttributeNS(self, namespaceURI: str | None, localName: str) -> str: ...\n    def setAttribute(self, attname: str, value: str) -> None: ...\n    def setAttributeNS(self, namespaceURI: str | None, qualifiedName: str, value: str) -> None: ...\n    def getAttributeNode(self, attrname: str) -> Attr | None: ...\n    def getAttributeNodeNS(self, namespaceURI: str | None, localName: str) -> Attr | None: ...\n    def setAttributeNode(self, attr: Attr) -> Attr | None: ...\n    setAttributeNodeNS = setAttributeNode\n    def removeAttribute(self, name: str) -> None: ...\n    def removeAttributeNS(self, namespaceURI: str | None, localName: str) -> None: ...\n    def removeAttributeNode(self, node: Attr) -> Attr: ...\n    removeAttributeNodeNS = removeAttributeNode\n    def hasAttribute(self, name: str) -> bool: ...\n    def hasAttributeNS(self, namespaceURI: str | None, localName: str) -> bool: ...\n    def getElementsByTagName(self, name: str) -> NodeList[Element]: ...\n    def getElementsByTagNameNS(self, namespaceURI: str | None, localName: str) -> NodeList[Element]: ...\n    def writexml(self, writer: SupportsWrite[str], indent: str = \"\", addindent: str = \"\", newl: str = \"\") -> None: ...\n    def hasAttributes(self) -> bool: ...\n    def setIdAttribute(self, name: str) -> None: ...\n    def setIdAttributeNS(self, namespaceURI: str | None, localName: str) -> None: ...\n    def setIdAttributeNode(self, idAttr: Attr) -> None: ...\n    def insertBefore(  # type: ignore[override]\n        self, newChild: _ElementChildrenPlusFragment, refChild: _ElementChildren | None\n    ) -> _ElementChildrenPlusFragment: ...\n    def appendChild(self, node: _ElementChildrenPlusFragment) -> _ElementChildrenPlusFragment: ...  # type: ignore[override]\n    @overload  # type: ignore[override]\n    def replaceChild(\n        self, newChild: DocumentFragment, oldChild: _ElementChildrenVar\n    ) -> _ElementChildrenVar | DocumentFragment: ...\n    @overload\n    def replaceChild(self, newChild: _ElementChildren, oldChild: _ElementChildrenVar) -> _ElementChildrenVar | None: ...  # type: ignore[override]\n    def removeChild(self, oldChild: _ElementChildrenVar) -> _ElementChildrenVar: ...  # type: ignore[override]\n\nclass Childless:\n    __slots__ = ()\n    attributes: None\n    childNodes: EmptyNodeList\n    @property\n    def firstChild(self) -> None: ...\n    @property\n    def lastChild(self) -> None: ...\n    def appendChild(self, node: _NodesThatAreChildren | DocumentFragment) -> NoReturn: ...\n    def hasChildNodes(self) -> Literal[False]: ...\n    def insertBefore(\n        self, newChild: _NodesThatAreChildren | DocumentFragment, refChild: _NodesThatAreChildren | None\n    ) -> NoReturn: ...\n    def removeChild(self, oldChild: _NodesThatAreChildren) -> NoReturn: ...\n    def normalize(self) -> None: ...\n    def replaceChild(self, newChild: _NodesThatAreChildren | DocumentFragment, oldChild: _NodesThatAreChildren) -> NoReturn: ...\n\nclass ProcessingInstruction(Childless, Node):\n    __slots__ = (\"target\", \"data\")\n    nodeType: ClassVar[Literal[7]]\n    nodeName: str  # same as ProcessingInstruction.target\n    nodeValue: str  # same as ProcessingInstruction.data\n    attributes: None\n\n    parentNode: Document | Element | DocumentFragment | None\n    nextSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None\n    previousSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None\n    childNodes: EmptyNodeList\n    @property\n    def firstChild(self) -> None: ...\n    @property\n    def lastChild(self) -> None: ...\n\n    namespaceURI: None\n    prefix: None\n    @property\n    def localName(self) -> None: ...\n\n    target: str\n    data: str\n\n    def __init__(self, target: str, data: str) -> None: ...\n    def writexml(self, writer: SupportsWrite[str], indent: str = \"\", addindent: str = \"\", newl: str = \"\") -> None: ...\n\nclass CharacterData(Childless, Node):\n    __slots__ = (\"_data\", \"ownerDocument\", \"parentNode\", \"previousSibling\", \"nextSibling\")\n    nodeValue: str\n    attributes: None\n\n    childNodes: EmptyNodeList\n    nextSibling: _NodesThatAreChildren | None\n    previousSibling: _NodesThatAreChildren | None\n\n    @property\n    def localName(self) -> None: ...\n\n    ownerDocument: Document | None\n    data: str\n\n    def __init__(self) -> None: ...\n    @property\n    def length(self) -> int: ...\n    def __len__(self) -> int: ...\n    def substringData(self, offset: int, count: int) -> str: ...\n    def appendData(self, arg: str) -> None: ...\n    def insertData(self, offset: int, arg: str) -> None: ...\n    def deleteData(self, offset: int, count: int) -> None: ...\n    def replaceData(self, offset: int, count: int, arg: str) -> None: ...\n\nclass Text(CharacterData):\n    __slots__ = ()\n    nodeType: ClassVar[Literal[3]]\n    nodeName: Literal[\"#text\"]\n    nodeValue: str  # same as CharacterData.data, the content of the text node\n    attributes: None\n\n    parentNode: Attr | Element | DocumentFragment | None\n    nextSibling: _DocumentFragmentChildren | _ElementChildren | _AttrChildren | None\n    previousSibling: _DocumentFragmentChildren | _ElementChildren | _AttrChildren | None\n    childNodes: EmptyNodeList\n    @property\n    def firstChild(self) -> None: ...\n    @property\n    def lastChild(self) -> None: ...\n\n    namespaceURI: None\n    prefix: None\n    @property\n    def localName(self) -> None: ...\n\n    data: str\n    def splitText(self, offset: int) -> Self: ...\n    def writexml(self, writer: SupportsWrite[str], indent: str = \"\", addindent: str = \"\", newl: str = \"\") -> None: ...\n    def replaceWholeText(self, content: str) -> Self | None: ...\n    @property\n    def isWhitespaceInElementContent(self) -> bool: ...\n    @property\n    def wholeText(self) -> str: ...\n\nclass Comment(CharacterData):\n    nodeType: ClassVar[Literal[8]]\n    nodeName: Literal[\"#comment\"]\n    nodeValue: str  # same as CharacterData.data, the content of the comment\n    attributes: None\n\n    parentNode: Document | Element | DocumentFragment | None\n    nextSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None\n    previousSibling: _DocumentChildren | _ElementChildren | _DocumentFragmentChildren | None\n    childNodes: EmptyNodeList\n    @property\n    def firstChild(self) -> None: ...\n    @property\n    def lastChild(self) -> None: ...\n\n    namespaceURI: None\n    prefix: None\n    @property\n    def localName(self) -> None: ...\n    def __init__(self, data: str) -> None: ...\n    def writexml(self, writer: SupportsWrite[str], indent: str = \"\", addindent: str = \"\", newl: str = \"\") -> None: ...\n\nclass CDATASection(Text):\n    __slots__ = ()\n    nodeType: ClassVar[Literal[4]]  # type: ignore[assignment]\n    nodeName: Literal[\"#cdata-section\"]  # type: ignore[assignment]\n    nodeValue: str  # same as CharacterData.data, the content of the CDATA Section\n    attributes: None\n\n    parentNode: Element | DocumentFragment | None\n    nextSibling: _DocumentFragmentChildren | _ElementChildren | None\n    previousSibling: _DocumentFragmentChildren | _ElementChildren | None\n\n    def writexml(self, writer: SupportsWrite[str], indent: str = \"\", addindent: str = \"\", newl: str = \"\") -> None: ...\n\nclass ReadOnlySequentialNamedNodeMap(Generic[_N]):\n    __slots__ = (\"_seq\",)\n    def __init__(self, seq: Sequence[_N] = ()) -> None: ...\n    def __len__(self) -> int: ...\n    def getNamedItem(self, name: str) -> _N | None: ...\n    def getNamedItemNS(self, namespaceURI: str | None, localName: str) -> _N | None: ...\n    def __getitem__(self, name_or_tuple: str | _NSName) -> _N | None: ...\n    def item(self, index: int) -> _N | None: ...\n    def removeNamedItem(self, name: str) -> NoReturn: ...\n    def removeNamedItemNS(self, namespaceURI: str | None, localName: str) -> NoReturn: ...\n    def setNamedItem(self, node: Node) -> NoReturn: ...\n    def setNamedItemNS(self, node: Node) -> NoReturn: ...\n    @property\n    def length(self) -> int: ...\n\nclass Identified:\n    __slots__ = (\"publicId\", \"systemId\")\n    publicId: str | None\n    systemId: str | None\n\nclass DocumentType(Identified, Childless, Node):\n    nodeType: ClassVar[Literal[10]]\n    nodeName: str | None  # same as DocumentType.name\n    nodeValue: None\n    attributes: None\n\n    parentNode: Document | None\n    nextSibling: _DocumentChildren | None\n    previousSibling: _DocumentChildren | None\n    childNodes: EmptyNodeList\n    @property\n    def firstChild(self) -> None: ...\n    @property\n    def lastChild(self) -> None: ...\n\n    namespaceURI: None\n    prefix: None\n    @property\n    def localName(self) -> None: ...\n\n    name: str | None\n    internalSubset: str | None\n    entities: ReadOnlySequentialNamedNodeMap[Entity]\n    notations: ReadOnlySequentialNamedNodeMap[Notation]\n\n    def __init__(self, qualifiedName: str | None) -> None: ...\n    def cloneNode(self, deep: bool) -> DocumentType | None: ...\n    def writexml(self, writer: SupportsWrite[str], indent: str = \"\", addindent: str = \"\", newl: str = \"\") -> None: ...\n\nclass Entity(Identified, Node):\n    nodeType: ClassVar[Literal[6]]\n    nodeName: str  # entity name\n    nodeValue: None\n    attributes: None\n\n    parentNode: None\n    nextSibling: None\n    previousSibling: None\n    childNodes: NodeList[_EntityChildren]\n    @property\n    def firstChild(self) -> _EntityChildren | None: ...\n    @property\n    def lastChild(self) -> _EntityChildren | None: ...\n\n    namespaceURI: None\n    prefix: None\n    @property\n    def localName(self) -> None: ...\n\n    actualEncoding: str | None\n    encoding: str | None\n    version: str | None\n    notationName: str | None\n\n    def __init__(self, name: str, publicId: str | None, systemId: str | None, notation: str | None) -> None: ...\n    def appendChild(self, newChild: _EntityChildren) -> NoReturn: ...  # type: ignore[override]\n    def insertBefore(self, newChild: _EntityChildren, refChild: _EntityChildren | None) -> NoReturn: ...  # type: ignore[override]\n    def removeChild(self, oldChild: _EntityChildren) -> NoReturn: ...  # type: ignore[override]\n    def replaceChild(self, newChild: _EntityChildren, oldChild: _EntityChildren) -> NoReturn: ...  # type: ignore[override]\n\nclass Notation(Identified, Childless, Node):\n    nodeType: ClassVar[Literal[12]]\n    nodeName: str  # notation name\n    nodeValue: None\n    attributes: None\n\n    parentNode: DocumentFragment | None\n    nextSibling: _DocumentFragmentChildren | None\n    previousSibling: _DocumentFragmentChildren | None\n    childNodes: EmptyNodeList\n    @property\n    def firstChild(self) -> None: ...\n    @property\n    def lastChild(self) -> None: ...\n\n    namespaceURI: None\n    prefix: None\n    @property\n    def localName(self) -> None: ...\n    def __init__(self, name: str, publicId: str | None, systemId: str | None) -> None: ...\n\nclass DOMImplementation(DOMImplementationLS):\n    def hasFeature(self, feature: str, version: str | None) -> bool: ...\n    def createDocument(self, namespaceURI: str | None, qualifiedName: str | None, doctype: DocumentType | None) -> Document: ...\n    def createDocumentType(self, qualifiedName: str | None, publicId: str | None, systemId: str | None) -> DocumentType: ...\n    def getInterface(self, feature: str) -> Self | None: ...\n\nclass ElementInfo:\n    __slots__ = (\"tagName\",)\n    tagName: str\n    def __init__(self, name: str) -> None: ...\n    def getAttributeType(self, aname: str) -> TypeInfo: ...\n    def getAttributeTypeNS(self, namespaceURI: str | None, localName: str) -> TypeInfo: ...\n    def isElementContent(self) -> bool: ...\n    def isEmpty(self) -> bool: ...\n    def isId(self, aname: str) -> bool: ...\n    def isIdNS(self, namespaceURI: str | None, localName: str) -> bool: ...\n\n_DocumentChildrenPlusFragment = TypeVar(\"_DocumentChildrenPlusFragment\", bound=_DocumentChildren | DocumentFragment)\n\nclass Document(Node, DocumentLS):\n    __slots__ = (\"_elem_info\", \"doctype\", \"_id_search_stack\", \"childNodes\", \"_id_cache\")\n    nodeType: ClassVar[Literal[9]]\n    nodeName: Literal[\"#document\"]\n    nodeValue: None\n    attributes: None\n\n    parentNode: None\n    previousSibling: None\n    nextSibling: None\n    childNodes: NodeList[_DocumentChildren]\n    @property\n    def firstChild(self) -> _DocumentChildren | None: ...\n    @property\n    def lastChild(self) -> _DocumentChildren | None: ...\n\n    namespaceURI: None\n    prefix: None\n    @property\n    def localName(self) -> None: ...\n\n    implementation: DOMImplementation\n    actualEncoding: str | None\n    encoding: str | None\n    standalone: bool | None\n    version: str | None\n    strictErrorChecking: bool\n    errorHandler: _DOMErrorHandler | None\n    documentURI: str | None\n    doctype: DocumentType | None\n    documentElement: Element | None\n\n    def __init__(self) -> None: ...\n    def appendChild(self, node: _DocumentChildrenVar) -> _DocumentChildrenVar: ...  # type: ignore[override]\n    def removeChild(self, oldChild: _DocumentChildrenVar) -> _DocumentChildrenVar: ...  # type: ignore[override]\n    def unlink(self) -> None: ...\n    def cloneNode(self, deep: bool) -> Document | None: ...\n    def createDocumentFragment(self) -> DocumentFragment: ...\n    def createElement(self, tagName: str) -> Element: ...\n    def createTextNode(self, data: str) -> Text: ...\n    def createCDATASection(self, data: str) -> CDATASection: ...\n    def createComment(self, data: str) -> Comment: ...\n    def createProcessingInstruction(self, target: str, data: str) -> ProcessingInstruction: ...\n    def createAttribute(self, qName: str) -> Attr: ...\n    def createElementNS(self, namespaceURI: str | None, qualifiedName: str) -> Element: ...\n    def createAttributeNS(self, namespaceURI: str | None, qualifiedName: str) -> Attr: ...\n    def getElementById(self, id: str) -> Element | None: ...\n    def getElementsByTagName(self, name: str) -> NodeList[Element]: ...\n    def getElementsByTagNameNS(self, namespaceURI: str | None, localName: str) -> NodeList[Element]: ...\n    def isSupported(self, feature: str, version: str | None) -> bool: ...\n    def importNode(self, node: _ImportableNodeVar, deep: bool) -> _ImportableNodeVar: ...\n    def writexml(\n        self,\n        writer: SupportsWrite[str],\n        indent: str = \"\",\n        addindent: str = \"\",\n        newl: str = \"\",\n        encoding: str | None = None,\n        standalone: bool | None = None,\n    ) -> None: ...\n    @overload\n    def renameNode(self, n: Element, namespaceURI: str, name: str) -> Element: ...\n    @overload\n    def renameNode(self, n: Attr, namespaceURI: str, name: str) -> Attr: ...\n    @overload\n    def renameNode(self, n: Element | Attr, namespaceURI: str, name: str) -> Element | Attr: ...\n    def insertBefore(\n        self, newChild: _DocumentChildrenPlusFragment, refChild: _DocumentChildren | None  # type: ignore[override]\n    ) -> _DocumentChildrenPlusFragment: ...\n    @overload  # type: ignore[override]\n    def replaceChild(\n        self, newChild: DocumentFragment, oldChild: _DocumentChildrenVar\n    ) -> _DocumentChildrenVar | DocumentFragment: ...\n    @overload\n    def replaceChild(self, newChild: _DocumentChildren, oldChild: _DocumentChildrenVar) -> _DocumentChildrenVar | None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/dom/pulldom.pyi",
    "content": "import sys\nfrom _typeshed import Incomplete, Unused\nfrom collections.abc import MutableSequence, Sequence\nfrom typing import Final, Literal, NoReturn\nfrom typing_extensions import Self, TypeAlias\nfrom xml.dom.minidom import Comment, Document, DOMImplementation, Element, ProcessingInstruction, Text\nfrom xml.sax import _SupportsReadClose\nfrom xml.sax.handler import ContentHandler\nfrom xml.sax.xmlreader import AttributesImpl, AttributesNSImpl, Locator, XMLReader\n\nSTART_ELEMENT: Final = \"START_ELEMENT\"\nEND_ELEMENT: Final = \"END_ELEMENT\"\nCOMMENT: Final = \"COMMENT\"\nSTART_DOCUMENT: Final = \"START_DOCUMENT\"\nEND_DOCUMENT: Final = \"END_DOCUMENT\"\nPROCESSING_INSTRUCTION: Final = \"PROCESSING_INSTRUCTION\"\nIGNORABLE_WHITESPACE: Final = \"IGNORABLE_WHITESPACE\"\nCHARACTERS: Final = \"CHARACTERS\"\n\n_NSName: TypeAlias = tuple[str | None, str]\n_DocumentFactory: TypeAlias = DOMImplementation | None\n\n_Event: TypeAlias = (\n    tuple[Literal[\"START_ELEMENT\"], Element]\n    | tuple[Literal[\"END_ELEMENT\"], Element]\n    | tuple[Literal[\"COMMENT\"], Comment]\n    | tuple[Literal[\"START_DOCUMENT\"], Document]\n    | tuple[Literal[\"END_DOCUMENT\"], Document]\n    | tuple[Literal[\"PROCESSING_INSTRUCTION\"], ProcessingInstruction]\n    | tuple[Literal[\"IGNORABLE_WHITESPACE\"], Text]\n    | tuple[Literal[\"CHARACTERS\"], Text]\n)\n\nclass PullDOM(ContentHandler):\n    document: Document | None\n    documentFactory: _DocumentFactory\n\n    # firstEvent is a list of length 2\n    # firstEvent[0] is always None\n    # firstEvent[1] is None prior to any events, after which it's a\n    # list of length 2, where the first item is of type _Event\n    # and the second item is None.\n    firstEvent: list[Incomplete]\n\n    # lastEvent is also a list of length 2. The second item is always None,\n    # and the first item is of type _Event\n    # This is a slight lie: The second item is sometimes temporarily what was just\n    # described for the type of lastEvent, after which lastEvent is always updated\n    # with `self.lastEvent = self.lastEvent[1]`.\n    lastEvent: list[Incomplete]\n\n    elementStack: MutableSequence[Element | Document]\n    pending_events: (\n        list[Sequence[tuple[Literal[\"COMMENT\"], str] | tuple[Literal[\"PROCESSING_INSTRUCTION\"], str, str] | None]] | None\n    )\n    def __init__(self, documentFactory: _DocumentFactory = None) -> None: ...\n    def pop(self) -> Element | Document: ...\n    def setDocumentLocator(self, locator: Locator) -> None: ...\n    def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ...\n    def endPrefixMapping(self, prefix: str | None) -> None: ...\n    def startElementNS(self, name: _NSName, tagName: str | None, attrs: AttributesNSImpl) -> None: ...\n    def endElementNS(self, name: _NSName, tagName: str | None) -> None: ...\n    def startElement(self, name: str, attrs: AttributesImpl) -> None: ...\n    def endElement(self, name: str) -> None: ...\n    def comment(self, s: str) -> None: ...\n    def processingInstruction(self, target: str, data: str) -> None: ...\n    def ignorableWhitespace(self, chars: str) -> None: ...\n    def characters(self, chars: str) -> None: ...\n    def startDocument(self) -> None: ...\n    def buildDocument(self, uri: str | None, tagname: str | None) -> Element: ...\n    def endDocument(self) -> None: ...\n    def clear(self) -> None: ...\n\nclass ErrorHandler:\n    def warning(self, exception: BaseException) -> None: ...\n    def error(self, exception: BaseException) -> NoReturn: ...\n    def fatalError(self, exception: BaseException) -> NoReturn: ...\n\nclass DOMEventStream:\n    stream: _SupportsReadClose[bytes] | _SupportsReadClose[str]\n    parser: XMLReader  # Set to none after .clear() is called\n    bufsize: int\n    pulldom: PullDOM\n    def __init__(self, stream: _SupportsReadClose[bytes] | _SupportsReadClose[str], parser: XMLReader, bufsize: int) -> None: ...\n    if sys.version_info < (3, 11):\n        def __getitem__(self, pos: Unused) -> _Event: ...\n\n    def __next__(self) -> _Event: ...\n    def __iter__(self) -> Self: ...\n    def getEvent(self) -> _Event | None: ...\n    def expandNode(self, node: Document) -> None: ...\n    def reset(self) -> None: ...\n    def clear(self) -> None: ...\n\nclass SAX2DOM(PullDOM):\n    def startElementNS(self, name: _NSName, tagName: str | None, attrs: AttributesNSImpl) -> None: ...\n    def startElement(self, name: str, attrs: AttributesImpl) -> None: ...\n    def processingInstruction(self, target: str, data: str) -> None: ...\n    def ignorableWhitespace(self, chars: str) -> None: ...\n    def characters(self, chars: str) -> None: ...\n\ndefault_bufsize: Final[int]\n\ndef parse(\n    stream_or_string: str | _SupportsReadClose[bytes] | _SupportsReadClose[str],\n    parser: XMLReader | None = None,\n    bufsize: int | None = None,\n) -> DOMEventStream: ...\ndef parseString(string: str, parser: XMLReader | None = None) -> DOMEventStream: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/dom/xmlbuilder.pyi",
    "content": "from _typeshed import SupportsRead\nfrom typing import Any, Final, Literal, NoReturn\nfrom xml.dom.minidom import Document, Node, _DOMErrorHandler\n\n__all__ = [\"DOMBuilder\", \"DOMEntityResolver\", \"DOMInputSource\"]\n\nclass Options:\n    namespaces: int\n    namespace_declarations: bool\n    validation: bool\n    external_parameter_entities: bool\n    external_general_entities: bool\n    external_dtd_subset: bool\n    validate_if_schema: bool\n    validate: bool\n    datatype_normalization: bool\n    create_entity_ref_nodes: bool\n    entities: bool\n    whitespace_in_element_content: bool\n    cdata_sections: bool\n    comments: bool\n    charset_overrides_xml_encoding: bool\n    infoset: bool\n    supported_mediatypes_only: bool\n    errorHandler: _DOMErrorHandler | None\n    filter: DOMBuilderFilter | None\n\nclass DOMBuilder:\n    entityResolver: DOMEntityResolver | None\n    errorHandler: _DOMErrorHandler | None\n    filter: DOMBuilderFilter | None\n    ACTION_REPLACE: Final = 1\n    ACTION_APPEND_AS_CHILDREN: Final = 2\n    ACTION_INSERT_AFTER: Final = 3\n    ACTION_INSERT_BEFORE: Final = 4\n    def __init__(self) -> None: ...\n    def setFeature(self, name: str, state: int) -> None: ...\n    def supportsFeature(self, name: str) -> bool: ...\n    def canSetFeature(self, name: str, state: Literal[1, 0]) -> bool: ...\n    # getFeature could return any attribute from an instance of `Options`\n    def getFeature(self, name: str) -> Any: ...\n    def parseURI(self, uri: str) -> Document: ...\n    def parse(self, input: DOMInputSource) -> Document: ...\n    def parseWithContext(self, input: DOMInputSource, cnode: Node, action: Literal[1, 2, 3, 4]) -> NoReturn: ...\n\nclass DOMEntityResolver:\n    __slots__ = (\"_opener\",)\n    def resolveEntity(self, publicId: str | None, systemId: str) -> DOMInputSource: ...\n\nclass DOMInputSource:\n    __slots__ = (\"byteStream\", \"characterStream\", \"stringData\", \"encoding\", \"publicId\", \"systemId\", \"baseURI\")\n    byteStream: SupportsRead[bytes] | None\n    characterStream: SupportsRead[str] | None\n    stringData: str | None\n    encoding: str | None\n    publicId: str | None\n    systemId: str | None\n    baseURI: str | None\n\nclass DOMBuilderFilter:\n    FILTER_ACCEPT: Final = 1\n    FILTER_REJECT: Final = 2\n    FILTER_SKIP: Final = 3\n    FILTER_INTERRUPT: Final = 4\n    whatToShow: int\n    def acceptNode(self, element: Node) -> Literal[1, 2, 3, 4]: ...\n    def startContainer(self, element: Node) -> Literal[1, 2, 3, 4]: ...\n\nclass DocumentLS:\n    async_: bool\n    def abort(self) -> NoReturn: ...\n    def load(self, uri: str) -> NoReturn: ...\n    def loadXML(self, source: str) -> NoReturn: ...\n    def saveXML(self, snode: Node | None) -> str: ...\n\nclass DOMImplementationLS:\n    MODE_SYNCHRONOUS: Final = 1\n    MODE_ASYNCHRONOUS: Final = 2\n    def createDOMBuilder(self, mode: Literal[1], schemaType: None) -> DOMBuilder: ...\n    def createDOMWriter(self) -> NoReturn: ...\n    def createDOMInputSource(self) -> DOMInputSource: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/etree/ElementInclude.pyi",
    "content": "from _typeshed import FileDescriptorOrPath\nfrom typing import Final, Literal, Protocol, overload, type_check_only\nfrom xml.etree.ElementTree import Element\n\n@type_check_only\nclass _Loader(Protocol):\n    @overload\n    def __call__(self, href: FileDescriptorOrPath, parse: Literal[\"xml\"], encoding: str | None = None) -> Element: ...\n    @overload\n    def __call__(self, href: FileDescriptorOrPath, parse: Literal[\"text\"], encoding: str | None = None) -> str: ...\n\nXINCLUDE: Final = \"{http://www.w3.org/2001/XInclude}\"\n\nXINCLUDE_INCLUDE: Final = \"{http://www.w3.org/2001/XInclude}include\"\nXINCLUDE_FALLBACK: Final = \"{http://www.w3.org/2001/XInclude}fallback\"\n\nDEFAULT_MAX_INCLUSION_DEPTH: Final = 6\n\nclass FatalIncludeError(SyntaxError): ...\n\n@overload\ndef default_loader(href: FileDescriptorOrPath, parse: Literal[\"xml\"], encoding: str | None = None) -> Element: ...\n@overload\ndef default_loader(href: FileDescriptorOrPath, parse: Literal[\"text\"], encoding: str | None = None) -> str: ...\ndef include(elem: Element, loader: _Loader | None = None, base_url: str | None = None, max_depth: int | None = 6) -> None: ...\n\nclass LimitedRecursiveIncludeError(FatalIncludeError): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/etree/ElementPath.pyi",
    "content": "from collections.abc import Callable, Generator, Iterable\nfrom re import Pattern\nfrom typing import Any, Final, Literal, TypeVar, overload\nfrom typing_extensions import TypeAlias\nfrom xml.etree.ElementTree import Element\n\nxpath_tokenizer_re: Final[Pattern[str]]\n\n_Token: TypeAlias = tuple[str, str]\n_Next: TypeAlias = Callable[[], _Token]\n_Callback: TypeAlias = Callable[[_SelectorContext, Iterable[Element]], Generator[Element, None, None]]\n_T = TypeVar(\"_T\")\n\ndef xpath_tokenizer(pattern: str, namespaces: dict[str, str] | None = None) -> Generator[_Token, None, None]: ...\ndef get_parent_map(context: _SelectorContext) -> dict[Element, Element]: ...\ndef prepare_child(next: _Next, token: _Token) -> _Callback: ...\ndef prepare_star(next: _Next, token: _Token) -> _Callback: ...\ndef prepare_self(next: _Next, token: _Token) -> _Callback: ...\ndef prepare_descendant(next: _Next, token: _Token) -> _Callback | None: ...\ndef prepare_parent(next: _Next, token: _Token) -> _Callback: ...\ndef prepare_predicate(next: _Next, token: _Token) -> _Callback | None: ...\n\nops: Final[dict[str, Callable[[_Next, _Token], _Callback | None]]]\n\nclass _SelectorContext:\n    parent_map: dict[Element, Element] | None\n    root: Element\n    def __init__(self, root: Element) -> None: ...\n\n@overload\ndef iterfind(  # type: ignore[overload-overlap]\n    elem: Element[Any], path: Literal[\"\"], namespaces: dict[str, str] | None = None\n) -> None: ...\n@overload\ndef iterfind(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Generator[Element, None, None]: ...\ndef find(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> Element | None: ...\ndef findall(elem: Element[Any], path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ...\n@overload\ndef findtext(elem: Element[Any], path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ...\n@overload\ndef findtext(elem: Element[Any], path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/etree/ElementTree.pyi",
    "content": "import sys\nfrom _collections_abc import dict_keys\nfrom _typeshed import FileDescriptorOrPath, ReadableBuffer, SupportsRead, SupportsWrite\nfrom collections.abc import Callable, Generator, ItemsView, Iterable, Iterator, Mapping, Sequence\nfrom typing import Any, Final, Generic, Literal, Protocol, SupportsIndex, TypeVar, overload, type_check_only\nfrom typing_extensions import TypeAlias, TypeGuard, deprecated, disjoint_base\nfrom xml.parsers.expat import XMLParserType\n\n__all__ = [\n    \"C14NWriterTarget\",\n    \"Comment\",\n    \"dump\",\n    \"Element\",\n    \"ElementTree\",\n    \"canonicalize\",\n    \"fromstring\",\n    \"fromstringlist\",\n    \"indent\",\n    \"iselement\",\n    \"iterparse\",\n    \"parse\",\n    \"ParseError\",\n    \"PI\",\n    \"ProcessingInstruction\",\n    \"QName\",\n    \"SubElement\",\n    \"tostring\",\n    \"tostringlist\",\n    \"TreeBuilder\",\n    \"VERSION\",\n    \"XML\",\n    \"XMLID\",\n    \"XMLParser\",\n    \"XMLPullParser\",\n    \"register_namespace\",\n]\n\n_T = TypeVar(\"_T\")\n_FileRead: TypeAlias = FileDescriptorOrPath | SupportsRead[bytes] | SupportsRead[str]\n_FileWriteC14N: TypeAlias = FileDescriptorOrPath | SupportsWrite[bytes]\n_FileWrite: TypeAlias = _FileWriteC14N | SupportsWrite[str]\n\nVERSION: Final[str]\n\nclass ParseError(SyntaxError):\n    code: int\n    position: tuple[int, int]\n\n# In reality it works based on `.tag` attribute duck typing.\ndef iselement(element: object) -> TypeGuard[Element]: ...\n@overload\ndef canonicalize(\n    xml_data: str | ReadableBuffer | None = None,\n    *,\n    out: None = None,\n    from_file: _FileRead | None = None,\n    with_comments: bool = False,\n    strip_text: bool = False,\n    rewrite_prefixes: bool = False,\n    qname_aware_tags: Iterable[str] | None = None,\n    qname_aware_attrs: Iterable[str] | None = None,\n    exclude_attrs: Iterable[str] | None = None,\n    exclude_tags: Iterable[str] | None = None,\n) -> str: ...\n@overload\ndef canonicalize(\n    xml_data: str | ReadableBuffer | None = None,\n    *,\n    out: SupportsWrite[str],\n    from_file: _FileRead | None = None,\n    with_comments: bool = False,\n    strip_text: bool = False,\n    rewrite_prefixes: bool = False,\n    qname_aware_tags: Iterable[str] | None = None,\n    qname_aware_attrs: Iterable[str] | None = None,\n    exclude_attrs: Iterable[str] | None = None,\n    exclude_tags: Iterable[str] | None = None,\n) -> None: ...\n\n# The tag for Element can be set to the Comment or ProcessingInstruction\n# functions defined in this module.\n_ElementCallable: TypeAlias = Callable[..., Element[_ElementCallable]]\n\n_Tag = TypeVar(\"_Tag\", default=str, bound=str | _ElementCallable)\n_OtherTag = TypeVar(\"_OtherTag\", default=str, bound=str | _ElementCallable)\n\n@disjoint_base\nclass Element(Generic[_Tag]):\n    tag: _Tag\n    attrib: dict[str, str]\n    text: str | None\n    tail: str | None\n    def __init__(self, tag: _Tag, attrib: dict[str, str] = {}, **extra: str) -> None: ...\n    def append(self, subelement: Element[Any], /) -> None: ...\n    def clear(self) -> None: ...\n    def extend(self, elements: Iterable[Element[Any]], /) -> None: ...\n    def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ...\n    def findall(self, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ...\n    @overload\n    def findtext(self, path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ...\n    @overload\n    def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ...\n    @overload\n    def get(self, key: str, default: None = None) -> str | None: ...\n    @overload\n    def get(self, key: str, default: _T) -> str | _T: ...\n    def insert(self, index: int, subelement: Element[Any], /) -> None: ...\n    def items(self) -> ItemsView[str, str]: ...\n    def iter(self, tag: str | None = None) -> Generator[Element, None, None]: ...\n    @overload\n    def iterfind(self, path: Literal[\"\"], namespaces: dict[str, str] | None = None) -> None: ...  # type: ignore[overload-overlap]\n    @overload\n    def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element, None, None]: ...\n    def itertext(self) -> Generator[str, None, None]: ...\n    def keys(self) -> dict_keys[str, str]: ...\n    # makeelement returns the type of self in Python impl, but not in C impl\n    def makeelement(self, tag: _OtherTag, attrib: dict[str, str], /) -> Element[_OtherTag]: ...\n    def remove(self, subelement: Element[Any], /) -> None: ...\n    def set(self, key: str, value: str, /) -> None: ...\n    def __copy__(self) -> Element[_Tag]: ...  # returns the type of self in Python impl, but not in C impl\n    def __deepcopy__(self, memo: Any, /) -> Element: ...  # Only exists in C impl\n    def __delitem__(self, key: SupportsIndex | slice, /) -> None: ...\n    @overload\n    def __getitem__(self, key: SupportsIndex, /) -> Element: ...\n    @overload\n    def __getitem__(self, key: slice[SupportsIndex | None], /) -> list[Element]: ...\n    def __len__(self) -> int: ...\n    # Doesn't actually exist at runtime, but instance of the class are indeed iterable due to __getitem__.\n    def __iter__(self) -> Iterator[Element]: ...\n    @overload\n    def __setitem__(self, key: SupportsIndex, value: Element[Any], /) -> None: ...\n    @overload\n    def __setitem__(self, key: slice[SupportsIndex | None], value: Iterable[Element[Any]], /) -> None: ...\n\n    # Doesn't really exist in earlier versions, where __len__ is called implicitly instead\n    @deprecated(\"Testing an element's truth value is deprecated.\")\n    def __bool__(self) -> bool: ...\n\ndef SubElement(parent: Element[Any], tag: str, attrib: dict[str, str] = ..., **extra: str) -> Element: ...\ndef Comment(text: str | None = None) -> Element[_ElementCallable]: ...\ndef ProcessingInstruction(target: str, text: str | None = None) -> Element[_ElementCallable]: ...\n\nPI = ProcessingInstruction\n\nclass QName:\n    text: str\n    def __init__(self, text_or_uri: str, tag: str | None = None) -> None: ...\n    def __lt__(self, other: QName | str) -> bool: ...\n    def __le__(self, other: QName | str) -> bool: ...\n    def __gt__(self, other: QName | str) -> bool: ...\n    def __ge__(self, other: QName | str) -> bool: ...\n    def __eq__(self, other: object) -> bool: ...\n    def __hash__(self) -> int: ...\n\n_Root = TypeVar(\"_Root\", Element, Element | None, default=Element | None)\n\nclass ElementTree(Generic[_Root]):\n    def __init__(self, element: Element[Any] | None = None, file: _FileRead | None = None) -> None: ...\n    def getroot(self) -> _Root: ...\n    def _setroot(self, element: Element[Any]) -> None: ...\n    def parse(self, source: _FileRead, parser: XMLParser | None = None) -> Element: ...\n    def iter(self, tag: str | None = None) -> Generator[Element, None, None]: ...\n    def find(self, path: str, namespaces: dict[str, str] | None = None) -> Element | None: ...\n    @overload\n    def findtext(self, path: str, default: None = None, namespaces: dict[str, str] | None = None) -> str | None: ...\n    @overload\n    def findtext(self, path: str, default: _T, namespaces: dict[str, str] | None = None) -> _T | str: ...\n    def findall(self, path: str, namespaces: dict[str, str] | None = None) -> list[Element]: ...\n    @overload\n    def iterfind(self, path: Literal[\"\"], namespaces: dict[str, str] | None = None) -> None: ...  # type: ignore[overload-overlap]\n    @overload\n    def iterfind(self, path: str, namespaces: dict[str, str] | None = None) -> Generator[Element, None, None]: ...\n    def write(\n        self,\n        file_or_filename: _FileWrite,\n        encoding: str | None = None,\n        xml_declaration: bool | None = None,\n        default_namespace: str | None = None,\n        method: Literal[\"xml\", \"html\", \"text\", \"c14n\"] | None = None,\n        *,\n        short_empty_elements: bool = True,\n    ) -> None: ...\n    def write_c14n(self, file: _FileWriteC14N) -> None: ...\n\nHTML_EMPTY: Final[set[str]]\n\ndef register_namespace(prefix: str, uri: str) -> None: ...\n@overload\ndef tostring(\n    element: Element[Any],\n    encoding: None = None,\n    method: Literal[\"xml\", \"html\", \"text\", \"c14n\"] | None = None,\n    *,\n    xml_declaration: bool | None = None,\n    default_namespace: str | None = None,\n    short_empty_elements: bool = True,\n) -> bytes: ...\n@overload\ndef tostring(\n    element: Element[Any],\n    encoding: Literal[\"unicode\"],\n    method: Literal[\"xml\", \"html\", \"text\", \"c14n\"] | None = None,\n    *,\n    xml_declaration: bool | None = None,\n    default_namespace: str | None = None,\n    short_empty_elements: bool = True,\n) -> str: ...\n@overload\ndef tostring(\n    element: Element[Any],\n    encoding: str,\n    method: Literal[\"xml\", \"html\", \"text\", \"c14n\"] | None = None,\n    *,\n    xml_declaration: bool | None = None,\n    default_namespace: str | None = None,\n    short_empty_elements: bool = True,\n) -> Any: ...\n@overload\ndef tostringlist(\n    element: Element[Any],\n    encoding: None = None,\n    method: Literal[\"xml\", \"html\", \"text\", \"c14n\"] | None = None,\n    *,\n    xml_declaration: bool | None = None,\n    default_namespace: str | None = None,\n    short_empty_elements: bool = True,\n) -> list[bytes]: ...\n@overload\ndef tostringlist(\n    element: Element[Any],\n    encoding: Literal[\"unicode\"],\n    method: Literal[\"xml\", \"html\", \"text\", \"c14n\"] | None = None,\n    *,\n    xml_declaration: bool | None = None,\n    default_namespace: str | None = None,\n    short_empty_elements: bool = True,\n) -> list[str]: ...\n@overload\ndef tostringlist(\n    element: Element[Any],\n    encoding: str,\n    method: Literal[\"xml\", \"html\", \"text\", \"c14n\"] | None = None,\n    *,\n    xml_declaration: bool | None = None,\n    default_namespace: str | None = None,\n    short_empty_elements: bool = True,\n) -> list[Any]: ...\ndef dump(elem: Element[Any] | ElementTree[Any]) -> None: ...\ndef indent(tree: Element[Any] | ElementTree[Any], space: str = \"  \", level: int = 0) -> None: ...\ndef parse(source: _FileRead, parser: XMLParser[Any] | None = None) -> ElementTree[Element]: ...\n\n# This class is defined inside the body of iterparse\n@type_check_only\nclass _IterParseIterator(Iterator[tuple[str, Element]], Protocol):\n    def __next__(self) -> tuple[str, Element]: ...\n    if sys.version_info >= (3, 13):\n        def close(self) -> None: ...\n    if sys.version_info >= (3, 11):\n        def __del__(self) -> None: ...\n\n@overload\ndef iterparse(source: _FileRead, events: Sequence[str] | None = None) -> _IterParseIterator: ...\n@overload\n@deprecated(\"The `parser` parameter is deprecated since Python 3.4.\")\ndef iterparse(source: _FileRead, events: Sequence[str] | None = None, parser: XMLParser | None = None) -> _IterParseIterator: ...\n\n_EventQueue: TypeAlias = tuple[str] | tuple[str, tuple[str, str]] | tuple[str, None]\n\nclass XMLPullParser(Generic[_E]):\n    def __init__(self, events: Sequence[str] | None = None, *, _parser: XMLParser[_E] | None = None) -> None: ...\n    def feed(self, data: str | ReadableBuffer) -> None: ...\n    def close(self) -> None: ...\n    def read_events(self) -> Iterator[_EventQueue | tuple[str, _E]]: ...\n    def flush(self) -> None: ...\n\ndef XML(text: str | ReadableBuffer, parser: XMLParser | None = None) -> Element: ...\ndef XMLID(text: str | ReadableBuffer, parser: XMLParser | None = None) -> tuple[Element, dict[str, Element]]: ...\n\n# This is aliased to XML in the source.\nfromstring = XML\n\ndef fromstringlist(sequence: Sequence[str | ReadableBuffer], parser: XMLParser | None = None) -> Element: ...\n\n# This type is both not precise enough and too precise. The TreeBuilder\n# requires the elementfactory to accept tag and attrs in its args and produce\n# some kind of object that has .text and .tail properties.\n# I've chosen to constrain the ElementFactory to always produce an Element\n# because that is how almost everyone will use it.\n# Unfortunately, the type of the factory arguments is dependent on how\n# TreeBuilder is called by client code (they could pass strs, bytes or whatever);\n# but we don't want to use a too-broad type, or it would be too hard to write\n# elementfactories.\n_ElementFactory: TypeAlias = Callable[[Any, dict[Any, Any]], Element]\n\n@disjoint_base\nclass TreeBuilder:\n    # comment_factory can take None because passing None to Comment is not an error\n    def __init__(\n        self,\n        element_factory: _ElementFactory | None = None,\n        *,\n        comment_factory: Callable[[str | None], Element[Any]] | None = None,\n        pi_factory: Callable[[str, str | None], Element[Any]] | None = None,\n        insert_comments: bool = False,\n        insert_pis: bool = False,\n    ) -> None: ...\n    insert_comments: bool\n    insert_pis: bool\n\n    def close(self) -> Element: ...\n    def data(self, data: str, /) -> None: ...\n    # tag and attrs are passed to the element_factory, so they could be anything\n    # depending on what the particular factory supports.\n    def start(self, tag: Any, attrs: dict[Any, Any], /) -> Element: ...\n    def end(self, tag: str, /) -> Element: ...\n    # These two methods have pos-only parameters in the C implementation\n    def comment(self, text: str | None, /) -> Element[Any]: ...\n    def pi(self, target: str, text: str | None = None, /) -> Element[Any]: ...\n\nclass C14NWriterTarget:\n    def __init__(\n        self,\n        write: Callable[[str], object],\n        *,\n        with_comments: bool = False,\n        strip_text: bool = False,\n        rewrite_prefixes: bool = False,\n        qname_aware_tags: Iterable[str] | None = None,\n        qname_aware_attrs: Iterable[str] | None = None,\n        exclude_attrs: Iterable[str] | None = None,\n        exclude_tags: Iterable[str] | None = None,\n    ) -> None: ...\n    def data(self, data: str) -> None: ...\n    def start_ns(self, prefix: str, uri: str) -> None: ...\n    def start(self, tag: str, attrs: Mapping[str, str]) -> None: ...\n    def end(self, tag: str) -> None: ...\n    def comment(self, text: str) -> None: ...\n    def pi(self, target: str, data: str) -> None: ...\n\n# The target type is tricky, because the implementation doesn't\n# require any particular attribute to be present. This documents the attributes\n# that can be present, but uncommenting any of them would require them.\n@type_check_only\nclass _Target(Protocol):\n    # start: Callable[str, dict[str, str], Any] | None\n    # end: Callable[[str], Any] | None\n    # start_ns: Callable[[str, str], Any] | None\n    # end_ns: Callable[[str], Any] | None\n    # data: Callable[[str], Any] | None\n    # comment: Callable[[str], Any]\n    # pi: Callable[[str, str], Any] | None\n    # close: Callable[[], Any] | None\n    ...\n\n_E = TypeVar(\"_E\", default=Element)\n\n# This is generic because the return type of close() depends on the target.\n# The default target is TreeBuilder, which returns Element.\n# C14NWriterTarget does not implement a close method, so using it results\n# in a type of XMLParser[None].\n@disjoint_base\nclass XMLParser(Generic[_E]):\n    parser: XMLParserType\n    target: _Target\n    # TODO: what is entity used for???\n    entity: dict[str, str]\n    version: str\n    def __init__(self, *, target: _Target | None = None, encoding: str | None = None) -> None: ...\n    def close(self) -> _E: ...\n    def feed(self, data: str | ReadableBuffer, /) -> None: ...\n    def flush(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/etree/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/xml/etree/cElementTree.pyi",
    "content": "from xml.etree.ElementTree import *\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/parsers/__init__.pyi",
    "content": "from xml.parsers import expat as expat\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/parsers/expat/__init__.pyi",
    "content": "from pyexpat import *\n\n# This is actually implemented in the C module pyexpat, but considers itself to live here.\nclass ExpatError(Exception):\n    code: int\n    lineno: int\n    offset: int\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/parsers/expat/errors.pyi",
    "content": "from pyexpat.errors import *\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/parsers/expat/model.pyi",
    "content": "from pyexpat.model import *\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/sax/__init__.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer, StrPath, SupportsRead, _T_co\nfrom collections.abc import Iterable\nfrom typing import Final, Protocol, type_check_only\nfrom typing_extensions import TypeAlias\nfrom xml.sax._exceptions import (\n    SAXException as SAXException,\n    SAXNotRecognizedException as SAXNotRecognizedException,\n    SAXNotSupportedException as SAXNotSupportedException,\n    SAXParseException as SAXParseException,\n    SAXReaderNotAvailable as SAXReaderNotAvailable,\n)\nfrom xml.sax.handler import ContentHandler as ContentHandler, ErrorHandler as ErrorHandler\nfrom xml.sax.xmlreader import InputSource as InputSource, XMLReader\n\n@type_check_only\nclass _SupportsReadClose(SupportsRead[_T_co], Protocol[_T_co]):\n    def close(self) -> None: ...\n\n_Source: TypeAlias = StrPath | _SupportsReadClose[bytes] | _SupportsReadClose[str]\n\ndefault_parser_list: Final[list[str]]\n\ndef make_parser(parser_list: Iterable[str] = ()) -> XMLReader: ...\ndef parse(source: _Source, handler: ContentHandler, errorHandler: ErrorHandler = ...) -> None: ...\ndef parseString(string: ReadableBuffer | str, handler: ContentHandler, errorHandler: ErrorHandler | None = ...) -> None: ...\ndef _create_parser(parser_name: str) -> XMLReader: ...\n\nif sys.version_info >= (3, 14):\n    __all__ = [\n        \"ContentHandler\",\n        \"ErrorHandler\",\n        \"InputSource\",\n        \"SAXException\",\n        \"SAXNotRecognizedException\",\n        \"SAXNotSupportedException\",\n        \"SAXParseException\",\n        \"SAXReaderNotAvailable\",\n        \"default_parser_list\",\n        \"make_parser\",\n        \"parse\",\n        \"parseString\",\n    ]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/sax/_exceptions.pyi",
    "content": "from typing import NoReturn\nfrom xml.sax.xmlreader import Locator\n\nclass SAXException(Exception):\n    def __init__(self, msg: str, exception: Exception | None = None) -> None: ...\n    def getMessage(self) -> str: ...\n    def getException(self) -> Exception | None: ...\n    def __getitem__(self, ix: object) -> NoReturn: ...\n\nclass SAXParseException(SAXException):\n    def __init__(self, msg: str, exception: Exception | None, locator: Locator) -> None: ...\n    def getColumnNumber(self) -> int | None: ...\n    def getLineNumber(self) -> int | None: ...\n    def getPublicId(self) -> str | None: ...\n    def getSystemId(self) -> str | None: ...\n\nclass SAXNotRecognizedException(SAXException): ...\nclass SAXNotSupportedException(SAXException): ...\nclass SAXReaderNotAvailable(SAXNotSupportedException): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/sax/expatreader.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Mapping\nfrom typing import Any, Final, Literal, overload\nfrom typing_extensions import TypeAlias\nfrom xml.sax import _Source, xmlreader\nfrom xml.sax.handler import _ContentHandlerProtocol\n\nif sys.version_info >= (3, 10):\n    from xml.sax.handler import LexicalHandler\n\n_BoolType: TypeAlias = Literal[0, 1] | bool\n\nversion: Final[str]\nAttributesImpl = xmlreader.AttributesImpl\nAttributesNSImpl = xmlreader.AttributesNSImpl\n\nclass _ClosedParser:\n    ErrorColumnNumber: int\n    ErrorLineNumber: int\n\nclass ExpatLocator(xmlreader.Locator):\n    def __init__(self, parser: ExpatParser) -> None: ...\n    def getColumnNumber(self) -> int | None: ...\n    def getLineNumber(self) -> int: ...\n    def getPublicId(self) -> str | None: ...\n    def getSystemId(self) -> str | None: ...\n\nclass ExpatParser(xmlreader.IncrementalParser, xmlreader.Locator):\n    def __init__(self, namespaceHandling: _BoolType = 0, bufsize: int = 65516) -> None: ...\n    def parse(self, source: xmlreader.InputSource | _Source) -> None: ...\n    def prepareParser(self, source: xmlreader.InputSource) -> None: ...\n    def setContentHandler(self, handler: _ContentHandlerProtocol) -> None: ...\n    def getFeature(self, name: str) -> _BoolType: ...\n    def setFeature(self, name: str, state: _BoolType) -> None: ...\n    if sys.version_info >= (3, 10):\n        @overload\n        def getProperty(self, name: Literal[\"http://xml.org/sax/properties/lexical-handler\"]) -> LexicalHandler | None: ...\n\n    @overload\n    def getProperty(self, name: Literal[\"http://www.python.org/sax/properties/interning-dict\"]) -> dict[str, Any] | None: ...\n    @overload\n    def getProperty(self, name: Literal[\"http://xml.org/sax/properties/xml-string\"]) -> bytes | None: ...\n    @overload\n    def getProperty(self, name: str) -> object: ...\n    if sys.version_info >= (3, 10):\n        @overload\n        def setProperty(self, name: Literal[\"http://xml.org/sax/properties/lexical-handler\"], value: LexicalHandler) -> None: ...\n\n    @overload\n    def setProperty(\n        self, name: Literal[\"http://www.python.org/sax/properties/interning-dict\"], value: dict[str, Any]\n    ) -> None: ...\n    @overload\n    def setProperty(self, name: str, value: object) -> None: ...\n    def feed(self, data: str | ReadableBuffer, isFinal: bool = False) -> None: ...\n    def flush(self) -> None: ...\n    def close(self) -> None: ...\n    def reset(self) -> None: ...\n    def getColumnNumber(self) -> int | None: ...\n    def getLineNumber(self) -> int: ...\n    def getPublicId(self) -> str | None: ...\n    def getSystemId(self) -> str | None: ...\n    def start_element(self, name: str, attrs: Mapping[str, str]) -> None: ...\n    def end_element(self, name: str) -> None: ...\n    def start_element_ns(self, name: str, attrs: Mapping[str, str]) -> None: ...\n    def end_element_ns(self, name: str) -> None: ...\n    def processing_instruction(self, target: str, data: str) -> None: ...\n    def character_data(self, data: str) -> None: ...\n    def start_namespace_decl(self, prefix: str | None, uri: str) -> None: ...\n    def end_namespace_decl(self, prefix: str | None) -> None: ...\n    def start_doctype_decl(self, name: str, sysid: str | None, pubid: str | None, has_internal_subset: bool) -> None: ...\n    def unparsed_entity_decl(self, name: str, base: str | None, sysid: str, pubid: str | None, notation_name: str) -> None: ...\n    def notation_decl(self, name: str, base: str | None, sysid: str, pubid: str | None) -> None: ...\n    def external_entity_ref(self, context: str, base: str | None, sysid: str, pubid: str | None) -> int: ...\n    def skipped_entity_handler(self, name: str, is_pe: bool) -> None: ...\n\ndef create_parser(namespaceHandling: int = 0, bufsize: int = 65516) -> ExpatParser: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/sax/handler.pyi",
    "content": "import sys\nfrom typing import Final, NoReturn, Protocol, type_check_only\nfrom xml.sax import xmlreader\n\nversion: Final[str]\n\n@type_check_only\nclass _ErrorHandlerProtocol(Protocol):  # noqa: Y046  # Protocol is not used\n    def error(self, exception: BaseException) -> NoReturn: ...\n    def fatalError(self, exception: BaseException) -> NoReturn: ...\n    def warning(self, exception: BaseException) -> None: ...\n\nclass ErrorHandler:\n    def error(self, exception: BaseException) -> NoReturn: ...\n    def fatalError(self, exception: BaseException) -> NoReturn: ...\n    def warning(self, exception: BaseException) -> None: ...\n\n@type_check_only\nclass _ContentHandlerProtocol(Protocol):  # noqa: Y046  # Protocol is not used\n    def setDocumentLocator(self, locator: xmlreader.Locator) -> None: ...\n    def startDocument(self) -> None: ...\n    def endDocument(self) -> None: ...\n    def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ...\n    def endPrefixMapping(self, prefix: str | None) -> None: ...\n    def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ...\n    def endElement(self, name: str) -> None: ...\n    def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ...\n    def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ...\n    def characters(self, content: str) -> None: ...\n    def ignorableWhitespace(self, whitespace: str) -> None: ...\n    def processingInstruction(self, target: str, data: str) -> None: ...\n    def skippedEntity(self, name: str) -> None: ...\n\nclass ContentHandler:\n    def setDocumentLocator(self, locator: xmlreader.Locator) -> None: ...\n    def startDocument(self) -> None: ...\n    def endDocument(self) -> None: ...\n    def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ...\n    def endPrefixMapping(self, prefix: str | None) -> None: ...\n    def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ...\n    def endElement(self, name: str) -> None: ...\n    def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ...\n    def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ...\n    def characters(self, content: str) -> None: ...\n    def ignorableWhitespace(self, whitespace: str) -> None: ...\n    def processingInstruction(self, target: str, data: str) -> None: ...\n    def skippedEntity(self, name: str) -> None: ...\n\n@type_check_only\nclass _DTDHandlerProtocol(Protocol):  # noqa: Y046  # Protocol is not used\n    def notationDecl(self, name: str, publicId: str | None, systemId: str) -> None: ...\n    def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: ...\n\nclass DTDHandler:\n    def notationDecl(self, name: str, publicId: str | None, systemId: str) -> None: ...\n    def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: ...\n\n@type_check_only\nclass _EntityResolverProtocol(Protocol):  # noqa: Y046  # Protocol is not used\n    def resolveEntity(self, publicId: str | None, systemId: str) -> str: ...\n\nclass EntityResolver:\n    def resolveEntity(self, publicId: str | None, systemId: str) -> str: ...\n\nfeature_namespaces: Final = \"http://xml.org/sax/features/namespaces\"\nfeature_namespace_prefixes: Final = \"http://xml.org/sax/features/namespace-prefixes\"\nfeature_string_interning: Final = \"http://xml.org/sax/features/string-interning\"\nfeature_validation: Final = \"http://xml.org/sax/features/validation\"\nfeature_external_ges: Final[str]  # too long string\nfeature_external_pes: Final[str]  # too long string\nall_features: Final[list[str]]\nproperty_lexical_handler: Final = \"http://xml.org/sax/properties/lexical-handler\"\nproperty_declaration_handler: Final = \"http://xml.org/sax/properties/declaration-handler\"\nproperty_dom_node: Final = \"http://xml.org/sax/properties/dom-node\"\nproperty_xml_string: Final = \"http://xml.org/sax/properties/xml-string\"\nproperty_encoding: Final = \"http://www.python.org/sax/properties/encoding\"\nproperty_interning_dict: Final[str]  # too long string\nall_properties: Final[list[str]]\n\nif sys.version_info >= (3, 10):\n    class LexicalHandler:\n        def comment(self, content: str) -> None: ...\n        def startDTD(self, name: str, public_id: str | None, system_id: str | None) -> None: ...\n        def endDTD(self) -> None: ...\n        def startCDATA(self) -> None: ...\n        def endCDATA(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/sax/saxutils.pyi",
    "content": "from _typeshed import SupportsWrite\nfrom codecs import StreamReaderWriter, StreamWriter\nfrom collections.abc import Mapping\nfrom io import RawIOBase, TextIOBase\nfrom typing import Literal, NoReturn\nfrom xml.sax import _Source, handler, xmlreader\n\ndef escape(data: str, entities: Mapping[str, str] = {}) -> str: ...\ndef unescape(data: str, entities: Mapping[str, str] = {}) -> str: ...\ndef quoteattr(data: str, entities: Mapping[str, str] = {}) -> str: ...\n\nclass XMLGenerator(handler.ContentHandler):\n    def __init__(\n        self,\n        out: TextIOBase | RawIOBase | StreamWriter | StreamReaderWriter | SupportsWrite[bytes] | None = None,\n        encoding: str = \"iso-8859-1\",\n        short_empty_elements: bool = False,\n    ) -> None: ...\n    def _qname(self, name: tuple[str | None, str]) -> str: ...\n    def startDocument(self) -> None: ...\n    def endDocument(self) -> None: ...\n    def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ...\n    def endPrefixMapping(self, prefix: str | None) -> None: ...\n    def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ...\n    def endElement(self, name: str) -> None: ...\n    def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ...\n    def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ...\n    def characters(self, content: str) -> None: ...\n    def ignorableWhitespace(self, content: str) -> None: ...\n    def processingInstruction(self, target: str, data: str) -> None: ...\n\nclass XMLFilterBase(xmlreader.XMLReader):\n    def __init__(self, parent: xmlreader.XMLReader | None = None) -> None: ...\n    # ErrorHandler methods\n    def error(self, exception: BaseException) -> NoReturn: ...\n    def fatalError(self, exception: BaseException) -> NoReturn: ...\n    def warning(self, exception: BaseException) -> None: ...\n    # ContentHandler methods\n    def setDocumentLocator(self, locator: xmlreader.Locator) -> None: ...\n    def startDocument(self) -> None: ...\n    def endDocument(self) -> None: ...\n    def startPrefixMapping(self, prefix: str | None, uri: str) -> None: ...\n    def endPrefixMapping(self, prefix: str | None) -> None: ...\n    def startElement(self, name: str, attrs: xmlreader.AttributesImpl) -> None: ...\n    def endElement(self, name: str) -> None: ...\n    def startElementNS(self, name: tuple[str | None, str], qname: str | None, attrs: xmlreader.AttributesNSImpl) -> None: ...\n    def endElementNS(self, name: tuple[str | None, str], qname: str | None) -> None: ...\n    def characters(self, content: str) -> None: ...\n    def ignorableWhitespace(self, chars: str) -> None: ...\n    def processingInstruction(self, target: str, data: str) -> None: ...\n    def skippedEntity(self, name: str) -> None: ...\n    # DTDHandler methods\n    def notationDecl(self, name: str, publicId: str | None, systemId: str) -> None: ...\n    def unparsedEntityDecl(self, name: str, publicId: str | None, systemId: str, ndata: str) -> None: ...\n    # EntityResolver methods\n    def resolveEntity(self, publicId: str | None, systemId: str) -> str: ...\n    # XMLReader methods\n    def parse(self, source: xmlreader.InputSource | _Source) -> None: ...\n    def setLocale(self, locale: str) -> None: ...\n    def getFeature(self, name: str) -> Literal[1, 0] | bool: ...\n    def setFeature(self, name: str, state: Literal[1, 0] | bool) -> None: ...\n    def getProperty(self, name: str) -> object: ...\n    def setProperty(self, name: str, value: object) -> None: ...\n    # XMLFilter methods\n    def getParent(self) -> xmlreader.XMLReader | None: ...\n    def setParent(self, parent: xmlreader.XMLReader) -> None: ...\n\ndef prepare_input_source(source: xmlreader.InputSource | _Source, base: str = \"\") -> xmlreader.InputSource: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xml/sax/xmlreader.pyi",
    "content": "from _typeshed import ReadableBuffer\nfrom collections.abc import Mapping\nfrom typing import Generic, Literal, TypeVar, overload\nfrom typing_extensions import Self, TypeAlias\nfrom xml.sax import _Source, _SupportsReadClose\nfrom xml.sax.handler import _ContentHandlerProtocol, _DTDHandlerProtocol, _EntityResolverProtocol, _ErrorHandlerProtocol\n\nclass XMLReader:\n    def parse(self, source: InputSource | _Source) -> None: ...\n    def getContentHandler(self) -> _ContentHandlerProtocol: ...\n    def setContentHandler(self, handler: _ContentHandlerProtocol) -> None: ...\n    def getDTDHandler(self) -> _DTDHandlerProtocol: ...\n    def setDTDHandler(self, handler: _DTDHandlerProtocol) -> None: ...\n    def getEntityResolver(self) -> _EntityResolverProtocol: ...\n    def setEntityResolver(self, resolver: _EntityResolverProtocol) -> None: ...\n    def getErrorHandler(self) -> _ErrorHandlerProtocol: ...\n    def setErrorHandler(self, handler: _ErrorHandlerProtocol) -> None: ...\n    def setLocale(self, locale: str) -> None: ...\n    def getFeature(self, name: str) -> Literal[0, 1] | bool: ...\n    def setFeature(self, name: str, state: Literal[0, 1] | bool) -> None: ...\n    def getProperty(self, name: str) -> object: ...\n    def setProperty(self, name: str, value: object) -> None: ...\n\nclass IncrementalParser(XMLReader):\n    def __init__(self, bufsize: int = 65536) -> None: ...\n    def parse(self, source: InputSource | _Source) -> None: ...\n    def feed(self, data: str | ReadableBuffer) -> None: ...\n    def prepareParser(self, source: InputSource) -> None: ...\n    def close(self) -> None: ...\n    def reset(self) -> None: ...\n\nclass Locator:\n    def getColumnNumber(self) -> int | None: ...\n    def getLineNumber(self) -> int | None: ...\n    def getPublicId(self) -> str | None: ...\n    def getSystemId(self) -> str | None: ...\n\nclass InputSource:\n    def __init__(self, system_id: str | None = None) -> None: ...\n    def setPublicId(self, public_id: str | None) -> None: ...\n    def getPublicId(self) -> str | None: ...\n    def setSystemId(self, system_id: str | None) -> None: ...\n    def getSystemId(self) -> str | None: ...\n    def setEncoding(self, encoding: str | None) -> None: ...\n    def getEncoding(self) -> str | None: ...\n    def setByteStream(self, bytefile: _SupportsReadClose[bytes] | None) -> None: ...\n    def getByteStream(self) -> _SupportsReadClose[bytes] | None: ...\n    def setCharacterStream(self, charfile: _SupportsReadClose[str] | None) -> None: ...\n    def getCharacterStream(self) -> _SupportsReadClose[str] | None: ...\n\n_AttrKey = TypeVar(\"_AttrKey\", default=str)\n\nclass AttributesImpl(Generic[_AttrKey]):\n    def __init__(self, attrs: Mapping[_AttrKey, str]) -> None: ...\n    def getLength(self) -> int: ...\n    def getType(self, name: str) -> str: ...\n    def getValue(self, name: _AttrKey) -> str: ...\n    def getValueByQName(self, name: str) -> str: ...\n    def getNameByQName(self, name: str) -> _AttrKey: ...\n    def getQNameByName(self, name: _AttrKey) -> str: ...\n    def getNames(self) -> list[_AttrKey]: ...\n    def getQNames(self) -> list[str]: ...\n    def __len__(self) -> int: ...\n    def __getitem__(self, name: _AttrKey) -> str: ...\n    def keys(self) -> list[_AttrKey]: ...\n    def __contains__(self, name: _AttrKey) -> bool: ...\n    @overload\n    def get(self, name: _AttrKey, alternative: None = None) -> str | None: ...\n    @overload\n    def get(self, name: _AttrKey, alternative: str) -> str: ...\n    def copy(self) -> Self: ...\n    def items(self) -> list[tuple[_AttrKey, str]]: ...\n    def values(self) -> list[str]: ...\n\n_NSName: TypeAlias = tuple[str | None, str]\n\nclass AttributesNSImpl(AttributesImpl[_NSName]):\n    def __init__(self, attrs: Mapping[_NSName, str], qnames: Mapping[_NSName, str]) -> None: ...\n    def getValue(self, name: _NSName) -> str: ...\n    def getNameByQName(self, name: str) -> _NSName: ...\n    def getQNameByName(self, name: _NSName) -> str: ...\n    def getNames(self) -> list[_NSName]: ...\n    def __getitem__(self, name: _NSName) -> str: ...\n    def keys(self) -> list[_NSName]: ...\n    def __contains__(self, name: _NSName) -> bool: ...\n    @overload\n    def get(self, name: _NSName, alternative: None = None) -> str | None: ...\n    @overload\n    def get(self, name: _NSName, alternative: str) -> str: ...\n    def items(self) -> list[tuple[_NSName, str]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xmlrpc/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stdlib/xmlrpc/client.pyi",
    "content": "import gzip\nimport http.client\nimport time\nfrom _typeshed import ReadableBuffer, SizedBuffer, SupportsRead, SupportsWrite\nfrom collections.abc import Callable, Iterable, Mapping\nfrom datetime import datetime\nfrom io import BytesIO\nfrom types import TracebackType\nfrom typing import Any, ClassVar, Final, Literal, Protocol, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\n@type_check_only\nclass _SupportsTimeTuple(Protocol):\n    def timetuple(self) -> time.struct_time: ...\n\n_DateTimeComparable: TypeAlias = DateTime | datetime | str | _SupportsTimeTuple\n_Marshallable: TypeAlias = (\n    bool\n    | int\n    | float\n    | str\n    | bytes\n    | bytearray\n    | None\n    | tuple[_Marshallable, ...]\n    # Ideally we'd use _Marshallable for list and dict, but invariance makes that impractical\n    | list[Any]\n    | dict[str, Any]\n    | datetime\n    | DateTime\n    | Binary\n)\n_XMLDate: TypeAlias = int | datetime | tuple[int, ...] | time.struct_time\n_HostType: TypeAlias = tuple[str, dict[str, str]] | str\n\ndef escape(s: str) -> str: ...  # undocumented\n\nMAXINT: Final[int]  # undocumented\nMININT: Final[int]  # undocumented\n\nPARSE_ERROR: Final[int]  # undocumented\nSERVER_ERROR: Final[int]  # undocumented\nAPPLICATION_ERROR: Final[int]  # undocumented\nSYSTEM_ERROR: Final[int]  # undocumented\nTRANSPORT_ERROR: Final[int]  # undocumented\n\nNOT_WELLFORMED_ERROR: Final[int]  # undocumented\nUNSUPPORTED_ENCODING: Final[int]  # undocumented\nINVALID_ENCODING_CHAR: Final[int]  # undocumented\nINVALID_XMLRPC: Final[int]  # undocumented\nMETHOD_NOT_FOUND: Final[int]  # undocumented\nINVALID_METHOD_PARAMS: Final[int]  # undocumented\nINTERNAL_ERROR: Final[int]  # undocumented\n\nclass Error(Exception): ...\n\nclass ProtocolError(Error):\n    url: str\n    errcode: int\n    errmsg: str\n    headers: dict[str, str]\n    def __init__(self, url: str, errcode: int, errmsg: str, headers: dict[str, str]) -> None: ...\n\nclass ResponseError(Error): ...\n\nclass Fault(Error):\n    faultCode: int\n    faultString: str\n    def __init__(self, faultCode: int, faultString: str, **extra: Any) -> None: ...\n\nboolean = bool\nBoolean = bool\n\ndef _iso8601_format(value: datetime) -> str: ...  # undocumented\ndef _strftime(value: _XMLDate) -> str: ...  # undocumented\n\nclass DateTime:\n    value: str  # undocumented\n    def __init__(self, value: int | str | datetime | time.struct_time | tuple[int, ...] = 0) -> None: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n    def __lt__(self, other: _DateTimeComparable) -> bool: ...\n    def __le__(self, other: _DateTimeComparable) -> bool: ...\n    def __gt__(self, other: _DateTimeComparable) -> bool: ...\n    def __ge__(self, other: _DateTimeComparable) -> bool: ...\n    def __eq__(self, other: _DateTimeComparable) -> bool: ...  # type: ignore[override]\n    def make_comparable(self, other: _DateTimeComparable) -> tuple[str, str]: ...  # undocumented\n    def timetuple(self) -> time.struct_time: ...  # undocumented\n    def decode(self, data: Any) -> None: ...\n    def encode(self, out: SupportsWrite[str]) -> None: ...\n\ndef _datetime(data: Any) -> DateTime: ...  # undocumented\ndef _datetime_type(data: str) -> datetime: ...  # undocumented\n\nclass Binary:\n    data: bytes\n    def __init__(self, data: bytes | bytearray | None = None) -> None: ...\n    def decode(self, data: ReadableBuffer) -> None: ...\n    def encode(self, out: SupportsWrite[str]) -> None: ...\n    def __eq__(self, other: object) -> bool: ...\n    __hash__: ClassVar[None]  # type: ignore[assignment]\n\ndef _binary(data: ReadableBuffer) -> Binary: ...  # undocumented\n\nWRAPPERS: Final[tuple[type[DateTime], type[Binary]]]  # undocumented\n\nclass ExpatParser:  # undocumented\n    def __init__(self, target: Unmarshaller) -> None: ...\n    def feed(self, data: str | ReadableBuffer) -> None: ...\n    def close(self) -> None: ...\n\n_WriteCallback: TypeAlias = Callable[[str], object]\n\nclass Marshaller:\n    dispatch: dict[type[_Marshallable] | Literal[\"_arbitrary_instance\"], Callable[[Marshaller, Any, _WriteCallback], None]]\n    memo: dict[Any, None]\n    data: None\n    encoding: str | None\n    allow_none: bool\n    def __init__(self, encoding: str | None = None, allow_none: bool = False) -> None: ...\n    def dumps(self, values: Fault | Iterable[_Marshallable]) -> str: ...\n    def __dump(self, value: _Marshallable, write: _WriteCallback) -> None: ...  # undocumented\n    def dump_nil(self, value: None, write: _WriteCallback) -> None: ...\n    def dump_bool(self, value: bool, write: _WriteCallback) -> None: ...\n    def dump_long(self, value: int, write: _WriteCallback) -> None: ...\n    def dump_int(self, value: int, write: _WriteCallback) -> None: ...\n    def dump_double(self, value: float, write: _WriteCallback) -> None: ...\n    def dump_unicode(self, value: str, write: _WriteCallback, escape: Callable[[str], str] = ...) -> None: ...\n    def dump_bytes(self, value: ReadableBuffer, write: _WriteCallback) -> None: ...\n    def dump_array(self, value: Iterable[_Marshallable], write: _WriteCallback) -> None: ...\n    def dump_struct(\n        self, value: Mapping[str, _Marshallable], write: _WriteCallback, escape: Callable[[str], str] = ...\n    ) -> None: ...\n    def dump_datetime(self, value: _XMLDate, write: _WriteCallback) -> None: ...\n    def dump_instance(self, value: object, write: _WriteCallback) -> None: ...\n\nclass Unmarshaller:\n    dispatch: dict[str, Callable[[Unmarshaller, str], None]]\n\n    _type: str | None\n    _stack: list[_Marshallable]\n    _marks: list[int]\n    _data: list[str]\n    _value: bool\n    _methodname: str | None\n    _encoding: str\n    append: Callable[[Any], None]\n    _use_datetime: bool\n    _use_builtin_types: bool\n    def __init__(self, use_datetime: bool = False, use_builtin_types: bool = False) -> None: ...\n    def close(self) -> tuple[_Marshallable, ...]: ...\n    def getmethodname(self) -> str | None: ...\n    def xml(self, encoding: str, standalone: Any) -> None: ...  # Standalone is ignored\n    def start(self, tag: str, attrs: dict[str, str]) -> None: ...\n    def data(self, text: str) -> None: ...\n    def end(self, tag: str) -> None: ...\n    def end_dispatch(self, tag: str, data: str) -> None: ...\n    def end_nil(self, data: str) -> None: ...\n    def end_boolean(self, data: str) -> None: ...\n    def end_int(self, data: str) -> None: ...\n    def end_double(self, data: str) -> None: ...\n    def end_bigdecimal(self, data: str) -> None: ...\n    def end_string(self, data: str) -> None: ...\n    def end_array(self, data: str) -> None: ...\n    def end_struct(self, data: str) -> None: ...\n    def end_base64(self, data: str) -> None: ...\n    def end_dateTime(self, data: str) -> None: ...\n    def end_value(self, data: str) -> None: ...\n    def end_params(self, data: str) -> None: ...\n    def end_fault(self, data: str) -> None: ...\n    def end_methodName(self, data: str) -> None: ...\n\nclass _MultiCallMethod:  # undocumented\n    __call_list: list[tuple[str, tuple[_Marshallable, ...]]]\n    __name: str\n    def __init__(self, call_list: list[tuple[str, _Marshallable]], name: str) -> None: ...\n    def __getattr__(self, name: str) -> _MultiCallMethod: ...\n    def __call__(self, *args: _Marshallable) -> None: ...\n\nclass MultiCallIterator:  # undocumented\n    results: list[list[_Marshallable]]\n    def __init__(self, results: list[list[_Marshallable]]) -> None: ...\n    def __getitem__(self, i: int) -> _Marshallable: ...\n\nclass MultiCall:\n    __server: ServerProxy\n    __call_list: list[tuple[str, tuple[_Marshallable, ...]]]\n    def __init__(self, server: ServerProxy) -> None: ...\n    def __getattr__(self, name: str) -> _MultiCallMethod: ...\n    def __call__(self) -> MultiCallIterator: ...\n\n# A little white lie\nFastMarshaller: Marshaller | None\nFastParser: ExpatParser | None\nFastUnmarshaller: Unmarshaller | None\n\ndef getparser(use_datetime: bool = False, use_builtin_types: bool = False) -> tuple[ExpatParser, Unmarshaller]: ...\ndef dumps(\n    params: Fault | tuple[_Marshallable, ...],\n    methodname: str | None = None,\n    methodresponse: bool | None = None,\n    encoding: str | None = None,\n    allow_none: bool = False,\n) -> str: ...\ndef loads(\n    data: str | ReadableBuffer, use_datetime: bool = False, use_builtin_types: bool = False\n) -> tuple[tuple[_Marshallable, ...], str | None]: ...\ndef gzip_encode(data: ReadableBuffer) -> bytes: ...  # undocumented\ndef gzip_decode(data: ReadableBuffer, max_decode: int = 20971520) -> bytes: ...  # undocumented\n\nclass GzipDecodedResponse(gzip.GzipFile):  # undocumented\n    io: BytesIO\n    def __init__(self, response: SupportsRead[ReadableBuffer]) -> None: ...\n\nclass _Method:  # undocumented\n    __send: Callable[[str, tuple[_Marshallable, ...]], _Marshallable]\n    __name: str\n    def __init__(self, send: Callable[[str, tuple[_Marshallable, ...]], _Marshallable], name: str) -> None: ...\n    def __getattr__(self, name: str) -> _Method: ...\n    def __call__(self, *args: _Marshallable) -> _Marshallable: ...\n\nclass Transport:\n    user_agent: str\n    accept_gzip_encoding: bool\n    encode_threshold: int | None\n\n    _use_datetime: bool\n    _use_builtin_types: bool\n    _connection: tuple[_HostType | None, http.client.HTTPConnection | None]\n    _headers: list[tuple[str, str]]\n    _extra_headers: list[tuple[str, str]]\n\n    def __init__(\n        self, use_datetime: bool = False, use_builtin_types: bool = False, *, headers: Iterable[tuple[str, str]] = ()\n    ) -> None: ...\n    def request(\n        self, host: _HostType, handler: str, request_body: SizedBuffer, verbose: bool = False\n    ) -> tuple[_Marshallable, ...]: ...\n    def single_request(\n        self, host: _HostType, handler: str, request_body: SizedBuffer, verbose: bool = False\n    ) -> tuple[_Marshallable, ...]: ...\n    def getparser(self) -> tuple[ExpatParser, Unmarshaller]: ...\n    def get_host_info(self, host: _HostType) -> tuple[str, list[tuple[str, str]], dict[str, str]]: ...\n    def make_connection(self, host: _HostType) -> http.client.HTTPConnection: ...\n    def close(self) -> None: ...\n    def send_request(\n        self, host: _HostType, handler: str, request_body: SizedBuffer, debug: bool\n    ) -> http.client.HTTPConnection: ...\n    def send_headers(self, connection: http.client.HTTPConnection, headers: list[tuple[str, str]]) -> None: ...\n    def send_content(self, connection: http.client.HTTPConnection, request_body: SizedBuffer) -> None: ...\n    def parse_response(self, response: http.client.HTTPResponse) -> tuple[_Marshallable, ...]: ...\n\nclass SafeTransport(Transport):\n    def __init__(\n        self,\n        use_datetime: bool = False,\n        use_builtin_types: bool = False,\n        *,\n        headers: Iterable[tuple[str, str]] = (),\n        context: Any | None = None,\n    ) -> None: ...\n    def make_connection(self, host: _HostType) -> http.client.HTTPSConnection: ...\n\nclass ServerProxy:\n    __host: str\n    __handler: str\n    __transport: Transport\n    __encoding: str\n    __verbose: bool\n    __allow_none: bool\n\n    def __init__(\n        self,\n        uri: str,\n        transport: Transport | None = None,\n        encoding: str | None = None,\n        verbose: bool = False,\n        allow_none: bool = False,\n        use_datetime: bool = False,\n        use_builtin_types: bool = False,\n        *,\n        headers: Iterable[tuple[str, str]] = (),\n        context: Any | None = None,\n    ) -> None: ...\n    def __getattr__(self, name: str) -> _Method: ...\n    @overload\n    def __call__(self, attr: Literal[\"close\"]) -> Callable[[], None]: ...\n    @overload\n    def __call__(self, attr: Literal[\"transport\"]) -> Transport: ...\n    @overload\n    def __call__(self, attr: str) -> Callable[[], None] | Transport: ...\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: TracebackType | None\n    ) -> None: ...\n    def __close(self) -> None: ...  # undocumented\n    def __request(self, methodname: str, params: tuple[_Marshallable, ...]) -> tuple[_Marshallable, ...]: ...  # undocumented\n\nServer = ServerProxy\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xmlrpc/server.pyi",
    "content": "import http.server\nimport pydoc\nimport socketserver\nfrom _typeshed import ReadableBuffer\nfrom collections.abc import Callable, Iterable, Mapping\nfrom re import Pattern\nfrom typing import Any, ClassVar, Protocol, type_check_only\nfrom typing_extensions import TypeAlias\nfrom xmlrpc.client import Fault, _Marshallable\n\n# The dispatch accepts anywhere from 0 to N arguments, no easy way to allow this in mypy\n@type_check_only\nclass _DispatchArity0(Protocol):\n    def __call__(self) -> _Marshallable: ...\n\n@type_check_only\nclass _DispatchArity1(Protocol):\n    def __call__(self, arg1: _Marshallable, /) -> _Marshallable: ...\n\n@type_check_only\nclass _DispatchArity2(Protocol):\n    def __call__(self, arg1: _Marshallable, arg2: _Marshallable, /) -> _Marshallable: ...\n\n@type_check_only\nclass _DispatchArity3(Protocol):\n    def __call__(self, arg1: _Marshallable, arg2: _Marshallable, arg3: _Marshallable, /) -> _Marshallable: ...\n\n@type_check_only\nclass _DispatchArity4(Protocol):\n    def __call__(\n        self, arg1: _Marshallable, arg2: _Marshallable, arg3: _Marshallable, arg4: _Marshallable, /\n    ) -> _Marshallable: ...\n\n@type_check_only\nclass _DispatchArityN(Protocol):\n    def __call__(self, *args: _Marshallable) -> _Marshallable: ...\n\n_DispatchProtocol: TypeAlias = (\n    _DispatchArity0 | _DispatchArity1 | _DispatchArity2 | _DispatchArity3 | _DispatchArity4 | _DispatchArityN\n)\n\ndef resolve_dotted_attribute(obj: Any, attr: str, allow_dotted_names: bool = True) -> Any: ...  # undocumented\ndef list_public_methods(obj: Any) -> list[str]: ...  # undocumented\n\nclass SimpleXMLRPCDispatcher:  # undocumented\n    funcs: dict[str, _DispatchProtocol]\n    instance: Any | None\n    allow_none: bool\n    encoding: str\n    use_builtin_types: bool\n    def __init__(self, allow_none: bool = False, encoding: str | None = None, use_builtin_types: bool = False) -> None: ...\n    def register_instance(self, instance: Any, allow_dotted_names: bool = False) -> None: ...\n    def register_function(self, function: _DispatchProtocol | None = None, name: str | None = None) -> Callable[..., Any]: ...\n    def register_introspection_functions(self) -> None: ...\n    def register_multicall_functions(self) -> None: ...\n    def _marshaled_dispatch(\n        self,\n        data: str | ReadableBuffer,\n        dispatch_method: Callable[[str, tuple[_Marshallable, ...]], Fault | tuple[_Marshallable, ...]] | None = None,\n        path: Any | None = None,\n    ) -> str: ...  # undocumented\n    def system_listMethods(self) -> list[str]: ...  # undocumented\n    def system_methodSignature(self, method_name: str) -> str: ...  # undocumented\n    def system_methodHelp(self, method_name: str) -> str: ...  # undocumented\n    def system_multicall(self, call_list: list[dict[str, _Marshallable]]) -> list[_Marshallable]: ...  # undocumented\n    def _dispatch(self, method: str, params: Iterable[_Marshallable]) -> _Marshallable: ...  # undocumented\n\nclass SimpleXMLRPCRequestHandler(http.server.BaseHTTPRequestHandler):\n    rpc_paths: ClassVar[tuple[str, ...]]\n    encode_threshold: int  # undocumented\n    aepattern: Pattern[str]  # undocumented\n    def accept_encodings(self) -> dict[str, float]: ...\n    def is_rpc_path_valid(self) -> bool: ...\n    def do_POST(self) -> None: ...\n    def decode_request_content(self, data: bytes) -> bytes | None: ...\n    def report_404(self) -> None: ...\n\nclass SimpleXMLRPCServer(socketserver.TCPServer, SimpleXMLRPCDispatcher):\n    _send_traceback_handler: bool\n    def __init__(\n        self,\n        addr: tuple[str, int],\n        requestHandler: type[SimpleXMLRPCRequestHandler] = ...,\n        logRequests: bool = True,\n        allow_none: bool = False,\n        encoding: str | None = None,\n        bind_and_activate: bool = True,\n        use_builtin_types: bool = False,\n    ) -> None: ...\n\nclass MultiPathXMLRPCServer(SimpleXMLRPCServer):  # undocumented\n    dispatchers: dict[str, SimpleXMLRPCDispatcher]\n    def __init__(\n        self,\n        addr: tuple[str, int],\n        requestHandler: type[SimpleXMLRPCRequestHandler] = ...,\n        logRequests: bool = True,\n        allow_none: bool = False,\n        encoding: str | None = None,\n        bind_and_activate: bool = True,\n        use_builtin_types: bool = False,\n    ) -> None: ...\n    def add_dispatcher(self, path: str, dispatcher: SimpleXMLRPCDispatcher) -> SimpleXMLRPCDispatcher: ...\n    def get_dispatcher(self, path: str) -> SimpleXMLRPCDispatcher: ...\n\nclass CGIXMLRPCRequestHandler(SimpleXMLRPCDispatcher):\n    def __init__(self, allow_none: bool = False, encoding: str | None = None, use_builtin_types: bool = False) -> None: ...\n    def handle_xmlrpc(self, request_text: str) -> None: ...\n    def handle_get(self) -> None: ...\n    def handle_request(self, request_text: str | None = None) -> None: ...\n\nclass ServerHTMLDoc(pydoc.HTMLDoc):  # undocumented\n    def docroutine(  # type: ignore[override]\n        self,\n        object: object,\n        name: str,\n        mod: str | None = None,\n        funcs: Mapping[str, str] = {},\n        classes: Mapping[str, str] = {},\n        methods: Mapping[str, str] = {},\n        cl: type | None = None,\n    ) -> str: ...\n    def docserver(self, server_name: str, package_documentation: str, methods: dict[str, str]) -> str: ...\n\nclass XMLRPCDocGenerator:  # undocumented\n    server_name: str\n    server_documentation: str\n    server_title: str\n    def set_server_title(self, server_title: str) -> None: ...\n    def set_server_name(self, server_name: str) -> None: ...\n    def set_server_documentation(self, server_documentation: str) -> None: ...\n    def generate_html_documentation(self) -> str: ...\n\nclass DocXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):\n    def do_GET(self) -> None: ...\n\nclass DocXMLRPCServer(SimpleXMLRPCServer, XMLRPCDocGenerator):\n    def __init__(\n        self,\n        addr: tuple[str, int],\n        requestHandler: type[SimpleXMLRPCRequestHandler] = ...,\n        logRequests: bool = True,\n        allow_none: bool = False,\n        encoding: str | None = None,\n        bind_and_activate: bool = True,\n        use_builtin_types: bool = False,\n    ) -> None: ...\n\nclass DocCGIXMLRPCRequestHandler(CGIXMLRPCRequestHandler, XMLRPCDocGenerator):\n    def __init__(self) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/xxlimited.pyi",
    "content": "import sys\nfrom typing import Any, ClassVar, final\n\nclass Str(str): ...\n\n@final\nclass Xxo:\n    def demo(self) -> None: ...\n    if sys.version_info >= (3, 11) and sys.platform != \"win32\":\n        x_exports: int\n\ndef foo(i: int, j: int, /) -> Any: ...\ndef new() -> Xxo: ...\n\nif sys.version_info >= (3, 10):\n    class Error(Exception): ...\n\nelse:\n    class error(Exception): ...\n\n    class Null:\n        __hash__: ClassVar[None]  # type: ignore[assignment]\n\n    def roj(b: Any, /) -> None: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/zipapp.pyi",
    "content": "from collections.abc import Callable\nfrom pathlib import Path\nfrom typing import BinaryIO\nfrom typing_extensions import TypeAlias\n\n__all__ = [\"ZipAppError\", \"create_archive\", \"get_interpreter\"]\n\n_Path: TypeAlias = str | Path | BinaryIO\n\nclass ZipAppError(ValueError): ...\n\ndef create_archive(\n    source: _Path,\n    target: _Path | None = None,\n    interpreter: str | None = None,\n    main: str | None = None,\n    filter: Callable[[Path], bool] | None = None,\n    compressed: bool = False,\n) -> None: ...\ndef get_interpreter(archive: _Path) -> str: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/zipfile/__init__.pyi",
    "content": "import io\nimport sys\nfrom _typeshed import SizedBuffer, StrOrBytesPath, StrPath\nfrom collections.abc import Callable, Iterable, Iterator\nfrom io import TextIOWrapper\nfrom os import PathLike\nfrom types import TracebackType\nfrom typing import IO, Final, Literal, Protocol, overload, type_check_only\nfrom typing_extensions import Self, TypeAlias\n\n__all__ = [\n    \"BadZipFile\",\n    \"BadZipfile\",\n    \"Path\",\n    \"error\",\n    \"ZIP_STORED\",\n    \"ZIP_DEFLATED\",\n    \"ZIP_BZIP2\",\n    \"ZIP_LZMA\",\n    \"is_zipfile\",\n    \"ZipInfo\",\n    \"ZipFile\",\n    \"PyZipFile\",\n    \"LargeZipFile\",\n]\n\nif sys.version_info >= (3, 14):\n    __all__ += [\"ZIP_ZSTANDARD\"]\n\n# TODO: use TypeAlias for these two when mypy bugs are fixed\n# https://github.com/python/mypy/issues/16581\n_DateTuple = tuple[int, int, int, int, int, int]  # noqa: Y026\n_ZipFileMode = Literal[\"r\", \"w\", \"x\", \"a\"]  # noqa: Y026\n\n_ReadWriteMode: TypeAlias = Literal[\"r\", \"w\"]\n\nclass BadZipFile(Exception): ...\n\nBadZipfile = BadZipFile\nerror = BadZipfile\n\nclass LargeZipFile(Exception): ...\n\n@type_check_only\nclass _ZipStream(Protocol):\n    def read(self, n: int, /) -> bytes: ...\n    # The following methods are optional:\n    # def seekable(self) -> bool: ...\n    # def tell(self) -> int: ...\n    # def seek(self, n: int, /) -> object: ...\n\n# Stream shape as required by _EndRecData() and _EndRecData64().\n@type_check_only\nclass _SupportsReadSeekTell(Protocol):\n    def read(self, n: int = ..., /) -> bytes: ...\n    def seek(self, cookie: int, whence: int, /) -> object: ...\n    def tell(self) -> int: ...\n\n@type_check_only\nclass _ClosableZipStream(_ZipStream, Protocol):\n    def close(self) -> object: ...\n\nclass ZipExtFile(io.BufferedIOBase):\n    MAX_N: int\n    MIN_READ_SIZE: int\n    MAX_SEEK_READ: int\n    newlines: list[bytes] | None\n    mode: _ReadWriteMode\n    name: str\n    @overload\n    def __init__(\n        self, fileobj: _ClosableZipStream, mode: _ReadWriteMode, zipinfo: ZipInfo, pwd: bytes | None, close_fileobj: Literal[True]\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        fileobj: _ClosableZipStream,\n        mode: _ReadWriteMode,\n        zipinfo: ZipInfo,\n        pwd: bytes | None = None,\n        *,\n        close_fileobj: Literal[True],\n    ) -> None: ...\n    @overload\n    def __init__(\n        self,\n        fileobj: _ZipStream,\n        mode: _ReadWriteMode,\n        zipinfo: ZipInfo,\n        pwd: bytes | None = None,\n        close_fileobj: Literal[False] = False,\n    ) -> None: ...\n    def read(self, n: int | None = -1) -> bytes: ...\n    def readline(self, limit: int = -1) -> bytes: ...  # type: ignore[override]\n    def peek(self, n: int = 1) -> bytes: ...\n    def read1(self, n: int | None) -> bytes: ...  # type: ignore[override]\n    def seek(self, offset: int, whence: int = 0) -> int: ...\n\n@type_check_only\nclass _Writer(Protocol):\n    def write(self, s: str, /) -> object: ...\n\n@type_check_only\nclass _ZipReadable(Protocol):\n    def seek(self, offset: int, whence: int = 0, /) -> int: ...\n    def read(self, n: int = -1, /) -> bytes: ...\n\n@type_check_only\nclass _ZipTellable(Protocol):\n    def tell(self) -> int: ...\n\n@type_check_only\nclass _ZipReadableTellable(_ZipReadable, _ZipTellable, Protocol): ...\n\n@type_check_only\nclass _ZipWritable(Protocol):\n    def flush(self) -> None: ...\n    def close(self) -> None: ...\n    def write(self, b: bytes, /) -> int: ...\n\nclass ZipFile:\n    filename: str | None\n    debug: int\n    comment: bytes\n    filelist: list[ZipInfo]\n    fp: IO[bytes] | None\n    NameToInfo: dict[str, ZipInfo]\n    start_dir: int  # undocumented\n    compression: int  # undocumented\n    compresslevel: int | None  # undocumented\n    mode: _ZipFileMode  # undocumented\n    pwd: bytes | None  # undocumented\n    # metadata_encoding is new in 3.11\n    if sys.version_info >= (3, 11):\n        @overload\n        def __init__(\n            self,\n            file: StrPath | IO[bytes],\n            mode: _ZipFileMode = \"r\",\n            compression: int = 0,\n            allowZip64: bool = True,\n            compresslevel: int | None = None,\n            *,\n            strict_timestamps: bool = True,\n            metadata_encoding: str | None = None,\n        ) -> None: ...\n        # metadata_encoding is only allowed for read mode\n        @overload\n        def __init__(\n            self,\n            file: StrPath | _ZipReadable,\n            mode: Literal[\"r\"] = \"r\",\n            compression: int = 0,\n            allowZip64: bool = True,\n            compresslevel: int | None = None,\n            *,\n            strict_timestamps: bool = True,\n            metadata_encoding: str | None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            file: StrPath | _ZipWritable,\n            mode: Literal[\"w\", \"x\"],\n            compression: int = 0,\n            allowZip64: bool = True,\n            compresslevel: int | None = None,\n            *,\n            strict_timestamps: bool = True,\n            metadata_encoding: None = None,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            file: StrPath | _ZipReadableTellable,\n            mode: Literal[\"a\"],\n            compression: int = 0,\n            allowZip64: bool = True,\n            compresslevel: int | None = None,\n            *,\n            strict_timestamps: bool = True,\n            metadata_encoding: None = None,\n        ) -> None: ...\n    else:\n        @overload\n        def __init__(\n            self,\n            file: StrPath | IO[bytes],\n            mode: _ZipFileMode = \"r\",\n            compression: int = 0,\n            allowZip64: bool = True,\n            compresslevel: int | None = None,\n            *,\n            strict_timestamps: bool = True,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            file: StrPath | _ZipReadable,\n            mode: Literal[\"r\"] = \"r\",\n            compression: int = 0,\n            allowZip64: bool = True,\n            compresslevel: int | None = None,\n            *,\n            strict_timestamps: bool = True,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            file: StrPath | _ZipWritable,\n            mode: Literal[\"w\", \"x\"],\n            compression: int = 0,\n            allowZip64: bool = True,\n            compresslevel: int | None = None,\n            *,\n            strict_timestamps: bool = True,\n        ) -> None: ...\n        @overload\n        def __init__(\n            self,\n            file: StrPath | _ZipReadableTellable,\n            mode: Literal[\"a\"],\n            compression: int = 0,\n            allowZip64: bool = True,\n            compresslevel: int | None = None,\n            *,\n            strict_timestamps: bool = True,\n        ) -> None: ...\n\n    def __enter__(self) -> Self: ...\n    def __exit__(\n        self, type: type[BaseException] | None, value: BaseException | None, traceback: TracebackType | None\n    ) -> None: ...\n    def close(self) -> None: ...\n    def getinfo(self, name: str) -> ZipInfo: ...\n    def infolist(self) -> list[ZipInfo]: ...\n    def namelist(self) -> list[str]: ...\n    def open(\n        self, name: str | ZipInfo, mode: _ReadWriteMode = \"r\", pwd: bytes | None = None, *, force_zip64: bool = False\n    ) -> IO[bytes]: ...\n    def extract(self, member: str | ZipInfo, path: StrPath | None = None, pwd: bytes | None = None) -> str: ...\n    def extractall(\n        self, path: StrPath | None = None, members: Iterable[str | ZipInfo] | None = None, pwd: bytes | None = None\n    ) -> None: ...\n    def printdir(self, file: _Writer | None = None) -> None: ...\n    def setpassword(self, pwd: bytes) -> None: ...\n    def read(self, name: str | ZipInfo, pwd: bytes | None = None) -> bytes: ...\n    def testzip(self) -> str | None: ...\n    def write(\n        self,\n        filename: StrPath,\n        arcname: StrPath | None = None,\n        compress_type: int | None = None,\n        compresslevel: int | None = None,\n    ) -> None: ...\n    def writestr(\n        self,\n        zinfo_or_arcname: str | ZipInfo,\n        data: SizedBuffer | str,\n        compress_type: int | None = None,\n        compresslevel: int | None = None,\n    ) -> None: ...\n    if sys.version_info >= (3, 11):\n        def mkdir(self, zinfo_or_directory_name: str | ZipInfo, mode: int = 0o777) -> None: ...\n\n    def __del__(self) -> None: ...\n\nclass PyZipFile(ZipFile):\n    def __init__(\n        self, file: str | IO[bytes], mode: _ZipFileMode = \"r\", compression: int = 0, allowZip64: bool = True, optimize: int = -1\n    ) -> None: ...\n    def writepy(self, pathname: str, basename: str = \"\", filterfunc: Callable[[str], bool] | None = None) -> None: ...\n\nclass ZipInfo:\n    __slots__ = (\n        \"orig_filename\",\n        \"filename\",\n        \"date_time\",\n        \"compress_type\",\n        \"compress_level\",\n        \"comment\",\n        \"extra\",\n        \"create_system\",\n        \"create_version\",\n        \"extract_version\",\n        \"reserved\",\n        \"flag_bits\",\n        \"volume\",\n        \"internal_attr\",\n        \"external_attr\",\n        \"header_offset\",\n        \"CRC\",\n        \"compress_size\",\n        \"file_size\",\n        \"_raw_time\",\n        \"_end_offset\",\n    )\n    filename: str\n    date_time: _DateTuple\n    compress_type: int\n    comment: bytes\n    extra: bytes\n    create_system: int\n    create_version: int\n    extract_version: int\n    reserved: int\n    flag_bits: int\n    volume: int\n    internal_attr: int\n    external_attr: int\n    header_offset: int\n    CRC: int\n    compress_size: int\n    file_size: int\n    orig_filename: str  # undocumented\n    if sys.version_info >= (3, 13):\n        compress_level: int | None\n\n    def __init__(self, filename: str = \"NoName\", date_time: _DateTuple = (1980, 1, 1, 0, 0, 0)) -> None: ...\n    @classmethod\n    def from_file(cls, filename: StrPath, arcname: StrPath | None = None, *, strict_timestamps: bool = True) -> Self: ...\n    def is_dir(self) -> bool: ...\n    def FileHeader(self, zip64: bool | None = None) -> bytes: ...\n    if sys.version_info >= (3, 14):\n        def _for_archive(self, archive: ZipFile) -> Self: ...\n\nif sys.version_info >= (3, 12):\n    from zipfile._path import CompleteDirs as CompleteDirs, Path as Path\n\nelse:\n    class CompleteDirs(ZipFile):\n        def resolve_dir(self, name: str) -> str: ...\n        @overload\n        @classmethod\n        def make(cls, source: ZipFile) -> CompleteDirs: ...\n        @overload\n        @classmethod\n        def make(cls, source: StrPath | IO[bytes]) -> Self: ...\n\n    class Path:\n        root: CompleteDirs\n        at: str\n        def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = \"\") -> None: ...\n        @property\n        def name(self) -> str: ...\n        @property\n        def parent(self) -> PathLike[str]: ...  # undocumented\n        if sys.version_info >= (3, 10):\n            @property\n            def filename(self) -> PathLike[str]: ...  # undocumented\n        if sys.version_info >= (3, 11):\n            @property\n            def suffix(self) -> str: ...\n            @property\n            def suffixes(self) -> list[str]: ...\n            @property\n            def stem(self) -> str: ...\n\n        @overload\n        def open(\n            self,\n            mode: Literal[\"r\", \"w\"] = \"r\",\n            encoding: str | None = None,\n            errors: str | None = None,\n            newline: str | None = None,\n            line_buffering: bool = False,\n            write_through: bool = False,\n            *,\n            pwd: bytes | None = None,\n        ) -> TextIOWrapper: ...\n        @overload\n        def open(self, mode: Literal[\"rb\", \"wb\"], *, pwd: bytes | None = None) -> IO[bytes]: ...\n\n        if sys.version_info >= (3, 10):\n            def iterdir(self) -> Iterator[Self]: ...\n        else:\n            def iterdir(self) -> Iterator[Path]: ...\n\n        def is_dir(self) -> bool: ...\n        def is_file(self) -> bool: ...\n        def exists(self) -> bool: ...\n        def read_text(\n            self,\n            encoding: str | None = None,\n            errors: str | None = None,\n            newline: str | None = None,\n            line_buffering: bool = False,\n            write_through: bool = False,\n        ) -> str: ...\n        def read_bytes(self) -> bytes: ...\n        if sys.version_info >= (3, 10):\n            def joinpath(self, *other: StrPath) -> Path: ...\n        else:\n            def joinpath(self, add: StrPath) -> Path: ...  # undocumented\n\n        def __truediv__(self, add: StrPath) -> Path: ...\n\ndef is_zipfile(filename: StrOrBytesPath | _SupportsReadSeekTell) -> bool: ...\n\nZIP64_LIMIT: Final[int]\nZIP_FILECOUNT_LIMIT: Final[int]\nZIP_MAX_COMMENT: Final[int]\n\nZIP_STORED: Final = 0\nZIP_DEFLATED: Final = 8\nZIP_BZIP2: Final = 12\nZIP_LZMA: Final = 14\nif sys.version_info >= (3, 14):\n    ZIP_ZSTANDARD: Final = 93\n\nDEFAULT_VERSION: Final[int]\nZIP64_VERSION: Final[int]\nBZIP2_VERSION: Final[int]\nLZMA_VERSION: Final[int]\nif sys.version_info >= (3, 14):\n    ZSTANDARD_VERSION: Final[int]\nMAX_EXTRACT_VERSION: Final[int]\n"
  },
  {
    "path": "mypy/typeshed/stdlib/zipfile/_path/__init__.pyi",
    "content": "import sys\nfrom _typeshed import StrPath\nfrom collections.abc import Iterator, Sequence\nfrom io import TextIOWrapper\nfrom os import PathLike\nfrom typing import IO, Literal, TypeVar, overload\nfrom typing_extensions import Self\nfrom zipfile import ZipFile\n\n_ZF = TypeVar(\"_ZF\", bound=ZipFile)\n\nif sys.version_info >= (3, 12):\n    __all__ = [\"Path\"]\n\n    class InitializedState:\n        def __init__(self, *args: object, **kwargs: object) -> None: ...\n        def __getstate__(self) -> tuple[list[object], dict[object, object]]: ...\n        def __setstate__(self, state: Sequence[tuple[list[object], dict[object, object]]]) -> None: ...\n\n    class CompleteDirs(InitializedState, ZipFile):\n        def resolve_dir(self, name: str) -> str: ...\n        @overload\n        @classmethod\n        def make(cls, source: ZipFile) -> CompleteDirs: ...\n        @overload\n        @classmethod\n        def make(cls, source: StrPath | IO[bytes]) -> Self: ...\n        if sys.version_info >= (3, 13):\n            @classmethod\n            def inject(cls, zf: _ZF) -> _ZF: ...\n\n    class Path:\n        root: CompleteDirs\n        at: str\n        def __init__(self, root: ZipFile | StrPath | IO[bytes], at: str = \"\") -> None: ...\n        @property\n        def name(self) -> str: ...\n        @property\n        def parent(self) -> PathLike[str]: ...  # undocumented\n        @property\n        def filename(self) -> PathLike[str]: ...  # undocumented\n        @property\n        def suffix(self) -> str: ...\n        @property\n        def suffixes(self) -> list[str]: ...\n        @property\n        def stem(self) -> str: ...\n        @overload\n        def open(\n            self,\n            mode: Literal[\"r\", \"w\"] = \"r\",\n            encoding: str | None = None,\n            errors: str | None = None,\n            newline: str | None = None,\n            line_buffering: bool = False,\n            write_through: bool = False,\n            *,\n            pwd: bytes | None = None,\n        ) -> TextIOWrapper: ...\n        @overload\n        def open(self, mode: Literal[\"rb\", \"wb\"], *, pwd: bytes | None = None) -> IO[bytes]: ...\n        def iterdir(self) -> Iterator[Self]: ...\n        def is_dir(self) -> bool: ...\n        def is_file(self) -> bool: ...\n        def exists(self) -> bool: ...\n        def read_text(\n            self,\n            encoding: str | None = None,\n            errors: str | None = None,\n            newline: str | None = None,\n            line_buffering: bool = False,\n            write_through: bool = False,\n        ) -> str: ...\n        def read_bytes(self) -> bytes: ...\n        def joinpath(self, *other: StrPath) -> Path: ...\n        def glob(self, pattern: str) -> Iterator[Self]: ...\n        def rglob(self, pattern: str) -> Iterator[Self]: ...\n        def is_symlink(self) -> Literal[False]: ...\n        def relative_to(self, other: Path, *extra: StrPath) -> str: ...\n        def match(self, path_pattern: str) -> bool: ...\n        def __eq__(self, other: object) -> bool: ...\n        def __hash__(self) -> int: ...\n        def __truediv__(self, add: StrPath) -> Path: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/zipfile/_path/glob.pyi",
    "content": "import sys\nfrom collections.abc import Iterator\nfrom re import Match\n\nif sys.version_info >= (3, 13):\n    class Translator:\n        if sys.platform == \"win32\":\n            def __init__(self, seps: str = \"\\\\/\") -> None: ...\n        else:\n            def __init__(self, seps: str = \"/\") -> None: ...\n\n        def translate(self, pattern: str) -> str: ...\n        def extend(self, pattern: str) -> str: ...\n        def match_dirs(self, pattern: str) -> str: ...\n        def translate_core(self, pattern: str) -> str: ...\n        def replace(self, match: Match[str]) -> str: ...\n        def restrict_rglob(self, pattern: str) -> None: ...\n        def star_not_empty(self, pattern: str) -> str: ...\n\nelse:\n    def translate(pattern: str) -> str: ...\n    def match_dirs(pattern: str) -> str: ...\n    def translate_core(pattern: str) -> str: ...\n    def replace(match: Match[str]) -> str: ...\n\ndef separate(pattern: str) -> Iterator[Match[str]]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/zipimport.pyi",
    "content": "import sys\nfrom _typeshed import StrOrBytesPath\nfrom importlib.machinery import ModuleSpec\nfrom types import CodeType, ModuleType\nfrom typing_extensions import deprecated\n\nif sys.version_info >= (3, 10):\n    from importlib.readers import ZipReader\nelse:\n    from importlib.abc import ResourceReader\n\nif sys.version_info >= (3, 10):\n    from _frozen_importlib_external import _LoaderBasics\nelse:\n    _LoaderBasics = object\n\n__all__ = [\"ZipImportError\", \"zipimporter\"]\n\nclass ZipImportError(ImportError): ...\n\nclass zipimporter(_LoaderBasics):\n    archive: str\n    prefix: str\n    if sys.version_info >= (3, 11):\n        def __init__(self, path: str) -> None: ...\n    else:\n        def __init__(self, path: StrOrBytesPath) -> None: ...\n\n    if sys.version_info < (3, 12):\n        if sys.version_info >= (3, 10):\n            @deprecated(\"Deprecated since Python 3.10; removed in Python 3.12. Use `find_spec()` instead.\")\n            def find_loader(self, fullname: str, path: str | None = None) -> tuple[zipimporter | None, list[str]]: ...\n            @deprecated(\"Deprecated since Python 3.10; removed in Python 3.12. Use `find_spec()` instead.\")\n            def find_module(self, fullname: str, path: str | None = None) -> zipimporter | None: ...\n        else:\n            def find_loader(self, fullname: str, path: str | None = None) -> tuple[zipimporter | None, list[str]]: ...\n            def find_module(self, fullname: str, path: str | None = None) -> zipimporter | None: ...\n\n    def get_code(self, fullname: str) -> CodeType: ...\n    def get_data(self, pathname: str) -> bytes: ...\n    def get_filename(self, fullname: str) -> str: ...\n    if sys.version_info >= (3, 14):\n        def get_resource_reader(self, fullname: str) -> ZipReader: ...  # undocumented\n    elif sys.version_info >= (3, 10):\n        def get_resource_reader(self, fullname: str) -> ZipReader | None: ...  # undocumented\n    else:\n        def get_resource_reader(self, fullname: str) -> ResourceReader | None: ...  # undocumented\n\n    def get_source(self, fullname: str) -> str | None: ...\n    def is_package(self, fullname: str) -> bool: ...\n    if sys.version_info >= (3, 10):\n        @deprecated(\"Deprecated since Python 3.10; removed in Python 3.15. Use `exec_module()` instead.\")\n        def load_module(self, fullname: str) -> ModuleType: ...\n        def exec_module(self, module: ModuleType) -> None: ...\n        def create_module(self, spec: ModuleSpec) -> None: ...\n        def find_spec(self, fullname: str, target: ModuleType | None = None) -> ModuleSpec | None: ...\n        def invalidate_caches(self) -> None: ...\n    else:\n        def load_module(self, fullname: str) -> ModuleType: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/zlib.pyi",
    "content": "import sys\nfrom _typeshed import ReadableBuffer\nfrom typing import Any, Final, final, type_check_only\nfrom typing_extensions import Self\n\nDEFLATED: Final = 8\nDEF_MEM_LEVEL: Final[int]\nDEF_BUF_SIZE: Final = 16384\nMAX_WBITS: Final[int]\nZLIB_VERSION: Final[str]\nZLIB_RUNTIME_VERSION: Final[str]\nZ_NO_COMPRESSION: Final = 0\nZ_PARTIAL_FLUSH: Final = 1\nZ_BEST_COMPRESSION: Final = 9\nZ_BEST_SPEED: Final = 1\nZ_BLOCK: Final = 5\nZ_DEFAULT_COMPRESSION: Final = -1\nZ_DEFAULT_STRATEGY: Final = 0\nZ_FILTERED: Final = 1\nZ_FINISH: Final = 4\nZ_FIXED: Final = 4\nZ_FULL_FLUSH: Final = 3\nZ_HUFFMAN_ONLY: Final = 2\nZ_NO_FLUSH: Final = 0\nZ_RLE: Final = 3\nZ_SYNC_FLUSH: Final = 2\nZ_TREES: Final = 6\n\nif sys.version_info >= (3, 14):\n    # Available when zlib was built with zlib-ng\n    ZLIBNG_VERSION: Final[str]\n\nclass error(Exception): ...\n\n# This class is not exposed at runtime. It calls itself zlib.Compress.\n@final\n@type_check_only\nclass _Compress:\n    def __copy__(self) -> Self: ...\n    def __deepcopy__(self, memo: Any, /) -> Self: ...\n    def compress(self, data: ReadableBuffer, /) -> bytes: ...\n    def flush(self, mode: int = 4, /) -> bytes: ...\n    def copy(self) -> _Compress: ...\n\n# This class is not exposed at runtime. It calls itself zlib.Decompress.\n@final\n@type_check_only\nclass _Decompress:\n    @property\n    def unused_data(self) -> bytes: ...\n    @property\n    def unconsumed_tail(self) -> bytes: ...\n    @property\n    def eof(self) -> bool: ...\n    def __copy__(self) -> Self: ...\n    def __deepcopy__(self, memo: Any, /) -> Self: ...\n    def decompress(self, data: ReadableBuffer, /, max_length: int = 0) -> bytes: ...\n    def flush(self, length: int = 16384, /) -> bytes: ...\n    def copy(self) -> _Decompress: ...\n\ndef adler32(data: ReadableBuffer, value: int = 1, /) -> int: ...\n\nif sys.version_info >= (3, 11):\n    def compress(data: ReadableBuffer, /, level: int = -1, wbits: int = 15) -> bytes: ...\n\nelse:\n    def compress(data: ReadableBuffer, /, level: int = -1) -> bytes: ...\n\ndef compressobj(\n    level: int = -1, method: int = 8, wbits: int = 15, memLevel: int = 8, strategy: int = 0, zdict: ReadableBuffer | None = None\n) -> _Compress: ...\ndef crc32(data: ReadableBuffer, value: int = 0, /) -> int: ...\ndef decompress(data: ReadableBuffer, /, wbits: int = 15, bufsize: int = 16384) -> bytes: ...\ndef decompressobj(wbits: int = 15, zdict: ReadableBuffer = b\"\") -> _Decompress: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/zoneinfo/__init__.pyi",
    "content": "import sys\nfrom collections.abc import Iterable\nfrom datetime import datetime, timedelta, tzinfo\nfrom typing_extensions import Self, disjoint_base\nfrom zoneinfo._common import ZoneInfoNotFoundError as ZoneInfoNotFoundError, _IOBytes\nfrom zoneinfo._tzpath import (\n    TZPATH as TZPATH,\n    InvalidTZPathWarning as InvalidTZPathWarning,\n    available_timezones as available_timezones,\n    reset_tzpath as reset_tzpath,\n)\n\n__all__ = [\"ZoneInfo\", \"reset_tzpath\", \"available_timezones\", \"TZPATH\", \"ZoneInfoNotFoundError\", \"InvalidTZPathWarning\"]\n\n@disjoint_base\nclass ZoneInfo(tzinfo):\n    @property\n    def key(self) -> str: ...\n    def __new__(cls, key: str) -> Self: ...\n    @classmethod\n    def no_cache(cls, key: str) -> Self: ...\n    if sys.version_info >= (3, 12):\n        @classmethod\n        def from_file(cls, file_obj: _IOBytes, /, key: str | None = None) -> Self: ...\n    else:\n        @classmethod\n        def from_file(cls, fobj: _IOBytes, /, key: str | None = None) -> Self: ...\n\n    @classmethod\n    def clear_cache(cls, *, only_keys: Iterable[str] | None = None) -> None: ...\n    def tzname(self, dt: datetime | None, /) -> str | None: ...\n    def utcoffset(self, dt: datetime | None, /) -> timedelta | None: ...\n    def dst(self, dt: datetime | None, /) -> timedelta | None: ...\n\ndef __dir__() -> list[str]: ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/zoneinfo/_common.pyi",
    "content": "import io\nfrom typing import Any, Protocol, type_check_only\n\n@type_check_only\nclass _IOBytes(Protocol):\n    def read(self, size: int, /) -> bytes: ...\n    def seek(self, size: int, whence: int = ..., /) -> Any: ...\n\ndef load_tzdata(key: str) -> io.BufferedReader: ...\ndef load_data(\n    fobj: _IOBytes,\n) -> tuple[tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[int, ...], tuple[str, ...], bytes | None]: ...\n\nclass ZoneInfoNotFoundError(KeyError): ...\n"
  },
  {
    "path": "mypy/typeshed/stdlib/zoneinfo/_tzpath.pyi",
    "content": "from _typeshed import StrPath\nfrom collections.abc import Sequence\n\n# Note: Both here and in clear_cache, the types allow the use of `str` where\n# a sequence of strings is required. This should be remedied if a solution\n# to this typing bug is found: https://github.com/python/typing/issues/256\ndef reset_tzpath(to: Sequence[StrPath] | None = None) -> None: ...\ndef find_tzfile(key: str) -> str | None: ...\ndef available_timezones() -> set[str]: ...\n\nTZPATH: tuple[str, ...]\n\nclass InvalidTZPathWarning(RuntimeWarning): ...\n"
  },
  {
    "path": "mypy/typeshed/stubs/librt/METADATA.toml",
    "content": "version = \"0.2.*\"\n"
  },
  {
    "path": "mypy/typeshed/stubs/librt/librt/__init__.pyi",
    "content": ""
  },
  {
    "path": "mypy/typeshed/stubs/librt/librt/base64.pyi",
    "content": "def b64encode(s: bytes) -> bytes: ...\ndef b64decode(s: bytes | str) -> bytes: ...\ndef urlsafe_b64encode(s: bytes) -> bytes: ...\ndef urlsafe_b64decode(s: bytes | str) -> bytes: ...\n"
  },
  {
    "path": "mypy/typeshed/stubs/librt/librt/internal.pyi",
    "content": "from mypy_extensions import u8\n\nclass ReadBuffer:\n    def __init__(self, source: bytes) -> None: ...\n\nclass WriteBuffer:\n    def getvalue(self) -> bytes: ...\n\ndef write_bool(data: WriteBuffer, value: bool, /) -> None: ...\ndef read_bool(data: ReadBuffer, /) -> bool: ...\ndef write_str(data: WriteBuffer, value: str, /) -> None: ...\ndef read_str(data: ReadBuffer, /) -> str: ...\ndef write_bytes(data: WriteBuffer, value: bytes, /) -> None: ...\ndef read_bytes(data: ReadBuffer, /) -> bytes: ...\ndef write_float(data: WriteBuffer, value: float, /) -> None: ...\ndef read_float(data: ReadBuffer, /) -> float: ...\ndef write_int(data: WriteBuffer, value: int, /) -> None: ...\ndef read_int(data: ReadBuffer, /) -> int: ...\ndef write_tag(data: WriteBuffer, value: u8, /) -> None: ...\ndef read_tag(data: ReadBuffer, /) -> u8: ...\ndef cache_version() -> u8: ...\n"
  },
  {
    "path": "mypy/typeshed/stubs/librt/librt/strings.pyi",
    "content": "from typing import final\n\nfrom mypy_extensions import i64, i32, i16, u8\n\n@final\nclass BytesWriter:\n    def append(self, x: int, /) -> None: ...\n    def write(self, b: bytes | bytearray, /) -> None: ...\n    def getvalue(self) -> bytes: ...\n    def truncate(self, size: i64, /) -> None: ...\n    def __len__(self) -> i64: ...\n    def __getitem__(self, i: i64, /) -> u8: ...\n    def __setitem__(self, i: i64, x: u8, /) -> None: ...\n\n@final\nclass StringWriter:\n    def append(self, x: int, /) -> None: ...\n    def write(self, s: str, /) -> None: ...\n    def getvalue(self) -> str: ...\n    def __len__(self) -> i64: ...\n    def __getitem__(self, i: i64, /) -> i32: ...\n\ndef write_i16_le(b: BytesWriter, n: i16, /) -> None: ...\ndef write_i16_be(b: BytesWriter, n: i16, /) -> None: ...\ndef read_i16_le(b: bytes, index: i64, /) -> i16: ...\ndef read_i16_be(b: bytes, index: i64, /) -> i16: ...\ndef write_i32_le(b: BytesWriter, n: i32, /) -> None: ...\ndef write_i32_be(b: BytesWriter, n: i32, /) -> None: ...\ndef read_i32_le(b: bytes, index: i64, /) -> i32: ...\ndef read_i32_be(b: bytes, index: i64, /) -> i32: ...\ndef write_i64_le(b: BytesWriter, n: i64, /) -> None: ...\ndef write_i64_be(b: BytesWriter, n: i64, /) -> None: ...\ndef read_i64_le(b: bytes, index: i64, /) -> i64: ...\ndef read_i64_be(b: bytes, index: i64, /) -> i64: ...\ndef write_f32_le(b: BytesWriter, n: float, /) -> None: ...\ndef write_f32_be(b: BytesWriter, n: float, /) -> None: ...\ndef read_f32_le(b: bytes, index: i64, /) -> float: ...\ndef read_f32_be(b: bytes, index: i64, /) -> float: ...\ndef write_f64_le(b: BytesWriter, n: float, /) -> None: ...\ndef write_f64_be(b: BytesWriter, n: float, /) -> None: ...\ndef read_f64_le(b: bytes, index: i64, /) -> float: ...\ndef read_f64_be(b: bytes, index: i64, /) -> float: ...\n"
  },
  {
    "path": "mypy/typeshed/stubs/librt/librt/time.pyi",
    "content": "def time() -> float: ...\n"
  },
  {
    "path": "mypy/typeshed/stubs/librt/librt/vecs.pyi",
    "content": "from typing import TypeVar, Generic, Iterable, Iterator, overload\nfrom mypy_extensions import i64\n\nT = TypeVar(\"T\")\n\nclass vec(Generic[T]):\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, items: Iterable[T], /) -> None: ...\n    def __len__(self) -> i64: ...\n    @overload\n    def __getitem__(self, i: i64, /) -> T: ...\n    @overload\n    def __getitem__(self, i: slice, /) -> vec[T]: ...\n    def __setitem__(self, i: i64, o: T, /) -> None: ...\n    def __iter__(self) -> Iterator[T]: ...\n\ndef append(v: vec[T], o: T, /) -> vec[T]: ...\ndef remove(v: vec[T], o: T, /) -> vec[T]: ...\ndef pop(v: vec[T], i: i64 = -1, /) -> tuple[vec[T], T]: ...\n"
  },
  {
    "path": "mypy/typeshed/stubs/mypy-extensions/@tests/stubtest_allowlist.txt",
    "content": "mypy_extensions.FlexibleAlias\nmypy_extensions.TypedDict\n"
  },
  {
    "path": "mypy/typeshed/stubs/mypy-extensions/METADATA.toml",
    "content": "version = \"1.0.*\"\n\n[tool.stubtest]\nignore_missing_stub = false\n"
  },
  {
    "path": "mypy/typeshed/stubs/mypy-extensions/mypy_extensions.pyi",
    "content": "# These stubs are forked from typeshed, since we use some definitions that only make\n# sense in the context of mypy/mypyc (in particular, native int types such as i64).\n\nimport abc\nimport sys\nfrom _collections_abc import dict_items, dict_keys, dict_values\nfrom _typeshed import IdentityFunction, Self\nfrom collections.abc import Mapping\nfrom typing import Any, ClassVar, Generic, SupportsInt, TypeVar, overload, type_check_only\nfrom typing_extensions import Never, SupportsIndex\nfrom _typeshed import ReadableBuffer, SupportsTrunc\n\n_T = TypeVar(\"_T\")\n_U = TypeVar(\"_U\")\n\n# Internal mypy fallback type for all typed dicts (does not exist at runtime)\n# N.B. Keep this mostly in sync with typing(_extensions)._TypedDict\n@type_check_only\nclass _TypedDict(Mapping[str, object], metaclass=abc.ABCMeta):\n    __total__: ClassVar[bool]\n    # Unlike typing(_extensions).TypedDict,\n    # subclasses of mypy_extensions.TypedDict do NOT have the __required_keys__ and __optional_keys__ ClassVars\n    def copy(self: Self) -> Self: ...\n    # Using Never so that only calls using mypy plugin hook that specialize the signature\n    # can go through.\n    def setdefault(self, k: Never, default: object) -> object: ...\n    # Mypy plugin hook for 'pop' expects that 'default' has a type variable type.\n    def pop(self, k: Never, default: _T = ...) -> object: ...  # pyright: ignore[reportInvalidTypeVarUse]\n    def update(self: Self, __m: Self) -> None: ...\n    def items(self) -> dict_items[str, object]: ...\n    def keys(self) -> dict_keys[str, object]: ...\n    def values(self) -> dict_values[str, object]: ...\n    def __delitem__(self, k: Never) -> None: ...\n    if sys.version_info >= (3, 9):\n        def __or__(self: Self, __other: Self) -> Self: ...\n        def __ior__(self: Self, __other: Self) -> Self: ...\n\ndef TypedDict(typename: str, fields: dict[str, type[Any]], total: bool = ...) -> type[dict[str, Any]]: ...\n@overload\ndef Arg(type: _T, name: str | None = ...) -> _T: ...\n@overload\ndef Arg(*, name: str | None = ...) -> Any: ...\n@overload\ndef DefaultArg(type: _T, name: str | None = ...) -> _T: ...\n@overload\ndef DefaultArg(*, name: str | None = ...) -> Any: ...\n@overload\ndef NamedArg(type: _T, name: str | None = ...) -> _T: ...\n@overload\ndef NamedArg(*, name: str | None = ...) -> Any: ...\n@overload\ndef DefaultNamedArg(type: _T, name: str | None = ...) -> _T: ...\n@overload\ndef DefaultNamedArg(*, name: str | None = ...) -> Any: ...\n@overload\ndef VarArg(type: _T) -> _T: ...\n@overload\ndef VarArg() -> Any: ...\n@overload\ndef KwArg(type: _T) -> _T: ...\n@overload\ndef KwArg() -> Any: ...\n\n# Return type that indicates a function does not return.\n# Deprecated: Use typing.NoReturn instead.\nclass NoReturn: ...\n\n# This is consistent with implementation. Usage intends for this as\n# a class decorator, but mypy does not support type[_T] for abstract\n# classes until this issue is resolved, https://github.com/python/mypy/issues/4717.\ndef trait(cls: _T) -> _T: ...\ndef mypyc_attr(*attrs: str, **kwattrs: object) -> IdentityFunction: ...\n\nclass FlexibleAlias(Generic[_T, _U]): ...\n\n# Native int types such as i64 are magical and support implicit\n# coercions to/from int using special logic in mypy. We generally only\n# include operations here for which we have specialized primitives.\n\nclass i64:\n    @overload\n    def __new__(cls, __x: str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> i64: ...\n    @overload\n    def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> i64: ...\n\n    def __add__(self, x: i64) -> i64: ...\n    def __radd__(self, x: i64) -> i64: ...\n    def __sub__(self, x: i64) -> i64: ...\n    def __rsub__(self, x: i64) -> i64: ...\n    def __mul__(self, x: i64) -> i64: ...\n    def __rmul__(self, x: i64) -> i64: ...\n    def __floordiv__(self, x: i64) -> i64: ...\n    def __rfloordiv__(self, x: i64) -> i64: ...\n    def __mod__(self, x: i64) -> i64: ...\n    def __rmod__(self, x: i64) -> i64: ...\n    def __and__(self, x: i64) -> i64: ...\n    def __rand__(self, x: i64) -> i64: ...\n    def __or__(self, x: i64) -> i64: ...\n    def __ror__(self, x: i64) -> i64: ...\n    def __xor__(self, x: i64) -> i64: ...\n    def __rxor__(self, x: i64) -> i64: ...\n    def __lshift__(self, x: i64) -> i64: ...\n    def __rlshift__(self, x: i64) -> i64: ...\n    def __rshift__(self, x: i64) -> i64: ...\n    def __rrshift__(self, x: i64) -> i64: ...\n    def __neg__(self) -> i64: ...\n    def __invert__(self) -> i64: ...\n    def __pos__(self) -> i64: ...\n    def __lt__(self, x: i64) -> bool: ...\n    def __le__(self, x: i64) -> bool: ...\n    def __ge__(self, x: i64) -> bool: ...\n    def __gt__(self, x: i64) -> bool: ...\n    def __index__(self) -> int: ...\n    def __eq__(self, x: object) -> bool: ...\n\nclass i32:\n    @overload\n    def __new__(cls, __x: str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> i32: ...\n    @overload\n    def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> i32: ...\n\n    def __add__(self, x: i32) -> i32: ...\n    def __radd__(self, x: i32) -> i32: ...\n    def __sub__(self, x: i32) -> i32: ...\n    def __rsub__(self, x: i32) -> i32: ...\n    def __mul__(self, x: i32) -> i32: ...\n    def __rmul__(self, x: i32) -> i32: ...\n    def __floordiv__(self, x: i32) -> i32: ...\n    def __rfloordiv__(self, x: i32) -> i32: ...\n    def __mod__(self, x: i32) -> i32: ...\n    def __rmod__(self, x: i32) -> i32: ...\n    def __and__(self, x: i32) -> i32: ...\n    def __rand__(self, x: i32) -> i32: ...\n    def __or__(self, x: i32) -> i32: ...\n    def __ror__(self, x: i32) -> i32: ...\n    def __xor__(self, x: i32) -> i32: ...\n    def __rxor__(self, x: i32) -> i32: ...\n    def __lshift__(self, x: i32) -> i32: ...\n    def __rlshift__(self, x: i32) -> i32: ...\n    def __rshift__(self, x: i32) -> i32: ...\n    def __rrshift__(self, x: i32) -> i32: ...\n    def __neg__(self) -> i32: ...\n    def __invert__(self) -> i32: ...\n    def __pos__(self) -> i32: ...\n    def __lt__(self, x: i32) -> bool: ...\n    def __le__(self, x: i32) -> bool: ...\n    def __ge__(self, x: i32) -> bool: ...\n    def __gt__(self, x: i32) -> bool: ...\n    def __index__(self) -> int: ...\n    def __eq__(self, x: object) -> bool: ...\n\nclass i16:\n    @overload\n    def __new__(cls, __x: str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> i16: ...\n    @overload\n    def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> i16: ...\n\n    def __add__(self, x: i16) -> i16: ...\n    def __radd__(self, x: i16) -> i16: ...\n    def __sub__(self, x: i16) -> i16: ...\n    def __rsub__(self, x: i16) -> i16: ...\n    def __mul__(self, x: i16) -> i16: ...\n    def __rmul__(self, x: i16) -> i16: ...\n    def __floordiv__(self, x: i16) -> i16: ...\n    def __rfloordiv__(self, x: i16) -> i16: ...\n    def __mod__(self, x: i16) -> i16: ...\n    def __rmod__(self, x: i16) -> i16: ...\n    def __and__(self, x: i16) -> i16: ...\n    def __rand__(self, x: i16) -> i16: ...\n    def __or__(self, x: i16) -> i16: ...\n    def __ror__(self, x: i16) -> i16: ...\n    def __xor__(self, x: i16) -> i16: ...\n    def __rxor__(self, x: i16) -> i16: ...\n    def __lshift__(self, x: i16) -> i16: ...\n    def __rlshift__(self, x: i16) -> i16: ...\n    def __rshift__(self, x: i16) -> i16: ...\n    def __rrshift__(self, x: i16) -> i16: ...\n    def __neg__(self) -> i16: ...\n    def __invert__(self) -> i16: ...\n    def __pos__(self) -> i16: ...\n    def __lt__(self, x: i16) -> bool: ...\n    def __le__(self, x: i16) -> bool: ...\n    def __ge__(self, x: i16) -> bool: ...\n    def __gt__(self, x: i16) -> bool: ...\n    def __index__(self) -> int: ...\n    def __eq__(self, x: object) -> bool: ...\n\nclass u8:\n    @overload\n    def __new__(cls, __x: str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc = ...) -> u8: ...\n    @overload\n    def __new__(cls, __x: str | bytes | bytearray, base: SupportsIndex) -> u8: ...\n\n    def __add__(self, x: u8) -> u8: ...\n    def __radd__(self, x: u8) -> u8: ...\n    def __sub__(self, x: u8) -> u8: ...\n    def __rsub__(self, x: u8) -> u8: ...\n    def __mul__(self, x: u8) -> u8: ...\n    def __rmul__(self, x: u8) -> u8: ...\n    def __floordiv__(self, x: u8) -> u8: ...\n    def __rfloordiv__(self, x: u8) -> u8: ...\n    def __mod__(self, x: u8) -> u8: ...\n    def __rmod__(self, x: u8) -> u8: ...\n    def __and__(self, x: u8) -> u8: ...\n    def __rand__(self, x: u8) -> u8: ...\n    def __or__(self, x: u8) -> u8: ...\n    def __ror__(self, x: u8) -> u8: ...\n    def __xor__(self, x: u8) -> u8: ...\n    def __rxor__(self, x: u8) -> u8: ...\n    def __lshift__(self, x: u8) -> u8: ...\n    def __rlshift__(self, x: u8) -> u8: ...\n    def __rshift__(self, x: u8) -> u8: ...\n    def __rrshift__(self, x: u8) -> u8: ...\n    def __neg__(self) -> u8: ...\n    def __invert__(self) -> u8: ...\n    def __pos__(self) -> u8: ...\n    def __lt__(self, x: u8) -> bool: ...\n    def __le__(self, x: u8) -> bool: ...\n    def __ge__(self, x: u8) -> bool: ...\n    def __gt__(self, x: u8) -> bool: ...\n    def __index__(self) -> int: ...\n    def __eq__(self, x: object) -> bool: ...\n"
  },
  {
    "path": "mypy/typestate.py",
    "content": "\"\"\"\nA shared state for all TypeInfos that holds global cache and dependency information,\nand potentially other mutable TypeInfo state. This module contains mutable global state.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final, TypeAlias as _TypeAlias\n\nfrom mypy.nodes import VARIANCE_NOT_READY, TypeInfo\nfrom mypy.server.trigger import make_trigger\nfrom mypy.types import Instance, Type, TypeVarId, TypeVarType, get_proper_type\n\nMAX_NEGATIVE_CACHE_TYPES: Final = 1000\nMAX_NEGATIVE_CACHE_ENTRIES: Final = 10000\n\n# Represents that the 'left' instance is a subtype of the 'right' instance\nSubtypeRelationship: _TypeAlias = tuple[Instance, Instance]\n\n# A tuple encoding the specific conditions under which we performed the subtype check.\n# (e.g. did we want a proper subtype? A regular subtype while ignoring variance?)\nSubtypeKind: _TypeAlias = tuple[bool, ...]\n\n# A cache that keeps track of whether the given TypeInfo is a part of a particular\n# subtype relationship\nSubtypeCache: _TypeAlias = dict[TypeInfo, dict[SubtypeKind, set[SubtypeRelationship]]]\n\n\nclass TypeState:\n    \"\"\"This class provides subtype caching to improve performance of subtype checks.\n    It also holds protocol fine grained dependencies.\n\n    Note: to avoid leaking global state, 'reset_all_subtype_caches()' should be called\n    after a build has finished and after a daemon shutdown. This subtype cache only exists for\n    performance reasons, resetting subtype caches for a class has no semantic effect.\n    The protocol dependencies however are only stored here, and shouldn't be deleted unless\n    not needed any more (e.g. during daemon shutdown).\n    \"\"\"\n\n    # '_subtype_caches' keeps track of (subtype, supertype) pairs where supertypes are\n    # instances of the given TypeInfo. The cache also keeps track of whether the check\n    # was done in strict optional mode and of the specific *kind* of subtyping relationship,\n    # which we represent as an arbitrary hashable tuple.\n    # We need the caches, since subtype checks for structural types are very slow.\n    _subtype_caches: Final[SubtypeCache]\n\n    # Same as above but for negative subtyping results.\n    _negative_subtype_caches: Final[SubtypeCache]\n\n    # This contains protocol dependencies generated after running a full build,\n    # or after an update. These dependencies are special because:\n    #   * They are a global property of the program; i.e. some dependencies for imported\n    #     classes can be generated in the importing modules.\n    #   * Because of the above, they are serialized separately, after a full run,\n    #     or a full update.\n    # `proto_deps` can be None if after deserialization it turns out that they are\n    # inconsistent with the other cache files (or an error occurred during deserialization).\n    # A blocking error will be generated in this case, since we can't proceed safely.\n    # For the description of kinds of protocol dependencies and corresponding examples,\n    # see _snapshot_protocol_deps.\n    proto_deps: dict[str, set[str]] | None\n\n    # Protocols (full names) a given class attempted to implement.\n    # Used to calculate fine grained protocol dependencies and optimize protocol\n    # subtype cache invalidation in fine grained mode. For example, if we pass a value\n    # of type a.A to a function expecting something compatible with protocol p.P,\n    # we'd have 'a.A' -> {'p.P', ...} in the map. This map is flushed after every incremental\n    # update.\n    _attempted_protocols: Final[dict[str, set[str]]]\n    # We also snapshot protocol members of the above protocols. For example, if we pass\n    # a value of type a.A to a function expecting something compatible with Iterable, we'd have\n    # 'a.A' -> {'__iter__', ...} in the map. This map is also flushed after every incremental\n    # update. This map is needed to only generate dependencies like <a.A.__iter__> -> <a.A>\n    # instead of a wildcard to avoid unnecessarily invalidating classes.\n    _checked_against_members: Final[dict[str, set[str]]]\n    # TypeInfos that appeared as a left type (subtype) in a subtype check since latest\n    # dependency snapshot update. This is an optimisation for fine grained mode; during a full\n    # run we only take a dependency snapshot at the very end, so this set will contain all\n    # subtype-checked TypeInfos. After a fine grained update however, we can gather only new\n    # dependencies generated from (typically) few TypeInfos that were subtype-checked\n    # (i.e. appeared as r.h.s. in an assignment or an argument in a function call in\n    # a re-checked target) during the update.\n    _rechecked_types: Final[set[TypeInfo]]\n\n    # The two attributes below are assumption stacks for subtyping relationships between\n    # recursive type aliases. Normally, one would pass type assumptions as an additional\n    # arguments to is_subtype(), but this would mean updating dozens of related functions\n    # threading this through all callsites (see also comment for TypeInfo.assuming).\n    _assuming: Final[list[tuple[Type, Type]]]\n    _assuming_proper: Final[list[tuple[Type, Type]]]\n    # Ditto for inference of generic constraints against recursive type aliases.\n    inferring: Final[list[tuple[Type, Type]]]\n    # Whether to use joins or unions when solving constraints, see checkexpr.py for details.\n    infer_unions: bool\n    # Whether to use new type inference algorithm that can infer polymorphic types.\n    # This is temporary and will be removed soon when new algorithm is more polished.\n    infer_polymorphic: bool\n\n    # N.B: We do all of the accesses to these properties through\n    # TypeState, instead of making these classmethods and accessing\n    # via the cls parameter, since mypyc can optimize accesses to\n    # Final attributes of a directly referenced type.\n\n    def __init__(self) -> None:\n        self._subtype_caches = {}\n        self._negative_subtype_caches = {}\n        self.proto_deps = {}\n        self._attempted_protocols = {}\n        self._checked_against_members = {}\n        self._rechecked_types = set()\n        self._assuming = []\n        self._assuming_proper = []\n        self.inferring = []\n        self.infer_unions = False\n        self.infer_polymorphic = False\n\n    def is_assumed_subtype(self, left: Type, right: Type) -> bool:\n        for l, r in reversed(self._assuming):\n            if get_proper_type(l) == get_proper_type(left) and get_proper_type(\n                r\n            ) == get_proper_type(right):\n                return True\n        return False\n\n    def is_assumed_proper_subtype(self, left: Type, right: Type) -> bool:\n        for l, r in reversed(self._assuming_proper):\n            if get_proper_type(l) == get_proper_type(left) and get_proper_type(\n                r\n            ) == get_proper_type(right):\n                return True\n        return False\n\n    def get_assumptions(self, is_proper: bool) -> list[tuple[Type, Type]]:\n        if is_proper:\n            return self._assuming_proper\n        return self._assuming\n\n    def reset_all_subtype_caches(self) -> None:\n        \"\"\"Completely reset all known subtype caches.\"\"\"\n        self._subtype_caches.clear()\n        self._negative_subtype_caches.clear()\n\n    def reset_subtype_caches_for(self, info: TypeInfo) -> None:\n        \"\"\"Reset subtype caches (if any) for a given supertype TypeInfo.\"\"\"\n        if info in self._subtype_caches:\n            self._subtype_caches[info].clear()\n        if info in self._negative_subtype_caches:\n            self._negative_subtype_caches[info].clear()\n\n    def reset_all_subtype_caches_for(self, info: TypeInfo) -> None:\n        \"\"\"Reset subtype caches (if any) for a given supertype TypeInfo and its MRO.\"\"\"\n        for item in info.mro:\n            self.reset_subtype_caches_for(item)\n\n    def is_cached_subtype_check(self, kind: SubtypeKind, left: Instance, right: Instance) -> bool:\n        if left.last_known_value is not None or right.last_known_value is not None:\n            # If there is a literal last known value, give up. There\n            # will be an unbounded number of potential types to cache,\n            # making caching less effective.\n            return False\n        info = right.type\n        cache = self._subtype_caches.get(info)\n        if cache is None:\n            return False\n        subcache = cache.get(kind)\n        if subcache is None:\n            return False\n        return (left, right) in subcache\n\n    def is_cached_negative_subtype_check(\n        self, kind: SubtypeKind, left: Instance, right: Instance\n    ) -> bool:\n        if left.last_known_value is not None or right.last_known_value is not None:\n            # If there is a literal last known value, give up. There\n            # will be an unbounded number of potential types to cache,\n            # making caching less effective.\n            return False\n        info = right.type\n        cache = self._negative_subtype_caches.get(info)\n        if cache is None:\n            return False\n        subcache = cache.get(kind)\n        if subcache is None:\n            return False\n        return (left, right) in subcache\n\n    def record_subtype_cache_entry(\n        self, kind: SubtypeKind, left: Instance, right: Instance\n    ) -> None:\n        if left.last_known_value is not None or right.last_known_value is not None:\n            # These are unlikely to match, due to the large space of\n            # possible values.  Avoid uselessly increasing cache sizes.\n            return\n        if any(\n            (isinstance(tv, TypeVarType) and tv.variance == VARIANCE_NOT_READY)\n            for tv in right.type.defn.type_vars\n        ):\n            # Variance indeterminate -- don't know the result\n            return\n        cache = self._subtype_caches.setdefault(right.type, {})\n        cache.setdefault(kind, set()).add((left, right))\n\n    def record_negative_subtype_cache_entry(\n        self, kind: SubtypeKind, left: Instance, right: Instance\n    ) -> None:\n        if left.last_known_value is not None or right.last_known_value is not None:\n            # These are unlikely to match, due to the large space of\n            # possible values.  Avoid uselessly increasing cache sizes.\n            return\n        if len(self._negative_subtype_caches) > MAX_NEGATIVE_CACHE_TYPES:\n            self._negative_subtype_caches.clear()\n        cache = self._negative_subtype_caches.setdefault(right.type, {})\n        subcache = cache.setdefault(kind, set())\n        if len(subcache) > MAX_NEGATIVE_CACHE_ENTRIES:\n            subcache.clear()\n        cache.setdefault(kind, set()).add((left, right))\n\n    def reset_protocol_deps(self) -> None:\n        \"\"\"Reset dependencies after a full run or before a daemon shutdown.\"\"\"\n        self.proto_deps = {}\n        self._attempted_protocols.clear()\n        self._checked_against_members.clear()\n        self._rechecked_types.clear()\n\n    def record_protocol_subtype_check(self, left_type: TypeInfo, right_type: TypeInfo) -> None:\n        assert right_type.is_protocol\n        self._rechecked_types.add(left_type)\n        self._attempted_protocols.setdefault(left_type.fullname, set()).add(right_type.fullname)\n        self._checked_against_members.setdefault(left_type.fullname, set()).update(\n            right_type.protocol_members\n        )\n\n    def _snapshot_protocol_deps(self) -> dict[str, set[str]]:\n        \"\"\"Collect protocol attribute dependencies found so far from registered subtype checks.\n\n        There are three kinds of protocol dependencies. For example, after a subtype check:\n\n            x: Proto = C()\n\n        the following dependencies will be generated:\n            1. ..., <SuperProto[wildcard]>, <Proto[wildcard]> -> <Proto>\n            2. ..., <B.attr>, <C.attr> -> <C> [for every attr in Proto members]\n            3. <C> -> Proto  # this one to invalidate the subtype cache\n\n        The first kind is generated immediately per-module in deps.py (see also an example there\n        for motivation why it is needed). While two other kinds are generated here after all\n        modules are type checked and we have recorded all the subtype checks. To understand these\n        two kinds, consider a simple example:\n\n            class A:\n                def __iter__(self) -> Iterator[int]:\n                    ...\n\n            it: Iterable[int] = A()\n\n        We add <a.A.__iter__> -> <a.A> to invalidate the assignment (module target in this case),\n        whenever the signature of a.A.__iter__ changes. We also add <a.A> -> typing.Iterable,\n        to invalidate the subtype caches of the latter. (Note that the same logic applies to\n        proper subtype checks, and calculating meets and joins, if this involves calling\n        'subtypes.is_protocol_implementation').\n        \"\"\"\n        deps: dict[str, set[str]] = {}\n        for info in self._rechecked_types:\n            for attr in self._checked_against_members[info.fullname]:\n                # The need for full MRO here is subtle, during an update, base classes of\n                # a concrete class may not be reprocessed, so not all <B.x> -> <C.x> deps\n                # are added.\n                for base_info in info.mro[:-1]:\n                    trigger = make_trigger(f\"{base_info.fullname}.{attr}\")\n                    if \"typing\" in trigger or \"builtins\" in trigger:\n                        # TODO: avoid everything from typeshed\n                        continue\n                    deps.setdefault(trigger, set()).add(make_trigger(info.fullname))\n            for proto in self._attempted_protocols[info.fullname]:\n                trigger = make_trigger(info.fullname)\n                if \"typing\" in trigger or \"builtins\" in trigger:\n                    continue\n                # If any class that was checked against a protocol changes,\n                # we need to reset the subtype cache for the protocol.\n                #\n                # Note: strictly speaking, the protocol doesn't need to be\n                # re-checked, we only need to reset the cache, and its uses\n                # elsewhere are still valid (unless invalidated by other deps).\n                deps.setdefault(trigger, set()).add(proto)\n        return deps\n\n    def update_protocol_deps(self, second_map: dict[str, set[str]] | None = None) -> None:\n        \"\"\"Update global protocol dependency map.\n\n        We update the global map incrementally, using a snapshot only from recently\n        type checked types. If second_map is given, update it as well. This is currently used\n        by FineGrainedBuildManager that maintains normal (non-protocol) dependencies.\n        \"\"\"\n        assert self.proto_deps is not None, \"This should not be called after failed cache load\"\n        new_deps = self._snapshot_protocol_deps()\n        for trigger, targets in new_deps.items():\n            self.proto_deps.setdefault(trigger, set()).update(targets)\n        if second_map is not None:\n            for trigger, targets in new_deps.items():\n                second_map.setdefault(trigger, set()).update(targets)\n        self._rechecked_types.clear()\n        self._attempted_protocols.clear()\n        self._checked_against_members.clear()\n\n    def add_all_protocol_deps(self, deps: dict[str, set[str]]) -> None:\n        \"\"\"Add all known protocol dependencies to deps.\n\n        This is used by tests and debug output, and also when collecting\n        all collected or loaded dependencies as part of build.\n        \"\"\"\n        self.update_protocol_deps()  # just in case\n        if self.proto_deps is not None:\n            for trigger, targets in self.proto_deps.items():\n                deps.setdefault(trigger, set()).update(targets)\n\n\ntype_state: Final = TypeState()\n\n\ndef reset_global_state() -> None:\n    \"\"\"Reset most existing global state.\n\n    Currently most of it is in this module. Few exceptions are strict optional status\n    and functools.lru_cache.\n    \"\"\"\n    type_state.reset_all_subtype_caches()\n    type_state.reset_protocol_deps()\n    TypeVarId.next_raw_id = 1\n"
  },
  {
    "path": "mypy/typetraverser.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Iterable\n\nfrom mypy_extensions import trait\n\nfrom mypy.types import (\n    AnyType,\n    CallableArgument,\n    CallableType,\n    DeletedType,\n    EllipsisType,\n    ErasedType,\n    Instance,\n    LiteralType,\n    NoneType,\n    Overloaded,\n    Parameters,\n    ParamSpecType,\n    PartialType,\n    PlaceholderType,\n    RawExpressionType,\n    SyntheticTypeVisitor,\n    TupleType,\n    Type,\n    TypeAliasType,\n    TypedDictType,\n    TypeList,\n    TypeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    UnpackType,\n)\n\n\n@trait\nclass TypeTraverserVisitor(SyntheticTypeVisitor[None]):\n    \"\"\"Visitor that traverses all components of a type\"\"\"\n\n    # Atomic types\n\n    def visit_any(self, t: AnyType, /) -> None:\n        pass\n\n    def visit_uninhabited_type(self, t: UninhabitedType, /) -> None:\n        pass\n\n    def visit_none_type(self, t: NoneType, /) -> None:\n        pass\n\n    def visit_erased_type(self, t: ErasedType, /) -> None:\n        pass\n\n    def visit_deleted_type(self, t: DeletedType, /) -> None:\n        pass\n\n    def visit_type_var(self, t: TypeVarType, /) -> None:\n        # Note that type variable values and upper bound aren't treated as\n        # components, since they are components of the type variable\n        # definition. We want to traverse everything just once.\n        t.default.accept(self)\n\n    def visit_param_spec(self, t: ParamSpecType, /) -> None:\n        # TODO: do we need to traverse prefix here?\n        t.default.accept(self)\n\n    def visit_parameters(self, t: Parameters, /) -> None:\n        self.traverse_type_list(t.arg_types)\n\n    def visit_type_var_tuple(self, t: TypeVarTupleType, /) -> None:\n        t.default.accept(self)\n\n    def visit_literal_type(self, t: LiteralType, /) -> None:\n        t.fallback.accept(self)\n\n    # Composite types\n\n    def visit_instance(self, t: Instance, /) -> None:\n        self.traverse_type_tuple(t.args)\n\n    def visit_callable_type(self, t: CallableType, /) -> None:\n        # FIX generics\n        self.traverse_type_list(t.arg_types)\n        t.ret_type.accept(self)\n        t.fallback.accept(self)\n\n        if t.type_guard is not None:\n            t.type_guard.accept(self)\n\n        if t.type_is is not None:\n            t.type_is.accept(self)\n\n    def visit_tuple_type(self, t: TupleType, /) -> None:\n        self.traverse_type_list(t.items)\n        t.partial_fallback.accept(self)\n\n    def visit_typeddict_type(self, t: TypedDictType, /) -> None:\n        self.traverse_types(t.items.values())\n        t.fallback.accept(self)\n\n    def visit_union_type(self, t: UnionType, /) -> None:\n        self.traverse_type_list(t.items)\n\n    def visit_overloaded(self, t: Overloaded, /) -> None:\n        self.traverse_types(t.items)\n\n    def visit_type_type(self, t: TypeType, /) -> None:\n        t.item.accept(self)\n\n    # Special types (not real types)\n\n    def visit_callable_argument(self, t: CallableArgument, /) -> None:\n        t.typ.accept(self)\n\n    def visit_unbound_type(self, t: UnboundType, /) -> None:\n        self.traverse_type_tuple(t.args)\n\n    def visit_type_list(self, t: TypeList, /) -> None:\n        self.traverse_type_list(t.items)\n\n    def visit_ellipsis_type(self, t: EllipsisType, /) -> None:\n        pass\n\n    def visit_placeholder_type(self, t: PlaceholderType, /) -> None:\n        self.traverse_type_list(t.args)\n\n    def visit_partial_type(self, t: PartialType, /) -> None:\n        pass\n\n    def visit_raw_expression_type(self, t: RawExpressionType, /) -> None:\n        pass\n\n    def visit_type_alias_type(self, t: TypeAliasType, /) -> None:\n        # TODO: sometimes we want to traverse target as well\n        # We need to find a way to indicate explicitly the intent,\n        # maybe make this method abstract (like for TypeTranslator)?\n        self.traverse_type_list(t.args)\n\n    def visit_unpack_type(self, t: UnpackType, /) -> None:\n        t.type.accept(self)\n\n    # Helpers\n\n    def traverse_types(self, types: Iterable[Type], /) -> None:\n        for typ in types:\n            typ.accept(self)\n\n    def traverse_type_list(self, types: list[Type], /) -> None:\n        # Micro-optimization: Specialized for lists\n        for typ in types:\n            typ.accept(self)\n\n    def traverse_type_tuple(self, types: tuple[Type, ...], /) -> None:\n        # Micro-optimization: Specialized for tuples\n        for typ in types:\n            typ.accept(self)\n"
  },
  {
    "path": "mypy/typevars.py",
    "content": "from __future__ import annotations\n\nfrom mypy.erasetype import erase_typevars\nfrom mypy.nodes import TypeInfo\nfrom mypy.types import (\n    Instance,\n    ParamSpecType,\n    ProperType,\n    TupleType,\n    Type,\n    TypeOfAny,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    TypeVarType,\n    UnpackType,\n)\nfrom mypy.typevartuples import erased_vars\n\n\ndef fill_typevars(typ: TypeInfo) -> Instance | TupleType:\n    \"\"\"For a non-generic type, return instance type representing the type.\n\n    For a generic G type with parameters T1, .., Tn, return G[T1, ..., Tn].\n    \"\"\"\n    tvs: list[Type] = []\n    # TODO: why do we need to keep both typ.type_vars and typ.defn.type_vars?\n    for i in range(len(typ.defn.type_vars)):\n        tv: TypeVarLikeType | UnpackType = typ.defn.type_vars[i]\n        # Change the line number\n        if isinstance(tv, TypeVarType):\n            tv = tv.copy_modified(line=-1, column=-1)\n        elif isinstance(tv, TypeVarTupleType):\n            tv = UnpackType(\n                TypeVarTupleType(\n                    tv.name,\n                    tv.fullname,\n                    tv.id,\n                    tv.upper_bound,\n                    tv.tuple_fallback,\n                    tv.default,\n                    line=-1,\n                    column=-1,\n                )\n            )\n        else:\n            assert isinstance(tv, ParamSpecType)\n            tv = ParamSpecType(\n                tv.name,\n                tv.fullname,\n                tv.id,\n                tv.flavor,\n                tv.upper_bound,\n                tv.default,\n                line=-1,\n                column=-1,\n            )\n        tvs.append(tv)\n    inst = Instance(typ, tvs)\n    # TODO: do we need to also handle typeddict_type here and below?\n    if typ.tuple_type is None:\n        return inst\n    return typ.tuple_type.copy_modified(fallback=inst)\n\n\ndef fill_typevars_with_any(typ: TypeInfo) -> Instance | TupleType:\n    \"\"\"Apply a correct number of Any's as type arguments to a type.\"\"\"\n    inst = Instance(typ, erased_vars(typ.defn.type_vars, TypeOfAny.special_form))\n    if typ.tuple_type is None:\n        return inst\n    erased_tuple_type = erase_typevars(typ.tuple_type, {tv.id for tv in typ.defn.type_vars})\n    assert isinstance(erased_tuple_type, ProperType)\n    if isinstance(erased_tuple_type, TupleType):\n        return typ.tuple_type.copy_modified(fallback=inst)\n    return inst\n\n\ndef has_no_typevars(typ: Type) -> bool:\n    # We test if a type contains type variables by erasing all type variables\n    # and comparing the result to the original type. We use comparison by equality that\n    # in turn uses `__eq__` defined for types. Note: we can't use `is_same_type` because\n    # it is not safe with unresolved forward references, while this function may be called\n    # before forward references resolution patch pass. Note also that it is not safe to use\n    # `is` comparison because `erase_typevars` doesn't preserve type identity.\n    return typ == erase_typevars(typ)\n"
  },
  {
    "path": "mypy/typevartuples.py",
    "content": "\"\"\"Helpers for interacting with type var tuples.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\n\nfrom mypy.types import (\n    AnyType,\n    Instance,\n    Type,\n    TypeVarLikeType,\n    TypeVarTupleType,\n    UnpackType,\n    split_with_prefix_and_suffix,\n)\n\n\ndef split_with_instance(\n    typ: Instance,\n) -> tuple[tuple[Type, ...], tuple[Type, ...], tuple[Type, ...]]:\n    assert typ.type.type_var_tuple_prefix is not None\n    assert typ.type.type_var_tuple_suffix is not None\n    return split_with_prefix_and_suffix(\n        typ.args, typ.type.type_var_tuple_prefix, typ.type.type_var_tuple_suffix\n    )\n\n\ndef erased_vars(type_vars: Sequence[TypeVarLikeType], type_of_any: int) -> list[Type]:\n    args: list[Type] = []\n    for tv in type_vars:\n        # Valid erasure for *Ts is *tuple[Any, ...], not just Any.\n        if isinstance(tv, TypeVarTupleType):\n            args.append(UnpackType(tv.tuple_fallback.copy_modified(args=[AnyType(type_of_any)])))\n        else:\n            args.append(AnyType(type_of_any))\n    return args\n"
  },
  {
    "path": "mypy/util.py",
    "content": "\"\"\"Utility functions with no non-trivial dependencies.\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport io\nimport json\nimport os\nimport re\nimport shutil\nimport sys\nimport time\nfrom collections.abc import Callable, Container, Iterable, Sequence, Sized\nfrom importlib import resources as importlib_resources\nfrom typing import IO, Any, Final, Literal, TypeVar\n\norjson: Any\ntry:\n    import orjson  # type: ignore[import-not-found, no-redef, unused-ignore]\nexcept ImportError:\n    orjson = None\n\ntry:\n    import _curses  # noqa: F401\n    import curses\n\n    CURSES_ENABLED = True\nexcept ImportError:\n    CURSES_ENABLED = False\n\nT = TypeVar(\"T\")\n\nTYPESHED_DIR: Final = str(importlib_resources.files(\"mypy\") / \"typeshed\")\n\nENCODING_RE: Final = re.compile(rb\"([ \\t\\v]*#.*(\\r\\n?|\\n))??[ \\t\\v]*#.*coding[:=][ \\t]*([-\\w.]+)\")\n\nDEFAULT_SOURCE_OFFSET: Final = 4\nCODE_START: Final = \" \" * DEFAULT_SOURCE_OFFSET\nDEFAULT_COLUMNS: Final = 80\n\n# At least this number of columns will be shown on each side of\n# error location when printing source code snippet.\nMINIMUM_WIDTH: Final = 20\n\n# VT100 color code processing was added in Windows 10, but only the second major update,\n# Threshold 2. Fortunately, everyone (even on LTSB, Long Term Support Branch) should\n# have a version of Windows 10 newer than this. Note that Windows 8 and below are not\n# supported, but are either going out of support, or make up only a few % of the market.\nMINIMUM_WINDOWS_MAJOR_VT100: Final = 10\nMINIMUM_WINDOWS_BUILD_VT100: Final = 10586\n\nSPECIAL_DUNDERS: Final = frozenset(\n    (\"__init__\", \"__new__\", \"__call__\", \"__init_subclass__\", \"__class_getitem__\")\n)\n\n\ndef is_dunder(name: str, exclude_special: bool = False) -> bool:\n    \"\"\"Returns whether name is a dunder name.\n\n    Args:\n        exclude_special: Whether to return False for a couple special dunder methods.\n\n    \"\"\"\n    if exclude_special and name in SPECIAL_DUNDERS:\n        return False\n    return name.startswith(\"__\") and name.endswith(\"__\")\n\n\ndef is_sunder(name: str) -> bool:\n    return not is_dunder(name) and name.startswith(\"_\") and name.endswith(\"_\") and name != \"_\"\n\n\ndef split_module_names(mod_name: str) -> list[str]:\n    \"\"\"Return the module and all parent module names.\n\n    So, if `mod_name` is 'a.b.c', this function will return\n    ['a.b.c', 'a.b', and 'a'].\n    \"\"\"\n    out = [mod_name]\n    while \".\" in mod_name:\n        mod_name = mod_name.rsplit(\".\", 1)[0]\n        out.append(mod_name)\n    return out\n\n\ndef module_prefix(modules: Iterable[str], target: str) -> str | None:\n    result = split_target(modules, target)\n    if result is None:\n        return None\n    return result[0]\n\n\ndef split_target(modules: Iterable[str], target: str) -> tuple[str, str] | None:\n    remaining: list[str] = []\n    while True:\n        if target in modules:\n            return target, \".\".join(remaining)\n        components = target.rsplit(\".\", 1)\n        if len(components) == 1:\n            return None\n        target = components[0]\n        remaining.insert(0, components[1])\n\n\ndef short_type(obj: object) -> str:\n    \"\"\"Return the last component of the type name of an object.\n\n    If obj is None, return 'nil'. For example, if obj is 1, return 'int'.\n    \"\"\"\n    if obj is None:\n        return \"nil\"\n    t = str(type(obj))\n    return t.split(\".\")[-1].rstrip(\"'>\")\n\n\ndef find_python_encoding(text: bytes) -> tuple[str, int]:\n    \"\"\"PEP-263 for detecting Python file encoding\"\"\"\n    result = ENCODING_RE.match(text)\n    if result:\n        line = 2 if result.group(1) else 1\n        encoding = result.group(3).decode(\"ascii\")\n        # Handle some aliases that Python is happy to accept and that are used in the wild.\n        if encoding.startswith((\"iso-latin-1-\", \"latin-1-\")) or encoding == \"iso-latin-1\":\n            encoding = \"latin-1\"\n        return encoding, line\n    else:\n        default_encoding = \"utf8\"\n        return default_encoding, -1\n\n\ndef bytes_to_human_readable_repr(b: bytes) -> str:\n    \"\"\"Converts bytes into some human-readable representation. Unprintable\n    bytes such as the nul byte are escaped. For example:\n\n        >>> b = bytes([102, 111, 111, 10, 0])\n        >>> s = bytes_to_human_readable_repr(b)\n        >>> print(s)\n        foo\\n\\x00\n        >>> print(repr(s))\n        'foo\\\\n\\\\x00'\n    \"\"\"\n    return repr(b)[2:-1]\n\n\nclass DecodeError(Exception):\n    \"\"\"Exception raised when a file cannot be decoded due to an unknown encoding type.\n\n    Essentially a wrapper for the LookupError raised by `bytearray.decode`\n    \"\"\"\n\n\ndef decode_python_encoding(source: bytes) -> str:\n    \"\"\"Read the Python file with while obeying PEP-263 encoding detection.\n\n    Returns the source as a string.\n    \"\"\"\n    # check for BOM UTF-8 encoding and strip it out if present\n    if source.startswith(b\"\\xef\\xbb\\xbf\"):\n        encoding = \"utf8\"\n        source = source[3:]\n    else:\n        # look at first two lines and check if PEP-263 coding is present\n        encoding, _ = find_python_encoding(source)\n\n    try:\n        source_text = source.decode(encoding)\n    except LookupError as lookuperr:\n        raise DecodeError(str(lookuperr)) from lookuperr\n    return source_text\n\n\ndef read_py_file(path: str, read: Callable[[str], bytes]) -> list[str] | None:\n    \"\"\"Try reading a Python file as list of source lines.\n\n    Return None if something goes wrong.\n    \"\"\"\n    try:\n        source = read(path)\n    except OSError:\n        return None\n    else:\n        try:\n            source_lines = decode_python_encoding(source).splitlines()\n        except DecodeError:\n            return None\n        return source_lines\n\n\ndef trim_source_line(line: str, max_len: int, col: int, min_width: int) -> tuple[str, int]:\n    \"\"\"Trim a line of source code to fit into max_len.\n\n    Show 'min_width' characters on each side of 'col' (an error location). If either\n    start or end is trimmed, this is indicated by adding '...' there.\n    A typical result looks like this:\n        ...some_variable = function_to_call(one_arg, other_arg) or...\n\n    Return the trimmed string and the column offset to adjust error location.\n    \"\"\"\n    if max_len < 2 * min_width + 1:\n        # In case the window is too tiny it is better to still show something.\n        max_len = 2 * min_width + 1\n\n    # Trivial case: line already fits in.\n    if len(line) <= max_len:\n        return line, 0\n\n    # If column is not too large so that there is still min_width after it,\n    # the line doesn't need to be trimmed at the start.\n    if col + min_width < max_len:\n        return line[:max_len] + \"...\", 0\n\n    # Otherwise, if the column is not too close to the end, trim both sides.\n    if col < len(line) - min_width - 1:\n        offset = col - max_len + min_width + 1\n        return \"...\" + line[offset : col + min_width + 1] + \"...\", offset - 3\n\n    # Finally, if the column is near the end, just trim the start.\n    return \"...\" + line[-max_len:], len(line) - max_len - 3\n\n\ndef get_mypy_comments(source: str) -> list[tuple[int, str]]:\n    PREFIX = \"# mypy: \"\n    # Don't bother splitting up the lines unless we know it is useful\n    if PREFIX not in source:\n        return []\n    lines = source.split(\"\\n\")\n    results = []\n    for i, line in enumerate(lines):\n        if line.startswith(PREFIX):\n            results.append((i + 1, line[len(PREFIX) :]))\n\n    return results\n\n\nJUNIT_HEADER_TEMPLATE: Final = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<testsuite errors=\"{errors}\" failures=\"{failures}\" name=\"mypy\" skips=\"0\" tests=\"{tests}\" time=\"{time:.3f}\">\n\"\"\"\n\nJUNIT_TESTCASE_FAIL_TEMPLATE: Final = \"\"\"  <testcase classname=\"mypy\" file=\"{filename}\" line=\"1\" name=\"{name}\" time=\"{time:.3f}\">\n    <failure message=\"mypy produced messages\">{text}</failure>\n  </testcase>\n\"\"\"\n\nJUNIT_ERROR_TEMPLATE: Final = \"\"\"  <testcase classname=\"mypy\" file=\"mypy\" line=\"1\" name=\"mypy-py{ver}-{platform}\" time=\"{time:.3f}\">\n    <error message=\"mypy produced errors\">{text}</error>\n  </testcase>\n\"\"\"\n\nJUNIT_TESTCASE_PASS_TEMPLATE: Final = \"\"\"  <testcase classname=\"mypy\" file=\"mypy\" line=\"1\" name=\"mypy-py{ver}-{platform}\" time=\"{time:.3f}\">\n  </testcase>\n\"\"\"\n\nJUNIT_FOOTER: Final = \"\"\"</testsuite>\n\"\"\"\n\n\ndef _generate_junit_contents(\n    dt: float,\n    serious: bool,\n    messages_by_file: dict[str | None, list[str]],\n    version: str,\n    platform: str,\n) -> str:\n    from xml.sax.saxutils import escape\n\n    if serious:\n        failures = 0\n        errors = len(messages_by_file)\n    else:\n        failures = len(messages_by_file)\n        errors = 0\n\n    xml = JUNIT_HEADER_TEMPLATE.format(\n        errors=errors,\n        failures=failures,\n        time=dt,\n        # If there are no messages, we still write one \"test\" indicating success.\n        tests=len(messages_by_file) or 1,\n    )\n\n    if not messages_by_file:\n        xml += JUNIT_TESTCASE_PASS_TEMPLATE.format(time=dt, ver=version, platform=platform)\n    else:\n        for filename, messages in messages_by_file.items():\n            if filename is not None:\n                xml += JUNIT_TESTCASE_FAIL_TEMPLATE.format(\n                    text=escape(\"\\n\".join(messages)),\n                    filename=filename,\n                    time=dt,\n                    name=\"mypy-py{ver}-{platform} {filename}\".format(\n                        ver=version, platform=platform, filename=filename\n                    ),\n                )\n            else:\n                xml += JUNIT_TESTCASE_FAIL_TEMPLATE.format(\n                    text=escape(\"\\n\".join(messages)),\n                    filename=\"mypy\",\n                    time=dt,\n                    name=f\"mypy-py{version}-{platform}\",\n                )\n\n    xml += JUNIT_FOOTER\n\n    return xml\n\n\ndef write_junit_xml(\n    dt: float,\n    serious: bool,\n    messages_by_file: dict[str | None, list[str]],\n    path: str,\n    version: str,\n    platform: str,\n) -> None:\n    xml = _generate_junit_contents(dt, serious, messages_by_file, version, platform)\n\n    # creates folders if needed\n    xml_dirs = os.path.dirname(os.path.abspath(path))\n    os.makedirs(xml_dirs, exist_ok=True)\n\n    with open(path, \"wb\") as f:\n        f.write(xml.encode(\"utf-8\"))\n\n\nclass IdMapper:\n    \"\"\"Generate integer ids for objects.\n\n    Unlike id(), these start from 0 and increment by 1, and ids won't\n    get reused across the life-time of IdMapper.\n\n    Assume objects don't redefine __eq__ or __hash__.\n    \"\"\"\n\n    def __init__(self) -> None:\n        self.id_map: dict[object, int] = {}\n        self.next_id = 0\n\n    def id(self, o: object) -> int:\n        if o not in self.id_map:\n            self.id_map[o] = self.next_id\n            self.next_id += 1\n        return self.id_map[o]\n\n\ndef get_prefix(fullname: str) -> str:\n    \"\"\"Drop the final component of a qualified name (e.g. ('x.y' -> 'x').\"\"\"\n    return fullname.rsplit(\".\", 1)[0]\n\n\ndef correct_relative_import(\n    cur_mod_id: str, relative: int, target: str, is_cur_package_init_file: bool\n) -> tuple[str, bool]:\n    if relative == 0:\n        return target, True\n    parts = cur_mod_id.split(\".\")\n    rel = relative\n    if is_cur_package_init_file:\n        rel -= 1\n    ok = len(parts) >= rel\n    if rel != 0:\n        cur_mod_id = \".\".join(parts[:-rel])\n    return cur_mod_id + ((\".\" + target) if target else \"\"), ok\n\n\nfields_cache: Final[dict[type[object], list[str]]] = {}\n\n\ndef get_class_descriptors(cls: type[object]) -> Sequence[str]:\n    import inspect  # Lazy import for minor startup speed win\n\n    # Maintain a cache of type -> attributes defined by descriptors in the class\n    # (that is, attributes from __slots__ and C extension classes)\n    if cls not in fields_cache:\n        members = inspect.getmembers(\n            cls, lambda o: inspect.isgetsetdescriptor(o) or inspect.ismemberdescriptor(o)\n        )\n        fields_cache[cls] = [x for x, y in members if x != \"__weakref__\" and x != \"__dict__\"]\n    return fields_cache[cls]\n\n\ndef replace_object_state(\n    new: object, old: object, copy_dict: bool = False, skip_slots: tuple[str, ...] = ()\n) -> None:\n    \"\"\"Copy state of old node to the new node.\n\n    This handles cases where there is __dict__ and/or attribute descriptors\n    (either from slots or because the type is defined in a C extension module).\n\n    Assume that both objects have the same __class__.\n    \"\"\"\n    if hasattr(old, \"__dict__\"):\n        if copy_dict:\n            new.__dict__ = dict(old.__dict__)\n        else:\n            new.__dict__ = old.__dict__\n\n    for attr in get_class_descriptors(old.__class__):\n        if attr in skip_slots:\n            continue\n        try:\n            if hasattr(old, attr):\n                setattr(new, attr, getattr(old, attr))\n            elif hasattr(new, attr):\n                delattr(new, attr)\n        # There is no way to distinguish getsetdescriptors that allow\n        # writes from ones that don't (I think?), so we just ignore\n        # AttributeErrors if we need to.\n        # TODO: What about getsetdescriptors that act like properties???\n        except AttributeError:\n            pass\n\n\ndef is_sub_path_normabs(path: str, dir: str) -> bool:\n    \"\"\"Given two paths, return if path is a sub-path of dir.\n\n    Moral equivalent of: Path(dir) in Path(path).parents\n\n    Similar to the pathlib version:\n    - Treats paths case-sensitively\n    - Does not fully handle unnormalised paths (e.g. paths with \"..\")\n    - Does not handle a mix of absolute and relative paths\n    Unlike the pathlib version:\n    - Fast\n    - On Windows, assumes input has been slash normalised\n    - Handles even fewer unnormalised paths (e.g. paths with \".\" and \"//\")\n\n    As a result, callers should ensure that inputs have had os.path.abspath called on them\n    (note that os.path.abspath will normalise)\n    \"\"\"\n    if not dir.endswith(os.sep):\n        dir += os.sep\n    return path.startswith(dir)\n\n\nif sys.platform == \"linux\" or sys.platform == \"darwin\":\n\n    def os_path_join(path: str, b: str) -> str:\n        # Based off of os.path.join, but simplified to str-only, 2 args and mypyc can compile it.\n        if b.startswith(\"/\") or not path:\n            return b\n        elif path.endswith(\"/\"):\n            return path + b\n        else:\n            return path + \"/\" + b\n\nelse:\n\n    def os_path_join(a: str, p: str) -> str:\n        return os.path.join(a, p)\n\n\ndef hard_exit(status: int = 0) -> None:\n    \"\"\"Kill the current process without fully cleaning up.\n\n    This can be quite a bit faster than a normal exit() since objects are not freed.\n    \"\"\"\n    sys.stdout.flush()\n    sys.stderr.flush()\n    os._exit(status)\n\n\ndef unmangle(name: str) -> str:\n    \"\"\"Remove internal suffixes from a short name.\"\"\"\n    return name.rstrip(\"'\")\n\n\ndef get_unique_redefinition_name(name: str, existing: Container[str]) -> str:\n    \"\"\"Get a simple redefinition name not present among existing.\n\n    For example, for name 'foo' we try 'foo-redefinition', 'foo-redefinition2',\n    'foo-redefinition3', etc. until we find one that is not in existing.\n    \"\"\"\n    r_name = name + \"-redefinition\"\n    if r_name not in existing:\n        return r_name\n\n    i = 2\n    while r_name + str(i) in existing:\n        i += 1\n    return r_name + str(i)\n\n\ndef check_python_version(program: str) -> None:\n    \"\"\"Report issues with the Python used to run mypy, dmypy, or stubgen\"\"\"\n    # Check for known bad Python versions.\n    if sys.version_info[:2] < (3, 10):  # noqa: UP036, RUF100\n        sys.exit(\n            \"Running {name} with Python 3.9 or lower is not supported; \"\n            \"please upgrade to 3.10 or newer\".format(name=program)\n        )\n\n\ndef count_stats(messages: list[str]) -> tuple[int, int, int]:\n    \"\"\"Count total number of errors, notes and error_files in message list.\"\"\"\n    errors = [e for e in messages if \": error:\" in e]\n    error_files = {e.split(\":\")[0] for e in errors}\n    notes = [e for e in messages if \": note:\" in e]\n    return len(errors), len(notes), len(error_files)\n\n\ndef split_words(msg: str) -> list[str]:\n    \"\"\"Split line of text into words (but not within quoted groups).\"\"\"\n    next_word = \"\"\n    res: list[str] = []\n    allow_break = True\n    for c in msg:\n        if c == \" \" and allow_break:\n            res.append(next_word)\n            next_word = \"\"\n            continue\n        if c == '\"':\n            allow_break = not allow_break\n        next_word += c\n    res.append(next_word)\n    return res\n\n\ndef get_terminal_width() -> int:\n    \"\"\"Get current terminal width if possible, otherwise return the default one.\"\"\"\n    return (\n        int(os.getenv(\"MYPY_FORCE_TERMINAL_WIDTH\", \"0\"))\n        or shutil.get_terminal_size().columns\n        or DEFAULT_COLUMNS\n    )\n\n\ndef soft_wrap(msg: str, max_len: int, first_offset: int, num_indent: int = 0) -> str:\n    \"\"\"Wrap a long error message into few lines.\n\n    Breaks will only happen between words, and never inside a quoted group\n    (to avoid breaking types such as \"Union[int, str]\"). The 'first_offset' is\n    the width before the start of first line.\n\n    Pad every next line with 'num_indent' spaces. Every line will be at most 'max_len'\n    characters, except if it is a single word or quoted group.\n\n    For example:\n               first_offset\n        ------------------------\n        path/to/file: error: 58: Some very long error message\n            that needs to be split in separate lines.\n            \"Long[Type, Names]\" are never split.\n        ^^^^--------------------------------------------------\n        num_indent           max_len\n    \"\"\"\n    words = split_words(msg)\n    next_line = words.pop(0)\n    lines: list[str] = []\n    while words:\n        next_word = words.pop(0)\n        max_line_len = max_len - num_indent if lines else max_len - first_offset\n        # Add 1 to account for space between words.\n        if len(next_line) + len(next_word) + 1 <= max_line_len:\n            next_line += \" \" + next_word\n        else:\n            lines.append(next_line)\n            next_line = next_word\n    lines.append(next_line)\n    padding = \"\\n\" + \" \" * num_indent\n    return padding.join(lines)\n\n\ndef hash_digest(data: bytes) -> str:\n    \"\"\"Compute a hash digest of some data.\n\n    We use a cryptographic hash because we want a low probability of\n    accidental collision, but we don't really care about any of the\n    cryptographic properties.\n    \"\"\"\n    return hashlib.sha1(data).hexdigest()\n\n\ndef hash_digest_bytes(data: bytes) -> bytes:\n    \"\"\"Compute a hash digest of some data.\n\n    Similar to above but returns a bytes object.\n    \"\"\"\n    return hashlib.sha1(data).digest()\n\n\ndef parse_gray_color(cup: bytes) -> str:\n    \"\"\"Reproduce a gray color in ANSI escape sequence\"\"\"\n    assert sys.platform != \"win32\", \"curses is not available on Windows\"\n    set_color = \"\".join([cup[:-1].decode(), \"m\"])\n    gray = curses.tparm(set_color.encode(\"utf-8\"), 1, 9).decode()\n    return gray\n\n\ndef should_force_color() -> bool:\n    env_var = os.getenv(\"MYPY_FORCE_COLOR\", os.getenv(\"FORCE_COLOR\", \"0\"))\n    try:\n        return bool(int(env_var))\n    except ValueError:\n        return bool(env_var)\n\n\nclass FancyFormatter:\n    \"\"\"Apply color and bold font to terminal output.\n\n    This currently only works on Linux and Mac.\n    \"\"\"\n\n    def __init__(\n        self, f_out: IO[str], f_err: IO[str], hide_error_codes: bool, hide_success: bool = False\n    ) -> None:\n        self.hide_error_codes = hide_error_codes\n        self.hide_success = hide_success\n\n        # Check if we are in a human-facing terminal on a supported platform.\n        if sys.platform not in (\"linux\", \"darwin\", \"win32\", \"emscripten\"):\n            self.dummy_term = True\n            return\n        if not should_force_color() and (not f_out.isatty() or not f_err.isatty()):\n            self.dummy_term = True\n            return\n        if sys.platform == \"win32\":\n            self.dummy_term = not self.initialize_win_colors()\n        elif sys.platform == \"emscripten\":\n            self.dummy_term = not self.initialize_vt100_colors()\n        else:\n            self.dummy_term = not self.initialize_unix_colors()\n        if not self.dummy_term:\n            self.colors = {\n                \"red\": self.RED,\n                \"green\": self.GREEN,\n                \"blue\": self.BLUE,\n                \"yellow\": self.YELLOW,\n                \"none\": \"\",\n            }\n\n    def initialize_vt100_colors(self) -> bool:\n        \"\"\"Return True if initialization was successful and we can use colors, False otherwise\"\"\"\n        # Windows and Emscripten can both use ANSI/VT100 escape sequences for color\n        assert sys.platform in (\"win32\", \"emscripten\")\n        self.BOLD = \"\\033[1m\"\n        self.UNDER = \"\\033[4m\"\n        self.BLUE = \"\\033[94m\"\n        self.GREEN = \"\\033[92m\"\n        self.RED = \"\\033[91m\"\n        self.YELLOW = \"\\033[93m\"\n        self.NORMAL = \"\\033[0m\"\n        self.DIM = \"\\033[2m\"\n        return True\n\n    def initialize_win_colors(self) -> bool:\n        \"\"\"Return True if initialization was successful and we can use colors, False otherwise\"\"\"\n        # Windows ANSI escape sequences are only supported on Threshold 2 and above.\n        # we check with an assert at runtime and an if check for mypy, as asserts do not\n        # yet narrow platform\n        if sys.platform == \"win32\":  # needed to find win specific sys apis\n            winver = sys.getwindowsversion()\n            if (\n                winver.major < MINIMUM_WINDOWS_MAJOR_VT100\n                or winver.build < MINIMUM_WINDOWS_BUILD_VT100\n            ):\n                return False\n            import ctypes\n\n            kernel32 = ctypes.windll.kernel32\n            ENABLE_PROCESSED_OUTPUT = 0x1\n            ENABLE_WRAP_AT_EOL_OUTPUT = 0x2\n            ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x4\n            STD_OUTPUT_HANDLE = -11\n            kernel32.SetConsoleMode(\n                kernel32.GetStdHandle(STD_OUTPUT_HANDLE),\n                ENABLE_PROCESSED_OUTPUT\n                | ENABLE_WRAP_AT_EOL_OUTPUT\n                | ENABLE_VIRTUAL_TERMINAL_PROCESSING,\n            )\n            self.initialize_vt100_colors()\n            return True\n        assert False, \"Running not on Windows\"\n\n    def initialize_unix_colors(self) -> bool:\n        \"\"\"Return True if initialization was successful and we can use colors, False otherwise\"\"\"\n        is_win = sys.platform == \"win32\"\n        if is_win or not CURSES_ENABLED:\n            return False\n        try:\n            # setupterm wants a fd to potentially write an \"initialization sequence\".\n            # We override sys.stdout for the daemon API so if stdout doesn't have an fd,\n            # just give it /dev/null.\n            try:\n                fd = sys.stdout.fileno()\n            except io.UnsupportedOperation:\n                with open(\"/dev/null\", \"rb\") as f:\n                    curses.setupterm(fd=f.fileno())\n            else:\n                curses.setupterm(fd=fd)\n        except curses.error:\n            # Most likely terminfo not found.\n            return False\n        bold = curses.tigetstr(\"bold\")\n        under = curses.tigetstr(\"smul\")\n        set_color = curses.tigetstr(\"setaf\")\n        set_eseq = curses.tigetstr(\"cup\")\n        normal = curses.tigetstr(\"sgr0\")\n\n        if not (bold and under and set_color and set_eseq and normal):\n            return False\n\n        self.NORMAL = normal.decode()\n        self.BOLD = bold.decode()\n        self.UNDER = under.decode()\n        self.DIM = parse_gray_color(set_eseq)\n        self.BLUE = curses.tparm(set_color, curses.COLOR_BLUE).decode()\n        self.GREEN = curses.tparm(set_color, curses.COLOR_GREEN).decode()\n        self.RED = curses.tparm(set_color, curses.COLOR_RED).decode()\n        self.YELLOW = curses.tparm(set_color, curses.COLOR_YELLOW).decode()\n        return True\n\n    def style(\n        self,\n        text: str,\n        color: Literal[\"red\", \"green\", \"blue\", \"yellow\", \"none\"],\n        bold: bool = False,\n        underline: bool = False,\n        dim: bool = False,\n    ) -> str:\n        \"\"\"Apply simple color and style (underlined or bold).\"\"\"\n        if self.dummy_term:\n            return text\n        if bold:\n            start = self.BOLD\n        else:\n            start = \"\"\n        if underline:\n            start += self.UNDER\n        if dim:\n            start += self.DIM\n        return start + self.colors[color] + text + self.NORMAL\n\n    def is_marker_line(self, line: str) -> bool:\n        s_line = line.lstrip()\n        return (\n            line.startswith(CODE_START)\n            and s_line.startswith(\"^\")\n            and set(s_line).issubset({\"^\", \"~\"})\n        )\n\n    def fit_in_terminal(\n        self, messages: list[str], fixed_terminal_width: int | None = None\n    ) -> list[str]:\n        \"\"\"Improve readability by wrapping error messages and trimming source code.\"\"\"\n        width = fixed_terminal_width or get_terminal_width()\n        new_messages = messages.copy()\n        for i, error in enumerate(messages):\n            # TODO: detecting source code highlights through an indent can be surprising.\n            if not error.startswith(CODE_START) and \": error:\" in error:\n                loc, msg = error.split(\"error:\", maxsplit=1)\n                msg = soft_wrap(msg, width, first_offset=len(loc) + len(\"error: \"))\n                new_messages[i] = loc + \"error:\" + msg\n            elif error.startswith(CODE_START) and not self.is_marker_line(error):\n                # Restore original error message and error location.\n                error = error[DEFAULT_SOURCE_OFFSET:]\n                marker_line = messages[i + 1]\n                marker_column = marker_line.index(\"^\")\n                column = marker_column - DEFAULT_SOURCE_OFFSET\n                if \"~\" not in marker_line:\n                    marker = \"^\"\n                else:\n                    # +1 because both ends are included\n                    marker = marker_line[marker_column : marker_line.rindex(\"~\") + 1]\n\n                # Let source have some space also on the right side, plus 6\n                # to accommodate ... on each side.\n                max_len = width - DEFAULT_SOURCE_OFFSET - 6\n                source_line, offset = trim_source_line(error, max_len, column, MINIMUM_WIDTH)\n\n                new_messages[i] = \" \" * DEFAULT_SOURCE_OFFSET + source_line\n                # Also adjust the error marker position and trim error marker is needed.\n                new_marker_line = \" \" * (DEFAULT_SOURCE_OFFSET + column - offset) + marker\n                if len(new_marker_line) > len(new_messages[i]) and len(marker) > 3:\n                    new_marker_line = new_marker_line[: len(new_messages[i]) - 3] + \"...\"\n                new_messages[i + 1] = new_marker_line\n        return new_messages\n\n    def colorize(self, error: str) -> str:\n        \"\"\"Colorize an output line by highlighting the status and error code.\"\"\"\n        # TODO: detecting source code highlights through an indent can be surprising.\n        if error.startswith(CODE_START):\n            if not self.is_marker_line(error):\n                return self.style(error, \"none\", dim=True)\n            return self.style(error, \"red\")\n        elif \": error:\" in error:\n            loc, msg = error.split(\"error:\", maxsplit=1)\n            if self.hide_error_codes:\n                return (\n                    loc + self.style(\"error:\", \"red\", bold=True) + self.highlight_quote_groups(msg)\n                )\n            codepos = msg.rfind(\"[\")\n            if codepos != -1:\n                code = msg[codepos:]\n                msg = msg[:codepos]\n            else:\n                code = \"\"  # no error code specified\n            return (\n                loc\n                + self.style(\"error:\", \"red\", bold=True)\n                + self.highlight_quote_groups(msg)\n                + self.style(code, \"yellow\")\n            )\n        elif \": note:\" in error:\n            loc, msg = error.split(\"note:\", maxsplit=1)\n            formatted = self.highlight_quote_groups(self.underline_link(msg))\n            return loc + self.style(\"note:\", \"blue\") + formatted\n        else:\n            return error\n\n    def highlight_quote_groups(self, msg: str) -> str:\n        \"\"\"Make groups quoted with double quotes bold (including quotes).\n\n        This is used to highlight types, attribute names etc.\n        \"\"\"\n        if msg.count('\"') % 2:\n            # Broken error message, don't do any formatting.\n            return msg\n        parts = msg.split('\"')\n        out = \"\"\n        for i, part in enumerate(parts):\n            if i % 2 == 0:\n                out += self.style(part, \"none\")\n            else:\n                out += self.style('\"' + part + '\"', \"none\", bold=True)\n        return out\n\n    def underline_link(self, note: str) -> str:\n        \"\"\"Underline a link in a note message (if any).\n\n        This assumes there is at most one link in the message.\n        \"\"\"\n        match = re.search(r\"https?://\\S*\", note)\n        if not match:\n            return note\n        start = match.start()\n        end = match.end()\n        return note[:start] + self.style(note[start:end], \"none\", underline=True) + note[end:]\n\n    def format_success(self, n_sources: int, use_color: bool = True) -> str:\n        \"\"\"Format short summary in case of success.\n\n        n_sources is total number of files passed directly on command line,\n        i.e. excluding stubs and followed imports.\n        \"\"\"\n        if self.hide_success:\n            return \"\"\n\n        msg = f\"Success: no issues found in {n_sources} source file{plural_s(n_sources)}\"\n        if not use_color:\n            return msg\n        return self.style(msg, \"green\", bold=True)\n\n    def format_error(\n        self,\n        n_errors: int,\n        n_files: int,\n        n_sources: int,\n        *,\n        blockers: bool = False,\n        use_color: bool = True,\n    ) -> str:\n        \"\"\"Format a short summary in case of errors.\"\"\"\n        msg = f\"Found {n_errors} error{plural_s(n_errors)} in {n_files} file{plural_s(n_files)}\"\n        if blockers:\n            msg += \" (errors prevented further checking)\"\n        else:\n            msg += f\" (checked {n_sources} source file{plural_s(n_sources)})\"\n        if not use_color:\n            return msg\n        return self.style(msg, \"red\", bold=True)\n\n\ndef is_typeshed_file(typeshed_dir: str | None, file: str) -> bool:\n    typeshed_dir = typeshed_dir if typeshed_dir is not None else TYPESHED_DIR\n    try:\n        return os.path.commonpath((typeshed_dir, os.path.abspath(file))) == typeshed_dir\n    except ValueError:  # Different drives on Windows\n        return False\n\n\ndef is_stdlib_file(typeshed_dir: str | None, file: str) -> bool:\n    if \"stdlib\" not in file:\n        # Fast path\n        return False\n    typeshed_dir = typeshed_dir if typeshed_dir is not None else TYPESHED_DIR\n    stdlib_dir = os.path.join(typeshed_dir, \"stdlib\")\n    try:\n        return os.path.commonpath((stdlib_dir, os.path.abspath(file))) == stdlib_dir\n    except ValueError:  # Different drives on Windows\n        return False\n\n\ndef is_stub_package_file(file: str) -> bool:\n    # Use hacky heuristics to check whether file is part of a PEP 561 stub package.\n    if not file.endswith(\".pyi\"):\n        return False\n    return any(component.endswith(\"-stubs\") for component in os.path.split(os.path.abspath(file)))\n\n\ndef unnamed_function(name: str | None) -> bool:\n    return name is not None and name == \"_\"\n\n\ntime_ref = time.perf_counter_ns\n\n\ndef time_spent_us(t0: int) -> int:\n    return int((time.perf_counter_ns() - t0) / 1000)\n\n\ndef plural_s(s: int | Sized) -> str:\n    count = s if isinstance(s, int) else len(s)\n    if count != 1:\n        return \"s\"\n    else:\n        return \"\"\n\n\ndef quote_docstring(docstr: str) -> str:\n    \"\"\"Returns docstring correctly encapsulated in a single or double quoted form.\"\"\"\n    # Uses repr to get hint on the correct quotes and escape everything properly.\n    # Creating multiline string for prettier output.\n    docstr_repr = \"\\n\".join(re.split(r\"(?<=[^\\\\])\\\\n\", repr(docstr)))\n\n    if docstr_repr.startswith(\"'\"):\n        # Enforce double quotes when it's safe to do so.\n        # That is when double quotes are not in the string\n        # or when it doesn't end with a single quote.\n        if '\"' not in docstr_repr[1:-1] and docstr_repr[-2] != \"'\":\n            return f'\"\"\"{docstr_repr[1:-1]}\"\"\"'\n        return f\"''{docstr_repr}''\"\n    else:\n        return f'\"\"{docstr_repr}\"\"'\n\n\ndef json_dumps(obj: object, debug: bool = False) -> bytes:\n    if orjson is not None:\n        if debug:\n            dumps_option = orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS\n        else:\n            # TODO: If we don't sort keys here, testIncrementalInternalScramble fails\n            # We should document exactly what is going on there\n            dumps_option = orjson.OPT_SORT_KEYS\n\n        try:\n            return orjson.dumps(obj, option=dumps_option)  # type: ignore[no-any-return]\n        except TypeError as e:\n            if str(e) != \"Integer exceeds 64-bit range\":\n                raise\n\n    if debug:\n        return json.dumps(obj, indent=2, sort_keys=True).encode(\"utf-8\")\n    else:\n        # See above for sort_keys comment\n        return json.dumps(obj, sort_keys=True, separators=(\",\", \":\")).encode(\"utf-8\")\n\n\ndef json_loads(data: bytes) -> Any:\n    if orjson is not None:\n        return orjson.loads(data)\n    return json.loads(data)\n"
  },
  {
    "path": "mypy/version.py",
    "content": "from __future__ import annotations\n\nimport os\n\nfrom mypy import git\n\n# Base version.\n# - Release versions have the form \"1.2.3\".\n# - Dev versions have the form \"1.2.3+dev\" (PLUS sign to conform to PEP 440).\n# - Before 1.0 we had the form \"0.NNN\".\n__version__ = \"1.20.0+dev\"\nbase_version = __version__\n\nmypy_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))\nif __version__.endswith(\"+dev\") and git.is_git_repo(mypy_dir) and git.have_git():\n    __version__ += \".\" + git.git_revision(mypy_dir).decode(\"utf-8\")\n    if git.is_dirty(mypy_dir):\n        __version__ += \".dirty\"\ndel mypy_dir\n"
  },
  {
    "path": "mypy/visitor.py",
    "content": "\"\"\"Generic abstract syntax tree node visitor\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom typing import TYPE_CHECKING, Generic, TypeVar\n\nfrom mypy_extensions import mypyc_attr, trait\n\nif TYPE_CHECKING:\n    # break import cycle only needed for mypy\n    import mypy.nodes\n    import mypy.patterns\n\n\nT = TypeVar(\"T\")\n\n\n@trait\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass ExpressionVisitor(Generic[T]):\n    @abstractmethod\n    def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_float_expr(self, o: mypy.nodes.FloatExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_complex_expr(self, o: mypy.nodes.ComplexExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_star_expr(self, o: mypy.nodes.StarExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_name_expr(self, o: mypy.nodes.NameExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_member_expr(self, o: mypy.nodes.MemberExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_yield_expr(self, o: mypy.nodes.YieldExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_call_expr(self, o: mypy.nodes.CallExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_op_expr(self, o: mypy.nodes.OpExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_cast_expr(self, o: mypy.nodes.CastExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_reveal_expr(self, o: mypy.nodes.RevealExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_super_expr(self, o: mypy.nodes.SuperExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_unary_expr(self, o: mypy.nodes.UnaryExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_list_expr(self, o: mypy.nodes.ListExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_dict_expr(self, o: mypy.nodes.DictExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_tuple_expr(self, o: mypy.nodes.TupleExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_set_expr(self, o: mypy.nodes.SetExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_index_expr(self, o: mypy.nodes.IndexExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_type_application(self, o: mypy.nodes.TypeApplication, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_list_comprehension(self, o: mypy.nodes.ListComprehension, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_set_comprehension(self, o: mypy.nodes.SetComprehension, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_slice_expr(self, o: mypy.nodes.SliceExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit__promote_expr(self, o: mypy.nodes.PromoteExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_await_expr(self, o: mypy.nodes.AwaitExpr, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_temp_node(self, o: mypy.nodes.TempNode, /) -> T:\n        pass\n\n\n@trait\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass StatementVisitor(Generic[T]):\n    # Definitions\n\n    @abstractmethod\n    def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_for_stmt(self, o: mypy.nodes.ForStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_with_stmt(self, o: mypy.nodes.WithStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_del_stmt(self, o: mypy.nodes.DelStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_func_def(self, o: mypy.nodes.FuncDef, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_class_def(self, o: mypy.nodes.ClassDef, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_global_decl(self, o: mypy.nodes.GlobalDecl, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_decorator(self, o: mypy.nodes.Decorator, /) -> T:\n        pass\n\n    # Module structure\n\n    @abstractmethod\n    def visit_import(self, o: mypy.nodes.Import, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_import_from(self, o: mypy.nodes.ImportFrom, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_import_all(self, o: mypy.nodes.ImportAll, /) -> T:\n        pass\n\n    # Statements\n\n    @abstractmethod\n    def visit_block(self, o: mypy.nodes.Block, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_while_stmt(self, o: mypy.nodes.WhileStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_return_stmt(self, o: mypy.nodes.ReturnStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_assert_stmt(self, o: mypy.nodes.AssertStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_if_stmt(self, o: mypy.nodes.IfStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_break_stmt(self, o: mypy.nodes.BreakStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_pass_stmt(self, o: mypy.nodes.PassStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_try_stmt(self, o: mypy.nodes.TryStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_match_stmt(self, o: mypy.nodes.MatchStmt, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt, /) -> T:\n        pass\n\n\n@trait\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass PatternVisitor(Generic[T]):\n    @abstractmethod\n    def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_starred_pattern(self, o: mypy.patterns.StarredPattern, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern, /) -> T:\n        pass\n\n    @abstractmethod\n    def visit_class_pattern(self, o: mypy.patterns.ClassPattern, /) -> T:\n        pass\n\n\n@trait\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass NodeVisitor(Generic[T], ExpressionVisitor[T], StatementVisitor[T], PatternVisitor[T]):\n    \"\"\"Empty base class for parse tree node visitors.\n\n    The T type argument specifies the return type of the visit\n    methods. As all methods defined here raise by default,\n    subclasses do not always need to override all the methods.\n    \"\"\"\n\n    # Not in superclasses:\n\n    def visit_mypy_file(self, o: mypy.nodes.MypyFile, /) -> T:\n        raise NotImplementedError()\n\n    # TODO: We have a visit_var method, but no visit_typeinfo or any\n    # other non-Statement SymbolNode (accepting those will raise a\n    # runtime error). Maybe this should be resolved in some direction.\n    def visit_var(self, o: mypy.nodes.Var, /) -> T:\n        raise NotImplementedError()\n\n    # Module structure\n\n    def visit_import(self, o: mypy.nodes.Import, /) -> T:\n        raise NotImplementedError()\n\n    def visit_import_from(self, o: mypy.nodes.ImportFrom, /) -> T:\n        raise NotImplementedError()\n\n    def visit_import_all(self, o: mypy.nodes.ImportAll, /) -> T:\n        raise NotImplementedError()\n\n    # Definitions\n\n    def visit_func_def(self, o: mypy.nodes.FuncDef, /) -> T:\n        raise NotImplementedError()\n\n    def visit_overloaded_func_def(self, o: mypy.nodes.OverloadedFuncDef, /) -> T:\n        raise NotImplementedError()\n\n    def visit_class_def(self, o: mypy.nodes.ClassDef, /) -> T:\n        raise NotImplementedError()\n\n    def visit_global_decl(self, o: mypy.nodes.GlobalDecl, /) -> T:\n        raise NotImplementedError()\n\n    def visit_nonlocal_decl(self, o: mypy.nodes.NonlocalDecl, /) -> T:\n        raise NotImplementedError()\n\n    def visit_decorator(self, o: mypy.nodes.Decorator, /) -> T:\n        raise NotImplementedError()\n\n    def visit_type_alias(self, o: mypy.nodes.TypeAlias, /) -> T:\n        raise NotImplementedError()\n\n    def visit_placeholder_node(self, o: mypy.nodes.PlaceholderNode, /) -> T:\n        raise NotImplementedError()\n\n    # Statements\n\n    def visit_block(self, o: mypy.nodes.Block, /) -> T:\n        raise NotImplementedError()\n\n    def visit_expression_stmt(self, o: mypy.nodes.ExpressionStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_assignment_stmt(self, o: mypy.nodes.AssignmentStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_operator_assignment_stmt(self, o: mypy.nodes.OperatorAssignmentStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_while_stmt(self, o: mypy.nodes.WhileStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_for_stmt(self, o: mypy.nodes.ForStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_return_stmt(self, o: mypy.nodes.ReturnStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_assert_stmt(self, o: mypy.nodes.AssertStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_del_stmt(self, o: mypy.nodes.DelStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_if_stmt(self, o: mypy.nodes.IfStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_break_stmt(self, o: mypy.nodes.BreakStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_continue_stmt(self, o: mypy.nodes.ContinueStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_pass_stmt(self, o: mypy.nodes.PassStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_raise_stmt(self, o: mypy.nodes.RaiseStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_try_stmt(self, o: mypy.nodes.TryStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_with_stmt(self, o: mypy.nodes.WithStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_match_stmt(self, o: mypy.nodes.MatchStmt, /) -> T:\n        raise NotImplementedError()\n\n    def visit_type_alias_stmt(self, o: mypy.nodes.TypeAliasStmt, /) -> T:\n        raise NotImplementedError()\n\n    # Expressions (default no-op implementation)\n\n    def visit_int_expr(self, o: mypy.nodes.IntExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_str_expr(self, o: mypy.nodes.StrExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_bytes_expr(self, o: mypy.nodes.BytesExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_float_expr(self, o: mypy.nodes.FloatExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_complex_expr(self, o: mypy.nodes.ComplexExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_ellipsis(self, o: mypy.nodes.EllipsisExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_star_expr(self, o: mypy.nodes.StarExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_name_expr(self, o: mypy.nodes.NameExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_member_expr(self, o: mypy.nodes.MemberExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_yield_from_expr(self, o: mypy.nodes.YieldFromExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_yield_expr(self, o: mypy.nodes.YieldExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_call_expr(self, o: mypy.nodes.CallExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_op_expr(self, o: mypy.nodes.OpExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_comparison_expr(self, o: mypy.nodes.ComparisonExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_cast_expr(self, o: mypy.nodes.CastExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_type_form_expr(self, o: mypy.nodes.TypeFormExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_assert_type_expr(self, o: mypy.nodes.AssertTypeExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_reveal_expr(self, o: mypy.nodes.RevealExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_super_expr(self, o: mypy.nodes.SuperExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_assignment_expr(self, o: mypy.nodes.AssignmentExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_unary_expr(self, o: mypy.nodes.UnaryExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_list_expr(self, o: mypy.nodes.ListExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_dict_expr(self, o: mypy.nodes.DictExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_template_str_expr(self, o: mypy.nodes.TemplateStrExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_tuple_expr(self, o: mypy.nodes.TupleExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_set_expr(self, o: mypy.nodes.SetExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_index_expr(self, o: mypy.nodes.IndexExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_type_application(self, o: mypy.nodes.TypeApplication, /) -> T:\n        raise NotImplementedError()\n\n    def visit_lambda_expr(self, o: mypy.nodes.LambdaExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_list_comprehension(self, o: mypy.nodes.ListComprehension, /) -> T:\n        raise NotImplementedError()\n\n    def visit_set_comprehension(self, o: mypy.nodes.SetComprehension, /) -> T:\n        raise NotImplementedError()\n\n    def visit_dictionary_comprehension(self, o: mypy.nodes.DictionaryComprehension, /) -> T:\n        raise NotImplementedError()\n\n    def visit_generator_expr(self, o: mypy.nodes.GeneratorExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_slice_expr(self, o: mypy.nodes.SliceExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_conditional_expr(self, o: mypy.nodes.ConditionalExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_type_var_expr(self, o: mypy.nodes.TypeVarExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_paramspec_expr(self, o: mypy.nodes.ParamSpecExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_type_var_tuple_expr(self, o: mypy.nodes.TypeVarTupleExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_type_alias_expr(self, o: mypy.nodes.TypeAliasExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_namedtuple_expr(self, o: mypy.nodes.NamedTupleExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_enum_call_expr(self, o: mypy.nodes.EnumCallExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_typeddict_expr(self, o: mypy.nodes.TypedDictExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_newtype_expr(self, o: mypy.nodes.NewTypeExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit__promote_expr(self, o: mypy.nodes.PromoteExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_await_expr(self, o: mypy.nodes.AwaitExpr, /) -> T:\n        raise NotImplementedError()\n\n    def visit_temp_node(self, o: mypy.nodes.TempNode, /) -> T:\n        raise NotImplementedError()\n\n    # Patterns\n\n    def visit_as_pattern(self, o: mypy.patterns.AsPattern, /) -> T:\n        raise NotImplementedError()\n\n    def visit_or_pattern(self, o: mypy.patterns.OrPattern, /) -> T:\n        raise NotImplementedError()\n\n    def visit_value_pattern(self, o: mypy.patterns.ValuePattern, /) -> T:\n        raise NotImplementedError()\n\n    def visit_singleton_pattern(self, o: mypy.patterns.SingletonPattern, /) -> T:\n        raise NotImplementedError()\n\n    def visit_sequence_pattern(self, o: mypy.patterns.SequencePattern, /) -> T:\n        raise NotImplementedError()\n\n    def visit_starred_pattern(self, o: mypy.patterns.StarredPattern, /) -> T:\n        raise NotImplementedError()\n\n    def visit_mapping_pattern(self, o: mypy.patterns.MappingPattern, /) -> T:\n        raise NotImplementedError()\n\n    def visit_class_pattern(self, o: mypy.patterns.ClassPattern, /) -> T:\n        raise NotImplementedError()\n"
  },
  {
    "path": "mypy/xml/mypy-html.css",
    "content": "/* CSS for type check coverage reports */\n\n/*\n    Used by both summary and file.\n*/\nbody {\n    font-family: \"Helvetica Neue\", sans-serif;\n}\n\n/*\n    Used only by summary.\n*/\n\nh1 {\n    text-align: center;\n    font-size: 135%;\n    margin: 20px;\n}\n\ntable.summary {\n    border-collapse: collapse;\n    margin-left: 7%;\n    margin-right: 7%;\n    width: 85%;\n}\n\ntable caption {\n    margin: 1em;\n}\n\ntable.summary, tr.summary, th.summary, td.summary {\n    border: 1px solid #aaa;\n}\n\nth.summary, td.summary {\n    padding: 0.4em;\n}\n\ntd.summary a {\n    text-decoration: none;\n}\n\n.summary-quality-0 {\n    background-color: #dfd;\n}\n\n.summary-quality-1 {\n    background-color: #ffa;\n}\n\n.summary-quality-2 {\n    background-color: #faa;\n}\n\ntd.summary-filename, th.summary-filename {\n    text-align: left;\n}\n\ntd.summary-filename {\n    width: 50%;\n}\n\n.summary-precision {\n    text-align: center;\n}\n\n.summary-lines {\n    text-align: center;\n}\n\n/*\n    Used only by file.\n*/\n\ntd.table-lines {\n    text-align: right;\n    padding-right: 0.5em;\n}\n\ntd.table-code { }\n\nspan.lineno {\n    text-align: right;\n}\n\na:link.lineno, a:visited.lineno {\n    color: #999; text-decoration: none;\n}\n\na:hover.lineno, a:active.lineno {\n    color: #000; text-decoration: underline;\n}\n\n.line-empty, .line-precise {\n    background-color: #dfd;\n}\n\n.line-imprecise {\n    background-color: #ffa;\n}\n\n.line-any, .line-unanalyzed {\n    background-color: #faa;\n}\n"
  },
  {
    "path": "mypy/xml/mypy-html.xslt",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- vim: set sts=2 sw=2: -->\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n  <xsl:param name=\"ext\" select=\"'xml'\"/>\n  <xsl:output method=\"html\"/>\n  <xsl:variable name=\"xml_stylesheet_pi\" select=\"string(//processing-instruction('xml-stylesheet'))\"/>\n  <xsl:variable name=\"stylesheet_name\" select=\"substring($xml_stylesheet_pi, 23, string-length($xml_stylesheet_pi) - 28)\"/>\n  <xsl:template match=\"/mypy-report-index\">\n    <html>\n      <head>\n        <link rel=\"stylesheet\" type=\"text/css\" href=\"{$stylesheet_name}.css\"/>\n      </head>\n      <body>\n        <h1>Mypy Type Check Coverage Summary</h1>\n        <table class=\"summary\">\n          <caption>Summary from <xsl:value-of select=\"@name\"/></caption>\n          <thead>\n            <tr class=\"summary\">\n              <th class=\"summary\">File</th>\n              <th class=\"summary\">Imprecision</th>\n              <th class=\"summary\">Lines</th>\n            </tr>\n          </thead>\n          <tfoot>\n            <xsl:variable name=\"bad_lines\" select=\"sum(file/@imprecise|file/@any)\"/>\n            <xsl:variable name=\"total_lines\" select=\"sum(file/@total)\"/>\n            <xsl:variable name=\"global_score\" select=\"$bad_lines div ($total_lines + not(number($total_lines)))\"/>\n            <xsl:variable name=\"global_quality\" select=\"string(number(number($global_score) &gt; 0.00) + number(number($global_score) &gt;= 0.20))\"/>\n            <tr class=\"summary summary-quality-{$global_quality}\">\n              <th class=\"summary summary-filename\">Total</th>\n              <th class=\"summary summary-precision\"><xsl:value-of select=\"format-number($global_score, '0.00%')\"/> imprecise</th>\n              <th class=\"summary summary-lines\"><xsl:value-of select=\"$total_lines\"/> LOC</th>\n            </tr>\n          </tfoot>\n          <tbody>\n            <xsl:for-each select=\"file\">\n              <xsl:variable name=\"local_score\" select=\"(@imprecise + @any) div (@total + not(number(@total)))\"/>\n              <xsl:variable name=\"local_quality\" select=\"string(number(number($local_score) &gt; 0.00) + number(number($local_score) &gt;= 0.20))\"/>\n              <tr class=\"summary summary-quality-{$local_quality}\">\n                <td class=\"summary summary-filename\"><a href=\"{$ext}/{@name}.{$ext}\"><xsl:value-of select=\"@module\"/></a></td>\n                <td class=\"summary summary-precision\"><xsl:value-of select=\"format-number($local_score, '0.00%')\"/> imprecise</td>\n                <td class=\"summary summary-lines\"><xsl:value-of select=\"@total\"/> LOC</td>\n              </tr>\n            </xsl:for-each>\n          </tbody>\n        </table>\n      </body>\n    </html>\n  </xsl:template>\n  <xsl:template match=\"/mypy-report-file\">\n    <html>\n      <head>\n        <link rel=\"stylesheet\" type=\"text/css\" href=\"{$stylesheet_name}.css\"/>\n      </head>\n      <body>\n        <h2><xsl:value-of select=\"@module\"/></h2>\n        <table>\n          <caption><xsl:value-of select=\"@name\"/></caption>\n          <tbody>\n            <tr>\n              <td class=\"table-lines\">\n                <pre>\n                  <xsl:for-each select=\"line\">\n                    <span id=\"L{@number}\" class=\"lineno\"><a class=\"lineno\" href=\"#L{@number}\"><xsl:value-of select=\"@number\"/></a></span><xsl:text>&#10;</xsl:text>\n                  </xsl:for-each>\n                </pre>\n              </td>\n              <td class=\"table-code\">\n                <pre>\n                  <xsl:for-each select=\"line\">\n                    <span class=\"line-{@precision}\" title=\"{@any_info}\"><xsl:value-of select=\"@content\"/></span><xsl:text>&#10;</xsl:text>\n                  </xsl:for-each>\n                </pre>\n              </td>\n            </tr>\n          </tbody>\n        </table>\n      </body>\n    </html>\n  </xsl:template>\n</xsl:stylesheet>\n"
  },
  {
    "path": "mypy/xml/mypy-txt.xslt",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- vim: set sts=2 sw=2: -->\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:math=\"http://exslt.org/math\" xmlns:str=\"http://exslt.org/strings\">\n  <xsl:output method=\"text\"/>\n  <xsl:template match=\"/mypy-report-index\">\n    <!-- It's possible to output without the <xsl:text> but it's harder to control. -->\n    <xsl:text>Mypy Type Check Coverage Summary&#10;</xsl:text>\n    <xsl:text>================================&#10;</xsl:text>\n    <xsl:text>&#10;</xsl:text>\n    <xsl:text>Script: </xsl:text><xsl:value-of select=\"@name\"/><xsl:text>&#10;</xsl:text>\n    <xsl:text>&#10;</xsl:text>\n\n    <xsl:variable name=\"max_module_width\">\n      <xsl:for-each select=\"file\">\n        <xsl:sort select=\"string-length(@module)\" data-type=\"number\"/>\n        <xsl:if test=\"position() = last()\">\n          <xsl:value-of select=\"string-length(@module)\"/>\n        </xsl:if>\n      </xsl:for-each>\n    </xsl:variable>\n    <xsl:variable name=\"max_imprecision_width\" select=\"string-length('100.00% imprecise')\"/>\n    <xsl:variable name=\"max_loc_width\" select=\"string-length(concat(sum(file/@total), ' LOC'))\"/>\n\n    <xsl:text>+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_module_width, '-')\"/>\n    <xsl:text>-+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_imprecision_width, '-')\"/>\n    <xsl:text>-+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_loc_width, '-')\"/>\n    <xsl:text>-+&#10;</xsl:text>\n\n    <xsl:text>| </xsl:text>\n    <xsl:value-of select=\"'Module'\"/>\n    <xsl:value-of select=\"str:padding($max_module_width - string-length('Module'), ' ')\"/>\n    <xsl:text> | </xsl:text>\n    <xsl:value-of select=\"'Imprecision'\"/>\n    <xsl:value-of select=\"str:padding($max_imprecision_width - string-length('Imprecision'), ' ')\"/>\n    <xsl:text> | </xsl:text>\n    <xsl:value-of select=\"'Lines'\"/>\n    <xsl:value-of select=\"str:padding($max_loc_width - string-length('Lines'), ' ')\"/>\n    <xsl:text> |&#10;</xsl:text>\n\n    <xsl:text>+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_module_width, '-')\"/>\n    <xsl:text>-+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_imprecision_width, '-')\"/>\n    <xsl:text>-+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_loc_width, '-')\"/>\n    <xsl:text>-+&#10;</xsl:text>\n\n    <xsl:for-each select=\"file\">\n      <xsl:variable name=\"score\" select=\"(@imprecise + @any) div (@total + not(number(@total)))\"/>\n      <xsl:variable name=\"imprecision\" select=\"concat(format-number($score, '0.00%'), ' imprecise')\"/>\n      <xsl:variable name=\"lines\" select=\"concat(@total, ' LOC')\"/>\n\n      <xsl:text>| </xsl:text>\n      <xsl:value-of select=\"@module\"/>\n      <xsl:value-of select=\"str:padding($max_module_width - string-length(@module), ' ')\"/>\n      <xsl:text> | </xsl:text>\n      <xsl:value-of select=\"str:padding($max_imprecision_width - string-length($imprecision), ' ')\"/>\n      <xsl:value-of select=\"$imprecision\"/>\n      <xsl:text> | </xsl:text>\n      <xsl:value-of select=\"str:padding($max_loc_width - string-length($lines), ' ')\"/>\n      <xsl:value-of select=\"$lines\"/>\n      <xsl:text> |&#10;</xsl:text>\n    </xsl:for-each>\n\n    <xsl:text>+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_module_width, '-')\"/>\n    <xsl:text>-+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_imprecision_width, '-')\"/>\n    <xsl:text>-+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_loc_width, '-')\"/>\n    <xsl:text>-+&#10;</xsl:text>\n\n    <xsl:variable name=\"total\" select=\"sum(file/@total)\"/>\n    <xsl:variable name=\"score\" select=\"(sum(file/@imprecise|file/@any)) div ($total + not(number($total)))\"/>\n    <xsl:variable name=\"imprecision\" select=\"concat(format-number($score, '0.00%'), ' imprecise')\"/>\n    <xsl:variable name=\"lines\" select=\"concat($total, ' LOC')\"/>\n\n    <xsl:text>| </xsl:text>\n    <xsl:value-of select=\"'Total'\"/>\n    <xsl:value-of select=\"str:padding($max_module_width - string-length('Total'), ' ')\"/>\n    <xsl:text> | </xsl:text>\n    <xsl:value-of select=\"str:padding($max_imprecision_width - string-length($imprecision), ' ')\"/>\n    <xsl:value-of select=\"$imprecision\"/>\n    <xsl:text> | </xsl:text>\n    <xsl:value-of select=\"str:padding($max_loc_width - string-length($lines), ' ')\"/>\n    <xsl:value-of select=\"$lines\"/>\n    <xsl:text> |&#10;</xsl:text>\n\n    <xsl:text>+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_module_width, '-')\"/>\n    <xsl:text>-+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_imprecision_width, '-')\"/>\n    <xsl:text>-+-</xsl:text>\n    <xsl:value-of select=\"str:padding($max_loc_width, '-')\"/>\n    <xsl:text>-+&#10;</xsl:text>\n  </xsl:template>\n</xsl:stylesheet>\n"
  },
  {
    "path": "mypy/xml/mypy.xsd",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- vim: set sts=2 sw=2: -->\n<xs:schema xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n  <!-- simple types -->\n  <xs:simpleType name=\"precision\">\n    <xs:restriction base=\"xs:string\">\n      <xs:enumeration value=\"empty\"/>\n      <xs:enumeration value=\"unanalyzed\"/>\n      <xs:enumeration value=\"precise\"/>\n      <xs:enumeration value=\"imprecise\"/>\n      <xs:enumeration value=\"any\"/>\n    </xs:restriction>\n  </xs:simpleType>\n  <!-- root elements -->\n  <xs:element name=\"mypy-report-index\">\n    <xs:complexType>\n      <xs:sequence>\n        <xs:element name=\"file\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n          <xs:complexType>\n            <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\"/>\n            <xs:attribute name=\"module\" type=\"xs:string\" use=\"required\"/>\n            <xs:attribute name=\"total\" type=\"xs:integer\" use=\"required\"/>\n            <xs:attribute name=\"empty\" type=\"xs:integer\" use=\"required\"/>\n            <xs:attribute name=\"unanalyzed\" type=\"xs:integer\" use=\"required\"/>\n            <xs:attribute name=\"precise\" type=\"xs:integer\" use=\"required\"/>\n            <xs:attribute name=\"imprecise\" type=\"xs:integer\" use=\"required\"/>\n            <xs:attribute name=\"any\" type=\"xs:integer\" use=\"required\"/>\n          </xs:complexType>\n        </xs:element>\n      </xs:sequence>\n      <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\"/>\n    </xs:complexType>\n  </xs:element>\n  <xs:element name=\"mypy-report-file\">\n    <xs:complexType>\n      <xs:sequence>\n        <xs:element name=\"line\" minOccurs=\"0\" maxOccurs=\"unbounded\">\n          <xs:complexType>\n            <xs:attribute name=\"number\" type=\"xs:integer\" use=\"required\"/>\n            <xs:attribute name=\"precision\" type=\"precision\" use=\"required\"/>\n            <xs:attribute name=\"any_info\" type=\"xs:string\" use=\"optional\"/>\n            <xs:attribute name=\"content\" type=\"xs:string\" use=\"required\"/>\n          </xs:complexType>\n        </xs:element>\n      </xs:sequence>\n      <xs:attribute name=\"name\" type=\"xs:string\" use=\"required\"/>\n      <xs:attribute name=\"module\" type=\"xs:string\" use=\"required\"/>\n    </xs:complexType>\n  </xs:element>\n</xs:schema>\n"
  },
  {
    "path": "mypy-requirements.txt",
    "content": "# NOTE: this needs to be kept in sync with the \"requires\" list in pyproject.toml\n# and the pins in setup.py\ntyping_extensions>=4.6.0\nmypy_extensions>=1.0.0\npathspec>=1.0.0\ntomli>=1.1.0; python_version<'3.11'\nlibrt>=0.8.0; platform_python_implementation != 'PyPy'\n"
  },
  {
    "path": "mypy_bootstrap.ini",
    "content": "[mypy]\nstrict = True\nwarn_unused_ignores = False\nshow_traceback = True\nalways_true = MYPYC\nlocal_partial_types = True\nallow_redefinition_new = True\n\n[mypy-mypy.visitor]\n# See docstring for NodeVisitor for motivation.\ndisable_error_code = empty-body\n"
  },
  {
    "path": "mypy_self_check.ini",
    "content": "[mypy]\n\npython_version = 3.10\nexclude = mypy/typeshed/|mypyc/test-data/|mypyc/lib-rt/\n\n# Options that affect type checking\nstrict = True\nallow_redefinition_new = True\nlocal_partial_types = True\ndisallow_any_unimported = True\nwarn_unreachable = True\nenable_error_code = ignore-without-code,redundant-expr\nenable_incomplete_feature = PreciseTupleTypes\n\n# Plugins or custom behaviour\nalways_false = MYPYC\nplugins = mypy.plugins.proper_plugin\n\n# Options that affect output\npretty = True\nshow_error_code_links = True\nshow_traceback = True\n\n# Miscellaneous\nsqlite_cache = True\n"
  },
  {
    "path": "mypyc/.readthedocs.yaml",
    "content": "# Read the Docs configuration file\n# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details\n\nversion: 2\n\nbuild:\n  os: ubuntu-22.04\n  tools:\n    python: \"3.11\"\n\nsphinx:\n   configuration: mypyc/doc/conf.py\n\nformats: [pdf, htmlzip, epub]\n\npython:\n   install:\n   - requirements: docs/requirements-docs.txt\n"
  },
  {
    "path": "mypyc/README.md",
    "content": "mypyc: Mypy to Python C Extension Compiler\n==========================================\n\nFor the mypyc README, refer to the [mypyc repository](https://github.com/mypyc/mypyc). The mypyc\nrepository also contains the mypyc issue tracker. All mypyc code lives\nhere in the mypy repository.\n\nSource code for the mypyc user documentation lives under\n[mypyc/doc](./doc).\n\nMypyc welcomes new contributors! Refer to our\n[developer documentation](./doc/dev-intro.md) for more information.\n"
  },
  {
    "path": "mypyc/__init__.py",
    "content": ""
  },
  {
    "path": "mypyc/__main__.py",
    "content": "\"\"\"Mypyc command-line tool.\n\nUsage:\n\n    $ mypyc foo.py [...]\n    $ python3 -c 'import foo'  # Uses compiled 'foo'\n\n\nThis is just a thin wrapper that generates a setup.py file that uses\nmypycify, suitable for prototyping and testing.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport os.path\nimport subprocess\nimport sys\n\nbase_path = os.path.join(os.path.dirname(__file__), \"..\")\n\nsetup_format = \"\"\"\\\nfrom setuptools import setup\nfrom mypyc.build import mypycify\n\nsetup(\n    name='mypyc_output',\n    ext_modules=mypycify(\n        {},\n        opt_level=\"{}\",\n        debug_level=\"{}\",\n        strict_dunder_typing={},\n        log_trace={},\n    ),\n)\n\"\"\"\n\n\ndef main() -> None:\n    build_dir = \"build\"  # can this be overridden??\n    try:\n        os.mkdir(build_dir)\n    except FileExistsError:\n        pass\n\n    opt_level = os.getenv(\"MYPYC_OPT_LEVEL\", \"3\")\n    debug_level = os.getenv(\"MYPYC_DEBUG_LEVEL\", \"1\")\n    strict_dunder_typing = bool(int(os.getenv(\"MYPYC_STRICT_DUNDER_TYPING\", \"0\")))\n    # If enabled, compiled code writes a sampled log of executed ops (or events) to\n    # mypyc_trace.txt.\n    log_trace = bool(int(os.getenv(\"MYPYC_LOG_TRACE\", \"0\")))\n\n    setup_file = os.path.join(build_dir, \"setup.py\")\n    with open(setup_file, \"w\") as f:\n        f.write(\n            setup_format.format(\n                sys.argv[1:], opt_level, debug_level, strict_dunder_typing, log_trace\n            )\n        )\n\n    # We don't use run_setup (like we do in the test suite) because it throws\n    # away the error code from distutils, and we don't care about the slight\n    # performance loss here.\n    env = os.environ.copy()\n    base_path = os.path.join(os.path.dirname(__file__), \"..\")\n    env[\"PYTHONPATH\"] = base_path + os.pathsep + env.get(\"PYTHONPATH\", \"\")\n    cmd = subprocess.run([sys.executable, setup_file, \"build_ext\", \"--inplace\"], env=env)\n    sys.exit(cmd.returncode)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "mypyc/analysis/__init__.py",
    "content": ""
  },
  {
    "path": "mypyc/analysis/attrdefined.py",
    "content": "\"\"\"Always defined attribute analysis.\n\nAn always defined attribute has some statements in __init__ or the\nclass body that cause the attribute to be always initialized when an\ninstance is constructed. It must also not be possible to read the\nattribute before initialization, and it can't be deletable.\n\nWe can assume that the value is always defined when reading an always\ndefined attribute. Otherwise we'll need to raise AttributeError if the\nvalue is undefined (i.e. has the error value).\n\nWe use data flow analysis to figure out attributes that are always\ndefined. Example:\n\n  class C:\n      def __init__(self) -> None:\n          self.x = 0\n          if func():\n              self.y = 1\n          else:\n              self.y = 2\n              self.z = 3\n\nIn this example, the attributes 'x' and 'y' are always defined, but 'z'\nis not. The analysis assumes that we know that there won't be any subclasses.\n\nThe analysis also works if there is a known, closed set of subclasses.\nAn attribute defined in a base class can only be always defined if it's\nalso always defined in all subclasses.\n\nAs soon as __init__ contains an op that can 'leak' self to another\nfunction, we will stop inferring always defined attributes, since the\nanalysis is mostly intra-procedural and only looks at __init__ methods.\nThe called code could read an uninitialized attribute. Example:\n\n  class C:\n      def __init__(self) -> None:\n          self.x = self.foo()\n\n      def foo(self) -> int:\n          ...\n\nNow we won't infer 'x' as always defined, since 'foo' might read 'x'\nbefore initialization.\n\nAs an exception to the above limitation, we perform inter-procedural\nanalysis of super().__init__ calls, since these are very common.\n\nOur analysis is somewhat optimistic. We assume that nobody calls a\nmethod of a partially uninitialized object through gc.get_objects(), in\nparticular. Code like this could potentially cause a segfault with a null\npointer dereference. This seems very unlikely to be an issue in practice,\nhowever.\n\nAccessing an attribute via getattr always checks for undefined attributes\nand thus works if the object is partially uninitialized. This can be used\nas a workaround if somebody ever needs to inspect partially uninitialized\nobjects via gc.get_objects().\n\nThe analysis runs after IR building as a separate pass. Since we only\nrun this on __init__ methods, this analysis pass will be fairly quick.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final\n\nfrom mypyc.analysis.dataflow import (\n    CFG,\n    MAYBE_ANALYSIS,\n    AnalysisResult,\n    BaseAnalysisVisitor,\n    get_cfg,\n    run_analysis,\n)\nfrom mypyc.analysis.selfleaks import analyze_self_leaks\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.ops import (\n    Assign,\n    AssignMulti,\n    BasicBlock,\n    Branch,\n    Call,\n    ControlOp,\n    GetAttr,\n    Register,\n    RegisterOp,\n    Return,\n    SetAttr,\n    SetMem,\n    Unreachable,\n)\nfrom mypyc.ir.rtypes import RInstance\n\n# If True, print out all always-defined attributes of native classes (to aid\n# debugging and testing)\ndump_always_defined: Final = False\n\n\ndef analyze_always_defined_attrs(class_irs: list[ClassIR]) -> None:\n    \"\"\"Find always defined attributes all classes of a compilation unit.\n\n    Also tag attribute initialization ops to not decref the previous\n    value (as this would read a NULL pointer and segfault).\n\n    Update the _always_initialized_attrs, _sometimes_initialized_attrs\n    and init_self_leak attributes in ClassIR instances.\n\n    This is the main entry point.\n    \"\"\"\n    seen: set[ClassIR] = set()\n\n    # First pass: only look at target class and classes in MRO\n    for cl in class_irs:\n        analyze_always_defined_attrs_in_class(cl, seen)\n\n    # Second pass: look at all derived class\n    seen = set()\n    for cl in class_irs:\n        update_always_defined_attrs_using_subclasses(cl, seen)\n\n    # Final pass: detect attributes that need to use a bitmap to track definedness\n    seen = set()\n    for cl in class_irs:\n        detect_undefined_bitmap(cl, seen)\n\n\ndef analyze_always_defined_attrs_in_class(cl: ClassIR, seen: set[ClassIR]) -> None:\n    if cl in seen:\n        return\n\n    seen.add(cl)\n\n    if (\n        cl.is_trait\n        or cl.inherits_python\n        or cl.allow_interpreted_subclasses\n        or cl.builtin_base is not None\n        or cl.children is None\n        or cl.is_serializable()\n        or cl.has_method(\"__new__\")\n    ):\n        # Give up -- we can't enforce that attributes are always defined.\n        return\n\n    # First analyze all base classes. Track seen classes to avoid duplicate work.\n    for base in cl.mro[1:]:\n        analyze_always_defined_attrs_in_class(base, seen)\n\n    m = cl.get_method(\"__init__\")\n    if m is None:\n        cl._always_initialized_attrs = cl.attrs_with_defaults.copy()\n        cl._sometimes_initialized_attrs = cl.attrs_with_defaults.copy()\n        return\n    self_reg = m.arg_regs[0]\n    cfg = get_cfg(m.blocks)\n    dirty = analyze_self_leaks(m.blocks, self_reg, cfg)\n    maybe_defined = analyze_maybe_defined_attrs_in_init(\n        m.blocks, self_reg, cl.attrs_with_defaults, cfg\n    )\n    all_attrs: set[str] = set()\n    for base in cl.mro:\n        all_attrs.update(base.attributes)\n    maybe_undefined = analyze_maybe_undefined_attrs_in_init(\n        m.blocks, self_reg, initial_undefined=all_attrs - cl.attrs_with_defaults, cfg=cfg\n    )\n\n    always_defined = find_always_defined_attributes(\n        m.blocks, self_reg, all_attrs, maybe_defined, maybe_undefined, dirty\n    )\n    always_defined = {a for a in always_defined if not cl.is_deletable(a)}\n\n    cl._always_initialized_attrs = always_defined\n    if dump_always_defined:\n        print(cl.name, sorted(always_defined))\n    cl._sometimes_initialized_attrs = find_sometimes_defined_attributes(\n        m.blocks, self_reg, maybe_defined, dirty\n    )\n\n    mark_attr_initialization_ops(m.blocks, self_reg, maybe_defined, dirty)\n\n    # Check if __init__ can run unpredictable code (leak 'self').\n    any_dirty = False\n    for b in m.blocks:\n        for i, op in enumerate(b.ops):\n            if dirty.after[b, i] and not isinstance(op, Return):\n                any_dirty = True\n                break\n    cl.init_self_leak = any_dirty\n\n\ndef find_always_defined_attributes(\n    blocks: list[BasicBlock],\n    self_reg: Register,\n    all_attrs: set[str],\n    maybe_defined: AnalysisResult[str],\n    maybe_undefined: AnalysisResult[str],\n    dirty: AnalysisResult[None],\n) -> set[str]:\n    \"\"\"Find attributes that are always initialized in some basic blocks.\n\n    The analysis results are expected to be up-to-date for the blocks.\n\n    Return a set of always defined attributes.\n    \"\"\"\n    attrs = all_attrs.copy()\n    for block in blocks:\n        for i, op in enumerate(block.ops):\n            # If an attribute we *read* may be undefined, it isn't always defined.\n            if isinstance(op, GetAttr) and op.obj is self_reg:\n                if op.attr in maybe_undefined.before[block, i]:\n                    attrs.discard(op.attr)\n            # If an attribute we *set* may be sometimes undefined and\n            # sometimes defined, don't consider it always defined. Unlike\n            # the get case, it's fine for the attribute to be undefined.\n            # The set operation will then be treated as initialization.\n            if isinstance(op, SetAttr) and op.obj is self_reg:\n                if (\n                    op.attr in maybe_undefined.before[block, i]\n                    and op.attr in maybe_defined.before[block, i]\n                ):\n                    attrs.discard(op.attr)\n            # Treat an op that might run arbitrary code as an \"exit\"\n            # in terms of the analysis -- we can't do any inference\n            # afterwards reliably.\n            if dirty.after[block, i]:\n                if not dirty.before[block, i]:\n                    attrs = attrs & (\n                        maybe_defined.after[block, i] - maybe_undefined.after[block, i]\n                    )\n                break\n            if isinstance(op, ControlOp):\n                for target in op.targets():\n                    # Gotos/branches can also be \"exits\".\n                    if not dirty.after[block, i] and dirty.before[target, 0]:\n                        attrs = attrs & (\n                            maybe_defined.after[target, 0] - maybe_undefined.after[target, 0]\n                        )\n    return attrs\n\n\ndef find_sometimes_defined_attributes(\n    blocks: list[BasicBlock],\n    self_reg: Register,\n    maybe_defined: AnalysisResult[str],\n    dirty: AnalysisResult[None],\n) -> set[str]:\n    \"\"\"Find attributes that are sometimes initialized in some basic blocks.\"\"\"\n    attrs: set[str] = set()\n    for block in blocks:\n        for i, op in enumerate(block.ops):\n            # Only look at possibly defined attributes at exits.\n            if dirty.after[block, i]:\n                if not dirty.before[block, i]:\n                    attrs = attrs | maybe_defined.after[block, i]\n                break\n            if isinstance(op, ControlOp):\n                for target in op.targets():\n                    if not dirty.after[block, i] and dirty.before[target, 0]:\n                        attrs = attrs | maybe_defined.after[target, 0]\n    return attrs\n\n\ndef mark_attr_initialization_ops(\n    blocks: list[BasicBlock],\n    self_reg: Register,\n    maybe_defined: AnalysisResult[str],\n    dirty: AnalysisResult[None],\n) -> None:\n    \"\"\"Tag all SetAttr ops in the basic blocks that initialize attributes.\n\n    Initialization ops assume that the previous attribute value is the error value,\n    so there's no need to decref or check for definedness.\n    \"\"\"\n    for block in blocks:\n        for i, op in enumerate(block.ops):\n            if isinstance(op, SetAttr) and op.obj is self_reg:\n                attr = op.attr\n                if attr not in maybe_defined.before[block, i] and not dirty.after[block, i]:\n                    op.mark_as_initializer()\n\n\nGenAndKill = tuple[set[str], set[str]]\n\n\ndef attributes_initialized_by_init_call(op: Call) -> set[str]:\n    \"\"\"Calculate attributes that are always initialized by a super().__init__ call.\"\"\"\n    self_type = op.fn.sig.args[0].type\n    assert isinstance(self_type, RInstance), self_type\n    cl = self_type.class_ir\n    return {a for base in cl.mro for a in base.attributes if base.is_always_defined(a)}\n\n\ndef attributes_maybe_initialized_by_init_call(op: Call) -> set[str]:\n    \"\"\"Calculate attributes that may be initialized by a super().__init__ call.\"\"\"\n    self_type = op.fn.sig.args[0].type\n    assert isinstance(self_type, RInstance), self_type\n    cl = self_type.class_ir\n    return attributes_initialized_by_init_call(op) | cl._sometimes_initialized_attrs\n\n\nclass AttributeMaybeDefinedVisitor(BaseAnalysisVisitor[str]):\n    \"\"\"Find attributes that may have been defined via some code path.\n\n    Consider initializations in class body and assignments to 'self.x'\n    and calls to base class '__init__'.\n    \"\"\"\n\n    def __init__(self, self_reg: Register) -> None:\n        self.self_reg = self_reg\n\n    def visit_branch(self, op: Branch) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n    def visit_return(self, op: Return) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n    def visit_unreachable(self, op: Unreachable) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n    def visit_register_op(self, op: RegisterOp) -> tuple[set[str], set[str]]:\n        if isinstance(op, SetAttr) and op.obj is self.self_reg:\n            return {op.attr}, set()\n        if isinstance(op, Call) and op.fn.class_name and op.fn.name == \"__init__\":\n            return attributes_maybe_initialized_by_init_call(op), set()\n        return set(), set()\n\n    def visit_assign(self, op: Assign) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n    def visit_assign_multi(self, op: AssignMulti) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n    def visit_set_mem(self, op: SetMem) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n\ndef analyze_maybe_defined_attrs_in_init(\n    blocks: list[BasicBlock], self_reg: Register, attrs_with_defaults: set[str], cfg: CFG\n) -> AnalysisResult[str]:\n    return run_analysis(\n        blocks=blocks,\n        cfg=cfg,\n        gen_and_kill=AttributeMaybeDefinedVisitor(self_reg),\n        initial=attrs_with_defaults,\n        backward=False,\n        kind=MAYBE_ANALYSIS,\n    )\n\n\nclass AttributeMaybeUndefinedVisitor(BaseAnalysisVisitor[str]):\n    \"\"\"Find attributes that may be undefined via some code path.\n\n    Consider initializations in class body, assignments to 'self.x'\n    and calls to base class '__init__'.\n    \"\"\"\n\n    def __init__(self, self_reg: Register) -> None:\n        self.self_reg = self_reg\n\n    def visit_branch(self, op: Branch) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n    def visit_return(self, op: Return) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n    def visit_unreachable(self, op: Unreachable) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n    def visit_register_op(self, op: RegisterOp) -> tuple[set[str], set[str]]:\n        if isinstance(op, SetAttr) and op.obj is self.self_reg:\n            return set(), {op.attr}\n        if isinstance(op, Call) and op.fn.class_name and op.fn.name == \"__init__\":\n            return set(), attributes_initialized_by_init_call(op)\n        return set(), set()\n\n    def visit_assign(self, op: Assign) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n    def visit_assign_multi(self, op: AssignMulti) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n    def visit_set_mem(self, op: SetMem) -> tuple[set[str], set[str]]:\n        return set(), set()\n\n\ndef analyze_maybe_undefined_attrs_in_init(\n    blocks: list[BasicBlock], self_reg: Register, initial_undefined: set[str], cfg: CFG\n) -> AnalysisResult[str]:\n    return run_analysis(\n        blocks=blocks,\n        cfg=cfg,\n        gen_and_kill=AttributeMaybeUndefinedVisitor(self_reg),\n        initial=initial_undefined,\n        backward=False,\n        kind=MAYBE_ANALYSIS,\n    )\n\n\ndef update_always_defined_attrs_using_subclasses(cl: ClassIR, seen: set[ClassIR]) -> None:\n    \"\"\"Remove attributes not defined in all subclasses from always defined attrs.\"\"\"\n    if cl in seen:\n        return\n    if cl.children is None:\n        # Subclasses are unknown\n        return\n    removed = set()\n    for attr in cl._always_initialized_attrs:\n        for child in cl.children:\n            update_always_defined_attrs_using_subclasses(child, seen)\n            if attr not in child._always_initialized_attrs:\n                removed.add(attr)\n    cl._always_initialized_attrs -= removed\n    seen.add(cl)\n\n\ndef detect_undefined_bitmap(cl: ClassIR, seen: set[ClassIR]) -> None:\n    if cl.is_trait:\n        return\n\n    if cl in seen:\n        return\n    seen.add(cl)\n    for base in cl.base_mro[1:]:\n        detect_undefined_bitmap(base, seen)\n\n    if len(cl.base_mro) > 1:\n        cl.bitmap_attrs.extend(cl.base_mro[1].bitmap_attrs)\n    for n, t in cl.attributes.items():\n        if t.error_overlap and not cl.is_always_defined(n):\n            cl.bitmap_attrs.append(n)\n\n    for base in cl.mro[1:]:\n        if base.is_trait:\n            for n, t in base.attributes.items():\n                if t.error_overlap and not cl.is_always_defined(n) and n not in cl.bitmap_attrs:\n                    cl.bitmap_attrs.append(n)\n"
  },
  {
    "path": "mypyc/analysis/blockfreq.py",
    "content": "\"\"\"Find basic blocks that are likely to be executed frequently.\n\nFor example, this would not include blocks that have exception handlers.\n\nWe can use different optimization heuristics for common and rare code. For\nexample, we can make IR fast to compile instead of fast to execute for rare\ncode.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.ops import BasicBlock, Branch, Goto\n\n\ndef frequently_executed_blocks(entry_point: BasicBlock) -> set[BasicBlock]:\n    result: set[BasicBlock] = set()\n    worklist = [entry_point]\n    while worklist:\n        block = worklist.pop()\n        if block in result:\n            continue\n        result.add(block)\n        t = block.terminator\n        if isinstance(t, Goto):\n            worklist.append(t.label)\n        elif isinstance(t, Branch):\n            if t.rare or t.traceback_entry is not None:\n                worklist.append(t.false)\n            else:\n                worklist.append(t.true)\n                worklist.append(t.false)\n    return result\n"
  },
  {
    "path": "mypyc/analysis/capsule_deps.py",
    "content": "from __future__ import annotations\n\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.deps import Dependency\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.ops import Assign, CallC, PrimitiveOp\nfrom mypyc.ir.rtypes import RStruct, RTuple, RType, RUnion, RVec\n\n\ndef find_implicit_op_dependencies(fn: FuncIR) -> set[Dependency] | None:\n    \"\"\"Find implicit dependencies that need to be imported.\n\n    Using primitives or types defined in librt submodules such as \"librt.base64\"\n    requires dependency imports (e.g., capsule imports).\n\n    Note that a module can depend on a librt module even if it doesn't explicitly\n    import it, for example via re-exported names or via return types of functions\n    defined in other modules.\n    \"\"\"\n    deps: set[Dependency] | None = None\n    # Check function signature types for dependencies\n    deps = find_type_dependencies(fn, deps)\n    # Check ops for dependencies\n    for block in fn.blocks:\n        for op in block.ops:\n            assert not isinstance(op, PrimitiveOp), \"Lowered IR is expected\"\n            if isinstance(op, CallC) and op.dependencies is not None:\n                for dep in op.dependencies:\n                    if deps is None:\n                        deps = set()\n                    deps.add(dep)\n            deps = collect_type_deps(op.type, deps)\n            if isinstance(op, Assign):\n                deps = collect_type_deps(op.dest.type, deps)\n    return deps\n\n\ndef find_type_dependencies(fn: FuncIR, deps: set[Dependency] | None) -> set[Dependency] | None:\n    \"\"\"Find dependencies from RTypes in function signatures.\n\n    Some RTypes (e.g., those for librt types) have associated dependencies\n    that need to be imported when the type is used.\n    \"\"\"\n    # Check parameter types\n    for arg in fn.decl.sig.args:\n        deps = collect_type_deps(arg.type, deps)\n    # Check return type\n    deps = collect_type_deps(fn.decl.sig.ret_type, deps)\n    return deps\n\n\ndef find_class_dependencies(cl: ClassIR) -> set[Dependency] | None:\n    \"\"\"Find dependencies from class attribute types.\"\"\"\n    deps: set[Dependency] | None = None\n    for base in cl.mro:\n        for attr_type in base.attributes.values():\n            deps = collect_type_deps(attr_type, deps)\n    return deps\n\n\ndef collect_type_deps(typ: RType, deps: set[Dependency] | None) -> set[Dependency] | None:\n    \"\"\"Collect dependencies from an RType, recursively checking compound types.\"\"\"\n    if typ.dependencies is not None:\n        for dep in typ.dependencies:\n            if deps is None:\n                deps = set()\n            deps.add(dep)\n    if isinstance(typ, RUnion):\n        for item in typ.items:\n            deps = collect_type_deps(item, deps)\n    elif isinstance(typ, RTuple):\n        for item in typ.types:\n            deps = collect_type_deps(item, deps)\n    elif isinstance(typ, RStruct):\n        for item in typ.types:\n            deps = collect_type_deps(item, deps)\n    elif isinstance(typ, RVec):\n        deps = collect_type_deps(typ.item_type, deps)\n    return deps\n"
  },
  {
    "path": "mypyc/analysis/dataflow.py",
    "content": "\"\"\"Data-flow analyses.\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections.abc import Iterable, Iterator, Set as AbstractSet\nfrom typing import Any, Generic, TypeVar\n\nfrom mypyc.ir.ops import (\n    Assign,\n    AssignMulti,\n    BasicBlock,\n    Box,\n    Branch,\n    Call,\n    CallC,\n    Cast,\n    ComparisonOp,\n    ControlOp,\n    DecRef,\n    Extend,\n    Float,\n    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\n    GetElement,\n    GetElementPtr,\n    Goto,\n    IncRef,\n    InitStatic,\n    Integer,\n    IntOp,\n    KeepAlive,\n    LoadAddress,\n    LoadErrorValue,\n    LoadGlobal,\n    LoadLiteral,\n    LoadMem,\n    LoadStatic,\n    MethodCall,\n    Op,\n    OpVisitor,\n    PrimitiveOp,\n    RaiseStandardError,\n    RegisterOp,\n    Return,\n    SetAttr,\n    SetElement,\n    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\n    Undef,\n    Unreachable,\n    Value,\n)\n\n\nclass CFG:\n    \"\"\"Control-flow graph.\n\n    Node 0 is always assumed to be the entry point. There must be a\n    non-empty set of exits.\n    \"\"\"\n\n    def __init__(\n        self,\n        succ: dict[BasicBlock, list[BasicBlock]],\n        pred: dict[BasicBlock, list[BasicBlock]],\n        exits: set[BasicBlock],\n    ) -> None:\n        assert exits\n        self.succ = succ\n        self.pred = pred\n        self.exits = exits\n\n    def __str__(self) -> str:\n        exits = sorted(self.exits, key=lambda e: int(e.label))\n        return f\"exits: {exits}\\nsucc: {self.succ}\\npred: {self.pred}\"\n\n\ndef get_cfg(blocks: list[BasicBlock], *, use_yields: bool = False) -> CFG:\n    \"\"\"Calculate basic block control-flow graph.\n\n    If use_yields is set, then we treat returns inserted by yields as gotos\n    instead of exits.\n    \"\"\"\n    succ_map = {}\n    pred_map: dict[BasicBlock, list[BasicBlock]] = {}\n    exits = set()\n    for block in blocks:\n        assert not any(\n            isinstance(op, ControlOp) for op in block.ops[:-1]\n        ), \"Control-flow ops must be at the end of blocks\"\n\n        if use_yields and isinstance(block.terminator, Return) and block.terminator.yield_target:\n            succ = [block.terminator.yield_target]\n        else:\n            succ = list(block.terminator.targets())\n        if not succ:\n            exits.add(block)\n\n        # Errors can occur anywhere inside a block, which means that\n        # we can't assume that the entire block has executed before\n        # jumping to the error handler. In our CFG construction, we\n        # model this as saying that a block can jump to its error\n        # handler or the error handlers of any of its normal\n        # successors (to represent an error before that next block\n        # completes). This works well for analyses like \"must\n        # defined\", where it implies that registers assigned in a\n        # block may be undefined in its error handler, but is in\n        # general not a precise representation of reality; any\n        # analyses that require more fidelity must wait until after\n        # exception insertion.\n        for error_point in [block] + succ:\n            if error_point.error_handler:\n                succ.append(error_point.error_handler)\n\n        succ_map[block] = succ\n        pred_map[block] = []\n    for prev, nxt in succ_map.items():\n        for label in nxt:\n            pred_map[label].append(prev)\n    return CFG(succ_map, pred_map, exits)\n\n\ndef get_real_target(label: BasicBlock) -> BasicBlock:\n    if len(label.ops) == 1 and isinstance(label.ops[-1], Goto):\n        label = label.ops[-1].label\n    return label\n\n\ndef cleanup_cfg(blocks: list[BasicBlock]) -> None:\n    \"\"\"Cleanup the control flow graph.\n\n    This eliminates obviously dead basic blocks and eliminates blocks that contain\n    nothing but a single jump.\n\n    There is a lot more that could be done.\n    \"\"\"\n    changed = True\n    while changed:\n        # First collapse any jumps to basic block that only contain a goto\n        for block in blocks:\n            for i, tgt in enumerate(block.terminator.targets()):\n                block.terminator.set_target(i, get_real_target(tgt))\n\n        # Then delete any blocks that have no predecessors\n        changed = False\n        cfg = get_cfg(blocks)\n        orig_blocks = blocks.copy()\n        blocks.clear()\n        for i, block in enumerate(orig_blocks):\n            if i == 0 or cfg.pred[block]:\n                blocks.append(block)\n            else:\n                changed = True\n\n\nT = TypeVar(\"T\")\n\nAnalysisDict = dict[tuple[BasicBlock, int], set[T]]\n\n\nclass AnalysisResult(Generic[T]):\n    def __init__(self, before: AnalysisDict[T], after: AnalysisDict[T]) -> None:\n        self.before = before\n        self.after = after\n\n    def __str__(self) -> str:\n        return f\"before: {self.before}\\nafter: {self.after}\\n\"\n\n\nGenAndKill = tuple[AbstractSet[T], AbstractSet[T]]\n\n_EMPTY: tuple[frozenset[Any], frozenset[Any]] = (frozenset(), frozenset())\n\n\nclass BaseAnalysisVisitor(OpVisitor[GenAndKill[T]]):\n    def visit_goto(self, op: Goto) -> GenAndKill[T]:\n        return _EMPTY\n\n    @abstractmethod\n    def visit_register_op(self, op: RegisterOp) -> GenAndKill[T]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_assign(self, op: Assign) -> GenAndKill[T]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[T]:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_set_mem(self, op: SetMem) -> GenAndKill[T]:\n        raise NotImplementedError\n\n    def visit_inc_ref(self, op: IncRef) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_dec_ref(self, op: DecRef) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_call(self, op: Call) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_method_call(self, op: MethodCall) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_load_error_value(self, op: LoadErrorValue) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_load_literal(self, op: LoadLiteral) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_get_attr(self, op: GetAttr) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_set_attr(self, op: SetAttr) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_load_static(self, op: LoadStatic) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_init_static(self, op: InitStatic) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_tuple_get(self, op: TupleGet) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_tuple_set(self, op: TupleSet) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_box(self, op: Box) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_unbox(self, op: Unbox) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_cast(self, op: Cast) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_call_c(self, op: CallC) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_truncate(self, op: Truncate) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_extend(self, op: Extend) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_load_global(self, op: LoadGlobal) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_int_op(self, op: IntOp) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_float_op(self, op: FloatOp) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_float_neg(self, op: FloatNeg) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_comparison_op(self, op: ComparisonOp) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_float_comparison_op(self, op: FloatComparisonOp) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_load_mem(self, op: LoadMem) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_get_element(self, op: GetElement) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_get_element_ptr(self, op: GetElementPtr) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_set_element(self, op: SetElement) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_load_address(self, op: LoadAddress) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_keep_alive(self, op: KeepAlive) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n    def visit_unborrow(self, op: Unborrow) -> GenAndKill[T]:\n        return self.visit_register_op(op)\n\n\nclass DefinedVisitor(BaseAnalysisVisitor[Value]):\n    \"\"\"Visitor for finding defined registers.\n\n    Note that this only deals with registers and not temporaries, on\n    the assumption that we never access temporaries when they might be\n    undefined.\n\n    If strict_errors is True, then we regard any use of LoadErrorValue\n    as making a register undefined. Otherwise we only do if\n    `undefines` is set on the error value.\n\n    This lets us only consider the things we care about during\n    uninitialized variable checking while capturing all possibly\n    undefined things for refcounting.\n    \"\"\"\n\n    def __init__(self, strict_errors: bool = False) -> None:\n        self.strict_errors = strict_errors\n\n    def visit_branch(self, op: Branch) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_return(self, op: Return) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_assign(self, op: Assign) -> GenAndKill[Value]:\n        # Loading an error value may undefine the register.\n        if isinstance(op.src, LoadErrorValue) and (op.src.undefines or self.strict_errors):\n            return set(), {op.dest}\n        else:\n            return {op.dest}, set()\n\n    def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:\n        # Array registers are special and we don't track the definedness of them.\n        return _EMPTY\n\n    def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:\n        return _EMPTY\n\n\ndef analyze_maybe_defined_regs(\n    blocks: list[BasicBlock], cfg: CFG, initial_defined: set[Value]\n) -> AnalysisResult[Value]:\n    \"\"\"Calculate potentially defined registers at each CFG location.\n\n    A register is defined if it has a value along some path from the initial location.\n    \"\"\"\n    return run_analysis(\n        blocks=blocks,\n        cfg=cfg,\n        gen_and_kill=DefinedVisitor(),\n        initial=initial_defined,\n        backward=False,\n        kind=MAYBE_ANALYSIS,\n    )\n\n\ndef analyze_must_defined_regs(\n    blocks: list[BasicBlock],\n    cfg: CFG,\n    initial_defined: set[Value],\n    regs: Iterable[Value],\n    strict_errors: bool = False,\n) -> AnalysisResult[Value]:\n    \"\"\"Calculate always defined registers at each CFG location.\n\n    This analysis can work before exception insertion, since it is a\n    sound assumption that registers defined in a block might not be\n    initialized in its error handler.\n\n    A register is defined if it has a value along all paths from the\n    initial location.\n    \"\"\"\n    return run_analysis(\n        blocks=blocks,\n        cfg=cfg,\n        gen_and_kill=DefinedVisitor(strict_errors=strict_errors),\n        initial=initial_defined,\n        backward=False,\n        kind=MUST_ANALYSIS,\n        universe=set(regs),\n    )\n\n\nclass BorrowedArgumentsVisitor(BaseAnalysisVisitor[Value]):\n    def __init__(self, args: set[Value]) -> None:\n        self.args = args\n\n    def visit_branch(self, op: Branch) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_return(self, op: Return) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_assign(self, op: Assign) -> GenAndKill[Value]:\n        if op.dest in self.args:\n            return set(), {op.dest}\n        return _EMPTY\n\n    def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:\n        return _EMPTY\n\n\ndef analyze_borrowed_arguments(\n    blocks: list[BasicBlock], cfg: CFG, borrowed: set[Value]\n) -> AnalysisResult[Value]:\n    \"\"\"Calculate arguments that can use references borrowed from the caller.\n\n    When assigning to an argument, it no longer is borrowed.\n    \"\"\"\n    return run_analysis(\n        blocks=blocks,\n        cfg=cfg,\n        gen_and_kill=BorrowedArgumentsVisitor(borrowed),\n        initial=borrowed,\n        backward=False,\n        kind=MUST_ANALYSIS,\n        universe=borrowed,\n    )\n\n\nclass UndefinedVisitor(BaseAnalysisVisitor[Value]):\n    def visit_branch(self, op: Branch) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_return(self, op: Return) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:\n        return set(), {op} if not op.is_void else set()\n\n    def visit_assign(self, op: Assign) -> GenAndKill[Value]:\n        return set(), {op.dest}\n\n    def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:\n        return set(), {op.dest}\n\n    def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:\n        return _EMPTY\n\n\ndef non_trivial_sources(op: Op) -> set[Value]:\n    result = set()\n    for source in op.sources():\n        if not isinstance(source, (Integer, Float, Undef)):\n            result.add(source)\n    return result\n\n\nclass LivenessVisitor(BaseAnalysisVisitor[Value]):\n    def visit_branch(self, op: Branch) -> GenAndKill[Value]:\n        return non_trivial_sources(op), set()\n\n    def visit_return(self, op: Return) -> GenAndKill[Value]:\n        if not isinstance(op.value, (Integer, Float)):\n            return {op.value}, set()\n        else:\n            return _EMPTY\n\n    def visit_unreachable(self, op: Unreachable) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_register_op(self, op: RegisterOp) -> GenAndKill[Value]:\n        gen = non_trivial_sources(op)\n        if not op.is_void:\n            return gen, {op}\n        else:\n            return gen, set()\n\n    def visit_assign(self, op: Assign) -> GenAndKill[Value]:\n        return non_trivial_sources(op), {op.dest}\n\n    def visit_assign_multi(self, op: AssignMulti) -> GenAndKill[Value]:\n        return non_trivial_sources(op), {op.dest}\n\n    def visit_set_mem(self, op: SetMem) -> GenAndKill[Value]:\n        return non_trivial_sources(op), set()\n\n    def visit_inc_ref(self, op: IncRef) -> GenAndKill[Value]:\n        return _EMPTY\n\n    def visit_dec_ref(self, op: DecRef) -> GenAndKill[Value]:\n        return _EMPTY\n\n\ndef analyze_live_regs(blocks: list[BasicBlock], cfg: CFG) -> AnalysisResult[Value]:\n    \"\"\"Calculate live registers at each CFG location.\n\n    A register is live at a location if it can be read along some CFG path starting\n    from the location.\n    \"\"\"\n    return run_analysis(\n        blocks=blocks,\n        cfg=cfg,\n        gen_and_kill=LivenessVisitor(),\n        initial=set(),\n        backward=True,\n        kind=MAYBE_ANALYSIS,\n    )\n\n\n# Analysis kinds\nMUST_ANALYSIS = 0\nMAYBE_ANALYSIS = 1\n\n\ndef run_analysis(\n    blocks: list[BasicBlock],\n    cfg: CFG,\n    gen_and_kill: OpVisitor[GenAndKill[T]],\n    initial: set[T],\n    kind: int,\n    backward: bool,\n    universe: set[T] | None = None,\n) -> AnalysisResult[T]:\n    \"\"\"Run a general set-based data flow analysis.\n\n    Args:\n        blocks: All basic blocks\n        cfg: Control-flow graph for the code\n        gen_and_kill: Implementation of gen and kill functions for each op\n        initial: Value of analysis for the entry points (for a forward analysis) or the\n            exit points (for a backward analysis)\n        kind: MUST_ANALYSIS or MAYBE_ANALYSIS\n        backward: If False, the analysis is a forward analysis; it's backward otherwise\n        universe: For a must analysis, the set of all possible values. This is the starting\n            value for the work list algorithm, which will narrow this down until reaching a\n            fixed point. For a maybe analysis the iteration always starts from an empty set\n            and this argument is ignored.\n\n    Return analysis results: (before, after)\n    \"\"\"\n    block_gen = {}\n    block_kill = {}\n\n    # Calculate kill and gen sets for entire basic blocks.\n    for block in blocks:\n        gen: set[T] = set()\n        kill: set[T] = set()\n        ops = block.ops\n        if backward:\n            ops = list(reversed(ops))\n        for op in ops:\n            opgen, opkill = op.accept(gen_and_kill)\n            if opkill:\n                gen -= opkill\n\n            if opgen:\n                gen |= opgen\n                kill -= opgen\n\n            if opkill:\n                kill |= opkill\n\n        block_gen[block] = gen\n        block_kill[block] = kill\n\n    # Set up initial state for worklist algorithm.\n    worklist = list(blocks)\n    if not backward:\n        worklist.reverse()  # Reverse for a small performance improvement\n    workset = set(worklist)\n    before: dict[BasicBlock, set[T]] = {}\n    after: dict[BasicBlock, set[T]] = {}\n    for block in blocks:\n        if kind == MAYBE_ANALYSIS:\n            before[block] = set()\n            after[block] = set()\n        else:\n            assert universe is not None, \"Universe must be defined for a must analysis\"\n            before[block] = set(universe)\n            after[block] = set(universe)\n\n    if backward:\n        pred_map = cfg.succ\n        succ_map = cfg.pred\n    else:\n        pred_map = cfg.pred\n        succ_map = cfg.succ\n\n    # Run work list algorithm to generate in and out sets for each basic block.\n    while worklist:\n        label = worklist.pop()\n        workset.remove(label)\n        if pred_map[label]:\n            new_before: set[T] | None = None\n            for pred in pred_map[label]:\n                if new_before is None:\n                    new_before = set(after[pred])\n                elif kind == MAYBE_ANALYSIS:\n                    new_before |= after[pred]\n                else:\n                    new_before &= after[pred]\n            assert new_before is not None\n        else:\n            new_before = set(initial)\n        before[label] = new_before\n        new_after = (new_before - block_kill[label]) | block_gen[label]\n        if new_after != after[label]:\n            for succ in succ_map[label]:\n                if succ not in workset:\n                    worklist.append(succ)\n                    workset.add(succ)\n        after[label] = new_after\n\n    # Run algorithm for each basic block to generate opcode-level sets.\n    op_before: dict[tuple[BasicBlock, int], set[T]] = {}\n    op_after: dict[tuple[BasicBlock, int], set[T]] = {}\n    for block in blocks:\n        label = block\n        cur = before[label]\n        ops_enum: Iterator[tuple[int, Op]] = enumerate(block.ops)\n        if backward:\n            ops_enum = reversed(list(ops_enum))\n        for idx, op in ops_enum:\n            op_before[label, idx] = cur\n            opgen, opkill = op.accept(gen_and_kill)\n            if opkill:\n                cur = cur - opkill\n            if opgen:\n                cur = cur | opgen\n            op_after[label, idx] = cur\n    if backward:\n        op_after, op_before = op_before, op_after\n\n    return AnalysisResult(op_before, op_after)\n"
  },
  {
    "path": "mypyc/analysis/ircheck.py",
    "content": "\"\"\"Utilities for checking that internal ir is valid and consistent.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncIR\nfrom mypyc.ir.ops import (\n    Assign,\n    AssignMulti,\n    BaseAssign,\n    BasicBlock,\n    Box,\n    Branch,\n    Call,\n    CallC,\n    Cast,\n    ComparisonOp,\n    ControlOp,\n    DecRef,\n    Extend,\n    Float,\n    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\n    GetElement,\n    GetElementPtr,\n    Goto,\n    IncRef,\n    InitStatic,\n    Integer,\n    IntOp,\n    KeepAlive,\n    LoadAddress,\n    LoadErrorValue,\n    LoadGlobal,\n    LoadLiteral,\n    LoadMem,\n    LoadStatic,\n    MethodCall,\n    Op,\n    OpVisitor,\n    PrimitiveOp,\n    RaiseStandardError,\n    Register,\n    Return,\n    SetAttr,\n    SetElement,\n    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\n    Undef,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.pprint import format_func\nfrom mypyc.ir.rtypes import (\n    KNOWN_NATIVE_TYPES,\n    RArray,\n    RInstance,\n    RPrimitive,\n    RType,\n    RUnion,\n    RVec,\n    bytes_rprimitive,\n    dict_rprimitive,\n    int_rprimitive,\n    is_c_py_ssize_t_rprimitive,\n    is_fixed_width_rtype,\n    is_float_rprimitive,\n    is_object_rprimitive,\n    is_pointer_rprimitive,\n    list_rprimitive,\n    pointer_rprimitive,\n    range_rprimitive,\n    set_rprimitive,\n    str_rprimitive,\n    tuple_rprimitive,\n)\n\n\nclass FnError:\n    def __init__(self, source: Op | BasicBlock, desc: str) -> None:\n        self.source = source\n        self.desc = desc\n\n    def __eq__(self, other: object) -> bool:\n        return (\n            isinstance(other, FnError) and self.source == other.source and self.desc == other.desc\n        )\n\n    def __repr__(self) -> str:\n        return f\"FnError(source={self.source}, desc={self.desc})\"\n\n\ndef check_func_ir(fn: FuncIR) -> list[FnError]:\n    \"\"\"Applies validations to a given function ir and returns a list of errors found.\"\"\"\n    errors = []\n\n    op_set = set()\n\n    for block in fn.blocks:\n        if not block.terminated:\n            errors.append(\n                FnError(source=block.ops[-1] if block.ops else block, desc=\"Block not terminated\")\n            )\n        for op in block.ops[:-1]:\n            if isinstance(op, ControlOp):\n                errors.append(FnError(source=op, desc=\"Block has operations after control op\"))\n\n            if op in op_set:\n                errors.append(FnError(source=op, desc=\"Func has a duplicate op\"))\n            op_set.add(op)\n\n    errors.extend(check_op_sources_valid(fn))\n    if errors:\n        return errors\n\n    op_checker = OpChecker(fn)\n    for block in fn.blocks:\n        for op in block.ops:\n            op.accept(op_checker)\n\n    return op_checker.errors\n\n\nclass IrCheckException(Exception):\n    pass\n\n\ndef assert_func_ir_valid(fn: FuncIR) -> None:\n    errors = check_func_ir(fn)\n    if errors:\n        raise IrCheckException(\n            \"Internal error: Generated invalid IR: \\n\"\n            + \"\\n\".join(format_func(fn, [(e.source, e.desc) for e in errors]))\n        )\n\n\ndef check_op_sources_valid(fn: FuncIR) -> list[FnError]:\n    errors = []\n    valid_ops: set[Op] = set()\n    valid_registers: set[Register] = set()\n\n    for block in fn.blocks:\n        valid_ops.update(block.ops)\n\n        for op in block.ops:\n            if isinstance(op, BaseAssign):\n                valid_registers.add(op.dest)\n            elif isinstance(op, LoadAddress) and isinstance(op.src, Register):\n                valid_registers.add(op.src)\n\n    valid_registers.update(fn.arg_regs)\n\n    for block in fn.blocks:\n        for op in block.ops:\n            for source in op.sources():\n                if isinstance(source, (Integer, Float, Undef)):\n                    pass\n                elif isinstance(source, Op):\n                    if source not in valid_ops:\n                        errors.append(\n                            FnError(\n                                source=op,\n                                desc=f\"Invalid op reference to op of type {type(source).__name__}\",\n                            )\n                        )\n                elif isinstance(source, Register):\n                    if source not in valid_registers:\n                        errors.append(\n                            FnError(\n                                source=op, desc=f\"Invalid op reference to register {source.name!r}\"\n                            )\n                        )\n\n    return errors\n\n\ndisjoint_types = {\n    int_rprimitive.name,\n    bytes_rprimitive.name,\n    str_rprimitive.name,\n    dict_rprimitive.name,\n    list_rprimitive.name,\n    set_rprimitive.name,\n    tuple_rprimitive.name,\n    range_rprimitive.name,\n} | set(KNOWN_NATIVE_TYPES)\n\n\ndef can_coerce_to(src: RType, dest: RType) -> bool:\n    \"\"\"Check if src can be assigned to dest_rtype.\n\n    Currently okay to have false positives.\n    \"\"\"\n    if isinstance(dest, RUnion):\n        return any(can_coerce_to(src, d) for d in dest.items)\n\n    if isinstance(dest, RPrimitive):\n        if isinstance(src, RPrimitive):\n            # If either src or dest is a disjoint type, then they must both be.\n            if src.name in disjoint_types and dest.name in disjoint_types:\n                return src.name == dest.name\n            return src.size == dest.size\n        if isinstance(src, (RInstance, RVec)):\n            return is_object_rprimitive(dest)\n        if isinstance(src, RUnion):\n            # IR doesn't have the ability to narrow unions based on\n            # control flow, so cannot be a strict all() here.\n            return any(can_coerce_to(s, dest) for s in src.items)\n        return False\n\n    return True\n\n\ndef is_valid_ptr_displacement_type(rtype: RType) -> bool:\n    \"\"\"Check if rtype is a valid displacement type for pointer arithmetic.\"\"\"\n    if not (is_fixed_width_rtype(rtype) or is_c_py_ssize_t_rprimitive(rtype)):\n        return False\n    assert isinstance(rtype, RPrimitive)\n    return rtype.size == pointer_rprimitive.size\n\n\ndef is_pointer_arithmetic(op: IntOp) -> bool:\n    \"\"\"Check if op is add/subtract targeting pointer_rprimitive and integer of the same size.\"\"\"\n    if op.op not in (IntOp.ADD, IntOp.SUB):\n        return False\n    if not is_pointer_rprimitive(op.type):\n        return False\n    left = op.lhs.type\n    right = op.rhs.type\n    if is_pointer_rprimitive(left):\n        return is_valid_ptr_displacement_type(right)\n    if is_pointer_rprimitive(right):\n        return is_valid_ptr_displacement_type(left)\n    return False\n\n\nclass OpChecker(OpVisitor[None]):\n    def __init__(self, parent_fn: FuncIR) -> None:\n        self.parent_fn = parent_fn\n        self.errors: list[FnError] = []\n\n    def fail(self, source: Op, desc: str) -> None:\n        self.errors.append(FnError(source=source, desc=desc))\n\n    def check_control_op_targets(self, op: ControlOp) -> None:\n        for target in op.targets():\n            if target not in self.parent_fn.blocks:\n                self.fail(source=op, desc=f\"Invalid control operation target: {target.label}\")\n\n    def check_type_coercion(self, op: Op, src: RType, dest: RType) -> None:\n        if not can_coerce_to(src, dest):\n            self.fail(\n                source=op, desc=f\"Cannot coerce source type {src.name} to dest type {dest.name}\"\n            )\n\n    def check_compatibility(self, op: Op, t: RType, s: RType) -> None:\n        if not can_coerce_to(t, s) or not can_coerce_to(s, t):\n            self.fail(source=op, desc=f\"{t.name} and {s.name} are not compatible\")\n\n    def expect_float(self, op: Op, v: Value) -> None:\n        if not is_float_rprimitive(v.type):\n            self.fail(op, f\"Float expected (actual type is {v.type})\")\n\n    def expect_non_float(self, op: Op, v: Value) -> None:\n        if is_float_rprimitive(v.type):\n            self.fail(op, \"Float not expected\")\n\n    def expect_primitive_type(self, op: Op, v: Value) -> None:\n        if not isinstance(v.type, RPrimitive):\n            self.fail(op, f\"RPrimitive expected, got {type(v.type).__name__}\")\n\n    def visit_goto(self, op: Goto) -> None:\n        self.check_control_op_targets(op)\n\n    def visit_branch(self, op: Branch) -> None:\n        self.check_control_op_targets(op)\n\n    def visit_return(self, op: Return) -> None:\n        self.check_type_coercion(op, op.value.type, self.parent_fn.decl.sig.ret_type)\n\n    def visit_unreachable(self, op: Unreachable) -> None:\n        # Unreachables are checked at a higher level since validation\n        # requires access to the entire basic block.\n        pass\n\n    def visit_assign(self, op: Assign) -> None:\n        self.check_type_coercion(op, op.src.type, op.dest.type)\n\n    def visit_assign_multi(self, op: AssignMulti) -> None:\n        for src in op.src:\n            assert isinstance(op.dest.type, RArray)\n            self.check_type_coercion(op, src.type, op.dest.type.item_type)\n\n    def visit_load_error_value(self, op: LoadErrorValue) -> None:\n        # Currently it is assumed that all types have an error value.\n        # Once this is fixed we can validate that the rtype here actually\n        # has an error value.\n        pass\n\n    def check_tuple_items_valid_literals(self, op: LoadLiteral, t: tuple[object, ...]) -> None:\n        for x in t:\n            if x is not None and not isinstance(x, (str, bytes, bool, int, float, complex, tuple)):\n                self.fail(op, f\"Invalid type for item of tuple literal: {type(x)})\")\n            if isinstance(x, tuple):\n                self.check_tuple_items_valid_literals(op, x)\n\n    def check_frozenset_items_valid_literals(self, op: LoadLiteral, s: frozenset[object]) -> None:\n        for x in s:\n            if x is None or isinstance(x, (str, bytes, bool, int, float, complex)):\n                pass\n            elif isinstance(x, tuple):\n                self.check_tuple_items_valid_literals(op, x)\n            else:\n                self.fail(op, f\"Invalid type for item of frozenset literal: {type(x)})\")\n\n    def visit_load_literal(self, op: LoadLiteral) -> None:\n        expected_type = None\n        if op.value is None:\n            expected_type = \"builtins.object\"\n        elif isinstance(op.value, int):\n            expected_type = \"builtins.int\"\n        elif isinstance(op.value, str):\n            expected_type = \"builtins.str\"\n        elif isinstance(op.value, bytes):\n            expected_type = \"builtins.bytes\"\n        elif isinstance(op.value, float):\n            expected_type = \"builtins.float\"\n        elif isinstance(op.value, complex):\n            expected_type = \"builtins.object\"\n        elif isinstance(op.value, tuple):\n            expected_type = \"builtins.tuple\"\n            self.check_tuple_items_valid_literals(op, op.value)\n        elif isinstance(op.value, frozenset):\n            # There's no frozenset_rprimitive type since it'd be pretty useless so we just pretend\n            # it's a set (when it's really a frozenset).\n            expected_type = \"builtins.set\"\n            self.check_frozenset_items_valid_literals(op, op.value)\n\n        assert expected_type is not None, \"Missed a case for LoadLiteral check\"\n\n        if op.type.name not in [expected_type, \"builtins.object\"]:\n            self.fail(\n                op,\n                f\"Invalid literal value for type: value has \"\n                f\"type {expected_type}, but op has type {op.type.name}\",\n            )\n\n    def visit_get_attr(self, op: GetAttr) -> None:\n        # Nothing to do.\n        pass\n\n    def visit_set_attr(self, op: SetAttr) -> None:\n        # Nothing to do.\n        pass\n\n    # Static operations cannot be checked at the function level.\n    def visit_load_static(self, op: LoadStatic) -> None:\n        pass\n\n    def visit_init_static(self, op: InitStatic) -> None:\n        pass\n\n    def visit_tuple_get(self, op: TupleGet) -> None:\n        # Nothing to do.\n        pass\n\n    def visit_tuple_set(self, op: TupleSet) -> None:\n        # Nothing to do.\n        pass\n\n    def visit_inc_ref(self, op: IncRef) -> None:\n        # Nothing to do.\n        pass\n\n    def visit_dec_ref(self, op: DecRef) -> None:\n        # Nothing to do.\n        pass\n\n    def visit_call(self, op: Call) -> None:\n        # Length is checked in constructor, and return type is set\n        # in a way that can't be incorrect\n        for arg_value, arg_runtime in zip(op.args, op.fn.sig.args):\n            self.check_type_coercion(op, arg_value.type, arg_runtime.type)\n\n    def visit_method_call(self, op: MethodCall) -> None:\n        # Similar to above, but we must look up method first.\n        method_decl = op.receiver_type.class_ir.method_decl(op.method)\n        if method_decl.kind == FUNC_STATICMETHOD:\n            decl_index = 0\n        else:\n            decl_index = 1\n\n        if len(op.args) + decl_index != len(method_decl.sig.args):\n            self.fail(op, \"Incorrect number of args for method call.\")\n\n        # Skip the receiver argument (self)\n        for arg_value, arg_runtime in zip(op.args, method_decl.sig.args[decl_index:]):\n            self.check_type_coercion(op, arg_value.type, arg_runtime.type)\n\n    def visit_cast(self, op: Cast) -> None:\n        pass\n\n    def visit_box(self, op: Box) -> None:\n        pass\n\n    def visit_unbox(self, op: Unbox) -> None:\n        pass\n\n    def visit_raise_standard_error(self, op: RaiseStandardError) -> None:\n        pass\n\n    def visit_call_c(self, op: CallC) -> None:\n        pass\n\n    def visit_primitive_op(self, op: PrimitiveOp) -> None:\n        pass\n\n    def visit_truncate(self, op: Truncate) -> None:\n        pass\n\n    def visit_extend(self, op: Extend) -> None:\n        pass\n\n    def visit_load_global(self, op: LoadGlobal) -> None:\n        pass\n\n    def visit_int_op(self, op: IntOp) -> None:\n        self.expect_primitive_type(op, op.lhs)\n        self.expect_primitive_type(op, op.rhs)\n        self.expect_non_float(op, op.lhs)\n        self.expect_non_float(op, op.rhs)\n        left = op.lhs.type\n        right = op.rhs.type\n        op_str = op.op_str[op.op]\n        if (\n            isinstance(left, RPrimitive)\n            and isinstance(right, RPrimitive)\n            and left.is_signed != right.is_signed\n            and (\n                op_str in (\"+\", \"-\", \"*\", \"/\", \"%\")\n                or (op_str not in (\"<<\", \">>\") and left.size != right.size)\n            )\n            and not is_pointer_arithmetic(op)\n        ):\n            self.fail(op, f\"Operand types have incompatible signs: {left}, {right}\")\n\n    def visit_comparison_op(self, op: ComparisonOp) -> None:\n        self.check_compatibility(op, op.lhs.type, op.rhs.type)\n        self.expect_non_float(op, op.lhs)\n        self.expect_non_float(op, op.rhs)\n        left = op.lhs.type\n        right = op.rhs.type\n        if (\n            isinstance(left, RPrimitive)\n            and isinstance(right, RPrimitive)\n            and left.is_signed != right.is_signed\n        ):\n            self.fail(op, f\"Operand types have incompatible signs: {left}, {right}\")\n\n    def visit_float_op(self, op: FloatOp) -> None:\n        self.expect_float(op, op.lhs)\n        self.expect_float(op, op.rhs)\n\n    def visit_float_neg(self, op: FloatNeg) -> None:\n        self.expect_float(op, op.src)\n\n    def visit_float_comparison_op(self, op: FloatComparisonOp) -> None:\n        self.expect_float(op, op.lhs)\n        self.expect_float(op, op.rhs)\n\n    def visit_load_mem(self, op: LoadMem) -> None:\n        pass\n\n    def visit_set_mem(self, op: SetMem) -> None:\n        pass\n\n    def visit_get_element(self, op: GetElement) -> None:\n        pass\n\n    def visit_get_element_ptr(self, op: GetElementPtr) -> None:\n        pass\n\n    def visit_set_element(self, op: SetElement) -> None:\n        pass\n\n    def visit_load_address(self, op: LoadAddress) -> None:\n        pass\n\n    def visit_keep_alive(self, op: KeepAlive) -> None:\n        pass\n\n    def visit_unborrow(self, op: Unborrow) -> None:\n        pass\n"
  },
  {
    "path": "mypyc/analysis/selfleaks.py",
    "content": "from __future__ import annotations\n\nfrom mypyc.analysis.dataflow import (\n    CFG,\n    MAYBE_ANALYSIS,\n    AnalysisResult,\n    GenAndKill as _DataflowGenAndKill,\n    run_analysis,\n)\nfrom mypyc.ir.ops import (\n    Assign,\n    AssignMulti,\n    BasicBlock,\n    Box,\n    Branch,\n    Call,\n    CallC,\n    Cast,\n    ComparisonOp,\n    DecRef,\n    Extend,\n    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\n    GetElement,\n    GetElementPtr,\n    Goto,\n    IncRef,\n    InitStatic,\n    IntOp,\n    KeepAlive,\n    LoadAddress,\n    LoadErrorValue,\n    LoadGlobal,\n    LoadLiteral,\n    LoadMem,\n    LoadStatic,\n    MethodCall,\n    OpVisitor,\n    PrimitiveOp,\n    RaiseStandardError,\n    Register,\n    RegisterOp,\n    Return,\n    SetAttr,\n    SetElement,\n    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\n    Unreachable,\n)\nfrom mypyc.ir.rtypes import RInstance\n\nGenAndKill = _DataflowGenAndKill[None]\n\nCLEAN: GenAndKill = (set(), set())\nDIRTY: GenAndKill = ({None}, {None})\n\n\nclass SelfLeakedVisitor(OpVisitor[GenAndKill]):\n    \"\"\"Analyze whether 'self' may be seen by arbitrary code in '__init__'.\n\n    More formally, the set is not empty if along some path from IR entry point\n    arbitrary code could have been executed that has access to 'self'.\n\n    (We don't consider access via 'gc.get_objects()'.)\n    \"\"\"\n\n    def __init__(self, self_reg: Register) -> None:\n        self.self_reg = self_reg\n\n    def visit_goto(self, op: Goto) -> GenAndKill:\n        return CLEAN\n\n    def visit_branch(self, op: Branch) -> GenAndKill:\n        return CLEAN\n\n    def visit_return(self, op: Return) -> GenAndKill:\n        # Consider all exits from the function 'dirty' since they implicitly\n        # cause 'self' to be returned.\n        return DIRTY\n\n    def visit_unreachable(self, op: Unreachable) -> GenAndKill:\n        return CLEAN\n\n    def visit_assign(self, op: Assign) -> GenAndKill:\n        if op.src is self.self_reg or op.dest is self.self_reg:\n            return DIRTY\n        return CLEAN\n\n    def visit_assign_multi(self, op: AssignMulti) -> GenAndKill:\n        return CLEAN\n\n    def visit_set_mem(self, op: SetMem) -> GenAndKill:\n        return CLEAN\n\n    def visit_inc_ref(self, op: IncRef) -> GenAndKill:\n        return CLEAN\n\n    def visit_dec_ref(self, op: DecRef) -> GenAndKill:\n        return CLEAN\n\n    def visit_call(self, op: Call) -> GenAndKill:\n        fn = op.fn\n        if fn.class_name and fn.name == \"__init__\":\n            self_type = op.fn.sig.args[0].type\n            assert isinstance(self_type, RInstance), self_type\n            cl = self_type.class_ir\n            if not cl.init_self_leak:\n                return CLEAN\n        return self.check_register_op(op)\n\n    def visit_method_call(self, op: MethodCall) -> GenAndKill:\n        return self.check_register_op(op)\n\n    def visit_load_error_value(self, op: LoadErrorValue) -> GenAndKill:\n        return CLEAN\n\n    def visit_load_literal(self, op: LoadLiteral) -> GenAndKill:\n        return CLEAN\n\n    def visit_get_attr(self, op: GetAttr) -> GenAndKill:\n        cl = op.class_type.class_ir\n        if cl.get_method(op.attr):\n            # Property -- calls a function\n            return self.check_register_op(op)\n        return CLEAN\n\n    def visit_set_attr(self, op: SetAttr) -> GenAndKill:\n        cl = op.class_type.class_ir\n        if cl.get_method(op.attr):\n            # Property - calls a function\n            return self.check_register_op(op)\n        return CLEAN\n\n    def visit_load_static(self, op: LoadStatic) -> GenAndKill:\n        return CLEAN\n\n    def visit_init_static(self, op: InitStatic) -> GenAndKill:\n        return self.check_register_op(op)\n\n    def visit_tuple_get(self, op: TupleGet) -> GenAndKill:\n        return CLEAN\n\n    def visit_tuple_set(self, op: TupleSet) -> GenAndKill:\n        return self.check_register_op(op)\n\n    def visit_box(self, op: Box) -> GenAndKill:\n        return self.check_register_op(op)\n\n    def visit_unbox(self, op: Unbox) -> GenAndKill:\n        return self.check_register_op(op)\n\n    def visit_cast(self, op: Cast) -> GenAndKill:\n        return self.check_register_op(op)\n\n    def visit_raise_standard_error(self, op: RaiseStandardError) -> GenAndKill:\n        return CLEAN\n\n    def visit_call_c(self, op: CallC) -> GenAndKill:\n        return self.check_register_op(op)\n\n    def visit_primitive_op(self, op: PrimitiveOp) -> GenAndKill:\n        return self.check_register_op(op)\n\n    def visit_truncate(self, op: Truncate) -> GenAndKill:\n        return CLEAN\n\n    def visit_extend(self, op: Extend) -> GenAndKill:\n        return CLEAN\n\n    def visit_load_global(self, op: LoadGlobal) -> GenAndKill:\n        return CLEAN\n\n    def visit_int_op(self, op: IntOp) -> GenAndKill:\n        return CLEAN\n\n    def visit_comparison_op(self, op: ComparisonOp) -> GenAndKill:\n        return CLEAN\n\n    def visit_float_op(self, op: FloatOp) -> GenAndKill:\n        return CLEAN\n\n    def visit_float_neg(self, op: FloatNeg) -> GenAndKill:\n        return CLEAN\n\n    def visit_float_comparison_op(self, op: FloatComparisonOp) -> GenAndKill:\n        return CLEAN\n\n    def visit_load_mem(self, op: LoadMem) -> GenAndKill:\n        return CLEAN\n\n    def visit_get_element(self, op: GetElement) -> GenAndKill:\n        return CLEAN\n\n    def visit_get_element_ptr(self, op: GetElementPtr) -> GenAndKill:\n        return CLEAN\n\n    def visit_set_element(self, op: SetElement) -> GenAndKill:\n        return CLEAN\n\n    def visit_load_address(self, op: LoadAddress) -> GenAndKill:\n        return CLEAN\n\n    def visit_keep_alive(self, op: KeepAlive) -> GenAndKill:\n        return CLEAN\n\n    def visit_unborrow(self, op: Unborrow) -> GenAndKill:\n        return CLEAN\n\n    def check_register_op(self, op: RegisterOp) -> GenAndKill:\n        if any(src is self.self_reg for src in op.sources()):\n            return DIRTY\n        return CLEAN\n\n\ndef analyze_self_leaks(\n    blocks: list[BasicBlock], self_reg: Register, cfg: CFG\n) -> AnalysisResult[None]:\n    return run_analysis(\n        blocks=blocks,\n        cfg=cfg,\n        gen_and_kill=SelfLeakedVisitor(self_reg),\n        initial=set(),\n        backward=False,\n        kind=MAYBE_ANALYSIS,\n    )\n"
  },
  {
    "path": "mypyc/annotate.py",
    "content": "\"\"\"Generate source code formatted as HTML, with bottlenecks annotated and highlighted.\n\nVarious heuristics are used to detect common issues that cause slower than\nexpected performance.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\nimport sys\nfrom html import escape\nfrom typing import Final\n\nfrom mypy.build import BuildResult\nfrom mypy.nodes import (\n    AssignmentStmt,\n    CallExpr,\n    ClassDef,\n    Decorator,\n    DictionaryComprehension,\n    Expression,\n    ForStmt,\n    FuncDef,\n    GeneratorExpr,\n    IndexExpr,\n    LambdaExpr,\n    MemberExpr,\n    MypyFile,\n    NamedTupleExpr,\n    NameExpr,\n    NewTypeExpr,\n    Node,\n    OpExpr,\n    RefExpr,\n    TupleExpr,\n    TypedDictExpr,\n    TypeInfo,\n    TypeVarExpr,\n    Var,\n    WithStmt,\n)\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.types import AnyType, Instance, ProperType, Type, TypeOfAny, get_proper_type\nfrom mypy.util import FancyFormatter\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.module_ir import ModuleIR\nfrom mypyc.ir.ops import CallC, LoadLiteral, LoadStatic, Value\nfrom mypyc.irbuild.mapper import Mapper\n\n\nclass Annotation:\n    \"\"\"HTML annotation for compiled source code\"\"\"\n\n    def __init__(self, message: str, priority: int = 1) -> None:\n        # Message as HTML that describes an issue and/or how to fix it.\n        # Multiple messages on a line may be concatenated.\n        self.message = message\n        # If multiple annotations are generated for a single line, only report\n        # the highest-priority ones. Some use cases generate multiple annotations,\n        # and this can be used to reduce verbosity by hiding the lower-priority\n        # ones.\n        self.priority = priority\n\n\nop_hints: Final = {\n    \"PyNumber_Add\": Annotation('Generic \"+\" operation.'),\n    \"PyNumber_Subtract\": Annotation('Generic \"-\" operation.'),\n    \"PyNumber_Multiply\": Annotation('Generic \"*\" operation.'),\n    \"PyNumber_TrueDivide\": Annotation('Generic \"/\" operation.'),\n    \"PyNumber_FloorDivide\": Annotation('Generic \"//\" operation.'),\n    \"PyNumber_Positive\": Annotation('Generic unary \"+\" operation.'),\n    \"PyNumber_Negative\": Annotation('Generic unary \"-\" operation.'),\n    \"PyNumber_And\": Annotation('Generic \"&\" operation.'),\n    \"PyNumber_Or\": Annotation('Generic \"|\" operation.'),\n    \"PyNumber_Xor\": Annotation('Generic \"^\" operation.'),\n    \"PyNumber_Lshift\": Annotation('Generic \"<<\" operation.'),\n    \"PyNumber_Rshift\": Annotation('Generic \">>\" operation.'),\n    \"PyNumber_Invert\": Annotation('Generic \"~\" operation.'),\n    \"PyObject_Call\": Annotation(\"Generic call operation.\"),\n    \"PyObject_CallObject\": Annotation(\"Generic call operation.\"),\n    \"PyObject_RichCompare\": Annotation(\"Generic comparison operation.\"),\n    \"PyObject_GetItem\": Annotation(\"Generic indexing operation.\"),\n    \"PyObject_SetItem\": Annotation(\"Generic indexed assignment.\"),\n}\n\nstdlib_hints: Final = {\n    \"functools.partial\": Annotation(\n        '\"functools.partial\" is inefficient in compiled code.', priority=3\n    ),\n    \"itertools.chain\": Annotation(\n        '\"itertools.chain\" is inefficient in compiled code (hint: replace with for loops).',\n        priority=3,\n    ),\n    \"itertools.groupby\": Annotation(\n        '\"itertools.groupby\" is inefficient in compiled code.', priority=3\n    ),\n    \"itertools.islice\": Annotation(\n        '\"itertools.islice\" is inefficient in compiled code (hint: replace with for loop over index range).',\n        priority=3,\n    ),\n    \"copy.deepcopy\": Annotation(\n        '\"copy.deepcopy\" tends to be slow. Make a shallow copy if possible.', priority=2\n    ),\n}\n\nCSS = \"\"\"\\\n.collapsible {\n    cursor: pointer;\n}\n\n.content {\n    display: block;\n    margin-top: 10px;\n    margin-bottom: 10px;\n}\n\n.hint {\n    display: inline;\n    border: 1px solid #ccc;\n    padding: 5px;\n}\n\"\"\"\n\nJS = \"\"\"\\\ndocument.querySelectorAll('.collapsible').forEach(function(collapsible) {\n    collapsible.addEventListener('click', function() {\n        const content = this.nextElementSibling;\n        if (content.style.display === 'none') {\n            content.style.display = 'block';\n        } else {\n            content.style.display = 'none';\n        }\n    });\n});\n\"\"\"\n\n\nclass AnnotatedSource:\n    \"\"\"Annotations for a single compiled source file.\"\"\"\n\n    def __init__(self, path: str, annotations: dict[int, list[Annotation]]) -> None:\n        self.path = path\n        self.annotations = annotations\n\n\ndef generate_annotated_html(\n    html_fnam: str, result: BuildResult, modules: dict[str, ModuleIR], mapper: Mapper\n) -> None:\n    annotations = []\n    for mod, mod_ir in modules.items():\n        path = result.graph[mod].path\n        tree = result.graph[mod].tree\n        assert tree is not None\n        annotations.append(\n            generate_annotations(path or \"<source>\", tree, mod_ir, result.types, mapper)\n        )\n    html = generate_html_report(annotations)\n    with open(html_fnam, \"w\") as f:\n        f.write(html)\n\n    formatter = FancyFormatter(sys.stdout, sys.stderr, False)\n    formatted = formatter.style(os.path.abspath(html_fnam), \"none\", underline=True, bold=True)\n    print(f\"\\nWrote {formatted} -- open in browser to view\\n\")\n\n\ndef generate_annotations(\n    path: str, tree: MypyFile, ir: ModuleIR, type_map: dict[Expression, Type], mapper: Mapper\n) -> AnnotatedSource:\n    anns = {}\n    for func_ir in ir.functions:\n        anns.update(function_annotations(func_ir, tree))\n    visitor = ASTAnnotateVisitor(type_map, mapper)\n    for defn in tree.defs:\n        defn.accept(visitor)\n    anns.update(visitor.anns)\n    for line in visitor.ignored_lines:\n        if line in anns:\n            del anns[line]\n    return AnnotatedSource(path, anns)\n\n\ndef function_annotations(func_ir: FuncIR, tree: MypyFile) -> dict[int, list[Annotation]]:\n    \"\"\"Generate annotations based on mypyc IR.\"\"\"\n    # TODO: check if func_ir.line is -1\n    anns: dict[int, list[Annotation]] = {}\n    for block in func_ir.blocks:\n        for op in block.ops:\n            if isinstance(op, CallC):\n                name = op.function_name\n                ann: str | Annotation | None = None\n                if name == \"CPyObject_GetAttr\":\n                    attr_name = get_str_literal(op.args[1])\n                    if attr_name in (\"__prepare__\", \"GeneratorExit\", \"StopIteration\"):\n                        # These attributes are internal to mypyc/CPython, and/or accessed\n                        # implicitly in generated code. The user has little control over\n                        # them.\n                        ann = None\n                    elif attr_name:\n                        ann = f'Get non-native attribute \"{attr_name}\".'\n                    else:\n                        ann = \"Dynamic attribute lookup.\"\n                elif name == \"PyObject_SetAttr\":\n                    attr_name = get_str_literal(op.args[1])\n                    if attr_name == \"__mypyc_attrs__\":\n                        # This is set implicitly and can't be avoided.\n                        ann = None\n                    elif attr_name:\n                        ann = f'Set non-native attribute \"{attr_name}\".'\n                    else:\n                        ann = \"Dynamic attribute set.\"\n                elif name == \"PyObject_VectorcallMethod\":\n                    method_name = get_str_literal(op.args[0])\n                    if method_name:\n                        ann = f'Call non-native method \"{method_name}\" (it may be defined in a non-native class, or decorated).'\n                    else:\n                        ann = \"Dynamic method call.\"\n                elif name in op_hints:\n                    ann = op_hints[name]\n                elif name in (\"CPyDict_GetItem\", \"CPyDict_SetItem\"):\n                    if (\n                        isinstance(op.args[0], LoadStatic)\n                        and isinstance(op.args[1], LoadLiteral)\n                        and func_ir.name != \"__top_level__\"\n                    ):\n                        load = op.args[0]\n                        name = str(op.args[1].value)\n                        sym = tree.names.get(name)\n                        if (\n                            sym\n                            and sym.node\n                            and load.namespace == \"static\"\n                            and load.identifier == \"globals\"\n                        ):\n                            if sym.node.fullname in stdlib_hints:\n                                ann = stdlib_hints[sym.node.fullname]\n                            elif isinstance(sym.node, Var):\n                                ann = (\n                                    f'Access global \"{name}\" through namespace '\n                                    + \"dictionary (hint: access is faster if you can make it Final).\"\n                                )\n                            else:\n                                ann = f'Access \"{name}\" through global namespace dictionary.'\n                if ann:\n                    if isinstance(ann, str):\n                        ann = Annotation(ann)\n                    anns.setdefault(op.line, []).append(ann)\n    return anns\n\n\nclass ASTAnnotateVisitor(TraverserVisitor):\n    \"\"\"Generate annotations from mypy AST and inferred types.\"\"\"\n\n    def __init__(self, type_map: dict[Expression, Type], mapper: Mapper) -> None:\n        self.anns: dict[int, list[Annotation]] = {}\n        self.ignored_lines: set[int] = set()\n        self.func_depth = 0\n        self.type_map = type_map\n        self.mapper = mapper\n\n    def visit_func_def(self, o: FuncDef, /) -> None:\n        if self.func_depth > 0:\n            self.annotate(\n                o,\n                \"A nested function object is allocated each time statement is executed. \"\n                + \"A module-level function would be faster.\",\n            )\n        self.func_depth += 1\n        super().visit_func_def(o)\n        self.func_depth -= 1\n\n    def visit_for_stmt(self, o: ForStmt, /) -> None:\n        self.check_iteration([o.expr], \"For loop\")\n        super().visit_for_stmt(o)\n\n    def visit_dictionary_comprehension(self, o: DictionaryComprehension, /) -> None:\n        self.check_iteration(o.sequences, \"Comprehension\")\n        super().visit_dictionary_comprehension(o)\n\n    def visit_generator_expr(self, o: GeneratorExpr, /) -> None:\n        self.check_iteration(o.sequences, \"Comprehension or generator\")\n        super().visit_generator_expr(o)\n\n    def check_iteration(self, expressions: list[Expression], kind: str) -> None:\n        for expr in expressions:\n            typ = self.get_type(expr)\n            if isinstance(typ, AnyType):\n                self.annotate(expr, f'{kind} uses generic operations (iterable has type \"Any\").')\n            elif isinstance(typ, Instance) and typ.type.fullname in (\n                \"typing.Iterable\",\n                \"typing.Iterator\",\n                \"typing.Sequence\",\n                \"typing.MutableSequence\",\n            ):\n                self.annotate(\n                    expr,\n                    f'{kind} uses generic operations (iterable has the abstract type \"{typ.type.fullname}\").',\n                )\n\n    def visit_class_def(self, o: ClassDef, /) -> None:\n        super().visit_class_def(o)\n        if self.func_depth == 0:\n            # Don't complain about base classes at top level\n            for base in o.base_type_exprs:\n                self.ignored_lines.add(base.line)\n\n            for s in o.defs.body:\n                if isinstance(s, AssignmentStmt):\n                    # Don't complain about attribute initializers\n                    self.ignored_lines.add(s.line)\n                elif isinstance(s, Decorator):\n                    # Don't complain about decorator definitions that generate some\n                    # dynamic operations. This is a bit heavy-handed.\n                    self.ignored_lines.add(s.func.line)\n\n    def visit_with_stmt(self, o: WithStmt, /) -> None:\n        for expr in o.expr:\n            if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr):\n                node = expr.callee.node\n                if isinstance(node, Decorator):\n                    if any(\n                        isinstance(d, RefExpr)\n                        and d.node\n                        and d.node.fullname == \"contextlib.contextmanager\"\n                        for d in node.decorators\n                    ):\n                        self.annotate(\n                            expr,\n                            f'\"{node.name}\" uses @contextmanager, which is slow '\n                            + \"in compiled code. Use a native class with \"\n                            + '\"__enter__\" and \"__exit__\" methods instead.',\n                            priority=3,\n                        )\n        super().visit_with_stmt(o)\n\n    def visit_assignment_stmt(self, o: AssignmentStmt, /) -> None:\n        special_form = False\n        if self.func_depth == 0:\n            analyzed: Expression | None = o.rvalue\n            if isinstance(o.rvalue, (CallExpr, IndexExpr, OpExpr)):\n                analyzed = o.rvalue.analyzed\n            if o.is_alias_def or isinstance(\n                analyzed, (TypeVarExpr, NamedTupleExpr, TypedDictExpr, NewTypeExpr)\n            ):\n                special_form = True\n            if special_form:\n                # TODO: Ignore all lines if multi-line\n                self.ignored_lines.add(o.line)\n        super().visit_assignment_stmt(o)\n\n    def visit_name_expr(self, o: NameExpr, /) -> None:\n        if ann := stdlib_hints.get(o.fullname):\n            self.annotate(o, ann)\n\n    def visit_member_expr(self, o: MemberExpr, /) -> None:\n        super().visit_member_expr(o)\n        if ann := stdlib_hints.get(o.fullname):\n            self.annotate(o, ann)\n\n    def visit_call_expr(self, o: CallExpr, /) -> None:\n        super().visit_call_expr(o)\n        if (\n            isinstance(o.callee, RefExpr)\n            and o.callee.fullname == \"builtins.isinstance\"\n            and len(o.args) == 2\n        ):\n            arg = o.args[1]\n            self.check_isinstance_arg(arg)\n        elif isinstance(o.callee, RefExpr) and isinstance(o.callee.node, TypeInfo):\n            info = o.callee.node\n            class_ir = self.mapper.type_to_ir.get(info)\n            if (class_ir and not class_ir.is_ext_class) or (\n                class_ir is None and not info.fullname.startswith(\"builtins.\")\n            ):\n                self.annotate(\n                    o, f'Creating an instance of non-native class \"{info.name}\" ' + \"is slow.\", 2\n                )\n            elif class_ir and class_ir.is_augmented:\n                self.annotate(\n                    o,\n                    f'Class \"{info.name}\" is only partially native, and '\n                    + \"constructing an instance is slow.\",\n                    2,\n                )\n        elif isinstance(o.callee, RefExpr) and isinstance(o.callee.node, Decorator):\n            decorator = o.callee.node\n            if self.mapper.is_native_ref_expr(o.callee):\n                self.annotate(\n                    o,\n                    f'Calling a decorated function (\"{decorator.name}\") is inefficient, even if it\\'s native.',\n                    2,\n                )\n\n    def check_isinstance_arg(self, arg: Expression) -> None:\n        if isinstance(arg, RefExpr):\n            if isinstance(arg.node, TypeInfo) and arg.node.is_protocol:\n                self.annotate(\n                    arg, f'Expensive isinstance() check against protocol \"{arg.node.name}\".'\n                )\n        elif isinstance(arg, TupleExpr):\n            for item in arg.items:\n                self.check_isinstance_arg(item)\n\n    def visit_lambda_expr(self, o: LambdaExpr, /) -> None:\n        self.annotate(\n            o,\n            \"A new object is allocated for lambda each time it is evaluated. \"\n            + \"A module-level function would be faster.\",\n        )\n        super().visit_lambda_expr(o)\n\n    def annotate(self, o: Node, ann: str | Annotation, priority: int = 1) -> None:\n        if isinstance(ann, str):\n            ann = Annotation(ann, priority=priority)\n        self.anns.setdefault(o.line, []).append(ann)\n\n    def get_type(self, e: Expression) -> ProperType:\n        t = self.type_map.get(e)\n        if t:\n            return get_proper_type(t)\n        return AnyType(TypeOfAny.unannotated)\n\n\ndef get_str_literal(v: Value) -> str | None:\n    if isinstance(v, LoadLiteral) and isinstance(v.value, str):\n        return v.value\n    return None\n\n\ndef get_max_prio(anns: list[Annotation]) -> list[Annotation]:\n    max_prio = max(a.priority for a in anns)\n    return [a for a in anns if a.priority == max_prio]\n\n\ndef generate_html_report(sources: list[AnnotatedSource]) -> str:\n    html = []\n    html.append(\"<html>\\n<head>\\n\")\n    html.append(f\"<style>\\n{CSS}\\n</style>\")\n    html.append(\"</head>\\n\")\n    html.append(\"<body>\\n\")\n    for src in sources:\n        html.append(f\"<h2><tt>{src.path}</tt></h2>\\n\")\n        html.append(\"<pre>\")\n        src_anns = src.annotations\n        with open(src.path) as f:\n            lines = f.readlines()\n        for i, s in enumerate(lines):\n            s = escape(s)\n            line = i + 1\n            linenum = \"%5d\" % line\n            if line in src_anns:\n                anns = get_max_prio(src_anns[line])\n                ann_strs = [a.message for a in anns]\n                hint = \" \".join(ann_strs)\n                s = colorize_line(linenum, s, hint_html=hint)\n            else:\n                s = linenum + \"  \" + s\n            html.append(s)\n        html.append(\"</pre>\")\n\n    html.append(\"<script>\")\n    html.append(JS)\n    html.append(\"</script>\")\n\n    html.append(\"</body></html>\\n\")\n    return \"\".join(html)\n\n\ndef colorize_line(linenum: str, s: str, hint_html: str) -> str:\n    hint_prefix = \" \" * len(linenum) + \"  \"\n    line_span = f'<div class=\"collapsible\" style=\"background-color: #fcc\">{linenum}  {s}</div>'\n    hint_div = f'<div class=\"content\">{hint_prefix}<div class=\"hint\">{hint_html}</div></div>'\n    return f\"<span>{line_span}{hint_div}</span>\"\n"
  },
  {
    "path": "mypyc/build.py",
    "content": "\"\"\"Support for building extensions using mypyc with distutils or setuptools\n\nThe main entry point is mypycify, which produces a list of extension\nmodules to be passed to setup. A trivial setup.py for a mypyc built\nproject, then, looks like:\n\n    from setuptools import setup\n    from mypyc.build import mypycify\n\n    setup(name='test_module',\n          ext_modules=mypycify(['foo.py']),\n    )\n\nSee the mypycify docs for additional arguments.\n\nmypycify can integrate with either distutils or setuptools, but needs\nto know at import-time whether it is using distutils or setuputils. We\nhackily decide based on whether setuptools has been imported already.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport os.path\nimport re\nimport sys\nimport time\nfrom collections.abc import Iterable\nfrom typing import TYPE_CHECKING, Any, NamedTuple, NoReturn, cast\n\nimport mypyc.build_setup  # noqa: F401\nfrom mypy.build import BuildSource\nfrom mypy.errors import CompileError\nfrom mypy.fscache import FileSystemCache\nfrom mypy.main import process_options\nfrom mypy.options import Options\nfrom mypy.util import write_junit_xml\nfrom mypyc.annotate import generate_annotated_html\nfrom mypyc.codegen import emitmodule\nfrom mypyc.common import IS_FREE_THREADED, RUNTIME_C_FILES, shared_lib_name\nfrom mypyc.errors import Errors\nfrom mypyc.ir.deps import SourceDep\nfrom mypyc.ir.pprint import format_modules\nfrom mypyc.namegen import exported_name\nfrom mypyc.options import CompilerOptions\n\n\nclass ModDesc(NamedTuple):\n    module: str\n    c_files: list[str]\n    other_files: list[str]\n    include_dirs: list[str]\n\n\nLIBRT_MODULES = [\n    ModDesc(\"librt.internal\", [\"internal/librt_internal.c\"], [], [\"internal\"]),\n    ModDesc(\"librt.strings\", [\"strings/librt_strings.c\"], [], [\"strings\"]),\n    ModDesc(\n        \"librt.base64\",\n        [\n            \"base64/librt_base64.c\",\n            \"base64/lib.c\",\n            \"base64/codec_choose.c\",\n            \"base64/tables/tables.c\",\n            \"base64/arch/generic/codec.c\",\n            \"base64/arch/ssse3/codec.c\",\n            \"base64/arch/sse41/codec.c\",\n            \"base64/arch/sse42/codec.c\",\n            \"base64/arch/avx/codec.c\",\n            \"base64/arch/avx2/codec.c\",\n            \"base64/arch/avx512/codec.c\",\n            \"base64/arch/neon32/codec.c\",\n            \"base64/arch/neon64/codec.c\",\n        ],\n        [\n            \"base64/arch/avx/enc_loop_asm.c\",\n            \"base64/arch/avx2/enc_loop.c\",\n            \"base64/arch/avx2/enc_loop_asm.c\",\n            \"base64/arch/avx2/enc_reshuffle.c\",\n            \"base64/arch/avx2/enc_translate.c\",\n            \"base64/arch/avx2/dec_loop.c\",\n            \"base64/arch/avx2/dec_reshuffle.c\",\n            \"base64/arch/generic/32/enc_loop.c\",\n            \"base64/arch/generic/64/enc_loop.c\",\n            \"base64/arch/generic/32/dec_loop.c\",\n            \"base64/arch/generic/enc_head.c\",\n            \"base64/arch/generic/enc_tail.c\",\n            \"base64/arch/generic/dec_head.c\",\n            \"base64/arch/generic/dec_tail.c\",\n            \"base64/arch/ssse3/dec_reshuffle.c\",\n            \"base64/arch/ssse3/dec_loop.c\",\n            \"base64/arch/ssse3/enc_loop_asm.c\",\n            \"base64/arch/ssse3/enc_translate.c\",\n            \"base64/arch/ssse3/enc_reshuffle.c\",\n            \"base64/arch/ssse3/enc_loop.c\",\n            \"base64/arch/neon64/dec_loop.c\",\n            \"base64/arch/neon64/enc_loop_asm.c\",\n            \"base64/codecs.h\",\n            \"base64/env.h\",\n            \"base64/lib_openmp.c\",\n            \"base64/tables/tables.h\",\n            \"base64/tables/table_dec_32bit.h\",\n            \"base64/tables/table_enc_12bit.h\",\n        ],\n        [\"base64\"],\n    ),\n    ModDesc(\n        \"librt.vecs\",\n        [\n            \"vecs/librt_vecs.c\",\n            \"vecs/vec_i64.c\",\n            \"vecs/vec_i32.c\",\n            \"vecs/vec_i16.c\",\n            \"vecs/vec_u8.c\",\n            \"vecs/vec_float.c\",\n            \"vecs/vec_bool.c\",\n            \"vecs/vec_t.c\",\n            \"vecs/vec_nested.c\",\n        ],\n        [\"vecs/librt_vecs.h\", \"vecs/vec_template.c\"],\n        [\"vecs\"],\n    ),\n    ModDesc(\"librt.time\", [\"time/librt_time.c\"], [\"time/librt_time.h\"], []),\n]\n\ntry:\n    # Import setuptools so that it monkey-patch overrides distutils\n    import setuptools\nexcept ImportError:\n    pass\n\nif TYPE_CHECKING:\n    if sys.version_info >= (3, 12):\n        from setuptools import Extension\n    else:\n        from distutils.core import Extension as _distutils_Extension\n        from typing import TypeAlias\n\n        from setuptools import Extension as _setuptools_Extension\n\n        Extension: TypeAlias = _setuptools_Extension | _distutils_Extension\n\nif sys.version_info >= (3, 12):\n    # From setuptools' monkeypatch\n    from distutils import ccompiler, sysconfig  # type: ignore[import-not-found]\nelse:\n    from distutils import ccompiler, sysconfig\n\n\ndef get_extension() -> type[Extension]:\n    # We can work with either setuptools or distutils, and pick setuptools\n    # if it has been imported.\n    use_setuptools = \"setuptools\" in sys.modules\n    extension_class: type[Extension]\n\n    if sys.version_info < (3, 12) and not use_setuptools:\n        import distutils.core\n\n        extension_class = distutils.core.Extension\n    else:\n        if not use_setuptools:\n            sys.exit(\"error: setuptools not installed\")\n        extension_class = setuptools.Extension\n\n    return extension_class\n\n\ndef setup_mypycify_vars() -> None:\n    \"\"\"Rewrite a bunch of config vars in pretty dubious ways.\"\"\"\n    # There has to be a better approach to this.\n\n    # The vars can contain ints but we only work with str ones\n    vars = cast(dict[str, str], sysconfig.get_config_vars())\n    if sys.platform == \"darwin\":\n        # Disable building 32-bit binaries, since we generate too much code\n        # for a 32-bit Mach-O object. There has to be a better way to do this.\n        vars[\"LDSHARED\"] = vars[\"LDSHARED\"].replace(\"-arch i386\", \"\")\n        vars[\"LDFLAGS\"] = vars[\"LDFLAGS\"].replace(\"-arch i386\", \"\")\n        vars[\"CFLAGS\"] = vars[\"CFLAGS\"].replace(\"-arch i386\", \"\")\n\n\ndef fail(message: str) -> NoReturn:\n    # TODO: Is there something else we should do to fail?\n    sys.exit(message)\n\n\ndef emit_messages(options: Options, messages: list[str], dt: float, serious: bool = False) -> None:\n    # ... you know, just in case.\n    if options.junit_xml:\n        py_version = f\"{options.python_version[0]}_{options.python_version[1]}\"\n        write_junit_xml(\n            dt,\n            serious,\n            {None: messages} if messages else {},\n            options.junit_xml,\n            py_version,\n            options.platform,\n        )\n    if messages:\n        print(\"\\n\".join(messages))\n\n\ndef get_mypy_config(\n    mypy_options: list[str],\n    only_compile_paths: Iterable[str] | None,\n    compiler_options: CompilerOptions,\n    fscache: FileSystemCache | None,\n) -> tuple[list[BuildSource], list[BuildSource], Options]:\n    \"\"\"Construct mypy BuildSources and Options from file and options lists\"\"\"\n    all_sources, options = process_options(mypy_options, fscache=fscache, mypyc=True)\n    if only_compile_paths is not None:\n        paths_set = set(only_compile_paths)\n        mypyc_sources = [s for s in all_sources if s.path in paths_set]\n    else:\n        mypyc_sources = all_sources\n\n    if compiler_options.separate:\n        mypyc_sources = [\n            src for src in mypyc_sources if src.path and not src.path.endswith(\"__init__.py\")\n        ]\n\n    if not mypyc_sources:\n        return mypyc_sources, all_sources, options\n\n    # Override whatever python_version is inferred from the .ini file,\n    # and set the python_version to be the currently used version.\n    options.python_version = sys.version_info[:2]\n\n    if options.python_version[0] == 2:\n        fail(\"Python 2 not supported\")\n    if not options.strict_optional:\n        fail(\"Disabling strict optional checking not supported\")\n    options.show_traceback = True\n    # Needed to get types for all AST nodes\n    options.export_types = True\n    # We use mypy incremental mode when doing separate/incremental mypyc compilation\n    options.incremental = compiler_options.separate\n    options.preserve_asts = True\n\n    for source in mypyc_sources:\n        options.per_module_options.setdefault(source.module, {})[\"mypyc\"] = True\n\n    return mypyc_sources, all_sources, options\n\n\ndef generate_c_extension_shim(\n    full_module_name: str, module_name: str, dir_name: str, group_name: str\n) -> str:\n    \"\"\"Create a C extension shim with a passthrough PyInit function.\n\n    Arguments:\n        full_module_name: the dotted full module name\n        module_name: the final component of the module name\n        dir_name: the directory to place source code\n        group_name: the name of the group\n    \"\"\"\n    cname = \"%s.c\" % full_module_name.replace(\".\", os.sep)\n    cpath = os.path.join(dir_name, cname)\n\n    if IS_FREE_THREADED:\n        # We use multi-phase init in free-threaded builds to enable free threading.\n        shim_name = \"module_shim_no_gil_multiphase.tmpl\"\n    else:\n        shim_name = \"module_shim.tmpl\"\n\n    # We load the C extension shim template from a file.\n    # (So that the file could be reused as a bazel template also.)\n    with open(os.path.join(include_dir(), shim_name)) as f:\n        shim_template = f.read()\n\n    write_file(\n        cpath,\n        shim_template.format(\n            modname=module_name,\n            libname=shared_lib_name(group_name),\n            full_modname=exported_name(full_module_name),\n        ),\n    )\n\n    return cpath\n\n\ndef group_name(modules: list[str]) -> str:\n    \"\"\"Produce a probably unique name for a group from a list of module names.\"\"\"\n    if len(modules) == 1:\n        return modules[0]\n\n    h = hashlib.sha1()\n    h.update(\",\".join(modules).encode())\n    return h.hexdigest()[:20]\n\n\ndef include_dir() -> str:\n    \"\"\"Find the path of the lib-rt dir that needs to be included\"\"\"\n    return os.path.join(os.path.abspath(os.path.dirname(__file__)), \"lib-rt\")\n\n\ndef generate_c(\n    sources: list[BuildSource],\n    options: Options,\n    groups: emitmodule.Groups,\n    fscache: FileSystemCache,\n    compiler_options: CompilerOptions,\n) -> tuple[list[list[tuple[str, str]]], str, list[SourceDep]]:\n    \"\"\"Drive the actual core compilation step.\n\n    The groups argument describes how modules are assigned to C\n    extension modules. See the comments on the Groups type in\n    mypyc.emitmodule for details.\n\n    Returns the C source code, (for debugging) the pretty printed IR, and list of SourceDeps.\n    \"\"\"\n    t0 = time.time()\n\n    try:\n        result = emitmodule.parse_and_typecheck(\n            sources, options, compiler_options, groups, fscache\n        )\n    except CompileError as e:\n        emit_messages(options, e.messages, time.time() - t0, serious=(not e.use_stdout))\n        sys.exit(1)\n\n    t1 = time.time()\n    if result.errors:\n        emit_messages(options, result.errors, t1 - t0)\n        sys.exit(1)\n\n    if compiler_options.verbose:\n        print(f\"Parsed and typechecked in {t1 - t0:.3f}s\")\n\n    errors = Errors(options)\n    modules, ctext, mapper = emitmodule.compile_modules_to_c(\n        result, compiler_options=compiler_options, errors=errors, groups=groups\n    )\n    t2 = time.time()\n    emit_messages(options, errors.new_messages(), t2 - t1)\n    if errors.num_errors:\n        # No need to stop the build if only warnings were emitted.\n        sys.exit(1)\n\n    if compiler_options.verbose:\n        print(f\"Compiled to C in {t2 - t1:.3f}s\")\n\n    if options.mypyc_annotation_file:\n        generate_annotated_html(options.mypyc_annotation_file, result, modules, mapper)\n\n    # Collect SourceDep dependencies\n    source_deps = sorted(emitmodule.collect_source_dependencies(modules), key=lambda d: d.path)\n\n    return ctext, \"\\n\".join(format_modules(modules)), source_deps\n\n\ndef build_using_shared_lib(\n    sources: list[BuildSource],\n    group_name: str,\n    cfiles: list[str],\n    deps: list[str],\n    build_dir: str,\n    extra_compile_args: list[str],\n) -> list[Extension]:\n    \"\"\"Produce the list of extension modules when a shared library is needed.\n\n    This creates one shared library extension module that all the\n    others import, and one shim extension module for each\n    module in the build. Each shim simply calls an initialization function\n    in the shared library.\n\n    The shared library (which lib_name is the name of) is a Python\n    extension module that exports the real initialization functions in\n    Capsules stored in module attributes.\n    \"\"\"\n    extensions = [\n        get_extension()(\n            shared_lib_name(group_name),\n            sources=cfiles,\n            include_dirs=[include_dir(), build_dir],\n            depends=deps,\n            extra_compile_args=extra_compile_args,\n        )\n    ]\n\n    for source in sources:\n        module_name = source.module.split(\".\")[-1]\n        shim_file = generate_c_extension_shim(source.module, module_name, build_dir, group_name)\n\n        # We include the __init__ in the \"module name\" we stick in the Extension,\n        # since this seems to be needed for it to end up in the right place.\n        full_module_name = source.module\n        assert source.path\n        if os.path.split(source.path)[1] == \"__init__.py\":\n            full_module_name += \".__init__\"\n        extensions.append(\n            get_extension()(\n                full_module_name, sources=[shim_file], extra_compile_args=extra_compile_args\n            )\n        )\n\n    return extensions\n\n\ndef build_single_module(\n    sources: list[BuildSource], cfiles: list[str], extra_compile_args: list[str]\n) -> list[Extension]:\n    \"\"\"Produce the list of extension modules for a standalone extension.\n\n    This contains just one module, since there is no need for a shared module.\n    \"\"\"\n    return [\n        get_extension()(\n            sources[0].module,\n            sources=cfiles,\n            include_dirs=[include_dir()],\n            extra_compile_args=extra_compile_args,\n        )\n    ]\n\n\ndef write_file(path: str, contents: str) -> None:\n    \"\"\"Write data into a file.\n\n    If the file already exists and has the same contents we\n    want to write, skip writing so as to preserve the mtime\n    and avoid triggering recompilation.\n    \"\"\"\n    # We encode it ourselves and open the files as binary to avoid windows\n    # newline translation\n    encoded_contents = contents.encode(\"utf-8\")\n    try:\n        with open(path, \"rb\") as f:\n            old_contents: bytes | None = f.read()\n    except OSError:\n        old_contents = None\n    if old_contents != encoded_contents:\n        os.makedirs(os.path.dirname(path), exist_ok=True)\n        with open(path, \"wb\") as g:\n            g.write(encoded_contents)\n\n        # Fudge the mtime forward because otherwise when two builds happen close\n        # together (like in a test) setuptools might not realize the source is newer\n        # than the new artifact.\n        # XXX: This is bad though.\n        new_mtime = os.stat(path).st_mtime + 1\n        os.utime(path, times=(new_mtime, new_mtime))\n\n\ndef construct_groups(\n    sources: list[BuildSource],\n    separate: bool | list[tuple[list[str], str | None]],\n    use_shared_lib: bool,\n    group_name_override: str | None,\n) -> emitmodule.Groups:\n    \"\"\"Compute Groups given the input source list and separate configs.\n\n    separate is the user-specified configuration for how to assign\n    modules to compilation groups (see mypycify docstring for details).\n\n    This takes that and expands it into our internal representation of\n    group configuration, documented in mypyc.emitmodule's definition\n    of Group.\n    \"\"\"\n\n    if separate is True:\n        groups: emitmodule.Groups = [([source], None) for source in sources]\n    elif isinstance(separate, list):\n        groups = []\n        used_sources = set()\n        for files, name in separate:\n            group_sources = [src for src in sources if src.path in files]\n            groups.append((group_sources, name))\n            used_sources.update(group_sources)\n        unused_sources = [src for src in sources if src not in used_sources]\n        if unused_sources:\n            groups.extend([([source], None) for source in unused_sources])\n    else:\n        groups = [(sources, None)]\n\n    # Generate missing names\n    for i, (group, name) in enumerate(groups):\n        if use_shared_lib and not name:\n            if group_name_override is not None:\n                name = group_name_override\n            else:\n                name = group_name([source.module for source in group])\n        groups[i] = (group, name)\n\n    return groups\n\n\ndef get_header_deps(cfiles: list[tuple[str, str]]) -> list[str]:\n    \"\"\"Find all the headers used by a group of cfiles.\n\n    We do this by just regexping the source, which is a bit simpler than\n    properly plumbing the data through.\n\n    Arguments:\n        cfiles: A list of (file name, file contents) pairs.\n    \"\"\"\n    headers: set[str] = set()\n    for _, contents in cfiles:\n        headers.update(re.findall(r'#include \"(.*)\"', contents))\n\n    return sorted(headers)\n\n\ndef mypyc_build(\n    paths: list[str],\n    compiler_options: CompilerOptions,\n    *,\n    separate: bool | list[tuple[list[str], str | None]] = False,\n    only_compile_paths: Iterable[str] | None = None,\n    skip_cgen_input: tuple[list[list[tuple[str, str]]], list[str]] | None = None,\n    always_use_shared_lib: bool = False,\n) -> tuple[emitmodule.Groups, list[tuple[list[str], list[str]]], list[SourceDep]]:\n    \"\"\"Do the front and middle end of mypyc building, producing and writing out C source.\"\"\"\n    fscache = FileSystemCache()\n    mypyc_sources, all_sources, options = get_mypy_config(\n        paths, only_compile_paths, compiler_options, fscache\n    )\n\n    # We generate a shared lib if there are multiple modules or if any\n    # of the modules are in package. (Because I didn't want to fuss\n    # around with making the single module code handle packages.)\n    use_shared_lib = (\n        len(mypyc_sources) > 1\n        or any(\".\" in x.module for x in mypyc_sources)\n        or always_use_shared_lib\n    )\n\n    groups = construct_groups(mypyc_sources, separate, use_shared_lib, compiler_options.group_name)\n\n    if compiler_options.group_name is not None:\n        assert len(groups) == 1, \"If using custom group_name, only one group is expected\"\n\n    # We let the test harness just pass in the c file contents instead\n    # so that it can do a corner-cutting version without full stubs.\n    source_deps: list[SourceDep] = []\n    if not skip_cgen_input:\n        group_cfiles, ops_text, source_deps = generate_c(\n            all_sources, options, groups, fscache, compiler_options=compiler_options\n        )\n        # TODO: unique names?\n        write_file(os.path.join(compiler_options.target_dir, \"ops.txt\"), ops_text)\n    else:\n        group_cfiles = skip_cgen_input[0]\n        source_deps = [SourceDep(d) for d in skip_cgen_input[1]]\n\n    # Write out the generated C and collect the files for each group\n    # Should this be here??\n    group_cfilenames: list[tuple[list[str], list[str]]] = []\n    for cfiles in group_cfiles:\n        cfilenames = []\n        for cfile, ctext in cfiles:\n            cfile = os.path.join(compiler_options.target_dir, cfile)\n            if not options.mypyc_skip_c_generation:\n                write_file(cfile, ctext)\n            if os.path.splitext(cfile)[1] == \".c\":\n                cfilenames.append(cfile)\n\n        deps = [os.path.join(compiler_options.target_dir, dep) for dep in get_header_deps(cfiles)]\n        group_cfilenames.append((cfilenames, deps))\n\n    return groups, group_cfilenames, source_deps\n\n\ndef get_cflags(\n    *,\n    compiler_type: str | None = None,\n    opt_level: str = \"3\",\n    debug_level: str = \"1\",\n    multi_file: bool = False,\n    experimental_features: bool = False,\n    log_trace: bool = False,\n) -> list[str]:\n    \"\"\"Get C compiler flags for the given configuration.\n\n    Args:\n        compiler_type: Compiler type, e.g. \"unix\" or \"msvc\". If None, detected automatically.\n        opt_level: Optimization level as string (\"0\", \"1\", \"2\", or \"3\").\n        debug_level: Debug level as string (\"0\", \"1\", \"2\", or \"3\").\n        multi_file: Whether multi-file compilation mode is enabled.\n        experimental_features: Whether experimental features are enabled.\n        log_trace: Whether trace logging is enabled.\n\n    Returns:\n        List of compiler flags.\n    \"\"\"\n    if compiler_type is None:\n        compiler: Any = ccompiler.new_compiler()\n        sysconfig.customize_compiler(compiler)\n        compiler_type = compiler.compiler_type\n\n    cflags: list[str] = []\n    if compiler_type == \"unix\":\n        cflags += [\n            f\"-O{opt_level}\",\n            f\"-g{debug_level}\",\n            \"-Werror\",\n            \"-Wno-unused-function\",\n            \"-Wno-unused-label\",\n            \"-Wno-unreachable-code\",\n            \"-Wno-unused-variable\",\n            \"-Wno-unused-command-line-argument\",\n            \"-Wno-unknown-warning-option\",\n            \"-Wno-unused-but-set-variable\",\n            \"-Wno-ignored-optimization-argument\",\n            # Disables C Preprocessor (cpp) warnings\n            # See https://github.com/mypyc/mypyc/issues/956\n            \"-Wno-cpp\",\n        ]\n        if log_trace:\n            cflags.append(\"-DMYPYC_LOG_TRACE\")\n        if experimental_features:\n            cflags.append(\"-DMYPYC_EXPERIMENTAL\")\n        if opt_level == \"0\":\n            cflags.append(\"-UNDEBUG\")\n    elif compiler_type == \"msvc\":\n        # msvc doesn't have levels, '/O2' is full and '/Od' is disable\n        if opt_level == \"0\":\n            opt_level = \"d\"\n            cflags.append(\"/UNDEBUG\")\n        elif opt_level in (\"1\", \"2\", \"3\"):\n            opt_level = \"2\"\n        if debug_level == \"0\":\n            debug_level = \"NONE\"\n        elif debug_level == \"1\":\n            debug_level = \"FASTLINK\"\n        elif debug_level in (\"2\", \"3\"):\n            debug_level = \"FULL\"\n        cflags += [\n            f\"/O{opt_level}\",\n            f\"/DEBUG:{debug_level}\",\n            \"/wd4102\",  # unreferenced label\n            \"/wd4101\",  # unreferenced local variable\n            \"/wd4146\",  # negating unsigned int\n        ]\n        if multi_file:\n            # Disable whole program optimization in multi-file mode so\n            # that we actually get the compilation speed and memory\n            # use wins that multi-file mode is intended for.\n            cflags += [\"/GL-\", \"/wd9025\"]  # warning about overriding /GL\n        if log_trace:\n            cflags.append(\"/DMYPYC_LOG_TRACE\")\n        if experimental_features:\n            cflags.append(\"/DMYPYC_EXPERIMENTAL\")\n    return cflags\n\n\ndef mypycify(\n    paths: list[str],\n    *,\n    only_compile_paths: Iterable[str] | None = None,\n    verbose: bool = False,\n    opt_level: str = \"3\",\n    debug_level: str = \"1\",\n    strip_asserts: bool = False,\n    multi_file: bool = False,\n    separate: bool | list[tuple[list[str], str | None]] = False,\n    skip_cgen_input: tuple[list[list[tuple[str, str]]], list[str]] | None = None,\n    target_dir: str | None = None,\n    include_runtime_files: bool | None = None,\n    strict_dunder_typing: bool = False,\n    group_name: str | None = None,\n    log_trace: bool = False,\n    depends_on_librt_internal: bool = False,\n    install_librt: bool = False,\n    experimental_features: bool = False,\n) -> list[Extension]:\n    \"\"\"Main entry point to building using mypyc.\n\n    This produces a list of Extension objects that should be passed as the\n    ext_modules parameter to setup.\n\n    Arguments:\n        paths: A list of file paths to build. It may also contain mypy options.\n        only_compile_paths: If not None, an iterable of paths that are to be\n                            the only modules compiled, even if other modules\n                            appear in the mypy command line given to paths.\n                            (These modules must still be passed to paths.)\n\n        verbose: Should mypyc be more verbose. Defaults to false.\n\n        opt_level: The optimization level, as a string. Defaults to '3' (meaning '-O3').\n        debug_level: The debug level, as a string. Defaults to '1' (meaning '-g1').\n        strip_asserts: Should asserts be stripped from the generated code.\n\n        multi_file: Should each Python module be compiled into its own C source file.\n                    This can reduce compile time and memory requirements at the likely\n                    cost of runtime performance of compiled code. Defaults to false.\n        separate: Should compiled modules be placed in separate extension modules.\n                  If False, all modules are placed in a single shared library.\n                  If True, every module is placed in its own library.\n                  Otherwise, separate should be a list of\n                  (file name list, optional shared library name) pairs specifying\n                  groups of files that should be placed in the same shared library\n                  (while all other modules will be placed in its own library).\n\n                  Each group can be compiled independently, which can\n                  speed up compilation, but calls between groups can\n                  be slower than calls within a group and can't be\n                  inlined.\n        target_dir: The directory to write C output files. Defaults to 'build'.\n        include_runtime_files: If not None, whether the mypyc runtime library\n                               should be directly #include'd instead of linked\n                               separately in order to reduce compiler invocations.\n                               Defaults to False in multi_file mode, True otherwise.\n        strict_dunder_typing: If True, force dunder methods to have the return type\n                              of the method strictly, which can lead to more\n                              optimization opportunities. Defaults to False.\n        group_name: If set, override the default group name derived from\n                    the hash of module names. This is used for the names of the\n                    output C files and the shared library. This is only supported\n                    if there is a single group. [Experimental]\n        log_trace: If True, compiled code writes a trace log of events in\n                   mypyc_trace.txt (derived from executed operations). This is\n                   useful for performance analysis, such as analyzing which\n                   primitive ops are used the most and on which lines.\n        depends_on_librt_internal: This is True only for mypy itself.\n        install_librt: If True, also build the librt extension modules. Normally,\n                       those are build and published on PyPI separately, but during\n                       tests, we want to use their development versions (i.e. from\n                       current commit).\n        experimental_features: Enable experimental features (install_librt=True is\n                               also needed if using experimental librt features). These\n                               have no backward compatibility guarantees!\n    \"\"\"\n\n    # Figure out our configuration\n    compiler_options = CompilerOptions(\n        strip_asserts=strip_asserts,\n        multi_file=multi_file,\n        verbose=verbose,\n        separate=separate is not False,\n        target_dir=target_dir,\n        include_runtime_files=include_runtime_files,\n        strict_dunder_typing=strict_dunder_typing,\n        group_name=group_name,\n        log_trace=log_trace,\n        depends_on_librt_internal=depends_on_librt_internal,\n        experimental_features=experimental_features,\n    )\n\n    # Generate all the actual important C code\n    groups, group_cfilenames, source_deps = mypyc_build(\n        paths,\n        only_compile_paths=only_compile_paths,\n        compiler_options=compiler_options,\n        separate=separate,\n        skip_cgen_input=skip_cgen_input,\n    )\n\n    # Mess around with setuptools and actually get the thing built\n    setup_mypycify_vars()\n\n    # Create a compiler object so we can make decisions based on what\n    # compiler is being used. typeshed is missing some attributes on the\n    # compiler object so we give it type Any\n    compiler: Any = ccompiler.new_compiler()\n    sysconfig.customize_compiler(compiler)\n\n    build_dir = compiler_options.target_dir\n\n    cflags = get_cflags(\n        compiler_type=compiler.compiler_type,\n        opt_level=opt_level,\n        debug_level=debug_level,\n        multi_file=multi_file,\n        experimental_features=experimental_features,\n        log_trace=log_trace,\n    )\n\n    # If configured to (defaults to yes in multi-file mode), copy the\n    # runtime library in. Otherwise it just gets #included to save on\n    # compiler invocations.\n    shared_cfilenames = []\n    if not compiler_options.include_runtime_files:\n        # Collect all files to copy: runtime files + conditional source files\n        files_to_copy = list(RUNTIME_C_FILES)\n        for source_dep in source_deps:\n            files_to_copy.append(source_dep.path)\n            files_to_copy.append(source_dep.get_header())\n\n        # Copy all files\n        for name in files_to_copy:\n            rt_file = os.path.join(build_dir, name)\n            with open(os.path.join(include_dir(), name), encoding=\"utf-8\") as f:\n                write_file(rt_file, f.read())\n            if name.endswith(\".c\"):\n                shared_cfilenames.append(rt_file)\n\n    extensions = []\n    for (group_sources, lib_name), (cfilenames, deps) in zip(groups, group_cfilenames):\n        if lib_name:\n            extensions.extend(\n                build_using_shared_lib(\n                    group_sources,\n                    lib_name,\n                    cfilenames + shared_cfilenames,\n                    deps,\n                    build_dir,\n                    cflags,\n                )\n            )\n        else:\n            extensions.extend(\n                build_single_module(group_sources, cfilenames + shared_cfilenames, cflags)\n            )\n\n    if install_librt:\n        for name in RUNTIME_C_FILES:\n            rt_file = os.path.join(build_dir, name)\n            with open(os.path.join(include_dir(), name), encoding=\"utf-8\") as f:\n                write_file(rt_file, f.read())\n        for mod, file_names, addit_files, includes in LIBRT_MODULES:\n            for file_name in file_names + addit_files:\n                rt_file = os.path.join(build_dir, file_name)\n                with open(os.path.join(include_dir(), file_name), encoding=\"utf-8\") as f:\n                    write_file(rt_file, f.read())\n            extensions.append(\n                get_extension()(\n                    mod,\n                    sources=[\n                        os.path.join(build_dir, file) for file in file_names + RUNTIME_C_FILES\n                    ],\n                    include_dirs=[include_dir()]\n                    + [os.path.join(include_dir(), d) for d in includes],\n                    extra_compile_args=cflags,\n                )\n            )\n\n    return extensions\n"
  },
  {
    "path": "mypyc/build_setup.py",
    "content": "# This file must have the same content for mypyc/build_setup.py and lib-rt/build_setup.py,\n# it exists to work around absence of support for per-file compile flags in setuptools.\n# The version in mypyc/ is the source of truth, and should be copied to lib-rt if modified.\n\nimport os\nimport platform\nimport sys\n\ntry:\n    # Import setuptools so that it monkey-patch overrides distutils\n    import setuptools  # noqa: F401\nexcept ImportError:\n    pass\n\nif sys.version_info >= (3, 12):\n    # From setuptools' monkeypatch\n    from distutils import ccompiler  # type: ignore[import-not-found]\nelse:\n    from distutils import ccompiler\n\nEXTRA_FLAGS_PER_COMPILER_TYPE_PER_PATH_COMPONENT = {\n    \"msvc\": {\n        \"base64/arch/sse42\": [\"/arch:SSE4.2\"],\n        \"base64/arch/avx2\": [\"/arch:AVX2\"],\n        \"base64/arch/avx\": [\"/arch:AVX\"],\n    }\n}\n\nccompiler.CCompiler.__spawn = ccompiler.CCompiler.spawn  # type: ignore[attr-defined]\nX86_64 = platform.machine() in (\"x86_64\", \"AMD64\", \"amd64\")\nPYODIDE = \"PYODIDE\" in os.environ\nNO_EXTRA_FLAGS = \"MYPYC_NO_EXTRA_FLAGS\" in os.environ\n\n\ndef spawn(self, cmd, **kwargs) -> None:  # type: ignore[no-untyped-def]\n    new_cmd = list(cmd)\n    if PYODIDE:\n        for argument in reversed(new_cmd):\n            if not str(argument).endswith(\".c\"):\n                continue\n            if \"base64/arch/\" in str(argument):\n                new_cmd.extend([\"-msimd128\"])\n    elif not NO_EXTRA_FLAGS:\n        compiler_type: str = self.compiler_type\n        extra_options = EXTRA_FLAGS_PER_COMPILER_TYPE_PER_PATH_COMPONENT.get(compiler_type, None)\n        if X86_64 and extra_options is not None:\n            # filenames are closer to the end of command line\n            for argument in reversed(new_cmd):\n                # Check if the matching argument contains a source filename.\n                if not str(argument).endswith(\".c\"):\n                    continue\n\n                for path in extra_options.keys():\n                    if path in str(argument):\n                        if compiler_type == \"bcpp\":\n                            compiler = new_cmd.pop()\n                            # Borland accepts a source file name at the end,\n                            # insert the options before it\n                            new_cmd.extend(extra_options[path])\n                            new_cmd.append(compiler)\n                        else:\n                            new_cmd.extend(extra_options[path])\n\n                        # path component is found, no need to search any further\n                        break\n    self.__spawn(new_cmd, **kwargs)\n\n\nccompiler.CCompiler.spawn = spawn  # type: ignore[method-assign]\n"
  },
  {
    "path": "mypyc/codegen/__init__.py",
    "content": ""
  },
  {
    "path": "mypyc/codegen/cstring.py",
    "content": "\"\"\"Encode valid C string literals from Python strings.\n\nIf a character is not allowed in C string literals, it is either emitted\nas a simple escape sequence (e.g. '\\\\n'), or an octal escape sequence\nwith exactly three digits ('\\\\oXXX'). Question marks are escaped to\nprevent trigraphs in the string literal from being interpreted. Note\nthat '\\\\?' is an invalid escape sequence in Python.\n\nConsider the string literal \"AB\\\\xCDEF\". As one would expect, Python\nparses it as ['A', 'B', 0xCD, 'E', 'F']. However, the C standard\nspecifies that all hexadecimal digits immediately following '\\\\x' will\nbe interpreted as part of the escape sequence. Therefore, it is\nunexpectedly parsed as ['A', 'B', 0xCDEF].\n\nEmitting (\"AB\\\\xCD\" \"EF\") would avoid this behaviour. However, we opt\nfor simplicity and use octal escape sequences instead. They do not\nsuffer from the same issue as they are defined to parse at most three\noctal digits.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport string\nfrom typing import Final\n\nCHAR_MAP: Final = [f\"\\\\{i:03o}\" for i in range(256)]\n\n# It is safe to use string.printable as it always uses the C locale.\nfor c in string.printable:\n    CHAR_MAP[ord(c)] = c\n\n# These assignments must come last because we prioritize simple escape\n# sequences over any other representation.\nfor c in (\"'\", '\"', \"\\\\\", \"a\", \"b\", \"f\", \"n\", \"r\", \"t\", \"v\"):\n    escaped = f\"\\\\{c}\"\n    decoded = escaped.encode(\"ascii\").decode(\"unicode_escape\")\n    CHAR_MAP[ord(decoded)] = escaped\n\n# This escape sequence is invalid in Python.\nCHAR_MAP[ord(\"?\")] = r\"\\?\"\n\n\ndef encode_bytes_as_c_string(b: bytes) -> str:\n    \"\"\"Produce contents of a C string literal for a byte string, without quotes.\"\"\"\n    escaped = \"\".join([CHAR_MAP[i] for i in b])\n    return escaped\n\n\ndef c_string_initializer(value: bytes) -> str:\n    \"\"\"Create initializer for a C char[]/ char * variable from a string.\n\n    For example, if value if b'foo', the result would be '\"foo\"'.\n    \"\"\"\n    return '\"' + encode_bytes_as_c_string(value) + '\"'\n"
  },
  {
    "path": "mypyc/codegen/emit.py",
    "content": "\"\"\"Utilities for emitting C code.\"\"\"\n\nfrom __future__ import annotations\n\nimport pprint\nimport sys\nimport textwrap\nfrom collections.abc import Callable\nfrom typing import Final\n\nfrom mypyc.codegen.cstring import c_string_initializer\nfrom mypyc.codegen.literals import Literals\nfrom mypyc.common import (\n    ATTR_PREFIX,\n    BITMAP_BITS,\n    FAST_ISINSTANCE_MAX_SUBCLASSES,\n    HAVE_IMMORTAL,\n    MODULE_PREFIX,\n    NATIVE_PREFIX,\n    PREFIX,\n    REG_PREFIX,\n    STATIC_PREFIX,\n    TYPE_PREFIX,\n    TYPE_VAR_PREFIX,\n)\nfrom mypyc.ir.class_ir import ClassIR, all_concrete_classes\nfrom mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncDecl, FuncIR, get_text_signature\nfrom mypyc.ir.ops import (\n    NAMESPACE_MODULE,\n    NAMESPACE_STATIC,\n    NAMESPACE_TYPE,\n    NAMESPACE_TYPE_VAR,\n    BasicBlock,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RPrimitive,\n    RTuple,\n    RType,\n    RUnion,\n    RVec,\n    int_rprimitive,\n    is_bool_or_bit_rprimitive,\n    is_bytearray_rprimitive,\n    is_bytes_rprimitive,\n    is_dict_rprimitive,\n    is_fixed_width_rtype,\n    is_float_rprimitive,\n    is_frozenset_rprimitive,\n    is_int16_rprimitive,\n    is_int32_rprimitive,\n    is_int64_rprimitive,\n    is_int_rprimitive,\n    is_list_rprimitive,\n    is_native_rprimitive,\n    is_none_rprimitive,\n    is_object_rprimitive,\n    is_optional_type,\n    is_range_rprimitive,\n    is_set_rprimitive,\n    is_short_int_rprimitive,\n    is_str_rprimitive,\n    is_tuple_rprimitive,\n    is_uint8_rprimitive,\n    object_rprimitive,\n    optional_value_type,\n    vec_api_by_item_type,\n    vec_item_type_tags,\n)\nfrom mypyc.namegen import NameGenerator, exported_name\nfrom mypyc.primitives.registry import builtin_names\nfrom mypyc.sametype import is_same_type\n\n# Whether to insert debug asserts for all error handling, to quickly\n# catch errors propagating without exceptions set.\nDEBUG_ERRORS: Final = False\n\nPREFIX_MAP: Final = {\n    NAMESPACE_STATIC: STATIC_PREFIX,\n    NAMESPACE_TYPE: TYPE_PREFIX,\n    NAMESPACE_MODULE: MODULE_PREFIX,\n    NAMESPACE_TYPE_VAR: TYPE_VAR_PREFIX,\n}\n\n\nclass HeaderDeclaration:\n    \"\"\"A representation of a declaration in C.\n\n    This is used to generate declarations in header files and\n    (optionally) definitions in source files.\n\n    Attributes:\n      decl: C source code for the declaration.\n      defn: Optionally, C source code for a definition.\n      dependencies: The names of any objects that must be declared prior.\n      is_type: Whether the declaration is of a C type. (C types will be declared in\n               external header files and not marked 'extern'.)\n      needs_export: Whether the declared object needs to be exported to\n                    other modules in the linking table.\n    \"\"\"\n\n    def __init__(\n        self,\n        decl: str | list[str],\n        defn: list[str] | None = None,\n        *,\n        dependencies: set[str] | None = None,\n        is_type: bool = False,\n        needs_export: bool = False,\n    ) -> None:\n        self.decl = [decl] if isinstance(decl, str) else decl\n        self.defn = defn\n        self.dependencies = dependencies or set()\n        self.is_type = is_type\n        self.needs_export = needs_export\n\n\nclass EmitterContext:\n    \"\"\"Shared emitter state for a compilation group.\"\"\"\n\n    def __init__(\n        self,\n        names: NameGenerator,\n        strict_traceback_checks: bool,\n        group_name: str | None = None,\n        group_map: dict[str, str | None] | None = None,\n    ) -> None:\n        \"\"\"Setup shared emitter state.\n\n        Args:\n            names: The name generator to use\n            group_map: Map from module names to group name\n            group_name: Current group name\n        \"\"\"\n        self.temp_counter = 0\n        self.names = names\n        self.group_name = group_name\n        self.group_map = group_map or {}\n        # Groups that this group depends on\n        self.group_deps: set[str] = set()\n\n        # The map below is used for generating declarations and\n        # definitions at the top of the C file. The main idea is that they can\n        # be generated at any time during the emit phase.\n\n        # A map of a C identifier to whatever the C identifier declares. Currently this is\n        # used for declaring structs and the key corresponds to the name of the struct.\n        # The declaration contains the body of the struct.\n        self.declarations: dict[str, HeaderDeclaration] = {}\n\n        self.literals = Literals()\n        # See mypyc/options.py for context.\n        self.strict_traceback_checks = strict_traceback_checks\n\n\nclass ErrorHandler:\n    \"\"\"Describes handling errors in unbox/cast operations.\"\"\"\n\n\nclass AssignHandler(ErrorHandler):\n    \"\"\"Assign an error value on error.\"\"\"\n\n\nclass GotoHandler(ErrorHandler):\n    \"\"\"Goto label on error.\"\"\"\n\n    def __init__(self, label: str) -> None:\n        self.label = label\n\n\nclass TracebackAndGotoHandler(ErrorHandler):\n    \"\"\"Add traceback item and goto label on error.\"\"\"\n\n    def __init__(\n        self, label: str, source_path: str, module_name: str, traceback_entry: tuple[str, int]\n    ) -> None:\n        self.label = label\n        self.source_path = source_path\n        self.module_name = module_name\n        self.traceback_entry = traceback_entry\n\n\nclass ReturnHandler(ErrorHandler):\n    \"\"\"Return a constant value on error.\"\"\"\n\n    def __init__(self, value: str) -> None:\n        self.value = value\n\n\nclass Emitter:\n    \"\"\"Helper for C code generation.\"\"\"\n\n    def __init__(\n        self,\n        context: EmitterContext,\n        value_names: dict[Value, str] | None = None,\n        capi_version: tuple[int, int] | None = None,\n        filepath: str | None = None,\n    ) -> None:\n        self.context = context\n        self.capi_version = capi_version or sys.version_info[:2]\n        self.names = context.names\n        self.value_names = value_names or {}\n        self.fragments: list[str] = []\n        self._indent = 0\n        self.filepath = filepath\n\n    # Low-level operations\n\n    def indent(self) -> None:\n        self._indent += 4\n\n    def dedent(self) -> None:\n        self._indent -= 4\n        assert self._indent >= 0\n\n    def label(self, label: BasicBlock) -> str:\n        return \"CPyL%s\" % label.label\n\n    def reg(self, reg: Value) -> str:\n        return REG_PREFIX + self.value_names[reg]\n\n    def attr(self, name: str) -> str:\n        return ATTR_PREFIX + name\n\n    def object_annotation(self, obj: object, line: str) -> str:\n        \"\"\"Build a C comment with an object's string representation.\n\n        If the comment exceeds the line length limit, it's wrapped into a\n        multiline string (with the extra lines indented to be aligned with\n        the first line's comment).\n\n        If it contains illegal characters, an empty string is returned.\"\"\"\n        line_width = self._indent + len(line)\n        formatted = pprint.pformat(obj, compact=True, width=max(90 - line_width, 20))\n        if any(x in formatted for x in (\"/*\", \"*/\", \"\\0\")):\n            return \"\"\n\n        if \"\\n\" in formatted:\n            first_line, rest = formatted.split(\"\\n\", maxsplit=1)\n            comment_continued = textwrap.indent(rest, (line_width + 3) * \" \")\n            return f\" /* {first_line}\\n{comment_continued} */\"\n        else:\n            return f\" /* {formatted} */\"\n\n    def emit_line(self, line: str = \"\", *, ann: object = None) -> None:\n        if line.startswith(\"}\"):\n            self.dedent()\n        comment = self.object_annotation(ann, line) if ann is not None else \"\"\n        self.fragments.append(self._indent * \" \" + line + comment + \"\\n\")\n        if line.endswith(\"{\"):\n            self.indent()\n\n    def emit_lines(self, *lines: str) -> None:\n        for line in lines:\n            self.emit_line(line)\n\n    def emit_label(self, label: BasicBlock | str) -> None:\n        if isinstance(label, str):\n            text = label\n        else:\n            if label.label == 0 or not label.referenced:\n                return\n\n            text = self.label(label)\n        # Extra semicolon prevents an error when the next line declares a tempvar\n        self.fragments.append(f\"{text}: ;\\n\")\n\n    def emit_from_emitter(self, emitter: Emitter) -> None:\n        self.fragments.extend(emitter.fragments)\n\n    def emit_printf(self, fmt: str, *args: str) -> None:\n        fmt = fmt.replace(\"\\n\", \"\\\\n\")\n        self.emit_line(\"printf(%s);\" % \", \".join(['\"%s\"' % fmt] + list(args)))\n        self.emit_line(\"fflush(stdout);\")\n\n    def temp_name(self) -> str:\n        self.context.temp_counter += 1\n        return \"__tmp%d\" % self.context.temp_counter\n\n    def new_label(self) -> str:\n        self.context.temp_counter += 1\n        return \"__LL%d\" % self.context.temp_counter\n\n    def get_module_group_prefix(self, module_name: str) -> str:\n        \"\"\"Get the group prefix for a module (relative to the current group).\n\n        The prefix should be prepended to the object name whenever\n        accessing an object from this module.\n\n        If the module lives is in the current compilation group, there is\n        no prefix.  But if it lives in a different group (and hence a separate\n        extension module), we need to access objects from it indirectly via an\n        export table.\n\n        For example, for code in group `a` to call a function `bar` in group `b`,\n        it would need to do `exports_b.CPyDef_bar(...)`, while code that is\n        also in group `b` can simply do `CPyDef_bar(...)`.\n\n        Thus the prefix for a module in group `b` is 'exports_b.' if the current\n        group is *not* b and just '' if it is.\n        \"\"\"\n        groups = self.context.group_map\n        target_group_name = groups.get(module_name)\n        if target_group_name and target_group_name != self.context.group_name:\n            self.context.group_deps.add(target_group_name)\n            return f\"exports_{exported_name(target_group_name)}.\"\n        else:\n            return \"\"\n\n    def get_group_prefix(self, obj: ClassIR | FuncDecl) -> str:\n        \"\"\"Get the group prefix for an object.\"\"\"\n        # See docs above\n        return self.get_module_group_prefix(obj.module_name)\n\n    def static_name(self, id: str, module: str | None, prefix: str = STATIC_PREFIX) -> str:\n        \"\"\"Create name of a C static variable.\n\n        These are used for literals and imported modules, among other\n        things.\n\n        The caller should ensure that the (id, module) pair cannot\n        overlap with other calls to this method within a compilation\n        group.\n        \"\"\"\n        lib_prefix = \"\" if not module else self.get_module_group_prefix(module)\n        # If we are accessing static via the export table, we need to dereference\n        # the pointer also.\n        star_maybe = \"*\" if lib_prefix else \"\"\n        suffix = self.names.private_name(module or \"\", id)\n        return f\"{star_maybe}{lib_prefix}{prefix}{suffix}\"\n\n    def type_struct_name(self, cl: ClassIR) -> str:\n        return self.static_name(cl.name, cl.module_name, prefix=TYPE_PREFIX)\n\n    def ctype(self, rtype: RType) -> str:\n        return rtype._ctype\n\n    def ctype_spaced(self, rtype: RType) -> str:\n        \"\"\"Adds a space after ctype for non-pointers.\"\"\"\n        ctype = self.ctype(rtype)\n        if ctype[-1] == \"*\":\n            return ctype\n        else:\n            return ctype + \" \"\n\n    def set_undefined_value(self, target: str, rtype: RType) -> None:\n        if isinstance(rtype, RVec):\n            self.emit_line(f\"{target}.len = -1;\")\n            self.emit_line(f\"{target}.buf = NULL;\")\n        else:\n            self.emit_line(f\"{target} = {self.c_undefined_value(rtype)};\")\n\n    def c_undefined_value(self, rtype: RType) -> str:\n        if not rtype.is_unboxed:\n            return \"NULL\"\n        elif isinstance(rtype, RPrimitive):\n            return rtype.c_undefined\n        elif isinstance(rtype, RTuple):\n            return self.tuple_undefined_value(rtype)\n        elif isinstance(rtype, RVec):\n            return f\"({self.ctype(rtype)}) {{ -1, NULL }}\"\n        assert False, rtype\n\n    def c_error_value(self, rtype: RType) -> str:\n        return self.c_undefined_value(rtype)\n\n    def native_function_name(self, fn: FuncDecl) -> str:\n        return f\"{NATIVE_PREFIX}{fn.cname(self.names)}\"\n\n    def tuple_c_declaration(self, rtuple: RTuple) -> list[str]:\n        result = [\n            f\"#ifndef MYPYC_DECLARED_{rtuple.struct_name}\",\n            f\"#define MYPYC_DECLARED_{rtuple.struct_name}\",\n            f\"typedef struct {rtuple.struct_name} {{\",\n        ]\n        if len(rtuple.types) == 0:  # empty tuple\n            # Empty tuples contain a flag so that they can still indicate\n            # error values.\n            result.append(\"int empty_struct_error_flag;\")\n        else:\n            i = 0\n            for typ in rtuple.types:\n                result.append(f\"{self.ctype_spaced(typ)}f{i};\")\n                i += 1\n        result.append(f\"}} {rtuple.struct_name};\")\n        result.append(\"#endif\")\n        result.append(\"\")\n\n        return result\n\n    def bitmap_field(self, index: int) -> str:\n        \"\"\"Return C field name used for attribute bitmap.\"\"\"\n        n = index // BITMAP_BITS\n        if n == 0:\n            return \"bitmap\"\n        return f\"bitmap{n + 1}\"\n\n    def attr_bitmap_expr(self, obj: str, cl: ClassIR, index: int) -> str:\n        \"\"\"Return reference to the attribute definedness bitmap.\"\"\"\n        cast = f\"({cl.struct_name(self.names)} *)\"\n        attr = self.bitmap_field(index)\n        return f\"({cast}{obj})->{attr}\"\n\n    def emit_attr_bitmap_set(\n        self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str\n    ) -> None:\n        \"\"\"Mark an attribute as defined in the attribute bitmap.\n\n        Assumes that the attribute is tracked in the bitmap (only some attributes\n        use the bitmap). If 'value' is not equal to the error value, do nothing.\n        \"\"\"\n        self._emit_attr_bitmap_update(value, obj, rtype, cl, attr, clear=False)\n\n    def emit_attr_bitmap_clear(self, obj: str, rtype: RType, cl: ClassIR, attr: str) -> None:\n        \"\"\"Mark an attribute as undefined in the attribute bitmap.\n\n        Unlike emit_attr_bitmap_set, clear unconditionally.\n        \"\"\"\n        self._emit_attr_bitmap_update(\"\", obj, rtype, cl, attr, clear=True)\n\n    def _emit_attr_bitmap_update(\n        self, value: str, obj: str, rtype: RType, cl: ClassIR, attr: str, clear: bool\n    ) -> None:\n        if value:\n            check = self.error_value_check(rtype, value, \"==\")\n            self.emit_line(f\"if (unlikely({check})) {{\")\n        index = cl.bitmap_attrs.index(attr)\n        mask = 1 << (index & (BITMAP_BITS - 1))\n        bitmap = self.attr_bitmap_expr(obj, cl, index)\n        if clear:\n            self.emit_line(f\"{bitmap} &= ~{mask};\")\n        else:\n            self.emit_line(f\"{bitmap} |= {mask};\")\n        if value:\n            self.emit_line(\"}\")\n\n    def emit_undefined_attr_check(\n        self,\n        rtype: RType,\n        attr_expr: str,\n        compare: str,\n        obj: str,\n        attr: str,\n        cl: ClassIR,\n        *,\n        unlikely: bool = False,\n    ) -> None:\n        check = self.error_value_check(rtype, attr_expr, compare)\n        if unlikely:\n            check = f\"unlikely({check})\"\n        if rtype.error_overlap:\n            index = cl.bitmap_attrs.index(attr)\n            bit = 1 << (index & (BITMAP_BITS - 1))\n            attr = self.bitmap_field(index)\n            obj_expr = f\"({cl.struct_name(self.names)} *){obj}\"\n            check = f\"{check} && !(({obj_expr})->{attr} & {bit})\"\n        self.emit_line(f\"if ({check}) {{\")\n\n    def error_value_check(self, rtype: RType, value: str, compare: str) -> str:\n        if isinstance(rtype, RTuple):\n            return self.tuple_undefined_check_cond(\n                rtype, value, self.c_error_value, compare, check_exception=False\n            )\n        elif isinstance(rtype, RVec):\n            if compare == \"==\":\n                return f\"{value}.len < 0\"\n            elif compare == \"!=\":\n                return f\"{value}.len >= 0\"\n            assert False, compare\n        else:\n            return f\"{value} {compare} {self.c_error_value(rtype)}\"\n\n    def tuple_undefined_check_cond(\n        self,\n        rtuple: RTuple,\n        tuple_expr_in_c: str,\n        c_type_compare_val: Callable[[RType], str],\n        compare: str,\n        *,\n        check_exception: bool = True,\n    ) -> str:\n        if len(rtuple.types) == 0:\n            # empty tuple\n            return \"{}.empty_struct_error_flag {} {}\".format(\n                tuple_expr_in_c, compare, c_type_compare_val(int_rprimitive)\n            )\n        if rtuple.error_overlap:\n            i = 0\n            item_type = rtuple.types[0]\n        else:\n            for i, typ in enumerate(rtuple.types):\n                if not typ.error_overlap:\n                    item_type = rtuple.types[i]\n                    break\n            else:\n                assert False, \"not expecting tuple with error overlap\"\n        if isinstance(item_type, RTuple):\n            return self.tuple_undefined_check_cond(\n                item_type, tuple_expr_in_c + f\".f{i}\", c_type_compare_val, compare\n            )\n        elif isinstance(item_type, RVec):\n            return f\"{tuple_expr_in_c}.f{i}.len {compare} -1\"\n        else:\n            check = f\"{tuple_expr_in_c}.f{i} {compare} {c_type_compare_val(item_type)}\"\n            if rtuple.error_overlap and check_exception:\n                check += \" && PyErr_Occurred()\"\n            return check\n\n    def tuple_undefined_value(self, rtuple: RTuple) -> str:\n        \"\"\"Undefined tuple value suitable in an expression.\"\"\"\n        return f\"({rtuple.struct_name}) {self.c_initializer_undefined_value(rtuple)}\"\n\n    def c_initializer_undefined_value(self, rtype: RType) -> str:\n        \"\"\"Undefined value represented in a form suitable for variable initialization.\"\"\"\n        if isinstance(rtype, RTuple):\n            if not rtype.types:\n                # Empty tuples contain a flag so that they can still indicate\n                # error values.\n                return f\"{{ {int_rprimitive.c_undefined} }}\"\n            items = \", \".join([self.c_initializer_undefined_value(t) for t in rtype.types])\n            return f\"{{ {items} }}\"\n        elif isinstance(rtype, RVec):\n            return \"{ -1, NULL }\"\n        else:\n            return self.c_undefined_value(rtype)\n\n    # Higher-level operations\n\n    def declare_tuple_struct(self, tuple_type: RTuple) -> None:\n        if tuple_type.struct_name not in self.context.declarations:\n            dependencies = set()\n            for typ in tuple_type.types:\n                # XXX other types might eventually need similar behavior\n                if isinstance(typ, RTuple):\n                    dependencies.add(typ.struct_name)\n\n            self.context.declarations[tuple_type.struct_name] = HeaderDeclaration(\n                self.tuple_c_declaration(tuple_type), dependencies=dependencies, is_type=True\n            )\n\n    def emit_inc_ref(self, dest: str, rtype: RType, *, rare: bool = False) -> None:\n        \"\"\"Increment reference count of C expression `dest`.\n\n        For composite unboxed structures (e.g. tuples) recursively\n        increment reference counts for each component.\n\n        If rare is True, optimize for code size and compilation speed.\n        \"\"\"\n        if is_int_rprimitive(rtype):\n            if rare:\n                self.emit_line(\"CPyTagged_IncRef(%s);\" % dest)\n            else:\n                self.emit_line(\"CPyTagged_INCREF(%s);\" % dest)\n        elif isinstance(rtype, RTuple):\n            for i, item_type in enumerate(rtype.types):\n                self.emit_inc_ref(f\"{dest}.f{i}\", item_type)\n        elif isinstance(rtype, RVec):\n            # TODO: Only use the X variant if buf can be NULL\n            self.emit_line(f\"Py_XINCREF({dest}.buf);\")\n        elif not rtype.is_unboxed:\n            # Always inline, since this is a simple but very hot op\n            if rtype.may_be_immortal or not HAVE_IMMORTAL:\n                self.emit_line(\"CPy_INCREF(%s);\" % dest)\n            else:\n                self.emit_line(\"CPy_INCREF_NO_IMM(%s);\" % dest)\n        # Otherwise assume it's an unboxed, pointerless value and do nothing.\n\n    def emit_dec_ref(\n        self, dest: str, rtype: RType, *, is_xdec: bool = False, rare: bool = False\n    ) -> None:\n        \"\"\"Decrement reference count of C expression `dest`.\n\n        For composite unboxed structures (e.g. tuples) recursively\n        decrement reference counts for each component.\n\n        If rare is True, optimize for code size and compilation speed.\n        \"\"\"\n        x = \"X\" if is_xdec else \"\"\n        if is_int_rprimitive(rtype):\n            if rare:\n                self.emit_line(f\"CPyTagged_{x}DecRef({dest});\")\n            else:\n                # Inlined\n                self.emit_line(f\"CPyTagged_{x}DECREF({dest});\")\n        elif isinstance(rtype, RTuple):\n            for i, item_type in enumerate(rtype.types):\n                self.emit_dec_ref(f\"{dest}.f{i}\", item_type, is_xdec=is_xdec, rare=rare)\n        elif isinstance(rtype, RVec):\n            # TODO: Only use the X variant if buf can be NULL\n            if rare:\n                self.emit_line(f\"CPy_XDecRef({dest}.buf);\")\n            else:\n                self.emit_line(f\"CPy_XDECREF({dest}.buf);\")\n        elif not rtype.is_unboxed:\n            if rare:\n                self.emit_line(f\"CPy_{x}DecRef({dest});\")\n            else:\n                # Inlined\n                if rtype.may_be_immortal or not HAVE_IMMORTAL:\n                    self.emit_line(f\"CPy_{x}DECREF({dest});\")\n                else:\n                    self.emit_line(f\"CPy_{x}DECREF_NO_IMM({dest});\")\n        elif rtype.is_refcounted:\n            assert False, f\"dec_ref not implemented for {rtype}\"\n        # Otherwise assume it's an unboxed, pointerless value and do nothing.\n\n    def pretty_name(self, typ: RType) -> str:\n        value_type = optional_value_type(typ)\n        if value_type is not None:\n            return \"%s or None\" % self.pretty_name(value_type)\n        return str(typ)\n\n    def emit_cast(\n        self,\n        src: str,\n        dest: str,\n        typ: RType,\n        *,\n        declare_dest: bool = False,\n        error: ErrorHandler | None = None,\n        raise_exception: bool = True,\n        optional: bool = False,\n        src_type: RType | None = None,\n        likely: bool = True,\n    ) -> None:\n        \"\"\"Emit code for casting a value of given type.\n\n        Somewhat strangely, this supports unboxed types but only\n        operates on boxed versions.  This is necessary to properly\n        handle types such as Optional[int] in compatibility glue.\n\n        By default, assign NULL (error value) to dest if the value has\n        an incompatible type and raise TypeError. These can be customized\n        using 'error' and 'raise_exception'.\n\n        Always copy/steal the reference in 'src'.\n\n        Args:\n            src: Name of source C variable\n            dest: Name of target C variable\n            typ: Type of value\n            declare_dest: If True, also declare the variable 'dest'\n            error: What happens on error\n            raise_exception: If True, also raise TypeError on failure\n            likely: If the cast is likely to succeed (can be False for unions)\n        \"\"\"\n        error = error or AssignHandler()\n\n        # Special case casting *from* optional\n        if src_type and is_optional_type(src_type) and not is_object_rprimitive(typ):\n            value_type = optional_value_type(src_type)\n            assert value_type is not None\n            if is_same_type(value_type, typ):\n                if declare_dest:\n                    self.emit_line(f\"PyObject *{dest};\")\n                check = \"({} != Py_None)\"\n                if likely:\n                    check = f\"(likely{check})\"\n                self.emit_arg_check(src, dest, typ, check.format(src), optional)\n                self.emit_lines(f\"    {dest} = {src};\", \"else {\")\n                self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n                self.emit_line(\"}\")\n                return\n\n        # TODO: Verify refcount handling.\n        if (\n            is_list_rprimitive(typ)\n            or is_dict_rprimitive(typ)\n            or is_set_rprimitive(typ)\n            or is_frozenset_rprimitive(typ)\n            or is_str_rprimitive(typ)\n            or is_range_rprimitive(typ)\n            or is_float_rprimitive(typ)\n            or is_int_rprimitive(typ)\n            or is_bool_or_bit_rprimitive(typ)\n            or is_fixed_width_rtype(typ)\n        ):\n            if declare_dest:\n                self.emit_line(f\"PyObject *{dest};\")\n            if is_list_rprimitive(typ):\n                prefix = \"PyList\"\n            elif is_dict_rprimitive(typ):\n                prefix = \"PyDict\"\n            elif is_set_rprimitive(typ):\n                prefix = \"PySet\"\n            elif is_frozenset_rprimitive(typ):\n                prefix = \"PyFrozenSet\"\n            elif is_str_rprimitive(typ):\n                prefix = \"PyUnicode\"\n            elif is_range_rprimitive(typ):\n                prefix = \"PyRange\"\n            elif is_float_rprimitive(typ):\n                prefix = \"CPyFloat\"\n            elif is_int_rprimitive(typ) or is_fixed_width_rtype(typ):\n                # TODO: Range check for fixed-width types?\n                prefix = \"PyLong\"\n            elif is_bool_or_bit_rprimitive(typ):\n                prefix = \"PyBool\"\n            else:\n                assert False, f\"unexpected primitive type: {typ}\"\n            check = \"({}_Check({}))\"\n            if likely:\n                check = f\"(likely{check})\"\n            self.emit_arg_check(src, dest, typ, check.format(prefix, src), optional)\n            self.emit_lines(f\"    {dest} = {src};\", \"else {\")\n            self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n            self.emit_line(\"}\")\n        elif is_bytes_rprimitive(typ):\n            if declare_dest:\n                self.emit_line(f\"PyObject *{dest};\")\n            check = \"(PyBytes_Check({}))\"\n            if likely:\n                check = f\"(likely{check})\"\n            self.emit_arg_check(src, dest, typ, check.format(src, src), optional)\n            self.emit_lines(f\"    {dest} = {src};\", \"else {\")\n            self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n            self.emit_line(\"}\")\n        elif is_bytearray_rprimitive(typ):\n            if declare_dest:\n                self.emit_line(f\"PyObject *{dest};\")\n            check = \"(PyByteArray_Check({}))\"\n            if likely:\n                check = f\"(likely{check})\"\n            self.emit_arg_check(src, dest, typ, check.format(src, src), optional)\n            self.emit_lines(f\"    {dest} = {src};\", \"else {\")\n            self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n            self.emit_line(\"}\")\n        elif is_tuple_rprimitive(typ):\n            if declare_dest:\n                self.emit_line(f\"{self.ctype(typ)} {dest};\")\n            check = \"(PyTuple_Check({}))\"\n            if likely:\n                check = f\"(likely{check})\"\n            self.emit_arg_check(src, dest, typ, check.format(src), optional)\n            self.emit_lines(f\"    {dest} = {src};\", \"else {\")\n            self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n            self.emit_line(\"}\")\n        elif isinstance(typ, RInstance):\n            if declare_dest:\n                self.emit_line(f\"PyObject *{dest};\")\n            concrete = all_concrete_classes(typ.class_ir)\n            # If there are too many concrete subclasses or we can't find any\n            # (meaning the code ought to be dead or we aren't doing global opts),\n            # fall back to a normal typecheck.\n            # Otherwise check all the subclasses.\n            if not concrete or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1:\n                check = \"(PyObject_TypeCheck({}, {}))\".format(\n                    src, self.type_struct_name(typ.class_ir)\n                )\n            else:\n                full_str = \"(Py_TYPE({src}) == {targets[0]})\"\n                for i in range(1, len(concrete)):\n                    full_str += \" || (Py_TYPE({src}) == {targets[%d]})\" % i\n                if len(concrete) > 1:\n                    full_str = \"(%s)\" % full_str\n                check = full_str.format(\n                    src=src, targets=[self.type_struct_name(ir) for ir in concrete]\n                )\n            if likely:\n                check = f\"(likely{check})\"\n            self.emit_arg_check(src, dest, typ, check, optional)\n            self.emit_lines(f\"    {dest} = {src};\", \"else {\")\n            self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n            self.emit_line(\"}\")\n        elif is_none_rprimitive(typ):\n            if declare_dest:\n                self.emit_line(f\"PyObject *{dest};\")\n            check = \"({} == Py_None)\"\n            if likely:\n                check = f\"(likely{check})\"\n            self.emit_arg_check(src, dest, typ, check.format(src), optional)\n            self.emit_lines(f\"    {dest} = {src};\", \"else {\")\n            self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n            self.emit_line(\"}\")\n        elif is_object_rprimitive(typ):\n            if declare_dest:\n                self.emit_line(f\"PyObject *{dest};\")\n            self.emit_arg_check(src, dest, typ, \"\", optional)\n            self.emit_line(f\"{dest} = {src};\")\n            if optional:\n                self.emit_line(\"}\")\n        elif is_native_rprimitive(typ):\n            # Native primitive types have type check functions of form \"CPy<Name>_Check(...)\".\n            if declare_dest:\n                self.emit_line(f\"PyObject *{dest};\")\n            short_name = typ.name.rsplit(\".\", 1)[-1]\n            check = f\"(CPy{short_name}_Check({src}))\"\n            if likely:\n                check = f\"(likely{check})\"\n            self.emit_arg_check(src, dest, typ, check, optional)\n            self.emit_lines(f\"    {dest} = {src};\", \"else {\")\n            self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n            self.emit_line(\"}\")\n        elif isinstance(typ, RUnion):\n            self.emit_union_cast(\n                src, dest, typ, declare_dest, error, optional, src_type, raise_exception\n            )\n        elif isinstance(typ, RTuple):\n            assert not optional\n            self.emit_tuple_cast(src, dest, typ, declare_dest, error, src_type)\n        elif isinstance(typ, RVec):\n            if declare_dest:\n                self.emit_line(f\"PyObject *{dest};\")\n            # Build type check expression based on vec kind\n            api_name = vec_api_by_item_type.get(typ.item_type)\n            depth = typ.depth()\n            if api_name:\n                # Specialized vec types (vec[i64], vec[i32], etc.)\n                check = f\"(Py_TYPE({src}) == {api_name}.boxed_type)\"\n            elif depth == 0:\n                # Generic vec types (vec[T], vec[T | None]) with reference type items\n                item_type_c = self.vec_item_type_c(typ)\n                check = (\n                    f\"(Py_TYPE({src}) == VecTApi.boxed_type && \"\n                    f\"((VecTObject *){src})->vec.buf->item_type == {item_type_c})\"\n                )\n            else:\n                # Nested vec types (vec[vec[...]]). Check boxed type, item type, and depth.\n                unwrapped = typ.unwrap_item_type()\n                if unwrapped in vec_item_type_tags:\n                    type_value = str(vec_item_type_tags[unwrapped])\n                else:\n                    type_value = self.vec_item_type_c(typ)\n                check = (\n                    f\"(Py_TYPE({src}) == VecNestedApi.boxed_type && \"\n                    f\"((VecNestedObject *){src})->vec.buf->item_type == {type_value} && \"\n                    f\"((VecNestedObject *){src})->vec.buf->depth == {depth})\"\n                )\n            if likely:\n                check = f\"(likely{check})\"\n            self.emit_arg_check(src, dest, typ, check, optional)\n            self.emit_lines(f\"    {dest} = {src};\", \"else {\")\n            self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n            self.emit_line(\"}\")\n        else:\n            assert False, \"Cast not implemented: %s\" % typ\n\n    def emit_cast_error_handler(\n        self, error: ErrorHandler, src: str, dest: str, typ: RType, raise_exception: bool\n    ) -> None:\n        if raise_exception:\n            if isinstance(error, TracebackAndGotoHandler):\n                # Merge raising and emitting traceback entry into a single call.\n                self.emit_type_error_traceback(\n                    error.source_path, error.module_name, error.traceback_entry, typ=typ, src=src\n                )\n                self.emit_line(\"goto %s;\" % error.label)\n                return\n            self.emit_line(f'CPy_TypeError(\"{self.pretty_name(typ)}\", {src}); ')\n        if isinstance(error, AssignHandler):\n            self.emit_line(\"%s = NULL;\" % dest)\n        elif isinstance(error, GotoHandler):\n            self.emit_line(\"goto %s;\" % error.label)\n        elif isinstance(error, TracebackAndGotoHandler):\n            self.emit_line(\"%s = NULL;\" % dest)\n            self.emit_traceback(error.source_path, error.module_name, error.traceback_entry)\n            self.emit_line(\"goto %s;\" % error.label)\n        else:\n            assert isinstance(error, ReturnHandler), error\n            self.emit_line(\"return %s;\" % error.value)\n\n    def emit_union_cast(\n        self,\n        src: str,\n        dest: str,\n        typ: RUnion,\n        declare_dest: bool,\n        error: ErrorHandler,\n        optional: bool,\n        src_type: RType | None,\n        raise_exception: bool,\n    ) -> None:\n        \"\"\"Emit cast to a union type.\n\n        The arguments are similar to emit_cast.\n        \"\"\"\n        if declare_dest:\n            self.emit_line(f\"PyObject *{dest};\")\n        good_label = self.new_label()\n        if optional:\n            self.emit_line(f\"if ({src} == NULL) {{\")\n            self.emit_line(f\"{dest} = {self.c_error_value(typ)};\")\n            self.emit_line(f\"goto {good_label};\")\n            self.emit_line(\"}\")\n        for item in typ.items:\n            self.emit_cast(\n                src,\n                dest,\n                item,\n                declare_dest=False,\n                raise_exception=False,\n                optional=False,\n                likely=False,\n            )\n            self.emit_line(f\"if ({dest} != NULL) goto {good_label};\")\n        # Handle cast failure.\n        self.emit_cast_error_handler(error, src, dest, typ, raise_exception)\n        self.emit_label(good_label)\n\n    def emit_tuple_cast(\n        self,\n        src: str,\n        dest: str,\n        typ: RTuple,\n        declare_dest: bool,\n        error: ErrorHandler,\n        src_type: RType | None,\n    ) -> None:\n        \"\"\"Emit cast to a tuple type.\n\n        The arguments are similar to emit_cast.\n        \"\"\"\n        if declare_dest:\n            self.emit_line(f\"PyObject *{dest};\")\n        # This reuse of the variable is super dodgy. We don't even\n        # care about the values except to check whether they are\n        # invalid.\n        out_label = self.new_label()\n        self.emit_lines(\n            \"if (unlikely(!(PyTuple_Check({r}) && PyTuple_GET_SIZE({r}) == {size}))) {{\".format(\n                r=src, size=len(typ.types)\n            ),\n            f\"{dest} = NULL;\",\n            f\"goto {out_label};\",\n            \"}\",\n        )\n        for i, item in enumerate(typ.types):\n            # Since we did the checks above this should never fail\n            self.emit_cast(\n                f\"PyTuple_GET_ITEM({src}, {i})\",\n                dest,\n                item,\n                declare_dest=False,\n                raise_exception=False,\n                optional=False,\n            )\n            self.emit_line(f\"if ({dest} == NULL) goto {out_label};\")\n\n        self.emit_line(f\"{dest} = {src};\")\n        self.emit_label(out_label)\n\n    def emit_arg_check(self, src: str, dest: str, typ: RType, check: str, optional: bool) -> None:\n        if optional:\n            self.emit_line(f\"if ({src} == NULL) {{\")\n            self.emit_line(f\"{dest} = {self.c_error_value(typ)};\")\n        if check != \"\":\n            self.emit_line(\"{}if {}\".format(\"} else \" if optional else \"\", check))\n        elif optional:\n            self.emit_line(\"else {\")\n\n    def emit_unbox(\n        self,\n        src: str,\n        dest: str,\n        typ: RType,\n        *,\n        declare_dest: bool = False,\n        error: ErrorHandler | None = None,\n        raise_exception: bool = True,\n        optional: bool = False,\n        borrow: bool = False,\n    ) -> None:\n        \"\"\"Emit code for unboxing a value of given type (from PyObject *).\n\n        By default, assign error value to dest if the value has an\n        incompatible type and raise TypeError. These can be customized\n        using 'error' and 'raise_exception'.\n\n        Generate a new reference unless 'borrow' is True.\n\n        Args:\n            src: Name of source C variable\n            dest: Name of target C variable\n            typ: Type of value\n            declare_dest: If True, also declare the variable 'dest'\n            error: What happens on error\n            raise_exception: If True, also raise TypeError on failure\n            optional: If True, NULL src value is allowed and will map to error value\n            borrow: If True, create a borrowed reference\n\n        \"\"\"\n        error = error or AssignHandler()\n        # TODO: Verify refcount handling.\n        if isinstance(error, AssignHandler):\n            failure = f\"{dest} = {self.c_error_value(typ)};\"\n        elif isinstance(error, GotoHandler):\n            failure = \"goto %s;\" % error.label\n        else:\n            assert isinstance(error, ReturnHandler), error\n            failure = \"return %s;\" % error.value\n        if raise_exception:\n            raise_exc = f'CPy_TypeError(\"{self.pretty_name(typ)}\", {src}); '\n            failure = raise_exc + failure\n        if is_int_rprimitive(typ) or is_short_int_rprimitive(typ):\n            if declare_dest:\n                self.emit_line(f\"CPyTagged {dest};\")\n            self.emit_arg_check(src, dest, typ, f\"(likely(PyLong_Check({src})))\", optional)\n            if borrow:\n                self.emit_line(f\"    {dest} = CPyTagged_BorrowFromObject({src});\")\n            else:\n                self.emit_line(f\"    {dest} = CPyTagged_FromObject({src});\")\n            self.emit_line(\"else {\")\n            self.emit_line(failure)\n            self.emit_line(\"}\")\n        elif is_bool_or_bit_rprimitive(typ):\n            # Whether we are borrowing or not makes no difference.\n            if declare_dest:\n                self.emit_line(f\"char {dest};\")\n            self.emit_arg_check(src, dest, typ, f\"(unlikely(!PyBool_Check({src}))) {{\", optional)\n            self.emit_line(failure)\n            self.emit_line(\"} else\")\n            conversion = f\"{src} == Py_True\"\n            self.emit_line(f\"    {dest} = {conversion};\")\n        elif is_none_rprimitive(typ):\n            # Whether we are borrowing or not makes no difference.\n            if declare_dest:\n                self.emit_line(f\"char {dest};\")\n            self.emit_arg_check(src, dest, typ, f\"(unlikely({src} != Py_None)) {{\", optional)\n            self.emit_line(failure)\n            self.emit_line(\"} else\")\n            self.emit_line(f\"    {dest} = 1;\")\n        elif is_int64_rprimitive(typ):\n            # Whether we are borrowing or not makes no difference.\n            assert not optional  # Not supported for overlapping error values\n            if declare_dest:\n                self.emit_line(f\"int64_t {dest};\")\n            self.emit_line(f\"{dest} = CPyLong_AsInt64({src});\")\n            if not isinstance(error, AssignHandler):\n                self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)\n        elif is_int32_rprimitive(typ):\n            # Whether we are borrowing or not makes no difference.\n            assert not optional  # Not supported for overlapping error values\n            if declare_dest:\n                self.emit_line(f\"int32_t {dest};\")\n            self.emit_line(f\"{dest} = CPyLong_AsInt32({src});\")\n            if not isinstance(error, AssignHandler):\n                self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)\n        elif is_int16_rprimitive(typ):\n            # Whether we are borrowing or not makes no difference.\n            assert not optional  # Not supported for overlapping error values\n            if declare_dest:\n                self.emit_line(f\"int16_t {dest};\")\n            self.emit_line(f\"{dest} = CPyLong_AsInt16({src});\")\n            if not isinstance(error, AssignHandler):\n                self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)\n        elif is_uint8_rprimitive(typ):\n            # Whether we are borrowing or not makes no difference.\n            assert not optional  # Not supported for overlapping error values\n            if declare_dest:\n                self.emit_line(f\"uint8_t {dest};\")\n            self.emit_line(f\"{dest} = CPyLong_AsUInt8({src});\")\n            if not isinstance(error, AssignHandler):\n                self.emit_unbox_failure_with_overlapping_error_value(dest, typ, failure)\n        elif is_float_rprimitive(typ):\n            assert not optional  # Not supported for overlapping error values\n            if declare_dest:\n                self.emit_line(f\"double {dest};\")\n            # TODO: Don't use __float__ and __index__\n            self.emit_line(f\"{dest} = PyFloat_AsDouble({src});\")\n            self.emit_lines(f\"if ({dest} == -1.0 && PyErr_Occurred()) {{\", failure, \"}\")\n        elif isinstance(typ, RTuple):\n            self.declare_tuple_struct(typ)\n            if declare_dest:\n                self.emit_line(f\"{self.ctype(typ)} {dest};\")\n            # HACK: The error handling for unboxing tuples is busted\n            # and instead of fixing it I am just wrapping it in the\n            # cast code which I think is right. This is not good.\n            if optional:\n                self.emit_line(f\"if ({src} == NULL) {{\")\n                self.emit_line(f\"{dest} = {self.c_error_value(typ)};\")\n                self.emit_line(\"} else {\")\n\n            cast_temp = self.temp_name()\n            self.emit_tuple_cast(\n                src, cast_temp, typ, declare_dest=True, error=error, src_type=None\n            )\n            self.emit_line(f\"if (unlikely({cast_temp} == NULL)) {{\")\n\n            # self.emit_arg_check(src, dest, typ,\n            #     '(!PyTuple_Check({}) || PyTuple_Size({}) != {}) {{'.format(\n            #         src, src, len(typ.types)), optional)\n            self.emit_line(failure)  # TODO: Decrease refcount?\n            self.emit_line(\"} else {\")\n            if not typ.types:\n                self.emit_line(f\"{dest}.empty_struct_error_flag = 0;\")\n            for i, item_type in enumerate(typ.types):\n                temp = self.temp_name()\n                # emit_tuple_cast above checks the size, so this should not fail\n                self.emit_line(f\"PyObject *{temp} = PyTuple_GET_ITEM({src}, {i});\")\n                temp2 = self.temp_name()\n                # Unbox or check the item.\n                if item_type.is_unboxed:\n                    self.emit_unbox(\n                        temp,\n                        temp2,\n                        item_type,\n                        raise_exception=raise_exception,\n                        error=error,\n                        declare_dest=True,\n                        borrow=borrow,\n                    )\n                else:\n                    if not borrow:\n                        self.emit_inc_ref(temp, object_rprimitive)\n                    self.emit_cast(temp, temp2, item_type, declare_dest=True)\n                self.emit_line(f\"{dest}.f{i} = {temp2};\")\n            self.emit_line(\"}\")\n            if optional:\n                self.emit_line(\"}\")\n        elif isinstance(typ, RVec):\n            if declare_dest:\n                self.emit_line(f\"{self.ctype(typ)} {dest};\")\n\n            if optional:\n                self.emit_line(f\"if ({src} == NULL) {{\")\n                self.emit_line(f\"{dest} = {self.c_error_value(typ)};\")\n                self.emit_line(\"} else {\")\n\n            specialized_api_name = vec_api_by_item_type.get(typ.item_type)\n            if specialized_api_name is not None:\n                self.emit_line(f\"{dest} = {specialized_api_name}.unbox({src});\")\n            else:\n                depth = typ.depth()\n                unwrapped = typ.unwrap_item_type()\n                if unwrapped in vec_item_type_tags:\n                    type_value = str(vec_item_type_tags[unwrapped])\n                else:\n                    type_value = self.vec_item_type_c(typ)\n                if depth == 0:\n                    self.emit_line(f\"{dest} = VecTApi.unbox({src}, {type_value});\")\n                else:\n                    self.emit_line(f\"{dest} = VecNestedApi.unbox({src}, {type_value}, {depth});\")\n\n            self.emit_line(f\"if (VEC_IS_ERROR({dest})) {{\")\n            self.emit_line(failure)\n            self.emit_line(\"}\")\n\n            if optional:\n                self.emit_line(\"}\")\n        else:\n            assert False, \"Unboxing not implemented: %s\" % typ\n\n    def vec_item_type_c(self, typ: RVec) -> str:\n        item_type = typ.unwrap_item_type()\n        type_c_ptr = self.type_c_ptr(item_type)\n        # Can never be None, since we unwrapped the item type above\n        assert type_c_ptr is not None\n        type_value = f\"(size_t){type_c_ptr}\"\n        if typ.is_optional():\n            type_value = f\"({type_value} | 1)\"\n        return type_value\n\n    def type_c_ptr(self, typ: RPrimitive | RInstance) -> str | None:\n        if isinstance(typ, RPrimitive) and typ.is_refcounted:\n            return \"&\" + builtin_names[typ.name][1]\n        elif isinstance(typ, RInstance):\n            return self.type_struct_name(typ.class_ir)\n        return None\n\n    def emit_box(\n        self, src: str, dest: str, typ: RType, declare_dest: bool = False, can_borrow: bool = False\n    ) -> None:\n        \"\"\"Emit code for boxing a value of given type.\n\n        Generate a simple assignment if no boxing is needed.\n\n        The source reference count is stolen for the result (no need to decref afterwards).\n        \"\"\"\n        # TODO: Always generate a new reference (if a reference type)\n        if declare_dest:\n            declaration = \"PyObject *\"\n        else:\n            declaration = \"\"\n        if is_int_rprimitive(typ) or is_short_int_rprimitive(typ):\n            # Steal the existing reference if it exists.\n            self.emit_line(f\"{declaration}{dest} = CPyTagged_StealAsObject({src});\")\n        elif is_bool_or_bit_rprimitive(typ):\n            # N.B: bool is special cased to produce a borrowed value\n            # after boxing, so we don't need to increment the refcount\n            # when this comes directly from a Box op.\n            self.emit_lines(f\"{declaration}{dest} = {src} ? Py_True : Py_False;\")\n            if not can_borrow:\n                self.emit_inc_ref(dest, object_rprimitive)\n        elif is_none_rprimitive(typ):\n            # N.B: None is special cased to produce a borrowed value\n            # after boxing, so we don't need to increment the refcount\n            # when this comes directly from a Box op.\n            self.emit_lines(f\"{declaration}{dest} = Py_None;\")\n            if not can_borrow:\n                self.emit_inc_ref(dest, object_rprimitive)\n        elif is_int32_rprimitive(typ) or is_int16_rprimitive(typ) or is_uint8_rprimitive(typ):\n            self.emit_line(f\"{declaration}{dest} = PyLong_FromLong({src});\")\n        elif is_int64_rprimitive(typ):\n            self.emit_line(f\"{declaration}{dest} = PyLong_FromLongLong({src});\")\n        elif is_float_rprimitive(typ):\n            self.emit_line(f\"{declaration}{dest} = PyFloat_FromDouble({src});\")\n        elif isinstance(typ, RTuple):\n            self.declare_tuple_struct(typ)\n            if not typ.types:\n                self.emit_line(f\"{declaration}{dest} = CPyTuple_LoadEmptyTupleConstant();\")\n            else:\n                self.emit_line(f\"{declaration}{dest} = PyTuple_New({len(typ.types)});\")\n                self.emit_line(f\"if (unlikely({dest} == NULL))\")\n                self.emit_line(\"    CPyError_OutOfMemory();\")\n\n                # TODO: Fail if dest is None\n                for i in range(len(typ.types)):\n                    if not typ.is_unboxed:\n                        self.emit_line(f\"PyTuple_SET_ITEM({dest}, {i}, {src}.f{i}\")\n                    else:\n                        inner_name = self.temp_name()\n                        self.emit_box(f\"{src}.f{i}\", inner_name, typ.types[i], declare_dest=True)\n                        self.emit_line(f\"PyTuple_SET_ITEM({dest}, {i}, {inner_name});\")\n        elif isinstance(typ, RVec):\n            specialized_api_name = vec_api_by_item_type.get(typ.item_type)\n            if specialized_api_name is not None:\n                api = specialized_api_name\n            elif typ.depth() > 0:\n                api = \"VecNestedApi\"\n            else:\n                api = \"VecTApi\"\n                # Empty vecs of this sort don't describe item type, so it needs to be\n                # passed explicitly.\n                item_type = self.vec_item_type_c(typ)\n                self.emit_line(f\"{declaration}{dest} = {api}.box({src}, {item_type});\")\n                return\n            self.emit_line(f\"{declaration}{dest} = {api}.box({src});\")\n        else:\n            assert not typ.is_unboxed\n            # Type is boxed -- trivially just assign.\n            self.emit_line(f\"{declaration}{dest} = {src};\")\n\n    def emit_error_check(self, value: str, rtype: RType, failure: str) -> None:\n        \"\"\"Emit code for checking a native function return value for uncaught exception.\"\"\"\n        if isinstance(rtype, RTuple):\n            if len(rtype.types) == 0:\n                return  # empty tuples can't fail.\n            else:\n                cond = self.tuple_undefined_check_cond(rtype, value, self.c_error_value, \"==\")\n                self.emit_line(f\"if ({cond}) {{\")\n        elif isinstance(rtype, RVec):\n            self.emit_line(f\"if ({value}.len < 0) {{\")\n        elif rtype.error_overlap:\n            # The error value is also valid as a normal value, so we need to also check\n            # for a raised exception.\n            self.emit_line(f\"if ({value} == {self.c_error_value(rtype)} && PyErr_Occurred()) {{\")\n        else:\n            self.emit_line(f\"if ({value} == {self.c_error_value(rtype)}) {{\")\n        self.emit_lines(failure, \"}\")\n\n    def emit_gc_visit(self, target: str, rtype: RType) -> None:\n        \"\"\"Emit code for GC visiting a C variable reference.\n\n        Assume that 'target' represents a C expression that refers to a\n        struct member, such as 'self->x'.\n        \"\"\"\n        if not rtype.is_refcounted:\n            # Not refcounted -> no pointers -> no GC interaction.\n            return\n        elif isinstance(rtype, RPrimitive) and rtype.name == \"builtins.int\":\n            self.emit_line(f\"if (CPyTagged_CheckLong({target})) {{\")\n            self.emit_line(f\"Py_VISIT(CPyTagged_LongAsObject({target}));\")\n            self.emit_line(\"}\")\n        elif isinstance(rtype, RTuple):\n            for i, item_type in enumerate(rtype.types):\n                self.emit_gc_visit(f\"{target}.f{i}\", item_type)\n        elif isinstance(rtype, RVec):\n            self.emit_line(f\"Py_VISIT({target}.buf);\")\n        elif self.ctype(rtype) == \"PyObject *\":\n            # The simplest case.\n            self.emit_line(f\"Py_VISIT({target});\")\n        else:\n            assert False, \"emit_gc_visit() not implemented for %s\" % repr(rtype)\n\n    def emit_gc_clear(self, target: str, rtype: RType) -> None:\n        \"\"\"Emit code for clearing a C attribute reference for GC.\n\n        Assume that 'target' represents a C expression that refers to a\n        struct member, such as 'self->x'.\n        \"\"\"\n        if not rtype.is_refcounted:\n            # Not refcounted -> no pointers -> no GC interaction.\n            return\n        elif isinstance(rtype, RPrimitive) and rtype.name == \"builtins.int\":\n            self.emit_line(f\"if (CPyTagged_CheckLong({target})) {{\")\n            self.emit_line(f\"CPyTagged __tmp = {target};\")\n            self.emit_line(f\"{target} = {self.c_undefined_value(rtype)};\")\n            self.emit_line(\"Py_XDECREF(CPyTagged_LongAsObject(__tmp));\")\n            self.emit_line(\"}\")\n        elif isinstance(rtype, RTuple):\n            for i, item_type in enumerate(rtype.types):\n                self.emit_gc_clear(f\"{target}.f{i}\", item_type)\n        elif isinstance(rtype, RVec):\n            self.emit_line(f\"Py_CLEAR({target}.buf);\")\n        elif self.ctype(rtype) == \"PyObject *\" and self.c_undefined_value(rtype) == \"NULL\":\n            # The simplest case.\n            self.emit_line(f\"Py_CLEAR({target});\")\n        else:\n            assert False, \"emit_gc_clear() not implemented for %s\" % repr(rtype)\n\n    def emit_reuse_clear(self, target: str, rtype: RType) -> None:\n        \"\"\"Emit attribute clear before object is added into freelist.\n\n        Assume that 'target' represents a C expression that refers to a\n        struct member, such as 'self->x'.\n\n        Unlike emit_gc_clear(), initialize attribute value to match a freshly\n        allocated object.\n        \"\"\"\n        if isinstance(rtype, RTuple):\n            for i, item_type in enumerate(rtype.types):\n                self.emit_reuse_clear(f\"{target}.f{i}\", item_type)\n        elif not rtype.is_refcounted:\n            self.emit_line(f\"{target} = {rtype.c_undefined};\")\n        elif isinstance(rtype, RPrimitive) and rtype.name == \"builtins.int\":\n            self.emit_line(f\"if (CPyTagged_CheckLong({target})) {{\")\n            self.emit_line(f\"CPyTagged __tmp = {target};\")\n            self.emit_line(f\"{target} = {self.c_undefined_value(rtype)};\")\n            self.emit_line(\"Py_XDECREF(CPyTagged_LongAsObject(__tmp));\")\n            self.emit_line(\"} else {\")\n            self.emit_line(f\"{target} = {self.c_undefined_value(rtype)};\")\n            self.emit_line(\"}\")\n        else:\n            self.emit_gc_clear(target, rtype)\n\n    def emit_traceback(\n        self, source_path: str, module_name: str, traceback_entry: tuple[str, int]\n    ) -> None:\n        return self._emit_traceback(\"CPy_AddTraceback\", source_path, module_name, traceback_entry)\n\n    def emit_type_error_traceback(\n        self,\n        source_path: str,\n        module_name: str,\n        traceback_entry: tuple[str, int],\n        *,\n        typ: RType,\n        src: str,\n    ) -> None:\n        func = \"CPy_TypeErrorTraceback\"\n        type_str = f'\"{self.pretty_name(typ)}\"'\n        return self._emit_traceback(\n            func, source_path, module_name, traceback_entry, type_str=type_str, src=src\n        )\n\n    def _emit_traceback(\n        self,\n        func: str,\n        source_path: str,\n        module_name: str,\n        traceback_entry: tuple[str, int],\n        type_str: str = \"\",\n        src: str = \"\",\n    ) -> None:\n        if self.context.strict_traceback_checks:\n            assert traceback_entry[1] >= 0, \"Traceback cannot have a negative line number\"\n        globals_static = self.static_name(\"globals\", module_name)\n        line = '%s(\"%s\", \"%s\", %d, %s' % (\n            func,\n            source_path.replace(\"\\\\\", \"\\\\\\\\\"),\n            traceback_entry[0],\n            traceback_entry[1],\n            globals_static,\n        )\n        if type_str:\n            assert src\n            line += f\", {type_str}, {src}\"\n        line += \");\"\n        self.emit_line(line)\n        if DEBUG_ERRORS:\n            self.emit_line('assert(PyErr_Occurred() != NULL && \"failure w/o err!\");')\n\n    def emit_unbox_failure_with_overlapping_error_value(\n        self, dest: str, typ: RType, failure: str\n    ) -> None:\n        self.emit_line(f\"if ({dest} == {self.c_error_value(typ)} && PyErr_Occurred()) {{\")\n        self.emit_line(failure)\n        self.emit_line(\"}\")\n\n    def emit_cpyfunction_instance(\n        self, fn: FuncIR, name: str, filepath: str, error_stmt: str\n    ) -> str:\n        module = self.static_name(fn.decl.module_name, None, prefix=MODULE_PREFIX)\n        cname = f\"{PREFIX}{fn.cname(self.names)}\"\n        wrapper_name = f\"{cname}_wrapper\"\n        cfunc = f\"(PyCFunction){cname}\"\n        func_flags = \"METH_FASTCALL | METH_KEYWORDS\"\n        doc = f\"PyDoc_STR({native_function_doc_initializer(fn)})\"\n        has_self_arg = \"true\" if fn.class_name and fn.decl.kind != FUNC_STATICMETHOD else \"false\"\n\n        code_flags = \"CO_COROUTINE\"\n        self.emit_line(\n            f'PyObject* {wrapper_name} = CPyFunction_New({module}, \"{filepath}\", \"{name}\", {cfunc}, {func_flags}, {doc}, {fn.line}, {code_flags}, {has_self_arg});'\n        )\n        self.emit_line(f\"if (unlikely(!{wrapper_name}))\")\n        self.emit_line(error_stmt)\n        return wrapper_name\n\n\ndef c_array_initializer(components: list[str], *, indented: bool = False) -> str:\n    \"\"\"Construct an initializer for a C array variable.\n\n    Components are C expressions valid in an initializer.\n\n    For example, if components are [\"1\", \"2\"], the result\n    would be \"{1, 2}\", which can be used like this:\n\n        int a[] = {1, 2};\n\n    If the result is long, split it into multiple lines.\n    \"\"\"\n    indent = \" \" * 4 if indented else \"\"\n    res = []\n    current: list[str] = []\n    cur_len = 0\n    for c in components:\n        if not current or cur_len + 2 + len(indent) + len(c) < 70:\n            current.append(c)\n            cur_len += len(c) + 2\n        else:\n            res.append(indent + \", \".join(current))\n            current = [c]\n            cur_len = len(c)\n    if not res:\n        # Result fits on a single line\n        return \"{%s}\" % \", \".join(current)\n    # Multi-line result\n    res.append(indent + \", \".join(current))\n    return \"{\\n    \" + \",\\n    \".join(res) + \"\\n\" + indent + \"}\"\n\n\ndef native_function_doc_initializer(func: FuncIR) -> str:\n    text_sig = get_text_signature(func)\n    if text_sig is None:\n        return \"NULL\"\n    docstring = f\"{text_sig}\\n--\\n\\n\"\n    return c_string_initializer(docstring.encode(\"ascii\", errors=\"backslashreplace\"))\n"
  },
  {
    "path": "mypyc/codegen/emitclass.py",
    "content": "\"\"\"Code generation for native classes and related wrappers.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable, Mapping\n\nfrom mypy.nodes import ARG_STAR, ARG_STAR2\nfrom mypyc.codegen.cstring import c_string_initializer\nfrom mypyc.codegen.emit import (\n    Emitter,\n    HeaderDeclaration,\n    ReturnHandler,\n    native_function_doc_initializer,\n)\nfrom mypyc.codegen.emitfunc import native_function_header\nfrom mypyc.codegen.emitwrapper import (\n    generate_bin_op_wrapper,\n    generate_bool_wrapper,\n    generate_contains_wrapper,\n    generate_dunder_wrapper,\n    generate_get_wrapper,\n    generate_hash_wrapper,\n    generate_ipow_wrapper,\n    generate_len_wrapper,\n    generate_richcompare_wrapper,\n    generate_set_del_item_wrapper,\n)\nfrom mypyc.common import (\n    BITMAP_BITS,\n    BITMAP_TYPE,\n    CPYFUNCTION_NAME,\n    NATIVE_PREFIX,\n    PREFIX,\n    REG_PREFIX,\n    short_id_from_name,\n)\nfrom mypyc.ir.class_ir import ClassIR, VTableEntries\nfrom mypyc.ir.func_ir import (\n    FUNC_CLASSMETHOD,\n    FUNC_STATICMETHOD,\n    FuncDecl,\n    FuncIR,\n    get_text_signature,\n)\nfrom mypyc.ir.rtypes import RTuple, RType, object_rprimitive\nfrom mypyc.namegen import NameGenerator\nfrom mypyc.sametype import is_same_type\n\n\ndef native_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    return f\"{NATIVE_PREFIX}{fn.cname(emitter.names)}\"\n\n\ndef dunder_attr_slot(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    wrapper_fn = cl.get_method(fn.name + \"__wrapper\")\n    assert wrapper_fn\n    return f\"{NATIVE_PREFIX}{wrapper_fn.cname(emitter.names)}\"\n\n\n# We maintain a table from dunder function names to struct slots they\n# correspond to and functions that generate a wrapper (if necessary)\n# and return the function name to stick in the slot.\n# TODO: Add remaining dunder methods\nSlotGenerator = Callable[[ClassIR, FuncIR, Emitter], str]\nSlotTable = Mapping[str, tuple[str, SlotGenerator]]\n\nSLOT_DEFS: SlotTable = {\n    \"__init__\": (\"tp_init\", lambda c, t, e: generate_init_for_class(c, t, e)),\n    \"__call__\": (\"tp_call\", lambda c, t, e: generate_call_wrapper(c, t, e)),\n    \"__str__\": (\"tp_str\", native_slot),\n    \"__repr__\": (\"tp_repr\", native_slot),\n    \"__next__\": (\"tp_iternext\", native_slot),\n    \"__iter__\": (\"tp_iter\", native_slot),\n    \"__hash__\": (\"tp_hash\", generate_hash_wrapper),\n    \"__get__\": (\"tp_descr_get\", generate_get_wrapper),\n    \"__getattr__\": (\"tp_getattro\", dunder_attr_slot),\n    \"__setattr__\": (\"tp_setattro\", dunder_attr_slot),\n}\n\nAS_MAPPING_SLOT_DEFS: SlotTable = {\n    \"__getitem__\": (\"mp_subscript\", generate_dunder_wrapper),\n    \"__setitem__\": (\"mp_ass_subscript\", generate_set_del_item_wrapper),\n    \"__delitem__\": (\"mp_ass_subscript\", generate_set_del_item_wrapper),\n    \"__len__\": (\"mp_length\", generate_len_wrapper),\n}\n\nAS_SEQUENCE_SLOT_DEFS: SlotTable = {\"__contains__\": (\"sq_contains\", generate_contains_wrapper)}\n\nAS_NUMBER_SLOT_DEFS: SlotTable = {\n    # Unary operations.\n    \"__bool__\": (\"nb_bool\", generate_bool_wrapper),\n    \"__int__\": (\"nb_int\", generate_dunder_wrapper),\n    \"__float__\": (\"nb_float\", generate_dunder_wrapper),\n    \"__neg__\": (\"nb_negative\", generate_dunder_wrapper),\n    \"__pos__\": (\"nb_positive\", generate_dunder_wrapper),\n    \"__abs__\": (\"nb_absolute\", generate_dunder_wrapper),\n    \"__invert__\": (\"nb_invert\", generate_dunder_wrapper),\n    # Binary operations.\n    \"__add__\": (\"nb_add\", generate_bin_op_wrapper),\n    \"__radd__\": (\"nb_add\", generate_bin_op_wrapper),\n    \"__sub__\": (\"nb_subtract\", generate_bin_op_wrapper),\n    \"__rsub__\": (\"nb_subtract\", generate_bin_op_wrapper),\n    \"__mul__\": (\"nb_multiply\", generate_bin_op_wrapper),\n    \"__rmul__\": (\"nb_multiply\", generate_bin_op_wrapper),\n    \"__mod__\": (\"nb_remainder\", generate_bin_op_wrapper),\n    \"__rmod__\": (\"nb_remainder\", generate_bin_op_wrapper),\n    \"__truediv__\": (\"nb_true_divide\", generate_bin_op_wrapper),\n    \"__rtruediv__\": (\"nb_true_divide\", generate_bin_op_wrapper),\n    \"__floordiv__\": (\"nb_floor_divide\", generate_bin_op_wrapper),\n    \"__rfloordiv__\": (\"nb_floor_divide\", generate_bin_op_wrapper),\n    \"__divmod__\": (\"nb_divmod\", generate_bin_op_wrapper),\n    \"__rdivmod__\": (\"nb_divmod\", generate_bin_op_wrapper),\n    \"__lshift__\": (\"nb_lshift\", generate_bin_op_wrapper),\n    \"__rlshift__\": (\"nb_lshift\", generate_bin_op_wrapper),\n    \"__rshift__\": (\"nb_rshift\", generate_bin_op_wrapper),\n    \"__rrshift__\": (\"nb_rshift\", generate_bin_op_wrapper),\n    \"__and__\": (\"nb_and\", generate_bin_op_wrapper),\n    \"__rand__\": (\"nb_and\", generate_bin_op_wrapper),\n    \"__or__\": (\"nb_or\", generate_bin_op_wrapper),\n    \"__ror__\": (\"nb_or\", generate_bin_op_wrapper),\n    \"__xor__\": (\"nb_xor\", generate_bin_op_wrapper),\n    \"__rxor__\": (\"nb_xor\", generate_bin_op_wrapper),\n    \"__matmul__\": (\"nb_matrix_multiply\", generate_bin_op_wrapper),\n    \"__rmatmul__\": (\"nb_matrix_multiply\", generate_bin_op_wrapper),\n    # In-place binary operations.\n    \"__iadd__\": (\"nb_inplace_add\", generate_dunder_wrapper),\n    \"__isub__\": (\"nb_inplace_subtract\", generate_dunder_wrapper),\n    \"__imul__\": (\"nb_inplace_multiply\", generate_dunder_wrapper),\n    \"__imod__\": (\"nb_inplace_remainder\", generate_dunder_wrapper),\n    \"__itruediv__\": (\"nb_inplace_true_divide\", generate_dunder_wrapper),\n    \"__ifloordiv__\": (\"nb_inplace_floor_divide\", generate_dunder_wrapper),\n    \"__ilshift__\": (\"nb_inplace_lshift\", generate_dunder_wrapper),\n    \"__irshift__\": (\"nb_inplace_rshift\", generate_dunder_wrapper),\n    \"__iand__\": (\"nb_inplace_and\", generate_dunder_wrapper),\n    \"__ior__\": (\"nb_inplace_or\", generate_dunder_wrapper),\n    \"__ixor__\": (\"nb_inplace_xor\", generate_dunder_wrapper),\n    \"__imatmul__\": (\"nb_inplace_matrix_multiply\", generate_dunder_wrapper),\n    # Ternary operations. (yes, really)\n    # These are special cased in generate_bin_op_wrapper().\n    \"__pow__\": (\"nb_power\", generate_bin_op_wrapper),\n    \"__rpow__\": (\"nb_power\", generate_bin_op_wrapper),\n    \"__ipow__\": (\"nb_inplace_power\", generate_ipow_wrapper),\n}\n\nAS_ASYNC_SLOT_DEFS: SlotTable = {\n    \"__await__\": (\"am_await\", native_slot),\n    \"__aiter__\": (\"am_aiter\", native_slot),\n    \"__anext__\": (\"am_anext\", native_slot),\n}\n\nSIDE_TABLES = [\n    (\"as_mapping\", \"PyMappingMethods\", AS_MAPPING_SLOT_DEFS),\n    (\"as_sequence\", \"PySequenceMethods\", AS_SEQUENCE_SLOT_DEFS),\n    (\"as_number\", \"PyNumberMethods\", AS_NUMBER_SLOT_DEFS),\n    (\"as_async\", \"PyAsyncMethods\", AS_ASYNC_SLOT_DEFS),\n]\n\n# Slots that need to always be filled in because they don't get\n# inherited right.\nALWAYS_FILL = {\"__hash__\"}\n\n\ndef generate_call_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    return \"PyVectorcall_Call\"\n\n\ndef slot_key(attr: str) -> str:\n    \"\"\"Map dunder method name to sort key.\n\n    Sort reverse operator methods and __delitem__ after others ('x' > '_').\n    \"\"\"\n    if (attr.startswith(\"__r\") and attr != \"__rshift__\") or attr == \"__delitem__\":\n        return \"x\" + attr\n    return attr\n\n\ndef generate_slots(cl: ClassIR, table: SlotTable, emitter: Emitter) -> dict[str, str]:\n    fields: dict[str, str] = {}\n    generated: dict[str, str] = {}\n    # Sort for determinism on Python 3.5\n    for name, (slot, generator) in sorted(table.items(), key=lambda x: slot_key(x[0])):\n        method_cls = cl.get_method_and_class(name)\n        if method_cls and (method_cls[1] == cl or name in ALWAYS_FILL):\n            if slot in generated:\n                # Reuse previously generated wrapper.\n                fields[slot] = generated[slot]\n            else:\n                # Generate new wrapper.\n                name = generator(cl, method_cls[0], emitter)\n                fields[slot] = name\n                generated[slot] = name\n\n    return fields\n\n\ndef generate_class_type_decl(\n    cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter\n) -> None:\n    context = c_emitter.context\n    name = emitter.type_struct_name(cl)\n    context.declarations[name] = HeaderDeclaration(\n        f\"PyTypeObject *{emitter.type_struct_name(cl)};\", needs_export=True\n    )\n\n    # If this is a non-extension class, all we want is the type object decl.\n    if not cl.is_ext_class:\n        return\n\n    generate_object_struct(cl, external_emitter)\n    generate_full = not cl.is_trait and not cl.builtin_base\n    if generate_full:\n        context.declarations[emitter.native_function_name(cl.ctor)] = HeaderDeclaration(\n            f\"{native_function_header(cl.ctor, emitter)};\", needs_export=True\n        )\n\n\ndef generate_class_reuse(\n    cl: ClassIR, c_emitter: Emitter, external_emitter: Emitter, emitter: Emitter\n) -> None:\n    \"\"\"Generate a definition of a single-object per-class free \"list\".\n\n    This speeds up object allocation and freeing when there are many short-lived\n    objects.\n\n    TODO: Generalize to support a free list with up to N objects.\n    \"\"\"\n    assert cl.reuse_freed_instance\n    context = c_emitter.context\n    name = cl.name_prefix(c_emitter.names) + \"_free_instance\"\n    struct_name = cl.struct_name(c_emitter.names)\n    context.declarations[name] = HeaderDeclaration(\n        f\"CPyThreadLocal {struct_name} *{name};\", needs_export=True\n    )\n\n\ndef generate_class(cl: ClassIR, module: str, emitter: Emitter) -> None:\n    \"\"\"Generate C code for a class.\n\n    This is the main entry point to the module.\n    \"\"\"\n    name = cl.name\n    name_prefix = cl.name_prefix(emitter.names)\n\n    setup_name = emitter.native_function_name(cl.setup)\n    new_name = f\"{name_prefix}_new\"\n    finalize_name = f\"{name_prefix}_finalize\"\n    members_name = f\"{name_prefix}_members\"\n    getseters_name = f\"{name_prefix}_getseters\"\n    vtable_name = f\"{name_prefix}_vtable\"\n    traverse_name = f\"{name_prefix}_traverse\"\n    clear_name = f\"{name_prefix}_clear\"\n    dealloc_name = f\"{name_prefix}_dealloc\"\n    methods_name = f\"{name_prefix}_methods\"\n    vtable_setup_name = f\"{name_prefix}_trait_vtable_setup\"\n    coroutine_setup_name = f\"{name_prefix}_coroutine_setup\"\n\n    fields: dict[str, str] = {\"tp_name\": f'\"{name}\"'}\n\n    generate_full = not cl.is_trait and not cl.builtin_base\n    needs_getseters = cl.needs_getseters or not cl.is_generated or cl.has_dict\n\n    if not cl.builtin_base:\n        fields[\"tp_new\"] = new_name\n\n    if generate_full:\n        fields[\"tp_dealloc\"] = f\"(destructor){name_prefix}_dealloc\"\n        if not cl.is_acyclic:\n            fields[\"tp_traverse\"] = f\"(traverseproc){name_prefix}_traverse\"\n            fields[\"tp_clear\"] = f\"(inquiry){name_prefix}_clear\"\n    # Populate .tp_finalize and generate a finalize method only if __del__ is defined for this class.\n    del_method = next((e.method for e in cl.vtable_entries if e.name == \"__del__\"), None)\n    if del_method:\n        fields[\"tp_finalize\"] = f\"(destructor){finalize_name}\"\n    if needs_getseters:\n        fields[\"tp_getset\"] = getseters_name\n    fields[\"tp_methods\"] = methods_name\n\n    def emit_line() -> None:\n        emitter.emit_line()\n\n    emit_line()\n\n    # If the class has a method to initialize default attribute\n    # values, we need to call it during initialization.\n    defaults_fn = cl.get_method(\"__mypyc_defaults_setup\")\n\n    # If there is a __init__ method, we'll use it in the native constructor.\n    init_fn = cl.get_method(\"__init__\")\n\n    # Fill out slots in the type object from dunder methods.\n    fields.update(generate_slots(cl, SLOT_DEFS, emitter))\n\n    # Fill out dunder methods that live in tables hanging off the side.\n    for table_name, type, slot_defs in SIDE_TABLES:\n        slots = generate_slots(cl, slot_defs, emitter)\n        if slots:\n            table_struct_name = generate_side_table_for_class(cl, table_name, type, slots, emitter)\n            fields[f\"tp_{table_name}\"] = f\"&{table_struct_name}\"\n\n    richcompare_name = generate_richcompare_wrapper(cl, emitter)\n    if richcompare_name:\n        fields[\"tp_richcompare\"] = richcompare_name\n\n    # If the class inherits from python, make space for a __dict__\n    struct_name = cl.struct_name(emitter.names)\n    if cl.builtin_base:\n        base_size = f\"sizeof({cl.builtin_base})\"\n    elif cl.is_trait:\n        base_size = \"sizeof(PyObject)\"\n    else:\n        base_size = f\"sizeof({struct_name})\"\n    # Since our types aren't allocated using type() we need to\n    # populate these fields ourselves if we want them to have correct\n    # values. PyType_Ready will inherit the offsets from tp_base but\n    # that isn't what we want.\n\n    # XXX: there is no reason for the __weakref__ stuff to be mixed up with __dict__\n    if cl.has_dict and not has_managed_dict(cl, emitter):\n        # __dict__ lives right after the struct and __weakref__ lives right after that\n        # TODO: They should get members in the struct instead of doing this nonsense.\n        weak_offset = f\"{base_size} + sizeof(PyObject *)\"\n        emitter.emit_lines(\n            f\"PyMemberDef {members_name}[] = {{\",\n            f'{{\"__dict__\", T_OBJECT_EX, {base_size}, 0, NULL}},',\n            f'{{\"__weakref__\", T_OBJECT_EX, {weak_offset}, 0, NULL}},',\n            \"{0}\",\n            \"};\",\n        )\n\n        fields[\"tp_members\"] = members_name\n        fields[\"tp_basicsize\"] = f\"{base_size} + 2*sizeof(PyObject *)\"\n        if emitter.capi_version < (3, 12):\n            fields[\"tp_dictoffset\"] = base_size\n            fields[\"tp_weaklistoffset\"] = weak_offset\n    else:\n        fields[\"tp_basicsize\"] = base_size\n\n    if generate_full:\n        assert cl.setup is not None\n        emitter.emit_line(native_function_header(cl.setup, emitter) + \";\")\n        assert cl.ctor is not None\n        emitter.emit_line(native_function_header(cl.ctor, emitter) + \";\")\n\n        emit_line()\n        init_fn = cl.get_method(\"__init__\")\n        generate_new_for_class(cl, new_name, vtable_name, setup_name, init_fn, emitter)\n        emit_line()\n        if not cl.is_acyclic:\n            generate_traverse_for_class(cl, traverse_name, emitter)\n            emit_line()\n        generate_clear_for_class(cl, clear_name, emitter)\n        emit_line()\n        generate_dealloc_for_class(cl, dealloc_name, clear_name, bool(del_method), emitter)\n        emit_line()\n\n        if cl.allow_interpreted_subclasses:\n            shadow_vtable_name: str | None = generate_vtables(\n                cl, vtable_setup_name + \"_shadow\", vtable_name + \"_shadow\", emitter, shadow=True\n            )\n            emit_line()\n        else:\n            shadow_vtable_name = None\n        vtable_name = generate_vtables(cl, vtable_setup_name, vtable_name, emitter, shadow=False)\n        emit_line()\n        generate_coroutine_setup(cl, coroutine_setup_name, module, emitter)\n        emit_line()\n    if del_method:\n        generate_finalize_for_class(del_method, finalize_name, emitter)\n        emit_line()\n    if needs_getseters:\n        generate_getseter_declarations(cl, emitter)\n        emit_line()\n        generate_getseters_table(cl, getseters_name, emitter)\n        emit_line()\n\n    if cl.is_trait:\n        generate_new_for_trait(cl, new_name, emitter)\n\n    generate_methods_table(cl, methods_name, setup_name if generate_full else None, emitter)\n    emit_line()\n\n    flags = [\"Py_TPFLAGS_DEFAULT\", \"Py_TPFLAGS_HEAPTYPE\", \"Py_TPFLAGS_BASETYPE\"]\n    if generate_full and not cl.is_acyclic:\n        flags.append(\"Py_TPFLAGS_HAVE_GC\")\n    if cl.has_method(\"__call__\"):\n        fields[\"tp_vectorcall_offset\"] = \"offsetof({}, vectorcall)\".format(\n            cl.struct_name(emitter.names)\n        )\n        flags.append(\"_Py_TPFLAGS_HAVE_VECTORCALL\")\n        if not fields.get(\"tp_vectorcall\"):\n            # This is just a placeholder to please CPython. It will be\n            # overridden during setup.\n            fields[\"tp_call\"] = \"PyVectorcall_Call\"\n    if has_managed_dict(cl, emitter):\n        flags.append(\"Py_TPFLAGS_MANAGED_DICT\")\n    fields[\"tp_flags\"] = \" | \".join(flags)\n\n    fields[\"tp_doc\"] = f\"PyDoc_STR({native_class_doc_initializer(cl)})\"\n\n    emitter.emit_line(f\"static PyTypeObject {emitter.type_struct_name(cl)}_template_ = {{\")\n    emitter.emit_line(\"PyVarObject_HEAD_INIT(NULL, 0)\")\n    for field, value in fields.items():\n        emitter.emit_line(f\".{field} = {value},\")\n    emitter.emit_line(\"};\")\n    emitter.emit_line(\n        \"static PyTypeObject *{t}_template = &{t}_template_;\".format(\n            t=emitter.type_struct_name(cl)\n        )\n    )\n\n    if cl.coroutine_name:\n        cpyfunction = emitter.static_name(cl.name + \"_cpyfunction\", module)\n        emitter.emit_line(f\"static PyObject *{cpyfunction} = NULL;\")\n\n    emitter.emit_line()\n    if generate_full:\n        generate_setup_for_class(cl, defaults_fn, vtable_name, shadow_vtable_name, emitter)\n        emitter.emit_line()\n        generate_constructor_for_class(cl, cl.ctor, init_fn, setup_name, vtable_name, emitter)\n        emitter.emit_line()\n    if needs_getseters:\n        generate_getseters(cl, emitter)\n\n\ndef getter_name(cl: ClassIR, attribute: str, names: NameGenerator) -> str:\n    return names.private_name(cl.module_name, f\"{cl.name}_get_{attribute}\")\n\n\ndef setter_name(cl: ClassIR, attribute: str, names: NameGenerator) -> str:\n    return names.private_name(cl.module_name, f\"{cl.name}_set_{attribute}\")\n\n\ndef generate_object_struct(cl: ClassIR, emitter: Emitter) -> None:\n    seen_attrs: set[str] = set()\n    lines: list[str] = []\n    lines += [\"typedef struct {\", \"PyObject_HEAD\", \"CPyVTableItem *vtable;\"]\n    if cl.has_method(\"__call__\"):\n        lines.append(\"vectorcallfunc vectorcall;\")\n    bitmap_attrs = []\n    for base in reversed(cl.base_mro):\n        if not base.is_trait:\n            if base.bitmap_attrs:\n                # Do we need another attribute bitmap field?\n                if emitter.bitmap_field(len(base.bitmap_attrs) - 1) not in bitmap_attrs:\n                    for i in range(0, len(base.bitmap_attrs), BITMAP_BITS):\n                        attr = emitter.bitmap_field(i)\n                        if attr not in bitmap_attrs:\n                            lines.append(f\"{BITMAP_TYPE} {attr};\")\n                            bitmap_attrs.append(attr)\n            for attr, rtype in base.attributes.items():\n                # Generated class may redefine certain attributes with different\n                # types in subclasses (this would be unsafe for user-defined classes).\n                if attr not in seen_attrs:\n                    lines.append(f\"{emitter.ctype_spaced(rtype)}{emitter.attr(attr)};\")\n                    seen_attrs.add(attr)\n\n                    if isinstance(rtype, RTuple):\n                        emitter.declare_tuple_struct(rtype)\n\n    lines.append(f\"}} {cl.struct_name(emitter.names)};\")\n    lines.append(\"\")\n    emitter.context.declarations[cl.struct_name(emitter.names)] = HeaderDeclaration(\n        lines, is_type=True\n    )\n\n\ndef generate_vtables(\n    base: ClassIR, vtable_setup_name: str, vtable_name: str, emitter: Emitter, shadow: bool\n) -> str:\n    \"\"\"Emit the vtables and vtable setup functions for a class.\n\n    This includes both the primary vtable and any trait implementation vtables.\n    The trait vtables go before the main vtable, and have the following layout:\n        {\n            CPyType_T1,         // pointer to type object\n            C_T1_trait_vtable,  // pointer to array of method pointers\n            C_T1_offset_table,  // pointer to array of attribute offsets\n            CPyType_T2,\n            C_T2_trait_vtable,\n            C_T2_offset_table,\n            ...\n        }\n    The method implementations are calculated at the end of IR pass, attribute\n    offsets are {offsetof(native__C, _x1), offsetof(native__C, _y1), ...}.\n\n    To account for both dynamic loading and dynamic class creation,\n    vtables are populated dynamically at class creation time, so we\n    emit empty array definitions to store the vtables and a function to\n    populate them.\n\n    If shadow is True, generate \"shadow vtables\" that point to the\n    shadow glue methods (which should dispatch via the Python C-API).\n\n    Returns the expression to use to refer to the vtable, which might be\n    different than the name, if there are trait vtables.\n    \"\"\"\n\n    def trait_vtable_name(trait: ClassIR) -> str:\n        return \"{}_{}_trait_vtable{}\".format(\n            base.name_prefix(emitter.names),\n            trait.name_prefix(emitter.names),\n            \"_shadow\" if shadow else \"\",\n        )\n\n    def trait_offset_table_name(trait: ClassIR) -> str:\n        return \"{}_{}_offset_table\".format(\n            base.name_prefix(emitter.names), trait.name_prefix(emitter.names)\n        )\n\n    # Emit array definitions with enough space for all the entries\n    emitter.emit_line(\n        \"static CPyVTableItem {}[{}];\".format(\n            vtable_name, max(1, len(base.vtable_entries) + 3 * len(base.trait_vtables))\n        )\n    )\n\n    for trait, vtable in base.trait_vtables.items():\n        # Trait methods entry (vtable index -> method implementation).\n        emitter.emit_line(\n            f\"static CPyVTableItem {trait_vtable_name(trait)}[{max(1, len(vtable))}];\"\n        )\n        # Trait attributes entry (attribute number in trait -> offset in actual struct).\n        emitter.emit_line(\n            \"static size_t {}[{}];\".format(\n                trait_offset_table_name(trait), max(1, len(trait.attributes))\n            )\n        )\n\n    # Emit vtable setup function\n    emitter.emit_line(\"static bool\")\n    emitter.emit_line(f\"{NATIVE_PREFIX}{vtable_setup_name}(void)\")\n    emitter.emit_line(\"{\")\n\n    if base.allow_interpreted_subclasses and not shadow:\n        emitter.emit_line(f\"{NATIVE_PREFIX}{vtable_setup_name}_shadow();\")\n\n    subtables = []\n    for trait, vtable in base.trait_vtables.items():\n        name = trait_vtable_name(trait)\n        offset_name = trait_offset_table_name(trait)\n        generate_vtable(vtable, name, emitter, [], shadow)\n        generate_offset_table(offset_name, emitter, trait, base)\n        subtables.append((trait, name, offset_name))\n\n    generate_vtable(base.vtable_entries, vtable_name, emitter, subtables, shadow)\n\n    emitter.emit_line(\"return 1;\")\n    emitter.emit_line(\"}\")\n\n    return vtable_name if not subtables else f\"{vtable_name} + {len(subtables) * 3}\"\n\n\ndef generate_offset_table(\n    trait_offset_table_name: str, emitter: Emitter, trait: ClassIR, cl: ClassIR\n) -> None:\n    \"\"\"Generate attribute offset row of a trait vtable.\"\"\"\n    emitter.emit_line(f\"size_t {trait_offset_table_name}_scratch[] = {{\")\n    for attr in trait.attributes:\n        emitter.emit_line(f\"offsetof({cl.struct_name(emitter.names)}, {emitter.attr(attr)}),\")\n    if not trait.attributes:\n        # This is for msvc.\n        emitter.emit_line(\"0\")\n    emitter.emit_line(\"};\")\n    emitter.emit_line(\n        \"memcpy({name}, {name}_scratch, sizeof({name}));\".format(name=trait_offset_table_name)\n    )\n\n\ndef generate_vtable(\n    entries: VTableEntries,\n    vtable_name: str,\n    emitter: Emitter,\n    subtables: list[tuple[ClassIR, str, str]],\n    shadow: bool,\n) -> None:\n    emitter.emit_line(f\"CPyVTableItem {vtable_name}_scratch[] = {{\")\n    if subtables:\n        emitter.emit_line(\"/* Array of trait vtables */\")\n        for trait, table, offset_table in subtables:\n            emitter.emit_line(\n                \"(CPyVTableItem){}, (CPyVTableItem){}, (CPyVTableItem){},\".format(\n                    emitter.type_struct_name(trait), table, offset_table\n                )\n            )\n        emitter.emit_line(\"/* Start of real vtable */\")\n\n    for entry in entries:\n        method = entry.shadow_method if shadow and entry.shadow_method else entry.method\n        emitter.emit_line(\n            \"(CPyVTableItem){}{}{},\".format(\n                emitter.get_group_prefix(entry.method.decl),\n                NATIVE_PREFIX,\n                method.cname(emitter.names),\n            )\n        )\n\n    # msvc doesn't allow empty arrays; maybe allowing them at all is an extension?\n    if not entries:\n        emitter.emit_line(\"NULL\")\n    emitter.emit_line(\"};\")\n    emitter.emit_line(\"memcpy({name}, {name}_scratch, sizeof({name}));\".format(name=vtable_name))\n\n\ndef generate_setup_for_class(\n    cl: ClassIR,\n    defaults_fn: FuncIR | None,\n    vtable_name: str,\n    shadow_vtable_name: str | None,\n    emitter: Emitter,\n) -> None:\n    \"\"\"Generate a native function that allocates an instance of a class.\"\"\"\n    emitter.emit_line(native_function_header(cl.setup, emitter))\n    emitter.emit_line(\"{\")\n    type_arg_name = REG_PREFIX + cl.setup.sig.args[0].name\n    emitter.emit_line(f\"PyTypeObject *type = (PyTypeObject*){type_arg_name};\")\n    struct_name = cl.struct_name(emitter.names)\n    emitter.emit_line(f\"{struct_name} *self;\")\n\n    prefix = cl.name_prefix(emitter.names)\n    if cl.reuse_freed_instance:\n        # Attempt to use a per-type free list first (a free \"list\" with up to one object only).\n        emitter.emit_line(f\"if ({prefix}_free_instance != NULL) {{\")\n        emitter.emit_line(f\"self = {prefix}_free_instance;\")\n        emitter.emit_line(f\"{prefix}_free_instance = NULL;\")\n        emitter.emit_line(\"Py_SET_REFCNT(self, 1);\")\n        if not cl.is_acyclic:\n            emitter.emit_line(\"PyObject_GC_Track(self);\")\n        if defaults_fn is not None:\n            emit_attr_defaults_func_call(defaults_fn, \"self\", emitter)\n        emitter.emit_line(\"return (PyObject *)self;\")\n        emitter.emit_line(\"}\")\n\n    emitter.emit_line(f\"self = ({cl.struct_name(emitter.names)} *)type->tp_alloc(type, 0);\")\n    emitter.emit_line(\"if (self == NULL)\")\n    emitter.emit_line(\"    return NULL;\")\n\n    if shadow_vtable_name:\n        emitter.emit_line(f\"if (type != {emitter.type_struct_name(cl)}) {{\")\n        emitter.emit_line(f\"self->vtable = {shadow_vtable_name};\")\n        emitter.emit_line(\"} else {\")\n        emitter.emit_line(f\"self->vtable = {vtable_name};\")\n        emitter.emit_line(\"}\")\n    else:\n        emitter.emit_line(f\"self->vtable = {vtable_name};\")\n\n    emit_clear_bitmaps(cl, emitter)\n\n    if cl.has_method(\"__call__\"):\n        name = cl.method_decl(\"__call__\").cname(emitter.names)\n        emitter.emit_line(f\"self->vectorcall = {PREFIX}{name};\")\n\n    for base in reversed(cl.base_mro):\n        for attr, rtype in base.attributes.items():\n            value = emitter.c_undefined_value(rtype)\n\n            # We don't need to set this field to NULL since tp_alloc() already\n            # zero-initializes `self`.\n            if value != \"NULL\":\n                emitter.set_undefined_value(f\"self->{emitter.attr(attr)}\", rtype)\n\n    # Initialize attributes to default values, if necessary\n    if defaults_fn is not None:\n        emit_attr_defaults_func_call(defaults_fn, \"self\", emitter)\n\n    emitter.emit_line(\"return (PyObject *)self;\")\n    emitter.emit_line(\"}\")\n\n\ndef emit_clear_bitmaps(cl: ClassIR, emitter: Emitter) -> None:\n    \"\"\"Emit C code to clear bitmaps that track if attributes have an assigned value.\"\"\"\n    for i in range(0, len(cl.bitmap_attrs), BITMAP_BITS):\n        field = emitter.bitmap_field(i)\n        emitter.emit_line(f\"self->{field} = 0;\")\n\n\ndef emit_attr_defaults_func_call(defaults_fn: FuncIR, self_name: str, emitter: Emitter) -> None:\n    \"\"\"Emit C code to initialize attribute defaults by calling defaults_fn.\n\n    The code returns NULL on a raised exception.\n    \"\"\"\n    emitter.emit_lines(\n        \"if ({}{}((PyObject *){}) == 0) {{\".format(\n            NATIVE_PREFIX, defaults_fn.cname(emitter.names), self_name\n        ),\n        \"Py_DECREF(self);\",\n        \"return NULL;\",\n        \"}\",\n    )\n\n\ndef emit_setup_or_dunder_new_call(\n    cl: ClassIR,\n    setup_name: str,\n    type_arg: str,\n    native_prefix: bool,\n    new_args: str,\n    emitter: Emitter,\n) -> None:\n    def emit_null_check() -> None:\n        emitter.emit_line(\"if (self == NULL)\")\n        emitter.emit_line(\"    return NULL;\")\n\n    new_fn = cl.get_method(\"__new__\")\n    if not new_fn:\n        emitter.emit_line(f\"PyObject *self = {setup_name}({type_arg});\")\n        emit_null_check()\n        return\n    prefix = emitter.get_group_prefix(new_fn.decl) + NATIVE_PREFIX if native_prefix else PREFIX\n    all_args = type_arg\n    if new_args != \"\":\n        all_args += \", \" + new_args\n    emitter.emit_line(f\"PyObject *self = {prefix}{new_fn.cname(emitter.names)}({all_args});\")\n    emit_null_check()\n\n    # skip __init__ if __new__ returns some other type\n    emitter.emit_line(f\"if (Py_TYPE(self) != {emitter.type_struct_name(cl)})\")\n    emitter.emit_line(\"    return self;\")\n\n\ndef generate_constructor_for_class(\n    cl: ClassIR,\n    fn: FuncDecl,\n    init_fn: FuncIR | None,\n    setup_name: str,\n    vtable_name: str,\n    emitter: Emitter,\n) -> None:\n    \"\"\"Generate a native function that allocates and initializes an instance of a class.\"\"\"\n    emitter.emit_line(f\"{native_function_header(fn, emitter)}\")\n    emitter.emit_line(\"{\")\n\n    fn_args = [REG_PREFIX + arg.name for arg in fn.sig.args]\n    type_arg = \"(PyObject *)\" + emitter.type_struct_name(cl)\n    new_args = \", \".join(fn_args)\n\n    use_wrapper = (\n        cl.has_method(\"__new__\")\n        and len(fn.sig.args) == 2\n        and fn.sig.args[0].kind == ARG_STAR\n        and fn.sig.args[1].kind == ARG_STAR2\n    )\n    emit_setup_or_dunder_new_call(cl, setup_name, type_arg, not use_wrapper, new_args, emitter)\n\n    args = \", \".join([\"self\"] + fn_args)\n    if init_fn is not None:\n        prefix = PREFIX if use_wrapper else NATIVE_PREFIX\n        cast = \"!= NULL ? 0 : -1\" if use_wrapper else \"\"\n        emitter.emit_line(\n            \"char res = {}{}{}({}){};\".format(\n                emitter.get_group_prefix(init_fn.decl),\n                prefix,\n                init_fn.cname(emitter.names),\n                args,\n                cast,\n            )\n        )\n        emitter.emit_line(\"if (res == 2) {\")\n        emitter.emit_line(\"Py_DECREF(self);\")\n        emitter.emit_line(\"return NULL;\")\n        emitter.emit_line(\"}\")\n\n    # If there is a nontrivial ctor that we didn't define, invoke it via tp_init\n    elif len(fn.sig.args) > 1:\n        emitter.emit_line(f\"int res = {emitter.type_struct_name(cl)}->tp_init({args});\")\n\n        emitter.emit_line(\"if (res < 0) {\")\n        emitter.emit_line(\"Py_DECREF(self);\")\n        emitter.emit_line(\"return NULL;\")\n        emitter.emit_line(\"}\")\n\n    emitter.emit_line(\"return self;\")\n    emitter.emit_line(\"}\")\n\n\ndef generate_init_for_class(cl: ClassIR, init_fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generate an init function suitable for use as tp_init.\n\n    tp_init needs to be a function that returns an int, and our\n    __init__ methods return a PyObject. Translate NULL to -1,\n    everything else to 0.\n    \"\"\"\n    func_name = f\"{cl.name_prefix(emitter.names)}_init\"\n\n    emitter.emit_line(\"static int\")\n    emitter.emit_line(f\"{func_name}(PyObject *self, PyObject *args, PyObject *kwds)\")\n    emitter.emit_line(\"{\")\n    if cl.allow_interpreted_subclasses or cl.builtin_base or cl.has_method(\"__new__\"):\n        emitter.emit_line(\n            \"return {}{}(self, args, kwds) != NULL ? 0 : -1;\".format(\n                PREFIX, init_fn.cname(emitter.names)\n            )\n        )\n    else:\n        emitter.emit_line(\"return 0;\")\n    emitter.emit_line(\"}\")\n\n    return func_name\n\n\ndef generate_new_for_class(\n    cl: ClassIR,\n    func_name: str,\n    vtable_name: str,\n    setup_name: str,\n    init_fn: FuncIR | None,\n    emitter: Emitter,\n) -> None:\n    emitter.emit_line(\"static PyObject *\")\n    emitter.emit_line(f\"{func_name}(PyTypeObject *type, PyObject *args, PyObject *kwds)\")\n    emitter.emit_line(\"{\")\n    # TODO: Check and unbox arguments\n    if not cl.allow_interpreted_subclasses:\n        emitter.emit_line(f\"if (type != {emitter.type_struct_name(cl)}) {{\")\n        emitter.emit_line(\n            'PyErr_SetString(PyExc_TypeError, \"interpreted classes cannot inherit from compiled\");'\n        )\n        emitter.emit_line(\"return NULL;\")\n        emitter.emit_line(\"}\")\n\n    type_arg = \"(PyObject*)type\"\n    new_args = \"args, kwds\"\n    emit_setup_or_dunder_new_call(cl, setup_name, type_arg, False, new_args, emitter)\n    if (\n        not init_fn\n        or cl.allow_interpreted_subclasses\n        or cl.builtin_base\n        or cl.is_serializable()\n        or cl.has_method(\"__new__\")\n    ):\n        # Match Python semantics -- __new__ doesn't call __init__.\n        emitter.emit_line(\"return self;\")\n    else:\n        # __new__ of a native class implicitly calls __init__ so that we\n        # can enforce that instances are always properly initialized. This\n        # is needed to support always defined attributes.\n        emitter.emit_line(\n            f\"PyObject *ret = {PREFIX}{init_fn.cname(emitter.names)}(self, args, kwds);\"\n        )\n        emitter.emit_lines(\"if (ret == NULL)\", \"    return NULL;\")\n        emitter.emit_line(\"return self;\")\n    emitter.emit_line(\"}\")\n\n\ndef generate_new_for_trait(cl: ClassIR, func_name: str, emitter: Emitter) -> None:\n    emitter.emit_line(\"static PyObject *\")\n    emitter.emit_line(f\"{func_name}(PyTypeObject *type, PyObject *args, PyObject *kwds)\")\n    emitter.emit_line(\"{\")\n    emitter.emit_line(f\"if (type != {emitter.type_struct_name(cl)}) {{\")\n    emitter.emit_line(\n        \"PyErr_SetString(PyExc_TypeError, \"\n        '\"interpreted classes cannot inherit from compiled traits\");'\n    )\n    emitter.emit_line(\"} else {\")\n    emitter.emit_line('PyErr_SetString(PyExc_TypeError, \"traits may not be directly created\");')\n    emitter.emit_line(\"}\")\n    emitter.emit_line(\"return NULL;\")\n    emitter.emit_line(\"}\")\n\n\ndef generate_traverse_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -> None:\n    \"\"\"Emit function that performs cycle GC traversal of an instance.\"\"\"\n    emitter.emit_line(\"static int\")\n    emitter.emit_line(\n        f\"{func_name}({cl.struct_name(emitter.names)} *self, visitproc visit, void *arg)\"\n    )\n    emitter.emit_line(\"{\")\n    for base in reversed(cl.base_mro):\n        for attr, rtype in base.attributes.items():\n            emitter.emit_gc_visit(f\"self->{emitter.attr(attr)}\", rtype)\n    if has_managed_dict(cl, emitter):\n        emitter.emit_line(\"PyObject_VisitManagedDict((PyObject *)self, visit, arg);\")\n    elif cl.has_dict:\n        struct_name = cl.struct_name(emitter.names)\n        # __dict__ lives right after the struct and __weakref__ lives right after that\n        emitter.emit_gc_visit(\n            f\"*((PyObject **)((char *)self + sizeof({struct_name})))\", object_rprimitive\n        )\n        emitter.emit_gc_visit(\n            f\"*((PyObject **)((char *)self + sizeof(PyObject *) + sizeof({struct_name})))\",\n            object_rprimitive,\n        )\n    emitter.emit_line(\"return 0;\")\n    emitter.emit_line(\"}\")\n\n\ndef generate_clear_for_class(cl: ClassIR, func_name: str, emitter: Emitter) -> None:\n    emitter.emit_line(\"static int\")\n    emitter.emit_line(f\"{func_name}({cl.struct_name(emitter.names)} *self)\")\n    emitter.emit_line(\"{\")\n    for base in reversed(cl.base_mro):\n        for attr, rtype in base.attributes.items():\n            emitter.emit_gc_clear(f\"self->{emitter.attr(attr)}\", rtype)\n    if has_managed_dict(cl, emitter):\n        emitter.emit_line(\"PyObject_ClearManagedDict((PyObject *)self);\")\n    elif cl.has_dict:\n        struct_name = cl.struct_name(emitter.names)\n        # __dict__ lives right after the struct and __weakref__ lives right after that\n        emitter.emit_gc_clear(\n            f\"*((PyObject **)((char *)self + sizeof({struct_name})))\", object_rprimitive\n        )\n        emitter.emit_gc_clear(\n            f\"*((PyObject **)((char *)self + sizeof(PyObject *) + sizeof({struct_name})))\",\n            object_rprimitive,\n        )\n    emitter.emit_line(\"return 0;\")\n    emitter.emit_line(\"}\")\n\n\ndef generate_dealloc_for_class(\n    cl: ClassIR,\n    dealloc_func_name: str,\n    clear_func_name: str,\n    has_tp_finalize: bool,\n    emitter: Emitter,\n) -> None:\n    emitter.emit_line(\"static void\")\n    emitter.emit_line(f\"{dealloc_func_name}({cl.struct_name(emitter.names)} *self)\")\n    emitter.emit_line(\"{\")\n    if has_tp_finalize:\n        emitter.emit_line(\"PyObject *type, *value, *traceback;\")\n        emitter.emit_line(\"PyErr_Fetch(&type, &value, &traceback);\")\n        emitter.emit_line(\"int res = PyObject_CallFinalizerFromDealloc((PyObject *)self);\")\n        # CPython interpreter uses PyErr_WriteUnraisable: https://docs.python.org/3/c-api/exceptions.html#c.PyErr_WriteUnraisable\n        # However, the message is slightly different due to the way mypyc compiles classes.\n        # CPython interpreter prints: Exception ignored in: <function F.__del__ at 0x100aed940>\n        # mypyc prints: Exception ignored in: <slot wrapper '__del__' of 'F' objects>\n        emitter.emit_line(\"if (PyErr_Occurred() != NULL) {\")\n        # Don't untrack instance if error occurred\n        emitter.emit_line(\"PyErr_WriteUnraisable((PyObject *)self);\")\n        emitter.emit_line(\"res = -1;\")\n        emitter.emit_line(\"}\")\n        emitter.emit_line(\"PyErr_Restore(type, value, traceback);\")\n        emitter.emit_line(\"if (res < 0) {\")\n        emitter.emit_line(\"goto done;\")\n        emitter.emit_line(\"}\")\n    if not cl.is_acyclic:\n        emitter.emit_line(\"PyObject_GC_UnTrack(self);\")\n    if cl.reuse_freed_instance:\n        emit_reuse_dealloc(cl, emitter)\n    # The trashcan is needed to handle deep recursive deallocations\n    emitter.emit_line(f\"CPy_TRASHCAN_BEGIN(self, {dealloc_func_name})\")\n    emitter.emit_line(f\"{clear_func_name}(self);\")\n    emitter.emit_line(\"Py_TYPE(self)->tp_free((PyObject *)self);\")\n    emitter.emit_line(\"CPy_TRASHCAN_END(self)\")\n    emitter.emit_line(\"done: ;\")\n    emitter.emit_line(\"}\")\n\n\ndef emit_reuse_dealloc(cl: ClassIR, emitter: Emitter) -> None:\n    \"\"\"Emit code to deallocate object by putting it to per-type free list.\n\n    The free \"list\" currently can have up to one object.\n    \"\"\"\n    prefix = cl.name_prefix(emitter.names)\n    emitter.emit_line(f\"if ({prefix}_free_instance == NULL) {{\")\n    emitter.emit_line(f\"{prefix}_free_instance = self;\")\n\n    # Clear attributes and free referenced objects.\n\n    emit_clear_bitmaps(cl, emitter)\n\n    for base in reversed(cl.base_mro):\n        for attr, rtype in base.attributes.items():\n            emitter.emit_reuse_clear(f\"self->{emitter.attr(attr)}\", rtype)\n\n    emitter.emit_line(\"return;\")\n    emitter.emit_line(\"}\")\n\n\ndef generate_finalize_for_class(\n    del_method: FuncIR, finalize_func_name: str, emitter: Emitter\n) -> None:\n    emitter.emit_line(\"static void\")\n    emitter.emit_line(f\"{finalize_func_name}(PyObject *self)\")\n    emitter.emit_line(\"{\")\n    emitter.emit_line(\n        \"{}{}{}(self);\".format(\n            emitter.get_group_prefix(del_method.decl),\n            NATIVE_PREFIX,\n            del_method.cname(emitter.names),\n        )\n    )\n    emitter.emit_line(\"}\")\n\n\ndef generate_methods_table(\n    cl: ClassIR, name: str, setup_name: str | None, emitter: Emitter\n) -> None:\n    emitter.emit_line(f\"static PyMethodDef {name}[] = {{\")\n    if setup_name:\n        # Store pointer to the setup function so it can be resolved dynamically\n        # in case of instance creation in __new__.\n        # CPy_SetupObject expects this method to be the first one in tp_methods.\n        emitter.emit_line(\n            f'{{\"__internal_mypyc_setup\", (PyCFunction){setup_name}, METH_O, NULL}},'\n        )\n    for fn in cl.methods.values():\n        if fn.decl.is_prop_setter or fn.decl.is_prop_getter or fn.internal:\n            continue\n        emitter.emit_line(f'{{\"{fn.name}\",')\n        emitter.emit_line(f\" (PyCFunction){PREFIX}{fn.cname(emitter.names)},\")\n        flags = [\"METH_FASTCALL\", \"METH_KEYWORDS\"]\n        if fn.decl.kind == FUNC_STATICMETHOD:\n            flags.append(\"METH_STATIC\")\n        elif fn.decl.kind == FUNC_CLASSMETHOD:\n            flags.append(\"METH_CLASS\")\n\n        doc = native_function_doc_initializer(fn)\n        emitter.emit_line(\" {}, PyDoc_STR({})}},\".format(\" | \".join(flags), doc))\n\n    # Provide a default __getstate__ and __setstate__\n    if not cl.has_method(\"__setstate__\") and not cl.has_method(\"__getstate__\"):\n        emitter.emit_lines(\n            '{\"__setstate__\", (PyCFunction)CPyPickle_SetState, METH_O, NULL},',\n            '{\"__getstate__\", (PyCFunction)CPyPickle_GetState, METH_NOARGS, NULL},',\n        )\n\n    emitter.emit_line(\"{NULL}  /* Sentinel */\")\n    emitter.emit_line(\"};\")\n\n\ndef generate_side_table_for_class(\n    cl: ClassIR, name: str, type: str, slots: dict[str, str], emitter: Emitter\n) -> str | None:\n    name = f\"{cl.name_prefix(emitter.names)}_{name}\"\n    emitter.emit_line(f\"static {type} {name} = {{\")\n    for field, value in slots.items():\n        emitter.emit_line(f\".{field} = {value},\")\n    emitter.emit_line(\"};\")\n    return name\n\n\ndef generate_getseter_declarations(cl: ClassIR, emitter: Emitter) -> None:\n    if not cl.is_trait:\n        for attr in cl.attributes:\n            emitter.emit_line(\"static PyObject *\")\n            emitter.emit_line(\n                \"{}({} *self, void *closure);\".format(\n                    getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)\n                )\n            )\n            emitter.emit_line(\"static int\")\n            emitter.emit_line(\n                \"{}({} *self, PyObject *value, void *closure);\".format(\n                    setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)\n                )\n            )\n\n    for prop, (getter, setter) in cl.properties.items():\n        if getter.decl.implicit:\n            continue\n\n        # Generate getter declaration\n        emitter.emit_line(\"static PyObject *\")\n        emitter.emit_line(\n            \"{}({} *self, void *closure);\".format(\n                getter_name(cl, prop, emitter.names), cl.struct_name(emitter.names)\n            )\n        )\n\n        # Generate property setter declaration if a setter exists\n        if setter:\n            emitter.emit_line(\"static int\")\n            emitter.emit_line(\n                \"{}({} *self, PyObject *value, void *closure);\".format(\n                    setter_name(cl, prop, emitter.names), cl.struct_name(emitter.names)\n                )\n            )\n\n\ndef generate_getseters_table(cl: ClassIR, name: str, emitter: Emitter) -> None:\n    emitter.emit_line(f\"static PyGetSetDef {name}[] = {{\")\n    if not cl.is_trait:\n        for attr in cl.attributes:\n            emitter.emit_line(f'{{\"{attr}\",')\n            emitter.emit_line(\n                \" (getter){}, (setter){},\".format(\n                    getter_name(cl, attr, emitter.names), setter_name(cl, attr, emitter.names)\n                )\n            )\n            emitter.emit_line(\" NULL, NULL},\")\n    for prop, (getter, setter) in cl.properties.items():\n        if getter.decl.implicit:\n            continue\n\n        emitter.emit_line(f'{{\"{prop}\",')\n        emitter.emit_line(f\" (getter){getter_name(cl, prop, emitter.names)},\")\n\n        if setter:\n            emitter.emit_line(f\" (setter){setter_name(cl, prop, emitter.names)},\")\n            emitter.emit_line(\"NULL, NULL},\")\n        else:\n            emitter.emit_line(\"NULL, NULL, NULL},\")\n\n    if cl.has_dict:\n        emitter.emit_line('{\"__dict__\", PyObject_GenericGetDict, PyObject_GenericSetDict},')\n\n    emitter.emit_line(\"{NULL}  /* Sentinel */\")\n    emitter.emit_line(\"};\")\n\n\ndef generate_getseters(cl: ClassIR, emitter: Emitter) -> None:\n    if not cl.is_trait:\n        for i, (attr, rtype) in enumerate(cl.attributes.items()):\n            generate_getter(cl, attr, rtype, emitter)\n            emitter.emit_line(\"\")\n            generate_setter(cl, attr, rtype, emitter)\n            if i < len(cl.attributes) - 1:\n                emitter.emit_line(\"\")\n    for prop, (getter, setter) in cl.properties.items():\n        if getter.decl.implicit:\n            continue\n\n        rtype = getter.sig.ret_type\n        emitter.emit_line(\"\")\n        generate_readonly_getter(cl, prop, rtype, getter, emitter)\n        if setter:\n            arg_type = setter.sig.args[1].type\n            emitter.emit_line(\"\")\n            generate_property_setter(cl, prop, arg_type, setter, emitter)\n\n\ndef generate_getter(cl: ClassIR, attr: str, rtype: RType, emitter: Emitter) -> None:\n    attr_field = emitter.attr(attr)\n    emitter.emit_line(\"static PyObject *\")\n    emitter.emit_line(\n        \"{}({} *self, void *closure)\".format(\n            getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)\n        )\n    )\n    emitter.emit_line(\"{\")\n    attr_expr = f\"self->{attr_field}\"\n\n    # HACK: Don't consider refcounted values as always defined, since it's possible to\n    #       access uninitialized values via 'gc.get_objects()'. Accessing non-refcounted\n    #       values is benign.\n    always_defined = cl.is_always_defined(attr) and not rtype.is_refcounted\n\n    if not always_defined:\n        emitter.emit_undefined_attr_check(rtype, attr_expr, \"==\", \"self\", attr, cl, unlikely=True)\n        emitter.emit_line(\"PyErr_SetString(PyExc_AttributeError,\")\n        emitter.emit_line(f'    \"attribute {repr(attr)} of {repr(cl.name)} undefined\");')\n        emitter.emit_line(\"return NULL;\")\n        emitter.emit_line(\"}\")\n    emitter.emit_inc_ref(f\"self->{attr_field}\", rtype)\n    emitter.emit_box(f\"self->{attr_field}\", \"retval\", rtype, declare_dest=True)\n    emitter.emit_line(\"return retval;\")\n    emitter.emit_line(\"}\")\n\n\ndef generate_setter(cl: ClassIR, attr: str, rtype: RType, emitter: Emitter) -> None:\n    attr_field = emitter.attr(attr)\n    emitter.emit_line(\"static int\")\n    emitter.emit_line(\n        \"{}({} *self, PyObject *value, void *closure)\".format(\n            setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)\n        )\n    )\n    emitter.emit_line(\"{\")\n\n    deletable = cl.is_deletable(attr)\n    if not deletable:\n        emitter.emit_line(\"if (value == NULL) {\")\n        emitter.emit_line(\"PyErr_SetString(PyExc_AttributeError,\")\n        emitter.emit_line(\n            f'    \"{repr(cl.name)} object attribute {repr(attr)} cannot be deleted\");'\n        )\n        emitter.emit_line(\"return -1;\")\n        emitter.emit_line(\"}\")\n\n    # HACK: Don't consider refcounted values as always defined, since it's possible to\n    #       access uninitialized values via 'gc.get_objects()'. Accessing non-refcounted\n    #       values is benign.\n    always_defined = cl.is_always_defined(attr) and not rtype.is_refcounted\n\n    if rtype.is_refcounted:\n        attr_expr = f\"self->{attr_field}\"\n        if not always_defined:\n            emitter.emit_undefined_attr_check(rtype, attr_expr, \"!=\", \"self\", attr, cl)\n        emitter.emit_dec_ref(f\"self->{attr_field}\", rtype)\n        if not always_defined:\n            emitter.emit_line(\"}\")\n\n    if deletable:\n        emitter.emit_line(\"if (value != NULL) {\")\n\n    if rtype.is_unboxed:\n        emitter.emit_unbox(\"value\", \"tmp\", rtype, error=ReturnHandler(\"-1\"), declare_dest=True)\n    elif is_same_type(rtype, object_rprimitive):\n        emitter.emit_line(\"PyObject *tmp = value;\")\n    else:\n        emitter.emit_cast(\"value\", \"tmp\", rtype, declare_dest=True)\n        emitter.emit_lines(\"if (!tmp)\", \"    return -1;\")\n    emitter.emit_inc_ref(\"tmp\", rtype)\n    emitter.emit_line(f\"self->{attr_field} = tmp;\")\n    if rtype.error_overlap and not always_defined:\n        emitter.emit_attr_bitmap_set(\"tmp\", \"self\", rtype, cl, attr)\n\n    if deletable:\n        emitter.emit_line(\"} else {\")\n        emitter.set_undefined_value(f\"self->{attr_field}\", rtype)\n        if rtype.error_overlap:\n            emitter.emit_attr_bitmap_clear(\"self\", rtype, cl, attr)\n        emitter.emit_line(\"}\")\n    emitter.emit_line(\"return 0;\")\n    emitter.emit_line(\"}\")\n\n\ndef generate_readonly_getter(\n    cl: ClassIR, attr: str, rtype: RType, func_ir: FuncIR, emitter: Emitter\n) -> None:\n    emitter.emit_line(\"static PyObject *\")\n    emitter.emit_line(\n        \"{}({} *self, void *closure)\".format(\n            getter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)\n        )\n    )\n    emitter.emit_line(\"{\")\n    if rtype.is_unboxed:\n        emitter.emit_line(\n            \"{}retval = {}{}((PyObject *) self);\".format(\n                emitter.ctype_spaced(rtype), NATIVE_PREFIX, func_ir.cname(emitter.names)\n            )\n        )\n        emitter.emit_error_check(\"retval\", rtype, \"return NULL;\")\n        emitter.emit_box(\"retval\", \"retbox\", rtype, declare_dest=True)\n        emitter.emit_line(\"return retbox;\")\n    else:\n        emitter.emit_line(\n            f\"return {NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self);\"\n        )\n    emitter.emit_line(\"}\")\n\n\ndef generate_property_setter(\n    cl: ClassIR, attr: str, arg_type: RType, func_ir: FuncIR, emitter: Emitter\n) -> None:\n    emitter.emit_line(\"static int\")\n    emitter.emit_line(\n        \"{}({} *self, PyObject *value, void *closure)\".format(\n            setter_name(cl, attr, emitter.names), cl.struct_name(emitter.names)\n        )\n    )\n    emitter.emit_line(\"{\")\n    if arg_type.is_unboxed:\n        emitter.emit_unbox(\"value\", \"tmp\", arg_type, error=ReturnHandler(\"-1\"), declare_dest=True)\n        emitter.emit_line(\n            f\"{NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self, tmp);\"\n        )\n    else:\n        emitter.emit_line(\n            f\"{NATIVE_PREFIX}{func_ir.cname(emitter.names)}((PyObject *) self, value);\"\n        )\n    emitter.emit_line(\"return 0;\")\n    emitter.emit_line(\"}\")\n\n\ndef has_managed_dict(cl: ClassIR, emitter: Emitter) -> bool:\n    \"\"\"Should the class get the Py_TPFLAGS_MANAGED_DICT flag?\"\"\"\n    # On 3.11 and earlier the flag doesn't exist and we use\n    # tp_dictoffset instead.  If a class inherits from Exception, the\n    # flag conflicts with tp_dictoffset set in the base class.\n    return (\n        emitter.capi_version >= (3, 12)\n        and cl.has_dict\n        and cl.builtin_base != \"PyBaseExceptionObject\"\n    )\n\n\ndef native_class_doc_initializer(cl: ClassIR) -> str:\n    init_fn = cl.get_method(\"__init__\")\n    if init_fn is not None:\n        text_sig = get_text_signature(init_fn, bound=True)\n        if text_sig is None:\n            return \"NULL\"\n        text_sig = text_sig.replace(\"__init__\", cl.name, 1)\n    else:\n        text_sig = f\"{cl.name}()\"\n    docstring = f\"{text_sig}\\n--\\n\\n\"\n    return c_string_initializer(docstring.encode(\"ascii\", errors=\"backslashreplace\"))\n\n\ndef generate_coroutine_setup(\n    cl: ClassIR, coroutine_setup_name: str, module_name: str, emitter: Emitter\n) -> None:\n    emitter.emit_line(\"static bool\")\n    emitter.emit_line(f\"{NATIVE_PREFIX}{coroutine_setup_name}(PyObject *type)\")\n    emitter.emit_line(\"{\")\n\n    error_stmt = \"    return 2;\"\n\n    def emit_instance(fn: FuncIR, fn_name: str) -> str:\n        filepath = emitter.filepath or \"\"\n        return emitter.emit_cpyfunction_instance(fn, fn_name, filepath, error_stmt)\n\n    def success() -> None:\n        emitter.emit_line(\"return 1;\")\n        emitter.emit_line(\"}\")\n\n    if cl.coroutine_name:\n        # Callable class generated for a coroutine. It stores its function wrapper as an attribute.\n        wrapper_name = emit_instance(cl.methods[\"__call__\"], cl.coroutine_name)\n        struct_name = cl.struct_name(emitter.names)\n        attr = emitter.attr(CPYFUNCTION_NAME)\n        emitter.emit_line(f\"(({struct_name} *)type)->{attr} = {wrapper_name};\")\n        return success()\n\n    if not any(fn.decl.is_coroutine for fn in cl.methods.values()):\n        return success()\n\n    emitter.emit_line(\"PyTypeObject *tp = (PyTypeObject *)type;\")\n\n    for fn in cl.methods.values():\n        if not fn.decl.is_coroutine:\n            continue\n\n        name = short_id_from_name(fn.name, fn.decl.shortname, fn.line)\n        wrapper_name = emit_instance(fn, name)\n        name_obj = f\"{wrapper_name}_name\"\n        emitter.emit_line(f'PyObject *{name_obj} = PyUnicode_FromString(\"{fn.name}\");')\n        emitter.emit_line(f\"if (unlikely(!{name_obj}))\")\n        emitter.emit_line(error_stmt)\n        emitter.emit_line(f\"if (PyDict_SetItem(tp->tp_dict, {name_obj}, {wrapper_name}) < 0)\")\n        emitter.emit_line(error_stmt)\n\n    return success()\n"
  },
  {
    "path": "mypyc/codegen/emitfunc.py",
    "content": "\"\"\"Code generation for native function bodies.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final\n\nfrom mypyc.analysis.blockfreq import frequently_executed_blocks\nfrom mypyc.codegen.emit import (\n    DEBUG_ERRORS,\n    PREFIX_MAP,\n    Emitter,\n    TracebackAndGotoHandler,\n    c_array_initializer,\n)\nfrom mypyc.common import GENERATOR_ATTRIBUTE_PREFIX, HAVE_IMMORTAL, NATIVE_PREFIX, REG_PREFIX\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FUNC_CLASSMETHOD, FUNC_STATICMETHOD, FuncDecl, FuncIR, all_values\nfrom mypyc.ir.ops import (\n    ERR_FALSE,\n    NAMESPACE_TYPE,\n    Assign,\n    AssignMulti,\n    BasicBlock,\n    Box,\n    Branch,\n    Call,\n    CallC,\n    Cast,\n    ComparisonOp,\n    ControlOp,\n    CString,\n    DecRef,\n    Extend,\n    Float,\n    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\n    GetElement,\n    GetElementPtr,\n    Goto,\n    IncRef,\n    InitStatic,\n    Integer,\n    IntOp,\n    KeepAlive,\n    LoadAddress,\n    LoadErrorValue,\n    LoadGlobal,\n    LoadLiteral,\n    LoadMem,\n    LoadStatic,\n    MethodCall,\n    Op,\n    OpVisitor,\n    PrimitiveOp,\n    RaiseStandardError,\n    Register,\n    Return,\n    SetAttr,\n    SetElement,\n    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\n    Undef,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.pprint import generate_names_for_ir\nfrom mypyc.ir.rtypes import (\n    RArray,\n    RInstance,\n    RStruct,\n    RTuple,\n    RType,\n    RVec,\n    is_bool_or_bit_rprimitive,\n    is_int32_rprimitive,\n    is_int64_rprimitive,\n    is_int_rprimitive,\n    is_none_rprimitive,\n    is_pointer_rprimitive,\n    is_tagged,\n)\n\n\ndef native_function_type(fn: FuncIR, emitter: Emitter) -> str:\n    args = \", \".join(emitter.ctype(arg.type) for arg in fn.args) or \"void\"\n    ret = emitter.ctype(fn.ret_type)\n    return f\"{ret} (*)({args})\"\n\n\ndef native_function_header(fn: FuncDecl, emitter: Emitter) -> str:\n    args = []\n    for arg in fn.sig.args:\n        args.append(f\"{emitter.ctype_spaced(arg.type)}{REG_PREFIX}{arg.name}\")\n\n    return \"{ret_type}{name}({args})\".format(\n        ret_type=emitter.ctype_spaced(fn.sig.ret_type),\n        name=emitter.native_function_name(fn),\n        args=\", \".join(args) or \"void\",\n    )\n\n\ndef generate_native_function(\n    fn: FuncIR, emitter: Emitter, source_path: str, module_name: str\n) -> None:\n    declarations = Emitter(emitter.context)\n    names = generate_names_for_ir(fn.arg_regs, fn.blocks)\n    body = Emitter(emitter.context, names)\n    visitor = FunctionEmitterVisitor(body, declarations, source_path, module_name)\n\n    declarations.emit_line(f\"{native_function_header(fn.decl, emitter)} {{\")\n    body.indent()\n\n    for r in all_values(fn.arg_regs, fn.blocks):\n        if isinstance(r.type, RTuple):\n            emitter.declare_tuple_struct(r.type)\n        if isinstance(r.type, RArray):\n            continue  # Special: declared on first assignment\n\n        if r in fn.arg_regs:\n            continue  # Skip the arguments\n\n        ctype = emitter.ctype_spaced(r.type)\n        init = \"\"\n        declarations.emit_line(\n            \"{ctype}{prefix}{name}{init};\".format(\n                ctype=ctype, prefix=REG_PREFIX, name=names[r], init=init\n            )\n        )\n\n    # Before we emit the blocks, give them all labels\n    blocks = fn.blocks\n    for i, block in enumerate(blocks):\n        block.label = i\n\n    # Find blocks that are never jumped to or are only jumped to from the\n    # block directly above it. This allows for more labels and gotos to be\n    # eliminated during code generation.\n    for block in fn.blocks:\n        terminator = block.terminator\n        assert isinstance(terminator, ControlOp), terminator\n\n        for target in terminator.targets():\n            is_next_block = target.label == block.label + 1\n\n            # Always emit labels for GetAttr error checks since the emit code that\n            # generates them will add instructions between the branch and the\n            # next label, causing the label to be wrongly removed. A better\n            # solution would be to change the IR so that it adds a basic block\n            # in between the calls.\n            is_problematic_op = isinstance(terminator, Branch) and any(\n                isinstance(s, GetAttr) for s in terminator.sources()\n            )\n\n            if not is_next_block or is_problematic_op:\n                fn.blocks[target.label].referenced = True\n\n    common = frequently_executed_blocks(fn.blocks[0])\n\n    for i in range(len(blocks)):\n        block = blocks[i]\n        visitor.rare = block not in common\n        next_block = None\n        if i + 1 < len(blocks):\n            next_block = blocks[i + 1]\n        body.emit_label(block)\n        visitor.next_block = next_block\n\n        ops = block.ops\n        visitor.ops = ops\n        visitor.op_index = 0\n        while visitor.op_index < len(ops):\n            ops[visitor.op_index].accept(visitor)\n            visitor.op_index += 1\n\n    body.emit_line(\"}\")\n\n    emitter.emit_from_emitter(declarations)\n    emitter.emit_from_emitter(body)\n\n\nclass FunctionEmitterVisitor(OpVisitor[None]):\n    def __init__(\n        self, emitter: Emitter, declarations: Emitter, source_path: str, module_name: str\n    ) -> None:\n        self.emitter = emitter\n        self.names = emitter.names\n        self.declarations = declarations\n        self.source_path = source_path\n        self.module_name = module_name\n        self.literals = emitter.context.literals\n        self.rare = False\n        # Next basic block to be processed after the current one (if any), set by caller\n        self.next_block: BasicBlock | None = None\n        # Ops in the basic block currently being processed, set by caller\n        self.ops: list[Op] = []\n        # Current index within ops; visit methods can increment this to skip/merge ops\n        self.op_index = 0\n\n    def temp_name(self) -> str:\n        return self.emitter.temp_name()\n\n    def visit_goto(self, op: Goto) -> None:\n        if op.label is not self.next_block:\n            self.emit_line(\"goto %s;\" % self.label(op.label))\n\n    def error_value_check(self, value: Value, compare: str) -> str:\n        typ = value.type\n        if isinstance(typ, RTuple):\n            # TODO: What about empty tuple?\n            return self.emitter.tuple_undefined_check_cond(\n                typ, self.reg(value), self.c_error_value, compare\n            )\n        elif isinstance(typ, RVec):\n            # Error values for vecs are represented by a negative length.\n            vec_compare = \">=\" if compare == \"!=\" else \"<\"\n            return f\"{self.reg(value)}.len {vec_compare} 0\"\n        else:\n            return f\"{self.reg(value)} {compare} {self.c_error_value(typ)}\"\n\n    def visit_branch(self, op: Branch) -> None:\n        true, false = op.true, op.false\n        negated = op.negated\n        negated_rare = False\n        if true is self.next_block and op.traceback_entry is None:\n            # Switch true/false since it avoids an else block.\n            true, false = false, true\n            negated = not negated\n            negated_rare = True\n\n        neg = \"!\" if negated else \"\"\n        cond = \"\"\n        if op.op == Branch.BOOL:\n            expr_result = self.reg(op.value)\n            cond = f\"{neg}{expr_result}\"\n        elif op.op == Branch.IS_ERROR:\n            compare = \"!=\" if negated else \"==\"\n            cond = self.error_value_check(op.value, compare)\n        else:\n            assert False, \"Invalid branch\"\n\n        # For error checks, tell the compiler the branch is unlikely\n        if op.traceback_entry is not None or op.rare:\n            if not negated_rare:\n                cond = f\"unlikely({cond})\"\n            else:\n                cond = f\"likely({cond})\"\n\n        if false is self.next_block:\n            if op.traceback_entry is None:\n                if true is not self.next_block:\n                    self.emit_line(f\"if ({cond}) goto {self.label(true)};\")\n            else:\n                self.emit_line(f\"if ({cond}) {{\")\n                self.emit_traceback(op)\n                self.emit_lines(\"goto %s;\" % self.label(true), \"}\")\n        else:\n            self.emit_line(f\"if ({cond}) {{\")\n            self.emit_traceback(op)\n\n            if true is not self.next_block:\n                self.emit_line(\"goto %s;\" % self.label(true))\n\n            self.emit_lines(\"} else\", \"    goto %s;\" % self.label(false))\n\n    def visit_return(self, op: Return) -> None:\n        value_str = self.reg(op.value)\n        self.emit_line(\"return %s;\" % value_str)\n\n    def visit_tuple_set(self, op: TupleSet) -> None:\n        dest = self.reg(op)\n        tuple_type = op.tuple_type\n        self.emitter.declare_tuple_struct(tuple_type)\n        if len(op.items) == 0:  # empty tuple\n            self.emit_line(f\"{dest}.empty_struct_error_flag = 0;\")\n        else:\n            for i, item in enumerate(op.items):\n                self.emit_line(f\"{dest}.f{i} = {self.reg(item)};\")\n\n    def visit_assign(self, op: Assign) -> None:\n        dest = self.reg(op.dest)\n        src = self.reg(op.src)\n        # clang whines about self assignment (which we might generate\n        # for some casts), so don't emit it.\n        if dest != src:\n            src_type = op.src.type\n            dest_type = op.dest.type\n            if src_type.is_unboxed and not dest_type.is_unboxed:\n                # We sometimes assign from an integer prepresentation of a pointer\n                # to a real pointer, and C compilers insist on a cast.\n                src = f\"(void *){src}\"\n            elif not src_type.is_unboxed and dest_type.is_unboxed:\n                # We sometimes assign a pointer to an integer type (e.g. to create\n                # tagged pointers), and here we need an explicit cast.\n                src = f\"({self.emitter.ctype(dest_type)}){src}\"\n            self.emit_line(f\"{dest} = {src};\")\n\n    def visit_assign_multi(self, op: AssignMulti) -> None:\n        typ = op.dest.type\n        assert isinstance(typ, RArray), typ\n        dest = self.reg(op.dest)\n        # RArray values can only be assigned to once, so we can always\n        # declare them on initialization.\n        self.emit_line(\n            \"%s%s[%d] = %s;\"\n            % (\n                self.emitter.ctype_spaced(typ.item_type),\n                dest,\n                len(op.src),\n                c_array_initializer([self.reg(s) for s in op.src], indented=True),\n            )\n        )\n\n    def visit_load_error_value(self, op: LoadErrorValue) -> None:\n        reg = self.reg(op)\n        if isinstance(op.type, RTuple):\n            values = [self.c_undefined_value(item) for item in op.type.types]\n            tmp = self.temp_name()\n            self.emit_line(\"{} {} = {{ {} }};\".format(self.ctype(op.type), tmp, \", \".join(values)))\n            self.emit_line(f\"{reg} = {tmp};\")\n        elif isinstance(op.type, RVec):\n            self.emitter.set_undefined_value(reg, op.type)\n        else:\n            self.emit_line(f\"{self.reg(op)} = {self.c_error_value(op.type)};\")\n\n    def visit_load_literal(self, op: LoadLiteral) -> None:\n        index = self.literals.literal_index(op.value)\n        if not is_int_rprimitive(op.type):\n            self.emit_line(\"%s = CPyStatics[%d];\" % (self.reg(op), index), ann=op.value)\n        else:\n            self.emit_line(\n                \"%s = (CPyTagged)CPyStatics[%d] | 1;\" % (self.reg(op), index), ann=op.value\n            )\n\n    def get_attr_expr(self, obj: str, op: GetAttr | SetAttr, decl_cl: ClassIR) -> str:\n        \"\"\"Generate attribute accessor for normal (non-property) access.\n\n        This either has a form like obj->attr_name for attributes defined in non-trait\n        classes, and *(obj + attr_offset) for attributes defined by traits. We also\n        insert all necessary C casts here.\n        \"\"\"\n        cast = f\"({op.class_type.struct_name(self.emitter.names)} *)\"\n        if decl_cl.is_trait and op.class_type.class_ir.is_trait:\n            # For pure trait access find the offset first, offsets\n            # are ordered by attribute position in the cl.attributes dict.\n            # TODO: pre-calculate the mapping to make this faster.\n            trait_attr_index = list(decl_cl.attributes).index(op.attr)\n            # TODO: reuse these names somehow?\n            offset = self.emitter.temp_name()\n            self.declarations.emit_line(f\"size_t {offset};\")\n            self.emitter.emit_line(\n                \"{} = {};\".format(\n                    offset,\n                    \"CPy_FindAttrOffset({}, {}, {})\".format(\n                        self.emitter.type_struct_name(decl_cl),\n                        f\"({cast}{obj})->vtable\",\n                        trait_attr_index,\n                    ),\n                )\n            )\n            attr_cast = f\"({self.ctype(op.class_type.attr_type(op.attr))} *)\"\n            return f\"*{attr_cast}((char *){obj} + {offset})\"\n        else:\n            # Cast to something non-trait. Note: for this to work, all struct\n            # members for non-trait classes must obey monotonic linear growth.\n            if op.class_type.class_ir.is_trait:\n                assert not decl_cl.is_trait\n                cast = f\"({decl_cl.struct_name(self.emitter.names)} *)\"\n            return f\"({cast}{obj})->{self.emitter.attr(op.attr)}\"\n\n    def visit_get_attr(self, op: GetAttr) -> None:\n        if op.allow_error_value:\n            self.get_attr_with_allow_error_value(op)\n            return\n        dest = self.reg(op)\n        obj = self.reg(op.obj)\n        rtype = op.class_type\n        cl = rtype.class_ir\n        attr_rtype, decl_cl = cl.attr_details(op.attr)\n        prefer_method = cl.is_trait and attr_rtype.error_overlap\n        if cl.get_method(op.attr, prefer_method=prefer_method):\n            # Properties are essentially methods, so use vtable access for them.\n            if cl.is_method_final(op.attr):\n                self.emit_method_call(f\"{dest} = \", op.obj, op.attr, [])\n            else:\n                version = \"_TRAIT\" if cl.is_trait else \"\"\n                self.emit_line(\n                    \"%s = CPY_GET_ATTR%s(%s, %s, %d, %s, %s); /* %s */\"\n                    % (\n                        dest,\n                        version,\n                        obj,\n                        self.emitter.type_struct_name(rtype.class_ir),\n                        rtype.getter_index(op.attr),\n                        rtype.struct_name(self.names),\n                        self.ctype(rtype.attr_type(op.attr)),\n                        op.attr,\n                    )\n                )\n        else:\n            # Otherwise, use direct or offset struct access.\n            attr_expr = self.get_attr_expr(obj, op, decl_cl)\n            self.emitter.emit_line(f\"{dest} = {attr_expr};\")\n            always_defined = cl.is_always_defined(op.attr)\n            merged_branch = None\n            if not always_defined:\n                self.emitter.emit_undefined_attr_check(\n                    attr_rtype, dest, \"==\", obj, op.attr, cl, unlikely=True\n                )\n                branch = self.next_branch()\n                if branch is not None:\n                    if (\n                        branch.value is op\n                        and branch.op == Branch.IS_ERROR\n                        and branch.traceback_entry is not None\n                        and not branch.negated\n                    ):\n                        # Generate code for the following branch here to avoid\n                        # redundant branches in the generated code.\n                        self.emit_attribute_error(branch, cl.name, op.attr)\n                        self.emit_line(\"goto %s;\" % self.label(branch.true))\n                        merged_branch = branch\n                        self.emitter.emit_line(\"}\")\n                if not merged_branch:\n                    exc_class = \"PyExc_AttributeError\"\n                    self.emitter.emit_line(\n                        'PyErr_SetString({}, \"attribute {} of {} undefined\");'.format(\n                            exc_class,\n                            repr(op.attr.removeprefix(GENERATOR_ATTRIBUTE_PREFIX)),\n                            repr(cl.name),\n                        )\n                    )\n\n            if attr_rtype.is_refcounted and not op.is_borrowed:\n                if not merged_branch and not always_defined:\n                    self.emitter.emit_line(\"} else {\")\n                self.emitter.emit_inc_ref(dest, attr_rtype)\n            if merged_branch:\n                if merged_branch.false is not self.next_block:\n                    self.emit_line(\"goto %s;\" % self.label(merged_branch.false))\n                self.op_index += 1\n            elif not always_defined:\n                self.emitter.emit_line(\"}\")\n\n    def get_attr_with_allow_error_value(self, op: GetAttr) -> None:\n        \"\"\"Handle GetAttr with allow_error_value=True.\n\n        This allows NULL or other error value without raising AttributeError.\n        \"\"\"\n        dest = self.reg(op)\n        obj = self.reg(op.obj)\n        rtype = op.class_type\n        cl = rtype.class_ir\n        attr_rtype, decl_cl = cl.attr_details(op.attr)\n\n        # Direct struct access without NULL check\n        attr_expr = self.get_attr_expr(obj, op, decl_cl)\n        self.emitter.emit_line(f\"{dest} = {attr_expr};\")\n\n        # Only emit inc_ref if not NULL\n        if attr_rtype.is_refcounted and not op.is_borrowed:\n            check = self.error_value_check(op, \"!=\")\n            self.emitter.emit_line(f\"if ({check}) {{\")\n            self.emitter.emit_inc_ref(dest, attr_rtype)\n            self.emitter.emit_line(\"}\")\n\n    def next_branch(self) -> Branch | None:\n        if self.op_index + 1 < len(self.ops):\n            next_op = self.ops[self.op_index + 1]\n            if isinstance(next_op, Branch):\n                return next_op\n        return None\n\n    def visit_set_attr(self, op: SetAttr) -> None:\n        if op.error_kind == ERR_FALSE:\n            dest = self.reg(op)\n        obj = self.reg(op.obj)\n        src = self.reg(op.src)\n        rtype = op.class_type\n        cl = rtype.class_ir\n        attr_rtype, decl_cl = cl.attr_details(op.attr)\n        if cl.get_method(op.attr):\n            # Again, use vtable access for properties...\n            assert not op.is_init and op.error_kind == ERR_FALSE, \"%s %d %d %s\" % (\n                op.attr,\n                op.is_init,\n                op.error_kind,\n                rtype,\n            )\n            version = \"_TRAIT\" if cl.is_trait else \"\"\n            self.emit_line(\n                \"%s = CPY_SET_ATTR%s(%s, %s, %d, %s, %s, %s); /* %s */\"\n                % (\n                    dest,\n                    version,\n                    obj,\n                    self.emitter.type_struct_name(rtype.class_ir),\n                    rtype.setter_index(op.attr),\n                    src,\n                    rtype.struct_name(self.names),\n                    self.ctype(rtype.attr_type(op.attr)),\n                    op.attr,\n                )\n            )\n        else:\n            # ...and struct access for normal attributes.\n            attr_expr = self.get_attr_expr(obj, op, decl_cl)\n            if not op.is_init and attr_rtype.is_refcounted:\n                # This is not an initialization (where we know that the attribute was\n                # previously undefined), so decref the old value.\n                always_defined = cl.is_always_defined(op.attr)\n                if not always_defined:\n                    self.emitter.emit_undefined_attr_check(\n                        attr_rtype, attr_expr, \"!=\", obj, op.attr, cl\n                    )\n                self.emitter.emit_dec_ref(attr_expr, attr_rtype)\n                if not always_defined:\n                    self.emitter.emit_line(\"}\")\n            elif attr_rtype.error_overlap and not cl.is_always_defined(op.attr):\n                # If there is overlap with the error value, update bitmap to mark\n                # attribute as defined.\n                self.emitter.emit_attr_bitmap_set(src, obj, attr_rtype, cl, op.attr)\n\n            # This steals the reference to src, so we don't need to increment the arg\n            self.emitter.emit_line(f\"{attr_expr} = {src};\")\n            if op.error_kind == ERR_FALSE:\n                self.emitter.emit_line(f\"{dest} = 1;\")\n\n    def visit_load_static(self, op: LoadStatic) -> None:\n        dest = self.reg(op)\n        prefix = PREFIX_MAP[op.namespace]\n        name = self.emitter.static_name(op.identifier, op.module_name, prefix)\n        if op.namespace == NAMESPACE_TYPE:\n            name = \"(PyObject *)%s\" % name\n        self.emit_line(f\"{dest} = {name};\", ann=op.ann)\n\n    def visit_init_static(self, op: InitStatic) -> None:\n        value = self.reg(op.value)\n        prefix = PREFIX_MAP[op.namespace]\n        name = self.emitter.static_name(op.identifier, op.module_name, prefix)\n        if op.namespace == NAMESPACE_TYPE:\n            value = \"(PyTypeObject *)%s\" % value\n        self.emit_line(f\"{name} = {value};\")\n        self.emit_inc_ref(name, op.value.type)\n\n    def visit_tuple_get(self, op: TupleGet) -> None:\n        dest = self.reg(op)\n        src = self.reg(op.src)\n        self.emit_line(f\"{dest} = {src}.f{op.index};\")\n        if not op.is_borrowed:\n            self.emit_inc_ref(dest, op.type)\n\n    def get_dest_assign(self, dest: Value) -> str:\n        if not dest.is_void:\n            return self.reg(dest) + \" = \"\n        else:\n            return \"\"\n\n    def visit_call(self, op: Call) -> None:\n        \"\"\"Call native function.\"\"\"\n        dest = self.get_dest_assign(op)\n        args = \", \".join(self.reg(arg) for arg in op.args)\n        lib = self.emitter.get_group_prefix(op.fn)\n        cname = op.fn.cname(self.names)\n        self.emit_line(f\"{dest}{lib}{NATIVE_PREFIX}{cname}({args});\")\n\n    def visit_method_call(self, op: MethodCall) -> None:\n        \"\"\"Call native method.\"\"\"\n        dest = self.get_dest_assign(op)\n        self.emit_method_call(dest, op.obj, op.method, op.args)\n\n    def emit_method_call(self, dest: str, op_obj: Value, name: str, op_args: list[Value]) -> None:\n        obj = self.reg(op_obj)\n        rtype = op_obj.type\n        assert isinstance(rtype, RInstance), rtype\n        class_ir = rtype.class_ir\n        method = rtype.class_ir.get_method(name)\n        assert method is not None\n\n        # Can we call the method directly, bypassing vtable?\n        is_direct = class_ir.is_method_final(name)\n\n        # The first argument gets omitted for static methods and\n        # turned into the class for class methods\n        obj_args = (\n            []\n            if method.decl.kind == FUNC_STATICMETHOD\n            else [f\"(PyObject *)Py_TYPE({obj})\"] if method.decl.kind == FUNC_CLASSMETHOD else [obj]\n        )\n        args = \", \".join(obj_args + [self.reg(arg) for arg in op_args])\n        mtype = native_function_type(method, self.emitter)\n        version = \"_TRAIT\" if rtype.class_ir.is_trait else \"\"\n        if is_direct:\n            # Directly call method, without going through the vtable.\n            lib = self.emitter.get_group_prefix(method.decl)\n            self.emit_line(f\"{dest}{lib}{NATIVE_PREFIX}{method.cname(self.names)}({args});\")\n        else:\n            # Call using vtable.\n            method_idx = rtype.method_index(name)\n            self.emit_line(\n                \"{}CPY_GET_METHOD{}({}, {}, {}, {}, {})({}); /* {} */\".format(\n                    dest,\n                    version,\n                    obj,\n                    self.emitter.type_struct_name(rtype.class_ir),\n                    method_idx,\n                    rtype.struct_name(self.names),\n                    mtype,\n                    args,\n                    name,\n                )\n            )\n\n    def visit_inc_ref(self, op: IncRef) -> None:\n        if (\n            isinstance(op.src, Box)\n            and (is_none_rprimitive(op.src.src.type) or is_bool_or_bit_rprimitive(op.src.src.type))\n            and HAVE_IMMORTAL\n        ):\n            # On Python 3.12+, None/True/False are immortal, and we can skip inc ref\n            return\n\n        if isinstance(op.src, LoadLiteral) and HAVE_IMMORTAL:\n            value = op.src.value\n            # We can skip inc ref for immortal literals on Python 3.12+\n            if type(value) is int and -5 <= value <= 256:\n                # Small integers are immortal\n                return\n\n        src = self.reg(op.src)\n        self.emit_inc_ref(src, op.src.type)\n\n    def visit_dec_ref(self, op: DecRef) -> None:\n        src = self.reg(op.src)\n        self.emit_dec_ref(src, op.src.type, is_xdec=op.is_xdec)\n\n    def visit_box(self, op: Box) -> None:\n        self.emitter.emit_box(self.reg(op.src), self.reg(op), op.src.type, can_borrow=True)\n\n    def visit_cast(self, op: Cast) -> None:\n        if op.is_unchecked and op.is_borrowed:\n            self.emit_line(f\"{self.reg(op)} = {self.reg(op.src)};\")\n            return\n        branch = self.next_branch()\n        handler = None\n        if branch is not None:\n            if (\n                branch.value is op\n                and branch.op == Branch.IS_ERROR\n                and branch.traceback_entry is not None\n                and not branch.negated\n                and branch.false is self.next_block\n            ):\n                # Generate code also for the following branch here to avoid\n                # redundant branches in the generated code.\n                handler = TracebackAndGotoHandler(\n                    self.label(branch.true),\n                    self.source_path,\n                    self.module_name,\n                    branch.traceback_entry,\n                )\n                self.op_index += 1\n\n        self.emitter.emit_cast(\n            self.reg(op.src), self.reg(op), op.type, src_type=op.src.type, error=handler\n        )\n\n    def visit_unbox(self, op: Unbox) -> None:\n        self.emitter.emit_unbox(self.reg(op.src), self.reg(op), op.type)\n\n    def visit_unreachable(self, op: Unreachable) -> None:\n        self.emitter.emit_line(\"CPy_Unreachable();\")\n\n    def visit_raise_standard_error(self, op: RaiseStandardError) -> None:\n        # TODO: Better escaping of backspaces and such\n        if op.value is not None:\n            if isinstance(op.value, str):\n                message = op.value.replace('\"', '\\\\\"')\n                self.emitter.emit_line(f'PyErr_SetString(PyExc_{op.class_name}, \"{message}\");')\n            elif isinstance(op.value, Value):\n                self.emitter.emit_line(\n                    \"PyErr_SetObject(PyExc_{}, {});\".format(\n                        op.class_name, self.emitter.reg(op.value)\n                    )\n                )\n            else:\n                assert False, \"op value type must be either str or Value\"\n        else:\n            self.emitter.emit_line(f\"PyErr_SetNone(PyExc_{op.class_name});\")\n        self.emitter.emit_line(f\"{self.reg(op)} = 0;\")\n\n    def visit_call_c(self, op: CallC) -> None:\n        if op.is_void:\n            dest = \"\"\n        else:\n            dest = self.get_dest_assign(op)\n        args = \", \".join(self.reg(arg) for arg in op.args)\n        self.emitter.emit_line(f\"{dest}{op.function_name}({args});\")\n\n    def visit_primitive_op(self, op: PrimitiveOp) -> None:\n        raise RuntimeError(\n            f\"unexpected PrimitiveOp {op.desc.name}: they must be lowered before codegen\"\n        )\n\n    def visit_truncate(self, op: Truncate) -> None:\n        dest = self.reg(op)\n        value = self.reg(op.src)\n        # for C backend the generated code are straight assignments\n        self.emit_line(f\"{dest} = {value};\")\n\n    def visit_extend(self, op: Extend) -> None:\n        dest = self.reg(op)\n        value = self.reg(op.src)\n        if op.signed:\n            src_cast = self.emit_signed_int_cast(op.src.type)\n        else:\n            src_cast = self.emit_unsigned_int_cast(op.src.type)\n        self.emit_line(f\"{dest} = {src_cast}{value};\")\n\n    def visit_load_global(self, op: LoadGlobal) -> None:\n        dest = self.reg(op)\n        self.emit_line(f\"{dest} = {op.identifier};\", ann=op.ann)\n\n    def visit_int_op(self, op: IntOp) -> None:\n        dest = self.reg(op)\n        lhs = self.reg(op.lhs)\n        rhs = self.reg(op.rhs)\n        if op.op == IntOp.RIGHT_SHIFT:\n            # Signed right shift\n            lhs = self.emit_signed_int_cast(op.lhs.type) + lhs\n            rhs = self.emit_signed_int_cast(op.rhs.type) + rhs\n        self.emit_line(f\"{dest} = {lhs} {op.op_str[op.op]} {rhs};\")\n\n    def visit_comparison_op(self, op: ComparisonOp) -> None:\n        dest = self.reg(op)\n        lhs = self.reg(op.lhs)\n        rhs = self.reg(op.rhs)\n        lhs_cast = \"\"\n        rhs_cast = \"\"\n        if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE):\n            # Always signed comparison op\n            lhs_cast = self.emit_signed_int_cast(op.lhs.type)\n            rhs_cast = self.emit_signed_int_cast(op.rhs.type)\n        elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE):\n            # Always unsigned comparison op\n            lhs_cast = self.emit_unsigned_int_cast(op.lhs.type)\n            rhs_cast = self.emit_unsigned_int_cast(op.rhs.type)\n        elif isinstance(op.lhs, Integer) and op.lhs.value < 0:\n            # Force signed ==/!= with negative operand\n            rhs_cast = self.emit_signed_int_cast(op.rhs.type)\n        elif isinstance(op.rhs, Integer) and op.rhs.value < 0:\n            # Force signed ==/!= with negative operand\n            lhs_cast = self.emit_signed_int_cast(op.lhs.type)\n        self.emit_line(f\"{dest} = {lhs_cast}{lhs} {op.op_str[op.op]} {rhs_cast}{rhs};\")\n\n    def visit_float_op(self, op: FloatOp) -> None:\n        dest = self.reg(op)\n        lhs = self.reg(op.lhs)\n        rhs = self.reg(op.rhs)\n        if op.op != FloatOp.MOD:\n            self.emit_line(f\"{dest} = {lhs} {op.op_str[op.op]} {rhs};\")\n        else:\n            # TODO: This may set errno as a side effect, that is a little sketchy.\n            self.emit_line(f\"{dest} = fmod({lhs}, {rhs});\")\n\n    def visit_float_neg(self, op: FloatNeg) -> None:\n        dest = self.reg(op)\n        src = self.reg(op.src)\n        self.emit_line(f\"{dest} = -{src};\")\n\n    def visit_float_comparison_op(self, op: FloatComparisonOp) -> None:\n        dest = self.reg(op)\n        lhs = self.reg(op.lhs)\n        rhs = self.reg(op.rhs)\n        self.emit_line(f\"{dest} = {lhs} {op.op_str[op.op]} {rhs};\")\n\n    def visit_load_mem(self, op: LoadMem) -> None:\n        dest = self.reg(op)\n        src = self.reg(op.src)\n        # TODO: we shouldn't dereference to type that are pointer type so far\n        type = self.ctype(op.type)\n        self.emit_line(f\"{dest} = *({type} *){src};\")\n        if not op.is_borrowed:\n            self.emit_inc_ref(dest, op.type)\n\n    def visit_set_mem(self, op: SetMem) -> None:\n        dest = self.reg(op.dest)\n        src = self.reg(op.src)\n        dest_type = self.ctype(op.dest_type)\n        # clang whines about self assignment (which we might generate\n        # for some casts), so don't emit it.\n        if dest != src:\n            self.emit_line(f\"*({dest_type} *){dest} = {src};\")\n\n    def visit_get_element(self, op: GetElement) -> None:\n        dest = self.reg(op)\n        src = self.reg(op.src)\n        dest_type = self.ctype(op.type)\n        self.emit_line(f\"{dest} = ({dest_type}){src}.{op.field};\")\n\n    def visit_get_element_ptr(self, op: GetElementPtr) -> None:\n        dest = self.reg(op)\n        src = self.reg(op.src)\n        # TODO: support tuple type\n        assert isinstance(op.src_type, RStruct), op.src_type\n        assert op.field in op.src_type.names, \"Invalid field name.\"\n        self.emit_line(\n            \"{} = ({})&(({} *){})->{};\".format(\n                dest, op.type._ctype, op.src_type.name, src, op.field\n            )\n        )\n\n    def visit_set_element(self, op: SetElement) -> None:\n        dest = self.reg(op)\n        item = self.reg(op.item)\n        field = op.field\n        if isinstance(op.src, Undef):\n            # First assignment to an undefined struct is trivial.\n            self.emit_line(f\"{dest}.{field} = {item};\")\n        else:\n            # In the general case create a copy of the struct with a single\n            # item modified.\n            #\n            # TODO: Can we do better if only a subset of fields are initialized?\n            # TODO: Make this less verbose in the common case\n            # TODO: Support tuples (or use RStruct for tuples)?\n            src = self.reg(op.src)\n            src_type = op.src.type\n            assert isinstance(src_type, RStruct), src_type\n            init_items = []\n            for n in src_type.names:\n                if n != field:\n                    init_items.append(f\"{src}.{n}\")\n                else:\n                    init_items.append(item)\n            self.emit_line(f\"{dest} = ({self.ctype(src_type)}) {{ {', '.join(init_items)} }};\")\n\n    def visit_load_address(self, op: LoadAddress) -> None:\n        typ = op.type\n        dest = self.reg(op)\n        if isinstance(op.src, Register):\n            src = self.reg(op.src)\n        elif isinstance(op.src, LoadStatic):\n            prefix = PREFIX_MAP[op.src.namespace]\n            src = self.emitter.static_name(op.src.identifier, op.src.module_name, prefix)\n        else:\n            src = op.src\n        self.emit_line(f\"{dest} = ({typ._ctype})&{src};\")\n\n    def visit_keep_alive(self, op: KeepAlive) -> None:\n        # This is a no-op.\n        pass\n\n    def visit_unborrow(self, op: Unborrow) -> None:\n        # This is a no-op that propagates the source value.\n        dest = self.reg(op)\n        src = self.reg(op.src)\n        self.emit_line(f\"{dest} = {src};\")\n\n    # Helpers\n\n    def label(self, label: BasicBlock) -> str:\n        return self.emitter.label(label)\n\n    def reg(self, reg: Value) -> str:\n        if isinstance(reg, Integer):\n            val = reg.value\n            if val == 0 and is_pointer_rprimitive(reg.type):\n                return \"NULL\"\n            s = str(val)\n            if val >= (1 << 31):\n                # Avoid overflowing signed 32-bit int\n                if val >= (1 << 63):\n                    s += \"ULL\"\n                else:\n                    s += \"LL\"\n            elif val == -(1 << 63):\n                # Avoid overflowing C integer literal\n                s = \"(-9223372036854775807LL - 1)\"\n            elif val <= -(1 << 31):\n                s += \"LL\"\n            return s\n        elif isinstance(reg, Float):\n            r = repr(reg.value)\n            if r == \"inf\":\n                return \"INFINITY\"\n            elif r == \"-inf\":\n                return \"-INFINITY\"\n            elif r == \"nan\":\n                return \"NAN\"\n            return r\n        elif isinstance(reg, CString):\n            return '\"' + encode_c_string_literal(reg.value) + '\"'\n        else:\n            return self.emitter.reg(reg)\n\n    def ctype(self, rtype: RType) -> str:\n        return self.emitter.ctype(rtype)\n\n    def c_error_value(self, rtype: RType) -> str:\n        return self.emitter.c_error_value(rtype)\n\n    def c_undefined_value(self, rtype: RType) -> str:\n        return self.emitter.c_undefined_value(rtype)\n\n    def emit_line(self, line: str, *, ann: object = None) -> None:\n        self.emitter.emit_line(line, ann=ann)\n\n    def emit_lines(self, *lines: str) -> None:\n        self.emitter.emit_lines(*lines)\n\n    def emit_inc_ref(self, dest: str, rtype: RType) -> None:\n        self.emitter.emit_inc_ref(dest, rtype, rare=self.rare)\n\n    def emit_dec_ref(self, dest: str, rtype: RType, is_xdec: bool) -> None:\n        self.emitter.emit_dec_ref(dest, rtype, is_xdec=is_xdec, rare=self.rare)\n\n    def emit_declaration(self, line: str) -> None:\n        self.declarations.emit_line(line)\n\n    def emit_traceback(self, op: Branch) -> None:\n        if op.traceback_entry is not None:\n            self.emitter.emit_traceback(self.source_path, self.module_name, op.traceback_entry)\n\n    def emit_attribute_error(self, op: Branch, class_name: str, attr: str) -> None:\n        assert op.traceback_entry is not None\n        if self.emitter.context.strict_traceback_checks:\n            assert (\n                op.traceback_entry[1] >= 0\n            ), \"AttributeError traceback cannot have a negative line number\"\n        globals_static = self.emitter.static_name(\"globals\", self.module_name)\n        self.emit_line(\n            'CPy_AttributeError(\"%s\", \"%s\", \"%s\", \"%s\", %d, %s);'\n            % (\n                self.source_path.replace(\"\\\\\", \"\\\\\\\\\"),\n                op.traceback_entry[0],\n                class_name,\n                attr.removeprefix(GENERATOR_ATTRIBUTE_PREFIX),\n                op.traceback_entry[1],\n                globals_static,\n            )\n        )\n        if DEBUG_ERRORS:\n            self.emit_line('assert(PyErr_Occurred() != NULL && \"failure w/o err!\");')\n\n    def emit_signed_int_cast(self, type: RType) -> str:\n        if is_tagged(type):\n            return \"(Py_ssize_t)\"\n        else:\n            return \"\"\n\n    def emit_unsigned_int_cast(self, type: RType) -> str:\n        if is_int32_rprimitive(type):\n            return \"(uint32_t)\"\n        elif is_int64_rprimitive(type):\n            return \"(uint64_t)\"\n        else:\n            return \"\"\n\n\n_translation_table: Final[dict[int, str]] = {}\n\n\ndef encode_c_string_literal(b: bytes) -> str:\n    \"\"\"Convert bytestring to the C string literal syntax (with necessary escaping).\n\n    For example, b'foo\\n' gets converted to 'foo\\\\n' (note that double quotes are not added).\n    \"\"\"\n    if not _translation_table:\n        # Initialize the translation table on the first call.\n        d = {\n            ord(\"\\n\"): \"\\\\n\",\n            ord(\"\\r\"): \"\\\\r\",\n            ord(\"\\t\"): \"\\\\t\",\n            ord('\"'): '\\\\\"',\n            ord(\"\\\\\"): \"\\\\\\\\\",\n        }\n        for i in range(256):\n            if i not in d:\n                if i < 32 or i >= 127:\n                    d[i] = \"\\\\x%.2x\" % i\n                else:\n                    d[i] = chr(i)\n        _translation_table.update(str.maketrans(d))\n    return b.decode(\"latin1\").translate(_translation_table)\n"
  },
  {
    "path": "mypyc/codegen/emitmodule.py",
    "content": "\"\"\"Generate C code for a Python C extension module from Python source code.\"\"\"\n\n# FIXME: Basically nothing in this file operates on the level of a\n#        single module and it should be renamed.\n\nfrom __future__ import annotations\n\nimport json\nimport os\nimport sys\nfrom collections.abc import Iterable\nfrom typing import TypeVar\n\nfrom mypy.build import (\n    BuildResult,\n    BuildSource,\n    State,\n    build,\n    compute_hash,\n    create_metastore,\n    get_cache_names,\n    sorted_components,\n)\nfrom mypy.errors import CompileError\nfrom mypy.fscache import FileSystemCache\nfrom mypy.nodes import MypyFile\nfrom mypy.options import Options\nfrom mypy.plugin import Plugin, ReportConfigContext\nfrom mypy.util import hash_digest, json_dumps\nfrom mypyc.analysis.capsule_deps import find_class_dependencies, find_implicit_op_dependencies\nfrom mypyc.codegen.cstring import c_string_initializer\nfrom mypyc.codegen.emit import (\n    Emitter,\n    EmitterContext,\n    HeaderDeclaration,\n    c_array_initializer,\n    native_function_doc_initializer,\n)\nfrom mypyc.codegen.emitclass import generate_class, generate_class_reuse, generate_class_type_decl\nfrom mypyc.codegen.emitfunc import generate_native_function, native_function_header\nfrom mypyc.codegen.emitwrapper import (\n    generate_legacy_wrapper_function,\n    generate_wrapper_function,\n    legacy_wrapper_function_header,\n    wrapper_function_header,\n)\nfrom mypyc.codegen.literals import Literals\nfrom mypyc.common import (\n    IS_FREE_THREADED,\n    MODULE_PREFIX,\n    PREFIX,\n    RUNTIME_C_FILES,\n    TOP_LEVEL_NAME,\n    TYPE_VAR_PREFIX,\n    shared_lib_name,\n    short_id_from_name,\n)\nfrom mypyc.errors import Errors\nfrom mypyc.ir.deps import LIBRT_BASE64, LIBRT_STRINGS, LIBRT_TIME, LIBRT_VECS, SourceDep\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.module_ir import ModuleIR, ModuleIRs, deserialize_modules\nfrom mypyc.ir.ops import DeserMaps, LoadLiteral\nfrom mypyc.ir.rtypes import RType\nfrom mypyc.irbuild.main import build_ir\nfrom mypyc.irbuild.mapper import Mapper\nfrom mypyc.irbuild.prepare import load_type_map\nfrom mypyc.namegen import NameGenerator, exported_name\nfrom mypyc.options import CompilerOptions\nfrom mypyc.transform.copy_propagation import do_copy_propagation\nfrom mypyc.transform.exceptions import insert_exception_handling\nfrom mypyc.transform.flag_elimination import do_flag_elimination\nfrom mypyc.transform.log_trace import insert_event_trace_logging\nfrom mypyc.transform.lower import lower_ir\nfrom mypyc.transform.refcount import insert_ref_count_opcodes\nfrom mypyc.transform.spill import insert_spills\nfrom mypyc.transform.uninit import insert_uninit_checks\n\n# All the modules being compiled are divided into \"groups\". A group\n# is a set of modules that are placed into the same shared library.\n# Two common configurations are that every module is placed in a group\n# by itself (fully separate compilation) and that every module is\n# placed in the same group (fully whole-program compilation), but we\n# support finer-grained control of the group as well.\n#\n# In fully whole-program compilation, we will generate N+1 extension\n# modules: one shim per module and one shared library containing all\n# the actual code.\n# In fully separate compilation, we (unfortunately) will generate 2*N\n# extension modules: one shim per module and also one library containing\n# each module's actual code. (This might be fixable in the future,\n# but allows a clean separation between setup of the export tables\n# (see generate_export_table) and running module top levels.)\n#\n# A group is represented as a list of BuildSources containing all of\n# its modules along with the name of the group. (Which can be None\n# only if we are compiling only a single group with a single file in it\n# and not using shared libraries).\nGroup = tuple[list[BuildSource], str | None]\nGroups = list[Group]\n\n# A list of (file name, file contents) pairs.\nFileContents = list[tuple[str, str]]\n\n\nclass MarkedDeclaration:\n    \"\"\"Add a mark, useful for topological sort.\"\"\"\n\n    def __init__(self, declaration: HeaderDeclaration, mark: bool) -> None:\n        self.declaration = declaration\n        self.mark = False\n\n\nclass MypycPlugin(Plugin):\n    \"\"\"Plugin for making mypyc interoperate properly with mypy incremental mode.\n\n    Basically the point of this plugin is to force mypy to recheck things\n    based on the demands of mypyc in a couple situations:\n      * Any modules in the same group must be compiled together, so we\n        tell mypy that modules depend on all their groupmates.\n      * If the IR metadata is missing or stale or any of the generated\n        C source files associated missing or stale, then we need to\n        recompile the module so we mark it as stale.\n    \"\"\"\n\n    def __init__(\n        self, options: Options, compiler_options: CompilerOptions, groups: Groups\n    ) -> None:\n        super().__init__(options)\n        self.group_map: dict[str, tuple[str | None, list[str]]] = {}\n        for sources, name in groups:\n            modules = sorted(source.module for source in sources)\n            for id in modules:\n                self.group_map[id] = (name, modules)\n\n        self.compiler_options = compiler_options\n        self.metastore = create_metastore(options)\n\n    def report_config_data(self, ctx: ReportConfigContext) -> tuple[str | None, list[str]] | None:\n        # The config data we report is the group map entry for the module.\n        # If the data is being used to check validity, we do additional checks\n        # that the IR cache exists and matches the metadata cache and all\n        # output source files exist and are up to date.\n\n        id, path, is_check = ctx.id, ctx.path, ctx.is_check\n\n        if id not in self.group_map:\n            return None\n\n        # If we aren't doing validity checks, just return the cache data\n        if not is_check:\n            return self.group_map[id]\n\n        # Load the metadata and IR cache\n        meta_path, _, _ = get_cache_names(id, path, self.options)\n        ir_path = get_ir_cache_name(id, path, self.options)\n        try:\n            meta_json = self.metastore.read(meta_path)\n            ir_json = self.metastore.read(ir_path)\n        except FileNotFoundError:\n            # This could happen if mypyc failed after mypy succeeded\n            # in the previous run or if some cache files got\n            # deleted. No big deal, just fail to load the cache.\n            return None\n\n        ir_data = json.loads(ir_json)\n\n        # Check that the IR cache matches the metadata cache\n        if hash_digest(meta_json) != ir_data[\"meta_hash\"]:\n            return None\n\n        # Check that all the source files are present and as\n        # expected. The main situation where this would come up is the\n        # user deleting the build directory without deleting\n        # .mypy_cache, which we should handle gracefully.\n        for path, hash in ir_data[\"src_hashes\"].items():\n            try:\n                with open(os.path.join(self.compiler_options.target_dir, path), \"rb\") as f:\n                    contents = f.read()\n            except FileNotFoundError:\n                return None\n            real_hash = hash_digest(contents)\n            if hash != real_hash:\n                return None\n\n        return self.group_map[id]\n\n    def get_additional_deps(self, file: MypyFile) -> list[tuple[int, str, int]]:\n        # Report dependency on modules in the module's group\n        return [(10, id, -1) for id in self.group_map.get(file.fullname, (None, []))[1]]\n\n\ndef parse_and_typecheck(\n    sources: list[BuildSource],\n    options: Options,\n    compiler_options: CompilerOptions,\n    groups: Groups,\n    fscache: FileSystemCache | None = None,\n    alt_lib_path: str | None = None,\n) -> BuildResult:\n    assert options.strict_optional, \"strict_optional must be turned on\"\n    mypyc_plugin = MypycPlugin(options, compiler_options, groups)\n    result = build(\n        sources=sources,\n        options=options,\n        alt_lib_path=alt_lib_path,\n        fscache=fscache,\n        extra_plugins=[mypyc_plugin],\n    )\n    mypyc_plugin.metastore.close()\n    if result.errors:\n        raise CompileError(result.errors)\n    return result\n\n\ndef compile_scc_to_ir(\n    scc: list[MypyFile],\n    result: BuildResult,\n    mapper: Mapper,\n    compiler_options: CompilerOptions,\n    errors: Errors,\n) -> ModuleIRs:\n    \"\"\"Compile an SCC into ModuleIRs.\n\n    Any modules that this SCC depends on must have either been compiled,\n    type checked, or loaded from a cache into mapper.\n\n    Arguments:\n        scc: The list of MypyFiles to compile\n        result: The BuildResult from the mypy front-end\n        mapper: The Mapper object mapping mypy ASTs to class and func IRs\n        compiler_options: The compilation options\n        errors: Where to report any errors encountered\n\n    Returns the IR of the modules.\n    \"\"\"\n\n    if compiler_options.verbose:\n        print(\"Compiling {}\".format(\", \".join(x.name for x in scc)))\n\n    # Generate basic IR, with missing exception and refcount handling.\n    modules = build_ir(scc, result.graph, result.types, mapper, compiler_options, errors)\n    if errors.num_errors > 0:\n        return modules\n\n    env_user_functions = {}\n    for module in modules.values():\n        for cls in module.classes:\n            if cls.env_user_function:\n                env_user_functions[cls.env_user_function] = cls\n\n    for module in modules.values():\n        for fn in module.functions:\n            # Insert checks for uninitialized values.\n            insert_uninit_checks(fn, compiler_options.strict_traceback_checks)\n            # Insert exception handling.\n            insert_exception_handling(fn, compiler_options.strict_traceback_checks)\n            # Insert reference count handling.\n            insert_ref_count_opcodes(fn)\n\n            if fn in env_user_functions:\n                insert_spills(fn, env_user_functions[fn])\n\n            if compiler_options.log_trace:\n                insert_event_trace_logging(fn, compiler_options)\n\n            # Switch to lower abstraction level IR.\n            lower_ir(fn, compiler_options)\n            # Calculate implicit module dependencies (needed for librt)\n            deps = find_implicit_op_dependencies(fn)\n            if deps is not None:\n                module.dependencies.update(deps)\n            # Perform optimizations.\n            do_copy_propagation(fn, compiler_options)\n            do_flag_elimination(fn, compiler_options)\n\n        # Calculate implicit dependencies from class attribute types\n        for cl in module.classes:\n            deps = find_class_dependencies(cl)\n            if deps is not None:\n                module.dependencies.update(deps)\n\n    return modules\n\n\ndef compile_modules_to_ir(\n    result: BuildResult, mapper: Mapper, compiler_options: CompilerOptions, errors: Errors\n) -> ModuleIRs:\n    \"\"\"Compile a collection of modules into ModuleIRs.\n\n    The modules to compile are specified as part of mapper's group_map.\n\n    Returns the IR of the modules.\n    \"\"\"\n    deser_ctx = DeserMaps({}, {})\n    modules = {}\n\n    # Process the graph by SCC in topological order, like we do in mypy.build\n    for scc in sorted_components(result.graph):\n        scc_states = [result.graph[id] for id in scc.mod_ids]\n        trees = [st.tree for st in scc_states if st.id in mapper.group_map and st.tree]\n\n        if not trees:\n            continue\n\n        fresh = all(id not in result.manager.rechecked_modules for id in scc.mod_ids)\n        if fresh:\n            load_scc_from_cache(trees, result, mapper, deser_ctx)\n        else:\n            scc_ir = compile_scc_to_ir(trees, result, mapper, compiler_options, errors)\n            modules.update(scc_ir)\n\n    return modules\n\n\ndef compile_ir_to_c(\n    groups: Groups,\n    modules: ModuleIRs,\n    result: BuildResult,\n    mapper: Mapper,\n    compiler_options: CompilerOptions,\n) -> dict[str | None, list[tuple[str, str]]]:\n    \"\"\"Compile a collection of ModuleIRs to C source text.\n\n    Returns a dictionary mapping group names to a list of (file name,\n    file text) pairs.\n    \"\"\"\n    source_paths = {\n        source.module: result.graph[source.module].xpath\n        for sources, _ in groups\n        for source in sources\n    }\n\n    names = NameGenerator(\n        [[source.module for source in sources] for sources, _ in groups],\n        separate=compiler_options.separate,\n    )\n\n    # Generate C code for each compilation group. Each group will be\n    # compiled into a separate extension module.\n    ctext: dict[str | None, list[tuple[str, str]]] = {}\n    for group_sources, group_name in groups:\n        group_modules = {\n            source.module: modules[source.module]\n            for source in group_sources\n            if source.module in modules\n        }\n        if not group_modules:\n            ctext[group_name] = []\n            continue\n        generator = GroupGenerator(\n            group_modules, source_paths, group_name, mapper.group_map, names, compiler_options\n        )\n        ctext[group_name] = generator.generate_c_for_modules()\n\n    return ctext\n\n\ndef get_ir_cache_name(id: str, path: str, options: Options) -> str:\n    meta_path, _, _ = get_cache_names(id, path, options)\n    # Mypyc uses JSON cache even with --fixed-format-cache (for now).\n    return meta_path.replace(\".meta.json\", \".ir.json\").replace(\".meta.ff\", \".ir.json\")\n\n\ndef get_state_ir_cache_name(state: State) -> str:\n    return get_ir_cache_name(state.id, state.xpath, state.options)\n\n\ndef write_cache(\n    modules: ModuleIRs,\n    result: BuildResult,\n    group_map: dict[str, str | None],\n    ctext: dict[str | None, list[tuple[str, str]]],\n) -> None:\n    \"\"\"Write out the cache information for modules.\n\n    Each module has the following cache information written (which is\n    in addition to the cache information written by mypy itself):\n      * A serialized version of its mypyc IR, minus the bodies of\n        functions. This allows code that depends on it to use\n        these serialized data structures when compiling against it\n        instead of needing to recompile it. (Compiling against a\n        module requires access to both its mypy and mypyc data\n        structures.)\n      * The hash of the mypy metadata cache file for the module.\n        This is used to ensure that the mypyc cache and the mypy\n        cache are in sync and refer to the same version of the code.\n        This is particularly important if mypyc crashes/errors/is\n        stopped after mypy has written its cache but before mypyc has.\n      * The hashes of all the source file outputs for the group\n        the module is in. This is so that the module will be\n        recompiled if the source outputs are missing.\n    \"\"\"\n\n    hashes = {}\n    for name, files in ctext.items():\n        hashes[name] = {file: compute_hash(data) for file, data in files}\n\n    # Write out cache data\n    for id, module in modules.items():\n        st = result.graph[id]\n\n        meta_path, _, _ = get_cache_names(id, st.xpath, result.manager.options)\n        # If the metadata isn't there, skip writing the cache.\n        try:\n            meta_data = result.manager.metastore.read(meta_path)\n        except OSError:\n            continue\n\n        newpath = get_state_ir_cache_name(st)\n        ir_data = {\n            \"ir\": module.serialize(),\n            \"meta_hash\": hash_digest(meta_data),\n            \"src_hashes\": hashes[group_map[id]],\n        }\n\n        result.manager.metastore.write(newpath, json_dumps(ir_data))\n\n    result.manager.metastore.commit()\n\n\ndef load_scc_from_cache(\n    scc: list[MypyFile], result: BuildResult, mapper: Mapper, ctx: DeserMaps\n) -> ModuleIRs:\n    \"\"\"Load IR for an SCC of modules from the cache.\n\n    Arguments and return are as compile_scc_to_ir.\n    \"\"\"\n    cache_data = {\n        k.fullname: json.loads(\n            result.manager.metastore.read(get_state_ir_cache_name(result.graph[k.fullname]))\n        )[\"ir\"]\n        for k in scc\n    }\n    modules = deserialize_modules(cache_data, ctx)\n    load_type_map(mapper, scc, ctx)\n    return modules\n\n\ndef collect_source_dependencies(modules: dict[str, ModuleIR]) -> set[SourceDep]:\n    \"\"\"Collect all SourceDep dependencies from all modules.\"\"\"\n    source_deps: set[SourceDep] = set()\n    for module in modules.values():\n        for dep in module.dependencies:\n            if isinstance(dep, SourceDep):\n                source_deps.add(dep)\n    return source_deps\n\n\ndef compile_modules_to_c(\n    result: BuildResult, compiler_options: CompilerOptions, errors: Errors, groups: Groups\n) -> tuple[ModuleIRs, list[FileContents], Mapper]:\n    \"\"\"Compile Python module(s) to the source of Python C extension modules.\n\n    This generates the source code for the \"shared library\" module\n    for each group. The shim modules are generated in mypyc.build.\n    Each shared library module provides, for each module in its group,\n    a PyCapsule containing an initialization function.\n    Additionally, it provides a capsule containing an export table of\n    pointers to all the group's functions and static variables.\n\n    Arguments:\n        result: The BuildResult from the mypy front-end\n        compiler_options: The compilation options\n        errors: Where to report any errors encountered\n        groups: The groups that we are compiling. See documentation of Groups type above.\n\n    Returns the IR of the modules and a list containing the generated files for each group.\n    \"\"\"\n    # Construct a map from modules to what group they belong to\n    group_map = {source.module: lib_name for group, lib_name in groups for source in group}\n    mapper = Mapper(group_map)\n\n    # Sometimes when we call back into mypy, there might be errors.\n    # We don't want to crash when that happens.\n    result.manager.errors.set_file(\n        \"<mypyc>\", module=None, scope=None, options=result.manager.options\n    )\n\n    modules = compile_modules_to_ir(result, mapper, compiler_options, errors)\n    if errors.num_errors > 0:\n        return {}, [], Mapper({})\n\n    ctext = compile_ir_to_c(groups, modules, result, mapper, compiler_options)\n    write_cache(modules, result, group_map, ctext)\n\n    return modules, [ctext[name] for _, name in groups], mapper\n\n\ndef generate_function_declaration(fn: FuncIR, emitter: Emitter) -> None:\n    emitter.context.declarations[emitter.native_function_name(fn.decl)] = HeaderDeclaration(\n        f\"{native_function_header(fn.decl, emitter)};\", needs_export=True\n    )\n    if fn.name != TOP_LEVEL_NAME and not fn.internal:\n        if is_fastcall_supported(fn, emitter.capi_version):\n            emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration(\n                f\"{wrapper_function_header(fn, emitter.names)};\"\n            )\n        else:\n            emitter.context.declarations[PREFIX + fn.cname(emitter.names)] = HeaderDeclaration(\n                f\"{legacy_wrapper_function_header(fn, emitter.names)};\"\n            )\n\n\ndef pointerize(decl: str, name: str) -> str:\n    \"\"\"Given a C decl and its name, modify it to be a declaration to a pointer.\"\"\"\n    # This doesn't work in general but does work for all our types...\n    if \"(\" in decl:\n        # Function pointer. Stick an * in front of the name and wrap it in parens.\n        return decl.replace(name, f\"(*{name})\")\n    else:\n        # Non-function pointer. Just stick an * in front of the name.\n        return decl.replace(name, f\"*{name}\")\n\n\ndef group_dir(group_name: str) -> str:\n    \"\"\"Given a group name, return the relative directory path for it.\"\"\"\n    return os.sep.join(group_name.split(\".\")[:-1])\n\n\nclass GroupGenerator:\n    def __init__(\n        self,\n        modules: dict[str, ModuleIR],\n        source_paths: dict[str, str],\n        group_name: str | None,\n        group_map: dict[str, str | None],\n        names: NameGenerator,\n        compiler_options: CompilerOptions,\n    ) -> None:\n        \"\"\"Generator for C source for a compilation group.\n\n        The code for a compilation group contains an internal and an\n        external .h file, and then one .c if not in multi_file mode or\n        one .c file per module if in multi_file mode.\n\n        Arguments:\n            modules: (name, ir) pairs for each module in the group\n            source_paths: Map from module names to source file paths\n            group_name: The name of the group (or None if this is single-module compilation)\n            group_map: A map of modules to their group names\n            names: The name generator for the compilation\n            compiler_options: Mypyc specific options, including multi_file mode\n        \"\"\"\n        self.modules = modules\n        self.source_paths = source_paths\n        self.context = EmitterContext(\n            names, compiler_options.strict_traceback_checks, group_name, group_map\n        )\n        self.names = names\n        # Initializations of globals to simple values that we can't\n        # do statically because the windows loader is bad.\n        self.simple_inits: list[tuple[str, str]] = []\n        self.group_name = group_name\n        self.use_shared_lib = group_name is not None\n        self.compiler_options = compiler_options\n        self.multi_file = compiler_options.multi_file\n        # Multi-phase init is needed to enable free-threading. In the future we'll\n        # probably want to enable it always, but we'll wait until it's stable.\n        self.multi_phase_init = IS_FREE_THREADED\n\n    @property\n    def group_suffix(self) -> str:\n        return \"_\" + exported_name(self.group_name) if self.group_name else \"\"\n\n    @property\n    def short_group_suffix(self) -> str:\n        return \"_\" + exported_name(self.group_name.split(\".\")[-1]) if self.group_name else \"\"\n\n    def generate_c_for_modules(self) -> list[tuple[str, str]]:\n        file_contents = []\n        multi_file = self.use_shared_lib and self.multi_file\n\n        # Collect all literal refs in IR.\n        for module in self.modules.values():\n            for fn in module.functions:\n                collect_literals(fn, self.context.literals)\n\n        base_emitter = Emitter(self.context)\n        # Optionally just include the runtime library c files to\n        # reduce the number of compiler invocations needed\n        if self.compiler_options.include_runtime_files:\n            for name in RUNTIME_C_FILES:\n                base_emitter.emit_line(f'#include \"{name}\"')\n            # Include conditional source files\n            source_deps = collect_source_dependencies(self.modules)\n            for source_dep in sorted(source_deps, key=lambda d: d.path):\n                base_emitter.emit_line(f'#include \"{source_dep.path}\"')\n        base_emitter.emit_line(f'#include \"__native{self.short_group_suffix}.h\"')\n        base_emitter.emit_line(f'#include \"__native_internal{self.short_group_suffix}.h\"')\n        emitter = base_emitter\n\n        self.generate_literal_tables()\n\n        for module_name, module in self.modules.items():\n            if multi_file:\n                emitter = Emitter(self.context, filepath=self.source_paths[module_name])\n                emitter.emit_line(f'#include \"__native{self.short_group_suffix}.h\"')\n                emitter.emit_line(f'#include \"__native_internal{self.short_group_suffix}.h\"')\n\n            self.declare_module(module_name, emitter)\n            self.declare_internal_globals(module_name, emitter)\n            self.declare_imports(module.imports, emitter)\n\n            for cl in module.classes:\n                if cl.is_ext_class:\n                    generate_class(cl, module_name, emitter)\n\n            # Generate Python extension module definitions and module initialization functions.\n            self.generate_module_def(emitter, module_name, module)\n\n            for fn in module.functions:\n                emitter.emit_line()\n                generate_native_function(fn, emitter, self.source_paths[module_name], module_name)\n                if fn.name != TOP_LEVEL_NAME and not fn.internal:\n                    emitter.emit_line()\n                    if is_fastcall_supported(fn, emitter.capi_version):\n                        generate_wrapper_function(\n                            fn, emitter, self.source_paths[module_name], module_name\n                        )\n                    else:\n                        generate_legacy_wrapper_function(\n                            fn, emitter, self.source_paths[module_name], module_name\n                        )\n            if multi_file:\n                name = f\"__native_{exported_name(module_name)}.c\"\n                file_contents.append((name, \"\".join(emitter.fragments)))\n\n        # The external header file contains type declarations while\n        # the internal contains declarations of functions and objects\n        # (which are shared between shared libraries via dynamic\n        # exports tables and not accessed directly.)\n        ext_declarations = Emitter(self.context)\n        ext_declarations.emit_line(f\"#ifndef MYPYC_NATIVE{self.group_suffix}_H\")\n        ext_declarations.emit_line(f\"#define MYPYC_NATIVE{self.group_suffix}_H\")\n        ext_declarations.emit_line(\"#include <Python.h>\")\n        ext_declarations.emit_line(\"#include <CPy.h>\")\n        if self.compiler_options.depends_on_librt_internal:\n            ext_declarations.emit_line(\"#include <internal/librt_internal.h>\")\n        if any(LIBRT_BASE64 in mod.dependencies for mod in self.modules.values()):\n            ext_declarations.emit_line(\"#include <base64/librt_base64.h>\")\n        if any(LIBRT_STRINGS in mod.dependencies for mod in self.modules.values()):\n            ext_declarations.emit_line(\"#include <strings/librt_strings.h>\")\n        if any(LIBRT_TIME in mod.dependencies for mod in self.modules.values()):\n            ext_declarations.emit_line(\"#include <time/librt_time.h>\")\n        if any(LIBRT_VECS in mod.dependencies for mod in self.modules.values()):\n            ext_declarations.emit_line(\"#include <vecs/librt_vecs.h>\")\n        # Include headers for conditional source files\n        source_deps = collect_source_dependencies(self.modules)\n        for source_dep in sorted(source_deps, key=lambda d: d.path):\n            ext_declarations.emit_line(f'#include \"{source_dep.get_header()}\"')\n\n        declarations = Emitter(self.context)\n        declarations.emit_line(f\"#ifndef MYPYC_LIBRT_INTERNAL{self.group_suffix}_H\")\n        declarations.emit_line(f\"#define MYPYC_LIBRT_INTERNAL{self.group_suffix}_H\")\n        declarations.emit_line(\"#include <Python.h>\")\n        declarations.emit_line(\"#include <CPy.h>\")\n        declarations.emit_line(f'#include \"__native{self.short_group_suffix}.h\"')\n        declarations.emit_line()\n        declarations.emit_line(\"int CPyGlobalsInit(void);\")\n        declarations.emit_line()\n\n        for module_name, module in self.modules.items():\n            self.declare_finals(module_name, module.final_names, declarations)\n            for cl in module.classes:\n                generate_class_type_decl(cl, emitter, ext_declarations, declarations)\n                if cl.reuse_freed_instance:\n                    generate_class_reuse(cl, emitter, ext_declarations, declarations)\n            self.declare_type_vars(module_name, module.type_var_names, declarations)\n            for fn in module.functions:\n                generate_function_declaration(fn, declarations)\n\n        for lib in sorted(self.context.group_deps):\n            elib = exported_name(lib)\n            short_lib = exported_name(lib.split(\".\")[-1])\n            declarations.emit_lines(\n                \"#include <{}>\".format(os.path.join(group_dir(lib), f\"__native_{short_lib}.h\")),\n                f\"struct export_table_{elib} exports_{elib};\",\n            )\n\n        sorted_decls = self.toposort_declarations()\n\n        emitter = base_emitter\n        self.generate_globals_init(emitter)\n\n        emitter.emit_line()\n\n        for declaration in sorted_decls:\n            decls = ext_declarations if declaration.is_type else declarations\n            if not declaration.is_type:\n                decls.emit_lines(f\"extern {declaration.decl[0]}\", *declaration.decl[1:])\n                # If there is a definition, emit it. Otherwise, repeat the declaration\n                # (without an extern).\n                if declaration.defn:\n                    emitter.emit_lines(*declaration.defn)\n                else:\n                    emitter.emit_lines(*declaration.decl)\n            else:\n                decls.emit_lines(*declaration.decl)\n\n        if self.group_name:\n            if self.compiler_options.separate:\n                self.generate_export_table(ext_declarations, emitter)\n\n            self.generate_shared_lib_init(emitter)\n\n        ext_declarations.emit_line(\"#endif\")\n        declarations.emit_line(\"#endif\")\n\n        output_dir = group_dir(self.group_name) if self.group_name else \"\"\n        return file_contents + [\n            (\n                os.path.join(output_dir, f\"__native{self.short_group_suffix}.c\"),\n                \"\".join(emitter.fragments),\n            ),\n            (\n                os.path.join(output_dir, f\"__native_internal{self.short_group_suffix}.h\"),\n                \"\".join(declarations.fragments),\n            ),\n            (\n                os.path.join(output_dir, f\"__native{self.short_group_suffix}.h\"),\n                \"\".join(ext_declarations.fragments),\n            ),\n        ]\n\n    def generate_literal_tables(self) -> None:\n        \"\"\"Generate tables containing descriptions of Python literals to construct.\n\n        We will store the constructed literals in a single array that contains\n        literals of all types. This way we can refer to an arbitrary literal by\n        its index.\n        \"\"\"\n        literals = self.context.literals\n        # During module initialization we store all the constructed objects here\n        self.declare_global(\"PyObject *[%d]\" % literals.num_literals(), \"CPyStatics\")\n        # Descriptions of str literals\n        init_str = c_string_array_initializer(literals.encoded_str_values())\n        self.declare_global(\"const char * const []\", \"CPyLit_Str\", initializer=init_str)\n        # Descriptions of bytes literals\n        init_bytes = c_string_array_initializer(literals.encoded_bytes_values())\n        self.declare_global(\"const char * const []\", \"CPyLit_Bytes\", initializer=init_bytes)\n        # Descriptions of int literals\n        init_int = c_string_array_initializer(literals.encoded_int_values())\n        self.declare_global(\"const char * const []\", \"CPyLit_Int\", initializer=init_int)\n        # Descriptions of float literals\n        init_floats = c_array_initializer(literals.encoded_float_values())\n        self.declare_global(\"const double []\", \"CPyLit_Float\", initializer=init_floats)\n        # Descriptions of complex literals\n        init_complex = c_array_initializer(literals.encoded_complex_values())\n        self.declare_global(\"const double []\", \"CPyLit_Complex\", initializer=init_complex)\n        # Descriptions of tuple literals\n        init_tuple = c_array_initializer(literals.encoded_tuple_values())\n        self.declare_global(\"const int []\", \"CPyLit_Tuple\", initializer=init_tuple)\n        # Descriptions of frozenset literals\n        init_frozenset = c_array_initializer(literals.encoded_frozenset_values())\n        self.declare_global(\"const int []\", \"CPyLit_FrozenSet\", initializer=init_frozenset)\n\n    def generate_export_table(self, decl_emitter: Emitter, code_emitter: Emitter) -> None:\n        \"\"\"Generate the declaration and definition of the group's export struct.\n\n        To avoid needing to deal with deeply platform specific issues\n        involving dynamic library linking (and some possibly\n        insurmountable issues involving cyclic dependencies), compiled\n        code accesses functions and data in other compilation groups\n        via an explicit \"export struct\".\n\n        Each group declares a struct type that contains a pointer to\n        every function and static variable it exports. It then\n        populates this struct and stores a pointer to it in a capsule\n        stored as an attribute named 'exports' on the group's shared\n        library's python module.\n\n        On load, a group's init function will import all of its\n        dependencies' exports tables using the capsule mechanism and\n        copy the contents into a local copy of the table (to eliminate\n        the need for a pointer indirection when accessing it).\n\n        Then, all calls to functions in another group and accesses to statics\n        from another group are done indirectly via the export table.\n\n        For example, a group containing a module b, where b contains a class B\n        and a function bar, would declare an export table like:\n            struct export_table_b {\n                PyTypeObject **CPyType_B;\n                PyObject *(*CPyDef_B)(CPyTagged cpy_r_x);\n                CPyTagged (*CPyDef_B___foo)(PyObject *cpy_r_self, CPyTagged cpy_r_y);\n                tuple_T2OI (*CPyDef_bar)(PyObject *cpy_r_x);\n                char (*CPyDef___top_level__)(void);\n            };\n        that would be initialized with:\n            static struct export_table_b exports = {\n                &CPyType_B,\n                &CPyDef_B,\n                &CPyDef_B___foo,\n                &CPyDef_bar,\n                &CPyDef___top_level__,\n            };\n        To call `b.foo`, then, a function in another group would do\n        `exports_b.CPyDef_bar(...)`.\n        \"\"\"\n\n        decls = decl_emitter.context.declarations\n\n        decl_emitter.emit_lines(\"\", f\"struct export_table{self.group_suffix} {{\")\n        for name, decl in decls.items():\n            if decl.needs_export:\n                decl_emitter.emit_line(pointerize(\"\\n\".join(decl.decl), name))\n\n        decl_emitter.emit_line(\"};\")\n\n        code_emitter.emit_lines(\"\", f\"static struct export_table{self.group_suffix} exports = {{\")\n        for name, decl in decls.items():\n            if decl.needs_export:\n                code_emitter.emit_line(f\"&{name},\")\n\n        code_emitter.emit_line(\"};\")\n\n    def generate_shared_lib_init(self, emitter: Emitter) -> None:\n        \"\"\"Generate the init function for a shared library.\n\n        A shared library contains all the actual code for a\n        compilation group.\n\n        The init function is responsible for creating Capsules that\n        wrap pointers to the initialization function of all the real\n        init functions for modules in this shared library as well as\n        the export table containing all the exported functions and\n        values from all the modules.\n\n        These capsules are stored in attributes of the shared library.\n        \"\"\"\n        assert self.group_name is not None\n\n        emitter.emit_line()\n\n        short_name = shared_lib_name(self.group_name).split(\".\")[-1]\n\n        emitter.emit_lines(\n            f\"static int exec_{short_name}(PyObject *module)\",\n            \"{\",\n            \"int res;\",\n            \"PyObject *capsule;\",\n            \"PyObject *tmp;\",\n            \"\",\n        )\n\n        if self.compiler_options.separate:\n            emitter.emit_lines(\n                'capsule = PyCapsule_New(&exports, \"{}.exports\", NULL);'.format(\n                    shared_lib_name(self.group_name)\n                ),\n                \"if (!capsule) {\",\n                \"goto fail;\",\n                \"}\",\n                'res = PyObject_SetAttrString(module, \"exports\", capsule);',\n                \"Py_DECREF(capsule);\",\n                \"if (res < 0) {\",\n                \"goto fail;\",\n                \"}\",\n                \"\",\n            )\n\n        for mod in self.modules:\n            name = exported_name(mod)\n            if self.multi_phase_init:\n                capsule_func_prefix = \"CPyExec_\"\n                capsule_name_prefix = \"exec_\"\n                emitter.emit_line(f\"extern int CPyExec_{name}(PyObject *);\")\n            else:\n                capsule_func_prefix = \"CPyInit_\"\n                capsule_name_prefix = \"init_\"\n                emitter.emit_line(f\"extern PyObject *CPyInit_{name}(void);\")\n            emitter.emit_lines(\n                'capsule = PyCapsule_New((void *){}{}, \"{}.{}{}\", NULL);'.format(\n                    capsule_func_prefix,\n                    name,\n                    shared_lib_name(self.group_name),\n                    capsule_name_prefix,\n                    name,\n                ),\n                \"if (!capsule) {\",\n                \"goto fail;\",\n                \"}\",\n                f'res = PyObject_SetAttrString(module, \"{capsule_name_prefix}{name}\", capsule);',\n                \"Py_DECREF(capsule);\",\n                \"if (res < 0) {\",\n                \"goto fail;\",\n                \"}\",\n                \"\",\n            )\n\n        for group in sorted(self.context.group_deps):\n            egroup = exported_name(group)\n            emitter.emit_lines(\n                'tmp = PyImport_ImportModule(\"{}\"); if (!tmp) goto fail; Py_DECREF(tmp);'.format(\n                    shared_lib_name(group)\n                ),\n                'struct export_table_{} *pexports_{} = PyCapsule_Import(\"{}.exports\", 0);'.format(\n                    egroup, egroup, shared_lib_name(group)\n                ),\n                f\"if (!pexports_{egroup}) {{\",\n                \"goto fail;\",\n                \"}\",\n                \"memcpy(&exports_{group}, pexports_{group}, sizeof(exports_{group}));\".format(\n                    group=egroup\n                ),\n                \"\",\n            )\n\n        emitter.emit_lines(\"return 0;\", \"fail:\", \"return -1;\", \"}\")\n\n        if self.multi_phase_init:\n            emitter.emit_lines(\n                f\"static PyModuleDef_Slot slots_{short_name}[] = {{\",\n                f\"{{Py_mod_exec, exec_{short_name}}},\",\n                \"{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},\",\n                \"{Py_mod_gil, Py_MOD_GIL_NOT_USED},\",\n                \"{0, NULL},\",\n                \"};\",\n            )\n\n        size = 0 if self.multi_phase_init else -1\n        emitter.emit_lines(\n            f\"static PyModuleDef module_def_{short_name} = {{\",\n            \"PyModuleDef_HEAD_INIT,\",\n            f'.m_name = \"{shared_lib_name(self.group_name)}\",',\n            \".m_doc = NULL,\",\n            f\".m_size = {size},\",\n            \".m_methods = NULL,\",\n        )\n        if self.multi_phase_init:\n            emitter.emit_line(f\".m_slots = slots_{short_name},\")\n        emitter.emit_line(\"};\")\n\n        if self.multi_phase_init:\n            emitter.emit_lines(\n                f\"PyMODINIT_FUNC PyInit_{short_name}(void) {{\",\n                f\"return PyModuleDef_Init(&module_def_{short_name});\",\n                \"}\",\n            )\n        else:\n            emitter.emit_lines(\n                f\"PyMODINIT_FUNC PyInit_{short_name}(void) {{\",\n                \"static PyObject *module = NULL;\",\n                \"if (module) {\",\n                \"Py_INCREF(module);\",\n                \"return module;\",\n                \"}\",\n                f\"module = PyModule_Create(&module_def_{short_name});\",\n                \"if (!module) {\",\n                \"return NULL;\",\n                \"}\",\n                f\"if (exec_{short_name}(module) < 0) {{\",\n                \"Py_DECREF(module);\",\n                \"return NULL;\",\n                \"}\",\n                \"return module;\",\n                \"}\",\n            )\n\n    def generate_globals_init(self, emitter: Emitter) -> None:\n        emitter.emit_lines(\n            \"\",\n            \"int CPyGlobalsInit(void)\",\n            \"{\",\n            \"static int is_initialized = 0;\",\n            \"if (is_initialized) return 0;\",\n            \"\",\n        )\n\n        emitter.emit_line(\"CPy_Init();\")\n        for symbol, fixup in self.simple_inits:\n            emitter.emit_line(f\"{symbol} = {fixup};\")\n\n        values = \"CPyLit_Str, CPyLit_Bytes, CPyLit_Int, CPyLit_Float, CPyLit_Complex, CPyLit_Tuple, CPyLit_FrozenSet\"\n        emitter.emit_lines(\n            f\"if (CPyStatics_Initialize(CPyStatics, {values}) < 0) {{\", \"return -1;\", \"}\"\n        )\n\n        emitter.emit_lines(\"is_initialized = 1;\", \"return 0;\", \"}\")\n\n    def generate_module_def(self, emitter: Emitter, module_name: str, module: ModuleIR) -> None:\n        \"\"\"Emit the PyModuleDef struct for a module and the module init function.\"\"\"\n        module_prefix = emitter.names.private_name(module_name)\n        self.emit_module_methods(emitter, module_name, module_prefix, module)\n        self.emit_module_exec_func(emitter, module_name, module_prefix, module)\n\n        # If using multi-phase init and a shared lib, parts of module definition\n        # will happen in the shim modules, so we skip some steps here.\n        if not (self.multi_phase_init and self.use_shared_lib):\n            if self.multi_phase_init:\n                self.emit_module_def_slots(emitter, module_prefix, module_name)\n            self.emit_module_def_struct(emitter, module_name, module_prefix)\n            self.emit_module_init_func(emitter, module_name, module_prefix)\n\n    def emit_module_def_slots(\n        self, emitter: Emitter, module_prefix: str, module_name: str\n    ) -> None:\n        name = f\"{module_prefix}_slots\"\n        exec_name = f\"CPyExec_{exported_name(module_name)}\"\n\n        emitter.emit_line(f\"static PyModuleDef_Slot {name}[] = {{\")\n        emitter.emit_line(f\"{{Py_mod_exec, {exec_name}}},\")\n        if sys.version_info >= (3, 12):\n            # Multiple interpreter support requires not using any C global state,\n            # which we don't support yet.\n            emitter.emit_line(\n                \"{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED},\"\n            )\n        if sys.version_info >= (3, 13):\n            # Declare support for free-threading to enable experimentation,\n            # even if we don't properly support it.\n            emitter.emit_line(\"{Py_mod_gil, Py_MOD_GIL_NOT_USED},\")\n        emitter.emit_line(\"{0, NULL},\")\n        emitter.emit_line(\"};\")\n\n    def emit_module_methods(\n        self, emitter: Emitter, module_name: str, module_prefix: str, module: ModuleIR\n    ) -> None:\n        \"\"\"Emit module methods (the static PyMethodDef table).\"\"\"\n        emitter.emit_line(f\"static PyMethodDef {module_prefix}module_methods[] = {{\")\n        for fn in module.functions:\n            if fn.class_name is not None or fn.name == TOP_LEVEL_NAME:\n                continue\n            # Coroutines are added to the module dict when the module is initialized.\n            if fn.decl.is_coroutine:\n                continue\n            name = short_id_from_name(fn.name, fn.decl.shortname, fn.line)\n            if is_fastcall_supported(fn, emitter.capi_version):\n                flag = \"METH_FASTCALL\"\n            else:\n                flag = \"METH_VARARGS\"\n            doc = native_function_doc_initializer(fn)\n            emitter.emit_line(\n                (\n                    '{{\"{name}\", (PyCFunction){prefix}{cname}, {flag} | METH_KEYWORDS, '\n                    \"PyDoc_STR({doc}) /* docstring */}},\"\n                ).format(\n                    name=name, cname=fn.cname(emitter.names), prefix=PREFIX, flag=flag, doc=doc\n                )\n            )\n        emitter.emit_line(\"{NULL, NULL, 0, NULL}\")\n        emitter.emit_line(\"};\")\n        emitter.emit_line()\n\n    def emit_module_def_struct(\n        self, emitter: Emitter, module_name: str, module_prefix: str\n    ) -> None:\n        \"\"\"Emit the static module definition struct (PyModuleDef).\"\"\"\n        emitter.emit_lines(\n            f\"static struct PyModuleDef {module_prefix}module = {{\",\n            \"PyModuleDef_HEAD_INIT,\",\n            f'\"{module_name}\",',\n            \"NULL, /* docstring */\",\n            \"0,       /* size of per-interpreter state of the module */\",\n            f\"{module_prefix}module_methods,\",\n        )\n        if self.multi_phase_init and not self.use_shared_lib:\n            slots_name = f\"{module_prefix}_slots\"\n            emitter.emit_line(f\"{slots_name}, /* m_slots */\")\n        else:\n            emitter.emit_line(\"NULL,\")\n        emitter.emit_line(\"};\")\n        emitter.emit_line()\n\n    def emit_coroutine_wrappers(self, emitter: Emitter, module: ModuleIR, globals: str) -> None:\n        \"\"\"Emit insertion of coroutines into the module dict when the module is initialized.\n        Coroutines are wrapped in CPyFunction objects to enable introspection by functions like\n        inspect.iscoroutinefunction(fn).\n        \"\"\"\n        for fn in module.functions:\n            if fn.class_name is not None or fn.name == TOP_LEVEL_NAME:\n                continue\n            if not fn.decl.is_coroutine:\n                continue\n\n            filepath = self.source_paths[module.fullname]\n            error_stmt = \"    goto fail;\"\n            name = short_id_from_name(fn.name, fn.decl.shortname, fn.line)\n            wrapper_name = emitter.emit_cpyfunction_instance(fn, name, filepath, error_stmt)\n            name_obj = f\"{wrapper_name}_name\"\n            emitter.emit_line(f'PyObject *{name_obj} = PyUnicode_FromString(\"{fn.name}\");')\n            emitter.emit_line(f\"if (unlikely(!{name_obj}))\")\n            emitter.emit_line(error_stmt)\n            emitter.emit_line(\n                f\"if (PyDict_SetItem({globals}, {name_obj}, (PyObject *){wrapper_name}) < 0)\"\n            )\n            emitter.emit_line(error_stmt)\n\n    def emit_module_exec_func(\n        self, emitter: Emitter, module_name: str, module_prefix: str, module: ModuleIR\n    ) -> None:\n        \"\"\"Emit the module exec function.\n\n        If we are compiling just one module, this will be the normal C API\n        exec function. If we are compiling 2+ modules, we generate a shared\n        library for the modules and shims that call into the shared\n        library, and in this case the shared module defines an internal\n        exec function for each module and these will be called by the shims\n        via Capsules.\n        \"\"\"\n        declaration = f\"int CPyExec_{exported_name(module_name)}(PyObject *module)\"\n        module_static = self.module_internal_static_name(module_name, emitter)\n        emitter.emit_lines(declaration, \"{\")\n        emitter.emit_line(\"intern_strings();\")\n        if self.compiler_options.depends_on_librt_internal:\n            emitter.emit_line(\"if (import_librt_internal() < 0) {\")\n            emitter.emit_line(\"return -1;\")\n            emitter.emit_line(\"}\")\n        if LIBRT_BASE64 in module.dependencies:\n            emitter.emit_line(\"if (import_librt_base64() < 0) {\")\n            emitter.emit_line(\"return -1;\")\n            emitter.emit_line(\"}\")\n        if LIBRT_STRINGS in module.dependencies:\n            emitter.emit_line(\"if (import_librt_strings() < 0) {\")\n            emitter.emit_line(\"return -1;\")\n            emitter.emit_line(\"}\")\n        if LIBRT_TIME in module.dependencies:\n            emitter.emit_line(\"if (import_librt_time() < 0) {\")\n            emitter.emit_line(\"return -1;\")\n            emitter.emit_line(\"}\")\n        if LIBRT_VECS in module.dependencies:\n            emitter.emit_line(\"if (import_librt_vecs() < 0) {\")\n            emitter.emit_line(\"return -1;\")\n            emitter.emit_line(\"}\")\n        emitter.emit_line(\"PyObject* modname = NULL;\")\n        if self.multi_phase_init:\n            emitter.emit_line(f\"{module_static} = module;\")\n        emitter.emit_line(\n            f'modname = PyObject_GetAttrString((PyObject *){module_static}, \"__name__\");'\n        )\n\n        module_globals = emitter.static_name(\"globals\", module_name)\n        emitter.emit_lines(\n            f\"{module_globals} = PyModule_GetDict({module_static});\",\n            f\"if (unlikely({module_globals} == NULL))\",\n            \"    goto fail;\",\n        )\n\n        if self.multi_phase_init:\n            emitter.emit_lines(\n                f\"if (PyModule_AddFunctions(module, {module_prefix}module_methods) < 0)\",\n                \"    goto fail;\",\n            )\n\n        self.emit_coroutine_wrappers(emitter, module, module_globals)\n\n        # HACK: Manually instantiate generated classes here\n        type_structs: list[str] = []\n        for cl in module.classes:\n            type_struct = emitter.type_struct_name(cl)\n            type_structs.append(type_struct)\n            if cl.is_generated:\n                error_stmt = \"    goto fail;\"\n                emitter.emit_lines(\n                    \"{t} = (PyTypeObject *)CPyType_FromTemplate(\"\n                    \"(PyObject *){t}_template, NULL, modname);\".format(t=type_struct)\n                )\n                emitter.emit_lines(f\"if (unlikely(!{type_struct}))\", error_stmt)\n                name_prefix = cl.name_prefix(emitter.names)\n                emitter.emit_line(f\"CPyDef_{name_prefix}_trait_vtable_setup();\")\n\n        emitter.emit_lines(\"if (CPyGlobalsInit() < 0)\", \"    goto fail;\")\n\n        self.generate_top_level_call(module, emitter)\n\n        emitter.emit_lines(\"Py_DECREF(modname);\")\n\n        emitter.emit_line(\"return 0;\")\n        emitter.emit_lines(\"fail:\")\n        if self.multi_phase_init:\n            emitter.emit_lines(f\"{module_static} = NULL;\", \"Py_CLEAR(modname);\")\n        else:\n            emitter.emit_lines(f\"Py_CLEAR({module_static});\", \"Py_CLEAR(modname);\")\n        for name, typ in module.final_names:\n            static_name = emitter.static_name(name, module_name)\n            emitter.emit_dec_ref(static_name, typ, is_xdec=True)\n            undef = emitter.c_undefined_value(typ)\n            emitter.emit_line(f\"{static_name} = {undef};\")\n        # the type objects returned from CPyType_FromTemplate are all new references\n        # so we have to decref them\n        for t in type_structs:\n            emitter.emit_line(f\"Py_CLEAR({t});\")\n        emitter.emit_line(\"return -1;\")\n        emitter.emit_line(\"}\")\n\n    def emit_module_init_func(\n        self, emitter: Emitter, module_name: str, module_prefix: str\n    ) -> None:\n        if not self.use_shared_lib:\n            declaration = f\"PyMODINIT_FUNC PyInit_{module_name}(void)\"\n        else:\n            declaration = f\"PyObject *CPyInit_{exported_name(module_name)}(void)\"\n        emitter.emit_lines(declaration, \"{\")\n\n        if self.multi_phase_init:\n            def_name = f\"{module_prefix}module\"\n            emitter.emit_line(f\"return PyModuleDef_Init(&{def_name});\")\n            emitter.emit_line(\"}\")\n            return\n\n        exec_func = f\"CPyExec_{exported_name(module_name)}\"\n\n        # Store the module reference in a static and return it when necessary.\n        # This is separate from the *global* reference to the module that will\n        # be populated when it is imported by a compiled module. We want that\n        # reference to only be populated when the module has been successfully\n        # imported, whereas this we want to have to stop a circular import.\n        module_static = self.module_internal_static_name(module_name, emitter)\n\n        emitter.emit_lines(\n            f\"if ({module_static}) {{\",\n            f\"Py_INCREF({module_static});\",\n            f\"return {module_static};\",\n            \"}\",\n        )\n\n        emitter.emit_lines(\n            f\"{module_static} = PyModule_Create(&{module_prefix}module);\",\n            f\"if (unlikely({module_static} == NULL))\",\n            \"    goto fail;\",\n        )\n        emitter.emit_lines(f\"if ({exec_func}({module_static}) != 0)\", \"    goto fail;\")\n        emitter.emit_line(f\"return {module_static};\")\n        emitter.emit_lines(\"fail:\", \"return NULL;\")\n        emitter.emit_lines(\"}\")\n\n    def generate_top_level_call(self, module: ModuleIR, emitter: Emitter) -> None:\n        \"\"\"Generate call to function representing module top level.\"\"\"\n        # Optimization: we tend to put the top level last, so reverse iterate\n        for fn in reversed(module.functions):\n            if fn.name == TOP_LEVEL_NAME:\n                emitter.emit_lines(\n                    f\"char result = {emitter.native_function_name(fn.decl)}();\",\n                    \"if (result == 2)\",\n                    \"    goto fail;\",\n                )\n                break\n\n    def toposort_declarations(self) -> list[HeaderDeclaration]:\n        \"\"\"Topologically sort the declaration dict by dependencies.\n\n        Declarations can require other declarations to come prior in C (such as declaring structs).\n        In order to guarantee that the C output will compile the declarations will thus need to\n        be properly ordered. This simple DFS guarantees that we have a proper ordering.\n\n        This runs in O(V + E).\n        \"\"\"\n        result = []\n        marked_declarations: dict[str, MarkedDeclaration] = {}\n        for k, v in self.context.declarations.items():\n            marked_declarations[k] = MarkedDeclaration(v, False)\n\n        def _toposort_visit(name: str) -> None:\n            decl = marked_declarations[name]\n            if decl.mark:\n                return\n\n            for child in decl.declaration.dependencies:\n                _toposort_visit(child)\n\n            result.append(decl.declaration)\n            decl.mark = True\n\n        for name in marked_declarations:\n            _toposort_visit(name)\n\n        return result\n\n    def declare_global(\n        self, type_spaced: str, name: str, *, initializer: str | None = None\n    ) -> None:\n        if \"[\" not in type_spaced:\n            base = f\"{type_spaced}{name}\"\n        else:\n            a, b = type_spaced.split(\"[\", 1)\n            base = f\"{a}{name}[{b}\"\n\n        if not initializer:\n            defn = None\n        else:\n            defn = [f\"{base} = {initializer};\"]\n        if name not in self.context.declarations:\n            self.context.declarations[name] = HeaderDeclaration(f\"{base};\", defn=defn)\n\n    def declare_internal_globals(self, module_name: str, emitter: Emitter) -> None:\n        static_name = emitter.static_name(\"globals\", module_name)\n        self.declare_global(\"PyObject *\", static_name)\n\n    def module_internal_static_name(self, module_name: str, emitter: Emitter) -> str:\n        return emitter.static_name(module_name + \"__internal\", None, prefix=MODULE_PREFIX)\n\n    def declare_module(self, module_name: str, emitter: Emitter) -> None:\n        # We declare two globals for each compiled module:\n        # one used internally in the implementation of module init to cache results\n        # and prevent infinite recursion in import cycles, and one used\n        # by other modules to refer to it.\n        if module_name in self.modules:\n            internal_static_name = self.module_internal_static_name(module_name, emitter)\n            self.declare_global(\"CPyModule *\", internal_static_name, initializer=\"NULL\")\n        static_name = emitter.static_name(module_name, None, prefix=MODULE_PREFIX)\n        self.declare_global(\"CPyModule *\", static_name)\n        self.simple_inits.append((static_name, \"Py_None\"))\n\n    def declare_imports(self, imps: Iterable[str], emitter: Emitter) -> None:\n        for imp in imps:\n            self.declare_module(imp, emitter)\n\n    def declare_finals(\n        self, module: str, final_names: Iterable[tuple[str, RType]], emitter: Emitter\n    ) -> None:\n        for name, typ in final_names:\n            static_name = emitter.static_name(name, module)\n            emitter.context.declarations[static_name] = HeaderDeclaration(\n                f\"{emitter.ctype_spaced(typ)}{static_name};\",\n                [self.final_definition(module, name, typ, emitter)],\n                needs_export=True,\n            )\n\n    def final_definition(self, module: str, name: str, typ: RType, emitter: Emitter) -> str:\n        static_name = emitter.static_name(name, module)\n        # Here we rely on the fact that undefined value and error value are always the same\n        undefined = emitter.c_initializer_undefined_value(typ)\n        return f\"{emitter.ctype_spaced(typ)}{static_name} = {undefined};\"\n\n    def declare_static_pyobject(self, identifier: str, emitter: Emitter) -> None:\n        symbol = emitter.static_name(identifier, None)\n        self.declare_global(\"PyObject *\", symbol)\n\n    def declare_type_vars(self, module: str, type_var_names: list[str], emitter: Emitter) -> None:\n        for name in type_var_names:\n            static_name = emitter.static_name(name, module, prefix=TYPE_VAR_PREFIX)\n            emitter.context.declarations[static_name] = HeaderDeclaration(\n                f\"PyObject *{static_name};\",\n                [f\"PyObject *{static_name} = NULL;\"],\n                needs_export=False,\n            )\n\n\nT = TypeVar(\"T\")\n\n\ndef toposort(deps: dict[T, set[T]]) -> list[T]:\n    \"\"\"Topologically sort a dict from item to dependencies.\n\n    This runs in O(V + E).\n    \"\"\"\n    result = []\n    visited: set[T] = set()\n\n    def visit(item: T) -> None:\n        if item in visited:\n            return\n\n        for child in deps[item]:\n            visit(child)\n\n        result.append(item)\n        visited.add(item)\n\n    for item in deps:\n        visit(item)\n\n    return result\n\n\ndef is_fastcall_supported(fn: FuncIR, capi_version: tuple[int, int]) -> bool:\n    if fn.class_name is not None:\n        if fn.name == \"__call__\":\n            # We can use vectorcalls (PEP 590) when supported\n            return True\n        # TODO: Support fastcall for __init__ and __new__.\n        return fn.name != \"__init__\" and fn.name != \"__new__\"\n    return True\n\n\ndef collect_literals(fn: FuncIR, literals: Literals) -> None:\n    \"\"\"Store all Python literal object refs in fn.\n\n    Collecting literals must happen only after we have the final IR.\n    This way we won't include literals that have been optimized away.\n    \"\"\"\n    for block in fn.blocks:\n        for op in block.ops:\n            if isinstance(op, LoadLiteral):\n                literals.record_literal(op.value)\n\n\ndef c_string_array_initializer(components: list[bytes]) -> str:\n    result = []\n    result.append(\"{\\n\")\n    for s in components:\n        result.append(\"    \" + c_string_initializer(s) + \",\\n\")\n    result.append(\"}\")\n    return \"\".join(result)\n"
  },
  {
    "path": "mypyc/codegen/emitwrapper.py",
    "content": "\"\"\"Generate CPython API wrapper functions for native functions.\n\nThe wrapper functions are used by the CPython runtime when calling\nnative functions from interpreted code, and when the called function\ncan't be determined statically in compiled code. They validate, match,\nunbox and type check function arguments, and box return values as\nneeded. All wrappers accept and return 'PyObject *' (boxed) values.\n\nThe wrappers aren't used for most calls between two native functions\nor methods in a single compilation unit.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\n\nfrom mypy.nodes import ARG_NAMED, ARG_NAMED_OPT, ARG_OPT, ARG_POS, ARG_STAR, ARG_STAR2, ArgKind\nfrom mypy.operators import op_methods_to_symbols, reverse_op_method_names, reverse_op_methods\nfrom mypyc.codegen.emit import AssignHandler, Emitter, ErrorHandler, GotoHandler, ReturnHandler\nfrom mypyc.common import (\n    BITMAP_BITS,\n    BITMAP_TYPE,\n    DUNDER_PREFIX,\n    NATIVE_PREFIX,\n    PREFIX,\n    bitmap_name,\n)\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FUNC_STATICMETHOD, FuncIR, RuntimeArg\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RType,\n    is_bool_rprimitive,\n    is_int_rprimitive,\n    is_object_rprimitive,\n    object_rprimitive,\n)\nfrom mypyc.namegen import NameGenerator\n\n# Generic vectorcall wrapper functions (Python 3.7+)\n#\n# A wrapper function has a signature like this:\n#\n# PyObject *fn(PyObject *self, PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames)\n#\n# The function takes a self object, pointer to an array of arguments,\n# the number of positional arguments, and a tuple of keyword argument\n# names (that are stored starting in args[nargs]).\n#\n# It returns the returned object, or NULL on an exception.\n#\n# These are more efficient than legacy wrapper functions, since\n# usually no tuple or dict objects need to be created for the\n# arguments. Vectorcalls also use pre-constructed str objects for\n# keyword argument names and other pre-computed information, instead\n# of processing the argument format string on each call.\n\n\ndef wrapper_function_header(fn: FuncIR, names: NameGenerator) -> str:\n    \"\"\"Return header of a vectorcall wrapper function.\n\n    See comment above for a summary of the arguments.\n    \"\"\"\n    assert not fn.internal\n    return (\n        \"PyObject *{prefix}{name}(\"\n        \"PyObject *self, PyObject *const *args, size_t nargs, PyObject *kwnames)\"\n    ).format(prefix=PREFIX, name=fn.cname(names))\n\n\ndef generate_traceback_code(\n    fn: FuncIR, emitter: Emitter, source_path: str, module_name: str\n) -> str:\n    # If we hit an error while processing arguments, then we emit a\n    # traceback frame to make it possible to debug where it happened.\n    # Unlike traceback frames added for exceptions seen in IR, we do this\n    # even if there is no `traceback_name`. This is because the error will\n    # have originated here and so we need it in the traceback.\n    globals_static = emitter.static_name(\"globals\", module_name)\n    traceback_code = 'CPy_AddTraceback(\"%s\", \"%s\", %d, %s);' % (\n        source_path.replace(\"\\\\\", \"\\\\\\\\\"),\n        fn.traceback_name or fn.name,\n        fn.line,\n        globals_static,\n    )\n    return traceback_code\n\n\ndef make_arg_groups(args: list[RuntimeArg]) -> dict[ArgKind, list[RuntimeArg]]:\n    \"\"\"Group arguments by kind.\"\"\"\n    return {k: [arg for arg in args if arg.kind == k] for k in ArgKind}\n\n\ndef reorder_arg_groups(groups: dict[ArgKind, list[RuntimeArg]]) -> list[RuntimeArg]:\n    \"\"\"Reorder argument groups to match their order in a format string.\"\"\"\n    return groups[ARG_POS] + groups[ARG_OPT] + groups[ARG_NAMED_OPT] + groups[ARG_NAMED]\n\n\ndef make_static_kwlist(args: list[RuntimeArg]) -> str:\n    arg_names = \"\".join(f'\"{arg.name}\", ' for arg in args)\n    return f\"static const char * const kwlist[] = {{{arg_names}0}};\"\n\n\ndef make_format_string(func_name: str | None, groups: dict[ArgKind, list[RuntimeArg]]) -> str:\n    \"\"\"Return a format string that specifies the accepted arguments.\n\n    The format string is an extended subset of what is supported by\n    PyArg_ParseTupleAndKeywords(). Only the type 'O' is used, and we\n    also support some extensions:\n\n    - Required keyword-only arguments are introduced after '@'\n    - If the function receives *args or **kwargs, we add a '%' prefix\n\n    Each group requires the previous groups' delimiters to be present\n    first.\n\n    These are used by both vectorcall and legacy wrapper functions.\n    \"\"\"\n    format = \"\"\n    if groups[ARG_STAR] or groups[ARG_STAR2]:\n        format += \"%\"\n    format += \"O\" * len(groups[ARG_POS])\n    if groups[ARG_OPT] or groups[ARG_NAMED_OPT] or groups[ARG_NAMED]:\n        format += \"|\" + \"O\" * len(groups[ARG_OPT])\n    if groups[ARG_NAMED_OPT] or groups[ARG_NAMED]:\n        format += \"$\" + \"O\" * len(groups[ARG_NAMED_OPT])\n    if groups[ARG_NAMED]:\n        format += \"@\" + \"O\" * len(groups[ARG_NAMED])\n    if func_name is not None:\n        format += f\":{func_name}\"\n    return format\n\n\ndef generate_wrapper_function(\n    fn: FuncIR, emitter: Emitter, source_path: str, module_name: str\n) -> None:\n    \"\"\"Generate a CPython-compatible vectorcall wrapper for a native function.\n\n    In particular, this handles unboxing the arguments, calling the native function, and\n    then boxing the return value.\n    \"\"\"\n    emitter.emit_line(f\"{wrapper_function_header(fn, emitter.names)} {{\")\n\n    # If fn is a method, then the first argument is a self param\n    real_args = list(fn.args)\n    if fn.sig.num_bitmap_args:\n        real_args = real_args[: -fn.sig.num_bitmap_args]\n    if fn.class_name and fn.decl.kind != FUNC_STATICMETHOD:\n        arg = real_args.pop(0)\n        emitter.emit_line(f\"PyObject *obj_{arg.name} = self;\")\n\n    # Need to order args as: required, optional, kwonly optional, kwonly required\n    # This is because CPyArg_ParseStackAndKeywords format string requires\n    # them grouped in that way.\n    groups = make_arg_groups(real_args)\n    reordered_args = reorder_arg_groups(groups)\n\n    emitter.emit_line(make_static_kwlist(reordered_args))\n    fmt = make_format_string(fn.name, groups)\n    # Define the arguments the function accepts (but no types yet)\n    emitter.emit_line(f'static CPyArg_Parser parser = {{\"{fmt}\", kwlist, 0}};')\n\n    for arg in real_args:\n        emitter.emit_line(\n            \"PyObject *obj_{}{};\".format(arg.name, \" = NULL\" if arg.optional else \"\")\n        )\n\n    cleanups = [f\"CPy_DECREF(obj_{arg.name});\" for arg in groups[ARG_STAR] + groups[ARG_STAR2]]\n\n    arg_ptrs: list[str] = []\n    if groups[ARG_STAR] or groups[ARG_STAR2]:\n        arg_ptrs += [f\"&obj_{groups[ARG_STAR][0].name}\" if groups[ARG_STAR] else \"NULL\"]\n        arg_ptrs += [f\"&obj_{groups[ARG_STAR2][0].name}\" if groups[ARG_STAR2] else \"NULL\"]\n    arg_ptrs += [f\"&obj_{arg.name}\" for arg in reordered_args]\n\n    if fn.name == \"__call__\":\n        nargs = \"PyVectorcall_NARGS(nargs)\"\n    else:\n        nargs = \"nargs\"\n    parse_fn = \"CPyArg_ParseStackAndKeywords\"\n    # Special case some common signatures\n    if not real_args:\n        # No args\n        parse_fn = \"CPyArg_ParseStackAndKeywordsNoArgs\"\n    elif len(real_args) == 1 and len(groups[ARG_POS]) == 1:\n        # Single positional arg\n        parse_fn = \"CPyArg_ParseStackAndKeywordsOneArg\"\n    elif len(real_args) == len(groups[ARG_POS]) + len(groups[ARG_OPT]):\n        # No keyword-only args, *args or **kwargs\n        parse_fn = \"CPyArg_ParseStackAndKeywordsSimple\"\n    emitter.emit_lines(\n        \"if (!{}(args, {}, kwnames, &parser{})) {{\".format(\n            parse_fn, nargs, \"\".join(\", \" + n for n in arg_ptrs)\n        ),\n        \"return NULL;\",\n        \"}\",\n    )\n    for i in range(fn.sig.num_bitmap_args):\n        name = bitmap_name(i)\n        emitter.emit_line(f\"{BITMAP_TYPE} {name} = 0;\")\n    traceback_code = generate_traceback_code(fn, emitter, source_path, module_name)\n    generate_wrapper_core(\n        fn,\n        emitter,\n        groups[ARG_OPT] + groups[ARG_NAMED_OPT],\n        cleanups=cleanups,\n        traceback_code=traceback_code,\n    )\n\n    emitter.emit_line(\"}\")\n\n\n# Legacy generic wrapper functions\n#\n# These take a self object, a Python tuple of positional arguments,\n# and a dict of keyword arguments. These are a lot slower than\n# vectorcall wrappers, especially in calls involving keyword\n# arguments.\n\n\ndef legacy_wrapper_function_header(fn: FuncIR, names: NameGenerator) -> str:\n    return \"PyObject *{prefix}{name}(PyObject *self, PyObject *args, PyObject *kw)\".format(\n        prefix=PREFIX, name=fn.cname(names)\n    )\n\n\ndef generate_legacy_wrapper_function(\n    fn: FuncIR, emitter: Emitter, source_path: str, module_name: str\n) -> None:\n    \"\"\"Generates a CPython-compatible legacy wrapper for a native function.\n\n    In particular, this handles unboxing the arguments, calling the native function, and\n    then boxing the return value.\n    \"\"\"\n    emitter.emit_line(f\"{legacy_wrapper_function_header(fn, emitter.names)} {{\")\n\n    # If fn is a method, then the first argument is a self param\n    real_args = list(fn.args)\n    if fn.sig.num_bitmap_args:\n        real_args = real_args[: -fn.sig.num_bitmap_args]\n    if fn.class_name and (fn.decl.name == \"__new__\" or fn.decl.kind != FUNC_STATICMETHOD):\n        arg = real_args.pop(0)\n        emitter.emit_line(f\"PyObject *obj_{arg.name} = self;\")\n\n    # Need to order args as: required, optional, kwonly optional, kwonly required\n    # This is because CPyArg_ParseTupleAndKeywords format string requires\n    # them grouped in that way.\n    groups = make_arg_groups(real_args)\n    reordered_args = reorder_arg_groups(groups)\n\n    emitter.emit_line(make_static_kwlist(reordered_args))\n    for arg in real_args:\n        emitter.emit_line(\n            \"PyObject *obj_{}{};\".format(arg.name, \" = NULL\" if arg.optional else \"\")\n        )\n\n    cleanups = [f\"CPy_DECREF(obj_{arg.name});\" for arg in groups[ARG_STAR] + groups[ARG_STAR2]]\n\n    arg_ptrs: list[str] = []\n    if groups[ARG_STAR] or groups[ARG_STAR2]:\n        arg_ptrs += [f\"&obj_{groups[ARG_STAR][0].name}\" if groups[ARG_STAR] else \"NULL\"]\n        arg_ptrs += [f\"&obj_{groups[ARG_STAR2][0].name}\" if groups[ARG_STAR2] else \"NULL\"]\n    arg_ptrs += [f\"&obj_{arg.name}\" for arg in reordered_args]\n\n    emitter.emit_lines(\n        'if (!CPyArg_ParseTupleAndKeywords(args, kw, \"{}\", \"{}\", kwlist{})) {{'.format(\n            make_format_string(None, groups), fn.name, \"\".join(\", \" + n for n in arg_ptrs)\n        ),\n        \"return NULL;\",\n        \"}\",\n    )\n    for i in range(fn.sig.num_bitmap_args):\n        name = bitmap_name(i)\n        emitter.emit_line(f\"{BITMAP_TYPE} {name} = 0;\")\n    traceback_code = generate_traceback_code(fn, emitter, source_path, module_name)\n    generate_wrapper_core(\n        fn,\n        emitter,\n        groups[ARG_OPT] + groups[ARG_NAMED_OPT],\n        cleanups=cleanups,\n        traceback_code=traceback_code,\n    )\n\n    emitter.emit_line(\"}\")\n\n\n# Specialized wrapper functions\n\n\ndef generate_dunder_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generates a wrapper for native __dunder__ methods to be able to fit into the mapping\n    protocol slot. This specifically means that the arguments are taken as *PyObjects and returned\n    as *PyObjects.\n    \"\"\"\n    gen = WrapperGenerator(cl, emitter)\n    gen.set_target(fn)\n    gen.emit_header()\n    gen.emit_arg_processing()\n    gen.emit_call()\n    gen.finish()\n    return gen.wrapper_name()\n\n\ndef generate_ipow_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generate a wrapper for native __ipow__.\n\n    Since __ipow__ fills a ternary slot, but almost no one defines __ipow__ to take three\n    arguments, the wrapper needs to tweaked to force it to accept three arguments.\n    \"\"\"\n    gen = WrapperGenerator(cl, emitter)\n    gen.set_target(fn)\n    assert len(fn.args) in (2, 3), \"__ipow__ should only take 2 or 3 arguments\"\n    gen.arg_names = [\"self\", \"exp\", \"mod\"]\n    gen.emit_header()\n    gen.emit_arg_processing()\n    handle_third_pow_argument(\n        fn,\n        emitter,\n        gen,\n        if_unsupported=[\n            'PyErr_SetString(PyExc_TypeError, \"__ipow__ takes 2 positional arguments but 3 were given\");',\n            \"return NULL;\",\n        ],\n    )\n    gen.emit_call()\n    gen.finish()\n    return gen.wrapper_name()\n\n\ndef generate_bin_op_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generates a wrapper for a native binary dunder method.\n\n    The same wrapper that handles the forward method (e.g. __add__) also handles\n    the corresponding reverse method (e.g. __radd__), if defined.\n\n    Both arguments and the return value are PyObject *.\n    \"\"\"\n    gen = WrapperGenerator(cl, emitter)\n    gen.set_target(fn)\n    if fn.name in (\"__pow__\", \"__rpow__\"):\n        gen.arg_names = [\"left\", \"right\", \"mod\"]\n    else:\n        gen.arg_names = [\"left\", \"right\"]\n    wrapper_name = gen.wrapper_name()\n\n    gen.emit_header()\n    if fn.name not in reverse_op_methods and fn.name in reverse_op_method_names:\n        # There's only a reverse operator method.\n        generate_bin_op_reverse_only_wrapper(fn, emitter, gen)\n    else:\n        rmethod = reverse_op_methods[fn.name]\n        fn_rev = cl.get_method(rmethod)\n        if fn_rev is None:\n            # There's only a forward operator method.\n            generate_bin_op_forward_only_wrapper(fn, emitter, gen)\n        else:\n            # There's both a forward and a reverse operator method.\n            generate_bin_op_both_wrappers(cl, fn, fn_rev, emitter, gen)\n    return wrapper_name\n\n\ndef generate_bin_op_forward_only_wrapper(\n    fn: FuncIR, emitter: Emitter, gen: WrapperGenerator\n) -> None:\n    gen.emit_arg_processing(error=GotoHandler(\"typefail\"), raise_exception=False)\n    handle_third_pow_argument(fn, emitter, gen, if_unsupported=[\"goto typefail;\"])\n    gen.emit_call(not_implemented_handler=\"goto typefail;\")\n    gen.emit_error_handling()\n    emitter.emit_label(\"typefail\")\n    # If some argument has an incompatible type, treat this the same as\n    # returning NotImplemented, and try to call the reverse operator method.\n    #\n    # Note that in normal Python you'd instead of an explicit\n    # return of NotImplemented, but it doesn't generally work here\n    # the body won't be executed at all if there is an argument\n    # type check failure.\n    #\n    # The recommended way is to still use a type check in the\n    # body. This will only be used in interpreted mode:\n    #\n    #    def __add__(self, other: int) -> Foo:\n    #        if not isinstance(other, int):\n    #            return NotImplemented\n    #        ...\n    generate_bin_op_reverse_dunder_call(fn, emitter, reverse_op_methods[fn.name])\n    gen.finish()\n\n\ndef generate_bin_op_reverse_only_wrapper(\n    fn: FuncIR, emitter: Emitter, gen: WrapperGenerator\n) -> None:\n    gen.arg_names = [\"right\", \"left\"]\n    gen.emit_arg_processing(error=GotoHandler(\"typefail\"), raise_exception=False)\n    handle_third_pow_argument(fn, emitter, gen, if_unsupported=[\"goto typefail;\"])\n    gen.emit_call()\n    gen.emit_error_handling()\n    emitter.emit_label(\"typefail\")\n    emitter.emit_line(\"Py_INCREF(Py_NotImplemented);\")\n    emitter.emit_line(\"return Py_NotImplemented;\")\n    gen.finish()\n\n\ndef generate_bin_op_both_wrappers(\n    cl: ClassIR, fn: FuncIR, fn_rev: FuncIR, emitter: Emitter, gen: WrapperGenerator\n) -> None:\n    # There's both a forward and a reverse operator method. First\n    # check if we should try calling the forward one. If the\n    # argument type check fails, fall back to the reverse method.\n    #\n    # Similar to above, we can't perfectly match Python semantics.\n    # In regular Python code you'd return NotImplemented if the\n    # operand has the wrong type, but in compiled code we'll never\n    # get to execute the type check.\n    emitter.emit_line(\n        \"if (PyObject_IsInstance(obj_left, (PyObject *){})) {{\".format(\n            emitter.type_struct_name(cl)\n        )\n    )\n    gen.emit_arg_processing(error=GotoHandler(\"typefail\"), raise_exception=False)\n    handle_third_pow_argument(fn, emitter, gen, if_unsupported=[\"goto typefail2;\"])\n    # Ternary __rpow__ calls aren't a thing so immediately bail\n    # if ternary __pow__ returns NotImplemented.\n    if fn.name == \"__pow__\" and len(fn.args) == 3:\n        fwd_not_implemented_handler = \"goto typefail2;\"\n    else:\n        fwd_not_implemented_handler = \"goto typefail;\"\n    gen.emit_call(not_implemented_handler=fwd_not_implemented_handler)\n    gen.emit_error_handling()\n    emitter.emit_line(\"}\")\n    emitter.emit_label(\"typefail\")\n    emitter.emit_line(\n        \"if (PyObject_IsInstance(obj_right, (PyObject *){})) {{\".format(\n            emitter.type_struct_name(cl)\n        )\n    )\n    gen.set_target(fn_rev)\n    gen.arg_names = [\"right\", \"left\"]\n    gen.emit_arg_processing(error=GotoHandler(\"typefail2\"), raise_exception=False)\n    handle_third_pow_argument(fn_rev, emitter, gen, if_unsupported=[\"goto typefail2;\"])\n    gen.emit_call()\n    gen.emit_error_handling()\n    emitter.emit_line(\"} else {\")\n    generate_bin_op_reverse_dunder_call(fn, emitter, fn_rev.name)\n    emitter.emit_line(\"}\")\n    emitter.emit_label(\"typefail2\")\n    emitter.emit_line(\"Py_INCREF(Py_NotImplemented);\")\n    emitter.emit_line(\"return Py_NotImplemented;\")\n    gen.finish()\n\n\ndef generate_bin_op_reverse_dunder_call(fn: FuncIR, emitter: Emitter, rmethod: str) -> None:\n    if fn.name in (\"__pow__\", \"__rpow__\"):\n        # Ternary pow() will never call the reverse dunder.\n        emitter.emit_line(\"if (obj_mod == Py_None) {\")\n    emitter.emit_line(\n        'return CPy_CallReverseOpMethod(obj_left, obj_right, \"{}\", mypyc_interned_str.{});'.format(\n            op_methods_to_symbols[fn.name], rmethod\n        )\n    )\n    if fn.name in (\"__pow__\", \"__rpow__\"):\n        emitter.emit_line(\"} else {\")\n        emitter.emit_line(\"Py_INCREF(Py_NotImplemented);\")\n        emitter.emit_line(\"return Py_NotImplemented;\")\n        emitter.emit_line(\"}\")\n\n\ndef handle_third_pow_argument(\n    fn: FuncIR, emitter: Emitter, gen: WrapperGenerator, *, if_unsupported: list[str]\n) -> None:\n    if fn.name not in (\"__pow__\", \"__rpow__\", \"__ipow__\"):\n        return\n\n    if (fn.name in (\"__pow__\", \"__ipow__\") and len(fn.args) == 2) or fn.name == \"__rpow__\":\n        # If the power dunder only supports two arguments and the third\n        # argument (AKA mod) is set to a non-default value, simply bail.\n        #\n        # Importantly, this prevents any ternary __rpow__ calls from\n        # happening (as per the language specification).\n        emitter.emit_line(\"if (obj_mod != Py_None) {\")\n        for line in if_unsupported:\n            emitter.emit_line(line)\n        emitter.emit_line(\"}\")\n        # The slot wrapper will receive three arguments, but the call only\n        # supports two so make sure that the third argument isn't passed\n        # along. This is needed as two-argument __(i)pow__ is allowed and\n        # rather common.\n        if len(gen.arg_names) == 3:\n            gen.arg_names.pop()\n\n\nRICHCOMPARE_OPS = {\n    \"__lt__\": \"Py_LT\",\n    \"__gt__\": \"Py_GT\",\n    \"__le__\": \"Py_LE\",\n    \"__ge__\": \"Py_GE\",\n    \"__eq__\": \"Py_EQ\",\n    \"__ne__\": \"Py_NE\",\n}\n\n\ndef generate_richcompare_wrapper(cl: ClassIR, emitter: Emitter) -> str | None:\n    \"\"\"Generates a wrapper for richcompare dunder methods.\"\"\"\n    # Sort for determinism on Python 3.5\n    matches = sorted(name for name in RICHCOMPARE_OPS if cl.has_method(name))\n    if not matches:\n        return None\n\n    name = f\"{DUNDER_PREFIX}_RichCompare_{cl.name_prefix(emitter.names)}\"\n    emitter.emit_line(\n        \"static PyObject *{name}(PyObject *obj_lhs, PyObject *obj_rhs, int op) {{\".format(\n            name=name\n        )\n    )\n    emitter.emit_line(\"switch (op) {\")\n    for func in matches:\n        emitter.emit_line(f\"case {RICHCOMPARE_OPS[func]}: {{\")\n        method = cl.get_method(func)\n        assert method is not None\n        generate_wrapper_core(method, emitter, arg_names=[\"lhs\", \"rhs\"])\n        emitter.emit_line(\"}\")\n    emitter.emit_line(\"}\")\n\n    emitter.emit_line(\"Py_INCREF(Py_NotImplemented);\")\n    emitter.emit_line(\"return Py_NotImplemented;\")\n\n    emitter.emit_line(\"}\")\n\n    return name\n\n\ndef generate_get_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generates a wrapper for native __get__ methods.\"\"\"\n    name = f\"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}\"\n    emitter.emit_line(\n        \"static PyObject *{name}(PyObject *self, PyObject *instance, PyObject *owner) {{\".format(\n            name=name\n        )\n    )\n    emitter.emit_line(\"instance = instance ? instance : Py_None;\")\n    emitter.emit_line(f\"return {NATIVE_PREFIX}{fn.cname(emitter.names)}(self, instance, owner);\")\n    emitter.emit_line(\"}\")\n\n    return name\n\n\ndef generate_hash_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generates a wrapper for native __hash__ methods.\"\"\"\n    name = f\"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}\"\n    emitter.emit_line(f\"static Py_ssize_t {name}(PyObject *self) {{\")\n    emitter.emit_line(\n        \"{}retval = {}{}{}(self);\".format(\n            emitter.ctype_spaced(fn.ret_type),\n            emitter.get_group_prefix(fn.decl),\n            NATIVE_PREFIX,\n            fn.cname(emitter.names),\n        )\n    )\n    emitter.emit_error_check(\"retval\", fn.ret_type, \"return -1;\")\n    if is_int_rprimitive(fn.ret_type):\n        emitter.emit_line(\"Py_ssize_t val = CPyTagged_AsSsize_t(retval);\")\n    else:\n        emitter.emit_line(\"Py_ssize_t val = PyLong_AsSsize_t(retval);\")\n    emitter.emit_dec_ref(\"retval\", fn.ret_type)\n    emitter.emit_line(\"if (PyErr_Occurred()) return -1;\")\n    # We can't return -1 from a hash function..\n    emitter.emit_line(\"if (val == -1) return -2;\")\n    emitter.emit_line(\"return val;\")\n    emitter.emit_line(\"}\")\n\n    return name\n\n\ndef generate_len_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generates a wrapper for native __len__ methods.\"\"\"\n    name = f\"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}\"\n    emitter.emit_line(f\"static Py_ssize_t {name}(PyObject *self) {{\")\n    emitter.emit_line(\n        \"{}retval = {}{}{}(self);\".format(\n            emitter.ctype_spaced(fn.ret_type),\n            emitter.get_group_prefix(fn.decl),\n            NATIVE_PREFIX,\n            fn.cname(emitter.names),\n        )\n    )\n    emitter.emit_error_check(\"retval\", fn.ret_type, \"return -1;\")\n    if is_int_rprimitive(fn.ret_type):\n        emitter.emit_line(\"Py_ssize_t val = CPyTagged_AsSsize_t(retval);\")\n    else:\n        emitter.emit_line(\"Py_ssize_t val = PyLong_AsSsize_t(retval);\")\n    emitter.emit_dec_ref(\"retval\", fn.ret_type)\n    emitter.emit_line(\"if (PyErr_Occurred()) return -1;\")\n    emitter.emit_line(\"return val;\")\n    emitter.emit_line(\"}\")\n\n    return name\n\n\ndef generate_bool_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generates a wrapper for native __bool__ methods.\"\"\"\n    name = f\"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}\"\n    emitter.emit_line(f\"static int {name}(PyObject *self) {{\")\n    emitter.emit_line(\n        \"{}val = {}{}(self);\".format(\n            emitter.ctype_spaced(fn.ret_type), NATIVE_PREFIX, fn.cname(emitter.names)\n        )\n    )\n    emitter.emit_error_check(\"val\", fn.ret_type, \"return -1;\")\n    # This wouldn't be that hard to fix but it seems unimportant and\n    # getting error handling and unboxing right would be fiddly. (And\n    # way easier to do in IR!)\n    assert is_bool_rprimitive(fn.ret_type), \"Only bool return supported for __bool__\"\n    emitter.emit_line(\"return val;\")\n    emitter.emit_line(\"}\")\n\n    return name\n\n\ndef generate_del_item_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generates a wrapper for native __delitem__.\n\n    This is only called from a combined __delitem__/__setitem__ wrapper.\n    \"\"\"\n    name = \"{}{}{}\".format(DUNDER_PREFIX, \"__delitem__\", cl.name_prefix(emitter.names))\n    input_args = \", \".join(f\"PyObject *obj_{arg.name}\" for arg in fn.args)\n    emitter.emit_line(f\"static int {name}({input_args}) {{\")\n    generate_set_del_item_wrapper_inner(fn, emitter, fn.args)\n    return name\n\n\ndef generate_set_del_item_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generates a wrapper for native __setitem__ method (also works for __delitem__).\n\n    This is used with the mapping protocol slot. Arguments are taken as *PyObjects and we\n    return a negative C int on error.\n\n    Create a separate wrapper function for __delitem__ as needed and have the\n    __setitem__ wrapper call it if the value is NULL. Return the name\n    of the outer (__setitem__) wrapper.\n    \"\"\"\n    method_cls = cl.get_method_and_class(\"__delitem__\")\n    del_name = None\n    if method_cls and method_cls[1] == cl:\n        # Generate a separate wrapper for __delitem__\n        del_name = generate_del_item_wrapper(cl, method_cls[0], emitter)\n\n    args = fn.args\n    if fn.name == \"__delitem__\":\n        # Add an extra argument for value that we expect to be NULL.\n        args = list(args) + [RuntimeArg(\"___value\", object_rprimitive, ARG_POS)]\n\n    name = \"{}{}{}\".format(DUNDER_PREFIX, \"__setitem__\", cl.name_prefix(emitter.names))\n    input_args = \", \".join(f\"PyObject *obj_{arg.name}\" for arg in args)\n    emitter.emit_line(f\"static int {name}({input_args}) {{\")\n\n    # First check if this is __delitem__\n    emitter.emit_line(f\"if (obj_{args[2].name} == NULL) {{\")\n    if del_name is not None:\n        # We have a native implementation, so call it\n        emitter.emit_line(f\"return {del_name}(obj_{args[0].name}, obj_{args[1].name});\")\n    else:\n        # Try to call superclass method instead\n        emitter.emit_line(f\"PyObject *super = CPy_Super(CPyModule_builtins, obj_{args[0].name});\")\n        emitter.emit_line(\"if (super == NULL) return -1;\")\n        emitter.emit_line(\n            'PyObject *result = PyObject_CallMethod(super, \"__delitem__\", \"O\", obj_{});'.format(\n                args[1].name\n            )\n        )\n        emitter.emit_line(\"Py_DECREF(super);\")\n        emitter.emit_line(\"Py_XDECREF(result);\")\n        emitter.emit_line(\"return result == NULL ? -1 : 0;\")\n    emitter.emit_line(\"}\")\n\n    method_cls = cl.get_method_and_class(\"__setitem__\")\n    if method_cls and method_cls[1] == cl:\n        generate_set_del_item_wrapper_inner(fn, emitter, args)\n    else:\n        emitter.emit_line(f\"PyObject *super = CPy_Super(CPyModule_builtins, obj_{args[0].name});\")\n        emitter.emit_line(\"if (super == NULL) return -1;\")\n        emitter.emit_line(\"PyObject *result;\")\n\n        if method_cls is None and cl.builtin_base is None:\n            msg = f\"'{cl.name}' object does not support item assignment\"\n            emitter.emit_line(f'PyErr_SetString(PyExc_TypeError, \"{msg}\");')\n            emitter.emit_line(\"result = NULL;\")\n        else:\n            # A base class may have __setitem__\n            emitter.emit_line(\n                'result = PyObject_CallMethod(super, \"__setitem__\", \"OO\", obj_{}, obj_{});'.format(\n                    args[1].name, args[2].name\n                )\n            )\n        emitter.emit_line(\"Py_DECREF(super);\")\n        emitter.emit_line(\"Py_XDECREF(result);\")\n        emitter.emit_line(\"return result == NULL ? -1 : 0;\")\n        emitter.emit_line(\"}\")\n    return name\n\n\ndef generate_set_del_item_wrapper_inner(\n    fn: FuncIR, emitter: Emitter, args: Sequence[RuntimeArg]\n) -> None:\n    for arg in args:\n        generate_arg_check(arg.name, arg.type, emitter, GotoHandler(\"fail\"))\n    native_args = \", \".join(f\"arg_{arg.name}\" for arg in args)\n    emitter.emit_line(\n        \"{}val = {}{}({});\".format(\n            emitter.ctype_spaced(fn.ret_type), NATIVE_PREFIX, fn.cname(emitter.names), native_args\n        )\n    )\n    emitter.emit_error_check(\"val\", fn.ret_type, \"goto fail;\")\n    emitter.emit_dec_ref(\"val\", fn.ret_type)\n    emitter.emit_line(\"return 0;\")\n    emitter.emit_label(\"fail\")\n    emitter.emit_line(\"return -1;\")\n    emitter.emit_line(\"}\")\n\n\ndef generate_contains_wrapper(cl: ClassIR, fn: FuncIR, emitter: Emitter) -> str:\n    \"\"\"Generates a wrapper for a native __contains__ method.\"\"\"\n    name = f\"{DUNDER_PREFIX}{fn.name}{cl.name_prefix(emitter.names)}\"\n    emitter.emit_line(f\"static int {name}(PyObject *self, PyObject *obj_item) {{\")\n    generate_arg_check(\"item\", fn.args[1].type, emitter, ReturnHandler(\"-1\"))\n    emitter.emit_line(\n        \"{}val = {}{}(self, arg_item);\".format(\n            emitter.ctype_spaced(fn.ret_type), NATIVE_PREFIX, fn.cname(emitter.names)\n        )\n    )\n    emitter.emit_error_check(\"val\", fn.ret_type, \"return -1;\")\n    if is_bool_rprimitive(fn.ret_type):\n        emitter.emit_line(\"return val;\")\n    else:\n        emitter.emit_line(\"int boolval = PyObject_IsTrue(val);\")\n        emitter.emit_dec_ref(\"val\", fn.ret_type)\n        emitter.emit_line(\"return boolval;\")\n    emitter.emit_line(\"}\")\n\n    return name\n\n\n# Helpers\n\n\ndef generate_wrapper_core(\n    fn: FuncIR,\n    emitter: Emitter,\n    optional_args: list[RuntimeArg] | None = None,\n    arg_names: list[str] | None = None,\n    cleanups: list[str] | None = None,\n    traceback_code: str | None = None,\n) -> None:\n    \"\"\"Generates the core part of a wrapper function for a native function.\n\n    This expects each argument as a PyObject * named obj_{arg} as a precondition.\n    It converts the PyObject *s to the necessary types, checking and unboxing if necessary,\n    makes the call, then boxes the result if necessary and returns it.\n    \"\"\"\n    gen = WrapperGenerator(None, emitter)\n    gen.set_target(fn)\n    if arg_names:\n        gen.arg_names = arg_names\n    gen.cleanups = cleanups or []\n    gen.optional_args = optional_args or []\n    gen.traceback_code = traceback_code or \"\"\n\n    error = ReturnHandler(\"NULL\") if not gen.use_goto() else GotoHandler(\"fail\")\n    gen.emit_arg_processing(error=error)\n    gen.emit_call()\n    gen.emit_error_handling()\n\n\ndef generate_arg_check(\n    name: str,\n    typ: RType,\n    emitter: Emitter,\n    error: ErrorHandler | None = None,\n    *,\n    optional: bool = False,\n    raise_exception: bool = True,\n    bitmap_arg_index: int = 0,\n) -> None:\n    \"\"\"Insert a runtime check for argument and unbox if necessary.\n\n    The object is named PyObject *obj_{}. This is expected to generate\n    a value of name arg_{} (unboxed if necessary). For each primitive a runtime\n    check ensures the correct type.\n    \"\"\"\n    error = error or AssignHandler()\n    if typ.is_unboxed:\n        if typ.error_overlap and optional:\n            # Update bitmap is value is provided.\n            init = emitter.c_undefined_value(typ)\n            emitter.emit_line(f\"{emitter.ctype(typ)} arg_{name} = {init};\")\n            emitter.emit_line(f\"if (obj_{name} != NULL) {{\")\n            bitmap = bitmap_name(bitmap_arg_index // BITMAP_BITS)\n            emitter.emit_line(f\"{bitmap} |= 1 << {bitmap_arg_index & (BITMAP_BITS - 1)};\")\n            emitter.emit_unbox(\n                f\"obj_{name}\",\n                f\"arg_{name}\",\n                typ,\n                declare_dest=False,\n                raise_exception=raise_exception,\n                error=error,\n                borrow=True,\n            )\n            emitter.emit_line(\"}\")\n        else:\n            # Borrow when unboxing to avoid reference count manipulation.\n            emitter.emit_unbox(\n                f\"obj_{name}\",\n                f\"arg_{name}\",\n                typ,\n                declare_dest=True,\n                raise_exception=raise_exception,\n                error=error,\n                borrow=True,\n                optional=optional,\n            )\n    elif is_object_rprimitive(typ):\n        # Object is trivial since any object is valid\n        if optional:\n            emitter.emit_line(f\"PyObject *arg_{name};\")\n            emitter.emit_line(f\"if (obj_{name} == NULL) {{\")\n            emitter.emit_line(f\"arg_{name} = {emitter.c_error_value(typ)};\")\n            emitter.emit_lines(\"} else {\", f\"arg_{name} = obj_{name}; \", \"}\")\n        else:\n            emitter.emit_line(f\"PyObject *arg_{name} = obj_{name};\")\n    else:\n        emitter.emit_cast(\n            f\"obj_{name}\",\n            f\"arg_{name}\",\n            typ,\n            declare_dest=True,\n            raise_exception=raise_exception,\n            error=error,\n            optional=optional,\n        )\n\n\nclass WrapperGenerator:\n    \"\"\"Helper that simplifies the generation of wrapper functions.\"\"\"\n\n    # TODO: Use this for more wrappers\n\n    def __init__(self, cl: ClassIR | None, emitter: Emitter) -> None:\n        self.cl = cl\n        self.emitter = emitter\n        self.cleanups: list[str] = []\n        self.optional_args: list[RuntimeArg] = []\n        self.traceback_code = \"\"\n\n    def set_target(self, fn: FuncIR) -> None:\n        \"\"\"Set the wrapped function.\n\n        It's fine to modify the attributes initialized here later to customize\n        the wrapper function.\n        \"\"\"\n        self.target_name = fn.name\n        self.target_cname = fn.cname(self.emitter.names)\n        self.num_bitmap_args = fn.sig.num_bitmap_args\n        if self.num_bitmap_args:\n            self.args = fn.args[: -self.num_bitmap_args]\n        else:\n            self.args = fn.args\n        self.arg_names = [arg.name for arg in self.args]\n        self.ret_type = fn.ret_type\n\n    def wrapper_name(self) -> str:\n        \"\"\"Return the name of the wrapper function.\"\"\"\n        return \"{}{}{}\".format(\n            DUNDER_PREFIX,\n            self.target_name,\n            self.cl.name_prefix(self.emitter.names) if self.cl else \"\",\n        )\n\n    def use_goto(self) -> bool:\n        \"\"\"Do we use a goto for error handling (instead of straight return)?\"\"\"\n        return bool(self.cleanups or self.traceback_code)\n\n    def emit_header(self) -> None:\n        \"\"\"Emit the function header of the wrapper implementation.\"\"\"\n        input_args = \", \".join(f\"PyObject *obj_{arg}\" for arg in self.arg_names)\n        self.emitter.emit_line(\n            \"static PyObject *{name}({input_args}) {{\".format(\n                name=self.wrapper_name(), input_args=input_args\n            )\n        )\n\n    def emit_arg_processing(\n        self, error: ErrorHandler | None = None, raise_exception: bool = True\n    ) -> None:\n        \"\"\"Emit validation and unboxing of arguments.\"\"\"\n        error = error or self.error()\n        bitmap_arg_index = 0\n        for arg_name, arg in zip(self.arg_names, self.args):\n            # Suppress the argument check for *args/**kwargs, since we know it must be right.\n            typ = arg.type if arg.kind not in (ARG_STAR, ARG_STAR2) else object_rprimitive\n            optional = arg in self.optional_args\n            generate_arg_check(\n                arg_name,\n                typ,\n                self.emitter,\n                error,\n                raise_exception=raise_exception,\n                optional=optional,\n                bitmap_arg_index=bitmap_arg_index,\n            )\n            if optional and typ.error_overlap:\n                bitmap_arg_index += 1\n\n    def emit_call(self, not_implemented_handler: str = \"\") -> None:\n        \"\"\"Emit call to the wrapper function.\n\n        If not_implemented_handler is non-empty, use this C code to handle\n        a NotImplemented return value (if it's possible based on the return type).\n        \"\"\"\n        native_args = \", \".join(f\"arg_{arg}\" for arg in self.arg_names)\n        if self.num_bitmap_args:\n            bitmap_args = \", \".join(\n                [bitmap_name(i) for i in reversed(range(self.num_bitmap_args))]\n            )\n            native_args = f\"{native_args}, {bitmap_args}\"\n\n        ret_type = self.ret_type\n        emitter = self.emitter\n        if ret_type.is_unboxed or self.use_goto():\n            # TODO: The Py_RETURN macros return the correct PyObject * with reference count\n            #       handling. Are they relevant?\n            emitter.emit_line(\n                \"{}retval = {}{}({});\".format(\n                    emitter.ctype_spaced(ret_type), NATIVE_PREFIX, self.target_cname, native_args\n                )\n            )\n            emitter.emit_lines(*self.cleanups)\n            if ret_type.is_unboxed:\n                emitter.emit_error_check(\"retval\", ret_type, \"return NULL;\")\n                emitter.emit_box(\"retval\", \"retbox\", ret_type, declare_dest=True)\n\n            emitter.emit_line(\"return {};\".format(\"retbox\" if ret_type.is_unboxed else \"retval\"))\n        else:\n            if not_implemented_handler and not isinstance(ret_type, RInstance):\n                # The return value type may overlap with NotImplemented.\n                emitter.emit_line(\n                    \"PyObject *retbox = {}{}({});\".format(\n                        NATIVE_PREFIX, self.target_cname, native_args\n                    )\n                )\n                emitter.emit_lines(\n                    \"if (retbox == Py_NotImplemented) {\",\n                    not_implemented_handler,\n                    \"}\",\n                    \"return retbox;\",\n                )\n            else:\n                emitter.emit_line(f\"return {NATIVE_PREFIX}{self.target_cname}({native_args});\")\n            # TODO: Tracebacks?\n\n    def error(self) -> ErrorHandler:\n        \"\"\"Figure out how to deal with errors in the wrapper.\"\"\"\n        if self.cleanups or self.traceback_code:\n            # We'll have a label at the end with error handling code.\n            return GotoHandler(\"fail\")\n        else:\n            # Nothing special needs to done to handle errors, so just return.\n            return ReturnHandler(\"NULL\")\n\n    def emit_error_handling(self) -> None:\n        \"\"\"Emit error handling block at the end of the wrapper, if needed.\"\"\"\n        emitter = self.emitter\n        if self.use_goto():\n            emitter.emit_label(\"fail\")\n            emitter.emit_lines(*self.cleanups)\n            if self.traceback_code:\n                emitter.emit_line(self.traceback_code)\n            emitter.emit_line(\"return NULL;\")\n\n    def finish(self) -> None:\n        self.emitter.emit_line(\"}\")\n"
  },
  {
    "path": "mypyc/codegen/literals.py",
    "content": "from __future__ import annotations\n\nfrom typing import Final, TypeGuard\n\n# Supported Python literal types. All tuple / frozenset items must have supported\n# literal types as well, but we can't represent the type precisely.\nLiteralValue = (\n    str | bytes | int | bool | float | complex | tuple[object, ...] | frozenset[object] | None\n)\n\n\ndef _is_literal_value(obj: object) -> TypeGuard[LiteralValue]:\n    return isinstance(obj, (str, bytes, int, float, complex, tuple, frozenset, type(None)))\n\n\n# Some literals are singletons and handled specially (None, False and True)\nNUM_SINGLETONS: Final = 3\n\n\nclass Literals:\n    \"\"\"Collection of literal values used in a compilation group and related helpers.\"\"\"\n\n    def __init__(self) -> None:\n        # Each dict maps value to literal index (0, 1, ...)\n        self.str_literals: dict[str, int] = {}\n        self.bytes_literals: dict[bytes, int] = {}\n        self.int_literals: dict[int, int] = {}\n        self.float_literals: dict[float, int] = {}\n        self.complex_literals: dict[complex, int] = {}\n        self.tuple_literals: dict[tuple[object, ...], int] = {}\n        self.frozenset_literals: dict[frozenset[object], int] = {}\n\n    def record_literal(self, value: LiteralValue) -> None:\n        \"\"\"Ensure that the literal value is available in generated code.\"\"\"\n        if value is None or value is True or value is False:\n            # These are special cased and always present\n            return\n        if isinstance(value, str):\n            str_literals = self.str_literals\n            if value not in str_literals:\n                str_literals[value] = len(str_literals)\n        elif isinstance(value, bytes):\n            bytes_literals = self.bytes_literals\n            if value not in bytes_literals:\n                bytes_literals[value] = len(bytes_literals)\n        elif isinstance(value, int):\n            int_literals = self.int_literals\n            if value not in int_literals:\n                int_literals[value] = len(int_literals)\n        elif isinstance(value, float):\n            float_literals = self.float_literals\n            if value not in float_literals:\n                float_literals[value] = len(float_literals)\n        elif isinstance(value, complex):\n            complex_literals = self.complex_literals\n            if value not in complex_literals:\n                complex_literals[value] = len(complex_literals)\n        elif isinstance(value, tuple):\n            tuple_literals = self.tuple_literals\n            if value not in tuple_literals:\n                for item in value:\n                    assert _is_literal_value(item)\n                    self.record_literal(item)\n                tuple_literals[value] = len(tuple_literals)\n        elif isinstance(value, frozenset):\n            frozenset_literals = self.frozenset_literals\n            if value not in frozenset_literals:\n                for item in value:\n                    assert _is_literal_value(item)\n                    self.record_literal(item)\n                frozenset_literals[value] = len(frozenset_literals)\n        else:\n            assert False, \"invalid literal: %r\" % value\n\n    def literal_index(self, value: LiteralValue) -> int:\n        \"\"\"Return the index to the literals array for given value.\"\"\"\n        # The array contains first None and booleans, followed by all str values,\n        # followed by bytes values, etc.\n        if value is None:\n            return 0\n        elif value is False:\n            return 1\n        elif value is True:\n            return 2\n        n = NUM_SINGLETONS\n        if isinstance(value, str):\n            return n + self.str_literals[value]\n        n += len(self.str_literals)\n        if isinstance(value, bytes):\n            return n + self.bytes_literals[value]\n        n += len(self.bytes_literals)\n        if isinstance(value, int):\n            return n + self.int_literals[value]\n        n += len(self.int_literals)\n        if isinstance(value, float):\n            return n + self.float_literals[value]\n        n += len(self.float_literals)\n        if isinstance(value, complex):\n            return n + self.complex_literals[value]\n        n += len(self.complex_literals)\n        if isinstance(value, tuple):\n            return n + self.tuple_literals[value]\n        n += len(self.tuple_literals)\n        if isinstance(value, frozenset):\n            return n + self.frozenset_literals[value]\n        assert False, \"invalid literal: %r\" % value\n\n    def num_literals(self) -> int:\n        # The first three are for None, True and False\n        return (\n            NUM_SINGLETONS\n            + len(self.str_literals)\n            + len(self.bytes_literals)\n            + len(self.int_literals)\n            + len(self.float_literals)\n            + len(self.complex_literals)\n            + len(self.tuple_literals)\n            + len(self.frozenset_literals)\n        )\n\n    # The following methods return the C encodings of literal values\n    # of different types\n\n    def encoded_str_values(self) -> list[bytes]:\n        return _encode_str_values(self.str_literals)\n\n    def encoded_int_values(self) -> list[bytes]:\n        return _encode_int_values(self.int_literals)\n\n    def encoded_bytes_values(self) -> list[bytes]:\n        return _encode_bytes_values(self.bytes_literals)\n\n    def encoded_float_values(self) -> list[str]:\n        return _encode_float_values(self.float_literals)\n\n    def encoded_complex_values(self) -> list[str]:\n        return _encode_complex_values(self.complex_literals)\n\n    def encoded_tuple_values(self) -> list[str]:\n        return self._encode_collection_values(self.tuple_literals)\n\n    def encoded_frozenset_values(self) -> list[str]:\n        return self._encode_collection_values(self.frozenset_literals)\n\n    def _encode_collection_values(\n        self, values: dict[tuple[object, ...], int] | dict[frozenset[object], int]\n    ) -> list[str]:\n        \"\"\"Encode tuple/frozenset values into a C array.\n\n        The format of the result is like this:\n\n           <number of collections>\n           <length of the first collection>\n           <literal index of first item>\n           ...\n           <literal index of last item>\n           <length of the second collection>\n           ...\n        \"\"\"\n        value_by_index = {index: value for value, index in values.items()}\n        result = []\n        count = len(values)\n        result.append(str(count))\n        for i in range(count):\n            value = value_by_index[i]\n            result.append(str(len(value)))\n            for item in value:\n                assert _is_literal_value(item)\n                index = self.literal_index(item)\n                result.append(str(index))\n        return result\n\n\ndef _encode_str_values(values: dict[str, int]) -> list[bytes]:\n    value_by_index = {index: value for value, index in values.items()}\n    result = []\n    line: list[bytes] = []\n    line_len = 0\n    for i in range(len(values)):\n        value = value_by_index[i]\n        c_literal = format_str_literal(value)\n        c_len = len(c_literal)\n        if line_len > 0 and line_len + c_len > 70:\n            result.append(format_int(len(line)) + b\"\".join(line))\n            line = []\n            line_len = 0\n        line.append(c_literal)\n        line_len += c_len\n    if line:\n        result.append(format_int(len(line)) + b\"\".join(line))\n    result.append(b\"\")\n    return result\n\n\ndef _encode_bytes_values(values: dict[bytes, int]) -> list[bytes]:\n    value_by_index = {index: value for value, index in values.items()}\n    result = []\n    line: list[bytes] = []\n    line_len = 0\n    for i in range(len(values)):\n        value = value_by_index[i]\n        c_init = format_int(len(value))\n        c_len = len(c_init) + len(value)\n        if line_len > 0 and line_len + c_len > 70:\n            result.append(format_int(len(line)) + b\"\".join(line))\n            line = []\n            line_len = 0\n        line.append(c_init + value)\n        line_len += c_len\n    if line:\n        result.append(format_int(len(line)) + b\"\".join(line))\n    result.append(b\"\")\n    return result\n\n\ndef format_int(n: int) -> bytes:\n    \"\"\"Format an integer using a variable-length binary encoding.\"\"\"\n    if n < 128:\n        a = [n]\n    else:\n        a = []\n        while n > 0:\n            a.insert(0, n & 0x7F)\n            n >>= 7\n        for i in range(len(a) - 1):\n            # If the highest bit is set, more 7-bit digits follow\n            a[i] |= 0x80\n    return bytes(a)\n\n\ndef format_str_literal(s: str) -> bytes:\n    utf8 = s.encode(\"utf-8\", errors=\"surrogatepass\")\n    return format_int(len(utf8)) + utf8\n\n\ndef _encode_int_values(values: dict[int, int]) -> list[bytes]:\n    \"\"\"Encode int values into C strings.\n\n    Values are stored in base 10 and separated by 0 bytes.\n    \"\"\"\n    value_by_index = {index: value for value, index in values.items()}\n    result = []\n    line: list[bytes] = []\n    line_len = 0\n    for i in range(len(values)):\n        value = value_by_index[i]\n        encoded = b\"%d\" % value\n        if line_len > 0 and line_len + len(encoded) > 70:\n            result.append(format_int(len(line)) + b\"\\0\".join(line))\n            line = []\n            line_len = 0\n        line.append(encoded)\n        line_len += len(encoded)\n    if line:\n        result.append(format_int(len(line)) + b\"\\0\".join(line))\n    result.append(b\"\")\n    return result\n\n\ndef float_to_c(x: float) -> str:\n    \"\"\"Return C literal representation of a float value.\"\"\"\n    s = str(x)\n    if s == \"inf\":\n        return \"INFINITY\"\n    elif s == \"-inf\":\n        return \"-INFINITY\"\n    elif s == \"nan\":\n        return \"NAN\"\n    return s\n\n\ndef _encode_float_values(values: dict[float, int]) -> list[str]:\n    \"\"\"Encode float values into a C array values.\n\n    The result contains the number of values followed by individual values.\n    \"\"\"\n    value_by_index = {index: value for value, index in values.items()}\n    result = []\n    num = len(values)\n    result.append(str(num))\n    for i in range(num):\n        value = value_by_index[i]\n        result.append(float_to_c(value))\n    return result\n\n\ndef _encode_complex_values(values: dict[complex, int]) -> list[str]:\n    \"\"\"Encode float values into a C array values.\n\n    The result contains the number of values followed by pairs of doubles\n    representing complex numbers.\n    \"\"\"\n    value_by_index = {index: value for value, index in values.items()}\n    result = []\n    num = len(values)\n    result.append(str(num))\n    for i in range(num):\n        value = value_by_index[i]\n        result.append(float_to_c(value.real))\n        result.append(float_to_c(value.imag))\n    return result\n"
  },
  {
    "path": "mypyc/common.py",
    "content": "from __future__ import annotations\n\nimport sys\nimport sysconfig\nfrom typing import Any, Final\n\nfrom mypy.util import unnamed_function\n\nPREFIX: Final = \"CPyPy_\"  # Python wrappers\nNATIVE_PREFIX: Final = \"CPyDef_\"  # Native functions etc.\nDUNDER_PREFIX: Final = \"CPyDunder_\"  # Wrappers for exposing dunder methods to the API\nREG_PREFIX: Final = \"cpy_r_\"  # Registers\nSTATIC_PREFIX: Final = \"CPyStatic_\"  # Static variables (for literals etc.)\nTYPE_PREFIX: Final = \"CPyType_\"  # Type object struct\nMODULE_PREFIX: Final = \"CPyModule_\"  # Cached modules\nTYPE_VAR_PREFIX: Final = \"CPyTypeVar_\"  # Type variables when using new-style Python 3.12 syntax\nATTR_PREFIX: Final = \"_\"  # Attributes\nFAST_PREFIX: Final = \"__mypyc_fast_\"  # Optimized methods in non-extension classes\n\nENV_ATTR_NAME: Final = \"__mypyc_env__\"\nNEXT_LABEL_ATTR_NAME: Final = \"__mypyc_next_label__\"\nTEMP_ATTR_NAME: Final = \"__mypyc_temp__\"\nLAMBDA_NAME: Final = \"__mypyc_lambda__\"\nPROPSET_PREFIX: Final = \"__mypyc_setter__\"\nSELF_NAME: Final = \"__mypyc_self__\"\nGENERATOR_ATTRIBUTE_PREFIX: Final = \"__mypyc_generator_attribute__\"\nCPYFUNCTION_NAME = \"__cpyfunction__\"\n\n# Max short int we accept as a literal is based on 32-bit platforms,\n# so that we can just always emit the same code.\n\nTOP_LEVEL_NAME: Final = \"__top_level__\"  # Special function representing module top level\n\n# Maximal number of subclasses for a class to trigger fast path in isinstance() checks.\nFAST_ISINSTANCE_MAX_SUBCLASSES: Final = 2\n\n# Size of size_t, if configured.\nSIZEOF_SIZE_T_SYSCONFIG: Final = sysconfig.get_config_var(\"SIZEOF_SIZE_T\")\n\nSIZEOF_SIZE_T: Final = (\n    int(SIZEOF_SIZE_T_SYSCONFIG)\n    if SIZEOF_SIZE_T_SYSCONFIG is not None\n    else (sys.maxsize + 1).bit_length() // 8\n)\n\nIS_32_BIT_PLATFORM: Final = int(SIZEOF_SIZE_T) == 4\n\nPLATFORM_SIZE = 4 if IS_32_BIT_PLATFORM else 8\n\n# Maximum value for a short tagged integer.\nMAX_SHORT_INT: Final = 2 ** (8 * int(SIZEOF_SIZE_T) - 2) - 1\n\n# Minimum value for a short tagged integer.\nMIN_SHORT_INT: Final = -(MAX_SHORT_INT) - 1\n\n# Maximum value for a short tagged integer represented as a C integer literal.\n#\n# Note: Assume that the compiled code uses the same bit width as mypyc\nMAX_LITERAL_SHORT_INT: Final = MAX_SHORT_INT\nMIN_LITERAL_SHORT_INT: Final = -MAX_LITERAL_SHORT_INT - 1\n\n# Description of the C type used to track the definedness of attributes and\n# the presence of argument default values that have types with overlapping\n# error values. Each tracked attribute/argument has a dedicated bit in the\n# relevant bitmap.\nBITMAP_TYPE: Final = \"uint32_t\"\nBITMAP_BITS: Final = 32\n\n# Runtime C library files that are always included (some ops may bring\n# extra dependencies via mypyc.ir.SourceDep)\nRUNTIME_C_FILES: Final = [\n    \"init.c\",\n    \"getargs.c\",\n    \"getargsfast.c\",\n    \"int_ops.c\",\n    \"float_ops.c\",\n    \"str_ops.c\",\n    \"bytes_ops.c\",\n    \"list_ops.c\",\n    \"dict_ops.c\",\n    \"set_ops.c\",\n    \"tuple_ops.c\",\n    \"exc_ops.c\",\n    \"misc_ops.c\",\n    \"generic_ops.c\",\n    \"pythonsupport.c\",\n    \"function_wrapper.c\",\n]\n\n# Python 3.12 introduced immortal objects, specified via a special reference count\n# value. The reference counts of immortal objects are normally not modified, but it's\n# not strictly wrong to modify them. See PEP 683 for more information, but note that\n# some details in the PEP are out of date.\nHAVE_IMMORTAL: Final = sys.version_info >= (3, 12)\n\n# Are we running on a free-threaded build (GIL disabled)? This implies that\n# we are on Python 3.13 or later.\nIS_FREE_THREADED: Final = bool(sysconfig.get_config_var(\"Py_GIL_DISABLED\"))\n\n\nJsonDict = dict[str, Any]\n\n\ndef shared_lib_name(group_name: str) -> str:\n    \"\"\"Given a group name, return the actual name of its extension module.\n\n    (This just adds a suffix to the final component.)\n    \"\"\"\n    return f\"{group_name}__mypyc\"\n\n\ndef short_name(name: str) -> str:\n    if name.startswith(\"builtins.\"):\n        return name[9:]\n    return name\n\n\ndef get_id_from_name(name: str, fullname: str, line: int) -> str:\n    \"\"\"Create a unique id for a function.\n\n    This creates an id that is unique for any given function definition, so that it can be used as\n    a dictionary key. This is usually the fullname of the function, but this is different in that\n    it handles the case where the function is named '_', in which case multiple different functions\n    could have the same name.\"\"\"\n    if unnamed_function(name):\n        return f\"{fullname}.{line}\"\n    else:\n        return fullname\n\n\ndef short_id_from_name(func_name: str, shortname: str, line: int | None) -> str:\n    if unnamed_function(func_name):\n        assert line is not None\n        partial_name = f\"{shortname}.{line}\"\n    else:\n        partial_name = shortname\n    return partial_name\n\n\ndef bitmap_name(index: int) -> str:\n    if index == 0:\n        return \"__bitmap\"\n    return f\"__bitmap{index + 1}\"\n"
  },
  {
    "path": "mypyc/crash.py",
    "content": "from __future__ import annotations\n\nimport sys\nimport traceback\nfrom collections.abc import Iterator\nfrom contextlib import contextmanager\nfrom typing import NoReturn\n\n\n@contextmanager\ndef catch_errors(module_path: str, line: int) -> Iterator[None]:\n    try:\n        yield\n    except Exception:\n        crash_report(module_path, line)\n\n\ndef crash_report(module_path: str, line: int) -> NoReturn:\n    # Adapted from report_internal_error in mypy\n    err = sys.exc_info()[1]\n    tb = traceback.extract_stack()[:-4]\n    # Excise all the traceback from the test runner\n    for i, x in enumerate(tb):\n        if x.name == \"pytest_runtest_call\":\n            tb = tb[i + 1 :]\n            break\n    tb2 = traceback.extract_tb(sys.exc_info()[2])[1:]\n    print(\"Traceback (most recent call last):\")\n    for s in traceback.format_list(tb + tb2):\n        print(s.rstrip(\"\\n\"))\n    print(f\"{module_path}:{line}: {type(err).__name__}: {err}\")\n    raise SystemExit(2)\n"
  },
  {
    "path": "mypyc/doc/Makefile",
    "content": "# Minimal makefile for Sphinx documentation\n#\n\n# You can set these variables from the command line, and also\n# from the environment for the first two.\nSPHINXOPTS    ?=\nSPHINXBUILD   ?= sphinx-build\nSOURCEDIR     = .\nBUILDDIR      = _build\n\n# Put it first so that \"make\" without argument is like \"make help\".\nhelp:\n\t@$(SPHINXBUILD) -M help \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)\n\n.PHONY: help Makefile\n\n# Catch-all target: route all unknown targets to Sphinx using the new\n# \"make mode\" option.  $(O) is meant as a shortcut for $(SPHINXOPTS).\n%: Makefile\n\t@$(SPHINXBUILD) -M $@ \"$(SOURCEDIR)\" \"$(BUILDDIR)\" $(SPHINXOPTS) $(O)\n"
  },
  {
    "path": "mypyc/doc/bool_operations.rst",
    "content": ".. _bool-ops:\n\nNative boolean operations\n=========================\n\nOperations on ``bool`` values that are listed here have fast,\noptimized implementations.\n\nConstruction\n------------\n\n* ``True``\n* ``False``\n* ``bool(obj)``\n\nOperators\n---------\n\n* ``b1 and b2``\n* ``b1 or b2``\n* ``not b``\n\nFunctions\n---------\n\n* ``any(expr for ... in ...)``\n* ``all(expr for ... in ...)``\n"
  },
  {
    "path": "mypyc/doc/bytearray_operations.rst",
    "content": ".. _bytearray-ops:\n\nNative bytearray operations\n============================\n\nThese ``bytearray`` operations have fast, optimized implementations. Other\nbytearray operations use generic implementations that are often slower.\n\nConstruction\n------------\n\n* ``bytearray()``\n* ``bytearray(x)``\n"
  },
  {
    "path": "mypyc/doc/bytes_operations.rst",
    "content": ".. _bytes-ops:\n\nNative bytes operations\n========================\n\nThese ``bytes`` operations have fast, optimized implementations. Other\nbytes operations use generic implementations that are often slower.\n\nConstruction\n------------\n\n* Bytes literal\n* ``bytes(x: list)``\n\nOperators\n---------\n\n* Concatenation (``b1 + b2``)\n* Indexing (``b[n]``)\n* Slicing (``b[n:m]``, ``b[n:]``, ``b[:m]``)\n* Repetition (``b * n``, ``n * b``)\n* Comparisons (``==``, ``!=``)\n\n.. _bytes-methods:\n\nMethods\n-------\n\n* ``b.decode()``\n* ``b.decode(encoding: str)``\n* ``b.decode(encoding: str, errors: str)``\n* ``b1.endswith(b2: bytes)``\n* ``b.join(x: Iterable)``\n* ``b1.startswith(b2: bytes)``\n* ``b.translate(table: bytes)``\n\n.. note::\n\n    :ref:`str.encode() <str-methods>` is also optimized.\n\nFormatting\n----------\n\nA subset of % formatting operations are optimized (``b\"...\" % (...)``).\n\nFunctions\n---------\n\n* ``len(b: bytes)``\n* ``ord(b: bytes)``\n"
  },
  {
    "path": "mypyc/doc/compilation_units.rst",
    "content": ".. _compilation-units:\n\nCompilation units\n=================\n\nWhen you run mypyc to compile a set of modules, these modules form a\n*compilation unit*. Mypyc will use early binding for references within\nthe compilation unit.\n\nIf you run mypyc multiple times to compile multiple sets of modules,\neach invocation will result in a new compilation unit. References\nbetween separate compilation units will fall back to late binding,\ni.e. looking up names using Python namespace dictionaries. Also, all\ncalls will use the slower Python calling convention, where arguments\nand the return value will be boxed (and potentially unboxed again in\nthe called function).\n\nFor maximal performance, minimize interactions across compilation\nunits. The simplest way to achieve this is to compile your entire\nprogram as a single compilation unit.\n"
  },
  {
    "path": "mypyc/doc/conf.py",
    "content": "# Configuration file for the Sphinx documentation builder.\n#\n# This file only contains a selection of the most common options. For a full\n# list see the documentation:\n# https://www.sphinx-doc.org/en/master/usage/configuration.html\n\nfrom __future__ import annotations\n\nimport os\nimport sys\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\nsys.path.insert(0, os.path.abspath(\"../..\"))\n\nfrom mypy.version import __version__ as mypy_version\n\n# -- Project information -----------------------------------------------------\n\nproject = \"mypyc\"\ncopyright = \"2020-2022, mypyc team\"\nauthor = \"mypyc team\"\n\n# The version info for the project you're documenting, acts as replacement for\n# |version| and |release|, also used in various other places throughout the\n# built documents.\n#\n# The short X.Y version.\nversion = mypy_version.split(\"-\")[0]\n# The full version, including alpha/beta/rc tags.\nrelease = mypy_version\n\n# -- General configuration ---------------------------------------------------\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions: list[str] = []\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = [\"_templates\"]\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path.\nexclude_patterns = [\"_build\", \"Thumbs.db\", \".DS_Store\"]\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\nhtml_theme = \"furo\"\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = [\"_static\"]\n"
  },
  {
    "path": "mypyc/doc/cpython-timings.md",
    "content": "# Timings of CPython Operations\n\nHere are some *very rough* approximate timings of CPython interpreter\noperations:\n\n* `f(1)` (empty function body): 70-90ns\n* `f(n=1)` (empty function body): 90-110ns\n* `o.x`: 30-40ns\n* `o.f(1)` (empty method body): 80-160ns\n* `Cls(1)` (initialize attribute in `__init__`): 290-330ns\n* `x + y` (integers): 20-35ns\n* `a[i]` (list) : 20-40ns\n* `[i]` (also dealloc): 35-55ns\n* `a.append(i)` (list, average over 5 appends): 70ns\n* `d[s]` (dict, shared str key): 20ns\n* `d[s] = i` (dict, shared str key): 40ns\n* `isinstance(x, A)`: 100ns\n* `(x, y)`: 20-35ns\n* `x, y = t` (tuple expand): 10ns\n\nNote that these results are very imprecise due to many factors, but\nthese should give a rough idea of the relative costs of various\noperations.\n\nDetails: CPython 3.6.2, Macbook Pro 15\" (Mid 2015), macOS Sierra\n"
  },
  {
    "path": "mypyc/doc/dev-intro.md",
    "content": "# Introduction for Mypyc Contributors\n\nThis is a short introduction aimed at anybody who is interested in\ncontributing to mypyc, or anybody who is curious to understand how\nmypyc works internally.\n\n## Developer Documentation in the Wiki\n\nWe have more mypyc developer documentation in our\n[wiki](https://github.com/python/mypy/wiki/Developer-Guides).\n\nFor basic information common to both mypy and mypyc development, refer\nto the [mypy wiki home page](https://github.com/python/mypy/wiki).\n\n## Key Differences from Python\n\nCode compiled using mypyc is often much faster than CPython since it\ndoes these things differently:\n\n* Mypyc generates C that is compiled to native code, instead of\n  compiling to interpreted byte code, which CPython uses. Interpreted\n  byte code always has some interpreter overhead, which slows things\n  down.\n\n* Mypyc doesn't let you arbitrarily monkey patch classes and functions\n  in compiled modules.  This allows *early binding* -- mypyc\n  statically binds calls to compiled functions, instead of going\n  through a namespace dictionary.  Mypyc can also call methods of\n  compiled classes using vtables, which are more efficient than\n  dictionary lookups used by CPython.\n\n* Mypyc compiles classes to C extension classes, which are generally\n  more efficient than normal Python classes. They use an efficient,\n  fixed memory representation (essentially a C struct).  This lets us\n  use direct memory access instead of (typically) two hash table\n  lookups to access an attribute.\n\n* As a result of early binding, compiled code can use C calls to call\n  compiled functions. Keyword arguments can be translated to\n  positional arguments during compilation. Thus most calls to native\n  functions and methods directly map to simple C calls. CPython calls\n  are quite expensive, since mapping of keyword arguments, `*args`,\n  and so on has to mostly happen at runtime.\n\n* Compiled code has runtime type checks to ensure that runtimes types\n  match the declared static types. Compiled code can thus make\n  assumptions about the types of expressions, resulting in both faster\n  and smaller code, since many runtime type checks performed by the\n  CPython interpreter can be omitted.\n\n* Compiled code can often use unboxed (not heap allocated)\n  representations for integers, booleans and tuples.\n\n## Supported Python Features\n\nMypyc supports a large subset of Python. Note that if you try to\ncompile something that is not supported, you may not always get a very\ngood error message.\n\nHere are some major things that aren't yet supported in compiled code:\n\n* Some dunder methods (most work though)\n* Monkey patching compiled functions or classes\n* General multiple inheritance (a limited form is supported)\n\nWe are generally happy to accept contributions that implement new Python\nfeatures.\n\n## Development Environment\n\nFirst you should set up the mypy development environment as described in\nthe [mypy docs](https://github.com/python/mypy/blob/master/README.md).\nmacOS, Linux and Windows are supported.\n\n## Compiling and Running Programs\n\nWhen working on a mypyc feature or a fix, you'll often need to run\ncompiled code. For example, you may want to do interactive testing or\nto run benchmarks. This is also handy if you want to inspect the\ngenerated C code (see Inspecting Generated C).\n\nRun `python -m mypyc` to compile a module to a C extension using your\ndevelopment version of mypyc:\n\n```\n$ python -m mypyc program.py\n```\n\nThis will generate a C extension for `program` in the current working\ndirectory.  For example, on a macOS system the generated file may be\ncalled `program.cpython-313-darwin.so`.\n\nSince C extensions can't be run as programs, use `python3 -c` to run\nthe compiled module as a program:\n\n```\n$ python3 -c \"import program\"\n```\n\nNote that `__name__` in `program.py` will now be `program`, not\n`__main__`!\n\nYou can manually delete the C extension to get back to an interpreted\nversion (this example works on macOS or Linux):\n\n```\n$ rm program.*.so\n```\n\nAnother option is to invoke mypyc through tests (see Testing below).\n\n## High-level Overview of Mypyc\n\nMypyc compiles a Python module (or a set of modules) to C, and\ncompiles the generated C to a Python C extension module (or\nmodules). You can compile only a subset of your program to C --\ncompiled and interpreted code can freely and transparently\ninteract. You can also freely use any Python libraries (including C\nextensions) in compiled code.\n\nMypyc will only make compiled code faster. To see a significant\nspeedup, you must make sure that most of the time is spent in compiled\ncode, and not in libraries or I/O.\n\nMypyc has these main passes:\n\n* Type check the code using mypy and infer types for variables and\n  expressions.  This produces a mypy AST (defined in `mypy.nodes`) and\n  a type map that describes the inferred types (`mypy.types.Type`) of\n  all expressions (as PEP 484 types).\n\n* Translate the mypy AST into a mypyc-specific intermediate representation (IR).\n  * The IR is defined in `mypyc.ir` (see below for an explanation of the IR).\n  * Various primitive operations used in the IR are defined in `mypyc.primitives`.\n  * The translation to IR happens in `mypyc.irbuild`. The top-level logic is in\n    `mypyc.irbuild.main`.\n\n* Insert checks for uses of potentially uninitialized variables\n  (`mypyc.transform.uninit`).\n\n* Insert exception handling (`mypyc.transform.exceptions`).\n\n* Insert explicit reference count inc/dec opcodes (`mypyc.transform.refcount`).\n\n* Translate the IR into C (`mypyc.codegen`).\n\n* Compile the generated C code using a C compiler (`mypyc.build`).\n\n## Useful Background Information\n\nBeyond the mypy documentation, here are some things that are helpful to\nknow for mypyc contributors:\n\n* Experience with C\n  ([The C Programming Language](https://en.wikipedia.org/wiki/The_C_Programming_Language)\n  is a classic book about C)\n* Basic familiarity with the Python C API (see\n  [Python C API documentation](https://docs.python.org/3/c-api/intro.html)). [Extending and Embedding the Python Interpreter](https://docs.python.org/3/extending/index.html) is a good tutorial for beginners.\n* Basics of compilers (see the\n  [mypy wiki](https://github.com/python/mypy/wiki/Learning-Resources)\n  for some ideas)\n\n## Mypyc Intermediate Representation (IR)\n\nThe mypyc IR is defined in `mypyc.ir`. It covers several key concepts\nthat are essential to understand by all mypyc contributors:\n\n* `mypyc.ir.ops.Op` is an Abstract Base Class for all IR\n  operations. These are low-level and generally map to simple\n  fragments of C each. Mypy expressions are translated to\n  linear sequences of these ops.\n\n* `mypyc.ir.ops.BasicBlock` is a container of a sequence of ops with a\n  branch/goto/return at the end, and no branch/goto/return ops in the\n  middle. Each function is compiled to a bunch of basic blocks.\n\n* `mypyc.ir.rtypes.RType` and its subclasses are the types used for\n  everything in the IR. These are lower-level and simpler than mypy or\n  PEP 484 types. For example, there are no general-purpose generic\n  types types here. Each `List[X]` type (for any `X`) is represented\n  by a single `list` type, for example.\n\n* Primitive types are special RTypes of which mypyc has some special\n  understanding, and there are typically some specialized\n  ops. Examples include `int` (referred to as `int_rprimitive` in the\n  code) and `list` (`list_rprimitive`). Python types for which there\n  is no specific RType type will be represented by the catch-all\n  `object_rprimitive` type.\n\n* Instances of compiled classes are generally represented using the\n  `RInstance` type.  Classes are compiled to C extension classes and\n  contain vtables for fast method calls and fast attribute access.\n\n* IR representations of functions and classes live in\n  `mypyc.ir.func_ir` and `mypyc.ir.class_ir`, respectively.\n\nLook at the docstrings and comments in `mypyc.ir` for additional\ninformation. See the test cases in\n`mypyc/test-data/irbuild-basic.test` for examples of what the IR looks\nlike in a pretty-printed form.\n\n## Testing Overview\n\nMost mypyc test cases are defined in the same format (`.test`) as used\nfor test cases for mypy. Look at mypy developer documentation for a\ngeneral overview of how things work. Test cases live under\n`mypyc/test-data/`, and you can run all mypyc tests via `pytest\n mypyc`. If you don't make changes to code under `mypy/`, it's not\nimportant to regularly run mypy tests during development.\n\nYou can use `python runtests.py mypyc-fast` to run a subset of mypyc\ntests that covers most functionality but runs significantly quicker\nthan the entire test suite.\n\nWhen you create a PR, we have Continuous Integration jobs set up that\ncompile mypy using mypyc and run the mypy test suite using the\ncompiled mypy. This will sometimes catch additional issues not caught\nby the mypyc test suite. It's okay to not do this in your local\ndevelopment environment.\n\nWe discuss writing tests in more detail later in this document.\n\n## Inspecting Generated IR\n\nIt's often useful to look at the generated IR when debugging issues or\nwhen trying to understand how mypyc compiles some code.  When you\ncompile some module by running `mypyc`, mypyc will write the\npretty-printed IR into `build/ops.txt`. This is the final IR that\nincludes the output from exception and reference count handling\ninsertion passes.\n\nWe also have tests that verify the generated IR\n(`mypyc/test-data/irbuild-*.text`).\n\n## Type-checking Mypyc\n\n`./runtests.py self` type checks mypy and mypyc. This is a little slow,\nhowever, since it's using an uncompiled mypy.\n\nInstalling a released version of mypy using `pip` (which is compiled)\nand using `dmypy` (mypy daemon) is a much, much faster way to type\ncheck mypyc during development.\n\n## Value Representation\n\nMypyc uses a tagged pointer representation for values of type `int`\n(`CPyTagged`), `char` for booleans, and C structs for tuples. For most\nother objects mypyc uses the CPython `PyObject *`.\n\nPython integers that fit in 31/63 bits (depending on whether we are on\na 32-bit or 64-bit platform) are represented as C integers\n(`CPyTagged`) shifted left by 1. Integers that don't fit in this\nrepresentation are represented as pointers to a `PyObject *` (this is\nalways a Python `int` object) with the least significant bit\nset. Tagged integer operations are defined in `mypyc/lib-rt/int_ops.c`\nand `mypyc/lib-rt/CPy.h`.\n\nThere are also low-level integer types, such as `int32` (see\n`mypyc.ir.rtypes`), that don't use the tagged representation. These\ntypes are not exposed to users, but they are used in generated code.\n\n## Overview of Generated C\n\nMypyc compiles a function into two functions, a native function and\na wrapper function:\n\n* The native function takes a fixed number of C arguments with the\n  correct C types. It assumes that all argument have correct types.\n\n* The wrapper function conforms to the Python C API calling convention\n  and takes an arbitrary set of arguments. It processes the arguments,\n  checks their types, unboxes values with special representations and\n  calls the native function. The return value from the native function\n  is translated back to a Python object (\"boxing\").\n\nCalls to other compiled functions don't go through the Python module\nnamespace but directly call the target native C function. This makes\ncalls very fast compared to CPython.\n\nThe generated code does runtime checking so that it can assume that\nvalues always have the declared types. Whenever accessing CPython\nvalues which might have unexpected types we need to insert a runtime\ntype check operation. For example, when getting a list item we need to\ninsert a runtime type check (an unbox or a cast operation), since\nPython lists can contain arbitrary objects.\n\nThe generated code uses various helpers defined in\n`mypyc/lib-rt/CPy.h`. The implementations are in various `.c` files\nunder `mypyc/lib-rt`.\n\n## Inspecting Generated C\n\nIt's often useful to inspect the C code generated by mypyc to debug\nissues.  Mypyc stores the generated C code as `build/__native.c`.\nCompiled native functions have the prefix `CPyDef_`, while wrapper\nfunctions used for calling functions from interpreted Python code have\nthe `CPyPy_` prefix.\n\nWhen running a test, the first test failure will copy generated C code\ninto the `.mypyc_test_output` directory. You will see something like\nthis in the test output:\n\n```\n...\n---------------------------- Captured stderr call -----------------------------\n\nGenerated files: /Users/me/src/mypy/.mypyc_test_output (for first failure only)\n\n...\n```\n\nYou can also run pytest with `--mypyc-showc` to display C code on every\ntest failure.\n\n## Other Important Limitations\n\nAll of these limitations will likely be fixed in the future:\n\n* We don't detect stack overflows.\n\n* We don't handle Ctrl-C in compiled code.\n\n## Hints for Implementing Typical Mypyc Features\n\nThis section gives an overview of where to look for and\nwhat to do to implement specific kinds of mypyc features.\n\n### Testing\n\nOur bread-and-butter testing strategy is compiling code with mypyc and\nrunning it. There are downsides to this (kind of slow, tests a huge\nnumber of components at once, insensitive to the particular details of\nthe IR), but there really is no substitute for running code. You can\nalso write tests that test the generated IR, however.\n\n### Tests That Compile and Run Code\n\nTest cases that compile and run code are located in\n`mypyc/test-data/run*.test` and the test runner is in\n`mypyc.test.test_run`.  The code to compile comes after `[case\ntest<name>]`. The code gets saved into the file `native.py`, and it\ngets compiled into the module `native`.\n\nEach test case uses a non-compiled Python driver that imports the\n`native` module and typically calls some compiled functions. Some\ntests also perform assertions and print messages in the driver.\n\nIf you don't provide a driver, a default driver is used. The default\ndriver just calls each module-level function that is prefixed with\n`test_` and reports any uncaught exceptions as failures. (Failure to\nbuild or a segfault also count as failures.) `testStringOps` in\n`mypyc/test-data/run-strings.test` is an example of a test that uses\nthe default driver.\n\nYou should usually use the default driver (don't include\n`driver.py`). It's the simplest way to write most tests.\n\nHere's an example test case that uses the default driver:\n\n```\n[case testConcatenateLists]\ndef test_concat_lists() -> None:\n    assert [1, 2] + [5, 6] == [1, 2, 5, 6]\n\ndef test_concat_empty_lists() -> None:\n    assert [] + [] == []\n```\n\nThere is one test case, `testConcatenateLists`. It has two sub-cases,\n`test_concat_lists` and `test_concat_empty_lists`. Note that you can\nuse the pytest -k argument to only run `testConcetanateLists`, but you\ncan't filter tests at the sub-case level.\n\nIt's recommended to have multiple sub-cases per test case, since each\ntest case has significant fixed overhead. Each test case is run in a\nfresh Python subprocess.\n\nMany of the existing test cases provide a custom driver by having\n`[file driver.py]`, followed by the driver implementation. Here the\ndriver is not compiled, which is useful if you want to test\ninteractions between compiled and non-compiled code. However, many of\nthe tests don't have a good reason to use a custom driver -- when they\nwere written, the default driver wasn't available.\n\nTest cases can also have a `[out]` section, which specifies the\nexpected contents of stdout the test case should produce. New test\ncases should prefer assert statements to `[out]` sections.\n\n### Adding Debug Prints and Editing Generated C\n\nSometimes it's helpful to add some debug prints or other debugging helpers\nto the generated C code. You can run mypyc using `--skip-c-gen` to skip the C\ngeneration step, so all manual changes to C files are preserved. Here is\nan example of how to use the workflow:\n\n* Compile some file you want to debug: `python -m mypyc foo.py`.\n* Add debug prints to the generated C in `build/__native.c`.\n* Run the same compilation command line again, but add `--skip-c-gen`:\n  `python -m mypyc --skip-c-gen foo.py`. This will only rebuild the\n  binaries.\n* Run the compiled code, including your changes: `python -c 'import foo'`.\n  You should now see the output from the debug prints you added.\n\nThis can also be helpful if you want to quickly experiment with different\nimplementation techniques, without having to first figure out how to\nmodify mypyc to generate the desired C code.\n\n### Debugging Segfaults\n\nIf you experience a segfault, it's recommended to use a debugger that supports\nC, such as gdb or lldb, to look into the segfault.\n\nIf a test case segfaults, you can run tests using the debugger, so\nyou can inspect the stack. Example of inspecting the C stack when a\ntest case segfaults (user input after `$` and `(gdb)` prompts):\n\n```\n$ pytest mypyc -n0 -s --mypyc-debug=gdb -k <name-of-test>\n...\n(gdb) r\n...\nProgram received signal SIGSEGV, Segmentation fault.\n...\n(gdb) bt\n#0  0x00005555556ed1a2 in _PyObject_HashFast (op=0x0) at ./Include/object.h:336\n#1  PyDict_GetItemWithError (op=0x7ffff6c894c0, key=0x0) at Objects/dictobject.c:2394\n...\n```\n\nYou must use `-n0 -s` to enable interactive input to the debugger.\nInstead of `gdb`, you can also try `lldb` (especially on macOS).\n\nTo get better C stack tracebacks and more assertions in the Python\nruntime, you can build Python in debug mode and use that to run tests,\nor to manually run the debugger outside the test framework.\n\n**Note:** You may need to build Python yourself on macOS, as official\nPython builds may not have sufficient entitlements to use a debugger.\n\nHere are some hints about building a debug version of CPython that may\nhelp (for Ubuntu, macOS is mostly similar except for installing build\ndependencies):\n\n```\n$ sudo apt install gdb build-essential libncursesw5-dev libssl-dev libgdbm-dev libc6-dev libsqlite3-dev libbz2-dev libffi-dev libgdbm-compat-dev\n$ <download Python tarball and extract it>\n$ cd Python-3.XX.Y\n$ ./configure --with-pydebug\n$ make -s -j16\n$ ./python -m venv ~/<venv-location>  # Use ./python.exe -m venv ... on macOS\n$ source ~/<venv-location>/bin/activate\n$ cd <mypy-repo-dir>\n$ pip install -r test-requirements.txt\n```\n\n### IR Tests\n\nIf the specifics of the generated IR of a change is important\n(because, for example, you want to make sure a particular optimization\nis triggering), you should add a `mypyc.irbuild` test as well.  Test\ncases are located in `mypyc/test-data/irbuild-*.test` and the test\ndriver is in `mypyc.test.test_irbuild`. IR build tests do a direct\ncomparison of the IR output, so try to make the test as targeted as\npossible so as to capture only the important details.  (Some of our\nexisting IR build tests do not follow this advice, unfortunately!)\n\nIf you pass the `--update-data` flag to pytest, it will automatically\nupdate the expected output of any tests to match the actual\noutput. This is very useful for changing or creating IR build tests,\nbut make sure to carefully inspect the diff!\n\nYou may also need to add some definitions to the stubs used for\nbuiltins during tests (`mypyc/test-data/fixtures/ir.py`). We don't use\nfull typeshed stubs to run tests since they would seriously slow down\ntests.\n\n### Benchmarking\n\nMany mypyc improvements attempt to make some operations faster. For\nany such change, you should run some measurements to verify that\nthere actually is a measurable performance impact.\n\nA typical benchmark would initialize some data to be operated on, and\nthen measure time spent in some function. In particular, you should\nnot measure time needed to run the entire benchmark program, as this\nwould include Python startup overhead and other things that aren't\nrelevant. In general, for microbenchmarks, you want to do as little as\npossible in the timed portion. So ideally you'll just have some loops\nand the code under test. Be ready to provide your benchmark in code\nreview so that mypyc developers can check that the benchmark is fine\n(writing a good benchmark is non-trivial).\n\nYou should run a benchmark at least five times, in both original and\nchanged versions, ignore outliers, and report the average\nruntime. Actual performance of a typical desktop or laptop computer is\nquite variable, due to dynamic CPU clock frequency changes, background\nprocesses, etc. If you observe a high variance in timings, you'll need\nto run the benchmark more times. Also try closing most applications,\nincluding web browsers.\n\nInterleave original and changed runs. Don't run 10 runs with variant A\nfollowed by 10 runs with variant B, but run an A run, a B run, an A\nrun, etc. Otherwise you risk that the CPU frequency will be different\nbetween variants. You can also try adding a delay of 5 to 20s between\nruns to avoid CPU frequency changes.\n\nInstead of averaging over many measurements, you can try to adjust\nyour environment to provide more stable measurements. However, this\ncan be hard to do with some hardware, including many laptops.  Victor\nStinner has written a series of blog posts about making measurements\nstable:\n\n* https://vstinner.github.io/journey-to-stable-benchmark-system.html\n* https://vstinner.github.io/journey-to-stable-benchmark-average.html\n\n### Adding C Helpers\n\nIf you add an operation that compiles into a lot of C code, you may\nalso want to add a C helper function for the operation to make the\ngenerated code smaller. Here is how to do this:\n\n* Declare the operation in `mypyc/lib-rt/CPy.h`. We avoid macros, and\n  we generally avoid inline functions to make it easier to target\n  additional backends in the future.\n\n* Consider adding a unit test for your C helper in `mypyc/lib-rt/test_capi.cc`.\n  We use\n  [Google Test](https://github.com/google/googletest) for writing\n  tests in C++. The framework is included in the repository under the\n  directory `googletest/`. The C unit tests are run as part of the\n  pytest test suite (`test_c_unit_test`).\n\n### Adding a Specialized Primitive Operation\n\nMypyc speeds up operations on primitive types such as `list` and `int`\nby having primitive operations specialized for specific types. These\noperations are declared in `mypyc.primitives` (and\n`mypyc/lib-rt/CPy.h`).  For example, `mypyc.primitives.list_ops`\ncontains primitives that target list objects.\n\nThe operation definitions are data driven: you specify the kind of\noperation (such as a call to `builtins.len` or a binary addition) and\nthe operand types (such as `list_primitive`), and what code should be\ngenerated for the operation. Mypyc does AST matching to find the most\nsuitable primitive operation automatically.\n\nLook at the existing primitive definitions and the docstrings in\n`mypyc.primitives.registry` for examples and more information.\n\n### Adding a New Primitive Type\n\nSome types (typically Python Python built-in types), such as `int` and\n`list`, are special cased in mypyc to generate optimized operations\nspecific to these types. We'll occasionally want to add additional\nprimitive types.\n\nHere are some hints about how to add support for a new primitive type\n(this may be incomplete):\n\n* Decide whether the primitive type has an \"unboxed\" representation (a\n  representation that is not just `PyObject *`). For most types we'll\n  use a boxed representation, as it's easier to implement and more\n  closely matches Python semantics.\n\n* Create a new instance of `RPrimitive` to support the primitive type\n  and add it to `mypyc.ir.rtypes`. Make sure all the attributes are\n  set correctly and also define `<foo>_rprimitive` and\n  `is_<foo>_rprimitive`.\n\n* Update `mypyc.irbuild.mapper.Mapper.type_to_rtype()`.\n\n* If the type is not unboxed, update `emit_cast` in `mypyc.codegen.emit`.\n\nIf the type is unboxed, there are some additional steps:\n\n* Update `emit_box` in `mypyc.codegen.emit`.\n\n* Update `emit_unbox` in `mypyc.codegen.emit`.\n\n* Update `emit_inc_ref` and `emit_dec_ref` in `mypypc.codegen.emit`.\n  If the unboxed representation does not need reference counting,\n  these can be no-ops.\n\n* Update `emit_error_check` in `mypyc.codegen.emit`.\n\n* Update `emit_gc_visit` and `emit_gc_clear` in `mypyc.codegen.emit`\n  if the type has an unboxed representation with pointers.\n\nThe above may be enough to allow you to declare variables with the\ntype, pass values around, perform runtime type checks, and use generic\nfallback primitive operations to perform method calls, binary\noperations, and so on. You likely also want to add some faster,\nspecialized primitive operations for the type (see Adding a\nSpecialized Primitive Operation above for how to do this).\n\nAdd a test case to `mypyc/test-data/run*.test` to test compilation and\nrunning compiled code. Ideas for things to test:\n\n* Test using the type as an argument.\n\n* Test using the type as a return value.\n\n* Test passing a value of the type to a function both within\n  compiled code and from regular Python code. Also test this\n  for return values.\n\n* Test using the type as list item type. Test both getting a list item\n  and setting a list item.\n\n### Supporting More Python Syntax\n\nMypyc supports most Python syntax, but there are still some gaps.\n\nSupport for syntactic sugar that doesn't need additional IR operations\ntypically only requires changes to `mypyc.irbuild`.\n\nSome new syntax also needs new IR primitives to be added to\n`mypyc.primitives`. See `mypyc.primitives.registry` for documentation\nabout how to do this.\n\n### Other Hints\n\n* This developer documentation is not aimed to be very complete. Much\n  of our documentation is in comments and docstring in the code. If\n  something is unclear, study the code.\n\n* It can be useful to look through some recent PRs to get an idea of\n  what typical code changes, test cases, etc. look like.\n\n* Feel free to open GitHub issues with questions if you need help when\n  contributing, or ask questions in existing issues. Note that we only\n  support contributors. Mypyc is not (yet) an end-user product. You\n  can also ask questions in our Gitter chat\n  (https://gitter.im/mypyc-dev/community).\n\n## Undocumented Workflows\n\nThese workflows would be useful for mypyc contributors. We should add\nthem to mypyc developer documentation:\n\n* How to inspect the generated IR before some transform passes.\n"
  },
  {
    "path": "mypyc/doc/dict_operations.rst",
    "content": ".. _dict-ops:\n\nNative dict operations\n======================\n\nThese ``dict`` operations have fast, optimized implementations. Other\ndictionary operations use generic implementations that are often slower.\n\nConstruction\n------------\n\nConstruct dict from keys and values:\n\n* ``{key: value,  ...}``\n\nConstruct empty dict:\n\n* ``{}``\n* ``dict()``\n\nConstruct dict from another object:\n\n* ``dict(d: dict)``\n* ``dict(x: Iterable)``\n\nDict comprehensions:\n\n* ``{...: ... for ... in ...}``\n* ``{...: ... for ... in ... if ...}``\n\nOperators\n---------\n\n* ``d[key]``\n* ``value in d``\n\nStatements\n----------\n\n* ``d[key] = value``\n* ``for key in d:``\n\nMethods\n-------\n\n* ``d.get(key)``\n* ``d.get(key, default)``\n* ``d.keys()``\n* ``d.values()``\n* ``d.items()``\n* ``d.copy()``\n* ``d.clear()``\n* ``d.setdefault(key)``\n* ``d.setdefault(key, value)``\n* ``d1.update(d2: dict)``\n* ``d.update(x: Iterable)``\n\nFunctions\n---------\n\n* ``len(d: dict)``\n"
  },
  {
    "path": "mypyc/doc/differences_from_python.rst",
    "content": ".. _differences-from-python:\n\nDifferences from Python\n=======================\n\nMypyc aims to be sufficiently compatible with Python semantics so that\nmigrating code to mypyc often doesn't require major code\nchanges. There are various differences to enable performance gains\nthat you need to be aware of, however.\n\nThis section documents notable differences from Python. We discuss\nmany of them also elsewhere, but it's convenient to have them here in\none place.\n\nRunning compiled modules\n------------------------\n\nYou can't use ``python3 <module>.py`` or ``python3 -m <module>``\nto run compiled modules. Use ``python3 -c \"import <module>\"`` instead,\nor write a wrapper script that imports your module.\n\nAs a side effect, you can't rely on checking the ``__name__`` attribute in compiled\ncode, like this::\n\n    if __name__ == \"__main__\":  # Can't be used in compiled code\n        main()\n\nType errors prevent compilation\n-------------------------------\n\nYou can't compile code that generates mypy type check errors. You can\nsometimes ignore these with a ``# type: ignore`` comment, but this can\nresult in bad code being generated, and it's considered dangerous.\n\n.. note::\n\n    In the future, mypyc may reject ``# type: ignore`` comments that\n    may be unsafe.\n\nRuntime type checking\n---------------------\n\nNon-erased types in annotations will be type checked at runtime. For example,\nconsider this function::\n\n    def twice(x: int) -> int:\n        return x * 2\n\nIf you try to call this function with a ``float`` or ``str`` argument,\nyou'll get a type error on the call site, even if the call site is not\nbeing type checked::\n\n    twice(5)  # OK\n    twice(2.2)  # TypeError\n    twice(\"blah\")  # TypeError\n\nAlso, values with *inferred* types will be type checked. For example,\nconsider a call to the stdlib function ``socket.gethostname()`` in\ncompiled code. This function is not compiled (no stdlib modules are\ncompiled with mypyc), but mypyc uses a *library stub file* to infer\nthe return type as ``str``. Compiled code calling ``gethostname()``\nwill fail with ``TypeError`` if ``gethostname()`` would return an\nincompatible value, such as ``None``::\n\n    import socket\n\n    # Fail if returned value is not a str\n    name = socket.gethostname()\n\nNote that ``gethostname()`` is defined like this in the stub file for\n``socket`` (in typeshed)::\n\n    def gethostname() -> str: ...\n\nThus mypyc verifies that library stub files and annotations in\nnon-compiled code match runtime values. This adds an extra layer of\ntype safety.\n\nCasts such as ``cast(str, x)`` will also result in strict type\nchecks. Consider this example::\n\n    from typing import cast\n    ...\n    x = cast(str, y)\n\nThe last line is essentially equivalent to this Python code when compiled::\n\n    if not isinstance(y, str):\n        raise TypeError(...)\n    x = y\n\nIn interpreted mode ``cast`` does not perform a runtime type check.\n\nNative classes\n--------------\n\nNative classes behave differently from Python classes.  See\n:ref:`native-classes` for the details.\n\nPrimitive types\n---------------\n\nSome primitive types behave differently in compiled code to improve\nperformance.\n\n``int`` objects use an unboxed (non-heap-allocated) representation for small\ninteger values. A side effect of this is that the exact runtime type of\n``int`` values is lost. For example, consider this simple function::\n\n    def first_int(x: list[int]) -> int:\n        return x[0]\n\n    print(first_int([True]))  # Output is 1, instead of True!\n\n``bool`` is a subclass of ``int``, so the above code is\nvalid. However, when the list value is converted to ``int``, ``True``\nis converted to the corresponding ``int`` value, which is ``1``.\n\nNote that integers still have an arbitrary precision in compiled code,\nsimilar to normal Python integers.\n\nFixed-length tuples are unboxed, similar to integers. The exact type\nand identity of fixed-length tuples is not preserved, and you can't\nreliably use ``is`` checks to compare tuples that are used in compiled\ncode.\n\n.. _early-binding:\n\nEarly binding\n-------------\n\nReferences to functions, types, most attributes, and methods in the\nsame :ref:`compilation unit <compilation-units>` use *early binding*:\nthe target of the reference is decided at compile time, whenever\npossible. This contrasts with normal Python behavior of *late\nbinding*, where the target is found by a namespace lookup at\nruntime. Omitting these namespace lookups improves performance, but\nsome Python idioms don't work without changes.\n\nNote that non-final module-level variables still use late binding.\nYou may want to avoid these in very performance-critical code.\n\nExamples of early and late binding::\n\n    from typing import Final\n\n    import lib  # \"lib\" is not compiled\n\n    x = 0\n    y: Final = 1\n\n    def func() -> None:\n        pass\n\n    class Cls:\n        def __init__(self, attr: int) -> None:\n            self.attr = attr\n\n        def method(self) -> None:\n            pass\n\n    def example() -> None:\n        # Early binding:\n        var = y\n        func()\n        o = Cls()\n        o.x\n        o.method()\n\n        # Late binding:\n        var = x  # Module-level variable\n        lib.func()  # Accessing library that is not compiled\n\nPickling and copying objects\n----------------------------\n\nMypyc tries to enforce that instances native classes are properly\ninitialized by calling ``__init__`` implicitly when constructing\nobjects, even if objects are constructed through ``pickle``,\n``copy.copy`` or ``copy.deepcopy``, for example.\n\nIf a native class doesn't support calling ``__init__`` without arguments,\nyou can't pickle or copy instances of the class. Use the\n``mypy_extensions.mypyc_attr`` class decorator to override this behavior\nand enable pickling through the ``serializable`` flag::\n\n    from mypy_extensions import mypyc_attr\n    import pickle\n\n    @mypyc_attr(serializable=True)\n    class Cls:\n        def __init__(self, n: int) -> None:\n            self.n = n\n\n    data = pickle.dumps(Cls(5))\n    obj = pickle.loads(data)  # OK\n\nAdditional notes:\n\n* All subclasses inherit the ``serializable`` flag.\n* If a class has the ``allow_interpreted_subclasses`` attribute, it\n  implicitly supports serialization.\n* Enabling serialization may slow down attribute access, since compiled\n  code has to be always prepared to raise ``AttributeError`` in case an\n  attribute is not defined at runtime.\n* If you try to pickle an object without setting the ``serializable``\n  flag, you'll get a ``TypeError`` about missing arguments to\n  ``__init__``.\n\n\nMonkey patching\n---------------\n\nSince mypyc function and class definitions are immutable, you can't\nperform arbitrary monkey patching, such as replacing functions or\nmethods with mocks in tests.\n\n.. note::\n\n    Each compiled module has a Python namespace that is initialized to\n    point to compiled functions and type objects. This namespace is a\n    regular ``dict`` object, and it *can* be modified. However,\n    compiled code generally doesn't use this namespace, so any changes\n    will only be visible to non-compiled code.\n\nStack overflows\n---------------\n\nCompiled code currently doesn't check for stack overflows. Your\nprogram may crash in an unrecoverable fashion if you have too many\nnested function calls, typically due to out-of-control recursion.\n\n.. note::\n\n   This limitation will be fixed in the future.\n\nFinal values\n------------\n\nCompiled code replaces a reference to an attribute declared ``Final`` with\nthe value of the attribute computed at compile time. This is an example of\n:ref:`early binding <early-binding>`. Example::\n\n    MAX: Final = 100\n\n    def limit_to_max(x: int) -> int:\n         if x > MAX:\n             return MAX\n         return x\n\nThe two references to ``MAX`` don't involve any module namespace lookups,\nand are equivalent to this code::\n\n    def limit_to_max(x: int) -> int:\n         if x > 100:\n             return 100\n         return x\n\nWhen run as interpreted, the first example will execute slower due to\nthe extra namespace lookups. In interpreted code final attributes can\nalso be modified.\n\nUnsupported features\n--------------------\n\nSome Python features are not supported by mypyc (yet). They can't be\nused in compiled code, or there are some limitations. You can\npartially work around some of these limitations by running your code\nin interpreted mode.\n\nNested classes\n**************\n\nNested classes are not supported.\n\nConditional functions or classes\n********************************\n\nFunction and class definitions guarded by an if-statement are not supported.\n\nDunder methods\n**************\n\nNative classes **cannot** use these dunders. If defined, they will not\nwork as expected.\n\n* ``__del__``\n* ``__index__``\n* ``__getattr__``, ``__getattribute__``\n* ``__setattr__``\n* ``__delattr__``\n\nGenerator expressions\n*********************\n\nGenerator expressions are not supported. To make it easier to compile\nexisting code, they are implicitly replaced with list comprehensions.\n*This does not always produce the same behavior.*\n\nTo work around this limitation, you can usually use a generator\nfunction instead.  You can sometimes replace the generator expression\nwith an explicit list comprehension.\n\nDescriptors\n***********\n\nNative classes can't contain arbitrary descriptors. Properties, static\nmethods and class methods are supported.\n\nIntrospection\n*************\n\nVarious methods of introspection may break by using mypyc. Here's an\nnon-exhaustive list of what won't work:\n\n- Instance ``__annotations__`` is usually not kept\n- Frames of compiled functions can't be inspected using ``inspect``\n- Compiled methods aren't considered methods by ``inspect.ismethod``\n- ``inspect.signature`` chokes on compiled functions with default arguments that\n  are not simple literals\n- ``inspect.iscoroutinefunction`` and ``asyncio.iscoroutinefunction`` will always return False for compiled functions, even those defined with `async def`\n\nProfiling hooks and tracing\n***************************\n\nCompiled functions don't trigger profiling and tracing hooks, such as\nwhen using the ``profile``, ``cProfile``, or ``trace`` modules.\n\nDebuggers\n*********\n\nYou can't set breakpoints in compiled functions or step through\ncompiled functions using ``pdb``. Often you can debug your code in\ninterpreted mode instead.\n"
  },
  {
    "path": "mypyc/doc/float_operations.rst",
    "content": ".. _float-ops:\n\nNative float operations\n========================\n\nThese ``float`` operations have fast, optimized implementations. Other\nfloating point operations use generic implementations that are often\nslower.\n\nConstruction\n------------\n\n* Float literal\n* ``float(x: int)``\n* ``float(x: i64)``\n* ``float(x: i32)``\n* ``float(x: i16)``\n* ``float(x: u8)``\n* ``float(x: str)``\n* ``float(x: float)`` (no-op)\n\nOperators\n---------\n\n* Arithmetic (``+``, ``-``, ``*``, ``/``, ``//``, ``%``)\n* Comparisons (``==``, ``!=``, ``<``, etc.)\n* Augmented assignment (``x += y``, etc.)\n\nFunctions\n---------\n\n* ``int(f)``\n* ``i64(f)`` (convert to 64-bit signed integer)\n* ``i32(f)`` (convert to 32-bit signed integer)\n* ``i16(f)`` (convert to 16-bit signed integer)\n* ``u8(f)`` (convert to 8-bit unsigned integer)\n* ``abs(f)``\n* ``math.sin(f)``\n* ``math.cos(f)``\n* ``math.tan(f)``\n* ``math.sqrt(f)``\n* ``math.exp(f)``\n* ``math.log(f)``\n* ``math.floor(f)``\n* ``math.ceil(f)``\n* ``math.fabs(f)``\n* ``math.pow(x, y)``\n* ``math.copysign(x, y)``\n* ``math.isinf(f)``\n* ``math.isnan(f)``\n"
  },
  {
    "path": "mypyc/doc/frozenset_operations.rst",
    "content": ".. _frozenset-ops:\n\nNative frozenset operations\n===========================\n\nThese ``frozenset`` operations have fast, optimized implementations. Other\nfrozenset operations use generic implementations that are often slower.\n\nConstruction\n------------\n\nConstruct empty frozenset:\n\n* ``frozenset()``\n\nConstruct frozenset from iterable:\n\n* ``frozenset(x: Iterable)``\n\n\nOperators\n---------\n\n* ``item in s``\n\nFunctions\n---------\n\n* ``len(s: set)``\n"
  },
  {
    "path": "mypyc/doc/future.md",
    "content": "# Future\n\nThis document introduces some ideas for future improvements.\n\n## Basic Optimizations\n\nImplement basic optimizations such as common subexpression elimination and\nloop invariant code motion.\n\nImportantly, common subexpression elimination could be used to avoid\nredundant type checks.\n\n## Operation-specific Optimizations\n\nSome operations or combinations of successive operations can be\nreplaced with more efficient operations. Examples:\n\n* If `s` is a string, `s[i] == 'x'` doesn't need to construct the\n  intermediate single-character string object `s[i]` but just compare\n  the character value to `ord('x')`.\n\n* `a + ':' + b` (two string concetenations) can be implemented as\n  single three-operand concatenation that doesn't construct an\n  intermediate object.\n\n* `x in {1, 3}` can be translated into `x == 1 or x == 3` (more\n  generally we need to evaluate all right-hand-side items).\n\n## Integer Range Analysis\n\nImplement integer range analysis. This can be used in various ways:\n\n* Use untagged representations for some registers.\n* Use faster integer arithmetic operations for operations that\n  only deal with short integers or that can't overflow.\n* Remove redundant list and string index checks.\n\n## Always Defined Attributes\n\nSomehow make it possible to enforce that attributes in a class are always\ndefined. This makes attribute access faster since we don't need to explicitly\ncheck if the attribute is defined.\n"
  },
  {
    "path": "mypyc/doc/getting_started.rst",
    "content": "Getting started\n===============\n\nHere you will learn some basic things you need to know to get started with mypyc.\n\nPrerequisites\n-------------\n\nYou need a Python C extension development environment. The way to set this up\ndepends on your operating system.\n\nmacOS\n*****\n\nInstall Xcode command line tools:\n\n.. code-block::\n\n    $ xcode-select --install\n\nLinux\n*****\n\nYou need a C compiler and CPython headers and libraries. The specifics\nof how to install these varies by distribution. Here are instructions for\nUbuntu 18.04, for example:\n\n.. code-block::\n\n    $ sudo apt install python3-dev\n\nWindows\n*******\n\nFrom `Build Tools for Visual Studio 2022 <https://www.visualstudio.com/downloads/#build-tools-for-visual-studio-2022>`_, install MSVC C++ build tools for your architecture and a Windows SDK. (latest versions recommended)\n\nInstallation\n------------\n\nMypyc is shipped as part of the mypy distribution. Install mypy like\nthis (you need Python 3.10 or later):\n\n.. code-block::\n\n    $ python3 -m pip install -U 'mypy[mypyc]'\n\nOn some systems you need to use this instead:\n\n.. code-block::\n\n    $ python -m pip install -U 'mypy[mypyc]'\n\nExample program\n---------------\n\nLet's start with a classic micro-benchmark, recursive fibonacci. Save\nthis file as ``fib.py``:\n\n.. code-block:: python\n\n   import time\n\n   def fib(n: int) -> int:\n       if n <= 1:\n           return n\n       else:\n           return fib(n - 2) + fib(n - 1)\n\n   t0 = time.time()\n   fib(32)\n   print(time.time() - t0)\n\nNote that we gave the ``fib`` function a type annotation. Without it,\nperformance won't be as impressive after compilation.\n\n.. note::\n\n   `Mypy documentation\n   <https://mypy.readthedocs.io/en/stable/index.html>`_ is a good\n   introduction if you are new to type annotations or mypy. Mypyc uses\n   mypy to perform type checking and type inference, so some familiarity\n   with mypy is very useful.\n\nCompiling and running\n---------------------\n\nWe can run ``fib.py`` as a regular, interpreted program using CPython:\n\n.. code-block:: console\n\n    $ python3 fib.py\n    0.4125328063964844\n\nIt took about 0.41s to run on my computer.\n\nRun ``mypyc`` to compile the program to a binary C extension:\n\n.. code-block:: console\n\n    $ mypyc fib.py\n\nThis will generate a C extension for ``fib`` in the current working\ndirectory.  For example, on a Linux system the generated file may be\ncalled ``fib.cpython-37m-x86_64-linux-gnu.so``.\n\nSince C extensions can't be run as programs, use ``python3 -c`` to run\nthe compiled module as a program:\n\n.. code-block:: console\n\n    $ python3 -c \"import fib\"\n    0.04097270965576172\n\nAfter compilation, the program is about 10x faster. Nice!\n\n.. note::\n\n   ``__name__`` in ``fib.py`` would now be ``\"fib\"``, not ``\"__main__\"``.\n\nYou can also pass most\n`mypy command line options <https://mypy.readthedocs.io/en/stable/command_line.html>`_\nto ``mypyc``.\n\nDeleting compiled binary\n------------------------\n\nYou can manually delete the C extension to get back to an interpreted\nversion (this example works on Linux):\n\n.. code-block::\n\n    $ rm fib.*.so\n\nUsing setup.py\n--------------\n\nYou can also use ``setup.py`` to compile modules using mypyc. Here is an\nexample ``setup.py`` file::\n\n    from setuptools import setup\n\n    from mypyc.build import mypycify\n\n    setup(\n        name='mylib',\n        packages=['mylib'],\n        ext_modules=mypycify([\n            'mylib/__init__.py',\n            'mylib/mod.py',\n        ]),\n    )\n\nWe used ``mypycify(...)`` to specify which files to compile using\nmypyc.  Your ``setup.py`` can include additional Python files outside\n``mypycify(...)`` that won't be compiled.\n\nNow you can build a wheel (.whl) file for the package::\n\n    python3 setup.py bdist_wheel\n\nThe wheel is created under ``dist/``.\n\nYou can also compile the C extensions in-place, in the current directory (similar\nto using ``mypyc`` to compile modules)::\n\n    python3 setup.py build_ext --inplace\n\nYou can include most `mypy command line options\n<https://mypy.readthedocs.io/en/stable/command_line.html>`_ in the\nlist of arguments passed to ``mypycify()``. For example, here we use\nthe ``--disallow-untyped-defs`` flag to require that all functions\nhave type annotations::\n\n    ...\n    setup(\n        name='frobnicate',\n        packages=['frobnicate'],\n        ext_modules=mypycify([\n            '--disallow-untyped-defs',  # Pass a mypy flag\n            'frobnicate.py',\n        ]),\n    )\n\n.. note:\n\n   You may be tempted to use `--check-untyped-defs\n   <https://mypy.readthedocs.io/en/stable/command_line.html#cmdoption-mypy-check-untyped-defs>`_\n   to type check functions without type annotations. Note that this\n   may reduce performance, due to many transitions between type-checked and unchecked\n   code.\n\nRecommended workflow\n--------------------\n\nA simple way to use mypyc is to always compile your code after any\ncode changes, but this can get tedious, especially if you have a lot\nof code. Instead, you can do most development in interpreted mode.\nThis development workflow has worked smoothly for developing mypy and\nmypyc (often we forget that we aren't working on a vanilla Python\nproject):\n\n1. During development, use interpreted mode. This gives you a fast\n   edit-run cycle.\n\n2. Use type annotations liberally and use mypy to type check your code\n   during development. Mypy and tests can find most errors that would\n   break your compiled code, if you have good type annotation\n   coverage. (Running mypy is pretty quick.)\n\n3. After you've implemented a feature or a fix, compile your project\n   and run tests again, now in compiled mode. Usually nothing will\n   break here, assuming your type annotation coverage is good. This\n   can happen locally or in a Continuous Integration (CI) job. If you\n   have CI, compiling locally may be rarely needed.\n\n4. Release or deploy a compiled version. Optionally, include a\n   fallback interpreted version for platforms that mypyc doesn't\n   support.\n\nThis mypyc workflow only involves minor tweaks to a typical Python\nworkflow. Most of development, testing and debugging happens in\ninterpreted mode. Incremental mypy runs, especially when using the\nmypy daemon, are very quick (often a few hundred milliseconds).\n\nNext steps\n----------\n\nYou can sometimes get good results by just annotating your code and\ncompiling it. If this isn't providing meaningful performance gains, if\nyou have trouble getting your code to work under mypyc, or if you want\nto optimize your code for maximum performance, you should read the\nrest of the documentation in some detail.\n\nHere are some specific recommendations, or you can just read the\ndocumentation in order:\n\n* :ref:`using-type-annotations`\n* :ref:`native-classes`\n* :ref:`differences-from-python`\n* :ref:`performance-tips`\n"
  },
  {
    "path": "mypyc/doc/index.rst",
    "content": ".. mypyc documentation master file, created by\n   sphinx-quickstart on Sun Apr  5 14:01:55 2020.\n   You can adapt this file completely to your liking, but it should at least\n   contain the root `toctree` directive.\n\nWelcome to mypyc documentation!\n===============================\n\nMypyc compiles Python modules to C extensions. It uses standard Python\n`type hints\n<https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html>`_ to\ngenerate fast code.\n\n.. toctree::\n   :maxdepth: 2\n   :caption: First steps\n\n   introduction\n   getting_started\n\n.. toctree::\n   :maxdepth: 2\n   :caption: Using mypyc\n\n   using_type_annotations\n   native_classes\n   differences_from_python\n   compilation_units\n\n.. toctree::\n   :maxdepth: 2\n   :caption: Native operations reference\n\n   native_operations\n   int_operations\n   bool_operations\n   float_operations\n   str_operations\n   bytes_operations\n   bytearray_operations\n   list_operations\n   dict_operations\n   set_operations\n   tuple_operations\n   frozenset_operations\n\n.. toctree::\n   :maxdepth: 2\n   :caption: Advanced topics\n\n   performance_tips_and_tricks\n\n.. toctree::\n   :hidden:\n   :caption: Project Links\n\n   GitHub <https://github.com/python/mypy>\n\nIndices and tables\n==================\n\n* :ref:`genindex`\n* :ref:`modindex`\n* :ref:`search`\n"
  },
  {
    "path": "mypyc/doc/int_operations.rst",
    "content": ".. _int-ops:\n\nNative integer operations\n=========================\n\nMypyc supports these integer types:\n\n* ``int`` (arbitrary-precision integer)\n* ``i64`` (64-bit signed integer)\n* ``i32`` (32-bit signed integer)\n* ``i16`` (16-bit signed integer)\n* ``u8`` (8-bit unsigned integer)\n\n``i64``, ``i32``, ``i16`` and ``u8`` are *native integer types* and\nare available in the ``mypy_extensions`` module. ``int`` corresponds\nto the Python ``int`` type, but uses a more efficient runtime\nrepresentation (tagged pointer). Native integer types are value types.\n\nAll integer types have optimized primitive operations, but the native\ninteger types are more efficient than ``int``, since they don't\nrequire range or bounds checks.\n\nOperations on integers that are listed here have fast, optimized\nimplementations. Other integer operations use generic implementations\nthat are generally slower. Some operations involving integers and other\ntypes, such as list indexing, are documented elsewhere.\n\nConstruction\n------------\n\n``int`` type:\n\n* Integer literal\n* ``int(x: float)``\n* ``int(x: i64)``\n* ``int(x: i32)``\n* ``int(x: i16)``\n* ``int(x: u8)``\n* ``int(x: str)``\n* ``int(x: str, base: int)``\n* ``int(x: int)`` (no-op)\n\n``i64`` type:\n\n* ``i64(x: int)``\n* ``i64(x: float)``\n* ``i64(x: i64)`` (no-op)\n* ``i64(x: i32)``\n* ``i64(x: i16)``\n* ``i64(x: u8)``\n* ``i64(x: str)``\n* ``i64(x: str, base: int)``\n\n``i32`` type:\n\n* ``i32(x: int)``\n* ``i32(x: float)``\n* ``i32(x: i64)`` (truncate)\n* ``i32(x: i32)`` (no-op)\n* ``i32(x: i16)``\n* ``i32(x: u8)``\n* ``i32(x: str)``\n* ``i32(x: str, base: int)``\n\n``i16`` type:\n\n* ``i16(x: int)``\n* ``i16(x: float)``\n* ``i16(x: i64)`` (truncate)\n* ``i16(x: i32)`` (truncate)\n* ``i16(x: i16)`` (no-op)\n* ``i16(x: u8)``\n* ``i16(x: str)``\n* ``i16(x: str, base: int)``\n\nConversions from ``int`` to a native integer type raise\n``OverflowError`` if the value is too large or small. Conversions from\na wider native integer type to a narrower one truncate the value and never\nfail. More generally, operations between native integer types don't\ncheck for overflow.\n\nImplicit conversions\n--------------------\n\n``int`` values can be implicitly converted to a native integer type,\nfor convenience. This means that these are equivalent::\n\n   from mypy_extensions import i64\n\n   def implicit() -> None:\n       # Implicit conversion of 0 (int) to i64\n       x: i64 = 0\n\n   def explicit() -> None:\n       # Explicit conversion of 0 (int) to i64\n       x = i64(0)\n\nSimilarly, a native integer value can be implicitly converted to an\narbitrary-precision integer. These two functions are equivalent::\n\n   def implicit(x: i64) -> int:\n       # Implicit conversion from i64 to int\n       return x\n\n   def explicit(x: i64) -> int:\n       # Explicit conversion from i64 to int\n       return int(x)\n\nOperators\n---------\n\n* Arithmetic (``+``, ``-``, ``*``, ``//``, ``/``, ``%``)\n* Bitwise operations (``&``, ``|``, ``^``, ``<<``, ``>>``, ``~``)\n* Comparisons (``==``, ``!=``, ``<``, etc.)\n* Augmented assignment (``x += y``, etc.)\n\nIf one of the above native integer operations overflows or underflows\nwith signed operands, the behavior is undefined. Signed native integer\ntypes should only be used if all possible values are small enough for\nthe type. For this reason, the arbitrary-precision ``int`` type is\nrecommended for signed values unless the performance of integer\noperations is critical.\n\nOperations on unsigned integers (``u8``) wrap around on overflow.\n\nIt's a compile-time error to mix different native integer types in a\nbinary operation such as addition. An explicit conversion is required::\n\n    from mypy_extensions import i64, i32\n\n    def add(x: i64, y: i32) -> None:\n        a = x + y  # Error (i64 + i32)\n        b = x + i64(y)  # OK\n\nYou can freely mix a native integer value and an arbitrary-precision\n``int`` value in an operation. The native integer type is \"sticky\"\nand the ``int`` operand is coerced to the native integer type::\n\n  def example(x: i64, y: int) -> None:\n      a = x * y\n      # Type of \"a\" is \"i64\"\n      ...\n      b = 1 - x\n      # Similarly, type of \"b\" is \"i64\"\n\nMethods\n-------\n\n* ``n.bit_length()``\n* ``n.to_bytes(length: int, byteorder: str)``\n* ``n.to_bytes(length: int, byteorder: str, signed: bool)``\n\nStatements\n----------\n\nFor loop over a range is compiled efficiently, if the ``range(...)`` object\nis constructed in the for statement (after ``in``):\n\n* ``for x in range(end)``\n* ``for x in range(start, end)``\n* ``for x in range(start, end, step)``\n\nIf one of the arguments to ``range`` in a for loop is a native integer\ntype, the type of the loop variable is inferred to have this native\ninteger type, instead of ``int``::\n\n  for x in range(i64(n)):\n      # Type of \"x\" is \"i64\"\n      ...\n"
  },
  {
    "path": "mypyc/doc/introduction.rst",
    "content": "Introduction\n============\n\nMypyc compiles Python modules to C extensions. It uses standard Python\n`type hints\n<https://mypy.readthedocs.io/en/stable/cheat_sheet_py3.html>`_ to\ngenerate fast code.\n\nThe compiled language is a strict, *gradually typed* Python variant. It\nrestricts the use of some dynamic Python features to gain performance,\nbut it's mostly compatible with standard Python.\n\nMypyc uses `mypy <https://www.mypy-lang.org/>`_ to perform type\nchecking and type inference. Most type system features in the stdlib\n`typing <https://docs.python.org/3/library/typing.html>`_ module are\nsupported.\n\nCompiled modules can import arbitrary Python modules and third-party\nlibraries. You can compile anything from a single performance-critical\nmodule to your entire codebase. You can run the modules you compile\nalso as normal, interpreted Python modules.\n\nExisting code with type annotations is often **1.5x to 5x** faster\nwhen compiled. Code tuned for mypyc can be **5x to 10x** faster.\n\nMypyc currently aims to speed up non-numeric code, such as server\napplications. Mypyc is also used to compile itself (and mypy).\n\nWhy mypyc?\n----------\n\n**Easy to get started.** Compiled code has the look and feel of\nregular Python code. Mypyc supports familiar Python syntax and idioms.\n\n**Expressive types.** Mypyc fully supports standard Python type hints.\nMypyc has local type inference, generics, optional types, tuple types,\nunion types, and more. Type hints act as machine-checked\ndocumentation, making code not only faster but also easier to\nunderstand and modify.\n\n**Python ecosystem.** Mypyc runs on top of CPython, the\nstandard Python implementation. You can use any third-party libraries,\nincluding C extensions, installed with pip. Mypyc uses only valid Python\nsyntax, so all Python editors and IDEs work perfectly.\n\n**Fast program startup.** Mypyc uses ahead-of-time compilation, so\ncompilation does not slow down program startup. Slow program startup\nis a common issue with JIT compilers.\n\n**Migration path for existing code.** Existing Python code often\nrequires only minor changes to compile using mypyc.\n\n**Waiting for compilation is optional.** Compiled code also runs as\nnormal Python code. You can use interpreted Python during development,\nwith familiar and fast workflows.\n\n**Runtime type safety.** Mypyc protects you from segfaults and memory\ncorruption. Any unexpected runtime type safety violation is a bug in\nmypyc. Runtime values are checked against type annotations. (Without\nmypyc, type annotations are ignored at runtime.)\n\n**Find errors statically.** Mypyc uses mypy for static type checking\nthat helps catch many bugs.\n\nUse cases\n---------\n\n**Fix only performance bottlenecks.** Often most time is spent in a few\nPython modules or functions. Add type annotations and compile these\nmodules for easy performance gains.\n\n**Compile it all.** During development you can use interpreted mode,\nfor a quick edit-run cycle. In releases all non-test code is compiled.\nThis is how mypy achieved a 4x performance improvement over interpreted\nPython.\n\n**Take advantage of existing type hints.** If you already use type\nannotations in your code, adopting mypyc will be easier. You've already\ndone most of the work needed to use mypyc.\n\n**Alternative to a lower-level language.** Instead of writing\nperformance-critical code in C, C++, Cython or Rust, you may get good\nperformance while staying in the comfort of Python.\n\n**Migrate C extensions.** Maintaining C extensions is not always fun\nfor a Python developer. With mypyc you may get performance similar to\nthe original C, with the convenience of Python.\n\nDifferences from Cython\n-----------------------\n\nMypyc targets many similar use cases as Cython. Mypyc does many things\ndifferently, however:\n\n* No need to use non-standard syntax, such as ``cpdef``, or extra\n  decorators to get good performance. Clean, normal-looking\n  type-annotated Python code can be fast without language extensions.\n  This makes it practical to compile entire codebases without a\n  developer productivity hit.\n\n* Mypyc has first-class support for features in the ``typing`` module,\n  such as tuple types, union types and generics.\n\n* Mypyc has powerful type inference, provided by mypy. Variable type\n  annotations are not needed for optimal performance.\n\n* Mypyc fully integrates with mypy for robust and seamless static type\n  checking.\n\n* Mypyc performs strict enforcement of type annotations at runtime,\n  resulting in better runtime type safety and easier debugging.\n\nUnlike Cython, mypyc doesn't directly support interfacing with C libraries\nor speeding up numeric code.\n\nHow does it work\n----------------\n\nMypyc uses several techniques to produce fast code:\n\n* Mypyc uses *ahead-of-time compilation* to native code. This removes\n  CPython interpreter overhead.\n\n* Mypyc enforces type annotations (and type comments) at runtime,\n  raising ``TypeError`` if runtime values don't match annotations.\n  Value types only need to be checked in the boundaries between\n  dynamic and static typing.\n\n* Compiled code uses optimized, type-specific primitives.\n\n* Mypyc uses *early binding* to resolve called functions and name\n  references at compile time. Mypyc avoids many dynamic namespace\n  lookups.\n\n* Classes are compiled to *C extension classes*. They use `vtables\n  <https://en.wikipedia.org/wiki/Virtual_method_table>`_ for fast\n  method calls and attribute access.\n\n* Mypyc treats compiled functions, classes, and attributes declared\n  ``Final`` as immutable.\n\n* Mypyc has memory-efficient, unboxed representations for integers and\n  booleans.\n\nDevelopment status\n------------------\n\nMypyc is currently alpha software. It's only recommended for\nproduction use cases with careful testing, and if you are willing to\ncontribute fixes or to work around issues you will encounter.\n"
  },
  {
    "path": "mypyc/doc/list_operations.rst",
    "content": ".. _list-ops:\n\nNative list operations\n======================\n\nThese ``list`` operations have fast, optimized implementations. Other\nlist operations use generic implementations that are often slower.\n\nConstruction\n------------\n\nConstruct list with specific items:\n\n* ``[item0, ..., itemN]``\n\nConstruct empty list:\n\n* ``[]``\n* ``list()``\n\nConstruct list from iterable:\n\n* ``list(x: Iterable)``\n\nList comprehensions:\n\n* ``[... for ... in ...]``\n* ``[... for ... in ... if ...]``\n\nOperators\n---------\n\n* ``lst[n]`` (get item by integer index)\n* ``lst[n:m]``, ``lst[n:]``, ``lst[:m]``, ``lst[:]`` (slicing)\n* ``lst1 + lst2``, ``lst += iter``\n* ``lst * n``, ``n * lst``, ``lst *= n``\n* ``obj in lst``\n\nStatements\n----------\n\nSet item by integer index:\n\n* ``lst[n] = x``\n\nFor loop over a list:\n\n* ``for item in lst:``\n\nMethods\n-------\n\n* ``lst.append(obj)``\n* ``lst.extend(x: Iterable)``\n* ``lst.insert(index, obj)``\n* ``lst.pop(index=-1)``\n* ``lst.remove(obj)``\n* ``lst.count(obj)``\n* ``lst.index(obj)``\n* ``lst.reverse()``\n* ``lst.sort()``\n\nFunctions\n---------\n\n* ``len(lst: list)``\n"
  },
  {
    "path": "mypyc/doc/make.bat",
    "content": "@ECHO OFF\r\n\r\npushd %~dp0\r\n\r\nREM Command file for Sphinx documentation\r\n\r\nif \"%SPHINXBUILD%\" == \"\" (\r\n\tset SPHINXBUILD=sphinx-build\r\n)\r\nset SOURCEDIR=.\r\nset BUILDDIR=_build\r\n\r\nif \"%1\" == \"\" goto help\r\n\r\n%SPHINXBUILD% >NUL 2>NUL\r\nif errorlevel 9009 (\r\n\techo.\r\n\techo.The 'sphinx-build' command was not found. Make sure you have Sphinx\r\n\techo.installed, then set the SPHINXBUILD environment variable to point\r\n\techo.to the full path of the 'sphinx-build' executable. Alternatively you\r\n\techo.may add the Sphinx directory to PATH.\r\n\techo.\r\n\techo.If you don't have Sphinx installed, grab it from\r\n\techo.https://www.sphinx-doc.org/\r\n\texit /b 1\r\n)\r\n\r\n%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%\r\ngoto end\r\n\r\n:help\r\n%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%\r\n\r\n:end\r\npopd\r\n"
  },
  {
    "path": "mypyc/doc/native_classes.rst",
    "content": ".. _native-classes:\n\nNative classes\n==============\n\nClasses in compiled modules are *native classes* by default (some\nexceptions are discussed below). Native classes are compiled to C\nextension classes, which have some important differences from normal\nPython classes. Native classes are similar in many ways to built-in\ntypes, such as ``int``, ``str``, and ``list``.\n\nImmutable namespaces\n--------------------\n\nThe type object namespace of native classes is mostly immutable (but\nclass variables can be assigned to)::\n\n    class Cls:\n        def method1(self) -> None:\n            print(\"method1\")\n\n        def method2(self) -> None:\n            print(\"method2\")\n\n    Cls.method1 = Cls.method2  # Error\n    Cls.new_method = Cls.method2  # Error\n\nOnly attributes defined within a class definition (or in a base class)\ncan be assigned to (similar to using ``__slots__``)::\n\n    class Cls:\n        x: int\n\n        def __init__(self, y: int) -> None:\n            self.x = 0\n            self.y = y\n\n        def method(self) -> None:\n            self.z = \"x\"\n\n    o = Cls(0)\n    print(o.x, o.y)  # OK\n    o.z = \"y\"  # OK\n    o.extra = 3  # Error: no attribute \"extra\"\n\n.. _inheritance:\n\nInheritance\n-----------\n\nOnly single inheritance is supported from native classes (except for\n:ref:`traits <trait-types>`). Most non-native extension classes can't\nbe used as base classes, but regular Python classes can be used as\nbase classes unless they use unsupported metaclasses (see below for\nmore about this).\n\nThese non-native extension classes can be used as base classes of native\nclasses:\n\n* ``object``\n* ``dict`` (and ``dict[k, v]``)\n* ``BaseException``\n* ``Exception``\n* ``ValueError``\n* ``IndexError``\n* ``LookupError``\n* ``UserWarning``\n\nBy default, a non-native class can't inherit a native class, and you\ncan't inherit from a native class outside the compilation unit that\ndefines the class. You can enable these through\n``mypy_extensions.mypyc_attr``::\n\n    from mypy_extensions import mypyc_attr\n\n    @mypyc_attr(allow_interpreted_subclasses=True)\n    class Cls:\n        ...\n\nAllowing interpreted subclasses has only minor impact on performance\nof instances of the native class.  Accessing methods and attributes of\na *non-native* subclass (or a subclass defined in another compilation\nunit) will be slower, since it needs to use the normal Python\nattribute access mechanism.\n\nYou need to install ``mypy-extensions`` to use ``@mypyc_attr``:\n\n.. code-block:: text\n\n    pip install --upgrade mypy-extensions\n\nAdditionally, mypyc recognizes these base classes as special, and\nunderstands how they alter the behavior of classes (including native\nclasses) that subclass them:\n\n* ``typing.NamedTuple``\n* ``typing.Generic``\n* ``typing.Protocol``\n* ``enum.Enum``\n\nClass variables\n---------------\n\nClass variables must be explicitly declared using ``attr: ClassVar``\nor ``attr: ClassVar[<type>]``. You can't assign to a class variable\nthrough an instance. Example::\n\n    from typing import ClassVar\n\n    class Cls:\n        cv: ClassVar = 0\n\n    Cls.cv = 2  # OK\n    o = Cls()\n    print(o.cv)  # OK (2)\n    o.cv = 3  # Error!\n\n.. tip::\n\n    Constant class variables can be declared using ``typing.Final`` or\n    ``typing.Final[<type>]``.\n\nGeneric native classes\n----------------------\n\nNative classes can be generic. Type variables are *erased* at runtime,\nand instances don't keep track of type variable values.\n\nCompiled code thus can't check the values of type variables when\nperforming runtime type checks. These checks are delayed to when\nreading a value with a type variable type::\n\n    from typing import TypeVar, Generic, cast\n\n    T = TypeVar('T')\n\n    class Box(Generic[T]):\n        def __init__(self, item: T) -> None:\n            self.item = item\n\n    x = Box(1)  # Box[int]\n    y = cast(Box[str], x)  # OK (type variable value not checked)\n    y.item  # Runtime error: item is \"int\", but \"str\" expected\n\nMetaclasses\n-----------\n\nMost metaclasses aren't supported with native classes, since their\nbehavior is too dynamic. You can use these metaclasses, however:\n\n* ``abc.ABCMeta``\n* ``typing.GenericMeta`` (used by ``typing.Generic``)\n\n.. note::\n\n   If a class definition uses an unsupported metaclass, *mypyc\n   compiles the class into a regular Python class* (non-native\n   class).\n\nClass decorators\n----------------\n\nSimilar to metaclasses, most class decorators aren't supported with\nnative classes, as they are usually too dynamic. These class\ndecorators can be used with native classes, however:\n\n* ``mypy_extensions.trait`` (for defining :ref:`trait types <trait-types>`)\n* ``mypy_extensions.mypyc_attr`` (see :ref:`above <inheritance>`)\n* ``dataclasses.dataclass``\n* ``@attr.s(auto_attribs=True)``\n\nDataclasses and attrs classes have partial native support, and they aren't as\nefficient as pure native classes.\n\n.. note::\n\n   If a class definition uses an unsupported class decorator, *mypyc\n   compiles the class into a regular Python class* (non-native class).\n\nDefining non-native classes\n---------------------------\n\nYou can use the ``@mypy_extensions.mypyc_attr(...)`` class decorator\nwith an argument ``native_class=False`` to explicitly define normal\nPython classes (non-native classes)::\n\n    from mypy_extensions import mypyc_attr\n\n    @mypyc_attr(native_class=False)\n    class NonNative:\n        def __init__(self) -> None:\n            self.attr = 1\n\n    setattr(NonNative, \"extra\", 1)  # Ok\n\nThis only has an effect in classes compiled using mypyc. Non-native\nclasses are significantly less efficient than native classes, but they\nare sometimes necessary to work around the limitations of native classes.\n\nNon-native classes can use arbitrary metaclasses and class decorators,\nand they support flexible multiple inheritance.  Mypyc will still\ngenerate a compile-time error if you try to assign to a method, or an\nattribute that is not defined in a class body, since these are static\ntype errors detected by mypy::\n\n    o = NonNative()\n    o.extra = \"x\"  # Static type error: \"extra\" not defined\n\nHowever, these operations still work at runtime, including in modules\nthat are not compiled using mypyc. You can also use ``setattr`` and\n``getattr`` for dynamic access of arbitrary attributes. Expressions\nwith an ``Any`` type are also not type checked statically, allowing\naccess to arbitrary attributes::\n\n    a: Any = o\n    a.extra = \"x\"  # Ok\n\n    setattr(o, \"extra\", \"y\")  # Also ok\n\nImplicit non-native classes\n---------------------------\n\nIf a compiled class uses an unsupported metaclass or an unsupported\nclass decorator, it will implicitly be a non-native class, as\ndiscussed above. You can still use ``@mypyc_attr(native_class=False)``\nto explicitly mark it as a non-native class.\n\nExplicit native classes\n-----------------------\n\nYou can use ``@mypyc_attr(native_class=True)`` to explicitly declare a\nclass as a native class. It will be a compile-time error if mypyc\ncan't compile the class as a native class. You can use this to avoid\naccidentally defining implicit non-native classes.\n\nDeleting attributes\n-------------------\n\nBy default, attributes defined in native classes can't be deleted. You\ncan explicitly allow certain attributes to be deleted by using\n``__deletable__``::\n\n   class Cls:\n       x: int = 0\n       y: int = 0\n       other: int = 0\n\n       __deletable__ = ['x', 'y']  # 'x' and 'y' can be deleted\n\n   o = Cls()\n   del o.x  # OK\n   del o.y  # OK\n   del o.other  # Error\n\nYou must initialize the ``__deletable__`` attribute in the class body,\nusing a list or a tuple expression with only string literal items that\nrefer to attributes. These are not valid::\n\n   a = ['x', 'y']\n\n   class Cls:\n       x: int\n       y: int\n\n       __deletable__ = a  # Error: cannot use variable 'a'\n\n   __deletable__ = ('a',)  # Error: not in a class body\n\nAcyclic classes\n---------------\n\nBy default, native classes participate in CPython's cyclic garbage\ncollector (GC). This adds some overhead to object allocation and\ndeallocation. If you know that instances of a class can never be\npart of reference cycles, you can opt out of cyclic GC using\n``@mypyc_attr(acyclic=True)``::\n\n    from mypy_extensions import mypyc_attr\n\n    @mypyc_attr(acyclic=True)\n    class Leaf:\n        def __init__(self, x: int, name: str) -> None:\n            self.x = x\n            self.name = name\n\nThis can improve performance, especially for classes that are\nallocated and deallocated frequently. Acyclic instances also use\nless memory, since CPython doesn't need to add a GC header to them.\n\nThe acyclic property is not inherited by subclasses. Each subclass\nmust explicitly use ``@mypyc_attr(acyclic=True)`` to also opt out\nof cyclic GC.\n\n.. warning::\n\n    If instances of an acyclic class actually participate in reference\n    cycles, those cycles will never be collected, resulting in memory\n    leaks. Only use this for classes whose instances won't refer back\n    to objects that (directly or indirectly) refer to the instance.\n\nOther properties\n----------------\n\nInstances of native classes don't usually have a ``__dict__`` attribute.\n"
  },
  {
    "path": "mypyc/doc/native_operations.rst",
    "content": "Miscellaneous native operations\n===============================\n\nThis is a list of various non-type-specific operations that have\ncustom native implementations.  If an operation has no native\nimplementation, mypyc will use fallback generic implementations that\nare often not as fast.\n\n.. note::\n\n  Operations specific to various primitive types are described\n  in the following sections.\n\nOperators\n---------\n\n* ``x is y`` (this is very fast for all types)\n\nFunctions\n---------\n\n* ``isinstance(obj, type: type)``\n* ``isinstance(obj, type: tuple)``\n* ``cast(<type>, obj)``\n* ``type(obj)``\n* ``len(obj)``\n* ``abs(obj)``\n* ``id(obj)``\n* ``iter(obj)``\n* ``next(iter: Iterator)``\n* ``hash(obj)``\n* ``getattr(obj, attr)``\n* ``getattr(obj, attr, default)``\n* ``setattr(obj, attr, value)``\n* ``hasattr(obj, attr)``\n* ``delattr(obj, name)``\n* ``slice(start, stop, step)``\n* ``globals()``\n* ``sorted(obj)``\n\nMethod decorators\n-----------------\n\n* ``@property``\n* ``@staticmethod``\n* ``@classmethod``\n* ``@abc.abstractmethod``\n\nStatements\n----------\n\nThese variants of statements have custom implementations:\n\n* ``for ... in seq:`` (for loop over a sequence)\n* ``for ... in enumerate(...):``\n* ``for ... in zip(...):``\n"
  },
  {
    "path": "mypyc/doc/performance_tips_and_tricks.rst",
    "content": ".. _performance-tips:\n\nPerformance tips and tricks\n===========================\n\nPerformance optimization is part art, part science. Just using mypyc\nin a simple manner will likely make your code faster, but squeezing\nthe most performance out of your code requires the use of some\ntechniques we'll summarize below.\n\nProfiling\n---------\n\nIf you are speeding up existing code, understanding where time is\nspent is important. Mypyc speeds up code that you compile. If most of\nthe time is spent elsewhere, you may come back disappointed. For\nexample, if you spend 40% of time outside compiled code, even if\ncompiled code would go 100x faster, overall performance will only be\n2.5x faster.\n\nA simple (but often effective) approach is to record the time in\nvarious points of program execution using ``time.time()``, and to\nprint out elapsed time (or to write it to a log file).\n\nThe stdlib modules ``profile`` and ``cProfile`` can provide much more\ndetailed data. (But these only work well with non-compiled code.)\n\nAvoiding slow libraries\n-----------------------\n\nIf profiling indicates that a lot of time is spent in the stdlib or\nthird-party libraries, you still have several options.\n\nFirst, if most time is spent in a few library features, you can\nperhaps easily reimplement them in type-annotated Python, or extract\nthe relevant code and annotate it. Now it may be easy to compile this\ncode to speed it up.\n\nSecond, you may be able to avoid the library altogether, or use an\nalternative, more efficient library to achieve the same purpose.\n\nType annotations\n----------------\n\nAs discussed earlier, type annotations are key to major performance\ngains. You should at least consider adding annotations to any\nperformance-critical functions and classes.  It may also be helpful to\nannotate code called by this code, even if it's not compiled, since\nthis may help mypy infer better types in the compile code. If you use\nlibraries, ensure they have stub files with decent type annotation\ncoverage. Writing a stub file is often easy, and you only need to\nannotate features you use a lot.\n\nIf annotating external code or writing stubs feel too burdensome, a\nsimple workaround is to annotate variables explicitly. For example,\nhere we call ``acme.get_items()``, but it has no type annotation. We\ncan use an explicit type annotation for the variable to which we\nassign the result::\n\n    import acme\n\n    def work() -> None:\n        # Annotate \"items\" to help mypyc\n        items: list[tuple[int, str]] = acme.get_items()\n        for item in items:\n            ...  # Do some work here\n\nWithout the annotation on ``items``, the type would be ``Any`` (since\n``acme`` has no type annotation), resulting in slower, generic\noperations being used later in the function.\n\nAvoiding slow Python features\n-----------------------------\n\nMypyc can optimize some features more effectively than others. Here\nthe difference is sometimes big -- some things only get marginally\nfaster at best, while others can get 10x faster, or more. Avoiding\nthese slow features in performance-critical parts of your code can\nhelp a lot.\n\nThese are some of the most important things to avoid:\n\n* Using class decorators or metaclasses in compiled code (that aren't\n  properly supported by mypyc)\n\n* Heavy reliance on interpreted Python libraries (C extensions are\n  usually fine)\n\nThese things also tend to be relatively slow:\n\n* Using Python classes and instances of Python classes (native classes\n  are much faster)\n\n* Calling decorated functions (``@property``, ``@staticmethod``, and\n  ``@classmethod`` are special cased and thus fast)\n\n* Calling nested functions\n\n* Calling functions or methods defined in other compilation units\n\n* Using ``*args`` or ``**kwargs``\n\n* Using generator functions\n\n* Using callable values (i.e. not leveraging early binding to call\n  functions or methods)\n\nNested functions can often be replaced with module-level functions or\nmethods of native classes.\n\nCallable values and nested functions can sometimes be replaced with an\ninstance of a native class with a single method only, such as\n``call(...)``. You can derive the class from an ABC, if there are\nmultiple possible functions.\n\n.. note::\n\n   Some slow features will likely get efficient implementations in the\n   future. You should check this section every once in a while to see\n   if some additional operations are fast.\n\nUsing fast native features\n--------------------------\n\nSome native operations are particularly quick relative to the\ncorresponding interpreted operations. Using them as much as possible\nmay allow you to see 10x or more in performance gains.\n\nSome things are not much (or any) faster in compiled code, such as set\nmath operations. In contrast, calling a method of a native class is\nmuch faster in compiled code.\n\nIf you are used to optimizing for CPython, you might have replaced\nsome class instances with dictionaries, as they can be\nfaster. However, in compiled code, this \"optimization\" would likely\nslow down your code.\n\nSimilarly, caching a frequently called method in a local variable can\nhelp in CPython, but it can slow things down in compiled code, since\nthe code won't use :ref:`early binding <early-binding>`::\n\n    def squares(n: int) -> list[int]:\n        a = []\n        append = a.append  # Not a good idea in compiled code!\n        for i in range(n):\n            append(i * i)\n        return a\n\nHere are examples of features that are fast, in no particular order\n(this list is *not* exhaustive):\n\n* Calling compiled functions directly defined in the same compilation\n  unit (with positional and/or keyword arguments)\n\n* Calling methods of native classes defined in the same compilation\n  unit (with positional and/or keyword arguments)\n\n* Many integer operations\n\n* Many ``float`` operations\n\n* Booleans\n\n* :ref:`Native list operations <list-ops>`, such as indexing,\n  ``append``, and list comprehensions\n\n* While loops\n\n* For loops over ranges and lists, and with ``enumerate`` or ``zip``\n\n* Reading dictionary items\n\n* ``isinstance()`` checks against native classes and instances of\n  primitive types (and unions of them)\n\n* Accessing local variables\n\n* Accessing attributes of native classes\n\n* Accessing final module-level attributes\n\n* Comparing strings for equality\n\nThese features are also fast, but somewhat less so (relative to other\nrelated operations):\n\n* Constructing instances of native classes\n\n* Constructing dictionaries\n\n* Setting dictionary items\n\n* Native :ref:`dict <dict-ops>` and :ref:`set <set-ops>` operations\n\n* Accessing module-level variables\n\nGenerally anything documented as a native operation is fast, even if\nit's not explicitly mentioned here\n\nAdjusting garbage collection\n----------------------------\n\nCompilation does not speed up cyclic garbage collection. If everything\nelse gets much faster, it's possible that garbage collection will take\na big fraction of time. You can use ``gc.set_threshold()`` to adjust\nthe garbage collector to run less often::\n\n    import gc\n\n    # Spend less time in gc; do this before significant computation\n    gc.set_threshold(150000)\n\n    ...  # Actual work happens here\n\nFast interpreter shutdown\n-------------------------\n\nIf you allocate many objects, it's possible that your program spends a\nlot of time cleaning up when the Python runtime shuts down. Mypyc\nwon't speed up the shutdown of a Python process much.\n\nYou can call ``os._exit(code)`` to immediately terminate the Python\nprocess, skipping normal cleanup. This can give a nice boost to a\nbatch process or a command-line tool.\n\n.. note::\n\n   This can be dangerous and can lose data. You need to ensure\n   that all streams are flushed and everything is otherwise cleaned up\n   properly.\n\nWork smarter\n------------\n\nUsually there are many things you can do to improve performance, even\nif most tweaks will yield only minor gains. The key to being effective\nis to focus on things that give a large gain with a small effort.\n\nFor example, low-level optimizations, such as avoiding a nested\nfunction, can be pointless, if you could instead avoid a metaclass --\nto allow a key class to be compiled as a native class. The latter\noptimization could speed up numerous method calls and attribute\naccesses, just like that.\n"
  },
  {
    "path": "mypyc/doc/set_operations.rst",
    "content": ".. _set-ops:\n\nNative set operations\n======================\n\nThese ``set`` operations have fast, optimized implementations. Other\nset operations use generic implementations that are often slower.\n\nConstruction\n------------\n\nConstruct set with specific items:\n\n* ``{item0, ..., itemN}``\n\nConstruct empty set:\n\n* ``set()``\n\nConstruct set from iterable:\n\n* ``set(x: Iterable)``\n\nSet comprehensions:\n\n* ``{... for ... in ...}``\n* ``{... for ... in ... if ...}``\n\nOperators\n---------\n\n* ``item in s``\n\nMethods\n-------\n\n* ``s.add(item)``\n* ``s.remove(item)``\n* ``s.discard(item)``\n* ``s.update(x: Iterable)``\n* ``s.clear()``\n* ``s.pop()``\n\nFunctions\n---------\n\n* ``len(s: set)``\n"
  },
  {
    "path": "mypyc/doc/str_operations.rst",
    "content": ".. _str-ops:\n\nNative string operations\n========================\n\nThese ``str`` operations have fast, optimized implementations. Other\nstring operations use generic implementations that are often slower.\n\nConstruction\n------------\n\n* String literal\n* ``str(x: int)``\n* ``str(x: object)``\n* ``repr(x: int)``\n* ``repr(x: object)``\n\nOperators\n---------\n\n* Concatenation (``s1 + s2``)\n* Indexing (``s[n]``; also ``ord(s[n])``, which avoids the temporary length-1 string)\n* Slicing (``s[n:m]``, ``s[n:]``, ``s[:m]``)\n* Repetition (``s * n``, ``n * s``)\n* Comparisons (``==``, ``!=``)\n* Augmented assignment (``s1 += s2``)\n* Containment (``s1 in s2``)\n\n.. _str-methods:\n\nMethods\n-------\n\n* ``s.encode()``\n* ``s.encode(encoding: str)``\n* ``s.encode(encoding: str, errors: str)``\n* ``s1.endswith(s2: str)``\n* ``s1.endswith(t: tuple[str, ...])``\n* ``s1.find(s2: str)``\n* ``s1.find(s2: str, start: int)``\n* ``s1.find(s2: str, start: int, end: int)``\n* ``s.isalnum()``\n* ``s.isdigit()``\n* ``s.isspace()``\n* ``s.lower()``\n* ``s.join(x: Iterable)``\n* ``s.lstrip()``\n* ``s.lstrip(chars: str)``\n* ``s.partition(sep: str)``\n* ``s.removeprefix(prefix: str)``\n* ``s.removesuffix(suffix: str)``\n* ``s.replace(old: str, new: str)``\n* ``s.replace(old: str, new: str, count: int)``\n* ``s1.rfind(s2: str)``\n* ``s1.rfind(s2: str, start: int)``\n* ``s1.rfind(s2: str, start: int, end: int)``\n* ``s.rpartition(sep: str)``\n* ``s.rsplit()``\n* ``s.rsplit(sep: str)``\n* ``s.rsplit(sep: str, maxsplit: int)``\n* ``s.rstrip()``\n* ``s.rstrip(chars: str)``\n* ``s.split()``\n* ``s.split(sep: str)``\n* ``s.split(sep: str, maxsplit: int)``\n* ``s.splitlines()``\n* ``s.splitlines(keepends: bool)``\n* ``s1.startswith(s2: str)``\n* ``s1.startswith(t: tuple[str, ...])``\n* ``s.upper()``\n* ``s.strip()``\n* ``s.strip(chars: str)``\n\n.. note::\n\n    :ref:`bytes.decode() <bytes-methods>` is also optimized.\n\nFormatting\n----------\n\nA subset of these common string formatting expressions are optimized:\n\n* F-strings\n* ``\"...\".format(...)``\n* ``\"...\" % (...)``\n\nFunctions\n---------\n\n* ``len(s: str)``\n* ``ord(s: str)``\n"
  },
  {
    "path": "mypyc/doc/tuple_operations.rst",
    "content": ".. _tuple-ops:\n\nNative tuple operations\n=======================\n\nThese ``tuple`` operations have fast, optimized implementations. Other\ntuple operations use generic implementations that are often slower.\n\nUnless mentioned otherwise, these operations apply to both fixed-length\ntuples and variable-length tuples.\n\nConstruction\n------------\n\n* ``item0, ..., itemN`` (construct a tuple)\n* ``tuple(lst: list)`` (construct a variable-length tuple)\n* ``tuple(lst: Iterable)`` (construct a variable-length tuple)\n\nOperators\n---------\n\n* ``tup[n]`` (integer index)\n* ``tup[n:m]``, ``tup[n:]``, ``tup[:m]`` (slicing)\n* ``tup1 + tup2``\n* ``tup * n``, ``n * tup``\n\nStatements\n----------\n\n* ``item0, ..., itemN = tup`` (for fixed-length tuples)\n\nFunctions\n---------\n\n* ``len(tup: tuple)``\n"
  },
  {
    "path": "mypyc/doc/using_type_annotations.rst",
    "content": ".. _using-type-annotations:\n\nUsing type annotations\n======================\n\nYou will get the most out of mypyc if you compile code with precise\ntype annotations. Not all type annotations will help performance\nequally, however. Using types such as :ref:`primitive types\n<primitive-types>`, :ref:`native classes <native-class-intro>`,\n:ref:`union types <union-types>`, :ref:`trait types <trait-types>`,\nand :ref:`tuple types <tuple-types>` as much as possible is a key to\nmajor performance gains over CPython.\n\nIn contrast, some other types, including ``Any``, are treated as\n:ref:`erased types <erased-types>`.  Operations on erased types use\ngeneric operations that work with arbitrary objects, similar to how\nthe CPython interpreter works. If you only use erased types, the only\nnotable benefits over CPython will be the removal of interpreter\noverhead (from compilation) and a bit of :ref:`early binding\n<early-binding>`, which will usually only give minor performance\ngains.\n\n.. _primitive-types:\n\nPrimitive types\n---------------\n\nThe following built-in types are treated as *primitive types* by\nmypyc, and many operations on these types have efficient\nimplementations:\n\n* ``int`` (:ref:`native operations <int-ops>`)\n* ``i64`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)\n* ``i32`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)\n* ``i16`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)\n* ``u8`` (:ref:`documentation <native-ints>`, :ref:`native operations <int-ops>`)\n* ``float`` (:ref:`native operations <float-ops>`)\n* ``bool`` (:ref:`native operations <bool-ops>`)\n* ``str`` (:ref:`native operations <str-ops>`)\n* ``bytes`` (:ref:`native operations <bytes-ops>`)\n* ``bytearray`` (:ref:`native operations <bytearray-ops>`)\n* ``list[T]`` (:ref:`native operations <list-ops>`)\n* ``dict[K, V]`` (:ref:`native operations <dict-ops>`)\n* ``set[T]`` (:ref:`native operations <set-ops>`)\n* ``tuple[T, ...]`` (variable-length tuple; :ref:`native operations <tuple-ops>`)\n* ``None``\n* ``range``\n\nThe link after each type lists all supported native, optimized\noperations for the type. You can use all operations supported by\nPython, but *native operations* will have custom, optimized\nimplementations.\n\nPrimitive containers\n--------------------\n\nPrimitive container objects such as ``list`` and ``dict`` don't\nmaintain knowledge of the item types at runtime -- the item type is\n*erased*.\n\nThis means that item types are checked when items are accessed, not\nwhen a container is passed as an argument or assigned to another\nvariable. For example, here we have a runtime type error on the final\nline of ``example`` (the ``Any`` type means an arbitrary, unchecked\nvalue)::\n\n    from typing import Any\n\n    def example(a: list[Any]) -> None:\n        b: list[int] = a  # No error -- items are not checked\n        print(b[0])  # Error here -- got str, but expected int\n\n    example([\"x\"])\n\n.. _native-class-intro:\n\nNative classes\n--------------\n\nClasses that get compiled to C extensions are called native\nclasses. Most common operations on instances of these classes are\noptimized, including construction, attribute access and method calls.\n\nNative class definitions look exactly like normal Python class\ndefinitions.  A class is usually native if it's in a compiled module\n(though there are some exceptions).\n\nConsider this example:\n\n.. code-block::\n\n   class Point:\n       def __init__(self, x: int, y: int) -> None:\n           self.x = x\n           self.y = y\n\n   def shift(p: Point) -> Point:\n       return Point(p.x + 1, p.y + 1)\n\nAll operations in the above example use native operations, if the file\nis compiled.\n\nNative classes have some notable different from Python classes:\n\n* Only attributes and methods defined in the class body or methods are\n  supported.  If you try to assign to an undefined attribute outside\n  the class definition, ``AttributeError`` will be raised. This enables\n  an efficient memory layout and fast method calls for native classes.\n\n* Native classes usually don't define the ``__dict__`` attribute (they\n  don't have an attribute dictionary). This follows from only having\n  a specific set of attributes.\n\n* Native classes can't have an arbitrary metaclass or use most class\n  decorators.\n\nNative classes only support single inheritance. A limited form of\nmultiple inheritance is supported through *trait types*. You generally\nmust inherit from another native class (or ``object``). By default,\nyou can't inherit a Python class from a native class (but there's\nan :ref:`override <inheritance>` to allow that).\n\nSee :ref:`native-classes` for more details.\n\n.. _tuple-types:\n\nTuple types\n-----------\n\nFixed-length\n`tuple types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#tuple-types>`_\nsuch as ``tuple[int, str]`` are represented\nas :ref:`value types <value-and-heap-types>` when stored in variables,\npassed as arguments, or returned from functions. Value types are\nallocated in the low-level machine stack or in CPU registers, as\nopposed to *heap types*, which are allocated dynamically from the\nheap.\n\nLike all value types, tuples will be *boxed*, i.e. converted to\ncorresponding heap types, when stored in Python containers, or passed\nto non-native code. A boxed tuple value will be a regular Python tuple\nobject.\n\n.. _union-types:\n\nUnion types\n-----------\n\n`Union types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#union-types>`_\nand\n`optional types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#optional-types-and-the-none-type>`_\nthat contain primitive types, native class types and\ntrait types are also efficient. If a union type has\n:ref:`erased <erased-types>` items, accessing items with\nnon-erased types is often still quite efficient.\n\nA value with a union types is always :ref:`boxed <value-and-heap-types>`,\neven if it contains a value that also has an unboxed representation, such\nas an integer or a boolean.\n\nFor example, using ``Optional[int]`` is quite efficient, but the value\nwill always be boxed. A plain ``int`` value will usually be faster, since\nit has an unboxed representation.\n\n.. _trait-types:\n\nTrait types\n-----------\n\nTrait types enable a form of multiple inheritance for native classes.\nA native class can inherit any number of traits.  Trait types are\ndefined as classes using the ``mypy_extensions.trait`` decorator::\n\n    from mypy_extensions import trait\n\n    @trait\n    class MyTrait:\n        def method(self) -> None:\n            ...\n\nTraits can define methods, properties and attributes. They often\ndefine abstract methods. Traits can be generic.\n\nIf a class subclasses both a non-trait class and traits, the traits\nmust be placed at the end of the base class list::\n\n    class Base: ...\n\n    class Derived(Base, MyTrait, FooTrait):  # OK\n        ...\n\n    class Derived2(MyTrait, FooTrait, Base):\n        # Error: traits should come last\n        ...\n\nTraits have some special properties:\n\n* You shouldn't create instances of traits (though mypyc does not\n  prevent it yet).\n\n* Traits can subclass other traits or native classes, but the MRO must be\n  linear (just like with native classes).\n\n* Accessing methods or attributes through a trait type is somewhat\n  less efficient than through a native class type, but this is much\n  faster than through Python class types or other\n  :ref:`erased types <erased-types>`.\n\nYou need to install ``mypy-extensions`` to use ``@trait``:\n\n.. code-block:: text\n\n    pip install --upgrade mypy-extensions\n\n.. _erased-types:\n\nErased types\n------------\n\nMypyc supports many other kinds of types as well, beyond those\ndescribed above.  However, these types don't have customized\noperations, and they are implemented using *type erasure*.  Type\nerasure means that all other types are equivalent to untyped values at\nruntime, i.e. they are the equivalent of the type ``Any``. Erased\ntypes include these:\n\n* Python classes (including ABCs)\n\n* Non-mypyc extension types and primitive types (including built-in\n  types that are not primitives)\n\n* `Callable types <https://mypy.readthedocs.io/en/stable/kinds_of_types.html#callable-types-and-lambdas>`_\n\n* `Type variable types <https://mypy.readthedocs.io/en/stable/generics.html>`_\n\n* Type `Any <https://mypy.readthedocs.io/en/stable/dynamic_typing.html>`_\n\n* Protocol types\n\nUsing erased types can still improve performance, since they can\nenable better types to be inferred for expressions that use these\ntypes.  For example, a value with type ``Callable[[], int]`` will not\nallow native calls. However, the return type is a primitive type, and\nwe can use fast operations on the return value::\n\n    from typing import Callable\n\n    def call_and_inc(f: Callable[[], int]) -> int:\n        # Slow call, since f has an erased type\n        n = f()\n        # Fast increment; inferred type of n is int (primitive type)\n        n += 1\n        return n\n\nIf the type of the argument ``f`` was ``Any``, the type of ``n`` would\nalso be ``Any``, resulting in a generic, slower increment operation\nbeing used.\n\nStrict runtime type checking\n----------------------------\n\nCompiled code ensures that any variable or expression with a\nnon-erased type only has compatible values at runtime. This is in\ncontrast with using *optional static typing*, such as by using mypy,\nwhen type annotations are not enforced at runtime. Mypyc ensures\ntype safety both statically and at runtime.\n\n``Any`` types and erased types in general can compromise type safety,\nand this is by design. Inserting strict runtime type checks for all\npossible values would be too expensive and against the goal of\nhigh performance.\n\n.. _value-and-heap-types:\n\nValue and heap types\n--------------------\n\nIn CPython, memory for all objects is dynamically allocated on the\nheap. All Python types are thus *heap types*. In compiled code, some\ntypes are *value types* -- no object is (necessarily) allocated on the\nheap.  ``bool``, ``float``, ``None``, :ref:`native integer types <native-ints>`\nand fixed-length tuples are value types.\n\n``int`` is a hybrid. For typical integer values, it is a value\ntype. Large enough integer values, those that require more than 63\nbits (or 31 bits on 32-bit platforms) to represent, use a heap-based\nrepresentation (same as CPython).\n\nValue types have a few differences from heap types:\n\n* When an instance of a value type is used in a context that expects a\n  heap value, for example as a list item, it will transparently switch\n  to a heap-based representation (boxing) as needed.\n\n* Similarly, mypyc transparently changes from a heap-based\n  representation to a value representation (unboxing).\n\n* Object identity of integers, floating point values and tuples is not\n  preserved. You should use ``==`` instead of ``is`` if you are comparing\n  two integers, floats or fixed-length tuples.\n\n* When an instance of a subclass of a value type is converted to the\n  base type, it is implicitly converted to an instance of the target\n  type.  For example, a ``bool`` value assigned to a variable with an\n  ``int`` type will be converted to the corresponding integer.\n\nThe latter conversion is the only implicit type conversion that\nhappens in mypyc programs.\n\nExample::\n\n    def example() -> None:\n        # A small integer uses the value (unboxed) representation\n        x = 5\n        # A large integer uses the heap (boxed) representation\n        x = 2**500\n        # Lists always contain boxed integers\n        a = [55]\n        # When reading from a list, the object is automatically unboxed\n        x = a[0]\n        # True is converted to 1 on assignment\n        x = True\n\nSince integers and floating point values have a different runtime\nrepresentations and neither can represent all the values of the other\ntype, type narrowing of floating point values through assignment is\ndisallowed in compiled code. For consistency, mypyc rejects assigning\nan integer value to a float variable even in variable initialization.\nAn explicit conversion is required.\n\nExamples::\n\n    def narrowing(n: int) -> None:\n        # Error: Incompatible value representations in assignment\n        # (expression has type \"int\", variable has type \"float\")\n        x: float = 0\n\n        y: float = 0.0  # Ok\n\n        if f():\n            y = n  # Error\n        if f():\n            y = float(n)  # Ok\n\n.. _native-ints:\n\nNative integer types\n--------------------\n\nYou can use the native integer types ``i64`` (64-bit signed integer),\n``i32`` (32-bit signed integer), ``i16`` (16-bit signed integer), and\n``u8`` (8-bit unsigned integer) if you know that integer values will\nalways fit within fixed bounds. These types are faster than the\narbitrary-precision ``int`` type, since they don't require overflow\nchecks on operations. They may also use less memory than ``int``\nvalues. The types are imported from the ``mypy_extensions`` module\n(installed via ``pip install mypy_extensions``).\n\nExample::\n\n    from mypy_extensions import i64\n\n    def sum_list(l: list[i64]) -> i64:\n        s: i64 = 0\n        for n in l:\n            s += n\n        return s\n\n    # Implicit conversions from int to i64\n    print(sum_list([1, 3, 5]))\n\n.. note::\n\n  Since there are no overflow checks when performing native integer\n  arithmetic, the above function could result in an overflow or other\n  undefined behavior if the sum might not fit within 64 bits.\n\n  The behavior when running as interpreted Python program will be\n  different if there are overflows. Declaring native integer types\n  have no effect unless code is compiled. Native integer types are\n  effectively equivalent to ``int`` when interpreted.\n\nNative integer types have these additional properties:\n\n* Values can be implicitly converted between ``int`` and a native\n  integer type (both ways).\n\n* Conversions between different native integer types must be explicit.\n  A conversion to a narrower native integer type truncates the value\n  without a runtime overflow check.\n\n* If a binary operation (such as ``+``) or an augmented assignment\n  (such as ``+=``) mixes native integer and ``int`` values, the\n  ``int`` operand is implicitly coerced to the native integer type\n  (native integer types are \"sticky\").\n\n* You can't mix different native integer types in binary\n  operations. Instead, convert between types explicitly.\n\nFor more information about native integer types, refer to\n:ref:`native integer operations <int-ops>`.\n"
  },
  {
    "path": "mypyc/errors.py",
    "content": "from __future__ import annotations\n\nimport mypy.errors\nfrom mypy.options import Options\n\n\nclass Errors:\n    def __init__(self, options: Options) -> None:\n        self.num_errors = 0\n        self.num_warnings = 0\n        self._errors = mypy.errors.Errors(options, hide_error_codes=True)\n\n    def error(self, msg: str, path: str, line: int) -> None:\n        self._errors.set_file(path, None, self._errors.options)\n        self._errors.report(line, None, msg, severity=\"error\")\n        self.num_errors += 1\n\n    def note(self, msg: str, path: str, line: int) -> None:\n        self._errors.set_file(path, None, self._errors.options)\n        self._errors.report(line, None, msg, severity=\"note\")\n\n    def warning(self, msg: str, path: str, line: int) -> None:\n        self._errors.set_file(path, None, self._errors.options)\n        self._errors.report(line, None, msg, severity=\"warning\")\n        self.num_warnings += 1\n\n    def new_messages(self) -> list[str]:\n        return self._errors.new_messages()\n\n    def flush_errors(self) -> None:\n        for error in self.new_messages():\n            print(error)\n"
  },
  {
    "path": "mypyc/external/googletest/LICENSE",
    "content": "Copyright 2008, Google Inc.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n    * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n    * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and/or other materials provided with the\ndistribution.\n    * Neither the name of Google Inc. nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n"
  },
  {
    "path": "mypyc/external/googletest/README.md",
    "content": "\n### Generic Build Instructions ###\n\n#### Setup ####\n\nTo build Google Test and your tests that use it, you need to tell your\nbuild system where to find its headers and source files.  The exact\nway to do it depends on which build system you use, and is usually\nstraightforward.\n\n#### Build ####\n\nSuppose you put Google Test in directory `${GTEST_DIR}`.  To build it,\ncreate a library build target (or a project as called by Visual Studio\nand Xcode) to compile\n\n    ${GTEST_DIR}/src/gtest-all.cc\n\nwith `${GTEST_DIR}/include` in the system header search path and `${GTEST_DIR}`\nin the normal header search path.  Assuming a Linux-like system and gcc,\nsomething like the following will do:\n\n    g++ -isystem ${GTEST_DIR}/include -I${GTEST_DIR} \\\n        -pthread -c ${GTEST_DIR}/src/gtest-all.cc\n    ar -rv libgtest.a gtest-all.o\n\n(We need `-pthread` as Google Test uses threads.)\n\nNext, you should compile your test source file with\n`${GTEST_DIR}/include` in the system header search path, and link it\nwith gtest and any other necessary libraries:\n\n    g++ -isystem ${GTEST_DIR}/include -pthread path/to/your_test.cc libgtest.a \\\n        -o your_test\n\nAs an example, the make/ directory contains a Makefile that you can\nuse to build Google Test on systems where GNU make is available\n(e.g. Linux, Mac OS X, and Cygwin).  It doesn't try to build Google\nTest's own tests.  Instead, it just builds the Google Test library and\na sample test.  You can use it as a starting point for your own build\nscript.\n\nIf the default settings are correct for your environment, the\nfollowing commands should succeed:\n\n    cd ${GTEST_DIR}/make\n    make\n    ./sample1_unittest\n\nIf you see errors, try to tweak the contents of `make/Makefile` to make\nthem go away.  There are instructions in `make/Makefile` on how to do\nit.\n\n### Using CMake ###\n\nGoogle Test comes with a CMake build script (\n[CMakeLists.txt](CMakeLists.txt)) that can be used on a wide range of platforms (\"C\" stands for\ncross-platform.). If you don't have CMake installed already, you can\ndownload it for free from <http://www.cmake.org/>.\n\nCMake works by generating native makefiles or build projects that can\nbe used in the compiler environment of your choice.  The typical\nworkflow starts with:\n\n    mkdir mybuild       # Create a directory to hold the build output.\n    cd mybuild\n    cmake ${GTEST_DIR}  # Generate native build scripts.\n\nIf you want to build Google Test's samples, you should replace the\nlast command with\n\n    cmake -Dgtest_build_samples=ON ${GTEST_DIR}\n\nIf you are on a \\*nix system, you should now see a Makefile in the\ncurrent directory.  Just type 'make' to build gtest.\n\nIf you use Windows and have Visual Studio installed, a `gtest.sln` file\nand several `.vcproj` files will be created.  You can then build them\nusing Visual Studio.\n\nOn Mac OS X with Xcode installed, a `.xcodeproj` file will be generated.\n\n### Legacy Build Scripts ###\n\nBefore settling on CMake, we have been providing hand-maintained build\nprojects/scripts for Visual Studio, Xcode, and Autotools.  While we\ncontinue to provide them for convenience, they are not actively\nmaintained any more.  We highly recommend that you follow the\ninstructions in the previous two sections to integrate Google Test\nwith your existing build system.\n\nIf you still need to use the legacy build scripts, here's how:\n\nThe msvc\\ folder contains two solutions with Visual C++ projects.\nOpen the `gtest.sln` or `gtest-md.sln` file using Visual Studio, and you\nare ready to build Google Test the same way you build any Visual\nStudio project.  Files that have names ending with -md use DLL\nversions of Microsoft runtime libraries (the /MD or the /MDd compiler\noption).  Files without that suffix use static versions of the runtime\nlibraries (the /MT or the /MTd option).  Please note that one must use\nthe same option to compile both gtest and the test code.  If you use\nVisual Studio 2005 or above, we recommend the -md version as /MD is\nthe default for new projects in these versions of Visual Studio.\n\nOn Mac OS X, open the `gtest.xcodeproj` in the `xcode/` folder using\nXcode.  Build the \"gtest\" target.  The universal binary framework will\nend up in your selected build directory (selected in the Xcode\n\"Preferences...\" -> \"Building\" pane and defaults to xcode/build).\nAlternatively, at the command line, enter:\n\n    xcodebuild\n\nThis will build the \"Release\" configuration of gtest.framework in your\ndefault build location.  See the \"xcodebuild\" man page for more\ninformation about building different configurations and building in\ndifferent locations.\n\nIf you wish to use the Google Test Xcode project with Xcode 4.x and\nabove, you need to either:\n\n * update the SDK configuration options in xcode/Config/General.xconfig.\n   Comment options `SDKROOT`, `MACOS_DEPLOYMENT_TARGET`, and `GCC_VERSION`. If\n   you choose this route you lose the ability to target earlier versions\n   of MacOS X.\n * Install an SDK for an earlier version. This doesn't appear to be\n   supported by Apple, but has been reported to work\n   (http://stackoverflow.com/questions/5378518).\n\n### Tweaking Google Test ###\n\nGoogle Test can be used in diverse environments.  The default\nconfiguration may not work (or may not work well) out of the box in\nsome environments.  However, you can easily tweak Google Test by\ndefining control macros on the compiler command line.  Generally,\nthese macros are named like `GTEST_XYZ` and you define them to either 1\nor 0 to enable or disable a certain feature.\n\nWe list the most frequently used macros below.  For a complete list,\nsee file [include/gtest/internal/gtest-port.h](include/gtest/internal/gtest-port.h).\n\n### Choosing a TR1 Tuple Library ###\n\nSome Google Test features require the C++ Technical Report 1 (TR1)\ntuple library, which is not yet available with all compilers.  The\ngood news is that Google Test implements a subset of TR1 tuple that's\nenough for its own need, and will automatically use this when the\ncompiler doesn't provide TR1 tuple.\n\nUsually you don't need to care about which tuple library Google Test\nuses.  However, if your project already uses TR1 tuple, you need to\ntell Google Test to use the same TR1 tuple library the rest of your\nproject uses, or the two tuple implementations will clash.  To do\nthat, add\n\n    -DGTEST_USE_OWN_TR1_TUPLE=0\n\nto the compiler flags while compiling Google Test and your tests.  If\nyou want to force Google Test to use its own tuple library, just add\n\n    -DGTEST_USE_OWN_TR1_TUPLE=1\n\nto the compiler flags instead.\n\nIf you don't want Google Test to use tuple at all, add\n\n    -DGTEST_HAS_TR1_TUPLE=0\n\nand all features using tuple will be disabled.\n\n### Multi-threaded Tests ###\n\nGoogle Test is thread-safe where the pthread library is available.\nAfter `#include \"gtest/gtest.h\"`, you can check the `GTEST_IS_THREADSAFE`\nmacro to see whether this is the case (yes if the macro is `#defined` to\n1, no if it's undefined.).\n\nIf Google Test doesn't correctly detect whether pthread is available\nin your environment, you can force it with\n\n    -DGTEST_HAS_PTHREAD=1\n\nor\n\n    -DGTEST_HAS_PTHREAD=0\n\nWhen Google Test uses pthread, you may need to add flags to your\ncompiler and/or linker to select the pthread library, or you'll get\nlink errors.  If you use the CMake script or the deprecated Autotools\nscript, this is taken care of for you.  If you use your own build\nscript, you'll need to read your compiler and linker's manual to\nfigure out what flags to add.\n\n### As a Shared Library (DLL) ###\n\nGoogle Test is compact, so most users can build and link it as a\nstatic library for the simplicity.  You can choose to use Google Test\nas a shared library (known as a DLL on Windows) if you prefer.\n\nTo compile *gtest* as a shared library, add\n\n    -DGTEST_CREATE_SHARED_LIBRARY=1\n\nto the compiler flags.  You'll also need to tell the linker to produce\na shared library instead - consult your linker's manual for how to do\nit.\n\nTo compile your *tests* that use the gtest shared library, add\n\n    -DGTEST_LINKED_AS_SHARED_LIBRARY=1\n\nto the compiler flags.\n\nNote: while the above steps aren't technically necessary today when\nusing some compilers (e.g. GCC), they may become necessary in the\nfuture, if we decide to improve the speed of loading the library (see\n<http://gcc.gnu.org/wiki/Visibility> for details).  Therefore you are\nrecommended to always add the above flags when using Google Test as a\nshared library.  Otherwise a future release of Google Test may break\nyour build script.\n\n### Avoiding Macro Name Clashes ###\n\nIn C++, macros don't obey namespaces.  Therefore two libraries that\nboth define a macro of the same name will clash if you `#include` both\ndefinitions.  In case a Google Test macro clashes with another\nlibrary, you can force Google Test to rename its macro to avoid the\nconflict.\n\nSpecifically, if both Google Test and some other code define macro\nFOO, you can add\n\n    -DGTEST_DONT_DEFINE_FOO=1\n\nto the compiler flags to tell Google Test to change the macro's name\nfrom `FOO` to `GTEST_FOO`.  Currently `FOO` can be `FAIL`, `SUCCEED`,\nor `TEST`.  For example, with `-DGTEST_DONT_DEFINE_TEST=1`, you'll\nneed to write\n\n    GTEST_TEST(SomeTest, DoesThis) { ... }\n\ninstead of\n\n    TEST(SomeTest, DoesThis) { ... }\n\nin order to define a test.\n\n## Developing Google Test ##\n\nThis section discusses how to make your own changes to Google Test.\n\n### Testing Google Test Itself ###\n\nTo make sure your changes work as intended and don't break existing\nfunctionality, you'll want to compile and run Google Test's own tests.\nFor that you can use CMake:\n\n    mkdir mybuild\n    cd mybuild\n    cmake -Dgtest_build_tests=ON ${GTEST_DIR}\n\nMake sure you have Python installed, as some of Google Test's tests\nare written in Python.  If the cmake command complains about not being\nable to find Python (`Could NOT find PythonInterp (missing:\nPYTHON_EXECUTABLE)`), try telling it explicitly where your Python\nexecutable can be found:\n\n    cmake -DPYTHON_EXECUTABLE=path/to/python -Dgtest_build_tests=ON ${GTEST_DIR}\n\nNext, you can build Google Test and all of its own tests.  On \\*nix,\nthis is usually done by 'make'.  To run the tests, do\n\n    make test\n\nAll tests should pass.\n\nNormally you don't need to worry about regenerating the source files,\nunless you need to modify them.  In that case, you should modify the\ncorresponding .pump files instead and run the pump.py Python script to\nregenerate them.  You can find pump.py in the [scripts/](scripts/) directory.\nRead the [Pump manual](docs/PumpManual.md) for how to use it.\n"
  },
  {
    "path": "mypyc/external/googletest/make/Makefile",
    "content": "# A sample Makefile for building Google Test and using it in user\n# tests.  Please tweak it to suit your environment and project.  You\n# may want to move it to your project's root directory.\n#\n# SYNOPSIS:\n#\n#   make [all]  - makes everything.\n#   make TARGET - makes the given target.\n#   make clean  - removes all files generated by make.\n\n# Please tweak the following variable definitions as needed by your\n# project, except GTEST_HEADERS, which you can use in your own targets\n# but shouldn't modify.\n\n# Points to the root of Google Test, relative to where this file is.\n# Remember to tweak this if you move this file.\nGTEST_DIR = ..\n\n# Flags passed to the preprocessor.\n# Set Google Test's header directory as a system directory, such that\n# the compiler doesn't generate warnings in Google Test headers.\nCPPFLAGS += -isystem $(GTEST_DIR)/include\n\n# Flags passed to the C++ compiler.\nCXXFLAGS += -g -Wall -Wextra -pthread -fPIC\n\n# All Google Test headers.  Usually you shouldn't change this\n# definition.\nGTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \\\n                $(GTEST_DIR)/include/gtest/internal/*.h\n\n# House-keeping build targets.\n\nall : libgtest.a libgtest_main.a\n\nclean :\n\trm -f libgtest.a libgtest_main.a *.o\n\n# Builds libgtest.a and libgtest_main.a.\n\n# Usually you shouldn't tweak such internal variables, indicated by a\n# trailing _.\nGTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS)\n\n# For simplicity and to avoid depending on Google Test's\n# implementation details, the dependencies specified below are\n# conservative and not optimized.  This is fine as Google Test\n# compiles fast and for ordinary users its source rarely changes.\ngtest-all.o : $(GTEST_SRCS_)\n\t$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \\\n            $(GTEST_DIR)/src/gtest-all.cc\n\ngtest_main.o : $(GTEST_SRCS_)\n\t$(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \\\n            $(GTEST_DIR)/src/gtest_main.cc\n\nlibgtest.a : gtest-all.o\n\t$(AR) $(ARFLAGS) $@ $^\n\nlibgtest_main.a : gtest-all.o gtest_main.o\n\t$(AR) $(ARFLAGS) $@ $^\n"
  },
  {
    "path": "mypyc/external/googletest/src/gtest-all.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: mheule@google.com (Markus Heule)\n//\n// Google C++ Testing Framework (Google Test)\n//\n// Sometimes it's desirable to build Google Test by compiling a single file.\n// This file serves this purpose.\n\n// This line ensures that gtest.h can be compiled on its own, even\n// when it's fused.\n#include \"gtest/gtest.h\"\n\n// The following lines pull in the real gtest *.cc files.\n#include \"src/gtest.cc\"\n#include \"src/gtest-death-test.cc\"\n#include \"src/gtest-filepath.cc\"\n#include \"src/gtest-port.cc\"\n#include \"src/gtest-printers.cc\"\n#include \"src/gtest-test-part.cc\"\n#include \"src/gtest-typed-test.cc\"\n"
  },
  {
    "path": "mypyc/external/googletest/src/gtest-death-test.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: wan@google.com (Zhanyong Wan), vladl@google.com (Vlad Losev)\n//\n// This file implements death tests.\n\n#include \"gtest/gtest-death-test.h\"\n#include \"gtest/internal/gtest-port.h\"\n#include \"gtest/internal/custom/gtest.h\"\n\n#if GTEST_HAS_DEATH_TEST\n\n# if GTEST_OS_MAC\n#  include <crt_externs.h>\n# endif  // GTEST_OS_MAC\n\n# include <errno.h>\n# include <fcntl.h>\n# include <limits.h>\n\n# if GTEST_OS_LINUX\n#  include <signal.h>\n# endif  // GTEST_OS_LINUX\n\n# include <stdarg.h>\n\n# if GTEST_OS_WINDOWS\n#  include <windows.h>\n# else\n#  include <sys/mman.h>\n#  include <sys/wait.h>\n# endif  // GTEST_OS_WINDOWS\n\n# if GTEST_OS_QNX\n#  include <spawn.h>\n# endif  // GTEST_OS_QNX\n\n#endif  // GTEST_HAS_DEATH_TEST\n\n#include \"gtest/gtest-message.h\"\n#include \"gtest/internal/gtest-string.h\"\n\n// Indicates that this translation unit is part of Google Test's\n// implementation.  It must come before gtest-internal-inl.h is\n// included, or there will be a compiler error.  This trick exists to\n// prevent the accidental inclusion of gtest-internal-inl.h in the\n// user's code.\n#define GTEST_IMPLEMENTATION_ 1\n#include \"src/gtest-internal-inl.h\"\n#undef GTEST_IMPLEMENTATION_\n\nnamespace testing {\n\n// Constants.\n\n// The default death test style.\nstatic const char kDefaultDeathTestStyle[] = \"fast\";\n\nGTEST_DEFINE_string_(\n    death_test_style,\n    internal::StringFromGTestEnv(\"death_test_style\", kDefaultDeathTestStyle),\n    \"Indicates how to run a death test in a forked child process: \"\n    \"\\\"threadsafe\\\" (child process re-executes the test binary \"\n    \"from the beginning, running only the specific death test) or \"\n    \"\\\"fast\\\" (child process runs the death test immediately \"\n    \"after forking).\");\n\nGTEST_DEFINE_bool_(\n    death_test_use_fork,\n    internal::BoolFromGTestEnv(\"death_test_use_fork\", false),\n    \"Instructs to use fork()/_exit() instead of clone() in death tests. \"\n    \"Ignored and always uses fork() on POSIX systems where clone() is not \"\n    \"implemented. Useful when running under valgrind or similar tools if \"\n    \"those do not support clone(). Valgrind 3.3.1 will just fail if \"\n    \"it sees an unsupported combination of clone() flags. \"\n    \"It is not recommended to use this flag w/o valgrind though it will \"\n    \"work in 99% of the cases. Once valgrind is fixed, this flag will \"\n    \"most likely be removed.\");\n\nnamespace internal {\nGTEST_DEFINE_string_(\n    internal_run_death_test, \"\",\n    \"Indicates the file, line number, temporal index of \"\n    \"the single death test to run, and a file descriptor to \"\n    \"which a success code may be sent, all separated by \"\n    \"the '|' characters.  This flag is specified if and only if the current \"\n    \"process is a sub-process launched for running a thread-safe \"\n    \"death test.  FOR INTERNAL USE ONLY.\");\n}  // namespace internal\n\n#if GTEST_HAS_DEATH_TEST\n\nnamespace internal {\n\n// Valid only for fast death tests. Indicates the code is running in the\n// child process of a fast style death test.\n# if !GTEST_OS_WINDOWS\nstatic bool g_in_fast_death_test_child = false;\n# endif\n\n// Returns a Boolean value indicating whether the caller is currently\n// executing in the context of the death test child process.  Tools such as\n// Valgrind heap checkers may need this to modify their behavior in death\n// tests.  IMPORTANT: This is an internal utility.  Using it may break the\n// implementation of death tests.  User code MUST NOT use it.\nbool InDeathTestChild() {\n# if GTEST_OS_WINDOWS\n\n  // On Windows, death tests are thread-safe regardless of the value of the\n  // death_test_style flag.\n  return !GTEST_FLAG(internal_run_death_test).empty();\n\n# else\n\n  if (GTEST_FLAG(death_test_style) == \"threadsafe\")\n    return !GTEST_FLAG(internal_run_death_test).empty();\n  else\n    return g_in_fast_death_test_child;\n#endif\n}\n\n}  // namespace internal\n\n// ExitedWithCode constructor.\nExitedWithCode::ExitedWithCode(int exit_code) : exit_code_(exit_code) {\n}\n\n// ExitedWithCode function-call operator.\nbool ExitedWithCode::operator()(int exit_status) const {\n# if GTEST_OS_WINDOWS\n\n  return exit_status == exit_code_;\n\n# else\n\n  return WIFEXITED(exit_status) && WEXITSTATUS(exit_status) == exit_code_;\n\n# endif  // GTEST_OS_WINDOWS\n}\n\n# if !GTEST_OS_WINDOWS\n// KilledBySignal constructor.\nKilledBySignal::KilledBySignal(int signum) : signum_(signum) {\n}\n\n// KilledBySignal function-call operator.\nbool KilledBySignal::operator()(int exit_status) const {\n#  if defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)\n  {\n    bool result;\n    if (GTEST_KILLED_BY_SIGNAL_OVERRIDE_(signum_, exit_status, &result)) {\n      return result;\n    }\n  }\n#  endif  // defined(GTEST_KILLED_BY_SIGNAL_OVERRIDE_)\n  return WIFSIGNALED(exit_status) && WTERMSIG(exit_status) == signum_;\n}\n# endif  // !GTEST_OS_WINDOWS\n\nnamespace internal {\n\n// Utilities needed for death tests.\n\n// Generates a textual description of a given exit code, in the format\n// specified by wait(2).\nstatic std::string ExitSummary(int exit_code) {\n  Message m;\n\n# if GTEST_OS_WINDOWS\n\n  m << \"Exited with exit status \" << exit_code;\n\n# else\n\n  if (WIFEXITED(exit_code)) {\n    m << \"Exited with exit status \" << WEXITSTATUS(exit_code);\n  } else if (WIFSIGNALED(exit_code)) {\n    m << \"Terminated by signal \" << WTERMSIG(exit_code);\n  }\n#  ifdef WCOREDUMP\n  if (WCOREDUMP(exit_code)) {\n    m << \" (core dumped)\";\n  }\n#  endif\n# endif  // GTEST_OS_WINDOWS\n\n  return m.GetString();\n}\n\n// Returns true if exit_status describes a process that was terminated\n// by a signal, or exited normally with a nonzero exit code.\nbool ExitedUnsuccessfully(int exit_status) {\n  return !ExitedWithCode(0)(exit_status);\n}\n\n# if !GTEST_OS_WINDOWS\n// Generates a textual failure message when a death test finds more than\n// one thread running, or cannot determine the number of threads, prior\n// to executing the given statement.  It is the responsibility of the\n// caller not to pass a thread_count of 1.\nstatic std::string DeathTestThreadWarning(size_t thread_count) {\n  Message msg;\n  msg << \"Death tests use fork(), which is unsafe particularly\"\n      << \" in a threaded context. For this test, \" << GTEST_NAME_ << \" \";\n  if (thread_count == 0)\n    msg << \"couldn't detect the number of threads.\";\n  else\n    msg << \"detected \" << thread_count << \" threads.\";\n  return msg.GetString();\n}\n# endif  // !GTEST_OS_WINDOWS\n\n// Flag characters for reporting a death test that did not die.\nstatic const char kDeathTestLived = 'L';\nstatic const char kDeathTestReturned = 'R';\nstatic const char kDeathTestThrew = 'T';\nstatic const char kDeathTestInternalError = 'I';\n\n// An enumeration describing all of the possible ways that a death test can\n// conclude.  DIED means that the process died while executing the test\n// code; LIVED means that process lived beyond the end of the test code;\n// RETURNED means that the test statement attempted to execute a return\n// statement, which is not allowed; THREW means that the test statement\n// returned control by throwing an exception.  IN_PROGRESS means the test\n// has not yet concluded.\n// TODO(vladl@google.com): Unify names and possibly values for\n// AbortReason, DeathTestOutcome, and flag characters above.\nenum DeathTestOutcome { IN_PROGRESS, DIED, LIVED, RETURNED, THREW };\n\n// Routine for aborting the program which is safe to call from an\n// exec-style death test child process, in which case the error\n// message is propagated back to the parent process.  Otherwise, the\n// message is simply printed to stderr.  In either case, the program\n// then exits with status 1.\nvoid DeathTestAbort(const std::string& message) {\n  // On a POSIX system, this function may be called from a threadsafe-style\n  // death test child process, which operates on a very small stack.  Use\n  // the heap for any additional non-minuscule memory requirements.\n  const InternalRunDeathTestFlag* const flag =\n      GetUnitTestImpl()->internal_run_death_test_flag();\n  if (flag != NULL) {\n    FILE* parent = posix::FDOpen(flag->write_fd(), \"w\");\n    fputc(kDeathTestInternalError, parent);\n    fprintf(parent, \"%s\", message.c_str());\n    fflush(parent);\n    _exit(1);\n  } else {\n    fprintf(stderr, \"%s\", message.c_str());\n    fflush(stderr);\n    posix::Abort();\n  }\n}\n\n// A replacement for CHECK that calls DeathTestAbort if the assertion\n// fails.\n# define GTEST_DEATH_TEST_CHECK_(expression) \\\n  do { \\\n    if (!::testing::internal::IsTrue(expression)) { \\\n      DeathTestAbort( \\\n          ::std::string(\"CHECK failed: File \") + __FILE__ +  \", line \" \\\n          + ::testing::internal::StreamableToString(__LINE__) + \": \" \\\n          + #expression); \\\n    } \\\n  } while (::testing::internal::AlwaysFalse())\n\n// This macro is similar to GTEST_DEATH_TEST_CHECK_, but it is meant for\n// evaluating any system call that fulfills two conditions: it must return\n// -1 on failure, and set errno to EINTR when it is interrupted and\n// should be tried again.  The macro expands to a loop that repeatedly\n// evaluates the expression as long as it evaluates to -1 and sets\n// errno to EINTR.  If the expression evaluates to -1 but errno is\n// something other than EINTR, DeathTestAbort is called.\n# define GTEST_DEATH_TEST_CHECK_SYSCALL_(expression) \\\n  do { \\\n    int gtest_retval; \\\n    do { \\\n      gtest_retval = (expression); \\\n    } while (gtest_retval == -1 && errno == EINTR); \\\n    if (gtest_retval == -1) { \\\n      DeathTestAbort( \\\n          ::std::string(\"CHECK failed: File \") + __FILE__ + \", line \" \\\n          + ::testing::internal::StreamableToString(__LINE__) + \": \" \\\n          + #expression + \" != -1\"); \\\n    } \\\n  } while (::testing::internal::AlwaysFalse())\n\n// Returns the message describing the last system error in errno.\nstd::string GetLastErrnoDescription() {\n    return errno == 0 ? \"\" : posix::StrError(errno);\n}\n\n// This is called from a death test parent process to read a failure\n// message from the death test child process and log it with the FATAL\n// severity. On Windows, the message is read from a pipe handle. On other\n// platforms, it is read from a file descriptor.\nstatic void FailFromInternalError(int fd) {\n  Message error;\n  char buffer[256];\n  int num_read;\n\n  do {\n    while ((num_read = posix::Read(fd, buffer, 255)) > 0) {\n      buffer[num_read] = '\\0';\n      error << buffer;\n    }\n  } while (num_read == -1 && errno == EINTR);\n\n  if (num_read == 0) {\n    GTEST_LOG_(FATAL) << error.GetString();\n  } else {\n    const int last_error = errno;\n    GTEST_LOG_(FATAL) << \"Error while reading death test internal: \"\n                      << GetLastErrnoDescription() << \" [\" << last_error << \"]\";\n  }\n}\n\n// Death test constructor.  Increments the running death test count\n// for the current test.\nDeathTest::DeathTest() {\n  TestInfo* const info = GetUnitTestImpl()->current_test_info();\n  if (info == NULL) {\n    DeathTestAbort(\"Cannot run a death test outside of a TEST or \"\n                   \"TEST_F construct\");\n  }\n}\n\n// Creates and returns a death test by dispatching to the current\n// death test factory.\nbool DeathTest::Create(const char* statement, const RE* regex,\n                       const char* file, int line, DeathTest** test) {\n  return GetUnitTestImpl()->death_test_factory()->Create(\n      statement, regex, file, line, test);\n}\n\nconst char* DeathTest::LastMessage() {\n  return last_death_test_message_.c_str();\n}\n\nvoid DeathTest::set_last_death_test_message(const std::string& message) {\n  last_death_test_message_ = message;\n}\n\nstd::string DeathTest::last_death_test_message_;\n\n// Provides cross platform implementation for some death functionality.\nclass DeathTestImpl : public DeathTest {\n protected:\n  DeathTestImpl(const char* a_statement, const RE* a_regex)\n      : statement_(a_statement),\n        regex_(a_regex),\n        spawned_(false),\n        status_(-1),\n        outcome_(IN_PROGRESS),\n        read_fd_(-1),\n        write_fd_(-1) {}\n\n  // read_fd_ is expected to be closed and cleared by a derived class.\n  ~DeathTestImpl() { GTEST_DEATH_TEST_CHECK_(read_fd_ == -1); }\n\n  void Abort(AbortReason reason);\n  virtual bool Passed(bool status_ok);\n\n  const char* statement() const { return statement_; }\n  const RE* regex() const { return regex_; }\n  bool spawned() const { return spawned_; }\n  void set_spawned(bool is_spawned) { spawned_ = is_spawned; }\n  int status() const { return status_; }\n  void set_status(int a_status) { status_ = a_status; }\n  DeathTestOutcome outcome() const { return outcome_; }\n  void set_outcome(DeathTestOutcome an_outcome) { outcome_ = an_outcome; }\n  int read_fd() const { return read_fd_; }\n  void set_read_fd(int fd) { read_fd_ = fd; }\n  int write_fd() const { return write_fd_; }\n  void set_write_fd(int fd) { write_fd_ = fd; }\n\n  // Called in the parent process only. Reads the result code of the death\n  // test child process via a pipe, interprets it to set the outcome_\n  // member, and closes read_fd_.  Outputs diagnostics and terminates in\n  // case of unexpected codes.\n  void ReadAndInterpretStatusByte();\n\n private:\n  // The textual content of the code this object is testing.  This class\n  // doesn't own this string and should not attempt to delete it.\n  const char* const statement_;\n  // The regular expression which test output must match.  DeathTestImpl\n  // doesn't own this object and should not attempt to delete it.\n  const RE* const regex_;\n  // True if the death test child process has been successfully spawned.\n  bool spawned_;\n  // The exit status of the child process.\n  int status_;\n  // How the death test concluded.\n  DeathTestOutcome outcome_;\n  // Descriptor to the read end of the pipe to the child process.  It is\n  // always -1 in the child process.  The child keeps its write end of the\n  // pipe in write_fd_.\n  int read_fd_;\n  // Descriptor to the child's write end of the pipe to the parent process.\n  // It is always -1 in the parent process.  The parent keeps its end of the\n  // pipe in read_fd_.\n  int write_fd_;\n};\n\n// Called in the parent process only. Reads the result code of the death\n// test child process via a pipe, interprets it to set the outcome_\n// member, and closes read_fd_.  Outputs diagnostics and terminates in\n// case of unexpected codes.\nvoid DeathTestImpl::ReadAndInterpretStatusByte() {\n  char flag;\n  int bytes_read;\n\n  // The read() here blocks until data is available (signifying the\n  // failure of the death test) or until the pipe is closed (signifying\n  // its success), so it's okay to call this in the parent before\n  // the child process has exited.\n  do {\n    bytes_read = posix::Read(read_fd(), &flag, 1);\n  } while (bytes_read == -1 && errno == EINTR);\n\n  if (bytes_read == 0) {\n    set_outcome(DIED);\n  } else if (bytes_read == 1) {\n    switch (flag) {\n      case kDeathTestReturned:\n        set_outcome(RETURNED);\n        break;\n      case kDeathTestThrew:\n        set_outcome(THREW);\n        break;\n      case kDeathTestLived:\n        set_outcome(LIVED);\n        break;\n      case kDeathTestInternalError:\n        FailFromInternalError(read_fd());  // Does not return.\n        break;\n      default:\n        GTEST_LOG_(FATAL) << \"Death test child process reported \"\n                          << \"unexpected status byte (\"\n                          << static_cast<unsigned int>(flag) << \")\";\n    }\n  } else {\n    GTEST_LOG_(FATAL) << \"Read from death test child process failed: \"\n                      << GetLastErrnoDescription();\n  }\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Close(read_fd()));\n  set_read_fd(-1);\n}\n\n// Signals that the death test code which should have exited, didn't.\n// Should be called only in a death test child process.\n// Writes a status byte to the child's status file descriptor, then\n// calls _exit(1).\nvoid DeathTestImpl::Abort(AbortReason reason) {\n  // The parent process considers the death test to be a failure if\n  // it finds any data in our pipe.  So, here we write a single flag byte\n  // to the pipe, then exit.\n  const char status_ch =\n      reason == TEST_DID_NOT_DIE ? kDeathTestLived :\n      reason == TEST_THREW_EXCEPTION ? kDeathTestThrew : kDeathTestReturned;\n\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(posix::Write(write_fd(), &status_ch, 1));\n  // We are leaking the descriptor here because on some platforms (i.e.,\n  // when built as Windows DLL), destructors of global objects will still\n  // run after calling _exit(). On such systems, write_fd_ will be\n  // indirectly closed from the destructor of UnitTestImpl, causing double\n  // close if it is also closed here. On debug configurations, double close\n  // may assert. As there are no in-process buffers to flush here, we are\n  // relying on the OS to close the descriptor after the process terminates\n  // when the destructors are not run.\n  _exit(1);  // Exits w/o any normal exit hooks (we were supposed to crash)\n}\n\n// Returns an indented copy of stderr output for a death test.\n// This makes distinguishing death test output lines from regular log lines\n// much easier.\nstatic ::std::string FormatDeathTestOutput(const ::std::string& output) {\n  ::std::string ret;\n  for (size_t at = 0; ; ) {\n    const size_t line_end = output.find('\\n', at);\n    ret += \"[  DEATH   ] \";\n    if (line_end == ::std::string::npos) {\n      ret += output.substr(at);\n      break;\n    }\n    ret += output.substr(at, line_end + 1 - at);\n    at = line_end + 1;\n  }\n  return ret;\n}\n\n// Assesses the success or failure of a death test, using both private\n// members which have previously been set, and one argument:\n//\n// Private data members:\n//   outcome:  An enumeration describing how the death test\n//             concluded: DIED, LIVED, THREW, or RETURNED.  The death test\n//             fails in the latter three cases.\n//   status:   The exit status of the child process. On *nix, it is in the\n//             in the format specified by wait(2). On Windows, this is the\n//             value supplied to the ExitProcess() API or a numeric code\n//             of the exception that terminated the program.\n//   regex:    A regular expression object to be applied to\n//             the test's captured standard error output; the death test\n//             fails if it does not match.\n//\n// Argument:\n//   status_ok: true if exit_status is acceptable in the context of\n//              this particular death test, which fails if it is false\n//\n// Returns true iff all of the above conditions are met.  Otherwise, the\n// first failing condition, in the order given above, is the one that is\n// reported. Also sets the last death test message string.\nbool DeathTestImpl::Passed(bool status_ok) {\n  if (!spawned())\n    return false;\n\n  const std::string error_message = GetCapturedStderr();\n\n  bool success = false;\n  Message buffer;\n\n  buffer << \"Death test: \" << statement() << \"\\n\";\n  switch (outcome()) {\n    case LIVED:\n      buffer << \"    Result: failed to die.\\n\"\n             << \" Error msg:\\n\" << FormatDeathTestOutput(error_message);\n      break;\n    case THREW:\n      buffer << \"    Result: threw an exception.\\n\"\n             << \" Error msg:\\n\" << FormatDeathTestOutput(error_message);\n      break;\n    case RETURNED:\n      buffer << \"    Result: illegal return in test statement.\\n\"\n             << \" Error msg:\\n\" << FormatDeathTestOutput(error_message);\n      break;\n    case DIED:\n      if (status_ok) {\n        const bool matched = RE::PartialMatch(error_message.c_str(), *regex());\n        if (matched) {\n          success = true;\n        } else {\n          buffer << \"    Result: died but not with expected error.\\n\"\n                 << \"  Expected: \" << regex()->pattern() << \"\\n\"\n                 << \"Actual msg:\\n\" << FormatDeathTestOutput(error_message);\n        }\n      } else {\n        buffer << \"    Result: died but not with expected exit code:\\n\"\n               << \"            \" << ExitSummary(status()) << \"\\n\"\n               << \"Actual msg:\\n\" << FormatDeathTestOutput(error_message);\n      }\n      break;\n    case IN_PROGRESS:\n    default:\n      GTEST_LOG_(FATAL)\n          << \"DeathTest::Passed somehow called before conclusion of test\";\n  }\n\n  DeathTest::set_last_death_test_message(buffer.GetString());\n  return success;\n}\n\n# if GTEST_OS_WINDOWS\n// WindowsDeathTest implements death tests on Windows. Due to the\n// specifics of starting new processes on Windows, death tests there are\n// always threadsafe, and Google Test considers the\n// --gtest_death_test_style=fast setting to be equivalent to\n// --gtest_death_test_style=threadsafe there.\n//\n// A few implementation notes:  Like the Linux version, the Windows\n// implementation uses pipes for child-to-parent communication. But due to\n// the specifics of pipes on Windows, some extra steps are required:\n//\n// 1. The parent creates a communication pipe and stores handles to both\n//    ends of it.\n// 2. The parent starts the child and provides it with the information\n//    necessary to acquire the handle to the write end of the pipe.\n// 3. The child acquires the write end of the pipe and signals the parent\n//    using a Windows event.\n// 4. Now the parent can release the write end of the pipe on its side. If\n//    this is done before step 3, the object's reference count goes down to\n//    0 and it is destroyed, preventing the child from acquiring it. The\n//    parent now has to release it, or read operations on the read end of\n//    the pipe will not return when the child terminates.\n// 5. The parent reads child's output through the pipe (outcome code and\n//    any possible error messages) from the pipe, and its stderr and then\n//    determines whether to fail the test.\n//\n// Note: to distinguish Win32 API calls from the local method and function\n// calls, the former are explicitly resolved in the global namespace.\n//\nclass WindowsDeathTest : public DeathTestImpl {\n public:\n  WindowsDeathTest(const char* a_statement,\n                   const RE* a_regex,\n                   const char* file,\n                   int line)\n      : DeathTestImpl(a_statement, a_regex), file_(file), line_(line) {}\n\n  // All of these virtual functions are inherited from DeathTest.\n  virtual int Wait();\n  virtual TestRole AssumeRole();\n\n private:\n  // The name of the file in which the death test is located.\n  const char* const file_;\n  // The line number on which the death test is located.\n  const int line_;\n  // Handle to the write end of the pipe to the child process.\n  AutoHandle write_handle_;\n  // Child process handle.\n  AutoHandle child_handle_;\n  // Event the child process uses to signal the parent that it has\n  // acquired the handle to the write end of the pipe. After seeing this\n  // event the parent can release its own handles to make sure its\n  // ReadFile() calls return when the child terminates.\n  AutoHandle event_handle_;\n};\n\n// Waits for the child in a death test to exit, returning its exit\n// status, or 0 if no child process exists.  As a side effect, sets the\n// outcome data member.\nint WindowsDeathTest::Wait() {\n  if (!spawned())\n    return 0;\n\n  // Wait until the child either signals that it has acquired the write end\n  // of the pipe or it dies.\n  const HANDLE wait_handles[2] = { child_handle_.Get(), event_handle_.Get() };\n  switch (::WaitForMultipleObjects(2,\n                                   wait_handles,\n                                   FALSE,  // Waits for any of the handles.\n                                   INFINITE)) {\n    case WAIT_OBJECT_0:\n    case WAIT_OBJECT_0 + 1:\n      break;\n    default:\n      GTEST_DEATH_TEST_CHECK_(false);  // Should not get here.\n  }\n\n  // The child has acquired the write end of the pipe or exited.\n  // We release the handle on our side and continue.\n  write_handle_.Reset();\n  event_handle_.Reset();\n\n  ReadAndInterpretStatusByte();\n\n  // Waits for the child process to exit if it haven't already. This\n  // returns immediately if the child has already exited, regardless of\n  // whether previous calls to WaitForMultipleObjects synchronized on this\n  // handle or not.\n  GTEST_DEATH_TEST_CHECK_(\n      WAIT_OBJECT_0 == ::WaitForSingleObject(child_handle_.Get(),\n                                             INFINITE));\n  DWORD status_code;\n  GTEST_DEATH_TEST_CHECK_(\n      ::GetExitCodeProcess(child_handle_.Get(), &status_code) != FALSE);\n  child_handle_.Reset();\n  set_status(static_cast<int>(status_code));\n  return status();\n}\n\n// The AssumeRole process for a Windows death test.  It creates a child\n// process with the same executable as the current process to run the\n// death test.  The child process is given the --gtest_filter and\n// --gtest_internal_run_death_test flags such that it knows to run the\n// current death test only.\nDeathTest::TestRole WindowsDeathTest::AssumeRole() {\n  const UnitTestImpl* const impl = GetUnitTestImpl();\n  const InternalRunDeathTestFlag* const flag =\n      impl->internal_run_death_test_flag();\n  const TestInfo* const info = impl->current_test_info();\n  const int death_test_index = info->result()->death_test_count();\n\n  if (flag != NULL) {\n    // ParseInternalRunDeathTestFlag() has performed all the necessary\n    // processing.\n    set_write_fd(flag->write_fd());\n    return EXECUTE_TEST;\n  }\n\n  // WindowsDeathTest uses an anonymous pipe to communicate results of\n  // a death test.\n  SECURITY_ATTRIBUTES handles_are_inheritable = {\n    sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };\n  HANDLE read_handle, write_handle;\n  GTEST_DEATH_TEST_CHECK_(\n      ::CreatePipe(&read_handle, &write_handle, &handles_are_inheritable,\n                   0)  // Default buffer size.\n      != FALSE);\n  set_read_fd(::_open_osfhandle(reinterpret_cast<intptr_t>(read_handle),\n                                O_RDONLY));\n  write_handle_.Reset(write_handle);\n  event_handle_.Reset(::CreateEvent(\n      &handles_are_inheritable,\n      TRUE,    // The event will automatically reset to non-signaled state.\n      FALSE,   // The initial state is non-signalled.\n      NULL));  // The even is unnamed.\n  GTEST_DEATH_TEST_CHECK_(event_handle_.Get() != NULL);\n  const std::string filter_flag =\n      std::string(\"--\") + GTEST_FLAG_PREFIX_ + kFilterFlag + \"=\" +\n      info->test_case_name() + \".\" + info->name();\n  const std::string internal_flag =\n      std::string(\"--\") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag +\n      \"=\" + file_ + \"|\" + StreamableToString(line_) + \"|\" +\n      StreamableToString(death_test_index) + \"|\" +\n      StreamableToString(static_cast<unsigned int>(::GetCurrentProcessId())) +\n      // size_t has the same width as pointers on both 32-bit and 64-bit\n      // Windows platforms.\n      // See http://msdn.microsoft.com/en-us/library/tcxf1dw6.aspx.\n      \"|\" + StreamableToString(reinterpret_cast<size_t>(write_handle)) +\n      \"|\" + StreamableToString(reinterpret_cast<size_t>(event_handle_.Get()));\n\n  char executable_path[_MAX_PATH + 1];  // NOLINT\n  GTEST_DEATH_TEST_CHECK_(\n      _MAX_PATH + 1 != ::GetModuleFileNameA(NULL,\n                                            executable_path,\n                                            _MAX_PATH));\n\n  std::string command_line =\n      std::string(::GetCommandLineA()) + \" \" + filter_flag + \" \\\"\" +\n      internal_flag + \"\\\"\";\n\n  DeathTest::set_last_death_test_message(\"\");\n\n  CaptureStderr();\n  // Flush the log buffers since the log streams are shared with the child.\n  FlushInfoLog();\n\n  // The child process will share the standard handles with the parent.\n  STARTUPINFOA startup_info;\n  memset(&startup_info, 0, sizeof(STARTUPINFO));\n  startup_info.dwFlags = STARTF_USESTDHANDLES;\n  startup_info.hStdInput = ::GetStdHandle(STD_INPUT_HANDLE);\n  startup_info.hStdOutput = ::GetStdHandle(STD_OUTPUT_HANDLE);\n  startup_info.hStdError = ::GetStdHandle(STD_ERROR_HANDLE);\n\n  PROCESS_INFORMATION process_info;\n  GTEST_DEATH_TEST_CHECK_(::CreateProcessA(\n      executable_path,\n      const_cast<char*>(command_line.c_str()),\n      NULL,   // Retuned process handle is not inheritable.\n      NULL,   // Retuned thread handle is not inheritable.\n      TRUE,   // Child inherits all inheritable handles (for write_handle_).\n      0x0,    // Default creation flags.\n      NULL,   // Inherit the parent's environment.\n      UnitTest::GetInstance()->original_working_dir(),\n      &startup_info,\n      &process_info) != FALSE);\n  child_handle_.Reset(process_info.hProcess);\n  ::CloseHandle(process_info.hThread);\n  set_spawned(true);\n  return OVERSEE_TEST;\n}\n# else  // We are not on Windows.\n\n// ForkingDeathTest provides implementations for most of the abstract\n// methods of the DeathTest interface.  Only the AssumeRole method is\n// left undefined.\nclass ForkingDeathTest : public DeathTestImpl {\n public:\n  ForkingDeathTest(const char* statement, const RE* regex);\n\n  // All of these virtual functions are inherited from DeathTest.\n  virtual int Wait();\n\n protected:\n  void set_child_pid(pid_t child_pid) { child_pid_ = child_pid; }\n\n private:\n  // PID of child process during death test; 0 in the child process itself.\n  pid_t child_pid_;\n};\n\n// Constructs a ForkingDeathTest.\nForkingDeathTest::ForkingDeathTest(const char* a_statement, const RE* a_regex)\n    : DeathTestImpl(a_statement, a_regex),\n      child_pid_(-1) {}\n\n// Waits for the child in a death test to exit, returning its exit\n// status, or 0 if no child process exists.  As a side effect, sets the\n// outcome data member.\nint ForkingDeathTest::Wait() {\n  if (!spawned())\n    return 0;\n\n  ReadAndInterpretStatusByte();\n\n  int status_value;\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(waitpid(child_pid_, &status_value, 0));\n  set_status(status_value);\n  return status_value;\n}\n\n// A concrete death test class that forks, then immediately runs the test\n// in the child process.\nclass NoExecDeathTest : public ForkingDeathTest {\n public:\n  NoExecDeathTest(const char* a_statement, const RE* a_regex) :\n      ForkingDeathTest(a_statement, a_regex) { }\n  virtual TestRole AssumeRole();\n};\n\n// The AssumeRole process for a fork-and-run death test.  It implements a\n// straightforward fork, with a simple pipe to transmit the status byte.\nDeathTest::TestRole NoExecDeathTest::AssumeRole() {\n  const size_t thread_count = GetThreadCount();\n  if (thread_count != 1) {\n    GTEST_LOG_(WARNING) << DeathTestThreadWarning(thread_count);\n  }\n\n  int pipe_fd[2];\n  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);\n\n  DeathTest::set_last_death_test_message(\"\");\n  CaptureStderr();\n  // When we fork the process below, the log file buffers are copied, but the\n  // file descriptors are shared.  We flush all log files here so that closing\n  // the file descriptors in the child process doesn't throw off the\n  // synchronization between descriptors and buffers in the parent process.\n  // This is as close to the fork as possible to avoid a race condition in case\n  // there are multiple threads running before the death test, and another\n  // thread writes to the log file.\n  FlushInfoLog();\n\n  const pid_t child_pid = fork();\n  GTEST_DEATH_TEST_CHECK_(child_pid != -1);\n  set_child_pid(child_pid);\n  if (child_pid == 0) {\n    GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[0]));\n    set_write_fd(pipe_fd[1]);\n    // Redirects all logging to stderr in the child process to prevent\n    // concurrent writes to the log files.  We capture stderr in the parent\n    // process and append the child process' output to a log.\n    LogToStderr();\n    // Event forwarding to the listeners of event listener API mush be shut\n    // down in death test subprocesses.\n    GetUnitTestImpl()->listeners()->SuppressEventForwarding();\n    g_in_fast_death_test_child = true;\n    return EXECUTE_TEST;\n  } else {\n    GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));\n    set_read_fd(pipe_fd[0]);\n    set_spawned(true);\n    return OVERSEE_TEST;\n  }\n}\n\n// A concrete death test class that forks and re-executes the main\n// program from the beginning, with command-line flags set that cause\n// only this specific death test to be run.\nclass ExecDeathTest : public ForkingDeathTest {\n public:\n  ExecDeathTest(const char* a_statement, const RE* a_regex,\n                const char* file, int line) :\n      ForkingDeathTest(a_statement, a_regex), file_(file), line_(line) { }\n  virtual TestRole AssumeRole();\n private:\n  static ::std::vector<testing::internal::string>\n  GetArgvsForDeathTestChildProcess() {\n    ::std::vector<testing::internal::string> args = GetInjectableArgvs();\n#  if defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)\n    ::std::vector<testing::internal::string> extra_args =\n        GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_();\n    args.insert(args.end(), extra_args.begin(), extra_args.end());\n#  endif  // defined(GTEST_EXTRA_DEATH_TEST_COMMAND_LINE_ARGS_)\n    return args;\n  }\n  // The name of the file in which the death test is located.\n  const char* const file_;\n  // The line number on which the death test is located.\n  const int line_;\n};\n\n// Utility class for accumulating command-line arguments.\nclass Arguments {\n public:\n  Arguments() {\n    args_.push_back(NULL);\n  }\n\n  ~Arguments() {\n    for (std::vector<char*>::iterator i = args_.begin(); i != args_.end();\n         ++i) {\n      free(*i);\n    }\n  }\n  void AddArgument(const char* argument) {\n    args_.insert(args_.end() - 1, posix::StrDup(argument));\n  }\n\n  template <typename Str>\n  void AddArguments(const ::std::vector<Str>& arguments) {\n    for (typename ::std::vector<Str>::const_iterator i = arguments.begin();\n         i != arguments.end();\n         ++i) {\n      args_.insert(args_.end() - 1, posix::StrDup(i->c_str()));\n    }\n  }\n  char* const* Argv() {\n    return &args_[0];\n  }\n\n private:\n  std::vector<char*> args_;\n};\n\n// A struct that encompasses the arguments to the child process of a\n// threadsafe-style death test process.\nstruct ExecDeathTestArgs {\n  char* const* argv;  // Command-line arguments for the child's call to exec\n  int close_fd;       // File descriptor to close; the read end of a pipe\n};\n\n#  if GTEST_OS_MAC\ninline char** GetEnviron() {\n  // When Google Test is built as a framework on MacOS X, the environ variable\n  // is unavailable. Apple's documentation (man environ) recommends using\n  // _NSGetEnviron() instead.\n  return *_NSGetEnviron();\n}\n#  else\n// Some POSIX platforms expect you to declare environ. extern \"C\" makes\n// it reside in the global namespace.\nextern \"C\" char** environ;\ninline char** GetEnviron() { return environ; }\n#  endif  // GTEST_OS_MAC\n\n#  if !GTEST_OS_QNX\n// The main function for a threadsafe-style death test child process.\n// This function is called in a clone()-ed process and thus must avoid\n// any potentially unsafe operations like malloc or libc functions.\nstatic int ExecDeathTestChildMain(void* child_arg) {\n  ExecDeathTestArgs* const args = static_cast<ExecDeathTestArgs*>(child_arg);\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(args->close_fd));\n\n  // We need to execute the test program in the same environment where\n  // it was originally invoked.  Therefore we change to the original\n  // working directory first.\n  const char* const original_dir =\n      UnitTest::GetInstance()->original_working_dir();\n  // We can safely call chdir() as it's a direct system call.\n  if (chdir(original_dir) != 0) {\n    DeathTestAbort(std::string(\"chdir(\\\"\") + original_dir + \"\\\") failed: \" +\n                   GetLastErrnoDescription());\n    return EXIT_FAILURE;\n  }\n\n  // We can safely call execve() as it's a direct system call.  We\n  // cannot use execvp() as it's a libc function and thus potentially\n  // unsafe.  Since execve() doesn't search the PATH, the user must\n  // invoke the test program via a valid path that contains at least\n  // one path separator.\n  execve(args->argv[0], args->argv, GetEnviron());\n  DeathTestAbort(std::string(\"execve(\") + args->argv[0] + \", ...) in \" +\n                 original_dir + \" failed: \" +\n                 GetLastErrnoDescription());\n  return EXIT_FAILURE;\n}\n#  endif  // !GTEST_OS_QNX\n\n// Two utility routines that together determine the direction the stack\n// grows.\n// This could be accomplished more elegantly by a single recursive\n// function, but we want to guard against the unlikely possibility of\n// a smart compiler optimizing the recursion away.\n//\n// GTEST_NO_INLINE_ is required to prevent GCC 4.6 from inlining\n// StackLowerThanAddress into StackGrowsDown, which then doesn't give\n// correct answer.\nvoid StackLowerThanAddress(const void* ptr, bool* result) GTEST_NO_INLINE_;\nvoid StackLowerThanAddress(const void* ptr, bool* result) {\n  int dummy;\n  *result = (&dummy < ptr);\n}\n\n// Make sure AddressSanitizer does not tamper with the stack here.\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nbool StackGrowsDown() {\n  int dummy;\n  bool result;\n  StackLowerThanAddress(&dummy, &result);\n  return result;\n}\n\n// Spawns a child process with the same executable as the current process in\n// a thread-safe manner and instructs it to run the death test.  The\n// implementation uses fork(2) + exec.  On systems where clone(2) is\n// available, it is used instead, being slightly more thread-safe.  On QNX,\n// fork supports only single-threaded environments, so this function uses\n// spawn(2) there instead.  The function dies with an error message if\n// anything goes wrong.\nstatic pid_t ExecDeathTestSpawnChild(char* const* argv, int close_fd) {\n  ExecDeathTestArgs args = { argv, close_fd };\n  pid_t child_pid = -1;\n\n#  if GTEST_OS_QNX\n  // Obtains the current directory and sets it to be closed in the child\n  // process.\n  const int cwd_fd = open(\".\", O_RDONLY);\n  GTEST_DEATH_TEST_CHECK_(cwd_fd != -1);\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(cwd_fd, F_SETFD, FD_CLOEXEC));\n  // We need to execute the test program in the same environment where\n  // it was originally invoked.  Therefore we change to the original\n  // working directory first.\n  const char* const original_dir =\n      UnitTest::GetInstance()->original_working_dir();\n  // We can safely call chdir() as it's a direct system call.\n  if (chdir(original_dir) != 0) {\n    DeathTestAbort(std::string(\"chdir(\\\"\") + original_dir + \"\\\") failed: \" +\n                   GetLastErrnoDescription());\n    return EXIT_FAILURE;\n  }\n\n  int fd_flags;\n  // Set close_fd to be closed after spawn.\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(fd_flags = fcntl(close_fd, F_GETFD));\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(fcntl(close_fd, F_SETFD,\n                                        fd_flags | FD_CLOEXEC));\n  struct inheritance inherit = {0};\n  // spawn is a system call.\n  child_pid = spawn(args.argv[0], 0, NULL, &inherit, args.argv, GetEnviron());\n  // Restores the current working directory.\n  GTEST_DEATH_TEST_CHECK_(fchdir(cwd_fd) != -1);\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(cwd_fd));\n\n#  else   // GTEST_OS_QNX\n#   if GTEST_OS_LINUX\n  // When a SIGPROF signal is received while fork() or clone() are executing,\n  // the process may hang. To avoid this, we ignore SIGPROF here and re-enable\n  // it after the call to fork()/clone() is complete.\n  struct sigaction saved_sigprof_action;\n  struct sigaction ignore_sigprof_action;\n  memset(&ignore_sigprof_action, 0, sizeof(ignore_sigprof_action));\n  sigemptyset(&ignore_sigprof_action.sa_mask);\n  ignore_sigprof_action.sa_handler = SIG_IGN;\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(sigaction(\n      SIGPROF, &ignore_sigprof_action, &saved_sigprof_action));\n#   endif  // GTEST_OS_LINUX\n\n#   if GTEST_HAS_CLONE\n  const bool use_fork = GTEST_FLAG(death_test_use_fork);\n\n  if (!use_fork) {\n    static const bool stack_grows_down = StackGrowsDown();\n    const size_t stack_size = getpagesize();\n    // MMAP_ANONYMOUS is not defined on Mac, so we use MAP_ANON instead.\n    void* const stack = mmap(NULL, stack_size, PROT_READ | PROT_WRITE,\n                             MAP_ANON | MAP_PRIVATE, -1, 0);\n    GTEST_DEATH_TEST_CHECK_(stack != MAP_FAILED);\n\n    // Maximum stack alignment in bytes:  For a downward-growing stack, this\n    // amount is subtracted from size of the stack space to get an address\n    // that is within the stack space and is aligned on all systems we care\n    // about.  As far as I know there is no ABI with stack alignment greater\n    // than 64.  We assume stack and stack_size already have alignment of\n    // kMaxStackAlignment.\n    const size_t kMaxStackAlignment = 64;\n    void* const stack_top =\n        static_cast<char*>(stack) +\n            (stack_grows_down ? stack_size - kMaxStackAlignment : 0);\n    GTEST_DEATH_TEST_CHECK_(stack_size > kMaxStackAlignment &&\n        reinterpret_cast<intptr_t>(stack_top) % kMaxStackAlignment == 0);\n\n    child_pid = clone(&ExecDeathTestChildMain, stack_top, SIGCHLD, &args);\n\n    GTEST_DEATH_TEST_CHECK_(munmap(stack, stack_size) != -1);\n  }\n#   else\n  const bool use_fork = true;\n#   endif  // GTEST_HAS_CLONE\n\n  if (use_fork && (child_pid = fork()) == 0) {\n      ExecDeathTestChildMain(&args);\n      _exit(0);\n  }\n#  endif  // GTEST_OS_QNX\n#  if GTEST_OS_LINUX\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(\n      sigaction(SIGPROF, &saved_sigprof_action, NULL));\n#  endif  // GTEST_OS_LINUX\n\n  GTEST_DEATH_TEST_CHECK_(child_pid != -1);\n  return child_pid;\n}\n\n// The AssumeRole process for a fork-and-exec death test.  It re-executes the\n// main program from the beginning, setting the --gtest_filter\n// and --gtest_internal_run_death_test flags to cause only the current\n// death test to be re-run.\nDeathTest::TestRole ExecDeathTest::AssumeRole() {\n  const UnitTestImpl* const impl = GetUnitTestImpl();\n  const InternalRunDeathTestFlag* const flag =\n      impl->internal_run_death_test_flag();\n  const TestInfo* const info = impl->current_test_info();\n  const int death_test_index = info->result()->death_test_count();\n\n  if (flag != NULL) {\n    set_write_fd(flag->write_fd());\n    return EXECUTE_TEST;\n  }\n\n  int pipe_fd[2];\n  GTEST_DEATH_TEST_CHECK_(pipe(pipe_fd) != -1);\n  // Clear the close-on-exec flag on the write end of the pipe, lest\n  // it be closed when the child process does an exec:\n  GTEST_DEATH_TEST_CHECK_(fcntl(pipe_fd[1], F_SETFD, 0) != -1);\n\n  const std::string filter_flag =\n      std::string(\"--\") + GTEST_FLAG_PREFIX_ + kFilterFlag + \"=\"\n      + info->test_case_name() + \".\" + info->name();\n  const std::string internal_flag =\n      std::string(\"--\") + GTEST_FLAG_PREFIX_ + kInternalRunDeathTestFlag + \"=\"\n      + file_ + \"|\" + StreamableToString(line_) + \"|\"\n      + StreamableToString(death_test_index) + \"|\"\n      + StreamableToString(pipe_fd[1]);\n  Arguments args;\n  args.AddArguments(GetArgvsForDeathTestChildProcess());\n  args.AddArgument(filter_flag.c_str());\n  args.AddArgument(internal_flag.c_str());\n\n  DeathTest::set_last_death_test_message(\"\");\n\n  CaptureStderr();\n  // See the comment in NoExecDeathTest::AssumeRole for why the next line\n  // is necessary.\n  FlushInfoLog();\n\n  const pid_t child_pid = ExecDeathTestSpawnChild(args.Argv(), pipe_fd[0]);\n  GTEST_DEATH_TEST_CHECK_SYSCALL_(close(pipe_fd[1]));\n  set_child_pid(child_pid);\n  set_read_fd(pipe_fd[0]);\n  set_spawned(true);\n  return OVERSEE_TEST;\n}\n\n# endif  // !GTEST_OS_WINDOWS\n\n// Creates a concrete DeathTest-derived class that depends on the\n// --gtest_death_test_style flag, and sets the pointer pointed to\n// by the \"test\" argument to its address.  If the test should be\n// skipped, sets that pointer to NULL.  Returns true, unless the\n// flag is set to an invalid value.\nbool DefaultDeathTestFactory::Create(const char* statement, const RE* regex,\n                                     const char* file, int line,\n                                     DeathTest** test) {\n  UnitTestImpl* const impl = GetUnitTestImpl();\n  const InternalRunDeathTestFlag* const flag =\n      impl->internal_run_death_test_flag();\n  const int death_test_index = impl->current_test_info()\n      ->increment_death_test_count();\n\n  if (flag != NULL) {\n    if (death_test_index > flag->index()) {\n      DeathTest::set_last_death_test_message(\n          \"Death test count (\" + StreamableToString(death_test_index)\n          + \") somehow exceeded expected maximum (\"\n          + StreamableToString(flag->index()) + \")\");\n      return false;\n    }\n\n    if (!(flag->file() == file && flag->line() == line &&\n          flag->index() == death_test_index)) {\n      *test = NULL;\n      return true;\n    }\n  }\n\n# if GTEST_OS_WINDOWS\n\n  if (GTEST_FLAG(death_test_style) == \"threadsafe\" ||\n      GTEST_FLAG(death_test_style) == \"fast\") {\n    *test = new WindowsDeathTest(statement, regex, file, line);\n  }\n\n# else\n\n  if (GTEST_FLAG(death_test_style) == \"threadsafe\") {\n    *test = new ExecDeathTest(statement, regex, file, line);\n  } else if (GTEST_FLAG(death_test_style) == \"fast\") {\n    *test = new NoExecDeathTest(statement, regex);\n  }\n\n# endif  // GTEST_OS_WINDOWS\n\n  else {  // NOLINT - this is more readable than unbalanced brackets inside #if.\n    DeathTest::set_last_death_test_message(\n        \"Unknown death test style \\\"\" + GTEST_FLAG(death_test_style)\n        + \"\\\" encountered\");\n    return false;\n  }\n\n  return true;\n}\n\n# if GTEST_OS_WINDOWS\n// Recreates the pipe and event handles from the provided parameters,\n// signals the event, and returns a file descriptor wrapped around the pipe\n// handle. This function is called in the child process only.\nint GetStatusFileDescriptor(unsigned int parent_process_id,\n                            size_t write_handle_as_size_t,\n                            size_t event_handle_as_size_t) {\n  AutoHandle parent_process_handle(::OpenProcess(PROCESS_DUP_HANDLE,\n                                                   FALSE,  // Non-inheritable.\n                                                   parent_process_id));\n  if (parent_process_handle.Get() == INVALID_HANDLE_VALUE) {\n    DeathTestAbort(\"Unable to open parent process \" +\n                   StreamableToString(parent_process_id));\n  }\n\n  // TODO(vladl@google.com): Replace the following check with a\n  // compile-time assertion when available.\n  GTEST_CHECK_(sizeof(HANDLE) <= sizeof(size_t));\n\n  const HANDLE write_handle =\n      reinterpret_cast<HANDLE>(write_handle_as_size_t);\n  HANDLE dup_write_handle;\n\n  // The newly initialized handle is accessible only in in the parent\n  // process. To obtain one accessible within the child, we need to use\n  // DuplicateHandle.\n  if (!::DuplicateHandle(parent_process_handle.Get(), write_handle,\n                         ::GetCurrentProcess(), &dup_write_handle,\n                         0x0,    // Requested privileges ignored since\n                                 // DUPLICATE_SAME_ACCESS is used.\n                         FALSE,  // Request non-inheritable handler.\n                         DUPLICATE_SAME_ACCESS)) {\n    DeathTestAbort(\"Unable to duplicate the pipe handle \" +\n                   StreamableToString(write_handle_as_size_t) +\n                   \" from the parent process \" +\n                   StreamableToString(parent_process_id));\n  }\n\n  const HANDLE event_handle = reinterpret_cast<HANDLE>(event_handle_as_size_t);\n  HANDLE dup_event_handle;\n\n  if (!::DuplicateHandle(parent_process_handle.Get(), event_handle,\n                         ::GetCurrentProcess(), &dup_event_handle,\n                         0x0,\n                         FALSE,\n                         DUPLICATE_SAME_ACCESS)) {\n    DeathTestAbort(\"Unable to duplicate the event handle \" +\n                   StreamableToString(event_handle_as_size_t) +\n                   \" from the parent process \" +\n                   StreamableToString(parent_process_id));\n  }\n\n  const int write_fd =\n      ::_open_osfhandle(reinterpret_cast<intptr_t>(dup_write_handle), O_APPEND);\n  if (write_fd == -1) {\n    DeathTestAbort(\"Unable to convert pipe handle \" +\n                   StreamableToString(write_handle_as_size_t) +\n                   \" to a file descriptor\");\n  }\n\n  // Signals the parent that the write end of the pipe has been acquired\n  // so the parent can release its own write end.\n  ::SetEvent(dup_event_handle);\n\n  return write_fd;\n}\n# endif  // GTEST_OS_WINDOWS\n\n// Returns a newly created InternalRunDeathTestFlag object with fields\n// initialized from the GTEST_FLAG(internal_run_death_test) flag if\n// the flag is specified; otherwise returns NULL.\nInternalRunDeathTestFlag* ParseInternalRunDeathTestFlag() {\n  if (GTEST_FLAG(internal_run_death_test) == \"\") return NULL;\n\n  // GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we\n  // can use it here.\n  int line = -1;\n  int index = -1;\n  ::std::vector< ::std::string> fields;\n  SplitString(GTEST_FLAG(internal_run_death_test).c_str(), '|', &fields);\n  int write_fd = -1;\n\n# if GTEST_OS_WINDOWS\n\n  unsigned int parent_process_id = 0;\n  size_t write_handle_as_size_t = 0;\n  size_t event_handle_as_size_t = 0;\n\n  if (fields.size() != 6\n      || !ParseNaturalNumber(fields[1], &line)\n      || !ParseNaturalNumber(fields[2], &index)\n      || !ParseNaturalNumber(fields[3], &parent_process_id)\n      || !ParseNaturalNumber(fields[4], &write_handle_as_size_t)\n      || !ParseNaturalNumber(fields[5], &event_handle_as_size_t)) {\n    DeathTestAbort(\"Bad --gtest_internal_run_death_test flag: \" +\n                   GTEST_FLAG(internal_run_death_test));\n  }\n  write_fd = GetStatusFileDescriptor(parent_process_id,\n                                     write_handle_as_size_t,\n                                     event_handle_as_size_t);\n# else\n\n  if (fields.size() != 4\n      || !ParseNaturalNumber(fields[1], &line)\n      || !ParseNaturalNumber(fields[2], &index)\n      || !ParseNaturalNumber(fields[3], &write_fd)) {\n    DeathTestAbort(\"Bad --gtest_internal_run_death_test flag: \"\n        + GTEST_FLAG(internal_run_death_test));\n  }\n\n# endif  // GTEST_OS_WINDOWS\n\n  return new InternalRunDeathTestFlag(fields[0], line, index, write_fd);\n}\n\n}  // namespace internal\n\n#endif  // GTEST_HAS_DEATH_TEST\n\n}  // namespace testing\n"
  },
  {
    "path": "mypyc/external/googletest/src/gtest-filepath.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Authors: keith.ray@gmail.com (Keith Ray)\n\n#include \"gtest/gtest-message.h\"\n#include \"gtest/internal/gtest-filepath.h\"\n#include \"gtest/internal/gtest-port.h\"\n\n#include <stdlib.h>\n\n#if GTEST_OS_WINDOWS_MOBILE\n# include <windows.h>\n#elif GTEST_OS_WINDOWS\n# include <direct.h>\n# include <io.h>\n#elif GTEST_OS_SYMBIAN\n// Symbian OpenC has PATH_MAX in sys/syslimits.h\n# include <sys/syslimits.h>\n#else\n# include <limits.h>\n# include <climits>  // Some Linux distributions define PATH_MAX here.\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n#if GTEST_OS_WINDOWS\n# define GTEST_PATH_MAX_ _MAX_PATH\n#elif defined(PATH_MAX)\n# define GTEST_PATH_MAX_ PATH_MAX\n#elif defined(_XOPEN_PATH_MAX)\n# define GTEST_PATH_MAX_ _XOPEN_PATH_MAX\n#else\n# define GTEST_PATH_MAX_ _POSIX_PATH_MAX\n#endif  // GTEST_OS_WINDOWS\n\n#include \"gtest/internal/gtest-string.h\"\n\nnamespace testing {\nnamespace internal {\n\n#if GTEST_OS_WINDOWS\n// On Windows, '\\\\' is the standard path separator, but many tools and the\n// Windows API also accept '/' as an alternate path separator. Unless otherwise\n// noted, a file path can contain either kind of path separators, or a mixture\n// of them.\nconst char kPathSeparator = '\\\\';\nconst char kAlternatePathSeparator = '/';\nconst char kAlternatePathSeparatorString[] = \"/\";\n# if GTEST_OS_WINDOWS_MOBILE\n// Windows CE doesn't have a current directory. You should not use\n// the current directory in tests on Windows CE, but this at least\n// provides a reasonable fallback.\nconst char kCurrentDirectoryString[] = \"\\\\\";\n// Windows CE doesn't define INVALID_FILE_ATTRIBUTES\nconst DWORD kInvalidFileAttributes = 0xffffffff;\n# else\nconst char kCurrentDirectoryString[] = \".\\\\\";\n# endif  // GTEST_OS_WINDOWS_MOBILE\n#else\nconst char kPathSeparator = '/';\nconst char kCurrentDirectoryString[] = \"./\";\n#endif  // GTEST_OS_WINDOWS\n\n// Returns whether the given character is a valid path separator.\nstatic bool IsPathSeparator(char c) {\n#if GTEST_HAS_ALT_PATH_SEP_\n  return (c == kPathSeparator) || (c == kAlternatePathSeparator);\n#else\n  return c == kPathSeparator;\n#endif\n}\n\n// Returns the current working directory, or \"\" if unsuccessful.\nFilePath FilePath::GetCurrentDir() {\n#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT\n  // Windows CE doesn't have a current directory, so we just return\n  // something reasonable.\n  return FilePath(kCurrentDirectoryString);\n#elif GTEST_OS_WINDOWS\n  char cwd[GTEST_PATH_MAX_ + 1] = { '\\0' };\n  return FilePath(_getcwd(cwd, sizeof(cwd)) == NULL ? \"\" : cwd);\n#else\n  char cwd[GTEST_PATH_MAX_ + 1] = { '\\0' };\n  char* result = getcwd(cwd, sizeof(cwd));\n# if GTEST_OS_NACL\n  // getcwd will likely fail in NaCl due to the sandbox, so return something\n  // reasonable. The user may have provided a shim implementation for getcwd,\n  // however, so fallback only when failure is detected.\n  return FilePath(result == NULL ? kCurrentDirectoryString : cwd);\n# endif  // GTEST_OS_NACL\n  return FilePath(result == NULL ? \"\" : cwd);\n#endif  // GTEST_OS_WINDOWS_MOBILE\n}\n\n// Returns a copy of the FilePath with the case-insensitive extension removed.\n// Example: FilePath(\"dir/file.exe\").RemoveExtension(\"EXE\") returns\n// FilePath(\"dir/file\"). If a case-insensitive extension is not\n// found, returns a copy of the original FilePath.\nFilePath FilePath::RemoveExtension(const char* extension) const {\n  const std::string dot_extension = std::string(\".\") + extension;\n  if (String::EndsWithCaseInsensitive(pathname_, dot_extension)) {\n    return FilePath(pathname_.substr(\n        0, pathname_.length() - dot_extension.length()));\n  }\n  return *this;\n}\n\n// Returns a pointer to the last occurence of a valid path separator in\n// the FilePath. On Windows, for example, both '/' and '\\' are valid path\n// separators. Returns NULL if no path separator was found.\nconst char* FilePath::FindLastPathSeparator() const {\n  const char* const last_sep = strrchr(c_str(), kPathSeparator);\n#if GTEST_HAS_ALT_PATH_SEP_\n  const char* const last_alt_sep = strrchr(c_str(), kAlternatePathSeparator);\n  // Comparing two pointers of which only one is NULL is undefined.\n  if (last_alt_sep != NULL &&\n      (last_sep == NULL || last_alt_sep > last_sep)) {\n    return last_alt_sep;\n  }\n#endif\n  return last_sep;\n}\n\n// Returns a copy of the FilePath with the directory part removed.\n// Example: FilePath(\"path/to/file\").RemoveDirectoryName() returns\n// FilePath(\"file\"). If there is no directory part (\"just_a_file\"), it returns\n// the FilePath unmodified. If there is no file part (\"just_a_dir/\") it\n// returns an empty FilePath (\"\").\n// On Windows platform, '\\' is the path separator, otherwise it is '/'.\nFilePath FilePath::RemoveDirectoryName() const {\n  const char* const last_sep = FindLastPathSeparator();\n  return last_sep ? FilePath(last_sep + 1) : *this;\n}\n\n// RemoveFileName returns the directory path with the filename removed.\n// Example: FilePath(\"path/to/file\").RemoveFileName() returns \"path/to/\".\n// If the FilePath is \"a_file\" or \"/a_file\", RemoveFileName returns\n// FilePath(\"./\") or, on Windows, FilePath(\".\\\\\"). If the filepath does\n// not have a file, like \"just/a/dir/\", it returns the FilePath unmodified.\n// On Windows platform, '\\' is the path separator, otherwise it is '/'.\nFilePath FilePath::RemoveFileName() const {\n  const char* const last_sep = FindLastPathSeparator();\n  std::string dir;\n  if (last_sep) {\n    dir = std::string(c_str(), last_sep + 1 - c_str());\n  } else {\n    dir = kCurrentDirectoryString;\n  }\n  return FilePath(dir);\n}\n\n// Helper functions for naming files in a directory for xml output.\n\n// Given directory = \"dir\", base_name = \"test\", number = 0,\n// extension = \"xml\", returns \"dir/test.xml\". If number is greater\n// than zero (e.g., 12), returns \"dir/test_12.xml\".\n// On Windows platform, uses \\ as the separator rather than /.\nFilePath FilePath::MakeFileName(const FilePath& directory,\n                                const FilePath& base_name,\n                                int number,\n                                const char* extension) {\n  std::string file;\n  if (number == 0) {\n    file = base_name.string() + \".\" + extension;\n  } else {\n    file = base_name.string() + \"_\" + StreamableToString(number)\n        + \".\" + extension;\n  }\n  return ConcatPaths(directory, FilePath(file));\n}\n\n// Given directory = \"dir\", relative_path = \"test.xml\", returns \"dir/test.xml\".\n// On Windows, uses \\ as the separator rather than /.\nFilePath FilePath::ConcatPaths(const FilePath& directory,\n                               const FilePath& relative_path) {\n  if (directory.IsEmpty())\n    return relative_path;\n  const FilePath dir(directory.RemoveTrailingPathSeparator());\n  return FilePath(dir.string() + kPathSeparator + relative_path.string());\n}\n\n// Returns true if pathname describes something findable in the file-system,\n// either a file, directory, or whatever.\nbool FilePath::FileOrDirectoryExists() const {\n#if GTEST_OS_WINDOWS_MOBILE\n  LPCWSTR unicode = String::AnsiToUtf16(pathname_.c_str());\n  const DWORD attributes = GetFileAttributes(unicode);\n  delete [] unicode;\n  return attributes != kInvalidFileAttributes;\n#else\n  posix::StatStruct file_stat;\n  return posix::Stat(pathname_.c_str(), &file_stat) == 0;\n#endif  // GTEST_OS_WINDOWS_MOBILE\n}\n\n// Returns true if pathname describes a directory in the file-system\n// that exists.\nbool FilePath::DirectoryExists() const {\n  bool result = false;\n#if GTEST_OS_WINDOWS\n  // Don't strip off trailing separator if path is a root directory on\n  // Windows (like \"C:\\\\\").\n  const FilePath& path(IsRootDirectory() ? *this :\n                                           RemoveTrailingPathSeparator());\n#else\n  const FilePath& path(*this);\n#endif\n\n#if GTEST_OS_WINDOWS_MOBILE\n  LPCWSTR unicode = String::AnsiToUtf16(path.c_str());\n  const DWORD attributes = GetFileAttributes(unicode);\n  delete [] unicode;\n  if ((attributes != kInvalidFileAttributes) &&\n      (attributes & FILE_ATTRIBUTE_DIRECTORY)) {\n    result = true;\n  }\n#else\n  posix::StatStruct file_stat;\n  result = posix::Stat(path.c_str(), &file_stat) == 0 &&\n      posix::IsDir(file_stat);\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n  return result;\n}\n\n// Returns true if pathname describes a root directory. (Windows has one\n// root directory per disk drive.)\nbool FilePath::IsRootDirectory() const {\n#if GTEST_OS_WINDOWS\n  // TODO(wan@google.com): on Windows a network share like\n  // \\\\server\\share can be a root directory, although it cannot be the\n  // current directory.  Handle this properly.\n  return pathname_.length() == 3 && IsAbsolutePath();\n#else\n  return pathname_.length() == 1 && IsPathSeparator(pathname_.c_str()[0]);\n#endif\n}\n\n// Returns true if pathname describes an absolute path.\nbool FilePath::IsAbsolutePath() const {\n  const char* const name = pathname_.c_str();\n#if GTEST_OS_WINDOWS\n  return pathname_.length() >= 3 &&\n     ((name[0] >= 'a' && name[0] <= 'z') ||\n      (name[0] >= 'A' && name[0] <= 'Z')) &&\n     name[1] == ':' &&\n     IsPathSeparator(name[2]);\n#else\n  return IsPathSeparator(name[0]);\n#endif\n}\n\n// Returns a pathname for a file that does not currently exist. The pathname\n// will be directory/base_name.extension or\n// directory/base_name_<number>.extension if directory/base_name.extension\n// already exists. The number will be incremented until a pathname is found\n// that does not already exist.\n// Examples: 'dir/foo_test.xml' or 'dir/foo_test_1.xml'.\n// There could be a race condition if two or more processes are calling this\n// function at the same time -- they could both pick the same filename.\nFilePath FilePath::GenerateUniqueFileName(const FilePath& directory,\n                                          const FilePath& base_name,\n                                          const char* extension) {\n  FilePath full_pathname;\n  int number = 0;\n  do {\n    full_pathname.Set(MakeFileName(directory, base_name, number++, extension));\n  } while (full_pathname.FileOrDirectoryExists());\n  return full_pathname;\n}\n\n// Returns true if FilePath ends with a path separator, which indicates that\n// it is intended to represent a directory. Returns false otherwise.\n// This does NOT check that a directory (or file) actually exists.\nbool FilePath::IsDirectory() const {\n  return !pathname_.empty() &&\n         IsPathSeparator(pathname_.c_str()[pathname_.length() - 1]);\n}\n\n// Create directories so that path exists. Returns true if successful or if\n// the directories already exist; returns false if unable to create directories\n// for any reason.\nbool FilePath::CreateDirectoriesRecursively() const {\n  if (!this->IsDirectory()) {\n    return false;\n  }\n\n  if (pathname_.length() == 0 || this->DirectoryExists()) {\n    return true;\n  }\n\n  const FilePath parent(this->RemoveTrailingPathSeparator().RemoveFileName());\n  return parent.CreateDirectoriesRecursively() && this->CreateFolder();\n}\n\n// Create the directory so that path exists. Returns true if successful or\n// if the directory already exists; returns false if unable to create the\n// directory for any reason, including if the parent directory does not\n// exist. Not named \"CreateDirectory\" because that's a macro on Windows.\nbool FilePath::CreateFolder() const {\n#if GTEST_OS_WINDOWS_MOBILE\n  FilePath removed_sep(this->RemoveTrailingPathSeparator());\n  LPCWSTR unicode = String::AnsiToUtf16(removed_sep.c_str());\n  int result = CreateDirectory(unicode, NULL) ? 0 : -1;\n  delete [] unicode;\n#elif GTEST_OS_WINDOWS\n  int result = _mkdir(pathname_.c_str());\n#else\n  int result = mkdir(pathname_.c_str(), 0777);\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n  if (result == -1) {\n    return this->DirectoryExists();  // An error is OK if the directory exists.\n  }\n  return true;  // No error.\n}\n\n// If input name has a trailing separator character, remove it and return the\n// name, otherwise return the name string unmodified.\n// On Windows platform, uses \\ as the separator, other platforms use /.\nFilePath FilePath::RemoveTrailingPathSeparator() const {\n  return IsDirectory()\n      ? FilePath(pathname_.substr(0, pathname_.length() - 1))\n      : *this;\n}\n\n// Removes any redundant separators that might be in the pathname.\n// For example, \"bar///foo\" becomes \"bar/foo\". Does not eliminate other\n// redundancies that might be in a pathname involving \".\" or \"..\".\n// TODO(wan@google.com): handle Windows network shares (e.g. \\\\server\\share).\nvoid FilePath::Normalize() {\n  if (pathname_.c_str() == NULL) {\n    pathname_ = \"\";\n    return;\n  }\n  const char* src = pathname_.c_str();\n  char* const dest = new char[pathname_.length() + 1];\n  char* dest_ptr = dest;\n  memset(dest_ptr, 0, pathname_.length() + 1);\n\n  while (*src != '\\0') {\n    *dest_ptr = *src;\n    if (!IsPathSeparator(*src)) {\n      src++;\n    } else {\n#if GTEST_HAS_ALT_PATH_SEP_\n      if (*dest_ptr == kAlternatePathSeparator) {\n        *dest_ptr = kPathSeparator;\n      }\n#endif\n      while (IsPathSeparator(*src))\n        src++;\n    }\n    dest_ptr++;\n  }\n  *dest_ptr = '\\0';\n  pathname_ = dest;\n  delete[] dest;\n}\n\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "mypyc/external/googletest/src/gtest-internal-inl.h",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n// Utility functions and classes used by the Google C++ testing framework.\n//\n// Author: wan@google.com (Zhanyong Wan)\n//\n// This file contains purely Google Test's internal implementation.  Please\n// DO NOT #INCLUDE IT IN A USER PROGRAM.\n\n#ifndef GTEST_SRC_GTEST_INTERNAL_INL_H_\n#define GTEST_SRC_GTEST_INTERNAL_INL_H_\n\n// GTEST_IMPLEMENTATION_ is defined to 1 iff the current translation unit is\n// part of Google Test's implementation; otherwise it's undefined.\n#if !GTEST_IMPLEMENTATION_\n// If this file is included from the user's code, just say no.\n# error \"gtest-internal-inl.h is part of Google Test's internal implementation.\"\n# error \"It must not be included except by Google Test itself.\"\n#endif  // GTEST_IMPLEMENTATION_\n\n#ifndef _WIN32_WCE\n# include <errno.h>\n#endif  // !_WIN32_WCE\n#include <stddef.h>\n#include <stdlib.h>  // For strtoll/_strtoul64/malloc/free.\n#include <string.h>  // For memmove.\n\n#include <algorithm>\n#include <string>\n#include <vector>\n\n#include \"gtest/internal/gtest-port.h\"\n\n#if GTEST_CAN_STREAM_RESULTS_\n# include <arpa/inet.h>  // NOLINT\n# include <netdb.h>  // NOLINT\n#endif\n\n#if GTEST_OS_WINDOWS\n# include <windows.h>  // NOLINT\n#endif  // GTEST_OS_WINDOWS\n\n#include \"gtest/gtest.h\"  // NOLINT\n#include \"gtest/gtest-spi.h\"\n\nnamespace testing {\n\n// Declares the flags.\n//\n// We don't want the users to modify this flag in the code, but want\n// Google Test's own unit tests to be able to access it. Therefore we\n// declare it here as opposed to in gtest.h.\nGTEST_DECLARE_bool_(death_test_use_fork);\n\nnamespace internal {\n\n// The value of GetTestTypeId() as seen from within the Google Test\n// library.  This is solely for testing GetTestTypeId().\nGTEST_API_ extern const TypeId kTestTypeIdInGoogleTest;\n\n// Names of the flags (needed for parsing Google Test flags).\nconst char kAlsoRunDisabledTestsFlag[] = \"also_run_disabled_tests\";\nconst char kBreakOnFailureFlag[] = \"break_on_failure\";\nconst char kCatchExceptionsFlag[] = \"catch_exceptions\";\nconst char kColorFlag[] = \"color\";\nconst char kFilterFlag[] = \"filter\";\nconst char kListTestsFlag[] = \"list_tests\";\nconst char kOutputFlag[] = \"output\";\nconst char kPrintTimeFlag[] = \"print_time\";\nconst char kRandomSeedFlag[] = \"random_seed\";\nconst char kRepeatFlag[] = \"repeat\";\nconst char kShuffleFlag[] = \"shuffle\";\nconst char kStackTraceDepthFlag[] = \"stack_trace_depth\";\nconst char kStreamResultToFlag[] = \"stream_result_to\";\nconst char kThrowOnFailureFlag[] = \"throw_on_failure\";\nconst char kFlagfileFlag[] = \"flagfile\";\n\n// A valid random seed must be in [1, kMaxRandomSeed].\nconst int kMaxRandomSeed = 99999;\n\n// g_help_flag is true iff the --help flag or an equivalent form is\n// specified on the command line.\nGTEST_API_ extern bool g_help_flag;\n\n// Returns the current time in milliseconds.\nGTEST_API_ TimeInMillis GetTimeInMillis();\n\n// Returns true iff Google Test should use colors in the output.\nGTEST_API_ bool ShouldUseColor(bool stdout_is_tty);\n\n// Formats the given time in milliseconds as seconds.\nGTEST_API_ std::string FormatTimeInMillisAsSeconds(TimeInMillis ms);\n\n// Converts the given time in milliseconds to a date string in the ISO 8601\n// format, without the timezone information.  N.B.: due to the use the\n// non-reentrant localtime() function, this function is not thread safe.  Do\n// not use it in any code that can be called from multiple threads.\nGTEST_API_ std::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms);\n\n// Parses a string for an Int32 flag, in the form of \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nGTEST_API_ bool ParseInt32Flag(\n    const char* str, const char* flag, Int32* value);\n\n// Returns a random seed in range [1, kMaxRandomSeed] based on the\n// given --gtest_random_seed flag value.\ninline int GetRandomSeedFromFlag(Int32 random_seed_flag) {\n  const unsigned int raw_seed = (random_seed_flag == 0) ?\n      static_cast<unsigned int>(GetTimeInMillis()) :\n      static_cast<unsigned int>(random_seed_flag);\n\n  // Normalizes the actual seed to range [1, kMaxRandomSeed] such that\n  // it's easy to type.\n  const int normalized_seed =\n      static_cast<int>((raw_seed - 1U) %\n                       static_cast<unsigned int>(kMaxRandomSeed)) + 1;\n  return normalized_seed;\n}\n\n// Returns the first valid random seed after 'seed'.  The behavior is\n// undefined if 'seed' is invalid.  The seed after kMaxRandomSeed is\n// considered to be 1.\ninline int GetNextRandomSeed(int seed) {\n  GTEST_CHECK_(1 <= seed && seed <= kMaxRandomSeed)\n      << \"Invalid random seed \" << seed << \" - must be in [1, \"\n      << kMaxRandomSeed << \"].\";\n  const int next_seed = seed + 1;\n  return (next_seed > kMaxRandomSeed) ? 1 : next_seed;\n}\n\n// This class saves the values of all Google Test flags in its c'tor, and\n// restores them in its d'tor.\nclass GTestFlagSaver {\n public:\n  // The c'tor.\n  GTestFlagSaver() {\n    also_run_disabled_tests_ = GTEST_FLAG(also_run_disabled_tests);\n    break_on_failure_ = GTEST_FLAG(break_on_failure);\n    catch_exceptions_ = GTEST_FLAG(catch_exceptions);\n    color_ = GTEST_FLAG(color);\n    death_test_style_ = GTEST_FLAG(death_test_style);\n    death_test_use_fork_ = GTEST_FLAG(death_test_use_fork);\n    filter_ = GTEST_FLAG(filter);\n    internal_run_death_test_ = GTEST_FLAG(internal_run_death_test);\n    list_tests_ = GTEST_FLAG(list_tests);\n    output_ = GTEST_FLAG(output);\n    print_time_ = GTEST_FLAG(print_time);\n    random_seed_ = GTEST_FLAG(random_seed);\n    repeat_ = GTEST_FLAG(repeat);\n    shuffle_ = GTEST_FLAG(shuffle);\n    stack_trace_depth_ = GTEST_FLAG(stack_trace_depth);\n    stream_result_to_ = GTEST_FLAG(stream_result_to);\n    throw_on_failure_ = GTEST_FLAG(throw_on_failure);\n  }\n\n  // The d'tor is not virtual.  DO NOT INHERIT FROM THIS CLASS.\n  ~GTestFlagSaver() {\n    GTEST_FLAG(also_run_disabled_tests) = also_run_disabled_tests_;\n    GTEST_FLAG(break_on_failure) = break_on_failure_;\n    GTEST_FLAG(catch_exceptions) = catch_exceptions_;\n    GTEST_FLAG(color) = color_;\n    GTEST_FLAG(death_test_style) = death_test_style_;\n    GTEST_FLAG(death_test_use_fork) = death_test_use_fork_;\n    GTEST_FLAG(filter) = filter_;\n    GTEST_FLAG(internal_run_death_test) = internal_run_death_test_;\n    GTEST_FLAG(list_tests) = list_tests_;\n    GTEST_FLAG(output) = output_;\n    GTEST_FLAG(print_time) = print_time_;\n    GTEST_FLAG(random_seed) = random_seed_;\n    GTEST_FLAG(repeat) = repeat_;\n    GTEST_FLAG(shuffle) = shuffle_;\n    GTEST_FLAG(stack_trace_depth) = stack_trace_depth_;\n    GTEST_FLAG(stream_result_to) = stream_result_to_;\n    GTEST_FLAG(throw_on_failure) = throw_on_failure_;\n  }\n\n private:\n  // Fields for saving the original values of flags.\n  bool also_run_disabled_tests_;\n  bool break_on_failure_;\n  bool catch_exceptions_;\n  std::string color_;\n  std::string death_test_style_;\n  bool death_test_use_fork_;\n  std::string filter_;\n  std::string internal_run_death_test_;\n  bool list_tests_;\n  std::string output_;\n  bool print_time_;\n  internal::Int32 random_seed_;\n  internal::Int32 repeat_;\n  bool shuffle_;\n  internal::Int32 stack_trace_depth_;\n  std::string stream_result_to_;\n  bool throw_on_failure_;\n} GTEST_ATTRIBUTE_UNUSED_;\n\n// Converts a Unicode code point to a narrow string in UTF-8 encoding.\n// code_point parameter is of type UInt32 because wchar_t may not be\n// wide enough to contain a code point.\n// If the code_point is not a valid Unicode code point\n// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted\n// to \"(Invalid Unicode 0xXXXXXXXX)\".\nGTEST_API_ std::string CodePointToUtf8(UInt32 code_point);\n\n// Converts a wide string to a narrow string in UTF-8 encoding.\n// The wide string is assumed to have the following encoding:\n//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)\n//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)\n// Parameter str points to a null-terminated wide string.\n// Parameter num_chars may additionally limit the number\n// of wchar_t characters processed. -1 is used when the entire string\n// should be processed.\n// If the string contains code points that are not valid Unicode code points\n// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output\n// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding\n// and contains invalid UTF-16 surrogate pairs, values in those pairs\n// will be encoded as individual Unicode characters from Basic Normal Plane.\nGTEST_API_ std::string WideStringToUtf8(const wchar_t* str, int num_chars);\n\n// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file\n// if the variable is present. If a file already exists at this location, this\n// function will write over it. If the variable is present, but the file cannot\n// be created, prints an error and exits.\nvoid WriteToShardStatusFileIfNeeded();\n\n// Checks whether sharding is enabled by examining the relevant\n// environment variable values. If the variables are present,\n// but inconsistent (e.g., shard_index >= total_shards), prints\n// an error and exits. If in_subprocess_for_death_test, sharding is\n// disabled because it must only be applied to the original test\n// process. Otherwise, we could filter out death tests we intended to execute.\nGTEST_API_ bool ShouldShard(const char* total_shards_str,\n                            const char* shard_index_str,\n                            bool in_subprocess_for_death_test);\n\n// Parses the environment variable var as an Int32. If it is unset,\n// returns default_val. If it is not an Int32, prints an error and\n// and aborts.\nGTEST_API_ Int32 Int32FromEnvOrDie(const char* env_var, Int32 default_val);\n\n// Given the total number of shards, the shard index, and the test id,\n// returns true iff the test should be run on this shard. The test id is\n// some arbitrary but unique non-negative integer assigned to each test\n// method. Assumes that 0 <= shard_index < total_shards.\nGTEST_API_ bool ShouldRunTestOnShard(\n    int total_shards, int shard_index, int test_id);\n\n// STL container utilities.\n\n// Returns the number of elements in the given container that satisfy\n// the given predicate.\ntemplate <class Container, typename Predicate>\ninline int CountIf(const Container& c, Predicate predicate) {\n  // Implemented as an explicit loop since std::count_if() in libCstd on\n  // Solaris has a non-standard signature.\n  int count = 0;\n  for (typename Container::const_iterator it = c.begin(); it != c.end(); ++it) {\n    if (predicate(*it))\n      ++count;\n  }\n  return count;\n}\n\n// Applies a function/functor to each element in the container.\ntemplate <class Container, typename Functor>\nvoid ForEach(const Container& c, Functor functor) {\n  std::for_each(c.begin(), c.end(), functor);\n}\n\n// Returns the i-th element of the vector, or default_value if i is not\n// in range [0, v.size()).\ntemplate <typename E>\ninline E GetElementOr(const std::vector<E>& v, int i, E default_value) {\n  return (i < 0 || i >= static_cast<int>(v.size())) ? default_value : v[i];\n}\n\n// Performs an in-place shuffle of a range of the vector's elements.\n// 'begin' and 'end' are element indices as an STL-style range;\n// i.e. [begin, end) are shuffled, where 'end' == size() means to\n// shuffle to the end of the vector.\ntemplate <typename E>\nvoid ShuffleRange(internal::Random* random, int begin, int end,\n                  std::vector<E>* v) {\n  const int size = static_cast<int>(v->size());\n  GTEST_CHECK_(0 <= begin && begin <= size)\n      << \"Invalid shuffle range start \" << begin << \": must be in range [0, \"\n      << size << \"].\";\n  GTEST_CHECK_(begin <= end && end <= size)\n      << \"Invalid shuffle range finish \" << end << \": must be in range [\"\n      << begin << \", \" << size << \"].\";\n\n  // Fisher-Yates shuffle, from\n  // http://en.wikipedia.org/wiki/Fisher-Yates_shuffle\n  for (int range_width = end - begin; range_width >= 2; range_width--) {\n    const int last_in_range = begin + range_width - 1;\n    const int selected = begin + random->Generate(range_width);\n    std::swap((*v)[selected], (*v)[last_in_range]);\n  }\n}\n\n// Performs an in-place shuffle of the vector's elements.\ntemplate <typename E>\ninline void Shuffle(internal::Random* random, std::vector<E>* v) {\n  ShuffleRange(random, 0, static_cast<int>(v->size()), v);\n}\n\n// A function for deleting an object.  Handy for being used as a\n// functor.\ntemplate <typename T>\nstatic void Delete(T* x) {\n  delete x;\n}\n\n// A predicate that checks the key of a TestProperty against a known key.\n//\n// TestPropertyKeyIs is copyable.\nclass TestPropertyKeyIs {\n public:\n  // Constructor.\n  //\n  // TestPropertyKeyIs has NO default constructor.\n  explicit TestPropertyKeyIs(const std::string& key) : key_(key) {}\n\n  // Returns true iff the test name of test property matches on key_.\n  bool operator()(const TestProperty& test_property) const {\n    return test_property.key() == key_;\n  }\n\n private:\n  std::string key_;\n};\n\n// Class UnitTestOptions.\n//\n// This class contains functions for processing options the user\n// specifies when running the tests.  It has only static members.\n//\n// In most cases, the user can specify an option using either an\n// environment variable or a command line flag.  E.g. you can set the\n// test filter using either GTEST_FILTER or --gtest_filter.  If both\n// the variable and the flag are present, the latter overrides the\n// former.\nclass GTEST_API_ UnitTestOptions {\n public:\n  // Functions for processing the gtest_output flag.\n\n  // Returns the output format, or \"\" for normal printed output.\n  static std::string GetOutputFormat();\n\n  // Returns the absolute path of the requested output file, or the\n  // default (test_detail.xml in the original working directory) if\n  // none was explicitly specified.\n  static std::string GetAbsolutePathToOutputFile();\n\n  // Functions for processing the gtest_filter flag.\n\n  // Returns true iff the wildcard pattern matches the string.  The\n  // first ':' or '\\0' character in pattern marks the end of it.\n  //\n  // This recursive algorithm isn't very efficient, but is clear and\n  // works well enough for matching test names, which are short.\n  static bool PatternMatchesString(const char *pattern, const char *str);\n\n  // Returns true iff the user-specified filter matches the test case\n  // name and the test name.\n  static bool FilterMatchesTest(const std::string &test_case_name,\n                                const std::string &test_name);\n\n#if GTEST_OS_WINDOWS\n  // Function for supporting the gtest_catch_exception flag.\n\n  // Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the\n  // given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.\n  // This function is useful as an __except condition.\n  static int GTestShouldProcessSEH(DWORD exception_code);\n#endif  // GTEST_OS_WINDOWS\n\n  // Returns true if \"name\" matches the ':' separated list of glob-style\n  // filters in \"filter\".\n  static bool MatchesFilter(const std::string& name, const char* filter);\n};\n\n// Returns the current application's name, removing directory path if that\n// is present.  Used by UnitTestOptions::GetOutputFile.\nGTEST_API_ FilePath GetCurrentExecutableName();\n\n// The role interface for getting the OS stack trace as a string.\nclass OsStackTraceGetterInterface {\n public:\n  OsStackTraceGetterInterface() {}\n  virtual ~OsStackTraceGetterInterface() {}\n\n  // Returns the current OS stack trace as an std::string.  Parameters:\n  //\n  //   max_depth  - the maximum number of stack frames to be included\n  //                in the trace.\n  //   skip_count - the number of top frames to be skipped; doesn't count\n  //                against max_depth.\n  virtual string CurrentStackTrace(int max_depth, int skip_count) = 0;\n\n  // UponLeavingGTest() should be called immediately before Google Test calls\n  // user code. It saves some information about the current stack that\n  // CurrentStackTrace() will use to find and hide Google Test stack frames.\n  virtual void UponLeavingGTest() = 0;\n\n  // This string is inserted in place of stack frames that are part of\n  // Google Test's implementation.\n  static const char* const kElidedFramesMarker;\n\n private:\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetterInterface);\n};\n\n// A working implementation of the OsStackTraceGetterInterface interface.\nclass OsStackTraceGetter : public OsStackTraceGetterInterface {\n public:\n  OsStackTraceGetter() {}\n\n  virtual string CurrentStackTrace(int max_depth, int skip_count);\n  virtual void UponLeavingGTest();\n\n private:\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(OsStackTraceGetter);\n};\n\n// Information about a Google Test trace point.\nstruct TraceInfo {\n  const char* file;\n  int line;\n  std::string message;\n};\n\n// This is the default global test part result reporter used in UnitTestImpl.\n// This class should only be used by UnitTestImpl.\nclass DefaultGlobalTestPartResultReporter\n  : public TestPartResultReporterInterface {\n public:\n  explicit DefaultGlobalTestPartResultReporter(UnitTestImpl* unit_test);\n  // Implements the TestPartResultReporterInterface. Reports the test part\n  // result in the current test.\n  virtual void ReportTestPartResult(const TestPartResult& result);\n\n private:\n  UnitTestImpl* const unit_test_;\n\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultGlobalTestPartResultReporter);\n};\n\n// This is the default per thread test part result reporter used in\n// UnitTestImpl. This class should only be used by UnitTestImpl.\nclass DefaultPerThreadTestPartResultReporter\n    : public TestPartResultReporterInterface {\n public:\n  explicit DefaultPerThreadTestPartResultReporter(UnitTestImpl* unit_test);\n  // Implements the TestPartResultReporterInterface. The implementation just\n  // delegates to the current global test part result reporter of *unit_test_.\n  virtual void ReportTestPartResult(const TestPartResult& result);\n\n private:\n  UnitTestImpl* const unit_test_;\n\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(DefaultPerThreadTestPartResultReporter);\n};\n\n// The private implementation of the UnitTest class.  We don't protect\n// the methods under a mutex, as this class is not accessible by a\n// user and the UnitTest class that delegates work to this class does\n// proper locking.\nclass GTEST_API_ UnitTestImpl {\n public:\n  explicit UnitTestImpl(UnitTest* parent);\n  virtual ~UnitTestImpl();\n\n  // There are two different ways to register your own TestPartResultReporter.\n  // You can register your own repoter to listen either only for test results\n  // from the current thread or for results from all threads.\n  // By default, each per-thread test result repoter just passes a new\n  // TestPartResult to the global test result reporter, which registers the\n  // test part result for the currently running test.\n\n  // Returns the global test part result reporter.\n  TestPartResultReporterInterface* GetGlobalTestPartResultReporter();\n\n  // Sets the global test part result reporter.\n  void SetGlobalTestPartResultReporter(\n      TestPartResultReporterInterface* reporter);\n\n  // Returns the test part result reporter for the current thread.\n  TestPartResultReporterInterface* GetTestPartResultReporterForCurrentThread();\n\n  // Sets the test part result reporter for the current thread.\n  void SetTestPartResultReporterForCurrentThread(\n      TestPartResultReporterInterface* reporter);\n\n  // Gets the number of successful test cases.\n  int successful_test_case_count() const;\n\n  // Gets the number of failed test cases.\n  int failed_test_case_count() const;\n\n  // Gets the number of all test cases.\n  int total_test_case_count() const;\n\n  // Gets the number of all test cases that contain at least one test\n  // that should run.\n  int test_case_to_run_count() const;\n\n  // Gets the number of successful tests.\n  int successful_test_count() const;\n\n  // Gets the number of failed tests.\n  int failed_test_count() const;\n\n  // Gets the number of disabled tests that will be reported in the XML report.\n  int reportable_disabled_test_count() const;\n\n  // Gets the number of disabled tests.\n  int disabled_test_count() const;\n\n  // Gets the number of tests to be printed in the XML report.\n  int reportable_test_count() const;\n\n  // Gets the number of all tests.\n  int total_test_count() const;\n\n  // Gets the number of tests that should run.\n  int test_to_run_count() const;\n\n  // Gets the time of the test program start, in ms from the start of the\n  // UNIX epoch.\n  TimeInMillis start_timestamp() const { return start_timestamp_; }\n\n  // Gets the elapsed time, in milliseconds.\n  TimeInMillis elapsed_time() const { return elapsed_time_; }\n\n  // Returns true iff the unit test passed (i.e. all test cases passed).\n  bool Passed() const { return !Failed(); }\n\n  // Returns true iff the unit test failed (i.e. some test case failed\n  // or something outside of all tests failed).\n  bool Failed() const {\n    return failed_test_case_count() > 0 || ad_hoc_test_result()->Failed();\n  }\n\n  // Gets the i-th test case among all the test cases. i can range from 0 to\n  // total_test_case_count() - 1. If i is not in that range, returns NULL.\n  const TestCase* GetTestCase(int i) const {\n    const int index = GetElementOr(test_case_indices_, i, -1);\n    return index < 0 ? NULL : test_cases_[i];\n  }\n\n  // Gets the i-th test case among all the test cases. i can range from 0 to\n  // total_test_case_count() - 1. If i is not in that range, returns NULL.\n  TestCase* GetMutableTestCase(int i) {\n    const int index = GetElementOr(test_case_indices_, i, -1);\n    return index < 0 ? NULL : test_cases_[index];\n  }\n\n  // Provides access to the event listener list.\n  TestEventListeners* listeners() { return &listeners_; }\n\n  // Returns the TestResult for the test that's currently running, or\n  // the TestResult for the ad hoc test if no test is running.\n  TestResult* current_test_result();\n\n  // Returns the TestResult for the ad hoc test.\n  const TestResult* ad_hoc_test_result() const { return &ad_hoc_test_result_; }\n\n  // Sets the OS stack trace getter.\n  //\n  // Does nothing if the input and the current OS stack trace getter\n  // are the same; otherwise, deletes the old getter and makes the\n  // input the current getter.\n  void set_os_stack_trace_getter(OsStackTraceGetterInterface* getter);\n\n  // Returns the current OS stack trace getter if it is not NULL;\n  // otherwise, creates an OsStackTraceGetter, makes it the current\n  // getter, and returns it.\n  OsStackTraceGetterInterface* os_stack_trace_getter();\n\n  // Returns the current OS stack trace as an std::string.\n  //\n  // The maximum number of stack frames to be included is specified by\n  // the gtest_stack_trace_depth flag.  The skip_count parameter\n  // specifies the number of top frames to be skipped, which doesn't\n  // count against the number of frames to be included.\n  //\n  // For example, if Foo() calls Bar(), which in turn calls\n  // CurrentOsStackTraceExceptTop(1), Foo() will be included in the\n  // trace but Bar() and CurrentOsStackTraceExceptTop() won't.\n  std::string CurrentOsStackTraceExceptTop(int skip_count) GTEST_NO_INLINE_;\n\n  // Finds and returns a TestCase with the given name.  If one doesn't\n  // exist, creates one and returns it.\n  //\n  // Arguments:\n  //\n  //   test_case_name: name of the test case\n  //   type_param:     the name of the test's type parameter, or NULL if\n  //                   this is not a typed or a type-parameterized test.\n  //   set_up_tc:      pointer to the function that sets up the test case\n  //   tear_down_tc:   pointer to the function that tears down the test case\n  TestCase* GetTestCase(const char* test_case_name,\n                        const char* type_param,\n                        Test::SetUpTestCaseFunc set_up_tc,\n                        Test::TearDownTestCaseFunc tear_down_tc);\n\n  // Adds a TestInfo to the unit test.\n  //\n  // Arguments:\n  //\n  //   set_up_tc:    pointer to the function that sets up the test case\n  //   tear_down_tc: pointer to the function that tears down the test case\n  //   test_info:    the TestInfo object\n  void AddTestInfo(Test::SetUpTestCaseFunc set_up_tc,\n                   Test::TearDownTestCaseFunc tear_down_tc,\n                   TestInfo* test_info) {\n    // In order to support thread-safe death tests, we need to\n    // remember the original working directory when the test program\n    // was first invoked.  We cannot do this in RUN_ALL_TESTS(), as\n    // the user may have changed the current directory before calling\n    // RUN_ALL_TESTS().  Therefore we capture the current directory in\n    // AddTestInfo(), which is called to register a TEST or TEST_F\n    // before main() is reached.\n    if (original_working_dir_.IsEmpty()) {\n      original_working_dir_.Set(FilePath::GetCurrentDir());\n      GTEST_CHECK_(!original_working_dir_.IsEmpty())\n          << \"Failed to get the current working directory.\";\n    }\n\n    GetTestCase(test_info->test_case_name(),\n                test_info->type_param(),\n                set_up_tc,\n                tear_down_tc)->AddTestInfo(test_info);\n  }\n\n#if GTEST_HAS_PARAM_TEST\n  // Returns ParameterizedTestCaseRegistry object used to keep track of\n  // value-parameterized tests and instantiate and register them.\n  internal::ParameterizedTestCaseRegistry& parameterized_test_registry() {\n    return parameterized_test_registry_;\n  }\n#endif  // GTEST_HAS_PARAM_TEST\n\n  // Sets the TestCase object for the test that's currently running.\n  void set_current_test_case(TestCase* a_current_test_case) {\n    current_test_case_ = a_current_test_case;\n  }\n\n  // Sets the TestInfo object for the test that's currently running.  If\n  // current_test_info is NULL, the assertion results will be stored in\n  // ad_hoc_test_result_.\n  void set_current_test_info(TestInfo* a_current_test_info) {\n    current_test_info_ = a_current_test_info;\n  }\n\n  // Registers all parameterized tests defined using TEST_P and\n  // INSTANTIATE_TEST_CASE_P, creating regular tests for each test/parameter\n  // combination. This method can be called more then once; it has guards\n  // protecting from registering the tests more then once.  If\n  // value-parameterized tests are disabled, RegisterParameterizedTests is\n  // present but does nothing.\n  void RegisterParameterizedTests();\n\n  // Runs all tests in this UnitTest object, prints the result, and\n  // returns true if all tests are successful.  If any exception is\n  // thrown during a test, this test is considered to be failed, but\n  // the rest of the tests will still be run.\n  bool RunAllTests();\n\n  // Clears the results of all tests, except the ad hoc tests.\n  void ClearNonAdHocTestResult() {\n    ForEach(test_cases_, TestCase::ClearTestCaseResult);\n  }\n\n  // Clears the results of ad-hoc test assertions.\n  void ClearAdHocTestResult() {\n    ad_hoc_test_result_.Clear();\n  }\n\n  // Adds a TestProperty to the current TestResult object when invoked in a\n  // context of a test or a test case, or to the global property set. If the\n  // result already contains a property with the same key, the value will be\n  // updated.\n  void RecordProperty(const TestProperty& test_property);\n\n  enum ReactionToSharding {\n    HONOR_SHARDING_PROTOCOL,\n    IGNORE_SHARDING_PROTOCOL\n  };\n\n  // Matches the full name of each test against the user-specified\n  // filter to decide whether the test should run, then records the\n  // result in each TestCase and TestInfo object.\n  // If shard_tests == HONOR_SHARDING_PROTOCOL, further filters tests\n  // based on sharding variables in the environment.\n  // Returns the number of tests that should run.\n  int FilterTests(ReactionToSharding shard_tests);\n\n  // Prints the names of the tests matching the user-specified filter flag.\n  void ListTestsMatchingFilter();\n\n  const TestCase* current_test_case() const { return current_test_case_; }\n  TestInfo* current_test_info() { return current_test_info_; }\n  const TestInfo* current_test_info() const { return current_test_info_; }\n\n  // Returns the vector of environments that need to be set-up/torn-down\n  // before/after the tests are run.\n  std::vector<Environment*>& environments() { return environments_; }\n\n  // Getters for the per-thread Google Test trace stack.\n  std::vector<TraceInfo>& gtest_trace_stack() {\n    return *(gtest_trace_stack_.pointer());\n  }\n  const std::vector<TraceInfo>& gtest_trace_stack() const {\n    return gtest_trace_stack_.get();\n  }\n\n#if GTEST_HAS_DEATH_TEST\n  void InitDeathTestSubprocessControlInfo() {\n    internal_run_death_test_flag_.reset(ParseInternalRunDeathTestFlag());\n  }\n  // Returns a pointer to the parsed --gtest_internal_run_death_test\n  // flag, or NULL if that flag was not specified.\n  // This information is useful only in a death test child process.\n  // Must not be called before a call to InitGoogleTest.\n  const InternalRunDeathTestFlag* internal_run_death_test_flag() const {\n    return internal_run_death_test_flag_.get();\n  }\n\n  // Returns a pointer to the current death test factory.\n  internal::DeathTestFactory* death_test_factory() {\n    return death_test_factory_.get();\n  }\n\n  void SuppressTestEventsIfInSubprocess();\n\n  friend class ReplaceDeathTestFactory;\n#endif  // GTEST_HAS_DEATH_TEST\n\n  // Initializes the event listener performing XML output as specified by\n  // UnitTestOptions. Must not be called before InitGoogleTest.\n  void ConfigureXmlOutput();\n\n#if GTEST_CAN_STREAM_RESULTS_\n  // Initializes the event listener for streaming test results to a socket.\n  // Must not be called before InitGoogleTest.\n  void ConfigureStreamingOutput();\n#endif\n\n  // Performs initialization dependent upon flag values obtained in\n  // ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to\n  // ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest\n  // this function is also called from RunAllTests.  Since this function can be\n  // called more than once, it has to be idempotent.\n  void PostFlagParsingInit();\n\n  // Gets the random seed used at the start of the current test iteration.\n  int random_seed() const { return random_seed_; }\n\n  // Gets the random number generator.\n  internal::Random* random() { return &random_; }\n\n  // Shuffles all test cases, and the tests within each test case,\n  // making sure that death tests are still run first.\n  void ShuffleTests();\n\n  // Restores the test cases and tests to their order before the first shuffle.\n  void UnshuffleTests();\n\n  // Returns the value of GTEST_FLAG(catch_exceptions) at the moment\n  // UnitTest::Run() starts.\n  bool catch_exceptions() const { return catch_exceptions_; }\n\n private:\n  friend class ::testing::UnitTest;\n\n  // Used by UnitTest::Run() to capture the state of\n  // GTEST_FLAG(catch_exceptions) at the moment it starts.\n  void set_catch_exceptions(bool value) { catch_exceptions_ = value; }\n\n  // The UnitTest object that owns this implementation object.\n  UnitTest* const parent_;\n\n  // The working directory when the first TEST() or TEST_F() was\n  // executed.\n  internal::FilePath original_working_dir_;\n\n  // The default test part result reporters.\n  DefaultGlobalTestPartResultReporter default_global_test_part_result_reporter_;\n  DefaultPerThreadTestPartResultReporter\n      default_per_thread_test_part_result_reporter_;\n\n  // Points to (but doesn't own) the global test part result reporter.\n  TestPartResultReporterInterface* global_test_part_result_repoter_;\n\n  // Protects read and write access to global_test_part_result_reporter_.\n  internal::Mutex global_test_part_result_reporter_mutex_;\n\n  // Points to (but doesn't own) the per-thread test part result reporter.\n  internal::ThreadLocal<TestPartResultReporterInterface*>\n      per_thread_test_part_result_reporter_;\n\n  // The vector of environments that need to be set-up/torn-down\n  // before/after the tests are run.\n  std::vector<Environment*> environments_;\n\n  // The vector of TestCases in their original order.  It owns the\n  // elements in the vector.\n  std::vector<TestCase*> test_cases_;\n\n  // Provides a level of indirection for the test case list to allow\n  // easy shuffling and restoring the test case order.  The i-th\n  // element of this vector is the index of the i-th test case in the\n  // shuffled order.\n  std::vector<int> test_case_indices_;\n\n#if GTEST_HAS_PARAM_TEST\n  // ParameterizedTestRegistry object used to register value-parameterized\n  // tests.\n  internal::ParameterizedTestCaseRegistry parameterized_test_registry_;\n\n  // Indicates whether RegisterParameterizedTests() has been called already.\n  bool parameterized_tests_registered_;\n#endif  // GTEST_HAS_PARAM_TEST\n\n  // Index of the last death test case registered.  Initially -1.\n  int last_death_test_case_;\n\n  // This points to the TestCase for the currently running test.  It\n  // changes as Google Test goes through one test case after another.\n  // When no test is running, this is set to NULL and Google Test\n  // stores assertion results in ad_hoc_test_result_.  Initially NULL.\n  TestCase* current_test_case_;\n\n  // This points to the TestInfo for the currently running test.  It\n  // changes as Google Test goes through one test after another.  When\n  // no test is running, this is set to NULL and Google Test stores\n  // assertion results in ad_hoc_test_result_.  Initially NULL.\n  TestInfo* current_test_info_;\n\n  // Normally, a user only writes assertions inside a TEST or TEST_F,\n  // or inside a function called by a TEST or TEST_F.  Since Google\n  // Test keeps track of which test is current running, it can\n  // associate such an assertion with the test it belongs to.\n  //\n  // If an assertion is encountered when no TEST or TEST_F is running,\n  // Google Test attributes the assertion result to an imaginary \"ad hoc\"\n  // test, and records the result in ad_hoc_test_result_.\n  TestResult ad_hoc_test_result_;\n\n  // The list of event listeners that can be used to track events inside\n  // Google Test.\n  TestEventListeners listeners_;\n\n  // The OS stack trace getter.  Will be deleted when the UnitTest\n  // object is destructed.  By default, an OsStackTraceGetter is used,\n  // but the user can set this field to use a custom getter if that is\n  // desired.\n  OsStackTraceGetterInterface* os_stack_trace_getter_;\n\n  // True iff PostFlagParsingInit() has been called.\n  bool post_flag_parse_init_performed_;\n\n  // The random number seed used at the beginning of the test run.\n  int random_seed_;\n\n  // Our random number generator.\n  internal::Random random_;\n\n  // The time of the test program start, in ms from the start of the\n  // UNIX epoch.\n  TimeInMillis start_timestamp_;\n\n  // How long the test took to run, in milliseconds.\n  TimeInMillis elapsed_time_;\n\n#if GTEST_HAS_DEATH_TEST\n  // The decomposed components of the gtest_internal_run_death_test flag,\n  // parsed when RUN_ALL_TESTS is called.\n  internal::scoped_ptr<InternalRunDeathTestFlag> internal_run_death_test_flag_;\n  internal::scoped_ptr<internal::DeathTestFactory> death_test_factory_;\n#endif  // GTEST_HAS_DEATH_TEST\n\n  // A per-thread stack of traces created by the SCOPED_TRACE() macro.\n  internal::ThreadLocal<std::vector<TraceInfo> > gtest_trace_stack_;\n\n  // The value of GTEST_FLAG(catch_exceptions) at the moment RunAllTests()\n  // starts.\n  bool catch_exceptions_;\n\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(UnitTestImpl);\n};  // class UnitTestImpl\n\n// Convenience function for accessing the global UnitTest\n// implementation object.\ninline UnitTestImpl* GetUnitTestImpl() {\n  return UnitTest::GetInstance()->impl();\n}\n\n#if GTEST_USES_SIMPLE_RE\n\n// Internal helper functions for implementing the simple regular\n// expression matcher.\nGTEST_API_ bool IsInSet(char ch, const char* str);\nGTEST_API_ bool IsAsciiDigit(char ch);\nGTEST_API_ bool IsAsciiPunct(char ch);\nGTEST_API_ bool IsRepeat(char ch);\nGTEST_API_ bool IsAsciiWhiteSpace(char ch);\nGTEST_API_ bool IsAsciiWordChar(char ch);\nGTEST_API_ bool IsValidEscape(char ch);\nGTEST_API_ bool AtomMatchesChar(bool escaped, char pattern, char ch);\nGTEST_API_ bool ValidateRegex(const char* regex);\nGTEST_API_ bool MatchRegexAtHead(const char* regex, const char* str);\nGTEST_API_ bool MatchRepetitionAndRegexAtHead(\n    bool escaped, char ch, char repeat, const char* regex, const char* str);\nGTEST_API_ bool MatchRegexAnywhere(const char* regex, const char* str);\n\n#endif  // GTEST_USES_SIMPLE_RE\n\n// Parses the command line for Google Test flags, without initializing\n// other parts of Google Test.\nGTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, char** argv);\nGTEST_API_ void ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv);\n\n#if GTEST_HAS_DEATH_TEST\n\n// Returns the message describing the last system error, regardless of the\n// platform.\nGTEST_API_ std::string GetLastErrnoDescription();\n\n// Attempts to parse a string into a positive integer pointed to by the\n// number parameter.  Returns true if that is possible.\n// GTEST_HAS_DEATH_TEST implies that we have ::std::string, so we can use\n// it here.\ntemplate <typename Integer>\nbool ParseNaturalNumber(const ::std::string& str, Integer* number) {\n  // Fail fast if the given string does not begin with a digit;\n  // this bypasses strtoXXX's \"optional leading whitespace and plus\n  // or minus sign\" semantics, which are undesirable here.\n  if (str.empty() || !IsDigit(str[0])) {\n    return false;\n  }\n  errno = 0;\n\n  char* end;\n  // BiggestConvertible is the largest integer type that system-provided\n  // string-to-number conversion routines can return.\n\n# if GTEST_OS_WINDOWS && !defined(__GNUC__)\n\n  // MSVC and C++ Builder define __int64 instead of the standard long long.\n  typedef unsigned __int64 BiggestConvertible;\n  const BiggestConvertible parsed = _strtoui64(str.c_str(), &end, 10);\n\n# else\n\n  typedef unsigned long long BiggestConvertible;  // NOLINT\n  const BiggestConvertible parsed = strtoull(str.c_str(), &end, 10);\n\n# endif  // GTEST_OS_WINDOWS && !defined(__GNUC__)\n\n  const bool parse_success = *end == '\\0' && errno == 0;\n\n  // TODO(vladl@google.com): Convert this to compile time assertion when it is\n  // available.\n  GTEST_CHECK_(sizeof(Integer) <= sizeof(parsed));\n\n  const Integer result = static_cast<Integer>(parsed);\n  if (parse_success && static_cast<BiggestConvertible>(result) == parsed) {\n    *number = result;\n    return true;\n  }\n  return false;\n}\n#endif  // GTEST_HAS_DEATH_TEST\n\n// TestResult contains some private methods that should be hidden from\n// Google Test user but are required for testing. This class allow our tests\n// to access them.\n//\n// This class is supplied only for the purpose of testing Google Test's own\n// constructs. Do not use it in user tests, either directly or indirectly.\nclass TestResultAccessor {\n public:\n  static void RecordProperty(TestResult* test_result,\n                             const std::string& xml_element,\n                             const TestProperty& property) {\n    test_result->RecordProperty(xml_element, property);\n  }\n\n  static void ClearTestPartResults(TestResult* test_result) {\n    test_result->ClearTestPartResults();\n  }\n\n  static const std::vector<testing::TestPartResult>& test_part_results(\n      const TestResult& test_result) {\n    return test_result.test_part_results();\n  }\n};\n\n#if GTEST_CAN_STREAM_RESULTS_\n\n// Streams test results to the given port on the given host machine.\nclass GTEST_API_ StreamingListener : public EmptyTestEventListener {\n public:\n  // Abstract base class for writing strings to a socket.\n  class AbstractSocketWriter {\n   public:\n    virtual ~AbstractSocketWriter() {}\n\n    // Sends a string to the socket.\n    virtual void Send(const string& message) = 0;\n\n    // Closes the socket.\n    virtual void CloseConnection() {}\n\n    // Sends a string and a newline to the socket.\n    void SendLn(const string& message) {\n      Send(message + \"\\n\");\n    }\n  };\n\n  // Concrete class for actually writing strings to a socket.\n  class SocketWriter : public AbstractSocketWriter {\n   public:\n    SocketWriter(const string& host, const string& port)\n        : sockfd_(-1), host_name_(host), port_num_(port) {\n      MakeConnection();\n    }\n\n    virtual ~SocketWriter() {\n      if (sockfd_ != -1)\n        CloseConnection();\n    }\n\n    // Sends a string to the socket.\n    virtual void Send(const string& message) {\n      GTEST_CHECK_(sockfd_ != -1)\n          << \"Send() can be called only when there is a connection.\";\n\n      const int len = static_cast<int>(message.length());\n      if (write(sockfd_, message.c_str(), len) != len) {\n        GTEST_LOG_(WARNING)\n            << \"stream_result_to: failed to stream to \"\n            << host_name_ << \":\" << port_num_;\n      }\n    }\n\n   private:\n    // Creates a client socket and connects to the server.\n    void MakeConnection();\n\n    // Closes the socket.\n    void CloseConnection() {\n      GTEST_CHECK_(sockfd_ != -1)\n          << \"CloseConnection() can be called only when there is a connection.\";\n\n      close(sockfd_);\n      sockfd_ = -1;\n    }\n\n    int sockfd_;  // socket file descriptor\n    const string host_name_;\n    const string port_num_;\n\n    GTEST_DISALLOW_COPY_AND_ASSIGN_(SocketWriter);\n  };  // class SocketWriter\n\n  // Escapes '=', '&', '%', and '\\n' characters in str as \"%xx\".\n  static string UrlEncode(const char* str);\n\n  StreamingListener(const string& host, const string& port)\n      : socket_writer_(new SocketWriter(host, port)) { Start(); }\n\n  explicit StreamingListener(AbstractSocketWriter* socket_writer)\n      : socket_writer_(socket_writer) { Start(); }\n\n  void OnTestProgramStart(const UnitTest& /* unit_test */) {\n    SendLn(\"event=TestProgramStart\");\n  }\n\n  void OnTestProgramEnd(const UnitTest& unit_test) {\n    // Note that Google Test current only report elapsed time for each\n    // test iteration, not for the entire test program.\n    SendLn(\"event=TestProgramEnd&passed=\" + FormatBool(unit_test.Passed()));\n\n    // Notify the streaming server to stop.\n    socket_writer_->CloseConnection();\n  }\n\n  void OnTestIterationStart(const UnitTest& /* unit_test */, int iteration) {\n    SendLn(\"event=TestIterationStart&iteration=\" +\n           StreamableToString(iteration));\n  }\n\n  void OnTestIterationEnd(const UnitTest& unit_test, int /* iteration */) {\n    SendLn(\"event=TestIterationEnd&passed=\" +\n           FormatBool(unit_test.Passed()) + \"&elapsed_time=\" +\n           StreamableToString(unit_test.elapsed_time()) + \"ms\");\n  }\n\n  void OnTestCaseStart(const TestCase& test_case) {\n    SendLn(std::string(\"event=TestCaseStart&name=\") + test_case.name());\n  }\n\n  void OnTestCaseEnd(const TestCase& test_case) {\n    SendLn(\"event=TestCaseEnd&passed=\" + FormatBool(test_case.Passed())\n           + \"&elapsed_time=\" + StreamableToString(test_case.elapsed_time())\n           + \"ms\");\n  }\n\n  void OnTestStart(const TestInfo& test_info) {\n    SendLn(std::string(\"event=TestStart&name=\") + test_info.name());\n  }\n\n  void OnTestEnd(const TestInfo& test_info) {\n    SendLn(\"event=TestEnd&passed=\" +\n           FormatBool((test_info.result())->Passed()) +\n           \"&elapsed_time=\" +\n           StreamableToString((test_info.result())->elapsed_time()) + \"ms\");\n  }\n\n  void OnTestPartResult(const TestPartResult& test_part_result) {\n    const char* file_name = test_part_result.file_name();\n    if (file_name == NULL)\n      file_name = \"\";\n    SendLn(\"event=TestPartResult&file=\" + UrlEncode(file_name) +\n           \"&line=\" + StreamableToString(test_part_result.line_number()) +\n           \"&message=\" + UrlEncode(test_part_result.message()));\n  }\n\n private:\n  // Sends the given message and a newline to the socket.\n  void SendLn(const string& message) { socket_writer_->SendLn(message); }\n\n  // Called at the start of streaming to notify the receiver what\n  // protocol we are using.\n  void Start() { SendLn(\"gtest_streaming_protocol_version=1.0\"); }\n\n  string FormatBool(bool value) { return value ? \"1\" : \"0\"; }\n\n  const scoped_ptr<AbstractSocketWriter> socket_writer_;\n\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(StreamingListener);\n};  // class StreamingListener\n\n#endif  // GTEST_CAN_STREAM_RESULTS_\n\n}  // namespace internal\n}  // namespace testing\n\n#endif  // GTEST_SRC_GTEST_INTERNAL_INL_H_\n"
  },
  {
    "path": "mypyc/external/googletest/src/gtest-port.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: wan@google.com (Zhanyong Wan)\n\n#include \"gtest/internal/gtest-port.h\"\n\n#include <limits.h>\n#include <stdlib.h>\n#include <stdio.h>\n#include <string.h>\n#include <fstream>\n\n#if GTEST_OS_WINDOWS\n# include <windows.h>\n# include <io.h>\n# include <sys/stat.h>\n# include <map>  // Used in ThreadLocal.\n#else\n# include <unistd.h>\n#endif  // GTEST_OS_WINDOWS\n\n#if GTEST_OS_MAC\n# include <mach/mach_init.h>\n# include <mach/task.h>\n# include <mach/vm_map.h>\n#endif  // GTEST_OS_MAC\n\n#if GTEST_OS_QNX\n# include <devctl.h>\n# include <fcntl.h>\n# include <sys/procfs.h>\n#endif  // GTEST_OS_QNX\n\n#if GTEST_OS_AIX\n# include <procinfo.h>\n# include <sys/types.h>\n#endif  // GTEST_OS_AIX\n\n#include \"gtest/gtest-spi.h\"\n#include \"gtest/gtest-message.h\"\n#include \"gtest/internal/gtest-internal.h\"\n#include \"gtest/internal/gtest-string.h\"\n\n// Indicates that this translation unit is part of Google Test's\n// implementation.  It must come before gtest-internal-inl.h is\n// included, or there will be a compiler error.  This trick exists to\n// prevent the accidental inclusion of gtest-internal-inl.h in the\n// user's code.\n#define GTEST_IMPLEMENTATION_ 1\n#include \"src/gtest-internal-inl.h\"\n#undef GTEST_IMPLEMENTATION_\n\nnamespace testing {\nnamespace internal {\n\n#if defined(_MSC_VER) || defined(__BORLANDC__)\n// MSVC and C++Builder do not provide a definition of STDERR_FILENO.\nconst int kStdOutFileno = 1;\nconst int kStdErrFileno = 2;\n#else\nconst int kStdOutFileno = STDOUT_FILENO;\nconst int kStdErrFileno = STDERR_FILENO;\n#endif  // _MSC_VER\n\n#if GTEST_OS_LINUX\n\nnamespace {\ntemplate <typename T>\nT ReadProcFileField(const string& filename, int field) {\n  std::string dummy;\n  std::ifstream file(filename.c_str());\n  while (field-- > 0) {\n    file >> dummy;\n  }\n  T output = 0;\n  file >> output;\n  return output;\n}\n}  // namespace\n\n// Returns the number of active threads, or 0 when there is an error.\nsize_t GetThreadCount() {\n  const string filename =\n      (Message() << \"/proc/\" << getpid() << \"/stat\").GetString();\n  return ReadProcFileField<int>(filename, 19);\n}\n\n#elif GTEST_OS_MAC\n\nsize_t GetThreadCount() {\n  const task_t task = mach_task_self();\n  mach_msg_type_number_t thread_count;\n  thread_act_array_t thread_list;\n  const kern_return_t status = task_threads(task, &thread_list, &thread_count);\n  if (status == KERN_SUCCESS) {\n    // task_threads allocates resources in thread_list and we need to free them\n    // to avoid leaks.\n    vm_deallocate(task,\n                  reinterpret_cast<vm_address_t>(thread_list),\n                  sizeof(thread_t) * thread_count);\n    return static_cast<size_t>(thread_count);\n  } else {\n    return 0;\n  }\n}\n\n#elif GTEST_OS_QNX\n\n// Returns the number of threads running in the process, or 0 to indicate that\n// we cannot detect it.\nsize_t GetThreadCount() {\n  const int fd = open(\"/proc/self/as\", O_RDONLY);\n  if (fd < 0) {\n    return 0;\n  }\n  procfs_info process_info;\n  const int status =\n      devctl(fd, DCMD_PROC_INFO, &process_info, sizeof(process_info), NULL);\n  close(fd);\n  if (status == EOK) {\n    return static_cast<size_t>(process_info.num_threads);\n  } else {\n    return 0;\n  }\n}\n\n#elif GTEST_OS_AIX\n\nsize_t GetThreadCount() {\n  struct procentry64 entry;\n  pid_t pid = getpid();\n  int status = getprocs64(&entry, sizeof(entry), NULL, 0, &pid, 1);\n  if (status == 1) {\n    return entry.pi_thcount;\n  } else {\n    return 0;\n  }\n}\n\n#else\n\nsize_t GetThreadCount() {\n  // There's no portable way to detect the number of threads, so we just\n  // return 0 to indicate that we cannot detect it.\n  return 0;\n}\n\n#endif  // GTEST_OS_LINUX\n\n#if GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS\n\nvoid SleepMilliseconds(int n) {\n  ::Sleep(n);\n}\n\nAutoHandle::AutoHandle()\n    : handle_(INVALID_HANDLE_VALUE) {}\n\nAutoHandle::AutoHandle(Handle handle)\n    : handle_(handle) {}\n\nAutoHandle::~AutoHandle() {\n  Reset();\n}\n\nAutoHandle::Handle AutoHandle::Get() const {\n  return handle_;\n}\n\nvoid AutoHandle::Reset() {\n  Reset(INVALID_HANDLE_VALUE);\n}\n\nvoid AutoHandle::Reset(HANDLE handle) {\n  // Resetting with the same handle we already own is invalid.\n  if (handle_ != handle) {\n    if (IsCloseable()) {\n      ::CloseHandle(handle_);\n    }\n    handle_ = handle;\n  } else {\n    GTEST_CHECK_(!IsCloseable())\n        << \"Resetting a valid handle to itself is likely a programmer error \"\n            \"and thus not allowed.\";\n  }\n}\n\nbool AutoHandle::IsCloseable() const {\n  // Different Windows APIs may use either of these values to represent an\n  // invalid handle.\n  return handle_ != NULL && handle_ != INVALID_HANDLE_VALUE;\n}\n\nNotification::Notification()\n    : event_(::CreateEvent(NULL,   // Default security attributes.\n                           TRUE,   // Do not reset automatically.\n                           FALSE,  // Initially unset.\n                           NULL)) {  // Anonymous event.\n  GTEST_CHECK_(event_.Get() != NULL);\n}\n\nvoid Notification::Notify() {\n  GTEST_CHECK_(::SetEvent(event_.Get()) != FALSE);\n}\n\nvoid Notification::WaitForNotification() {\n  GTEST_CHECK_(\n      ::WaitForSingleObject(event_.Get(), INFINITE) == WAIT_OBJECT_0);\n}\n\nMutex::Mutex()\n    : owner_thread_id_(0),\n      type_(kDynamic),\n      critical_section_init_phase_(0),\n      critical_section_(new CRITICAL_SECTION) {\n  ::InitializeCriticalSection(critical_section_);\n}\n\nMutex::~Mutex() {\n  // Static mutexes are leaked intentionally. It is not thread-safe to try\n  // to clean them up.\n  // TODO(yukawa): Switch to Slim Reader/Writer (SRW) Locks, which requires\n  // nothing to clean it up but is available only on Vista and later.\n  // http://msdn.microsoft.com/en-us/library/windows/desktop/aa904937.aspx\n  if (type_ == kDynamic) {\n    ::DeleteCriticalSection(critical_section_);\n    delete critical_section_;\n    critical_section_ = NULL;\n  }\n}\n\nvoid Mutex::Lock() {\n  ThreadSafeLazyInit();\n  ::EnterCriticalSection(critical_section_);\n  owner_thread_id_ = ::GetCurrentThreadId();\n}\n\nvoid Mutex::Unlock() {\n  ThreadSafeLazyInit();\n  // We don't protect writing to owner_thread_id_ here, as it's the\n  // caller's responsibility to ensure that the current thread holds the\n  // mutex when this is called.\n  owner_thread_id_ = 0;\n  ::LeaveCriticalSection(critical_section_);\n}\n\n// Does nothing if the current thread holds the mutex. Otherwise, crashes\n// with high probability.\nvoid Mutex::AssertHeld() {\n  ThreadSafeLazyInit();\n  GTEST_CHECK_(owner_thread_id_ == ::GetCurrentThreadId())\n      << \"The current thread is not holding the mutex @\" << this;\n}\n\n// Initializes owner_thread_id_ and critical_section_ in static mutexes.\nvoid Mutex::ThreadSafeLazyInit() {\n  // Dynamic mutexes are initialized in the constructor.\n  if (type_ == kStatic) {\n    switch (\n        ::InterlockedCompareExchange(&critical_section_init_phase_, 1L, 0L)) {\n      case 0:\n        // If critical_section_init_phase_ was 0 before the exchange, we\n        // are the first to test it and need to perform the initialization.\n        owner_thread_id_ = 0;\n        critical_section_ = new CRITICAL_SECTION;\n        ::InitializeCriticalSection(critical_section_);\n        // Updates the critical_section_init_phase_ to 2 to signal\n        // initialization complete.\n        GTEST_CHECK_(::InterlockedCompareExchange(\n                          &critical_section_init_phase_, 2L, 1L) ==\n                      1L);\n        break;\n      case 1:\n        // Somebody else is already initializing the mutex; spin until they\n        // are done.\n        while (::InterlockedCompareExchange(&critical_section_init_phase_,\n                                            2L,\n                                            2L) != 2L) {\n          // Possibly yields the rest of the thread's time slice to other\n          // threads.\n          ::Sleep(0);\n        }\n        break;\n\n      case 2:\n        break;  // The mutex is already initialized and ready for use.\n\n      default:\n        GTEST_CHECK_(false)\n            << \"Unexpected value of critical_section_init_phase_ \"\n            << \"while initializing a static mutex.\";\n    }\n  }\n}\n\nnamespace {\n\nclass ThreadWithParamSupport : public ThreadWithParamBase {\n public:\n  static HANDLE CreateThread(Runnable* runnable,\n                             Notification* thread_can_start) {\n    ThreadMainParam* param = new ThreadMainParam(runnable, thread_can_start);\n    DWORD thread_id;\n    // TODO(yukawa): Consider to use _beginthreadex instead.\n    HANDLE thread_handle = ::CreateThread(\n        NULL,    // Default security.\n        0,       // Default stack size.\n        &ThreadWithParamSupport::ThreadMain,\n        param,   // Parameter to ThreadMainStatic\n        0x0,     // Default creation flags.\n        &thread_id);  // Need a valid pointer for the call to work under Win98.\n    GTEST_CHECK_(thread_handle != NULL) << \"CreateThread failed with error \"\n                                        << ::GetLastError() << \".\";\n    if (thread_handle == NULL) {\n      delete param;\n    }\n    return thread_handle;\n  }\n\n private:\n  struct ThreadMainParam {\n    ThreadMainParam(Runnable* runnable, Notification* thread_can_start)\n        : runnable_(runnable),\n          thread_can_start_(thread_can_start) {\n    }\n    scoped_ptr<Runnable> runnable_;\n    // Does not own.\n    Notification* thread_can_start_;\n  };\n\n  static DWORD WINAPI ThreadMain(void* ptr) {\n    // Transfers ownership.\n    scoped_ptr<ThreadMainParam> param(static_cast<ThreadMainParam*>(ptr));\n    if (param->thread_can_start_ != NULL)\n      param->thread_can_start_->WaitForNotification();\n    param->runnable_->Run();\n    return 0;\n  }\n\n  // Prohibit instantiation.\n  ThreadWithParamSupport();\n\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(ThreadWithParamSupport);\n};\n\n}  // namespace\n\nThreadWithParamBase::ThreadWithParamBase(Runnable *runnable,\n                                         Notification* thread_can_start)\n      : thread_(ThreadWithParamSupport::CreateThread(runnable,\n                                                     thread_can_start)) {\n}\n\nThreadWithParamBase::~ThreadWithParamBase() {\n  Join();\n}\n\nvoid ThreadWithParamBase::Join() {\n  GTEST_CHECK_(::WaitForSingleObject(thread_.Get(), INFINITE) == WAIT_OBJECT_0)\n      << \"Failed to join the thread with error \" << ::GetLastError() << \".\";\n}\n\n// Maps a thread to a set of ThreadIdToThreadLocals that have values\n// instantiated on that thread and notifies them when the thread exits.  A\n// ThreadLocal instance is expected to persist until all threads it has\n// values on have terminated.\nclass ThreadLocalRegistryImpl {\n public:\n  // Registers thread_local_instance as having value on the current thread.\n  // Returns a value that can be used to identify the thread from other threads.\n  static ThreadLocalValueHolderBase* GetValueOnCurrentThread(\n      const ThreadLocalBase* thread_local_instance) {\n    DWORD current_thread = ::GetCurrentThreadId();\n    MutexLock lock(&mutex_);\n    ThreadIdToThreadLocals* const thread_to_thread_locals =\n        GetThreadLocalsMapLocked();\n    ThreadIdToThreadLocals::iterator thread_local_pos =\n        thread_to_thread_locals->find(current_thread);\n    if (thread_local_pos == thread_to_thread_locals->end()) {\n      thread_local_pos = thread_to_thread_locals->insert(\n          std::make_pair(current_thread, ThreadLocalValues())).first;\n      StartWatcherThreadFor(current_thread);\n    }\n    ThreadLocalValues& thread_local_values = thread_local_pos->second;\n    ThreadLocalValues::iterator value_pos =\n        thread_local_values.find(thread_local_instance);\n    if (value_pos == thread_local_values.end()) {\n      value_pos =\n          thread_local_values\n              .insert(std::make_pair(\n                  thread_local_instance,\n                  linked_ptr<ThreadLocalValueHolderBase>(\n                      thread_local_instance->NewValueForCurrentThread())))\n              .first;\n    }\n    return value_pos->second.get();\n  }\n\n  static void OnThreadLocalDestroyed(\n      const ThreadLocalBase* thread_local_instance) {\n    std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;\n    // Clean up the ThreadLocalValues data structure while holding the lock, but\n    // defer the destruction of the ThreadLocalValueHolderBases.\n    {\n      MutexLock lock(&mutex_);\n      ThreadIdToThreadLocals* const thread_to_thread_locals =\n          GetThreadLocalsMapLocked();\n      for (ThreadIdToThreadLocals::iterator it =\n          thread_to_thread_locals->begin();\n          it != thread_to_thread_locals->end();\n          ++it) {\n        ThreadLocalValues& thread_local_values = it->second;\n        ThreadLocalValues::iterator value_pos =\n            thread_local_values.find(thread_local_instance);\n        if (value_pos != thread_local_values.end()) {\n          value_holders.push_back(value_pos->second);\n          thread_local_values.erase(value_pos);\n          // This 'if' can only be successful at most once, so theoretically we\n          // could break out of the loop here, but we don't bother doing so.\n        }\n      }\n    }\n    // Outside the lock, let the destructor for 'value_holders' deallocate the\n    // ThreadLocalValueHolderBases.\n  }\n\n  static void OnThreadExit(DWORD thread_id) {\n    GTEST_CHECK_(thread_id != 0) << ::GetLastError();\n    std::vector<linked_ptr<ThreadLocalValueHolderBase> > value_holders;\n    // Clean up the ThreadIdToThreadLocals data structure while holding the\n    // lock, but defer the destruction of the ThreadLocalValueHolderBases.\n    {\n      MutexLock lock(&mutex_);\n      ThreadIdToThreadLocals* const thread_to_thread_locals =\n          GetThreadLocalsMapLocked();\n      ThreadIdToThreadLocals::iterator thread_local_pos =\n          thread_to_thread_locals->find(thread_id);\n      if (thread_local_pos != thread_to_thread_locals->end()) {\n        ThreadLocalValues& thread_local_values = thread_local_pos->second;\n        for (ThreadLocalValues::iterator value_pos =\n            thread_local_values.begin();\n            value_pos != thread_local_values.end();\n            ++value_pos) {\n          value_holders.push_back(value_pos->second);\n        }\n        thread_to_thread_locals->erase(thread_local_pos);\n      }\n    }\n    // Outside the lock, let the destructor for 'value_holders' deallocate the\n    // ThreadLocalValueHolderBases.\n  }\n\n private:\n  // In a particular thread, maps a ThreadLocal object to its value.\n  typedef std::map<const ThreadLocalBase*,\n                   linked_ptr<ThreadLocalValueHolderBase> > ThreadLocalValues;\n  // Stores all ThreadIdToThreadLocals having values in a thread, indexed by\n  // thread's ID.\n  typedef std::map<DWORD, ThreadLocalValues> ThreadIdToThreadLocals;\n\n  // Holds the thread id and thread handle that we pass from\n  // StartWatcherThreadFor to WatcherThreadFunc.\n  typedef std::pair<DWORD, HANDLE> ThreadIdAndHandle;\n\n  static void StartWatcherThreadFor(DWORD thread_id) {\n    // The returned handle will be kept in thread_map and closed by\n    // watcher_thread in WatcherThreadFunc.\n    HANDLE thread = ::OpenThread(SYNCHRONIZE | THREAD_QUERY_INFORMATION,\n                                 FALSE,\n                                 thread_id);\n    GTEST_CHECK_(thread != NULL);\n    // We need to to pass a valid thread ID pointer into CreateThread for it\n    // to work correctly under Win98.\n    DWORD watcher_thread_id;\n    HANDLE watcher_thread = ::CreateThread(\n        NULL,   // Default security.\n        0,      // Default stack size\n        &ThreadLocalRegistryImpl::WatcherThreadFunc,\n        reinterpret_cast<LPVOID>(new ThreadIdAndHandle(thread_id, thread)),\n        CREATE_SUSPENDED,\n        &watcher_thread_id);\n    GTEST_CHECK_(watcher_thread != NULL);\n    // Give the watcher thread the same priority as ours to avoid being\n    // blocked by it.\n    ::SetThreadPriority(watcher_thread,\n                        ::GetThreadPriority(::GetCurrentThread()));\n    ::ResumeThread(watcher_thread);\n    ::CloseHandle(watcher_thread);\n  }\n\n  // Monitors exit from a given thread and notifies those\n  // ThreadIdToThreadLocals about thread termination.\n  static DWORD WINAPI WatcherThreadFunc(LPVOID param) {\n    const ThreadIdAndHandle* tah =\n        reinterpret_cast<const ThreadIdAndHandle*>(param);\n    GTEST_CHECK_(\n        ::WaitForSingleObject(tah->second, INFINITE) == WAIT_OBJECT_0);\n    OnThreadExit(tah->first);\n    ::CloseHandle(tah->second);\n    delete tah;\n    return 0;\n  }\n\n  // Returns map of thread local instances.\n  static ThreadIdToThreadLocals* GetThreadLocalsMapLocked() {\n    mutex_.AssertHeld();\n    static ThreadIdToThreadLocals* map = new ThreadIdToThreadLocals;\n    return map;\n  }\n\n  // Protects access to GetThreadLocalsMapLocked() and its return value.\n  static Mutex mutex_;\n  // Protects access to GetThreadMapLocked() and its return value.\n  static Mutex thread_map_mutex_;\n};\n\nMutex ThreadLocalRegistryImpl::mutex_(Mutex::kStaticMutex);\nMutex ThreadLocalRegistryImpl::thread_map_mutex_(Mutex::kStaticMutex);\n\nThreadLocalValueHolderBase* ThreadLocalRegistry::GetValueOnCurrentThread(\n      const ThreadLocalBase* thread_local_instance) {\n  return ThreadLocalRegistryImpl::GetValueOnCurrentThread(\n      thread_local_instance);\n}\n\nvoid ThreadLocalRegistry::OnThreadLocalDestroyed(\n      const ThreadLocalBase* thread_local_instance) {\n  ThreadLocalRegistryImpl::OnThreadLocalDestroyed(thread_local_instance);\n}\n\n#endif  // GTEST_IS_THREADSAFE && GTEST_OS_WINDOWS\n\n#if GTEST_USES_POSIX_RE\n\n// Implements RE.  Currently only needed for death tests.\n\nRE::~RE() {\n  if (is_valid_) {\n    // regfree'ing an invalid regex might crash because the content\n    // of the regex is undefined. Since the regex's are essentially\n    // the same, one cannot be valid (or invalid) without the other\n    // being so too.\n    regfree(&partial_regex_);\n    regfree(&full_regex_);\n  }\n  free(const_cast<char*>(pattern_));\n}\n\n// Returns true iff regular expression re matches the entire str.\nbool RE::FullMatch(const char* str, const RE& re) {\n  if (!re.is_valid_) return false;\n\n  regmatch_t match;\n  return regexec(&re.full_regex_, str, 1, &match, 0) == 0;\n}\n\n// Returns true iff regular expression re matches a substring of str\n// (including str itself).\nbool RE::PartialMatch(const char* str, const RE& re) {\n  if (!re.is_valid_) return false;\n\n  regmatch_t match;\n  return regexec(&re.partial_regex_, str, 1, &match, 0) == 0;\n}\n\n// Initializes an RE from its string representation.\nvoid RE::Init(const char* regex) {\n  pattern_ = posix::StrDup(regex);\n\n  // Reserves enough bytes to hold the regular expression used for a\n  // full match.\n  const size_t full_regex_len = strlen(regex) + 10;\n  char* const full_pattern = new char[full_regex_len];\n\n  snprintf(full_pattern, full_regex_len, \"^(%s)$\", regex);\n  is_valid_ = regcomp(&full_regex_, full_pattern, REG_EXTENDED) == 0;\n  // We want to call regcomp(&partial_regex_, ...) even if the\n  // previous expression returns false.  Otherwise partial_regex_ may\n  // not be properly initialized can may cause trouble when it's\n  // freed.\n  //\n  // Some implementation of POSIX regex (e.g. on at least some\n  // versions of Cygwin) doesn't accept the empty string as a valid\n  // regex.  We change it to an equivalent form \"()\" to be safe.\n  if (is_valid_) {\n    const char* const partial_regex = (*regex == '\\0') ? \"()\" : regex;\n    is_valid_ = regcomp(&partial_regex_, partial_regex, REG_EXTENDED) == 0;\n  }\n  EXPECT_TRUE(is_valid_)\n      << \"Regular expression \\\"\" << regex\n      << \"\\\" is not a valid POSIX Extended regular expression.\";\n\n  delete[] full_pattern;\n}\n\n#elif GTEST_USES_SIMPLE_RE\n\n// Returns true iff ch appears anywhere in str (excluding the\n// terminating '\\0' character).\nbool IsInSet(char ch, const char* str) {\n  return ch != '\\0' && strchr(str, ch) != NULL;\n}\n\n// Returns true iff ch belongs to the given classification.  Unlike\n// similar functions in <ctype.h>, these aren't affected by the\n// current locale.\nbool IsAsciiDigit(char ch) { return '0' <= ch && ch <= '9'; }\nbool IsAsciiPunct(char ch) {\n  return IsInSet(ch, \"^-!\\\"#$%&'()*+,./:;<=>?@[\\\\]_`{|}~\");\n}\nbool IsRepeat(char ch) { return IsInSet(ch, \"?*+\"); }\nbool IsAsciiWhiteSpace(char ch) { return IsInSet(ch, \" \\f\\n\\r\\t\\v\"); }\nbool IsAsciiWordChar(char ch) {\n  return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z') ||\n      ('0' <= ch && ch <= '9') || ch == '_';\n}\n\n// Returns true iff \"\\\\c\" is a supported escape sequence.\nbool IsValidEscape(char c) {\n  return (IsAsciiPunct(c) || IsInSet(c, \"dDfnrsStvwW\"));\n}\n\n// Returns true iff the given atom (specified by escaped and pattern)\n// matches ch.  The result is undefined if the atom is invalid.\nbool AtomMatchesChar(bool escaped, char pattern_char, char ch) {\n  if (escaped) {  // \"\\\\p\" where p is pattern_char.\n    switch (pattern_char) {\n      case 'd': return IsAsciiDigit(ch);\n      case 'D': return !IsAsciiDigit(ch);\n      case 'f': return ch == '\\f';\n      case 'n': return ch == '\\n';\n      case 'r': return ch == '\\r';\n      case 's': return IsAsciiWhiteSpace(ch);\n      case 'S': return !IsAsciiWhiteSpace(ch);\n      case 't': return ch == '\\t';\n      case 'v': return ch == '\\v';\n      case 'w': return IsAsciiWordChar(ch);\n      case 'W': return !IsAsciiWordChar(ch);\n    }\n    return IsAsciiPunct(pattern_char) && pattern_char == ch;\n  }\n\n  return (pattern_char == '.' && ch != '\\n') || pattern_char == ch;\n}\n\n// Helper function used by ValidateRegex() to format error messages.\nstd::string FormatRegexSyntaxError(const char* regex, int index) {\n  return (Message() << \"Syntax error at index \" << index\n          << \" in simple regular expression \\\"\" << regex << \"\\\": \").GetString();\n}\n\n// Generates non-fatal failures and returns false if regex is invalid;\n// otherwise returns true.\nbool ValidateRegex(const char* regex) {\n  if (regex == NULL) {\n    // TODO(wan@google.com): fix the source file location in the\n    // assertion failures to match where the regex is used in user\n    // code.\n    ADD_FAILURE() << \"NULL is not a valid simple regular expression.\";\n    return false;\n  }\n\n  bool is_valid = true;\n\n  // True iff ?, *, or + can follow the previous atom.\n  bool prev_repeatable = false;\n  for (int i = 0; regex[i]; i++) {\n    if (regex[i] == '\\\\') {  // An escape sequence\n      i++;\n      if (regex[i] == '\\0') {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)\n                      << \"'\\\\' cannot appear at the end.\";\n        return false;\n      }\n\n      if (!IsValidEscape(regex[i])) {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i - 1)\n                      << \"invalid escape sequence \\\"\\\\\" << regex[i] << \"\\\".\";\n        is_valid = false;\n      }\n      prev_repeatable = true;\n    } else {  // Not an escape sequence.\n      const char ch = regex[i];\n\n      if (ch == '^' && i > 0) {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\n                      << \"'^' can only appear at the beginning.\";\n        is_valid = false;\n      } else if (ch == '$' && regex[i + 1] != '\\0') {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\n                      << \"'$' can only appear at the end.\";\n        is_valid = false;\n      } else if (IsInSet(ch, \"()[]{}|\")) {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\n                      << \"'\" << ch << \"' is unsupported.\";\n        is_valid = false;\n      } else if (IsRepeat(ch) && !prev_repeatable) {\n        ADD_FAILURE() << FormatRegexSyntaxError(regex, i)\n                      << \"'\" << ch << \"' can only follow a repeatable token.\";\n        is_valid = false;\n      }\n\n      prev_repeatable = !IsInSet(ch, \"^$?*+\");\n    }\n  }\n\n  return is_valid;\n}\n\n// Matches a repeated regex atom followed by a valid simple regular\n// expression.  The regex atom is defined as c if escaped is false,\n// or \\c otherwise.  repeat is the repetition meta character (?, *,\n// or +).  The behavior is undefined if str contains too many\n// characters to be indexable by size_t, in which case the test will\n// probably time out anyway.  We are fine with this limitation as\n// std::string has it too.\nbool MatchRepetitionAndRegexAtHead(\n    bool escaped, char c, char repeat, const char* regex,\n    const char* str) {\n  const size_t min_count = (repeat == '+') ? 1 : 0;\n  const size_t max_count = (repeat == '?') ? 1 :\n      static_cast<size_t>(-1) - 1;\n  // We cannot call numeric_limits::max() as it conflicts with the\n  // max() macro on Windows.\n\n  for (size_t i = 0; i <= max_count; ++i) {\n    // We know that the atom matches each of the first i characters in str.\n    if (i >= min_count && MatchRegexAtHead(regex, str + i)) {\n      // We have enough matches at the head, and the tail matches too.\n      // Since we only care about *whether* the pattern matches str\n      // (as opposed to *how* it matches), there is no need to find a\n      // greedy match.\n      return true;\n    }\n    if (str[i] == '\\0' || !AtomMatchesChar(escaped, c, str[i]))\n      return false;\n  }\n  return false;\n}\n\n// Returns true iff regex matches a prefix of str.  regex must be a\n// valid simple regular expression and not start with \"^\", or the\n// result is undefined.\nbool MatchRegexAtHead(const char* regex, const char* str) {\n  if (*regex == '\\0')  // An empty regex matches a prefix of anything.\n    return true;\n\n  // \"$\" only matches the end of a string.  Note that regex being\n  // valid guarantees that there's nothing after \"$\" in it.\n  if (*regex == '$')\n    return *str == '\\0';\n\n  // Is the first thing in regex an escape sequence?\n  const bool escaped = *regex == '\\\\';\n  if (escaped)\n    ++regex;\n  if (IsRepeat(regex[1])) {\n    // MatchRepetitionAndRegexAtHead() calls MatchRegexAtHead(), so\n    // here's an indirect recursion.  It terminates as the regex gets\n    // shorter in each recursion.\n    return MatchRepetitionAndRegexAtHead(\n        escaped, regex[0], regex[1], regex + 2, str);\n  } else {\n    // regex isn't empty, isn't \"$\", and doesn't start with a\n    // repetition.  We match the first atom of regex with the first\n    // character of str and recurse.\n    return (*str != '\\0') && AtomMatchesChar(escaped, *regex, *str) &&\n        MatchRegexAtHead(regex + 1, str + 1);\n  }\n}\n\n// Returns true iff regex matches any substring of str.  regex must be\n// a valid simple regular expression, or the result is undefined.\n//\n// The algorithm is recursive, but the recursion depth doesn't exceed\n// the regex length, so we won't need to worry about running out of\n// stack space normally.  In rare cases the time complexity can be\n// exponential with respect to the regex length + the string length,\n// but usually it's must faster (often close to linear).\nbool MatchRegexAnywhere(const char* regex, const char* str) {\n  if (regex == NULL || str == NULL)\n    return false;\n\n  if (*regex == '^')\n    return MatchRegexAtHead(regex + 1, str);\n\n  // A successful match can be anywhere in str.\n  do {\n    if (MatchRegexAtHead(regex, str))\n      return true;\n  } while (*str++ != '\\0');\n  return false;\n}\n\n// Implements the RE class.\n\nRE::~RE() {\n  free(const_cast<char*>(pattern_));\n  free(const_cast<char*>(full_pattern_));\n}\n\n// Returns true iff regular expression re matches the entire str.\nbool RE::FullMatch(const char* str, const RE& re) {\n  return re.is_valid_ && MatchRegexAnywhere(re.full_pattern_, str);\n}\n\n// Returns true iff regular expression re matches a substring of str\n// (including str itself).\nbool RE::PartialMatch(const char* str, const RE& re) {\n  return re.is_valid_ && MatchRegexAnywhere(re.pattern_, str);\n}\n\n// Initializes an RE from its string representation.\nvoid RE::Init(const char* regex) {\n  pattern_ = full_pattern_ = NULL;\n  if (regex != NULL) {\n    pattern_ = posix::StrDup(regex);\n  }\n\n  is_valid_ = ValidateRegex(regex);\n  if (!is_valid_) {\n    // No need to calculate the full pattern when the regex is invalid.\n    return;\n  }\n\n  const size_t len = strlen(regex);\n  // Reserves enough bytes to hold the regular expression used for a\n  // full match: we need space to prepend a '^', append a '$', and\n  // terminate the string with '\\0'.\n  char* buffer = static_cast<char*>(malloc(len + 3));\n  full_pattern_ = buffer;\n\n  if (*regex != '^')\n    *buffer++ = '^';  // Makes sure full_pattern_ starts with '^'.\n\n  // We don't use snprintf or strncpy, as they trigger a warning when\n  // compiled with VC++ 8.0.\n  memcpy(buffer, regex, len);\n  buffer += len;\n\n  if (len == 0 || regex[len - 1] != '$')\n    *buffer++ = '$';  // Makes sure full_pattern_ ends with '$'.\n\n  *buffer = '\\0';\n}\n\n#endif  // GTEST_USES_POSIX_RE\n\nconst char kUnknownFile[] = \"unknown file\";\n\n// Formats a source file path and a line number as they would appear\n// in an error message from the compiler used to compile this code.\nGTEST_API_ ::std::string FormatFileLocation(const char* file, int line) {\n  const std::string file_name(file == NULL ? kUnknownFile : file);\n\n  if (line < 0) {\n    return file_name + \":\";\n  }\n#ifdef _MSC_VER\n  return file_name + \"(\" + StreamableToString(line) + \"):\";\n#else\n  return file_name + \":\" + StreamableToString(line) + \":\";\n#endif  // _MSC_VER\n}\n\n// Formats a file location for compiler-independent XML output.\n// Although this function is not platform dependent, we put it next to\n// FormatFileLocation in order to contrast the two functions.\n// Note that FormatCompilerIndependentFileLocation() does NOT append colon\n// to the file location it produces, unlike FormatFileLocation().\nGTEST_API_ ::std::string FormatCompilerIndependentFileLocation(\n    const char* file, int line) {\n  const std::string file_name(file == NULL ? kUnknownFile : file);\n\n  if (line < 0)\n    return file_name;\n  else\n    return file_name + \":\" + StreamableToString(line);\n}\n\nGTestLog::GTestLog(GTestLogSeverity severity, const char* file, int line)\n    : severity_(severity) {\n  const char* const marker =\n      severity == GTEST_INFO ?    \"[  INFO ]\" :\n      severity == GTEST_WARNING ? \"[WARNING]\" :\n      severity == GTEST_ERROR ?   \"[ ERROR ]\" : \"[ FATAL ]\";\n  GetStream() << ::std::endl << marker << \" \"\n              << FormatFileLocation(file, line).c_str() << \": \";\n}\n\n// Flushes the buffers and, if severity is GTEST_FATAL, aborts the program.\nGTestLog::~GTestLog() {\n  GetStream() << ::std::endl;\n  if (severity_ == GTEST_FATAL) {\n    fflush(stderr);\n    posix::Abort();\n  }\n}\n// Disable Microsoft deprecation warnings for POSIX functions called from\n// this class (creat, dup, dup2, and close)\nGTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)\n\n#if GTEST_HAS_STREAM_REDIRECTION\n\n// Object that captures an output stream (stdout/stderr).\nclass CapturedStream {\n public:\n  // The ctor redirects the stream to a temporary file.\n  explicit CapturedStream(int fd) : fd_(fd), uncaptured_fd_(dup(fd)) {\n# if GTEST_OS_WINDOWS\n    char temp_dir_path[MAX_PATH + 1] = { '\\0' };  // NOLINT\n    char temp_file_path[MAX_PATH + 1] = { '\\0' };  // NOLINT\n\n    ::GetTempPathA(sizeof(temp_dir_path), temp_dir_path);\n    const UINT success = ::GetTempFileNameA(temp_dir_path,\n                                            \"gtest_redir\",\n                                            0,  // Generate unique file name.\n                                            temp_file_path);\n    GTEST_CHECK_(success != 0)\n        << \"Unable to create a temporary file in \" << temp_dir_path;\n    const int captured_fd = creat(temp_file_path, _S_IREAD | _S_IWRITE);\n    GTEST_CHECK_(captured_fd != -1) << \"Unable to open temporary file \"\n                                    << temp_file_path;\n    filename_ = temp_file_path;\n# else\n    // There's no guarantee that a test has write access to the current\n    // directory, so we create the temporary file in the /tmp directory\n    // instead. We use /tmp on most systems, and /sdcard on Android.\n    // That's because Android doesn't have /tmp.\n#  if GTEST_OS_LINUX_ANDROID\n    // Note: Android applications are expected to call the framework's\n    // Context.getExternalStorageDirectory() method through JNI to get\n    // the location of the world-writable SD Card directory. However,\n    // this requires a Context handle, which cannot be retrieved\n    // globally from native code. Doing so also precludes running the\n    // code as part of a regular standalone executable, which doesn't\n    // run in a Dalvik process (e.g. when running it through 'adb shell').\n    //\n    // The location /sdcard is directly accessible from native code\n    // and is the only location (unofficially) supported by the Android\n    // team. It's generally a symlink to the real SD Card mount point\n    // which can be /mnt/sdcard, /mnt/sdcard0, /system/media/sdcard, or\n    // other OEM-customized locations. Never rely on these, and always\n    // use /sdcard.\n    char name_template[] = \"/sdcard/gtest_captured_stream.XXXXXX\";\n#  else\n    char name_template[] = \"/tmp/captured_stream.XXXXXX\";\n#  endif  // GTEST_OS_LINUX_ANDROID\n    const int captured_fd = mkstemp(name_template);\n    filename_ = name_template;\n# endif  // GTEST_OS_WINDOWS\n    fflush(NULL);\n    dup2(captured_fd, fd_);\n    close(captured_fd);\n  }\n\n  ~CapturedStream() {\n    remove(filename_.c_str());\n  }\n\n  std::string GetCapturedString() {\n    if (uncaptured_fd_ != -1) {\n      // Restores the original stream.\n      fflush(NULL);\n      dup2(uncaptured_fd_, fd_);\n      close(uncaptured_fd_);\n      uncaptured_fd_ = -1;\n    }\n\n    FILE* const file = posix::FOpen(filename_.c_str(), \"r\");\n    const std::string content = ReadEntireFile(file);\n    posix::FClose(file);\n    return content;\n  }\n\n private:\n  const int fd_;  // A stream to capture.\n  int uncaptured_fd_;\n  // Name of the temporary file holding the stderr output.\n  ::std::string filename_;\n\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(CapturedStream);\n};\n\nGTEST_DISABLE_MSC_WARNINGS_POP_()\n\nstatic CapturedStream* g_captured_stderr = NULL;\nstatic CapturedStream* g_captured_stdout = NULL;\n\n// Starts capturing an output stream (stdout/stderr).\nvoid CaptureStream(int fd, const char* stream_name, CapturedStream** stream) {\n  if (*stream != NULL) {\n    GTEST_LOG_(FATAL) << \"Only one \" << stream_name\n                      << \" capturer can exist at a time.\";\n  }\n  *stream = new CapturedStream(fd);\n}\n\n// Stops capturing the output stream and returns the captured string.\nstd::string GetCapturedStream(CapturedStream** captured_stream) {\n  const std::string content = (*captured_stream)->GetCapturedString();\n\n  delete *captured_stream;\n  *captured_stream = NULL;\n\n  return content;\n}\n\n// Starts capturing stdout.\nvoid CaptureStdout() {\n  CaptureStream(kStdOutFileno, \"stdout\", &g_captured_stdout);\n}\n\n// Starts capturing stderr.\nvoid CaptureStderr() {\n  CaptureStream(kStdErrFileno, \"stderr\", &g_captured_stderr);\n}\n\n// Stops capturing stdout and returns the captured string.\nstd::string GetCapturedStdout() {\n  return GetCapturedStream(&g_captured_stdout);\n}\n\n// Stops capturing stderr and returns the captured string.\nstd::string GetCapturedStderr() {\n  return GetCapturedStream(&g_captured_stderr);\n}\n\n#endif  // GTEST_HAS_STREAM_REDIRECTION\n\nstd::string TempDir() {\n#if GTEST_OS_WINDOWS_MOBILE\n  return \"\\\\temp\\\\\";\n#elif GTEST_OS_WINDOWS\n  const char* temp_dir = posix::GetEnv(\"TEMP\");\n  if (temp_dir == NULL || temp_dir[0] == '\\0')\n    return \"\\\\temp\\\\\";\n  else if (temp_dir[strlen(temp_dir) - 1] == '\\\\')\n    return temp_dir;\n  else\n    return std::string(temp_dir) + \"\\\\\";\n#elif GTEST_OS_LINUX_ANDROID\n  return \"/sdcard/\";\n#else\n  return \"/tmp/\";\n#endif  // GTEST_OS_WINDOWS_MOBILE\n}\n\nsize_t GetFileSize(FILE* file) {\n  fseek(file, 0, SEEK_END);\n  return static_cast<size_t>(ftell(file));\n}\n\nstd::string ReadEntireFile(FILE* file) {\n  const size_t file_size = GetFileSize(file);\n  char* const buffer = new char[file_size];\n\n  size_t bytes_last_read = 0;  // # of bytes read in the last fread()\n  size_t bytes_read = 0;       // # of bytes read so far\n\n  fseek(file, 0, SEEK_SET);\n\n  // Keeps reading the file until we cannot read further or the\n  // pre-determined file size is reached.\n  do {\n    bytes_last_read = fread(buffer+bytes_read, 1, file_size-bytes_read, file);\n    bytes_read += bytes_last_read;\n  } while (bytes_last_read > 0 && bytes_read < file_size);\n\n  const std::string content(buffer, bytes_read);\n  delete[] buffer;\n\n  return content;\n}\n\n#if GTEST_HAS_DEATH_TEST\n\nstatic const ::std::vector<testing::internal::string>* g_injected_test_argvs =\n                                        NULL;  // Owned.\n\nvoid SetInjectableArgvs(const ::std::vector<testing::internal::string>* argvs) {\n  if (g_injected_test_argvs != argvs)\n    delete g_injected_test_argvs;\n  g_injected_test_argvs = argvs;\n}\n\nconst ::std::vector<testing::internal::string>& GetInjectableArgvs() {\n  if (g_injected_test_argvs != NULL) {\n    return *g_injected_test_argvs;\n  }\n  return GetArgvs();\n}\n#endif  // GTEST_HAS_DEATH_TEST\n\n#if GTEST_OS_WINDOWS_MOBILE\nnamespace posix {\nvoid Abort() {\n  DebugBreak();\n  TerminateProcess(GetCurrentProcess(), 1);\n}\n}  // namespace posix\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n// Returns the name of the environment variable corresponding to the\n// given flag.  For example, FlagToEnvVar(\"foo\") will return\n// \"GTEST_FOO\" in the open-source version.\nstatic std::string FlagToEnvVar(const char* flag) {\n  const std::string full_flag =\n      (Message() << GTEST_FLAG_PREFIX_ << flag).GetString();\n\n  Message env_var;\n  for (size_t i = 0; i != full_flag.length(); i++) {\n    env_var << ToUpper(full_flag.c_str()[i]);\n  }\n\n  return env_var.GetString();\n}\n\n// Parses 'str' for a 32-bit signed integer.  If successful, writes\n// the result to *value and returns true; otherwise leaves *value\n// unchanged and returns false.\nbool ParseInt32(const Message& src_text, const char* str, Int32* value) {\n  // Parses the environment variable as a decimal integer.\n  char* end = NULL;\n  const long long_value = strtol(str, &end, 10);  // NOLINT\n\n  // Has strtol() consumed all characters in the string?\n  if (*end != '\\0') {\n    // No - an invalid character was encountered.\n    Message msg;\n    msg << \"WARNING: \" << src_text\n        << \" is expected to be a 32-bit integer, but actually\"\n        << \" has value \\\"\" << str << \"\\\".\\n\";\n    printf(\"%s\", msg.GetString().c_str());\n    fflush(stdout);\n    return false;\n  }\n\n  // Is the parsed value in the range of an Int32?\n  const Int32 result = static_cast<Int32>(long_value);\n  if (long_value == LONG_MAX || long_value == LONG_MIN ||\n      // The parsed value overflows as a long.  (strtol() returns\n      // LONG_MAX or LONG_MIN when the input overflows.)\n      result != long_value\n      // The parsed value overflows as an Int32.\n      ) {\n    Message msg;\n    msg << \"WARNING: \" << src_text\n        << \" is expected to be a 32-bit integer, but actually\"\n        << \" has value \" << str << \", which overflows.\\n\";\n    printf(\"%s\", msg.GetString().c_str());\n    fflush(stdout);\n    return false;\n  }\n\n  *value = result;\n  return true;\n}\n\n// Reads and returns the Boolean environment variable corresponding to\n// the given flag; if it's not set, returns default_value.\n//\n// The value is considered true iff it's not \"0\".\nbool BoolFromGTestEnv(const char* flag, bool default_value) {\n#if defined(GTEST_GET_BOOL_FROM_ENV_)\n  return GTEST_GET_BOOL_FROM_ENV_(flag, default_value);\n#endif  // defined(GTEST_GET_BOOL_FROM_ENV_)\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* const string_value = posix::GetEnv(env_var.c_str());\n  return string_value == NULL ?\n      default_value : strcmp(string_value, \"0\") != 0;\n}\n\n// Reads and returns a 32-bit integer stored in the environment\n// variable corresponding to the given flag; if it isn't set or\n// doesn't represent a valid 32-bit integer, returns default_value.\nInt32 Int32FromGTestEnv(const char* flag, Int32 default_value) {\n#if defined(GTEST_GET_INT32_FROM_ENV_)\n  return GTEST_GET_INT32_FROM_ENV_(flag, default_value);\n#endif  // defined(GTEST_GET_INT32_FROM_ENV_)\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* const string_value = posix::GetEnv(env_var.c_str());\n  if (string_value == NULL) {\n    // The environment variable is not set.\n    return default_value;\n  }\n\n  Int32 result = default_value;\n  if (!ParseInt32(Message() << \"Environment variable \" << env_var,\n                  string_value, &result)) {\n    printf(\"The default value %s is used.\\n\",\n           (Message() << default_value).GetString().c_str());\n    fflush(stdout);\n    return default_value;\n  }\n\n  return result;\n}\n\n// Reads and returns the string environment variable corresponding to\n// the given flag; if it's not set, returns default_value.\nstd::string StringFromGTestEnv(const char* flag, const char* default_value) {\n#if defined(GTEST_GET_STRING_FROM_ENV_)\n  return GTEST_GET_STRING_FROM_ENV_(flag, default_value);\n#endif  // defined(GTEST_GET_STRING_FROM_ENV_)\n  const std::string env_var = FlagToEnvVar(flag);\n  const char* value = posix::GetEnv(env_var.c_str());\n  if (value != NULL) {\n    return value;\n  }\n\n  // As a special case for the 'output' flag, if GTEST_OUTPUT is not\n  // set, we look for XML_OUTPUT_FILE, which is set by the Bazel build\n  // system.  The value of XML_OUTPUT_FILE is a filename without the\n  // \"xml:\" prefix of GTEST_OUTPUT.\n  //\n  // The net priority order after flag processing is thus:\n  //   --gtest_output command line flag\n  //   GTEST_OUTPUT environment variable\n  //   XML_OUTPUT_FILE environment variable\n  //   'default_value'\n  if (strcmp(flag, \"output\") == 0) {\n    value = posix::GetEnv(\"XML_OUTPUT_FILE\");\n    if (value != NULL) {\n      return std::string(\"xml:\") + value;\n    }\n  }\n  return default_value;\n}\n\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "mypyc/external/googletest/src/gtest-printers.cc",
    "content": "// Copyright 2007, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: wan@google.com (Zhanyong Wan)\n\n// Google Test - The Google C++ Testing Framework\n//\n// This file implements a universal value printer that can print a\n// value of any type T:\n//\n//   void ::testing::internal::UniversalPrinter<T>::Print(value, ostream_ptr);\n//\n// It uses the << operator when possible, and prints the bytes in the\n// object otherwise.  A user can override its behavior for a class\n// type Foo by defining either operator<<(::std::ostream&, const Foo&)\n// or void PrintTo(const Foo&, ::std::ostream*) in the namespace that\n// defines Foo.\n\n#include \"gtest/gtest-printers.h\"\n#include <ctype.h>\n#include <stdio.h>\n#include <cwchar>\n#include <ostream>  // NOLINT\n#include <string>\n#include \"gtest/internal/gtest-port.h\"\n\nnamespace testing {\n\nnamespace {\n\nusing ::std::ostream;\n\n// Prints a segment of bytes in the given object.\nGTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\nvoid PrintByteSegmentInObjectTo(const unsigned char* obj_bytes, size_t start,\n                                size_t count, ostream* os) {\n  char text[5] = \"\";\n  for (size_t i = 0; i != count; i++) {\n    const size_t j = start + i;\n    if (i != 0) {\n      // Organizes the bytes into groups of 2 for easy parsing by\n      // human.\n      if ((j % 2) == 0)\n        *os << ' ';\n      else\n        *os << '-';\n    }\n    GTEST_SNPRINTF_(text, sizeof(text), \"%02X\", obj_bytes[j]);\n    *os << text;\n  }\n}\n\n// Prints the bytes in the given value to the given ostream.\nvoid PrintBytesInObjectToImpl(const unsigned char* obj_bytes, size_t count,\n                              ostream* os) {\n  // Tells the user how big the object is.\n  *os << count << \"-byte object <\";\n\n  const size_t kThreshold = 132;\n  const size_t kChunkSize = 64;\n  // If the object size is bigger than kThreshold, we'll have to omit\n  // some details by printing only the first and the last kChunkSize\n  // bytes.\n  // TODO(wan): let the user control the threshold using a flag.\n  if (count < kThreshold) {\n    PrintByteSegmentInObjectTo(obj_bytes, 0, count, os);\n  } else {\n    PrintByteSegmentInObjectTo(obj_bytes, 0, kChunkSize, os);\n    *os << \" ... \";\n    // Rounds up to 2-byte boundary.\n    const size_t resume_pos = (count - kChunkSize + 1)/2*2;\n    PrintByteSegmentInObjectTo(obj_bytes, resume_pos, count - resume_pos, os);\n  }\n  *os << \">\";\n}\n\n}  // namespace\n\nnamespace internal2 {\n\n// Delegates to PrintBytesInObjectToImpl() to print the bytes in the\n// given object.  The delegation simplifies the implementation, which\n// uses the << operator and thus is easier done outside of the\n// ::testing::internal namespace, which contains a << operator that\n// sometimes conflicts with the one in STL.\nvoid PrintBytesInObjectTo(const unsigned char* obj_bytes, size_t count,\n                          ostream* os) {\n  PrintBytesInObjectToImpl(obj_bytes, count, os);\n}\n\n}  // namespace internal2\n\nnamespace internal {\n\n// Depending on the value of a char (or wchar_t), we print it in one\n// of three formats:\n//   - as is if it's a printable ASCII (e.g. 'a', '2', ' '),\n//   - as a hexidecimal escape sequence (e.g. '\\x7F'), or\n//   - as a special escape sequence (e.g. '\\r', '\\n').\nenum CharFormat {\n  kAsIs,\n  kHexEscape,\n  kSpecialEscape\n};\n\n// Returns true if c is a printable ASCII character.  We test the\n// value of c directly instead of calling isprint(), which is buggy on\n// Windows Mobile.\ninline bool IsPrintableAscii(wchar_t c) {\n  return 0x20 <= c && c <= 0x7E;\n}\n\n// Prints a wide or narrow char c as a character literal without the\n// quotes, escaping it when necessary; returns how c was formatted.\n// The template argument UnsignedChar is the unsigned version of Char,\n// which is the type of c.\ntemplate <typename UnsignedChar, typename Char>\nstatic CharFormat PrintAsCharLiteralTo(Char c, ostream* os) {\n  switch (static_cast<wchar_t>(c)) {\n    case L'\\0':\n      *os << \"\\\\0\";\n      break;\n    case L'\\'':\n      *os << \"\\\\'\";\n      break;\n    case L'\\\\':\n      *os << \"\\\\\\\\\";\n      break;\n    case L'\\a':\n      *os << \"\\\\a\";\n      break;\n    case L'\\b':\n      *os << \"\\\\b\";\n      break;\n    case L'\\f':\n      *os << \"\\\\f\";\n      break;\n    case L'\\n':\n      *os << \"\\\\n\";\n      break;\n    case L'\\r':\n      *os << \"\\\\r\";\n      break;\n    case L'\\t':\n      *os << \"\\\\t\";\n      break;\n    case L'\\v':\n      *os << \"\\\\v\";\n      break;\n    default:\n      if (IsPrintableAscii(c)) {\n        *os << static_cast<char>(c);\n        return kAsIs;\n      } else {\n        *os << \"\\\\x\" + String::FormatHexInt(static_cast<UnsignedChar>(c));\n        return kHexEscape;\n      }\n  }\n  return kSpecialEscape;\n}\n\n// Prints a wchar_t c as if it's part of a string literal, escaping it when\n// necessary; returns how c was formatted.\nstatic CharFormat PrintAsStringLiteralTo(wchar_t c, ostream* os) {\n  switch (c) {\n    case L'\\'':\n      *os << \"'\";\n      return kAsIs;\n    case L'\"':\n      *os << \"\\\\\\\"\";\n      return kSpecialEscape;\n    default:\n      return PrintAsCharLiteralTo<wchar_t>(c, os);\n  }\n}\n\n// Prints a char c as if it's part of a string literal, escaping it when\n// necessary; returns how c was formatted.\nstatic CharFormat PrintAsStringLiteralTo(char c, ostream* os) {\n  return PrintAsStringLiteralTo(\n      static_cast<wchar_t>(static_cast<unsigned char>(c)), os);\n}\n\n// Prints a wide or narrow character c and its code.  '\\0' is printed\n// as \"'\\\\0'\", other unprintable characters are also properly escaped\n// using the standard C++ escape sequence.  The template argument\n// UnsignedChar is the unsigned version of Char, which is the type of c.\ntemplate <typename UnsignedChar, typename Char>\nvoid PrintCharAndCodeTo(Char c, ostream* os) {\n  // First, print c as a literal in the most readable form we can find.\n  *os << ((sizeof(c) > 1) ? \"L'\" : \"'\");\n  const CharFormat format = PrintAsCharLiteralTo<UnsignedChar>(c, os);\n  *os << \"'\";\n\n  // To aid user debugging, we also print c's code in decimal, unless\n  // it's 0 (in which case c was printed as '\\\\0', making the code\n  // obvious).\n  if (c == 0)\n    return;\n  *os << \" (\" << static_cast<int>(c);\n\n  // For more convenience, we print c's code again in hexidecimal,\n  // unless c was already printed in the form '\\x##' or the code is in\n  // [1, 9].\n  if (format == kHexEscape || (1 <= c && c <= 9)) {\n    // Do nothing.\n  } else {\n    *os << \", 0x\" << String::FormatHexInt(static_cast<UnsignedChar>(c));\n  }\n  *os << \")\";\n}\n\nvoid PrintTo(unsigned char c, ::std::ostream* os) {\n  PrintCharAndCodeTo<unsigned char>(c, os);\n}\nvoid PrintTo(signed char c, ::std::ostream* os) {\n  PrintCharAndCodeTo<unsigned char>(c, os);\n}\n\n// Prints a wchar_t as a symbol if it is printable or as its internal\n// code otherwise and also as its code.  L'\\0' is printed as \"L'\\\\0'\".\nvoid PrintTo(wchar_t wc, ostream* os) {\n  PrintCharAndCodeTo<wchar_t>(wc, os);\n}\n\n// Prints the given array of characters to the ostream.  CharType must be either\n// char or wchar_t.\n// The array starts at begin, the length is len, it may include '\\0' characters\n// and may not be NUL-terminated.\ntemplate <typename CharType>\nGTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\nstatic void PrintCharsAsStringTo(\n    const CharType* begin, size_t len, ostream* os) {\n  const char* const kQuoteBegin = sizeof(CharType) == 1 ? \"\\\"\" : \"L\\\"\";\n  *os << kQuoteBegin;\n  bool is_previous_hex = false;\n  for (size_t index = 0; index < len; ++index) {\n    const CharType cur = begin[index];\n    if (is_previous_hex && IsXDigit(cur)) {\n      // Previous character is of '\\x..' form and this character can be\n      // interpreted as another hexadecimal digit in its number. Break string to\n      // disambiguate.\n      *os << \"\\\" \" << kQuoteBegin;\n    }\n    is_previous_hex = PrintAsStringLiteralTo(cur, os) == kHexEscape;\n  }\n  *os << \"\\\"\";\n}\n\n// Prints a (const) char/wchar_t array of 'len' elements, starting at address\n// 'begin'.  CharType must be either char or wchar_t.\ntemplate <typename CharType>\nGTEST_ATTRIBUTE_NO_SANITIZE_MEMORY_\nGTEST_ATTRIBUTE_NO_SANITIZE_ADDRESS_\nGTEST_ATTRIBUTE_NO_SANITIZE_THREAD_\nstatic void UniversalPrintCharArray(\n    const CharType* begin, size_t len, ostream* os) {\n  // The code\n  //   const char kFoo[] = \"foo\";\n  // generates an array of 4, not 3, elements, with the last one being '\\0'.\n  //\n  // Therefore when printing a char array, we don't print the last element if\n  // it's '\\0', such that the output matches the string literal as it's\n  // written in the source code.\n  if (len > 0 && begin[len - 1] == '\\0') {\n    PrintCharsAsStringTo(begin, len - 1, os);\n    return;\n  }\n\n  // If, however, the last element in the array is not '\\0', e.g.\n  //    const char kFoo[] = { 'f', 'o', 'o' };\n  // we must print the entire array.  We also print a message to indicate\n  // that the array is not NUL-terminated.\n  PrintCharsAsStringTo(begin, len, os);\n  *os << \" (no terminating NUL)\";\n}\n\n// Prints a (const) char array of 'len' elements, starting at address 'begin'.\nvoid UniversalPrintArray(const char* begin, size_t len, ostream* os) {\n  UniversalPrintCharArray(begin, len, os);\n}\n\n// Prints a (const) wchar_t array of 'len' elements, starting at address\n// 'begin'.\nvoid UniversalPrintArray(const wchar_t* begin, size_t len, ostream* os) {\n  UniversalPrintCharArray(begin, len, os);\n}\n\n// Prints the given C string to the ostream.\nvoid PrintTo(const char* s, ostream* os) {\n  if (s == NULL) {\n    *os << \"NULL\";\n  } else {\n    *os << ImplicitCast_<const void*>(s) << \" pointing to \";\n    PrintCharsAsStringTo(s, strlen(s), os);\n  }\n}\n\n// MSVC compiler can be configured to define whar_t as a typedef\n// of unsigned short. Defining an overload for const wchar_t* in that case\n// would cause pointers to unsigned shorts be printed as wide strings,\n// possibly accessing more memory than intended and causing invalid\n// memory accesses. MSVC defines _NATIVE_WCHAR_T_DEFINED symbol when\n// wchar_t is implemented as a native type.\n#if !defined(_MSC_VER) || defined(_NATIVE_WCHAR_T_DEFINED)\n// Prints the given wide C string to the ostream.\nvoid PrintTo(const wchar_t* s, ostream* os) {\n  if (s == NULL) {\n    *os << \"NULL\";\n  } else {\n    *os << ImplicitCast_<const void*>(s) << \" pointing to \";\n    PrintCharsAsStringTo(s, std::wcslen(s), os);\n  }\n}\n#endif  // wchar_t is native\n\n// Prints a ::string object.\n#if GTEST_HAS_GLOBAL_STRING\nvoid PrintStringTo(const ::string& s, ostream* os) {\n  PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n#endif  // GTEST_HAS_GLOBAL_STRING\n\nvoid PrintStringTo(const ::std::string& s, ostream* os) {\n  PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n\n// Prints a ::wstring object.\n#if GTEST_HAS_GLOBAL_WSTRING\nvoid PrintWideStringTo(const ::wstring& s, ostream* os) {\n  PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n#endif  // GTEST_HAS_GLOBAL_WSTRING\n\n#if GTEST_HAS_STD_WSTRING\nvoid PrintWideStringTo(const ::std::wstring& s, ostream* os) {\n  PrintCharsAsStringTo(s.data(), s.size(), os);\n}\n#endif  // GTEST_HAS_STD_WSTRING\n\n}  // namespace internal\n\n}  // namespace testing\n"
  },
  {
    "path": "mypyc/external/googletest/src/gtest-test-part.cc",
    "content": "// Copyright 2008, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: mheule@google.com (Markus Heule)\n//\n// The Google C++ Testing Framework (Google Test)\n\n#include \"gtest/gtest-test-part.h\"\n\n// Indicates that this translation unit is part of Google Test's\n// implementation.  It must come before gtest-internal-inl.h is\n// included, or there will be a compiler error.  This trick exists to\n// prevent the accidental inclusion of gtest-internal-inl.h in the\n// user's code.\n#define GTEST_IMPLEMENTATION_ 1\n#include \"src/gtest-internal-inl.h\"\n#undef GTEST_IMPLEMENTATION_\n\nnamespace testing {\n\nusing internal::GetUnitTestImpl;\n\n// Gets the summary of the failure message by omitting the stack trace\n// in it.\nstd::string TestPartResult::ExtractSummary(const char* message) {\n  const char* const stack_trace = strstr(message, internal::kStackTraceMarker);\n  return stack_trace == NULL ? message :\n      std::string(message, stack_trace);\n}\n\n// Prints a TestPartResult object.\nstd::ostream& operator<<(std::ostream& os, const TestPartResult& result) {\n  return os\n      << result.file_name() << \":\" << result.line_number() << \": \"\n      << (result.type() == TestPartResult::kSuccess ? \"Success\" :\n          result.type() == TestPartResult::kFatalFailure ? \"Fatal failure\" :\n          \"Non-fatal failure\") << \":\\n\"\n      << result.message() << std::endl;\n}\n\n// Appends a TestPartResult to the array.\nvoid TestPartResultArray::Append(const TestPartResult& result) {\n  array_.push_back(result);\n}\n\n// Returns the TestPartResult at the given index (0-based).\nconst TestPartResult& TestPartResultArray::GetTestPartResult(int index) const {\n  if (index < 0 || index >= size()) {\n    printf(\"\\nInvalid index (%d) into TestPartResultArray.\\n\", index);\n    internal::posix::Abort();\n  }\n\n  return array_[index];\n}\n\n// Returns the number of TestPartResult objects in the array.\nint TestPartResultArray::size() const {\n  return static_cast<int>(array_.size());\n}\n\nnamespace internal {\n\nHasNewFatalFailureHelper::HasNewFatalFailureHelper()\n    : has_new_fatal_failure_(false),\n      original_reporter_(GetUnitTestImpl()->\n                         GetTestPartResultReporterForCurrentThread()) {\n  GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(this);\n}\n\nHasNewFatalFailureHelper::~HasNewFatalFailureHelper() {\n  GetUnitTestImpl()->SetTestPartResultReporterForCurrentThread(\n      original_reporter_);\n}\n\nvoid HasNewFatalFailureHelper::ReportTestPartResult(\n    const TestPartResult& result) {\n  if (result.fatally_failed())\n    has_new_fatal_failure_ = true;\n  original_reporter_->ReportTestPartResult(result);\n}\n\n}  // namespace internal\n\n}  // namespace testing\n"
  },
  {
    "path": "mypyc/external/googletest/src/gtest-typed-test.cc",
    "content": "// Copyright 2008 Google Inc.\n// All Rights Reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: wan@google.com (Zhanyong Wan)\n\n#include \"gtest/gtest-typed-test.h\"\n#include \"gtest/gtest.h\"\n\nnamespace testing {\nnamespace internal {\n\n#if GTEST_HAS_TYPED_TEST_P\n\n// Skips to the first non-space char in str. Returns an empty string if str\n// contains only whitespace characters.\nstatic const char* SkipSpaces(const char* str) {\n  while (IsSpace(*str))\n    str++;\n  return str;\n}\n\nstatic std::vector<std::string> SplitIntoTestNames(const char* src) {\n  std::vector<std::string> name_vec;\n  src = SkipSpaces(src);\n  for (; src != NULL; src = SkipComma(src)) {\n    name_vec.push_back(StripTrailingSpaces(GetPrefixUntilComma(src)));\n  }\n  return name_vec;\n}\n\n// Verifies that registered_tests match the test names in\n// registered_tests_; returns registered_tests if successful, or\n// aborts the program otherwise.\nconst char* TypedTestCasePState::VerifyRegisteredTestNames(\n    const char* file, int line, const char* registered_tests) {\n  typedef RegisteredTestsMap::const_iterator RegisteredTestIter;\n  registered_ = true;\n\n  std::vector<std::string> name_vec = SplitIntoTestNames(registered_tests);\n\n  Message errors;\n\n  std::set<std::string> tests;\n  for (std::vector<std::string>::const_iterator name_it = name_vec.begin();\n       name_it != name_vec.end(); ++name_it) {\n    const std::string& name = *name_it;\n    if (tests.count(name) != 0) {\n      errors << \"Test \" << name << \" is listed more than once.\\n\";\n      continue;\n    }\n\n    bool found = false;\n    for (RegisteredTestIter it = registered_tests_.begin();\n         it != registered_tests_.end();\n         ++it) {\n      if (name == it->first) {\n        found = true;\n        break;\n      }\n    }\n\n    if (found) {\n      tests.insert(name);\n    } else {\n      errors << \"No test named \" << name\n             << \" can be found in this test case.\\n\";\n    }\n  }\n\n  for (RegisteredTestIter it = registered_tests_.begin();\n       it != registered_tests_.end();\n       ++it) {\n    if (tests.count(it->first) == 0) {\n      errors << \"You forgot to list test \" << it->first << \".\\n\";\n    }\n  }\n\n  const std::string& errors_str = errors.GetString();\n  if (errors_str != \"\") {\n    fprintf(stderr, \"%s %s\", FormatFileLocation(file, line).c_str(),\n            errors_str.c_str());\n    fflush(stderr);\n    posix::Abort();\n  }\n\n  return registered_tests;\n}\n\n#endif  // GTEST_HAS_TYPED_TEST_P\n\n}  // namespace internal\n}  // namespace testing\n"
  },
  {
    "path": "mypyc/external/googletest/src/gtest.cc",
    "content": "// Copyright 2005, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n//\n// Author: wan@google.com (Zhanyong Wan)\n//\n// The Google C++ Testing Framework (Google Test)\n\n#include \"gtest/gtest.h\"\n#include \"gtest/internal/custom/gtest.h\"\n#include \"gtest/gtest-spi.h\"\n\n#include <ctype.h>\n#include <math.h>\n#include <stdarg.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <wchar.h>\n#include <wctype.h>\n\n#include <algorithm>\n#include <iomanip>\n#include <limits>\n#include <list>\n#include <map>\n#include <ostream>  // NOLINT\n#include <sstream>\n#include <vector>\n\n#if GTEST_OS_LINUX\n\n// TODO(kenton@google.com): Use autoconf to detect availability of\n// gettimeofday().\n# define GTEST_HAS_GETTIMEOFDAY_ 1\n\n# include <fcntl.h>  // NOLINT\n# include <limits.h>  // NOLINT\n# include <sched.h>  // NOLINT\n// Declares vsnprintf().  This header is not available on Windows.\n# include <strings.h>  // NOLINT\n# include <sys/mman.h>  // NOLINT\n# include <sys/time.h>  // NOLINT\n# include <unistd.h>  // NOLINT\n# include <string>\n\n#elif GTEST_OS_SYMBIAN\n# define GTEST_HAS_GETTIMEOFDAY_ 1\n# include <sys/time.h>  // NOLINT\n\n#elif GTEST_OS_ZOS\n# define GTEST_HAS_GETTIMEOFDAY_ 1\n# include <sys/time.h>  // NOLINT\n\n// On z/OS we additionally need strings.h for strcasecmp.\n# include <strings.h>  // NOLINT\n\n#elif GTEST_OS_WINDOWS_MOBILE  // We are on Windows CE.\n\n# include <windows.h>  // NOLINT\n# undef min\n\n#elif GTEST_OS_WINDOWS  // We are on Windows proper.\n\n# include <io.h>  // NOLINT\n# include <sys/timeb.h>  // NOLINT\n# include <sys/types.h>  // NOLINT\n# include <sys/stat.h>  // NOLINT\n\n# if GTEST_OS_WINDOWS_MINGW\n// MinGW has gettimeofday() but not _ftime64().\n// TODO(kenton@google.com): Use autoconf to detect availability of\n//   gettimeofday().\n// TODO(kenton@google.com): There are other ways to get the time on\n//   Windows, like GetTickCount() or GetSystemTimeAsFileTime().  MinGW\n//   supports these.  consider using them instead.\n#  define GTEST_HAS_GETTIMEOFDAY_ 1\n#  include <sys/time.h>  // NOLINT\n# endif  // GTEST_OS_WINDOWS_MINGW\n\n// cpplint thinks that the header is already included, so we want to\n// silence it.\n# include <windows.h>  // NOLINT\n# undef min\n\n#else\n\n// Assume other platforms have gettimeofday().\n// TODO(kenton@google.com): Use autoconf to detect availability of\n//   gettimeofday().\n# define GTEST_HAS_GETTIMEOFDAY_ 1\n\n// cpplint thinks that the header is already included, so we want to\n// silence it.\n# include <sys/time.h>  // NOLINT\n# include <unistd.h>  // NOLINT\n\n#endif  // GTEST_OS_LINUX\n\n#if GTEST_HAS_EXCEPTIONS\n# include <stdexcept>\n#endif\n\n#if GTEST_CAN_STREAM_RESULTS_\n# include <arpa/inet.h>  // NOLINT\n# include <netdb.h>  // NOLINT\n# include <sys/socket.h>  // NOLINT\n# include <sys/types.h>  // NOLINT\n#endif\n\n// Indicates that this translation unit is part of Google Test's\n// implementation.  It must come before gtest-internal-inl.h is\n// included, or there will be a compiler error.  This trick is to\n// prevent a user from accidentally including gtest-internal-inl.h in\n// his code.\n#define GTEST_IMPLEMENTATION_ 1\n#include \"src/gtest-internal-inl.h\"\n#undef GTEST_IMPLEMENTATION_\n\n#if GTEST_OS_WINDOWS\n# define vsnprintf _vsnprintf\n#endif  // GTEST_OS_WINDOWS\n\nnamespace testing {\n\nusing internal::CountIf;\nusing internal::ForEach;\nusing internal::GetElementOr;\nusing internal::Shuffle;\n\n// Constants.\n\n// A test whose test case name or test name matches this filter is\n// disabled and not run.\nstatic const char kDisableTestFilter[] = \"DISABLED_*:*/DISABLED_*\";\n\n// A test case whose name matches this filter is considered a death\n// test case and will be run before test cases whose name doesn't\n// match this filter.\nstatic const char kDeathTestCaseFilter[] = \"*DeathTest:*DeathTest/*\";\n\n// A test filter that matches everything.\nstatic const char kUniversalFilter[] = \"*\";\n\n// The default output file for XML output.\nstatic const char kDefaultOutputFile[] = \"test_detail.xml\";\n\n// The environment variable name for the test shard index.\nstatic const char kTestShardIndex[] = \"GTEST_SHARD_INDEX\";\n// The environment variable name for the total number of test shards.\nstatic const char kTestTotalShards[] = \"GTEST_TOTAL_SHARDS\";\n// The environment variable name for the test shard status file.\nstatic const char kTestShardStatusFile[] = \"GTEST_SHARD_STATUS_FILE\";\n\nnamespace internal {\n\n// The text used in failure messages to indicate the start of the\n// stack trace.\nconst char kStackTraceMarker[] = \"\\nStack trace:\\n\";\n\n// g_help_flag is true iff the --help flag or an equivalent form is\n// specified on the command line.\nbool g_help_flag = false;\n\n}  // namespace internal\n\nstatic const char* GetDefaultFilter() {\n#ifdef GTEST_TEST_FILTER_ENV_VAR_\n  const char* const testbridge_test_only = getenv(GTEST_TEST_FILTER_ENV_VAR_);\n  if (testbridge_test_only != NULL) {\n    return testbridge_test_only;\n  }\n#endif  // GTEST_TEST_FILTER_ENV_VAR_\n  return kUniversalFilter;\n}\n\nGTEST_DEFINE_bool_(\n    also_run_disabled_tests,\n    internal::BoolFromGTestEnv(\"also_run_disabled_tests\", false),\n    \"Run disabled tests too, in addition to the tests normally being run.\");\n\nGTEST_DEFINE_bool_(\n    break_on_failure,\n    internal::BoolFromGTestEnv(\"break_on_failure\", false),\n    \"True iff a failed assertion should be a debugger break-point.\");\n\nGTEST_DEFINE_bool_(\n    catch_exceptions,\n    internal::BoolFromGTestEnv(\"catch_exceptions\", true),\n    \"True iff \" GTEST_NAME_\n    \" should catch exceptions and treat them as test failures.\");\n\nGTEST_DEFINE_string_(\n    color,\n    internal::StringFromGTestEnv(\"color\", \"auto\"),\n    \"Whether to use colors in the output.  Valid values: yes, no, \"\n    \"and auto.  'auto' means to use colors if the output is \"\n    \"being sent to a terminal and the TERM environment variable \"\n    \"is set to a terminal type that supports colors.\");\n\nGTEST_DEFINE_string_(\n    filter,\n    internal::StringFromGTestEnv(\"filter\", GetDefaultFilter()),\n    \"A colon-separated list of glob (not regex) patterns \"\n    \"for filtering the tests to run, optionally followed by a \"\n    \"'-' and a : separated list of negative patterns (tests to \"\n    \"exclude).  A test is run if it matches one of the positive \"\n    \"patterns and does not match any of the negative patterns.\");\n\nGTEST_DEFINE_bool_(list_tests, false,\n                   \"List all tests without running them.\");\n\nGTEST_DEFINE_string_(\n    output,\n    internal::StringFromGTestEnv(\"output\", \"\"),\n    \"A format (currently must be \\\"xml\\\"), optionally followed \"\n    \"by a colon and an output file name or directory. A directory \"\n    \"is indicated by a trailing pathname separator. \"\n    \"Examples: \\\"xml:filename.xml\\\", \\\"xml::directoryname/\\\". \"\n    \"If a directory is specified, output files will be created \"\n    \"within that directory, with file-names based on the test \"\n    \"executable's name and, if necessary, made unique by adding \"\n    \"digits.\");\n\nGTEST_DEFINE_bool_(\n    print_time,\n    internal::BoolFromGTestEnv(\"print_time\", true),\n    \"True iff \" GTEST_NAME_\n    \" should display elapsed time in text output.\");\n\nGTEST_DEFINE_int32_(\n    random_seed,\n    internal::Int32FromGTestEnv(\"random_seed\", 0),\n    \"Random number seed to use when shuffling test orders.  Must be in range \"\n    \"[1, 99999], or 0 to use a seed based on the current time.\");\n\nGTEST_DEFINE_int32_(\n    repeat,\n    internal::Int32FromGTestEnv(\"repeat\", 1),\n    \"How many times to repeat each test.  Specify a negative number \"\n    \"for repeating forever.  Useful for shaking out flaky tests.\");\n\nGTEST_DEFINE_bool_(\n    show_internal_stack_frames, false,\n    \"True iff \" GTEST_NAME_ \" should include internal stack frames when \"\n    \"printing test failure stack traces.\");\n\nGTEST_DEFINE_bool_(\n    shuffle,\n    internal::BoolFromGTestEnv(\"shuffle\", false),\n    \"True iff \" GTEST_NAME_\n    \" should randomize tests' order on every run.\");\n\nGTEST_DEFINE_int32_(\n    stack_trace_depth,\n    internal::Int32FromGTestEnv(\"stack_trace_depth\", kMaxStackTraceDepth),\n    \"The maximum number of stack frames to print when an \"\n    \"assertion fails.  The valid range is 0 through 100, inclusive.\");\n\nGTEST_DEFINE_string_(\n    stream_result_to,\n    internal::StringFromGTestEnv(\"stream_result_to\", \"\"),\n    \"This flag specifies the host name and the port number on which to stream \"\n    \"test results. Example: \\\"localhost:555\\\". The flag is effective only on \"\n    \"Linux.\");\n\nGTEST_DEFINE_bool_(\n    throw_on_failure,\n    internal::BoolFromGTestEnv(\"throw_on_failure\", false),\n    \"When this flag is specified, a failed assertion will throw an exception \"\n    \"if exceptions are enabled or exit the program with a non-zero code \"\n    \"otherwise.\");\n\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\nGTEST_DEFINE_string_(\n    flagfile,\n    internal::StringFromGTestEnv(\"flagfile\", \"\"),\n    \"This flag specifies the flagfile to read command-line flags from.\");\n#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_\n\nnamespace internal {\n\n// Generates a random number from [0, range), using a Linear\n// Congruential Generator (LCG).  Crashes if 'range' is 0 or greater\n// than kMaxRange.\nUInt32 Random::Generate(UInt32 range) {\n  // These constants are the same as are used in glibc's rand(3).\n  state_ = (1103515245U*state_ + 12345U) % kMaxRange;\n\n  GTEST_CHECK_(range > 0)\n      << \"Cannot generate a number in the range [0, 0).\";\n  GTEST_CHECK_(range <= kMaxRange)\n      << \"Generation of a number in [0, \" << range << \") was requested, \"\n      << \"but this can only generate numbers in [0, \" << kMaxRange << \").\";\n\n  // Converting via modulus introduces a bit of downward bias, but\n  // it's simple, and a linear congruential generator isn't too good\n  // to begin with.\n  return state_ % range;\n}\n\n// GTestIsInitialized() returns true iff the user has initialized\n// Google Test.  Useful for catching the user mistake of not initializing\n// Google Test before calling RUN_ALL_TESTS().\nstatic bool GTestIsInitialized() { return GetArgvs().size() > 0; }\n\n// Iterates over a vector of TestCases, keeping a running sum of the\n// results of calling a given int-returning method on each.\n// Returns the sum.\nstatic int SumOverTestCaseList(const std::vector<TestCase*>& case_list,\n                               int (TestCase::*method)() const) {\n  int sum = 0;\n  for (size_t i = 0; i < case_list.size(); i++) {\n    sum += (case_list[i]->*method)();\n  }\n  return sum;\n}\n\n// Returns true iff the test case passed.\nstatic bool TestCasePassed(const TestCase* test_case) {\n  return test_case->should_run() && test_case->Passed();\n}\n\n// Returns true iff the test case failed.\nstatic bool TestCaseFailed(const TestCase* test_case) {\n  return test_case->should_run() && test_case->Failed();\n}\n\n// Returns true iff test_case contains at least one test that should\n// run.\nstatic bool ShouldRunTestCase(const TestCase* test_case) {\n  return test_case->should_run();\n}\n\n// AssertHelper constructor.\nAssertHelper::AssertHelper(TestPartResult::Type type,\n                           const char* file,\n                           int line,\n                           const char* message)\n    : data_(new AssertHelperData(type, file, line, message)) {\n}\n\nAssertHelper::~AssertHelper() {\n  delete data_;\n}\n\n// Message assignment, for assertion streaming support.\nvoid AssertHelper::operator=(const Message& message) const {\n  UnitTest::GetInstance()->\n    AddTestPartResult(data_->type, data_->file, data_->line,\n                      AppendUserMessage(data_->message, message),\n                      UnitTest::GetInstance()->impl()\n                      ->CurrentOsStackTraceExceptTop(1)\n                      // Skips the stack frame for this function itself.\n                      );  // NOLINT\n}\n\n// Mutex for linked pointers.\nGTEST_API_ GTEST_DEFINE_STATIC_MUTEX_(g_linked_ptr_mutex);\n\n// A copy of all command line arguments.  Set by InitGoogleTest().\n::std::vector<testing::internal::string> g_argvs;\n\nconst ::std::vector<testing::internal::string>& GetArgvs() {\n#if defined(GTEST_CUSTOM_GET_ARGVS_)\n  return GTEST_CUSTOM_GET_ARGVS_();\n#else  // defined(GTEST_CUSTOM_GET_ARGVS_)\n  return g_argvs;\n#endif  // defined(GTEST_CUSTOM_GET_ARGVS_)\n}\n\n// Returns the current application's name, removing directory path if that\n// is present.\nFilePath GetCurrentExecutableName() {\n  FilePath result;\n\n#if GTEST_OS_WINDOWS\n  result.Set(FilePath(GetArgvs()[0]).RemoveExtension(\"exe\"));\n#else\n  result.Set(FilePath(GetArgvs()[0]));\n#endif  // GTEST_OS_WINDOWS\n\n  return result.RemoveDirectoryName();\n}\n\n// Functions for processing the gtest_output flag.\n\n// Returns the output format, or \"\" for normal printed output.\nstd::string UnitTestOptions::GetOutputFormat() {\n  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();\n  if (gtest_output_flag == NULL) return std::string(\"\");\n\n  const char* const colon = strchr(gtest_output_flag, ':');\n  return (colon == NULL) ?\n      std::string(gtest_output_flag) :\n      std::string(gtest_output_flag, colon - gtest_output_flag);\n}\n\n// Returns the name of the requested output file, or the default if none\n// was explicitly specified.\nstd::string UnitTestOptions::GetAbsolutePathToOutputFile() {\n  const char* const gtest_output_flag = GTEST_FLAG(output).c_str();\n  if (gtest_output_flag == NULL)\n    return \"\";\n\n  const char* const colon = strchr(gtest_output_flag, ':');\n  if (colon == NULL)\n    return internal::FilePath::ConcatPaths(\n        internal::FilePath(\n            UnitTest::GetInstance()->original_working_dir()),\n        internal::FilePath(kDefaultOutputFile)).string();\n\n  internal::FilePath output_name(colon + 1);\n  if (!output_name.IsAbsolutePath())\n    // TODO(wan@google.com): on Windows \\some\\path is not an absolute\n    // path (as its meaning depends on the current drive), yet the\n    // following logic for turning it into an absolute path is wrong.\n    // Fix it.\n    output_name = internal::FilePath::ConcatPaths(\n        internal::FilePath(UnitTest::GetInstance()->original_working_dir()),\n        internal::FilePath(colon + 1));\n\n  if (!output_name.IsDirectory())\n    return output_name.string();\n\n  internal::FilePath result(internal::FilePath::GenerateUniqueFileName(\n      output_name, internal::GetCurrentExecutableName(),\n      GetOutputFormat().c_str()));\n  return result.string();\n}\n\n// Returns true iff the wildcard pattern matches the string.  The\n// first ':' or '\\0' character in pattern marks the end of it.\n//\n// This recursive algorithm isn't very efficient, but is clear and\n// works well enough for matching test names, which are short.\nbool UnitTestOptions::PatternMatchesString(const char *pattern,\n                                           const char *str) {\n  switch (*pattern) {\n    case '\\0':\n    case ':':  // Either ':' or '\\0' marks the end of the pattern.\n      return *str == '\\0';\n    case '?':  // Matches any single character.\n      return *str != '\\0' && PatternMatchesString(pattern + 1, str + 1);\n    case '*':  // Matches any string (possibly empty) of characters.\n      return (*str != '\\0' && PatternMatchesString(pattern, str + 1)) ||\n          PatternMatchesString(pattern + 1, str);\n    default:  // Non-special character.  Matches itself.\n      return *pattern == *str &&\n          PatternMatchesString(pattern + 1, str + 1);\n  }\n}\n\nbool UnitTestOptions::MatchesFilter(\n    const std::string& name, const char* filter) {\n  const char *cur_pattern = filter;\n  for (;;) {\n    if (PatternMatchesString(cur_pattern, name.c_str())) {\n      return true;\n    }\n\n    // Finds the next pattern in the filter.\n    cur_pattern = strchr(cur_pattern, ':');\n\n    // Returns if no more pattern can be found.\n    if (cur_pattern == NULL) {\n      return false;\n    }\n\n    // Skips the pattern separater (the ':' character).\n    cur_pattern++;\n  }\n}\n\n// Returns true iff the user-specified filter matches the test case\n// name and the test name.\nbool UnitTestOptions::FilterMatchesTest(const std::string &test_case_name,\n                                        const std::string &test_name) {\n  const std::string& full_name = test_case_name + \".\" + test_name.c_str();\n\n  // Split --gtest_filter at '-', if there is one, to separate into\n  // positive filter and negative filter portions\n  const char* const p = GTEST_FLAG(filter).c_str();\n  const char* const dash = strchr(p, '-');\n  std::string positive;\n  std::string negative;\n  if (dash == NULL) {\n    positive = GTEST_FLAG(filter).c_str();  // Whole string is a positive filter\n    negative = \"\";\n  } else {\n    positive = std::string(p, dash);   // Everything up to the dash\n    negative = std::string(dash + 1);  // Everything after the dash\n    if (positive.empty()) {\n      // Treat '-test1' as the same as '*-test1'\n      positive = kUniversalFilter;\n    }\n  }\n\n  // A filter is a colon-separated list of patterns.  It matches a\n  // test if any pattern in it matches the test.\n  return (MatchesFilter(full_name, positive.c_str()) &&\n          !MatchesFilter(full_name, negative.c_str()));\n}\n\n#if GTEST_HAS_SEH\n// Returns EXCEPTION_EXECUTE_HANDLER if Google Test should handle the\n// given SEH exception, or EXCEPTION_CONTINUE_SEARCH otherwise.\n// This function is useful as an __except condition.\nint UnitTestOptions::GTestShouldProcessSEH(DWORD exception_code) {\n  // Google Test should handle a SEH exception if:\n  //   1. the user wants it to, AND\n  //   2. this is not a breakpoint exception, AND\n  //   3. this is not a C++ exception (VC++ implements them via SEH,\n  //      apparently).\n  //\n  // SEH exception code for C++ exceptions.\n  // (see http://support.microsoft.com/kb/185294 for more information).\n  const DWORD kCxxExceptionCode = 0xe06d7363;\n\n  bool should_handle = true;\n\n  if (!GTEST_FLAG(catch_exceptions))\n    should_handle = false;\n  else if (exception_code == EXCEPTION_BREAKPOINT)\n    should_handle = false;\n  else if (exception_code == kCxxExceptionCode)\n    should_handle = false;\n\n  return should_handle ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH;\n}\n#endif  // GTEST_HAS_SEH\n\n}  // namespace internal\n\n// The c'tor sets this object as the test part result reporter used by\n// Google Test.  The 'result' parameter specifies where to report the\n// results. Intercepts only failures from the current thread.\nScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(\n    TestPartResultArray* result)\n    : intercept_mode_(INTERCEPT_ONLY_CURRENT_THREAD),\n      result_(result) {\n  Init();\n}\n\n// The c'tor sets this object as the test part result reporter used by\n// Google Test.  The 'result' parameter specifies where to report the\n// results.\nScopedFakeTestPartResultReporter::ScopedFakeTestPartResultReporter(\n    InterceptMode intercept_mode, TestPartResultArray* result)\n    : intercept_mode_(intercept_mode),\n      result_(result) {\n  Init();\n}\n\nvoid ScopedFakeTestPartResultReporter::Init() {\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {\n    old_reporter_ = impl->GetGlobalTestPartResultReporter();\n    impl->SetGlobalTestPartResultReporter(this);\n  } else {\n    old_reporter_ = impl->GetTestPartResultReporterForCurrentThread();\n    impl->SetTestPartResultReporterForCurrentThread(this);\n  }\n}\n\n// The d'tor restores the test part result reporter used by Google Test\n// before.\nScopedFakeTestPartResultReporter::~ScopedFakeTestPartResultReporter() {\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  if (intercept_mode_ == INTERCEPT_ALL_THREADS) {\n    impl->SetGlobalTestPartResultReporter(old_reporter_);\n  } else {\n    impl->SetTestPartResultReporterForCurrentThread(old_reporter_);\n  }\n}\n\n// Increments the test part result count and remembers the result.\n// This method is from the TestPartResultReporterInterface interface.\nvoid ScopedFakeTestPartResultReporter::ReportTestPartResult(\n    const TestPartResult& result) {\n  result_->Append(result);\n}\n\nnamespace internal {\n\n// Returns the type ID of ::testing::Test.  We should always call this\n// instead of GetTypeId< ::testing::Test>() to get the type ID of\n// testing::Test.  This is to work around a suspected linker bug when\n// using Google Test as a framework on Mac OS X.  The bug causes\n// GetTypeId< ::testing::Test>() to return different values depending\n// on whether the call is from the Google Test framework itself or\n// from user test code.  GetTestTypeId() is guaranteed to always\n// return the same value, as it always calls GetTypeId<>() from the\n// gtest.cc, which is within the Google Test framework.\nTypeId GetTestTypeId() {\n  return GetTypeId<Test>();\n}\n\n// The value of GetTestTypeId() as seen from within the Google Test\n// library.  This is solely for testing GetTestTypeId().\nextern const TypeId kTestTypeIdInGoogleTest = GetTestTypeId();\n\n// This predicate-formatter checks that 'results' contains a test part\n// failure of the given type and that the failure message contains the\n// given substring.\nAssertionResult HasOneFailure(const char* /* results_expr */,\n                              const char* /* type_expr */,\n                              const char* /* substr_expr */,\n                              const TestPartResultArray& results,\n                              TestPartResult::Type type,\n                              const string& substr) {\n  const std::string expected(type == TestPartResult::kFatalFailure ?\n                        \"1 fatal failure\" :\n                        \"1 non-fatal failure\");\n  Message msg;\n  if (results.size() != 1) {\n    msg << \"Expected: \" << expected << \"\\n\"\n        << \"  Actual: \" << results.size() << \" failures\";\n    for (int i = 0; i < results.size(); i++) {\n      msg << \"\\n\" << results.GetTestPartResult(i);\n    }\n    return AssertionFailure() << msg;\n  }\n\n  const TestPartResult& r = results.GetTestPartResult(0);\n  if (r.type() != type) {\n    return AssertionFailure() << \"Expected: \" << expected << \"\\n\"\n                              << \"  Actual:\\n\"\n                              << r;\n  }\n\n  if (strstr(r.message(), substr.c_str()) == NULL) {\n    return AssertionFailure() << \"Expected: \" << expected << \" containing \\\"\"\n                              << substr << \"\\\"\\n\"\n                              << \"  Actual:\\n\"\n                              << r;\n  }\n\n  return AssertionSuccess();\n}\n\n// The constructor of SingleFailureChecker remembers where to look up\n// test part results, what type of failure we expect, and what\n// substring the failure message should contain.\nSingleFailureChecker:: SingleFailureChecker(\n    const TestPartResultArray* results,\n    TestPartResult::Type type,\n    const string& substr)\n    : results_(results),\n      type_(type),\n      substr_(substr) {}\n\n// The destructor of SingleFailureChecker verifies that the given\n// TestPartResultArray contains exactly one failure that has the given\n// type and contains the given substring.  If that's not the case, a\n// non-fatal failure will be generated.\nSingleFailureChecker::~SingleFailureChecker() {\n  EXPECT_PRED_FORMAT3(HasOneFailure, *results_, type_, substr_);\n}\n\nDefaultGlobalTestPartResultReporter::DefaultGlobalTestPartResultReporter(\n    UnitTestImpl* unit_test) : unit_test_(unit_test) {}\n\nvoid DefaultGlobalTestPartResultReporter::ReportTestPartResult(\n    const TestPartResult& result) {\n  unit_test_->current_test_result()->AddTestPartResult(result);\n  unit_test_->listeners()->repeater()->OnTestPartResult(result);\n}\n\nDefaultPerThreadTestPartResultReporter::DefaultPerThreadTestPartResultReporter(\n    UnitTestImpl* unit_test) : unit_test_(unit_test) {}\n\nvoid DefaultPerThreadTestPartResultReporter::ReportTestPartResult(\n    const TestPartResult& result) {\n  unit_test_->GetGlobalTestPartResultReporter()->ReportTestPartResult(result);\n}\n\n// Returns the global test part result reporter.\nTestPartResultReporterInterface*\nUnitTestImpl::GetGlobalTestPartResultReporter() {\n  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);\n  return global_test_part_result_repoter_;\n}\n\n// Sets the global test part result reporter.\nvoid UnitTestImpl::SetGlobalTestPartResultReporter(\n    TestPartResultReporterInterface* reporter) {\n  internal::MutexLock lock(&global_test_part_result_reporter_mutex_);\n  global_test_part_result_repoter_ = reporter;\n}\n\n// Returns the test part result reporter for the current thread.\nTestPartResultReporterInterface*\nUnitTestImpl::GetTestPartResultReporterForCurrentThread() {\n  return per_thread_test_part_result_reporter_.get();\n}\n\n// Sets the test part result reporter for the current thread.\nvoid UnitTestImpl::SetTestPartResultReporterForCurrentThread(\n    TestPartResultReporterInterface* reporter) {\n  per_thread_test_part_result_reporter_.set(reporter);\n}\n\n// Gets the number of successful test cases.\nint UnitTestImpl::successful_test_case_count() const {\n  return CountIf(test_cases_, TestCasePassed);\n}\n\n// Gets the number of failed test cases.\nint UnitTestImpl::failed_test_case_count() const {\n  return CountIf(test_cases_, TestCaseFailed);\n}\n\n// Gets the number of all test cases.\nint UnitTestImpl::total_test_case_count() const {\n  return static_cast<int>(test_cases_.size());\n}\n\n// Gets the number of all test cases that contain at least one test\n// that should run.\nint UnitTestImpl::test_case_to_run_count() const {\n  return CountIf(test_cases_, ShouldRunTestCase);\n}\n\n// Gets the number of successful tests.\nint UnitTestImpl::successful_test_count() const {\n  return SumOverTestCaseList(test_cases_, &TestCase::successful_test_count);\n}\n\n// Gets the number of failed tests.\nint UnitTestImpl::failed_test_count() const {\n  return SumOverTestCaseList(test_cases_, &TestCase::failed_test_count);\n}\n\n// Gets the number of disabled tests that will be reported in the XML report.\nint UnitTestImpl::reportable_disabled_test_count() const {\n  return SumOverTestCaseList(test_cases_,\n                             &TestCase::reportable_disabled_test_count);\n}\n\n// Gets the number of disabled tests.\nint UnitTestImpl::disabled_test_count() const {\n  return SumOverTestCaseList(test_cases_, &TestCase::disabled_test_count);\n}\n\n// Gets the number of tests to be printed in the XML report.\nint UnitTestImpl::reportable_test_count() const {\n  return SumOverTestCaseList(test_cases_, &TestCase::reportable_test_count);\n}\n\n// Gets the number of all tests.\nint UnitTestImpl::total_test_count() const {\n  return SumOverTestCaseList(test_cases_, &TestCase::total_test_count);\n}\n\n// Gets the number of tests that should run.\nint UnitTestImpl::test_to_run_count() const {\n  return SumOverTestCaseList(test_cases_, &TestCase::test_to_run_count);\n}\n\n// Returns the current OS stack trace as an std::string.\n//\n// The maximum number of stack frames to be included is specified by\n// the gtest_stack_trace_depth flag.  The skip_count parameter\n// specifies the number of top frames to be skipped, which doesn't\n// count against the number of frames to be included.\n//\n// For example, if Foo() calls Bar(), which in turn calls\n// CurrentOsStackTraceExceptTop(1), Foo() will be included in the\n// trace but Bar() and CurrentOsStackTraceExceptTop() won't.\nstd::string UnitTestImpl::CurrentOsStackTraceExceptTop(int skip_count) {\n  return os_stack_trace_getter()->CurrentStackTrace(\n      static_cast<int>(GTEST_FLAG(stack_trace_depth)),\n      skip_count + 1\n      // Skips the user-specified number of frames plus this function\n      // itself.\n      );  // NOLINT\n}\n\n// Returns the current time in milliseconds.\nTimeInMillis GetTimeInMillis() {\n#if GTEST_OS_WINDOWS_MOBILE || defined(__BORLANDC__)\n  // Difference between 1970-01-01 and 1601-01-01 in milliseconds.\n  // http://analogous.blogspot.com/2005/04/epoch.html\n  const TimeInMillis kJavaEpochToWinFileTimeDelta =\n    static_cast<TimeInMillis>(116444736UL) * 100000UL;\n  const DWORD kTenthMicrosInMilliSecond = 10000;\n\n  SYSTEMTIME now_systime;\n  FILETIME now_filetime;\n  ULARGE_INTEGER now_int64;\n  // TODO(kenton@google.com): Shouldn't this just use\n  //   GetSystemTimeAsFileTime()?\n  GetSystemTime(&now_systime);\n  if (SystemTimeToFileTime(&now_systime, &now_filetime)) {\n    now_int64.LowPart = now_filetime.dwLowDateTime;\n    now_int64.HighPart = now_filetime.dwHighDateTime;\n    now_int64.QuadPart = (now_int64.QuadPart / kTenthMicrosInMilliSecond) -\n      kJavaEpochToWinFileTimeDelta;\n    return now_int64.QuadPart;\n  }\n  return 0;\n#elif GTEST_OS_WINDOWS && !GTEST_HAS_GETTIMEOFDAY_\n  __timeb64 now;\n\n  // MSVC 8 deprecates _ftime64(), so we want to suppress warning 4996\n  // (deprecated function) there.\n  // TODO(kenton@google.com): Use GetTickCount()?  Or use\n  //   SystemTimeToFileTime()\n  GTEST_DISABLE_MSC_WARNINGS_PUSH_(4996)\n  _ftime64(&now);\n  GTEST_DISABLE_MSC_WARNINGS_POP_()\n\n  return static_cast<TimeInMillis>(now.time) * 1000 + now.millitm;\n#elif GTEST_HAS_GETTIMEOFDAY_\n  struct timeval now;\n  gettimeofday(&now, NULL);\n  return static_cast<TimeInMillis>(now.tv_sec) * 1000 + now.tv_usec / 1000;\n#else\n# error \"Don't know how to get the current time on your system.\"\n#endif\n}\n\n// Utilities\n\n// class String.\n\n#if GTEST_OS_WINDOWS_MOBILE\n// Creates a UTF-16 wide string from the given ANSI string, allocating\n// memory using new. The caller is responsible for deleting the return\n// value using delete[]. Returns the wide string, or NULL if the\n// input is NULL.\nLPCWSTR String::AnsiToUtf16(const char* ansi) {\n  if (!ansi) return NULL;\n  const int length = strlen(ansi);\n  const int unicode_length =\n      MultiByteToWideChar(CP_ACP, 0, ansi, length,\n                          NULL, 0);\n  WCHAR* unicode = new WCHAR[unicode_length + 1];\n  MultiByteToWideChar(CP_ACP, 0, ansi, length,\n                      unicode, unicode_length);\n  unicode[unicode_length] = 0;\n  return unicode;\n}\n\n// Creates an ANSI string from the given wide string, allocating\n// memory using new. The caller is responsible for deleting the return\n// value using delete[]. Returns the ANSI string, or NULL if the\n// input is NULL.\nconst char* String::Utf16ToAnsi(LPCWSTR utf16_str)  {\n  if (!utf16_str) return NULL;\n  const int ansi_length =\n      WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,\n                          NULL, 0, NULL, NULL);\n  char* ansi = new char[ansi_length + 1];\n  WideCharToMultiByte(CP_ACP, 0, utf16_str, -1,\n                      ansi, ansi_length, NULL, NULL);\n  ansi[ansi_length] = 0;\n  return ansi;\n}\n\n#endif  // GTEST_OS_WINDOWS_MOBILE\n\n// Compares two C strings.  Returns true iff they have the same content.\n//\n// Unlike strcmp(), this function can handle NULL argument(s).  A NULL\n// C string is considered different to any non-NULL C string,\n// including the empty string.\nbool String::CStringEquals(const char * lhs, const char * rhs) {\n  if ( lhs == NULL ) return rhs == NULL;\n\n  if ( rhs == NULL ) return false;\n\n  return strcmp(lhs, rhs) == 0;\n}\n\n#if GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING\n\n// Converts an array of wide chars to a narrow string using the UTF-8\n// encoding, and streams the result to the given Message object.\nstatic void StreamWideCharsToMessage(const wchar_t* wstr, size_t length,\n                                     Message* msg) {\n  for (size_t i = 0; i != length; ) {  // NOLINT\n    if (wstr[i] != L'\\0') {\n      *msg << WideStringToUtf8(wstr + i, static_cast<int>(length - i));\n      while (i != length && wstr[i] != L'\\0')\n        i++;\n    } else {\n      *msg << '\\0';\n      i++;\n    }\n  }\n}\n\n#endif  // GTEST_HAS_STD_WSTRING || GTEST_HAS_GLOBAL_WSTRING\n\nvoid SplitString(const ::std::string& str, char delimiter,\n                 ::std::vector< ::std::string>* dest) {\n  ::std::vector< ::std::string> parsed;\n  ::std::string::size_type pos = 0;\n  while (::testing::internal::AlwaysTrue()) {\n    const ::std::string::size_type colon = str.find(delimiter, pos);\n    if (colon == ::std::string::npos) {\n      parsed.push_back(str.substr(pos));\n      break;\n    } else {\n      parsed.push_back(str.substr(pos, colon - pos));\n      pos = colon + 1;\n    }\n  }\n  dest->swap(parsed);\n}\n\n}  // namespace internal\n\n// Constructs an empty Message.\n// We allocate the stringstream separately because otherwise each use of\n// ASSERT/EXPECT in a procedure adds over 200 bytes to the procedure's\n// stack frame leading to huge stack frames in some cases; gcc does not reuse\n// the stack space.\nMessage::Message() : ss_(new ::std::stringstream) {\n  // By default, we want there to be enough precision when printing\n  // a double to a Message.\n  *ss_ << std::setprecision(std::numeric_limits<double>::digits10 + 2);\n}\n\n// These two overloads allow streaming a wide C string to a Message\n// using the UTF-8 encoding.\nMessage& Message::operator <<(const wchar_t* wide_c_str) {\n  return *this << internal::String::ShowWideCString(wide_c_str);\n}\nMessage& Message::operator <<(wchar_t* wide_c_str) {\n  return *this << internal::String::ShowWideCString(wide_c_str);\n}\n\n#if GTEST_HAS_STD_WSTRING\n// Converts the given wide string to a narrow string using the UTF-8\n// encoding, and streams the result to this Message object.\nMessage& Message::operator <<(const ::std::wstring& wstr) {\n  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);\n  return *this;\n}\n#endif  // GTEST_HAS_STD_WSTRING\n\n#if GTEST_HAS_GLOBAL_WSTRING\n// Converts the given wide string to a narrow string using the UTF-8\n// encoding, and streams the result to this Message object.\nMessage& Message::operator <<(const ::wstring& wstr) {\n  internal::StreamWideCharsToMessage(wstr.c_str(), wstr.length(), this);\n  return *this;\n}\n#endif  // GTEST_HAS_GLOBAL_WSTRING\n\n// Gets the text streamed to this object so far as an std::string.\n// Each '\\0' character in the buffer is replaced with \"\\\\0\".\nstd::string Message::GetString() const {\n  return internal::StringStreamToString(ss_.get());\n}\n\n// AssertionResult constructors.\n// Used in EXPECT_TRUE/FALSE(assertion_result).\nAssertionResult::AssertionResult(const AssertionResult& other)\n    : success_(other.success_),\n      message_(other.message_.get() != NULL ?\n               new ::std::string(*other.message_) :\n               static_cast< ::std::string*>(NULL)) {\n}\n\n// Swaps two AssertionResults.\nvoid AssertionResult::swap(AssertionResult& other) {\n  using std::swap;\n  swap(success_, other.success_);\n  swap(message_, other.message_);\n}\n\n// Returns the assertion's negation. Used with EXPECT/ASSERT_FALSE.\nAssertionResult AssertionResult::operator!() const {\n  AssertionResult negation(!success_);\n  if (message_.get() != NULL)\n    negation << *message_;\n  return negation;\n}\n\n// Makes a successful assertion result.\nAssertionResult AssertionSuccess() {\n  return AssertionResult(true);\n}\n\n// Makes a failed assertion result.\nAssertionResult AssertionFailure() {\n  return AssertionResult(false);\n}\n\n// Makes a failed assertion result with the given failure message.\n// Deprecated; use AssertionFailure() << message.\nAssertionResult AssertionFailure(const Message& message) {\n  return AssertionFailure() << message;\n}\n\nnamespace internal {\n\nnamespace edit_distance {\nstd::vector<EditType> CalculateOptimalEdits(const std::vector<size_t>& left,\n                                            const std::vector<size_t>& right) {\n  std::vector<std::vector<double> > costs(\n      left.size() + 1, std::vector<double>(right.size() + 1));\n  std::vector<std::vector<EditType> > best_move(\n      left.size() + 1, std::vector<EditType>(right.size() + 1));\n\n  // Populate for empty right.\n  for (size_t l_i = 0; l_i < costs.size(); ++l_i) {\n    costs[l_i][0] = static_cast<double>(l_i);\n    best_move[l_i][0] = kRemove;\n  }\n  // Populate for empty left.\n  for (size_t r_i = 1; r_i < costs[0].size(); ++r_i) {\n    costs[0][r_i] = static_cast<double>(r_i);\n    best_move[0][r_i] = kAdd;\n  }\n\n  for (size_t l_i = 0; l_i < left.size(); ++l_i) {\n    for (size_t r_i = 0; r_i < right.size(); ++r_i) {\n      if (left[l_i] == right[r_i]) {\n        // Found a match. Consume it.\n        costs[l_i + 1][r_i + 1] = costs[l_i][r_i];\n        best_move[l_i + 1][r_i + 1] = kMatch;\n        continue;\n      }\n\n      const double add = costs[l_i + 1][r_i];\n      const double remove = costs[l_i][r_i + 1];\n      const double replace = costs[l_i][r_i];\n      if (add < remove && add < replace) {\n        costs[l_i + 1][r_i + 1] = add + 1;\n        best_move[l_i + 1][r_i + 1] = kAdd;\n      } else if (remove < add && remove < replace) {\n        costs[l_i + 1][r_i + 1] = remove + 1;\n        best_move[l_i + 1][r_i + 1] = kRemove;\n      } else {\n        // We make replace a little more expensive than add/remove to lower\n        // their priority.\n        costs[l_i + 1][r_i + 1] = replace + 1.00001;\n        best_move[l_i + 1][r_i + 1] = kReplace;\n      }\n    }\n  }\n\n  // Reconstruct the best path. We do it in reverse order.\n  std::vector<EditType> best_path;\n  for (size_t l_i = left.size(), r_i = right.size(); l_i > 0 || r_i > 0;) {\n    EditType move = best_move[l_i][r_i];\n    best_path.push_back(move);\n    l_i -= move != kAdd;\n    r_i -= move != kRemove;\n  }\n  std::reverse(best_path.begin(), best_path.end());\n  return best_path;\n}\n\nnamespace {\n\n// Helper class to convert string into ids with deduplication.\nclass InternalStrings {\n public:\n  size_t GetId(const std::string& str) {\n    IdMap::iterator it = ids_.find(str);\n    if (it != ids_.end()) return it->second;\n    size_t id = ids_.size();\n    return ids_[str] = id;\n  }\n\n private:\n  typedef std::map<std::string, size_t> IdMap;\n  IdMap ids_;\n};\n\n}  // namespace\n\nstd::vector<EditType> CalculateOptimalEdits(\n    const std::vector<std::string>& left,\n    const std::vector<std::string>& right) {\n  std::vector<size_t> left_ids, right_ids;\n  {\n    InternalStrings intern_table;\n    for (size_t i = 0; i < left.size(); ++i) {\n      left_ids.push_back(intern_table.GetId(left[i]));\n    }\n    for (size_t i = 0; i < right.size(); ++i) {\n      right_ids.push_back(intern_table.GetId(right[i]));\n    }\n  }\n  return CalculateOptimalEdits(left_ids, right_ids);\n}\n\nnamespace {\n\n// Helper class that holds the state for one hunk and prints it out to the\n// stream.\n// It reorders adds/removes when possible to group all removes before all\n// adds. It also adds the hunk header before printint into the stream.\nclass Hunk {\n public:\n  Hunk(size_t left_start, size_t right_start)\n      : left_start_(left_start),\n        right_start_(right_start),\n        adds_(),\n        removes_(),\n        common_() {}\n\n  void PushLine(char edit, const char* line) {\n    switch (edit) {\n      case ' ':\n        ++common_;\n        FlushEdits();\n        hunk_.push_back(std::make_pair(' ', line));\n        break;\n      case '-':\n        ++removes_;\n        hunk_removes_.push_back(std::make_pair('-', line));\n        break;\n      case '+':\n        ++adds_;\n        hunk_adds_.push_back(std::make_pair('+', line));\n        break;\n    }\n  }\n\n  void PrintTo(std::ostream* os) {\n    PrintHeader(os);\n    FlushEdits();\n    for (std::list<std::pair<char, const char*> >::const_iterator it =\n             hunk_.begin();\n         it != hunk_.end(); ++it) {\n      *os << it->first << it->second << \"\\n\";\n    }\n  }\n\n  bool has_edits() const { return adds_ || removes_; }\n\n private:\n  void FlushEdits() {\n    hunk_.splice(hunk_.end(), hunk_removes_);\n    hunk_.splice(hunk_.end(), hunk_adds_);\n  }\n\n  // Print a unified diff header for one hunk.\n  // The format is\n  //   \"@@ -<left_start>,<left_length> +<right_start>,<right_length> @@\"\n  // where the left/right parts are ommitted if unnecessary.\n  void PrintHeader(std::ostream* ss) const {\n    *ss << \"@@ \";\n    if (removes_) {\n      *ss << \"-\" << left_start_ << \",\" << (removes_ + common_);\n    }\n    if (removes_ && adds_) {\n      *ss << \" \";\n    }\n    if (adds_) {\n      *ss << \"+\" << right_start_ << \",\" << (adds_ + common_);\n    }\n    *ss << \" @@\\n\";\n  }\n\n  size_t left_start_, right_start_;\n  size_t adds_, removes_, common_;\n  std::list<std::pair<char, const char*> > hunk_, hunk_adds_, hunk_removes_;\n};\n\n}  // namespace\n\n// Create a list of diff hunks in Unified diff format.\n// Each hunk has a header generated by PrintHeader above plus a body with\n// lines prefixed with ' ' for no change, '-' for deletion and '+' for\n// addition.\n// 'context' represents the desired unchanged prefix/suffix around the diff.\n// If two hunks are close enough that their contexts overlap, then they are\n// joined into one hunk.\nstd::string CreateUnifiedDiff(const std::vector<std::string>& left,\n                              const std::vector<std::string>& right,\n                              size_t context) {\n  const std::vector<EditType> edits = CalculateOptimalEdits(left, right);\n\n  size_t l_i = 0, r_i = 0, edit_i = 0;\n  std::stringstream ss;\n  while (edit_i < edits.size()) {\n    // Find first edit.\n    while (edit_i < edits.size() && edits[edit_i] == kMatch) {\n      ++l_i;\n      ++r_i;\n      ++edit_i;\n    }\n\n    // Find the first line to include in the hunk.\n    const size_t prefix_context = std::min(l_i, context);\n    Hunk hunk(l_i - prefix_context + 1, r_i - prefix_context + 1);\n    for (size_t i = prefix_context; i > 0; --i) {\n      hunk.PushLine(' ', left[l_i - i].c_str());\n    }\n\n    // Iterate the edits until we found enough suffix for the hunk or the input\n    // is over.\n    size_t n_suffix = 0;\n    for (; edit_i < edits.size(); ++edit_i) {\n      if (n_suffix >= context) {\n        // Continue only if the next hunk is very close.\n        std::vector<EditType>::const_iterator it = edits.begin() + edit_i;\n        while (it != edits.end() && *it == kMatch) ++it;\n        if (it == edits.end() || (it - edits.begin()) - edit_i >= context) {\n          // There is no next edit or it is too far away.\n          break;\n        }\n      }\n\n      EditType edit = edits[edit_i];\n      // Reset count when a non match is found.\n      n_suffix = edit == kMatch ? n_suffix + 1 : 0;\n\n      if (edit == kMatch || edit == kRemove || edit == kReplace) {\n        hunk.PushLine(edit == kMatch ? ' ' : '-', left[l_i].c_str());\n      }\n      if (edit == kAdd || edit == kReplace) {\n        hunk.PushLine('+', right[r_i].c_str());\n      }\n\n      // Advance indices, depending on edit type.\n      l_i += edit != kAdd;\n      r_i += edit != kRemove;\n    }\n\n    if (!hunk.has_edits()) {\n      // We are done. We don't want this hunk.\n      break;\n    }\n\n    hunk.PrintTo(&ss);\n  }\n  return ss.str();\n}\n\n}  // namespace edit_distance\n\nnamespace {\n\n// The string representation of the values received in EqFailure() are already\n// escaped. Split them on escaped '\\n' boundaries. Leave all other escaped\n// characters the same.\nstd::vector<std::string> SplitEscapedString(const std::string& str) {\n  std::vector<std::string> lines;\n  size_t start = 0, end = str.size();\n  if (end > 2 && str[0] == '\"' && str[end - 1] == '\"') {\n    ++start;\n    --end;\n  }\n  bool escaped = false;\n  for (size_t i = start; i + 1 < end; ++i) {\n    if (escaped) {\n      escaped = false;\n      if (str[i] == 'n') {\n        lines.push_back(str.substr(start, i - start - 1));\n        start = i + 1;\n      }\n    } else {\n      escaped = str[i] == '\\\\';\n    }\n  }\n  lines.push_back(str.substr(start, end - start));\n  return lines;\n}\n\n}  // namespace\n\n// Constructs and returns the message for an equality assertion\n// (e.g. ASSERT_EQ, EXPECT_STREQ, etc) failure.\n//\n// The first four parameters are the expressions used in the assertion\n// and their values, as strings.  For example, for ASSERT_EQ(foo, bar)\n// where foo is 5 and bar is 6, we have:\n//\n//   lhs_expression: \"foo\"\n//   rhs_expression: \"bar\"\n//   lhs_value:      \"5\"\n//   rhs_value:      \"6\"\n//\n// The ignoring_case parameter is true iff the assertion is a\n// *_STRCASEEQ*.  When it's true, the string \"Ignoring case\" will\n// be inserted into the message.\nAssertionResult EqFailure(const char* lhs_expression,\n                          const char* rhs_expression,\n                          const std::string& lhs_value,\n                          const std::string& rhs_value,\n                          bool ignoring_case) {\n  Message msg;\n  msg << \"      Expected: \" << lhs_expression;\n  if (lhs_value != lhs_expression) {\n    msg << \"\\n      Which is: \" << lhs_value;\n  }\n  msg << \"\\nTo be equal to: \" << rhs_expression;\n  if (rhs_value != rhs_expression) {\n    msg << \"\\n      Which is: \" << rhs_value;\n  }\n\n  if (ignoring_case) {\n    msg << \"\\nIgnoring case\";\n  }\n\n  if (!lhs_value.empty() && !rhs_value.empty()) {\n    const std::vector<std::string> lhs_lines =\n        SplitEscapedString(lhs_value);\n    const std::vector<std::string> rhs_lines =\n        SplitEscapedString(rhs_value);\n    if (lhs_lines.size() > 1 || rhs_lines.size() > 1) {\n      msg << \"\\nWith diff:\\n\"\n          << edit_distance::CreateUnifiedDiff(lhs_lines, rhs_lines);\n    }\n  }\n\n  return AssertionFailure() << msg;\n}\n\n// Constructs a failure message for Boolean assertions such as EXPECT_TRUE.\nstd::string GetBoolAssertionFailureMessage(\n    const AssertionResult& assertion_result,\n    const char* expression_text,\n    const char* actual_predicate_value,\n    const char* expected_predicate_value) {\n  const char* actual_message = assertion_result.message();\n  Message msg;\n  msg << \"Value of: \" << expression_text\n      << \"\\n  Actual: \" << actual_predicate_value;\n  if (actual_message[0] != '\\0')\n    msg << \" (\" << actual_message << \")\";\n  msg << \"\\nExpected: \" << expected_predicate_value;\n  return msg.GetString();\n}\n\n// Helper function for implementing ASSERT_NEAR.\nAssertionResult DoubleNearPredFormat(const char* expr1,\n                                     const char* expr2,\n                                     const char* abs_error_expr,\n                                     double val1,\n                                     double val2,\n                                     double abs_error) {\n  const double diff = fabs(val1 - val2);\n  if (diff <= abs_error) return AssertionSuccess();\n\n  // TODO(wan): do not print the value of an expression if it's\n  // already a literal.\n  return AssertionFailure()\n      << \"The difference between \" << expr1 << \" and \" << expr2\n      << \" is \" << diff << \", which exceeds \" << abs_error_expr << \", where\\n\"\n      << expr1 << \" evaluates to \" << val1 << \",\\n\"\n      << expr2 << \" evaluates to \" << val2 << \", and\\n\"\n      << abs_error_expr << \" evaluates to \" << abs_error << \".\";\n}\n\n\n// Helper template for implementing FloatLE() and DoubleLE().\ntemplate <typename RawType>\nAssertionResult FloatingPointLE(const char* expr1,\n                                const char* expr2,\n                                RawType val1,\n                                RawType val2) {\n  // Returns success if val1 is less than val2,\n  if (val1 < val2) {\n    return AssertionSuccess();\n  }\n\n  // or if val1 is almost equal to val2.\n  const FloatingPoint<RawType> lhs(val1), rhs(val2);\n  if (lhs.AlmostEquals(rhs)) {\n    return AssertionSuccess();\n  }\n\n  // Note that the above two checks will both fail if either val1 or\n  // val2 is NaN, as the IEEE floating-point standard requires that\n  // any predicate involving a NaN must return false.\n\n  ::std::stringstream val1_ss;\n  val1_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)\n          << val1;\n\n  ::std::stringstream val2_ss;\n  val2_ss << std::setprecision(std::numeric_limits<RawType>::digits10 + 2)\n          << val2;\n\n  return AssertionFailure()\n      << \"Expected: (\" << expr1 << \") <= (\" << expr2 << \")\\n\"\n      << \"  Actual: \" << StringStreamToString(&val1_ss) << \" vs \"\n      << StringStreamToString(&val2_ss);\n}\n\n}  // namespace internal\n\n// Asserts that val1 is less than, or almost equal to, val2.  Fails\n// otherwise.  In particular, it fails if either val1 or val2 is NaN.\nAssertionResult FloatLE(const char* expr1, const char* expr2,\n                        float val1, float val2) {\n  return internal::FloatingPointLE<float>(expr1, expr2, val1, val2);\n}\n\n// Asserts that val1 is less than, or almost equal to, val2.  Fails\n// otherwise.  In particular, it fails if either val1 or val2 is NaN.\nAssertionResult DoubleLE(const char* expr1, const char* expr2,\n                         double val1, double val2) {\n  return internal::FloatingPointLE<double>(expr1, expr2, val1, val2);\n}\n\nnamespace internal {\n\n// The helper function for {ASSERT|EXPECT}_EQ with int or enum\n// arguments.\nAssertionResult CmpHelperEQ(const char* lhs_expression,\n                            const char* rhs_expression,\n                            BiggestInt lhs,\n                            BiggestInt rhs) {\n  if (lhs == rhs) {\n    return AssertionSuccess();\n  }\n\n  return EqFailure(lhs_expression,\n                   rhs_expression,\n                   FormatForComparisonFailureMessage(lhs, rhs),\n                   FormatForComparisonFailureMessage(rhs, lhs),\n                   false);\n}\n\n// A macro for implementing the helper functions needed to implement\n// ASSERT_?? and EXPECT_?? with integer or enum arguments.  It is here\n// just to avoid copy-and-paste of similar code.\n#define GTEST_IMPL_CMP_HELPER_(op_name, op)\\\nAssertionResult CmpHelper##op_name(const char* expr1, const char* expr2, \\\n                                   BiggestInt val1, BiggestInt val2) {\\\n  if (val1 op val2) {\\\n    return AssertionSuccess();\\\n  } else {\\\n    return AssertionFailure() \\\n        << \"Expected: (\" << expr1 << \") \" #op \" (\" << expr2\\\n        << \"), actual: \" << FormatForComparisonFailureMessage(val1, val2)\\\n        << \" vs \" << FormatForComparisonFailureMessage(val2, val1);\\\n  }\\\n}\n\n// Implements the helper function for {ASSERT|EXPECT}_NE with int or\n// enum arguments.\nGTEST_IMPL_CMP_HELPER_(NE, !=)\n// Implements the helper function for {ASSERT|EXPECT}_LE with int or\n// enum arguments.\nGTEST_IMPL_CMP_HELPER_(LE, <=)\n// Implements the helper function for {ASSERT|EXPECT}_LT with int or\n// enum arguments.\nGTEST_IMPL_CMP_HELPER_(LT, < )\n// Implements the helper function for {ASSERT|EXPECT}_GE with int or\n// enum arguments.\nGTEST_IMPL_CMP_HELPER_(GE, >=)\n// Implements the helper function for {ASSERT|EXPECT}_GT with int or\n// enum arguments.\nGTEST_IMPL_CMP_HELPER_(GT, > )\n\n#undef GTEST_IMPL_CMP_HELPER_\n\n// The helper function for {ASSERT|EXPECT}_STREQ.\nAssertionResult CmpHelperSTREQ(const char* lhs_expression,\n                               const char* rhs_expression,\n                               const char* lhs,\n                               const char* rhs) {\n  if (String::CStringEquals(lhs, rhs)) {\n    return AssertionSuccess();\n  }\n\n  return EqFailure(lhs_expression,\n                   rhs_expression,\n                   PrintToString(lhs),\n                   PrintToString(rhs),\n                   false);\n}\n\n// The helper function for {ASSERT|EXPECT}_STRCASEEQ.\nAssertionResult CmpHelperSTRCASEEQ(const char* lhs_expression,\n                                   const char* rhs_expression,\n                                   const char* lhs,\n                                   const char* rhs) {\n  if (String::CaseInsensitiveCStringEquals(lhs, rhs)) {\n    return AssertionSuccess();\n  }\n\n  return EqFailure(lhs_expression,\n                   rhs_expression,\n                   PrintToString(lhs),\n                   PrintToString(rhs),\n                   true);\n}\n\n// The helper function for {ASSERT|EXPECT}_STRNE.\nAssertionResult CmpHelperSTRNE(const char* s1_expression,\n                               const char* s2_expression,\n                               const char* s1,\n                               const char* s2) {\n  if (!String::CStringEquals(s1, s2)) {\n    return AssertionSuccess();\n  } else {\n    return AssertionFailure() << \"Expected: (\" << s1_expression << \") != (\"\n                              << s2_expression << \"), actual: \\\"\"\n                              << s1 << \"\\\" vs \\\"\" << s2 << \"\\\"\";\n  }\n}\n\n// The helper function for {ASSERT|EXPECT}_STRCASENE.\nAssertionResult CmpHelperSTRCASENE(const char* s1_expression,\n                                   const char* s2_expression,\n                                   const char* s1,\n                                   const char* s2) {\n  if (!String::CaseInsensitiveCStringEquals(s1, s2)) {\n    return AssertionSuccess();\n  } else {\n    return AssertionFailure()\n        << \"Expected: (\" << s1_expression << \") != (\"\n        << s2_expression << \") (ignoring case), actual: \\\"\"\n        << s1 << \"\\\" vs \\\"\" << s2 << \"\\\"\";\n  }\n}\n\n}  // namespace internal\n\nnamespace {\n\n// Helper functions for implementing IsSubString() and IsNotSubstring().\n\n// This group of overloaded functions return true iff needle is a\n// substring of haystack.  NULL is considered a substring of itself\n// only.\n\nbool IsSubstringPred(const char* needle, const char* haystack) {\n  if (needle == NULL || haystack == NULL)\n    return needle == haystack;\n\n  return strstr(haystack, needle) != NULL;\n}\n\nbool IsSubstringPred(const wchar_t* needle, const wchar_t* haystack) {\n  if (needle == NULL || haystack == NULL)\n    return needle == haystack;\n\n  return wcsstr(haystack, needle) != NULL;\n}\n\n// StringType here can be either ::std::string or ::std::wstring.\ntemplate <typename StringType>\nbool IsSubstringPred(const StringType& needle,\n                     const StringType& haystack) {\n  return haystack.find(needle) != StringType::npos;\n}\n\n// This function implements either IsSubstring() or IsNotSubstring(),\n// depending on the value of the expected_to_be_substring parameter.\n// StringType here can be const char*, const wchar_t*, ::std::string,\n// or ::std::wstring.\ntemplate <typename StringType>\nAssertionResult IsSubstringImpl(\n    bool expected_to_be_substring,\n    const char* needle_expr, const char* haystack_expr,\n    const StringType& needle, const StringType& haystack) {\n  if (IsSubstringPred(needle, haystack) == expected_to_be_substring)\n    return AssertionSuccess();\n\n  const bool is_wide_string = sizeof(needle[0]) > 1;\n  const char* const begin_string_quote = is_wide_string ? \"L\\\"\" : \"\\\"\";\n  return AssertionFailure()\n      << \"Value of: \" << needle_expr << \"\\n\"\n      << \"  Actual: \" << begin_string_quote << needle << \"\\\"\\n\"\n      << \"Expected: \" << (expected_to_be_substring ? \"\" : \"not \")\n      << \"a substring of \" << haystack_expr << \"\\n\"\n      << \"Which is: \" << begin_string_quote << haystack << \"\\\"\";\n}\n\n}  // namespace\n\n// IsSubstring() and IsNotSubstring() check whether needle is a\n// substring of haystack (NULL is considered a substring of itself\n// only), and return an appropriate error message when they fail.\n\nAssertionResult IsSubstring(\n    const char* needle_expr, const char* haystack_expr,\n    const char* needle, const char* haystack) {\n  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsSubstring(\n    const char* needle_expr, const char* haystack_expr,\n    const wchar_t* needle, const wchar_t* haystack) {\n  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(\n    const char* needle_expr, const char* haystack_expr,\n    const char* needle, const char* haystack) {\n  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(\n    const char* needle_expr, const char* haystack_expr,\n    const wchar_t* needle, const wchar_t* haystack) {\n  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsSubstring(\n    const char* needle_expr, const char* haystack_expr,\n    const ::std::string& needle, const ::std::string& haystack) {\n  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(\n    const char* needle_expr, const char* haystack_expr,\n    const ::std::string& needle, const ::std::string& haystack) {\n  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n\n#if GTEST_HAS_STD_WSTRING\nAssertionResult IsSubstring(\n    const char* needle_expr, const char* haystack_expr,\n    const ::std::wstring& needle, const ::std::wstring& haystack) {\n  return IsSubstringImpl(true, needle_expr, haystack_expr, needle, haystack);\n}\n\nAssertionResult IsNotSubstring(\n    const char* needle_expr, const char* haystack_expr,\n    const ::std::wstring& needle, const ::std::wstring& haystack) {\n  return IsSubstringImpl(false, needle_expr, haystack_expr, needle, haystack);\n}\n#endif  // GTEST_HAS_STD_WSTRING\n\nnamespace internal {\n\n#if GTEST_OS_WINDOWS\n\nnamespace {\n\n// Helper function for IsHRESULT{SuccessFailure} predicates\nAssertionResult HRESULTFailureHelper(const char* expr,\n                                     const char* expected,\n                                     long hr) {  // NOLINT\n# if GTEST_OS_WINDOWS_MOBILE\n\n  // Windows CE doesn't support FormatMessage.\n  const char error_text[] = \"\";\n\n# else\n\n  // Looks up the human-readable system message for the HRESULT code\n  // and since we're not passing any params to FormatMessage, we don't\n  // want inserts expanded.\n  const DWORD kFlags = FORMAT_MESSAGE_FROM_SYSTEM |\n                       FORMAT_MESSAGE_IGNORE_INSERTS;\n  const DWORD kBufSize = 4096;\n  // Gets the system's human readable message string for this HRESULT.\n  char error_text[kBufSize] = { '\\0' };\n  DWORD message_length = ::FormatMessageA(kFlags,\n                                          0,  // no source, we're asking system\n                                          hr,  // the error\n                                          0,  // no line width restrictions\n                                          error_text,  // output buffer\n                                          kBufSize,  // buf size\n                                          NULL);  // no arguments for inserts\n  // Trims tailing white space (FormatMessage leaves a trailing CR-LF)\n  for (; message_length && IsSpace(error_text[message_length - 1]);\n          --message_length) {\n    error_text[message_length - 1] = '\\0';\n  }\n\n# endif  // GTEST_OS_WINDOWS_MOBILE\n\n  const std::string error_hex(\"0x\" + String::FormatHexInt(hr));\n  return ::testing::AssertionFailure()\n      << \"Expected: \" << expr << \" \" << expected << \".\\n\"\n      << \"  Actual: \" << error_hex << \" \" << error_text << \"\\n\";\n}\n\n}  // namespace\n\nAssertionResult IsHRESULTSuccess(const char* expr, long hr) {  // NOLINT\n  if (SUCCEEDED(hr)) {\n    return AssertionSuccess();\n  }\n  return HRESULTFailureHelper(expr, \"succeeds\", hr);\n}\n\nAssertionResult IsHRESULTFailure(const char* expr, long hr) {  // NOLINT\n  if (FAILED(hr)) {\n    return AssertionSuccess();\n  }\n  return HRESULTFailureHelper(expr, \"fails\", hr);\n}\n\n#endif  // GTEST_OS_WINDOWS\n\n// Utility functions for encoding Unicode text (wide strings) in\n// UTF-8.\n\n// A Unicode code-point can have upto 21 bits, and is encoded in UTF-8\n// like this:\n//\n// Code-point length   Encoding\n//   0 -  7 bits       0xxxxxxx\n//   8 - 11 bits       110xxxxx 10xxxxxx\n//  12 - 16 bits       1110xxxx 10xxxxxx 10xxxxxx\n//  17 - 21 bits       11110xxx 10xxxxxx 10xxxxxx 10xxxxxx\n\n// The maximum code-point a one-byte UTF-8 sequence can represent.\nconst UInt32 kMaxCodePoint1 = (static_cast<UInt32>(1) <<  7) - 1;\n\n// The maximum code-point a two-byte UTF-8 sequence can represent.\nconst UInt32 kMaxCodePoint2 = (static_cast<UInt32>(1) << (5 + 6)) - 1;\n\n// The maximum code-point a three-byte UTF-8 sequence can represent.\nconst UInt32 kMaxCodePoint3 = (static_cast<UInt32>(1) << (4 + 2*6)) - 1;\n\n// The maximum code-point a four-byte UTF-8 sequence can represent.\nconst UInt32 kMaxCodePoint4 = (static_cast<UInt32>(1) << (3 + 3*6)) - 1;\n\n// Chops off the n lowest bits from a bit pattern.  Returns the n\n// lowest bits.  As a side effect, the original bit pattern will be\n// shifted to the right by n bits.\ninline UInt32 ChopLowBits(UInt32* bits, int n) {\n  const UInt32 low_bits = *bits & ((static_cast<UInt32>(1) << n) - 1);\n  *bits >>= n;\n  return low_bits;\n}\n\n// Converts a Unicode code point to a narrow string in UTF-8 encoding.\n// code_point parameter is of type UInt32 because wchar_t may not be\n// wide enough to contain a code point.\n// If the code_point is not a valid Unicode code point\n// (i.e. outside of Unicode range U+0 to U+10FFFF) it will be converted\n// to \"(Invalid Unicode 0xXXXXXXXX)\".\nstd::string CodePointToUtf8(UInt32 code_point) {\n  if (code_point > kMaxCodePoint4) {\n    return \"(Invalid Unicode 0x\" + String::FormatHexInt(code_point) + \")\";\n  }\n\n  char str[5];  // Big enough for the largest valid code point.\n  if (code_point <= kMaxCodePoint1) {\n    str[1] = '\\0';\n    str[0] = static_cast<char>(code_point);                          // 0xxxxxxx\n  } else if (code_point <= kMaxCodePoint2) {\n    str[2] = '\\0';\n    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[0] = static_cast<char>(0xC0 | code_point);                   // 110xxxxx\n  } else if (code_point <= kMaxCodePoint3) {\n    str[3] = '\\0';\n    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[0] = static_cast<char>(0xE0 | code_point);                   // 1110xxxx\n  } else {  // code_point <= kMaxCodePoint4\n    str[4] = '\\0';\n    str[3] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[2] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[1] = static_cast<char>(0x80 | ChopLowBits(&code_point, 6));  // 10xxxxxx\n    str[0] = static_cast<char>(0xF0 | code_point);                   // 11110xxx\n  }\n  return str;\n}\n\n// The following two functions only make sense if the system\n// uses UTF-16 for wide string encoding. All supported systems\n// with 16 bit wchar_t (Windows, Cygwin, Symbian OS) do use UTF-16.\n\n// Determines if the arguments constitute UTF-16 surrogate pair\n// and thus should be combined into a single Unicode code point\n// using CreateCodePointFromUtf16SurrogatePair.\ninline bool IsUtf16SurrogatePair(wchar_t first, wchar_t second) {\n  return sizeof(wchar_t) == 2 &&\n      (first & 0xFC00) == 0xD800 && (second & 0xFC00) == 0xDC00;\n}\n\n// Creates a Unicode code point from UTF16 surrogate pair.\ninline UInt32 CreateCodePointFromUtf16SurrogatePair(wchar_t first,\n                                                    wchar_t second) {\n  const UInt32 mask = (1 << 10) - 1;\n  return (sizeof(wchar_t) == 2) ?\n      (((first & mask) << 10) | (second & mask)) + 0x10000 :\n      // This function should not be called when the condition is\n      // false, but we provide a sensible default in case it is.\n      static_cast<UInt32>(first);\n}\n\n// Converts a wide string to a narrow string in UTF-8 encoding.\n// The wide string is assumed to have the following encoding:\n//   UTF-16 if sizeof(wchar_t) == 2 (on Windows, Cygwin, Symbian OS)\n//   UTF-32 if sizeof(wchar_t) == 4 (on Linux)\n// Parameter str points to a null-terminated wide string.\n// Parameter num_chars may additionally limit the number\n// of wchar_t characters processed. -1 is used when the entire string\n// should be processed.\n// If the string contains code points that are not valid Unicode code points\n// (i.e. outside of Unicode range U+0 to U+10FFFF) they will be output\n// as '(Invalid Unicode 0xXXXXXXXX)'. If the string is in UTF16 encoding\n// and contains invalid UTF-16 surrogate pairs, values in those pairs\n// will be encoded as individual Unicode characters from Basic Normal Plane.\nstd::string WideStringToUtf8(const wchar_t* str, int num_chars) {\n  if (num_chars == -1)\n    num_chars = static_cast<int>(wcslen(str));\n\n  ::std::stringstream stream;\n  for (int i = 0; i < num_chars; ++i) {\n    UInt32 unicode_code_point;\n\n    if (str[i] == L'\\0') {\n      break;\n    } else if (i + 1 < num_chars && IsUtf16SurrogatePair(str[i], str[i + 1])) {\n      unicode_code_point = CreateCodePointFromUtf16SurrogatePair(str[i],\n                                                                 str[i + 1]);\n      i++;\n    } else {\n      unicode_code_point = static_cast<UInt32>(str[i]);\n    }\n\n    stream << CodePointToUtf8(unicode_code_point);\n  }\n  return StringStreamToString(&stream);\n}\n\n// Converts a wide C string to an std::string using the UTF-8 encoding.\n// NULL will be converted to \"(null)\".\nstd::string String::ShowWideCString(const wchar_t * wide_c_str) {\n  if (wide_c_str == NULL)  return \"(null)\";\n\n  return internal::WideStringToUtf8(wide_c_str, -1);\n}\n\n// Compares two wide C strings.  Returns true iff they have the same\n// content.\n//\n// Unlike wcscmp(), this function can handle NULL argument(s).  A NULL\n// C string is considered different to any non-NULL C string,\n// including the empty string.\nbool String::WideCStringEquals(const wchar_t * lhs, const wchar_t * rhs) {\n  if (lhs == NULL) return rhs == NULL;\n\n  if (rhs == NULL) return false;\n\n  return wcscmp(lhs, rhs) == 0;\n}\n\n// Helper function for *_STREQ on wide strings.\nAssertionResult CmpHelperSTREQ(const char* lhs_expression,\n                               const char* rhs_expression,\n                               const wchar_t* lhs,\n                               const wchar_t* rhs) {\n  if (String::WideCStringEquals(lhs, rhs)) {\n    return AssertionSuccess();\n  }\n\n  return EqFailure(lhs_expression,\n                   rhs_expression,\n                   PrintToString(lhs),\n                   PrintToString(rhs),\n                   false);\n}\n\n// Helper function for *_STRNE on wide strings.\nAssertionResult CmpHelperSTRNE(const char* s1_expression,\n                               const char* s2_expression,\n                               const wchar_t* s1,\n                               const wchar_t* s2) {\n  if (!String::WideCStringEquals(s1, s2)) {\n    return AssertionSuccess();\n  }\n\n  return AssertionFailure() << \"Expected: (\" << s1_expression << \") != (\"\n                            << s2_expression << \"), actual: \"\n                            << PrintToString(s1)\n                            << \" vs \" << PrintToString(s2);\n}\n\n// Compares two C strings, ignoring case.  Returns true iff they have\n// the same content.\n//\n// Unlike strcasecmp(), this function can handle NULL argument(s).  A\n// NULL C string is considered different to any non-NULL C string,\n// including the empty string.\nbool String::CaseInsensitiveCStringEquals(const char * lhs, const char * rhs) {\n  if (lhs == NULL)\n    return rhs == NULL;\n  if (rhs == NULL)\n    return false;\n  return posix::StrCaseCmp(lhs, rhs) == 0;\n}\n\n  // Compares two wide C strings, ignoring case.  Returns true iff they\n  // have the same content.\n  //\n  // Unlike wcscasecmp(), this function can handle NULL argument(s).\n  // A NULL C string is considered different to any non-NULL wide C string,\n  // including the empty string.\n  // NB: The implementations on different platforms slightly differ.\n  // On windows, this method uses _wcsicmp which compares according to LC_CTYPE\n  // environment variable. On GNU platform this method uses wcscasecmp\n  // which compares according to LC_CTYPE category of the current locale.\n  // On MacOS X, it uses towlower, which also uses LC_CTYPE category of the\n  // current locale.\nbool String::CaseInsensitiveWideCStringEquals(const wchar_t* lhs,\n                                              const wchar_t* rhs) {\n  if (lhs == NULL) return rhs == NULL;\n\n  if (rhs == NULL) return false;\n\n#if GTEST_OS_WINDOWS\n  return _wcsicmp(lhs, rhs) == 0;\n#elif GTEST_OS_LINUX && !GTEST_OS_LINUX_ANDROID\n  return wcscasecmp(lhs, rhs) == 0;\n#else\n  // Android, Mac OS X and Cygwin don't define wcscasecmp.\n  // Other unknown OSes may not define it either.\n  wint_t left, right;\n  do {\n    left = towlower(*lhs++);\n    right = towlower(*rhs++);\n  } while (left && left == right);\n  return left == right;\n#endif  // OS selector\n}\n\n// Returns true iff str ends with the given suffix, ignoring case.\n// Any string is considered to end with an empty suffix.\nbool String::EndsWithCaseInsensitive(\n    const std::string& str, const std::string& suffix) {\n  const size_t str_len = str.length();\n  const size_t suffix_len = suffix.length();\n  return (str_len >= suffix_len) &&\n         CaseInsensitiveCStringEquals(str.c_str() + str_len - suffix_len,\n                                      suffix.c_str());\n}\n\n// Formats an int value as \"%02d\".\nstd::string String::FormatIntWidth2(int value) {\n  std::stringstream ss;\n  ss << std::setfill('0') << std::setw(2) << value;\n  return ss.str();\n}\n\n// Formats an int value as \"%X\".\nstd::string String::FormatHexInt(int value) {\n  std::stringstream ss;\n  ss << std::hex << std::uppercase << value;\n  return ss.str();\n}\n\n// Formats a byte as \"%02X\".\nstd::string String::FormatByte(unsigned char value) {\n  std::stringstream ss;\n  ss << std::setfill('0') << std::setw(2) << std::hex << std::uppercase\n     << static_cast<unsigned int>(value);\n  return ss.str();\n}\n\n// Converts the buffer in a stringstream to an std::string, converting NUL\n// bytes to \"\\\\0\" along the way.\nstd::string StringStreamToString(::std::stringstream* ss) {\n  const ::std::string& str = ss->str();\n  const char* const start = str.c_str();\n  const char* const end = start + str.length();\n\n  std::string result;\n  result.reserve(2 * (end - start));\n  for (const char* ch = start; ch != end; ++ch) {\n    if (*ch == '\\0') {\n      result += \"\\\\0\";  // Replaces NUL with \"\\\\0\";\n    } else {\n      result += *ch;\n    }\n  }\n\n  return result;\n}\n\n// Appends the user-supplied message to the Google-Test-generated message.\nstd::string AppendUserMessage(const std::string& gtest_msg,\n                              const Message& user_msg) {\n  // Appends the user message if it's non-empty.\n  const std::string user_msg_string = user_msg.GetString();\n  if (user_msg_string.empty()) {\n    return gtest_msg;\n  }\n\n  return gtest_msg + \"\\n\" + user_msg_string;\n}\n\n}  // namespace internal\n\n// class TestResult\n\n// Creates an empty TestResult.\nTestResult::TestResult()\n    : death_test_count_(0),\n      elapsed_time_(0) {\n}\n\n// D'tor.\nTestResult::~TestResult() {\n}\n\n// Returns the i-th test part result among all the results. i can\n// range from 0 to total_part_count() - 1. If i is not in that range,\n// aborts the program.\nconst TestPartResult& TestResult::GetTestPartResult(int i) const {\n  if (i < 0 || i >= total_part_count())\n    internal::posix::Abort();\n  return test_part_results_.at(i);\n}\n\n// Returns the i-th test property. i can range from 0 to\n// test_property_count() - 1. If i is not in that range, aborts the\n// program.\nconst TestProperty& TestResult::GetTestProperty(int i) const {\n  if (i < 0 || i >= test_property_count())\n    internal::posix::Abort();\n  return test_properties_.at(i);\n}\n\n// Clears the test part results.\nvoid TestResult::ClearTestPartResults() {\n  test_part_results_.clear();\n}\n\n// Adds a test part result to the list.\nvoid TestResult::AddTestPartResult(const TestPartResult& test_part_result) {\n  test_part_results_.push_back(test_part_result);\n}\n\n// Adds a test property to the list. If a property with the same key as the\n// supplied property is already represented, the value of this test_property\n// replaces the old value for that key.\nvoid TestResult::RecordProperty(const std::string& xml_element,\n                                const TestProperty& test_property) {\n  if (!ValidateTestProperty(xml_element, test_property)) {\n    return;\n  }\n  internal::MutexLock lock(&test_properites_mutex_);\n  const std::vector<TestProperty>::iterator property_with_matching_key =\n      std::find_if(test_properties_.begin(), test_properties_.end(),\n                   internal::TestPropertyKeyIs(test_property.key()));\n  if (property_with_matching_key == test_properties_.end()) {\n    test_properties_.push_back(test_property);\n    return;\n  }\n  property_with_matching_key->SetValue(test_property.value());\n}\n\n// The list of reserved attributes used in the <testsuites> element of XML\n// output.\nstatic const char* const kReservedTestSuitesAttributes[] = {\n  \"disabled\",\n  \"errors\",\n  \"failures\",\n  \"name\",\n  \"random_seed\",\n  \"tests\",\n  \"time\",\n  \"timestamp\"\n};\n\n// The list of reserved attributes used in the <testsuite> element of XML\n// output.\nstatic const char* const kReservedTestSuiteAttributes[] = {\n  \"disabled\",\n  \"errors\",\n  \"failures\",\n  \"name\",\n  \"tests\",\n  \"time\"\n};\n\n// The list of reserved attributes used in the <testcase> element of XML output.\nstatic const char* const kReservedTestCaseAttributes[] = {\n  \"classname\",\n  \"name\",\n  \"status\",\n  \"time\",\n  \"type_param\",\n  \"value_param\"\n};\n\ntemplate <int kSize>\nstd::vector<std::string> ArrayAsVector(const char* const (&array)[kSize]) {\n  return std::vector<std::string>(array, array + kSize);\n}\n\nstatic std::vector<std::string> GetReservedAttributesForElement(\n    const std::string& xml_element) {\n  if (xml_element == \"testsuites\") {\n    return ArrayAsVector(kReservedTestSuitesAttributes);\n  } else if (xml_element == \"testsuite\") {\n    return ArrayAsVector(kReservedTestSuiteAttributes);\n  } else if (xml_element == \"testcase\") {\n    return ArrayAsVector(kReservedTestCaseAttributes);\n  } else {\n    GTEST_CHECK_(false) << \"Unrecognized xml_element provided: \" << xml_element;\n  }\n  // This code is unreachable but some compilers may not realizes that.\n  return std::vector<std::string>();\n}\n\nstatic std::string FormatWordList(const std::vector<std::string>& words) {\n  Message word_list;\n  for (size_t i = 0; i < words.size(); ++i) {\n    if (i > 0 && words.size() > 2) {\n      word_list << \", \";\n    }\n    if (i == words.size() - 1) {\n      word_list << \"and \";\n    }\n    word_list << \"'\" << words[i] << \"'\";\n  }\n  return word_list.GetString();\n}\n\nbool ValidateTestPropertyName(const std::string& property_name,\n                              const std::vector<std::string>& reserved_names) {\n  if (std::find(reserved_names.begin(), reserved_names.end(), property_name) !=\n          reserved_names.end()) {\n    ADD_FAILURE() << \"Reserved key used in RecordProperty(): \" << property_name\n                  << \" (\" << FormatWordList(reserved_names)\n                  << \" are reserved by \" << GTEST_NAME_ << \")\";\n    return false;\n  }\n  return true;\n}\n\n// Adds a failure if the key is a reserved attribute of the element named\n// xml_element.  Returns true if the property is valid.\nbool TestResult::ValidateTestProperty(const std::string& xml_element,\n                                      const TestProperty& test_property) {\n  return ValidateTestPropertyName(test_property.key(),\n                                  GetReservedAttributesForElement(xml_element));\n}\n\n// Clears the object.\nvoid TestResult::Clear() {\n  test_part_results_.clear();\n  test_properties_.clear();\n  death_test_count_ = 0;\n  elapsed_time_ = 0;\n}\n\n// Returns true iff the test failed.\nbool TestResult::Failed() const {\n  for (int i = 0; i < total_part_count(); ++i) {\n    if (GetTestPartResult(i).failed())\n      return true;\n  }\n  return false;\n}\n\n// Returns true iff the test part fatally failed.\nstatic bool TestPartFatallyFailed(const TestPartResult& result) {\n  return result.fatally_failed();\n}\n\n// Returns true iff the test fatally failed.\nbool TestResult::HasFatalFailure() const {\n  return CountIf(test_part_results_, TestPartFatallyFailed) > 0;\n}\n\n// Returns true iff the test part non-fatally failed.\nstatic bool TestPartNonfatallyFailed(const TestPartResult& result) {\n  return result.nonfatally_failed();\n}\n\n// Returns true iff the test has a non-fatal failure.\nbool TestResult::HasNonfatalFailure() const {\n  return CountIf(test_part_results_, TestPartNonfatallyFailed) > 0;\n}\n\n// Gets the number of all test parts.  This is the sum of the number\n// of successful test parts and the number of failed test parts.\nint TestResult::total_part_count() const {\n  return static_cast<int>(test_part_results_.size());\n}\n\n// Returns the number of the test properties.\nint TestResult::test_property_count() const {\n  return static_cast<int>(test_properties_.size());\n}\n\n// class Test\n\n// Creates a Test object.\n\n// The c'tor saves the states of all flags.\nTest::Test()\n    : gtest_flag_saver_(new GTEST_FLAG_SAVER_) {\n}\n\n// The d'tor restores the states of all flags.  The actual work is\n// done by the d'tor of the gtest_flag_saver_ field, and thus not\n// visible here.\nTest::~Test() {\n}\n\n// Sets up the test fixture.\n//\n// A sub-class may override this.\nvoid Test::SetUp() {\n}\n\n// Tears down the test fixture.\n//\n// A sub-class may override this.\nvoid Test::TearDown() {\n}\n\n// Allows user supplied key value pairs to be recorded for later output.\nvoid Test::RecordProperty(const std::string& key, const std::string& value) {\n  UnitTest::GetInstance()->RecordProperty(key, value);\n}\n\n// Allows user supplied key value pairs to be recorded for later output.\nvoid Test::RecordProperty(const std::string& key, int value) {\n  Message value_message;\n  value_message << value;\n  RecordProperty(key, value_message.GetString().c_str());\n}\n\nnamespace internal {\n\nvoid ReportFailureInUnknownLocation(TestPartResult::Type result_type,\n                                    const std::string& message) {\n  // This function is a friend of UnitTest and as such has access to\n  // AddTestPartResult.\n  UnitTest::GetInstance()->AddTestPartResult(\n      result_type,\n      NULL,  // No info about the source file where the exception occurred.\n      -1,    // We have no info on which line caused the exception.\n      message,\n      \"\");   // No stack trace, either.\n}\n\n}  // namespace internal\n\n// Google Test requires all tests in the same test case to use the same test\n// fixture class.  This function checks if the current test has the\n// same fixture class as the first test in the current test case.  If\n// yes, it returns true; otherwise it generates a Google Test failure and\n// returns false.\nbool Test::HasSameFixtureClass() {\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  const TestCase* const test_case = impl->current_test_case();\n\n  // Info about the first test in the current test case.\n  const TestInfo* const first_test_info = test_case->test_info_list()[0];\n  const internal::TypeId first_fixture_id = first_test_info->fixture_class_id_;\n  const char* const first_test_name = first_test_info->name();\n\n  // Info about the current test.\n  const TestInfo* const this_test_info = impl->current_test_info();\n  const internal::TypeId this_fixture_id = this_test_info->fixture_class_id_;\n  const char* const this_test_name = this_test_info->name();\n\n  if (this_fixture_id != first_fixture_id) {\n    // Is the first test defined using TEST?\n    const bool first_is_TEST = first_fixture_id == internal::GetTestTypeId();\n    // Is this test defined using TEST?\n    const bool this_is_TEST = this_fixture_id == internal::GetTestTypeId();\n\n    if (first_is_TEST || this_is_TEST) {\n      // Both TEST and TEST_F appear in same test case, which is incorrect.\n      // Tell the user how to fix this.\n\n      // Gets the name of the TEST and the name of the TEST_F.  Note\n      // that first_is_TEST and this_is_TEST cannot both be true, as\n      // the fixture IDs are different for the two tests.\n      const char* const TEST_name =\n          first_is_TEST ? first_test_name : this_test_name;\n      const char* const TEST_F_name =\n          first_is_TEST ? this_test_name : first_test_name;\n\n      ADD_FAILURE()\n          << \"All tests in the same test case must use the same test fixture\\n\"\n          << \"class, so mixing TEST_F and TEST in the same test case is\\n\"\n          << \"illegal.  In test case \" << this_test_info->test_case_name()\n          << \",\\n\"\n          << \"test \" << TEST_F_name << \" is defined using TEST_F but\\n\"\n          << \"test \" << TEST_name << \" is defined using TEST.  You probably\\n\"\n          << \"want to change the TEST to TEST_F or move it to another test\\n\"\n          << \"case.\";\n    } else {\n      // Two fixture classes with the same name appear in two different\n      // namespaces, which is not allowed. Tell the user how to fix this.\n      ADD_FAILURE()\n          << \"All tests in the same test case must use the same test fixture\\n\"\n          << \"class.  However, in test case \"\n          << this_test_info->test_case_name() << \",\\n\"\n          << \"you defined test \" << first_test_name\n          << \" and test \" << this_test_name << \"\\n\"\n          << \"using two different test fixture classes.  This can happen if\\n\"\n          << \"the two classes are from different namespaces or translation\\n\"\n          << \"units and have the same name.  You should probably rename one\\n\"\n          << \"of the classes to put the tests into different test cases.\";\n    }\n    return false;\n  }\n\n  return true;\n}\n\n#if GTEST_HAS_SEH\n\n// Adds an \"exception thrown\" fatal failure to the current test.  This\n// function returns its result via an output parameter pointer because VC++\n// prohibits creation of objects with destructors on stack in functions\n// using __try (see error C2712).\nstatic std::string* FormatSehExceptionMessage(DWORD exception_code,\n                                              const char* location) {\n  Message message;\n  message << \"SEH exception with code 0x\" << std::setbase(16) <<\n    exception_code << std::setbase(10) << \" thrown in \" << location << \".\";\n\n  return new std::string(message.GetString());\n}\n\n#endif  // GTEST_HAS_SEH\n\nnamespace internal {\n\n#if GTEST_HAS_EXCEPTIONS\n\n// Adds an \"exception thrown\" fatal failure to the current test.\nstatic std::string FormatCxxExceptionMessage(const char* description,\n                                             const char* location) {\n  Message message;\n  if (description != NULL) {\n    message << \"C++ exception with description \\\"\" << description << \"\\\"\";\n  } else {\n    message << \"Unknown C++ exception\";\n  }\n  message << \" thrown in \" << location << \".\";\n\n  return message.GetString();\n}\n\nstatic std::string PrintTestPartResultToString(\n    const TestPartResult& test_part_result);\n\nGoogleTestFailureException::GoogleTestFailureException(\n    const TestPartResult& failure)\n    : ::std::runtime_error(PrintTestPartResultToString(failure).c_str()) {}\n\n#endif  // GTEST_HAS_EXCEPTIONS\n\n// We put these helper functions in the internal namespace as IBM's xlC\n// compiler rejects the code if they were declared static.\n\n// Runs the given method and handles SEH exceptions it throws, when\n// SEH is supported; returns the 0-value for type Result in case of an\n// SEH exception.  (Microsoft compilers cannot handle SEH and C++\n// exceptions in the same function.  Therefore, we provide a separate\n// wrapper function for handling SEH exceptions.)\ntemplate <class T, typename Result>\nResult HandleSehExceptionsInMethodIfSupported(\n    T* object, Result (T::*method)(), const char* location) {\n#if GTEST_HAS_SEH\n  __try {\n    return (object->*method)();\n  } __except (internal::UnitTestOptions::GTestShouldProcessSEH(  // NOLINT\n      GetExceptionCode())) {\n    // We create the exception message on the heap because VC++ prohibits\n    // creation of objects with destructors on stack in functions using __try\n    // (see error C2712).\n    std::string* exception_message = FormatSehExceptionMessage(\n        GetExceptionCode(), location);\n    internal::ReportFailureInUnknownLocation(TestPartResult::kFatalFailure,\n                                             *exception_message);\n    delete exception_message;\n    return static_cast<Result>(0);\n  }\n#else\n  (void)location;\n  return (object->*method)();\n#endif  // GTEST_HAS_SEH\n}\n\n// Runs the given method and catches and reports C++ and/or SEH-style\n// exceptions, if they are supported; returns the 0-value for type\n// Result in case of an SEH exception.\ntemplate <class T, typename Result>\nResult HandleExceptionsInMethodIfSupported(\n    T* object, Result (T::*method)(), const char* location) {\n  // NOTE: The user code can affect the way in which Google Test handles\n  // exceptions by setting GTEST_FLAG(catch_exceptions), but only before\n  // RUN_ALL_TESTS() starts. It is technically possible to check the flag\n  // after the exception is caught and either report or re-throw the\n  // exception based on the flag's value:\n  //\n  // try {\n  //   // Perform the test method.\n  // } catch (...) {\n  //   if (GTEST_FLAG(catch_exceptions))\n  //     // Report the exception as failure.\n  //   else\n  //     throw;  // Re-throws the original exception.\n  // }\n  //\n  // However, the purpose of this flag is to allow the program to drop into\n  // the debugger when the exception is thrown. On most platforms, once the\n  // control enters the catch block, the exception origin information is\n  // lost and the debugger will stop the program at the point of the\n  // re-throw in this function -- instead of at the point of the original\n  // throw statement in the code under test.  For this reason, we perform\n  // the check early, sacrificing the ability to affect Google Test's\n  // exception handling in the method where the exception is thrown.\n  if (internal::GetUnitTestImpl()->catch_exceptions()) {\n#if GTEST_HAS_EXCEPTIONS\n    try {\n      return HandleSehExceptionsInMethodIfSupported(object, method, location);\n    } catch (const internal::GoogleTestFailureException&) {  // NOLINT\n      // This exception type can only be thrown by a failed Google\n      // Test assertion with the intention of letting another testing\n      // framework catch it.  Therefore we just re-throw it.\n      throw;\n    } catch (const std::exception& e) {  // NOLINT\n      internal::ReportFailureInUnknownLocation(\n          TestPartResult::kFatalFailure,\n          FormatCxxExceptionMessage(e.what(), location));\n    } catch (...) {  // NOLINT\n      internal::ReportFailureInUnknownLocation(\n          TestPartResult::kFatalFailure,\n          FormatCxxExceptionMessage(NULL, location));\n    }\n    return static_cast<Result>(0);\n#else\n    return HandleSehExceptionsInMethodIfSupported(object, method, location);\n#endif  // GTEST_HAS_EXCEPTIONS\n  } else {\n    return (object->*method)();\n  }\n}\n\n}  // namespace internal\n\n// Runs the test and updates the test result.\nvoid Test::Run() {\n  if (!HasSameFixtureClass()) return;\n\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n  internal::HandleExceptionsInMethodIfSupported(this, &Test::SetUp, \"SetUp()\");\n  // We will run the test only if SetUp() was successful.\n  if (!HasFatalFailure()) {\n    impl->os_stack_trace_getter()->UponLeavingGTest();\n    internal::HandleExceptionsInMethodIfSupported(\n        this, &Test::TestBody, \"the test body\");\n  }\n\n  // However, we want to clean up as much as possible.  Hence we will\n  // always call TearDown(), even if SetUp() or the test body has\n  // failed.\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n  internal::HandleExceptionsInMethodIfSupported(\n      this, &Test::TearDown, \"TearDown()\");\n}\n\n// Returns true iff the current test has a fatal failure.\nbool Test::HasFatalFailure() {\n  return internal::GetUnitTestImpl()->current_test_result()->HasFatalFailure();\n}\n\n// Returns true iff the current test has a non-fatal failure.\nbool Test::HasNonfatalFailure() {\n  return internal::GetUnitTestImpl()->current_test_result()->\n      HasNonfatalFailure();\n}\n\n// class TestInfo\n\n// Constructs a TestInfo object. It assumes ownership of the test factory\n// object.\nTestInfo::TestInfo(const std::string& a_test_case_name,\n                   const std::string& a_name,\n                   const char* a_type_param,\n                   const char* a_value_param,\n                   internal::CodeLocation a_code_location,\n                   internal::TypeId fixture_class_id,\n                   internal::TestFactoryBase* factory)\n    : test_case_name_(a_test_case_name),\n      name_(a_name),\n      type_param_(a_type_param ? new std::string(a_type_param) : NULL),\n      value_param_(a_value_param ? new std::string(a_value_param) : NULL),\n      location_(a_code_location),\n      fixture_class_id_(fixture_class_id),\n      should_run_(false),\n      is_disabled_(false),\n      matches_filter_(false),\n      factory_(factory),\n      result_() {}\n\n// Destructs a TestInfo object.\nTestInfo::~TestInfo() { delete factory_; }\n\nnamespace internal {\n\n// Creates a new TestInfo object and registers it with Google Test;\n// returns the created object.\n//\n// Arguments:\n//\n//   test_case_name:   name of the test case\n//   name:             name of the test\n//   type_param:       the name of the test's type parameter, or NULL if\n//                     this is not a typed or a type-parameterized test.\n//   value_param:      text representation of the test's value parameter,\n//                     or NULL if this is not a value-parameterized test.\n//   code_location:    code location where the test is defined\n//   fixture_class_id: ID of the test fixture class\n//   set_up_tc:        pointer to the function that sets up the test case\n//   tear_down_tc:     pointer to the function that tears down the test case\n//   factory:          pointer to the factory that creates a test object.\n//                     The newly created TestInfo instance will assume\n//                     ownership of the factory object.\nTestInfo* MakeAndRegisterTestInfo(\n    const char* test_case_name,\n    const char* name,\n    const char* type_param,\n    const char* value_param,\n    CodeLocation code_location,\n    TypeId fixture_class_id,\n    SetUpTestCaseFunc set_up_tc,\n    TearDownTestCaseFunc tear_down_tc,\n    TestFactoryBase* factory) {\n  TestInfo* const test_info =\n      new TestInfo(test_case_name, name, type_param, value_param,\n                   code_location, fixture_class_id, factory);\n  GetUnitTestImpl()->AddTestInfo(set_up_tc, tear_down_tc, test_info);\n  return test_info;\n}\n\n#if GTEST_HAS_PARAM_TEST\nvoid ReportInvalidTestCaseType(const char* test_case_name,\n                               CodeLocation code_location) {\n  Message errors;\n  errors\n      << \"Attempted redefinition of test case \" << test_case_name << \".\\n\"\n      << \"All tests in the same test case must use the same test fixture\\n\"\n      << \"class.  However, in test case \" << test_case_name << \", you tried\\n\"\n      << \"to define a test using a fixture class different from the one\\n\"\n      << \"used earlier. This can happen if the two fixture classes are\\n\"\n      << \"from different namespaces and have the same name. You should\\n\"\n      << \"probably rename one of the classes to put the tests into different\\n\"\n      << \"test cases.\";\n\n  fprintf(stderr, \"%s %s\",\n          FormatFileLocation(code_location.file.c_str(),\n                             code_location.line).c_str(),\n          errors.GetString().c_str());\n}\n#endif  // GTEST_HAS_PARAM_TEST\n\n}  // namespace internal\n\nnamespace {\n\n// A predicate that checks the test name of a TestInfo against a known\n// value.\n//\n// This is used for implementation of the TestCase class only.  We put\n// it in the anonymous namespace to prevent polluting the outer\n// namespace.\n//\n// TestNameIs is copyable.\nclass TestNameIs {\n public:\n  // Constructor.\n  //\n  // TestNameIs has NO default constructor.\n  explicit TestNameIs(const char* name)\n      : name_(name) {}\n\n  // Returns true iff the test name of test_info matches name_.\n  bool operator()(const TestInfo * test_info) const {\n    return test_info && test_info->name() == name_;\n  }\n\n private:\n  std::string name_;\n};\n\n}  // namespace\n\nnamespace internal {\n\n// This method expands all parameterized tests registered with macros TEST_P\n// and INSTANTIATE_TEST_CASE_P into regular tests and registers those.\n// This will be done just once during the program runtime.\nvoid UnitTestImpl::RegisterParameterizedTests() {\n#if GTEST_HAS_PARAM_TEST\n  if (!parameterized_tests_registered_) {\n    parameterized_test_registry_.RegisterTests();\n    parameterized_tests_registered_ = true;\n  }\n#endif\n}\n\n}  // namespace internal\n\n// Creates the test object, runs it, records its result, and then\n// deletes it.\nvoid TestInfo::Run() {\n  if (!should_run_) return;\n\n  // Tells UnitTest where to store test result.\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  impl->set_current_test_info(this);\n\n  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\n\n  // Notifies the unit test event listeners that a test is about to start.\n  repeater->OnTestStart(*this);\n\n  const TimeInMillis start = internal::GetTimeInMillis();\n\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n\n  // Creates the test object.\n  Test* const test = internal::HandleExceptionsInMethodIfSupported(\n      factory_, &internal::TestFactoryBase::CreateTest,\n      \"the test fixture's constructor\");\n\n  // Runs the test only if the test object was created and its\n  // constructor didn't generate a fatal failure.\n  if ((test != NULL) && !Test::HasFatalFailure()) {\n    // This doesn't throw as all user code that can throw are wrapped into\n    // exception handling code.\n    test->Run();\n  }\n\n  // Deletes the test object.\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n  internal::HandleExceptionsInMethodIfSupported(\n      test, &Test::DeleteSelf_, \"the test fixture's destructor\");\n\n  result_.set_elapsed_time(internal::GetTimeInMillis() - start);\n\n  // Notifies the unit test event listener that a test has just finished.\n  repeater->OnTestEnd(*this);\n\n  // Tells UnitTest to stop associating assertion results to this\n  // test.\n  impl->set_current_test_info(NULL);\n}\n\n// class TestCase\n\n// Gets the number of successful tests in this test case.\nint TestCase::successful_test_count() const {\n  return CountIf(test_info_list_, TestPassed);\n}\n\n// Gets the number of failed tests in this test case.\nint TestCase::failed_test_count() const {\n  return CountIf(test_info_list_, TestFailed);\n}\n\n// Gets the number of disabled tests that will be reported in the XML report.\nint TestCase::reportable_disabled_test_count() const {\n  return CountIf(test_info_list_, TestReportableDisabled);\n}\n\n// Gets the number of disabled tests in this test case.\nint TestCase::disabled_test_count() const {\n  return CountIf(test_info_list_, TestDisabled);\n}\n\n// Gets the number of tests to be printed in the XML report.\nint TestCase::reportable_test_count() const {\n  return CountIf(test_info_list_, TestReportable);\n}\n\n// Get the number of tests in this test case that should run.\nint TestCase::test_to_run_count() const {\n  return CountIf(test_info_list_, ShouldRunTest);\n}\n\n// Gets the number of all tests.\nint TestCase::total_test_count() const {\n  return static_cast<int>(test_info_list_.size());\n}\n\n// Creates a TestCase with the given name.\n//\n// Arguments:\n//\n//   name:         name of the test case\n//   a_type_param: the name of the test case's type parameter, or NULL if\n//                 this is not a typed or a type-parameterized test case.\n//   set_up_tc:    pointer to the function that sets up the test case\n//   tear_down_tc: pointer to the function that tears down the test case\nTestCase::TestCase(const char* a_name, const char* a_type_param,\n                   Test::SetUpTestCaseFunc set_up_tc,\n                   Test::TearDownTestCaseFunc tear_down_tc)\n    : name_(a_name),\n      type_param_(a_type_param ? new std::string(a_type_param) : NULL),\n      set_up_tc_(set_up_tc),\n      tear_down_tc_(tear_down_tc),\n      should_run_(false),\n      elapsed_time_(0) {\n}\n\n// Destructor of TestCase.\nTestCase::~TestCase() {\n  // Deletes every Test in the collection.\n  ForEach(test_info_list_, internal::Delete<TestInfo>);\n}\n\n// Returns the i-th test among all the tests. i can range from 0 to\n// total_test_count() - 1. If i is not in that range, returns NULL.\nconst TestInfo* TestCase::GetTestInfo(int i) const {\n  const int index = GetElementOr(test_indices_, i, -1);\n  return index < 0 ? NULL : test_info_list_[index];\n}\n\n// Returns the i-th test among all the tests. i can range from 0 to\n// total_test_count() - 1. If i is not in that range, returns NULL.\nTestInfo* TestCase::GetMutableTestInfo(int i) {\n  const int index = GetElementOr(test_indices_, i, -1);\n  return index < 0 ? NULL : test_info_list_[index];\n}\n\n// Adds a test to this test case.  Will delete the test upon\n// destruction of the TestCase object.\nvoid TestCase::AddTestInfo(TestInfo * test_info) {\n  test_info_list_.push_back(test_info);\n  test_indices_.push_back(static_cast<int>(test_indices_.size()));\n}\n\n// Runs every test in this TestCase.\nvoid TestCase::Run() {\n  if (!should_run_) return;\n\n  internal::UnitTestImpl* const impl = internal::GetUnitTestImpl();\n  impl->set_current_test_case(this);\n\n  TestEventListener* repeater = UnitTest::GetInstance()->listeners().repeater();\n\n  repeater->OnTestCaseStart(*this);\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n  internal::HandleExceptionsInMethodIfSupported(\n      this, &TestCase::RunSetUpTestCase, \"SetUpTestCase()\");\n\n  const internal::TimeInMillis start = internal::GetTimeInMillis();\n  for (int i = 0; i < total_test_count(); i++) {\n    GetMutableTestInfo(i)->Run();\n  }\n  elapsed_time_ = internal::GetTimeInMillis() - start;\n\n  impl->os_stack_trace_getter()->UponLeavingGTest();\n  internal::HandleExceptionsInMethodIfSupported(\n      this, &TestCase::RunTearDownTestCase, \"TearDownTestCase()\");\n\n  repeater->OnTestCaseEnd(*this);\n  impl->set_current_test_case(NULL);\n}\n\n// Clears the results of all tests in this test case.\nvoid TestCase::ClearResult() {\n  ad_hoc_test_result_.Clear();\n  ForEach(test_info_list_, TestInfo::ClearTestResult);\n}\n\n// Shuffles the tests in this test case.\nvoid TestCase::ShuffleTests(internal::Random* random) {\n  Shuffle(random, &test_indices_);\n}\n\n// Restores the test order to before the first shuffle.\nvoid TestCase::UnshuffleTests() {\n  for (size_t i = 0; i < test_indices_.size(); i++) {\n    test_indices_[i] = static_cast<int>(i);\n  }\n}\n\n// Formats a countable noun.  Depending on its quantity, either the\n// singular form or the plural form is used. e.g.\n//\n// FormatCountableNoun(1, \"formula\", \"formuli\") returns \"1 formula\".\n// FormatCountableNoun(5, \"book\", \"books\") returns \"5 books\".\nstatic std::string FormatCountableNoun(int count,\n                                       const char * singular_form,\n                                       const char * plural_form) {\n  return internal::StreamableToString(count) + \" \" +\n      (count == 1 ? singular_form : plural_form);\n}\n\n// Formats the count of tests.\nstatic std::string FormatTestCount(int test_count) {\n  return FormatCountableNoun(test_count, \"test\", \"tests\");\n}\n\n// Formats the count of test cases.\nstatic std::string FormatTestCaseCount(int test_case_count) {\n  return FormatCountableNoun(test_case_count, \"test case\", \"test cases\");\n}\n\n// Converts a TestPartResult::Type enum to human-friendly string\n// representation.  Both kNonFatalFailure and kFatalFailure are translated\n// to \"Failure\", as the user usually doesn't care about the difference\n// between the two when viewing the test result.\nstatic const char * TestPartResultTypeToString(TestPartResult::Type type) {\n  switch (type) {\n    case TestPartResult::kSuccess:\n      return \"Success\";\n\n    case TestPartResult::kNonFatalFailure:\n    case TestPartResult::kFatalFailure:\n#ifdef _MSC_VER\n      return \"error: \";\n#else\n      return \"Failure\\n\";\n#endif\n    default:\n      return \"Unknown result type\";\n  }\n}\n\nnamespace internal {\n\n// Prints a TestPartResult to an std::string.\nstatic std::string PrintTestPartResultToString(\n    const TestPartResult& test_part_result) {\n  return (Message()\n          << internal::FormatFileLocation(test_part_result.file_name(),\n                                          test_part_result.line_number())\n          << \" \" << TestPartResultTypeToString(test_part_result.type())\n          << test_part_result.message()).GetString();\n}\n\n// Prints a TestPartResult.\nstatic void PrintTestPartResult(const TestPartResult& test_part_result) {\n  const std::string& result =\n      PrintTestPartResultToString(test_part_result);\n  printf(\"%s\\n\", result.c_str());\n  fflush(stdout);\n  // If the test program runs in Visual Studio or a debugger, the\n  // following statements add the test part result message to the Output\n  // window such that the user can double-click on it to jump to the\n  // corresponding source code location; otherwise they do nothing.\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\n  // We don't call OutputDebugString*() on Windows Mobile, as printing\n  // to stdout is done by OutputDebugString() there already - we don't\n  // want the same message printed twice.\n  ::OutputDebugStringA(result.c_str());\n  ::OutputDebugStringA(\"\\n\");\n#endif\n}\n\n// class PrettyUnitTestResultPrinter\n\nenum GTestColor {\n  COLOR_DEFAULT,\n  COLOR_RED,\n  COLOR_GREEN,\n  COLOR_YELLOW\n};\n\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \\\n    !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\n\n// Returns the character attribute for the given color.\nWORD GetColorAttribute(GTestColor color) {\n  switch (color) {\n    case COLOR_RED:    return FOREGROUND_RED;\n    case COLOR_GREEN:  return FOREGROUND_GREEN;\n    case COLOR_YELLOW: return FOREGROUND_RED | FOREGROUND_GREEN;\n    default:           return 0;\n  }\n}\n\n#else\n\n// Returns the ANSI color code for the given color.  COLOR_DEFAULT is\n// an invalid input.\nconst char* GetAnsiColorCode(GTestColor color) {\n  switch (color) {\n    case COLOR_RED:     return \"1\";\n    case COLOR_GREEN:   return \"2\";\n    case COLOR_YELLOW:  return \"3\";\n    default:            return NULL;\n  };\n}\n\n#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\n\n// Returns true iff Google Test should use colors in the output.\nbool ShouldUseColor(bool stdout_is_tty) {\n  const char* const gtest_color = GTEST_FLAG(color).c_str();\n\n  if (String::CaseInsensitiveCStringEquals(gtest_color, \"auto\")) {\n#if GTEST_OS_WINDOWS\n    // On Windows the TERM variable is usually not set, but the\n    // console there does support colors.\n    return stdout_is_tty;\n#else\n    // On non-Windows platforms, we rely on the TERM variable.\n    const char* const term = posix::GetEnv(\"TERM\");\n    const bool term_supports_color =\n        String::CStringEquals(term, \"xterm\") ||\n        String::CStringEquals(term, \"xterm-color\") ||\n        String::CStringEquals(term, \"xterm-256color\") ||\n        String::CStringEquals(term, \"screen\") ||\n        String::CStringEquals(term, \"screen-256color\") ||\n        String::CStringEquals(term, \"tmux\") ||\n        String::CStringEquals(term, \"tmux-256color\") ||\n        String::CStringEquals(term, \"rxvt-unicode\") ||\n        String::CStringEquals(term, \"rxvt-unicode-256color\") ||\n        String::CStringEquals(term, \"linux\") ||\n        String::CStringEquals(term, \"cygwin\");\n    return stdout_is_tty && term_supports_color;\n#endif  // GTEST_OS_WINDOWS\n  }\n\n  return String::CaseInsensitiveCStringEquals(gtest_color, \"yes\") ||\n      String::CaseInsensitiveCStringEquals(gtest_color, \"true\") ||\n      String::CaseInsensitiveCStringEquals(gtest_color, \"t\") ||\n      String::CStringEquals(gtest_color, \"1\");\n  // We take \"yes\", \"true\", \"t\", and \"1\" as meaning \"yes\".  If the\n  // value is neither one of these nor \"auto\", we treat it as \"no\" to\n  // be conservative.\n}\n\n// Helpers for printing colored strings to stdout. Note that on Windows, we\n// cannot simply emit special characters and have the terminal change colors.\n// This routine must actually emit the characters rather than return a string\n// that would be colored when printed, as can be done on Linux.\nvoid ColoredPrintf(GTestColor color, const char* fmt, ...) {\n  va_list args;\n  va_start(args, fmt);\n\n#if GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS || \\\n    GTEST_OS_IOS || GTEST_OS_WINDOWS_PHONE || GTEST_OS_WINDOWS_RT\n  const bool use_color = AlwaysFalse();\n#else\n  static const bool in_color_mode =\n      ShouldUseColor(posix::IsATTY(posix::FileNo(stdout)) != 0);\n  const bool use_color = in_color_mode && (color != COLOR_DEFAULT);\n#endif  // GTEST_OS_WINDOWS_MOBILE || GTEST_OS_SYMBIAN || GTEST_OS_ZOS\n  // The '!= 0' comparison is necessary to satisfy MSVC 7.1.\n\n  if (!use_color) {\n    vprintf(fmt, args);\n    va_end(args);\n    return;\n  }\n\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE && \\\n    !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\n  const HANDLE stdout_handle = GetStdHandle(STD_OUTPUT_HANDLE);\n\n  // Gets the current text color.\n  CONSOLE_SCREEN_BUFFER_INFO buffer_info;\n  GetConsoleScreenBufferInfo(stdout_handle, &buffer_info);\n  const WORD old_color_attrs = buffer_info.wAttributes;\n\n  // We need to flush the stream buffers into the console before each\n  // SetConsoleTextAttribute call lest it affect the text that is already\n  // printed but has not yet reached the console.\n  fflush(stdout);\n  SetConsoleTextAttribute(stdout_handle,\n                          GetColorAttribute(color) | FOREGROUND_INTENSITY);\n  vprintf(fmt, args);\n\n  fflush(stdout);\n  // Restores the text color.\n  SetConsoleTextAttribute(stdout_handle, old_color_attrs);\n#else\n  printf(\"\\033[0;3%sm\", GetAnsiColorCode(color));\n  vprintf(fmt, args);\n  printf(\"\\033[m\");  // Resets the terminal to default.\n#endif  // GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_MOBILE\n  va_end(args);\n}\n\n// Text printed in Google Test's text output and --gunit_list_tests\n// output to label the type parameter and value parameter for a test.\nstatic const char kTypeParamLabel[] = \"TypeParam\";\nstatic const char kValueParamLabel[] = \"GetParam()\";\n\nvoid PrintFullTestCommentIfPresent(const TestInfo& test_info) {\n  const char* const type_param = test_info.type_param();\n  const char* const value_param = test_info.value_param();\n\n  if (type_param != NULL || value_param != NULL) {\n    printf(\", where \");\n    if (type_param != NULL) {\n      printf(\"%s = %s\", kTypeParamLabel, type_param);\n      if (value_param != NULL)\n        printf(\" and \");\n    }\n    if (value_param != NULL) {\n      printf(\"%s = %s\", kValueParamLabel, value_param);\n    }\n  }\n}\n\n// This class implements the TestEventListener interface.\n//\n// Class PrettyUnitTestResultPrinter is copyable.\nclass PrettyUnitTestResultPrinter : public TestEventListener {\n public:\n  PrettyUnitTestResultPrinter() {}\n  static void PrintTestName(const char * test_case, const char * test) {\n    printf(\"%s.%s\", test_case, test);\n  }\n\n  // The following methods override what's in the TestEventListener class.\n  virtual void OnTestProgramStart(const UnitTest& /*unit_test*/) {}\n  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);\n  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);\n  virtual void OnEnvironmentsSetUpEnd(const UnitTest& /*unit_test*/) {}\n  virtual void OnTestCaseStart(const TestCase& test_case);\n  virtual void OnTestStart(const TestInfo& test_info);\n  virtual void OnTestPartResult(const TestPartResult& result);\n  virtual void OnTestEnd(const TestInfo& test_info);\n  virtual void OnTestCaseEnd(const TestCase& test_case);\n  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);\n  virtual void OnEnvironmentsTearDownEnd(const UnitTest& /*unit_test*/) {}\n  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);\n  virtual void OnTestProgramEnd(const UnitTest& /*unit_test*/) {}\n\n private:\n  static void PrintFailedTests(const UnitTest& unit_test);\n};\n\n  // Fired before each iteration of tests starts.\nvoid PrettyUnitTestResultPrinter::OnTestIterationStart(\n    const UnitTest& unit_test, int iteration) {\n  if (GTEST_FLAG(repeat) != 1)\n    printf(\"\\nRepeating all tests (iteration %d) . . .\\n\\n\", iteration + 1);\n\n  const char* const filter = GTEST_FLAG(filter).c_str();\n\n  // Prints the filter if it's not *.  This reminds the user that some\n  // tests may be skipped.\n  if (!String::CStringEquals(filter, kUniversalFilter)) {\n    ColoredPrintf(COLOR_YELLOW,\n                  \"Note: %s filter = %s\\n\", GTEST_NAME_, filter);\n  }\n\n  if (internal::ShouldShard(kTestTotalShards, kTestShardIndex, false)) {\n    const Int32 shard_index = Int32FromEnvOrDie(kTestShardIndex, -1);\n    ColoredPrintf(COLOR_YELLOW,\n                  \"Note: This is test shard %d of %s.\\n\",\n                  static_cast<int>(shard_index) + 1,\n                  internal::posix::GetEnv(kTestTotalShards));\n  }\n\n  if (GTEST_FLAG(shuffle)) {\n    ColoredPrintf(COLOR_YELLOW,\n                  \"Note: Randomizing tests' orders with a seed of %d .\\n\",\n                  unit_test.random_seed());\n  }\n\n  ColoredPrintf(COLOR_GREEN,  \"[==========] \");\n  printf(\"Running %s from %s.\\n\",\n         FormatTestCount(unit_test.test_to_run_count()).c_str(),\n         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());\n  fflush(stdout);\n}\n\nvoid PrettyUnitTestResultPrinter::OnEnvironmentsSetUpStart(\n    const UnitTest& /*unit_test*/) {\n  ColoredPrintf(COLOR_GREEN,  \"[----------] \");\n  printf(\"Global test environment set-up.\\n\");\n  fflush(stdout);\n}\n\nvoid PrettyUnitTestResultPrinter::OnTestCaseStart(const TestCase& test_case) {\n  const std::string counts =\n      FormatCountableNoun(test_case.test_to_run_count(), \"test\", \"tests\");\n  ColoredPrintf(COLOR_GREEN, \"[----------] \");\n  printf(\"%s from %s\", counts.c_str(), test_case.name());\n  if (test_case.type_param() == NULL) {\n    printf(\"\\n\");\n  } else {\n    printf(\", where %s = %s\\n\", kTypeParamLabel, test_case.type_param());\n  }\n  fflush(stdout);\n}\n\nvoid PrettyUnitTestResultPrinter::OnTestStart(const TestInfo& test_info) {\n  ColoredPrintf(COLOR_GREEN,  \"[ RUN      ] \");\n  PrintTestName(test_info.test_case_name(), test_info.name());\n  printf(\"\\n\");\n  fflush(stdout);\n}\n\n// Called after an assertion failure.\nvoid PrettyUnitTestResultPrinter::OnTestPartResult(\n    const TestPartResult& result) {\n  // If the test part succeeded, we don't need to do anything.\n  if (result.type() == TestPartResult::kSuccess)\n    return;\n\n  // Print failure message from the assertion (e.g. expected this and got that).\n  PrintTestPartResult(result);\n  fflush(stdout);\n}\n\nvoid PrettyUnitTestResultPrinter::OnTestEnd(const TestInfo& test_info) {\n  if (test_info.result()->Passed()) {\n    ColoredPrintf(COLOR_GREEN, \"[       OK ] \");\n  } else {\n    ColoredPrintf(COLOR_RED, \"[  FAILED  ] \");\n  }\n  PrintTestName(test_info.test_case_name(), test_info.name());\n  if (test_info.result()->Failed())\n    PrintFullTestCommentIfPresent(test_info);\n\n  if (GTEST_FLAG(print_time)) {\n    printf(\" (%s ms)\\n\", internal::StreamableToString(\n           test_info.result()->elapsed_time()).c_str());\n  } else {\n    printf(\"\\n\");\n  }\n  fflush(stdout);\n}\n\nvoid PrettyUnitTestResultPrinter::OnTestCaseEnd(const TestCase& test_case) {\n  if (!GTEST_FLAG(print_time)) return;\n\n  const std::string counts =\n      FormatCountableNoun(test_case.test_to_run_count(), \"test\", \"tests\");\n  ColoredPrintf(COLOR_GREEN, \"[----------] \");\n  printf(\"%s from %s (%s ms total)\\n\\n\",\n         counts.c_str(), test_case.name(),\n         internal::StreamableToString(test_case.elapsed_time()).c_str());\n  fflush(stdout);\n}\n\nvoid PrettyUnitTestResultPrinter::OnEnvironmentsTearDownStart(\n    const UnitTest& /*unit_test*/) {\n  ColoredPrintf(COLOR_GREEN,  \"[----------] \");\n  printf(\"Global test environment tear-down\\n\");\n  fflush(stdout);\n}\n\n// Internal helper for printing the list of failed tests.\nvoid PrettyUnitTestResultPrinter::PrintFailedTests(const UnitTest& unit_test) {\n  const int failed_test_count = unit_test.failed_test_count();\n  if (failed_test_count == 0) {\n    return;\n  }\n\n  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {\n    const TestCase& test_case = *unit_test.GetTestCase(i);\n    if (!test_case.should_run() || (test_case.failed_test_count() == 0)) {\n      continue;\n    }\n    for (int j = 0; j < test_case.total_test_count(); ++j) {\n      const TestInfo& test_info = *test_case.GetTestInfo(j);\n      if (!test_info.should_run() || test_info.result()->Passed()) {\n        continue;\n      }\n      ColoredPrintf(COLOR_RED, \"[  FAILED  ] \");\n      printf(\"%s.%s\", test_case.name(), test_info.name());\n      PrintFullTestCommentIfPresent(test_info);\n      printf(\"\\n\");\n    }\n  }\n}\n\nvoid PrettyUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\n                                                     int /*iteration*/) {\n  ColoredPrintf(COLOR_GREEN,  \"[==========] \");\n  printf(\"%s from %s ran.\",\n         FormatTestCount(unit_test.test_to_run_count()).c_str(),\n         FormatTestCaseCount(unit_test.test_case_to_run_count()).c_str());\n  if (GTEST_FLAG(print_time)) {\n    printf(\" (%s ms total)\",\n           internal::StreamableToString(unit_test.elapsed_time()).c_str());\n  }\n  printf(\"\\n\");\n  ColoredPrintf(COLOR_GREEN,  \"[  PASSED  ] \");\n  printf(\"%s.\\n\", FormatTestCount(unit_test.successful_test_count()).c_str());\n\n  int num_failures = unit_test.failed_test_count();\n  if (!unit_test.Passed()) {\n    const int failed_test_count = unit_test.failed_test_count();\n    ColoredPrintf(COLOR_RED,  \"[  FAILED  ] \");\n    printf(\"%s, listed below:\\n\", FormatTestCount(failed_test_count).c_str());\n    PrintFailedTests(unit_test);\n    printf(\"\\n%2d FAILED %s\\n\", num_failures,\n                        num_failures == 1 ? \"TEST\" : \"TESTS\");\n  }\n\n  int num_disabled = unit_test.reportable_disabled_test_count();\n  if (num_disabled && !GTEST_FLAG(also_run_disabled_tests)) {\n    if (!num_failures) {\n      printf(\"\\n\");  // Add a spacer if no FAILURE banner is displayed.\n    }\n    ColoredPrintf(COLOR_YELLOW,\n                  \"  YOU HAVE %d DISABLED %s\\n\\n\",\n                  num_disabled,\n                  num_disabled == 1 ? \"TEST\" : \"TESTS\");\n  }\n  // Ensure that Google Test output is printed before, e.g., heapchecker output.\n  fflush(stdout);\n}\n\n// End PrettyUnitTestResultPrinter\n\n// class TestEventRepeater\n//\n// This class forwards events to other event listeners.\nclass TestEventRepeater : public TestEventListener {\n public:\n  TestEventRepeater() : forwarding_enabled_(true) {}\n  virtual ~TestEventRepeater();\n  void Append(TestEventListener *listener);\n  TestEventListener* Release(TestEventListener* listener);\n\n  // Controls whether events will be forwarded to listeners_. Set to false\n  // in death test child processes.\n  bool forwarding_enabled() const { return forwarding_enabled_; }\n  void set_forwarding_enabled(bool enable) { forwarding_enabled_ = enable; }\n\n  virtual void OnTestProgramStart(const UnitTest& unit_test);\n  virtual void OnTestIterationStart(const UnitTest& unit_test, int iteration);\n  virtual void OnEnvironmentsSetUpStart(const UnitTest& unit_test);\n  virtual void OnEnvironmentsSetUpEnd(const UnitTest& unit_test);\n  virtual void OnTestCaseStart(const TestCase& test_case);\n  virtual void OnTestStart(const TestInfo& test_info);\n  virtual void OnTestPartResult(const TestPartResult& result);\n  virtual void OnTestEnd(const TestInfo& test_info);\n  virtual void OnTestCaseEnd(const TestCase& test_case);\n  virtual void OnEnvironmentsTearDownStart(const UnitTest& unit_test);\n  virtual void OnEnvironmentsTearDownEnd(const UnitTest& unit_test);\n  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);\n  virtual void OnTestProgramEnd(const UnitTest& unit_test);\n\n private:\n  // Controls whether events will be forwarded to listeners_. Set to false\n  // in death test child processes.\n  bool forwarding_enabled_;\n  // The list of listeners that receive events.\n  std::vector<TestEventListener*> listeners_;\n\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(TestEventRepeater);\n};\n\nTestEventRepeater::~TestEventRepeater() {\n  ForEach(listeners_, Delete<TestEventListener>);\n}\n\nvoid TestEventRepeater::Append(TestEventListener *listener) {\n  listeners_.push_back(listener);\n}\n\n// TODO(vladl@google.com): Factor the search functionality into Vector::Find.\nTestEventListener* TestEventRepeater::Release(TestEventListener *listener) {\n  for (size_t i = 0; i < listeners_.size(); ++i) {\n    if (listeners_[i] == listener) {\n      listeners_.erase(listeners_.begin() + i);\n      return listener;\n    }\n  }\n\n  return NULL;\n}\n\n// Since most methods are very similar, use macros to reduce boilerplate.\n// This defines a member that forwards the call to all listeners.\n#define GTEST_REPEATER_METHOD_(Name, Type) \\\nvoid TestEventRepeater::Name(const Type& parameter) { \\\n  if (forwarding_enabled_) { \\\n    for (size_t i = 0; i < listeners_.size(); i++) { \\\n      listeners_[i]->Name(parameter); \\\n    } \\\n  } \\\n}\n// This defines a member that forwards the call to all listeners in reverse\n// order.\n#define GTEST_REVERSE_REPEATER_METHOD_(Name, Type) \\\nvoid TestEventRepeater::Name(const Type& parameter) { \\\n  if (forwarding_enabled_) { \\\n    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) { \\\n      listeners_[i]->Name(parameter); \\\n    } \\\n  } \\\n}\n\nGTEST_REPEATER_METHOD_(OnTestProgramStart, UnitTest)\nGTEST_REPEATER_METHOD_(OnEnvironmentsSetUpStart, UnitTest)\nGTEST_REPEATER_METHOD_(OnTestCaseStart, TestCase)\nGTEST_REPEATER_METHOD_(OnTestStart, TestInfo)\nGTEST_REPEATER_METHOD_(OnTestPartResult, TestPartResult)\nGTEST_REPEATER_METHOD_(OnEnvironmentsTearDownStart, UnitTest)\nGTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsSetUpEnd, UnitTest)\nGTEST_REVERSE_REPEATER_METHOD_(OnEnvironmentsTearDownEnd, UnitTest)\nGTEST_REVERSE_REPEATER_METHOD_(OnTestEnd, TestInfo)\nGTEST_REVERSE_REPEATER_METHOD_(OnTestCaseEnd, TestCase)\nGTEST_REVERSE_REPEATER_METHOD_(OnTestProgramEnd, UnitTest)\n\n#undef GTEST_REPEATER_METHOD_\n#undef GTEST_REVERSE_REPEATER_METHOD_\n\nvoid TestEventRepeater::OnTestIterationStart(const UnitTest& unit_test,\n                                             int iteration) {\n  if (forwarding_enabled_) {\n    for (size_t i = 0; i < listeners_.size(); i++) {\n      listeners_[i]->OnTestIterationStart(unit_test, iteration);\n    }\n  }\n}\n\nvoid TestEventRepeater::OnTestIterationEnd(const UnitTest& unit_test,\n                                           int iteration) {\n  if (forwarding_enabled_) {\n    for (int i = static_cast<int>(listeners_.size()) - 1; i >= 0; i--) {\n      listeners_[i]->OnTestIterationEnd(unit_test, iteration);\n    }\n  }\n}\n\n// End TestEventRepeater\n\n// This class generates an XML output file.\nclass XmlUnitTestResultPrinter : public EmptyTestEventListener {\n public:\n  explicit XmlUnitTestResultPrinter(const char* output_file);\n\n  virtual void OnTestIterationEnd(const UnitTest& unit_test, int iteration);\n\n private:\n  // Is c a whitespace character that is normalized to a space character\n  // when it appears in an XML attribute value?\n  static bool IsNormalizableWhitespace(char c) {\n    return c == 0x9 || c == 0xA || c == 0xD;\n  }\n\n  // May c appear in a well-formed XML document?\n  static bool IsValidXmlCharacter(char c) {\n    return IsNormalizableWhitespace(c) || c >= 0x20;\n  }\n\n  // Returns an XML-escaped copy of the input string str.  If\n  // is_attribute is true, the text is meant to appear as an attribute\n  // value, and normalizable whitespace is preserved by replacing it\n  // with character references.\n  static std::string EscapeXml(const std::string& str, bool is_attribute);\n\n  // Returns the given string with all characters invalid in XML removed.\n  static std::string RemoveInvalidXmlCharacters(const std::string& str);\n\n  // Convenience wrapper around EscapeXml when str is an attribute value.\n  static std::string EscapeXmlAttribute(const std::string& str) {\n    return EscapeXml(str, true);\n  }\n\n  // Convenience wrapper around EscapeXml when str is not an attribute value.\n  static std::string EscapeXmlText(const char* str) {\n    return EscapeXml(str, false);\n  }\n\n  // Verifies that the given attribute belongs to the given element and\n  // streams the attribute as XML.\n  static void OutputXmlAttribute(std::ostream* stream,\n                                 const std::string& element_name,\n                                 const std::string& name,\n                                 const std::string& value);\n\n  // Streams an XML CDATA section, escaping invalid CDATA sequences as needed.\n  static void OutputXmlCDataSection(::std::ostream* stream, const char* data);\n\n  // Streams an XML representation of a TestInfo object.\n  static void OutputXmlTestInfo(::std::ostream* stream,\n                                const char* test_case_name,\n                                const TestInfo& test_info);\n\n  // Prints an XML representation of a TestCase object\n  static void PrintXmlTestCase(::std::ostream* stream,\n                               const TestCase& test_case);\n\n  // Prints an XML summary of unit_test to output stream out.\n  static void PrintXmlUnitTest(::std::ostream* stream,\n                               const UnitTest& unit_test);\n\n  // Produces a string representing the test properties in a result as space\n  // delimited XML attributes based on the property key=\"value\" pairs.\n  // When the std::string is not empty, it includes a space at the beginning,\n  // to delimit this attribute from prior attributes.\n  static std::string TestPropertiesAsXmlAttributes(const TestResult& result);\n\n  // The output file.\n  const std::string output_file_;\n\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(XmlUnitTestResultPrinter);\n};\n\n// Creates a new XmlUnitTestResultPrinter.\nXmlUnitTestResultPrinter::XmlUnitTestResultPrinter(const char* output_file)\n    : output_file_(output_file) {\n  if (output_file_.c_str() == NULL || output_file_.empty()) {\n    fprintf(stderr, \"XML output file may not be null\\n\");\n    fflush(stderr);\n    exit(EXIT_FAILURE);\n  }\n}\n\n// Called after the unit test ends.\nvoid XmlUnitTestResultPrinter::OnTestIterationEnd(const UnitTest& unit_test,\n                                                  int /*iteration*/) {\n  FILE* xmlout = NULL;\n  FilePath output_file(output_file_);\n  FilePath output_dir(output_file.RemoveFileName());\n\n  if (output_dir.CreateDirectoriesRecursively()) {\n    xmlout = posix::FOpen(output_file_.c_str(), \"w\");\n  }\n  if (xmlout == NULL) {\n    // TODO(wan): report the reason of the failure.\n    //\n    // We don't do it for now as:\n    //\n    //   1. There is no urgent need for it.\n    //   2. It's a bit involved to make the errno variable thread-safe on\n    //      all three operating systems (Linux, Windows, and Mac OS).\n    //   3. To interpret the meaning of errno in a thread-safe way,\n    //      we need the strerror_r() function, which is not available on\n    //      Windows.\n    fprintf(stderr,\n            \"Unable to open file \\\"%s\\\"\\n\",\n            output_file_.c_str());\n    fflush(stderr);\n    exit(EXIT_FAILURE);\n  }\n  std::stringstream stream;\n  PrintXmlUnitTest(&stream, unit_test);\n  fprintf(xmlout, \"%s\", StringStreamToString(&stream).c_str());\n  fclose(xmlout);\n}\n\n// Returns an XML-escaped copy of the input string str.  If is_attribute\n// is true, the text is meant to appear as an attribute value, and\n// normalizable whitespace is preserved by replacing it with character\n// references.\n//\n// Invalid XML characters in str, if any, are stripped from the output.\n// It is expected that most, if not all, of the text processed by this\n// module will consist of ordinary English text.\n// If this module is ever modified to produce version 1.1 XML output,\n// most invalid characters can be retained using character references.\n// TODO(wan): It might be nice to have a minimally invasive, human-readable\n// escaping scheme for invalid characters, rather than dropping them.\nstd::string XmlUnitTestResultPrinter::EscapeXml(\n    const std::string& str, bool is_attribute) {\n  Message m;\n\n  for (size_t i = 0; i < str.size(); ++i) {\n    const char ch = str[i];\n    switch (ch) {\n      case '<':\n        m << \"&lt;\";\n        break;\n      case '>':\n        m << \"&gt;\";\n        break;\n      case '&':\n        m << \"&amp;\";\n        break;\n      case '\\'':\n        if (is_attribute)\n          m << \"&apos;\";\n        else\n          m << '\\'';\n        break;\n      case '\"':\n        if (is_attribute)\n          m << \"&quot;\";\n        else\n          m << '\"';\n        break;\n      default:\n        if (IsValidXmlCharacter(ch)) {\n          if (is_attribute && IsNormalizableWhitespace(ch))\n            m << \"&#x\" << String::FormatByte(static_cast<unsigned char>(ch))\n              << \";\";\n          else\n            m << ch;\n        }\n        break;\n    }\n  }\n\n  return m.GetString();\n}\n\n// Returns the given string with all characters invalid in XML removed.\n// Currently invalid characters are dropped from the string. An\n// alternative is to replace them with certain characters such as . or ?.\nstd::string XmlUnitTestResultPrinter::RemoveInvalidXmlCharacters(\n    const std::string& str) {\n  std::string output;\n  output.reserve(str.size());\n  for (std::string::const_iterator it = str.begin(); it != str.end(); ++it)\n    if (IsValidXmlCharacter(*it))\n      output.push_back(*it);\n\n  return output;\n}\n\n// The following routines generate an XML representation of a UnitTest\n// object.\n//\n// This is how Google Test concepts map to the DTD:\n//\n// <testsuites name=\"AllTests\">        <-- corresponds to a UnitTest object\n//   <testsuite name=\"testcase-name\">  <-- corresponds to a TestCase object\n//     <testcase name=\"test-name\">     <-- corresponds to a TestInfo object\n//       <failure message=\"...\">...</failure>\n//       <failure message=\"...\">...</failure>\n//       <failure message=\"...\">...</failure>\n//                                     <-- individual assertion failures\n//     </testcase>\n//   </testsuite>\n// </testsuites>\n\n// Formats the given time in milliseconds as seconds.\nstd::string FormatTimeInMillisAsSeconds(TimeInMillis ms) {\n  ::std::stringstream ss;\n  ss << (static_cast<double>(ms) * 1e-3);\n  return ss.str();\n}\n\nstatic bool PortableLocaltime(time_t seconds, struct tm* out) {\n#if defined(_MSC_VER)\n  return localtime_s(out, &seconds) == 0;\n#elif defined(__MINGW32__) || defined(__MINGW64__)\n  // MINGW <time.h> provides neither localtime_r nor localtime_s, but uses\n  // Windows' localtime(), which has a thread-local tm buffer.\n  struct tm* tm_ptr = localtime(&seconds);  // NOLINT\n  if (tm_ptr == NULL)\n    return false;\n  *out = *tm_ptr;\n  return true;\n#else\n  return localtime_r(&seconds, out) != NULL;\n#endif\n}\n\n// Converts the given epoch time in milliseconds to a date string in the ISO\n// 8601 format, without the timezone information.\nstd::string FormatEpochTimeInMillisAsIso8601(TimeInMillis ms) {\n  struct tm time_struct;\n  if (!PortableLocaltime(static_cast<time_t>(ms / 1000), &time_struct))\n    return \"\";\n  // YYYY-MM-DDThh:mm:ss\n  return StreamableToString(time_struct.tm_year + 1900) + \"-\" +\n      String::FormatIntWidth2(time_struct.tm_mon + 1) + \"-\" +\n      String::FormatIntWidth2(time_struct.tm_mday) + \"T\" +\n      String::FormatIntWidth2(time_struct.tm_hour) + \":\" +\n      String::FormatIntWidth2(time_struct.tm_min) + \":\" +\n      String::FormatIntWidth2(time_struct.tm_sec);\n}\n\n// Streams an XML CDATA section, escaping invalid CDATA sequences as needed.\nvoid XmlUnitTestResultPrinter::OutputXmlCDataSection(::std::ostream* stream,\n                                                     const char* data) {\n  const char* segment = data;\n  *stream << \"<![CDATA[\";\n  for (;;) {\n    const char* const next_segment = strstr(segment, \"]]>\");\n    if (next_segment != NULL) {\n      stream->write(\n          segment, static_cast<std::streamsize>(next_segment - segment));\n      *stream << \"]]>]]&gt;<![CDATA[\";\n      segment = next_segment + strlen(\"]]>\");\n    } else {\n      *stream << segment;\n      break;\n    }\n  }\n  *stream << \"]]>\";\n}\n\nvoid XmlUnitTestResultPrinter::OutputXmlAttribute(\n    std::ostream* stream,\n    const std::string& element_name,\n    const std::string& name,\n    const std::string& value) {\n  const std::vector<std::string>& allowed_names =\n      GetReservedAttributesForElement(element_name);\n\n  GTEST_CHECK_(std::find(allowed_names.begin(), allowed_names.end(), name) !=\n                   allowed_names.end())\n      << \"Attribute \" << name << \" is not allowed for element <\" << element_name\n      << \">.\";\n\n  *stream << \" \" << name << \"=\\\"\" << EscapeXmlAttribute(value) << \"\\\"\";\n}\n\n// Prints an XML representation of a TestInfo object.\n// TODO(wan): There is also value in printing properties with the plain printer.\nvoid XmlUnitTestResultPrinter::OutputXmlTestInfo(::std::ostream* stream,\n                                                 const char* test_case_name,\n                                                 const TestInfo& test_info) {\n  const TestResult& result = *test_info.result();\n  const std::string kTestcase = \"testcase\";\n\n  *stream << \"    <testcase\";\n  OutputXmlAttribute(stream, kTestcase, \"name\", test_info.name());\n\n  if (test_info.value_param() != NULL) {\n    OutputXmlAttribute(stream, kTestcase, \"value_param\",\n                       test_info.value_param());\n  }\n  if (test_info.type_param() != NULL) {\n    OutputXmlAttribute(stream, kTestcase, \"type_param\", test_info.type_param());\n  }\n\n  OutputXmlAttribute(stream, kTestcase, \"status\",\n                     test_info.should_run() ? \"run\" : \"notrun\");\n  OutputXmlAttribute(stream, kTestcase, \"time\",\n                     FormatTimeInMillisAsSeconds(result.elapsed_time()));\n  OutputXmlAttribute(stream, kTestcase, \"classname\", test_case_name);\n  *stream << TestPropertiesAsXmlAttributes(result);\n\n  int failures = 0;\n  for (int i = 0; i < result.total_part_count(); ++i) {\n    const TestPartResult& part = result.GetTestPartResult(i);\n    if (part.failed()) {\n      if (++failures == 1) {\n        *stream << \">\\n\";\n      }\n      const string location = internal::FormatCompilerIndependentFileLocation(\n          part.file_name(), part.line_number());\n      const string summary = location + \"\\n\" + part.summary();\n      *stream << \"      <failure message=\\\"\"\n              << EscapeXmlAttribute(summary.c_str())\n              << \"\\\" type=\\\"\\\">\";\n      const string detail = location + \"\\n\" + part.message();\n      OutputXmlCDataSection(stream, RemoveInvalidXmlCharacters(detail).c_str());\n      *stream << \"</failure>\\n\";\n    }\n  }\n\n  if (failures == 0)\n    *stream << \" />\\n\";\n  else\n    *stream << \"    </testcase>\\n\";\n}\n\n// Prints an XML representation of a TestCase object\nvoid XmlUnitTestResultPrinter::PrintXmlTestCase(std::ostream* stream,\n                                                const TestCase& test_case) {\n  const std::string kTestsuite = \"testsuite\";\n  *stream << \"  <\" << kTestsuite;\n  OutputXmlAttribute(stream, kTestsuite, \"name\", test_case.name());\n  OutputXmlAttribute(stream, kTestsuite, \"tests\",\n                     StreamableToString(test_case.reportable_test_count()));\n  OutputXmlAttribute(stream, kTestsuite, \"failures\",\n                     StreamableToString(test_case.failed_test_count()));\n  OutputXmlAttribute(\n      stream, kTestsuite, \"disabled\",\n      StreamableToString(test_case.reportable_disabled_test_count()));\n  OutputXmlAttribute(stream, kTestsuite, \"errors\", \"0\");\n  OutputXmlAttribute(stream, kTestsuite, \"time\",\n                     FormatTimeInMillisAsSeconds(test_case.elapsed_time()));\n  *stream << TestPropertiesAsXmlAttributes(test_case.ad_hoc_test_result())\n          << \">\\n\";\n\n  for (int i = 0; i < test_case.total_test_count(); ++i) {\n    if (test_case.GetTestInfo(i)->is_reportable())\n      OutputXmlTestInfo(stream, test_case.name(), *test_case.GetTestInfo(i));\n  }\n  *stream << \"  </\" << kTestsuite << \">\\n\";\n}\n\n// Prints an XML summary of unit_test to output stream out.\nvoid XmlUnitTestResultPrinter::PrintXmlUnitTest(std::ostream* stream,\n                                                const UnitTest& unit_test) {\n  const std::string kTestsuites = \"testsuites\";\n\n  *stream << \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n\";\n  *stream << \"<\" << kTestsuites;\n\n  OutputXmlAttribute(stream, kTestsuites, \"tests\",\n                     StreamableToString(unit_test.reportable_test_count()));\n  OutputXmlAttribute(stream, kTestsuites, \"failures\",\n                     StreamableToString(unit_test.failed_test_count()));\n  OutputXmlAttribute(\n      stream, kTestsuites, \"disabled\",\n      StreamableToString(unit_test.reportable_disabled_test_count()));\n  OutputXmlAttribute(stream, kTestsuites, \"errors\", \"0\");\n  OutputXmlAttribute(\n      stream, kTestsuites, \"timestamp\",\n      FormatEpochTimeInMillisAsIso8601(unit_test.start_timestamp()));\n  OutputXmlAttribute(stream, kTestsuites, \"time\",\n                     FormatTimeInMillisAsSeconds(unit_test.elapsed_time()));\n\n  if (GTEST_FLAG(shuffle)) {\n    OutputXmlAttribute(stream, kTestsuites, \"random_seed\",\n                       StreamableToString(unit_test.random_seed()));\n  }\n\n  *stream << TestPropertiesAsXmlAttributes(unit_test.ad_hoc_test_result());\n\n  OutputXmlAttribute(stream, kTestsuites, \"name\", \"AllTests\");\n  *stream << \">\\n\";\n\n  for (int i = 0; i < unit_test.total_test_case_count(); ++i) {\n    if (unit_test.GetTestCase(i)->reportable_test_count() > 0)\n      PrintXmlTestCase(stream, *unit_test.GetTestCase(i));\n  }\n  *stream << \"</\" << kTestsuites << \">\\n\";\n}\n\n// Produces a string representing the test properties in a result as space\n// delimited XML attributes based on the property key=\"value\" pairs.\nstd::string XmlUnitTestResultPrinter::TestPropertiesAsXmlAttributes(\n    const TestResult& result) {\n  Message attributes;\n  for (int i = 0; i < result.test_property_count(); ++i) {\n    const TestProperty& property = result.GetTestProperty(i);\n    attributes << \" \" << property.key() << \"=\"\n        << \"\\\"\" << EscapeXmlAttribute(property.value()) << \"\\\"\";\n  }\n  return attributes.GetString();\n}\n\n// End XmlUnitTestResultPrinter\n\n#if GTEST_CAN_STREAM_RESULTS_\n\n// Checks if str contains '=', '&', '%' or '\\n' characters. If yes,\n// replaces them by \"%xx\" where xx is their hexadecimal value. For\n// example, replaces \"=\" with \"%3D\".  This algorithm is O(strlen(str))\n// in both time and space -- important as the input str may contain an\n// arbitrarily long test failure message and stack trace.\nstring StreamingListener::UrlEncode(const char* str) {\n  string result;\n  result.reserve(strlen(str) + 1);\n  for (char ch = *str; ch != '\\0'; ch = *++str) {\n    switch (ch) {\n      case '%':\n      case '=':\n      case '&':\n      case '\\n':\n        result.append(\"%\" + String::FormatByte(static_cast<unsigned char>(ch)));\n        break;\n      default:\n        result.push_back(ch);\n        break;\n    }\n  }\n  return result;\n}\n\nvoid StreamingListener::SocketWriter::MakeConnection() {\n  GTEST_CHECK_(sockfd_ == -1)\n      << \"MakeConnection() can't be called when there is already a connection.\";\n\n  addrinfo hints;\n  memset(&hints, 0, sizeof(hints));\n  hints.ai_family = AF_UNSPEC;    // To allow both IPv4 and IPv6 addresses.\n  hints.ai_socktype = SOCK_STREAM;\n  addrinfo* servinfo = NULL;\n\n  // Use the getaddrinfo() to get a linked list of IP addresses for\n  // the given host name.\n  const int error_num = getaddrinfo(\n      host_name_.c_str(), port_num_.c_str(), &hints, &servinfo);\n  if (error_num != 0) {\n    GTEST_LOG_(WARNING) << \"stream_result_to: getaddrinfo() failed: \"\n                        << gai_strerror(error_num);\n  }\n\n  // Loop through all the results and connect to the first we can.\n  for (addrinfo* cur_addr = servinfo; sockfd_ == -1 && cur_addr != NULL;\n       cur_addr = cur_addr->ai_next) {\n    sockfd_ = socket(\n        cur_addr->ai_family, cur_addr->ai_socktype, cur_addr->ai_protocol);\n    if (sockfd_ != -1) {\n      // Connect the client socket to the server socket.\n      if (connect(sockfd_, cur_addr->ai_addr, cur_addr->ai_addrlen) == -1) {\n        close(sockfd_);\n        sockfd_ = -1;\n      }\n    }\n  }\n\n  freeaddrinfo(servinfo);  // all done with this structure\n\n  if (sockfd_ == -1) {\n    GTEST_LOG_(WARNING) << \"stream_result_to: failed to connect to \"\n                        << host_name_ << \":\" << port_num_;\n  }\n}\n\n// End of class Streaming Listener\n#endif  // GTEST_CAN_STREAM_RESULTS__\n\n// Class ScopedTrace\n\n// Pushes the given source file location and message onto a per-thread\n// trace stack maintained by Google Test.\nScopedTrace::ScopedTrace(const char* file, int line, const Message& message)\n    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {\n  TraceInfo trace;\n  trace.file = file;\n  trace.line = line;\n  trace.message = message.GetString();\n\n  UnitTest::GetInstance()->PushGTestTrace(trace);\n}\n\n// Pops the info pushed by the c'tor.\nScopedTrace::~ScopedTrace()\n    GTEST_LOCK_EXCLUDED_(&UnitTest::mutex_) {\n  UnitTest::GetInstance()->PopGTestTrace();\n}\n\n\n// class OsStackTraceGetter\n\nconst char* const OsStackTraceGetterInterface::kElidedFramesMarker =\n    \"... \" GTEST_NAME_ \" internal frames ...\";\n\nstring OsStackTraceGetter::CurrentStackTrace(int /*max_depth*/,\n                                             int /*skip_count*/) {\n  return \"\";\n}\n\nvoid OsStackTraceGetter::UponLeavingGTest() {}\n\n// A helper class that creates the premature-exit file in its\n// constructor and deletes the file in its destructor.\nclass ScopedPrematureExitFile {\n public:\n  explicit ScopedPrematureExitFile(const char* premature_exit_filepath)\n      : premature_exit_filepath_(premature_exit_filepath) {\n    // If a path to the premature-exit file is specified...\n    if (premature_exit_filepath != NULL && *premature_exit_filepath != '\\0') {\n      // create the file with a single \"0\" character in it.  I/O\n      // errors are ignored as there's nothing better we can do and we\n      // don't want to fail the test because of this.\n      FILE* pfile = posix::FOpen(premature_exit_filepath, \"w\");\n      fwrite(\"0\", 1, 1, pfile);\n      fclose(pfile);\n    }\n  }\n\n  ~ScopedPrematureExitFile() {\n    if (premature_exit_filepath_ != NULL && *premature_exit_filepath_ != '\\0') {\n      remove(premature_exit_filepath_);\n    }\n  }\n\n private:\n  const char* const premature_exit_filepath_;\n\n  GTEST_DISALLOW_COPY_AND_ASSIGN_(ScopedPrematureExitFile);\n};\n\n}  // namespace internal\n\n// class TestEventListeners\n\nTestEventListeners::TestEventListeners()\n    : repeater_(new internal::TestEventRepeater()),\n      default_result_printer_(NULL),\n      default_xml_generator_(NULL) {\n}\n\nTestEventListeners::~TestEventListeners() { delete repeater_; }\n\n// Returns the standard listener responsible for the default console\n// output.  Can be removed from the listeners list to shut down default\n// console output.  Note that removing this object from the listener list\n// with Release transfers its ownership to the user.\nvoid TestEventListeners::Append(TestEventListener* listener) {\n  repeater_->Append(listener);\n}\n\n// Removes the given event listener from the list and returns it.  It then\n// becomes the caller's responsibility to delete the listener. Returns\n// NULL if the listener is not found in the list.\nTestEventListener* TestEventListeners::Release(TestEventListener* listener) {\n  if (listener == default_result_printer_)\n    default_result_printer_ = NULL;\n  else if (listener == default_xml_generator_)\n    default_xml_generator_ = NULL;\n  return repeater_->Release(listener);\n}\n\n// Returns repeater that broadcasts the TestEventListener events to all\n// subscribers.\nTestEventListener* TestEventListeners::repeater() { return repeater_; }\n\n// Sets the default_result_printer attribute to the provided listener.\n// The listener is also added to the listener list and previous\n// default_result_printer is removed from it and deleted. The listener can\n// also be NULL in which case it will not be added to the list. Does\n// nothing if the previous and the current listener objects are the same.\nvoid TestEventListeners::SetDefaultResultPrinter(TestEventListener* listener) {\n  if (default_result_printer_ != listener) {\n    // It is an error to pass this method a listener that is already in the\n    // list.\n    delete Release(default_result_printer_);\n    default_result_printer_ = listener;\n    if (listener != NULL)\n      Append(listener);\n  }\n}\n\n// Sets the default_xml_generator attribute to the provided listener.  The\n// listener is also added to the listener list and previous\n// default_xml_generator is removed from it and deleted. The listener can\n// also be NULL in which case it will not be added to the list. Does\n// nothing if the previous and the current listener objects are the same.\nvoid TestEventListeners::SetDefaultXmlGenerator(TestEventListener* listener) {\n  if (default_xml_generator_ != listener) {\n    // It is an error to pass this method a listener that is already in the\n    // list.\n    delete Release(default_xml_generator_);\n    default_xml_generator_ = listener;\n    if (listener != NULL)\n      Append(listener);\n  }\n}\n\n// Controls whether events will be forwarded by the repeater to the\n// listeners in the list.\nbool TestEventListeners::EventForwardingEnabled() const {\n  return repeater_->forwarding_enabled();\n}\n\nvoid TestEventListeners::SuppressEventForwarding() {\n  repeater_->set_forwarding_enabled(false);\n}\n\n// class UnitTest\n\n// Gets the singleton UnitTest object.  The first time this method is\n// called, a UnitTest object is constructed and returned.  Consecutive\n// calls will return the same object.\n//\n// We don't protect this under mutex_ as a user is not supposed to\n// call this before main() starts, from which point on the return\n// value will never change.\nUnitTest* UnitTest::GetInstance() {\n  // When compiled with MSVC 7.1 in optimized mode, destroying the\n  // UnitTest object upon exiting the program messes up the exit code,\n  // causing successful tests to appear failed.  We have to use a\n  // different implementation in this case to bypass the compiler bug.\n  // This implementation makes the compiler happy, at the cost of\n  // leaking the UnitTest object.\n\n  // CodeGear C++Builder insists on a public destructor for the\n  // default implementation.  Use this implementation to keep good OO\n  // design with private destructor.\n\n#if (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)\n  static UnitTest* const instance = new UnitTest;\n  return instance;\n#else\n  static UnitTest instance;\n  return &instance;\n#endif  // (_MSC_VER == 1310 && !defined(_DEBUG)) || defined(__BORLANDC__)\n}\n\n// Gets the number of successful test cases.\nint UnitTest::successful_test_case_count() const {\n  return impl()->successful_test_case_count();\n}\n\n// Gets the number of failed test cases.\nint UnitTest::failed_test_case_count() const {\n  return impl()->failed_test_case_count();\n}\n\n// Gets the number of all test cases.\nint UnitTest::total_test_case_count() const {\n  return impl()->total_test_case_count();\n}\n\n// Gets the number of all test cases that contain at least one test\n// that should run.\nint UnitTest::test_case_to_run_count() const {\n  return impl()->test_case_to_run_count();\n}\n\n// Gets the number of successful tests.\nint UnitTest::successful_test_count() const {\n  return impl()->successful_test_count();\n}\n\n// Gets the number of failed tests.\nint UnitTest::failed_test_count() const { return impl()->failed_test_count(); }\n\n// Gets the number of disabled tests that will be reported in the XML report.\nint UnitTest::reportable_disabled_test_count() const {\n  return impl()->reportable_disabled_test_count();\n}\n\n// Gets the number of disabled tests.\nint UnitTest::disabled_test_count() const {\n  return impl()->disabled_test_count();\n}\n\n// Gets the number of tests to be printed in the XML report.\nint UnitTest::reportable_test_count() const {\n  return impl()->reportable_test_count();\n}\n\n// Gets the number of all tests.\nint UnitTest::total_test_count() const { return impl()->total_test_count(); }\n\n// Gets the number of tests that should run.\nint UnitTest::test_to_run_count() const { return impl()->test_to_run_count(); }\n\n// Gets the time of the test program start, in ms from the start of the\n// UNIX epoch.\ninternal::TimeInMillis UnitTest::start_timestamp() const {\n    return impl()->start_timestamp();\n}\n\n// Gets the elapsed time, in milliseconds.\ninternal::TimeInMillis UnitTest::elapsed_time() const {\n  return impl()->elapsed_time();\n}\n\n// Returns true iff the unit test passed (i.e. all test cases passed).\nbool UnitTest::Passed() const { return impl()->Passed(); }\n\n// Returns true iff the unit test failed (i.e. some test case failed\n// or something outside of all tests failed).\nbool UnitTest::Failed() const { return impl()->Failed(); }\n\n// Gets the i-th test case among all the test cases. i can range from 0 to\n// total_test_case_count() - 1. If i is not in that range, returns NULL.\nconst TestCase* UnitTest::GetTestCase(int i) const {\n  return impl()->GetTestCase(i);\n}\n\n// Returns the TestResult containing information on test failures and\n// properties logged outside of individual test cases.\nconst TestResult& UnitTest::ad_hoc_test_result() const {\n  return *impl()->ad_hoc_test_result();\n}\n\n// Gets the i-th test case among all the test cases. i can range from 0 to\n// total_test_case_count() - 1. If i is not in that range, returns NULL.\nTestCase* UnitTest::GetMutableTestCase(int i) {\n  return impl()->GetMutableTestCase(i);\n}\n\n// Returns the list of event listeners that can be used to track events\n// inside Google Test.\nTestEventListeners& UnitTest::listeners() {\n  return *impl()->listeners();\n}\n\n// Registers and returns a global test environment.  When a test\n// program is run, all global test environments will be set-up in the\n// order they were registered.  After all tests in the program have\n// finished, all global test environments will be torn-down in the\n// *reverse* order they were registered.\n//\n// The UnitTest object takes ownership of the given environment.\n//\n// We don't protect this under mutex_, as we only support calling it\n// from the main thread.\nEnvironment* UnitTest::AddEnvironment(Environment* env) {\n  if (env == NULL) {\n    return NULL;\n  }\n\n  impl_->environments().push_back(env);\n  return env;\n}\n\n// Adds a TestPartResult to the current TestResult object.  All Google Test\n// assertion macros (e.g. ASSERT_TRUE, EXPECT_EQ, etc) eventually call\n// this to report their results.  The user code should use the\n// assertion macros instead of calling this directly.\nvoid UnitTest::AddTestPartResult(\n    TestPartResult::Type result_type,\n    const char* file_name,\n    int line_number,\n    const std::string& message,\n    const std::string& os_stack_trace) GTEST_LOCK_EXCLUDED_(mutex_) {\n  Message msg;\n  msg << message;\n\n  internal::MutexLock lock(&mutex_);\n  if (impl_->gtest_trace_stack().size() > 0) {\n    msg << \"\\n\" << GTEST_NAME_ << \" trace:\";\n\n    for (int i = static_cast<int>(impl_->gtest_trace_stack().size());\n         i > 0; --i) {\n      const internal::TraceInfo& trace = impl_->gtest_trace_stack()[i - 1];\n      msg << \"\\n\" << internal::FormatFileLocation(trace.file, trace.line)\n          << \" \" << trace.message;\n    }\n  }\n\n  if (os_stack_trace.c_str() != NULL && !os_stack_trace.empty()) {\n    msg << internal::kStackTraceMarker << os_stack_trace;\n  }\n\n  const TestPartResult result =\n    TestPartResult(result_type, file_name, line_number,\n                   msg.GetString().c_str());\n  impl_->GetTestPartResultReporterForCurrentThread()->\n      ReportTestPartResult(result);\n\n  if (result_type != TestPartResult::kSuccess) {\n    // gtest_break_on_failure takes precedence over\n    // gtest_throw_on_failure.  This allows a user to set the latter\n    // in the code (perhaps in order to use Google Test assertions\n    // with another testing framework) and specify the former on the\n    // command line for debugging.\n    if (GTEST_FLAG(break_on_failure)) {\n#if GTEST_OS_WINDOWS && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\n      // Using DebugBreak on Windows allows gtest to still break into a debugger\n      // when a failure happens and both the --gtest_break_on_failure and\n      // the --gtest_catch_exceptions flags are specified.\n      DebugBreak();\n#else\n      // Dereference NULL through a volatile pointer to prevent the compiler\n      // from removing. We use this rather than abort() or __builtin_trap() for\n      // portability: Symbian doesn't implement abort() well, and some debuggers\n      // don't correctly trap abort().\n      *static_cast<volatile int*>(NULL) = 1;\n#endif  // GTEST_OS_WINDOWS\n    } else if (GTEST_FLAG(throw_on_failure)) {\n#if GTEST_HAS_EXCEPTIONS\n      throw internal::GoogleTestFailureException(result);\n#else\n      // We cannot call abort() as it generates a pop-up in debug mode\n      // that cannot be suppressed in VC 7.1 or below.\n      exit(1);\n#endif\n    }\n  }\n}\n\n// Adds a TestProperty to the current TestResult object when invoked from\n// inside a test, to current TestCase's ad_hoc_test_result_ when invoked\n// from SetUpTestCase or TearDownTestCase, or to the global property set\n// when invoked elsewhere.  If the result already contains a property with\n// the same key, the value will be updated.\nvoid UnitTest::RecordProperty(const std::string& key,\n                              const std::string& value) {\n  impl_->RecordProperty(TestProperty(key, value));\n}\n\n// Runs all tests in this UnitTest object and prints the result.\n// Returns 0 if successful, or 1 otherwise.\n//\n// We don't protect this under mutex_, as we only support calling it\n// from the main thread.\nint UnitTest::Run() {\n  const bool in_death_test_child_process =\n      internal::GTEST_FLAG(internal_run_death_test).length() > 0;\n\n  // Google Test implements this protocol for catching that a test\n  // program exits before returning control to Google Test:\n  //\n  //   1. Upon start, Google Test creates a file whose absolute path\n  //      is specified by the environment variable\n  //      TEST_PREMATURE_EXIT_FILE.\n  //   2. When Google Test has finished its work, it deletes the file.\n  //\n  // This allows a test runner to set TEST_PREMATURE_EXIT_FILE before\n  // running a Google-Test-based test program and check the existence\n  // of the file at the end of the test execution to see if it has\n  // exited prematurely.\n\n  // If we are in the child process of a death test, don't\n  // create/delete the premature exit file, as doing so is unnecessary\n  // and will confuse the parent process.  Otherwise, create/delete\n  // the file upon entering/leaving this function.  If the program\n  // somehow exits before this function has a chance to return, the\n  // premature-exit file will be left undeleted, causing a test runner\n  // that understands the premature-exit-file protocol to report the\n  // test as having failed.\n  const internal::ScopedPrematureExitFile premature_exit_file(\n      in_death_test_child_process ?\n      NULL : internal::posix::GetEnv(\"TEST_PREMATURE_EXIT_FILE\"));\n\n  // Captures the value of GTEST_FLAG(catch_exceptions).  This value will be\n  // used for the duration of the program.\n  impl()->set_catch_exceptions(GTEST_FLAG(catch_exceptions));\n\n#if GTEST_HAS_SEH\n  // Either the user wants Google Test to catch exceptions thrown by the\n  // tests or this is executing in the context of death test child\n  // process. In either case the user does not want to see pop-up dialogs\n  // about crashes - they are expected.\n  if (impl()->catch_exceptions() || in_death_test_child_process) {\n# if !GTEST_OS_WINDOWS_MOBILE && !GTEST_OS_WINDOWS_PHONE && !GTEST_OS_WINDOWS_RT\n    // SetErrorMode doesn't exist on CE.\n    SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOALIGNMENTFAULTEXCEPT |\n                 SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);\n# endif  // !GTEST_OS_WINDOWS_MOBILE\n\n# if (defined(_MSC_VER) || GTEST_OS_WINDOWS_MINGW) && !GTEST_OS_WINDOWS_MOBILE\n    // Death test children can be terminated with _abort().  On Windows,\n    // _abort() can show a dialog with a warning message.  This forces the\n    // abort message to go to stderr instead.\n    _set_error_mode(_OUT_TO_STDERR);\n# endif\n\n# if _MSC_VER >= 1400 && !GTEST_OS_WINDOWS_MOBILE\n    // In the debug version, Visual Studio pops up a separate dialog\n    // offering a choice to debug the aborted program. We need to suppress\n    // this dialog or it will pop up for every EXPECT/ASSERT_DEATH statement\n    // executed. Google Test will notify the user of any unexpected\n    // failure via stderr.\n    //\n    // VC++ doesn't define _set_abort_behavior() prior to the version 8.0.\n    // Users of prior VC versions shall suffer the agony and pain of\n    // clicking through the countless debug dialogs.\n    // TODO(vladl@google.com): find a way to suppress the abort dialog() in the\n    // debug mode when compiled with VC 7.1 or lower.\n    if (!GTEST_FLAG(break_on_failure))\n      _set_abort_behavior(\n          0x0,                                    // Clear the following flags:\n          _WRITE_ABORT_MSG | _CALL_REPORTFAULT);  // pop-up window, core dump.\n# endif\n  }\n#endif  // GTEST_HAS_SEH\n\n  return internal::HandleExceptionsInMethodIfSupported(\n      impl(),\n      &internal::UnitTestImpl::RunAllTests,\n      \"auxiliary test code (environments or event listeners)\") ? 0 : 1;\n}\n\n// Returns the working directory when the first TEST() or TEST_F() was\n// executed.\nconst char* UnitTest::original_working_dir() const {\n  return impl_->original_working_dir_.c_str();\n}\n\n// Returns the TestCase object for the test that's currently running,\n// or NULL if no test is running.\nconst TestCase* UnitTest::current_test_case() const\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n  internal::MutexLock lock(&mutex_);\n  return impl_->current_test_case();\n}\n\n// Returns the TestInfo object for the test that's currently running,\n// or NULL if no test is running.\nconst TestInfo* UnitTest::current_test_info() const\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n  internal::MutexLock lock(&mutex_);\n  return impl_->current_test_info();\n}\n\n// Returns the random seed used at the start of the current test run.\nint UnitTest::random_seed() const { return impl_->random_seed(); }\n\n#if GTEST_HAS_PARAM_TEST\n// Returns ParameterizedTestCaseRegistry object used to keep track of\n// value-parameterized tests and instantiate and register them.\ninternal::ParameterizedTestCaseRegistry&\n    UnitTest::parameterized_test_registry()\n        GTEST_LOCK_EXCLUDED_(mutex_) {\n  return impl_->parameterized_test_registry();\n}\n#endif  // GTEST_HAS_PARAM_TEST\n\n// Creates an empty UnitTest.\nUnitTest::UnitTest() {\n  impl_ = new internal::UnitTestImpl(this);\n}\n\n// Destructor of UnitTest.\nUnitTest::~UnitTest() {\n  delete impl_;\n}\n\n// Pushes a trace defined by SCOPED_TRACE() on to the per-thread\n// Google Test trace stack.\nvoid UnitTest::PushGTestTrace(const internal::TraceInfo& trace)\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n  internal::MutexLock lock(&mutex_);\n  impl_->gtest_trace_stack().push_back(trace);\n}\n\n// Pops a trace from the per-thread Google Test trace stack.\nvoid UnitTest::PopGTestTrace()\n    GTEST_LOCK_EXCLUDED_(mutex_) {\n  internal::MutexLock lock(&mutex_);\n  impl_->gtest_trace_stack().pop_back();\n}\n\nnamespace internal {\n\nUnitTestImpl::UnitTestImpl(UnitTest* parent)\n    : parent_(parent),\n      GTEST_DISABLE_MSC_WARNINGS_PUSH_(4355 /* using this in initializer */)\n      default_global_test_part_result_reporter_(this),\n      default_per_thread_test_part_result_reporter_(this),\n      GTEST_DISABLE_MSC_WARNINGS_POP_()\n      global_test_part_result_repoter_(\n          &default_global_test_part_result_reporter_),\n      per_thread_test_part_result_reporter_(\n          &default_per_thread_test_part_result_reporter_),\n#if GTEST_HAS_PARAM_TEST\n      parameterized_test_registry_(),\n      parameterized_tests_registered_(false),\n#endif  // GTEST_HAS_PARAM_TEST\n      last_death_test_case_(-1),\n      current_test_case_(NULL),\n      current_test_info_(NULL),\n      ad_hoc_test_result_(),\n      os_stack_trace_getter_(NULL),\n      post_flag_parse_init_performed_(false),\n      random_seed_(0),  // Will be overridden by the flag before first use.\n      random_(0),  // Will be reseeded before first use.\n      start_timestamp_(0),\n      elapsed_time_(0),\n#if GTEST_HAS_DEATH_TEST\n      death_test_factory_(new DefaultDeathTestFactory),\n#endif\n      // Will be overridden by the flag before first use.\n      catch_exceptions_(false) {\n  listeners()->SetDefaultResultPrinter(new PrettyUnitTestResultPrinter);\n}\n\nUnitTestImpl::~UnitTestImpl() {\n  // Deletes every TestCase.\n  ForEach(test_cases_, internal::Delete<TestCase>);\n\n  // Deletes every Environment.\n  ForEach(environments_, internal::Delete<Environment>);\n\n  delete os_stack_trace_getter_;\n}\n\n// Adds a TestProperty to the current TestResult object when invoked in a\n// context of a test, to current test case's ad_hoc_test_result when invoke\n// from SetUpTestCase/TearDownTestCase, or to the global property set\n// otherwise.  If the result already contains a property with the same key,\n// the value will be updated.\nvoid UnitTestImpl::RecordProperty(const TestProperty& test_property) {\n  std::string xml_element;\n  TestResult* test_result;  // TestResult appropriate for property recording.\n\n  if (current_test_info_ != NULL) {\n    xml_element = \"testcase\";\n    test_result = &(current_test_info_->result_);\n  } else if (current_test_case_ != NULL) {\n    xml_element = \"testsuite\";\n    test_result = &(current_test_case_->ad_hoc_test_result_);\n  } else {\n    xml_element = \"testsuites\";\n    test_result = &ad_hoc_test_result_;\n  }\n  test_result->RecordProperty(xml_element, test_property);\n}\n\n#if GTEST_HAS_DEATH_TEST\n// Disables event forwarding if the control is currently in a death test\n// subprocess. Must not be called before InitGoogleTest.\nvoid UnitTestImpl::SuppressTestEventsIfInSubprocess() {\n  if (internal_run_death_test_flag_.get() != NULL)\n    listeners()->SuppressEventForwarding();\n}\n#endif  // GTEST_HAS_DEATH_TEST\n\n// Initializes event listeners performing XML output as specified by\n// UnitTestOptions. Must not be called before InitGoogleTest.\nvoid UnitTestImpl::ConfigureXmlOutput() {\n  const std::string& output_format = UnitTestOptions::GetOutputFormat();\n  if (output_format == \"xml\") {\n    listeners()->SetDefaultXmlGenerator(new XmlUnitTestResultPrinter(\n        UnitTestOptions::GetAbsolutePathToOutputFile().c_str()));\n  } else if (output_format != \"\") {\n    printf(\"WARNING: unrecognized output format \\\"%s\\\" ignored.\\n\",\n           output_format.c_str());\n    fflush(stdout);\n  }\n}\n\n#if GTEST_CAN_STREAM_RESULTS_\n// Initializes event listeners for streaming test results in string form.\n// Must not be called before InitGoogleTest.\nvoid UnitTestImpl::ConfigureStreamingOutput() {\n  const std::string& target = GTEST_FLAG(stream_result_to);\n  if (!target.empty()) {\n    const size_t pos = target.find(':');\n    if (pos != std::string::npos) {\n      listeners()->Append(new StreamingListener(target.substr(0, pos),\n                                                target.substr(pos+1)));\n    } else {\n      printf(\"WARNING: unrecognized streaming target \\\"%s\\\" ignored.\\n\",\n             target.c_str());\n      fflush(stdout);\n    }\n  }\n}\n#endif  // GTEST_CAN_STREAM_RESULTS_\n\n// Performs initialization dependent upon flag values obtained in\n// ParseGoogleTestFlagsOnly.  Is called from InitGoogleTest after the call to\n// ParseGoogleTestFlagsOnly.  In case a user neglects to call InitGoogleTest\n// this function is also called from RunAllTests.  Since this function can be\n// called more than once, it has to be idempotent.\nvoid UnitTestImpl::PostFlagParsingInit() {\n  // Ensures that this function does not execute more than once.\n  if (!post_flag_parse_init_performed_) {\n    post_flag_parse_init_performed_ = true;\n\n#if defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)\n    // Register to send notifications about key process state changes.\n    listeners()->Append(new GTEST_CUSTOM_TEST_EVENT_LISTENER_());\n#endif  // defined(GTEST_CUSTOM_TEST_EVENT_LISTENER_)\n\n#if GTEST_HAS_DEATH_TEST\n    InitDeathTestSubprocessControlInfo();\n    SuppressTestEventsIfInSubprocess();\n#endif  // GTEST_HAS_DEATH_TEST\n\n    // Registers parameterized tests. This makes parameterized tests\n    // available to the UnitTest reflection API without running\n    // RUN_ALL_TESTS.\n    RegisterParameterizedTests();\n\n    // Configures listeners for XML output. This makes it possible for users\n    // to shut down the default XML output before invoking RUN_ALL_TESTS.\n    ConfigureXmlOutput();\n\n#if GTEST_CAN_STREAM_RESULTS_\n    // Configures listeners for streaming test results to the specified server.\n    ConfigureStreamingOutput();\n#endif  // GTEST_CAN_STREAM_RESULTS_\n  }\n}\n\n// A predicate that checks the name of a TestCase against a known\n// value.\n//\n// This is used for implementation of the UnitTest class only.  We put\n// it in the anonymous namespace to prevent polluting the outer\n// namespace.\n//\n// TestCaseNameIs is copyable.\nclass TestCaseNameIs {\n public:\n  // Constructor.\n  explicit TestCaseNameIs(const std::string& name)\n      : name_(name) {}\n\n  // Returns true iff the name of test_case matches name_.\n  bool operator()(const TestCase* test_case) const {\n    return test_case != NULL && strcmp(test_case->name(), name_.c_str()) == 0;\n  }\n\n private:\n  std::string name_;\n};\n\n// Finds and returns a TestCase with the given name.  If one doesn't\n// exist, creates one and returns it.  It's the CALLER'S\n// RESPONSIBILITY to ensure that this function is only called WHEN THE\n// TESTS ARE NOT SHUFFLED.\n//\n// Arguments:\n//\n//   test_case_name: name of the test case\n//   type_param:     the name of the test case's type parameter, or NULL if\n//                   this is not a typed or a type-parameterized test case.\n//   set_up_tc:      pointer to the function that sets up the test case\n//   tear_down_tc:   pointer to the function that tears down the test case\nTestCase* UnitTestImpl::GetTestCase(const char* test_case_name,\n                                    const char* type_param,\n                                    Test::SetUpTestCaseFunc set_up_tc,\n                                    Test::TearDownTestCaseFunc tear_down_tc) {\n  // Can we find a TestCase with the given name?\n  const std::vector<TestCase*>::const_iterator test_case =\n      std::find_if(test_cases_.begin(), test_cases_.end(),\n                   TestCaseNameIs(test_case_name));\n\n  if (test_case != test_cases_.end())\n    return *test_case;\n\n  // No.  Let's create one.\n  TestCase* const new_test_case =\n      new TestCase(test_case_name, type_param, set_up_tc, tear_down_tc);\n\n  // Is this a death test case?\n  if (internal::UnitTestOptions::MatchesFilter(test_case_name,\n                                               kDeathTestCaseFilter)) {\n    // Yes.  Inserts the test case after the last death test case\n    // defined so far.  This only works when the test cases haven't\n    // been shuffled.  Otherwise we may end up running a death test\n    // after a non-death test.\n    ++last_death_test_case_;\n    test_cases_.insert(test_cases_.begin() + last_death_test_case_,\n                       new_test_case);\n  } else {\n    // No.  Appends to the end of the list.\n    test_cases_.push_back(new_test_case);\n  }\n\n  test_case_indices_.push_back(static_cast<int>(test_case_indices_.size()));\n  return new_test_case;\n}\n\n// Helpers for setting up / tearing down the given environment.  They\n// are for use in the ForEach() function.\nstatic void SetUpEnvironment(Environment* env) { env->SetUp(); }\nstatic void TearDownEnvironment(Environment* env) { env->TearDown(); }\n\n// Runs all tests in this UnitTest object, prints the result, and\n// returns true if all tests are successful.  If any exception is\n// thrown during a test, the test is considered to be failed, but the\n// rest of the tests will still be run.\n//\n// When parameterized tests are enabled, it expands and registers\n// parameterized tests first in RegisterParameterizedTests().\n// All other functions called from RunAllTests() may safely assume that\n// parameterized tests are ready to be counted and run.\nbool UnitTestImpl::RunAllTests() {\n  // Makes sure InitGoogleTest() was called.\n  if (!GTestIsInitialized()) {\n    printf(\"%s\",\n           \"\\nThis test program did NOT call ::testing::InitGoogleTest \"\n           \"before calling RUN_ALL_TESTS().  Please fix it.\\n\");\n    return false;\n  }\n\n  // Do not run any test if the --help flag was specified.\n  if (g_help_flag)\n    return true;\n\n  // Repeats the call to the post-flag parsing initialization in case the\n  // user didn't call InitGoogleTest.\n  PostFlagParsingInit();\n\n  // Even if sharding is not on, test runners may want to use the\n  // GTEST_SHARD_STATUS_FILE to query whether the test supports the sharding\n  // protocol.\n  internal::WriteToShardStatusFileIfNeeded();\n\n  // True iff we are in a subprocess for running a thread-safe-style\n  // death test.\n  bool in_subprocess_for_death_test = false;\n\n#if GTEST_HAS_DEATH_TEST\n  in_subprocess_for_death_test = (internal_run_death_test_flag_.get() != NULL);\n# if defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)\n  if (in_subprocess_for_death_test) {\n    GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_();\n  }\n# endif  // defined(GTEST_EXTRA_DEATH_TEST_CHILD_SETUP_)\n#endif  // GTEST_HAS_DEATH_TEST\n\n  const bool should_shard = ShouldShard(kTestTotalShards, kTestShardIndex,\n                                        in_subprocess_for_death_test);\n\n  // Compares the full test names with the filter to decide which\n  // tests to run.\n  const bool has_tests_to_run = FilterTests(should_shard\n                                              ? HONOR_SHARDING_PROTOCOL\n                                              : IGNORE_SHARDING_PROTOCOL) > 0;\n\n  // Lists the tests and exits if the --gtest_list_tests flag was specified.\n  if (GTEST_FLAG(list_tests)) {\n    // This must be called *after* FilterTests() has been called.\n    ListTestsMatchingFilter();\n    return true;\n  }\n\n  random_seed_ = GTEST_FLAG(shuffle) ?\n      GetRandomSeedFromFlag(GTEST_FLAG(random_seed)) : 0;\n\n  // True iff at least one test has failed.\n  bool failed = false;\n\n  TestEventListener* repeater = listeners()->repeater();\n\n  start_timestamp_ = GetTimeInMillis();\n  repeater->OnTestProgramStart(*parent_);\n\n  // How many times to repeat the tests?  We don't want to repeat them\n  // when we are inside the subprocess of a death test.\n  const int repeat = in_subprocess_for_death_test ? 1 : GTEST_FLAG(repeat);\n  // Repeats forever if the repeat count is negative.\n  const bool forever = repeat < 0;\n  for (int i = 0; forever || i != repeat; i++) {\n    // We want to preserve failures generated by ad-hoc test\n    // assertions executed before RUN_ALL_TESTS().\n    ClearNonAdHocTestResult();\n\n    const TimeInMillis start = GetTimeInMillis();\n\n    // Shuffles test cases and tests if requested.\n    if (has_tests_to_run && GTEST_FLAG(shuffle)) {\n      random()->Reseed(random_seed_);\n      // This should be done before calling OnTestIterationStart(),\n      // such that a test event listener can see the actual test order\n      // in the event.\n      ShuffleTests();\n    }\n\n    // Tells the unit test event listeners that the tests are about to start.\n    repeater->OnTestIterationStart(*parent_, i);\n\n    // Runs each test case if there is at least one test to run.\n    if (has_tests_to_run) {\n      // Sets up all environments beforehand.\n      repeater->OnEnvironmentsSetUpStart(*parent_);\n      ForEach(environments_, SetUpEnvironment);\n      repeater->OnEnvironmentsSetUpEnd(*parent_);\n\n      // Runs the tests only if there was no fatal failure during global\n      // set-up.\n      if (!Test::HasFatalFailure()) {\n        for (int test_index = 0; test_index < total_test_case_count();\n             test_index++) {\n          GetMutableTestCase(test_index)->Run();\n        }\n      }\n\n      // Tears down all environments in reverse order afterwards.\n      repeater->OnEnvironmentsTearDownStart(*parent_);\n      std::for_each(environments_.rbegin(), environments_.rend(),\n                    TearDownEnvironment);\n      repeater->OnEnvironmentsTearDownEnd(*parent_);\n    }\n\n    elapsed_time_ = GetTimeInMillis() - start;\n\n    // Tells the unit test event listener that the tests have just finished.\n    repeater->OnTestIterationEnd(*parent_, i);\n\n    // Gets the result and clears it.\n    if (!Passed()) {\n      failed = true;\n    }\n\n    // Restores the original test order after the iteration.  This\n    // allows the user to quickly repro a failure that happens in the\n    // N-th iteration without repeating the first (N - 1) iterations.\n    // This is not enclosed in \"if (GTEST_FLAG(shuffle)) { ... }\", in\n    // case the user somehow changes the value of the flag somewhere\n    // (it's always safe to unshuffle the tests).\n    UnshuffleTests();\n\n    if (GTEST_FLAG(shuffle)) {\n      // Picks a new random seed for each iteration.\n      random_seed_ = GetNextRandomSeed(random_seed_);\n    }\n  }\n\n  repeater->OnTestProgramEnd(*parent_);\n\n  return !failed;\n}\n\n// Reads the GTEST_SHARD_STATUS_FILE environment variable, and creates the file\n// if the variable is present. If a file already exists at this location, this\n// function will write over it. If the variable is present, but the file cannot\n// be created, prints an error and exits.\nvoid WriteToShardStatusFileIfNeeded() {\n  const char* const test_shard_file = posix::GetEnv(kTestShardStatusFile);\n  if (test_shard_file != NULL) {\n    FILE* const file = posix::FOpen(test_shard_file, \"w\");\n    if (file == NULL) {\n      ColoredPrintf(COLOR_RED,\n                    \"Could not write to the test shard status file \\\"%s\\\" \"\n                    \"specified by the %s environment variable.\\n\",\n                    test_shard_file, kTestShardStatusFile);\n      fflush(stdout);\n      exit(EXIT_FAILURE);\n    }\n    fclose(file);\n  }\n}\n\n// Checks whether sharding is enabled by examining the relevant\n// environment variable values. If the variables are present,\n// but inconsistent (i.e., shard_index >= total_shards), prints\n// an error and exits. If in_subprocess_for_death_test, sharding is\n// disabled because it must only be applied to the original test\n// process. Otherwise, we could filter out death tests we intended to execute.\nbool ShouldShard(const char* total_shards_env,\n                 const char* shard_index_env,\n                 bool in_subprocess_for_death_test) {\n  if (in_subprocess_for_death_test) {\n    return false;\n  }\n\n  const Int32 total_shards = Int32FromEnvOrDie(total_shards_env, -1);\n  const Int32 shard_index = Int32FromEnvOrDie(shard_index_env, -1);\n\n  if (total_shards == -1 && shard_index == -1) {\n    return false;\n  } else if (total_shards == -1 && shard_index != -1) {\n    const Message msg = Message()\n      << \"Invalid environment variables: you have \"\n      << kTestShardIndex << \" = \" << shard_index\n      << \", but have left \" << kTestTotalShards << \" unset.\\n\";\n    ColoredPrintf(COLOR_RED, msg.GetString().c_str());\n    fflush(stdout);\n    exit(EXIT_FAILURE);\n  } else if (total_shards != -1 && shard_index == -1) {\n    const Message msg = Message()\n      << \"Invalid environment variables: you have \"\n      << kTestTotalShards << \" = \" << total_shards\n      << \", but have left \" << kTestShardIndex << \" unset.\\n\";\n    ColoredPrintf(COLOR_RED, msg.GetString().c_str());\n    fflush(stdout);\n    exit(EXIT_FAILURE);\n  } else if (shard_index < 0 || shard_index >= total_shards) {\n    const Message msg = Message()\n      << \"Invalid environment variables: we require 0 <= \"\n      << kTestShardIndex << \" < \" << kTestTotalShards\n      << \", but you have \" << kTestShardIndex << \"=\" << shard_index\n      << \", \" << kTestTotalShards << \"=\" << total_shards << \".\\n\";\n    ColoredPrintf(COLOR_RED, msg.GetString().c_str());\n    fflush(stdout);\n    exit(EXIT_FAILURE);\n  }\n\n  return total_shards > 1;\n}\n\n// Parses the environment variable var as an Int32. If it is unset,\n// returns default_val. If it is not an Int32, prints an error\n// and aborts.\nInt32 Int32FromEnvOrDie(const char* var, Int32 default_val) {\n  const char* str_val = posix::GetEnv(var);\n  if (str_val == NULL) {\n    return default_val;\n  }\n\n  Int32 result;\n  if (!ParseInt32(Message() << \"The value of environment variable \" << var,\n                  str_val, &result)) {\n    exit(EXIT_FAILURE);\n  }\n  return result;\n}\n\n// Given the total number of shards, the shard index, and the test id,\n// returns true iff the test should be run on this shard. The test id is\n// some arbitrary but unique non-negative integer assigned to each test\n// method. Assumes that 0 <= shard_index < total_shards.\nbool ShouldRunTestOnShard(int total_shards, int shard_index, int test_id) {\n  return (test_id % total_shards) == shard_index;\n}\n\n// Compares the name of each test with the user-specified filter to\n// decide whether the test should be run, then records the result in\n// each TestCase and TestInfo object.\n// If shard_tests == true, further filters tests based on sharding\n// variables in the environment - see\n// http://code.google.com/p/googletest/wiki/GoogleTestAdvancedGuide.\n// Returns the number of tests that should run.\nint UnitTestImpl::FilterTests(ReactionToSharding shard_tests) {\n  const Int32 total_shards = shard_tests == HONOR_SHARDING_PROTOCOL ?\n      Int32FromEnvOrDie(kTestTotalShards, -1) : -1;\n  const Int32 shard_index = shard_tests == HONOR_SHARDING_PROTOCOL ?\n      Int32FromEnvOrDie(kTestShardIndex, -1) : -1;\n\n  // num_runnable_tests are the number of tests that will\n  // run across all shards (i.e., match filter and are not disabled).\n  // num_selected_tests are the number of tests to be run on\n  // this shard.\n  int num_runnable_tests = 0;\n  int num_selected_tests = 0;\n  for (size_t i = 0; i < test_cases_.size(); i++) {\n    TestCase* const test_case = test_cases_[i];\n    const std::string &test_case_name = test_case->name();\n    test_case->set_should_run(false);\n\n    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {\n      TestInfo* const test_info = test_case->test_info_list()[j];\n      const std::string test_name(test_info->name());\n      // A test is disabled if test case name or test name matches\n      // kDisableTestFilter.\n      const bool is_disabled =\n          internal::UnitTestOptions::MatchesFilter(test_case_name,\n                                                   kDisableTestFilter) ||\n          internal::UnitTestOptions::MatchesFilter(test_name,\n                                                   kDisableTestFilter);\n      test_info->is_disabled_ = is_disabled;\n\n      const bool matches_filter =\n          internal::UnitTestOptions::FilterMatchesTest(test_case_name,\n                                                       test_name);\n      test_info->matches_filter_ = matches_filter;\n\n      const bool is_runnable =\n          (GTEST_FLAG(also_run_disabled_tests) || !is_disabled) &&\n          matches_filter;\n\n      const bool is_selected = is_runnable &&\n          (shard_tests == IGNORE_SHARDING_PROTOCOL ||\n           ShouldRunTestOnShard(total_shards, shard_index,\n                                num_runnable_tests));\n\n      num_runnable_tests += is_runnable;\n      num_selected_tests += is_selected;\n\n      test_info->should_run_ = is_selected;\n      test_case->set_should_run(test_case->should_run() || is_selected);\n    }\n  }\n  return num_selected_tests;\n}\n\n// Prints the given C-string on a single line by replacing all '\\n'\n// characters with string \"\\\\n\".  If the output takes more than\n// max_length characters, only prints the first max_length characters\n// and \"...\".\nstatic void PrintOnOneLine(const char* str, int max_length) {\n  if (str != NULL) {\n    for (int i = 0; *str != '\\0'; ++str) {\n      if (i >= max_length) {\n        printf(\"...\");\n        break;\n      }\n      if (*str == '\\n') {\n        printf(\"\\\\n\");\n        i += 2;\n      } else {\n        printf(\"%c\", *str);\n        ++i;\n      }\n    }\n  }\n}\n\n// Prints the names of the tests matching the user-specified filter flag.\nvoid UnitTestImpl::ListTestsMatchingFilter() {\n  // Print at most this many characters for each type/value parameter.\n  const int kMaxParamLength = 250;\n\n  for (size_t i = 0; i < test_cases_.size(); i++) {\n    const TestCase* const test_case = test_cases_[i];\n    bool printed_test_case_name = false;\n\n    for (size_t j = 0; j < test_case->test_info_list().size(); j++) {\n      const TestInfo* const test_info =\n          test_case->test_info_list()[j];\n      if (test_info->matches_filter_) {\n        if (!printed_test_case_name) {\n          printed_test_case_name = true;\n          printf(\"%s.\", test_case->name());\n          if (test_case->type_param() != NULL) {\n            printf(\"  # %s = \", kTypeParamLabel);\n            // We print the type parameter on a single line to make\n            // the output easy to parse by a program.\n            PrintOnOneLine(test_case->type_param(), kMaxParamLength);\n          }\n          printf(\"\\n\");\n        }\n        printf(\"  %s\", test_info->name());\n        if (test_info->value_param() != NULL) {\n          printf(\"  # %s = \", kValueParamLabel);\n          // We print the value parameter on a single line to make the\n          // output easy to parse by a program.\n          PrintOnOneLine(test_info->value_param(), kMaxParamLength);\n        }\n        printf(\"\\n\");\n      }\n    }\n  }\n  fflush(stdout);\n}\n\n// Sets the OS stack trace getter.\n//\n// Does nothing if the input and the current OS stack trace getter are\n// the same; otherwise, deletes the old getter and makes the input the\n// current getter.\nvoid UnitTestImpl::set_os_stack_trace_getter(\n    OsStackTraceGetterInterface* getter) {\n  if (os_stack_trace_getter_ != getter) {\n    delete os_stack_trace_getter_;\n    os_stack_trace_getter_ = getter;\n  }\n}\n\n// Returns the current OS stack trace getter if it is not NULL;\n// otherwise, creates an OsStackTraceGetter, makes it the current\n// getter, and returns it.\nOsStackTraceGetterInterface* UnitTestImpl::os_stack_trace_getter() {\n  if (os_stack_trace_getter_ == NULL) {\n#ifdef GTEST_OS_STACK_TRACE_GETTER_\n    os_stack_trace_getter_ = new GTEST_OS_STACK_TRACE_GETTER_;\n#else\n    os_stack_trace_getter_ = new OsStackTraceGetter;\n#endif  // GTEST_OS_STACK_TRACE_GETTER_\n  }\n\n  return os_stack_trace_getter_;\n}\n\n// Returns the TestResult for the test that's currently running, or\n// the TestResult for the ad hoc test if no test is running.\nTestResult* UnitTestImpl::current_test_result() {\n  return current_test_info_ ?\n      &(current_test_info_->result_) : &ad_hoc_test_result_;\n}\n\n// Shuffles all test cases, and the tests within each test case,\n// making sure that death tests are still run first.\nvoid UnitTestImpl::ShuffleTests() {\n  // Shuffles the death test cases.\n  ShuffleRange(random(), 0, last_death_test_case_ + 1, &test_case_indices_);\n\n  // Shuffles the non-death test cases.\n  ShuffleRange(random(), last_death_test_case_ + 1,\n               static_cast<int>(test_cases_.size()), &test_case_indices_);\n\n  // Shuffles the tests inside each test case.\n  for (size_t i = 0; i < test_cases_.size(); i++) {\n    test_cases_[i]->ShuffleTests(random());\n  }\n}\n\n// Restores the test cases and tests to their order before the first shuffle.\nvoid UnitTestImpl::UnshuffleTests() {\n  for (size_t i = 0; i < test_cases_.size(); i++) {\n    // Unshuffles the tests in each test case.\n    test_cases_[i]->UnshuffleTests();\n    // Resets the index of each test case.\n    test_case_indices_[i] = static_cast<int>(i);\n  }\n}\n\n// Returns the current OS stack trace as an std::string.\n//\n// The maximum number of stack frames to be included is specified by\n// the gtest_stack_trace_depth flag.  The skip_count parameter\n// specifies the number of top frames to be skipped, which doesn't\n// count against the number of frames to be included.\n//\n// For example, if Foo() calls Bar(), which in turn calls\n// GetCurrentOsStackTraceExceptTop(..., 1), Foo() will be included in\n// the trace but Bar() and GetCurrentOsStackTraceExceptTop() won't.\nstd::string GetCurrentOsStackTraceExceptTop(UnitTest* /*unit_test*/,\n                                            int skip_count) {\n  // We pass skip_count + 1 to skip this wrapper function in addition\n  // to what the user really wants to skip.\n  return GetUnitTestImpl()->CurrentOsStackTraceExceptTop(skip_count + 1);\n}\n\n// Used by the GTEST_SUPPRESS_UNREACHABLE_CODE_WARNING_BELOW_ macro to\n// suppress unreachable code warnings.\nnamespace {\nclass ClassUniqueToAlwaysTrue {};\n}\n\nbool IsTrue(bool condition) { return condition; }\n\nbool AlwaysTrue() {\n#if GTEST_HAS_EXCEPTIONS\n  // This condition is always false so AlwaysTrue() never actually throws,\n  // but it makes the compiler think that it may throw.\n  if (IsTrue(false))\n    throw ClassUniqueToAlwaysTrue();\n#endif  // GTEST_HAS_EXCEPTIONS\n  return true;\n}\n\n// If *pstr starts with the given prefix, modifies *pstr to be right\n// past the prefix and returns true; otherwise leaves *pstr unchanged\n// and returns false.  None of pstr, *pstr, and prefix can be NULL.\nbool SkipPrefix(const char* prefix, const char** pstr) {\n  const size_t prefix_len = strlen(prefix);\n  if (strncmp(*pstr, prefix, prefix_len) == 0) {\n    *pstr += prefix_len;\n    return true;\n  }\n  return false;\n}\n\n// Parses a string as a command line flag.  The string should have\n// the format \"--flag=value\".  When def_optional is true, the \"=value\"\n// part can be omitted.\n//\n// Returns the value of the flag, or NULL if the parsing failed.\nconst char* ParseFlagValue(const char* str,\n                           const char* flag,\n                           bool def_optional) {\n  // str and flag must not be NULL.\n  if (str == NULL || flag == NULL) return NULL;\n\n  // The flag must start with \"--\" followed by GTEST_FLAG_PREFIX_.\n  const std::string flag_str = std::string(\"--\") + GTEST_FLAG_PREFIX_ + flag;\n  const size_t flag_len = flag_str.length();\n  if (strncmp(str, flag_str.c_str(), flag_len) != 0) return NULL;\n\n  // Skips the flag name.\n  const char* flag_end = str + flag_len;\n\n  // When def_optional is true, it's OK to not have a \"=value\" part.\n  if (def_optional && (flag_end[0] == '\\0')) {\n    return flag_end;\n  }\n\n  // If def_optional is true and there are more characters after the\n  // flag name, or if def_optional is false, there must be a '=' after\n  // the flag name.\n  if (flag_end[0] != '=') return NULL;\n\n  // Returns the string after \"=\".\n  return flag_end + 1;\n}\n\n// Parses a string for a bool flag, in the form of either\n// \"--flag=value\" or \"--flag\".\n//\n// In the former case, the value is taken as true as long as it does\n// not start with '0', 'f', or 'F'.\n//\n// In the latter case, the value is taken as true.\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nbool ParseBoolFlag(const char* str, const char* flag, bool* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseFlagValue(str, flag, true);\n\n  // Aborts if the parsing failed.\n  if (value_str == NULL) return false;\n\n  // Converts the string value to a bool.\n  *value = !(*value_str == '0' || *value_str == 'f' || *value_str == 'F');\n  return true;\n}\n\n// Parses a string for an Int32 flag, in the form of\n// \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nbool ParseInt32Flag(const char* str, const char* flag, Int32* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseFlagValue(str, flag, false);\n\n  // Aborts if the parsing failed.\n  if (value_str == NULL) return false;\n\n  // Sets *value to the value of the flag.\n  return ParseInt32(Message() << \"The value of flag --\" << flag,\n                    value_str, value);\n}\n\n// Parses a string for a string flag, in the form of\n// \"--flag=value\".\n//\n// On success, stores the value of the flag in *value, and returns\n// true.  On failure, returns false without changing *value.\nbool ParseStringFlag(const char* str, const char* flag, std::string* value) {\n  // Gets the value of the flag as a string.\n  const char* const value_str = ParseFlagValue(str, flag, false);\n\n  // Aborts if the parsing failed.\n  if (value_str == NULL) return false;\n\n  // Sets *value to the value of the flag.\n  *value = value_str;\n  return true;\n}\n\n// Determines whether a string has a prefix that Google Test uses for its\n// flags, i.e., starts with GTEST_FLAG_PREFIX_ or GTEST_FLAG_PREFIX_DASH_.\n// If Google Test detects that a command line flag has its prefix but is not\n// recognized, it will print its help message. Flags starting with\n// GTEST_INTERNAL_PREFIX_ followed by \"internal_\" are considered Google Test\n// internal flags and do not trigger the help message.\nstatic bool HasGoogleTestFlagPrefix(const char* str) {\n  return (SkipPrefix(\"--\", &str) ||\n          SkipPrefix(\"-\", &str) ||\n          SkipPrefix(\"/\", &str)) &&\n         !SkipPrefix(GTEST_FLAG_PREFIX_ \"internal_\", &str) &&\n         (SkipPrefix(GTEST_FLAG_PREFIX_, &str) ||\n          SkipPrefix(GTEST_FLAG_PREFIX_DASH_, &str));\n}\n\n// Prints a string containing code-encoded text.  The following escape\n// sequences can be used in the string to control the text color:\n//\n//   @@    prints a single '@' character.\n//   @R    changes the color to red.\n//   @G    changes the color to green.\n//   @Y    changes the color to yellow.\n//   @D    changes to the default terminal text color.\n//\n// TODO(wan@google.com): Write tests for this once we add stdout\n// capturing to Google Test.\nstatic void PrintColorEncoded(const char* str) {\n  GTestColor color = COLOR_DEFAULT;  // The current color.\n\n  // Conceptually, we split the string into segments divided by escape\n  // sequences.  Then we print one segment at a time.  At the end of\n  // each iteration, the str pointer advances to the beginning of the\n  // next segment.\n  for (;;) {\n    const char* p = strchr(str, '@');\n    if (p == NULL) {\n      ColoredPrintf(color, \"%s\", str);\n      return;\n    }\n\n    ColoredPrintf(color, \"%s\", std::string(str, p).c_str());\n\n    const char ch = p[1];\n    str = p + 2;\n    if (ch == '@') {\n      ColoredPrintf(color, \"@\");\n    } else if (ch == 'D') {\n      color = COLOR_DEFAULT;\n    } else if (ch == 'R') {\n      color = COLOR_RED;\n    } else if (ch == 'G') {\n      color = COLOR_GREEN;\n    } else if (ch == 'Y') {\n      color = COLOR_YELLOW;\n    } else {\n      --str;\n    }\n  }\n}\n\nstatic const char kColorEncodedHelpMessage[] =\n\"This program contains tests written using \" GTEST_NAME_ \". You can use the\\n\"\n\"following command line flags to control its behavior:\\n\"\n\"\\n\"\n\"Test Selection:\\n\"\n\"  @G--\" GTEST_FLAG_PREFIX_ \"list_tests@D\\n\"\n\"      List the names of all tests instead of running them. The name of\\n\"\n\"      TEST(Foo, Bar) is \\\"Foo.Bar\\\".\\n\"\n\"  @G--\" GTEST_FLAG_PREFIX_ \"filter=@YPOSTIVE_PATTERNS\"\n    \"[@G-@YNEGATIVE_PATTERNS]@D\\n\"\n\"      Run only the tests whose name matches one of the positive patterns but\\n\"\n\"      none of the negative patterns. '?' matches any single character; '*'\\n\"\n\"      matches any substring; ':' separates two patterns.\\n\"\n\"  @G--\" GTEST_FLAG_PREFIX_ \"also_run_disabled_tests@D\\n\"\n\"      Run all disabled tests too.\\n\"\n\"\\n\"\n\"Test Execution:\\n\"\n\"  @G--\" GTEST_FLAG_PREFIX_ \"repeat=@Y[COUNT]@D\\n\"\n\"      Run the tests repeatedly; use a negative count to repeat forever.\\n\"\n\"  @G--\" GTEST_FLAG_PREFIX_ \"shuffle@D\\n\"\n\"      Randomize tests' orders on every iteration.\\n\"\n\"  @G--\" GTEST_FLAG_PREFIX_ \"random_seed=@Y[NUMBER]@D\\n\"\n\"      Random number seed to use for shuffling test orders (between 1 and\\n\"\n\"      99999, or 0 to use a seed based on the current time).\\n\"\n\"\\n\"\n\"Test Output:\\n\"\n\"  @G--\" GTEST_FLAG_PREFIX_ \"color=@Y(@Gyes@Y|@Gno@Y|@Gauto@Y)@D\\n\"\n\"      Enable/disable colored output. The default is @Gauto@D.\\n\"\n\"  -@G-\" GTEST_FLAG_PREFIX_ \"print_time=0@D\\n\"\n\"      Don't print the elapsed time of each test.\\n\"\n\"  @G--\" GTEST_FLAG_PREFIX_ \"output=xml@Y[@G:@YDIRECTORY_PATH@G\"\n    GTEST_PATH_SEP_ \"@Y|@G:@YFILE_PATH]@D\\n\"\n\"      Generate an XML report in the given directory or with the given file\\n\"\n\"      name. @YFILE_PATH@D defaults to @Gtest_details.xml@D.\\n\"\n#if GTEST_CAN_STREAM_RESULTS_\n\"  @G--\" GTEST_FLAG_PREFIX_ \"stream_result_to=@YHOST@G:@YPORT@D\\n\"\n\"      Stream test results to the given server.\\n\"\n#endif  // GTEST_CAN_STREAM_RESULTS_\n\"\\n\"\n\"Assertion Behavior:\\n\"\n#if GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS\n\"  @G--\" GTEST_FLAG_PREFIX_ \"death_test_style=@Y(@Gfast@Y|@Gthreadsafe@Y)@D\\n\"\n\"      Set the default death test style.\\n\"\n#endif  // GTEST_HAS_DEATH_TEST && !GTEST_OS_WINDOWS\n\"  @G--\" GTEST_FLAG_PREFIX_ \"break_on_failure@D\\n\"\n\"      Turn assertion failures into debugger break-points.\\n\"\n\"  @G--\" GTEST_FLAG_PREFIX_ \"throw_on_failure@D\\n\"\n\"      Turn assertion failures into C++ exceptions.\\n\"\n\"  @G--\" GTEST_FLAG_PREFIX_ \"catch_exceptions=0@D\\n\"\n\"      Do not report exceptions as test failures. Instead, allow them\\n\"\n\"      to crash the program or throw a pop-up (on Windows).\\n\"\n\"\\n\"\n\"Except for @G--\" GTEST_FLAG_PREFIX_ \"list_tests@D, you can alternatively set \"\n    \"the corresponding\\n\"\n\"environment variable of a flag (all letters in upper-case). For example, to\\n\"\n\"disable colored text output, you can either specify @G--\" GTEST_FLAG_PREFIX_\n    \"color=no@D or set\\n\"\n\"the @G\" GTEST_FLAG_PREFIX_UPPER_ \"COLOR@D environment variable to @Gno@D.\\n\"\n\"\\n\"\n\"For more information, please read the \" GTEST_NAME_ \" documentation at\\n\"\n\"@G\" GTEST_PROJECT_URL_ \"@D. If you find a bug in \" GTEST_NAME_ \"\\n\"\n\"(not one in your own code or tests), please report it to\\n\"\n\"@G<\" GTEST_DEV_EMAIL_ \">@D.\\n\";\n\nbool ParseGoogleTestFlag(const char* const arg) {\n  return ParseBoolFlag(arg, kAlsoRunDisabledTestsFlag,\n                       &GTEST_FLAG(also_run_disabled_tests)) ||\n      ParseBoolFlag(arg, kBreakOnFailureFlag,\n                    &GTEST_FLAG(break_on_failure)) ||\n      ParseBoolFlag(arg, kCatchExceptionsFlag,\n                    &GTEST_FLAG(catch_exceptions)) ||\n      ParseStringFlag(arg, kColorFlag, &GTEST_FLAG(color)) ||\n      ParseStringFlag(arg, kDeathTestStyleFlag,\n                      &GTEST_FLAG(death_test_style)) ||\n      ParseBoolFlag(arg, kDeathTestUseFork,\n                    &GTEST_FLAG(death_test_use_fork)) ||\n      ParseStringFlag(arg, kFilterFlag, &GTEST_FLAG(filter)) ||\n      ParseStringFlag(arg, kInternalRunDeathTestFlag,\n                      &GTEST_FLAG(internal_run_death_test)) ||\n      ParseBoolFlag(arg, kListTestsFlag, &GTEST_FLAG(list_tests)) ||\n      ParseStringFlag(arg, kOutputFlag, &GTEST_FLAG(output)) ||\n      ParseBoolFlag(arg, kPrintTimeFlag, &GTEST_FLAG(print_time)) ||\n      ParseInt32Flag(arg, kRandomSeedFlag, &GTEST_FLAG(random_seed)) ||\n      ParseInt32Flag(arg, kRepeatFlag, &GTEST_FLAG(repeat)) ||\n      ParseBoolFlag(arg, kShuffleFlag, &GTEST_FLAG(shuffle)) ||\n      ParseInt32Flag(arg, kStackTraceDepthFlag,\n                     &GTEST_FLAG(stack_trace_depth)) ||\n      ParseStringFlag(arg, kStreamResultToFlag,\n                      &GTEST_FLAG(stream_result_to)) ||\n      ParseBoolFlag(arg, kThrowOnFailureFlag,\n                    &GTEST_FLAG(throw_on_failure));\n}\n\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\nvoid LoadFlagsFromFile(const std::string& path) {\n  FILE* flagfile = posix::FOpen(path.c_str(), \"r\");\n  if (!flagfile) {\n    fprintf(stderr,\n            \"Unable to open file \\\"%s\\\"\\n\",\n            GTEST_FLAG(flagfile).c_str());\n    fflush(stderr);\n    exit(EXIT_FAILURE);\n  }\n  std::string contents(ReadEntireFile(flagfile));\n  posix::FClose(flagfile);\n  std::vector<std::string> lines;\n  SplitString(contents, '\\n', &lines);\n  for (size_t i = 0; i < lines.size(); ++i) {\n    if (lines[i].empty())\n      continue;\n    if (!ParseGoogleTestFlag(lines[i].c_str()))\n      g_help_flag = true;\n  }\n}\n#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_\n\n// Parses the command line for Google Test flags, without initializing\n// other parts of Google Test.  The type parameter CharType can be\n// instantiated to either char or wchar_t.\ntemplate <typename CharType>\nvoid ParseGoogleTestFlagsOnlyImpl(int* argc, CharType** argv) {\n  for (int i = 1; i < *argc; i++) {\n    const std::string arg_string = StreamableToString(argv[i]);\n    const char* const arg = arg_string.c_str();\n\n    using internal::ParseBoolFlag;\n    using internal::ParseInt32Flag;\n    using internal::ParseStringFlag;\n\n    bool remove_flag = false;\n    if (ParseGoogleTestFlag(arg)) {\n      remove_flag = true;\n#if GTEST_USE_OWN_FLAGFILE_FLAG_\n    } else if (ParseStringFlag(arg, kFlagfileFlag, &GTEST_FLAG(flagfile))) {\n      LoadFlagsFromFile(GTEST_FLAG(flagfile));\n      remove_flag = true;\n#endif  // GTEST_USE_OWN_FLAGFILE_FLAG_\n    } else if (arg_string == \"--help\" || arg_string == \"-h\" ||\n               arg_string == \"-?\" || arg_string == \"/?\" ||\n               HasGoogleTestFlagPrefix(arg)) {\n      // Both help flag and unrecognized Google Test flags (excluding\n      // internal ones) trigger help display.\n      g_help_flag = true;\n    }\n\n    if (remove_flag) {\n      // Shift the remainder of the argv list left by one.  Note\n      // that argv has (*argc + 1) elements, the last one always being\n      // NULL.  The following loop moves the trailing NULL element as\n      // well.\n      for (int j = i; j != *argc; j++) {\n        argv[j] = argv[j + 1];\n      }\n\n      // Decrements the argument count.\n      (*argc)--;\n\n      // We also need to decrement the iterator as we just removed\n      // an element.\n      i--;\n    }\n  }\n\n  if (g_help_flag) {\n    // We print the help here instead of in RUN_ALL_TESTS(), as the\n    // latter may not be called at all if the user is using Google\n    // Test with another testing framework.\n    PrintColorEncoded(kColorEncodedHelpMessage);\n  }\n}\n\n// Parses the command line for Google Test flags, without initializing\n// other parts of Google Test.\nvoid ParseGoogleTestFlagsOnly(int* argc, char** argv) {\n  ParseGoogleTestFlagsOnlyImpl(argc, argv);\n}\nvoid ParseGoogleTestFlagsOnly(int* argc, wchar_t** argv) {\n  ParseGoogleTestFlagsOnlyImpl(argc, argv);\n}\n\n// The internal implementation of InitGoogleTest().\n//\n// The type parameter CharType can be instantiated to either char or\n// wchar_t.\ntemplate <typename CharType>\nvoid InitGoogleTestImpl(int* argc, CharType** argv) {\n  // We don't want to run the initialization code twice.\n  if (GTestIsInitialized()) return;\n\n  if (*argc <= 0) return;\n\n  g_argvs.clear();\n  for (int i = 0; i != *argc; i++) {\n    g_argvs.push_back(StreamableToString(argv[i]));\n  }\n\n  ParseGoogleTestFlagsOnly(argc, argv);\n  GetUnitTestImpl()->PostFlagParsingInit();\n}\n\n}  // namespace internal\n\n// Initializes Google Test.  This must be called before calling\n// RUN_ALL_TESTS().  In particular, it parses a command line for the\n// flags that Google Test recognizes.  Whenever a Google Test flag is\n// seen, it is removed from argv, and *argc is decremented.\n//\n// No value is returned.  Instead, the Google Test flag variables are\n// updated.\n//\n// Calling the function for the second time has no user-visible effect.\nvoid InitGoogleTest(int* argc, char** argv) {\n#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);\n#else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n  internal::InitGoogleTestImpl(argc, argv);\n#endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n}\n\n// This overloaded version can be used in Windows programs compiled in\n// UNICODE mode.\nvoid InitGoogleTest(int* argc, wchar_t** argv) {\n#if defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n  GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_(argc, argv);\n#else  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n  internal::InitGoogleTestImpl(argc, argv);\n#endif  // defined(GTEST_CUSTOM_INIT_GOOGLE_TEST_FUNCTION_)\n}\n\n}  // namespace testing\n"
  },
  {
    "path": "mypyc/external/googletest/src/gtest_main.cc",
    "content": "// Copyright 2006, Google Inc.\n// All rights reserved.\n//\n// Redistribution and use in source and binary forms, with or without\n// modification, are permitted provided that the following conditions are\n// met:\n//\n//     * Redistributions of source code must retain the above copyright\n// notice, this list of conditions and the following disclaimer.\n//     * Redistributions in binary form must reproduce the above\n// copyright notice, this list of conditions and the following disclaimer\n// in the documentation and/or other materials provided with the\n// distribution.\n//     * Neither the name of Google Inc. nor the names of its\n// contributors may be used to endorse or promote products derived from\n// this software without specific prior written permission.\n//\n// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n// \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#include <stdio.h>\n\n#include \"gtest/gtest.h\"\n\nGTEST_API_ int main(int argc, char **argv) {\n  printf(\"Running main() from gtest_main.cc\\n\");\n  testing::InitGoogleTest(&argc, argv);\n  return RUN_ALL_TESTS();\n}\n"
  },
  {
    "path": "mypyc/ir/__init__.py",
    "content": ""
  },
  {
    "path": "mypyc/ir/class_ir.py",
    "content": "\"\"\"Intermediate representation of classes.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import NamedTuple\n\nfrom mypyc.common import PROPSET_PREFIX, JsonDict\nfrom mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature, RuntimeArg\nfrom mypyc.ir.ops import DeserMaps, Value\nfrom mypyc.ir.rtypes import RInstance, RType, deserialize_type, object_rprimitive\nfrom mypyc.namegen import NameGenerator, exported_name\n\n# Some notes on the vtable layout: Each concrete class has a vtable\n# that contains function pointers for its methods. So that subclasses\n# may be efficiently used when their parent class is expected, the\n# layout of child vtables must be an extension of their base class's\n# vtable.\n#\n# This makes multiple inheritance tricky, since obviously we cannot be\n# an extension of multiple parent classes. We solve this by requiring\n# all but one parent to be \"traits\", which we can operate on in a\n# somewhat less efficient way. For each trait implemented by a class,\n# we generate a separate vtable for the methods in that trait.\n# We then store an array of (trait type, trait vtable) pointers alongside\n# a class's main vtable. When we want to call a trait method, we\n# (at runtime!) search the array of trait vtables to find the correct one,\n# then call through it.\n# Trait vtables additionally need entries for attribute getters and setters,\n# since they can't always be in the same location.\n#\n# To keep down the number of indirections necessary, we store the\n# array of trait vtables in the memory *before* the class vtable, and\n# search it backwards.  (This is a trick we can only do once---there\n# are only two directions to store data in---but I don't think we'll\n# need it again.)\n# There are some tricks we could try in the future to store the trait\n# vtables inline in the trait table (which would cut down one indirection),\n# but this seems good enough for now.\n#\n# As an example:\n# Imagine that we have a class B that inherits from a concrete class A\n# and traits T1 and T2, and that A has methods foo() and\n# bar() and B overrides bar() with a more specific type.\n# Then B's vtable will look something like:\n#\n#      T1 type object\n#      ptr to B's T1 trait vtable\n#      T2 type object\n#      ptr to B's T2 trait vtable\n# -> | A.foo\n#    | Glue function that converts between A.bar's type and B.bar\n#      B.bar\n#      B.baz\n#\n# The arrow points to the \"start\" of the vtable (what vtable pointers\n# point to) and the bars indicate which parts correspond to the parent\n# class A's vtable layout.\n#\n# Classes that allow interpreted code to subclass them also have a\n# \"shadow vtable\" that contains implementations that delegate to\n# making a pycall, so that overridden methods in interpreted children\n# will be called. (A better strategy could dynamically generate these\n# vtables based on which methods are overridden in the children.)\n\n# Descriptions of method and attribute entries in class vtables.\n# The 'cls' field is the class that the method/attr was defined in,\n# which might be a parent class.\n# The 'shadow_method', if present, contains the method that should be\n# placed in the class's shadow vtable (if it has one).\n\n\nclass VTableMethod(NamedTuple):\n    cls: \"ClassIR\"  # noqa: UP037\n    name: str\n    method: FuncIR\n    shadow_method: FuncIR | None\n\n\nVTableEntries = list[VTableMethod]\n\n\nclass ClassIR:\n    \"\"\"Intermediate representation of a class.\n\n    This also describes the runtime structure of native instances.\n    \"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        module_name: str,\n        is_trait: bool = False,\n        is_generated: bool = False,\n        is_abstract: bool = False,\n        is_ext_class: bool = True,\n        is_final_class: bool = False,\n    ) -> None:\n        self.name = name\n        self.module_name = module_name\n        self.is_trait = is_trait\n        self.is_generated = is_generated\n        self.is_abstract = is_abstract\n        self.is_ext_class = is_ext_class\n        self.is_final_class = is_final_class\n        # An augmented class has additional methods separate from what mypyc generates.\n        # Right now the only one is dataclasses.\n        self.is_augmented = False\n        # Does this inherit from a Python class?\n        self.inherits_python = False\n        # Do instances of this class have __dict__?\n        self.has_dict = False\n        # Do we allow interpreted subclasses? Derived from a mypyc_attr.\n        self.allow_interpreted_subclasses = False\n        # Does this class need getseters to be generated for its attributes? (getseters are also\n        # added if is_generated is False)\n        self.needs_getseters = False\n        # Is this class declared as serializable (supports copy.copy\n        # and pickle) using @mypyc_attr(serializable=True)?\n        #\n        # Additionally, any class with this attribute False but with\n        # an __init__ that can be called without any arguments is\n        # *implicitly serializable*. In this case __init__ will be\n        # called during deserialization without arguments. If this is\n        # True, we match Python semantics and __init__ won't be called\n        # during deserialization.\n        #\n        # This impacts also all subclasses. Use is_serializable() to\n        # also consider base classes.\n        self._serializable = False\n        # If this a subclass of some built-in python class, the name\n        # of the object for that class. We currently only support this\n        # in a few ad-hoc cases.\n        self.builtin_base: str | None = None\n        # Default empty constructor\n        self.ctor = FuncDecl(name, None, module_name, FuncSignature([], RInstance(self)))\n        # Declare setup method that allocates and initializes an object. type is the\n        # type of the class being initialized, which could be another class if there\n        # is an interpreted subclass.\n        # TODO: Make it a regular method and generate its body in IR\n        self.setup = FuncDecl(\n            \"__mypyc__\" + name + \"_setup\",\n            None,\n            module_name,\n            FuncSignature([RuntimeArg(\"type\", object_rprimitive)], RInstance(self)),\n        )\n        # Attributes defined in the class (not inherited)\n        self.attributes: dict[str, RType] = {}\n        # Deletable attributes\n        self.deletable: list[str] = []\n        # We populate method_types with the signatures of every method before\n        # we generate methods, and we rely on this information being present.\n        self.method_decls: dict[str, FuncDecl] = {}\n        # Map of methods that are actually present in an extension class\n        self.methods: dict[str, FuncIR] = {}\n        # Glue methods for boxing/unboxing when a class changes the type\n        # while overriding a method. Maps from (parent class overridden, method)\n        # to IR of glue method.\n        self.glue_methods: dict[tuple[ClassIR, str], FuncIR] = {}\n\n        # Properties are accessed like attributes, but have behavior like method calls.\n        # They don't belong in the methods dictionary, since we don't want to expose them to\n        # Python's method API. But we want to put them into our own vtable as methods, so that\n        # they are properly handled and overridden. The property dictionary values are a tuple\n        # containing a property getter and an optional property setter.\n        self.properties: dict[str, tuple[FuncIR, FuncIR | None]] = {}\n        # We generate these in prepare_class_def so that we have access to them when generating\n        # other methods and properties that rely on these types.\n        self.property_types: dict[str, RType] = {}\n\n        self.vtable: dict[str, int] | None = None\n        self.vtable_entries: VTableEntries = []\n        self.trait_vtables: dict[ClassIR, VTableEntries] = {}\n        # N.B: base might not actually quite be the direct base.\n        # It is the nearest concrete base, but we allow a trait in between.\n        self.base: ClassIR | None = None\n        self.traits: list[ClassIR] = []\n        # Supply a working mro for most generated classes. Real classes will need to\n        # fix it up.\n        self.mro: list[ClassIR] = [self]\n        # base_mro is the chain of concrete (non-trait) ancestors\n        self.base_mro: list[ClassIR] = [self]\n\n        # Direct subclasses of this class (use subclasses() to also include non-direct ones)\n        # None if separate compilation prevents this from working.\n        #\n        # Often it's better to use has_no_subclasses() or subclasses() instead.\n        self.children: list[ClassIR] | None = []\n\n        # Instance attributes that are initialized in the class body.\n        self.attrs_with_defaults: set[str] = set()\n\n        # Attributes that are always initialized in __init__ or class body\n        # (inferred in mypyc.analysis.attrdefined using interprocedural analysis).\n        # These can never raise AttributeError when accessed. If an attribute\n        # is *not* always initialized, we normally use the error value for\n        # an undefined value. If the attribute byte has an overlapping error value\n        # (the error_overlap attribute is true for the RType), we use a bitmap\n        # to track if the attribute is defined instead (see bitmap_attrs).\n        self._always_initialized_attrs: set[str] = set()\n\n        # Attributes that are sometimes initialized in __init__\n        self._sometimes_initialized_attrs: set[str] = set()\n\n        # If True, __init__ can make 'self' visible to unanalyzed/arbitrary code\n        self.init_self_leak = False\n\n        # Definedness of these attributes is backed by a bitmap. Index in the list\n        # indicates the bit number. Includes inherited attributes. We need the\n        # bitmap for types such as native ints (i64 etc.) that can't have a dedicated\n        # error value that doesn't overlap a valid value. The bitmap is used if the\n        # value of an attribute is the same as the error value.\n        self.bitmap_attrs: list[str] = []\n\n        # If this is a generator environment class, what is the actual method for it\n        self.env_user_function: FuncIR | None = None\n\n        # If True, keep one freed, cleared instance available for immediate reuse to\n        # speed up allocations. This helps if many objects are freed quickly, before\n        # other instances of the same class are allocated. This is effectively a\n        # per-type free \"list\" of up to length 1.\n        self.reuse_freed_instance = False\n\n        # If True, the class does not participate in cyclic garbage collection.\n        # This can improve performance but is only safe if instances can never\n        # be part of reference cycles. Derived from @mypyc_attr(acyclic=True).\n        self.is_acyclic = False\n\n        # Is this a class inheriting from enum.Enum? Such classes can be special-cased.\n        self.is_enum = False\n\n        # Name of the function if this a callable class representing a coroutine.\n        self.coroutine_name: str | None = None\n\n    def __repr__(self) -> str:\n        return (\n            \"ClassIR(\"\n            \"name={self.name}, module_name={self.module_name}, \"\n            \"is_trait={self.is_trait}, is_generated={self.is_generated}, \"\n            \"is_abstract={self.is_abstract}, is_ext_class={self.is_ext_class}, \"\n            \"is_final_class={self.is_final_class}\"\n            \")\".format(self=self)\n        )\n\n    @property\n    def fullname(self) -> str:\n        return f\"{self.module_name}.{self.name}\"\n\n    def real_base(self) -> ClassIR | None:\n        \"\"\"Return the actual concrete base class, if there is one.\"\"\"\n        if len(self.mro) > 1 and not self.mro[1].is_trait:\n            return self.mro[1]\n        return None\n\n    def vtable_entry(self, name: str) -> int:\n        assert self.vtable is not None, \"vtable not computed yet\"\n        assert name in self.vtable, f\"{self.name!r} has no attribute {name!r}\"\n        return self.vtable[name]\n\n    def attr_details(self, name: str) -> tuple[RType, ClassIR]:\n        for ir in self.mro:\n            if name in ir.attributes:\n                return ir.attributes[name], ir\n            if name in ir.property_types:\n                return ir.property_types[name], ir\n        raise KeyError(f\"{self.name!r} has no attribute {name!r}\")\n\n    def attr_type(self, name: str) -> RType:\n        return self.attr_details(name)[0]\n\n    def method_decl(self, name: str) -> FuncDecl:\n        for ir in self.mro:\n            if name in ir.method_decls:\n                return ir.method_decls[name]\n        raise KeyError(f\"{self.name!r} has no attribute {name!r}\")\n\n    def method_sig(self, name: str) -> FuncSignature:\n        return self.method_decl(name).sig\n\n    def has_method(self, name: str) -> bool:\n        try:\n            self.method_decl(name)\n        except KeyError:\n            return False\n        return True\n\n    def is_method_final(self, name: str) -> bool:\n        subs = self.subclasses()\n        if subs is None:\n            return self.is_final_class\n\n        if self.has_method(name):\n            method_decl = self.method_decl(name)\n            for subc in subs:\n                if subc.method_decl(name) != method_decl:\n                    return False\n            return True\n        else:\n            return not any(subc.has_method(name) for subc in subs)\n\n    def has_attr(self, name: str) -> bool:\n        try:\n            self.attr_type(name)\n        except KeyError:\n            return False\n        return True\n\n    def is_deletable(self, name: str) -> bool:\n        return any(name in ir.deletable for ir in self.mro)\n\n    def is_always_defined(self, name: str) -> bool:\n        if self.is_deletable(name):\n            return False\n        return name in self._always_initialized_attrs\n\n    def name_prefix(self, names: NameGenerator) -> str:\n        return names.private_name(self.module_name, self.name)\n\n    def struct_name(self, names: NameGenerator) -> str:\n        return f\"{exported_name(self.fullname)}Object\"\n\n    def get_method_and_class(\n        self, name: str, *, prefer_method: bool = False\n    ) -> tuple[FuncIR, ClassIR] | None:\n        for ir in self.mro:\n            if name in ir.methods:\n                func_ir = ir.methods[name]\n                if not prefer_method and func_ir.decl.implicit:\n                    # This is an implicit accessor, so there is also an attribute definition\n                    # which the caller prefers. This happens if an attribute overrides a\n                    # property.\n                    return None\n                return func_ir, ir\n\n        return None\n\n    def get_method(self, name: str, *, prefer_method: bool = False) -> FuncIR | None:\n        res = self.get_method_and_class(name, prefer_method=prefer_method)\n        return res[0] if res else None\n\n    def has_method_decl(self, name: str) -> bool:\n        return any(name in ir.method_decls for ir in self.mro)\n\n    def has_no_subclasses(self) -> bool:\n        return self.children == [] and not self.allow_interpreted_subclasses\n\n    def subclasses(self) -> set[ClassIR] | None:\n        \"\"\"Return all subclasses of this class, both direct and indirect.\n\n        Return None if it is impossible to identify all subclasses, for example\n        because we are performing separate compilation.\n        \"\"\"\n        if self.children is None or self.allow_interpreted_subclasses:\n            return None\n        result = set(self.children)\n        for child in self.children:\n            if child.children:\n                child_subs = child.subclasses()\n                if child_subs is None:\n                    return None\n                result.update(child_subs)\n        return result\n\n    def concrete_subclasses(self) -> list[ClassIR] | None:\n        \"\"\"Return all concrete (i.e. non-trait and non-abstract) subclasses.\n\n        Include both direct and indirect subclasses. Place classes with no children first.\n        \"\"\"\n        subs = self.subclasses()\n        if subs is None:\n            return None\n        concrete = {c for c in subs if not (c.is_trait or c.is_abstract)}\n        # We place classes with no children first because they are more likely\n        # to appear in various isinstance() checks. We then sort leaves by name\n        # to get stable order.\n        return sorted(concrete, key=lambda c: (len(c.children or []), c.name))\n\n    def is_serializable(self) -> bool:\n        return any(ci._serializable for ci in self.mro)\n\n    def serialize(self) -> JsonDict:\n        return {\n            \"name\": self.name,\n            \"module_name\": self.module_name,\n            \"is_trait\": self.is_trait,\n            \"is_ext_class\": self.is_ext_class,\n            \"is_abstract\": self.is_abstract,\n            \"is_generated\": self.is_generated,\n            \"is_augmented\": self.is_augmented,\n            \"is_final_class\": self.is_final_class,\n            \"inherits_python\": self.inherits_python,\n            \"has_dict\": self.has_dict,\n            \"allow_interpreted_subclasses\": self.allow_interpreted_subclasses,\n            \"needs_getseters\": self.needs_getseters,\n            \"_serializable\": self._serializable,\n            \"builtin_base\": self.builtin_base,\n            \"ctor\": self.ctor.serialize(),\n            # We serialize dicts as lists to ensure order is preserved\n            \"attributes\": [(k, t.serialize()) for k, t in self.attributes.items()],\n            # We try to serialize a name reference, but if the decl isn't in methods\n            # then we can't be sure that will work so we serialize the whole decl.\n            \"method_decls\": [\n                (k, d.id if k in self.methods else d.serialize())\n                for k, d in self.method_decls.items()\n            ],\n            # We serialize method fullnames out and put methods in a separate dict\n            \"methods\": [(k, m.id) for k, m in self.methods.items()],\n            \"glue_methods\": [\n                ((cir.fullname, k), m.id) for (cir, k), m in self.glue_methods.items()\n            ],\n            # We serialize properties and property_types separately out of an\n            # abundance of caution about preserving dict ordering...\n            \"property_types\": [(k, t.serialize()) for k, t in self.property_types.items()],\n            \"properties\": list(self.properties),\n            \"vtable\": self.vtable,\n            \"vtable_entries\": serialize_vtable(self.vtable_entries),\n            \"trait_vtables\": [\n                (cir.fullname, serialize_vtable(v)) for cir, v in self.trait_vtables.items()\n            ],\n            # References to class IRs are all just names\n            \"base\": self.base.fullname if self.base else None,\n            \"traits\": [cir.fullname for cir in self.traits],\n            \"mro\": [cir.fullname for cir in self.mro],\n            \"base_mro\": [cir.fullname for cir in self.base_mro],\n            \"children\": (\n                [cir.fullname for cir in self.children] if self.children is not None else None\n            ),\n            \"deletable\": self.deletable,\n            \"attrs_with_defaults\": sorted(self.attrs_with_defaults),\n            \"_always_initialized_attrs\": sorted(self._always_initialized_attrs),\n            \"_sometimes_initialized_attrs\": sorted(self._sometimes_initialized_attrs),\n            \"init_self_leak\": self.init_self_leak,\n            \"env_user_function\": self.env_user_function.id if self.env_user_function else None,\n            \"reuse_freed_instance\": self.reuse_freed_instance,\n            \"is_acyclic\": self.is_acyclic,\n            \"is_enum\": self.is_enum,\n            \"is_coroutine\": self.coroutine_name,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ClassIR:\n        fullname = data[\"module_name\"] + \".\" + data[\"name\"]\n        assert fullname in ctx.classes, \"Class %s not in deser class map\" % fullname\n        ir = ctx.classes[fullname]\n\n        ir.is_trait = data[\"is_trait\"]\n        ir.is_generated = data[\"is_generated\"]\n        ir.is_abstract = data[\"is_abstract\"]\n        ir.is_ext_class = data[\"is_ext_class\"]\n        ir.is_augmented = data[\"is_augmented\"]\n        ir.is_final_class = data[\"is_final_class\"]\n        ir.inherits_python = data[\"inherits_python\"]\n        ir.has_dict = data[\"has_dict\"]\n        ir.allow_interpreted_subclasses = data[\"allow_interpreted_subclasses\"]\n        ir.needs_getseters = data[\"needs_getseters\"]\n        ir._serializable = data[\"_serializable\"]\n        ir.builtin_base = data[\"builtin_base\"]\n        ir.ctor = FuncDecl.deserialize(data[\"ctor\"], ctx)\n        ir.attributes = {k: deserialize_type(t, ctx) for k, t in data[\"attributes\"]}\n        ir.method_decls = {\n            k: ctx.functions[v].decl if isinstance(v, str) else FuncDecl.deserialize(v, ctx)\n            for k, v in data[\"method_decls\"]\n        }\n        ir.methods = {k: ctx.functions[v] for k, v in data[\"methods\"]}\n        ir.glue_methods = {\n            (ctx.classes[c], k): ctx.functions[v] for (c, k), v in data[\"glue_methods\"]\n        }\n        ir.property_types = {k: deserialize_type(t, ctx) for k, t in data[\"property_types\"]}\n        ir.properties = {\n            k: (ir.methods[k], ir.methods.get(PROPSET_PREFIX + k)) for k in data[\"properties\"]\n        }\n\n        ir.vtable = data[\"vtable\"]\n        ir.vtable_entries = deserialize_vtable(data[\"vtable_entries\"], ctx)\n        ir.trait_vtables = {\n            ctx.classes[k]: deserialize_vtable(v, ctx) for k, v in data[\"trait_vtables\"]\n        }\n\n        base = data[\"base\"]\n        ir.base = ctx.classes[base] if base else None\n        ir.traits = [ctx.classes[s] for s in data[\"traits\"]]\n        ir.mro = [ctx.classes[s] for s in data[\"mro\"]]\n        ir.base_mro = [ctx.classes[s] for s in data[\"base_mro\"]]\n        ir.children = data[\"children\"] and [ctx.classes[s] for s in data[\"children\"]]\n        ir.deletable = data[\"deletable\"]\n        ir.attrs_with_defaults = set(data[\"attrs_with_defaults\"])\n        ir._always_initialized_attrs = set(data[\"_always_initialized_attrs\"])\n        ir._sometimes_initialized_attrs = set(data[\"_sometimes_initialized_attrs\"])\n        ir.init_self_leak = data[\"init_self_leak\"]\n        ir.env_user_function = (\n            ctx.functions[data[\"env_user_function\"]] if data[\"env_user_function\"] else None\n        )\n        ir.reuse_freed_instance = data[\"reuse_freed_instance\"]\n        ir.is_acyclic = data.get(\"is_acyclic\", False)\n        ir.is_enum = data[\"is_enum\"]\n        ir.coroutine_name = data[\"is_coroutine\"]\n\n        return ir\n\n\nclass NonExtClassInfo:\n    \"\"\"Information needed to construct a non-extension class (Python class).\n\n    Includes the class dictionary, a tuple of base classes,\n    the class annotations dictionary, and the metaclass.\n    \"\"\"\n\n    def __init__(self, dict: Value, bases: Value, anns: Value, metaclass: Value) -> None:\n        self.dict = dict\n        self.bases = bases\n        self.anns = anns\n        self.metaclass = metaclass\n\n\ndef serialize_vtable_entry(entry: VTableMethod) -> JsonDict:\n    return {\n        \".class\": \"VTableMethod\",\n        \"cls\": entry.cls.fullname,\n        \"name\": entry.name,\n        \"method\": entry.method.decl.id,\n        \"shadow_method\": entry.shadow_method.decl.id if entry.shadow_method else None,\n    }\n\n\ndef serialize_vtable(vtable: VTableEntries) -> list[JsonDict]:\n    return [serialize_vtable_entry(v) for v in vtable]\n\n\ndef deserialize_vtable_entry(data: JsonDict, ctx: DeserMaps) -> VTableMethod:\n    if data[\".class\"] == \"VTableMethod\":\n        return VTableMethod(\n            ctx.classes[data[\"cls\"]],\n            data[\"name\"],\n            ctx.functions[data[\"method\"]],\n            ctx.functions[data[\"shadow_method\"]] if data[\"shadow_method\"] else None,\n        )\n    assert False, \"Bogus vtable .class: %s\" % data[\".class\"]\n\n\ndef deserialize_vtable(data: list[JsonDict], ctx: DeserMaps) -> VTableEntries:\n    return [deserialize_vtable_entry(x, ctx) for x in data]\n\n\ndef all_concrete_classes(class_ir: ClassIR) -> list[ClassIR] | None:\n    \"\"\"Return all concrete classes among the class itself and its subclasses.\"\"\"\n    concrete = class_ir.concrete_subclasses()\n    if concrete is None:\n        return None\n    if not (class_ir.is_abstract or class_ir.is_trait):\n        concrete.append(class_ir)\n    return concrete\n"
  },
  {
    "path": "mypyc/ir/deps.py",
    "content": "from typing import Final\n\n\nclass Capsule:\n    \"\"\"Defines a C extension capsule that a primitive may require.\"\"\"\n\n    def __init__(self, name: str) -> None:\n        # Module fullname, e.g. 'librt.base64'\n        self.name: Final = name\n\n    def __repr__(self) -> str:\n        return f\"Capsule(name={self.name!r})\"\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, Capsule) and self.name == other.name\n\n    def __hash__(self) -> int:\n        return hash((\"Capsule\", self.name))\n\n\nclass SourceDep:\n    \"\"\"Defines a C source file that a primitive may require.\n\n    Each source file must also have a corresponding .h file (replace .c with .h)\n    that gets implicitly #included if the source is used.\n    \"\"\"\n\n    def __init__(self, path: str) -> None:\n        # Relative path from mypyc/lib-rt, e.g. 'bytes_extra_ops.c'\n        self.path: Final = path\n\n    def __repr__(self) -> str:\n        return f\"SourceDep(path={self.path!r})\"\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, SourceDep) and self.path == other.path\n\n    def __hash__(self) -> int:\n        return hash((\"SourceDep\", self.path))\n\n    def get_header(self) -> str:\n        \"\"\"Get the header file path by replacing .c with .h\"\"\"\n        return self.path.replace(\".c\", \".h\")\n\n\nDependency = Capsule | SourceDep\n\n\nLIBRT_STRINGS: Final = Capsule(\"librt.strings\")\nLIBRT_BASE64: Final = Capsule(\"librt.base64\")\nLIBRT_VECS: Final = Capsule(\"librt.vecs\")\nLIBRT_TIME: Final = Capsule(\"librt.time\")\n\nBYTES_EXTRA_OPS: Final = SourceDep(\"bytes_extra_ops.c\")\nBYTES_WRITER_EXTRA_OPS: Final = SourceDep(\"byteswriter_extra_ops.c\")\nSTRING_WRITER_EXTRA_OPS: Final = SourceDep(\"stringwriter_extra_ops.c\")\nBYTEARRAY_EXTRA_OPS: Final = SourceDep(\"bytearray_extra_ops.c\")\nSTR_EXTRA_OPS: Final = SourceDep(\"str_extra_ops.c\")\nVECS_EXTRA_OPS: Final = SourceDep(\"vecs_extra_ops.c\")\n"
  },
  {
    "path": "mypyc/ir/func_ir.py",
    "content": "\"\"\"Intermediate representation of functions.\"\"\"\n\nfrom __future__ import annotations\n\nimport inspect\nfrom collections.abc import Sequence\nfrom typing import Final\n\nfrom mypy.nodes import ARG_POS, ArgKind, Block, FuncDef\nfrom mypyc.common import BITMAP_BITS, JsonDict, bitmap_name, get_id_from_name, short_id_from_name\nfrom mypyc.ir.ops import (\n    Assign,\n    AssignMulti,\n    BasicBlock,\n    Box,\n    ControlOp,\n    DeserMaps,\n    Float,\n    Integer,\n    LoadAddress,\n    LoadLiteral,\n    Register,\n    TupleSet,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RType,\n    bitmap_rprimitive,\n    deserialize_type,\n    is_bool_rprimitive,\n    is_none_rprimitive,\n)\nfrom mypyc.namegen import NameGenerator\n\n\nclass RuntimeArg:\n    \"\"\"Description of a function argument in IR.\n\n    Argument kind is one of ARG_* constants defined in mypy.nodes.\n    \"\"\"\n\n    def __init__(\n        self, name: str, typ: RType, kind: ArgKind = ARG_POS, pos_only: bool = False\n    ) -> None:\n        self.name = name\n        self.type = typ\n        self.kind = kind\n        self.pos_only = pos_only\n\n    @property\n    def optional(self) -> bool:\n        return self.kind.is_optional()\n\n    def __repr__(self) -> str:\n        return \"RuntimeArg(name={}, type={}, optional={!r}, pos_only={!r})\".format(\n            self.name, self.type, self.optional, self.pos_only\n        )\n\n    def serialize(self) -> JsonDict:\n        return {\n            \"name\": self.name,\n            \"type\": self.type.serialize(),\n            \"kind\": int(self.kind.value),\n            \"pos_only\": self.pos_only,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RuntimeArg:\n        return RuntimeArg(\n            data[\"name\"],\n            deserialize_type(data[\"type\"], ctx),\n            ArgKind(data[\"kind\"]),\n            data[\"pos_only\"],\n        )\n\n\nclass FuncSignature:\n    \"\"\"Signature of a function in IR.\"\"\"\n\n    # TODO: Track if method?\n\n    def __init__(self, args: Sequence[RuntimeArg], ret_type: RType) -> None:\n        self.args = tuple(args)\n        self.ret_type = ret_type\n        # Bitmap arguments are use to mark default values for arguments that\n        # have types with overlapping error values.\n        self.num_bitmap_args = num_bitmap_args(self.args)\n        if self.num_bitmap_args:\n            extra = [\n                RuntimeArg(bitmap_name(i), bitmap_rprimitive, pos_only=True)\n                for i in range(self.num_bitmap_args)\n            ]\n            self.args = self.args + tuple(reversed(extra))\n\n    def real_args(self) -> tuple[RuntimeArg, ...]:\n        \"\"\"Return arguments without any synthetic bitmap arguments.\"\"\"\n        if self.num_bitmap_args:\n            return self.args[: -self.num_bitmap_args]\n        return self.args\n\n    def bound_sig(self) -> FuncSignature:\n        if self.num_bitmap_args:\n            return FuncSignature(self.args[1 : -self.num_bitmap_args], self.ret_type)\n        else:\n            return FuncSignature(self.args[1:], self.ret_type)\n\n    def __repr__(self) -> str:\n        return f\"FuncSignature(args={self.args!r}, ret={self.ret_type!r})\"\n\n    def serialize(self) -> JsonDict:\n        if self.num_bitmap_args:\n            args = self.args[: -self.num_bitmap_args]\n        else:\n            args = self.args\n        return {\"args\": [t.serialize() for t in args], \"ret_type\": self.ret_type.serialize()}\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> FuncSignature:\n        return FuncSignature(\n            [RuntimeArg.deserialize(arg, ctx) for arg in data[\"args\"]],\n            deserialize_type(data[\"ret_type\"], ctx),\n        )\n\n\ndef num_bitmap_args(args: tuple[RuntimeArg, ...]) -> int:\n    n = 0\n    for arg in args:\n        if arg.type.error_overlap and arg.kind.is_optional():\n            n += 1\n    return (n + (BITMAP_BITS - 1)) // BITMAP_BITS\n\n\nFUNC_NORMAL: Final = 0\nFUNC_STATICMETHOD: Final = 1\nFUNC_CLASSMETHOD: Final = 2\n\n\nclass FuncDecl:\n    \"\"\"Declaration of a function in IR (without body or implementation).\n\n    A function can be a regular module-level function, a method, a\n    static method, a class method, or a property getter/setter.\n    \"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        class_name: str | None,\n        module_name: str,\n        sig: FuncSignature,\n        kind: int = FUNC_NORMAL,\n        *,\n        is_prop_setter: bool = False,\n        is_prop_getter: bool = False,\n        is_generator: bool = False,\n        is_coroutine: bool = False,\n        implicit: bool = False,\n        internal: bool = False,\n    ) -> None:\n        self.name = name\n        self.class_name = class_name\n        self.module_name = module_name\n        self.sig = sig\n        self.kind = kind\n        self.is_prop_setter = is_prop_setter\n        self.is_prop_getter = is_prop_getter\n        self.is_generator = is_generator\n        self.is_coroutine = is_coroutine\n        if class_name is None:\n            self.bound_sig: FuncSignature | None = None\n        else:\n            if kind == FUNC_STATICMETHOD:\n                self.bound_sig = sig\n            else:\n                self.bound_sig = sig.bound_sig()\n\n        # If True, not present in the mypy AST and must be synthesized during irbuild\n        # Currently only supported for property getters/setters\n        self.implicit = implicit\n\n        # If True, only direct C level calls are supported (no wrapper function)\n        self.internal = internal\n\n        # This is optional because this will be set to the line number when the corresponding\n        # FuncIR is created\n        self._line: int | None = None\n\n    @property\n    def line(self) -> int:\n        assert self._line is not None\n        return self._line\n\n    @line.setter\n    def line(self, line: int) -> None:\n        self._line = line\n\n    @property\n    def id(self) -> str:\n        assert self.line is not None\n        return get_id_from_name(self.name, self.fullname, self.line)\n\n    @staticmethod\n    def compute_shortname(class_name: str | None, name: str) -> str:\n        return class_name + \".\" + name if class_name else name\n\n    @property\n    def shortname(self) -> str:\n        return FuncDecl.compute_shortname(self.class_name, self.name)\n\n    @property\n    def fullname(self) -> str:\n        return self.module_name + \".\" + self.shortname\n\n    def cname(self, names: NameGenerator) -> str:\n        partial_name = short_id_from_name(self.name, self.shortname, self._line)\n        return names.private_name(self.module_name, partial_name)\n\n    def serialize(self) -> JsonDict:\n        return {\n            \"name\": self.name,\n            \"class_name\": self.class_name,\n            \"module_name\": self.module_name,\n            \"sig\": self.sig.serialize(),\n            \"kind\": self.kind,\n            \"is_prop_setter\": self.is_prop_setter,\n            \"is_prop_getter\": self.is_prop_getter,\n            \"is_generator\": self.is_generator,\n            \"is_coroutine\": self.is_coroutine,\n            \"implicit\": self.implicit,\n            \"internal\": self.internal,\n        }\n\n    # TODO: move this to FuncIR?\n    @staticmethod\n    def get_id_from_json(func_ir: JsonDict) -> str:\n        \"\"\"Get the id from the serialized FuncIR associated with this FuncDecl\"\"\"\n        decl = func_ir[\"decl\"]\n        shortname = FuncDecl.compute_shortname(decl[\"class_name\"], decl[\"name\"])\n        fullname = decl[\"module_name\"] + \".\" + shortname\n        return get_id_from_name(decl[\"name\"], fullname, func_ir[\"line\"])\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> FuncDecl:\n        return FuncDecl(\n            data[\"name\"],\n            data[\"class_name\"],\n            data[\"module_name\"],\n            FuncSignature.deserialize(data[\"sig\"], ctx),\n            data[\"kind\"],\n            is_prop_setter=data[\"is_prop_setter\"],\n            is_prop_getter=data[\"is_prop_getter\"],\n            is_generator=data[\"is_generator\"],\n            is_coroutine=data[\"is_coroutine\"],\n            implicit=data[\"implicit\"],\n            internal=data[\"internal\"],\n        )\n\n\nclass FuncIR:\n    \"\"\"Intermediate representation of a function with contextual information.\n\n    Unlike FuncDecl, this includes the IR of the body (basic blocks).\n    \"\"\"\n\n    def __init__(\n        self,\n        decl: FuncDecl,\n        arg_regs: list[Register],\n        blocks: list[BasicBlock],\n        line: int = -1,\n        traceback_name: str | None = None,\n    ) -> None:\n        # Declaration of the function, including the signature\n        self.decl = decl\n        # Registers for all the arguments to the function\n        self.arg_regs = arg_regs\n        # Body of the function\n        self.blocks = blocks\n        self.decl.line = line\n        # The name that should be displayed for tracebacks that\n        # include this function. Function will be omitted from\n        # tracebacks if None.\n        self.traceback_name = traceback_name\n\n    @property\n    def line(self) -> int:\n        return self.decl.line\n\n    @property\n    def args(self) -> Sequence[RuntimeArg]:\n        return self.decl.sig.args\n\n    @property\n    def ret_type(self) -> RType:\n        return self.decl.sig.ret_type\n\n    @property\n    def class_name(self) -> str | None:\n        return self.decl.class_name\n\n    @property\n    def sig(self) -> FuncSignature:\n        return self.decl.sig\n\n    @property\n    def name(self) -> str:\n        return self.decl.name\n\n    @property\n    def fullname(self) -> str:\n        return self.decl.fullname\n\n    @property\n    def id(self) -> str:\n        return self.decl.id\n\n    @property\n    def internal(self) -> bool:\n        return self.decl.internal\n\n    def cname(self, names: NameGenerator) -> str:\n        return self.decl.cname(names)\n\n    def __repr__(self) -> str:\n        if self.class_name:\n            return f\"<FuncIR {self.class_name}.{self.name}>\"\n        else:\n            return f\"<FuncIR {self.name}>\"\n\n    def serialize(self) -> JsonDict:\n        # We don't include blocks in the serialized version\n        return {\n            \"decl\": self.decl.serialize(),\n            \"line\": self.line,\n            \"traceback_name\": self.traceback_name,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> FuncIR:\n        return FuncIR(\n            FuncDecl.deserialize(data[\"decl\"], ctx), [], [], data[\"line\"], data[\"traceback_name\"]\n        )\n\n\nINVALID_FUNC_DEF: Final = FuncDef(\"<INVALID_FUNC_DEF>\", [], Block([]))\n\n\ndef all_values(args: list[Register], blocks: list[BasicBlock]) -> list[Value]:\n    \"\"\"Return the set of all values that may be initialized in the blocks.\n\n    This omits registers that are only read.\n    \"\"\"\n    values: list[Value] = list(args)\n    seen_registers = set(args)\n\n    for block in blocks:\n        for op in block.ops:\n            if not isinstance(op, ControlOp):\n                if isinstance(op, (Assign, AssignMulti)):\n                    if op.dest not in seen_registers:\n                        values.append(op.dest)\n                        seen_registers.add(op.dest)\n                elif op.is_void:\n                    continue\n                else:\n                    # If we take the address of a register, it might get initialized.\n                    if (\n                        isinstance(op, LoadAddress)\n                        and isinstance(op.src, Register)\n                        and op.src not in seen_registers\n                    ):\n                        values.append(op.src)\n                        seen_registers.add(op.src)\n                    values.append(op)\n\n    return values\n\n\ndef all_values_full(args: list[Register], blocks: list[BasicBlock]) -> list[Value]:\n    \"\"\"Return set of all values that are initialized or accessed.\"\"\"\n    values: list[Value] = list(args)\n    seen_registers = set(args)\n\n    for block in blocks:\n        for op in block.ops:\n            for source in op.sources():\n                # Look for uninitialized registers that are accessed. Ignore\n                # non-registers since we don't allow ops outside basic blocks.\n                if isinstance(source, Register) and source not in seen_registers:\n                    values.append(source)\n                    seen_registers.add(source)\n            if not isinstance(op, ControlOp):\n                if isinstance(op, (Assign, AssignMulti)):\n                    if op.dest not in seen_registers:\n                        values.append(op.dest)\n                        seen_registers.add(op.dest)\n                elif op.is_void:\n                    continue\n                else:\n                    values.append(op)\n\n    return values\n\n\n_ARG_KIND_TO_INSPECT: Final = {\n    ArgKind.ARG_POS: inspect.Parameter.POSITIONAL_OR_KEYWORD,\n    ArgKind.ARG_OPT: inspect.Parameter.POSITIONAL_OR_KEYWORD,\n    ArgKind.ARG_STAR: inspect.Parameter.VAR_POSITIONAL,\n    ArgKind.ARG_NAMED: inspect.Parameter.KEYWORD_ONLY,\n    ArgKind.ARG_STAR2: inspect.Parameter.VAR_KEYWORD,\n    ArgKind.ARG_NAMED_OPT: inspect.Parameter.KEYWORD_ONLY,\n}\n\n# Sentinel indicating a value that cannot be represented in a text signature.\n_NOT_REPRESENTABLE = object()\n\n\ndef get_text_signature(fn: FuncIR, *, bound: bool = False) -> str | None:\n    \"\"\"Return a text signature in CPython's internal doc format, or None\n    if the function's signature cannot be represented.\n    \"\"\"\n    parameters = []\n    mark_self = (fn.class_name is not None) and (fn.decl.kind != FUNC_STATICMETHOD) and not bound\n    sig = fn.decl.bound_sig if bound and fn.decl.bound_sig is not None else fn.decl.sig\n    # Pre-scan for end of positional-only parameters.\n    # This is needed to handle signatures like 'def foo(self, __x)', where mypy\n    # currently sees 'self' as being positional-or-keyword and '__x' as positional-only.\n    pos_only_idx = -1\n    for idx, arg in enumerate(sig.args):\n        if arg.pos_only and arg.kind in (ArgKind.ARG_POS, ArgKind.ARG_OPT):\n            pos_only_idx = idx\n    for idx, arg in enumerate(sig.args):\n        if arg.name.startswith((\"__bitmap\", \"__mypyc\")):\n            continue\n        kind = (\n            inspect.Parameter.POSITIONAL_ONLY\n            if idx <= pos_only_idx\n            else _ARG_KIND_TO_INSPECT[arg.kind]\n        )\n        default: object = inspect.Parameter.empty\n        if arg.optional:\n            default = _find_default_argument(arg.name, fn.blocks)\n            if default is _NOT_REPRESENTABLE:\n                # This default argument cannot be represented in a __text_signature__\n                return None\n\n        curr_param = inspect.Parameter(arg.name, kind, default=default)\n        parameters.append(curr_param)\n        if mark_self:\n            # Parameter.__init__/Parameter.replace do not accept $\n            curr_param._name = f\"${arg.name}\"  # type: ignore[attr-defined]\n            mark_self = False\n    return f\"{fn.name}{inspect.Signature(parameters)}\"\n\n\ndef _find_default_argument(name: str, blocks: list[BasicBlock]) -> object:\n    # Find assignment inserted by gen_arg_defaults. Assumed to be the first assignment.\n    for block in blocks:\n        for op in block.ops:\n            if isinstance(op, Assign) and op.dest.name == name:\n                return _extract_python_literal(op.src)\n    return _NOT_REPRESENTABLE\n\n\ndef _extract_python_literal(value: Value) -> object:\n    if isinstance(value, Integer):\n        if is_none_rprimitive(value.type):\n            return None\n        val = value.numeric_value()\n        if is_bool_rprimitive(value.type):\n            return bool(val)\n        return val\n    elif isinstance(value, Float):\n        return value.value\n    elif isinstance(value, LoadLiteral):\n        return value.value\n    elif isinstance(value, Box):\n        return _extract_python_literal(value.src)\n    elif isinstance(value, TupleSet):\n        items = tuple(_extract_python_literal(item) for item in value.items)\n        if any(itm is _NOT_REPRESENTABLE for itm in items):\n            return _NOT_REPRESENTABLE\n        return items\n    return _NOT_REPRESENTABLE\n"
  },
  {
    "path": "mypyc/ir/module_ir.py",
    "content": "\"\"\"Intermediate representation of modules.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.common import JsonDict\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.deps import Capsule, Dependency, SourceDep\nfrom mypyc.ir.func_ir import FuncDecl, FuncIR\nfrom mypyc.ir.ops import DeserMaps\nfrom mypyc.ir.rtypes import RType, deserialize_type\n\n\nclass ModuleIR:\n    \"\"\"Intermediate representation of a module.\"\"\"\n\n    def __init__(\n        self,\n        fullname: str,\n        imports: list[str],\n        functions: list[FuncIR],\n        classes: list[ClassIR],\n        final_names: list[tuple[str, RType]],\n        type_var_names: list[str],\n    ) -> None:\n        self.fullname = fullname\n        self.imports = imports.copy()\n        self.functions = functions\n        self.classes = classes\n        self.final_names = final_names\n        # Names of C statics used for Python 3.12 type variable objects.\n        # These are only visible in the module that defined them, so no need\n        # to serialize.\n        self.type_var_names = type_var_names\n        # Dependencies needed by the module (such as capsules or source files)\n        self.dependencies: set[Dependency] = set()\n\n    def serialize(self) -> JsonDict:\n        # Serialize dependencies as a list of dicts with type information\n        serialized_deps = []\n        for dep in sorted(self.dependencies, key=lambda d: (type(d).__name__, str(d))):\n            if isinstance(dep, Capsule):\n                serialized_deps.append({\"type\": \"Capsule\", \"name\": dep.name})\n            elif isinstance(dep, SourceDep):\n                serialized_deps.append({\"type\": \"SourceDep\", \"path\": dep.path})\n\n        return {\n            \"fullname\": self.fullname,\n            \"imports\": self.imports,\n            \"functions\": [f.serialize() for f in self.functions],\n            \"classes\": [c.serialize() for c in self.classes],\n            \"final_names\": [(k, t.serialize()) for k, t in self.final_names],\n            \"dependencies\": serialized_deps,\n        }\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> ModuleIR:\n        module = ModuleIR(\n            data[\"fullname\"],\n            data[\"imports\"],\n            [ctx.functions[FuncDecl.get_id_from_json(f)] for f in data[\"functions\"]],\n            [ClassIR.deserialize(c, ctx) for c in data[\"classes\"]],\n            [(k, deserialize_type(t, ctx)) for k, t in data[\"final_names\"]],\n            [],\n        )\n\n        # Deserialize dependencies\n        deps: set[Dependency] = set()\n        for dep_dict in data[\"dependencies\"]:\n            if dep_dict[\"type\"] == \"Capsule\":\n                deps.add(Capsule(dep_dict[\"name\"]))\n            elif dep_dict[\"type\"] == \"SourceDep\":\n                deps.add(SourceDep(dep_dict[\"path\"]))\n        module.dependencies = deps\n\n        return module\n\n\ndef deserialize_modules(data: dict[str, JsonDict], ctx: DeserMaps) -> dict[str, ModuleIR]:\n    \"\"\"Deserialize a collection of modules.\n\n    The modules can contain dependencies on each other.\n\n    Arguments:\n        data: A dict containing the modules to deserialize.\n        ctx: The deserialization maps to use and to populate.\n             They are populated with information from the deserialized\n             modules and as a precondition must have been populated by\n             deserializing any dependencies of the modules being deserialized\n             (outside of dependencies between the modules themselves).\n\n    Returns a map containing the deserialized modules.\n    \"\"\"\n    for mod in data.values():\n        # First create ClassIRs for every class so that we can construct types and whatnot\n        for cls in mod[\"classes\"]:\n            ir = ClassIR(cls[\"name\"], cls[\"module_name\"])\n            assert ir.fullname not in ctx.classes, \"Class %s already in map\" % ir.fullname\n            ctx.classes[ir.fullname] = ir\n\n    for mod in data.values():\n        # Then deserialize all of the functions so that methods are available\n        # to the class deserialization.\n        for method in mod[\"functions\"]:\n            func = FuncIR.deserialize(method, ctx)\n            assert func.decl.id not in ctx.functions, (\n                \"Method %s already in map\" % func.decl.fullname\n            )\n            ctx.functions[func.decl.id] = func\n\n    return {k: ModuleIR.deserialize(v, ctx) for k, v in data.items()}\n\n\n# ModulesIRs should also always be an *OrderedDict*, but if we\n# declared it that way we would need to put it in quotes everywhere...\nModuleIRs = dict[str, ModuleIR]\n"
  },
  {
    "path": "mypyc/ir/ops.py",
    "content": "\"\"\"Low-level opcodes for compiler intermediate representation (IR).\n\nOpcodes operate on abstract values (Value) in a register machine. Each\nvalue has a type (RType). A value can hold various things, such as:\n\n- local variables or temporaries (Register)\n- intermediate values of expressions (RegisterOp subclasses)\n- condition flags (true/false)\n- literals (integer literals, True, False, etc.)\n\nNOTE: As a convention, we don't create subclasses of concrete Value/Op\n      subclasses (e.g. you shouldn't define a subclass of Integer, which\n      is a concrete class).\n\n      If you want to introduce a variant of an existing class, you'd\n      typically add an attribute (e.g. a flag) to an existing concrete\n      class to enable the new behavior. Sometimes adding a new abstract\n      base class is also an option, or just creating a new subclass\n      without any inheritance relationship (some duplication of code\n      is preferred over introducing complex implementation inheritance).\n\n      This makes it possible to use isinstance(x, <concrete Value\n      subclass>) checks without worrying about potential subclasses.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections.abc import Sequence\nfrom typing import TYPE_CHECKING, Final, Generic, NamedTuple, TypeVar, final\n\nfrom mypy_extensions import trait\n\nfrom mypyc.ir.deps import Dependency\nfrom mypyc.ir.rtypes import (\n    RArray,\n    RInstance,\n    RStruct,\n    RTuple,\n    RType,\n    RUnion,\n    RVec,\n    RVoid,\n    bit_rprimitive,\n    bool_rprimitive,\n    cstring_rprimitive,\n    float_rprimitive,\n    int_rprimitive,\n    is_bool_or_bit_rprimitive,\n    is_fixed_width_rtype,\n    is_int_rprimitive,\n    is_none_rprimitive,\n    is_pointer_rprimitive,\n    is_short_int_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    short_int_rprimitive,\n    void_rtype,\n)\n\nif TYPE_CHECKING:\n    from mypyc.codegen.literals import LiteralValue\n    from mypyc.ir.class_ir import ClassIR\n    from mypyc.ir.func_ir import FuncDecl, FuncIR\n\nT = TypeVar(\"T\")\n\n\n@final\nclass BasicBlock:\n    \"\"\"IR basic block.\n\n    Contains a sequence of Ops and ends with a ControlOp (Goto,\n    Branch, Return or Unreachable). Only the last op can be a\n    ControlOp.\n\n    All generated Ops live in basic blocks. Basic blocks determine the\n    order of evaluation and control flow within a function. A basic\n    block is always associated with a single function/method (FuncIR).\n\n    When building the IR, ops that raise exceptions can be included in\n    the middle of a basic block, but the exceptions aren't checked.\n    Afterwards we perform a transform that inserts explicit checks for\n    all error conditions and splits basic blocks accordingly to preserve\n    the invariant that a jump, branch or return can only ever appear\n    as the final op in a block. Manually inserting error checking ops\n    would be boring and error-prone.\n\n    BasicBlocks have an error_handler attribute that determines where\n    to jump if an error occurs. If none is specified, an error will\n    propagate up out of the function. This is compiled away by the\n    `exceptions` module.\n\n    Block labels are used for pretty printing and emitting C code, and\n    get filled in by those passes.\n\n    Ops that may terminate the program aren't treated as exits.\n    \"\"\"\n\n    def __init__(self, label: int = -1) -> None:\n        self.label = label\n        self.ops: list[Op] = []\n        self.error_handler: BasicBlock | None = None\n        self.referenced = False\n\n    @property\n    def terminated(self) -> bool:\n        \"\"\"Does the block end with a jump, branch or return?\n\n        This should always be true after the basic block has been fully built, but\n        this is false during construction.\n        \"\"\"\n        return bool(self.ops) and isinstance(self.ops[-1], ControlOp)\n\n    @property\n    def terminator(self) -> ControlOp:\n        \"\"\"The terminator operation of the block.\"\"\"\n        assert bool(self.ops) and isinstance(self.ops[-1], ControlOp)\n        return self.ops[-1]\n\n\n# Never generates an exception\nERR_NEVER: Final = 0\n# Generates magic value (c_error_value) based on target RType on exception\nERR_MAGIC: Final = 1\n# Generates false (bool) on exception\nERR_FALSE: Final = 2\n# Always fails\nERR_ALWAYS: Final = 3\n# Like ERR_MAGIC, but the magic return overlaps with a possible return value, and\n# an extra PyErr_Occurred() check is also required\nERR_MAGIC_OVERLAPPING: Final = 4\n\n# Hack: using this line number for an op will suppress it in tracebacks\nNO_TRACEBACK_LINE_NO = -10000\n\n\nclass Value:\n    \"\"\"Abstract base class for all IR values.\n\n    These include references to registers, literals, and all\n    operations (Ops), such as assignments, calls and branches.\n\n    Values are often used as inputs of Ops. Register can be used as an\n    assignment target.\n\n    A Value is part of the IR being compiled if it's included in a BasicBlock\n    that is reachable from a FuncIR (i.e., is part of a function).\n\n    See also: Op is a subclass of Value that is the base class of all\n    operations.\n    \"\"\"\n\n    # Source line number (-1 for no/unknown line)\n    line = -1\n    # Type of the value or the result of the operation\n    type: RType = void_rtype\n    is_borrowed = False\n\n    @property\n    def is_void(self) -> bool:\n        return isinstance(self.type, RVoid)\n\n\n@final\nclass Register(Value):\n    \"\"\"A Register holds a value of a specific type, and it can be read and mutated.\n\n    A Register is always local to a function. Each local variable maps\n    to a Register, and they are also used for some (but not all)\n    temporary values.\n\n    Note that the term 'register' is overloaded and is sometimes used\n    to refer to arbitrary Values (for example, in RegisterOp).\n    \"\"\"\n\n    def __init__(self, type: RType, name: str = \"\", is_arg: bool = False, line: int = -1) -> None:\n        self.type = type\n        self.name = name\n        self.is_arg = is_arg\n        self.is_borrowed = is_arg\n        self.line = line\n\n    @property\n    def is_void(self) -> bool:\n        return False\n\n    def __repr__(self) -> str:\n        return f\"<Register {self.name!r} at {hex(id(self))}>\"\n\n\n@final\nclass Integer(Value):\n    \"\"\"Short integer literal.\n\n    Integer literals are treated as constant values and are generally\n    not included in data flow analyses and such, unlike Register and\n    Op subclasses.\n\n    Integer can represent multiple types:\n\n     * Short tagged integers (short_int_primitive type; the tag bit is clear)\n     * Ordinary fixed-width integers (e.g., int32_rprimitive)\n     * Values of other unboxed primitive types that are represented as integers\n       (none_rprimitive, bool_rprimitive)\n     * Null pointers (value 0) of various types, including object_rprimitive\n    \"\"\"\n\n    def __init__(self, value: int, rtype: RType = short_int_rprimitive, line: int = -1) -> None:\n        if is_short_int_rprimitive(rtype) or is_int_rprimitive(rtype):\n            self.value = value * 2\n        else:\n            self.value = value\n        self.type = rtype\n        self.line = line\n\n    def numeric_value(self) -> int:\n        if is_short_int_rprimitive(self.type) or is_int_rprimitive(self.type):\n            return self.value // 2\n        return self.value\n\n\n@final\nclass Float(Value):\n    \"\"\"Float literal.\n\n    Floating point literals are treated as constant values and are generally\n    not included in data flow analyses and such, unlike Register and\n    Op subclasses.\n    \"\"\"\n\n    def __init__(self, value: float, line: int = -1) -> None:\n        self.value = value\n        self.type = float_rprimitive\n        self.line = line\n\n\n@final\nclass CString(Value):\n    \"\"\"C string literal (zero-terminated).\n\n    You can also include zero values in the value, but then you'll need to track\n    the length of the string separately.\n    \"\"\"\n\n    def __init__(self, value: bytes, line: int = -1) -> None:\n        self.value = value\n        self.type = cstring_rprimitive\n        self.line = line\n\n\n@final\nclass Undef(Value):\n    \"\"\"An undefined value.\n\n    Use Undef() as the initial value followed by one or more SetElement\n    ops to initialize a struct. Pseudocode example:\n\n      r0 = set_element undef MyStruct, \"field1\", f1\n      r1 = set_element r0, \"field2\", f2\n      # r1 now has new struct value with two fields set\n\n    Warning: Always initialize undefined values before using them,\n    as otherwise the values are garbage. You shouldn't expect that\n    undefined values are zeroed, in particular.\n    \"\"\"\n\n    def __init__(self, rtype: RType) -> None:\n        self.type = rtype\n\n\nclass Op(Value):\n    \"\"\"Abstract base class for all IR operations.\n\n    Each operation must be stored in a BasicBlock (in 'ops') to be\n    active in the IR. This is different from non-Op values, including\n    Register and Integer, where a reference from an active Op is\n    sufficient to be considered active.\n\n    In well-formed IR an active Op has no references to inactive ops\n    or ops used in another function.\n    \"\"\"\n\n    def __init__(self, line: int) -> None:\n        self.line = line\n\n    def can_raise(self) -> bool:\n        # Override this is if Op may raise an exception. Note that currently the fact that\n        # only RegisterOps may raise an exception in hard coded in some places.\n        return False\n\n    @abstractmethod\n    def sources(self) -> list[Value]:\n        \"\"\"All the values the op may read.\"\"\"\n\n    @abstractmethod\n    def set_sources(self, new: list[Value]) -> None:\n        \"\"\"Rewrite the sources of an op\"\"\"\n\n    def stolen(self) -> list[Value]:\n        \"\"\"Return arguments that have a reference count stolen by this op\"\"\"\n        return []\n\n    def unique_sources(self) -> list[Value]:\n        result: list[Value] = []\n        for reg in self.sources():\n            if reg not in result:\n                result.append(reg)\n        return result\n\n    @abstractmethod\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        pass\n\n\nclass BaseAssign(Op):\n    \"\"\"Abstract base class for ops that assign to a register.\"\"\"\n\n    def __init__(self, dest: Register, line: int = -1) -> None:\n        super().__init__(line)\n        self.dest = dest\n\n\n@final\nclass Assign(BaseAssign):\n    \"\"\"Assign a value to a Register (dest = src).\"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, dest: Register, src: Value, line: int = -1) -> None:\n        super().__init__(dest, line)\n        self.src = src\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def stolen(self) -> list[Value]:\n        if not self.dest.type.is_refcounted:\n            return []\n        return [self.src]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_assign(self)\n\n\n@final\nclass AssignMulti(BaseAssign):\n    \"\"\"Assign multiple values to a Register (dest = src1, src2, ...).\n\n    This is used to initialize RArray values. It's provided to avoid\n    very verbose IR for common vectorcall operations.\n\n    Note that this interacts atypically with reference counting. We\n    assume that each RArray register is initialized exactly once\n    with this op.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, dest: Register, src: list[Value], line: int = -1) -> None:\n        super().__init__(dest, line)\n        assert src\n        assert isinstance(dest.type, RArray)\n        assert dest.type.length == len(src)\n        self.src = src\n\n    def sources(self) -> list[Value]:\n        return self.src.copy()\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.src = new[:]\n\n    def stolen(self) -> list[Value]:\n        return []\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_assign_multi(self)\n\n\nclass ControlOp(Op):\n    \"\"\"Abstract base class for control flow operations.\"\"\"\n\n    def targets(self) -> Sequence[BasicBlock]:\n        \"\"\"Get all basic block targets of the control operation.\"\"\"\n        return ()\n\n    def set_target(self, i: int, new: BasicBlock) -> None:\n        \"\"\"Update a basic block target.\"\"\"\n        raise AssertionError(f\"Invalid set_target({self}, {i})\")\n\n\n@final\nclass Goto(ControlOp):\n    \"\"\"Unconditional jump.\"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, label: BasicBlock, line: int = -1) -> None:\n        super().__init__(line)\n        self.label = label\n\n    def targets(self) -> Sequence[BasicBlock]:\n        return (self.label,)\n\n    def set_target(self, i: int, new: BasicBlock) -> None:\n        assert i == 0\n        self.label = new\n\n    def __repr__(self) -> str:\n        return \"<Goto %s>\" % self.label.label\n\n    def sources(self) -> list[Value]:\n        return []\n\n    def set_sources(self, new: list[Value]) -> None:\n        assert not new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_goto(self)\n\n\n@final\nclass Branch(ControlOp):\n    \"\"\"Branch based on a value.\n\n    If op is BOOL, branch based on a bit/bool value:\n       if [not] r1 goto L1 else goto L2\n\n    If op is IS_ERROR, branch based on whether there is an error value:\n       if [not] is_error(r1) goto L1 else goto L2\n    \"\"\"\n\n    # Branch ops never raise an exception.\n    error_kind = ERR_NEVER\n\n    BOOL: Final = 100\n    IS_ERROR: Final = 101\n\n    def __init__(\n        self,\n        value: Value,\n        true_label: BasicBlock,\n        false_label: BasicBlock,\n        op: int,\n        line: int = -1,\n        *,\n        rare: bool = False,\n    ) -> None:\n        super().__init__(line)\n        # Target value being checked\n        self.value = value\n        # Branch here if the condition is true\n        self.true = true_label\n        # Branch here if the condition is false\n        self.false = false_label\n        # Branch.BOOL (boolean check) or Branch.IS_ERROR (error value check)\n        self.op = op\n        # If True, the condition is negated\n        self.negated = False\n        # If not None, the true label should generate a traceback entry (func name, line number)\n        self.traceback_entry: tuple[str, int] | None = None\n        # If True, we expect to usually take the false branch (for optimization purposes);\n        # this is implicitly treated as true if there is a traceback entry\n        self.rare = rare\n\n    def targets(self) -> Sequence[BasicBlock]:\n        return (self.true, self.false)\n\n    def set_target(self, i: int, new: BasicBlock) -> None:\n        assert i == 0 or i == 1\n        if i == 0:\n            self.true = new\n        else:\n            self.false = new\n\n    def sources(self) -> list[Value]:\n        return [self.value]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.value,) = new\n\n    def invert(self) -> None:\n        self.negated = not self.negated\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_branch(self)\n\n\n@final\nclass Return(ControlOp):\n    \"\"\"Return a value from a function.\"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(\n        self, value: Value, line: int = -1, *, yield_target: BasicBlock | None = None\n    ) -> None:\n        super().__init__(line)\n        self.value = value\n        # If this return is created by a yield, keep track of the next\n        # basic block. This doesn't affect the code we generate but\n        # can feed into analysis that need to understand the\n        # *original* CFG.\n        self.yield_target = yield_target\n\n    def sources(self) -> list[Value]:\n        return [self.value]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.value,) = new\n\n    def stolen(self) -> list[Value]:\n        return [self.value]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_return(self)\n\n\n@final\nclass Unreachable(ControlOp):\n    \"\"\"Mark the end of basic block as unreachable.\n\n    This is sometimes necessary when the end of a basic block is never\n    reached. This can also be explicitly added to the end of non-None\n    returning functions (in None-returning function we can just return\n    None).\n\n    Mypy statically guarantees that the end of the function is not\n    unreachable if there is not a return statement.\n\n    This prevents the block formatter from being confused due to lack\n    of a leave and also leaves a nifty note in the IR. It is not\n    generally processed by visitors.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, line: int = -1) -> None:\n        super().__init__(line)\n\n    def sources(self) -> list[Value]:\n        return []\n\n    def set_sources(self, new: list[Value]) -> None:\n        assert not new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_unreachable(self)\n\n\nclass RegisterOp(Op):\n    \"\"\"Abstract base class for operations that can be written as r1 = f(r2, ..., rn).\n\n    Takes some values, performs an operation, and generates an output\n    (unless the 'type' attribute is void_rtype, which is the default).\n    Other ops can refer to the result of the Op by referring to the Op\n    instance. This doesn't do any explicit control flow, but can raise an\n    error.\n\n    Note that the operands can be arbitrary Values, not just Register\n    instances, even though the naming may suggest otherwise.\n    \"\"\"\n\n    error_kind = -1  # Can this raise exception and how is it signalled; one of ERR_*\n\n    _type: RType | None = None\n\n    def __init__(self, line: int) -> None:\n        super().__init__(line)\n        assert self.error_kind != -1, \"error_kind not defined\"\n\n    def can_raise(self) -> bool:\n        return self.error_kind != ERR_NEVER\n\n\n@final\nclass IncRef(RegisterOp):\n    \"\"\"Increase reference count (inc_ref src).\"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: Value, line: int = -1) -> None:\n        assert src.type.is_refcounted\n        super().__init__(line)\n        self.src = src\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_inc_ref(self)\n\n\n@final\nclass DecRef(RegisterOp):\n    \"\"\"Decrease reference count and free object if zero (dec_ref src).\n\n    The is_xdec flag says to use an XDECREF, which checks if the\n    pointer is NULL first.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: Value, is_xdec: bool = False, line: int = -1) -> None:\n        assert src.type.is_refcounted\n        super().__init__(line)\n        self.src = src\n        self.is_xdec = is_xdec\n\n    def __repr__(self) -> str:\n        return \"<{}DecRef {!r}>\".format(\"X\" if self.is_xdec else \"\", self.src)\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_dec_ref(self)\n\n\n@final\nclass Call(RegisterOp):\n    \"\"\"Native call f(arg, ...).\n\n    The call target can be a module-level function or a class.\n    \"\"\"\n\n    def __init__(self, fn: FuncDecl, args: Sequence[Value], line: int) -> None:\n        self.fn = fn\n        self.args = list(args)\n        assert len(self.args) == len(fn.sig.args)\n        self.type = fn.sig.ret_type\n        ret_type = fn.sig.ret_type\n        if not ret_type.error_overlap:\n            self.error_kind = ERR_MAGIC\n        else:\n            self.error_kind = ERR_MAGIC_OVERLAPPING\n        super().__init__(line)\n\n    def sources(self) -> list[Value]:\n        return list(self.args.copy())\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.args = new[:]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_call(self)\n\n\n@final\nclass MethodCall(RegisterOp):\n    \"\"\"Native method call obj.method(arg, ...)\"\"\"\n\n    def __init__(self, obj: Value, method: str, args: list[Value], line: int = -1) -> None:\n        self.obj = obj\n        self.method = method\n        self.args = args\n        assert isinstance(obj.type, RInstance), \"Methods can only be called on instances\"\n        self.receiver_type = obj.type\n        method_ir = self.receiver_type.class_ir.method_sig(method)\n        assert method_ir is not None, \"{} doesn't have method {}\".format(\n            self.receiver_type.name, method\n        )\n        ret_type = method_ir.ret_type\n        self.type = ret_type\n        if not ret_type.error_overlap:\n            self.error_kind = ERR_MAGIC\n        else:\n            self.error_kind = ERR_MAGIC_OVERLAPPING\n        super().__init__(line)\n\n    def sources(self) -> list[Value]:\n        return self.args.copy() + [self.obj]\n\n    def set_sources(self, new: list[Value]) -> None:\n        *self.args, self.obj = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_method_call(self)\n\n\n@final\nclass PrimitiveDescription:\n    \"\"\"Description of a primitive op.\n\n    Primitives get lowered into lower-level ops before code generation.\n\n    If c_function_name is provided, a primitive will be lowered into a CallC op.\n    Otherwise, custom logic will need to be implemented to transform the\n    primitive into lower-level ops.\n    \"\"\"\n\n    def __init__(\n        self,\n        name: str,\n        arg_types: list[RType],\n        return_type: RType,  # TODO: What about generic?\n        var_arg_type: RType | None,\n        truncated_type: RType | None,\n        c_function_name: str | None,\n        error_kind: int,\n        steals: StealsDescription,\n        is_borrowed: bool,\n        ordering: list[int] | None,\n        extra_int_constants: list[tuple[int, RType]],\n        priority: int,\n        is_pure: bool,\n        experimental: bool,\n        dependencies: list[Dependency] | None,\n    ) -> None:\n        # Each primitive much have a distinct name, but otherwise they are arbitrary.\n        self.name: Final = name\n        self.arg_types: Final = arg_types\n        self.return_type: Final = return_type\n        self.var_arg_type: Final = var_arg_type\n        self.truncated_type: Final = truncated_type\n        # If non-None, this will map to a call of a C helper function; if None,\n        # there must be a custom handler function that gets invoked during the lowering\n        # pass to generate low-level IR for the primitive (in the mypyc.lower package)\n        self.c_function_name: Final = c_function_name\n        self.error_kind: Final = error_kind\n        self.steals: Final = steals\n        self.is_borrowed: Final = is_borrowed\n        self.ordering: Final = ordering\n        self.extra_int_constants: Final = extra_int_constants\n        self.priority: Final = priority\n        # Pure primitives have no side effects, take immutable arguments, and\n        # never fail. They support additional optimizations.\n        self.is_pure: Final = is_pure\n        if is_pure:\n            assert error_kind == ERR_NEVER\n        # Experimental primitives are not used unless mypyc experimental features are\n        # explicitly enabled\n        self.experimental = experimental\n        # Dependencies for the primitive, such as a capsule that needs to imported\n        # and configured to call the primitive.\n        self.dependencies = dependencies\n        # Native integer types such as u8 can cause ambiguity in primitive\n        # matching, since these are assignable to plain int *and* vice versa.\n        # If this flag is set, the primitive has native integer types and must\n        # be matched using more complex rules.\n        self.is_ambiguous = any(has_fixed_width_int(t) for t in arg_types)\n\n    def __repr__(self) -> str:\n        return f\"<PrimitiveDescription {self.name!r}: {self.arg_types}>\"\n\n\ndef has_fixed_width_int(t: RType) -> bool:\n    if isinstance(t, RTuple):\n        return any(has_fixed_width_int(t) for t in t.types)\n    elif isinstance(t, RUnion):\n        return any(has_fixed_width_int(t) for t in t.items)\n    return is_fixed_width_rtype(t)\n\n\n@final\nclass PrimitiveOp(RegisterOp):\n    \"\"\"A higher-level primitive operation.\n\n    Some of these have special compiler support. These will be lowered\n    (transformed) into lower-level IR ops before code generation, and after\n    reference counting op insertion. Others will be transformed into CallC\n    ops.\n\n    Tagged integer equality is a typical primitive op with non-trivial\n    lowering. It gets transformed into a tag check, followed by different\n    code paths for short and long representations.\n    \"\"\"\n\n    def __init__(self, args: list[Value], desc: PrimitiveDescription, line: int = -1) -> None:\n        self.error_kind = desc.error_kind\n        super().__init__(line)\n        self.args = args\n        self.type = desc.return_type\n        self.desc = desc\n\n    def sources(self) -> list[Value]:\n        return self.args\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.args = new[:]\n\n    def stolen(self) -> list[Value]:\n        steals = self.desc.steals\n        if isinstance(steals, list):\n            assert len(steals) == len(self.args)\n            return [arg for arg, steal in zip(self.args, steals) if steal]\n        else:\n            return [] if not steals else self.sources()\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_primitive_op(self)\n\n\n@final\nclass LoadErrorValue(RegisterOp):\n    \"\"\"Load an error value.\n\n    Each type has one reserved value that signals an error (exception). This\n    loads the error value for a specific type.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(\n        self, rtype: RType, line: int = -1, is_borrowed: bool = False, undefines: bool = False\n    ) -> None:\n        super().__init__(line)\n        self.type = rtype\n        self.is_borrowed = is_borrowed\n        # Undefines is true if this should viewed by the definedness\n        # analysis pass as making the register it is assigned to\n        # undefined (and thus checks should be added on uses).\n        self.undefines = undefines\n\n    def sources(self) -> list[Value]:\n        return []\n\n    def set_sources(self, new: list[Value]) -> None:\n        assert not new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_error_value(self)\n\n\n@final\nclass LoadLiteral(RegisterOp):\n    \"\"\"Load a Python literal object (dest = 'foo' / b'foo' / ...).\n\n    This is used to load a static PyObject * value corresponding to\n    a literal of one of the supported types.\n\n    Tuple / frozenset literals must contain only valid literal values as items.\n\n    NOTE: You can use this to load boxed (Python) int objects. Use\n          Integer to load unboxed, tagged integers or fixed-width,\n          low-level integers.\n\n          For int literals, both int_rprimitive (CPyTagged) and\n          object_primitive (PyObject *) are supported as rtype. However,\n          when using int_rprimitive, the value must *not* be small enough\n          to fit in an unboxed integer.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n    is_borrowed = True\n\n    def __init__(self, value: LiteralValue, rtype: RType, line: int = -1) -> None:\n        super().__init__(line)\n        self.value = value\n        self.type = rtype\n\n    def sources(self) -> list[Value]:\n        return []\n\n    def set_sources(self, new: list[Value]) -> None:\n        assert not new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_literal(self)\n\n\n@final\nclass GetAttr(RegisterOp):\n    \"\"\"obj.attr (for a native object)\"\"\"\n\n    error_kind = ERR_MAGIC\n\n    def __init__(\n        self,\n        obj: Value,\n        attr: str,\n        line: int,\n        *,\n        borrow: bool = False,\n        allow_error_value: bool = False,\n    ) -> None:\n        super().__init__(line)\n        self.obj = obj\n        self.attr = attr\n        self.allow_error_value = allow_error_value\n        assert isinstance(obj.type, RInstance), \"Attribute access not supported: %s\" % obj.type\n        self.class_type = obj.type\n        attr_type = obj.type.attr_type(attr)\n        self.type = attr_type\n        if allow_error_value:\n            self.error_kind = ERR_NEVER\n        elif attr_type.error_overlap:\n            self.error_kind = ERR_MAGIC_OVERLAPPING\n        self.is_borrowed = borrow and attr_type.is_refcounted\n\n    def sources(self) -> list[Value]:\n        return [self.obj]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.obj,) = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_get_attr(self)\n\n\n@final\nclass SetAttr(RegisterOp):\n    \"\"\"obj.attr = src (for a native object)\n\n    Steals the reference to src.\n    \"\"\"\n\n    error_kind = ERR_FALSE\n\n    def __init__(self, obj: Value, attr: str, src: Value, line: int) -> None:\n        super().__init__(line)\n        self.obj = obj\n        self.attr = attr\n        self.src = src\n        assert isinstance(obj.type, RInstance), \"Attribute access not supported: %s\" % obj.type\n        self.class_type = obj.type\n        self.type = bool_rprimitive\n        # If True, we can safely assume that the attribute is previously undefined\n        # and we don't use a setter\n        self.is_init = False\n\n    def mark_as_initializer(self) -> None:\n        self.is_init = True\n        self.error_kind = ERR_NEVER\n        self.type = void_rtype\n\n    def sources(self) -> list[Value]:\n        return [self.obj, self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.obj, self.src = new\n\n    def stolen(self) -> list[Value]:\n        return [self.src]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_set_attr(self)\n\n\n# Default name space for statics, variables\nNAMESPACE_STATIC: Final = \"static\"\n\n# Static namespace for pointers to native type objects\nNAMESPACE_TYPE: Final = \"type\"\n\n# Namespace for modules\nNAMESPACE_MODULE: Final = \"module\"\n\n# Namespace for Python 3.12 type variable objects (implicitly created TypeVar instances, etc.)\nNAMESPACE_TYPE_VAR: Final = \"typevar\"\n\n\n@final\nclass LoadStatic(RegisterOp):\n    \"\"\"Load a static name (name :: static).\n\n    Load a C static variable/pointer. The namespace for statics is shared\n    for the entire compilation group. You can optionally provide a module\n    name and a sub-namespace identifier for additional namespacing to avoid\n    name conflicts. The static namespace does not overlap with other C names,\n    since the final C name will get a prefix, so conflicts only must be\n    avoided with other statics.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n    is_borrowed = True\n\n    def __init__(\n        self,\n        type: RType,\n        identifier: str,\n        module_name: str | None = None,\n        namespace: str = NAMESPACE_STATIC,\n        line: int = -1,\n        ann: object = None,\n    ) -> None:\n        super().__init__(line)\n        self.identifier = identifier\n        self.module_name = module_name\n        self.namespace = namespace\n        self.type = type\n        self.ann = ann  # An object to pretty print with the load\n\n    def sources(self) -> list[Value]:\n        return []\n\n    def set_sources(self, new: list[Value]) -> None:\n        assert not new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_static(self)\n\n\n@final\nclass InitStatic(RegisterOp):\n    \"\"\"static = value :: static\n\n    Initialize a C static variable/pointer. See everything in LoadStatic.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(\n        self,\n        value: Value,\n        identifier: str,\n        module_name: str | None = None,\n        namespace: str = NAMESPACE_STATIC,\n        line: int = -1,\n    ) -> None:\n        super().__init__(line)\n        self.identifier = identifier\n        self.module_name = module_name\n        self.namespace = namespace\n        self.value = value\n\n    def sources(self) -> list[Value]:\n        return [self.value]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.value,) = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_init_static(self)\n\n\n@final\nclass TupleSet(RegisterOp):\n    \"\"\"dest = (reg, ...) (for fixed-length tuple)\"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, items: list[Value], line: int) -> None:\n        super().__init__(line)\n        self.items = items\n        # Don't keep track of the fact that an int is short after it\n        # is put into a tuple, since we don't properly implement\n        # runtime subtyping for tuples.\n        self.tuple_type = RTuple(\n            [\n                arg.type if not is_short_int_rprimitive(arg.type) else int_rprimitive\n                for arg in items\n            ]\n        )\n        self.type = self.tuple_type\n\n    def sources(self) -> list[Value]:\n        return self.items.copy()\n\n    def stolen(self) -> list[Value]:\n        return self.items.copy()\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.items = new[:]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_tuple_set(self)\n\n\n@final\nclass TupleGet(RegisterOp):\n    \"\"\"Get item of a fixed-length tuple (src[index]).\"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: Value, index: int, line: int = -1, *, borrow: bool = False) -> None:\n        super().__init__(line)\n        assert isinstance(\n            src.type, RTuple\n        ), f\"TupleGet only operates on tuples, not {type(src.type).__name__}\"\n        src_len = len(src.type.types)\n        self.src = src\n        self.index = index\n        if index < 0:\n            self.index += src_len\n        assert (\n            self.index <= src_len - 1\n        ), f\"Index out of range.\\nsource type: {src.type}\\nindex: {index}\"\n        self.type = src.type.types[index]\n        self.is_borrowed = borrow\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_tuple_get(self)\n\n\n@final\nclass Cast(RegisterOp):\n    \"\"\"cast(type, src)\n\n    Perform a runtime type check (no representation or value conversion).\n\n    DO NOT increment reference counts.\n    \"\"\"\n\n    error_kind = ERR_MAGIC\n\n    def __init__(\n        self, src: Value, typ: RType, line: int, *, borrow: bool = False, unchecked: bool = False\n    ) -> None:\n        super().__init__(line)\n        self.src = src\n        self.type = typ\n        # If true, don't incref the result.\n        self.is_borrowed = borrow\n        # If true, don't perform a runtime type check (only changes the static type of\n        # the operand). Used when we know that the cast will always succeed.\n        self.is_unchecked = unchecked\n        if unchecked:\n            self.error_kind = ERR_NEVER\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def stolen(self) -> list[Value]:\n        if self.is_borrowed:\n            return []\n        return [self.src]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_cast(self)\n\n\n@final\nclass Box(RegisterOp):\n    \"\"\"box(type, src)\n\n    This converts from a potentially unboxed representation to a straight Python object.\n    Only supported for types with an unboxed representation.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: Value, line: int = -1) -> None:\n        super().__init__(line)\n        self.src = src\n        self.type = object_rprimitive\n        # When we box None and bool values, we produce a borrowed result\n        if is_none_rprimitive(self.src.type) or is_bool_or_bit_rprimitive(self.src.type):\n            self.is_borrowed = True\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def stolen(self) -> list[Value]:\n        return [self.src]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_box(self)\n\n\n@final\nclass Unbox(RegisterOp):\n    \"\"\"unbox(type, src)\n\n    This is similar to a cast, but it also changes to a (potentially) unboxed runtime\n    representation. Only supported for types with an unboxed representation.\n    \"\"\"\n\n    def __init__(self, src: Value, typ: RType, line: int) -> None:\n        self.src = src\n        self.type = typ\n        if not typ.error_overlap:\n            self.error_kind = ERR_MAGIC\n        else:\n            self.error_kind = ERR_MAGIC_OVERLAPPING\n        super().__init__(line)\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_unbox(self)\n\n\n@final\nclass RaiseStandardError(RegisterOp):\n    \"\"\"Raise built-in exception with an optional error string.\n\n    We have a separate opcode for this for convenience and to\n    generate smaller, more idiomatic C code.\n    \"\"\"\n\n    # TODO: Make it more explicit at IR level that this always raises\n\n    error_kind = ERR_FALSE\n\n    VALUE_ERROR: Final = \"ValueError\"\n    ASSERTION_ERROR: Final = \"AssertionError\"\n    STOP_ITERATION: Final = \"StopIteration\"\n    UNBOUND_LOCAL_ERROR: Final = \"UnboundLocalError\"\n    RUNTIME_ERROR: Final = \"RuntimeError\"\n    NAME_ERROR: Final = \"NameError\"\n    ZERO_DIVISION_ERROR: Final = \"ZeroDivisionError\"\n    INDEX_ERROR: Final = \"IndexError\"\n\n    def __init__(self, class_name: str, value: str | Value | None, line: int) -> None:\n        super().__init__(line)\n        self.class_name = class_name\n        self.value = value\n        self.type = bool_rprimitive\n\n    def sources(self) -> list[Value]:\n        return []\n\n    def set_sources(self, new: list[Value]) -> None:\n        assert not new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_raise_standard_error(self)\n\n\n# True steals all arguments, False steals none, a list steals those in matching positions\nStealsDescription = bool | list[bool]\n\n\n@final\nclass CallC(RegisterOp):\n    \"\"\"result = function(arg0, arg1, ...)\n\n    Call a C function that is not a compiled/native function (for\n    example, a Python C API function). Use Call to call native\n    functions.\n    \"\"\"\n\n    def __init__(\n        self,\n        function_name: str,\n        args: list[Value],\n        ret_type: RType,\n        steals: StealsDescription,\n        is_borrowed: bool,\n        error_kind: int,\n        line: int,\n        var_arg_idx: int = -1,\n        *,\n        is_pure: bool = False,\n        returns_null: bool = False,\n        dependencies: list[Dependency] | None = None,\n    ) -> None:\n        self.error_kind = error_kind\n        super().__init__(line)\n        self.function_name = function_name\n        self.args = args\n        self.type = ret_type\n        self.steals = steals\n        self.is_borrowed = is_borrowed\n        # The position of the first variable argument in args (if >= 0)\n        self.var_arg_idx = var_arg_idx\n        # Is the function pure? Pure functions have no side effects\n        # and all the arguments are immutable. Pure functions support\n        # additional optimizations. Pure functions never fail.\n        self.is_pure = is_pure\n        # The function might return a null value that does not indicate\n        # an error.\n        self.returns_null = returns_null\n        # Dependencies (such as capsules) that must be imported and initialized before\n        # calling this function (used for C functions exported from librt).\n        self.dependencies = dependencies\n        if is_pure or returns_null:\n            assert error_kind == ERR_NEVER\n\n    def sources(self) -> list[Value]:\n        return self.args[:]\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.args = new[:]\n\n    def stolen(self) -> list[Value]:\n        if isinstance(self.steals, list):\n            assert len(self.steals) == len(self.args)\n            return [arg for arg, steal in zip(self.args, self.steals) if steal]\n        else:\n            return [] if not self.steals else self.sources()\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_call_c(self)\n\n\n@final\nclass Truncate(RegisterOp):\n    \"\"\"result = truncate src from src_type to dst_type\n\n    Truncate a value from type with more bits to type with less bits.\n\n    dst_type and src_type can be native integer types, bools or tagged\n    integers. Tagged integers should have the tag bit unset.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: Value, dst_type: RType, line: int = -1) -> None:\n        super().__init__(line)\n        self.src = src\n        self.type = dst_type\n        self.src_type = src.type\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def stolen(self) -> list[Value]:\n        return []\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_truncate(self)\n\n\n@final\nclass Extend(RegisterOp):\n    \"\"\"result = extend src from src_type to dst_type\n\n    Extend a value from a type with fewer bits to a type with more bits.\n\n    dst_type and src_type can be native integer types, bools or tagged\n    integers. Tagged integers should have the tag bit unset.\n\n    If 'signed' is true, perform sign extension. Otherwise, the result will be\n    zero extended.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: Value, dst_type: RType, signed: bool, line: int = -1) -> None:\n        super().__init__(line)\n        self.src = src\n        self.type = dst_type\n        self.src_type = src.type\n        self.signed = signed\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def stolen(self) -> list[Value]:\n        return []\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_extend(self)\n\n\n@final\nclass LoadGlobal(RegisterOp):\n    \"\"\"Load a low-level global variable/pointer.\n\n    Note that can't be used to directly load Python module-level\n    global variable, since they are stored in a globals dictionary\n    and accessed using dictionary operations.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n    is_borrowed = True\n\n    def __init__(self, type: RType, identifier: str, line: int = -1, ann: object = None) -> None:\n        super().__init__(line)\n        self.identifier = identifier\n        self.type = type\n        self.ann = ann  # An object to pretty print with the load\n\n    def sources(self) -> list[Value]:\n        return []\n\n    def set_sources(self, new: list[Value]) -> None:\n        assert not new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_global(self)\n\n\n@final\nclass IntOp(RegisterOp):\n    \"\"\"Binary arithmetic or bitwise op on integer operands (e.g., r1 = r2 + r3).\n\n    These ops are low-level and are similar to the corresponding C\n    operations.\n\n    The left and right values must have low-level integer types with\n    compatible representations. Fixed-width integers, short_int_rprimitive,\n    bool_rprimitive and bit_rprimitive are supported.\n\n    For tagged (arbitrary-precision) integer ops look at mypyc.primitives.int_ops.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    # Arithmetic ops\n    ADD: Final = 0\n    SUB: Final = 1\n    MUL: Final = 2\n    DIV: Final = 3\n    MOD: Final = 4\n\n    # Bitwise ops\n    AND: Final = 200\n    OR: Final = 201\n    XOR: Final = 202\n    LEFT_SHIFT: Final = 203\n    RIGHT_SHIFT: Final = 204\n\n    op_str: Final = {\n        ADD: \"+\",\n        SUB: \"-\",\n        MUL: \"*\",\n        DIV: \"/\",\n        MOD: \"%\",\n        AND: \"&\",\n        OR: \"|\",\n        XOR: \"^\",\n        LEFT_SHIFT: \"<<\",\n        RIGHT_SHIFT: \">>\",\n    }\n\n    def __init__(self, type: RType, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:\n        super().__init__(line)\n        self.type = type\n        self.lhs = lhs\n        self.rhs = rhs\n        self.op = op\n\n    def sources(self) -> list[Value]:\n        return [self.lhs, self.rhs]\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.lhs, self.rhs = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_int_op(self)\n\n\n# We can't have this in the IntOp class body, because of\n# https://github.com/mypyc/mypyc/issues/932.\nint_op_to_id: Final = {op: op_id for op_id, op in IntOp.op_str.items()}\n\n\n@final\nclass ComparisonOp(RegisterOp):\n    \"\"\"Low-level comparison op for integers and pointers.\n\n    Both unsigned and signed comparisons are supported. Supports\n    comparisons between fixed-width integer types and pointer types.\n    The operands should have matching sizes.\n\n    The result is always a bit (representing a boolean).\n\n    Python semantics, such as calling __eq__, are not supported.\n    \"\"\"\n\n    # Must be ERR_NEVER or ERR_FALSE. ERR_FALSE means that a false result\n    # indicates that an exception has been raised and should be propagated.\n    error_kind = ERR_NEVER\n\n    # S for signed and U for unsigned\n    EQ: Final = 100\n    NEQ: Final = 101\n    SLT: Final = 102\n    SGT: Final = 103\n    SLE: Final = 104\n    SGE: Final = 105\n    ULT: Final = 106\n    UGT: Final = 107\n    ULE: Final = 108\n    UGE: Final = 109\n\n    op_str: Final = {\n        EQ: \"==\",\n        NEQ: \"!=\",\n        SLT: \"<\",\n        SGT: \">\",\n        SLE: \"<=\",\n        SGE: \">=\",\n        ULT: \"<\",\n        UGT: \">\",\n        ULE: \"<=\",\n        UGE: \">=\",\n    }\n\n    signed_ops: Final = {\"==\": EQ, \"!=\": NEQ, \"<\": SLT, \">\": SGT, \"<=\": SLE, \">=\": SGE}\n    unsigned_ops: Final = {\"==\": EQ, \"!=\": NEQ, \"<\": ULT, \">\": UGT, \"<=\": ULE, \">=\": UGE}\n\n    def __init__(self, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:\n        super().__init__(line)\n        self.type = bit_rprimitive\n        self.lhs = lhs\n        self.rhs = rhs\n        self.op = op\n\n    def sources(self) -> list[Value]:\n        return [self.lhs, self.rhs]\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.lhs, self.rhs = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_comparison_op(self)\n\n\n@final\nclass FloatOp(RegisterOp):\n    \"\"\"Binary float arithmetic op (e.g., r1 = r2 + r3).\n\n    These ops are low-level and are similar to the corresponding C\n    operations (and somewhat different from Python operations).\n\n    The left and right values must be floats.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    ADD: Final = 0\n    SUB: Final = 1\n    MUL: Final = 2\n    DIV: Final = 3\n    MOD: Final = 4\n\n    op_str: Final = {ADD: \"+\", SUB: \"-\", MUL: \"*\", DIV: \"/\", MOD: \"%\"}\n\n    def __init__(self, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:\n        super().__init__(line)\n        self.type = float_rprimitive\n        self.lhs = lhs\n        self.rhs = rhs\n        self.op = op\n\n    def sources(self) -> list[Value]:\n        return [self.lhs, self.rhs]\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.lhs, self.rhs = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_float_op(self)\n\n\n# We can't have this in the FloatOp class body, because of\n# https://github.com/mypyc/mypyc/issues/932.\nfloat_op_to_id: Final = {op: op_id for op_id, op in FloatOp.op_str.items()}\n\n\n@final\nclass FloatNeg(RegisterOp):\n    \"\"\"Float negation op (r1 = -r2).\"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: Value, line: int = -1) -> None:\n        super().__init__(line)\n        self.type = float_rprimitive\n        self.src = src\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_float_neg(self)\n\n\n@final\nclass FloatComparisonOp(RegisterOp):\n    \"\"\"Low-level comparison op for floats.\"\"\"\n\n    error_kind = ERR_NEVER\n\n    EQ: Final = 200\n    NEQ: Final = 201\n    LT: Final = 202\n    GT: Final = 203\n    LE: Final = 204\n    GE: Final = 205\n\n    op_str: Final = {EQ: \"==\", NEQ: \"!=\", LT: \"<\", GT: \">\", LE: \"<=\", GE: \">=\"}\n\n    def __init__(self, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:\n        super().__init__(line)\n        self.type = bit_rprimitive\n        self.lhs = lhs\n        self.rhs = rhs\n        self.op = op\n\n    def sources(self) -> list[Value]:\n        return [self.lhs, self.rhs]\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.lhs, self.rhs = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_float_comparison_op(self)\n\n\n# We can't have this in the FloatOp class body, because of\n# https://github.com/mypyc/mypyc/issues/932.\nfloat_comparison_op_to_id: Final = {op: op_id for op_id, op in FloatComparisonOp.op_str.items()}\n\n\n@final\nclass LoadMem(RegisterOp):\n    \"\"\"Read a memory location: result = *(type *)src.\n\n    Attributes:\n      type: Type of the read value\n      src: Pointer to memory to read\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, type: RType, src: Value, line: int = -1, *, borrow: bool = False) -> None:\n        super().__init__(line)\n        self.type = type\n        # TODO: Support other native integer types\n        assert is_pointer_rprimitive(src.type)\n        self.src = src\n        self.is_borrowed = borrow and type.is_refcounted\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_mem(self)\n\n\n@final\nclass SetMem(Op):\n    \"\"\"Write to a memory location: *(type *)dest = src\n\n    Attributes:\n      type: Type of the written value\n      dest: Pointer to memory to write\n      src: Source value\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, type: RType, dest: Value, src: Value, line: int = -1) -> None:\n        super().__init__(line)\n        self.type = void_rtype\n        self.dest_type = type\n        self.src = src\n        self.dest = dest\n\n    def sources(self) -> list[Value]:\n        return [self.src, self.dest]\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.src, self.dest = new\n\n    def stolen(self) -> list[Value]:\n        return [self.src]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_set_mem(self)\n\n\n@final\nclass GetElement(RegisterOp):\n    \"\"\"Get the value of a struct element from a struct value.\"\"\"\n\n    error_kind = ERR_NEVER\n    is_borrowed = True\n\n    def __init__(self, src: Value, field: str, line: int = -1) -> None:\n        super().__init__(line)\n        assert isinstance(src.type, (RStruct, RVec))\n        self.type = src.type.field_type(field)\n        self.src = src\n        self.src_type = src.type\n        self.field = field\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_get_element(self)\n\n\n@final\nclass GetElementPtr(RegisterOp):\n    \"\"\"Get the address of a struct element from a pointer to a struct.\n\n    If you have a struct value, use GetElement instead.\n\n    Note that you may need to use KeepAlive to avoid the struct\n    being freed, if it's reference counted, such as PyObject *.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: Value, src_type: RType, field: str, line: int = -1) -> None:\n        super().__init__(line)\n        assert not isinstance(src.type, (RStruct, RVec))\n        self.type = pointer_rprimitive\n        self.src = src\n        self.src_type = src_type\n        self.field = field\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_get_element_ptr(self)\n\n\n@final\nclass SetElement(RegisterOp):\n    \"\"\"Set the value of a struct element.\n\n    This evaluates to a new struct with the changed value.\n\n    Use together with Undef to initialize a fresh struct value\n    (see Undef for more details).\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: Value, field: str, item: Value, line: int = -1) -> None:\n        super().__init__(line)\n        assert isinstance(src.type, (RStruct, RVec)), src.type\n        self.type = src.type\n        self.src = src\n        self.item = item\n        self.field = field\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def stolen(self) -> list[Value]:\n        return [self.src]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_set_element(self)\n\n\n@final\nclass LoadAddress(RegisterOp):\n    \"\"\"Get the address of a value: result = (type)&src\n\n    Attributes:\n      type: Type of the loaded address(e.g. ptr/object_ptr)\n      src: Source value (str for globals like 'PyList_Type',\n           Register for temporary values or locals, LoadStatic\n           for statics.)\n    \"\"\"\n\n    error_kind = ERR_NEVER\n    is_borrowed = True\n\n    def __init__(self, type: RType, src: str | Register | LoadStatic, line: int = -1) -> None:\n        super().__init__(line)\n        self.type = type\n        self.src = src\n\n    def sources(self) -> list[Value]:\n        if isinstance(self.src, Register):\n            return [self.src]\n        else:\n            return []\n\n    def set_sources(self, new: list[Value]) -> None:\n        if new:\n            assert isinstance(new[0], Register)\n            assert len(new) == 1\n            self.src = new[0]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_load_address(self)\n\n\n@final\nclass KeepAlive(RegisterOp):\n    \"\"\"A no-op operation that ensures source values aren't freed.\n\n    This is sometimes useful to avoid decref when a reference is still\n    being held but not seen by the compiler.\n\n    A typical use case is like this (C-like pseudocode):\n\n      ptr = &x.item\n      r = *ptr\n      keep_alive x  # x must not be freed here\n      # x may be freed here\n\n    If we didn't have \"keep_alive x\", x could be freed immediately\n    after taking the address of 'item', resulting in a read after free\n    on the second line.\n\n    If 'steal' is true, the value is considered to be stolen at\n    this op, i.e. it won't be decref'd. You need to ensure that\n    the value is freed otherwise, perhaps by using borrowing\n    followed by Unborrow.\n\n    Be careful with steal=True -- this can cause memory leaks.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: list[Value], line: int = -1, *, steal: bool = False) -> None:\n        super().__init__(line)\n        assert src\n        self.src = src\n        self.steal = steal\n\n    def sources(self) -> list[Value]:\n        return self.src.copy()\n\n    def stolen(self) -> list[Value]:\n        if self.steal:\n            return self.src.copy()\n        return []\n\n    def set_sources(self, new: list[Value]) -> None:\n        self.src = new[:]\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_keep_alive(self)\n\n\n@final\nclass Unborrow(RegisterOp):\n    \"\"\"A no-op op to create a regular reference from a borrowed one.\n\n    Borrowed references can only be used temporarily and the reference\n    counts won't be managed. This value will be refcounted normally.\n\n    This is mainly useful if you split an aggregate value, such as\n    a tuple, into components using borrowed values (to avoid increfs),\n    and want to treat the components as sharing the original managed\n    reference. You'll also need to use KeepAlive with steal=True to\n    \"consume\" the original tuple reference:\n\n      # t is a 2-tuple\n      r0 = borrow t[0]\n      r1 = borrow t[1]\n      keep_alive steal t\n      r2 = unborrow r0\n      r3 = unborrow r1\n      # now (r2, r3) represent the tuple as separate items, that are\n      # managed again. (Note we need to steal before unborrow, to avoid\n      # refcount briefly touching zero if r2 or r3 are unused.)\n\n    Be careful with this -- this can easily cause double freeing.\n    \"\"\"\n\n    error_kind = ERR_NEVER\n\n    def __init__(self, src: Value, line: int = -1) -> None:\n        super().__init__(line)\n        assert src.is_borrowed\n        self.src = src\n        self.type = src.type\n\n    def sources(self) -> list[Value]:\n        return [self.src]\n\n    def set_sources(self, new: list[Value]) -> None:\n        (self.src,) = new\n\n    def stolen(self) -> list[Value]:\n        return []\n\n    def accept(self, visitor: OpVisitor[T]) -> T:\n        return visitor.visit_unborrow(self)\n\n\n@trait\nclass OpVisitor(Generic[T]):\n    \"\"\"Generic visitor over ops (uses the visitor design pattern).\"\"\"\n\n    @abstractmethod\n    def visit_goto(self, op: Goto) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_branch(self, op: Branch) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_return(self, op: Return) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_unreachable(self, op: Unreachable) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_assign(self, op: Assign) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_assign_multi(self, op: AssignMulti) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_load_error_value(self, op: LoadErrorValue) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_load_literal(self, op: LoadLiteral) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_get_attr(self, op: GetAttr) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_set_attr(self, op: SetAttr) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_load_static(self, op: LoadStatic) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_init_static(self, op: InitStatic) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_tuple_get(self, op: TupleGet) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_tuple_set(self, op: TupleSet) -> T:\n        raise NotImplementedError\n\n    def visit_inc_ref(self, op: IncRef) -> T:\n        raise NotImplementedError\n\n    def visit_dec_ref(self, op: DecRef) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_call(self, op: Call) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_method_call(self, op: MethodCall) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_cast(self, op: Cast) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_box(self, op: Box) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_unbox(self, op: Unbox) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_raise_standard_error(self, op: RaiseStandardError) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_call_c(self, op: CallC) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_primitive_op(self, op: PrimitiveOp) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_truncate(self, op: Truncate) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_extend(self, op: Extend) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_load_global(self, op: LoadGlobal) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_int_op(self, op: IntOp) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_comparison_op(self, op: ComparisonOp) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_float_op(self, op: FloatOp) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_float_neg(self, op: FloatNeg) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_float_comparison_op(self, op: FloatComparisonOp) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_load_mem(self, op: LoadMem) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_set_mem(self, op: SetMem) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_get_element(self, op: GetElement) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_get_element_ptr(self, op: GetElementPtr) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_set_element(self, op: SetElement) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_load_address(self, op: LoadAddress) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_keep_alive(self, op: KeepAlive) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_unborrow(self, op: Unborrow) -> T:\n        raise NotImplementedError\n\n\n# TODO: Should the following definition live somewhere else?\n\n\n# We do a three-pass deserialization scheme in order to resolve name\n# references.\n#  1. Create an empty ClassIR for each class in an SCC.\n#  2. Deserialize all of the functions, which can contain references\n#     to ClassIRs in their types\n#  3. Deserialize all of the classes, which contain lots of references\n#     to the functions they contain. (And to other classes.)\n#\n# Note that this approach differs from how we deserialize ASTs in mypy itself,\n# where everything is deserialized in one pass then a second pass cleans up\n# 'cross_refs'. We don't follow that approach here because it seems to be more\n# code for not a lot of gain since it is easy in mypyc to identify all the objects\n# we might need to reference.\n#\n# Because of these references, we need to maintain maps from class\n# names to ClassIRs and func IDs to FuncIRs.\n#\n# These are tracked in a DeserMaps which is passed to every\n# deserialization function.\n#\n# (Serialization and deserialization *will* be used for incremental\n# compilation but so far it is not hooked up to anything.)\nclass DeserMaps(NamedTuple):\n    classes: dict[str, ClassIR]\n    functions: dict[str, FuncIR]\n"
  },
  {
    "path": "mypyc/ir/pprint.py",
    "content": "\"\"\"Utilities for pretty-printing IR in a human-readable form.\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom collections.abc import Sequence\nfrom typing import Any, Final\n\nfrom mypyc.common import short_name\nfrom mypyc.ir.func_ir import FuncIR, all_values_full\nfrom mypyc.ir.module_ir import ModuleIRs\nfrom mypyc.ir.ops import (\n    ERR_NEVER,\n    Assign,\n    AssignMulti,\n    BasicBlock,\n    Box,\n    Branch,\n    Call,\n    CallC,\n    Cast,\n    ComparisonOp,\n    ControlOp,\n    CString,\n    DecRef,\n    Extend,\n    Float,\n    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\n    GetElement,\n    GetElementPtr,\n    Goto,\n    IncRef,\n    InitStatic,\n    Integer,\n    IntOp,\n    KeepAlive,\n    LoadAddress,\n    LoadErrorValue,\n    LoadGlobal,\n    LoadLiteral,\n    LoadMem,\n    LoadStatic,\n    MethodCall,\n    Op,\n    OpVisitor,\n    PrimitiveOp,\n    RaiseStandardError,\n    Register,\n    Return,\n    SetAttr,\n    SetElement,\n    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\n    Undef,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import RType, is_bool_rprimitive, is_int_rprimitive\n\nErrorSource = BasicBlock | Op\n\n\nclass IRPrettyPrintVisitor(OpVisitor[str]):\n    \"\"\"Internal visitor that pretty-prints ops.\"\"\"\n\n    def __init__(self, names: dict[Value, str]) -> None:\n        # This should contain a name for all values that are shown as\n        # registers in the output. This is not just for Register\n        # instances -- all Ops that produce values need (generated) names.\n        self.names = names\n\n    def visit_goto(self, op: Goto) -> str:\n        return self.format(\"goto %l\", op.label)\n\n    branch_op_names: Final = {Branch.BOOL: (\"%r\", \"bool\"), Branch.IS_ERROR: (\"is_error(%r)\", \"\")}\n\n    def visit_branch(self, op: Branch) -> str:\n        fmt, typ = self.branch_op_names[op.op]\n        if op.negated:\n            fmt = f\"not {fmt}\"\n\n        cond = self.format(fmt, op.value)\n        tb = \"\"\n        if op.traceback_entry:\n            tb = \" (error at %s:%d)\" % op.traceback_entry\n        fmt = f\"if {cond} goto %l{tb} else goto %l\"\n        if typ:\n            fmt += f\" :: {typ}\"\n        return self.format(fmt, op.true, op.false)\n\n    def visit_return(self, op: Return) -> str:\n        return self.format(\"return %r\", op.value)\n\n    def visit_unreachable(self, op: Unreachable) -> str:\n        return \"unreachable\"\n\n    def visit_assign(self, op: Assign) -> str:\n        return self.format(\"%r = %r\", op.dest, op.src)\n\n    def visit_assign_multi(self, op: AssignMulti) -> str:\n        return self.format(\"%r = [%s]\", op.dest, \", \".join(self.format(\"%r\", v) for v in op.src))\n\n    def visit_load_error_value(self, op: LoadErrorValue) -> str:\n        return self.format(\"%r = <error> :: %s\", op, op.type)\n\n    def visit_load_literal(self, op: LoadLiteral) -> str:\n        prefix = \"\"\n        # For values that have a potential unboxed representation, make\n        # it explicit that this is a Python object.\n        if isinstance(op.value, int):\n            prefix = \"object \"\n\n        rvalue = repr(op.value)\n        if isinstance(op.value, frozenset):\n            # We need to generate a string representation that won't vary\n            # run-to-run because sets are unordered, otherwise we may get\n            # spurious irbuild test failures.\n            #\n            # Sorting by the item's string representation is a bit of a\n            # hack, but it's stable and won't cause TypeErrors.\n            formatted_items = [repr(i) for i in sorted(op.value, key=str)]\n            rvalue = \"frozenset({\" + \", \".join(formatted_items) + \"})\"\n        return self.format(\"%r = %s%s\", op, prefix, rvalue)\n\n    def visit_get_attr(self, op: GetAttr) -> str:\n        return self.format(\"%r = %s%r.%s\", op, self.borrow_prefix(op), op.obj, op.attr)\n\n    def borrow_prefix(self, op: Op) -> str:\n        if op.is_borrowed:\n            return \"borrow \"\n        return \"\"\n\n    def visit_set_attr(self, op: SetAttr) -> str:\n        if op.is_init:\n            assert op.error_kind == ERR_NEVER\n        if op.error_kind == ERR_NEVER:\n            # Initialization and direct struct access can never fail\n            return self.format(\"%r.%s = %r\", op.obj, op.attr, op.src)\n        else:\n            return self.format(\"%r.%s = %r; %r = is_error\", op.obj, op.attr, op.src, op)\n\n    def visit_load_static(self, op: LoadStatic) -> str:\n        ann = f\"  ({repr(op.ann)})\" if op.ann else \"\"\n        name = op.identifier\n        if op.module_name is not None:\n            name = f\"{op.module_name}.{name}\"\n        return self.format(\"%r = %s :: %s%s\", op, name, op.namespace, ann)\n\n    def visit_init_static(self, op: InitStatic) -> str:\n        name = op.identifier\n        if op.module_name is not None:\n            name = f\"{op.module_name}.{name}\"\n        return self.format(\"%s = %r :: %s\", name, op.value, op.namespace)\n\n    def visit_tuple_get(self, op: TupleGet) -> str:\n        return self.format(\"%r = %s%r[%d]\", op, self.borrow_prefix(op), op.src, op.index)\n\n    def visit_tuple_set(self, op: TupleSet) -> str:\n        item_str = \", \".join(self.format(\"%r\", item) for item in op.items)\n        return self.format(\"%r = (%s)\", op, item_str)\n\n    def visit_inc_ref(self, op: IncRef) -> str:\n        s = self.format(\"inc_ref %r\", op.src)\n        # TODO: Remove bool check (it's unboxed)\n        if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type):\n            s += f\" :: {short_name(op.src.type.name)}\"\n        return s\n\n    def visit_dec_ref(self, op: DecRef) -> str:\n        s = self.format(\"%sdec_ref %r\", \"x\" if op.is_xdec else \"\", op.src)\n        # TODO: Remove bool check (it's unboxed)\n        if is_bool_rprimitive(op.src.type) or is_int_rprimitive(op.src.type):\n            s += f\" :: {short_name(op.src.type.name)}\"\n        return s\n\n    def visit_call(self, op: Call) -> str:\n        args = \", \".join(self.format(\"%r\", arg) for arg in op.args)\n        # TODO: Display long name?\n        short_name = op.fn.shortname\n        s = f\"{short_name}({args})\"\n        if not op.is_void:\n            s = self.format(\"%r = \", op) + s\n        return s\n\n    def visit_method_call(self, op: MethodCall) -> str:\n        args = \", \".join(self.format(\"%r\", arg) for arg in op.args)\n        s = self.format(\"%r.%s(%s)\", op.obj, op.method, args)\n        if not op.is_void:\n            s = self.format(\"%r = \", op) + s\n        return s\n\n    def visit_cast(self, op: Cast) -> str:\n        if op.is_unchecked:\n            prefix = \"unchecked \"\n        else:\n            prefix = \"\"\n        return self.format(\n            \"%r = %s%scast(%s, %r)\", op, prefix, self.borrow_prefix(op), op.type, op.src\n        )\n\n    def visit_box(self, op: Box) -> str:\n        return self.format(\"%r = box(%s, %r)\", op, op.src.type, op.src)\n\n    def visit_unbox(self, op: Unbox) -> str:\n        return self.format(\"%r = unbox(%s, %r)\", op, op.type, op.src)\n\n    def visit_raise_standard_error(self, op: RaiseStandardError) -> str:\n        if op.value is not None:\n            if isinstance(op.value, str):\n                return self.format(\"%r = raise %s(%s)\", op, op.class_name, repr(op.value))\n            elif isinstance(op.value, Value):\n                return self.format(\"%r = raise %s(%r)\", op, op.class_name, op.value)\n            else:\n                assert False, \"value type must be either str or Value\"\n        else:\n            return self.format(\"%r = raise %s\", op, op.class_name)\n\n    def visit_call_c(self, op: CallC) -> str:\n        args_str = \", \".join(self.format(\"%r\", arg) for arg in op.args)\n        if op.is_void:\n            return self.format(\"%s(%s)\", op.function_name, args_str)\n        else:\n            return self.format(\"%r = %s(%s)\", op, op.function_name, args_str)\n\n    def visit_primitive_op(self, op: PrimitiveOp) -> str:\n        args_str = \", \".join(self.format(\"%r\", arg) for arg in op.args)\n        if op.is_void:\n            return self.format(\"%s %s\", op.desc.name, args_str)\n        else:\n            return self.format(\"%r = %s %s\", op, op.desc.name, args_str)\n\n    def visit_truncate(self, op: Truncate) -> str:\n        return self.format(\"%r = truncate %r: %t to %t\", op, op.src, op.src_type, op.type)\n\n    def visit_extend(self, op: Extend) -> str:\n        if op.signed:\n            extra = \" signed\"\n        else:\n            extra = \"\"\n        return self.format(\"%r = extend%s %r: %t to %t\", op, extra, op.src, op.src_type, op.type)\n\n    def visit_load_global(self, op: LoadGlobal) -> str:\n        ann = f\"  ({repr(op.ann)})\" if op.ann else \"\"\n        return self.format(\"%r = load_global %s :: static%s\", op, op.identifier, ann)\n\n    def visit_int_op(self, op: IntOp) -> str:\n        return self.format(\"%r = %r %s %r\", op, op.lhs, IntOp.op_str[op.op], op.rhs)\n\n    def visit_comparison_op(self, op: ComparisonOp) -> str:\n        if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE):\n            sign_format = \" :: signed\"\n        elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE):\n            sign_format = \" :: unsigned\"\n        else:\n            sign_format = \"\"\n        return self.format(\n            \"%r = %r %s %r%s\", op, op.lhs, ComparisonOp.op_str[op.op], op.rhs, sign_format\n        )\n\n    def visit_float_op(self, op: FloatOp) -> str:\n        return self.format(\"%r = %r %s %r\", op, op.lhs, FloatOp.op_str[op.op], op.rhs)\n\n    def visit_float_neg(self, op: FloatNeg) -> str:\n        return self.format(\"%r = -%r\", op, op.src)\n\n    def visit_float_comparison_op(self, op: FloatComparisonOp) -> str:\n        return self.format(\"%r = %r %s %r\", op, op.lhs, op.op_str[op.op], op.rhs)\n\n    def visit_load_mem(self, op: LoadMem) -> str:\n        return self.format(\n            \"%r = %sload_mem %r :: %t*\", op, self.borrow_prefix(op), op.src, op.type\n        )\n\n    def visit_set_mem(self, op: SetMem) -> str:\n        return self.format(\"set_mem %r, %r :: %t*\", op.dest, op.src, op.dest_type)\n\n    def visit_get_element(self, op: GetElement) -> str:\n        return self.format(\"%r = %r.%s\", op, op.src, op.field)\n\n    def visit_get_element_ptr(self, op: GetElementPtr) -> str:\n        return self.format(\"%r = get_element_ptr %r %s :: %t\", op, op.src, op.field, op.src_type)\n\n    def visit_set_element(self, op: SetElement) -> str:\n        return self.format(\"%r = set_element %r, %s, %r\", op, op.src, op.field, op.item)\n\n    def visit_load_address(self, op: LoadAddress) -> str:\n        if isinstance(op.src, Register):\n            return self.format(\"%r = load_address %r\", op, op.src)\n        elif isinstance(op.src, LoadStatic):\n            name = op.src.identifier\n            if op.src.module_name is not None:\n                name = f\"{op.src.module_name}.{name}\"\n            return self.format(\"%r = load_address %s :: %s\", op, name, op.src.namespace)\n        else:\n            return self.format(\"%r = load_address %s\", op, op.src)\n\n    def visit_keep_alive(self, op: KeepAlive) -> str:\n        if op.steal:\n            steal = \"steal \"\n        else:\n            steal = \"\"\n        return self.format(\n            \"keep_alive {}{}\".format(steal, \", \".join(self.format(\"%r\", v) for v in op.src))\n        )\n\n    def visit_unborrow(self, op: Unborrow) -> str:\n        return self.format(\"%r = unborrow %r\", op, op.src)\n\n    # Helpers\n\n    def format(self, fmt: str, *args: Any) -> str:\n        \"\"\"Helper for formatting strings.\n\n        These format sequences are supported in fmt:\n\n          %s: arbitrary object converted to string using str()\n          %r: name of IR value/register\n          %d: int\n          %f: float\n          %l: BasicBlock (formatted as label 'Ln')\n          %t: RType\n        \"\"\"\n        result = []\n        i = 0\n        arglist = list(args)\n        while i < len(fmt):\n            n = fmt.find(\"%\", i)\n            if n < 0:\n                n = len(fmt)\n            result.append(fmt[i:n])\n            if n < len(fmt):\n                typespec = fmt[n + 1]\n                arg = arglist.pop(0)\n                if typespec == \"r\":\n                    # Register/value\n                    assert isinstance(arg, Value)\n                    if isinstance(arg, Integer):\n                        result.append(str(arg.value))\n                    elif isinstance(arg, Float):\n                        result.append(repr(arg.value))\n                    elif isinstance(arg, CString):\n                        result.append(f\"CString({arg.value!r})\")\n                    elif isinstance(arg, Undef):\n                        result.append(f\"undef {arg.type.name}\")\n                    else:\n                        result.append(self.names[arg])\n                elif typespec == \"d\":\n                    # Integer\n                    result.append(\"%d\" % arg)\n                elif typespec == \"f\":\n                    # Float\n                    result.append(\"%f\" % arg)\n                elif typespec == \"l\":\n                    # Basic block (label)\n                    assert isinstance(arg, BasicBlock)\n                    result.append(\"L%s\" % arg.label)\n                elif typespec == \"t\":\n                    # RType\n                    assert isinstance(arg, RType)\n                    result.append(arg.name)\n                elif typespec == \"s\":\n                    # String\n                    result.append(str(arg))\n                else:\n                    raise ValueError(f\"Invalid format sequence %{typespec}\")\n                i = n + 2\n            else:\n                i = n\n        return \"\".join(result)\n\n\ndef format_registers(func_ir: FuncIR, names: dict[Value, str]) -> list[str]:\n    result = []\n    i = 0\n    regs = all_values_full(func_ir.arg_regs, func_ir.blocks)\n    while i < len(regs):\n        i0 = i\n        group = [names[regs[i0]]]\n        while i + 1 < len(regs) and regs[i + 1].type == regs[i0].type:\n            i += 1\n            group.append(names[regs[i]])\n        i += 1\n        result.append(\"{} :: {}\".format(\", \".join(group), regs[i0].type))\n    return result\n\n\ndef format_blocks(\n    blocks: list[BasicBlock],\n    names: dict[Value, str],\n    source_to_error: dict[ErrorSource, list[str]],\n) -> list[str]:\n    \"\"\"Format a list of IR basic blocks into a human-readable form.\"\"\"\n    # First label all of the blocks\n    for i, block in enumerate(blocks):\n        block.label = i\n\n    handler_map: dict[BasicBlock, list[BasicBlock]] = {}\n    for b in blocks:\n        if b.error_handler:\n            handler_map.setdefault(b.error_handler, []).append(b)\n\n    visitor = IRPrettyPrintVisitor(names)\n\n    lines = []\n    for i, block in enumerate(blocks):\n        handler_msg = \"\"\n        if block in handler_map:\n            labels = sorted(\"L%d\" % b.label for b in handler_map[block])\n            handler_msg = \" (handler for {})\".format(\", \".join(labels))\n\n        lines.append(\"L%d:%s\" % (block.label, handler_msg))\n        if block in source_to_error:\n            for error in source_to_error[block]:\n                lines.append(f\"  ERROR: {error}\")\n        ops = block.ops\n        if (\n            isinstance(ops[-1], Goto)\n            and i + 1 < len(blocks)\n            and ops[-1].label == blocks[i + 1]\n            and not source_to_error.get(ops[-1], [])\n        ):\n            # Hide the last goto if it just goes to the next basic block,\n            # and there are no assocatiated errors with the op.\n            ops = ops[:-1]\n        for op in ops:\n            line = \"    \" + op.accept(visitor)\n            lines.append(line)\n            if op in source_to_error:\n                first = len(lines) - 1\n                # Use emojis to highlight the error\n                for error in source_to_error[op]:\n                    lines.append(f\"    \\U0001f446 ERROR: {error}\")\n                lines[first] = \" \\U0000274c \" + lines[first][4:]\n\n        if not isinstance(block.ops[-1], (Goto, Branch, Return, Unreachable)):\n            # Each basic block needs to exit somewhere.\n            lines.append(\"    [MISSING BLOCK EXIT OPCODE]\")\n    return lines\n\n\ndef format_func(fn: FuncIR, errors: Sequence[tuple[ErrorSource, str]] = ()) -> list[str]:\n    lines = []\n    cls_prefix = fn.class_name + \".\" if fn.class_name else \"\"\n    lines.append(\n        \"def {}{}({}):\".format(cls_prefix, fn.name, \", \".join(arg.name for arg in fn.args))\n    )\n    names = generate_names_for_ir(fn.arg_regs, fn.blocks)\n    for line in format_registers(fn, names):\n        lines.append(\"    \" + line)\n\n    source_to_error = defaultdict(list)\n    for source, error in errors:\n        source_to_error[source].append(error)\n\n    code = format_blocks(fn.blocks, names, source_to_error)\n    lines.extend(code)\n    return lines\n\n\ndef format_modules(modules: ModuleIRs) -> list[str]:\n    ops = []\n    for module in modules.values():\n        for fn in module.functions:\n            ops.extend(format_func(fn))\n            ops.append(\"\")\n    return ops\n\n\ndef generate_names_for_ir(args: list[Register], blocks: list[BasicBlock]) -> dict[Value, str]:\n    \"\"\"Generate unique names for IR values.\n\n    Give names such as 'r5' to temp values in IR which are useful when\n    pretty-printing or generating C. Ensure generated names are unique.\n    \"\"\"\n    names: dict[Value, str] = {}\n    used_names = set()\n\n    temp_index = 0\n\n    for arg in args:\n        names[arg] = arg.name\n        used_names.add(arg.name)\n\n    for block in blocks:\n        for op in block.ops:\n            values = []\n\n            for source in op.sources():\n                if source not in names:\n                    values.append(source)\n\n            if isinstance(op, (Assign, AssignMulti)):\n                values.append(op.dest)\n            elif isinstance(op, ControlOp) or op.is_void:\n                continue\n            elif op not in names:\n                values.append(op)\n\n            for value in values:\n                if value in names:\n                    continue\n                if isinstance(value, Register) and value.name:\n                    name = value.name\n                elif isinstance(value, (Integer, Float, Undef)):\n                    continue\n                else:\n                    name = \"r%d\" % temp_index\n                    temp_index += 1\n\n                # Append _2, _3, ... if needed to make the name unique.\n                if name in used_names:\n                    n = 2\n                    while True:\n                        candidate = \"%s_%d\" % (name, n)\n                        if candidate not in used_names:\n                            name = candidate\n                            break\n                        n += 1\n\n                names[value] = name\n                used_names.add(name)\n\n    return names\n"
  },
  {
    "path": "mypyc/ir/rtypes.py",
    "content": "\"\"\"Types used in the intermediate representation.\n\nThese are runtime types (RTypes), as opposed to mypy Type objects.\nThe latter are only used during type checking and not directly used at\nruntime.  Runtime types are derived from mypy types, but there's no\nsimple one-to-one correspondence. (Here 'runtime' means 'runtime\nchecked'.)\n\nThe generated IR ensures some runtime type safety properties based on\nRTypes. Compiled code can assume that the runtime value matches the\nstatic RType of a value. If the RType of a register is 'builtins.str'\n(str_rprimitive), for example, the generated IR will ensure that the\nregister will have a 'str' object.\n\nRTypes are simpler and less expressive than mypy (or PEP 484)\ntypes. For example, all mypy types of form 'list[T]' (for arbitrary T)\nare erased to the single RType 'builtins.list' (list_rprimitive).\n\nmypyc.irbuild.mapper.Mapper.type_to_rtype converts mypy Types to mypyc\nRTypes.\n\nNOTE: As a convention, we don't create subclasses of concrete RType\n      subclasses (e.g. you shouldn't define a subclass of RTuple, which\n      is a concrete class). We prefer a flat class hierarchy.\n\n      If you want to introduce a variant of an existing class, you'd\n      typically add an attribute (e.g. a flag) to an existing concrete\n      class to enable the new behavior. In rare cases, adding a new\n      abstract base class could also be an option. Adding a completely\n      separate class and sharing some functionality using module-level\n      helper functions may also be reasonable.\n\n      This makes it possible to use isinstance(x, <concrete RType\n      subclass>) checks without worrying about potential subclasses\n      and avoids most trouble caused by implementation inheritance.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom typing import TYPE_CHECKING, ClassVar, Final, Generic, TypeGuard, TypeVar, Union, final\n\nfrom mypyc.common import HAVE_IMMORTAL, IS_32_BIT_PLATFORM, PLATFORM_SIZE, JsonDict, short_name\nfrom mypyc.ir.deps import LIBRT_STRINGS, LIBRT_VECS, Dependency\nfrom mypyc.namegen import NameGenerator\n\nif TYPE_CHECKING:\n    from mypyc.ir.class_ir import ClassIR\n    from mypyc.ir.ops import DeserMaps\n\nT = TypeVar(\"T\")\n\n\nclass RType:\n    \"\"\"Abstract base class for runtime types (erased, only concrete; no generics).\"\"\"\n\n    name: str\n    # If True, the type has a special unboxed representation. If False, the\n    # type is represented as PyObject *. Even if True, the representation\n    # may contain pointers.\n    is_unboxed = False\n    # This is the C undefined value for this type. It's used for initialization\n    # if there's no value yet, and for function return value on error/exception.\n    #\n    # TODO: This shouldn't be specific to C or a string\n    c_undefined: str\n    # If unboxed: does the unboxed version use reference counting?\n    is_refcounted = True\n    # C type; use Emitter.ctype() to access\n    _ctype: str\n    # If True, error/undefined value overlaps with a valid value. To\n    # detect an exception, PyErr_Occurred() must be used in addition\n    # to checking for error value as the return value of a function.\n    #\n    # For example, no i64 value can be reserved for error value, so we\n    # pick an arbitrary value (-113) to signal error, but this is\n    # also a valid non-error value. The chosen value is rare as a\n    # normal, non-error value, so most of the time we can avoid calling\n    # PyErr_Occurred() when checking for errors raised by called\n    # functions.\n    #\n    # This also means that if an attribute with this type might be\n    # undefined, we can't just rely on the error value to signal this.\n    # Instead, we add a bitfield to keep track whether attributes with\n    # \"error overlap\" have a value. If there is no value, AttributeError\n    # is raised on attribute read. Parameters with default values also\n    # use the bitfield trick to indicate whether the caller passed a\n    # value. (If we can determine that an attribute is \"always defined\",\n    # we never raise an AttributeError and don't need the bitfield\n    # entry.)\n    error_overlap = False\n    dependencies: tuple[Dependency, ...] | None = None\n\n    @abstractmethod\n    def accept(self, visitor: RTypeVisitor[T]) -> T:\n        raise NotImplementedError()\n\n    def short_name(self) -> str:\n        return short_name(self.name)\n\n    @property\n    @abstractmethod\n    def may_be_immortal(self) -> bool:\n        raise NotImplementedError\n\n    def __str__(self) -> str:\n        return short_name(self.name)\n\n    def __repr__(self) -> str:\n        return \"<%s>\" % self.__class__.__name__\n\n    def serialize(self) -> JsonDict | str:\n        raise NotImplementedError(f\"Cannot serialize {self.__class__.__name__} instance\")\n\n\ndef deserialize_type(data: JsonDict | str, ctx: DeserMaps) -> RType:\n    \"\"\"Deserialize a JSON-serialized RType.\n\n    Arguments:\n        data: The decoded JSON of the serialized type\n        ctx: The deserialization maps to use\n    \"\"\"\n    # Since there are so few types, we just case on them directly.  If\n    # more get added we should switch to a system like mypy.types\n    # uses.\n    if isinstance(data, str):\n        if data in ctx.classes:\n            return RInstance(ctx.classes[data])\n        elif data in RPrimitive.primitive_map:\n            return RPrimitive.primitive_map[data]\n        elif data == \"void\":\n            return RVoid()\n        else:\n            assert False, f\"Can't find class {data}\"\n    elif data[\".class\"] == \"RTuple\":\n        return RTuple.deserialize(data, ctx)\n    elif data[\".class\"] == \"RUnion\":\n        return RUnion.deserialize(data, ctx)\n    elif data[\".class\"] == \"RVec\":\n        return RVec.deserialize(data, ctx)\n    raise NotImplementedError(\"unexpected .class {}\".format(data[\".class\"]))\n\n\nclass RTypeVisitor(Generic[T]):\n    \"\"\"Generic visitor over RTypes (uses the visitor design pattern).\"\"\"\n\n    @abstractmethod\n    def visit_rprimitive(self, typ: RPrimitive, /) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_rinstance(self, typ: RInstance, /) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_rvec(self, typ: RVec, /) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_runion(self, typ: RUnion, /) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_rtuple(self, typ: RTuple, /) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_rstruct(self, typ: RStruct, /) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_rarray(self, typ: RArray, /) -> T:\n        raise NotImplementedError\n\n    @abstractmethod\n    def visit_rvoid(self, typ: RVoid, /) -> T:\n        raise NotImplementedError\n\n\n# These types are implemented as C structs.\nRStructLike = Union[\"RStruct\", \"RVec\"]\n\n\n@final\nclass RVoid(RType):\n    \"\"\"The void type (no value).\n\n    This is a singleton -- use void_rtype (below) to refer to this instead of\n    constructing a new instance.\n    \"\"\"\n\n    is_unboxed = False\n    name = \"void\"\n    ctype = \"void\"\n\n    def accept(self, visitor: RTypeVisitor[T]) -> T:\n        return visitor.visit_rvoid(self)\n\n    @property\n    def may_be_immortal(self) -> bool:\n        return False\n\n    def serialize(self) -> str:\n        return \"void\"\n\n    def __eq__(self, other: object) -> TypeGuard[RVoid]:\n        return isinstance(other, RVoid)\n\n    def __hash__(self) -> int:\n        return hash(RVoid)\n\n\n# Singleton instance of RVoid\nvoid_rtype: Final = RVoid()\n\n\n@final\nclass RPrimitive(RType):\n    \"\"\"Primitive type such as 'object' or 'int'.\n\n    These often have custom ops associated with them. The 'object'\n    primitive type can be used to hold arbitrary Python objects.\n\n    Different primitive types have different representations, and\n    primitives may be unboxed or boxed. Primitive types don't need to\n    directly correspond to Python types, but most do.\n\n    NOTE: All supported primitive types are defined below\n    (e.g. object_rprimitive).\n    \"\"\"\n\n    # Map from primitive names to primitive types and is used by deserialization\n    primitive_map: ClassVar[dict[str, RPrimitive]] = {}\n\n    def __init__(\n        self,\n        name: str,\n        *,\n        is_unboxed: bool,\n        is_refcounted: bool,\n        is_native_int: bool = False,\n        is_signed: bool = False,\n        ctype: str = \"PyObject *\",\n        size: int = PLATFORM_SIZE,\n        error_overlap: bool = False,\n        may_be_immortal: bool = True,\n        dependencies: tuple[Dependency, ...] | None = None,\n    ) -> None:\n        RPrimitive.primitive_map[name] = self\n\n        self.name = name\n        self.is_unboxed = is_unboxed\n        self.is_refcounted = is_refcounted\n        self.is_native_int = is_native_int\n        self.is_signed = is_signed\n        self._ctype = ctype\n        self.size = size\n        self.error_overlap = error_overlap\n        self._may_be_immortal = may_be_immortal and HAVE_IMMORTAL\n        self.dependencies = dependencies\n        if ctype == \"CPyTagged\":\n            self.c_undefined = \"CPY_INT_TAG\"\n        elif ctype in (\"int16_t\", \"int32_t\", \"int64_t\"):\n            # This is basically an arbitrary value that is pretty\n            # unlikely to overlap with a real value.\n            self.c_undefined = \"-113\"\n        elif ctype == \"CPyPtr\":\n            # TODO: Invent an overlapping error value?\n            self.c_undefined = \"0\"\n        elif ctype.endswith(\"*\"):\n            # Boxed and pointer types use the null pointer as the error value.\n            self.c_undefined = \"NULL\"\n        elif ctype == \"char\":\n            self.c_undefined = \"2\"\n        elif ctype == \"double\":\n            self.c_undefined = \"-113.0\"\n        elif ctype in (\"uint8_t\", \"uint16_t\", \"uint32_t\", \"uint64_t\"):\n            self.c_undefined = \"239\"  # An arbitrary number\n        else:\n            assert False, \"Unrecognized ctype: %r\" % ctype\n\n    def accept(self, visitor: RTypeVisitor[T]) -> T:\n        return visitor.visit_rprimitive(self)\n\n    @property\n    def may_be_immortal(self) -> bool:\n        return self._may_be_immortal\n\n    def serialize(self) -> str:\n        return self.name\n\n    def __repr__(self) -> str:\n        return \"<RPrimitive %s>\" % self.name\n\n    def __eq__(self, other: object) -> TypeGuard[RPrimitive]:\n        return isinstance(other, RPrimitive) and other.name == self.name\n\n    def __hash__(self) -> int:\n        return hash(self.name)\n\n\n# NOTE: All the supported instances of RPrimitive are defined\n# below. Use these instead of creating new instances.\n\n# Used to represent arbitrary objects and dynamically typed (Any)\n# values. There are various ops that let you perform generic, runtime\n# checked operations on these (that match Python semantics). See the\n# ops in mypyc.primitives.misc_ops, including py_getattr_op,\n# py_call_op, and many others.\n#\n# If there is no more specific RType available for some value, we fall\n# back to using this type.\n#\n# NOTE: Even though this is very flexible, this type should be used as\n# little as possible, as generic ops are typically slow. Other types,\n# including other primitive types and RInstance, are usually much\n# faster.\nobject_rprimitive: Final = RPrimitive(\"builtins.object\", is_unboxed=False, is_refcounted=True)\n\n# represents a low level pointer of an object\nobject_pointer_rprimitive: Final = RPrimitive(\n    \"object_ptr\", is_unboxed=False, is_refcounted=False, ctype=\"PyObject **\"\n)\n\n# Similar to object_primitive, but does not use automatic reference\n# counting. Useful for temporaries.\nobject_non_refcounted_rprimitive: Final = RPrimitive(\n    \"builtins.object_nrc\", is_unboxed=False, is_refcounted=False\n)\n\n# Arbitrary-precision integer (corresponds to Python 'int'). Small\n# enough values are stored unboxed, while large integers are\n# represented as a tagged pointer to a Python 'int' PyObject. The\n# lowest bit is used as the tag to decide whether it is a signed\n# unboxed value (shifted left by one) or a PyObject * pointing to an\n# 'int' object. Pointers have the least significant bit set.\n#\n# The undefined/error value is the null pointer (1 -- only the least\n# significant bit is set)).\n#\n# This cannot represent a subclass of int. An instance of a subclass\n# of int is coerced to the corresponding 'int' value.\nint_rprimitive: Final = RPrimitive(\n    \"builtins.int\", is_unboxed=True, is_refcounted=True, ctype=\"CPyTagged\"\n)\n\n# An unboxed integer. The representation is the same as for unboxed\n# int_rprimitive (shifted left by one). These can be used when an\n# integer is known to be small enough to fit size_t (CPyTagged).\nshort_int_rprimitive: Final = RPrimitive(\n    \"short_int\", is_unboxed=True, is_refcounted=False, ctype=\"CPyTagged\"\n)\n\n# Low level integer types (correspond to C integer types)\n\nint16_rprimitive: Final = RPrimitive(\n    \"i16\",\n    is_unboxed=True,\n    is_refcounted=False,\n    is_native_int=True,\n    is_signed=True,\n    ctype=\"int16_t\",\n    size=2,\n    error_overlap=True,\n)\nint32_rprimitive: Final = RPrimitive(\n    \"i32\",\n    is_unboxed=True,\n    is_refcounted=False,\n    is_native_int=True,\n    is_signed=True,\n    ctype=\"int32_t\",\n    size=4,\n    error_overlap=True,\n)\nint64_rprimitive: Final = RPrimitive(\n    \"i64\",\n    is_unboxed=True,\n    is_refcounted=False,\n    is_native_int=True,\n    is_signed=True,\n    ctype=\"int64_t\",\n    size=8,\n    error_overlap=True,\n)\nuint8_rprimitive: Final = RPrimitive(\n    \"u8\",\n    is_unboxed=True,\n    is_refcounted=False,\n    is_native_int=True,\n    is_signed=False,\n    ctype=\"uint8_t\",\n    size=1,\n    error_overlap=True,\n)\n\n# The following unsigned native int types (u16, u32, u64) are not\n# exposed to the user. They are for internal use within mypyc only.\n\nu16_rprimitive: Final = RPrimitive(\n    \"u16\",\n    is_unboxed=True,\n    is_refcounted=False,\n    is_native_int=True,\n    is_signed=False,\n    ctype=\"uint16_t\",\n    size=2,\n    error_overlap=True,\n)\nuint32_rprimitive: Final = RPrimitive(\n    \"u32\",\n    is_unboxed=True,\n    is_refcounted=False,\n    is_native_int=True,\n    is_signed=False,\n    ctype=\"uint32_t\",\n    size=4,\n    error_overlap=True,\n)\nuint64_rprimitive: Final = RPrimitive(\n    \"u64\",\n    is_unboxed=True,\n    is_refcounted=False,\n    is_native_int=True,\n    is_signed=False,\n    ctype=\"uint64_t\",\n    size=8,\n    error_overlap=True,\n)\n\n# The C 'int' type\nc_int_rprimitive = int32_rprimitive\n\nif IS_32_BIT_PLATFORM:\n    c_size_t_rprimitive = uint32_rprimitive\n    c_pyssize_t_rprimitive = RPrimitive(\n        \"native_int\",\n        is_unboxed=True,\n        is_refcounted=False,\n        is_native_int=True,\n        is_signed=True,\n        ctype=\"int32_t\",\n        size=4,\n    )\nelse:\n    c_size_t_rprimitive = uint64_rprimitive\n    c_pyssize_t_rprimitive = RPrimitive(\n        \"native_int\",\n        is_unboxed=True,\n        is_refcounted=False,\n        is_native_int=True,\n        is_signed=True,\n        ctype=\"int64_t\",\n        size=8,\n    )\n\n# Untyped pointer, represented as integer in the C backend\npointer_rprimitive: Final = RPrimitive(\"ptr\", is_unboxed=True, is_refcounted=False, ctype=\"CPyPtr\")\n\n# Untyped pointer, represented as void * in the C backend\nc_pointer_rprimitive: Final = RPrimitive(\n    \"c_ptr\", is_unboxed=False, is_refcounted=False, ctype=\"void *\"\n)\n\ncstring_rprimitive: Final = RPrimitive(\n    \"cstring\", is_unboxed=True, is_refcounted=False, ctype=\"const char *\"\n)\n\n# The type corresponding to mypyc.common.BITMAP_TYPE\nbitmap_rprimitive: Final = uint32_rprimitive\n\n# Floats are represent as 'float' PyObject * values. (In the future\n# we'll likely switch to a more efficient, unboxed representation.)\nfloat_rprimitive: Final = RPrimitive(\n    \"builtins.float\",\n    is_unboxed=True,\n    is_refcounted=False,\n    ctype=\"double\",\n    size=8,\n    error_overlap=True,\n)\n\n# An unboxed Python bool value. This actually has three possible values\n# (0 -> False, 1 -> True, 2 -> error). If you only need True/False, use\n# bit_rprimitive instead.\nbool_rprimitive: Final = RPrimitive(\n    \"builtins.bool\", is_unboxed=True, is_refcounted=False, ctype=\"char\", size=1\n)\n\n# A low-level boolean value with two possible values: 0 and 1. Any\n# other value results in undefined behavior. Undefined or error values\n# are not supported.\nbit_rprimitive: Final = RPrimitive(\n    \"bit\", is_unboxed=True, is_refcounted=False, ctype=\"char\", size=1\n)\n\n# The 'None' value. The possible values are 0 -> None and 2 -> error.\nnone_rprimitive: Final = RPrimitive(\n    \"builtins.None\", is_unboxed=True, is_refcounted=False, ctype=\"char\", size=1\n)\n\n# Python list object (or an instance of a subclass of list). These could be\n# immortal, but since this is expected to be very rare, and the immortality checks\n# can be pretty expensive for lists, we treat lists as non-immortal.\nlist_rprimitive: Final = RPrimitive(\n    \"builtins.list\", is_unboxed=False, is_refcounted=True, may_be_immortal=False\n)\n\n# Python dict object (or an instance of a subclass of dict).\ndict_rprimitive: Final = RPrimitive(\"builtins.dict\", is_unboxed=False, is_refcounted=True)\n\n# Python set object (or an instance of a subclass of set).\nset_rprimitive: Final = RPrimitive(\"builtins.set\", is_unboxed=False, is_refcounted=True)\n\n# Python frozenset object (or an instance of a subclass of frozenset).\nfrozenset_rprimitive: Final = RPrimitive(\n    \"builtins.frozenset\", is_unboxed=False, is_refcounted=True\n)\n\n# Python str object. At the C layer, str is referred to as unicode\n# (PyUnicode).\nstr_rprimitive: Final = RPrimitive(\"builtins.str\", is_unboxed=False, is_refcounted=True)\n\n# Python bytes object.\nbytes_rprimitive: Final = RPrimitive(\"builtins.bytes\", is_unboxed=False, is_refcounted=True)\n\n# Python bytearray object.\nbytearray_rprimitive: Final = RPrimitive(\n    \"builtins.bytearray\", is_unboxed=False, is_refcounted=True\n)\n\n# Tuple of an arbitrary length (corresponds to Tuple[t, ...], with\n# explicit '...').\ntuple_rprimitive: Final = RPrimitive(\"builtins.tuple\", is_unboxed=False, is_refcounted=True)\n\n# Python range object.\nrange_rprimitive: Final = RPrimitive(\"builtins.range\", is_unboxed=False, is_refcounted=True)\n\nKNOWN_NATIVE_TYPES: Final = {\n    name: RPrimitive(name, is_unboxed=False, is_refcounted=True, dependencies=(LIBRT_STRINGS,))\n    for name in [\n        \"librt.internal.WriteBuffer\",\n        \"librt.internal.ReadBuffer\",\n        \"librt.strings.BytesWriter\",\n        \"librt.strings.StringWriter\",\n    ]\n}\n\nbytes_writer_rprimitive: Final = KNOWN_NATIVE_TYPES[\"librt.strings.BytesWriter\"]\nstring_writer_rprimitive: Final = KNOWN_NATIVE_TYPES[\"librt.strings.StringWriter\"]\n\n\ndef is_native_rprimitive(rtype: RType) -> bool:\n    return isinstance(rtype, RPrimitive) and rtype.name in KNOWN_NATIVE_TYPES\n\n\ndef is_tagged(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is int_rprimitive or rtype is short_int_rprimitive\n\n\ndef is_any_int(rtype: RType) -> bool:\n    return is_tagged(rtype) or is_int32_rprimitive(rtype) or is_int64_rprimitive(rtype)\n\n\ndef is_int_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is int_rprimitive\n\n\ndef is_short_int_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is short_int_rprimitive\n\n\ndef is_int16_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is int16_rprimitive\n\n\ndef is_int32_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is int32_rprimitive or (\n        rtype is c_pyssize_t_rprimitive and rtype._ctype == \"int32_t\"\n    )\n\n\ndef is_int64_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is int64_rprimitive or (\n        rtype is c_pyssize_t_rprimitive and rtype._ctype == \"int64_t\"\n    )\n\n\ndef is_fixed_width_rtype(rtype: RType) -> TypeGuard[RPrimitive]:\n    return (\n        is_int64_rprimitive(rtype)\n        or is_int32_rprimitive(rtype)\n        or is_int16_rprimitive(rtype)\n        or is_uint8_rprimitive(rtype)\n    )\n\n\ndef is_uint8_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is uint8_rprimitive\n\n\ndef is_uint32_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is uint32_rprimitive\n\n\ndef is_uint64_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is uint64_rprimitive\n\n\ndef is_c_py_ssize_t_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is c_pyssize_t_rprimitive\n\n\ndef is_pointer_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return rtype is pointer_rprimitive\n\n\ndef is_float_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.float\"\n\n\ndef is_bool_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.bool\"\n\n\ndef is_bit_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"bit\"\n\n\ndef is_bool_or_bit_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return is_bool_rprimitive(rtype) or is_bit_rprimitive(rtype)\n\n\ndef is_object_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.object\"\n\n\ndef is_none_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.None\"\n\n\ndef is_list_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.list\"\n\n\ndef is_dict_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.dict\"\n\n\ndef is_set_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.set\"\n\n\ndef is_frozenset_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.frozenset\"\n\n\ndef is_str_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.str\"\n\n\ndef is_bytes_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.bytes\"\n\n\ndef is_bytearray_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.bytearray\"\n\n\ndef is_tuple_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.tuple\"\n\n\ndef is_range_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and rtype.name == \"builtins.range\"\n\n\ndef is_sequence_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return isinstance(rtype, RPrimitive) and (\n        is_list_rprimitive(rtype)\n        or is_tuple_rprimitive(rtype)\n        or is_str_rprimitive(rtype)\n        or is_bytes_rprimitive(rtype)\n        or is_bytearray_rprimitive(rtype)\n    )\n\n\ndef is_immutable_rprimitive(rtype: RType) -> TypeGuard[RPrimitive]:\n    return (\n        is_str_rprimitive(rtype)\n        or is_bytes_rprimitive(rtype)\n        or is_tuple_rprimitive(rtype)\n        or is_frozenset_rprimitive(rtype)\n    )\n\n\nclass TupleNameVisitor(RTypeVisitor[str]):\n    \"\"\"Produce a tuple name based on the concrete representations of types.\"\"\"\n\n    def visit_rinstance(self, t: RInstance) -> str:\n        return \"O\"\n\n    def visit_rvec(self, t: RVec) -> str:\n        if isinstance(t.item_type, RVec):\n            # All nested vecs share a representation\n            return \"Vv\"\n        return \"V\" + t.item_type.accept(self)\n\n    def visit_runion(self, t: RUnion) -> str:\n        return \"O\"\n\n    def visit_rprimitive(self, t: RPrimitive) -> str:\n        if t._ctype == \"CPyTagged\":\n            return \"I\"\n        elif t._ctype == \"char\":\n            return \"C\"\n        elif t._ctype == \"int64_t\":\n            return \"8\"  # \"8 byte integer\"\n        elif t._ctype == \"int32_t\":\n            return \"4\"  # \"4 byte integer\"\n        elif t._ctype == \"int16_t\":\n            return \"2\"  # \"2 byte integer\"\n        elif t._ctype == \"uint8_t\":\n            return \"U1\"  # \"1 byte unsigned integer\"\n        elif t._ctype == \"double\":\n            return \"F\"\n        assert not t.is_unboxed, f\"{t} unexpected unboxed type\"\n        return \"O\"\n\n    def visit_rtuple(self, t: RTuple) -> str:\n        parts = [elem.accept(self) for elem in t.types]\n        return \"T{}{}\".format(len(parts), \"\".join(parts))\n\n    def visit_rstruct(self, t: RStruct) -> str:\n        if t.name == \"VecNestedBufItem\":\n            return \"Vi\"\n        assert False, \"RStruct not supported in tuple\"\n\n    def visit_rarray(self, t: RArray) -> str:\n        assert False, \"RArray not supported in tuple\"\n\n    def visit_rvoid(self, t: RVoid) -> str:\n        assert False, \"rvoid in tuple?\"\n\n\n@final\nclass RTuple(RType):\n    \"\"\"Fixed-length unboxed tuple (represented as a C struct).\n\n    These are used to represent mypy TupleType values (fixed-length\n    Python tuples). Since this is unboxed, the identity of a tuple\n    object is not preserved within compiled code. If the identity of a\n    tuple is important, or there is a need to have multiple references\n    to a single tuple object, a variable-length tuple should be used\n    (tuple_rprimitive or Tuple[T, ...]  with explicit '...'), as they\n    are boxed.\n\n    These aren't immutable. However, user code won't be able to mutate\n    individual tuple items.\n    \"\"\"\n\n    is_unboxed = True\n\n    def __init__(self, types: list[RType]) -> None:\n        self.name = \"tuple\"\n        self.types = tuple(types)\n        self.is_refcounted = any(t.is_refcounted for t in self.types)\n        # Generate a unique id which is used in naming corresponding C identifiers.\n        # This is necessary since C does not have anonymous structural type equivalence\n        # in the same way python can just assign a Tuple[int, bool] to a Tuple[int, bool].\n        self.unique_id = self.accept(TupleNameVisitor())\n        # Nominally the max c length is 31 chars, but I'm not honestly worried about this.\n        self.struct_name = f\"tuple_{self.unique_id}\"\n        self._ctype = f\"{self.struct_name}\"\n        self.error_overlap = all(t.error_overlap for t in self.types) and bool(self.types)\n\n    def accept(self, visitor: RTypeVisitor[T]) -> T:\n        return visitor.visit_rtuple(self)\n\n    @property\n    def may_be_immortal(self) -> bool:\n        return False\n\n    def __str__(self) -> str:\n        return \"tuple[%s]\" % \", \".join(str(typ) for typ in self.types)\n\n    def __repr__(self) -> str:\n        return \"<RTuple %s>\" % \", \".join(repr(typ) for typ in self.types)\n\n    def __eq__(self, other: object) -> TypeGuard[RTuple]:\n        return isinstance(other, RTuple) and self.types == other.types\n\n    def __hash__(self) -> int:\n        return hash((self.name, self.types))\n\n    def serialize(self) -> JsonDict:\n        types = [x.serialize() for x in self.types]\n        return {\".class\": \"RTuple\", \"types\": types}\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RTuple:\n        types = [deserialize_type(t, ctx) for t in data[\"types\"]]\n        return RTuple(types)\n\n\n# Exception tuple: (exception class, exception instance, traceback object)\nexc_rtuple = RTuple([object_rprimitive, object_rprimitive, object_rprimitive])\n\n# Dictionary iterator tuple: (should continue, internal offset, key, value)\n# See mypyc.irbuild.for_helpers.ForDictionaryCommon for more details.\ndict_next_rtuple_pair = RTuple(\n    [bool_rprimitive, short_int_rprimitive, object_rprimitive, object_rprimitive]\n)\n# Same as above but just for key or value.\ndict_next_rtuple_single = RTuple([bool_rprimitive, short_int_rprimitive, object_rprimitive])\n\n\ndef compute_rtype_alignment(typ: RType) -> int:\n    \"\"\"Compute alignment of a given type based on platform alignment rule\"\"\"\n    platform_alignment = PLATFORM_SIZE\n    if isinstance(typ, RPrimitive):\n        return typ.size\n    elif isinstance(typ, RInstance):\n        return platform_alignment\n    elif isinstance(typ, RUnion):\n        return platform_alignment\n    elif isinstance(typ, RArray):\n        return compute_rtype_alignment(typ.item_type)\n    else:\n        if isinstance(typ, RTuple):\n            items = list(typ.types)\n        elif isinstance(typ, RStruct):\n            items = typ.types\n        else:\n            assert False, \"invalid rtype for computing alignment\"\n        max_alignment = max(compute_rtype_alignment(item) for item in items)\n        return max_alignment\n\n\ndef compute_rtype_size(typ: RType) -> int:\n    \"\"\"Compute unaligned size of rtype\"\"\"\n    if isinstance(typ, RPrimitive):\n        return typ.size\n    elif isinstance(typ, RTuple):\n        return compute_aligned_offsets_and_size(list(typ.types))[1]\n    elif isinstance(typ, RUnion):\n        return PLATFORM_SIZE\n    elif isinstance(typ, RStruct):\n        return compute_aligned_offsets_and_size(typ.types)[1]\n    elif isinstance(typ, RInstance):\n        return PLATFORM_SIZE\n    elif isinstance(typ, RArray):\n        alignment = compute_rtype_alignment(typ)\n        aligned_size = (compute_rtype_size(typ.item_type) + (alignment - 1)) & ~(alignment - 1)\n        return aligned_size * typ.length\n    else:\n        assert False, \"invalid rtype for computing size\"\n\n\ndef compute_aligned_offsets_and_size(types: list[RType]) -> tuple[list[int], int]:\n    \"\"\"Compute offsets and total size of a list of types after alignment\n\n    Note that the types argument are types of values that are stored\n    sequentially with platform default alignment.\n    \"\"\"\n    unaligned_sizes = [compute_rtype_size(typ) for typ in types]\n    alignments = [compute_rtype_alignment(typ) for typ in types]\n\n    current_offset = 0\n    offsets = []\n    final_size = 0\n    for i in range(len(unaligned_sizes)):\n        offsets.append(current_offset)\n        if i + 1 < len(unaligned_sizes):\n            cur_size = unaligned_sizes[i]\n            current_offset += cur_size\n            next_alignment = alignments[i + 1]\n            # compute aligned offset,\n            # check https://en.wikipedia.org/wiki/Data_structure_alignment for more information\n            current_offset = (current_offset + (next_alignment - 1)) & -next_alignment\n        else:\n            struct_alignment = max(alignments)\n            final_size = current_offset + unaligned_sizes[i]\n            final_size = (final_size + (struct_alignment - 1)) & -struct_alignment\n    return offsets, final_size\n\n\n@final\nclass RStruct(RType):\n    \"\"\"C struct type\"\"\"\n\n    def __init__(self, name: str, names: list[str], types: list[RType]) -> None:\n        self.name = name\n        self.names = names\n        self.types = types\n        self.is_refcounted = any(t.is_refcounted for t in self.types)\n\n        # generate dummy names\n        if len(self.names) < len(self.types):\n            for i in range(len(self.types) - len(self.names)):\n                self.names.append(\"_item\" + str(i))\n        self.offsets, self.size = compute_aligned_offsets_and_size(types)\n        self._ctype = name\n\n    def field_type(self, name: str) -> RType:\n        for n, t in zip(self.names, self.types):\n            if n == name:\n                return t\n        assert False, f\"{self.name} has no field '{name}'\"\n\n    def accept(self, visitor: RTypeVisitor[T]) -> T:\n        return visitor.visit_rstruct(self)\n\n    @property\n    def may_be_immortal(self) -> bool:\n        return False\n\n    def __str__(self) -> str:\n        # if not tuple(unnamed structs)\n        return \"{}{{{}}}\".format(\n            self.name,\n            \", \".join(name + \":\" + str(typ) for name, typ in zip(self.names, self.types)),\n        )\n\n    def __repr__(self) -> str:\n        return \"<RStruct {}{{{}}}>\".format(\n            self.name,\n            \", \".join(name + \":\" + repr(typ) for name, typ in zip(self.names, self.types)),\n        )\n\n    def __eq__(self, other: object) -> TypeGuard[RStruct]:\n        return (\n            isinstance(other, RStruct)\n            and self.name == other.name\n            and self.names == other.names\n            and self.types == other.types\n        )\n\n    def __hash__(self) -> int:\n        return hash((self.name, tuple(self.names), tuple(self.types)))\n\n    def serialize(self) -> JsonDict:\n        assert False\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RStruct:\n        assert False\n\n\n@final\nclass RInstance(RType):\n    \"\"\"Instance of user-defined class (compiled to C extension class).\n\n    The runtime representation is 'PyObject *', and these are always\n    boxed and thus reference-counted.\n\n    These support fast method calls and fast attribute access using\n    vtables, and they usually use a dict-free, struct-based\n    representation of attributes. Method calls and attribute access\n    can skip the vtable if we know that there is no overriding.\n\n    These are also sometimes called 'native' types, since these have\n    the most efficient representation and ops (along with certain\n    RPrimitive types and RTuple).\n    \"\"\"\n\n    is_unboxed = False\n\n    def __init__(self, class_ir: ClassIR) -> None:\n        # name is used for formatting the name in messages and debug output\n        # so we want the fullname for precision.\n        self.name = class_ir.fullname\n        self.class_ir = class_ir\n        self._ctype = \"PyObject *\"\n\n    def accept(self, visitor: RTypeVisitor[T]) -> T:\n        return visitor.visit_rinstance(self)\n\n    @property\n    def may_be_immortal(self) -> bool:\n        return False\n\n    def struct_name(self, names: NameGenerator) -> str:\n        return self.class_ir.struct_name(names)\n\n    def getter_index(self, name: str) -> int:\n        return self.class_ir.vtable_entry(name)\n\n    def setter_index(self, name: str) -> int:\n        return self.getter_index(name) + 1\n\n    def method_index(self, name: str) -> int:\n        return self.class_ir.vtable_entry(name)\n\n    def attr_type(self, name: str) -> RType:\n        return self.class_ir.attr_type(name)\n\n    def __repr__(self) -> str:\n        return \"<RInstance %s>\" % self.name\n\n    def __eq__(self, other: object) -> TypeGuard[RInstance]:\n        return isinstance(other, RInstance) and other.name == self.name\n\n    def __hash__(self) -> int:\n        return hash(self.name)\n\n    def serialize(self) -> str:\n        return self.name\n\n\n@final\nclass RVec(RType):\n    \"\"\"librt.vecs.vec[T]\"\"\"\n\n    is_unboxed = True\n\n    def __init__(self, item_type: RType) -> None:\n        self.name = \"vec[%s]\" % item_type\n        self.item_type = item_type\n        self.names = [\"len\", \"buf\"]\n        self.dependencies = (LIBRT_VECS,)\n        if isinstance(item_type, RUnion):\n            non_opt = optional_value_type(item_type)\n        else:\n            non_opt = item_type\n        if item_type in vec_buf_types:\n            self._ctype = vec_c_types[item_type]\n            self.buf_type = vec_buf_types[item_type]\n            self.types = [c_pyssize_t_rprimitive, self.buf_type]\n        elif isinstance(non_opt, RVec):\n            self._ctype = \"VecNested\"\n            self.types = [c_pyssize_t_rprimitive, VecTBufObject]\n            self.buf_type = VecNestedBufObject\n        else:\n            self._ctype = \"VecT\"\n            self.types = [c_pyssize_t_rprimitive, VecTBufObject]\n            self.buf_type = VecTBufObject\n\n    @property\n    def may_be_immortal(self) -> bool:\n        return False\n\n    def unwrap_item_type(self) -> RPrimitive | RInstance:\n        \"\"\"Return the non-optional value (non-vec) item type in a potentially nested vec.\"\"\"\n        item_type = self.item_type\n        while True:\n            if isinstance(item_type, RUnion):\n                value_type = optional_value_type(item_type)\n                assert value_type is not None\n                item_type = value_type\n            elif isinstance(item_type, RVec):\n                item_type = item_type.item_type\n            elif isinstance(item_type, (RPrimitive, RInstance)):\n                return item_type\n            else:\n                assert False, f\"unexpected item type: {self.item_type}\"\n\n    def is_optional(self) -> bool:\n        item_type = self.item_type\n        if isinstance(item_type, RUnion):\n            return True\n        elif isinstance(item_type, RVec):\n            return item_type.is_optional()\n        return False\n\n    def depth(self) -> int:\n        item_type = self.item_type\n        if isinstance(item_type, RUnion):\n            value_type = optional_value_type(item_type)\n            assert value_type is not None\n            item_type = value_type\n        if isinstance(item_type, RVec):\n            return 1 + item_type.depth()\n        return 0\n\n    def field_type(self, name: str) -> RType:\n        if name == \"len\":\n            return c_pyssize_t_rprimitive\n        elif name == \"buf\":\n            return object_rprimitive\n        assert False, f\"RVec has no field '{name}'\"\n\n    def accept(self, visitor: RTypeVisitor[T]) -> T:\n        return visitor.visit_rvec(self)\n\n    def __str__(self) -> str:\n        if self.is_optional() and self.depth() == 0:\n            type_str = f\"{self.unwrap_item_type()} | None\"\n        else:\n            type_str = str(self.item_type)\n        return f\"vec[{type_str}]\"\n\n    def __repr__(self) -> str:\n        return \"<RVec[%s]>\" % self.item_type\n\n    def __eq__(self, other: object) -> bool:\n        return isinstance(other, RVec) and other.item_type == self.item_type\n\n    def __hash__(self) -> int:\n        return hash(self.item_type) ^ 1\n\n    def serialize(self) -> JsonDict:\n        return {\".class\": \"RVec\", \"item_type\": self.item_type.serialize()}\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RVec:\n        return RVec(deserialize_type(data[\"item_type\"], ctx))\n\n\n@final\nclass RUnion(RType):\n    \"\"\"union[x, ..., y]\"\"\"\n\n    is_unboxed = False\n\n    def __init__(self, items: list[RType]) -> None:\n        self.name = \"union\"\n        self.items = items\n        self.items_set = frozenset(items)\n        self._ctype = \"PyObject *\"\n\n    @staticmethod\n    def make_simplified_union(items: list[RType]) -> RType:\n        \"\"\"Return a normalized union that covers the given items.\n\n        Flatten nested unions and remove duplicate items.\n\n        Overlapping items are *not* simplified. For example,\n        [object, str] will not be simplified.\n        \"\"\"\n        items = flatten_nested_unions(items)\n        assert items\n\n        unique_items = dict.fromkeys(items)\n        if len(unique_items) > 1:\n            return RUnion(list(unique_items))\n        else:\n            return next(iter(unique_items))\n\n    def accept(self, visitor: RTypeVisitor[T]) -> T:\n        return visitor.visit_runion(self)\n\n    @property\n    def may_be_immortal(self) -> bool:\n        return any(item.may_be_immortal for item in self.items)\n\n    def __repr__(self) -> str:\n        return \"<RUnion %s>\" % \", \".join(str(item) for item in self.items)\n\n    def __str__(self) -> str:\n        return \"union[%s]\" % \", \".join(str(item) for item in self.items)\n\n    # We compare based on the set because order in a union doesn't matter\n    def __eq__(self, other: object) -> TypeGuard[RUnion]:\n        return isinstance(other, RUnion) and self.items_set == other.items_set\n\n    def __hash__(self) -> int:\n        return hash((\"union\", self.items_set))\n\n    def serialize(self) -> JsonDict:\n        types = [x.serialize() for x in self.items]\n        return {\".class\": \"RUnion\", \"types\": types}\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RUnion:\n        types = [deserialize_type(t, ctx) for t in data[\"types\"]]\n        return RUnion(types)\n\n\ndef flatten_nested_unions(types: list[RType]) -> list[RType]:\n    if not any(isinstance(t, RUnion) for t in types):\n        return types  # Fast path\n\n    flat_items: list[RType] = []\n    for t in types:\n        if isinstance(t, RUnion):\n            flat_items.extend(flatten_nested_unions(t.items))\n        else:\n            flat_items.append(t)\n    return flat_items\n\n\ndef optional_value_type(rtype: RType) -> RType | None:\n    \"\"\"If rtype is the union of none_rprimitive and another type X, return X.\n\n    Otherwise, return None.\n    \"\"\"\n    if isinstance(rtype, RUnion) and len(rtype.items) == 2:\n        if rtype.items[0] == none_rprimitive:\n            return rtype.items[1]\n        elif rtype.items[1] == none_rprimitive:\n            return rtype.items[0]\n    return None\n\n\ndef is_optional_type(rtype: RType) -> TypeGuard[RUnion]:\n    \"\"\"Is rtype an optional type with exactly two union items?\"\"\"\n    return optional_value_type(rtype) is not None\n\n\n@final\nclass RArray(RType):\n    \"\"\"Fixed-length C array type (for example, int[5]).\n\n    Note that the implementation is a bit limited, and these can basically\n    be only used for local variables that are initialized in one location.\n    \"\"\"\n\n    def __init__(self, item_type: RType, length: int) -> None:\n        self.item_type = item_type\n        # Number of items\n        self.length = length\n        self.is_refcounted = False\n\n    def accept(self, visitor: RTypeVisitor[T]) -> T:\n        return visitor.visit_rarray(self)\n\n    @property\n    def may_be_immortal(self) -> bool:\n        return False\n\n    def __str__(self) -> str:\n        return f\"{self.item_type}[{self.length}]\"\n\n    def __repr__(self) -> str:\n        return f\"<RArray {self.item_type!r}[{self.length}]>\"\n\n    def __eq__(self, other: object) -> TypeGuard[RArray]:\n        return (\n            isinstance(other, RArray)\n            and self.item_type == other.item_type\n            and self.length == other.length\n        )\n\n    def __hash__(self) -> int:\n        return hash((self.item_type, self.length))\n\n    def serialize(self) -> JsonDict:\n        assert False\n\n    @classmethod\n    def deserialize(cls, data: JsonDict, ctx: DeserMaps) -> RArray:\n        assert False\n\n\nPyObject = RStruct(\n    name=\"PyObject\",\n    names=[\"ob_refcnt\", \"ob_type\"],\n    types=[c_pyssize_t_rprimitive, pointer_rprimitive],\n)\n\nPyVarObject = RStruct(\n    name=\"PyVarObject\", names=[\"ob_base\", \"ob_size\"], types=[PyObject, c_pyssize_t_rprimitive]\n)\n\nsetentry = RStruct(\n    name=\"setentry\", names=[\"key\", \"hash\"], types=[pointer_rprimitive, c_pyssize_t_rprimitive]\n)\n\nsmalltable = RStruct(name=\"smalltable\", names=[], types=[setentry] * 8)\n\nPySetObject = RStruct(\n    name=\"PySetObject\",\n    names=[\n        \"ob_base\",\n        \"fill\",\n        \"used\",\n        \"mask\",\n        \"table\",\n        \"hash\",\n        \"finger\",\n        \"smalltable\",\n        \"weakreflist\",\n    ],\n    types=[\n        PyObject,\n        c_pyssize_t_rprimitive,\n        c_pyssize_t_rprimitive,\n        c_pyssize_t_rprimitive,\n        pointer_rprimitive,\n        c_pyssize_t_rprimitive,\n        c_pyssize_t_rprimitive,\n        smalltable,\n        pointer_rprimitive,\n    ],\n)\n\nPyListObject = RStruct(\n    name=\"PyListObject\",\n    names=[\"ob_base\", \"ob_item\", \"allocated\"],\n    types=[PyVarObject, pointer_rprimitive, c_pyssize_t_rprimitive],\n)\n\n\ndef check_native_int_range(rtype: RPrimitive, n: int) -> bool:\n    \"\"\"Is n within the range of a native, fixed-width int type?\n\n    Assume the type is a fixed-width int type.\n    \"\"\"\n    if not rtype.is_signed:\n        return 0 <= n < (1 << (8 * rtype.size))\n    else:\n        limit = 1 << (rtype.size * 8 - 1)\n        return -limit <= n < limit\n\n\n# Buffers for vec item types that have a packed representation\n#\n# Note that the 'items' fields are variable-length arrays, and mypyc IR isn't\n# able to represent these, so the field type is omitted for now.\n\nVecI64BufObject = RStruct(\n    name=\"VecI64BufObject\",\n    names=[\"ob_base\", \"len\", \"items\"],\n    types=[PyVarObject, int64_rprimitive],\n)\n\nVecI32BufObject = RStruct(\n    name=\"VecI32BufObject\",\n    names=[\"ob_base\", \"len\", \"items\"],\n    types=[PyVarObject, int64_rprimitive],\n)\n\nVecI16BufObject = RStruct(\n    name=\"VecI16BufObject\",\n    names=[\"ob_base\", \"len\", \"items\"],\n    types=[PyVarObject, int64_rprimitive],\n)\n\nVecU8BufObject = RStruct(\n    name=\"VecU8BufObject\", names=[\"ob_base\", \"len\", \"items\"], types=[PyVarObject, int64_rprimitive]\n)\n\nVecFloatBufObject = RStruct(\n    name=\"VecFloatBufObject\",\n    names=[\"ob_base\", \"len\", \"items\"],\n    types=[PyVarObject, int64_rprimitive],\n)\n\nVecBoolBufObject = RStruct(\n    name=\"VecBoolBufObject\",\n    names=[\"ob_base\", \"len\", \"items\"],\n    types=[PyVarObject, int64_rprimitive],\n)\n\n\n# Struct type for vec[i64] (in most cases use RVec instead).\nVecI64 = RStruct(\n    name=\"VecI64\", names=[\"len\", \"buf\"], types=[c_pyssize_t_rprimitive, object_rprimitive]\n)\n\n\n# Buffer for vec[t]\nVecTBufObject = RStruct(\n    name=\"VecTBufObject\",\n    names=[\"ob_base\", \"item_type\", \"items\"],\n    types=[PyVarObject, c_pyssize_t_rprimitive, object_rprimitive],\n)\n\n# Struct type for vec[t] (in most cases use RVec instead).\nVecT = RStruct(\n    name=\"VecT\", names=[\"len\", \"buf\"], types=[c_pyssize_t_rprimitive, object_rprimitive]\n)\n\nVecNestedBufItem = RStruct(\n    name=\"VecNestedBufItem\",\n    names=[\"len\", \"buf\"],\n    types=[c_pyssize_t_rprimitive, object_non_refcounted_rprimitive],\n)\n\n# Buffer for vec[vec[t]]\nVecNestedBufObject = RStruct(\n    name=\"VecNestedBufObject\",\n    names=[\"ob_base\", \"item_type\", \"depth\", \"optionals\", \"items\"],\n    types=[\n        PyVarObject,\n        c_pyssize_t_rprimitive,\n        int32_rprimitive,\n        int32_rprimitive,\n        VecNestedBufItem,\n    ],\n)\n\n# Struct type for vec[vec[...]] (in most cases use RVec instead).\nVecNested = RStruct(\n    name=\"VecNested\", names=[\"len\", \"buf\"], types=[c_pyssize_t_rprimitive, object_rprimitive]\n)\n\nVecNestedBufObject_rprimitive = RPrimitive(\n    \"VecNestedBufObject_ptr\", is_unboxed=False, is_refcounted=True, ctype=\"VecNestedBufObject *\"\n)\n\nVecNestedPopResult = RStruct(\n    name=\"VecNestedPopResult\", names=[\"vec\", \"item\"], types=[VecNested, VecNestedBufItem]\n)\n\n\nvec_buf_types: Final[dict[RType, RStruct]] = {\n    int64_rprimitive: VecI64BufObject,\n    int32_rprimitive: VecI32BufObject,\n    int16_rprimitive: VecI16BufObject,\n    uint8_rprimitive: VecU8BufObject,\n    float_rprimitive: VecFloatBufObject,\n    bool_rprimitive: VecBoolBufObject,\n}\n\nvec_c_types: Final[dict[RType, str]] = {\n    int64_rprimitive: \"VecI64\",\n    int32_rprimitive: \"VecI32\",\n    int16_rprimitive: \"VecI16\",\n    uint8_rprimitive: \"VecU8\",\n    float_rprimitive: \"VecFloat\",\n    bool_rprimitive: \"VecBool\",\n}\n\nvec_api_fields: Final[dict[RType, str]] = {\n    int64_rprimitive: \"i64\",\n    int32_rprimitive: \"i32\",\n    int16_rprimitive: \"i16\",\n    uint8_rprimitive: \"u8\",\n    float_rprimitive: \"float_\",\n    bool_rprimitive: \"bool_\",\n}\n\nvec_api_by_item_type: Final[dict[RType, str]] = {\n    int64_rprimitive: \"VecI64Api\",\n    int32_rprimitive: \"VecI32Api\",\n    int16_rprimitive: \"VecI16Api\",\n    uint8_rprimitive: \"VecU8Api\",\n    float_rprimitive: \"VecFloatApi\",\n    bool_rprimitive: \"VecBoolApi\",\n}\n\n# These are special item type constants used in nested vecs to represent\n# item types with specialized representations. These must match definitions\n# in the vecs module (see VEC_ITEM_TYPE_I64 etc.).\nvec_item_type_tags: Final[dict[RType, int]] = {\n    int64_rprimitive: 2,\n    int32_rprimitive: 6,\n    int16_rprimitive: 10,\n    uint8_rprimitive: 14,\n    float_rprimitive: 18,\n    bool_rprimitive: 22,\n}\n"
  },
  {
    "path": "mypyc/irbuild/__init__.py",
    "content": ""
  },
  {
    "path": "mypyc/irbuild/ast_helpers.py",
    "content": "\"\"\"IRBuilder AST transform helpers shared between expressions and statements.\n\nShared code that is tightly coupled to mypy ASTs can be put here instead of\nmaking mypyc.irbuild.builder larger.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import (\n    LDEF,\n    BytesExpr,\n    ComparisonExpr,\n    Expression,\n    FloatExpr,\n    IntExpr,\n    MemberExpr,\n    NameExpr,\n    OpExpr,\n    StrExpr,\n    UnaryExpr,\n    Var,\n)\nfrom mypyc.ir.ops import BasicBlock\nfrom mypyc.ir.rtypes import is_fixed_width_rtype, is_tagged\nfrom mypyc.irbuild.builder import IRBuilder\nfrom mypyc.irbuild.constant_fold import constant_fold_expr\n\n\ndef process_conditional(\n    self: IRBuilder, e: Expression, true: BasicBlock, false: BasicBlock\n) -> None:\n    if isinstance(e, OpExpr) and e.op in [\"and\", \"or\"]:\n        if e.op == \"and\":\n            # Short circuit 'and' in a conditional context.\n            new = BasicBlock()\n            process_conditional(self, e.left, new, false)\n            self.activate_block(new)\n            process_conditional(self, e.right, true, false)\n        else:\n            # Short circuit 'or' in a conditional context.\n            new = BasicBlock()\n            process_conditional(self, e.left, true, new)\n            self.activate_block(new)\n            process_conditional(self, e.right, true, false)\n    elif isinstance(e, UnaryExpr) and e.op == \"not\":\n        process_conditional(self, e.expr, false, true)\n    else:\n        res = maybe_process_conditional_comparison(self, e, true, false)\n        if res:\n            return\n        # Catch-all for arbitrary expressions.\n        reg = self.accept(e)\n        self.add_bool_branch(reg, true, false)\n\n\ndef maybe_process_conditional_comparison(\n    self: IRBuilder, e: Expression, true: BasicBlock, false: BasicBlock\n) -> bool:\n    \"\"\"Transform simple tagged integer comparisons in a conditional context.\n\n    Return True if the operation is supported (and was transformed). Otherwise,\n    do nothing and return False.\n\n    Args:\n        self: IR form Builder\n        e: Arbitrary expression\n        true: Branch target if comparison is true\n        false: Branch target if comparison is false\n    \"\"\"\n    if not isinstance(e, ComparisonExpr) or len(e.operands) != 2:\n        return False\n    ltype = self.node_type(e.operands[0])\n    rtype = self.node_type(e.operands[1])\n    if not (\n        (is_tagged(ltype) or is_fixed_width_rtype(ltype))\n        and (is_tagged(rtype) or is_fixed_width_rtype(rtype))\n    ):\n        return False\n    op = e.operators[0]\n    if op not in (\"==\", \"!=\", \"<\", \"<=\", \">\", \">=\"):\n        return False\n    left_expr = e.operands[0]\n    right_expr = e.operands[1]\n    borrow_left = is_borrow_friendly_expr(self, right_expr)\n    left = self.accept(left_expr, can_borrow=borrow_left)\n    right = self.accept(right_expr, can_borrow=True)\n    if is_fixed_width_rtype(ltype) or is_fixed_width_rtype(rtype):\n        if not is_fixed_width_rtype(ltype):\n            left = self.coerce(left, rtype, e.line)\n        elif not is_fixed_width_rtype(rtype):\n            right = self.coerce(right, ltype, e.line)\n        reg = self.binary_op(left, right, op, e.line)\n        self.builder.flush_keep_alives(e.line)\n        self.add_bool_branch(reg, true, false)\n    else:\n        # \"left op right\" for two tagged integers\n        reg = self.builder.binary_op(left, right, op, e.line)\n        self.flush_keep_alives(e.line)\n        self.add_bool_branch(reg, true, false)\n    return True\n\n\ndef is_borrow_friendly_expr(self: IRBuilder, expr: Expression) -> bool:\n    \"\"\"Can the result of the expression borrowed temporarily?\n\n    Borrowing means keeping a reference without incrementing the reference count.\n    \"\"\"\n    if isinstance(expr, (IntExpr, FloatExpr, StrExpr, BytesExpr)):\n        # Literals are immortal and can always be borrowed\n        return True\n    if (\n        isinstance(expr, (UnaryExpr, OpExpr, NameExpr, MemberExpr))\n        and constant_fold_expr(self, expr) is not None\n    ):\n        # Literal expressions are similar to literals\n        return True\n    if isinstance(expr, NameExpr):\n        if isinstance(expr.node, Var) and expr.kind == LDEF:\n            # Local variable reference can be borrowed\n            return True\n    if isinstance(expr, MemberExpr) and self.is_native_attr_ref(expr):\n        return True\n    return False\n"
  },
  {
    "path": "mypyc/irbuild/builder.py",
    "content": "\"\"\"Builder class to transform a mypy AST to the IR form.\n\nSee the docstring of class IRBuilder for more information.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable, Iterator, Sequence\nfrom contextlib import contextmanager\nfrom typing import Any, Final, overload\n\nfrom mypy.build import Graph\nfrom mypy.maptype import map_instance_to_supertype\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    GDEF,\n    LDEF,\n    PARAM_SPEC_KIND,\n    TYPE_VAR_KIND,\n    TYPE_VAR_TUPLE_KIND,\n    ArgKind,\n    CallExpr,\n    Decorator,\n    Expression,\n    FuncDef,\n    IndexExpr,\n    IntExpr,\n    Lvalue,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    OpExpr,\n    OverloadedFuncDef,\n    RefExpr,\n    StarExpr,\n    Statement,\n    SymbolNode,\n    TupleExpr,\n    TypeAlias,\n    TypeInfo,\n    TypeParam,\n    Var,\n)\nfrom mypy.types import (\n    AnyType,\n    DeletedType,\n    Instance,\n    ProperType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeOfAny,\n    TypeVarLikeType,\n    UninhabitedType,\n    UnionType,\n    get_proper_type,\n)\nfrom mypy.util import module_prefix, split_target\nfrom mypy.visitor import ExpressionVisitor, StatementVisitor\nfrom mypyc.common import BITMAP_BITS, GENERATOR_ATTRIBUTE_PREFIX, SELF_NAME, TEMP_ATTR_NAME\nfrom mypyc.crash import catch_errors\nfrom mypyc.errors import Errors\nfrom mypyc.ir.class_ir import ClassIR, NonExtClassInfo\nfrom mypyc.ir.func_ir import INVALID_FUNC_DEF, FuncDecl, FuncIR, FuncSignature, RuntimeArg\nfrom mypyc.ir.ops import (\n    NAMESPACE_MODULE,\n    NAMESPACE_TYPE_VAR,\n    NO_TRACEBACK_LINE_NO,\n    Assign,\n    BasicBlock,\n    Branch,\n    Call,\n    ComparisonOp,\n    GetAttr,\n    InitStatic,\n    Integer,\n    IntOp,\n    LoadStatic,\n    MethodCall,\n    Op,\n    PrimitiveDescription,\n    RaiseStandardError,\n    Register,\n    SetAttr,\n    TupleGet,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RTuple,\n    RType,\n    RUnion,\n    RVec,\n    bitmap_rprimitive,\n    bool_rprimitive,\n    bytes_rprimitive,\n    c_pyssize_t_rprimitive,\n    dict_rprimitive,\n    int_rprimitive,\n    is_float_rprimitive,\n    is_list_rprimitive,\n    is_none_rprimitive,\n    is_object_rprimitive,\n    is_tagged,\n    is_tuple_rprimitive,\n    none_rprimitive,\n    object_rprimitive,\n    str_rprimitive,\n)\nfrom mypyc.irbuild.constant_fold import constant_fold_expr\nfrom mypyc.irbuild.context import FuncInfo, ImplicitClass\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\nfrom mypyc.irbuild.mapper import Mapper\nfrom mypyc.irbuild.nonlocalcontrol import (\n    BaseNonlocalControl,\n    GeneratorNonlocalControl,\n    LoopNonlocalControl,\n    NonlocalControl,\n)\nfrom mypyc.irbuild.prebuildvisitor import PreBuildVisitor\nfrom mypyc.irbuild.prepare import RegisterImplInfo\nfrom mypyc.irbuild.targets import (\n    AssignmentTarget,\n    AssignmentTargetAttr,\n    AssignmentTargetIndex,\n    AssignmentTargetRegister,\n    AssignmentTargetTuple,\n)\nfrom mypyc.irbuild.util import bytes_from_str, is_constant\nfrom mypyc.irbuild.vec import vec_set_item\nfrom mypyc.options import CompilerOptions\nfrom mypyc.primitives.dict_ops import dict_get_item_op, dict_set_item_op\nfrom mypyc.primitives.generic_ops import iter_op, next_op, py_setattr_op\nfrom mypyc.primitives.list_ops import list_get_item_unsafe_op, list_pop_last, to_list\nfrom mypyc.primitives.misc_ops import check_unpack_count_op, get_module_dict_op, import_op\nfrom mypyc.primitives.registry import CFunctionDescription, function_ops\nfrom mypyc.primitives.tuple_ops import tuple_get_item_unsafe_op\n\n# These int binary operations can borrow their operands safely, since the\n# primitives take this into consideration.\nint_borrow_friendly_op: Final = {\"+\", \"-\", \"==\", \"!=\", \"<\", \"<=\", \">\", \">=\"}\n\n\nclass IRVisitor(ExpressionVisitor[Value], StatementVisitor[None]):\n    pass\n\n\nclass UnsupportedException(Exception):\n    pass\n\n\nSymbolTarget = AssignmentTargetRegister | AssignmentTargetAttr\n\n\nclass IRBuilder:\n    \"\"\"Builder class used to construct mypyc IR from a mypy AST.\n\n    The IRBuilder class maintains IR transformation state and provides access\n    to various helpers used to implement the transform.\n\n    mypyc.irbuild.visitor.IRBuilderVisitor is used to dispatch based on mypy\n    AST node type to code that actually does the bulk of the work. For\n    example, expressions are transformed in mypyc.irbuild.expression and\n    functions are transformed in mypyc.irbuild.function.\n\n    Use the \"accept()\" method to translate individual mypy AST nodes to IR.\n    Other methods are used to generate IR for various lower-level operations.\n\n    This class wraps the lower-level LowLevelIRBuilder class, an instance\n    of which is available through the \"builder\" attribute. The low-level\n    builder class doesn't have any knowledge of the mypy AST. Wrappers for\n    some LowLevelIRBuilder method are provided for convenience, but others\n    can also be accessed via the \"builder\" attribute.\n\n    See also:\n     * The mypyc IR is defined in the mypyc.ir package.\n     * The top-level IR transform control logic is in mypyc.irbuild.main.\n    \"\"\"\n\n    def __init__(\n        self,\n        current_module: str,\n        types: dict[Expression, Type],\n        graph: Graph,\n        errors: Errors,\n        mapper: Mapper,\n        pbv: PreBuildVisitor,\n        visitor: IRVisitor,\n        options: CompilerOptions,\n        singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]],\n    ) -> None:\n        self.builder = LowLevelIRBuilder(errors, options)\n        self.builders = [self.builder]\n        self.symtables: list[dict[SymbolNode, SymbolTarget]] = [{}]\n        self.runtime_args: list[list[RuntimeArg]] = [[]]\n        self.function_name_stack: list[str] = []\n        self.class_ir_stack: list[ClassIR] = []\n        # Keep track of whether the next statement in a block is reachable\n        # or not, separately for each block nesting level\n        self.block_reachable_stack: list[bool] = [True]\n\n        self.current_module = current_module\n        self.mapper = mapper\n        self.types = types\n        self.graph = graph\n        self.ret_types: list[RType] = []\n        self.functions: list[FuncIR] = []\n        self.function_names: set[tuple[str | None, str]] = set()\n        self.classes: list[ClassIR] = []\n        self.final_names: list[tuple[str, RType]] = []\n        self.type_var_names: list[str] = []\n        self.callable_class_names: set[str] = set()\n        self.options = options\n\n        # These variables keep track of the number of lambdas, implicit indices, and implicit\n        # iterators instantiated so we avoid name conflicts. The indices and iterators are\n        # instantiated from for-loops.\n        self.lambda_counter = 0\n        self.temp_counter = 0\n\n        # These variables are populated from the first-pass PreBuildVisitor.\n        self.free_variables = pbv.free_variables\n        self.prop_setters = pbv.prop_setters\n        self.encapsulating_funcs = pbv.encapsulating_funcs\n        self.nested_fitems = pbv.nested_funcs.keys()\n        self.fdefs_to_decorators = pbv.funcs_to_decorators\n        self.module_import_groups = pbv.module_import_groups\n        self.comprehension_to_fitem = pbv.comprehension_to_fitem\n\n        self.singledispatch_impls = singledispatch_impls\n\n        self.visitor = visitor\n\n        # This list operates similarly to a function call stack for nested functions. Whenever a\n        # function definition begins to be generated, a FuncInfo instance is added to the stack,\n        # and information about that function (e.g. whether it is nested, its environment class to\n        # be generated) is stored in that FuncInfo instance. When the function is done being\n        # generated, its corresponding FuncInfo is popped off the stack.\n        self.fn_info = FuncInfo(INVALID_FUNC_DEF, \"\", \"\")\n        self.fn_infos: list[FuncInfo] = [self.fn_info]\n\n        # This list operates as a stack of constructs that modify the\n        # behavior of nonlocal control flow constructs.\n        self.nonlocal_control: list[NonlocalControl] = []\n\n        self.errors = errors\n        # Notionally a list of all of the modules imported by the\n        # module being compiled, but stored as an OrderedDict so we\n        # can also do quick lookups.\n        self.imports: dict[str, None] = {}\n\n        self.can_borrow = False\n\n    # High-level control\n\n    def set_module(self, module_name: str, module_path: str) -> None:\n        \"\"\"Set the name and path of the current module.\n\n        This must be called before transforming any AST nodes.\n        \"\"\"\n        self.module_name = module_name\n        self.module_path = module_path\n        self.builder.set_module(module_name, module_path)\n\n    @overload\n    def accept(self, node: Expression, *, can_borrow: bool = False) -> Value: ...\n\n    @overload\n    def accept(self, node: Statement) -> None: ...\n\n    def accept(self, node: Statement | Expression, *, can_borrow: bool = False) -> Value | None:\n        \"\"\"Transform an expression or a statement.\n\n        If can_borrow is true, prefer to generate a borrowed reference.\n        Borrowed references are faster since they don't require reference count\n        manipulation, but they are only safe to use in specific contexts.\n        \"\"\"\n        with self.catch_errors(node.line):\n            if isinstance(node, Expression):\n                old_can_borrow = self.can_borrow\n                self.can_borrow = can_borrow\n                try:\n                    res = node.accept(self.visitor)\n                    res = self.coerce(res, self.node_type(node), node.line)\n                # If we hit an error during compilation, we want to\n                # keep trying, so we can produce more error\n                # messages. Generate a temp of the right type to keep\n                # from causing more downstream trouble.\n                except UnsupportedException:\n                    res = Register(self.node_type(node))\n                self.can_borrow = old_can_borrow\n                if not can_borrow:\n                    self.flush_keep_alives(node.line)\n                return res\n            else:\n                try:\n                    node.accept(self.visitor)\n                except UnsupportedException:\n                    pass\n                return None\n\n    def flush_keep_alives(self, line: int) -> None:\n        self.builder.flush_keep_alives(line)\n\n    # Pass through methods for the most common low-level builder ops, for convenience.\n\n    def add(self, op: Op) -> Value:\n        return self.builder.add(op)\n\n    def goto(self, target: BasicBlock) -> None:\n        self.builder.goto(target)\n\n    def activate_block(self, block: BasicBlock) -> None:\n        self.builder.activate_block(block)\n\n    def goto_and_activate(self, block: BasicBlock) -> None:\n        self.builder.goto_and_activate(block)\n\n    def self(self) -> Register:\n        return self.builder.self()\n\n    def py_get_attr(self, obj: Value, attr: str, line: int) -> Value:\n        return self.builder.py_get_attr(obj, attr, line)\n\n    def load_str(self, value: str, line: int = -1) -> Value:\n        return self.builder.load_str(value, line)\n\n    def load_bytes_from_str_literal(self, value: str, line: int = -1) -> Value:\n        \"\"\"Load bytes object from a string literal.\n\n        The literal characters of BytesExpr (the characters inside b'')\n        are stored in BytesExpr.value, whose type is 'str' not 'bytes'.\n        Thus we perform a special conversion here.\n        \"\"\"\n        return self.builder.load_bytes(bytes_from_str(value), line)\n\n    def load_int(self, value: int, line: int = -1) -> Value:\n        return self.builder.load_int(value, line)\n\n    def load_float(self, value: float, line: int = -1) -> Value:\n        return self.builder.load_float(value, line)\n\n    def unary_op(self, lreg: Value, expr_op: str, line: int) -> Value:\n        return self.builder.unary_op(lreg, expr_op, line)\n\n    def binary_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:\n        return self.builder.binary_op(lreg, rreg, expr_op, line)\n\n    def coerce(self, src: Value, target_type: RType, line: int, force: bool = False) -> Value:\n        return self.builder.coerce(src, target_type, line, force, can_borrow=self.can_borrow)\n\n    def none_object(self, line: int = -1) -> Value:\n        return self.builder.none_object(line)\n\n    def none(self, line: int = -1) -> Value:\n        return self.builder.none(line)\n\n    def true(self, line: int = -1) -> Value:\n        return self.builder.true(line)\n\n    def false(self, line: int = -1) -> Value:\n        return self.builder.false(line)\n\n    def new_list_op(self, values: list[Value], line: int) -> Value:\n        return self.builder.new_list_op(values, line)\n\n    def new_set_op(self, values: list[Value], line: int) -> Value:\n        return self.builder.new_set_op(values, line)\n\n    def translate_is_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:\n        return self.builder.translate_is_op(lreg, rreg, expr_op, line)\n\n    def py_call(\n        self,\n        function: Value,\n        arg_values: list[Value],\n        line: int,\n        arg_kinds: list[ArgKind] | None = None,\n        arg_names: Sequence[str | None] | None = None,\n    ) -> Value:\n        return self.builder.py_call(function, arg_values, line, arg_kinds, arg_names)\n\n    def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None:\n        self.builder.add_bool_branch(value, true, false)\n\n    def load_native_type_object(self, fullname: str) -> Value:\n        return self.builder.load_native_type_object(fullname)\n\n    def gen_method_call(\n        self,\n        base: Value,\n        name: str,\n        arg_values: list[Value],\n        result_type: RType | None,\n        line: int,\n        arg_kinds: list[ArgKind] | None = None,\n        arg_names: list[str | None] | None = None,\n    ) -> Value:\n        return self.builder.gen_method_call(\n            base, name, arg_values, result_type, line, arg_kinds, arg_names, self.can_borrow\n        )\n\n    def load_module(self, name: str) -> Value:\n        return self.builder.load_module(name)\n\n    def call_c(self, desc: CFunctionDescription, args: list[Value], line: int) -> Value:\n        return self.builder.call_c(desc, args, line)\n\n    def primitive_op(\n        self,\n        desc: PrimitiveDescription,\n        args: list[Value],\n        line: int,\n        result_type: RType | None = None,\n    ) -> Value:\n        return self.builder.primitive_op(desc, args, line, result_type)\n\n    def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int) -> Value:\n        return self.builder.int_op(type, lhs, rhs, op, line)\n\n    def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:\n        return self.builder.compare_tuples(lhs, rhs, op, line)\n\n    def builtin_len(self, val: Value, line: int, use_pyssize_t: bool = False) -> Value:\n        return self.builder.builtin_len(val, line, use_pyssize_t)\n\n    def new_tuple(self, items: list[Value], line: int) -> Value:\n        return self.builder.new_tuple(items, line)\n\n    def debug_print(self, toprint: str | Value) -> None:\n        return self.builder.debug_print(toprint)\n\n    def set_immortal_if_free_threaded(self, v: Value, line: int) -> None:\n        \"\"\"Make an object immortal on free-threaded builds (to avoid contention).\"\"\"\n        self.builder.set_immortal_if_free_threaded(v, line)\n\n    # Helpers for IR building\n\n    def add_to_non_ext_dict(\n        self, non_ext: NonExtClassInfo, key: str, val: Value, line: int\n    ) -> None:\n        # Add an attribute entry into the class dict of a non-extension class.\n        key_unicode = self.load_str(key, line)\n        self.primitive_op(dict_set_item_op, [non_ext.dict, key_unicode, val], line)\n\n        # It's important that accessing class dictionary items from multiple threads\n        # doesn't cause contention.\n        self.builder.set_immortal_if_free_threaded(val, line)\n\n    def gen_import(self, id: str, line: int) -> None:\n        self.imports[id] = None\n\n        needs_import, out = BasicBlock(), BasicBlock()\n        self.check_if_module_loaded(id, line, needs_import, out)\n\n        self.activate_block(needs_import)\n        value = self.call_c(import_op, [self.load_str(id, line)], line)\n        self.add(InitStatic(value, id, namespace=NAMESPACE_MODULE))\n        self.goto_and_activate(out)\n\n    def check_if_module_loaded(\n        self, id: str, line: int, needs_import: BasicBlock, out: BasicBlock\n    ) -> None:\n        \"\"\"Generate code that checks if the module `id` has been loaded yet.\n\n        Arguments:\n            id: name of module to check if imported\n            line: line number that the import occurs on\n            needs_import: the BasicBlock that is run if the module has not been loaded yet\n            out: the BasicBlock that is run if the module has already been loaded\"\"\"\n        first_load = self.load_module(id)\n        comparison = self.translate_is_op(first_load, self.none_object(line), \"is not\", line)\n        self.add_bool_branch(comparison, out, needs_import)\n\n    def get_module(self, module: str, line: int) -> Value:\n        # Python 3.7 has a nice 'PyImport_GetModule' function that we can't use :(\n        mod_dict = self.call_c(get_module_dict_op, [], line)\n        # Get module object from modules dict.\n        return self.primitive_op(dict_get_item_op, [mod_dict, self.load_str(module, line)], line)\n\n    def get_module_attr(self, module: str, attr: str, line: int) -> Value:\n        \"\"\"Look up an attribute of a module without storing it in the local namespace.\n\n        For example, get_module_attr('typing', 'TypedDict', line) results in\n        the value of 'typing.TypedDict'.\n\n        Import the module if needed.\n        \"\"\"\n        self.gen_import(module, line)\n        module_obj = self.get_module(module, line)\n        return self.py_get_attr(module_obj, attr, line)\n\n    def assign_if_null(self, target: Register, get_val: Callable[[], Value], line: int) -> None:\n        \"\"\"If target is NULL, assign value produced by get_val to it.\"\"\"\n        error_block, body_block = BasicBlock(), BasicBlock()\n        self.add(Branch(target, error_block, body_block, Branch.IS_ERROR, line))\n        self.activate_block(error_block)\n        self.add(Assign(target, self.coerce(get_val(), target.type, line), line))\n        self.goto(body_block)\n        self.activate_block(body_block)\n\n    def assign_if_bitmap_unset(\n        self, target: Register, get_val: Callable[[], Value], index: int, line: int\n    ) -> None:\n        error_block, body_block = BasicBlock(), BasicBlock()\n        o = self.int_op(\n            bitmap_rprimitive,\n            self.builder.args[-1 - index // BITMAP_BITS],\n            Integer(1 << (index & (BITMAP_BITS - 1)), bitmap_rprimitive),\n            IntOp.AND,\n            line,\n        )\n        b = self.add(ComparisonOp(o, Integer(0, bitmap_rprimitive), ComparisonOp.EQ, line))\n        self.add(Branch(b, error_block, body_block, Branch.BOOL))\n        self.activate_block(error_block)\n        self.add(Assign(target, self.coerce(get_val(), target.type, line)))\n        self.goto(body_block)\n        self.activate_block(body_block)\n\n    def maybe_add_implicit_return(self) -> None:\n        if is_none_rprimitive(self.ret_types[-1]) or is_object_rprimitive(self.ret_types[-1]):\n            self.add_implicit_return()\n        else:\n            self.add_implicit_unreachable()\n\n    def add_implicit_return(self) -> None:\n        block = self.builder.blocks[-1]\n        if not block.terminated:\n            line = self.fn_info.fitem.line\n            retval = self.coerce(self.builder.none(), self.ret_types[-1], line)\n            self.nonlocal_control[-1].gen_return(self, retval, line)\n\n    def add_implicit_unreachable(self) -> None:\n        block = self.builder.blocks[-1]\n        if not block.terminated:\n            self.add(Unreachable())\n\n    def disallow_class_assignments(self, lvalues: list[Lvalue], line: int) -> None:\n        # Some best-effort attempts to disallow assigning to class\n        # variables that aren't marked ClassVar, since we blatantly\n        # miscompile the interaction between instance and class\n        # variables.\n        for lvalue in lvalues:\n            if (\n                isinstance(lvalue, MemberExpr)\n                and isinstance(lvalue.expr, RefExpr)\n                and isinstance(lvalue.expr.node, TypeInfo)\n            ):\n                var = lvalue.expr.node[lvalue.name].node\n                if isinstance(var, Var) and not var.is_classvar:\n                    self.error(\"Only class variables defined as ClassVar can be assigned to\", line)\n\n    def non_function_scope(self) -> bool:\n        # Currently the stack always has at least two items: dummy and top-level.\n        return len(self.fn_infos) <= 2\n\n    def top_level_fn_info(self) -> FuncInfo | None:\n        if self.non_function_scope():\n            return None\n        return self.fn_infos[2]\n\n    def init_final_static(\n        self,\n        lvalue: Lvalue,\n        rvalue_reg: Value,\n        class_name: str | None = None,\n        *,\n        type_override: RType | None = None,\n    ) -> None:\n        assert isinstance(lvalue, NameExpr), lvalue\n        assert isinstance(lvalue.node, Var), lvalue.node\n        if lvalue.node.final_value is None:\n            if class_name is None:\n                name = lvalue.name\n            else:\n                name = f\"{class_name}.{lvalue.name}\"\n            assert name is not None, \"Full name not set for variable\"\n            coerced = self.coerce(rvalue_reg, type_override or self.node_type(lvalue), lvalue.line)\n            self.final_names.append((name, coerced.type))\n            self.add(InitStatic(coerced, name, self.module_name))\n\n    def load_final_static(\n        self, fullname: str, typ: RType, line: int, error_name: str | None = None\n    ) -> Value:\n        split_name = split_target(self.graph, fullname)\n        assert split_name is not None\n        module, name = split_name\n        return self.builder.load_static_checked(\n            typ,\n            name,\n            module,\n            line=line,\n            error_msg=f'value for final name \"{error_name}\" was not set',\n        )\n\n    def init_type_var(self, value: Value, name: str, line: int) -> None:\n        unique_name = name + \"___\" + str(line)\n        self.type_var_names.append(unique_name)\n        self.add(InitStatic(value, unique_name, self.module_name, namespace=NAMESPACE_TYPE_VAR))\n\n    def load_type_var(self, name: str, line: int) -> Value:\n        return self.add(\n            LoadStatic(\n                object_rprimitive,\n                name + \"___\" + str(line),\n                self.module_name,\n                namespace=NAMESPACE_TYPE_VAR,\n            )\n        )\n\n    def load_literal_value(\n        self, val: int | str | bytes | float | complex | bool, line: int = -1\n    ) -> Value:\n        \"\"\"Load value of a final name, class-level attribute, or constant folded expression.\"\"\"\n        if isinstance(val, bool):\n            if val:\n                return self.true(line)\n            else:\n                return self.false(line)\n        elif isinstance(val, int):\n            return self.builder.load_int(val)\n        elif isinstance(val, float):\n            return self.builder.load_float(val)\n        elif isinstance(val, str):\n            return self.builder.load_str(val)\n        elif isinstance(val, bytes):\n            return self.builder.load_bytes(val)\n        elif isinstance(val, complex):\n            return self.builder.load_complex(val)\n        else:\n            assert False, \"Unsupported literal value\"\n\n    def get_assignment_target(\n        self, lvalue: Lvalue, line: int = -1, *, for_read: bool = False\n    ) -> AssignmentTarget:\n        if line == -1:\n            line = lvalue.line\n        if isinstance(lvalue, NameExpr):\n            # If we are visiting a decorator, then the SymbolNode we really want to be looking at\n            # is the function that is decorated, not the entire Decorator node itself.\n            symbol = lvalue.node\n            if isinstance(symbol, Decorator):\n                symbol = symbol.func\n            if symbol is None:\n                # Semantic analyzer doesn't create ad-hoc Vars for special forms.\n                assert lvalue.is_special_form\n                symbol = Var(lvalue.name)\n            if not for_read and isinstance(symbol, Var) and symbol.is_cls:\n                self.error(\"Cannot assign to the first argument of classmethod\", line)\n            if lvalue.kind == LDEF:\n                if symbol not in self.symtables[-1]:\n                    if isinstance(symbol, Var) and not isinstance(symbol.type, DeletedType):\n                        reg_type = self.type_to_rtype(symbol.type)\n                    else:\n                        reg_type = self.node_type(lvalue)\n                    # If the function is a generator function, then first define a new variable\n                    # in the current function's environment class. Next, define a target that\n                    # refers to the newly defined variable in that environment class. Add the\n                    # target to the table containing class environment variables, as well as the\n                    # current environment.\n                    if self.fn_info.is_generator or self.fn_info.is_coroutine:\n                        return self.add_var_to_env_class(\n                            symbol,\n                            reg_type,\n                            self.fn_info.generator_class,\n                            reassign=False,\n                            prefix=GENERATOR_ATTRIBUTE_PREFIX,\n                        )\n\n                    # Otherwise define a new local variable.\n                    return self.add_local_reg(symbol, reg_type)\n                else:\n                    # Assign to a previously defined variable.\n                    return self.lookup(symbol)\n            elif lvalue.kind == GDEF:\n                globals_dict = self.load_globals_dict()\n                name = self.load_str(lvalue.name, line)\n                return AssignmentTargetIndex(globals_dict, name)\n            else:\n                assert False, lvalue.kind\n        elif isinstance(lvalue, IndexExpr):\n            # Indexed assignment x[y] = e\n            base = self.accept(lvalue.base)\n            index = self.accept(lvalue.index)\n            return AssignmentTargetIndex(base, index)\n        elif isinstance(lvalue, MemberExpr):\n            # Attribute assignment x.y = e\n            can_borrow = self.is_native_attr_ref(lvalue)\n            obj = self.accept(lvalue.expr, can_borrow=can_borrow)\n            return AssignmentTargetAttr(obj, lvalue.name, can_borrow=can_borrow)\n        elif isinstance(lvalue, TupleExpr):\n            # Multiple assignment a, ..., b = e\n            star_idx: int | None = None\n            lvalues = []\n            for idx, item in enumerate(lvalue.items):\n                targ = self.get_assignment_target(item)\n                lvalues.append(targ)\n                if isinstance(item, StarExpr):\n                    if star_idx is not None:\n                        self.error(\"Two starred expressions in assignment\", line)\n                    star_idx = idx\n\n            return AssignmentTargetTuple(lvalues, star_idx)\n\n        elif isinstance(lvalue, StarExpr):\n            return self.get_assignment_target(lvalue.expr)\n\n        assert False, \"Unsupported lvalue: %r\" % lvalue\n\n    def read(\n        self,\n        target: Value | AssignmentTarget,\n        line: int = -1,\n        *,\n        can_borrow: bool = False,\n        allow_error_value: bool = False,\n    ) -> Value:\n        if isinstance(target, Value):\n            return target\n        if isinstance(target, AssignmentTargetRegister):\n            return target.register\n        if isinstance(target, AssignmentTargetIndex):\n            reg = self.gen_method_call(\n                target.base, \"__getitem__\", [target.index], target.type, line\n            )\n            if reg is not None:\n                return reg\n            assert False, target.base.type\n        if isinstance(target, AssignmentTargetAttr):\n            if isinstance(target.obj.type, RInstance) and target.obj.type.class_ir.is_ext_class:\n                borrow = can_borrow and target.can_borrow\n                return self.add(\n                    GetAttr(\n                        target.obj,\n                        target.attr,\n                        line,\n                        borrow=borrow,\n                        allow_error_value=allow_error_value,\n                    )\n                )\n            else:\n                return self.py_get_attr(target.obj, target.attr, line)\n\n        assert False, \"Unsupported lvalue: %r\" % target\n\n    def read_nullable_attr(self, obj: Value, attr: str, line: int = -1) -> Value:\n        \"\"\"Read an attribute that might have an error value without raising AttributeError.\"\"\"\n        assert isinstance(obj.type, RInstance) and obj.type.class_ir.is_ext_class\n        return self.add(GetAttr(obj, attr, line, allow_error_value=True))\n\n    def assign(self, target: Register | AssignmentTarget, rvalue_reg: Value, line: int) -> None:\n        if isinstance(target, Register):\n            self.add(Assign(target, self.coerce_rvalue(rvalue_reg, target.type, line), line))\n        elif isinstance(target, AssignmentTargetRegister):\n            rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line)\n            self.add(Assign(target.register, rvalue_reg, line))\n        elif isinstance(target, AssignmentTargetAttr):\n            if isinstance(target.obj_type, RInstance):\n                setattr = target.obj_type.class_ir.get_method(\"__setattr__\")\n                if setattr:\n                    key = self.load_str(target.attr, line)\n                    boxed_reg = self.builder.box(rvalue_reg)\n                    call = MethodCall(target.obj, setattr.name, [key, boxed_reg], line)\n                    self.add(call)\n                else:\n                    rvalue_reg = self.coerce_rvalue(rvalue_reg, target.type, line)\n                    self.add(SetAttr(target.obj, target.attr, rvalue_reg, line))\n            else:\n                key = self.load_str(target.attr, line)\n                boxed_reg = self.builder.box(rvalue_reg)\n                self.primitive_op(py_setattr_op, [target.obj, key, boxed_reg], line)\n        elif isinstance(target, AssignmentTargetIndex):\n            if isinstance(target.base.type, RVec):\n                vec_set_item(self.builder, target.base, target.index, rvalue_reg, line)\n            else:\n                target_reg2 = self.gen_method_call(\n                    target.base, \"__setitem__\", [target.index, rvalue_reg], None, line\n                )\n                assert target_reg2 is not None, target.base.type\n        elif isinstance(target, AssignmentTargetTuple):\n            if isinstance(rvalue_reg.type, RTuple) and target.star_idx is None:\n                rtypes = rvalue_reg.type.types\n                assert len(rtypes) == len(target.items)\n                for i in range(len(rtypes)):\n                    item_value = self.add(TupleGet(rvalue_reg, i, line))\n                    self.assign(target.items[i], item_value, line)\n            elif (\n                is_list_rprimitive(rvalue_reg.type) or is_tuple_rprimitive(rvalue_reg.type)\n            ) and target.star_idx is None:\n                self.process_sequence_assignment(target, rvalue_reg, line)\n            else:\n                self.process_iterator_tuple_assignment(target, rvalue_reg, line)\n        else:\n            assert False, \"Unsupported assignment target\"\n\n    def coerce_rvalue(self, rvalue: Value, rtype: RType, line: int) -> Value:\n        if is_float_rprimitive(rtype) and is_tagged(rvalue.type):\n            typename = rvalue.type.short_name()\n            if typename == \"short_int\":\n                typename = \"int\"\n            self.error(\n                \"Incompatible value representations in assignment \"\n                + f'(expression has type \"{typename}\", variable has type \"float\")',\n                line,\n            )\n        return self.coerce(rvalue, rtype, line)\n\n    def process_sequence_assignment(\n        self, target: AssignmentTargetTuple, rvalue: Value, line: int\n    ) -> None:\n        \"\"\"Process assignment like 'x, y = s', where s is a variable-length list or tuple.\"\"\"\n        # Check the length of sequence.\n        expected_len = Integer(len(target.items), c_pyssize_t_rprimitive)\n        self.builder.call_c(check_unpack_count_op, [rvalue, expected_len], line)\n\n        # Read sequence items.\n        values = []\n        for i in range(len(target.items)):\n            item = target.items[i]\n            index: Value\n            if is_list_rprimitive(rvalue.type):\n                index = Integer(i, c_pyssize_t_rprimitive)\n                item_value = self.primitive_op(list_get_item_unsafe_op, [rvalue, index], line)\n            elif is_tuple_rprimitive(rvalue.type):\n                index = Integer(i, c_pyssize_t_rprimitive)\n                item_value = self.call_c(tuple_get_item_unsafe_op, [rvalue, index], line)\n            else:\n                index = self.builder.load_int(i)\n                item_value = self.builder.gen_method_call(\n                    rvalue, \"__getitem__\", [index], item.type, line\n                )\n            values.append(item_value)\n\n        # Assign sequence items to the target lvalues.\n        for lvalue, value in zip(target.items, values):\n            self.assign(lvalue, value, line)\n\n    def process_iterator_tuple_assignment_helper(\n        self, litem: AssignmentTarget, ritem: Value, line: int\n    ) -> None:\n        error_block, ok_block = BasicBlock(), BasicBlock()\n        self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))\n\n        self.activate_block(error_block)\n        self.add(\n            RaiseStandardError(RaiseStandardError.VALUE_ERROR, \"not enough values to unpack\", line)\n        )\n        self.add(Unreachable())\n\n        self.activate_block(ok_block)\n        self.assign(litem, ritem, line)\n\n    def process_iterator_tuple_assignment(\n        self, target: AssignmentTargetTuple, rvalue_reg: Value, line: int\n    ) -> None:\n        iterator = self.primitive_op(iter_op, [rvalue_reg], line)\n\n        # This may be the whole lvalue list if there is no starred value\n        split_idx = target.star_idx if target.star_idx is not None else len(target.items)\n\n        # Assign values before the first starred value\n        for litem in target.items[:split_idx]:\n            ritem = self.call_c(next_op, [iterator], line)\n            error_block, ok_block = BasicBlock(), BasicBlock()\n            self.add(Branch(ritem, error_block, ok_block, Branch.IS_ERROR))\n\n            self.activate_block(error_block)\n            self.add(\n                RaiseStandardError(\n                    RaiseStandardError.VALUE_ERROR, \"not enough values to unpack\", line\n                )\n            )\n            self.add(Unreachable())\n\n            self.activate_block(ok_block)\n\n            self.assign(litem, ritem, line)\n\n        # Assign the starred value and all values after it\n        if target.star_idx is not None:\n            post_star_vals = target.items[split_idx + 1 :]\n            iter_list = self.primitive_op(to_list, [iterator], line)\n            iter_list_len = self.builtin_len(iter_list, line)\n            post_star_len = Integer(len(post_star_vals))\n            condition = self.binary_op(post_star_len, iter_list_len, \"<=\", line)\n\n            error_block, ok_block = BasicBlock(), BasicBlock()\n            self.add(Branch(condition, ok_block, error_block, Branch.BOOL))\n\n            self.activate_block(error_block)\n            self.add(\n                RaiseStandardError(\n                    RaiseStandardError.VALUE_ERROR, \"not enough values to unpack\", line\n                )\n            )\n            self.add(Unreachable())\n\n            self.activate_block(ok_block)\n\n            for litem in reversed(post_star_vals):\n                ritem = self.primitive_op(list_pop_last, [iter_list], line)\n                self.assign(litem, ritem, line)\n\n            # Assign the starred value\n            self.assign(target.items[target.star_idx], iter_list, line)\n\n        # There is no starred value, so check if there are extra values in rhs that\n        # have not been assigned.\n        else:\n            extra = self.call_c(next_op, [iterator], line)\n            error_block, ok_block = BasicBlock(), BasicBlock()\n            self.add(Branch(extra, ok_block, error_block, Branch.IS_ERROR))\n\n            self.activate_block(error_block)\n            self.add(\n                RaiseStandardError(\n                    RaiseStandardError.VALUE_ERROR, \"too many values to unpack\", line\n                )\n            )\n            self.add(Unreachable())\n\n            self.activate_block(ok_block)\n\n    def push_loop_stack(self, continue_block: BasicBlock, break_block: BasicBlock) -> None:\n        self.nonlocal_control.append(\n            LoopNonlocalControl(self.nonlocal_control[-1], continue_block, break_block)\n        )\n\n    def pop_loop_stack(self) -> None:\n        self.nonlocal_control.pop()\n\n    def make_spill_target(self, type: RType) -> AssignmentTarget:\n        \"\"\"Moves a given Value instance into the generator class' environment class.\"\"\"\n        name = f\"{TEMP_ATTR_NAME}{self.temp_counter}\"\n        self.temp_counter += 1\n        target = self.add_var_to_env_class(Var(name), type, self.fn_info.generator_class)\n        return target\n\n    def spill(self, value: Value) -> AssignmentTarget:\n        \"\"\"Moves a given Value instance into the generator class' environment class.\"\"\"\n        target = self.make_spill_target(value.type)\n        # Shouldn't be able to fail\n        self.assign(target, value, NO_TRACEBACK_LINE_NO)\n        return target\n\n    def maybe_spill(self, value: Value) -> Value | AssignmentTarget:\n        \"\"\"\n        Moves a given Value instance into the environment class for generator functions. For\n        non-generator functions, leaves the Value instance as it is.\n\n        Returns an AssignmentTarget associated with the Value for generator functions and the\n        original Value itself for non-generator functions.\n        \"\"\"\n        if self.fn_info.is_generator:\n            return self.spill(value)\n        return value\n\n    def maybe_spill_assignable(self, value: Value) -> Register | AssignmentTarget:\n        \"\"\"\n        Moves a given Value instance into the environment class for generator functions. For\n        non-generator functions, allocate a temporary Register.\n\n        Returns an AssignmentTarget associated with the Value for generator functions and an\n        assignable Register for non-generator functions.\n        \"\"\"\n        if self.fn_info.is_generator:\n            return self.spill(value)\n\n        if isinstance(value, Register):\n            return value\n\n        # Allocate a temporary register for the assignable value.\n        reg = Register(value.type)\n        self.assign(reg, value, NO_TRACEBACK_LINE_NO)\n        return reg\n\n    def extract_int(self, e: Expression) -> int | None:\n        folded = constant_fold_expr(self, e)\n        return folded if isinstance(folded, int) else None\n\n    def get_sequence_type(self, expr: Expression) -> RType:\n        return self.get_sequence_type_from_type(self.types[expr])\n\n    def get_sequence_type_from_type(self, target_type: Type) -> RType:\n        target_type = get_proper_type(target_type)\n        if isinstance(target_type, UnionType):\n            return RUnion.make_simplified_union(\n                [self.get_sequence_type_from_type(item) for item in target_type.items]\n            )\n        elif isinstance(target_type, Instance):\n            if target_type.type.fullname == \"builtins.str\":\n                return str_rprimitive\n            elif target_type.type.fullname == \"builtins.bytes\":\n                return bytes_rprimitive\n            try:\n                return self.type_to_rtype(target_type.args[0])\n            except IndexError:\n                raise ValueError(f\"{target_type!r} is not a valid sequence.\") from None\n        # This elif-blocks are needed for iterating over classes derived from NamedTuple.\n        elif isinstance(target_type, TypeVarLikeType):\n            return self.get_sequence_type_from_type(target_type.upper_bound)\n        elif isinstance(target_type, TupleType):\n            items = target_type.items\n            assert items, \"This function does not support empty tuples\"\n            # Tuple might have elements of different types.\n            rtypes = set(map(self.mapper.type_to_rtype, items))\n            if len(rtypes) == 1:\n                return rtypes.pop()\n            else:\n                return RUnion.make_simplified_union(list(rtypes))\n        assert False, target_type\n\n    def get_dict_base_type(self, expr: Expression) -> list[Instance]:\n        \"\"\"Find dict type of a dict-like expression.\n\n        This is useful for dict subclasses like SymbolTable.\n        \"\"\"\n        return self.get_dict_base_type_from_type(self.types[expr])\n\n    def get_dict_base_type_from_type(self, target_type: Type) -> list[Instance]:\n        target_type = get_proper_type(target_type)\n        if isinstance(target_type, UnionType):\n            return [\n                inner\n                for item in target_type.items\n                for inner in self.get_dict_base_type_from_type(item)\n            ]\n        if isinstance(target_type, TypeVarLikeType):\n            # Match behaviour of self.node_type\n            # We can only reach this point if `target_type` was a TypeVar(bound=dict[...])\n            # or a ParamSpec.\n            return self.get_dict_base_type_from_type(target_type.upper_bound)\n\n        if isinstance(target_type, TypedDictType):\n            target_type = target_type.fallback\n            dict_base = next(\n                base for base in target_type.type.mro if base.fullname == \"typing.Mapping\"\n            )\n        elif isinstance(target_type, Instance):\n            dict_base = next(\n                base for base in target_type.type.mro if base.fullname == \"builtins.dict\"\n            )\n        else:\n            assert False, f\"Failed to extract dict base from {target_type}\"\n        return [map_instance_to_supertype(target_type, dict_base)]\n\n    def get_dict_key_type(self, expr: Expression) -> RType:\n        dict_base_types = self.get_dict_base_type(expr)\n        rtypes = [self.type_to_rtype(t.args[0]) for t in dict_base_types]\n        return RUnion.make_simplified_union(rtypes)\n\n    def get_dict_value_type(self, expr: Expression) -> RType:\n        dict_base_types = self.get_dict_base_type(expr)\n        rtypes = [self.type_to_rtype(t.args[1]) for t in dict_base_types]\n        return RUnion.make_simplified_union(rtypes)\n\n    def get_dict_item_type(self, expr: Expression) -> RType:\n        key_type = self.get_dict_key_type(expr)\n        value_type = self.get_dict_value_type(expr)\n        return RTuple([key_type, value_type])\n\n    def _analyze_iterable_item_type(self, expr: Expression) -> Type:\n        \"\"\"Return the item type given by 'expr' in an iterable context.\"\"\"\n        # This logic is copied from mypy's TypeChecker.analyze_iterable_item_type.\n        if expr not in self.types:\n            # Mypy thinks this is unreachable.\n            iterable: ProperType = AnyType(TypeOfAny.from_error)\n        else:\n            iterable = get_proper_type(self.types[expr])\n        echk = self.graph[self.module_name].type_checker().expr_checker\n        iterator = echk.check_method_call_by_name(\"__iter__\", iterable, [], [], expr)[0]\n\n        from mypy.join import join_types\n\n        if isinstance(iterable, TupleType):\n            joined: Type = UninhabitedType()\n            for item in iterable.items:\n                joined = join_types(joined, item)\n            return joined\n        else:\n            # Non-tuple iterable.\n            return echk.check_method_call_by_name(\"__next__\", iterator, [], [], expr)[0]\n\n    def is_native_module(self, module: str) -> bool:\n        \"\"\"Is the given module one compiled by mypyc?\"\"\"\n        return self.mapper.is_native_module(module)\n\n    def is_native_ref_expr(self, expr: RefExpr) -> bool:\n        return self.mapper.is_native_ref_expr(expr)\n\n    def is_native_module_ref_expr(self, expr: RefExpr) -> bool:\n        return self.mapper.is_native_module_ref_expr(expr)\n\n    def is_synthetic_type(self, typ: TypeInfo) -> bool:\n        \"\"\"Is a type something other than just a class we've created?\"\"\"\n        return typ.is_named_tuple or typ.is_newtype or typ.typeddict_type is not None\n\n    def get_final_ref(self, expr: MemberExpr) -> tuple[str, Var, bool] | None:\n        \"\"\"Check if `expr` is a final attribute.\n\n        This needs to be done differently for class and module attributes to\n        correctly determine fully qualified name. Return a tuple that consists of\n        the qualified name, the corresponding Var node, and a flag indicating whether\n        the final name was defined in a compiled module. Return None if `expr` does not\n        refer to a final attribute.\n        \"\"\"\n        final_var = None\n        if isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, TypeInfo):\n            # a class attribute\n            sym = expr.expr.node.get(expr.name)\n            if sym and isinstance(sym.node, Var):\n                # Enum attribute are treated as final since they are added to the global cache\n                expr_fullname = expr.expr.node.bases[0].type.fullname\n                is_final = sym.node.is_final or expr_fullname == \"enum.Enum\"\n                if is_final:\n                    final_var = sym.node\n                    fullname = f\"{sym.node.info.fullname}.{final_var.name}\"\n                    native = self.is_native_module(expr.expr.node.module_name)\n        elif self.is_module_member_expr(expr):\n            # a module attribute\n            if isinstance(expr.node, Var) and expr.node.is_final:\n                final_var = expr.node\n                fullname = expr.node.fullname\n                native = self.is_native_ref_expr(expr)\n        if final_var is not None:\n            return fullname, final_var, native\n        return None\n\n    def emit_load_final(\n        self, final_var: Var, fullname: str, name: str, native: bool, typ: Type, line: int\n    ) -> Value | None:\n        \"\"\"Emit code for loading value of a final name (if possible).\n\n        Args:\n            final_var: Var corresponding to the final name\n            fullname: its qualified name\n            name: shorter name to show in errors\n            native: whether the name was defined in a compiled module\n            typ: its type\n            line: line number where loading occurs\n        \"\"\"\n        if final_var.final_value is not None:  # this is safe even for non-native names\n            return self.load_literal_value(final_var.final_value, line)\n        elif native and module_prefix(self.graph, fullname):\n            return self.load_final_static(fullname, self.mapper.type_to_rtype(typ), line, name)\n        else:\n            return None\n\n    def is_module_member_expr(self, expr: MemberExpr) -> bool:\n        return isinstance(expr.expr, RefExpr) and isinstance(expr.expr.node, MypyFile)\n\n    def call_refexpr_with_args(\n        self, expr: CallExpr, callee: RefExpr, arg_values: list[Value]\n    ) -> Value:\n        # Handle data-driven special-cased primitive call ops.\n        if callee.fullname and expr.arg_kinds == [ARG_POS] * len(arg_values):\n            fullname = get_call_target_fullname(callee)\n            primitive_candidates = function_ops.get(fullname, [])\n            target = self.builder.matching_primitive_op(\n                primitive_candidates, arg_values, expr.line, self.node_type(expr)\n            )\n            if target:\n                return target\n\n        # Standard native call if signature and fullname are good and all arguments are positional\n        # or named.\n        callee_node = callee.node\n        if isinstance(callee_node, OverloadedFuncDef):\n            callee_node = callee_node.impl\n        # TODO: use native calls for any decorated functions which have all their decorators\n        # removed, not just singledispatch functions (which we don't do now just in case those\n        # decorated functions are callable classes or cannot be called without the python API for\n        # some other reason)\n        if (\n            isinstance(callee_node, Decorator)\n            and callee_node.func not in self.fdefs_to_decorators\n            and callee_node.func in self.singledispatch_impls\n        ):\n            callee_node = callee_node.func\n        if (\n            callee_node is not None\n            and callee.fullname\n            and callee_node in self.mapper.func_to_decl\n            and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds)\n        ):\n            decl = self.mapper.func_to_decl[callee_node]\n            return self.builder.call(decl, arg_values, expr.arg_kinds, expr.arg_names, expr.line)\n\n        # Fall back to a Python call\n        function = self.accept(callee)\n        return self.py_call(\n            function, arg_values, expr.line, arg_kinds=expr.arg_kinds, arg_names=expr.arg_names\n        )\n\n    def shortcircuit_expr(self, expr: OpExpr) -> Value:\n        def handle_right() -> Value:\n            if expr.right_unreachable:\n                self.builder.add(\n                    RaiseStandardError(\n                        RaiseStandardError.RUNTIME_ERROR,\n                        \"mypyc internal error: should be unreachable\",\n                        expr.right.line,\n                    )\n                )\n                return self.builder.none()\n            return self.accept(expr.right)\n\n        return self.builder.shortcircuit_helper(\n            expr.op, self.node_type(expr), lambda: self.accept(expr.left), handle_right, expr.line\n        )\n\n    # Basic helpers\n\n    def flatten_classes(self, arg: RefExpr | TupleExpr) -> list[ClassIR] | None:\n        \"\"\"Flatten classes in isinstance(obj, (A, (B, C))).\n\n        If at least one item is not a reference to a native class, return None.\n        \"\"\"\n        if isinstance(arg, RefExpr):\n            if isinstance(arg.node, TypeInfo) and self.is_native_module_ref_expr(arg):\n                ir = self.mapper.type_to_ir.get(arg.node)\n                if ir:\n                    return [ir]\n            return None\n        else:\n            res: list[ClassIR] = []\n            for item in arg.items:\n                if isinstance(item, (RefExpr, TupleExpr)):\n                    item_part = self.flatten_classes(item)\n                    if item_part is None:\n                        return None\n                    res.extend(item_part)\n                else:\n                    return None\n            return res\n\n    def enter(self, fn_info: FuncInfo | str = \"\", *, ret_type: RType = none_rprimitive) -> None:\n        if isinstance(fn_info, str):\n            fn_info = FuncInfo(name=fn_info)\n        self.builder = LowLevelIRBuilder(self.errors, self.options)\n        self.builder.set_module(self.module_name, self.module_path)\n        self.builders.append(self.builder)\n        self.symtables.append({})\n        self.runtime_args.append([])\n        self.fn_info = fn_info\n        self.fn_infos.append(self.fn_info)\n        self.ret_types.append(ret_type)\n        if fn_info.is_generator:\n            self.nonlocal_control.append(GeneratorNonlocalControl())\n        else:\n            self.nonlocal_control.append(BaseNonlocalControl())\n        self.activate_block(BasicBlock())\n\n    def leave(self) -> tuple[list[Register], list[RuntimeArg], list[BasicBlock], RType, FuncInfo]:\n        builder = self.builders.pop()\n        self.symtables.pop()\n        runtime_args = self.runtime_args.pop()\n        ret_type = self.ret_types.pop()\n        fn_info = self.fn_infos.pop()\n        self.nonlocal_control.pop()\n        self.builder = self.builders[-1]\n        self.fn_info = self.fn_infos[-1]\n        return builder.args, runtime_args, builder.blocks, ret_type, fn_info\n\n    @contextmanager\n    def enter_scope(self, fn_info: FuncInfo) -> Iterator[None]:\n        \"\"\"Push a lightweight scope for comprehensions.\n\n        Unlike enter(), this reuses the same LowLevelIRBuilder (same basic\n        blocks and registers) but pushes new symtable and fn_info entries\n        so that the closure machinery sees a scope boundary.\n        \"\"\"\n        self.builders.append(self.builder)\n        # Copy the parent symtable so variables from the enclosing scope\n        # (e.g. function parameters used as the comprehension iterable)\n        # remain accessible. The comprehension is inlined (same basic blocks\n        # and registers), so the parent's register references are still valid.\n        self.symtables.append(dict(self.symtables[-1]))\n        self.runtime_args.append([])\n        self.fn_info = fn_info\n        self.fn_infos.append(self.fn_info)\n        self.ret_types.append(none_rprimitive)\n        self.nonlocal_control.append(BaseNonlocalControl())\n        try:\n            yield\n        finally:\n            self.builders.pop()\n            self.symtables.pop()\n            self.runtime_args.pop()\n            self.ret_types.pop()\n            self.fn_infos.pop()\n            self.nonlocal_control.pop()\n            self.builder = self.builders[-1]\n            self.fn_info = self.fn_infos[-1]\n\n    @contextmanager\n    def enter_method(\n        self,\n        class_ir: ClassIR,\n        name: str,\n        ret_type: RType,\n        fn_info: FuncInfo | str = \"\",\n        self_type: RType | None = None,\n        internal: bool = False,\n    ) -> Iterator[None]:\n        \"\"\"Generate IR for a method.\n\n        If the method takes arguments, you should immediately afterwards call\n        add_argument() for each non-self argument (self is created implicitly).\n\n        Args:\n            class_ir: Add method to this class\n            name: Short name of the method\n            ret_type: Return type of the method\n            fn_info: Optionally, additional information about the method\n            self_type: If not None, override default type of the implicit 'self'\n                argument (by default, derive type from class_ir)\n        \"\"\"\n        self.enter(fn_info, ret_type=ret_type)\n        self.function_name_stack.append(name)\n        self.class_ir_stack.append(class_ir)\n        if self_type is None:\n            self_type = RInstance(class_ir)\n        self.add_argument(SELF_NAME, self_type)\n        try:\n            yield\n        finally:\n            arg_regs, args, blocks, ret_type, fn_info = self.leave()\n            sig = FuncSignature(args, ret_type)\n            name = self.function_name_stack.pop()\n            class_ir = self.class_ir_stack.pop()\n            decl = FuncDecl(name, class_ir.name, self.module_name, sig, internal=internal)\n            ir = FuncIR(decl, arg_regs, blocks)\n            class_ir.methods[name] = ir\n            class_ir.method_decls[name] = ir.decl\n            self.functions.append(ir)\n\n    def add_argument(self, var: str | Var, typ: RType, kind: ArgKind = ARG_POS) -> Register:\n        \"\"\"Declare an argument in the current function.\n\n        You should use this instead of directly calling add_local() in new code.\n        \"\"\"\n        if isinstance(var, str):\n            var = Var(var)\n        reg = self.add_local(var, typ, is_arg=True)\n        self.runtime_args[-1].append(RuntimeArg(var.name, typ, kind))\n        return reg\n\n    def lookup(self, symbol: SymbolNode) -> SymbolTarget:\n        return self.symtables[-1][symbol]\n\n    def add_local(self, symbol: SymbolNode, typ: RType, is_arg: bool = False) -> Register:\n        \"\"\"Add register that represents a symbol to the symbol table.\n\n        Args:\n            is_arg: is this a function argument\n        \"\"\"\n        assert isinstance(symbol, SymbolNode), symbol\n        reg = Register(\n            typ, remangle_redefinition_name(symbol.name), is_arg=is_arg, line=symbol.line\n        )\n        self.symtables[-1][symbol] = AssignmentTargetRegister(reg)\n        if is_arg:\n            self.builder.args.append(reg)\n        return reg\n\n    def add_local_reg(\n        self, symbol: SymbolNode, typ: RType, is_arg: bool = False\n    ) -> AssignmentTargetRegister:\n        \"\"\"Like add_local, but return an assignment target instead of value.\"\"\"\n        self.add_local(symbol, typ, is_arg)\n        target = self.symtables[-1][symbol]\n        assert isinstance(target, AssignmentTargetRegister), target\n        return target\n\n    def add_self_to_env(self, cls: ClassIR) -> AssignmentTargetRegister:\n        \"\"\"Low-level function that adds a 'self' argument.\n\n        This is only useful if using enter() instead of enter_method().\n        \"\"\"\n        return self.add_local_reg(Var(SELF_NAME), RInstance(cls), is_arg=True)\n\n    def add_target(self, symbol: SymbolNode, target: SymbolTarget) -> SymbolTarget:\n        self.symtables[-1][symbol] = target\n        return target\n\n    def type_to_rtype(self, typ: Type | None) -> RType:\n        return self.mapper.type_to_rtype(typ)\n\n    def node_type(self, node: Expression) -> RType:\n        if isinstance(node, IntExpr):\n            # TODO: Don't special case IntExpr\n            return int_rprimitive\n        if node not in self.types:\n            return object_rprimitive\n        mypy_type = self.types[node]\n        return self.type_to_rtype(mypy_type)\n\n    def add_var_to_env_class(\n        self,\n        var: SymbolNode,\n        rtype: RType,\n        base: FuncInfo | ImplicitClass,\n        reassign: bool = False,\n        always_defined: bool = False,\n        prefix: str = \"\",\n    ) -> AssignmentTarget:\n        # First, define the variable name as an attribute of the environment class, and then\n        # construct a target for that attribute.\n        name = prefix + remangle_redefinition_name(var.name)\n        self.fn_info.env_class.attributes[name] = rtype\n        if always_defined:\n            self.fn_info.env_class.attrs_with_defaults.add(name)\n        attr_target = AssignmentTargetAttr(base.curr_env_reg, name)\n\n        if reassign:\n            # Read the local definition of the variable, and set the corresponding attribute of\n            # the environment class' variable to be that value.\n            reg = self.read(self.lookup(var), self.fn_info.fitem.line)\n            self.add(SetAttr(base.curr_env_reg, name, reg, self.fn_info.fitem.line))\n\n        # Override the local definition of the variable to instead point at the variable in\n        # the environment class.\n        return self.add_target(var, attr_target)\n\n    def is_builtin_ref_expr(self, expr: RefExpr) -> bool:\n        assert expr.node, \"RefExpr not resolved\"\n        return \".\" in expr.node.fullname and expr.node.fullname.split(\".\")[0] == \"builtins\"\n\n    def load_global(self, expr: NameExpr) -> Value:\n        \"\"\"Loads a Python-level global.\n\n        This takes a NameExpr and uses its name as a key to retrieve the corresponding PyObject *\n        from the _globals dictionary in the C-generated code.\n        \"\"\"\n        # If the global is from 'builtins', turn it into a module attr load instead\n        if self.is_builtin_ref_expr(expr):\n            assert expr.node, \"RefExpr not resolved\"\n            return self.load_module_attr_by_fullname(expr.node.fullname, expr.line)\n        if (\n            self.is_native_module_ref_expr(expr)\n            and isinstance(expr.node, TypeInfo)\n            and not self.is_synthetic_type(expr.node)\n        ):\n            assert expr.fullname\n            return self.load_native_type_object(expr.fullname)\n        return self.load_global_str(expr.name, expr.line)\n\n    def load_global_str(self, name: str, line: int) -> Value:\n        _globals = self.load_globals_dict()\n        reg = self.load_str(name, line)\n        return self.primitive_op(dict_get_item_op, [_globals, reg], line)\n\n    def load_globals_dict(self) -> Value:\n        return self.add(LoadStatic(dict_rprimitive, \"globals\", self.module_name))\n\n    def load_module_attr_by_fullname(self, fullname: str, line: int) -> Value:\n        module, _, name = fullname.rpartition(\".\")\n        left = self.load_module(module)\n        return self.py_get_attr(left, name, line)\n\n    def is_native_attr_ref(self, expr: MemberExpr) -> bool:\n        \"\"\"Is expr a direct reference to a native (struct) attribute of an instance?\"\"\"\n        obj_rtype = self.node_type(expr.expr)\n        return (\n            isinstance(obj_rtype, RInstance)\n            and obj_rtype.class_ir.is_ext_class\n            and obj_rtype.class_ir.has_attr(expr.name)\n            and not obj_rtype.class_ir.get_method(expr.name)\n        )\n\n    def mark_block_unreachable(self) -> None:\n        \"\"\"Mark statements in the innermost block being processed as unreachable.\n\n        This should be called after a statement that unconditionally leaves the\n        block, such as 'break' or 'return'.\n        \"\"\"\n        self.block_reachable_stack[-1] = False\n\n    # Lacks a good type because there wasn't a reasonable type in 3.5 :(\n    def catch_errors(self, line: int) -> Any:\n        return catch_errors(self.module_path, line)\n\n    def warning(self, msg: str, line: int) -> None:\n        self.errors.warning(msg, self.module_path, line)\n\n    def error(self, msg: str, line: int) -> None:\n        self.errors.error(msg, self.module_path, line)\n\n    def note(self, msg: str, line: int) -> None:\n        self.errors.note(msg, self.module_path, line)\n\n    def add_function(self, func_ir: FuncIR, line: int) -> None:\n        name = (func_ir.class_name, func_ir.name)\n        if name in self.function_names:\n            self.error(f'Duplicate definition of \"{name[1]}\" not supported by mypyc', line)\n            return\n        self.function_names.add(name)\n        self.functions.append(func_ir)\n\n    def get_current_class_ir(self) -> ClassIR | None:\n        type_info = self.fn_info.fitem.info\n        return self.mapper.type_to_ir.get(type_info)\n\n    def add_coroutine_setup_call(self, class_name: str, obj: Value) -> Value:\n        return self.add(\n            Call(\n                FuncDecl(\n                    class_name + \"_coroutine_setup\",\n                    None,\n                    self.module_name,\n                    FuncSignature([RuntimeArg(\"type\", object_rprimitive)], bool_rprimitive),\n                ),\n                [obj],\n                obj.line,\n            )\n        )\n\n\ndef gen_arg_defaults(builder: IRBuilder) -> None:\n    \"\"\"Generate blocks for arguments that have default values.\n\n    If the passed value is an error value, then assign the default\n    value to the argument.\n    \"\"\"\n    fitem = builder.fn_info.fitem\n    nb = 0\n    for arg in fitem.arguments:\n        if arg.initializer:\n            target = builder.lookup(arg.variable)\n\n            def get_default() -> Value:\n                assert arg.initializer is not None\n\n                # If it is constant, don't bother storing it\n                if is_constant(arg.initializer):\n                    return builder.accept(arg.initializer)\n\n                # Because gen_arg_defaults runs before calculate_arg_defaults, we\n                # add the static/attribute to final_names/the class here.\n                elif not builder.fn_info.is_nested:\n                    name = fitem.fullname + \".\" + arg.variable.name\n                    builder.final_names.append((name, target.type))\n                    return builder.add(LoadStatic(target.type, name, builder.module_name))\n                else:\n                    name = arg.variable.name\n                    builder.fn_info.callable_class.ir.attributes[name] = target.type\n                    return builder.add(\n                        GetAttr(builder.fn_info.callable_class.self_reg, name, arg.line)\n                    )\n\n            assert isinstance(target, AssignmentTargetRegister), target\n            reg = target.register\n            if not reg.type.error_overlap:\n                builder.assign_if_null(target.register, get_default, arg.initializer.line)\n            else:\n                builder.assign_if_bitmap_unset(\n                    target.register, get_default, nb, arg.initializer.line\n                )\n                nb += 1\n\n\ndef remangle_redefinition_name(name: str) -> str:\n    \"\"\"Remangle names produced by mypy when allow-redefinition-old is used and a name\n    is used with multiple types within a single block.\n\n    We only need to do this for locals, because the name is used as the name of the register;\n    for globals, the name itself is stored in a register for the purpose of doing dict\n    lookups.\n    \"\"\"\n    return name.replace(\"'\", \"__redef__\")\n\n\ndef get_call_target_fullname(ref: RefExpr) -> str:\n    if isinstance(ref.node, TypeAlias):\n        # Resolve simple type aliases. In calls they evaluate to the type they point to.\n        target = get_proper_type(ref.node.target)\n        if isinstance(target, Instance):\n            return target.type.fullname\n    return ref.fullname\n\n\ndef create_type_params(\n    builder: IRBuilder, typing_mod: Value, type_args: list[TypeParam], line: int\n) -> list[Value]:\n    \"\"\"Create objects representing various kinds of Python 3.12 type parameters.\n\n    The \"typing_mod\" argument is the \"_typing\" module object. The type objects\n    are looked up from it.\n\n    The returned list has one item for each \"type_args\" item, in the same order.\n    Each item is either a TypeVar, TypeVarTuple or ParamSpec instance.\n    \"\"\"\n    tvs = []\n    type_var_imported: Value | None = None\n    for type_param in type_args:\n        if type_param.kind == TYPE_VAR_KIND:\n            if type_var_imported:\n                # Reuse previously imported value as a minor optimization\n                tvt = type_var_imported\n            else:\n                tvt = builder.py_get_attr(typing_mod, \"TypeVar\", line)\n                type_var_imported = tvt\n        elif type_param.kind == TYPE_VAR_TUPLE_KIND:\n            tvt = builder.py_get_attr(typing_mod, \"TypeVarTuple\", line)\n        else:\n            assert type_param.kind == PARAM_SPEC_KIND\n            tvt = builder.py_get_attr(typing_mod, \"ParamSpec\", line)\n        if type_param.kind != TYPE_VAR_TUPLE_KIND:\n            # To match runtime semantics, pass infer_variance=True\n            tv = builder.py_call(\n                tvt,\n                [builder.load_str(type_param.name, line), builder.true(line)],\n                line,\n                arg_kinds=[ARG_POS, ARG_NAMED],\n                arg_names=[None, \"infer_variance\"],\n            )\n        else:\n            tv = builder.py_call(tvt, [builder.load_str(type_param.name, line)], line)\n        builder.init_type_var(tv, type_param.name, line)\n        tvs.append(tv)\n    return tvs\n\n\ndef calculate_arg_defaults(\n    builder: IRBuilder,\n    fn_info: FuncInfo,\n    func_reg: Value | None,\n    symtable: dict[SymbolNode, SymbolTarget],\n) -> None:\n    \"\"\"Calculate default argument values and store them.\n\n    They are stored in statics for top level functions and in\n    the function objects for nested functions (while constants are\n    still stored computed on demand).\n    \"\"\"\n    fitem = fn_info.fitem\n    for arg in fitem.arguments:\n        # Constant values don't get stored but just recomputed\n        if arg.initializer and not is_constant(arg.initializer):\n            value = builder.coerce(\n                builder.accept(arg.initializer), symtable[arg.variable].type, arg.line\n            )\n            if not fn_info.is_nested:\n                name = fitem.fullname + \".\" + arg.variable.name\n                builder.add(InitStatic(value, name, builder.module_name))\n            else:\n                assert func_reg is not None\n                builder.add(SetAttr(func_reg, arg.variable.name, value, arg.line))\n"
  },
  {
    "path": "mypyc/irbuild/callable_class.py",
    "content": "\"\"\"Generate a class that represents a nested function.\n\nThe class defines __call__ for calling the function and allows access to\nnon-local variables defined in outer scopes.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.common import CPYFUNCTION_NAME, ENV_ATTR_NAME, PROPSET_PREFIX, SELF_NAME\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature, RuntimeArg\nfrom mypyc.ir.ops import BasicBlock, Call, GetAttr, Integer, Register, Return, SetAttr, Value\nfrom mypyc.ir.rtypes import RInstance, c_pointer_rprimitive, int_rprimitive, object_rprimitive\nfrom mypyc.irbuild.builder import IRBuilder\nfrom mypyc.irbuild.context import FuncInfo, ImplicitClass\nfrom mypyc.primitives.misc_ops import (\n    cpyfunction_get_annotations,\n    cpyfunction_get_code,\n    cpyfunction_get_defaults,\n    cpyfunction_get_kwdefaults,\n    cpyfunction_get_name,\n    cpyfunction_set_annotations,\n    cpyfunction_set_name,\n    method_new_op,\n)\n\n\ndef setup_callable_class(builder: IRBuilder) -> None:\n    \"\"\"Generate an (incomplete) callable class representing a function.\n\n    This can be a nested function or a function within a non-extension\n    class.  Also set up the 'self' variable for that class.\n\n    This takes the most recently visited function and returns a\n    ClassIR to represent that function. Each callable class contains\n    an environment attribute which points to another ClassIR\n    representing the environment class where some of its variables can\n    be accessed.\n\n    Note that some methods, such as '__call__', are not yet\n    created here. Use additional functions, such as\n    add_call_to_callable_class(), to add them.\n\n    Return a newly constructed ClassIR representing the callable\n    class for the nested function.\n    \"\"\"\n    # Check to see that the name has not already been taken. If so,\n    # rename the class. We allow multiple uses of the same function\n    # name because this is valid in if-else blocks. Example:\n    #\n    #     if True:\n    #         def foo():          ---->    foo_obj()\n    #             return True\n    #     else:\n    #         def foo():          ---->    foo_obj_0()\n    #             return False\n    name = base_name = f\"{builder.fn_info.namespaced_name()}_obj\"\n    count = 0\n    while name in builder.callable_class_names:\n        name = base_name + \"_\" + str(count)\n        count += 1\n    builder.callable_class_names.add(name)\n\n    # Define the actual callable class ClassIR, and set its\n    # environment to point at the previously defined environment\n    # class.\n    callable_class_ir = ClassIR(name, builder.module_name, is_generated=True, is_final_class=True)\n    callable_class_ir.reuse_freed_instance = True\n\n    # The functools @wraps decorator attempts to call setattr on\n    # nested functions, so we create a dict for these nested\n    # functions.\n    # https://github.com/python/cpython/blob/3.7/Lib/functools.py#L58\n    if builder.fn_info.is_nested:\n        callable_class_ir.has_dict = True\n\n    # If the enclosing class doesn't contain nested (which will happen if\n    # this is a toplevel lambda), don't set up an environment.\n    if builder.fn_infos[-2].contains_nested:\n        callable_class_ir.attributes[ENV_ATTR_NAME] = RInstance(builder.fn_infos[-2].env_class)\n    callable_class_ir.mro = [callable_class_ir]\n    builder.fn_info.callable_class = ImplicitClass(callable_class_ir)\n    builder.classes.append(callable_class_ir)\n\n    # Add a 'self' variable to the environment of the callable class,\n    # and store that variable in a register to be accessed later.\n    self_target = builder.add_self_to_env(callable_class_ir)\n    builder.fn_info.callable_class.self_reg = builder.read(self_target, builder.fn_info.fitem.line)\n\n    if not builder.fn_info.in_non_ext and builder.fn_info.is_coroutine:\n        add_coroutine_properties(builder, callable_class_ir, builder.fn_info.name)\n\n\ndef add_coroutine_properties(\n    builder: IRBuilder, callable_class_ir: ClassIR, coroutine_name: str\n) -> None:\n    \"\"\"Adds properties to the class to make it look like a regular python function.\n    Needed to make introspection functions like inspect.iscoroutinefunction work.\n    \"\"\"\n    callable_class_ir.coroutine_name = coroutine_name\n    callable_class_ir.attributes[CPYFUNCTION_NAME] = object_rprimitive\n\n    properties = {\n        \"__name__\": cpyfunction_get_name,\n        \"__code__\": cpyfunction_get_code,\n        \"__annotations__\": cpyfunction_get_annotations,\n        \"__defaults__\": cpyfunction_get_defaults,\n        \"__kwdefaults__\": cpyfunction_get_kwdefaults,\n    }\n\n    writable_props = {\n        \"__name__\": cpyfunction_set_name,\n        \"__annotations__\": cpyfunction_set_annotations,\n    }\n\n    line = builder.fn_info.fitem.line\n\n    def get_func_wrapper() -> Value:\n        return builder.add(GetAttr(builder.self(), CPYFUNCTION_NAME, line))\n\n    for name, primitive in properties.items():\n        with builder.enter_method(callable_class_ir, name, object_rprimitive, internal=True):\n            func = get_func_wrapper()\n            val = builder.primitive_op(primitive, [func, Integer(0, c_pointer_rprimitive)], line)\n            builder.add(Return(val))\n\n    for name, primitive in writable_props.items():\n        with builder.enter_method(\n            callable_class_ir, f\"{PROPSET_PREFIX}{name}\", int_rprimitive, internal=True\n        ):\n            value = builder.add_argument(\"value\", object_rprimitive)\n            func = get_func_wrapper()\n            rv = builder.primitive_op(\n                primitive, [func, value, Integer(0, c_pointer_rprimitive)], line\n            )\n            builder.add(Return(rv))\n\n    for name in properties:\n        getter = callable_class_ir.get_method(name)\n        assert getter\n        setter = callable_class_ir.get_method(f\"{PROPSET_PREFIX}{name}\")\n        callable_class_ir.properties[name] = (getter, setter)\n\n\ndef add_call_to_callable_class(\n    builder: IRBuilder,\n    args: list[Register],\n    blocks: list[BasicBlock],\n    sig: FuncSignature,\n    fn_info: FuncInfo,\n) -> FuncIR:\n    \"\"\"Generate a '__call__' method for a callable class representing a nested function.\n\n    This takes the blocks and signature associated with a function\n    definition and uses those to build the '__call__' method of a\n    given callable class, used to represent that function.\n    \"\"\"\n    # Since we create a method, we also add a 'self' parameter.\n    nargs = len(sig.args) - sig.num_bitmap_args\n    sig = FuncSignature(\n        (RuntimeArg(SELF_NAME, object_rprimitive),) + sig.args[:nargs], sig.ret_type\n    )\n    call_fn_decl = FuncDecl(\"__call__\", fn_info.callable_class.ir.name, builder.module_name, sig)\n    call_fn_ir = FuncIR(\n        call_fn_decl, args, blocks, fn_info.fitem.line, traceback_name=fn_info.fitem.name\n    )\n    fn_info.callable_class.ir.methods[\"__call__\"] = call_fn_ir\n    fn_info.callable_class.ir.method_decls[\"__call__\"] = call_fn_decl\n    return call_fn_ir\n\n\ndef add_get_to_callable_class(builder: IRBuilder, fn_info: FuncInfo) -> None:\n    \"\"\"Generate the '__get__' method for a callable class.\"\"\"\n    line = fn_info.fitem.line\n    with builder.enter_method(\n        fn_info.callable_class.ir,\n        \"__get__\",\n        object_rprimitive,\n        fn_info,\n        self_type=object_rprimitive,\n    ):\n        instance = builder.add_argument(\"instance\", object_rprimitive)\n        builder.add_argument(\"owner\", object_rprimitive)\n\n        # If accessed through the class, just return the callable\n        # object. If accessed through an object, create a new bound\n        # instance method object.\n        instance_block, class_block = BasicBlock(), BasicBlock()\n        comparison = builder.translate_is_op(\n            builder.read(instance), builder.none_object(line), \"is\", line\n        )\n        builder.add_bool_branch(comparison, class_block, instance_block)\n\n        builder.activate_block(class_block)\n        builder.add(Return(builder.self()))\n\n        builder.activate_block(instance_block)\n        builder.add(\n            Return(builder.call_c(method_new_op, [builder.self(), builder.read(instance)], line))\n        )\n\n\ndef instantiate_callable_class(builder: IRBuilder, fn_info: FuncInfo) -> Value:\n    \"\"\"Create an instance of a callable class for a function.\n\n    Calls to the function will actually call this instance.\n\n    Note that fn_info refers to the function being assigned, whereas\n    builder.fn_info refers to the function encapsulating the function\n    being turned into a callable class.\n    \"\"\"\n    fitem = fn_info.fitem\n    func_reg = builder.add(Call(fn_info.callable_class.ir.ctor, [], fitem.line))\n\n    # Set the environment attribute of the callable class to point at\n    # the environment class defined in the callable class' immediate\n    # outer scope. Note that there are three possible environment\n    # class registers we may use. This depends on what the encapsulating\n    # (parent) function is:\n    #\n    # - A nested function: the callable class is instantiated\n    #   from the current callable class' '__call__' function, and hence\n    #   the callable class' environment register is used.\n    # - A generator function: the callable class is instantiated\n    #   from the '__next__' method of the generator class, and hence the\n    #   environment of the generator class is used.\n    # - Regular function or comprehension scope: we use the environment\n    #   of the original function. Comprehension scopes are inlined (no\n    #   callable class), so they fall into this case despite is_nested.\n    curr_env_reg = None\n    if builder.fn_info.is_generator:\n        curr_env_reg = builder.fn_info.generator_class.curr_env_reg\n    elif builder.fn_info.is_nested and not builder.fn_info.is_comprehension_scope:\n        curr_env_reg = builder.fn_info.callable_class.curr_env_reg\n    elif builder.fn_info.contains_nested:\n        curr_env_reg = builder.fn_info.curr_env_reg\n    if curr_env_reg:\n        builder.add(SetAttr(func_reg, ENV_ATTR_NAME, curr_env_reg, fitem.line))\n    # Initialize function wrapper for callable classes. As opposed to regular functions,\n    # each instance of a callable class needs its own wrapper because they might be instantiated\n    # inside other functions.\n    if not fn_info.in_non_ext and fn_info.is_coroutine:\n        builder.add_coroutine_setup_call(fn_info.callable_class.ir.name, func_reg)\n    return func_reg\n"
  },
  {
    "path": "mypyc/irbuild/classdef.py",
    "content": "\"\"\"Transform class definitions from the mypy AST form to IR.\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom collections.abc import Callable\nfrom typing import Final\n\nfrom mypy.nodes import (\n    EXCLUDED_ENUM_ATTRIBUTES,\n    TYPE_VAR_TUPLE_KIND,\n    AssignmentStmt,\n    CallExpr,\n    ClassDef,\n    Decorator,\n    EllipsisExpr,\n    ExpressionStmt,\n    FuncDef,\n    Lvalue,\n    MemberExpr,\n    NameExpr,\n    OverloadedFuncDef,\n    PassStmt,\n    RefExpr,\n    StrExpr,\n    TempNode,\n    TypeInfo,\n    TypeParam,\n    is_class_var,\n)\nfrom mypy.types import Instance, UnboundType, get_proper_type\nfrom mypyc.common import PROPSET_PREFIX\nfrom mypyc.ir.class_ir import ClassIR, NonExtClassInfo\nfrom mypyc.ir.func_ir import FuncDecl, FuncSignature\nfrom mypyc.ir.ops import (\n    NAMESPACE_TYPE,\n    BasicBlock,\n    Branch,\n    Call,\n    InitStatic,\n    LoadAddress,\n    LoadErrorValue,\n    LoadStatic,\n    MethodCall,\n    Register,\n    Return,\n    SetAttr,\n    TupleSet,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RType,\n    bool_rprimitive,\n    dict_rprimitive,\n    is_none_rprimitive,\n    is_object_rprimitive,\n    is_optional_type,\n    object_rprimitive,\n)\nfrom mypyc.irbuild.builder import IRBuilder, create_type_params\nfrom mypyc.irbuild.function import (\n    gen_property_getter_ir,\n    gen_property_setter_ir,\n    handle_ext_method,\n    handle_non_ext_method,\n    load_type,\n)\nfrom mypyc.irbuild.prepare import GENERATOR_HELPER_NAME\nfrom mypyc.irbuild.util import dataclass_type, get_func_def, is_constant, is_dataclass_decorator\nfrom mypyc.primitives.dict_ops import dict_new_op, exact_dict_set_item_op\nfrom mypyc.primitives.generic_ops import (\n    iter_op,\n    next_op,\n    py_get_item_op,\n    py_hasattr_op,\n    py_setattr_op,\n)\nfrom mypyc.primitives.misc_ops import (\n    dataclass_sleight_of_hand,\n    import_op,\n    not_implemented_op,\n    py_calc_meta_op,\n    py_init_subclass_op,\n    pytype_from_template_op,\n    type_object_op,\n)\nfrom mypyc.subtype import is_subtype\n\n\ndef transform_class_def(builder: IRBuilder, cdef: ClassDef) -> None:\n    \"\"\"Create IR for a class definition.\n\n    This can generate both extension (native) and non-extension\n    classes.  These are generated in very different ways. In the\n    latter case we construct a Python type object at runtime by doing\n    the equivalent of \"type(name, bases, dict)\" in IR. Extension\n    classes are defined via C structs that are generated later in\n    mypyc.codegen.emitclass.\n\n    This is the main entry point to this module.\n    \"\"\"\n    if cdef.info not in builder.mapper.type_to_ir:\n        builder.error(\"Nested class definitions not supported\", cdef.line)\n        return\n\n    ir = builder.mapper.type_to_ir[cdef.info]\n\n    # We do this check here because the base field of parent\n    # classes aren't necessarily populated yet at\n    # prepare_class_def time.\n    if any(ir.base_mro[i].base != ir.base_mro[i + 1] for i in range(len(ir.base_mro) - 1)):\n        builder.error(\"Multiple inheritance is not supported (except for traits)\", cdef.line)\n\n    if ir.allow_interpreted_subclasses:\n        for parent in ir.mro:\n            if not parent.allow_interpreted_subclasses:\n                builder.error(\n                    'Base class \"{}\" does not allow interpreted subclasses'.format(\n                        parent.fullname\n                    ),\n                    cdef.line,\n                )\n\n    # Currently, we only create non-extension classes for classes that are\n    # decorated or inherit from Enum. Classes decorated with @trait do not\n    # apply here, and are handled in a different way.\n    if ir.is_ext_class:\n        cls_type = dataclass_type(cdef)\n        if cls_type is None:\n            cls_builder: ClassBuilder = ExtClassBuilder(builder, cdef)\n        elif cls_type in [\"dataclasses\", \"attr-auto\"]:\n            cls_builder = DataClassBuilder(builder, cdef)\n        elif cls_type == \"attr\":\n            cls_builder = AttrsClassBuilder(builder, cdef)\n        else:\n            raise ValueError(cls_type)\n    else:\n        cls_builder = NonExtClassBuilder(builder, cdef)\n\n    for stmt in cdef.defs.body:\n        if (\n            isinstance(stmt, (FuncDef, Decorator, OverloadedFuncDef))\n            and stmt.name == GENERATOR_HELPER_NAME\n        ):\n            builder.error(\n                f'Method name \"{stmt.name}\" is reserved for mypyc internal use', stmt.line\n            )\n\n        if isinstance(stmt, OverloadedFuncDef) and stmt.is_property:\n            if isinstance(cls_builder, NonExtClassBuilder):\n                # properties with both getters and setters in non_extension\n                # classes not supported\n                builder.error(\"Property setters not supported in non-extension classes\", stmt.line)\n            for item in stmt.items:\n                with builder.catch_errors(stmt.line):\n                    cls_builder.add_method(get_func_def(item))\n        elif isinstance(stmt, (FuncDef, Decorator, OverloadedFuncDef)):\n            # Ignore plugin generated methods (since they have no\n            # bodies to compile and will need to have the bodies\n            # provided by some other mechanism.)\n            if cdef.info.names[stmt.name].plugin_generated:\n                continue\n            with builder.catch_errors(stmt.line):\n                cls_builder.add_method(get_func_def(stmt))\n        elif isinstance(stmt, PassStmt) or (\n            isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, EllipsisExpr)\n        ):\n            continue\n        elif isinstance(stmt, AssignmentStmt):\n            if len(stmt.lvalues) != 1:\n                builder.error(\"Multiple assignment in class bodies not supported\", stmt.line)\n                continue\n            lvalue = stmt.lvalues[0]\n            if not isinstance(lvalue, NameExpr):\n                builder.error(\n                    \"Only assignment to variables is supported in class bodies\", stmt.line\n                )\n                continue\n            # We want to collect class variables in a dictionary for both real\n            # non-extension classes and fake dataclass ones.\n            cls_builder.add_attr(lvalue, stmt)\n\n        elif isinstance(stmt, ExpressionStmt) and isinstance(stmt.expr, StrExpr):\n            # Docstring. Ignore\n            pass\n        else:\n            builder.error(\"Unsupported statement in class body\", stmt.line)\n\n    # Generate implicit property setters/getters\n    for name, decl in ir.method_decls.items():\n        if decl.implicit and decl.is_prop_getter:\n            getter_ir = gen_property_getter_ir(builder, decl, cdef, ir.is_trait)\n            builder.functions.append(getter_ir)\n            ir.methods[getter_ir.decl.name] = getter_ir\n\n            setter_ir = None\n            setter_name = PROPSET_PREFIX + name\n            if setter_name in ir.method_decls:\n                setter_ir = gen_property_setter_ir(\n                    builder, ir.method_decls[setter_name], cdef, ir.is_trait\n                )\n                builder.functions.append(setter_ir)\n                ir.methods[setter_name] = setter_ir\n\n            ir.properties[name] = (getter_ir, setter_ir)\n            # TODO: Generate glue method if needed?\n            # TODO: Do we need interpreted glue methods? Maybe not?\n\n    cls_builder.finalize(ir)\n\n\nclass ClassBuilder:\n    \"\"\"Create IR for a class definition.\n\n    This is an abstract base class.\n    \"\"\"\n\n    def __init__(self, builder: IRBuilder, cdef: ClassDef) -> None:\n        self.builder = builder\n        self.cdef = cdef\n        self.attrs_to_cache: list[tuple[Lvalue, RType]] = []\n\n    @abstractmethod\n    def add_method(self, fdef: FuncDef) -> None:\n        \"\"\"Add a method to the class IR\"\"\"\n\n    @abstractmethod\n    def add_attr(self, lvalue: NameExpr, stmt: AssignmentStmt) -> None:\n        \"\"\"Add an attribute to the class IR\"\"\"\n\n    @abstractmethod\n    def finalize(self, ir: ClassIR) -> None:\n        \"\"\"Perform any final operations to complete the class IR\"\"\"\n\n\nclass NonExtClassBuilder(ClassBuilder):\n    def __init__(self, builder: IRBuilder, cdef: ClassDef) -> None:\n        super().__init__(builder, cdef)\n        self.non_ext = self.create_non_ext_info()\n\n    def create_non_ext_info(self) -> NonExtClassInfo:\n        non_ext_bases = populate_non_ext_bases(self.builder, self.cdef)\n        non_ext_metaclass = find_non_ext_metaclass(self.builder, self.cdef, non_ext_bases)\n        non_ext_dict = setup_non_ext_dict(\n            self.builder, self.cdef, non_ext_metaclass, non_ext_bases\n        )\n        # We populate __annotations__ for non-extension classes\n        # because dataclasses uses it to determine which attributes to compute on.\n        # TODO: Maybe generate more precise types for annotations\n        non_ext_anns = self.builder.call_c(dict_new_op, [], self.cdef.line)\n        return NonExtClassInfo(non_ext_dict, non_ext_bases, non_ext_anns, non_ext_metaclass)\n\n    def add_method(self, fdef: FuncDef) -> None:\n        handle_non_ext_method(self.builder, self.non_ext, self.cdef, fdef)\n\n    def add_attr(self, lvalue: NameExpr, stmt: AssignmentStmt) -> None:\n        add_non_ext_class_attr_ann(self.builder, self.non_ext, lvalue, stmt)\n        add_non_ext_class_attr(\n            self.builder, self.non_ext, lvalue, stmt, self.cdef, self.attrs_to_cache\n        )\n\n    def finalize(self, ir: ClassIR) -> None:\n        # Dynamically create the class via the type constructor\n        non_ext_class = load_non_ext_class(self.builder, ir, self.non_ext, self.cdef.line)\n        non_ext_class = load_decorated_class(self.builder, self.cdef, non_ext_class)\n\n        # Try to avoid contention when using free threading.\n        self.builder.set_immortal_if_free_threaded(non_ext_class, self.cdef.line)\n\n        # Save the decorated class\n        self.builder.add(\n            InitStatic(non_ext_class, self.cdef.name, self.builder.module_name, NAMESPACE_TYPE)\n        )\n\n        # Add the non-extension class to the dict\n        self.builder.call_c(\n            exact_dict_set_item_op,\n            [\n                self.builder.load_globals_dict(),\n                self.builder.load_str(self.cdef.name),\n                non_ext_class,\n            ],\n            self.cdef.line,\n        )\n\n        # Cache any cacheable class attributes\n        cache_class_attrs(self.builder, self.attrs_to_cache, self.cdef)\n\n\nclass ExtClassBuilder(ClassBuilder):\n    def __init__(self, builder: IRBuilder, cdef: ClassDef) -> None:\n        super().__init__(builder, cdef)\n        # If the class is not decorated, generate an extension class for it.\n        self.type_obj: Value = allocate_class(builder, cdef)\n\n    def skip_attr_default(self, name: str, stmt: AssignmentStmt) -> bool:\n        \"\"\"Controls whether to skip generating a default for an attribute.\"\"\"\n        return False\n\n    def add_method(self, fdef: FuncDef) -> None:\n        handle_ext_method(self.builder, self.cdef, fdef)\n\n    def add_attr(self, lvalue: NameExpr, stmt: AssignmentStmt) -> None:\n        # Variable declaration with no body\n        if isinstance(stmt.rvalue, TempNode):\n            return\n        # Only treat marked class variables as class variables.\n        if not (is_class_var(lvalue) or stmt.is_final_def):\n            return\n        typ = self.builder.load_native_type_object(self.cdef.fullname)\n        value = self.builder.accept(stmt.rvalue)\n        self.builder.primitive_op(\n            py_setattr_op, [typ, self.builder.load_str(lvalue.name), value], stmt.line\n        )\n        if self.builder.non_function_scope() and stmt.is_final_def:\n            self.builder.init_final_static(lvalue, value, self.cdef.name)\n\n    def finalize(self, ir: ClassIR) -> None:\n        # Call __init_subclass__ after class attributes have been set\n        self.builder.call_c(py_init_subclass_op, [self.type_obj], self.cdef.line)\n\n        attrs_with_defaults, default_assignments = find_attr_initializers(\n            self.builder, self.cdef, self.skip_attr_default\n        )\n        ir.attrs_with_defaults.update(attrs_with_defaults)\n        generate_attr_defaults_init(self.builder, self.cdef, default_assignments)\n        create_ne_from_eq(self.builder, self.cdef)\n\n\nclass DataClassBuilder(ExtClassBuilder):\n    # controls whether an __annotations__ attribute should be added to the class\n    # __dict__.  This is not desirable for attrs classes where auto_attribs is\n    # disabled, as attrs will reject it.\n    add_annotations_to_dict = True\n\n    def __init__(self, builder: IRBuilder, cdef: ClassDef) -> None:\n        super().__init__(builder, cdef)\n        self.non_ext = self.create_non_ext_info()\n\n    def create_non_ext_info(self) -> NonExtClassInfo:\n        \"\"\"Set up a NonExtClassInfo to track dataclass attributes.\n\n        In addition to setting up a normal extension class for dataclasses,\n        we also collect its class attributes like a non-extension class so\n        that we can hand them to the dataclass decorator.\n        \"\"\"\n        return NonExtClassInfo(\n            self.builder.call_c(dict_new_op, [], self.cdef.line),\n            self.builder.add(TupleSet([], self.cdef.line)),\n            self.builder.call_c(dict_new_op, [], self.cdef.line),\n            self.builder.add(LoadAddress(type_object_op.type, type_object_op.src, self.cdef.line)),\n        )\n\n    def skip_attr_default(self, name: str, stmt: AssignmentStmt) -> bool:\n        return stmt.type is not None\n\n    def get_type_annotation(self, stmt: AssignmentStmt) -> TypeInfo | None:\n        # We populate __annotations__ because dataclasses uses it to determine\n        # which attributes to compute on.\n        ann_type = get_proper_type(stmt.type)\n        if isinstance(ann_type, Instance):\n            return ann_type.type\n        return None\n\n    def add_attr(self, lvalue: NameExpr, stmt: AssignmentStmt) -> None:\n        add_non_ext_class_attr_ann(\n            self.builder, self.non_ext, lvalue, stmt, self.get_type_annotation\n        )\n        add_non_ext_class_attr(\n            self.builder, self.non_ext, lvalue, stmt, self.cdef, self.attrs_to_cache\n        )\n        super().add_attr(lvalue, stmt)\n\n    def finalize(self, ir: ClassIR) -> None:\n        \"\"\"Generate code to finish instantiating a dataclass.\n\n        This works by replacing all of the attributes on the class\n        (which will be descriptors) with whatever they would be in a\n        non-extension class, calling dataclass, then switching them back.\n\n        The resulting class is an extension class and instances of it do not\n        have a __dict__ (unless something else requires it).\n        All methods written explicitly in the source are compiled and\n        may be called through the vtable while the methods generated\n        by dataclasses are interpreted and may not be.\n\n        (If we just called dataclass without doing this, it would think that all\n        of the descriptors for our attributes are default values and generate an\n        incorrect constructor. We need to do the switch so that dataclass gets the\n        appropriate defaults.)\n        \"\"\"\n        super().finalize(ir)\n        assert self.type_obj\n        add_dunders_to_non_ext_dict(\n            self.builder, self.non_ext, self.cdef.line, self.add_annotations_to_dict\n        )\n        dec = self.builder.accept(\n            next(d for d in self.cdef.decorators if is_dataclass_decorator(d))\n        )\n        dataclass_type_val = self.builder.load_str(dataclass_type(self.cdef) or \"unknown\")\n        self.builder.call_c(\n            dataclass_sleight_of_hand,\n            [dec, self.type_obj, self.non_ext.dict, self.non_ext.anns, dataclass_type_val],\n            self.cdef.line,\n        )\n\n\nclass AttrsClassBuilder(DataClassBuilder):\n    \"\"\"Create IR for an attrs class where auto_attribs=False (the default).\n\n    When auto_attribs is enabled, attrs classes behave similarly to dataclasses\n    (i.e. types are stored as annotations on the class) and are thus handled\n    by DataClassBuilder, but when auto_attribs is disabled the types are\n    provided via attr.ib(type=...)\n    \"\"\"\n\n    add_annotations_to_dict = False\n\n    def skip_attr_default(self, name: str, stmt: AssignmentStmt) -> bool:\n        return True\n\n    def get_type_annotation(self, stmt: AssignmentStmt) -> TypeInfo | None:\n        if isinstance(stmt.rvalue, CallExpr):\n            # find the type arg in `attr.ib(type=str)`\n            callee = stmt.rvalue.callee\n            if (\n                isinstance(callee, MemberExpr)\n                and callee.fullname in [\"attr.ib\", \"attr.attr\"]\n                and \"type\" in stmt.rvalue.arg_names\n            ):\n                index = stmt.rvalue.arg_names.index(\"type\")\n                type_name = stmt.rvalue.args[index]\n                if isinstance(type_name, NameExpr) and isinstance(type_name.node, TypeInfo):\n                    lvalue = stmt.lvalues[0]\n                    assert isinstance(lvalue, NameExpr), lvalue\n                    return type_name.node\n        return None\n\n\ndef allocate_class(builder: IRBuilder, cdef: ClassDef) -> Value:\n    # OK AND NOW THE FUN PART\n    base_exprs = cdef.base_type_exprs + cdef.removed_base_type_exprs\n    new_style_type_args = cdef.type_args\n    if new_style_type_args:\n        bases = [make_generic_base_class(builder, cdef.fullname, new_style_type_args, cdef.line)]\n    else:\n        bases = []\n\n    if base_exprs or new_style_type_args:\n        bases.extend([builder.accept(x) for x in base_exprs])\n        tp_bases = builder.new_tuple(bases, cdef.line)\n    else:\n        tp_bases = builder.add(LoadErrorValue(object_rprimitive, is_borrowed=True))\n    modname = builder.load_str(builder.module_name)\n    template = builder.add(\n        LoadStatic(object_rprimitive, cdef.name + \"_template\", builder.module_name, NAMESPACE_TYPE)\n    )\n    # Create the class\n    tp = builder.call_c(pytype_from_template_op, [template, tp_bases, modname], cdef.line)\n\n    # Set type object to be immortal if free threaded, as otherwise reference count contention\n    # can cause a big performance hit.\n    builder.set_immortal_if_free_threaded(tp, cdef.line)\n\n    # Immediately fix up the trait vtables, before doing anything with the class.\n    ir = builder.mapper.type_to_ir[cdef.info]\n    if not ir.is_trait and not ir.builtin_base:\n        builder.add(\n            Call(\n                FuncDecl(\n                    cdef.name + \"_trait_vtable_setup\",\n                    None,\n                    builder.module_name,\n                    FuncSignature([], bool_rprimitive),\n                ),\n                [],\n                cdef.line,\n            )\n        )\n        builder.add_coroutine_setup_call(cdef.name, tp)\n\n    # Populate a '__mypyc_attrs__' field containing the list of attrs\n    builder.primitive_op(\n        py_setattr_op,\n        [\n            tp,\n            builder.load_str(\"__mypyc_attrs__\"),\n            create_mypyc_attrs_tuple(builder, builder.mapper.type_to_ir[cdef.info], cdef.line),\n        ],\n        cdef.line,\n    )\n\n    # Save the class\n    builder.add(InitStatic(tp, cdef.name, builder.module_name, NAMESPACE_TYPE))\n\n    # Add it to the dict\n    builder.call_c(\n        exact_dict_set_item_op,\n        [builder.load_globals_dict(), builder.load_str(cdef.name), tp],\n        cdef.line,\n    )\n\n    return tp\n\n\ndef make_generic_base_class(\n    builder: IRBuilder, fullname: str, type_args: list[TypeParam], line: int\n) -> Value:\n    \"\"\"Construct Generic[...] base class object for a new-style generic class (Python 3.12).\"\"\"\n    mod = builder.call_c(import_op, [builder.load_str(\"_typing\")], line)\n    tvs = create_type_params(builder, mod, type_args, line)\n    args = []\n    for tv, type_param in zip(tvs, type_args):\n        if type_param.kind == TYPE_VAR_TUPLE_KIND:\n            # Evaluate *Ts for a TypeVarTuple\n            it = builder.primitive_op(iter_op, [tv], line)\n            tv = builder.call_c(next_op, [it], line)\n        args.append(tv)\n\n    gent = builder.py_get_attr(mod, \"Generic\", line)\n    if len(args) == 1:\n        arg = args[0]\n    else:\n        arg = builder.new_tuple(args, line)\n\n    base = builder.primitive_op(py_get_item_op, [gent, arg], line)\n    return base\n\n\n# Mypy uses these internally as base classes of TypedDict classes. These are\n# lies and don't have any runtime equivalent.\nMAGIC_TYPED_DICT_CLASSES: Final[tuple[str, ...]] = (\n    \"typing._TypedDict\",\n    \"typing_extensions._TypedDict\",\n)\n\n\ndef populate_non_ext_bases(builder: IRBuilder, cdef: ClassDef) -> Value:\n    \"\"\"Create base class tuple of a non-extension class.\n\n    The tuple is passed to the metaclass constructor.\n    \"\"\"\n    is_named_tuple = cdef.info.is_named_tuple\n    ir = builder.mapper.type_to_ir[cdef.info]\n    bases = []\n    for cls in (b.type for b in cdef.info.bases):\n        if cls.fullname == \"builtins.object\":\n            continue\n        if is_named_tuple and cls.fullname in (\n            \"typing.Sequence\",\n            \"typing.Iterable\",\n            \"typing.Collection\",\n            \"typing.Reversible\",\n            \"typing.Container\",\n            \"typing.Sized\",\n        ):\n            # HAX: Synthesized base classes added by mypy don't exist at runtime, so skip them.\n            #      This could break if they were added explicitly, though...\n            continue\n        # Add the current class to the base classes list of concrete subclasses\n        if cls in builder.mapper.type_to_ir:\n            base_ir = builder.mapper.type_to_ir[cls]\n            if base_ir.children is not None:\n                base_ir.children.append(ir)\n\n        if cls.fullname in MAGIC_TYPED_DICT_CLASSES:\n            # HAX: Mypy internally represents TypedDict classes differently from what\n            #      should happen at runtime. Replace with something that works.\n            module = \"typing\"\n            name = \"_TypedDict\"\n            base = builder.get_module_attr(module, name, cdef.line)\n        elif is_named_tuple and cls.fullname == \"builtins.tuple\":\n            name = \"_NamedTuple\"\n            base = builder.get_module_attr(\"typing\", name, cdef.line)\n        else:\n            cls_module = cls.fullname.rsplit(\".\", 1)[0]\n            if cls_module == builder.current_module:\n                base = builder.load_global_str(cls.name, cdef.line)\n            else:\n                base = builder.load_module_attr_by_fullname(cls.fullname, cdef.line)\n        bases.append(base)\n        if cls.fullname in MAGIC_TYPED_DICT_CLASSES:\n            # The remaining base classes are synthesized by mypy and should be ignored.\n            break\n    return builder.new_tuple(bases, cdef.line)\n\n\ndef find_non_ext_metaclass(builder: IRBuilder, cdef: ClassDef, bases: Value) -> Value:\n    \"\"\"Find the metaclass of a class from its defs and bases.\"\"\"\n    if cdef.metaclass:\n        declared_metaclass = builder.accept(cdef.metaclass)\n    else:\n        if cdef.info.typeddict_type is not None:\n            # In Python 3.9, the metaclass for class-based TypedDict is typing._TypedDictMeta.\n            # We can't easily calculate it generically, so special case it.\n            return builder.get_module_attr(\"typing\", \"_TypedDictMeta\", cdef.line)\n        elif cdef.info.is_named_tuple:\n            # In Python 3.9, the metaclass for class-based NamedTuple is typing.NamedTupleMeta.\n            # We can't easily calculate it generically, so special case it.\n            return builder.get_module_attr(\"typing\", \"NamedTupleMeta\", cdef.line)\n\n        declared_metaclass = builder.add(\n            LoadAddress(type_object_op.type, type_object_op.src, cdef.line)\n        )\n\n    return builder.call_c(py_calc_meta_op, [declared_metaclass, bases], cdef.line)\n\n\ndef setup_non_ext_dict(\n    builder: IRBuilder, cdef: ClassDef, metaclass: Value, bases: Value\n) -> Value:\n    \"\"\"Initialize the class dictionary for a non-extension class.\n\n    This class dictionary is passed to the metaclass constructor.\n    \"\"\"\n    # Check if the metaclass defines a __prepare__ method, and if so, call it.\n    has_prepare = builder.primitive_op(\n        py_hasattr_op, [metaclass, builder.load_str(\"__prepare__\")], cdef.line\n    )\n\n    non_ext_dict = Register(dict_rprimitive)\n\n    true_block, false_block, exit_block = BasicBlock(), BasicBlock(), BasicBlock()\n    builder.add_bool_branch(has_prepare, true_block, false_block)\n\n    builder.activate_block(true_block)\n    cls_name = builder.load_str(cdef.name)\n    prepare_meth = builder.py_get_attr(metaclass, \"__prepare__\", cdef.line)\n    prepare_dict = builder.py_call(prepare_meth, [cls_name, bases], cdef.line)\n    builder.assign(non_ext_dict, prepare_dict, cdef.line)\n    builder.goto(exit_block)\n\n    builder.activate_block(false_block)\n    builder.assign(non_ext_dict, builder.call_c(dict_new_op, [], cdef.line), cdef.line)\n    builder.goto(exit_block)\n    builder.activate_block(exit_block)\n\n    return non_ext_dict\n\n\ndef add_non_ext_class_attr_ann(\n    builder: IRBuilder,\n    non_ext: NonExtClassInfo,\n    lvalue: NameExpr,\n    stmt: AssignmentStmt,\n    get_type_info: Callable[[AssignmentStmt], TypeInfo | None] | None = None,\n) -> None:\n    \"\"\"Add a class attribute to __annotations__ of a non-extension class.\"\"\"\n    # FIXME: try to better preserve the special forms and type parameters of generics.\n    typ: Value | None = None\n    if get_type_info is not None:\n        type_info = get_type_info(stmt)\n        if type_info:\n            # NOTE: Using string type information is similar to using\n            # `from __future__ import annotations` in standard python.\n            # NOTE: For string types we need to use the fullname since it\n            # includes the module. If string type doesn't have the module,\n            # @dataclass will try to get the current module and fail since the\n            # current module is not in sys.modules.\n            if builder.current_module == type_info.module_name and stmt.line < type_info.line:\n                typ = builder.load_str(type_info.fullname)\n            else:\n                typ = load_type(builder, type_info, stmt.unanalyzed_type, stmt.line)\n\n    if typ is None:\n        # FIXME: if get_type_info is not provided, don't fall back to stmt.type?\n        ann_type = get_proper_type(stmt.type)\n        if (\n            isinstance(stmt.unanalyzed_type, UnboundType)\n            and stmt.unanalyzed_type.original_str_expr is not None\n        ):\n            # Annotation is a forward reference, so don't attempt to load the actual\n            # type and load the string instead.\n            #\n            # TODO: is it possible to determine whether a non-string annotation is\n            # actually a forward reference due to the __annotations__ future?\n            typ = builder.load_str(stmt.unanalyzed_type.original_str_expr)\n        elif isinstance(ann_type, Instance):\n            typ = load_type(builder, ann_type.type, stmt.unanalyzed_type, stmt.line)\n        else:\n            typ = builder.add(LoadAddress(type_object_op.type, type_object_op.src, stmt.line))\n\n    key = builder.load_str(lvalue.name)\n    builder.call_c(exact_dict_set_item_op, [non_ext.anns, key, typ], stmt.line)\n\n\ndef add_non_ext_class_attr(\n    builder: IRBuilder,\n    non_ext: NonExtClassInfo,\n    lvalue: NameExpr,\n    stmt: AssignmentStmt,\n    cdef: ClassDef,\n    attr_to_cache: list[tuple[Lvalue, RType]],\n) -> None:\n    \"\"\"Add a class attribute to __dict__ of a non-extension class.\"\"\"\n    # Only add the attribute to the __dict__ if the assignment is of the form:\n    # x: type = value (don't add attributes of the form 'x: type' to the __dict__).\n    if not isinstance(stmt.rvalue, TempNode):\n        rvalue = builder.accept(stmt.rvalue)\n        builder.add_to_non_ext_dict(non_ext, lvalue.name, rvalue, stmt.line)\n        # We cache enum attributes to speed up enum attribute lookup since they\n        # are final.\n        if (\n            cdef.info.bases\n            # Enum class must be the last parent class.\n            and cdef.info.bases[-1].type.is_enum\n            # Skip these since Enum will remove it\n            and lvalue.name not in EXCLUDED_ENUM_ATTRIBUTES\n        ):\n            # Enum values are always boxed, so use object_rprimitive.\n            attr_to_cache.append((lvalue, object_rprimitive))\n\n\ndef find_attr_initializers(\n    builder: IRBuilder, cdef: ClassDef, skip: Callable[[str, AssignmentStmt], bool] | None = None\n) -> tuple[set[str], list[AssignmentStmt]]:\n    \"\"\"Find initializers of attributes in a class body.\n\n    If provided, the skip arg should be a callable which will return whether\n    to skip generating a default for an attribute.  It will be passed the name of\n    the attribute and the corresponding AssignmentStmt.\n    \"\"\"\n    cls = builder.mapper.type_to_ir[cdef.info]\n    if cls.builtin_base:\n        return set(), []\n\n    attrs_with_defaults = set()\n\n    # Pull out all assignments in classes in the mro so we can initialize them\n    # TODO: Support nested statements\n    default_assignments = []\n    for info in reversed(cdef.info.mro):\n        if info not in builder.mapper.type_to_ir:\n            continue\n        for stmt in info.defn.defs.body:\n            if (\n                isinstance(stmt, AssignmentStmt)\n                and isinstance(stmt.lvalues[0], NameExpr)\n                and not is_class_var(stmt.lvalues[0])\n                and not isinstance(stmt.rvalue, TempNode)\n            ):\n                name = stmt.lvalues[0].name\n                if name == \"__slots__\":\n                    continue\n\n                if name == \"__deletable__\":\n                    check_deletable_declaration(builder, cls, stmt.line)\n                    continue\n\n                if skip is not None and skip(name, stmt):\n                    continue\n\n                attr_type = cls.attr_type(name)\n\n                # If the attribute is initialized to None and type isn't optional,\n                # doesn't initialize it to anything (special case for \"# type:\" comments).\n                if isinstance(stmt.rvalue, RefExpr) and stmt.rvalue.fullname == \"builtins.None\":\n                    if (\n                        not is_optional_type(attr_type)\n                        and not is_object_rprimitive(attr_type)\n                        and not is_none_rprimitive(attr_type)\n                    ):\n                        continue\n\n                attrs_with_defaults.add(name)\n                default_assignments.append(stmt)\n\n    return attrs_with_defaults, default_assignments\n\n\ndef generate_attr_defaults_init(\n    builder: IRBuilder, cdef: ClassDef, default_assignments: list[AssignmentStmt]\n) -> None:\n    \"\"\"Generate an initialization method for default attr values (from class vars).\"\"\"\n    if not default_assignments:\n        return\n    cls = builder.mapper.type_to_ir[cdef.info]\n    if cls.builtin_base:\n        return\n\n    with builder.enter_method(cls, \"__mypyc_defaults_setup\", bool_rprimitive):\n        self_var = builder.self()\n        for stmt in default_assignments:\n            lvalue = stmt.lvalues[0]\n            assert isinstance(lvalue, NameExpr), lvalue\n            if not stmt.is_final_def and not is_constant(stmt.rvalue):\n                builder.warning(\"Unsupported default attribute value\", stmt.rvalue.line)\n\n            attr_type = cls.attr_type(lvalue.name)\n            val = builder.coerce(builder.accept(stmt.rvalue), attr_type, stmt.line)\n            init = SetAttr(self_var, lvalue.name, val, stmt.rvalue.line)\n            init.mark_as_initializer()\n            builder.add(init)\n\n        builder.add(Return(builder.true()))\n\n\ndef check_deletable_declaration(builder: IRBuilder, cl: ClassIR, line: int) -> None:\n    for attr in cl.deletable:\n        if attr not in cl.attributes:\n            if not cl.has_attr(attr):\n                builder.error(f'Attribute \"{attr}\" not defined', line)\n                continue\n            for base in cl.mro:\n                if attr in base.property_types:\n                    builder.error(f'Cannot make property \"{attr}\" deletable', line)\n                    break\n            else:\n                _, base = cl.attr_details(attr)\n                builder.error(\n                    ('Attribute \"{}\" not defined in \"{}\" ' + '(defined in \"{}\")').format(\n                        attr, cl.name, base.name\n                    ),\n                    line,\n                )\n\n\ndef create_ne_from_eq(builder: IRBuilder, cdef: ClassDef) -> None:\n    \"\"\"Create a \"__ne__\" method from a \"__eq__\" method (if only latter exists).\"\"\"\n    cls = builder.mapper.type_to_ir[cdef.info]\n    if cls.has_method(\"__eq__\") and not cls.has_method(\"__ne__\"):\n        gen_glue_ne_method(builder, cls, cdef.line)\n\n\ndef gen_glue_ne_method(builder: IRBuilder, cls: ClassIR, line: int) -> None:\n    \"\"\"Generate a \"__ne__\" method from a \"__eq__\" method.\"\"\"\n    func_ir = cls.get_method(\"__eq__\")\n    assert func_ir\n    eq_sig = func_ir.decl.sig\n    strict_typing = builder.options.strict_dunders_typing\n    with builder.enter_method(cls, \"__ne__\", eq_sig.ret_type):\n        rhs_type = eq_sig.args[0].type if strict_typing else object_rprimitive\n        rhs_arg = builder.add_argument(\"rhs\", rhs_type)\n        eqval = builder.add(MethodCall(builder.self(), \"__eq__\", [rhs_arg], line))\n\n        can_return_not_implemented = is_subtype(not_implemented_op.type, eq_sig.ret_type)\n        return_bool = is_subtype(eq_sig.ret_type, bool_rprimitive)\n\n        if not strict_typing or can_return_not_implemented:\n            # If __eq__ returns NotImplemented, then __ne__ should also\n            not_implemented_block, regular_block = BasicBlock(), BasicBlock()\n            not_implemented = builder.add(\n                LoadAddress(not_implemented_op.type, not_implemented_op.src, line)\n            )\n            builder.add(\n                Branch(\n                    builder.translate_is_op(eqval, not_implemented, \"is\", line),\n                    not_implemented_block,\n                    regular_block,\n                    Branch.BOOL,\n                )\n            )\n            builder.activate_block(regular_block)\n            rettype = bool_rprimitive if return_bool and strict_typing else object_rprimitive\n            retval = builder.coerce(\n                builder.builder.unary_not(eqval, line, likely_bool=True), rettype, line\n            )\n            builder.add(Return(retval))\n            builder.activate_block(not_implemented_block)\n            builder.add(Return(not_implemented))\n        else:\n            rettype = bool_rprimitive if return_bool and strict_typing else object_rprimitive\n            retval = builder.coerce(builder.unary_op(eqval, \"not\", line), rettype, line)\n            builder.add(Return(retval))\n\n\ndef load_non_ext_class(\n    builder: IRBuilder, ir: ClassIR, non_ext: NonExtClassInfo, line: int\n) -> Value:\n    cls_name = builder.load_str(ir.name)\n\n    add_dunders_to_non_ext_dict(builder, non_ext, line)\n\n    class_type_obj = builder.py_call(\n        non_ext.metaclass, [cls_name, non_ext.bases, non_ext.dict], line\n    )\n    return class_type_obj\n\n\ndef load_decorated_class(builder: IRBuilder, cdef: ClassDef, type_obj: Value) -> Value:\n    \"\"\"Apply class decorators to create a decorated (non-extension) class object.\n\n    Given a decorated ClassDef and a register containing a\n    non-extension representation of the ClassDef created via the type\n    constructor, applies the corresponding decorator functions on that\n    decorated ClassDef and returns a register containing the decorated\n    ClassDef.\n    \"\"\"\n    decorators = cdef.decorators\n    dec_class = type_obj\n    for d in reversed(decorators):\n        decorator = d.accept(builder.visitor)\n        assert isinstance(decorator, Value), decorator\n        dec_class = builder.py_call(decorator, [dec_class], dec_class.line)\n    return dec_class\n\n\ndef cache_class_attrs(\n    builder: IRBuilder, attrs_to_cache: list[tuple[Lvalue, RType]], cdef: ClassDef\n) -> None:\n    \"\"\"Add class attributes to be cached to the global cache.\"\"\"\n    typ = builder.load_native_type_object(cdef.info.fullname)\n    for lval, rtype in attrs_to_cache:\n        assert isinstance(lval, NameExpr), lval\n        rval = builder.py_get_attr(typ, lval.name, cdef.line)\n        builder.init_final_static(lval, rval, cdef.name, type_override=rtype)\n\n\ndef create_mypyc_attrs_tuple(builder: IRBuilder, ir: ClassIR, line: int) -> Value:\n    attrs = [name for ancestor in ir.mro for name in ancestor.attributes]\n    if ir.inherits_python:\n        attrs.append(\"__dict__\")\n    items = [builder.load_str(attr) for attr in attrs]\n    return builder.new_tuple(items, line)\n\n\ndef add_dunders_to_non_ext_dict(\n    builder: IRBuilder, non_ext: NonExtClassInfo, line: int, add_annotations: bool = True\n) -> None:\n    if add_annotations:\n        # Add __annotations__ to the class dict.\n        builder.add_to_non_ext_dict(non_ext, \"__annotations__\", non_ext.anns, line)\n\n    # We add a __doc__ attribute so if the non-extension class is decorated with the\n    # dataclass decorator, dataclass will not try to look for __text_signature__.\n    # https://github.com/python/cpython/blob/3.7/Lib/dataclasses.py#L957\n    filler_doc_str = \"mypyc filler docstring\"\n    builder.add_to_non_ext_dict(non_ext, \"__doc__\", builder.load_str(filler_doc_str), line)\n    builder.add_to_non_ext_dict(non_ext, \"__module__\", builder.load_str(builder.module_name), line)\n"
  },
  {
    "path": "mypyc/irbuild/constant_fold.py",
    "content": "\"\"\"Constant folding of IR values.\n\nFor example, 3 + 5 can be constant folded into 8.\n\nThis is mostly like mypy.constant_fold, but we can bind some additional\nNameExpr and MemberExpr references here, since we have more knowledge\nabout which definitions can be trusted -- we constant fold only references\nto other compiled modules in the same compilation unit.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Final\n\nfrom mypy.constant_fold import constant_fold_binary_op, constant_fold_unary_op\nfrom mypy.nodes import (\n    BytesExpr,\n    ComplexExpr,\n    Expression,\n    FloatExpr,\n    IntExpr,\n    MemberExpr,\n    NameExpr,\n    OpExpr,\n    StrExpr,\n    UnaryExpr,\n    Var,\n)\nfrom mypyc.irbuild.util import bytes_from_str\n\nif TYPE_CHECKING:\n    from mypyc.irbuild.builder import IRBuilder\n\n# All possible result types of constant folding\nConstantValue = int | float | complex | str | bytes\nCONST_TYPES: Final = (int, float, complex, str, bytes)\n\n\ndef constant_fold_expr(builder: IRBuilder, expr: Expression) -> ConstantValue | None:\n    \"\"\"Return the constant value of an expression for supported operations.\n\n    Return None otherwise.\n    \"\"\"\n    if isinstance(expr, IntExpr):\n        return expr.value\n    if isinstance(expr, FloatExpr):\n        return expr.value\n    if isinstance(expr, StrExpr):\n        return expr.value\n    if isinstance(expr, BytesExpr):\n        return bytes_from_str(expr.value)\n    if isinstance(expr, ComplexExpr):\n        return expr.value\n    elif isinstance(expr, NameExpr):\n        node = expr.node\n        if isinstance(node, Var) and node.is_final:\n            final_value = node.final_value\n            if isinstance(final_value, (CONST_TYPES)):\n                return final_value\n    elif isinstance(expr, MemberExpr):\n        final = builder.get_final_ref(expr)\n        if final is not None:\n            fn, final_var, native = final\n            if final_var.is_final:\n                final_value = final_var.final_value\n                if isinstance(final_value, (CONST_TYPES)):\n                    return final_value\n    elif isinstance(expr, OpExpr):\n        left = constant_fold_expr(builder, expr.left)\n        right = constant_fold_expr(builder, expr.right)\n        if left is not None and right is not None:\n            return constant_fold_binary_op_extended(expr.op, left, right)\n    elif isinstance(expr, UnaryExpr):\n        value = constant_fold_expr(builder, expr.expr)\n        if value is not None and not isinstance(value, bytes):\n            return constant_fold_unary_op(expr.op, value)\n    return None\n\n\ndef constant_fold_binary_op_extended(\n    op: str, left: ConstantValue, right: ConstantValue\n) -> ConstantValue | None:\n    \"\"\"Like mypy's constant_fold_binary_op(), but includes bytes support.\n\n    mypy cannot use constant folded bytes easily so it's simpler to only support them in mypyc.\n    \"\"\"\n    if not isinstance(left, bytes) and not isinstance(right, bytes):\n        return constant_fold_binary_op(op, left, right)\n\n    if op == \"+\" and isinstance(left, bytes) and isinstance(right, bytes):\n        return left + right\n    elif op == \"*\" and isinstance(left, bytes) and isinstance(right, int):\n        return left * right\n    elif op == \"*\" and isinstance(left, int) and isinstance(right, bytes):\n        return left * right\n\n    return None\n"
  },
  {
    "path": "mypyc/irbuild/context.py",
    "content": "\"\"\"Helpers that store information about functions and the related classes.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import FuncItem\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import INVALID_FUNC_DEF\nfrom mypyc.ir.ops import BasicBlock, Value\nfrom mypyc.irbuild.targets import AssignmentTarget\n\n\nclass FuncInfo:\n    \"\"\"Contains information about functions as they are generated.\"\"\"\n\n    def __init__(\n        self,\n        fitem: FuncItem = INVALID_FUNC_DEF,\n        name: str = \"\",\n        class_name: str | None = None,\n        namespace: str = \"\",\n        is_nested: bool = False,\n        contains_nested: bool = False,\n        is_decorated: bool = False,\n        in_non_ext: bool = False,\n        add_nested_funcs_to_env: bool = False,\n        is_comprehension_scope: bool = False,\n    ) -> None:\n        self.fitem = fitem\n        self.name = name\n        self.class_name = class_name\n        self.ns = namespace\n        # Callable classes implement the '__call__' method, and are used to represent functions\n        # that are nested inside of other functions.\n        self._callable_class: ImplicitClass | None = None\n        # Environment classes are ClassIR instances that contain attributes representing the\n        # variables in the environment of the function they correspond to. Environment classes are\n        # generated for functions that contain nested functions.\n        self._env_class: ClassIR | None = None\n        # Generator classes implement the '__next__' method, and are used to represent generators\n        # returned by generator functions.\n        self._generator_class: GeneratorClass | None = None\n        # Environment class registers are the local registers associated with instances of an\n        # environment class, used for getting and setting attributes. curr_env_reg is the register\n        # associated with the current environment.\n        self._curr_env_reg: Value | None = None\n        # These are flags denoting whether a given function is nested, contains a nested function,\n        # is decorated, or is within a non-extension class.\n        self.is_nested = is_nested\n        self.contains_nested = contains_nested\n        self.is_decorated = is_decorated\n        self.in_non_ext = in_non_ext\n        self.add_nested_funcs_to_env = add_nested_funcs_to_env\n        # Comprehension scopes are lightweight scope boundaries created when\n        # a comprehension body contains a lambda. The comprehension is still\n        # inlined (same basic blocks), but we push a new FuncInfo so the\n        # closure machinery can capture loop variables through env classes.\n        self.is_comprehension_scope = is_comprehension_scope\n\n        # TODO: add field for ret_type: RType = none_rprimitive\n\n    def namespaced_name(self) -> str:\n        return \"_\".join(x for x in [self.name, self.class_name, self.ns] if x)\n\n    @property\n    def is_generator(self) -> bool:\n        return self.fitem.is_generator or self.fitem.is_coroutine\n\n    @property\n    def is_coroutine(self) -> bool:\n        return self.fitem.is_coroutine\n\n    @property\n    def callable_class(self) -> ImplicitClass:\n        assert self._callable_class is not None\n        return self._callable_class\n\n    @callable_class.setter\n    def callable_class(self, cls: ImplicitClass) -> None:\n        self._callable_class = cls\n\n    @property\n    def env_class(self) -> ClassIR:\n        assert self._env_class is not None\n        return self._env_class\n\n    @env_class.setter\n    def env_class(self, ir: ClassIR) -> None:\n        self._env_class = ir\n\n    @property\n    def generator_class(self) -> GeneratorClass:\n        assert self._generator_class is not None\n        return self._generator_class\n\n    @generator_class.setter\n    def generator_class(self, cls: GeneratorClass) -> None:\n        self._generator_class = cls\n\n    @property\n    def curr_env_reg(self) -> Value:\n        assert self._curr_env_reg is not None\n        return self._curr_env_reg\n\n    def can_merge_generator_and_env_classes(self) -> bool:\n        # In simple cases we can place the environment into the generator class,\n        # instead of having two separate classes.\n        if self._generator_class and not self._generator_class.ir.is_final_class:\n            result = False\n        else:\n            result = self.is_generator and not self.is_nested and not self.contains_nested\n        return result\n\n\nclass ImplicitClass:\n    \"\"\"Contains information regarding implicitly generated classes.\n\n    Implicit classes are generated for nested functions and generator\n    functions. They are not explicitly defined in the source code.\n\n    NOTE: This is both a concrete class and used as a base class.\n    \"\"\"\n\n    def __init__(self, ir: ClassIR) -> None:\n        # The ClassIR instance associated with this class.\n        self.ir = ir\n        # The register associated with the 'self' instance for this generator class.\n        self._self_reg: Value | None = None\n        # Environment class registers are the local registers associated with instances of an\n        # environment class, used for getting and setting attributes. curr_env_reg is the register\n        # associated with the current environment. prev_env_reg is the self.__mypyc_env__ field\n        # associated with the previous environment.\n        self._curr_env_reg: Value | None = None\n        self._prev_env_reg: Value | None = None\n\n    @property\n    def self_reg(self) -> Value:\n        assert self._self_reg is not None\n        return self._self_reg\n\n    @self_reg.setter\n    def self_reg(self, reg: Value) -> None:\n        self._self_reg = reg\n\n    @property\n    def curr_env_reg(self) -> Value:\n        assert self._curr_env_reg is not None\n        return self._curr_env_reg\n\n    @curr_env_reg.setter\n    def curr_env_reg(self, reg: Value) -> None:\n        self._curr_env_reg = reg\n\n    @property\n    def prev_env_reg(self) -> Value:\n        assert self._prev_env_reg is not None\n        return self._prev_env_reg\n\n    @prev_env_reg.setter\n    def prev_env_reg(self, reg: Value) -> None:\n        self._prev_env_reg = reg\n\n\nclass GeneratorClass(ImplicitClass):\n    \"\"\"Contains information about implicit generator function classes.\"\"\"\n\n    def __init__(self, ir: ClassIR) -> None:\n        super().__init__(ir)\n        # This register holds the label number that the '__next__' function should go to the next\n        # time it is called.\n        self._next_label_reg: Value | None = None\n        self._next_label_target: AssignmentTarget | None = None\n\n        # These registers hold the error values for the generator object for the case that the\n        # 'throw' function is called.\n        self.exc_regs: tuple[Value, Value, Value] | None = None\n\n        # Holds the arg passed to send\n        self.send_arg_reg: Value | None = None\n\n        # Holds the PyObject ** pointer through which return value can be passed\n        # instead of raising StopIteration(ret_value) (only if not NULL). This\n        # is used for faster native-to-native calls.\n        self.stop_iter_value_reg: Value | None = None\n\n        # The switch block is used to decide which instruction to go using the value held in the\n        # next-label register.\n        self.switch_block = BasicBlock()\n        self.continuation_blocks: list[BasicBlock] = []\n\n    @property\n    def next_label_reg(self) -> Value:\n        assert self._next_label_reg is not None\n        return self._next_label_reg\n\n    @next_label_reg.setter\n    def next_label_reg(self, reg: Value) -> None:\n        self._next_label_reg = reg\n\n    @property\n    def next_label_target(self) -> AssignmentTarget:\n        assert self._next_label_target is not None\n        return self._next_label_target\n\n    @next_label_target.setter\n    def next_label_target(self, target: AssignmentTarget) -> None:\n        self._next_label_target = target\n"
  },
  {
    "path": "mypyc/irbuild/env_class.py",
    "content": "\"\"\"Generate classes representing function environments (+ related operations).\n\nIf we have a nested function that has non-local (free) variables, access to the\nnon-locals is via an instance of an environment class. Example:\n\n    def f() -> int:\n        x = 0  # Make 'x' an attribute of an environment class instance\n\n        def g() -> int:\n            # We have access to the environment class instance to\n            # allow accessing 'x'\n            return x + 2\n\n        x = x + 1  # Modify the attribute\n        return g()\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import Argument, FuncDef, SymbolNode, Var\nfrom mypyc.common import (\n    BITMAP_BITS,\n    ENV_ATTR_NAME,\n    GENERATOR_ATTRIBUTE_PREFIX,\n    SELF_NAME,\n    bitmap_name,\n)\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.ops import Call, GetAttr, SetAttr, Value\nfrom mypyc.ir.rtypes import RInstance, bitmap_rprimitive, object_rprimitive\nfrom mypyc.irbuild.builder import IRBuilder, SymbolTarget\nfrom mypyc.irbuild.context import FuncInfo, GeneratorClass, ImplicitClass\nfrom mypyc.irbuild.targets import AssignmentTargetAttr\n\n\ndef setup_env_class(builder: IRBuilder) -> ClassIR:\n    \"\"\"Generate a class representing a function environment.\n\n    Note that the variables in the function environment are not\n    actually populated here. This is because when the environment\n    class is generated, the function environment has not yet been\n    visited. This behavior is allowed so that when the compiler visits\n    nested functions, it can use the returned ClassIR instance to\n    figure out free variables it needs to access.  The remaining\n    attributes of the environment class are populated when the\n    environment registers are loaded.\n\n    Return a ClassIR representing an environment for a function\n    containing a nested function.\n    \"\"\"\n    env_class = ClassIR(\n        f\"{builder.fn_info.namespaced_name()}_env\",\n        builder.module_name,\n        is_generated=True,\n        is_final_class=True,\n    )\n    env_class.reuse_freed_instance = True\n    env_class.attributes[SELF_NAME] = RInstance(env_class)\n    if builder.fn_info.is_nested and builder.fn_infos[-2]._env_class is not None:\n        # If the function is nested, its environment class must contain an environment\n        # attribute pointing to its encapsulating functions' environment class.\n        env_class.attributes[ENV_ATTR_NAME] = RInstance(builder.fn_infos[-2].env_class)\n    env_class.mro = [env_class]\n    builder.fn_info.env_class = env_class\n    builder.classes.append(env_class)\n    return env_class\n\n\ndef finalize_env_class(builder: IRBuilder, prefix: str = \"\") -> None:\n    \"\"\"Generate, instantiate, and set up the environment of an environment class.\"\"\"\n    if not builder.fn_info.can_merge_generator_and_env_classes():\n        instantiate_env_class(builder)\n\n    # Iterate through the function arguments and replace local definitions (using registers)\n    # that were previously added to the environment with references to the function's\n    # environment class. Comprehension scopes have no arguments to add.\n    if not builder.fn_info.is_comprehension_scope:\n        if builder.fn_info.is_nested:\n            add_args_to_env(\n                builder, local=False, base=builder.fn_info.callable_class, prefix=prefix\n            )\n        else:\n            add_args_to_env(builder, local=False, base=builder.fn_info, prefix=prefix)\n\n\ndef instantiate_env_class(builder: IRBuilder) -> Value:\n    \"\"\"Assign an environment class to a register named after the given function definition.\"\"\"\n    curr_env_reg = builder.add(\n        Call(builder.fn_info.env_class.ctor, [], builder.fn_info.fitem.line)\n    )\n\n    if builder.fn_info.is_nested and not builder.fn_info.is_comprehension_scope:\n        builder.fn_info.callable_class._curr_env_reg = curr_env_reg\n        builder.add(\n            SetAttr(\n                curr_env_reg,\n                ENV_ATTR_NAME,\n                builder.fn_info.callable_class.prev_env_reg,\n                builder.fn_info.fitem.line,\n            )\n        )\n    else:\n        # Top-level functions and comprehension scopes store env reg directly.\n        builder.fn_info._curr_env_reg = curr_env_reg\n        # Comprehension scopes link to parent env if it exists.\n        if (\n            builder.fn_info.is_nested\n            and builder.fn_infos[-2]._env_class is not None\n            and builder.fn_infos[-2]._curr_env_reg is not None\n        ):\n            builder.add(\n                SetAttr(\n                    curr_env_reg,\n                    ENV_ATTR_NAME,\n                    builder.fn_infos[-2].curr_env_reg,\n                    builder.fn_info.fitem.line,\n                )\n            )\n\n    return curr_env_reg\n\n\ndef load_env_registers(builder: IRBuilder, prefix: str = \"\") -> None:\n    \"\"\"Load the registers for the current FuncItem being visited.\n\n    Adds the arguments of the FuncItem to the environment. If the\n    FuncItem is nested inside of another function, then this also\n    loads all of the outer environments of the FuncItem into registers\n    so that they can be used when accessing free variables.\n    \"\"\"\n    add_args_to_env(builder, local=True, prefix=prefix)\n\n    fn_info = builder.fn_info\n    fitem = fn_info.fitem\n    if fn_info.is_nested and builder.fn_infos[-2]._env_class is not None:\n        load_outer_envs(builder, fn_info.callable_class)\n        # If this is a FuncDef, then make sure to load the FuncDef into its own environment\n        # class so that the function can be called recursively.\n        if isinstance(fitem, FuncDef) and fn_info.add_nested_funcs_to_env:\n            setup_func_for_recursive_call(builder, fitem, fn_info.callable_class, prefix=prefix)\n\n\ndef load_outer_env(\n    builder: IRBuilder, base: Value, outer_env: dict[SymbolNode, SymbolTarget]\n) -> Value:\n    \"\"\"Load the environment class for a given base into a register.\n\n    Additionally, iterates through all of the SymbolNode and\n    AssignmentTarget instances of the environment at the given index's\n    symtable, and adds those instances to the environment of the\n    current environment. This is done so that the current environment\n    can access outer environment variables without having to reload\n    all of the environment registers.\n\n    Returns the register where the environment class was loaded.\n    \"\"\"\n    env = builder.add(GetAttr(base, ENV_ATTR_NAME, builder.fn_info.fitem.line))\n    assert isinstance(env.type, RInstance), f\"{env} must be of type RInstance\"\n\n    for symbol, target in outer_env.items():\n        attr_name = symbol.name\n        if isinstance(target, AssignmentTargetAttr):\n            attr_name = target.attr\n        env.type.class_ir.attributes[attr_name] = target.type\n        symbol_target = AssignmentTargetAttr(env, attr_name)\n        builder.add_target(symbol, symbol_target)\n\n    return env\n\n\ndef load_outer_envs(builder: IRBuilder, base: ImplicitClass) -> None:\n    index = len(builder.builders) - 2\n\n    # Load the first outer environment. This one is special because it gets saved in the\n    # FuncInfo instance's prev_env_reg field.\n    has_outer = index > 1 or (index == 1 and builder.fn_infos[1].contains_nested)\n    if has_outer and builder.fn_infos[index]._env_class is not None:\n        # outer_env = builder.fn_infos[index].environment\n        outer_env = builder.symtables[index]\n        if isinstance(base, GeneratorClass):\n            base.prev_env_reg = load_outer_env(builder, base.curr_env_reg, outer_env)\n        else:\n            base.prev_env_reg = load_outer_env(builder, base.self_reg, outer_env)\n        env_reg = base.prev_env_reg\n        index -= 1\n\n    # Load the remaining outer environments into registers.\n    while index > 1:\n        if builder.fn_infos[index]._env_class is None:\n            break\n        # outer_env = builder.fn_infos[index].environment\n        outer_env = builder.symtables[index]\n        env_reg = load_outer_env(builder, env_reg, outer_env)\n        index -= 1\n\n\ndef num_bitmap_args(builder: IRBuilder, args: list[Argument]) -> int:\n    n = 0\n    for arg in args:\n        t = builder.type_to_rtype(arg.variable.type)\n        if t.error_overlap and arg.kind.is_optional():\n            n += 1\n    return (n + (BITMAP_BITS - 1)) // BITMAP_BITS\n\n\ndef add_args_to_env(\n    builder: IRBuilder,\n    local: bool = True,\n    base: FuncInfo | ImplicitClass | None = None,\n    reassign: bool = True,\n    prefix: str = \"\",\n) -> None:\n    fn_info = builder.fn_info\n    args = fn_info.fitem.arguments\n    nb = num_bitmap_args(builder, args)\n    if local:\n        for arg in args:\n            rtype = builder.type_to_rtype(arg.variable.type)\n            builder.add_local_reg(arg.variable, rtype, is_arg=True)\n        for i in reversed(range(nb)):\n            builder.add_local_reg(Var(bitmap_name(i)), bitmap_rprimitive, is_arg=True)\n    else:\n        for arg in args:\n            if (\n                is_free_variable(builder, arg.variable)\n                or fn_info.is_generator\n                or fn_info.is_coroutine\n            ):\n                rtype = builder.type_to_rtype(arg.variable.type)\n                assert base is not None, \"base cannot be None for adding nonlocal args\"\n                builder.add_var_to_env_class(\n                    arg.variable, rtype, base, reassign=reassign, prefix=prefix\n                )\n\n\ndef add_vars_to_env(builder: IRBuilder, prefix: str = \"\") -> None:\n    \"\"\"Add relevant local variables and nested functions to the environment class.\n\n    Add all variables and functions that are declared/defined within current\n    function and are referenced in functions nested within this one to this\n    function's environment class so the nested functions can reference\n    them even if they are declared after the nested function's definition.\n    Note that this is done before visiting the body of the function.\n    \"\"\"\n    env_for_func: FuncInfo | ImplicitClass = builder.fn_info\n    if builder.fn_info.is_generator:\n        env_for_func = builder.fn_info.generator_class\n    elif (\n        builder.fn_info.is_nested or builder.fn_info.in_non_ext\n    ) and not builder.fn_info.is_comprehension_scope:\n        env_for_func = builder.fn_info.callable_class\n\n    if builder.fn_info.fitem in builder.free_variables:\n        # Sort the variables to keep things deterministic\n        for var in sorted(builder.free_variables[builder.fn_info.fitem], key=lambda x: x.name):\n            if isinstance(var, Var):\n                rtype = builder.type_to_rtype(var.type)\n                builder.add_var_to_env_class(\n                    var, rtype, env_for_func, reassign=False, prefix=prefix\n                )\n\n    if builder.fn_info.fitem in builder.encapsulating_funcs:\n        for nested_fn in builder.encapsulating_funcs[builder.fn_info.fitem]:\n            if isinstance(nested_fn, FuncDef):\n                # The return type is 'object' instead of an RInstance of the\n                # callable class because differently defined functions with\n                # the same name and signature across conditional blocks\n                # will generate different callable classes, so the callable\n                # class that gets instantiated must be generic.\n                if nested_fn.is_generator or nested_fn.is_coroutine:\n                    prefix = GENERATOR_ATTRIBUTE_PREFIX\n                builder.add_var_to_env_class(\n                    nested_fn, object_rprimitive, env_for_func, reassign=False, prefix=prefix\n                )\n\n\ndef setup_func_for_recursive_call(\n    builder: IRBuilder, fdef: FuncDef, base: ImplicitClass, prefix: str = \"\"\n) -> None:\n    \"\"\"Enable calling a nested function (with a callable class) recursively.\n\n    Adds the instance of the callable class representing the given\n    FuncDef to a register in the environment so that the function can\n    be called recursively. Note that this needs to be done only for\n    nested functions.\n    \"\"\"\n    # First, set the attribute of the environment class so that GetAttr can be called on it.\n    prev_env = builder.fn_infos[-2].env_class\n    attr_name = prefix + fdef.name\n    prev_env.attributes[attr_name] = builder.type_to_rtype(fdef.type)\n    line = fdef.line\n\n    if isinstance(base, GeneratorClass):\n        # If we are dealing with a generator class, then we need to first get the register\n        # holding the current environment class, and load the previous environment class from\n        # there.\n        prev_env_reg = builder.add(GetAttr(base.curr_env_reg, ENV_ATTR_NAME, line))\n    else:\n        prev_env_reg = base.prev_env_reg\n\n    # Obtain the instance of the callable class representing the FuncDef, and add it to the\n    # current environment.\n    val = builder.add(GetAttr(prev_env_reg, attr_name, line))\n    target = builder.add_local_reg(fdef, object_rprimitive)\n    builder.assign(target, val, line)\n\n\ndef is_free_variable(builder: IRBuilder, symbol: SymbolNode) -> bool:\n    fitem = builder.fn_info.fitem\n    return fitem in builder.free_variables and symbol in builder.free_variables[fitem]\n"
  },
  {
    "path": "mypyc/irbuild/expression.py",
    "content": "\"\"\"Transform mypy expression ASTs to mypyc IR (Intermediate Representation).\n\nThe top-level AST transformation logic is implemented in mypyc.irbuild.visitor\nand mypyc.irbuild.builder.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport math\nfrom collections.abc import Callable, Sequence\n\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    LDEF,\n    AssertTypeExpr,\n    AssignmentExpr,\n    BytesExpr,\n    CallExpr,\n    CastExpr,\n    ComparisonExpr,\n    ComplexExpr,\n    ConditionalExpr,\n    DictExpr,\n    DictionaryComprehension,\n    EllipsisExpr,\n    Expression,\n    FloatExpr,\n    GeneratorExpr,\n    IndexExpr,\n    IntExpr,\n    ListComprehension,\n    ListExpr,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    OpExpr,\n    RefExpr,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    StrExpr,\n    SuperExpr,\n    TupleExpr,\n    TypeApplication,\n    TypeInfo,\n    TypeVarLikeExpr,\n    UnaryExpr,\n    Var,\n)\nfrom mypy.types import (\n    AnyType,\n    Instance,\n    ProperType,\n    TupleType,\n    TypeOfAny,\n    TypeType,\n    get_proper_type,\n)\nfrom mypyc.common import MAX_SHORT_INT\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FUNC_CLASSMETHOD, FUNC_STATICMETHOD\nfrom mypyc.ir.ops import (\n    Assign,\n    BasicBlock,\n    ComparisonOp,\n    Integer,\n    LoadAddress,\n    LoadLiteral,\n    PrimitiveDescription,\n    RaiseStandardError,\n    Register,\n    TupleGet,\n    TupleSet,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RTuple,\n    RVec,\n    bool_rprimitive,\n    int_rprimitive,\n    is_any_int,\n    is_fixed_width_rtype,\n    is_int64_rprimitive,\n    is_int_rprimitive,\n    is_list_rprimitive,\n    is_none_rprimitive,\n    is_object_rprimitive,\n    object_rprimitive,\n    set_rprimitive,\n)\nfrom mypyc.irbuild.ast_helpers import is_borrow_friendly_expr, process_conditional\nfrom mypyc.irbuild.builder import IRBuilder, int_borrow_friendly_op\nfrom mypyc.irbuild.constant_fold import constant_fold_expr\nfrom mypyc.irbuild.for_helpers import (\n    comprehension_helper,\n    raise_error_if_contains_unreachable_names,\n    translate_list_comprehension,\n    translate_set_comprehension,\n    translate_vec_comprehension,\n)\nfrom mypyc.irbuild.format_str_tokenizer import (\n    convert_format_expr_to_bytes,\n    convert_format_expr_to_str,\n    join_formatted_bytes,\n    join_formatted_strings,\n    tokenizer_printf_style,\n)\nfrom mypyc.irbuild.specialize import (\n    apply_dunder_specialization,\n    apply_function_specialization,\n    apply_method_specialization,\n    translate_object_new,\n    translate_object_setattr,\n)\nfrom mypyc.irbuild.vec import (\n    vec_append,\n    vec_create,\n    vec_create_from_values,\n    vec_create_initialized,\n    vec_slice,\n)\nfrom mypyc.primitives.bytes_ops import bytes_slice_op\nfrom mypyc.primitives.dict_ops import dict_get_item_op, dict_new_op, exact_dict_set_item_op\nfrom mypyc.primitives.generic_ops import iter_op, name_op\nfrom mypyc.primitives.list_ops import list_append_op, list_extend_op, list_slice_op\nfrom mypyc.primitives.misc_ops import ellipsis_op, get_module_dict_op, new_slice_op, type_op\nfrom mypyc.primitives.registry import builtin_names\nfrom mypyc.primitives.set_ops import set_add_op, set_in_op, set_update_op\nfrom mypyc.primitives.str_ops import str_slice_op\nfrom mypyc.primitives.tuple_ops import list_tuple_op, tuple_slice_op\n\n# Name and attribute references\n\n\ndef transform_name_expr(builder: IRBuilder, expr: NameExpr) -> Value:\n    if isinstance(expr.node, TypeVarLikeExpr) and expr.node.is_new_style:\n        # Reference to Python 3.12 implicit TypeVar/TupleVarTuple/... object.\n        # These are stored in C statics and not visible in Python namespaces.\n        return builder.load_type_var(expr.node.name, expr.node.line)\n    if expr.node is None:\n        builder.add(\n            RaiseStandardError(\n                RaiseStandardError.NAME_ERROR, f'name \"{expr.name}\" is not defined', expr.line\n            )\n        )\n        return builder.none(expr.line)\n    fullname = expr.node.fullname\n    if fullname in builtin_names:\n        typ, src = builtin_names[fullname]\n        return builder.add(LoadAddress(typ, src, expr.line))\n    # special cases\n    if fullname == \"builtins.None\":\n        return builder.none(expr.line)\n    if fullname == \"builtins.True\":\n        return builder.true(expr.line)\n    if fullname == \"builtins.False\":\n        return builder.false(expr.line)\n    if fullname in (\"typing.TYPE_CHECKING\", \"typing_extensions.TYPE_CHECKING\"):\n        return builder.false(expr.line)\n\n    math_literal = transform_math_literal(builder, fullname, expr.line)\n    if math_literal is not None:\n        return math_literal\n\n    if isinstance(expr.node, Var) and expr.node.is_final:\n        final_type = builder.types.get(expr) or expr.node.type\n        if final_type is None:\n            final_type = AnyType(TypeOfAny.special_form)\n        value = builder.emit_load_final(\n            expr.node, fullname, expr.name, builder.is_native_ref_expr(expr), final_type, expr.line\n        )\n        if value is not None:\n            return value\n\n    if isinstance(expr.node, MypyFile) and expr.node.fullname in builder.imports:\n        return builder.load_module(expr.node.fullname)\n\n    # If the expression is locally defined, then read the result from the corresponding\n    # assignment target and return it. Otherwise if the expression is a global, load it from\n    # the globals dictionary.\n    # Except for imports, that currently always happens in the global namespace.\n    if expr.kind == LDEF and not (isinstance(expr.node, Var) and expr.node.is_suppressed_import):\n        # Try to detect and error when we hit the irritating mypy bug\n        # where a local variable is cast to None. (#5423)\n        if (\n            isinstance(expr.node, Var)\n            and is_none_rprimitive(builder.node_type(expr))\n            and expr.node.is_inferred\n        ):\n            builder.error(\n                'Local variable \"{}\" has inferred type None; add an annotation'.format(\n                    expr.node.name\n                ),\n                expr.node.line,\n            )\n\n        # TODO: Behavior currently only defined for Var, FuncDef and MypyFile node types.\n        if isinstance(expr.node, MypyFile):\n            # Load reference to a module imported inside function from\n            # the modules dictionary. It would be closer to Python\n            # semantics to access modules imported inside functions\n            # via local variables, but this is tricky since the mypy\n            # AST doesn't include a Var node for the module. We\n            # instead load the module separately on each access.\n            mod_dict = builder.call_c(get_module_dict_op, [], expr.line)\n            obj = builder.primitive_op(\n                dict_get_item_op, [mod_dict, builder.load_str(expr.node.fullname)], expr.line\n            )\n            return obj\n        else:\n            return builder.read(builder.get_assignment_target(expr, for_read=True), expr.line)\n\n    return builder.load_global(expr)\n\n\ndef transform_member_expr(builder: IRBuilder, expr: MemberExpr) -> Value:\n    # Special Cases\n    if expr.fullname in (\"typing.TYPE_CHECKING\", \"typing_extensions.TYPE_CHECKING\"):\n        return builder.false(expr.line)\n\n    # First check if this is maybe a final attribute.\n    final = builder.get_final_ref(expr)\n    if final is not None:\n        fullname, final_var, native = final\n        final_type = builder.types.get(expr) or final_var.type\n        if final_type is None:\n            final_type = AnyType(TypeOfAny.special_form)\n        value = builder.emit_load_final(\n            final_var, fullname, final_var.name, native, final_type, expr.line\n        )\n        if value is not None:\n            return value\n\n    math_literal = transform_math_literal(builder, expr.fullname, expr.line)\n    if math_literal is not None:\n        return math_literal\n\n    if isinstance(expr.node, MypyFile) and expr.node.fullname in builder.imports:\n        return builder.load_module(expr.node.fullname)\n\n    can_borrow = builder.is_native_attr_ref(expr)\n    obj = builder.accept(expr.expr, can_borrow=can_borrow)\n    rtype = builder.node_type(expr)\n\n    if (\n        is_object_rprimitive(obj.type)\n        and expr.name == \"__name__\"\n        and builder.options.capi_version >= (3, 11)\n    ):\n        return builder.primitive_op(name_op, [obj], expr.line)\n\n    if isinstance(obj.type, RInstance) and expr.name == \"__class__\":\n        # A non-native class could override \"__class__\" using \"__getattribute__\", so\n        # only apply to RInstance types.\n        return builder.primitive_op(type_op, [obj], expr.line)\n\n    # Special case: for named tuples transform attribute access to faster index access.\n    typ = get_proper_type(builder.types.get(expr.expr))\n    if isinstance(typ, TupleType) and typ.partial_fallback.type.is_named_tuple:\n        fields = typ.partial_fallback.type.metadata[\"namedtuple\"][\"fields\"]\n        if expr.name in fields:\n            index = builder.builder.load_int(fields.index(expr.name))\n            return builder.gen_method_call(obj, \"__getitem__\", [index], rtype, expr.line)\n\n    check_instance_attribute_access_through_class(builder, expr, typ)\n\n    borrow = can_borrow and builder.can_borrow\n    return builder.builder.get_attr(obj, expr.name, rtype, expr.line, borrow=borrow)\n\n\ndef check_instance_attribute_access_through_class(\n    builder: IRBuilder, expr: MemberExpr, typ: ProperType | None\n) -> None:\n    \"\"\"Report error if accessing an instance attribute through class object.\"\"\"\n    if isinstance(expr.expr, RefExpr):\n        node = expr.expr.node\n        if isinstance(typ, TypeType) and isinstance(typ.item, Instance):\n            # TODO: Handle other item types\n            node = typ.item.type\n        if isinstance(node, TypeInfo):\n            class_ir = builder.mapper.type_to_ir.get(node)\n            if class_ir is not None and class_ir.is_ext_class:\n                sym = node.get(expr.name)\n                if (\n                    sym is not None\n                    and isinstance(sym.node, Var)\n                    and not sym.node.is_classvar\n                    and not sym.node.is_final\n                ):\n                    builder.error(\n                        'Cannot access instance attribute \"{}\" through class object'.format(\n                            expr.name\n                        ),\n                        expr.line,\n                    )\n                    builder.note(\n                        '(Hint: Use \"x: Final = ...\" or \"x: ClassVar = ...\" to define '\n                        \"a class attribute)\",\n                        expr.line,\n                    )\n\n\ndef transform_super_expr(builder: IRBuilder, o: SuperExpr) -> Value:\n    # warning(builder, 'can not optimize super() expression', o.line)\n    sup_val = builder.load_module_attr_by_fullname(\"builtins.super\", o.line)\n    if o.call.args:\n        args = [builder.accept(arg) for arg in o.call.args]\n    else:\n        assert o.info is not None\n        typ = builder.load_native_type_object(o.info.fullname)\n        ir = builder.mapper.type_to_ir[o.info]\n        iter_env = iter(builder.builder.args)\n        # Grab first argument\n        vself: Value = next(iter_env)\n        if builder.fn_info.is_generator:\n            # grab seventh argument (see comment in translate_super_method_call)\n            self_targ = list(builder.symtables[-1].values())[7]\n            vself = builder.read(self_targ, builder.fn_info.fitem.line)\n        elif not ir.is_ext_class:\n            vself = next(iter_env)  # second argument is self if non_extension class\n        args = [typ, vself]\n    res = builder.py_call(sup_val, args, o.line)\n    return builder.py_get_attr(res, o.name, o.line)\n\n\n# Calls\n\n\ndef transform_call_expr(builder: IRBuilder, expr: CallExpr) -> Value:\n    callee = expr.callee\n    if isinstance(expr.analyzed, CastExpr):\n        return translate_cast_expr(builder, expr.analyzed)\n    elif isinstance(expr.analyzed, AssertTypeExpr):\n        # Compile to a no-op.\n        return builder.accept(expr.analyzed.expr)\n    elif (\n        isinstance(callee, (NameExpr, MemberExpr))\n        and isinstance(callee.node, TypeInfo)\n        and callee.node.is_newtype\n    ):\n        # A call to a NewType type is a no-op at runtime.\n        return builder.accept(expr.args[0])\n\n    if isinstance(callee, IndexExpr) and isinstance(callee.analyzed, TypeApplication):\n        analyzed = callee.analyzed\n        if (\n            isinstance(analyzed.expr, RefExpr)\n            and analyzed.expr.fullname == \"librt.vecs.vec\"\n            and len(analyzed.types) == 1\n        ):\n            item_type = builder.type_to_rtype(analyzed.types[0])\n            vec_type = RVec(item_type)\n            if len(expr.args) == 0:\n                return vec_create(builder.builder, vec_type, 0, expr.line)\n            elif len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]:\n                return translate_vec_create_from_iterable(builder, vec_type, expr.args[0])\n        callee = analyzed.expr  # Unwrap type application\n\n    if isinstance(callee, MemberExpr):\n        if isinstance(callee.expr, RefExpr) and isinstance(callee.expr.node, MypyFile):\n            # Call a module-level function, not a method.\n            return translate_call(builder, expr, callee)\n        return apply_method_specialization(builder, expr, callee) or translate_method_call(\n            builder, expr, callee\n        )\n    elif isinstance(callee, SuperExpr):\n        return translate_super_method_call(builder, expr, callee)\n    else:\n        return translate_call(builder, expr, callee)\n\n\ndef translate_call(builder: IRBuilder, expr: CallExpr, callee: Expression) -> Value:\n    # The common case of calls is refexprs\n    if isinstance(callee, RefExpr):\n        return apply_function_specialization(builder, expr, callee) or translate_refexpr_call(\n            builder, expr, callee\n        )\n\n    function = builder.accept(callee)\n    args = [builder.accept(arg) for arg in expr.args]\n    return builder.py_call(\n        function, args, expr.line, arg_kinds=expr.arg_kinds, arg_names=expr.arg_names\n    )\n\n\ndef translate_refexpr_call(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value:\n    \"\"\"Translate a non-method call.\"\"\"\n    # Gen the argument values\n    arg_values = [builder.accept(arg) for arg in expr.args]\n\n    return builder.call_refexpr_with_args(expr, callee, arg_values)\n\n\ndef translate_method_call(builder: IRBuilder, expr: CallExpr, callee: MemberExpr) -> Value:\n    \"\"\"Generate IR for an arbitrary call of form e.m(...).\n\n    This can also deal with calls to module-level functions.\n    \"\"\"\n    if builder.is_native_ref_expr(callee):\n        # Call to module-level native function or such\n        return translate_call(builder, expr, callee)\n    elif (\n        isinstance(callee.expr, RefExpr)\n        and isinstance(callee.expr.node, TypeInfo)\n        and callee.expr.node in builder.mapper.type_to_ir\n        and builder.mapper.type_to_ir[callee.expr.node].has_method(callee.name)\n        and all(kind in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds)\n    ):\n        # Call a method via the *class*\n        assert isinstance(callee.expr.node, TypeInfo), callee.expr.node\n        ir = builder.mapper.type_to_ir[callee.expr.node]\n        return call_classmethod(builder, ir, expr, callee)\n    elif builder.is_module_member_expr(callee):\n        # Fall back to a PyCall for non-native module calls\n        function = builder.accept(callee)\n        args = [builder.accept(arg) for arg in expr.args]\n        return builder.py_call(\n            function, args, expr.line, arg_kinds=expr.arg_kinds, arg_names=expr.arg_names\n        )\n    else:\n        if isinstance(callee.expr, RefExpr):\n            node = callee.expr.node\n            if isinstance(node, Var) and node.is_cls:\n                typ = get_proper_type(node.type)\n                if isinstance(typ, TypeType) and isinstance(typ.item, Instance):\n                    class_ir = builder.mapper.type_to_ir.get(typ.item.type)\n                    if class_ir and class_ir.is_ext_class and class_ir.has_no_subclasses():\n                        # Call a native classmethod via cls that can be statically bound,\n                        # since the class has no subclasses.\n                        return call_classmethod(builder, class_ir, expr, callee)\n\n        receiver_typ = builder.node_type(callee.expr)\n\n        # If there is a specializer for this method name/type, try calling it.\n        # We would return the first successful one.\n        val = apply_method_specialization(builder, expr, callee, receiver_typ)\n        if val is not None:\n            return val\n\n        obj = builder.accept(callee.expr)\n        args = [builder.accept(arg) for arg in expr.args]\n        return builder.gen_method_call(\n            obj,\n            callee.name,\n            args,\n            builder.node_type(expr),\n            expr.line,\n            expr.arg_kinds,\n            expr.arg_names,\n        )\n\n\ndef call_classmethod(builder: IRBuilder, ir: ClassIR, expr: CallExpr, callee: MemberExpr) -> Value:\n    decl = ir.method_decl(callee.name)\n    args = []\n    arg_kinds, arg_names = expr.arg_kinds.copy(), expr.arg_names.copy()\n    # Add the class argument for class methods in extension classes\n    if decl.kind == FUNC_CLASSMETHOD and ir.is_ext_class:\n        args.append(builder.load_native_type_object(ir.fullname))\n        arg_kinds.insert(0, ARG_POS)\n        arg_names.insert(0, None)\n    args += [builder.accept(arg) for arg in expr.args]\n\n    if ir.is_ext_class:\n        return builder.builder.call(decl, args, arg_kinds, arg_names, expr.line)\n    else:\n        obj = builder.accept(callee.expr)\n        return builder.gen_method_call(\n            obj,\n            callee.name,\n            args,\n            builder.node_type(expr),\n            expr.line,\n            expr.arg_kinds,\n            expr.arg_names,\n        )\n\n\ndef translate_super_method_call(builder: IRBuilder, expr: CallExpr, callee: SuperExpr) -> Value:\n    if callee.info is None or (len(callee.call.args) != 0 and len(callee.call.args) != 2):\n        return translate_call(builder, expr, callee)\n\n    # We support two-argument super but only when it is super(CurrentClass, self)\n    # TODO: We could support it when it is a parent class in many cases?\n    if len(callee.call.args) == 2:\n        self_arg = callee.call.args[1]\n        if (\n            not isinstance(self_arg, NameExpr)\n            or not isinstance(self_arg.node, Var)\n            or not self_arg.node.is_self\n        ):\n            return translate_call(builder, expr, callee)\n\n        typ_arg = callee.call.args[0]\n        if (\n            not isinstance(typ_arg, NameExpr)\n            or not isinstance(typ_arg.node, TypeInfo)\n            or callee.info is not typ_arg.node\n        ):\n            return translate_call(builder, expr, callee)\n\n    ir = builder.mapper.type_to_ir[callee.info]\n    # Search for the method in the mro, skipping ourselves. We\n    # determine targets of super calls to native methods statically.\n    for base in ir.mro[1:]:\n        if callee.name in base.method_decls:\n            break\n    else:\n        if callee.name == \"__new__\":\n            result = translate_object_new(builder, expr, MemberExpr(callee.call, \"__new__\"))\n            if result:\n                return result\n        elif callee.name == \"__setattr__\":\n            result = translate_object_setattr(\n                builder, expr, MemberExpr(callee.call, \"__setattr__\")\n            )\n            if result:\n                return result\n        if ir.is_ext_class and ir.builtin_base is None and not ir.inherits_python:\n            if callee.name == \"__init__\" and len(expr.args) == 0:\n                # Call translates to object.__init__(self), which is a\n                # no-op, so omit the call.\n                return builder.none()\n        return translate_call(builder, expr, callee)\n\n    decl = base.method_decl(callee.name)\n    arg_values = [builder.accept(arg) for arg in expr.args]\n    arg_kinds, arg_names = expr.arg_kinds.copy(), expr.arg_names.copy()\n\n    if decl.kind != FUNC_STATICMETHOD and decl.name != \"__new__\":\n        # Grab first argument\n        vself: Value = builder.self()\n        if decl.kind == FUNC_CLASSMETHOD:\n            vself = builder.primitive_op(type_op, [vself], expr.line)\n        elif builder.fn_info.is_generator:\n            # For generator classes, the self target is the 7th value\n            # in the symbol table (which is an ordered dict). This is sort\n            # of ugly, but we can't search by name since the 'self' parameter\n            # could be named anything, and it doesn't get added to the\n            # environment indexes.\n            self_targ = list(builder.symtables[-1].values())[7]\n            vself = builder.read(self_targ, builder.fn_info.fitem.line)\n        arg_values.insert(0, vself)\n        arg_kinds.insert(0, ARG_POS)\n        arg_names.insert(0, None)\n\n    return builder.builder.call(decl, arg_values, arg_kinds, arg_names, expr.line)\n\n\ndef translate_vec_create_from_iterable(\n    builder: IRBuilder, vec_type: RVec, arg: Expression\n) -> Value:\n    line = arg.line\n    item_type = vec_type.item_type\n    if isinstance(arg, OpExpr) and arg.op == \"*\":\n        if isinstance(arg.left, ListExpr):\n            lst = arg.left\n            other = arg.right\n        elif isinstance(arg.right, ListExpr):\n            lst = arg.right\n            other = arg.left\n        else:\n            assert False\n        assert len(lst.items) == 1\n        other_type = builder.node_type(other)\n        # TODO: is_any_int(...)\n        if is_int64_rprimitive(other_type) or is_int_rprimitive(other_type):\n            length = builder.accept(other)\n            init = builder.accept(lst.items[0])\n            return vec_create_initialized(builder.builder, vec_type, length, init, line)\n        assert False, other_type\n    if isinstance(arg, ListExpr):\n        items = []\n        for item in arg.items:\n            value = builder.accept(item)\n            items.append(builder.coerce(value, item_type, line))\n        return vec_create_from_values(builder.builder, vec_type, items, line)\n    if isinstance(arg, ListComprehension):\n        return translate_vec_comprehension(builder, vec_type, arg.generator)\n    return vec_from_iterable(builder, vec_type, arg, line)\n\n\ndef vec_from_iterable(\n    builder: IRBuilder, vec_type: RVec, iterable: Expression, line: int\n) -> Value:\n    \"\"\"Construct a vec from an arbitrary iterable.\"\"\"\n    # Translate it as a vec comprehension vec[t]([<name> for <name> in\n    # iterable]). This way we can use various special casing supported\n    # by for loops and comprehensions.\n    vec = Register(vec_type)\n    builder.assign(vec, vec_create(builder.builder, vec_type, 0, line), line)\n    name = f\"___tmp_{line}\"\n    var = Var(name)\n    reg = builder.add_local(var, vec_type.item_type)\n    index = NameExpr(name)\n    index.kind = LDEF\n    index.node = var\n    loop_params: list[tuple[Expression, Expression, list[Expression], bool]] = [\n        (index, iterable, [], False)\n    ]\n\n    def gen_inner_stmts() -> None:\n        builder.assign(vec, vec_append(builder.builder, vec, reg, line), line)\n\n    comprehension_helper(builder, loop_params, gen_inner_stmts, line)\n    return vec\n\n\ndef translate_cast_expr(builder: IRBuilder, expr: CastExpr) -> Value:\n    src = builder.accept(expr.expr)\n    target_type = builder.type_to_rtype(expr.type)\n    return builder.coerce(src, target_type, expr.line)\n\n\n# Operators\n\n\ndef transform_unary_expr(builder: IRBuilder, expr: UnaryExpr) -> Value:\n    folded = try_constant_fold(builder, expr)\n    if folded:\n        return folded\n\n    return builder.unary_op(builder.accept(expr.expr), expr.op, expr.line)\n\n\ndef transform_op_expr(builder: IRBuilder, expr: OpExpr) -> Value:\n    if expr.op in (\"and\", \"or\"):\n        return builder.shortcircuit_expr(expr)\n\n    # Special case for string formatting\n    if expr.op == \"%\" and isinstance(expr.left, (StrExpr, BytesExpr)):\n        ret = translate_printf_style_formatting(builder, expr.left, expr.right)\n        if ret is not None:\n            return ret\n\n    folded = try_constant_fold(builder, expr)\n    if folded:\n        return folded\n\n    borrow_left = False\n    borrow_right = False\n\n    ltype = builder.node_type(expr.left)\n    rtype = builder.node_type(expr.right)\n\n    # Special case some int ops to allow borrowing operands.\n    if is_int_rprimitive(ltype) and is_int_rprimitive(rtype):\n        if expr.op == \"//\":\n            expr = try_optimize_int_floor_divide(builder, expr)\n        if expr.op in int_borrow_friendly_op:\n            borrow_left = is_borrow_friendly_expr(builder, expr.right)\n            borrow_right = True\n    elif is_fixed_width_rtype(ltype) and is_fixed_width_rtype(rtype):\n        borrow_left = is_borrow_friendly_expr(builder, expr.right)\n        borrow_right = True\n\n    left = builder.accept(expr.left, can_borrow=borrow_left)\n    right = builder.accept(expr.right, can_borrow=borrow_right)\n    return builder.binary_op(left, right, expr.op, expr.line)\n\n\ndef try_optimize_int_floor_divide(builder: IRBuilder, expr: OpExpr) -> OpExpr:\n    \"\"\"Replace // with a power of two with a right shift, if possible.\"\"\"\n    divisor = constant_fold_expr(builder, expr.right)\n    if not isinstance(divisor, int):\n        return expr\n    shift = divisor.bit_length() - 1\n    if 0 < shift < 28 and divisor == (1 << shift):\n        new_expr = OpExpr(\">>\", expr.left, IntExpr(shift))\n        new_expr.line = expr.line\n        return new_expr\n    return expr\n\n\ndef transform_index_expr(builder: IRBuilder, expr: IndexExpr) -> Value:\n    index = expr.index\n    base_type = builder.node_type(expr.base)\n    can_borrow = is_list_rprimitive(base_type) or isinstance(base_type, RVec)\n    can_borrow_base = can_borrow and is_borrow_friendly_expr(builder, index)\n\n    # Check for dunder specialization for non-slice indexing\n    if not isinstance(index, SliceExpr):\n        specialized = apply_dunder_specialization(builder, expr.base, [index], \"__getitem__\", expr)\n        if specialized is not None:\n            return specialized\n\n    base = builder.accept(expr.base, can_borrow=can_borrow_base)\n\n    if isinstance(base.type, RTuple):\n        folded_index = constant_fold_expr(builder, index)\n        if isinstance(folded_index, int):\n            length = len(base.type.types)\n            if -length <= folded_index <= length - 1:\n                return builder.add(TupleGet(base, folded_index, expr.line))\n\n    if isinstance(index, SliceExpr):\n        value = try_gen_slice_op(builder, base, index)\n        if value:\n            return value\n\n    index_reg = builder.accept(expr.index, can_borrow=can_borrow)\n    return builder.builder.get_item(\n        base, index_reg, builder.node_type(expr), expr.line, can_borrow=builder.can_borrow\n    )\n\n\ndef try_constant_fold(builder: IRBuilder, expr: Expression) -> Value | None:\n    \"\"\"Return the constant value of an expression if possible.\n\n    Return None otherwise.\n    \"\"\"\n    value = constant_fold_expr(builder, expr)\n    if value is not None:\n        return builder.load_literal_value(value)\n    return None\n\n\ndef try_gen_slice_op(builder: IRBuilder, base: Value, index: SliceExpr) -> Value | None:\n    \"\"\"Generate specialized slice op for some index expressions.\n\n    Return None if a specialized op isn't available.\n\n    This supports obj[x:y], obj[:x], and obj[x:] for a few types.\n    \"\"\"\n    if index.stride:\n        # We can only handle the default stride of 1.\n        return None\n\n    if index.begin_index:\n        begin_type = builder.node_type(index.begin_index)\n    else:\n        begin_type = int_rprimitive\n    if index.end_index:\n        end_type = builder.node_type(index.end_index)\n    else:\n        end_type = int_rprimitive\n\n    # Both begin and end index must be int (or missing).\n    if is_any_int(begin_type) and is_any_int(end_type):\n        if index.begin_index:\n            begin = builder.accept(index.begin_index)\n        else:\n            begin = builder.load_int(0)\n        if index.end_index:\n            end = builder.accept(index.end_index)\n        else:\n            # Replace missing end index with the largest short integer\n            # (a sequence can't be longer).\n            end = builder.load_int(MAX_SHORT_INT)\n        if isinstance(base.type, RVec):\n            return vec_slice(builder.builder, base, begin, end, index.line)\n        candidates = [list_slice_op, tuple_slice_op, str_slice_op, bytes_slice_op]\n        return builder.builder.matching_call_c(candidates, [base, begin, end], index.line)\n\n    return None\n\n\ndef transform_conditional_expr(builder: IRBuilder, expr: ConditionalExpr) -> Value:\n    if_body, else_body, next_block = BasicBlock(), BasicBlock(), BasicBlock()\n\n    process_conditional(builder, expr.cond, if_body, else_body)\n    expr_type = builder.node_type(expr)\n    # Having actual Phi nodes would be really nice here!\n    target = Register(expr_type)\n\n    builder.activate_block(if_body)\n    true_value = builder.accept(expr.if_expr)\n    true_value = builder.coerce(true_value, expr_type, expr.line)\n    builder.add(Assign(target, true_value, expr.line))\n    builder.goto(next_block)\n\n    builder.activate_block(else_body)\n    false_value = builder.accept(expr.else_expr)\n    false_value = builder.coerce(false_value, expr_type, expr.line)\n    builder.add(Assign(target, false_value, expr.line))\n    builder.goto(next_block)\n\n    builder.activate_block(next_block)\n\n    return target\n\n\ndef set_literal_values(builder: IRBuilder, items: Sequence[Expression]) -> list[object] | None:\n    values: list[object] = []\n    for item in items:\n        const_value = constant_fold_expr(builder, item)\n        if const_value is not None:\n            values.append(const_value)\n            continue\n\n        if isinstance(item, RefExpr):\n            if item.fullname == \"builtins.None\":\n                values.append(None)\n            elif item.fullname == \"builtins.True\":\n                values.append(True)\n            elif item.fullname == \"builtins.False\":\n                values.append(False)\n        elif isinstance(item, TupleExpr):\n            tuple_values = set_literal_values(builder, item.items)\n            if tuple_values is not None:\n                values.append(tuple(tuple_values))\n\n    if len(values) != len(items):\n        # Bail if not all items can be converted into values.\n        return None\n    return values\n\n\ndef precompute_set_literal(builder: IRBuilder, s: SetExpr) -> Value | None:\n    \"\"\"Try to pre-compute a frozenset literal during module initialization.\n\n    Return None if it's not possible.\n\n    Supported items:\n     - Anything supported by irbuild.constant_fold.constant_fold_expr()\n     - None, True, and False\n     - Tuple literals with only items listed above\n    \"\"\"\n    values = set_literal_values(builder, s.items)\n    if values is not None:\n        return builder.add(LoadLiteral(frozenset(values), set_rprimitive))\n\n    return None\n\n\ndef transform_comparison_expr(builder: IRBuilder, e: ComparisonExpr) -> Value:\n    # x in (...)/[...]\n    # x not in (...)/[...]\n    first_op = e.operators[0]\n    if first_op in [\"in\", \"not in\"] and len(e.operators) == 1:\n        result = try_specialize_in_expr(builder, first_op, e.operands[0], e.operands[1], e.line)\n        if result is not None:\n            return result\n\n    if len(e.operators) == 1:\n        # Special some common simple cases\n        if first_op in (\"is\", \"is not\"):\n            right_expr = e.operands[1]\n            if isinstance(right_expr, NameExpr) and right_expr.fullname == \"builtins.None\":\n                # Special case 'is None' / 'is not None'.\n                return translate_is_none(builder, e.operands[0], negated=first_op != \"is\")\n        left_expr = e.operands[0]\n        if is_int_rprimitive(builder.node_type(left_expr)):\n            right_expr = e.operands[1]\n            if is_int_rprimitive(builder.node_type(right_expr)):\n                if first_op in int_borrow_friendly_op:\n                    borrow_left = is_borrow_friendly_expr(builder, right_expr)\n                    left = builder.accept(left_expr, can_borrow=borrow_left)\n                    right = builder.accept(right_expr, can_borrow=True)\n                    return builder.binary_op(left, right, first_op, e.line)\n\n    # TODO: Don't produce an expression when used in conditional context\n    # All of the trickiness here is due to support for chained conditionals\n    # (`e1 < e2 > e3`, etc). `e1 < e2 > e3` is approximately equivalent to\n    # `e1 < e2 and e2 > e3` except that `e2` is only evaluated once.\n    expr_type = builder.node_type(e)\n\n    # go(i, prev) generates code for `ei opi e{i+1} op{i+1} ... en`,\n    # assuming that prev contains the value of `ei`.\n    def go(i: int, prev: Value) -> Value:\n        if i == len(e.operators) - 1:\n            return transform_basic_comparison(\n                builder, e.operators[i], prev, builder.accept(e.operands[i + 1]), e.line\n            )\n\n        next = builder.accept(e.operands[i + 1])\n        return builder.builder.shortcircuit_helper(\n            \"and\",\n            expr_type,\n            lambda: transform_basic_comparison(builder, e.operators[i], prev, next, e.line),\n            lambda: go(i + 1, next),\n            e.line,\n        )\n\n    return go(0, builder.accept(e.operands[0]))\n\n\ndef try_specialize_in_expr(\n    builder: IRBuilder, op: str, lhs: Expression, rhs: Expression, line: int\n) -> Value | None:\n    left: Value | None = None\n    items: list[Value] | None = None\n\n    if isinstance(rhs, (TupleExpr, ListExpr)):\n        left = builder.accept(lhs)\n        items = [builder.accept(item) for item in rhs.items]\n    elif isinstance(builder.node_type(rhs), RTuple):\n        left = builder.accept(lhs)\n        tuple_val = builder.accept(rhs)\n        assert isinstance(tuple_val.type, RTuple)\n        items = [builder.add(TupleGet(tuple_val, i)) for i in range(len(tuple_val.type.types))]\n\n    if items is not None:\n        assert left is not None\n        n_items = len(items)\n        # x in y -> x == y[0] or ... or x == y[n]\n        # x not in y -> x != y[0] and ... and x != y[n]\n        if n_items > 1:\n            if op == \"in\":\n                cmp_op = \"==\"\n            else:\n                cmp_op = \"!=\"\n            out = BasicBlock()\n            for item in items:\n                cmp = transform_basic_comparison(builder, cmp_op, left, item, line)\n                bool_val = builder.builder.bool_value(cmp)\n                next_block = BasicBlock()\n                if op == \"in\":\n                    builder.add_bool_branch(bool_val, out, next_block)\n                else:\n                    builder.add_bool_branch(bool_val, next_block, out)\n                builder.activate_block(next_block)\n            result_reg = Register(bool_rprimitive)\n            end = BasicBlock()\n            if op == \"in\":\n                values = builder.false(), builder.true()\n            else:\n                values = builder.true(), builder.false()\n            builder.assign(result_reg, values[0], line)\n            builder.goto(end)\n            builder.activate_block(out)\n            builder.assign(result_reg, values[1], line)\n            builder.goto(end)\n            builder.activate_block(end)\n            return result_reg\n        # x in [y]/(y) -> x == y\n        # x not in [y]/(y) -> x != y\n        elif n_items == 1:\n            if op == \"in\":\n                cmp_op = \"==\"\n            else:\n                cmp_op = \"!=\"\n            right = items[0]\n            return transform_basic_comparison(builder, cmp_op, left, right, line)\n        # x in []/() -> False\n        # x not in []/() -> True\n        elif n_items == 0:\n            if op == \"in\":\n                return builder.false()\n            else:\n                return builder.true()\n\n    # x in {...}\n    # x not in {...}\n    if isinstance(rhs, SetExpr):\n        set_literal = precompute_set_literal(builder, rhs)\n        if set_literal is not None:\n            result = builder.builder.primitive_op(\n                set_in_op, [builder.accept(lhs), set_literal], line, bool_rprimitive\n            )\n            if op == \"not in\":\n                return builder.unary_op(result, \"not\", line)\n            return result\n\n    return None\n\n\ndef translate_is_none(builder: IRBuilder, expr: Expression, negated: bool) -> Value:\n    v = builder.accept(expr, can_borrow=True)\n    return builder.binary_op(v, builder.none_object(), \"is not\" if negated else \"is\", expr.line)\n\n\ndef transform_basic_comparison(\n    builder: IRBuilder, op: str, left: Value, right: Value, line: int\n) -> Value:\n    \"\"\"Transform single comparison.\n\n    'op' must be one of these:\n\n       '==', '!=', '<', '<=', '>', '>='\n       'in', 'not in'\n       'is', 'is not'\n    \"\"\"\n    if is_fixed_width_rtype(left.type) and op in ComparisonOp.signed_ops:\n        if right.type == left.type:\n            if left.type.is_signed:\n                op_id = ComparisonOp.signed_ops[op]\n            else:\n                op_id = ComparisonOp.unsigned_ops[op]\n            return builder.builder.comparison_op(left, right, op_id, line)\n        elif isinstance(right, Integer):\n            if left.type.is_signed:\n                op_id = ComparisonOp.signed_ops[op]\n            else:\n                op_id = ComparisonOp.unsigned_ops[op]\n            return builder.builder.comparison_op(\n                left, builder.coerce(right, left.type, line), op_id, line\n            )\n    elif (\n        is_fixed_width_rtype(right.type)\n        and op in ComparisonOp.signed_ops\n        and isinstance(left, Integer)\n    ):\n        if right.type.is_signed:\n            op_id = ComparisonOp.signed_ops[op]\n        else:\n            op_id = ComparisonOp.unsigned_ops[op]\n        return builder.builder.comparison_op(\n            builder.coerce(left, right.type, line), right, op_id, line\n        )\n\n    negate = False\n    if op == \"is not\":\n        op, negate = \"is\", True\n    elif op == \"not in\":\n        op, negate = \"in\", True\n\n    target = builder.binary_op(left, right, op, line)\n\n    if negate:\n        target = builder.unary_op(target, \"not\", line)\n    return target\n\n\ndef translate_printf_style_formatting(\n    builder: IRBuilder, format_expr: StrExpr | BytesExpr, rhs: Expression\n) -> Value | None:\n    tokens = tokenizer_printf_style(format_expr.value)\n    if tokens is not None:\n        literals, format_ops = tokens\n\n        exprs = []\n        if isinstance(rhs, TupleExpr):\n            exprs = rhs.items\n        elif isinstance(rhs, Expression):\n            exprs.append(rhs)\n\n        if isinstance(format_expr, BytesExpr):\n            substitutions = convert_format_expr_to_bytes(\n                builder, format_ops, exprs, format_expr.line\n            )\n            if substitutions is not None:\n                return join_formatted_bytes(builder, literals, substitutions, format_expr.line)\n        else:\n            substitutions = convert_format_expr_to_str(\n                builder, format_ops, exprs, format_expr.line\n            )\n            if substitutions is not None:\n                return join_formatted_strings(builder, literals, substitutions, format_expr.line)\n\n    return None\n\n\n# Literals\n\n\ndef transform_int_expr(builder: IRBuilder, expr: IntExpr) -> Value:\n    return builder.builder.load_int(expr.value)\n\n\ndef transform_float_expr(builder: IRBuilder, expr: FloatExpr) -> Value:\n    return builder.builder.load_float(expr.value)\n\n\ndef transform_complex_expr(builder: IRBuilder, expr: ComplexExpr) -> Value:\n    return builder.builder.load_complex(expr.value)\n\n\ndef transform_str_expr(builder: IRBuilder, expr: StrExpr) -> Value:\n    return builder.load_str(expr.value)\n\n\ndef transform_bytes_expr(builder: IRBuilder, expr: BytesExpr) -> Value:\n    return builder.load_bytes_from_str_literal(expr.value)\n\n\ndef transform_ellipsis(builder: IRBuilder, o: EllipsisExpr) -> Value:\n    return builder.add(LoadAddress(ellipsis_op.type, ellipsis_op.src, o.line))\n\n\n# Display expressions\n\n\ndef transform_list_expr(builder: IRBuilder, expr: ListExpr) -> Value:\n    return _visit_list_display(builder, expr.items, expr.line)\n\n\ndef _visit_list_display(builder: IRBuilder, items: list[Expression], line: int) -> Value:\n    return _visit_display(\n        builder, items, builder.new_list_op, list_append_op, list_extend_op, line, True\n    )\n\n\ndef transform_tuple_expr(builder: IRBuilder, expr: TupleExpr) -> Value:\n    if any(isinstance(item, StarExpr) for item in expr.items):\n        # create a tuple of unknown length\n        return _visit_tuple_display(builder, expr)\n\n    # create a tuple of fixed length (RTuple)\n    tuple_type = builder.node_type(expr)\n    # When handling NamedTuple et. al we might not have proper type info,\n    # so make some up if we need it.\n    types = (\n        tuple_type.types\n        if isinstance(tuple_type, RTuple)\n        else [object_rprimitive] * len(expr.items)\n    )\n\n    items = []\n    for item_expr, item_type in zip(expr.items, types):\n        reg = builder.accept(item_expr)\n        items.append(builder.coerce(reg, item_type, item_expr.line))\n    return builder.add(TupleSet(items, expr.line))\n\n\ndef _visit_tuple_display(builder: IRBuilder, expr: TupleExpr) -> Value:\n    \"\"\"Create a list, then turn it into a tuple.\"\"\"\n    val_as_list = _visit_list_display(builder, expr.items, expr.line)\n    return builder.primitive_op(list_tuple_op, [val_as_list], expr.line)\n\n\ndef transform_dict_expr(builder: IRBuilder, expr: DictExpr) -> Value:\n    \"\"\"First accepts all keys and values, then makes a dict out of them.\"\"\"\n    key_value_pairs = []\n    for key_expr, value_expr in expr.items:\n        key = builder.accept(key_expr) if key_expr is not None else None\n        value = builder.accept(value_expr)\n        key_value_pairs.append((key, value))\n\n    return builder.builder.make_dict(key_value_pairs, expr.line)\n\n\ndef transform_set_expr(builder: IRBuilder, expr: SetExpr) -> Value:\n    return _visit_display(\n        builder, expr.items, builder.new_set_op, set_add_op, set_update_op, expr.line, False\n    )\n\n\ndef _visit_display(\n    builder: IRBuilder,\n    items: list[Expression],\n    constructor_op: Callable[[list[Value], int], Value],\n    append_op: PrimitiveDescription,\n    extend_op: PrimitiveDescription,\n    line: int,\n    is_list: bool,\n) -> Value:\n    accepted_items = []\n    for item in items:\n        if isinstance(item, StarExpr):\n            accepted_items.append((True, builder.accept(item.expr)))\n        else:\n            accepted_items.append((False, builder.accept(item)))\n\n    result: Value | None = None\n    initial_items = []\n    for starred, value in accepted_items:\n        if result is None and not starred and is_list:\n            initial_items.append(value)\n            continue\n\n        if result is None:\n            result = constructor_op(initial_items, line)\n\n        builder.primitive_op(extend_op if starred else append_op, [result, value], line)\n\n    if result is None:\n        result = constructor_op(initial_items, line)\n\n    return result\n\n\n# Comprehensions\n#\n# mypyc always inlines comprehensions (the loop body is emitted directly into\n# the enclosing function's IR, no implicit function call like CPython).\n#\n# However, when a comprehension body contains a lambda, we need a lightweight\n# scope boundary so the closure/env-class machinery can see the comprehension\n# as a separate scope. The comprehension is still inlined (same basic blocks\n# and registers), but we push a new FuncInfo and set up an env class so the\n# lambda can capture loop variables through the standard env-class chain.\n\n\ndef transform_list_comprehension(builder: IRBuilder, o: ListComprehension) -> Value:\n    gen = o.generator\n    if gen in builder.comprehension_to_fitem:\n        return _translate_comprehension_with_scope(\n            builder, gen, lambda: translate_list_comprehension(builder, gen)\n        )\n    return translate_list_comprehension(builder, gen)\n\n\ndef transform_set_comprehension(builder: IRBuilder, o: SetComprehension) -> Value:\n    gen = o.generator\n    if gen in builder.comprehension_to_fitem:\n        return _translate_comprehension_with_scope(\n            builder, gen, lambda: translate_set_comprehension(builder, gen)\n        )\n    return translate_set_comprehension(builder, gen)\n\n\ndef transform_dictionary_comprehension(builder: IRBuilder, o: DictionaryComprehension) -> Value:\n    if raise_error_if_contains_unreachable_names(builder, o):\n        return builder.none()\n\n    if o in builder.comprehension_to_fitem:\n        return _translate_comprehension_with_scope(builder, o, lambda: _dict_comp_body(builder, o))\n    return _dict_comp_body(builder, o)\n\n\ndef _dict_comp_body(builder: IRBuilder, o: DictionaryComprehension) -> Value:\n    d = builder.maybe_spill(builder.call_c(dict_new_op, [], o.line))\n    loop_params = list(zip(o.indices, o.sequences, o.condlists, o.is_async))\n\n    def gen_inner_stmts() -> None:\n        k = builder.accept(o.key)\n        v = builder.accept(o.value)\n        builder.call_c(exact_dict_set_item_op, [builder.read(d, o.line), k, v], o.line)\n\n    comprehension_helper(builder, loop_params, gen_inner_stmts, o.line)\n    return builder.read(d, o.line)\n\n\ndef _translate_comprehension_with_scope(\n    builder: IRBuilder,\n    node: GeneratorExpr | DictionaryComprehension,\n    gen_body: Callable[[], Value],\n) -> Value:\n    \"\"\"Wrap a comprehension body with a lightweight scope for closure capture.\"\"\"\n    from mypyc.irbuild.context import FuncInfo\n    from mypyc.irbuild.env_class import add_vars_to_env, finalize_env_class, setup_env_class\n\n    comprehension_fdef = builder.comprehension_to_fitem[node]\n    fn_info = FuncInfo(\n        fitem=comprehension_fdef,\n        name=comprehension_fdef.name,\n        is_nested=True,\n        contains_nested=True,\n        is_comprehension_scope=True,\n    )\n\n    with builder.enter_scope(fn_info):\n        setup_env_class(builder)\n        finalize_env_class(builder)\n        add_vars_to_env(builder)\n        return gen_body()\n\n\n# Misc\n\n\ndef transform_slice_expr(builder: IRBuilder, expr: SliceExpr) -> Value:\n    def get_arg(arg: Expression | None) -> Value:\n        if arg is None:\n            return builder.none_object()\n        else:\n            return builder.accept(arg)\n\n    args = [get_arg(expr.begin_index), get_arg(expr.end_index), get_arg(expr.stride)]\n    return builder.primitive_op(new_slice_op, args, expr.line)\n\n\ndef transform_generator_expr(builder: IRBuilder, o: GeneratorExpr) -> Value:\n    builder.warning(\"Treating generator comprehension as list\", o.line)\n    if o in builder.comprehension_to_fitem:\n        return builder.primitive_op(\n            iter_op,\n            [\n                _translate_comprehension_with_scope(\n                    builder, o, lambda: translate_list_comprehension(builder, o)\n                )\n            ],\n            o.line,\n        )\n    return builder.primitive_op(iter_op, [translate_list_comprehension(builder, o)], o.line)\n\n\ndef transform_assignment_expr(builder: IRBuilder, o: AssignmentExpr) -> Value:\n    value = builder.accept(o.value)\n    target = builder.get_assignment_target(o.target)\n    builder.assign(target, value, o.line)\n    return value\n\n\ndef transform_math_literal(builder: IRBuilder, fullname: str, line: int) -> Value | None:\n    if fullname == \"math.e\":\n        return builder.load_float(math.e, line)\n    if fullname == \"math.pi\":\n        return builder.load_float(math.pi, line)\n    if fullname == \"math.inf\":\n        return builder.load_float(math.inf, line)\n    if fullname == \"math.nan\":\n        return builder.load_float(math.nan, line)\n    if fullname == \"math.tau\":\n        return builder.load_float(math.tau, line)\n\n    return None\n"
  },
  {
    "path": "mypyc/irbuild/for_helpers.py",
    "content": "\"\"\"Helpers for generating for loops and comprehensions.\n\nWe special case certain kinds for loops such as \"for x in range(...)\"\nfor better efficiency.  Each for loop generator class below deals one\nsuch special case.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom typing import ClassVar, cast\n\nfrom mypy.nodes import (\n    ARG_POS,\n    CallExpr,\n    DictionaryComprehension,\n    Expression,\n    GeneratorExpr,\n    ListExpr,\n    Lvalue,\n    MemberExpr,\n    NameExpr,\n    RefExpr,\n    SetExpr,\n    StarExpr,\n    TupleExpr,\n    TypeAlias,\n    Var,\n)\nfrom mypy.types import LiteralType, TupleType, get_proper_type, get_proper_types\nfrom mypyc.ir.ops import (\n    ERR_NEVER,\n    BasicBlock,\n    Branch,\n    Integer,\n    IntOp,\n    LoadAddress,\n    LoadErrorValue,\n    LoadLiteral,\n    LoadMem,\n    MethodCall,\n    RaiseStandardError,\n    Register,\n    TupleGet,\n    TupleSet,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RTuple,\n    RType,\n    RVec,\n    bool_rprimitive,\n    c_pyssize_t_rprimitive,\n    int_rprimitive,\n    is_dict_rprimitive,\n    is_fixed_width_rtype,\n    is_immutable_rprimitive,\n    is_list_rprimitive,\n    is_sequence_rprimitive,\n    is_short_int_rprimitive,\n    is_str_rprimitive,\n    is_tuple_rprimitive,\n    object_pointer_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    short_int_rprimitive,\n)\nfrom mypyc.irbuild.builder import IRBuilder\nfrom mypyc.irbuild.constant_fold import constant_fold_expr\nfrom mypyc.irbuild.prepare import GENERATOR_HELPER_NAME\nfrom mypyc.irbuild.targets import AssignmentTarget, AssignmentTargetTuple\nfrom mypyc.irbuild.vec import vec_append, vec_create, vec_get_item_unsafe, vec_init_item_unsafe\nfrom mypyc.primitives.dict_ops import (\n    dict_check_size_op,\n    dict_item_iter_op,\n    dict_key_iter_op,\n    dict_next_item_op,\n    dict_next_key_op,\n    dict_next_value_op,\n    dict_value_iter_op,\n)\nfrom mypyc.primitives.exc_ops import no_err_occurred_op, propagate_if_error_op\nfrom mypyc.primitives.generic_ops import aiter_op, anext_op, iter_op, next_op\nfrom mypyc.primitives.list_ops import list_append_op, list_get_item_unsafe_op, new_list_set_item_op\nfrom mypyc.primitives.misc_ops import stop_async_iteration_op\nfrom mypyc.primitives.registry import CFunctionDescription\nfrom mypyc.primitives.set_ops import set_add_op\nfrom mypyc.primitives.str_ops import str_get_item_unsafe_op\nfrom mypyc.primitives.tuple_ops import tuple_get_item_unsafe_op\n\nGenFunc = Callable[[], None]\n\n\ndef for_loop_helper(\n    builder: IRBuilder,\n    index: Lvalue,\n    expr: Expression,\n    body_insts: GenFunc,\n    else_insts: GenFunc | None,\n    is_async: bool,\n    line: int,\n) -> None:\n    \"\"\"Generate IR for a loop.\n\n    Args:\n        index: the loop index Lvalue\n        expr: the expression to iterate over\n        body_insts: a function that generates the body of the loop\n        else_insts: a function that generates the else block instructions\n    \"\"\"\n    # Body of the loop\n    body_block = BasicBlock()\n    # Block that steps to the next item\n    step_block = BasicBlock()\n    # Block for the else clause, if we need it\n    else_block = BasicBlock()\n    # Block executed after the loop\n    exit_block = BasicBlock()\n\n    # Determine where we want to exit, if our condition check fails.\n    normal_loop_exit = else_block if else_insts is not None else exit_block\n\n    for_gen = make_for_loop_generator(\n        builder, index, expr, body_block, normal_loop_exit, line, is_async=is_async\n    )\n\n    builder.push_loop_stack(step_block, exit_block)\n    condition_block = BasicBlock()\n    builder.goto_and_activate(condition_block)\n\n    # Add loop condition check.\n    for_gen.gen_condition()\n\n    # Generate loop body.\n    builder.activate_block(body_block)\n    for_gen.begin_body()\n    body_insts()\n\n    # We generate a separate step block (which might be empty).\n    builder.goto_and_activate(step_block)\n    for_gen.gen_step()\n    # Go back to loop condition.\n    builder.goto(condition_block)\n\n    for_gen.add_cleanup(normal_loop_exit)\n    builder.pop_loop_stack()\n\n    if else_insts is not None:\n        builder.activate_block(else_block)\n        else_insts()\n        builder.goto(exit_block)\n\n    builder.activate_block(exit_block)\n\n\ndef for_loop_helper_with_index(\n    builder: IRBuilder,\n    index: Lvalue,\n    expr: Expression,\n    expr_reg: Value,\n    body_insts: Callable[[Value], None],\n    line: int,\n    length: Value,\n) -> None:\n    \"\"\"Generate IR for a sequence iteration.\n\n    This function only works for sequence type. Compared to for_loop_helper,\n    it would feed iteration index to body_insts.\n\n    Args:\n        index: the loop index Lvalue\n        expr: the expression to iterate over\n        body_insts: a function that generates the body of the loop.\n                    It needs a index as parameter.\n    \"\"\"\n    assert is_sequence_rprimitive(expr_reg.type) or isinstance(expr_reg.type, RVec), (\n        expr_reg,\n        expr_reg.type,\n    )\n    target_type = builder.get_sequence_type(expr)\n\n    body_block = BasicBlock()\n    step_block = BasicBlock()\n    exit_block = BasicBlock()\n    condition_block = BasicBlock()\n\n    for_gen = ForSequence(builder, index, body_block, exit_block, line, False)\n    for_gen.init(expr_reg, target_type, reverse=False, length=length)\n\n    builder.push_loop_stack(step_block, exit_block)\n\n    if isinstance(length, Integer) and length.value > 0:\n        builder.goto(body_block)\n        builder.activate_block(condition_block)\n    else:\n        builder.goto_and_activate(condition_block)\n\n    for_gen.gen_condition()\n\n    builder.activate_block(body_block)\n    for_gen.begin_body()\n    body_insts(builder.read(for_gen.index_target, line))\n\n    builder.goto_and_activate(step_block)\n    for_gen.gen_step()\n    builder.goto(condition_block)\n\n    for_gen.add_cleanup(exit_block)\n    builder.pop_loop_stack()\n\n    builder.activate_block(exit_block)\n\n\ndef sequence_from_generator_preallocate_helper(\n    builder: IRBuilder,\n    gen: GeneratorExpr,\n    empty_op_llbuilder: Callable[[Value, int], Value],\n    set_item_op: Callable[[Value, Value, Value, int], None],\n) -> Value | None:\n    \"\"\"Generate a new tuple or list from a simple generator expression.\n\n    Currently we only optimize for simplest generator expression, which means that\n    there is no condition list in the generator and only one original sequence with\n    one index is allowed.\n\n    e.g.  (1) tuple(f(x) for x in a_list/a_tuple/a_str/a_bytes/an_rtuple)\n          (2) list(f(x) for x in a_list/a_tuple/a_str/a_bytes/an_rtuple)\n          (3) [f(x) for x in a_list/a_tuple/a_str/a_bytes/an_rtuple]\n\n    Args:\n        empty_op_llbuilder: A function that can generate an empty sequence op when\n            passed in length. See `new_list_op_with_length` and `new_tuple_op_with_length`\n            for detailed implementation.\n        set_item_op: A primitive that can modify an arbitrary position of a sequence.\n            The op should have three arguments:\n                - Self\n                - Target position\n                - New Value\n            See `new_list_set_item_op` and `new_tuple_set_item_op` for detailed\n            implementation.\n    \"\"\"\n    if len(gen.sequences) == 1 and len(gen.indices) == 1 and len(gen.condlists[0]) == 0:\n        line = gen.line\n        sequence_expr = gen.sequences[0]\n        rtype = builder.node_type(sequence_expr)\n        if not (is_sequence_rprimitive(rtype) or isinstance(rtype, (RTuple, RVec))):\n            return None\n\n        if isinstance(rtype, RTuple):\n            # If input is RTuple, box it to tuple_rprimitive for generic iteration\n            # TODO: this can be optimized a bit better with an unrolled ForRTuple helper\n            proper_type = get_proper_type(builder.types[sequence_expr])\n            assert isinstance(proper_type, TupleType), proper_type\n\n            # the for_loop_helper_with_index crashes for empty tuples, bail out\n            if not proper_type.items:\n                return None\n\n            proper_types = get_proper_types(proper_type.items)\n\n            get_item_ops: list[LoadLiteral | TupleGet]\n            if all(isinstance(typ, LiteralType) for typ in proper_types):\n                get_item_ops = [\n                    LoadLiteral(cast(LiteralType, typ).value, object_rprimitive)\n                    for typ in proper_types\n                ]\n\n            else:\n                sequence = builder.accept(sequence_expr)\n                get_item_ops = [\n                    (\n                        LoadLiteral(typ.value, object_rprimitive)\n                        if isinstance(typ, LiteralType)\n                        else TupleGet(sequence, i, line)\n                    )\n                    for i, typ in enumerate(proper_types)\n                ]\n\n            items = list(map(builder.add, get_item_ops))\n            sequence = builder.new_tuple(items, line)\n\n        else:\n            sequence = builder.accept(sequence_expr)\n\n        length = get_expr_length_value(builder, sequence_expr, sequence, line, use_pyssize_t=True)\n\n        target_op = empty_op_llbuilder(length, line)\n\n        def set_item(item_index: Value) -> None:\n            e = builder.accept(gen.left_expr)\n            set_item_op(target_op, item_index, e, line)\n\n        for_loop_helper_with_index(\n            builder, gen.indices[0], sequence_expr, sequence, set_item, line, length\n        )\n\n        return target_op\n    return None\n\n\ndef translate_list_comprehension(builder: IRBuilder, gen: GeneratorExpr) -> Value:\n    if raise_error_if_contains_unreachable_names(builder, gen):\n        return builder.none()\n\n    def set_item(x: Value, y: Value, z: Value, line: int) -> None:\n        builder.call_c(new_list_set_item_op, [x, y, z], line)\n\n    # Try simplest list comprehension, otherwise fall back to general one\n    val = sequence_from_generator_preallocate_helper(\n        builder,\n        gen,\n        empty_op_llbuilder=builder.builder.new_list_op_with_length,\n        set_item_op=set_item,\n    )\n    if val is not None:\n        return val\n\n    list_ops = builder.maybe_spill(builder.new_list_op([], gen.line))\n\n    loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async))\n\n    def gen_inner_stmts() -> None:\n        e = builder.accept(gen.left_expr)\n        builder.primitive_op(list_append_op, [builder.read(list_ops, gen.line), e], gen.line)\n\n    comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)\n    return builder.read(list_ops, gen.line)\n\n\ndef raise_error_if_contains_unreachable_names(\n    builder: IRBuilder, gen: GeneratorExpr | DictionaryComprehension\n) -> bool:\n    \"\"\"Raise a runtime error and return True if generator contains unreachable names.\n\n    False is returned if the generator can be safely transformed without crashing.\n    (It may still be unreachable!)\n    \"\"\"\n    if any(isinstance(s, NameExpr) and s.node is None for s in gen.indices):\n        error = RaiseStandardError(\n            RaiseStandardError.RUNTIME_ERROR,\n            \"mypyc internal error: should be unreachable\",\n            gen.line,\n        )\n        builder.add(error)\n        return True\n\n    return False\n\n\ndef translate_set_comprehension(builder: IRBuilder, gen: GeneratorExpr) -> Value:\n    if raise_error_if_contains_unreachable_names(builder, gen):\n        return builder.none()\n\n    set_ops = builder.maybe_spill(builder.new_set_op([], gen.line))\n    loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async))\n\n    def gen_inner_stmts() -> None:\n        e = builder.accept(gen.left_expr)\n        builder.primitive_op(set_add_op, [builder.read(set_ops, gen.line), e], gen.line)\n\n    comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)\n    return builder.read(set_ops, gen.line)\n\n\ndef translate_vec_comprehension(builder: IRBuilder, vec_type: RVec, gen: GeneratorExpr) -> Value:\n    def set_item(x: Value, y: Value, z: Value, line: int) -> None:\n        vec_init_item_unsafe(builder.builder, x, y, z, line)\n\n    # Try simplest comprehension, otherwise fall back to general one\n    val = sequence_from_generator_preallocate_helper(\n        builder,\n        gen,\n        empty_op_llbuilder=lambda length, line: vec_create(\n            builder.builder, vec_type, length, line\n        ),\n        set_item_op=set_item,\n    )\n    if val is not None:\n        return val\n\n    vec = Register(vec_type)\n    builder.assign(vec, vec_create(builder.builder, vec_type, 0, gen.line), gen.line)\n    loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async))\n\n    def gen_inner_stmts() -> None:\n        e = builder.accept(gen.left_expr)\n        builder.assign(vec, vec_append(builder.builder, vec, e, gen.line), gen.line)\n\n    comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)\n    return vec\n\n\ndef comprehension_helper(\n    builder: IRBuilder,\n    loop_params: list[tuple[Lvalue, Expression, list[Expression], bool]],\n    gen_inner_stmts: Callable[[], None],\n    line: int,\n) -> None:\n    \"\"\"Helper function for list comprehensions.\n\n    Args:\n        loop_params: a list of (index, expr, [conditions]) tuples defining nested loops:\n            - \"index\" is the Lvalue indexing that loop;\n            - \"expr\" is the expression for the object to be iterated over;\n            - \"conditions\" is a list of conditions, evaluated in order with short-circuiting,\n                that must all be true for the loop body to be executed\n        gen_inner_stmts: function to generate the IR for the body of the innermost loop\n    \"\"\"\n\n    def handle_loop(loop_params: list[tuple[Lvalue, Expression, list[Expression], bool]]) -> None:\n        \"\"\"Generate IR for a loop.\n\n        Given a list of (index, expression, [conditions]) tuples, generate IR\n        for the nested loops the list defines.\n        \"\"\"\n        index, expr, conds, is_async = loop_params[0]\n        for_loop_helper(\n            builder,\n            index,\n            expr,\n            lambda: loop_contents(conds, loop_params[1:]),\n            None,\n            is_async=is_async,\n            line=line,\n        )\n\n    def loop_contents(\n        conds: list[Expression],\n        remaining_loop_params: list[tuple[Lvalue, Expression, list[Expression], bool]],\n    ) -> None:\n        \"\"\"Generate the body of the loop.\n\n        Args:\n            conds: a list of conditions to be evaluated (in order, with short circuiting)\n                to gate the body of the loop\n            remaining_loop_params: the parameters for any further nested loops; if it's empty\n                we'll instead evaluate the \"gen_inner_stmts\" function\n        \"\"\"\n        # Check conditions, in order, short circuiting them.\n        for cond in conds:\n            cond_val = builder.accept(cond)\n            cont_block, rest_block = BasicBlock(), BasicBlock()\n            # If the condition is true we'll skip the continue.\n            builder.add_bool_branch(cond_val, rest_block, cont_block)\n            builder.activate_block(cont_block)\n            builder.nonlocal_control[-1].gen_continue(builder, cond.line)\n            builder.goto_and_activate(rest_block)\n\n        if remaining_loop_params:\n            # There's another nested level, so the body of this loop is another loop.\n            return handle_loop(remaining_loop_params)\n        else:\n            # We finally reached the actual body of the generator.\n            # Generate the IR for the inner loop body.\n            gen_inner_stmts()\n\n    handle_loop(loop_params)\n\n\ndef is_range_ref(expr: RefExpr) -> bool:\n    return (\n        expr.fullname == \"builtins.range\"\n        or isinstance(expr.node, TypeAlias)\n        and expr.fullname == \"six.moves.xrange\"\n    )\n\n\ndef make_for_loop_generator(\n    builder: IRBuilder,\n    index: Lvalue,\n    expr: Expression,\n    body_block: BasicBlock,\n    loop_exit: BasicBlock,\n    line: int,\n    is_async: bool = False,\n    nested: bool = False,\n) -> ForGenerator:\n    \"\"\"Return helper object for generating a for loop over an iterable.\n\n    If \"nested\" is True, this is a nested iterator such as \"e\" in \"enumerate(e)\".\n    \"\"\"\n\n    # Do an async loop if needed. async is always generic\n    if is_async:\n        expr_reg = builder.accept(expr)\n        async_obj = ForAsyncIterable(builder, index, body_block, loop_exit, line, nested)\n        item_type = builder._analyze_iterable_item_type(expr)\n        item_rtype = builder.type_to_rtype(item_type)\n        async_obj.init(expr_reg, item_rtype)\n        return async_obj\n\n    rtyp = builder.node_type(expr)\n    if is_sequence_rprimitive(rtyp) or isinstance(rtyp, RVec):\n        # Special case \"for x in <seq>\" for concrete sequence types.\n        expr_reg = builder.accept(expr)\n        target_type = builder.get_sequence_type(expr)\n\n        for_list = ForSequence(builder, index, body_block, loop_exit, line, nested)\n        for_list.init(expr_reg, target_type, reverse=False)\n        return for_list\n\n    if is_dict_rprimitive(rtyp):\n        # Special case \"for k in <dict>\".\n        expr_reg = builder.accept(expr)\n        target_type = builder.get_dict_key_type(expr)\n\n        for_dict = ForDictionaryKeys(builder, index, body_block, loop_exit, line, nested)\n        for_dict.init(expr_reg, target_type)\n        return for_dict\n\n    if isinstance(expr, CallExpr) and isinstance(expr.callee, RefExpr):\n        if (\n            is_range_ref(expr.callee)\n            and (\n                len(expr.args) <= 2\n                or (len(expr.args) == 3 and builder.extract_int(expr.args[2]) is not None)\n            )\n            and set(expr.arg_kinds) == {ARG_POS}\n        ):\n            # Special case \"for x in range(...)\".\n            # We support the 3 arg form but only for int literals, since it doesn't\n            # seem worth the hassle of supporting dynamically determining which\n            # direction of comparison to do.\n            if len(expr.args) == 1:\n                start_reg: Value = Integer(0)\n                end_reg = builder.accept(expr.args[0])\n            else:\n                start_reg = builder.accept(expr.args[0])\n                end_reg = builder.accept(expr.args[1])\n            if len(expr.args) == 3:\n                step = builder.extract_int(expr.args[2])\n                assert step is not None\n                if step == 0:\n                    builder.error(\"range() step can't be zero\", expr.args[2].line)\n            else:\n                step = 1\n\n            for_range = ForRange(builder, index, body_block, loop_exit, line, nested)\n            for_range.init(start_reg, end_reg, step)\n            return for_range\n\n        elif (\n            expr.callee.fullname == \"builtins.enumerate\"\n            and len(expr.args) == 1\n            and expr.arg_kinds == [ARG_POS]\n            and isinstance(index, TupleExpr)\n            and len(index.items) == 2\n        ):\n            # Special case \"for i, x in enumerate(y)\".\n            lvalue1 = index.items[0]\n            lvalue2 = index.items[1]\n            for_enumerate = ForEnumerate(builder, index, body_block, loop_exit, line, nested)\n            for_enumerate.init(lvalue1, lvalue2, expr.args[0])\n            return for_enumerate\n\n        elif (\n            expr.callee.fullname == \"builtins.zip\"\n            and len(expr.args) >= 2\n            and set(expr.arg_kinds) == {ARG_POS}\n            and isinstance(index, TupleExpr)\n            and len(index.items) == len(expr.args)\n        ):\n            # Special case \"for x, y in zip(a, b)\".\n            for_zip = ForZip(builder, index, body_block, loop_exit, line, nested)\n            for_zip.init(index.items, expr.args)\n            return for_zip\n\n        if (\n            expr.callee.fullname == \"builtins.reversed\"\n            and len(expr.args) == 1\n            and expr.arg_kinds == [ARG_POS]\n            and is_sequence_rprimitive(builder.node_type(expr.args[0]))\n        ):\n            # Special case \"for x in reversed(<list>)\".\n            expr_reg = builder.accept(expr.args[0])\n            target_type = builder.get_sequence_type(expr)\n\n            for_list = ForSequence(builder, index, body_block, loop_exit, line, nested)\n            for_list.init(expr_reg, target_type, reverse=True)\n            return for_list\n    if isinstance(expr, CallExpr) and isinstance(expr.callee, MemberExpr) and not expr.args:\n        # Special cases for dictionary iterator methods, like dict.items().\n        rtype = builder.node_type(expr.callee.expr)\n        if is_dict_rprimitive(rtype) and expr.callee.name in (\"keys\", \"values\", \"items\"):\n            expr_reg = builder.accept(expr.callee.expr)\n            for_dict_type: type[ForGenerator] | None = None\n            if expr.callee.name == \"keys\":\n                target_type = builder.get_dict_key_type(expr.callee.expr)\n                for_dict_type = ForDictionaryKeys\n            elif expr.callee.name == \"values\":\n                target_type = builder.get_dict_value_type(expr.callee.expr)\n                for_dict_type = ForDictionaryValues\n            else:\n                target_type = builder.get_dict_item_type(expr.callee.expr)\n                for_dict_type = ForDictionaryItems\n            for_dict_gen = for_dict_type(builder, index, body_block, loop_exit, line, nested)\n            for_dict_gen.init(expr_reg, target_type)\n            return for_dict_gen\n\n    iterable_expr_reg: Value | None = None\n    if isinstance(expr, SetExpr):\n        # Special case \"for x in <set literal>\".\n        from mypyc.irbuild.expression import precompute_set_literal\n\n        set_literal = precompute_set_literal(builder, expr)\n        if set_literal is not None:\n            iterable_expr_reg = set_literal\n\n    # Default to a generic for loop.\n    if iterable_expr_reg is None:\n        iterable_expr_reg = builder.accept(expr)\n\n    it = iterable_expr_reg.type\n    for_obj: ForNativeGenerator | ForIterable\n    if isinstance(it, RInstance) and it.class_ir.has_method(GENERATOR_HELPER_NAME):\n        # Directly call generator object methods if iterating over a native generator.\n        for_obj = ForNativeGenerator(builder, index, body_block, loop_exit, line, nested)\n    else:\n        # Generic implementation that works of arbitrary iterables.\n        for_obj = ForIterable(builder, index, body_block, loop_exit, line, nested)\n    item_type = builder._analyze_iterable_item_type(expr)\n    item_rtype = builder.type_to_rtype(item_type)\n    for_obj.init(iterable_expr_reg, item_rtype)\n    return for_obj\n\n\nclass ForGenerator:\n    \"\"\"Abstract base class for generating for loops.\"\"\"\n\n    def __init__(\n        self,\n        builder: IRBuilder,\n        index: Lvalue,\n        body_block: BasicBlock,\n        loop_exit: BasicBlock,\n        line: int,\n        nested: bool,\n    ) -> None:\n        self.builder = builder\n        self.index = index\n        self.body_block = body_block\n        self.line = line\n        # Some for loops need a cleanup block that we execute at exit. We\n        # create a cleanup block if needed. However, if we are generating a for\n        # loop for a nested iterator, such as \"e\" in \"enumerate(e)\", the\n        # outermost generator should generate the cleanup block -- we don't\n        # need to do it here.\n        if self.need_cleanup() and not nested:\n            # Create a new block to handle cleanup after loop exit.\n            self.loop_exit = BasicBlock()\n        else:\n            # Just use the existing loop exit block.\n            self.loop_exit = loop_exit\n\n    def need_cleanup(self) -> bool:\n        \"\"\"If this returns true, we need post-loop cleanup.\"\"\"\n        return False\n\n    def add_cleanup(self, exit_block: BasicBlock) -> None:\n        \"\"\"Add post-loop cleanup, if needed.\"\"\"\n        if self.need_cleanup():\n            self.builder.activate_block(self.loop_exit)\n            self.gen_cleanup()\n            self.builder.goto(exit_block)\n\n    def gen_condition(self) -> None:\n        \"\"\"Generate check for loop exit (e.g. exhaustion of iteration).\"\"\"\n\n    def begin_body(self) -> None:\n        \"\"\"Generate ops at the beginning of the body (if needed).\"\"\"\n\n    def gen_step(self) -> None:\n        \"\"\"Generate stepping to the next item (if needed).\"\"\"\n\n    def gen_cleanup(self) -> None:\n        \"\"\"Generate post-loop cleanup (if needed).\"\"\"\n\n    def load_len(self, expr: Value | AssignmentTarget) -> Value:\n        \"\"\"A helper to get collection length, used by several subclasses.\"\"\"\n        return self.builder.builder.builtin_len(\n            self.builder.read(expr, self.line), self.line, use_pyssize_t=True\n        )\n\n\nclass ForIterable(ForGenerator):\n    \"\"\"Generate IR for a for loop over an arbitrary iterable (the general case).\"\"\"\n\n    def need_cleanup(self) -> bool:\n        # Create a new cleanup block for when the loop is finished.\n        return True\n\n    def init(self, expr_reg: Value, target_type: RType) -> None:\n        # Define targets to contain the expression, along with the iterator that will be used\n        # for the for-loop. If we are inside of a generator function, spill these into the\n        # environment class.\n        builder = self.builder\n        iter_reg = builder.primitive_op(iter_op, [expr_reg], self.line)\n        builder.maybe_spill(expr_reg)\n        self.iter_target = builder.maybe_spill(iter_reg)\n        self.target_type = target_type\n\n    def gen_condition(self) -> None:\n        # We call __next__ on the iterator and check to see if the return value\n        # is NULL, which signals either the end of the Iterable being traversed\n        # or an exception being raised. Note that Branch.IS_ERROR checks only\n        # for NULL (an exception does not necessarily have to be raised).\n        builder = self.builder\n        line = self.line\n        self.next_reg = builder.call_c(next_op, [builder.read(self.iter_target, line)], line)\n        builder.add(Branch(self.next_reg, self.loop_exit, self.body_block, Branch.IS_ERROR))\n\n    def begin_body(self) -> None:\n        # Assign the value obtained from __next__ to the\n        # lvalue so that it can be referenced by code in the body of the loop.\n        builder = self.builder\n        line = self.line\n        # We unbox here so that iterating with tuple unpacking generates a tuple based\n        # unpack instead of an iterator based one.\n        next_reg = builder.coerce(self.next_reg, self.target_type, line)\n        builder.assign(builder.get_assignment_target(self.index), next_reg, line)\n\n    def gen_step(self) -> None:\n        # Nothing to do here, since we get the next item as part of gen_condition().\n        pass\n\n    def gen_cleanup(self) -> None:\n        # We set the branch to go here if the conditional evaluates to true. If\n        # an exception was raised during the loop, then err_reg will be set to\n        # True. If no_err_occurred_op returns False, then the exception will be\n        # propagated using the ERR_FALSE flag.\n        self.builder.call_c(no_err_occurred_op, [], self.line)\n\n\nclass ForNativeGenerator(ForGenerator):\n    \"\"\"Generate IR for a for loop over a native generator.\"\"\"\n\n    def need_cleanup(self) -> bool:\n        # Create a new cleanup block for when the loop is finished.\n        return True\n\n    def init(self, expr_reg: Value, target_type: RType) -> None:\n        # Define target to contains the generator expression. It's also the iterator.\n        # If we are inside a generator function, spill these into the environment class.\n        builder = self.builder\n        self.iter_target = builder.maybe_spill(expr_reg)\n        self.target_type = target_type\n\n    def gen_condition(self) -> None:\n        builder = self.builder\n        line = self.line\n        self.return_value = Register(object_rprimitive)\n        err = builder.add(LoadErrorValue(object_rprimitive, undefines=True))\n        builder.assign(self.return_value, err, line)\n\n        # Call generated generator helper method, passing a PyObject ** as the final\n        # argument that will be used to store the return value in the return value\n        # register. We ignore the return value but the presence of a return value\n        # indicates that the generator has finished. This is faster than raising\n        # and catching StopIteration, which is the non-native way of doing this.\n        ptr = builder.add(LoadAddress(object_pointer_rprimitive, self.return_value))\n        nn = builder.none_object()\n        helper_call = MethodCall(\n            builder.read(self.iter_target, line),\n            GENERATOR_HELPER_NAME,\n            [nn, nn, nn, nn, ptr],\n            line,\n        )\n        # We provide custom handling for error values.\n        helper_call.error_kind = ERR_NEVER\n\n        self.next_reg = builder.add(helper_call)\n        builder.add(Branch(self.next_reg, self.loop_exit, self.body_block, Branch.IS_ERROR))\n\n    def begin_body(self) -> None:\n        # Assign the value obtained from the generator helper method to the\n        # lvalue so that it can be referenced by code in the body of the loop.\n        builder = self.builder\n        line = self.line\n        # We unbox here so that iterating with tuple unpacking generates a tuple based\n        # unpack instead of an iterator based one.\n        next_reg = builder.coerce(self.next_reg, self.target_type, line)\n        builder.assign(builder.get_assignment_target(self.index), next_reg, line)\n\n    def gen_step(self) -> None:\n        # Nothing to do here, since we get the next item as part of gen_condition().\n        pass\n\n    def gen_cleanup(self) -> None:\n        # If return value is NULL (it wasn't assigned to by the generator helper method),\n        # an exception was raised that we need to propagate.\n        self.builder.primitive_op(propagate_if_error_op, [self.return_value], self.line)\n\n\nclass ForAsyncIterable(ForGenerator):\n    \"\"\"Generate IR for an async for loop.\"\"\"\n\n    def init(self, expr_reg: Value, target_type: RType) -> None:\n        # Define targets to contain the expression, along with the\n        # iterator that will be used for the for-loop. We are inside\n        # of a generator function, so we will spill these into\n        # environment class.\n        builder = self.builder\n        iter_reg = builder.call_c(aiter_op, [expr_reg], self.line)\n        builder.maybe_spill(expr_reg)\n        self.iter_target = builder.maybe_spill(iter_reg)\n        self.target_type = target_type\n        self.stop_reg = Register(bool_rprimitive)\n\n    def gen_condition(self) -> None:\n        # This does the test and fetches the next value\n        # try:\n        #     TARGET = await type(iter).__anext__(iter)\n        #     stop = False\n        # except StopAsyncIteration:\n        #     stop = True\n        #\n        # What a pain.\n        # There are optimizations available here if we punch through some abstractions.\n\n        from mypyc.irbuild.statement import emit_await, transform_try_except\n\n        builder = self.builder\n        line = self.line\n\n        def except_match() -> Value:\n            addr = builder.add(LoadAddress(pointer_rprimitive, stop_async_iteration_op.src, line))\n            return builder.add(LoadMem(stop_async_iteration_op.type, addr, borrow=True))\n\n        def try_body() -> None:\n            awaitable = builder.call_c(anext_op, [builder.read(self.iter_target, line)], line)\n            self.next_reg = emit_await(builder, awaitable, line)\n            builder.assign(self.stop_reg, builder.false(), line)\n\n        def except_body() -> None:\n            builder.assign(self.stop_reg, builder.true(), line)\n\n        transform_try_except(\n            builder, try_body, [((except_match, line), None, except_body)], None, line\n        )\n\n        builder.add(Branch(self.stop_reg, self.loop_exit, self.body_block, Branch.BOOL))\n\n    def begin_body(self) -> None:\n        # Assign the value obtained from await __anext__ to the\n        # lvalue so that it can be referenced by code in the body of the loop.\n        builder = self.builder\n        line = self.line\n        # We unbox here so that iterating with tuple unpacking generates a tuple based\n        # unpack instead of an iterator based one.\n        next_reg = builder.coerce(self.next_reg, self.target_type, line)\n        builder.assign(builder.get_assignment_target(self.index), next_reg, line)\n\n    def gen_step(self) -> None:\n        # Nothing to do here, since we get the next item as part of gen_condition().\n        pass\n\n\ndef unsafe_index(builder: IRBuilder, target: Value, index: Value, line: int) -> Value:\n    \"\"\"Emit a potentially unsafe index into a target.\"\"\"\n    # This doesn't really fit nicely into any of our data-driven frameworks\n    # since we want to use __getitem__ if we don't have an unsafe version,\n    # so we just check manually.\n    if is_list_rprimitive(target.type):\n        return builder.primitive_op(list_get_item_unsafe_op, [target, index], line)\n    elif is_tuple_rprimitive(target.type):\n        return builder.call_c(tuple_get_item_unsafe_op, [target, index], line)\n    elif is_str_rprimitive(target.type):\n        return builder.call_c(str_get_item_unsafe_op, [target, index], line)\n    elif isinstance(target.type, RVec):\n        return vec_get_item_unsafe(builder.builder, target, index, line)\n    else:\n        return builder.gen_method_call(target, \"__getitem__\", [index], None, line)\n\n\nclass ForSequence(ForGenerator):\n    \"\"\"Generate optimized IR for a for loop over a sequence.\n\n    Supports iterating in both forward and reverse.\n    \"\"\"\n\n    length_reg: Value | AssignmentTarget | None\n\n    def init(\n        self, expr_reg: Value, target_type: RType, reverse: bool, length: Value | None = None\n    ) -> None:\n        assert is_sequence_rprimitive(expr_reg.type) or isinstance(expr_reg.type, RVec), (\n            expr_reg,\n            expr_reg.type,\n        )\n        builder = self.builder\n        # Record a Value indicating the length of the sequence, if known at compile time.\n        self.length = length\n        self.reverse = reverse\n        # Define target to contain the expression, along with the index that will be used\n        # for the for-loop. If we are inside of a generator function, spill these into the\n        # environment class.\n        self.expr_target = builder.maybe_spill(expr_reg)\n        if is_immutable_rprimitive(expr_reg.type):\n            # If the expression is an immutable type, we can load the length just once.\n            self.length_reg = builder.maybe_spill(self.length or self.load_len(self.expr_target))\n        else:\n            # Otherwise, even if the length is known, we must recalculate the length\n            # at every iteration for compatibility with python semantics.\n            self.length_reg = None\n        if not reverse:\n            index_reg: Value = Integer(0, c_pyssize_t_rprimitive)\n        else:\n            if self.length_reg is not None:\n                len_val = builder.read(self.length_reg, self.line)\n            else:\n                len_val = self.load_len(self.expr_target)\n            index_reg = builder.builder.int_sub(len_val, 1)\n        self.index_target = builder.maybe_spill_assignable(index_reg)\n        self.target_type = target_type\n\n    def gen_condition(self) -> None:\n        builder = self.builder\n        line = self.line\n        if self.reverse:\n            # If we are iterating in reverse order, we obviously need\n            # to check that the index is still positive. Somewhat less\n            # obviously we still need to check against the length,\n            # since it could shrink out from under us.\n            comparison = builder.binary_op(\n                builder.read(self.index_target, line), Integer(0), \">=\", line\n            )\n            second_check = BasicBlock()\n            builder.add_bool_branch(comparison, second_check, self.loop_exit)\n            builder.activate_block(second_check)\n        if self.length_reg is None:\n            # For compatibility with python semantics we recalculate the length\n            # at every iteration.\n            len_reg = self.load_len(self.expr_target)\n        else:\n            # (unless input is immutable type).\n            len_reg = builder.read(self.length_reg, line)\n        comparison = builder.binary_op(builder.read(self.index_target, line), len_reg, \"<\", line)\n        builder.add_bool_branch(comparison, self.body_block, self.loop_exit)\n\n    def begin_body(self) -> None:\n        builder = self.builder\n        line = self.line\n        # Read the next list item.\n        value_box = unsafe_index(\n            builder,\n            builder.read(self.expr_target, line),\n            builder.read(self.index_target, line),\n            line,\n        )\n        assert value_box\n        # We coerce to the type of list elements here so that\n        # iterating with tuple unpacking generates a tuple based\n        # unpack instead of an iterator based one.\n        builder.assign(\n            builder.get_assignment_target(self.index),\n            builder.coerce(value_box, self.target_type, line),\n            line,\n        )\n\n    def gen_step(self) -> None:\n        # Step to the next item.\n        builder = self.builder\n        line = self.line\n        step = 1 if not self.reverse else -1\n        add = builder.builder.int_add(builder.read(self.index_target, line), step)\n        builder.assign(self.index_target, add, line)\n\n\nclass ForDictionaryCommon(ForGenerator):\n    \"\"\"Generate optimized IR for a for loop over dictionary keys/values.\n\n    The logic is pretty straightforward, we use PyDict_Next() API wrapped in\n    a tuple, so that we can modify only a single register. The layout of the tuple:\n      * f0: are there more items (bool)\n      * f1: current offset (int)\n      * f2: next key (object)\n      * f3: next value (object)\n    For more info see https://docs.python.org/3/c-api/dict.html#c.PyDict_Next.\n\n    Note that for subclasses we fall back to generic PyObject_GetIter() logic,\n    since they may override some iteration methods in subtly incompatible manner.\n    The fallback logic is implemented in CPy.h via dynamic type check.\n    \"\"\"\n\n    dict_next_op: ClassVar[CFunctionDescription]\n    dict_iter_op: ClassVar[CFunctionDescription]\n\n    def need_cleanup(self) -> bool:\n        # Technically, a dict subclass can raise an unrelated exception\n        # in __next__(), so we need this.\n        return True\n\n    def init(self, expr_reg: Value, target_type: RType) -> None:\n        builder = self.builder\n        self.target_type = target_type\n\n        # We add some variables to environment class, so they can be read across yield.\n        self.expr_target = builder.maybe_spill(expr_reg)\n        offset = Integer(0)\n        self.offset_target = builder.maybe_spill_assignable(offset)\n        self.size = builder.maybe_spill(self.load_len(self.expr_target))\n\n        # For dict class (not a subclass) this is the dictionary itself.\n        iter_reg = builder.call_c(self.dict_iter_op, [expr_reg], self.line)\n        self.iter_target = builder.maybe_spill(iter_reg)\n\n    def gen_condition(self) -> None:\n        \"\"\"Get next key/value pair, set new offset, and check if we should continue.\"\"\"\n        builder = self.builder\n        line = self.line\n        self.next_tuple = self.builder.call_c(\n            self.dict_next_op,\n            [builder.read(self.iter_target, line), builder.read(self.offset_target, line)],\n            line,\n        )\n\n        # Do this here instead of in gen_step() to minimize variables in environment.\n        new_offset = builder.add(TupleGet(self.next_tuple, 1, line))\n        builder.assign(self.offset_target, new_offset, line)\n\n        should_continue = builder.add(TupleGet(self.next_tuple, 0, line))\n        builder.add(Branch(should_continue, self.body_block, self.loop_exit, Branch.BOOL))\n\n    def gen_step(self) -> None:\n        \"\"\"Check that dictionary didn't change size during iteration.\n\n        Raise RuntimeError if it is not the case to match CPython behavior.\n        \"\"\"\n        builder = self.builder\n        line = self.line\n        # Technically, we don't need a new primitive for this, but it is simpler.\n        builder.call_c(\n            dict_check_size_op,\n            [builder.read(self.expr_target, line), builder.read(self.size, line)],\n            line,\n        )\n\n    def gen_cleanup(self) -> None:\n        # Same as for generic ForIterable.\n        self.builder.call_c(no_err_occurred_op, [], self.line)\n\n\nclass ForDictionaryKeys(ForDictionaryCommon):\n    \"\"\"Generate optimized IR for a for loop over dictionary keys.\"\"\"\n\n    dict_next_op = dict_next_key_op\n    dict_iter_op = dict_key_iter_op\n\n    def begin_body(self) -> None:\n        builder = self.builder\n        line = self.line\n\n        # Key is stored at the third place in the tuple.\n        key = builder.add(TupleGet(self.next_tuple, 2, line))\n        builder.assign(\n            builder.get_assignment_target(self.index),\n            builder.coerce(key, self.target_type, line),\n            line,\n        )\n\n\nclass ForDictionaryValues(ForDictionaryCommon):\n    \"\"\"Generate optimized IR for a for loop over dictionary values.\"\"\"\n\n    dict_next_op = dict_next_value_op\n    dict_iter_op = dict_value_iter_op\n\n    def begin_body(self) -> None:\n        builder = self.builder\n        line = self.line\n\n        # Value is stored at the third place in the tuple.\n        value = builder.add(TupleGet(self.next_tuple, 2, line))\n        builder.assign(\n            builder.get_assignment_target(self.index),\n            builder.coerce(value, self.target_type, line),\n            line,\n        )\n\n\nclass ForDictionaryItems(ForDictionaryCommon):\n    \"\"\"Generate optimized IR for a for loop over dictionary items.\"\"\"\n\n    dict_next_op = dict_next_item_op\n    dict_iter_op = dict_item_iter_op\n\n    def begin_body(self) -> None:\n        builder = self.builder\n        line = self.line\n\n        key = builder.add(TupleGet(self.next_tuple, 2, line))\n        value = builder.add(TupleGet(self.next_tuple, 3, line))\n\n        # Coerce just in case e.g. key is itself a tuple to be unpacked.\n        assert isinstance(self.target_type, RTuple), self.target_type\n        key = builder.coerce(key, self.target_type.types[0], line)\n        value = builder.coerce(value, self.target_type.types[1], line)\n\n        target = builder.get_assignment_target(self.index)\n        if isinstance(target, AssignmentTargetTuple):\n            # Simpler code for common case: for k, v in d.items().\n            if len(target.items) != 2:\n                builder.error(\"Expected a pair for dict item iteration\", line)\n            builder.assign(target.items[0], key, line)\n            builder.assign(target.items[1], value, line)\n        else:\n            rvalue = builder.add(TupleSet([key, value], line))\n            builder.assign(target, rvalue, line)\n\n\nclass ForRange(ForGenerator):\n    \"\"\"Generate optimized IR for a for loop over an integer range.\"\"\"\n\n    def init(self, start_reg: Value, end_reg: Value, step: int) -> None:\n        builder = self.builder\n        self.start_reg = start_reg\n        self.end_reg = end_reg\n        self.step = step\n        self.end_target = builder.maybe_spill(end_reg)\n        if is_short_int_rprimitive(start_reg.type) and is_short_int_rprimitive(end_reg.type):\n            index_type: RType = short_int_rprimitive\n        elif is_fixed_width_rtype(end_reg.type):\n            index_type = end_reg.type\n        else:\n            index_type = int_rprimitive\n        index_reg = Register(index_type, line=self.line)\n        builder.assign(index_reg, start_reg, self.line)\n        self.index_reg = builder.maybe_spill_assignable(index_reg)\n        # Initialize loop index to 0. Assert that the index target is assignable.\n        self.index_target: Register | AssignmentTarget = builder.get_assignment_target(self.index)\n        builder.assign(self.index_target, builder.read(self.index_reg, self.line), self.line)\n\n    def gen_condition(self) -> None:\n        builder = self.builder\n        line = self.line\n        # Add loop condition check.\n        cmp = \"<\" if self.step > 0 else \">\"\n        comparison = builder.binary_op(\n            builder.read(self.index_reg, line), builder.read(self.end_target, line), cmp, line\n        )\n        builder.add_bool_branch(comparison, self.body_block, self.loop_exit)\n\n    def gen_step(self) -> None:\n        builder = self.builder\n        line = self.line\n\n        # Increment index register. If the range is known to fit in short ints, use\n        # short ints.\n        if is_short_int_rprimitive(self.start_reg.type) and is_short_int_rprimitive(\n            self.end_reg.type\n        ):\n            new_val = builder.int_op(\n                short_int_rprimitive,\n                builder.read(self.index_reg, line),\n                Integer(self.step),\n                IntOp.ADD,\n                line,\n            )\n\n        else:\n            new_val = builder.binary_op(\n                builder.read(self.index_reg, line), Integer(self.step), \"+\", line\n            )\n        builder.assign(self.index_reg, new_val, line)\n        builder.assign(self.index_target, new_val, line)\n\n\nclass ForInfiniteCounter(ForGenerator):\n    \"\"\"Generate optimized IR for a for loop counting from 0 to infinity.\"\"\"\n\n    def init(self) -> None:\n        builder = self.builder\n        # Create a register to store the state of the loop index and\n        # initialize this register along with the loop index to 0.\n        zero = Integer(0)\n        self.index_reg = builder.maybe_spill_assignable(zero)\n        self.index_target: Register | AssignmentTarget = builder.get_assignment_target(self.index)\n\n    def gen_step(self) -> None:\n        builder = self.builder\n        line = self.line\n        # We can safely assume that the integer is short, since we are not going to wrap\n        # around a 63-bit integer.\n        # NOTE: This would be questionable if short ints could be 32 bits.\n        new_val = builder.int_op(\n            short_int_rprimitive, builder.read(self.index_reg, line), Integer(1), IntOp.ADD, line\n        )\n        builder.assign(self.index_reg, new_val, line)\n\n    def begin_body(self) -> None:\n        self.builder.assign(\n            self.index_target, self.builder.read(self.index_reg, self.line), self.line\n        )\n\n\nclass ForEnumerate(ForGenerator):\n    \"\"\"Generate optimized IR for a for loop of form \"for i, x in enumerate(it)\".\"\"\"\n\n    def need_cleanup(self) -> bool:\n        # The wrapped for loop might need cleanup. This might generate a\n        # redundant cleanup block, but that's okay.\n        return True\n\n    def init(self, index1: Lvalue, index2: Lvalue, expr: Expression) -> None:\n        # Count from 0 to infinity (for the index lvalue).\n        self.index_gen = ForInfiniteCounter(\n            self.builder, index1, self.body_block, self.loop_exit, self.line, nested=True\n        )\n        self.index_gen.init()\n        # Iterate over the actual iterable.\n        self.main_gen = make_for_loop_generator(\n            self.builder, index2, expr, self.body_block, self.loop_exit, self.line, nested=True\n        )\n\n    def gen_condition(self) -> None:\n        # No need for a check for the index generator, since it's unconditional.\n        self.main_gen.gen_condition()\n\n    def begin_body(self) -> None:\n        self.index_gen.begin_body()\n        self.main_gen.begin_body()\n\n    def gen_step(self) -> None:\n        self.index_gen.gen_step()\n        self.main_gen.gen_step()\n\n    def gen_cleanup(self) -> None:\n        self.index_gen.gen_cleanup()\n        self.main_gen.gen_cleanup()\n\n\nclass ForZip(ForGenerator):\n    \"\"\"Generate IR for a for loop of form `for x, ... in zip(a, ...)`.\"\"\"\n\n    def need_cleanup(self) -> bool:\n        # The wrapped for loops might need cleanup. We might generate a\n        # redundant cleanup block, but that's okay.\n        return True\n\n    def init(self, indexes: list[Lvalue], exprs: list[Expression]) -> None:\n        assert len(indexes) == len(exprs)\n        # Condition check will require multiple basic blocks, since there will be\n        # multiple conditions to check.\n        self.cond_blocks = [BasicBlock() for _ in range(len(indexes) - 1)] + [self.body_block]\n        self.gens: list[ForGenerator] = []\n        for index, expr, next_block in zip(indexes, exprs, self.cond_blocks):\n            gen = make_for_loop_generator(\n                self.builder, index, expr, next_block, self.loop_exit, self.line, nested=True\n            )\n            self.gens.append(gen)\n\n    def gen_condition(self) -> None:\n        for i, gen in enumerate(self.gens):\n            gen.gen_condition()\n            if i < len(self.gens) - 1:\n                self.builder.activate_block(self.cond_blocks[i])\n\n    def begin_body(self) -> None:\n        for gen in self.gens:\n            gen.begin_body()\n\n    def gen_step(self) -> None:\n        for gen in self.gens:\n            gen.gen_step()\n\n    def gen_cleanup(self) -> None:\n        for gen in self.gens:\n            gen.gen_cleanup()\n\n\ndef get_expr_length(builder: IRBuilder, expr: Expression) -> int | None:\n    folded = constant_fold_expr(builder, expr)\n    if isinstance(folded, (str, bytes)):\n        return len(folded)\n    elif isinstance(expr, (ListExpr, TupleExpr)):\n        # if there are no star expressions, or we know the length of them,\n        # we know the length of the expression\n        stars = [get_expr_length(builder, i) for i in expr.items if isinstance(i, StarExpr)]\n        if None not in stars:\n            other = sum(not isinstance(i, StarExpr) for i in expr.items)\n            return other + sum(stars)  # type: ignore [arg-type]\n    elif isinstance(expr, StarExpr):\n        return get_expr_length(builder, expr.expr)\n    elif (\n        isinstance(expr, RefExpr)\n        and isinstance(expr.node, Var)\n        and expr.node.is_final\n        and isinstance(expr.node.final_value, str)\n        and expr.node.has_explicit_value\n    ):\n        return len(expr.node.final_value)\n    elif (\n        isinstance(expr, CallExpr)\n        and isinstance(callee := expr.callee, NameExpr)\n        and all(kind == ARG_POS for kind in expr.arg_kinds)\n    ):\n        fullname = callee.fullname\n        if (\n            fullname\n            in (\n                \"builtins.list\",\n                \"builtins.tuple\",\n                \"builtins.enumerate\",\n                \"builtins.sorted\",\n                \"builtins.reversed\",\n            )\n            and len(expr.args) == 1\n        ):\n            return get_expr_length(builder, expr.args[0])\n        elif fullname == \"builtins.map\" and len(expr.args) == 2:\n            return get_expr_length(builder, expr.args[1])\n        elif fullname == \"builtins.zip\" and expr.args:\n            arg_lengths = [get_expr_length(builder, arg) for arg in expr.args]\n            if all(arg is not None for arg in arg_lengths):\n                return min(arg_lengths)  # type: ignore [type-var]\n        elif fullname == \"builtins.range\" and len(expr.args) <= 3:\n            folded_args = [constant_fold_expr(builder, arg) for arg in expr.args]\n            if all(isinstance(arg, int) for arg in folded_args):\n                try:\n                    return len(range(*cast(list[int], folded_args)))\n                except ValueError:  # prevent crash if invalid args\n                    pass\n\n    # TODO: extend this, passing length of listcomp and genexp should have worthwhile\n    # performance boost and can be (sometimes) figured out pretty easily. set and dict\n    # comps *can* be done as well but will need special logic to consider the possibility\n    # of key conflicts.\n\n    # we might still be able to get the length directly from the type\n    rtype = builder.node_type(expr)\n    if isinstance(rtype, RTuple):\n        return len(rtype.types)\n    return None\n\n\ndef get_expr_length_value(\n    builder: IRBuilder, expr: Expression, expr_reg: Value, line: int, use_pyssize_t: bool\n) -> Value:\n    rtype = builder.node_type(expr)\n    assert is_sequence_rprimitive(rtype) or isinstance(rtype, (RTuple, RVec)), rtype\n    length = get_expr_length(builder, expr)\n    if length is None:\n        # We cannot compute the length at compile time, so we will fetch it.\n        return builder.builder.builtin_len(expr_reg, line, use_pyssize_t=use_pyssize_t)\n    # The expression result is known at compile time, so we can use a constant.\n    return Integer(length, c_pyssize_t_rprimitive if use_pyssize_t else short_int_rprimitive)\n"
  },
  {
    "path": "mypyc/irbuild/format_str_tokenizer.py",
    "content": "\"\"\"Tokenizers for three string formatting methods\"\"\"\n\nfrom __future__ import annotations\n\nfrom enum import Enum, unique\nfrom typing import Final\n\nfrom mypy.checkstrformat import (\n    ConversionSpecifier,\n    parse_conversion_specifiers,\n    parse_format_value,\n)\nfrom mypy.errors import Errors\nfrom mypy.messages import MessageBuilder\nfrom mypy.nodes import Context, Expression\nfrom mypy.options import Options\nfrom mypyc.ir.ops import Integer, Value\nfrom mypyc.ir.rtypes import (\n    c_pyssize_t_rprimitive,\n    is_bytes_rprimitive,\n    is_int_rprimitive,\n    is_short_int_rprimitive,\n    is_str_rprimitive,\n)\nfrom mypyc.irbuild.builder import IRBuilder\nfrom mypyc.irbuild.constant_fold import constant_fold_expr\nfrom mypyc.primitives.bytes_ops import bytes_build_op\nfrom mypyc.primitives.int_ops import int_to_ascii_op, int_to_str_op\nfrom mypyc.primitives.str_ops import str_build_op, str_op\n\n\n@unique\nclass FormatOp(Enum):\n    \"\"\"FormatOp represents conversion operations of string formatting during\n    compile time.\n\n    Compare to ConversionSpecifier, FormatOp has fewer attributes.\n    For example, to mark a conversion from any object to string,\n    ConversionSpecifier may have several representations, like '%s', '{}'\n    or '{:{}}'. However, there would only exist one corresponding FormatOp.\n    \"\"\"\n\n    STR = \"s\"\n    INT = \"d\"\n    BYTES = \"b\"\n\n\ndef generate_format_ops(specifiers: list[ConversionSpecifier]) -> list[FormatOp] | None:\n    \"\"\"Convert ConversionSpecifier to FormatOp.\n\n    Different ConversionSpecifiers may share a same FormatOp.\n    \"\"\"\n    format_ops = []\n    for spec in specifiers:\n        # TODO: Match specifiers instead of using whole_seq\n        if spec.whole_seq == \"%s\" or spec.whole_seq == \"{:{}}\":\n            format_op = FormatOp.STR\n        elif spec.whole_seq == \"%d\":\n            format_op = FormatOp.INT\n        elif spec.whole_seq == \"%b\":\n            format_op = FormatOp.BYTES\n        elif spec.whole_seq:\n            return None\n        else:\n            format_op = FormatOp.STR\n        format_ops.append(format_op)\n    return format_ops\n\n\ndef tokenizer_printf_style(format_str: str) -> tuple[list[str], list[FormatOp]] | None:\n    \"\"\"Tokenize a printf-style format string using regex.\n\n    Return:\n        A list of string literals and a list of FormatOps.\n    \"\"\"\n    literals: list[str] = []\n    specifiers: list[ConversionSpecifier] = parse_conversion_specifiers(format_str)\n    format_ops = generate_format_ops(specifiers)\n    if format_ops is None:\n        return None\n\n    last_end = 0\n    for spec in specifiers:\n        cur_start = spec.start_pos\n        literals.append(format_str[last_end:cur_start])\n        last_end = cur_start + len(spec.whole_seq)\n    literals.append(format_str[last_end:])\n\n    return literals, format_ops\n\n\n# The empty Context as an argument for parse_format_value().\n# It wouldn't be used since the code has passed the type-checking.\nEMPTY_CONTEXT: Final = Context()\n\n\ndef tokenizer_format_call(format_str: str) -> tuple[list[str], list[FormatOp]] | None:\n    \"\"\"Tokenize a str.format() format string.\n\n    The core function parse_format_value() is shared with mypy.\n    With these specifiers, we then parse the literal substrings\n    of the original format string and convert `ConversionSpecifier`\n    to `FormatOp`.\n\n    Return:\n        A list of string literals and a list of FormatOps. The literals\n        are interleaved with FormatOps and the length of returned literals\n        should be exactly one more than FormatOps.\n        Return None if it cannot parse the string.\n    \"\"\"\n    # Creates an empty MessageBuilder here.\n    # It wouldn't be used since the code has passed the type-checking.\n    specifiers = parse_format_value(\n        format_str, EMPTY_CONTEXT, MessageBuilder(Errors(Options()), {})\n    )\n    if specifiers is None:\n        return None\n    format_ops = generate_format_ops(specifiers)\n    if format_ops is None:\n        return None\n\n    literals: list[str] = []\n    last_end = 0\n    for spec in specifiers:\n        # Skip { and }\n        literals.append(format_str[last_end : spec.start_pos - 1])\n        last_end = spec.start_pos + len(spec.whole_seq) + 1\n    literals.append(format_str[last_end:])\n    # Deal with escaped {{\n    literals = [x.replace(\"{{\", \"{\").replace(\"}}\", \"}\") for x in literals]\n\n    return literals, format_ops\n\n\ndef convert_format_expr_to_str(\n    builder: IRBuilder, format_ops: list[FormatOp], exprs: list[Expression], line: int\n) -> list[Value] | None:\n    \"\"\"Convert expressions into string literal objects with the guidance\n    of FormatOps. Return None when fails.\"\"\"\n    if len(format_ops) != len(exprs):\n        return None\n\n    converted = []\n    for x, format_op in zip(exprs, format_ops):\n        node_type = builder.node_type(x)\n        if format_op == FormatOp.STR:\n            if isinstance(folded := constant_fold_expr(builder, x), str):\n                var_str = builder.load_literal_value(folded)\n            elif is_str_rprimitive(node_type):\n                var_str = builder.accept(x)\n            elif is_int_rprimitive(node_type) or is_short_int_rprimitive(node_type):\n                var_str = builder.primitive_op(int_to_str_op, [builder.accept(x)], line)\n            else:\n                var_str = builder.primitive_op(str_op, [builder.accept(x)], line)\n        elif format_op == FormatOp.INT:\n            if isinstance(folded := constant_fold_expr(builder, x), int):\n                var_str = builder.load_literal_value(str(folded))\n            elif is_int_rprimitive(node_type) or is_short_int_rprimitive(node_type):\n                var_str = builder.primitive_op(int_to_str_op, [builder.accept(x)], line)\n            else:\n                return None\n        else:\n            return None\n        converted.append(var_str)\n    return converted\n\n\ndef join_formatted_strings(\n    builder: IRBuilder, literals: list[str] | None, substitutions: list[Value], line: int\n) -> Value:\n    \"\"\"Merge the list of literals and the list of substitutions\n    alternatively using 'str_build_op'.\n\n    `substitutions` is the result value of formatting conversions.\n\n    If the `literals` is set to None, we simply join the substitutions;\n    Otherwise, the `literals` is the literal substrings of the original\n    format string and its length should be exactly one more than\n    substitutions.\n\n    For example:\n    (1)    'This is a %s and the value is %d'\n        -> literals: ['This is a ', ' and the value is', '']\n    (2)    '{} and the value is {}'\n        -> literals: ['', ' and the value is', '']\n    \"\"\"\n    # The first parameter for str_build_op is the total size of\n    # the following PyObject*\n    result_list: list[Value] = [Integer(0, c_pyssize_t_rprimitive)]\n\n    if literals is not None:\n        for a, b in zip(literals, substitutions):\n            if a:\n                result_list.append(builder.load_str(a))\n            result_list.append(b)\n        if literals[-1]:\n            result_list.append(builder.load_str(literals[-1]))\n    else:\n        result_list.extend(substitutions)\n\n    # Special case for empty string and literal string\n    if len(result_list) == 1:\n        return builder.load_str(\"\")\n    if not substitutions and len(result_list) == 2:\n        return result_list[1]\n\n    result_list[0] = Integer(len(result_list) - 1, c_pyssize_t_rprimitive)\n    return builder.call_c(str_build_op, result_list, line)\n\n\ndef convert_format_expr_to_bytes(\n    builder: IRBuilder, format_ops: list[FormatOp], exprs: list[Expression], line: int\n) -> list[Value] | None:\n    \"\"\"Convert expressions into bytes literal objects with the guidance\n    of FormatOps. Return None when fails.\"\"\"\n    if len(format_ops) != len(exprs):\n        return None\n\n    converted = []\n    for x, format_op in zip(exprs, format_ops):\n        node_type = builder.node_type(x)\n        # conversion type 's' is an alias of 'b' in bytes formatting\n        if format_op == FormatOp.BYTES or format_op == FormatOp.STR:\n            if is_bytes_rprimitive(node_type):\n                var_bytes = builder.accept(x)\n            else:\n                return None\n        elif format_op == FormatOp.INT:\n            if isinstance(folded := constant_fold_expr(builder, x), int):\n                var_bytes = builder.load_literal_value(str(folded).encode(\"ascii\"))\n            elif is_int_rprimitive(node_type) or is_short_int_rprimitive(node_type):\n                var_bytes = builder.call_c(int_to_ascii_op, [builder.accept(x)], line)\n            else:\n                return None\n        converted.append(var_bytes)\n    return converted\n\n\ndef join_formatted_bytes(\n    builder: IRBuilder, literals: list[str], substitutions: list[Value], line: int\n) -> Value:\n    \"\"\"Merge the list of literals and the list of substitutions\n    alternatively using 'bytes_build_op'.\"\"\"\n    result_list: list[Value] = [Integer(0, c_pyssize_t_rprimitive)]\n\n    for a, b in zip(literals, substitutions):\n        if a:\n            result_list.append(builder.load_bytes_from_str_literal(a))\n        result_list.append(b)\n    if literals[-1]:\n        result_list.append(builder.load_bytes_from_str_literal(literals[-1]))\n\n    # Special case for empty bytes and literal\n    if len(result_list) == 1:\n        return builder.load_bytes_from_str_literal(\"\")\n    if not substitutions and len(result_list) == 2:\n        return result_list[1]\n\n    result_list[0] = Integer(len(result_list) - 1, c_pyssize_t_rprimitive)\n    return builder.call_c(bytes_build_op, result_list, line)\n"
  },
  {
    "path": "mypyc/irbuild/function.py",
    "content": "\"\"\"Transform mypy AST functions to IR (and related things).\n\nNormal functions are translated into a list of basic blocks\ncontaining various IR ops (defined in mypyc.ir.ops).\n\nThis also deals with generators, async functions and nested\nfunctions. All of these are transformed into callable classes. These\nhave a custom __call__ method that implements the call, and state, such\nas an environment containing non-local variables, is stored in the\ninstance of the callable class.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom collections.abc import Sequence\nfrom typing import NamedTuple\n\nfrom mypy.nodes import (\n    ArgKind,\n    ClassDef,\n    Decorator,\n    FuncBase,\n    FuncDef,\n    FuncItem,\n    LambdaExpr,\n    OverloadedFuncDef,\n    TypeInfo,\n    Var,\n)\nfrom mypy.types import CallableType, Type, UnboundType, get_proper_type\nfrom mypyc.common import FAST_PREFIX, LAMBDA_NAME, PROPSET_PREFIX, SELF_NAME\nfrom mypyc.ir.class_ir import ClassIR, NonExtClassInfo\nfrom mypyc.ir.func_ir import (\n    FUNC_CLASSMETHOD,\n    FUNC_NORMAL,\n    FUNC_STATICMETHOD,\n    FuncDecl,\n    FuncIR,\n    FuncSignature,\n    RuntimeArg,\n)\nfrom mypyc.ir.ops import (\n    BasicBlock,\n    ComparisonOp,\n    GetAttr,\n    Integer,\n    LoadAddress,\n    LoadLiteral,\n    Register,\n    Return,\n    SetAttr,\n    Unbox,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    bool_rprimitive,\n    c_int_rprimitive,\n    dict_rprimitive,\n    int_rprimitive,\n    object_rprimitive,\n)\nfrom mypyc.irbuild.builder import IRBuilder, calculate_arg_defaults, gen_arg_defaults\nfrom mypyc.irbuild.callable_class import (\n    add_call_to_callable_class,\n    add_get_to_callable_class,\n    instantiate_callable_class,\n    setup_callable_class,\n)\nfrom mypyc.irbuild.context import FuncInfo, GeneratorClass\nfrom mypyc.irbuild.env_class import (\n    add_vars_to_env,\n    finalize_env_class,\n    load_env_registers,\n    setup_env_class,\n)\nfrom mypyc.irbuild.generator import gen_generator_func, gen_generator_func_body\nfrom mypyc.irbuild.targets import AssignmentTarget\nfrom mypyc.primitives.dict_ops import (\n    dict_get_method_with_none,\n    dict_new_op,\n    exact_dict_set_item_op,\n)\nfrom mypyc.primitives.generic_ops import generic_getattr, generic_setattr, py_setattr_op\nfrom mypyc.primitives.misc_ops import register_function\nfrom mypyc.primitives.registry import builtin_names\nfrom mypyc.sametype import is_same_method_signature, is_same_type\n\n# Top-level transform functions\n\n\ndef transform_func_def(builder: IRBuilder, fdef: FuncDef) -> None:\n    sig = builder.mapper.fdef_to_sig(fdef, builder.options.strict_dunders_typing)\n    func_ir, func_reg = gen_func_item(builder, fdef, fdef.name, sig)\n\n    # If the function that was visited was a nested function, then either look it up in our\n    # current environment or define it if it was not already defined.\n    if func_reg:\n        builder.assign(get_func_target(builder, fdef), func_reg, fdef.line)\n    maybe_insert_into_registry_dict(builder, fdef)\n    builder.add_function(func_ir, fdef.line)\n\n\ndef transform_overloaded_func_def(builder: IRBuilder, o: OverloadedFuncDef) -> None:\n    # Handle regular overload case\n    assert o.impl\n    builder.accept(o.impl)\n\n\ndef transform_decorator(builder: IRBuilder, dec: Decorator) -> None:\n    sig = builder.mapper.fdef_to_sig(dec.func, builder.options.strict_dunders_typing)\n    func_ir, func_reg = gen_func_item(builder, dec.func, dec.func.name, sig)\n    decorated_func: Value | None = None\n    if func_reg:\n        decorated_func = load_decorated_func(builder, dec.func, func_reg)\n        builder.assign(get_func_target(builder, dec.func), decorated_func, dec.func.line)\n    # If the prebuild pass didn't put this function in the function to decorators map (for example\n    # if this is a registered singledispatch implementation with no other decorators), we should\n    # treat this function as a regular function, not a decorated function\n    elif dec.func in builder.fdefs_to_decorators:\n        # Obtain the function name in order to construct the name of the helper function.\n        name = dec.func.fullname.split(\".\")[-1]\n\n        # Load the callable object representing the non-decorated function, and decorate it.\n        orig_func = builder.load_global_str(name, dec.line)\n        decorated_func = load_decorated_func(builder, dec.func, orig_func)\n\n    if decorated_func is not None:\n        # Set the callable object representing the decorated function as a global.\n        builder.call_c(\n            exact_dict_set_item_op,\n            [builder.load_globals_dict(), builder.load_str(dec.func.name), decorated_func],\n            decorated_func.line,\n        )\n\n    maybe_insert_into_registry_dict(builder, dec.func)\n\n    builder.functions.append(func_ir)\n\n\ndef transform_lambda_expr(builder: IRBuilder, expr: LambdaExpr) -> Value:\n    typ = get_proper_type(builder.types[expr])\n    assert isinstance(typ, CallableType), typ\n\n    runtime_args = []\n    for arg, arg_type in zip(expr.arguments, typ.arg_types):\n        arg.variable.type = arg_type\n        runtime_args.append(\n            RuntimeArg(arg.variable.name, builder.type_to_rtype(arg_type), arg.kind)\n        )\n    ret_type = builder.type_to_rtype(typ.ret_type)\n\n    fsig = FuncSignature(runtime_args, ret_type)\n\n    fname = f\"{LAMBDA_NAME}{builder.lambda_counter}\"\n    builder.lambda_counter += 1\n    func_ir, func_reg = gen_func_item(builder, expr, fname, fsig)\n    assert func_reg is not None\n\n    builder.functions.append(func_ir)\n    return func_reg\n\n\n# Internal functions\n\n\ndef gen_func_item(\n    builder: IRBuilder,\n    fitem: FuncItem,\n    name: str,\n    sig: FuncSignature,\n    cdef: ClassDef | None = None,\n    make_ext_method: bool = False,\n) -> tuple[FuncIR, Value | None]:\n    \"\"\"Generate and return the FuncIR for a given FuncDef.\n\n    If the given FuncItem is a nested function, then we generate a\n    callable class representing the function and use that instead of\n    the actual function. if the given FuncItem contains a nested\n    function, then we generate an environment class so that inner\n    nested functions can access the environment of the given FuncDef.\n\n    Consider the following nested function:\n\n        def a() -> None:\n            def b() -> None:\n                def c() -> None:\n                    return None\n                return None\n            return None\n\n    The classes generated would look something like the following.\n\n                has pointer to        +-------+\n        +-------------------------->  | a_env |\n        |                             +-------+\n        |                                 ^\n        |                                 | has pointer to\n    +-------+     associated with     +-------+\n    | b_obj |   ------------------->  | b_env |\n    +-------+                         +-------+\n                                          ^\n                                          |\n    +-------+         has pointer to      |\n    | c_obj |   --------------------------+\n    +-------+\n    \"\"\"\n\n    # TODO: do something about abstract methods.\n\n    func_reg: Value | None = None\n\n    # We treat lambdas as always being nested because we always generate\n    # a class for lambdas, no matter where they are. (It would probably also\n    # work to special case toplevel lambdas and generate a non-class function.)\n    is_nested = fitem in builder.nested_fitems or isinstance(fitem, LambdaExpr)\n    contains_nested = fitem in builder.encapsulating_funcs.keys()\n    is_decorated = fitem in builder.fdefs_to_decorators\n    is_singledispatch = fitem in builder.singledispatch_impls\n    in_non_ext = False\n    add_nested_funcs_to_env = has_nested_func_self_reference(builder, fitem)\n    class_name = None\n    if cdef:\n        ir = builder.mapper.type_to_ir[cdef.info]\n        in_non_ext = not ir.is_ext_class and not make_ext_method\n        class_name = cdef.name\n\n    if is_singledispatch:\n        func_name = singledispatch_main_func_name(name)\n    else:\n        func_name = name\n\n    fn_info = FuncInfo(\n        fitem=fitem,\n        name=func_name,\n        class_name=class_name,\n        namespace=gen_func_ns(builder),\n        is_nested=is_nested,\n        contains_nested=contains_nested,\n        is_decorated=is_decorated,\n        in_non_ext=in_non_ext,\n        add_nested_funcs_to_env=add_nested_funcs_to_env,\n    )\n    is_generator = fn_info.is_generator\n    builder.enter(fn_info, ret_type=sig.ret_type)\n\n    if is_generator:\n        fitem = builder.fn_info.fitem\n        assert isinstance(fitem, FuncDef), fitem\n        generator_class_ir = builder.mapper.fdef_to_generator[fitem]\n        builder.fn_info.generator_class = GeneratorClass(generator_class_ir)\n\n    # Functions that contain nested functions need an environment class to store variables that\n    # are free in their nested functions. Generator functions need an environment class to\n    # store a variable denoting the next instruction to be executed when the __next__ function\n    # is called, along with all the variables inside the function itself.\n    if contains_nested or (\n        is_generator and not builder.fn_info.can_merge_generator_and_env_classes()\n    ):\n        setup_env_class(builder)\n\n    if is_nested or in_non_ext:\n        setup_callable_class(builder)\n\n    if is_generator:\n        # First generate a function that just constructs and returns a generator object.\n        func_ir, func_reg = gen_generator_func(\n            builder,\n            lambda args, blocks, fn_info: gen_func_ir(\n                builder, args, blocks, sig, fn_info, cdef, is_singledispatch\n            ),\n        )\n\n        # Re-enter the FuncItem and visit the body of the function this time.\n        gen_generator_func_body(builder, fn_info, func_reg)\n    else:\n        func_ir, func_reg = gen_func_body(builder, sig, cdef, is_singledispatch)\n\n    if is_singledispatch:\n        # add the generated main singledispatch function\n        builder.functions.append(func_ir)\n        # create the dispatch function\n        assert isinstance(fitem, FuncDef), fitem\n        return gen_dispatch_func_ir(builder, fitem, fn_info.name, name, sig)\n\n    return func_ir, func_reg\n\n\ndef gen_func_body(\n    builder: IRBuilder, sig: FuncSignature, cdef: ClassDef | None, is_singledispatch: bool\n) -> tuple[FuncIR, Value | None]:\n    load_env_registers(builder)\n    gen_arg_defaults(builder)\n    if builder.fn_info.contains_nested:\n        finalize_env_class(builder)\n    add_vars_to_env(builder)\n    builder.accept(builder.fn_info.fitem.body)\n    builder.maybe_add_implicit_return()\n\n    # Hang on to the local symbol table for a while, since we use it\n    # to calculate argument defaults below.\n    symtable = builder.symtables[-1]\n\n    args, _, blocks, ret_type, fn_info = builder.leave()\n\n    func_ir, func_reg = gen_func_ir(builder, args, blocks, sig, fn_info, cdef, is_singledispatch)\n\n    # Evaluate argument defaults in the surrounding scope, since we\n    # calculate them *once* when the function definition is evaluated.\n    calculate_arg_defaults(builder, fn_info, func_reg, symtable)\n    return func_ir, func_reg\n\n\ndef has_nested_func_self_reference(builder: IRBuilder, fitem: FuncItem) -> bool:\n    \"\"\"Does a nested function contain a self-reference in its body?\n\n    If a nested function only has references in the surrounding function,\n    we don't need to add it to the environment.\n    \"\"\"\n    if any(isinstance(sym, FuncBase) for sym in builder.free_variables.get(fitem, set())):\n        return True\n    return any(\n        has_nested_func_self_reference(builder, nested)\n        for nested in builder.encapsulating_funcs.get(fitem, [])\n    )\n\n\ndef gen_func_ir(\n    builder: IRBuilder,\n    args: list[Register],\n    blocks: list[BasicBlock],\n    sig: FuncSignature,\n    fn_info: FuncInfo,\n    cdef: ClassDef | None,\n    is_singledispatch_main_func: bool = False,\n) -> tuple[FuncIR, Value | None]:\n    \"\"\"Generate the FuncIR for a function.\n\n    This takes the basic blocks and function info of a particular\n    function and returns the IR. If the function is nested,\n    also returns the register containing the instance of the\n    corresponding callable class.\n    \"\"\"\n    func_reg: Value | None = None\n    if fn_info.is_nested or fn_info.in_non_ext:\n        func_ir = add_call_to_callable_class(builder, args, blocks, sig, fn_info)\n        add_get_to_callable_class(builder, fn_info)\n        func_reg = instantiate_callable_class(builder, fn_info)\n    else:\n        fitem = fn_info.fitem\n        assert isinstance(fitem, FuncDef), fitem\n        func_decl = builder.mapper.func_to_decl[fitem]\n        if cdef and fn_info.name == FAST_PREFIX + func_decl.name:\n            # Special-cased version of a method has a separate FuncDecl, use that one.\n            func_decl = builder.mapper.type_to_ir[cdef.info].method_decls[fn_info.name]\n        if fn_info.is_decorated or is_singledispatch_main_func:\n            class_name = None if cdef is None else cdef.name\n            func_decl = FuncDecl(\n                fn_info.name,\n                class_name,\n                builder.module_name,\n                sig,\n                func_decl.kind,\n                is_prop_getter=func_decl.is_prop_getter,\n                is_prop_setter=func_decl.is_prop_setter,\n                is_generator=func_decl.is_generator,\n                is_coroutine=func_decl.is_coroutine,\n                implicit=func_decl.implicit,\n                internal=func_decl.internal,\n            )\n            func_ir = FuncIR(func_decl, args, blocks, fitem.line, traceback_name=fitem.name)\n        else:\n            func_ir = FuncIR(func_decl, args, blocks, fitem.line, traceback_name=fitem.name)\n    return (func_ir, func_reg)\n\n\ndef generate_getattr_wrapper(builder: IRBuilder, cdef: ClassDef, getattr: FuncDef) -> None:\n    \"\"\"\n    Generate a wrapper function for __getattr__ that can be put into the tp_getattro slot.\n    The wrapper takes one argument besides self which is the attribute name.\n    It first checks if the name matches any of the attributes of this class.\n    If it does, it returns that attribute. If none match, it calls __getattr__.\n\n    __getattr__ is not supported in classes that allow interpreted subclasses because the\n    tp_getattro slot is inherited by subclasses and if the subclass overrides __getattr__,\n    the override would be ignored in our wrapper. TODO: To support this, the wrapper would\n    have to check type of self and if it's not the compiled class, resolve \"__getattr__\" against\n    the type at runtime and call the returned method, like _Py_slot_tp_getattr_hook in cpython.\n\n    __getattr__ is not supported in classes which inherit from non-native classes because those\n    have __dict__ which currently has some strange interactions when class attributes and\n    variables are assigned through __dict__ vs. through regular attribute access. Allowing\n    __getattr__ on top of that could be problematic.\n    \"\"\"\n    name = getattr.name + \"__wrapper\"\n    ir = builder.mapper.type_to_ir[cdef.info]\n    line = getattr.line\n\n    error_base = f'\"__getattr__\" not supported in class \"{cdef.name}\" because '\n    if ir.allow_interpreted_subclasses:\n        builder.error(error_base + \"it allows interpreted subclasses\", line)\n    if ir.inherits_python:\n        builder.error(error_base + \"it inherits from a non-native class\", line)\n\n    with builder.enter_method(ir, name, object_rprimitive, internal=True):\n        attr_arg = builder.add_argument(\"attr\", object_rprimitive)\n        generic_getattr_result = builder.call_c(generic_getattr, [builder.self(), attr_arg], line)\n\n        return_generic, call_getattr = BasicBlock(), BasicBlock()\n        null = Integer(0, object_rprimitive, line)\n        got_generic = builder.add(\n            ComparisonOp(generic_getattr_result, null, ComparisonOp.NEQ, line)\n        )\n        builder.add_bool_branch(got_generic, return_generic, call_getattr)\n\n        builder.activate_block(return_generic)\n        builder.add(Return(generic_getattr_result, line))\n\n        builder.activate_block(call_getattr)\n        # No attribute matched so call user-provided __getattr__.\n        getattr_result = builder.gen_method_call(\n            builder.self(), getattr.name, [attr_arg], object_rprimitive, line\n        )\n        builder.add(Return(getattr_result, line))\n\n\ndef generate_setattr_wrapper(builder: IRBuilder, cdef: ClassDef, setattr: FuncDef) -> None:\n    \"\"\"\n    Generate a wrapper function for __setattr__ that can be put into the tp_setattro slot.\n    The wrapper takes two arguments besides self - attribute name and the new value.\n    Returns 0 on success and -1 on failure. Restrictions are similar to the __getattr__\n    wrapper above.\n\n    The wrapper calls the user-defined __setattr__ when the value to set is not NULL.\n    When it's NULL, this means that the call to tp_setattro comes from a del statement,\n    so it calls __delattr__ instead. If __delattr__ is not overridden in the native class,\n    this will call the base implementation in object which doesn't work without __dict__.\n    \"\"\"\n    name = setattr.name + \"__wrapper\"\n    ir = builder.mapper.type_to_ir[cdef.info]\n    line = setattr.line\n\n    error_base = f'\"__setattr__\" not supported in class \"{cdef.name}\" because '\n    if ir.allow_interpreted_subclasses:\n        builder.error(error_base + \"it allows interpreted subclasses\", line)\n    if ir.inherits_python:\n        builder.error(error_base + \"it inherits from a non-native class\", line)\n\n    with builder.enter_method(ir, name, c_int_rprimitive, internal=True):\n        attr_arg = builder.add_argument(\"attr\", object_rprimitive)\n        value_arg = builder.add_argument(\"value\", object_rprimitive)\n\n        call_delattr, call_setattr = BasicBlock(), BasicBlock()\n        null = Integer(0, object_rprimitive, line)\n        is_delattr = builder.add(ComparisonOp(value_arg, null, ComparisonOp.EQ, line))\n        builder.add_bool_branch(is_delattr, call_delattr, call_setattr)\n\n        builder.activate_block(call_delattr)\n        delattr_symbol = cdef.info.get(\"__delattr__\")\n        delattr = delattr_symbol.node if delattr_symbol else None\n        delattr_override = delattr is not None and not delattr.fullname.startswith(\"builtins.\")\n        if delattr_override:\n            builder.gen_method_call(builder.self(), \"__delattr__\", [attr_arg], None, line)\n        else:\n            # Call internal function that cpython normally calls when deleting an attribute.\n            # Cannot call object.__delattr__ here because it calls PyObject_SetAttr internally\n            # which in turn calls our wrapper and recurses infinitely.\n            # Note that since native classes don't have __dict__, this will raise AttributeError\n            # for dynamic attributes.\n            builder.call_c(generic_setattr, [builder.self(), attr_arg, null], line)\n        builder.add(Return(Integer(0, c_int_rprimitive), line))\n\n        builder.activate_block(call_setattr)\n        builder.gen_method_call(builder.self(), setattr.name, [attr_arg, value_arg], None, line)\n        builder.add(Return(Integer(0, c_int_rprimitive), line))\n\n\ndef handle_ext_method(builder: IRBuilder, cdef: ClassDef, fdef: FuncDef) -> None:\n    # Perform the function of visit_method for methods inside extension classes.\n    name = fdef.name\n    class_ir = builder.mapper.type_to_ir[cdef.info]\n    sig = builder.mapper.fdef_to_sig(fdef, builder.options.strict_dunders_typing)\n    func_ir, func_reg = gen_func_item(builder, fdef, name, sig, cdef)\n    builder.functions.append(func_ir)\n\n    if is_decorated(builder, fdef):\n        # Obtain the function name in order to construct the name of the helper function.\n        _, _, name = fdef.fullname.rpartition(\".\")\n        # Read the PyTypeObject representing the class, get the callable object\n        # representing the non-decorated method\n        typ = builder.load_native_type_object(cdef.fullname)\n        orig_func = builder.py_get_attr(typ, name, fdef.line)\n\n        # Decorate the non-decorated method\n        decorated_func = load_decorated_func(builder, fdef, orig_func)\n\n        # Set the callable object representing the decorated method as an attribute of the\n        # extension class.\n        builder.primitive_op(\n            py_setattr_op, [typ, builder.load_str(name), decorated_func], fdef.line\n        )\n\n    if fdef.is_property:\n        # If there is a property setter, it will be processed after the getter,\n        # We populate the optional setter field with none for now.\n        assert name not in class_ir.properties\n        class_ir.properties[name] = (func_ir, None)\n\n    elif fdef in builder.prop_setters:\n        # The respective property getter must have been processed already\n        assert name in class_ir.properties\n        getter_ir, _ = class_ir.properties[name]\n        class_ir.properties[name] = (getter_ir, func_ir)\n\n    class_ir.methods[func_ir.decl.name] = func_ir\n\n    # If this overrides a parent class method with a different type, we need\n    # to generate a glue method to mediate between them.\n    for base in class_ir.mro[1:]:\n        if (\n            name in base.method_decls\n            and name != \"__init__\"\n            and not is_same_method_signature(\n                class_ir.method_decls[name].sig, base.method_decls[name].sig\n            )\n        ):\n            # TODO: Support contravariant subtyping in the input argument for\n            # property setters. Need to make a special glue method for handling this,\n            # similar to gen_glue_property.\n\n            f = gen_glue(builder, base.method_decls[name].sig, func_ir, class_ir, base, fdef)\n            class_ir.glue_methods[(base, name)] = f\n            builder.functions.append(f)\n\n    # If the class allows interpreted children, create glue\n    # methods that dispatch via the Python API. These will go in a\n    # \"shadow vtable\" that will be assigned to interpreted\n    # children.\n    if class_ir.allow_interpreted_subclasses:\n        f = gen_glue(builder, func_ir.sig, func_ir, class_ir, class_ir, fdef, do_py_ops=True)\n        # Use func_ir.decl.name (unique) rather than fdef.name, because for properties\n        # the getter and setter share the same fdef.name but have distinct decl names\n        # (e.g. \"prop\" vs \"__mypyc_setter__prop\"). Using fdef.name would cause the\n        # setter's glue to overwrite the getter's glue in the shadow vtable.\n        class_ir.glue_methods[(class_ir, func_ir.decl.name)] = f\n        builder.functions.append(f)\n\n    if fdef.name == \"__getattr__\":\n        generate_getattr_wrapper(builder, cdef, fdef)\n    elif fdef.name == \"__setattr__\":\n        generate_setattr_wrapper(builder, cdef, fdef)\n    elif fdef.name == \"__delattr__\":\n        setattr = cdef.info.get(\"__setattr__\")\n        if not setattr or not setattr.node or setattr.node.fullname.startswith(\"builtins.\"):\n            builder.error(\n                '\"__delattr__\" supported only in classes that also override \"__setattr__\", '\n                + \"or inherit from a native class that overrides it.\",\n                fdef.line,\n            )\n\n\ndef handle_non_ext_method(\n    builder: IRBuilder, non_ext: NonExtClassInfo, cdef: ClassDef, fdef: FuncDef\n) -> None:\n    # Perform the function of visit_method for methods inside non-extension classes.\n    name = fdef.name\n    sig = builder.mapper.fdef_to_sig(fdef, builder.options.strict_dunders_typing)\n    func_ir, func_reg = gen_func_item(builder, fdef, name, sig, cdef)\n    assert func_reg is not None\n    builder.functions.append(func_ir)\n\n    if is_decorated(builder, fdef):\n        # The undecorated method is a generated callable class\n        orig_func = func_reg\n        func_reg = load_decorated_func(builder, fdef, orig_func)\n\n    # TODO: Support property setters in non-extension classes\n    if fdef.is_property:\n        prop = builder.load_module_attr_by_fullname(\"builtins.property\", fdef.line)\n        func_reg = builder.py_call(prop, [func_reg], fdef.line)\n\n    elif builder.mapper.func_to_decl[fdef].kind == FUNC_CLASSMETHOD:\n        cls_meth = builder.load_module_attr_by_fullname(\"builtins.classmethod\", fdef.line)\n        func_reg = builder.py_call(cls_meth, [func_reg], fdef.line)\n\n    elif builder.mapper.func_to_decl[fdef].kind == FUNC_STATICMETHOD:\n        stat_meth = builder.load_module_attr_by_fullname(\"builtins.staticmethod\", fdef.line)\n        func_reg = builder.py_call(stat_meth, [func_reg], fdef.line)\n\n    builder.add_to_non_ext_dict(non_ext, name, func_reg, fdef.line)\n\n    # If we identified that this non-extension class method can be special-cased for\n    # direct access during prepare phase, generate a \"static\" version of it.\n    class_ir = builder.mapper.type_to_ir[cdef.info]\n    name = FAST_PREFIX + fdef.name\n    if name in class_ir.method_decls:\n        func_ir, func_reg = gen_func_item(builder, fdef, name, sig, cdef, make_ext_method=True)\n        class_ir.methods[name] = func_ir\n        builder.functions.append(func_ir)\n\n\ndef gen_func_ns(builder: IRBuilder) -> str:\n    \"\"\"Generate a namespace for a nested function using its outer function names.\"\"\"\n    return \"_\".join(\n        info.name + (\"\" if not info.class_name else \"_\" + info.class_name)\n        for info in builder.fn_infos\n        if info.name and info.name != \"<module>\"\n    )\n\n\ndef load_decorated_func(builder: IRBuilder, fdef: FuncDef, orig_func_reg: Value) -> Value:\n    \"\"\"Apply decorators to a function.\n\n    Given a decorated FuncDef and an instance of the callable class\n    representing that FuncDef, apply the corresponding decorator\n    functions on that decorated FuncDef and return the decorated\n    function.\n    \"\"\"\n    if not is_decorated(builder, fdef):\n        # If there are no decorators associated with the function, then just return the\n        # original function.\n        return orig_func_reg\n\n    decorators = builder.fdefs_to_decorators[fdef]\n    func_reg = orig_func_reg\n    for d in reversed(decorators):\n        decorator = d.accept(builder.visitor)\n        assert isinstance(decorator, Value), decorator\n        func_reg = builder.py_call(decorator, [func_reg], func_reg.line)\n    return func_reg\n\n\ndef is_decorated(builder: IRBuilder, fdef: FuncDef) -> bool:\n    return fdef in builder.fdefs_to_decorators\n\n\ndef gen_glue(\n    builder: IRBuilder,\n    base_sig: FuncSignature,\n    target: FuncIR,\n    cls: ClassIR,\n    base: ClassIR,\n    fdef: FuncItem,\n    *,\n    do_py_ops: bool = False,\n) -> FuncIR:\n    \"\"\"Generate glue methods that mediate between different method types in subclasses.\n\n    Works on both properties and methods. See gen_glue_methods below\n    for more details.\n\n    If do_py_ops is True, then the glue methods should use generic\n    C API operations instead of direct calls, to enable generating\n    \"shadow\" glue methods that work with interpreted subclasses.\n    \"\"\"\n    if fdef.is_property:\n        return gen_glue_property(builder, base_sig, target, cls, base, fdef.line, do_py_ops)\n    if do_py_ops and target.name.startswith(PROPSET_PREFIX):\n        return gen_glue_property_setter(builder, base_sig, target, cls, base, fdef.line)\n    return gen_glue_method(builder, base_sig, target, cls, base, fdef.line, do_py_ops)\n\n\nclass ArgInfo(NamedTuple):\n    args: list[Value]\n    arg_names: list[str | None]\n    arg_kinds: list[ArgKind]\n\n\ndef get_args(builder: IRBuilder, rt_args: Sequence[RuntimeArg], line: int) -> ArgInfo:\n    # The environment operates on Vars, so we make some up\n    fake_vars = [(Var(arg.name), arg.type) for arg in rt_args]\n    args = [\n        builder.read(builder.add_local_reg(var, type, is_arg=True), line)\n        for var, type in fake_vars\n    ]\n    arg_names = [\n        arg.name if arg.kind.is_named() or (arg.kind.is_optional() and not arg.pos_only) else None\n        for arg in rt_args\n    ]\n    arg_kinds = [arg.kind for arg in rt_args]\n    return ArgInfo(args, arg_names, arg_kinds)\n\n\ndef gen_glue_method(\n    builder: IRBuilder,\n    base_sig: FuncSignature,\n    target: FuncIR,\n    cls: ClassIR,\n    base: ClassIR,\n    line: int,\n    do_pycall: bool,\n) -> FuncIR:\n    \"\"\"Generate glue methods that mediate between different method types in subclasses.\n\n    For example, if we have:\n\n    class A:\n        def f(builder: IRBuilder, x: int) -> object: ...\n\n    then it is totally permissible to have a subclass\n\n    class B(A):\n        def f(builder: IRBuilder, x: object) -> int: ...\n\n    since '(object) -> int' is a subtype of '(int) -> object' by the usual\n    contra/co-variant function subtyping rules.\n\n    The trickiness here is that int and object have different\n    runtime representations in mypyc, so A.f and B.f have\n    different signatures at the native C level. To deal with this,\n    we need to generate glue methods that mediate between the\n    different versions by coercing the arguments and return\n    values.\n\n    If do_pycall is True, then make the call using the C API\n    instead of a native call.\n    \"\"\"\n    check_native_override(builder, base_sig, target.decl.sig, line)\n\n    builder.enter()\n    builder.ret_types[-1] = base_sig.ret_type\n\n    rt_args = list(base_sig.args)\n    if target.decl.kind == FUNC_NORMAL:\n        rt_args[0] = RuntimeArg(base_sig.args[0].name, RInstance(cls))\n\n    arg_info = get_args(builder, rt_args, line)\n    args, arg_kinds, arg_names = arg_info.args, arg_info.arg_kinds, arg_info.arg_names\n\n    bitmap_args = None\n    if base_sig.num_bitmap_args:\n        args = args[: -base_sig.num_bitmap_args]\n        arg_kinds = arg_kinds[: -base_sig.num_bitmap_args]\n        arg_names = arg_names[: -base_sig.num_bitmap_args]\n        bitmap_args = list(builder.builder.args[-base_sig.num_bitmap_args :])\n\n    # We can do a passthrough *args/**kwargs with a native call, but if the\n    # args need to get distributed out to arguments, we just let python handle it\n    if any(kind.is_star() for kind in arg_kinds) and any(\n        not arg.kind.is_star() for arg in target.decl.sig.args\n    ):\n        do_pycall = True\n\n    if do_pycall:\n        if target.decl.kind == FUNC_STATICMETHOD:\n            # FIXME: this won't work if we can do interpreted subclasses\n            first = builder.builder.get_native_type(cls)\n            st = 0\n        else:\n            first = args[0]\n            st = 1\n        retval = builder.builder.py_method_call(\n            first, target.name, args[st:], line, arg_kinds[st:], arg_names[st:]\n        )\n    else:\n        retval = builder.builder.call(\n            target.decl, args, arg_kinds, arg_names, line, bitmap_args=bitmap_args\n        )\n    retval = builder.coerce(retval, base_sig.ret_type, line)\n    builder.add(Return(retval))\n\n    arg_regs, _, blocks, ret_type, _ = builder.leave()\n    if base_sig.num_bitmap_args:\n        rt_args = rt_args[: -base_sig.num_bitmap_args]\n    return FuncIR(\n        FuncDecl(\n            target.name + \"__\" + base.name + \"_glue\",\n            cls.name,\n            builder.module_name,\n            FuncSignature(rt_args, ret_type),\n            target.decl.kind,\n            is_coroutine=target.decl.is_coroutine,\n        ),\n        arg_regs,\n        blocks,\n    )\n\n\ndef check_native_override(\n    builder: IRBuilder, base_sig: FuncSignature, sub_sig: FuncSignature, line: int\n) -> None:\n    \"\"\"Report an error if an override changes signature in unsupported ways.\n\n    Glue methods can work around many signature changes but not all of them.\n    \"\"\"\n    for base_arg, sub_arg in zip(base_sig.real_args(), sub_sig.real_args()):\n        if base_arg.type.error_overlap:\n            if not base_arg.optional and sub_arg.optional and base_sig.num_bitmap_args:\n                # This would change the meanings of bits in the argument defaults\n                # bitmap, which we don't support. We'd need to do tricky bit\n                # manipulations to support this generally.\n                builder.error(\n                    \"An argument with type \"\n                    + f'\"{base_arg.type}\" cannot be given a default value in a method override',\n                    line,\n                )\n        if base_arg.type.error_overlap or sub_arg.type.error_overlap:\n            if not is_same_type(base_arg.type, sub_arg.type):\n                # This would change from signaling a default via an error value to\n                # signaling a default via bitmap, which we don't support.\n                builder.error(\n                    \"Incompatible argument type \"\n                    + f'\"{sub_arg.type}\" (base class has type \"{base_arg.type}\")',\n                    line,\n                )\n\n\ndef gen_glue_property(\n    builder: IRBuilder,\n    sig: FuncSignature,\n    target: FuncIR,\n    cls: ClassIR,\n    base: ClassIR,\n    line: int,\n    do_pygetattr: bool,\n) -> FuncIR:\n    \"\"\"Generate glue methods for properties that mediate between different subclass types.\n\n    Similarly to methods, properties of derived types can be covariantly subtyped. Thus,\n    properties also require glue. However, this only requires the return type to change.\n    Further, instead of a method call, an attribute get is performed.\n\n    If do_pygetattr is True, then get the attribute using the Python C\n    API instead of a native call.\n    \"\"\"\n    builder.enter()\n\n    rt_arg = RuntimeArg(SELF_NAME, RInstance(cls))\n    self_target = builder.add_self_to_env(cls)\n    arg = builder.read(self_target, line)\n    builder.ret_types[-1] = sig.ret_type\n    if do_pygetattr:\n        retval = builder.py_get_attr(arg, target.name, line)\n    else:\n        retval = builder.add(GetAttr(arg, target.name, line))\n    retbox = builder.coerce(retval, sig.ret_type, line)\n    builder.add(Return(retbox))\n\n    args, _, blocks, return_type, _ = builder.leave()\n    return FuncIR(\n        FuncDecl(\n            target.name + \"__\" + base.name + \"_glue\",\n            cls.name,\n            builder.module_name,\n            FuncSignature([rt_arg], return_type),\n        ),\n        args,\n        blocks,\n    )\n\n\ndef gen_glue_property_setter(\n    builder: IRBuilder, sig: FuncSignature, target: FuncIR, cls: ClassIR, base: ClassIR, line: int\n) -> FuncIR:\n    \"\"\"Generate a shadow glue method for a property setter.\n\n    For interpreted subclasses, property setters can't be called via the\n    internal __mypyc_setter__<name> method. Instead, use Python's setattr\n    to set the property via the standard descriptor protocol.\n    \"\"\"\n    builder.enter()\n    builder.ret_types[-1] = sig.ret_type\n\n    rt_args = list(sig.args)\n    rt_args[0] = RuntimeArg(sig.args[0].name, RInstance(cls))\n\n    arg_info = get_args(builder, rt_args, line)\n    args = arg_info.args\n\n    self_arg = args[0]\n    value_arg = args[1]\n\n    # Extract the property name from \"__mypyc_setter__<name>\"\n    assert target.name.startswith(PROPSET_PREFIX)\n    prop_name = target.name[len(PROPSET_PREFIX) :]\n\n    builder.primitive_op(\n        py_setattr_op,\n        [\n            self_arg,\n            builder.load_str(prop_name),\n            builder.coerce(value_arg, object_rprimitive, line),\n        ],\n        line,\n    )\n    retval = builder.coerce(builder.none(), sig.ret_type, line)\n    builder.add(Return(retval))\n\n    arg_regs, _, blocks, return_type, _ = builder.leave()\n    return FuncIR(\n        FuncDecl(\n            target.name + \"__\" + base.name + \"_glue\",\n            cls.name,\n            builder.module_name,\n            FuncSignature(rt_args, return_type),\n        ),\n        arg_regs,\n        blocks,\n    )\n\n\ndef get_func_target(builder: IRBuilder, fdef: FuncDef) -> AssignmentTarget:\n    \"\"\"Given a FuncDef, return the target for the instance of its callable class.\n\n    If the function was not already defined somewhere, then define it\n    and add it to the current environment.\n    \"\"\"\n    if orig := fdef.original_def:\n        if isinstance(orig, Decorator):\n            orig = orig.func\n        # Get the target associated with the previously defined FuncDef.\n        return builder.lookup(orig)\n\n    if builder.fn_info.is_generator or builder.fn_info.add_nested_funcs_to_env:\n        return builder.lookup(fdef)\n\n    return builder.add_local_reg(fdef, object_rprimitive)\n\n\ndef load_type(builder: IRBuilder, typ: TypeInfo, unbounded_type: Type | None, line: int) -> Value:\n    # typ.fullname contains the module where the class object was defined. However, it is possible\n    # that the class object's module was not imported in the file currently being compiled. So, we\n    # use unbounded_type.name (if provided by caller) to load the class object through one of the\n    # imported modules.\n    # Example: for `json.JSONDecoder`, typ.fullname is `json.decoder.JSONDecoder` but the Python\n    # file may import `json` not `json.decoder`.\n    # Another corner case: The Python file being compiled imports mod1 and has a type hint\n    # `mod1.OuterClass.InnerClass`. But, mod1/__init__.py might import OuterClass like this:\n    # `from mod2.mod3 import OuterClass`. In this case, typ.fullname is\n    # `mod2.mod3.OuterClass.InnerClass` and `unbounded_type.name` is `mod1.OuterClass.InnerClass`.\n    # So, we must use unbounded_type.name to load the class object.\n    # See issue mypyc/mypyc#1087.\n    if typ in builder.mapper.type_to_ir:\n        class_ir = builder.mapper.type_to_ir[typ]\n        class_obj = builder.builder.get_native_type(class_ir)\n    elif typ.fullname in builtin_names:\n        builtin_addr_type, src = builtin_names[typ.fullname]\n        class_obj = builder.add(LoadAddress(builtin_addr_type, src, line))\n    elif isinstance(unbounded_type, UnboundType):\n        path_parts = unbounded_type.name.split(\".\")\n        class_obj = builder.load_global_str(path_parts[0], line)\n        for attr in path_parts[1:]:\n            class_obj = builder.py_get_attr(class_obj, attr, line)\n    else:\n        class_obj = builder.load_global_str(typ.name, line)\n\n    return class_obj\n\n\ndef load_func(builder: IRBuilder, func_name: str, fullname: str | None, line: int) -> Value:\n    if fullname and not fullname.startswith(builder.current_module):\n        # we're calling a function in a different module\n\n        # We can't use load_module_attr_by_fullname here because we need to load the function using\n        # func_name, not the name specified by fullname (which can be different for underscore\n        # function)\n        module = fullname.rsplit(\".\")[0]\n        loaded_module = builder.load_module(module)\n\n        func = builder.py_get_attr(loaded_module, func_name, line)\n    else:\n        func = builder.load_global_str(func_name, line)\n    return func\n\n\ndef generate_singledispatch_dispatch_function(\n    builder: IRBuilder, main_singledispatch_function_name: str, fitem: FuncDef\n) -> None:\n    line = fitem.line\n    current_func_decl = builder.mapper.func_to_decl[fitem]\n    arg_info = get_args(builder, current_func_decl.sig.args, line)\n\n    dispatch_func_obj = builder.self()\n\n    arg_type = builder.builder.get_type_of_obj(arg_info.args[0], line)\n    dispatch_cache = builder.builder.get_attr(\n        dispatch_func_obj, \"dispatch_cache\", dict_rprimitive, line\n    )\n    call_find_impl, use_cache, call_func = BasicBlock(), BasicBlock(), BasicBlock()\n    get_result = builder.primitive_op(dict_get_method_with_none, [dispatch_cache, arg_type], line)\n    is_not_none = builder.translate_is_op(get_result, builder.none_object(), \"is not\", line)\n    impl_to_use = Register(object_rprimitive)\n    builder.add_bool_branch(is_not_none, use_cache, call_find_impl)\n\n    builder.activate_block(use_cache)\n    builder.assign(impl_to_use, get_result, line)\n    builder.goto(call_func)\n\n    builder.activate_block(call_find_impl)\n    find_impl = builder.load_module_attr_by_fullname(\"functools._find_impl\", line)\n    registry = load_singledispatch_registry(builder, dispatch_func_obj, line)\n    uncached_impl = builder.py_call(find_impl, [arg_type, registry], line)\n    builder.call_c(exact_dict_set_item_op, [dispatch_cache, arg_type, uncached_impl], line)\n    builder.assign(impl_to_use, uncached_impl, line)\n    builder.goto(call_func)\n\n    builder.activate_block(call_func)\n    gen_calls_to_correct_impl(builder, impl_to_use, arg_info, fitem, line)\n\n\ndef gen_calls_to_correct_impl(\n    builder: IRBuilder, impl_to_use: Value, arg_info: ArgInfo, fitem: FuncDef, line: int\n) -> None:\n    current_func_decl = builder.mapper.func_to_decl[fitem]\n\n    def gen_native_func_call_and_return(fdef: FuncDef) -> None:\n        func_decl = builder.mapper.func_to_decl[fdef]\n        ret_val = builder.builder.call(\n            func_decl, arg_info.args, arg_info.arg_kinds, arg_info.arg_names, line\n        )\n        coerced = builder.coerce(ret_val, current_func_decl.sig.ret_type, line)\n        builder.add(Return(coerced))\n\n    typ, src = builtin_names[\"builtins.int\"]\n    int_type_obj = builder.add(LoadAddress(typ, src, line))\n    is_int = builder.builder.type_is_op(impl_to_use, int_type_obj, line)\n\n    native_call, non_native_call = BasicBlock(), BasicBlock()\n    builder.add_bool_branch(is_int, native_call, non_native_call)\n    builder.activate_block(native_call)\n\n    passed_id = builder.add(Unbox(impl_to_use, int_rprimitive, line))\n\n    native_ids = get_native_impl_ids(builder, fitem)\n    for impl, i in native_ids.items():\n        call_impl, next_impl = BasicBlock(), BasicBlock()\n\n        current_id = builder.load_int(i)\n        cond = builder.binary_op(passed_id, current_id, \"==\", line)\n        builder.add_bool_branch(cond, call_impl, next_impl)\n\n        # Call the registered implementation\n        builder.activate_block(call_impl)\n\n        gen_native_func_call_and_return(impl)\n        builder.activate_block(next_impl)\n\n    # We've already handled all the possible integer IDs, so we should never get here\n    builder.add(Unreachable())\n\n    builder.activate_block(non_native_call)\n    ret_val = builder.py_call(\n        impl_to_use, arg_info.args, line, arg_info.arg_kinds, arg_info.arg_names\n    )\n    coerced = builder.coerce(ret_val, current_func_decl.sig.ret_type, line)\n    builder.add(Return(coerced))\n\n\ndef gen_dispatch_func_ir(\n    builder: IRBuilder, fitem: FuncDef, main_func_name: str, dispatch_name: str, sig: FuncSignature\n) -> tuple[FuncIR, Value]:\n    \"\"\"Create a dispatch function (a function that checks the first argument type and dispatches\n    to the correct implementation)\n    \"\"\"\n    builder.enter(FuncInfo(fitem, dispatch_name))\n    setup_callable_class(builder)\n    builder.fn_info.callable_class.ir.attributes[\"registry\"] = dict_rprimitive\n    builder.fn_info.callable_class.ir.attributes[\"dispatch_cache\"] = dict_rprimitive\n    builder.fn_info.callable_class.ir.has_dict = True\n    builder.fn_info.callable_class.ir.needs_getseters = True\n    generate_singledispatch_callable_class_ctor(builder)\n\n    generate_singledispatch_dispatch_function(builder, main_func_name, fitem)\n    args, _, blocks, _, fn_info = builder.leave()\n    dispatch_callable_class = add_call_to_callable_class(builder, args, blocks, sig, fn_info)\n    builder.functions.append(dispatch_callable_class)\n    add_get_to_callable_class(builder, fn_info)\n    add_register_method_to_callable_class(builder, fn_info)\n    func_reg = instantiate_callable_class(builder, fn_info)\n    dispatch_func_ir = generate_dispatch_glue_native_function(\n        builder, fitem, dispatch_callable_class.decl, dispatch_name\n    )\n\n    return dispatch_func_ir, func_reg\n\n\ndef generate_dispatch_glue_native_function(\n    builder: IRBuilder, fitem: FuncDef, callable_class_decl: FuncDecl, dispatch_name: str\n) -> FuncIR:\n    line = fitem.line\n    builder.enter()\n    # We store the callable class in the globals dict for this function\n    callable_class = builder.load_global_str(dispatch_name, line)\n    decl = builder.mapper.func_to_decl[fitem]\n    arg_info = get_args(builder, decl.sig.args, line)\n    args = [callable_class] + arg_info.args\n    arg_kinds = [ArgKind.ARG_POS] + arg_info.arg_kinds\n    arg_names = arg_info.arg_names\n    arg_names.insert(0, \"self\")\n    ret_val = builder.builder.call(callable_class_decl, args, arg_kinds, arg_names, line)\n    builder.add(Return(ret_val))\n    arg_regs, _, blocks, _, fn_info = builder.leave()\n    return FuncIR(decl, arg_regs, blocks)\n\n\ndef generate_singledispatch_callable_class_ctor(builder: IRBuilder) -> None:\n    \"\"\"Create an __init__ that sets registry and dispatch_cache to empty dicts\"\"\"\n    line = builder.fn_info.fitem.line\n    class_ir = builder.fn_info.callable_class.ir\n    with builder.enter_method(class_ir, \"__init__\", bool_rprimitive):\n        empty_dict = builder.call_c(dict_new_op, [], line)\n        builder.add(SetAttr(builder.self(), \"registry\", empty_dict, line))\n        cache_dict = builder.call_c(dict_new_op, [], line)\n        dispatch_cache_str = builder.load_str(\"dispatch_cache\")\n        # use the py_setattr_op instead of SetAttr so that it also gets added to our __dict__\n        builder.primitive_op(py_setattr_op, [builder.self(), dispatch_cache_str, cache_dict], line)\n        # the generated C code seems to expect that __init__ returns a char, so just return 1\n        builder.add(Return(Integer(1, bool_rprimitive, line), line))\n\n\ndef add_register_method_to_callable_class(builder: IRBuilder, fn_info: FuncInfo) -> None:\n    line = fn_info.fitem.line\n    with builder.enter_method(fn_info.callable_class.ir, \"register\", object_rprimitive):\n        cls_arg = builder.add_argument(\"cls\", object_rprimitive)\n        func_arg = builder.add_argument(\"func\", object_rprimitive, ArgKind.ARG_OPT)\n        ret_val = builder.call_c(register_function, [builder.self(), cls_arg, func_arg], line)\n        builder.add(Return(ret_val, line))\n\n\ndef load_singledispatch_registry(builder: IRBuilder, dispatch_func_obj: Value, line: int) -> Value:\n    return builder.builder.get_attr(dispatch_func_obj, \"registry\", dict_rprimitive, line)\n\n\ndef singledispatch_main_func_name(orig_name: str) -> str:\n    return f\"__mypyc_singledispatch_main_function_{orig_name}__\"\n\n\ndef maybe_insert_into_registry_dict(builder: IRBuilder, fitem: FuncDef) -> None:\n    line = fitem.line\n    is_singledispatch_main_func = fitem in builder.singledispatch_impls\n    # dict of singledispatch_func to list of register_types (fitem is the function to register)\n    to_register: defaultdict[FuncDef, list[TypeInfo]] = defaultdict(list)\n    for main_func, impls in builder.singledispatch_impls.items():\n        for dispatch_type, impl in impls:\n            if fitem == impl:\n                to_register[main_func].append(dispatch_type)\n\n    if not to_register and not is_singledispatch_main_func:\n        return\n\n    if is_singledispatch_main_func:\n        main_func_name = singledispatch_main_func_name(fitem.name)\n        main_func_obj = load_func(builder, main_func_name, fitem.fullname, line)\n\n        loaded_object_type = builder.load_module_attr_by_fullname(\"builtins.object\", line)\n        registry_dict = builder.builder.make_dict([(loaded_object_type, main_func_obj)], line)\n\n        dispatch_func_obj = builder.load_global_str(fitem.name, line)\n        builder.primitive_op(\n            py_setattr_op, [dispatch_func_obj, builder.load_str(\"registry\"), registry_dict], line\n        )\n\n    for singledispatch_func, types in to_register.items():\n        # TODO: avoid recomputing the native IDs for all the functions every time we find a new\n        # function\n        native_ids = get_native_impl_ids(builder, singledispatch_func)\n        if fitem not in native_ids:\n            to_insert = load_func(builder, fitem.name, fitem.fullname, line)\n        else:\n            current_id = native_ids[fitem]\n            load_literal = LoadLiteral(current_id, object_rprimitive)\n            to_insert = builder.add(load_literal)\n        # TODO: avoid reloading the registry here if we just created it\n        dispatch_func_obj = load_func(\n            builder, singledispatch_func.name, singledispatch_func.fullname, line\n        )\n        registry = load_singledispatch_registry(builder, dispatch_func_obj, line)\n        for typ in types:\n            loaded_type = load_type(builder, typ, None, line)\n            builder.call_c(exact_dict_set_item_op, [registry, loaded_type, to_insert], line)\n        dispatch_cache = builder.builder.get_attr(\n            dispatch_func_obj, \"dispatch_cache\", dict_rprimitive, line\n        )\n        builder.gen_method_call(dispatch_cache, \"clear\", [], None, line)\n\n\ndef get_native_impl_ids(builder: IRBuilder, singledispatch_func: FuncDef) -> dict[FuncDef, int]:\n    \"\"\"Return a dict of registered implementation to native implementation ID for all\n    implementations\n    \"\"\"\n    impls = builder.singledispatch_impls[singledispatch_func]\n    return {impl: i for i, (typ, impl) in enumerate(impls) if not is_decorated(builder, impl)}\n\n\ndef gen_property_getter_ir(\n    builder: IRBuilder, func_decl: FuncDecl, cdef: ClassDef, is_trait: bool\n) -> FuncIR:\n    \"\"\"Generate an implicit trivial property getter for an attribute.\n\n    These are used if an attribute can also be accessed as a property.\n    \"\"\"\n    name = func_decl.name\n    builder.enter(name)\n    self_reg = builder.add_argument(\"self\", func_decl.sig.args[0].type)\n    line = func_decl._line or -1\n    if not is_trait:\n        value = builder.builder.get_attr(self_reg, name, func_decl.sig.ret_type, line)\n        builder.add(Return(value, line))\n    else:\n        builder.add(Unreachable())\n    args, _, blocks, ret_type, fn_info = builder.leave()\n    return FuncIR(func_decl, args, blocks)\n\n\ndef gen_property_setter_ir(\n    builder: IRBuilder, func_decl: FuncDecl, cdef: ClassDef, is_trait: bool\n) -> FuncIR:\n    \"\"\"Generate an implicit trivial property setter for an attribute.\n\n    These are used if an attribute can also be accessed as a property.\n    \"\"\"\n    name = func_decl.name\n    builder.enter(name)\n    self_reg = builder.add_argument(\"self\", func_decl.sig.args[0].type)\n    value_reg = builder.add_argument(\"value\", func_decl.sig.args[1].type)\n    assert name.startswith(PROPSET_PREFIX)\n    attr_name = name[len(PROPSET_PREFIX) :]\n    line = func_decl._line or -1\n    if not is_trait:\n        builder.add(SetAttr(self_reg, attr_name, value_reg, line))\n    builder.add(Return(builder.none(), line))\n    args, _, blocks, ret_type, fn_info = builder.leave()\n    return FuncIR(func_decl, args, blocks, line)\n"
  },
  {
    "path": "mypyc/irbuild/generator.py",
    "content": "\"\"\"Generate IR for generator functions.\n\nA generator function is represented by a class that implements the\ngenerator protocol and keeps track of the generator state, including\nlocal variables.\n\nThe top-level logic for dealing with generator functions is in\nmypyc.irbuild.function.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\n\nfrom mypy.nodes import ARG_OPT, FuncDef, Var\nfrom mypyc.common import ENV_ATTR_NAME, GENERATOR_ATTRIBUTE_PREFIX, NEXT_LABEL_ATTR_NAME\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FuncDecl, FuncIR\nfrom mypyc.ir.ops import (\n    NO_TRACEBACK_LINE_NO,\n    BasicBlock,\n    Branch,\n    Call,\n    Goto,\n    Integer,\n    MethodCall,\n    RaiseStandardError,\n    Register,\n    Return,\n    SetAttr,\n    TupleSet,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    int32_rprimitive,\n    object_pointer_rprimitive,\n    object_rprimitive,\n)\nfrom mypyc.irbuild.builder import IRBuilder, calculate_arg_defaults, gen_arg_defaults\nfrom mypyc.irbuild.context import FuncInfo\nfrom mypyc.irbuild.env_class import (\n    add_args_to_env,\n    add_vars_to_env,\n    finalize_env_class,\n    load_env_registers,\n    load_outer_env,\n    load_outer_envs,\n    setup_func_for_recursive_call,\n)\nfrom mypyc.irbuild.nonlocalcontrol import ExceptNonlocalControl\nfrom mypyc.irbuild.prepare import GENERATOR_HELPER_NAME\nfrom mypyc.primitives.exc_ops import (\n    error_catch_op,\n    exc_matches_op,\n    raise_exception_with_tb_op,\n    reraise_exception_op,\n    restore_exc_info_op,\n)\n\n\ndef gen_generator_func(\n    builder: IRBuilder,\n    gen_func_ir: Callable[\n        [list[Register], list[BasicBlock], FuncInfo], tuple[FuncIR, Value | None]\n    ],\n) -> tuple[FuncIR, Value | None]:\n    \"\"\"Generate IR for generator function that returns generator object.\"\"\"\n    setup_generator_class(builder)\n    load_env_registers(builder, prefix=GENERATOR_ATTRIBUTE_PREFIX)\n    gen_arg_defaults(builder)\n    if builder.fn_info.can_merge_generator_and_env_classes():\n        gen = instantiate_generator_class(builder)\n        builder.fn_info._curr_env_reg = gen\n        finalize_env_class(builder, prefix=GENERATOR_ATTRIBUTE_PREFIX)\n    else:\n        finalize_env_class(builder, prefix=GENERATOR_ATTRIBUTE_PREFIX)\n        gen = instantiate_generator_class(builder)\n    builder.add(Return(gen))\n\n    args, _, blocks, ret_type, fn_info = builder.leave()\n    func_ir, func_reg = gen_func_ir(args, blocks, fn_info)\n    return func_ir, func_reg\n\n\ndef gen_generator_func_body(builder: IRBuilder, fn_info: FuncInfo, func_reg: Value | None) -> None:\n    \"\"\"Generate IR based on the body of a generator function.\n\n    Add \"__next__\", \"__iter__\" and other generator methods to the generator\n    class that implements the function (each function gets a separate class).\n\n    Return the symbol table for the body.\n    \"\"\"\n    builder.enter(fn_info, ret_type=object_rprimitive)\n    setup_env_for_generator_class(builder)\n\n    load_outer_envs(builder, builder.fn_info.generator_class)\n    top_level = builder.top_level_fn_info()\n    fitem = fn_info.fitem\n    if (\n        builder.fn_info.is_nested\n        and isinstance(fitem, FuncDef)\n        and top_level\n        and top_level.add_nested_funcs_to_env\n    ):\n        setup_func_for_recursive_call(\n            builder, fitem, builder.fn_info.generator_class, prefix=GENERATOR_ATTRIBUTE_PREFIX\n        )\n    create_switch_for_generator_class(builder)\n    add_raise_exception_blocks_to_generator_class(builder, fitem.line)\n\n    add_vars_to_env(builder, prefix=GENERATOR_ATTRIBUTE_PREFIX)\n\n    builder.accept(fitem.body)\n    builder.maybe_add_implicit_return()\n\n    populate_switch_for_generator_class(builder)\n\n    # Hang on to the local symbol table, since the caller will use it\n    # to calculate argument defaults.\n    symtable = builder.symtables[-1]\n\n    args, _, blocks, ret_type, fn_info = builder.leave()\n\n    add_methods_to_generator_class(builder, fn_info, args, blocks, fitem.is_coroutine)\n\n    # Evaluate argument defaults in the surrounding scope, since we\n    # calculate them *once* when the function definition is evaluated.\n    calculate_arg_defaults(builder, fn_info, func_reg, symtable)\n\n\ndef instantiate_generator_class(builder: IRBuilder) -> Value:\n    fitem = builder.fn_info.fitem\n    generator_reg = builder.add(Call(builder.fn_info.generator_class.ir.ctor, [], fitem.line))\n\n    if builder.fn_info.can_merge_generator_and_env_classes():\n        # Set the generator instance to the initial state (zero).\n        zero = Integer(0)\n        builder.add(SetAttr(generator_reg, NEXT_LABEL_ATTR_NAME, zero, fitem.line))\n    else:\n        # Get the current environment register. If the current function is nested, then the\n        # generator class gets instantiated from the callable class' '__call__' method, and hence\n        # we use the callable class' environment register. Otherwise, we use the original\n        # function's environment register.\n        if builder.fn_info.is_nested:\n            curr_env_reg = builder.fn_info.callable_class.curr_env_reg\n        else:\n            curr_env_reg = builder.fn_info.curr_env_reg\n\n        # Set the generator class' environment attribute to point at the environment class\n        # defined in the current scope.\n        builder.add(SetAttr(generator_reg, ENV_ATTR_NAME, curr_env_reg, fitem.line))\n\n        # Set the generator instance's environment to the initial state (zero).\n        zero = Integer(0)\n        builder.add(SetAttr(curr_env_reg, NEXT_LABEL_ATTR_NAME, zero, fitem.line))\n    return generator_reg\n\n\ndef setup_generator_class(builder: IRBuilder) -> ClassIR:\n    mapper = builder.mapper\n    assert isinstance(builder.fn_info.fitem, FuncDef), builder.fn_info.fitem\n    generator_class_ir = mapper.fdef_to_generator[builder.fn_info.fitem]\n    if builder.fn_info.can_merge_generator_and_env_classes():\n        builder.fn_info.env_class = generator_class_ir\n    else:\n        generator_class_ir.attributes[ENV_ATTR_NAME] = RInstance(builder.fn_info.env_class)\n\n    builder.classes.append(generator_class_ir)\n    return generator_class_ir\n\n\ndef create_switch_for_generator_class(builder: IRBuilder) -> None:\n    builder.add(Goto(builder.fn_info.generator_class.switch_block))\n    block = BasicBlock()\n    builder.fn_info.generator_class.continuation_blocks.append(block)\n    builder.activate_block(block)\n\n\ndef populate_switch_for_generator_class(builder: IRBuilder) -> None:\n    cls = builder.fn_info.generator_class\n    line = builder.fn_info.fitem.line\n\n    builder.activate_block(cls.switch_block)\n    for label, true_block in enumerate(cls.continuation_blocks):\n        false_block = BasicBlock()\n        comparison = builder.binary_op(cls.next_label_reg, Integer(label), \"==\", line)\n        builder.add_bool_branch(comparison, true_block, false_block)\n        builder.activate_block(false_block)\n\n    builder.add(RaiseStandardError(RaiseStandardError.STOP_ITERATION, None, line))\n    builder.add(Unreachable())\n\n\ndef add_raise_exception_blocks_to_generator_class(builder: IRBuilder, line: int) -> None:\n    \"\"\"Add error handling blocks to a generator class.\n\n    Generates blocks to check if error flags are set while calling the\n    helper method for generator functions, and raises an exception if\n    those flags are set.\n    \"\"\"\n    cls = builder.fn_info.generator_class\n    assert cls.exc_regs is not None\n    exc_type, exc_val, exc_tb = cls.exc_regs\n\n    # Check to see if an exception was raised.\n    error_block = BasicBlock()\n    ok_block = BasicBlock()\n    comparison = builder.translate_is_op(exc_type, builder.none_object(), \"is not\", line)\n    builder.add_bool_branch(comparison, error_block, ok_block)\n\n    builder.activate_block(error_block)\n    builder.call_c(raise_exception_with_tb_op, [exc_type, exc_val, exc_tb], line)\n    builder.add(Unreachable())\n    builder.goto_and_activate(ok_block)\n\n\ndef add_methods_to_generator_class(\n    builder: IRBuilder,\n    fn_info: FuncInfo,\n    arg_regs: list[Register],\n    blocks: list[BasicBlock],\n    is_coroutine: bool,\n) -> None:\n    helper_fn_decl = add_helper_to_generator_class(builder, arg_regs, blocks, fn_info)\n    add_next_to_generator_class(builder, fn_info, helper_fn_decl)\n    add_send_to_generator_class(builder, fn_info, helper_fn_decl)\n    add_iter_to_generator_class(builder, fn_info)\n    add_throw_to_generator_class(builder, fn_info, helper_fn_decl)\n    add_close_to_generator_class(builder, fn_info)\n    if is_coroutine:\n        add_await_to_generator_class(builder, fn_info)\n\n\ndef add_helper_to_generator_class(\n    builder: IRBuilder, arg_regs: list[Register], blocks: list[BasicBlock], fn_info: FuncInfo\n) -> FuncDecl:\n    \"\"\"Generates a helper method for a generator class, called by '__next__' and 'throw'.\"\"\"\n    helper_fn_decl = fn_info.generator_class.ir.method_decls[GENERATOR_HELPER_NAME]\n    helper_fn_ir = FuncIR(\n        helper_fn_decl, arg_regs, blocks, fn_info.fitem.line, traceback_name=fn_info.fitem.name\n    )\n    fn_info.generator_class.ir.methods[GENERATOR_HELPER_NAME] = helper_fn_ir\n    builder.functions.append(helper_fn_ir)\n    fn_info.env_class.env_user_function = helper_fn_ir\n\n    return helper_fn_decl\n\n\ndef add_iter_to_generator_class(builder: IRBuilder, fn_info: FuncInfo) -> None:\n    \"\"\"Generates the '__iter__' method for a generator class.\"\"\"\n    with builder.enter_method(fn_info.generator_class.ir, \"__iter__\", object_rprimitive, fn_info):\n        builder.add(Return(builder.self()))\n\n\ndef add_next_to_generator_class(builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl) -> None:\n    \"\"\"Generates the '__next__' method for a generator class.\"\"\"\n    with builder.enter_method(fn_info.generator_class.ir, \"__next__\", object_rprimitive, fn_info):\n        none_reg = builder.none_object()\n        # Call the helper function with error flags set to Py_None, and return that result.\n        result = builder.add(\n            Call(\n                fn_decl,\n                [\n                    builder.self(),\n                    none_reg,\n                    none_reg,\n                    none_reg,\n                    none_reg,\n                    Integer(0, object_pointer_rprimitive),\n                ],\n                fn_info.fitem.line,\n            )\n        )\n        builder.add(Return(result))\n\n\ndef add_send_to_generator_class(builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl) -> None:\n    \"\"\"Generates the 'send' method for a generator class.\"\"\"\n    with builder.enter_method(fn_info.generator_class.ir, \"send\", object_rprimitive, fn_info):\n        arg = builder.add_argument(\"arg\", object_rprimitive)\n        none_reg = builder.none_object()\n        # Call the helper function with error flags set to Py_None, and return that result.\n        result = builder.add(\n            Call(\n                fn_decl,\n                [\n                    builder.self(),\n                    none_reg,\n                    none_reg,\n                    none_reg,\n                    builder.read(arg),\n                    Integer(0, object_pointer_rprimitive),\n                ],\n                fn_info.fitem.line,\n            )\n        )\n        builder.add(Return(result))\n\n\ndef add_throw_to_generator_class(builder: IRBuilder, fn_info: FuncInfo, fn_decl: FuncDecl) -> None:\n    \"\"\"Generates the 'throw' method for a generator class.\"\"\"\n    with builder.enter_method(fn_info.generator_class.ir, \"throw\", object_rprimitive, fn_info):\n        typ = builder.add_argument(\"type\", object_rprimitive)\n        val = builder.add_argument(\"value\", object_rprimitive, ARG_OPT)\n        tb = builder.add_argument(\"traceback\", object_rprimitive, ARG_OPT)\n\n        # Because the value and traceback arguments are optional and hence\n        # can be NULL if not passed in, we have to assign them Py_None if\n        # they are not passed in.\n        none_reg = builder.none_object()\n        builder.assign_if_null(val, lambda: none_reg, fn_info.fitem.line)\n        builder.assign_if_null(tb, lambda: none_reg, fn_info.fitem.line)\n\n        # Call the helper function using the arguments passed in, and return that result.\n        result = builder.add(\n            Call(\n                fn_decl,\n                [\n                    builder.self(),\n                    builder.read(typ),\n                    builder.read(val),\n                    builder.read(tb),\n                    none_reg,\n                    Integer(0, object_pointer_rprimitive),\n                ],\n                fn_info.fitem.line,\n            )\n        )\n        builder.add(Return(result))\n\n\ndef add_close_to_generator_class(builder: IRBuilder, fn_info: FuncInfo) -> None:\n    \"\"\"Generates the '__close__' method for a generator class.\"\"\"\n    with builder.enter_method(fn_info.generator_class.ir, \"close\", object_rprimitive, fn_info):\n        except_block, else_block = BasicBlock(), BasicBlock()\n        builder.builder.push_error_handler(except_block)\n        builder.goto_and_activate(BasicBlock())\n        generator_exit = builder.load_module_attr_by_fullname(\n            \"builtins.GeneratorExit\", fn_info.fitem.line\n        )\n        builder.add(\n            MethodCall(\n                builder.self(),\n                \"throw\",\n                [generator_exit, builder.none_object(), builder.none_object()],\n                fn_info.fitem.line,\n            )\n        )\n        builder.goto(else_block)\n        builder.builder.pop_error_handler()\n\n        builder.activate_block(except_block)\n        old_exc = builder.call_c(error_catch_op, [], fn_info.fitem.line)\n        builder.nonlocal_control.append(\n            ExceptNonlocalControl(builder.nonlocal_control[-1], old_exc)\n        )\n        stop_iteration = builder.load_module_attr_by_fullname(\n            \"builtins.StopIteration\", fn_info.fitem.line\n        )\n        exceptions = builder.add(TupleSet([generator_exit, stop_iteration], fn_info.fitem.line))\n        matches = builder.call_c(exc_matches_op, [exceptions], fn_info.fitem.line)\n\n        match_block, non_match_block = BasicBlock(), BasicBlock()\n        builder.add(Branch(matches, match_block, non_match_block, Branch.BOOL))\n\n        builder.activate_block(match_block)\n        builder.call_c(restore_exc_info_op, [builder.read(old_exc)], fn_info.fitem.line)\n        builder.add(Return(builder.none_object()))\n\n        builder.activate_block(non_match_block)\n        builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)\n        builder.add(Unreachable())\n\n        builder.nonlocal_control.pop()\n\n        builder.activate_block(else_block)\n        builder.add(\n            RaiseStandardError(\n                RaiseStandardError.RUNTIME_ERROR,\n                \"generator ignored GeneratorExit\",\n                fn_info.fitem.line,\n            )\n        )\n        builder.add(Unreachable())\n\n\ndef add_await_to_generator_class(builder: IRBuilder, fn_info: FuncInfo) -> None:\n    \"\"\"Generates the '__await__' method for a generator class.\"\"\"\n    with builder.enter_method(fn_info.generator_class.ir, \"__await__\", object_rprimitive, fn_info):\n        builder.add(Return(builder.self()))\n\n\ndef setup_env_for_generator_class(builder: IRBuilder) -> None:\n    \"\"\"Populates the environment for a generator class.\"\"\"\n    fitem = builder.fn_info.fitem\n    cls = builder.fn_info.generator_class\n    self_target = builder.add_self_to_env(cls.ir)\n\n    # Add the type, value, and traceback variables to the environment.\n    exc_type = builder.add_local(Var(\"type\"), object_rprimitive, is_arg=True)\n    exc_val = builder.add_local(Var(\"value\"), object_rprimitive, is_arg=True)\n    exc_tb = builder.add_local(Var(\"traceback\"), object_rprimitive, is_arg=True)\n    # TODO: Use the right type here instead of object?\n    exc_arg = builder.add_local(Var(\"arg\"), object_rprimitive, is_arg=True)\n\n    # Parameter that can used to pass a pointer which can used instead of\n    # raising StopIteration(value). If the value is NULL, this won't be used.\n    stop_iter_value_arg = builder.add_local(\n        Var(\"stop_iter_ptr\"), object_pointer_rprimitive, is_arg=True\n    )\n\n    cls.exc_regs = (exc_type, exc_val, exc_tb)\n    cls.send_arg_reg = exc_arg\n    cls.stop_iter_value_reg = stop_iter_value_arg\n\n    cls.self_reg = builder.read(self_target, fitem.line)\n    if builder.fn_info.can_merge_generator_and_env_classes():\n        cls.curr_env_reg = cls.self_reg\n    else:\n        cls.curr_env_reg = load_outer_env(builder, cls.self_reg, builder.symtables[-1])\n\n    # Define a variable representing the label to go to the next time\n    # the '__next__' function of the generator is called, and add it\n    # as an attribute to the environment class.\n    cls.next_label_target = builder.add_var_to_env_class(\n        Var(NEXT_LABEL_ATTR_NAME), int32_rprimitive, cls, reassign=False, always_defined=True\n    )\n\n    # Add arguments from the original generator function to the\n    # environment of the generator class.\n    add_args_to_env(\n        builder, local=False, base=cls, reassign=False, prefix=GENERATOR_ATTRIBUTE_PREFIX\n    )\n\n    # Set the next label register for the generator class.\n    cls.next_label_reg = builder.read(cls.next_label_target, fitem.line)\n"
  },
  {
    "path": "mypyc/irbuild/ll_builder.py",
    "content": "\"\"\"A \"low-level\" IR builder class.\n\nSee the docstring of class LowLevelIRBuilder for more information.\n\n\"\"\"\n\nfrom __future__ import annotations\n\nimport sys\nfrom collections.abc import Callable, Sequence\nfrom typing import Final, TypeGuard, cast\n\nfrom mypy.argmap import map_actuals_to_formals\nfrom mypy.nodes import ARG_POS, ARG_STAR, ARG_STAR2, ArgKind\nfrom mypy.operators import op_methods, unary_op_methods\nfrom mypy.types import AnyType, TypeOfAny\nfrom mypyc.common import (\n    BITMAP_BITS,\n    FAST_ISINSTANCE_MAX_SUBCLASSES,\n    FAST_PREFIX,\n    IS_FREE_THREADED,\n    MAX_LITERAL_SHORT_INT,\n    MAX_SHORT_INT,\n    MIN_LITERAL_SHORT_INT,\n    MIN_SHORT_INT,\n    PLATFORM_SIZE,\n)\nfrom mypyc.errors import Errors\nfrom mypyc.ir.class_ir import ClassIR, all_concrete_classes\nfrom mypyc.ir.func_ir import FuncDecl, FuncSignature\nfrom mypyc.ir.ops import (\n    ERR_FALSE,\n    ERR_NEVER,\n    NAMESPACE_MODULE,\n    NAMESPACE_STATIC,\n    NAMESPACE_TYPE,\n    Assign,\n    AssignMulti,\n    BasicBlock,\n    Box,\n    Branch,\n    Call,\n    CallC,\n    Cast,\n    ComparisonOp,\n    Extend,\n    Float,\n    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\n    GetElement,\n    GetElementPtr,\n    Goto,\n    Integer,\n    IntOp,\n    KeepAlive,\n    LoadAddress,\n    LoadErrorValue,\n    LoadGlobal,\n    LoadLiteral,\n    LoadMem,\n    LoadStatic,\n    MethodCall,\n    Op,\n    PrimitiveDescription,\n    PrimitiveOp,\n    RaiseStandardError,\n    Register,\n    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unbox,\n    Unreachable,\n    Value,\n    float_comparison_op_to_id,\n    float_op_to_id,\n    int_op_to_id,\n)\nfrom mypyc.ir.rtypes import (\n    PyObject,\n    PySetObject,\n    RArray,\n    RInstance,\n    RPrimitive,\n    RStruct,\n    RTuple,\n    RType,\n    RUnion,\n    RVec,\n    bit_rprimitive,\n    bitmap_rprimitive,\n    bool_rprimitive,\n    bytes_rprimitive,\n    c_int_rprimitive,\n    c_pointer_rprimitive,\n    c_pyssize_t_rprimitive,\n    c_size_t_rprimitive,\n    check_native_int_range,\n    float_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    is_bool_or_bit_rprimitive,\n    is_bytes_rprimitive,\n    is_c_py_ssize_t_rprimitive,\n    is_dict_rprimitive,\n    is_fixed_width_rtype,\n    is_float_rprimitive,\n    is_frozenset_rprimitive,\n    is_int16_rprimitive,\n    is_int32_rprimitive,\n    is_int64_rprimitive,\n    is_int_rprimitive,\n    is_list_rprimitive,\n    is_none_rprimitive,\n    is_object_rprimitive,\n    is_optional_type,\n    is_set_rprimitive,\n    is_short_int_rprimitive,\n    is_str_rprimitive,\n    is_tagged,\n    is_tuple_rprimitive,\n    is_uint8_rprimitive,\n    none_rprimitive,\n    object_pointer_rprimitive,\n    object_rprimitive,\n    optional_value_type,\n    pointer_rprimitive,\n    short_int_rprimitive,\n    str_rprimitive,\n)\nfrom mypyc.irbuild.util import concrete_arg_kind\nfrom mypyc.irbuild.vec import vec_contains, vec_get_item, vec_len_native\nfrom mypyc.options import CompilerOptions\nfrom mypyc.primitives.bytes_ops import bytes_compare\nfrom mypyc.primitives.dict_ops import (\n    dict_build_op,\n    dict_copy,\n    dict_copy_op,\n    dict_new_op,\n    dict_ssize_t_size_op,\n    dict_update_in_display_op,\n)\nfrom mypyc.primitives.exc_ops import err_occurred_op, keep_propagating_op\nfrom mypyc.primitives.float_ops import copysign_op, int_to_float_op\nfrom mypyc.primitives.generic_ops import (\n    generic_len_op,\n    generic_ssize_t_len_op,\n    py_call_op,\n    py_call_with_kwargs_op,\n    py_call_with_posargs_op,\n    py_getattr_op,\n    py_method_call_op,\n    py_vectorcall_method_op,\n    py_vectorcall_op,\n)\nfrom mypyc.primitives.int_ops import (\n    int16_divide_op,\n    int16_mod_op,\n    int16_overflow,\n    int32_divide_op,\n    int32_mod_op,\n    int32_overflow,\n    int64_divide_op,\n    int64_mod_op,\n    int64_to_int_op,\n    int_to_int32_op,\n    int_to_int64_op,\n    ssize_t_to_int_op,\n    uint8_overflow,\n)\nfrom mypyc.primitives.list_ops import list_build_op, list_extend_op, list_items, new_list_op\nfrom mypyc.primitives.misc_ops import (\n    bool_op,\n    buf_init_item,\n    debug_print_op,\n    fast_isinstance_op,\n    none_object_op,\n    not_implemented_op,\n    set_immortal_op,\n    var_object_size,\n)\nfrom mypyc.primitives.registry import (\n    ERR_NEG_INT,\n    CFunctionDescription,\n    binary_ops,\n    function_ops,\n    method_call_ops,\n    unary_ops,\n)\nfrom mypyc.primitives.set_ops import new_set_op\nfrom mypyc.primitives.str_ops import (\n    str_check_if_true,\n    str_eq,\n    str_eq_literal,\n    str_ssize_t_size_op,\n    unicode_compare,\n)\nfrom mypyc.primitives.tuple_ops import (\n    list_tuple_op,\n    load_empty_tuple_constant_op,\n    new_tuple_op,\n    new_tuple_with_length_op,\n    sequence_tuple_op,\n)\nfrom mypyc.rt_subtype import is_runtime_subtype\nfrom mypyc.sametype import is_same_type\nfrom mypyc.subtype import is_subtype\n\nDictEntry = tuple[Value | None, Value]\n\n# If the number of items is less than the threshold when initializing\n# a list, we would inline the generate IR using SetMem and expanded\n# for-loop. Otherwise, we would call `list_build_op` for larger lists.\n# TODO: The threshold is a randomly chosen number which needs further\n#       study on real-world projects for a better balance.\nLIST_BUILDING_EXPANSION_THRESHOLD = 10\n\n# From CPython\nPY_VECTORCALL_ARGUMENTS_OFFSET: Final = 1 << (PLATFORM_SIZE * 8 - 1)\n\nFIXED_WIDTH_INT_BINARY_OPS: Final = {\n    \"+\",\n    \"-\",\n    \"*\",\n    \"//\",\n    \"%\",\n    \"&\",\n    \"|\",\n    \"^\",\n    \"<<\",\n    \">>\",\n    \"+=\",\n    \"-=\",\n    \"*=\",\n    \"//=\",\n    \"%=\",\n    \"&=\",\n    \"|=\",\n    \"^=\",\n    \"<<=\",\n    \">>=\",\n}\n\n# Binary operations on bools that are specialized and don't just promote operands to int\nBOOL_BINARY_OPS: Final = {\"&\", \"&=\", \"|\", \"|=\", \"^\", \"^=\", \"==\", \"!=\", \"<\", \"<=\", \">\", \">=\"}\n\n\nclass LowLevelIRBuilder:\n    \"\"\"A \"low-level\" IR builder class.\n\n    LowLevelIRBuilder provides core abstractions we use for constructing\n    IR as well as a number of higher-level ones (accessing attributes,\n    calling functions and methods, and coercing between types, for\n    example).\n\n    The core principle of the low-level IR builder is that all of its\n    facilities operate solely on the mypyc IR level and not the mypy AST\n    level---it has *no knowledge* of mypy types or expressions.\n\n    The mypyc.irbuilder.builder.IRBuilder class wraps an instance of this\n    class and provides additional functionality to transform mypy AST nodes\n    to IR.\n    \"\"\"\n\n    def __init__(self, errors: Errors | None, options: CompilerOptions) -> None:\n        self.errors = errors\n        self.options = options\n        self.args: list[Register] = []\n        self.blocks: list[BasicBlock] = []\n        # Stack of except handler entry blocks\n        self.error_handlers: list[BasicBlock | None] = [None]\n        # Values that we need to keep alive as long as we have borrowed\n        # temporaries. Use flush_keep_alives() to mark the end of the live range.\n        self.keep_alives: list[Value] = []\n\n    def set_module(self, module_name: str, module_path: str) -> None:\n        \"\"\"Set the name and path of the current module.\"\"\"\n        self.module_name = module_name\n        self.module_path = module_path\n\n    # Basic operations\n\n    def add(self, op: Op) -> Value:\n        \"\"\"Add an op.\"\"\"\n        assert not self.blocks[-1].terminated, \"Can't add to finished block\"\n        self.blocks[-1].ops.append(op)\n        return op\n\n    def assign(self, lvalue: Register, rvalue: Value | int) -> None:\n        if isinstance(rvalue, int):\n            rvalue = Integer(rvalue, lvalue.type)\n        self.add(Assign(lvalue, rvalue))\n\n    def goto(self, target: BasicBlock) -> None:\n        \"\"\"Add goto to a basic block.\"\"\"\n        if not self.blocks[-1].terminated:\n            self.add(Goto(target))\n\n    def activate_block(self, block: BasicBlock) -> None:\n        \"\"\"Add a basic block and make it the active one (target of adds).\"\"\"\n        if self.blocks:\n            assert self.blocks[-1].terminated\n\n        block.error_handler = self.error_handlers[-1]\n        self.blocks.append(block)\n\n    def goto_and_activate(self, block: BasicBlock) -> None:\n        \"\"\"Add goto a block and make it the active block.\"\"\"\n        self.goto(block)\n        self.activate_block(block)\n\n    def keep_alive(self, values: list[Value], line: int, *, steal: bool = False) -> None:\n        self.add(KeepAlive(values, line, steal=steal))\n\n    def load_mem(self, ptr: Value, value_type: RType, *, borrow: bool = False) -> Value:\n        return self.add(LoadMem(value_type, ptr, borrow=borrow))\n\n    def set_mem(self, ptr: Value, value_type: RType, value: Value) -> None:\n        self.add(SetMem(value_type, ptr, value, line=-1))\n\n    def get_element(self, reg: Value, field: str) -> Value:\n        return self.add(GetElement(reg, field))\n\n    def load_address(self, name: str, rtype: RType) -> Value:\n        return self.add(LoadAddress(rtype, name))\n\n    def load_struct_field(\n        self, ptr: Value, struct: RStruct, field: str, *, borrow: bool = False\n    ) -> Value:\n        address = self.add(GetElementPtr(ptr, struct, field))\n        return self.load_mem(address, struct.field_type(field), borrow=borrow)\n\n    def set_struct_field(\n        self, ptr: Value, struct: RStruct, field: str, value: Value, line: int\n    ) -> None:\n        address = self.add(GetElementPtr(ptr, struct, field))\n        field_type = struct.field_type(field)\n        value = self.coerce(value, field_type, line)\n        self.set_mem(address, field_type, value)\n        self.keep_alive([ptr], line)\n\n    def push_error_handler(self, handler: BasicBlock | None) -> None:\n        self.error_handlers.append(handler)\n\n    def pop_error_handler(self) -> BasicBlock | None:\n        return self.error_handlers.pop()\n\n    def self(self) -> Register:\n        \"\"\"Return reference to the 'self' argument.\n\n        This only works in a method.\n        \"\"\"\n        return self.args[0]\n\n    def flush_keep_alives(self, line: int) -> None:\n        if self.keep_alives:\n            self.add(KeepAlive(self.keep_alives.copy(), line))\n            self.keep_alives = []\n\n    def debug_print(self, toprint: str | Value) -> None:\n        if isinstance(toprint, str):\n            toprint = self.load_str(toprint)\n        self.primitive_op(debug_print_op, [toprint], -1)\n\n    # Type conversions\n\n    def box(self, src: Value) -> Value:\n        if src.type.is_unboxed:\n            if isinstance(src, Integer) and is_tagged(src.type):\n                return self.add(LoadLiteral(src.value >> 1, rtype=object_rprimitive))\n            return self.add(Box(src, src.line))\n        else:\n            return src\n\n    def unbox_or_cast(\n        self,\n        src: Value,\n        target_type: RType,\n        line: int,\n        *,\n        can_borrow: bool = False,\n        unchecked: bool = False,\n    ) -> Value:\n        if target_type.is_unboxed:\n            return self.add(Unbox(src, target_type, line))\n        else:\n            if can_borrow:\n                self.keep_alives.append(src)\n            return self.add(Cast(src, target_type, line, borrow=can_borrow, unchecked=unchecked))\n\n    def coerce(\n        self,\n        src: Value,\n        target_type: RType,\n        line: int,\n        force: bool = False,\n        *,\n        can_borrow: bool = False,\n    ) -> Value:\n        \"\"\"Generate a coercion/cast from one type to other (only if needed).\n\n        For example, int -> object boxes the source int; int -> int emits nothing;\n        object -> int unboxes the object. All conversions preserve object value.\n\n        If force is true, always generate an op (even if it is just an assignment) so\n        that the result will have exactly target_type as the type.\n\n        Returns the register with the converted value (may be same as src).\n        \"\"\"\n        src_type = src.type\n        if src_type.is_unboxed and not target_type.is_unboxed:\n            # Unboxed -> boxed\n            return self.box(src)\n        if (src_type.is_unboxed and target_type.is_unboxed) and not is_runtime_subtype(\n            src_type, target_type\n        ):\n            if (\n                isinstance(src, Integer)\n                and is_short_int_rprimitive(src_type)\n                and is_fixed_width_rtype(target_type)\n            ):\n                value = src.numeric_value()\n                if not check_native_int_range(target_type, value):\n                    self.error(f'Value {value} is out of range for \"{target_type}\"', line)\n                return Integer(src.value >> 1, target_type)\n            elif is_int_rprimitive(src_type) and is_fixed_width_rtype(target_type):\n                return self.coerce_int_to_fixed_width(src, target_type, line)\n            elif is_fixed_width_rtype(src_type) and is_int_rprimitive(target_type):\n                return self.coerce_fixed_width_to_int(src, line)\n            elif is_short_int_rprimitive(src_type) and is_fixed_width_rtype(target_type):\n                return self.coerce_short_int_to_fixed_width(src, target_type, line)\n            elif (\n                isinstance(src_type, RPrimitive)\n                and isinstance(target_type, RPrimitive)\n                and src_type.is_native_int\n                and target_type.is_native_int\n                and src_type.size <= target_type.size\n                and src_type.is_signed == target_type.is_signed\n            ):\n                if src_type.size == target_type.size:\n                    # Equivalent types\n                    return src\n                else:\n                    # Extend to larger type\n                    return self.add(Extend(src, target_type, target_type.is_signed, line))\n            elif is_int64_rprimitive(src_type) and is_c_py_ssize_t_rprimitive(target_type):\n                return self.coerce_i64_to_ssize_t(src, line)\n            elif is_bool_or_bit_rprimitive(src_type) and is_tagged(target_type):\n                shifted = self.int_op(\n                    bool_rprimitive, src, Integer(1, bool_rprimitive), IntOp.LEFT_SHIFT\n                )\n                return self.add(Extend(shifted, target_type, signed=False))\n            elif is_bool_or_bit_rprimitive(src_type) and is_fixed_width_rtype(target_type):\n                return self.add(Extend(src, target_type, signed=False))\n            elif isinstance(src, Integer) and is_float_rprimitive(target_type):\n                if is_tagged(src_type):\n                    return Float(float(src.value // 2))\n                return Float(float(src.value))\n            elif is_tagged(src_type) and is_float_rprimitive(target_type):\n                return self.int_to_float(src, line)\n            elif (\n                isinstance(src_type, RTuple)\n                and isinstance(target_type, RTuple)\n                and len(src_type.types) == len(target_type.types)\n            ):\n                # Coerce between two tuple types by coercing each item separately\n                values = []\n                for i in range(len(src_type.types)):\n                    v = None\n                    if isinstance(src, TupleSet):\n                        item = src.items[i]\n                        # We can't reuse register values, since they can be modified.\n                        if not isinstance(item, Register):\n                            v = item\n                    if v is None:\n                        v = TupleGet(src, i)\n                        self.add(v)\n                    values.append(v)\n                return self.add(\n                    TupleSet(\n                        [self.coerce(v, t, line) for v, t in zip(values, target_type.types)], line\n                    )\n                )\n            # To go between any other unboxed types, we go through a boxed\n            # in-between value, for simplicity.\n            tmp = self.box(src)\n            return self.unbox_or_cast(tmp, target_type, line)\n        if (not src_type.is_unboxed and target_type.is_unboxed) or not is_subtype(\n            src_type, target_type\n        ):\n            return self.unbox_or_cast(src, target_type, line, can_borrow=can_borrow)\n        elif force:\n            tmp = Register(target_type)\n            self.add(Assign(tmp, src, line))\n            return tmp\n        return src\n\n    def coerce_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:\n        assert is_fixed_width_rtype(target_type), target_type\n        assert isinstance(target_type, RPrimitive), target_type\n\n        fast, slow, end = BasicBlock(), BasicBlock(), BasicBlock()\n\n        check = self.check_tagged_short_int(src, line)\n        self.add(Branch(check, fast, slow, Branch.BOOL))\n\n        self.activate_block(fast)\n\n        size = target_type.size\n        if size < int_rprimitive.size:\n            # Add a range check when the target type is smaller than the source type\n            # Use helper method to generate range checking and conversion\n            res = self.coerce_tagged_to_fixed_width_with_range_check(\n                src, target_type, int_rprimitive.size, slow, end, line\n            )\n        else:\n            # No range check needed when target is same size or larger\n            if size > int_rprimitive.size:\n                tmp = self.add(Extend(src, target_type, signed=True))\n            else:\n                tmp = src\n            tmp = self.int_op(target_type, tmp, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)\n            res = Register(target_type)\n            self.add(Assign(res, tmp))\n            self.goto(end)\n\n        self.activate_block(slow)\n        if is_int64_rprimitive(target_type) or (\n            is_int32_rprimitive(target_type) and size == int_rprimitive.size\n        ):\n            # Slow path calls a library function that handles more complex logic\n            ptr = self.int_op(\n                pointer_rprimitive, src, Integer(1, pointer_rprimitive), IntOp.XOR, line\n            )\n            ptr2 = Register(c_pointer_rprimitive)\n            self.add(Assign(ptr2, ptr))\n            if is_int64_rprimitive(target_type):\n                conv_op = int_to_int64_op\n            else:\n                conv_op = int_to_int32_op\n            tmp = self.call_c(conv_op, [ptr2], line)\n            self.add(Assign(res, tmp))\n            self.add(KeepAlive([src]))\n            self.goto(end)\n        else:\n            # Slow path just always generates an OverflowError\n            self.emit_fixed_width_overflow_error(target_type, line)\n\n        self.activate_block(end)\n        return res\n\n    def check_fixed_width_range(\n        self, src: Value, target_type: RPrimitive, overflow_block: BasicBlock, line: int\n    ) -> None:\n        \"\"\"Check if src fits in target_type range, branch to overflow_block if not.\n\n        On success, continues in a newly activated block where the value is\n        known to be in range.\n\n        Args:\n            src: Source value to check\n            target_type: Target fixed-width type defining the valid range\n            overflow_block: Block to branch to if value is out of range\n            line: Line number\n        \"\"\"\n        in_range, in_range2 = BasicBlock(), BasicBlock()\n\n        size = target_type.size\n        upper_bound = 1 << (size * 8 - 1)\n        if not target_type.is_signed:\n            upper_bound *= 2\n\n        # Check if value < upper_bound\n        check_upper = self.add(\n            ComparisonOp(src, Integer(upper_bound, src.type), ComparisonOp.SLT, line)\n        )\n        self.add(Branch(check_upper, in_range, overflow_block, Branch.BOOL, line))\n\n        self.activate_block(in_range)\n\n        # Check if value >= lower_bound\n        if target_type.is_signed:\n            lower_bound = -upper_bound\n        else:\n            lower_bound = 0\n        check_lower = self.add(\n            ComparisonOp(src, Integer(lower_bound, src.type), ComparisonOp.SGE, line)\n        )\n        self.add(Branch(check_lower, in_range2, overflow_block, Branch.BOOL, line))\n\n        self.activate_block(in_range2)\n\n    def coerce_tagged_to_fixed_width_with_range_check(\n        self,\n        src: Value,\n        target_type: RType,\n        source_size: int,\n        overflow_block: BasicBlock,\n        success_block: BasicBlock,\n        line: int,\n    ) -> Register:\n        \"\"\"Helper to convert a tagged value to a smaller fixed-width type with range checking.\n\n        This method generates IR for converting a tagged integer (like short_int or the fast\n        path of int) to a smaller fixed-width type (i32, i16, uint8) with overflow detection.\n\n        The method performs range checks and branches to overflow_block on failure, or\n        success_block on success (after assigning the result to a register).\n\n        Args:\n            src: Tagged source value (with tag bit set)\n            target_type: Target fixed-width type (must be smaller than source_size)\n            source_size: Size in bytes of the source type\n            overflow_block: Block to branch to on overflow\n            success_block: Block to goto after successful conversion\n            line: Line number\n\n        Returns:\n            Result register containing the converted value (valid in success_block)\n        \"\"\"\n        assert is_fixed_width_rtype(target_type), target_type\n        assert isinstance(target_type, RPrimitive), target_type\n        size = target_type.size\n        assert size < source_size, (target_type, size, source_size)\n\n        res = Register(target_type)\n\n        self.check_fixed_width_range(src, target_type, overflow_block, line)\n\n        # Value is in range - shift right to remove tag, then truncate\n        shifted = self.int_op(\n            c_pyssize_t_rprimitive,\n            src,\n            Integer(1, c_pyssize_t_rprimitive),\n            IntOp.RIGHT_SHIFT,\n            line,\n        )\n        tmp = self.add(Truncate(shifted, target_type, line))\n        self.add(Assign(res, tmp, line))\n        self.goto(success_block)\n\n        return res\n\n    def emit_fixed_width_overflow_error(self, target_type: RType, line: int) -> None:\n        \"\"\"Emit overflow error for fixed-width type conversion.\"\"\"\n        if is_int32_rprimitive(target_type):\n            self.call_c(int32_overflow, [], line)\n        elif is_int16_rprimitive(target_type):\n            self.call_c(int16_overflow, [], line)\n        elif is_uint8_rprimitive(target_type):\n            self.call_c(uint8_overflow, [], line)\n        else:\n            assert False, target_type\n        self.add(Unreachable())\n\n    def coerce_short_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:\n        # short_int (CPyTagged) is guaranteed to be a tagged value, never a pointer,\n        # so we don't need the fast/slow path split like coerce_int_to_fixed_width.\n        # However, we still need range checking when target type is smaller than source.\n        assert is_fixed_width_rtype(target_type), target_type\n        assert isinstance(target_type, RPrimitive), target_type\n\n        if is_int64_rprimitive(target_type) or (\n            PLATFORM_SIZE == 4 and is_int32_rprimitive(target_type)\n        ):\n            # No range check needed - target is same size or larger than source\n            return self.int_op(target_type, src, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)\n\n        # Target is smaller than source - need range checking\n        # Use helper method to generate range checking and conversion\n        overflow, end = BasicBlock(), BasicBlock()\n        res = self.coerce_tagged_to_fixed_width_with_range_check(\n            src, target_type, short_int_rprimitive.size, overflow, end, line\n        )\n\n        # Handle overflow case\n        self.activate_block(overflow)\n        self.emit_fixed_width_overflow_error(target_type, line)\n\n        self.activate_block(end)\n        return res\n\n    def coerce_fixed_width_to_int(self, src: Value, line: int) -> Value:\n        if (\n            (is_int32_rprimitive(src.type) and PLATFORM_SIZE == 8)\n            or is_int16_rprimitive(src.type)\n            or is_uint8_rprimitive(src.type)\n        ):\n            # Simple case -- just sign extend and shift.\n            extended = self.add(Extend(src, c_pyssize_t_rprimitive, signed=src.type.is_signed))\n            return self.int_op(\n                int_rprimitive,\n                extended,\n                Integer(1, c_pyssize_t_rprimitive),\n                IntOp.LEFT_SHIFT,\n                line,\n            )\n\n        src_type = src.type\n\n        assert is_fixed_width_rtype(src_type), src_type\n        assert isinstance(src_type, RPrimitive), src_type\n\n        res = Register(int_rprimitive)\n\n        fast, fast2, slow, end = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()\n\n        c1 = self.add(ComparisonOp(src, Integer(MAX_SHORT_INT, src_type), ComparisonOp.SLE, line))\n        self.add(Branch(c1, fast, slow, Branch.BOOL))\n\n        self.activate_block(fast)\n        c2 = self.add(ComparisonOp(src, Integer(MIN_SHORT_INT, src_type), ComparisonOp.SGE, line))\n        self.add(Branch(c2, fast2, slow, Branch.BOOL))\n\n        self.activate_block(slow)\n        if is_int64_rprimitive(src_type):\n            conv_op = int64_to_int_op\n        elif is_int32_rprimitive(src_type):\n            assert PLATFORM_SIZE == 4\n            conv_op = ssize_t_to_int_op\n        else:\n            assert False, src_type\n        x = self.call_c(conv_op, [src], line)\n        self.add(Assign(res, x))\n        self.goto(end)\n\n        self.activate_block(fast2)\n        if int_rprimitive.size < src_type.size:\n            tmp = self.add(Truncate(src, c_pyssize_t_rprimitive))\n        else:\n            tmp = src\n        s = self.int_op(int_rprimitive, tmp, Integer(1, tmp.type), IntOp.LEFT_SHIFT, line)\n        self.add(Assign(res, s))\n        self.goto(end)\n\n        self.activate_block(end)\n        return res\n\n    def coerce_i64_to_ssize_t(self, src: Value, line: int) -> Value:\n        \"\"\"Coerce int64 to c_pyssize_t with range check on 32-bit platforms.\n\n        On 64-bit platforms, this is a no-op since the types have the same size.\n        On 32-bit platforms, raises ValueError if the value doesn't fit in 32 bits.\n        \"\"\"\n        if PLATFORM_SIZE == 8:\n            return src\n\n        # 32-bit platform: need range check\n        overflow, end = BasicBlock(), BasicBlock()\n\n        self.check_fixed_width_range(src, c_pyssize_t_rprimitive, overflow, line)\n\n        # Value is in range - truncate to 32 bits\n        res = self.add(Truncate(src, c_pyssize_t_rprimitive, line))\n        self.goto(end)\n\n        # Handle overflow case\n        self.activate_block(overflow)\n        self.call_c(int32_overflow, [], line)\n        self.add(Unreachable())\n\n        self.activate_block(end)\n        return res\n\n    def coerce_nullable(self, src: Value, target_type: RType, line: int) -> Value:\n        \"\"\"Generate a coercion from a potentially null value.\"\"\"\n        if src.type.is_unboxed == target_type.is_unboxed and (\n            (target_type.is_unboxed and is_runtime_subtype(src.type, target_type))\n            or (not target_type.is_unboxed and is_subtype(src.type, target_type))\n        ):\n            return src\n\n        target = Register(target_type)\n\n        valid, invalid, out = BasicBlock(), BasicBlock(), BasicBlock()\n        self.add(Branch(src, invalid, valid, Branch.IS_ERROR))\n\n        self.activate_block(valid)\n        coerced = self.coerce(src, target_type, line)\n        self.add(Assign(target, coerced, line))\n        self.goto(out)\n\n        self.activate_block(invalid)\n        error = self.add(LoadErrorValue(target_type))\n        self.add(Assign(target, error, line))\n\n        self.goto_and_activate(out)\n        return target\n\n    # Attribute access\n\n    def get_attr(\n        self, obj: Value, attr: str, result_type: RType, line: int, *, borrow: bool = False\n    ) -> Value:\n        \"\"\"Get a native or Python attribute of an object.\"\"\"\n        if (\n            isinstance(obj.type, RInstance)\n            and obj.type.class_ir.is_ext_class\n            and obj.type.class_ir.has_attr(attr)\n        ):\n            op = GetAttr(obj, attr, line, borrow=borrow)\n            # For non-refcounted attribute types, the borrow might be\n            # disabled even if requested, so don't check 'borrow'.\n            if op.is_borrowed:\n                self.keep_alives.append(obj)\n            return self.add(op)\n        elif isinstance(obj.type, RUnion):\n            return self.union_get_attr(obj, obj.type, attr, result_type, line)\n        else:\n            return self.py_get_attr(obj, attr, line)\n\n    def union_get_attr(\n        self, obj: Value, rtype: RUnion, attr: str, result_type: RType, line: int\n    ) -> Value:\n        \"\"\"Get an attribute of an object with a union type.\"\"\"\n\n        def get_item_attr(value: Value) -> Value:\n            return self.get_attr(value, attr, result_type, line)\n\n        return self.decompose_union_helper(obj, rtype, result_type, get_item_attr, line)\n\n    def py_get_attr(self, obj: Value, attr: str, line: int) -> Value:\n        \"\"\"Get a Python attribute (slow).\n\n        Prefer get_attr() which generates optimized code for native classes.\n        \"\"\"\n        key = self.load_str(attr)\n        return self.primitive_op(py_getattr_op, [obj, key], line)\n\n    # isinstance() checks\n\n    def isinstance_helper(self, obj: Value, class_irs: list[ClassIR], line: int) -> Value:\n        \"\"\"Fast path for isinstance() that checks against a list of native classes.\"\"\"\n        if not class_irs:\n            return self.false()\n        ret = self.isinstance_native(obj, class_irs[0], line)\n        for class_ir in class_irs[1:]:\n\n            def other() -> Value:\n                return self.isinstance_native(obj, class_ir, line)\n\n            ret = self.shortcircuit_helper(\"or\", bool_rprimitive, lambda: ret, other, line)\n        return ret\n\n    def get_type_of_obj(self, obj: Value, line: int) -> Value:\n        ob_type_address = self.add(GetElementPtr(obj, PyObject, \"ob_type\", line))\n        ob_type = self.load_mem(ob_type_address, object_rprimitive, borrow=True)\n        self.add(KeepAlive([obj], line))\n        return ob_type\n\n    def type_is_op(self, obj: Value, type_obj: Value, line: int) -> Value:\n        typ = self.get_type_of_obj(obj, line)\n        return self.add(ComparisonOp(typ, type_obj, ComparisonOp.EQ, line))\n\n    def isinstance_native(self, obj: Value, class_ir: ClassIR, line: int) -> Value:\n        \"\"\"Fast isinstance() check for a native class.\n\n        If there are three or fewer concrete (non-trait) classes among the class\n        and all its children, use even faster type comparison checks `type(obj)\n        is typ`.\n        \"\"\"\n        concrete = all_concrete_classes(class_ir)\n        if concrete is None or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1:\n            return self.primitive_op(\n                fast_isinstance_op, [obj, self.get_native_type(class_ir)], line\n            )\n        if not concrete:\n            # There can't be any concrete instance that matches this.\n            return self.false()\n        type_obj = self.get_native_type(concrete[0])\n        ret = self.type_is_op(obj, type_obj, line)\n        for c in concrete[1:]:\n\n            def other() -> Value:\n                return self.type_is_op(obj, self.get_native_type(c), line)\n\n            ret = self.shortcircuit_helper(\"or\", bool_rprimitive, lambda: ret, other, line)\n        return ret\n\n    # Calls\n\n    def _construct_varargs(\n        self,\n        args: Sequence[tuple[Value, ArgKind, str | None]],\n        line: int,\n        *,\n        has_star: bool,\n        has_star2: bool,\n    ) -> tuple[Value | None, Value | None]:\n        \"\"\"Construct *args and **kwargs from a collection of arguments\n\n        This is pretty complicated, and almost all of the complication here stems from\n        one of two things (but mostly the second):\n          * The handling of ARG_STAR/ARG_STAR2. We want to create as much of the args/kwargs\n            values in one go as we can, so we collect values until our hand is forced, and\n            then we emit creation of the list/tuple, and expand it from there if needed.\n\n          * Support potentially nullable argument values. This has very narrow applicability,\n            as this will never be done by our compiled Python code, but is critically used\n            by gen_glue_method when generating glue methods to mediate between the function\n            signature of a parent class and its subclasses.\n\n            For named-only arguments, this is quite simple: if it is\n            null, don't put it in the dict.\n\n            For positional-or-named arguments, things are much more complicated.\n              * First, anything that was passed as a positional arg\n                must be forwarded along as a positional arg. It *must\n                not* be converted to a named arg. This is because mypy\n                does not enforce that positional-or-named arguments\n                have the same name in subclasses, and it is not\n                uncommon for code to have different names in\n                subclasses (a bunch of mypy's visitors do this, for\n                example!). This is arguably a bug in both mypy and code doing\n                this, and they ought to be using positional-only arguments, but\n                positional-only arguments are new and ugly.\n\n              * On the flip side, we're willing to accept the\n                infelicity of sometimes turning an argument that was\n                passed by keyword into a positional argument. It's wrong,\n                but it's very marginal, and avoiding it would require passing\n                a bitmask of which arguments were named with every function call,\n                or something similar.\n                (See some discussion of this in testComplicatedArgs)\n\n            Thus, our strategy for positional-or-named arguments is to\n            always pass them as positional, except in the one\n            situation where we can not, and where we can be absolutely\n            sure they were passed by name: when an *earlier*\n            positional argument was missing its value.\n\n            This means that if we have a method `f(self, x: int=..., y: object=...)`:\n              * x and y present:      args=(x, y), kwargs={}\n              * x present, y missing: args=(x,),   kwargs={}\n              * x missing, y present: args=(),     kwargs={'y': y}\n\n            To implement this, when we have multiple optional\n            positional arguments, we maintain a flag in a register\n            that tracks whether an argument has been missing, and for\n            each such optional argument (except the first), we check\n            the flag to determine whether to append the argument to\n            the *args list or add it to the **kwargs dict. What a\n            mess!\n\n            This is what really makes everything here such a tangle;\n            otherwise the *args and **kwargs code could be separated.\n\n        The arguments has_star and has_star2 indicate whether the target function\n        takes an ARG_STAR and ARG_STAR2 argument, respectively.\n        (These will always be true when making a pycall, and be based\n        on the actual target signature for a native call.)\n        \"\"\"\n\n        star_result: Value | None = None\n        star2_result: Value | None = None\n        # We aggregate values that need to go into *args and **kwargs\n        # in these lists. Once all arguments are processed (in the\n        # happiest case), or we encounter an ARG_STAR/ARG_STAR2 or a\n        # nullable arg, then we create the list and/or dict.\n        star_values: list[Value] = []\n        star2_keys: list[Value] = []\n        star2_values: list[Value] = []\n\n        seen_empty_reg: Register | None = None\n\n        for value, kind, name in args:\n            if kind == ARG_STAR:\n                if star_result is None:\n                    # star args fastpath\n                    if len(args) == 1:\n                        # fn(*args)\n                        if is_list_rprimitive(value.type):\n                            value = self.primitive_op(list_tuple_op, [value], line)\n                        elif not is_tuple_rprimitive(value.type) and not isinstance(\n                            value.type, RTuple\n                        ):\n                            value = self.primitive_op(sequence_tuple_op, [value], line)\n                        return value, None\n                    elif len(args) == 2 and args[1][1] == ARG_STAR2:\n                        # fn(*args, **kwargs)\n                        # TODO: extend to cover(*args, **k, **w, **a, **r, **g, **s)\n                        if is_tuple_rprimitive(value.type) or isinstance(value.type, RTuple):\n                            star_result = value\n                        elif is_list_rprimitive(value.type):\n                            star_result = self.primitive_op(list_tuple_op, [value], line)\n                        else:\n                            star_result = self.primitive_op(sequence_tuple_op, [value], line)\n\n                        star2_arg = args[1]\n                        star2_value = star2_arg[0]\n                        if is_dict_rprimitive(star2_value.type):\n                            star2_fastpath_op = dict_copy_op\n                        else:\n                            star2_fastpath_op = dict_copy\n                        return star_result, self.primitive_op(\n                            star2_fastpath_op, [star2_value], line\n                        )\n                        # elif ...: TODO extend this to optimize fn(*args, k=1, **kwargs) case\n                    # TODO optimize this case using the length utils - currently in review\n                    star_result = self.new_list_op(star_values, line)\n                self.primitive_op(list_extend_op, [star_result, value], line)\n            elif kind == ARG_STAR2:\n                if star2_result is None:\n                    if len(args) == 1:\n                        # early exit with fastpath if the only arg is ARG_STAR2\n                        # TODO: can we maintain an empty tuple in memory and just reuse it again and again?\n                        if is_dict_rprimitive(value.type):\n                            star2_fastpath_op = dict_copy_op\n                        else:\n                            star2_fastpath_op = dict_copy\n                        return self.new_tuple([], line), self.primitive_op(\n                            star2_fastpath_op, [value], line\n                        )\n\n                    star2_result = self._create_dict(star2_keys, star2_values, line)\n\n                self.call_c(dict_update_in_display_op, [star2_result, value], line=line)\n            else:\n                nullable = kind.is_optional()\n                maybe_pos = kind.is_positional() and has_star\n                maybe_named = kind.is_named() or (kind.is_optional() and name and has_star2)\n\n                # If the argument is nullable, we need to create the\n                # relevant args/kwargs objects so that we can\n                # conditionally modify them.\n                if nullable:\n                    if maybe_pos and star_result is None:\n                        star_result = self.new_list_op(star_values, line)\n                    if maybe_named and star2_result is None:\n                        star2_result = self._create_dict(star2_keys, star2_values, line)\n\n                # Easy cases: just collect the argument.\n                if maybe_pos and star_result is None:\n                    star_values.append(value)\n                    continue\n\n                if maybe_named and star2_result is None:\n                    assert name is not None\n                    key = self.load_str(name)\n                    star2_keys.append(key)\n                    star2_values.append(value)\n                    continue\n\n                # OK, anything that is nullable or *after* a nullable arg needs to be here\n                # TODO: We could try harder to avoid creating basic blocks in the common case\n                new_seen_empty_reg = seen_empty_reg\n\n                out = BasicBlock()\n                if nullable:\n                    # If this is the first nullable positional arg we've seen, create\n                    # a register to track whether anything has been null.\n                    # (We won't *check* the register until the next argument, though.)\n                    if maybe_pos and not seen_empty_reg:\n                        new_seen_empty_reg = Register(bool_rprimitive)\n                        self.add(Assign(new_seen_empty_reg, self.false(), line))\n\n                    skip = BasicBlock() if maybe_pos else out\n                    keep = BasicBlock()\n                    self.add(Branch(value, skip, keep, Branch.IS_ERROR))\n                    self.activate_block(keep)\n\n                # If this could be positional or named and we /might/ have seen a missing\n                # positional arg, then we need to compile *both* a positional and named\n                # version! What a pain!\n                if maybe_pos and maybe_named and seen_empty_reg:\n                    pos_block, named_block = BasicBlock(), BasicBlock()\n                    self.add(Branch(seen_empty_reg, named_block, pos_block, Branch.BOOL))\n                else:\n                    pos_block = named_block = BasicBlock()\n                    self.goto(pos_block)\n\n                if maybe_pos:\n                    self.activate_block(pos_block)\n                    assert star_result\n                    self.translate_special_method_call(\n                        star_result, \"append\", [value], result_type=None, line=line\n                    )\n                    self.goto(out)\n\n                if maybe_named and (not maybe_pos or seen_empty_reg):\n                    self.activate_block(named_block)\n                    assert name is not None\n                    key = self.load_str(name)\n                    assert star2_result\n                    self.translate_special_method_call(\n                        star2_result, \"__setitem__\", [key, value], result_type=None, line=line\n                    )\n                    self.goto(out)\n\n                if nullable and maybe_pos and new_seen_empty_reg:\n                    assert skip is not out\n                    self.activate_block(skip)\n                    self.add(Assign(new_seen_empty_reg, self.true(), line))\n                    self.goto(out)\n\n                self.activate_block(out)\n\n                seen_empty_reg = new_seen_empty_reg\n\n        assert not (star_result or star_values) or has_star\n        assert not (star2_result or star2_values) or has_star2\n        if has_star:\n            # If we managed to make it this far without creating a\n            # *args list, then we can directly create a\n            # tuple. Otherwise create the tuple from the list.\n            if star_result is None:\n                star_result = self.new_tuple(star_values, line)\n            elif not is_tuple_rprimitive(star_result.type):\n                # if star_result is a tuple we took the fast path\n                star_result = self.primitive_op(list_tuple_op, [star_result], line)\n        if has_star2 and star2_result is None and len(star2_keys) > 0:\n            # TODO: use dict_copy_op for simple cases of **kwargs\n            star2_result = self._create_dict(star2_keys, star2_values, line)\n\n        return star_result, star2_result\n\n    def py_call(\n        self,\n        function: Value,\n        arg_values: list[Value],\n        line: int,\n        arg_kinds: list[ArgKind] | None = None,\n        arg_names: Sequence[str | None] | None = None,\n    ) -> Value:\n        \"\"\"Call a Python function (non-native and slow).\n\n        Use py_call_op or py_call_with_kwargs_op for Python function call.\n        \"\"\"\n        result = self._py_vector_call(function, arg_values, line, arg_kinds, arg_names)\n        if result is not None:\n            return result\n\n        # If all arguments are positional, we can use py_call_op.\n        if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds):\n            return self.call_c(py_call_op, [function] + arg_values, line)\n\n        # Otherwise fallback to py_call_with_posargs_op or py_call_with_kwargs_op.\n        assert arg_names is not None\n\n        pos_args_tuple, kw_args_dict = self._construct_varargs(\n            list(zip(arg_values, arg_kinds, arg_names)), line, has_star=True, has_star2=True\n        )\n        assert pos_args_tuple\n\n        if kw_args_dict is None:\n            return self.call_c(py_call_with_posargs_op, [function, pos_args_tuple], line)\n\n        return self.call_c(py_call_with_kwargs_op, [function, pos_args_tuple, kw_args_dict], line)\n\n    def _py_vector_call(\n        self,\n        function: Value,\n        arg_values: list[Value],\n        line: int,\n        arg_kinds: list[ArgKind] | None = None,\n        arg_names: Sequence[str | None] | None = None,\n    ) -> Value | None:\n        \"\"\"Call function using the vectorcall API if possible.\n\n        Return the return value if successful. Return None if a non-vectorcall\n        API should be used instead.\n        \"\"\"\n        # We can do this if all args are positional or named (no *args or **kwargs, not optional).\n        if arg_kinds is None or all(\n            not kind.is_star() and not kind.is_optional() for kind in arg_kinds\n        ):\n            if arg_values:\n                # Create a C array containing all arguments as boxed values.\n                coerced_args = [self.coerce(arg, object_rprimitive, line) for arg in arg_values]\n                arg_ptr = self.setup_rarray(object_rprimitive, coerced_args, line, object_ptr=True)\n            else:\n                arg_ptr = Integer(0, object_pointer_rprimitive)\n            num_pos = num_positional_args(arg_values, arg_kinds)\n            keywords = self._vectorcall_keywords(arg_names)\n            value = self.call_c(\n                py_vectorcall_op,\n                [function, arg_ptr, Integer(num_pos, c_size_t_rprimitive), keywords],\n                line,\n            )\n            if arg_values:\n                # Make sure arguments won't be freed until after the call.\n                # We need this because RArray doesn't support automatic\n                # memory management.\n                self.add(KeepAlive(coerced_args, line))\n            return value\n        return None\n\n    def _vectorcall_keywords(self, arg_names: Sequence[str | None] | None) -> Value:\n        \"\"\"Return a reference to a tuple literal with keyword argument names.\n\n        Return null pointer if there are no keyword arguments.\n        \"\"\"\n        if arg_names:\n            kw_list = [name for name in arg_names if name is not None]\n            if kw_list:\n                return self.add(LoadLiteral(tuple(kw_list), object_rprimitive))\n        return Integer(0, object_rprimitive)\n\n    def py_method_call(\n        self,\n        obj: Value,\n        method_name: str,\n        arg_values: list[Value],\n        line: int,\n        arg_kinds: list[ArgKind] | None,\n        arg_names: Sequence[str | None] | None,\n    ) -> Value:\n        \"\"\"Call a Python method (non-native and slow).\"\"\"\n        result = self._py_vector_method_call(\n            obj, method_name, arg_values, line, arg_kinds, arg_names\n        )\n        if result is not None:\n            return result\n\n        if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds):\n            # Use legacy method call API\n            method_name_reg = self.load_str(method_name)\n            return self.call_c(py_method_call_op, [obj, method_name_reg] + arg_values, line)\n        else:\n            # Use py_call since it supports keyword arguments (and vectorcalls).\n            method = self.py_get_attr(obj, method_name, line)\n            return self.py_call(method, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names)\n\n    def _py_vector_method_call(\n        self,\n        obj: Value,\n        method_name: str,\n        arg_values: list[Value],\n        line: int,\n        arg_kinds: list[ArgKind] | None,\n        arg_names: Sequence[str | None] | None,\n    ) -> Value | None:\n        \"\"\"Call method using the vectorcall API if possible.\n\n        Return the return value if successful. Return None if a non-vectorcall\n        API should be used instead.\n        \"\"\"\n        if arg_kinds is None or all(\n            not kind.is_star() and not kind.is_optional() for kind in arg_kinds\n        ):\n            method_name_reg = self.load_str(method_name)\n            coerced_args = [\n                self.coerce(arg, object_rprimitive, line) for arg in [obj] + arg_values\n            ]\n            arg_ptr = self.setup_rarray(object_rprimitive, coerced_args, line, object_ptr=True)\n            num_pos = num_positional_args(arg_values, arg_kinds)\n            keywords = self._vectorcall_keywords(arg_names)\n            value = self.call_c(\n                py_vectorcall_method_op,\n                [\n                    method_name_reg,\n                    arg_ptr,\n                    Integer((num_pos + 1) | PY_VECTORCALL_ARGUMENTS_OFFSET, c_size_t_rprimitive),\n                    keywords,\n                ],\n                line,\n            )\n            # Make sure arguments won't be freed until after the call.\n            # We need this because RArray doesn't support automatic\n            # memory management.\n            self.add(KeepAlive(coerced_args, line))\n            return value\n        return None\n\n    def call(\n        self,\n        decl: FuncDecl,\n        args: Sequence[Value],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None],\n        line: int,\n        *,\n        bitmap_args: list[Register] | None = None,\n    ) -> Value:\n        \"\"\"Call a native function.\n\n        If bitmap_args is given, they override the values of (some) of the bitmap\n        arguments used to track the presence of values for certain arguments. By\n        default, the values of the bitmap arguments are inferred from args.\n        \"\"\"\n        # Normalize args to positionals.\n        args = self.native_args_to_positional(\n            args, arg_kinds, arg_names, decl.sig, line, bitmap_args=bitmap_args\n        )\n        return self.add(Call(decl, args, line))\n\n    def native_args_to_positional(\n        self,\n        args: Sequence[Value],\n        arg_kinds: list[ArgKind],\n        arg_names: Sequence[str | None],\n        sig: FuncSignature,\n        line: int,\n        *,\n        bitmap_args: list[Register] | None = None,\n    ) -> list[Value]:\n        \"\"\"Prepare arguments for a native call.\n\n        Given args/kinds/names and a target signature for a native call, map\n        keyword arguments to their appropriate place in the argument list,\n        fill in error values for unspecified default arguments,\n        package arguments that will go into *args/**kwargs into a tuple/dict,\n        and coerce arguments to the appropriate type.\n        \"\"\"\n\n        sig_args = sig.args\n        n = sig.num_bitmap_args\n        if n:\n            sig_args = sig_args[:-n]\n\n        sig_arg_kinds = [arg.kind for arg in sig_args]\n        sig_arg_names = [arg.name for arg in sig_args]\n\n        concrete_kinds = [concrete_arg_kind(arg_kind) for arg_kind in arg_kinds]\n        formal_to_actual = map_actuals_to_formals(\n            concrete_kinds,\n            arg_names,\n            sig_arg_kinds,\n            sig_arg_names,\n            lambda n: AnyType(TypeOfAny.special_form),\n        )\n\n        # First scan for */** and construct those\n        has_star = has_star2 = False\n        star_arg_entries = []\n        for lst, arg in zip(formal_to_actual, sig_args):\n            if arg.kind.is_star():\n                star_arg_entries.extend([(args[i], arg_kinds[i], arg_names[i]) for i in lst])\n            has_star = has_star or arg.kind == ARG_STAR\n            has_star2 = has_star2 or arg.kind == ARG_STAR2\n\n        star_arg, star2_arg = self._construct_varargs(\n            star_arg_entries, line, has_star=has_star, has_star2=has_star2\n        )\n\n        # Flatten out the arguments, loading error values for default\n        # arguments, constructing tuples/dicts for star args, and\n        # coercing everything to the expected type.\n        output_args: list[Value] = []\n        for lst, arg in zip(formal_to_actual, sig_args):\n            if arg.kind == ARG_STAR:\n                assert star_arg\n                output_arg = star_arg\n            elif arg.kind == ARG_STAR2:\n                output_arg = star2_arg or self._create_dict([], [], line)\n            elif not lst:\n                if is_fixed_width_rtype(arg.type):\n                    output_arg = Integer(0, arg.type)\n                elif is_float_rprimitive(arg.type):\n                    output_arg = Float(0.0)\n                else:\n                    output_arg = self.add(LoadErrorValue(arg.type, is_borrowed=True))\n            else:\n                base_arg = args[lst[0]]\n\n                if arg_kinds[lst[0]].is_optional():\n                    output_arg = self.coerce_nullable(base_arg, arg.type, line)\n                else:\n                    output_arg = self.coerce(base_arg, arg.type, line)\n\n            output_args.append(output_arg)\n\n        for i in reversed(range(n)):\n            if bitmap_args and i < len(bitmap_args):\n                # Use override provided by caller\n                output_args.append(bitmap_args[i])\n                continue\n            # Infer values of bitmap args\n            bitmap = 0\n            c = 0\n            for lst, arg in zip(formal_to_actual, sig_args):\n                if arg.kind.is_optional() and arg.type.error_overlap:\n                    if i * BITMAP_BITS <= c < (i + 1) * BITMAP_BITS:\n                        if lst:\n                            bitmap |= 1 << (c & (BITMAP_BITS - 1))\n                    c += 1\n            output_args.append(Integer(bitmap, bitmap_rprimitive))\n\n        return output_args\n\n    def gen_method_call(\n        self,\n        base: Value,\n        name: str,\n        arg_values: list[Value],\n        result_type: RType | None,\n        line: int,\n        arg_kinds: list[ArgKind] | None = None,\n        arg_names: list[str | None] | None = None,\n        can_borrow: bool = False,\n    ) -> Value:\n        \"\"\"Generate either a native or Python method call.\"\"\"\n        # If we have *args, then fallback to Python method call.\n        if arg_kinds is not None and any(kind.is_star() for kind in arg_kinds):\n            return self.py_method_call(base, name, arg_values, line, arg_kinds, arg_names)\n\n        # If the base type is one of ours, do a MethodCall\n        fast_name = FAST_PREFIX + name\n        if (\n            isinstance(base.type, RInstance)\n            and (base.type.class_ir.is_ext_class or base.type.class_ir.has_method(fast_name))\n            and not base.type.class_ir.builtin_base\n        ):\n            name = name if base.type.class_ir.is_ext_class else fast_name\n            if base.type.class_ir.has_method(name):\n                decl = base.type.class_ir.method_decl(name)\n                if arg_kinds is None:\n                    assert arg_names is None, \"arg_kinds not present but arg_names is\"\n                    arg_kinds = [ARG_POS for _ in arg_values]\n                    arg_names = [None for _ in arg_values]\n                else:\n                    assert arg_names is not None, \"arg_kinds present but arg_names is not\"\n\n                # Normalize args to positionals.\n                assert decl.bound_sig\n                arg_values = self.native_args_to_positional(\n                    arg_values, arg_kinds, arg_names, decl.bound_sig, line\n                )\n                return self.add(MethodCall(base, name, arg_values, line))\n            elif base.type.class_ir.has_attr(name):\n                function = self.add(GetAttr(base, name, line))\n                return self.py_call(\n                    function, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names\n                )\n\n        elif isinstance(base.type, RUnion):\n            return self.union_method_call(\n                base, base.type, name, arg_values, result_type, line, arg_kinds, arg_names\n            )\n\n        # Try to do a special-cased method call\n        if not arg_kinds or arg_kinds == [ARG_POS] * len(arg_values):\n            target = self.translate_special_method_call(\n                base, name, arg_values, result_type, line, can_borrow=can_borrow\n            )\n            if target:\n                return target\n\n        # Fall back to Python method call\n        return self.py_method_call(base, name, arg_values, line, arg_kinds, arg_names)\n\n    def union_method_call(\n        self,\n        base: Value,\n        obj_type: RUnion,\n        name: str,\n        arg_values: list[Value],\n        return_rtype: RType | None,\n        line: int,\n        arg_kinds: list[ArgKind] | None,\n        arg_names: list[str | None] | None,\n    ) -> Value:\n        \"\"\"Generate a method call with a union type for the object.\"\"\"\n        # Union method call needs a return_rtype for the type of the output register.\n        # If we don't have one, use object_rprimitive.\n        return_rtype = return_rtype or object_rprimitive\n\n        def call_union_item(value: Value) -> Value:\n            return self.gen_method_call(\n                value, name, arg_values, return_rtype, line, arg_kinds, arg_names\n            )\n\n        return self.decompose_union_helper(base, obj_type, return_rtype, call_union_item, line)\n\n    # Loading various values\n\n    def none(self, line: int = -1) -> Value:\n        \"\"\"Load unboxed None value (type: none_rprimitive).\"\"\"\n        return Integer(1, none_rprimitive, line)\n\n    def true(self, line: int = -1) -> Value:\n        \"\"\"Load unboxed True value (type: bool_rprimitive).\"\"\"\n        return Integer(1, bool_rprimitive, line)\n\n    def false(self, line: int = -1) -> Value:\n        \"\"\"Load unboxed False value (type: bool_rprimitive).\"\"\"\n        return Integer(0, bool_rprimitive, line)\n\n    def none_object(self, line: int = -1) -> Value:\n        \"\"\"Load Python None value (type: object_rprimitive).\"\"\"\n        return self.add(LoadAddress(none_object_op.type, none_object_op.src, line))\n\n    def true_object(self, line: int = -1) -> Value:\n        \"\"\"Load Python True object (type: object_rprimitive).\"\"\"\n        return self.add(LoadGlobal(object_rprimitive, \"Py_True\", line))\n\n    def false_object(self, line: int = -1) -> Value:\n        \"\"\"Load Python False object (type: object_rprimitive).\"\"\"\n        return self.add(LoadGlobal(object_rprimitive, \"Py_False\", line))\n\n    def load_int(self, value: int, line: int = -1) -> Value:\n        \"\"\"Load a tagged (Python) integer literal value.\"\"\"\n        if value > MAX_LITERAL_SHORT_INT or value < MIN_LITERAL_SHORT_INT:\n            return self.add(LoadLiteral(value, int_rprimitive, line))\n        else:\n            return Integer(value, line=line)\n\n    def load_float(self, value: float, line: int = -1) -> Value:\n        \"\"\"Load a float literal value.\"\"\"\n        return Float(value, line)\n\n    def load_str(self, value: str, line: int = -1) -> Value:\n        \"\"\"Load a str literal value.\n\n        This is useful for more than just str literals; for example, method calls\n        also require a PyObject * form for the name of the method.\n        \"\"\"\n        return self.add(LoadLiteral(value, str_rprimitive, line))\n\n    def load_bytes(self, value: bytes, line: int = -1) -> Value:\n        \"\"\"Load a bytes literal value.\"\"\"\n        return self.add(LoadLiteral(value, bytes_rprimitive, line))\n\n    def load_complex(self, value: complex, line: int = -1) -> Value:\n        \"\"\"Load a complex literal value.\"\"\"\n        return self.add(LoadLiteral(value, object_rprimitive, line))\n\n    def load_static_checked(\n        self,\n        typ: RType,\n        identifier: str,\n        module_name: str | None = None,\n        namespace: str = NAMESPACE_STATIC,\n        line: int = -1,\n        error_msg: str | None = None,\n    ) -> Value:\n        if error_msg is None:\n            error_msg = f'name \"{identifier}\" is not defined'\n        ok_block, error_block = BasicBlock(), BasicBlock()\n        value = self.add(LoadStatic(typ, identifier, module_name, namespace, line=line))\n        self.add(Branch(value, error_block, ok_block, Branch.IS_ERROR, rare=True))\n        self.activate_block(error_block)\n        self.add(RaiseStandardError(RaiseStandardError.NAME_ERROR, error_msg, line))\n        self.add(Unreachable())\n        self.activate_block(ok_block)\n        return value\n\n    def load_module(self, name: str) -> Value:\n        return self.add(LoadStatic(object_rprimitive, name, namespace=NAMESPACE_MODULE))\n\n    def get_native_type(self, cls: ClassIR) -> Value:\n        \"\"\"Load native type object.\"\"\"\n        fullname = f\"{cls.module_name}.{cls.name}\"\n        return self.load_native_type_object(fullname)\n\n    def load_native_type_object(self, fullname: str) -> Value:\n        module, name = fullname.rsplit(\".\", 1)\n        return self.add(LoadStatic(object_rprimitive, name, module, NAMESPACE_TYPE))\n\n    # Other primitive operations\n\n    def binary_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:\n        \"\"\"Perform a binary operation.\n\n        Generate specialized operations based on operand types, with a fallback\n        to generic operations.\n        \"\"\"\n        ltype = lreg.type\n        rtype = rreg.type\n\n        # Special case tuple comparison here so that nested tuples can be supported\n        if isinstance(ltype, RTuple) and isinstance(rtype, RTuple) and op in (\"==\", \"!=\"):\n            return self.compare_tuples(lreg, rreg, op, line)\n\n        # Special case == and != when we can resolve the method call statically\n        if op in (\"==\", \"!=\"):\n            value = self.translate_eq_cmp(lreg, rreg, op, line)\n            if value is not None:\n                return value\n\n        # Special case various ops\n        if op in (\"is\", \"is not\"):\n            return self.translate_is_op(lreg, rreg, op, line)\n        if (\n            is_bool_or_bit_rprimitive(ltype)\n            and is_bool_or_bit_rprimitive(rtype)\n            and op in BOOL_BINARY_OPS\n        ):\n            if op in ComparisonOp.signed_ops:\n                return self.bool_comparison_op(lreg, rreg, op, line)\n            else:\n                return self.bool_bitwise_op(lreg, rreg, op[0], line)\n        if isinstance(rtype, RInstance) and op in (\"in\", \"not in\"):\n            return self.translate_instance_contains(rreg, lreg, op, line)\n        if is_fixed_width_rtype(ltype):\n            if op in FIXED_WIDTH_INT_BINARY_OPS:\n                op = op.removesuffix(\"=\")\n                if op != \"//\":\n                    op_id = int_op_to_id[op]\n                else:\n                    op_id = IntOp.DIV\n                if is_bool_or_bit_rprimitive(rtype):\n                    rreg = self.coerce(rreg, ltype, line)\n                    rtype = ltype\n                if is_fixed_width_rtype(rtype) or is_tagged(rtype):\n                    return self.fixed_width_int_op(ltype, lreg, rreg, op_id, line)\n                if isinstance(rreg, Integer):\n                    return self.fixed_width_int_op(\n                        ltype, lreg, self.coerce(rreg, ltype, line), op_id, line\n                    )\n            elif op in ComparisonOp.signed_ops:\n                if is_int_rprimitive(rtype):\n                    rreg = self.coerce_int_to_fixed_width(rreg, ltype, line)\n                elif is_bool_or_bit_rprimitive(rtype):\n                    rreg = self.coerce(rreg, ltype, line)\n                op_id = ComparisonOp.signed_ops[op]\n                if is_fixed_width_rtype(rreg.type):\n                    return self.comparison_op(lreg, rreg, op_id, line)\n                if isinstance(rreg, Integer):\n                    return self.comparison_op(lreg, self.coerce(rreg, ltype, line), op_id, line)\n        elif is_fixed_width_rtype(rtype):\n            if op in FIXED_WIDTH_INT_BINARY_OPS:\n                op = op.removesuffix(\"=\")\n                if op != \"//\":\n                    op_id = int_op_to_id[op]\n                else:\n                    op_id = IntOp.DIV\n                if isinstance(lreg, Integer):\n                    return self.fixed_width_int_op(\n                        rtype, self.coerce(lreg, rtype, line), rreg, op_id, line\n                    )\n                if is_tagged(ltype):\n                    return self.fixed_width_int_op(rtype, lreg, rreg, op_id, line)\n                if is_bool_or_bit_rprimitive(ltype):\n                    lreg = self.coerce(lreg, rtype, line)\n                    return self.fixed_width_int_op(rtype, lreg, rreg, op_id, line)\n            elif op in ComparisonOp.signed_ops:\n                if is_int_rprimitive(ltype):\n                    lreg = self.coerce_int_to_fixed_width(lreg, rtype, line)\n                elif is_bool_or_bit_rprimitive(ltype):\n                    lreg = self.coerce(lreg, rtype, line)\n                op_id = ComparisonOp.signed_ops[op]\n                if isinstance(lreg, Integer):\n                    return self.comparison_op(self.coerce(lreg, rtype, line), rreg, op_id, line)\n                if is_fixed_width_rtype(lreg.type):\n                    return self.comparison_op(lreg, rreg, op_id, line)\n\n        if is_float_rprimitive(ltype) or is_float_rprimitive(rtype):\n            if isinstance(lreg, Integer):\n                lreg = Float(float(lreg.numeric_value()))\n            elif isinstance(rreg, Integer):\n                rreg = Float(float(rreg.numeric_value()))\n            elif is_int_rprimitive(lreg.type):\n                lreg = self.int_to_float(lreg, line)\n            elif is_int_rprimitive(rreg.type):\n                rreg = self.int_to_float(rreg, line)\n            if is_float_rprimitive(lreg.type) and is_float_rprimitive(rreg.type):\n                if op in float_comparison_op_to_id:\n                    return self.compare_floats(lreg, rreg, float_comparison_op_to_id[op], line)\n                if op.endswith(\"=\"):\n                    base_op = op[:-1]\n                else:\n                    base_op = op\n                if base_op in float_op_to_id:\n                    return self.float_op(lreg, rreg, base_op, line)\n\n        dunder_op = self.dunder_op(lreg, rreg, op, line)\n        if dunder_op:\n            return dunder_op\n\n        if isinstance(rtype, RVec) and op == \"in\":\n            return vec_contains(self, rreg, lreg, line)\n\n        primitive_ops_candidates = binary_ops.get(op, [])\n        target = self.matching_primitive_op(primitive_ops_candidates, [lreg, rreg], line)\n        assert target, \"Unsupported binary operation: %s\" % op\n        return target\n\n    def dunder_op(self, lreg: Value, rreg: Value | None, op: str, line: int) -> Value | None:\n        \"\"\"\n        Dispatch a dunder method if applicable.\n\n        For example for `a + b` it will use `a.__add__(b)` which can lead to higher performance\n        due to the fact that the method could be already compiled and optimized instead of going\n        all the way through `PyNumber_Add(a, b)` python api (making a jump into the python DL).\n        \"\"\"\n        ltype = lreg.type\n        if not isinstance(ltype, RInstance):\n            return None\n\n        method_name = op_methods.get(op) if rreg else unary_op_methods.get(op)\n        if method_name is None:\n            return None\n\n        if not ltype.class_ir.has_method(method_name):\n            return None\n\n        decl = ltype.class_ir.method_decl(method_name)\n        if not rreg and len(decl.sig.args) != 1:\n            return None\n\n        if rreg and (len(decl.sig.args) != 2 or not is_subtype(rreg.type, decl.sig.args[1].type)):\n            return None\n\n        if rreg and is_subtype(not_implemented_op.type, decl.sig.ret_type):\n            # If the method is able to return NotImplemented, we should not optimize it.\n            # We can just let go so it will be handled through the python api.\n            return None\n\n        args = [rreg] if rreg else []\n        return self.gen_method_call(lreg, method_name, args, decl.sig.ret_type, line)\n\n    def check_tagged_short_int(self, val: Value, line: int, negated: bool = False) -> Value:\n        \"\"\"Check if a tagged integer is a short integer.\n\n        Return the result of the check (value of type 'bit').\n        \"\"\"\n        int_tag = Integer(1, c_pyssize_t_rprimitive, line)\n        bitwise_and = self.int_op(c_pyssize_t_rprimitive, val, int_tag, IntOp.AND, line)\n        zero = Integer(0, c_pyssize_t_rprimitive, line)\n        op = ComparisonOp.NEQ if negated else ComparisonOp.EQ\n        check = self.comparison_op(bitwise_and, zero, op, line)\n        return check\n\n    def compare_strings(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:\n        \"\"\"Compare two strings\"\"\"\n        if op == \"==\":\n            # We can specialize this case if one or both values are string literals\n            literal_fastpath = False\n\n            def is_string_literal(value: Value) -> TypeGuard[LoadLiteral]:\n                return isinstance(value, LoadLiteral) and is_str_rprimitive(value.type)\n\n            if is_string_literal(lhs):\n                if is_string_literal(rhs):\n                    # we can optimize out the check entirely in some constant-folded cases\n                    return self.true() if lhs.value == rhs.value else self.false()\n\n                # if lhs argument is string literal, switch sides to match specializer C api\n                lhs, rhs = rhs, lhs\n                literal_fastpath = True\n            elif is_string_literal(rhs):\n                literal_fastpath = True\n\n            if literal_fastpath:\n                literal_string = cast(str, cast(LoadLiteral, rhs).value)\n                literal_length = Integer(len(literal_string), c_pyssize_t_rprimitive, line)\n                return self.primitive_op(str_eq_literal, [lhs, rhs, literal_length], line)\n\n            return self.primitive_op(str_eq, [lhs, rhs], line)\n\n        elif op == \"!=\":\n            # perform a standard equality check, then negate\n            eq = self.compare_strings(lhs, rhs, \"==\", line)\n            return self.add(ComparisonOp(eq, self.false(), ComparisonOp.EQ, line))\n\n        # TODO: modify 'str' to use same interface as 'compare_bytes' as it would avoid\n        # call to PyErr_Occurred() below\n\n        compare_result = self.call_c(unicode_compare, [lhs, rhs], line)\n        error_constant = Integer(-1, c_int_rprimitive, line)\n        compare_error_check = self.add(\n            ComparisonOp(compare_result, error_constant, ComparisonOp.EQ, line)\n        )\n        exception_check, propagate, final_compare = BasicBlock(), BasicBlock(), BasicBlock()\n        branch = Branch(compare_error_check, exception_check, final_compare, Branch.BOOL)\n        branch.negated = False\n        self.add(branch)\n        self.activate_block(exception_check)\n        check_error_result = self.call_c(err_occurred_op, [], line)\n        null = Integer(0, pointer_rprimitive, line)\n        compare_error_check = self.add(\n            ComparisonOp(check_error_result, null, ComparisonOp.NEQ, line)\n        )\n        branch = Branch(compare_error_check, propagate, final_compare, Branch.BOOL)\n        branch.negated = False\n        self.add(branch)\n        self.activate_block(propagate)\n        self.call_c(keep_propagating_op, [], line)\n        self.goto(final_compare)\n        self.activate_block(final_compare)\n        op_type = ComparisonOp.EQ if op == \"==\" else ComparisonOp.NEQ\n        return self.add(ComparisonOp(compare_result, Integer(0, c_int_rprimitive), op_type, line))\n\n    def compare_bytes(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:\n        compare_result = self.call_c(bytes_compare, [lhs, rhs], line)\n        op_type = ComparisonOp.EQ if op == \"==\" else ComparisonOp.NEQ\n        return self.add(ComparisonOp(compare_result, Integer(1, c_int_rprimitive), op_type, line))\n\n    def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int = -1) -> Value:\n        \"\"\"Compare two tuples item by item\"\"\"\n        # type cast to pass mypy check\n        assert isinstance(lhs.type, RTuple) and isinstance(rhs.type, RTuple), (lhs.type, rhs.type)\n        equal = True if op == \"==\" else False\n        result = Register(bool_rprimitive)\n        # tuples of different lengths\n        if len(lhs.type.types) != len(rhs.type.types):\n            self.add(Assign(result, self.false() if equal else self.true(), line))\n            return result\n        # empty tuples\n        if len(lhs.type.types) == 0 and len(rhs.type.types) == 0:\n            self.add(Assign(result, self.true() if equal else self.false(), line))\n            return result\n        length = len(lhs.type.types)\n        false_assign, true_assign, out = BasicBlock(), BasicBlock(), BasicBlock()\n        check_blocks = [BasicBlock() for _ in range(length)]\n        lhs_items = [self.add(TupleGet(lhs, i, line)) for i in range(length)]\n        rhs_items = [self.add(TupleGet(rhs, i, line)) for i in range(length)]\n\n        if equal:\n            early_stop, final = false_assign, true_assign\n        else:\n            early_stop, final = true_assign, false_assign\n\n        for i in range(len(lhs.type.types)):\n            if i != 0:\n                self.activate_block(check_blocks[i])\n            lhs_item = lhs_items[i]\n            rhs_item = rhs_items[i]\n            compare = self.binary_op(lhs_item, rhs_item, op, line)\n            # Cast to bool if necessary since most types uses comparison returning a object type\n            # See generic_ops.py for more information\n            if not is_bool_or_bit_rprimitive(compare.type):\n                compare = self.primitive_op(bool_op, [compare], line)\n            if i < len(lhs.type.types) - 1:\n                branch = Branch(compare, early_stop, check_blocks[i + 1], Branch.BOOL)\n            else:\n                branch = Branch(compare, early_stop, final, Branch.BOOL)\n            # if op is ==, we branch on false, else branch on true\n            branch.negated = equal\n            self.add(branch)\n        self.activate_block(false_assign)\n        self.add(Assign(result, self.false(), line))\n        self.goto(out)\n        self.activate_block(true_assign)\n        self.add(Assign(result, self.true(), line))\n        self.goto_and_activate(out)\n        return result\n\n    def translate_instance_contains(self, inst: Value, item: Value, op: str, line: int) -> Value:\n        res = self.gen_method_call(inst, \"__contains__\", [item], None, line)\n        if not is_bool_or_bit_rprimitive(res.type):\n            res = self.primitive_op(bool_op, [res], line)\n        if op == \"not in\":\n            res = self.bool_bitwise_op(res, Integer(1, rtype=bool_rprimitive), \"^\", line)\n        return res\n\n    def bool_bitwise_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:\n        if op == \"&\":\n            code = IntOp.AND\n        elif op == \"|\":\n            code = IntOp.OR\n        elif op == \"^\":\n            code = IntOp.XOR\n        else:\n            assert False, op\n        return self.add(IntOp(bool_rprimitive, lreg, rreg, code, line))\n\n    def bool_comparison_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:\n        op_id = ComparisonOp.signed_ops[op]\n        return self.comparison_op(lreg, rreg, op_id, line)\n\n    def _non_specialized_unary_op(self, value: Value, op: str, line: int) -> Value:\n        if isinstance(value.type, RInstance):\n            result = self.dunder_op(value, None, op, line)\n            if result is not None:\n                return result\n        primitive_ops_candidates = unary_ops.get(op, [])\n        target = self.matching_primitive_op(primitive_ops_candidates, [value], line)\n        assert target, \"Unsupported unary operation: %s\" % op\n        return target\n\n    def unary_not(self, value: Value, line: int, *, likely_bool: bool = False) -> Value:\n        \"\"\"Perform unary 'not'.\n\n        Args:\n            likely_bool: The operand is likely a bool value, even if the type is something\n                more general, so specialize for bool values\n        \"\"\"\n        typ = value.type\n        if is_bool_or_bit_rprimitive(typ):\n            mask = Integer(1, typ, line)\n            return self.int_op(typ, value, mask, IntOp.XOR, line)\n        if is_tagged(typ) or is_fixed_width_rtype(typ):\n            return self.binary_op(value, Integer(0), \"==\", line)\n        if (\n            is_str_rprimitive(typ)\n            or is_list_rprimitive(typ)\n            or is_tuple_rprimitive(typ)\n            or is_dict_rprimitive(typ)\n            or isinstance(typ, RInstance)\n        ):\n            bool_val = self.bool_value(value)\n            return self.unary_not(bool_val, line)\n        if is_optional_type(typ):\n            value_typ = optional_value_type(typ)\n            assert value_typ\n            if (\n                is_str_rprimitive(value_typ)\n                or is_list_rprimitive(value_typ)\n                or is_tuple_rprimitive(value_typ)\n                or is_dict_rprimitive(value_typ)\n                or isinstance(value_typ, RInstance)\n            ):\n                # 'X | None' type: Check for None first and then specialize for X.\n                res = Register(bit_rprimitive)\n                cmp = self.add(ComparisonOp(value, self.none_object(), ComparisonOp.EQ, line))\n                none, not_none, out = BasicBlock(), BasicBlock(), BasicBlock()\n                self.add(Branch(cmp, none, not_none, Branch.BOOL))\n                self.activate_block(none)\n                self.add(Assign(res, self.true()))\n                self.goto(out)\n                self.activate_block(not_none)\n                val = self.unary_not(\n                    self.unbox_or_cast(value, value_typ, line, can_borrow=True, unchecked=True),\n                    line,\n                )\n                self.add(Assign(res, val))\n                self.goto(out)\n                self.activate_block(out)\n                return res\n        if likely_bool and is_object_rprimitive(typ):\n            # First quickly check if it's a bool, and otherwise fall back to generic op.\n            res = Register(bit_rprimitive)\n            false, not_false, true, other = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()\n            out = BasicBlock()\n            cmp = self.add(ComparisonOp(value, self.true_object(), ComparisonOp.EQ, line))\n            self.add(Branch(cmp, false, not_false, Branch.BOOL))\n            self.activate_block(false)\n            self.add(Assign(res, self.false()))\n            self.goto(out)\n            self.activate_block(not_false)\n            cmp = self.add(ComparisonOp(value, self.false_object(), ComparisonOp.EQ, line))\n            self.add(Branch(cmp, true, other, Branch.BOOL))\n            self.activate_block(true)\n            self.add(Assign(res, self.true()))\n            self.goto(out)\n            self.activate_block(other)\n            val = self._non_specialized_unary_op(value, \"not\", line)\n            self.add(Assign(res, val))\n            self.goto(out)\n            self.activate_block(out)\n            return res\n        return self._non_specialized_unary_op(value, \"not\", line)\n\n    def unary_minus(self, value: Value, line: int) -> Value:\n        \"\"\"Perform unary '-'.\"\"\"\n        typ = value.type\n        if isinstance(value, Integer):\n            # TODO: Overflow? Unsigned?\n            return Integer(-value.numeric_value(), typ, line)\n        elif isinstance(value, Float):\n            return Float(-value.value, line)\n        elif is_fixed_width_rtype(typ):\n            # Translate to '0 - x'\n            return self.int_op(typ, Integer(0, typ), value, IntOp.SUB, line)\n        elif is_float_rprimitive(typ):\n            return self.add(FloatNeg(value, line))\n        return self._non_specialized_unary_op(value, \"-\", line)\n\n    def unary_plus(self, value: Value, line: int) -> Value:\n        \"\"\"Perform unary '+'.\"\"\"\n        typ = value.type\n        if (\n            is_tagged(typ)\n            or is_float_rprimitive(typ)\n            or is_bool_or_bit_rprimitive(typ)\n            or is_fixed_width_rtype(typ)\n        ):\n            return value\n        return self._non_specialized_unary_op(value, \"+\", line)\n\n    def unary_invert(self, value: Value, line: int) -> Value:\n        \"\"\"Perform unary '~'.\"\"\"\n        typ = value.type\n        if is_fixed_width_rtype(typ):\n            if typ.is_signed:\n                # Translate to 'x ^ -1'\n                return self.int_op(typ, value, Integer(-1, typ), IntOp.XOR, line)\n            else:\n                # Translate to 'x ^ 0xff...'\n                mask = (1 << (typ.size * 8)) - 1\n                return self.int_op(typ, value, Integer(mask, typ), IntOp.XOR, line)\n        return self._non_specialized_unary_op(value, \"~\", line)\n\n    def unary_op(self, value: Value, op: str, line: int) -> Value:\n        \"\"\"Perform a unary operation.\"\"\"\n        if op == \"not\":\n            return self.unary_not(value, line)\n        elif op == \"-\":\n            return self.unary_minus(value, line)\n        elif op == \"+\":\n            return self.unary_plus(value, line)\n        elif op == \"~\":\n            return self.unary_invert(value, line)\n        raise RuntimeError(\"Unsupported unary operation: %s\" % op)\n\n    def get_item(\n        self,\n        base: Value,\n        item: Value,\n        result_type: RType | None,\n        line: int,\n        *,\n        can_borrow: bool = False,\n    ) -> Value:\n        \"\"\"Generate base[item].\"\"\"\n        if isinstance(base.type, RVec):\n            if is_int_rprimitive(item.type) or is_short_int_rprimitive(item.type):\n                item = self.coerce(item, int64_rprimitive, line)\n            if is_int64_rprimitive(item.type):\n                return vec_get_item(self, base, item, line, can_borrow=can_borrow)\n        # TODO: Move special casing for RTuple here from transform_index_expr\n        return self.gen_method_call(\n            base, \"__getitem__\", [item], result_type, line, can_borrow=can_borrow\n        )\n\n    def make_dict(self, key_value_pairs: Sequence[DictEntry], line: int) -> Value:\n        result: Value | None = None\n        keys: list[Value] = []\n        values: list[Value] = []\n        for key, value in key_value_pairs:\n            if key is not None:\n                # key:value\n                if result is None:\n                    keys.append(key)\n                    values.append(value)\n                    continue\n\n                self.translate_special_method_call(\n                    result, \"__setitem__\", [key, value], result_type=None, line=line\n                )\n            else:\n                # **value\n                if result is None:\n                    result = self._create_dict(keys, values, line)\n\n                self.call_c(dict_update_in_display_op, [result, value], line=line)\n\n        if result is None:\n            result = self._create_dict(keys, values, line)\n\n        return result\n\n    def new_list_op_with_length(self, length: Value, line: int) -> Value:\n        \"\"\"This function returns an uninitialized list.\n\n        If the length is non-zero, the caller must initialize the list, before\n        it can be made visible to user code -- otherwise the list object is broken.\n        You might need further initialization with `new_list_set_item_op` op.\n\n        Args:\n            length: desired length of the new list. The rtype should be\n                    c_pyssize_t_rprimitive\n            line: line number\n        \"\"\"\n        return self.call_c(new_list_op, [length], line)\n\n    def new_list_op(self, values: list[Value], line: int) -> Value:\n        length: list[Value] = [Integer(len(values), c_pyssize_t_rprimitive, line)]\n        if len(values) >= LIST_BUILDING_EXPANSION_THRESHOLD:\n            return self.call_c(list_build_op, length + values, line)\n\n        # If the length of the list is less than the threshold,\n        # LIST_BUILDING_EXPANSION_THRESHOLD, we directly expand the\n        # for-loop and inline the SetMem operation, which is faster\n        # than list_build_op, however generates more code.\n        result_list = self.call_c(new_list_op, length, line)\n        if not values:\n            return result_list\n        args = [self.coerce(item, object_rprimitive, line) for item in values]\n        ob_item_base = self.add(PrimitiveOp([result_list], list_items, line))\n        for i in range(len(values)):\n            self.primitive_op(\n                buf_init_item, [ob_item_base, Integer(i, c_pyssize_t_rprimitive), args[i]], line\n            )\n        self.add(KeepAlive([result_list], line))\n        return result_list\n\n    def new_set_op(self, values: list[Value], line: int) -> Value:\n        return self.primitive_op(new_set_op, values, line)\n\n    def setup_rarray(\n        self, item_type: RType, values: Sequence[Value], line: int, *, object_ptr: bool = False\n    ) -> Value:\n        \"\"\"Declare and initialize a new RArray, returning its address.\"\"\"\n        array = Register(RArray(item_type, len(values)))\n        self.add(AssignMulti(array, list(values), line))\n        return self.add(\n            LoadAddress(object_pointer_rprimitive if object_ptr else c_pointer_rprimitive, array)\n        )\n\n    def shortcircuit_helper(\n        self,\n        op: str,\n        expr_type: RType,\n        left: Callable[[], Value],\n        right: Callable[[], Value],\n        line: int,\n    ) -> Value:\n        # Having actual Phi nodes would be really nice here!\n        target = Register(expr_type, line=line)\n        # left_body takes the value of the left side, right_body the right\n        left_body, right_body, next_block = BasicBlock(), BasicBlock(), BasicBlock()\n        # true_body is taken if the left is true, false_body if it is false.\n        # For 'and' the value is the right side if the left is true, and for 'or'\n        # it is the right side if the left is false.\n        true_body, false_body = (right_body, left_body) if op == \"and\" else (left_body, right_body)\n\n        left_value = left()\n        self.add_bool_branch(left_value, true_body, false_body)\n\n        self.activate_block(left_body)\n        left_coerced = self.coerce(left_value, expr_type, line)\n        self.add(Assign(target, left_coerced, line))\n        self.goto(next_block)\n\n        self.activate_block(right_body)\n        right_value = right()\n        right_coerced = self.coerce(right_value, expr_type, line)\n        self.add(Assign(target, right_coerced, line))\n        self.goto(next_block)\n\n        self.activate_block(next_block)\n        return target\n\n    def bool_value(self, value: Value) -> Value:\n        \"\"\"Return bool(value).\n\n        The result type can be bit_rprimitive or bool_rprimitive.\n        \"\"\"\n        if is_bool_or_bit_rprimitive(value.type):\n            result = value\n        elif is_runtime_subtype(value.type, int_rprimitive):\n            zero = Integer(0, short_int_rprimitive)\n            result = self.comparison_op(value, zero, ComparisonOp.NEQ, value.line)\n        elif is_fixed_width_rtype(value.type):\n            zero = Integer(0, value.type)\n            result = self.add(ComparisonOp(value, zero, ComparisonOp.NEQ))\n        elif is_str_rprimitive(value.type):\n            result = self.call_c(str_check_if_true, [value], value.line)\n        elif (\n            is_list_rprimitive(value.type)\n            or is_dict_rprimitive(value.type)\n            or is_tuple_rprimitive(value.type)\n        ):\n            length = self.builtin_len(value, value.line)\n            zero = Integer(0)\n            result = self.binary_op(length, zero, \"!=\", value.line)\n        elif (\n            isinstance(value.type, RInstance)\n            and value.type.class_ir.is_ext_class\n            and value.type.class_ir.has_method(\"__bool__\")\n        ):\n            # Directly call the __bool__ method on classes that have it.\n            result = self.gen_method_call(value, \"__bool__\", [], bool_rprimitive, value.line)\n        elif is_float_rprimitive(value.type):\n            result = self.compare_floats(value, Float(0.0), FloatComparisonOp.NEQ, value.line)\n        else:\n            value_type = optional_value_type(value.type)\n            if value_type is not None:\n                not_none = self.translate_is_op(value, self.none_object(), \"is not\", value.line)\n                always_truthy = False\n                if isinstance(value_type, RInstance):\n                    # check whether X.__bool__ is always just the default (object.__bool__)\n                    if not value_type.class_ir.has_method(\n                        \"__bool__\"\n                    ) and value_type.class_ir.is_method_final(\"__bool__\"):\n                        always_truthy = True\n\n                if always_truthy:\n                    result = not_none\n                else:\n                    # \"X | None\" where X may be falsey and requires a check\n                    result = Register(bit_rprimitive)\n                    true, false, end = BasicBlock(), BasicBlock(), BasicBlock()\n                    branch = Branch(not_none, true, false, Branch.BOOL)\n                    self.add(branch)\n                    self.activate_block(true)\n                    # unbox_or_cast instead of coerce because we want the\n                    # type to change even if it is a subtype.\n                    remaining = self.unbox_or_cast(value, value_type, value.line)\n                    as_bool = self.bool_value(remaining)\n                    self.add(Assign(result, as_bool))\n                    self.goto(end)\n                    self.activate_block(false)\n                    self.add(Assign(result, Integer(0, bit_rprimitive)))\n                    self.goto(end)\n                    self.activate_block(end)\n            else:\n                result = self.primitive_op(bool_op, [value], value.line)\n        return result\n\n    def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None:\n        opt_value_type = optional_value_type(value.type)\n        if opt_value_type is None:\n            bool_value = self.bool_value(value)\n            self.add(Branch(bool_value, true, false, Branch.BOOL, value.line))\n        else:\n            # Special-case optional types\n            is_none = self.translate_is_op(value, self.none_object(), \"is not\", value.line)\n            branch = Branch(is_none, true, false, Branch.BOOL, value.line)\n            self.add(branch)\n            always_truthy = False\n            if isinstance(opt_value_type, RInstance):\n                # check whether X.__bool__ is always just the default (object.__bool__)\n                if not opt_value_type.class_ir.has_method(\n                    \"__bool__\"\n                ) and opt_value_type.class_ir.is_method_final(\"__bool__\"):\n                    always_truthy = True\n\n            if not always_truthy:\n                # Optional[X] where X may be falsey and requires a check\n                branch.true = BasicBlock()\n                self.activate_block(branch.true)\n                # unbox_or_cast instead of coerce because we want the\n                # type to change even if it is a subtype.\n                remaining = self.unbox_or_cast(value, opt_value_type, value.line)\n                self.add_bool_branch(remaining, true, false)\n\n    def call_c(\n        self,\n        desc: CFunctionDescription,\n        args: list[Value],\n        line: int,\n        result_type: RType | None = None,\n    ) -> Value:\n        \"\"\"Call function using C/native calling convention (not a Python callable).\"\"\"\n        # Handle void function via singleton RVoid instance\n        coerced = []\n        # Coerce fixed number arguments\n        for i in range(min(len(args), len(desc.arg_types))):\n            formal_type = desc.arg_types[i]\n            arg = args[i]\n            arg = self.coerce(arg, formal_type, line)\n            coerced.append(arg)\n        # Reorder args if necessary\n        if desc.ordering is not None:\n            assert desc.var_arg_type is None\n            coerced = [coerced[i] for i in desc.ordering]\n        # Coerce any var_arg\n        var_arg_idx = -1\n        if desc.var_arg_type is not None:\n            var_arg_idx = len(desc.arg_types)\n            for i in range(len(desc.arg_types), len(args)):\n                arg = args[i]\n                arg = self.coerce(arg, desc.var_arg_type, line)\n                coerced.append(arg)\n        # Add extra integer constant if any\n        for item in desc.extra_int_constants:\n            val, typ = item\n            extra_int_constant = Integer(val, typ, line)\n            coerced.append(extra_int_constant)\n        error_kind = desc.error_kind\n        if error_kind == ERR_NEG_INT:\n            # Handled with an explicit comparison\n            error_kind = ERR_NEVER\n        target = self.add(\n            CallC(\n                desc.c_function_name,\n                coerced,\n                desc.return_type,\n                desc.steals,\n                desc.is_borrowed,\n                error_kind,\n                line,\n                var_arg_idx,\n                is_pure=desc.is_pure,\n                returns_null=desc.returns_null,\n                dependencies=desc.dependencies,\n            )\n        )\n        if desc.is_borrowed:\n            # If the result is borrowed, force the arguments to be\n            # kept alive afterwards, as otherwise the result might be\n            # immediately freed, at the risk of a dangling pointer.\n            for arg in coerced:\n                if not isinstance(arg, (Integer, LoadLiteral)):\n                    self.keep_alives.append(arg)\n        if desc.error_kind == ERR_NEG_INT:\n            comp = ComparisonOp(target, Integer(0, desc.return_type, line), ComparisonOp.SGE, line)\n            comp.error_kind = ERR_FALSE\n            self.add(comp)\n\n        if desc.truncated_type is None:\n            result = target\n        else:\n            truncate = self.add(Truncate(target, desc.truncated_type))\n            result = truncate\n        if result_type and not is_runtime_subtype(result.type, result_type):\n            if is_none_rprimitive(result_type):\n                # Special case None return. The actual result may actually be a bool\n                # and so we can't just coerce it.\n                result = self.none()\n            else:\n                result = self.coerce(target, result_type, line, can_borrow=desc.is_borrowed)\n        return result\n\n    def matching_call_c(\n        self,\n        candidates: list[CFunctionDescription],\n        args: list[Value],\n        line: int,\n        result_type: RType | None = None,\n        can_borrow: bool = False,\n    ) -> Value | None:\n        matching: CFunctionDescription | None = None\n        for desc in candidates:\n            if len(desc.arg_types) != len(args):\n                continue\n            if all(\n                is_subtype(actual.type, formal) for actual, formal in zip(args, desc.arg_types)\n            ) and (not desc.is_borrowed or can_borrow):\n                if matching:\n                    assert matching.priority != desc.priority, \"Ambiguous:\\n1) {}\\n2) {}\".format(\n                        matching, desc\n                    )\n                    if desc.priority > matching.priority:\n                        matching = desc\n                else:\n                    matching = desc\n        if matching:\n            target = self.call_c(matching, args, line, result_type)\n            return target\n        return None\n\n    def primitive_op(\n        self,\n        desc: PrimitiveDescription,\n        args: list[Value],\n        line: int,\n        result_type: RType | None = None,\n    ) -> Value:\n        \"\"\"Add a primitive op.\"\"\"\n        # Does this primitive map into calling a Python C API\n        # or an internal mypyc C API function?\n        if desc.c_function_name:\n            # TODO: Generate PrimitiveOps here and transform them into CallC\n            # ops only later in the lowering pass\n            c_desc = CFunctionDescription(\n                desc.name,\n                desc.arg_types,\n                desc.return_type,\n                desc.var_arg_type,\n                desc.truncated_type,\n                desc.c_function_name,\n                desc.error_kind,\n                desc.steals,\n                desc.is_borrowed,\n                desc.ordering,\n                desc.extra_int_constants,\n                desc.priority,\n                is_pure=desc.is_pure,\n                returns_null=False,\n                dependencies=desc.dependencies,\n            )\n            return self.call_c(c_desc, args, line, result_type=result_type)\n\n        # This primitive gets transformed in a lowering pass to\n        # lower-level IR ops using a custom transform function.\n\n        coerced = []\n        # Coerce fixed number arguments\n        for i in range(min(len(args), len(desc.arg_types))):\n            formal_type = desc.arg_types[i]\n            arg = args[i]\n            assert formal_type is not None  # TODO\n            arg = self.coerce(arg, formal_type, line)\n            coerced.append(arg)\n        assert desc.ordering is None\n        assert desc.var_arg_type is None\n        assert not desc.extra_int_constants\n        target = self.add(PrimitiveOp(coerced, desc, line=line))\n        if desc.is_borrowed:\n            # If the result is borrowed, force the arguments to be\n            # kept alive afterwards, as otherwise the result might be\n            # immediately freed, at the risk of a dangling pointer.\n            for arg in coerced:\n                if not isinstance(arg, (Integer, LoadLiteral)):\n                    self.keep_alives.append(arg)\n        if desc.error_kind == ERR_NEG_INT:\n            comp = ComparisonOp(target, Integer(0, desc.return_type, line), ComparisonOp.SGE, line)\n            comp.error_kind = ERR_FALSE\n            self.add(comp)\n\n        assert desc.truncated_type is None\n        result = target\n        if result_type and not is_runtime_subtype(result.type, result_type):\n            if is_none_rprimitive(result_type):\n                # Special case None return. The actual result may actually be a bool\n                # and so we can't just coerce it.\n                result = self.none()\n            else:\n                result = self.coerce(result, result_type, line, can_borrow=desc.is_borrowed)\n        return result\n\n    def matching_primitive_op(\n        self,\n        candidates: list[PrimitiveDescription],\n        args: list[Value],\n        line: int,\n        result_type: RType | None = None,\n        *,\n        can_borrow: bool = False,\n        strict: bool = True,\n    ) -> Value | None:\n        \"\"\"Find primitive operation that is compatible with types of args.\n\n        Return None if none of them match.\n        \"\"\"\n        matching: PrimitiveDescription | None = None\n        for desc in candidates:\n            if len(desc.arg_types) != len(args):\n                continue\n            if desc.experimental and not self.options.experimental_features:\n                continue\n            if all(\n                # formal is not None and # TODO\n                is_subtype(actual.type, formal, relaxed=not strict)\n                for actual, formal in zip(args, desc.arg_types)\n            ) and (not desc.is_borrowed or can_borrow):\n                if matching:\n                    assert matching.priority != desc.priority, \"Ambiguous:\\n1) {}\\n2) {}\".format(\n                        matching, desc\n                    )\n                    if desc.priority > matching.priority:\n                        matching = desc\n                else:\n                    matching = desc\n        if matching:\n            return self.primitive_op(matching, args, line=line, result_type=result_type)\n        if strict and any(prim.is_ambiguous for prim in candidates):\n            # Also try a non-exact match if any primitives have ambiguous types.\n            return self.matching_primitive_op(\n                candidates, args, line, result_type, can_borrow=can_borrow, strict=False\n            )\n\n        return None\n\n    def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int = -1) -> Value:\n        \"\"\"Generate a native integer binary op.\n\n        Use native/C semantics, which sometimes differ from Python\n        semantics.\n\n        Args:\n            type: Either int64_rprimitive or int32_rprimitive\n            op: IntOp.* constant (e.g. IntOp.ADD)\n        \"\"\"\n        return self.add(IntOp(type, lhs, rhs, op, line))\n\n    def float_op(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:\n        \"\"\"Generate a native float binary arithmetic operation.\n\n        This follows Python semantics (e.g. raise exception on division by zero).\n        Add a FloatOp directly if you want low-level semantics.\n\n        Args:\n            op: Binary operator (e.g. '+' or '*')\n        \"\"\"\n        op_id = float_op_to_id[op]\n        if op_id in (FloatOp.DIV, FloatOp.MOD):\n            if not (isinstance(rhs, Float) and rhs.value != 0.0):\n                c = self.compare_floats(rhs, Float(0.0), FloatComparisonOp.EQ, line)\n                err, ok = BasicBlock(), BasicBlock()\n                self.add(Branch(c, err, ok, Branch.BOOL, rare=True))\n                self.activate_block(err)\n                if op_id == FloatOp.DIV:\n                    msg = \"float division by zero\"\n                else:\n                    msg = \"float modulo\"\n                self.add(RaiseStandardError(RaiseStandardError.ZERO_DIVISION_ERROR, msg, line))\n                self.add(Unreachable())\n                self.activate_block(ok)\n        if op_id == FloatOp.MOD:\n            # Adjust the result to match Python semantics (FloatOp follows C semantics).\n            return self.float_mod(lhs, rhs, line)\n        else:\n            return self.add(FloatOp(lhs, rhs, op_id, line))\n\n    def float_mod(self, lhs: Value, rhs: Value, line: int) -> Value:\n        \"\"\"Perform x % y on floats using Python semantics.\"\"\"\n        mod = self.add(FloatOp(lhs, rhs, FloatOp.MOD, line))\n        res = Register(float_rprimitive)\n        self.add(Assign(res, mod))\n        tricky, adjust, copysign, done = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()\n        is_zero = self.add(FloatComparisonOp(res, Float(0.0), FloatComparisonOp.EQ, line))\n        self.add(Branch(is_zero, copysign, tricky, Branch.BOOL))\n        self.activate_block(tricky)\n        same_signs = self.is_same_float_signs(lhs, rhs, line)\n        self.add(Branch(same_signs, done, adjust, Branch.BOOL))\n        self.activate_block(adjust)\n        adj = self.float_op(res, rhs, \"+\", line)\n        self.add(Assign(res, adj))\n        self.add(Goto(done))\n        self.activate_block(copysign)\n        # If the remainder is zero, CPython ensures the result has the\n        # same sign as the denominator.\n        adj = self.primitive_op(copysign_op, [Float(0.0), rhs], line)\n        self.add(Assign(res, adj))\n        self.add(Goto(done))\n        self.activate_block(done)\n        return res\n\n    def compare_floats(self, lhs: Value, rhs: Value, op: int, line: int) -> Value:\n        return self.add(FloatComparisonOp(lhs, rhs, op, line))\n\n    def int_add(self, lhs: Value, rhs: Value | int) -> Value:\n        \"\"\"Helper to add two native integers.\n\n        The result has the type of lhs.\n        \"\"\"\n        if isinstance(rhs, int):\n            rhs = Integer(rhs, lhs.type)\n        return self.int_op(lhs.type, lhs, rhs, IntOp.ADD, lhs.line)\n\n    def int_sub(self, lhs: Value, rhs: Value | int) -> Value:\n        \"\"\"Helper to subtract a native integer from another one.\n\n        The result has the type of lhs.\n        \"\"\"\n        if isinstance(rhs, int):\n            rhs = Integer(rhs, lhs.type)\n        return self.int_op(lhs.type, lhs, rhs, IntOp.SUB, lhs.line)\n\n    def int_mul(self, lhs: Value, rhs: Value | int) -> Value:\n        \"\"\"Helper to multiply two native integers.\n\n        The result has the type of lhs.\n        \"\"\"\n        if isinstance(rhs, int):\n            rhs = Integer(rhs, lhs.type)\n        return self.int_op(lhs.type, lhs, rhs, IntOp.MUL, lhs.line)\n\n    def fixed_width_int_op(\n        self, type: RPrimitive, lhs: Value, rhs: Value, op: int, line: int\n    ) -> Value:\n        \"\"\"Generate a binary op using Python fixed-width integer semantics.\n\n        These may differ in overflow/rounding behavior from native/C ops.\n\n        Args:\n            type: Either int64_rprimitive or int32_rprimitive\n            op: IntOp.* constant (e.g. IntOp.ADD)\n        \"\"\"\n        lhs = self.coerce(lhs, type, line)\n        rhs = self.coerce(rhs, type, line)\n        if op == IntOp.DIV:\n            if isinstance(rhs, Integer) and rhs.value not in (-1, 0):\n                if not type.is_signed:\n                    return self.int_op(type, lhs, rhs, IntOp.DIV, line)\n                else:\n                    # Inline simple division by a constant, so that C\n                    # compilers can optimize more\n                    return self.inline_fixed_width_divide(type, lhs, rhs, line)\n            if is_int64_rprimitive(type):\n                prim = int64_divide_op\n            elif is_int32_rprimitive(type):\n                prim = int32_divide_op\n            elif is_int16_rprimitive(type):\n                prim = int16_divide_op\n            elif is_uint8_rprimitive(type):\n                self.check_for_zero_division(rhs, type, line)\n                return self.int_op(type, lhs, rhs, op, line)\n            else:\n                assert False, type\n            return self.call_c(prim, [lhs, rhs], line)\n        if op == IntOp.MOD:\n            if isinstance(rhs, Integer) and rhs.value not in (-1, 0):\n                if not type.is_signed:\n                    return self.int_op(type, lhs, rhs, IntOp.MOD, line)\n                else:\n                    # Inline simple % by a constant, so that C\n                    # compilers can optimize more\n                    return self.inline_fixed_width_mod(type, lhs, rhs, line)\n            if is_int64_rprimitive(type):\n                prim = int64_mod_op\n            elif is_int32_rprimitive(type):\n                prim = int32_mod_op\n            elif is_int16_rprimitive(type):\n                prim = int16_mod_op\n            elif is_uint8_rprimitive(type):\n                self.check_for_zero_division(rhs, type, line)\n                return self.int_op(type, lhs, rhs, op, line)\n            else:\n                assert False, type\n            return self.call_c(prim, [lhs, rhs], line)\n        return self.int_op(type, lhs, rhs, op, line)\n\n    def check_for_zero_division(self, rhs: Value, type: RType, line: int) -> None:\n        err, ok = BasicBlock(), BasicBlock()\n        is_zero = self.binary_op(rhs, Integer(0, type), \"==\", line)\n        self.add(Branch(is_zero, err, ok, Branch.BOOL))\n        self.activate_block(err)\n        self.add(\n            RaiseStandardError(\n                RaiseStandardError.ZERO_DIVISION_ERROR, \"integer division or modulo by zero\", line\n            )\n        )\n        self.add(Unreachable())\n        self.activate_block(ok)\n\n    def inline_fixed_width_divide(self, type: RType, lhs: Value, rhs: Value, line: int) -> Value:\n        # Perform floor division (native division truncates)\n        res = Register(type)\n        div = self.int_op(type, lhs, rhs, IntOp.DIV, line)\n        self.add(Assign(res, div))\n        same_signs = self.is_same_native_int_signs(type, lhs, rhs, line)\n        tricky, adjust, done = BasicBlock(), BasicBlock(), BasicBlock()\n        self.add(Branch(same_signs, done, tricky, Branch.BOOL))\n        self.activate_block(tricky)\n        mul = self.int_op(type, res, rhs, IntOp.MUL, line)\n        mul_eq = self.add(ComparisonOp(mul, lhs, ComparisonOp.EQ, line))\n        self.add(Branch(mul_eq, done, adjust, Branch.BOOL))\n        self.activate_block(adjust)\n        adj = self.int_op(type, res, Integer(1, type), IntOp.SUB, line)\n        self.add(Assign(res, adj))\n        self.add(Goto(done))\n        self.activate_block(done)\n        return res\n\n    def inline_fixed_width_mod(self, type: RType, lhs: Value, rhs: Value, line: int) -> Value:\n        # Perform floor modulus\n        res = Register(type)\n        mod = self.int_op(type, lhs, rhs, IntOp.MOD, line)\n        self.add(Assign(res, mod))\n        same_signs = self.is_same_native_int_signs(type, lhs, rhs, line)\n        tricky, adjust, done = BasicBlock(), BasicBlock(), BasicBlock()\n        self.add(Branch(same_signs, done, tricky, Branch.BOOL))\n        self.activate_block(tricky)\n        is_zero = self.add(ComparisonOp(res, Integer(0, type), ComparisonOp.EQ, line))\n        self.add(Branch(is_zero, done, adjust, Branch.BOOL))\n        self.activate_block(adjust)\n        adj = self.int_op(type, res, rhs, IntOp.ADD, line)\n        self.add(Assign(res, adj))\n        self.add(Goto(done))\n        self.activate_block(done)\n        return res\n\n    def is_same_native_int_signs(self, type: RType, a: Value, b: Value, line: int) -> Value:\n        neg1 = self.add(ComparisonOp(a, Integer(0, type), ComparisonOp.SLT, line))\n        neg2 = self.add(ComparisonOp(b, Integer(0, type), ComparisonOp.SLT, line))\n        return self.add(ComparisonOp(neg1, neg2, ComparisonOp.EQ, line))\n\n    def is_same_float_signs(self, a: Value, b: Value, line: int) -> Value:\n        neg1 = self.add(FloatComparisonOp(a, Float(0.0), FloatComparisonOp.LT, line))\n        neg2 = self.add(FloatComparisonOp(b, Float(0.0), FloatComparisonOp.LT, line))\n        return self.add(ComparisonOp(neg1, neg2, ComparisonOp.EQ, line))\n\n    def comparison_op(self, lhs: Value, rhs: Value, op: int, line: int) -> Value:\n        return self.add(ComparisonOp(lhs, rhs, op, line))\n\n    def builtin_len(self, val: Value, line: int, use_pyssize_t: bool = False) -> Value:\n        \"\"\"Generate len(val).\n\n        Return short_int_rprimitive by default.\n        Return c_pyssize_t if use_pyssize_t is true (unshifted).\n        \"\"\"\n        typ = val.type\n        size_value = None\n        if is_list_rprimitive(typ) or is_tuple_rprimitive(typ) or is_bytes_rprimitive(typ):\n            size_value = self.primitive_op(var_object_size, [val], line)\n        elif is_set_rprimitive(typ) or is_frozenset_rprimitive(typ):\n            elem_address = self.add(GetElementPtr(val, PySetObject, \"used\"))\n            size_value = self.load_mem(elem_address, c_pyssize_t_rprimitive)\n            self.add(KeepAlive([val], line))\n        elif is_dict_rprimitive(typ):\n            size_value = self.call_c(dict_ssize_t_size_op, [val], line)\n        elif is_str_rprimitive(typ):\n            size_value = self.call_c(str_ssize_t_size_op, [val], line)\n\n        if size_value is not None:\n            if use_pyssize_t:\n                return size_value\n            offset = Integer(1, c_pyssize_t_rprimitive, line)\n            return self.int_op(short_int_rprimitive, size_value, offset, IntOp.LEFT_SHIFT, line)\n\n        if isinstance(typ, RInstance):\n            # TODO: Support use_pyssize_t\n            assert not use_pyssize_t\n            length = self.gen_method_call(val, \"__len__\", [], int_rprimitive, line)\n            length = self.coerce(length, int_rprimitive, line)\n            ok, fail = BasicBlock(), BasicBlock()\n            cond = self.binary_op(length, Integer(0), \">=\", line)\n            self.add_bool_branch(cond, ok, fail)\n            self.activate_block(fail)\n            self.add(\n                RaiseStandardError(\n                    RaiseStandardError.VALUE_ERROR, \"__len__() should return >= 0\", line\n                )\n            )\n            self.add(Unreachable())\n            self.activate_block(ok)\n            return length\n\n        elif isinstance(typ, RVec):\n            len_value = vec_len_native(self, val)\n            if use_pyssize_t:\n                return len_value\n            count = Integer(1, c_pyssize_t_rprimitive, line)\n            return self.int_op(short_int_rprimitive, len_value, count, IntOp.LEFT_SHIFT, line)\n\n        op = self.matching_primitive_op(function_ops[\"builtins.len\"], [val], line)\n        if op is not None:\n            return op\n\n        # Fallback generic case\n        if use_pyssize_t:\n            return self.call_c(generic_ssize_t_len_op, [val], line)\n        else:\n            return self.call_c(generic_len_op, [val], line)\n\n    def new_tuple(self, items: list[Value], line: int) -> Value:\n        if items:\n            size: Value = Integer(len(items), c_pyssize_t_rprimitive)\n            return self.call_c(new_tuple_op, [size] + items, line)\n        else:\n            return self.call_c(load_empty_tuple_constant_op, [], line)\n\n    def new_tuple_with_length(self, length: Value, line: int) -> Value:\n        \"\"\"This function returns an uninitialized tuple.\n\n        If the length is non-zero, the caller must initialize the tuple, before\n        it can be made visible to user code -- otherwise the tuple object is broken.\n        You might need further initialization with `new_tuple_set_item_op` op.\n\n        Args:\n            length: desired length of the new tuple. The rtype should be\n                    c_pyssize_t_rprimitive\n            line: line number\n        \"\"\"\n        return self.call_c(new_tuple_with_length_op, [length], line)\n\n    def int_to_float(self, n: Value, line: int) -> Value:\n        return self.primitive_op(int_to_float_op, [n], line)\n\n    def set_immortal_if_free_threaded(self, v: Value, line: int) -> None:\n        \"\"\"Make an object immortal on free-threaded builds (to avoid contention).\"\"\"\n        if IS_FREE_THREADED and sys.version_info >= (3, 14):\n            self.primitive_op(set_immortal_op, [v], line)\n\n    # Internal helpers\n\n    def decompose_union_helper(\n        self,\n        obj: Value,\n        rtype: RUnion,\n        result_type: RType,\n        process_item: Callable[[Value], Value],\n        line: int,\n    ) -> Value:\n        \"\"\"Generate isinstance() + specialized operations for union items.\n\n        Say, for Union[A, B] generate ops resembling this (pseudocode):\n\n            if isinstance(obj, A):\n                result = <result of process_item(cast(A, obj)>\n            else:\n                result = <result of process_item(cast(B, obj)>\n\n        Args:\n            obj: value with a union type\n            rtype: the union type\n            result_type: result of the operation\n            process_item: callback to generate op for a single union item (arg is coerced\n                to union item type)\n            line: line number\n        \"\"\"\n        # TODO: Optimize cases where a single operation can handle multiple union items\n        #     (say a method is implemented in a common base class)\n        fast_items = []\n        rest_items = []\n        for item in rtype.items:\n            if isinstance(item, RInstance):\n                fast_items.append(item)\n            else:\n                # For everything but RInstance we fall back to C API\n                rest_items.append(item)\n        exit_block = BasicBlock()\n        result = Register(result_type, line=line)\n        for i, item in enumerate(fast_items):\n            more_types = i < len(fast_items) - 1 or rest_items\n            if more_types:\n                # We are not at the final item so we need one more branch\n                op = self.isinstance_native(obj, item.class_ir, line)\n                true_block, false_block = BasicBlock(), BasicBlock()\n                self.add_bool_branch(op, true_block, false_block)\n                self.activate_block(true_block)\n            coerced = self.coerce(obj, item, line)\n            temp = process_item(coerced)\n            temp2 = self.coerce(temp, result_type, line)\n            self.add(Assign(result, temp2, line))\n            self.goto(exit_block)\n            if more_types:\n                self.activate_block(false_block)\n        if rest_items:\n            # For everything else we use generic operation. Use force=True to drop the\n            # union type.\n            coerced = self.coerce(obj, object_rprimitive, line, force=True)\n            temp = process_item(coerced)\n            temp2 = self.coerce(temp, result_type, line)\n            self.add(Assign(result, temp2, line))\n            self.goto(exit_block)\n        self.activate_block(exit_block)\n        return result\n\n    def translate_special_method_call(\n        self,\n        base_reg: Value,\n        name: str,\n        args: list[Value],\n        result_type: RType | None,\n        line: int,\n        can_borrow: bool = False,\n    ) -> Value | None:\n        \"\"\"Translate a method call which is handled nongenerically.\n\n        These are special in the sense that we have code generated specifically for them.\n        They tend to be method calls which have equivalents in C that are more direct\n        than calling with the PyObject api.\n\n        Return None if no translation found; otherwise return the target register.\n        \"\"\"\n        low_level_op = self._translate_special_low_level_method_call(\n            base_reg, name, args, result_type, line, can_borrow\n        )\n        if low_level_op is not None:\n            return low_level_op\n        primitive_ops_candidates = method_call_ops.get(name, [])\n        primitive_op = self.matching_primitive_op(\n            primitive_ops_candidates, [base_reg] + args, line, result_type, can_borrow=can_borrow\n        )\n        return primitive_op\n\n    def _translate_special_low_level_method_call(\n        self,\n        base_reg: Value,\n        name: str,\n        args: list[Value],\n        result_type: RType | None,\n        line: int,\n        can_borrow: bool = False,\n    ) -> Value | None:\n        if name == \"__getitem__\" and len(args) == 1:\n            arg = args[0]\n            if isinstance(base_reg.type, RVec) and (\n                is_int64_rprimitive(arg.type) or is_tagged(arg.type)\n            ):\n                if is_tagged(arg.type):\n                    arg = self.coerce(arg, int64_rprimitive, line)\n                return vec_get_item(self, base_reg, arg, line)\n        return None\n\n    def translate_eq_cmp(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value | None:\n        \"\"\"Add an equality comparison operation.\n\n        Note that this doesn't cover all possible types.\n\n        Args:\n            expr_op: either '==' or '!='\n        \"\"\"\n        ltype = lreg.type\n        rtype = rreg.type\n\n        if is_str_rprimitive(ltype) and is_str_rprimitive(rtype):\n            return self.compare_strings(lreg, rreg, expr_op, line)\n        if is_bytes_rprimitive(ltype) and is_bytes_rprimitive(rtype):\n            return self.compare_bytes(lreg, rreg, expr_op, line)\n\n        lopt = optional_value_type(ltype)\n        ropt = optional_value_type(rtype)\n\n        # Can we do a quick comparison of two optional types (special case None values)?\n        fast_opt_eq = False\n        if lopt is not None:\n            if ropt is not None and is_same_type(lopt, ropt) and self._never_equal_to_none(lopt):\n                fast_opt_eq = True\n            if is_same_type(lopt, rtype) and self._never_equal_to_none(lopt):\n                fast_opt_eq = True\n        elif ropt is not None:\n            if is_same_type(ropt, ltype) and self._never_equal_to_none(ropt):\n                fast_opt_eq = True\n        if fast_opt_eq:\n            return self._translate_fast_optional_eq_cmp(lreg, rreg, expr_op, line)\n\n        if not (isinstance(ltype, RInstance) and ltype == rtype):\n            return None\n\n        class_ir = ltype.class_ir\n        # Check whether any subclasses of the operand redefines __eq__\n        # or it might be redefined in a Python parent class or by\n        # dataclasses\n        cmp_varies_at_runtime = (\n            not class_ir.is_method_final(\"__eq__\")\n            or not class_ir.is_method_final(\"__ne__\")\n            or class_ir.inherits_python\n            or class_ir.is_augmented\n        )\n\n        if cmp_varies_at_runtime:\n            # We might need to call left.__eq__(right) or right.__eq__(left)\n            # depending on which is the more specific type.\n            return None\n\n        if not class_ir.has_method(\"__eq__\"):\n            # There's no __eq__ defined, so just use object identity.\n            identity_ref_op = \"is\" if expr_op == \"==\" else \"is not\"\n            return self.translate_is_op(lreg, rreg, identity_ref_op, line)\n\n        return self.gen_method_call(lreg, op_methods[expr_op], [rreg], ltype, line)\n\n    def _never_equal_to_none(self, typ: RType) -> bool:\n        \"\"\"Are the values of type never equal to None?\"\"\"\n        # TODO: Support RInstance with no custom __eq__/__ne__ and other primitive types.\n        return is_str_rprimitive(typ) or is_bytes_rprimitive(typ)\n\n    def _translate_fast_optional_eq_cmp(\n        self, lreg: Value, rreg: Value, expr_op: str, line: int\n    ) -> Value:\n        \"\"\"Generate eq/ne fast path between 'X | None' and ('X | None' or X).\n\n        Assume 'X' never compares equal to None.\n        \"\"\"\n        if not isinstance(lreg.type, RUnion):\n            lreg, rreg = rreg, lreg\n        value_typ = optional_value_type(lreg.type)\n        assert value_typ\n        res = Register(bool_rprimitive, line=line)\n\n        # Fast path: left value is None?\n        cmp = self.add(ComparisonOp(lreg, self.none_object(), ComparisonOp.EQ, line))\n        l_none = BasicBlock()\n        l_not_none = BasicBlock()\n        out = BasicBlock()\n        self.add(Branch(cmp, l_none, l_not_none, Branch.BOOL))\n        self.activate_block(l_none)\n        if not isinstance(rreg.type, RUnion):\n            val = self.false() if expr_op == \"==\" else self.true()\n            self.add(Assign(res, val, line))\n        else:\n            op = ComparisonOp.EQ if expr_op == \"==\" else ComparisonOp.NEQ\n            cmp = self.add(ComparisonOp(rreg, self.none_object(), op, line))\n            self.add(Assign(res, cmp, line))\n        self.goto(out)\n\n        self.activate_block(l_not_none)\n        if not isinstance(rreg.type, RUnion):\n            # Both operands are known to be not None, perform specialized comparison\n            eq = self.translate_eq_cmp(\n                self.unbox_or_cast(lreg, value_typ, line, can_borrow=True, unchecked=True),\n                rreg,\n                expr_op,\n                line,\n            )\n            assert eq is not None\n            self.add(Assign(res, eq, line))\n        else:\n            r_none = BasicBlock()\n            r_not_none = BasicBlock()\n            # Fast path: right value is None?\n            cmp = self.add(ComparisonOp(rreg, self.none_object(), ComparisonOp.EQ, line))\n            self.add(Branch(cmp, r_none, r_not_none, Branch.BOOL))\n            self.activate_block(r_none)\n            # None vs not-None\n            val = self.false() if expr_op == \"==\" else self.true()\n            self.add(Assign(res, val, line))\n            self.goto(out)\n            self.activate_block(r_not_none)\n            # Both operands are known to be not None, perform specialized comparison\n            eq = self.translate_eq_cmp(\n                self.unbox_or_cast(lreg, value_typ, line, can_borrow=True, unchecked=True),\n                self.unbox_or_cast(rreg, value_typ, line, can_borrow=True, unchecked=True),\n                expr_op,\n                line,\n            )\n            assert eq is not None\n            self.add(Assign(res, eq, line))\n        self.goto(out)\n        self.activate_block(out)\n        return res\n\n    def translate_is_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:\n        \"\"\"Create equality comparison operation between object identities\n\n        Args:\n            expr_op: either 'is' or 'is not'\n        \"\"\"\n        op = ComparisonOp.EQ if expr_op == \"is\" else ComparisonOp.NEQ\n        lhs = self.coerce(lreg, object_rprimitive, line)\n        rhs = self.coerce(rreg, object_rprimitive, line)\n        return self.add(ComparisonOp(lhs, rhs, op, line))\n\n    def _create_dict(self, keys: list[Value], values: list[Value], line: int) -> Value:\n        \"\"\"Create a dictionary(possibly empty) using keys and values\"\"\"\n        # keys and values should have the same number of items\n        size = len(keys)\n        if size > 0:\n            size_value: Value = Integer(size, c_pyssize_t_rprimitive)\n            # merge keys and values\n            items = [i for t in list(zip(keys, values)) for i in t]\n            return self.call_c(dict_build_op, [size_value] + items, line)\n        else:\n            return self.call_c(dict_new_op, [], line)\n\n    # Loop helpers\n\n    def begin_for(self, start: Value, end: Value, step: Value, *, signed: bool) -> ForBuilder:\n        \"\"\"Generate for loop over a pointer or native int range.\n\n        Roughly corresponds to \"for i in range(start, end, step): ....\". Only\n        positive values for step are supported.\n\n        The loop index register is generated automatically and is available\n        via the return value. Do not modify it!\n\n        Example usage that clears a memory area:\n\n          for_loop = builder.begin_for(start_ptr, end_ptr, int32_rprimitive.size)\n\n          # For loop body\n          builder.set_mem(for_loop.index, int32_rprimitive, Integer(0, int32_rprimitive))\n\n          for_loop.finish()\n        \"\"\"\n        b = ForBuilder(self, start, end, step, signed=signed)\n        b.begin()\n        return b\n\n    def error(self, msg: str, line: int) -> None:\n        assert self.errors is not None, \"cannot generate errors in this compiler phase\"\n        self.errors.error(msg, self.module_path, line)\n\n\ndef num_positional_args(arg_values: list[Value], arg_kinds: list[ArgKind] | None) -> int:\n    if arg_kinds is None:\n        return len(arg_values)\n    num_pos = 0\n    for kind in arg_kinds:\n        if kind == ARG_POS:\n            num_pos += 1\n    return num_pos\n\n\nclass ForBuilder:\n    \"\"\"Builder for simple for loops.\"\"\"\n\n    def __init__(\n        self, builder: LowLevelIRBuilder, start: Value, end: Value, step: Value, *, signed: bool\n    ) -> None:\n        self.builder = builder\n        self.start = start\n        self.end = end\n        self.step = step\n        self.signed = signed\n        self.index = Register(start.type)\n        self.top = BasicBlock()\n        self.body = BasicBlock()\n        self.loop_exit = BasicBlock()\n\n    def begin(self) -> None:\n        builder = self.builder\n        builder.assign(self.index, self.start)\n        builder.goto_and_activate(self.top)\n        op = ComparisonOp.SLT if self.signed else ComparisonOp.ULT\n        comp = ComparisonOp(self.index, self.end, op, line=-1)\n        builder.add(comp)\n        builder.add(Branch(comp, self.body, self.loop_exit, Branch.BOOL))\n        builder.goto_and_activate(self.body)\n\n    def finish(self) -> None:\n        builder = self.builder\n        builder.assign(self.index, builder.int_add(self.index, self.step))\n        builder.goto(self.top)\n        builder.activate_block(self.loop_exit)\n"
  },
  {
    "path": "mypyc/irbuild/main.py",
    "content": "\"\"\"Transform a mypy AST to the IR form (Intermediate Representation).\n\nFor example, consider a function like this:\n\n   def f(x: int) -> int:\n       return x * 2 + 1\n\nIt would be translated to something that conceptually looks like this:\n\n   r0 = 2\n   r1 = 1\n   r2 = x * r0 :: int\n   r3 = r2 + r1 :: int\n   return r3\n\nThis module deals with the module-level IR transformation logic and\nputting it all together. The actual IR is implemented in mypyc.ir.\n\nFor the core of the IR transform implementation, look at build_ir()\nbelow, mypyc.irbuild.builder, and mypyc.irbuild.visitor.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom typing import Any, TypeVar, cast\n\nfrom mypy.build import Graph\nfrom mypy.nodes import ClassDef, Expression, FuncDef, MypyFile\nfrom mypy.state import state\nfrom mypy.types import Type\nfrom mypyc.analysis.attrdefined import analyze_always_defined_attrs\nfrom mypyc.common import TOP_LEVEL_NAME\nfrom mypyc.errors import Errors\nfrom mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature\nfrom mypyc.ir.module_ir import ModuleIR, ModuleIRs\nfrom mypyc.ir.rtypes import none_rprimitive\nfrom mypyc.irbuild.builder import IRBuilder\nfrom mypyc.irbuild.mapper import Mapper\nfrom mypyc.irbuild.prebuildvisitor import PreBuildVisitor\nfrom mypyc.irbuild.prepare import (\n    adjust_generator_classes_of_methods,\n    build_type_map,\n    create_generator_class_for_func,\n    find_singledispatch_register_impls,\n)\nfrom mypyc.irbuild.visitor import IRBuilderVisitor\nfrom mypyc.irbuild.vtable import compute_vtable\nfrom mypyc.options import CompilerOptions\n\n# The stubs for callable contextmanagers are busted so cast it to the\n# right type...\nF = TypeVar(\"F\", bound=Callable[..., Any])\nstrict_optional_dec = cast(Callable[[F], F], state.strict_optional_set(True))\n\n\n@strict_optional_dec  # Turn on strict optional for any type manipulations we do\ndef build_ir(\n    modules: list[MypyFile],\n    graph: Graph,\n    types: dict[Expression, Type],\n    mapper: Mapper,\n    options: CompilerOptions,\n    errors: Errors,\n) -> ModuleIRs:\n    \"\"\"Build basic IR for a set of modules that have been type-checked by mypy.\n\n    The returned IR is not complete and requires additional\n    transformations, such as the insertion of refcount handling.\n    \"\"\"\n\n    build_type_map(mapper, modules, graph, types, options, errors)\n    adjust_generator_classes_of_methods(mapper)\n    singledispatch_info = find_singledispatch_register_impls(modules, errors)\n\n    result: ModuleIRs = {}\n    if errors.num_errors > 0:\n        return result\n\n    # Generate IR for all modules.\n    class_irs = []\n\n    for module in modules:\n        # First pass to determine free symbols.\n        pbv = PreBuildVisitor(errors, module, singledispatch_info.decorators_to_remove, types)\n        module.accept(pbv)\n\n        # Declare generator classes for nested async functions and generators.\n        for fdef in pbv.nested_funcs:\n            if isinstance(fdef, FuncDef):\n                # Make generator class name sufficiently unique.\n                suffix = f\"___{fdef.line}\"\n                if fdef.is_coroutine or fdef.is_generator:\n                    create_generator_class_for_func(\n                        module.fullname, None, fdef, mapper, name_suffix=suffix\n                    )\n\n        # Construct and configure builder objects (cyclic runtime dependency).\n        visitor = IRBuilderVisitor()\n        builder = IRBuilder(\n            module.fullname,\n            types,\n            graph,\n            errors,\n            mapper,\n            pbv,\n            visitor,\n            options,\n            singledispatch_info.singledispatch_impls,\n        )\n        visitor.builder = builder\n\n        # Second pass does the bulk of the work.\n        transform_mypy_file(builder, module)\n        module_ir = ModuleIR(\n            module.fullname,\n            list(builder.imports),\n            builder.functions,\n            builder.classes,\n            builder.final_names,\n            builder.type_var_names,\n        )\n        result[module.fullname] = module_ir\n        class_irs.extend(builder.classes)\n\n    analyze_always_defined_attrs(class_irs)\n\n    # Compute vtables.\n    for cir in class_irs:\n        if cir.is_ext_class:\n            compute_vtable(cir)\n\n    return result\n\n\ndef transform_mypy_file(builder: IRBuilder, mypyfile: MypyFile) -> None:\n    \"\"\"Generate IR for a single module.\"\"\"\n\n    if mypyfile.fullname in (\"typing\", \"abc\"):\n        # These module are special; their contents are currently all\n        # built-in primitives.\n        return\n\n    builder.set_module(mypyfile.fullname, mypyfile.path)\n\n    classes = [node for node in mypyfile.defs if isinstance(node, ClassDef)]\n\n    # Collect all classes.\n    for cls in classes:\n        ir = builder.mapper.type_to_ir[cls.info]\n        builder.classes.append(ir)\n\n    builder.enter(\"<module>\")\n\n    # Make sure we have a builtins import\n    builder.gen_import(\"builtins\", 1)\n\n    # Generate ops.\n    for node in mypyfile.defs:\n        builder.accept(node)\n\n    builder.maybe_add_implicit_return()\n\n    # Generate special function representing module top level.\n    args, _, blocks, ret_type, _ = builder.leave()\n    sig = FuncSignature([], none_rprimitive)\n    func_ir = FuncIR(\n        FuncDecl(TOP_LEVEL_NAME, None, builder.module_name, sig),\n        args,\n        blocks,\n        traceback_name=\"<module>\",\n    )\n    builder.functions.append(func_ir)\n"
  },
  {
    "path": "mypyc/irbuild/mapper.py",
    "content": "\"\"\"Maintain a mapping from mypy concepts to IR/compiled concepts.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypy.nodes import ARG_STAR, ARG_STAR2, GDEF, ArgKind, FuncDef, RefExpr, SymbolNode, TypeInfo\nfrom mypy.types import (\n    AnyType,\n    CallableType,\n    Instance,\n    LiteralType,\n    NoneTyp,\n    Overloaded,\n    PartialType,\n    TupleType,\n    Type,\n    TypedDictType,\n    TypeType,\n    TypeVarLikeType,\n    UnboundType,\n    UninhabitedType,\n    UnionType,\n    find_unpack_in_list,\n    get_proper_type,\n)\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FuncDecl, FuncSignature, RuntimeArg\nfrom mypyc.ir.rtypes import (\n    KNOWN_NATIVE_TYPES,\n    RInstance,\n    RTuple,\n    RType,\n    RUnion,\n    RVec,\n    bool_rprimitive,\n    bytearray_rprimitive,\n    bytes_rprimitive,\n    dict_rprimitive,\n    float_rprimitive,\n    frozenset_rprimitive,\n    int16_rprimitive,\n    int32_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    list_rprimitive,\n    none_rprimitive,\n    object_rprimitive,\n    range_rprimitive,\n    set_rprimitive,\n    str_rprimitive,\n    tuple_rprimitive,\n    uint8_rprimitive,\n)\n\n\nclass Mapper:\n    \"\"\"Keep track of mappings from mypy concepts to IR concepts.\n\n    For example, we keep track of how the mypy TypeInfos of compiled\n    classes map to class IR objects.\n\n    This state is shared across all modules being compiled in all\n    compilation groups.\n    \"\"\"\n\n    def __init__(self, group_map: dict[str, str | None]) -> None:\n        self.group_map = group_map\n        self.type_to_ir: dict[TypeInfo, ClassIR] = {}\n        self.func_to_decl: dict[SymbolNode, FuncDecl] = {}\n        self.symbol_fullnames: set[str] = set()\n        # The corresponding generator class that implements a generator/async function\n        self.fdef_to_generator: dict[FuncDef, ClassIR] = {}\n\n    def type_to_rtype(self, typ: Type | None) -> RType:\n        if typ is None:\n            return object_rprimitive\n\n        typ = get_proper_type(typ)\n        if isinstance(typ, Instance):\n            if typ.type.is_newtype:\n                # Unwrap NewType to its base type for rprimitive mapping\n                assert len(typ.type.bases) == 1, typ.type.bases\n                return self.type_to_rtype(typ.type.bases[0])\n            if typ.type.fullname == \"builtins.int\":\n                return int_rprimitive\n            elif typ.type.fullname == \"builtins.float\":\n                return float_rprimitive\n            elif typ.type.fullname == \"builtins.bool\":\n                return bool_rprimitive\n            elif typ.type.fullname == \"builtins.str\":\n                return str_rprimitive\n            elif typ.type.fullname == \"builtins.bytes\":\n                return bytes_rprimitive\n            elif typ.type.fullname == \"builtins.bytearray\":\n                return bytearray_rprimitive\n            elif typ.type.fullname == \"builtins.list\":\n                return list_rprimitive\n            # Dict subclasses are at least somewhat common and we\n            # specifically support them, so make sure that dict operations\n            # get optimized on them.\n            elif any(cls.fullname == \"builtins.dict\" for cls in typ.type.mro):\n                return dict_rprimitive\n            elif typ.type.fullname == \"builtins.set\":\n                return set_rprimitive\n            elif typ.type.fullname == \"builtins.frozenset\":\n                return frozenset_rprimitive\n            elif typ.type.fullname == \"builtins.tuple\":\n                return tuple_rprimitive  # Varying-length tuple\n            elif typ.type.fullname == \"builtins.range\":\n                return range_rprimitive\n            elif typ.type in self.type_to_ir:\n                inst = RInstance(self.type_to_ir[typ.type])\n                # Treat protocols as Union[protocol, object], so that we can do fast\n                # method calls in the cases where the protocol is explicitly inherited from\n                # and fall back to generic operations when it isn't.\n                if typ.type.is_protocol:\n                    return RUnion([inst, object_rprimitive])\n                else:\n                    return inst\n            elif typ.type.fullname == \"mypy_extensions.i64\":\n                return int64_rprimitive\n            elif typ.type.fullname == \"mypy_extensions.i32\":\n                return int32_rprimitive\n            elif typ.type.fullname == \"mypy_extensions.i16\":\n                return int16_rprimitive\n            elif typ.type.fullname == \"mypy_extensions.u8\":\n                return uint8_rprimitive\n            elif typ.type.fullname == \"librt.vecs.vec\":\n                return RVec(self.type_to_rtype(typ.args[0]))\n            elif typ.type.fullname in KNOWN_NATIVE_TYPES:\n                return KNOWN_NATIVE_TYPES[typ.type.fullname]\n            else:\n                return object_rprimitive\n        elif isinstance(typ, TupleType):\n            # Use our unboxed tuples for raw tuples but fall back to\n            # being boxed for NamedTuple or for variadic tuples.\n            if (\n                typ.partial_fallback.type.fullname == \"builtins.tuple\"\n                and find_unpack_in_list(typ.items) is None\n            ):\n                return RTuple([self.type_to_rtype(t) for t in typ.items])\n            else:\n                return tuple_rprimitive\n        elif isinstance(typ, CallableType):\n            return object_rprimitive\n        elif isinstance(typ, NoneTyp):\n            return none_rprimitive\n        elif isinstance(typ, UnionType):\n            return RUnion.make_simplified_union([self.type_to_rtype(item) for item in typ.items])\n        elif isinstance(typ, AnyType):\n            return object_rprimitive\n        elif isinstance(typ, TypeType):\n            return object_rprimitive\n        elif isinstance(typ, TypeVarLikeType):\n            # Erase type variable to upper bound.\n            # TODO: Erase to union if object has value restriction?\n            return self.type_to_rtype(typ.upper_bound)\n        elif isinstance(typ, PartialType):\n            assert typ.var.type is not None\n            return self.type_to_rtype(typ.var.type)\n        elif isinstance(typ, Overloaded):\n            return object_rprimitive\n        elif isinstance(typ, TypedDictType):\n            return dict_rprimitive\n        elif isinstance(typ, LiteralType):\n            return self.type_to_rtype(typ.fallback)\n        elif isinstance(typ, (UninhabitedType, UnboundType)):\n            # Sure, whatever!\n            return object_rprimitive\n\n        # I think we've covered everything that is supposed to\n        # actually show up, so anything else is a bug somewhere.\n        assert False, \"unexpected type %s\" % type(typ)\n\n    def get_arg_rtype(self, typ: Type, kind: ArgKind) -> RType:\n        if kind == ARG_STAR:\n            return tuple_rprimitive\n        elif kind == ARG_STAR2:\n            return dict_rprimitive\n        else:\n            return self.type_to_rtype(typ)\n\n    def fdef_to_sig(self, fdef: FuncDef, strict_dunders_typing: bool) -> FuncSignature:\n        if isinstance(fdef.type, CallableType):\n            arg_types = [\n                self.get_arg_rtype(typ, kind)\n                for typ, kind in zip(fdef.type.arg_types, fdef.type.arg_kinds)\n            ]\n            arg_pos_onlys = [name is None for name in fdef.type.arg_names]\n            ret = self.type_to_rtype(fdef.type.ret_type)\n        else:\n            # Handle unannotated functions\n            arg_types = [object_rprimitive for _ in fdef.arguments]\n            arg_pos_onlys = [arg.pos_only for arg in fdef.arguments]\n            # We at least know the return type for __init__ methods will be None.\n            is_init_method = fdef.name == \"__init__\" and bool(fdef.info)\n            if is_init_method:\n                ret = none_rprimitive\n            else:\n                ret = object_rprimitive\n\n        # mypyc FuncSignatures (unlike mypy types) want to have a name\n        # present even when the argument is position only, since it is\n        # the sole way that FuncDecl arguments are tracked. This is\n        # generally fine except in some cases (like for computing\n        # init_sig) we need to produce FuncSignatures from a\n        # deserialized FuncDef that lacks arguments. We won't ever\n        # need to use those inside of a FuncIR, so we just make up\n        # some crap.\n        if hasattr(fdef, \"arguments\"):\n            arg_names = [arg.variable.name for arg in fdef.arguments]\n        else:\n            arg_names = [name or \"\" for name in fdef.arg_names]\n\n        args = [\n            RuntimeArg(arg_name, arg_type, arg_kind, arg_pos_only)\n            for arg_name, arg_kind, arg_type, arg_pos_only in zip(\n                arg_names, fdef.arg_kinds, arg_types, arg_pos_onlys\n            )\n        ]\n\n        if not strict_dunders_typing:\n            # We force certain dunder methods to return objects to support letting them\n            # return NotImplemented. It also avoids some pointless boxing and unboxing,\n            # since tp_richcompare needs an object anyways.\n            # However, it also prevents some optimizations.\n            if fdef.name in (\"__eq__\", \"__ne__\", \"__lt__\", \"__gt__\", \"__le__\", \"__ge__\"):\n                ret = object_rprimitive\n\n        return FuncSignature(args, ret)\n\n    def is_native_module(self, module: str) -> bool:\n        \"\"\"Is the given module one compiled by mypyc?\"\"\"\n        return module in self.group_map\n\n    def is_native_ref_expr(self, expr: RefExpr) -> bool:\n        if expr.node is None:\n            return False\n        if \".\" in expr.node.fullname:\n            name = expr.node.fullname.rpartition(\".\")[0]\n            return self.is_native_module(name) or name in self.symbol_fullnames\n        return True\n\n    def is_native_module_ref_expr(self, expr: RefExpr) -> bool:\n        return self.is_native_ref_expr(expr) and expr.kind == GDEF\n"
  },
  {
    "path": "mypyc/irbuild/match.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Generator\nfrom contextlib import contextmanager\n\nfrom mypy.nodes import MatchStmt, NameExpr, TypeInfo\nfrom mypy.patterns import (\n    AsPattern,\n    ClassPattern,\n    MappingPattern,\n    OrPattern,\n    Pattern,\n    SequencePattern,\n    SingletonPattern,\n    StarredPattern,\n    ValuePattern,\n)\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.types import Instance, LiteralType, TupleType, get_proper_type\nfrom mypyc.ir.ops import BasicBlock, Value\nfrom mypyc.ir.rtypes import object_rprimitive\nfrom mypyc.irbuild.builder import IRBuilder\nfrom mypyc.primitives.dict_ops import (\n    dict_copy,\n    dict_del_item,\n    mapping_has_key,\n    supports_mapping_protocol,\n)\nfrom mypyc.primitives.generic_ops import generic_ssize_t_len_op\nfrom mypyc.primitives.list_ops import (\n    sequence_get_item,\n    sequence_get_slice,\n    supports_sequence_protocol,\n)\nfrom mypyc.primitives.misc_ops import fast_isinstance_op, slow_isinstance_op\n\n# From: https://peps.python.org/pep-0634/#class-patterns\nMATCHABLE_BUILTINS = {\n    \"builtins.bool\",\n    \"builtins.bytearray\",\n    \"builtins.bytes\",\n    \"builtins.dict\",\n    \"builtins.float\",\n    \"builtins.frozenset\",\n    \"builtins.int\",\n    \"builtins.list\",\n    \"builtins.set\",\n    \"builtins.str\",\n    \"builtins.tuple\",\n}\n\n\nclass MatchVisitor(TraverserVisitor):\n    builder: IRBuilder\n    code_block: BasicBlock\n    next_block: BasicBlock\n    final_block: BasicBlock\n    subject: Value\n    match: MatchStmt\n\n    as_pattern: AsPattern | None = None\n\n    def __init__(self, builder: IRBuilder, match_node: MatchStmt) -> None:\n        self.builder = builder\n\n        self.code_block = BasicBlock()\n        self.next_block = BasicBlock()\n        self.final_block = BasicBlock()\n\n        self.match = match_node\n        self.subject = builder.accept(match_node.subject)\n\n    def build_match_body(self, index: int) -> None:\n        self.builder.activate_block(self.code_block)\n\n        guard = self.match.guards[index]\n\n        if guard:\n            self.code_block = BasicBlock()\n\n            cond = self.builder.accept(guard)\n            self.builder.add_bool_branch(cond, self.code_block, self.next_block)\n\n            self.builder.activate_block(self.code_block)\n\n        self.builder.accept(self.match.bodies[index])\n        self.builder.goto(self.final_block)\n\n    def visit_match_stmt(self, m: MatchStmt) -> None:\n        for i, pattern in enumerate(m.patterns):\n            self.code_block = BasicBlock()\n            self.next_block = BasicBlock()\n\n            pattern.accept(self)\n\n            self.build_match_body(i)\n            self.builder.activate_block(self.next_block)\n\n        self.builder.goto_and_activate(self.final_block)\n\n    def visit_value_pattern(self, pattern: ValuePattern) -> None:\n        value = self.builder.accept(pattern.expr)\n\n        cond = self.builder.binary_op(self.subject, value, \"==\", pattern.expr.line)\n\n        self.bind_as_pattern(value)\n\n        self.builder.add_bool_branch(cond, self.code_block, self.next_block)\n\n    def visit_or_pattern(self, pattern: OrPattern) -> None:\n        backup_block = self.next_block\n        self.next_block = BasicBlock()\n\n        for p in pattern.patterns:\n            # Hack to ensure the as pattern is bound to each pattern in the\n            # \"or\" pattern, but not every subpattern\n            backup = self.as_pattern\n            p.accept(self)\n            self.as_pattern = backup\n\n            self.builder.activate_block(self.next_block)\n            self.next_block = BasicBlock()\n\n        self.next_block = backup_block\n        self.builder.goto(self.next_block)\n\n    def visit_class_pattern(self, pattern: ClassPattern) -> None:\n        # TODO: use faster instance check for native classes (while still\n        # making sure to account for inheritance)\n        isinstance_op = (\n            fast_isinstance_op\n            if self.builder.is_builtin_ref_expr(pattern.class_ref)\n            else slow_isinstance_op\n        )\n\n        cond = self.builder.primitive_op(\n            isinstance_op, [self.subject, self.builder.accept(pattern.class_ref)], pattern.line\n        )\n\n        self.builder.add_bool_branch(cond, self.code_block, self.next_block)\n\n        self.bind_as_pattern(self.subject, new_block=True)\n\n        if pattern.positionals:\n            if pattern.class_ref.fullname in MATCHABLE_BUILTINS:\n                self.builder.activate_block(self.code_block)\n                self.code_block = BasicBlock()\n\n                pattern.positionals[0].accept(self)\n\n                return\n\n            node = pattern.class_ref.node\n            assert isinstance(node, TypeInfo), node\n            match_args = extract_dunder_match_args_names(node)\n\n            for i, expr in enumerate(pattern.positionals):\n                self.builder.activate_block(self.code_block)\n                self.code_block = BasicBlock()\n\n                # TODO: use faster \"get_attr\" method instead when calling on native or\n                # builtin objects\n                positional = self.builder.py_get_attr(self.subject, match_args[i], expr.line)\n\n                with self.enter_subpattern(positional):\n                    expr.accept(self)\n\n        for key, value in zip(pattern.keyword_keys, pattern.keyword_values):\n            self.builder.activate_block(self.code_block)\n            self.code_block = BasicBlock()\n\n            # TODO: same as above \"get_attr\" comment\n            attr = self.builder.py_get_attr(self.subject, key, value.line)\n\n            with self.enter_subpattern(attr):\n                value.accept(self)\n\n    def visit_as_pattern(self, pattern: AsPattern) -> None:\n        if pattern.pattern:\n            old_pattern = self.as_pattern\n            self.as_pattern = pattern\n            pattern.pattern.accept(self)\n            self.as_pattern = old_pattern\n\n        elif pattern.name:\n            target = self.builder.get_assignment_target(pattern.name)\n\n            self.builder.assign(target, self.subject, pattern.line)\n\n        self.builder.goto(self.code_block)\n\n    def visit_singleton_pattern(self, pattern: SingletonPattern) -> None:\n        if pattern.value is None:\n            obj = self.builder.none_object()\n        elif pattern.value is True:\n            obj = self.builder.true()\n        else:\n            obj = self.builder.false()\n\n        cond = self.builder.binary_op(self.subject, obj, \"is\", pattern.line)\n\n        self.builder.add_bool_branch(cond, self.code_block, self.next_block)\n\n    def visit_mapping_pattern(self, pattern: MappingPattern) -> None:\n        is_dict = self.builder.call_c(supports_mapping_protocol, [self.subject], pattern.line)\n\n        self.builder.add_bool_branch(is_dict, self.code_block, self.next_block)\n\n        keys: list[Value] = []\n\n        for key, value in zip(pattern.keys, pattern.values):\n            self.builder.activate_block(self.code_block)\n            self.code_block = BasicBlock()\n\n            key_value = self.builder.accept(key)\n            keys.append(key_value)\n\n            exists = self.builder.call_c(mapping_has_key, [self.subject, key_value], pattern.line)\n\n            self.builder.add_bool_branch(exists, self.code_block, self.next_block)\n            self.builder.activate_block(self.code_block)\n            self.code_block = BasicBlock()\n\n            item = self.builder.gen_method_call(\n                self.subject, \"__getitem__\", [key_value], object_rprimitive, pattern.line\n            )\n\n            with self.enter_subpattern(item):\n                value.accept(self)\n\n        if pattern.rest:\n            self.builder.activate_block(self.code_block)\n            self.code_block = BasicBlock()\n\n            rest = self.builder.primitive_op(dict_copy, [self.subject], pattern.rest.line)\n\n            target = self.builder.get_assignment_target(pattern.rest)\n\n            self.builder.assign(target, rest, pattern.rest.line)\n\n            for i, key_name in enumerate(keys):\n                self.builder.call_c(dict_del_item, [rest, key_name], pattern.keys[i].line)\n\n            self.builder.goto(self.code_block)\n\n    def visit_sequence_pattern(self, seq_pattern: SequencePattern) -> None:\n        star_index, capture, patterns = prep_sequence_pattern(seq_pattern)\n\n        is_list = self.builder.call_c(supports_sequence_protocol, [self.subject], seq_pattern.line)\n\n        self.builder.add_bool_branch(is_list, self.code_block, self.next_block)\n\n        self.builder.activate_block(self.code_block)\n        self.code_block = BasicBlock()\n\n        actual_len = self.builder.call_c(generic_ssize_t_len_op, [self.subject], seq_pattern.line)\n        min_len = len(patterns)\n\n        is_long_enough = self.builder.binary_op(\n            actual_len,\n            self.builder.load_int(min_len),\n            \"==\" if star_index is None else \">=\",\n            seq_pattern.line,\n        )\n\n        self.builder.add_bool_branch(is_long_enough, self.code_block, self.next_block)\n\n        for i, pattern in enumerate(patterns):\n            self.builder.activate_block(self.code_block)\n            self.code_block = BasicBlock()\n\n            if star_index is not None and i >= star_index:\n                current = self.builder.binary_op(\n                    actual_len, self.builder.load_int(min_len - i), \"-\", pattern.line\n                )\n\n            else:\n                current = self.builder.load_int(i)\n\n            item = self.builder.call_c(sequence_get_item, [self.subject, current], pattern.line)\n\n            with self.enter_subpattern(item):\n                pattern.accept(self)\n\n        if capture and star_index is not None:\n            self.builder.activate_block(self.code_block)\n            self.code_block = BasicBlock()\n\n            capture_end = self.builder.binary_op(\n                actual_len, self.builder.load_int(min_len - star_index), \"-\", capture.line\n            )\n\n            rest = self.builder.call_c(\n                sequence_get_slice,\n                [self.subject, self.builder.load_int(star_index), capture_end],\n                capture.line,\n            )\n\n            target = self.builder.get_assignment_target(capture)\n            self.builder.assign(target, rest, capture.line)\n\n            self.builder.goto(self.code_block)\n\n    def bind_as_pattern(self, value: Value, new_block: bool = False) -> None:\n        if self.as_pattern and self.as_pattern.pattern and self.as_pattern.name:\n            if new_block:\n                self.builder.activate_block(self.code_block)\n                self.code_block = BasicBlock()\n\n            target = self.builder.get_assignment_target(self.as_pattern.name)\n            self.builder.assign(target, value, self.as_pattern.pattern.line)\n\n            self.as_pattern = None\n\n            if new_block:\n                self.builder.goto(self.code_block)\n\n    @contextmanager\n    def enter_subpattern(self, subject: Value) -> Generator[None]:\n        old_subject = self.subject\n        self.subject = subject\n        yield\n        self.subject = old_subject\n\n\ndef prep_sequence_pattern(\n    seq_pattern: SequencePattern,\n) -> tuple[int | None, NameExpr | None, list[Pattern]]:\n    star_index: int | None = None\n    capture: NameExpr | None = None\n    patterns: list[Pattern] = []\n\n    for i, pattern in enumerate(seq_pattern.patterns):\n        if isinstance(pattern, StarredPattern):\n            star_index = i\n            capture = pattern.capture\n\n        else:\n            patterns.append(pattern)\n\n    return star_index, capture, patterns\n\n\ndef extract_dunder_match_args_names(info: TypeInfo) -> list[str]:\n    ty = info.names.get(\"__match_args__\")\n    assert ty\n    match_args_type = get_proper_type(ty.type)\n    assert isinstance(match_args_type, TupleType), match_args_type\n\n    match_args: list[str] = []\n    for item in match_args_type.items:\n        proper_item = get_proper_type(item)\n\n        match_arg = None\n        if isinstance(proper_item, Instance) and proper_item.last_known_value:\n            match_arg = proper_item.last_known_value.value\n        elif isinstance(proper_item, LiteralType):\n            match_arg = proper_item.value\n        assert isinstance(match_arg, str), f\"Unrecognized __match_args__ item: {item}\"\n\n        match_args.append(match_arg)\n    return match_args\n"
  },
  {
    "path": "mypyc/irbuild/missingtypevisitor.py",
    "content": "from __future__ import annotations\n\nfrom mypy.nodes import Expression, Node\nfrom mypy.traverser import ExtendedTraverserVisitor\nfrom mypy.types import AnyType, Type, TypeOfAny\n\n\nclass MissingTypesVisitor(ExtendedTraverserVisitor):\n    \"\"\"AST visitor that can be used to add any missing types as a generic AnyType.\"\"\"\n\n    def __init__(self, types: dict[Expression, Type]) -> None:\n        super().__init__()\n        self.types: dict[Expression, Type] = types\n\n    def visit(self, o: Node) -> bool:\n        if isinstance(o, Expression) and o not in self.types:\n            self.types[o] = AnyType(TypeOfAny.special_form)\n\n        # If returns True, will continue to nested nodes.\n        return True\n"
  },
  {
    "path": "mypyc/irbuild/nonlocalcontrol.py",
    "content": "\"\"\"Helpers for dealing with nonlocal control such as 'break' and 'return'.\n\nModel how these behave differently in different contexts.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom abc import abstractmethod\nfrom typing import TYPE_CHECKING\n\nfrom mypyc.ir.ops import (\n    NO_TRACEBACK_LINE_NO,\n    BasicBlock,\n    Branch,\n    Goto,\n    Integer,\n    Register,\n    Return,\n    SetMem,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import object_rprimitive\nfrom mypyc.irbuild.targets import AssignmentTarget\nfrom mypyc.primitives.exc_ops import restore_exc_info_op, set_stop_iteration_value\n\nif TYPE_CHECKING:\n    from mypyc.irbuild.builder import IRBuilder\n\n\nclass NonlocalControl:\n    \"\"\"ABC representing a stack frame of constructs that modify nonlocal control flow.\n\n    The nonlocal control flow constructs are break, continue, and\n    return, and their behavior is modified by a number of other\n    constructs.  The most obvious is loop, which override where break\n    and continue jump to, but also `except` (which needs to clear\n    exc_info when left) and (eventually) finally blocks (which need to\n    ensure that the finally block is always executed when leaving the\n    try/except blocks).\n    \"\"\"\n\n    @abstractmethod\n    def gen_break(self, builder: IRBuilder, line: int) -> None:\n        pass\n\n    @abstractmethod\n    def gen_continue(self, builder: IRBuilder, line: int) -> None:\n        pass\n\n    @abstractmethod\n    def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:\n        pass\n\n\nclass BaseNonlocalControl(NonlocalControl):\n    \"\"\"Default nonlocal control outside any statements that affect it.\"\"\"\n\n    def gen_break(self, builder: IRBuilder, line: int) -> None:\n        assert False, \"break outside of loop\"\n\n    def gen_continue(self, builder: IRBuilder, line: int) -> None:\n        assert False, \"continue outside of loop\"\n\n    def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:\n        builder.add(Return(value, line))\n\n\nclass LoopNonlocalControl(NonlocalControl):\n    \"\"\"Nonlocal control within a loop.\"\"\"\n\n    def __init__(\n        self, outer: NonlocalControl, continue_block: BasicBlock, break_block: BasicBlock\n    ) -> None:\n        self.outer = outer\n        self.continue_block = continue_block\n        self.break_block = break_block\n\n    def gen_break(self, builder: IRBuilder, line: int) -> None:\n        builder.add(Goto(self.break_block))\n\n    def gen_continue(self, builder: IRBuilder, line: int) -> None:\n        builder.add(Goto(self.continue_block))\n\n    def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:\n        self.outer.gen_return(builder, value, line)\n\n\nclass GeneratorNonlocalControl(BaseNonlocalControl):\n    \"\"\"Default nonlocal control in a generator function outside statements.\"\"\"\n\n    def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:\n        # Assign an invalid next label number so that the next time\n        # __next__ is called, we jump to the case in which\n        # StopIteration is raised.\n        builder.assign(builder.fn_info.generator_class.next_label_target, Integer(-1), line)\n\n        # Raise a StopIteration containing a field for the value that\n        # should be returned. Before doing so, create a new block\n        # without an error handler set so that the implicitly thrown\n        # StopIteration isn't caught by except blocks inside of the\n        # generator function.\n        builder.builder.push_error_handler(None)\n        builder.goto_and_activate(BasicBlock())\n\n        # Skip creating a traceback frame when we raise here, because\n        # we don't care about the traceback frame and it is kind of\n        # expensive since raising StopIteration is an extremely common\n        # case.  Also we call a special internal function to set\n        # StopIteration instead of using RaiseStandardError because\n        # the obvious thing doesn't work if the value is a tuple\n        # (???).\n\n        true, false = BasicBlock(), BasicBlock()\n        stop_iter_reg = builder.fn_info.generator_class.stop_iter_value_reg\n        assert stop_iter_reg is not None\n\n        builder.add(Branch(stop_iter_reg, true, false, Branch.IS_ERROR))\n\n        builder.activate_block(true)\n        # The default/slow path is to raise a StopIteration exception with\n        # return value.\n        builder.call_c(set_stop_iteration_value, [value], NO_TRACEBACK_LINE_NO)\n        builder.add(Unreachable())\n        builder.builder.pop_error_handler()\n\n        builder.activate_block(false)\n        # The fast path is to store return value via caller-provided pointer\n        # instead of raising an exception. This can only be used when the\n        # caller is a native function.\n        builder.add(SetMem(object_rprimitive, stop_iter_reg, value))\n        builder.add(Return(Integer(0, object_rprimitive)))\n\n\nclass CleanupNonlocalControl(NonlocalControl):\n    \"\"\"Abstract nonlocal control that runs some cleanup code.\"\"\"\n\n    def __init__(self, outer: NonlocalControl) -> None:\n        self.outer = outer\n\n    @abstractmethod\n    def gen_cleanup(self, builder: IRBuilder, line: int) -> None: ...\n\n    def gen_break(self, builder: IRBuilder, line: int) -> None:\n        self.gen_cleanup(builder, line)\n        self.outer.gen_break(builder, line)\n\n    def gen_continue(self, builder: IRBuilder, line: int) -> None:\n        self.gen_cleanup(builder, line)\n        self.outer.gen_continue(builder, line)\n\n    def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:\n        self.gen_cleanup(builder, line)\n        self.outer.gen_return(builder, value, line)\n\n\nclass TryFinallyNonlocalControl(NonlocalControl):\n    \"\"\"Nonlocal control within try/finally.\"\"\"\n\n    def __init__(self, target: BasicBlock) -> None:\n        self.target = target\n        self.ret_reg: None | Register | AssignmentTarget = None\n\n    def gen_break(self, builder: IRBuilder, line: int) -> None:\n        builder.error(\"break inside try/finally block is unimplemented\", line)\n\n    def gen_continue(self, builder: IRBuilder, line: int) -> None:\n        builder.error(\"continue inside try/finally block is unimplemented\", line)\n\n    def gen_return(self, builder: IRBuilder, value: Value, line: int) -> None:\n        if self.ret_reg is None:\n            if builder.fn_info.is_generator:\n                self.ret_reg = builder.make_spill_target(builder.ret_types[-1])\n            else:\n                self.ret_reg = Register(builder.ret_types[-1])\n        # assert needed because of apparent mypy bug... it loses track of the union\n        # and infers the type as object\n        assert isinstance(self.ret_reg, (Register, AssignmentTarget)), self.ret_reg\n        builder.assign(self.ret_reg, value, line)\n\n        builder.add(Goto(self.target))\n\n\nclass ExceptNonlocalControl(CleanupNonlocalControl):\n    \"\"\"Nonlocal control for except blocks.\n\n    Just makes sure that sys.exc_info always gets restored when we leave.\n    This is super annoying.\n    \"\"\"\n\n    def __init__(self, outer: NonlocalControl, saved: Value | AssignmentTarget) -> None:\n        super().__init__(outer)\n        self.saved = saved\n\n    def gen_cleanup(self, builder: IRBuilder, line: int) -> None:\n        builder.call_c(restore_exc_info_op, [builder.read(self.saved, line)], line)\n\n\nclass FinallyNonlocalControl(CleanupNonlocalControl):\n    \"\"\"Nonlocal control for finally blocks.\n\n    Just makes sure that sys.exc_info always gets restored when we\n    leave and the return register is decrefed if it isn't null.\n    \"\"\"\n\n    def __init__(self, outer: NonlocalControl, saved: Value) -> None:\n        super().__init__(outer)\n        self.saved = saved\n\n    def gen_cleanup(self, builder: IRBuilder, line: int) -> None:\n        # Restore the old exc_info\n        target, cleanup = BasicBlock(), BasicBlock()\n        builder.add(Branch(self.saved, target, cleanup, Branch.IS_ERROR))\n        builder.activate_block(cleanup)\n        builder.call_c(restore_exc_info_op, [self.saved], line)\n        builder.goto_and_activate(target)\n"
  },
  {
    "path": "mypyc/irbuild/prebuildvisitor.py",
    "content": "from __future__ import annotations\n\nfrom mypy.nodes import (\n    AssignmentStmt,\n    Block,\n    Decorator,\n    DictionaryComprehension,\n    Expression,\n    FuncDef,\n    FuncItem,\n    GeneratorExpr,\n    Import,\n    LambdaExpr,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    Node,\n    SymbolNode,\n    Var,\n)\nfrom mypy.traverser import ExtendedTraverserVisitor, TraverserVisitor\nfrom mypy.types import Type\nfrom mypyc.errors import Errors\nfrom mypyc.irbuild.missingtypevisitor import MissingTypesVisitor\n\n\nclass _LambdaChecker(TraverserVisitor):\n    \"\"\"Check whether an AST subtree contains a lambda expression.\"\"\"\n\n    found = False\n\n    def visit_lambda_expr(self, _o: LambdaExpr) -> None:\n        self.found = True\n\n\ndef _comprehension_has_lambda(node: GeneratorExpr | DictionaryComprehension) -> bool:\n    \"\"\"Return True if a comprehension body contains a lambda.\n\n    Only checks body expressions (left_expr/key/value and conditions),\n    not the sequences, since sequences are evaluated in the enclosing scope.\n    \"\"\"\n    checker = _LambdaChecker()\n    if isinstance(node, GeneratorExpr):\n        node.left_expr.accept(checker)\n    else:\n        node.key.accept(checker)\n        node.value.accept(checker)\n    for conds in node.condlists:\n        for cond in conds:\n            cond.accept(checker)\n    return checker.found\n\n\nclass PreBuildVisitor(ExtendedTraverserVisitor):\n    \"\"\"Mypy file AST visitor run before building the IR.\n\n    This collects various things, including:\n\n    * Determine relationships between nested functions and functions that\n      contain nested functions\n    * Find non-local variables (free variables)\n    * Find property setters\n    * Find decorators of functions\n    * Find module import groups\n\n    The main IR build pass uses this information.\n    \"\"\"\n\n    def __init__(\n        self,\n        errors: Errors,\n        current_file: MypyFile,\n        decorators_to_remove: dict[FuncDef, list[int]],\n        types: dict[Expression, Type],\n    ) -> None:\n        super().__init__()\n        # Dict from a function to symbols defined directly in the\n        # function that are used as non-local (free) variables within a\n        # nested function.\n        self.free_variables: dict[FuncItem, set[SymbolNode]] = {}\n\n        # Intermediate data structure used to find the function where\n        # a SymbolNode is declared. Initially this may point to a\n        # function nested inside the function with the declaration,\n        # but we'll eventually update this to refer to the function\n        # with the declaration.\n        self.symbols_to_funcs: dict[SymbolNode, FuncItem] = {}\n\n        # Stack representing current function nesting.\n        self.funcs: list[FuncItem] = []\n\n        # All property setters encountered so far.\n        self.prop_setters: set[FuncDef] = set()\n\n        # A map from any function that contains nested functions to\n        # a set of all the functions that are nested within it.\n        self.encapsulating_funcs: dict[FuncItem, list[FuncItem]] = {}\n\n        # Map nested function to its parent/encapsulating function.\n        self.nested_funcs: dict[FuncItem, FuncItem] = {}\n\n        # Map function to its non-special decorators.\n        self.funcs_to_decorators: dict[FuncDef, list[Expression]] = {}\n\n        # Map function to indices of decorators to remove\n        self.decorators_to_remove: dict[FuncDef, list[int]] = decorators_to_remove\n\n        # A mapping of import groups (a series of Import nodes with\n        # nothing in between) where each group is keyed by its first\n        # import node.\n        self.module_import_groups: dict[Import, list[Import]] = {}\n        self._current_import_group: Import | None = None\n\n        self.errors: Errors = errors\n\n        self.current_file: MypyFile = current_file\n\n        self.missing_types_visitor = MissingTypesVisitor(types)\n\n        # Synthetic FuncDef representing the module scope, created on demand\n        # when a comprehension at module/class level contains a lambda.\n        self._module_fitem: FuncDef | None = None\n\n        # Counter for generating unique synthetic comprehension scope names.\n        self._comprehension_counter = 0\n\n        # Map comprehension AST nodes to synthetic FuncDefs representing\n        # their scope (only for comprehensions that contain lambdas).\n        self.comprehension_to_fitem: dict[GeneratorExpr | DictionaryComprehension, FuncDef] = {}\n\n    def visit(self, o: Node) -> bool:\n        if not isinstance(o, Import):\n            self._current_import_group = None\n        return True\n\n    def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None:\n        # These are cases where mypy may not have types for certain expressions,\n        # but mypyc needs some form type to exist.\n        if stmt.is_alias_def:\n            stmt.rvalue.accept(self.missing_types_visitor)\n        return super().visit_assignment_stmt(stmt)\n\n    def visit_block(self, block: Block) -> None:\n        self._current_import_group = None\n        super().visit_block(block)\n        self._current_import_group = None\n\n    def visit_decorator(self, dec: Decorator) -> None:\n        if dec.decorators:\n            # Only add the function being decorated if there exist\n            # (ordinary) decorators in the decorator list. Certain\n            # decorators (such as @property, @abstractmethod) are\n            # special cased and removed from this list by\n            # mypy. Functions decorated only by special decorators\n            # (and property setters) are not treated as decorated\n            # functions by the IR builder.\n            if isinstance(dec.decorators[0], MemberExpr) and dec.decorators[0].name == \"setter\":\n                # Property setters are not treated as decorated methods.\n                self.prop_setters.add(dec.func)\n            else:\n                decorators_to_store = dec.decorators.copy()\n                if dec.func in self.decorators_to_remove:\n                    to_remove = self.decorators_to_remove[dec.func]\n\n                    for i in reversed(to_remove):\n                        del decorators_to_store[i]\n                    # if all of the decorators are removed, we shouldn't treat this as a decorated\n                    # function because there aren't any decorators to apply\n                    if not decorators_to_store:\n                        return\n\n                self.funcs_to_decorators[dec.func] = decorators_to_store\n        super().visit_decorator(dec)\n\n    def visit_func_def(self, fdef: FuncDef) -> None:\n        # TODO: What about overloaded functions?\n        self.visit_func(fdef)\n        self.visit_symbol_node(fdef)\n\n    def visit_lambda_expr(self, expr: LambdaExpr) -> None:\n        self.visit_func(expr)\n\n    def visit_func(self, func: FuncItem) -> None:\n        # If there were already functions or lambda expressions\n        # defined in the function stack, then note the previous\n        # FuncItem as containing a nested function and the current\n        # FuncItem as being a nested function.\n        if self.funcs:\n            # Add the new func to the set of nested funcs within the\n            # func at top of the func stack.\n            self.encapsulating_funcs.setdefault(self.funcs[-1], []).append(func)\n            # Add the func at top of the func stack as the parent of\n            # new func.\n            self.nested_funcs[func] = self.funcs[-1]\n\n        self.funcs.append(func)\n        super().visit_func(func)\n        self.funcs.pop()\n\n    def _visit_comprehension_with_scope(self, o: GeneratorExpr | DictionaryComprehension) -> None:\n        \"\"\"Visit a comprehension that contains lambdas.\n\n        Creates a synthetic FuncDef to represent the comprehension's scope,\n        registers it in the function nesting hierarchy, and traverses the\n        comprehension body with it on the stack.\n        \"\"\"\n        pushed_module = False\n        if not self.funcs:\n            # At module level: push synthetic module FuncDef.\n            if self._module_fitem is None:\n                self._module_fitem = FuncDef(\"__mypyc_module__\")\n                self._module_fitem.line = 1\n            self.funcs.append(self._module_fitem)\n            pushed_module = True\n\n        # Create synthetic FuncDef for the comprehension scope.\n        comprehension_fdef = FuncDef(f\"__comprehension_{self._comprehension_counter}__\")\n        self._comprehension_counter += 1\n        comprehension_fdef.line = o.line\n        self.comprehension_to_fitem[o] = comprehension_fdef\n\n        # Register as nested within enclosing function.\n        self.encapsulating_funcs.setdefault(self.funcs[-1], []).append(comprehension_fdef)\n        self.nested_funcs[comprehension_fdef] = self.funcs[-1]\n\n        # Push and traverse.\n        self.funcs.append(comprehension_fdef)\n        if isinstance(o, GeneratorExpr):\n            super().visit_generator_expr(o)\n        else:\n            super().visit_dictionary_comprehension(o)\n        self.funcs.pop()\n\n        if pushed_module:\n            self.funcs.pop()\n\n    def visit_generator_expr(self, o: GeneratorExpr) -> None:\n        if _comprehension_has_lambda(o):\n            self._visit_comprehension_with_scope(o)\n        else:\n            super().visit_generator_expr(o)\n\n    def visit_dictionary_comprehension(self, o: DictionaryComprehension) -> None:\n        if _comprehension_has_lambda(o):\n            self._visit_comprehension_with_scope(o)\n        else:\n            super().visit_dictionary_comprehension(o)\n\n    def visit_import(self, imp: Import) -> None:\n        if self._current_import_group is not None:\n            self.module_import_groups[self._current_import_group].append(imp)\n        else:\n            self.module_import_groups[imp] = [imp]\n            self._current_import_group = imp\n        super().visit_import(imp)\n\n    def visit_name_expr(self, expr: NameExpr) -> None:\n        if isinstance(expr.node, (Var, FuncDef)):\n            self.visit_symbol_node(expr.node)\n\n    def visit_var(self, var: Var) -> None:\n        self.visit_symbol_node(var)\n\n    def visit_symbol_node(self, symbol: SymbolNode) -> None:\n        if not self.funcs:\n            # We are not inside a function and hence do not need to do\n            # anything regarding free variables.\n            return\n\n        if symbol in self.symbols_to_funcs:\n            orig_func = self.symbols_to_funcs[symbol]\n            if self.is_parent(self.funcs[-1], orig_func):\n                # The function in which the symbol was previously seen is\n                # nested within the function currently being visited. Thus\n                # the current function is a better candidate to contain the\n                # declaration.\n                self.symbols_to_funcs[symbol] = self.funcs[-1]\n                # TODO: Remove from the orig_func free_variables set?\n                self.free_variables.setdefault(self.funcs[-1], set()).add(symbol)\n\n            elif self.is_parent(orig_func, self.funcs[-1]):\n                # The SymbolNode instance has already been visited\n                # before in a parent function, thus it's a non-local\n                # symbol.\n                self.add_free_variable(symbol)\n\n        else:\n            # This is the first time the SymbolNode is being\n            # visited. We map the SymbolNode to the current FuncDef\n            # being visited to note where it was first visited.\n            self.symbols_to_funcs[symbol] = self.funcs[-1]\n\n    def is_parent(self, fitem: FuncItem, child: FuncItem) -> bool:\n        # Check if child is nested within fdef (possibly indirectly\n        # within multiple nested functions).\n        if child not in self.nested_funcs:\n            return False\n        parent = self.nested_funcs[child]\n        return parent == fitem or self.is_parent(fitem, parent)\n\n    def add_free_variable(self, symbol: SymbolNode) -> None:\n        # Find the function where the symbol was (likely) first declared,\n        # and mark is as a non-local symbol within that function.\n        func = self.symbols_to_funcs[symbol]\n        self.free_variables.setdefault(func, set()).add(symbol)\n"
  },
  {
    "path": "mypyc/irbuild/prepare.py",
    "content": "\"\"\"Prepare for IR transform.\n\nThis needs to run after type checking and before generating IR.\n\nFor example, construct partially initialized FuncIR and ClassIR\nobjects for all functions and classes. This allows us to bind\nreferences to functions and classes before we've generated full IR for\nfunctions or classes.  The actual IR transform will then populate all\nthe missing bits, such as function bodies (basic blocks).\n\nAlso build a mapping from mypy TypeInfos to ClassIR objects.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections import defaultdict\nfrom collections.abc import Iterable\nfrom typing import Final, NamedTuple\n\nfrom mypy.build import Graph\nfrom mypy.nodes import (\n    ARG_STAR,\n    ARG_STAR2,\n    CallExpr,\n    ClassDef,\n    Decorator,\n    Expression,\n    FuncDef,\n    MemberExpr,\n    MypyFile,\n    NameExpr,\n    OverloadedFuncDef,\n    RefExpr,\n    SymbolNode,\n    TypeInfo,\n    Var,\n)\nfrom mypy.semanal import refers_to_fullname\nfrom mypy.traverser import TraverserVisitor\nfrom mypy.types import Instance, Type, get_proper_type\nfrom mypyc.common import FAST_PREFIX, PROPSET_PREFIX, SELF_NAME, get_id_from_name\nfrom mypyc.crash import catch_errors\nfrom mypyc.errors import Errors\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import (\n    FUNC_CLASSMETHOD,\n    FUNC_NORMAL,\n    FUNC_STATICMETHOD,\n    FuncDecl,\n    FuncSignature,\n    RuntimeArg,\n)\nfrom mypyc.ir.ops import DeserMaps\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RType,\n    dict_rprimitive,\n    none_rprimitive,\n    object_pointer_rprimitive,\n    object_rprimitive,\n    tuple_rprimitive,\n)\nfrom mypyc.irbuild.mapper import Mapper\nfrom mypyc.irbuild.util import (\n    get_func_def,\n    get_mypyc_attrs,\n    is_dataclass,\n    is_extension_class,\n    is_trait,\n)\nfrom mypyc.options import CompilerOptions\nfrom mypyc.sametype import is_same_type\n\nGENERATOR_HELPER_NAME: Final = \"__mypyc_generator_helper__\"\n\n\ndef build_type_map(\n    mapper: Mapper,\n    modules: list[MypyFile],\n    graph: Graph,\n    types: dict[Expression, Type],\n    options: CompilerOptions,\n    errors: Errors,\n) -> None:\n    # Collect all classes defined in everything we are compiling\n    classes = []\n    for module in modules:\n        module_classes = [node for node in module.defs if isinstance(node, ClassDef)]\n        classes.extend([(module, cdef) for cdef in module_classes])\n\n    # Collect all class mappings so that we can bind arbitrary class name\n    # references even if there are import cycles.\n    for module, cdef in classes:\n        class_ir = ClassIR(\n            cdef.name,\n            module.fullname,\n            is_trait(cdef),\n            is_abstract=cdef.info.is_abstract,\n            is_final_class=cdef.info.is_final,\n        )\n        class_ir.is_ext_class = is_extension_class(module.path, cdef, errors)\n        if class_ir.is_ext_class:\n            class_ir.deletable = cdef.info.deletable_attributes.copy()\n        # If global optimizations are disabled, turn of tracking of class children\n        if not options.global_opts:\n            class_ir.children = None\n        mapper.type_to_ir[cdef.info] = class_ir\n        mapper.symbol_fullnames.add(class_ir.fullname)\n        class_ir.is_enum = cdef.info.is_enum and len(cdef.info.enum_members) > 0\n\n    # Populate structural information in class IR for extension classes.\n    for module, cdef in classes:\n        with catch_errors(module.path, cdef.line):\n            if mapper.type_to_ir[cdef.info].is_ext_class:\n                prepare_class_def(module.path, module.fullname, cdef, errors, mapper, options)\n            else:\n                prepare_non_ext_class_def(\n                    module.path, module.fullname, cdef, errors, mapper, options\n                )\n\n    # Prepare implicit attribute accessors as needed if an attribute overrides a property.\n    for module, cdef in classes:\n        class_ir = mapper.type_to_ir[cdef.info]\n        if class_ir.is_ext_class:\n            prepare_implicit_property_accessors(cdef.info, class_ir, module.fullname, mapper)\n\n    # Collect all the functions also. We collect from the symbol table\n    # so that we can easily pick out the right copy of a function that\n    # is conditionally defined. This doesn't include nested functions!\n    for module in modules:\n        for func in get_module_func_defs(module):\n            prepare_func_def(module.fullname, None, func, mapper, options)\n            # TODO: what else?\n\n    # Check for incompatible attribute definitions that were not\n    # flagged by mypy but can't be supported when compiling.\n    for module, cdef in classes:\n        class_ir = mapper.type_to_ir[cdef.info]\n        for attr in class_ir.attributes:\n            for base_ir in class_ir.mro[1:]:\n                if attr in base_ir.attributes:\n                    if not is_same_type(class_ir.attributes[attr], base_ir.attributes[attr]):\n                        node = cdef.info.names[attr].node\n                        assert node is not None\n                        kind = \"trait\" if base_ir.is_trait else \"class\"\n                        errors.error(\n                            f'Type of \"{attr}\" is incompatible with '\n                            f'definition in {kind} \"{base_ir.name}\"',\n                            module.path,\n                            node.line,\n                        )\n\n\ndef is_from_module(node: SymbolNode, module: MypyFile) -> bool:\n    return node.fullname == module.fullname + \".\" + node.name\n\n\ndef load_type_map(mapper: Mapper, modules: list[MypyFile], deser_ctx: DeserMaps) -> None:\n    \"\"\"Populate a Mapper with deserialized IR from a list of modules.\"\"\"\n    for module in modules:\n        for node in module.names.values():\n            if (\n                isinstance(node.node, TypeInfo)\n                and is_from_module(node.node, module)\n                and not node.node.is_newtype\n                and not node.node.is_named_tuple\n                and node.node.typeddict_type is None\n            ):\n                ir = deser_ctx.classes[node.node.fullname]\n                mapper.type_to_ir[node.node] = ir\n                mapper.symbol_fullnames.add(node.node.fullname)\n                mapper.func_to_decl[node.node] = ir.ctor\n\n    for module in modules:\n        for func in get_module_func_defs(module):\n            func_id = get_id_from_name(func.name, func.fullname, func.line)\n            mapper.func_to_decl[func] = deser_ctx.functions[func_id].decl\n\n\ndef get_module_func_defs(module: MypyFile) -> Iterable[FuncDef]:\n    \"\"\"Collect all of the (non-method) functions declared in a module.\"\"\"\n    for node in module.names.values():\n        # We need to filter out functions that are imported or\n        # aliases.  The best way to do this seems to be by\n        # checking that the fullname matches.\n        if isinstance(node.node, (FuncDef, Decorator, OverloadedFuncDef)) and is_from_module(\n            node.node, module\n        ):\n            yield get_func_def(node.node)\n\n\ndef prepare_func_def(\n    module_name: str,\n    class_name: str | None,\n    fdef: FuncDef,\n    mapper: Mapper,\n    options: CompilerOptions,\n) -> FuncDecl:\n    kind = (\n        FUNC_CLASSMETHOD\n        if fdef.is_class\n        else (FUNC_STATICMETHOD if fdef.is_static else FUNC_NORMAL)\n    )\n    sig = mapper.fdef_to_sig(fdef, options.strict_dunders_typing)\n    decl = FuncDecl(\n        fdef.name,\n        class_name,\n        module_name,\n        sig,\n        kind,\n        is_generator=fdef.is_generator,\n        is_coroutine=fdef.is_coroutine,\n    )\n    mapper.func_to_decl[fdef] = decl\n    return decl\n\n\ndef create_generator_class_for_func(\n    module_name: str, class_name: str | None, fdef: FuncDef, mapper: Mapper, name_suffix: str = \"\"\n) -> ClassIR:\n    \"\"\"For a generator/async function, declare a generator class.\n\n    Each generator and async function gets a dedicated class that implements the\n    generator protocol with generated methods.\n    \"\"\"\n    assert fdef.is_coroutine or fdef.is_generator\n    name = \"_\".join(x for x in [fdef.name, class_name] if x) + \"_gen\" + name_suffix\n    cir = ClassIR(name, module_name, is_generated=True, is_final_class=class_name is None)\n    cir.reuse_freed_instance = True\n    mapper.fdef_to_generator[fdef] = cir\n\n    helper_sig = FuncSignature(\n        (\n            RuntimeArg(SELF_NAME, object_rprimitive),\n            RuntimeArg(\"type\", object_rprimitive),\n            RuntimeArg(\"value\", object_rprimitive),\n            RuntimeArg(\"traceback\", object_rprimitive),\n            RuntimeArg(\"arg\", object_rprimitive),\n            # If non-NULL, used to store return value instead of raising StopIteration(retv)\n            RuntimeArg(\"stop_iter_ptr\", object_pointer_rprimitive),\n        ),\n        object_rprimitive,\n    )\n\n    # The implementation of most generator functionality is behind this magic method.\n    helper_fn_decl = FuncDecl(GENERATOR_HELPER_NAME, name, module_name, helper_sig, internal=True)\n    cir.method_decls[helper_fn_decl.name] = helper_fn_decl\n    return cir\n\n\ndef prepare_method_def(\n    ir: ClassIR,\n    module_name: str,\n    cdef: ClassDef,\n    mapper: Mapper,\n    node: FuncDef | Decorator,\n    options: CompilerOptions,\n) -> None:\n    if isinstance(node, FuncDef):\n        ir.method_decls[node.name] = prepare_func_def(\n            module_name, cdef.name, node, mapper, options\n        )\n    elif isinstance(node, Decorator):\n        # TODO: do something about abstract methods here. Currently, they are handled just like\n        # normal methods.\n        decl = prepare_func_def(module_name, cdef.name, node.func, mapper, options)\n        if not node.decorators:\n            ir.method_decls[node.name] = decl\n        elif isinstance(node.decorators[0], MemberExpr) and node.decorators[0].name == \"setter\":\n            # Make property setter name different than getter name so there are no\n            # name clashes when generating C code, and property lookup at the IR level\n            # works correctly.\n            decl.name = PROPSET_PREFIX + decl.name\n            decl.is_prop_setter = True\n            # Making the argument implicitly positional-only avoids unnecessary glue methods\n            decl.sig.args[1].pos_only = True\n            ir.method_decls[PROPSET_PREFIX + node.name] = decl\n\n        if node.func.is_property:\n            assert node.func.type, f\"Expected return type annotation for property '{node.name}'\"\n            decl.is_prop_getter = True\n            ir.property_types[node.name] = decl.sig.ret_type\n\n\ndef prepare_fast_path(\n    ir: ClassIR,\n    module_name: str,\n    cdef: ClassDef,\n    mapper: Mapper,\n    node: SymbolNode | None,\n    options: CompilerOptions,\n) -> None:\n    \"\"\"Add fast (direct) variants of methods in non-extension classes.\"\"\"\n    if ir.is_enum:\n        # We check that non-empty enums are implicitly final in mypy, so we\n        # can generate direct calls to enum methods.\n        if isinstance(node, OverloadedFuncDef):\n            if node.is_property:\n                return\n            node = node.impl\n        if not isinstance(node, FuncDef):\n            # TODO: support decorated methods (at least @classmethod and @staticmethod).\n            return\n        # The simplest case is a regular or overloaded method without decorators. In this\n        # case we can generate practically identical IR method body, but with a signature\n        # suitable for direct calls (usual non-extension class methods are converted to\n        # callable classes, and thus have an extra __mypyc_self__ argument).\n        name = FAST_PREFIX + node.name\n        sig = mapper.fdef_to_sig(node, options.strict_dunders_typing)\n        decl = FuncDecl(name, cdef.name, module_name, sig, FUNC_NORMAL)\n        ir.method_decls[name] = decl\n    return\n\n\ndef is_valid_multipart_property_def(prop: OverloadedFuncDef) -> bool:\n    # Checks to ensure supported property decorator semantics\n    if len(prop.items) != 2:\n        return False\n\n    getter = prop.items[0]\n    setter = prop.items[1]\n\n    return (\n        isinstance(getter, Decorator)\n        and isinstance(setter, Decorator)\n        and getter.func.is_property\n        and len(setter.decorators) == 1\n        and isinstance(setter.decorators[0], MemberExpr)\n        and setter.decorators[0].name == \"setter\"\n    )\n\n\ndef can_subclass_builtin(builtin_base: str) -> bool:\n    # BaseException and dict are special cased.\n    return builtin_base in (\n        (\n            \"builtins.Exception\",\n            \"builtins.LookupError\",\n            \"builtins.IndexError\",\n            \"builtins.Warning\",\n            \"builtins.UserWarning\",\n            \"builtins.ValueError\",\n            \"builtins.object\",\n        )\n    )\n\n\ndef prepare_class_def(\n    path: str,\n    module_name: str,\n    cdef: ClassDef,\n    errors: Errors,\n    mapper: Mapper,\n    options: CompilerOptions,\n) -> None:\n    \"\"\"Populate the interface-level information in a class IR.\n\n    This includes attribute and method declarations, and the MRO, among other things, but\n    method bodies are generated in a later pass.\n    \"\"\"\n\n    ir = mapper.type_to_ir[cdef.info]\n    info = cdef.info\n\n    attrs, attrs_lines = get_mypyc_attrs(cdef, path, errors)\n    if attrs.get(\"allow_interpreted_subclasses\") is True:\n        ir.allow_interpreted_subclasses = True\n    if attrs.get(\"serializable\") is True:\n        # Supports copy.copy and pickle (including subclasses)\n        ir._serializable = True\n\n    if attrs.get(\"acyclic\") is True:\n        ir.is_acyclic = True\n\n    free_list_len = attrs.get(\"free_list_len\")\n    if free_list_len is not None:\n        line = attrs_lines[\"free_list_len\"]\n        if ir.is_trait:\n            errors.error('\"free_list_len\" can\\'t be used with traits', path, line)\n        if ir.allow_interpreted_subclasses:\n            errors.error(\n                '\"free_list_len\" can\\'t be used in a class that allows interpreted subclasses',\n                path,\n                line,\n            )\n        if free_list_len == 1:\n            ir.reuse_freed_instance = True\n        else:\n            errors.error(f'Unsupported value for \"free_list_len\": {free_list_len}', path, line)\n\n    # Check for subclassing from builtin types\n    for cls in info.mro:\n        # Special case exceptions and dicts\n        # XXX: How do we handle *other* things??\n        if cls.fullname == \"builtins.BaseException\":\n            ir.builtin_base = \"PyBaseExceptionObject\"\n        elif cls.fullname == \"builtins.dict\":\n            ir.builtin_base = \"PyDictObject\"\n        elif cls.fullname.startswith(\"builtins.\"):\n            if not can_subclass_builtin(cls.fullname):\n                # Note that if we try to subclass a C extension class that\n                # isn't in builtins, bad things will happen and we won't\n                # catch it here! But this should catch a lot of the most\n                # common pitfalls.\n                errors.error(\n                    \"Inheriting from most builtin types is unimplemented\", path, cdef.line\n                )\n                errors.note(\n                    \"Potential workaround: @mypy_extensions.mypyc_attr(native_class=False)\",\n                    path,\n                    cdef.line,\n                )\n                errors.note(\n                    \"https://mypyc.readthedocs.io/en/stable/native_classes.html#defining-non-native-classes\",\n                    path,\n                    cdef.line,\n                )\n\n    # Set up the parent class\n    bases = [mapper.type_to_ir[base.type] for base in info.bases if base.type in mapper.type_to_ir]\n    if len(bases) > 1 and any(not c.is_trait for c in bases) and bases[0].is_trait:\n        # If the first base is a non-trait, don't ever error here. While it is correct\n        # to error if a trait comes before the next non-trait base (e.g. non-trait, trait,\n        # non-trait), it's pointless, confusing noise from the bigger issue: multiple\n        # inheritance is *not* supported.\n        errors.error(\"Non-trait base must appear first in parent list\", path, cdef.line)\n    ir.traits = [c for c in bases if c.is_trait]\n\n    mro = []  # All mypyc base classes\n    base_mro = []  # Non-trait mypyc base classes\n    for cls in info.mro:\n        if cls not in mapper.type_to_ir:\n            if cls.fullname != \"builtins.object\":\n                ir.inherits_python = True\n            continue\n        base_ir = mapper.type_to_ir[cls]\n        if not base_ir.is_trait:\n            base_mro.append(base_ir)\n        mro.append(base_ir)\n\n        if cls.defn.removed_base_type_exprs or not base_ir.is_ext_class:\n            ir.inherits_python = True\n\n    base_idx = 1 if not ir.is_trait else 0\n    if len(base_mro) > base_idx:\n        ir.base = base_mro[base_idx]\n    ir.mro = mro\n    ir.base_mro = base_mro\n\n    prepare_methods_and_attributes(cdef, ir, path, module_name, errors, mapper, options)\n    prepare_init_method(cdef, ir, module_name, mapper)\n\n    for base in bases:\n        if base.children is not None:\n            base.children.append(ir)\n\n    if is_dataclass(cdef):\n        ir.is_augmented = True\n\n\ndef prepare_methods_and_attributes(\n    cdef: ClassDef,\n    ir: ClassIR,\n    path: str,\n    module_name: str,\n    errors: Errors,\n    mapper: Mapper,\n    options: CompilerOptions,\n) -> None:\n    \"\"\"Populate attribute and method declarations.\"\"\"\n    info = cdef.info\n    for name, node in info.names.items():\n        # Currently all plugin generated methods are dummies and not included.\n        if node.plugin_generated:\n            continue\n\n        if isinstance(node.node, Var):\n            assert node.node.type, \"Class member %s missing type\" % name\n            if not node.node.is_classvar and name not in (\"__slots__\", \"__deletable__\"):\n                attr_rtype = mapper.type_to_rtype(node.node.type)\n                if ir.is_trait and attr_rtype.error_overlap:\n                    # Traits don't have attribute definedness bitmaps, so use\n                    # property accessor methods to access attributes that need them.\n                    # We will generate accessor implementations that use the class bitmap\n                    # for any concrete subclasses.\n                    add_getter_declaration(ir, name, attr_rtype, module_name)\n                    add_setter_declaration(ir, name, attr_rtype, module_name)\n                ir.attributes[name] = attr_rtype\n        elif isinstance(node.node, (FuncDef, Decorator)):\n            prepare_method_def(ir, module_name, cdef, mapper, node.node, options)\n        elif isinstance(node.node, OverloadedFuncDef):\n            # Handle case for property with both a getter and a setter\n            if node.node.is_property:\n                if is_valid_multipart_property_def(node.node):\n                    for item in node.node.items:\n                        prepare_method_def(ir, module_name, cdef, mapper, item, options)\n                else:\n                    errors.error(\"Unsupported property decorator semantics\", path, cdef.line)\n\n            # Handle case for regular function overload\n            else:\n                if not node.node.impl:\n                    errors.error(\n                        \"Overloads without implementation are not supported\", path, cdef.line\n                    )\n                else:\n                    prepare_method_def(ir, module_name, cdef, mapper, node.node.impl, options)\n\n    if ir.builtin_base:\n        ir.attributes.clear()\n\n\ndef prepare_implicit_property_accessors(\n    info: TypeInfo, ir: ClassIR, module_name: str, mapper: Mapper\n) -> None:\n    concrete_attributes = set()\n    for base in ir.base_mro:\n        for name, attr_rtype in base.attributes.items():\n            concrete_attributes.add(name)\n            add_property_methods_for_attribute_if_needed(\n                info, ir, name, attr_rtype, module_name, mapper\n            )\n    for base in ir.mro[1:]:\n        if base.is_trait:\n            for name, attr_rtype in base.attributes.items():\n                if name not in concrete_attributes:\n                    add_property_methods_for_attribute_if_needed(\n                        info, ir, name, attr_rtype, module_name, mapper\n                    )\n\n\ndef add_property_methods_for_attribute_if_needed(\n    info: TypeInfo,\n    ir: ClassIR,\n    attr_name: str,\n    attr_rtype: RType,\n    module_name: str,\n    mapper: Mapper,\n) -> None:\n    \"\"\"Add getter and/or setter for attribute if defined as property in a base class.\n\n    Only add declarations. The body IR will be synthesized later during irbuild.\n    \"\"\"\n    for base in info.mro[1:]:\n        if base in mapper.type_to_ir:\n            base_ir = mapper.type_to_ir[base]\n            n = base.names.get(attr_name)\n            if n is None:\n                continue\n            node = n.node\n            if isinstance(node, Decorator) and node.name not in ir.method_decls:\n                # Defined as a read-only property in base class/trait\n                add_getter_declaration(ir, attr_name, attr_rtype, module_name)\n            elif isinstance(node, OverloadedFuncDef) and is_valid_multipart_property_def(node):\n                # Defined as a read-write property in base class/trait\n                add_getter_declaration(ir, attr_name, attr_rtype, module_name)\n                add_setter_declaration(ir, attr_name, attr_rtype, module_name)\n            elif base_ir.is_trait and attr_rtype.error_overlap:\n                add_getter_declaration(ir, attr_name, attr_rtype, module_name)\n                add_setter_declaration(ir, attr_name, attr_rtype, module_name)\n\n\ndef add_getter_declaration(\n    ir: ClassIR, attr_name: str, attr_rtype: RType, module_name: str\n) -> None:\n    self_arg = RuntimeArg(\"self\", RInstance(ir), pos_only=True)\n    sig = FuncSignature([self_arg], attr_rtype)\n    decl = FuncDecl(attr_name, ir.name, module_name, sig, FUNC_NORMAL)\n    decl.is_prop_getter = True\n    decl.implicit = True  # Triggers synthesization\n    ir.method_decls[attr_name] = decl\n    ir.property_types[attr_name] = attr_rtype  # TODO: Needed??\n\n\ndef add_setter_declaration(\n    ir: ClassIR, attr_name: str, attr_rtype: RType, module_name: str\n) -> None:\n    self_arg = RuntimeArg(\"self\", RInstance(ir), pos_only=True)\n    value_arg = RuntimeArg(\"value\", attr_rtype, pos_only=True)\n    sig = FuncSignature([self_arg, value_arg], none_rprimitive)\n    setter_name = PROPSET_PREFIX + attr_name\n    decl = FuncDecl(setter_name, ir.name, module_name, sig, FUNC_NORMAL)\n    decl.is_prop_setter = True\n    decl.implicit = True  # Triggers synthesization\n    ir.method_decls[setter_name] = decl\n\n\ndef check_matching_args(init_sig: FuncSignature, new_sig: FuncSignature) -> bool:\n    num_init_args = len(init_sig.args) - init_sig.num_bitmap_args\n    num_new_args = len(new_sig.args) - new_sig.num_bitmap_args\n    if num_init_args != num_new_args:\n        return False\n\n    for idx in range(1, num_init_args):\n        init_arg = init_sig.args[idx]\n        new_arg = new_sig.args[idx]\n        if init_arg.type != new_arg.type:\n            return False\n\n        if init_arg.kind != new_arg.kind:\n            return False\n\n    return True\n\n\ndef prepare_init_method(cdef: ClassDef, ir: ClassIR, module_name: str, mapper: Mapper) -> None:\n    # Set up a constructor decl\n    init_node = cdef.info[\"__init__\"].node\n\n    new_node: SymbolNode | None = None\n    new_symbol = cdef.info.get(\"__new__\")\n    # We are only interested in __new__ method defined in a user-defined class,\n    # so we ignore it if it comes from a builtin type. It's usually builtins.object\n    # but could also be builtins.type for metaclasses so we detect the prefix which\n    # matches both.\n    if new_symbol and new_symbol.fullname and not new_symbol.fullname.startswith(\"builtins.\"):\n        new_node = new_symbol.node\n    if isinstance(new_node, (Decorator, OverloadedFuncDef)):\n        new_node = get_func_def(new_node)\n    if not ir.is_trait and not ir.builtin_base and isinstance(init_node, FuncDef):\n        init_sig = mapper.fdef_to_sig(init_node, True)\n        args_match = True\n        if isinstance(new_node, FuncDef):\n            new_sig = mapper.fdef_to_sig(new_node, True)\n            args_match = check_matching_args(init_sig, new_sig)\n\n        defining_ir = mapper.type_to_ir.get(init_node.info)\n        # If there is a nontrivial __init__ that wasn't defined in an\n        # extension class, we need to make the constructor take *args,\n        # **kwargs so it can call tp_init.\n        if (\n            (\n                defining_ir is None\n                or not defining_ir.is_ext_class\n                or cdef.info[\"__init__\"].plugin_generated\n            )\n            and init_node.info.fullname != \"builtins.object\"\n        ) or not args_match:\n            init_sig = FuncSignature(\n                [\n                    init_sig.args[0],\n                    RuntimeArg(\"args\", tuple_rprimitive, ARG_STAR),\n                    RuntimeArg(\"kwargs\", dict_rprimitive, ARG_STAR2),\n                ],\n                init_sig.ret_type,\n            )\n\n        last_arg = len(init_sig.args) - init_sig.num_bitmap_args\n        ctor_sig = FuncSignature(init_sig.args[1:last_arg], RInstance(ir))\n        ir.ctor = FuncDecl(cdef.name, None, module_name, ctor_sig)\n        mapper.func_to_decl[cdef.info] = ir.ctor\n\n\ndef prepare_non_ext_class_def(\n    path: str,\n    module_name: str,\n    cdef: ClassDef,\n    errors: Errors,\n    mapper: Mapper,\n    options: CompilerOptions,\n) -> None:\n    ir = mapper.type_to_ir[cdef.info]\n    info = cdef.info\n\n    for node in info.names.values():\n        if isinstance(node.node, (FuncDef, Decorator)):\n            prepare_method_def(ir, module_name, cdef, mapper, node.node, options)\n        elif isinstance(node.node, OverloadedFuncDef):\n            # Handle case for property with both a getter and a setter\n            if node.node.is_property:\n                if not is_valid_multipart_property_def(node.node):\n                    errors.error(\"Unsupported property decorator semantics\", path, cdef.line)\n                for item in node.node.items:\n                    prepare_method_def(ir, module_name, cdef, mapper, item, options)\n            # Handle case for regular function overload\n            else:\n                prepare_method_def(ir, module_name, cdef, mapper, get_func_def(node.node), options)\n\n        prepare_fast_path(ir, module_name, cdef, mapper, node.node, options)\n\n    if any(cls in mapper.type_to_ir and mapper.type_to_ir[cls].is_ext_class for cls in info.mro):\n        errors.error(\n            \"Non-extension classes may not inherit from extension classes\", path, cdef.line\n        )\n\n\nRegisterImplInfo = tuple[TypeInfo, FuncDef]\n\n\nclass SingledispatchInfo(NamedTuple):\n    singledispatch_impls: dict[FuncDef, list[RegisterImplInfo]]\n    decorators_to_remove: dict[FuncDef, list[int]]\n\n\ndef find_singledispatch_register_impls(\n    modules: list[MypyFile], errors: Errors\n) -> SingledispatchInfo:\n    visitor = SingledispatchVisitor(errors)\n    for module in modules:\n        visitor.current_path = module.path\n        module.accept(visitor)\n    return SingledispatchInfo(visitor.singledispatch_impls, visitor.decorators_to_remove)\n\n\nclass SingledispatchVisitor(TraverserVisitor):\n    current_path: str\n\n    def __init__(self, errors: Errors) -> None:\n        super().__init__()\n\n        # Map of main singledispatch function to list of registered implementations\n        self.singledispatch_impls: defaultdict[FuncDef, list[RegisterImplInfo]] = defaultdict(list)\n\n        # Map of decorated function to the indices of any decorators to remove\n        self.decorators_to_remove: dict[FuncDef, list[int]] = {}\n\n        self.errors: Errors = errors\n        self.func_stack_depth = 0\n\n    def visit_func_def(self, o: FuncDef) -> None:\n        self.func_stack_depth += 1\n        super().visit_func_def(o)\n        self.func_stack_depth -= 1\n\n    def visit_decorator(self, dec: Decorator) -> None:\n        if dec.decorators:\n            decorators_to_store = dec.decorators.copy()\n            decorators_to_remove: list[int] = []\n            # the index of the last non-register decorator before finding a register decorator\n            # when going through decorators from top to bottom\n            last_non_register: int | None = None\n            for i, d in enumerate(decorators_to_store):\n                impl = get_singledispatch_register_call_info(d, dec.func)\n                if impl is not None:\n                    if self.func_stack_depth > 0:\n                        self.errors.error(\n                            \"Registering nested functions not supported\", self.current_path, d.line\n                        )\n                    self.singledispatch_impls[impl.singledispatch_func].append(\n                        (impl.dispatch_type, dec.func)\n                    )\n                    decorators_to_remove.append(i)\n                    if last_non_register is not None:\n                        # found a register decorator after a non-register decorator, which we\n                        # don't support because we'd have to make a copy of the function before\n                        # calling the decorator so that we can call it later, which complicates\n                        # the implementation for something that is probably not commonly used\n                        self.errors.error(\n                            \"Calling decorator after registering function not supported\",\n                            self.current_path,\n                            decorators_to_store[last_non_register].line,\n                        )\n                else:\n                    if refers_to_fullname(d, \"functools.singledispatch\"):\n                        if self.func_stack_depth > 0:\n                            self.errors.error(\n                                \"Nested singledispatch functions not supported\",\n                                self.current_path,\n                                d.line,\n                            )\n                        decorators_to_remove.append(i)\n                        # make sure that we still treat the function as a singledispatch function\n                        # even if we don't find any registered implementations (which might happen\n                        # if all registered implementations are registered dynamically)\n                        self.singledispatch_impls.setdefault(dec.func, [])\n                    last_non_register = i\n\n            if decorators_to_remove:\n                # calling register on a function that tries to dispatch based on type annotations\n                # raises a TypeError because compiled functions don't have an __annotations__\n                # attribute\n                self.decorators_to_remove[dec.func] = decorators_to_remove\n\n        super().visit_decorator(dec)\n\n\nclass RegisteredImpl(NamedTuple):\n    singledispatch_func: FuncDef\n    dispatch_type: TypeInfo\n\n\ndef get_singledispatch_register_call_info(\n    decorator: Expression, func: FuncDef\n) -> RegisteredImpl | None:\n    # @fun.register(complex)\n    # def g(arg): ...\n    if (\n        isinstance(decorator, CallExpr)\n        and len(decorator.args) == 1\n        and isinstance(decorator.args[0], RefExpr)\n    ):\n        callee = decorator.callee\n        dispatch_type = decorator.args[0].node\n        if not isinstance(dispatch_type, TypeInfo):\n            return None\n\n        if isinstance(callee, MemberExpr):\n            return registered_impl_from_possible_register_call(callee, dispatch_type)\n    # @fun.register\n    # def g(arg: int): ...\n    elif isinstance(decorator, MemberExpr):\n        # we don't know if this is a register call yet, so we can't be sure that the function\n        # actually has arguments\n        if not func.arguments:\n            return None\n        arg_type = get_proper_type(func.arguments[0].variable.type)\n        if not isinstance(arg_type, Instance):\n            return None\n        info = arg_type.type\n        return registered_impl_from_possible_register_call(decorator, info)\n    return None\n\n\ndef registered_impl_from_possible_register_call(\n    expr: MemberExpr, dispatch_type: TypeInfo\n) -> RegisteredImpl | None:\n    if expr.name == \"register\" and isinstance(expr.expr, NameExpr):\n        node = expr.expr.node\n        if isinstance(node, Decorator):\n            return RegisteredImpl(node.func, dispatch_type)\n    return None\n\n\ndef adjust_generator_classes_of_methods(mapper: Mapper) -> None:\n    \"\"\"Make optimizations and adjustments to generated generator classes of methods.\n\n    This is a separate pass after type map has been built, since we need all classes\n    to be processed to analyze class hierarchies.\n    \"\"\"\n\n    generator_methods = []\n\n    for fdef, fn_ir in mapper.func_to_decl.items():\n        if isinstance(fdef, FuncDef) and (fdef.is_coroutine or fdef.is_generator):\n            gen_ir = create_generator_class_for_func(\n                fn_ir.module_name, fn_ir.class_name, fdef, mapper\n            )\n            # TODO: We could probably support decorators sometimes (static and class method?)\n            if not fdef.is_decorated:\n                name = fn_ir.name\n                precise_ret_type = True\n                if fn_ir.class_name is not None:\n                    class_ir = mapper.type_to_ir[fdef.info]\n                    subcls = class_ir.subclasses()\n                    if subcls is None:\n                        # Override could be of a different type, so we can't make assumptions.\n                        precise_ret_type = False\n                    elif class_ir.is_trait:\n                        # Give up on traits. We could possibly have an abstract base class\n                        # for generator return types to make this use precise types.\n                        precise_ret_type = False\n                    else:\n                        for s in subcls:\n                            if name in s.method_decls:\n                                m = s.method_decls[name]\n                                if (\n                                    m.is_generator != fn_ir.is_generator\n                                    or m.is_coroutine != fn_ir.is_coroutine\n                                ):\n                                    # Override is of a different kind, and the optimization\n                                    # to use a precise generator return type doesn't work.\n                                    precise_ret_type = False\n                else:\n                    class_ir = None\n\n                if precise_ret_type:\n                    # Give a more precise type for generators, so that we can optimize\n                    # code that uses them. They return a generator object, which has a\n                    # specific class. Without this, the type would have to be 'object'.\n                    fn_ir.sig.ret_type = RInstance(gen_ir)\n                    if fn_ir.bound_sig:\n                        fn_ir.bound_sig.ret_type = RInstance(gen_ir)\n                    if class_ir is not None:\n                        if class_ir.is_method_final(name):\n                            gen_ir.is_final_class = True\n                        generator_methods.append((name, class_ir, gen_ir))\n\n    new_bases = {}\n\n    for name, class_ir, gen in generator_methods:\n        # For generator methods, we need to have subclass generator classes inherit from\n        # baseclass generator classes when there are overrides to maintain LSP.\n        base = class_ir.real_base()\n        if base is not None:\n            if base.has_method(name):\n                base_sig = base.method_sig(name)\n                if isinstance(base_sig.ret_type, RInstance):\n                    base_gen = base_sig.ret_type.class_ir\n                    new_bases[gen] = base_gen\n\n    # Add generator inheritance relationships by adjusting MROs.\n    for deriv, base in new_bases.items():\n        if base.children is not None:\n            base.children.append(deriv)\n        while True:\n            deriv.mro.append(base)\n            deriv.base_mro.append(base)\n            if base not in new_bases:\n                break\n            base = new_bases[base]\n"
  },
  {
    "path": "mypyc/irbuild/specialize.py",
    "content": "\"\"\"Special case IR generation of calls to specific builtin functions.\n\nMost special cases should be handled using the data driven \"primitive\nops\" system, but certain operations require special handling that has\naccess to the AST/IR directly and can make decisions/optimizations\nbased on it. These special cases can be implemented here.\n\nFor example, we use specializers to statically emit the length of a\nfixed length tuple and to emit optimized code for any()/all() calls with\ngenerator comprehensions as the argument.\n\nSee comment below for more documentation.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Callable\nfrom typing import Final, cast\n\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    CallExpr,\n    DictExpr,\n    Expression,\n    GeneratorExpr,\n    IndexExpr,\n    IntExpr,\n    ListExpr,\n    MemberExpr,\n    NameExpr,\n    RefExpr,\n    StrExpr,\n    SuperExpr,\n    TupleExpr,\n    Var,\n)\nfrom mypy.types import AnyType, TypeOfAny\nfrom mypyc.ir.ops import (\n    BasicBlock,\n    Call,\n    Extend,\n    Integer,\n    PrimitiveDescription,\n    RaiseStandardError,\n    Register,\n    SetAttr,\n    Truncate,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RPrimitive,\n    RTuple,\n    RType,\n    RVec,\n    bool_rprimitive,\n    bytes_rprimitive,\n    bytes_writer_rprimitive,\n    c_int_rprimitive,\n    dict_rprimitive,\n    int16_rprimitive,\n    int32_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    is_bool_rprimitive,\n    is_dict_rprimitive,\n    is_fixed_width_rtype,\n    is_float_rprimitive,\n    is_int16_rprimitive,\n    is_int32_rprimitive,\n    is_int64_rprimitive,\n    is_int_rprimitive,\n    is_list_rprimitive,\n    is_sequence_rprimitive,\n    is_str_rprimitive,\n    is_tagged,\n    is_uint8_rprimitive,\n    list_rprimitive,\n    object_rprimitive,\n    set_rprimitive,\n    str_rprimitive,\n    string_writer_rprimitive,\n    uint8_rprimitive,\n)\nfrom mypyc.irbuild.builder import IRBuilder\nfrom mypyc.irbuild.constant_fold import constant_fold_expr\nfrom mypyc.irbuild.for_helpers import (\n    comprehension_helper,\n    get_expr_length_value,\n    sequence_from_generator_preallocate_helper,\n    translate_list_comprehension,\n    translate_set_comprehension,\n)\nfrom mypyc.irbuild.format_str_tokenizer import (\n    FormatOp,\n    convert_format_expr_to_str,\n    join_formatted_strings,\n    tokenizer_format_call,\n)\nfrom mypyc.irbuild.vec import vec_append, vec_pop, vec_remove\nfrom mypyc.primitives.bytearray_ops import isinstance_bytearray\nfrom mypyc.primitives.bytes_ops import (\n    bytes_adjust_index_op,\n    bytes_get_item_unsafe_op,\n    bytes_range_check_op,\n    isinstance_bytes,\n)\nfrom mypyc.primitives.dict_ops import (\n    dict_items_op,\n    dict_keys_op,\n    dict_setdefault_spec_init_op,\n    dict_values_op,\n    isinstance_dict,\n)\nfrom mypyc.primitives.float_ops import isinstance_float\nfrom mypyc.primitives.generic_ops import generic_setattr, setup_object\nfrom mypyc.primitives.int_ops import (\n    int_to_big_endian_op,\n    int_to_bytes_op,\n    int_to_little_endian_op,\n    isinstance_int,\n)\nfrom mypyc.primitives.librt_strings_ops import (\n    bytes_writer_adjust_index_op,\n    bytes_writer_get_item_unsafe_op,\n    bytes_writer_range_check_op,\n    bytes_writer_set_item_unsafe_op,\n    string_writer_adjust_index_op,\n    string_writer_get_item_unsafe_op,\n    string_writer_range_check_op,\n)\nfrom mypyc.primitives.librt_vecs_ops import isinstance_vec\nfrom mypyc.primitives.list_ops import isinstance_list, new_list_set_item_op\nfrom mypyc.primitives.misc_ops import isinstance_bool\nfrom mypyc.primitives.set_ops import isinstance_frozenset, isinstance_set\nfrom mypyc.primitives.str_ops import (\n    bytes_decode_ascii_strict,\n    bytes_decode_latin1_strict,\n    bytes_decode_utf8_strict,\n    isinstance_str,\n    str_adjust_index_op,\n    str_encode_ascii_strict,\n    str_encode_latin1_strict,\n    str_encode_utf8_strict,\n    str_get_item_unsafe_as_int_op,\n    str_range_check_op,\n)\nfrom mypyc.primitives.tuple_ops import isinstance_tuple, new_tuple_set_item_op\n\n# Specializers are attempted before compiling the arguments to the\n# function.  Specializers can return None to indicate that they failed\n# and the call should be compiled normally. Otherwise they should emit\n# code for the call and return a Value containing the result.\n#\n# Specializers take three arguments: the IRBuilder, the CallExpr being\n# compiled, and the RefExpr that is the left hand side of the call.\nSpecializer = Callable[[\"IRBuilder\", CallExpr, RefExpr], Value | None]\n\n# Dunder specializers are for special method calls like __getitem__, __setitem__, etc.\n# that don't naturally map to CallExpr nodes (e.g., from IndexExpr).\n#\n# They take four arguments: the IRBuilder, the base expression (target object),\n# the list of argument expressions (positional arguments to the dunder), and the\n# context expression (e.g., IndexExpr) for error reporting.\nDunderSpecializer = Callable[[\"IRBuilder\", Expression, list[Expression], Expression], Value | None]\n\n# Dictionary containing all configured specializers.\n#\n# Specializers can operate on methods as well, and are keyed on the\n# name and RType in that case.\nspecializers: dict[tuple[str, RType | None], list[Specializer]] = {}\n\n# Dictionary containing all configured dunder specializers.\n#\n# Dunder specializers are keyed on the dunder name and RType (always a method call).\ndunder_specializers: dict[tuple[str, RType], list[DunderSpecializer]] = {}\n\n\ndef _apply_specialization(\n    builder: IRBuilder, expr: CallExpr, callee: RefExpr, name: str | None, typ: RType | None = None\n) -> Value | None:\n    # TODO: Allow special cases to have default args or named args. Currently they don't since\n    #       they check that everything in arg_kinds is ARG_POS.\n\n    # If there is a specializer for this function, try calling it.\n    # Return the first successful one.\n    if name and (name, typ) in specializers:\n        for specializer in specializers[name, typ]:\n            val = specializer(builder, expr, callee)\n            if val is not None:\n                return val\n    return None\n\n\ndef apply_function_specialization(\n    builder: IRBuilder, expr: CallExpr, callee: RefExpr\n) -> Value | None:\n    \"\"\"Invoke the Specializer callback for a function if one has been registered\"\"\"\n    return _apply_specialization(builder, expr, callee, callee.fullname)\n\n\ndef apply_method_specialization(\n    builder: IRBuilder, expr: CallExpr, callee: MemberExpr, typ: RType | None = None\n) -> Value | None:\n    \"\"\"Invoke the Specializer callback for a method if one has been registered\"\"\"\n    name = callee.fullname if typ is None else callee.name\n    return _apply_specialization(builder, expr, callee, name, typ)\n\n\ndef specialize_function(\n    name: str, typ: RType | None = None\n) -> Callable[[Specializer], Specializer]:\n    \"\"\"Decorator to register a function as being a specializer.\n\n    There may exist multiple specializers for one function. When\n    translating method calls, the earlier appended specializer has\n    higher priority.\n    \"\"\"\n\n    def wrapper(f: Specializer) -> Specializer:\n        specializers.setdefault((name, typ), []).append(f)\n        return f\n\n    return wrapper\n\n\ndef specialize_dunder(name: str, typ: RType) -> Callable[[DunderSpecializer], DunderSpecializer]:\n    \"\"\"Decorator to register a function as being a dunder specializer.\n\n    Dunder specializers handle special method calls like __getitem__ that\n    don't naturally map to CallExpr nodes.\n\n    There may exist multiple specializers for one dunder. When translating\n    dunder calls, the earlier appended specializer has higher priority.\n    \"\"\"\n\n    def wrapper(f: DunderSpecializer) -> DunderSpecializer:\n        dunder_specializers.setdefault((name, typ), []).append(f)\n        return f\n\n    return wrapper\n\n\ndef apply_dunder_specialization(\n    builder: IRBuilder,\n    base_expr: Expression,\n    args: list[Expression],\n    name: str,\n    ctx_expr: Expression,\n) -> Value | None:\n    \"\"\"Invoke the DunderSpecializer callback if one has been registered.\n\n    Args:\n        builder: The IR builder\n        base_expr: The base expression (target object)\n        args: List of argument expressions (positional arguments to the dunder)\n        name: The dunder method name (e.g., \"__getitem__\")\n        ctx_expr: The context expression for error reporting (e.g., IndexExpr)\n\n    Returns:\n        The specialized value, or None if no specialization was found.\n    \"\"\"\n    base_type = builder.node_type(base_expr)\n\n    # Check if there's a specializer for this dunder method and type\n    if (name, base_type) in dunder_specializers:\n        for specializer in dunder_specializers[name, base_type]:\n            val = specializer(builder, base_expr, args, ctx_expr)\n            if val is not None:\n                return val\n    return None\n\n\n@specialize_function(\"builtins.globals\")\ndef translate_globals(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) == 0:\n        return builder.load_globals_dict()\n    return None\n\n\n@specialize_function(\"builtins.abs\")\n@specialize_function(\"builtins.int\")\n@specialize_function(\"builtins.float\")\n@specialize_function(\"builtins.complex\")\n@specialize_function(\"mypy_extensions.i64\")\n@specialize_function(\"mypy_extensions.i32\")\n@specialize_function(\"mypy_extensions.i16\")\n@specialize_function(\"mypy_extensions.u8\")\ndef translate_builtins_with_unary_dunder(\n    builder: IRBuilder, expr: CallExpr, callee: RefExpr\n) -> Value | None:\n    \"\"\"Specialize calls on native classes that implement the associated dunder.\n\n    E.g. i64(x) gets specialized to x.__int__() if x is a native instance.\n    \"\"\"\n    if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS] and isinstance(callee, NameExpr):\n        arg = expr.args[0]\n        arg_typ = builder.node_type(arg)\n        shortname = callee.fullname.split(\".\")[1]\n        if shortname in (\"i64\", \"i32\", \"i16\", \"u8\"):\n            method = \"__int__\"\n        else:\n            method = f\"__{shortname}__\"\n        if isinstance(arg_typ, RInstance) and arg_typ.class_ir.has_method(method):\n            obj = builder.accept(arg)\n            return builder.gen_method_call(obj, method, [], None, expr.line)\n\n    return None\n\n\n@specialize_function(\"builtins.len\")\ndef translate_len(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]:\n        arg = expr.args[0]\n        expr_rtype = builder.node_type(arg)\n        # NOTE (?) I'm not sure if my handling of can_borrow is correct here\n        obj = builder.accept(\n            arg, can_borrow=is_list_rprimitive(expr_rtype) or isinstance(expr_rtype, RVec)\n        )\n        if is_sequence_rprimitive(expr_rtype) or isinstance(expr_rtype, RTuple):\n            return get_expr_length_value(builder, arg, obj, expr.line, use_pyssize_t=False)\n        else:\n            # TODO: Decide type of result based on context somehow?\n            if isinstance(obj.type, RVec):\n                return builder.builtin_len(obj, expr.line, use_pyssize_t=True)\n            else:\n                return builder.builtin_len(obj, expr.line)\n    return None\n\n\n@specialize_function(\"builtins.list\")\ndef dict_methods_fast_path(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    \"\"\"Specialize a common case when list() is called on a dictionary\n    view method call.\n\n    For example:\n        foo = list(bar.keys())\n    \"\"\"\n    if not (len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]):\n        return None\n    arg = expr.args[0]\n    if not (isinstance(arg, CallExpr) and not arg.args and isinstance(arg.callee, MemberExpr)):\n        return None\n    base = arg.callee.expr\n    attr = arg.callee.name\n    rtype = builder.node_type(base)\n    if not (is_dict_rprimitive(rtype) and attr in (\"keys\", \"values\", \"items\")):\n        return None\n\n    obj = builder.accept(base)\n    # Note that it is not safe to use fast methods on dict subclasses,\n    # so the corresponding helpers in CPy.h fallback to (inlined)\n    # generic logic.\n    if attr == \"keys\":\n        return builder.call_c(dict_keys_op, [obj], expr.line)\n    elif attr == \"values\":\n        return builder.call_c(dict_values_op, [obj], expr.line)\n    else:\n        return builder.call_c(dict_items_op, [obj], expr.line)\n\n\n@specialize_function(\"builtins.list\")\ndef translate_list_from_generator_call(\n    builder: IRBuilder, expr: CallExpr, callee: RefExpr\n) -> Value | None:\n    \"\"\"Special case for simplest list comprehension.\n\n    For example:\n        list(f(x) for x in some_list/some_tuple/some_str)\n    'translate_list_comprehension()' would take care of other cases\n    if this fails.\n    \"\"\"\n    if (\n        len(expr.args) == 1\n        and expr.arg_kinds[0] == ARG_POS\n        and isinstance(expr.args[0], GeneratorExpr)\n    ):\n\n        def set_item(x: Value, y: Value, z: Value, line: int) -> None:\n            builder.call_c(new_list_set_item_op, [x, y, z], line)\n\n        return sequence_from_generator_preallocate_helper(\n            builder,\n            expr.args[0],\n            empty_op_llbuilder=builder.builder.new_list_op_with_length,\n            set_item_op=set_item,\n        )\n    return None\n\n\n@specialize_function(\"builtins.tuple\")\ndef translate_tuple_from_generator_call(\n    builder: IRBuilder, expr: CallExpr, callee: RefExpr\n) -> Value | None:\n    \"\"\"Special case for simplest tuple creation from a generator.\n\n    For example:\n        tuple(f(x) for x in some_list/some_tuple/some_str/some_bytes)\n    'translate_safe_generator_call()' would take care of other cases\n    if this fails.\n    \"\"\"\n    if (\n        len(expr.args) == 1\n        and expr.arg_kinds[0] == ARG_POS\n        and isinstance(expr.args[0], GeneratorExpr)\n    ):\n\n        def set_item(x: Value, y: Value, z: Value, line: int) -> None:\n            builder.call_c(new_tuple_set_item_op, [x, y, z], line)\n\n        return sequence_from_generator_preallocate_helper(\n            builder,\n            expr.args[0],\n            empty_op_llbuilder=builder.builder.new_tuple_with_length,\n            set_item_op=set_item,\n        )\n    return None\n\n\n@specialize_function(\"builtins.set\")\ndef translate_set_from_generator_call(\n    builder: IRBuilder, expr: CallExpr, callee: RefExpr\n) -> Value | None:\n    \"\"\"Special case for set creation from a generator.\n\n    For example:\n        set(f(...) for ... in iterator/nested_generators...)\n    \"\"\"\n    if (\n        len(expr.args) == 1\n        and expr.arg_kinds[0] == ARG_POS\n        and isinstance(expr.args[0], GeneratorExpr)\n    ):\n        return translate_set_comprehension(builder, expr.args[0])\n    return None\n\n\n@specialize_function(\"builtins.min\")\n@specialize_function(\"builtins.max\")\ndef faster_min_max(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if expr.arg_kinds == [ARG_POS, ARG_POS]:\n        x, y = builder.accept(expr.args[0]), builder.accept(expr.args[1])\n        result = Register(builder.node_type(expr))\n        # CPython evaluates arguments reversely when calling min(...) or max(...)\n        if callee.fullname == \"builtins.min\":\n            comparison = builder.binary_op(y, x, \"<\", expr.line)\n        else:\n            comparison = builder.binary_op(y, x, \">\", expr.line)\n\n        true_block, false_block, next_block = BasicBlock(), BasicBlock(), BasicBlock()\n        builder.add_bool_branch(comparison, true_block, false_block)\n\n        builder.activate_block(true_block)\n        builder.assign(result, builder.coerce(y, result.type, expr.line), expr.line)\n        builder.goto(next_block)\n\n        builder.activate_block(false_block)\n        builder.assign(result, builder.coerce(x, result.type, expr.line), expr.line)\n        builder.goto(next_block)\n\n        builder.activate_block(next_block)\n        return result\n    return None\n\n\n@specialize_function(\"builtins.tuple\")\n@specialize_function(\"builtins.frozenset\")\n@specialize_function(\"builtins.dict\")\n@specialize_function(\"builtins.min\")\n@specialize_function(\"builtins.max\")\n@specialize_function(\"builtins.sorted\")\n@specialize_function(\"collections.OrderedDict\")\n@specialize_function(\"join\", str_rprimitive)\n@specialize_function(\"extend\", list_rprimitive)\n@specialize_function(\"update\", dict_rprimitive)\n@specialize_function(\"update\", set_rprimitive)\ndef translate_safe_generator_call(\n    builder: IRBuilder, expr: CallExpr, callee: RefExpr\n) -> Value | None:\n    \"\"\"Special cases for things that consume iterators where we know we\n    can safely compile a generator into a list.\n    \"\"\"\n    if (\n        len(expr.args) > 0\n        and expr.arg_kinds[0] == ARG_POS\n        and isinstance(expr.args[0], GeneratorExpr)\n    ):\n        if isinstance(callee, MemberExpr):\n            return builder.gen_method_call(\n                builder.accept(callee.expr),\n                callee.name,\n                (\n                    [translate_list_comprehension(builder, expr.args[0])]\n                    + [builder.accept(arg) for arg in expr.args[1:]]\n                ),\n                builder.node_type(expr),\n                expr.line,\n                expr.arg_kinds,\n                expr.arg_names,\n            )\n        else:\n            return builder.call_refexpr_with_args(\n                expr,\n                callee,\n                (\n                    [translate_list_comprehension(builder, expr.args[0])]\n                    + [builder.accept(arg) for arg in expr.args[1:]]\n                ),\n            )\n    return None\n\n\n@specialize_function(\"builtins.any\")\ndef translate_any_call(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if (\n        len(expr.args) == 1\n        and expr.arg_kinds == [ARG_POS]\n        and isinstance(expr.args[0], GeneratorExpr)\n    ):\n        return any_all_helper(builder, expr.args[0], builder.false, lambda x: x, builder.true)\n    return None\n\n\n@specialize_function(\"builtins.all\")\ndef translate_all_call(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if (\n        len(expr.args) == 1\n        and expr.arg_kinds == [ARG_POS]\n        and isinstance(expr.args[0], GeneratorExpr)\n    ):\n        return any_all_helper(\n            builder,\n            expr.args[0],\n            builder.true,\n            lambda x: builder.unary_op(x, \"not\", expr.line),\n            builder.false,\n        )\n    return None\n\n\ndef any_all_helper(\n    builder: IRBuilder,\n    gen: GeneratorExpr,\n    initial_value: Callable[[], Value],\n    modify: Callable[[Value], Value],\n    new_value: Callable[[], Value],\n) -> Value:\n    init_val = initial_value()\n    retval = Register(bool_rprimitive, line=init_val.line)\n    builder.assign(retval, init_val, init_val.line)\n    loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async))\n    true_block, false_block, exit_block = BasicBlock(), BasicBlock(), BasicBlock()\n\n    def gen_inner_stmts() -> None:\n        comparison = modify(builder.accept(gen.left_expr))\n        builder.add_bool_branch(comparison, true_block, false_block)\n        builder.activate_block(true_block)\n        new_val = new_value()\n        builder.assign(retval, new_val, new_val.line)\n        builder.goto(exit_block)\n        builder.activate_block(false_block)\n\n    comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)\n    builder.goto_and_activate(exit_block)\n\n    return retval\n\n\n@specialize_function(\"builtins.sum\")\ndef translate_sum_call(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    # specialized implementation is used if:\n    # - only one or two arguments given (if not, sum() has been given invalid arguments)\n    # - first argument is a Generator (there is no benefit to optimizing the performance of eg.\n    #   sum([1, 2, 3]), so non-Generator Iterables are not handled)\n    if not (\n        len(expr.args) in (1, 2)\n        and expr.arg_kinds[0] == ARG_POS\n        and isinstance(expr.args[0], GeneratorExpr)\n    ):\n        return None\n\n    # handle 'start' argument, if given\n    if len(expr.args) == 2:\n        # ensure call to sum() was properly constructed\n        if expr.arg_kinds[1] not in (ARG_POS, ARG_NAMED):\n            return None\n        start_expr = expr.args[1]\n    else:\n        start_expr = IntExpr(0)\n\n    gen_expr = expr.args[0]\n    target_type = builder.node_type(expr)\n    retval = Register(target_type, line=expr.line)\n    builder.assign(\n        retval, builder.coerce(builder.accept(start_expr), target_type, expr.line), expr.line\n    )\n\n    def gen_inner_stmts() -> None:\n        call_expr = builder.accept(gen_expr.left_expr)\n        builder.assign(\n            retval, builder.binary_op(retval, call_expr, \"+\", call_expr.line), call_expr.line\n        )\n\n    loop_params = list(\n        zip(gen_expr.indices, gen_expr.sequences, gen_expr.condlists, gen_expr.is_async)\n    )\n    comprehension_helper(builder, loop_params, gen_inner_stmts, gen_expr.line)\n\n    return retval\n\n\n@specialize_function(\"dataclasses.field\")\n@specialize_function(\"attr.ib\")\n@specialize_function(\"attr.attrib\")\n@specialize_function(\"attr.Factory\")\ndef translate_dataclasses_field_call(\n    builder: IRBuilder, expr: CallExpr, callee: RefExpr\n) -> Value | None:\n    \"\"\"Special case for 'dataclasses.field', 'attr.attrib', and 'attr.Factory'\n    function calls because the results of such calls are type-checked\n    by mypy using the types of the arguments to their respective\n    functions, resulting in attempted coercions by mypyc that throw a\n    runtime error.\n    \"\"\"\n    builder.types[expr] = AnyType(TypeOfAny.from_error)\n    return None\n\n\n@specialize_function(\"builtins.next\")\ndef translate_next_call(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    \"\"\"Special case for calling next() on a generator expression, an\n    idiom that shows up some in mypy.\n\n    For example, next(x for x in l if x.id == 12, None) will\n    generate code that searches l for an element where x.id == 12\n    and produce the first such object, or None if no such element\n    exists.\n    \"\"\"\n    if not (\n        expr.arg_kinds in ([ARG_POS], [ARG_POS, ARG_POS])\n        and isinstance(expr.args[0], GeneratorExpr)\n    ):\n        return None\n\n    gen = expr.args[0]\n    retval = Register(builder.node_type(expr))\n    default_val = builder.accept(expr.args[1]) if len(expr.args) > 1 else None\n    exit_block = BasicBlock()\n\n    def gen_inner_stmts() -> None:\n        # next takes the first element of the generator, so if\n        # something gets produced, we are done.\n        builder.assign(retval, builder.accept(gen.left_expr), gen.left_expr.line)\n        builder.goto(exit_block)\n\n    loop_params = list(zip(gen.indices, gen.sequences, gen.condlists, gen.is_async))\n    comprehension_helper(builder, loop_params, gen_inner_stmts, gen.line)\n\n    # Now we need the case for when nothing got hit. If there was\n    # a default value, we produce it, and otherwise we raise\n    # StopIteration.\n    if default_val:\n        builder.assign(retval, default_val, gen.left_expr.line)\n        builder.goto(exit_block)\n    else:\n        builder.add(RaiseStandardError(RaiseStandardError.STOP_ITERATION, None, expr.line))\n        builder.add(Unreachable())\n\n    builder.activate_block(exit_block)\n    return retval\n\n\nisinstance_primitives: Final = {\n    \"builtins.bool\": isinstance_bool,\n    \"builtins.bytearray\": isinstance_bytearray,\n    \"builtins.bytes\": isinstance_bytes,\n    \"builtins.dict\": isinstance_dict,\n    \"builtins.float\": isinstance_float,\n    \"builtins.frozenset\": isinstance_frozenset,\n    \"builtins.int\": isinstance_int,\n    \"builtins.list\": isinstance_list,\n    \"builtins.set\": isinstance_set,\n    \"builtins.str\": isinstance_str,\n    \"builtins.tuple\": isinstance_tuple,\n    \"librt.vecs.vec\": isinstance_vec,\n}\n\n\n@specialize_function(\"builtins.isinstance\")\ndef translate_isinstance(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    \"\"\"Special case for builtins.isinstance.\n\n    Prevent coercions on the thing we are checking the instance of -\n    there is no need to coerce something to a new type before checking\n    what type it is, and the coercion could lead to bugs.\n    \"\"\"\n    if not (len(expr.args) == 2 and expr.arg_kinds == [ARG_POS, ARG_POS]):\n        return None\n\n    obj_expr = expr.args[0]\n    type_expr = expr.args[1]\n\n    if isinstance(type_expr, TupleExpr) and not type_expr.items:\n        # we can compile this case to a noop\n        return builder.false()\n\n    if isinstance(type_expr, (RefExpr, TupleExpr)):\n        builder.types[obj_expr] = AnyType(TypeOfAny.from_error)\n\n        irs = builder.flatten_classes(type_expr)\n        if irs is not None:\n            can_borrow = all(\n                ir.is_ext_class and not ir.inherits_python and not ir.allow_interpreted_subclasses\n                for ir in irs\n            )\n            obj = builder.accept(obj_expr, can_borrow=can_borrow)\n            return builder.builder.isinstance_helper(obj, irs, expr.line)\n\n    if isinstance(type_expr, RefExpr):\n        node = type_expr.node\n        if node:\n            desc = isinstance_primitives.get(node.fullname)\n            if desc:\n                obj = builder.accept(obj_expr)\n                return builder.primitive_op(desc, [obj], expr.line)\n\n    elif isinstance(type_expr, TupleExpr):\n        node_names: list[str] = []\n        for item in type_expr.items:\n            if not isinstance(item, RefExpr):\n                return None\n            if item.node is None:\n                return None\n            if item.node.fullname not in node_names:\n                node_names.append(item.node.fullname)\n\n        descs = [isinstance_primitives.get(fullname) for fullname in node_names]\n        if None in descs:\n            # not all types are primitive types, abort\n            return None\n\n        obj = builder.accept(obj_expr)\n\n        retval = Register(bool_rprimitive)\n        pass_block = BasicBlock()\n        fail_block = BasicBlock()\n        exit_block = BasicBlock()\n\n        # Chain the checks: if any succeed, jump to pass_block; else, continue\n        for i, desc in enumerate(descs):\n            is_last = i == len(descs) - 1\n            next_block = fail_block if is_last else BasicBlock()\n            builder.add_bool_branch(\n                builder.primitive_op(cast(PrimitiveDescription, desc), [obj], expr.line),\n                pass_block,\n                next_block,\n            )\n            if not is_last:\n                builder.activate_block(next_block)\n\n        # If any check passed\n        builder.activate_block(pass_block)\n        builder.assign(retval, builder.true(), expr.line)\n        builder.goto(exit_block)\n\n        # If all checks failed\n        builder.activate_block(fail_block)\n        builder.assign(retval, builder.false(), expr.line)\n        builder.goto(exit_block)\n\n        # Return the result\n        builder.activate_block(exit_block)\n        return retval\n\n    return None\n\n\n@specialize_function(\"setdefault\", dict_rprimitive)\ndef translate_dict_setdefault(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    \"\"\"Special case for 'dict.setdefault' which would only construct\n    default empty collection when needed.\n\n    The dict_setdefault_spec_init_op checks whether the dict contains\n    the key and would construct the empty collection only once.\n\n    For example, this specializer works for the following cases:\n         d.setdefault(key, set()).add(value)\n         d.setdefault(key, []).append(value)\n         d.setdefault(key, {})[inner_key] = inner_val\n    \"\"\"\n    if (\n        len(expr.args) == 2\n        and expr.arg_kinds == [ARG_POS, ARG_POS]\n        and isinstance(callee, MemberExpr)\n    ):\n        arg = expr.args[1]\n        if isinstance(arg, ListExpr):\n            if len(arg.items):\n                return None\n            data_type = Integer(1, c_int_rprimitive, expr.line)\n        elif isinstance(arg, DictExpr):\n            if len(arg.items):\n                return None\n            data_type = Integer(2, c_int_rprimitive, expr.line)\n        elif (\n            isinstance(arg, CallExpr)\n            and isinstance(arg.callee, NameExpr)\n            and arg.callee.fullname == \"builtins.set\"\n        ):\n            if len(arg.args):\n                return None\n            data_type = Integer(3, c_int_rprimitive, expr.line)\n        else:\n            return None\n\n        callee_dict = builder.accept(callee.expr)\n        key_val = builder.accept(expr.args[0])\n        return builder.call_c(\n            dict_setdefault_spec_init_op, [callee_dict, key_val, data_type], expr.line\n        )\n    return None\n\n\n@specialize_function(\"format\", str_rprimitive)\ndef translate_str_format(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if isinstance(callee, MemberExpr):\n        folded_callee = constant_fold_expr(builder, callee.expr)\n        if isinstance(folded_callee, str) and expr.arg_kinds.count(ARG_POS) == len(expr.arg_kinds):\n            tokens = tokenizer_format_call(folded_callee)\n            if tokens is None:\n                return None\n            literals, format_ops = tokens\n            # Convert variables to strings\n            substitutions = convert_format_expr_to_str(builder, format_ops, expr.args, expr.line)\n            if substitutions is None:\n                return None\n            return join_formatted_strings(builder, literals, substitutions, expr.line)\n    return None\n\n\n@specialize_function(\"join\", str_rprimitive)\ndef translate_fstring(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    \"\"\"Special case for f-string, which is translated into str.join()\n    in mypy AST.\n\n    This specializer optimizes simplest f-strings which don't contain\n    any format operation.\n    \"\"\"\n    if (\n        isinstance(callee, MemberExpr)\n        and isinstance(callee.expr, StrExpr)\n        and callee.expr.value == \"\"\n        and expr.arg_kinds == [ARG_POS]\n        and isinstance(expr.args[0], ListExpr)\n    ):\n        for item in expr.args[0].items:\n            if isinstance(item, StrExpr):\n                continue\n            elif isinstance(item, CallExpr):\n                if not isinstance(item.callee, MemberExpr) or item.callee.name != \"format\":\n                    return None\n                elif (\n                    not isinstance(item.callee.expr, StrExpr) or item.callee.expr.value != \"{:{}}\"\n                ):\n                    return None\n\n                if not isinstance(item.args[1], StrExpr) or item.args[1].value != \"\":\n                    return None\n            else:\n                return None\n\n        format_ops = []\n        exprs: list[Expression] = []\n\n        for item in expr.args[0].items:\n            if isinstance(item, StrExpr) and item.value != \"\":\n                format_ops.append(FormatOp.STR)\n                exprs.append(item)\n            elif isinstance(item, CallExpr):\n                format_ops.append(FormatOp.STR)\n                exprs.append(item.args[0])\n\n        def get_literal_str(expr: Expression) -> str | None:\n            if isinstance(expr, StrExpr):\n                return expr.value\n            elif isinstance(expr, RefExpr) and isinstance(expr.node, Var) and expr.node.is_final:\n                final_value = expr.node.final_value\n                if final_value is not None:\n                    return str(final_value)\n            return None\n\n        for i in range(len(exprs) - 1):\n            while (\n                len(exprs) >= i + 2\n                and (first := get_literal_str(exprs[i])) is not None\n                and (second := get_literal_str(exprs[i + 1])) is not None\n            ):\n                exprs = [*exprs[:i], StrExpr(first + second), *exprs[i + 2 :]]\n                format_ops = [*format_ops[:i], FormatOp.STR, *format_ops[i + 2 :]]\n\n        substitutions = convert_format_expr_to_str(builder, format_ops, exprs, expr.line)\n        if substitutions is None:\n            return None\n\n        return join_formatted_strings(builder, None, substitutions, expr.line)\n    return None\n\n\n@specialize_function(\"encode\", str_rprimitive)\ndef str_encode_fast_path(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    \"\"\"Specialize common cases of str.encode for most used encodings and strict errors.\"\"\"\n\n    if not isinstance(callee, MemberExpr):\n        return None\n\n    # We can only specialize if we have string literals as args\n    if len(expr.arg_kinds) > 0 and not isinstance(expr.args[0], StrExpr):\n        return None\n    if len(expr.arg_kinds) > 1 and not isinstance(expr.args[1], StrExpr):\n        return None\n\n    encoding = \"utf8\"\n    errors = \"strict\"\n    if len(expr.arg_kinds) > 0 and isinstance(expr.args[0], StrExpr):\n        if expr.arg_kinds[0] == ARG_NAMED:\n            if expr.arg_names[0] == \"encoding\":\n                encoding = expr.args[0].value\n            elif expr.arg_names[0] == \"errors\":\n                errors = expr.args[0].value\n        elif expr.arg_kinds[0] == ARG_POS:\n            encoding = expr.args[0].value\n        else:\n            return None\n    if len(expr.arg_kinds) > 1 and isinstance(expr.args[1], StrExpr):\n        if expr.arg_kinds[1] == ARG_NAMED:\n            if expr.arg_names[1] == \"encoding\":\n                encoding = expr.args[1].value\n            elif expr.arg_names[1] == \"errors\":\n                errors = expr.args[1].value\n        elif expr.arg_kinds[1] == ARG_POS:\n            errors = expr.args[1].value\n        else:\n            return None\n\n    if errors != \"strict\":\n        # We can only specialize strict errors\n        return None\n\n    encoding = encoding.lower().replace(\"-\", \"\").replace(\"_\", \"\")  # normalize\n    # Specialized encodings and their accepted aliases\n    if encoding in [\"u8\", \"utf\", \"utf8\", \"cp65001\"]:\n        return builder.call_c(str_encode_utf8_strict, [builder.accept(callee.expr)], expr.line)\n    elif encoding in [\"646\", \"ascii\", \"usascii\"]:\n        return builder.call_c(str_encode_ascii_strict, [builder.accept(callee.expr)], expr.line)\n    elif encoding in [\"iso88591\", \"8859\", \"cp819\", \"latin\", \"latin1\", \"l1\"]:\n        return builder.call_c(str_encode_latin1_strict, [builder.accept(callee.expr)], expr.line)\n\n    return None\n\n\n@specialize_function(\"decode\", bytes_rprimitive)\ndef bytes_decode_fast_path(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    \"\"\"Specialize common cases of obj.decode for most used encodings and strict errors.\"\"\"\n\n    if not isinstance(callee, MemberExpr):\n        return None\n\n    # We can only specialize if we have string literals as args\n    if len(expr.arg_kinds) > 0 and not isinstance(expr.args[0], StrExpr):\n        return None\n    if len(expr.arg_kinds) > 1 and not isinstance(expr.args[1], StrExpr):\n        return None\n\n    encoding = \"utf8\"\n    errors = \"strict\"\n    if len(expr.arg_kinds) > 0 and isinstance(expr.args[0], StrExpr):\n        if expr.arg_kinds[0] == ARG_NAMED:\n            if expr.arg_names[0] == \"encoding\":\n                encoding = expr.args[0].value\n            elif expr.arg_names[0] == \"errors\":\n                errors = expr.args[0].value\n        elif expr.arg_kinds[0] == ARG_POS:\n            encoding = expr.args[0].value\n        else:\n            return None\n    if len(expr.arg_kinds) > 1 and isinstance(expr.args[1], StrExpr):\n        if expr.arg_kinds[1] == ARG_NAMED:\n            if expr.arg_names[1] == \"encoding\":\n                encoding = expr.args[1].value\n            elif expr.arg_names[1] == \"errors\":\n                errors = expr.args[1].value\n        elif expr.arg_kinds[1] == ARG_POS:\n            errors = expr.args[1].value\n        else:\n            return None\n\n    if errors != \"strict\":\n        # We can only specialize strict errors\n        return None\n\n    encoding = encoding.lower().replace(\"_\", \"-\")  # normalize\n    # Specialized encodings and their accepted aliases\n    if encoding in [\"u8\", \"utf\", \"utf8\", \"utf-8\", \"cp65001\"]:\n        return builder.call_c(bytes_decode_utf8_strict, [builder.accept(callee.expr)], expr.line)\n    elif encoding in [\"646\", \"ascii\", \"usascii\", \"us-ascii\"]:\n        return builder.call_c(bytes_decode_ascii_strict, [builder.accept(callee.expr)], expr.line)\n    elif encoding in [\n        \"iso8859-1\",\n        \"iso-8859-1\",\n        \"8859\",\n        \"cp819\",\n        \"latin\",\n        \"latin1\",\n        \"latin-1\",\n        \"l1\",\n    ]:\n        return builder.call_c(bytes_decode_latin1_strict, [builder.accept(callee.expr)], expr.line)\n\n    return None\n\n\n@specialize_function(\"mypy_extensions.i64\")\ndef translate_i64(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:\n        return None\n    arg = expr.args[0]\n    arg_type = builder.node_type(arg)\n    if is_int64_rprimitive(arg_type):\n        return builder.accept(arg)\n    elif is_int32_rprimitive(arg_type) or is_int16_rprimitive(arg_type):\n        val = builder.accept(arg)\n        return builder.add(Extend(val, int64_rprimitive, signed=True, line=expr.line))\n    elif is_uint8_rprimitive(arg_type):\n        val = builder.accept(arg)\n        return builder.add(Extend(val, int64_rprimitive, signed=False, line=expr.line))\n    elif is_int_rprimitive(arg_type) or is_bool_rprimitive(arg_type):\n        val = builder.accept(arg)\n        return builder.coerce(val, int64_rprimitive, expr.line)\n    return None\n\n\n@specialize_function(\"mypy_extensions.i32\")\ndef translate_i32(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:\n        return None\n    arg = expr.args[0]\n    arg_type = builder.node_type(arg)\n    if is_int32_rprimitive(arg_type):\n        return builder.accept(arg)\n    elif is_int64_rprimitive(arg_type):\n        val = builder.accept(arg)\n        return builder.add(Truncate(val, int32_rprimitive, line=expr.line))\n    elif is_int16_rprimitive(arg_type):\n        val = builder.accept(arg)\n        return builder.add(Extend(val, int32_rprimitive, signed=True, line=expr.line))\n    elif is_uint8_rprimitive(arg_type):\n        val = builder.accept(arg)\n        return builder.add(Extend(val, int32_rprimitive, signed=False, line=expr.line))\n    elif is_int_rprimitive(arg_type) or is_bool_rprimitive(arg_type):\n        val = builder.accept(arg)\n        val = truncate_literal(val, int32_rprimitive)\n        return builder.coerce(val, int32_rprimitive, expr.line)\n    return None\n\n\n@specialize_function(\"mypy_extensions.i16\")\ndef translate_i16(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:\n        return None\n    arg = expr.args[0]\n    arg_type = builder.node_type(arg)\n    if is_int16_rprimitive(arg_type):\n        return builder.accept(arg)\n    elif is_int32_rprimitive(arg_type) or is_int64_rprimitive(arg_type):\n        val = builder.accept(arg)\n        return builder.add(Truncate(val, int16_rprimitive, line=expr.line))\n    elif is_uint8_rprimitive(arg_type):\n        val = builder.accept(arg)\n        return builder.add(Extend(val, int16_rprimitive, signed=False, line=expr.line))\n    elif is_int_rprimitive(arg_type) or is_bool_rprimitive(arg_type):\n        val = builder.accept(arg)\n        val = truncate_literal(val, int16_rprimitive)\n        return builder.coerce(val, int16_rprimitive, expr.line)\n    return None\n\n\n@specialize_function(\"mypy_extensions.u8\")\ndef translate_u8(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:\n        return None\n    arg = expr.args[0]\n    arg_type = builder.node_type(arg)\n    if is_uint8_rprimitive(arg_type):\n        return builder.accept(arg)\n    elif (\n        is_int16_rprimitive(arg_type)\n        or is_int32_rprimitive(arg_type)\n        or is_int64_rprimitive(arg_type)\n    ):\n        val = builder.accept(arg)\n        return builder.add(Truncate(val, uint8_rprimitive, line=expr.line))\n    elif is_int_rprimitive(arg_type) or is_bool_rprimitive(arg_type):\n        val = builder.accept(arg)\n        val = truncate_literal(val, uint8_rprimitive)\n        return builder.coerce(val, uint8_rprimitive, expr.line)\n    return None\n\n\ndef truncate_literal(value: Value, rtype: RPrimitive) -> Value:\n    \"\"\"If value is an integer literal value, truncate it to given native int rtype.\n\n    For example, truncate 256 into 0 if rtype is u8.\n    \"\"\"\n    if not isinstance(value, Integer):\n        return value  # Not a literal, nothing to do\n    x = value.numeric_value()\n    max_unsigned = (1 << (rtype.size * 8)) - 1\n    x = x & max_unsigned\n    if rtype.is_signed and x >= (max_unsigned + 1) // 2:\n        # Adjust to make it a negative value\n        x -= max_unsigned + 1\n    return Integer(x, rtype)\n\n\n@specialize_function(\"builtins.int\")\ndef translate_int(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:\n        return None\n    arg = expr.args[0]\n    arg_type = builder.node_type(arg)\n    if (\n        is_bool_rprimitive(arg_type)\n        or is_int_rprimitive(arg_type)\n        or is_fixed_width_rtype(arg_type)\n    ):\n        src = builder.accept(arg)\n        return builder.coerce(src, int_rprimitive, expr.line)\n    return None\n\n\n@specialize_function(\"builtins.bool\")\ndef translate_bool(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:\n        return None\n    arg = expr.args[0]\n    src = builder.accept(arg)\n    return builder.builder.bool_value(src)\n\n\n@specialize_function(\"builtins.float\")\ndef translate_float(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:\n        return None\n    arg = expr.args[0]\n    arg_type = builder.node_type(arg)\n    if is_float_rprimitive(arg_type):\n        # No-op float conversion.\n        return builder.accept(arg)\n    return None\n\n\n@specialize_function(\"builtins.ord\")\ndef translate_ord(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) != 1 or expr.arg_kinds[0] != ARG_POS:\n        return None\n    arg_expr = expr.args[0]\n    arg = constant_fold_expr(builder, arg_expr)\n    if isinstance(arg, (str, bytes)) and len(arg) == 1:\n        return Integer(ord(arg))\n\n    # Check for ord(s[i]) where s is str and i is an integer\n    if isinstance(arg_expr, IndexExpr):\n        # Check base type\n        base_type = builder.node_type(arg_expr.base)\n        if is_str_rprimitive(base_type):\n            # Check index type\n            index_expr = arg_expr.index\n            index_type = builder.node_type(index_expr)\n            if is_tagged(index_type) or is_fixed_width_rtype(index_type):\n                # This is ord(s[i]) where s is str and i is an integer.\n                # Generate specialized inline code using the helper.\n                result = translate_getitem_with_bounds_check(\n                    builder,\n                    arg_expr.base,\n                    [arg_expr.index],\n                    expr,\n                    str_adjust_index_op,\n                    str_range_check_op,\n                    str_get_item_unsafe_as_int_op,\n                )\n                return result\n\n    return None\n\n\ndef is_object(callee: RefExpr) -> bool:\n    \"\"\"Returns True for object.<name> calls.\"\"\"\n    return (\n        isinstance(callee, MemberExpr)\n        and isinstance(callee.expr, NameExpr)\n        and callee.expr.fullname == \"builtins.object\"\n    )\n\n\ndef is_super_or_object(expr: CallExpr, callee: RefExpr) -> bool:\n    \"\"\"Returns True for super().<name> or object.<name> calls.\"\"\"\n    return isinstance(expr.callee, SuperExpr) or is_object(callee)\n\n\n@specialize_function(\"__new__\", object_rprimitive)\ndef translate_object_new(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    fn = builder.fn_info\n    if fn.name != \"__new__\" or not is_super_or_object(expr, callee):\n        return None\n\n    ir = builder.get_current_class_ir()\n    if ir is None:\n        return None\n\n    call = '\"object.__new__()\"'\n    if not ir.is_ext_class:\n        builder.error(f\"{call} not supported for non-extension classes\", expr.line)\n        return None\n    if ir.inherits_python:\n        builder.error(\n            f\"{call} not supported for classes inheriting from non-native classes\", expr.line\n        )\n        return None\n    if len(expr.args) != 1:\n        builder.error(f\"{call} supported only with 1 argument, got {len(expr.args)}\", expr.line)\n        return None\n\n    typ_arg = expr.args[0]\n    method_args = fn.fitem.arg_names\n    if isinstance(typ_arg, NameExpr) and len(method_args) > 0 and method_args[0] == typ_arg.name:\n        subtype = builder.accept(expr.args[0])\n        subs = ir.subclasses()\n        if subs is not None and len(subs) == 0:\n            return builder.add(Call(ir.setup, [subtype], expr.line))\n        # Call a function that dynamically resolves the setup function of extension classes from the type object.\n        # This is necessary because the setup involves default attribute initialization and setting up\n        # the vtable which are specific to a given type and will not work if a subtype is created using\n        # the setup function of its base.\n        return builder.call_c(setup_object, [subtype], expr.line)\n\n    return None\n\n\n@specialize_function(\"__setattr__\", object_rprimitive)\ndef translate_object_setattr(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    is_super = isinstance(expr.callee, SuperExpr)\n    is_object_callee = is_object(callee)\n    if not ((is_super and len(expr.args) >= 2) or (is_object_callee and len(expr.args) >= 3)):\n        return None\n\n    self_reg = builder.accept(expr.args[0]) if is_object_callee else builder.self()\n    ir = builder.get_current_class_ir()\n    if ir and (not ir.is_ext_class or ir.builtin_base or ir.inherits_python):\n        return None\n    # Need to offset by 1 for super().__setattr__ calls because there is no self arg in this case.\n    name_idx = 0 if is_super else 1\n    value_idx = 1 if is_super else 2\n    attr_name = expr.args[name_idx]\n    attr_value = expr.args[value_idx]\n    value = builder.accept(attr_value)\n\n    if isinstance(attr_name, StrExpr) and ir and ir.has_attr(attr_name.value):\n        name = attr_name.value\n        value = builder.coerce(value, ir.attributes[name], expr.line)\n        return builder.add(SetAttr(self_reg, name, value, expr.line))\n\n    name_reg = builder.accept(attr_name)\n    return builder.call_c(generic_setattr, [self_reg, name_reg, value], expr.line)\n\n\n@specialize_function(\"to_bytes\", int_rprimitive)\ndef specialize_int_to_bytes(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    # int.to_bytes(length, byteorder, signed=False)\n    if any(kind not in (ARG_POS, ARG_NAMED) for kind in expr.arg_kinds):\n        return None\n    if not isinstance(callee, MemberExpr):\n        return None\n    length_expr: Expression | None = None\n    byteorder_expr: Expression | None = None\n    signed_expr: Expression | None = None\n    positional_index = 0\n    for name, arg in zip(expr.arg_names, expr.args):\n        if name is None:\n            if positional_index == 0:\n                length_expr = arg\n            elif positional_index == 1:\n                byteorder_expr = arg\n            elif positional_index == 2:\n                signed_expr = arg\n            else:\n                return None\n            positional_index += 1\n        elif name == \"length\":\n            if length_expr is not None:\n                return None\n            length_expr = arg\n        elif name == \"byteorder\":\n            if byteorder_expr is not None:\n                return None\n            byteorder_expr = arg\n        elif name == \"signed\":\n            if signed_expr is not None:\n                return None\n            signed_expr = arg\n        else:\n            return None\n    if length_expr is None or byteorder_expr is None:\n        return None\n\n    signed_is_bool = True\n    if signed_expr is not None:\n        signed_is_bool = is_bool_rprimitive(builder.node_type(signed_expr))\n    if not (\n        is_int_rprimitive(builder.node_type(length_expr))\n        and is_str_rprimitive(builder.node_type(byteorder_expr))\n        and signed_is_bool\n    ):\n        return None\n\n    self_arg = builder.accept(callee.expr)\n    length_arg = builder.accept(length_expr)\n    if signed_expr is None:\n        signed_arg = builder.false()\n    else:\n        signed_arg = builder.accept(signed_expr)\n    if isinstance(byteorder_expr, StrExpr):\n        if byteorder_expr.value == \"little\":\n            return builder.call_c(\n                int_to_little_endian_op, [self_arg, length_arg, signed_arg], expr.line\n            )\n        elif byteorder_expr.value == \"big\":\n            return builder.call_c(\n                int_to_big_endian_op, [self_arg, length_arg, signed_arg], expr.line\n            )\n    # Fallback to generic primitive op\n    byteorder_arg = builder.accept(byteorder_expr)\n    return builder.call_c(\n        int_to_bytes_op, [self_arg, length_arg, byteorder_arg, signed_arg], expr.line\n    )\n\n\ndef translate_getitem_with_bounds_check(\n    builder: IRBuilder,\n    base_expr: Expression,\n    args: list[Expression],\n    ctx_expr: Expression,\n    adjust_index_op: PrimitiveDescription,\n    range_check_op: PrimitiveDescription,\n    get_item_unsafe_op: PrimitiveDescription,\n) -> Value | None:\n    \"\"\"Shared helper for optimized __getitem__ with bounds checking.\n\n    This implements the common pattern of:\n    1. Adjusting negative indices\n    2. Checking if index is in valid range\n    3. Raising IndexError if out of range\n    4. Getting the item if in range\n\n    Args:\n        builder: The IR builder\n        base_expr: The base object expression\n        args: The arguments to __getitem__ (should be length 1)\n        ctx_expr: The context expression for line numbers\n        adjust_index_op: Primitive op to adjust negative indices\n        range_check_op: Primitive op to check if index is in valid range\n        get_item_unsafe_op: Primitive op to get item (no bounds checking)\n\n    Returns:\n        The result value, or None if optimization doesn't apply\n    \"\"\"\n    # Check that we have exactly one argument\n    if len(args) != 1:\n        return None\n\n    # Get the object\n    obj = builder.accept(base_expr)\n\n    # Get the index argument\n    index = builder.accept(args[0])\n\n    # Adjust the index (handle negative indices)\n    adjusted_index = builder.primitive_op(adjust_index_op, [obj, index], ctx_expr.line)\n\n    # Check if the adjusted index is in valid range\n    range_check = builder.primitive_op(range_check_op, [obj, adjusted_index], ctx_expr.line)\n\n    # Create blocks for branching\n    valid_block = BasicBlock()\n    invalid_block = BasicBlock()\n\n    builder.add_bool_branch(range_check, valid_block, invalid_block)\n\n    # Handle invalid index - raise IndexError\n    builder.activate_block(invalid_block)\n    builder.add(\n        RaiseStandardError(RaiseStandardError.INDEX_ERROR, \"index out of range\", ctx_expr.line)\n    )\n    builder.add(Unreachable())\n\n    # Handle valid index - get the item\n    builder.activate_block(valid_block)\n    result = builder.primitive_op(get_item_unsafe_op, [obj, adjusted_index], ctx_expr.line)\n\n    return result\n\n\n@specialize_dunder(\"__getitem__\", bytes_writer_rprimitive)\ndef translate_bytes_writer_get_item(\n    builder: IRBuilder, base_expr: Expression, args: list[Expression], ctx_expr: Expression\n) -> Value | None:\n    \"\"\"Optimized BytesWriter.__getitem__ implementation with bounds checking.\"\"\"\n    return translate_getitem_with_bounds_check(\n        builder,\n        base_expr,\n        args,\n        ctx_expr,\n        bytes_writer_adjust_index_op,\n        bytes_writer_range_check_op,\n        bytes_writer_get_item_unsafe_op,\n    )\n\n\n@specialize_dunder(\"__setitem__\", bytes_writer_rprimitive)\ndef translate_bytes_writer_set_item(\n    builder: IRBuilder, base_expr: Expression, args: list[Expression], ctx_expr: Expression\n) -> Value | None:\n    \"\"\"Optimized BytesWriter.__setitem__ implementation with bounds checking.\"\"\"\n    # Check that we have exactly two arguments (index and value)\n    if len(args) != 2:\n        return None\n\n    # Get the BytesWriter object\n    obj = builder.accept(base_expr)\n\n    # Get the index and value arguments\n    index = builder.accept(args[0])\n    value = builder.accept(args[1])\n\n    # Adjust the index (handle negative indices)\n    adjusted_index = builder.primitive_op(\n        bytes_writer_adjust_index_op, [obj, index], ctx_expr.line\n    )\n\n    # Check if the adjusted index is in valid range\n    range_check = builder.primitive_op(\n        bytes_writer_range_check_op, [obj, adjusted_index], ctx_expr.line\n    )\n\n    # Create blocks for branching\n    valid_block = BasicBlock()\n    invalid_block = BasicBlock()\n\n    builder.add_bool_branch(range_check, valid_block, invalid_block)\n\n    # Handle invalid index - raise IndexError\n    builder.activate_block(invalid_block)\n    builder.add(\n        RaiseStandardError(RaiseStandardError.INDEX_ERROR, \"index out of range\", ctx_expr.line)\n    )\n    builder.add(Unreachable())\n\n    # Handle valid index - set the item\n    builder.activate_block(valid_block)\n    builder.primitive_op(\n        bytes_writer_set_item_unsafe_op, [obj, adjusted_index, value], ctx_expr.line\n    )\n\n    return builder.none()\n\n\n@specialize_dunder(\"__getitem__\", string_writer_rprimitive)\ndef translate_string_writer_get_item(\n    builder: IRBuilder, base_expr: Expression, args: list[Expression], ctx_expr: Expression\n) -> Value | None:\n    \"\"\"Optimized StringWriter.__getitem__ implementation with bounds checking.\"\"\"\n    return translate_getitem_with_bounds_check(\n        builder,\n        base_expr,\n        args,\n        ctx_expr,\n        string_writer_adjust_index_op,\n        string_writer_range_check_op,\n        string_writer_get_item_unsafe_op,\n    )\n\n\n@specialize_dunder(\"__getitem__\", bytes_rprimitive)\ndef translate_bytes_get_item(\n    builder: IRBuilder, base_expr: Expression, args: list[Expression], ctx_expr: Expression\n) -> Value | None:\n    \"\"\"Optimized bytes.__getitem__ implementation with bounds checking.\"\"\"\n    return translate_getitem_with_bounds_check(\n        builder,\n        base_expr,\n        args,\n        ctx_expr,\n        bytes_adjust_index_op,\n        bytes_range_check_op,\n        bytes_get_item_unsafe_op,\n    )\n\n\n@specialize_function(\"librt.vecs.append\")\ndef translate_vec_append(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) == 2 and expr.arg_kinds == [ARG_POS, ARG_POS]:\n        vec_arg = expr.args[0]\n        item_arg = expr.args[1]\n        vec_type = builder.node_type(vec_arg)\n        if isinstance(vec_type, RVec):\n            vec_value = builder.accept(vec_arg)\n            arg_value = builder.accept(item_arg)\n            return vec_append(builder.builder, vec_value, arg_value, item_arg.line)\n    return None\n\n\n@specialize_function(\"librt.vecs.remove\")\ndef translate_vec_remove(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if len(expr.args) == 2 and expr.arg_kinds == [ARG_POS, ARG_POS]:\n        vec_arg = expr.args[0]\n        item_arg = expr.args[1]\n        vec_type = builder.node_type(vec_arg)\n        if isinstance(vec_type, RVec):\n            vec_value = builder.accept(vec_arg)\n            arg_value = builder.accept(item_arg)\n            return vec_remove(builder.builder, vec_value, arg_value, item_arg.line)\n    return None\n\n\n@specialize_function(\"librt.vecs.pop\")\ndef translate_vec_pop(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None:\n    if 1 <= len(expr.args) <= 2 and all(kind == ARG_POS for kind in expr.arg_kinds):\n        vec_arg = expr.args[0]\n        vec_type = builder.node_type(vec_arg)\n        if isinstance(vec_type, RVec):\n            vec_value = builder.accept(vec_arg)\n            if len(expr.args) == 2:\n                index_value = builder.accept(expr.args[1])\n            else:\n                index_value = Integer(-1, int64_rprimitive)\n            return vec_pop(builder.builder, vec_value, index_value, vec_arg.line)\n    return None\n"
  },
  {
    "path": "mypyc/irbuild/statement.py",
    "content": "\"\"\"Transform mypy statement ASTs to mypyc IR (Intermediate Representation).\n\nThe top-level AST transformation logic is implemented in mypyc.irbuild.visitor\nand mypyc.irbuild.builder.\n\nA few statements are transformed in mypyc.irbuild.function (yield, for example).\n\"\"\"\n\nfrom __future__ import annotations\n\nimport importlib.util\nfrom collections.abc import Callable, Sequence\n\nimport mypy.nodes\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_POS,\n    AssertStmt,\n    AssignmentStmt,\n    AwaitExpr,\n    Block,\n    BreakStmt,\n    ContinueStmt,\n    DelStmt,\n    Expression,\n    ExpressionStmt,\n    ForStmt,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    ListExpr,\n    Lvalue,\n    MatchStmt,\n    NameExpr,\n    OperatorAssignmentStmt,\n    RaiseStmt,\n    ReturnStmt,\n    StarExpr,\n    StrExpr,\n    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAliasStmt,\n    WhileStmt,\n    WithStmt,\n    YieldExpr,\n    YieldFromExpr,\n)\nfrom mypyc.common import TEMP_ATTR_NAME\nfrom mypyc.ir.ops import (\n    ERR_NEVER,\n    NAMESPACE_MODULE,\n    NO_TRACEBACK_LINE_NO,\n    Assign,\n    BasicBlock,\n    Branch,\n    Call,\n    InitStatic,\n    Integer,\n    LoadAddress,\n    LoadErrorValue,\n    LoadLiteral,\n    LoadStatic,\n    MethodCall,\n    PrimitiveDescription,\n    RaiseStandardError,\n    Register,\n    Return,\n    TupleGet,\n    Unborrow,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RTuple,\n    c_pyssize_t_rprimitive,\n    exc_rtuple,\n    is_tagged,\n    none_rprimitive,\n    object_pointer_rprimitive,\n    object_rprimitive,\n)\nfrom mypyc.irbuild.ast_helpers import is_borrow_friendly_expr, process_conditional\nfrom mypyc.irbuild.builder import IRBuilder, create_type_params, int_borrow_friendly_op\nfrom mypyc.irbuild.for_helpers import for_loop_helper\nfrom mypyc.irbuild.generator import add_raise_exception_blocks_to_generator_class\nfrom mypyc.irbuild.nonlocalcontrol import (\n    ExceptNonlocalControl,\n    FinallyNonlocalControl,\n    TryFinallyNonlocalControl,\n)\nfrom mypyc.irbuild.prepare import GENERATOR_HELPER_NAME\nfrom mypyc.irbuild.specialize import apply_dunder_specialization\nfrom mypyc.irbuild.targets import (\n    AssignmentTarget,\n    AssignmentTargetAttr,\n    AssignmentTargetIndex,\n    AssignmentTargetRegister,\n    AssignmentTargetTuple,\n)\nfrom mypyc.primitives.exc_ops import (\n    error_catch_op,\n    exc_matches_op,\n    get_exc_info_op,\n    get_exc_value_op,\n    keep_propagating_op,\n    no_err_occurred_op,\n    propagate_if_error_op,\n    raise_exception_op,\n    reraise_exception_op,\n    restore_exc_info_op,\n)\nfrom mypyc.primitives.generic_ops import iter_op, next_raw_op, py_delattr_op\nfrom mypyc.primitives.misc_ops import (\n    check_stop_op,\n    coro_op,\n    import_from_many_op,\n    import_many_op,\n    import_op,\n    send_op,\n    set_type_alias_compute_function_op,\n    type_op,\n    yield_from_except_op,\n)\n\nfrom .match import MatchVisitor\n\nGenFunc = Callable[[], None]\nValueGenFunc = Callable[[], Value]\n\n\ndef transform_block(builder: IRBuilder, block: Block) -> None:\n    if not block.is_unreachable:\n        builder.block_reachable_stack.append(True)\n        for stmt in block.body:\n            builder.accept(stmt)\n            if not builder.block_reachable_stack[-1]:\n                # The rest of the block is unreachable, so skip it\n                break\n        builder.block_reachable_stack.pop()\n    # Raise a RuntimeError if we hit a non-empty unreachable block.\n    # Don't complain about empty unreachable blocks, since mypy inserts\n    # those after `if MYPY`.\n    elif block.body:\n        builder.add(\n            RaiseStandardError(\n                RaiseStandardError.RUNTIME_ERROR, \"Reached allegedly unreachable code!\", block.line\n            )\n        )\n        builder.add(Unreachable())\n\n\ndef transform_expression_stmt(builder: IRBuilder, stmt: ExpressionStmt) -> None:\n    if isinstance(stmt.expr, StrExpr):\n        # Docstring. Ignore\n        return\n    # ExpressionStmts do not need to be coerced like other Expressions, so we shouldn't\n    # call builder.accept here.\n    stmt.expr.accept(builder.visitor)\n    builder.flush_keep_alives(stmt.line)\n\n\ndef transform_return_stmt(builder: IRBuilder, stmt: ReturnStmt) -> None:\n    if stmt.expr:\n        retval = builder.accept(stmt.expr)\n    else:\n        retval = builder.builder.none()\n    retval = builder.coerce(retval, builder.ret_types[-1], stmt.line)\n    builder.nonlocal_control[-1].gen_return(builder, retval, stmt.line)\n\n\ndef check_unsupported_cls_assignment(builder: IRBuilder, stmt: AssignmentStmt) -> None:\n    fn = builder.fn_info\n    method_args = fn.fitem.arg_names\n    if fn.name != \"__new__\" or len(method_args) == 0:\n        return\n\n    ir = builder.get_current_class_ir()\n    if ir is None or ir.inherits_python or not ir.is_ext_class:\n        return\n\n    cls_arg = method_args[0]\n\n    def flatten(lvalues: list[Expression]) -> list[Expression]:\n        flat = []\n        for lvalue in lvalues:\n            if isinstance(lvalue, (TupleExpr, ListExpr)):\n                flat += flatten(lvalue.items)\n            else:\n                flat.append(lvalue)\n        return flat\n\n    lvalues = flatten(stmt.lvalues)\n\n    for lvalue in lvalues:\n        if isinstance(lvalue, NameExpr) and lvalue.name == cls_arg:\n            # Disallowed because it could break the transformation of object.__new__ calls\n            # inside __new__ methods.\n            builder.error(\n                f'Assignment to argument \"{cls_arg}\" in \"__new__\" method unsupported', stmt.line\n            )\n\n\ndef transform_assignment_stmt(builder: IRBuilder, stmt: AssignmentStmt) -> None:\n    lvalues = stmt.lvalues\n    assert lvalues\n    builder.disallow_class_assignments(lvalues, stmt.line)\n    check_unsupported_cls_assignment(builder, stmt)\n    first_lvalue = lvalues[0]\n    if stmt.type and isinstance(stmt.rvalue, TempNode):\n        # This is actually a variable annotation without initializer. Don't generate\n        # an assignment but we need to call get_assignment_target since it adds a\n        # name binding as a side effect.\n        builder.get_assignment_target(first_lvalue, stmt.line)\n        return\n\n    # Special case multiple assignments like 'x, y = e1, e2'.\n    if (\n        isinstance(first_lvalue, (TupleExpr, ListExpr))\n        and isinstance(stmt.rvalue, (TupleExpr, ListExpr))\n        and len(first_lvalue.items) == len(stmt.rvalue.items)\n        and all(is_simple_lvalue(item) for item in first_lvalue.items)\n        and len(lvalues) == 1\n    ):\n        temps = []\n        for right in stmt.rvalue.items:\n            rvalue_reg = builder.accept(right)\n            temp = Register(rvalue_reg.type)\n            builder.assign(temp, rvalue_reg, stmt.line)\n            temps.append(temp)\n        for left, temp in zip(first_lvalue.items, temps):\n            assignment_target = builder.get_assignment_target(left)\n            builder.assign(assignment_target, temp, stmt.line)\n        builder.flush_keep_alives(stmt.line)\n        return\n\n    line = stmt.rvalue.line\n    rvalue_reg = builder.accept(stmt.rvalue)\n\n    if builder.non_function_scope() and stmt.is_final_def:\n        builder.init_final_static(first_lvalue, rvalue_reg)\n\n    # Special-case multiple assignments like 'x, y = expr' to reduce refcount ops.\n    if (\n        isinstance(first_lvalue, (TupleExpr, ListExpr))\n        and isinstance(rvalue_reg.type, RTuple)\n        and len(rvalue_reg.type.types) == len(first_lvalue.items)\n        and len(lvalues) == 1\n        and all(is_simple_lvalue(item) for item in first_lvalue.items)\n        and any(t.is_refcounted for t in rvalue_reg.type.types)\n    ):\n        n = len(first_lvalue.items)\n        borrows = [builder.add(TupleGet(rvalue_reg, i, borrow=True)) for i in range(n)]\n        builder.builder.keep_alive([rvalue_reg], line, steal=True)\n        for lvalue_item, rvalue_item in zip(first_lvalue.items, borrows):\n            rvalue_item = builder.add(Unborrow(rvalue_item))\n            builder.assign(builder.get_assignment_target(lvalue_item), rvalue_item, line)\n        builder.flush_keep_alives(line)\n        return\n\n    for lvalue in lvalues:\n        # Check for __setitem__ dunder specialization before converting to assignment target\n        if isinstance(lvalue, IndexExpr):\n            specialized = apply_dunder_specialization(\n                builder, lvalue.base, [lvalue.index, stmt.rvalue], \"__setitem__\", lvalue\n            )\n            if specialized is not None:\n                builder.flush_keep_alives(lvalue.line)\n                continue\n\n        target = builder.get_assignment_target(lvalue)\n        builder.assign(target, rvalue_reg, line)\n        builder.flush_keep_alives(line)\n\n\ndef is_simple_lvalue(expr: Expression) -> bool:\n    return not isinstance(expr, (StarExpr, ListExpr, TupleExpr))\n\n\ndef transform_operator_assignment_stmt(builder: IRBuilder, stmt: OperatorAssignmentStmt) -> None:\n    \"\"\"Operator assignment statement such as x += 1\"\"\"\n    builder.disallow_class_assignments([stmt.lvalue], stmt.line)\n    if (\n        is_tagged(builder.node_type(stmt.lvalue))\n        and is_tagged(builder.node_type(stmt.rvalue))\n        and stmt.op in int_borrow_friendly_op\n    ):\n        can_borrow = is_borrow_friendly_expr(builder, stmt.rvalue) and is_borrow_friendly_expr(\n            builder, stmt.lvalue\n        )\n    else:\n        can_borrow = False\n    target = builder.get_assignment_target(stmt.lvalue)\n    target_value = builder.read(target, stmt.line, can_borrow=can_borrow)\n    rreg = builder.accept(stmt.rvalue, can_borrow=can_borrow)\n    # the Python parser strips the '=' from operator assignment statements, so re-add it\n    op = stmt.op + \"=\"\n    res = builder.binary_op(target_value, rreg, op, stmt.line)\n    # usually operator assignments are done in-place\n    # but when target doesn't support that we need to manually assign\n    builder.assign(target, res, res.line)\n    builder.flush_keep_alives(res.line)\n\n\ndef import_globals_id_and_name(module_id: str, as_name: str | None) -> tuple[str, str]:\n    \"\"\"Compute names for updating the globals dict with the appropriate module.\n\n    * For 'import foo.bar as baz' we add 'foo.bar' with the name 'baz'\n    * For 'import foo.bar' we add 'foo' with the name 'foo'\n\n    Typically we then ignore these entries and access things directly\n    via the module static, but we will use the globals version for\n    modules that mypy couldn't find, since it doesn't analyze module\n    references from those properly.\"\"\"\n    if as_name:\n        globals_id = module_id\n        globals_name = as_name\n    else:\n        globals_id = globals_name = module_id.split(\".\")[0]\n\n    return globals_id, globals_name\n\n\ndef transform_import(builder: IRBuilder, node: Import) -> None:\n    if node.is_mypy_only:\n        return\n\n    # Imports (not from imports!) are processed in an odd way so they can be\n    # table-driven and compact. Here's how it works:\n    #\n    # Import nodes are divided in groups (in the prebuild visitor). Each group\n    # consists of consecutive Import nodes:\n    #\n    #   import mod         <| group #1\n    #   import mod2         |\n    #\n    #   def foo() -> None:\n    #       import mod3    <- group #2 (*)\n    #\n    #   import mod4        <| group #3\n    #   import mod5         |\n    #\n    # Every time we encounter the first import of a group, build IR to call a\n    # helper function that will perform all of the group's imports in one go.\n    if not node.is_top_level:\n        # (*) Unless the import is within a function. In that case, prioritize\n        # speed over codesize when generating IR.\n        globals = builder.load_globals_dict()\n        for mod_id, as_name in node.ids:\n            builder.gen_import(mod_id, node.line)\n            globals_id, globals_name = import_globals_id_and_name(mod_id, as_name)\n            builder.gen_method_call(\n                globals,\n                \"__setitem__\",\n                [builder.load_str(globals_name), builder.get_module(globals_id, node.line)],\n                result_type=None,\n                line=node.line,\n            )\n        return\n\n    if node not in builder.module_import_groups:\n        return\n\n    modules = []\n    static_ptrs = []\n    # To show the right line number on failure, we have to add the traceback\n    # entry within the helper function (which is admittedly ugly). To drive\n    # this, we need the line number corresponding to each module.\n    mod_lines = []\n    for import_node in builder.module_import_groups[node]:\n        for mod_id, as_name in import_node.ids:\n            builder.imports[mod_id] = None\n            modules.append((mod_id, *import_globals_id_and_name(mod_id, as_name)))\n            mod_static = LoadStatic(object_rprimitive, mod_id, namespace=NAMESPACE_MODULE)\n            static_ptrs.append(builder.add(LoadAddress(object_pointer_rprimitive, mod_static)))\n            mod_lines.append(Integer(import_node.line, c_pyssize_t_rprimitive))\n\n    static_array_ptr = builder.builder.setup_rarray(\n        object_pointer_rprimitive, static_ptrs, node.line\n    )\n    import_line_ptr = builder.builder.setup_rarray(c_pyssize_t_rprimitive, mod_lines, node.line)\n    builder.call_c(\n        import_many_op,\n        [\n            builder.add(LoadLiteral(tuple(modules), object_rprimitive)),\n            static_array_ptr,\n            builder.load_globals_dict(),\n            builder.load_str(builder.module_path),\n            builder.load_str(builder.fn_info.name),\n            import_line_ptr,\n        ],\n        NO_TRACEBACK_LINE_NO,\n    )\n\n\ndef transform_import_from(builder: IRBuilder, node: ImportFrom) -> None:\n    if node.is_mypy_only:\n        return\n\n    module_state = builder.graph[builder.module_name]\n    if builder.module_path.endswith(\"__init__.py\"):\n        module_package = builder.module_name\n    elif module_state.ancestors is not None and module_state.ancestors:\n        module_package = module_state.ancestors[0]\n    else:\n        module_package = \"\"\n\n    id = importlib.util.resolve_name(\".\" * node.relative + node.id, module_package)\n    builder.imports[id] = None\n\n    names = [name for name, _ in node.names]\n    as_names = [as_name or name for name, as_name in node.names]\n    names_literal = builder.add(LoadLiteral(tuple(names), object_rprimitive))\n    if as_names == names:\n        # Reuse names tuple to reduce verbosity.\n        as_names_literal = names_literal\n    else:\n        as_names_literal = builder.add(LoadLiteral(tuple(as_names), object_rprimitive))\n    # Note that we miscompile import from inside of functions here,\n    # since that case *shouldn't* load everything into the globals dict.\n    # This probably doesn't matter much and the code runs basically right.\n    module = builder.call_c(\n        import_from_many_op,\n        [builder.load_str(id), names_literal, as_names_literal, builder.load_globals_dict()],\n        node.line,\n    )\n    builder.add(InitStatic(module, id, namespace=NAMESPACE_MODULE))\n\n\ndef transform_import_all(builder: IRBuilder, node: ImportAll) -> None:\n    if node.is_mypy_only:\n        return\n    builder.gen_import(node.id, node.line)\n\n\ndef transform_if_stmt(builder: IRBuilder, stmt: IfStmt) -> None:\n    if_body, next = BasicBlock(), BasicBlock()\n    else_body = BasicBlock() if stmt.else_body else next\n\n    # If statements are normalized\n    assert len(stmt.expr) == 1\n\n    process_conditional(builder, stmt.expr[0], if_body, else_body)\n    builder.activate_block(if_body)\n    builder.accept(stmt.body[0])\n    builder.goto(next)\n    if stmt.else_body:\n        builder.activate_block(else_body)\n        builder.accept(stmt.else_body)\n        builder.goto(next)\n    builder.activate_block(next)\n\n\ndef transform_while_stmt(builder: IRBuilder, s: WhileStmt) -> None:\n    body, next, top, else_block = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()\n    normal_loop_exit = else_block if s.else_body is not None else next\n\n    builder.push_loop_stack(top, next)\n\n    # Split block so that we get a handle to the top of the loop.\n    builder.goto_and_activate(top)\n    process_conditional(builder, s.expr, body, normal_loop_exit)\n\n    builder.activate_block(body)\n    builder.accept(s.body)\n    # Add branch to the top at the end of the body.\n    builder.goto(top)\n\n    builder.pop_loop_stack()\n\n    if s.else_body is not None:\n        builder.activate_block(else_block)\n        builder.accept(s.else_body)\n        builder.goto(next)\n\n    builder.activate_block(next)\n\n\ndef transform_for_stmt(builder: IRBuilder, s: ForStmt) -> None:\n    def body() -> None:\n        builder.accept(s.body)\n\n    def else_block() -> None:\n        assert s.else_body is not None\n        builder.accept(s.else_body)\n\n    for_loop_helper(\n        builder, s.index, s.expr, body, else_block if s.else_body else None, s.is_async, s.line\n    )\n\n\ndef transform_break_stmt(builder: IRBuilder, node: BreakStmt) -> None:\n    builder.nonlocal_control[-1].gen_break(builder, node.line)\n\n\ndef transform_continue_stmt(builder: IRBuilder, node: ContinueStmt) -> None:\n    builder.nonlocal_control[-1].gen_continue(builder, node.line)\n\n\ndef transform_raise_stmt(builder: IRBuilder, s: RaiseStmt) -> None:\n    if s.expr is None:\n        builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)\n        builder.add(Unreachable())\n        return\n\n    exc = builder.accept(s.expr)\n    builder.call_c(raise_exception_op, [exc], s.line)\n    builder.add(Unreachable())\n\n\ndef transform_try_except(\n    builder: IRBuilder,\n    body: GenFunc,\n    handlers: Sequence[tuple[tuple[ValueGenFunc, int] | None, Expression | None, GenFunc]],\n    else_body: GenFunc | None,\n    line: int,\n) -> None:\n    \"\"\"Generalized try/except/else handling that takes functions to gen the bodies.\n\n    The point of this is to also be able to support with.\"\"\"\n    assert handlers, \"try needs except\"\n\n    except_entry, exit_block, cleanup_block = BasicBlock(), BasicBlock(), BasicBlock()\n    double_except_block = BasicBlock()\n    # If there is an else block, jump there after the try, otherwise just leave\n    else_block = BasicBlock() if else_body else exit_block\n\n    # Compile the try block with an error handler\n    builder.builder.push_error_handler(except_entry)\n    builder.goto_and_activate(BasicBlock())\n    body()\n    builder.goto(else_block)\n    builder.builder.pop_error_handler()\n\n    # The error handler catches the error and then checks it\n    # against the except clauses. We compile the error handler\n    # itself with an error handler so that it can properly restore\n    # the *old* exc_info if an exception occurs.\n    # The exception chaining will be done automatically when the\n    # exception is raised, based on the exception in exc_info.\n    builder.builder.push_error_handler(double_except_block)\n    builder.activate_block(except_entry)\n    old_exc = builder.maybe_spill(builder.call_c(error_catch_op, [], line))\n    # Compile the except blocks with the nonlocal control flow overridden to clear exc_info\n    builder.nonlocal_control.append(ExceptNonlocalControl(builder.nonlocal_control[-1], old_exc))\n\n    # Process the bodies\n    for type, var, handler_body in handlers:\n        next_block = None\n        if type:\n            type_f, type_line = type\n            next_block, body_block = BasicBlock(), BasicBlock()\n            matches = builder.call_c(exc_matches_op, [type_f()], type_line)\n            builder.add(Branch(matches, body_block, next_block, Branch.BOOL, type_line))\n            builder.activate_block(body_block)\n        if var:\n            target = builder.get_assignment_target(var)\n            builder.assign(target, builder.call_c(get_exc_value_op, [], var.line), var.line)\n        handler_body()\n        builder.goto(cleanup_block)\n        if next_block:\n            builder.activate_block(next_block)\n\n    # Reraise the exception if needed\n    if next_block:\n        builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)\n        builder.add(Unreachable())\n\n    builder.nonlocal_control.pop()\n    builder.builder.pop_error_handler()\n\n    # Cleanup for if we leave except through normal control flow:\n    # restore the saved exc_info information and continue propagating\n    # the exception if it exists.\n    builder.activate_block(cleanup_block)\n    builder.call_c(restore_exc_info_op, [builder.read(old_exc, line)], line)\n    builder.goto(exit_block)\n\n    # Cleanup for if we leave except through a raised exception:\n    # restore the saved exc_info information and continue propagating\n    # the exception.\n    builder.activate_block(double_except_block)\n    builder.call_c(restore_exc_info_op, [builder.read(old_exc, line)], line)\n    builder.call_c(keep_propagating_op, [], NO_TRACEBACK_LINE_NO)\n    builder.add(Unreachable())\n\n    # If present, compile the else body in the obvious way\n    if else_body:\n        builder.activate_block(else_block)\n        else_body()\n        builder.goto(exit_block)\n\n    builder.activate_block(exit_block)\n\n\ndef transform_try_except_stmt(builder: IRBuilder, t: TryStmt) -> None:\n    def body() -> None:\n        builder.accept(t.body)\n\n    # Work around scoping woes\n    def make_handler(body: Block) -> GenFunc:\n        return lambda: builder.accept(body)\n\n    def make_entry(type: Expression) -> tuple[ValueGenFunc, int]:\n        return (lambda: builder.accept(type), type.line)\n\n    handlers = [\n        (make_entry(type) if type else None, var, make_handler(body))\n        for type, var, body in zip(t.types, t.vars, t.handlers)\n    ]\n\n    _else_body = t.else_body\n    else_body = (lambda: builder.accept(_else_body)) if _else_body else None\n    transform_try_except(builder, body, handlers, else_body, t.line)\n\n\ndef try_finally_try(\n    builder: IRBuilder,\n    err_handler: BasicBlock,\n    return_entry: BasicBlock,\n    main_entry: BasicBlock,\n    try_body: GenFunc,\n) -> Register | AssignmentTarget | None:\n    # Compile the try block with an error handler\n    control = TryFinallyNonlocalControl(return_entry)\n    builder.builder.push_error_handler(err_handler)\n\n    builder.nonlocal_control.append(control)\n    builder.goto_and_activate(BasicBlock())\n    try_body()\n    builder.goto(main_entry)\n    builder.nonlocal_control.pop()\n    builder.builder.pop_error_handler()\n\n    return control.ret_reg\n\n\ndef try_finally_entry_blocks(\n    builder: IRBuilder,\n    err_handler: BasicBlock,\n    return_entry: BasicBlock,\n    main_entry: BasicBlock,\n    finally_block: BasicBlock,\n    ret_reg: Register | AssignmentTarget | None,\n) -> Value:\n    line = builder.fn_info.fitem.line\n    old_exc = Register(exc_rtuple, line=line)\n\n    # Entry block for non-exceptional flow\n    builder.activate_block(main_entry)\n    if ret_reg:\n        builder.assign(ret_reg, builder.add(LoadErrorValue(builder.ret_types[-1], line)), line)\n    builder.goto(return_entry)\n\n    builder.activate_block(return_entry)\n    builder.add(Assign(old_exc, builder.add(LoadErrorValue(exc_rtuple, line)), line))\n    builder.goto(finally_block)\n\n    # Entry block for errors\n    builder.activate_block(err_handler)\n    if ret_reg:\n        builder.assign(ret_reg, builder.add(LoadErrorValue(builder.ret_types[-1], line)), line)\n    builder.add(Assign(old_exc, builder.call_c(error_catch_op, [], line), line))\n    builder.goto(finally_block)\n\n    return old_exc\n\n\ndef try_finally_body(\n    builder: IRBuilder, finally_block: BasicBlock, finally_body: GenFunc, old_exc: Value\n) -> tuple[BasicBlock, FinallyNonlocalControl]:\n    cleanup_block = BasicBlock()\n    # Compile the finally block with the nonlocal control flow overridden to restore exc_info\n    builder.builder.push_error_handler(cleanup_block)\n    finally_control = FinallyNonlocalControl(builder.nonlocal_control[-1], old_exc)\n    builder.nonlocal_control.append(finally_control)\n    builder.activate_block(finally_block)\n    finally_body()\n    builder.nonlocal_control.pop()\n\n    return cleanup_block, finally_control\n\n\ndef try_finally_resolve_control(\n    builder: IRBuilder,\n    cleanup_block: BasicBlock,\n    finally_control: FinallyNonlocalControl,\n    old_exc: Value,\n    ret_reg: Register | AssignmentTarget | None,\n) -> BasicBlock:\n    \"\"\"Resolve the control flow out of a finally block.\n\n    This means returning if there was a return, propagating\n    exceptions, break/continue (soon), or just continuing on.\n    \"\"\"\n    line = builder.fn_info.fitem.line\n    reraise, rest = BasicBlock(), BasicBlock()\n    builder.add(Branch(old_exc, rest, reraise, Branch.IS_ERROR, line))\n\n    # Reraise the exception if there was one\n    builder.activate_block(reraise)\n    builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)\n    builder.add(Unreachable(line))\n    builder.builder.pop_error_handler()\n\n    # If there was a return, keep returning\n    if ret_reg:\n        builder.activate_block(rest)\n        return_block, rest = BasicBlock(), BasicBlock()\n        # For spill targets in try/finally, use nullable read to avoid AttributeError\n        if isinstance(ret_reg, AssignmentTargetAttr) and ret_reg.attr.startswith(TEMP_ATTR_NAME):\n            ret_val = builder.read_nullable_attr(ret_reg.obj, ret_reg.attr, line)\n        else:\n            ret_val = builder.read(ret_reg, line)\n        builder.add(Branch(ret_val, rest, return_block, Branch.IS_ERROR, line))\n\n        builder.activate_block(return_block)\n        builder.nonlocal_control[-1].gen_return(builder, ret_val, line)\n\n    # TODO: handle break/continue\n    builder.activate_block(rest)\n    out_block = BasicBlock()\n    builder.goto(out_block)\n\n    # If there was an exception, restore again\n    builder.activate_block(cleanup_block)\n    finally_control.gen_cleanup(builder, line)\n    builder.call_c(keep_propagating_op, [], NO_TRACEBACK_LINE_NO)\n    builder.add(Unreachable())\n\n    return out_block\n\n\ndef transform_try_finally_stmt(\n    builder: IRBuilder, try_body: GenFunc, finally_body: GenFunc, line: int = -1\n) -> None:\n    \"\"\"Generalized try/finally handling that takes functions to gen the bodies.\n\n    The point of this is to also be able to support with.\"\"\"\n    # Finally is a big pain, because there are so many ways that\n    # exits can occur. We emit 10+ basic blocks for every finally!\n\n    err_handler, main_entry, return_entry, finally_block = (\n        BasicBlock(),\n        BasicBlock(),\n        BasicBlock(),\n        BasicBlock(),\n    )\n\n    # Compile the body of the try\n    ret_reg = try_finally_try(builder, err_handler, return_entry, main_entry, try_body)\n\n    # Set up the entry blocks for the finally statement\n    old_exc = try_finally_entry_blocks(\n        builder, err_handler, return_entry, main_entry, finally_block, ret_reg\n    )\n\n    # Compile the body of the finally\n    cleanup_block, finally_control = try_finally_body(\n        builder, finally_block, finally_body, old_exc\n    )\n\n    # Resolve the control flow out of the finally block\n    out_block = try_finally_resolve_control(\n        builder, cleanup_block, finally_control, old_exc, ret_reg\n    )\n\n    builder.activate_block(out_block)\n\n\ndef transform_try_finally_stmt_async(\n    builder: IRBuilder, try_body: GenFunc, finally_body: GenFunc, line: int = -1\n) -> None:\n    \"\"\"Async-aware try/finally handling for when finally contains await.\n\n    This version uses a modified approach that preserves exceptions across await.\"\"\"\n\n    # We need to handle returns properly, so we'll use TryFinallyNonlocalControl\n    # to track return values, similar to the regular try/finally implementation\n\n    err_handler, main_entry, return_entry, finally_entry = (\n        BasicBlock(),\n        BasicBlock(),\n        BasicBlock(),\n        BasicBlock(),\n    )\n\n    # Track if we're returning from the try block\n    control = TryFinallyNonlocalControl(return_entry)\n    builder.builder.push_error_handler(err_handler)\n    builder.nonlocal_control.append(control)\n    builder.goto_and_activate(BasicBlock())\n    try_body()\n    builder.goto(main_entry)\n    builder.nonlocal_control.pop()\n    builder.builder.pop_error_handler()\n    ret_reg = control.ret_reg\n\n    # Normal case - no exception or return\n    builder.activate_block(main_entry)\n    builder.goto(finally_entry)\n\n    # Return case\n    builder.activate_block(return_entry)\n    builder.goto(finally_entry)\n\n    # Exception case - need to catch to clear the error indicator\n    builder.activate_block(err_handler)\n    # Catch the error to clear Python's error indicator\n    builder.call_c(error_catch_op, [], line)\n    # We're not going to use old_exc since it won't survive await\n    # The exception is now in sys.exc_info()\n    builder.goto(finally_entry)\n\n    # Finally block\n    builder.activate_block(finally_entry)\n\n    # Execute finally body\n    finally_body()\n\n    # After finally, we need to handle exceptions carefully:\n    # 1. If finally raised a new exception, it's in the error indicator - let it propagate\n    # 2. If finally didn't raise, check if we need to reraise the original from sys.exc_info()\n    # 3. If there was a return, return that value\n    # 4. Otherwise, normal exit\n\n    # First, check if there's a current exception in the error indicator\n    # (this would be from the finally block)\n    no_current_exc = builder.call_c(no_err_occurred_op, [], line)\n    finally_raised = BasicBlock()\n    check_original = BasicBlock()\n    builder.add(Branch(no_current_exc, check_original, finally_raised, Branch.BOOL))\n\n    # Finally raised an exception - let it propagate naturally\n    builder.activate_block(finally_raised)\n    builder.call_c(keep_propagating_op, [], NO_TRACEBACK_LINE_NO)\n    builder.add(Unreachable())\n\n    # No exception from finally, check if we need to handle return or original exception\n    builder.activate_block(check_original)\n\n    # Check if we have a return value\n    if ret_reg:\n        return_block, check_old_exc = BasicBlock(), BasicBlock()\n        builder.add(\n            Branch(\n                builder.read(ret_reg, line, allow_error_value=True),\n                check_old_exc,\n                return_block,\n                Branch.IS_ERROR,\n            )\n        )\n\n        builder.activate_block(return_block)\n        builder.nonlocal_control[-1].gen_return(builder, builder.read(ret_reg, line), line)\n\n        builder.activate_block(check_old_exc)\n\n    # Check if we need to reraise the original exception from sys.exc_info\n    exc_info = builder.call_c(get_exc_info_op, [], line)\n    exc_type = builder.add(TupleGet(exc_info, 0, line))\n\n    # Check if exc_type is None\n    none_obj = builder.none_object()\n    has_exc = builder.binary_op(exc_type, none_obj, \"is not\", line)\n\n    reraise_block, exit_block = BasicBlock(), BasicBlock()\n    builder.add(Branch(has_exc, reraise_block, exit_block, Branch.BOOL))\n\n    # Reraise the original exception\n    builder.activate_block(reraise_block)\n    builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)\n    builder.add(Unreachable())\n\n    # Normal exit\n    builder.activate_block(exit_block)\n\n\n# A simple visitor to detect await expressions\nclass AwaitDetector(mypy.traverser.TraverserVisitor):\n    def __init__(self) -> None:\n        super().__init__()\n        self.has_await = False\n\n    def visit_await_expr(self, o: mypy.nodes.AwaitExpr) -> None:\n        self.has_await = True\n        super().visit_await_expr(o)\n\n\ndef transform_try_stmt(builder: IRBuilder, t: TryStmt) -> None:\n    # Our compilation strategy for try/except/else/finally is to\n    # treat try/except/else and try/finally as separate language\n    # constructs that we compile separately. When we have a\n    # try/except/else/finally, we treat the try/except/else as the\n    # body of a try/finally block.\n    if t.is_star:\n        builder.error(\"Exception groups and except* cannot be compiled yet\", t.line)\n\n    # Check if we're in an async function with a finally block that contains await\n    use_async_version = False\n    if t.finally_body and builder.fn_info.is_coroutine:\n        detector = AwaitDetector()\n        t.finally_body.accept(detector)\n\n        if detector.has_await:\n            # Use the async version that handles exceptions correctly\n            use_async_version = True\n\n    if t.finally_body:\n\n        def transform_try_body() -> None:\n            if t.handlers:\n                transform_try_except_stmt(builder, t)\n            else:\n                builder.accept(t.body)\n\n        body = t.finally_body\n\n        if use_async_version:\n            transform_try_finally_stmt_async(\n                builder, transform_try_body, lambda: builder.accept(body), t.line\n            )\n        else:\n            transform_try_finally_stmt(\n                builder, transform_try_body, lambda: builder.accept(body), t.line\n            )\n    else:\n        transform_try_except_stmt(builder, t)\n\n\ndef get_sys_exc_info(builder: IRBuilder) -> list[Value]:\n    line = builder.fn_info.fitem.line\n    exc_info = builder.call_c(get_exc_info_op, [], line)\n    return [builder.add(TupleGet(exc_info, i, line)) for i in range(3)]\n\n\ndef transform_with(\n    builder: IRBuilder,\n    expr: Expression,\n    target: Lvalue | None,\n    body: GenFunc,\n    is_async: bool,\n    line: int,\n) -> None:\n    # This is basically a straight transcription of the Python code in PEP 343.\n    # I don't actually understand why a bunch of it is the way it is.\n    # We could probably optimize the case where the manager is compiled by us,\n    # but that is not our common case at all, so.\n\n    al = \"a\" if is_async else \"\"\n\n    mgr_v = builder.accept(expr)\n    is_native = isinstance(mgr_v.type, RInstance)\n    if is_native:\n        value = builder.add(MethodCall(mgr_v, f\"__{al}enter__\", args=[], line=line))\n        exit_ = None\n    else:\n        typ = builder.primitive_op(type_op, [mgr_v], line)\n        exit_ = builder.maybe_spill(builder.py_get_attr(typ, f\"__{al}exit__\", line))\n        value = builder.py_call(builder.py_get_attr(typ, f\"__{al}enter__\", line), [mgr_v], line)\n\n    mgr = builder.maybe_spill(mgr_v)\n    exc = builder.maybe_spill_assignable(builder.true())\n    if is_async:\n        value = emit_await(builder, value, line)\n\n    def maybe_natively_call_exit(exc_info: bool) -> Value:\n        if exc_info:\n            args = get_sys_exc_info(builder)\n        else:\n            none = builder.none_object()\n            args = [none, none, none]\n\n        if is_native:\n            assert isinstance(mgr_v.type, RInstance), mgr_v.type\n            exit_val = builder.gen_method_call(\n                builder.read(mgr, line),\n                f\"__{al}exit__\",\n                arg_values=args,\n                line=line,\n                result_type=none_rprimitive,\n            )\n        else:\n            assert exit_ is not None\n            exit_val = builder.py_call(\n                builder.read(exit_, line), [builder.read(mgr, line)] + args, line\n            )\n\n        if is_async:\n            return emit_await(builder, exit_val, line)\n        else:\n            return exit_val\n\n    def try_body() -> None:\n        if target:\n            builder.assign(builder.get_assignment_target(target), value, line)\n        body()\n\n    def except_body() -> None:\n        builder.assign(exc, builder.false(), line)\n        out_block, reraise_block = BasicBlock(), BasicBlock()\n        builder.add_bool_branch(maybe_natively_call_exit(exc_info=True), out_block, reraise_block)\n        builder.activate_block(reraise_block)\n        builder.call_c(reraise_exception_op, [], NO_TRACEBACK_LINE_NO)\n        builder.add(Unreachable())\n        builder.activate_block(out_block)\n\n    def finally_body() -> None:\n        out_block, exit_block = BasicBlock(), BasicBlock()\n        builder.add(Branch(builder.read(exc, line), exit_block, out_block, Branch.BOOL))\n        builder.activate_block(exit_block)\n\n        maybe_natively_call_exit(exc_info=False)\n        builder.goto_and_activate(out_block)\n\n    transform_try_finally_stmt(\n        builder,\n        lambda: transform_try_except(builder, try_body, [(None, None, except_body)], None, line),\n        finally_body,\n        line,\n    )\n\n\ndef transform_with_stmt(builder: IRBuilder, o: WithStmt) -> None:\n    # Generate separate logic for each expr in it, left to right\n    def generate(i: int) -> None:\n        if i >= len(o.expr):\n            builder.accept(o.body)\n        else:\n            transform_with(\n                builder, o.expr[i], o.target[i], lambda: generate(i + 1), o.is_async, o.line\n            )\n\n    generate(0)\n\n\ndef transform_assert_stmt(builder: IRBuilder, a: AssertStmt) -> None:\n    if builder.options.strip_asserts:\n        return\n    cond = builder.accept(a.expr)\n    ok_block, error_block = BasicBlock(), BasicBlock()\n    builder.add_bool_branch(cond, ok_block, error_block)\n    builder.activate_block(error_block)\n    if a.msg is None:\n        # Special case (for simpler generated code)\n        builder.add(RaiseStandardError(RaiseStandardError.ASSERTION_ERROR, None, a.line))\n    elif isinstance(a.msg, StrExpr):\n        # Another special case\n        builder.add(RaiseStandardError(RaiseStandardError.ASSERTION_ERROR, a.msg.value, a.line))\n    else:\n        # The general case -- explicitly construct an exception instance\n        message = builder.accept(a.msg)\n        exc_type = builder.load_module_attr_by_fullname(\"builtins.AssertionError\", a.line)\n        exc = builder.py_call(exc_type, [message], a.line)\n        builder.call_c(raise_exception_op, [exc], a.line)\n    builder.add(Unreachable())\n    builder.activate_block(ok_block)\n\n\ndef transform_del_stmt(builder: IRBuilder, o: DelStmt) -> None:\n    transform_del_item(builder, builder.get_assignment_target(o.expr), o.line)\n\n\ndef transform_del_item(builder: IRBuilder, target: AssignmentTarget, line: int) -> None:\n    if isinstance(target, AssignmentTargetIndex):\n        builder.gen_method_call(\n            target.base, \"__delitem__\", [target.index], result_type=None, line=line\n        )\n    elif isinstance(target, AssignmentTargetAttr):\n        if isinstance(target.obj_type, RInstance):\n            cl = target.obj_type.class_ir\n            if not cl.is_deletable(target.attr):\n                builder.error(f'\"{target.attr}\" cannot be deleted', line)\n                builder.note(\n                    'Using \"__deletable__ = '\n                    + '[\\'<attr>\\']\" in the class body enables \"del obj.<attr>\"',\n                    line,\n                )\n        key = builder.load_str(target.attr)\n        builder.primitive_op(py_delattr_op, [target.obj, key], line)\n    elif isinstance(target, AssignmentTargetRegister):\n        # Delete a local by assigning an error value to it, which will\n        # prompt the insertion of uninit checks.\n        builder.add(\n            Assign(target.register, builder.add(LoadErrorValue(target.type, undefines=True)))\n        )\n    elif isinstance(target, AssignmentTargetTuple):\n        for subtarget in target.items:\n            transform_del_item(builder, subtarget, line)\n\n\n# yield/yield from/await\n\n# These are really expressions, not statements... but they depend on try/except/finally\n\n\ndef emit_yield(builder: IRBuilder, val: Value, line: int) -> Value:\n    retval = builder.coerce(val, builder.ret_types[-1], line)\n\n    cls = builder.fn_info.generator_class\n    # Create a new block for the instructions immediately following the yield expression, and\n    # set the next label so that the next time '__next__' is called on the generator object,\n    # the function continues at the new block.\n    next_block = BasicBlock()\n    next_label = len(cls.continuation_blocks)\n    cls.continuation_blocks.append(next_block)\n    builder.assign(cls.next_label_target, Integer(next_label), line)\n    builder.add(Return(retval, yield_target=next_block))\n    builder.activate_block(next_block)\n\n    add_raise_exception_blocks_to_generator_class(builder, line)\n\n    assert cls.send_arg_reg is not None\n    return cls.send_arg_reg\n\n\ndef emit_yield_from_or_await(\n    builder: IRBuilder, val: Value, line: int, *, is_await: bool\n) -> Value:\n    # This is basically an implementation of the code in PEP 380.\n\n    # TODO: do we want to use the right types here?\n    result = Register(object_rprimitive, line=line)\n    to_yield_reg = Register(object_rprimitive, line=line)\n    received_reg = Register(object_rprimitive, line=line)\n\n    helper_method = GENERATOR_HELPER_NAME\n    if (\n        isinstance(val, (Call, MethodCall))\n        and isinstance(val.type, RInstance)\n        and val.type.class_ir.has_method(helper_method)\n    ):\n        # This is a generated native generator class, and we can use a fast path.\n        # This allows two optimizations:\n        # 1) No need to call CPy_GetCoro() or iter() since for native generators\n        #    it just returns the generator object (implemented here).\n        # 2) Instead of calling next(), call generator helper method directly,\n        #    since next() just calls __next__ which calls the helper method.\n        iter_val: Value = val\n    else:\n        get_op = coro_op if is_await else iter_op\n        if isinstance(get_op, PrimitiveDescription):\n            iter_val = builder.primitive_op(get_op, [val], line)\n        else:\n            iter_val = builder.call_c(get_op, [val], line)\n\n    iter_reg = builder.maybe_spill_assignable(iter_val)\n\n    stop_block, main_block, done_block = BasicBlock(), BasicBlock(), BasicBlock()\n\n    if isinstance(iter_reg.type, RInstance) and iter_reg.type.class_ir.has_method(helper_method):\n        # Second fast path optimization: call helper directly (see also comment above).\n        #\n        # Calling a generated generator, so avoid raising StopIteration by passing\n        # an extra PyObject ** argument to helper where the stop iteration value is stored.\n        fast_path = True\n        obj = builder.read(iter_reg, line)\n        nn = builder.none_object()\n        stop_iter_val = Register(object_rprimitive)\n        err = builder.add(LoadErrorValue(object_rprimitive, undefines=True))\n        builder.assign(stop_iter_val, err, line)\n        ptr = builder.add(LoadAddress(object_pointer_rprimitive, stop_iter_val))\n        m = MethodCall(obj, helper_method, [nn, nn, nn, nn, ptr], line)\n        # Generators have custom error handling, so disable normal error handling.\n        m.error_kind = ERR_NEVER\n        _y_init = builder.add(m)\n    else:\n        fast_path = False\n        _y_init = builder.call_c(next_raw_op, [builder.read(iter_reg, line)], line)\n\n    builder.add(Branch(_y_init, stop_block, main_block, Branch.IS_ERROR))\n\n    builder.activate_block(stop_block)\n    if fast_path:\n        builder.primitive_op(propagate_if_error_op, [stop_iter_val], line)\n        builder.assign(result, stop_iter_val, line)\n    else:\n        # Try extracting a return value from a StopIteration and return it.\n        # If it wasn't, this reraises the exception.\n        builder.assign(result, builder.call_c(check_stop_op, [], line), line)\n    # Clear the spilled iterator/coroutine so that it will be freed.\n    # Otherwise, the freeing of the spilled register would likely be delayed.\n    err = builder.add(LoadErrorValue(iter_reg.type))\n    builder.assign(iter_reg, err, line)\n    builder.goto(done_block)\n\n    builder.activate_block(main_block)\n    builder.assign(to_yield_reg, _y_init, line)\n\n    # OK Now the main loop!\n    loop_block = BasicBlock()\n    builder.goto_and_activate(loop_block)\n\n    def try_body() -> None:\n        builder.assign(\n            received_reg, emit_yield(builder, builder.read(to_yield_reg, line), line), line\n        )\n\n    def except_body() -> None:\n        # The body of the except is all implemented in a C function to\n        # reduce how much code we need to generate. It returns a value\n        # indicating whether to break or yield (or raise an exception).\n        val = Register(object_rprimitive)\n        val_address = builder.add(LoadAddress(object_pointer_rprimitive, val))\n        to_stop = builder.call_c(\n            yield_from_except_op, [builder.read(iter_reg, line), val_address], line\n        )\n\n        ok, stop = BasicBlock(), BasicBlock()\n        builder.add(Branch(to_stop, stop, ok, Branch.BOOL))\n\n        # The exception got swallowed. Continue, yielding the returned value\n        builder.activate_block(ok)\n        builder.assign(to_yield_reg, val, line)\n        builder.nonlocal_control[-1].gen_continue(builder, line)\n\n        # The exception was a StopIteration. Stop iterating.\n        builder.activate_block(stop)\n        builder.assign(result, val, line)\n        builder.nonlocal_control[-1].gen_break(builder, line)\n\n    def else_body() -> None:\n        # Do a next() or a .send(). It will return NULL on exception\n        # but it won't automatically propagate.\n        _y = builder.call_c(\n            send_op, [builder.read(iter_reg, line), builder.read(received_reg, line)], line\n        )\n        ok, stop = BasicBlock(), BasicBlock()\n        builder.add(Branch(_y, stop, ok, Branch.IS_ERROR))\n\n        # Everything's fine. Yield it.\n        builder.activate_block(ok)\n        builder.assign(to_yield_reg, _y, line)\n        builder.nonlocal_control[-1].gen_continue(builder, line)\n\n        # Try extracting a return value from a StopIteration and return it.\n        # If it wasn't, this rereaises the exception.\n        builder.activate_block(stop)\n        builder.assign(result, builder.call_c(check_stop_op, [], line), line)\n        builder.nonlocal_control[-1].gen_break(builder, line)\n\n    builder.push_loop_stack(loop_block, done_block)\n    transform_try_except(builder, try_body, [(None, None, except_body)], else_body, line)\n    builder.pop_loop_stack()\n\n    builder.goto_and_activate(done_block)\n    return builder.read(result, line)\n\n\ndef emit_await(builder: IRBuilder, val: Value, line: int) -> Value:\n    return emit_yield_from_or_await(builder, val, line, is_await=True)\n\n\ndef transform_yield_expr(builder: IRBuilder, expr: YieldExpr) -> Value:\n    if builder.fn_info.is_coroutine:\n        builder.error(\"async generators are unimplemented\", expr.line)\n\n    if expr.expr:\n        retval = builder.accept(expr.expr)\n    else:\n        retval = builder.builder.none()\n    return emit_yield(builder, retval, expr.line)\n\n\ndef transform_yield_from_expr(builder: IRBuilder, o: YieldFromExpr) -> Value:\n    return emit_yield_from_or_await(builder, builder.accept(o.expr), o.line, is_await=False)\n\n\ndef transform_await_expr(builder: IRBuilder, o: AwaitExpr) -> Value:\n    return emit_yield_from_or_await(builder, builder.accept(o.expr), o.line, is_await=True)\n\n\ndef transform_match_stmt(builder: IRBuilder, m: MatchStmt) -> None:\n    m.accept(MatchVisitor(builder, m))\n\n\ndef transform_type_alias_stmt(builder: IRBuilder, s: TypeAliasStmt) -> None:\n    line = s.line\n    # Use \"_typing\" to avoid importing \"typing\", as the latter can be expensive.\n    # \"_typing\" includes everything we need here.\n    mod = builder.call_c(import_op, [builder.load_str(\"_typing\")], line)\n    type_params = create_type_params(builder, mod, s.type_args, s.line)\n\n    type_alias_type = builder.py_get_attr(mod, \"TypeAliasType\", line)\n    args = [builder.load_str(s.name.name), builder.none()]\n    arg_names: list[str | None] = [None, None]\n    arg_kinds = [ARG_POS, ARG_POS]\n    if s.type_args:\n        args.append(builder.new_tuple(type_params, line))\n        arg_names.append(\"type_params\")\n        arg_kinds.append(ARG_NAMED)\n    alias = builder.py_call(type_alias_type, args, line, arg_names=arg_names, arg_kinds=arg_kinds)\n\n    # Use primitive to set function used to lazily compute type alias type value.\n    # The value needs to be lazily computed to match Python runtime behavior, but\n    # Python public APIs don't support this, so we use a C primitive.\n    compute_fn = s.value.accept(builder.visitor)\n    builder.builder.primitive_op(set_type_alias_compute_function_op, [alias, compute_fn], line)\n\n    target = builder.get_assignment_target(s.name)\n    builder.assign(target, alias, line)\n"
  },
  {
    "path": "mypyc/irbuild/targets.py",
    "content": "from __future__ import annotations\n\nfrom mypyc.ir.ops import Register, Value\nfrom mypyc.ir.rtypes import RInstance, RType, object_rprimitive\n\n\nclass AssignmentTarget:\n    \"\"\"Abstract base class for assignment targets during IR building.\"\"\"\n\n    type: RType = object_rprimitive\n\n\nclass AssignmentTargetRegister(AssignmentTarget):\n    \"\"\"Register as an assignment target.\n\n    This is used for local variables and some temporaries.\n    \"\"\"\n\n    def __init__(self, register: Register) -> None:\n        self.register = register\n        self.type = register.type\n\n    def __repr__(self) -> str:\n        return f\"AssignmentTargetRegister({self.register.name})\"\n\n\nclass AssignmentTargetIndex(AssignmentTarget):\n    \"\"\"base[index] as assignment target\"\"\"\n\n    def __init__(self, base: Value, index: Value) -> None:\n        self.base = base\n        self.index = index\n        # TODO: object_rprimitive won't be right for user-defined classes. Store the\n        #       lvalue type in mypy and use a better type to avoid unneeded boxing.\n        self.type = object_rprimitive\n\n    def __repr__(self) -> str:\n        return f\"AssignmentTargetIndex({self.base!r}, {self.index!r})\"\n\n\nclass AssignmentTargetAttr(AssignmentTarget):\n    \"\"\"obj.attr as assignment target\"\"\"\n\n    def __init__(self, obj: Value, attr: str, can_borrow: bool = False) -> None:\n        self.obj = obj\n        self.attr = attr\n        self.can_borrow = can_borrow\n        if isinstance(obj.type, RInstance) and obj.type.class_ir.has_attr(attr):\n            # Native attribute reference\n            self.obj_type: RType = obj.type\n            self.type = obj.type.attr_type(attr)\n        else:\n            # Python attribute reference\n            self.obj_type = object_rprimitive\n            self.type = object_rprimitive\n\n    def __repr__(self) -> str:\n        can_borrow_str = \", can_borrow=True\" if self.can_borrow else \"\"\n        return f\"AssignmentTargetAttr({self.obj!r}.{self.attr}{can_borrow_str})\"\n\n\nclass AssignmentTargetTuple(AssignmentTarget):\n    \"\"\"x, ..., y as assignment target\"\"\"\n\n    def __init__(self, items: list[AssignmentTarget], star_idx: int | None = None) -> None:\n        self.items = items\n        self.star_idx = star_idx\n\n    def __repr__(self) -> str:\n        return f\"AssignmentTargetTuple({self.items}, {self.star_idx})\"\n"
  },
  {
    "path": "mypyc/irbuild/util.py",
    "content": "\"\"\"Various utilities that don't depend on other modules in mypyc.irbuild.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Any, Final, Literal, TypedDict\nfrom typing_extensions import NotRequired\n\nfrom mypy.nodes import (\n    ARG_NAMED,\n    ARG_NAMED_OPT,\n    ARG_OPT,\n    ARG_POS,\n    GDEF,\n    ArgKind,\n    BytesExpr,\n    CallExpr,\n    ClassDef,\n    Decorator,\n    Expression,\n    FloatExpr,\n    FuncDef,\n    IntExpr,\n    NameExpr,\n    OverloadedFuncDef,\n    RefExpr,\n    StrExpr,\n    TupleExpr,\n    UnaryExpr,\n    Var,\n)\nfrom mypy.semanal import refers_to_fullname\nfrom mypy.types import FINAL_DECORATOR_NAMES\nfrom mypyc.errors import Errors\n\nMYPYC_ATTRS: Final[frozenset[MypycAttr]] = frozenset(\n    [\"native_class\", \"allow_interpreted_subclasses\", \"serializable\", \"free_list_len\", \"acyclic\"]\n)\n\nDATACLASS_DECORATORS: Final = frozenset([\"dataclasses.dataclass\", \"attr.s\", \"attr.attrs\"])\n\n\nMypycAttr = Literal[\n    \"native_class\", \"allow_interpreted_subclasses\", \"serializable\", \"free_list_len\", \"acyclic\"\n]\n\n\nclass MypycAttrs(TypedDict):\n    native_class: NotRequired[bool]\n    allow_interpreted_subclasses: NotRequired[bool]\n    serializable: NotRequired[bool]\n    free_list_len: NotRequired[int]\n    acyclic: NotRequired[bool]\n\n\ndef is_final_decorator(d: Expression) -> bool:\n    return refers_to_fullname(d, FINAL_DECORATOR_NAMES)\n\n\ndef is_trait_decorator(d: Expression) -> bool:\n    return isinstance(d, RefExpr) and d.fullname == \"mypy_extensions.trait\"\n\n\ndef is_trait(cdef: ClassDef) -> bool:\n    return any(is_trait_decorator(d) for d in cdef.decorators) or cdef.info.is_protocol\n\n\ndef dataclass_decorator_type(d: Expression) -> str | None:\n    if isinstance(d, RefExpr) and d.fullname in DATACLASS_DECORATORS:\n        return d.fullname.split(\".\")[0]\n    elif (\n        isinstance(d, CallExpr)\n        and isinstance(d.callee, RefExpr)\n        and d.callee.fullname in DATACLASS_DECORATORS\n    ):\n        name = d.callee.fullname.split(\".\")[0]\n        if name == \"attr\" and \"auto_attribs\" in d.arg_names:\n            # Note: the mypy attrs plugin checks that the value of auto_attribs is\n            # not computed at runtime, so we don't need to perform that check here\n            auto = d.args[d.arg_names.index(\"auto_attribs\")]\n            if isinstance(auto, NameExpr) and auto.name == \"True\":\n                return \"attr-auto\"\n        return name\n    else:\n        return None\n\n\ndef is_dataclass_decorator(d: Expression) -> bool:\n    return dataclass_decorator_type(d) is not None\n\n\ndef is_dataclass(cdef: ClassDef) -> bool:\n    return any(is_dataclass_decorator(d) for d in cdef.decorators)\n\n\n# The string values returned by this function are inspected in\n# mypyc/lib-rt/misc_ops.c:CPyDataclass_SleightOfHand(...).\ndef dataclass_type(cdef: ClassDef) -> str | None:\n    for d in cdef.decorators:\n        typ = dataclass_decorator_type(d)\n        if typ is not None:\n            return typ\n    return None\n\n\ndef get_mypyc_attr_literal(e: Expression) -> Any:\n    \"\"\"Convert an expression from a mypyc_attr decorator to a value.\n\n    Supports a pretty limited range.\"\"\"\n    if isinstance(e, (StrExpr, IntExpr, FloatExpr)):\n        return e.value\n    elif isinstance(e, RefExpr) and e.fullname == \"builtins.True\":\n        return True\n    elif isinstance(e, RefExpr) and e.fullname == \"builtins.False\":\n        return False\n    elif isinstance(e, RefExpr) and e.fullname == \"builtins.None\":\n        return None\n    elif isinstance(e, IntExpr):\n        return e.value\n    return NotImplemented\n\n\ndef get_mypyc_attr_call(d: Expression) -> CallExpr | None:\n    \"\"\"Check if an expression is a call to mypyc_attr and return it if so.\"\"\"\n    if (\n        isinstance(d, CallExpr)\n        and isinstance(d.callee, RefExpr)\n        and d.callee.fullname == \"mypy_extensions.mypyc_attr\"\n    ):\n        return d\n    return None\n\n\ndef get_mypyc_attrs(\n    stmt: ClassDef | Decorator, path: str, errors: Errors\n) -> tuple[MypycAttrs, dict[MypycAttr, int]]:\n    \"\"\"Collect all the mypyc_attr attributes on a class definition or a function.\"\"\"\n    attrs: MypycAttrs = {}\n    lines: dict[MypycAttr, int] = {}\n\n    def set_mypyc_attr(key: str, value: Any, line: int) -> None:\n        if key in MYPYC_ATTRS:\n            attrs[key] = value\n            lines[key] = line\n        else:\n            errors.error(f'\"{key}\" is not a supported \"mypyc_attr\"', path, line)\n            supported_keys = '\", \"'.join(sorted(MYPYC_ATTRS))\n            errors.note(f'supported keys: \"{supported_keys}\"', path, line)\n\n    for dec in stmt.decorators:\n        if d := get_mypyc_attr_call(dec):\n            line = d.line\n            for name, arg in zip(d.arg_names, d.args):\n                if name is None:\n                    if isinstance(arg, StrExpr):\n                        set_mypyc_attr(arg.value, True, line)\n                    else:\n                        errors.error(\n                            'All \"mypyc_attr\" positional arguments must be string literals.',\n                            path,\n                            line,\n                        )\n                else:\n                    arg_value = get_mypyc_attr_literal(arg)\n                    set_mypyc_attr(name, arg_value, line)\n\n    return attrs, lines\n\n\ndef is_extension_class(path: str, cdef: ClassDef, errors: Errors) -> bool:\n    # Check for @mypyc_attr(native_class=True/False) decorator.\n    explicit_native_class = get_explicit_native_class(path, cdef, errors)\n\n    # Classes with native_class=False are explicitly marked as non extension.\n    if explicit_native_class is False:\n        return False\n\n    implicit_extension_class, reason = is_implicit_extension_class(cdef)\n\n    # Classes with native_class=True should be extension classes, but they might\n    # not be able to be due to other reasons. Print an error in that case.\n    if explicit_native_class is True and not implicit_extension_class:\n        errors.error(\n            f\"Class is marked as native_class=True but it can't be a native class. {reason}\",\n            path,\n            cdef.line,\n        )\n\n    return implicit_extension_class\n\n\ndef get_explicit_native_class(path: str, cdef: ClassDef, errors: Errors) -> bool | None:\n    \"\"\"Return value of @mypyc_attr(native_class=True/False) decorator.\n\n    Look for a @mypyc_attr decorator with native_class=True/False and return\n    the value assigned or None if it doesn't exist. Other values are an error.\n    \"\"\"\n\n    for d in cdef.decorators:\n        mypyc_attr_call = get_mypyc_attr_call(d)\n        if not mypyc_attr_call:\n            continue\n\n        for i, name in enumerate(mypyc_attr_call.arg_names):\n            if name != \"native_class\":\n                continue\n\n            arg = mypyc_attr_call.args[i]\n            if not isinstance(arg, NameExpr):\n                errors.error(\"native_class must be used with True or False only\", path, cdef.line)\n                return None\n\n            if arg.name == \"False\":\n                return False\n            elif arg.name == \"True\":\n                return True\n            else:\n                errors.error(\"native_class must be used with True or False only\", path, cdef.line)\n                return None\n    return None\n\n\ndef is_implicit_extension_class(cdef: ClassDef) -> tuple[bool, str]:\n    \"\"\"Check if class can be extension class and return a user-friendly reason it can't be one.\"\"\"\n\n    for d in cdef.decorators:\n        if (\n            not is_trait_decorator(d)\n            and not is_dataclass_decorator(d)\n            and not get_mypyc_attr_call(d)\n            and not is_final_decorator(d)\n        ):\n            return (\n                False,\n                \"Classes that have decorators other than supported decorators\"\n                \" can't be native classes.\",\n            )\n\n    if cdef.info.typeddict_type:\n        return False, \"TypedDict classes can't be native classes.\"\n    if cdef.info.is_named_tuple:\n        return False, \"NamedTuple classes can't be native classes.\"\n    if cdef.info.metaclass_type and cdef.info.metaclass_type.type.fullname not in (\n        \"abc.ABCMeta\",\n        \"typing.TypingMeta\",\n        \"typing.GenericMeta\",\n    ):\n        return (\n            False,\n            \"Classes with a metaclass other than ABCMeta, TypingMeta or\"\n            \" GenericMeta can't be native classes.\",\n        )\n    return True, \"\"\n\n\ndef get_func_def(op: FuncDef | Decorator | OverloadedFuncDef) -> FuncDef:\n    if isinstance(op, OverloadedFuncDef):\n        assert op.impl\n        op = op.impl\n    if isinstance(op, Decorator):\n        op = op.func\n    return op\n\n\ndef concrete_arg_kind(kind: ArgKind) -> ArgKind:\n    \"\"\"Find the concrete version of an arg kind that is being passed.\"\"\"\n    if kind == ARG_OPT:\n        return ARG_POS\n    elif kind == ARG_NAMED_OPT:\n        return ARG_NAMED\n    else:\n        return kind\n\n\ndef is_constant(e: Expression) -> bool:\n    \"\"\"Check whether we allow an expression to appear as a default value.\n\n    We don't currently properly support storing the evaluated\n    values for default arguments and default attribute values, so\n    we restrict what expressions we allow.  We allow literals of\n    primitives types, None, and references to Final global\n    variables.\n    \"\"\"\n    return (\n        isinstance(e, (StrExpr, BytesExpr, IntExpr, FloatExpr))\n        or (isinstance(e, UnaryExpr) and e.op == \"-\" and isinstance(e.expr, (IntExpr, FloatExpr)))\n        or (isinstance(e, TupleExpr) and all(is_constant(e) for e in e.items))\n        or (\n            isinstance(e, RefExpr)\n            and e.kind == GDEF\n            and (\n                e.fullname in (\"builtins.True\", \"builtins.False\", \"builtins.None\")\n                or (isinstance(e.node, Var) and e.node.is_final)\n            )\n        )\n    )\n\n\ndef bytes_from_str(value: str) -> bytes:\n    \"\"\"Convert a string representing bytes into actual bytes.\n\n    This is needed because the literal characters of BytesExpr (the\n    characters inside b'') are stored in BytesExpr.value, whose type is\n    'str' not 'bytes'.\n    \"\"\"\n    return bytes(value, \"utf8\").decode(\"unicode-escape\").encode(\"raw-unicode-escape\")\n"
  },
  {
    "path": "mypyc/irbuild/vec.py",
    "content": "\"\"\"Generate IR for librt.vecs.vec operations\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import TYPE_CHECKING, Final, cast\n\nfrom mypyc.common import IS_32_BIT_PLATFORM, PLATFORM_SIZE\nfrom mypyc.ir.ops import (\n    ERR_MAGIC,\n    ERR_NEVER,\n    Assign,\n    BasicBlock,\n    Branch,\n    CallC,\n    ComparisonOp,\n    DecRef,\n    GetElement,\n    GetElementPtr,\n    Integer,\n    IntOp,\n    RaiseStandardError,\n    Register,\n    SetElement,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Undef,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RPrimitive,\n    RTuple,\n    RType,\n    RUnion,\n    RVec,\n    VecNestedBufItem,\n    bool_rprimitive,\n    c_pyssize_t_rprimitive,\n    c_size_t_rprimitive,\n    int32_rprimitive,\n    int64_rprimitive,\n    is_c_py_ssize_t_rprimitive,\n    is_int32_rprimitive,\n    is_int64_rprimitive,\n    is_int_rprimitive,\n    is_short_int_rprimitive,\n    object_rprimitive,\n    optional_value_type,\n    pointer_rprimitive,\n    vec_api_by_item_type,\n    vec_item_type_tags,\n)\nfrom mypyc.primitives.registry import builtin_names\n\nif TYPE_CHECKING:\n    from mypyc.irbuild.ll_builder import LowLevelIRBuilder\n\n\ndef as_platform_int(builder: LowLevelIRBuilder, v: Value, line: int) -> Value:\n    rtype = v.type\n    if is_c_py_ssize_t_rprimitive(rtype):\n        return v\n    if isinstance(v, Integer):\n        if is_short_int_rprimitive(rtype) or is_int_rprimitive(rtype):\n            return Integer(v.value // 2, c_pyssize_t_rprimitive)\n        return Integer(v.value, c_pyssize_t_rprimitive)\n    if isinstance(rtype, RPrimitive):\n        if PLATFORM_SIZE == 8 and is_int64_rprimitive(rtype):\n            return v\n        if PLATFORM_SIZE == 4 and is_int32_rprimitive(rtype):\n            return v\n    return builder.coerce(v, c_pyssize_t_rprimitive, line)\n\n\ndef vec_create(builder: LowLevelIRBuilder, vtype: RVec, length: int | Value, line: int) -> Value:\n    if isinstance(length, int):\n        length = Integer(length, c_pyssize_t_rprimitive)\n    length = as_platform_int(builder, length, line)\n\n    item_type = vtype.item_type\n    api_name = vec_api_by_item_type.get(item_type)\n    if api_name is not None:\n        call = CallC(\n            f\"{api_name}.alloc\",\n            [length, length],\n            vtype,\n            False,\n            False,\n            error_kind=ERR_MAGIC,\n            line=line,\n        )\n        return builder.add(call)\n\n    typeobj, optional, depth = vec_item_type_info(builder, item_type, line)\n    if typeobj is not None:\n        typeval: Value\n        if isinstance(typeobj, Integer):\n            typeval = typeobj\n        else:\n            # Create an integer which will hold the type object * as an integral value.\n            # Assign implicitly coerces between pointer/integer types.\n            typeval = Register(pointer_rprimitive)\n            builder.add(Assign(typeval, typeobj))\n            if optional:\n                typeval = builder.add(\n                    IntOp(pointer_rprimitive, typeval, Integer(1, pointer_rprimitive), IntOp.OR)\n                )\n        if depth == 0:\n            call = CallC(\n                \"VecTApi.alloc\",\n                [length, length, typeval],\n                vtype,\n                False,\n                False,\n                error_kind=ERR_MAGIC,\n                line=line,\n            )\n            return builder.add(call)\n        else:\n            call = CallC(\n                \"VecNestedApi.alloc\",\n                [length, length, typeval, Integer(depth, int32_rprimitive)],\n                vtype,\n                False,\n                False,\n                error_kind=ERR_MAGIC,\n                line=line,\n            )\n            return builder.add(call)\n\n    assert False, \"unsupported: %s\" % vtype\n\n\ndef vec_create_initialized(\n    builder: LowLevelIRBuilder, vtype: RVec, length: int | Value, init: Value, line: int\n) -> Value:\n    \"\"\"Create vec with items initialized to the given value.\"\"\"\n    if isinstance(length, int):\n        length = Integer(length, c_pyssize_t_rprimitive)\n    length = as_platform_int(builder, length, line)\n\n    item_type = vtype.item_type\n    init = builder.coerce(init, item_type, line)\n    vec = vec_create(builder, vtype, length, line)\n\n    items_start = vec_items(builder, vec)\n    step = step_size(item_type)\n    items_end = builder.int_add(items_start, builder.int_mul(length, step))\n\n    for_loop = builder.begin_for(\n        items_start, items_end, Integer(step, c_pyssize_t_rprimitive), signed=False\n    )\n    builder.set_mem(for_loop.index, item_type, init)\n    for_loop.finish()\n\n    builder.keep_alive([vec], line)\n    return vec\n\n\ndef vec_create_from_values(\n    builder: LowLevelIRBuilder, vtype: RVec, values: list[Value], line: int\n) -> Value:\n    vec = vec_create(builder, vtype, len(values), line)\n    ptr = vec_items(builder, vec)\n    item_type = vtype.item_type\n    step = step_size(item_type)\n    for value in values:\n        builder.set_mem(ptr, item_type, value)\n        ptr = builder.int_add(ptr, step)\n    builder.keep_alive([vec], line)\n    return vec\n\n\ndef step_size(item_type: RType) -> int:\n    if isinstance(item_type, RPrimitive):\n        return item_type.size\n    elif isinstance(item_type, RVec):\n        return PLATFORM_SIZE * 2\n    else:\n        return PLATFORM_SIZE\n\n\nVEC_TYPE_INFO_I64: Final = 2\n\n\ndef vec_item_type_info(\n    builder: LowLevelIRBuilder, typ: RType, line: int\n) -> tuple[Value | None, bool, int]:\n    if isinstance(typ, RPrimitive) and typ.is_refcounted:\n        typ, src = builtin_names[typ.name]\n        return builder.load_address(src, typ), False, 0\n    elif isinstance(typ, RInstance):\n        return builder.load_native_type_object(typ.name), False, 0\n    elif typ in vec_item_type_tags:\n        return Integer(vec_item_type_tags[typ], c_size_t_rprimitive), False, 0\n    elif isinstance(typ, RUnion):\n        non_opt = optional_value_type(typ)\n        assert non_opt is not None\n        typeval, _, _ = vec_item_type_info(builder, non_opt, line)\n        if typeval is not None:\n            return typeval, True, 0\n    elif isinstance(typ, RVec):\n        typeval, optional, depth = vec_item_type_info(builder, typ.item_type, line)\n        if typeval is not None:\n            return typeval, optional, depth + 1\n    return None, False, 0\n\n\ndef vec_len(builder: LowLevelIRBuilder, val: Value) -> Value:\n    \"\"\"Return len(<vec>) as i64.\"\"\"\n    len_val = vec_len_native(builder, val)\n    if IS_32_BIT_PLATFORM:\n        return builder.coerce(len_val, int64_rprimitive, -1)\n    return len_val\n\n\ndef vec_len_native(builder: LowLevelIRBuilder, val: Value) -> Value:\n    \"\"\"Return len(<vec>) as platform integer type (32-bit/64-bit).\"\"\"\n    return builder.get_element(val, \"len\")\n\n\ndef vec_items(builder: LowLevelIRBuilder, vecobj: Value) -> Value:\n    vtype = cast(RVec, vecobj.type)\n    buf = builder.get_element(vecobj, \"buf\")\n    return builder.add(GetElementPtr(buf, vtype.buf_type, \"items\"))\n\n\ndef vec_item_ptr(builder: LowLevelIRBuilder, vecobj: Value, index: Value) -> Value:\n    items_addr = vec_items(builder, vecobj)\n    assert isinstance(vecobj.type, RVec)\n    # TODO: Do we need to care about alignment?\n    item_type = vecobj.type.item_type\n    if isinstance(item_type, RPrimitive):\n        item_size = item_type.size\n    elif isinstance(item_type, RVec):\n        item_size = 2 * PLATFORM_SIZE\n    else:\n        item_size = object_rprimitive.size\n    delta = builder.int_mul(index, item_size)\n    return builder.int_add(items_addr, delta)\n\n\ndef vec_check_and_adjust_index(\n    builder: LowLevelIRBuilder, lenv: Value, index: Value, line: int\n) -> Value:\n    r = Register(int64_rprimitive)\n    index = builder.coerce(index, int64_rprimitive, line)\n    lenv = builder.coerce(lenv, int64_rprimitive, line)\n    ok, ok2, ok3 = BasicBlock(), BasicBlock(), BasicBlock()\n    fail, fail2 = BasicBlock(), BasicBlock()\n    is_less = builder.comparison_op(index, lenv, ComparisonOp.ULT, line)\n    builder.add_bool_branch(is_less, ok2, fail)\n    builder.activate_block(fail)\n\n    x = builder.int_add(index, lenv)\n    is_less2 = builder.comparison_op(x, lenv, ComparisonOp.ULT, line)\n    builder.add_bool_branch(is_less2, ok, fail2)\n\n    builder.activate_block(fail2)\n    # TODO: Include index in exception\n    builder.add(RaiseStandardError(RaiseStandardError.INDEX_ERROR, None, line))\n    builder.add(Unreachable())\n\n    builder.activate_block(ok)\n    builder.assign(r, x)\n    builder.goto(ok3)\n\n    builder.activate_block(ok2)\n    builder.assign(r, index)\n    builder.goto(ok3)\n\n    builder.activate_block(ok3)\n    return r\n\n\ndef vec_get_item(\n    builder: LowLevelIRBuilder, base: Value, index: Value, line: int, *, can_borrow: bool = False\n) -> Value:\n    \"\"\"Generate inlined vec __getitem__ call.\n\n    We inline this, since it's simple but performance-critical.\n    \"\"\"\n    # TODO: Support more item types\n    # TODO: Support more index types\n    len_val = vec_len(builder, base)\n    index = vec_check_and_adjust_index(builder, len_val, index, line)\n    return vec_get_item_unsafe(builder, base, index, line, can_borrow=can_borrow)\n\n\ndef vec_get_item_unsafe(\n    builder: LowLevelIRBuilder, base: Value, index: Value, line: int, *, can_borrow: bool = False\n) -> Value:\n    \"\"\"Get vec item, assuming index is non-negative and within bounds.\"\"\"\n    assert isinstance(base.type, RVec)\n    index = as_platform_int(builder, index, line)\n    vtype = base.type\n    item_addr = vec_item_ptr(builder, base, index)\n    result = builder.load_mem(item_addr, vtype.item_type, borrow=can_borrow)\n    builder.keep_alives.append(base)\n    return result\n\n\ndef vec_set_item(\n    builder: LowLevelIRBuilder, base: Value, index: Value, item: Value, line: int\n) -> None:\n    assert isinstance(base.type, RVec)\n    vtype = base.type\n    len_val = vec_len(builder, base)\n    index = vec_check_and_adjust_index(builder, len_val, index, line)\n    index = builder.coerce(index, c_pyssize_t_rprimitive, line)\n    item_addr = vec_item_ptr(builder, base, index)\n    item_type = vtype.item_type\n    item = builder.coerce(item, item_type, line)\n    if item_type.is_refcounted:\n        # Read an unborrowed reference to cause a decref to be\n        # generated for the old item.\n        old_item = builder.load_mem(item_addr, item_type, borrow=True)\n        builder.add(DecRef(old_item))\n    builder.set_mem(item_addr, item_type, item)\n    builder.keep_alive([base], line)\n\n\ndef vec_init_item_unsafe(\n    builder: LowLevelIRBuilder, base: Value, index: Value, item: Value, line: int\n) -> None:\n    assert isinstance(base.type, RVec)\n    index = as_platform_int(builder, index, line)\n    vtype = base.type\n    item_addr = vec_item_ptr(builder, base, index)\n    item_type = vtype.item_type\n    item = builder.coerce(item, item_type, line)\n    builder.set_mem(item_addr, item_type, item)\n    builder.keep_alive([base], line)\n\n\ndef convert_to_t_ext_item(builder: LowLevelIRBuilder, item: Value) -> Value:\n    vec_len = builder.add(GetElement(item, \"len\"))\n    vec_buf = builder.add(GetElement(item, \"buf\"))\n    temp = builder.add(SetElement(Undef(VecNestedBufItem), \"len\", vec_len))\n    return builder.add(SetElement(temp, \"buf\", vec_buf))\n\n\ndef convert_from_t_ext_item(builder: LowLevelIRBuilder, item: Value, vec_type: RVec) -> Value:\n    \"\"\"Convert a value of type VecNestedBufItem to the corresponding RVec value.\"\"\"\n    api_name = vec_api_by_item_type.get(vec_type.item_type)\n    if api_name is not None:\n        name = f\"{api_name}.convert_from_nested\"\n    elif isinstance(vec_type.item_type, RVec):\n        name = \"VecNestedApi.convert_from_nested\"\n    else:\n        name = \"VecTApi.convert_from_nested\"\n\n    return builder.add(\n        CallC(\n            name, [item], vec_type, steals=[True], is_borrowed=False, error_kind=ERR_NEVER, line=-1\n        )\n    )\n\n\ndef vec_item_type(builder: LowLevelIRBuilder, item_type: RType, line: int) -> Value:\n    typeobj, optional, depth = vec_item_type_info(builder, item_type, line)\n    assert typeobj is not None\n    if isinstance(typeobj, Integer):\n        return typeobj\n    else:\n        # Create an integer which will hold the type object * as an integral value.\n        # Assign implicitly coerces between pointer/integer types.\n        typeval: Value\n        typeval = Register(pointer_rprimitive)\n        builder.add(Assign(typeval, typeobj))\n        if optional:\n            typeval = builder.add(\n                IntOp(pointer_rprimitive, typeval, Integer(1, pointer_rprimitive), IntOp.OR)\n            )\n        return typeval\n\n\ndef vec_append(builder: LowLevelIRBuilder, vec: Value, item: Value, line: int) -> Value:\n    vec_type = vec.type\n    assert isinstance(vec_type, RVec)\n    item_type = vec_type.item_type\n    coerced_item = builder.coerce(item, item_type, line)\n    item_type_arg = []\n    api_name = vec_api_by_item_type.get(item_type)\n    if api_name is not None:\n        name = f\"{api_name}.append\"\n    elif vec_type.depth() == 0:\n        name = \"VecTApi.append\"\n        item_type_arg = [vec_item_type(builder, item_type, line)]\n    else:\n        coerced_item = convert_to_t_ext_item(builder, coerced_item)\n        name = \"VecNestedApi.append\"\n    call = builder.add(\n        CallC(\n            name,\n            [vec, coerced_item] + item_type_arg,\n            vec_type,\n            steals=[True, False] + ([False] if item_type_arg else []),\n            is_borrowed=False,\n            error_kind=ERR_MAGIC,\n            line=line,\n        )\n    )\n    if vec_type.depth() > 0:\n        builder.keep_alive([item], line)\n    return call\n\n\ndef vec_pop(builder: LowLevelIRBuilder, base: Value, index: Value, line: int) -> Value:\n    assert isinstance(base.type, RVec)\n    vec_type = base.type\n    item_type = vec_type.item_type\n    index = as_platform_int(builder, index, line)\n\n    api_name = vec_api_by_item_type.get(item_type)\n    if api_name is not None:\n        name = f\"{api_name}.pop\"\n    elif vec_type.depth() == 0:\n        name = \"VecTApi.pop\"\n    else:\n        name = \"VecNestedApi.pop\"\n        # Nested vecs return a generic vec struct.\n        item_type = VecNestedBufItem\n    result = builder.add(\n        CallC(\n            name,\n            [base, index],\n            RTuple([vec_type, item_type]),\n            steals=[True, False],\n            is_borrowed=False,\n            error_kind=ERR_MAGIC,\n            line=line,\n        )\n    )\n    if vec_type.depth() > 0:\n        orig = result\n        x = builder.add(TupleGet(result, 0, borrow=True))\n        x = builder.add(Unborrow(x))\n        y = builder.add(TupleGet(result, 1, borrow=True))\n        y = builder.add(Unborrow(y))\n        assert isinstance(vec_type.item_type, RVec)\n        z = convert_from_t_ext_item(builder, y, vec_type.item_type)\n        result = builder.add(TupleSet([x, z], line))\n        builder.keep_alive([orig], line, steal=True)\n    return result\n\n\ndef vec_remove(builder: LowLevelIRBuilder, vec: Value, item: Value, line: int) -> Value:\n    assert isinstance(vec.type, RVec)\n    vec_type = vec.type\n    item_type = vec_type.item_type\n    coerced_item = builder.coerce(item, item_type, line)\n\n    if item_type in vec_api_by_item_type:\n        name = f\"{vec_api_by_item_type[item_type]}.remove\"\n    elif vec_type.depth() == 0:\n        name = \"VecTApi.remove\"\n    else:\n        coerced_item = convert_to_t_ext_item(builder, coerced_item)\n        name = \"VecNestedApi.remove\"\n    call = builder.add(\n        CallC(\n            name,\n            [vec, coerced_item],\n            vec_type,\n            steals=[True, False],\n            is_borrowed=False,\n            error_kind=ERR_MAGIC,\n            line=line,\n        )\n    )\n    if vec_type.depth() > 0:\n        builder.keep_alive([item], line)\n    return call\n\n\ndef vec_contains(builder: LowLevelIRBuilder, vec: Value, target: Value, line: int) -> Value:\n    assert isinstance(vec.type, RVec)\n    vec_type = vec.type\n    item_type = vec_type.item_type\n    target = builder.coerce(target, item_type, line)\n\n    step = step_size(item_type)\n    len_val = vec_len_native(builder, vec)\n    items_start = vec_items(builder, vec)\n    items_end = builder.int_add(items_start, builder.int_mul(len_val, step))\n\n    true, end = BasicBlock(), BasicBlock()\n\n    for_loop = builder.begin_for(\n        items_start, items_end, Integer(step, c_pyssize_t_rprimitive), signed=False\n    )\n    item = builder.load_mem(for_loop.index, item_type, borrow=True)\n    comp = builder.binary_op(item, target, \"==\", line)\n    false = BasicBlock()\n    builder.add(Branch(comp, true, false, Branch.BOOL))\n    builder.activate_block(false)\n    for_loop.finish()\n\n    builder.keep_alive([vec], line)\n\n    res = Register(bool_rprimitive)\n    builder.assign(res, Integer(0, bool_rprimitive))\n    builder.goto(end)\n    builder.activate_block(true)\n    builder.assign(res, Integer(1, bool_rprimitive))\n    builder.goto_and_activate(end)\n    return res\n\n\ndef vec_slice(\n    builder: LowLevelIRBuilder, vec: Value, begin: Value, end: Value, line: int\n) -> Value:\n    assert isinstance(vec.type, RVec)\n    vec_type = vec.type\n    item_type = vec_type.item_type\n    begin = builder.coerce(begin, int64_rprimitive, line)\n    end = builder.coerce(end, int64_rprimitive, line)\n    api_name = vec_api_by_item_type.get(item_type)\n    if api_name is not None:\n        name = f\"{api_name}.slice\"\n    elif vec_type.depth() == 0:\n        name = \"VecTApi.slice\"\n    else:\n        name = \"VecNestedApi.slice\"\n    call = CallC(\n        name,\n        [vec, begin, end],\n        vec_type,\n        steals=[False, False, False],\n        is_borrowed=False,\n        error_kind=ERR_MAGIC,\n        line=line,\n    )\n    return builder.add(call)\n"
  },
  {
    "path": "mypyc/irbuild/visitor.py",
    "content": "\"\"\"Dispatcher used when transforming a mypy AST to the IR form.\n\nmypyc.irbuild.builder and mypyc.irbuild.main are closely related.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import NoReturn\n\nfrom mypy.nodes import (\n    AssertStmt,\n    AssertTypeExpr,\n    AssignmentExpr,\n    AssignmentStmt,\n    AwaitExpr,\n    Block,\n    BreakStmt,\n    BytesExpr,\n    CallExpr,\n    CastExpr,\n    ClassDef,\n    ComparisonExpr,\n    ComplexExpr,\n    ConditionalExpr,\n    ContinueStmt,\n    Decorator,\n    DelStmt,\n    DictExpr,\n    DictionaryComprehension,\n    EllipsisExpr,\n    EnumCallExpr,\n    ExpressionStmt,\n    FloatExpr,\n    ForStmt,\n    FuncDef,\n    GeneratorExpr,\n    GlobalDecl,\n    IfStmt,\n    Import,\n    ImportAll,\n    ImportFrom,\n    IndexExpr,\n    IntExpr,\n    LambdaExpr,\n    ListComprehension,\n    ListExpr,\n    MatchStmt,\n    MemberExpr,\n    MypyFile,\n    NamedTupleExpr,\n    NameExpr,\n    NewTypeExpr,\n    NonlocalDecl,\n    OperatorAssignmentStmt,\n    OpExpr,\n    OverloadedFuncDef,\n    ParamSpecExpr,\n    PassStmt,\n    PromoteExpr,\n    RaiseStmt,\n    ReturnStmt,\n    RevealExpr,\n    SetComprehension,\n    SetExpr,\n    SliceExpr,\n    StarExpr,\n    StrExpr,\n    SuperExpr,\n    TemplateStrExpr,\n    TempNode,\n    TryStmt,\n    TupleExpr,\n    TypeAliasExpr,\n    TypeAliasStmt,\n    TypeApplication,\n    TypedDictExpr,\n    TypeFormExpr,\n    TypeVarExpr,\n    TypeVarTupleExpr,\n    UnaryExpr,\n    Var,\n    WhileStmt,\n    WithStmt,\n    YieldExpr,\n    YieldFromExpr,\n)\nfrom mypyc.ir.ops import Value\nfrom mypyc.irbuild.builder import IRBuilder, IRVisitor, UnsupportedException\nfrom mypyc.irbuild.classdef import transform_class_def\nfrom mypyc.irbuild.expression import (\n    transform_assignment_expr,\n    transform_bytes_expr,\n    transform_call_expr,\n    transform_comparison_expr,\n    transform_complex_expr,\n    transform_conditional_expr,\n    transform_dict_expr,\n    transform_dictionary_comprehension,\n    transform_ellipsis,\n    transform_float_expr,\n    transform_generator_expr,\n    transform_index_expr,\n    transform_int_expr,\n    transform_list_comprehension,\n    transform_list_expr,\n    transform_member_expr,\n    transform_name_expr,\n    transform_op_expr,\n    transform_set_comprehension,\n    transform_set_expr,\n    transform_slice_expr,\n    transform_str_expr,\n    transform_super_expr,\n    transform_tuple_expr,\n    transform_unary_expr,\n)\nfrom mypyc.irbuild.function import (\n    transform_decorator,\n    transform_func_def,\n    transform_lambda_expr,\n    transform_overloaded_func_def,\n)\nfrom mypyc.irbuild.statement import (\n    transform_assert_stmt,\n    transform_assignment_stmt,\n    transform_await_expr,\n    transform_block,\n    transform_break_stmt,\n    transform_continue_stmt,\n    transform_del_stmt,\n    transform_expression_stmt,\n    transform_for_stmt,\n    transform_if_stmt,\n    transform_import,\n    transform_import_all,\n    transform_import_from,\n    transform_match_stmt,\n    transform_operator_assignment_stmt,\n    transform_raise_stmt,\n    transform_return_stmt,\n    transform_try_stmt,\n    transform_type_alias_stmt,\n    transform_while_stmt,\n    transform_with_stmt,\n    transform_yield_expr,\n    transform_yield_from_expr,\n)\n\n\nclass IRBuilderVisitor(IRVisitor):\n    \"\"\"Mypy node visitor that dispatches to node transform implementations.\n\n    This class should have no non-trivial logic.\n\n    This visitor is separated from the rest of code to improve modularity and\n    to avoid import cycles.\n\n    This is based on the visitor pattern\n    (https://en.wikipedia.org/wiki/Visitor_pattern).\n    \"\"\"\n\n    # This gets passed to all the implementations and contains all the\n    # state and many helpers. The attribute is initialized outside\n    # this class since this class and IRBuilder form a reference loop.\n    builder: IRBuilder\n\n    def visit_mypy_file(self, mypyfile: MypyFile) -> None:\n        assert False, \"use transform_mypy_file instead\"\n\n    def visit_class_def(self, cdef: ClassDef) -> None:\n        transform_class_def(self.builder, cdef)\n\n    def visit_import(self, node: Import) -> None:\n        transform_import(self.builder, node)\n\n    def visit_import_from(self, node: ImportFrom) -> None:\n        transform_import_from(self.builder, node)\n\n    def visit_import_all(self, node: ImportAll) -> None:\n        transform_import_all(self.builder, node)\n\n    def visit_func_def(self, fdef: FuncDef) -> None:\n        transform_func_def(self.builder, fdef)\n\n    def visit_overloaded_func_def(self, o: OverloadedFuncDef) -> None:\n        transform_overloaded_func_def(self.builder, o)\n\n    def visit_decorator(self, dec: Decorator) -> None:\n        transform_decorator(self.builder, dec)\n\n    def visit_block(self, block: Block) -> None:\n        transform_block(self.builder, block)\n\n    # Statements\n\n    def visit_expression_stmt(self, stmt: ExpressionStmt) -> None:\n        transform_expression_stmt(self.builder, stmt)\n\n    def visit_return_stmt(self, stmt: ReturnStmt) -> None:\n        transform_return_stmt(self.builder, stmt)\n        self.builder.mark_block_unreachable()\n\n    def visit_assignment_stmt(self, stmt: AssignmentStmt) -> None:\n        transform_assignment_stmt(self.builder, stmt)\n\n    def visit_operator_assignment_stmt(self, stmt: OperatorAssignmentStmt) -> None:\n        transform_operator_assignment_stmt(self.builder, stmt)\n\n    def visit_if_stmt(self, stmt: IfStmt) -> None:\n        transform_if_stmt(self.builder, stmt)\n\n    def visit_while_stmt(self, stmt: WhileStmt) -> None:\n        transform_while_stmt(self.builder, stmt)\n\n    def visit_for_stmt(self, stmt: ForStmt) -> None:\n        transform_for_stmt(self.builder, stmt)\n\n    def visit_break_stmt(self, stmt: BreakStmt) -> None:\n        transform_break_stmt(self.builder, stmt)\n        self.builder.mark_block_unreachable()\n\n    def visit_continue_stmt(self, stmt: ContinueStmt) -> None:\n        transform_continue_stmt(self.builder, stmt)\n        self.builder.mark_block_unreachable()\n\n    def visit_raise_stmt(self, stmt: RaiseStmt) -> None:\n        transform_raise_stmt(self.builder, stmt)\n        self.builder.mark_block_unreachable()\n\n    def visit_try_stmt(self, stmt: TryStmt) -> None:\n        transform_try_stmt(self.builder, stmt)\n\n    def visit_with_stmt(self, stmt: WithStmt) -> None:\n        transform_with_stmt(self.builder, stmt)\n\n    def visit_pass_stmt(self, stmt: PassStmt) -> None:\n        pass\n\n    def visit_assert_stmt(self, stmt: AssertStmt) -> None:\n        transform_assert_stmt(self.builder, stmt)\n\n    def visit_del_stmt(self, stmt: DelStmt) -> None:\n        transform_del_stmt(self.builder, stmt)\n\n    def visit_global_decl(self, stmt: GlobalDecl) -> None:\n        # Pure declaration -- no runtime effect\n        pass\n\n    def visit_nonlocal_decl(self, stmt: NonlocalDecl) -> None:\n        # Pure declaration -- no runtime effect\n        pass\n\n    def visit_match_stmt(self, stmt: MatchStmt) -> None:\n        transform_match_stmt(self.builder, stmt)\n\n    def visit_type_alias_stmt(self, stmt: TypeAliasStmt) -> None:\n        transform_type_alias_stmt(self.builder, stmt)\n\n    # Expressions\n\n    def visit_name_expr(self, expr: NameExpr) -> Value:\n        return transform_name_expr(self.builder, expr)\n\n    def visit_member_expr(self, expr: MemberExpr) -> Value:\n        return transform_member_expr(self.builder, expr)\n\n    def visit_super_expr(self, expr: SuperExpr) -> Value:\n        return transform_super_expr(self.builder, expr)\n\n    def visit_call_expr(self, expr: CallExpr) -> Value:\n        return transform_call_expr(self.builder, expr)\n\n    def visit_unary_expr(self, expr: UnaryExpr) -> Value:\n        return transform_unary_expr(self.builder, expr)\n\n    def visit_op_expr(self, expr: OpExpr) -> Value:\n        return transform_op_expr(self.builder, expr)\n\n    def visit_index_expr(self, expr: IndexExpr) -> Value:\n        return transform_index_expr(self.builder, expr)\n\n    def visit_conditional_expr(self, expr: ConditionalExpr) -> Value:\n        return transform_conditional_expr(self.builder, expr)\n\n    def visit_comparison_expr(self, expr: ComparisonExpr) -> Value:\n        return transform_comparison_expr(self.builder, expr)\n\n    def visit_int_expr(self, expr: IntExpr) -> Value:\n        return transform_int_expr(self.builder, expr)\n\n    def visit_float_expr(self, expr: FloatExpr) -> Value:\n        return transform_float_expr(self.builder, expr)\n\n    def visit_complex_expr(self, expr: ComplexExpr) -> Value:\n        return transform_complex_expr(self.builder, expr)\n\n    def visit_str_expr(self, expr: StrExpr) -> Value:\n        return transform_str_expr(self.builder, expr)\n\n    def visit_bytes_expr(self, expr: BytesExpr) -> Value:\n        return transform_bytes_expr(self.builder, expr)\n\n    def visit_ellipsis(self, expr: EllipsisExpr) -> Value:\n        return transform_ellipsis(self.builder, expr)\n\n    def visit_list_expr(self, expr: ListExpr) -> Value:\n        return transform_list_expr(self.builder, expr)\n\n    def visit_tuple_expr(self, expr: TupleExpr) -> Value:\n        return transform_tuple_expr(self.builder, expr)\n\n    def visit_dict_expr(self, expr: DictExpr) -> Value:\n        return transform_dict_expr(self.builder, expr)\n\n    def visit_template_str_expr(self, expr: TemplateStrExpr) -> Value:\n        self.bail(\"Template strings are not supported by mypyc\", expr.line)\n\n    def visit_set_expr(self, expr: SetExpr) -> Value:\n        return transform_set_expr(self.builder, expr)\n\n    def visit_list_comprehension(self, expr: ListComprehension) -> Value:\n        return transform_list_comprehension(self.builder, expr)\n\n    def visit_set_comprehension(self, expr: SetComprehension) -> Value:\n        return transform_set_comprehension(self.builder, expr)\n\n    def visit_dictionary_comprehension(self, expr: DictionaryComprehension) -> Value:\n        return transform_dictionary_comprehension(self.builder, expr)\n\n    def visit_slice_expr(self, expr: SliceExpr) -> Value:\n        return transform_slice_expr(self.builder, expr)\n\n    def visit_generator_expr(self, expr: GeneratorExpr) -> Value:\n        return transform_generator_expr(self.builder, expr)\n\n    def visit_lambda_expr(self, expr: LambdaExpr) -> Value:\n        return transform_lambda_expr(self.builder, expr)\n\n    def visit_yield_expr(self, expr: YieldExpr) -> Value:\n        return transform_yield_expr(self.builder, expr)\n\n    def visit_yield_from_expr(self, o: YieldFromExpr) -> Value:\n        return transform_yield_from_expr(self.builder, o)\n\n    def visit_await_expr(self, o: AwaitExpr) -> Value:\n        return transform_await_expr(self.builder, o)\n\n    def visit_assignment_expr(self, o: AssignmentExpr) -> Value:\n        return transform_assignment_expr(self.builder, o)\n\n    # Constructs that shouldn't ever show up\n\n    def visit_enum_call_expr(self, o: EnumCallExpr) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit__promote_expr(self, o: PromoteExpr) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_namedtuple_expr(self, o: NamedTupleExpr) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_newtype_expr(self, o: NewTypeExpr) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_temp_node(self, o: TempNode) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_type_alias_expr(self, o: TypeAliasExpr) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_type_application(self, o: TypeApplication) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_type_var_expr(self, o: TypeVarExpr) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_paramspec_expr(self, o: ParamSpecExpr) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_type_var_tuple_expr(self, o: TypeVarTupleExpr) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_typeddict_expr(self, o: TypedDictExpr) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_reveal_expr(self, o: RevealExpr) -> Value:\n        assert False, \"can't compile analysis-only expressions\"\n\n    def visit_var(self, o: Var) -> None:\n        assert False, \"can't compile Var; should have been handled already?\"\n\n    def visit_cast_expr(self, o: CastExpr) -> Value:\n        assert False, \"CastExpr should have been handled in CallExpr\"\n\n    def visit_type_form_expr(self, o: TypeFormExpr) -> Value:\n        assert False, \"TypeFormExpr should have been handled in CallExpr\"\n\n    def visit_assert_type_expr(self, o: AssertTypeExpr) -> Value:\n        assert False, \"AssertTypeExpr should have been handled in CallExpr\"\n\n    def visit_star_expr(self, o: StarExpr) -> Value:\n        assert False, \"should have been handled in Tuple/List/Set/DictExpr or CallExpr\"\n\n    # Helpers\n\n    def bail(self, msg: str, line: int) -> NoReturn:\n        \"\"\"Reports an error and aborts compilation up until the last accept() call\n\n        (accept() catches the UnsupportedException and keeps on\n        processing. This allows errors to be non-blocking without always\n        needing to write handling for them.\n        \"\"\"\n        self.builder.error(msg, line)\n        raise UnsupportedException()\n"
  },
  {
    "path": "mypyc/irbuild/vtable.py",
    "content": "\"\"\"Compute vtables of native (extension) classes.\"\"\"\n\nfrom __future__ import annotations\n\nimport itertools\n\nfrom mypyc.ir.class_ir import ClassIR, VTableEntries, VTableMethod\nfrom mypyc.sametype import is_same_method_signature\n\n\ndef compute_vtable(cls: ClassIR) -> None:\n    \"\"\"Compute the vtable structure for a class.\"\"\"\n    if cls.vtable is not None:\n        return\n\n    if not cls.is_generated:\n        cls.has_dict = any(x.inherits_python for x in cls.mro)\n\n    for t in cls.mro[1:]:\n        # Make sure all ancestors are processed first\n        compute_vtable(t)\n        # Merge attributes from traits into the class\n        if not t.is_trait:\n            continue\n        for name, typ in t.attributes.items():\n            if not cls.is_trait and not any(name in b.attributes for b in cls.base_mro):\n                cls.attributes[name] = typ\n\n    cls.vtable = {}\n    if cls.base:\n        assert cls.base.vtable is not None\n        cls.vtable.update(cls.base.vtable)\n        cls.vtable_entries = specialize_parent_vtable(cls, cls.base)\n\n    # Include the vtable from the parent classes, but handle method overrides.\n    entries = cls.vtable_entries\n\n    all_traits = [t for t in cls.mro if t.is_trait]\n\n    for t in [cls] + [t for t in all_traits if t is not cls]:\n        for fn in itertools.chain(t.methods.values()):\n            # TODO: don't generate a new entry when we overload without changing the type\n            if fn == cls.get_method(fn.name, prefer_method=True):\n                cls.vtable[fn.name] = len(entries)\n                # If the class contains a glue method referring to itself, that is a\n                # shadow glue method to support interpreted subclasses.\n                shadow = cls.glue_methods.get((cls, fn.name))\n                entries.append(VTableMethod(t, fn.name, fn, shadow))\n\n    # Compute vtables for all of the traits that the class implements\n    if not cls.is_trait:\n        for trait in all_traits:\n            compute_vtable(trait)\n            cls.trait_vtables[trait] = specialize_parent_vtable(cls, trait)\n\n\ndef specialize_parent_vtable(cls: ClassIR, parent: ClassIR) -> VTableEntries:\n    \"\"\"Generate the part of a vtable corresponding to a parent class or trait\"\"\"\n    updated = []\n    for entry in parent.vtable_entries:\n        # Find the original method corresponding to this vtable entry.\n        # (This may not be the method in the entry, if it was overridden.)\n        orig_parent_method = entry.cls.get_method(entry.name, prefer_method=True)\n        assert orig_parent_method\n        method_cls = cls.get_method_and_class(entry.name, prefer_method=True)\n        if method_cls:\n            child_method, defining_cls = method_cls\n            # TODO: emit a wrapper for __init__ that raises or something\n            if (\n                is_same_method_signature(orig_parent_method.sig, child_method.sig)\n                or orig_parent_method.name == \"__init__\"\n            ):\n                entry = VTableMethod(entry.cls, entry.name, child_method, entry.shadow_method)\n            else:\n                entry = VTableMethod(\n                    entry.cls,\n                    entry.name,\n                    defining_cls.glue_methods[(entry.cls, entry.name)],\n                    entry.shadow_method,\n                )\n        updated.append(entry)\n    return updated\n"
  },
  {
    "path": "mypyc/lib-rt/CPy.h",
    "content": "// Mypyc C API\n\n#ifndef CPY_CPY_H\n#define CPY_CPY_H\n\n#include <stdbool.h>\n#include <Python.h>\n#include <frameobject.h>\n#include <structmember.h>\n#include <assert.h>\n#include <stdint.h>\n#include \"pythonsupport.h\"\n#include \"mypyc_util.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n#if 0\n} // why isn't emacs smart enough to not indent this\n#endif\n\n#define CPYTHON_LARGE_INT_ERRMSG \"Python int too large to convert to C ssize_t\"\n\n\n// Naming conventions:\n//\n// Tagged: tagged int\n// Long: tagged long int (pointer)\n// Short: tagged short int (unboxed)\n// Ssize_t: A Py_ssize_t, which ought to be the same width as pointers\n// Object: CPython object (PyObject *)\n\n\n// Tuple type definitions needed for API functions\n\n\n#ifndef MYPYC_DECLARED_tuple_T3OOO\n#define MYPYC_DECLARED_tuple_T3OOO\ntypedef struct tuple_T3OOO {\n    PyObject *f0;\n    PyObject *f1;\n    PyObject *f2;\n} tuple_T3OOO;\n#endif\n\n// Our return tuple wrapper for dictionary iteration helper.\n#ifndef MYPYC_DECLARED_tuple_T3CIO\n#define MYPYC_DECLARED_tuple_T3CIO\ntypedef struct tuple_T3CIO {\n    char f0;  // Should continue?\n    CPyTagged f1;  // Last dict offset\n    PyObject *f2;  // Next dictionary key or value\n} tuple_T3CIO;\n#endif\n\n// Same as above but for both key and value.\n#ifndef MYPYC_DECLARED_tuple_T4CIOO\n#define MYPYC_DECLARED_tuple_T4CIOO\ntypedef struct tuple_T4CIOO {\n    char f0;  // Should continue?\n    CPyTagged f1;  // Last dict offset\n    PyObject *f2;  // Next dictionary key\n    PyObject *f3;  // Next dictionary value\n} tuple_T4CIOO;\n#endif\n\n// System-wide empty tuple constant\nextern PyObject * __mypyc_empty_tuple__;\n\nstatic inline PyObject *CPyTuple_LoadEmptyTupleConstant(void) {\n#if !CPY_3_12_FEATURES\n    Py_INCREF(__mypyc_empty_tuple__);\n#endif\n    return __mypyc_empty_tuple__;\n}\n\n// Native object operations\n\n\n// Search backwards through the trait part of a vtable (which sits *before*\n// the start of the vtable proper) looking for the subvtable describing a trait\n// implementation. We don't do any bounds checking so we'd better be pretty sure\n// we know that it is there.\nstatic inline CPyVTableItem *CPy_FindTraitVtable(PyTypeObject *trait, CPyVTableItem *vtable) {\n    int i;\n    for (i = -3; ; i -= 3) {\n        if ((PyTypeObject *)vtable[i] == trait) {\n            return (CPyVTableItem *)vtable[i + 1];\n        }\n    }\n}\n\n// Use the same logic for offset table.\nstatic inline size_t CPy_FindAttrOffset(PyTypeObject *trait, CPyVTableItem *vtable, size_t index) {\n    int i;\n    for (i = -3; ; i -= 3) {\n        if ((PyTypeObject *)vtable[i] == trait) {\n            return ((size_t *)vtable[i + 2])[index];\n        }\n    }\n}\n\n// Get attribute value using vtable (may return an undefined value)\n#define CPY_GET_ATTR(obj, type, vtable_index, object_type, attr_type)    \\\n    ((attr_type (*)(object_type *))((object_type *)obj)->vtable[vtable_index])((object_type *)obj)\n\n#define CPY_GET_ATTR_TRAIT(obj, trait, vtable_index, object_type, attr_type)   \\\n    ((attr_type (*)(object_type *))(CPy_FindTraitVtable(trait, ((object_type *)obj)->vtable))[vtable_index])((object_type *)obj)\n\n// Set attribute value using vtable\n#define CPY_SET_ATTR(obj, type, vtable_index, value, object_type, attr_type) \\\n    ((bool (*)(object_type *, attr_type))((object_type *)obj)->vtable[vtable_index])( \\\n        (object_type *)obj, value)\n\n#define CPY_SET_ATTR_TRAIT(obj, trait, vtable_index, value, object_type, attr_type) \\\n    ((bool (*)(object_type *, attr_type))(CPy_FindTraitVtable(trait, ((object_type *)obj)->vtable))[vtable_index])( \\\n        (object_type *)obj, value)\n\n#define CPY_GET_METHOD(obj, type, vtable_index, object_type, method_type) \\\n    ((method_type)(((object_type *)obj)->vtable[vtable_index]))\n\n#define CPY_GET_METHOD_TRAIT(obj, trait, vtable_index, object_type, method_type) \\\n    ((method_type)(CPy_FindTraitVtable(trait, ((object_type *)obj)->vtable)[vtable_index]))\n\n\n// Int operations\n\n\nCPyTagged CPyTagged_FromSsize_t(Py_ssize_t value);\nCPyTagged CPyTagged_FromVoidPtr(void *ptr);\nCPyTagged CPyTagged_FromInt64(int64_t value);\nPyObject *CPyTagged_AsObject(CPyTagged x);\nPyObject *CPyTagged_StealAsObject(CPyTagged x);\nPy_ssize_t CPyTagged_AsSsize_t(CPyTagged x);\nvoid CPyTagged_IncRef(CPyTagged x);\nvoid CPyTagged_DecRef(CPyTagged x);\nvoid CPyTagged_XDecRef(CPyTagged x);\n\nbool CPyTagged_IsEq_(CPyTagged left, CPyTagged right);\nbool CPyTagged_IsLt_(CPyTagged left, CPyTagged right);\nCPyTagged CPyTagged_Negate_(CPyTagged num);\nCPyTagged CPyTagged_Invert_(CPyTagged num);\nCPyTagged CPyTagged_Add_(CPyTagged left, CPyTagged right);\nCPyTagged CPyTagged_Subtract_(CPyTagged left, CPyTagged right);\nCPyTagged CPyTagged_Multiply_(CPyTagged left, CPyTagged right);\nCPyTagged CPyTagged_FloorDivide_(CPyTagged left, CPyTagged right);\nCPyTagged CPyTagged_Remainder_(CPyTagged left, CPyTagged right);\nCPyTagged CPyTagged_BitwiseLongOp_(CPyTagged a, CPyTagged b, char op);\nCPyTagged CPyTagged_Rshift_(CPyTagged left, CPyTagged right);\nCPyTagged CPyTagged_Lshift_(CPyTagged left, CPyTagged right);\nCPyTagged CPyTagged_BitLength(CPyTagged self);\nPyObject *CPyTagged_ToBytes(CPyTagged self, Py_ssize_t length, PyObject *byteorder, int signed_flag);\nPyObject *CPyTagged_ToBigEndianBytes(CPyTagged self, Py_ssize_t length, int signed_flag);\nPyObject *CPyTagged_ToLittleEndianBytes(CPyTagged self, Py_ssize_t length, int signed_flag);\n\nPyObject *CPyTagged_Str(CPyTagged n);\nPyObject *CPyTagged_AsciiBytes(CPyTagged n);\nCPyTagged CPyTagged_FromFloat(double f);\nPyObject *CPyLong_FromStrWithBase(PyObject *o, CPyTagged base);\nPyObject *CPyLong_FromStr(PyObject *o);\nPyObject *CPyBool_Str(bool b);\nint64_t CPyLong_AsInt64_(PyObject *o);\nint64_t CPyInt64_Divide(int64_t x, int64_t y);\nint64_t CPyInt64_Remainder(int64_t x, int64_t y);\nint32_t CPyLong_AsInt32_(PyObject *o);\nint32_t CPyInt32_Divide(int32_t x, int32_t y);\nint32_t CPyInt32_Remainder(int32_t x, int32_t y);\nvoid CPyInt32_Overflow(void);\nint16_t CPyLong_AsInt16_(PyObject *o);\nint16_t CPyInt16_Divide(int16_t x, int16_t y);\nint16_t CPyInt16_Remainder(int16_t x, int16_t y);\nvoid CPyInt16_Overflow(void);\nuint8_t CPyLong_AsUInt8_(PyObject *o);\nvoid CPyUInt8_Overflow(void);\ndouble CPyTagged_TrueDivide(CPyTagged x, CPyTagged y);\n\nstatic inline int CPyTagged_CheckLong(CPyTagged x) {\n    return x & CPY_INT_TAG;\n}\n\nstatic inline int CPyTagged_CheckShort(CPyTagged x) {\n    return !CPyTagged_CheckLong(x);\n}\n\nstatic inline void CPyTagged_INCREF(CPyTagged x) {\n    if (unlikely(CPyTagged_CheckLong(x))) {\n        CPyTagged_IncRef(x);\n    }\n}\n\nstatic inline void CPyTagged_DECREF(CPyTagged x) {\n    if (unlikely(CPyTagged_CheckLong(x))) {\n        CPyTagged_DecRef(x);\n    }\n}\n\nstatic inline void CPyTagged_XDECREF(CPyTagged x) {\n    if (unlikely(CPyTagged_CheckLong(x))) {\n        CPyTagged_XDecRef(x);\n    }\n}\n\nstatic inline Py_ssize_t CPyTagged_ShortAsSsize_t(CPyTagged x) {\n    // NOTE: Assume that we sign extend.\n    return (Py_ssize_t)x >> 1;\n}\n\nstatic inline PyObject *CPyTagged_LongAsObject(CPyTagged x) {\n    // NOTE: Assume target is not a short int.\n    return (PyObject *)(x & ~CPY_INT_TAG);\n}\n\nstatic inline CPyTagged CPyTagged_FromObject(PyObject *object) {\n    int overflow;\n    // The overflow check knows about CPyTagged's width\n    Py_ssize_t value = CPyLong_AsSsize_tAndOverflow(object, &overflow);\n    if (unlikely(overflow != 0)) {\n        Py_INCREF(object);\n        return ((CPyTagged)object) | CPY_INT_TAG;\n    } else {\n        return value << 1;\n    }\n}\n\nstatic inline CPyTagged CPyTagged_StealFromObject(PyObject *object) {\n    int overflow;\n    // The overflow check knows about CPyTagged's width\n    Py_ssize_t value = CPyLong_AsSsize_tAndOverflow(object, &overflow);\n    if (unlikely(overflow != 0)) {\n        return ((CPyTagged)object) | CPY_INT_TAG;\n    } else {\n        Py_DECREF(object);\n        return value << 1;\n    }\n}\n\nstatic inline CPyTagged CPyTagged_BorrowFromObject(PyObject *object) {\n    int overflow;\n    // The overflow check knows about CPyTagged's width\n    Py_ssize_t value = CPyLong_AsSsize_tAndOverflow(object, &overflow);\n    if (unlikely(overflow != 0)) {\n        return ((CPyTagged)object) | CPY_INT_TAG;\n    } else {\n        return value << 1;\n    }\n}\n\nstatic inline bool CPyTagged_TooBig(Py_ssize_t value) {\n    // Micro-optimized for the common case where it fits.\n    return (size_t)value > CPY_TAGGED_MAX\n        && (value >= 0 || value < CPY_TAGGED_MIN);\n}\n\nstatic inline bool CPyTagged_TooBigInt64(int64_t value) {\n    // Micro-optimized for the common case where it fits.\n    return (uint64_t)value > CPY_TAGGED_MAX\n        && (value >= 0 || value < CPY_TAGGED_MIN);\n}\n\nstatic inline bool CPyTagged_IsAddOverflow(CPyTagged sum, CPyTagged left, CPyTagged right) {\n    // This check was copied from some of my old code I believe that it works :-)\n    return (Py_ssize_t)(sum ^ left) < 0 && (Py_ssize_t)(sum ^ right) < 0;\n}\n\nstatic inline bool CPyTagged_IsSubtractOverflow(CPyTagged diff, CPyTagged left, CPyTagged right) {\n    // This check was copied from some of my old code I believe that it works :-)\n    return (Py_ssize_t)(diff ^ left) < 0 && (Py_ssize_t)(diff ^ right) >= 0;\n}\n\nstatic inline bool CPyTagged_IsMultiplyOverflow(CPyTagged left, CPyTagged right) {\n    // This is conservative -- return false only in a small number of all non-overflow cases\n    return left >= (1U << (CPY_INT_BITS/2 - 1)) || right >= (1U << (CPY_INT_BITS/2 - 1));\n}\n\nstatic inline bool CPyTagged_MaybeFloorDivideFault(CPyTagged left, CPyTagged right) {\n    return right == 0 || left == -((size_t)1 << (CPY_INT_BITS-1));\n}\n\nstatic inline bool CPyTagged_MaybeRemainderFault(CPyTagged left, CPyTagged right) {\n    // Division/modulus can fault when dividing INT_MIN by -1, but we\n    // do our mods on still-tagged integers with the low-bit clear, so\n    // -1 is actually represented as -2 and can't overflow.\n    // Mod by 0 can still fault though.\n    return right == 0;\n}\n\nstatic inline bool CPyTagged_IsEq(CPyTagged left, CPyTagged right) {\n    if (CPyTagged_CheckShort(left)) {\n        return left == right;\n    } else {\n        return CPyTagged_IsEq_(left, right);\n    }\n}\n\nstatic inline bool CPyTagged_IsNe(CPyTagged left, CPyTagged right) {\n    if (CPyTagged_CheckShort(left)) {\n        return left != right;\n    } else {\n        return !CPyTagged_IsEq_(left, right);\n    }\n}\n\nstatic inline bool CPyTagged_IsLt(CPyTagged left, CPyTagged right) {\n    if (CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right)) {\n        return (Py_ssize_t)left < (Py_ssize_t)right;\n    } else {\n        return CPyTagged_IsLt_(left, right);\n    }\n}\n\nstatic inline bool CPyTagged_IsGe(CPyTagged left, CPyTagged right) {\n    if (CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right)) {\n        return (Py_ssize_t)left >= (Py_ssize_t)right;\n    } else {\n        return !CPyTagged_IsLt_(left, right);\n    }\n}\n\nstatic inline bool CPyTagged_IsGt(CPyTagged left, CPyTagged right) {\n    if (CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right)) {\n        return (Py_ssize_t)left > (Py_ssize_t)right;\n    } else {\n        return CPyTagged_IsLt_(right, left);\n    }\n}\n\nstatic inline bool CPyTagged_IsLe(CPyTagged left, CPyTagged right) {\n    if (CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right)) {\n        return (Py_ssize_t)left <= (Py_ssize_t)right;\n    } else {\n        return !CPyTagged_IsLt_(right, left);\n    }\n}\n\nstatic inline int64_t CPyLong_AsInt64(PyObject *o) {\n    if (likely(PyLong_Check(o))) {\n        PyLongObject *lobj = (PyLongObject *)o;\n    #if CPY_3_12_FEATURES\n        if (likely(PyUnstable_Long_IsCompact(lobj))) {\n            return PyUnstable_Long_CompactValue(lobj);\n        }\n    #else\n        Py_ssize_t size = Py_SIZE(lobj);\n        if (likely(size == 1)) {\n            // Fast path\n            return CPY_LONG_DIGIT(lobj, 0);\n        } else if (likely(size == 0)) {\n            return 0;\n        }\n    #endif\n    }\n    // Slow path\n    return CPyLong_AsInt64_(o);\n}\n\nstatic inline int32_t CPyLong_AsInt32(PyObject *o) {\n    if (likely(PyLong_Check(o))) {\n    #if CPY_3_12_FEATURES\n        PyLongObject *lobj = (PyLongObject *)o;\n        size_t tag = CPY_LONG_TAG(lobj);\n        if (likely(tag == (1 << CPY_NON_SIZE_BITS))) {\n            // Fast path\n            return CPY_LONG_DIGIT(lobj, 0);\n        } else if (likely(tag == CPY_SIGN_ZERO)) {\n            return 0;\n        }\n    #else\n        PyLongObject *lobj = (PyLongObject *)o;\n        Py_ssize_t size = lobj->ob_base.ob_size;\n        if (likely(size == 1)) {\n            // Fast path\n            return CPY_LONG_DIGIT(lobj, 0);\n        } else if (likely(size == 0)) {\n            return 0;\n        }\n    #endif\n    }\n    // Slow path\n    return CPyLong_AsInt32_(o);\n}\n\nstatic inline int16_t CPyLong_AsInt16(PyObject *o) {\n    if (likely(PyLong_Check(o))) {\n    #if CPY_3_12_FEATURES\n        PyLongObject *lobj = (PyLongObject *)o;\n        size_t tag = CPY_LONG_TAG(lobj);\n        if (likely(tag == (1 << CPY_NON_SIZE_BITS))) {\n            // Fast path\n            digit x = CPY_LONG_DIGIT(lobj, 0);\n            if (x < 0x8000)\n                return x;\n        } else if (likely(tag == CPY_SIGN_ZERO)) {\n            return 0;\n        }\n    #else\n        PyLongObject *lobj = (PyLongObject *)o;\n        Py_ssize_t size = lobj->ob_base.ob_size;\n        if (likely(size == 1)) {\n            // Fast path\n            digit x = lobj->ob_digit[0];\n            if (x < 0x8000)\n                return x;\n        } else if (likely(size == 0)) {\n            return 0;\n        }\n    #endif\n    }\n    // Slow path\n    return CPyLong_AsInt16_(o);\n}\n\nstatic inline uint8_t CPyLong_AsUInt8(PyObject *o) {\n    if (likely(PyLong_Check(o))) {\n    #if CPY_3_12_FEATURES\n        PyLongObject *lobj = (PyLongObject *)o;\n        size_t tag = CPY_LONG_TAG(lobj);\n        if (likely(tag == (1 << CPY_NON_SIZE_BITS))) {\n            // Fast path\n            digit x = CPY_LONG_DIGIT(lobj, 0);\n            if (x < 256)\n                return x;\n        } else if (likely(tag == CPY_SIGN_ZERO)) {\n            return 0;\n        }\n    #else\n        PyLongObject *lobj = (PyLongObject *)o;\n        Py_ssize_t size = lobj->ob_base.ob_size;\n        if (likely(size == 1)) {\n            // Fast path\n            digit x = lobj->ob_digit[0];\n            if (x < 256)\n                return x;\n        } else if (likely(size == 0)) {\n            return 0;\n        }\n    #endif\n    }\n    // Slow path\n    return CPyLong_AsUInt8_(o);\n}\n\nstatic inline CPyTagged CPyTagged_Negate(CPyTagged num) {\n    if (likely(CPyTagged_CheckShort(num)\n               && num != (CPyTagged) ((Py_ssize_t)1 << (CPY_INT_BITS - 1)))) {\n        // The only possibility of an overflow error happening when negating a short is if we\n        // attempt to negate the most negative number.\n        return -num;\n    }\n    return CPyTagged_Negate_(num);\n}\n\nstatic inline CPyTagged CPyTagged_Add(CPyTagged left, CPyTagged right) {\n    // TODO: Use clang/gcc extension __builtin_saddll_overflow instead.\n    if (likely(CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right))) {\n        CPyTagged sum = left + right;\n        if (likely(!CPyTagged_IsAddOverflow(sum, left, right))) {\n            return sum;\n        }\n    }\n    return CPyTagged_Add_(left, right);\n}\n\nstatic inline CPyTagged CPyTagged_Subtract(CPyTagged left, CPyTagged right) {\n    // TODO: Use clang/gcc extension __builtin_saddll_overflow instead.\n    if (likely(CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right))) {\n        CPyTagged diff = left - right;\n        if (likely(!CPyTagged_IsSubtractOverflow(diff, left, right))) {\n            return diff;\n        }\n    }\n    return CPyTagged_Subtract_(left, right);\n}\n\nstatic inline CPyTagged CPyTagged_Multiply(CPyTagged left, CPyTagged right) {\n    // TODO: Consider using some clang/gcc extension to check for overflow\n    if (CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right)) {\n        if (!CPyTagged_IsMultiplyOverflow(left, right)) {\n            return left * CPyTagged_ShortAsSsize_t(right);\n        }\n    }\n    return CPyTagged_Multiply_(left, right);\n}\n\nstatic inline CPyTagged CPyTagged_FloorDivide(CPyTagged left, CPyTagged right) {\n    if (CPyTagged_CheckShort(left)\n        && CPyTagged_CheckShort(right)\n        && !CPyTagged_MaybeFloorDivideFault(left, right)) {\n        Py_ssize_t result = CPyTagged_ShortAsSsize_t(left) / CPyTagged_ShortAsSsize_t(right);\n        if (((Py_ssize_t)left < 0) != (((Py_ssize_t)right) < 0)) {\n            if (result * right != left) {\n                // Round down\n                result--;\n            }\n        }\n        return result << 1;\n    }\n    return CPyTagged_FloorDivide_(left, right);\n}\n\nstatic inline CPyTagged CPyTagged_Remainder(CPyTagged left, CPyTagged right) {\n    if (CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right)\n        && !CPyTagged_MaybeRemainderFault(left, right)) {\n        Py_ssize_t result = (Py_ssize_t)left % (Py_ssize_t)right;\n        if (((Py_ssize_t)right < 0) != ((Py_ssize_t)left < 0) && result != 0) {\n            result += right;\n        }\n        return result;\n    }\n    return CPyTagged_Remainder_(left, right);\n}\n\n// Bitwise '~'\nstatic inline CPyTagged CPyTagged_Invert(CPyTagged num) {\n    if (likely(CPyTagged_CheckShort(num) && num != CPY_TAGGED_ABS_MIN)) {\n        return ~num & ~CPY_INT_TAG;\n    }\n    return CPyTagged_Invert_(num);\n}\n\n// Bitwise '&'\nstatic inline CPyTagged CPyTagged_And(CPyTagged left, CPyTagged right) {\n    if (likely(CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right))) {\n        return left & right;\n    }\n    return CPyTagged_BitwiseLongOp_(left, right, '&');\n}\n\n// Bitwise '|'\nstatic inline CPyTagged CPyTagged_Or(CPyTagged left, CPyTagged right) {\n    if (likely(CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right))) {\n        return left | right;\n    }\n    return CPyTagged_BitwiseLongOp_(left, right, '|');\n}\n\n// Bitwise '^'\nstatic inline CPyTagged CPyTagged_Xor(CPyTagged left, CPyTagged right) {\n    if (likely(CPyTagged_CheckShort(left) && CPyTagged_CheckShort(right))) {\n        return left ^ right;\n    }\n    return CPyTagged_BitwiseLongOp_(left, right, '^');\n}\n\n// Bitwise '>>'\nstatic inline CPyTagged CPyTagged_Rshift(CPyTagged left, CPyTagged right) {\n    if (likely(CPyTagged_CheckShort(left)\n               && CPyTagged_CheckShort(right)\n               && (Py_ssize_t)right >= 0)) {\n        CPyTagged count = CPyTagged_ShortAsSsize_t(right);\n        if (unlikely(count >= CPY_INT_BITS)) {\n            if ((Py_ssize_t)left >= 0) {\n                return 0;\n            } else {\n                return CPyTagged_ShortFromInt(-1);\n            }\n        }\n        return ((Py_ssize_t)left >> count) & ~CPY_INT_TAG;\n    }\n    return CPyTagged_Rshift_(left, right);\n}\n\nstatic inline bool IsShortLshiftOverflow(Py_ssize_t short_int, Py_ssize_t shift) {\n    return ((Py_ssize_t)(short_int << shift) >> shift) != short_int;\n}\n\n// Bitwise '<<'\nstatic inline CPyTagged CPyTagged_Lshift(CPyTagged left, CPyTagged right) {\n    if (likely(CPyTagged_CheckShort(left)\n               && CPyTagged_CheckShort(right)\n               && (Py_ssize_t)right >= 0\n               && right < CPY_INT_BITS * 2)) {\n        CPyTagged shift = CPyTagged_ShortAsSsize_t(right);\n        if (!IsShortLshiftOverflow(left, shift))\n            // Short integers, no overflow\n            return left << shift;\n    }\n    return CPyTagged_Lshift_(left, right);\n}\n\n\n// Float operations\n\n\ndouble CPyFloat_FloorDivide(double x, double y);\ndouble CPyFloat_Pow(double x, double y);\ndouble CPyFloat_Sin(double x);\ndouble CPyFloat_Cos(double x);\ndouble CPyFloat_Tan(double x);\ndouble CPyFloat_Sqrt(double x);\ndouble CPyFloat_Exp(double x);\ndouble CPyFloat_Log(double x);\nCPyTagged CPyFloat_Floor(double x);\nCPyTagged CPyFloat_Ceil(double x);\ndouble CPyFloat_FromTagged(CPyTagged x);\nbool CPyFloat_IsInf(double x);\nbool CPyFloat_IsNaN(double x);\n\n\n// Generic operations (that work with arbitrary types)\n\n\n/* We use intentionally non-inlined decrefs in rarely executed code\n * paths since it pretty substantially speeds up compile time. We have\n * our own copies both to avoid the null check in Py_DecRef and to avoid\n * making an indirect PIC call. */\nCPy_NOINLINE\nstatic void CPy_DecRef(PyObject *p) {\n    CPy_DECREF(p);\n}\n\nCPy_NOINLINE\nstatic void CPy_XDecRef(void *p) {\n    CPy_XDECREF((PyObject *)p);\n}\n\nstatic inline CPyTagged CPyObject_Size(PyObject *obj) {\n    Py_ssize_t s = PyObject_Size(obj);\n    if (s < 0) {\n        return CPY_INT_TAG;\n    } else {\n        // Technically __len__ could return a really big number, so we\n        // should allow this to produce a boxed int. In practice it\n        // shouldn't ever if the data structure actually contains all\n        // the elements, but...\n        return CPyTagged_FromSsize_t(s);\n    }\n}\n\n#ifdef MYPYC_LOG_GETATTR\nstatic void CPy_LogGetAttr(const char *method, PyObject *obj, PyObject *attr) {\n    PyObject *module = PyImport_ImportModule(\"getattr_hook\");\n    if (module) {\n        PyObject *res = PyObject_CallMethodObjArgs(module, method, obj, attr, NULL);\n        Py_XDECREF(res);\n        Py_DECREF(module);\n    }\n    PyErr_Clear();\n}\n#else\n#define CPy_LogGetAttr(method, obj, attr) (void)0\n#endif\n\n// Intercept a method call and log it. This needs to be a macro\n// because there is no API that accepts va_args for making a\n// call. Worse, it needs to use the comma operator to return the right\n// value.\n#define CPyObject_CallMethodObjArgs(obj, attr, ...)             \\\n    (CPy_LogGetAttr(\"log_method\", (obj), (attr)),               \\\n     PyObject_CallMethodObjArgs((obj), (attr), __VA_ARGS__))\n\n// This one is a macro for consistency with the above, I guess.\n#define CPyObject_GetAttr(obj, attr)                       \\\n    (CPy_LogGetAttr(\"log\", (obj), (attr)),                 \\\n     PyObject_GetAttr((obj), (attr)))\n\nCPyTagged CPyObject_Hash(PyObject *o);\nPyObject *CPyObject_GetAttr3(PyObject *v, PyObject *name, PyObject *defl);\nPyObject *CPyIter_Next(PyObject *iter);\nPyObject *CPyNumber_Power(PyObject *base, PyObject *index);\nPyObject *CPyNumber_InPlacePower(PyObject *base, PyObject *index);\nPyObject *CPyObject_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end);\n\n\n// List operations\n\n\nPyObject *CPyList_Build(Py_ssize_t len, ...);\nPyObject *CPyList_GetItem(PyObject *list, CPyTagged index);\nPyObject *CPyList_GetItemShort(PyObject *list, CPyTagged index);\nPyObject *CPyList_GetItemBorrow(PyObject *list, CPyTagged index);\nPyObject *CPyList_GetItemShortBorrow(PyObject *list, CPyTagged index);\nPyObject *CPyList_GetItemInt64(PyObject *list, int64_t index);\nPyObject *CPyList_GetItemInt64Borrow(PyObject *list, int64_t index);\nbool CPyList_SetItem(PyObject *list, CPyTagged index, PyObject *value);\nvoid CPyList_SetItemUnsafe(PyObject *list, Py_ssize_t index, PyObject *value);\nbool CPyList_SetItemInt64(PyObject *list, int64_t index, PyObject *value);\nPyObject *CPyList_PopLast(PyObject *obj);\nPyObject *CPyList_Pop(PyObject *obj, CPyTagged index);\nCPyTagged CPyList_Count(PyObject *obj, PyObject *value);\nint CPyList_Insert(PyObject *list, CPyTagged index, PyObject *value);\nPyObject *CPyList_Extend(PyObject *o1, PyObject *o2);\nint CPyList_Remove(PyObject *list, PyObject *obj);\nCPyTagged CPyList_Index(PyObject *list, PyObject *obj);\nPyObject *CPySequence_Sort(PyObject *seq);\nPyObject *CPySequence_Multiply(PyObject *seq, CPyTagged t_size);\nPyObject *CPySequence_RMultiply(CPyTagged t_size, PyObject *seq);\nPyObject *CPySequence_InPlaceMultiply(PyObject *seq, CPyTagged t_size);\nPyObject *CPyList_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end);\nchar CPyList_Clear(PyObject *list);\nPyObject *CPyList_Copy(PyObject *list);\nint CPySequence_Check(PyObject *obj);\n\n\n// Dict operations\n\n\nPyObject *CPyDict_GetItem(PyObject *dict, PyObject *key);\nint CPyDict_SetItem(PyObject *dict, PyObject *key, PyObject *value);\nPyObject *CPyDict_Get(PyObject *dict, PyObject *key, PyObject *fallback);\nPyObject *CPyDict_GetWithNone(PyObject *dict, PyObject *key);\nPyObject *CPyDict_SetDefault(PyObject *dict, PyObject *key, PyObject *value);\nPyObject *CPyDict_SetDefaultWithNone(PyObject *dict, PyObject *key);\nPyObject *CPyDict_SetDefaultWithEmptyDatatype(PyObject *dict, PyObject *key, int data_type);\nPyObject *CPyDict_Build(Py_ssize_t size, ...);\nint CPyDict_Update(PyObject *dict, PyObject *stuff);\nint CPyDict_UpdateInDisplay(PyObject *dict, PyObject *stuff);\nint CPyDict_UpdateFromAny(PyObject *dict, PyObject *stuff);\nPyObject *CPyDict_FromAny(PyObject *obj);\nPyObject *CPyDict_KeysView(PyObject *dict);\nPyObject *CPyDict_ValuesView(PyObject *dict);\nPyObject *CPyDict_ItemsView(PyObject *dict);\nPyObject *CPyDict_Keys(PyObject *dict);\nPyObject *CPyDict_Values(PyObject *dict);\nPyObject *CPyDict_Items(PyObject *dict);\nchar CPyDict_Clear(PyObject *dict);\nPyObject *CPyDict_Copy(PyObject *dict);\nPyObject *CPyDict_GetKeysIter(PyObject *dict);\nPyObject *CPyDict_GetItemsIter(PyObject *dict);\nPyObject *CPyDict_GetValuesIter(PyObject *dict);\ntuple_T3CIO CPyDict_NextKey(PyObject *dict_or_iter, CPyTagged offset);\ntuple_T3CIO CPyDict_NextValue(PyObject *dict_or_iter, CPyTagged offset);\ntuple_T4CIOO CPyDict_NextItem(PyObject *dict_or_iter, CPyTagged offset);\nint CPyMapping_Check(PyObject *obj);\n\n// Check that dictionary didn't change size during iteration.\nstatic inline char CPyDict_CheckSize(PyObject *dict, Py_ssize_t size) {\n    if (!PyDict_CheckExact(dict)) {\n        // Dict subclasses will be checked by Python runtime.\n        return 1;\n    }\n    Py_ssize_t dict_size = PyDict_Size(dict);\n    if (size != dict_size) {\n        PyErr_SetString(PyExc_RuntimeError, \"dictionary changed size during iteration\");\n        return 0;\n    }\n    return 1;\n}\n\n\n// Str operations\n\n// Macros for strip type. These values are copied from CPython.\n#define LEFTSTRIP  0\n#define RIGHTSTRIP 1\n#define BOTHSTRIP  2\n\nchar CPyStr_Equal(PyObject *str1, PyObject *str2);\nchar CPyStr_EqualLiteral(PyObject *str, PyObject *literal_str, Py_ssize_t literal_length);\nPyObject *CPyStr_Build(Py_ssize_t len, ...);\nPyObject *CPyStr_GetItem(PyObject *str, CPyTagged index);\nPyObject *CPyStr_GetItemUnsafe(PyObject *str, Py_ssize_t index);\nCPyTagged CPyStr_Find(PyObject *str, PyObject *substr, CPyTagged start, int direction);\nCPyTagged CPyStr_FindWithEnd(PyObject *str, PyObject *substr, CPyTagged start, CPyTagged end, int direction);\nPyObject *CPyStr_Split(PyObject *str, PyObject *sep, CPyTagged max_split);\nPyObject *CPyStr_RSplit(PyObject *str, PyObject *sep, CPyTagged max_split);\nPyObject *_CPyStr_Strip(PyObject *self, int strip_type, PyObject *sep);\nstatic inline PyObject *CPyStr_Strip(PyObject *self, PyObject *sep) {\n    return _CPyStr_Strip(self, BOTHSTRIP, sep);\n}\nstatic inline PyObject *CPyStr_LStrip(PyObject *self, PyObject *sep) {\n    return _CPyStr_Strip(self, LEFTSTRIP, sep);\n}\nstatic inline PyObject *CPyStr_RStrip(PyObject *self, PyObject *sep) {\n    return _CPyStr_Strip(self, RIGHTSTRIP, sep);\n}\nPyObject *CPyStr_Replace(PyObject *str, PyObject *old_substr, PyObject *new_substr, CPyTagged max_replace);\nPyObject *CPyStr_Append(PyObject *o1, PyObject *o2);\nPyObject *CPyStr_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end);\nint CPyStr_Startswith(PyObject *self, PyObject *subobj);\nint CPyStr_Endswith(PyObject *self, PyObject *subobj);\nPyObject *CPyStr_Removeprefix(PyObject *self, PyObject *prefix);\nPyObject *CPyStr_Removesuffix(PyObject *self, PyObject *suffix);\nbool CPyStr_IsTrue(PyObject *obj);\nPy_ssize_t CPyStr_Size_size_t(PyObject *str);\nPyObject *CPy_Decode(PyObject *obj, PyObject *encoding, PyObject *errors);\nPyObject *CPy_DecodeUTF8(PyObject *bytes);\nPyObject *CPy_DecodeASCII(PyObject *bytes);\nPyObject *CPy_DecodeLatin1(PyObject *bytes);\nPyObject *CPy_Encode(PyObject *obj, PyObject *encoding, PyObject *errors);\nPy_ssize_t CPyStr_Count(PyObject *unicode, PyObject *substring, CPyTagged start);\nPy_ssize_t CPyStr_CountFull(PyObject *unicode, PyObject *substring, CPyTagged start, CPyTagged end);\nCPyTagged CPyStr_Ord(PyObject *obj);\nPyObject *CPyStr_Multiply(PyObject *str, CPyTagged count);\nPyObject *CPyStr_Lower(PyObject *str);\nPyObject *CPyStr_Upper(PyObject *str);\nbool CPyStr_IsSpace(PyObject *str);\nbool CPyStr_IsAlnum(PyObject *str);\nbool CPyStr_IsDigit(PyObject *str);\n\n// Bytes operations\n\n\nPyObject *CPyBytes_Build(Py_ssize_t len, ...);\nPyObject *CPyBytes_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end);\nCPyTagged CPyBytes_GetItem(PyObject *o, CPyTagged index);\nPyObject *CPyBytes_Concat(PyObject *a, PyObject *b);\nPyObject *CPyBytes_Join(PyObject *sep, PyObject *iter);\nCPyTagged CPyBytes_Ord(PyObject *obj);\nPyObject *CPyBytes_Multiply(PyObject *bytes, CPyTagged count);\nint CPyBytes_Startswith(PyObject *self, PyObject *subobj);\nint CPyBytes_Endswith(PyObject *self, PyObject *subobj);\nint CPyBytes_Compare(PyObject *left, PyObject *right);\n\n\n// Set operations\n\n\nbool CPySet_Remove(PyObject *set, PyObject *key);\n\n\n// Tuple operations\n\n\nPyObject *CPySequenceTuple_GetItem(PyObject *tuple, CPyTagged index);\nPyObject *CPySequenceTuple_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end);\nPyObject *CPySequenceTuple_GetItemUnsafe(PyObject *tuple, Py_ssize_t index);\nvoid CPySequenceTuple_SetItemUnsafe(PyObject *tuple, Py_ssize_t index, PyObject *value);\n\n\n// Exception operations\n\n\n// mypyc is not very good at dealing with refcount management of\n// pointers that might be NULL. As a workaround for this, the\n// exception APIs that might want to return NULL pointers instead\n// return properly refcounted pointers to this dummy object.\nstruct ExcDummyStruct { PyObject_HEAD };\nextern struct ExcDummyStruct _CPy_ExcDummyStruct;\nextern PyObject *_CPy_ExcDummy;\n\nstatic inline void _CPy_ToDummy(PyObject **p) {\n    if (*p == NULL) {\n        Py_INCREF(_CPy_ExcDummy);\n        *p = _CPy_ExcDummy;\n    }\n}\n\nstatic inline PyObject *_CPy_FromDummy(PyObject *p) {\n    if (p == _CPy_ExcDummy) return NULL;\n    Py_INCREF(p);\n    return p;\n}\n\nstatic int CPy_NoErrOccurred(void) {\n    return PyErr_Occurred() == NULL;\n}\n\nstatic inline bool CPy_KeepPropagating(void) {\n    return 0;\n}\n// We want to avoid the public PyErr_GetExcInfo API for these because\n// it requires a bunch of spurious refcount traffic on the parts of\n// the triple we don't care about.\n#define CPy_ExcState() PyThreadState_GET()->exc_info\n\nvoid CPy_Raise(PyObject *exc);\nvoid CPy_Reraise(void);\nvoid CPyErr_SetObjectAndTraceback(PyObject *type, PyObject *value, PyObject *traceback);\ntuple_T3OOO CPy_CatchError(void);\nvoid CPy_RestoreExcInfo(tuple_T3OOO info);\nbool CPy_ExceptionMatches(PyObject *type);\nPyObject *CPy_GetExcValue(void);\ntuple_T3OOO CPy_GetExcInfo(void);\nvoid _CPy_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback);\nvoid CPyError_OutOfMemory(void);\nvoid CPy_TypeError(const char *expected, PyObject *value);\nvoid CPy_AddTraceback(const char *filename, const char *funcname, int line, PyObject *globals);\nvoid CPy_TypeErrorTraceback(const char *filename, const char *funcname, int line,\n                            PyObject *globals, const char *expected, PyObject *value);\nvoid CPy_AttributeError(const char *filename, const char *funcname, const char *classname,\n                        const char *attrname, int line, PyObject *globals);\n\n\n// Misc operations\n\n#define CPy_TRASHCAN_BEGIN(op, dealloc) Py_TRASHCAN_BEGIN(op, dealloc)\n#define CPy_TRASHCAN_END(op) Py_TRASHCAN_END\n\n// Tweaked version of _PyArg_Parser in CPython\ntypedef struct CPyArg_Parser {\n    const char *format;\n    const char * const *keywords;\n    const char *fname;\n    const char *custom_msg;\n    int pos;               /* number of positional-only arguments */\n    int min;               /* minimal number of arguments */\n    int max;               /* maximal number of positional arguments */\n    int has_required_kws;  /* are there any keyword-only arguments? */\n    int required_kwonly_start;\n    int varargs;           /* does the function accept *args or **kwargs? */\n    PyObject *kwtuple;     /* tuple of keyword parameter names */\n    struct CPyArg_Parser *next;\n} CPyArg_Parser;\n\n// mypy lets ints silently coerce to floats, so a mypyc runtime float\n// might be an int also\nstatic inline bool CPyFloat_Check(PyObject *o) {\n    return PyFloat_Check(o) || PyLong_Check(o);\n}\n\n// TODO: find an unified way to avoid inline functions in non-C back ends that can not\n//       use inline functions\nstatic inline bool CPy_TypeCheck(PyObject *o, PyObject *type) {\n    return PyObject_TypeCheck(o, (PyTypeObject *)type);\n}\n\nstatic inline PyObject *CPy_TYPE(PyObject *obj) {\n    PyObject *result = (PyObject *)Py_TYPE(obj);\n    Py_INCREF(result);\n    return result;\n}\n\nPyObject *CPy_CalculateMetaclass(PyObject *type, PyObject *o);\nPyObject *CPy_GetCoro(PyObject *obj);\nPyObject *CPyIter_Send(PyObject *iter, PyObject *val);\nint CPy_YieldFromErrorHandle(PyObject *iter, PyObject **outp);\nPyObject *CPy_FetchStopIterationValue(void);\nPyObject *CPyType_FromTemplate(PyObject *template_,\n                               PyObject *orig_bases,\n                               PyObject *modname);\nPyObject *CPyType_FromTemplateWrapper(PyObject *template_,\n                                      PyObject *orig_bases,\n                                      PyObject *modname);\nbool CPy_InitSubclass(PyObject *type);\nint CPyDataclass_SleightOfHand(PyObject *dataclass_dec, PyObject *tp,\n                               PyObject *dict, PyObject *annotations,\n                               PyObject *dataclass_type);\nPyObject *CPyPickle_SetState(PyObject *obj, PyObject *state);\nPyObject *CPyPickle_GetState(PyObject *obj);\nCPyTagged CPyTagged_Id(PyObject *o);\nvoid CPyDebug_Print(const char *msg);\nvoid CPyDebug_PrintObject(PyObject *obj);\nvoid CPy_Init(void);\nint CPyArg_ParseTupleAndKeywords(PyObject *, PyObject *,\n                                 const char *, const char *, const char * const *, ...);\nint CPyArg_ParseStackAndKeywords(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,\n                                 CPyArg_Parser *parser, ...);\nint CPyArg_ParseStackAndKeywordsNoArgs(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,\n                                       CPyArg_Parser *parser, ...);\nint CPyArg_ParseStackAndKeywordsOneArg(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,\n                                       CPyArg_Parser *parser, ...);\nint CPyArg_ParseStackAndKeywordsSimple(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,\n                                       CPyArg_Parser *parser, ...);\n\nint CPySequence_CheckUnpackCount(PyObject *sequence, Py_ssize_t expected);\nint CPyStatics_Initialize(PyObject **statics,\n                          const char * const *strings,\n                          const char * const *bytestrings,\n                          const char * const *ints,\n                          const double *floats,\n                          const double *complex_numbers,\n                          const int *tuples,\n                          const int *frozensets);\nPyObject *CPy_Super(PyObject *builtins, PyObject *self);\nPyObject *CPy_CallReverseOpMethod(PyObject *left, PyObject *right, const char *op,\n                                  PyObject *method);\n\nbool CPyImport_ImportMany(PyObject *modules, CPyModule **statics[], PyObject *globals,\n                          PyObject *tb_path, PyObject *tb_function, Py_ssize_t *tb_lines);\nPyObject *CPyImport_ImportFromMany(PyObject *mod_id, PyObject *names, PyObject *as_names,\n                                   PyObject *globals);\n\nPyObject *CPySingledispatch_RegisterFunction(PyObject *singledispatch_func, PyObject *cls,\n                                             PyObject *func);\n\nPyObject *CPy_GetAIter(PyObject *obj);\nPyObject *CPy_GetANext(PyObject *aiter);\nvoid CPy_SetTypeAliasTypeComputeFunction(PyObject *alias, PyObject *compute_value);\nvoid CPyTrace_LogEvent(const char *location, const char *line, const char *op, const char *details);\n\nstatic inline PyObject *CPyObject_GenericGetAttr(PyObject *self, PyObject *name) {\n    return _PyObject_GenericGetAttrWithDict(self, name, NULL, 1);\n}\nstatic inline int CPyObject_GenericSetAttr(PyObject *self, PyObject *name, PyObject *value) {\n    return _PyObject_GenericSetAttrWithDict(self, name, value, NULL);\n}\n\nPyObject *CPy_SetupObject(PyObject *type);\n\ntypedef struct {\n    PyCMethodObject func;\n\n    PyObject *func_name;\n    PyObject *func_code;\n} CPyFunction;\n\nPyObject* CPyFunction_New(PyObject *module, const char *filename, const char *funcname,\n                          PyCFunction func, int func_flags, const char *func_doc,\n                          int first_line, int code_flags, bool has_self_arg);\nPyObject* CPyFunction_get_name(PyObject *op, void *context);\nint CPyFunction_set_name(PyObject *op, PyObject *value, void *context);\nPyObject* CPyFunction_get_code(PyObject *op, void *context);\nPyObject* CPyFunction_get_defaults(PyObject *op, void *context);\nPyObject* CPyFunction_get_kwdefaults(PyObject *op, void *context);\nPyObject* CPyFunction_get_annotations(PyObject *op, void *context);\nint CPyFunction_set_annotations(PyObject *op, PyObject *value, void *context);\n\n#if CPY_3_11_FEATURES\nPyObject *CPy_GetName(PyObject *obj);\n#endif\n\n#if CPY_3_14_FEATURES\nvoid CPy_SetImmortal(PyObject *obj);\n#endif\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif // CPY_CPY_H\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx/codec.c",
    "content": "#include <stdint.h>\n#include <stddef.h>\n#include <stdlib.h>\n\n#include \"libbase64.h\"\n#include \"../../tables/tables.h\"\n#include \"../../codecs.h\"\n#include \"config.h\"\n#include \"../../env.h\"\n\n#if HAVE_AVX\n#if defined(__clang__)\n#pragma clang attribute push (__attribute__((target(\"avx\"))), apply_to=function)\n#else\n#pragma GCC target(\"avx\")\n#endif\n#include <immintrin.h>\n\n// Only enable inline assembly on supported compilers and on 64-bit CPUs.\n#ifndef BASE64_AVX_USE_ASM\n# if (defined(__GNUC__) || defined(__clang__)) && BASE64_WORDSIZE == 64\n#  define BASE64_AVX_USE_ASM 1\n# else\n#  define BASE64_AVX_USE_ASM 0\n# endif\n#endif\n\n#include \"../ssse3/dec_reshuffle.c\"\n#include \"../ssse3/dec_loop.c\"\n\n#if BASE64_AVX_USE_ASM\n# include \"./enc_loop_asm.c\"\n#else\n# include \"../ssse3/enc_translate.c\"\n# include \"../ssse3/enc_reshuffle.c\"\n# include \"../ssse3/enc_loop.c\"\n#endif\n\n#endif\t// HAVE_AVX\n\nvoid\nbase64_stream_encode_avx BASE64_ENC_PARAMS\n{\n#if HAVE_AVX\n\t#include \"../generic/enc_head.c\"\n\n\t// For supported compilers, use a hand-optimized inline assembly\n\t// encoder. Otherwise fall back on the SSSE3 encoder, but compiled with\n\t// AVX flags to generate better optimized AVX code.\n\n#if BASE64_AVX_USE_ASM\n\tenc_loop_avx(&s, &slen, &o, &olen);\n#else\n\tenc_loop_ssse3(&s, &slen, &o, &olen);\n#endif\n\n\t#include \"../generic/enc_tail.c\"\n#else\n\tbase64_enc_stub(state, src, srclen, out, outlen);\n#endif\n}\n\nint\nbase64_stream_decode_avx BASE64_DEC_PARAMS\n{\n#if HAVE_AVX\n\t#include \"../generic/dec_head.c\"\n\tdec_loop_ssse3(&s, &slen, &o, &olen);\n\t#include \"../generic/dec_tail.c\"\n#if defined(__clang__)\n\t#pragma clang attribute pop\n#endif\n#else\n\treturn base64_dec_stub(state, src, srclen, out, outlen);\n#endif\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx/enc_loop_asm.c",
    "content": "// Apologies in advance for combining the preprocessor with inline assembly,\n// two notoriously gnarly parts of C, but it was necessary to avoid a lot of\n// code repetition. The preprocessor is used to template large sections of\n// inline assembly that differ only in the registers used. If the code was\n// written out by hand, it would become very large and hard to audit.\n\n// Generate a block of inline assembly that loads register R0 from memory. The\n// offset at which the register is loaded is set by the given round.\n#define LOAD(R0, ROUND) \\\n\t\"vlddqu (\"#ROUND\" * 12)(%[src]), %[\"R0\"] \\n\\t\"\n\n// Generate a block of inline assembly that deinterleaves and shuffles register\n// R0 using preloaded constants. Outputs in R0 and R1.\n#define SHUF(R0, R1, R2) \\\n\t\"vpshufb  %[lut0], %[\"R0\"], %[\"R1\"] \\n\\t\" \\\n\t\"vpand    %[\"R1\"], %[msk0], %[\"R2\"] \\n\\t\" \\\n\t\"vpand    %[\"R1\"], %[msk2], %[\"R1\"] \\n\\t\" \\\n\t\"vpmulhuw %[\"R2\"], %[msk1], %[\"R2\"] \\n\\t\" \\\n\t\"vpmullw  %[\"R1\"], %[msk3], %[\"R1\"] \\n\\t\" \\\n\t\"vpor     %[\"R1\"], %[\"R2\"], %[\"R1\"] \\n\\t\"\n\n// Generate a block of inline assembly that takes R0 and R1 and translates\n// their contents to the base64 alphabet, using preloaded constants.\n#define TRAN(R0, R1, R2) \\\n\t\"vpsubusb %[n51],  %[\"R1\"], %[\"R0\"] \\n\\t\" \\\n\t\"vpcmpgtb %[n25],  %[\"R1\"], %[\"R2\"] \\n\\t\" \\\n\t\"vpsubb   %[\"R2\"], %[\"R0\"], %[\"R0\"] \\n\\t\" \\\n\t\"vpshufb  %[\"R0\"], %[lut1], %[\"R2\"] \\n\\t\" \\\n\t\"vpaddb   %[\"R1\"], %[\"R2\"], %[\"R0\"] \\n\\t\"\n\n// Generate a block of inline assembly that stores the given register R0 at an\n// offset set by the given round.\n#define STOR(R0, ROUND) \\\n\t\"vmovdqu %[\"R0\"], (\"#ROUND\" * 16)(%[dst]) \\n\\t\"\n\n// Generate a block of inline assembly that generates a single self-contained\n// encoder round: fetch the data, process it, and store the result. Then update\n// the source and destination pointers.\n#define ROUND() \\\n\tLOAD(\"a\", 0) \\\n\tSHUF(\"a\", \"b\", \"c\") \\\n\tTRAN(\"a\", \"b\", \"c\") \\\n\tSTOR(\"a\", 0) \\\n\t\"add $12, %[src] \\n\\t\" \\\n\t\"add $16, %[dst] \\n\\t\"\n\n// Define a macro that initiates a three-way interleaved encoding round by\n// preloading registers a, b and c from memory.\n// The register graph shows which registers are in use during each step, and\n// is a visual aid for choosing registers for that step. Symbol index:\n//\n//  +  indicates that a register is loaded by that step.\n//  |  indicates that a register is in use and must not be touched.\n//  -  indicates that a register is decommissioned by that step.\n//  x  indicates that a register is used as a temporary by that step.\n//  V  indicates that a register is an input or output to the macro.\n//\n#define ROUND_3_INIT() \t\t\t/*  a b c d e f  */ \\\n\tLOAD(\"a\",   0)\t\t\t/*  +            */ \\\n\tSHUF(\"a\", \"d\", \"e\")\t\t/*  |     + x    */ \\\n\tLOAD(\"b\",   1)\t\t\t/*  | +   |      */ \\\n\tTRAN(\"a\", \"d\", \"e\")\t\t/*  | |   - x    */ \\\n\tLOAD(\"c\",   2)\t\t\t/*  V V V        */\n\n// Define a macro that translates, shuffles and stores the input registers A, B\n// and C, and preloads registers D, E and F for the next round.\n// This macro can be arbitrarily daisy-chained by feeding output registers D, E\n// and F back into the next round as input registers A, B and C. The macro\n// carefully interleaves memory operations with data operations for optimal\n// pipelined performance.\n\n#define ROUND_3(ROUND, A,B,C,D,E,F) \t/*  A B C D E F  */ \\\n\tLOAD(D, (ROUND + 3))\t\t/*  V V V +      */ \\\n\tSHUF(B, E, F)\t\t\t/*  | | | | + x  */ \\\n\tSTOR(A, (ROUND + 0))\t\t/*  - | | | |    */ \\\n\tTRAN(B, E, F)\t\t\t/*    | | | - x  */ \\\n\tLOAD(E, (ROUND + 4))\t\t/*    | | | +    */ \\\n\tSHUF(C, A, F)\t\t\t/*  + | | | | x  */ \\\n\tSTOR(B, (ROUND + 1))\t\t/*  | - | | |    */ \\\n\tTRAN(C, A, F)\t\t\t/*  -   | | | x  */ \\\n\tLOAD(F, (ROUND + 5))\t\t/*      | | | +  */ \\\n\tSHUF(D, A, B)\t\t\t/*  + x | | | |  */ \\\n\tSTOR(C, (ROUND + 2))\t\t/*  |   - | | |  */ \\\n\tTRAN(D, A, B)\t\t\t/*  - x   V V V  */\n\n// Define a macro that terminates a ROUND_3 macro by taking pre-loaded\n// registers D, E and F, and translating, shuffling and storing them.\n#define ROUND_3_END(ROUND, A,B,C,D,E,F)\t/*  A B C D E F  */ \\\n\tSHUF(E, A, B)\t\t\t/*  + x   V V V  */ \\\n\tSTOR(D, (ROUND + 3))\t\t/*  |     - | |  */ \\\n\tTRAN(E, A, B)\t\t\t/*  - x     | |  */ \\\n\tSHUF(F, C, D)\t\t\t/*      + x | |  */ \\\n\tSTOR(E, (ROUND + 4))\t\t/*      |   - |  */ \\\n\tTRAN(F, C, D)\t\t\t/*      - x   |  */ \\\n\tSTOR(F, (ROUND + 5))\t\t/*            -  */\n\n// Define a type A round. Inputs are a, b, and c, outputs are d, e, and f.\n#define ROUND_3_A(ROUND) \\\n\tROUND_3(ROUND, \"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\n\n// Define a type B round. Inputs and outputs are swapped with regard to type A.\n#define ROUND_3_B(ROUND) \\\n\tROUND_3(ROUND, \"d\", \"e\", \"f\", \"a\", \"b\", \"c\")\n\n// Terminating macro for a type A round.\n#define ROUND_3_A_LAST(ROUND) \\\n\tROUND_3_A(ROUND) \\\n\tROUND_3_END(ROUND, \"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\n\n// Terminating macro for a type B round.\n#define ROUND_3_B_LAST(ROUND) \\\n\tROUND_3_B(ROUND) \\\n\tROUND_3_END(ROUND, \"d\", \"e\", \"f\", \"a\", \"b\", \"c\")\n\n// Suppress clang's warning that the literal string in the asm statement is\n// overlong (longer than the ISO-mandated minimum size of 4095 bytes for C99\n// compilers). It may be true, but the goal here is not C99 portability.\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Woverlength-strings\"\n\nstatic inline void\nenc_loop_avx (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\t// For a clearer explanation of the algorithm used by this function,\n\t// please refer to the plain (not inline assembly) implementation. This\n\t// function follows the same basic logic.\n\n\tif (*slen < 16) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 12 bytes at a time. Input is read in blocks of 16\n\t// bytes, so \"reserve\" four bytes from the input buffer to ensure that\n\t// we never read beyond the end of the input buffer.\n\tsize_t rounds = (*slen - 4) / 12;\n\n\t*slen -= rounds * 12;   // 12 bytes consumed per round\n\t*olen += rounds * 16;   // 16 bytes produced per round\n\n\t// Number of times to go through the 36x loop.\n\tsize_t loops = rounds / 36;\n\n\t// Number of rounds remaining after the 36x loop.\n\trounds %= 36;\n\n\t// Lookup tables.\n\tconst __m128i lut0 = _mm_set_epi8(\n\t\t10, 11,  9, 10,  7,  8,  6,  7,  4,  5,  3,  4,  1,  2,  0,  1);\n\n\tconst __m128i lut1 = _mm_setr_epi8(\n\t\t65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0);\n\n\t// Temporary registers.\n\t__m128i a, b, c, d, e, f;\n\n\t__asm__ volatile (\n\n\t\t// If there are 36 rounds or more, enter a 36x unrolled loop of\n\t\t// interleaved encoding rounds. The rounds interleave memory\n\t\t// operations (load/store) with data operations (table lookups,\n\t\t// etc) to maximize pipeline throughput.\n\t\t\"    test %[loops], %[loops] \\n\\t\"\n\t\t\"    jz   18f                \\n\\t\"\n\t\t\"    jmp  36f                \\n\\t\"\n\t\t\"                            \\n\\t\"\n\t\t\".balign 64                  \\n\\t\"\n\t\t\"36: \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A( 0)\n\t\t\"    \" ROUND_3_B( 3)\n\t\t\"    \" ROUND_3_A( 6)\n\t\t\"    \" ROUND_3_B( 9)\n\t\t\"    \" ROUND_3_A(12)\n\t\t\"    \" ROUND_3_B(15)\n\t\t\"    \" ROUND_3_A(18)\n\t\t\"    \" ROUND_3_B(21)\n\t\t\"    \" ROUND_3_A(24)\n\t\t\"    \" ROUND_3_B(27)\n\t\t\"    \" ROUND_3_A_LAST(30)\n\t\t\"    add $(12 * 36), %[src] \\n\\t\"\n\t\t\"    add $(16 * 36), %[dst] \\n\\t\"\n\t\t\"    dec %[loops]           \\n\\t\"\n\t\t\"    jnz 36b                \\n\\t\"\n\n\t\t// Enter an 18x unrolled loop for rounds of 18 or more.\n\t\t\"18: cmp $18, %[rounds] \\n\\t\"\n\t\t\"    jl  9f             \\n\\t\"\n\t\t\"    \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A(0)\n\t\t\"    \" ROUND_3_B(3)\n\t\t\"    \" ROUND_3_A(6)\n\t\t\"    \" ROUND_3_B(9)\n\t\t\"    \" ROUND_3_A_LAST(12)\n\t\t\"    sub $18,        %[rounds] \\n\\t\"\n\t\t\"    add $(12 * 18), %[src]    \\n\\t\"\n\t\t\"    add $(16 * 18), %[dst]    \\n\\t\"\n\n\t\t// Enter a 9x unrolled loop for rounds of 9 or more.\n\t\t\"9:  cmp $9, %[rounds] \\n\\t\"\n\t\t\"    jl  6f            \\n\\t\"\n\t\t\"    \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A(0)\n\t\t\"    \" ROUND_3_B_LAST(3)\n\t\t\"    sub $9,        %[rounds] \\n\\t\"\n\t\t\"    add $(12 * 9), %[src]    \\n\\t\"\n\t\t\"    add $(16 * 9), %[dst]    \\n\\t\"\n\n\t\t// Enter a 6x unrolled loop for rounds of 6 or more.\n\t\t\"6:  cmp $6, %[rounds] \\n\\t\"\n\t\t\"    jl  55f           \\n\\t\"\n\t\t\"    \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A_LAST(0)\n\t\t\"    sub $6,        %[rounds] \\n\\t\"\n\t\t\"    add $(12 * 6), %[src]    \\n\\t\"\n\t\t\"    add $(16 * 6), %[dst]    \\n\\t\"\n\n\t\t// Dispatch the remaining rounds 0..5.\n\t\t\"55: cmp $3, %[rounds] \\n\\t\"\n\t\t\"    jg  45f           \\n\\t\"\n\t\t\"    je  3f            \\n\\t\"\n\t\t\"    cmp $1, %[rounds] \\n\\t\"\n\t\t\"    jg  2f            \\n\\t\"\n\t\t\"    je  1f            \\n\\t\"\n\t\t\"    jmp 0f            \\n\\t\"\n\n\t\t\"45: cmp $4, %[rounds] \\n\\t\"\n\t\t\"    je  4f            \\n\\t\"\n\n\t\t// Block of non-interlaced encoding rounds, which can each\n\t\t// individually be jumped to. Rounds fall through to the next.\n\t\t\"5: \" ROUND()\n\t\t\"4: \" ROUND()\n\t\t\"3: \" ROUND()\n\t\t\"2: \" ROUND()\n\t\t\"1: \" ROUND()\n\t\t\"0: \\n\\t\"\n\n\t\t// Outputs (modified).\n\t\t: [rounds] \"+r\"  (rounds),\n\t\t  [loops]  \"+r\"  (loops),\n\t\t  [src]    \"+r\"  (*s),\n\t\t  [dst]    \"+r\"  (*o),\n\t\t  [a]      \"=&x\" (a),\n\t\t  [b]      \"=&x\" (b),\n\t\t  [c]      \"=&x\" (c),\n\t\t  [d]      \"=&x\" (d),\n\t\t  [e]      \"=&x\" (e),\n\t\t  [f]      \"=&x\" (f)\n\n\t\t// Inputs (not modified).\n\t\t: [lut0] \"x\" (lut0),\n\t\t  [lut1] \"x\" (lut1),\n\t\t  [msk0] \"x\" (_mm_set1_epi32(0x0FC0FC00)),\n\t\t  [msk1] \"x\" (_mm_set1_epi32(0x04000040)),\n\t\t  [msk2] \"x\" (_mm_set1_epi32(0x003F03F0)),\n\t\t  [msk3] \"x\" (_mm_set1_epi32(0x01000010)),\n\t\t  [n51]  \"x\" (_mm_set1_epi8(51)),\n\t\t  [n25]  \"x\" (_mm_set1_epi8(25))\n\n\t\t// Clobbers.\n\t\t: \"cc\", \"memory\"\n\t);\n}\n\n#pragma GCC diagnostic pop\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx2/codec.c",
    "content": "#include <stdint.h>\n#include <stddef.h>\n#include <stdlib.h>\n\n#include \"libbase64.h\"\n#include \"../../tables/tables.h\"\n#include \"../../codecs.h\"\n#include \"config.h\"\n#include \"../../env.h\"\n\n#if HAVE_AVX2\n#if defined(__clang__)\n#pragma clang attribute push (__attribute__((target(\"avx2\"))), apply_to=function)\n#else\n#pragma GCC target(\"avx2\")\n#endif\n#include <immintrin.h>\n\n// Only enable inline assembly on supported compilers and on 64-bit CPUs.\n#ifndef BASE64_AVX2_USE_ASM\n# if (defined(__GNUC__) || defined(__clang__)) && BASE64_WORDSIZE == 64\n#  define BASE64_AVX2_USE_ASM 1\n# else\n#  define BASE64_AVX2_USE_ASM 0\n# endif\n#endif\n\n#include \"./dec_reshuffle.c\"\n#include \"./dec_loop.c\"\n\n#if BASE64_AVX2_USE_ASM\n# include \"./enc_loop_asm.c\"\n#else\n# include \"./enc_translate.c\"\n# include \"./enc_reshuffle.c\"\n# include \"./enc_loop.c\"\n#endif\n\n#endif\t// HAVE_AVX2\n\nvoid\nbase64_stream_encode_avx2 BASE64_ENC_PARAMS\n{\n#if HAVE_AVX2\n\t#include \"../generic/enc_head.c\"\n\tenc_loop_avx2(&s, &slen, &o, &olen);\n\t#include \"../generic/enc_tail.c\"\n#else\n\tbase64_enc_stub(state, src, srclen, out, outlen);\n#endif\n}\n\nint\nbase64_stream_decode_avx2 BASE64_DEC_PARAMS\n{\n#if HAVE_AVX2\n\t#include \"../generic/dec_head.c\"\n\tdec_loop_avx2(&s, &slen, &o, &olen);\n\t#include \"../generic/dec_tail.c\"\n#if defined(__clang__)\n\t#pragma clang attribute pop\n#endif\n#else\n\treturn base64_dec_stub(state, src, srclen, out, outlen);\n#endif\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx2/dec_loop.c",
    "content": "static BASE64_FORCE_INLINE int\ndec_loop_avx2_inner (const uint8_t **s, uint8_t **o, size_t *rounds)\n{\n\tconst __m256i lut_lo = _mm256_setr_epi8(\n\t\t0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,\n\t\t0x11, 0x11, 0x13, 0x1A, 0x1B, 0x1B, 0x1B, 0x1A,\n\t\t0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,\n\t\t0x11, 0x11, 0x13, 0x1A, 0x1B, 0x1B, 0x1B, 0x1A);\n\n\tconst __m256i lut_hi = _mm256_setr_epi8(\n\t\t0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08,\n\t\t0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10,\n\t\t0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08,\n\t\t0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10);\n\n\tconst __m256i lut_roll = _mm256_setr_epi8(\n\t\t0,  16,  19,   4, -65, -65, -71, -71,\n\t\t0,   0,   0,   0,   0,   0,   0,   0,\n\t\t0,  16,  19,   4, -65, -65, -71, -71,\n\t\t0,   0,   0,   0,   0,   0,   0,   0);\n\n\tconst __m256i mask_2F = _mm256_set1_epi8(0x2F);\n\n\t// Load input:\n\t__m256i str = _mm256_loadu_si256((__m256i *) *s);\n\n\t// See the SSSE3 decoder for an explanation of the algorithm.\n\tconst __m256i hi_nibbles = _mm256_and_si256(_mm256_srli_epi32(str, 4), mask_2F);\n\tconst __m256i lo_nibbles = _mm256_and_si256(str, mask_2F);\n\tconst __m256i hi         = _mm256_shuffle_epi8(lut_hi, hi_nibbles);\n\tconst __m256i lo         = _mm256_shuffle_epi8(lut_lo, lo_nibbles);\n\n\tif (!_mm256_testz_si256(lo, hi)) {\n\t\treturn 0;\n\t}\n\n\tconst __m256i eq_2F = _mm256_cmpeq_epi8(str, mask_2F);\n\tconst __m256i roll  = _mm256_shuffle_epi8(lut_roll, _mm256_add_epi8(eq_2F, hi_nibbles));\n\n\t// Now simply add the delta values to the input:\n\tstr = _mm256_add_epi8(str, roll);\n\n\t// Reshuffle the input to packed 12-byte output format:\n\tstr = dec_reshuffle(str);\n\n\t// Store the output:\n\t_mm256_storeu_si256((__m256i *) *o, str);\n\n\t*s += 32;\n\t*o += 24;\n\t*rounds -= 1;\n\n\treturn 1;\n}\n\nstatic inline void\ndec_loop_avx2 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tif (*slen < 45) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 32 bytes per round. Because 8 extra zero bytes are\n\t// written after the output, ensure that there will be at least 13\n\t// bytes of input data left to cover the gap. (11 data bytes and up to\n\t// two end-of-string markers.)\n\tsize_t rounds = (*slen - 13) / 32;\n\n\t*slen -= rounds * 32;\t// 32 bytes consumed per round\n\t*olen += rounds * 24;\t// 24 bytes produced per round\n\n\tdo {\n\t\tif (rounds >= 8) {\n\t\t\tif (dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (rounds >= 4) {\n\t\t\tif (dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (rounds >= 2) {\n\t\t\tif (dec_loop_avx2_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_avx2_inner(s, o, &rounds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdec_loop_avx2_inner(s, o, &rounds);\n\t\tbreak;\n\n\t} while (rounds > 0);\n\n\t// Adjust for any rounds that were skipped:\n\t*slen += rounds * 32;\n\t*olen -= rounds * 24;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx2/dec_reshuffle.c",
    "content": "static BASE64_FORCE_INLINE __m256i\ndec_reshuffle (const __m256i in)\n{\n\t// in, lower lane, bits, upper case are most significant bits, lower\n\t// case are least significant bits:\n\t// 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ\n\t// 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG\n\t// 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD\n\t// 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA\n\n\tconst __m256i merge_ab_and_bc = _mm256_maddubs_epi16(in, _mm256_set1_epi32(0x01400140));\n\t// 0000kkkk LLllllll 0000JJJJ JJjjKKKK\n\t// 0000hhhh IIiiiiii 0000GGGG GGggHHHH\n\t// 0000eeee FFffffff 0000DDDD DDddEEEE\n\t// 0000bbbb CCcccccc 0000AAAA AAaaBBBB\n\n\t__m256i out = _mm256_madd_epi16(merge_ab_and_bc, _mm256_set1_epi32(0x00011000));\n\t// 00000000 JJJJJJjj KKKKkkkk LLllllll\n\t// 00000000 GGGGGGgg HHHHhhhh IIiiiiii\n\t// 00000000 DDDDDDdd EEEEeeee FFffffff\n\t// 00000000 AAAAAAaa BBBBbbbb CCcccccc\n\n\t// Pack bytes together in each lane:\n\tout = _mm256_shuffle_epi8(out, _mm256_setr_epi8(\n\t\t2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1,\n\t\t2, 1, 0, 6, 5, 4, 10, 9, 8, 14, 13, 12, -1, -1, -1, -1));\n\t// 00000000 00000000 00000000 00000000\n\t// LLllllll KKKKkkkk JJJJJJjj IIiiiiii\n\t// HHHHhhhh GGGGGGgg FFffffff EEEEeeee\n\t// DDDDDDdd CCcccccc BBBBbbbb AAAAAAaa\n\n\t// Pack lanes:\n\treturn _mm256_permutevar8x32_epi32(out, _mm256_setr_epi32(0, 1, 2, 4, 5, 6, -1, -1));\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx2/enc_loop.c",
    "content": "static BASE64_FORCE_INLINE void\nenc_loop_avx2_inner_first (const uint8_t **s, uint8_t **o)\n{\n\t// First load is done at s - 0 to not get a segfault:\n\t__m256i src = _mm256_loadu_si256((__m256i *) *s);\n\n\t// Shift by 4 bytes, as required by enc_reshuffle:\n\tsrc = _mm256_permutevar8x32_epi32(src, _mm256_setr_epi32(0, 0, 1, 2, 3, 4, 5, 6));\n\n\t// Reshuffle, translate, store:\n\tsrc = enc_reshuffle(src);\n\tsrc = enc_translate(src);\n\t_mm256_storeu_si256((__m256i *) *o, src);\n\n\t// Subsequent loads will be done at s - 4, set pointer for next round:\n\t*s += 20;\n\t*o += 32;\n}\n\nstatic BASE64_FORCE_INLINE void\nenc_loop_avx2_inner (const uint8_t **s, uint8_t **o)\n{\n\t// Load input:\n\t__m256i src = _mm256_loadu_si256((__m256i *) *s);\n\n\t// Reshuffle, translate, store:\n\tsrc = enc_reshuffle(src);\n\tsrc = enc_translate(src);\n\t_mm256_storeu_si256((__m256i *) *o, src);\n\n\t*s += 24;\n\t*o += 32;\n}\n\nstatic inline void\nenc_loop_avx2 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tif (*slen < 32) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 24 bytes at a time. Because blocks are loaded 32\n\t// bytes at a time an offset of -4, ensure that there will be at least\n\t// 4 remaining bytes after the last round, so that the final read will\n\t// not pass beyond the bounds of the input buffer:\n\tsize_t rounds = (*slen - 4) / 24;\n\n\t*slen -= rounds * 24;   // 24 bytes consumed per round\n\t*olen += rounds * 32;   // 32 bytes produced per round\n\n\t// The first loop iteration requires special handling to ensure that\n\t// the read, which is done at an offset, does not underflow the buffer:\n\tenc_loop_avx2_inner_first(s, o);\n\trounds--;\n\n\twhile (rounds > 0) {\n\t\tif (rounds >= 8) {\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\trounds -= 8;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 4) {\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\trounds -= 4;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 2) {\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\tenc_loop_avx2_inner(s, o);\n\t\t\trounds -= 2;\n\t\t\tcontinue;\n\t\t}\n\t\tenc_loop_avx2_inner(s, o);\n\t\tbreak;\n\t}\n\n\t// Add the offset back:\n\t*s += 4;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx2/enc_loop_asm.c",
    "content": "// Apologies in advance for combining the preprocessor with inline assembly,\n// two notoriously gnarly parts of C, but it was necessary to avoid a lot of\n// code repetition. The preprocessor is used to template large sections of\n// inline assembly that differ only in the registers used. If the code was\n// written out by hand, it would become very large and hard to audit.\n\n// Generate a block of inline assembly that loads register R0 from memory. The\n// offset at which the register is loaded is set by the given round and a\n// constant offset.\n#define LOAD(R0, ROUND, OFFSET) \\\n\t\"vlddqu (\"#ROUND\" * 24 + \"#OFFSET\")(%[src]), %[\"R0\"] \\n\\t\"\n\n// Generate a block of inline assembly that deinterleaves and shuffles register\n// R0 using preloaded constants. Outputs in R0 and R1.\n#define SHUF(R0, R1, R2) \\\n\t\"vpshufb  %[lut0], %[\"R0\"], %[\"R1\"] \\n\\t\" \\\n\t\"vpand    %[\"R1\"], %[msk0], %[\"R2\"] \\n\\t\" \\\n\t\"vpand    %[\"R1\"], %[msk2], %[\"R1\"] \\n\\t\" \\\n\t\"vpmulhuw %[\"R2\"], %[msk1], %[\"R2\"] \\n\\t\" \\\n\t\"vpmullw  %[\"R1\"], %[msk3], %[\"R1\"] \\n\\t\" \\\n\t\"vpor     %[\"R1\"], %[\"R2\"], %[\"R1\"] \\n\\t\"\n\n// Generate a block of inline assembly that takes R0 and R1 and translates\n// their contents to the base64 alphabet, using preloaded constants.\n#define TRAN(R0, R1, R2) \\\n\t\"vpsubusb %[n51],  %[\"R1\"], %[\"R0\"] \\n\\t\" \\\n\t\"vpcmpgtb %[n25],  %[\"R1\"], %[\"R2\"] \\n\\t\" \\\n\t\"vpsubb   %[\"R2\"], %[\"R0\"], %[\"R0\"] \\n\\t\" \\\n\t\"vpshufb  %[\"R0\"], %[lut1], %[\"R2\"] \\n\\t\" \\\n\t\"vpaddb   %[\"R1\"], %[\"R2\"], %[\"R0\"] \\n\\t\"\n\n// Generate a block of inline assembly that stores the given register R0 at an\n// offset set by the given round.\n#define STOR(R0, ROUND) \\\n\t\"vmovdqu %[\"R0\"], (\"#ROUND\" * 32)(%[dst]) \\n\\t\"\n\n// Generate a block of inline assembly that generates a single self-contained\n// encoder round: fetch the data, process it, and store the result. Then update\n// the source and destination pointers.\n#define ROUND() \\\n\tLOAD(\"a\", 0, -4) \\\n\tSHUF(\"a\", \"b\", \"c\") \\\n\tTRAN(\"a\", \"b\", \"c\") \\\n\tSTOR(\"a\", 0) \\\n\t\"add $24, %[src] \\n\\t\" \\\n\t\"add $32, %[dst] \\n\\t\"\n\n// Define a macro that initiates a three-way interleaved encoding round by\n// preloading registers a, b and c from memory.\n// The register graph shows which registers are in use during each step, and\n// is a visual aid for choosing registers for that step. Symbol index:\n//\n//  +  indicates that a register is loaded by that step.\n//  |  indicates that a register is in use and must not be touched.\n//  -  indicates that a register is decommissioned by that step.\n//  x  indicates that a register is used as a temporary by that step.\n//  V  indicates that a register is an input or output to the macro.\n//\n#define ROUND_3_INIT() \t\t\t/*  a b c d e f  */ \\\n\tLOAD(\"a\",   0,  -4)\t\t/*  +            */ \\\n\tSHUF(\"a\", \"d\", \"e\")\t\t/*  |     + x    */ \\\n\tLOAD(\"b\",   1,  -4)\t\t/*  | +   |      */ \\\n\tTRAN(\"a\", \"d\", \"e\")\t\t/*  | |   - x    */ \\\n\tLOAD(\"c\",   2,  -4)\t\t/*  V V V        */\n\n// Define a macro that translates, shuffles and stores the input registers A, B\n// and C, and preloads registers D, E and F for the next round.\n// This macro can be arbitrarily daisy-chained by feeding output registers D, E\n// and F back into the next round as input registers A, B and C. The macro\n// carefully interleaves memory operations with data operations for optimal\n// pipelined performance.\n\n#define ROUND_3(ROUND, A,B,C,D,E,F) \t/*  A B C D E F  */ \\\n\tLOAD(D, (ROUND + 3), -4)\t/*  V V V +      */ \\\n\tSHUF(B, E, F)\t\t\t/*  | | | | + x  */ \\\n\tSTOR(A, (ROUND + 0))\t\t/*  - | | | |    */ \\\n\tTRAN(B, E, F)\t\t\t/*    | | | - x  */ \\\n\tLOAD(E, (ROUND + 4), -4)\t/*    | | | +    */ \\\n\tSHUF(C, A, F)\t\t\t/*  + | | | | x  */ \\\n\tSTOR(B, (ROUND + 1))\t\t/*  | - | | |    */ \\\n\tTRAN(C, A, F)\t\t\t/*  -   | | | x  */ \\\n\tLOAD(F, (ROUND + 5), -4)\t/*      | | | +  */ \\\n\tSHUF(D, A, B)\t\t\t/*  + x | | | |  */ \\\n\tSTOR(C, (ROUND + 2))\t\t/*  |   - | | |  */ \\\n\tTRAN(D, A, B)\t\t\t/*  - x   V V V  */\n\n// Define a macro that terminates a ROUND_3 macro by taking pre-loaded\n// registers D, E and F, and translating, shuffling and storing them.\n#define ROUND_3_END(ROUND, A,B,C,D,E,F)\t/*  A B C D E F  */ \\\n\tSHUF(E, A, B)\t\t\t/*  + x   V V V  */ \\\n\tSTOR(D, (ROUND + 3))\t\t/*  |     - | |  */ \\\n\tTRAN(E, A, B)\t\t\t/*  - x     | |  */ \\\n\tSHUF(F, C, D)\t\t\t/*      + x | |  */ \\\n\tSTOR(E, (ROUND + 4))\t\t/*      |   - |  */ \\\n\tTRAN(F, C, D)\t\t\t/*      - x   |  */ \\\n\tSTOR(F, (ROUND + 5))\t\t/*            -  */\n\n// Define a type A round. Inputs are a, b, and c, outputs are d, e, and f.\n#define ROUND_3_A(ROUND) \\\n\tROUND_3(ROUND, \"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\n\n// Define a type B round. Inputs and outputs are swapped with regard to type A.\n#define ROUND_3_B(ROUND) \\\n\tROUND_3(ROUND, \"d\", \"e\", \"f\", \"a\", \"b\", \"c\")\n\n// Terminating macro for a type A round.\n#define ROUND_3_A_LAST(ROUND) \\\n\tROUND_3_A(ROUND) \\\n\tROUND_3_END(ROUND, \"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\n\n// Terminating macro for a type B round.\n#define ROUND_3_B_LAST(ROUND) \\\n\tROUND_3_B(ROUND) \\\n\tROUND_3_END(ROUND, \"d\", \"e\", \"f\", \"a\", \"b\", \"c\")\n\n// Suppress clang's warning that the literal string in the asm statement is\n// overlong (longer than the ISO-mandated minimum size of 4095 bytes for C99\n// compilers). It may be true, but the goal here is not C99 portability.\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Woverlength-strings\"\n\nstatic inline void\nenc_loop_avx2 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\t// For a clearer explanation of the algorithm used by this function,\n\t// please refer to the plain (not inline assembly) implementation. This\n\t// function follows the same basic logic.\n\n\tif (*slen < 32) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 24 bytes at a time. Because blocks are loaded 32\n\t// bytes at a time an offset of -4, ensure that there will be at least\n\t// 4 remaining bytes after the last round, so that the final read will\n\t// not pass beyond the bounds of the input buffer.\n\tsize_t rounds = (*slen - 4) / 24;\n\n\t*slen -= rounds * 24;   // 24 bytes consumed per round\n\t*olen += rounds * 32;   // 32 bytes produced per round\n\n\t// Pre-decrement the number of rounds to get the number of rounds\n\t// *after* the first round, which is handled as a special case.\n\trounds--;\n\n\t// Number of times to go through the 36x loop.\n\tsize_t loops = rounds / 36;\n\n\t// Number of rounds remaining after the 36x loop.\n\trounds %= 36;\n\n\t// Lookup tables.\n\tconst __m256i lut0 = _mm256_set_epi8(\n\t\t10, 11,  9, 10,  7,  8,  6,  7,  4,  5,  3,  4,  1,  2,  0,  1,\n\t\t14, 15, 13, 14, 11, 12, 10, 11,  8,  9,  7,  8,  5,  6,  4,  5);\n\n\tconst __m256i lut1 = _mm256_setr_epi8(\n\t\t65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0,\n\t\t65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0);\n\n\t// Temporary registers.\n\t__m256i a, b, c, d, e;\n\n\t// Temporary register f doubles as the shift mask for the first round.\n\t__m256i f = _mm256_setr_epi32(0, 0, 1, 2, 3, 4, 5, 6);\n\n\t__asm__ volatile (\n\n\t\t// The first loop iteration requires special handling to ensure\n\t\t// that the read, which is normally done at an offset of -4,\n\t\t// does not underflow the buffer. Load the buffer at an offset\n\t\t// of 0 and permute the input to achieve the same effect.\n\t\tLOAD(\"a\", 0, 0)\n\t\t\"vpermd %[a], %[f], %[a] \\n\\t\"\n\n\t\t// Perform the standard shuffling and translation steps.\n\t\tSHUF(\"a\", \"b\", \"c\")\n\t\tTRAN(\"a\", \"b\", \"c\")\n\n\t\t// Store the result and increment the source and dest pointers.\n\t\t\"vmovdqu %[a], (%[dst]) \\n\\t\"\n\t\t\"add     $24,  %[src]   \\n\\t\"\n\t\t\"add     $32,  %[dst]   \\n\\t\"\n\n\t\t// If there are 36 rounds or more, enter a 36x unrolled loop of\n\t\t// interleaved encoding rounds. The rounds interleave memory\n\t\t// operations (load/store) with data operations (table lookups,\n\t\t// etc) to maximize pipeline throughput.\n\t\t\"    test %[loops], %[loops] \\n\\t\"\n\t\t\"    jz   18f                \\n\\t\"\n\t\t\"    jmp  36f                \\n\\t\"\n\t\t\"                            \\n\\t\"\n\t\t\".balign 64                  \\n\\t\"\n\t\t\"36: \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A( 0)\n\t\t\"    \" ROUND_3_B( 3)\n\t\t\"    \" ROUND_3_A( 6)\n\t\t\"    \" ROUND_3_B( 9)\n\t\t\"    \" ROUND_3_A(12)\n\t\t\"    \" ROUND_3_B(15)\n\t\t\"    \" ROUND_3_A(18)\n\t\t\"    \" ROUND_3_B(21)\n\t\t\"    \" ROUND_3_A(24)\n\t\t\"    \" ROUND_3_B(27)\n\t\t\"    \" ROUND_3_A_LAST(30)\n\t\t\"    add $(24 * 36), %[src] \\n\\t\"\n\t\t\"    add $(32 * 36), %[dst] \\n\\t\"\n\t\t\"    dec %[loops]           \\n\\t\"\n\t\t\"    jnz 36b                \\n\\t\"\n\n\t\t// Enter an 18x unrolled loop for rounds of 18 or more.\n\t\t\"18: cmp $18, %[rounds] \\n\\t\"\n\t\t\"    jl  9f             \\n\\t\"\n\t\t\"    \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A(0)\n\t\t\"    \" ROUND_3_B(3)\n\t\t\"    \" ROUND_3_A(6)\n\t\t\"    \" ROUND_3_B(9)\n\t\t\"    \" ROUND_3_A_LAST(12)\n\t\t\"    sub $18,        %[rounds] \\n\\t\"\n\t\t\"    add $(24 * 18), %[src]    \\n\\t\"\n\t\t\"    add $(32 * 18), %[dst]    \\n\\t\"\n\n\t\t// Enter a 9x unrolled loop for rounds of 9 or more.\n\t\t\"9:  cmp $9, %[rounds] \\n\\t\"\n\t\t\"    jl  6f            \\n\\t\"\n\t\t\"    \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A(0)\n\t\t\"    \" ROUND_3_B_LAST(3)\n\t\t\"    sub $9,        %[rounds] \\n\\t\"\n\t\t\"    add $(24 * 9), %[src]    \\n\\t\"\n\t\t\"    add $(32 * 9), %[dst]    \\n\\t\"\n\n\t\t// Enter a 6x unrolled loop for rounds of 6 or more.\n\t\t\"6:  cmp $6, %[rounds] \\n\\t\"\n\t\t\"    jl  55f           \\n\\t\"\n\t\t\"    \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A_LAST(0)\n\t\t\"    sub $6,        %[rounds] \\n\\t\"\n\t\t\"    add $(24 * 6), %[src]    \\n\\t\"\n\t\t\"    add $(32 * 6), %[dst]    \\n\\t\"\n\n\t\t// Dispatch the remaining rounds 0..5.\n\t\t\"55: cmp $3, %[rounds] \\n\\t\"\n\t\t\"    jg  45f           \\n\\t\"\n\t\t\"    je  3f            \\n\\t\"\n\t\t\"    cmp $1, %[rounds] \\n\\t\"\n\t\t\"    jg  2f            \\n\\t\"\n\t\t\"    je  1f            \\n\\t\"\n\t\t\"    jmp 0f            \\n\\t\"\n\n\t\t\"45: cmp $4, %[rounds] \\n\\t\"\n\t\t\"    je  4f            \\n\\t\"\n\n\t\t// Block of non-interlaced encoding rounds, which can each\n\t\t// individually be jumped to. Rounds fall through to the next.\n\t\t\"5: \" ROUND()\n\t\t\"4: \" ROUND()\n\t\t\"3: \" ROUND()\n\t\t\"2: \" ROUND()\n\t\t\"1: \" ROUND()\n\t\t\"0: \\n\\t\"\n\n\t\t// Outputs (modified).\n\t\t: [rounds] \"+r\"  (rounds),\n\t\t  [loops]  \"+r\"  (loops),\n\t\t  [src]    \"+r\"  (*s),\n\t\t  [dst]    \"+r\"  (*o),\n\t\t  [a]      \"=&x\" (a),\n\t\t  [b]      \"=&x\" (b),\n\t\t  [c]      \"=&x\" (c),\n\t\t  [d]      \"=&x\" (d),\n\t\t  [e]      \"=&x\" (e),\n\t\t  [f]      \"+x\"  (f)\n\n\t\t// Inputs (not modified).\n\t\t: [lut0] \"x\" (lut0),\n\t\t  [lut1] \"x\" (lut1),\n\t\t  [msk0] \"x\" (_mm256_set1_epi32(0x0FC0FC00)),\n\t\t  [msk1] \"x\" (_mm256_set1_epi32(0x04000040)),\n\t\t  [msk2] \"x\" (_mm256_set1_epi32(0x003F03F0)),\n\t\t  [msk3] \"x\" (_mm256_set1_epi32(0x01000010)),\n\t\t  [n51]  \"x\" (_mm256_set1_epi8(51)),\n\t\t  [n25]  \"x\" (_mm256_set1_epi8(25))\n\n\t\t// Clobbers.\n\t\t: \"cc\", \"memory\"\n\t);\n}\n\n#pragma GCC diagnostic pop\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx2/enc_reshuffle.c",
    "content": "static BASE64_FORCE_INLINE __m256i\nenc_reshuffle (const __m256i input)\n{\n\t// Translation of the SSSE3 reshuffling algorithm to AVX2. This one\n\t// works with shifted (4 bytes) input in order to be able to work\n\t// efficiently in the two 128-bit lanes.\n\n\t// Input, bytes MSB to LSB:\n\t// 0 0 0 0 x w v u t s r q p o n m\n\t// l k j i h g f e d c b a 0 0 0 0\n\n\tconst __m256i in = _mm256_shuffle_epi8(input, _mm256_set_epi8(\n\t\t10, 11,  9, 10,\n\t\t 7,  8,  6,  7,\n\t\t 4,  5,  3,  4,\n\t\t 1,  2,  0,  1,\n\n\t\t14, 15, 13, 14,\n\t\t11, 12, 10, 11,\n\t\t 8,  9,  7,  8,\n\t\t 5,  6,  4,  5));\n\t// in, bytes MSB to LSB:\n\t// w x v w\n\t// t u s t\n\t// q r p q\n\t// n o m n\n\t// k l j k\n\t// h i g h\n\t// e f d e\n\t// b c a b\n\n\tconst __m256i t0 = _mm256_and_si256(in, _mm256_set1_epi32(0x0FC0FC00));\n\t// bits, upper case are most significant bits, lower case are least\n\t// significant bits.\n\t// 0000wwww XX000000 VVVVVV00 00000000\n\t// 0000tttt UU000000 SSSSSS00 00000000\n\t// 0000qqqq RR000000 PPPPPP00 00000000\n\t// 0000nnnn OO000000 MMMMMM00 00000000\n\t// 0000kkkk LL000000 JJJJJJ00 00000000\n\t// 0000hhhh II000000 GGGGGG00 00000000\n\t// 0000eeee FF000000 DDDDDD00 00000000\n\t// 0000bbbb CC000000 AAAAAA00 00000000\n\n\tconst __m256i t1 = _mm256_mulhi_epu16(t0, _mm256_set1_epi32(0x04000040));\n\t// 00000000 00wwwwXX 00000000 00VVVVVV\n\t// 00000000 00ttttUU 00000000 00SSSSSS\n\t// 00000000 00qqqqRR 00000000 00PPPPPP\n\t// 00000000 00nnnnOO 00000000 00MMMMMM\n\t// 00000000 00kkkkLL 00000000 00JJJJJJ\n\t// 00000000 00hhhhII 00000000 00GGGGGG\n\t// 00000000 00eeeeFF 00000000 00DDDDDD\n\t// 00000000 00bbbbCC 00000000 00AAAAAA\n\n\tconst __m256i t2 = _mm256_and_si256(in, _mm256_set1_epi32(0x003F03F0));\n\t// 00000000 00xxxxxx 000000vv WWWW0000\n\t// 00000000 00uuuuuu 000000ss TTTT0000\n\t// 00000000 00rrrrrr 000000pp QQQQ0000\n\t// 00000000 00oooooo 000000mm NNNN0000\n\t// 00000000 00llllll 000000jj KKKK0000\n\t// 00000000 00iiiiii 000000gg HHHH0000\n\t// 00000000 00ffffff 000000dd EEEE0000\n\t// 00000000 00cccccc 000000aa BBBB0000\n\n\tconst __m256i t3 = _mm256_mullo_epi16(t2, _mm256_set1_epi32(0x01000010));\n\t// 00xxxxxx 00000000 00vvWWWW 00000000\n\t// 00uuuuuu 00000000 00ssTTTT 00000000\n\t// 00rrrrrr 00000000 00ppQQQQ 00000000\n\t// 00oooooo 00000000 00mmNNNN 00000000\n\t// 00llllll 00000000 00jjKKKK 00000000\n\t// 00iiiiii 00000000 00ggHHHH 00000000\n\t// 00ffffff 00000000 00ddEEEE 00000000\n\t// 00cccccc 00000000 00aaBBBB 00000000\n\n\treturn _mm256_or_si256(t1, t3);\n\t// 00xxxxxx 00wwwwXX 00vvWWWW 00VVVVVV\n\t// 00uuuuuu 00ttttUU 00ssTTTT 00SSSSSS\n\t// 00rrrrrr 00qqqqRR 00ppQQQQ 00PPPPPP\n\t// 00oooooo 00nnnnOO 00mmNNNN 00MMMMMM\n\t// 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ\n\t// 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG\n\t// 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD\n\t// 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx2/enc_translate.c",
    "content": "static BASE64_FORCE_INLINE __m256i\nenc_translate (const __m256i in)\n{\n\t// A lookup table containing the absolute offsets for all ranges:\n\tconst __m256i lut = _mm256_setr_epi8(\n\t\t65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0,\n\t\t65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0);\n\n\t// Translate values 0..63 to the Base64 alphabet. There are five sets:\n\t// #  From      To         Abs    Index  Characters\n\t// 0  [0..25]   [65..90]   +65        0  ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t// 1  [26..51]  [97..122]  +71        1  abcdefghijklmnopqrstuvwxyz\n\t// 2  [52..61]  [48..57]    -4  [2..11]  0123456789\n\t// 3  [62]      [43]       -19       12  +\n\t// 4  [63]      [47]       -16       13  /\n\n\t// Create LUT indices from the input. The index for range #0 is right,\n\t// others are 1 less than expected:\n\t__m256i indices = _mm256_subs_epu8(in, _mm256_set1_epi8(51));\n\n\t// mask is 0xFF (-1) for range #[1..4] and 0x00 for range #0:\n\tconst __m256i mask = _mm256_cmpgt_epi8(in, _mm256_set1_epi8(25));\n\n\t// Subtract -1, so add 1 to indices for range #[1..4]. All indices are\n\t// now correct:\n\tindices = _mm256_sub_epi8(indices, mask);\n\n\t// Add offsets to input values:\n\treturn _mm256_add_epi8(in, _mm256_shuffle_epi8(lut, indices));\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx512/codec.c",
    "content": "#include <stdint.h>\n#include <stddef.h>\n#include <stdlib.h>\n\n#include \"libbase64.h\"\n#include \"../../tables/tables.h\"\n#include \"../../codecs.h\"\n#include \"config.h\"\n#include \"../../env.h\"\n\n#if HAVE_AVX512\n#if defined(__clang__)\n#pragma clang attribute push (__attribute__((target(\"avx512vbmi\"))), apply_to=function)\n#else\n#pragma GCC target(\"avx512vbmi\")\n#endif\n#include <immintrin.h>\n\n#include \"../avx2/dec_reshuffle.c\"\n#include \"../avx2/dec_loop.c\"\n#include \"enc_reshuffle_translate.c\"\n#include \"enc_loop.c\"\n\n#endif\t// HAVE_AVX512\n\nvoid\nbase64_stream_encode_avx512 BASE64_ENC_PARAMS\n{\n#if HAVE_AVX512\n\t#include \"../generic/enc_head.c\"\n\tenc_loop_avx512(&s, &slen, &o, &olen);\n\t#include \"../generic/enc_tail.c\"\n#else\n\tbase64_enc_stub(state, src, srclen, out, outlen);\n#endif\n}\n\n// Reuse AVX2 decoding. Not supporting AVX512 at present\nint\nbase64_stream_decode_avx512 BASE64_DEC_PARAMS\n{\n#if HAVE_AVX512\n\t#include \"../generic/dec_head.c\"\n\tdec_loop_avx2(&s, &slen, &o, &olen);\n\t#include \"../generic/dec_tail.c\"\n#if defined(__clang__)\n\t#pragma clang attribute pop\n#endif\n#else\n\treturn base64_dec_stub(state, src, srclen, out, outlen);\n#endif\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx512/enc_loop.c",
    "content": "static BASE64_FORCE_INLINE void\nenc_loop_avx512_inner (const uint8_t **s, uint8_t **o)\n{\n\t// Load input.\n\t__m512i src = _mm512_loadu_si512((__m512i *) *s);\n\n\t// Reshuffle, translate, store.\n\tsrc = enc_reshuffle_translate(src);\n\t_mm512_storeu_si512((__m512i *) *o, src);\n\n\t*s += 48;\n\t*o += 64;\n}\n\nstatic inline void\nenc_loop_avx512 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tif (*slen < 64) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 48 bytes at a time. Because blocks are loaded 64\n\t// bytes at a time, ensure that there will be at least 24 remaining\n\t// bytes after the last round, so that the final read will not pass\n\t// beyond the bounds of the input buffer.\n\tsize_t rounds = (*slen - 24) / 48;\n\n\t*slen -= rounds * 48;   // 48 bytes consumed per round\n\t*olen += rounds * 64;   // 64 bytes produced per round\n\n\twhile (rounds > 0) {\n\t\tif (rounds >= 8) {\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\trounds -= 8;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 4) {\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\trounds -= 4;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 2) {\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\tenc_loop_avx512_inner(s, o);\n\t\t\trounds -= 2;\n\t\t\tcontinue;\n\t\t}\n\t\tenc_loop_avx512_inner(s, o);\n\t\tbreak;\n\t}\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/avx512/enc_reshuffle_translate.c",
    "content": "// AVX512 algorithm is based on permutevar and multishift. The code is based on\n// https://github.com/WojciechMula/base64simd which is under BSD-2 license.\n\nstatic BASE64_FORCE_INLINE __m512i\nenc_reshuffle_translate (const __m512i input)\n{\n\t// 32-bit input\n\t// [ 0  0  0  0  0  0  0  0|c1 c0 d5 d4 d3 d2 d1 d0|\n\t//  b3 b2 b1 b0 c5 c4 c3 c2|a5 a4 a3 a2 a1 a0 b5 b4]\n\t// output order  [1, 2, 0, 1]\n\t// [b3 b2 b1 b0 c5 c4 c3 c2|c1 c0 d5 d4 d3 d2 d1 d0|\n\t//  a5 a4 a3 a2 a1 a0 b5 b4|b3 b2 b1 b0 c3 c2 c1 c0]\n\n\tconst __m512i shuffle_input = _mm512_setr_epi32(0x01020001,\n\t                                                0x04050304,\n\t                                                0x07080607,\n\t                                                0x0a0b090a,\n\t                                                0x0d0e0c0d,\n\t                                                0x10110f10,\n\t                                                0x13141213,\n\t                                                0x16171516,\n\t                                                0x191a1819,\n\t                                                0x1c1d1b1c,\n\t                                                0x1f201e1f,\n\t                                                0x22232122,\n\t                                                0x25262425,\n\t                                                0x28292728,\n\t                                                0x2b2c2a2b,\n\t                                                0x2e2f2d2e);\n\n\t// Reorder bytes\n\t// [b3 b2 b1 b0 c5 c4 c3 c2|c1 c0 d5 d4 d3 d2 d1 d0|\n\t//  a5 a4 a3 a2 a1 a0 b5 b4|b3 b2 b1 b0 c3 c2 c1 c0]\n\tconst __m512i in = _mm512_permutexvar_epi8(shuffle_input, input);\n\n\t// After multishift a single 32-bit lane has following layout\n\t// [c1 c0 d5 d4 d3 d2 d1 d0|b1 b0 c5 c4 c3 c2 c1 c0|\n\t//  a1 a0 b5 b4 b3 b2 b1 b0|d1 d0 a5 a4 a3 a2 a1 a0]\n\t// (a = [10:17], b = [4:11], c = [22:27], d = [16:21])\n\n\t// 48, 54, 36, 42, 16, 22, 4, 10\n\tconst __m512i shifts = _mm512_set1_epi64(0x3036242a1016040alu);\n\t__m512i shuffled_in = _mm512_multishift_epi64_epi8(shifts, in);\n\n\t// Translate immediately after reshuffled.\n\tconst __m512i lookup = _mm512_loadu_si512(base64_table_enc_6bit);\n\n\t// Translation 6-bit values to ASCII.\n\treturn _mm512_permutexvar_epi8(shuffled_in, lookup);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/generic/32/dec_loop.c",
    "content": "static BASE64_FORCE_INLINE int\ndec_loop_generic_32_inner (const uint8_t **s, uint8_t **o, size_t *rounds)\n{\n\tconst uint32_t str\n\t\t= base64_table_dec_32bit_d0[(*s)[0]]\n\t\t| base64_table_dec_32bit_d1[(*s)[1]]\n\t\t| base64_table_dec_32bit_d2[(*s)[2]]\n\t\t| base64_table_dec_32bit_d3[(*s)[3]];\n\n#if BASE64_LITTLE_ENDIAN\n\n\t// LUTs for little-endian set MSB in case of invalid character:\n\tif (str & UINT32_C(0x80000000)) {\n\t\treturn 0;\n\t}\n#else\n\t// LUTs for big-endian set LSB in case of invalid character:\n\tif (str & UINT32_C(1)) {\n\t\treturn 0;\n\t}\n#endif\n\t// Store the output:\n\tmemcpy(*o, &str, sizeof (str));\n\n\t*s += 4;\n\t*o += 3;\n\t*rounds -= 1;\n\n\treturn 1;\n}\n\nstatic inline void\ndec_loop_generic_32 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tif (*slen < 8) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 4 bytes per round. Because one extra zero byte is\n\t// written after the output, ensure that there will be at least 4 bytes\n\t// of input data left to cover the gap. (Two data bytes and up to two\n\t// end-of-string markers.)\n\tsize_t rounds = (*slen - 4) / 4;\n\n\t*slen -= rounds * 4;\t// 4 bytes consumed per round\n\t*olen += rounds * 3;\t// 3 bytes produced per round\n\n\tdo {\n\t\tif (rounds >= 8) {\n\t\t\tif (dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (rounds >= 4) {\n\t\t\tif (dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (rounds >= 2) {\n\t\t\tif (dec_loop_generic_32_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_generic_32_inner(s, o, &rounds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdec_loop_generic_32_inner(s, o, &rounds);\n\t\tbreak;\n\n\t} while (rounds > 0);\n\n\t// Adjust for any rounds that were skipped:\n\t*slen += rounds * 4;\n\t*olen -= rounds * 3;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/generic/32/enc_loop.c",
    "content": "static BASE64_FORCE_INLINE void\nenc_loop_generic_32_inner (const uint8_t **s, uint8_t **o)\n{\n\tuint32_t src;\n\n\t// Load input:\n\tmemcpy(&src, *s, sizeof (src));\n\n\t// Reorder to 32-bit big-endian, if not already in that format. The\n\t// workset must be in big-endian, otherwise the shifted bits do not\n\t// carry over properly among adjacent bytes:\n\tsrc = BASE64_HTOBE32(src);\n\n\t// Two indices for the 12-bit lookup table:\n\tconst size_t index0 = (src >> 20) & 0xFFFU;\n\tconst size_t index1 = (src >>  8) & 0xFFFU;\n\n\t// Table lookup and store:\n\tmemcpy(*o + 0, base64_table_enc_12bit + index0, 2);\n\tmemcpy(*o + 2, base64_table_enc_12bit + index1, 2);\n\n\t*s += 3;\n\t*o += 4;\n}\n\nstatic inline void\nenc_loop_generic_32 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tif (*slen < 4) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 3 bytes at a time. Because blocks are loaded 4\n\t// bytes at a time, ensure that there will be at least one remaining\n\t// byte after the last round, so that the final read will not pass\n\t// beyond the bounds of the input buffer:\n\tsize_t rounds = (*slen - 1) / 3;\n\n\t*slen -= rounds * 3;\t// 3 bytes consumed per round\n\t*olen += rounds * 4;\t// 4 bytes produced per round\n\n\tdo {\n\t\tif (rounds >= 8) {\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\trounds -= 8;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 4) {\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\trounds -= 4;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 2) {\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\tenc_loop_generic_32_inner(s, o);\n\t\t\trounds -= 2;\n\t\t\tcontinue;\n\t\t}\n\t\tenc_loop_generic_32_inner(s, o);\n\t\tbreak;\n\n\t} while (rounds > 0);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/generic/64/enc_loop.c",
    "content": "static BASE64_FORCE_INLINE void\nenc_loop_generic_64_inner (const uint8_t **s, uint8_t **o)\n{\n\tuint64_t src;\n\n\t// Load input:\n\tmemcpy(&src, *s, sizeof (src));\n\n\t// Reorder to 64-bit big-endian, if not already in that format. The\n\t// workset must be in big-endian, otherwise the shifted bits do not\n\t// carry over properly among adjacent bytes:\n\tsrc = BASE64_HTOBE64(src);\n\n\t// Four indices for the 12-bit lookup table:\n\tconst size_t index0 = (src >> 52) & 0xFFFU;\n\tconst size_t index1 = (src >> 40) & 0xFFFU;\n\tconst size_t index2 = (src >> 28) & 0xFFFU;\n\tconst size_t index3 = (src >> 16) & 0xFFFU;\n\n\t// Table lookup and store:\n\tmemcpy(*o + 0, base64_table_enc_12bit + index0, 2);\n\tmemcpy(*o + 2, base64_table_enc_12bit + index1, 2);\n\tmemcpy(*o + 4, base64_table_enc_12bit + index2, 2);\n\tmemcpy(*o + 6, base64_table_enc_12bit + index3, 2);\n\n\t*s += 6;\n\t*o += 8;\n}\n\nstatic inline void\nenc_loop_generic_64 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tif (*slen < 8) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 6 bytes at a time. Because blocks are loaded 8\n\t// bytes at a time, ensure that there will be at least 2 remaining\n\t// bytes after the last round, so that the final read will not pass\n\t// beyond the bounds of the input buffer:\n\tsize_t rounds = (*slen - 2) / 6;\n\n\t*slen -= rounds * 6;\t// 6 bytes consumed per round\n\t*olen += rounds * 8;\t// 8 bytes produced per round\n\n\tdo {\n\t\tif (rounds >= 8) {\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\trounds -= 8;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 4) {\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\trounds -= 4;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 2) {\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\tenc_loop_generic_64_inner(s, o);\n\t\t\trounds -= 2;\n\t\t\tcontinue;\n\t\t}\n\t\tenc_loop_generic_64_inner(s, o);\n\t\tbreak;\n\n\t} while (rounds > 0);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/generic/codec.c",
    "content": "#include <stdint.h>\n#include <stddef.h>\n#include <string.h>\n\n#include \"libbase64.h\"\n#include \"../../tables/tables.h\"\n#include \"../../codecs.h\"\n#include \"config.h\"\n#include \"../../env.h\"\n\n#if BASE64_WORDSIZE == 32\n#  include \"32/enc_loop.c\"\n#elif BASE64_WORDSIZE == 64\n#  include \"64/enc_loop.c\"\n#endif\n\n#if BASE64_WORDSIZE >= 32\n#  include \"32/dec_loop.c\"\n#endif\n\nvoid\nbase64_stream_encode_plain BASE64_ENC_PARAMS\n{\n\t#include \"enc_head.c\"\n#if BASE64_WORDSIZE == 32\n\tenc_loop_generic_32(&s, &slen, &o, &olen);\n#elif BASE64_WORDSIZE == 64\n\tenc_loop_generic_64(&s, &slen, &o, &olen);\n#endif\n\t#include \"enc_tail.c\"\n}\n\nint\nbase64_stream_decode_plain BASE64_DEC_PARAMS\n{\n\t#include \"dec_head.c\"\n#if BASE64_WORDSIZE >= 32\n\tdec_loop_generic_32(&s, &slen, &o, &olen);\n#endif\n\t#include \"dec_tail.c\"\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/generic/dec_head.c",
    "content": "int ret = 0;\nconst uint8_t *s = (const uint8_t *) src;\nuint8_t *o = (uint8_t *) out;\nuint8_t q;\n\n// Use local temporaries to avoid cache thrashing:\nsize_t olen = 0;\nsize_t slen = srclen;\nstruct base64_state st;\nst.eof = state->eof;\nst.bytes = state->bytes;\nst.carry = state->carry;\n\n// If we previously saw an EOF or an invalid character, bail out:\nif (st.eof) {\n\t*outlen = 0;\n\tret = 0;\n\t// If there was a trailing '=' to check, check it:\n\tif (slen && (st.eof == BASE64_AEOF)) {\n\t\tstate->bytes = 0;\n\t\tstate->eof = BASE64_EOF;\n\t\tret = ((base64_table_dec_8bit[*s++] == 254) && (slen == 1)) ? 1 : 0;\n\t}\n\treturn ret;\n}\n\n// Turn four 6-bit numbers into three bytes:\n// out[0] = 11111122\n// out[1] = 22223333\n// out[2] = 33444444\n\n// Duff's device again:\nswitch (st.bytes)\n{\n\tfor (;;)\n\t{\n\tcase 0:\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/generic/dec_tail.c",
    "content": "\t\tif (slen-- == 0) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif ((q = base64_table_dec_8bit[*s++]) >= 254) {\n\t\t\tst.eof = BASE64_EOF;\n\t\t\t// Treat character '=' as invalid for byte 0:\n\t\t\tbreak;\n\t\t}\n\t\tst.carry = q << 2;\n\t\tst.bytes++;\n\n\t\t// Deliberate fallthrough:\n\t\tBASE64_FALLTHROUGH\n\n\tcase 1:\tif (slen-- == 0) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif ((q = base64_table_dec_8bit[*s++]) >= 254) {\n\t\t\tst.eof = BASE64_EOF;\n\t\t\t// Treat character '=' as invalid for byte 1:\n\t\t\tbreak;\n\t\t}\n\t\t*o++ = st.carry | (q >> 4);\n\t\tst.carry = q << 4;\n\t\tst.bytes++;\n\t\tolen++;\n\n\t\t// Deliberate fallthrough:\n\t\tBASE64_FALLTHROUGH\n\n\tcase 2:\tif (slen-- == 0) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif ((q = base64_table_dec_8bit[*s++]) >= 254) {\n\t\t\tst.bytes++;\n\t\t\t// When q == 254, the input char is '='.\n\t\t\t// Check if next byte is also '=':\n\t\t\tif (q == 254) {\n\t\t\t\tif (slen-- != 0) {\n\t\t\t\t\tst.bytes = 0;\n\t\t\t\t\t// EOF:\n\t\t\t\t\tst.eof = BASE64_EOF;\n\t\t\t\t\tq = base64_table_dec_8bit[*s++];\n\t\t\t\t\tret = ((q == 254) && (slen == 0)) ? 1 : 0;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\t// Almost EOF\n\t\t\t\t\tst.eof = BASE64_AEOF;\n\t\t\t\t\tret = 1;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t// If we get here, there was an error:\n\t\t\tbreak;\n\t\t}\n\t\t*o++ = st.carry | (q >> 2);\n\t\tst.carry = q << 6;\n\t\tst.bytes++;\n\t\tolen++;\n\n\t\t// Deliberate fallthrough:\n\t\tBASE64_FALLTHROUGH\n\n\tcase 3:\tif (slen-- == 0) {\n\t\t\tret = 1;\n\t\t\tbreak;\n\t\t}\n\t\tif ((q = base64_table_dec_8bit[*s++]) >= 254) {\n\t\t\tst.bytes = 0;\n\t\t\tst.eof = BASE64_EOF;\n\t\t\t// When q == 254, the input char is '='. Return 1 and EOF.\n\t\t\t// When q == 255, the input char is invalid. Return 0 and EOF.\n\t\t\tret = ((q == 254) && (slen == 0)) ? 1 : 0;\n\t\t\tbreak;\n\t\t}\n\t\t*o++ = st.carry | q;\n\t\tst.carry = 0;\n\t\tst.bytes = 0;\n\t\tolen++;\n\t}\n}\n\nstate->eof = st.eof;\nstate->bytes = st.bytes;\nstate->carry = st.carry;\n*outlen = olen;\nreturn ret;\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/generic/enc_head.c",
    "content": "// Assume that *out is large enough to contain the output.\n// Theoretically it should be 4/3 the length of src.\nconst uint8_t *s = (const uint8_t *) src;\nuint8_t *o = (uint8_t *) out;\n\n// Use local temporaries to avoid cache thrashing:\nsize_t olen = 0;\nsize_t slen = srclen;\nstruct base64_state st;\nst.bytes = state->bytes;\nst.carry = state->carry;\n\n// Turn three bytes into four 6-bit numbers:\n// in[0] = 00111111\n// in[1] = 00112222\n// in[2] = 00222233\n// in[3] = 00333333\n\n// Duff's device, a for() loop inside a switch() statement. Legal!\nswitch (st.bytes)\n{\n\tfor (;;)\n\t{\n\tcase 0:\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/generic/enc_tail.c",
    "content": "\t\tif (slen-- == 0) {\n\t\t\tbreak;\n\t\t}\n\t\t*o++ = base64_table_enc_6bit[*s >> 2];\n\t\tst.carry = (*s++ << 4) & 0x30;\n\t\tst.bytes++;\n\t\tolen += 1;\n\n\t\t// Deliberate fallthrough:\n\t\tBASE64_FALLTHROUGH\n\n\tcase 1:\tif (slen-- == 0) {\n\t\t\tbreak;\n\t\t}\n\t\t*o++ = base64_table_enc_6bit[st.carry | (*s >> 4)];\n\t\tst.carry = (*s++ << 2) & 0x3C;\n\t\tst.bytes++;\n\t\tolen += 1;\n\n\t\t// Deliberate fallthrough:\n\t\tBASE64_FALLTHROUGH\n\n\tcase 2:\tif (slen-- == 0) {\n\t\t\tbreak;\n\t\t}\n\t\t*o++ = base64_table_enc_6bit[st.carry | (*s >> 6)];\n\t\t*o++ = base64_table_enc_6bit[*s++ & 0x3F];\n\t\tst.bytes = 0;\n\t\tolen += 2;\n\t}\n}\nstate->bytes = st.bytes;\nstate->carry = st.carry;\n*outlen = olen;\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/neon32/codec.c",
    "content": "#include <stdint.h>\n#include <stddef.h>\n#include <string.h>\n\n#include \"libbase64.h\"\n#include \"../../tables/tables.h\"\n#include \"../../codecs.h\"\n#include \"config.h\"\n#include \"../../env.h\"\n\n#ifdef __arm__\n#  if (defined(__ARM_NEON__) || defined(__ARM_NEON)) && HAVE_NEON32\n#    define BASE64_USE_NEON32\n#  endif\n#endif\n\n#ifdef BASE64_USE_NEON32\n#include <arm_neon.h>\n\n// Only enable inline assembly on supported compilers.\n#if defined(__GNUC__) || defined(__clang__)\n#define BASE64_NEON32_USE_ASM\n#endif\n\nstatic BASE64_FORCE_INLINE uint8x16_t\nvqtbl1q_u8 (const uint8x16_t lut, const uint8x16_t indices)\n{\n\t// NEON32 only supports 64-bit wide lookups in 128-bit tables. Emulate\n\t// the NEON64 `vqtbl1q_u8` intrinsic to do 128-bit wide lookups.\n\tuint8x8x2_t lut2;\n\tuint8x8x2_t result;\n\n\tlut2.val[0] = vget_low_u8(lut);\n\tlut2.val[1] = vget_high_u8(lut);\n\n\tresult.val[0] = vtbl2_u8(lut2, vget_low_u8(indices));\n\tresult.val[1] = vtbl2_u8(lut2, vget_high_u8(indices));\n\n\treturn vcombine_u8(result.val[0], result.val[1]);\n}\n\n#include \"../generic/32/dec_loop.c\"\n#include \"../generic/32/enc_loop.c\"\n#include \"dec_loop.c\"\n#include \"enc_reshuffle.c\"\n#include \"enc_translate.c\"\n#include \"enc_loop.c\"\n\n#endif\t// BASE64_USE_NEON32\n\n// Stride size is so large on these NEON 32-bit functions\n// (48 bytes encode, 32 bytes decode) that we inline the\n// uint32 codec to stay performant on smaller inputs.\n\nvoid\nbase64_stream_encode_neon32 BASE64_ENC_PARAMS\n{\n#ifdef BASE64_USE_NEON32\n\t#include \"../generic/enc_head.c\"\n\tenc_loop_neon32(&s, &slen, &o, &olen);\n\tenc_loop_generic_32(&s, &slen, &o, &olen);\n\t#include \"../generic/enc_tail.c\"\n#else\n\tbase64_enc_stub(state, src, srclen, out, outlen);\n#endif\n}\n\nint\nbase64_stream_decode_neon32 BASE64_DEC_PARAMS\n{\n#ifdef BASE64_USE_NEON32\n\t#include \"../generic/dec_head.c\"\n\tdec_loop_neon32(&s, &slen, &o, &olen);\n\tdec_loop_generic_32(&s, &slen, &o, &olen);\n\t#include \"../generic/dec_tail.c\"\n#else\n\treturn base64_dec_stub(state, src, srclen, out, outlen);\n#endif\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/neon32/dec_loop.c",
    "content": "static BASE64_FORCE_INLINE int\nis_nonzero (const uint8x16_t v)\n{\n\tuint64_t u64;\n\tconst uint64x2_t v64 = vreinterpretq_u64_u8(v);\n\tconst uint32x2_t v32 = vqmovn_u64(v64);\n\n\tvst1_u64(&u64, vreinterpret_u64_u32(v32));\n\treturn u64 != 0;\n}\n\nstatic BASE64_FORCE_INLINE uint8x16_t\ndelta_lookup (const uint8x16_t v)\n{\n\tconst uint8x8_t lut = {\n\t\t0, 16, 19, 4, (uint8_t) -65, (uint8_t) -65, (uint8_t) -71, (uint8_t) -71,\n\t};\n\n\treturn vcombine_u8(\n\t\tvtbl1_u8(lut, vget_low_u8(v)),\n\t\tvtbl1_u8(lut, vget_high_u8(v)));\n}\n\nstatic BASE64_FORCE_INLINE uint8x16_t\ndec_loop_neon32_lane (uint8x16_t *lane)\n{\n\t// See the SSSE3 decoder for an explanation of the algorithm.\n\tconst uint8x16_t lut_lo = {\n\t\t0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,\n\t\t0x11, 0x11, 0x13, 0x1A, 0x1B, 0x1B, 0x1B, 0x1A\n\t};\n\n\tconst uint8x16_t lut_hi = {\n\t\t0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08,\n\t\t0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10\n\t};\n\n\tconst uint8x16_t mask_0F = vdupq_n_u8(0x0F);\n\tconst uint8x16_t mask_2F = vdupq_n_u8(0x2F);\n\n\tconst uint8x16_t hi_nibbles = vshrq_n_u8(*lane, 4);\n\tconst uint8x16_t lo_nibbles = vandq_u8(*lane, mask_0F);\n\tconst uint8x16_t eq_2F      = vceqq_u8(*lane, mask_2F);\n\n\tconst uint8x16_t hi = vqtbl1q_u8(lut_hi, hi_nibbles);\n\tconst uint8x16_t lo = vqtbl1q_u8(lut_lo, lo_nibbles);\n\n\t// Now simply add the delta values to the input:\n\t*lane = vaddq_u8(*lane, delta_lookup(vaddq_u8(eq_2F, hi_nibbles)));\n\n\t// Return the validity mask:\n\treturn vandq_u8(lo, hi);\n}\n\nstatic inline void\ndec_loop_neon32 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tif (*slen < 64) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 64 bytes per round. Unlike the SSE codecs, no\n\t// extra trailing zero bytes are written, so it is not necessary to\n\t// reserve extra input bytes:\n\tsize_t rounds = *slen / 64;\n\n\t*slen -= rounds * 64;\t// 64 bytes consumed per round\n\t*olen += rounds * 48;\t// 48 bytes produced per round\n\n\tdo {\n\t\tuint8x16x3_t dec;\n\n\t\t// Load 64 bytes and deinterleave:\n\t\tuint8x16x4_t str = vld4q_u8(*s);\n\n\t\t// Decode each lane, collect a mask of invalid inputs:\n\t\tconst uint8x16_t classified\n\t\t\t= dec_loop_neon32_lane(&str.val[0])\n\t\t\t| dec_loop_neon32_lane(&str.val[1])\n\t\t\t| dec_loop_neon32_lane(&str.val[2])\n\t\t\t| dec_loop_neon32_lane(&str.val[3]);\n\n\t\t// Check for invalid input: if any of the delta values are\n\t\t// zero, fall back on bytewise code to do error checking and\n\t\t// reporting:\n\t\tif (is_nonzero(classified)) {\n\t\t\tbreak;\n\t\t}\n\n\t\t// Compress four bytes into three:\n\t\tdec.val[0] = vorrq_u8(vshlq_n_u8(str.val[0], 2), vshrq_n_u8(str.val[1], 4));\n\t\tdec.val[1] = vorrq_u8(vshlq_n_u8(str.val[1], 4), vshrq_n_u8(str.val[2], 2));\n\t\tdec.val[2] = vorrq_u8(vshlq_n_u8(str.val[2], 6), str.val[3]);\n\n\t\t// Interleave and store decoded result:\n\t\tvst3q_u8(*o, dec);\n\n\t\t*s += 64;\n\t\t*o += 48;\n\n\t} while (--rounds > 0);\n\n\t// Adjust for any rounds that were skipped:\n\t*slen += rounds * 64;\n\t*olen -= rounds * 48;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/neon32/enc_loop.c",
    "content": "#ifdef BASE64_NEON32_USE_ASM\nstatic BASE64_FORCE_INLINE void\nenc_loop_neon32_inner_asm (const uint8_t **s, uint8_t **o)\n{\n\t// This function duplicates the functionality of enc_loop_neon32_inner,\n\t// but entirely with inline assembly. This gives a significant speedup\n\t// over using NEON intrinsics, which do not always generate very good\n\t// code. The logic of the assembly is directly lifted from the\n\t// intrinsics version, so it can be used as a guide to this code.\n\n\t// Temporary registers, used as scratch space.\n\tuint8x16_t tmp0, tmp1, tmp2, tmp3;\n\tuint8x16_t mask0, mask1, mask2, mask3;\n\n\t// A lookup table containing the absolute offsets for all ranges.\n\tconst uint8x16_t lut = {\n\t\t  65U,  71U, 252U, 252U,\n\t\t 252U, 252U, 252U, 252U,\n\t\t 252U, 252U, 252U, 252U,\n\t\t 237U, 240U,   0U,   0U\n\t};\n\n\t// Numeric constants.\n\tconst uint8x16_t n51 = vdupq_n_u8(51);\n\tconst uint8x16_t n25 = vdupq_n_u8(25);\n\tconst uint8x16_t n63 = vdupq_n_u8(63);\n\n\t__asm__ (\n\n\t\t// Load 48 bytes and deinterleave. The bytes are loaded to\n\t\t// hard-coded registers q12, q13 and q14, to ensure that they\n\t\t// are contiguous. Increment the source pointer.\n\t\t\"vld3.8 {d24, d26, d28}, [%[src]]! \\n\\t\"\n\t\t\"vld3.8 {d25, d27, d29}, [%[src]]! \\n\\t\"\n\n\t\t// Reshuffle the bytes using temporaries.\n\t\t\"vshr.u8 %q[t0], q12,    #2      \\n\\t\"\n\t\t\"vshr.u8 %q[t1], q13,    #4      \\n\\t\"\n\t\t\"vshr.u8 %q[t2], q14,    #6      \\n\\t\"\n\t\t\"vsli.8  %q[t1], q12,    #4      \\n\\t\"\n\t\t\"vsli.8  %q[t2], q13,    #2      \\n\\t\"\n\t\t\"vand.u8 %q[t1], %q[t1], %q[n63] \\n\\t\"\n\t\t\"vand.u8 %q[t2], %q[t2], %q[n63] \\n\\t\"\n\t\t\"vand.u8 %q[t3], q14,    %q[n63] \\n\\t\"\n\n\t\t// t0..t3 are the reshuffled inputs. Create LUT indices.\n\t\t\"vqsub.u8 q12, %q[t0], %q[n51] \\n\\t\"\n\t\t\"vqsub.u8 q13, %q[t1], %q[n51] \\n\\t\"\n\t\t\"vqsub.u8 q14, %q[t2], %q[n51] \\n\\t\"\n\t\t\"vqsub.u8 q15, %q[t3], %q[n51] \\n\\t\"\n\n\t\t// Create the mask for range #0.\n\t\t\"vcgt.u8 %q[m0], %q[t0], %q[n25] \\n\\t\"\n\t\t\"vcgt.u8 %q[m1], %q[t1], %q[n25] \\n\\t\"\n\t\t\"vcgt.u8 %q[m2], %q[t2], %q[n25] \\n\\t\"\n\t\t\"vcgt.u8 %q[m3], %q[t3], %q[n25] \\n\\t\"\n\n\t\t// Subtract -1 to correct the LUT indices.\n\t\t\"vsub.u8 q12, %q[m0] \\n\\t\"\n\t\t\"vsub.u8 q13, %q[m1] \\n\\t\"\n\t\t\"vsub.u8 q14, %q[m2] \\n\\t\"\n\t\t\"vsub.u8 q15, %q[m3] \\n\\t\"\n\n\t\t// Lookup the delta values.\n\t\t\"vtbl.u8 d24, {%q[lut]}, d24 \\n\\t\"\n\t\t\"vtbl.u8 d25, {%q[lut]}, d25 \\n\\t\"\n\t\t\"vtbl.u8 d26, {%q[lut]}, d26 \\n\\t\"\n\t\t\"vtbl.u8 d27, {%q[lut]}, d27 \\n\\t\"\n\t\t\"vtbl.u8 d28, {%q[lut]}, d28 \\n\\t\"\n\t\t\"vtbl.u8 d29, {%q[lut]}, d29 \\n\\t\"\n\t\t\"vtbl.u8 d30, {%q[lut]}, d30 \\n\\t\"\n\t\t\"vtbl.u8 d31, {%q[lut]}, d31 \\n\\t\"\n\n\t\t// Add the delta values.\n\t\t\"vadd.u8 q12, %q[t0] \\n\\t\"\n\t\t\"vadd.u8 q13, %q[t1] \\n\\t\"\n\t\t\"vadd.u8 q14, %q[t2] \\n\\t\"\n\t\t\"vadd.u8 q15, %q[t3] \\n\\t\"\n\n\t\t// Store 64 bytes and interleave. Increment the dest pointer.\n\t\t\"vst4.8 {d24, d26, d28, d30}, [%[dst]]! \\n\\t\"\n\t\t\"vst4.8 {d25, d27, d29, d31}, [%[dst]]! \\n\\t\"\n\n\t\t// Outputs (modified).\n\t\t: [src] \"+r\"  (*s),\n\t\t  [dst] \"+r\"  (*o),\n\t\t  [t0]  \"=&w\" (tmp0),\n\t\t  [t1]  \"=&w\" (tmp1),\n\t\t  [t2]  \"=&w\" (tmp2),\n\t\t  [t3]  \"=&w\" (tmp3),\n\t\t  [m0]  \"=&w\" (mask0),\n\t\t  [m1]  \"=&w\" (mask1),\n\t\t  [m2]  \"=&w\" (mask2),\n\t\t  [m3]  \"=&w\" (mask3)\n\n\t\t// Inputs (not modified).\n\t\t: [lut] \"w\" (lut),\n\t\t  [n25] \"w\" (n25),\n\t\t  [n51] \"w\" (n51),\n\t\t  [n63] \"w\" (n63)\n\n\t\t// Clobbers.\n\t\t: \"d24\", \"d25\", \"d26\", \"d27\", \"d28\", \"d29\", \"d30\", \"d31\",\n\t\t  \"cc\", \"memory\"\n\t);\n}\n#endif\n\nstatic BASE64_FORCE_INLINE void\nenc_loop_neon32_inner (const uint8_t **s, uint8_t **o)\n{\n#ifdef BASE64_NEON32_USE_ASM\n\tenc_loop_neon32_inner_asm(s, o);\n#else\n\t// Load 48 bytes and deinterleave:\n\tuint8x16x3_t src = vld3q_u8(*s);\n\n\t// Reshuffle:\n\tuint8x16x4_t out = enc_reshuffle(src);\n\n\t// Translate reshuffled bytes to the Base64 alphabet:\n\tout = enc_translate(out);\n\n\t// Interleave and store output:\n\tvst4q_u8(*o, out);\n\n\t*s += 48;\n\t*o += 64;\n#endif\n}\n\nstatic inline void\nenc_loop_neon32 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tsize_t rounds = *slen / 48;\n\n\t*slen -= rounds * 48;\t// 48 bytes consumed per round\n\t*olen += rounds * 64;\t// 64 bytes produced per round\n\n\twhile (rounds > 0) {\n\t\tif (rounds >= 8) {\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\trounds -= 8;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 4) {\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\trounds -= 4;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 2) {\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\tenc_loop_neon32_inner(s, o);\n\t\t\trounds -= 2;\n\t\t\tcontinue;\n\t\t}\n\t\tenc_loop_neon32_inner(s, o);\n\t\tbreak;\n\t}\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/neon32/enc_reshuffle.c",
    "content": "static BASE64_FORCE_INLINE uint8x16x4_t\nenc_reshuffle (uint8x16x3_t in)\n{\n\tuint8x16x4_t out;\n\n\t// Input:\n\t// in[0]  = a7 a6 a5 a4 a3 a2 a1 a0\n\t// in[1]  = b7 b6 b5 b4 b3 b2 b1 b0\n\t// in[2]  = c7 c6 c5 c4 c3 c2 c1 c0\n\n\t// Output:\n\t// out[0] = 00 00 a7 a6 a5 a4 a3 a2\n\t// out[1] = 00 00 a1 a0 b7 b6 b5 b4\n\t// out[2] = 00 00 b3 b2 b1 b0 c7 c6\n\t// out[3] = 00 00 c5 c4 c3 c2 c1 c0\n\n\t// Move the input bits to where they need to be in the outputs. Except\n\t// for the first output, the high two bits are not cleared.\n\tout.val[0] = vshrq_n_u8(in.val[0], 2);\n\tout.val[1] = vshrq_n_u8(in.val[1], 4);\n\tout.val[2] = vshrq_n_u8(in.val[2], 6);\n\tout.val[1] = vsliq_n_u8(out.val[1], in.val[0], 4);\n\tout.val[2] = vsliq_n_u8(out.val[2], in.val[1], 2);\n\n\t// Clear the high two bits in the second, third and fourth output.\n\tout.val[1] = vandq_u8(out.val[1], vdupq_n_u8(0x3F));\n\tout.val[2] = vandq_u8(out.val[2], vdupq_n_u8(0x3F));\n\tout.val[3] = vandq_u8(in.val[2],  vdupq_n_u8(0x3F));\n\n\treturn out;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/neon32/enc_translate.c",
    "content": "static BASE64_FORCE_INLINE uint8x16x4_t\nenc_translate (const uint8x16x4_t in)\n{\n\t// A lookup table containing the absolute offsets for all ranges:\n\tconst uint8x16_t lut = {\n\t\t 65U,  71U, 252U, 252U,\n\t\t252U, 252U, 252U, 252U,\n\t\t252U, 252U, 252U, 252U,\n\t\t237U, 240U,   0U,   0U\n\t};\n\n\tconst uint8x16_t offset = vdupq_n_u8(51);\n\n\tuint8x16x4_t indices, mask, delta, out;\n\n\t// Translate values 0..63 to the Base64 alphabet. There are five sets:\n\t// #  From      To         Abs    Index  Characters\n\t// 0  [0..25]   [65..90]   +65        0  ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t// 1  [26..51]  [97..122]  +71        1  abcdefghijklmnopqrstuvwxyz\n\t// 2  [52..61]  [48..57]    -4  [2..11]  0123456789\n\t// 3  [62]      [43]       -19       12  +\n\t// 4  [63]      [47]       -16       13  /\n\n\t// Create LUT indices from input:\n\t// the index for range #0 is right, others are 1 less than expected:\n\tindices.val[0] = vqsubq_u8(in.val[0], offset);\n\tindices.val[1] = vqsubq_u8(in.val[1], offset);\n\tindices.val[2] = vqsubq_u8(in.val[2], offset);\n\tindices.val[3] = vqsubq_u8(in.val[3], offset);\n\n\t// mask is 0xFF (-1) for range #[1..4] and 0x00 for range #0:\n\tmask.val[0] = vcgtq_u8(in.val[0], vdupq_n_u8(25));\n\tmask.val[1] = vcgtq_u8(in.val[1], vdupq_n_u8(25));\n\tmask.val[2] = vcgtq_u8(in.val[2], vdupq_n_u8(25));\n\tmask.val[3] = vcgtq_u8(in.val[3], vdupq_n_u8(25));\n\n\t// Subtract -1, so add 1 to indices for range #[1..4], All indices are\n\t// now correct:\n\tindices.val[0] = vsubq_u8(indices.val[0], mask.val[0]);\n\tindices.val[1] = vsubq_u8(indices.val[1], mask.val[1]);\n\tindices.val[2] = vsubq_u8(indices.val[2], mask.val[2]);\n\tindices.val[3] = vsubq_u8(indices.val[3], mask.val[3]);\n\n\t// Lookup delta values:\n\tdelta.val[0] = vqtbl1q_u8(lut, indices.val[0]);\n\tdelta.val[1] = vqtbl1q_u8(lut, indices.val[1]);\n\tdelta.val[2] = vqtbl1q_u8(lut, indices.val[2]);\n\tdelta.val[3] = vqtbl1q_u8(lut, indices.val[3]);\n\n\t// Add delta values:\n\tout.val[0] = vaddq_u8(in.val[0], delta.val[0]);\n\tout.val[1] = vaddq_u8(in.val[1], delta.val[1]);\n\tout.val[2] = vaddq_u8(in.val[2], delta.val[2]);\n\tout.val[3] = vaddq_u8(in.val[3], delta.val[3]);\n\n\treturn out;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/neon64/codec.c",
    "content": "#include <stdint.h>\n#include <stddef.h>\n#include <string.h>\n\n#include \"libbase64.h\"\n#include \"../../tables/tables.h\"\n#include \"../../codecs.h\"\n#include \"config.h\"\n#include \"../../env.h\"\n\n#if HAVE_NEON64\n#include <arm_neon.h>\n\n// Only enable inline assembly on supported compilers.\n#if !defined(__wasm__) && (defined(__GNUC__) || defined(__clang__))\n#define BASE64_NEON64_USE_ASM\n#endif\n\nstatic BASE64_FORCE_INLINE uint8x16x4_t\nload_64byte_table (const uint8_t *p)\n{\n#ifdef BASE64_NEON64_USE_ASM\n\n\t// Force the table to be loaded into contiguous registers. GCC will not\n\t// normally allocate contiguous registers for a `uint8x16x4_t'. These\n\t// registers are chosen to not conflict with the ones in the enc loop.\n\tregister uint8x16_t t0 __asm__ (\"v8\");\n\tregister uint8x16_t t1 __asm__ (\"v9\");\n\tregister uint8x16_t t2 __asm__ (\"v10\");\n\tregister uint8x16_t t3 __asm__ (\"v11\");\n\n\t__asm__ (\n\t\t\"ld1 {%[t0].16b, %[t1].16b, %[t2].16b, %[t3].16b}, [%[src]], #64 \\n\\t\"\n\t\t: [src] \"+r\" (p),\n\t\t  [t0]  \"=w\" (t0),\n\t\t  [t1]  \"=w\" (t1),\n\t\t  [t2]  \"=w\" (t2),\n\t\t  [t3]  \"=w\" (t3)\n\t);\n\n\treturn (uint8x16x4_t) {\n\t\t.val[0] = t0,\n\t\t.val[1] = t1,\n\t\t.val[2] = t2,\n\t\t.val[3] = t3,\n\t};\n#else\n\treturn vld1q_u8_x4(p);\n#endif\n}\n\n#include \"../generic/32/dec_loop.c\"\n#include \"../generic/64/enc_loop.c\"\n#include \"dec_loop.c\"\n\n#ifdef BASE64_NEON64_USE_ASM\n# include \"enc_loop_asm.c\"\n#else\n# include \"enc_reshuffle.c\"\n# include \"enc_loop.c\"\n#endif\n\n#endif\t// HAVE_NEON64\n\n// Stride size is so large on these NEON 64-bit functions\n// (48 bytes encode, 64 bytes decode) that we inline the\n// uint64 codec to stay performant on smaller inputs.\n\nvoid\nbase64_stream_encode_neon64 BASE64_ENC_PARAMS\n{\n#if HAVE_NEON64\n\t#include \"../generic/enc_head.c\"\n\tenc_loop_neon64(&s, &slen, &o, &olen);\n\tenc_loop_generic_64(&s, &slen, &o, &olen);\n\t#include \"../generic/enc_tail.c\"\n#else\n\tbase64_enc_stub(state, src, srclen, out, outlen);\n#endif\n}\n\nint\nbase64_stream_decode_neon64 BASE64_DEC_PARAMS\n{\n#if HAVE_NEON64\n\t#include \"../generic/dec_head.c\"\n\tdec_loop_neon64(&s, &slen, &o, &olen);\n\tdec_loop_generic_32(&s, &slen, &o, &olen);\n\t#include \"../generic/dec_tail.c\"\n#else\n\treturn base64_dec_stub(state, src, srclen, out, outlen);\n#endif\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/neon64/dec_loop.c",
    "content": "// The input consists of five valid character sets in the Base64 alphabet,\n// which we need to map back to the 6-bit values they represent.\n// There are three ranges, two singles, and then there's the rest.\n//\n//   #  From       To        LUT  Characters\n//   1  [0..42]    [255]      #1  invalid input\n//   2  [43]       [62]       #1  +\n//   3  [44..46]   [255]      #1  invalid input\n//   4  [47]       [63]       #1  /\n//   5  [48..57]   [52..61]   #1  0..9\n//   6  [58..63]   [255]      #1  invalid input\n//   7  [64]       [255]      #2  invalid input\n//   8  [65..90]   [0..25]    #2  A..Z\n//   9  [91..96]   [255]      #2  invalid input\n//  10  [97..122]  [26..51]   #2  a..z\n//  11  [123..126] [255]      #2  invalid input\n// (12) Everything else => invalid input\n\n// The first LUT will use the VTBL instruction (out of range indices are set to\n// 0 in destination).\nstatic const uint8_t dec_lut1[] = {\n\t255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U,\n\t255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U,\n\t255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U, 255U,  62U, 255U, 255U, 255U,  63U,\n\t 52U,  53U,  54U,  55U,  56U,  57U,  58U,  59U,  60U,  61U, 255U, 255U, 255U, 255U, 255U, 255U,\n};\n\n// The second LUT will use the VTBX instruction (out of range indices will be\n// unchanged in destination). Input [64..126] will be mapped to index [1..63]\n// in this LUT. Index 0 means that value comes from LUT #1.\nstatic const uint8_t dec_lut2[] = {\n\t  0U, 255U,   0U,   1U,   2U,   3U,   4U,   5U,   6U,   7U,   8U,   9U,  10U,  11U,  12U,  13U,\n\t 14U,  15U,  16U,  17U,  18U,  19U,  20U,  21U,  22U,  23U,  24U,  25U, 255U, 255U, 255U, 255U,\n\t255U, 255U,  26U,  27U,  28U,  29U,  30U,  31U,  32U,  33U,  34U,  35U,  36U,  37U,  38U,  39U,\n\t 40U,  41U,  42U,  43U,  44U,  45U,  46U,  47U,  48U,  49U,  50U,  51U, 255U, 255U, 255U, 255U,\n};\n\n// All input values in range for the first look-up will be 0U in the second\n// look-up result. All input values out of range for the first look-up will be\n// 0U in the first look-up result. Thus, the two results can be ORed without\n// conflicts.\n//\n// Invalid characters that are in the valid range for either look-up will be\n// set to 255U in the combined result. Other invalid characters will just be\n// passed through with the second look-up result (using the VTBX instruction).\n// Since the second LUT is 64 bytes, those passed-through values are guaranteed\n// to have a value greater than 63U. Therefore, valid characters will be mapped\n// to the valid [0..63] range and all invalid characters will be mapped to\n// values greater than 63.\n\nstatic inline void\ndec_loop_neon64 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tif (*slen < 64) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 64 bytes per round. Unlike the SSE codecs, no\n\t// extra trailing zero bytes are written, so it is not necessary to\n\t// reserve extra input bytes:\n\tsize_t rounds = *slen / 64;\n\n\t*slen -= rounds * 64;\t// 64 bytes consumed per round\n\t*olen += rounds * 48;\t// 48 bytes produced per round\n\n\tconst uint8x16x4_t tbl_dec1 = load_64byte_table(dec_lut1);\n\tconst uint8x16x4_t tbl_dec2 = load_64byte_table(dec_lut2);\n\n\tdo {\n\t\tconst uint8x16_t offset = vdupq_n_u8(63U);\n\t\tuint8x16x4_t dec1, dec2;\n\t\tuint8x16x3_t dec;\n\n\t\t// Load 64 bytes and deinterleave:\n\t\tuint8x16x4_t str = vld4q_u8((uint8_t *) *s);\n\n\t\t// Get indices for second LUT:\n\t\tdec2.val[0] = vqsubq_u8(str.val[0], offset);\n\t\tdec2.val[1] = vqsubq_u8(str.val[1], offset);\n\t\tdec2.val[2] = vqsubq_u8(str.val[2], offset);\n\t\tdec2.val[3] = vqsubq_u8(str.val[3], offset);\n\n\t\t// Get values from first LUT:\n\t\tdec1.val[0] = vqtbl4q_u8(tbl_dec1, str.val[0]);\n\t\tdec1.val[1] = vqtbl4q_u8(tbl_dec1, str.val[1]);\n\t\tdec1.val[2] = vqtbl4q_u8(tbl_dec1, str.val[2]);\n\t\tdec1.val[3] = vqtbl4q_u8(tbl_dec1, str.val[3]);\n\n\t\t// Get values from second LUT:\n\t\tdec2.val[0] = vqtbx4q_u8(dec2.val[0], tbl_dec2, dec2.val[0]);\n\t\tdec2.val[1] = vqtbx4q_u8(dec2.val[1], tbl_dec2, dec2.val[1]);\n\t\tdec2.val[2] = vqtbx4q_u8(dec2.val[2], tbl_dec2, dec2.val[2]);\n\t\tdec2.val[3] = vqtbx4q_u8(dec2.val[3], tbl_dec2, dec2.val[3]);\n\n\t\t// Get final values:\n\t\tstr.val[0] = vorrq_u8(dec1.val[0], dec2.val[0]);\n\t\tstr.val[1] = vorrq_u8(dec1.val[1], dec2.val[1]);\n\t\tstr.val[2] = vorrq_u8(dec1.val[2], dec2.val[2]);\n\t\tstr.val[3] = vorrq_u8(dec1.val[3], dec2.val[3]);\n\n\t\t// Check for invalid input, any value larger than 63:\n\t\tconst uint8x16_t classified\n\t\t\t= vorrq_u8(\n\t\t\t\tvorrq_u8(vcgtq_u8(str.val[0], vdupq_n_u8(63)), vcgtq_u8(str.val[1], vdupq_n_u8(63))),\n\t\t\t\tvorrq_u8(vcgtq_u8(str.val[2], vdupq_n_u8(63)), vcgtq_u8(str.val[3], vdupq_n_u8(63)))\n\t\t\t);\n\n\t\t// Check that all bits are zero:\n\t\tif (vmaxvq_u8(classified) != 0U) {\n\t\t\tbreak;\n\t\t}\n\n\t\t// Compress four bytes into three:\n\t\tdec.val[0] = vorrq_u8(vshlq_n_u8(str.val[0], 2), vshrq_n_u8(str.val[1], 4));\n\t\tdec.val[1] = vorrq_u8(vshlq_n_u8(str.val[1], 4), vshrq_n_u8(str.val[2], 2));\n\t\tdec.val[2] = vorrq_u8(vshlq_n_u8(str.val[2], 6), str.val[3]);\n\n\t\t// Interleave and store decoded result:\n\t\tvst3q_u8((uint8_t *) *o, dec);\n\n\t\t*s += 64;\n\t\t*o += 48;\n\n\t} while (--rounds > 0);\n\n\t// Adjust for any rounds that were skipped:\n\t*slen += rounds * 64;\n\t*olen -= rounds * 48;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/neon64/enc_loop.c",
    "content": "static BASE64_FORCE_INLINE void\nenc_loop_neon64_inner (const uint8_t **s, uint8_t **o, const uint8x16x4_t tbl_enc)\n{\n\t// Load 48 bytes and deinterleave:\n\tuint8x16x3_t src = vld3q_u8(*s);\n\n\t// Divide bits of three input bytes over four output bytes:\n\tuint8x16x4_t out = enc_reshuffle(src);\n\n\t// The bits have now been shifted to the right locations;\n\t// translate their values 0..63 to the Base64 alphabet.\n\t// Use a 64-byte table lookup:\n\tout.val[0] = vqtbl4q_u8(tbl_enc, out.val[0]);\n\tout.val[1] = vqtbl4q_u8(tbl_enc, out.val[1]);\n\tout.val[2] = vqtbl4q_u8(tbl_enc, out.val[2]);\n\tout.val[3] = vqtbl4q_u8(tbl_enc, out.val[3]);\n\n\t// Interleave and store output:\n\tvst4q_u8(*o, out);\n\n\t*s += 48;\n\t*o += 64;\n}\n\nstatic inline void\nenc_loop_neon64 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tsize_t rounds = *slen / 48;\n\n\t*slen -= rounds * 48;\t// 48 bytes consumed per round\n\t*olen += rounds * 64;\t// 64 bytes produced per round\n\n\t// Load the encoding table:\n\tconst uint8x16x4_t tbl_enc = load_64byte_table(base64_table_enc_6bit);\n\n\twhile (rounds > 0) {\n\t\tif (rounds >= 8) {\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\trounds -= 8;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 4) {\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\trounds -= 4;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 2) {\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\t\trounds -= 2;\n\t\t\tcontinue;\n\t\t}\n\t\tenc_loop_neon64_inner(s, o, tbl_enc);\n\t\tbreak;\n\t}\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/neon64/enc_loop_asm.c",
    "content": "// Apologies in advance for combining the preprocessor with inline assembly,\n// two notoriously gnarly parts of C, but it was necessary to avoid a lot of\n// code repetition. The preprocessor is used to template large sections of\n// inline assembly that differ only in the registers used. If the code was\n// written out by hand, it would become very large and hard to audit.\n\n// Generate a block of inline assembly that loads three user-defined registers\n// A, B, C from memory and deinterleaves them, post-incrementing the src\n// pointer. The register set should be sequential.\n#define LOAD(A, B, C) \\\n\t\"ld3 {\"A\".16b, \"B\".16b, \"C\".16b}, [%[src]], #48 \\n\\t\"\n\n// Generate a block of inline assembly that takes three deinterleaved registers\n// and shuffles the bytes. The output is in temporary registers t0..t3.\n#define SHUF(A, B, C) \\\n\t\"ushr %[t0].16b, \"A\".16b,   #2         \\n\\t\" \\\n\t\"ushr %[t1].16b, \"B\".16b,   #4         \\n\\t\" \\\n\t\"ushr %[t2].16b, \"C\".16b,   #6         \\n\\t\" \\\n\t\"sli  %[t1].16b, \"A\".16b,   #4         \\n\\t\" \\\n\t\"sli  %[t2].16b, \"B\".16b,   #2         \\n\\t\" \\\n\t\"and  %[t1].16b, %[t1].16b, %[n63].16b \\n\\t\" \\\n\t\"and  %[t2].16b, %[t2].16b, %[n63].16b \\n\\t\" \\\n\t\"and  %[t3].16b, \"C\".16b,   %[n63].16b \\n\\t\"\n\n// Generate a block of inline assembly that takes temporary registers t0..t3\n// and translates them to the base64 alphabet, using a table loaded into\n// v8..v11. The output is in user-defined registers A..D.\n#define TRAN(A, B, C, D) \\\n\t\"tbl \"A\".16b, {v8.16b-v11.16b}, %[t0].16b \\n\\t\" \\\n\t\"tbl \"B\".16b, {v8.16b-v11.16b}, %[t1].16b \\n\\t\" \\\n\t\"tbl \"C\".16b, {v8.16b-v11.16b}, %[t2].16b \\n\\t\" \\\n\t\"tbl \"D\".16b, {v8.16b-v11.16b}, %[t3].16b \\n\\t\"\n\n// Generate a block of inline assembly that interleaves four registers and\n// stores them, post-incrementing the destination pointer.\n#define STOR(A, B, C, D) \\\n\t\"st4 {\"A\".16b, \"B\".16b, \"C\".16b, \"D\".16b}, [%[dst]], #64 \\n\\t\"\n\n// Generate a block of inline assembly that generates a single self-contained\n// encoder round: fetch the data, process it, and store the result.\n#define ROUND() \\\n\tLOAD(\"v12\", \"v13\", \"v14\") \\\n\tSHUF(\"v12\", \"v13\", \"v14\") \\\n\tTRAN(\"v12\", \"v13\", \"v14\", \"v15\") \\\n\tSTOR(\"v12\", \"v13\", \"v14\", \"v15\")\n\n// Generate a block of assembly that generates a type A interleaved encoder\n// round. It uses registers that were loaded by the previous type B round, and\n// in turn loads registers for the next type B round.\n#define ROUND_A() \\\n\tSHUF(\"v2\",  \"v3\",  \"v4\") \\\n\tLOAD(\"v12\", \"v13\", \"v14\") \\\n\tTRAN(\"v2\",  \"v3\",  \"v4\", \"v5\") \\\n\tSTOR(\"v2\",  \"v3\",  \"v4\", \"v5\")\n\n// Type B interleaved encoder round. Same as type A, but register sets swapped.\n#define ROUND_B() \\\n\tSHUF(\"v12\", \"v13\", \"v14\") \\\n\tLOAD(\"v2\",  \"v3\",  \"v4\") \\\n\tTRAN(\"v12\", \"v13\", \"v14\", \"v15\") \\\n\tSTOR(\"v12\", \"v13\", \"v14\", \"v15\")\n\n// The first type A round needs to load its own registers.\n#define ROUND_A_FIRST() \\\n\tLOAD(\"v2\", \"v3\", \"v4\") \\\n\tROUND_A()\n\n// The last type B round omits the load for the next step.\n#define ROUND_B_LAST() \\\n\tSHUF(\"v12\", \"v13\", \"v14\") \\\n\tTRAN(\"v12\", \"v13\", \"v14\", \"v15\") \\\n\tSTOR(\"v12\", \"v13\", \"v14\", \"v15\")\n\n// Suppress clang's warning that the literal string in the asm statement is\n// overlong (longer than the ISO-mandated minimum size of 4095 bytes for C99\n// compilers). It may be true, but the goal here is not C99 portability.\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Woverlength-strings\"\n\nstatic inline void\nenc_loop_neon64 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tsize_t rounds = *slen / 48;\n\n\tif (rounds == 0) {\n\t\treturn;\n\t}\n\n\t*slen -= rounds * 48;\t// 48 bytes consumed per round.\n\t*olen += rounds * 64;\t// 64 bytes produced per round.\n\n\t// Number of times to go through the 8x loop.\n\tsize_t loops = rounds / 8;\n\n\t// Number of rounds remaining after the 8x loop.\n\trounds %= 8;\n\n\t// Temporary registers, used as scratch space.\n\tuint8x16_t tmp0, tmp1, tmp2, tmp3;\n\n\t__asm__ volatile (\n\n\t\t// Load the encoding table into v8..v11.\n\t\t\"    ld1 {v8.16b-v11.16b}, [%[tbl]] \\n\\t\"\n\n\t\t// If there are eight rounds or more, enter an 8x unrolled loop\n\t\t// of interleaved encoding rounds. The rounds interleave memory\n\t\t// operations (load/store) with data operations to maximize\n\t\t// pipeline throughput.\n\t\t\"    cbz %[loops], 4f \\n\\t\"\n\n\t\t// The SIMD instructions do not touch the flags.\n\t\t\"88: subs %[loops], %[loops], #1 \\n\\t\"\n\t\t\"    \" ROUND_A_FIRST()\n\t\t\"    \" ROUND_B()\n\t\t\"    \" ROUND_A()\n\t\t\"    \" ROUND_B()\n\t\t\"    \" ROUND_A()\n\t\t\"    \" ROUND_B()\n\t\t\"    \" ROUND_A()\n\t\t\"    \" ROUND_B_LAST()\n\t\t\"    b.ne 88b \\n\\t\"\n\n\t\t// Enter a 4x unrolled loop for rounds of 4 or more.\n\t\t\"4:  cmp  %[rounds], #4 \\n\\t\"\n\t\t\"    b.lt 30f           \\n\\t\"\n\t\t\"    \" ROUND_A_FIRST()\n\t\t\"    \" ROUND_B()\n\t\t\"    \" ROUND_A()\n\t\t\"    \" ROUND_B_LAST()\n\t\t\"    sub %[rounds], %[rounds], #4 \\n\\t\"\n\n\t\t// Dispatch the remaining rounds 0..3.\n\t\t\"30: cbz  %[rounds], 0f \\n\\t\"\n\t\t\"    cmp  %[rounds], #2 \\n\\t\"\n\t\t\"    b.eq 2f            \\n\\t\"\n\t\t\"    b.lt 1f            \\n\\t\"\n\n\t\t// Block of non-interlaced encoding rounds, which can each\n\t\t// individually be jumped to. Rounds fall through to the next.\n\t\t\"3:  \" ROUND()\n\t\t\"2:  \" ROUND()\n\t\t\"1:  \" ROUND()\n\t\t\"0:  \\n\\t\"\n\n\t\t// Outputs (modified).\n\t\t: [loops] \"+r\"  (loops),\n\t\t  [src]   \"+r\"  (*s),\n\t\t  [dst]   \"+r\"  (*o),\n\t\t  [t0]    \"=&w\" (tmp0),\n\t\t  [t1]    \"=&w\" (tmp1),\n\t\t  [t2]    \"=&w\" (tmp2),\n\t\t  [t3]    \"=&w\" (tmp3)\n\n\t\t// Inputs (not modified).\n\t\t: [rounds] \"r\" (rounds),\n\t\t  [tbl]    \"r\" (base64_table_enc_6bit),\n\t\t  [n63]    \"w\" (vdupq_n_u8(63))\n\n\t\t// Clobbers.\n\t\t: \"v2\",  \"v3\",  \"v4\",  \"v5\",\n\t\t  \"v8\",  \"v9\",  \"v10\", \"v11\",\n\t\t  \"v12\", \"v13\", \"v14\", \"v15\",\n\t\t  \"cc\", \"memory\"\n\t);\n}\n\n#pragma GCC diagnostic pop\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/neon64/enc_reshuffle.c",
    "content": "static BASE64_FORCE_INLINE uint8x16x4_t\nenc_reshuffle (const uint8x16x3_t in)\n{\n\tuint8x16x4_t out;\n\n\t// Input:\n\t// in[0]  = a7 a6 a5 a4 a3 a2 a1 a0\n\t// in[1]  = b7 b6 b5 b4 b3 b2 b1 b0\n\t// in[2]  = c7 c6 c5 c4 c3 c2 c1 c0\n\n\t// Output:\n\t// out[0] = 00 00 a7 a6 a5 a4 a3 a2\n\t// out[1] = 00 00 a1 a0 b7 b6 b5 b4\n\t// out[2] = 00 00 b3 b2 b1 b0 c7 c6\n\t// out[3] = 00 00 c5 c4 c3 c2 c1 c0\n\n\t// Move the input bits to where they need to be in the outputs. Except\n\t// for the first output, the high two bits are not cleared.\n\tout.val[0] = vshrq_n_u8(in.val[0], 2);\n\tout.val[1] = vshrq_n_u8(in.val[1], 4);\n\tout.val[2] = vshrq_n_u8(in.val[2], 6);\n\tout.val[1] = vsliq_n_u8(out.val[1], in.val[0], 4);\n\tout.val[2] = vsliq_n_u8(out.val[2], in.val[1], 2);\n\n\t// Clear the high two bits in the second, third and fourth output.\n\tout.val[1] = vandq_u8(out.val[1], vdupq_n_u8(0x3F));\n\tout.val[2] = vandq_u8(out.val[2], vdupq_n_u8(0x3F));\n\tout.val[3] = vandq_u8(in.val[2],  vdupq_n_u8(0x3F));\n\n\treturn out;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/sse41/codec.c",
    "content": "#include <stdint.h>\n#include <stddef.h>\n#include <stdlib.h>\n\n#include \"libbase64.h\"\n#include \"../../tables/tables.h\"\n#include \"../../codecs.h\"\n#include \"config.h\"\n#include \"../../env.h\"\n\n#if HAVE_SSE41\n#if defined(__clang__)\n#pragma clang attribute push (__attribute__((target(\"sse4.1\"))), apply_to=function)\n#else\n#pragma GCC target(\"sse4.1\")\n#endif\n#include <smmintrin.h>\n\n// Only enable inline assembly on supported compilers and on 64-bit CPUs.\n#ifndef BASE64_SSE41_USE_ASM\n# if (defined(__GNUC__) || defined(__clang__)) && BASE64_WORDSIZE == 64\n#  define BASE64_SSE41_USE_ASM 1\n# else\n#  define BASE64_SSE41_USE_ASM 0\n# endif\n#endif\n\n#include \"../ssse3/dec_reshuffle.c\"\n#include \"../ssse3/dec_loop.c\"\n\n#if BASE64_SSE41_USE_ASM\n# include \"../ssse3/enc_loop_asm.c\"\n#else\n# include \"../ssse3/enc_translate.c\"\n# include \"../ssse3/enc_reshuffle.c\"\n# include \"../ssse3/enc_loop.c\"\n#endif\n\n#endif\t// HAVE_SSE41\n\nvoid\nbase64_stream_encode_sse41 BASE64_ENC_PARAMS\n{\n#if HAVE_SSE41\n\t#include \"../generic/enc_head.c\"\n\tenc_loop_ssse3(&s, &slen, &o, &olen);\n\t#include \"../generic/enc_tail.c\"\n#else\n\tbase64_enc_stub(state, src, srclen, out, outlen);\n#endif\n}\n\nint\nbase64_stream_decode_sse41 BASE64_DEC_PARAMS\n{\n#if HAVE_SSE41\n\t#include \"../generic/dec_head.c\"\n\tdec_loop_ssse3(&s, &slen, &o, &olen);\n\t#include \"../generic/dec_tail.c\"\n#if defined(__clang__)\n\t#pragma clang attribute pop\n#endif\n#else\n\treturn base64_dec_stub(state, src, srclen, out, outlen);\n#endif\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/sse42/codec.c",
    "content": "#include <stdint.h>\n#include <stddef.h>\n#include <stdlib.h>\n\n#include \"libbase64.h\"\n#include \"../../tables/tables.h\"\n#include \"../../codecs.h\"\n#include \"config.h\"\n#include \"../../env.h\"\n\n#if HAVE_SSE42\n#if defined(__clang__)\n#pragma clang attribute push (__attribute__((target(\"sse4.2\"))), apply_to=function)\n#else\n#pragma GCC target(\"sse4.2\")\n#endif\n#include <nmmintrin.h>\n\n// Only enable inline assembly on supported compilers and on 64-bit CPUs.\n#ifndef BASE64_SSE42_USE_ASM\n# if (defined(__GNUC__) || defined(__clang__)) && BASE64_WORDSIZE == 64\n#  define BASE64_SSE42_USE_ASM 1\n# else\n#  define BASE64_SSE42_USE_ASM 0\n# endif\n#endif\n\n#include \"../ssse3/dec_reshuffle.c\"\n#include \"../ssse3/dec_loop.c\"\n\n#if BASE64_SSE42_USE_ASM\n# include \"../ssse3/enc_loop_asm.c\"\n#else\n# include \"../ssse3/enc_translate.c\"\n# include \"../ssse3/enc_reshuffle.c\"\n# include \"../ssse3/enc_loop.c\"\n#endif\n\n#endif\t// HAVE_SSE42\n\nvoid\nbase64_stream_encode_sse42 BASE64_ENC_PARAMS\n{\n#if HAVE_SSE42\n\t#include \"../generic/enc_head.c\"\n\tenc_loop_ssse3(&s, &slen, &o, &olen);\n\t#include \"../generic/enc_tail.c\"\n#else\n\tbase64_enc_stub(state, src, srclen, out, outlen);\n#endif\n}\n\nint\nbase64_stream_decode_sse42 BASE64_DEC_PARAMS\n{\n#if HAVE_SSE42\n\t#include \"../generic/dec_head.c\"\n\tdec_loop_ssse3(&s, &slen, &o, &olen);\n\t#include \"../generic/dec_tail.c\"\n#if defined(__clang__)\n\t#pragma clang attribute pop\n#endif\n#else\n\treturn base64_dec_stub(state, src, srclen, out, outlen);\n#endif\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/ssse3/codec.c",
    "content": "#include <stdint.h>\n#include <stddef.h>\n#include <stdlib.h>\n\n#include \"libbase64.h\"\n#include \"../../tables/tables.h\"\n#include \"../../codecs.h\"\n#include \"config.h\"\n#include \"../../env.h\"\n\n#if HAVE_SSSE3\n#if defined(__clang__)\n#pragma clang attribute push (__attribute__((target(\"ssse3\"))), apply_to=function)\n#else\n#pragma GCC target(\"ssse3\")\n#endif\n#include <tmmintrin.h>\n\n// Only enable inline assembly on supported compilers and on 64-bit CPUs.\n// 32-bit CPUs with SSSE3 support, such as low-end Atoms, only have eight XMM\n// registers, which is not enough to run the inline assembly.\n#ifndef BASE64_SSSE3_USE_ASM\n# if (defined(__GNUC__) || defined(__clang__)) && BASE64_WORDSIZE == 64\n#  define BASE64_SSSE3_USE_ASM 1\n# else\n#  define BASE64_SSSE3_USE_ASM 0\n# endif\n#endif\n\n#include \"dec_reshuffle.c\"\n#include \"dec_loop.c\"\n\n#if BASE64_SSSE3_USE_ASM\n# include \"enc_loop_asm.c\"\n#else\n# include \"enc_reshuffle.c\"\n# include \"enc_translate.c\"\n# include \"enc_loop.c\"\n#endif\n\n#endif\t// HAVE_SSSE3\n\nvoid\nbase64_stream_encode_ssse3 BASE64_ENC_PARAMS\n{\n#if HAVE_SSSE3\n\t#include \"../generic/enc_head.c\"\n\tenc_loop_ssse3(&s, &slen, &o, &olen);\n\t#include \"../generic/enc_tail.c\"\n#else\n\tbase64_enc_stub(state, src, srclen, out, outlen);\n#endif\n}\n\nint\nbase64_stream_decode_ssse3 BASE64_DEC_PARAMS\n{\n#if HAVE_SSSE3\n\t#include \"../generic/dec_head.c\"\n\tdec_loop_ssse3(&s, &slen, &o, &olen);\n\t#include \"../generic/dec_tail.c\"\n#if defined(__clang__)\n\t#pragma clang attribute pop\n#endif\n#else\n\treturn base64_dec_stub(state, src, srclen, out, outlen);\n#endif\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/ssse3/dec_loop.c",
    "content": "// The input consists of six character sets in the Base64 alphabet, which we\n// need to map back to the 6-bit values they represent. There are three ranges,\n// two singles, and then there's the rest.\n//\n//  #  From       To        Add  Characters\n//  1  [43]       [62]      +19  +\n//  2  [47]       [63]      +16  /\n//  3  [48..57]   [52..61]   +4  0..9\n//  4  [65..90]   [0..25]   -65  A..Z\n//  5  [97..122]  [26..51]  -71  a..z\n// (6) Everything else => invalid input\n//\n// We will use lookup tables for character validation and offset computation.\n// Remember that 0x2X and 0x0X are the same index for _mm_shuffle_epi8, this\n// allows to mask with 0x2F instead of 0x0F and thus save one constant\n// declaration (register and/or memory access).\n//\n// For offsets:\n// Perfect hash for lut = ((src >> 4) & 0x2F) + ((src == 0x2F) ? 0xFF : 0x00)\n// 0000 = garbage\n// 0001 = /\n// 0010 = +\n// 0011 = 0-9\n// 0100 = A-Z\n// 0101 = A-Z\n// 0110 = a-z\n// 0111 = a-z\n// 1000 >= garbage\n//\n// For validation, here's the table.\n// A character is valid if and only if the AND of the 2 lookups equals 0:\n//\n// hi \\ lo              0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111\n//      LUT             0x15 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x11 0x13 0x1A 0x1B 0x1B 0x1B 0x1A\n//\n// 0000 0x10 char        NUL  SOH  STX  ETX  EOT  ENQ  ACK  BEL   BS   HT   LF   VT   FF   CR   SO   SI\n//           andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\n//\n// 0001 0x10 char        DLE  DC1  DC2  DC3  DC4  NAK  SYN  ETB  CAN   EM  SUB  ESC   FS   GS   RS   US\n//           andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\n//\n// 0010 0x01 char               !    \"    #    $    %    &    '    (    )    *    +    ,    -    .    /\n//           andlut     0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x01 0x00 0x01 0x01 0x01 0x00\n//\n// 0011 0x02 char          0    1    2    3    4    5    6    7    8    9    :    ;    <    =    >    ?\n//           andlut     0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x02 0x02 0x02 0x02 0x02 0x02\n//\n// 0100 0x04 char          @    A    B    C    D    E    F    G    H    I    J    K    L    M    N    O\n//           andlut     0x04 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00\n//\n// 0101 0x08 char          P    Q    R    S    T    U    V    W    X    Y    Z    [    \\    ]    ^    _\n//           andlut     0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x08 0x08 0x08 0x08 0x08\n//\n// 0110 0x04 char          `    a    b    c    d    e    f    g    h    i    j    k    l    m    n    o\n//           andlut     0x04 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00\n// 0111 0x08 char          p    q    r    s    t    u    v    w    x    y    z    {    |    }    ~\n//           andlut     0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x00 0x08 0x08 0x08 0x08 0x08\n//\n// 1000 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\n// 1001 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\n// 1010 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\n// 1011 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\n// 1100 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\n// 1101 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\n// 1110 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\n// 1111 0x10 andlut     0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10 0x10\n\nstatic BASE64_FORCE_INLINE int\ndec_loop_ssse3_inner (const uint8_t **s, uint8_t **o, size_t *rounds)\n{\n\tconst __m128i lut_lo = _mm_setr_epi8(\n\t\t0x15, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11,\n\t\t0x11, 0x11, 0x13, 0x1A, 0x1B, 0x1B, 0x1B, 0x1A);\n\n\tconst __m128i lut_hi = _mm_setr_epi8(\n\t\t0x10, 0x10, 0x01, 0x02, 0x04, 0x08, 0x04, 0x08,\n\t\t0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10);\n\n\tconst __m128i lut_roll = _mm_setr_epi8(\n\t\t0,  16,  19,   4, -65, -65, -71, -71,\n\t\t0,   0,   0,   0,   0,   0,   0,   0);\n\n\tconst __m128i mask_2F = _mm_set1_epi8(0x2F);\n\n\t// Load input:\n\t__m128i str = _mm_loadu_si128((__m128i *) *s);\n\n\t// Table lookups:\n\tconst __m128i hi_nibbles = _mm_and_si128(_mm_srli_epi32(str, 4), mask_2F);\n\tconst __m128i lo_nibbles = _mm_and_si128(str, mask_2F);\n\tconst __m128i hi         = _mm_shuffle_epi8(lut_hi, hi_nibbles);\n\tconst __m128i lo         = _mm_shuffle_epi8(lut_lo, lo_nibbles);\n\n\t// Check for invalid input: if any \"and\" values from lo and hi are not\n\t// zero, fall back on bytewise code to do error checking and reporting:\n\tif (_mm_movemask_epi8(_mm_cmpgt_epi8(_mm_and_si128(lo, hi), _mm_setzero_si128())) != 0) {\n\t\treturn 0;\n\t}\n\n\tconst __m128i eq_2F = _mm_cmpeq_epi8(str, mask_2F);\n\tconst __m128i roll  = _mm_shuffle_epi8(lut_roll, _mm_add_epi8(eq_2F, hi_nibbles));\n\n\t// Now simply add the delta values to the input:\n\tstr = _mm_add_epi8(str, roll);\n\n\t// Reshuffle the input to packed 12-byte output format:\n\tstr = dec_reshuffle(str);\n\n\t// Store the output:\n\t_mm_storeu_si128((__m128i *) *o, str);\n\n\t*s += 16;\n\t*o += 12;\n\t*rounds -= 1;\n\n\treturn 1;\n}\n\nstatic inline void\ndec_loop_ssse3 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tif (*slen < 24) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 16 bytes per round. Because 4 extra zero bytes are\n\t// written after the output, ensure that there will be at least 8 bytes\n\t// of input data left to cover the gap. (6 data bytes and up to two\n\t// end-of-string markers.)\n\tsize_t rounds = (*slen - 8) / 16;\n\n\t*slen -= rounds * 16;\t// 16 bytes consumed per round\n\t*olen += rounds * 12;\t// 12 bytes produced per round\n\n\tdo {\n\t\tif (rounds >= 8) {\n\t\t\tif (dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (rounds >= 4) {\n\t\t\tif (dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tif (rounds >= 2) {\n\t\t\tif (dec_loop_ssse3_inner(s, o, &rounds) &&\n\t\t\t    dec_loop_ssse3_inner(s, o, &rounds)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tbreak;\n\t\t}\n\t\tdec_loop_ssse3_inner(s, o, &rounds);\n\t\tbreak;\n\n\t} while (rounds > 0);\n\n\t// Adjust for any rounds that were skipped:\n\t*slen += rounds * 16;\n\t*olen -= rounds * 12;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/ssse3/dec_reshuffle.c",
    "content": "static BASE64_FORCE_INLINE __m128i\ndec_reshuffle (const __m128i in)\n{\n\t// in, bits, upper case are most significant bits, lower case are least significant bits\n\t// 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ\n\t// 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG\n\t// 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD\n\t// 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA\n\n\tconst __m128i merge_ab_and_bc = _mm_maddubs_epi16(in, _mm_set1_epi32(0x01400140));\n\t// 0000kkkk LLllllll 0000JJJJ JJjjKKKK\n\t// 0000hhhh IIiiiiii 0000GGGG GGggHHHH\n\t// 0000eeee FFffffff 0000DDDD DDddEEEE\n\t// 0000bbbb CCcccccc 0000AAAA AAaaBBBB\n\n\tconst __m128i out = _mm_madd_epi16(merge_ab_and_bc, _mm_set1_epi32(0x00011000));\n\t// 00000000 JJJJJJjj KKKKkkkk LLllllll\n\t// 00000000 GGGGGGgg HHHHhhhh IIiiiiii\n\t// 00000000 DDDDDDdd EEEEeeee FFffffff\n\t// 00000000 AAAAAAaa BBBBbbbb CCcccccc\n\n\t// Pack bytes together:\n\treturn  _mm_shuffle_epi8(out, _mm_setr_epi8(\n\t\t 2,  1,  0,\n\t\t 6,  5,  4,\n\t\t10,  9,  8,\n\t\t14, 13, 12,\n\t\t-1, -1, -1, -1));\n\t// 00000000 00000000 00000000 00000000\n\t// LLllllll KKKKkkkk JJJJJJjj IIiiiiii\n\t// HHHHhhhh GGGGGGgg FFffffff EEEEeeee\n\t// DDDDDDdd CCcccccc BBBBbbbb AAAAAAaa\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/ssse3/enc_loop.c",
    "content": "static BASE64_FORCE_INLINE void\nenc_loop_ssse3_inner (const uint8_t **s, uint8_t **o)\n{\n\t// Load input:\n\t__m128i str = _mm_loadu_si128((__m128i *) *s);\n\n\t// Reshuffle:\n\tstr = enc_reshuffle(str);\n\n\t// Translate reshuffled bytes to the Base64 alphabet:\n\tstr = enc_translate(str);\n\n\t// Store:\n\t_mm_storeu_si128((__m128i *) *o, str);\n\n\t*s += 12;\n\t*o += 16;\n}\n\nstatic inline void\nenc_loop_ssse3 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\tif (*slen < 16) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 12 bytes at a time. Because blocks are loaded 16\n\t// bytes at a time, ensure that there will be at least 4 remaining\n\t// bytes after the last round, so that the final read will not pass\n\t// beyond the bounds of the input buffer:\n\tsize_t rounds = (*slen - 4) / 12;\n\n\t*slen -= rounds * 12;\t// 12 bytes consumed per round\n\t*olen += rounds * 16;\t// 16 bytes produced per round\n\n\tdo {\n\t\tif (rounds >= 8) {\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\trounds -= 8;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 4) {\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\trounds -= 4;\n\t\t\tcontinue;\n\t\t}\n\t\tif (rounds >= 2) {\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\tenc_loop_ssse3_inner(s, o);\n\t\t\trounds -= 2;\n\t\t\tcontinue;\n\t\t}\n\t\tenc_loop_ssse3_inner(s, o);\n\t\tbreak;\n\n\t} while (rounds > 0);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/ssse3/enc_loop_asm.c",
    "content": "// Apologies in advance for combining the preprocessor with inline assembly,\n// two notoriously gnarly parts of C, but it was necessary to avoid a lot of\n// code repetition. The preprocessor is used to template large sections of\n// inline assembly that differ only in the registers used. If the code was\n// written out by hand, it would become very large and hard to audit.\n\n// Generate a block of inline assembly that loads register R0 from memory. The\n// offset at which the register is loaded is set by the given round.\n#define LOAD(R0, ROUND) \\\n\t\"lddqu (\"#ROUND\" * 12)(%[src]), %[\"R0\"] \\n\\t\"\n\n// Generate a block of inline assembly that deinterleaves and shuffles register\n// R0 using preloaded constants. Outputs in R0 and R1.\n#define SHUF(R0, R1) \\\n\t\"pshufb  %[lut0], %[\"R0\"] \\n\\t\" \\\n\t\"movdqa  %[\"R0\"], %[\"R1\"] \\n\\t\" \\\n\t\"pand    %[msk0], %[\"R0\"] \\n\\t\" \\\n\t\"pand    %[msk2], %[\"R1\"] \\n\\t\" \\\n\t\"pmulhuw %[msk1], %[\"R0\"] \\n\\t\" \\\n\t\"pmullw  %[msk3], %[\"R1\"] \\n\\t\" \\\n\t\"por     %[\"R1\"], %[\"R0\"] \\n\\t\"\n\n// Generate a block of inline assembly that takes R0 and R1 and translates\n// their contents to the base64 alphabet, using preloaded constants.\n#define TRAN(R0, R1, R2) \\\n\t\"movdqa  %[\"R0\"], %[\"R1\"] \\n\\t\" \\\n\t\"movdqa  %[\"R0\"], %[\"R2\"] \\n\\t\" \\\n\t\"psubusb %[n51],  %[\"R1\"] \\n\\t\" \\\n\t\"pcmpgtb %[n25],  %[\"R2\"] \\n\\t\" \\\n\t\"psubb   %[\"R2\"], %[\"R1\"] \\n\\t\" \\\n\t\"movdqa  %[lut1], %[\"R2\"] \\n\\t\" \\\n\t\"pshufb  %[\"R1\"], %[\"R2\"] \\n\\t\" \\\n\t\"paddb   %[\"R2\"], %[\"R0\"] \\n\\t\"\n\n// Generate a block of inline assembly that stores the given register R0 at an\n// offset set by the given round.\n#define STOR(R0, ROUND) \\\n\t\"movdqu %[\"R0\"], (\"#ROUND\" * 16)(%[dst]) \\n\\t\"\n\n// Generate a block of inline assembly that generates a single self-contained\n// encoder round: fetch the data, process it, and store the result. Then update\n// the source and destination pointers.\n#define ROUND() \\\n\tLOAD(\"a\", 0) \\\n\tSHUF(\"a\", \"b\") \\\n\tTRAN(\"a\", \"b\", \"c\") \\\n\tSTOR(\"a\", 0) \\\n\t\"add $12, %[src] \\n\\t\" \\\n\t\"add $16, %[dst] \\n\\t\"\n\n// Define a macro that initiates a three-way interleaved encoding round by\n// preloading registers a, b and c from memory.\n// The register graph shows which registers are in use during each step, and\n// is a visual aid for choosing registers for that step. Symbol index:\n//\n//  +  indicates that a register is loaded by that step.\n//  |  indicates that a register is in use and must not be touched.\n//  -  indicates that a register is decommissioned by that step.\n//  x  indicates that a register is used as a temporary by that step.\n//  V  indicates that a register is an input or output to the macro.\n//\n#define ROUND_3_INIT() \t\t\t/*  a b c d e f  */ \\\n\tLOAD(\"a\", 0)\t\t\t/*  +            */ \\\n\tSHUF(\"a\", \"d\")\t\t\t/*  |     +      */ \\\n\tLOAD(\"b\", 1)\t\t\t/*  | +   |      */ \\\n\tTRAN(\"a\", \"d\", \"e\")\t\t/*  | |   - x    */ \\\n\tLOAD(\"c\", 2)\t\t\t/*  V V V        */\n\n// Define a macro that translates, shuffles and stores the input registers A, B\n// and C, and preloads registers D, E and F for the next round.\n// This macro can be arbitrarily daisy-chained by feeding output registers D, E\n// and F back into the next round as input registers A, B and C. The macro\n// carefully interleaves memory operations with data operations for optimal\n// pipelined performance.\n\n#define ROUND_3(ROUND, A,B,C,D,E,F) \t/*  A B C D E F  */ \\\n\tLOAD(D, (ROUND + 3))\t\t/*  V V V +      */ \\\n\tSHUF(B, E)\t\t\t/*  | | | | +    */ \\\n\tSTOR(A, (ROUND + 0))\t\t/*  - | | | |    */ \\\n\tTRAN(B, E, F)\t\t\t/*    | | | - x  */ \\\n\tLOAD(E, (ROUND + 4))\t\t/*    | | | +    */ \\\n\tSHUF(C, A)\t\t\t/*  + | | | |    */ \\\n\tSTOR(B, (ROUND + 1))\t\t/*  | - | | |    */ \\\n\tTRAN(C, A, F)\t\t\t/*  -   | | | x  */ \\\n\tLOAD(F, (ROUND + 5))\t\t/*      | | | +  */ \\\n\tSHUF(D, A)\t\t\t/*  +   | | | |  */ \\\n\tSTOR(C, (ROUND + 2))\t\t/*  |   - | | |  */ \\\n\tTRAN(D, A, B)\t\t\t/*  - x   V V V  */\n\n// Define a macro that terminates a ROUND_3 macro by taking pre-loaded\n// registers D, E and F, and translating, shuffling and storing them.\n#define ROUND_3_END(ROUND, A,B,C,D,E,F)\t/*  A B C D E F  */ \\\n\tSHUF(E, A)\t\t\t/*  +     V V V  */ \\\n\tSTOR(D, (ROUND + 3))\t\t/*  |     - | |  */ \\\n\tTRAN(E, A, B)\t\t\t/*  - x     | |  */ \\\n\tSHUF(F, C)\t\t\t/*      +   | |  */ \\\n\tSTOR(E, (ROUND + 4))\t\t/*      |   - |  */ \\\n\tTRAN(F, C, D)\t\t\t/*      - x   |  */ \\\n\tSTOR(F, (ROUND + 5))\t\t/*            -  */\n\n// Define a type A round. Inputs are a, b, and c, outputs are d, e, and f.\n#define ROUND_3_A(ROUND) \\\n\tROUND_3(ROUND, \"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\n\n// Define a type B round. Inputs and outputs are swapped with regard to type A.\n#define ROUND_3_B(ROUND) \\\n\tROUND_3(ROUND, \"d\", \"e\", \"f\", \"a\", \"b\", \"c\")\n\n// Terminating macro for a type A round.\n#define ROUND_3_A_LAST(ROUND) \\\n\tROUND_3_A(ROUND) \\\n\tROUND_3_END(ROUND, \"a\", \"b\", \"c\", \"d\", \"e\", \"f\")\n\n// Terminating macro for a type B round.\n#define ROUND_3_B_LAST(ROUND) \\\n\tROUND_3_B(ROUND) \\\n\tROUND_3_END(ROUND, \"d\", \"e\", \"f\", \"a\", \"b\", \"c\")\n\n// Suppress clang's warning that the literal string in the asm statement is\n// overlong (longer than the ISO-mandated minimum size of 4095 bytes for C99\n// compilers). It may be true, but the goal here is not C99 portability.\n#pragma GCC diagnostic push\n#pragma GCC diagnostic ignored \"-Woverlength-strings\"\n\nstatic inline void\nenc_loop_ssse3 (const uint8_t **s, size_t *slen, uint8_t **o, size_t *olen)\n{\n\t// For a clearer explanation of the algorithm used by this function,\n\t// please refer to the plain (not inline assembly) implementation. This\n\t// function follows the same basic logic.\n\n\tif (*slen < 16) {\n\t\treturn;\n\t}\n\n\t// Process blocks of 12 bytes at a time. Input is read in blocks of 16\n\t// bytes, so \"reserve\" four bytes from the input buffer to ensure that\n\t// we never read beyond the end of the input buffer.\n\tsize_t rounds = (*slen - 4) / 12;\n\n\t*slen -= rounds * 12;   // 12 bytes consumed per round\n\t*olen += rounds * 16;   // 16 bytes produced per round\n\n\t// Number of times to go through the 36x loop.\n\tsize_t loops = rounds / 36;\n\n\t// Number of rounds remaining after the 36x loop.\n\trounds %= 36;\n\n\t// Lookup tables.\n\tconst __m128i lut0 = _mm_set_epi8(\n\t\t10, 11,  9, 10,  7,  8,  6,  7,  4,  5,  3,  4,  1,  2,  0,  1);\n\n\tconst __m128i lut1 = _mm_setr_epi8(\n\t\t65, 71, -4, -4, -4, -4, -4, -4, -4, -4, -4, -4, -19, -16, 0, 0);\n\n\t// Temporary registers.\n\t__m128i a, b, c, d, e, f;\n\n\t__asm__ volatile (\n\n\t\t// If there are 36 rounds or more, enter a 36x unrolled loop of\n\t\t// interleaved encoding rounds. The rounds interleave memory\n\t\t// operations (load/store) with data operations (table lookups,\n\t\t// etc) to maximize pipeline throughput.\n\t\t\"    test %[loops], %[loops] \\n\\t\"\n\t\t\"    jz   18f                \\n\\t\"\n\t\t\"    jmp  36f                \\n\\t\"\n\t\t\"                            \\n\\t\"\n\t\t\".balign 64                  \\n\\t\"\n\t\t\"36: \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A( 0)\n\t\t\"    \" ROUND_3_B( 3)\n\t\t\"    \" ROUND_3_A( 6)\n\t\t\"    \" ROUND_3_B( 9)\n\t\t\"    \" ROUND_3_A(12)\n\t\t\"    \" ROUND_3_B(15)\n\t\t\"    \" ROUND_3_A(18)\n\t\t\"    \" ROUND_3_B(21)\n\t\t\"    \" ROUND_3_A(24)\n\t\t\"    \" ROUND_3_B(27)\n\t\t\"    \" ROUND_3_A_LAST(30)\n\t\t\"    add $(12 * 36), %[src] \\n\\t\"\n\t\t\"    add $(16 * 36), %[dst] \\n\\t\"\n\t\t\"    dec %[loops]           \\n\\t\"\n\t\t\"    jnz 36b                \\n\\t\"\n\n\t\t// Enter an 18x unrolled loop for rounds of 18 or more.\n\t\t\"18: cmp $18, %[rounds] \\n\\t\"\n\t\t\"    jl  9f             \\n\\t\"\n\t\t\"    \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A(0)\n\t\t\"    \" ROUND_3_B(3)\n\t\t\"    \" ROUND_3_A(6)\n\t\t\"    \" ROUND_3_B(9)\n\t\t\"    \" ROUND_3_A_LAST(12)\n\t\t\"    sub $18,        %[rounds] \\n\\t\"\n\t\t\"    add $(12 * 18), %[src]    \\n\\t\"\n\t\t\"    add $(16 * 18), %[dst]    \\n\\t\"\n\n\t\t// Enter a 9x unrolled loop for rounds of 9 or more.\n\t\t\"9:  cmp $9, %[rounds] \\n\\t\"\n\t\t\"    jl  6f            \\n\\t\"\n\t\t\"    \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A(0)\n\t\t\"    \" ROUND_3_B_LAST(3)\n\t\t\"    sub $9,        %[rounds] \\n\\t\"\n\t\t\"    add $(12 * 9), %[src]    \\n\\t\"\n\t\t\"    add $(16 * 9), %[dst]    \\n\\t\"\n\n\t\t// Enter a 6x unrolled loop for rounds of 6 or more.\n\t\t\"6:  cmp $6, %[rounds] \\n\\t\"\n\t\t\"    jl  55f           \\n\\t\"\n\t\t\"    \" ROUND_3_INIT()\n\t\t\"    \" ROUND_3_A_LAST(0)\n\t\t\"    sub $6,        %[rounds] \\n\\t\"\n\t\t\"    add $(12 * 6), %[src]    \\n\\t\"\n\t\t\"    add $(16 * 6), %[dst]    \\n\\t\"\n\n\t\t// Dispatch the remaining rounds 0..5.\n\t\t\"55: cmp $3, %[rounds] \\n\\t\"\n\t\t\"    jg  45f           \\n\\t\"\n\t\t\"    je  3f            \\n\\t\"\n\t\t\"    cmp $1, %[rounds] \\n\\t\"\n\t\t\"    jg  2f            \\n\\t\"\n\t\t\"    je  1f            \\n\\t\"\n\t\t\"    jmp 0f            \\n\\t\"\n\n\t\t\"45: cmp $4, %[rounds] \\n\\t\"\n\t\t\"    je  4f            \\n\\t\"\n\n\t\t// Block of non-interlaced encoding rounds, which can each\n\t\t// individually be jumped to. Rounds fall through to the next.\n\t\t\"5: \" ROUND()\n\t\t\"4: \" ROUND()\n\t\t\"3: \" ROUND()\n\t\t\"2: \" ROUND()\n\t\t\"1: \" ROUND()\n\t\t\"0: \\n\\t\"\n\n\t\t// Outputs (modified).\n\t\t: [rounds] \"+r\"  (rounds),\n\t\t  [loops]  \"+r\"  (loops),\n\t\t  [src]    \"+r\"  (*s),\n\t\t  [dst]    \"+r\"  (*o),\n\t\t  [a]      \"=&x\" (a),\n\t\t  [b]      \"=&x\" (b),\n\t\t  [c]      \"=&x\" (c),\n\t\t  [d]      \"=&x\" (d),\n\t\t  [e]      \"=&x\" (e),\n\t\t  [f]      \"=&x\" (f)\n\n\t\t// Inputs (not modified).\n\t\t: [lut0] \"x\" (lut0),\n\t\t  [lut1] \"x\" (lut1),\n\t\t  [msk0] \"x\" (_mm_set1_epi32(0x0FC0FC00)),\n\t\t  [msk1] \"x\" (_mm_set1_epi32(0x04000040)),\n\t\t  [msk2] \"x\" (_mm_set1_epi32(0x003F03F0)),\n\t\t  [msk3] \"x\" (_mm_set1_epi32(0x01000010)),\n\t\t  [n51]  \"x\" (_mm_set1_epi8(51)),\n\t\t  [n25]  \"x\" (_mm_set1_epi8(25))\n\n\t\t// Clobbers.\n\t\t: \"cc\", \"memory\"\n\t);\n}\n\n#pragma GCC diagnostic pop\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/ssse3/enc_reshuffle.c",
    "content": "static BASE64_FORCE_INLINE __m128i\nenc_reshuffle (__m128i in)\n{\n\t// Input, bytes MSB to LSB:\n\t// 0 0 0 0 l k j i h g f e d c b a\n\n\tin = _mm_shuffle_epi8(in, _mm_set_epi8(\n\t\t10, 11,  9, 10,\n\t\t 7,  8,  6,  7,\n\t\t 4,  5,  3,  4,\n\t\t 1,  2,  0,  1));\n\t// in, bytes MSB to LSB:\n\t// k l j k\n\t// h i g h\n\t// e f d e\n\t// b c a b\n\n\tconst __m128i t0 = _mm_and_si128(in, _mm_set1_epi32(0x0FC0FC00));\n\t// bits, upper case are most significant bits, lower case are least significant bits\n\t// 0000kkkk LL000000 JJJJJJ00 00000000\n\t// 0000hhhh II000000 GGGGGG00 00000000\n\t// 0000eeee FF000000 DDDDDD00 00000000\n\t// 0000bbbb CC000000 AAAAAA00 00000000\n\n\tconst __m128i t1 = _mm_mulhi_epu16(t0, _mm_set1_epi32(0x04000040));\n\t// 00000000 00kkkkLL 00000000 00JJJJJJ\n\t// 00000000 00hhhhII 00000000 00GGGGGG\n\t// 00000000 00eeeeFF 00000000 00DDDDDD\n\t// 00000000 00bbbbCC 00000000 00AAAAAA\n\n\tconst __m128i t2 = _mm_and_si128(in, _mm_set1_epi32(0x003F03F0));\n\t// 00000000 00llllll 000000jj KKKK0000\n\t// 00000000 00iiiiii 000000gg HHHH0000\n\t// 00000000 00ffffff 000000dd EEEE0000\n\t// 00000000 00cccccc 000000aa BBBB0000\n\n\tconst __m128i t3 = _mm_mullo_epi16(t2, _mm_set1_epi32(0x01000010));\n\t// 00llllll 00000000 00jjKKKK 00000000\n\t// 00iiiiii 00000000 00ggHHHH 00000000\n\t// 00ffffff 00000000 00ddEEEE 00000000\n\t// 00cccccc 00000000 00aaBBBB 00000000\n\n\treturn _mm_or_si128(t1, t3);\n\t// 00llllll 00kkkkLL 00jjKKKK 00JJJJJJ\n\t// 00iiiiii 00hhhhII 00ggHHHH 00GGGGGG\n\t// 00ffffff 00eeeeFF 00ddEEEE 00DDDDDD\n\t// 00cccccc 00bbbbCC 00aaBBBB 00AAAAAA\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/arch/ssse3/enc_translate.c",
    "content": "static BASE64_FORCE_INLINE __m128i\nenc_translate (const __m128i in)\n{\n\t// A lookup table containing the absolute offsets for all ranges:\n\tconst __m128i lut = _mm_setr_epi8(\n\t\t 65,  71, -4, -4,\n\t\t -4,  -4, -4, -4,\n\t\t -4,  -4, -4, -4,\n\t\t-19, -16,  0,  0\n\t);\n\n\t// Translate values 0..63 to the Base64 alphabet. There are five sets:\n\t// #  From      To         Abs    Index  Characters\n\t// 0  [0..25]   [65..90]   +65        0  ABCDEFGHIJKLMNOPQRSTUVWXYZ\n\t// 1  [26..51]  [97..122]  +71        1  abcdefghijklmnopqrstuvwxyz\n\t// 2  [52..61]  [48..57]    -4  [2..11]  0123456789\n\t// 3  [62]      [43]       -19       12  +\n\t// 4  [63]      [47]       -16       13  /\n\n\t// Create LUT indices from the input. The index for range #0 is right,\n\t// others are 1 less than expected:\n\t__m128i indices = _mm_subs_epu8(in, _mm_set1_epi8(51));\n\n\t// mask is 0xFF (-1) for range #[1..4] and 0x00 for range #0:\n\t__m128i mask = _mm_cmpgt_epi8(in, _mm_set1_epi8(25));\n\n\t// Subtract -1, so add 1 to indices for range #[1..4]. All indices are\n\t// now correct:\n\tindices = _mm_sub_epi8(indices, mask);\n\n\t// Add offsets to input values:\n\treturn _mm_add_epi8(in, _mm_shuffle_epi8(lut, indices));\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/codec_choose.c",
    "content": "#include <stdbool.h>\n#include <stdint.h>\n#include <stddef.h>\n#include <stdint.h>\n#include <stdio.h>\n\n#include \"libbase64.h\"\n#include \"codecs.h\"\n#include \"config.h\"\n#include \"env.h\"\n\n#if (__x86_64__ || __i386__ || _M_X86 || _M_X64)\n  #define BASE64_X86\n  #if (HAVE_SSSE3 || HAVE_SSE41 || HAVE_SSE42 || HAVE_AVX || HAVE_AVX2 || HAVE_AVX512)\n    #define BASE64_X86_SIMD\n  #endif\n#endif\n\n#ifdef BASE64_X86\n#ifdef _MSC_VER\n\t#include <intrin.h>\n\t#define __cpuid_count(__level, __count, __eax, __ebx, __ecx, __edx) \\\n\t{\t\t\t\t\t\t\\\n\t\tint info[4];\t\t\t\t\\\n\t\t__cpuidex(info, __level, __count);\t\\\n\t\t__eax = info[0];\t\t\t\\\n\t\t__ebx = info[1];\t\t\t\\\n\t\t__ecx = info[2];\t\t\t\\\n\t\t__edx = info[3];\t\t\t\\\n\t}\n\t#define __cpuid(__level, __eax, __ebx, __ecx, __edx) \\\n\t\t__cpuid_count(__level, 0, __eax, __ebx, __ecx, __edx)\n#else\n\t#include <cpuid.h>\n\t#if HAVE_AVX512 || HAVE_AVX2 || HAVE_AVX\n\t\t#if ((__GNUC__ > 4 || __GNUC__ == 4 && __GNUC_MINOR__ >= 2) || (__clang_major__ >= 3))\n\t\t\tstatic inline uint64_t _xgetbv (uint32_t index)\n\t\t\t{\n\t\t\t\tuint32_t eax, edx;\n\t\t\t\t__asm__ __volatile__(\"xgetbv\" : \"=a\"(eax), \"=d\"(edx) : \"c\"(index));\n\t\t\t\treturn ((uint64_t)edx << 32) | eax;\n\t\t\t}\n\t\t#else\n\t\t\t#error \"Platform not supported\"\n\t\t#endif\n\t#endif\n#endif\n\n#ifndef bit_AVX512vl\n#define bit_AVX512vl (1 << 31)\n#endif\n#ifndef bit_AVX512vbmi\n#define bit_AVX512vbmi (1 << 1)\n#endif\n#ifndef bit_AVX2\n#define bit_AVX2 (1 << 5)\n#endif\n#ifndef bit_SSSE3\n#define bit_SSSE3 (1 << 9)\n#endif\n#ifndef bit_SSE41\n#define bit_SSE41 (1 << 19)\n#endif\n#ifndef bit_SSE42\n#define bit_SSE42 (1 << 20)\n#endif\n#ifndef bit_AVX\n#define bit_AVX (1 << 28)\n#endif\n\n#define bit_XSAVE_XRSTORE (1 << 27)\n\n#ifndef _XCR_XFEATURE_ENABLED_MASK\n#define _XCR_XFEATURE_ENABLED_MASK 0\n#endif\n\n#define bit_XMM      (1 << 1)\n#define bit_YMM      (1 << 2)\n#define bit_OPMASK   (1 << 5)\n#define bit_ZMM      (1 << 6)\n#define bit_HIGH_ZMM (1 << 7)\n\n#define _XCR_XMM_AND_YMM_STATE_ENABLED_BY_OS (bit_XMM | bit_YMM)\n\n#define _AVX_512_ENABLED_BY_OS (bit_XMM | bit_YMM | bit_OPMASK | bit_ZMM | bit_HIGH_ZMM)\n\n#endif\n\n// Function declarations:\n#define BASE64_CODEC_FUNCS(arch)\t\t\t\t\t\\\n\textern void base64_stream_encode_ ## arch BASE64_ENC_PARAMS;\t\\\n\textern int  base64_stream_decode_ ## arch BASE64_DEC_PARAMS;\n\nBASE64_CODEC_FUNCS(avx512)\nBASE64_CODEC_FUNCS(avx2)\nBASE64_CODEC_FUNCS(neon32)\nBASE64_CODEC_FUNCS(neon64)\nBASE64_CODEC_FUNCS(plain)\nBASE64_CODEC_FUNCS(ssse3)\nBASE64_CODEC_FUNCS(sse41)\nBASE64_CODEC_FUNCS(sse42)\nBASE64_CODEC_FUNCS(avx)\n\nstatic bool\ncodec_choose_forced (struct codec *codec, int flags)\n{\n\t// If the user wants to use a certain codec,\n\t// always allow it, even if the codec is a no-op.\n\t// For testing purposes.\n\n\tif (!(flags & 0xFFFF)) {\n\t\treturn false;\n\t}\n\n\tif (flags & BASE64_FORCE_AVX2) {\n\t\tcodec->enc = base64_stream_encode_avx2;\n\t\tcodec->dec = base64_stream_decode_avx2;\n\t\treturn true;\n\t}\n\tif (flags & BASE64_FORCE_NEON32) {\n\t\tcodec->enc = base64_stream_encode_neon32;\n\t\tcodec->dec = base64_stream_decode_neon32;\n\t\treturn true;\n\t}\n\tif (flags & BASE64_FORCE_NEON64) {\n\t\tcodec->enc = base64_stream_encode_neon64;\n\t\tcodec->dec = base64_stream_decode_neon64;\n\t\treturn true;\n\t}\n\tif (flags & BASE64_FORCE_PLAIN) {\n\t\tcodec->enc = base64_stream_encode_plain;\n\t\tcodec->dec = base64_stream_decode_plain;\n\t\treturn true;\n\t}\n\tif (flags & BASE64_FORCE_SSSE3) {\n\t\tcodec->enc = base64_stream_encode_ssse3;\n\t\tcodec->dec = base64_stream_decode_ssse3;\n\t\treturn true;\n\t}\n\tif (flags & BASE64_FORCE_SSE41) {\n\t\tcodec->enc = base64_stream_encode_sse41;\n\t\tcodec->dec = base64_stream_decode_sse41;\n\t\treturn true;\n\t}\n\tif (flags & BASE64_FORCE_SSE42) {\n\t\tcodec->enc = base64_stream_encode_sse42;\n\t\tcodec->dec = base64_stream_decode_sse42;\n\t\treturn true;\n\t}\n\tif (flags & BASE64_FORCE_AVX) {\n\t\tcodec->enc = base64_stream_encode_avx;\n\t\tcodec->dec = base64_stream_decode_avx;\n\t\treturn true;\n\t}\n\tif (flags & BASE64_FORCE_AVX512) {\n\t\tcodec->enc = base64_stream_encode_avx512;\n\t\tcodec->dec = base64_stream_decode_avx512;\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nstatic bool\ncodec_choose_arm (struct codec *codec)\n{\n#if HAVE_NEON64 || ((defined(__ARM_NEON__) || defined(__ARM_NEON)) && HAVE_NEON32)\n\n\t// Unfortunately there is no portable way to check for NEON\n\t// support at runtime from userland in the same way that x86\n\t// has cpuid, so just stick to the compile-time configuration:\n\n\t#if HAVE_NEON64\n\tcodec->enc = base64_stream_encode_neon64;\n\tcodec->dec = base64_stream_decode_neon64;\n\t#else\n\tcodec->enc = base64_stream_encode_neon32;\n\tcodec->dec = base64_stream_decode_neon32;\n\t#endif\n\n\treturn true;\n\n#else\n\t(void)codec;\n\treturn false;\n#endif\n}\n\nstatic bool\ncodec_choose_x86 (struct codec *codec)\n{\n#ifdef BASE64_X86_SIMD\n\n\tunsigned int eax, ebx = 0, ecx = 0, edx;\n\tunsigned int max_level;\n\n\t#ifdef _MSC_VER\n\tint info[4];\n\t__cpuidex(info, 0, 0);\n\tmax_level = info[0];\n\t#else\n\tmax_level = __get_cpuid_max(0, NULL);\n\t#endif\n\n\t#if HAVE_AVX512 || HAVE_AVX2 || HAVE_AVX\n\t// Check for AVX/AVX2/AVX512 support:\n\t// Checking for AVX requires 3 things:\n\t// 1) CPUID indicates that the OS uses XSAVE and XRSTORE instructions\n\t//    (allowing saving YMM registers on context switch)\n\t// 2) CPUID indicates support for AVX\n\t// 3) XGETBV indicates the AVX registers will be saved and restored on\n\t//    context switch\n\t//\n\t// Note that XGETBV is only available on 686 or later CPUs, so the\n\t// instruction needs to be conditionally run.\n\tif (max_level >= 1) {\n\t\t__cpuid_count(1, 0, eax, ebx, ecx, edx);\n\t\tif (ecx & bit_XSAVE_XRSTORE) {\n\t\t\tuint64_t xcr_mask;\n\t\t\txcr_mask = _xgetbv(_XCR_XFEATURE_ENABLED_MASK);\n\t\t\tif ((xcr_mask & _XCR_XMM_AND_YMM_STATE_ENABLED_BY_OS) == _XCR_XMM_AND_YMM_STATE_ENABLED_BY_OS) { // check multiple bits at once\n\t\t\t\t#if HAVE_AVX512\n\t\t\t\tif (max_level >= 7 && ((xcr_mask & _AVX_512_ENABLED_BY_OS) == _AVX_512_ENABLED_BY_OS)) {\n\t\t\t\t\t__cpuid_count(7, 0, eax, ebx, ecx, edx);\n\t\t\t\t\tif ((ebx & bit_AVX512vl) && (ecx & bit_AVX512vbmi)) {\n\t\t\t\t\t\tcodec->enc = base64_stream_encode_avx512;\n\t\t\t\t\t\tcodec->dec = base64_stream_decode_avx512;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t\t#if HAVE_AVX2\n\t\t\t\tif (max_level >= 7) {\n\t\t\t\t\t__cpuid_count(7, 0, eax, ebx, ecx, edx);\n\t\t\t\t\tif (ebx & bit_AVX2) {\n\t\t\t\t\t\tcodec->enc = base64_stream_encode_avx2;\n\t\t\t\t\t\tcodec->dec = base64_stream_decode_avx2;\n\t\t\t\t\t\treturn true;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t\t#if HAVE_AVX\n\t\t\t\t__cpuid_count(1, 0, eax, ebx, ecx, edx);\n\t\t\t\tif (ecx & bit_AVX) {\n\t\t\t\t\tcodec->enc = base64_stream_encode_avx;\n\t\t\t\t\tcodec->dec = base64_stream_decode_avx;\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\t\t\t\t#endif\n\t\t\t}\n\t\t}\n\t}\n\t#endif\n\n\t#if HAVE_SSE42\n\t// Check for SSE42 support:\n\tif (max_level >= 1) {\n\t\t__cpuid(1, eax, ebx, ecx, edx);\n\t\tif (ecx & bit_SSE42) {\n\t\t\tcodec->enc = base64_stream_encode_sse42;\n\t\t\tcodec->dec = base64_stream_decode_sse42;\n\t\t\treturn true;\n\t\t}\n\t}\n\t#endif\n\n\t#if HAVE_SSE41\n\t// Check for SSE41 support:\n\tif (max_level >= 1) {\n\t\t__cpuid(1, eax, ebx, ecx, edx);\n\t\tif (ecx & bit_SSE41) {\n\t\t\tcodec->enc = base64_stream_encode_sse41;\n\t\t\tcodec->dec = base64_stream_decode_sse41;\n\t\t\treturn true;\n\t\t}\n\t}\n\t#endif\n\n\t#if HAVE_SSSE3\n\t// Check for SSSE3 support:\n\tif (max_level >= 1) {\n\t\t__cpuid(1, eax, ebx, ecx, edx);\n\t\tif (ecx & bit_SSSE3) {\n\t\t\tcodec->enc = base64_stream_encode_ssse3;\n\t\t\tcodec->dec = base64_stream_decode_ssse3;\n\t\t\treturn true;\n\t\t}\n\t}\n\t#endif\n\n#else\n\t(void)codec;\n#endif\n\n\treturn false;\n}\n\nvoid\ncodec_choose (struct codec *codec, int flags)\n{\n\t// User forced a codec:\n\tif (codec_choose_forced(codec, flags)) {\n\t\treturn;\n\t}\n\n\t// Runtime feature detection:\n\tif (codec_choose_arm(codec)) {\n\t\treturn;\n\t}\n\tif (codec_choose_x86(codec)) {\n\t\treturn;\n\t}\n\tcodec->enc = base64_stream_encode_plain;\n\tcodec->dec = base64_stream_decode_plain;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/codecs.h",
    "content": "#include \"libbase64.h\"\n\n// Function parameters for encoding functions:\n#define BASE64_ENC_PARAMS\t\t\t\\\n\t( struct base64_state\t*state\t\t\\\n\t, const char\t\t*src\t\t\\\n\t, size_t\t\t srclen\t\t\\\n\t, char\t\t\t*out\t\t\\\n\t, size_t\t\t*outlen\t\t\\\n\t)\n\n// Function parameters for decoding functions:\n#define BASE64_DEC_PARAMS\t\t\t\\\n\t( struct base64_state\t*state\t\t\\\n\t, const char\t\t*src\t\t\\\n\t, size_t\t\t srclen\t\t\\\n\t, char\t\t\t*out\t\t\\\n\t, size_t\t\t*outlen\t\t\\\n\t)\n\n// This function is used as a stub when a certain encoder is not compiled in.\n// It discards the inputs and returns zero output bytes.\nstatic inline void\nbase64_enc_stub BASE64_ENC_PARAMS\n{\n\t(void) state;\n\t(void) src;\n\t(void) srclen;\n\t(void) out;\n\n\t*outlen = 0;\n}\n\n// This function is used as a stub when a certain decoder is not compiled in.\n// It discards the inputs and returns an invalid decoding result.\nstatic inline int\nbase64_dec_stub BASE64_DEC_PARAMS\n{\n\t(void) state;\n\t(void) src;\n\t(void) srclen;\n\t(void) out;\n\t(void) outlen;\n\n\treturn -1;\n}\n\ntypedef void (* base64_enc_fn) BASE64_ENC_PARAMS;\ntypedef int  (* base64_dec_fn) BASE64_DEC_PARAMS;\n\nstruct codec\n{\n\tbase64_enc_fn enc;\n\tbase64_dec_fn dec;\n};\n\nextern void codec_choose (struct codec *, int flags);\n"
  },
  {
    "path": "mypyc/lib-rt/base64/config.h",
    "content": "#ifndef BASE64_CONFIG_H\n#define BASE64_CONFIG_H\n\n#if !defined(__APPLE__) && ((defined(__x86_64__) && defined(__LP64__)) || defined(_M_X64))\n  #define HAVE_SSSE3 1\n  #define HAVE_SSE41 1\n  #define HAVE_SSE42 1\n  #define HAVE_AVX 1\n  #define HAVE_AVX2 1\n  #define HAVE_AVX512 0\n#elif (defined(__APPLE__) && defined(__aarch64__))\n  #define HAVE_NEON64 1\n#elif (defined(__wasm__) && defined(__wasm_simd128__))\n  #include \"emscripten/version.h\"\n  #if __EMSCRIPTEN_major__ == 3\n    #define HAVE_NEON32 1\n  #elif __EMSCRIPTEN_major__ > 3\n    #define HAVE_NEON64 1\n  #endif\n#endif\n\n#endif // BASE64_CONFIG_H\n"
  },
  {
    "path": "mypyc/lib-rt/base64/env.h",
    "content": "#ifndef BASE64_ENV_H\n#define BASE64_ENV_H\n\n#include <stdint.h>\n\n// This header file contains macro definitions that describe certain aspects of\n// the compile-time environment. Compatibility and portability macros go here.\n\n// Define machine endianness. This is for GCC:\n#if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)\n#  define BASE64_LITTLE_ENDIAN 1\n#else\n#  define BASE64_LITTLE_ENDIAN 0\n#endif\n\n// This is for Clang:\n#ifdef __LITTLE_ENDIAN__\n#  define BASE64_LITTLE_ENDIAN 1\n#endif\n\n#ifdef __BIG_ENDIAN__\n#  define BASE64_LITTLE_ENDIAN 0\n#endif\n\n// MSVC++ needs intrin.h for _byteswap_uint64 (issue #68):\n#if BASE64_LITTLE_ENDIAN && defined(_MSC_VER)\n#  include <intrin.h>\n#endif\n\n// Endian conversion functions:\n#if BASE64_LITTLE_ENDIAN\n#  ifdef _MSC_VER\n//   Microsoft Visual C++:\n#    define BASE64_HTOBE32(x)\t_byteswap_ulong(x)\n#    define BASE64_HTOBE64(x)\t_byteswap_uint64(x)\n#  else\n//   GCC and Clang:\n#    define BASE64_HTOBE32(x)\t__builtin_bswap32(x)\n#    define BASE64_HTOBE64(x)\t__builtin_bswap64(x)\n#  endif\n#else\n// No conversion needed:\n#  define BASE64_HTOBE32(x)\t(x)\n#  define BASE64_HTOBE64(x)\t(x)\n#endif\n\n// Detect word size:\n#if defined (__x86_64__)\n// This also works for the x32 ABI, which has a 64-bit word size.\n#  define BASE64_WORDSIZE 64\n#elif SIZE_MAX == UINT32_MAX\n#  define BASE64_WORDSIZE 32\n#elif SIZE_MAX == UINT64_MAX\n#  define BASE64_WORDSIZE 64\n#else\n#  error BASE64_WORDSIZE_NOT_DEFINED\n#endif\n\n// End-of-file definitions.\n// Almost end-of-file when waiting for the last '=' character:\n#define BASE64_AEOF 1\n// End-of-file when stream end has been reached or invalid input provided:\n#define BASE64_EOF 2\n\n// GCC 7 defaults to issuing a warning for fallthrough in switch statements,\n// unless the fallthrough cases are marked with an attribute. As we use\n// fallthrough deliberately, define an alias for the attribute:\n#if __GNUC__ >= 7\n#  define BASE64_FALLTHROUGH  __attribute__((fallthrough));\n#else\n#  define BASE64_FALLTHROUGH\n#endif\n\n// Declare macros to ensure that functions that are intended to be inlined, are\n// actually inlined, even when no optimization is applied. A lot of inner loop\n// code is factored into separate functions for reasons of readability, but\n// that code should always be inlined (and optimized) in the main loop.\n#ifdef _MSC_VER\n#  define BASE64_FORCE_INLINE\t__forceinline\n#else\n#  define BASE64_FORCE_INLINE  inline __attribute__((always_inline))\n#endif\n\n#endif\t// BASE64_ENV_H\n"
  },
  {
    "path": "mypyc/lib-rt/base64/lib.c",
    "content": "#include <stdint.h>\n#include <stddef.h>\n#ifdef _OPENMP\n#include <omp.h>\n#endif\n\n#include \"libbase64.h\"\n#include \"tables/tables.h\"\n#include \"codecs.h\"\n#include \"env.h\"\n\n// These static function pointers are initialized once when the library is\n// first used, and remain in use for the remaining lifetime of the program.\n// The idea being that CPU features don't change at runtime.\nstatic struct codec codec = { NULL, NULL };\n\nvoid\nbase64_stream_encode_init (struct base64_state *state, int flags)\n{\n\t// If any of the codec flags are set, redo choice:\n\tif (codec.enc == NULL || flags & 0xFF) {\n\t\tcodec_choose(&codec, flags);\n\t}\n\tstate->eof = 0;\n\tstate->bytes = 0;\n\tstate->carry = 0;\n\tstate->flags = flags;\n}\n\nvoid\nbase64_stream_encode\n\t( struct base64_state\t*state\n\t, const char\t\t*src\n\t, size_t\t\t srclen\n\t, char\t\t\t*out\n\t, size_t\t\t*outlen\n\t)\n{\n\tcodec.enc(state, src, srclen, out, outlen);\n}\n\nvoid\nbase64_stream_encode_final\n\t( struct base64_state\t*state\n\t, char\t\t\t*out\n\t, size_t\t\t*outlen\n\t)\n{\n\tuint8_t *o = (uint8_t *)out;\n\n\tif (state->bytes == 1) {\n\t\t*o++ = base64_table_enc_6bit[state->carry];\n\t\t*o++ = '=';\n\t\t*o++ = '=';\n\t\t*outlen = 3;\n\t\treturn;\n\t}\n\tif (state->bytes == 2) {\n\t\t*o++ = base64_table_enc_6bit[state->carry];\n\t\t*o++ = '=';\n\t\t*outlen = 2;\n\t\treturn;\n\t}\n\t*outlen = 0;\n}\n\nvoid\nbase64_stream_decode_init (struct base64_state *state, int flags)\n{\n\t// If any of the codec flags are set, redo choice:\n\tif (codec.dec == NULL || flags & 0xFFFF) {\n\t\tcodec_choose(&codec, flags);\n\t}\n\tstate->eof = 0;\n\tstate->bytes = 0;\n\tstate->carry = 0;\n\tstate->flags = flags;\n}\n\nint\nbase64_stream_decode\n\t( struct base64_state\t*state\n\t, const char\t\t*src\n\t, size_t\t\t srclen\n\t, char\t\t\t*out\n\t, size_t\t\t*outlen\n\t)\n{\n\treturn codec.dec(state, src, srclen, out, outlen);\n}\n\n#ifdef _OPENMP\n\n\t// Due to the overhead of initializing OpenMP and creating a team of\n\t// threads, we require the data length to be larger than a threshold:\n\t#define OMP_THRESHOLD 20000\n\n\t// Conditionally include OpenMP-accelerated codec implementations:\n\t#include \"lib_openmp.c\"\n#endif\n\nvoid\nbase64_encode\n\t( const char\t*src\n\t, size_t\t srclen\n\t, char\t\t*out\n\t, size_t\t*outlen\n\t, int\t\t flags\n\t)\n{\n\tsize_t s;\n\tsize_t t;\n\tstruct base64_state state;\n\n\t#ifdef _OPENMP\n\tif (srclen >= OMP_THRESHOLD) {\n\t\tbase64_encode_openmp(src, srclen, out, outlen, flags);\n\t\treturn;\n\t}\n\t#endif\n\n\t// Init the stream reader:\n\tbase64_stream_encode_init(&state, flags);\n\n\t// Feed the whole string to the stream reader:\n\tbase64_stream_encode(&state, src, srclen, out, &s);\n\n\t// Finalize the stream by writing trailer if any:\n\tbase64_stream_encode_final(&state, out + s, &t);\n\n\t// Final output length is stream length plus tail:\n\t*outlen = s + t;\n}\n\nint\nbase64_decode\n\t( const char\t*src\n\t, size_t\t srclen\n\t, char\t\t*out\n\t, size_t\t*outlen\n\t, int\t\t flags\n\t)\n{\n\tint ret;\n\tstruct base64_state state;\n\n\t#ifdef _OPENMP\n\tif (srclen >= OMP_THRESHOLD) {\n\t\treturn base64_decode_openmp(src, srclen, out, outlen, flags);\n\t}\n\t#endif\n\n\t// Init the stream reader:\n\tbase64_stream_decode_init(&state, flags);\n\n\t// Feed the whole string to the stream reader:\n\tret = base64_stream_decode(&state, src, srclen, out, outlen);\n\n\t// If when decoding a whole block, we're still waiting for input then fail:\n\tif (ret && (state.bytes == 0)) {\n\t\treturn ret;\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/lib_openmp.c",
    "content": "// This code makes some assumptions on the implementation of\n// base64_stream_encode_init(), base64_stream_encode() and base64_stream_decode().\n// Basically these assumptions boil down to that when breaking the src into\n// parts, out parts can be written without side effects.\n// This is met when:\n// 1) base64_stream_encode() and base64_stream_decode() don't use globals;\n// 2) the shared variables src and out are not read or written outside of the\n//    bounds of their parts, i.e.  when base64_stream_encode() reads a multiple\n//    of 3 bytes, it must write no more then a multiple of 4 bytes, not even\n//    temporarily;\n// 3) the state flag can be discarded after base64_stream_encode() and\n//    base64_stream_decode() on the parts.\n\nstatic inline void\nbase64_encode_openmp\n\t( const char\t*src\n\t, size_t\t srclen\n\t, char\t\t*out\n\t, size_t\t*outlen\n\t, int\t\t flags\n\t)\n{\n\tsize_t s;\n\tsize_t t;\n\tsize_t sum = 0, len, last_len;\n\tstruct base64_state state, initial_state;\n\tint num_threads, i;\n\n\t// Request a number of threads but not necessarily get them:\n\t#pragma omp parallel\n\t{\n\t\t// Get the number of threads used from one thread only,\n\t\t// as num_threads is a shared var:\n\t\t#pragma omp single\n\t\t{\n\t\t\tnum_threads = omp_get_num_threads();\n\n\t\t\t// Split the input string into num_threads parts, each\n\t\t\t// part a multiple of 3 bytes. The remaining bytes will\n\t\t\t// be done later:\n\t\t\tlen = srclen / (num_threads * 3);\n\t\t\tlen *= 3;\n\t\t\tlast_len = srclen - num_threads * len;\n\n\t\t\t// Init the stream reader:\n\t\t\tbase64_stream_encode_init(&state, flags);\n\t\t\tinitial_state = state;\n\t\t}\n\n\t\t// Single has an implicit barrier for all threads to wait here\n\t\t// for the above to complete:\n\t\t#pragma omp for firstprivate(state) private(s) reduction(+:sum) schedule(static,1)\n\t\tfor (i = 0; i < num_threads; i++)\n\t\t{\n\t\t\t// Feed each part of the string to the stream reader:\n\t\t\tbase64_stream_encode(&state, src + i * len, len, out + i * len * 4 / 3, &s);\n\t\t\tsum += s;\n\t\t}\n\t}\n\n\t// As encoding should never fail and we encode an exact multiple\n\t// of 3 bytes, we can discard state:\n\tstate = initial_state;\n\n\t// Encode the remaining bytes:\n\tbase64_stream_encode(&state, src + num_threads * len, last_len, out + num_threads * len * 4 / 3, &s);\n\n\t// Finalize the stream by writing trailer if any:\n\tbase64_stream_encode_final(&state, out + num_threads * len * 4 / 3 + s, &t);\n\n\t// Final output length is stream length plus tail:\n\tsum += s + t;\n\t*outlen = sum;\n}\n\nstatic inline int\nbase64_decode_openmp\n\t( const char\t*src\n\t, size_t\t srclen\n\t, char\t\t*out\n\t, size_t\t*outlen\n\t, int\t\t flags\n\t)\n{\n\tint num_threads, result = 0, i;\n\tsize_t sum = 0, len, last_len, s;\n\tstruct base64_state state, initial_state;\n\n\t// Request a number of threads but not necessarily get them:\n\t#pragma omp parallel\n\t{\n\t\t// Get the number of threads used from one thread only,\n\t\t// as num_threads is a shared var:\n\t\t#pragma omp single\n\t\t{\n\t\t\tnum_threads = omp_get_num_threads();\n\n\t\t\t// Split the input string into num_threads parts, each\n\t\t\t// part a multiple of 4 bytes. The remaining bytes will\n\t\t\t// be done later:\n\t\t\tlen = srclen / (num_threads * 4);\n\t\t\tlen *= 4;\n\t\t\tlast_len = srclen - num_threads * len;\n\n\t\t\t// Init the stream reader:\n\t\t\tbase64_stream_decode_init(&state, flags);\n\n\t\t\tinitial_state = state;\n\t\t}\n\n\t\t// Single has an implicit barrier to wait here for the above to\n\t\t// complete:\n\t\t#pragma omp for firstprivate(state) private(s) reduction(+:sum, result) schedule(static,1)\n\t\tfor (i = 0; i < num_threads; i++)\n\t\t{\n\t\t\tint this_result;\n\n\t\t\t// Feed each part of the string to the stream reader:\n\t\t\tthis_result = base64_stream_decode(&state, src + i * len, len, out + i * len * 3 / 4, &s);\n\t\t\tsum += s;\n\t\t\tresult += this_result;\n\t\t}\n\t}\n\n\t// If `result' equals `-num_threads', then all threads returned -1,\n\t// indicating that the requested codec is not available:\n\tif (result == -num_threads) {\n\t\treturn -1;\n\t}\n\n\t// If `result' does not equal `num_threads', then at least one of the\n\t// threads hit a decode error:\n\tif (result != num_threads) {\n\t\treturn 0;\n\t}\n\n\t// So far so good, now decode whatever remains in the buffer. Reuse the\n\t// initial state, since we are at a 4-byte boundary:\n\tstate = initial_state;\n\tresult = base64_stream_decode(&state, src + num_threads * len, last_len, out + num_threads * len * 3 / 4, &s);\n\tsum += s;\n\t*outlen = sum;\n\n\t// If when decoding a whole block, we're still waiting for input then fail:\n\tif (result && (state.bytes == 0)) {\n\t\treturn result;\n\t}\n\treturn 0;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/libbase64.h",
    "content": "#ifndef LIBBASE64_H\n#define LIBBASE64_H\n\n#include <stddef.h>\t/* size_t */\n\n\n#if defined(_WIN32) || defined(__CYGWIN__)\n#define BASE64_SYMBOL_IMPORT __declspec(dllimport)\n#define BASE64_SYMBOL_EXPORT __declspec(dllexport)\n#define BASE64_SYMBOL_PRIVATE\n\n#elif __GNUC__ >= 4\n#define BASE64_SYMBOL_IMPORT   __attribute__ ((visibility (\"default\")))\n#define BASE64_SYMBOL_EXPORT   __attribute__ ((visibility (\"default\")))\n#define BASE64_SYMBOL_PRIVATE  __attribute__ ((visibility (\"hidden\")))\n\n#else\n#define BASE64_SYMBOL_IMPORT\n#define BASE64_SYMBOL_EXPORT\n#define BASE64_SYMBOL_PRIVATE\n#endif\n\n#if defined(BASE64_STATIC_DEFINE)\n#define BASE64_EXPORT\n#define BASE64_NO_EXPORT\n\n#else\n#if defined(BASE64_EXPORTS) // defined if we are building the shared library\n#define BASE64_EXPORT BASE64_SYMBOL_EXPORT\n\n#else\n#define BASE64_EXPORT BASE64_SYMBOL_IMPORT\n#endif\n\n#define BASE64_NO_EXPORT BASE64_SYMBOL_PRIVATE\n#endif\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* These are the flags that can be passed in the `flags` argument. The values\n * below force the use of a given codec, even if that codec is a no-op in the\n * current build. Used in testing. Set to 0 for the default behavior, which is\n * runtime feature detection on x86, a compile-time fixed codec on ARM, and\n * the plain codec on other platforms: */\n#define BASE64_FORCE_AVX2\t(1 << 0)\n#define BASE64_FORCE_NEON32\t(1 << 1)\n#define BASE64_FORCE_NEON64\t(1 << 2)\n#define BASE64_FORCE_PLAIN\t(1 << 3)\n#define BASE64_FORCE_SSSE3\t(1 << 4)\n#define BASE64_FORCE_SSE41\t(1 << 5)\n#define BASE64_FORCE_SSE42\t(1 << 6)\n#define BASE64_FORCE_AVX\t(1 << 7)\n#define BASE64_FORCE_AVX512\t(1 << 8)\n\nstruct base64_state {\n\tint eof;\n\tint bytes;\n\tint flags;\n\tunsigned char carry;\n};\n\n/* Wrapper function to encode a plain string of given length. Output is written\n * to *out without trailing zero. Output length in bytes is written to *outlen.\n * The buffer in `out` has been allocated by the caller and is at least 4/3 the\n * size of the input. See above for `flags`; set to 0 for default operation: */\nvoid BASE64_EXPORT base64_encode\n\t( const char\t\t*src\n\t, size_t\t\t srclen\n\t, char\t\t\t*out\n\t, size_t\t\t*outlen\n\t, int\t\t\t flags\n\t) ;\n\n/* Call this before calling base64_stream_encode() to init the state. See above\n * for `flags`; set to 0 for default operation: */\nvoid BASE64_EXPORT base64_stream_encode_init\n\t( struct base64_state\t*state\n\t, int\t\t\t flags\n\t) ;\n\n/* Encodes the block of data of given length at `src`, into the buffer at\n * `out`. Caller is responsible for allocating a large enough out-buffer; it\n * must be at least 4/3 the size of the in-buffer, but take some margin. Places\n * the number of new bytes written into `outlen` (which is set to zero when the\n * function starts). Does not zero-terminate or finalize the output. */\nvoid BASE64_EXPORT base64_stream_encode\n\t( struct base64_state\t*state\n\t, const char\t\t*src\n\t, size_t\t\t srclen\n\t, char\t\t\t*out\n\t, size_t\t\t*outlen\n\t) ;\n\n/* Finalizes the output begun by previous calls to `base64_stream_encode()`.\n * Adds the required end-of-stream markers if appropriate. `outlen` is modified\n * and will contain the number of new bytes written at `out` (which will quite\n * often be zero). */\nvoid BASE64_EXPORT base64_stream_encode_final\n\t( struct base64_state\t*state\n\t, char\t\t\t*out\n\t, size_t\t\t*outlen\n\t) ;\n\n/* Wrapper function to decode a plain string of given length. Output is written\n * to *out without trailing zero. Output length in bytes is written to *outlen.\n * The buffer in `out` has been allocated by the caller and is at least 3/4 the\n * size of the input. See above for `flags`, set to 0 for default operation: */\nint BASE64_EXPORT base64_decode\n\t( const char\t\t*src\n\t, size_t\t\t srclen\n\t, char\t\t\t*out\n\t, size_t\t\t*outlen\n\t, int\t\t\t flags\n\t) ;\n\n/* Call this before calling base64_stream_decode() to init the state. See above\n * for `flags`; set to 0 for default operation: */\nvoid BASE64_EXPORT base64_stream_decode_init\n\t( struct base64_state\t*state\n\t, int\t\t\t flags\n\t) ;\n\n/* Decodes the block of data of given length at `src`, into the buffer at\n * `out`. Caller is responsible for allocating a large enough out-buffer; it\n * must be at least 3/4 the size of the in-buffer, but take some margin. Places\n * the number of new bytes written into `outlen` (which is set to zero when the\n * function starts). Does not zero-terminate the output. Returns 1 if all is\n * well, and 0 if a decoding error was found, such as an invalid character.\n * Returns -1 if the chosen codec is not included in the current build. Used by\n * the test harness to check whether a codec is available for testing. */\nint BASE64_EXPORT base64_stream_decode\n\t( struct base64_state\t*state\n\t, const char\t\t*src\n\t, size_t\t\t srclen\n\t, char\t\t\t*out\n\t, size_t\t\t*outlen\n\t) ;\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif /* LIBBASE64_H */\n"
  },
  {
    "path": "mypyc/lib-rt/base64/librt_base64.c",
    "content": "#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <stdbool.h>\n\n#define BASE64_EXPORTS\n\n#include \"librt_base64.h\"\n#include \"libbase64.h\"\n#include \"pythoncapi_compat.h\"\n\nstatic PyObject *\nb64decode_handle_invalid_input(\n    PyObject *out_bytes, char *outbuf, size_t max_out, const char *src, size_t srclen, bool freesrc);\n\n#define BASE64_MAXBIN ((PY_SSIZE_T_MAX - 3) / 2)\n\n#define STACK_BUFFER_SIZE 1024\n\nstatic void\nconvert_encoded_to_urlsafe(char *buf, size_t len) {\n    // The loop is written to enable SIMD optimizations\n    for (size_t i = 0; i < len; i++) {\n        char ch = buf[i];\n        if (ch == '+') {\n            ch = '-';\n        } else if (ch == '/') {\n            ch = '_';\n        }\n        buf[i] = ch;\n    }\n}\n\nstatic void\nconvert_urlsafe_to_encoded(const char *src, size_t len, char *buf) {\n    // The loop is written to enable SIMD optimizations\n    for (size_t i = 0; i < len; i++) {\n        char ch = src[i];\n        if (ch == '-') {\n            ch = '+';\n        } else if (ch == '_') {\n            ch = '/';\n        }\n        buf[i] = ch;\n    }\n}\n\nstatic PyObject *\nb64encode_internal(PyObject *obj, bool urlsafe) {\n    unsigned char *ascii_data;\n    char *bin_data;\n    int leftbits = 0;\n    unsigned char this_ch;\n    unsigned int leftchar = 0;\n    Py_ssize_t bin_len, out_len;\n    PyBytesWriter *writer;\n    int newline = 0; // TODO\n\n    if (!PyBytes_Check(obj)) {\n        PyErr_SetString(PyExc_TypeError, \"base64() expects a bytes object\");\n        return NULL;\n    }\n\n    bin_data = PyBytes_AS_STRING(obj);\n    bin_len = PyBytes_GET_SIZE(obj);\n    assert(bin_len >= 0);\n\n    if (bin_len > BASE64_MAXBIN) {\n        PyErr_SetString(PyExc_ValueError, \"Too much data for base64 line\");\n        return NULL;\n    }\n\n    Py_ssize_t buflen = 4 * bin_len / 3 + 4;\n    char *buf;\n    char stack_buf[STACK_BUFFER_SIZE];\n    if (buflen <= STACK_BUFFER_SIZE) {\n        buf = stack_buf;\n    } else {\n        buf = PyMem_Malloc(buflen);\n        if (buf == NULL) {\n            return PyErr_NoMemory();\n        }\n    }\n    size_t actual_len;\n    base64_encode(bin_data, bin_len, buf, &actual_len, 0);\n\n    if (urlsafe) {\n        convert_encoded_to_urlsafe(buf, actual_len);\n    }\n\n    PyObject *res = PyBytes_FromStringAndSize(buf, actual_len);\n    if (buflen > STACK_BUFFER_SIZE)\n        PyMem_Free(buf);\n    return res;\n}\n\nstatic PyObject*\nb64encode(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (nargs != 1) {\n        PyErr_SetString(PyExc_TypeError, \"b64encode() takes exactly one argument\");\n        return 0;\n    }\n    return b64encode_internal(args[0], false);\n}\n\nstatic PyObject*\nurlsafe_b64encode(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (nargs != 1) {\n        PyErr_SetString(PyExc_TypeError, \"urlsafe_b64encode() takes exactly one argument\");\n        return 0;\n    }\n    return b64encode_internal(args[0], true);\n}\n\nstatic inline int\nis_valid_base64_char(char c, bool allow_padding) {\n    return ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') ||\n            (c >= '0' && c <= '9') || (c == '+') || (c == '/') || (allow_padding && c == '='));\n}\n\nstatic PyObject *\nb64decode_internal(PyObject *arg, bool urlsafe) {\n    const char *src;\n    Py_ssize_t srclen_ssz;\n\n    // Get input pointer and length\n    if (PyBytes_Check(arg)) {\n        src = PyBytes_AS_STRING(arg);\n        srclen_ssz = PyBytes_GET_SIZE(arg);\n    } else if (PyUnicode_Check(arg)) {\n        if (!PyUnicode_IS_ASCII(arg)) {\n            PyErr_SetString(PyExc_ValueError,\n                            \"string argument should contain only ASCII characters\");\n            return NULL;\n        }\n        src = (const char *)PyUnicode_1BYTE_DATA(arg);\n        srclen_ssz = PyUnicode_GET_LENGTH(arg);\n    } else {\n        PyErr_SetString(PyExc_TypeError,\n                        \"argument should be a bytes-like object or ASCII string\");\n        return NULL;\n    }\n\n    // Fast-path: empty input\n    if (srclen_ssz == 0) {\n        return PyBytes_FromStringAndSize(NULL, 0);\n    }\n\n    if (urlsafe) {\n        char *new_src = PyMem_Malloc(srclen_ssz + 1);\n        if (new_src == NULL) {\n            return PyErr_NoMemory();\n        }\n        convert_urlsafe_to_encoded(src, srclen_ssz, new_src);\n        src = new_src;\n    }\n\n    // Quickly ignore invalid characters at the end. Other invalid characters\n    // are also accepted, but they need a slow path.\n    while (srclen_ssz > 0 && !is_valid_base64_char(src[srclen_ssz - 1], true)) {\n        srclen_ssz--;\n    }\n\n    // Compute an output capacity that's at least 3/4 of input, without overflow:\n    // ceil(3/4 * N) == N - floor(N/4)\n    size_t srclen = (size_t)srclen_ssz;\n    size_t max_out = srclen - (srclen / 4);\n    if (max_out == 0) {\n        max_out = 1; // defensive (srclen > 0 implies >= 1 anyway)\n    }\n    if (max_out > (size_t)PY_SSIZE_T_MAX) {\n        PyErr_SetString(PyExc_OverflowError, \"input too large\");\n        return NULL;\n    }\n\n    // Allocate output bytes (uninitialized) of the max capacity\n    PyObject *out_bytes = PyBytes_FromStringAndSize(NULL, (Py_ssize_t)max_out);\n    if (out_bytes == NULL) {\n        if (urlsafe) {\n            PyMem_Free((void *)src);\n        }\n        return NULL; // Propagate memory error\n    }\n\n    char *outbuf = PyBytes_AS_STRING(out_bytes);\n    size_t outlen = max_out;\n\n    int ret = base64_decode(src, srclen, outbuf, &outlen, 0);\n\n    if (ret != 1) {\n        if (ret == 0) {\n            // Slow path: handle non-base64 input\n            return b64decode_handle_invalid_input(out_bytes, outbuf, max_out, src, srclen, urlsafe);\n        }\n        Py_DECREF(out_bytes);\n        if (urlsafe) {\n            PyMem_Free((void *)src);\n        }\n        if (ret == -1) {\n            PyErr_SetString(PyExc_NotImplementedError, \"base64 codec not available in this build\");\n        } else {\n            PyErr_SetString(PyExc_RuntimeError, \"base64_decode failed\");\n        }\n        return NULL;\n    }\n\n    if (urlsafe) {\n        PyMem_Free((void *)src);\n    }\n\n    // Sanity-check contract (decoder must not overflow our buffer)\n    if (outlen > max_out) {\n        Py_DECREF(out_bytes);\n        PyErr_SetString(PyExc_RuntimeError, \"decoder wrote past output buffer\");\n        return NULL;\n    }\n\n    // Shrink in place to the actual decoded length\n    if (_PyBytes_Resize(&out_bytes, (Py_ssize_t)outlen) < 0) {\n        // _PyBytes_Resize sets an exception and may free the old object\n        return NULL;\n    }\n    return out_bytes;\n}\n\n// Process non-base64 input by ignoring non-base64 characters, for compatibility\n// with stdlib b64decode.\nstatic PyObject *\nb64decode_handle_invalid_input(\n    PyObject *out_bytes, char *outbuf, size_t max_out, const char *src, size_t srclen, bool freesrc)\n{\n    // Copy input to a temporary buffer, with non-base64 characters and extra suffix\n    // characters removed\n    size_t newbuf_len = 0;\n    char *newbuf = PyMem_Malloc(srclen);\n    if (newbuf == NULL) {\n        Py_DECREF(out_bytes);\n        if (freesrc) {\n            PyMem_Free((void *)src);\n        }\n        return PyErr_NoMemory();\n    }\n\n    // Copy base64 characters and some padding to the new buffer\n    for (size_t i = 0; i < srclen; i++) {\n        char c = src[i];\n        if (is_valid_base64_char(c, false)) {\n            newbuf[newbuf_len++] = c;\n        } else if (c == '=') {\n            // Copy a necessary amount of padding\n            int remainder = newbuf_len % 4;\n            if (remainder == 0) {\n                // No padding needed\n                break;\n            }\n            int numpad = 4 - remainder;\n            // Check that there is at least the required amount padding (CPython ignores\n            // extra padding)\n            while (numpad > 0) {\n                if (i == srclen || src[i] != '=') {\n                    break;\n                }\n                newbuf[newbuf_len++] = '=';\n                i++;\n                numpad--;\n                // Skip non-base64 alphabet characters within padding\n                while (i < srclen && !is_valid_base64_char(src[i], true)) {\n                    i++;\n                }\n            }\n            break;\n        }\n    }\n\n    // Stdlib always performs a non-strict padding check\n    if (newbuf_len % 4 != 0) {\n        if (freesrc) {\n            PyMem_Free((void *)src);\n        }\n        Py_DECREF(out_bytes);\n        PyMem_Free(newbuf);\n        PyErr_SetString(PyExc_ValueError, \"Incorrect padding\");\n        return NULL;\n    }\n\n    size_t outlen = max_out;\n    int ret = base64_decode(newbuf, newbuf_len, outbuf, &outlen, 0);\n    PyMem_Free(newbuf);\n    if (freesrc) {\n        PyMem_Free((void *)src);\n    }\n\n    if (ret != 1) {\n        Py_DECREF(out_bytes);\n        if (ret == 0) {\n            PyErr_SetString(PyExc_ValueError, \"Only base64 data is allowed\");\n        }\n        if (ret == -1) {\n            PyErr_SetString(PyExc_NotImplementedError, \"base64 codec not available in this build\");\n        } else {\n            PyErr_SetString(PyExc_RuntimeError, \"base64_decode failed\");\n        }\n        return NULL;\n    }\n\n    // Shrink in place to the actual decoded length\n    if (_PyBytes_Resize(&out_bytes, (Py_ssize_t)outlen) < 0) {\n        // _PyBytes_Resize sets an exception and may free the old object\n        return NULL;\n    }\n    return out_bytes;\n}\n\nstatic PyObject*\nb64decode(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (nargs != 1) {\n        PyErr_SetString(PyExc_TypeError, \"b64decode() takes exactly one argument\");\n        return 0;\n    }\n    return b64decode_internal(args[0], false);\n}\n\nstatic PyObject*\nurlsafe_b64decode(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (nargs != 1) {\n        PyErr_SetString(PyExc_TypeError, \"urlsafe_b64decode() takes exactly one argument\");\n        return 0;\n    }\n    return b64decode_internal(args[0], true);\n}\n\nstatic PyMethodDef librt_base64_module_methods[] = {\n    {\"b64encode\", (PyCFunction)b64encode, METH_FASTCALL, PyDoc_STR(\"Encode bytes object using Base64.\")},\n    {\"b64decode\", (PyCFunction)b64decode, METH_FASTCALL, PyDoc_STR(\"Decode a Base64 encoded bytes object or ASCII string.\")},\n    {\"urlsafe_b64encode\", (PyCFunction)urlsafe_b64encode, METH_FASTCALL, PyDoc_STR(\"Encode bytes object using URL and file system safe Base64 alphabet.\")},\n    {\"urlsafe_b64decode\", (PyCFunction)urlsafe_b64decode, METH_FASTCALL, PyDoc_STR(\"Decode bytes or ASCII string using URL and file system safe Base64 alphabet.\")},\n    {NULL, NULL, 0, NULL}\n};\n\nstatic int\nbase64_abi_version(void) {\n    return LIBRT_BASE64_ABI_VERSION;\n}\n\nstatic int\nbase64_api_version(void) {\n    return LIBRT_BASE64_API_VERSION;\n}\n\nstatic int\nlibrt_base64_module_exec(PyObject *m)\n{\n    // Export mypy internal C API, be careful with the order!\n    static void *base64_api[LIBRT_BASE64_API_LEN] = {\n        (void *)base64_abi_version,\n        (void *)base64_api_version,\n        (void *)b64encode_internal,\n        (void *)b64decode_internal,\n    };\n    PyObject *c_api_object = PyCapsule_New((void *)base64_api, \"librt.base64._C_API\", NULL);\n    if (PyModule_Add(m, \"_C_API\", c_api_object) < 0) {\n        return -1;\n    }\n    return 0;\n}\n\nstatic PyModuleDef_Slot librt_base64_module_slots[] = {\n    {Py_mod_exec, librt_base64_module_exec},\n#ifdef Py_MOD_GIL_NOT_USED\n    {Py_mod_gil, Py_MOD_GIL_NOT_USED},\n#endif\n    {0, NULL}\n};\n\nstatic PyModuleDef librt_base64_module = {\n    .m_base = PyModuleDef_HEAD_INIT,\n    .m_name = \"base64\",\n    .m_doc = \"Fast base64 encoding and decoding optimized for mypyc\",\n    .m_size = 0,\n    .m_methods = librt_base64_module_methods,\n    .m_slots = librt_base64_module_slots,\n};\n\nPyMODINIT_FUNC\nPyInit_base64(void)\n{\n    return PyModuleDef_Init(&librt_base64_module);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/base64/librt_base64.h",
    "content": "#ifndef LIBRT_BASE64_H\n#define LIBRT_BASE64_H\n\n#include <Python.h>\n\n#define LIBRT_BASE64_ABI_VERSION 1\n#define LIBRT_BASE64_API_VERSION 2\n#define LIBRT_BASE64_API_LEN 4\n\nstatic void *LibRTBase64_API[LIBRT_BASE64_API_LEN];\n\n#define LibRTBase64_ABIVersion (*(int (*)(void)) LibRTBase64_API[0])\n#define LibRTBase64_APIVersion (*(int (*)(void)) LibRTBase64_API[1])\n#define LibRTBase64_b64encode_internal (*(PyObject* (*)(PyObject *source, bool urlsafe)) LibRTBase64_API[2])\n#define LibRTBase64_b64decode_internal (*(PyObject* (*)(PyObject *source, bool urlsafe)) LibRTBase64_API[3])\n\nstatic int\nimport_librt_base64(void)\n{\n    PyObject *mod = PyImport_ImportModule(\"librt.base64\");\n    if (mod == NULL)\n        return -1;\n    Py_DECREF(mod);  // we import just for the side effect of making the below work.\n    void *capsule = PyCapsule_Import(\"librt.base64._C_API\", 0);\n    if (capsule == NULL)\n        return -1;\n    memcpy(LibRTBase64_API, capsule, sizeof(LibRTBase64_API));\n    if (LibRTBase64_ABIVersion() != LIBRT_BASE64_ABI_VERSION) {\n        char err[128];\n        snprintf(err, sizeof(err), \"ABI version conflict for librt.base64, expected %d, found %d\",\n            LIBRT_BASE64_ABI_VERSION,\n            LibRTBase64_ABIVersion()\n        );\n        PyErr_SetString(PyExc_ValueError, err);\n        return -1;\n    }\n    if (LibRTBase64_APIVersion() < LIBRT_BASE64_API_VERSION) {\n        char err[128];\n        snprintf(err, sizeof(err),\n                 \"API version conflict for librt.base64, expected %d or newer, found %d (hint: upgrade librt)\",\n            LIBRT_BASE64_API_VERSION,\n            LibRTBase64_APIVersion()\n        );\n        PyErr_SetString(PyExc_ValueError, err);\n        return -1;\n    }\n    return 0;\n}\n\n#endif  // LIBRT_BASE64_H\n"
  },
  {
    "path": "mypyc/lib-rt/base64/tables/table_dec_32bit.h",
    "content": "#include <stdint.h>\n#define CHAR62 '+'\n#define CHAR63 '/'\n#define CHARPAD '='\n\n\n#if BASE64_LITTLE_ENDIAN\n\n\n/* SPECIAL DECODE TABLES FOR LITTLE ENDIAN (INTEL) CPUS */\n\nconst uint32_t base64_table_dec_32bit_d0[256] = {\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x000000f8, 0xffffffff, 0xffffffff, 0xffffffff, 0x000000fc,\n0x000000d0, 0x000000d4, 0x000000d8, 0x000000dc, 0x000000e0, 0x000000e4,\n0x000000e8, 0x000000ec, 0x000000f0, 0x000000f4, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,\n0x00000004, 0x00000008, 0x0000000c, 0x00000010, 0x00000014, 0x00000018,\n0x0000001c, 0x00000020, 0x00000024, 0x00000028, 0x0000002c, 0x00000030,\n0x00000034, 0x00000038, 0x0000003c, 0x00000040, 0x00000044, 0x00000048,\n0x0000004c, 0x00000050, 0x00000054, 0x00000058, 0x0000005c, 0x00000060,\n0x00000064, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x00000068, 0x0000006c, 0x00000070, 0x00000074, 0x00000078,\n0x0000007c, 0x00000080, 0x00000084, 0x00000088, 0x0000008c, 0x00000090,\n0x00000094, 0x00000098, 0x0000009c, 0x000000a0, 0x000000a4, 0x000000a8,\n0x000000ac, 0x000000b0, 0x000000b4, 0x000000b8, 0x000000bc, 0x000000c0,\n0x000000c4, 0x000000c8, 0x000000cc, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff\n};\n\n\nconst uint32_t base64_table_dec_32bit_d1[256] = {\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x0000e003, 0xffffffff, 0xffffffff, 0xffffffff, 0x0000f003,\n0x00004003, 0x00005003, 0x00006003, 0x00007003, 0x00008003, 0x00009003,\n0x0000a003, 0x0000b003, 0x0000c003, 0x0000d003, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,\n0x00001000, 0x00002000, 0x00003000, 0x00004000, 0x00005000, 0x00006000,\n0x00007000, 0x00008000, 0x00009000, 0x0000a000, 0x0000b000, 0x0000c000,\n0x0000d000, 0x0000e000, 0x0000f000, 0x00000001, 0x00001001, 0x00002001,\n0x00003001, 0x00004001, 0x00005001, 0x00006001, 0x00007001, 0x00008001,\n0x00009001, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x0000a001, 0x0000b001, 0x0000c001, 0x0000d001, 0x0000e001,\n0x0000f001, 0x00000002, 0x00001002, 0x00002002, 0x00003002, 0x00004002,\n0x00005002, 0x00006002, 0x00007002, 0x00008002, 0x00009002, 0x0000a002,\n0x0000b002, 0x0000c002, 0x0000d002, 0x0000e002, 0x0000f002, 0x00000003,\n0x00001003, 0x00002003, 0x00003003, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff\n};\n\n\nconst uint32_t base64_table_dec_32bit_d2[256] = {\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x00800f00, 0xffffffff, 0xffffffff, 0xffffffff, 0x00c00f00,\n0x00000d00, 0x00400d00, 0x00800d00, 0x00c00d00, 0x00000e00, 0x00400e00,\n0x00800e00, 0x00c00e00, 0x00000f00, 0x00400f00, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,\n0x00400000, 0x00800000, 0x00c00000, 0x00000100, 0x00400100, 0x00800100,\n0x00c00100, 0x00000200, 0x00400200, 0x00800200, 0x00c00200, 0x00000300,\n0x00400300, 0x00800300, 0x00c00300, 0x00000400, 0x00400400, 0x00800400,\n0x00c00400, 0x00000500, 0x00400500, 0x00800500, 0x00c00500, 0x00000600,\n0x00400600, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x00800600, 0x00c00600, 0x00000700, 0x00400700, 0x00800700,\n0x00c00700, 0x00000800, 0x00400800, 0x00800800, 0x00c00800, 0x00000900,\n0x00400900, 0x00800900, 0x00c00900, 0x00000a00, 0x00400a00, 0x00800a00,\n0x00c00a00, 0x00000b00, 0x00400b00, 0x00800b00, 0x00c00b00, 0x00000c00,\n0x00400c00, 0x00800c00, 0x00c00c00, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff\n};\n\n\nconst uint32_t base64_table_dec_32bit_d3[256] = {\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x003e0000, 0xffffffff, 0xffffffff, 0xffffffff, 0x003f0000,\n0x00340000, 0x00350000, 0x00360000, 0x00370000, 0x00380000, 0x00390000,\n0x003a0000, 0x003b0000, 0x003c0000, 0x003d0000, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,\n0x00010000, 0x00020000, 0x00030000, 0x00040000, 0x00050000, 0x00060000,\n0x00070000, 0x00080000, 0x00090000, 0x000a0000, 0x000b0000, 0x000c0000,\n0x000d0000, 0x000e0000, 0x000f0000, 0x00100000, 0x00110000, 0x00120000,\n0x00130000, 0x00140000, 0x00150000, 0x00160000, 0x00170000, 0x00180000,\n0x00190000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x001a0000, 0x001b0000, 0x001c0000, 0x001d0000, 0x001e0000,\n0x001f0000, 0x00200000, 0x00210000, 0x00220000, 0x00230000, 0x00240000,\n0x00250000, 0x00260000, 0x00270000, 0x00280000, 0x00290000, 0x002a0000,\n0x002b0000, 0x002c0000, 0x002d0000, 0x002e0000, 0x002f0000, 0x00300000,\n0x00310000, 0x00320000, 0x00330000, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff\n};\n\n\n#else\n\n\n/* SPECIAL DECODE TABLES FOR BIG ENDIAN (IBM/MOTOROLA/SUN) CPUS */\n\nconst uint32_t base64_table_dec_32bit_d0[256] = {\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xf8000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xfc000000,\n0xd0000000, 0xd4000000, 0xd8000000, 0xdc000000, 0xe0000000, 0xe4000000,\n0xe8000000, 0xec000000, 0xf0000000, 0xf4000000, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,\n0x04000000, 0x08000000, 0x0c000000, 0x10000000, 0x14000000, 0x18000000,\n0x1c000000, 0x20000000, 0x24000000, 0x28000000, 0x2c000000, 0x30000000,\n0x34000000, 0x38000000, 0x3c000000, 0x40000000, 0x44000000, 0x48000000,\n0x4c000000, 0x50000000, 0x54000000, 0x58000000, 0x5c000000, 0x60000000,\n0x64000000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x68000000, 0x6c000000, 0x70000000, 0x74000000, 0x78000000,\n0x7c000000, 0x80000000, 0x84000000, 0x88000000, 0x8c000000, 0x90000000,\n0x94000000, 0x98000000, 0x9c000000, 0xa0000000, 0xa4000000, 0xa8000000,\n0xac000000, 0xb0000000, 0xb4000000, 0xb8000000, 0xbc000000, 0xc0000000,\n0xc4000000, 0xc8000000, 0xcc000000, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff\n};\n\n\nconst uint32_t base64_table_dec_32bit_d1[256] = {\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x03e00000, 0xffffffff, 0xffffffff, 0xffffffff, 0x03f00000,\n0x03400000, 0x03500000, 0x03600000, 0x03700000, 0x03800000, 0x03900000,\n0x03a00000, 0x03b00000, 0x03c00000, 0x03d00000, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,\n0x00100000, 0x00200000, 0x00300000, 0x00400000, 0x00500000, 0x00600000,\n0x00700000, 0x00800000, 0x00900000, 0x00a00000, 0x00b00000, 0x00c00000,\n0x00d00000, 0x00e00000, 0x00f00000, 0x01000000, 0x01100000, 0x01200000,\n0x01300000, 0x01400000, 0x01500000, 0x01600000, 0x01700000, 0x01800000,\n0x01900000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x01a00000, 0x01b00000, 0x01c00000, 0x01d00000, 0x01e00000,\n0x01f00000, 0x02000000, 0x02100000, 0x02200000, 0x02300000, 0x02400000,\n0x02500000, 0x02600000, 0x02700000, 0x02800000, 0x02900000, 0x02a00000,\n0x02b00000, 0x02c00000, 0x02d00000, 0x02e00000, 0x02f00000, 0x03000000,\n0x03100000, 0x03200000, 0x03300000, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff\n};\n\n\nconst uint32_t base64_table_dec_32bit_d2[256] = {\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x000f8000, 0xffffffff, 0xffffffff, 0xffffffff, 0x000fc000,\n0x000d0000, 0x000d4000, 0x000d8000, 0x000dc000, 0x000e0000, 0x000e4000,\n0x000e8000, 0x000ec000, 0x000f0000, 0x000f4000, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,\n0x00004000, 0x00008000, 0x0000c000, 0x00010000, 0x00014000, 0x00018000,\n0x0001c000, 0x00020000, 0x00024000, 0x00028000, 0x0002c000, 0x00030000,\n0x00034000, 0x00038000, 0x0003c000, 0x00040000, 0x00044000, 0x00048000,\n0x0004c000, 0x00050000, 0x00054000, 0x00058000, 0x0005c000, 0x00060000,\n0x00064000, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x00068000, 0x0006c000, 0x00070000, 0x00074000, 0x00078000,\n0x0007c000, 0x00080000, 0x00084000, 0x00088000, 0x0008c000, 0x00090000,\n0x00094000, 0x00098000, 0x0009c000, 0x000a0000, 0x000a4000, 0x000a8000,\n0x000ac000, 0x000b0000, 0x000b4000, 0x000b8000, 0x000bc000, 0x000c0000,\n0x000c4000, 0x000c8000, 0x000cc000, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff\n};\n\n\nconst uint32_t base64_table_dec_32bit_d3[256] = {\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x00003e00, 0xffffffff, 0xffffffff, 0xffffffff, 0x00003f00,\n0x00003400, 0x00003500, 0x00003600, 0x00003700, 0x00003800, 0x00003900,\n0x00003a00, 0x00003b00, 0x00003c00, 0x00003d00, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,\n0x00000100, 0x00000200, 0x00000300, 0x00000400, 0x00000500, 0x00000600,\n0x00000700, 0x00000800, 0x00000900, 0x00000a00, 0x00000b00, 0x00000c00,\n0x00000d00, 0x00000e00, 0x00000f00, 0x00001000, 0x00001100, 0x00001200,\n0x00001300, 0x00001400, 0x00001500, 0x00001600, 0x00001700, 0x00001800,\n0x00001900, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0x00001a00, 0x00001b00, 0x00001c00, 0x00001d00, 0x00001e00,\n0x00001f00, 0x00002000, 0x00002100, 0x00002200, 0x00002300, 0x00002400,\n0x00002500, 0x00002600, 0x00002700, 0x00002800, 0x00002900, 0x00002a00,\n0x00002b00, 0x00002c00, 0x00002d00, 0x00002e00, 0x00002f00, 0x00003000,\n0x00003100, 0x00003200, 0x00003300, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff,\n0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff\n};\n\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/base64/tables/table_enc_12bit.h",
    "content": "#include <stdint.h>\n\nconst uint16_t base64_table_enc_12bit[] = {\n#if BASE64_LITTLE_ENDIAN\n\t0x4141U, 0x4241U, 0x4341U, 0x4441U, 0x4541U, 0x4641U, 0x4741U, 0x4841U,\n\t0x4941U, 0x4A41U, 0x4B41U, 0x4C41U, 0x4D41U, 0x4E41U, 0x4F41U, 0x5041U,\n\t0x5141U, 0x5241U, 0x5341U, 0x5441U, 0x5541U, 0x5641U, 0x5741U, 0x5841U,\n\t0x5941U, 0x5A41U, 0x6141U, 0x6241U, 0x6341U, 0x6441U, 0x6541U, 0x6641U,\n\t0x6741U, 0x6841U, 0x6941U, 0x6A41U, 0x6B41U, 0x6C41U, 0x6D41U, 0x6E41U,\n\t0x6F41U, 0x7041U, 0x7141U, 0x7241U, 0x7341U, 0x7441U, 0x7541U, 0x7641U,\n\t0x7741U, 0x7841U, 0x7941U, 0x7A41U, 0x3041U, 0x3141U, 0x3241U, 0x3341U,\n\t0x3441U, 0x3541U, 0x3641U, 0x3741U, 0x3841U, 0x3941U, 0x2B41U, 0x2F41U,\n\t0x4142U, 0x4242U, 0x4342U, 0x4442U, 0x4542U, 0x4642U, 0x4742U, 0x4842U,\n\t0x4942U, 0x4A42U, 0x4B42U, 0x4C42U, 0x4D42U, 0x4E42U, 0x4F42U, 0x5042U,\n\t0x5142U, 0x5242U, 0x5342U, 0x5442U, 0x5542U, 0x5642U, 0x5742U, 0x5842U,\n\t0x5942U, 0x5A42U, 0x6142U, 0x6242U, 0x6342U, 0x6442U, 0x6542U, 0x6642U,\n\t0x6742U, 0x6842U, 0x6942U, 0x6A42U, 0x6B42U, 0x6C42U, 0x6D42U, 0x6E42U,\n\t0x6F42U, 0x7042U, 0x7142U, 0x7242U, 0x7342U, 0x7442U, 0x7542U, 0x7642U,\n\t0x7742U, 0x7842U, 0x7942U, 0x7A42U, 0x3042U, 0x3142U, 0x3242U, 0x3342U,\n\t0x3442U, 0x3542U, 0x3642U, 0x3742U, 0x3842U, 0x3942U, 0x2B42U, 0x2F42U,\n\t0x4143U, 0x4243U, 0x4343U, 0x4443U, 0x4543U, 0x4643U, 0x4743U, 0x4843U,\n\t0x4943U, 0x4A43U, 0x4B43U, 0x4C43U, 0x4D43U, 0x4E43U, 0x4F43U, 0x5043U,\n\t0x5143U, 0x5243U, 0x5343U, 0x5443U, 0x5543U, 0x5643U, 0x5743U, 0x5843U,\n\t0x5943U, 0x5A43U, 0x6143U, 0x6243U, 0x6343U, 0x6443U, 0x6543U, 0x6643U,\n\t0x6743U, 0x6843U, 0x6943U, 0x6A43U, 0x6B43U, 0x6C43U, 0x6D43U, 0x6E43U,\n\t0x6F43U, 0x7043U, 0x7143U, 0x7243U, 0x7343U, 0x7443U, 0x7543U, 0x7643U,\n\t0x7743U, 0x7843U, 0x7943U, 0x7A43U, 0x3043U, 0x3143U, 0x3243U, 0x3343U,\n\t0x3443U, 0x3543U, 0x3643U, 0x3743U, 0x3843U, 0x3943U, 0x2B43U, 0x2F43U,\n\t0x4144U, 0x4244U, 0x4344U, 0x4444U, 0x4544U, 0x4644U, 0x4744U, 0x4844U,\n\t0x4944U, 0x4A44U, 0x4B44U, 0x4C44U, 0x4D44U, 0x4E44U, 0x4F44U, 0x5044U,\n\t0x5144U, 0x5244U, 0x5344U, 0x5444U, 0x5544U, 0x5644U, 0x5744U, 0x5844U,\n\t0x5944U, 0x5A44U, 0x6144U, 0x6244U, 0x6344U, 0x6444U, 0x6544U, 0x6644U,\n\t0x6744U, 0x6844U, 0x6944U, 0x6A44U, 0x6B44U, 0x6C44U, 0x6D44U, 0x6E44U,\n\t0x6F44U, 0x7044U, 0x7144U, 0x7244U, 0x7344U, 0x7444U, 0x7544U, 0x7644U,\n\t0x7744U, 0x7844U, 0x7944U, 0x7A44U, 0x3044U, 0x3144U, 0x3244U, 0x3344U,\n\t0x3444U, 0x3544U, 0x3644U, 0x3744U, 0x3844U, 0x3944U, 0x2B44U, 0x2F44U,\n\t0x4145U, 0x4245U, 0x4345U, 0x4445U, 0x4545U, 0x4645U, 0x4745U, 0x4845U,\n\t0x4945U, 0x4A45U, 0x4B45U, 0x4C45U, 0x4D45U, 0x4E45U, 0x4F45U, 0x5045U,\n\t0x5145U, 0x5245U, 0x5345U, 0x5445U, 0x5545U, 0x5645U, 0x5745U, 0x5845U,\n\t0x5945U, 0x5A45U, 0x6145U, 0x6245U, 0x6345U, 0x6445U, 0x6545U, 0x6645U,\n\t0x6745U, 0x6845U, 0x6945U, 0x6A45U, 0x6B45U, 0x6C45U, 0x6D45U, 0x6E45U,\n\t0x6F45U, 0x7045U, 0x7145U, 0x7245U, 0x7345U, 0x7445U, 0x7545U, 0x7645U,\n\t0x7745U, 0x7845U, 0x7945U, 0x7A45U, 0x3045U, 0x3145U, 0x3245U, 0x3345U,\n\t0x3445U, 0x3545U, 0x3645U, 0x3745U, 0x3845U, 0x3945U, 0x2B45U, 0x2F45U,\n\t0x4146U, 0x4246U, 0x4346U, 0x4446U, 0x4546U, 0x4646U, 0x4746U, 0x4846U,\n\t0x4946U, 0x4A46U, 0x4B46U, 0x4C46U, 0x4D46U, 0x4E46U, 0x4F46U, 0x5046U,\n\t0x5146U, 0x5246U, 0x5346U, 0x5446U, 0x5546U, 0x5646U, 0x5746U, 0x5846U,\n\t0x5946U, 0x5A46U, 0x6146U, 0x6246U, 0x6346U, 0x6446U, 0x6546U, 0x6646U,\n\t0x6746U, 0x6846U, 0x6946U, 0x6A46U, 0x6B46U, 0x6C46U, 0x6D46U, 0x6E46U,\n\t0x6F46U, 0x7046U, 0x7146U, 0x7246U, 0x7346U, 0x7446U, 0x7546U, 0x7646U,\n\t0x7746U, 0x7846U, 0x7946U, 0x7A46U, 0x3046U, 0x3146U, 0x3246U, 0x3346U,\n\t0x3446U, 0x3546U, 0x3646U, 0x3746U, 0x3846U, 0x3946U, 0x2B46U, 0x2F46U,\n\t0x4147U, 0x4247U, 0x4347U, 0x4447U, 0x4547U, 0x4647U, 0x4747U, 0x4847U,\n\t0x4947U, 0x4A47U, 0x4B47U, 0x4C47U, 0x4D47U, 0x4E47U, 0x4F47U, 0x5047U,\n\t0x5147U, 0x5247U, 0x5347U, 0x5447U, 0x5547U, 0x5647U, 0x5747U, 0x5847U,\n\t0x5947U, 0x5A47U, 0x6147U, 0x6247U, 0x6347U, 0x6447U, 0x6547U, 0x6647U,\n\t0x6747U, 0x6847U, 0x6947U, 0x6A47U, 0x6B47U, 0x6C47U, 0x6D47U, 0x6E47U,\n\t0x6F47U, 0x7047U, 0x7147U, 0x7247U, 0x7347U, 0x7447U, 0x7547U, 0x7647U,\n\t0x7747U, 0x7847U, 0x7947U, 0x7A47U, 0x3047U, 0x3147U, 0x3247U, 0x3347U,\n\t0x3447U, 0x3547U, 0x3647U, 0x3747U, 0x3847U, 0x3947U, 0x2B47U, 0x2F47U,\n\t0x4148U, 0x4248U, 0x4348U, 0x4448U, 0x4548U, 0x4648U, 0x4748U, 0x4848U,\n\t0x4948U, 0x4A48U, 0x4B48U, 0x4C48U, 0x4D48U, 0x4E48U, 0x4F48U, 0x5048U,\n\t0x5148U, 0x5248U, 0x5348U, 0x5448U, 0x5548U, 0x5648U, 0x5748U, 0x5848U,\n\t0x5948U, 0x5A48U, 0x6148U, 0x6248U, 0x6348U, 0x6448U, 0x6548U, 0x6648U,\n\t0x6748U, 0x6848U, 0x6948U, 0x6A48U, 0x6B48U, 0x6C48U, 0x6D48U, 0x6E48U,\n\t0x6F48U, 0x7048U, 0x7148U, 0x7248U, 0x7348U, 0x7448U, 0x7548U, 0x7648U,\n\t0x7748U, 0x7848U, 0x7948U, 0x7A48U, 0x3048U, 0x3148U, 0x3248U, 0x3348U,\n\t0x3448U, 0x3548U, 0x3648U, 0x3748U, 0x3848U, 0x3948U, 0x2B48U, 0x2F48U,\n\t0x4149U, 0x4249U, 0x4349U, 0x4449U, 0x4549U, 0x4649U, 0x4749U, 0x4849U,\n\t0x4949U, 0x4A49U, 0x4B49U, 0x4C49U, 0x4D49U, 0x4E49U, 0x4F49U, 0x5049U,\n\t0x5149U, 0x5249U, 0x5349U, 0x5449U, 0x5549U, 0x5649U, 0x5749U, 0x5849U,\n\t0x5949U, 0x5A49U, 0x6149U, 0x6249U, 0x6349U, 0x6449U, 0x6549U, 0x6649U,\n\t0x6749U, 0x6849U, 0x6949U, 0x6A49U, 0x6B49U, 0x6C49U, 0x6D49U, 0x6E49U,\n\t0x6F49U, 0x7049U, 0x7149U, 0x7249U, 0x7349U, 0x7449U, 0x7549U, 0x7649U,\n\t0x7749U, 0x7849U, 0x7949U, 0x7A49U, 0x3049U, 0x3149U, 0x3249U, 0x3349U,\n\t0x3449U, 0x3549U, 0x3649U, 0x3749U, 0x3849U, 0x3949U, 0x2B49U, 0x2F49U,\n\t0x414AU, 0x424AU, 0x434AU, 0x444AU, 0x454AU, 0x464AU, 0x474AU, 0x484AU,\n\t0x494AU, 0x4A4AU, 0x4B4AU, 0x4C4AU, 0x4D4AU, 0x4E4AU, 0x4F4AU, 0x504AU,\n\t0x514AU, 0x524AU, 0x534AU, 0x544AU, 0x554AU, 0x564AU, 0x574AU, 0x584AU,\n\t0x594AU, 0x5A4AU, 0x614AU, 0x624AU, 0x634AU, 0x644AU, 0x654AU, 0x664AU,\n\t0x674AU, 0x684AU, 0x694AU, 0x6A4AU, 0x6B4AU, 0x6C4AU, 0x6D4AU, 0x6E4AU,\n\t0x6F4AU, 0x704AU, 0x714AU, 0x724AU, 0x734AU, 0x744AU, 0x754AU, 0x764AU,\n\t0x774AU, 0x784AU, 0x794AU, 0x7A4AU, 0x304AU, 0x314AU, 0x324AU, 0x334AU,\n\t0x344AU, 0x354AU, 0x364AU, 0x374AU, 0x384AU, 0x394AU, 0x2B4AU, 0x2F4AU,\n\t0x414BU, 0x424BU, 0x434BU, 0x444BU, 0x454BU, 0x464BU, 0x474BU, 0x484BU,\n\t0x494BU, 0x4A4BU, 0x4B4BU, 0x4C4BU, 0x4D4BU, 0x4E4BU, 0x4F4BU, 0x504BU,\n\t0x514BU, 0x524BU, 0x534BU, 0x544BU, 0x554BU, 0x564BU, 0x574BU, 0x584BU,\n\t0x594BU, 0x5A4BU, 0x614BU, 0x624BU, 0x634BU, 0x644BU, 0x654BU, 0x664BU,\n\t0x674BU, 0x684BU, 0x694BU, 0x6A4BU, 0x6B4BU, 0x6C4BU, 0x6D4BU, 0x6E4BU,\n\t0x6F4BU, 0x704BU, 0x714BU, 0x724BU, 0x734BU, 0x744BU, 0x754BU, 0x764BU,\n\t0x774BU, 0x784BU, 0x794BU, 0x7A4BU, 0x304BU, 0x314BU, 0x324BU, 0x334BU,\n\t0x344BU, 0x354BU, 0x364BU, 0x374BU, 0x384BU, 0x394BU, 0x2B4BU, 0x2F4BU,\n\t0x414CU, 0x424CU, 0x434CU, 0x444CU, 0x454CU, 0x464CU, 0x474CU, 0x484CU,\n\t0x494CU, 0x4A4CU, 0x4B4CU, 0x4C4CU, 0x4D4CU, 0x4E4CU, 0x4F4CU, 0x504CU,\n\t0x514CU, 0x524CU, 0x534CU, 0x544CU, 0x554CU, 0x564CU, 0x574CU, 0x584CU,\n\t0x594CU, 0x5A4CU, 0x614CU, 0x624CU, 0x634CU, 0x644CU, 0x654CU, 0x664CU,\n\t0x674CU, 0x684CU, 0x694CU, 0x6A4CU, 0x6B4CU, 0x6C4CU, 0x6D4CU, 0x6E4CU,\n\t0x6F4CU, 0x704CU, 0x714CU, 0x724CU, 0x734CU, 0x744CU, 0x754CU, 0x764CU,\n\t0x774CU, 0x784CU, 0x794CU, 0x7A4CU, 0x304CU, 0x314CU, 0x324CU, 0x334CU,\n\t0x344CU, 0x354CU, 0x364CU, 0x374CU, 0x384CU, 0x394CU, 0x2B4CU, 0x2F4CU,\n\t0x414DU, 0x424DU, 0x434DU, 0x444DU, 0x454DU, 0x464DU, 0x474DU, 0x484DU,\n\t0x494DU, 0x4A4DU, 0x4B4DU, 0x4C4DU, 0x4D4DU, 0x4E4DU, 0x4F4DU, 0x504DU,\n\t0x514DU, 0x524DU, 0x534DU, 0x544DU, 0x554DU, 0x564DU, 0x574DU, 0x584DU,\n\t0x594DU, 0x5A4DU, 0x614DU, 0x624DU, 0x634DU, 0x644DU, 0x654DU, 0x664DU,\n\t0x674DU, 0x684DU, 0x694DU, 0x6A4DU, 0x6B4DU, 0x6C4DU, 0x6D4DU, 0x6E4DU,\n\t0x6F4DU, 0x704DU, 0x714DU, 0x724DU, 0x734DU, 0x744DU, 0x754DU, 0x764DU,\n\t0x774DU, 0x784DU, 0x794DU, 0x7A4DU, 0x304DU, 0x314DU, 0x324DU, 0x334DU,\n\t0x344DU, 0x354DU, 0x364DU, 0x374DU, 0x384DU, 0x394DU, 0x2B4DU, 0x2F4DU,\n\t0x414EU, 0x424EU, 0x434EU, 0x444EU, 0x454EU, 0x464EU, 0x474EU, 0x484EU,\n\t0x494EU, 0x4A4EU, 0x4B4EU, 0x4C4EU, 0x4D4EU, 0x4E4EU, 0x4F4EU, 0x504EU,\n\t0x514EU, 0x524EU, 0x534EU, 0x544EU, 0x554EU, 0x564EU, 0x574EU, 0x584EU,\n\t0x594EU, 0x5A4EU, 0x614EU, 0x624EU, 0x634EU, 0x644EU, 0x654EU, 0x664EU,\n\t0x674EU, 0x684EU, 0x694EU, 0x6A4EU, 0x6B4EU, 0x6C4EU, 0x6D4EU, 0x6E4EU,\n\t0x6F4EU, 0x704EU, 0x714EU, 0x724EU, 0x734EU, 0x744EU, 0x754EU, 0x764EU,\n\t0x774EU, 0x784EU, 0x794EU, 0x7A4EU, 0x304EU, 0x314EU, 0x324EU, 0x334EU,\n\t0x344EU, 0x354EU, 0x364EU, 0x374EU, 0x384EU, 0x394EU, 0x2B4EU, 0x2F4EU,\n\t0x414FU, 0x424FU, 0x434FU, 0x444FU, 0x454FU, 0x464FU, 0x474FU, 0x484FU,\n\t0x494FU, 0x4A4FU, 0x4B4FU, 0x4C4FU, 0x4D4FU, 0x4E4FU, 0x4F4FU, 0x504FU,\n\t0x514FU, 0x524FU, 0x534FU, 0x544FU, 0x554FU, 0x564FU, 0x574FU, 0x584FU,\n\t0x594FU, 0x5A4FU, 0x614FU, 0x624FU, 0x634FU, 0x644FU, 0x654FU, 0x664FU,\n\t0x674FU, 0x684FU, 0x694FU, 0x6A4FU, 0x6B4FU, 0x6C4FU, 0x6D4FU, 0x6E4FU,\n\t0x6F4FU, 0x704FU, 0x714FU, 0x724FU, 0x734FU, 0x744FU, 0x754FU, 0x764FU,\n\t0x774FU, 0x784FU, 0x794FU, 0x7A4FU, 0x304FU, 0x314FU, 0x324FU, 0x334FU,\n\t0x344FU, 0x354FU, 0x364FU, 0x374FU, 0x384FU, 0x394FU, 0x2B4FU, 0x2F4FU,\n\t0x4150U, 0x4250U, 0x4350U, 0x4450U, 0x4550U, 0x4650U, 0x4750U, 0x4850U,\n\t0x4950U, 0x4A50U, 0x4B50U, 0x4C50U, 0x4D50U, 0x4E50U, 0x4F50U, 0x5050U,\n\t0x5150U, 0x5250U, 0x5350U, 0x5450U, 0x5550U, 0x5650U, 0x5750U, 0x5850U,\n\t0x5950U, 0x5A50U, 0x6150U, 0x6250U, 0x6350U, 0x6450U, 0x6550U, 0x6650U,\n\t0x6750U, 0x6850U, 0x6950U, 0x6A50U, 0x6B50U, 0x6C50U, 0x6D50U, 0x6E50U,\n\t0x6F50U, 0x7050U, 0x7150U, 0x7250U, 0x7350U, 0x7450U, 0x7550U, 0x7650U,\n\t0x7750U, 0x7850U, 0x7950U, 0x7A50U, 0x3050U, 0x3150U, 0x3250U, 0x3350U,\n\t0x3450U, 0x3550U, 0x3650U, 0x3750U, 0x3850U, 0x3950U, 0x2B50U, 0x2F50U,\n\t0x4151U, 0x4251U, 0x4351U, 0x4451U, 0x4551U, 0x4651U, 0x4751U, 0x4851U,\n\t0x4951U, 0x4A51U, 0x4B51U, 0x4C51U, 0x4D51U, 0x4E51U, 0x4F51U, 0x5051U,\n\t0x5151U, 0x5251U, 0x5351U, 0x5451U, 0x5551U, 0x5651U, 0x5751U, 0x5851U,\n\t0x5951U, 0x5A51U, 0x6151U, 0x6251U, 0x6351U, 0x6451U, 0x6551U, 0x6651U,\n\t0x6751U, 0x6851U, 0x6951U, 0x6A51U, 0x6B51U, 0x6C51U, 0x6D51U, 0x6E51U,\n\t0x6F51U, 0x7051U, 0x7151U, 0x7251U, 0x7351U, 0x7451U, 0x7551U, 0x7651U,\n\t0x7751U, 0x7851U, 0x7951U, 0x7A51U, 0x3051U, 0x3151U, 0x3251U, 0x3351U,\n\t0x3451U, 0x3551U, 0x3651U, 0x3751U, 0x3851U, 0x3951U, 0x2B51U, 0x2F51U,\n\t0x4152U, 0x4252U, 0x4352U, 0x4452U, 0x4552U, 0x4652U, 0x4752U, 0x4852U,\n\t0x4952U, 0x4A52U, 0x4B52U, 0x4C52U, 0x4D52U, 0x4E52U, 0x4F52U, 0x5052U,\n\t0x5152U, 0x5252U, 0x5352U, 0x5452U, 0x5552U, 0x5652U, 0x5752U, 0x5852U,\n\t0x5952U, 0x5A52U, 0x6152U, 0x6252U, 0x6352U, 0x6452U, 0x6552U, 0x6652U,\n\t0x6752U, 0x6852U, 0x6952U, 0x6A52U, 0x6B52U, 0x6C52U, 0x6D52U, 0x6E52U,\n\t0x6F52U, 0x7052U, 0x7152U, 0x7252U, 0x7352U, 0x7452U, 0x7552U, 0x7652U,\n\t0x7752U, 0x7852U, 0x7952U, 0x7A52U, 0x3052U, 0x3152U, 0x3252U, 0x3352U,\n\t0x3452U, 0x3552U, 0x3652U, 0x3752U, 0x3852U, 0x3952U, 0x2B52U, 0x2F52U,\n\t0x4153U, 0x4253U, 0x4353U, 0x4453U, 0x4553U, 0x4653U, 0x4753U, 0x4853U,\n\t0x4953U, 0x4A53U, 0x4B53U, 0x4C53U, 0x4D53U, 0x4E53U, 0x4F53U, 0x5053U,\n\t0x5153U, 0x5253U, 0x5353U, 0x5453U, 0x5553U, 0x5653U, 0x5753U, 0x5853U,\n\t0x5953U, 0x5A53U, 0x6153U, 0x6253U, 0x6353U, 0x6453U, 0x6553U, 0x6653U,\n\t0x6753U, 0x6853U, 0x6953U, 0x6A53U, 0x6B53U, 0x6C53U, 0x6D53U, 0x6E53U,\n\t0x6F53U, 0x7053U, 0x7153U, 0x7253U, 0x7353U, 0x7453U, 0x7553U, 0x7653U,\n\t0x7753U, 0x7853U, 0x7953U, 0x7A53U, 0x3053U, 0x3153U, 0x3253U, 0x3353U,\n\t0x3453U, 0x3553U, 0x3653U, 0x3753U, 0x3853U, 0x3953U, 0x2B53U, 0x2F53U,\n\t0x4154U, 0x4254U, 0x4354U, 0x4454U, 0x4554U, 0x4654U, 0x4754U, 0x4854U,\n\t0x4954U, 0x4A54U, 0x4B54U, 0x4C54U, 0x4D54U, 0x4E54U, 0x4F54U, 0x5054U,\n\t0x5154U, 0x5254U, 0x5354U, 0x5454U, 0x5554U, 0x5654U, 0x5754U, 0x5854U,\n\t0x5954U, 0x5A54U, 0x6154U, 0x6254U, 0x6354U, 0x6454U, 0x6554U, 0x6654U,\n\t0x6754U, 0x6854U, 0x6954U, 0x6A54U, 0x6B54U, 0x6C54U, 0x6D54U, 0x6E54U,\n\t0x6F54U, 0x7054U, 0x7154U, 0x7254U, 0x7354U, 0x7454U, 0x7554U, 0x7654U,\n\t0x7754U, 0x7854U, 0x7954U, 0x7A54U, 0x3054U, 0x3154U, 0x3254U, 0x3354U,\n\t0x3454U, 0x3554U, 0x3654U, 0x3754U, 0x3854U, 0x3954U, 0x2B54U, 0x2F54U,\n\t0x4155U, 0x4255U, 0x4355U, 0x4455U, 0x4555U, 0x4655U, 0x4755U, 0x4855U,\n\t0x4955U, 0x4A55U, 0x4B55U, 0x4C55U, 0x4D55U, 0x4E55U, 0x4F55U, 0x5055U,\n\t0x5155U, 0x5255U, 0x5355U, 0x5455U, 0x5555U, 0x5655U, 0x5755U, 0x5855U,\n\t0x5955U, 0x5A55U, 0x6155U, 0x6255U, 0x6355U, 0x6455U, 0x6555U, 0x6655U,\n\t0x6755U, 0x6855U, 0x6955U, 0x6A55U, 0x6B55U, 0x6C55U, 0x6D55U, 0x6E55U,\n\t0x6F55U, 0x7055U, 0x7155U, 0x7255U, 0x7355U, 0x7455U, 0x7555U, 0x7655U,\n\t0x7755U, 0x7855U, 0x7955U, 0x7A55U, 0x3055U, 0x3155U, 0x3255U, 0x3355U,\n\t0x3455U, 0x3555U, 0x3655U, 0x3755U, 0x3855U, 0x3955U, 0x2B55U, 0x2F55U,\n\t0x4156U, 0x4256U, 0x4356U, 0x4456U, 0x4556U, 0x4656U, 0x4756U, 0x4856U,\n\t0x4956U, 0x4A56U, 0x4B56U, 0x4C56U, 0x4D56U, 0x4E56U, 0x4F56U, 0x5056U,\n\t0x5156U, 0x5256U, 0x5356U, 0x5456U, 0x5556U, 0x5656U, 0x5756U, 0x5856U,\n\t0x5956U, 0x5A56U, 0x6156U, 0x6256U, 0x6356U, 0x6456U, 0x6556U, 0x6656U,\n\t0x6756U, 0x6856U, 0x6956U, 0x6A56U, 0x6B56U, 0x6C56U, 0x6D56U, 0x6E56U,\n\t0x6F56U, 0x7056U, 0x7156U, 0x7256U, 0x7356U, 0x7456U, 0x7556U, 0x7656U,\n\t0x7756U, 0x7856U, 0x7956U, 0x7A56U, 0x3056U, 0x3156U, 0x3256U, 0x3356U,\n\t0x3456U, 0x3556U, 0x3656U, 0x3756U, 0x3856U, 0x3956U, 0x2B56U, 0x2F56U,\n\t0x4157U, 0x4257U, 0x4357U, 0x4457U, 0x4557U, 0x4657U, 0x4757U, 0x4857U,\n\t0x4957U, 0x4A57U, 0x4B57U, 0x4C57U, 0x4D57U, 0x4E57U, 0x4F57U, 0x5057U,\n\t0x5157U, 0x5257U, 0x5357U, 0x5457U, 0x5557U, 0x5657U, 0x5757U, 0x5857U,\n\t0x5957U, 0x5A57U, 0x6157U, 0x6257U, 0x6357U, 0x6457U, 0x6557U, 0x6657U,\n\t0x6757U, 0x6857U, 0x6957U, 0x6A57U, 0x6B57U, 0x6C57U, 0x6D57U, 0x6E57U,\n\t0x6F57U, 0x7057U, 0x7157U, 0x7257U, 0x7357U, 0x7457U, 0x7557U, 0x7657U,\n\t0x7757U, 0x7857U, 0x7957U, 0x7A57U, 0x3057U, 0x3157U, 0x3257U, 0x3357U,\n\t0x3457U, 0x3557U, 0x3657U, 0x3757U, 0x3857U, 0x3957U, 0x2B57U, 0x2F57U,\n\t0x4158U, 0x4258U, 0x4358U, 0x4458U, 0x4558U, 0x4658U, 0x4758U, 0x4858U,\n\t0x4958U, 0x4A58U, 0x4B58U, 0x4C58U, 0x4D58U, 0x4E58U, 0x4F58U, 0x5058U,\n\t0x5158U, 0x5258U, 0x5358U, 0x5458U, 0x5558U, 0x5658U, 0x5758U, 0x5858U,\n\t0x5958U, 0x5A58U, 0x6158U, 0x6258U, 0x6358U, 0x6458U, 0x6558U, 0x6658U,\n\t0x6758U, 0x6858U, 0x6958U, 0x6A58U, 0x6B58U, 0x6C58U, 0x6D58U, 0x6E58U,\n\t0x6F58U, 0x7058U, 0x7158U, 0x7258U, 0x7358U, 0x7458U, 0x7558U, 0x7658U,\n\t0x7758U, 0x7858U, 0x7958U, 0x7A58U, 0x3058U, 0x3158U, 0x3258U, 0x3358U,\n\t0x3458U, 0x3558U, 0x3658U, 0x3758U, 0x3858U, 0x3958U, 0x2B58U, 0x2F58U,\n\t0x4159U, 0x4259U, 0x4359U, 0x4459U, 0x4559U, 0x4659U, 0x4759U, 0x4859U,\n\t0x4959U, 0x4A59U, 0x4B59U, 0x4C59U, 0x4D59U, 0x4E59U, 0x4F59U, 0x5059U,\n\t0x5159U, 0x5259U, 0x5359U, 0x5459U, 0x5559U, 0x5659U, 0x5759U, 0x5859U,\n\t0x5959U, 0x5A59U, 0x6159U, 0x6259U, 0x6359U, 0x6459U, 0x6559U, 0x6659U,\n\t0x6759U, 0x6859U, 0x6959U, 0x6A59U, 0x6B59U, 0x6C59U, 0x6D59U, 0x6E59U,\n\t0x6F59U, 0x7059U, 0x7159U, 0x7259U, 0x7359U, 0x7459U, 0x7559U, 0x7659U,\n\t0x7759U, 0x7859U, 0x7959U, 0x7A59U, 0x3059U, 0x3159U, 0x3259U, 0x3359U,\n\t0x3459U, 0x3559U, 0x3659U, 0x3759U, 0x3859U, 0x3959U, 0x2B59U, 0x2F59U,\n\t0x415AU, 0x425AU, 0x435AU, 0x445AU, 0x455AU, 0x465AU, 0x475AU, 0x485AU,\n\t0x495AU, 0x4A5AU, 0x4B5AU, 0x4C5AU, 0x4D5AU, 0x4E5AU, 0x4F5AU, 0x505AU,\n\t0x515AU, 0x525AU, 0x535AU, 0x545AU, 0x555AU, 0x565AU, 0x575AU, 0x585AU,\n\t0x595AU, 0x5A5AU, 0x615AU, 0x625AU, 0x635AU, 0x645AU, 0x655AU, 0x665AU,\n\t0x675AU, 0x685AU, 0x695AU, 0x6A5AU, 0x6B5AU, 0x6C5AU, 0x6D5AU, 0x6E5AU,\n\t0x6F5AU, 0x705AU, 0x715AU, 0x725AU, 0x735AU, 0x745AU, 0x755AU, 0x765AU,\n\t0x775AU, 0x785AU, 0x795AU, 0x7A5AU, 0x305AU, 0x315AU, 0x325AU, 0x335AU,\n\t0x345AU, 0x355AU, 0x365AU, 0x375AU, 0x385AU, 0x395AU, 0x2B5AU, 0x2F5AU,\n\t0x4161U, 0x4261U, 0x4361U, 0x4461U, 0x4561U, 0x4661U, 0x4761U, 0x4861U,\n\t0x4961U, 0x4A61U, 0x4B61U, 0x4C61U, 0x4D61U, 0x4E61U, 0x4F61U, 0x5061U,\n\t0x5161U, 0x5261U, 0x5361U, 0x5461U, 0x5561U, 0x5661U, 0x5761U, 0x5861U,\n\t0x5961U, 0x5A61U, 0x6161U, 0x6261U, 0x6361U, 0x6461U, 0x6561U, 0x6661U,\n\t0x6761U, 0x6861U, 0x6961U, 0x6A61U, 0x6B61U, 0x6C61U, 0x6D61U, 0x6E61U,\n\t0x6F61U, 0x7061U, 0x7161U, 0x7261U, 0x7361U, 0x7461U, 0x7561U, 0x7661U,\n\t0x7761U, 0x7861U, 0x7961U, 0x7A61U, 0x3061U, 0x3161U, 0x3261U, 0x3361U,\n\t0x3461U, 0x3561U, 0x3661U, 0x3761U, 0x3861U, 0x3961U, 0x2B61U, 0x2F61U,\n\t0x4162U, 0x4262U, 0x4362U, 0x4462U, 0x4562U, 0x4662U, 0x4762U, 0x4862U,\n\t0x4962U, 0x4A62U, 0x4B62U, 0x4C62U, 0x4D62U, 0x4E62U, 0x4F62U, 0x5062U,\n\t0x5162U, 0x5262U, 0x5362U, 0x5462U, 0x5562U, 0x5662U, 0x5762U, 0x5862U,\n\t0x5962U, 0x5A62U, 0x6162U, 0x6262U, 0x6362U, 0x6462U, 0x6562U, 0x6662U,\n\t0x6762U, 0x6862U, 0x6962U, 0x6A62U, 0x6B62U, 0x6C62U, 0x6D62U, 0x6E62U,\n\t0x6F62U, 0x7062U, 0x7162U, 0x7262U, 0x7362U, 0x7462U, 0x7562U, 0x7662U,\n\t0x7762U, 0x7862U, 0x7962U, 0x7A62U, 0x3062U, 0x3162U, 0x3262U, 0x3362U,\n\t0x3462U, 0x3562U, 0x3662U, 0x3762U, 0x3862U, 0x3962U, 0x2B62U, 0x2F62U,\n\t0x4163U, 0x4263U, 0x4363U, 0x4463U, 0x4563U, 0x4663U, 0x4763U, 0x4863U,\n\t0x4963U, 0x4A63U, 0x4B63U, 0x4C63U, 0x4D63U, 0x4E63U, 0x4F63U, 0x5063U,\n\t0x5163U, 0x5263U, 0x5363U, 0x5463U, 0x5563U, 0x5663U, 0x5763U, 0x5863U,\n\t0x5963U, 0x5A63U, 0x6163U, 0x6263U, 0x6363U, 0x6463U, 0x6563U, 0x6663U,\n\t0x6763U, 0x6863U, 0x6963U, 0x6A63U, 0x6B63U, 0x6C63U, 0x6D63U, 0x6E63U,\n\t0x6F63U, 0x7063U, 0x7163U, 0x7263U, 0x7363U, 0x7463U, 0x7563U, 0x7663U,\n\t0x7763U, 0x7863U, 0x7963U, 0x7A63U, 0x3063U, 0x3163U, 0x3263U, 0x3363U,\n\t0x3463U, 0x3563U, 0x3663U, 0x3763U, 0x3863U, 0x3963U, 0x2B63U, 0x2F63U,\n\t0x4164U, 0x4264U, 0x4364U, 0x4464U, 0x4564U, 0x4664U, 0x4764U, 0x4864U,\n\t0x4964U, 0x4A64U, 0x4B64U, 0x4C64U, 0x4D64U, 0x4E64U, 0x4F64U, 0x5064U,\n\t0x5164U, 0x5264U, 0x5364U, 0x5464U, 0x5564U, 0x5664U, 0x5764U, 0x5864U,\n\t0x5964U, 0x5A64U, 0x6164U, 0x6264U, 0x6364U, 0x6464U, 0x6564U, 0x6664U,\n\t0x6764U, 0x6864U, 0x6964U, 0x6A64U, 0x6B64U, 0x6C64U, 0x6D64U, 0x6E64U,\n\t0x6F64U, 0x7064U, 0x7164U, 0x7264U, 0x7364U, 0x7464U, 0x7564U, 0x7664U,\n\t0x7764U, 0x7864U, 0x7964U, 0x7A64U, 0x3064U, 0x3164U, 0x3264U, 0x3364U,\n\t0x3464U, 0x3564U, 0x3664U, 0x3764U, 0x3864U, 0x3964U, 0x2B64U, 0x2F64U,\n\t0x4165U, 0x4265U, 0x4365U, 0x4465U, 0x4565U, 0x4665U, 0x4765U, 0x4865U,\n\t0x4965U, 0x4A65U, 0x4B65U, 0x4C65U, 0x4D65U, 0x4E65U, 0x4F65U, 0x5065U,\n\t0x5165U, 0x5265U, 0x5365U, 0x5465U, 0x5565U, 0x5665U, 0x5765U, 0x5865U,\n\t0x5965U, 0x5A65U, 0x6165U, 0x6265U, 0x6365U, 0x6465U, 0x6565U, 0x6665U,\n\t0x6765U, 0x6865U, 0x6965U, 0x6A65U, 0x6B65U, 0x6C65U, 0x6D65U, 0x6E65U,\n\t0x6F65U, 0x7065U, 0x7165U, 0x7265U, 0x7365U, 0x7465U, 0x7565U, 0x7665U,\n\t0x7765U, 0x7865U, 0x7965U, 0x7A65U, 0x3065U, 0x3165U, 0x3265U, 0x3365U,\n\t0x3465U, 0x3565U, 0x3665U, 0x3765U, 0x3865U, 0x3965U, 0x2B65U, 0x2F65U,\n\t0x4166U, 0x4266U, 0x4366U, 0x4466U, 0x4566U, 0x4666U, 0x4766U, 0x4866U,\n\t0x4966U, 0x4A66U, 0x4B66U, 0x4C66U, 0x4D66U, 0x4E66U, 0x4F66U, 0x5066U,\n\t0x5166U, 0x5266U, 0x5366U, 0x5466U, 0x5566U, 0x5666U, 0x5766U, 0x5866U,\n\t0x5966U, 0x5A66U, 0x6166U, 0x6266U, 0x6366U, 0x6466U, 0x6566U, 0x6666U,\n\t0x6766U, 0x6866U, 0x6966U, 0x6A66U, 0x6B66U, 0x6C66U, 0x6D66U, 0x6E66U,\n\t0x6F66U, 0x7066U, 0x7166U, 0x7266U, 0x7366U, 0x7466U, 0x7566U, 0x7666U,\n\t0x7766U, 0x7866U, 0x7966U, 0x7A66U, 0x3066U, 0x3166U, 0x3266U, 0x3366U,\n\t0x3466U, 0x3566U, 0x3666U, 0x3766U, 0x3866U, 0x3966U, 0x2B66U, 0x2F66U,\n\t0x4167U, 0x4267U, 0x4367U, 0x4467U, 0x4567U, 0x4667U, 0x4767U, 0x4867U,\n\t0x4967U, 0x4A67U, 0x4B67U, 0x4C67U, 0x4D67U, 0x4E67U, 0x4F67U, 0x5067U,\n\t0x5167U, 0x5267U, 0x5367U, 0x5467U, 0x5567U, 0x5667U, 0x5767U, 0x5867U,\n\t0x5967U, 0x5A67U, 0x6167U, 0x6267U, 0x6367U, 0x6467U, 0x6567U, 0x6667U,\n\t0x6767U, 0x6867U, 0x6967U, 0x6A67U, 0x6B67U, 0x6C67U, 0x6D67U, 0x6E67U,\n\t0x6F67U, 0x7067U, 0x7167U, 0x7267U, 0x7367U, 0x7467U, 0x7567U, 0x7667U,\n\t0x7767U, 0x7867U, 0x7967U, 0x7A67U, 0x3067U, 0x3167U, 0x3267U, 0x3367U,\n\t0x3467U, 0x3567U, 0x3667U, 0x3767U, 0x3867U, 0x3967U, 0x2B67U, 0x2F67U,\n\t0x4168U, 0x4268U, 0x4368U, 0x4468U, 0x4568U, 0x4668U, 0x4768U, 0x4868U,\n\t0x4968U, 0x4A68U, 0x4B68U, 0x4C68U, 0x4D68U, 0x4E68U, 0x4F68U, 0x5068U,\n\t0x5168U, 0x5268U, 0x5368U, 0x5468U, 0x5568U, 0x5668U, 0x5768U, 0x5868U,\n\t0x5968U, 0x5A68U, 0x6168U, 0x6268U, 0x6368U, 0x6468U, 0x6568U, 0x6668U,\n\t0x6768U, 0x6868U, 0x6968U, 0x6A68U, 0x6B68U, 0x6C68U, 0x6D68U, 0x6E68U,\n\t0x6F68U, 0x7068U, 0x7168U, 0x7268U, 0x7368U, 0x7468U, 0x7568U, 0x7668U,\n\t0x7768U, 0x7868U, 0x7968U, 0x7A68U, 0x3068U, 0x3168U, 0x3268U, 0x3368U,\n\t0x3468U, 0x3568U, 0x3668U, 0x3768U, 0x3868U, 0x3968U, 0x2B68U, 0x2F68U,\n\t0x4169U, 0x4269U, 0x4369U, 0x4469U, 0x4569U, 0x4669U, 0x4769U, 0x4869U,\n\t0x4969U, 0x4A69U, 0x4B69U, 0x4C69U, 0x4D69U, 0x4E69U, 0x4F69U, 0x5069U,\n\t0x5169U, 0x5269U, 0x5369U, 0x5469U, 0x5569U, 0x5669U, 0x5769U, 0x5869U,\n\t0x5969U, 0x5A69U, 0x6169U, 0x6269U, 0x6369U, 0x6469U, 0x6569U, 0x6669U,\n\t0x6769U, 0x6869U, 0x6969U, 0x6A69U, 0x6B69U, 0x6C69U, 0x6D69U, 0x6E69U,\n\t0x6F69U, 0x7069U, 0x7169U, 0x7269U, 0x7369U, 0x7469U, 0x7569U, 0x7669U,\n\t0x7769U, 0x7869U, 0x7969U, 0x7A69U, 0x3069U, 0x3169U, 0x3269U, 0x3369U,\n\t0x3469U, 0x3569U, 0x3669U, 0x3769U, 0x3869U, 0x3969U, 0x2B69U, 0x2F69U,\n\t0x416AU, 0x426AU, 0x436AU, 0x446AU, 0x456AU, 0x466AU, 0x476AU, 0x486AU,\n\t0x496AU, 0x4A6AU, 0x4B6AU, 0x4C6AU, 0x4D6AU, 0x4E6AU, 0x4F6AU, 0x506AU,\n\t0x516AU, 0x526AU, 0x536AU, 0x546AU, 0x556AU, 0x566AU, 0x576AU, 0x586AU,\n\t0x596AU, 0x5A6AU, 0x616AU, 0x626AU, 0x636AU, 0x646AU, 0x656AU, 0x666AU,\n\t0x676AU, 0x686AU, 0x696AU, 0x6A6AU, 0x6B6AU, 0x6C6AU, 0x6D6AU, 0x6E6AU,\n\t0x6F6AU, 0x706AU, 0x716AU, 0x726AU, 0x736AU, 0x746AU, 0x756AU, 0x766AU,\n\t0x776AU, 0x786AU, 0x796AU, 0x7A6AU, 0x306AU, 0x316AU, 0x326AU, 0x336AU,\n\t0x346AU, 0x356AU, 0x366AU, 0x376AU, 0x386AU, 0x396AU, 0x2B6AU, 0x2F6AU,\n\t0x416BU, 0x426BU, 0x436BU, 0x446BU, 0x456BU, 0x466BU, 0x476BU, 0x486BU,\n\t0x496BU, 0x4A6BU, 0x4B6BU, 0x4C6BU, 0x4D6BU, 0x4E6BU, 0x4F6BU, 0x506BU,\n\t0x516BU, 0x526BU, 0x536BU, 0x546BU, 0x556BU, 0x566BU, 0x576BU, 0x586BU,\n\t0x596BU, 0x5A6BU, 0x616BU, 0x626BU, 0x636BU, 0x646BU, 0x656BU, 0x666BU,\n\t0x676BU, 0x686BU, 0x696BU, 0x6A6BU, 0x6B6BU, 0x6C6BU, 0x6D6BU, 0x6E6BU,\n\t0x6F6BU, 0x706BU, 0x716BU, 0x726BU, 0x736BU, 0x746BU, 0x756BU, 0x766BU,\n\t0x776BU, 0x786BU, 0x796BU, 0x7A6BU, 0x306BU, 0x316BU, 0x326BU, 0x336BU,\n\t0x346BU, 0x356BU, 0x366BU, 0x376BU, 0x386BU, 0x396BU, 0x2B6BU, 0x2F6BU,\n\t0x416CU, 0x426CU, 0x436CU, 0x446CU, 0x456CU, 0x466CU, 0x476CU, 0x486CU,\n\t0x496CU, 0x4A6CU, 0x4B6CU, 0x4C6CU, 0x4D6CU, 0x4E6CU, 0x4F6CU, 0x506CU,\n\t0x516CU, 0x526CU, 0x536CU, 0x546CU, 0x556CU, 0x566CU, 0x576CU, 0x586CU,\n\t0x596CU, 0x5A6CU, 0x616CU, 0x626CU, 0x636CU, 0x646CU, 0x656CU, 0x666CU,\n\t0x676CU, 0x686CU, 0x696CU, 0x6A6CU, 0x6B6CU, 0x6C6CU, 0x6D6CU, 0x6E6CU,\n\t0x6F6CU, 0x706CU, 0x716CU, 0x726CU, 0x736CU, 0x746CU, 0x756CU, 0x766CU,\n\t0x776CU, 0x786CU, 0x796CU, 0x7A6CU, 0x306CU, 0x316CU, 0x326CU, 0x336CU,\n\t0x346CU, 0x356CU, 0x366CU, 0x376CU, 0x386CU, 0x396CU, 0x2B6CU, 0x2F6CU,\n\t0x416DU, 0x426DU, 0x436DU, 0x446DU, 0x456DU, 0x466DU, 0x476DU, 0x486DU,\n\t0x496DU, 0x4A6DU, 0x4B6DU, 0x4C6DU, 0x4D6DU, 0x4E6DU, 0x4F6DU, 0x506DU,\n\t0x516DU, 0x526DU, 0x536DU, 0x546DU, 0x556DU, 0x566DU, 0x576DU, 0x586DU,\n\t0x596DU, 0x5A6DU, 0x616DU, 0x626DU, 0x636DU, 0x646DU, 0x656DU, 0x666DU,\n\t0x676DU, 0x686DU, 0x696DU, 0x6A6DU, 0x6B6DU, 0x6C6DU, 0x6D6DU, 0x6E6DU,\n\t0x6F6DU, 0x706DU, 0x716DU, 0x726DU, 0x736DU, 0x746DU, 0x756DU, 0x766DU,\n\t0x776DU, 0x786DU, 0x796DU, 0x7A6DU, 0x306DU, 0x316DU, 0x326DU, 0x336DU,\n\t0x346DU, 0x356DU, 0x366DU, 0x376DU, 0x386DU, 0x396DU, 0x2B6DU, 0x2F6DU,\n\t0x416EU, 0x426EU, 0x436EU, 0x446EU, 0x456EU, 0x466EU, 0x476EU, 0x486EU,\n\t0x496EU, 0x4A6EU, 0x4B6EU, 0x4C6EU, 0x4D6EU, 0x4E6EU, 0x4F6EU, 0x506EU,\n\t0x516EU, 0x526EU, 0x536EU, 0x546EU, 0x556EU, 0x566EU, 0x576EU, 0x586EU,\n\t0x596EU, 0x5A6EU, 0x616EU, 0x626EU, 0x636EU, 0x646EU, 0x656EU, 0x666EU,\n\t0x676EU, 0x686EU, 0x696EU, 0x6A6EU, 0x6B6EU, 0x6C6EU, 0x6D6EU, 0x6E6EU,\n\t0x6F6EU, 0x706EU, 0x716EU, 0x726EU, 0x736EU, 0x746EU, 0x756EU, 0x766EU,\n\t0x776EU, 0x786EU, 0x796EU, 0x7A6EU, 0x306EU, 0x316EU, 0x326EU, 0x336EU,\n\t0x346EU, 0x356EU, 0x366EU, 0x376EU, 0x386EU, 0x396EU, 0x2B6EU, 0x2F6EU,\n\t0x416FU, 0x426FU, 0x436FU, 0x446FU, 0x456FU, 0x466FU, 0x476FU, 0x486FU,\n\t0x496FU, 0x4A6FU, 0x4B6FU, 0x4C6FU, 0x4D6FU, 0x4E6FU, 0x4F6FU, 0x506FU,\n\t0x516FU, 0x526FU, 0x536FU, 0x546FU, 0x556FU, 0x566FU, 0x576FU, 0x586FU,\n\t0x596FU, 0x5A6FU, 0x616FU, 0x626FU, 0x636FU, 0x646FU, 0x656FU, 0x666FU,\n\t0x676FU, 0x686FU, 0x696FU, 0x6A6FU, 0x6B6FU, 0x6C6FU, 0x6D6FU, 0x6E6FU,\n\t0x6F6FU, 0x706FU, 0x716FU, 0x726FU, 0x736FU, 0x746FU, 0x756FU, 0x766FU,\n\t0x776FU, 0x786FU, 0x796FU, 0x7A6FU, 0x306FU, 0x316FU, 0x326FU, 0x336FU,\n\t0x346FU, 0x356FU, 0x366FU, 0x376FU, 0x386FU, 0x396FU, 0x2B6FU, 0x2F6FU,\n\t0x4170U, 0x4270U, 0x4370U, 0x4470U, 0x4570U, 0x4670U, 0x4770U, 0x4870U,\n\t0x4970U, 0x4A70U, 0x4B70U, 0x4C70U, 0x4D70U, 0x4E70U, 0x4F70U, 0x5070U,\n\t0x5170U, 0x5270U, 0x5370U, 0x5470U, 0x5570U, 0x5670U, 0x5770U, 0x5870U,\n\t0x5970U, 0x5A70U, 0x6170U, 0x6270U, 0x6370U, 0x6470U, 0x6570U, 0x6670U,\n\t0x6770U, 0x6870U, 0x6970U, 0x6A70U, 0x6B70U, 0x6C70U, 0x6D70U, 0x6E70U,\n\t0x6F70U, 0x7070U, 0x7170U, 0x7270U, 0x7370U, 0x7470U, 0x7570U, 0x7670U,\n\t0x7770U, 0x7870U, 0x7970U, 0x7A70U, 0x3070U, 0x3170U, 0x3270U, 0x3370U,\n\t0x3470U, 0x3570U, 0x3670U, 0x3770U, 0x3870U, 0x3970U, 0x2B70U, 0x2F70U,\n\t0x4171U, 0x4271U, 0x4371U, 0x4471U, 0x4571U, 0x4671U, 0x4771U, 0x4871U,\n\t0x4971U, 0x4A71U, 0x4B71U, 0x4C71U, 0x4D71U, 0x4E71U, 0x4F71U, 0x5071U,\n\t0x5171U, 0x5271U, 0x5371U, 0x5471U, 0x5571U, 0x5671U, 0x5771U, 0x5871U,\n\t0x5971U, 0x5A71U, 0x6171U, 0x6271U, 0x6371U, 0x6471U, 0x6571U, 0x6671U,\n\t0x6771U, 0x6871U, 0x6971U, 0x6A71U, 0x6B71U, 0x6C71U, 0x6D71U, 0x6E71U,\n\t0x6F71U, 0x7071U, 0x7171U, 0x7271U, 0x7371U, 0x7471U, 0x7571U, 0x7671U,\n\t0x7771U, 0x7871U, 0x7971U, 0x7A71U, 0x3071U, 0x3171U, 0x3271U, 0x3371U,\n\t0x3471U, 0x3571U, 0x3671U, 0x3771U, 0x3871U, 0x3971U, 0x2B71U, 0x2F71U,\n\t0x4172U, 0x4272U, 0x4372U, 0x4472U, 0x4572U, 0x4672U, 0x4772U, 0x4872U,\n\t0x4972U, 0x4A72U, 0x4B72U, 0x4C72U, 0x4D72U, 0x4E72U, 0x4F72U, 0x5072U,\n\t0x5172U, 0x5272U, 0x5372U, 0x5472U, 0x5572U, 0x5672U, 0x5772U, 0x5872U,\n\t0x5972U, 0x5A72U, 0x6172U, 0x6272U, 0x6372U, 0x6472U, 0x6572U, 0x6672U,\n\t0x6772U, 0x6872U, 0x6972U, 0x6A72U, 0x6B72U, 0x6C72U, 0x6D72U, 0x6E72U,\n\t0x6F72U, 0x7072U, 0x7172U, 0x7272U, 0x7372U, 0x7472U, 0x7572U, 0x7672U,\n\t0x7772U, 0x7872U, 0x7972U, 0x7A72U, 0x3072U, 0x3172U, 0x3272U, 0x3372U,\n\t0x3472U, 0x3572U, 0x3672U, 0x3772U, 0x3872U, 0x3972U, 0x2B72U, 0x2F72U,\n\t0x4173U, 0x4273U, 0x4373U, 0x4473U, 0x4573U, 0x4673U, 0x4773U, 0x4873U,\n\t0x4973U, 0x4A73U, 0x4B73U, 0x4C73U, 0x4D73U, 0x4E73U, 0x4F73U, 0x5073U,\n\t0x5173U, 0x5273U, 0x5373U, 0x5473U, 0x5573U, 0x5673U, 0x5773U, 0x5873U,\n\t0x5973U, 0x5A73U, 0x6173U, 0x6273U, 0x6373U, 0x6473U, 0x6573U, 0x6673U,\n\t0x6773U, 0x6873U, 0x6973U, 0x6A73U, 0x6B73U, 0x6C73U, 0x6D73U, 0x6E73U,\n\t0x6F73U, 0x7073U, 0x7173U, 0x7273U, 0x7373U, 0x7473U, 0x7573U, 0x7673U,\n\t0x7773U, 0x7873U, 0x7973U, 0x7A73U, 0x3073U, 0x3173U, 0x3273U, 0x3373U,\n\t0x3473U, 0x3573U, 0x3673U, 0x3773U, 0x3873U, 0x3973U, 0x2B73U, 0x2F73U,\n\t0x4174U, 0x4274U, 0x4374U, 0x4474U, 0x4574U, 0x4674U, 0x4774U, 0x4874U,\n\t0x4974U, 0x4A74U, 0x4B74U, 0x4C74U, 0x4D74U, 0x4E74U, 0x4F74U, 0x5074U,\n\t0x5174U, 0x5274U, 0x5374U, 0x5474U, 0x5574U, 0x5674U, 0x5774U, 0x5874U,\n\t0x5974U, 0x5A74U, 0x6174U, 0x6274U, 0x6374U, 0x6474U, 0x6574U, 0x6674U,\n\t0x6774U, 0x6874U, 0x6974U, 0x6A74U, 0x6B74U, 0x6C74U, 0x6D74U, 0x6E74U,\n\t0x6F74U, 0x7074U, 0x7174U, 0x7274U, 0x7374U, 0x7474U, 0x7574U, 0x7674U,\n\t0x7774U, 0x7874U, 0x7974U, 0x7A74U, 0x3074U, 0x3174U, 0x3274U, 0x3374U,\n\t0x3474U, 0x3574U, 0x3674U, 0x3774U, 0x3874U, 0x3974U, 0x2B74U, 0x2F74U,\n\t0x4175U, 0x4275U, 0x4375U, 0x4475U, 0x4575U, 0x4675U, 0x4775U, 0x4875U,\n\t0x4975U, 0x4A75U, 0x4B75U, 0x4C75U, 0x4D75U, 0x4E75U, 0x4F75U, 0x5075U,\n\t0x5175U, 0x5275U, 0x5375U, 0x5475U, 0x5575U, 0x5675U, 0x5775U, 0x5875U,\n\t0x5975U, 0x5A75U, 0x6175U, 0x6275U, 0x6375U, 0x6475U, 0x6575U, 0x6675U,\n\t0x6775U, 0x6875U, 0x6975U, 0x6A75U, 0x6B75U, 0x6C75U, 0x6D75U, 0x6E75U,\n\t0x6F75U, 0x7075U, 0x7175U, 0x7275U, 0x7375U, 0x7475U, 0x7575U, 0x7675U,\n\t0x7775U, 0x7875U, 0x7975U, 0x7A75U, 0x3075U, 0x3175U, 0x3275U, 0x3375U,\n\t0x3475U, 0x3575U, 0x3675U, 0x3775U, 0x3875U, 0x3975U, 0x2B75U, 0x2F75U,\n\t0x4176U, 0x4276U, 0x4376U, 0x4476U, 0x4576U, 0x4676U, 0x4776U, 0x4876U,\n\t0x4976U, 0x4A76U, 0x4B76U, 0x4C76U, 0x4D76U, 0x4E76U, 0x4F76U, 0x5076U,\n\t0x5176U, 0x5276U, 0x5376U, 0x5476U, 0x5576U, 0x5676U, 0x5776U, 0x5876U,\n\t0x5976U, 0x5A76U, 0x6176U, 0x6276U, 0x6376U, 0x6476U, 0x6576U, 0x6676U,\n\t0x6776U, 0x6876U, 0x6976U, 0x6A76U, 0x6B76U, 0x6C76U, 0x6D76U, 0x6E76U,\n\t0x6F76U, 0x7076U, 0x7176U, 0x7276U, 0x7376U, 0x7476U, 0x7576U, 0x7676U,\n\t0x7776U, 0x7876U, 0x7976U, 0x7A76U, 0x3076U, 0x3176U, 0x3276U, 0x3376U,\n\t0x3476U, 0x3576U, 0x3676U, 0x3776U, 0x3876U, 0x3976U, 0x2B76U, 0x2F76U,\n\t0x4177U, 0x4277U, 0x4377U, 0x4477U, 0x4577U, 0x4677U, 0x4777U, 0x4877U,\n\t0x4977U, 0x4A77U, 0x4B77U, 0x4C77U, 0x4D77U, 0x4E77U, 0x4F77U, 0x5077U,\n\t0x5177U, 0x5277U, 0x5377U, 0x5477U, 0x5577U, 0x5677U, 0x5777U, 0x5877U,\n\t0x5977U, 0x5A77U, 0x6177U, 0x6277U, 0x6377U, 0x6477U, 0x6577U, 0x6677U,\n\t0x6777U, 0x6877U, 0x6977U, 0x6A77U, 0x6B77U, 0x6C77U, 0x6D77U, 0x6E77U,\n\t0x6F77U, 0x7077U, 0x7177U, 0x7277U, 0x7377U, 0x7477U, 0x7577U, 0x7677U,\n\t0x7777U, 0x7877U, 0x7977U, 0x7A77U, 0x3077U, 0x3177U, 0x3277U, 0x3377U,\n\t0x3477U, 0x3577U, 0x3677U, 0x3777U, 0x3877U, 0x3977U, 0x2B77U, 0x2F77U,\n\t0x4178U, 0x4278U, 0x4378U, 0x4478U, 0x4578U, 0x4678U, 0x4778U, 0x4878U,\n\t0x4978U, 0x4A78U, 0x4B78U, 0x4C78U, 0x4D78U, 0x4E78U, 0x4F78U, 0x5078U,\n\t0x5178U, 0x5278U, 0x5378U, 0x5478U, 0x5578U, 0x5678U, 0x5778U, 0x5878U,\n\t0x5978U, 0x5A78U, 0x6178U, 0x6278U, 0x6378U, 0x6478U, 0x6578U, 0x6678U,\n\t0x6778U, 0x6878U, 0x6978U, 0x6A78U, 0x6B78U, 0x6C78U, 0x6D78U, 0x6E78U,\n\t0x6F78U, 0x7078U, 0x7178U, 0x7278U, 0x7378U, 0x7478U, 0x7578U, 0x7678U,\n\t0x7778U, 0x7878U, 0x7978U, 0x7A78U, 0x3078U, 0x3178U, 0x3278U, 0x3378U,\n\t0x3478U, 0x3578U, 0x3678U, 0x3778U, 0x3878U, 0x3978U, 0x2B78U, 0x2F78U,\n\t0x4179U, 0x4279U, 0x4379U, 0x4479U, 0x4579U, 0x4679U, 0x4779U, 0x4879U,\n\t0x4979U, 0x4A79U, 0x4B79U, 0x4C79U, 0x4D79U, 0x4E79U, 0x4F79U, 0x5079U,\n\t0x5179U, 0x5279U, 0x5379U, 0x5479U, 0x5579U, 0x5679U, 0x5779U, 0x5879U,\n\t0x5979U, 0x5A79U, 0x6179U, 0x6279U, 0x6379U, 0x6479U, 0x6579U, 0x6679U,\n\t0x6779U, 0x6879U, 0x6979U, 0x6A79U, 0x6B79U, 0x6C79U, 0x6D79U, 0x6E79U,\n\t0x6F79U, 0x7079U, 0x7179U, 0x7279U, 0x7379U, 0x7479U, 0x7579U, 0x7679U,\n\t0x7779U, 0x7879U, 0x7979U, 0x7A79U, 0x3079U, 0x3179U, 0x3279U, 0x3379U,\n\t0x3479U, 0x3579U, 0x3679U, 0x3779U, 0x3879U, 0x3979U, 0x2B79U, 0x2F79U,\n\t0x417AU, 0x427AU, 0x437AU, 0x447AU, 0x457AU, 0x467AU, 0x477AU, 0x487AU,\n\t0x497AU, 0x4A7AU, 0x4B7AU, 0x4C7AU, 0x4D7AU, 0x4E7AU, 0x4F7AU, 0x507AU,\n\t0x517AU, 0x527AU, 0x537AU, 0x547AU, 0x557AU, 0x567AU, 0x577AU, 0x587AU,\n\t0x597AU, 0x5A7AU, 0x617AU, 0x627AU, 0x637AU, 0x647AU, 0x657AU, 0x667AU,\n\t0x677AU, 0x687AU, 0x697AU, 0x6A7AU, 0x6B7AU, 0x6C7AU, 0x6D7AU, 0x6E7AU,\n\t0x6F7AU, 0x707AU, 0x717AU, 0x727AU, 0x737AU, 0x747AU, 0x757AU, 0x767AU,\n\t0x777AU, 0x787AU, 0x797AU, 0x7A7AU, 0x307AU, 0x317AU, 0x327AU, 0x337AU,\n\t0x347AU, 0x357AU, 0x367AU, 0x377AU, 0x387AU, 0x397AU, 0x2B7AU, 0x2F7AU,\n\t0x4130U, 0x4230U, 0x4330U, 0x4430U, 0x4530U, 0x4630U, 0x4730U, 0x4830U,\n\t0x4930U, 0x4A30U, 0x4B30U, 0x4C30U, 0x4D30U, 0x4E30U, 0x4F30U, 0x5030U,\n\t0x5130U, 0x5230U, 0x5330U, 0x5430U, 0x5530U, 0x5630U, 0x5730U, 0x5830U,\n\t0x5930U, 0x5A30U, 0x6130U, 0x6230U, 0x6330U, 0x6430U, 0x6530U, 0x6630U,\n\t0x6730U, 0x6830U, 0x6930U, 0x6A30U, 0x6B30U, 0x6C30U, 0x6D30U, 0x6E30U,\n\t0x6F30U, 0x7030U, 0x7130U, 0x7230U, 0x7330U, 0x7430U, 0x7530U, 0x7630U,\n\t0x7730U, 0x7830U, 0x7930U, 0x7A30U, 0x3030U, 0x3130U, 0x3230U, 0x3330U,\n\t0x3430U, 0x3530U, 0x3630U, 0x3730U, 0x3830U, 0x3930U, 0x2B30U, 0x2F30U,\n\t0x4131U, 0x4231U, 0x4331U, 0x4431U, 0x4531U, 0x4631U, 0x4731U, 0x4831U,\n\t0x4931U, 0x4A31U, 0x4B31U, 0x4C31U, 0x4D31U, 0x4E31U, 0x4F31U, 0x5031U,\n\t0x5131U, 0x5231U, 0x5331U, 0x5431U, 0x5531U, 0x5631U, 0x5731U, 0x5831U,\n\t0x5931U, 0x5A31U, 0x6131U, 0x6231U, 0x6331U, 0x6431U, 0x6531U, 0x6631U,\n\t0x6731U, 0x6831U, 0x6931U, 0x6A31U, 0x6B31U, 0x6C31U, 0x6D31U, 0x6E31U,\n\t0x6F31U, 0x7031U, 0x7131U, 0x7231U, 0x7331U, 0x7431U, 0x7531U, 0x7631U,\n\t0x7731U, 0x7831U, 0x7931U, 0x7A31U, 0x3031U, 0x3131U, 0x3231U, 0x3331U,\n\t0x3431U, 0x3531U, 0x3631U, 0x3731U, 0x3831U, 0x3931U, 0x2B31U, 0x2F31U,\n\t0x4132U, 0x4232U, 0x4332U, 0x4432U, 0x4532U, 0x4632U, 0x4732U, 0x4832U,\n\t0x4932U, 0x4A32U, 0x4B32U, 0x4C32U, 0x4D32U, 0x4E32U, 0x4F32U, 0x5032U,\n\t0x5132U, 0x5232U, 0x5332U, 0x5432U, 0x5532U, 0x5632U, 0x5732U, 0x5832U,\n\t0x5932U, 0x5A32U, 0x6132U, 0x6232U, 0x6332U, 0x6432U, 0x6532U, 0x6632U,\n\t0x6732U, 0x6832U, 0x6932U, 0x6A32U, 0x6B32U, 0x6C32U, 0x6D32U, 0x6E32U,\n\t0x6F32U, 0x7032U, 0x7132U, 0x7232U, 0x7332U, 0x7432U, 0x7532U, 0x7632U,\n\t0x7732U, 0x7832U, 0x7932U, 0x7A32U, 0x3032U, 0x3132U, 0x3232U, 0x3332U,\n\t0x3432U, 0x3532U, 0x3632U, 0x3732U, 0x3832U, 0x3932U, 0x2B32U, 0x2F32U,\n\t0x4133U, 0x4233U, 0x4333U, 0x4433U, 0x4533U, 0x4633U, 0x4733U, 0x4833U,\n\t0x4933U, 0x4A33U, 0x4B33U, 0x4C33U, 0x4D33U, 0x4E33U, 0x4F33U, 0x5033U,\n\t0x5133U, 0x5233U, 0x5333U, 0x5433U, 0x5533U, 0x5633U, 0x5733U, 0x5833U,\n\t0x5933U, 0x5A33U, 0x6133U, 0x6233U, 0x6333U, 0x6433U, 0x6533U, 0x6633U,\n\t0x6733U, 0x6833U, 0x6933U, 0x6A33U, 0x6B33U, 0x6C33U, 0x6D33U, 0x6E33U,\n\t0x6F33U, 0x7033U, 0x7133U, 0x7233U, 0x7333U, 0x7433U, 0x7533U, 0x7633U,\n\t0x7733U, 0x7833U, 0x7933U, 0x7A33U, 0x3033U, 0x3133U, 0x3233U, 0x3333U,\n\t0x3433U, 0x3533U, 0x3633U, 0x3733U, 0x3833U, 0x3933U, 0x2B33U, 0x2F33U,\n\t0x4134U, 0x4234U, 0x4334U, 0x4434U, 0x4534U, 0x4634U, 0x4734U, 0x4834U,\n\t0x4934U, 0x4A34U, 0x4B34U, 0x4C34U, 0x4D34U, 0x4E34U, 0x4F34U, 0x5034U,\n\t0x5134U, 0x5234U, 0x5334U, 0x5434U, 0x5534U, 0x5634U, 0x5734U, 0x5834U,\n\t0x5934U, 0x5A34U, 0x6134U, 0x6234U, 0x6334U, 0x6434U, 0x6534U, 0x6634U,\n\t0x6734U, 0x6834U, 0x6934U, 0x6A34U, 0x6B34U, 0x6C34U, 0x6D34U, 0x6E34U,\n\t0x6F34U, 0x7034U, 0x7134U, 0x7234U, 0x7334U, 0x7434U, 0x7534U, 0x7634U,\n\t0x7734U, 0x7834U, 0x7934U, 0x7A34U, 0x3034U, 0x3134U, 0x3234U, 0x3334U,\n\t0x3434U, 0x3534U, 0x3634U, 0x3734U, 0x3834U, 0x3934U, 0x2B34U, 0x2F34U,\n\t0x4135U, 0x4235U, 0x4335U, 0x4435U, 0x4535U, 0x4635U, 0x4735U, 0x4835U,\n\t0x4935U, 0x4A35U, 0x4B35U, 0x4C35U, 0x4D35U, 0x4E35U, 0x4F35U, 0x5035U,\n\t0x5135U, 0x5235U, 0x5335U, 0x5435U, 0x5535U, 0x5635U, 0x5735U, 0x5835U,\n\t0x5935U, 0x5A35U, 0x6135U, 0x6235U, 0x6335U, 0x6435U, 0x6535U, 0x6635U,\n\t0x6735U, 0x6835U, 0x6935U, 0x6A35U, 0x6B35U, 0x6C35U, 0x6D35U, 0x6E35U,\n\t0x6F35U, 0x7035U, 0x7135U, 0x7235U, 0x7335U, 0x7435U, 0x7535U, 0x7635U,\n\t0x7735U, 0x7835U, 0x7935U, 0x7A35U, 0x3035U, 0x3135U, 0x3235U, 0x3335U,\n\t0x3435U, 0x3535U, 0x3635U, 0x3735U, 0x3835U, 0x3935U, 0x2B35U, 0x2F35U,\n\t0x4136U, 0x4236U, 0x4336U, 0x4436U, 0x4536U, 0x4636U, 0x4736U, 0x4836U,\n\t0x4936U, 0x4A36U, 0x4B36U, 0x4C36U, 0x4D36U, 0x4E36U, 0x4F36U, 0x5036U,\n\t0x5136U, 0x5236U, 0x5336U, 0x5436U, 0x5536U, 0x5636U, 0x5736U, 0x5836U,\n\t0x5936U, 0x5A36U, 0x6136U, 0x6236U, 0x6336U, 0x6436U, 0x6536U, 0x6636U,\n\t0x6736U, 0x6836U, 0x6936U, 0x6A36U, 0x6B36U, 0x6C36U, 0x6D36U, 0x6E36U,\n\t0x6F36U, 0x7036U, 0x7136U, 0x7236U, 0x7336U, 0x7436U, 0x7536U, 0x7636U,\n\t0x7736U, 0x7836U, 0x7936U, 0x7A36U, 0x3036U, 0x3136U, 0x3236U, 0x3336U,\n\t0x3436U, 0x3536U, 0x3636U, 0x3736U, 0x3836U, 0x3936U, 0x2B36U, 0x2F36U,\n\t0x4137U, 0x4237U, 0x4337U, 0x4437U, 0x4537U, 0x4637U, 0x4737U, 0x4837U,\n\t0x4937U, 0x4A37U, 0x4B37U, 0x4C37U, 0x4D37U, 0x4E37U, 0x4F37U, 0x5037U,\n\t0x5137U, 0x5237U, 0x5337U, 0x5437U, 0x5537U, 0x5637U, 0x5737U, 0x5837U,\n\t0x5937U, 0x5A37U, 0x6137U, 0x6237U, 0x6337U, 0x6437U, 0x6537U, 0x6637U,\n\t0x6737U, 0x6837U, 0x6937U, 0x6A37U, 0x6B37U, 0x6C37U, 0x6D37U, 0x6E37U,\n\t0x6F37U, 0x7037U, 0x7137U, 0x7237U, 0x7337U, 0x7437U, 0x7537U, 0x7637U,\n\t0x7737U, 0x7837U, 0x7937U, 0x7A37U, 0x3037U, 0x3137U, 0x3237U, 0x3337U,\n\t0x3437U, 0x3537U, 0x3637U, 0x3737U, 0x3837U, 0x3937U, 0x2B37U, 0x2F37U,\n\t0x4138U, 0x4238U, 0x4338U, 0x4438U, 0x4538U, 0x4638U, 0x4738U, 0x4838U,\n\t0x4938U, 0x4A38U, 0x4B38U, 0x4C38U, 0x4D38U, 0x4E38U, 0x4F38U, 0x5038U,\n\t0x5138U, 0x5238U, 0x5338U, 0x5438U, 0x5538U, 0x5638U, 0x5738U, 0x5838U,\n\t0x5938U, 0x5A38U, 0x6138U, 0x6238U, 0x6338U, 0x6438U, 0x6538U, 0x6638U,\n\t0x6738U, 0x6838U, 0x6938U, 0x6A38U, 0x6B38U, 0x6C38U, 0x6D38U, 0x6E38U,\n\t0x6F38U, 0x7038U, 0x7138U, 0x7238U, 0x7338U, 0x7438U, 0x7538U, 0x7638U,\n\t0x7738U, 0x7838U, 0x7938U, 0x7A38U, 0x3038U, 0x3138U, 0x3238U, 0x3338U,\n\t0x3438U, 0x3538U, 0x3638U, 0x3738U, 0x3838U, 0x3938U, 0x2B38U, 0x2F38U,\n\t0x4139U, 0x4239U, 0x4339U, 0x4439U, 0x4539U, 0x4639U, 0x4739U, 0x4839U,\n\t0x4939U, 0x4A39U, 0x4B39U, 0x4C39U, 0x4D39U, 0x4E39U, 0x4F39U, 0x5039U,\n\t0x5139U, 0x5239U, 0x5339U, 0x5439U, 0x5539U, 0x5639U, 0x5739U, 0x5839U,\n\t0x5939U, 0x5A39U, 0x6139U, 0x6239U, 0x6339U, 0x6439U, 0x6539U, 0x6639U,\n\t0x6739U, 0x6839U, 0x6939U, 0x6A39U, 0x6B39U, 0x6C39U, 0x6D39U, 0x6E39U,\n\t0x6F39U, 0x7039U, 0x7139U, 0x7239U, 0x7339U, 0x7439U, 0x7539U, 0x7639U,\n\t0x7739U, 0x7839U, 0x7939U, 0x7A39U, 0x3039U, 0x3139U, 0x3239U, 0x3339U,\n\t0x3439U, 0x3539U, 0x3639U, 0x3739U, 0x3839U, 0x3939U, 0x2B39U, 0x2F39U,\n\t0x412BU, 0x422BU, 0x432BU, 0x442BU, 0x452BU, 0x462BU, 0x472BU, 0x482BU,\n\t0x492BU, 0x4A2BU, 0x4B2BU, 0x4C2BU, 0x4D2BU, 0x4E2BU, 0x4F2BU, 0x502BU,\n\t0x512BU, 0x522BU, 0x532BU, 0x542BU, 0x552BU, 0x562BU, 0x572BU, 0x582BU,\n\t0x592BU, 0x5A2BU, 0x612BU, 0x622BU, 0x632BU, 0x642BU, 0x652BU, 0x662BU,\n\t0x672BU, 0x682BU, 0x692BU, 0x6A2BU, 0x6B2BU, 0x6C2BU, 0x6D2BU, 0x6E2BU,\n\t0x6F2BU, 0x702BU, 0x712BU, 0x722BU, 0x732BU, 0x742BU, 0x752BU, 0x762BU,\n\t0x772BU, 0x782BU, 0x792BU, 0x7A2BU, 0x302BU, 0x312BU, 0x322BU, 0x332BU,\n\t0x342BU, 0x352BU, 0x362BU, 0x372BU, 0x382BU, 0x392BU, 0x2B2BU, 0x2F2BU,\n\t0x412FU, 0x422FU, 0x432FU, 0x442FU, 0x452FU, 0x462FU, 0x472FU, 0x482FU,\n\t0x492FU, 0x4A2FU, 0x4B2FU, 0x4C2FU, 0x4D2FU, 0x4E2FU, 0x4F2FU, 0x502FU,\n\t0x512FU, 0x522FU, 0x532FU, 0x542FU, 0x552FU, 0x562FU, 0x572FU, 0x582FU,\n\t0x592FU, 0x5A2FU, 0x612FU, 0x622FU, 0x632FU, 0x642FU, 0x652FU, 0x662FU,\n\t0x672FU, 0x682FU, 0x692FU, 0x6A2FU, 0x6B2FU, 0x6C2FU, 0x6D2FU, 0x6E2FU,\n\t0x6F2FU, 0x702FU, 0x712FU, 0x722FU, 0x732FU, 0x742FU, 0x752FU, 0x762FU,\n\t0x772FU, 0x782FU, 0x792FU, 0x7A2FU, 0x302FU, 0x312FU, 0x322FU, 0x332FU,\n\t0x342FU, 0x352FU, 0x362FU, 0x372FU, 0x382FU, 0x392FU, 0x2B2FU, 0x2F2FU,\n#else\n\t0x4141U, 0x4142U, 0x4143U, 0x4144U, 0x4145U, 0x4146U, 0x4147U, 0x4148U,\n\t0x4149U, 0x414AU, 0x414BU, 0x414CU, 0x414DU, 0x414EU, 0x414FU, 0x4150U,\n\t0x4151U, 0x4152U, 0x4153U, 0x4154U, 0x4155U, 0x4156U, 0x4157U, 0x4158U,\n\t0x4159U, 0x415AU, 0x4161U, 0x4162U, 0x4163U, 0x4164U, 0x4165U, 0x4166U,\n\t0x4167U, 0x4168U, 0x4169U, 0x416AU, 0x416BU, 0x416CU, 0x416DU, 0x416EU,\n\t0x416FU, 0x4170U, 0x4171U, 0x4172U, 0x4173U, 0x4174U, 0x4175U, 0x4176U,\n\t0x4177U, 0x4178U, 0x4179U, 0x417AU, 0x4130U, 0x4131U, 0x4132U, 0x4133U,\n\t0x4134U, 0x4135U, 0x4136U, 0x4137U, 0x4138U, 0x4139U, 0x412BU, 0x412FU,\n\t0x4241U, 0x4242U, 0x4243U, 0x4244U, 0x4245U, 0x4246U, 0x4247U, 0x4248U,\n\t0x4249U, 0x424AU, 0x424BU, 0x424CU, 0x424DU, 0x424EU, 0x424FU, 0x4250U,\n\t0x4251U, 0x4252U, 0x4253U, 0x4254U, 0x4255U, 0x4256U, 0x4257U, 0x4258U,\n\t0x4259U, 0x425AU, 0x4261U, 0x4262U, 0x4263U, 0x4264U, 0x4265U, 0x4266U,\n\t0x4267U, 0x4268U, 0x4269U, 0x426AU, 0x426BU, 0x426CU, 0x426DU, 0x426EU,\n\t0x426FU, 0x4270U, 0x4271U, 0x4272U, 0x4273U, 0x4274U, 0x4275U, 0x4276U,\n\t0x4277U, 0x4278U, 0x4279U, 0x427AU, 0x4230U, 0x4231U, 0x4232U, 0x4233U,\n\t0x4234U, 0x4235U, 0x4236U, 0x4237U, 0x4238U, 0x4239U, 0x422BU, 0x422FU,\n\t0x4341U, 0x4342U, 0x4343U, 0x4344U, 0x4345U, 0x4346U, 0x4347U, 0x4348U,\n\t0x4349U, 0x434AU, 0x434BU, 0x434CU, 0x434DU, 0x434EU, 0x434FU, 0x4350U,\n\t0x4351U, 0x4352U, 0x4353U, 0x4354U, 0x4355U, 0x4356U, 0x4357U, 0x4358U,\n\t0x4359U, 0x435AU, 0x4361U, 0x4362U, 0x4363U, 0x4364U, 0x4365U, 0x4366U,\n\t0x4367U, 0x4368U, 0x4369U, 0x436AU, 0x436BU, 0x436CU, 0x436DU, 0x436EU,\n\t0x436FU, 0x4370U, 0x4371U, 0x4372U, 0x4373U, 0x4374U, 0x4375U, 0x4376U,\n\t0x4377U, 0x4378U, 0x4379U, 0x437AU, 0x4330U, 0x4331U, 0x4332U, 0x4333U,\n\t0x4334U, 0x4335U, 0x4336U, 0x4337U, 0x4338U, 0x4339U, 0x432BU, 0x432FU,\n\t0x4441U, 0x4442U, 0x4443U, 0x4444U, 0x4445U, 0x4446U, 0x4447U, 0x4448U,\n\t0x4449U, 0x444AU, 0x444BU, 0x444CU, 0x444DU, 0x444EU, 0x444FU, 0x4450U,\n\t0x4451U, 0x4452U, 0x4453U, 0x4454U, 0x4455U, 0x4456U, 0x4457U, 0x4458U,\n\t0x4459U, 0x445AU, 0x4461U, 0x4462U, 0x4463U, 0x4464U, 0x4465U, 0x4466U,\n\t0x4467U, 0x4468U, 0x4469U, 0x446AU, 0x446BU, 0x446CU, 0x446DU, 0x446EU,\n\t0x446FU, 0x4470U, 0x4471U, 0x4472U, 0x4473U, 0x4474U, 0x4475U, 0x4476U,\n\t0x4477U, 0x4478U, 0x4479U, 0x447AU, 0x4430U, 0x4431U, 0x4432U, 0x4433U,\n\t0x4434U, 0x4435U, 0x4436U, 0x4437U, 0x4438U, 0x4439U, 0x442BU, 0x442FU,\n\t0x4541U, 0x4542U, 0x4543U, 0x4544U, 0x4545U, 0x4546U, 0x4547U, 0x4548U,\n\t0x4549U, 0x454AU, 0x454BU, 0x454CU, 0x454DU, 0x454EU, 0x454FU, 0x4550U,\n\t0x4551U, 0x4552U, 0x4553U, 0x4554U, 0x4555U, 0x4556U, 0x4557U, 0x4558U,\n\t0x4559U, 0x455AU, 0x4561U, 0x4562U, 0x4563U, 0x4564U, 0x4565U, 0x4566U,\n\t0x4567U, 0x4568U, 0x4569U, 0x456AU, 0x456BU, 0x456CU, 0x456DU, 0x456EU,\n\t0x456FU, 0x4570U, 0x4571U, 0x4572U, 0x4573U, 0x4574U, 0x4575U, 0x4576U,\n\t0x4577U, 0x4578U, 0x4579U, 0x457AU, 0x4530U, 0x4531U, 0x4532U, 0x4533U,\n\t0x4534U, 0x4535U, 0x4536U, 0x4537U, 0x4538U, 0x4539U, 0x452BU, 0x452FU,\n\t0x4641U, 0x4642U, 0x4643U, 0x4644U, 0x4645U, 0x4646U, 0x4647U, 0x4648U,\n\t0x4649U, 0x464AU, 0x464BU, 0x464CU, 0x464DU, 0x464EU, 0x464FU, 0x4650U,\n\t0x4651U, 0x4652U, 0x4653U, 0x4654U, 0x4655U, 0x4656U, 0x4657U, 0x4658U,\n\t0x4659U, 0x465AU, 0x4661U, 0x4662U, 0x4663U, 0x4664U, 0x4665U, 0x4666U,\n\t0x4667U, 0x4668U, 0x4669U, 0x466AU, 0x466BU, 0x466CU, 0x466DU, 0x466EU,\n\t0x466FU, 0x4670U, 0x4671U, 0x4672U, 0x4673U, 0x4674U, 0x4675U, 0x4676U,\n\t0x4677U, 0x4678U, 0x4679U, 0x467AU, 0x4630U, 0x4631U, 0x4632U, 0x4633U,\n\t0x4634U, 0x4635U, 0x4636U, 0x4637U, 0x4638U, 0x4639U, 0x462BU, 0x462FU,\n\t0x4741U, 0x4742U, 0x4743U, 0x4744U, 0x4745U, 0x4746U, 0x4747U, 0x4748U,\n\t0x4749U, 0x474AU, 0x474BU, 0x474CU, 0x474DU, 0x474EU, 0x474FU, 0x4750U,\n\t0x4751U, 0x4752U, 0x4753U, 0x4754U, 0x4755U, 0x4756U, 0x4757U, 0x4758U,\n\t0x4759U, 0x475AU, 0x4761U, 0x4762U, 0x4763U, 0x4764U, 0x4765U, 0x4766U,\n\t0x4767U, 0x4768U, 0x4769U, 0x476AU, 0x476BU, 0x476CU, 0x476DU, 0x476EU,\n\t0x476FU, 0x4770U, 0x4771U, 0x4772U, 0x4773U, 0x4774U, 0x4775U, 0x4776U,\n\t0x4777U, 0x4778U, 0x4779U, 0x477AU, 0x4730U, 0x4731U, 0x4732U, 0x4733U,\n\t0x4734U, 0x4735U, 0x4736U, 0x4737U, 0x4738U, 0x4739U, 0x472BU, 0x472FU,\n\t0x4841U, 0x4842U, 0x4843U, 0x4844U, 0x4845U, 0x4846U, 0x4847U, 0x4848U,\n\t0x4849U, 0x484AU, 0x484BU, 0x484CU, 0x484DU, 0x484EU, 0x484FU, 0x4850U,\n\t0x4851U, 0x4852U, 0x4853U, 0x4854U, 0x4855U, 0x4856U, 0x4857U, 0x4858U,\n\t0x4859U, 0x485AU, 0x4861U, 0x4862U, 0x4863U, 0x4864U, 0x4865U, 0x4866U,\n\t0x4867U, 0x4868U, 0x4869U, 0x486AU, 0x486BU, 0x486CU, 0x486DU, 0x486EU,\n\t0x486FU, 0x4870U, 0x4871U, 0x4872U, 0x4873U, 0x4874U, 0x4875U, 0x4876U,\n\t0x4877U, 0x4878U, 0x4879U, 0x487AU, 0x4830U, 0x4831U, 0x4832U, 0x4833U,\n\t0x4834U, 0x4835U, 0x4836U, 0x4837U, 0x4838U, 0x4839U, 0x482BU, 0x482FU,\n\t0x4941U, 0x4942U, 0x4943U, 0x4944U, 0x4945U, 0x4946U, 0x4947U, 0x4948U,\n\t0x4949U, 0x494AU, 0x494BU, 0x494CU, 0x494DU, 0x494EU, 0x494FU, 0x4950U,\n\t0x4951U, 0x4952U, 0x4953U, 0x4954U, 0x4955U, 0x4956U, 0x4957U, 0x4958U,\n\t0x4959U, 0x495AU, 0x4961U, 0x4962U, 0x4963U, 0x4964U, 0x4965U, 0x4966U,\n\t0x4967U, 0x4968U, 0x4969U, 0x496AU, 0x496BU, 0x496CU, 0x496DU, 0x496EU,\n\t0x496FU, 0x4970U, 0x4971U, 0x4972U, 0x4973U, 0x4974U, 0x4975U, 0x4976U,\n\t0x4977U, 0x4978U, 0x4979U, 0x497AU, 0x4930U, 0x4931U, 0x4932U, 0x4933U,\n\t0x4934U, 0x4935U, 0x4936U, 0x4937U, 0x4938U, 0x4939U, 0x492BU, 0x492FU,\n\t0x4A41U, 0x4A42U, 0x4A43U, 0x4A44U, 0x4A45U, 0x4A46U, 0x4A47U, 0x4A48U,\n\t0x4A49U, 0x4A4AU, 0x4A4BU, 0x4A4CU, 0x4A4DU, 0x4A4EU, 0x4A4FU, 0x4A50U,\n\t0x4A51U, 0x4A52U, 0x4A53U, 0x4A54U, 0x4A55U, 0x4A56U, 0x4A57U, 0x4A58U,\n\t0x4A59U, 0x4A5AU, 0x4A61U, 0x4A62U, 0x4A63U, 0x4A64U, 0x4A65U, 0x4A66U,\n\t0x4A67U, 0x4A68U, 0x4A69U, 0x4A6AU, 0x4A6BU, 0x4A6CU, 0x4A6DU, 0x4A6EU,\n\t0x4A6FU, 0x4A70U, 0x4A71U, 0x4A72U, 0x4A73U, 0x4A74U, 0x4A75U, 0x4A76U,\n\t0x4A77U, 0x4A78U, 0x4A79U, 0x4A7AU, 0x4A30U, 0x4A31U, 0x4A32U, 0x4A33U,\n\t0x4A34U, 0x4A35U, 0x4A36U, 0x4A37U, 0x4A38U, 0x4A39U, 0x4A2BU, 0x4A2FU,\n\t0x4B41U, 0x4B42U, 0x4B43U, 0x4B44U, 0x4B45U, 0x4B46U, 0x4B47U, 0x4B48U,\n\t0x4B49U, 0x4B4AU, 0x4B4BU, 0x4B4CU, 0x4B4DU, 0x4B4EU, 0x4B4FU, 0x4B50U,\n\t0x4B51U, 0x4B52U, 0x4B53U, 0x4B54U, 0x4B55U, 0x4B56U, 0x4B57U, 0x4B58U,\n\t0x4B59U, 0x4B5AU, 0x4B61U, 0x4B62U, 0x4B63U, 0x4B64U, 0x4B65U, 0x4B66U,\n\t0x4B67U, 0x4B68U, 0x4B69U, 0x4B6AU, 0x4B6BU, 0x4B6CU, 0x4B6DU, 0x4B6EU,\n\t0x4B6FU, 0x4B70U, 0x4B71U, 0x4B72U, 0x4B73U, 0x4B74U, 0x4B75U, 0x4B76U,\n\t0x4B77U, 0x4B78U, 0x4B79U, 0x4B7AU, 0x4B30U, 0x4B31U, 0x4B32U, 0x4B33U,\n\t0x4B34U, 0x4B35U, 0x4B36U, 0x4B37U, 0x4B38U, 0x4B39U, 0x4B2BU, 0x4B2FU,\n\t0x4C41U, 0x4C42U, 0x4C43U, 0x4C44U, 0x4C45U, 0x4C46U, 0x4C47U, 0x4C48U,\n\t0x4C49U, 0x4C4AU, 0x4C4BU, 0x4C4CU, 0x4C4DU, 0x4C4EU, 0x4C4FU, 0x4C50U,\n\t0x4C51U, 0x4C52U, 0x4C53U, 0x4C54U, 0x4C55U, 0x4C56U, 0x4C57U, 0x4C58U,\n\t0x4C59U, 0x4C5AU, 0x4C61U, 0x4C62U, 0x4C63U, 0x4C64U, 0x4C65U, 0x4C66U,\n\t0x4C67U, 0x4C68U, 0x4C69U, 0x4C6AU, 0x4C6BU, 0x4C6CU, 0x4C6DU, 0x4C6EU,\n\t0x4C6FU, 0x4C70U, 0x4C71U, 0x4C72U, 0x4C73U, 0x4C74U, 0x4C75U, 0x4C76U,\n\t0x4C77U, 0x4C78U, 0x4C79U, 0x4C7AU, 0x4C30U, 0x4C31U, 0x4C32U, 0x4C33U,\n\t0x4C34U, 0x4C35U, 0x4C36U, 0x4C37U, 0x4C38U, 0x4C39U, 0x4C2BU, 0x4C2FU,\n\t0x4D41U, 0x4D42U, 0x4D43U, 0x4D44U, 0x4D45U, 0x4D46U, 0x4D47U, 0x4D48U,\n\t0x4D49U, 0x4D4AU, 0x4D4BU, 0x4D4CU, 0x4D4DU, 0x4D4EU, 0x4D4FU, 0x4D50U,\n\t0x4D51U, 0x4D52U, 0x4D53U, 0x4D54U, 0x4D55U, 0x4D56U, 0x4D57U, 0x4D58U,\n\t0x4D59U, 0x4D5AU, 0x4D61U, 0x4D62U, 0x4D63U, 0x4D64U, 0x4D65U, 0x4D66U,\n\t0x4D67U, 0x4D68U, 0x4D69U, 0x4D6AU, 0x4D6BU, 0x4D6CU, 0x4D6DU, 0x4D6EU,\n\t0x4D6FU, 0x4D70U, 0x4D71U, 0x4D72U, 0x4D73U, 0x4D74U, 0x4D75U, 0x4D76U,\n\t0x4D77U, 0x4D78U, 0x4D79U, 0x4D7AU, 0x4D30U, 0x4D31U, 0x4D32U, 0x4D33U,\n\t0x4D34U, 0x4D35U, 0x4D36U, 0x4D37U, 0x4D38U, 0x4D39U, 0x4D2BU, 0x4D2FU,\n\t0x4E41U, 0x4E42U, 0x4E43U, 0x4E44U, 0x4E45U, 0x4E46U, 0x4E47U, 0x4E48U,\n\t0x4E49U, 0x4E4AU, 0x4E4BU, 0x4E4CU, 0x4E4DU, 0x4E4EU, 0x4E4FU, 0x4E50U,\n\t0x4E51U, 0x4E52U, 0x4E53U, 0x4E54U, 0x4E55U, 0x4E56U, 0x4E57U, 0x4E58U,\n\t0x4E59U, 0x4E5AU, 0x4E61U, 0x4E62U, 0x4E63U, 0x4E64U, 0x4E65U, 0x4E66U,\n\t0x4E67U, 0x4E68U, 0x4E69U, 0x4E6AU, 0x4E6BU, 0x4E6CU, 0x4E6DU, 0x4E6EU,\n\t0x4E6FU, 0x4E70U, 0x4E71U, 0x4E72U, 0x4E73U, 0x4E74U, 0x4E75U, 0x4E76U,\n\t0x4E77U, 0x4E78U, 0x4E79U, 0x4E7AU, 0x4E30U, 0x4E31U, 0x4E32U, 0x4E33U,\n\t0x4E34U, 0x4E35U, 0x4E36U, 0x4E37U, 0x4E38U, 0x4E39U, 0x4E2BU, 0x4E2FU,\n\t0x4F41U, 0x4F42U, 0x4F43U, 0x4F44U, 0x4F45U, 0x4F46U, 0x4F47U, 0x4F48U,\n\t0x4F49U, 0x4F4AU, 0x4F4BU, 0x4F4CU, 0x4F4DU, 0x4F4EU, 0x4F4FU, 0x4F50U,\n\t0x4F51U, 0x4F52U, 0x4F53U, 0x4F54U, 0x4F55U, 0x4F56U, 0x4F57U, 0x4F58U,\n\t0x4F59U, 0x4F5AU, 0x4F61U, 0x4F62U, 0x4F63U, 0x4F64U, 0x4F65U, 0x4F66U,\n\t0x4F67U, 0x4F68U, 0x4F69U, 0x4F6AU, 0x4F6BU, 0x4F6CU, 0x4F6DU, 0x4F6EU,\n\t0x4F6FU, 0x4F70U, 0x4F71U, 0x4F72U, 0x4F73U, 0x4F74U, 0x4F75U, 0x4F76U,\n\t0x4F77U, 0x4F78U, 0x4F79U, 0x4F7AU, 0x4F30U, 0x4F31U, 0x4F32U, 0x4F33U,\n\t0x4F34U, 0x4F35U, 0x4F36U, 0x4F37U, 0x4F38U, 0x4F39U, 0x4F2BU, 0x4F2FU,\n\t0x5041U, 0x5042U, 0x5043U, 0x5044U, 0x5045U, 0x5046U, 0x5047U, 0x5048U,\n\t0x5049U, 0x504AU, 0x504BU, 0x504CU, 0x504DU, 0x504EU, 0x504FU, 0x5050U,\n\t0x5051U, 0x5052U, 0x5053U, 0x5054U, 0x5055U, 0x5056U, 0x5057U, 0x5058U,\n\t0x5059U, 0x505AU, 0x5061U, 0x5062U, 0x5063U, 0x5064U, 0x5065U, 0x5066U,\n\t0x5067U, 0x5068U, 0x5069U, 0x506AU, 0x506BU, 0x506CU, 0x506DU, 0x506EU,\n\t0x506FU, 0x5070U, 0x5071U, 0x5072U, 0x5073U, 0x5074U, 0x5075U, 0x5076U,\n\t0x5077U, 0x5078U, 0x5079U, 0x507AU, 0x5030U, 0x5031U, 0x5032U, 0x5033U,\n\t0x5034U, 0x5035U, 0x5036U, 0x5037U, 0x5038U, 0x5039U, 0x502BU, 0x502FU,\n\t0x5141U, 0x5142U, 0x5143U, 0x5144U, 0x5145U, 0x5146U, 0x5147U, 0x5148U,\n\t0x5149U, 0x514AU, 0x514BU, 0x514CU, 0x514DU, 0x514EU, 0x514FU, 0x5150U,\n\t0x5151U, 0x5152U, 0x5153U, 0x5154U, 0x5155U, 0x5156U, 0x5157U, 0x5158U,\n\t0x5159U, 0x515AU, 0x5161U, 0x5162U, 0x5163U, 0x5164U, 0x5165U, 0x5166U,\n\t0x5167U, 0x5168U, 0x5169U, 0x516AU, 0x516BU, 0x516CU, 0x516DU, 0x516EU,\n\t0x516FU, 0x5170U, 0x5171U, 0x5172U, 0x5173U, 0x5174U, 0x5175U, 0x5176U,\n\t0x5177U, 0x5178U, 0x5179U, 0x517AU, 0x5130U, 0x5131U, 0x5132U, 0x5133U,\n\t0x5134U, 0x5135U, 0x5136U, 0x5137U, 0x5138U, 0x5139U, 0x512BU, 0x512FU,\n\t0x5241U, 0x5242U, 0x5243U, 0x5244U, 0x5245U, 0x5246U, 0x5247U, 0x5248U,\n\t0x5249U, 0x524AU, 0x524BU, 0x524CU, 0x524DU, 0x524EU, 0x524FU, 0x5250U,\n\t0x5251U, 0x5252U, 0x5253U, 0x5254U, 0x5255U, 0x5256U, 0x5257U, 0x5258U,\n\t0x5259U, 0x525AU, 0x5261U, 0x5262U, 0x5263U, 0x5264U, 0x5265U, 0x5266U,\n\t0x5267U, 0x5268U, 0x5269U, 0x526AU, 0x526BU, 0x526CU, 0x526DU, 0x526EU,\n\t0x526FU, 0x5270U, 0x5271U, 0x5272U, 0x5273U, 0x5274U, 0x5275U, 0x5276U,\n\t0x5277U, 0x5278U, 0x5279U, 0x527AU, 0x5230U, 0x5231U, 0x5232U, 0x5233U,\n\t0x5234U, 0x5235U, 0x5236U, 0x5237U, 0x5238U, 0x5239U, 0x522BU, 0x522FU,\n\t0x5341U, 0x5342U, 0x5343U, 0x5344U, 0x5345U, 0x5346U, 0x5347U, 0x5348U,\n\t0x5349U, 0x534AU, 0x534BU, 0x534CU, 0x534DU, 0x534EU, 0x534FU, 0x5350U,\n\t0x5351U, 0x5352U, 0x5353U, 0x5354U, 0x5355U, 0x5356U, 0x5357U, 0x5358U,\n\t0x5359U, 0x535AU, 0x5361U, 0x5362U, 0x5363U, 0x5364U, 0x5365U, 0x5366U,\n\t0x5367U, 0x5368U, 0x5369U, 0x536AU, 0x536BU, 0x536CU, 0x536DU, 0x536EU,\n\t0x536FU, 0x5370U, 0x5371U, 0x5372U, 0x5373U, 0x5374U, 0x5375U, 0x5376U,\n\t0x5377U, 0x5378U, 0x5379U, 0x537AU, 0x5330U, 0x5331U, 0x5332U, 0x5333U,\n\t0x5334U, 0x5335U, 0x5336U, 0x5337U, 0x5338U, 0x5339U, 0x532BU, 0x532FU,\n\t0x5441U, 0x5442U, 0x5443U, 0x5444U, 0x5445U, 0x5446U, 0x5447U, 0x5448U,\n\t0x5449U, 0x544AU, 0x544BU, 0x544CU, 0x544DU, 0x544EU, 0x544FU, 0x5450U,\n\t0x5451U, 0x5452U, 0x5453U, 0x5454U, 0x5455U, 0x5456U, 0x5457U, 0x5458U,\n\t0x5459U, 0x545AU, 0x5461U, 0x5462U, 0x5463U, 0x5464U, 0x5465U, 0x5466U,\n\t0x5467U, 0x5468U, 0x5469U, 0x546AU, 0x546BU, 0x546CU, 0x546DU, 0x546EU,\n\t0x546FU, 0x5470U, 0x5471U, 0x5472U, 0x5473U, 0x5474U, 0x5475U, 0x5476U,\n\t0x5477U, 0x5478U, 0x5479U, 0x547AU, 0x5430U, 0x5431U, 0x5432U, 0x5433U,\n\t0x5434U, 0x5435U, 0x5436U, 0x5437U, 0x5438U, 0x5439U, 0x542BU, 0x542FU,\n\t0x5541U, 0x5542U, 0x5543U, 0x5544U, 0x5545U, 0x5546U, 0x5547U, 0x5548U,\n\t0x5549U, 0x554AU, 0x554BU, 0x554CU, 0x554DU, 0x554EU, 0x554FU, 0x5550U,\n\t0x5551U, 0x5552U, 0x5553U, 0x5554U, 0x5555U, 0x5556U, 0x5557U, 0x5558U,\n\t0x5559U, 0x555AU, 0x5561U, 0x5562U, 0x5563U, 0x5564U, 0x5565U, 0x5566U,\n\t0x5567U, 0x5568U, 0x5569U, 0x556AU, 0x556BU, 0x556CU, 0x556DU, 0x556EU,\n\t0x556FU, 0x5570U, 0x5571U, 0x5572U, 0x5573U, 0x5574U, 0x5575U, 0x5576U,\n\t0x5577U, 0x5578U, 0x5579U, 0x557AU, 0x5530U, 0x5531U, 0x5532U, 0x5533U,\n\t0x5534U, 0x5535U, 0x5536U, 0x5537U, 0x5538U, 0x5539U, 0x552BU, 0x552FU,\n\t0x5641U, 0x5642U, 0x5643U, 0x5644U, 0x5645U, 0x5646U, 0x5647U, 0x5648U,\n\t0x5649U, 0x564AU, 0x564BU, 0x564CU, 0x564DU, 0x564EU, 0x564FU, 0x5650U,\n\t0x5651U, 0x5652U, 0x5653U, 0x5654U, 0x5655U, 0x5656U, 0x5657U, 0x5658U,\n\t0x5659U, 0x565AU, 0x5661U, 0x5662U, 0x5663U, 0x5664U, 0x5665U, 0x5666U,\n\t0x5667U, 0x5668U, 0x5669U, 0x566AU, 0x566BU, 0x566CU, 0x566DU, 0x566EU,\n\t0x566FU, 0x5670U, 0x5671U, 0x5672U, 0x5673U, 0x5674U, 0x5675U, 0x5676U,\n\t0x5677U, 0x5678U, 0x5679U, 0x567AU, 0x5630U, 0x5631U, 0x5632U, 0x5633U,\n\t0x5634U, 0x5635U, 0x5636U, 0x5637U, 0x5638U, 0x5639U, 0x562BU, 0x562FU,\n\t0x5741U, 0x5742U, 0x5743U, 0x5744U, 0x5745U, 0x5746U, 0x5747U, 0x5748U,\n\t0x5749U, 0x574AU, 0x574BU, 0x574CU, 0x574DU, 0x574EU, 0x574FU, 0x5750U,\n\t0x5751U, 0x5752U, 0x5753U, 0x5754U, 0x5755U, 0x5756U, 0x5757U, 0x5758U,\n\t0x5759U, 0x575AU, 0x5761U, 0x5762U, 0x5763U, 0x5764U, 0x5765U, 0x5766U,\n\t0x5767U, 0x5768U, 0x5769U, 0x576AU, 0x576BU, 0x576CU, 0x576DU, 0x576EU,\n\t0x576FU, 0x5770U, 0x5771U, 0x5772U, 0x5773U, 0x5774U, 0x5775U, 0x5776U,\n\t0x5777U, 0x5778U, 0x5779U, 0x577AU, 0x5730U, 0x5731U, 0x5732U, 0x5733U,\n\t0x5734U, 0x5735U, 0x5736U, 0x5737U, 0x5738U, 0x5739U, 0x572BU, 0x572FU,\n\t0x5841U, 0x5842U, 0x5843U, 0x5844U, 0x5845U, 0x5846U, 0x5847U, 0x5848U,\n\t0x5849U, 0x584AU, 0x584BU, 0x584CU, 0x584DU, 0x584EU, 0x584FU, 0x5850U,\n\t0x5851U, 0x5852U, 0x5853U, 0x5854U, 0x5855U, 0x5856U, 0x5857U, 0x5858U,\n\t0x5859U, 0x585AU, 0x5861U, 0x5862U, 0x5863U, 0x5864U, 0x5865U, 0x5866U,\n\t0x5867U, 0x5868U, 0x5869U, 0x586AU, 0x586BU, 0x586CU, 0x586DU, 0x586EU,\n\t0x586FU, 0x5870U, 0x5871U, 0x5872U, 0x5873U, 0x5874U, 0x5875U, 0x5876U,\n\t0x5877U, 0x5878U, 0x5879U, 0x587AU, 0x5830U, 0x5831U, 0x5832U, 0x5833U,\n\t0x5834U, 0x5835U, 0x5836U, 0x5837U, 0x5838U, 0x5839U, 0x582BU, 0x582FU,\n\t0x5941U, 0x5942U, 0x5943U, 0x5944U, 0x5945U, 0x5946U, 0x5947U, 0x5948U,\n\t0x5949U, 0x594AU, 0x594BU, 0x594CU, 0x594DU, 0x594EU, 0x594FU, 0x5950U,\n\t0x5951U, 0x5952U, 0x5953U, 0x5954U, 0x5955U, 0x5956U, 0x5957U, 0x5958U,\n\t0x5959U, 0x595AU, 0x5961U, 0x5962U, 0x5963U, 0x5964U, 0x5965U, 0x5966U,\n\t0x5967U, 0x5968U, 0x5969U, 0x596AU, 0x596BU, 0x596CU, 0x596DU, 0x596EU,\n\t0x596FU, 0x5970U, 0x5971U, 0x5972U, 0x5973U, 0x5974U, 0x5975U, 0x5976U,\n\t0x5977U, 0x5978U, 0x5979U, 0x597AU, 0x5930U, 0x5931U, 0x5932U, 0x5933U,\n\t0x5934U, 0x5935U, 0x5936U, 0x5937U, 0x5938U, 0x5939U, 0x592BU, 0x592FU,\n\t0x5A41U, 0x5A42U, 0x5A43U, 0x5A44U, 0x5A45U, 0x5A46U, 0x5A47U, 0x5A48U,\n\t0x5A49U, 0x5A4AU, 0x5A4BU, 0x5A4CU, 0x5A4DU, 0x5A4EU, 0x5A4FU, 0x5A50U,\n\t0x5A51U, 0x5A52U, 0x5A53U, 0x5A54U, 0x5A55U, 0x5A56U, 0x5A57U, 0x5A58U,\n\t0x5A59U, 0x5A5AU, 0x5A61U, 0x5A62U, 0x5A63U, 0x5A64U, 0x5A65U, 0x5A66U,\n\t0x5A67U, 0x5A68U, 0x5A69U, 0x5A6AU, 0x5A6BU, 0x5A6CU, 0x5A6DU, 0x5A6EU,\n\t0x5A6FU, 0x5A70U, 0x5A71U, 0x5A72U, 0x5A73U, 0x5A74U, 0x5A75U, 0x5A76U,\n\t0x5A77U, 0x5A78U, 0x5A79U, 0x5A7AU, 0x5A30U, 0x5A31U, 0x5A32U, 0x5A33U,\n\t0x5A34U, 0x5A35U, 0x5A36U, 0x5A37U, 0x5A38U, 0x5A39U, 0x5A2BU, 0x5A2FU,\n\t0x6141U, 0x6142U, 0x6143U, 0x6144U, 0x6145U, 0x6146U, 0x6147U, 0x6148U,\n\t0x6149U, 0x614AU, 0x614BU, 0x614CU, 0x614DU, 0x614EU, 0x614FU, 0x6150U,\n\t0x6151U, 0x6152U, 0x6153U, 0x6154U, 0x6155U, 0x6156U, 0x6157U, 0x6158U,\n\t0x6159U, 0x615AU, 0x6161U, 0x6162U, 0x6163U, 0x6164U, 0x6165U, 0x6166U,\n\t0x6167U, 0x6168U, 0x6169U, 0x616AU, 0x616BU, 0x616CU, 0x616DU, 0x616EU,\n\t0x616FU, 0x6170U, 0x6171U, 0x6172U, 0x6173U, 0x6174U, 0x6175U, 0x6176U,\n\t0x6177U, 0x6178U, 0x6179U, 0x617AU, 0x6130U, 0x6131U, 0x6132U, 0x6133U,\n\t0x6134U, 0x6135U, 0x6136U, 0x6137U, 0x6138U, 0x6139U, 0x612BU, 0x612FU,\n\t0x6241U, 0x6242U, 0x6243U, 0x6244U, 0x6245U, 0x6246U, 0x6247U, 0x6248U,\n\t0x6249U, 0x624AU, 0x624BU, 0x624CU, 0x624DU, 0x624EU, 0x624FU, 0x6250U,\n\t0x6251U, 0x6252U, 0x6253U, 0x6254U, 0x6255U, 0x6256U, 0x6257U, 0x6258U,\n\t0x6259U, 0x625AU, 0x6261U, 0x6262U, 0x6263U, 0x6264U, 0x6265U, 0x6266U,\n\t0x6267U, 0x6268U, 0x6269U, 0x626AU, 0x626BU, 0x626CU, 0x626DU, 0x626EU,\n\t0x626FU, 0x6270U, 0x6271U, 0x6272U, 0x6273U, 0x6274U, 0x6275U, 0x6276U,\n\t0x6277U, 0x6278U, 0x6279U, 0x627AU, 0x6230U, 0x6231U, 0x6232U, 0x6233U,\n\t0x6234U, 0x6235U, 0x6236U, 0x6237U, 0x6238U, 0x6239U, 0x622BU, 0x622FU,\n\t0x6341U, 0x6342U, 0x6343U, 0x6344U, 0x6345U, 0x6346U, 0x6347U, 0x6348U,\n\t0x6349U, 0x634AU, 0x634BU, 0x634CU, 0x634DU, 0x634EU, 0x634FU, 0x6350U,\n\t0x6351U, 0x6352U, 0x6353U, 0x6354U, 0x6355U, 0x6356U, 0x6357U, 0x6358U,\n\t0x6359U, 0x635AU, 0x6361U, 0x6362U, 0x6363U, 0x6364U, 0x6365U, 0x6366U,\n\t0x6367U, 0x6368U, 0x6369U, 0x636AU, 0x636BU, 0x636CU, 0x636DU, 0x636EU,\n\t0x636FU, 0x6370U, 0x6371U, 0x6372U, 0x6373U, 0x6374U, 0x6375U, 0x6376U,\n\t0x6377U, 0x6378U, 0x6379U, 0x637AU, 0x6330U, 0x6331U, 0x6332U, 0x6333U,\n\t0x6334U, 0x6335U, 0x6336U, 0x6337U, 0x6338U, 0x6339U, 0x632BU, 0x632FU,\n\t0x6441U, 0x6442U, 0x6443U, 0x6444U, 0x6445U, 0x6446U, 0x6447U, 0x6448U,\n\t0x6449U, 0x644AU, 0x644BU, 0x644CU, 0x644DU, 0x644EU, 0x644FU, 0x6450U,\n\t0x6451U, 0x6452U, 0x6453U, 0x6454U, 0x6455U, 0x6456U, 0x6457U, 0x6458U,\n\t0x6459U, 0x645AU, 0x6461U, 0x6462U, 0x6463U, 0x6464U, 0x6465U, 0x6466U,\n\t0x6467U, 0x6468U, 0x6469U, 0x646AU, 0x646BU, 0x646CU, 0x646DU, 0x646EU,\n\t0x646FU, 0x6470U, 0x6471U, 0x6472U, 0x6473U, 0x6474U, 0x6475U, 0x6476U,\n\t0x6477U, 0x6478U, 0x6479U, 0x647AU, 0x6430U, 0x6431U, 0x6432U, 0x6433U,\n\t0x6434U, 0x6435U, 0x6436U, 0x6437U, 0x6438U, 0x6439U, 0x642BU, 0x642FU,\n\t0x6541U, 0x6542U, 0x6543U, 0x6544U, 0x6545U, 0x6546U, 0x6547U, 0x6548U,\n\t0x6549U, 0x654AU, 0x654BU, 0x654CU, 0x654DU, 0x654EU, 0x654FU, 0x6550U,\n\t0x6551U, 0x6552U, 0x6553U, 0x6554U, 0x6555U, 0x6556U, 0x6557U, 0x6558U,\n\t0x6559U, 0x655AU, 0x6561U, 0x6562U, 0x6563U, 0x6564U, 0x6565U, 0x6566U,\n\t0x6567U, 0x6568U, 0x6569U, 0x656AU, 0x656BU, 0x656CU, 0x656DU, 0x656EU,\n\t0x656FU, 0x6570U, 0x6571U, 0x6572U, 0x6573U, 0x6574U, 0x6575U, 0x6576U,\n\t0x6577U, 0x6578U, 0x6579U, 0x657AU, 0x6530U, 0x6531U, 0x6532U, 0x6533U,\n\t0x6534U, 0x6535U, 0x6536U, 0x6537U, 0x6538U, 0x6539U, 0x652BU, 0x652FU,\n\t0x6641U, 0x6642U, 0x6643U, 0x6644U, 0x6645U, 0x6646U, 0x6647U, 0x6648U,\n\t0x6649U, 0x664AU, 0x664BU, 0x664CU, 0x664DU, 0x664EU, 0x664FU, 0x6650U,\n\t0x6651U, 0x6652U, 0x6653U, 0x6654U, 0x6655U, 0x6656U, 0x6657U, 0x6658U,\n\t0x6659U, 0x665AU, 0x6661U, 0x6662U, 0x6663U, 0x6664U, 0x6665U, 0x6666U,\n\t0x6667U, 0x6668U, 0x6669U, 0x666AU, 0x666BU, 0x666CU, 0x666DU, 0x666EU,\n\t0x666FU, 0x6670U, 0x6671U, 0x6672U, 0x6673U, 0x6674U, 0x6675U, 0x6676U,\n\t0x6677U, 0x6678U, 0x6679U, 0x667AU, 0x6630U, 0x6631U, 0x6632U, 0x6633U,\n\t0x6634U, 0x6635U, 0x6636U, 0x6637U, 0x6638U, 0x6639U, 0x662BU, 0x662FU,\n\t0x6741U, 0x6742U, 0x6743U, 0x6744U, 0x6745U, 0x6746U, 0x6747U, 0x6748U,\n\t0x6749U, 0x674AU, 0x674BU, 0x674CU, 0x674DU, 0x674EU, 0x674FU, 0x6750U,\n\t0x6751U, 0x6752U, 0x6753U, 0x6754U, 0x6755U, 0x6756U, 0x6757U, 0x6758U,\n\t0x6759U, 0x675AU, 0x6761U, 0x6762U, 0x6763U, 0x6764U, 0x6765U, 0x6766U,\n\t0x6767U, 0x6768U, 0x6769U, 0x676AU, 0x676BU, 0x676CU, 0x676DU, 0x676EU,\n\t0x676FU, 0x6770U, 0x6771U, 0x6772U, 0x6773U, 0x6774U, 0x6775U, 0x6776U,\n\t0x6777U, 0x6778U, 0x6779U, 0x677AU, 0x6730U, 0x6731U, 0x6732U, 0x6733U,\n\t0x6734U, 0x6735U, 0x6736U, 0x6737U, 0x6738U, 0x6739U, 0x672BU, 0x672FU,\n\t0x6841U, 0x6842U, 0x6843U, 0x6844U, 0x6845U, 0x6846U, 0x6847U, 0x6848U,\n\t0x6849U, 0x684AU, 0x684BU, 0x684CU, 0x684DU, 0x684EU, 0x684FU, 0x6850U,\n\t0x6851U, 0x6852U, 0x6853U, 0x6854U, 0x6855U, 0x6856U, 0x6857U, 0x6858U,\n\t0x6859U, 0x685AU, 0x6861U, 0x6862U, 0x6863U, 0x6864U, 0x6865U, 0x6866U,\n\t0x6867U, 0x6868U, 0x6869U, 0x686AU, 0x686BU, 0x686CU, 0x686DU, 0x686EU,\n\t0x686FU, 0x6870U, 0x6871U, 0x6872U, 0x6873U, 0x6874U, 0x6875U, 0x6876U,\n\t0x6877U, 0x6878U, 0x6879U, 0x687AU, 0x6830U, 0x6831U, 0x6832U, 0x6833U,\n\t0x6834U, 0x6835U, 0x6836U, 0x6837U, 0x6838U, 0x6839U, 0x682BU, 0x682FU,\n\t0x6941U, 0x6942U, 0x6943U, 0x6944U, 0x6945U, 0x6946U, 0x6947U, 0x6948U,\n\t0x6949U, 0x694AU, 0x694BU, 0x694CU, 0x694DU, 0x694EU, 0x694FU, 0x6950U,\n\t0x6951U, 0x6952U, 0x6953U, 0x6954U, 0x6955U, 0x6956U, 0x6957U, 0x6958U,\n\t0x6959U, 0x695AU, 0x6961U, 0x6962U, 0x6963U, 0x6964U, 0x6965U, 0x6966U,\n\t0x6967U, 0x6968U, 0x6969U, 0x696AU, 0x696BU, 0x696CU, 0x696DU, 0x696EU,\n\t0x696FU, 0x6970U, 0x6971U, 0x6972U, 0x6973U, 0x6974U, 0x6975U, 0x6976U,\n\t0x6977U, 0x6978U, 0x6979U, 0x697AU, 0x6930U, 0x6931U, 0x6932U, 0x6933U,\n\t0x6934U, 0x6935U, 0x6936U, 0x6937U, 0x6938U, 0x6939U, 0x692BU, 0x692FU,\n\t0x6A41U, 0x6A42U, 0x6A43U, 0x6A44U, 0x6A45U, 0x6A46U, 0x6A47U, 0x6A48U,\n\t0x6A49U, 0x6A4AU, 0x6A4BU, 0x6A4CU, 0x6A4DU, 0x6A4EU, 0x6A4FU, 0x6A50U,\n\t0x6A51U, 0x6A52U, 0x6A53U, 0x6A54U, 0x6A55U, 0x6A56U, 0x6A57U, 0x6A58U,\n\t0x6A59U, 0x6A5AU, 0x6A61U, 0x6A62U, 0x6A63U, 0x6A64U, 0x6A65U, 0x6A66U,\n\t0x6A67U, 0x6A68U, 0x6A69U, 0x6A6AU, 0x6A6BU, 0x6A6CU, 0x6A6DU, 0x6A6EU,\n\t0x6A6FU, 0x6A70U, 0x6A71U, 0x6A72U, 0x6A73U, 0x6A74U, 0x6A75U, 0x6A76U,\n\t0x6A77U, 0x6A78U, 0x6A79U, 0x6A7AU, 0x6A30U, 0x6A31U, 0x6A32U, 0x6A33U,\n\t0x6A34U, 0x6A35U, 0x6A36U, 0x6A37U, 0x6A38U, 0x6A39U, 0x6A2BU, 0x6A2FU,\n\t0x6B41U, 0x6B42U, 0x6B43U, 0x6B44U, 0x6B45U, 0x6B46U, 0x6B47U, 0x6B48U,\n\t0x6B49U, 0x6B4AU, 0x6B4BU, 0x6B4CU, 0x6B4DU, 0x6B4EU, 0x6B4FU, 0x6B50U,\n\t0x6B51U, 0x6B52U, 0x6B53U, 0x6B54U, 0x6B55U, 0x6B56U, 0x6B57U, 0x6B58U,\n\t0x6B59U, 0x6B5AU, 0x6B61U, 0x6B62U, 0x6B63U, 0x6B64U, 0x6B65U, 0x6B66U,\n\t0x6B67U, 0x6B68U, 0x6B69U, 0x6B6AU, 0x6B6BU, 0x6B6CU, 0x6B6DU, 0x6B6EU,\n\t0x6B6FU, 0x6B70U, 0x6B71U, 0x6B72U, 0x6B73U, 0x6B74U, 0x6B75U, 0x6B76U,\n\t0x6B77U, 0x6B78U, 0x6B79U, 0x6B7AU, 0x6B30U, 0x6B31U, 0x6B32U, 0x6B33U,\n\t0x6B34U, 0x6B35U, 0x6B36U, 0x6B37U, 0x6B38U, 0x6B39U, 0x6B2BU, 0x6B2FU,\n\t0x6C41U, 0x6C42U, 0x6C43U, 0x6C44U, 0x6C45U, 0x6C46U, 0x6C47U, 0x6C48U,\n\t0x6C49U, 0x6C4AU, 0x6C4BU, 0x6C4CU, 0x6C4DU, 0x6C4EU, 0x6C4FU, 0x6C50U,\n\t0x6C51U, 0x6C52U, 0x6C53U, 0x6C54U, 0x6C55U, 0x6C56U, 0x6C57U, 0x6C58U,\n\t0x6C59U, 0x6C5AU, 0x6C61U, 0x6C62U, 0x6C63U, 0x6C64U, 0x6C65U, 0x6C66U,\n\t0x6C67U, 0x6C68U, 0x6C69U, 0x6C6AU, 0x6C6BU, 0x6C6CU, 0x6C6DU, 0x6C6EU,\n\t0x6C6FU, 0x6C70U, 0x6C71U, 0x6C72U, 0x6C73U, 0x6C74U, 0x6C75U, 0x6C76U,\n\t0x6C77U, 0x6C78U, 0x6C79U, 0x6C7AU, 0x6C30U, 0x6C31U, 0x6C32U, 0x6C33U,\n\t0x6C34U, 0x6C35U, 0x6C36U, 0x6C37U, 0x6C38U, 0x6C39U, 0x6C2BU, 0x6C2FU,\n\t0x6D41U, 0x6D42U, 0x6D43U, 0x6D44U, 0x6D45U, 0x6D46U, 0x6D47U, 0x6D48U,\n\t0x6D49U, 0x6D4AU, 0x6D4BU, 0x6D4CU, 0x6D4DU, 0x6D4EU, 0x6D4FU, 0x6D50U,\n\t0x6D51U, 0x6D52U, 0x6D53U, 0x6D54U, 0x6D55U, 0x6D56U, 0x6D57U, 0x6D58U,\n\t0x6D59U, 0x6D5AU, 0x6D61U, 0x6D62U, 0x6D63U, 0x6D64U, 0x6D65U, 0x6D66U,\n\t0x6D67U, 0x6D68U, 0x6D69U, 0x6D6AU, 0x6D6BU, 0x6D6CU, 0x6D6DU, 0x6D6EU,\n\t0x6D6FU, 0x6D70U, 0x6D71U, 0x6D72U, 0x6D73U, 0x6D74U, 0x6D75U, 0x6D76U,\n\t0x6D77U, 0x6D78U, 0x6D79U, 0x6D7AU, 0x6D30U, 0x6D31U, 0x6D32U, 0x6D33U,\n\t0x6D34U, 0x6D35U, 0x6D36U, 0x6D37U, 0x6D38U, 0x6D39U, 0x6D2BU, 0x6D2FU,\n\t0x6E41U, 0x6E42U, 0x6E43U, 0x6E44U, 0x6E45U, 0x6E46U, 0x6E47U, 0x6E48U,\n\t0x6E49U, 0x6E4AU, 0x6E4BU, 0x6E4CU, 0x6E4DU, 0x6E4EU, 0x6E4FU, 0x6E50U,\n\t0x6E51U, 0x6E52U, 0x6E53U, 0x6E54U, 0x6E55U, 0x6E56U, 0x6E57U, 0x6E58U,\n\t0x6E59U, 0x6E5AU, 0x6E61U, 0x6E62U, 0x6E63U, 0x6E64U, 0x6E65U, 0x6E66U,\n\t0x6E67U, 0x6E68U, 0x6E69U, 0x6E6AU, 0x6E6BU, 0x6E6CU, 0x6E6DU, 0x6E6EU,\n\t0x6E6FU, 0x6E70U, 0x6E71U, 0x6E72U, 0x6E73U, 0x6E74U, 0x6E75U, 0x6E76U,\n\t0x6E77U, 0x6E78U, 0x6E79U, 0x6E7AU, 0x6E30U, 0x6E31U, 0x6E32U, 0x6E33U,\n\t0x6E34U, 0x6E35U, 0x6E36U, 0x6E37U, 0x6E38U, 0x6E39U, 0x6E2BU, 0x6E2FU,\n\t0x6F41U, 0x6F42U, 0x6F43U, 0x6F44U, 0x6F45U, 0x6F46U, 0x6F47U, 0x6F48U,\n\t0x6F49U, 0x6F4AU, 0x6F4BU, 0x6F4CU, 0x6F4DU, 0x6F4EU, 0x6F4FU, 0x6F50U,\n\t0x6F51U, 0x6F52U, 0x6F53U, 0x6F54U, 0x6F55U, 0x6F56U, 0x6F57U, 0x6F58U,\n\t0x6F59U, 0x6F5AU, 0x6F61U, 0x6F62U, 0x6F63U, 0x6F64U, 0x6F65U, 0x6F66U,\n\t0x6F67U, 0x6F68U, 0x6F69U, 0x6F6AU, 0x6F6BU, 0x6F6CU, 0x6F6DU, 0x6F6EU,\n\t0x6F6FU, 0x6F70U, 0x6F71U, 0x6F72U, 0x6F73U, 0x6F74U, 0x6F75U, 0x6F76U,\n\t0x6F77U, 0x6F78U, 0x6F79U, 0x6F7AU, 0x6F30U, 0x6F31U, 0x6F32U, 0x6F33U,\n\t0x6F34U, 0x6F35U, 0x6F36U, 0x6F37U, 0x6F38U, 0x6F39U, 0x6F2BU, 0x6F2FU,\n\t0x7041U, 0x7042U, 0x7043U, 0x7044U, 0x7045U, 0x7046U, 0x7047U, 0x7048U,\n\t0x7049U, 0x704AU, 0x704BU, 0x704CU, 0x704DU, 0x704EU, 0x704FU, 0x7050U,\n\t0x7051U, 0x7052U, 0x7053U, 0x7054U, 0x7055U, 0x7056U, 0x7057U, 0x7058U,\n\t0x7059U, 0x705AU, 0x7061U, 0x7062U, 0x7063U, 0x7064U, 0x7065U, 0x7066U,\n\t0x7067U, 0x7068U, 0x7069U, 0x706AU, 0x706BU, 0x706CU, 0x706DU, 0x706EU,\n\t0x706FU, 0x7070U, 0x7071U, 0x7072U, 0x7073U, 0x7074U, 0x7075U, 0x7076U,\n\t0x7077U, 0x7078U, 0x7079U, 0x707AU, 0x7030U, 0x7031U, 0x7032U, 0x7033U,\n\t0x7034U, 0x7035U, 0x7036U, 0x7037U, 0x7038U, 0x7039U, 0x702BU, 0x702FU,\n\t0x7141U, 0x7142U, 0x7143U, 0x7144U, 0x7145U, 0x7146U, 0x7147U, 0x7148U,\n\t0x7149U, 0x714AU, 0x714BU, 0x714CU, 0x714DU, 0x714EU, 0x714FU, 0x7150U,\n\t0x7151U, 0x7152U, 0x7153U, 0x7154U, 0x7155U, 0x7156U, 0x7157U, 0x7158U,\n\t0x7159U, 0x715AU, 0x7161U, 0x7162U, 0x7163U, 0x7164U, 0x7165U, 0x7166U,\n\t0x7167U, 0x7168U, 0x7169U, 0x716AU, 0x716BU, 0x716CU, 0x716DU, 0x716EU,\n\t0x716FU, 0x7170U, 0x7171U, 0x7172U, 0x7173U, 0x7174U, 0x7175U, 0x7176U,\n\t0x7177U, 0x7178U, 0x7179U, 0x717AU, 0x7130U, 0x7131U, 0x7132U, 0x7133U,\n\t0x7134U, 0x7135U, 0x7136U, 0x7137U, 0x7138U, 0x7139U, 0x712BU, 0x712FU,\n\t0x7241U, 0x7242U, 0x7243U, 0x7244U, 0x7245U, 0x7246U, 0x7247U, 0x7248U,\n\t0x7249U, 0x724AU, 0x724BU, 0x724CU, 0x724DU, 0x724EU, 0x724FU, 0x7250U,\n\t0x7251U, 0x7252U, 0x7253U, 0x7254U, 0x7255U, 0x7256U, 0x7257U, 0x7258U,\n\t0x7259U, 0x725AU, 0x7261U, 0x7262U, 0x7263U, 0x7264U, 0x7265U, 0x7266U,\n\t0x7267U, 0x7268U, 0x7269U, 0x726AU, 0x726BU, 0x726CU, 0x726DU, 0x726EU,\n\t0x726FU, 0x7270U, 0x7271U, 0x7272U, 0x7273U, 0x7274U, 0x7275U, 0x7276U,\n\t0x7277U, 0x7278U, 0x7279U, 0x727AU, 0x7230U, 0x7231U, 0x7232U, 0x7233U,\n\t0x7234U, 0x7235U, 0x7236U, 0x7237U, 0x7238U, 0x7239U, 0x722BU, 0x722FU,\n\t0x7341U, 0x7342U, 0x7343U, 0x7344U, 0x7345U, 0x7346U, 0x7347U, 0x7348U,\n\t0x7349U, 0x734AU, 0x734BU, 0x734CU, 0x734DU, 0x734EU, 0x734FU, 0x7350U,\n\t0x7351U, 0x7352U, 0x7353U, 0x7354U, 0x7355U, 0x7356U, 0x7357U, 0x7358U,\n\t0x7359U, 0x735AU, 0x7361U, 0x7362U, 0x7363U, 0x7364U, 0x7365U, 0x7366U,\n\t0x7367U, 0x7368U, 0x7369U, 0x736AU, 0x736BU, 0x736CU, 0x736DU, 0x736EU,\n\t0x736FU, 0x7370U, 0x7371U, 0x7372U, 0x7373U, 0x7374U, 0x7375U, 0x7376U,\n\t0x7377U, 0x7378U, 0x7379U, 0x737AU, 0x7330U, 0x7331U, 0x7332U, 0x7333U,\n\t0x7334U, 0x7335U, 0x7336U, 0x7337U, 0x7338U, 0x7339U, 0x732BU, 0x732FU,\n\t0x7441U, 0x7442U, 0x7443U, 0x7444U, 0x7445U, 0x7446U, 0x7447U, 0x7448U,\n\t0x7449U, 0x744AU, 0x744BU, 0x744CU, 0x744DU, 0x744EU, 0x744FU, 0x7450U,\n\t0x7451U, 0x7452U, 0x7453U, 0x7454U, 0x7455U, 0x7456U, 0x7457U, 0x7458U,\n\t0x7459U, 0x745AU, 0x7461U, 0x7462U, 0x7463U, 0x7464U, 0x7465U, 0x7466U,\n\t0x7467U, 0x7468U, 0x7469U, 0x746AU, 0x746BU, 0x746CU, 0x746DU, 0x746EU,\n\t0x746FU, 0x7470U, 0x7471U, 0x7472U, 0x7473U, 0x7474U, 0x7475U, 0x7476U,\n\t0x7477U, 0x7478U, 0x7479U, 0x747AU, 0x7430U, 0x7431U, 0x7432U, 0x7433U,\n\t0x7434U, 0x7435U, 0x7436U, 0x7437U, 0x7438U, 0x7439U, 0x742BU, 0x742FU,\n\t0x7541U, 0x7542U, 0x7543U, 0x7544U, 0x7545U, 0x7546U, 0x7547U, 0x7548U,\n\t0x7549U, 0x754AU, 0x754BU, 0x754CU, 0x754DU, 0x754EU, 0x754FU, 0x7550U,\n\t0x7551U, 0x7552U, 0x7553U, 0x7554U, 0x7555U, 0x7556U, 0x7557U, 0x7558U,\n\t0x7559U, 0x755AU, 0x7561U, 0x7562U, 0x7563U, 0x7564U, 0x7565U, 0x7566U,\n\t0x7567U, 0x7568U, 0x7569U, 0x756AU, 0x756BU, 0x756CU, 0x756DU, 0x756EU,\n\t0x756FU, 0x7570U, 0x7571U, 0x7572U, 0x7573U, 0x7574U, 0x7575U, 0x7576U,\n\t0x7577U, 0x7578U, 0x7579U, 0x757AU, 0x7530U, 0x7531U, 0x7532U, 0x7533U,\n\t0x7534U, 0x7535U, 0x7536U, 0x7537U, 0x7538U, 0x7539U, 0x752BU, 0x752FU,\n\t0x7641U, 0x7642U, 0x7643U, 0x7644U, 0x7645U, 0x7646U, 0x7647U, 0x7648U,\n\t0x7649U, 0x764AU, 0x764BU, 0x764CU, 0x764DU, 0x764EU, 0x764FU, 0x7650U,\n\t0x7651U, 0x7652U, 0x7653U, 0x7654U, 0x7655U, 0x7656U, 0x7657U, 0x7658U,\n\t0x7659U, 0x765AU, 0x7661U, 0x7662U, 0x7663U, 0x7664U, 0x7665U, 0x7666U,\n\t0x7667U, 0x7668U, 0x7669U, 0x766AU, 0x766BU, 0x766CU, 0x766DU, 0x766EU,\n\t0x766FU, 0x7670U, 0x7671U, 0x7672U, 0x7673U, 0x7674U, 0x7675U, 0x7676U,\n\t0x7677U, 0x7678U, 0x7679U, 0x767AU, 0x7630U, 0x7631U, 0x7632U, 0x7633U,\n\t0x7634U, 0x7635U, 0x7636U, 0x7637U, 0x7638U, 0x7639U, 0x762BU, 0x762FU,\n\t0x7741U, 0x7742U, 0x7743U, 0x7744U, 0x7745U, 0x7746U, 0x7747U, 0x7748U,\n\t0x7749U, 0x774AU, 0x774BU, 0x774CU, 0x774DU, 0x774EU, 0x774FU, 0x7750U,\n\t0x7751U, 0x7752U, 0x7753U, 0x7754U, 0x7755U, 0x7756U, 0x7757U, 0x7758U,\n\t0x7759U, 0x775AU, 0x7761U, 0x7762U, 0x7763U, 0x7764U, 0x7765U, 0x7766U,\n\t0x7767U, 0x7768U, 0x7769U, 0x776AU, 0x776BU, 0x776CU, 0x776DU, 0x776EU,\n\t0x776FU, 0x7770U, 0x7771U, 0x7772U, 0x7773U, 0x7774U, 0x7775U, 0x7776U,\n\t0x7777U, 0x7778U, 0x7779U, 0x777AU, 0x7730U, 0x7731U, 0x7732U, 0x7733U,\n\t0x7734U, 0x7735U, 0x7736U, 0x7737U, 0x7738U, 0x7739U, 0x772BU, 0x772FU,\n\t0x7841U, 0x7842U, 0x7843U, 0x7844U, 0x7845U, 0x7846U, 0x7847U, 0x7848U,\n\t0x7849U, 0x784AU, 0x784BU, 0x784CU, 0x784DU, 0x784EU, 0x784FU, 0x7850U,\n\t0x7851U, 0x7852U, 0x7853U, 0x7854U, 0x7855U, 0x7856U, 0x7857U, 0x7858U,\n\t0x7859U, 0x785AU, 0x7861U, 0x7862U, 0x7863U, 0x7864U, 0x7865U, 0x7866U,\n\t0x7867U, 0x7868U, 0x7869U, 0x786AU, 0x786BU, 0x786CU, 0x786DU, 0x786EU,\n\t0x786FU, 0x7870U, 0x7871U, 0x7872U, 0x7873U, 0x7874U, 0x7875U, 0x7876U,\n\t0x7877U, 0x7878U, 0x7879U, 0x787AU, 0x7830U, 0x7831U, 0x7832U, 0x7833U,\n\t0x7834U, 0x7835U, 0x7836U, 0x7837U, 0x7838U, 0x7839U, 0x782BU, 0x782FU,\n\t0x7941U, 0x7942U, 0x7943U, 0x7944U, 0x7945U, 0x7946U, 0x7947U, 0x7948U,\n\t0x7949U, 0x794AU, 0x794BU, 0x794CU, 0x794DU, 0x794EU, 0x794FU, 0x7950U,\n\t0x7951U, 0x7952U, 0x7953U, 0x7954U, 0x7955U, 0x7956U, 0x7957U, 0x7958U,\n\t0x7959U, 0x795AU, 0x7961U, 0x7962U, 0x7963U, 0x7964U, 0x7965U, 0x7966U,\n\t0x7967U, 0x7968U, 0x7969U, 0x796AU, 0x796BU, 0x796CU, 0x796DU, 0x796EU,\n\t0x796FU, 0x7970U, 0x7971U, 0x7972U, 0x7973U, 0x7974U, 0x7975U, 0x7976U,\n\t0x7977U, 0x7978U, 0x7979U, 0x797AU, 0x7930U, 0x7931U, 0x7932U, 0x7933U,\n\t0x7934U, 0x7935U, 0x7936U, 0x7937U, 0x7938U, 0x7939U, 0x792BU, 0x792FU,\n\t0x7A41U, 0x7A42U, 0x7A43U, 0x7A44U, 0x7A45U, 0x7A46U, 0x7A47U, 0x7A48U,\n\t0x7A49U, 0x7A4AU, 0x7A4BU, 0x7A4CU, 0x7A4DU, 0x7A4EU, 0x7A4FU, 0x7A50U,\n\t0x7A51U, 0x7A52U, 0x7A53U, 0x7A54U, 0x7A55U, 0x7A56U, 0x7A57U, 0x7A58U,\n\t0x7A59U, 0x7A5AU, 0x7A61U, 0x7A62U, 0x7A63U, 0x7A64U, 0x7A65U, 0x7A66U,\n\t0x7A67U, 0x7A68U, 0x7A69U, 0x7A6AU, 0x7A6BU, 0x7A6CU, 0x7A6DU, 0x7A6EU,\n\t0x7A6FU, 0x7A70U, 0x7A71U, 0x7A72U, 0x7A73U, 0x7A74U, 0x7A75U, 0x7A76U,\n\t0x7A77U, 0x7A78U, 0x7A79U, 0x7A7AU, 0x7A30U, 0x7A31U, 0x7A32U, 0x7A33U,\n\t0x7A34U, 0x7A35U, 0x7A36U, 0x7A37U, 0x7A38U, 0x7A39U, 0x7A2BU, 0x7A2FU,\n\t0x3041U, 0x3042U, 0x3043U, 0x3044U, 0x3045U, 0x3046U, 0x3047U, 0x3048U,\n\t0x3049U, 0x304AU, 0x304BU, 0x304CU, 0x304DU, 0x304EU, 0x304FU, 0x3050U,\n\t0x3051U, 0x3052U, 0x3053U, 0x3054U, 0x3055U, 0x3056U, 0x3057U, 0x3058U,\n\t0x3059U, 0x305AU, 0x3061U, 0x3062U, 0x3063U, 0x3064U, 0x3065U, 0x3066U,\n\t0x3067U, 0x3068U, 0x3069U, 0x306AU, 0x306BU, 0x306CU, 0x306DU, 0x306EU,\n\t0x306FU, 0x3070U, 0x3071U, 0x3072U, 0x3073U, 0x3074U, 0x3075U, 0x3076U,\n\t0x3077U, 0x3078U, 0x3079U, 0x307AU, 0x3030U, 0x3031U, 0x3032U, 0x3033U,\n\t0x3034U, 0x3035U, 0x3036U, 0x3037U, 0x3038U, 0x3039U, 0x302BU, 0x302FU,\n\t0x3141U, 0x3142U, 0x3143U, 0x3144U, 0x3145U, 0x3146U, 0x3147U, 0x3148U,\n\t0x3149U, 0x314AU, 0x314BU, 0x314CU, 0x314DU, 0x314EU, 0x314FU, 0x3150U,\n\t0x3151U, 0x3152U, 0x3153U, 0x3154U, 0x3155U, 0x3156U, 0x3157U, 0x3158U,\n\t0x3159U, 0x315AU, 0x3161U, 0x3162U, 0x3163U, 0x3164U, 0x3165U, 0x3166U,\n\t0x3167U, 0x3168U, 0x3169U, 0x316AU, 0x316BU, 0x316CU, 0x316DU, 0x316EU,\n\t0x316FU, 0x3170U, 0x3171U, 0x3172U, 0x3173U, 0x3174U, 0x3175U, 0x3176U,\n\t0x3177U, 0x3178U, 0x3179U, 0x317AU, 0x3130U, 0x3131U, 0x3132U, 0x3133U,\n\t0x3134U, 0x3135U, 0x3136U, 0x3137U, 0x3138U, 0x3139U, 0x312BU, 0x312FU,\n\t0x3241U, 0x3242U, 0x3243U, 0x3244U, 0x3245U, 0x3246U, 0x3247U, 0x3248U,\n\t0x3249U, 0x324AU, 0x324BU, 0x324CU, 0x324DU, 0x324EU, 0x324FU, 0x3250U,\n\t0x3251U, 0x3252U, 0x3253U, 0x3254U, 0x3255U, 0x3256U, 0x3257U, 0x3258U,\n\t0x3259U, 0x325AU, 0x3261U, 0x3262U, 0x3263U, 0x3264U, 0x3265U, 0x3266U,\n\t0x3267U, 0x3268U, 0x3269U, 0x326AU, 0x326BU, 0x326CU, 0x326DU, 0x326EU,\n\t0x326FU, 0x3270U, 0x3271U, 0x3272U, 0x3273U, 0x3274U, 0x3275U, 0x3276U,\n\t0x3277U, 0x3278U, 0x3279U, 0x327AU, 0x3230U, 0x3231U, 0x3232U, 0x3233U,\n\t0x3234U, 0x3235U, 0x3236U, 0x3237U, 0x3238U, 0x3239U, 0x322BU, 0x322FU,\n\t0x3341U, 0x3342U, 0x3343U, 0x3344U, 0x3345U, 0x3346U, 0x3347U, 0x3348U,\n\t0x3349U, 0x334AU, 0x334BU, 0x334CU, 0x334DU, 0x334EU, 0x334FU, 0x3350U,\n\t0x3351U, 0x3352U, 0x3353U, 0x3354U, 0x3355U, 0x3356U, 0x3357U, 0x3358U,\n\t0x3359U, 0x335AU, 0x3361U, 0x3362U, 0x3363U, 0x3364U, 0x3365U, 0x3366U,\n\t0x3367U, 0x3368U, 0x3369U, 0x336AU, 0x336BU, 0x336CU, 0x336DU, 0x336EU,\n\t0x336FU, 0x3370U, 0x3371U, 0x3372U, 0x3373U, 0x3374U, 0x3375U, 0x3376U,\n\t0x3377U, 0x3378U, 0x3379U, 0x337AU, 0x3330U, 0x3331U, 0x3332U, 0x3333U,\n\t0x3334U, 0x3335U, 0x3336U, 0x3337U, 0x3338U, 0x3339U, 0x332BU, 0x332FU,\n\t0x3441U, 0x3442U, 0x3443U, 0x3444U, 0x3445U, 0x3446U, 0x3447U, 0x3448U,\n\t0x3449U, 0x344AU, 0x344BU, 0x344CU, 0x344DU, 0x344EU, 0x344FU, 0x3450U,\n\t0x3451U, 0x3452U, 0x3453U, 0x3454U, 0x3455U, 0x3456U, 0x3457U, 0x3458U,\n\t0x3459U, 0x345AU, 0x3461U, 0x3462U, 0x3463U, 0x3464U, 0x3465U, 0x3466U,\n\t0x3467U, 0x3468U, 0x3469U, 0x346AU, 0x346BU, 0x346CU, 0x346DU, 0x346EU,\n\t0x346FU, 0x3470U, 0x3471U, 0x3472U, 0x3473U, 0x3474U, 0x3475U, 0x3476U,\n\t0x3477U, 0x3478U, 0x3479U, 0x347AU, 0x3430U, 0x3431U, 0x3432U, 0x3433U,\n\t0x3434U, 0x3435U, 0x3436U, 0x3437U, 0x3438U, 0x3439U, 0x342BU, 0x342FU,\n\t0x3541U, 0x3542U, 0x3543U, 0x3544U, 0x3545U, 0x3546U, 0x3547U, 0x3548U,\n\t0x3549U, 0x354AU, 0x354BU, 0x354CU, 0x354DU, 0x354EU, 0x354FU, 0x3550U,\n\t0x3551U, 0x3552U, 0x3553U, 0x3554U, 0x3555U, 0x3556U, 0x3557U, 0x3558U,\n\t0x3559U, 0x355AU, 0x3561U, 0x3562U, 0x3563U, 0x3564U, 0x3565U, 0x3566U,\n\t0x3567U, 0x3568U, 0x3569U, 0x356AU, 0x356BU, 0x356CU, 0x356DU, 0x356EU,\n\t0x356FU, 0x3570U, 0x3571U, 0x3572U, 0x3573U, 0x3574U, 0x3575U, 0x3576U,\n\t0x3577U, 0x3578U, 0x3579U, 0x357AU, 0x3530U, 0x3531U, 0x3532U, 0x3533U,\n\t0x3534U, 0x3535U, 0x3536U, 0x3537U, 0x3538U, 0x3539U, 0x352BU, 0x352FU,\n\t0x3641U, 0x3642U, 0x3643U, 0x3644U, 0x3645U, 0x3646U, 0x3647U, 0x3648U,\n\t0x3649U, 0x364AU, 0x364BU, 0x364CU, 0x364DU, 0x364EU, 0x364FU, 0x3650U,\n\t0x3651U, 0x3652U, 0x3653U, 0x3654U, 0x3655U, 0x3656U, 0x3657U, 0x3658U,\n\t0x3659U, 0x365AU, 0x3661U, 0x3662U, 0x3663U, 0x3664U, 0x3665U, 0x3666U,\n\t0x3667U, 0x3668U, 0x3669U, 0x366AU, 0x366BU, 0x366CU, 0x366DU, 0x366EU,\n\t0x366FU, 0x3670U, 0x3671U, 0x3672U, 0x3673U, 0x3674U, 0x3675U, 0x3676U,\n\t0x3677U, 0x3678U, 0x3679U, 0x367AU, 0x3630U, 0x3631U, 0x3632U, 0x3633U,\n\t0x3634U, 0x3635U, 0x3636U, 0x3637U, 0x3638U, 0x3639U, 0x362BU, 0x362FU,\n\t0x3741U, 0x3742U, 0x3743U, 0x3744U, 0x3745U, 0x3746U, 0x3747U, 0x3748U,\n\t0x3749U, 0x374AU, 0x374BU, 0x374CU, 0x374DU, 0x374EU, 0x374FU, 0x3750U,\n\t0x3751U, 0x3752U, 0x3753U, 0x3754U, 0x3755U, 0x3756U, 0x3757U, 0x3758U,\n\t0x3759U, 0x375AU, 0x3761U, 0x3762U, 0x3763U, 0x3764U, 0x3765U, 0x3766U,\n\t0x3767U, 0x3768U, 0x3769U, 0x376AU, 0x376BU, 0x376CU, 0x376DU, 0x376EU,\n\t0x376FU, 0x3770U, 0x3771U, 0x3772U, 0x3773U, 0x3774U, 0x3775U, 0x3776U,\n\t0x3777U, 0x3778U, 0x3779U, 0x377AU, 0x3730U, 0x3731U, 0x3732U, 0x3733U,\n\t0x3734U, 0x3735U, 0x3736U, 0x3737U, 0x3738U, 0x3739U, 0x372BU, 0x372FU,\n\t0x3841U, 0x3842U, 0x3843U, 0x3844U, 0x3845U, 0x3846U, 0x3847U, 0x3848U,\n\t0x3849U, 0x384AU, 0x384BU, 0x384CU, 0x384DU, 0x384EU, 0x384FU, 0x3850U,\n\t0x3851U, 0x3852U, 0x3853U, 0x3854U, 0x3855U, 0x3856U, 0x3857U, 0x3858U,\n\t0x3859U, 0x385AU, 0x3861U, 0x3862U, 0x3863U, 0x3864U, 0x3865U, 0x3866U,\n\t0x3867U, 0x3868U, 0x3869U, 0x386AU, 0x386BU, 0x386CU, 0x386DU, 0x386EU,\n\t0x386FU, 0x3870U, 0x3871U, 0x3872U, 0x3873U, 0x3874U, 0x3875U, 0x3876U,\n\t0x3877U, 0x3878U, 0x3879U, 0x387AU, 0x3830U, 0x3831U, 0x3832U, 0x3833U,\n\t0x3834U, 0x3835U, 0x3836U, 0x3837U, 0x3838U, 0x3839U, 0x382BU, 0x382FU,\n\t0x3941U, 0x3942U, 0x3943U, 0x3944U, 0x3945U, 0x3946U, 0x3947U, 0x3948U,\n\t0x3949U, 0x394AU, 0x394BU, 0x394CU, 0x394DU, 0x394EU, 0x394FU, 0x3950U,\n\t0x3951U, 0x3952U, 0x3953U, 0x3954U, 0x3955U, 0x3956U, 0x3957U, 0x3958U,\n\t0x3959U, 0x395AU, 0x3961U, 0x3962U, 0x3963U, 0x3964U, 0x3965U, 0x3966U,\n\t0x3967U, 0x3968U, 0x3969U, 0x396AU, 0x396BU, 0x396CU, 0x396DU, 0x396EU,\n\t0x396FU, 0x3970U, 0x3971U, 0x3972U, 0x3973U, 0x3974U, 0x3975U, 0x3976U,\n\t0x3977U, 0x3978U, 0x3979U, 0x397AU, 0x3930U, 0x3931U, 0x3932U, 0x3933U,\n\t0x3934U, 0x3935U, 0x3936U, 0x3937U, 0x3938U, 0x3939U, 0x392BU, 0x392FU,\n\t0x2B41U, 0x2B42U, 0x2B43U, 0x2B44U, 0x2B45U, 0x2B46U, 0x2B47U, 0x2B48U,\n\t0x2B49U, 0x2B4AU, 0x2B4BU, 0x2B4CU, 0x2B4DU, 0x2B4EU, 0x2B4FU, 0x2B50U,\n\t0x2B51U, 0x2B52U, 0x2B53U, 0x2B54U, 0x2B55U, 0x2B56U, 0x2B57U, 0x2B58U,\n\t0x2B59U, 0x2B5AU, 0x2B61U, 0x2B62U, 0x2B63U, 0x2B64U, 0x2B65U, 0x2B66U,\n\t0x2B67U, 0x2B68U, 0x2B69U, 0x2B6AU, 0x2B6BU, 0x2B6CU, 0x2B6DU, 0x2B6EU,\n\t0x2B6FU, 0x2B70U, 0x2B71U, 0x2B72U, 0x2B73U, 0x2B74U, 0x2B75U, 0x2B76U,\n\t0x2B77U, 0x2B78U, 0x2B79U, 0x2B7AU, 0x2B30U, 0x2B31U, 0x2B32U, 0x2B33U,\n\t0x2B34U, 0x2B35U, 0x2B36U, 0x2B37U, 0x2B38U, 0x2B39U, 0x2B2BU, 0x2B2FU,\n\t0x2F41U, 0x2F42U, 0x2F43U, 0x2F44U, 0x2F45U, 0x2F46U, 0x2F47U, 0x2F48U,\n\t0x2F49U, 0x2F4AU, 0x2F4BU, 0x2F4CU, 0x2F4DU, 0x2F4EU, 0x2F4FU, 0x2F50U,\n\t0x2F51U, 0x2F52U, 0x2F53U, 0x2F54U, 0x2F55U, 0x2F56U, 0x2F57U, 0x2F58U,\n\t0x2F59U, 0x2F5AU, 0x2F61U, 0x2F62U, 0x2F63U, 0x2F64U, 0x2F65U, 0x2F66U,\n\t0x2F67U, 0x2F68U, 0x2F69U, 0x2F6AU, 0x2F6BU, 0x2F6CU, 0x2F6DU, 0x2F6EU,\n\t0x2F6FU, 0x2F70U, 0x2F71U, 0x2F72U, 0x2F73U, 0x2F74U, 0x2F75U, 0x2F76U,\n\t0x2F77U, 0x2F78U, 0x2F79U, 0x2F7AU, 0x2F30U, 0x2F31U, 0x2F32U, 0x2F33U,\n\t0x2F34U, 0x2F35U, 0x2F36U, 0x2F37U, 0x2F38U, 0x2F39U, 0x2F2BU, 0x2F2FU,\n#endif\n};\n"
  },
  {
    "path": "mypyc/lib-rt/base64/tables/tables.c",
    "content": "#include \"tables.h\"\n\nconst uint8_t\nbase64_table_enc_6bit[] =\n\t\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\t\"abcdefghijklmnopqrstuvwxyz\"\n\t\"0123456789\"\n\t\"+/\";\n\n// In the lookup table below, note that the value for '=' (character 61) is\n// 254, not 255. This character is used for in-band signaling of the end of\n// the datastream, and we will use that later. The characters A-Z, a-z, 0-9\n// and + / are mapped to their \"decoded\" values. The other bytes all map to\n// the value 255, which flags them as \"invalid input\".\n\nconst uint8_t\nbase64_table_dec_8bit[] =\n{\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\t\t//   0..15\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\t\t//  16..31\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,  62, 255, 255, 255,  63,\t\t//  32..47\n\t 52,  53,  54,  55,  56,  57,  58,  59,  60,  61, 255, 255, 255, 254, 255, 255,\t\t//  48..63\n\t255,   0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  10,  11,  12,  13,  14,\t\t//  64..79\n\t 15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25, 255, 255, 255, 255, 255,\t\t//  80..95\n\t255,  26,  27,  28,  29,  30,  31,  32,  33,  34,  35,  36,  37,  38,  39,  40,\t\t//  96..111\n\t 41,  42,  43,  44,  45,  46,  47,  48,  49,  50,  51, 255, 255, 255, 255, 255,\t\t// 112..127\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\t\t// 128..143\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n\t255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,\n};\n\n#if BASE64_WORDSIZE >= 32\n#  include \"table_dec_32bit.h\"\n#  include \"table_enc_12bit.h\"\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/base64/tables/tables.h",
    "content": "#ifndef BASE64_TABLES_H\n#define BASE64_TABLES_H\n\n#include <stdint.h>\n\n#include \"../env.h\"\n\n// These tables are used by all codecs for fallback plain encoding/decoding:\nextern const uint8_t base64_table_enc_6bit[];\nextern const uint8_t base64_table_dec_8bit[];\n\n// These tables are used for the 32-bit and 64-bit generic decoders:\n#if BASE64_WORDSIZE >= 32\nextern const uint32_t base64_table_dec_32bit_d0[];\nextern const uint32_t base64_table_dec_32bit_d1[];\nextern const uint32_t base64_table_dec_32bit_d2[];\nextern const uint32_t base64_table_dec_32bit_d3[];\n\n// This table is used by the 32 and 64-bit generic encoders:\nextern const uint16_t base64_table_enc_12bit[];\n#endif\n\n#endif\t// BASE64_TABLES_H\n"
  },
  {
    "path": "mypyc/lib-rt/build_setup.py",
    "content": "# This file must have the same content for mypyc/build_setup.py and lib-rt/build_setup.py,\n# it exists to work around absence of support for per-file compile flags in setuptools.\n# The version in mypyc/ is the source of truth, and should be copied to lib-rt if modified.\n\nimport os\nimport platform\nimport sys\n\ntry:\n    # Import setuptools so that it monkey-patch overrides distutils\n    import setuptools  # noqa: F401\nexcept ImportError:\n    pass\n\nif sys.version_info >= (3, 12):\n    # From setuptools' monkeypatch\n    from distutils import ccompiler  # type: ignore[import-not-found]\nelse:\n    from distutils import ccompiler\n\nEXTRA_FLAGS_PER_COMPILER_TYPE_PER_PATH_COMPONENT = {\n    \"msvc\": {\n        \"base64/arch/sse42\": [\"/arch:SSE4.2\"],\n        \"base64/arch/avx2\": [\"/arch:AVX2\"],\n        \"base64/arch/avx\": [\"/arch:AVX\"],\n    }\n}\n\nccompiler.CCompiler.__spawn = ccompiler.CCompiler.spawn  # type: ignore[attr-defined]\nX86_64 = platform.machine() in (\"x86_64\", \"AMD64\", \"amd64\")\nPYODIDE = \"PYODIDE\" in os.environ\nNO_EXTRA_FLAGS = \"MYPYC_NO_EXTRA_FLAGS\" in os.environ\n\n\ndef spawn(self, cmd, **kwargs) -> None:  # type: ignore[no-untyped-def]\n    new_cmd = list(cmd)\n    if PYODIDE:\n        for argument in reversed(new_cmd):\n            if not str(argument).endswith(\".c\"):\n                continue\n            if \"base64/arch/\" in str(argument):\n                new_cmd.extend([\"-msimd128\"])\n    elif not NO_EXTRA_FLAGS:\n        compiler_type: str = self.compiler_type\n        extra_options = EXTRA_FLAGS_PER_COMPILER_TYPE_PER_PATH_COMPONENT.get(compiler_type, None)\n        if X86_64 and extra_options is not None:\n            # filenames are closer to the end of command line\n            for argument in reversed(new_cmd):\n                # Check if the matching argument contains a source filename.\n                if not str(argument).endswith(\".c\"):\n                    continue\n\n                for path in extra_options.keys():\n                    if path in str(argument):\n                        if compiler_type == \"bcpp\":\n                            compiler = new_cmd.pop()\n                            # Borland accepts a source file name at the end,\n                            # insert the options before it\n                            new_cmd.extend(extra_options[path])\n                            new_cmd.append(compiler)\n                        else:\n                            new_cmd.extend(extra_options[path])\n\n                        # path component is found, no need to search any further\n                        break\n    self.__spawn(new_cmd, **kwargs)\n\n\nccompiler.CCompiler.spawn = spawn  # type: ignore[method-assign]\n"
  },
  {
    "path": "mypyc/lib-rt/bytearray_extra_ops.c",
    "content": "#include \"bytearray_extra_ops.h\"\n\nPyObject *CPyByteArray_New(void) {\n    return PyByteArray_FromStringAndSize(NULL, 0);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/bytearray_extra_ops.h",
    "content": "#ifndef MYPYC_BYTEARRAY_EXTRA_OPS_H\n#define MYPYC_BYTEARRAY_EXTRA_OPS_H\n\n#include <Python.h>\n#include \"CPy.h\"\n\n// Construct empty bytearray\nPyObject *CPyByteArray_New(void);\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/bytes_extra_ops.c",
    "content": "#include \"bytes_extra_ops.h\"\n\nPyObject *CPyBytes_Translate(PyObject *bytes, PyObject *table) {\n    // Fast path: exact bytes object with exact bytes table\n    if (PyBytes_CheckExact(bytes) && PyBytes_CheckExact(table)) {\n        Py_ssize_t table_len = PyBytes_GET_SIZE(table);\n        if (table_len != 256) {\n            PyErr_SetString(PyExc_ValueError,\n                           \"translation table must be 256 characters long\");\n            return NULL;\n        }\n\n        Py_ssize_t len = PyBytes_GET_SIZE(bytes);\n        const char *input = PyBytes_AS_STRING(bytes);\n        const char *trans_table = PyBytes_AS_STRING(table);\n\n        PyObject *result = PyBytes_FromStringAndSize(NULL, len);\n        if (result == NULL) {\n            return NULL;\n        }\n\n        char *output = PyBytes_AS_STRING(result);\n        bool changed = false;\n\n        // Without a loop unrolling hint performance can be worse than CPython\n        CPY_UNROLL_LOOP(4)\n        for (Py_ssize_t i = len; --i >= 0;) {\n            char c = *input++;\n            if ((*output++ = trans_table[(unsigned char)c]) != c)\n                changed = true;\n        }\n\n        // If nothing changed, discard result and return the original object\n        if (!changed) {\n            Py_DECREF(result);\n            Py_INCREF(bytes);\n            return bytes;\n        }\n\n        return result;\n    }\n\n    // Fallback to Python method call for non-exact types or non-standard tables\n    return PyObject_CallMethodOneArg(bytes, mypyc_interned_str.translate, table);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/bytes_extra_ops.h",
    "content": "#ifndef MYPYC_BYTES_EXTRA_OPS_H\n#define MYPYC_BYTES_EXTRA_OPS_H\n\n#include <Python.h>\n#include <stdint.h>\n#include \"CPy.h\"\n\n// Optimized bytes translate operation\nPyObject *CPyBytes_Translate(PyObject *bytes, PyObject *table);\n\n// Optimized bytes.__getitem__ operations\n\n// If index is negative, convert to non-negative index (no range checking)\nstatic inline int64_t CPyBytes_AdjustIndex(PyObject *obj, int64_t index) {\n    if (index < 0) {\n        return index + Py_SIZE(obj);\n    }\n    return index;\n}\n\n// Check if index is in valid range [0, len)\nstatic inline bool CPyBytes_RangeCheck(PyObject *obj, int64_t index) {\n    return index >= 0 && index < Py_SIZE(obj);\n}\n\n// Get byte at index (no bounds checking) - returns as CPyTagged\nstatic inline CPyTagged CPyBytes_GetItemUnsafe(PyObject *obj, int64_t index) {\n    return ((CPyTagged)(uint8_t)(PyBytes_AS_STRING(obj))[index]) << 1;\n}\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/bytes_ops.c",
    "content": "// Bytes primitive operations\n//\n// These are registered in mypyc.primitives.bytes_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\n\n// Returns -1 on error, 0 on inequality, 1 on equality.\n//\n// Falls back to PyObject_RichCompareBool.\nint CPyBytes_Compare(PyObject *left, PyObject *right) {\n    if (PyBytes_CheckExact(left) && PyBytes_CheckExact(right)) {\n        if (left == right) {\n            return 1;\n        }\n\n        // Adapted from cpython internal implementation of bytes_compare.\n        Py_ssize_t len = Py_SIZE(left);\n        if (Py_SIZE(right) != len) {\n            return 0;\n        }\n        PyBytesObject *left_b = (PyBytesObject *)left;\n        PyBytesObject *right_b = (PyBytesObject *)right;\n        if (left_b->ob_sval[0] != right_b->ob_sval[0]) {\n            return 0;\n        }\n\n        return memcmp(left_b->ob_sval, right_b->ob_sval, len) == 0;\n    }\n    return PyObject_RichCompareBool(left, right, Py_EQ);\n}\n\nCPyTagged CPyBytes_GetItem(PyObject *o, CPyTagged index) {\n    if (CPyTagged_CheckShort(index)) {\n        Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n        Py_ssize_t size = ((PyVarObject *)o)->ob_size;\n        if (n < 0)\n            n += size;\n        if (n < 0 || n >= size) {\n            PyErr_SetString(PyExc_IndexError, \"index out of range\");\n            return CPY_INT_TAG;\n        }\n        unsigned char num = PyBytes_Check(o) ? ((PyBytesObject *)o)->ob_sval[n]\n                                             : ((PyByteArrayObject *)o)->ob_bytes[n];\n        return num << 1;\n    } else {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return CPY_INT_TAG;\n    }\n}\n\nPyObject *CPyBytes_Concat(PyObject *a, PyObject *b) {\n    Py_ssize_t a_len = ((PyVarObject *)a)->ob_size;\n    Py_ssize_t b_len = ((PyVarObject *)b)->ob_size;\n    PyBytesObject *ret = (PyBytesObject *)PyBytes_FromStringAndSize(NULL, a_len + b_len);\n    if (ret != NULL) {\n        memcpy(ret->ob_sval, ((PyBytesObject *)a)->ob_sval, a_len);\n        memcpy(ret->ob_sval + a_len, ((PyBytesObject *)b)->ob_sval, b_len);\n    }\n    return (PyObject *)ret;\n}\n\nstatic inline Py_ssize_t Clamp(Py_ssize_t a, Py_ssize_t b, Py_ssize_t c) {\n    return a < b ? b : (a >= c ? c : a);\n}\n\nPyObject *CPyBytes_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) {\n    if (CPyTagged_CheckShort(start) && CPyTagged_CheckShort(end)) {\n        Py_ssize_t startn = CPyTagged_ShortAsSsize_t(start);\n        Py_ssize_t endn = CPyTagged_ShortAsSsize_t(end);\n        Py_ssize_t len = ((PyVarObject *)obj)->ob_size;\n        if (startn < 0) {\n            startn += len;\n        }\n        if (endn < 0) {\n            endn += len;\n        }\n        startn = Clamp(startn, 0, len);\n        endn = Clamp(endn, 0, len);\n        Py_ssize_t slice_len = endn - startn;\n        if (PyBytes_Check(obj)) {\n            return PyBytes_FromStringAndSize(PyBytes_AS_STRING(obj) + startn, slice_len);\n        } else {\n            return PyByteArray_FromStringAndSize(PyByteArray_AS_STRING(obj) + startn, slice_len);\n        }\n    }\n    return CPyObject_GetSlice(obj, start, end);\n}\n\n// Like _PyBytes_Join but fallback to dynamic call if 'sep' is not bytes\n// (mostly commonly, for bytearrays)\nPyObject *CPyBytes_Join(PyObject *sep, PyObject *iter) {\n    if (PyBytes_CheckExact(sep)) {\n        return PyBytes_Join(sep, iter);\n    } else {\n        return PyObject_CallMethodOneArg(sep, mypyc_interned_str.join, iter);\n    }\n}\n\nPyObject *CPyBytes_Build(Py_ssize_t len, ...) {\n    Py_ssize_t i;\n    Py_ssize_t sz = 0;\n\n    va_list args;\n    va_start(args, len);\n    for (i = 0; i < len; i++) {\n        PyObject *item = va_arg(args, PyObject *);\n        size_t add_sz = ((PyVarObject *)item)->ob_size;\n        // Using size_t to avoid overflow during arithmetic calculation\n        if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {\n            PyErr_SetString(PyExc_OverflowError,\n                            \"join() result is too long for a Python bytes\");\n            return NULL;\n        }\n        sz += add_sz;\n    }\n    va_end(args);\n\n    PyBytesObject *ret = (PyBytesObject *)PyBytes_FromStringAndSize(NULL, sz);\n    if (ret != NULL) {\n        char *res_data = ret->ob_sval;\n        va_start(args, len);\n        for (i = 0; i < len; i++) {\n            PyObject *item = va_arg(args, PyObject *);\n            Py_ssize_t item_sz = ((PyVarObject *)item)->ob_size;\n            memcpy(res_data, ((PyBytesObject *)item)->ob_sval, item_sz);\n            res_data += item_sz;\n        }\n        va_end(args);\n        assert(res_data == ret->ob_sval + ((PyVarObject *)ret)->ob_size);\n    }\n\n    return (PyObject *)ret;\n}\n\nCPyTagged CPyBytes_Ord(PyObject *obj) {\n    Py_ssize_t s = PyBytes_GET_SIZE(obj);\n    if (s == 1) {\n        return (unsigned char)(PyBytes_AS_STRING(obj)[0]) << 1;\n    }\n    PyErr_SetString(PyExc_TypeError, \"ord() expects a character\");\n    return CPY_INT_TAG;\n}\n\nPyObject *CPyBytes_Multiply(PyObject *bytes, CPyTagged count) {\n    Py_ssize_t temp_count = CPyTagged_AsSsize_t(count);\n    if (temp_count == -1 && PyErr_Occurred()) {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return NULL;\n    }\n    return PySequence_Repeat(bytes, temp_count);\n}\n\nint CPyBytes_Startswith(PyObject *self, PyObject *subobj) {\n    if (PyBytes_CheckExact(self) && PyBytes_CheckExact(subobj)) {\n        if (self == subobj) {\n            return 1;\n        }\n\n        Py_ssize_t subobj_len = PyBytes_GET_SIZE(subobj);\n        if (subobj_len == 0) {\n            return 1;\n        }\n\n        Py_ssize_t self_len = PyBytes_GET_SIZE(self);\n        if (subobj_len > self_len) {\n            return 0;\n        }\n\n        const char *self_buf = PyBytes_AS_STRING(self);\n        const char *subobj_buf = PyBytes_AS_STRING(subobj);\n\n        return memcmp(self_buf, subobj_buf, (size_t)subobj_len) == 0 ? 1 : 0;\n    }\n    PyObject *result = PyObject_CallMethodOneArg(self, mypyc_interned_str.startswith, subobj);\n    if (result == NULL) {\n        return 2;\n    }\n    int ret = PyObject_IsTrue(result);\n    Py_DECREF(result);\n    if (ret < 0) {\n        return 2;\n    }\n    return ret;\n}\n\nint CPyBytes_Endswith(PyObject *self, PyObject *subobj) {\n    if (PyBytes_CheckExact(self) && PyBytes_CheckExact(subobj)) {\n        if (self == subobj) {\n            return 1;\n        }\n\n        Py_ssize_t subobj_len = PyBytes_GET_SIZE(subobj);\n        if (subobj_len == 0) {\n            return 1;\n        }\n\n        Py_ssize_t self_len = PyBytes_GET_SIZE(self);\n        if (subobj_len > self_len) {\n            return 0;\n        }\n\n        const char *self_buf = PyBytes_AS_STRING(self);\n        const char *subobj_buf = PyBytes_AS_STRING(subobj);\n\n        return memcmp(self_buf + (self_len - subobj_len), subobj_buf, (size_t)subobj_len) == 0 ? 1 : 0;\n    }\n    PyObject *result = PyObject_CallMethodOneArg(self, mypyc_interned_str.endswith, subobj);\n    if (result == NULL) {\n        return 2;\n    }\n    int ret = PyObject_IsTrue(result);\n    Py_DECREF(result);\n    if (ret < 0) {\n        return 2;\n    }\n    return ret;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/byteswriter_extra_ops.c",
    "content": "// Primitives related to librt.strings.BytesWriter that get linked statically\n// with compiled modules, instead of being called via a capsule.\n\n#include \"byteswriter_extra_ops.h\"\n\n#ifdef MYPYC_EXPERIMENTAL\n\nchar CPyBytesWriter_Write(PyObject *obj, PyObject *value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    const char *data;\n    Py_ssize_t size;\n    if (likely(PyBytes_Check(value))) {\n        data = PyBytes_AS_STRING(value);\n        size = PyBytes_GET_SIZE(value);\n    } else {\n        data = PyByteArray_AS_STRING(value);\n        size = PyByteArray_GET_SIZE(value);\n    }\n    // Write bytes content.\n    if (!CPyBytesWriter_EnsureSize(self, size))\n        return CPY_NONE_ERROR;\n    if (size < 8) {\n        // Loop tends to be faster for small sizes\n        char *p = self->buf + self->len;\n        for (Py_ssize_t i = 0; i < size; i++) {\n            p[i] = data[i];\n        }\n    } else {\n        memcpy(self->buf + self->len, data, size);\n    }\n    self->len += size;\n    return CPY_NONE;\n}\n\nvoid CPyBytes_ReadError(int64_t index, Py_ssize_t size) {\n    if (index < 0) {\n        PyErr_SetString(PyExc_ValueError, \"index must be non-negative\");\n    } else {\n        PyErr_Format(PyExc_IndexError,\n                     \"index %lld out of range for bytes of length %zd\",\n                     (long long)index, size);\n    }\n}\n\n#endif // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/byteswriter_extra_ops.h",
    "content": "#ifndef BYTESWRITER_EXTRA_OPS_H\n#define BYTESWRITER_EXTRA_OPS_H\n\n#ifdef MYPYC_EXPERIMENTAL\n\n#include <stdbool.h>\n#include <stdint.h>\n#include <Python.h>\n\n#include \"mypyc_util.h\"\n#include \"strings/librt_strings.h\"\n#include \"strings/librt_strings_common.h\"\n\n// BytesWriter: Length and capacity\n\nstatic inline CPyTagged\nCPyBytesWriter_Len(PyObject *obj) {\n    return (CPyTagged)((BytesWriterObject *)obj)->len << 1;\n}\n\nstatic inline bool\nCPyBytesWriter_EnsureSize(BytesWriterObject *data, Py_ssize_t n) {\n    if (likely(data->capacity - data->len >= n)) {\n        return true;\n    } else {\n        return LibRTStrings_ByteWriter_grow_buffer_internal(data, n);\n    }\n}\n\n// BytesWriter: Basic write operations\n\nstatic inline char\nCPyBytesWriter_Append(PyObject *obj, uint8_t value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    // Store length in a local variable to enable additional optimizations\n    Py_ssize_t len = self->len;\n    if (!CPyBytesWriter_EnsureSize(self, 1))\n        return CPY_NONE_ERROR;\n    self->buf[len] = value;\n    self->len = len + 1;\n    return CPY_NONE;\n}\n\nchar CPyBytesWriter_Write(PyObject *obj, PyObject *value);\n\n// BytesWriter: Indexing operations\n\n// If index is negative, convert to non-negative index (no range checking)\nstatic inline int64_t CPyBytesWriter_AdjustIndex(PyObject *obj, int64_t index) {\n    if (index < 0) {\n        return index + ((BytesWriterObject *)obj)->len;\n    }\n    return index;\n}\n\nstatic inline bool CPyBytesWriter_RangeCheck(PyObject *obj, int64_t index) {\n    return index >= 0 && index < ((BytesWriterObject *)obj)->len;\n}\n\nstatic inline uint8_t CPyBytesWriter_GetItem(PyObject *obj, int64_t index) {\n    return (((BytesWriterObject *)obj)->buf)[index];\n}\n\nstatic inline void CPyBytesWriter_SetItem(PyObject *obj, int64_t index, uint8_t x) {\n    (((BytesWriterObject *)obj)->buf)[index] = x;\n}\n\n// BytesWriter: Write integer operations (little-endian)\n\nstatic inline char\nCPyBytesWriter_WriteI16LE(PyObject *obj, int16_t value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    if (!CPyBytesWriter_EnsureSize(self, 2))\n        return CPY_NONE_ERROR;\n    BytesWriter_WriteI16LEUnsafe(self, value);\n    return CPY_NONE;\n}\n\nstatic inline char\nCPyBytesWriter_WriteI16BE(PyObject *obj, int16_t value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    if (!CPyBytesWriter_EnsureSize(self, 2))\n        return CPY_NONE_ERROR;\n    BytesWriter_WriteI16BEUnsafe(self, value);\n    return CPY_NONE;\n}\n\nstatic inline char\nCPyBytesWriter_WriteI32LE(PyObject *obj, int32_t value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    if (!CPyBytesWriter_EnsureSize(self, 4))\n        return CPY_NONE_ERROR;\n    BytesWriter_WriteI32LEUnsafe(self, value);\n    return CPY_NONE;\n}\n\nstatic inline char\nCPyBytesWriter_WriteI32BE(PyObject *obj, int32_t value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    if (!CPyBytesWriter_EnsureSize(self, 4))\n        return CPY_NONE_ERROR;\n    BytesWriter_WriteI32BEUnsafe(self, value);\n    return CPY_NONE;\n}\n\nstatic inline char\nCPyBytesWriter_WriteI64LE(PyObject *obj, int64_t value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    if (!CPyBytesWriter_EnsureSize(self, 8))\n        return CPY_NONE_ERROR;\n    BytesWriter_WriteI64LEUnsafe(self, value);\n    return CPY_NONE;\n}\n\nstatic inline char\nCPyBytesWriter_WriteI64BE(PyObject *obj, int64_t value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    if (!CPyBytesWriter_EnsureSize(self, 8))\n        return CPY_NONE_ERROR;\n    BytesWriter_WriteI64BEUnsafe(self, value);\n    return CPY_NONE;\n}\n\n// BytesWriter: Write float operations\n\nstatic inline char\nCPyBytesWriter_WriteF32LE(PyObject *obj, double value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    if (!CPyBytesWriter_EnsureSize(self, 4))\n        return CPY_NONE_ERROR;\n    BytesWriter_WriteF32LEUnsafe(self, (float)value);\n    return CPY_NONE;\n}\n\nstatic inline char\nCPyBytesWriter_WriteF32BE(PyObject *obj, double value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    if (!CPyBytesWriter_EnsureSize(self, 4))\n        return CPY_NONE_ERROR;\n    BytesWriter_WriteF32BEUnsafe(self, (float)value);\n    return CPY_NONE;\n}\n\nstatic inline char\nCPyBytesWriter_WriteF64LE(PyObject *obj, double value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    if (!CPyBytesWriter_EnsureSize(self, 8))\n        return CPY_NONE_ERROR;\n    BytesWriter_WriteF64LEUnsafe(self, value);\n    return CPY_NONE;\n}\n\nstatic inline char\nCPyBytesWriter_WriteF64BE(PyObject *obj, double value) {\n    BytesWriterObject *self = (BytesWriterObject *)obj;\n    if (!CPyBytesWriter_EnsureSize(self, 8))\n        return CPY_NONE_ERROR;\n    BytesWriter_WriteF64BEUnsafe(self, value);\n    return CPY_NONE;\n}\n\n// Bytes: Read integer operations\n\n// Helper function for bytes read error handling (negative index or out of range)\nvoid CPyBytes_ReadError(int64_t index, Py_ssize_t size);\n\nstatic inline int16_t\nCPyBytes_ReadI16LE(PyObject *bytes_obj, int64_t index) {\n    // bytes_obj type is enforced by mypyc\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index < 0 || index > size - 2)) {\n        CPyBytes_ReadError(index, size);\n        return CPY_LL_INT_ERROR;\n    }\n    const unsigned char *data = (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n    return CPyBytes_ReadI16LEUnsafe(data + index);\n}\n\nstatic inline int16_t\nCPyBytes_ReadI16BE(PyObject *bytes_obj, int64_t index) {\n    // bytes_obj type is enforced by mypyc\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index < 0 || index > size - 2)) {\n        CPyBytes_ReadError(index, size);\n        return CPY_LL_INT_ERROR;\n    }\n    const unsigned char *data = (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n    return CPyBytes_ReadI16BEUnsafe(data + index);\n}\n\nstatic inline int32_t\nCPyBytes_ReadI32BE(PyObject *bytes_obj, int64_t index) {\n    // bytes_obj type is enforced by mypyc\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index < 0 || index > size - 4)) {\n        CPyBytes_ReadError(index, size);\n        return CPY_LL_INT_ERROR;\n    }\n    const unsigned char *data = (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n    return CPyBytes_ReadI32BEUnsafe(data + index);\n}\n\nstatic inline int32_t\nCPyBytes_ReadI32LE(PyObject *bytes_obj, int64_t index) {\n    // bytes_obj type is enforced by mypyc\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index < 0 || index > size - 4)) {\n        CPyBytes_ReadError(index, size);\n        return CPY_LL_INT_ERROR;\n    }\n    const unsigned char *data = (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n    return CPyBytes_ReadI32LEUnsafe(data + index);\n}\n\nstatic inline int64_t\nCPyBytes_ReadI64LE(PyObject *bytes_obj, int64_t index) {\n    // bytes_obj type is enforced by mypyc\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index < 0 || index > size - 8)) {\n        CPyBytes_ReadError(index, size);\n        return CPY_LL_INT_ERROR;\n    }\n    const unsigned char *data = (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n    return CPyBytes_ReadI64LEUnsafe(data + index);\n}\n\nstatic inline int64_t\nCPyBytes_ReadI64BE(PyObject *bytes_obj, int64_t index) {\n    // bytes_obj type is enforced by mypyc\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index < 0 || index > size - 8)) {\n        CPyBytes_ReadError(index, size);\n        return CPY_LL_INT_ERROR;\n    }\n    const unsigned char *data = (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n    return CPyBytes_ReadI64BEUnsafe(data + index);\n}\n\n// Bytes: Read float operations\n\nstatic inline double\nCPyBytes_ReadF32LE(PyObject *bytes_obj, int64_t index) {\n    // bytes_obj type is enforced by mypyc\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index < 0 || index > size - 4)) {\n        CPyBytes_ReadError(index, size);\n        return CPY_FLOAT_ERROR;\n    }\n    const unsigned char *data = (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n    return (double)CPyBytes_ReadF32LEUnsafe(data + index);\n}\n\nstatic inline double\nCPyBytes_ReadF32BE(PyObject *bytes_obj, int64_t index) {\n    // bytes_obj type is enforced by mypyc\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index < 0 || index > size - 4)) {\n        CPyBytes_ReadError(index, size);\n        return CPY_FLOAT_ERROR;\n    }\n    const unsigned char *data = (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n    return (double)CPyBytes_ReadF32BEUnsafe(data + index);\n}\n\nstatic inline double\nCPyBytes_ReadF64LE(PyObject *bytes_obj, int64_t index) {\n    // bytes_obj type is enforced by mypyc\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index < 0 || index > size - 8)) {\n        CPyBytes_ReadError(index, size);\n        return CPY_FLOAT_ERROR;\n    }\n    const unsigned char *data = (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n    return CPyBytes_ReadF64LEUnsafe(data + index);\n}\n\nstatic inline double\nCPyBytes_ReadF64BE(PyObject *bytes_obj, int64_t index) {\n    // bytes_obj type is enforced by mypyc\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index < 0 || index > size - 8)) {\n        CPyBytes_ReadError(index, size);\n        return CPY_FLOAT_ERROR;\n    }\n    const unsigned char *data = (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n    return CPyBytes_ReadF64BEUnsafe(data + index);\n}\n\n#endif // MYPYC_EXPERIMENTAL\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/dict_ops.c",
    "content": "// Dict primitive operations\n//\n// These are registered in mypyc.primitives.dict_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\n\n#ifndef Py_TPFLAGS_MAPPING\n#define Py_TPFLAGS_MAPPING (1 << 6)\n#endif\n\n// Dict subclasses like defaultdict override things in interesting\n// ways, so we don't want to just directly use the dict methods. Not\n// sure if it is actually worth doing all this stuff, but it saves\n// some indirections.\nPyObject *CPyDict_GetItem(PyObject *dict, PyObject *key) {\n    if (PyDict_CheckExact(dict)) {\n        PyObject *res = PyDict_GetItemWithError(dict, key);\n        if (!res) {\n            if (!PyErr_Occurred()) {\n                PyErr_SetObject(PyExc_KeyError, key);\n            }\n        } else {\n            Py_INCREF(res);\n        }\n        return res;\n    } else {\n        return PyObject_GetItem(dict, key);\n    }\n}\n\nPyObject *CPyDict_Build(Py_ssize_t size, ...) {\n    Py_ssize_t i;\n\n    PyObject *res = _PyDict_NewPresized(size);\n    if (res == NULL) {\n        return NULL;\n    }\n\n    va_list args;\n    va_start(args, size);\n\n    for (i = 0; i < size; i++) {\n        PyObject *key = va_arg(args, PyObject *);\n        PyObject *value = va_arg(args, PyObject *);\n        if (PyDict_SetItem(res, key, value)) {\n            Py_DECREF(res);\n            return NULL;\n        }\n    }\n\n    va_end(args);\n    return res;\n}\n\nPyObject *CPyDict_Get(PyObject *dict, PyObject *key, PyObject *fallback) {\n    // We are dodgily assuming that get on a subclass doesn't have\n    // different behavior.\n    PyObject *res = PyDict_GetItemWithError(dict, key);\n    if (!res) {\n        if (PyErr_Occurred()) {\n            return NULL;\n        }\n        res = fallback;\n    }\n    Py_INCREF(res);\n    return res;\n}\n\nPyObject *CPyDict_GetWithNone(PyObject *dict, PyObject *key) {\n    return CPyDict_Get(dict, key, Py_None);\n}\n\nPyObject *CPyDict_SetDefault(PyObject *dict, PyObject *key, PyObject *value) {\n    if (PyDict_CheckExact(dict)) {\n        PyObject* ret = PyDict_SetDefault(dict, key, value);\n        Py_XINCREF(ret);\n        return ret;\n    }\n    return PyObject_CallMethodObjArgs(dict, mypyc_interned_str.setdefault, key, value, NULL);\n}\n\nPyObject *CPyDict_SetDefaultWithNone(PyObject *dict, PyObject *key) {\n    return CPyDict_SetDefault(dict, key, Py_None);\n}\n\nPyObject *CPyDict_SetDefaultWithEmptyDatatype(PyObject *dict, PyObject *key,\n                                              int data_type) {\n    PyObject *res = CPyDict_GetItem(dict, key);\n    if (!res) {\n        // CPyDict_GetItem() would generates a PyExc_KeyError\n        // when key is not found.\n        PyErr_Clear();\n\n        PyObject *new_obj;\n        if (data_type == 1) {\n            new_obj = PyList_New(0);\n        } else if (data_type == 2) {\n            new_obj = PyDict_New();\n        } else if (data_type == 3) {\n            new_obj = PySet_New(NULL);\n        } else {\n            return NULL;\n        }\n\n        if (CPyDict_SetItem(dict, key, new_obj) == -1) {\n            return NULL;\n        } else {\n            return new_obj;\n        }\n    } else {\n        return res;\n    }\n}\n\nint CPyDict_SetItem(PyObject *dict, PyObject *key, PyObject *value) {\n    if (PyDict_CheckExact(dict)) {\n        return PyDict_SetItem(dict, key, value);\n    } else {\n        return PyObject_SetItem(dict, key, value);\n    }\n}\n\nstatic inline int CPy_ObjectToStatus(PyObject *obj) {\n    if (obj) {\n        Py_DECREF(obj);\n        return 0;\n    } else {\n        return -1;\n    }\n}\n\nstatic int CPyDict_UpdateGeneral(PyObject *dict, PyObject *stuff) {\n    PyObject *res = PyObject_CallMethodOneArg(dict, mypyc_interned_str.update, stuff);\n    return CPy_ObjectToStatus(res);\n}\n\nint CPyDict_UpdateInDisplay(PyObject *dict, PyObject *stuff) {\n    // from https://github.com/python/cpython/blob/55d035113dfb1bd90495c8571758f504ae8d4802/Python/ceval.c#L2710\n    int ret = PyDict_Update(dict, stuff);\n    if (ret < 0) {\n        if (PyErr_ExceptionMatches(PyExc_AttributeError)) {\n            PyErr_Format(PyExc_TypeError,\n                         \"'%.200s' object is not a mapping\",\n                         Py_TYPE(stuff)->tp_name);\n        }\n    }\n    return ret;\n}\n\nint CPyDict_Update(PyObject *dict, PyObject *stuff) {\n    if (PyDict_CheckExact(dict)) {\n        return PyDict_Update(dict, stuff);\n    } else {\n        return CPyDict_UpdateGeneral(dict, stuff);\n    }\n}\n\nint CPyDict_UpdateFromAny(PyObject *dict, PyObject *stuff) {\n    if (PyDict_CheckExact(dict)) {\n        // Argh this sucks\n        if (PyDict_Check(stuff) || PyObject_HasAttrWithError(stuff, mypyc_interned_str.keys) > 0) {\n            return PyDict_Update(dict, stuff);\n        } else {\n            return PyDict_MergeFromSeq2(dict, stuff, 1);\n        }\n    } else {\n        return CPyDict_UpdateGeneral(dict, stuff);\n    }\n}\n\nPyObject *CPyDict_FromAny(PyObject *obj) {\n    if (PyDict_Check(obj)) {\n        return PyDict_Copy(obj);\n    } else {\n        int res;\n        PyObject *dict = PyDict_New();\n        if (!dict) {\n            return NULL;\n        }\n        if (PyObject_HasAttrWithError(obj, mypyc_interned_str.keys) > 0) {\n            res = PyDict_Update(dict, obj);\n        } else {\n            res = PyDict_MergeFromSeq2(dict, obj, 1);\n        }\n        if (res < 0) {\n            Py_DECREF(dict);\n            return NULL;\n        }\n        return dict;\n    }\n}\n\nPyObject *CPyDict_KeysView(PyObject *dict) {\n    if (PyDict_CheckExact(dict)){\n        return _CPyDictView_New(dict, &PyDictKeys_Type);\n    }\n    return PyObject_CallMethodNoArgs(dict, mypyc_interned_str.keys);\n}\n\nPyObject *CPyDict_ValuesView(PyObject *dict) {\n    if (PyDict_CheckExact(dict)){\n        return _CPyDictView_New(dict, &PyDictValues_Type);\n    }\n    return PyObject_CallMethodNoArgs(dict, mypyc_interned_str.values);\n}\n\nPyObject *CPyDict_ItemsView(PyObject *dict) {\n    if (PyDict_CheckExact(dict)){\n        return _CPyDictView_New(dict, &PyDictItems_Type);\n    }\n    return PyObject_CallMethodNoArgs(dict, mypyc_interned_str.items);\n}\n\nPyObject *CPyDict_Keys(PyObject *dict) {\n    if (PyDict_CheckExact(dict)) {\n        return PyDict_Keys(dict);\n    }\n    // Inline generic fallback logic to also return a list.\n    PyObject *list = PyList_New(0);\n    PyObject *view = PyObject_CallMethodNoArgs(dict, mypyc_interned_str.keys);\n    if (view == NULL) {\n        return NULL;\n    }\n    int res = PyList_Extend(list, view);\n    Py_DECREF(view);\n    if (res < 0) {\n        return NULL;\n    }\n    return list;\n}\n\nPyObject *CPyDict_Values(PyObject *dict) {\n    if (PyDict_CheckExact(dict)) {\n        return PyDict_Values(dict);\n    }\n    // Inline generic fallback logic to also return a list.\n    PyObject *list = PyList_New(0);\n    PyObject *view = PyObject_CallMethodNoArgs(dict, mypyc_interned_str.values);\n    if (view == NULL) {\n        return NULL;\n    }\n    int res = PyList_Extend(list, view);\n    Py_DECREF(view);\n    if (res < 0) {\n        return NULL;\n    }\n    return list;\n}\n\nPyObject *CPyDict_Items(PyObject *dict) {\n    if (PyDict_CheckExact(dict)) {\n        return PyDict_Items(dict);\n    }\n    // Inline generic fallback logic to also return a list.\n    PyObject *list = PyList_New(0);\n    PyObject *view = PyObject_CallMethodNoArgs(dict, mypyc_interned_str.items);\n    if (view == NULL) {\n        return NULL;\n    }\n    int res = PyList_Extend(list, view);\n    Py_DECREF(view);\n    if (res < 0) {\n        return NULL;\n    }\n    return list;\n}\n\nchar CPyDict_Clear(PyObject *dict) {\n    if (PyDict_CheckExact(dict)) {\n        PyDict_Clear(dict);\n    } else {\n        PyObject *res = PyObject_CallMethodNoArgs(dict, mypyc_interned_str.clear);\n        if (res == NULL) {\n            return 0;\n        }\n    }\n    return 1;\n}\n\nPyObject *CPyDict_Copy(PyObject *dict) {\n    if (PyDict_CheckExact(dict)) {\n        return PyDict_Copy(dict);\n    }\n    return PyObject_CallMethodNoArgs(dict, mypyc_interned_str.copy);\n}\n\nPyObject *CPyDict_GetKeysIter(PyObject *dict) {\n    if (PyDict_CheckExact(dict)) {\n        // Return dict itself to indicate we can use fast path instead.\n        Py_INCREF(dict);\n        return dict;\n    }\n    return PyObject_GetIter(dict);\n}\n\nPyObject *CPyDict_GetItemsIter(PyObject *dict) {\n    if (PyDict_CheckExact(dict)) {\n        // Return dict itself to indicate we can use fast path instead.\n        Py_INCREF(dict);\n        return dict;\n    }\n    PyObject *view = PyObject_CallMethodNoArgs(dict, mypyc_interned_str.items);\n    if (view == NULL) {\n        return NULL;\n    }\n    PyObject *iter = PyObject_GetIter(view);\n    Py_DECREF(view);\n    return iter;\n}\n\nPyObject *CPyDict_GetValuesIter(PyObject *dict) {\n    if (PyDict_CheckExact(dict)) {\n        // Return dict itself to indicate we can use fast path instead.\n        Py_INCREF(dict);\n        return dict;\n    }\n    PyObject *view = PyObject_CallMethodNoArgs(dict, mypyc_interned_str.values);\n    if (view == NULL) {\n        return NULL;\n    }\n    PyObject *iter = PyObject_GetIter(view);\n    Py_DECREF(view);\n    return iter;\n}\n\nstatic void _CPyDict_FromNext(tuple_T3CIO *ret, PyObject *dict_iter) {\n    // Get next item from iterator and set \"should continue\" flag.\n    ret->f2 = PyIter_Next(dict_iter);\n    if (ret->f2 == NULL) {\n        ret->f0 = 0;\n        Py_INCREF(Py_None);\n        ret->f2 = Py_None;\n    } else {\n        ret->f0 = 1;\n    }\n}\n\n// Helpers for fast dictionary iteration, return a single tuple\n// instead of writing to multiple registers, for exact dicts use\n// the fast path, and fall back to generic iterator logic for subclasses.\ntuple_T3CIO CPyDict_NextKey(PyObject *dict_or_iter, CPyTagged offset) {\n    tuple_T3CIO ret;\n    Py_ssize_t py_offset = CPyTagged_AsSsize_t(offset);\n    PyObject *dummy;\n\n    if (PyDict_CheckExact(dict_or_iter)) {\n        ret.f0 = PyDict_Next(dict_or_iter, &py_offset, &ret.f2, &dummy);\n        if (ret.f0) {\n            ret.f1 = CPyTagged_FromSsize_t(py_offset);\n        } else {\n            // Set key to None, so mypyc can manage refcounts.\n            ret.f1 = 0;\n            ret.f2 = Py_None;\n        }\n        // PyDict_Next() returns borrowed references.\n        Py_INCREF(ret.f2);\n    } else {\n        // offset is dummy in this case, just use the old value.\n        ret.f1 = offset;\n        _CPyDict_FromNext(&ret, dict_or_iter);\n    }\n    return ret;\n}\n\ntuple_T3CIO CPyDict_NextValue(PyObject *dict_or_iter, CPyTagged offset) {\n    tuple_T3CIO ret;\n    Py_ssize_t py_offset = CPyTagged_AsSsize_t(offset);\n    PyObject *dummy;\n\n    if (PyDict_CheckExact(dict_or_iter)) {\n        ret.f0 = PyDict_Next(dict_or_iter, &py_offset, &dummy, &ret.f2);\n        if (ret.f0) {\n            ret.f1 = CPyTagged_FromSsize_t(py_offset);\n        } else {\n            // Set value to None, so mypyc can manage refcounts.\n            ret.f1 = 0;\n            ret.f2 = Py_None;\n        }\n        // PyDict_Next() returns borrowed references.\n        Py_INCREF(ret.f2);\n    } else {\n        // offset is dummy in this case, just use the old value.\n        ret.f1 = offset;\n        _CPyDict_FromNext(&ret, dict_or_iter);\n    }\n    return ret;\n}\n\ntuple_T4CIOO CPyDict_NextItem(PyObject *dict_or_iter, CPyTagged offset) {\n    tuple_T4CIOO ret;\n    Py_ssize_t py_offset = CPyTagged_AsSsize_t(offset);\n\n    if (PyDict_CheckExact(dict_or_iter)) {\n        ret.f0 = PyDict_Next(dict_or_iter, &py_offset, &ret.f2, &ret.f3);\n        if (ret.f0) {\n            ret.f1 = CPyTagged_FromSsize_t(py_offset);\n        } else {\n            // Set key and value to None, so mypyc can manage refcounts.\n            ret.f1 = 0;\n            ret.f2 = Py_None;\n            ret.f3 = Py_None;\n        }\n    } else {\n        ret.f1 = offset;\n        PyObject *item = PyIter_Next(dict_or_iter);\n        if (item == NULL || !PyTuple_Check(item) || PyTuple_GET_SIZE(item) != 2) {\n            if (item != NULL) {\n                PyErr_SetString(PyExc_TypeError, \"a tuple of length 2 expected\");\n            }\n            ret.f0 = 0;\n            ret.f2 = Py_None;\n            ret.f3 = Py_None;\n        } else {\n            ret.f0 = 1;\n            ret.f2 = PyTuple_GET_ITEM(item, 0);\n            ret.f3 = PyTuple_GET_ITEM(item, 1);\n            Py_DECREF(item);\n        }\n    }\n    // PyDict_Next() returns borrowed references.\n    Py_INCREF(ret.f2);\n    Py_INCREF(ret.f3);\n    return ret;\n}\n\nint CPyMapping_Check(PyObject *obj) {\n    return Py_TYPE(obj)->tp_flags & Py_TPFLAGS_MAPPING;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/exc_ops.c",
    "content": "#include \"pythoncapi_compat.h\"\n\n// Exception related primitive operations\n//\n// These are registered in mypyc.primitives.exc_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\n\nvoid CPy_Raise(PyObject *exc) {\n    if (PyObject_IsInstance(exc, (PyObject *)&PyType_Type)) {\n        PyObject *obj = PyObject_CallNoArgs(exc);\n        if (!obj)\n            return;\n        PyErr_SetObject(exc, obj);\n        Py_DECREF(obj);\n    } else {\n        PyErr_SetObject((PyObject *)Py_TYPE(exc), exc);\n    }\n}\n\nvoid CPy_Reraise(void) {\n    PyObject *p_type, *p_value, *p_traceback;\n    PyErr_GetExcInfo(&p_type, &p_value, &p_traceback);\n    PyErr_Restore(p_type, p_value, p_traceback);\n}\n\nvoid CPyErr_SetObjectAndTraceback(PyObject *type, PyObject *value, PyObject *traceback) {\n    if (!PyType_Check(type) && Py_IsNone(value)) {\n        // The first argument must be an exception instance\n        value = type;\n        type = (PyObject *)Py_TYPE(value);\n    }\n\n    // Set the value and traceback of an error. Because calling\n    // PyErr_Restore takes away a reference to each object passed in\n    // as an argument, we manually increase the reference count of\n    // each argument before calling it.\n    Py_INCREF(type);\n    Py_INCREF(value);\n    Py_INCREF(traceback);\n    PyErr_Restore(type, value, traceback);\n}\n\ntuple_T3OOO CPy_CatchError(void) {\n    // We need to return the existing sys.exc_info() information, so\n    // that it can be restored when we finish handling the error we\n    // are catching now. Grab that triple and convert NULL values to\n    // the ExcDummy object in order to simplify refcount handling in\n    // generated code.\n    tuple_T3OOO ret;\n    PyErr_GetExcInfo(&ret.f0, &ret.f1, &ret.f2);\n    _CPy_ToDummy(&ret.f0);\n    _CPy_ToDummy(&ret.f1);\n    _CPy_ToDummy(&ret.f2);\n\n    if (!PyErr_Occurred()) {\n        PyErr_SetString(PyExc_RuntimeError, \"CPy_CatchError called with no error!\");\n    }\n\n    // Retrieve the error info and normalize it so that it looks like\n    // what python code needs it to be.\n    PyObject *type, *value, *traceback;\n    PyErr_Fetch(&type, &value, &traceback);\n    // Could we avoid always normalizing?\n    PyErr_NormalizeException(&type, &value, &traceback);\n    if (traceback != NULL) {\n        PyException_SetTraceback(value, traceback);\n    }\n    // Indicate that we are now handling this exception by stashing it\n    // in sys.exc_info().  mypyc routines that need access to the\n    // exception will read it out of there.\n    PyErr_SetExcInfo(type, value, traceback);\n    // Clear the error indicator, since the exception isn't\n    // propagating anymore.\n    PyErr_Clear();\n\n    return ret;\n}\n\nvoid CPy_RestoreExcInfo(tuple_T3OOO info) {\n    PyErr_SetExcInfo(_CPy_FromDummy(info.f0), _CPy_FromDummy(info.f1), _CPy_FromDummy(info.f2));\n}\n\nbool CPy_ExceptionMatches(PyObject *type) {\n    return PyErr_GivenExceptionMatches((PyObject *)Py_TYPE(CPy_ExcState()->exc_value), type);\n}\n\nPyObject *CPy_GetExcValue(void) {\n    PyObject *exc = CPy_ExcState()->exc_value;\n    Py_INCREF(exc);\n    return exc;\n}\n\nstatic inline void _CPy_ToNone(PyObject **p) {\n    if (*p == NULL) {\n        Py_INCREF(Py_None);\n        *p = Py_None;\n    }\n}\n\nvoid _CPy_GetExcInfo(PyObject **p_type, PyObject **p_value, PyObject **p_traceback) {\n    PyErr_GetExcInfo(p_type, p_value, p_traceback);\n    _CPy_ToNone(p_type);\n    _CPy_ToNone(p_value);\n    _CPy_ToNone(p_traceback);\n}\n\ntuple_T3OOO CPy_GetExcInfo(void) {\n    tuple_T3OOO ret;\n    _CPy_GetExcInfo(&ret.f0, &ret.f1, &ret.f2);\n    return ret;\n}\n\nvoid CPyError_OutOfMemory(void) {\n    fprintf(stderr, \"fatal: out of memory\\n\");\n    fflush(stderr);\n    abort();\n}\n\n// Construct a nicely formatted type name based on __module__ and __name__.\nstatic PyObject *CPy_GetTypeName(PyObject *type) {\n    PyObject *module = NULL, *name = NULL;\n    PyObject *full = NULL;\n\n    module = PyObject_GetAttr(type, mypyc_interned_str.__module__);\n    if (!module || !PyUnicode_Check(module)) {\n        goto out;\n    }\n    name = PyObject_GetAttr(type, mypyc_interned_str.__qualname__);\n    if (!name || !PyUnicode_Check(name)) {\n        goto out;\n    }\n\n    if (PyUnicode_CompareWithASCIIString(module, \"builtins\") == 0) {\n        Py_INCREF(name);\n        full = name;\n    } else {\n        full = PyUnicode_FromFormat(\"%U.%U\", module, name);\n    }\n\nout:\n    Py_XDECREF(module);\n    Py_XDECREF(name);\n    return full;\n}\n\n// Get the type of a value as a string, expanding tuples to include\n// all the element types.\nstatic PyObject *CPy_FormatTypeName(PyObject *value) {\n    if (Py_IsNone(value)) {\n        return PyUnicode_FromString(\"None\");\n    }\n\n    if (!PyTuple_CheckExact(value)) {\n        return CPy_GetTypeName((PyObject *)Py_TYPE(value));\n    }\n\n    if (PyTuple_GET_SIZE(value) > 10) {\n        return PyUnicode_FromFormat(\"tuple[<%d items>]\", PyTuple_GET_SIZE(value));\n    }\n\n    // Most of the logic is all for tuples, which is the only interesting case\n    PyObject *output = PyUnicode_FromString(\"tuple[\");\n    if (!output) {\n        return NULL;\n    }\n    /* This is quadratic but if that ever matters something is really weird. */\n    int i;\n    for (i = 0; i < PyTuple_GET_SIZE(value); i++) {\n        PyObject *s = CPy_FormatTypeName(PyTuple_GET_ITEM(value, i));\n        if (!s) {\n            Py_DECREF(output);\n            return NULL;\n        }\n        PyObject *next = PyUnicode_FromFormat(\"%U%U%s\", output, s,\n                                              i + 1 == PyTuple_GET_SIZE(value) ? \"]\" : \", \");\n        Py_DECREF(output);\n        Py_DECREF(s);\n        if (!next) {\n            return NULL;\n        }\n        output = next;\n    }\n    return output;\n}\n\nCPy_NOINLINE\nvoid CPy_TypeError(const char *expected, PyObject *value) {\n    PyObject *out = CPy_FormatTypeName(value);\n    if (out) {\n        PyErr_Format(PyExc_TypeError, \"%s object expected; got %U\", expected, out);\n        Py_DECREF(out);\n    } else {\n        PyErr_Format(PyExc_TypeError, \"%s object expected; and errored formatting real type!\",\n                     expected);\n    }\n}\n\n// The PyFrameObject type definition (struct _frame) has been moved\n// to the internal C API: to the pycore_frame.h header file.\n// https://github.com/python/cpython/pull/31530\n#if PY_VERSION_HEX >= 0x030b00a6\n#include \"internal/pycore_frame.h\"\n#endif\n\n// This function is basically exactly the same with _PyTraceback_Add\n// which is available in all the versions we support.\n// We're continuing to use this because we'll probably optimize this later.\nvoid CPy_AddTraceback(const char *filename, const char *funcname, int line, PyObject *globals) {\n    PyObject *exc, *val, *tb;\n    PyThreadState *thread_state = PyThreadState_GET();\n    PyFrameObject *frame_obj;\n\n    // We need to save off the exception state because in 3.8,\n    // PyFrame_New fails if there is an error set and it fails to look\n    // up builtins in the globals. (_PyTraceback_Add documents that it\n    // needs to do it because it decodes the filename according to the\n    // FS encoding, which could have a decoder in Python. We don't do\n    // that so *that* doesn't apply to us.)\n    PyErr_Fetch(&exc, &val, &tb);\n    PyCodeObject *code_obj = PyCode_NewEmpty(filename, funcname, line);\n    if (code_obj == NULL) {\n        goto error;\n    }\n\n    frame_obj = PyFrame_New(thread_state, code_obj, globals, 0);\n    if (frame_obj == NULL) {\n        Py_DECREF(code_obj);\n        goto error;\n    }\n    frame_obj->f_lineno = line;\n    PyErr_Restore(exc, val, tb);\n    PyTraceBack_Here(frame_obj);\n    Py_DECREF(code_obj);\n    Py_DECREF(frame_obj);\n\n    return;\n\nerror:\n#if CPY_3_12_FEATURES\n    _PyErr_ChainExceptions1(exc);\n#else\n    _PyErr_ChainExceptions(exc, val, tb);\n#endif\n}\n\nCPy_NOINLINE\nvoid CPy_TypeErrorTraceback(const char *filename, const char *funcname, int line,\n                            PyObject *globals, const char *expected, PyObject *value) {\n    CPy_TypeError(expected, value);\n    CPy_AddTraceback(filename, funcname, line, globals);\n}\n\nvoid CPy_AttributeError(const char *filename, const char *funcname, const char *classname,\n                        const char *attrname, int line, PyObject *globals) {\n    char buf[500];\n    snprintf(buf, sizeof(buf), \"attribute '%.200s' of '%.200s' undefined\", attrname, classname);\n    PyErr_SetString(PyExc_AttributeError, buf);\n    CPy_AddTraceback(filename, funcname, line, globals);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/float_ops.c",
    "content": "// Float primitive operations\n//\n// These are registered in mypyc.primitives.float_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\n\n\nstatic double CPy_DomainError(void) {\n    PyErr_SetString(PyExc_ValueError, \"math domain error\");\n    return CPY_FLOAT_ERROR;\n}\n\nstatic double CPy_MathRangeError(void) {\n    PyErr_SetString(PyExc_OverflowError, \"math range error\");\n    return CPY_FLOAT_ERROR;\n}\n\nstatic double CPy_MathExpectedNonNegativeInputError(double x) {\n    char *buf = PyOS_double_to_string(x, 'r', 0, Py_DTSF_ADD_DOT_0, NULL);\n    if (buf) {\n        PyErr_Format(PyExc_ValueError, \"expected a nonnegative input, got %s\", buf);\n        PyMem_Free(buf);\n    }\n    return CPY_FLOAT_ERROR;\n}\n\nstatic double CPy_MathExpectedPositiveInputError(double x) {\n    char *buf = PyOS_double_to_string(x, 'r', 0, Py_DTSF_ADD_DOT_0, NULL);\n    if (buf) {\n        PyErr_Format(PyExc_ValueError, \"expected a positive input, got %s\", buf);\n        PyMem_Free(buf);\n    }\n    return CPY_FLOAT_ERROR;\n}\n\nstatic double CPy_MathExpectedFiniteInput(double x) {\n    char *buf = PyOS_double_to_string(x, 'r', 0, Py_DTSF_ADD_DOT_0, NULL);\n    if (buf) {\n        PyErr_Format(PyExc_ValueError, \"expected a finite input, got %s\", buf);\n        PyMem_Free(buf);\n    }\n    return CPY_FLOAT_ERROR;\n}\n\ndouble CPyFloat_FromTagged(CPyTagged x) {\n    if (CPyTagged_CheckShort(x)) {\n        return CPyTagged_ShortAsSsize_t(x);\n    }\n    double result = PyFloat_AsDouble(CPyTagged_LongAsObject(x));\n    if (unlikely(result == -1.0) && PyErr_Occurred()) {\n        return CPY_FLOAT_ERROR;\n    }\n    return result;\n}\n\ndouble CPyFloat_Sin(double x) {\n    double v = sin(x);\n    if (unlikely(isnan(v)) && !isnan(x)) {\n#if CPY_3_14_FEATURES\n        return CPy_MathExpectedFiniteInput(x);\n#else\n        return CPy_DomainError();\n#endif\n    }\n    return v;\n}\n\ndouble CPyFloat_Cos(double x) {\n    double v = cos(x);\n    if (unlikely(isnan(v)) && !isnan(x)) {\n#if CPY_3_14_FEATURES\n        return CPy_MathExpectedFiniteInput(x);\n#else\n        return CPy_DomainError();\n#endif\n    }\n    return v;\n}\n\ndouble CPyFloat_Tan(double x) {\n    if (unlikely(isinf(x))) {\n#if CPY_3_14_FEATURES\n        return CPy_MathExpectedFiniteInput(x);\n#else\n        return CPy_DomainError();\n#endif\n    }\n    return tan(x);\n}\n\ndouble CPyFloat_Sqrt(double x) {\n    if (x < 0.0) {\n#if CPY_3_14_FEATURES\n        return CPy_MathExpectedNonNegativeInputError(x);\n#else\n        return CPy_DomainError();\n#endif\n    }\n    return sqrt(x);\n}\n\ndouble CPyFloat_Exp(double x) {\n    double v = exp(x);\n    if (unlikely(v == INFINITY) && x != INFINITY) {\n        return CPy_MathRangeError();\n    }\n    return v;\n}\n\ndouble CPyFloat_Log(double x) {\n    if (x <= 0.0) {\n#if CPY_3_14_FEATURES\n        return CPy_MathExpectedPositiveInputError(x);\n#else\n        return CPy_DomainError();\n#endif\n    }\n    return log(x);\n}\n\nCPyTagged CPyFloat_Floor(double x) {\n    double v = floor(x);\n    return CPyTagged_FromFloat(v);\n}\n\nCPyTagged CPyFloat_Ceil(double x) {\n    double v = ceil(x);\n    return CPyTagged_FromFloat(v);\n}\n\nbool CPyFloat_IsInf(double x) {\n    return isinf(x) != 0;\n}\n\nbool CPyFloat_IsNaN(double x) {\n    return isnan(x) != 0;\n}\n\n// From CPython 3.10.0, Objects/floatobject.c\nstatic void\n_float_div_mod(double vx, double wx, double *floordiv, double *mod)\n{\n    double div;\n    *mod = fmod(vx, wx);\n    /* fmod is typically exact, so vx-mod is *mathematically* an\n       exact multiple of wx.  But this is fp arithmetic, and fp\n       vx - mod is an approximation; the result is that div may\n       not be an exact integral value after the division, although\n       it will always be very close to one.\n    */\n    div = (vx - *mod) / wx;\n    if (*mod) {\n        /* ensure the remainder has the same sign as the denominator */\n        if ((wx < 0) != (*mod < 0)) {\n            *mod += wx;\n            div -= 1.0;\n        }\n    }\n    else {\n        /* the remainder is zero, and in the presence of signed zeroes\n           fmod returns different results across platforms; ensure\n           it has the same sign as the denominator. */\n        *mod = copysign(0.0, wx);\n    }\n    /* snap quotient to nearest integral value */\n    if (div) {\n        *floordiv = floor(div);\n        if (div - *floordiv > 0.5) {\n            *floordiv += 1.0;\n        }\n    }\n    else {\n        /* div is zero - get the same sign as the true quotient */\n        *floordiv = copysign(0.0, vx / wx); /* zero w/ sign of vx/wx */\n    }\n}\n\ndouble CPyFloat_FloorDivide(double x, double y) {\n    double mod, floordiv;\n    if (y == 0) {\n        PyErr_SetString(PyExc_ZeroDivisionError, \"float floor division by zero\");\n        return CPY_FLOAT_ERROR;\n    }\n    _float_div_mod(x, y, &floordiv, &mod);\n    return floordiv;\n}\n\n// Adapted from CPython 3.10.7\ndouble CPyFloat_Pow(double x, double y) {\n    if (!isfinite(x) || !isfinite(y)) {\n        if (isnan(x))\n            return y == 0.0 ? 1.0 : x; /* NaN**0 = 1 */\n        else if (isnan(y))\n            return x == 1.0 ? 1.0 : y; /* 1**NaN = 1 */\n        else if (isinf(x)) {\n            int odd_y = isfinite(y) && fmod(fabs(y), 2.0) == 1.0;\n            if (y > 0.0)\n                return odd_y ? x : fabs(x);\n            else if (y == 0.0)\n                return 1.0;\n            else /* y < 0. */\n                return odd_y ? copysign(0.0, x) : 0.0;\n        }\n        else if (isinf(y)) {\n            if (fabs(x) == 1.0)\n                return 1.0;\n            else if (y > 0.0 && fabs(x) > 1.0)\n                return y;\n            else if (y < 0.0 && fabs(x) < 1.0) {\n                #if PY_VERSION_HEX < 0x030B0000\n                if (x == 0.0) { /* 0**-inf: divide-by-zero */\n                    return CPy_DomainError();\n                }\n                #endif\n                return -y; /* result is +inf */\n            } else\n                return 0.0;\n        }\n    }\n    double r = pow(x, y);\n    if (!isfinite(r)) {\n        if (isnan(r)) {\n            return CPy_DomainError();\n        }\n        /*\n           an infinite result here arises either from:\n           (A) (+/-0.)**negative (-> divide-by-zero)\n           (B) overflow of x**y with x and y finite\n        */\n        else if (isinf(r)) {\n            if (x == 0.0)\n                return CPy_DomainError();\n            else\n                return CPy_MathRangeError();\n        }\n    }\n    return r;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/function_wrapper.c",
    "content": "#define PY_SSIZE_T_CLEAN\n#include <stdint.h>\n#include \"CPy.h\"\n\n#define CPyFunction_weakreflist(f) (((PyCFunctionObject *)f)->m_weakreflist)\n#define CPyFunction_class(f) ((PyObject*) ((PyCMethodObject *) (f))->mm_class)\n#define CPyFunction_func_vectorcall(f) (((PyCFunctionObject *)f)->vectorcall)\n\nstatic int\nCPyFunction_clear(CPyFunction *m) {\n    Py_CLEAR(((PyCFunctionObject*)m)->m_module);\n    PyObject_ClearManagedDict((PyObject*)m);\n    Py_CLEAR(m->func_name);\n    Py_CLEAR(m->func_code);\n    PyObject *cls = CPyFunction_class(m);\n    ((PyCMethodObject *)m)->mm_class = NULL;\n    Py_XDECREF(cls);\n\n    return 0;\n}\n\nstatic void CPyFunction_dealloc(CPyFunction *m) {\n    PyObject_GC_UnTrack(m);\n    if (CPyFunction_weakreflist(m) != NULL)\n        PyObject_ClearWeakRefs((PyObject *) m);\n    CPyFunction_clear(m);\n    PyMem_Free(m->func.func.m_ml);\n    PyObject_GC_Del(m);\n}\n\nstatic PyObject* CPyFunction_repr(CPyFunction *op) {\n    return PyUnicode_FromFormat(\"<function %U at %p>\", op->func_name, (void *)op);\n}\n\nstatic PyObject* CPyFunction_call(PyObject *func, PyObject *args, PyObject *kw) {\n    CPyFunction *f = (CPyFunction *)func;\n    vectorcallfunc vc = CPyFunction_func_vectorcall(f);\n    assert(vc);\n    return PyVectorcall_Call(func, args, kw);\n}\n\nstatic int CPyFunction_traverse(CPyFunction *m, visitproc visit, void *arg) {\n    Py_VISIT(((PyCFunctionObject *)m)->m_module);\n    int e = PyObject_VisitManagedDict((PyObject*)m, visit, arg);\n    if (e != 0) return e;\n    Py_VISIT(m->func_name);\n    Py_VISIT(m->func_code);\n    Py_VISIT(CPyFunction_class(m));\n    return 0;\n}\n\nstatic PyMemberDef CPyFunction_members[] = {\n    {\"__module__\", T_OBJECT, offsetof(PyCFunctionObject, m_module), 0, 0},\n    {\"__vectorcalloffset__\", T_PYSSIZET, offsetof(PyCFunctionObject, vectorcall), READONLY, 0},\n    {\"__weaklistoffset__\", T_PYSSIZET, offsetof(PyCFunctionObject, m_weakreflist), READONLY, 0},\n    {0, 0, 0,  0, 0}\n};\n\nPyObject* CPyFunction_get_name(PyObject *op, void *context) {\n    (void)context;\n    CPyFunction *func = (CPyFunction *)op;\n    if (unlikely(func->func_name == NULL)) {\n        func->func_name = PyUnicode_InternFromString(((PyCFunctionObject *)func)->m_ml->ml_name);\n        if (unlikely(func->func_name == NULL))\n            return NULL;\n    }\n    Py_INCREF(func->func_name);\n    return func->func_name;\n}\n\nint CPyFunction_set_name(PyObject *op, PyObject *value, void *context) {\n    (void)context;\n    CPyFunction *func = (CPyFunction *)op;\n    if (unlikely(!value || !PyUnicode_Check(value))) {\n        PyErr_SetString(PyExc_TypeError, \"__name__ must be set to a string object\");\n        return -1;\n    }\n\n    Py_INCREF(value);\n    Py_XDECREF(func->func_name);\n    func->func_name = value;\n    return 0;\n}\n\nPyObject* CPyFunction_get_code(PyObject *op, void *context) {\n    (void)context;\n    CPyFunction *func = (CPyFunction *)op;\n    PyObject* result = (func->func_code) ? func->func_code : Py_None;\n    Py_INCREF(result);\n    return result;\n}\n\nstatic PyObject* CPyFunction_get_none(PyObject *op, void *context) {\n    (void)op;\n    (void)context;\n    PyObject* result = Py_None;\n    Py_INCREF(result);\n    return result;\n}\n\nint CPyFunction_set_none(PyObject *op, PyObject *value, void *context) {\n    (void)op;\n    (void)value;\n    (void)context;\n    return 0;\n}\n\nPyObject* CPyFunction_get_defaults(PyObject *op, void *context) {\n    return CPyFunction_get_none(op, context);\n}\n\nPyObject* CPyFunction_get_kwdefaults(PyObject *op, void *context) {\n    return CPyFunction_get_none(op, context);\n}\n\nPyObject* CPyFunction_get_annotations(PyObject *op, void *context) {\n    return CPyFunction_get_none(op, context);\n}\n\nint CPyFunction_set_annotations(PyObject *op, PyObject *value, void *context) {\n    return CPyFunction_set_none(op, value, context);\n}\n\nstatic PyGetSetDef CPyFunction_getsets[] = {\n    {\"__dict__\", (getter)PyObject_GenericGetDict, (setter)PyObject_GenericSetDict, 0, 0},\n    {\"__name__\", (getter)CPyFunction_get_name, (setter)CPyFunction_set_name, 0, 0},\n    {\"__code__\", (getter)CPyFunction_get_code, 0, 0, 0},\n    {\"__defaults__\", (getter)CPyFunction_get_defaults, 0, 0, 0},\n    {\"__kwdefaults__\", (getter)CPyFunction_get_kwdefaults, 0, 0, 0},\n    {\"__annotations__\", (getter)CPyFunction_get_annotations, CPyFunction_set_annotations, 0, 0},\n    {0, 0, 0, 0, 0}\n};\n\nstatic PyObject* CPy_PyMethod_New(PyObject *func, PyObject *self, PyObject *typ) {\n    (void)typ;\n    if (!self) {\n        Py_INCREF(func);\n        return func;\n    }\n    return PyMethod_New(func, self);\n}\n\nstatic PyType_Slot CPyFunction_slots[] = {\n    {Py_tp_dealloc, (void *)CPyFunction_dealloc},\n    {Py_tp_repr, (void *)CPyFunction_repr},\n    {Py_tp_call, (void *)CPyFunction_call},\n    {Py_tp_traverse, (void *)CPyFunction_traverse},\n    {Py_tp_clear, (void *)CPyFunction_clear},\n    {Py_tp_members, (void *)CPyFunction_members},\n    {Py_tp_getset, (void *)CPyFunction_getsets},\n    {Py_tp_descr_get, (void *)CPy_PyMethod_New},\n    {0, 0},\n};\n\nstatic PyType_Spec CPyFunction_spec = {\n    .name = \"Function compiled with mypyc\",\n    .basicsize = sizeof(CPyFunction),\n    .itemsize = 0,\n    .flags = Py_TPFLAGS_IMMUTABLETYPE |\n#if PY_VERSION_HEX >= 0x030C0000\n             Py_TPFLAGS_MANAGED_DICT |\n#endif\n             Py_TPFLAGS_HAVE_VECTORCALL | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE,\n    .slots = CPyFunction_slots,\n};\n\nstatic PyTypeObject *CPyFunctionType = NULL;\n\nstatic PyObject* CPyFunction_Vectorcall(PyObject *func, PyObject *const *args, size_t nargsf, PyObject *kwnames) {\n    CPyFunction *f = (CPyFunction *)func;\n    Py_ssize_t nargs = PyVectorcall_NARGS(nargsf);\n    PyObject *self;\n    PyCFunction meth = ((PyCFunctionObject *)f)->m_ml->ml_meth;\n\n    self = ((PyCFunctionObject *)f)->m_self;\n    if (!self) {\n        self = args[0];\n        args += 1;\n        nargs -= 1;\n    }\n    return ((_PyCFunctionFastWithKeywords)(void(*)(void))meth)(self, args, nargs, kwnames);\n}\n\n\nstatic CPyFunction* CPyFunction_Init(CPyFunction *op, PyMethodDef *ml, PyObject* name,\n                                     PyObject *module, PyObject* code, bool set_self) {\n    PyCFunctionObject *cf = (PyCFunctionObject *)op;\n    CPyFunction_weakreflist(op) = NULL;\n    cf->m_ml = ml;\n    cf->m_self = set_self ? (PyObject *) op : NULL;\n\n    Py_XINCREF(module);\n    cf->m_module = module;\n\n    Py_INCREF(name);\n    op->func_name = name;\n\n    ((PyCMethodObject *)op)->mm_class = NULL;\n\n    Py_XINCREF(code);\n    op->func_code = code;\n\n    CPyFunction_func_vectorcall(op) = CPyFunction_Vectorcall;\n    return op;\n}\n\nstatic PyObject* CPyCode_New(const char *filename, const char *funcname, int first_line, int flags) {\n    PyCodeObject *code_obj = PyCode_NewEmpty(filename, funcname, first_line);\n    if (unlikely(!code_obj)) {\n        return NULL;\n    }\n    code_obj->co_flags = flags;\n    return (PyObject *)code_obj;\n}\n\nstatic PyMethodDef* CPyMethodDef_New(const char *name, PyCFunction func, int flags, const char *doc) {\n    PyMethodDef *method = (PyMethodDef *)PyMem_Malloc(sizeof(PyMethodDef));\n    if (unlikely(!method)) {\n        return NULL;\n    }\n    method->ml_name = name;\n    method->ml_meth = func;\n    method->ml_flags = flags;\n    method->ml_doc = doc;\n    return method;\n}\n\nPyObject* CPyFunction_New(PyObject *module, const char *filename, const char *funcname,\n                          PyCFunction func, int func_flags, const char *func_doc,\n                          int first_line, int code_flags, bool has_self_arg) {\n    PyMethodDef *method = NULL;\n    PyObject *code = NULL, *op = NULL;\n    bool set_self = false;\n\n    if (!CPyFunctionType) {\n        CPyFunctionType = (PyTypeObject *)PyType_FromSpec(&CPyFunction_spec);\n        if (unlikely(!CPyFunctionType)) {\n            goto err;\n        }\n    }\n\n    method = CPyMethodDef_New(funcname, func, func_flags, func_doc);\n    if (unlikely(!method)) {\n        goto err;\n    }\n    code = CPyCode_New(filename, funcname, first_line, code_flags);\n    if (unlikely(!code)) {\n        goto err;\n    }\n\n    // Set m_self inside the function wrapper only if the wrapped function has no self arg\n    // to pass m_self as the self arg when the function is called.\n    // When the function has a self arg, it will come in the args vector passed to the\n    // vectorcall handler.\n    set_self = !has_self_arg;\n    op = (PyObject *)CPyFunction_Init(PyObject_GC_New(CPyFunction, CPyFunctionType),\n                                      method, PyUnicode_FromString(funcname), module,\n                                      code, set_self);\n    if (unlikely(!op)) {\n        goto err;\n    }\n    PyObject_GC_Track(op);\n    return op;\n\nerr:\n    CPyError_OutOfMemory();\n    if (method) {\n        PyMem_Free(method);\n    }\n    return NULL;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/generic_ops.c",
    "content": "// Generic primitive operations\n//\n// These are registered in mypyc.primitives.generic_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\n\nCPyTagged CPyObject_Hash(PyObject *o) {\n    Py_hash_t h = PyObject_Hash(o);\n    if (h == -1) {\n        return CPY_INT_TAG;\n    } else {\n        // This is tragically annoying. The range of hash values in\n        // 64-bit python covers 64-bits, and our short integers only\n        // cover 63. This means that half the time we are boxing the\n        // result for basically no good reason. To add insult to\n        // injury it is probably about to be immediately unboxed by a\n        // tp_hash wrapper.\n        return CPyTagged_FromSsize_t(h);\n    }\n}\n\nPyObject *CPyObject_GetAttr3(PyObject *v, PyObject *name, PyObject *defl)\n{\n    PyObject *result = PyObject_GetAttr(v, name);\n    if (!result && PyErr_ExceptionMatches(PyExc_AttributeError)) {\n        PyErr_Clear();\n        Py_INCREF(defl);\n        result = defl;\n    }\n    return result;\n}\n\nPyObject *CPyIter_Next(PyObject *iter)\n{\n    return (*Py_TYPE(iter)->tp_iternext)(iter);\n}\n\nPyObject *CPyNumber_Power(PyObject *base, PyObject *index)\n{\n    return PyNumber_Power(base, index, Py_None);\n}\n\nPyObject *CPyNumber_InPlacePower(PyObject *base, PyObject *index)\n{\n    return PyNumber_InPlacePower(base, index, Py_None);\n}\n\nPyObject *CPyObject_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) {\n    PyObject *start_obj = CPyTagged_AsObject(start);\n    PyObject *end_obj = CPyTagged_AsObject(end);\n    if (unlikely(start_obj == NULL || end_obj == NULL)) {\n        return NULL;\n    }\n    PyObject *slice = PySlice_New(start_obj, end_obj, NULL);\n    Py_DECREF(start_obj);\n    Py_DECREF(end_obj);\n    if (unlikely(slice == NULL)) {\n        return NULL;\n    }\n    PyObject *result = PyObject_GetItem(obj, slice);\n    Py_DECREF(slice);\n    return result;\n}\n\ntypedef PyObject *(*SetupFunction)(PyObject *);\n\nPyObject *CPy_SetupObject(PyObject *type) {\n    PyTypeObject *tp = (PyTypeObject *)type;\n    PyMethodDef *def = NULL;\n    for(; tp; tp = tp->tp_base) {\n        def = tp->tp_methods;\n        if (!def || !def->ml_name) {\n            continue;\n        }\n\n        if (!strcmp(def->ml_name, \"__internal_mypyc_setup\")) {\n            return ((SetupFunction)(void(*)(void))def->ml_meth)(type);\n        }\n    }\n\n    PyErr_SetString(PyExc_RuntimeError, \"Internal mypyc error: Unable to find object setup function\");\n    return NULL;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/getargs.c",
    "content": "/* getargs implementation copied from Python 3.8 and stripped down to only include\n * the functions we need.\n * We also add support for required kwonly args and accepting *args / **kwargs.\n * A good idea would be to also vendor in the Fast versions and get our stuff\n * working with *that*.\n * Another probably good idea is to strip out all the formatting stuff we don't need\n * and then add in custom stuff that we do need.\n *\n * DOCUMENTATION OF THE EXTENSIONS:\n *  - Arguments given after a @ format specify are required keyword-only arguments.\n *    The | and $ specifiers must both appear before @.\n *  - If the first character of a format string is %, then the function can support\n *    *args and **kwargs. On seeing a %, the parser will consume two arguments,\n *    which should be pointers to variables to store the *args and **kwargs, respectively.\n *    Either pointer can be NULL, in which case the function doesn't take that\n *    variety of vararg.\n *    Unlike most format specifiers, the caller takes ownership of these objects\n *    and is responsible for decrefing them.\n *  - All arguments must use the 'O' format.\n *  - There's minimal error checking of format strings. They are generated\n *    programmatically and can be assumed valid.\n */\n\n// These macro definitions are copied from pyport.h in Python 3.9 and later\n// https://bugs.python.org/issue19569\n#if defined(__clang__)\n#define _Py_COMP_DIAG_PUSH _Pragma(\"clang diagnostic push\")\n#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS \\\n    _Pragma(\"clang diagnostic ignored \\\"-Wdeprecated-declarations\\\"\")\n#define _Py_COMP_DIAG_POP _Pragma(\"clang diagnostic pop\")\n#elif defined(__GNUC__) \\\n    && ((__GNUC__ >= 5) || (__GNUC__ == 4) && (__GNUC_MINOR__ >= 6))\n#define _Py_COMP_DIAG_PUSH _Pragma(\"GCC diagnostic push\")\n#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS \\\n    _Pragma(\"GCC diagnostic ignored \\\"-Wdeprecated-declarations\\\"\")\n#define _Py_COMP_DIAG_POP _Pragma(\"GCC diagnostic pop\")\n#elif defined(_MSC_VER)\n#define _Py_COMP_DIAG_PUSH __pragma(warning(push))\n#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS __pragma(warning(disable: 4996))\n#define _Py_COMP_DIAG_POP __pragma(warning(pop))\n#else\n#define _Py_COMP_DIAG_PUSH\n#define _Py_COMP_DIAG_IGNORE_DEPR_DECLS\n#define _Py_COMP_DIAG_POP\n#endif\n\n#include \"Python.h\"\n#include \"pythonsupport.h\"\n\n#include <ctype.h>\n#include <float.h>\n\n#ifndef PyDict_GET_SIZE\n#define PyDict_GET_SIZE(d) PyDict_Size(d)\n#endif\n\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\nint CPyArg_ParseTupleAndKeywords(PyObject *, PyObject *,\n                                 const char *, const char *, const char * const *, ...);\n\n/* Forward */\nstatic int vgetargskeywords(PyObject *, PyObject *,\n                            const char *, const char *, const char * const *, va_list *);\nstatic void skipitem(const char **, va_list *);\n\n/* Support for keyword arguments donated by\n   Geoff Philbrick <philbric@delphi.hks.com> */\n\n/* Return false (0) for error, else true. */\nint\nCPyArg_ParseTupleAndKeywords(PyObject *args,\n                             PyObject *keywords,\n                             const char *format,\n                             const char *fname,\n                             const char * const *kwlist, ...)\n{\n    int retval;\n    va_list va;\n\n    va_start(va, kwlist);\n    retval = vgetargskeywords(args, keywords, format, fname, kwlist, &va);\n    va_end(va);\n    return retval;\n}\n\n#define IS_END_OF_FORMAT(c) (c == '\\0' || c == ';' || c == ':')\n\nstatic int\nvgetargskeywords(PyObject *args, PyObject *kwargs, const char *format,\n                 const char *fname, const char * const *kwlist, va_list *p_va)\n{\n    int min = INT_MAX;\n    int max = INT_MAX;\n    int required_kwonly_start = INT_MAX;\n    int has_required_kws = 0;\n    int i, pos, len;\n    int skip = 0;\n    Py_ssize_t nargs, nkwargs;\n    PyObject *current_arg;\n    int bound_pos_args;\n\n    PyObject **p_args = NULL, **p_kwargs = NULL;\n\n    assert(args != NULL && PyTuple_Check(args));\n    assert(kwargs == NULL || PyDict_Check(kwargs));\n    assert(format != NULL);\n    assert(kwlist != NULL);\n    assert(p_va != NULL);\n\n    /* scan kwlist and count the number of positional-only parameters */\n    for (pos = 0; kwlist[pos] && !*kwlist[pos]; pos++) {\n    }\n    /* scan kwlist and get greatest possible nbr of args */\n    for (len = pos; kwlist[len]; len++) {\n#ifdef DEBUG\n        if (!*kwlist[len]) {\n            PyErr_SetString(PyExc_SystemError,\n                            \"Empty keyword parameter name\");\n            return 0;\n        }\n#endif\n    }\n\n    if (*format == '%') {\n        p_args = va_arg(*p_va, PyObject **);\n        p_kwargs = va_arg(*p_va, PyObject **);\n        format++;\n    }\n\n    nargs = PyTuple_GET_SIZE(args);\n    nkwargs = (kwargs == NULL) ? 0 : PyDict_GET_SIZE(kwargs);\n    if (unlikely(nargs + nkwargs > len && !p_args && !p_kwargs)) {\n        /* Adding \"keyword\" (when nargs == 0) prevents producing wrong error\n           messages in some special cases (see bpo-31229). */\n        PyErr_Format(PyExc_TypeError,\n                     \"%.200s%s takes at most %d %sargument%s (%zd given)\",\n                     (fname == NULL) ? \"function\" : fname,\n                     (fname == NULL) ? \"\" : \"()\",\n                     len,\n                     (nargs == 0) ? \"keyword \" : \"\",\n                     (len == 1) ? \"\" : \"s\",\n                     nargs + nkwargs);\n        return 0;\n    }\n\n    /* convert tuple args and keyword args in same loop, using kwlist to drive process */\n    for (i = 0; i < len; i++) {\n        if (*format == '|') {\n#ifdef DEBUG\n            if (min != INT_MAX) {\n                PyErr_SetString(PyExc_SystemError,\n                                \"Invalid format string (| specified twice)\");\n                return 0;\n            }\n#endif\n\n            min = i;\n            format++;\n\n#ifdef DEBUG\n            if (max != INT_MAX) {\n                PyErr_SetString(PyExc_SystemError,\n                                \"Invalid format string ($ before |)\");\n                return 0;\n            }\n#endif\n\n            /* If there are optional args, figure out whether we have\n             * required keyword arguments so that we don't bail without\n             * enforcing them. */\n            has_required_kws = strchr(format, '@') != NULL;\n        }\n        if (*format == '$') {\n#ifdef DEBUG\n            if (max != INT_MAX) {\n                PyErr_SetString(PyExc_SystemError,\n                                \"Invalid format string ($ specified twice)\");\n                return 0;\n            }\n#endif\n\n            max = i;\n            format++;\n\n#ifdef DEBUG\n            if (max < pos) {\n                PyErr_SetString(PyExc_SystemError,\n                                \"Empty parameter name after $\");\n                return 0;\n            }\n#endif\n            if (skip) {\n                /* Now we know the minimal and the maximal numbers of\n                 * positional arguments and can raise an exception with\n                 * informative message (see below). */\n                break;\n            }\n            if (unlikely(max < nargs && !p_args)) {\n                if (max == 0) {\n                    PyErr_Format(PyExc_TypeError,\n                                 \"%.200s%s takes no positional arguments\",\n                                 (fname == NULL) ? \"function\" : fname,\n                                 (fname == NULL) ? \"\" : \"()\");\n                }\n                else {\n                    PyErr_Format(PyExc_TypeError,\n                                 \"%.200s%s takes %s %d positional argument%s\"\n                                 \" (%zd given)\",\n                                 (fname == NULL) ? \"function\" : fname,\n                                 (fname == NULL) ? \"\" : \"()\",\n                                 (min < max) ? \"at most\" : \"exactly\",\n                                 max,\n                                 max == 1 ? \"\" : \"s\",\n                                 nargs);\n                }\n                return 0;\n            }\n        }\n        if (*format == '@') {\n#ifdef DEBUG\n            if (min == INT_MAX && max == INT_MAX) {\n                PyErr_SetString(PyExc_SystemError,\n                                \"Invalid format string \"\n                                \"(@ without preceding | and $)\");\n                return 0;\n            }\n            if (required_kwonly_start != INT_MAX) {\n                PyErr_SetString(PyExc_SystemError,\n                                \"Invalid format string (@ specified twice)\");\n                return 0;\n            }\n#endif\n\n            required_kwonly_start = i;\n            format++;\n        }\n#ifdef DEBUG\n        if (IS_END_OF_FORMAT(*format)) {\n            PyErr_Format(PyExc_SystemError,\n                         \"More keyword list entries (%d) than \"\n                         \"format specifiers (%d)\", len, i);\n            return 0;\n        }\n#endif\n        if (!skip) {\n            if (i < nargs && i < max) {\n                current_arg = Py_NewRef(PyTuple_GET_ITEM(args, i));\n            }\n            else if (nkwargs && i >= pos) {\n                if (unlikely(PyDict_GetItemStringRef(kwargs, kwlist[i], &current_arg) < 0)) {\n                    return 0;\n                }\n                if (current_arg) {\n                    --nkwargs;\n                }\n            }\n            else {\n                current_arg = NULL;\n            }\n\n            if (current_arg) {\n                PyObject **p = va_arg(*p_va, PyObject **);\n                *p = current_arg;\n                Py_DECREF(current_arg);\n                format++;\n                continue;\n            }\n\n            if (i < min || i >= required_kwonly_start) {\n                if (likely(i < pos)) {\n                    assert (min == INT_MAX);\n                    assert (max == INT_MAX);\n                    skip = 1;\n                    /* At that moment we still don't know the minimal and\n                     * the maximal numbers of positional arguments.  Raising\n                     * an exception is deferred until we encounter | and $\n                     * or the end of the format. */\n                }\n                else {\n                    if (i >= max) {\n                        PyErr_Format(PyExc_TypeError,\n                                     \"%.200s%s missing required \"\n                                     \"keyword-only argument '%s'\",\n                                     (fname == NULL) ? \"function\" : fname,\n                                     (fname == NULL) ? \"\" : \"()\",\n                                     kwlist[i]);\n                    }\n                    else {\n                        PyErr_Format(PyExc_TypeError,\n                                     \"%.200s%s missing required \"\n                                     \"argument '%s' (pos %d)\",\n                                     (fname == NULL) ? \"function\" : fname,\n                                     (fname == NULL) ? \"\" : \"()\",\n                                     kwlist[i], i+1);\n                    }\n                    return 0;\n                }\n            }\n            /* current code reports success when all required args\n             * fulfilled and no keyword args left, with no further\n             * validation. XXX Maybe skip this in debug build ?\n             */\n            if (!nkwargs && !skip && !has_required_kws &&\n                !p_args && !p_kwargs)\n            {\n                return 1;\n            }\n        }\n\n        /* We are into optional args, skip through to any remaining\n         * keyword args */\n        skipitem(&format, p_va);\n    }\n\n    if (unlikely(skip)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"%.200s%s takes %s %d positional argument%s\"\n                     \" (%zd given)\",\n                     (fname == NULL) ? \"function\" : fname,\n                     (fname == NULL) ? \"\" : \"()\",\n                     (Py_MIN(pos, min) < i) ? \"at least\" : \"exactly\",\n                     Py_MIN(pos, min),\n                     Py_MIN(pos, min) == 1 ? \"\" : \"s\",\n                     nargs);\n        return 0;\n    }\n\n#ifdef DEBUG\n    if (!IS_END_OF_FORMAT(*format) &&\n        (*format != '|') && (*format != '$') && (*format != '@'))\n    {\n        PyErr_Format(PyExc_SystemError,\n            \"more argument specifiers than keyword list entries \"\n            \"(remaining format:'%s')\", format);\n        return 0;\n    }\n#endif\n\n    bound_pos_args = Py_MIN(nargs, Py_MIN(max, len));\n    if (p_args) {\n        *p_args = PyTuple_GetSlice(args, bound_pos_args, nargs);\n        if (!*p_args) {\n            return 0;\n        }\n    }\n\n    if (p_kwargs) {\n        /* This unfortunately needs to be special cased because if len is 0 then we\n         * never go through the main loop. */\n        if (unlikely(nargs > 0 && len == 0 && !p_args)) {\n            PyErr_Format(PyExc_TypeError,\n                         \"%.200s%s takes no positional arguments\",\n                         (fname == NULL) ? \"function\" : fname,\n                         (fname == NULL) ? \"\" : \"()\");\n\n            return 0;\n        }\n\n        *p_kwargs = PyDict_New();\n        if (!*p_kwargs) {\n            goto latefail;\n        }\n    }\n\n    if (nkwargs > 0) {\n        PyObject *key, *value;\n        Py_ssize_t j;\n        /* make sure there are no arguments given by name and position */\n        for (i = pos; i < bound_pos_args && i < len; i++) {\n            PyObject *current_arg;\n            if (unlikely(PyDict_GetItemStringRef(kwargs, kwlist[i], &current_arg) < 0)) {\n                goto latefail;\n            }\n            if (unlikely(current_arg != NULL)) {\n                Py_DECREF(current_arg);\n                /* arg present in tuple and in dict */\n                PyErr_Format(PyExc_TypeError,\n                             \"argument for %.200s%s given by name ('%s') \"\n                             \"and position (%d)\",\n                             (fname == NULL) ? \"function\" : fname,\n                             (fname == NULL) ? \"\" : \"()\",\n                             kwlist[i], i+1);\n                goto latefail;\n            }\n        }\n        /* make sure there are no extraneous keyword arguments */\n        j = 0;\n        while (PyDict_Next(kwargs, &j, &key, &value)) {\n            int match = 0;\n            if (unlikely(!PyUnicode_Check(key))) {\n                PyErr_SetString(PyExc_TypeError,\n                                \"keywords must be strings\");\n                goto latefail;\n            }\n            for (i = pos; i < len; i++) {\n                if (PyUnicode_EqualToUTF8(key, kwlist[i])) {\n                    match = 1;\n                    break;\n                }\n            }\n            if (!match) {\n                if (unlikely(!p_kwargs)) {\n                    PyErr_Format(PyExc_TypeError,\n                                 \"'%U' is an invalid keyword \"\n                                 \"argument for %.200s%s\",\n                                 key,\n                                 (fname == NULL) ? \"this function\" : fname,\n                                 (fname == NULL) ? \"\" : \"()\");\n                    goto latefail;\n                } else {\n                    if (PyDict_SetItem(*p_kwargs, key, value) < 0) {\n                        goto latefail;\n                    }\n                }\n            }\n        }\n    }\n\n    return 1;\n    /* Handle failures that have happened after we have tried to\n     * create *args and **kwargs, if they exist. */\nlatefail:\n    if (p_args) {\n        Py_XDECREF(*p_args);\n    }\n    if (p_kwargs) {\n        Py_XDECREF(*p_kwargs);\n    }\n    return 0;\n}\n\n\nstatic void\nskipitem(const char **p_format, va_list *p_va)\n{\n    const char *format = *p_format;\n    format++;\n\n    if (p_va != NULL) {\n        (void) va_arg(*p_va, PyObject **);\n    }\n\n    *p_format = format;\n}\n\n#ifdef __cplusplus\n};\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/getargsfast.c",
    "content": "/* getargskeywordsfast implementation copied from Python 3.9 and stripped down to\n * only include the functionality we need.\n *\n * We also add support for required kwonly args and accepting *args / **kwargs.\n *\n * DOCUMENTATION OF THE EXTENSIONS:\n *  - Arguments given after a @ format specify required keyword-only arguments.\n *    The | and $ specifiers must both appear before @.\n *  - If the first character of a format string is %, then the function can support\n *    *args and/or **kwargs. In this case the parser will consume two arguments,\n *    which should be pointers to variables to store the *args and **kwargs, respectively.\n *    Either pointer can be NULL, in which case the function doesn't take that\n *    variety of vararg.\n *    Unlike most format specifiers, the caller takes ownership of these objects\n *    and is responsible for decrefing them.\n */\n\n#include <Python.h>\n#include \"CPy.h\"\n\n#define PARSER_INITED(parser) ((parser)->kwtuple != NULL)\n\n/* Forward */\nstatic int\nvgetargskeywordsfast_impl(PyObject *const *args, Py_ssize_t nargs,\n                          PyObject *kwargs, PyObject *kwnames,\n                          CPyArg_Parser *parser,\n                          va_list *p_va);\nstatic void skipitem_fast(const char **, va_list *);\n\n/* Parse args for an arbitrary signature */\nint\nCPyArg_ParseStackAndKeywords(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,\n                             CPyArg_Parser *parser, ...)\n{\n    int retval;\n    va_list va;\n\n    va_start(va, parser);\n    retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va);\n    va_end(va);\n    return retval;\n}\n\n/* Parse args for a function that takes no args */\nint\nCPyArg_ParseStackAndKeywordsNoArgs(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,\n                                   CPyArg_Parser *parser, ...)\n{\n    int retval;\n    va_list va;\n\n    va_start(va, parser);\n    if (nargs == 0 && kwnames == NULL) {\n        // Fast path: no arguments\n        retval = 1;\n    } else {\n        retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va);\n    }\n    va_end(va);\n    return retval;\n}\n\n/* Parse args for a function that takes one arg */\nint\nCPyArg_ParseStackAndKeywordsOneArg(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,\n                                   CPyArg_Parser *parser, ...)\n{\n    int retval;\n    va_list va;\n\n    va_start(va, parser);\n    if (kwnames == NULL && nargs == 1) {\n        // Fast path: one positional argument\n        PyObject **p;\n        p = va_arg(va, PyObject **);\n        *p = args[0];\n        retval = 1;\n    } else {\n        retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va);\n    }\n    va_end(va);\n    return retval;\n}\n\n/* Parse args for a function that takes no keyword-only args, *args or **kwargs */\nint\nCPyArg_ParseStackAndKeywordsSimple(PyObject *const *args, Py_ssize_t nargs, PyObject *kwnames,\n                                   CPyArg_Parser *parser, ...)\n{\n    int retval;\n    va_list va;\n\n    va_start(va, parser);\n    if (kwnames == NULL && PARSER_INITED(parser) &&\n            nargs >= parser->min && nargs <= parser->max) {\n        // Fast path: correct number of positional arguments only\n        PyObject **p;\n        Py_ssize_t i;\n        for (i = 0; i < nargs; i++) {\n            p = va_arg(va, PyObject **);\n            *p = args[i];\n        }\n        retval = 1;\n    } else {\n        retval = vgetargskeywordsfast_impl(args, nargs, NULL, kwnames, parser, &va);\n    }\n    va_end(va);\n    return retval;\n}\n\n#define IS_END_OF_FORMAT(c) (c == '\\0' || c == ';' || c == ':')\n\n\n/* List of static parsers. */\nstatic struct CPyArg_Parser *static_arg_parsers = NULL;\n\nstatic int\nparser_init(CPyArg_Parser *parser)\n{\n    const char * const *keywords;\n    const char *format;\n    int i, len, min, max, nkw;\n    PyObject *kwtuple;\n\n    assert(parser->keywords != NULL);\n    if (PARSER_INITED(parser)) {\n        return 1;\n    }\n\n    keywords = parser->keywords;\n    /* scan keywords and count the number of positional-only parameters */\n    for (i = 0; keywords[i] && !*keywords[i]; i++) {\n    }\n    parser->pos = i;\n    /* scan keywords and get greatest possible nbr of args */\n    for (; keywords[i]; i++) {\n        if (!*keywords[i]) {\n            PyErr_SetString(PyExc_SystemError,\n                            \"Empty keyword parameter name\");\n            return 0;\n        }\n    }\n    len = i;\n\n    parser->required_kwonly_start = INT_MAX;\n    if (*parser->format == '%') {\n        parser->format++;\n        parser->varargs = 1;\n    }\n\n    format = parser->format;\n    if (format) {\n        /* grab the function name or custom error msg first (mutually exclusive) */\n        parser->fname = strchr(parser->format, ':');\n        if (parser->fname) {\n            parser->fname++;\n            parser->custom_msg = NULL;\n        }\n        else {\n            parser->custom_msg = strchr(parser->format,';');\n            if (parser->custom_msg)\n                parser->custom_msg++;\n        }\n\n        min = max = INT_MAX;\n        for (i = 0; i < len; i++) {\n            if (*format == '|') {\n                if (min != INT_MAX) {\n                    PyErr_SetString(PyExc_SystemError,\n                                    \"Invalid format string (| specified twice)\");\n                    return 0;\n                }\n                if (max != INT_MAX) {\n                    PyErr_SetString(PyExc_SystemError,\n                                    \"Invalid format string ($ before |)\");\n                    return 0;\n                }\n                min = i;\n                format++;\n            }\n            if (*format == '$') {\n                if (max != INT_MAX) {\n                    PyErr_SetString(PyExc_SystemError,\n                                    \"Invalid format string ($ specified twice)\");\n                    return 0;\n                }\n                if (i < parser->pos) {\n                    PyErr_SetString(PyExc_SystemError,\n                                    \"Empty parameter name after $\");\n                    return 0;\n                }\n                max = i;\n                format++;\n            }\n            if (*format == '@') {\n                if (parser->required_kwonly_start != INT_MAX) {\n                    PyErr_SetString(PyExc_SystemError,\n                                    \"Invalid format string (@ specified twice)\");\n                    return 0;\n                }\n                if (min == INT_MAX && max == INT_MAX) {\n                    PyErr_SetString(PyExc_SystemError,\n                                    \"Invalid format string \"\n                                    \"(@ without preceding | and $)\");\n                    return 0;\n                }\n                format++;\n                parser->has_required_kws = 1;\n                parser->required_kwonly_start = i;\n            }\n            if (IS_END_OF_FORMAT(*format)) {\n                PyErr_Format(PyExc_SystemError,\n                            \"More keyword list entries (%d) than \"\n                            \"format specifiers (%d)\", len, i);\n                return 0;\n            }\n\n            skipitem_fast(&format, NULL);\n        }\n        parser->min = Py_MIN(min, len);\n        parser->max = Py_MIN(max, len);\n\n        if (!IS_END_OF_FORMAT(*format) && (*format != '|') && (*format != '$')) {\n            PyErr_Format(PyExc_SystemError,\n                \"more argument specifiers than keyword list entries \"\n                \"(remaining format:'%s')\", format);\n            return 0;\n        }\n    }\n\n    nkw = len - parser->pos;\n    kwtuple = PyTuple_New(nkw);\n    if (kwtuple == NULL) {\n        return 0;\n    }\n    keywords = parser->keywords + parser->pos;\n    for (i = 0; i < nkw; i++) {\n        PyObject *str = PyUnicode_FromString(keywords[i]);\n        if (str == NULL) {\n            Py_DECREF(kwtuple);\n            return 0;\n        }\n        PyUnicode_InternInPlace(&str);\n        PyTuple_SET_ITEM(kwtuple, i, str);\n    }\n    parser->kwtuple = kwtuple;\n\n    assert(parser->next == NULL);\n    parser->next = static_arg_parsers;\n    static_arg_parsers = parser;\n    return 1;\n}\n\nstatic PyObject*\nfind_keyword(PyObject *kwnames, PyObject *const *kwstack, PyObject *key)\n{\n    Py_ssize_t i, nkwargs;\n\n    nkwargs = PyTuple_GET_SIZE(kwnames);\n    for (i = 0; i < nkwargs; i++) {\n        PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);\n\n        /* kwname == key will normally find a match in since keyword keys\n           should be interned strings; if not retry below in a new loop. */\n        if (kwname == key) {\n            return kwstack[i];\n        }\n    }\n\n    for (i = 0; i < nkwargs; i++) {\n        PyObject *kwname = PyTuple_GET_ITEM(kwnames, i);\n        assert(PyUnicode_Check(kwname));\n        if (PyUnicode_Equal(kwname, key)) {\n            return kwstack[i];\n        }\n    }\n    return NULL;\n}\n\nstatic int\nvgetargskeywordsfast_impl(PyObject *const *args, Py_ssize_t nargs,\n                          PyObject *kwargs, PyObject *kwnames,\n                          CPyArg_Parser *parser,\n                          va_list *p_va)\n{\n    PyObject *kwtuple;\n    const char *format;\n    PyObject *keyword;\n    int i, pos, len;\n    Py_ssize_t nkwargs;\n    PyObject *current_arg;\n    PyObject *const *kwstack = NULL;\n    int bound_pos_args;\n    PyObject **p_args = NULL, **p_kwargs = NULL;\n\n    assert(kwargs == NULL || PyDict_Check(kwargs));\n    assert(kwargs == NULL || kwnames == NULL);\n    assert(p_va != NULL);\n\n    if (!parser_init(parser)) {\n        return 0;\n    }\n\n    kwtuple = parser->kwtuple;\n    pos = parser->pos;\n    len = pos + (int)PyTuple_GET_SIZE(kwtuple);\n\n    if (parser->varargs) {\n        p_args = va_arg(*p_va, PyObject **);\n        p_kwargs = va_arg(*p_va, PyObject **);\n    }\n\n    if (kwargs != NULL) {\n        nkwargs = PyDict_GET_SIZE(kwargs);\n    }\n    else if (kwnames != NULL) {\n        nkwargs = PyTuple_GET_SIZE(kwnames);\n        kwstack = args + nargs;\n    }\n    else {\n        nkwargs = 0;\n    }\n    if (nargs + nkwargs > len && !p_args && !p_kwargs) {\n        /* Adding \"keyword\" (when nargs == 0) prevents producing wrong error\n           messages in some special cases (see bpo-31229). */\n        PyErr_Format(PyExc_TypeError,\n                     \"%.200s%s takes at most %d %sargument%s (%zd given)\",\n                     (parser->fname == NULL) ? \"function\" : parser->fname,\n                     (parser->fname == NULL) ? \"\" : \"()\",\n                     len,\n                     (nargs == 0) ? \"keyword \" : \"\",\n                     (len == 1) ? \"\" : \"s\",\n                     nargs + nkwargs);\n        return 0;\n    }\n    if (parser->max < nargs && !p_args) {\n        if (parser->max == 0) {\n            PyErr_Format(PyExc_TypeError,\n                         \"%.200s%s takes no positional arguments\",\n                         (parser->fname == NULL) ? \"function\" : parser->fname,\n                         (parser->fname == NULL) ? \"\" : \"()\");\n        }\n        else {\n            PyErr_Format(PyExc_TypeError,\n                         \"%.200s%s takes %s %d positional argument%s (%zd given)\",\n                         (parser->fname == NULL) ? \"function\" : parser->fname,\n                         (parser->fname == NULL) ? \"\" : \"()\",\n                         (parser->min < parser->max) ? \"at most\" : \"exactly\",\n                         parser->max,\n                         parser->max == 1 ? \"\" : \"s\",\n                         nargs);\n        }\n        return 0;\n    }\n\n    format = parser->format;\n\n    /* convert tuple args and keyword args in same loop, using kwtuple to drive process */\n    for (i = 0; i < len; i++) {\n        if (*format == '|') {\n            format++;\n        }\n        if (*format == '$') {\n            format++;\n        }\n        if (*format == '@') {\n            format++;\n        }\n        assert(!IS_END_OF_FORMAT(*format));\n\n        if (i < nargs && i < parser->max) {\n            current_arg = args[i];\n        }\n        else if (nkwargs && i >= pos) {\n            keyword = PyTuple_GET_ITEM(kwtuple, i - pos);\n            if (kwargs != NULL) {\n                current_arg = PyDict_GetItemWithError(kwargs, keyword);\n                if (!current_arg && PyErr_Occurred()) {\n                    return 0;\n                }\n            }\n            else {\n                current_arg = find_keyword(kwnames, kwstack, keyword);\n            }\n            if (current_arg) {\n                --nkwargs;\n            }\n        }\n        else {\n            current_arg = NULL;\n        }\n\n        if (current_arg) {\n            PyObject **p = va_arg(*p_va, PyObject **);\n            *p = current_arg;\n            format++;\n            continue;\n        }\n\n        if (i < parser->min || i >= parser->required_kwonly_start) {\n            /* Less arguments than required */\n            if (i < pos) {\n                Py_ssize_t min = Py_MIN(pos, parser->min);\n                PyErr_Format(PyExc_TypeError,\n                             \"%.200s%s takes %s %d positional argument%s\"\n                             \" (%zd given)\",\n                             (parser->fname == NULL) ? \"function\" : parser->fname,\n                             (parser->fname == NULL) ? \"\" : \"()\",\n                             min < parser->max ? \"at least\" : \"exactly\",\n                             min,\n                             min == 1 ? \"\" : \"s\",\n                             nargs);\n            }\n            else {\n                keyword = PyTuple_GET_ITEM(kwtuple, i - pos);\n                if (i >= parser->max) {\n                    PyErr_Format(PyExc_TypeError,  \"%.200s%s missing required \"\n                                 \"keyword-only argument '%U'\",\n                                 (parser->fname == NULL) ? \"function\" : parser->fname,\n                                 (parser->fname == NULL) ? \"\" : \"()\",\n                                 keyword);\n                }\n                else {\n                    PyErr_Format(PyExc_TypeError,  \"%.200s%s missing required \"\n                                 \"argument '%U' (pos %d)\",\n                                 (parser->fname == NULL) ? \"function\" : parser->fname,\n                                 (parser->fname == NULL) ? \"\" : \"()\",\n                                 keyword, i+1);\n                }\n            }\n            return 0;\n        }\n        /* current code reports success when all required args\n         * fulfilled and no keyword args left, with no further\n         * validation. XXX Maybe skip this in debug build ?\n         */\n        if (!nkwargs && !parser->has_required_kws && !p_args && !p_kwargs) {\n            return 1;\n        }\n\n        /* We are into optional args, skip through to any remaining\n         * keyword args */\n        skipitem_fast(&format, p_va);\n    }\n\n    assert(IS_END_OF_FORMAT(*format) || (*format == '|') || (*format == '$'));\n\n    bound_pos_args = Py_MIN(nargs, Py_MIN(parser->max, len));\n    if (p_args) {\n        *p_args = PyTuple_New(nargs - bound_pos_args);\n        if (!*p_args) {\n            return 0;\n        }\n        for (i = bound_pos_args; i < nargs; i++) {\n            PyObject *arg = args[i];\n            Py_INCREF(arg);\n            PyTuple_SET_ITEM(*p_args, i - bound_pos_args, arg);\n        }\n    }\n\n    if (p_kwargs) {\n        /* This unfortunately needs to be special cased because if len is 0 then we\n         * never go through the main loop. */\n        if (nargs > 0 && len == 0 && !p_args) {\n            PyErr_Format(PyExc_TypeError,\n                         \"%.200s%s takes no positional arguments\",\n                         (parser->fname == NULL) ? \"function\" : parser->fname,\n                         (parser->fname == NULL) ? \"\" : \"()\");\n\n            return 0;\n        }\n\n        *p_kwargs = PyDict_New();\n        if (!*p_kwargs) {\n            goto latefail;\n        }\n    }\n\n    if (nkwargs > 0) {\n        Py_ssize_t j;\n        PyObject *value;\n        /* make sure there are no arguments given by name and position */\n        for (i = pos; i < bound_pos_args; i++) {\n            keyword = PyTuple_GET_ITEM(kwtuple, i - pos);\n            if (kwargs != NULL) {\n                current_arg = PyDict_GetItemWithError(kwargs, keyword);\n                if (!current_arg && PyErr_Occurred()) {\n                    goto latefail;\n                }\n            }\n            else {\n                current_arg = find_keyword(kwnames, kwstack, keyword);\n            }\n            if (current_arg) {\n                /* arg present in tuple and in dict */\n                PyErr_Format(PyExc_TypeError,\n                             \"argument for %.200s%s given by name ('%U') \"\n                             \"and position (%d)\",\n                             (parser->fname == NULL) ? \"function\" : parser->fname,\n                             (parser->fname == NULL) ? \"\" : \"()\",\n                             keyword, i+1);\n                goto latefail;\n            }\n        }\n        /* make sure there are no extraneous keyword arguments */\n        j = 0;\n        while (1) {\n            int match;\n            if (kwargs != NULL) {\n                if (!PyDict_Next(kwargs, &j, &keyword, &value))\n                    break;\n            }\n            else {\n                if (j >= PyTuple_GET_SIZE(kwnames))\n                    break;\n                keyword = PyTuple_GET_ITEM(kwnames, j);\n                value = kwstack[j];\n                j++;\n            }\n\n            match = PySequence_Contains(kwtuple, keyword);\n            if (match <= 0) {\n                if (!match) {\n                    if (!p_kwargs) {\n                        PyErr_Format(PyExc_TypeError,\n                                     \"'%S' is an invalid keyword \"\n                                     \"argument for %.200s%s\",\n                                     keyword,\n                                     (parser->fname == NULL) ? \"this function\" : parser->fname,\n                                     (parser->fname == NULL) ? \"\" : \"()\");\n                        goto latefail;\n                    } else {\n                        if (PyDict_SetItem(*p_kwargs, keyword, value) < 0) {\n                            goto latefail;\n                        }\n                    }\n                } else {\n                    goto latefail;\n                }\n            }\n        }\n    }\n\n    return 1;\n    /* Handle failures that have happened after we have tried to\n     * create *args and **kwargs, if they exist. */\nlatefail:\n    if (p_args) {\n        Py_XDECREF(*p_args);\n    }\n    if (p_kwargs) {\n        Py_XDECREF(*p_kwargs);\n    }\n    return 0;\n}\n\nstatic void\nskipitem_fast(const char **p_format, va_list *p_va)\n{\n    const char *format = *p_format;\n    char c = *format++;\n\n    if (p_va != NULL) {\n        (void) va_arg(*p_va, PyObject **);\n    }\n\n    *p_format = format;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/init.c",
    "content": "#include <Python.h>\n#include \"CPy.h\"\n#include \"static_data.c\"\n\nstruct ExcDummyStruct _CPy_ExcDummyStruct = { PyObject_HEAD_INIT(NULL) };\nPyObject *_CPy_ExcDummy = (PyObject *)&_CPy_ExcDummyStruct;\n\n// System-wide empty tuple constant\nPyObject * __mypyc_empty_tuple__ = NULL;\n\n// Because its dynamic linker is more restricted than linux/OS X,\n// Windows doesn't allow initializing globals with values from\n// other dynamic libraries. This means we need to initialize\n// things at load time.\nvoid CPy_Init(void) {\n    _CPy_ExcDummyStruct.ob_base.ob_type = &PyBaseObject_Type;\n\n    // Initialize system-wide empty tuple constant\n    if (__mypyc_empty_tuple__ == NULL) {\n        __mypyc_empty_tuple__ = PyTuple_New(0);\n        if (!__mypyc_empty_tuple__) {\n            CPyError_OutOfMemory();\n        }\n    }\n}\n"
  },
  {
    "path": "mypyc/lib-rt/int_ops.c",
    "content": "// Int primitive operations (tagged arbitrary-precision integers)\n//\n// These are registered in mypyc.primitives.int_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\n\n#ifdef _MSC_VER\n#include <intrin.h>\n#endif\n\n#ifndef _WIN32\n// On 64-bit Linux and macOS, ssize_t and long are both 64 bits, and\n// PyLong_FromLong is faster than PyLong_FromSsize_t, so use the faster one\n#define CPyLong_FromSsize_t PyLong_FromLong\n#else\n// On 64-bit Windows, ssize_t is 64 bits but long is 32 bits, so we\n// can't use the above trick\n#define CPyLong_FromSsize_t PyLong_FromSsize_t\n#endif\n\n#if defined(__GNUC__) || defined(__clang__)\n#  if defined(__x86_64__) || defined(_M_X64) || defined(__aarch64__) || (defined(__SIZEOF_POINTER__) && __SIZEOF_POINTER__ == 8)\n#    define CPY_CLZ(x) __builtin_clzll((unsigned long long)(x))\n#    define CPY_BITS 64\n#  else\n#    define CPY_CLZ(x) __builtin_clz((unsigned int)(x))\n#    define CPY_BITS 32\n#  endif\n#endif\n\n\nCPyTagged CPyTagged_FromSsize_t(Py_ssize_t value) {\n    // We use a Python object if the value shifted left by 1 is too\n    // large for Py_ssize_t\n    if (unlikely(CPyTagged_TooBig(value))) {\n        PyObject *object = PyLong_FromSsize_t(value);\n        return ((CPyTagged)object) | CPY_INT_TAG;\n    } else {\n        return value << 1;\n    }\n}\n\nCPyTagged CPyTagged_FromVoidPtr(void *ptr) {\n    if ((uintptr_t)ptr > PY_SSIZE_T_MAX) {\n        PyObject *object = PyLong_FromVoidPtr(ptr);\n        return ((CPyTagged)object) | CPY_INT_TAG;\n    } else {\n        return CPyTagged_FromSsize_t((Py_ssize_t)ptr);\n    }\n}\n\nCPyTagged CPyTagged_FromInt64(int64_t value) {\n    if (unlikely(CPyTagged_TooBigInt64(value))) {\n        PyObject *object = PyLong_FromLongLong(value);\n        return ((CPyTagged)object) | CPY_INT_TAG;\n    } else {\n        return value << 1;\n    }\n}\n\nPyObject *CPyTagged_AsObject(CPyTagged x) {\n    PyObject *value;\n    if (unlikely(CPyTagged_CheckLong(x))) {\n        value = CPyTagged_LongAsObject(x);\n        Py_INCREF(value);\n    } else {\n        value = CPyLong_FromSsize_t(CPyTagged_ShortAsSsize_t(x));\n        if (value == NULL) {\n            CPyError_OutOfMemory();\n        }\n    }\n    return value;\n}\n\nPyObject *CPyTagged_StealAsObject(CPyTagged x) {\n    PyObject *value;\n    if (unlikely(CPyTagged_CheckLong(x))) {\n        value = CPyTagged_LongAsObject(x);\n    } else {\n        value = CPyLong_FromSsize_t(CPyTagged_ShortAsSsize_t(x));\n        if (value == NULL) {\n            CPyError_OutOfMemory();\n        }\n    }\n    return value;\n}\n\nPy_ssize_t CPyTagged_AsSsize_t(CPyTagged x) {\n    if (likely(CPyTagged_CheckShort(x))) {\n        return CPyTagged_ShortAsSsize_t(x);\n    } else {\n        return PyLong_AsSsize_t(CPyTagged_LongAsObject(x));\n    }\n}\n\nCPy_NOINLINE\nvoid CPyTagged_IncRef(CPyTagged x) {\n    if (unlikely(CPyTagged_CheckLong(x))) {\n        Py_INCREF(CPyTagged_LongAsObject(x));\n    }\n}\n\nCPy_NOINLINE\nvoid CPyTagged_DecRef(CPyTagged x) {\n    if (unlikely(CPyTagged_CheckLong(x))) {\n        Py_DECREF(CPyTagged_LongAsObject(x));\n    }\n}\n\nCPy_NOINLINE\nvoid CPyTagged_XDecRef(CPyTagged x) {\n    if (unlikely(CPyTagged_CheckLong(x))) {\n        Py_XDECREF(CPyTagged_LongAsObject(x));\n    }\n}\n\n// Tagged int negation slow path, where the result may be a long integer\nCPyTagged CPyTagged_Negate_(CPyTagged num) {\n    PyObject *num_obj = CPyTagged_AsObject(num);\n    PyObject *result = PyNumber_Negative(num_obj);\n    if (result == NULL) {\n        CPyError_OutOfMemory();\n    }\n    Py_DECREF(num_obj);\n    return CPyTagged_StealFromObject(result);\n}\n\n// Tagged int addition slow path, where the result may be a long integer\nCPyTagged CPyTagged_Add_(CPyTagged left, CPyTagged right) {\n    PyObject *left_obj = CPyTagged_AsObject(left);\n    PyObject *right_obj = CPyTagged_AsObject(right);\n    PyObject *result = PyNumber_Add(left_obj, right_obj);\n    if (result == NULL) {\n        CPyError_OutOfMemory();\n    }\n    Py_DECREF(left_obj);\n    Py_DECREF(right_obj);\n    return CPyTagged_StealFromObject(result);\n}\n\n// Tagged int subtraction slow path, where the result may be a long integer\nCPyTagged CPyTagged_Subtract_(CPyTagged left, CPyTagged right) {\n    PyObject *left_obj = CPyTagged_AsObject(left);\n    PyObject *right_obj = CPyTagged_AsObject(right);\n    PyObject *result = PyNumber_Subtract(left_obj, right_obj);\n    if (result == NULL) {\n        CPyError_OutOfMemory();\n    }\n    Py_DECREF(left_obj);\n    Py_DECREF(right_obj);\n    return CPyTagged_StealFromObject(result);\n}\n\n// Tagged int multiplication slow path, where the result may be a long integer\nCPyTagged CPyTagged_Multiply_(CPyTagged left, CPyTagged right) {\n    PyObject *left_obj = CPyTagged_AsObject(left);\n    PyObject *right_obj = CPyTagged_AsObject(right);\n    PyObject *result = PyNumber_Multiply(left_obj, right_obj);\n    if (result == NULL) {\n        CPyError_OutOfMemory();\n    }\n    Py_DECREF(left_obj);\n    Py_DECREF(right_obj);\n    return CPyTagged_StealFromObject(result);\n}\n\n// Tagged int // slow path, where the result may be a long integer (or raise)\nCPyTagged CPyTagged_FloorDivide_(CPyTagged left, CPyTagged right) {\n    PyObject *left_obj = CPyTagged_AsObject(left);\n    PyObject *right_obj = CPyTagged_AsObject(right);\n    PyObject *result = PyNumber_FloorDivide(left_obj, right_obj);\n    Py_DECREF(left_obj);\n    Py_DECREF(right_obj);\n    // Handle exceptions honestly because it could be ZeroDivisionError\n    if (result == NULL) {\n        return CPY_INT_TAG;\n    } else {\n        return CPyTagged_StealFromObject(result);\n    }\n}\n\n// Tagged int % slow path, where the result may be a long integer (or raise)\nCPyTagged CPyTagged_Remainder_(CPyTagged left, CPyTagged right) {\n    PyObject *left_obj = CPyTagged_AsObject(left);\n    PyObject *right_obj = CPyTagged_AsObject(right);\n    PyObject *result = PyNumber_Remainder(left_obj, right_obj);\n    Py_DECREF(left_obj);\n    Py_DECREF(right_obj);\n    // Handle exceptions honestly because it could be ZeroDivisionError\n    if (result == NULL) {\n        return CPY_INT_TAG;\n    } else {\n        return CPyTagged_StealFromObject(result);\n    }\n}\n\nbool CPyTagged_IsEq_(CPyTagged left, CPyTagged right) {\n    if (CPyTagged_CheckShort(right)) {\n        return false;\n    } else {\n        PyObject *left_obj = CPyTagged_AsObject(left);\n        PyObject *right_obj = CPyTagged_AsObject(right);\n        int result = PyObject_RichCompareBool(left_obj, right_obj, Py_EQ);\n        Py_DECREF(left_obj);\n        Py_DECREF(right_obj);\n        if (result == -1) {\n            CPyError_OutOfMemory();\n        }\n        return result;\n    }\n}\n\nbool CPyTagged_IsLt_(CPyTagged left, CPyTagged right) {\n    PyObject *left_obj = CPyTagged_AsObject(left);\n    PyObject *right_obj = CPyTagged_AsObject(right);\n    int result = PyObject_RichCompareBool(left_obj, right_obj, Py_LT);\n    Py_DECREF(left_obj);\n    Py_DECREF(right_obj);\n    if (result == -1) {\n        CPyError_OutOfMemory();\n    }\n    return result;\n}\n\nPyObject *CPyLong_FromStrWithBase(PyObject *o, CPyTagged base) {\n    Py_ssize_t base_size_t = CPyTagged_AsSsize_t(base);\n    return PyLong_FromUnicodeObject(o, base_size_t);\n}\n\nPyObject *CPyLong_FromStr(PyObject *o) {\n    CPyTagged base = CPyTagged_FromSsize_t(10);\n    return CPyLong_FromStrWithBase(o, base);\n}\n\nCPyTagged CPyTagged_FromFloat(double f) {\n    if (f < ((double)CPY_TAGGED_MAX + 1.0) && f > (CPY_TAGGED_MIN - 1.0)) {\n        return (Py_ssize_t)f << 1;\n    }\n    PyObject *o = PyLong_FromDouble(f);\n    if (o == NULL)\n        return CPY_INT_TAG;\n    return CPyTagged_StealFromObject(o);\n}\n\nPyObject *CPyBool_Str(bool b) {\n    return PyObject_Str(b ? Py_True : Py_False);\n}\n\n// Bitwise op '&', '|' or '^' using the generic (slow) API\nstatic CPyTagged GenericBitwiseOp(CPyTagged a, CPyTagged b, char op) {\n    PyObject *aobj = CPyTagged_AsObject(a);\n    PyObject *bobj = CPyTagged_AsObject(b);\n    PyObject *r;\n    if (op == '&') {\n        r = PyNumber_And(aobj, bobj);\n    } else if (op == '|') {\n        r = PyNumber_Or(aobj, bobj);\n    } else {\n        r = PyNumber_Xor(aobj, bobj);\n    }\n    if (unlikely(r == NULL)) {\n        CPyError_OutOfMemory();\n    }\n    Py_DECREF(aobj);\n    Py_DECREF(bobj);\n    return CPyTagged_StealFromObject(r);\n}\n\n// Return pointer to digits of a PyLong object. If it's a short\n// integer, place digits in the buffer buf instead to avoid memory\n// allocation (it's assumed to be big enough). Return the number of\n// digits in *size. *size is negative if the integer is negative.\nstatic digit *GetIntDigits(CPyTagged n, Py_ssize_t *size, digit *buf) {\n    if (CPyTagged_CheckShort(n)) {\n        Py_ssize_t val = CPyTagged_ShortAsSsize_t(n);\n        bool neg = val < 0;\n        int len = 1;\n        if (neg) {\n            val = -val;\n        }\n        buf[0] = val & PyLong_MASK;\n        if (val > (Py_ssize_t)PyLong_MASK) {\n            val >>= PyLong_SHIFT;\n            buf[1] = val & PyLong_MASK;\n            if (val > (Py_ssize_t)PyLong_MASK) {\n                buf[2] = val >> PyLong_SHIFT;\n                len = 3;\n            } else {\n                len = 2;\n            }\n        }\n        *size = neg ? -len : len;\n        return buf;\n    } else {\n        PyLongObject *obj = (PyLongObject *)CPyTagged_LongAsObject(n);\n        *size = CPY_LONG_SIZE_SIGNED(obj);\n        return &CPY_LONG_DIGIT(obj, 0);\n    }\n}\n\n// Shared implementation of bitwise '&', '|' and '^' (specified by op) for at least\n// one long operand. This is somewhat optimized for performance.\nCPyTagged CPyTagged_BitwiseLongOp_(CPyTagged a, CPyTagged b, char op) {\n    // Directly access the digits, as there is no fast C API function for this.\n    digit abuf[3];\n    digit bbuf[3];\n    Py_ssize_t asize;\n    Py_ssize_t bsize;\n    digit *adigits = GetIntDigits(a, &asize, abuf);\n    digit *bdigits = GetIntDigits(b, &bsize, bbuf);\n\n    if (unlikely(asize < 0 || bsize < 0)) {\n        // Negative operand. This is slower, but bitwise ops on them are pretty rare.\n        return GenericBitwiseOp(a, b, op);\n    }\n    // Optimized implementation for two non-negative integers.\n    // Swap a and b as needed to ensure a is no longer than b.\n    if (asize > bsize) {\n        digit *tmp = adigits;\n        adigits = bdigits;\n        bdigits = tmp;\n        Py_ssize_t tmp_size = asize;\n        asize = bsize;\n        bsize = tmp_size;\n    }\n    void *digits = NULL;\n    PyLongWriter *writer = PyLongWriter_Create(0, op == '&' ? asize : bsize, &digits);\n    if (unlikely(writer == NULL)) {\n        CPyError_OutOfMemory();\n    }\n    Py_ssize_t i;\n    if (op == '&') {\n        for (i = 0; i < asize; i++) {\n            ((digit *)digits)[i] = adigits[i] & bdigits[i];\n        }\n    } else {\n        if (op == '|') {\n            for (i = 0; i < asize; i++) {\n                ((digit *)digits)[i] = adigits[i] | bdigits[i];\n            }\n        } else {\n            for (i = 0; i < asize; i++) {\n                ((digit *)digits)[i] = adigits[i] ^ bdigits[i];\n            }\n        }\n        for (; i < bsize; i++) {\n            ((digit *)digits)[i] = bdigits[i];\n        }\n    }\n    return CPyTagged_StealFromObject(PyLongWriter_Finish(writer));\n}\n\n// Bitwise '~' slow path\nCPyTagged CPyTagged_Invert_(CPyTagged num) {\n    PyObject *obj = CPyTagged_AsObject(num);\n    PyObject *result = PyNumber_Invert(obj);\n    if (unlikely(result == NULL)) {\n        CPyError_OutOfMemory();\n    }\n    Py_DECREF(obj);\n    return CPyTagged_StealFromObject(result);\n}\n\n// Bitwise '>>' slow path\nCPyTagged CPyTagged_Rshift_(CPyTagged left, CPyTagged right) {\n    // Long integer or negative shift -- use generic op\n    PyObject *lobj = CPyTagged_AsObject(left);\n    PyObject *robj = CPyTagged_AsObject(right);\n    PyObject *result = PyNumber_Rshift(lobj, robj);\n    Py_DECREF(lobj);\n    Py_DECREF(robj);\n    if (result == NULL) {\n        // Propagate error (could be negative shift count)\n        return CPY_INT_TAG;\n    }\n    return CPyTagged_StealFromObject(result);\n}\n\n// Bitwise '<<' slow path\nCPyTagged CPyTagged_Lshift_(CPyTagged left, CPyTagged right) {\n    // Long integer or out of range shift -- use generic op\n    PyObject *lobj = CPyTagged_AsObject(left);\n    PyObject *robj = CPyTagged_AsObject(right);\n    PyObject *result = PyNumber_Lshift(lobj, robj);\n    Py_DECREF(lobj);\n    Py_DECREF(robj);\n    if (result == NULL) {\n        // Propagate error (could be negative shift count)\n        return CPY_INT_TAG;\n    }\n    return CPyTagged_StealFromObject(result);\n}\n\n// i64 unboxing slow path\nint64_t CPyLong_AsInt64_(PyObject *o) {\n    int overflow;\n    int64_t result = PyLong_AsLongLongAndOverflow(o, &overflow);\n    if (result == -1) {\n        if (PyErr_Occurred()) {\n            return CPY_LL_INT_ERROR;\n        } else if (overflow) {\n            PyErr_SetString(PyExc_ValueError, \"int too large to convert to i64\");\n            return CPY_LL_INT_ERROR;\n        }\n    }\n    return result;\n}\n\nint64_t CPyInt64_Divide(int64_t x, int64_t y) {\n    if (y == 0) {\n        PyErr_SetString(PyExc_ZeroDivisionError, \"integer division or modulo by zero\");\n        return CPY_LL_INT_ERROR;\n    }\n    if (y == -1 && x == INT64_MIN) {\n        PyErr_SetString(PyExc_OverflowError, \"integer division overflow\");\n        return CPY_LL_INT_ERROR;\n    }\n    int64_t d = x / y;\n    // Adjust for Python semantics\n    if (((x < 0) != (y < 0)) && d * y != x) {\n        d--;\n    }\n    return d;\n}\n\nint64_t CPyInt64_Remainder(int64_t x, int64_t y) {\n    if (y == 0) {\n        PyErr_SetString(PyExc_ZeroDivisionError, \"integer division or modulo by zero\");\n        return CPY_LL_INT_ERROR;\n    }\n    // Edge case: avoid core dump\n    if (y == -1 && x == INT64_MIN) {\n        return 0;\n    }\n    int64_t d = x % y;\n    // Adjust for Python semantics\n    if (((x < 0) != (y < 0)) && d != 0) {\n        d += y;\n    }\n    return d;\n}\n\n// i32 unboxing slow path\nint32_t CPyLong_AsInt32_(PyObject *o) {\n    int overflow;\n    long result = PyLong_AsLongAndOverflow(o, &overflow);\n    if (result > 0x7fffffffLL || result < -0x80000000LL) {\n        overflow = 1;\n        result = -1;\n    }\n    if (result == -1) {\n        if (PyErr_Occurred()) {\n            return CPY_LL_INT_ERROR;\n        } else if (overflow) {\n            PyErr_SetString(PyExc_ValueError, \"int too large to convert to i32\");\n            return CPY_LL_INT_ERROR;\n        }\n    }\n    return result;\n}\n\nint32_t CPyInt32_Divide(int32_t x, int32_t y) {\n    if (y == 0) {\n        PyErr_SetString(PyExc_ZeroDivisionError, \"integer division or modulo by zero\");\n        return CPY_LL_INT_ERROR;\n    }\n    if (y == -1 && x == INT32_MIN) {\n        PyErr_SetString(PyExc_OverflowError, \"integer division overflow\");\n        return CPY_LL_INT_ERROR;\n    }\n    int32_t d = x / y;\n    // Adjust for Python semantics\n    if (((x < 0) != (y < 0)) && d * y != x) {\n        d--;\n    }\n    return d;\n}\n\nint32_t CPyInt32_Remainder(int32_t x, int32_t y) {\n    if (y == 0) {\n        PyErr_SetString(PyExc_ZeroDivisionError, \"integer division or modulo by zero\");\n        return CPY_LL_INT_ERROR;\n    }\n    // Edge case: avoid core dump\n    if (y == -1 && x == INT32_MIN) {\n        return 0;\n    }\n    int32_t d = x % y;\n    // Adjust for Python semantics\n    if (((x < 0) != (y < 0)) && d != 0) {\n        d += y;\n    }\n    return d;\n}\n\nvoid CPyInt32_Overflow() {\n    PyErr_SetString(PyExc_ValueError, \"int too large to convert to i32\");\n}\n\n// i16 unboxing slow path\nint16_t CPyLong_AsInt16_(PyObject *o) {\n    int overflow;\n    long result = PyLong_AsLongAndOverflow(o, &overflow);\n    if (result > 0x7fff || result < -0x8000) {\n        overflow = 1;\n        result = -1;\n    }\n    if (result == -1) {\n        if (PyErr_Occurred()) {\n            return CPY_LL_INT_ERROR;\n        } else if (overflow) {\n            PyErr_SetString(PyExc_ValueError, \"int too large to convert to i16\");\n            return CPY_LL_INT_ERROR;\n        }\n    }\n    return result;\n}\n\nint16_t CPyInt16_Divide(int16_t x, int16_t y) {\n    if (y == 0) {\n        PyErr_SetString(PyExc_ZeroDivisionError, \"integer division or modulo by zero\");\n        return CPY_LL_INT_ERROR;\n    }\n    if (y == -1 && x == INT16_MIN) {\n        PyErr_SetString(PyExc_OverflowError, \"integer division overflow\");\n        return CPY_LL_INT_ERROR;\n    }\n    int16_t d = x / y;\n    // Adjust for Python semantics\n    if (((x < 0) != (y < 0)) && d * y != x) {\n        d--;\n    }\n    return d;\n}\n\nint16_t CPyInt16_Remainder(int16_t x, int16_t y) {\n    if (y == 0) {\n        PyErr_SetString(PyExc_ZeroDivisionError, \"integer division or modulo by zero\");\n        return CPY_LL_INT_ERROR;\n    }\n    // Edge case: avoid core dump\n    if (y == -1 && x == INT16_MIN) {\n        return 0;\n    }\n    int16_t d = x % y;\n    // Adjust for Python semantics\n    if (((x < 0) != (y < 0)) && d != 0) {\n        d += y;\n    }\n    return d;\n}\n\nvoid CPyInt16_Overflow() {\n    PyErr_SetString(PyExc_ValueError, \"int too large to convert to i16\");\n}\n\n// u8 unboxing slow path\nuint8_t CPyLong_AsUInt8_(PyObject *o) {\n    int overflow;\n    long result = PyLong_AsLongAndOverflow(o, &overflow);\n    if (result < 0 || result >= 256) {\n        overflow = 1;\n        result = -1;\n    }\n    if (result == -1) {\n        if (PyErr_Occurred()) {\n            return CPY_LL_UINT_ERROR;\n        } else if (overflow) {\n            PyErr_SetString(PyExc_ValueError, \"int too large or small to convert to u8\");\n            return CPY_LL_UINT_ERROR;\n        }\n    }\n    return result;\n}\n\nvoid CPyUInt8_Overflow() {\n    PyErr_SetString(PyExc_ValueError, \"int too large or small to convert to u8\");\n}\n\ndouble CPyTagged_TrueDivide(CPyTagged x, CPyTagged y) {\n    if (unlikely(y == 0)) {\n        PyErr_SetString(PyExc_ZeroDivisionError, \"division by zero\");\n        return CPY_FLOAT_ERROR;\n    }\n    if (likely(!CPyTagged_CheckLong(x) && !CPyTagged_CheckLong(y))) {\n        return (double)((Py_ssize_t)x >> 1) / (double)((Py_ssize_t)y >> 1);\n    } else {\n        PyObject *xo = CPyTagged_AsObject(x);\n        PyObject *yo = CPyTagged_AsObject(y);\n        PyObject *result = PyNumber_TrueDivide(xo, yo);\n        if (result == NULL) {\n            return CPY_FLOAT_ERROR;\n        }\n        return PyFloat_AsDouble(result);\n    }\n    return 1.0;\n}\n\nstatic PyObject *CPyLong_ToBytes(PyObject *v, Py_ssize_t length, int little_endian, int signed_flag) {\n    // This is a wrapper for PyLong_AsByteArray and PyBytes_FromStringAndSize\n    PyObject *result = PyBytes_FromStringAndSize(NULL, length);\n    if (!result) {\n        return NULL;\n    }\n    unsigned char *bytes = (unsigned char *)PyBytes_AS_STRING(result);\n#if PY_VERSION_HEX >= 0x030D0000  // 3.13.0\n    int res = _PyLong_AsByteArray((PyLongObject *)v, bytes, length, little_endian, signed_flag, 1);\n#else\n    int res = _PyLong_AsByteArray((PyLongObject *)v, bytes, length, little_endian, signed_flag);\n#endif\n    if (res < 0) {\n        Py_DECREF(result);\n        return NULL;\n    }\n    return result;\n}\n\n// int.to_bytes(length, byteorder, signed=False)\nPyObject *CPyTagged_ToBytes(CPyTagged self, Py_ssize_t length, PyObject *byteorder, int signed_flag) {\n    PyObject *pyint = CPyTagged_AsObject(self);\n    if (!PyUnicode_Check(byteorder)) {\n        Py_DECREF(pyint);\n        PyErr_SetString(PyExc_TypeError, \"byteorder must be str\");\n        return NULL;\n    }\n    const char *order = PyUnicode_AsUTF8(byteorder);\n    if (!order) {\n        Py_DECREF(pyint);\n        return NULL;\n    }\n    int little_endian;\n    if (strcmp(order, \"big\") == 0) {\n        little_endian = 0;\n    } else if (strcmp(order, \"little\") == 0) {\n        little_endian = 1;\n    } else {\n        PyErr_SetString(PyExc_ValueError, \"byteorder must be either 'little' or 'big'\");\n        return NULL;\n    }\n    PyObject *result = CPyLong_ToBytes(pyint, length, little_endian, signed_flag);\n    Py_DECREF(pyint);\n    return result;\n}\n\n// int.to_bytes(length, byteorder=\"little\", signed=False)\nPyObject *CPyTagged_ToLittleEndianBytes(CPyTagged self, Py_ssize_t length, int signed_flag) {\n    PyObject *pyint = CPyTagged_AsObject(self);\n    PyObject *result = CPyLong_ToBytes(pyint, length, 1, signed_flag);\n    Py_DECREF(pyint);\n    return result;\n}\n\n// int.to_bytes(length, \"big\", signed=False)\nPyObject *CPyTagged_ToBigEndianBytes(CPyTagged self, Py_ssize_t length, int signed_flag) {\n    PyObject *pyint = CPyTagged_AsObject(self);\n    PyObject *result = CPyLong_ToBytes(pyint, length, 0, signed_flag);\n    Py_DECREF(pyint);\n    return result;\n}\n\n// int.bit_length()\nCPyTagged CPyTagged_BitLength(CPyTagged self) {\n    // Handle zero\n    if (self == 0) {\n        return 0;\n    }\n\n    // Fast path for small (tagged) ints\n    if (CPyTagged_CheckShort(self)) {\n        Py_ssize_t val = CPyTagged_ShortAsSsize_t(self);\n        Py_ssize_t absval = val < 0 ? -val : val;\n        int bits = 0;\n        if (absval) {\n#if defined(_MSC_VER)\n    #if defined(_WIN64)\n            unsigned long idx;\n            if (_BitScanReverse64(&idx, (unsigned __int64)absval)) {\n                bits = (int)(idx + 1);\n            }\n    #else\n            unsigned long idx;\n            if (_BitScanReverse(&idx, (unsigned long)absval)) {\n                bits = (int)(idx + 1);\n            }\n    #endif\n#elif defined(__GNUC__) || defined(__clang__)\n            bits = (int)(CPY_BITS - CPY_CLZ(absval));\n#else\n            // Fallback to loop if no builtin\n            while (absval) {\n                absval >>= 1;\n                bits++;\n            }\n#endif\n        }\n        return bits << 1;\n    }\n\n    // Slow path for big ints\n    PyObject *pyint = CPyTagged_AsObject(self);\n    int bits = _PyLong_NumBits(pyint);\n    Py_DECREF(pyint);\n    if (bits < 0) {\n        // _PyLong_NumBits sets an error on failure\n        return CPY_INT_TAG;\n    }\n    return bits << 1;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/internal/librt_internal.c",
    "content": "#include \"pythoncapi_compat.h\"\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <stdint.h>\n#include <string.h>\n#include \"CPy.h\"\n#define LIBRT_INTERNAL_MODULE\n#include \"librt_internal.h\"\n\n#define START_SIZE 512\n\n// See comment in read_int_internal() on motivation for these values.\n#define MIN_ONE_BYTE_INT -10\n#define MAX_ONE_BYTE_INT 117  // 2 ** 7 - 1 - 10\n#define MIN_TWO_BYTES_INT -100\n#define MAX_TWO_BYTES_INT 16283  // 2 ** (8 + 6) - 1 - 100\n#define MIN_FOUR_BYTES_INT -10000\n#define MAX_FOUR_BYTES_INT 536860911  // 2 ** (3 * 8 + 5) - 1 - 10000\n\n#define TWO_BYTES_INT_BIT 1\n#define FOUR_BYTES_INT_BIT 2\n#define LONG_INT_BIT 4\n\n#define FOUR_BYTES_INT_TRAILER 3\n// We add one reserved bit here so that we can potentially support\n// 8 bytes format in the future.\n#define LONG_INT_TRAILER 15\n\n#define CPY_BOOL_ERROR 2\n\n#define _CHECK_READ_BUFFER(data, err)  if (unlikely(_check_read_buffer(data) == CPY_NONE_ERROR)) \\\n                                           return err;\n#define _CHECK_WRITE_BUFFER(data, err) if (unlikely(_check_write_buffer(data) == CPY_NONE_ERROR)) \\\n                                           return err;\n#define _CHECK_WRITE(data, need)        if (unlikely(_check_size((WriteBufferObject *)data, need) == CPY_NONE_ERROR)) \\\n                                           return CPY_NONE_ERROR;\n#define _CHECK_READ(data, size, err)   if (unlikely(_check_read((ReadBufferObject *)data, size) == CPY_NONE_ERROR)) \\\n                                           return err;\n\n#define _READ(result, data, type) \\\n    do { \\\n        memcpy((void *) result, ((ReadBufferObject *)data)->ptr, sizeof(type)); \\\n        ((ReadBufferObject *)data)->ptr += sizeof(type); \\\n    } while (0)\n\n#define _WRITE(data, type, v) \\\n    do { \\\n       type temp = v; \\\n       memcpy(((WriteBufferObject *)data)->ptr, (const void *) &temp, sizeof(type)); \\\n       ((WriteBufferObject *)data)->ptr += sizeof(type); \\\n    } while (0)\n\n//\n// ReadBuffer\n//\n\n#if PY_BIG_ENDIAN\nuint16_t reverse_16(uint16_t number) {\n  return (number << 8) | (number >> 8);\n}\n\nuint32_t reverse_32(uint32_t number) {\n  return ((number & 0xFF) << 24) | ((number & 0xFF00) << 8) | ((number & 0xFF0000) >> 8) | (number >> 24);\n}\n#endif\n\ntypedef struct {\n    PyObject_HEAD\n    char *ptr;  // Current read location in the buffer\n    char *end;  // End of the buffer\n    PyObject *source;  // The object that contains the buffer\n} ReadBufferObject;\n\nstatic PyTypeObject ReadBufferType;\n\nstatic PyObject*\nReadBuffer_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\n    if (type != &ReadBufferType) {\n        PyErr_SetString(PyExc_TypeError, \"ReadBuffer should not be subclassed\");\n        return NULL;\n    }\n\n    ReadBufferObject *self = (ReadBufferObject *)type->tp_alloc(type, 0);\n    if (self != NULL) {\n        self->source = NULL;\n        self->ptr = NULL;\n        self->end = NULL;\n    }\n    return (PyObject *) self;\n}\n\nstatic int\nReadBuffer_init_internal(ReadBufferObject *self, PyObject *source) {\n    if (!PyBytes_CheckExact(source)) {\n        PyErr_SetString(PyExc_TypeError, \"source must be a bytes object\");\n        return -1;\n    }\n    self->source = Py_NewRef(source);\n    self->ptr = PyBytes_AS_STRING(source);\n    self->end = self->ptr + PyBytes_GET_SIZE(source);\n    return 0;\n}\n\nstatic PyObject*\nReadBuffer_internal(PyObject *source) {\n    ReadBufferObject *self = (ReadBufferObject *)ReadBufferType.tp_alloc(&ReadBufferType, 0);\n    if (self == NULL)\n        return NULL;\n    self->ptr = NULL;\n    self->end = NULL;\n    self->source = NULL;\n    if (ReadBuffer_init_internal(self, source) == -1) {\n        Py_DECREF(self);\n        return NULL;\n    }\n    return (PyObject *)self;\n}\n\nstatic int\nReadBuffer_init(ReadBufferObject *self, PyObject *args, PyObject *kwds)\n{\n    static char *kwlist[] = {\"source\", NULL};\n    PyObject *source = NULL;\n\n    if (!PyArg_ParseTupleAndKeywords(args, kwds, \"|O\", kwlist, &source))\n        return -1;\n\n    return ReadBuffer_init_internal(self, source);\n}\n\nstatic void\nReadBuffer_dealloc(ReadBufferObject *self)\n{\n    Py_CLEAR(self->source);\n    Py_TYPE(self)->tp_free((PyObject *)self);\n}\n\nstatic PyMethodDef ReadBuffer_methods[] = {\n    {NULL}  /* Sentinel */\n};\n\nstatic PyTypeObject ReadBufferType = {\n    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"ReadBuffer\",\n    .tp_doc = PyDoc_STR(\"Mypy cache buffer objects\"),\n    .tp_basicsize = sizeof(ReadBufferObject),\n    .tp_itemsize = 0,\n    .tp_flags = Py_TPFLAGS_DEFAULT,\n    .tp_new = ReadBuffer_new,\n    .tp_init = (initproc) ReadBuffer_init,\n    .tp_dealloc = (destructor) ReadBuffer_dealloc,\n    .tp_methods = ReadBuffer_methods,\n};\n\n//\n// WriteBuffer\n//\n\ntypedef struct {\n    PyObject_HEAD\n    char *buf;  // Beginning of the buffer\n    char *ptr;  // Current write location in the buffer\n    char *end;  // End of the buffer\n} WriteBufferObject;\n\nstatic PyTypeObject WriteBufferType;\n\nstatic PyObject*\nWriteBuffer_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\n    if (type != &WriteBufferType) {\n        PyErr_SetString(PyExc_TypeError, \"WriteBuffer cannot be subclassed\");\n        return NULL;\n    }\n\n    WriteBufferObject *self = (WriteBufferObject *)type->tp_alloc(type, 0);\n    if (self != NULL) {\n        self->buf = NULL;\n        self->ptr = NULL;\n        self->end = NULL;\n    }\n    return (PyObject *)self;\n}\n\nstatic int\nWriteBuffer_init_internal(WriteBufferObject *self) {\n    Py_ssize_t size = START_SIZE;\n    self->buf = PyMem_Malloc(size + 1);\n    if (self->buf == NULL) {\n        PyErr_NoMemory();\n        return -1;\n    }\n    self->ptr = self->buf;\n    self->end = self->buf + size;\n    return 0;\n}\n\nstatic PyObject*\nWriteBuffer_internal(void) {\n    WriteBufferObject *self = (WriteBufferObject *)WriteBufferType.tp_alloc(&WriteBufferType, 0);\n    if (self == NULL)\n        return NULL;\n    self->buf = NULL;\n    self->ptr = NULL;\n    self->end = NULL;\n    if (WriteBuffer_init_internal(self) == -1) {\n        Py_DECREF(self);\n        return NULL;\n    }\n    return (PyObject *)self;\n}\n\nstatic int\nWriteBuffer_init(WriteBufferObject *self, PyObject *args, PyObject *kwds)\n{\n    if (!PyArg_ParseTuple(args, \"\")) {\n        return -1;\n    }\n\n    if (kwds != NULL && PyDict_Size(kwds) > 0) {\n        PyErr_SetString(PyExc_TypeError,\n                        \"WriteBuffer() takes no keyword arguments\");\n        return -1;\n    }\n\n    return WriteBuffer_init_internal(self);\n}\n\nstatic void\nWriteBuffer_dealloc(WriteBufferObject *self)\n{\n    PyMem_Free(self->buf);\n    self->buf = NULL;\n    Py_TYPE(self)->tp_free((PyObject *)self);\n}\n\nstatic PyObject*\nWriteBuffer_getvalue_internal(PyObject *self)\n{\n    WriteBufferObject *obj = (WriteBufferObject *)self;\n    return PyBytes_FromStringAndSize(obj->buf, obj->ptr - obj->buf);\n}\n\nstatic PyObject*\nWriteBuffer_getvalue(WriteBufferObject *self, PyObject *Py_UNUSED(ignored))\n{\n    return PyBytes_FromStringAndSize(self->buf, self->ptr - self->buf);\n}\n\nstatic PyMethodDef WriteBuffer_methods[] = {\n    {\"getvalue\", (PyCFunction) WriteBuffer_getvalue, METH_NOARGS,\n     \"Return the buffer content as bytes object\"\n    },\n    {NULL}  /* Sentinel */\n};\n\nstatic PyTypeObject WriteBufferType = {\n    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"WriteBuffer\",\n    .tp_doc = PyDoc_STR(\"Mypy cache buffer objects\"),\n    .tp_basicsize = sizeof(WriteBufferObject),\n    .tp_itemsize = 0,\n    .tp_flags = Py_TPFLAGS_DEFAULT,\n    .tp_new = WriteBuffer_new,\n    .tp_init = (initproc) WriteBuffer_init,\n    .tp_dealloc = (destructor) WriteBuffer_dealloc,\n    .tp_methods = WriteBuffer_methods,\n};\n\n// ----------\n\nstatic inline char\n_check_read_buffer(PyObject *data) {\n    if (unlikely(Py_TYPE(data) != &ReadBufferType)) {\n        PyErr_Format(\n            PyExc_TypeError, \"data must be a ReadBuffer object, got %s\", Py_TYPE(data)->tp_name\n        );\n        return CPY_NONE_ERROR;\n    }\n    return CPY_NONE;\n}\n\nstatic inline char\n_check_write_buffer(PyObject *data) {\n    if (unlikely(Py_TYPE(data) != &WriteBufferType)) {\n        PyErr_Format(\n            PyExc_TypeError, \"data must be a WriteBuffer object, got %s\", Py_TYPE(data)->tp_name\n        );\n        return CPY_NONE_ERROR;\n    }\n    return CPY_NONE;\n}\n\nstatic inline char\n_check_size(WriteBufferObject *data, Py_ssize_t need) {\n    if (data->end - data->ptr >= need)\n        return CPY_NONE;\n    Py_ssize_t index = data->ptr - data->buf;\n    Py_ssize_t target = index + need;\n    Py_ssize_t size = data->end - data->buf;\n    do {\n        size *= 2;\n    } while (target >= size);\n    data->buf = PyMem_Realloc(data->buf, size);\n    if (unlikely(data->buf == NULL)) {\n        PyErr_NoMemory();\n        return CPY_NONE_ERROR;\n    }\n    data->ptr = data->buf + index;\n    data->end = data->buf + size;\n    return CPY_NONE;\n}\n\nstatic inline char\n_check_read(ReadBufferObject *data, Py_ssize_t need) {\n    if (unlikely((data->end - data->ptr) < need)) {\n        PyErr_SetString(PyExc_ValueError, \"reading past the buffer end\");\n        return CPY_NONE_ERROR;\n    }\n    return CPY_NONE;\n}\n\n/*\nbool format: single byte\n    \\x00 - False\n    \\x01 - True\n*/\n\nstatic char\nread_bool_internal(PyObject *data) {\n    _CHECK_READ(data, 1, CPY_BOOL_ERROR)\n    char res;\n    _READ(&res, data, char);\n    if (unlikely((res != 0) & (res != 1))) {\n        PyErr_SetString(PyExc_ValueError, \"invalid bool value\");\n        return CPY_BOOL_ERROR;\n    }\n    return res;\n}\n\nstatic PyObject*\nread_bool(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"read_bool() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    _CHECK_READ_BUFFER(data, NULL)\n    char res = read_bool_internal(data);\n    if (unlikely(res == CPY_BOOL_ERROR))\n        return NULL;\n    PyObject *retval = res ? Py_True : Py_False;\n    Py_INCREF(retval);\n    return retval;\n}\n\nstatic char\nwrite_bool_internal(PyObject *data, char value) {\n    _CHECK_WRITE(data, 1)\n    _WRITE(data, char, value);\n    return CPY_NONE;\n}\n\nstatic PyObject*\nwrite_bool(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 2)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"write_bool() takes exactly 2 arguments (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    PyObject *value = args[1];\n    _CHECK_WRITE_BUFFER(data, NULL)\n    if (unlikely(!PyBool_Check(value))) {\n        PyErr_SetString(PyExc_TypeError, \"value must be a bool\");\n        return NULL;\n    }\n    if (unlikely(write_bool_internal(data, Py_IsTrue(value)) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\n/*\nstr format: size as int (see below) followed by UTF-8 bytes\n*/\n\nstatic inline CPyTagged\n_read_short_int(PyObject *data, uint8_t first) {\n    uint8_t second;\n    uint16_t two_more;\n    if ((first & TWO_BYTES_INT_BIT) == 0) {\n       // Note we use tagged ints since this function can return an error.\n       return ((Py_ssize_t)(first >> 1) + MIN_ONE_BYTE_INT) << 1;\n    }\n    if ((first & FOUR_BYTES_INT_BIT) == 0) {\n       _CHECK_READ(data, 1, CPY_INT_TAG)\n       _READ(&second, data, uint8_t);\n       return ((((Py_ssize_t)second) << 6) + (Py_ssize_t)(first >> 2) + MIN_TWO_BYTES_INT) << 1;\n    }\n    // The caller is responsible to verify this is called only for short ints.\n    _CHECK_READ(data, 3, CPY_INT_TAG)\n    // TODO: check if compilers emit optimal code for these two reads, and tweak if needed.\n    _READ(&second, data, uint8_t);\n    _READ(&two_more, data, uint16_t);\n#if PY_BIG_ENDIAN\n    two_more = reverse_16(two_more);\n#endif\n    Py_ssize_t higher = (((Py_ssize_t)two_more) << 13) + (((Py_ssize_t)second) << 5);\n    return (higher + (Py_ssize_t)(first >> 3) + MIN_FOUR_BYTES_INT) << 1;\n}\n\nstatic PyObject*\nread_str_internal(PyObject *data) {\n    // Read string length.\n    _CHECK_READ(data, 1, NULL)\n    uint8_t first;\n    _READ(&first, data, uint8_t);\n    if (unlikely(first == LONG_INT_TRAILER)) {\n        // Fail fast for invalid/tampered data.\n        PyErr_SetString(PyExc_ValueError, \"invalid str size\");\n        return NULL;\n    }\n    CPyTagged tagged_size = _read_short_int(data, first);\n    if (tagged_size == CPY_INT_TAG)\n        return NULL;\n    if ((Py_ssize_t)tagged_size < 0) {\n        // Fail fast for invalid/tampered data.\n        PyErr_SetString(PyExc_ValueError, \"invalid str size\");\n        return NULL;\n    }\n    Py_ssize_t size = tagged_size >> 1;\n    // Read string content.\n    char *ptr = ((ReadBufferObject *)data)->ptr;\n    _CHECK_READ(data, size, NULL)\n    PyObject *res = PyUnicode_FromStringAndSize(ptr, (Py_ssize_t)size);\n    if (unlikely(res == NULL))\n        return NULL;\n    ((ReadBufferObject *)data)->ptr += size;\n    return res;\n}\n\nstatic PyObject*\nread_str(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"read_str() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    _CHECK_READ_BUFFER(data, NULL)\n    return read_str_internal(data);\n}\n\n// The caller *must* check that real_value is within allowed range (29 bits).\nstatic inline char\n_write_short_int(PyObject *data, Py_ssize_t real_value) {\n    if (real_value >= MIN_ONE_BYTE_INT && real_value <= MAX_ONE_BYTE_INT) {\n        _CHECK_WRITE(data, 1)\n        _WRITE(data, uint8_t, (uint8_t)(real_value - MIN_ONE_BYTE_INT) << 1);\n    } else if (real_value >= MIN_TWO_BYTES_INT && real_value <= MAX_TWO_BYTES_INT) {\n        _CHECK_WRITE(data, 2)\n#if PY_BIG_ENDIAN\n        uint16_t to_write = ((uint16_t)(real_value - MIN_TWO_BYTES_INT) << 2) | TWO_BYTES_INT_BIT;\n        _WRITE(data, uint16_t, reverse_16(to_write));\n#else\n        _WRITE(data, uint16_t, ((uint16_t)(real_value - MIN_TWO_BYTES_INT) << 2) | TWO_BYTES_INT_BIT);\n#endif\n    } else {\n        _CHECK_WRITE(data, 4)\n#if PY_BIG_ENDIAN\n        uint32_t to_write = ((uint32_t)(real_value - MIN_FOUR_BYTES_INT) << 3) | FOUR_BYTES_INT_TRAILER;\n        _WRITE(data, uint32_t, reverse_32(to_write));\n#else\n        _WRITE(data, uint32_t, ((uint32_t)(real_value - MIN_FOUR_BYTES_INT) << 3) | FOUR_BYTES_INT_TRAILER);\n#endif\n    }\n    return CPY_NONE;\n}\n\nstatic char\nwrite_str_internal(PyObject *data, PyObject *value) {\n    Py_ssize_t size;\n    const char *chunk = PyUnicode_AsUTF8AndSize(value, &size);\n    if (unlikely(chunk == NULL))\n        return CPY_NONE_ERROR;\n\n    // Write string length.\n    if (likely(size >= MIN_FOUR_BYTES_INT && size <= MAX_FOUR_BYTES_INT)) {\n        if (_write_short_int(data, size) == CPY_NONE_ERROR)\n            return CPY_NONE_ERROR;\n    } else {\n        PyErr_SetString(PyExc_ValueError, \"str too long to serialize\");\n        return CPY_NONE_ERROR;\n    }\n    // Write string content.\n    _CHECK_WRITE(data, size)\n    char *ptr = ((WriteBufferObject *)data)->ptr;\n    memcpy(ptr, chunk, size);\n    ((WriteBufferObject *)data)->ptr += size;\n    return CPY_NONE;\n}\n\nstatic PyObject*\nwrite_str(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 2)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"write_str() takes exactly 2 arguments (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    PyObject *value = args[1];\n    _CHECK_WRITE_BUFFER(data, NULL)\n    if (unlikely(!PyUnicode_Check(value))) {\n        PyErr_SetString(PyExc_TypeError, \"value must be a str\");\n        return NULL;\n    }\n    if (unlikely(write_str_internal(data, value) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\n/*\nbytes format: size as int (see below) followed by bytes\n*/\n\nstatic PyObject*\nread_bytes_internal(PyObject *data) {\n    // Read length.\n    _CHECK_READ(data, 1, NULL)\n    uint8_t first;\n    _READ(&first, data, uint8_t);\n    if (unlikely(first == LONG_INT_TRAILER)) {\n        // Fail fast for invalid/tampered data.\n        PyErr_SetString(PyExc_ValueError, \"invalid bytes size\");\n        return NULL;\n    }\n    CPyTagged tagged_size = _read_short_int(data, first);\n    if (tagged_size == CPY_INT_TAG)\n        return NULL;\n    if ((Py_ssize_t)tagged_size < 0) {\n        // Fail fast for invalid/tampered data.\n        PyErr_SetString(PyExc_ValueError, \"invalid bytes size\");\n        return NULL;\n    }\n    Py_ssize_t size = tagged_size >> 1;\n    // Read bytes content.\n    char *ptr = ((ReadBufferObject *)data)->ptr;\n    _CHECK_READ(data, size, NULL)\n    PyObject *res = PyBytes_FromStringAndSize(ptr, (Py_ssize_t)size);\n    if (unlikely(res == NULL))\n        return NULL;\n    ((ReadBufferObject *)data)->ptr += size;\n    return res;\n}\n\nstatic PyObject*\nread_bytes(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"read_bytes() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    _CHECK_READ_BUFFER(data, NULL)\n    return read_bytes_internal(data);\n}\n\nstatic char\nwrite_bytes_internal(PyObject *data, PyObject *value) {\n    const char *chunk = PyBytes_AsString(value);\n    if (unlikely(chunk == NULL))\n        return CPY_NONE_ERROR;\n    Py_ssize_t size = PyBytes_GET_SIZE(value);\n\n    // Write length.\n    if (likely(size >= MIN_FOUR_BYTES_INT && size <= MAX_FOUR_BYTES_INT)) {\n        if (_write_short_int(data, size) == CPY_NONE_ERROR)\n            return CPY_NONE_ERROR;\n    } else {\n        PyErr_SetString(PyExc_ValueError, \"bytes too long to serialize\");\n        return CPY_NONE_ERROR;\n    }\n    // Write bytes content.\n    _CHECK_WRITE(data, size)\n    char *ptr = ((WriteBufferObject *)data)->ptr;\n    memcpy(ptr, chunk, size);\n    ((WriteBufferObject *)data)->ptr += size;\n    return CPY_NONE;\n}\n\nstatic PyObject*\nwrite_bytes(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 2)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"write_bytes() takes exactly 2 arguments (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    PyObject *value = args[1];\n    _CHECK_WRITE_BUFFER(data, NULL)\n    if (unlikely(!PyBytes_Check(value))) {\n        PyErr_SetString(PyExc_TypeError, \"value must be a bytes object\");\n        return NULL;\n    }\n    if (unlikely(write_bytes_internal(data, value) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\n/*\nfloat format:\n    stored using PyFloat helpers in little-endian format.\n*/\n\nstatic double\nread_float_internal(PyObject *data) {\n    _CHECK_READ(data, 8, CPY_FLOAT_ERROR)\n    char *ptr = ((ReadBufferObject *)data)->ptr;\n    double res = PyFloat_Unpack8(ptr, 1);\n    if (unlikely((res == -1.0) && PyErr_Occurred()))\n        return CPY_FLOAT_ERROR;\n    ((ReadBufferObject *)data)->ptr += 8;\n    return res;\n}\n\nstatic PyObject*\nread_float(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"read_float() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    _CHECK_READ_BUFFER(data, NULL)\n    double retval = read_float_internal(data);\n    if (unlikely(retval == CPY_FLOAT_ERROR && PyErr_Occurred())) {\n        return NULL;\n    }\n    return PyFloat_FromDouble(retval);\n}\n\nstatic char\nwrite_float_internal(PyObject *data, double value) {\n    _CHECK_WRITE(data, 8)\n    char *ptr = ((WriteBufferObject *)data)->ptr;\n    int res = PyFloat_Pack8(value, ptr, 1);\n    if (unlikely(res == -1))\n        return CPY_NONE_ERROR;\n    ((WriteBufferObject *)data)->ptr += 8;\n    return CPY_NONE;\n}\n\nstatic PyObject*\nwrite_float(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 2)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"write_float() takes exactly 2 arguments (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    PyObject *value = args[1];\n    _CHECK_WRITE_BUFFER(data, NULL)\n    if (unlikely(!PyFloat_Check(value))) {\n        PyErr_SetString(PyExc_TypeError, \"value must be a float\");\n        return NULL;\n    }\n    if (unlikely(write_float_internal(data, PyFloat_AsDouble(value)) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\n/*\nint format:\n    one byte: last bit 0, 7 bits used\n    two bytes: last two bits 01, 14 bits used\n    four bytes: last three bits 011, 29 bits used\n    everything else: 00001111 followed by serialized string representation\n\nNote: for fixed size formats we skew ranges towards more positive values,\nsince negative integers are much more rare.\n*/\n\nstatic CPyTagged\nread_int_internal(PyObject *data) {\n    _CHECK_READ(data, 1, CPY_INT_TAG)\n\n    uint8_t first;\n    _READ(&first, data, uint8_t);\n    if (likely(first != LONG_INT_TRAILER)) {\n        return _read_short_int(data, first);\n    }\n\n    // Long integer encoding -- byte length and sign, followed by a byte array.\n\n    // Read byte length and sign.\n    _CHECK_READ(data, 1, CPY_INT_TAG)\n    _READ(&first, data, uint8_t);\n    Py_ssize_t size_and_sign = _read_short_int(data, first);\n    if (size_and_sign == CPY_INT_TAG)\n        return CPY_INT_TAG;\n    if ((Py_ssize_t)size_and_sign < 0) {\n        PyErr_SetString(PyExc_ValueError, \"invalid int data\");\n        return CPY_INT_TAG;\n    }\n    bool sign = (size_and_sign >> 1) & 1;\n    Py_ssize_t size = size_and_sign >> 2;\n\n    // Construct an int object from the byte array.\n    _CHECK_READ(data, size, CPY_INT_TAG)\n    char *ptr = ((ReadBufferObject *)data)->ptr;\n    PyObject *num = _PyLong_FromByteArray((unsigned char *)ptr, size, 1, 0);\n    if (num == NULL)\n        return CPY_INT_TAG;\n    ((ReadBufferObject *)data)->ptr += size;\n    if (sign) {\n        PyObject *old = num;\n        num = PyNumber_Negative(old);\n        Py_DECREF(old);\n        if (num == NULL) {\n            return CPY_INT_TAG;\n        }\n    }\n    return CPyTagged_StealFromObject(num);\n}\n\nstatic PyObject*\nread_int(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"read_int() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    _CHECK_READ_BUFFER(data, NULL)\n    CPyTagged retval = read_int_internal(data);\n    if (unlikely(retval == CPY_INT_TAG)) {\n        return NULL;\n    }\n    return CPyTagged_StealAsObject(retval);\n}\n\n\nstatic inline int hex_to_int(char c) {\n    if (c >= '0' && c <= '9')\n        return c - '0';\n    else if (c >= 'a' && c <= 'f')\n        return c - 'a' + 10;\n    else\n        return c - 'A' + 10;  // Assume valid hex digit\n}\n\nstatic inline char\n_write_long_int(PyObject *data, CPyTagged value) {\n    _CHECK_WRITE(data, 1)\n    _WRITE(data, uint8_t, LONG_INT_TRAILER);\n\n    PyObject *hex_str = NULL;\n    PyObject* int_value = CPyTagged_AsObject(value);\n    if (unlikely(int_value == NULL))\n        goto error;\n\n    hex_str = PyNumber_ToBase(int_value, 16);\n    if (hex_str == NULL)\n        goto error;\n    Py_DECREF(int_value);\n    int_value = NULL;\n\n    const char *str = PyUnicode_AsUTF8(hex_str);\n    if (str == NULL)\n        goto error;\n    Py_ssize_t len = strlen(str);\n    bool neg;\n    if (str[0] == '-') {\n        str++;\n        len--;\n        neg = true;\n    } else {\n        neg = false;\n    }\n    // Skip the 0x hex prefix.\n    str += 2;\n    len -= 2;\n\n    // Write bytes encoded length and sign.\n    Py_ssize_t size = (len + 1) / 2;\n    Py_ssize_t encoded_size = (size << 1) | neg;\n    if (encoded_size <= MAX_FOUR_BYTES_INT) {\n        if (_write_short_int(data, encoded_size) == CPY_NONE_ERROR)\n            goto error;\n    } else {\n        PyErr_SetString(PyExc_ValueError, \"int too long to serialize\");\n        goto error;\n    }\n\n    // Write absolute integer value as byte array in a variable-length little endian format.\n    int i;\n    for (i = len; i > 1; i -= 2) {\n        if (write_tag_internal(\n                data, hex_to_int(str[i - 1]) | (hex_to_int(str[i - 2]) << 4)) == CPY_NONE_ERROR)\n            goto error;\n    }\n    // The final byte may correspond to only one hex digit.\n    if (i == 1) {\n        if (write_tag_internal(data, hex_to_int(str[i - 1])) == CPY_NONE_ERROR)\n            goto error;\n    }\n\n    Py_DECREF(hex_str);\n    return CPY_NONE;\n\n  error:\n\n    Py_XDECREF(int_value);\n    Py_XDECREF(hex_str);\n    return CPY_NONE_ERROR;\n}\n\nstatic char\nwrite_int_internal(PyObject *data, CPyTagged value) {\n    if (likely((value & CPY_INT_TAG) == 0)) {\n        Py_ssize_t real_value = CPyTagged_ShortAsSsize_t(value);\n        if (likely(real_value >= MIN_FOUR_BYTES_INT && real_value <= MAX_FOUR_BYTES_INT)) {\n            return _write_short_int(data, real_value);\n        } else {\n            return _write_long_int(data, value);\n        }\n    } else {\n        return _write_long_int(data, value);\n    }\n}\n\nstatic PyObject*\nwrite_int(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 2)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"write_int() takes exactly 2 arguments (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    PyObject *value = args[1];\n    _CHECK_WRITE_BUFFER(data, NULL)\n    if (unlikely(!PyLong_Check(value))) {\n        PyErr_SetString(PyExc_TypeError, \"value must be an int\");\n        return NULL;\n    }\n    CPyTagged tagged_value = CPyTagged_BorrowFromObject(value);\n    if (unlikely(write_int_internal(data, tagged_value) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\n/*\ninteger tag format (0 <= t <= 255):\n    stored as a uint8_t\n*/\n\nstatic uint8_t\nread_tag_internal(PyObject *data) {\n    _CHECK_READ(data, 1, CPY_LL_UINT_ERROR)\n    uint8_t ret;\n    _READ(&ret, data, uint8_t);\n    return ret;\n}\n\nstatic PyObject*\nread_tag(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"read_tag() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    _CHECK_READ_BUFFER(data, NULL)\n    uint8_t retval = read_tag_internal(data);\n    if (unlikely(retval == CPY_LL_UINT_ERROR && PyErr_Occurred())) {\n        return NULL;\n    }\n    return PyLong_FromLong(retval);\n}\n\nstatic char\nwrite_tag_internal(PyObject *data, uint8_t value) {\n    _CHECK_WRITE(data, 1)\n    _WRITE(data, uint8_t, value);\n    return CPY_NONE;\n}\n\nstatic PyObject*\nwrite_tag(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 2)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"write_tag() takes exactly 2 arguments (%zu given)\", nargs);\n        return NULL;\n    }\n    PyObject *data = args[0];\n    PyObject *value = args[1];\n    _CHECK_WRITE_BUFFER(data, NULL)\n    uint8_t unboxed = CPyLong_AsUInt8(value);\n    if (unlikely(unboxed == CPY_LL_UINT_ERROR && PyErr_Occurred())) {\n        CPy_TypeError(\"u8\", value);\n        return NULL;\n    }\n    if (unlikely(write_tag_internal(data, unboxed) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic uint8_t\ncache_version_internal(void) {\n    return 0;\n}\n\nstatic PyObject*\ncache_version(PyObject *self, PyObject *Py_UNUSED(ignored)) {\n    return PyLong_FromLong(cache_version_internal());\n}\n\nstatic PyTypeObject *\nReadBuffer_type_internal(void) {\n    return &ReadBufferType;  // Return borrowed reference\n}\n\nstatic PyTypeObject *\nWriteBuffer_type_internal(void) {\n    return &WriteBufferType;  // Return borrowed reference\n};\n\nstatic PyMethodDef librt_internal_module_methods[] = {\n    {\"write_bool\", (PyCFunction)write_bool, METH_FASTCALL, PyDoc_STR(\"write a bool\")},\n    {\"read_bool\", (PyCFunction)read_bool, METH_FASTCALL, PyDoc_STR(\"read a bool\")},\n    {\"write_str\", (PyCFunction)write_str, METH_FASTCALL, PyDoc_STR(\"write a string\")},\n    {\"read_str\", (PyCFunction)read_str, METH_FASTCALL, PyDoc_STR(\"read a string\")},\n    {\"write_bytes\", (PyCFunction)write_bytes, METH_FASTCALL, PyDoc_STR(\"write bytes\")},\n    {\"read_bytes\", (PyCFunction)read_bytes, METH_FASTCALL, PyDoc_STR(\"read bytes\")},\n    {\"write_float\", (PyCFunction)write_float, METH_FASTCALL, PyDoc_STR(\"write a float\")},\n    {\"read_float\", (PyCFunction)read_float, METH_FASTCALL, PyDoc_STR(\"read a float\")},\n    {\"write_int\", (PyCFunction)write_int, METH_FASTCALL, PyDoc_STR(\"write an int\")},\n    {\"read_int\", (PyCFunction)read_int, METH_FASTCALL, PyDoc_STR(\"read an int\")},\n    {\"write_tag\", (PyCFunction)write_tag, METH_FASTCALL, PyDoc_STR(\"write a short int\")},\n    {\"read_tag\", (PyCFunction)read_tag, METH_FASTCALL, PyDoc_STR(\"read a short int\")},\n    {\"cache_version\", (PyCFunction)cache_version, METH_NOARGS, PyDoc_STR(\"cache format version\")},\n    {NULL, NULL, 0, NULL}\n};\n\nstatic int\nNativeInternal_ABI_Version(void) {\n    return LIBRT_INTERNAL_ABI_VERSION;\n}\n\nstatic int\nNativeInternal_API_Version(void) {\n    return LIBRT_INTERNAL_API_VERSION;\n}\n\nstatic int\nlibrt_internal_module_exec(PyObject *m)\n{\n    if (PyType_Ready(&ReadBufferType) < 0) {\n        return -1;\n    }\n    if (PyType_Ready(&WriteBufferType) < 0) {\n        return -1;\n    }\n    if (PyModule_AddObjectRef(m, \"ReadBuffer\", (PyObject *) &ReadBufferType) < 0) {\n        return -1;\n    }\n    if (PyModule_AddObjectRef(m, \"WriteBuffer\", (PyObject *) &WriteBufferType) < 0) {\n        return -1;\n    }\n\n    // Export mypy internal C API, be careful with the order!\n    static void *NativeInternal_API[LIBRT_INTERNAL_API_LEN] = {\n        (void *)ReadBuffer_internal,\n        (void *)WriteBuffer_internal,\n        (void *)WriteBuffer_getvalue_internal,\n        (void *)write_bool_internal,\n        (void *)read_bool_internal,\n        (void *)write_str_internal,\n        (void *)read_str_internal,\n        (void *)write_float_internal,\n        (void *)read_float_internal,\n        (void *)write_int_internal,\n        (void *)read_int_internal,\n        (void *)write_tag_internal,\n        (void *)read_tag_internal,\n        (void *)NativeInternal_ABI_Version,\n        (void *)write_bytes_internal,\n        (void *)read_bytes_internal,\n        (void *)cache_version_internal,\n        (void *)ReadBuffer_type_internal,\n        (void *)WriteBuffer_type_internal,\n        (void *)NativeInternal_API_Version,\n    };\n    PyObject *c_api_object = PyCapsule_New((void *)NativeInternal_API, \"librt.internal._C_API\", NULL);\n    if (PyModule_Add(m, \"_C_API\", c_api_object) < 0) {\n        return -1;\n    }\n    return 0;\n}\n\nstatic PyModuleDef_Slot librt_internal_module_slots[] = {\n    {Py_mod_exec, librt_internal_module_exec},\n#ifdef Py_MOD_GIL_NOT_USED\n    {Py_mod_gil, Py_MOD_GIL_NOT_USED},\n#endif\n    {0, NULL}\n};\n\nstatic PyModuleDef librt_internal_module = {\n    .m_base = PyModuleDef_HEAD_INIT,\n    .m_name = \"internal\",\n    .m_doc = \"Mypy cache serialization utils\",\n    .m_size = 0,\n    .m_methods = librt_internal_module_methods,\n    .m_slots = librt_internal_module_slots,\n};\n\nPyMODINIT_FUNC\nPyInit_internal(void)\n{\n    return PyModuleDef_Init(&librt_internal_module);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/internal/librt_internal.h",
    "content": "#ifndef LIBRT_INTERNAL_H\n#define LIBRT_INTERNAL_H\n\n#include <Python.h>\n\n// ABI version -- only an exact match is compatible. This will only be changed in\n// very exceptional cases (likely never) due to strict backward compatibility\n// requirements.\n#define LIBRT_INTERNAL_ABI_VERSION 2\n\n// API version -- more recent versions must maintain backward compatibility, i.e.\n// we can add new features but not remove or change existing features (unless\n// ABI version is changed, but see the comment above).\n #define LIBRT_INTERNAL_API_VERSION 0\n\n// Number of functions in the capsule API. If you add a new function, also increase\n// LIBRT_INTERNAL_API_VERSION.\n#define LIBRT_INTERNAL_API_LEN 20\n\n#ifdef LIBRT_INTERNAL_MODULE\n\nstatic PyObject *ReadBuffer_internal(PyObject *source);\nstatic PyObject *WriteBuffer_internal(void);\nstatic PyObject *WriteBuffer_getvalue_internal(PyObject *self);\nstatic PyObject *ReadBuffer_internal(PyObject *source);\nstatic PyObject *ReadBuffer_internal_empty(void);\nstatic char write_bool_internal(PyObject *data, char value);\nstatic char read_bool_internal(PyObject *data);\nstatic char write_str_internal(PyObject *data, PyObject *value);\nstatic PyObject *read_str_internal(PyObject *data);\nstatic char write_float_internal(PyObject *data, double value);\nstatic double read_float_internal(PyObject *data);\nstatic char write_int_internal(PyObject *data, CPyTagged value);\nstatic CPyTagged read_int_internal(PyObject *data);\nstatic char write_tag_internal(PyObject *data, uint8_t value);\nstatic uint8_t read_tag_internal(PyObject *data);\nstatic int NativeInternal_ABI_Version(void);\nstatic char write_bytes_internal(PyObject *data, PyObject *value);\nstatic PyObject *read_bytes_internal(PyObject *data);\nstatic uint8_t cache_version_internal(void);\nstatic PyTypeObject *ReadBuffer_type_internal(void);\nstatic PyTypeObject *WriteBuffer_type_internal(void);\nstatic int NativeInternal_API_Version(void);\n\n#else\n\nstatic void *NativeInternal_API[LIBRT_INTERNAL_API_LEN];\n\n#define ReadBuffer_internal (*(PyObject* (*)(PyObject *source)) NativeInternal_API[0])\n#define WriteBuffer_internal (*(PyObject* (*)(void)) NativeInternal_API[1])\n#define WriteBuffer_getvalue_internal (*(PyObject* (*)(PyObject *source)) NativeInternal_API[2])\n#define write_bool_internal (*(char (*)(PyObject *source, char value)) NativeInternal_API[3])\n#define read_bool_internal (*(char (*)(PyObject *source)) NativeInternal_API[4])\n#define write_str_internal (*(char (*)(PyObject *source, PyObject *value)) NativeInternal_API[5])\n#define read_str_internal (*(PyObject* (*)(PyObject *source)) NativeInternal_API[6])\n#define write_float_internal (*(char (*)(PyObject *source, double value)) NativeInternal_API[7])\n#define read_float_internal (*(double (*)(PyObject *source)) NativeInternal_API[8])\n#define write_int_internal (*(char (*)(PyObject *source, CPyTagged value)) NativeInternal_API[9])\n#define read_int_internal (*(CPyTagged (*)(PyObject *source)) NativeInternal_API[10])\n#define write_tag_internal (*(char (*)(PyObject *source, uint8_t value)) NativeInternal_API[11])\n#define read_tag_internal (*(uint8_t (*)(PyObject *source)) NativeInternal_API[12])\n#define NativeInternal_ABI_Version (*(int (*)(void)) NativeInternal_API[13])\n#define write_bytes_internal (*(char (*)(PyObject *source, PyObject *value)) NativeInternal_API[14])\n#define read_bytes_internal (*(PyObject* (*)(PyObject *source)) NativeInternal_API[15])\n#define cache_version_internal (*(uint8_t (*)(void)) NativeInternal_API[16])\n#define ReadBuffer_type_internal (*(PyTypeObject* (*)(void)) NativeInternal_API[17])\n#define WriteBuffer_type_internal (*(PyTypeObject* (*)(void)) NativeInternal_API[18])\n#define NativeInternal_API_Version (*(int (*)(void)) NativeInternal_API[19])\n\nstatic int\nimport_librt_internal(void)\n{\n    PyObject *mod = PyImport_ImportModule(\"librt.internal\");\n    if (mod == NULL)\n        return -1;\n    Py_DECREF(mod);  // we import just for the side effect of making the below work.\n    void *capsule = PyCapsule_Import(\"librt.internal._C_API\", 0);\n    if (capsule == NULL)\n        return -1;\n    memcpy(NativeInternal_API, capsule, sizeof(NativeInternal_API));\n    if (NativeInternal_ABI_Version() != LIBRT_INTERNAL_ABI_VERSION) {\n        char err[128];\n        snprintf(err, sizeof(err), \"ABI version conflict for librt.internal, expected %d, found %d\",\n            LIBRT_INTERNAL_ABI_VERSION,\n            NativeInternal_ABI_Version()\n        );\n        PyErr_SetString(PyExc_ValueError, err);\n        return -1;\n    }\n    if (NativeInternal_API_Version() < LIBRT_INTERNAL_API_VERSION) {\n        char err[128];\n        snprintf(err, sizeof(err),\n                 \"API version conflict for librt.internal, expected %d or newer, found %d (hint: upgrade librt)\",\n            LIBRT_INTERNAL_API_VERSION,\n            NativeInternal_API_Version()\n        );\n        PyErr_SetString(PyExc_ValueError, err);\n        return -1;\n    }\n    return 0;\n}\n\n#endif\n\nstatic inline bool CPyReadBuffer_Check(PyObject *obj) {\n    return Py_TYPE(obj) == ReadBuffer_type_internal();\n}\n\nstatic inline bool CPyWriteBuffer_Check(PyObject *obj) {\n    return Py_TYPE(obj) == WriteBuffer_type_internal();\n}\n\n#endif  // LIBRT_INTERNAL_H\n"
  },
  {
    "path": "mypyc/lib-rt/list_ops.c",
    "content": "// List primitive operations\n//\n// These are registered in mypyc.primitives.list_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\n\n#ifndef Py_TPFLAGS_SEQUENCE\n#define Py_TPFLAGS_SEQUENCE (1 << 5)\n#endif\n\nPyObject *CPyList_Build(Py_ssize_t len, ...) {\n    Py_ssize_t i;\n\n    PyObject *res = PyList_New(len);\n    if (res == NULL) {\n        return NULL;\n    }\n\n    va_list args;\n    va_start(args, len);\n    for (i = 0; i < len; i++) {\n        // Steals the reference\n        PyObject *value = va_arg(args, PyObject *);\n        PyList_SET_ITEM(res, i, value);\n    }\n    va_end(args);\n\n    return res;\n}\n\nchar CPyList_Clear(PyObject *list) {\n    if (PyList_CheckExact(list)) {\n        PyList_Clear(list);\n    } else {\n        PyObject *res = PyObject_CallMethodNoArgs(list, mypyc_interned_str.clear);\n        if (res == NULL) {\n            return 0;\n        }\n    }\n    return 1;\n}\n\nPyObject *CPyList_Copy(PyObject *list) {\n    if(PyList_CheckExact(list)) {\n        return PyList_GetSlice(list, 0, PyList_GET_SIZE(list));\n    }\n    return PyObject_CallMethodNoArgs(list, mypyc_interned_str.copy);\n}\n\nPyObject *CPyList_GetItemShort(PyObject *list, CPyTagged index) {\n    Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n    Py_ssize_t size = PyList_GET_SIZE(list);\n    if (n >= 0) {\n        if (n >= size) {\n            PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n            return NULL;\n        }\n    } else {\n        n += size;\n        if (n < 0) {\n            PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n            return NULL;\n        }\n    }\n    PyObject *result = PyList_GET_ITEM(list, n);\n    Py_INCREF(result);\n    return result;\n}\n\nPyObject *CPyList_GetItemShortBorrow(PyObject *list, CPyTagged index) {\n    Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n    Py_ssize_t size = PyList_GET_SIZE(list);\n    if (n >= 0) {\n        if (n >= size) {\n            PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n            return NULL;\n        }\n    } else {\n        n += size;\n        if (n < 0) {\n            PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n            return NULL;\n        }\n    }\n    return PyList_GET_ITEM(list, n);\n}\n\nPyObject *CPyList_GetItem(PyObject *list, CPyTagged index) {\n    if (CPyTagged_CheckShort(index)) {\n        Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n        Py_ssize_t size = PyList_GET_SIZE(list);\n        if (n >= 0) {\n            if (n >= size) {\n                PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n                return NULL;\n            }\n        } else {\n            n += size;\n            if (n < 0) {\n                PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n                return NULL;\n            }\n        }\n        PyObject *result = PyList_GET_ITEM(list, n);\n        Py_INCREF(result);\n        return result;\n    } else {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return NULL;\n    }\n}\n\nPyObject *CPyList_GetItemBorrow(PyObject *list, CPyTagged index) {\n    if (CPyTagged_CheckShort(index)) {\n        Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n        Py_ssize_t size = PyList_GET_SIZE(list);\n        if (n >= 0) {\n            if (n >= size) {\n                PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n                return NULL;\n            }\n        } else {\n            n += size;\n            if (n < 0) {\n                PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n                return NULL;\n            }\n        }\n        return PyList_GET_ITEM(list, n);\n    } else {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return NULL;\n    }\n}\n\nPyObject *CPyList_GetItemInt64(PyObject *list, int64_t index) {\n    size_t size = PyList_GET_SIZE(list);\n    if (likely((uint64_t)index < size)) {\n        PyObject *result = PyList_GET_ITEM(list, index);\n        Py_INCREF(result);\n        return result;\n    }\n    if (index >= 0) {\n        PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n        return NULL;\n    }\n    index += size;\n    if (index < 0) {\n        PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n        return NULL;\n    }\n    PyObject *result = PyList_GET_ITEM(list, index);\n    Py_INCREF(result);\n    return result;\n}\n\nPyObject *CPyList_GetItemInt64Borrow(PyObject *list, int64_t index) {\n    size_t size = PyList_GET_SIZE(list);\n    if (likely((uint64_t)index < size)) {\n        return PyList_GET_ITEM(list, index);\n    }\n    if (index >= 0) {\n        PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n        return NULL;\n    }\n    index += size;\n    if (index < 0) {\n        PyErr_SetString(PyExc_IndexError, \"list index out of range\");\n        return NULL;\n    }\n    return PyList_GET_ITEM(list, index);\n}\n\nbool CPyList_SetItem(PyObject *list, CPyTagged index, PyObject *value) {\n    if (CPyTagged_CheckShort(index)) {\n        Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n        Py_ssize_t size = PyList_GET_SIZE(list);\n        if (n >= 0) {\n            if (n >= size) {\n                PyErr_SetString(PyExc_IndexError, \"list assignment index out of range\");\n                return false;\n            }\n        } else {\n            n += size;\n            if (n < 0) {\n                PyErr_SetString(PyExc_IndexError, \"list assignment index out of range\");\n                return false;\n            }\n        }\n        // PyList_SET_ITEM doesn't decref the old element, so we do\n        Py_DECREF(PyList_GET_ITEM(list, n));\n        // N.B: Steals reference\n        PyList_SET_ITEM(list, n, value);\n        return true;\n    } else {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return false;\n    }\n}\n\nbool CPyList_SetItemInt64(PyObject *list, int64_t index, PyObject *value) {\n    size_t size = PyList_GET_SIZE(list);\n    if (unlikely((uint64_t)index >= size)) {\n        if (index > 0) {\n            PyErr_SetString(PyExc_IndexError, \"list assignment index out of range\");\n            return false;\n        }\n        index += size;\n        if (index < 0) {\n            PyErr_SetString(PyExc_IndexError, \"list assignment index out of range\");\n            return false;\n        }\n    }\n    // PyList_SET_ITEM doesn't decref the old element, so we do\n    Py_DECREF(PyList_GET_ITEM(list, index));\n    // N.B: Steals reference\n    PyList_SET_ITEM(list, index, value);\n    return true;\n}\n\n// This function should only be used to fill in brand new lists.\nvoid CPyList_SetItemUnsafe(PyObject *list, Py_ssize_t index, PyObject *value) {\n    PyList_SET_ITEM(list, index, value);\n}\n\n#ifdef Py_GIL_DISABLED\n// The original optimized list.pop implementation doesn't work on free-threaded\n// builds, so provide an alternative that is a bit slower but works.\n//\n// Note that this implementation isn't intended to be atomic.\nstatic inline PyObject *list_pop_index(PyObject *list, Py_ssize_t index) {\n    PyObject *item = PyList_GetItemRef(list, index);\n    if (item == NULL) {\n        return NULL;\n    }\n    if (PySequence_DelItem(list, index) < 0) {\n        Py_DECREF(item);\n        return NULL;\n    }\n    return item;\n}\n#endif\n\nPyObject *CPyList_PopLast(PyObject *list)\n{\n#ifdef Py_GIL_DISABLED\n    // The other implementation causes segfaults on a free-threaded Python 3.14b4 build.\n    Py_ssize_t index = PyList_GET_SIZE(list) - 1;\n    return list_pop_index(list, index);\n#else\n    // I tried a specalized version of pop_impl for just removing the\n    // last element and it wasn't any faster in microbenchmarks than\n    // the generic one so I ditched it.\n    return list_pop_impl((PyListObject *)list, -1);\n#endif\n}\n\nPyObject *CPyList_Pop(PyObject *obj, CPyTagged index)\n{\n    if (CPyTagged_CheckShort(index)) {\n        Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n#ifdef Py_GIL_DISABLED\n        // We must use a slower implementation on free-threaded builds.\n        if (n < 0) {\n            n += PyList_GET_SIZE(obj);\n        }\n        return list_pop_index(obj, n);\n#else\n        return list_pop_impl((PyListObject *)obj, n);\n#endif\n    } else {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return NULL;\n    }\n}\n\nCPyTagged CPyList_Count(PyObject *obj, PyObject *value)\n{\n    return list_count((PyListObject *)obj, value);\n}\n\nint CPyList_Insert(PyObject *list, CPyTagged index, PyObject *value)\n{\n    if (CPyTagged_CheckShort(index)) {\n        Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n        return PyList_Insert(list, n, value);\n    }\n    // The max range doesn't exactly coincide with ssize_t, but we still\n    // want to keep the error message compatible with CPython.\n    PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n    return -1;\n}\n\nPyObject *CPyList_Extend(PyObject *o1, PyObject *o2) {\n    if (PyList_Extend(o1, o2) < 0) {\n        return NULL;\n    }\n    Py_RETURN_NONE;\n}\n\n// Return -2 or error, -1 if not found, or index of first match otherwise.\nstatic Py_ssize_t _CPyList_Find(PyObject *list, PyObject *obj) {\n    Py_ssize_t i;\n    for (i = 0; i < Py_SIZE(list); i++) {\n        PyObject *item = PyList_GET_ITEM(list, i);\n        Py_INCREF(item);\n        int cmp = PyObject_RichCompareBool(item, obj, Py_EQ);\n        Py_DECREF(item);\n        if (cmp != 0) {\n            if (cmp > 0) {\n                return i;\n            } else {\n                return -2;\n            }\n        }\n    }\n    return -1;\n}\n\nint CPyList_Remove(PyObject *list, PyObject *obj) {\n    Py_ssize_t index = _CPyList_Find(list, obj);\n    if (index == -2) {\n        return -1;\n    }\n    if (index == -1) {\n        PyErr_SetString(PyExc_ValueError, \"list.remove(x): x not in list\");\n        return -1;\n    }\n    return PyList_SetSlice(list, index, index + 1, NULL);\n}\n\nCPyTagged CPyList_Index(PyObject *list, PyObject *obj) {\n    Py_ssize_t index = _CPyList_Find(list, obj);\n    if (index == -2) {\n        return CPY_INT_TAG;\n    }\n    if (index == -1) {\n        PyErr_SetString(PyExc_ValueError, \"value is not in list\");\n        return CPY_INT_TAG;\n    }\n    return index << 1;\n}\n\nPyObject *CPySequence_Sort(PyObject *seq) {\n    PyObject *newlist = PySequence_List(seq);\n    if (newlist == NULL)\n        return NULL;\n    int res = PyList_Sort(newlist);\n    if (res < 0) {\n        Py_DECREF(newlist);\n        return NULL;\n    }\n    return newlist;\n}\n\nPyObject *CPySequence_Multiply(PyObject *seq, CPyTagged t_size) {\n    Py_ssize_t size = CPyTagged_AsSsize_t(t_size);\n    if (size == -1 && PyErr_Occurred()) {\n        return NULL;\n    }\n    return PySequence_Repeat(seq, size);\n}\n\nPyObject *CPySequence_RMultiply(CPyTagged t_size, PyObject *seq) {\n    return CPySequence_Multiply(seq, t_size);\n}\n\nPyObject *CPySequence_InPlaceMultiply(PyObject *seq, CPyTagged t_size) {\n    Py_ssize_t size = CPyTagged_AsSsize_t(t_size);\n    if (size == -1 && PyErr_Occurred()) {\n        return NULL;\n    }\n    return PySequence_InPlaceRepeat(seq, size);\n}\n\nPyObject *CPyList_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) {\n    if (likely(PyList_CheckExact(obj)\n               && CPyTagged_CheckShort(start) && CPyTagged_CheckShort(end))) {\n        Py_ssize_t startn = CPyTagged_ShortAsSsize_t(start);\n        Py_ssize_t endn = CPyTagged_ShortAsSsize_t(end);\n        if (startn < 0) {\n            startn += PyList_GET_SIZE(obj);\n        }\n        if (endn < 0) {\n            endn += PyList_GET_SIZE(obj);\n        }\n        return PyList_GetSlice(obj, startn, endn);\n    }\n    return CPyObject_GetSlice(obj, start, end);\n}\n\nint CPySequence_Check(PyObject *obj) {\n    return Py_TYPE(obj)->tp_flags & Py_TPFLAGS_SEQUENCE;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/misc_ops.c",
    "content": "#include \"pythoncapi_compat.h\"\n\n// Misc primitive operations + C helpers\n//\n// These are registered in mypyc.primitives.misc_ops.\n\n#include <Python.h>\n#include <patchlevel.h>\n#include \"CPy.h\"\n\nPyObject *CPy_GetCoro(PyObject *obj)\n{\n    // If the type has an __await__ method, call it,\n    // otherwise, fallback to calling __iter__.\n    PyAsyncMethods* async_struct = Py_TYPE(obj)->tp_as_async;\n    if (async_struct != NULL && async_struct->am_await != NULL) {\n        return (async_struct->am_await)(obj);\n    } else {\n        // TODO: We should check that the type is a generator decorated with\n        // asyncio.coroutine\n        return PyObject_GetIter(obj);\n    }\n}\n\nPyObject *CPyIter_Send(PyObject *iter, PyObject *val)\n{\n    // Do a send, or a next if second arg is None.\n    // (This behavior is to match the PEP 380 spec for yield from.)\n    if (Py_IsNone(val)) {\n        return CPyIter_Next(iter);\n    } else {\n        return PyObject_CallMethodOneArg(iter, mypyc_interned_str.send, val);\n    }\n}\n\n// A somewhat hairy implementation of specifically most of the error handling\n// in `yield from` error handling. The point here is to reduce code size.\n//\n// This implements most of the bodies of the `except` blocks in the\n// pseudocode in PEP 380.\n//\n// Returns true (1) if a StopIteration was received and we should return.\n// Returns false (0) if a value should be yielded.\n// In both cases the value is stored in outp.\n// Signals an error (2) if the an exception should be propagated.\nint CPy_YieldFromErrorHandle(PyObject *iter, PyObject **outp)\n{\n    PyObject *exc_type = (PyObject *)Py_TYPE(CPy_ExcState()->exc_value);\n    PyObject *type, *value, *traceback;\n    PyObject *_m;\n    PyObject *res;\n    *outp = NULL;\n\n    if (PyErr_GivenExceptionMatches(exc_type, PyExc_GeneratorExit)) {\n        _m = PyObject_GetAttr(iter, mypyc_interned_str.close_);\n        if (_m) {\n            res = PyObject_CallNoArgs(_m);\n            Py_DECREF(_m);\n            if (!res)\n                return 2;\n            Py_DECREF(res);\n        } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) {\n            PyErr_Clear();\n        } else {\n            return 2;\n        }\n    } else {\n        _m = PyObject_GetAttr(iter, mypyc_interned_str.throw_);\n        if (_m) {\n            _CPy_GetExcInfo(&type, &value, &traceback);\n            res = PyObject_CallFunctionObjArgs(_m, type, value, traceback, NULL);\n            Py_DECREF(type);\n            Py_DECREF(value);\n            Py_DECREF(traceback);\n            Py_DECREF(_m);\n            if (res) {\n                *outp = res;\n                return 0;\n            } else {\n                res = CPy_FetchStopIterationValue();\n                if (res) {\n                    *outp = res;\n                    return 1;\n                } else {\n                    return 2;\n                }\n            }\n        } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) {\n            PyErr_Clear();\n        } else {\n            return 2;\n        }\n    }\n\n    CPy_Reraise();\n    return 2;\n}\n\nPyObject *CPy_FetchStopIterationValue(void)\n{\n    PyObject *val = NULL;\n    _PyGen_FetchStopIterationValue(&val);\n    return val;\n}\n\nstatic bool _CPy_IsSafeMetaClass(PyTypeObject *metaclass) {\n    // mypyc classes can't work with metaclasses in\n    // general. Through some various nasty hacks we *do*\n    // manage to work with TypingMeta and its friends.\n    if (metaclass == &PyType_Type)\n        return true;\n    PyObject *module = PyObject_GetAttr((PyObject *)metaclass, mypyc_interned_str.__module__);\n    if (!module) {\n        PyErr_Clear();\n        return false;\n    }\n\n    bool matches = false;\n    if (PyUnicode_CompareWithASCIIString(module, \"typing\") == 0 &&\n            (strcmp(metaclass->tp_name, \"TypingMeta\") == 0\n             || strcmp(metaclass->tp_name, \"GenericMeta\") == 0\n             || strcmp(metaclass->tp_name, \"_ProtocolMeta\") == 0)) {\n        matches = true;\n    } else if (PyUnicode_CompareWithASCIIString(module, \"typing_extensions\") == 0 &&\n               strcmp(metaclass->tp_name, \"_ProtocolMeta\") == 0) {\n        matches = true;\n    } else if (PyUnicode_CompareWithASCIIString(module, \"abc\") == 0 &&\n               strcmp(metaclass->tp_name, \"ABCMeta\") == 0) {\n        matches = true;\n    }\n    Py_DECREF(module);\n    return matches;\n}\n\n#if CPY_3_13_FEATURES\n\n// Adapted from CPython 3.13.0b3\n/* Determine the most derived metatype. */\nPyObject *CPy_CalculateMetaclass(PyObject *metatype, PyObject *bases)\n{\n    Py_ssize_t i, nbases;\n    PyTypeObject *winner;\n    PyObject *tmp;\n    PyTypeObject *tmptype;\n\n    /* Determine the proper metatype to deal with this,\n       and check for metatype conflicts while we're at it.\n       Note that if some other metatype wins to contract,\n       it's possible that its instances are not types. */\n\n    nbases = PyTuple_GET_SIZE(bases);\n    winner = (PyTypeObject *)metatype;\n    for (i = 0; i < nbases; i++) {\n        tmp = PyTuple_GET_ITEM(bases, i);\n        tmptype = Py_TYPE(tmp);\n        if (PyType_IsSubtype(winner, tmptype))\n            continue;\n        if (PyType_IsSubtype(tmptype, winner)) {\n            winner = tmptype;\n            continue;\n        }\n        /* else: */\n        PyErr_SetString(PyExc_TypeError,\n                        \"metaclass conflict: \"\n                        \"the metaclass of a derived class \"\n                        \"must be a (non-strict) subclass \"\n                        \"of the metaclasses of all its bases\");\n        return NULL;\n    }\n    return (PyObject *)winner;\n}\n\n#else\n\nPyObject *CPy_CalculateMetaclass(PyObject *metatype, PyObject *bases) {\n    return (PyObject *)_PyType_CalculateMetaclass((PyTypeObject *)metatype, bases);\n}\n\n#endif\n\n// Create a heap type based on a template non-heap type.\n// This is super hacky and maybe we should suck it up and use PyType_FromSpec instead.\n// We allow bases to be NULL to represent just inheriting from object.\n// We don't support NULL bases and a non-type metaclass.\nPyObject *CPyType_FromTemplate(PyObject *template,\n                               PyObject *orig_bases,\n                               PyObject *modname) {\n    PyTypeObject *template_ = (PyTypeObject *)template;\n    PyHeapTypeObject *t = NULL;\n    PyTypeObject *dummy_class = NULL;\n    PyObject *name = NULL;\n    PyObject *bases = NULL;\n    PyObject *slots;\n\n    // If the type of the class (the metaclass) is NULL, we default it\n    // to being type.  (This allows us to avoid needing to initialize\n    // it explicitly on windows.)\n    if (!Py_TYPE(template_)) {\n        Py_SET_TYPE(template_, &PyType_Type);\n    }\n    PyTypeObject *metaclass = Py_TYPE(template_);\n\n    if (orig_bases) {\n        bases = update_bases(orig_bases);\n        // update_bases doesn't increment the refcount if nothing changes,\n        // so we do it to make sure we have distinct \"references\" to both\n        if (bases == orig_bases)\n            Py_INCREF(bases);\n\n        // Find the appropriate metaclass from our base classes. We\n        // care about this because Generic uses a metaclass prior to\n        // Python 3.7.\n        metaclass = (PyTypeObject *)CPy_CalculateMetaclass((PyObject *)metaclass, bases);\n        if (!metaclass)\n            goto error;\n\n        if (!_CPy_IsSafeMetaClass(metaclass)) {\n            PyErr_SetString(PyExc_TypeError, \"mypyc classes can't have a metaclass\");\n            goto error;\n        }\n    }\n\n    name = PyUnicode_FromString(template_->tp_name);\n    if (!name)\n        goto error;\n\n    if (template_->tp_doc) {\n        // cpython expects tp_doc to be heap-allocated so convert it here to\n        // avoid segfaults on deallocation.\n        Py_ssize_t size = strlen(template_->tp_doc) + 1;\n        char *doc = (char *)PyMem_Malloc(size);\n        if (!doc)\n            goto error;\n        memcpy(doc, template_->tp_doc, size);\n        template_->tp_doc = doc;\n    }\n\n    // Allocate the type and then copy the main stuff in.\n    t = (PyHeapTypeObject*)PyType_GenericAlloc(&PyType_Type, 0);\n    if (!t)\n        goto error;\n    memcpy((char *)t + sizeof(PyVarObject),\n           (char *)template_ + sizeof(PyVarObject),\n           sizeof(PyTypeObject) - sizeof(PyVarObject));\n\n    if (bases != orig_bases) {\n        if (PyObject_SetAttr((PyObject *)t, mypyc_interned_str.__orig_bases__, orig_bases) < 0)\n            goto error;\n    }\n\n    // Having tp_base set is I think required for stuff to get\n    // inherited in PyType_Ready, which we needed for subclassing\n    // BaseException. XXX: Taking the first element is wrong I think though.\n    if (bases) {\n        t->ht_type.tp_base = (PyTypeObject *)PyTuple_GET_ITEM(bases, 0);\n        Py_INCREF((PyObject *)t->ht_type.tp_base);\n    }\n\n    t->ht_name = name;\n    Py_INCREF(name);\n    t->ht_qualname = name;\n    t->ht_type.tp_bases = bases;\n    // references stolen so NULL these out\n    bases = name = NULL;\n\n    if (PyType_Ready((PyTypeObject *)t) < 0)\n        goto error;\n\n    assert(t->ht_type.tp_base != NULL);\n\n    // XXX: This is a terrible hack to work around a cpython check on\n    // the mro. It was needed for mypy.stats. I need to investigate\n    // what is actually going on here.\n    Py_INCREF(metaclass);\n    Py_SET_TYPE(t, metaclass);\n\n    if (dummy_class) {\n        if (PyDict_Merge(t->ht_type.tp_dict, dummy_class->tp_dict, 0) != 0)\n            goto error;\n        // This is the *really* tasteless bit. GenericMeta's __new__\n        // in certain versions of typing sets _gorg to point back to\n        // the class. We need to override it to keep it from pointing\n        // to the proxy.\n        if (PyDict_SetItemString(t->ht_type.tp_dict, \"_gorg\", (PyObject *)t) < 0)\n            goto error;\n    }\n\n    // Reject anything that would give us a nontrivial __slots__,\n    // because the layout will conflict\n    slots = PyObject_GetAttr((PyObject *)t, mypyc_interned_str.__slots__);\n    if (slots) {\n        // don't fail on an empty __slots__\n        int is_true = PyObject_IsTrue(slots);\n        Py_DECREF(slots);\n        if (is_true > 0)\n            PyErr_SetString(PyExc_TypeError, \"mypyc classes can't have __slots__\");\n        if (is_true != 0)\n            goto error;\n    } else {\n        PyErr_Clear();\n    }\n\n    if (PyObject_SetAttr((PyObject *)t, mypyc_interned_str.__module__, modname) < 0)\n        goto error;\n\n    Py_XDECREF(dummy_class);\n\n    // Unlike the tp_doc slots of most other object, a heap type's tp_doc\n    // must be heap allocated.\n    if (template_->tp_doc) {\n        // Silently truncate the docstring if it contains a null byte\n        Py_ssize_t size = strlen(template_->tp_doc) + 1;\n        char *tp_doc = (char *)PyMem_Malloc(size);\n        if (tp_doc == NULL) {\n            PyErr_NoMemory();\n            goto error;\n        }\n\n        memcpy(tp_doc, template_->tp_doc, size);\n        t->ht_type.tp_doc = tp_doc;\n    }\n\n#if PY_MINOR_VERSION == 11\n    // This is a hack. Python 3.11 doesn't include good public APIs to work with managed\n    // dicts, which are the default for heap types. So we try to opt-out until Python 3.12.\n    t->ht_type.tp_flags &= ~Py_TPFLAGS_MANAGED_DICT;\n#endif\n    return (PyObject *)t;\n\nerror:\n    Py_XDECREF(t);\n    Py_XDECREF(bases);\n    Py_XDECREF(dummy_class);\n    Py_XDECREF(name);\n    return NULL;\n}\n\n// Call __init_subclass__ on the appropriate base class of type.\n// This is separated from CPyType_FromTemplate so that class attributes\n// can be set before __init_subclass__ is called.\nbool CPy_InitSubclass(PyObject *type) {\n    if (init_subclass((PyTypeObject *)type, NULL)) {\n        return false;\n    }\n    return true;\n}\n\nstatic int _CPy_UpdateObjFromDict(PyObject *obj, PyObject *dict)\n{\n    Py_ssize_t pos = 0;\n    PyObject *key, *value;\n    while (PyDict_Next(dict, &pos, &key, &value)) {\n        if (PyObject_SetAttr(obj, key, value) != 0) {\n            return -1;\n        }\n    }\n    return 0;\n}\n\n/* Support for our partial built-in support for dataclasses.\n *\n * Take a class we want to make a dataclass, remove any descriptors\n * for annotated attributes, swap in the actual values of the class\n * variables invoke dataclass, and then restore all of the\n * descriptors.\n *\n * The purpose of all this is that dataclasses uses the values of\n * class variables to drive which attributes are required and what the\n * default values/factories are for optional attributes. This means\n * that the class dict needs to contain those values instead of getset\n * descriptors for the attributes when we invoke dataclass.\n *\n * We need to remove descriptors for attributes even when there is no\n * default value for them, or else dataclass will think the descriptor\n * is the default value. We remove only the attributes, since we don't\n * want dataclasses to try generating functions when they are already\n * implemented.\n *\n * Args:\n *   dataclass_dec: The decorator to apply\n *   tp: The class we are making a dataclass\n *   dict: The dictionary containing values that dataclasses needs\n *   annotations: The type annotation dictionary\n *   dataclass_type: A str object with the return value of util.py:dataclass_type()\n */\nint\nCPyDataclass_SleightOfHand(PyObject *dataclass_dec, PyObject *tp,\n                           PyObject *dict, PyObject *annotations,\n                           PyObject *dataclass_type) {\n    PyTypeObject *ttp = (PyTypeObject *)tp;\n    Py_ssize_t pos;\n    PyObject *res = NULL;\n\n    /* Make a copy of the original class __dict__ */\n    PyObject *orig_dict = PyDict_Copy(ttp->tp_dict);\n    if (!orig_dict) {\n        goto fail;\n    }\n\n    /* Delete anything that had an annotation */\n    pos = 0;\n    PyObject *key;\n    while (PyDict_Next(annotations, &pos, &key, NULL)) {\n        // Check and delete key. Key may be absent from tp for InitVar variables.\n        if (PyObject_HasAttr(tp, key) == 1 && PyObject_DelAttr(tp, key) != 0) {\n            goto fail;\n        }\n    }\n\n    /* Copy in all the attributes that we want dataclass to see */\n    if (_CPy_UpdateObjFromDict(tp, dict) != 0) {\n        goto fail;\n    }\n\n    /* Run the @dataclass descriptor */\n    res = PyObject_CallOneArg(dataclass_dec, tp);\n    if (!res) {\n        goto fail;\n    }\n    const char *dataclass_type_ptr = PyUnicode_AsUTF8(dataclass_type);\n    if (dataclass_type_ptr == NULL) {\n        goto fail;\n    }\n    if (strcmp(dataclass_type_ptr, \"attr\") == 0 ||\n        strcmp(dataclass_type_ptr, \"attr-auto\") == 0) {\n        // These attributes are added or modified by @attr.s(slots=True).\n        const char * const keys[] = {\"__attrs_attrs__\", \"__attrs_own_setattr__\", \"__init__\", \"\"};\n        for (const char * const *key_iter = keys; **key_iter != '\\0'; key_iter++) {\n            PyObject *value = NULL;\n            int rv = PyObject_GetOptionalAttrString(res, *key_iter, &value);\n            if (rv == 1) {\n                PyObject_SetAttrString(tp, *key_iter, value);\n                Py_DECREF(value);\n            } else if (rv == -1) {\n              goto fail;\n            }\n        }\n    }\n\n    /* Copy back the original contents of the dict */\n    if (_CPy_UpdateObjFromDict(tp, orig_dict) != 0) {\n        goto fail;\n    }\n\n    Py_DECREF(res);\n    Py_DECREF(orig_dict);\n    return 1;\n\nfail:\n    Py_XDECREF(res);\n    Py_XDECREF(orig_dict);\n    return 0;\n}\n\n// Support for pickling; reusable getstate and setstate functions\nPyObject *\nCPyPickle_SetState(PyObject *obj, PyObject *state)\n{\n    if (_CPy_UpdateObjFromDict(obj, state) != 0) {\n        return NULL;\n    }\n    Py_RETURN_NONE;\n}\n\nPyObject *\nCPyPickle_GetState(PyObject *obj)\n{\n    PyObject *attrs = NULL, *state = NULL;\n\n    attrs = PyObject_GetAttr((PyObject *)Py_TYPE(obj), mypyc_interned_str.__mypyc_attrs__);\n    if (!attrs) {\n        goto fail;\n    }\n    if (!PyTuple_Check(attrs)) {\n        PyErr_SetString(PyExc_TypeError, \"__mypyc_attrs__ is not a tuple\");\n        goto fail;\n    }\n    state = PyDict_New();\n    if (!state) {\n        goto fail;\n    }\n\n    // Collect all the values of attributes in __mypyc_attrs__\n    // Attributes that are missing we just ignore\n    int i;\n    for (i = 0; i < PyTuple_GET_SIZE(attrs); i++) {\n        PyObject *key = PyTuple_GET_ITEM(attrs, i);\n        PyObject *value = PyObject_GetAttr(obj, key);\n        if (!value) {\n            if (PyErr_ExceptionMatches(PyExc_AttributeError)) {\n                PyErr_Clear();\n                continue;\n            }\n            goto fail;\n        }\n        int result = PyDict_SetItem(state, key, value);\n        Py_DECREF(value);\n        if (result != 0) {\n            goto fail;\n        }\n    }\n\n    Py_DECREF(attrs);\n\n    return state;\nfail:\n    Py_XDECREF(attrs);\n    Py_XDECREF(state);\n    return NULL;\n}\n\nCPyTagged CPyTagged_Id(PyObject *o) {\n    return CPyTagged_FromVoidPtr(o);\n}\n\n#define MAX_INT_CHARS 22\n#define _PyUnicode_LENGTH(op)                           \\\n    (((PyASCIIObject *)(op))->length)\n\n// using snprintf or PyUnicode_FromFormat was way slower than\n// boxing the int and calling PyObject_Str on it, so we implement our own\nstatic int fmt_ssize_t(char *out, Py_ssize_t n) {\n\tbool neg = n < 0;\n\tif (neg) n = -n;\n\n\t// buf gets filled backward and then we copy it forward\n\tchar buf[MAX_INT_CHARS];\n\tint i = 0;\n\tdo {\n\t\tbuf[i] = (n % 10) + '0';\n\t\tn /= 10;\n\t\ti++;\n\t} while (n);\n\n\n\tint len = i;\n\tint j = 0;\n\tif (neg) {\n\t\tout[j++] = '-';\n\t\tlen++;\n\t}\n\n\tfor (; j < len; j++, i--) {\n\t\tout[j] = buf[i-1];\n\t}\n\tout[j] = '\\0';\n\n\treturn len;\n}\n\nstatic PyObject *CPyTagged_ShortToStr(Py_ssize_t n) {\n    PyObject *obj = PyUnicode_New(MAX_INT_CHARS, 127);\n    if (!obj) return NULL;\n    int len = fmt_ssize_t((char *)PyUnicode_1BYTE_DATA(obj), n);\n    _PyUnicode_LENGTH(obj) = len;\n    return obj;\n}\n\nPyObject *CPyTagged_Str(CPyTagged n) {\n    if (CPyTagged_CheckShort(n)) {\n        return CPyTagged_ShortToStr(CPyTagged_ShortAsSsize_t(n));\n    } else {\n        return PyObject_Str(CPyTagged_AsObject(n));\n    }\n}\n\nstatic PyObject *CPyTagged_ShortToAsciiBytes(Py_ssize_t n) {\n    PyObject *obj = PyBytes_FromStringAndSize(NULL, MAX_INT_CHARS);\n    if (!obj) return NULL;\n    int len = fmt_ssize_t(PyBytes_AsString(obj), n);\n    Py_SET_SIZE(obj, len);\n    return obj;\n}\n\nPyObject *CPyTagged_AsciiBytes(CPyTagged n) {\n    if (CPyTagged_CheckShort(n)) {\n        return CPyTagged_ShortToAsciiBytes(CPyTagged_ShortAsSsize_t(n));\n    }\n    PyObject *str = PyObject_Str(CPyTagged_AsObject(n));\n    PyObject *bytes = PyUnicode_AsASCIIString(str);\n    CPy_DECREF(str);\n    return bytes;\n}\n\nvoid CPyDebug_Print(const char *msg) {\n    printf(\"%s\\n\", msg);\n    fflush(stdout);\n}\n\nvoid CPyDebug_PrintObject(PyObject *obj) {\n    // Printing can cause errors. We don't want this to affect any existing\n    // state so we'll save any existing error and restore it at the end.\n    PyObject *exc_type, *exc_value, *exc_traceback;\n    PyErr_Fetch(&exc_type, &exc_value, &exc_traceback);\n\n    if (PyObject_Print(obj, stderr, 0) == -1) {\n        PyErr_Print();\n    } else {\n        fprintf(stderr, \"\\n\");\n    }\n    fflush(stderr);\n\n    PyErr_Restore(exc_type, exc_value, exc_traceback);\n}\n\nint CPySequence_CheckUnpackCount(PyObject *sequence, Py_ssize_t expected) {\n    Py_ssize_t actual = Py_SIZE(sequence);\n    if (unlikely(actual != expected)) {\n        if (actual < expected) {\n            PyErr_Format(PyExc_ValueError, \"not enough values to unpack (expected %zd, got %zd)\",\n                         expected, actual);\n        } else {\n            PyErr_Format(PyExc_ValueError, \"too many values to unpack (expected %zd)\", expected);\n        }\n        return -1;\n    }\n    return 0;\n}\n\n// Parse an integer (size_t) encoded as a variable-length binary sequence.\nstatic const char *parse_int(const char *s, size_t *len) {\n    Py_ssize_t n = 0;\n    while ((unsigned char)*s >= 0x80) {\n        n = (n << 7) + (*s & 0x7f);\n        s++;\n    }\n    n = (n << 7) | *s++;\n    *len = n;\n    return s;\n}\n\n// Initialize static constant array of literal values\nint CPyStatics_Initialize(PyObject **statics,\n                          const char * const *strings,\n                          const char * const *bytestrings,\n                          const char * const *ints,\n                          const double *floats,\n                          const double *complex_numbers,\n                          const int *tuples,\n                          const int *frozensets) {\n    PyObject **result = statics;\n    // Start with some hard-coded values\n    *result++ = Py_None;\n    Py_INCREF(Py_None);\n    *result++ = Py_False;\n    Py_INCREF(Py_False);\n    *result++ = Py_True;\n    Py_INCREF(Py_True);\n    if (strings) {\n        for (; **strings != '\\0'; strings++) {\n            size_t num;\n            const char *data = *strings;\n            data = parse_int(data, &num);\n            while (num-- > 0) {\n                size_t len;\n                data = parse_int(data, &len);\n                PyObject *obj = PyUnicode_DecodeUTF8(data, len, \"surrogatepass\");\n                if (obj == NULL) {\n                    return -1;\n                }\n                PyUnicode_InternInPlace(&obj);\n                *result++ = obj;\n                data += len;\n            }\n        }\n    }\n    if (bytestrings) {\n        for (; **bytestrings != '\\0'; bytestrings++) {\n            size_t num;\n            const char *data = *bytestrings;\n            data = parse_int(data, &num);\n            while (num-- > 0) {\n                size_t len;\n                data = parse_int(data, &len);\n                PyObject *obj = PyBytes_FromStringAndSize(data, len);\n                if (obj == NULL) {\n                    return -1;\n                }\n                *result++ = obj;\n                data += len;\n            }\n        }\n    }\n    if (ints) {\n        for (; **ints != '\\0'; ints++) {\n            size_t num;\n            const char *data = *ints;\n            data = parse_int(data, &num);\n            while (num-- > 0) {\n                char *end;\n                PyObject *obj = PyLong_FromString(data, &end, 10);\n                if (obj == NULL) {\n                    return -1;\n                }\n                data = end;\n                data++;\n                *result++ = obj;\n            }\n        }\n    }\n    if (floats) {\n        size_t num = (size_t)*floats++;\n        while (num-- > 0) {\n            PyObject *obj = PyFloat_FromDouble(*floats++);\n            if (obj == NULL) {\n                return -1;\n            }\n            *result++ = obj;\n        }\n    }\n    if (complex_numbers) {\n        size_t num = (size_t)*complex_numbers++;\n        while (num-- > 0) {\n            double real = *complex_numbers++;\n            double imag = *complex_numbers++;\n            PyObject *obj = PyComplex_FromDoubles(real, imag);\n            if (obj == NULL) {\n                return -1;\n            }\n            *result++ = obj;\n        }\n    }\n    if (tuples) {\n        int num = *tuples++;\n        while (num-- > 0) {\n            int num_items = *tuples++;\n            PyObject *obj = PyTuple_New(num_items);\n            if (obj == NULL) {\n                return -1;\n            }\n            int i;\n            for (i = 0; i < num_items; i++) {\n                PyObject *item = statics[*tuples++];\n                Py_INCREF(item);\n                PyTuple_SET_ITEM(obj, i, item);\n            }\n            *result++ = obj;\n        }\n    }\n    if (frozensets) {\n        int num = *frozensets++;\n        while (num-- > 0) {\n            int num_items = *frozensets++;\n            PyObject *obj = PyFrozenSet_New(NULL);\n            if (obj == NULL) {\n                return -1;\n            }\n            for (int i = 0; i < num_items; i++) {\n                PyObject *item = statics[*frozensets++];\n                Py_INCREF(item);\n                if (PySet_Add(obj, item) == -1) {\n                    return -1;\n                }\n            }\n            *result++ = obj;\n        }\n    }\n    return 0;\n}\n\n// Call super(type(self), self)\nPyObject *\nCPy_Super(PyObject *builtins, PyObject *self) {\n    PyObject *super_type = PyObject_GetAttr(builtins, mypyc_interned_str.super);\n    if (!super_type)\n        return NULL;\n    PyObject *result = PyObject_CallFunctionObjArgs(\n        super_type, (PyObject*)Py_TYPE(self), self, NULL);\n    Py_DECREF(super_type);\n    return result;\n}\n\nstatic bool import_single(PyObject *mod_id, PyObject **mod_static,\n                          PyObject *globals_id, PyObject *globals_name, PyObject *globals) {\n    if (Py_IsNone(*mod_static)) {\n        CPyModule *mod = PyImport_Import(mod_id);\n        if (mod == NULL) {\n            return false;\n        }\n        *mod_static = mod;\n    }\n\n    PyObject *mod_dict = PyImport_GetModuleDict();\n    CPyModule *globals_mod = CPyDict_GetItem(mod_dict, globals_id);\n    if (globals_mod == NULL) {\n        return false;\n    }\n    int ret = CPyDict_SetItem(globals, globals_name, globals_mod);\n    Py_DECREF(globals_mod);\n    if (ret < 0) {\n        return false;\n    }\n\n    return true;\n}\n\n// Table-driven import helper. See transform_import() in irbuild for the details.\nbool CPyImport_ImportMany(PyObject *modules, CPyModule **statics[], PyObject *globals,\n                          PyObject *tb_path, PyObject *tb_function, Py_ssize_t *tb_lines) {\n    for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(modules); i++) {\n        PyObject *module = PyTuple_GET_ITEM(modules, i);\n        PyObject *mod_id = PyTuple_GET_ITEM(module, 0);\n        PyObject *globals_id = PyTuple_GET_ITEM(module, 1);\n        PyObject *globals_name = PyTuple_GET_ITEM(module, 2);\n\n        if (!import_single(mod_id, statics[i], globals_id, globals_name, globals)) {\n            assert(PyErr_Occurred() && \"error indicator should be set on bad import!\");\n            PyObject *typ, *val, *tb;\n            PyErr_Fetch(&typ, &val, &tb);\n            const char *path = PyUnicode_AsUTF8(tb_path);\n            if (path == NULL) {\n                path = \"<unable to display>\";\n            }\n            const char *function = PyUnicode_AsUTF8(tb_function);\n            if (function == NULL) {\n                function = \"<unable to display>\";\n            }\n            PyErr_Restore(typ, val, tb);\n            CPy_AddTraceback(path, function, tb_lines[i], globals);\n            return false;\n        }\n    }\n    return true;\n}\n\n// This helper function is a simplification of cpython/ceval.c/import_from()\nstatic PyObject *CPyImport_ImportFrom(PyObject *module, PyObject *package_name,\n                                      PyObject *import_name, PyObject *as_name) {\n    // check if the imported module has an attribute by that name\n    PyObject *x = PyObject_GetAttr(module, import_name);\n    if (x == NULL) {\n        // if not, attempt to import a submodule with that name\n        PyObject *fullmodname = PyUnicode_FromFormat(\"%U.%U\", package_name, import_name);\n        if (fullmodname == NULL) {\n            goto fail;\n        }\n\n        // The following code is a simplification of cpython/import.c/PyImport_GetModule()\n        x = PyObject_GetItem(module, fullmodname);\n        Py_DECREF(fullmodname);\n        if (x == NULL) {\n            goto fail;\n        }\n    }\n    return x;\n\nfail:\n    PyErr_Clear();\n    PyObject *package_path = PyModule_GetFilenameObject(module);\n    PyObject *errmsg = PyUnicode_FromFormat(\"cannot import name %R from %R (%S)\",\n                                            import_name, package_name, package_path);\n    // NULL checks for errmsg and package_name done by PyErr_SetImportError.\n    PyErr_SetImportError(errmsg, package_name, package_path);\n    Py_DECREF(package_path);\n    Py_DECREF(errmsg);\n    return NULL;\n}\n\nPyObject *CPyImport_ImportFromMany(PyObject *mod_id, PyObject *names, PyObject *as_names,\n                                   PyObject *globals) {\n    PyObject *mod = PyImport_ImportModuleLevelObject(mod_id, globals, 0, names, 0);\n    if (mod == NULL) {\n        return NULL;\n    }\n\n    for (Py_ssize_t i = 0; i < PyTuple_GET_SIZE(names); i++) {\n        PyObject *name = PyTuple_GET_ITEM(names, i);\n        PyObject *as_name = PyTuple_GET_ITEM(as_names, i);\n        PyObject *obj = CPyImport_ImportFrom(mod, mod_id, name, as_name);\n        if (obj == NULL) {\n            Py_DECREF(mod);\n            return NULL;\n        }\n        int ret = CPyDict_SetItem(globals, as_name, obj);\n        Py_DECREF(obj);\n        if (ret < 0) {\n            Py_DECREF(mod);\n            return NULL;\n        }\n    }\n    return mod;\n}\n\n// From CPython\nstatic PyObject *\nCPy_BinopTypeError(PyObject *left, PyObject *right, const char *op) {\n    PyErr_Format(PyExc_TypeError,\n                 \"unsupported operand type(s) for %.100s: \"\n                 \"'%.100s' and '%.100s'\",\n                 op,\n                 Py_TYPE(left)->tp_name,\n                 Py_TYPE(right)->tp_name);\n    return NULL;\n}\n\nPyObject *\nCPy_CallReverseOpMethod(PyObject *left,\n                        PyObject *right,\n                        const char *op,\n                        PyObject *method) {\n    // Look up reverse method\n    PyObject *m = PyObject_GetAttr(right, method);\n    if (m == NULL) {\n        // If reverse method not defined, generate TypeError instead AttributeError\n        if (PyErr_ExceptionMatches(PyExc_AttributeError)) {\n            CPy_BinopTypeError(left, right, op);\n        }\n        return NULL;\n    }\n    // Call reverse method\n    PyObject *result = PyObject_CallOneArg(m, left);\n    Py_DECREF(m);\n    return result;\n}\n\nPyObject *CPySingledispatch_RegisterFunction(PyObject *singledispatch_func,\n                                             PyObject *cls,\n                                             PyObject *func) {\n    PyObject *registry = PyObject_GetAttr(singledispatch_func, mypyc_interned_str.registry);\n    PyObject *register_func = NULL;\n    PyObject *typing = NULL;\n    PyObject *get_type_hints = NULL;\n    PyObject *type_hints = NULL;\n\n    if (registry == NULL) goto fail;\n    if (func == NULL) {\n        // one argument case\n        if (PyType_Check(cls)) {\n            // passed a class\n            // bind cls to the first argument so that register gets called again with both the\n            // class and the function\n            register_func = PyObject_GetAttr(singledispatch_func, mypyc_interned_str.register_);\n            if (register_func == NULL) goto fail;\n            return PyMethod_New(register_func, cls);\n        }\n        // passed a function\n        PyObject *annotations = PyFunction_GetAnnotations(cls);\n        const char *invalid_first_arg_msg =\n            \"Invalid first argument to `register()`: %R. \"\n            \"Use either `@register(some_class)` or plain `@register` \"\n            \"on an annotated function.\";\n\n        if (annotations == NULL) {\n            PyErr_Format(PyExc_TypeError, invalid_first_arg_msg, cls);\n            goto fail;\n        }\n\n        Py_INCREF(annotations);\n\n        func = cls;\n        typing = PyImport_ImportModule(\"typing\");\n        if (typing == NULL) goto fail;\n        get_type_hints = PyObject_GetAttr(typing, mypyc_interned_str.get_type_hints);\n\n        type_hints = PyObject_CallOneArg(get_type_hints, func);\n        PyObject *argname;\n        Py_ssize_t pos = 0;\n        if (!PyDict_Next(type_hints, &pos, &argname, &cls)) {\n            // the functools implementation raises the same type error if annotations is an empty dict\n            PyErr_Format(PyExc_TypeError, invalid_first_arg_msg, cls);\n            goto fail;\n        }\n        if (!PyType_Check(cls)) {\n            const char *invalid_annotation_msg = \"Invalid annotation for %R. %R is not a class.\";\n            PyErr_Format(PyExc_TypeError, invalid_annotation_msg, argname, cls);\n            goto fail;\n        }\n    }\n    if (PyDict_SetItem(registry, cls, func) == -1) {\n        goto fail;\n    }\n\n    // clear the cache so we consider the newly added function when dispatching\n    PyObject *dispatch_cache = PyObject_GetAttr(singledispatch_func, mypyc_interned_str.dispatch_cache);\n    if (dispatch_cache == NULL) goto fail;\n    PyDict_Clear(dispatch_cache);\n\n    Py_INCREF(func);\n    return func;\n\nfail:\n    Py_XDECREF(registry);\n    Py_XDECREF(register_func);\n    Py_XDECREF(typing);\n    Py_XDECREF(get_type_hints);\n    Py_XDECREF(type_hints);\n    return NULL;\n\n}\n\n// Adapted from ceval.c GET_AITER\nPyObject *CPy_GetAIter(PyObject *obj)\n{\n    unaryfunc getter = NULL;\n    PyTypeObject *type = Py_TYPE(obj);\n\n    if (type->tp_as_async != NULL) {\n        getter = type->tp_as_async->am_aiter;\n    }\n\n    if (getter == NULL) {\n        PyErr_Format(PyExc_TypeError,\n                     \"'async for' requires an object with \"\n                     \"__aiter__ method, got %.100s\",\n                     type->tp_name);\n        Py_DECREF(obj);\n        return NULL;\n    }\n\n    PyObject *iter = (*getter)(obj);\n    if (!iter) {\n        return NULL;\n    }\n\n    if (Py_TYPE(iter)->tp_as_async == NULL ||\n        Py_TYPE(iter)->tp_as_async->am_anext == NULL) {\n\n        PyErr_Format(PyExc_TypeError,\n                     \"'async for' received an object from __aiter__ \"\n                     \"that does not implement __anext__: %.100s\",\n                     Py_TYPE(iter)->tp_name);\n        Py_DECREF(iter);\n        return NULL;\n    }\n\n    return iter;\n}\n\n// Adapted from ceval.c GET_ANEXT\nPyObject *CPy_GetANext(PyObject *aiter)\n{\n    unaryfunc getter = NULL;\n    PyObject *next_iter = NULL;\n    PyObject *awaitable = NULL;\n    PyTypeObject *type = Py_TYPE(aiter);\n\n    if (PyAsyncGen_CheckExact(aiter)) {\n        awaitable = type->tp_as_async->am_anext(aiter);\n        if (awaitable == NULL) {\n            goto error;\n        }\n    } else {\n        if (type->tp_as_async != NULL){\n            getter = type->tp_as_async->am_anext;\n        }\n\n        if (getter != NULL) {\n            next_iter = (*getter)(aiter);\n            if (next_iter == NULL) {\n                goto error;\n            }\n        }\n        else {\n            PyErr_Format(PyExc_TypeError,\n                         \"'async for' requires an iterator with \"\n                         \"__anext__ method, got %.100s\",\n                         type->tp_name);\n            goto error;\n        }\n\n        awaitable = CPyCoro_GetAwaitableIter(next_iter);\n        if (awaitable == NULL) {\n            _PyErr_FormatFromCause(\n                PyExc_TypeError,\n                \"'async for' received an invalid object \"\n                \"from __anext__: %.100s\",\n                Py_TYPE(next_iter)->tp_name);\n\n            Py_DECREF(next_iter);\n            goto error;\n        } else {\n            Py_DECREF(next_iter);\n        }\n    }\n\n    return awaitable;\nerror:\n    return NULL;\n}\n\n#if CPY_3_11_FEATURES\n\n// Return obj.__name__ (specialized to type objects, which are the most common target).\nPyObject *CPy_GetName(PyObject *obj) {\n    if (PyType_Check(obj)) {\n        return PyType_GetName((PyTypeObject *)obj);\n    }\n    return PyObject_GetAttr(obj, mypyc_interned_str.__name__);\n}\n\n#endif\n\n#ifdef MYPYC_LOG_TRACE\n\n// This is only compiled in if trace logging is enabled by user\n\nstatic int TraceCounter = 0;\nstatic const int TRACE_EVERY_NTH = 1009;  // Should be a prime number\n#define TRACE_LOG_FILE_NAME \"mypyc_trace.txt\"\nstatic FILE *TraceLogFile = NULL;\n\n// Log a tracing event on every Nth call\nvoid CPyTrace_LogEvent(const char *location, const char *line, const char *op, const char *details) {\n    if (TraceLogFile == NULL) {\n        if ((TraceLogFile = fopen(TRACE_LOG_FILE_NAME, \"w\")) == NULL) {\n            fprintf(stderr, \"error: Could not open trace file %s\\n\", TRACE_LOG_FILE_NAME);\n            abort();\n        }\n    }\n    if (TraceCounter == 0) {\n        fprintf(TraceLogFile, \"%s:%s:%s:%s\\n\", location, line, op, details);\n    }\n    TraceCounter++;\n    if (TraceCounter == TRACE_EVERY_NTH) {\n        TraceCounter = 0;\n    }\n}\n\n#endif\n\n#if CPY_3_12_FEATURES\n\n// Copied from Python 3.12.3, since this struct is internal to CPython. It defines\n// the structure of typing.TypeAliasType objects. We need it since compute_value is\n// not part of the public API, and we need to set it to match Python runtime semantics.\n//\n// IMPORTANT: This needs to be kept in sync with CPython!\ntypedef struct {\n    PyObject_HEAD\n    PyObject *name;\n    PyObject *type_params;\n    PyObject *compute_value;\n    PyObject *value;\n    PyObject *module;\n} typealiasobject;\n\nvoid CPy_SetTypeAliasTypeComputeFunction(PyObject *alias, PyObject *compute_value) {\n    typealiasobject *obj = (typealiasobject *)alias;\n    if (obj->value != NULL) {\n        Py_DECREF(obj->value);\n    }\n    obj->value = NULL;\n    Py_INCREF(compute_value);\n    if (obj->compute_value != NULL) {\n        Py_DECREF(obj->compute_value);\n    }\n    obj->compute_value = compute_value;\n}\n\n#endif\n\n#if CPY_3_14_FEATURES\n\n#include \"internal/pycore_object.h\"\n\nvoid CPy_SetImmortal(PyObject *obj) {\n    _Py_SetImmortal(obj);\n}\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/module_shim.tmpl",
    "content": "#include <Python.h>\n\nPyMODINIT_FUNC\nPyInit_{modname}(void)\n{{\n    PyObject *tmp;\n    if (!(tmp = PyImport_ImportModule(\"{libname}\"))) return NULL;\n    PyObject *capsule = PyObject_GetAttrString(tmp, \"init_{full_modname}\");\n    Py_DECREF(tmp);\n    if (capsule == NULL) return NULL;\n    void *init_func = PyCapsule_GetPointer(capsule, \"{libname}.init_{full_modname}\");\n    Py_DECREF(capsule);\n    if (!init_func) {{\n        return NULL;\n    }}\n    return ((PyObject *(*)(void))init_func)();\n}}\n\n// distutils sometimes spuriously tells cl to export CPyInit___init__,\n// so provide that so it chills out\nPyMODINIT_FUNC PyInit___init__(void) {{ return PyInit_{modname}(); }}\n"
  },
  {
    "path": "mypyc/lib-rt/module_shim_no_gil_multiphase.tmpl",
    "content": "#include <Python.h>\n\nstatic int {modname}_exec(PyObject *module)\n{{\n    PyObject *tmp;\n    if (!(tmp = PyImport_ImportModule(\"{libname}\"))) return -1;\n    PyObject *capsule = PyObject_GetAttrString(tmp, \"exec_{full_modname}\");\n    Py_DECREF(tmp);\n    if (capsule == NULL) return -1;\n    void *exec_func = PyCapsule_GetPointer(capsule, \"{libname}.exec_{full_modname}\");\n    Py_DECREF(capsule);\n    if (!exec_func) return -1;\n    if (((int (*)(PyObject *))exec_func)(module) != 0) return -1;\n    return 0;\n}}\n\nstatic PyModuleDef_Slot {modname}_slots[] = {{\n    {{Py_mod_exec, {modname}_exec}},\n    {{Py_mod_multiple_interpreters, Py_MOD_MULTIPLE_INTERPRETERS_NOT_SUPPORTED}},\n    {{Py_mod_gil, Py_MOD_GIL_NOT_USED}},\n    {{0, NULL}},\n}};\n\nstatic struct PyModuleDef {modname}_module = {{\n    PyModuleDef_HEAD_INIT,\n    .m_name = \"{modname}\",\n    .m_doc = NULL,\n    .m_methods = NULL,\n    .m_size = 0,\n    .m_slots = {modname}_slots,\n}};\n\nPyMODINIT_FUNC\nPyInit_{modname}(void)\n{{\n    return PyModuleDef_Init(&{modname}_module);\n}}\n\n// distutils sometimes spuriously tells cl to export CPyInit___init__,\n// so provide that so it chills out\nPyMODINIT_FUNC PyInit___init__(void) {{ return PyInit_{modname}(); }}\n"
  },
  {
    "path": "mypyc/lib-rt/mypyc_util.h",
    "content": "#ifndef MYPYC_UTIL_H\n#define MYPYC_UTIL_H\n\n#include <Python.h>\n#include <frameobject.h>\n#include <assert.h>\n\n#if defined(__clang__) || defined(__GNUC__)\n#define likely(x)       __builtin_expect((x),1)\n#define unlikely(x)     __builtin_expect((x),0)\n#define CPy_Unreachable() __builtin_unreachable()\n#else\n#define likely(x)       (x)\n#define unlikely(x)     (x)\n#define CPy_Unreachable() abort()\n#endif\n\n#if defined(__clang__) || defined(__GNUC__)\n#define CPy_NOINLINE __attribute__((noinline))\n#elif defined(_MSC_VER)\n#define CPy_NOINLINE __declspec(noinline)\n#else\n#define CPy_NOINLINE\n#endif\n\n#ifndef Py_GIL_DISABLED\n\n// Everything is running in the same thread, so no need for thread locals\n#define CPyThreadLocal\n\n#else\n\n// 1. Use C11 standard thread_local storage, if available\n#if defined(__STDC_VERSION__)  && __STDC_VERSION__ >= 201112L && !defined(__STDC_NO_THREADS__)\n#define CPyThreadLocal _Thread_local\n\n// 2. Microsoft Visual Studio fallback\n#elif defined(_MSC_VER)\n#define CPyThreadLocal __declspec(thread)\n\n// 3. GNU thread local storage for GCC/Clang targets that still need it\n#elif defined(__GNUC__) || defined(__clang__)\n#define CPyThreadLocal __thread\n\n#else\n#error \"Can't define CPyThreadLocal for this compiler/target (consider using a non-free-threaded Python build)\"\n#endif\n\n#endif // Py_GIL_DISABLED\n\n// Helper macro for stringification in _Pragma\n#define CPY_STRINGIFY(x) #x\n\n#if defined(__clang__)\n    #define CPY_UNROLL_LOOP_IMPL(x) _Pragma(CPY_STRINGIFY(x))\n    #define CPY_UNROLL_LOOP(n) CPY_UNROLL_LOOP_IMPL(unroll n)\n#elif defined(__GNUC__) && __GNUC__ >= 8\n    #define CPY_UNROLL_LOOP_IMPL(x) _Pragma(CPY_STRINGIFY(x))\n    #define CPY_UNROLL_LOOP(n) CPY_UNROLL_LOOP_IMPL(GCC unroll n)\n#else\n    #define CPY_UNROLL_LOOP(n)\n#endif\n\n// INCREF and DECREF that assert the pointer is not NULL.\n// asserts are disabled in release builds so there shouldn't be a perf hit.\n// I'm honestly kind of surprised that this isn't done by default.\n#define CPy_INCREF(p) do { assert(p); Py_INCREF(p); } while (0)\n#define CPy_DECREF(p) do { assert(p); Py_DECREF(p); } while (0)\n// Here just for consistency\n#define CPy_XDECREF(p) Py_XDECREF(p)\n\n#ifndef Py_GIL_DISABLED\n\n// The *_NO_IMM operations below perform refcount manipulation for\n// non-immortal objects (Python 3.12 and later).\n//\n// Py_INCREF and other CPython operations check for immortality. This\n// can be expensive when we know that an object cannot be immortal.\n//\n// This optimization cannot be performed in free-threaded mode so we\n// fall back to just calling the normal incref/decref operations.\n\nstatic inline void CPy_INCREF_NO_IMM(PyObject *op)\n{\n    op->ob_refcnt++;\n}\n\nstatic inline void CPy_DECREF_NO_IMM(PyObject *op)\n{\n    if (--op->ob_refcnt == 0) {\n        _Py_Dealloc(op);\n    }\n}\n\nstatic inline void CPy_XDECREF_NO_IMM(PyObject *op)\n{\n    if (op != NULL && --op->ob_refcnt == 0) {\n        _Py_Dealloc(op);\n    }\n}\n\n#define CPy_INCREF_NO_IMM(op) CPy_INCREF_NO_IMM((PyObject *)(op))\n#define CPy_DECREF_NO_IMM(op) CPy_DECREF_NO_IMM((PyObject *)(op))\n#define CPy_XDECREF_NO_IMM(op) CPy_XDECREF_NO_IMM((PyObject *)(op))\n\n#else\n\n#define CPy_INCREF_NO_IMM(op) CPy_INCREF(op)\n#define CPy_DECREF_NO_IMM(op) CPy_DECREF(op)\n#define CPy_XDECREF_NO_IMM(op) CPy_XDECREF(op)\n\n#endif\n\n// Tagged integer -- our representation of Python 'int' objects.\n// Small enough integers are represented as unboxed integers (shifted\n// left by 1); larger integers (larger than 63 bits on a 64-bit\n// platform) are stored as a tagged pointer (PyObject *)\n// representing a Python int object, with the lowest bit set.\n// Tagged integers are always normalized. A small integer *must not*\n// have the tag bit set.\ntypedef size_t CPyTagged;\n\ntypedef size_t CPyPtr;\n\n#define CPY_INT_BITS (CHAR_BIT * sizeof(CPyTagged))\n\n#define CPY_TAGGED_MAX (((Py_ssize_t)1 << (CPY_INT_BITS - 2)) - 1)\n#define CPY_TAGGED_MIN (-((Py_ssize_t)1 << (CPY_INT_BITS - 2)))\n#define CPY_TAGGED_ABS_MIN (0-(size_t)CPY_TAGGED_MIN)\n\ntypedef PyObject CPyModule;\n\n// Tag bit used for long integers\n#define CPY_INT_TAG 1\n\n// Error value for signed fixed-width (low-level) integers\n#define CPY_LL_INT_ERROR -113\n\n// Error value for unsigned fixed-width (low-level) integers\n#define CPY_LL_UINT_ERROR 239\n\n// Error value for floats\n#define CPY_FLOAT_ERROR -113.0\n\n// Value for 'None' primitive type\n#define CPY_NONE_ERROR 2\n#define CPY_NONE 1\n\ntypedef void (*CPyVTableItem)(void);\n\nstatic inline CPyTagged CPyTagged_ShortFromInt(int x) {\n    return x << 1;\n}\n\nstatic inline CPyTagged CPyTagged_ShortFromSsize_t(Py_ssize_t x) {\n    return x << 1;\n}\n\n// Are we targeting Python 3.X or newer?\n#define CPY_3_11_FEATURES (PY_VERSION_HEX >= 0x030b0000)\n#define CPY_3_12_FEATURES (PY_VERSION_HEX >= 0x030c0000)\n#define CPY_3_14_FEATURES (PY_VERSION_HEX >= 0x030e0000)\n\n#if CPY_3_12_FEATURES\n\n// Same as macros in CPython internal/pycore_long.h, but with a CPY_ prefix\n#define CPY_NON_SIZE_BITS 3\n#define CPY_SIGN_ZERO 1\n#define CPY_SIGN_NEGATIVE 2\n#define CPY_SIGN_MASK 3\n\n#define CPY_LONG_DIGIT(o, n) ((o)->long_value.ob_digit[n])\n\n// Only available on Python 3.12 and later\n#define CPY_LONG_TAG(o) ((o)->long_value.lv_tag)\n#define CPY_LONG_IS_NEGATIVE(o) (((o)->long_value.lv_tag & CPY_SIGN_MASK) == CPY_SIGN_NEGATIVE)\n// Only available on Python 3.12 and later\n#define CPY_LONG_SIZE(o) ((o)->long_value.lv_tag >> CPY_NON_SIZE_BITS)\n// Number of digits; negative for negative ints\n#define CPY_LONG_SIZE_SIGNED(o) (CPY_LONG_IS_NEGATIVE(o) ? -CPY_LONG_SIZE(o) : CPY_LONG_SIZE(o))\n// Number of digits, assuming int is non-negative\n#define CPY_LONG_SIZE_UNSIGNED(o) CPY_LONG_SIZE(o)\n\n#else\n\n#define CPY_LONG_DIGIT(o, n) ((o)->ob_digit[n])\n#define CPY_LONG_IS_NEGATIVE(o) (((o)->ob_base.ob_size < 0)\n#define CPY_LONG_SIZE_SIGNED(o) ((o)->ob_base.ob_size)\n#define CPY_LONG_SIZE_UNSIGNED(o) ((o)->ob_base.ob_size)\n\n#endif\n\n// Are we targeting Python 3.13 or newer?\n#define CPY_3_13_FEATURES (PY_VERSION_HEX >= 0x030d0000)\n\n// Are we targeting Python 3.14 or newer?\n#define CPY_3_14_FEATURES (PY_VERSION_HEX >= 0x030e0000)\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/pythoncapi_compat.h",
    "content": "// Header file providing new C API functions to old Python versions.\n//\n// File distributed under the Zero Clause BSD (0BSD) license.\n// Copyright Contributors to the pythoncapi_compat project.\n//\n// Homepage:\n// https://github.com/python/pythoncapi_compat\n//\n// Latest version:\n// https://raw.githubusercontent.com/python/pythoncapi-compat/main/pythoncapi_compat.h\n//\n// SPDX-License-Identifier: 0BSD\n\n#ifndef PYTHONCAPI_COMPAT\n#define PYTHONCAPI_COMPAT\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n#include <Python.h>\n#include <stddef.h>               // offsetof()\n\n// Python 3.11.0b4 added PyFrame_Back() to Python.h\n#if PY_VERSION_HEX < 0x030b00B4 && !defined(PYPY_VERSION)\n#  include \"frameobject.h\"        // PyFrameObject, PyFrame_GetBack()\n#endif\n#if PY_VERSION_HEX < 0x030C00A3\n#  include <structmember.h>       // T_SHORT, READONLY\n#endif\n\n\n#ifndef _Py_CAST\n#  define _Py_CAST(type, expr) ((type)(expr))\n#endif\n\n// Static inline functions should use _Py_NULL rather than using directly NULL\n// to prevent C++ compiler warnings. On C23 and newer and on C++11 and newer,\n// _Py_NULL is defined as nullptr.\n#ifndef _Py_NULL\n#  if (defined (__STDC_VERSION__) && __STDC_VERSION__ > 201710L) \\\n          || (defined(__cplusplus) && __cplusplus >= 201103)\n#    define _Py_NULL nullptr\n#  else\n#    define _Py_NULL NULL\n#  endif\n#endif\n\n// Cast argument to PyObject* type.\n#ifndef _PyObject_CAST\n#  define _PyObject_CAST(op) _Py_CAST(PyObject*, op)\n#endif\n\n#ifndef Py_BUILD_ASSERT\n#  define Py_BUILD_ASSERT(cond) \\\n        do { \\\n            (void)sizeof(char [1 - 2 * !(cond)]); \\\n        } while(0)\n#endif\n\n\n// bpo-42262 added Py_NewRef() to Python 3.10.0a3\n#if PY_VERSION_HEX < 0x030A00A3 && !defined(Py_NewRef)\nstatic inline PyObject* _Py_NewRef(PyObject *obj)\n{\n    Py_INCREF(obj);\n    return obj;\n}\n#define Py_NewRef(obj) _Py_NewRef(_PyObject_CAST(obj))\n#endif\n\n\n// bpo-42262 added Py_XNewRef() to Python 3.10.0a3\n#if PY_VERSION_HEX < 0x030A00A3 && !defined(Py_XNewRef)\nstatic inline PyObject* _Py_XNewRef(PyObject *obj)\n{\n    Py_XINCREF(obj);\n    return obj;\n}\n#define Py_XNewRef(obj) _Py_XNewRef(_PyObject_CAST(obj))\n#endif\n\n\n// bpo-39573 added Py_SET_REFCNT() to Python 3.9.0a4\n#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_REFCNT)\nstatic inline void _Py_SET_REFCNT(PyObject *ob, Py_ssize_t refcnt)\n{\n    ob->ob_refcnt = refcnt;\n}\n#define Py_SET_REFCNT(ob, refcnt) _Py_SET_REFCNT(_PyObject_CAST(ob), refcnt)\n#endif\n\n\n// Py_SETREF() and Py_XSETREF() were added to Python 3.5.2.\n// It is excluded from the limited C API.\n#if (PY_VERSION_HEX < 0x03050200 && !defined(Py_SETREF)) && !defined(Py_LIMITED_API)\n#define Py_SETREF(dst, src)                                     \\\n    do {                                                        \\\n        PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \\\n        PyObject *_tmp_dst = (*_tmp_dst_ptr);                   \\\n        *_tmp_dst_ptr = _PyObject_CAST(src);                    \\\n        Py_DECREF(_tmp_dst);                                    \\\n    } while (0)\n\n#define Py_XSETREF(dst, src)                                    \\\n    do {                                                        \\\n        PyObject **_tmp_dst_ptr = _Py_CAST(PyObject**, &(dst)); \\\n        PyObject *_tmp_dst = (*_tmp_dst_ptr);                   \\\n        *_tmp_dst_ptr = _PyObject_CAST(src);                    \\\n        Py_XDECREF(_tmp_dst);                                   \\\n    } while (0)\n#endif\n\n\n// bpo-43753 added Py_Is(), Py_IsNone(), Py_IsTrue() and Py_IsFalse()\n// to Python 3.10.0b1.\n#if PY_VERSION_HEX < 0x030A00B1 && !defined(Py_Is)\n#  define Py_Is(x, y) ((x) == (y))\n#endif\n#if PY_VERSION_HEX < 0x030A00B1 && !defined(Py_IsNone)\n#  define Py_IsNone(x) Py_Is(x, Py_None)\n#endif\n#if (PY_VERSION_HEX < 0x030A00B1 || defined(PYPY_VERSION)) && !defined(Py_IsTrue)\n#  define Py_IsTrue(x) Py_Is(x, Py_True)\n#endif\n#if (PY_VERSION_HEX < 0x030A00B1 || defined(PYPY_VERSION)) && !defined(Py_IsFalse)\n#  define Py_IsFalse(x) Py_Is(x, Py_False)\n#endif\n\n\n// bpo-39573 added Py_SET_TYPE() to Python 3.9.0a4\n#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE)\nstatic inline void _Py_SET_TYPE(PyObject *ob, PyTypeObject *type)\n{\n    ob->ob_type = type;\n}\n#define Py_SET_TYPE(ob, type) _Py_SET_TYPE(_PyObject_CAST(ob), type)\n#endif\n\n\n// bpo-39573 added Py_SET_SIZE() to Python 3.9.0a4\n#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_SIZE)\nstatic inline void _Py_SET_SIZE(PyVarObject *ob, Py_ssize_t size)\n{\n    ob->ob_size = size;\n}\n#define Py_SET_SIZE(ob, size) _Py_SET_SIZE((PyVarObject*)(ob), size)\n#endif\n\n\n// bpo-40421 added PyFrame_GetCode() to Python 3.9.0b1\n#if PY_VERSION_HEX < 0x030900B1 || defined(PYPY_VERSION)\nstatic inline PyCodeObject* PyFrame_GetCode(PyFrameObject *frame)\n{\n    assert(frame != _Py_NULL);\n    assert(frame->f_code != _Py_NULL);\n    return _Py_CAST(PyCodeObject*, Py_NewRef(frame->f_code));\n}\n#endif\n\nstatic inline PyCodeObject* _PyFrame_GetCodeBorrow(PyFrameObject *frame)\n{\n    PyCodeObject *code = PyFrame_GetCode(frame);\n    Py_DECREF(code);\n    return code;\n}\n\n\n// bpo-40421 added PyFrame_GetBack() to Python 3.9.0b1\n#if PY_VERSION_HEX < 0x030900B1 && !defined(PYPY_VERSION)\nstatic inline PyFrameObject* PyFrame_GetBack(PyFrameObject *frame)\n{\n    assert(frame != _Py_NULL);\n    return _Py_CAST(PyFrameObject*, Py_XNewRef(frame->f_back));\n}\n#endif\n\n#if !defined(PYPY_VERSION)\nstatic inline PyFrameObject* _PyFrame_GetBackBorrow(PyFrameObject *frame)\n{\n    PyFrameObject *back = PyFrame_GetBack(frame);\n    Py_XDECREF(back);\n    return back;\n}\n#endif\n\n\n// bpo-40421 added PyFrame_GetLocals() to Python 3.11.0a7\n#if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION)\nstatic inline PyObject* PyFrame_GetLocals(PyFrameObject *frame)\n{\n#if PY_VERSION_HEX >= 0x030400B1\n    if (PyFrame_FastToLocalsWithError(frame) < 0) {\n        return NULL;\n    }\n#else\n    PyFrame_FastToLocals(frame);\n#endif\n    return Py_NewRef(frame->f_locals);\n}\n#endif\n\n\n// bpo-40421 added PyFrame_GetGlobals() to Python 3.11.0a7\n#if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION)\nstatic inline PyObject* PyFrame_GetGlobals(PyFrameObject *frame)\n{\n    return Py_NewRef(frame->f_globals);\n}\n#endif\n\n\n// bpo-40421 added PyFrame_GetBuiltins() to Python 3.11.0a7\n#if PY_VERSION_HEX < 0x030B00A7 && !defined(PYPY_VERSION)\nstatic inline PyObject* PyFrame_GetBuiltins(PyFrameObject *frame)\n{\n    return Py_NewRef(frame->f_builtins);\n}\n#endif\n\n\n// bpo-40421 added PyFrame_GetLasti() to Python 3.11.0b1\n#if PY_VERSION_HEX < 0x030B00B1 && !defined(PYPY_VERSION)\nstatic inline int PyFrame_GetLasti(PyFrameObject *frame)\n{\n#if PY_VERSION_HEX >= 0x030A00A7\n    // bpo-27129: Since Python 3.10.0a7, f_lasti is an instruction offset,\n    // not a bytes offset anymore. Python uses 16-bit \"wordcode\" (2 bytes)\n    // instructions.\n    if (frame->f_lasti < 0) {\n        return -1;\n    }\n    return frame->f_lasti * 2;\n#else\n    return frame->f_lasti;\n#endif\n}\n#endif\n\n\n// gh-91248 added PyFrame_GetVar() to Python 3.12.0a2\n#if PY_VERSION_HEX < 0x030C00A2 && !defined(PYPY_VERSION)\nstatic inline PyObject* PyFrame_GetVar(PyFrameObject *frame, PyObject *name)\n{\n    PyObject *locals, *value;\n\n    locals = PyFrame_GetLocals(frame);\n    if (locals == NULL) {\n        return NULL;\n    }\n#if PY_VERSION_HEX >= 0x03000000\n    value = PyDict_GetItemWithError(locals, name);\n#else\n    value = _PyDict_GetItemWithError(locals, name);\n#endif\n    Py_DECREF(locals);\n\n    if (value == NULL) {\n        if (PyErr_Occurred()) {\n            return NULL;\n        }\n#if PY_VERSION_HEX >= 0x03000000\n        PyErr_Format(PyExc_NameError, \"variable %R does not exist\", name);\n#else\n        PyErr_SetString(PyExc_NameError, \"variable does not exist\");\n#endif\n        return NULL;\n    }\n    return Py_NewRef(value);\n}\n#endif\n\n\n// gh-91248 added PyFrame_GetVarString() to Python 3.12.0a2\n#if PY_VERSION_HEX < 0x030C00A2 && !defined(PYPY_VERSION)\nstatic inline PyObject*\nPyFrame_GetVarString(PyFrameObject *frame, const char *name)\n{\n    PyObject *name_obj, *value;\n#if PY_VERSION_HEX >= 0x03000000\n    name_obj = PyUnicode_FromString(name);\n#else\n    name_obj = PyString_FromString(name);\n#endif\n    if (name_obj == NULL) {\n        return NULL;\n    }\n    value = PyFrame_GetVar(frame, name_obj);\n    Py_DECREF(name_obj);\n    return value;\n}\n#endif\n\n\n// bpo-39947 added PyThreadState_GetInterpreter() to Python 3.9.0a5\n#if PY_VERSION_HEX < 0x030900A5 || (defined(PYPY_VERSION) && PY_VERSION_HEX < 0x030B0000)\nstatic inline PyInterpreterState *\nPyThreadState_GetInterpreter(PyThreadState *tstate)\n{\n    assert(tstate != _Py_NULL);\n    return tstate->interp;\n}\n#endif\n\n\n// bpo-40429 added PyThreadState_GetFrame() to Python 3.9.0b1\n#if PY_VERSION_HEX < 0x030900B1 && !defined(PYPY_VERSION)\nstatic inline PyFrameObject* PyThreadState_GetFrame(PyThreadState *tstate)\n{\n    assert(tstate != _Py_NULL);\n    return _Py_CAST(PyFrameObject *, Py_XNewRef(tstate->frame));\n}\n#endif\n\n#if !defined(PYPY_VERSION)\nstatic inline PyFrameObject*\n_PyThreadState_GetFrameBorrow(PyThreadState *tstate)\n{\n    PyFrameObject *frame = PyThreadState_GetFrame(tstate);\n    Py_XDECREF(frame);\n    return frame;\n}\n#endif\n\n\n// bpo-39947 added PyInterpreterState_Get() to Python 3.9.0a5\n#if PY_VERSION_HEX < 0x030900A5 || defined(PYPY_VERSION)\nstatic inline PyInterpreterState* PyInterpreterState_Get(void)\n{\n    PyThreadState *tstate;\n    PyInterpreterState *interp;\n\n    tstate = PyThreadState_GET();\n    if (tstate == _Py_NULL) {\n        Py_FatalError(\"GIL released (tstate is NULL)\");\n    }\n    interp = tstate->interp;\n    if (interp == _Py_NULL) {\n        Py_FatalError(\"no current interpreter\");\n    }\n    return interp;\n}\n#endif\n\n\n// bpo-39947 added PyInterpreterState_Get() to Python 3.9.0a6\n#if 0x030700A1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030900A6 && !defined(PYPY_VERSION)\nstatic inline uint64_t PyThreadState_GetID(PyThreadState *tstate)\n{\n    assert(tstate != _Py_NULL);\n    return tstate->id;\n}\n#endif\n\n// bpo-43760 added PyThreadState_EnterTracing() to Python 3.11.0a2\n#if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION)\nstatic inline void PyThreadState_EnterTracing(PyThreadState *tstate)\n{\n    tstate->tracing++;\n#if PY_VERSION_HEX >= 0x030A00A1\n    tstate->cframe->use_tracing = 0;\n#else\n    tstate->use_tracing = 0;\n#endif\n}\n#endif\n\n// bpo-43760 added PyThreadState_LeaveTracing() to Python 3.11.0a2\n#if PY_VERSION_HEX < 0x030B00A2 && !defined(PYPY_VERSION)\nstatic inline void PyThreadState_LeaveTracing(PyThreadState *tstate)\n{\n    int use_tracing = (tstate->c_tracefunc != _Py_NULL\n                       || tstate->c_profilefunc != _Py_NULL);\n    tstate->tracing--;\n#if PY_VERSION_HEX >= 0x030A00A1\n    tstate->cframe->use_tracing = use_tracing;\n#else\n    tstate->use_tracing = use_tracing;\n#endif\n}\n#endif\n\n\n// bpo-37194 added PyObject_CallNoArgs() to Python 3.9.0a1\n// PyObject_CallNoArgs() added to PyPy 3.9.16-v7.3.11\n#if !defined(PyObject_CallNoArgs) && PY_VERSION_HEX < 0x030900A1\nstatic inline PyObject* PyObject_CallNoArgs(PyObject *func)\n{\n    return PyObject_CallFunctionObjArgs(func, NULL);\n}\n#endif\n\n\n// bpo-39245 made PyObject_CallOneArg() public (previously called\n// _PyObject_CallOneArg) in Python 3.9.0a4\n// PyObject_CallOneArg() added to PyPy 3.9.16-v7.3.11\n#if !defined(PyObject_CallOneArg) && PY_VERSION_HEX < 0x030900A4\nstatic inline PyObject* PyObject_CallOneArg(PyObject *func, PyObject *arg)\n{\n    return PyObject_CallFunctionObjArgs(func, arg, NULL);\n}\n#endif\n\n\n// bpo-1635741 added PyModule_AddObjectRef() to Python 3.10.0a3\n#if PY_VERSION_HEX < 0x030A00A3\nstatic inline int\nPyModule_AddObjectRef(PyObject *module, const char *name, PyObject *value)\n{\n    int res;\n\n    if (!value && !PyErr_Occurred()) {\n        // PyModule_AddObject() raises TypeError in this case\n        PyErr_SetString(PyExc_SystemError,\n                        \"PyModule_AddObjectRef() must be called \"\n                        \"with an exception raised if value is NULL\");\n        return -1;\n    }\n\n    Py_XINCREF(value);\n    res = PyModule_AddObject(module, name, value);\n    if (res < 0) {\n        Py_XDECREF(value);\n    }\n    return res;\n}\n#endif\n\n\n// bpo-40024 added PyModule_AddType() to Python 3.9.0a5\n#if PY_VERSION_HEX < 0x030900A5\nstatic inline int PyModule_AddType(PyObject *module, PyTypeObject *type)\n{\n    const char *name, *dot;\n\n    if (PyType_Ready(type) < 0) {\n        return -1;\n    }\n\n    // inline _PyType_Name()\n    name = type->tp_name;\n    assert(name != _Py_NULL);\n    dot = strrchr(name, '.');\n    if (dot != _Py_NULL) {\n        name = dot + 1;\n    }\n\n    return PyModule_AddObjectRef(module, name, _PyObject_CAST(type));\n}\n#endif\n\n\n// bpo-40241 added PyObject_GC_IsTracked() to Python 3.9.0a6.\n// bpo-4688 added _PyObject_GC_IS_TRACKED() to Python 2.7.0a2.\n#if PY_VERSION_HEX < 0x030900A6 && !defined(PYPY_VERSION)\nstatic inline int PyObject_GC_IsTracked(PyObject* obj)\n{\n    return (PyObject_IS_GC(obj) && _PyObject_GC_IS_TRACKED(obj));\n}\n#endif\n\n// bpo-40241 added PyObject_GC_IsFinalized() to Python 3.9.0a6.\n// bpo-18112 added _PyGCHead_FINALIZED() to Python 3.4.0 final.\n#if PY_VERSION_HEX < 0x030900A6 && PY_VERSION_HEX >= 0x030400F0 && !defined(PYPY_VERSION)\nstatic inline int PyObject_GC_IsFinalized(PyObject *obj)\n{\n    PyGC_Head *gc = _Py_CAST(PyGC_Head*, obj) - 1;\n    return (PyObject_IS_GC(obj) && _PyGCHead_FINALIZED(gc));\n}\n#endif\n\n\n// bpo-39573 added Py_IS_TYPE() to Python 3.9.0a4\n#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_IS_TYPE)\nstatic inline int _Py_IS_TYPE(PyObject *ob, PyTypeObject *type) {\n    return Py_TYPE(ob) == type;\n}\n#define Py_IS_TYPE(ob, type) _Py_IS_TYPE(_PyObject_CAST(ob), type)\n#endif\n\n\n// bpo-46906 added PyFloat_Pack2() and PyFloat_Unpack2() to Python 3.11a7.\n// bpo-11734 added _PyFloat_Pack2() and _PyFloat_Unpack2() to Python 3.6.0b1.\n// Python 3.11a2 moved _PyFloat_Pack2() and _PyFloat_Unpack2() to the internal\n// C API: Python 3.11a2-3.11a6 versions are not supported.\n#if 0x030600B1 <= PY_VERSION_HEX && PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION)\nstatic inline int PyFloat_Pack2(double x, char *p, int le)\n{ return _PyFloat_Pack2(x, (unsigned char*)p, le); }\n\nstatic inline double PyFloat_Unpack2(const char *p, int le)\n{ return _PyFloat_Unpack2((const unsigned char *)p, le); }\n#endif\n\n\n// bpo-46906 added PyFloat_Pack4(), PyFloat_Pack8(), PyFloat_Unpack4() and\n// PyFloat_Unpack8() to Python 3.11a7.\n// Python 3.11a2 moved _PyFloat_Pack4(), _PyFloat_Pack8(), _PyFloat_Unpack4()\n// and _PyFloat_Unpack8() to the internal C API: Python 3.11a2-3.11a6 versions\n// are not supported.\n#if PY_VERSION_HEX <= 0x030B00A1 && !defined(PYPY_VERSION)\nstatic inline int PyFloat_Pack4(double x, char *p, int le)\n{ return _PyFloat_Pack4(x, (unsigned char*)p, le); }\n\nstatic inline int PyFloat_Pack8(double x, char *p, int le)\n{ return _PyFloat_Pack8(x, (unsigned char*)p, le); }\n\nstatic inline double PyFloat_Unpack4(const char *p, int le)\n{ return _PyFloat_Unpack4((const unsigned char *)p, le); }\n\nstatic inline double PyFloat_Unpack8(const char *p, int le)\n{ return _PyFloat_Unpack8((const unsigned char *)p, le); }\n#endif\n\n\n// gh-92154 added PyCode_GetCode() to Python 3.11.0b1\n#if PY_VERSION_HEX < 0x030B00B1 && !defined(PYPY_VERSION)\nstatic inline PyObject* PyCode_GetCode(PyCodeObject *code)\n{\n    return Py_NewRef(code->co_code);\n}\n#endif\n\n\n// gh-95008 added PyCode_GetVarnames() to Python 3.11.0rc1\n#if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION)\nstatic inline PyObject* PyCode_GetVarnames(PyCodeObject *code)\n{\n    return Py_NewRef(code->co_varnames);\n}\n#endif\n\n// gh-95008 added PyCode_GetFreevars() to Python 3.11.0rc1\n#if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION)\nstatic inline PyObject* PyCode_GetFreevars(PyCodeObject *code)\n{\n    return Py_NewRef(code->co_freevars);\n}\n#endif\n\n// gh-95008 added PyCode_GetCellvars() to Python 3.11.0rc1\n#if PY_VERSION_HEX < 0x030B00C1 && !defined(PYPY_VERSION)\nstatic inline PyObject* PyCode_GetCellvars(PyCodeObject *code)\n{\n    return Py_NewRef(code->co_cellvars);\n}\n#endif\n\n\n// Py_UNUSED() was added to Python 3.4.0b2.\n#if PY_VERSION_HEX < 0x030400B2 && !defined(Py_UNUSED)\n#  if defined(__GNUC__) || defined(__clang__)\n#    define Py_UNUSED(name) _unused_ ## name __attribute__((unused))\n#  else\n#    define Py_UNUSED(name) _unused_ ## name\n#  endif\n#endif\n\n\n// gh-105922 added PyImport_AddModuleRef() to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A0\nstatic inline PyObject* PyImport_AddModuleRef(const char *name)\n{\n    return Py_XNewRef(PyImport_AddModule(name));\n}\n#endif\n\n\n// gh-105927 added PyWeakref_GetRef() to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D0000\nstatic inline int PyWeakref_GetRef(PyObject *ref, PyObject **pobj)\n{\n    PyObject *obj;\n    if (ref != NULL && !PyWeakref_Check(ref)) {\n        *pobj = NULL;\n        PyErr_SetString(PyExc_TypeError, \"expected a weakref\");\n        return -1;\n    }\n    obj = PyWeakref_GetObject(ref);\n    if (obj == NULL) {\n        // SystemError if ref is NULL\n        *pobj = NULL;\n        return -1;\n    }\n    if (obj == Py_None) {\n        *pobj = NULL;\n        return 0;\n    }\n    *pobj = Py_NewRef(obj);\n    return 1;\n}\n#endif\n\n\n// bpo-36974 added PY_VECTORCALL_ARGUMENTS_OFFSET to Python 3.8b1\n#ifndef PY_VECTORCALL_ARGUMENTS_OFFSET\n#  define PY_VECTORCALL_ARGUMENTS_OFFSET (_Py_CAST(size_t, 1) << (8 * sizeof(size_t) - 1))\n#endif\n\n// bpo-36974 added PyVectorcall_NARGS() to Python 3.8b1\n#if PY_VERSION_HEX < 0x030800B1\nstatic inline Py_ssize_t PyVectorcall_NARGS(size_t n)\n{\n    return n & ~PY_VECTORCALL_ARGUMENTS_OFFSET;\n}\n#endif\n\n\n// gh-105922 added PyObject_Vectorcall() to Python 3.9.0a4\n#if PY_VERSION_HEX < 0x030900A4\nstatic inline PyObject*\nPyObject_Vectorcall(PyObject *callable, PyObject *const *args,\n                     size_t nargsf, PyObject *kwnames)\n{\n#if PY_VERSION_HEX >= 0x030800B1 && !defined(PYPY_VERSION)\n    // bpo-36974 added _PyObject_Vectorcall() to Python 3.8.0b1\n    return _PyObject_Vectorcall(callable, args, nargsf, kwnames);\n#else\n    PyObject *posargs = NULL, *kwargs = NULL;\n    PyObject *res;\n    Py_ssize_t nposargs, nkwargs, i;\n\n    if (nargsf != 0 && args == NULL) {\n        PyErr_BadInternalCall();\n        goto error;\n    }\n    if (kwnames != NULL && !PyTuple_Check(kwnames)) {\n        PyErr_BadInternalCall();\n        goto error;\n    }\n\n    nposargs = (Py_ssize_t)PyVectorcall_NARGS(nargsf);\n    if (kwnames) {\n        nkwargs = PyTuple_GET_SIZE(kwnames);\n    }\n    else {\n        nkwargs = 0;\n    }\n\n    posargs = PyTuple_New(nposargs);\n    if (posargs == NULL) {\n        goto error;\n    }\n    if (nposargs) {\n        for (i=0; i < nposargs; i++) {\n            PyTuple_SET_ITEM(posargs, i, Py_NewRef(*args));\n            args++;\n        }\n    }\n\n    if (nkwargs) {\n        kwargs = PyDict_New();\n        if (kwargs == NULL) {\n            goto error;\n        }\n\n        for (i = 0; i < nkwargs; i++) {\n            PyObject *key = PyTuple_GET_ITEM(kwnames, i);\n            PyObject *value = *args;\n            args++;\n            if (PyDict_SetItem(kwargs, key, value) < 0) {\n                goto error;\n            }\n        }\n    }\n    else {\n        kwargs = NULL;\n    }\n\n    res = PyObject_Call(callable, posargs, kwargs);\n    Py_DECREF(posargs);\n    Py_XDECREF(kwargs);\n    return res;\n\nerror:\n    Py_DECREF(posargs);\n    Py_XDECREF(kwargs);\n    return NULL;\n#endif\n}\n#endif\n\n\n// gh-106521 added PyObject_GetOptionalAttr() and\n// PyObject_GetOptionalAttrString() to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A1\nstatic inline int\nPyObject_GetOptionalAttr(PyObject *obj, PyObject *attr_name, PyObject **result)\n{\n    // bpo-32571 added _PyObject_LookupAttr() to Python 3.7.0b1\n#if PY_VERSION_HEX >= 0x030700B1 && !defined(PYPY_VERSION)\n    return _PyObject_LookupAttr(obj, attr_name, result);\n#else\n    *result = PyObject_GetAttr(obj, attr_name);\n    if (*result != NULL) {\n        return 1;\n    }\n    if (!PyErr_Occurred()) {\n        return 0;\n    }\n    if (PyErr_ExceptionMatches(PyExc_AttributeError)) {\n        PyErr_Clear();\n        return 0;\n    }\n    return -1;\n#endif\n}\n\nstatic inline int\nPyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, PyObject **result)\n{\n    PyObject *name_obj;\n    int rc;\n#if PY_VERSION_HEX >= 0x03000000\n    name_obj = PyUnicode_FromString(attr_name);\n#else\n    name_obj = PyString_FromString(attr_name);\n#endif\n    if (name_obj == NULL) {\n        *result = NULL;\n        return -1;\n    }\n    rc = PyObject_GetOptionalAttr(obj, name_obj, result);\n    Py_DECREF(name_obj);\n    return rc;\n}\n#endif\n\n\n// gh-106307 added PyObject_GetOptionalAttr() and\n// PyMapping_GetOptionalItemString() to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A1\nstatic inline int\nPyMapping_GetOptionalItem(PyObject *obj, PyObject *key, PyObject **result)\n{\n    *result = PyObject_GetItem(obj, key);\n    if (*result) {\n        return 1;\n    }\n    if (!PyErr_ExceptionMatches(PyExc_KeyError)) {\n        return -1;\n    }\n    PyErr_Clear();\n    return 0;\n}\n\nstatic inline int\nPyMapping_GetOptionalItemString(PyObject *obj, const char *key, PyObject **result)\n{\n    PyObject *key_obj;\n    int rc;\n#if PY_VERSION_HEX >= 0x03000000\n    key_obj = PyUnicode_FromString(key);\n#else\n    key_obj = PyString_FromString(key);\n#endif\n    if (key_obj == NULL) {\n        *result = NULL;\n        return -1;\n    }\n    rc = PyMapping_GetOptionalItem(obj, key_obj, result);\n    Py_DECREF(key_obj);\n    return rc;\n}\n#endif\n\n// gh-108511 added PyMapping_HasKeyWithError() and\n// PyMapping_HasKeyStringWithError() to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A1\nstatic inline int\nPyMapping_HasKeyWithError(PyObject *obj, PyObject *key)\n{\n    PyObject *res;\n    int rc = PyMapping_GetOptionalItem(obj, key, &res);\n    Py_XDECREF(res);\n    return rc;\n}\n\nstatic inline int\nPyMapping_HasKeyStringWithError(PyObject *obj, const char *key)\n{\n    PyObject *res;\n    int rc = PyMapping_GetOptionalItemString(obj, key, &res);\n    Py_XDECREF(res);\n    return rc;\n}\n#endif\n\n\n// gh-108511 added PyObject_HasAttrWithError() and\n// PyObject_HasAttrStringWithError() to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A1\nstatic inline int\nPyObject_HasAttrWithError(PyObject *obj, PyObject *attr)\n{\n    PyObject *res;\n    int rc = PyObject_GetOptionalAttr(obj, attr, &res);\n    Py_XDECREF(res);\n    return rc;\n}\n\nstatic inline int\nPyObject_HasAttrStringWithError(PyObject *obj, const char *attr)\n{\n    PyObject *res;\n    int rc = PyObject_GetOptionalAttrString(obj, attr, &res);\n    Py_XDECREF(res);\n    return rc;\n}\n#endif\n\n\n// gh-106004 added PyDict_GetItemRef() and PyDict_GetItemStringRef()\n// to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A1\nstatic inline int\nPyDict_GetItemRef(PyObject *mp, PyObject *key, PyObject **result)\n{\n#if PY_VERSION_HEX >= 0x03000000\n    PyObject *item = PyDict_GetItemWithError(mp, key);\n#else\n    PyObject *item = _PyDict_GetItemWithError(mp, key);\n#endif\n    if (item != NULL) {\n        *result = Py_NewRef(item);\n        return 1;  // found\n    }\n    if (!PyErr_Occurred()) {\n        *result = NULL;\n        return 0;  // not found\n    }\n    *result = NULL;\n    return -1;\n}\n\nstatic inline int\nPyDict_GetItemStringRef(PyObject *mp, const char *key, PyObject **result)\n{\n    int res;\n#if PY_VERSION_HEX >= 0x03000000\n    PyObject *key_obj = PyUnicode_FromString(key);\n#else\n    PyObject *key_obj = PyString_FromString(key);\n#endif\n    if (key_obj == NULL) {\n        *result = NULL;\n        return -1;\n    }\n    res = PyDict_GetItemRef(mp, key_obj, result);\n    Py_DECREF(key_obj);\n    return res;\n}\n#endif\n\n\n// gh-106307 added PyModule_Add() to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A1\nstatic inline int\nPyModule_Add(PyObject *mod, const char *name, PyObject *value)\n{\n    int res = PyModule_AddObjectRef(mod, name, value);\n    Py_XDECREF(value);\n    return res;\n}\n#endif\n\n\n// gh-108014 added Py_IsFinalizing() to Python 3.13.0a1\n// bpo-1856 added _Py_Finalizing to Python 3.2.1b1.\n// _Py_IsFinalizing() was added to PyPy 7.3.0.\n#if (0x030201B1 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030D00A1) \\\n        && (!defined(PYPY_VERSION_NUM) || PYPY_VERSION_NUM >= 0x7030000)\nstatic inline int Py_IsFinalizing(void)\n{\n#if PY_VERSION_HEX >= 0x030700A1\n    // _Py_IsFinalizing() was added to Python 3.7.0a1.\n    return _Py_IsFinalizing();\n#else\n    return (_Py_Finalizing != NULL);\n#endif\n}\n#endif\n\n\n// gh-108323 added PyDict_ContainsString() to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A1\nstatic inline int PyDict_ContainsString(PyObject *op, const char *key)\n{\n    PyObject *key_obj = PyUnicode_FromString(key);\n    if (key_obj == NULL) {\n        return -1;\n    }\n    int res = PyDict_Contains(op, key_obj);\n    Py_DECREF(key_obj);\n    return res;\n}\n#endif\n\n\n// gh-108445 added PyLong_AsInt() to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A1\nstatic inline int PyLong_AsInt(PyObject *obj)\n{\n#ifdef PYPY_VERSION\n    long value = PyLong_AsLong(obj);\n    if (value == -1 && PyErr_Occurred()) {\n        return -1;\n    }\n    if (value < (long)INT_MIN || (long)INT_MAX < value) {\n        PyErr_SetString(PyExc_OverflowError,\n                        \"Python int too large to convert to C int\");\n        return -1;\n    }\n    return (int)value;\n#else\n    return _PyLong_AsInt(obj);\n#endif\n}\n#endif\n\n\n// gh-107073 added PyObject_VisitManagedDict() to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A1\nstatic inline int\nPyObject_VisitManagedDict(PyObject *obj, visitproc visit, void *arg)\n{\n    PyObject **dict = _PyObject_GetDictPtr(obj);\n    if (dict == NULL || *dict == NULL) {\n        return -1;\n    }\n    Py_VISIT(*dict);\n    return 0;\n}\n\nstatic inline void\nPyObject_ClearManagedDict(PyObject *obj)\n{\n    PyObject **dict = _PyObject_GetDictPtr(obj);\n    if (dict == NULL || *dict == NULL) {\n        return;\n    }\n    Py_CLEAR(*dict);\n}\n#endif\n\n// gh-108867 added PyThreadState_GetUnchecked() to Python 3.13.0a1\n// Python 3.5.2 added _PyThreadState_UncheckedGet().\n#if PY_VERSION_HEX >= 0x03050200 && PY_VERSION_HEX < 0x030D00A1\nstatic inline PyThreadState*\nPyThreadState_GetUnchecked(void)\n{\n    return _PyThreadState_UncheckedGet();\n}\n#endif\n\n// gh-110289 added PyUnicode_EqualToUTF8() and PyUnicode_EqualToUTF8AndSize()\n// to Python 3.13.0a1\n#if PY_VERSION_HEX < 0x030D00A1\nstatic inline int\nPyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t str_len)\n{\n    Py_ssize_t len;\n    const void *utf8;\n    PyObject *exc_type, *exc_value, *exc_tb;\n    int res;\n\n    // API cannot report errors so save/restore the exception\n    PyErr_Fetch(&exc_type, &exc_value, &exc_tb);\n\n    // Python 3.3.0a1 added PyUnicode_AsUTF8AndSize()\n#if PY_VERSION_HEX >= 0x030300A1\n    if (PyUnicode_IS_ASCII(unicode)) {\n        utf8 = PyUnicode_DATA(unicode);\n        len = PyUnicode_GET_LENGTH(unicode);\n    }\n    else {\n        utf8 = PyUnicode_AsUTF8AndSize(unicode, &len);\n        if (utf8 == NULL) {\n            // Memory allocation failure. The API cannot report error,\n            // so ignore the exception and return 0.\n            res = 0;\n            goto done;\n        }\n    }\n\n    if (len != str_len) {\n        res = 0;\n        goto done;\n    }\n    res = (memcmp(utf8, str, (size_t)len) == 0);\n#else\n    PyObject *bytes = PyUnicode_AsUTF8String(unicode);\n    if (bytes == NULL) {\n        // Memory allocation failure. The API cannot report error,\n        // so ignore the exception and return 0.\n        res = 0;\n        goto done;\n    }\n\n#if PY_VERSION_HEX >= 0x03000000\n    len = PyBytes_GET_SIZE(bytes);\n    utf8 = PyBytes_AS_STRING(bytes);\n#else\n    len = PyString_GET_SIZE(bytes);\n    utf8 = PyString_AS_STRING(bytes);\n#endif\n    if (len != str_len) {\n        Py_DECREF(bytes);\n        res = 0;\n        goto done;\n    }\n\n    res = (memcmp(utf8, str, (size_t)len) == 0);\n    Py_DECREF(bytes);\n#endif\n\ndone:\n    PyErr_Restore(exc_type, exc_value, exc_tb);\n    return res;\n}\n\nstatic inline int\nPyUnicode_EqualToUTF8(PyObject *unicode, const char *str)\n{\n    return PyUnicode_EqualToUTF8AndSize(unicode, str, (Py_ssize_t)strlen(str));\n}\n#endif\n\n\n// gh-111138 added PyList_Extend() and PyList_Clear() to Python 3.13.0a2\n#if PY_VERSION_HEX < 0x030D00A2\nstatic inline int\nPyList_Extend(PyObject *list, PyObject *iterable)\n{\n    return PyList_SetSlice(list, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, iterable);\n}\n\nstatic inline int\nPyList_Clear(PyObject *list)\n{\n    return PyList_SetSlice(list, 0, PY_SSIZE_T_MAX, NULL);\n}\n#endif\n\n// gh-111262 added PyDict_Pop() and PyDict_PopString() to Python 3.13.0a2\n#if PY_VERSION_HEX < 0x030D00A2\nstatic inline int\nPyDict_Pop(PyObject *dict, PyObject *key, PyObject **result)\n{\n    PyObject *value;\n\n    if (!PyDict_Check(dict)) {\n        PyErr_BadInternalCall();\n        if (result) {\n            *result = NULL;\n        }\n        return -1;\n    }\n\n    // bpo-16991 added _PyDict_Pop() to Python 3.5.0b2.\n    // Python 3.6.0b3 changed _PyDict_Pop() first argument type to PyObject*.\n    // Python 3.13.0a1 removed _PyDict_Pop().\n#if defined(PYPY_VERSION) || PY_VERSION_HEX < 0x030500b2 || PY_VERSION_HEX >= 0x030D0000\n    value = PyObject_CallMethod(dict, \"pop\", \"O\", key);\n#elif PY_VERSION_HEX < 0x030600b3\n    value = _PyDict_Pop(_Py_CAST(PyDictObject*, dict), key, NULL);\n#else\n    value = _PyDict_Pop(dict, key, NULL);\n#endif\n    if (value == NULL) {\n        if (result) {\n            *result = NULL;\n        }\n        if (PyErr_Occurred() && !PyErr_ExceptionMatches(PyExc_KeyError)) {\n            return -1;\n        }\n        PyErr_Clear();\n        return 0;\n    }\n    if (result) {\n        *result = value;\n    }\n    else {\n        Py_DECREF(value);\n    }\n    return 1;\n}\n\nstatic inline int\nPyDict_PopString(PyObject *dict, const char *key, PyObject **result)\n{\n    PyObject *key_obj = PyUnicode_FromString(key);\n    if (key_obj == NULL) {\n        if (result != NULL) {\n            *result = NULL;\n        }\n        return -1;\n    }\n\n    int res = PyDict_Pop(dict, key_obj, result);\n    Py_DECREF(key_obj);\n    return res;\n}\n#endif\n\n\n#if PY_VERSION_HEX < 0x030200A4\n// Python 3.2.0a4 added Py_hash_t type\ntypedef Py_ssize_t Py_hash_t;\n#endif\n\n\n// gh-111545 added Py_HashPointer() to Python 3.13.0a3\n#if PY_VERSION_HEX < 0x030D00A3\nstatic inline Py_hash_t Py_HashPointer(const void *ptr)\n{\n#if PY_VERSION_HEX >= 0x030900A4 && !defined(PYPY_VERSION)\n    return _Py_HashPointer(ptr);\n#else\n    return _Py_HashPointer(_Py_CAST(void*, ptr));\n#endif\n}\n#endif\n\n\n// Python 3.13a4 added a PyTime API.\n// Use the private API added to Python 3.5.\n#if PY_VERSION_HEX < 0x030D00A4 && PY_VERSION_HEX  >= 0x03050000\ntypedef _PyTime_t PyTime_t;\n#define PyTime_MIN _PyTime_MIN\n#define PyTime_MAX _PyTime_MAX\n\nstatic inline double PyTime_AsSecondsDouble(PyTime_t t)\n{ return _PyTime_AsSecondsDouble(t); }\n\nstatic inline int PyTime_Monotonic(PyTime_t *result)\n{ return _PyTime_GetMonotonicClockWithInfo(result, NULL); }\n\nstatic inline int PyTime_Time(PyTime_t *result)\n{ return _PyTime_GetSystemClockWithInfo(result, NULL); }\n\nstatic inline int PyTime_PerfCounter(PyTime_t *result)\n{\n#if PY_VERSION_HEX >= 0x03070000 && !defined(PYPY_VERSION)\n    return _PyTime_GetPerfCounterWithInfo(result, NULL);\n#elif PY_VERSION_HEX >= 0x03070000\n    // Call time.perf_counter_ns() and convert Python int object to PyTime_t.\n    // Cache time.perf_counter_ns() function for best performance.\n    static PyObject *func = NULL;\n    if (func == NULL) {\n        PyObject *mod = PyImport_ImportModule(\"time\");\n        if (mod == NULL) {\n            return -1;\n        }\n\n        func = PyObject_GetAttrString(mod, \"perf_counter_ns\");\n        Py_DECREF(mod);\n        if (func == NULL) {\n            return -1;\n        }\n    }\n\n    PyObject *res = PyObject_CallNoArgs(func);\n    if (res == NULL) {\n        return -1;\n    }\n    long long value = PyLong_AsLongLong(res);\n    Py_DECREF(res);\n\n    if (value == -1 && PyErr_Occurred()) {\n        return -1;\n    }\n\n    Py_BUILD_ASSERT(sizeof(value) >= sizeof(PyTime_t));\n    *result = (PyTime_t)value;\n    return 0;\n#else\n    // Call time.perf_counter() and convert C double to PyTime_t.\n    // Cache time.perf_counter() function for best performance.\n    static PyObject *func = NULL;\n    if (func == NULL) {\n        PyObject *mod = PyImport_ImportModule(\"time\");\n        if (mod == NULL) {\n            return -1;\n        }\n\n        func = PyObject_GetAttrString(mod, \"perf_counter\");\n        Py_DECREF(mod);\n        if (func == NULL) {\n            return -1;\n        }\n    }\n\n    PyObject *res = PyObject_CallNoArgs(func);\n    if (res == NULL) {\n        return -1;\n    }\n    double d = PyFloat_AsDouble(res);\n    Py_DECREF(res);\n\n    if (d == -1.0 && PyErr_Occurred()) {\n        return -1;\n    }\n\n    // Avoid floor() to avoid having to link to libm\n    *result = (PyTime_t)(d * 1e9);\n    return 0;\n#endif\n}\n\n#endif\n\n// gh-111389 added hash constants to Python 3.13.0a5. These constants were\n// added first as private macros to Python 3.4.0b1 and PyPy 7.3.8.\n#if (!defined(PyHASH_BITS) \\\n     && ((!defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x030400B1) \\\n         || (defined(PYPY_VERSION) && PY_VERSION_HEX >= 0x03070000 \\\n             && PYPY_VERSION_NUM >= 0x07030800)))\n#  define PyHASH_BITS _PyHASH_BITS\n#  define PyHASH_MODULUS _PyHASH_MODULUS\n#  define PyHASH_INF _PyHASH_INF\n#  define PyHASH_IMAG _PyHASH_IMAG\n#endif\n\n\n// gh-111545 added Py_GetConstant() and Py_GetConstantBorrowed()\n// to Python 3.13.0a6\n#if PY_VERSION_HEX < 0x030D00A6 && !defined(Py_CONSTANT_NONE)\n\n#define Py_CONSTANT_NONE 0\n#define Py_CONSTANT_FALSE 1\n#define Py_CONSTANT_TRUE 2\n#define Py_CONSTANT_ELLIPSIS 3\n#define Py_CONSTANT_NOT_IMPLEMENTED 4\n#define Py_CONSTANT_ZERO 5\n#define Py_CONSTANT_ONE 6\n#define Py_CONSTANT_EMPTY_STR 7\n#define Py_CONSTANT_EMPTY_BYTES 8\n#define Py_CONSTANT_EMPTY_TUPLE 9\n\nstatic inline PyObject* Py_GetConstant(unsigned int constant_id)\n{\n    static PyObject* constants[Py_CONSTANT_EMPTY_TUPLE + 1] = {NULL};\n\n    if (constants[Py_CONSTANT_NONE] == NULL) {\n        constants[Py_CONSTANT_NONE] = Py_None;\n        constants[Py_CONSTANT_FALSE] = Py_False;\n        constants[Py_CONSTANT_TRUE] = Py_True;\n        constants[Py_CONSTANT_ELLIPSIS] = Py_Ellipsis;\n        constants[Py_CONSTANT_NOT_IMPLEMENTED] = Py_NotImplemented;\n\n        constants[Py_CONSTANT_ZERO] = PyLong_FromLong(0);\n        if (constants[Py_CONSTANT_ZERO] == NULL) {\n            goto fatal_error;\n        }\n\n        constants[Py_CONSTANT_ONE] = PyLong_FromLong(1);\n        if (constants[Py_CONSTANT_ONE] == NULL) {\n            goto fatal_error;\n        }\n\n        constants[Py_CONSTANT_EMPTY_STR] = PyUnicode_FromStringAndSize(\"\", 0);\n        if (constants[Py_CONSTANT_EMPTY_STR] == NULL) {\n            goto fatal_error;\n        }\n\n        constants[Py_CONSTANT_EMPTY_BYTES] = PyBytes_FromStringAndSize(\"\", 0);\n        if (constants[Py_CONSTANT_EMPTY_BYTES] == NULL) {\n            goto fatal_error;\n        }\n\n        constants[Py_CONSTANT_EMPTY_TUPLE] = PyTuple_New(0);\n        if (constants[Py_CONSTANT_EMPTY_TUPLE] == NULL) {\n            goto fatal_error;\n        }\n        // goto dance to avoid compiler warnings about Py_FatalError()\n        goto init_done;\n\nfatal_error:\n        // This case should never happen\n        Py_FatalError(\"Py_GetConstant() failed to get constants\");\n    }\n\ninit_done:\n    if (constant_id <= Py_CONSTANT_EMPTY_TUPLE) {\n        return Py_NewRef(constants[constant_id]);\n    }\n    else {\n        PyErr_BadInternalCall();\n        return NULL;\n    }\n}\n\nstatic inline PyObject* Py_GetConstantBorrowed(unsigned int constant_id)\n{\n    PyObject *obj = Py_GetConstant(constant_id);\n    Py_XDECREF(obj);\n    return obj;\n}\n#endif\n\n\n// gh-114329 added PyList_GetItemRef() to Python 3.13.0a4\n#if PY_VERSION_HEX < 0x030D00A4\nstatic inline PyObject *\nPyList_GetItemRef(PyObject *op, Py_ssize_t index)\n{\n    PyObject *item = PyList_GetItem(op, index);\n    Py_XINCREF(item);\n    return item;\n}\n#endif\n\n\n// gh-114329 added PyList_GetItemRef() to Python 3.13.0a4\n#if PY_VERSION_HEX < 0x030D00A4\nstatic inline int\nPyDict_SetDefaultRef(PyObject *d, PyObject *key, PyObject *default_value,\n                     PyObject **result)\n{\n    PyObject *value;\n    if (PyDict_GetItemRef(d, key, &value) < 0) {\n        // get error\n        if (result) {\n            *result = NULL;\n        }\n        return -1;\n    }\n    if (value != NULL) {\n        // present\n        if (result) {\n            *result = value;\n        }\n        else {\n            Py_DECREF(value);\n        }\n        return 1;\n    }\n\n    // missing: set the item\n    if (PyDict_SetItem(d, key, default_value) < 0) {\n        // set error\n        if (result) {\n            *result = NULL;\n        }\n        return -1;\n    }\n    if (result) {\n        *result = Py_NewRef(default_value);\n    }\n    return 0;\n}\n#endif\n\n#if PY_VERSION_HEX < 0x030D00B3\n#  define Py_BEGIN_CRITICAL_SECTION(op) {\n#  define Py_END_CRITICAL_SECTION() }\n#  define Py_BEGIN_CRITICAL_SECTION2(a, b) {\n#  define Py_END_CRITICAL_SECTION2() }\n#endif\n\n#if PY_VERSION_HEX < 0x030E0000 && PY_VERSION_HEX >= 0x03060000 && !defined(PYPY_VERSION)\ntypedef struct PyUnicodeWriter PyUnicodeWriter;\n\nstatic inline void PyUnicodeWriter_Discard(PyUnicodeWriter *writer)\n{\n    _PyUnicodeWriter_Dealloc((_PyUnicodeWriter*)writer);\n    PyMem_Free(writer);\n}\n\nstatic inline PyUnicodeWriter* PyUnicodeWriter_Create(Py_ssize_t length)\n{\n    if (length < 0) {\n        PyErr_SetString(PyExc_ValueError,\n                        \"length must be positive\");\n        return NULL;\n    }\n\n    const size_t size = sizeof(_PyUnicodeWriter);\n    PyUnicodeWriter *pub_writer = (PyUnicodeWriter *)PyMem_Malloc(size);\n    if (pub_writer == _Py_NULL) {\n        PyErr_NoMemory();\n        return _Py_NULL;\n    }\n    _PyUnicodeWriter *writer = (_PyUnicodeWriter *)pub_writer;\n\n    _PyUnicodeWriter_Init(writer);\n    if (_PyUnicodeWriter_Prepare(writer, length, 127) < 0) {\n        PyUnicodeWriter_Discard(pub_writer);\n        return NULL;\n    }\n    writer->overallocate = 1;\n    return pub_writer;\n}\n\nstatic inline PyObject* PyUnicodeWriter_Finish(PyUnicodeWriter *writer)\n{\n    PyObject *str = _PyUnicodeWriter_Finish((_PyUnicodeWriter*)writer);\n    assert(((_PyUnicodeWriter*)writer)->buffer == NULL);\n    PyMem_Free(writer);\n    return str;\n}\n\nstatic inline int\nPyUnicodeWriter_WriteChar(PyUnicodeWriter *writer, Py_UCS4 ch)\n{\n    if (ch > 0x10ffff) {\n        PyErr_SetString(PyExc_ValueError,\n                        \"character must be in range(0x110000)\");\n        return -1;\n    }\n\n    return _PyUnicodeWriter_WriteChar((_PyUnicodeWriter*)writer, ch);\n}\n\nstatic inline int\nPyUnicodeWriter_WriteStr(PyUnicodeWriter *writer, PyObject *obj)\n{\n    PyObject *str = PyObject_Str(obj);\n    if (str == NULL) {\n        return -1;\n    }\n\n    int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str);\n    Py_DECREF(str);\n    return res;\n}\n\nstatic inline int\nPyUnicodeWriter_WriteRepr(PyUnicodeWriter *writer, PyObject *obj)\n{\n    PyObject *str = PyObject_Repr(obj);\n    if (str == NULL) {\n        return -1;\n    }\n\n    int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str);\n    Py_DECREF(str);\n    return res;\n}\n\nstatic inline int\nPyUnicodeWriter_WriteUTF8(PyUnicodeWriter *writer,\n                          const char *str, Py_ssize_t size)\n{\n    if (size < 0) {\n        size = (Py_ssize_t)strlen(str);\n    }\n\n    PyObject *str_obj = PyUnicode_FromStringAndSize(str, size);\n    if (str_obj == _Py_NULL) {\n        return -1;\n    }\n\n    int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str_obj);\n    Py_DECREF(str_obj);\n    return res;\n}\n\nstatic inline int\nPyUnicodeWriter_WriteASCII(PyUnicodeWriter *writer,\n                           const char *str, Py_ssize_t size)\n{\n    if (size < 0) {\n        size = (Py_ssize_t)strlen(str);\n    }\n\n    return _PyUnicodeWriter_WriteASCIIString((_PyUnicodeWriter*)writer,\n                                             str, size);\n}\n\nstatic inline int\nPyUnicodeWriter_WriteWideChar(PyUnicodeWriter *writer,\n                              const wchar_t *str, Py_ssize_t size)\n{\n    if (size < 0) {\n        size = (Py_ssize_t)wcslen(str);\n    }\n\n    PyObject *str_obj = PyUnicode_FromWideChar(str, size);\n    if (str_obj == _Py_NULL) {\n        return -1;\n    }\n\n    int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str_obj);\n    Py_DECREF(str_obj);\n    return res;\n}\n\nstatic inline int\nPyUnicodeWriter_WriteSubstring(PyUnicodeWriter *writer, PyObject *str,\n                               Py_ssize_t start, Py_ssize_t end)\n{\n    if (!PyUnicode_Check(str)) {\n        PyErr_Format(PyExc_TypeError, \"expect str, not %s\",\n                     Py_TYPE(str)->tp_name);\n        return -1;\n    }\n    if (start < 0 || start > end) {\n        PyErr_Format(PyExc_ValueError, \"invalid start argument\");\n        return -1;\n    }\n    if (end > PyUnicode_GET_LENGTH(str)) {\n        PyErr_Format(PyExc_ValueError, \"invalid end argument\");\n        return -1;\n    }\n\n    return _PyUnicodeWriter_WriteSubstring((_PyUnicodeWriter*)writer, str,\n                                           start, end);\n}\n\nstatic inline int\nPyUnicodeWriter_Format(PyUnicodeWriter *writer, const char *format, ...)\n{\n    va_list vargs;\n    va_start(vargs, format);\n    PyObject *str = PyUnicode_FromFormatV(format, vargs);\n    va_end(vargs);\n    if (str == _Py_NULL) {\n        return -1;\n    }\n\n    int res = _PyUnicodeWriter_WriteStr((_PyUnicodeWriter*)writer, str);\n    Py_DECREF(str);\n    return res;\n}\n#endif  // PY_VERSION_HEX < 0x030E0000\n\n// gh-116560 added PyLong_GetSign() to Python 3.14.0a0\n#if PY_VERSION_HEX < 0x030E00A0\nstatic inline int PyLong_GetSign(PyObject *obj, int *sign)\n{\n    if (!PyLong_Check(obj)) {\n        PyErr_Format(PyExc_TypeError, \"expect int, got %s\", Py_TYPE(obj)->tp_name);\n        return -1;\n    }\n\n    *sign = _PyLong_Sign(obj);\n    return 0;\n}\n#endif\n\n// gh-126061 added PyLong_IsPositive/Negative/Zero() to Python in 3.14.0a2\n#if PY_VERSION_HEX < 0x030E00A2\nstatic inline int PyLong_IsPositive(PyObject *obj)\n{\n    if (!PyLong_Check(obj)) {\n        PyErr_Format(PyExc_TypeError, \"expected int, got %s\", Py_TYPE(obj)->tp_name);\n        return -1;\n    }\n    return _PyLong_Sign(obj) == 1;\n}\n\nstatic inline int PyLong_IsNegative(PyObject *obj)\n{\n    if (!PyLong_Check(obj)) {\n        PyErr_Format(PyExc_TypeError, \"expected int, got %s\", Py_TYPE(obj)->tp_name);\n        return -1;\n    }\n    return _PyLong_Sign(obj) == -1;\n}\n\nstatic inline int PyLong_IsZero(PyObject *obj)\n{\n    if (!PyLong_Check(obj)) {\n        PyErr_Format(PyExc_TypeError, \"expected int, got %s\", Py_TYPE(obj)->tp_name);\n        return -1;\n    }\n    return _PyLong_Sign(obj) == 0;\n}\n#endif\n\n\n// gh-124502 added PyUnicode_Equal() to Python 3.14.0a0\n#if PY_VERSION_HEX < 0x030E00A0\nstatic inline int PyUnicode_Equal(PyObject *str1, PyObject *str2)\n{\n    if (!PyUnicode_Check(str1)) {\n        PyErr_Format(PyExc_TypeError, \"first argument must be str, not %s\",\n                     Py_TYPE(str1)->tp_name);\n        return -1;\n    }\n    if (!PyUnicode_Check(str2)) {\n        PyErr_Format(PyExc_TypeError, \"second argument must be str, not %s\",\n                     Py_TYPE(str2)->tp_name);\n        return -1;\n    }\n\n#if PY_VERSION_HEX >= 0x030d0000 && !defined(PYPY_VERSION)\n    PyAPI_FUNC(int) _PyUnicode_Equal(PyObject *str1, PyObject *str2);\n\n    return _PyUnicode_Equal(str1, str2);\n#elif PY_VERSION_HEX >= 0x03060000 && !defined(PYPY_VERSION)\n    return _PyUnicode_EQ(str1, str2);\n#elif PY_VERSION_HEX >= 0x03090000 && defined(PYPY_VERSION)\n    return _PyUnicode_EQ(str1, str2);\n#else\n    return (PyUnicode_Compare(str1, str2) == 0);\n#endif\n}\n#endif\n\n\n// gh-121645 added PyBytes_Join() to Python 3.14.0a0\n#if PY_VERSION_HEX < 0x030E00A0\nstatic inline PyObject* PyBytes_Join(PyObject *sep, PyObject *iterable)\n{\n    return _PyBytes_Join(sep, iterable);\n}\n#endif\n\n\n#if PY_VERSION_HEX < 0x030E00A0\nstatic inline Py_hash_t Py_HashBuffer(const void *ptr, Py_ssize_t len)\n{\n#if PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION)\n    PyAPI_FUNC(Py_hash_t) _Py_HashBytes(const void *src, Py_ssize_t len);\n\n    return _Py_HashBytes(ptr, len);\n#else\n    Py_hash_t hash;\n    PyObject *bytes = PyBytes_FromStringAndSize((const char*)ptr, len);\n    if (bytes == NULL) {\n        return -1;\n    }\n    hash = PyObject_Hash(bytes);\n    Py_DECREF(bytes);\n    return hash;\n#endif\n}\n#endif\n\n\n#if PY_VERSION_HEX < 0x030E00A0\nstatic inline int PyIter_NextItem(PyObject *iter, PyObject **item)\n{\n    iternextfunc tp_iternext;\n\n    assert(iter != NULL);\n    assert(item != NULL);\n\n    tp_iternext = Py_TYPE(iter)->tp_iternext;\n    if (tp_iternext == NULL) {\n        *item = NULL;\n        PyErr_Format(PyExc_TypeError, \"expected an iterator, got '%s'\",\n                     Py_TYPE(iter)->tp_name);\n        return -1;\n    }\n\n    if ((*item = tp_iternext(iter))) {\n        return 1;\n    }\n    if (!PyErr_Occurred()) {\n        return 0;\n    }\n    if (PyErr_ExceptionMatches(PyExc_StopIteration)) {\n        PyErr_Clear();\n        return 0;\n    }\n    return -1;\n}\n#endif\n\n\n#if PY_VERSION_HEX < 0x030E00A0\nstatic inline PyObject* PyLong_FromInt32(int32_t value)\n{\n    Py_BUILD_ASSERT(sizeof(long) >= 4);\n    return PyLong_FromLong(value);\n}\n\nstatic inline PyObject* PyLong_FromInt64(int64_t value)\n{\n    Py_BUILD_ASSERT(sizeof(long long) >= 8);\n    return PyLong_FromLongLong(value);\n}\n\nstatic inline PyObject* PyLong_FromUInt32(uint32_t value)\n{\n    Py_BUILD_ASSERT(sizeof(unsigned long) >= 4);\n    return PyLong_FromUnsignedLong(value);\n}\n\nstatic inline PyObject* PyLong_FromUInt64(uint64_t value)\n{\n    Py_BUILD_ASSERT(sizeof(unsigned long long) >= 8);\n    return PyLong_FromUnsignedLongLong(value);\n}\n\nstatic inline int PyLong_AsInt32(PyObject *obj, int32_t *pvalue)\n{\n    Py_BUILD_ASSERT(sizeof(int) == 4);\n    int value = PyLong_AsInt(obj);\n    if (value == -1 && PyErr_Occurred()) {\n        return -1;\n    }\n    *pvalue = (int32_t)value;\n    return 0;\n}\n\nstatic inline int PyLong_AsInt64(PyObject *obj, int64_t *pvalue)\n{\n    Py_BUILD_ASSERT(sizeof(long long) == 8);\n    long long value = PyLong_AsLongLong(obj);\n    if (value == -1 && PyErr_Occurred()) {\n        return -1;\n    }\n    *pvalue = (int64_t)value;\n    return 0;\n}\n\nstatic inline int PyLong_AsUInt32(PyObject *obj, uint32_t *pvalue)\n{\n    Py_BUILD_ASSERT(sizeof(long) >= 4);\n    unsigned long value = PyLong_AsUnsignedLong(obj);\n    if (value == (unsigned long)-1 && PyErr_Occurred()) {\n        return -1;\n    }\n#if SIZEOF_LONG > 4\n    if ((unsigned long)UINT32_MAX < value) {\n        PyErr_SetString(PyExc_OverflowError,\n                        \"Python int too large to convert to C uint32_t\");\n        return -1;\n    }\n#endif\n    *pvalue = (uint32_t)value;\n    return 0;\n}\n\nstatic inline int PyLong_AsUInt64(PyObject *obj, uint64_t *pvalue)\n{\n    Py_BUILD_ASSERT(sizeof(long long) == 8);\n    unsigned long long value = PyLong_AsUnsignedLongLong(obj);\n    if (value == (unsigned long long)-1 && PyErr_Occurred()) {\n        return -1;\n    }\n    *pvalue = (uint64_t)value;\n    return 0;\n}\n#endif\n\n\n// gh-102471 added import and export API for integers to 3.14.0a2.\n#if PY_VERSION_HEX < 0x030E00A2 && PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION)\n// Helpers to access PyLongObject internals.\nstatic inline void\n_PyLong_SetSignAndDigitCount(PyLongObject *op, int sign, Py_ssize_t size)\n{\n#if PY_VERSION_HEX >= 0x030C0000\n    op->long_value.lv_tag = (uintptr_t)(1 - sign) | ((uintptr_t)(size) << 3);\n#elif PY_VERSION_HEX >= 0x030900A4\n    Py_SET_SIZE(op, sign * size);\n#else\n    Py_SIZE(op) = sign * size;\n#endif\n}\n\nstatic inline Py_ssize_t\n_PyLong_DigitCount(const PyLongObject *op)\n{\n#if PY_VERSION_HEX >= 0x030C0000\n    return (Py_ssize_t)(op->long_value.lv_tag >> 3);\n#else\n    return _PyLong_Sign((PyObject*)op) < 0 ? -Py_SIZE(op) : Py_SIZE(op);\n#endif\n}\n\nstatic inline digit*\n_PyLong_GetDigits(const PyLongObject *op)\n{\n#if PY_VERSION_HEX >= 0x030C0000\n    return (digit*)(op->long_value.ob_digit);\n#else\n    return (digit*)(op->ob_digit);\n#endif\n}\n\ntypedef struct PyLongLayout {\n    uint8_t bits_per_digit;\n    uint8_t digit_size;\n    int8_t digits_order;\n    int8_t digit_endianness;\n} PyLongLayout;\n\ntypedef struct PyLongExport {\n    int64_t value;\n    uint8_t negative;\n    Py_ssize_t ndigits;\n    const void *digits;\n    Py_uintptr_t _reserved;\n} PyLongExport;\n\ntypedef struct PyLongWriter PyLongWriter;\n\nstatic inline const PyLongLayout*\nPyLong_GetNativeLayout(void)\n{\n    static const PyLongLayout PyLong_LAYOUT = {\n        PyLong_SHIFT,\n        sizeof(digit),\n        -1,  // least significant first\n        PY_LITTLE_ENDIAN ? -1 : 1,\n    };\n\n    return &PyLong_LAYOUT;\n}\n\nstatic inline int\nPyLong_Export(PyObject *obj, PyLongExport *export_long)\n{\n    if (!PyLong_Check(obj)) {\n        memset(export_long, 0, sizeof(*export_long));\n        PyErr_Format(PyExc_TypeError, \"expected int, got %s\",\n                     Py_TYPE(obj)->tp_name);\n        return -1;\n    }\n\n    // Fast-path: try to convert to a int64_t\n    PyLongObject *self = (PyLongObject*)obj;\n    int overflow;\n#if SIZEOF_LONG == 8\n    long value = PyLong_AsLongAndOverflow(obj, &overflow);\n#else\n    // Windows has 32-bit long, so use 64-bit long long instead\n    long long value = PyLong_AsLongLongAndOverflow(obj, &overflow);\n#endif\n    Py_BUILD_ASSERT(sizeof(value) == sizeof(int64_t));\n    // the function cannot fail since obj is a PyLongObject\n    assert(!(value == -1 && PyErr_Occurred()));\n\n    if (!overflow) {\n        export_long->value = value;\n        export_long->negative = 0;\n        export_long->ndigits = 0;\n        export_long->digits = 0;\n        export_long->_reserved = 0;\n    }\n    else {\n        export_long->value = 0;\n        export_long->negative = _PyLong_Sign(obj) < 0;\n        export_long->ndigits = _PyLong_DigitCount(self);\n        if (export_long->ndigits == 0) {\n            export_long->ndigits = 1;\n        }\n        export_long->digits = _PyLong_GetDigits(self);\n        export_long->_reserved = (Py_uintptr_t)Py_NewRef(obj);\n    }\n    return 0;\n}\n\nstatic inline void\nPyLong_FreeExport(PyLongExport *export_long)\n{\n    PyObject *obj = (PyObject*)export_long->_reserved;\n\n    if (obj) {\n        export_long->_reserved = 0;\n        Py_DECREF(obj);\n    }\n}\n\nstatic inline PyLongWriter*\nPyLongWriter_Create(int negative, Py_ssize_t ndigits, void **digits)\n{\n    if (ndigits <= 0) {\n        PyErr_SetString(PyExc_ValueError, \"ndigits must be positive\");\n        return NULL;\n    }\n    assert(digits != NULL);\n\n    PyLongObject *obj = _PyLong_New(ndigits);\n    if (obj == NULL) {\n        return NULL;\n    }\n    _PyLong_SetSignAndDigitCount(obj, negative?-1:1, ndigits);\n\n    *digits = _PyLong_GetDigits(obj);\n    return (PyLongWriter*)obj;\n}\n\nstatic inline void\nPyLongWriter_Discard(PyLongWriter *writer)\n{\n    PyLongObject *obj = (PyLongObject *)writer;\n\n    assert(Py_REFCNT(obj) == 1);\n    Py_DECREF(obj);\n}\n\nstatic inline PyObject*\nPyLongWriter_Finish(PyLongWriter *writer)\n{\n    PyObject *obj = (PyObject *)writer;\n    PyLongObject *self = (PyLongObject*)obj;\n    Py_ssize_t j = _PyLong_DigitCount(self);\n    Py_ssize_t i = j;\n    int sign = _PyLong_Sign(obj);\n\n    assert(Py_REFCNT(obj) == 1);\n\n    // Normalize and get singleton if possible\n    while (i > 0 && _PyLong_GetDigits(self)[i-1] == 0) {\n        --i;\n    }\n    if (i != j) {\n        if (i == 0) {\n            sign = 0;\n        }\n        _PyLong_SetSignAndDigitCount(self, sign, i);\n    }\n    if (i <= 1) {\n        long val = sign * (long)(_PyLong_GetDigits(self)[0]);\n        Py_DECREF(obj);\n        return PyLong_FromLong(val);\n    }\n\n    return obj;\n}\n#endif\n\n\n#if PY_VERSION_HEX < 0x030C00A3\n#  define Py_T_SHORT      T_SHORT\n#  define Py_T_INT        T_INT\n#  define Py_T_LONG       T_LONG\n#  define Py_T_FLOAT      T_FLOAT\n#  define Py_T_DOUBLE     T_DOUBLE\n#  define Py_T_STRING     T_STRING\n#  define _Py_T_OBJECT    T_OBJECT\n#  define Py_T_CHAR       T_CHAR\n#  define Py_T_BYTE       T_BYTE\n#  define Py_T_UBYTE      T_UBYTE\n#  define Py_T_USHORT     T_USHORT\n#  define Py_T_UINT       T_UINT\n#  define Py_T_ULONG      T_ULONG\n#  define Py_T_STRING_INPLACE  T_STRING_INPLACE\n#  define Py_T_BOOL       T_BOOL\n#  define Py_T_OBJECT_EX  T_OBJECT_EX\n#  define Py_T_LONGLONG   T_LONGLONG\n#  define Py_T_ULONGLONG  T_ULONGLONG\n#  define Py_T_PYSSIZET   T_PYSSIZET\n\n#  if PY_VERSION_HEX >= 0x03000000 && !defined(PYPY_VERSION)\n#    define _Py_T_NONE      T_NONE\n#  endif\n\n#  define Py_READONLY            READONLY\n#  define Py_AUDIT_READ          READ_RESTRICTED\n#  define _Py_WRITE_RESTRICTED   PY_WRITE_RESTRICTED\n#endif\n\n\n// gh-127350 added Py_fopen() and Py_fclose() to Python 3.14a4\n#if PY_VERSION_HEX < 0x030E00A4\nstatic inline FILE* Py_fopen(PyObject *path, const char *mode)\n{\n#if 0x030400A2 <= PY_VERSION_HEX && !defined(PYPY_VERSION)\n    PyAPI_FUNC(FILE*) _Py_fopen_obj(PyObject *path, const char *mode);\n\n    return _Py_fopen_obj(path, mode);\n#else\n    FILE *f;\n    PyObject *bytes;\n#if PY_VERSION_HEX >= 0x03000000\n    if (!PyUnicode_FSConverter(path, &bytes)) {\n        return NULL;\n    }\n#else\n    if (!PyString_Check(path)) {\n        PyErr_SetString(PyExc_TypeError, \"except str\");\n        return NULL;\n    }\n    bytes = Py_NewRef(path);\n#endif\n    const char *path_bytes = PyBytes_AS_STRING(bytes);\n\n    f = fopen(path_bytes, mode);\n    Py_DECREF(bytes);\n\n    if (f == NULL) {\n        PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, path);\n        return NULL;\n    }\n    return f;\n#endif\n}\n\nstatic inline int Py_fclose(FILE *file)\n{\n    return fclose(file);\n}\n#endif\n\n\n#if 0x03080000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x030E0000 && !defined(PYPY_VERSION)\nstatic inline PyObject*\nPyConfig_Get(const char *name)\n{\n    typedef enum {\n        _PyConfig_MEMBER_INT,\n        _PyConfig_MEMBER_UINT,\n        _PyConfig_MEMBER_ULONG,\n        _PyConfig_MEMBER_BOOL,\n        _PyConfig_MEMBER_WSTR,\n        _PyConfig_MEMBER_WSTR_OPT,\n        _PyConfig_MEMBER_WSTR_LIST,\n    } PyConfigMemberType;\n\n    typedef struct {\n        const char *name;\n        size_t offset;\n        PyConfigMemberType type;\n        const char *sys_attr;\n    } PyConfigSpec;\n\n#define PYTHONCAPI_COMPAT_SPEC(MEMBER, TYPE, sys_attr) \\\n    {#MEMBER, offsetof(PyConfig, MEMBER), \\\n     _PyConfig_MEMBER_##TYPE, sys_attr}\n\n    static const PyConfigSpec config_spec[] = {\n        PYTHONCAPI_COMPAT_SPEC(argv, WSTR_LIST, \"argv\"),\n        PYTHONCAPI_COMPAT_SPEC(base_exec_prefix, WSTR_OPT, \"base_exec_prefix\"),\n        PYTHONCAPI_COMPAT_SPEC(base_executable, WSTR_OPT, \"_base_executable\"),\n        PYTHONCAPI_COMPAT_SPEC(base_prefix, WSTR_OPT, \"base_prefix\"),\n        PYTHONCAPI_COMPAT_SPEC(bytes_warning, UINT, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(exec_prefix, WSTR_OPT, \"exec_prefix\"),\n        PYTHONCAPI_COMPAT_SPEC(executable, WSTR_OPT, \"executable\"),\n        PYTHONCAPI_COMPAT_SPEC(inspect, BOOL, _Py_NULL),\n#if 0x030C0000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(int_max_str_digits, UINT, _Py_NULL),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(interactive, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(module_search_paths, WSTR_LIST, \"path\"),\n        PYTHONCAPI_COMPAT_SPEC(optimization_level, UINT, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(parser_debug, BOOL, _Py_NULL),\n#if 0x03090000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(platlibdir, WSTR, \"platlibdir\"),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(prefix, WSTR_OPT, \"prefix\"),\n        PYTHONCAPI_COMPAT_SPEC(pycache_prefix, WSTR_OPT, \"pycache_prefix\"),\n        PYTHONCAPI_COMPAT_SPEC(quiet, BOOL, _Py_NULL),\n#if 0x030B0000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(stdlib_dir, WSTR_OPT, \"_stdlib_dir\"),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(use_environment, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(verbose, UINT, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(warnoptions, WSTR_LIST, \"warnoptions\"),\n        PYTHONCAPI_COMPAT_SPEC(write_bytecode, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(xoptions, WSTR_LIST, \"_xoptions\"),\n        PYTHONCAPI_COMPAT_SPEC(buffered_stdio, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(check_hash_pycs_mode, WSTR, _Py_NULL),\n#if 0x030B0000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(code_debug_ranges, BOOL, _Py_NULL),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(configure_c_stdio, BOOL, _Py_NULL),\n#if 0x030D0000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(cpu_count, INT, _Py_NULL),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(dev_mode, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(dump_refs, BOOL, _Py_NULL),\n#if 0x030B0000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(dump_refs_file, WSTR_OPT, _Py_NULL),\n#endif\n#ifdef Py_GIL_DISABLED\n        PYTHONCAPI_COMPAT_SPEC(enable_gil, INT, _Py_NULL),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(faulthandler, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(filesystem_encoding, WSTR, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(filesystem_errors, WSTR, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(hash_seed, ULONG, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(home, WSTR_OPT, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(import_time, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(install_signal_handlers, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(isolated, BOOL, _Py_NULL),\n#ifdef MS_WINDOWS\n        PYTHONCAPI_COMPAT_SPEC(legacy_windows_stdio, BOOL, _Py_NULL),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(malloc_stats, BOOL, _Py_NULL),\n#if 0x030A0000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(orig_argv, WSTR_LIST, \"orig_argv\"),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(parse_argv, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(pathconfig_warnings, BOOL, _Py_NULL),\n#if 0x030C0000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(perf_profiling, UINT, _Py_NULL),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(program_name, WSTR, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(run_command, WSTR_OPT, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(run_filename, WSTR_OPT, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(run_module, WSTR_OPT, _Py_NULL),\n#if 0x030B0000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(safe_path, BOOL, _Py_NULL),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(show_ref_count, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(site_import, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(skip_source_first_line, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(stdio_encoding, WSTR, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(stdio_errors, WSTR, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(tracemalloc, UINT, _Py_NULL),\n#if 0x030B0000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(use_frozen_modules, BOOL, _Py_NULL),\n#endif\n        PYTHONCAPI_COMPAT_SPEC(use_hash_seed, BOOL, _Py_NULL),\n        PYTHONCAPI_COMPAT_SPEC(user_site_directory, BOOL, _Py_NULL),\n#if 0x030A0000 <= PY_VERSION_HEX\n        PYTHONCAPI_COMPAT_SPEC(warn_default_encoding, BOOL, _Py_NULL),\n#endif\n    };\n\n#undef PYTHONCAPI_COMPAT_SPEC\n\n    const PyConfigSpec *spec;\n    int found = 0;\n    for (size_t i=0; i < sizeof(config_spec) / sizeof(config_spec[0]); i++) {\n        spec = &config_spec[i];\n        if (strcmp(spec->name, name) == 0) {\n            found = 1;\n            break;\n        }\n    }\n    if (found) {\n        if (spec->sys_attr != NULL) {\n            PyObject *value = PySys_GetObject(spec->sys_attr);\n            if (value == NULL) {\n                PyErr_Format(PyExc_RuntimeError, \"lost sys.%s\", spec->sys_attr);\n                return NULL;\n            }\n            return Py_NewRef(value);\n        }\n\n        PyAPI_FUNC(const PyConfig*) _Py_GetConfig(void);\n\n        const PyConfig *config = _Py_GetConfig();\n        void *member = (char *)config + spec->offset;\n        switch (spec->type) {\n        case _PyConfig_MEMBER_INT:\n        case _PyConfig_MEMBER_UINT:\n        {\n            int value = *(int *)member;\n            return PyLong_FromLong(value);\n        }\n        case _PyConfig_MEMBER_BOOL:\n        {\n            int value = *(int *)member;\n            return PyBool_FromLong(value != 0);\n        }\n        case _PyConfig_MEMBER_ULONG:\n        {\n            unsigned long value = *(unsigned long *)member;\n            return PyLong_FromUnsignedLong(value);\n        }\n        case _PyConfig_MEMBER_WSTR:\n        case _PyConfig_MEMBER_WSTR_OPT:\n        {\n            wchar_t *wstr = *(wchar_t **)member;\n            if (wstr != NULL) {\n                return PyUnicode_FromWideChar(wstr, -1);\n            }\n            else {\n                return Py_NewRef(Py_None);\n            }\n        }\n        case _PyConfig_MEMBER_WSTR_LIST:\n        {\n            const PyWideStringList *list = (const PyWideStringList *)member;\n            PyObject *tuple = PyTuple_New(list->length);\n            if (tuple == NULL) {\n                return NULL;\n            }\n\n            for (Py_ssize_t i = 0; i < list->length; i++) {\n                PyObject *item = PyUnicode_FromWideChar(list->items[i], -1);\n                if (item == NULL) {\n                    Py_DECREF(tuple);\n                    return NULL;\n                }\n                PyTuple_SET_ITEM(tuple, i, item);\n            }\n            return tuple;\n        }\n        default:\n            Py_UNREACHABLE();\n        }\n    }\n\n    PyErr_Format(PyExc_ValueError, \"unknown config option name: %s\", name);\n    return NULL;\n}\n\nstatic inline int\nPyConfig_GetInt(const char *name, int *value)\n{\n    PyObject *obj = PyConfig_Get(name);\n    if (obj == NULL) {\n        return -1;\n    }\n\n    if (!PyLong_Check(obj)) {\n        Py_DECREF(obj);\n        PyErr_Format(PyExc_TypeError, \"config option %s is not an int\", name);\n        return -1;\n    }\n\n    int as_int = PyLong_AsInt(obj);\n    Py_DECREF(obj);\n    if (as_int == -1 && PyErr_Occurred()) {\n        PyErr_Format(PyExc_OverflowError,\n                     \"config option %s value does not fit into a C int\", name);\n        return -1;\n    }\n\n    *value = as_int;\n    return 0;\n}\n#endif  // PY_VERSION_HEX > 0x03090000 && !defined(PYPY_VERSION)\n\n// gh-133144 added PyUnstable_Object_IsUniquelyReferenced() to Python 3.14.0b1.\n// Adapted from  _PyObject_IsUniquelyReferenced() implementation.\n#if PY_VERSION_HEX < 0x030E00B0\nstatic inline int PyUnstable_Object_IsUniquelyReferenced(PyObject *obj)\n{\n#if !defined(Py_GIL_DISABLED)\n    return Py_REFCNT(obj) == 1;\n#else\n    // NOTE: the entire ob_ref_shared field must be zero, including flags, to\n    // ensure that other threads cannot concurrently create new references to\n    // this object.\n    return (_Py_IsOwnedByCurrentThread(obj) &&\n            _Py_atomic_load_uint32_relaxed(&obj->ob_ref_local) == 1 &&\n            _Py_atomic_load_ssize_relaxed(&obj->ob_ref_shared) == 0);\n#endif\n}\n#endif\n\n\n#if PY_VERSION_HEX < 0x030F0000\nstatic inline PyObject*\nPySys_GetAttrString(const char *name)\n{\n#if PY_VERSION_HEX >= 0x03000000\n    PyObject *value = Py_XNewRef(PySys_GetObject(name));\n#else\n    PyObject *value = Py_XNewRef(PySys_GetObject((char*)name));\n#endif\n    if (value != NULL) {\n        return value;\n    }\n    if (!PyErr_Occurred()) {\n        PyErr_Format(PyExc_RuntimeError, \"lost sys.%s\", name);\n    }\n    return NULL;\n}\n\nstatic inline PyObject*\nPySys_GetAttr(PyObject *name)\n{\n#if PY_VERSION_HEX >= 0x03000000\n    const char *name_str = PyUnicode_AsUTF8(name);\n#else\n    const char *name_str = PyString_AsString(name);\n#endif\n    if (name_str == NULL) {\n        return NULL;\n    }\n\n    return PySys_GetAttrString(name_str);\n}\n\nstatic inline int\nPySys_GetOptionalAttrString(const char *name, PyObject **value)\n{\n#if PY_VERSION_HEX >= 0x03000000\n    *value = Py_XNewRef(PySys_GetObject(name));\n#else\n    *value = Py_XNewRef(PySys_GetObject((char*)name));\n#endif\n    if (*value != NULL) {\n        return 1;\n    }\n    return 0;\n}\n\nstatic inline int\nPySys_GetOptionalAttr(PyObject *name, PyObject **value)\n{\n#if PY_VERSION_HEX >= 0x03000000\n    const char *name_str = PyUnicode_AsUTF8(name);\n#else\n    const char *name_str = PyString_AsString(name);\n#endif\n    if (name_str == NULL) {\n        *value = NULL;\n        return -1;\n    }\n\n    return PySys_GetOptionalAttrString(name_str, value);\n}\n#endif  // PY_VERSION_HEX < 0x030F00A1\n\n\n#if PY_VERSION_HEX < 0x030F00A1\ntypedef struct PyBytesWriter {\n    char small_buffer[256];\n    PyObject *obj;\n    Py_ssize_t size;\n} PyBytesWriter;\n\nstatic inline Py_ssize_t\n_PyBytesWriter_GetAllocated(PyBytesWriter *writer)\n{\n    if (writer->obj == NULL) {\n        return sizeof(writer->small_buffer);\n    }\n    else {\n        return PyBytes_GET_SIZE(writer->obj);\n    }\n}\n\n\nstatic inline int\n_PyBytesWriter_Resize_impl(PyBytesWriter *writer, Py_ssize_t size,\n                           int resize)\n{\n    int overallocate = resize;\n    assert(size >= 0);\n\n    if (size <= _PyBytesWriter_GetAllocated(writer)) {\n        return 0;\n    }\n\n    if (overallocate) {\n#ifdef MS_WINDOWS\n        /* On Windows, overallocate by 50% is the best factor */\n        if (size <= (PY_SSIZE_T_MAX - size / 2)) {\n            size += size / 2;\n        }\n#else\n        /* On Linux, overallocate by 25% is the best factor */\n        if (size <= (PY_SSIZE_T_MAX - size / 4)) {\n            size += size / 4;\n        }\n#endif\n    }\n\n    if (writer->obj != NULL) {\n        if (_PyBytes_Resize(&writer->obj, size)) {\n            return -1;\n        }\n        assert(writer->obj != NULL);\n    }\n    else {\n        writer->obj = PyBytes_FromStringAndSize(NULL, size);\n        if (writer->obj == NULL) {\n            return -1;\n        }\n\n        if (resize) {\n            assert((size_t)size > sizeof(writer->small_buffer));\n            memcpy(PyBytes_AS_STRING(writer->obj),\n                   writer->small_buffer,\n                   sizeof(writer->small_buffer));\n        }\n    }\n    return 0;\n}\n\nstatic inline void*\nPyBytesWriter_GetData(PyBytesWriter *writer)\n{\n    if (writer->obj == NULL) {\n        return writer->small_buffer;\n    }\n    else {\n        return PyBytes_AS_STRING(writer->obj);\n    }\n}\n\nstatic inline Py_ssize_t\nPyBytesWriter_GetSize(PyBytesWriter *writer)\n{\n    return writer->size;\n}\n\nstatic inline void\nPyBytesWriter_Discard(PyBytesWriter *writer)\n{\n    if (writer == NULL) {\n        return;\n    }\n\n    Py_XDECREF(writer->obj);\n    PyMem_Free(writer);\n}\n\nstatic inline PyBytesWriter*\nPyBytesWriter_Create(Py_ssize_t size)\n{\n    if (size < 0) {\n        PyErr_SetString(PyExc_ValueError, \"size must be >= 0\");\n        return NULL;\n    }\n\n    PyBytesWriter *writer = (PyBytesWriter*)PyMem_Malloc(sizeof(PyBytesWriter));\n    if (writer == NULL) {\n        PyErr_NoMemory();\n        return NULL;\n    }\n\n    writer->obj = NULL;\n    writer->size = 0;\n\n    if (size >= 1) {\n        if (_PyBytesWriter_Resize_impl(writer, size, 0) < 0) {\n            PyBytesWriter_Discard(writer);\n            return NULL;\n        }\n        writer->size = size;\n    }\n    return writer;\n}\n\nstatic inline PyObject*\nPyBytesWriter_FinishWithSize(PyBytesWriter *writer, Py_ssize_t size)\n{\n    PyObject *result;\n    if (size == 0) {\n        result = PyBytes_FromStringAndSize(\"\", 0);\n    }\n    else if (writer->obj != NULL) {\n        if (size != PyBytes_GET_SIZE(writer->obj)) {\n            if (_PyBytes_Resize(&writer->obj, size)) {\n                goto error;\n            }\n        }\n        result = writer->obj;\n        writer->obj = NULL;\n    }\n    else {\n        result = PyBytes_FromStringAndSize(writer->small_buffer, size);\n    }\n    PyBytesWriter_Discard(writer);\n    return result;\n\nerror:\n    PyBytesWriter_Discard(writer);\n    return NULL;\n}\n\nstatic inline PyObject*\nPyBytesWriter_Finish(PyBytesWriter *writer)\n{\n    return PyBytesWriter_FinishWithSize(writer, writer->size);\n}\n\nstatic inline PyObject*\nPyBytesWriter_FinishWithPointer(PyBytesWriter *writer, void *buf)\n{\n    Py_ssize_t size = (char*)buf - (char*)PyBytesWriter_GetData(writer);\n    if (size < 0 || size > _PyBytesWriter_GetAllocated(writer)) {\n        PyBytesWriter_Discard(writer);\n        PyErr_SetString(PyExc_ValueError, \"invalid end pointer\");\n        return NULL;\n    }\n\n    return PyBytesWriter_FinishWithSize(writer, size);\n}\n\nstatic inline int\nPyBytesWriter_Resize(PyBytesWriter *writer, Py_ssize_t size)\n{\n    if (size < 0) {\n        PyErr_SetString(PyExc_ValueError, \"size must be >= 0\");\n        return -1;\n    }\n    if (_PyBytesWriter_Resize_impl(writer, size, 1) < 0) {\n        return -1;\n    }\n    writer->size = size;\n    return 0;\n}\n\nstatic inline int\nPyBytesWriter_Grow(PyBytesWriter *writer, Py_ssize_t size)\n{\n    if (size < 0 && writer->size + size < 0) {\n        PyErr_SetString(PyExc_ValueError, \"invalid size\");\n        return -1;\n    }\n    if (size > PY_SSIZE_T_MAX - writer->size) {\n        PyErr_NoMemory();\n        return -1;\n    }\n    size = writer->size + size;\n\n    if (_PyBytesWriter_Resize_impl(writer, size, 1) < 0) {\n        return -1;\n    }\n    writer->size = size;\n    return 0;\n}\n\nstatic inline void*\nPyBytesWriter_GrowAndUpdatePointer(PyBytesWriter *writer,\n                                   Py_ssize_t size, void *buf)\n{\n    Py_ssize_t pos = (char*)buf - (char*)PyBytesWriter_GetData(writer);\n    if (PyBytesWriter_Grow(writer, size) < 0) {\n        return NULL;\n    }\n    return (char*)PyBytesWriter_GetData(writer) + pos;\n}\n\nstatic inline int\nPyBytesWriter_WriteBytes(PyBytesWriter *writer,\n                         const void *bytes, Py_ssize_t size)\n{\n    if (size < 0) {\n        size_t len = strlen((const char*)bytes);\n        if (len > (size_t)PY_SSIZE_T_MAX) {\n            PyErr_NoMemory();\n            return -1;\n        }\n        size = (Py_ssize_t)len;\n    }\n\n    Py_ssize_t pos = writer->size;\n    if (PyBytesWriter_Grow(writer, size) < 0) {\n        return -1;\n    }\n    char *buf = (char*)PyBytesWriter_GetData(writer);\n    memcpy(buf + pos, bytes, (size_t)size);\n    return 0;\n}\n\nstatic inline int\nPyBytesWriter_Format(PyBytesWriter *writer, const char *format, ...)\n                     Py_GCC_ATTRIBUTE((format(printf, 2, 3)));\n\nstatic inline int\nPyBytesWriter_Format(PyBytesWriter *writer, const char *format, ...)\n{\n    va_list vargs;\n    va_start(vargs, format);\n    PyObject *str = PyBytes_FromFormatV(format, vargs);\n    va_end(vargs);\n\n    if (str == NULL) {\n        return -1;\n    }\n    int res = PyBytesWriter_WriteBytes(writer,\n                                       PyBytes_AS_STRING(str),\n                                       PyBytes_GET_SIZE(str));\n    Py_DECREF(str);\n    return res;\n}\n#endif  // PY_VERSION_HEX < 0x030F00A1\n\n\n#if PY_VERSION_HEX < 0x030F00A1\nstatic inline PyObject*\nPyTuple_FromArray(PyObject *const *array, Py_ssize_t size)\n{\n    PyObject *tuple = PyTuple_New(size);\n    if (tuple == NULL) {\n        return NULL;\n    }\n    for (Py_ssize_t i=0; i < size; i++) {\n        PyObject *item = array[i];\n        PyTuple_SET_ITEM(tuple, i, Py_NewRef(item));\n    }\n    return tuple;\n}\n#endif\n\n\n#if PY_VERSION_HEX < 0x030F00A1\nstatic inline Py_hash_t\nPyUnstable_Unicode_GET_CACHED_HASH(PyObject *op)\n{\n#ifdef PYPY_VERSION\n    (void)op;  // unused argument\n    return -1;\n#elif PY_VERSION_HEX >= 0x03000000\n    return ((PyASCIIObject*)op)->hash;\n#else\n    return ((PyUnicodeObject*)op)->hash;\n#endif\n}\n#endif\n\n\n#ifdef __cplusplus\n}\n#endif\n#endif  // PYTHONCAPI_COMPAT\n"
  },
  {
    "path": "mypyc/lib-rt/pythonsupport.c",
    "content": "// Collects code that was copied in from cpython, for a couple of different reasons:\n//  * We wanted to modify it to produce a more efficient version for our uses\n//  * We needed to call it and it was static :(\n//  * We wanted to call it and needed to backport it\n\n#include \"pythonsupport.h\"\n\n/////////////////////////////////////////\n// Adapted from bltinmodule.c in Python 3.7.0\nPyObject*\nupdate_bases(PyObject *bases)\n{\n    Py_ssize_t i, j;\n    PyObject *base, *meth, *new_base, *result, *new_bases = NULL;\n    PyObject *stack[1] = {bases};\n    assert(PyTuple_Check(bases));\n\n    Py_ssize_t nargs = PyTuple_GET_SIZE(bases);\n    for (i = 0; i < nargs; i++) {\n        base = PyTuple_GET_ITEM(bases, i);\n        if (PyType_Check(base)) {\n            if (new_bases) {\n                /* If we already have made a replacement, then we append every normal base,\n                   otherwise just skip it. */\n                if (PyList_Append(new_bases, base) < 0) {\n                    goto error;\n                }\n            }\n            continue;\n        }\n        if (PyObject_GetOptionalAttr(base, mypyc_interned_str.__mro_entries__, &meth) < 0) {\n            goto error;\n        }\n        if (!meth) {\n            if (new_bases) {\n                if (PyList_Append(new_bases, base) < 0) {\n                    goto error;\n                }\n            }\n            continue;\n        }\n        new_base = PyObject_Vectorcall(meth, stack, 1, NULL);\n        Py_DECREF(meth);\n        if (!new_base) {\n            goto error;\n        }\n        if (!PyTuple_Check(new_base)) {\n            PyErr_SetString(PyExc_TypeError,\n                            \"__mro_entries__ must return a tuple\");\n            Py_DECREF(new_base);\n            goto error;\n        }\n        if (!new_bases) {\n            /* If this is a first successful replacement, create new_bases list and\n               copy previously encountered bases. */\n            if (!(new_bases = PyList_New(i))) {\n                goto error;\n            }\n            for (j = 0; j < i; j++) {\n                base = PyTuple_GET_ITEM(bases, j);\n                PyList_SET_ITEM(new_bases, j, base);\n                Py_INCREF(base);\n            }\n        }\n        j = PyList_GET_SIZE(new_bases);\n        if (PyList_SetSlice(new_bases, j, j, new_base) < 0) {\n            goto error;\n        }\n        Py_DECREF(new_base);\n    }\n    if (!new_bases) {\n        return bases;\n    }\n    result = PyList_AsTuple(new_bases);\n    Py_DECREF(new_bases);\n    return result;\n\nerror:\n    Py_XDECREF(new_bases);\n    return NULL;\n}\n\n// From Python 3.7's typeobject.c\nint\ninit_subclass(PyTypeObject *type, PyObject *kwds)\n{\n    PyObject *super, *func, *result;\n    PyObject *args[2] = {(PyObject *)type, (PyObject *)type};\n\n    super = PyObject_Vectorcall((PyObject *)&PySuper_Type, args, 2, NULL);\n    if (super == NULL) {\n        return -1;\n    }\n\n    func = PyObject_GetAttr(super, mypyc_interned_str.__init_subclass__);\n    Py_DECREF(super);\n    if (func == NULL) {\n        return -1;\n    }\n\n    result = _PyObject_FastCallDict(func, NULL, 0, kwds);\n    Py_DECREF(func);\n    if (result == NULL) {\n        return -1;\n    }\n\n    Py_DECREF(result);\n    return 0;\n}\n\n#if CPY_3_12_FEATURES\n\n// Slow path of CPyLong_AsSsize_tAndOverflow (non-inlined)\nPy_ssize_t\nCPyLong_AsSsize_tAndOverflow_(PyObject *vv, int *overflow)\n{\n    PyLongObject *v = (PyLongObject *)vv;\n    size_t x, prev;\n    Py_ssize_t res;\n    Py_ssize_t i;\n    int sign;\n\n    *overflow = 0;\n\n    res = -1;\n    i = CPY_LONG_TAG(v);\n\n    sign = 1;\n    x = 0;\n    if (i & CPY_SIGN_NEGATIVE) {\n        sign = -1;\n    }\n    i >>= CPY_NON_SIZE_BITS;\n    while (--i >= 0) {\n        prev = x;\n        x = (x << PyLong_SHIFT) + CPY_LONG_DIGIT(v, i);\n        if ((x >> PyLong_SHIFT) != prev) {\n            *overflow = sign;\n            goto exit;\n        }\n    }\n    /* Haven't lost any bits, but casting to long requires extra\n     * care.\n     */\n    if (x <= (size_t)CPY_TAGGED_MAX) {\n        res = (Py_ssize_t)x * sign;\n    }\n    else if (sign < 0 && x == CPY_TAGGED_ABS_MIN) {\n        res = CPY_TAGGED_MIN;\n    }\n    else {\n        *overflow = sign;\n        /* res is already set to -1 */\n    }\n  exit:\n    return res;\n}\n\n#else\n\n// Slow path of CPyLong_AsSsize_tAndOverflow (non-inlined, Python 3.11 and earlier)\nPy_ssize_t\nCPyLong_AsSsize_tAndOverflow_(PyObject *vv, int *overflow)\n{\n    /* This version by Tim Peters */\n    PyLongObject *v = (PyLongObject *)vv;\n    size_t x, prev;\n    Py_ssize_t res;\n    Py_ssize_t i;\n    int sign;\n\n    *overflow = 0;\n\n    res = -1;\n    i = Py_SIZE(v);\n\n    sign = 1;\n    x = 0;\n    if (i < 0) {\n        sign = -1;\n        i = -(i);\n    }\n    while (--i >= 0) {\n        prev = x;\n        x = (x << PyLong_SHIFT) + CPY_LONG_DIGIT(v, i);\n        if ((x >> PyLong_SHIFT) != prev) {\n            *overflow = sign;\n            goto exit;\n        }\n    }\n    /* Haven't lost any bits, but casting to long requires extra\n     * care.\n     */\n    if (x <= (size_t)CPY_TAGGED_MAX) {\n        res = (Py_ssize_t)x * sign;\n    }\n    else if (sign < 0 && x == CPY_TAGGED_ABS_MIN) {\n        res = CPY_TAGGED_MIN;\n    }\n    else {\n        *overflow = sign;\n        /* res is already set to -1 */\n    }\n  exit:\n    return res;\n}\n\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/pythonsupport.h",
    "content": "// Collects code that was copied in from cpython, for a couple of different reasons:\n//  * We wanted to modify it to produce a more efficient version for our uses\n//  * We needed to call it and it was static :(\n//  * We wanted to call it and needed to backport it\n\n#ifndef CPY_PYTHONSUPPORT_H\n#define CPY_PYTHONSUPPORT_H\n\n#include <stdbool.h>\n#include <Python.h>\n#include \"pythoncapi_compat.h\"\n#include <frameobject.h>\n#include <assert.h>\n#include \"static_data.h\"\n#include \"mypyc_util.h\"\n\n#if CPY_3_13_FEATURES\n#ifndef Py_BUILD_CORE\n#define Py_BUILD_CORE\n#endif\n#include \"internal/pycore_genobject.h\"  // _PyGen_FetchStopIterationValue\n#include \"internal/pycore_pyerrors.h\"  // _PyErr_FormatFromCause, _PyErr_SetKeyError\n#include \"internal/pycore_setobject.h\"  // _PySet_Update\n#endif\n\n#if CPY_3_12_FEATURES\n#include \"internal/pycore_frame.h\"\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n#if 0\n} // why isn't emacs smart enough to not indent this\n#endif\n\nPyObject* update_bases(PyObject *bases);\nint init_subclass(PyTypeObject *type, PyObject *kwds);\n\nPy_ssize_t\nCPyLong_AsSsize_tAndOverflow_(PyObject *vv, int *overflow);\n\n#if CPY_3_12_FEATURES\n\nstatic inline Py_ssize_t\nCPyLong_AsSsize_tAndOverflow(PyObject *vv, int *overflow)\n{\n    /* This version by Tim Peters */\n    PyLongObject *v = (PyLongObject *)vv;\n    Py_ssize_t res;\n    Py_ssize_t i;\n\n    *overflow = 0;\n\n    res = -1;\n    i = CPY_LONG_TAG(v);\n\n    // TODO: Combine zero and non-zero cases helow?\n    if (likely(i == (1 << CPY_NON_SIZE_BITS))) {\n        res = CPY_LONG_DIGIT(v, 0);\n    } else if (likely(i == CPY_SIGN_ZERO)) {\n        res = 0;\n    } else if (i == ((1 << CPY_NON_SIZE_BITS) | CPY_SIGN_NEGATIVE)) {\n        res = -(sdigit)CPY_LONG_DIGIT(v, 0);\n    } else {\n        // Slow path is moved to a non-inline helper function to\n        // limit size of generated code\n        int overflow_local;\n        res = CPyLong_AsSsize_tAndOverflow_(vv, &overflow_local);\n        *overflow = overflow_local;\n    }\n    return res;\n}\n\n#else\n\n// Adapted from longobject.c in Python 3.7.0\n\n/* This function adapted from PyLong_AsLongLongAndOverflow, but with\n * some safety checks removed and specialized to only work for objects\n * that are already longs.\n * About half of the win this provides, though, just comes from being\n * able to inline the function, which in addition to saving function call\n * overhead allows the out-parameter overflow flag to be collapsed into\n * control flow.\n * Additionally, we check against the possible range of CPyTagged, not of\n * Py_ssize_t. */\nstatic inline Py_ssize_t\nCPyLong_AsSsize_tAndOverflow(PyObject *vv, int *overflow)\n{\n    /* This version by Tim Peters */\n    PyLongObject *v = (PyLongObject *)vv;\n    Py_ssize_t res;\n    Py_ssize_t i;\n\n    *overflow = 0;\n\n    res = -1;\n    i = Py_SIZE(v);\n\n    if (likely(i == 1)) {\n        res = CPY_LONG_DIGIT(v, 0);\n    } else if (likely(i == 0)) {\n        res = 0;\n    } else if (i == -1) {\n        res = -(sdigit)CPY_LONG_DIGIT(v, 0);\n    } else {\n        // Slow path is moved to a non-inline helper function to\n        // limit size of generated code\n        int overflow_local;\n        res = CPyLong_AsSsize_tAndOverflow_(vv, &overflow_local);\n        *overflow = overflow_local;\n    }\n    return res;\n}\n\n#endif\n\n// Adapted from listobject.c in Python 3.7.0\nstatic int\nlist_resize(PyListObject *self, Py_ssize_t newsize)\n{\n    PyObject **items;\n    size_t new_allocated, num_allocated_bytes;\n    Py_ssize_t allocated = self->allocated;\n\n    /* Bypass realloc() when a previous overallocation is large enough\n       to accommodate the newsize.  If the newsize falls lower than half\n       the allocated size, then proceed with the realloc() to shrink the list.\n    */\n    if (allocated >= newsize && newsize >= (allocated >> 1)) {\n        assert(self->ob_item != NULL || newsize == 0);\n        Py_SET_SIZE(self, newsize);\n        return 0;\n    }\n\n    /* This over-allocates proportional to the list size, making room\n     * for additional growth.  The over-allocation is mild, but is\n     * enough to give linear-time amortized behavior over a long\n     * sequence of appends() in the presence of a poorly-performing\n     * system realloc().\n     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...\n     * Note: new_allocated won't overflow because the largest possible value\n     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.\n     */\n    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);\n    if (new_allocated > (size_t)PY_SSIZE_T_MAX / sizeof(PyObject *)) {\n        PyErr_NoMemory();\n        return -1;\n    }\n\n    if (newsize == 0)\n        new_allocated = 0;\n    num_allocated_bytes = new_allocated * sizeof(PyObject *);\n    items = (PyObject **)PyMem_Realloc(self->ob_item, num_allocated_bytes);\n    if (items == NULL) {\n        PyErr_NoMemory();\n        return -1;\n    }\n    self->ob_item = items;\n    Py_SET_SIZE(self, newsize);\n    self->allocated = new_allocated;\n    return 0;\n}\n\n// Changed to use PyList_SetSlice instead of the internal list_ass_slice\nstatic PyObject *\nlist_pop_impl(PyListObject *self, Py_ssize_t index)\n{\n    PyObject *v;\n    int status;\n\n    if (Py_SIZE(self) == 0) {\n        /* Special-case most common failure cause */\n        PyErr_SetString(PyExc_IndexError, \"pop from empty list\");\n        return NULL;\n    }\n    if (index < 0)\n        index += Py_SIZE(self);\n    if (index < 0 || index >= Py_SIZE(self)) {\n        PyErr_SetString(PyExc_IndexError, \"pop index out of range\");\n        return NULL;\n    }\n    v = self->ob_item[index];\n    if (index == Py_SIZE(self) - 1) {\n        status = list_resize(self, Py_SIZE(self) - 1);\n        if (status >= 0)\n            return v; /* and v now owns the reference the list had */\n        else\n            return NULL;\n    }\n    Py_INCREF(v);\n    status = PyList_SetSlice((PyObject *)self, index, index+1, (PyObject *)NULL);\n    if (status < 0) {\n        Py_DECREF(v);\n        return NULL;\n    }\n    return v;\n}\n\n// Tweaked to directly use CPyTagged\nstatic CPyTagged\nlist_count(PyListObject *self, PyObject *value)\n{\n    Py_ssize_t count = 0;\n    Py_ssize_t i;\n\n    for (i = 0; i < Py_SIZE(self); i++) {\n        int cmp = PyObject_RichCompareBool(self->ob_item[i], value, Py_EQ);\n        if (cmp > 0)\n            count++;\n        else if (cmp < 0)\n            return CPY_INT_TAG;\n    }\n    return CPyTagged_ShortFromSsize_t(count);\n}\n\n// Adapted from genobject.c in Python 3.7.2\n// Copied because it wasn't in 3.5.2 and it is undocumented anyways.\n/*\n * Set StopIteration with specified value.  Value can be arbitrary object\n * or NULL.\n *\n * Returns 0 if StopIteration is set and -1 if any other exception is set.\n */\nstatic int\nCPyGen_SetStopIterationValue(PyObject *value)\n{\n    PyObject *e;\n\n    if (value == NULL ||\n        (!PyTuple_Check(value) && !PyExceptionInstance_Check(value)))\n    {\n        /* Delay exception instantiation if we can */\n        PyErr_SetObject(PyExc_StopIteration, value);\n        return 0;\n    }\n    /* Construct an exception instance manually with\n     * PyObject_CallOneArg and pass it to PyErr_SetObject.\n     *\n     * We do this to handle a situation when \"value\" is a tuple, in which\n     * case PyErr_SetObject would set the value of StopIteration to\n     * the first element of the tuple.\n     *\n     * (See PyErr_SetObject/_PyErr_CreateException code for details.)\n     */\n    e = PyObject_CallOneArg(PyExc_StopIteration, value);\n    if (e == NULL) {\n        return -1;\n    }\n    PyErr_SetObject(PyExc_StopIteration, e);\n    Py_DECREF(e);\n    return 0;\n}\n\n// Copied from dictobject.c and dictobject.h, these are not Public before\n// Python 3.8. Also remove some error checks that we do in the callers.\ntypedef struct {\n    PyObject_HEAD\n    PyDictObject *dv_dict;\n} _CPyDictViewObject;\n\nstatic PyObject *\n_CPyDictView_New(PyObject *dict, PyTypeObject *type)\n{\n    _CPyDictViewObject *dv = PyObject_GC_New(_CPyDictViewObject, type);\n    if (dv == NULL)\n        return NULL;\n    Py_INCREF(dict);\n    dv->dv_dict = (PyDictObject *)dict;\n    PyObject_GC_Track(dv);\n    return (PyObject *)dv;\n}\n\n#ifdef __cplusplus\n}\n#endif\n\n#if CPY_3_12_FEATURES\n\n// These are copied from genobject.c in Python 3.12\n\nstatic int\ngen_is_coroutine(PyObject *o)\n{\n    if (PyGen_CheckExact(o)) {\n        PyCodeObject *code = PyGen_GetCode((PyGenObject*)o);\n        if (code->co_flags & CO_ITERABLE_COROUTINE) {\n            return 1;\n        }\n    }\n    return 0;\n}\n\n#else\n\n// Copied from genobject.c in Python 3.10\nstatic int\ngen_is_coroutine(PyObject *o)\n{\n    if (PyGen_CheckExact(o)) {\n        PyCodeObject *code = (PyCodeObject *)((PyGenObject*)o)->gi_code;\n        if (code->co_flags & CO_ITERABLE_COROUTINE) {\n            return 1;\n        }\n    }\n    return 0;\n}\n\n#endif\n\n/*\n *   This helper function returns an awaitable for `o`:\n *     - `o` if `o` is a coroutine-object;\n *     - `type(o)->tp_as_async->am_await(o)`\n *\n *   Raises a TypeError if it's not possible to return\n *   an awaitable and returns NULL.\n */\nstatic PyObject *\nCPyCoro_GetAwaitableIter(PyObject *o)\n{\n    unaryfunc getter = NULL;\n    PyTypeObject *ot;\n\n    if (PyCoro_CheckExact(o) || gen_is_coroutine(o)) {\n        /* 'o' is a coroutine. */\n        Py_INCREF(o);\n        return o;\n    }\n\n    ot = Py_TYPE(o);\n    if (ot->tp_as_async != NULL) {\n        getter = ot->tp_as_async->am_await;\n    }\n    if (getter != NULL) {\n        PyObject *res = (*getter)(o);\n        if (res != NULL) {\n            if (PyCoro_CheckExact(res) || gen_is_coroutine(res)) {\n                /* __await__ must return an *iterator*, not\n                   a coroutine or another awaitable (see PEP 492) */\n                PyErr_SetString(PyExc_TypeError,\n                                \"__await__() returned a coroutine\");\n                Py_CLEAR(res);\n            } else if (!PyIter_Check(res)) {\n                PyErr_Format(PyExc_TypeError,\n                             \"__await__() returned non-iterator \"\n                             \"of type '%.100s'\",\n                             Py_TYPE(res)->tp_name);\n                Py_CLEAR(res);\n            }\n        }\n        return res;\n    }\n\n    PyErr_Format(PyExc_TypeError,\n                 \"object %.100s can't be used in 'await' expression\",\n                 ot->tp_name);\n    return NULL;\n}\n\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/set_ops.c",
    "content": "// Set primitive operations\n//\n// These are registered in mypyc.primitives.set_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\n\nbool CPySet_Remove(PyObject *set, PyObject *key) {\n    int success = PySet_Discard(set, key);\n    if (success == 1) {\n        return true;\n    }\n    if (success == 0) {\n        _PyErr_SetKeyError(key);\n    }\n    return false;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/setup.py",
    "content": "\"\"\"Build script for mypyc C runtime library and C API unit tests.\n\nThe tests are written in C++ and use the Google Test framework.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport subprocess\nimport sys\nfrom distutils import ccompiler, sysconfig\nfrom typing import Any\n\n# we'll import stuff from the source tree, let's ensure is on the sys path\nsys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))\n\nimport build_setup  # noqa: F401\nfrom setuptools import Extension, setup\nfrom setuptools.command.build_ext import build_ext\n\nC_APIS_TO_TEST = [\n    \"init.c\",\n    \"int_ops.c\",\n    \"float_ops.c\",\n    \"list_ops.c\",\n    \"exc_ops.c\",\n    \"generic_ops.c\",\n    \"pythonsupport.c\",\n]\n\n\nclass BuildExtGtest(build_ext):\n    def get_library_names(self) -> list[str]:\n        return [\"gtest\"]\n\n    def run(self) -> None:\n        # Build Google Test, the C++ framework we use for testing C code.\n        # The source code for Google Test is copied to this repository.\n        gtest_dir = os.path.abspath(\n            os.path.join(os.path.dirname(__file__), \"..\", \"external\", \"googletest\")\n        )\n        os.makedirs(self.build_temp, exist_ok=True)\n        subprocess.check_call(\n            [\"make\", \"-f\", os.path.join(gtest_dir, \"make\", \"Makefile\"), f\"GTEST_DIR={gtest_dir}\"],\n            cwd=self.build_temp,\n        )\n        self.library_dirs = [self.build_temp]\n        return build_ext.run(self)\n\n\nif \"--run-capi-tests\" in sys.argv:\n    sys.argv.pop()\n\n    kwargs: dict[str, Any]\n    if sys.platform == \"darwin\":\n        kwargs = {\"language\": \"c++\"}\n        compile_args: list[str] = []\n    else:\n        kwargs = {}\n        compile_args = [\"--std=c++11\"]\n\n    setup(\n        name=\"test_capi\",\n        version=\"0.1\",\n        ext_modules=[\n            Extension(\n                \"test_capi\",\n                [\"test_capi.cc\"] + C_APIS_TO_TEST,\n                depends=[\"CPy.h\", \"mypyc_util.h\", \"pythonsupport.h\"],\n                extra_compile_args=[\"-Wno-unused-function\", \"-Wno-sign-compare\"] + compile_args,\n                libraries=[\"gtest\"],\n                include_dirs=[\"../external/googletest\", \"../external/googletest/include\"],\n                **kwargs,\n            )\n        ],\n        cmdclass={\"build_ext\": BuildExtGtest},\n    )\nelse:\n    compiler = ccompiler.new_compiler()\n    sysconfig.customize_compiler(compiler)\n    cflags: list[str] = []\n    if compiler.compiler_type == \"unix\":  # type: ignore[attr-defined]\n        cflags += [\"-O3\", \"-Wno-unused-function\"]\n    elif compiler.compiler_type == \"msvc\":  # type: ignore[attr-defined]\n        cflags += [\"/O2\"]\n\n    setup(\n        ext_modules=[\n            Extension(\n                \"librt.internal\",\n                [\n                    \"internal/librt_internal.c\",\n                    \"init.c\",\n                    \"int_ops.c\",\n                    \"exc_ops.c\",\n                    \"pythonsupport.c\",\n                    \"getargsfast.c\",\n                ],\n                include_dirs=[\".\", \"internal\"],\n                extra_compile_args=cflags,\n            ),\n            Extension(\n                \"librt.strings\",\n                [\n                    \"strings/librt_strings.c\",\n                    \"init.c\",\n                    \"int_ops.c\",\n                    \"exc_ops.c\",\n                    \"pythonsupport.c\",\n                    \"getargsfast.c\",\n                ],\n                include_dirs=[\".\", \"strings\"],\n                extra_compile_args=cflags,\n            ),\n            Extension(\n                \"librt.base64\",\n                [\n                    \"base64/librt_base64.c\",\n                    \"base64/lib.c\",\n                    \"base64/codec_choose.c\",\n                    \"base64/tables/tables.c\",\n                    \"base64/arch/generic/codec.c\",\n                    \"base64/arch/ssse3/codec.c\",\n                    \"base64/arch/sse41/codec.c\",\n                    \"base64/arch/sse42/codec.c\",\n                    \"base64/arch/avx/codec.c\",\n                    \"base64/arch/avx2/codec.c\",\n                    \"base64/arch/avx512/codec.c\",\n                    \"base64/arch/neon32/codec.c\",\n                    \"base64/arch/neon64/codec.c\",\n                ],\n                include_dirs=[\".\", \"base64\"],\n                extra_compile_args=cflags,\n            ),\n            Extension(\n                \"librt.vecs\",\n                [\n                    \"vecs/librt_vecs.c\",\n                    \"vecs/vec_i64.c\",\n                    \"vecs/vec_i32.c\",\n                    \"vecs/vec_i16.c\",\n                    \"vecs/vec_u8.c\",\n                    \"vecs/vec_float.c\",\n                    \"vecs/vec_bool.c\",\n                    \"vecs/vec_t.c\",\n                    \"vecs/vec_nested.c\",\n                ],\n                include_dirs=[\".\", \"vecs\"],\n                extra_compile_args=cflags,\n            ),\n            Extension(\n                \"librt.time\", [\"time/librt_time.c\"], include_dirs=[\".\"], extra_compile_args=cflags\n            ),\n        ]\n    )\n"
  },
  {
    "path": "mypyc/lib-rt/static_data.c",
    "content": "#ifndef STATIC_DATA\n#define STATIC_DATA\n\n#include \"static_data.h\"\n\n// Adopted from numpy 2.4.0: numpy/_core/src/multiarry/npy_static_data.c\n\nmypyc_interned_str_struct mypyc_interned_str;\n\n#define INTERN_STRING(struct_member, string) \\\n    assert(mypyc_interned_str.struct_member == NULL); \\\n    mypyc_interned_str.struct_member = PyUnicode_InternFromString(string); \\\n    if (mypyc_interned_str.struct_member == NULL) { \\\n        return -1; \\\n    }\n\nint\nintern_strings(void) {\n    if (mypyc_interned_str.values != NULL) {\n        // Already interned.\n        return 0;\n    }\n    INTERN_STRING(__init_subclass__, \"__init_subclass__\");\n    INTERN_STRING(__module__, \"__module__\");\n    INTERN_STRING(__mro_entries__, \"__mro_entries__\");\n    INTERN_STRING(__mypyc_attrs__, \"__mypyc_attrs__\");\n    INTERN_STRING(__name__, \"__name__\");\n    INTERN_STRING(__orig_bases__, \"__orig_bases__\");\n    INTERN_STRING(__qualname__, \"__qualname__\");\n    INTERN_STRING(__slots__, \"__slots__\");\n    INTERN_STRING(__radd__, \"__radd__\");\n    INTERN_STRING(__rsub__, \"__rsub__\");\n    INTERN_STRING(__rmul__, \"__rmul__\");\n    INTERN_STRING(__rtruediv__, \"__rtruediv__\");\n    INTERN_STRING(__rmod__, \"__rmod__\");\n    INTERN_STRING(__rdivmod__, \"__rdivmod__\");\n    INTERN_STRING(__rfloordiv__, \"__rfloordiv__\");\n    INTERN_STRING(__rpow__, \"__rpow__\");\n    INTERN_STRING(__rmatmul__, \"__rmatmul__\");\n    INTERN_STRING(__rand__, \"__rand__\");\n    INTERN_STRING(__ror__, \"__ror__\");\n    INTERN_STRING(__rxor__, \"__rxor__\");\n    INTERN_STRING(__rlshift__, \"__rlshift__\");\n    INTERN_STRING(__rrshift__, \"__rrshift__\");\n    INTERN_STRING(__eq__, \"__eq__\");\n    INTERN_STRING(__ne__, \"__ne__\");\n    INTERN_STRING(__gt__, \"__gt__\");\n    INTERN_STRING(__le__, \"__le__\");\n    INTERN_STRING(__lt__, \"__lt__\");\n    INTERN_STRING(__ge__, \"__ge__\");\n    INTERN_STRING(clear, \"clear\");\n    INTERN_STRING(close_, \"close\");\n    INTERN_STRING(copy, \"copy\");\n    INTERN_STRING(dispatch_cache, \"dispatch_cache\");\n    INTERN_STRING(endswith, \"endswith\");\n    INTERN_STRING(get_type_hints, \"get_type_hints\");\n    INTERN_STRING(keys, \"keys\");\n    INTERN_STRING(lower, \"lower\");\n    INTERN_STRING(items, \"items\");\n    INTERN_STRING(join, \"join\");\n    INTERN_STRING(register_, \"register\");\n    INTERN_STRING(registry, \"registry\");\n    INTERN_STRING(send, \"send\");\n    INTERN_STRING(setdefault, \"setdefault\");\n    INTERN_STRING(startswith, \"startswith\");\n    INTERN_STRING(super, \"super\");\n    INTERN_STRING(throw_, \"throw\");\n    INTERN_STRING(translate, \"translate\");\n    INTERN_STRING(update, \"update\");\n    INTERN_STRING(upper, \"upper\");\n    INTERN_STRING(values, \"values\");\n    return 0;\n}\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/static_data.h",
    "content": "#ifndef STATIC_DATA_H\n#define STATIC_DATA_H\n\n#include <Python.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// Adopted from numpy 2.4.0: numpy/_core/src/multiarry/npy_static_data.h\n\nint intern_strings(void);\n\ntypedef struct mypyc_interned_str_struct {\n    PyObject *__init_subclass__;\n    PyObject *__module__;\n    PyObject *__mro_entries__;\n    PyObject *__mypyc_attrs__;\n    PyObject *__orig_bases__;\n    PyObject *__qualname__;\n    PyObject *__slots__;\n    PyObject *__name__;\n    PyObject *__radd__;\n    PyObject *__rsub__;\n    PyObject *__rmul__;\n    PyObject *__rtruediv__;\n    PyObject *__rmod__;\n    PyObject *__rdivmod__;\n    PyObject *__rfloordiv__;\n    PyObject *__rpow__;\n    PyObject *__rmatmul__;\n    PyObject *__rand__;\n    PyObject *__ror__;\n    PyObject *__rxor__;\n    PyObject *__rlshift__;\n    PyObject *__rrshift__;\n    PyObject *__eq__;\n    PyObject *__ne__;\n    PyObject *__gt__;\n    PyObject *__le__;\n    PyObject *__lt__;\n    PyObject *__ge__;\n    PyObject *clear;\n    PyObject *close_;\n    PyObject *copy;\n    PyObject *dispatch_cache;\n    PyObject *endswith;\n    PyObject *get_type_hints;\n    PyObject *keys;\n    PyObject *lower;\n    PyObject *items;\n    PyObject *join;\n    PyObject *register_;\n    PyObject *registry;\n    PyObject *send;\n    PyObject *setdefault;\n    PyObject *startswith;\n    PyObject *super;\n    PyObject *throw_;\n    PyObject *translate;\n    PyObject *update;\n    PyObject *upper;\n    PyObject *values;\n} mypyc_interned_str_struct;\n\nextern mypyc_interned_str_struct mypyc_interned_str;\n\n#ifdef __cplusplus\n}\n#endif\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/str_extra_ops.c",
    "content": "#include \"str_extra_ops.h\"\n\n// All str extra ops are inline functions in str_extra_ops.h\n// This file exists to satisfy the SourceDep requirements\n"
  },
  {
    "path": "mypyc/lib-rt/str_extra_ops.h",
    "content": "#ifndef MYPYC_STR_EXTRA_OPS_H\n#define MYPYC_STR_EXTRA_OPS_H\n\n#include <Python.h>\n#include <stdint.h>\n#include \"CPy.h\"\n\n// Optimized str indexing for ord(s[i])\n\n// If index is negative, convert to non-negative index (no range checking)\nstatic inline int64_t CPyStr_AdjustIndex(PyObject *obj, int64_t index) {\n    if (index < 0) {\n        return index + PyUnicode_GET_LENGTH(obj);\n    }\n    return index;\n}\n\n// Check if index is in valid range [0, len)\nstatic inline bool CPyStr_RangeCheck(PyObject *obj, int64_t index) {\n    return index >= 0 && index < PyUnicode_GET_LENGTH(obj);\n}\n\n// Get character at index as int (ord value) - no bounds checking, returns as CPyTagged\nstatic inline CPyTagged CPyStr_GetItemUnsafeAsInt(PyObject *obj, int64_t index) {\n    int kind = PyUnicode_KIND(obj);\n    return PyUnicode_READ(kind, PyUnicode_DATA(obj), index) << 1;\n}\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/str_ops.c",
    "content": "#include \"pythoncapi_compat.h\"\n\n// String primitive operations\n//\n// These are registered in mypyc.primitives.str_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\n\n// The _PyUnicode_CheckConsistency definition has been moved to the internal API\n// https://github.com/python/cpython/pull/106398\n#if defined(Py_DEBUG) && CPY_3_13_FEATURES\n#include \"internal/pycore_unicodeobject.h\"\n#endif\n\n// Copied from cpython.git:Objects/unicodeobject.c@0ef4ffeefd1737c18dc9326133c7894d58108c2e.\n#define BLOOM_MASK unsigned long\n#define BLOOM(mask, ch)     ((mask &  (1UL << ((ch) & (BLOOM_WIDTH - 1)))))\n#if LONG_BIT >= 128\n#define BLOOM_WIDTH 128\n#elif LONG_BIT >= 64\n#define BLOOM_WIDTH 64\n#elif LONG_BIT >= 32\n#define BLOOM_WIDTH 32\n#else\n#error \"LONG_BIT is smaller than 32\"\n#endif\n\n// Copied from cpython.git:Objects/unicodeobject.c@0ef4ffeefd1737c18dc9326133c7894d58108c2e.\n// This is needed for str.strip(\"...\").\nstatic inline BLOOM_MASK\nmake_bloom_mask(int kind, const void* ptr, Py_ssize_t len)\n{\n#define BLOOM_UPDATE(TYPE, MASK, PTR, LEN)             \\\n    do {                                               \\\n        TYPE *data = (TYPE *)PTR;                      \\\n        TYPE *end = data + LEN;                        \\\n        Py_UCS4 ch;                                    \\\n        for (; data != end; data++) {                  \\\n            ch = *data;                                \\\n            MASK |= (1UL << (ch & (BLOOM_WIDTH - 1))); \\\n        }                                              \\\n        break;                                         \\\n    } while (0)\n\n    /* calculate simple bloom-style bitmask for a given unicode string */\n\n    BLOOM_MASK mask;\n\n    mask = 0;\n    switch (kind) {\n    case PyUnicode_1BYTE_KIND:\n        BLOOM_UPDATE(Py_UCS1, mask, ptr, len);\n        break;\n    case PyUnicode_2BYTE_KIND:\n        BLOOM_UPDATE(Py_UCS2, mask, ptr, len);\n        break;\n    case PyUnicode_4BYTE_KIND:\n        BLOOM_UPDATE(Py_UCS4, mask, ptr, len);\n        break;\n    default:\n        Py_UNREACHABLE();\n    }\n    return mask;\n\n#undef BLOOM_UPDATE\n}\n\nstatic inline char _CPyStr_Equal_NoIdentCheck(PyObject *str1, PyObject *str2, Py_ssize_t str2_length) {\n    // This helper function only exists to deduplicate code in CPyStr_Equal and CPyStr_EqualLiteral\n    Py_ssize_t str1_length = PyUnicode_GET_LENGTH(str1);\n    if (str1_length != str2_length)\n        return 0;\n    int kind = PyUnicode_KIND(str1);\n    if (PyUnicode_KIND(str2) != kind)\n        return 0;\n    const void *data1 = PyUnicode_DATA(str1);\n    const void *data2 = PyUnicode_DATA(str2);\n    return memcmp(data1, data2, str1_length * kind) == 0;\n}\n\n// Adapted from CPython 3.13.1 (_PyUnicode_Equal)\nchar CPyStr_Equal(PyObject *str1, PyObject *str2) {\n    if (str1 == str2) {\n        return 1;\n    }\n    Py_ssize_t str2_length = PyUnicode_GET_LENGTH(str2);\n    return _CPyStr_Equal_NoIdentCheck(str1, str2, str2_length);\n}\n\nchar CPyStr_EqualLiteral(PyObject *str, PyObject *literal_str, Py_ssize_t literal_length) {\n    if (str == literal_str) {\n        return 1;\n    }\n    return _CPyStr_Equal_NoIdentCheck(str, literal_str, literal_length);\n}\n\nPyObject *CPyStr_GetItem(PyObject *str, CPyTagged index) {\n    if (PyUnicode_READY(str) != -1) {\n        if (CPyTagged_CheckShort(index)) {\n            Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n            Py_ssize_t size = PyUnicode_GET_LENGTH(str);\n            if (n < 0)\n                n += size;\n            if (n < 0 || n >= size) {\n                PyErr_SetString(PyExc_IndexError, \"string index out of range\");\n                return NULL;\n            }\n            enum PyUnicode_Kind kind = (enum PyUnicode_Kind)PyUnicode_KIND(str);\n            void *data = PyUnicode_DATA(str);\n            Py_UCS4 ch = PyUnicode_READ(kind, data, n);\n            if (ch < 256) {\n                // Latin-1 single-char strings are cached by CPython, so\n                // PyUnicode_FromOrdinal returns the cached object (with a\n                // new reference) instead of allocating a new string each time.\n                return PyUnicode_FromOrdinal(ch);\n            }\n            PyObject *unicode = PyUnicode_New(1, ch);\n            if (unicode == NULL)\n                return NULL;\n            if (PyUnicode_KIND(unicode) == PyUnicode_2BYTE_KIND) {\n                PyUnicode_2BYTE_DATA(unicode)[0] = (Py_UCS2)ch;\n            } else {\n                assert(PyUnicode_KIND(unicode) == PyUnicode_4BYTE_KIND);\n                PyUnicode_4BYTE_DATA(unicode)[0] = ch;\n            }\n            return unicode;\n        } else {\n            PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n            return NULL;\n        }\n    } else {\n        PyObject *index_obj = CPyTagged_AsObject(index);\n        return PyObject_GetItem(str, index_obj);\n    }\n}\n\nPyObject *CPyStr_GetItemUnsafe(PyObject *str, Py_ssize_t index) {\n    // This is unsafe since we don't check for overflow when doing <<.\n    return CPyStr_GetItem(str, index << 1);\n}\n\n// A simplification of _PyUnicode_JoinArray() from CPython 3.9.6\nPyObject *CPyStr_Build(Py_ssize_t len, ...) {\n    Py_ssize_t i;\n    va_list args;\n\n    // Calculate the total amount of space and check\n    // whether all components have the same kind.\n    Py_ssize_t sz = 0;\n    Py_UCS4 maxchar = 0;\n    int use_memcpy = 1; // Use memcpy by default\n    PyObject *last_obj = NULL;\n\n    va_start(args, len);\n    for (i = 0; i < len; i++) {\n        PyObject *item = va_arg(args, PyObject *);\n        if (!PyUnicode_Check(item)) {\n            PyErr_Format(PyExc_TypeError,\n                         \"sequence item %zd: expected str instance,\"\n                         \" %.80s found\",\n                         i, Py_TYPE(item)->tp_name);\n            return NULL;\n        }\n        if (PyUnicode_READY(item) == -1)\n            return NULL;\n\n        size_t add_sz = PyUnicode_GET_LENGTH(item);\n        Py_UCS4 item_maxchar = PyUnicode_MAX_CHAR_VALUE(item);\n        maxchar = Py_MAX(maxchar, item_maxchar);\n\n        // Using size_t to avoid overflow during arithmetic calculation\n        if (add_sz > (size_t)(PY_SSIZE_T_MAX - sz)) {\n            PyErr_SetString(PyExc_OverflowError,\n                            \"join() result is too long for a Python string\");\n            return NULL;\n        }\n        sz += add_sz;\n\n        // If these strings have different kind, we would call\n        // _PyUnicode_FastCopyCharacters() in the following part.\n        if (use_memcpy && last_obj != NULL) {\n            if (PyUnicode_KIND(last_obj) != PyUnicode_KIND(item))\n                use_memcpy = 0;\n        }\n        last_obj = item;\n    }\n    va_end(args);\n\n    // Construct the string\n    PyObject *res = PyUnicode_New(sz, maxchar);\n    if (res == NULL)\n        return NULL;\n\n    if (use_memcpy) {\n        unsigned char *res_data = PyUnicode_1BYTE_DATA(res);\n        unsigned int kind = PyUnicode_KIND(res);\n\n        va_start(args, len);\n        for (i = 0; i < len; ++i) {\n            PyObject *item = va_arg(args, PyObject *);\n            Py_ssize_t itemlen = PyUnicode_GET_LENGTH(item);\n            if (itemlen != 0) {\n                memcpy(res_data, PyUnicode_DATA(item), kind * itemlen);\n                res_data += kind * itemlen;\n            }\n        }\n        va_end(args);\n        assert(res_data == PyUnicode_1BYTE_DATA(res) + kind * PyUnicode_GET_LENGTH(res));\n    } else {\n        Py_ssize_t res_offset = 0;\n\n        va_start(args, len);\n        for (i = 0; i < len; ++i) {\n            PyObject *item = va_arg(args, PyObject *);\n            Py_ssize_t itemlen = PyUnicode_GET_LENGTH(item);\n            if (itemlen != 0) {\n#if CPY_3_13_FEATURES\n                PyUnicode_CopyCharacters(res, res_offset, item, 0, itemlen);\n#else\n                _PyUnicode_FastCopyCharacters(res, res_offset, item, 0, itemlen);\n#endif\n                res_offset += itemlen;\n            }\n        }\n        va_end(args);\n        assert(res_offset == PyUnicode_GET_LENGTH(res));\n    }\n\n#ifdef Py_DEBUG\n    assert(_PyUnicode_CheckConsistency(res, 1));\n#endif\n    return res;\n}\n\nCPyTagged CPyStr_Find(PyObject *str, PyObject *substr, CPyTagged start, int direction) {\n    CPyTagged end = PyUnicode_GET_LENGTH(str) << 1;\n    return CPyStr_FindWithEnd(str, substr, start, end, direction);\n}\n\nCPyTagged CPyStr_FindWithEnd(PyObject *str, PyObject *substr, CPyTagged start, CPyTagged end, int direction) {\n    Py_ssize_t temp_start = CPyTagged_AsSsize_t(start);\n    if (temp_start == -1 && PyErr_Occurred()) {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return CPY_INT_TAG;\n    }\n    Py_ssize_t temp_end = CPyTagged_AsSsize_t(end);\n    if (temp_end == -1 && PyErr_Occurred()) {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return CPY_INT_TAG;\n    }\n    Py_ssize_t index = PyUnicode_Find(str, substr, temp_start, temp_end, direction);\n    if (unlikely(index == -2)) {\n        return CPY_INT_TAG;\n    }\n    return index << 1;\n}\n\nPyObject *CPyStr_Split(PyObject *str, PyObject *sep, CPyTagged max_split) {\n    Py_ssize_t temp_max_split = CPyTagged_AsSsize_t(max_split);\n    if (temp_max_split == -1 && PyErr_Occurred()) {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return NULL;\n    }\n    return PyUnicode_Split(str, sep, temp_max_split);\n}\n\nPyObject *CPyStr_RSplit(PyObject *str, PyObject *sep, CPyTagged max_split) {\n    Py_ssize_t temp_max_split = CPyTagged_AsSsize_t(max_split);\n    if (temp_max_split == -1 && PyErr_Occurred()) {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return NULL;\n    }\n    return PyUnicode_RSplit(str, sep, temp_max_split);\n}\n\n// This function has been copied from _PyUnicode_XStrip in cpython.git:Objects/unicodeobject.c@0ef4ffeefd1737c18dc9326133c7894d58108c2e.\nstatic PyObject *_PyStr_XStrip(PyObject *self, int striptype, PyObject *sepobj) {\n    const void *data;\n    int kind;\n    Py_ssize_t i, j, len;\n    BLOOM_MASK sepmask;\n    Py_ssize_t seplen;\n\n    // This check is needed from Python 3.9 and earlier.\n    if (PyUnicode_READY(self) == -1 || PyUnicode_READY(sepobj) == -1)\n        return NULL;\n\n    kind = PyUnicode_KIND(self);\n    data = PyUnicode_DATA(self);\n    len = PyUnicode_GET_LENGTH(self);\n    seplen = PyUnicode_GET_LENGTH(sepobj);\n    sepmask = make_bloom_mask(PyUnicode_KIND(sepobj),\n                              PyUnicode_DATA(sepobj),\n                              seplen);\n\n    i = 0;\n    if (striptype != RIGHTSTRIP) {\n        while (i < len) {\n            Py_UCS4 ch = PyUnicode_READ(kind, data, i);\n            if (!BLOOM(sepmask, ch))\n                break;\n            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)\n                break;\n            i++;\n        }\n    }\n\n    j = len;\n    if (striptype != LEFTSTRIP) {\n        j--;\n        while (j >= i) {\n            Py_UCS4 ch = PyUnicode_READ(kind, data, j);\n            if (!BLOOM(sepmask, ch))\n                break;\n            if (PyUnicode_FindChar(sepobj, ch, 0, seplen, 1) < 0)\n                break;\n            j--;\n        }\n\n        j++;\n    }\n\n    return PyUnicode_Substring(self, i, j);\n}\n\n// Copied from do_strip function in cpython.git/Objects/unicodeobject.c@0ef4ffeefd1737c18dc9326133c7894d58108c2e.\nPyObject *_CPyStr_Strip(PyObject *self, int strip_type, PyObject *sep) {\n    if (sep == NULL || Py_IsNone(sep)) {\n        Py_ssize_t len, i, j;\n\n        // This check is needed from Python 3.9 and earlier.\n        if (PyUnicode_READY(self) == -1)\n            return NULL;\n\n        len = PyUnicode_GET_LENGTH(self);\n\n        if (PyUnicode_IS_ASCII(self)) {\n            const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);\n\n            i = 0;\n            if (strip_type != RIGHTSTRIP) {\n                while (i < len) {\n                    Py_UCS1 ch = data[i];\n                    if (!_Py_ascii_whitespace[ch])\n                        break;\n                    i++;\n                }\n            }\n\n            j = len;\n            if (strip_type != LEFTSTRIP) {\n                j--;\n                while (j >= i) {\n                    Py_UCS1 ch = data[j];\n                    if (!_Py_ascii_whitespace[ch])\n                        break;\n                    j--;\n                }\n                j++;\n            }\n        }\n        else {\n            int kind = PyUnicode_KIND(self);\n            const void *data = PyUnicode_DATA(self);\n\n            i = 0;\n            if (strip_type != RIGHTSTRIP) {\n                while (i < len) {\n                    Py_UCS4 ch = PyUnicode_READ(kind, data, i);\n                    if (!Py_UNICODE_ISSPACE(ch))\n                        break;\n                    i++;\n                }\n            }\n\n            j = len;\n            if (strip_type != LEFTSTRIP) {\n                j--;\n                while (j >= i) {\n                    Py_UCS4 ch = PyUnicode_READ(kind, data, j);\n                    if (!Py_UNICODE_ISSPACE(ch))\n                        break;\n                    j--;\n                }\n                j++;\n            }\n        }\n\n        return PyUnicode_Substring(self, i, j);\n    }\n    return _PyStr_XStrip(self, strip_type, sep);\n}\n\nPyObject *CPyStr_Replace(PyObject *str, PyObject *old_substr,\n                         PyObject *new_substr, CPyTagged max_replace) {\n    Py_ssize_t temp_max_replace = CPyTagged_AsSsize_t(max_replace);\n    if (temp_max_replace == -1 && PyErr_Occurred()) {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return NULL;\n    }\n    return PyUnicode_Replace(str, old_substr, new_substr, temp_max_replace);\n}\n\nint CPyStr_Startswith(PyObject *self, PyObject *subobj) {\n    Py_ssize_t start = 0;\n    Py_ssize_t end = PyUnicode_GET_LENGTH(self);\n    if (PyTuple_Check(subobj)) {\n        Py_ssize_t i;\n        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {\n            PyObject *substring = PyTuple_GET_ITEM(subobj, i);\n            if (!PyUnicode_Check(substring)) {\n                PyErr_Format(PyExc_TypeError,\n                             \"tuple for startswith must only contain str, \"\n                             \"not %.100s\",\n                             Py_TYPE(substring)->tp_name);\n                return 2;\n            }\n            int result = PyUnicode_Tailmatch(self, substring, start, end, -1);\n            if (result) {\n                return 1;\n            }\n        }\n        return 0;\n    }\n    return PyUnicode_Tailmatch(self, subobj, start, end, -1);\n}\n\nint CPyStr_Endswith(PyObject *self, PyObject *subobj) {\n    Py_ssize_t start = 0;\n    Py_ssize_t end = PyUnicode_GET_LENGTH(self);\n    if (PyTuple_Check(subobj)) {\n        Py_ssize_t i;\n        for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {\n            PyObject *substring = PyTuple_GET_ITEM(subobj, i);\n            if (!PyUnicode_Check(substring)) {\n                PyErr_Format(PyExc_TypeError,\n                             \"tuple for endswith must only contain str, \"\n                             \"not %.100s\",\n                             Py_TYPE(substring)->tp_name);\n                return 2;\n            }\n            int result = PyUnicode_Tailmatch(self, substring, start, end, 1);\n            if (result) {\n                return 1;\n            }\n        }\n        return 0;\n    }\n    return PyUnicode_Tailmatch(self, subobj, start, end, 1);\n}\n\nPyObject *CPyStr_Removeprefix(PyObject *self, PyObject *prefix) {\n    Py_ssize_t end = PyUnicode_GET_LENGTH(self);\n    int match = PyUnicode_Tailmatch(self, prefix, 0, end, -1);\n    if (match) {\n        Py_ssize_t prefix_end = PyUnicode_GET_LENGTH(prefix);\n        return PyUnicode_Substring(self, prefix_end, end);\n    }\n    return Py_NewRef(self);\n}\n\nPyObject *CPyStr_Removesuffix(PyObject *self, PyObject *suffix) {\n    Py_ssize_t end = PyUnicode_GET_LENGTH(self);\n    int match = PyUnicode_Tailmatch(self, suffix, 0, end, 1);\n    if (match) {\n        Py_ssize_t suffix_end = PyUnicode_GET_LENGTH(suffix);\n        return PyUnicode_Substring(self, 0, end - suffix_end);\n    }\n    return Py_NewRef(self);\n}\n\n/* This does a dodgy attempt to append in place  */\nPyObject *CPyStr_Append(PyObject *o1, PyObject *o2) {\n    PyUnicode_Append(&o1, o2);\n    return o1;\n}\n\nPyObject *CPyStr_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) {\n    if (likely(PyUnicode_CheckExact(obj)\n               && CPyTagged_CheckShort(start) && CPyTagged_CheckShort(end))) {\n        Py_ssize_t startn = CPyTagged_ShortAsSsize_t(start);\n        Py_ssize_t endn = CPyTagged_ShortAsSsize_t(end);\n        if (startn < 0) {\n            startn += PyUnicode_GET_LENGTH(obj);\n            if (startn < 0) {\n                startn = 0;\n            }\n        }\n        if (endn < 0) {\n            endn += PyUnicode_GET_LENGTH(obj);\n            if (endn < 0) {\n                endn = 0;\n            }\n        }\n        return PyUnicode_Substring(obj, startn, endn);\n    }\n    return CPyObject_GetSlice(obj, start, end);\n}\n\n/* Check if the given string is true (i.e. its length isn't zero) */\nbool CPyStr_IsTrue(PyObject *obj) {\n    Py_ssize_t length = PyUnicode_GET_LENGTH(obj);\n    return length != 0;\n}\n\nPy_ssize_t CPyStr_Size_size_t(PyObject *str) {\n    if (PyUnicode_READY(str) != -1) {\n        return PyUnicode_GET_LENGTH(str);\n    }\n    return -1;\n}\n\nPyObject *CPy_Decode(PyObject *obj, PyObject *encoding, PyObject *errors) {\n    const char *enc = NULL;\n    const char *err = NULL;\n    if (encoding) {\n        enc = PyUnicode_AsUTF8AndSize(encoding, NULL);\n        if (!enc) return NULL;\n    }\n    if (errors) {\n        err = PyUnicode_AsUTF8AndSize(errors, NULL);\n        if (!err) return NULL;\n    }\n    if (PyBytes_Check(obj)) {\n        return PyUnicode_Decode(((PyBytesObject *)obj)->ob_sval,\n                                ((PyVarObject *)obj)->ob_size,\n                                enc, err);\n    } else {\n        return PyUnicode_FromEncodedObject(obj, enc, err);\n    }\n}\n\nPyObject *CPy_DecodeUTF8(PyObject *bytes) {\n    if (PyBytes_CheckExact(bytes)) {\n        char *buffer = PyBytes_AsString(bytes);   // Borrowed reference\n        if (buffer == NULL) {\n            return NULL;\n        }\n        Py_ssize_t size = PyBytes_Size(bytes);\n        return PyUnicode_DecodeUTF8(buffer, size, \"strict\");\n    } else {\n        return PyUnicode_FromEncodedObject(bytes, \"utf-8\", \"strict\");\n    }\n}\n\nPyObject *CPy_DecodeASCII(PyObject *bytes) {\n    if (PyBytes_CheckExact(bytes)) {\n        char *buffer = PyBytes_AsString(bytes);   // Borrowed reference\n        if (buffer == NULL) {\n            return NULL;\n        }\n        Py_ssize_t size = PyBytes_Size(bytes);\n        return PyUnicode_DecodeASCII(buffer, size, \"strict\");;\n    } else {\n        return PyUnicode_FromEncodedObject(bytes, \"ascii\", \"strict\");\n    }\n}\n\nPyObject *CPy_DecodeLatin1(PyObject *bytes) {\n    if (PyBytes_CheckExact(bytes)) {\n        char *buffer = PyBytes_AsString(bytes);   // Borrowed reference\n        if (buffer == NULL) {\n            return NULL;\n        }\n        Py_ssize_t size = PyBytes_Size(bytes);\n        return PyUnicode_DecodeLatin1(buffer, size, \"strict\");\n    } else {\n        return PyUnicode_FromEncodedObject(bytes, \"latin1\", \"strict\");\n    }\n}\n\nPyObject *CPy_Encode(PyObject *obj, PyObject *encoding, PyObject *errors) {\n    const char *enc = NULL;\n    const char *err = NULL;\n    if (encoding) {\n        enc = PyUnicode_AsUTF8AndSize(encoding, NULL);\n        if (!enc) return NULL;\n    }\n    if (errors) {\n        err = PyUnicode_AsUTF8AndSize(errors, NULL);\n        if (!err) return NULL;\n    }\n    if (PyUnicode_Check(obj)) {\n        return PyUnicode_AsEncodedString(obj, enc, err);\n    } else {\n        PyErr_BadArgument();\n        return NULL;\n    }\n}\n\nPy_ssize_t CPyStr_Count(PyObject *unicode, PyObject *substring, CPyTagged start) {\n    Py_ssize_t temp_start = CPyTagged_AsSsize_t(start);\n    if (temp_start == -1 && PyErr_Occurred()) {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return -1;\n    }\n    Py_ssize_t end = PyUnicode_GET_LENGTH(unicode);\n    return PyUnicode_Count(unicode, substring, temp_start, end);\n}\n\nPy_ssize_t CPyStr_CountFull(PyObject *unicode, PyObject *substring, CPyTagged start, CPyTagged end) {\n    Py_ssize_t temp_start = CPyTagged_AsSsize_t(start);\n    if (temp_start == -1 && PyErr_Occurred()) {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return -1;\n    }\n    Py_ssize_t temp_end = CPyTagged_AsSsize_t(end);\n    if (temp_end == -1 && PyErr_Occurred()) {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return -1;\n    }\n    return PyUnicode_Count(unicode, substring, temp_start, temp_end);\n}\n\n\nCPyTagged CPyStr_Ord(PyObject *obj) {\n    Py_ssize_t s = PyUnicode_GET_LENGTH(obj);\n    if (s == 1) {\n        int kind = PyUnicode_KIND(obj);\n        return PyUnicode_READ(kind, PyUnicode_DATA(obj), 0) << 1;\n    }\n    PyErr_Format(\n        PyExc_TypeError, \"ord() expected a character, but a string of length %zd found\", s);\n    return CPY_INT_TAG;\n}\n\nPyObject *CPyStr_Multiply(PyObject *str, CPyTagged count) {\n    Py_ssize_t temp_count = CPyTagged_AsSsize_t(count);\n    if (temp_count == -1 && PyErr_Occurred()) {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return NULL;\n    }\n    return PySequence_Repeat(str, temp_count);\n}\n\n\nbool CPyStr_IsSpace(PyObject *str) {\n    Py_ssize_t len = PyUnicode_GET_LENGTH(str);\n    if (len == 0) return false;\n\n    if (PyUnicode_IS_ASCII(str)) {\n        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(str);\n        for (Py_ssize_t i = 0; i < len; i++) {\n            if (!_Py_ascii_whitespace[data[i]])\n                return false;\n        }\n        return true;\n    }\n\n    int kind = PyUnicode_KIND(str);\n    const void *data = PyUnicode_DATA(str);\n    for (Py_ssize_t i = 0; i < len; i++) {\n        Py_UCS4 ch = PyUnicode_READ(kind, data, i);\n        if (!Py_UNICODE_ISSPACE(ch))\n            return false;\n    }\n    return true;\n}\n\nbool CPyStr_IsAlnum(PyObject *str) {\n    Py_ssize_t len = PyUnicode_GET_LENGTH(str);\n    if (len == 0) return false;\n\n    if (PyUnicode_IS_ASCII(str)) {\n        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(str);\n        for (Py_ssize_t i = 0; i < len; i++) {\n            if (!Py_ISALNUM(data[i]))\n                return false;\n        }\n        return true;\n    }\n\n    int kind = PyUnicode_KIND(str);\n    const void *data = PyUnicode_DATA(str);\n    for (Py_ssize_t i = 0; i < len; i++) {\n        Py_UCS4 ch = PyUnicode_READ(kind, data, i);\n        if (!Py_UNICODE_ISALNUM(ch))\n            return false;\n    }\n    return true;\n}\n\nstatic inline int CPy_ASCII_Lower(unsigned char c) { return Py_TOLOWER(c); }\nstatic inline int CPy_ASCII_Upper(unsigned char c) { return Py_TOUPPER(c); }\n\nstatic inline PyObject *CPyStr_ChangeCase(PyObject *self,\n                                    int (*ascii_func)(unsigned char),\n#if CPY_3_13_FEATURES\n                                    PyObject *method_name\n#else\n                                    int (*unicode_func)(Py_UCS4, Py_UCS4 *)\n#endif\n                                    ) {\n    Py_ssize_t len = PyUnicode_GET_LENGTH(self);\n    if (len == 0) {\n        Py_INCREF(self);\n        return self;\n    }\n\n    // ASCII fast path: 1-to-1, no expansion possible\n    if (PyUnicode_IS_ASCII(self)) {\n        PyObject *res = PyUnicode_New(len, 127);\n        if (res == NULL) return NULL;\n        const Py_UCS1 *data = PyUnicode_1BYTE_DATA(self);\n        Py_UCS1 *res_data = PyUnicode_1BYTE_DATA(res);\n        for (Py_ssize_t i = 0; i < len; i++) {\n            res_data[i] = ascii_func(data[i]);\n        }\n        return res;\n    }\n\n#if CPY_3_13_FEATURES\n    // On 3.13+, _PyUnicode_ToLowerFull/ToUpperFull are no longer exported,\n    // so fall back to CPython's method implementation for non-ASCII strings.\n    return PyObject_CallMethodNoArgs(self, method_name);\n#else\n    // General Unicode: unicode_func handles 1-to-N expansion.\n    // Worst case: each codepoint expands to 3 (per Unicode standard).\n    // The tmp buffer is short-lived, and PyUnicode_FromKindAndData\n    // compacts the result to the optimal string kind automatically.\n    int kind = PyUnicode_KIND(self);\n    const void *data = PyUnicode_DATA(self);\n    Py_UCS4 *tmp = PyMem_Malloc(sizeof(Py_UCS4) * len * 3);\n    if (tmp == NULL) return PyErr_NoMemory();\n\n    Py_UCS4 mapped[3];\n    Py_ssize_t out_len = 0;\n    for (Py_ssize_t i = 0; i < len; i++) {\n        int n = unicode_func(PyUnicode_READ(kind, data, i), mapped);\n        for (int j = 0; j < n; j++) {\n            tmp[out_len++] = mapped[j];\n        }\n    }\n\n    PyObject *res = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, tmp, out_len);\n    PyMem_Free(tmp);\n    return res;\n#endif\n}\n\nPyObject *CPyStr_Lower(PyObject *self) {\n#if CPY_3_13_FEATURES\n    return CPyStr_ChangeCase(self, CPy_ASCII_Lower, mypyc_interned_str.lower);\n#else\n    return CPyStr_ChangeCase(self, CPy_ASCII_Lower, _PyUnicode_ToLowerFull);\n#endif\n}\n\nPyObject *CPyStr_Upper(PyObject *self) {\n#if CPY_3_13_FEATURES\n    return CPyStr_ChangeCase(self, CPy_ASCII_Upper, mypyc_interned_str.upper);\n#else\n    return CPyStr_ChangeCase(self, CPy_ASCII_Upper, _PyUnicode_ToUpperFull);\n#endif\n}\n\nbool CPyStr_IsDigit(PyObject *str) {\n    Py_ssize_t len = PyUnicode_GET_LENGTH(str);\n    if (len == 0) return false;\n\n#define CHECK_ISDIGIT(TYPE, DATA, CHECK)              \\\n    {                                                 \\\n        const TYPE *data = (const TYPE *)(DATA);      \\\n        for (Py_ssize_t i = 0; i < len; i++) {        \\\n            if (!CHECK(data[i]))                      \\\n                return false;                         \\\n        }                                             \\\n    }\n\n    // ASCII fast path\n    if (PyUnicode_IS_ASCII(str)) {\n        CHECK_ISDIGIT(Py_UCS1, PyUnicode_1BYTE_DATA(str), Py_ISDIGIT);\n        return true;\n    }\n\n    switch (PyUnicode_KIND(str)) {\n    case PyUnicode_1BYTE_KIND:\n        CHECK_ISDIGIT(Py_UCS1, PyUnicode_1BYTE_DATA(str), Py_UNICODE_ISDIGIT);\n        break;\n    case PyUnicode_2BYTE_KIND:\n        CHECK_ISDIGIT(Py_UCS2, PyUnicode_2BYTE_DATA(str), Py_UNICODE_ISDIGIT);\n        break;\n    case PyUnicode_4BYTE_KIND:\n        CHECK_ISDIGIT(Py_UCS4, PyUnicode_4BYTE_DATA(str), Py_UNICODE_ISDIGIT);\n        break;\n    default:\n        Py_UNREACHABLE();\n    }\n    return true;\n\n#undef CHECK_ISDIGIT\n}\n"
  },
  {
    "path": "mypyc/lib-rt/strings/librt_strings.c",
    "content": "#include \"pythoncapi_compat.h\"\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <stdint.h>\n#include \"CPy.h\"\n#include \"librt_strings.h\"\n\n#define CPY_BOOL_ERROR 2\n\n//\n// BytesWriter\n//\n\n#define _WRITE_BYTES(data, type, v) \\\n    do { \\\n       *(type *)(((BytesWriterObject *)data)->buf + ((BytesWriterObject *)data)->len) = v; \\\n       ((BytesWriterObject *)data)->len += sizeof(type); \\\n    } while (0)\n\n#ifdef MYPYC_EXPERIMENTAL\n\nstatic PyTypeObject BytesWriterType;\n\nstatic bool\n_grow_buffer(BytesWriterObject *data, Py_ssize_t n) {\n    Py_ssize_t target = data->len + n;\n    Py_ssize_t size = data->capacity;\n    do {\n        size *= 2;\n    } while (target >= size);\n    if (data->buf == data->data) {\n        // Move from embedded buffer to heap-allocated buffer\n        data->buf = PyMem_Malloc(size);\n        if (data->buf != NULL) {\n            memcpy(data->buf, data->data, WRITER_EMBEDDED_BUF_LEN);\n        }\n    } else {\n        data->buf = PyMem_Realloc(data->buf, size);\n    }\n    if (unlikely(data->buf == NULL)) {\n        PyErr_NoMemory();\n        return false;\n    }\n    data->capacity = size;\n    return true;\n}\n\nstatic inline bool\nensure_bytes_writer_size(BytesWriterObject *data, Py_ssize_t n) {\n    if (likely(data->capacity - data->len >= n)) {\n        return true;\n    } else {\n        return _grow_buffer(data, n);\n    }\n}\n\nstatic inline void\nBytesWriter_init_internal(BytesWriterObject *self) {\n    self->buf = self->data;\n    self->len = 0;\n    self->capacity = WRITER_EMBEDDED_BUF_LEN;\n}\n\nstatic PyObject*\nBytesWriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\n    if (type != &BytesWriterType) {\n        PyErr_SetString(PyExc_TypeError, \"BytesWriter cannot be subclassed\");\n        return NULL;\n    }\n\n    BytesWriterObject *self = (BytesWriterObject *)type->tp_alloc(type, 0);\n    if (self != NULL) {\n        BytesWriter_init_internal(self);\n    }\n    return (PyObject *)self;\n}\n\nstatic PyObject *\nBytesWriter_internal(void) {\n    BytesWriterObject *self = (BytesWriterObject *)BytesWriterType.tp_alloc(&BytesWriterType, 0);\n    if (self == NULL)\n        return NULL;\n    BytesWriter_init_internal(self);\n    return (PyObject *)self;\n}\n\nstatic int\nBytesWriter_init(BytesWriterObject *self, PyObject *args, PyObject *kwds)\n{\n    if (!PyArg_ParseTuple(args, \"\")) {\n        return -1;\n    }\n\n    if (kwds != NULL && PyDict_Size(kwds) > 0) {\n        PyErr_SetString(PyExc_TypeError,\n                        \"BytesWriter() takes no keyword arguments\");\n        return -1;\n    }\n\n    BytesWriter_init_internal(self);\n    return 0;\n}\n\nstatic void\nBytesWriter_dealloc(BytesWriterObject *self)\n{\n    if (self->buf != self->data) {\n        PyMem_Free(self->buf);\n        self->buf = NULL;\n    }\n    Py_TYPE(self)->tp_free((PyObject *)self);\n}\n\nstatic PyObject*\nBytesWriter_getvalue_internal(PyObject *self)\n{\n    BytesWriterObject *obj = (BytesWriterObject *)self;\n    return PyBytes_FromStringAndSize(obj->buf, obj->len);\n}\n\nstatic PyObject*\nBytesWriter_repr(BytesWriterObject *self)\n{\n    PyObject *value = BytesWriter_getvalue_internal((PyObject *)self);\n    if (value == NULL) {\n        return NULL;\n    }\n    PyObject *value_repr = PyObject_Repr(value);\n    Py_DECREF(value);\n    if (value_repr == NULL) {\n        return NULL;\n    }\n    PyObject *result = PyUnicode_FromFormat(\"BytesWriter(%U)\", value_repr);\n    Py_DECREF(value_repr);\n    return result;\n}\n\nstatic PyObject*\nBytesWriter_getvalue(BytesWriterObject *self, PyObject *Py_UNUSED(ignored))\n{\n    return PyBytes_FromStringAndSize(self->buf, self->len);\n}\n\nstatic Py_ssize_t\nBytesWriter_length(BytesWriterObject *self)\n{\n    return self->len;\n}\n\nstatic PyObject*\nBytesWriter_item(BytesWriterObject *self, Py_ssize_t index)\n{\n    Py_ssize_t length = self->len;\n\n    // Check bounds\n    if (index < 0 || index >= length) {\n        PyErr_SetString(PyExc_IndexError, \"BytesWriter index out of range\");\n        return NULL;\n    }\n\n    // Return the byte at the given index as a Python int\n    return PyLong_FromLong((unsigned char)self->buf[index]);\n}\n\nstatic int\nBytesWriter_ass_item(BytesWriterObject *self, Py_ssize_t index, PyObject *value)\n{\n    Py_ssize_t length = self->len;\n\n    // Check bounds\n    if (index < 0 || index >= length) {\n        PyErr_SetString(PyExc_IndexError, \"BytesWriter index out of range\");\n        return -1;\n    }\n\n    // Check that value is not NULL (deletion not supported)\n    if (value == NULL) {\n        PyErr_SetString(PyExc_TypeError, \"BytesWriter does not support item deletion\");\n        return -1;\n    }\n\n    // Convert value to uint8\n    uint8_t byte_value = CPyLong_AsUInt8(value);\n    if (unlikely(byte_value == CPY_LL_UINT_ERROR && PyErr_Occurred())) {\n        CPy_TypeError(\"u8\", value);\n        return -1;\n    }\n\n    // Assign the byte\n    self->buf[index] = (char)byte_value;\n    return 0;\n}\n\nstatic PySequenceMethods BytesWriter_as_sequence = {\n    .sq_length = (lenfunc)BytesWriter_length,\n    .sq_item = (ssizeargfunc)BytesWriter_item,\n    .sq_ass_item = (ssizeobjargproc)BytesWriter_ass_item,\n};\n\nstatic PyObject* BytesWriter_append(PyObject *self, PyObject *const *args, size_t nargs);\nstatic PyObject* BytesWriter_write(PyObject *self, PyObject *const *args, size_t nargs);\nstatic PyObject* BytesWriter_truncate(PyObject *self, PyObject *const *args, size_t nargs);\n\nstatic PyMethodDef BytesWriter_methods[] = {\n    {\"append\", (PyCFunction) BytesWriter_append, METH_FASTCALL,\n     PyDoc_STR(\"Append a single byte to the buffer\")\n    },\n    {\"write\", (PyCFunction) BytesWriter_write, METH_FASTCALL,\n     PyDoc_STR(\"Append bytes to the buffer\")\n    },\n    {\"getvalue\", (PyCFunction) BytesWriter_getvalue, METH_NOARGS,\n     \"Return the buffer content as bytes object\"\n    },\n    {\"truncate\", (PyCFunction) BytesWriter_truncate, METH_FASTCALL,\n     PyDoc_STR(\"Truncate the buffer to the specified size\")\n    },\n    {NULL}  /* Sentinel */\n};\n\nstatic PyTypeObject BytesWriterType = {\n    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"BytesWriter\",\n    .tp_doc = PyDoc_STR(\"Memory buffer for building bytes objects from parts\"),\n    .tp_basicsize = sizeof(BytesWriterObject),\n    .tp_itemsize = 0,\n    .tp_flags = Py_TPFLAGS_DEFAULT,\n    .tp_new = BytesWriter_new,\n    .tp_init = (initproc) BytesWriter_init,\n    .tp_dealloc = (destructor) BytesWriter_dealloc,\n    .tp_methods = BytesWriter_methods,\n    .tp_as_sequence = &BytesWriter_as_sequence,\n    .tp_repr = (reprfunc)BytesWriter_repr,\n};\n\nstatic inline bool\ncheck_bytes_writer(PyObject *data) {\n    if (unlikely(Py_TYPE(data) != &BytesWriterType)) {\n        PyErr_Format(\n            PyExc_TypeError, \"data must be a BytesWriter object, got %s\", Py_TYPE(data)->tp_name\n        );\n        return false;\n    }\n    return true;\n}\n\nstatic char\nBytesWriter_write_internal(BytesWriterObject *self, PyObject *value) {\n    const char *data;\n    Py_ssize_t size;\n    if (likely(PyBytes_Check(value))) {\n        data = PyBytes_AS_STRING(value);\n        size = PyBytes_GET_SIZE(value);\n    } else {\n        data = PyByteArray_AS_STRING(value);\n        size = PyByteArray_GET_SIZE(value);\n    }\n    // Write bytes content.\n    if (!ensure_bytes_writer_size(self, size))\n        return CPY_NONE_ERROR;\n    memcpy(self->buf + self->len, data, size);\n    self->len += size;\n    return CPY_NONE;\n}\n\nstatic PyObject*\nBytesWriter_write(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"write() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    if (!check_bytes_writer(self)) {\n        return NULL;\n    }\n    PyObject *value = args[0];\n    if (unlikely(!PyBytes_Check(value) && !PyByteArray_Check(value))) {\n        PyErr_SetString(PyExc_TypeError, \"value must be a bytes or bytearray object\");\n        return NULL;\n    }\n    if (unlikely(BytesWriter_write_internal((BytesWriterObject *)self, value) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic inline char\nBytesWriter_append_internal(BytesWriterObject *self, uint8_t value) {\n    if (!ensure_bytes_writer_size(self, 1))\n        return CPY_NONE_ERROR;\n    _WRITE_BYTES(self, uint8_t, value);\n    return CPY_NONE;\n}\n\nstatic PyObject*\nBytesWriter_append(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"append() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    if (!check_bytes_writer(self)) {\n        return NULL;\n    }\n    PyObject *value = args[0];\n    uint8_t unboxed = CPyLong_AsUInt8(value);\n    if (unlikely(unboxed == CPY_LL_UINT_ERROR && PyErr_Occurred())) {\n        CPy_TypeError(\"u8\", value);\n        return NULL;\n    }\n    if (unlikely(BytesWriter_append_internal((BytesWriterObject *)self, unboxed) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic char\nBytesWriter_truncate_internal(PyObject *self, int64_t size) {\n    BytesWriterObject *writer = (BytesWriterObject *)self;\n    Py_ssize_t current_size = writer->len;\n\n    // Validate size is non-negative\n    if (size < 0) {\n        PyErr_SetString(PyExc_ValueError, \"size must be non-negative\");\n        return CPY_NONE_ERROR;\n    }\n\n    // Validate size doesn't exceed current size\n    if (size > current_size) {\n        PyErr_SetString(PyExc_ValueError, \"size cannot be larger than current buffer size\");\n        return CPY_NONE_ERROR;\n    }\n\n    writer->len = size;\n    return CPY_NONE;\n}\n\nstatic PyObject*\nBytesWriter_truncate(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"truncate() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    if (!check_bytes_writer(self)) {\n        return NULL;\n    }\n\n    PyObject *size_obj = args[0];\n    int overflow;\n    long long size = PyLong_AsLongLongAndOverflow(size_obj, &overflow);\n\n    if (size == -1 && PyErr_Occurred()) {\n        return NULL;\n    }\n    if (overflow != 0) {\n        PyErr_SetString(PyExc_ValueError, \"integer out of range\");\n        return NULL;\n    }\n\n    if (unlikely(BytesWriter_truncate_internal(self, size) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic PyTypeObject *\nBytesWriter_type_internal(void) {\n    return &BytesWriterType;  // Return borrowed reference\n};\n\nstatic CPyTagged\nBytesWriter_len_internal(PyObject *self) {\n    BytesWriterObject *writer = (BytesWriterObject *)self;\n    return writer->len << 1;\n}\n\n//\n// StringWriter\n//\n\nstatic PyTypeObject StringWriterType;\n\nstatic void convert_string_data_in_place(char *buf, Py_ssize_t len,\n                                         char old_kind, char new_kind);\n\n// Helper to grow string buffer and optionally convert to new kind\n// Returns true on success, false on failure (with PyErr set)\n// Updates self->buf, self->capacity, and self->kind\nstatic bool\ngrow_string_buffer_helper(StringWriterObject *self, Py_ssize_t target_capacity, char new_kind) {\n    char old_kind = self->kind;\n    Py_ssize_t new_capacity = self->capacity;\n\n    while (target_capacity >= new_capacity) {\n        new_capacity *= 2;\n    }\n\n    Py_ssize_t size_bytes = new_capacity * new_kind;\n    char *new_buf;\n    bool from_embedded = (self->buf == self->data);\n\n    if (from_embedded) {\n        // Move from embedded buffer to heap-allocated buffer\n        new_buf = PyMem_Malloc(size_bytes);\n        if (new_buf != NULL) {\n            // Copy existing data from embedded buffer\n            memcpy(new_buf, self->data, self->len * old_kind);\n        }\n    } else {\n        // Realloc existing heap buffer\n        new_buf = PyMem_Realloc(self->buf, size_bytes);\n    }\n\n    if (unlikely(new_buf == NULL)) {\n        PyErr_NoMemory();\n        return false;\n    }\n\n    // Convert data if kind changed\n    if (old_kind != new_kind) {\n        convert_string_data_in_place(new_buf, self->len, old_kind, new_kind);\n    }\n\n    self->buf = new_buf;\n    self->capacity = new_capacity;\n    self->kind = new_kind;\n    return true;\n}\n\nstatic bool grow_string_buffer(StringWriterObject *data, Py_ssize_t n) {\n    return grow_string_buffer_helper(data, data->len + n, data->kind);\n}\n\nstatic inline bool\nensure_string_writer_size(StringWriterObject *data, Py_ssize_t n) {\n    if (likely(data->capacity - data->len >= n)) {\n        return true;\n    } else {\n        // Don't inline the grow function since this is slow path and we\n        // want to keep this as short as possible for better inlining\n        return grow_string_buffer(data, n);\n    }\n}\n\nstatic inline void\nStringWriter_init_internal(StringWriterObject *self) {\n    self->buf = self->data;\n    self->kind = 1;\n    self->len = 0;\n    self->capacity = WRITER_EMBEDDED_BUF_LEN;\n}\n\nstatic PyObject*\nStringWriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\n{\n    if (type != &StringWriterType) {\n        PyErr_SetString(PyExc_TypeError, \"StringWriter cannot be subclassed\");\n        return NULL;\n    }\n\n    StringWriterObject *self = (StringWriterObject *)type->tp_alloc(type, 0);\n    if (self != NULL) {\n        StringWriter_init_internal(self);\n    }\n    return (PyObject *)self;\n}\n\nstatic PyObject *\nStringWriter_internal(void) {\n    StringWriterObject *self = (StringWriterObject *)StringWriterType.tp_alloc(&StringWriterType, 0);\n    if (self == NULL)\n        return NULL;\n    StringWriter_init_internal(self);\n    return (PyObject *)self;\n}\n\nstatic int\nStringWriter_init(StringWriterObject *self, PyObject *args, PyObject *kwds)\n{\n    if (!PyArg_ParseTuple(args, \"\")) {\n        return -1;\n    }\n\n    if (kwds != NULL && PyDict_Size(kwds) > 0) {\n        PyErr_SetString(PyExc_TypeError,\n                        \"StringWriter() takes no keyword arguments\");\n        return -1;\n    }\n\n    StringWriter_init_internal(self);\n    return 0;\n}\n\nstatic void\nStringWriter_dealloc(StringWriterObject *self)\n{\n    if (self->buf != self->data) {\n        PyMem_Free(self->buf);\n        self->buf = NULL;\n    }\n    Py_TYPE(self)->tp_free((PyObject *)self);\n}\n\nstatic PyObject*\nStringWriter_getvalue_internal(PyObject *self)\n{\n    StringWriterObject *obj = (StringWriterObject *)self;\n    return PyUnicode_FromKindAndData(obj->kind, obj->buf, obj->len);\n}\n\nstatic PyObject*\nStringWriter_repr(StringWriterObject *self)\n{\n    PyObject *value = StringWriter_getvalue_internal((PyObject *)self);\n    if (value == NULL) {\n        return NULL;\n    }\n    PyObject *value_repr = PyObject_Repr(value);\n    Py_DECREF(value);\n    if (value_repr == NULL) {\n        return NULL;\n    }\n    PyObject *result = PyUnicode_FromFormat(\"StringWriter(%U)\", value_repr);\n    Py_DECREF(value_repr);\n    return result;\n}\n\nstatic PyObject*\nStringWriter_getvalue(StringWriterObject *self, PyObject *Py_UNUSED(ignored))\n{\n    return PyUnicode_FromKindAndData(self->kind, self->buf, self->len);\n}\n\nstatic Py_ssize_t\nStringWriter_length(StringWriterObject *self)\n{\n    return self->len;\n}\n\nstatic PyObject*\nStringWriter_item(StringWriterObject *self, Py_ssize_t index)\n{\n    Py_ssize_t length = self->len;\n\n    // Check bounds\n    if (index < 0 || index >= length) {\n        PyErr_SetString(PyExc_IndexError, \"StringWriter index out of range\");\n        return NULL;\n    }\n\n    // Read the character at the given index based on kind using memcpy\n    uint32_t value;\n    if (self->kind == 1) {\n        uint8_t val;\n        memcpy(&val, self->buf + index, 1);\n        value = val;\n    } else if (self->kind == 2) {\n        uint16_t val;\n        memcpy(&val, self->buf + index * 2, 2);\n        value = val;\n    } else {\n        memcpy(&value, self->buf + index * 4, 4);\n    }\n    return PyLong_FromLong(value);\n}\n\nstatic PySequenceMethods StringWriter_as_sequence = {\n    .sq_length = (lenfunc)StringWriter_length,\n    .sq_item = (ssizeargfunc)StringWriter_item,\n};\n\nstatic PyObject* StringWriter_append(PyObject *self, PyObject *const *args, size_t nargs);\nstatic PyObject* StringWriter_write(PyObject *self, PyObject *const *args, size_t nargs);\n\nstatic PyMethodDef StringWriter_methods[] = {\n    {\"append\", (PyCFunction) StringWriter_append, METH_FASTCALL,\n     PyDoc_STR(\"Append a single character (as int codepoint) to the buffer\")\n    },\n    {\"write\", (PyCFunction) StringWriter_write, METH_FASTCALL,\n     PyDoc_STR(\"Append a string to the buffer\")\n    },\n    {\"getvalue\", (PyCFunction) StringWriter_getvalue, METH_NOARGS,\n     \"Return the buffer content as str object\"\n    },\n    {NULL}  /* Sentinel */\n};\n\nstatic PyTypeObject StringWriterType = {\n    .ob_base = PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"StringWriter\",\n    .tp_doc = PyDoc_STR(\"Memory buffer for building string objects from parts\"),\n    .tp_basicsize = sizeof(StringWriterObject),\n    .tp_itemsize = 0,\n    .tp_flags = Py_TPFLAGS_DEFAULT,\n    .tp_new = StringWriter_new,\n    .tp_init = (initproc) StringWriter_init,\n    .tp_dealloc = (destructor) StringWriter_dealloc,\n    .tp_methods = StringWriter_methods,\n    .tp_as_sequence = &StringWriter_as_sequence,\n    .tp_repr = (reprfunc)StringWriter_repr,\n};\n\nstatic inline bool\ncheck_string_writer(PyObject *data) {\n    if (unlikely(Py_TYPE(data) != &StringWriterType)) {\n        PyErr_Format(\n            PyExc_TypeError, \"data must be a StringWriter object, got %s\", Py_TYPE(data)->tp_name\n        );\n        return false;\n    }\n    return true;\n}\n\nstatic char string_writer_switch_kind(StringWriterObject *self, int32_t value);\n\nstatic char\nStringWriter_write_internal(PyObject *obj, PyObject *value) {\n    StringWriterObject *self = (StringWriterObject *)obj;\n    Py_ssize_t str_len = PyUnicode_GET_LENGTH(value);\n    if (str_len == 0) {\n        return CPY_NONE;\n    }\n\n    int src_kind = PyUnicode_KIND(value);\n    void *src_data = PyUnicode_DATA(value);\n    int self_kind = self->kind;\n\n    // Switch kind if source requires wider characters\n    if (src_kind > self_kind) {\n        // Use value in the source kind range to trigger proper kind switch\n        int32_t codepoint = (src_kind == 2) ? 0x100 : 0x10000;\n        if (string_writer_switch_kind(self, codepoint) == CPY_NONE_ERROR) {\n            return CPY_NONE_ERROR;\n        }\n        self_kind = self->kind;\n    }\n\n    // Ensure we have enough space\n    if (!ensure_string_writer_size(self, str_len)) {\n        return CPY_NONE_ERROR;\n    }\n\n    // Copy data - ASCII/Latin1 (kind 1) are handled uniformly\n    if (self_kind == src_kind) {\n        // Same kind, direct copy\n        memcpy(self->buf + self->len * self_kind, src_data, str_len * src_kind);\n    } else {\n        // Different kinds, convert character by character\n        for (Py_ssize_t i = 0; i < str_len; i++) {\n            Py_UCS4 ch = PyUnicode_READ(src_kind, src_data, i);\n            PyUnicode_WRITE(self_kind, self->buf, self->len + i, ch);\n        }\n    }\n\n    self->len += str_len;\n    return CPY_NONE;\n}\n\nstatic PyObject*\nStringWriter_write(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"write() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    if (!check_string_writer(self)) {\n        return NULL;\n    }\n    PyObject *value = args[0];\n    if (unlikely(!PyUnicode_Check(value))) {\n        PyErr_SetString(PyExc_TypeError, \"value must be a str object\");\n        return NULL;\n    }\n    if (unlikely(StringWriter_write_internal(self, value) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\n// Convert string data to next larger kind (1->2 or 2->4)\nstatic void convert_string_data_in_place(char *buf, Py_ssize_t len,\n                                         char old_kind, char new_kind) {\n    if (old_kind == 1 && new_kind == 2) {\n        // Convert backwards to avoid overwriting\n        for (Py_ssize_t i = len - 1; i >= 0; i--) {\n            uint8_t val = (uint8_t)buf[i];\n            uint16_t expanded = val;\n            memcpy(buf + i * 2, &expanded, 2);\n        }\n    } else if (old_kind == 2 && new_kind == 4) {\n        // Convert backwards to avoid overwriting\n        for (Py_ssize_t i = len - 1; i >= 0; i--) {\n            uint16_t val;\n            memcpy(&val, buf + i * 2, 2);\n            uint32_t expanded = val;\n            memcpy(buf + i * 4, &expanded, 4);\n        }\n    } else {\n        assert(false);\n    }\n}\n\nstatic char convert_string_buffer_kind(StringWriterObject *self, char old_kind, char new_kind) {\n    // Current buffer size in bytes\n    Py_ssize_t current_buf_size = (self->buf == self->data) ? WRITER_EMBEDDED_BUF_LEN : (self->capacity * old_kind);\n    // Needed buffer size in bytes for new kind\n    Py_ssize_t needed_size = self->len * new_kind;\n\n    if (current_buf_size >= needed_size) {\n        // Convert in place\n        convert_string_data_in_place(self->buf, self->len, old_kind, new_kind);\n        self->kind = new_kind;\n        self->capacity = current_buf_size / new_kind;\n    } else {\n        // Need to allocate new buffer\n        if (!grow_string_buffer_helper(self, self->len, new_kind)) {\n            return CPY_NONE_ERROR;\n        }\n    }\n    return CPY_NONE;\n}\n\nstatic char string_writer_switch_kind(StringWriterObject *self, int32_t value) {\n    if (self->kind == 1) {\n        // Either kind 1 -> 2 or 1 -> 4. First switch to kind 2.\n        if (convert_string_buffer_kind(self, 1, 2) == CPY_NONE_ERROR)\n            return CPY_NONE_ERROR;\n        if ((uint32_t)value > 0xffff) {\n            // Call recursively to switch from kind 2 to 4\n            return string_writer_switch_kind(self, value);\n        }\n        return CPY_NONE;\n    } else {\n        // Must be kind 2 -> 4\n        assert(self->kind == 2);\n        assert((uint32_t)value > 0xffff);\n        return convert_string_buffer_kind(self, 2, 4);\n    }\n}\n\n// Handle all append cases except for append that stays within kind 1\nstatic char string_append_slow_path(StringWriterObject *self, int32_t value) {\n    if (self->kind == 2) {\n        if ((uint32_t)value <= 0xffff) {\n            // Kind stays the same\n            if (!ensure_string_writer_size(self, 1))\n                return CPY_NONE_ERROR;\n            // Copy 2-byte character to buffer\n            uint16_t val16 = (uint16_t)value;\n            memcpy(self->buf + self->len * 2, &val16, 2);\n            self->len++;\n            return CPY_NONE;\n        }\n        if (string_writer_switch_kind(self, value) == CPY_NONE_ERROR)\n            return CPY_NONE_ERROR;\n        return string_append_slow_path(self, value);\n    } else if (self->kind == 1) {\n        // Check precondition -- this must only be used on slow path\n        assert((uint32_t)value > 0xff);\n        if (string_writer_switch_kind(self, value) == CPY_NONE_ERROR)\n            return CPY_NONE_ERROR;\n        return string_append_slow_path(self, value);\n    }\n    assert(self->kind == 4);\n    if ((uint32_t)value <= 0x10FFFF) {\n        if (!ensure_string_writer_size(self, 1))\n            return CPY_NONE_ERROR;\n        // Copy 4-byte character to buffer\n        uint32_t val32 = (uint32_t)value;\n        memcpy(self->buf + self->len * 4, &val32, 4);\n        self->len++;\n        return CPY_NONE;\n    }\n    // Code point is out of valid Unicode range\n    PyErr_Format(PyExc_ValueError, \"code point %d is outside valid Unicode range (0-1114111)\", value);\n    return CPY_NONE_ERROR;\n}\n\nstatic inline char\nStringWriter_append_internal(StringWriterObject *self, int32_t value) {\n    char kind = self->kind;\n    if (kind == 1 && (uint32_t)value < 256) {\n        if (!ensure_string_writer_size(self, 1))\n            return CPY_NONE_ERROR;\n        self->buf[self->len++] = value;\n        self->kind = kind;\n        return CPY_NONE;\n    }\n    return string_append_slow_path(self, value);\n}\n\nstatic PyObject*\nStringWriter_append(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (unlikely(nargs != 1)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"append() takes exactly 1 argument (%zu given)\", nargs);\n        return NULL;\n    }\n    if (!check_string_writer(self)) {\n        return NULL;\n    }\n    PyObject *value = args[0];\n    int32_t unboxed = CPyLong_AsInt32(value);\n    if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred())) {\n        CPy_TypeError(\"i32\", value);\n        return NULL;\n    }\n    if (unlikely(StringWriter_append_internal((StringWriterObject *)self, unboxed) == CPY_NONE_ERROR)) {\n        return NULL;\n    }\n    Py_INCREF(Py_None);\n    return Py_None;\n}\n\nstatic PyTypeObject *\nStringWriter_type_internal(void) {\n    return &StringWriterType;  // Return borrowed reference\n};\n\nstatic CPyTagged\nStringWriter_len_internal(PyObject *self) {\n    StringWriterObject *writer = (StringWriterObject *)self;\n    return writer->len << 1;\n}\n\n// End of StringWriter\n\n// Helper for write_*_le/be functions - validates args and returns BytesWriter\nstatic inline BytesWriterObject *\nparse_write_args(PyObject *const *args, size_t nargs, const char *func_name) {\n    if (unlikely(nargs != 2)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"%s() takes exactly 2 arguments (%zu given)\", func_name, nargs);\n        return NULL;\n    }\n    PyObject *writer = args[0];\n    if (!check_bytes_writer(writer)) {\n        return NULL;\n    }\n    return (BytesWriterObject *)writer;\n}\n\n// Helper for read_*_le/be functions - validates args and returns data pointer\n// Returns NULL on error, sets *out_index to the validated index on success\nstatic inline const unsigned char *\nparse_read_args(PyObject *const *args, size_t nargs, const char *func_name,\n                    Py_ssize_t num_bytes, int64_t *out_index) {\n    if (unlikely(nargs != 2)) {\n        PyErr_Format(PyExc_TypeError,\n                     \"%s() takes exactly 2 arguments (%zu given)\", func_name, nargs);\n        return NULL;\n    }\n    PyObject *bytes_obj = args[0];\n    if (unlikely(!PyBytes_Check(bytes_obj))) {\n        PyErr_Format(PyExc_TypeError, \"%s() argument 1 must be bytes\", func_name);\n        return NULL;\n    }\n    int64_t index = CPyLong_AsInt64(args[1]);\n    if (unlikely(index == CPY_LL_INT_ERROR && PyErr_Occurred())) {\n        return NULL;\n    }\n    if (unlikely(index < 0)) {\n        PyErr_SetString(PyExc_ValueError, \"index must be non-negative\");\n        return NULL;\n    }\n    Py_ssize_t size = PyBytes_GET_SIZE(bytes_obj);\n    if (unlikely(index > size - num_bytes)) {\n        PyErr_Format(PyExc_IndexError,\n                     \"index %lld out of range for bytes of length %zd\",\n                     (long long)index, size);\n        return NULL;\n    }\n    *out_index = index;\n    return (const unsigned char *)PyBytes_AS_STRING(bytes_obj);\n}\n\nstatic PyObject*\nwrite_i16_le(PyObject *module, PyObject *const *args, size_t nargs) {\n    BytesWriterObject *bw = parse_write_args(args, nargs, \"write_i16_le\");\n    if (bw == NULL)\n        return NULL;\n    int16_t unboxed = CPyLong_AsInt16(args[1]);\n    if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred()))\n        return NULL;\n    if (unlikely(!ensure_bytes_writer_size(bw, 2)))\n        return NULL;\n    BytesWriter_WriteI16LEUnsafe(bw, unboxed);\n    Py_RETURN_NONE;\n}\n\nstatic PyObject*\nwrite_i16_be(PyObject *module, PyObject *const *args, size_t nargs) {\n    BytesWriterObject *bw = parse_write_args(args, nargs, \"write_i16_be\");\n    if (bw == NULL)\n        return NULL;\n    int16_t unboxed = CPyLong_AsInt16(args[1]);\n    if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred()))\n        return NULL;\n    if (unlikely(!ensure_bytes_writer_size(bw, 2)))\n        return NULL;\n    BytesWriter_WriteI16BEUnsafe(bw, unboxed);\n    Py_RETURN_NONE;\n}\n\nstatic PyObject*\nread_i16_le(PyObject *module, PyObject *const *args, size_t nargs) {\n    int64_t index;\n    const unsigned char *data = parse_read_args(args, nargs, \"read_i16_le\", 2, &index);\n    if (data == NULL)\n        return NULL;\n    return PyLong_FromLong(CPyBytes_ReadI16LEUnsafe(data + index));\n}\n\nstatic PyObject*\nread_i16_be(PyObject *module, PyObject *const *args, size_t nargs) {\n    int64_t index;\n    const unsigned char *data = parse_read_args(args, nargs, \"read_i16_be\", 2, &index);\n    if (data == NULL)\n        return NULL;\n    return PyLong_FromLong(CPyBytes_ReadI16BEUnsafe(data + index));\n}\n\nstatic PyObject*\nwrite_i32_le(PyObject *module, PyObject *const *args, size_t nargs) {\n    BytesWriterObject *bw = parse_write_args(args, nargs, \"write_i32_le\");\n    if (bw == NULL)\n        return NULL;\n    int32_t unboxed = CPyLong_AsInt32(args[1]);\n    if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred()))\n        return NULL;\n    if (unlikely(!ensure_bytes_writer_size(bw, 4)))\n        return NULL;\n    BytesWriter_WriteI32LEUnsafe(bw, unboxed);\n    Py_RETURN_NONE;\n}\n\nstatic PyObject*\nwrite_i32_be(PyObject *module, PyObject *const *args, size_t nargs) {\n    BytesWriterObject *bw = parse_write_args(args, nargs, \"write_i32_be\");\n    if (bw == NULL)\n        return NULL;\n    int32_t unboxed = CPyLong_AsInt32(args[1]);\n    if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred()))\n        return NULL;\n    if (unlikely(!ensure_bytes_writer_size(bw, 4)))\n        return NULL;\n    BytesWriter_WriteI32BEUnsafe(bw, unboxed);\n    Py_RETURN_NONE;\n}\n\nstatic PyObject*\nread_i32_le(PyObject *module, PyObject *const *args, size_t nargs) {\n    int64_t index;\n    const unsigned char *data = parse_read_args(args, nargs, \"read_i32_le\", 4, &index);\n    if (data == NULL)\n        return NULL;\n    return PyLong_FromLong(CPyBytes_ReadI32LEUnsafe(data + index));\n}\n\nstatic PyObject*\nread_i32_be(PyObject *module, PyObject *const *args, size_t nargs) {\n    int64_t index;\n    const unsigned char *data = parse_read_args(args, nargs, \"read_i32_be\", 4, &index);\n    if (data == NULL)\n        return NULL;\n    return PyLong_FromLong(CPyBytes_ReadI32BEUnsafe(data + index));\n}\n\nstatic PyObject*\nwrite_i64_le(PyObject *module, PyObject *const *args, size_t nargs) {\n    BytesWriterObject *bw = parse_write_args(args, nargs, \"write_i64_le\");\n    if (bw == NULL)\n        return NULL;\n    int64_t unboxed = CPyLong_AsInt64(args[1]);\n    if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred()))\n        return NULL;\n    if (unlikely(!ensure_bytes_writer_size(bw, 8)))\n        return NULL;\n    BytesWriter_WriteI64LEUnsafe(bw, unboxed);\n    Py_RETURN_NONE;\n}\n\nstatic PyObject*\nwrite_i64_be(PyObject *module, PyObject *const *args, size_t nargs) {\n    BytesWriterObject *bw = parse_write_args(args, nargs, \"write_i64_be\");\n    if (bw == NULL)\n        return NULL;\n    int64_t unboxed = CPyLong_AsInt64(args[1]);\n    if (unlikely(unboxed == CPY_LL_INT_ERROR && PyErr_Occurred()))\n        return NULL;\n    if (unlikely(!ensure_bytes_writer_size(bw, 8)))\n        return NULL;\n    BytesWriter_WriteI64BEUnsafe(bw, unboxed);\n    Py_RETURN_NONE;\n}\n\nstatic PyObject*\nread_i64_le(PyObject *module, PyObject *const *args, size_t nargs) {\n    int64_t index;\n    const unsigned char *data = parse_read_args(args, nargs, \"read_i64_le\", 8, &index);\n    if (data == NULL)\n        return NULL;\n    return PyLong_FromLongLong(CPyBytes_ReadI64LEUnsafe(data + index));\n}\n\nstatic PyObject*\nread_i64_be(PyObject *module, PyObject *const *args, size_t nargs) {\n    int64_t index;\n    const unsigned char *data = parse_read_args(args, nargs, \"read_i64_be\", 8, &index);\n    if (data == NULL)\n        return NULL;\n    return PyLong_FromLongLong(CPyBytes_ReadI64BEUnsafe(data + index));\n}\n\nstatic PyObject*\nwrite_f32_le(PyObject *module, PyObject *const *args, size_t nargs) {\n    BytesWriterObject *bw = parse_write_args(args, nargs, \"write_f32_le\");\n    if (bw == NULL)\n        return NULL;\n    double unboxed = PyFloat_AsDouble(args[1]);\n    if (unlikely(unboxed == -1.0 && PyErr_Occurred()))\n        return NULL;\n    if (unlikely(!ensure_bytes_writer_size(bw, 4)))\n        return NULL;\n    BytesWriter_WriteF32LEUnsafe(bw, (float)unboxed);\n    Py_RETURN_NONE;\n}\n\nstatic PyObject*\nwrite_f32_be(PyObject *module, PyObject *const *args, size_t nargs) {\n    BytesWriterObject *bw = parse_write_args(args, nargs, \"write_f32_be\");\n    if (bw == NULL)\n        return NULL;\n    double unboxed = PyFloat_AsDouble(args[1]);\n    if (unlikely(unboxed == -1.0 && PyErr_Occurred()))\n        return NULL;\n    if (unlikely(!ensure_bytes_writer_size(bw, 4)))\n        return NULL;\n    BytesWriter_WriteF32BEUnsafe(bw, (float)unboxed);\n    Py_RETURN_NONE;\n}\n\nstatic PyObject*\nread_f32_le(PyObject *module, PyObject *const *args, size_t nargs) {\n    int64_t index;\n    const unsigned char *data = parse_read_args(args, nargs, \"read_f32_le\", 4, &index);\n    if (data == NULL)\n        return NULL;\n    return PyFloat_FromDouble((double)CPyBytes_ReadF32LEUnsafe(data + index));\n}\n\nstatic PyObject*\nread_f32_be(PyObject *module, PyObject *const *args, size_t nargs) {\n    int64_t index;\n    const unsigned char *data = parse_read_args(args, nargs, \"read_f32_be\", 4, &index);\n    if (data == NULL)\n        return NULL;\n    return PyFloat_FromDouble((double)CPyBytes_ReadF32BEUnsafe(data + index));\n}\n\nstatic PyObject*\nwrite_f64_le(PyObject *module, PyObject *const *args, size_t nargs) {\n    BytesWriterObject *bw = parse_write_args(args, nargs, \"write_f64_le\");\n    if (bw == NULL)\n        return NULL;\n    double unboxed = PyFloat_AsDouble(args[1]);\n    if (unlikely(unboxed == -1.0 && PyErr_Occurred()))\n        return NULL;\n    if (unlikely(!ensure_bytes_writer_size(bw, 8)))\n        return NULL;\n    BytesWriter_WriteF64LEUnsafe(bw, unboxed);\n    Py_RETURN_NONE;\n}\n\nstatic PyObject*\nwrite_f64_be(PyObject *module, PyObject *const *args, size_t nargs) {\n    BytesWriterObject *bw = parse_write_args(args, nargs, \"write_f64_be\");\n    if (bw == NULL)\n        return NULL;\n    double unboxed = PyFloat_AsDouble(args[1]);\n    if (unlikely(unboxed == -1.0 && PyErr_Occurred()))\n        return NULL;\n    if (unlikely(!ensure_bytes_writer_size(bw, 8)))\n        return NULL;\n    BytesWriter_WriteF64BEUnsafe(bw, unboxed);\n    Py_RETURN_NONE;\n}\n\nstatic PyObject*\nread_f64_le(PyObject *module, PyObject *const *args, size_t nargs) {\n    int64_t index;\n    const unsigned char *data = parse_read_args(args, nargs, \"read_f64_le\", 8, &index);\n    if (data == NULL)\n        return NULL;\n    return PyFloat_FromDouble(CPyBytes_ReadF64LEUnsafe(data + index));\n}\n\nstatic PyObject*\nread_f64_be(PyObject *module, PyObject *const *args, size_t nargs) {\n    int64_t index;\n    const unsigned char *data = parse_read_args(args, nargs, \"read_f64_be\", 8, &index);\n    if (data == NULL)\n        return NULL;\n    return PyFloat_FromDouble(CPyBytes_ReadF64BEUnsafe(data + index));\n}\n\n#endif\n\nstatic PyMethodDef librt_strings_module_methods[] = {\n#ifdef MYPYC_EXPERIMENTAL\n    {\"write_i16_le\", (PyCFunction) write_i16_le, METH_FASTCALL,\n     PyDoc_STR(\"Write a 16-bit signed integer to BytesWriter in little-endian format\")\n    },\n    {\"write_i16_be\", (PyCFunction) write_i16_be, METH_FASTCALL,\n     PyDoc_STR(\"Write a 16-bit signed integer to BytesWriter in big-endian format\")\n    },\n    {\"read_i16_le\", (PyCFunction) read_i16_le, METH_FASTCALL,\n     PyDoc_STR(\"Read a 16-bit signed integer from bytes in little-endian format\")\n    },\n    {\"read_i16_be\", (PyCFunction) read_i16_be, METH_FASTCALL,\n     PyDoc_STR(\"Read a 16-bit signed integer from bytes in big-endian format\")\n    },\n    {\"write_i32_le\", (PyCFunction) write_i32_le, METH_FASTCALL,\n     PyDoc_STR(\"Write a 32-bit signed integer to BytesWriter in little-endian format\")\n    },\n    {\"write_i32_be\", (PyCFunction) write_i32_be, METH_FASTCALL,\n     PyDoc_STR(\"Write a 32-bit signed integer to BytesWriter in big-endian format\")\n    },\n    {\"read_i32_le\", (PyCFunction) read_i32_le, METH_FASTCALL,\n     PyDoc_STR(\"Read a 32-bit signed integer from bytes in little-endian format\")\n    },\n    {\"read_i32_be\", (PyCFunction) read_i32_be, METH_FASTCALL,\n     PyDoc_STR(\"Read a 32-bit signed integer from bytes in big-endian format\")\n    },\n    {\"write_i64_le\", (PyCFunction) write_i64_le, METH_FASTCALL,\n     PyDoc_STR(\"Write a 64-bit signed integer to BytesWriter in little-endian format\")\n    },\n    {\"write_i64_be\", (PyCFunction) write_i64_be, METH_FASTCALL,\n     PyDoc_STR(\"Write a 64-bit signed integer to BytesWriter in big-endian format\")\n    },\n    {\"read_i64_le\", (PyCFunction) read_i64_le, METH_FASTCALL,\n     PyDoc_STR(\"Read a 64-bit signed integer from bytes in little-endian format\")\n    },\n    {\"read_i64_be\", (PyCFunction) read_i64_be, METH_FASTCALL,\n     PyDoc_STR(\"Read a 64-bit signed integer from bytes in big-endian format\")\n    },\n    {\"write_f32_le\", (PyCFunction) write_f32_le, METH_FASTCALL,\n     PyDoc_STR(\"Write a 32-bit float to BytesWriter in little-endian format\")\n    },\n    {\"write_f32_be\", (PyCFunction) write_f32_be, METH_FASTCALL,\n     PyDoc_STR(\"Write a 32-bit float to BytesWriter in big-endian format\")\n    },\n    {\"read_f32_le\", (PyCFunction) read_f32_le, METH_FASTCALL,\n     PyDoc_STR(\"Read a 32-bit float from bytes in little-endian format\")\n    },\n    {\"read_f32_be\", (PyCFunction) read_f32_be, METH_FASTCALL,\n     PyDoc_STR(\"Read a 32-bit float from bytes in big-endian format\")\n    },\n    {\"write_f64_le\", (PyCFunction) write_f64_le, METH_FASTCALL,\n     PyDoc_STR(\"Write a 64-bit float to BytesWriter in little-endian format\")\n    },\n    {\"write_f64_be\", (PyCFunction) write_f64_be, METH_FASTCALL,\n     PyDoc_STR(\"Write a 64-bit float to BytesWriter in big-endian format\")\n    },\n    {\"read_f64_le\", (PyCFunction) read_f64_le, METH_FASTCALL,\n     PyDoc_STR(\"Read a 64-bit float from bytes in little-endian format\")\n    },\n    {\"read_f64_be\", (PyCFunction) read_f64_be, METH_FASTCALL,\n     PyDoc_STR(\"Read a 64-bit float from bytes in big-endian format\")\n    },\n#endif\n    {NULL, NULL, 0, NULL}\n};\n\n#ifdef MYPYC_EXPERIMENTAL\n\nstatic int\nstrings_abi_version(void) {\n    return LIBRT_STRINGS_ABI_VERSION;\n}\n\nstatic int\nstrings_api_version(void) {\n    return LIBRT_STRINGS_API_VERSION;\n}\n\n#endif\n\nstatic int\nlibrt_strings_module_exec(PyObject *m)\n{\n#ifdef MYPYC_EXPERIMENTAL\n    if (PyType_Ready(&BytesWriterType) < 0) {\n        return -1;\n    }\n    if (PyType_Ready(&StringWriterType) < 0) {\n        return -1;\n    }\n    if (PyModule_AddObjectRef(m, \"BytesWriter\", (PyObject *) &BytesWriterType) < 0) {\n        return -1;\n    }\n    if (PyModule_AddObjectRef(m, \"StringWriter\", (PyObject *) &StringWriterType) < 0) {\n        return -1;\n    }\n\n    // Export mypy internal C API, be careful with the order!\n    static void *librt_strings_api[LIBRT_STRINGS_API_LEN] = {\n        (void *)strings_abi_version,\n        (void *)strings_api_version,\n        (void *)BytesWriter_internal,\n        (void *)BytesWriter_getvalue_internal,\n        (void *)BytesWriter_append_internal,\n        (void *)_grow_buffer,\n        (void *)BytesWriter_type_internal,\n        (void *)BytesWriter_truncate_internal,\n        (void *)StringWriter_internal,\n        (void *)StringWriter_getvalue_internal,\n        (void *)string_append_slow_path,\n        (void *)StringWriter_type_internal,\n        (void *)StringWriter_write_internal,\n        (void *)grow_string_buffer,\n    };\n    PyObject *c_api_object = PyCapsule_New((void *)librt_strings_api, \"librt.strings._C_API\", NULL);\n    if (PyModule_Add(m, \"_C_API\", c_api_object) < 0) {\n        return -1;\n    }\n#endif\n    return 0;\n}\n\nstatic PyModuleDef_Slot librt_strings_module_slots[] = {\n    {Py_mod_exec, librt_strings_module_exec},\n#ifdef Py_MOD_GIL_NOT_USED\n    {Py_mod_gil, Py_MOD_GIL_NOT_USED},\n#endif\n    {0, NULL}\n};\n\nstatic PyModuleDef librt_strings_module = {\n    .m_base = PyModuleDef_HEAD_INIT,\n    .m_name = \"strings\",\n    .m_doc = \"Utilities for working with str and bytes objects\",\n    .m_size = 0,\n    .m_methods = librt_strings_module_methods,\n    .m_slots = librt_strings_module_slots,\n};\n\nPyMODINIT_FUNC\nPyInit_strings(void)\n{\n    intern_strings();\n    return PyModuleDef_Init(&librt_strings_module);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/strings/librt_strings.h",
    "content": "#ifndef LIBRT_STRINGS_H\n#define LIBRT_STRINGS_H\n\n#ifndef MYPYC_EXPERIMENTAL\n\nstatic int\nimport_librt_strings(void)\n{\n    // All librt.base64 features are experimental for now, so don't set up the API here\n    return 0;\n}\n\n#else  // MYPYC_EXPERIMENTAL\n\n#include <stdbool.h>\n#include <Python.h>\n#include \"librt_strings_common.h\"\n\n// ABI version -- only an exact match is compatible. This will only be changed in\n// very exceptional cases (likely never) due to strict backward compatibility\n// requirements.\n#define LIBRT_STRINGS_ABI_VERSION 1\n\n// API version -- more recent versions must maintain backward compatibility, i.e.\n// we can add new features but not remove or change existing features (unless\n// ABI version is changed, but see the comment above).\n #define LIBRT_STRINGS_API_VERSION 4\n\n// Number of functions in the capsule API. If you add a new function, also increase\n// LIBRT_STRINGS_API_VERSION.\n#define LIBRT_STRINGS_API_LEN 14\n\nstatic void *LibRTStrings_API[LIBRT_STRINGS_API_LEN];\n\ntypedef struct {\n    PyObject_HEAD\n    char *buf;  // Beginning of the buffer\n    char kind;  // Bytes per code point (1, 2 or 4)\n    Py_ssize_t len;  // Current length (number of code points written)\n    Py_ssize_t capacity;  // Total capacity of the buffer (number of code points)\n    char data[WRITER_EMBEDDED_BUF_LEN];  // Default buffer\n} StringWriterObject;\n\n#define LibRTStrings_ABIVersion (*(int (*)(void)) LibRTStrings_API[0])\n#define LibRTStrings_APIVersion (*(int (*)(void)) LibRTStrings_API[1])\n#define LibRTStrings_BytesWriter_internal (*(PyObject* (*)(void)) LibRTStrings_API[2])\n#define LibRTStrings_BytesWriter_getvalue_internal (*(PyObject* (*)(PyObject *source)) LibRTStrings_API[3])\n#define LibRTStrings_BytesWriter_append_internal (*(char (*)(PyObject *source, uint8_t value)) LibRTStrings_API[4])\n#define LibRTStrings_ByteWriter_grow_buffer_internal (*(bool (*)(BytesWriterObject *obj, Py_ssize_t size)) LibRTStrings_API[5])\n#define LibRTStrings_BytesWriter_type_internal (*(PyTypeObject* (*)(void)) LibRTStrings_API[6])\n#define LibRTStrings_BytesWriter_truncate_internal (*(char (*)(PyObject *self, int64_t size)) LibRTStrings_API[7])\n#define LibRTStrings_StringWriter_internal (*(PyObject* (*)(void)) LibRTStrings_API[8])\n#define LibRTStrings_StringWriter_getvalue_internal (*(PyObject* (*)(PyObject *source)) LibRTStrings_API[9])\n#define LibRTStrings_string_append_slow_path (*(char (*)(StringWriterObject *obj, int32_t value)) LibRTStrings_API[10])\n#define LibRTStrings_StringWriter_type_internal (*(PyTypeObject* (*)(void)) LibRTStrings_API[11])\n#define LibRTStrings_StringWriter_write_internal (*(char (*)(PyObject *source, PyObject *value)) LibRTStrings_API[12])\n#define LibRTStrings_grow_string_buffer (*(bool (*)(StringWriterObject *obj, Py_ssize_t n)) LibRTStrings_API[13])\n\nstatic int\nimport_librt_strings(void)\n{\n    PyObject *mod = PyImport_ImportModule(\"librt.strings\");\n    if (mod == NULL)\n        return -1;\n    Py_DECREF(mod);  // we import just for the side effect of making the below work.\n    void *capsule = PyCapsule_Import(\"librt.strings._C_API\", 0);\n    if (capsule == NULL)\n        return -1;\n    memcpy(LibRTStrings_API, capsule, sizeof(LibRTStrings_API));\n    if (LibRTStrings_ABIVersion() != LIBRT_STRINGS_ABI_VERSION) {\n        char err[128];\n        snprintf(err, sizeof(err), \"ABI version conflict for librt.strings, expected %d, found %d\",\n            LIBRT_STRINGS_ABI_VERSION,\n            LibRTStrings_ABIVersion()\n        );\n        PyErr_SetString(PyExc_ValueError, err);\n        return -1;\n    }\n    if (LibRTStrings_APIVersion() < LIBRT_STRINGS_API_VERSION) {\n        char err[128];\n        snprintf(err, sizeof(err),\n                 \"API version conflict for librt.strings, expected %d or newer, found %d (hint: upgrade librt)\",\n            LIBRT_STRINGS_API_VERSION,\n            LibRTStrings_APIVersion()\n        );\n        PyErr_SetString(PyExc_ValueError, err);\n        return -1;\n    }\n    return 0;\n}\n\nstatic inline bool CPyBytesWriter_Check(PyObject *obj) {\n    return Py_TYPE(obj) == LibRTStrings_BytesWriter_type_internal();\n}\n\nstatic inline bool CPyStringWriter_Check(PyObject *obj) {\n    return Py_TYPE(obj) == LibRTStrings_StringWriter_type_internal();\n}\n\n#endif  // MYPYC_EXPERIMENTAL\n\n#endif  // LIBRT_STRINGS_H\n"
  },
  {
    "path": "mypyc/lib-rt/strings/librt_strings_common.h",
    "content": "#ifndef LIBRT_STRINGS_COMMON_H\n#define LIBRT_STRINGS_COMMON_H\n\n#include <Python.h>\n#include <stdint.h>\n#include <string.h>\n\n// Byte-swap functions for endianness conversion (needed for both LE and BE operations)\n#if defined(_MSC_VER)\n#  include <stdlib.h>\n#  define BSWAP16(x) _byteswap_ushort(x)\n#  define BSWAP32(x) _byteswap_ulong(x)\n#  define BSWAP64(x) _byteswap_uint64(x)\n#elif defined(__GNUC__) || defined(__clang__)\n#  define BSWAP16(x) __builtin_bswap16(x)\n#  define BSWAP32(x) __builtin_bswap32(x)\n#  define BSWAP64(x) __builtin_bswap64(x)\n#else\n// Fallback for other compilers (slower but portable)\nstatic inline uint16_t BSWAP16(uint16_t x) {\n    return (uint16_t)((x >> 8) | (x << 8));\n}\nstatic inline uint32_t BSWAP32(uint32_t x) {\n    return ((x >> 24) & 0xFFU) |\n           ((x >>  8) & 0xFF00U) |\n           ((x <<  8) & 0xFF0000U) |\n           ((x << 24) & 0xFF000000U);\n}\nstatic inline uint64_t BSWAP64(uint64_t x) {\n    return ((x >> 56) & 0xFFULL) |\n           ((x >> 40) & 0xFF00ULL) |\n           ((x >> 24) & 0xFF0000ULL) |\n           ((x >>  8) & 0xFF000000ULL) |\n           ((x <<  8) & 0xFF00000000ULL) |\n           ((x << 24) & 0xFF0000000000ULL) |\n           ((x << 40) & 0xFF000000000000ULL) |\n           ((x << 56) & 0xFF00000000000000ULL);\n}\n#endif\n\n// Length of the default buffer embedded directly in a BytesWriter object\n#define WRITER_EMBEDDED_BUF_LEN 256\n\ntypedef struct {\n    PyObject_HEAD\n    char *buf;  // Beginning of the buffer\n    Py_ssize_t len;  // Current length (number of bytes written)\n    Py_ssize_t capacity;  // Total capacity of the buffer\n    char data[WRITER_EMBEDDED_BUF_LEN];  // Default buffer\n} BytesWriterObject;\n\n// Write a 16-bit signed integer in little-endian format to BytesWriter.\n// NOTE: This does NOT check buffer capacity - caller must ensure space is available.\nstatic inline void\nBytesWriter_WriteI16LEUnsafe(BytesWriterObject *self, int16_t value) {\n    // memcpy is reliably optimized to a single store by GCC, Clang, and MSVC\n#if PY_BIG_ENDIAN\n    uint16_t swapped = BSWAP16((uint16_t)value);\n    memcpy(self->buf + self->len, &swapped, 2);\n#else\n    memcpy(self->buf + self->len, &value, 2);\n#endif\n    self->len += 2;\n}\n\n// Write a 16-bit signed integer in big-endian format to BytesWriter.\n// NOTE: This does NOT check buffer capacity - caller must ensure space is available.\nstatic inline void\nBytesWriter_WriteI16BEUnsafe(BytesWriterObject *self, int16_t value) {\n    // memcpy is reliably optimized to a single store by GCC, Clang, and MSVC\n#if PY_BIG_ENDIAN\n    memcpy(self->buf + self->len, &value, 2);\n#else\n    uint16_t swapped = BSWAP16((uint16_t)value);\n    memcpy(self->buf + self->len, &swapped, 2);\n#endif\n    self->len += 2;\n}\n\n// Read a 16-bit signed integer in little-endian format from bytes.\n// NOTE: This does NOT check bounds - caller must ensure valid index.\nstatic inline int16_t\nCPyBytes_ReadI16LEUnsafe(const unsigned char *data) {\n    // memcpy is reliably optimized to a single load by GCC, Clang, and MSVC\n    uint16_t value;\n    memcpy(&value, data, 2);\n#if PY_BIG_ENDIAN\n    value = BSWAP16(value);\n#endif\n    return (int16_t)value;\n}\n\n// Read a 16-bit signed integer in big-endian format from bytes.\n// NOTE: This does NOT check bounds - caller must ensure valid index.\nstatic inline int16_t\nCPyBytes_ReadI16BEUnsafe(const unsigned char *data) {\n    // memcpy is reliably optimized to a single load by GCC, Clang, and MSVC\n    uint16_t value;\n    memcpy(&value, data, 2);\n#if PY_BIG_ENDIAN\n    // Already in big-endian format, no swap needed\n#else\n    value = BSWAP16(value);\n#endif\n    return (int16_t)value;\n}\n\n// Write a 32-bit signed integer in little-endian format to BytesWriter.\n// NOTE: This does NOT check buffer capacity - caller must ensure space is available.\nstatic inline void\nBytesWriter_WriteI32LEUnsafe(BytesWriterObject *self, int32_t value) {\n    // memcpy is reliably optimized to a single store by GCC, Clang, and MSVC\n#if PY_BIG_ENDIAN\n    uint32_t swapped = BSWAP32((uint32_t)value);\n    memcpy(self->buf + self->len, &swapped, 4);\n#else\n    memcpy(self->buf + self->len, &value, 4);\n#endif\n    self->len += 4;\n}\n\n// Write a 32-bit signed integer in big-endian format to BytesWriter.\n// NOTE: This does NOT check buffer capacity - caller must ensure space is available.\nstatic inline void\nBytesWriter_WriteI32BEUnsafe(BytesWriterObject *self, int32_t value) {\n    // memcpy is reliably optimized to a single store by GCC, Clang, and MSVC\n#if PY_BIG_ENDIAN\n    memcpy(self->buf + self->len, &value, 4);\n#else\n    uint32_t swapped = BSWAP32((uint32_t)value);\n    memcpy(self->buf + self->len, &swapped, 4);\n#endif\n    self->len += 4;\n}\n\n// Read a 32-bit signed integer in little-endian format from bytes.\n// NOTE: This does NOT check bounds - caller must ensure valid index.\nstatic inline int32_t\nCPyBytes_ReadI32LEUnsafe(const unsigned char *data) {\n    // memcpy is reliably optimized to a single load by GCC, Clang, and MSVC\n    uint32_t value;\n    memcpy(&value, data, 4);\n#if PY_BIG_ENDIAN\n    value = BSWAP32(value);\n#endif\n    return (int32_t)value;\n}\n\n// Read a 32-bit signed integer in big-endian format from bytes.\n// NOTE: This does NOT check bounds - caller must ensure valid index.\nstatic inline int32_t\nCPyBytes_ReadI32BEUnsafe(const unsigned char *data) {\n    // memcpy is reliably optimized to a single load by GCC, Clang, and MSVC\n    uint32_t value;\n    memcpy(&value, data, 4);\n#if PY_BIG_ENDIAN\n    // Already in big-endian format, no swap needed\n#else\n    value = BSWAP32(value);\n#endif\n    return (int32_t)value;\n}\n\n// Write a 64-bit signed integer in little-endian format to BytesWriter.\n// NOTE: This does NOT check buffer capacity - caller must ensure space is available.\nstatic inline void\nBytesWriter_WriteI64LEUnsafe(BytesWriterObject *self, int64_t value) {\n    // memcpy is reliably optimized to a single store by GCC, Clang, and MSVC\n#if PY_BIG_ENDIAN\n    uint64_t swapped = BSWAP64((uint64_t)value);\n    memcpy(self->buf + self->len, &swapped, 8);\n#else\n    memcpy(self->buf + self->len, &value, 8);\n#endif\n    self->len += 8;\n}\n\n// Write a 64-bit signed integer in big-endian format to BytesWriter.\n// NOTE: This does NOT check buffer capacity - caller must ensure space is available.\nstatic inline void\nBytesWriter_WriteI64BEUnsafe(BytesWriterObject *self, int64_t value) {\n    // memcpy is reliably optimized to a single store by GCC, Clang, and MSVC\n#if PY_BIG_ENDIAN\n    memcpy(self->buf + self->len, &value, 8);\n#else\n    uint64_t swapped = BSWAP64((uint64_t)value);\n    memcpy(self->buf + self->len, &swapped, 8);\n#endif\n    self->len += 8;\n}\n\n// Read a 64-bit signed integer in little-endian format from bytes.\n// NOTE: This does NOT check bounds - caller must ensure valid index.\nstatic inline int64_t\nCPyBytes_ReadI64LEUnsafe(const unsigned char *data) {\n    // memcpy is reliably optimized to a single load by GCC, Clang, and MSVC\n    uint64_t value;\n    memcpy(&value, data, 8);\n#if PY_BIG_ENDIAN\n    value = BSWAP64(value);\n#endif\n    return (int64_t)value;\n}\n\n// Read a 64-bit signed integer in big-endian format from bytes.\n// NOTE: This does NOT check bounds - caller must ensure valid index.\nstatic inline int64_t\nCPyBytes_ReadI64BEUnsafe(const unsigned char *data) {\n    // memcpy is reliably optimized to a single load by GCC, Clang, and MSVC\n    uint64_t value;\n    memcpy(&value, data, 8);\n#if PY_BIG_ENDIAN\n    // Already in big-endian format, no swap needed\n#else\n    value = BSWAP64(value);\n#endif\n    return (int64_t)value;\n}\n\n// Write a 32-bit float in little-endian format to BytesWriter.\n// NOTE: This does NOT check buffer capacity - caller must ensure space is available.\nstatic inline void\nBytesWriter_WriteF32LEUnsafe(BytesWriterObject *self, float value) {\n    // memcpy is reliably optimized to a single store by GCC, Clang, and MSVC\n#if PY_BIG_ENDIAN\n    uint32_t bits;\n    memcpy(&bits, &value, 4);\n    bits = BSWAP32(bits);\n    memcpy(self->buf + self->len, &bits, 4);\n#else\n    memcpy(self->buf + self->len, &value, 4);\n#endif\n    self->len += 4;\n}\n\n// Write a 32-bit float in big-endian format to BytesWriter.\n// NOTE: This does NOT check buffer capacity - caller must ensure space is available.\nstatic inline void\nBytesWriter_WriteF32BEUnsafe(BytesWriterObject *self, float value) {\n    // memcpy is reliably optimized to a single store by GCC, Clang, and MSVC\n#if PY_BIG_ENDIAN\n    memcpy(self->buf + self->len, &value, 4);\n#else\n    uint32_t bits;\n    memcpy(&bits, &value, 4);\n    bits = BSWAP32(bits);\n    memcpy(self->buf + self->len, &bits, 4);\n#endif\n    self->len += 4;\n}\n\n// Read a 32-bit float in little-endian format from bytes.\n// NOTE: This does NOT check bounds - caller must ensure valid index.\nstatic inline float\nCPyBytes_ReadF32LEUnsafe(const unsigned char *data) {\n    // memcpy is reliably optimized to a single load by GCC, Clang, and MSVC\n    float value;\n#if PY_BIG_ENDIAN\n    uint32_t bits;\n    memcpy(&bits, data, 4);\n    bits = BSWAP32(bits);\n    memcpy(&value, &bits, 4);\n#else\n    memcpy(&value, data, 4);\n#endif\n    return value;\n}\n\n// Read a 32-bit float in big-endian format from bytes.\n// NOTE: This does NOT check bounds - caller must ensure valid index.\nstatic inline float\nCPyBytes_ReadF32BEUnsafe(const unsigned char *data) {\n    // memcpy is reliably optimized to a single load by GCC, Clang, and MSVC\n    float value;\n#if PY_BIG_ENDIAN\n    memcpy(&value, data, 4);\n#else\n    uint32_t bits;\n    memcpy(&bits, data, 4);\n    bits = BSWAP32(bits);\n    memcpy(&value, &bits, 4);\n#endif\n    return value;\n}\n\n// Write a 64-bit float (double) in little-endian format to BytesWriter.\n// NOTE: This does NOT check buffer capacity - caller must ensure space is available.\nstatic inline void\nBytesWriter_WriteF64LEUnsafe(BytesWriterObject *self, double value) {\n    // memcpy is reliably optimized to a single store by GCC, Clang, and MSVC\n#if PY_BIG_ENDIAN\n    uint64_t bits;\n    memcpy(&bits, &value, 8);\n    bits = BSWAP64(bits);\n    memcpy(self->buf + self->len, &bits, 8);\n#else\n    memcpy(self->buf + self->len, &value, 8);\n#endif\n    self->len += 8;\n}\n\n// Write a 64-bit float (double) in big-endian format to BytesWriter.\n// NOTE: This does NOT check buffer capacity - caller must ensure space is available.\nstatic inline void\nBytesWriter_WriteF64BEUnsafe(BytesWriterObject *self, double value) {\n    // memcpy is reliably optimized to a single store by GCC, Clang, and MSVC\n#if PY_BIG_ENDIAN\n    memcpy(self->buf + self->len, &value, 8);\n#else\n    uint64_t bits;\n    memcpy(&bits, &value, 8);\n    bits = BSWAP64(bits);\n    memcpy(self->buf + self->len, &bits, 8);\n#endif\n    self->len += 8;\n}\n\n// Read a 64-bit float (double) in little-endian format from bytes.\n// NOTE: This does NOT check bounds - caller must ensure valid index.\nstatic inline double\nCPyBytes_ReadF64LEUnsafe(const unsigned char *data) {\n    // memcpy is reliably optimized to a single load by GCC, Clang, and MSVC\n    double value;\n#if PY_BIG_ENDIAN\n    uint64_t bits;\n    memcpy(&bits, data, 8);\n    bits = BSWAP64(bits);\n    memcpy(&value, &bits, 8);\n#else\n    memcpy(&value, data, 8);\n#endif\n    return value;\n}\n\n// Read a 64-bit float (double) in big-endian format from bytes.\n// NOTE: This does NOT check bounds - caller must ensure valid index.\nstatic inline double\nCPyBytes_ReadF64BEUnsafe(const unsigned char *data) {\n    // memcpy is reliably optimized to a single load by GCC, Clang, and MSVC\n    double value;\n#if PY_BIG_ENDIAN\n    memcpy(&value, data, 8);\n#else\n    uint64_t bits;\n    memcpy(&bits, data, 8);\n    bits = BSWAP64(bits);\n    memcpy(&value, &bits, 8);\n#endif\n    return value;\n}\n\n#endif  // LIBRT_STRINGS_COMMON_H\n"
  },
  {
    "path": "mypyc/lib-rt/stringwriter_extra_ops.c",
    "content": "// Primitives related to librt.strings.StringWriter that get linked statically\n// with compiled modules, instead of being called via a capsule.\n\n#include \"stringwriter_extra_ops.h\"\n\n#ifdef MYPYC_EXPERIMENTAL\n\n// All StringWriter operations are currently implemented as inline functions\n// in stringwriter_extra_ops.h, or use the exported capsule API directly.\n\n#endif // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/stringwriter_extra_ops.h",
    "content": "#ifndef STRINGWRITER_EXTRA_OPS_H\n#define STRINGWRITER_EXTRA_OPS_H\n\n#ifdef MYPYC_EXPERIMENTAL\n\n#include <stdbool.h>\n#include <stdint.h>\n#include <Python.h>\n\n#include \"mypyc_util.h\"\n#include \"strings/librt_strings.h\"\n\nstatic inline CPyTagged\nCPyStringWriter_Len(PyObject *obj) {\n    return (CPyTagged)((StringWriterObject *)obj)->len << 1;\n}\n\nstatic inline bool\nCPyStringWriter_EnsureSize(StringWriterObject *data, Py_ssize_t n) {\n    if (likely(data->capacity - data->len >= n)) {\n        return true;\n    } else {\n        return LibRTStrings_grow_string_buffer(data, n);\n    }\n}\n\nstatic inline char\nCPyStringWriter_Append(PyObject *obj, int32_t value) {\n    StringWriterObject *self = (StringWriterObject *)obj;\n    char kind = self->kind;\n\n    // Fast path: kind 1 (ASCII/Latin-1) with character < 256\n    if (kind == 1 && (uint32_t)value < 256) {\n        // Store length in local variable to enable additional optimizations\n        Py_ssize_t len = self->len;\n        if (!CPyStringWriter_EnsureSize(self, 1))\n            return CPY_NONE_ERROR;\n        self->buf[len] = (char)value;\n        self->len = len + 1;\n        return CPY_NONE;\n    }\n\n    // Slow path: handles kind switching and other cases\n    return LibRTStrings_string_append_slow_path(self, value);\n}\n\n// If index is negative, convert to non-negative index (no range checking)\nstatic inline int64_t CPyStringWriter_AdjustIndex(PyObject *obj, int64_t index) {\n    if (index < 0) {\n        return index + ((StringWriterObject *)obj)->len;\n    }\n    return index;\n}\n\nstatic inline bool CPyStringWriter_RangeCheck(PyObject *obj, int64_t index) {\n    return index >= 0 && index < ((StringWriterObject *)obj)->len;\n}\n\nstatic inline int32_t CPyStringWriter_GetItem(PyObject *obj, int64_t index) {\n    StringWriterObject *self = (StringWriterObject *)obj;\n    char kind = self->kind;\n    char *buf = self->buf;\n\n    if (kind == 1) {\n        return (uint8_t)buf[index];\n    } else if (kind == 2) {\n        uint16_t val;\n        memcpy(&val, buf + index * 2, 2);\n        return (int32_t)val;\n    } else {\n        uint32_t val;\n        memcpy(&val, buf + index * 4, 4);\n        return (int32_t)val;\n    }\n}\n\n#endif // MYPYC_EXPERIMENTAL\n\n#endif\n"
  },
  {
    "path": "mypyc/lib-rt/test_capi.cc",
    "content": "// Test cases\n\n#include <gtest/gtest.h>\n#include <Python.h>\n#include \"CPy.h\"\n\nstatic PyObject *moduleDict;\n\nstatic PyObject *int_from_str(const char *str) {\n    return PyLong_FromString(str, 0, 10);\n}\n\nstatic std::string str_from_object(PyObject *x) {\n    PyObject *str = PyObject_Str(x);\n    const char *utf8 = PyUnicode_AsUTF8(str);\n    return std::string(utf8);\n}\n\nstatic std::string str_from_int(CPyTagged x) {\n    return str_from_object(CPyTagged_AsObject(x));\n}\n\nstatic bool is_py_equal(PyObject *x, PyObject *y) {\n    int result = PyObject_RichCompareBool(x, y, Py_EQ);\n    if (result < 0) {\n        std::cout << \"ERROR: Rich compare failed\";\n    }\n    return result == 1;\n}\n\nstatic bool is_int_equal(CPyTagged x, CPyTagged y) {\n    if (CPyTagged_CheckShort(x)) {\n        return x == y;\n    } else if (CPyTagged_CheckShort(y)) {\n        return false;\n    } else {\n        return is_py_equal(CPyTagged_LongAsObject(x), CPyTagged_LongAsObject(y));\n    }\n}\n\nstatic void fail(std::string message) {\n    std::cerr << message << \"\\n\";\n    exit(1);\n}\n\nstatic PyObject *eval(std::string expr) {\n    PyObject *dict = PyDict_New();\n    auto result = PyRun_String(expr.c_str(), Py_eval_input, moduleDict, dict);\n    Py_DECREF(dict);\n    if (result == 0) {\n        fail(\"Python exception\");\n    }\n    return result;\n}\n\nstatic CPyTagged eval_int(std::string expr) {\n    auto o = eval(expr);\n    EXPECT_TRUE(PyLong_Check(o));\n    return CPyTagged_FromObject(o);\n}\n\nstatic PyObject *empty_list() {\n    PyObject *list = PyList_New(0);\n    EXPECT_TRUE(list);\n    return list;\n}\n\nstatic void list_append(PyObject *list, std::string expr) {\n    PyObject *obj = eval(expr);\n    int result = PyList_Append(list, obj);\n    EXPECT_TRUE(result == 0);\n}\n\nclass CAPITest : public ::testing::Test {\nprotected:\n    PyObject *max_short;\n    PyObject *min_short;\n    PyObject *min_pos_long;\n    PyObject *max_neg_long;\n    Py_ssize_t c_max_short;\n    Py_ssize_t c_min_short;\n    Py_ssize_t c_min_pos_long;\n    Py_ssize_t c_max_neg_long;\n\n    virtual void SetUp() {\n        if (!moduleDict) {\n            fail(\"Could not find module dictionary\");\n        }\n\n        c_max_short = CPY_TAGGED_MAX; // 2**62-1\n        c_min_pos_long = c_max_short + 1; // 2**62\n        c_min_short = CPY_TAGGED_MIN; // -2**62\n        c_max_neg_long = c_min_short - 1; // -(2**62+1)\n        max_short = PyLong_FromSsize_t(c_max_short);\n        min_pos_long = PyLong_FromSsize_t(c_min_pos_long);\n        min_short = PyLong_FromSsize_t(c_min_short);\n        max_neg_long = PyLong_FromSsize_t(c_max_neg_long);\n    }\n\n    virtual void TearDown() {\n        Py_DECREF(max_short);\n        Py_DECREF(min_pos_long);\n        Py_DECREF(min_short);\n        Py_DECREF(max_neg_long);\n    }\n};\n\nTEST_F(CAPITest, test_cint_conversions) {\n    EXPECT_EQ(CPyTagged_ShortFromInt(0), 0);\n    EXPECT_EQ(CPyTagged_ShortFromInt(3), 6);\n    EXPECT_EQ(CPyTagged_ShortFromInt(-5), -10);\n    EXPECT_EQ(CPyTagged_ShortAsSsize_t(0), 0);\n    EXPECT_EQ(CPyTagged_ShortAsSsize_t(6), 3);\n    EXPECT_EQ(CPyTagged_ShortAsSsize_t(-10), -5);\n}\n\nTEST_F(CAPITest, test_is_long_int) {\n    EXPECT_TRUE(CPyTagged_CheckLong(1));\n    EXPECT_TRUE(CPyTagged_CheckLong(15));\n    EXPECT_FALSE(CPyTagged_CheckLong(0));\n    EXPECT_FALSE(CPyTagged_CheckLong(6));\n    EXPECT_FALSE(CPyTagged_CheckLong(-4));\n}\n\nTEST_F(CAPITest, test_is_short_int) {\n    EXPECT_FALSE(CPyTagged_CheckShort(1));\n    EXPECT_FALSE(CPyTagged_CheckShort(15));\n    EXPECT_TRUE(CPyTagged_CheckShort(0));\n    EXPECT_TRUE(CPyTagged_CheckShort(6));\n    EXPECT_TRUE(CPyTagged_CheckShort(-4));\n}\n\nTEST_F(CAPITest, test_obj_to_short_int) {\n    EXPECT_EQ(CPyTagged_FromObject(int_from_str(\"0\")), CPyTagged_ShortFromInt(0));\n    EXPECT_EQ(CPyTagged_FromObject(int_from_str(\"1234\")), CPyTagged_ShortFromInt(1234));\n    EXPECT_EQ(CPyTagged_FromObject(int_from_str(\"-1234\")), CPyTagged_ShortFromInt(-1234));\n\n    EXPECT_EQ(CPyTagged_FromObject(max_short), CPyTagged_ShortFromSsize_t(c_max_short));\n    EXPECT_EQ(CPyTagged_FromObject(min_short), CPyTagged_ShortFromSsize_t(c_min_short));\n}\n\nTEST_F(CAPITest, test_obj_to_long_int) {\n    // A value larger than 2**64\n    PyObject *large = int_from_str(\"18464758493694263305\");\n    PyObject *small = int_from_str(\"-18464758493694263305\");\n    CPyTagged x;\n\n    x = CPyTagged_FromObject(large);\n    ASSERT_TRUE(CPyTagged_CheckLong(x));\n    EXPECT_TRUE(is_py_equal(large, CPyTagged_LongAsObject(x)));\n\n    x = CPyTagged_FromObject(small);\n    ASSERT_TRUE(CPyTagged_CheckLong(x));\n    EXPECT_TRUE(is_py_equal(small, CPyTagged_LongAsObject(x)));\n\n    x = CPyTagged_FromObject(min_pos_long);\n    ASSERT_TRUE(CPyTagged_CheckLong(x));\n    EXPECT_TRUE(is_py_equal(min_pos_long, CPyTagged_LongAsObject(x)));\n\n    x = CPyTagged_FromObject(max_neg_long);\n    ASSERT_TRUE(CPyTagged_CheckLong(x));\n    EXPECT_TRUE(is_py_equal(max_neg_long, CPyTagged_LongAsObject(x)));\n}\n\nTEST_F(CAPITest, test_short_int_to_obj) {\n    EXPECT_TRUE(is_py_equal(CPyTagged_AsObject(CPyTagged_ShortFromInt(0)), int_from_str(\"0\")));\n    EXPECT_TRUE(is_py_equal(CPyTagged_AsObject(CPyTagged_ShortFromInt(1234)),\n                            int_from_str(\"1234\")));\n    EXPECT_TRUE(is_py_equal(CPyTagged_AsObject(CPyTagged_ShortFromInt(-1234)),\n                            int_from_str(\"-1234\")));\n    EXPECT_TRUE(is_py_equal(CPyTagged_AsObject(CPyTagged_ShortFromSsize_t(c_max_short)),\n                            max_short));\n    EXPECT_TRUE(is_py_equal(CPyTagged_AsObject(CPyTagged_ShortFromSsize_t(c_min_short)),\n                            min_short));\n}\n\nTEST_F(CAPITest, test_long_int_to_obj) {\n    // A value larger than 2**64\n    PyObject *large = int_from_str(\"18464758493694263305\");\n    PyObject *small = int_from_str(\"-18464758493694263305\");\n    PyObject *x;\n\n    x = CPyTagged_AsObject(CPyTagged_FromObject(large));\n    EXPECT_TRUE(is_py_equal(large, x));\n    x = CPyTagged_AsObject(CPyTagged_FromObject(small));\n    EXPECT_TRUE(is_py_equal(small, x));\n    x = CPyTagged_AsObject(CPyTagged_FromObject(min_pos_long));\n    EXPECT_TRUE(is_py_equal(min_pos_long, x));\n    x = CPyTagged_AsObject(CPyTagged_FromObject(max_neg_long));\n    EXPECT_TRUE(is_py_equal(max_neg_long, x));\n}\n\n#define EXPECT_INT_EQUAL(x, y) \\\n    do { \\\n        if (!is_int_equal(x, y)) \\\n            std::cout << \"Failure: \" << str_from_int(x) << \" != \" << str_from_int(y) << \\\n                \"\\n\"; \\\n        EXPECT_TRUE(is_int_equal(x, y));  \\\n    } while (false)\n\n#define ASSERT_ADD(x, y, result) \\\n    EXPECT_TRUE(is_int_equal(CPyTagged_Add(eval_int(x), eval_int(y)), eval_int(result)))\n\nTEST_F(CAPITest, test_add_short_int) {\n    ASSERT_ADD(\"13\", \"8\", \"21\");\n    ASSERT_ADD(\"-13\", \"8\", \"-5\");\n    ASSERT_ADD(\"13\", \"-7\", \"6\");\n    ASSERT_ADD(\"13\", \"-14\", \"-1\");\n    ASSERT_ADD(\"-3\", \"-5\", \"-8\");\n}\n\nTEST_F(CAPITest, test_add_long_ints) {\n    ASSERT_ADD(\"2**64\", \"2**65\", \"2**64 + 2**65\");\n    ASSERT_ADD(\"2**64\", \"-2**65\", \"2**64 - 2**65\");\n}\n\nTEST_F(CAPITest, test_add_long_and_short) {\n    ASSERT_ADD(\"1\", \"2**65\", \"1 + 2**65\");\n    ASSERT_ADD(\"2**65\", \"1\", \"1 + 2**65\");\n}\n\nTEST_F(CAPITest, test_add_short_overflow) {\n    // Overfloat\n    ASSERT_ADD(\"2**62 - 1\", \"1\", \"2**62\");\n    ASSERT_ADD(\"-2**62\", \"-1\", \"-2**62 - 1\");\n}\n\nTEST_F(CAPITest, test_add_short_edge_cases) {\n    // Close but not quite overflow\n    ASSERT_ADD(\"2**62 - 2\", \"1\", \"2**62 - 1\");\n    ASSERT_ADD(\"-2**62 + 1\", \"-1\", \"-2**62\");\n    // Max magnitudes\n    ASSERT_ADD(\"2**62 - 1\", \"2**62 - 1\", \"2**63 - 2\");\n    ASSERT_ADD(\"2**62 - 1\", \"-2**62\", \"-1\");\n}\n\n#define ASSERT_SUBTRACT(x, y, result) \\\n    EXPECT_TRUE(is_int_equal(CPyTagged_Subtract(eval_int(x), eval_int(y)), eval_int(result)))\n\nTEST_F(CAPITest, test_subtract_short_int) {\n    ASSERT_SUBTRACT(\"13\", \"8\", \"5\");\n    ASSERT_SUBTRACT(\"8\", \"13\", \"-5\");\n    ASSERT_SUBTRACT(\"-13\", \"8\", \"-21\");\n    ASSERT_SUBTRACT(\"13\", \"-7\", \"20\");\n    ASSERT_SUBTRACT(\"-3\", \"-5\", \"2\");\n}\n\nTEST_F(CAPITest, test_subtract_long_int) {\n    ASSERT_SUBTRACT(\"2**65\", \"2**64\", \"2**65 - 2**64\");\n    ASSERT_SUBTRACT(\"2**65\", \"-2**64\", \"2**65 + 2**64\");\n}\n\nTEST_F(CAPITest, test_subtract_long_and_short) {\n    ASSERT_SUBTRACT(\"1\", \"2**65\", \"1 - 2**65\");\n    ASSERT_SUBTRACT(\"2**65\", \"1\", \"2**65 - 1\");\n}\n\nTEST_F(CAPITest, test_subtract_short_overflow) {\n    ASSERT_SUBTRACT(\"2**62-1\", \"-1\", \"2**62\");\n    ASSERT_SUBTRACT(\"-2**62\", \"1\", \"-2**62 - 1\");\n    ASSERT_SUBTRACT(\"0\", \"-2**62\", \"2**62\");\n    ASSERT_SUBTRACT(\"1\", \"-2**62 + 1\", \"2**62\");\n    ASSERT_SUBTRACT(\"-2\", \"2**62 - 1\", \"-2**62 - 1\");\n}\n\nTEST_F(CAPITest, test_subtract_short_edge_cases) {\n    // Close but not quite overflow\n    ASSERT_SUBTRACT(\"2**62 - 2\", \"-1\", \"2**62 - 1\");\n    ASSERT_SUBTRACT(\"-2**62 + 1\", \"1\", \"-2**62\");\n    // Max magnitudes\n    ASSERT_SUBTRACT(\"2**62 - 1\", \"-2**62\", \"2**63 - 1\");\n    ASSERT_SUBTRACT(\"-2**62\", \"2**62 - 1\", \"-2**63 + 1\");\n}\n\n#define ASSERT_MULTIPLY(x, y, result) \\\n    EXPECT_TRUE(is_int_equal(CPyTagged_Multiply(eval_int(x), eval_int(y)), eval_int(result)))\n\nTEST_F(CAPITest, test_multiply_int) {\n    ASSERT_MULTIPLY(\"0\", \"0\", \"0\");\n    ASSERT_MULTIPLY(\"3\", \"5\", \"15\");\n    ASSERT_MULTIPLY(\"2**40\", \"2**40\", \"2**80\");\n    ASSERT_MULTIPLY(\"2**30-1\", \"2**30-1\", \"(2**30-1)**2\");\n    ASSERT_MULTIPLY(\"2**30\", \"2**30-1\", \"2**30 * (2**30-1)\");\n    ASSERT_MULTIPLY(\"2**30-1\", \"2**30\", \"2**30 * (2**30-1)\");\n    ASSERT_MULTIPLY(\"2**15\", \"2**15-1\", \"2**15 * (2**15-1)\");\n    ASSERT_MULTIPLY(\"2**15-1\", \"2**15\", \"2**15 * (2**15-1)\");\n    ASSERT_MULTIPLY(\"3\", \"-5\", \"-15\");\n    ASSERT_MULTIPLY(\"-3\", \"5\", \"-15\");\n    ASSERT_MULTIPLY(\"-3\", \"-5\", \"15\");\n}\n\n#define ASSERT_FLOOR_DIV(x, y, result) \\\n    EXPECT_INT_EQUAL(CPyTagged_FloorDivide(eval_int(x), eval_int(y)), eval_int(result))\n\nTEST_F(CAPITest, test_floor_divide_short_int) {\n    ASSERT_FLOOR_DIV(\"18\", \"6\", \"3\");\n    ASSERT_FLOOR_DIV(\"17\", \"6\", \"2\");\n    ASSERT_FLOOR_DIV(\"12\", \"6\", \"2\");\n    ASSERT_FLOOR_DIV(\"15\", \"5\", \"3\");\n    ASSERT_FLOOR_DIV(\"14\", \"5\", \"2\");\n    ASSERT_FLOOR_DIV(\"11\", \"5\", \"2\");\n    ASSERT_FLOOR_DIV(\"-18\", \"6\", \"-3\");\n    ASSERT_FLOOR_DIV(\"-13\", \"6\", \"-3\");\n    ASSERT_FLOOR_DIV(\"-12\", \"6\", \"-2\");\n    ASSERT_FLOOR_DIV(\"18\", \"-6\", \"-3\");\n    ASSERT_FLOOR_DIV(\"13\", \"-6\", \"-3\");\n    ASSERT_FLOOR_DIV(\"12\", \"-6\", \"-2\");\n    ASSERT_FLOOR_DIV(\"-3\", \"-3\", \"1\");\n    ASSERT_FLOOR_DIV(\"-5\", \"-3\", \"1\");\n    ASSERT_FLOOR_DIV(\"-6\", \"-3\", \"2\");\n\n    ASSERT_FLOOR_DIV(\"2**60\", \"3\", \"2**60 // 3\");\n    ASSERT_FLOOR_DIV(\"-2**62\", \"-1\", \"2**62\");\n    ASSERT_FLOOR_DIV(\"-2**62\", \"1\", \"-2**62\");\n    ASSERT_FLOOR_DIV(\"2**62 - 1\", \"1\", \"2**62 - 1\");\n    ASSERT_FLOOR_DIV(\"2**62 - 1\", \"-1\", \"-2**62 + 1\");\n    ASSERT_FLOOR_DIV(\"2**60\", \"3\", \"2**60 // 3\");\n    ASSERT_FLOOR_DIV(\"-2**30\", \"-1\", \"2**30\");\n    ASSERT_FLOOR_DIV(\"-2**30\", \"1\", \"-2**30\");\n    ASSERT_FLOOR_DIV(\"2**30 - 1\", \"1\", \"2**30 - 1\");\n    ASSERT_FLOOR_DIV(\"2**30 - 1\", \"-1\", \"-2**30 + 1\");\n}\n\nTEST_F(CAPITest, test_floor_divide_long_int) {\n    ASSERT_FLOOR_DIV(\"2**100\", \"3\", \"2**100 // 3\");\n    ASSERT_FLOOR_DIV(\"3\", \"2**100\", \"0\");\n    ASSERT_FLOOR_DIV(\"2**100\", \"2**70 // 3\", \"2**100 // (2**70 // 3)\");\n}\n\n#define ASSERT_REMAINDER(x, y, result) \\\n    EXPECT_INT_EQUAL(CPyTagged_Remainder(eval_int(x), eval_int(y)), eval_int(result))\n\nTEST_F(CAPITest, test_remainder_short_int) {\n    ASSERT_REMAINDER(\"18\", \"6\", \"0\");\n    ASSERT_REMAINDER(\"17\", \"6\", \"5\");\n    ASSERT_REMAINDER(\"13\", \"6\", \"1\");\n    ASSERT_REMAINDER(\"12\", \"6\", \"0\");\n    ASSERT_REMAINDER(\"15\", \"5\", \"0\");\n    ASSERT_REMAINDER(\"14\", \"5\", \"4\");\n    ASSERT_REMAINDER(\"11\", \"5\", \"1\");\n    ASSERT_REMAINDER(\"-18\", \"6\", \"0\");\n    ASSERT_REMAINDER(\"-13\", \"6\", \"5\");\n    ASSERT_REMAINDER(\"-12\", \"6\", \"0\");\n    ASSERT_REMAINDER(\"18\", \"-6\", \"0\");\n    ASSERT_REMAINDER(\"13\", \"-6\", \"-5\");\n    ASSERT_REMAINDER(\"12\", \"-6\", \"0\");\n    ASSERT_REMAINDER(\"-3\", \"-3\", \"0\");\n    ASSERT_REMAINDER(\"-5\", \"-3\", \"-2\");\n    ASSERT_REMAINDER(\"-6\", \"-3\", \"0\");\n\n    ASSERT_REMAINDER(\"-1\", \"2**62 - 1\", \"2**62 - 2\");\n    ASSERT_REMAINDER(\"1\", \"-2**62\", \"-2**62 + 1\");\n}\n\nTEST_F(CAPITest, test_remainder_long_int) {\n    ASSERT_REMAINDER(\"2**100\", \"3\", \"2**100 % 3\");\n    ASSERT_REMAINDER(\"3\", \"2**100\", \"3\");\n    ASSERT_REMAINDER(\"2**100\", \"2**70 // 3\", \"2**100 % (2**70 // 3)\");\n}\n\n#define INT_EQ(x, y) \\\n    CPyTagged_IsEq(eval_int(x), eval_int(y))\n\nTEST_F(CAPITest, test_int_equality) {\n    EXPECT_TRUE(INT_EQ(\"0\", \"0\"));\n    EXPECT_TRUE(INT_EQ(\"5\", \"5\"));\n    EXPECT_TRUE(INT_EQ(\"-7\", \"-7\"));\n    EXPECT_TRUE(INT_EQ(\"2**65 + 0x1234\", \"2**65 + 0x1234\"));\n    EXPECT_TRUE(INT_EQ(\"-2**65 + 0x1234\", \"-2**65 + 0x1234\"));\n    EXPECT_FALSE(INT_EQ(\"0\", \"1\"));\n    EXPECT_FALSE(INT_EQ(\"5\", \"4\"));\n    EXPECT_FALSE(INT_EQ(\"-7\", \"7\"));\n    EXPECT_FALSE(INT_EQ(\"-7\", \"-6\"));\n    EXPECT_FALSE(INT_EQ(\"-7\", \"-5\"));\n    EXPECT_FALSE(INT_EQ(\"2**65 + 0x1234\", \"2**65 + 0x1233\"));\n    EXPECT_FALSE(INT_EQ(\"2**65 + 0x1234\", \"2**66 + 0x1234\"));\n    EXPECT_FALSE(INT_EQ(\"2**65 + 0x1234\", \"-2**65 - 0x1234\"));\n    EXPECT_FALSE(INT_EQ(\"-2**65 + 0x1234\", \"-2**65 + 0x1233\"));\n}\n\n#define INT_NE(x, y) \\\n    CPyTagged_IsNe(eval_int(x), eval_int(y))\n\nTEST_F(CAPITest, test_int_non_equality) {\n    EXPECT_FALSE(INT_NE(\"0\", \"0\"));\n    EXPECT_FALSE(INT_NE(\"5\", \"5\"));\n    EXPECT_FALSE(INT_NE(\"-7\", \"-7\"));\n    EXPECT_FALSE(INT_NE(\"2**65 + 0x1234\", \"2**65 + 0x1234\"));\n    EXPECT_FALSE(INT_NE(\"-2**65 + 0x1234\", \"-2**65 + 0x1234\"));\n    EXPECT_TRUE(INT_NE(\"0\", \"1\"));\n    EXPECT_TRUE(INT_NE(\"5\", \"4\"));\n    EXPECT_TRUE(INT_NE(\"-7\", \"7\"));\n    EXPECT_TRUE(INT_NE(\"-7\", \"-6\"));\n    EXPECT_TRUE(INT_NE(\"-7\", \"-5\"));\n    EXPECT_TRUE(INT_NE(\"2**65 + 0x1234\", \"2**65 + 0x1233\"));\n    EXPECT_TRUE(INT_NE(\"2**65 + 0x1234\", \"2**66 + 0x1234\"));\n    EXPECT_TRUE(INT_NE(\"2**65 + 0x1234\", \"-2**65 - 0x1234\"));\n    EXPECT_TRUE(INT_NE(\"-2**65 + 0x1234\", \"-2**65 + 0x1233\"));\n}\n\n#define INT_LT(x, y) \\\n    CPyTagged_IsLt(eval_int(x), eval_int(y))\n\nTEST_F(CAPITest, test_int_less_than) {\n    EXPECT_TRUE(INT_LT(\"0\", \"5\"));\n    EXPECT_TRUE(INT_LT(\"4\", \"5\"));\n    EXPECT_TRUE(INT_LT(\"-3\", \"1\"));\n    EXPECT_TRUE(INT_LT(\"-3\", \"0\"));\n    EXPECT_TRUE(INT_LT(\"-3\", \"-2\"));\n\n    EXPECT_FALSE(INT_LT(\"5\", \"0\"));\n    EXPECT_FALSE(INT_LT(\"5\", \"4\"));\n    EXPECT_FALSE(INT_LT(\"1\", \"-3\"));\n    EXPECT_FALSE(INT_LT(\"0\", \"-3\"));\n    EXPECT_FALSE(INT_LT(\"-2\", \"-3\"));\n    EXPECT_FALSE(INT_LT(\"-3\", \"-3\"));\n    EXPECT_FALSE(INT_LT(\"3\", \"3\"));\n\n    EXPECT_TRUE(INT_LT(\"5\", \"2**65\"));\n    EXPECT_TRUE(INT_LT(\"-2**65\", \"-5\"));\n    EXPECT_TRUE(INT_LT(\"-2**66\", \"2**65\"));\n    EXPECT_TRUE(INT_LT(\"2**65\", \"2**66\"));\n    EXPECT_TRUE(INT_LT(\"-2**66\", \"-2**65\"));\n\n    EXPECT_FALSE(INT_LT(\"2**65\", \"5\"));\n    EXPECT_FALSE(INT_LT(\"-5\", \"-2**65\"));\n    EXPECT_FALSE(INT_LT(\"2**65\", \"-2**66\"));\n    EXPECT_FALSE(INT_LT(\"2**66\", \"2**65\"));\n    EXPECT_FALSE(INT_LT(\"-2**65\", \"-2**66\"));\n    EXPECT_FALSE(INT_LT(\"-2**65\", \"-2**65\"));\n    EXPECT_FALSE(INT_LT(\"2**65\", \"2**65\"));\n}\n\n#define INT_GE(x, y) \\\n    CPyTagged_IsGe(eval_int(x), eval_int(y))\n\nTEST_F(CAPITest, test_int_greater_than_or_equal) {\n    EXPECT_TRUE(INT_GE(\"3\", \"2\"));\n    EXPECT_TRUE(INT_GE(\"3\", \"3\"));\n    EXPECT_FALSE(INT_GE(\"3\", \"4\"));\n    EXPECT_TRUE(INT_GE(\"3\", \"-4\"));\n    EXPECT_TRUE(INT_GE(\"-3\", \"-4\"));\n    EXPECT_TRUE(INT_GE(\"-3\", \"-3\"));\n    EXPECT_FALSE(INT_GE(\"-3\", \"-2\"));\n    EXPECT_FALSE(INT_GE(\"-3\", \"2\"));\n\n    EXPECT_TRUE(INT_GE(\"2**65\", \"2**65\"));\n    EXPECT_TRUE(INT_GE(\"2**65\", \"2**65 - 1\"));\n    EXPECT_FALSE(INT_GE(\"2**65\", \"2**65 + 1\"));\n    EXPECT_TRUE(INT_GE(\"2**65\", \"2**60\"));\n}\n\n#define INT_GT(x, y) \\\n    CPyTagged_IsGt(eval_int(x), eval_int(y))\n\nTEST_F(CAPITest, test_int_greater_than) {\n    EXPECT_TRUE(INT_GT(\"5\", \"0\"));\n    EXPECT_TRUE(INT_GT(\"5\", \"4\"));\n    EXPECT_FALSE(INT_GT(\"5\", \"5\"));\n    EXPECT_FALSE(INT_GT(\"5\", \"6\"));\n\n    EXPECT_TRUE(INT_GT(\"1\", \"-3\"));\n    EXPECT_FALSE(INT_GT(\"-3\", \"1\"));\n\n    EXPECT_TRUE(INT_GT(\"0\", \"-3\"));\n    EXPECT_TRUE(INT_GT(\"-2\", \"-3\"));\n    EXPECT_FALSE(INT_GT(\"-2\", \"-2\"));\n    EXPECT_FALSE(INT_GT(\"-2\", \"-1\"));\n\n    EXPECT_TRUE(INT_GT(\"2**65\", \"5\"));\n    EXPECT_TRUE(INT_GT(\"2**65\", \"2**65 - 1\"));\n    EXPECT_FALSE(INT_GT(\"2**65\", \"2**65\"));\n    EXPECT_FALSE(INT_GT(\"2**65\", \"2**65 + 1\"));\n\n    EXPECT_FALSE(INT_GT(\"-2**65\", \"1\"));\n    EXPECT_TRUE(INT_GT(\"-2**65\", \"-2**65 - 1\"));\n    EXPECT_FALSE(INT_GT(\"-2**65\", \"-2**65\"));\n    EXPECT_FALSE(INT_GT(\"-2**65\", \"-2**65 + 1\"));\n}\n\n#define INT_LE(x, y) \\\n    CPyTagged_IsLe(eval_int(x), eval_int(y))\n\nTEST_F(CAPITest, test_int_less_than_or_equal) {\n    EXPECT_TRUE(INT_LE(\"0\", \"5\"));\n    EXPECT_TRUE(INT_LE(\"5\", \"6\"));\n    EXPECT_TRUE(INT_LE(\"5\", \"5\"));\n    EXPECT_FALSE(INT_LE(\"5\", \"4\"));\n\n    EXPECT_FALSE(INT_LE(\"1\", \"-3\"));\n    EXPECT_TRUE(INT_LE(\"-3\", \"1\"));\n\n    EXPECT_TRUE(INT_LT(\"-3\", \"0\"));\n    EXPECT_TRUE(INT_LE(\"-2\", \"-1\"));\n    EXPECT_TRUE(INT_LE(\"-2\", \"-2\"));\n    EXPECT_FALSE(INT_LT(\"-2\", \"-3\"));\n\n    EXPECT_TRUE(INT_LE(\"5\", \"2**65\"));\n    EXPECT_FALSE(INT_LE(\"2**65\", \"5\"));\n    EXPECT_TRUE(INT_LE(\"2**65\", \"2**65 + 1\"));\n    EXPECT_TRUE(INT_LE(\"2**65\", \"2**65\"));\n    EXPECT_FALSE(INT_LE(\"2**65\", \"2**65 - 1\"));\n\n    EXPECT_TRUE(INT_LE(\"-2**65\", \"1\"));\n    EXPECT_FALSE(INT_LE(\"1\", \"-2**65\"));\n    EXPECT_TRUE(INT_LE(\"-2**65\", \"-2**65 + 1\"));\n    EXPECT_TRUE(INT_LE(\"-2**65\", \"-2**65\"));\n    EXPECT_FALSE(INT_LE(\"-2**65\", \"-2**65 - 1\"));\n}\n\n#define list_get_eq(list, index, value) \\\n    is_py_equal(CPyList_GetItem(list, eval_int(index)), eval(value))\n\nTEST_F(CAPITest, test_list_get) {\n    auto l = empty_list();\n    list_append(l, \"3\");\n    list_append(l, \"5\");\n    list_append(l, \"7\");\n    EXPECT_TRUE(list_get_eq(l, \"0\", \"3\"));\n    EXPECT_TRUE(list_get_eq(l, \"1\", \"5\"));\n    EXPECT_TRUE(list_get_eq(l, \"2\", \"7\"));\n    EXPECT_TRUE(list_get_eq(l, \"-1\", \"7\"));\n    EXPECT_TRUE(list_get_eq(l, \"-2\", \"5\"));\n    EXPECT_TRUE(list_get_eq(l, \"-3\", \"3\"));\n}\n\nTEST_F(CAPITest, test_tagged_as_long_long) {\n    auto s = eval_int(\"3\");\n    auto neg = eval_int(\"-1\");\n    auto l = eval_int(\"2**128\");\n    EXPECT_TRUE(CPyTagged_AsSsize_t(s) == 3);\n    EXPECT_FALSE(PyErr_Occurred());\n    EXPECT_TRUE(CPyTagged_AsSsize_t(neg) == -1);\n    EXPECT_FALSE(PyErr_Occurred());\n    EXPECT_TRUE(CPyTagged_AsSsize_t(l) == -1);\n    EXPECT_TRUE(PyErr_Occurred());\n    PyErr_Clear();\n}\n\n\n////\n// Python module glue to drive the C-API tests.\n//\n// The reason we have this as an extension module instead of a\n// standalone binary is because building an extension module is pretty\n// well behaved (just specify it with distutils/setuptools and it will\n// get compiled and linked against the running python) while linking a\n// library against libpython is a huge non-standard\n// PITA: python-config locations are janky and it behaves in weird\n// ways that I don't understand, while this works very cleanly.\n\nstatic PyObject *run_tests(PyObject *dummy, PyObject *should_be_null) {\n    // Fake command line arguments. We could arrange to actually pass\n    // in command line arguments (either real ones or ones given as\n    // arguments) but have not bothered.\n    int argc = 1;\n    char asdf[] = \"test_capi\"; // InitGoogleTest wants char** which means it can't be const...\n    char *argv[] = {asdf, NULL};\n    ::testing::InitGoogleTest(&argc, argv);\n    return PyLong_FromLong(RUN_ALL_TESTS());\n}\n\n\nstatic PyMethodDef test_methods[] = {\n    {\"run_tests\",  run_tests, METH_NOARGS, \"Run the C API tests\"},\n    {NULL, NULL, 0, NULL}\n};\n\nstatic struct PyModuleDef test_module = {\n    PyModuleDef_HEAD_INIT,\n    \"test_capi\",\n    NULL,\n    -1,\n    test_methods\n};\n\nPyMODINIT_FUNC\nPyInit_test_capi(void)\n{\n    PyObject *module = PyModule_Create(&test_module);\n    if (module) {\n        moduleDict = PyModule_GetDict(module);\n    }\n    return module;\n}\n"
  },
  {
    "path": "mypyc/lib-rt/time/librt_time.c",
    "content": "#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <time.h>\n#include <stdint.h>\n#include \"librt_time.h\"\n#include \"pythoncapi_compat.h\"\n#include \"mypyc_util.h\"\n\n#ifdef _WIN32\n#include <windows.h>\n#else\n#include <sys/time.h>\n#endif\n\n#ifdef MYPYC_EXPERIMENTAL\n\n// Internal function that returns a C double for mypyc primitives\n// Returns high-precision time in seconds (like time.time())\nstatic double\ntime_time_internal(void) {\n#ifdef _WIN32\n    // Windows: Use GetSystemTimePreciseAsFileTime for ~100ns precision\n    FILETIME ft;\n    ULARGE_INTEGER large;\n\n    GetSystemTimePreciseAsFileTime(&ft);\n    large.LowPart = ft.dwLowDateTime;\n    large.HighPart = ft.dwHighDateTime;\n\n    // Windows FILETIME is 100-nanosecond intervals since January 1, 1601\n    // 116444736000000000 = number of 100-ns intervals between 1601 and 1970\n    // Convert directly to seconds: 100ns * 1e-9 = 1e-7\n    int64_t intervals = large.QuadPart - 116444736000000000LL;\n    return (double)intervals * 1e-7;\n\n#else  // Unix-like systems (Linux, macOS, BSD, etc.)\n\n    // Try clock_gettime(CLOCK_REALTIME) for nanosecond precision\n    // This is available on POSIX.1-2001 and later (widely available on modern systems)\n#if defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0\n    struct timespec ts;\n    if (clock_gettime(CLOCK_REALTIME, &ts) == 0) {\n        // Convert seconds and nanoseconds separately to avoid large integer operations\n        return (double)ts.tv_sec + (double)ts.tv_nsec * 1e-9;\n    }\n    // Fall through to gettimeofday if clock_gettime failed\n#endif\n\n    // Fallback: gettimeofday for microsecond precision\n    // This is widely available (POSIX.1-2001, BSD, etc.)\n    struct timeval tv;\n    if (unlikely(gettimeofday(&tv, NULL) != 0)) {\n        PyErr_SetFromErrno(PyExc_OSError);\n        return CPY_FLOAT_ERROR;\n    }\n\n    // Convert seconds and microseconds separately to avoid large integer operations\n    return (double)tv.tv_sec + (double)tv.tv_usec * 1e-6;\n#endif\n}\n\n// Wrapper function for normal Python extension usage\nstatic PyObject*\ntime_time(PyObject *self, PyObject *const *args, size_t nargs) {\n    if (nargs != 0) {\n        PyErr_SetString(PyExc_TypeError, \"time() takes no arguments\");\n        return NULL;\n    }\n\n    double result = time_time_internal();\n    if (result == CPY_FLOAT_ERROR) {\n        return NULL;\n    }\n    return PyFloat_FromDouble(result);\n}\n\n#endif\n\nstatic PyMethodDef librt_time_module_methods[] = {\n#ifdef MYPYC_EXPERIMENTAL\n    {\"time\", (PyCFunction)time_time, METH_FASTCALL,\n     PyDoc_STR(\"Return the current time in seconds since the Unix epoch as a floating point number.\")},\n#endif\n    {NULL, NULL, 0, NULL}\n};\n\n#ifdef MYPYC_EXPERIMENTAL\n\nstatic int\ntime_abi_version(void) {\n    return LIBRT_TIME_ABI_VERSION;\n}\n\nstatic int\ntime_api_version(void) {\n    return LIBRT_TIME_API_VERSION;\n}\n\n#endif\n\nstatic int\nlibrt_time_module_exec(PyObject *m)\n{\n#ifdef MYPYC_EXPERIMENTAL\n    // Export mypyc internal C API via capsule\n    static void *time_api[LIBRT_TIME_API_LEN] = {\n        (void *)time_abi_version,\n        (void *)time_api_version,\n        (void *)time_time_internal,\n    };\n    PyObject *c_api_object = PyCapsule_New((void *)time_api, \"librt.time._C_API\", NULL);\n    if (PyModule_Add(m, \"_C_API\", c_api_object) < 0) {\n        return -1;\n    }\n#endif\n    return 0;\n}\n\nstatic PyModuleDef_Slot librt_time_module_slots[] = {\n    {Py_mod_exec, librt_time_module_exec},\n#ifdef Py_MOD_GIL_NOT_USED\n    {Py_mod_gil, Py_MOD_GIL_NOT_USED},\n#endif\n    {0, NULL}\n};\n\nstatic PyModuleDef librt_time_module = {\n    .m_base = PyModuleDef_HEAD_INIT,\n    .m_name = \"time\",\n    .m_doc = \"Fast time() function optimized for mypyc\",\n    .m_size = 0,\n    .m_methods = librt_time_module_methods,\n    .m_slots = librt_time_module_slots,\n};\n\nPyMODINIT_FUNC\nPyInit_time(void)\n{\n    return PyModuleDef_Init(&librt_time_module);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/time/librt_time.h",
    "content": "#ifndef LIBRT_TIME_H\n#define LIBRT_TIME_H\n\n#ifndef MYPYC_EXPERIMENTAL\n\nstatic int\nimport_librt_time(void)\n{\n    // All librt.time features are experimental for now, so don't set up the API here\n    return 0;\n}\n\n#else  // MYPYC_EXPERIMENTAL\n\n#include <Python.h>\n\n#define LIBRT_TIME_ABI_VERSION 1\n#define LIBRT_TIME_API_VERSION 1\n#define LIBRT_TIME_API_LEN 3\n\nstatic void *LibRTTime_API[LIBRT_TIME_API_LEN];\n\n#define LibRTTime_ABIVersion (*(int (*)(void)) LibRTTime_API[0])\n#define LibRTTime_APIVersion (*(int (*)(void)) LibRTTime_API[1])\n#define LibRTTime_time (*(double (*)(void)) LibRTTime_API[2])\n\nstatic int\nimport_librt_time(void)\n{\n    PyObject *mod = PyImport_ImportModule(\"librt.time\");\n    if (mod == NULL)\n        return -1;\n    Py_DECREF(mod);  // we import just for the side effect of making the below work.\n    void *capsule = PyCapsule_Import(\"librt.time._C_API\", 0);\n    if (capsule == NULL)\n        return -1;\n    memcpy(LibRTTime_API, capsule, sizeof(LibRTTime_API));\n    if (LibRTTime_ABIVersion() != LIBRT_TIME_ABI_VERSION) {\n        char err[128];\n        snprintf(err, sizeof(err), \"ABI version conflict for librt.time, expected %d, found %d\",\n            LIBRT_TIME_ABI_VERSION,\n            LibRTTime_ABIVersion()\n        );\n        PyErr_SetString(PyExc_ValueError, err);\n        return -1;\n    }\n    if (LibRTTime_APIVersion() < LIBRT_TIME_API_VERSION) {\n        char err[128];\n        snprintf(err, sizeof(err),\n                 \"API version conflict for librt.time, expected %d or newer, found %d (hint: upgrade librt)\",\n            LIBRT_TIME_API_VERSION,\n            LibRTTime_APIVersion()\n        );\n        PyErr_SetString(PyExc_ValueError, err);\n        return -1;\n    }\n    return 0;\n}\n\n#endif  // MYPYC_EXPERIMENTAL\n\n#endif  // LIBRT_TIME_H\n"
  },
  {
    "path": "mypyc/lib-rt/tuple_ops.c",
    "content": "// Tuple primitive operations\n//\n// These are registered in mypyc.primitives.tuple_ops.\n\n#include <Python.h>\n#include \"CPy.h\"\n\nPyObject *CPySequenceTuple_GetItem(PyObject *tuple, CPyTagged index) {\n    if (CPyTagged_CheckShort(index)) {\n        Py_ssize_t n = CPyTagged_ShortAsSsize_t(index);\n        Py_ssize_t size = PyTuple_GET_SIZE(tuple);\n        if (n >= 0) {\n            if (n >= size) {\n                PyErr_SetString(PyExc_IndexError, \"tuple index out of range\");\n                return NULL;\n            }\n        } else {\n            n += size;\n            if (n < 0) {\n                PyErr_SetString(PyExc_IndexError, \"tuple index out of range\");\n                return NULL;\n            }\n        }\n        PyObject *result = PyTuple_GET_ITEM(tuple, n);\n        Py_INCREF(result);\n        return result;\n    } else {\n        PyErr_SetString(PyExc_OverflowError, CPYTHON_LARGE_INT_ERRMSG);\n        return NULL;\n    }\n}\n\nPyObject *CPySequenceTuple_GetSlice(PyObject *obj, CPyTagged start, CPyTagged end) {\n    if (likely(PyTuple_CheckExact(obj)\n               && CPyTagged_CheckShort(start) && CPyTagged_CheckShort(end))) {\n        Py_ssize_t startn = CPyTagged_ShortAsSsize_t(start);\n        Py_ssize_t endn = CPyTagged_ShortAsSsize_t(end);\n        if (startn < 0) {\n            startn += PyTuple_GET_SIZE(obj);\n        }\n        if (endn < 0) {\n            endn += PyTuple_GET_SIZE(obj);\n        }\n        return PyTuple_GetSlice(obj, startn, endn);\n    }\n    return CPyObject_GetSlice(obj, start, end);\n}\n\n// No error checking\nPyObject *CPySequenceTuple_GetItemUnsafe(PyObject *tuple, Py_ssize_t index)\n{\n    PyObject *result = PyTuple_GET_ITEM(tuple, index);\n    Py_INCREF(result);\n    return result;\n}\n\n// PyTuple_SET_ITEM does no error checking,\n// and should only be used to fill in brand new tuples.\nvoid CPySequenceTuple_SetItemUnsafe(PyObject *tuple, Py_ssize_t index, PyObject *value)\n{\n    PyTuple_SET_ITEM(tuple, index, value);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/librt_vecs.c",
    "content": "// Definition of the mypyc.vecs module, which implements 'vec' and related functionality.\n//\n// NOTE: This is still experimental and work in progress.\n//\n// vec[t] is a sequence type that is optimized for use in mypyc-compiled code.\n// Performance in interpreted code is a secondary concern. It's primarily optimized\n// to provide fast item get/set operations and fast len(), especially for primitive\n// value item types, such as 'i32', 'float' or 'bool'.\n//\n// Example:\n//\n//    from mypy_extensions import i64\n//\n//    v = vec[i64]()\n//    v = append(v, 123)\n//    print(v[0])\n//    v[-1] = 234\n//\n// Key properties:\n//\n//  * In native code, a vec instance is an immutable value type with two fields\n//    (length, item buffer).\n//  * The item buffer can only store types of a specific type (enforced at runtime).\n//  * There are specialized item buffer types for certain primitive value item types,\n//    such as 'i32', 'float' and 'bool'. These use a packed value encoding.\n//  * Since vec values are immutable (only the buffer is mutable), any operation\n//    that changes the length (such as append) must return the updated vec value.\n//  * The buffer often a has higher capacity than the length of a vec. Append\n//    operations only allocate a new buffer if the capacity is exhausted, for O(1)\n//    amortized time complexity for appends.\n//  * Vec values can be boxed to PyObject *; this happens transparently and uses\n//    a wrapper object.\n//  * The item type can be a class type, or 't | None' if t is a class type. However,\n//    optional value item types such as 'float | None' are not supported, and 'int'\n//    is not valid as item type -- a native integer type such as `i64` or `u8` must\n//    be used instead.\n//  * Nested vecs are also supported (e.g. vec[vec[i32]]).\n//  * All features are also available in interpreted code, but often at some\n//    performance cost compared to using plain lists.\n//\n// Implementation summary:\n//\n//  * In a non-native context, instances are constructed via a temporary VecGenericAlias\n//    object, which is the result of 'vec[<t>]' (indexing the 'vec' type).\n//  * The module exports a C API via a capsule that mypyc compiled code uses for most\n//    operations.\n//  * There are multiple C structs that represent vec value objects with different item\n//    types, such as VecI64 and VecT. The latter is for arbitrary reference objects\n//    ('PyObject *' items internally).\n//  * There are also multiple buffer types, such as VecI64Buf and VecTBuf.\n//  * Similarly, there are multiple Python wrapper object types for boxed vecs, such as\n//    VecI64Type and VecTType.\n//  * An empty vec in compiled code can use a NULL pointer to represent the buffer,\n//    saving an object allocation in a common use case.\n//\n// Motivation:\n//  * A vec with value type items, such as vec[i64] or vec[vec[i32]], is very efficient\n//    compared to a list object, since values are not boxed, there is no need for runtime\n//    type checks on read, and index overflow checks are very fast due to the immutable\n//    value encoding.\n//  * A vec with a reference item type, such as vec[str], is often faster than a list,\n//    since there is no need for a cast on item read and the index checks are faster\n//    (among other things), but here the benefit is much smaller compared to using a\n//    value item type.\n//\n// Summary of files:\n//  * vec_t.c implements vec[t] and vec[t | None] for reference types\n//  * vec_nested.c implements nested vecs, such as vec[vec[str]]\n//  * vec_template.c is #included in multiples files (e.g. vec_i64.c) to produce\n//    specialized code for vecs with value item types (e.g. vec[i64])\n//  * This file defines the C extension and has some shared code\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include \"librt_vecs.h\"\n\n#ifdef MYPYC_EXPERIMENTAL\n\nPyTypeObject *LibRTVecs_I64TypeObj;\nPyTypeObject *LibRTVecs_I32TypeObj;\nPyTypeObject *LibRTVecs_I16TypeObj;\nPyTypeObject *LibRTVecs_U8TypeObj;\n\n\n// vec generic alias\n//\n// Used for the result of vec[t] (indexing) in interpreted context that must preserve\n// knowledge of 't'. These aren't real types. This only supports constructing instances.\ntypedef struct {\n    PyObject_HEAD\n    // Tagged pointer to PyTypeObject *, lowest bit set for optional item type\n    // Can also be one of magic VEC_ITEM_TYPE_* constants\n    size_t item_type;\n    size_t depth;  // Number of nested VecNested or VecT types\n} VecGenericAlias;\n\nstatic PyObject *vec_generic_alias_call(PyObject *self, PyObject *args, PyObject *kw)\n{\n    static char *kwlist[] = {\"\", NULL};\n    PyObject *init = NULL;\n    if (!PyArg_ParseTupleAndKeywords(args, kw, \"|O:vec\", kwlist, &init)) {\n        return NULL;\n    }\n    VecGenericAlias *p = (VecGenericAlias *)self;\n    if (p->depth == 0) {\n        if (init == NULL) {\n            VecT vec = VecT_New(0, 0, p->item_type);\n            if (VEC_IS_ERROR(vec))\n                return NULL;\n            return VecT_Box(vec, p->item_type);\n        } else {\n            return VecT_FromIterable(p->item_type, init);\n        }\n    } else {\n        if (init == NULL) {\n            VecNested vec = VecNested_New(0, 0, p->item_type, p->depth);\n            if (VEC_IS_ERROR(vec))\n                return NULL;\n            return VecNested_Box(vec);\n        } else {\n            return VecNested_FromIterable(p->item_type, p->depth, init);\n        }\n    }\n}\n\nstatic int\nVecGenericAlias_traverse(VecGenericAlias *self, visitproc visit, void *arg)\n{\n    if (!Vec_IsMagicItemType(self->item_type))\n        Py_VISIT((PyObject *)(self->item_type & ~1));\n    return 0;\n}\n\nstatic void\nVecGenericAlias_dealloc(VecGenericAlias *self)\n{\n    if (self->item_type && !Vec_IsMagicItemType(self->item_type)) {\n        Py_DECREF((PyObject *)(self->item_type & ~1));\n        self->item_type = 0;\n    }\n    PyObject_GC_Del(self);\n}\n\nPyObject *Vec_TypeToStr(size_t item_type, size_t depth) {\n    PyObject *item = NULL;\n    PyObject *result = NULL;\n\n    if (depth == 0) {\n        if ((item_type & ~1) == VEC_ITEM_TYPE_I64) {\n            item = PyUnicode_FromFormat(\"i64\");\n        } else if ((item_type & ~1) == VEC_ITEM_TYPE_U8) {\n            item = PyUnicode_FromFormat(\"u8\");\n        } else if ((item_type & ~1) == VEC_ITEM_TYPE_FLOAT) {\n            item = PyUnicode_FromFormat(\"float\");\n        } else if ((item_type & ~1) == VEC_ITEM_TYPE_I32) {\n            item = PyUnicode_FromFormat(\"i32\");\n        } else if ((item_type & ~1) == VEC_ITEM_TYPE_I16) {\n            item = PyUnicode_FromFormat(\"i16\");\n        } else if ((item_type & ~1) == VEC_ITEM_TYPE_BOOL) {\n            item = PyUnicode_FromFormat(\"bool\");\n        } else {\n            item = PyObject_GetAttrString((PyObject *)(item_type & ~1), \"__name__\");\n            if (item == NULL) {\n                return NULL;\n            }\n            if (item_type & 1) {\n                PyObject *optional_item = PyUnicode_FromFormat(\"%U | None\", item);\n                Py_DECREF(item);\n                if (optional_item == NULL) {\n                    return NULL;\n                }\n                item = optional_item;\n            }\n        }\n    } else {\n        item = Vec_TypeToStr(item_type, depth - 1);\n    }\n\n    if (item == NULL) {\n        return NULL;\n    }\n\n    result = PyUnicode_FromFormat(\"vec[%U]\", item);\n    Py_DECREF(item);\n    return result;\n}\n\nPyObject *VecGenericAlias_repr(PyObject *self) {\n    PyObject *l = NULL;\n    PyObject *prefix = NULL;\n    PyObject *suffix = NULL;\n    PyObject *sep = NULL;\n    PyObject *type_str = NULL;\n    PyObject *result = NULL;\n\n    l = PyList_New(0);\n    if (l == NULL) goto error;\n\n    prefix = PyUnicode_FromString(\"<class_proxy '\");\n    if (prefix == NULL) goto error;\n\n    suffix = PyUnicode_FromString(\"'>\");\n    if (suffix == NULL) goto error;\n\n    sep = PyUnicode_FromString(\"\");\n    if (sep == NULL) goto error;\n\n    if (PyList_Append(l, prefix) < 0) goto error;\n\n    VecGenericAlias *v = (VecGenericAlias *)self;\n    type_str = Vec_TypeToStr(v->item_type, v->depth);\n    if (type_str == NULL) goto error;\n\n    if (PyList_Append(l, type_str) < 0) goto error;\n    if (PyList_Append(l, suffix) < 0) goto error;\n\n    result = PyUnicode_Join(sep, l);\n\nerror:\n    Py_XDECREF(l);\n    Py_XDECREF(prefix);\n    Py_XDECREF(suffix);\n    Py_XDECREF(sep);\n    Py_XDECREF(type_str);\n    return result;\n}\n\nPyTypeObject VecGenericAliasType = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"vec_generic_alias\",\n    .tp_basicsize = sizeof(VecGenericAlias),\n    .tp_itemsize = 0,\n    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,\n    .tp_call = vec_generic_alias_call,\n    .tp_traverse = (traverseproc)VecGenericAlias_traverse,\n    .tp_dealloc = (destructor)VecGenericAlias_dealloc,\n    .tp_repr = (reprfunc)VecGenericAlias_repr,\n};\n\n\n// The 'vec' type\n//\n// This cannot be instantiated, and it's only used for isinstance and indexing: vec[T].\n// All specialized vec types (VecI64Type, VecI32Type, etc.) inherit from this base type,\n// so isinstance(v, vec) returns True for any specialized vec instance.\n\nstatic PyObject *extract_optional_item(PyObject *item) {\n    PyObject *args = PyObject_GetAttrString(item, \"__args__\");\n    if (args == NULL) {\n        PyErr_Clear();\n        return NULL;\n    }\n    if (!PyTuple_CheckExact(args))\n        goto error;\n    if (PyTuple_GET_SIZE(args) != 2)\n        goto error;\n    PyObject *item0 = PyTuple_GET_ITEM(args, 0);\n    PyObject *item1 = PyTuple_GET_ITEM(args, 1);\n    if (item0 == (PyObject *)Py_None->ob_type) {\n        Py_DECREF(args);\n        return item1;\n    } else if (item1 == (PyObject *)Py_None->ob_type) {\n        Py_DECREF(args);\n        return item0;\n    }\n  error:\n    Py_DECREF(args);\n    return NULL;\n}\n\n// Evaluation vec[<type>] in interpreted code and produce a generic alias object.\nstatic PyObject *vec_class_getitem(PyObject *type, PyObject *item)\n{\n    if (item == (PyObject *)LibRTVecs_I64TypeObj) {\n        Py_INCREF(&VecI64Type);\n        return (PyObject *)&VecI64Type;\n    } else if (item == (PyObject *)LibRTVecs_U8TypeObj) {\n        Py_INCREF(&VecU8Type);\n        return (PyObject *)&VecU8Type;\n    } else if (item == (PyObject *)&PyFloat_Type) {\n        Py_INCREF(&VecFloatType);\n        return (PyObject *)&VecFloatType;\n    } else if (item == (PyObject *)LibRTVecs_I32TypeObj) {\n        Py_INCREF(&VecI32Type);\n        return (PyObject *)&VecI32Type;\n    } else if (item == (PyObject *)LibRTVecs_I16TypeObj) {\n        Py_INCREF(&VecI16Type);\n        return (PyObject *)&VecI16Type;\n    } else if (item == (PyObject *)&PyBool_Type) {\n        Py_INCREF(&VecBoolType);\n        return (PyObject *)&VecBoolType;\n    } else {\n        size_t depth = 0;\n        size_t item_type;\n        int optional = 0;\n        if (!PyObject_TypeCheck(item, &PyType_Type)) {\n            PyObject *it = extract_optional_item(item);\n            if (it != NULL) {\n                optional = 1;\n                item = it;\n                // Check if this is a specialized value type that doesn't support None\n                if (item == (PyObject *)LibRTVecs_I64TypeObj ||\n                    item == (PyObject *)LibRTVecs_U8TypeObj ||\n                    item == (PyObject *)&PyFloat_Type ||\n                    item == (PyObject *)LibRTVecs_I32TypeObj ||\n                    item == (PyObject *)LibRTVecs_I16TypeObj ||\n                    item == (PyObject *)&PyBool_Type) {\n                    PyErr_SetString(PyExc_TypeError,\n                        \"vec does not support optional value types (use vec[object] instead)\");\n                    return NULL;\n                }\n            }\n            if (item->ob_type == &VecGenericAliasType) {\n                if (optional) {\n                    PyErr_SetString(PyExc_TypeError, \"optional type not expected in vec[...]\");\n                    return NULL;\n                }\n                VecGenericAlias *p = (VecGenericAlias *)item;\n                item_type = p->item_type;\n                depth = p->depth + 1;\n            } else if (!PyObject_TypeCheck(item, &PyType_Type)) {\n                PyErr_SetString(PyExc_TypeError, \"type object expected in vec[...]\");\n                return NULL;\n            } else {\n                item_type = (size_t)item | optional;\n            }\n        } else {\n            if (item == (PyObject *)&VecI64Type) {\n                item_type = VEC_ITEM_TYPE_I64;\n                depth = 1;\n            } else if (item == (PyObject *)&VecU8Type) {\n                item_type = VEC_ITEM_TYPE_U8;\n                depth = 1;\n            } else if (item == (PyObject *)&VecFloatType) {\n                item_type = VEC_ITEM_TYPE_FLOAT;\n                depth = 1;\n            } else if (item == (PyObject *)&VecI32Type) {\n                item_type = VEC_ITEM_TYPE_I32;\n                depth = 1;\n            } else if (item == (PyObject *)&VecI16Type) {\n                item_type = VEC_ITEM_TYPE_I16;\n                depth = 1;\n            } else if (item == (PyObject *)&VecBoolType) {\n                item_type = VEC_ITEM_TYPE_BOOL;\n                depth = 1;\n            } else {\n                item_type = (size_t)item;\n            }\n        }\n        if (item == (PyObject *)&PyLong_Type) {\n            PyErr_Format(PyExc_ValueError, \"unsupported type in vec[%s] (use i64, i32, i16, or u8)\",\n                         ((PyTypeObject *)item)->tp_name);\n            return NULL;\n        }\n        VecGenericAlias *p;\n        p = PyObject_GC_New(VecGenericAlias, &VecGenericAliasType);\n        if (p == NULL)\n            return NULL;\n        Py_INCREF(item);\n        p->item_type = item_type;\n        p->depth = depth;\n        PyObject_GC_Track(p);\n        return (PyObject *)p;\n    }\n}\n\nstatic PyMethodDef vec_methods[] = {\n    {\"__class_getitem__\", vec_class_getitem, METH_O|METH_CLASS, NULL},\n    {NULL, NULL, 0, NULL},  /* Sentinel */\n};\n\nPyTypeObject VecType = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"vec\",\n    .tp_basicsize = sizeof(VecBaseObject),\n    .tp_itemsize = 0,\n    .tp_flags = Py_TPFLAGS_DEFAULT,  // No Py_TPFLAGS_BASETYPE - prevent Python subclassing\n    .tp_methods = vec_methods,\n};\n\n// Common helpers\n\nPyObject *Vec_GenericRepr(PyObject *vec, size_t item_type, size_t depth, int verbose) {\n    PyObject *l = NULL;\n    PyObject *prefix = NULL;\n    PyObject *mid = NULL;\n    PyObject *suffix = NULL;\n    PyObject *sep = NULL;\n    PyObject *comma = NULL;\n    PyObject *result = NULL;\n\n    l = PyList_New(0);\n    if (l == NULL) goto error;\n\n    sep = PyUnicode_FromString(\"\");\n    if (sep == NULL) goto error;\n\n    comma = PyUnicode_FromString(\", \");\n    if (comma == NULL) goto error;\n\n    if (verbose) {\n        prefix = Vec_TypeToStr(item_type, depth);\n        if (prefix == NULL) goto error;\n\n        mid = PyUnicode_FromString(\"([\");\n        if (mid == NULL) goto error;\n\n        suffix = PyUnicode_FromString(\"])\");\n        if (suffix == NULL) goto error;\n    } else {\n        prefix = PyUnicode_FromString(\"\");\n        if (prefix == NULL) goto error;\n\n        mid = PyUnicode_FromString(\"[\");\n        if (mid == NULL) goto error;\n\n        suffix = PyUnicode_FromString(\"]\");\n        if (suffix == NULL) goto error;\n    }\n\n    if (PyList_Append(l, prefix) < 0) goto error;\n    if (PyList_Append(l, mid) < 0) goto error;\n\n    Py_ssize_t len = PyObject_Length(vec);\n    if (len < 0) goto error;\n\n    for (Py_ssize_t i = 0; i < len; i++) {\n        PyObject *it = PySequence_GetItem(vec, i);\n        if (it == NULL) goto error;\n\n        PyObject *r;\n        if (depth == 0 || it == Py_None) {\n            r = PyObject_Repr(it);\n        } else {\n            r = Vec_GenericRepr(it, item_type, depth - 1, 0);\n        }\n        Py_DECREF(it);\n\n        if (r == NULL) goto error;\n\n        if (PyList_Append(l, r) < 0) {\n            Py_DECREF(r);\n            goto error;\n        }\n        Py_DECREF(r);\n\n        if (i + 1 < len) {\n            if (PyList_Append(l, comma) < 0) goto error;\n        }\n    }\n\n    if (PyList_Append(l, suffix) < 0) goto error;\n\n    result = PyUnicode_Join(sep, l);\n\nerror:\n    Py_XDECREF(l);\n    Py_XDECREF(prefix);\n    Py_XDECREF(mid);\n    Py_XDECREF(suffix);\n    Py_XDECREF(sep);\n    Py_XDECREF(comma);\n    return result;\n}\n\n// Generic comparison implementation for vecs with PyObject * items.\nPyObject *Vec_GenericRichcompare(Py_ssize_t *len, PyObject **items,\n                                  Py_ssize_t *other_len, PyObject **other_items,\n                                  int op) {\n    int cmp = 1;\n    PyObject *res;\n    if (op == Py_EQ || op == Py_NE) {\n        if (*len != *other_len) {\n            cmp = 0;\n        } else {\n            for (Py_ssize_t i = 0; i < *len && i < *other_len; i++) {\n                int itemcmp = PyObject_RichCompareBool(items[i], other_items[i], Py_EQ);\n                if (itemcmp < 0)\n                    return NULL;\n                if (!itemcmp) {\n                    cmp = 0;\n                    break;\n                }\n            }\n        }\n        if (op == Py_NE)\n            cmp = cmp ^ 1;\n        res = cmp ? Py_True : Py_False;\n    } else\n        res = Py_NotImplemented;\n    Py_INCREF(res);\n    return res;\n}\n\nint Vec_GenericRemove(Py_ssize_t *len, PyObject **items, PyObject *item) {\n    for (Py_ssize_t i = 0; i < *len; i++) {\n        int match = 0;\n        if (items[i] == item)\n            match = 1;\n        else {\n            int itemcmp = PyObject_RichCompareBool(items[i], item, Py_EQ);\n            if (itemcmp < 0)\n                return 0;\n            match = itemcmp;\n        }\n        if (match) {\n            Py_CLEAR(items[i]);\n            for (; i < *len - 1; i++) {\n                items[i] = items[i + 1];\n            }\n            (*len)--;\n            return 1;\n        }\n    }\n    PyErr_SetString(PyExc_ValueError, \"vec.remove(x): x not in vec\");\n    return 0;\n}\n\nPyObject *Vec_GenericPop(Py_ssize_t *len, PyObject **items, Py_ssize_t index) {\n    if (index < 0)\n        index += *len;\n\n    if (index < 0 || index >= *len) {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        return NULL;\n    }\n\n    PyObject *item = items[index];\n    for (Py_ssize_t i = index; i < *len - 1; i++)\n        items[i] = items[i + 1];\n\n    (*len)--;\n    return item;\n}\n\nPyObject *Vec_GenericPopWrapper(Py_ssize_t *len, PyObject **items, PyObject *args) {\n    Py_ssize_t index = -1;\n    if (!PyArg_ParseTuple(args, \"|n:pop\", &index))\n        return NULL;\n\n    return Vec_GenericPop(len, items, index);\n}\n\n// Module-level functions\n\nstatic PyObject *vec_append(PyObject *self, PyObject *args)\n{\n    PyObject *vec;\n    PyObject *item;\n\n    if (!PyArg_ParseTuple(args, \"OO\", &vec, &item))\n        return NULL;\n\n    if (VecI64_Check(vec)) {\n        int64_t x = VecI64_UnboxItem(item);\n        if (VecI64_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecI64 v = ((VecI64Object *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecI64_Append(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecI64_Box(v);\n    } else if (VecU8_Check(vec)) {\n        uint8_t x = VecU8_UnboxItem(item);\n        if (VecU8_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecU8 v = ((VecU8Object *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecU8_Append(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecU8_Box(v);\n    } else if (VecFloat_Check(vec)) {\n        double x = VecFloat_UnboxItem(item);\n        if (VecFloat_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecFloat v = ((VecFloatObject *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecFloat_Append(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecFloat_Box(v);\n    } else if (VecI32_Check(vec)) {\n        int32_t x = VecI32_UnboxItem(item);\n        if (VecI32_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecI32 v = ((VecI32Object *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecI32_Append(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecI32_Box(v);\n    } else if (VecI16_Check(vec)) {\n        int16_t x = VecI16_UnboxItem(item);\n        if (VecI16_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecI16 v = ((VecI16Object *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecI16_Append(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecI16_Box(v);\n    } else if (VecBool_Check(vec)) {\n        double x = VecBool_UnboxItem(item);\n        if (VecBool_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecBool v = ((VecBoolObject *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecBool_Append(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecBool_Box(v);\n    } else if (VecT_Check(vec)) {\n        VecT v = ((VecTObject *)vec)->vec;\n        if (!VecT_ItemCheck(v, item, v.buf->item_type)) {\n            return NULL;\n        }\n        VEC_INCREF(v);\n        v = VecT_Append(v, item, v.buf->item_type);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecT_Box(v, v.buf->item_type);\n    } else if (VecNested_Check(vec)) {\n        VecNested v = ((VecNestedObject *)vec)->vec;\n        VecNestedBufItem vecitem;\n        if (VecNested_UnboxItem(v, item, &vecitem) < 0)\n            return NULL;\n        VEC_INCREF(v);\n        v = VecNested_Append(v, vecitem);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecNested_Box(v);\n    } else {\n        PyErr_Format(PyExc_TypeError, \"vec argument expected, got %.100s\",\n                     Py_TYPE(vec)->tp_name);\n        return NULL;\n    }\n}\n\nstatic PyObject *vec_remove(PyObject *self, PyObject *args)\n{\n    PyObject *vec;\n    PyObject *item;\n\n    if (!PyArg_ParseTuple(args, \"OO\", &vec, &item))\n        return NULL;\n\n    if (VecI64_Check(vec)) {\n        int64_t x = VecI64_UnboxItem(item);\n        if (VecI64_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecI64 v = ((VecI64Object *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecI64_Remove(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecI64_Box(v);\n    } else if (VecU8_Check(vec)) {\n        uint8_t x = VecU8_UnboxItem(item);\n        if (VecU8_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecU8 v = ((VecU8Object *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecU8_Remove(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecU8_Box(v);\n    } else if (VecFloat_Check(vec)) {\n        double x = VecFloat_UnboxItem(item);\n        if (VecFloat_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecFloat v = ((VecFloatObject *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecFloat_Remove(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecFloat_Box(v);\n    } else if (VecI32_Check(vec)) {\n        int32_t x = VecI32_UnboxItem(item);\n        if (VecI32_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecI32 v = ((VecI32Object *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecI32_Remove(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecI32_Box(v);\n    } else if (VecI16_Check(vec)) {\n        int16_t x = VecI16_UnboxItem(item);\n        if (VecI16_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecI16 v = ((VecI16Object *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecI16_Remove(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecI16_Box(v);\n    } else if (VecBool_Check(vec)) {\n        char x = VecBool_UnboxItem(item);\n        if (VecBool_IsUnboxError(x)) {\n            return NULL;\n        }\n        VecBool v = ((VecBoolObject *)vec)->vec;\n        VEC_INCREF(v);\n        v = VecBool_Remove(v, x);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecBool_Box(v);\n    } else if (VecT_Check(vec)) {\n        VecT v = ((VecTObject *)vec)->vec;\n        if (!VecT_ItemCheck(v, item, v.buf->item_type)) {\n            return NULL;\n        }\n        VEC_INCREF(v);\n        v = VecT_Remove(v, item);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecT_Box(v, v.buf->item_type);\n    } else if (VecNested_Check(vec)) {\n        VecNested v = ((VecNestedObject *)vec)->vec;\n        VecNestedBufItem vecitem;\n        if (VecNested_UnboxItem(v, item, &vecitem) < 0)\n            return NULL;\n        VEC_INCREF(v);\n        v = VecNested_Remove(v, vecitem);\n        if (VEC_IS_ERROR(v))\n            return NULL;\n        return VecNested_Box(v);\n    } else {\n        PyErr_Format(PyExc_TypeError, \"vec argument expected, got %.100s\",\n                     Py_TYPE(vec)->tp_name);\n        return NULL;\n    }\n}\n\nstatic PyObject *vec_pop(PyObject *self, PyObject *args)\n{\n    PyObject *vec;\n    Py_ssize_t index = -1;\n\n    if (!PyArg_ParseTuple(args, \"O|n:pop\", &vec, &index))\n        return NULL;\n\n    PyObject *result_item0;\n    PyObject *result_item1;\n\n    if (VecI64_Check(vec)) {\n        VecI64 v = ((VecI64Object *)vec)->vec;\n        VEC_INCREF(v);\n        VecI64PopResult r;\n        r = VecI64_Pop(v, index);\n        if (VEC_IS_ERROR(r.f0))\n            return NULL;\n        if ((result_item0 = VecI64_Box(r.f0)) == NULL)\n            return NULL;\n        result_item1 = VecI64_BoxItem(r.f1);\n    } else if (VecU8_Check(vec)) {\n        VecU8 v = ((VecU8Object *)vec)->vec;\n        VEC_INCREF(v);\n        VecU8PopResult r;\n        r = VecU8_Pop(v, index);\n        if (VEC_IS_ERROR(r.f0))\n            return NULL;\n        if ((result_item0 = VecU8_Box(r.f0)) == NULL)\n            return NULL;\n        result_item1 = VecU8_BoxItem(r.f1);\n    } else if (VecFloat_Check(vec)) {\n        VecFloat v = ((VecFloatObject *)vec)->vec;\n        VEC_INCREF(v);\n        VecFloatPopResult r;\n        r = VecFloat_Pop(v, index);\n        if (VEC_IS_ERROR(r.f0))\n            return NULL;\n        if ((result_item0 = VecFloat_Box(r.f0)) == NULL)\n            return NULL;\n        result_item1 = VecFloat_BoxItem(r.f1);\n    } else if (VecI32_Check(vec)) {\n        VecI32 v = ((VecI32Object *)vec)->vec;\n        VEC_INCREF(v);\n        VecI32PopResult r;\n        r = VecI32_Pop(v, index);\n        if (VEC_IS_ERROR(r.f0))\n            return NULL;\n        if ((result_item0 = VecI32_Box(r.f0)) == NULL)\n            return NULL;\n        result_item1 = VecI32_BoxItem(r.f1);\n    } else if (VecI16_Check(vec)) {\n        VecI16 v = ((VecI16Object *)vec)->vec;\n        VEC_INCREF(v);\n        VecI16PopResult r;\n        r = VecI16_Pop(v, index);\n        if (VEC_IS_ERROR(r.f0))\n            return NULL;\n        if ((result_item0 = VecI16_Box(r.f0)) == NULL)\n            return NULL;\n        result_item1 = VecI16_BoxItem(r.f1);\n    } else if (VecBool_Check(vec)) {\n        VecBool v = ((VecBoolObject *)vec)->vec;\n        VEC_INCREF(v);\n        VecBoolPopResult r;\n        r = VecBool_Pop(v, index);\n        if (VEC_IS_ERROR(r.f0))\n            return NULL;\n        if ((result_item0 = VecBool_Box(r.f0)) == NULL)\n            return NULL;\n        result_item1 = VecBool_BoxItem(r.f1);\n    } else if (VecT_Check(vec)) {\n        VecT v = ((VecTObject *)vec)->vec;\n        VEC_INCREF(v);\n        VecTPopResult r;\n        r = VecT_Pop(v, index);\n        if (VEC_IS_ERROR(r.f0))\n            return NULL;\n        result_item0 = VecT_Box(r.f0, v.buf->item_type);\n        if (result_item0 == NULL) {\n            Py_DECREF(r.f1);\n            return NULL;\n        }\n        result_item1 = r.f1;\n    } else if (VecNested_Check(vec)) {\n        VecNested v = ((VecNestedObject *)vec)->vec;\n        VEC_INCREF(v);\n        VecNestedPopResult r;\n        r = VecNested_Pop(v, index);\n        if (VEC_IS_ERROR(r.f0))\n            return NULL;\n        result_item0 = VecNested_Box(r.f0);\n        if (result_item0 == NULL) {\n            Py_DECREF(r.f0.buf);\n            Py_DECREF(r.f1.buf);\n            return NULL;\n        }\n        result_item1 = VecNested_BoxItem(r.f0, r.f1);\n        if (result_item1 == NULL) {\n            Py_DECREF(result_item0);\n            Py_DECREF(r.f1.buf);\n            return NULL;\n        }\n    } else {\n        PyErr_Format(PyExc_TypeError, \"vec argument expected, got %.100s\",\n                     Py_TYPE(vec)->tp_name);\n        return NULL;\n    }\n\n    if (result_item1 == NULL) {\n        Py_DECREF(result_item0);\n        return NULL;\n    }\n\n    PyObject *res = PyTuple_New(2);\n    if (res == NULL) {\n        Py_DECREF(result_item0);\n        Py_DECREF(result_item1);\n        return NULL;\n    }\n\n    PyTuple_SET_ITEM(res, 0, result_item0);\n    PyTuple_SET_ITEM(res, 1, result_item1);\n    return res;\n}\n\n// Return the base VecType for isinstance checks\nstatic PyTypeObject *get_vec_type(void) {\n    return &VecType;\n}\n\nstatic VecCapsule Capsule = {\n    &Vec_TAPI,\n    &Vec_NestedAPI,\n    &Vec_I64API,\n    &Vec_I32API,\n    &Vec_I16API,\n    &Vec_U8API,\n    &Vec_FloatAPI,\n    &Vec_BoolAPI,\n    get_vec_type,\n};\n\n#endif  // MYPYC_EXPERIMENTAL\n\nstatic PyMethodDef VecsMethods[] = {\n#ifdef MYPYC_EXPERIMENTAL\n    {\"append\",  vec_append, METH_VARARGS, \"Append a value to the end of a vec\"},\n    {\"remove\",  vec_remove, METH_VARARGS, \"Remove first occurrence of value from a vec\"},\n    {\"pop\",  vec_pop, METH_VARARGS, \"Remove and return vec item at index (default last)\"},\n#endif\n    {NULL, NULL, 0, NULL}        /* Sentinel */\n};\n\nstatic int\nlibrt_vecs_module_exec(PyObject *m)\n{\n#ifdef MYPYC_EXPERIMENTAL\n    PyObject *ext = PyImport_ImportModule(\"mypy_extensions\");\n    if (ext == NULL) {\n        return -1;\n    }\n\n    LibRTVecs_I64TypeObj = (PyTypeObject *)PyObject_GetAttrString(ext, \"i64\");\n    if (LibRTVecs_I64TypeObj == NULL) {\n        return -1;\n    }\n    if (!PyType_Check(LibRTVecs_I64TypeObj)) {\n        PyErr_SetString(PyExc_TypeError, \"mypy_extensions.i64 is not a type\");\n        return -1;\n    }\n    LibRTVecs_I32TypeObj = (PyTypeObject *)PyObject_GetAttrString(ext, \"i32\");\n    if (LibRTVecs_I32TypeObj == NULL) {\n        return -1;\n    }\n    if (!PyType_Check(LibRTVecs_I32TypeObj)) {\n        PyErr_SetString(PyExc_TypeError, \"mypy_extensions.i32 is not a type\");\n        return -1;\n    }\n    LibRTVecs_I16TypeObj = (PyTypeObject *)PyObject_GetAttrString(ext, \"i16\");\n    if (LibRTVecs_I16TypeObj == NULL) {\n        return -1;\n    }\n    if (!PyType_Check(LibRTVecs_I16TypeObj)) {\n        PyErr_SetString(PyExc_TypeError, \"mypy_extensions.i16 is not a type\");\n        return -1;\n    }\n    LibRTVecs_U8TypeObj = (PyTypeObject *)PyObject_GetAttrString(ext, \"u8\");\n    if (LibRTVecs_U8TypeObj == NULL) {\n        return -1;\n    }\n    if (!PyType_Check(LibRTVecs_U8TypeObj)) {\n        PyErr_SetString(PyExc_TypeError, \"mypy_extensions.u8 is not a type\");\n        return -1;\n    }\n\n    if (PyType_Ready(&VecType) < 0)\n        return -1;\n    if (PyType_Ready(&VecGenericAliasType) < 0)\n        return -1;\n\n    if (PyType_Ready(&VecTType) < 0)\n        return -1;\n    if (PyType_Ready(&VecTBufType) < 0)\n        return -1;\n\n    if (PyType_Ready(&VecNestedType) < 0)\n        return -1;\n    if (PyType_Ready(&VecNestedBufType) < 0)\n        return -1;\n\n    if (PyType_Ready(&VecI64Type) < 0)\n        return -1;\n    if (PyType_Ready(&VecI64BufType) < 0)\n        return -1;\n    if (PyType_Ready(&VecI32Type) < 0)\n        return -1;\n    if (PyType_Ready(&VecI32BufType) < 0)\n        return -1;\n    if (PyType_Ready(&VecI16Type) < 0)\n        return -1;\n    if (PyType_Ready(&VecI16BufType) < 0)\n        return -1;\n    if (PyType_Ready(&VecU8Type) < 0)\n        return -1;\n    if (PyType_Ready(&VecU8BufType) < 0)\n        return -1;\n    if (PyType_Ready(&VecFloatType) < 0)\n        return -1;\n    if (PyType_Ready(&VecFloatBufType) < 0)\n        return -1;\n    if (PyType_Ready(&VecBoolType) < 0)\n        return -1;\n    if (PyType_Ready(&VecBoolBufType) < 0)\n        return -1;\n\n    Py_INCREF(&VecType);\n    if (PyModule_AddObject(m, \"vec\", (PyObject *)&VecType) < 0) {\n        Py_DECREF(&VecType);\n        return -1;\n    }\n\n    PyObject *c_api = PyCapsule_New(&Capsule, \"librt.vecs._C_API\", NULL);\n    if (c_api == NULL)\n        return -1;\n\n    if (PyModule_AddObject(m, \"_C_API\", c_api) < 0) {\n        Py_XDECREF(c_api);\n        Py_DECREF(&VecType);\n        return -1;\n    }\n\n    Py_DECREF(ext);\n#endif\n    return 0;\n}\n\nstatic PyModuleDef_Slot librt_vecs_module_slots[] = {\n    {Py_mod_exec, librt_vecs_module_exec},\n#ifdef Py_MOD_GIL_NOT_USED\n    {Py_mod_gil, Py_MOD_GIL_NOT_USED},\n#endif\n    {0, NULL}\n};\n\nstatic PyModuleDef vecsmodule = {\n    .m_base = PyModuleDef_HEAD_INIT,\n    .m_name = \"vecs\",\n    .m_doc = \"This module implements the vec type and related functionality.\",\n    .m_size = 0,\n    .m_methods = VecsMethods,\n    .m_slots = librt_vecs_module_slots,\n};\n\nPyMODINIT_FUNC\nPyInit_vecs(void)\n{\n    return PyModuleDef_Init(&vecsmodule);\n}\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/librt_vecs.h",
    "content": "#ifndef VEC_H_INCL\n#define VEC_H_INCL\n\n// Header for the implementation of librt.vecs, which defines the 'vec' type.\n// Refer to librt_vecs.c for more detailed information.\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include <stdint.h>\n\n#ifndef MYPYC_EXPERIMENTAL\n\nstatic int\nimport_librt_vecs(void)\n{\n    // All librt.vecs features are experimental for now, so don't set up the API here\n    return 0;\n}\n\n#else  // MYPYC_EXPERIMENTAL\n\n// Magic (native) integer return value on exception. Caller must also\n// use PyErr_Occurred() since this overlaps with valid integer values.\n#define MYPYC_INT_ERROR -113\n\n// Item type constants for supported packed/specialized item types; must be\n// even but not a multiple of 4 (2 + 4 * n). Each of these has a corresponding\n// distinct implementation C extension class. For example, vec[i64] has a\n// different runtime type than vec[i32]. All other item types use generic\n// implementations.\n#define VEC_ITEM_TYPE_I64 2\n#define VEC_ITEM_TYPE_I32 6\n#define VEC_ITEM_TYPE_I16 10\n#define VEC_ITEM_TYPE_U8  14\n#define VEC_ITEM_TYPE_FLOAT 18\n#define VEC_ITEM_TYPE_BOOL 22\n\nstatic inline size_t Vec_IsMagicItemType(size_t item_type) {\n    return item_type & 2;\n}\n\n\n// Buffer objects\n\n\n// vecbuf[i64]\ntypedef struct _VecI64BufObject {\n    PyObject_VAR_HEAD\n    int64_t items[1];\n} VecI64BufObject;\n\n// vecbuf[i32]\ntypedef struct _VecI32BufObject {\n    PyObject_VAR_HEAD\n    int32_t items[1];\n} VecI32BufObject;\n\n// vecbuf[i16]\ntypedef struct _VecI16BufObject {\n    PyObject_VAR_HEAD\n    int16_t items[1];\n} VecI16BufObject;\n\n// vecbuf[u8]\ntypedef struct _VecU8BufObject {\n    PyObject_VAR_HEAD\n    uint8_t items[1];\n} VecU8BufObject;\n\n// vecbuf[float]\ntypedef struct _VecFloatBufObject {\n    PyObject_VAR_HEAD\n    double items[1];\n} VecFloatBufObject;\n\n// vecbuf[bool]\ntypedef struct _VecBoolBufObject {\n    PyObject_VAR_HEAD\n    char items[1];\n} VecBoolBufObject;\n\n// Simple generic vecbuf: vecbuf[t] when t is a type object\ntypedef struct _VecTBufObject {\n    PyObject_VAR_HEAD\n    // Tagged pointer to PyTypeObject *. The lowest bit is 1 for optional item type.\n    size_t item_type;\n    PyObject *items[1];\n} VecTBufObject;\n\ntypedef struct _VecNestedBufItem {\n    Py_ssize_t len;\n    PyObject *buf;\n} VecNestedBufItem;\n\n// Nested vec type: vec[vec[...]], vec[vec[...] | None], etc.\ntypedef struct _VecNestedBufObject {\n    PyObject_VAR_HEAD\n    // Tagged pointer to PyTypeObject *. Lowest bit is set for optional item type.\n    // The second lowest bit is set for a packed item type (VEC_ITEM_TYPE_*).\n    size_t item_type;\n    // Number of nested vec types (of any kind, at least 1)\n    size_t depth;\n    VecNestedBufItem items[1];\n} VecNestedBufObject;\n\n\n// Unboxed vec objects\n\n\ntypedef struct _VecI64 {\n    Py_ssize_t len;\n    VecI64BufObject *buf;\n} VecI64;\n\ntypedef struct _VecI32 {\n    Py_ssize_t len;\n    VecI32BufObject *buf;\n} VecI32;\n\ntypedef struct _VecI16 {\n    Py_ssize_t len;\n    VecI16BufObject *buf;\n} VecI16;\n\ntypedef struct _VecU8 {\n    Py_ssize_t len;\n    VecU8BufObject *buf;\n} VecU8;\n\ntypedef struct _VecFloat {\n    Py_ssize_t len;\n    VecFloatBufObject *buf;\n} VecFloat;\n\ntypedef struct _VecBool {\n    Py_ssize_t len;\n    VecBoolBufObject *buf;\n} VecBool;\n\ntypedef struct _VecT {\n    Py_ssize_t len;\n    VecTBufObject *buf;\n} VecT;\n\ntypedef struct _VecNested {\n    Py_ssize_t len;\n    VecNestedBufObject *buf;\n} VecNested;\n\n\n// Boxed vec objects\n\n\n// Arbitrary boxed vec object (only shared bits)\ntypedef struct _VecObject {\n    PyObject_HEAD\n    Py_ssize_t len;\n} VecObject;\n\n// Base vec type object (for isinstance checks)\n// This is an abstract base type that all specialized vec types inherit from.\n// It cannot be instantiated directly - only used for isinstance(x, vec).\ntypedef struct _VecBaseObject {\n    PyObject_HEAD\n} VecBaseObject;\n\n// Boxed vec[i64]\ntypedef struct _VecI64Object {\n    PyObject_HEAD\n    VecI64 vec;\n} VecI64Object;\n\n// Boxed vec[i32]\ntypedef struct _VecI32Object {\n    PyObject_HEAD\n    VecI32 vec;\n} VecI32Object;\n\n// Boxed vec[i16]\ntypedef struct _VecI16Object {\n    PyObject_HEAD\n    VecI16 vec;\n} VecI16Object;\n\n// Boxed vec[u8]\ntypedef struct _VecU8Object {\n    PyObject_HEAD\n    VecU8 vec;\n} VecU8Object;\n\n// Boxed vec[float]\ntypedef struct _VecFloatObject {\n    PyObject_HEAD\n    VecFloat vec;\n} VecFloatObject;\n\n// Boxed vec[bool]\ntypedef struct _VecBoolObject {\n    PyObject_HEAD\n    VecBool vec;\n} VecBoolObject;\n\n// Simple boxed generic vecbuf: vecbuf[t] when t is a type object\ntypedef struct _VecTObject {\n    PyObject_HEAD\n    VecT vec;\n} VecTObject;\n\n// Extended generic vec type: vec[t | None], vec[vec[...]], etc.\ntypedef struct _VecNestedObject {\n    PyObject_HEAD\n    VecNested vec;\n} VecNestedObject;\n\n\n#ifndef MYPYC_DECLARED_tuple_T2V88\n#define MYPYC_DECLARED_tuple_T2V88\ntypedef struct tuple_T2V88 {\n    VecI64 f0;\n    int64_t f1;\n} tuple_T2V88;\nstatic tuple_T2V88 tuple_undefined_T2V88 = { { -1, NULL } , 0 };\n#endif\n\n#ifndef MYPYC_DECLARED_tuple_T2V44\n#define MYPYC_DECLARED_tuple_T2V44\ntypedef struct tuple_T2V44 {\n    VecI32 f0;\n    int32_t f1;\n} tuple_T2V44;\nstatic tuple_T2V44 tuple_undefined_T2V44 = { { -1, NULL } , 0 };\n#endif\n\n#ifndef MYPYC_DECLARED_tuple_T2V22\n#define MYPYC_DECLARED_tuple_T2V22\ntypedef struct tuple_T2V22 {\n    VecI16 f0;\n    int16_t f1;\n} tuple_T2V22;\nstatic tuple_T2V22 tuple_undefined_T2V22 = { { -1, NULL } , 0 };\n#endif\n\n#ifndef MYPYC_DECLARED_tuple_T2VU1U1\n#define MYPYC_DECLARED_tuple_T2VU1U1\ntypedef struct tuple_T2VU1U1 {\n    VecU8 f0;\n    uint8_t f1;\n} tuple_T2VU1U1;\nstatic tuple_T2VU1U1 tuple_undefined_T2VU1U1 = { { -1, NULL } , 0 };\n#endif\n\n#ifndef MYPYC_DECLARED_tuple_T2VFF\n#define MYPYC_DECLARED_tuple_T2VFF\ntypedef struct tuple_T2VFF {\n    VecFloat f0;\n    double f1;\n} tuple_T2VFF;\nstatic tuple_T2VFF tuple_undefined_T2VFF = { { -1, NULL } , 0.0 };\n#endif\n\n#ifndef MYPYC_DECLARED_tuple_T2VCC\n#define MYPYC_DECLARED_tuple_T2VCC\ntypedef struct tuple_T2VCC {\n    VecBool f0;\n    char f1;\n} tuple_T2VCC;\nstatic tuple_T2VCC tuple_undefined_T2VCC = { { -1, NULL } , 0 };\n#endif\n\ntypedef tuple_T2V88 VecI64PopResult;\ntypedef tuple_T2V44 VecI32PopResult;\ntypedef tuple_T2V22 VecI16PopResult;\ntypedef tuple_T2VU1U1 VecU8PopResult;\ntypedef tuple_T2VFF VecFloatPopResult;\ntypedef tuple_T2VCC VecBoolPopResult;\n\n// vec[i64] operations + type objects (stored in a capsule)\ntypedef struct _VecI64API {\n    PyTypeObject *boxed_type;\n    PyTypeObject *buf_type;\n    VecI64 (*alloc)(Py_ssize_t, Py_ssize_t);\n    PyObject *(*box)(VecI64);\n    VecI64 (*unbox)(PyObject *);\n    VecI64 (*convert_from_nested)(VecNestedBufItem);\n    VecI64 (*append)(VecI64, int64_t);\n    VecI64PopResult (*pop)(VecI64, Py_ssize_t);\n    VecI64 (*remove)(VecI64, int64_t);\n    // TODO: Py_ssize_t\n    VecI64 (*slice)(VecI64, int64_t, int64_t);\n    // PyObject *(*extend)(PyObject *, PyObject *);\n    // PyObject *(*concat)(PyObject *, PyObject *);\n    // bool (*contains)(PyObject *, int64_t);\n    // iter?\n} VecI64API;\n\n// vec[i32] operations + type objects (stored in a capsule)\ntypedef struct _VecI32API {\n    PyTypeObject *boxed_type;\n    PyTypeObject *buf_type;\n    VecI32 (*alloc)(Py_ssize_t, Py_ssize_t);\n    PyObject *(*box)(VecI32);\n    VecI32 (*unbox)(PyObject *);\n    VecI32 (*convert_from_nested)(VecNestedBufItem);\n    VecI32 (*append)(VecI32, int32_t);\n    VecI32PopResult (*pop)(VecI32, Py_ssize_t);\n    VecI32 (*remove)(VecI32, int32_t);\n    // TODO: Py_ssize_t\n    VecI32 (*slice)(VecI32, int64_t, int64_t);\n    // PyObject *(*extend)(PyObject *, PyObject *);\n    // PyObject *(*concat)(PyObject *, PyObject *);\n    // bool (*contains)(PyObject *, int32_t);\n    // iter?\n} VecI32API;\n\n// vec[i16] operations + type objects (stored in a capsule)\ntypedef struct _VecI16API {\n    PyTypeObject *boxed_type;\n    PyTypeObject *buf_type;\n    VecI16 (*alloc)(Py_ssize_t, Py_ssize_t);\n    PyObject *(*box)(VecI16);\n    VecI16 (*unbox)(PyObject *);\n    VecI16 (*convert_from_nested)(VecNestedBufItem);\n    VecI16 (*append)(VecI16, int16_t);\n    VecI16PopResult (*pop)(VecI16, Py_ssize_t);\n    VecI16 (*remove)(VecI16, int16_t);\n    // TODO: Py_ssize_t\n    VecI16 (*slice)(VecI16, int64_t, int64_t);\n    // PyObject *(*extend)(PyObject *, PyObject *);\n    // PyObject *(*concat)(PyObject *, PyObject *);\n    // bool (*contains)(PyObject *, int16_t);\n    // iter?\n} VecI16API;\n\n// vec[u8] operations + type objects (stored in a capsule)\ntypedef struct _VecU8API {\n    PyTypeObject *boxed_type;\n    PyTypeObject *buf_type;\n    VecU8 (*alloc)(Py_ssize_t, Py_ssize_t);\n    PyObject *(*box)(VecU8);\n    VecU8 (*unbox)(PyObject *);\n    VecU8 (*convert_from_nested)(VecNestedBufItem);\n    VecU8 (*append)(VecU8, uint8_t);\n    VecU8PopResult (*pop)(VecU8, Py_ssize_t);\n    VecU8 (*remove)(VecU8, uint8_t);\n    // TODO: Py_ssize_t\n    VecU8 (*slice)(VecU8, int64_t, int64_t);\n    // PyObject *(*extend)(PyObject *, PyObject *);\n    // PyObject *(*concat)(PyObject *, PyObject *);\n    // bool (*contains)(PyObject *, uint8_t);\n    // iter?\n} VecU8API;\n\n// vec[float] operations + type objects (stored in a capsule)\ntypedef struct _VecFloatAPI {\n    PyTypeObject *boxed_type;\n    PyTypeObject *buf_type;\n    VecFloat (*alloc)(Py_ssize_t, Py_ssize_t);\n    PyObject *(*box)(VecFloat);\n    VecFloat (*unbox)(PyObject *);\n    VecFloat (*convert_from_nested)(VecNestedBufItem);\n    VecFloat (*append)(VecFloat, double);\n    VecFloatPopResult (*pop)(VecFloat, Py_ssize_t);\n    VecFloat (*remove)(VecFloat, double);\n    // TODO: Py_ssize_t\n    VecFloat (*slice)(VecFloat, int64_t, int64_t);\n    // PyObject *(*extend)(PyObject *, PyObject *);\n    // PyObject *(*concat)(PyObject *, PyObject *);\n    // bool (*contains)(PyObject *, double);\n    // iter?\n} VecFloatAPI;\n\n// vec[bool] operations + type objects (stored in a capsule)\ntypedef struct _VecBoolAPI {\n    PyTypeObject *boxed_type;\n    PyTypeObject *buf_type;\n    VecBool (*alloc)(Py_ssize_t, Py_ssize_t);\n    PyObject *(*box)(VecBool);\n    VecBool (*unbox)(PyObject *);\n    VecBool (*convert_from_nested)(VecNestedBufItem);\n    VecBool (*append)(VecBool, char);\n    VecBoolPopResult (*pop)(VecBool, Py_ssize_t);\n    VecBool (*remove)(VecBool, char);\n    // TODO: Py_ssize_t\n    VecBool (*slice)(VecBool, int64_t, int64_t);\n    // PyObject *(*extend)(PyObject *, PyObject *);\n    // PyObject *(*concat)(PyObject *, PyObject *);\n    // bool (*contains)(PyObject *, char);\n    // iter?\n} VecBoolAPI;\n\n#ifndef MYPYC_DECLARED_tuple_T2VOO\n#define MYPYC_DECLARED_tuple_T2VOO\ntypedef struct tuple_T2VOO {\n    VecT f0;\n    PyObject *f1;\n} tuple_T2VOO;\nstatic tuple_T2VOO tuple_undefined_T2VOO = { { -1, NULL } , NULL };\n#endif\n\ntypedef tuple_T2VOO VecTPopResult;\n\n// vec[T] operations + type objects (stored in a capsule)\n//\n// T is a class type or class type | None\ntypedef struct _VecTAPI {\n    PyTypeObject *boxed_type;\n    PyTypeObject *buf_type;\n    VecT (*alloc)(Py_ssize_t, Py_ssize_t, size_t);\n    PyObject *(*box)(VecT, size_t);\n    VecT (*unbox)(PyObject *, size_t);\n    VecT (*convert_from_nested)(VecNestedBufItem);\n    VecT (*append)(VecT, PyObject *, size_t);\n    VecTPopResult (*pop)(VecT, Py_ssize_t);\n    VecT (*remove)(VecT, PyObject *);\n    // TODO: Py_ssize_t\n    VecT (*slice)(VecT, int64_t, int64_t);\n    // PyObject *(*extend)(PyObject *, PyObject *);\n    // PyObject *(*concat)(PyObject *, PyObject *);\n    // bool (*contains)(PyObject *, PyObject *);\n    // iter?\n} VecTAPI;\n\n\n#ifndef MYPYC_DECLARED_tuple_T2VvVi\n#define MYPYC_DECLARED_tuple_T2VvVi\ntypedef struct tuple_T2VvVi {\n    VecNested f0;\n    VecNestedBufItem f1;\n} tuple_T2VvVi;\nstatic tuple_T2VvVi tuple_undefined_T2VvVi = { { -1, NULL } , { -1, NULL } };\n#endif\n\ntypedef tuple_T2VvVi VecNestedPopResult;\n\n// Nested vec operations + type objects (stored in a capsule)\ntypedef struct _VecNestedAPI {\n    PyTypeObject *boxed_type;\n    PyTypeObject *buf_type;\n    VecNested (*alloc)(Py_ssize_t, Py_ssize_t, size_t, size_t depth);\n    PyObject *(*box)(VecNested);\n    VecNested (*unbox)(PyObject *, size_t, size_t depth);\n    VecNested (*convert_from_nested)(VecNestedBufItem);\n    VecNested (*append)(VecNested, VecNestedBufItem);\n    VecNestedPopResult (*pop)(VecNested, Py_ssize_t);\n    VecNested (*remove)(VecNested, VecNestedBufItem);\n    // TODO: Py_ssize_t\n    VecNested (*slice)(VecNested, int64_t, int64_t);\n    // PyObject *(*extend)(PyObject *, PyObject *);\n    // PyObject *(*concat)(PyObject *, PyObject *);\n    // bool (*contains)(PyObject *, PyObject *);\n    // iter?\n} VecNestedAPI;\n\ntypedef struct {\n    VecTAPI *t;\n    VecNestedAPI *nested;\n    VecI64API *i64;\n    VecI32API *i32;\n    VecI16API *i16;\n    VecU8API *u8;\n    VecFloatAPI *float_;\n    VecBoolAPI *bool_;\n    PyTypeObject *(*get_vec_type)(void);  // Function to get base VecType for isinstance checks\n} VecCapsule;\n\n#define VEC_BUF_SIZE(b) ((b)->ob_base.ob_size)\n#define VEC_ITEM_TYPE(t) ((PyTypeObject *)((t) & ~1))\n#define VEC_BUF_ITEM_TYPE(b) VEC_ITEM_TYPE((b)->item_type)\n#define VEC_CAP(v) ((v).buf->ob_base.ob_size)\n#define VEC_IS_ERROR(v) ((v).len < 0)\n#define VEC_DECREF(v) Py_XDECREF((v).buf)\n#define VEC_INCREF(v) Py_XINCREF((v).buf)\n\n// Type objects\n\n// Buffer type objects that store vec items\nextern PyTypeObject VecI64BufType;\nextern PyTypeObject VecI32BufType;\nextern PyTypeObject VecI16BufType;\nextern PyTypeObject VecU8BufType;\nextern PyTypeObject VecFloatBufType;\nextern PyTypeObject VecBoolBufType;\nextern PyTypeObject VecTBufType;\nextern PyTypeObject VecNestedBufType;\n\n// Wrapper type objects for boxed vec values\nextern PyTypeObject VecI64Type;\nextern PyTypeObject VecI32Type;\nextern PyTypeObject VecI16Type;\nextern PyTypeObject VecU8Type;\nextern PyTypeObject VecFloatType;\nextern PyTypeObject VecBoolType;\nextern PyTypeObject VecTType;\nextern PyTypeObject VecNestedType;\n\n// Type objects corresponding to the 'i64', 'i32', 'i16, and 'u8' types\nextern PyTypeObject *LibRTVecs_I64TypeObj;\nextern PyTypeObject *LibRTVecs_I32TypeObj;\nextern PyTypeObject *LibRTVecs_I16TypeObj;\nextern PyTypeObject *LibRTVecs_U8TypeObj;\n\nextern VecI64API Vec_I64API;\nextern VecI32API Vec_I32API;\nextern VecI16API Vec_I16API;\nextern VecU8API Vec_U8API;\nextern VecFloatAPI Vec_FloatAPI;\nextern VecBoolAPI Vec_BoolAPI;\nextern VecTAPI Vec_TAPI;\nextern VecNestedAPI Vec_NestedAPI;\n\nstatic inline int Vec_CheckFloatError(PyObject *o) {\n    if (PyFloat_Check(o)) {\n        PyErr_SetString(PyExc_TypeError, \"integer argument expected, got float\");\n        return 1;\n    }\n    return 0;\n}\n\n// vec[i64] operations\n\nstatic inline int VecI64_Check(PyObject *o) {\n    return o->ob_type == &VecI64Type;\n}\n\nstatic inline PyObject *VecI64_BoxItem(int64_t x) {\n    return PyLong_FromLongLong(x);\n}\n\nstatic inline int64_t VecI64_UnboxItem(PyObject *o) {\n    if (Vec_CheckFloatError(o))\n        return -1;\n    return PyLong_AsLongLong(o);\n}\n\nstatic inline int VecI64_IsUnboxError(int64_t x) {\n    return x == -1 && PyErr_Occurred();\n}\n\nPyObject *VecI64_Box(VecI64);\nVecI64 VecI64_Append(VecI64, int64_t x);\nVecI64 VecI64_Remove(VecI64, int64_t x);\nVecI64PopResult VecI64_Pop(VecI64 v, Py_ssize_t index);\n\n// vec[i32] operations\n\nstatic inline int VecI32_Check(PyObject *o) {\n    return o->ob_type == &VecI32Type;\n}\n\nstatic inline PyObject *VecI32_BoxItem(int32_t x) {\n    return PyLong_FromLongLong(x);\n}\n\nstatic inline int32_t VecI32_UnboxItem(PyObject *o) {\n    if (Vec_CheckFloatError(o))\n        return -1;\n    long x = PyLong_AsLong(o);\n    if (x > INT32_MAX || x < INT32_MIN) {\n        PyErr_SetString(PyExc_OverflowError, \"Python int too large to convert to i32\");\n        return -1;\n    }\n    return x;\n}\n\nstatic inline int VecI32_IsUnboxError(int32_t x) {\n    return x == -1 && PyErr_Occurred();\n}\n\nPyObject *VecI32_Box(VecI32);\nVecI32 VecI32_Append(VecI32, int32_t x);\nVecI32 VecI32_Remove(VecI32, int32_t x);\nVecI32PopResult VecI32_Pop(VecI32 v, Py_ssize_t index);\n\n// vec[i16] operations\n\nstatic inline int VecI16_Check(PyObject *o) {\n    return o->ob_type == &VecI16Type;\n}\n\nstatic inline PyObject *VecI16_BoxItem(int16_t x) {\n    return PyLong_FromLongLong(x);\n}\n\nstatic inline int16_t VecI16_UnboxItem(PyObject *o) {\n    if (Vec_CheckFloatError(o))\n        return -1;\n    long x = PyLong_AsLong(o);\n    if (x >= 32768 || x < -32768) {\n        PyErr_SetString(PyExc_OverflowError, \"Python int too large to convert to i16\");\n        return -1;\n    }\n    return x;\n}\n\nstatic inline int VecI16_IsUnboxError(int16_t x) {\n    return x == -1 && PyErr_Occurred();\n}\n\nPyObject *VecI16_Box(VecI16);\nVecI16 VecI16_Append(VecI16, int16_t x);\nVecI16 VecI16_Remove(VecI16, int16_t x);\nVecI16PopResult VecI16_Pop(VecI16 v, Py_ssize_t index);\n\n// vec[u8] operations\n\nstatic inline int VecU8_Check(PyObject *o) {\n    return o->ob_type == &VecU8Type;\n}\n\nstatic inline PyObject *VecU8_BoxItem(uint8_t x) {\n    return PyLong_FromUnsignedLong(x);\n}\n\nstatic inline uint8_t VecU8_UnboxItem(PyObject *o) {\n    if (Vec_CheckFloatError(o))\n        return -1;\n    unsigned long x = PyLong_AsUnsignedLong(o);\n    if (x <= 255)\n        return x;\n    else if (x == (unsigned long)-1)\n        return 239;\n    else {\n        PyErr_SetString(PyExc_OverflowError, \"Python int too large to convert to u8\");\n        return 239;\n    }\n}\n\nstatic inline int VecU8_IsUnboxError(uint8_t x) {\n    return x == 239 && PyErr_Occurred();\n}\n\nPyObject *VecU8_Box(VecU8);\nVecU8 VecU8_Append(VecU8, uint8_t x);\nVecU8 VecU8_Remove(VecU8, uint8_t x);\nVecU8PopResult VecU8_Pop(VecU8 v, Py_ssize_t index);\n\n// vec[float] operations\n\nstatic inline int VecFloat_Check(PyObject *o) {\n    return o->ob_type == &VecFloatType;\n}\n\nstatic inline PyObject *VecFloat_BoxItem(double x) {\n    return PyFloat_FromDouble(x);\n}\n\nstatic inline double VecFloat_UnboxItem(PyObject *o) {\n    return PyFloat_AsDouble(o);\n}\n\nstatic inline int VecFloat_IsUnboxError(double x) {\n    return x == -1.0 && PyErr_Occurred();\n}\n\nPyObject *VecFloat_Box(VecFloat);\nVecFloat VecFloat_Append(VecFloat, double x);\nVecFloat VecFloat_Remove(VecFloat, double x);\nVecFloatPopResult VecFloat_Pop(VecFloat v, Py_ssize_t index);\n\n// vec[bool] operations\n\nstatic inline int VecBool_Check(PyObject *o) {\n    return o->ob_type == &VecBoolType;\n}\n\nstatic inline PyObject *VecBool_BoxItem(char x) {\n    if (x == 1) {\n        Py_INCREF(Py_True);\n        return Py_True;\n    } else {\n        Py_INCREF(Py_False);\n        return Py_False;\n    }\n}\n\nstatic inline char VecBool_UnboxItem(PyObject *o) {\n    if (o == Py_False) {\n        return 0;\n    } else if (o == Py_True) {\n        return 1;\n    } else {\n        PyErr_SetString(PyExc_TypeError, \"bool value expected\");\n        return 2;\n    }\n}\n\nstatic inline int VecBool_IsUnboxError(char x) {\n    return x == 2;\n}\n\nPyObject *VecBool_Box(VecBool);\nVecBool VecBool_Append(VecBool, char x);\nVecBool VecBool_Remove(VecBool, char x);\nVecBoolPopResult VecBool_Pop(VecBool v, Py_ssize_t index);\n\n// vec[t] operations\n\nstatic inline int VecT_Check(PyObject *o) {\n    return o->ob_type == &VecTType;\n}\n\nstatic inline int VecT_ItemCheck(VecT v, PyObject *item, size_t item_type) {\n    if (PyObject_TypeCheck(item, VEC_ITEM_TYPE(item_type))) {\n        return 1;\n    } else if ((item_type & 1) && item == Py_None) {\n        return 1;\n    } else {\n        // TODO: better error message\n        PyErr_SetString(PyExc_TypeError, \"invalid item type\");\n        return 0;\n    }\n}\n\nVecT VecT_New(Py_ssize_t size, Py_ssize_t cap, size_t item_type);\nPyObject *VecT_FromIterable(size_t item_type, PyObject *iterable);\nPyObject *VecT_Box(VecT vec, size_t item_type);\nVecT VecT_Append(VecT vec, PyObject *x, size_t item_type);\nVecT VecT_Remove(VecT vec, PyObject *x);\nVecTPopResult VecT_Pop(VecT v, Py_ssize_t index);\n\n// Nested vec operations\n\nstatic inline int VecNested_Check(PyObject *o) {\n    return o->ob_type == &VecNestedType;\n}\n\nVecNested VecNested_New(Py_ssize_t size, Py_ssize_t cap, size_t item_type, size_t depth);\nPyObject *VecNested_FromIterable(size_t item_type, size_t depth, PyObject *iterable);\nPyObject *VecNested_Box(VecNested);\nVecNested VecNested_Append(VecNested vec, VecNestedBufItem x);\nVecNested VecNested_Remove(VecNested vec, VecNestedBufItem x);\nVecNestedPopResult VecNested_Pop(VecNested v, Py_ssize_t index);\n\n// Return 0 on success, -1 on error. Store unboxed item in *unboxed if successful.\n// Return a *borrowed* reference.\nstatic inline int VecNested_UnboxItem(VecNested v, PyObject *item, VecNestedBufItem *unboxed) {\n    size_t depth = v.buf->depth;\n    if (depth == 1) {\n        if (item->ob_type == &VecTType) {\n            VecNestedObject *o = (VecNestedObject *)item;\n            if (o->vec.buf->item_type == v.buf->item_type) {\n                unboxed->len = o->vec.len;\n                unboxed->buf = (PyObject *)o->vec.buf;\n                return 0;\n            }\n        } else if (item->ob_type == &VecI64Type && v.buf->item_type == VEC_ITEM_TYPE_I64) {\n            VecI64Object *o = (VecI64Object *)item;\n            unboxed->len = o->vec.len;\n            unboxed->buf = (PyObject *)o->vec.buf;\n            return 0;\n        } else if (item->ob_type == &VecU8Type && v.buf->item_type == VEC_ITEM_TYPE_U8) {\n            VecU8Object *o = (VecU8Object *)item;\n            unboxed->len = o->vec.len;\n            unboxed->buf = (PyObject *)o->vec.buf;\n            return 0;\n        } else if (item->ob_type == &VecFloatType && v.buf->item_type == VEC_ITEM_TYPE_FLOAT) {\n            VecFloatObject *o = (VecFloatObject *)item;\n            unboxed->len = o->vec.len;\n            unboxed->buf = (PyObject *)o->vec.buf;\n            return 0;\n        } else if (item->ob_type == &VecI32Type && v.buf->item_type == VEC_ITEM_TYPE_I32) {\n            VecI32Object *o = (VecI32Object *)item;\n            unboxed->len = o->vec.len;\n            unboxed->buf = (PyObject *)o->vec.buf;\n            return 0;\n        } else if (item->ob_type == &VecI16Type && v.buf->item_type == VEC_ITEM_TYPE_I16) {\n            VecI16Object *o = (VecI16Object *)item;\n            unboxed->len = o->vec.len;\n            unboxed->buf = (PyObject *)o->vec.buf;\n            return 0;\n        } else if (item->ob_type == &VecBoolType && v.buf->item_type == VEC_ITEM_TYPE_BOOL) {\n            VecBoolObject *o = (VecBoolObject *)item;\n            unboxed->len = o->vec.len;\n            unboxed->buf = (PyObject *)o->vec.buf;\n            return 0;\n        }\n    } else if (item->ob_type == &VecNestedType) {\n        VecNestedObject *o = (VecNestedObject *)item;\n        if (o->vec.buf->depth == v.buf->depth - 1\n            && o->vec.buf->item_type == v.buf->item_type) {\n            unboxed->len = o->vec.len;\n            unboxed->buf = (PyObject *)o->vec.buf;\n            return 0;\n        }\n    }\n    // TODO: better error message\n    PyErr_SetString(PyExc_TypeError, \"invalid item type\");\n    return -1;\n}\n\nstatic inline PyObject *VecNested_BoxItem(VecNested v, VecNestedBufItem item) {\n    if (item.len < 0)\n        Py_RETURN_NONE;\n    Py_XINCREF(item.buf);\n    if (v.buf->depth > 1) {\n        // Item is a nested vec\n        VecNested v = { .len = item.len, .buf = (VecNestedBufObject *)item.buf };\n        return VecNested_Box(v);\n    } else {\n        // Item is a non-nested vec\n        size_t item_type = v.buf->item_type;\n        if (item_type == VEC_ITEM_TYPE_I64) {\n            VecI64 v = { .len = item.len, .buf = (VecI64BufObject *)item.buf };\n            return VecI64_Box(v);\n        } else if (item_type == VEC_ITEM_TYPE_U8) {\n            VecU8 v = { .len = item.len, .buf = (VecU8BufObject *)item.buf };\n            return VecU8_Box(v);\n        } else if (item_type == VEC_ITEM_TYPE_FLOAT) {\n            VecFloat v = { .len = item.len, .buf = (VecFloatBufObject *)item.buf };\n            return VecFloat_Box(v);\n        } else if (item_type == VEC_ITEM_TYPE_I32) {\n            VecI32 v = { .len = item.len, .buf = (VecI32BufObject *)item.buf };\n            return VecI32_Box(v);\n        } else if (item_type == VEC_ITEM_TYPE_I16) {\n            VecI16 v = { .len = item.len, .buf = (VecI16BufObject *)item.buf };\n            return VecI16_Box(v);\n        } else if (item_type == VEC_ITEM_TYPE_BOOL) {\n            VecBool v = { .len = item.len, .buf = (VecBoolBufObject *)item.buf };\n            return VecBool_Box(v);\n        } else {\n            // Generic vec[t]\n            VecT v = { .len = item.len, .buf = (VecTBufObject *)item.buf };\n            return VecT_Box(v, item_type);\n        }\n    }\n}\n\n// Misc helpers\n\nPyObject *Vec_TypeToStr(size_t item_type, size_t depth);\nPyObject *Vec_GenericRepr(PyObject *vec, size_t item_type, size_t depth, int verbose);\nPyObject *Vec_GenericRichcompare(Py_ssize_t *len, PyObject **items,\n                                  Py_ssize_t *other_len, PyObject **other_items,\n                                  int op);\nint Vec_GenericRemove(Py_ssize_t *len, PyObject **items, PyObject *item);\nPyObject *Vec_GenericPopWrapper(Py_ssize_t *len, PyObject **items, PyObject *args);\nPyObject *Vec_GenericPop(Py_ssize_t *len, PyObject **items, Py_ssize_t index);\n\n// Global API pointers initialized by import_librt_vecs()\nstatic VecCapsule *VecApi;\nstatic VecI64API VecI64Api;\nstatic VecI32API VecI32Api;\nstatic VecI16API VecI16Api;\nstatic VecU8API VecU8Api;\nstatic VecFloatAPI VecFloatApi;\nstatic VecBoolAPI VecBoolApi;\nstatic VecTAPI VecTApi;\nstatic VecNestedAPI VecNestedApi;\n\nstatic int\nimport_librt_vecs(void)\n{\n    PyObject *mod = PyImport_ImportModule(\"librt.vecs\");\n    if (mod == NULL)\n        return -1;\n    Py_DECREF(mod);  // we import just for the side effect of making the below work.\n    VecApi = PyCapsule_Import(\"librt.vecs._C_API\", 0);\n    if (!VecApi)\n        return -1;\n    VecI64Api = *VecApi->i64;\n    VecI32Api = *VecApi->i32;\n    VecI16Api = *VecApi->i16;\n    VecU8Api = *VecApi->u8;\n    VecFloatApi = *VecApi->float_;\n    VecBoolApi = *VecApi->bool_;\n    VecTApi = *VecApi->t;\n    VecNestedApi = *VecApi->nested;\n    return 0;\n}\n\n#endif  // MYPYC_EXPERIMENTAL\n\n#endif  // VEC_H_INCL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/vec_bool.c",
    "content": "#ifdef MYPYC_EXPERIMENTAL\n#define VEC VecBool\n#define VEC_TYPE VecBoolType\n#define VEC_OBJECT VecBoolObject\n#define BUF_OBJECT VecBoolBufObject\n#define BUF_TYPE VecBoolBufType\n#define NAME(suffix) VecBool##suffix\n#define FUNC(suffix) VecBool_##suffix\n#define ITEM_TYPE_STR \"bool\"\n#define ITEM_TYPE_MAGIC VEC_ITEM_TYPE_BOOL\n#define ITEM_C_TYPE char\n#define FEATURES Vec_BoolAPI\n\n#define BOX_ITEM VecBool_BoxItem\n#define UNBOX_ITEM VecBool_UnboxItem\n#define IS_UNBOX_ERROR VecBool_IsUnboxError\n\n#include \"vec_template.c\"\n\n#endif  // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/vec_float.c",
    "content": "#ifdef MYPYC_EXPERIMENTAL\n#define VEC VecFloat\n#define VEC_TYPE VecFloatType\n#define VEC_OBJECT VecFloatObject\n#define BUF_OBJECT VecFloatBufObject\n#define BUF_TYPE VecFloatBufType\n#define NAME(suffix) VecFloat##suffix\n#define FUNC(suffix) VecFloat_##suffix\n#define ITEM_TYPE_STR \"float\"\n#define ITEM_TYPE_MAGIC VEC_ITEM_TYPE_FLOAT\n#define ITEM_C_TYPE double\n#define FEATURES Vec_FloatAPI\n\n#define BOX_ITEM VecFloat_BoxItem\n#define UNBOX_ITEM VecFloat_UnboxItem\n#define IS_UNBOX_ERROR VecFloat_IsUnboxError\n\n#include \"vec_template.c\"\n\n#endif  // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/vec_i16.c",
    "content": "#ifdef MYPYC_EXPERIMENTAL\n#define VEC VecI16\n#define VEC_TYPE VecI16Type\n#define VEC_OBJECT VecI16Object\n#define BUF_OBJECT VecI16BufObject\n#define BUF_TYPE VecI16BufType\n#define NAME(suffix) VecI16##suffix\n#define FUNC(suffix) VecI16_##suffix\n#define ITEM_TYPE_STR \"i16\"\n#define ITEM_TYPE_MAGIC VEC_ITEM_TYPE_I16\n#define ITEM_C_TYPE int16_t\n#define FEATURES Vec_I16API\n\n#define BOX_ITEM VecI16_BoxItem\n#define UNBOX_ITEM VecI16_UnboxItem\n#define IS_UNBOX_ERROR VecI16_IsUnboxError\n\n#include \"vec_template.c\"\n\n#endif  // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/vec_i32.c",
    "content": "#ifdef MYPYC_EXPERIMENTAL\n#define VEC VecI32\n#define VEC_TYPE VecI32Type\n#define VEC_OBJECT VecI32Object\n#define BUF_OBJECT VecI32BufObject\n#define BUF_TYPE VecI32BufType\n#define NAME(suffix) VecI32##suffix\n#define FUNC(suffix) VecI32_##suffix\n#define ITEM_TYPE_STR \"i32\"\n#define ITEM_TYPE_MAGIC VEC_ITEM_TYPE_I32\n#define ITEM_C_TYPE int32_t\n#define FEATURES Vec_I32API\n\n#define BOX_ITEM VecI32_BoxItem\n#define UNBOX_ITEM VecI32_UnboxItem\n#define IS_UNBOX_ERROR VecI32_IsUnboxError\n\n#include \"vec_template.c\"\n\n#endif  // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/vec_i64.c",
    "content": "#ifdef MYPYC_EXPERIMENTAL\n#define VEC VecI64\n#define VEC_TYPE VecI64Type\n#define VEC_OBJECT VecI64Object\n#define BUF_OBJECT VecI64BufObject\n#define BUF_TYPE VecI64BufType\n#define NAME(suffix) VecI64##suffix\n#define FUNC(suffix) VecI64_##suffix\n#define ITEM_TYPE_STR \"i64\"\n#define ITEM_TYPE_MAGIC VEC_ITEM_TYPE_I64\n#define ITEM_C_TYPE int64_t\n#define FEATURES Vec_I64API\n\n#define BOX_ITEM VecI64_BoxItem\n#define UNBOX_ITEM VecI64_UnboxItem\n#define IS_UNBOX_ERROR VecI64_IsUnboxError\n\n#include \"vec_template.c\"\n\n#endif  // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/vec_nested.c",
    "content": "#ifdef MYPYC_EXPERIMENTAL\n// Implementation of nested vec[t], when t is a vec type.\n//\n// Examples of types supported:\n//  - vec[vec[i64]]\n//  - vec[vec[vec[str]]]\n//  - vec[vec[str | None]]\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include \"librt_vecs.h\"\n#include \"vecs_internal.h\"\n\nstatic inline VecNested vec_error() {\n    VecNested v = { .len = -1 };\n    return v;\n}\n\nstatic inline PyObject *box_vec_item_by_index(VecNested v, Py_ssize_t index) {\n    return VecNested_BoxItem(v, v.buf->items[index]);\n}\n\n// Alloc a partially initialized vec. Caller *must* initialize len and buf->items of the\n// return value.\nstatic VecNested vec_alloc(Py_ssize_t size, size_t item_type, size_t depth) {\n    VecNestedBufObject *buf = PyObject_GC_NewVar(VecNestedBufObject, &VecNestedBufType, size);\n    if (buf == NULL)\n        return vec_error();\n    buf->item_type = item_type;\n    buf->depth = depth;\n    if (!Vec_IsMagicItemType(item_type))\n        Py_INCREF(VEC_BUF_ITEM_TYPE(buf));\n    VecNested res = { .buf = buf };\n    PyObject_GC_Track(buf);\n    return res;\n}\n\n// Box a nested vec value, stealing 'vec'. On error, decref 'vec'.\nPyObject *VecNested_Box(VecNested vec) {\n    VecNestedObject *obj = PyObject_GC_New(VecNestedObject, &VecNestedType);\n    if (obj == NULL) {\n        VEC_DECREF(vec);\n        return NULL;\n    }\n    obj->vec = vec;\n    PyObject_GC_Track(obj);\n    return (PyObject *)obj;\n}\n\nVecNested VecNested_Unbox(PyObject *obj, size_t item_type, size_t depth) {\n    if (obj->ob_type == &VecNestedType) {\n        VecNested result = ((VecNestedObject *)obj)->vec;\n        if (result.buf->item_type == item_type && result.buf->depth == depth) {\n            VEC_INCREF(result);  // TODO: Should we borrow instead?\n            return result;\n        }\n    }\n    // TODO: Better error message, with name of type\n    PyErr_SetString(PyExc_TypeError, \"vec[t] expected\");\n    return vec_error();\n}\n\nVecNested VecNested_ConvertFromNested(VecNestedBufItem item) {\n    return (VecNested) { item.len, (VecNestedBufObject *)item.buf };\n}\n\nVecNested VecNested_New(Py_ssize_t size, Py_ssize_t cap, size_t item_type, size_t depth) {\n    if (cap < size)\n        cap = size;\n    VecNested vec = vec_alloc(cap, item_type, depth);\n    if (VEC_IS_ERROR(vec))\n        return vec;\n    for (Py_ssize_t i = 0; i < cap; i++) {\n        vec.buf->items[i].len = -1;\n        vec.buf->items[i].buf = NULL;\n    }\n    vec.len = size;\n    return vec;\n}\n\nstatic PyObject *vec_repr(PyObject *self) {\n    VecNested v = ((VecNestedObject *)self)->vec;\n    return Vec_GenericRepr(self, v.buf->item_type, v.buf->depth, 1);\n}\n\nstatic PyObject *vec_get_item(PyObject *o, Py_ssize_t i) {\n    VecNested v = ((VecNestedObject *)o)->vec;\n    if ((size_t)i < (size_t)v.len) {\n        return box_vec_item_by_index(v, i);\n    } else if ((size_t)i + (size_t)v.len < (size_t)v.len) {\n        return box_vec_item_by_index(v, i + v.len);\n    } else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        return NULL;\n    }\n}\n\nVecNested VecNested_Slice(VecNested vec, int64_t start, int64_t end) {\n    if (start < 0)\n        start += vec.len;\n    if (end < 0)\n        end += vec.len;\n    if (start < 0)\n        start = 0;\n    if (start >= vec.len)\n        start = vec.len;\n    if (end < start)\n        end = start;\n    if (end > vec.len)\n        end = vec.len;\n    int64_t slicelength = end - start;\n    VecNested res = vec_alloc(slicelength, vec.buf->item_type, vec.buf->depth);\n    if (VEC_IS_ERROR(res))\n        return res;\n    res.len = slicelength;\n    for (Py_ssize_t i = 0; i < slicelength; i++) {\n        VecNestedBufItem item = vec.buf->items[start + i];\n        Py_XINCREF(item.buf);\n        res.buf->items[i] = item;\n    }\n    return res;\n}\n\nstatic PyObject *vec_subscript(PyObject *self, PyObject *item) {\n    VecNested vec = ((VecNestedObject *)self)->vec;\n    if (PyIndex_Check(item)) {\n        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);\n        if (i == -1 && PyErr_Occurred())\n            return NULL;\n        if ((size_t)i < (size_t)vec.len) {\n            return box_vec_item_by_index(vec, i);\n        } else if ((size_t)i + (size_t)vec.len < (size_t)vec.len) {\n            return box_vec_item_by_index(vec, i + vec.len);\n        } else {\n            PyErr_SetString(PyExc_IndexError, \"index out of range\");\n            return NULL;\n        }\n    } else if (PySlice_Check(item)) {\n        Py_ssize_t start, stop, step;\n        if (PySlice_Unpack(item, &start, &stop, &step) < 0)\n            return NULL;\n        Py_ssize_t slicelength = PySlice_AdjustIndices(vec.len, &start, &stop, step);\n        VecNested res = vec_alloc(slicelength, vec.buf->item_type, vec.buf->depth);\n        if (VEC_IS_ERROR(res))\n            return NULL;\n        res.len = slicelength;\n        Py_ssize_t j = start;\n        for (Py_ssize_t i = 0; i < slicelength; i++) {\n            VecNestedBufItem item = vec.buf->items[j];\n            Py_INCREF(item.buf);\n            res.buf->items[i] = item;\n            j += step;\n        }\n        return VecNested_Box(res);\n    } else {\n        PyErr_Format(PyExc_TypeError, \"vec indices must be integers or slices, not %.100s\",\n                     item->ob_type->tp_name);\n        return NULL;\n    }\n}\n\nstatic int vec_ass_item(PyObject *self, Py_ssize_t i, PyObject *o) {\n    VecNested v = ((VecNestedObject *)self)->vec;\n    if ((size_t)i + (size_t)v.len < (size_t)v.len) {\n        i += v.len;\n    }\n    if ((size_t)i < (size_t)v.len) {\n        VecNestedBufItem item;\n        if (VecNested_UnboxItem(v, o, &item) < 0)\n            return -1;\n        VEC_INCREF(item);\n        VEC_DECREF(v.buf->items[i]);\n        v.buf->items[i] = item;\n        return 0;\n    } else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        return -1;\n    }\n}\n\nstatic PyObject *compare_vec_eq(VecNested x, VecNested y, int op) {\n    int cmp = 1;\n    PyObject *res;\n    if (x.len != y.len\n            || x.buf->item_type != y.buf->item_type\n            || x.buf->depth != y.buf->depth) {\n        cmp = 0;\n    } else {\n        for (Py_ssize_t i = 0; i < x.len; i++) {\n            PyObject *x_item = box_vec_item_by_index(x, i);\n            PyObject *y_item = box_vec_item_by_index(y, i);\n            int itemcmp = PyObject_RichCompareBool(x_item, y_item, Py_EQ);\n            Py_DECREF(x_item);\n            Py_DECREF(y_item);\n            if (itemcmp < 0)\n                return NULL;\n            if (!itemcmp) {\n                cmp = 0;\n                break;\n            }\n        }\n    }\n    if (op == Py_NE)\n        cmp = cmp ^ 1;\n    res = cmp ? Py_True : Py_False;\n    Py_INCREF(res);\n    return res;\n}\n\nPyObject *vec_richcompare(PyObject *self, PyObject *other, int op) {\n    PyObject *res;\n    if (op == Py_EQ || op == Py_NE) {\n        if (other->ob_type != &VecNestedType) {\n            res = op == Py_EQ ? Py_False : Py_True;\n        } else {\n            return compare_vec_eq(((VecNestedObject *)self)->vec,\n                                        ((VecNestedObject *)other)->vec, op);\n        }\n    } else\n        res = Py_NotImplemented;\n    Py_INCREF(res);\n    return res;\n}\n\n// Append item to 'vec', stealing 'vec'. Return 'vec' with item appended.\nVecNested VecNested_Append(VecNested vec, VecNestedBufItem x) {\n    Py_ssize_t cap = VEC_CAP(vec);\n    VEC_INCREF(x);\n    if (vec.len < cap) {\n        // Slot may have duplicate ref from prior remove/pop\n        Py_XDECREF(vec.buf->items[vec.len].buf);\n        vec.buf->items[vec.len] = x;\n        vec.len++;\n        return vec;\n    } else {\n        Py_ssize_t new_size = 2 * cap + 1;\n        // TODO: Avoid initializing to zero here\n        VecNested new = vec_alloc(new_size, vec.buf->item_type, vec.buf->depth);\n        if (VEC_IS_ERROR(new)) {\n            VEC_DECREF(x);\n            // The input vec is being consumed/stolen by this function, so on error\n            // we must decref it to avoid leaking the buffer.\n            VEC_DECREF(vec);\n            return new;\n        }\n        // Copy items to new vec.\n        memcpy(new.buf->items, vec.buf->items, sizeof(VecNestedBufItem) * vec.len);\n        // TODO: How to safely represent deleted items?\n        memset(new.buf->items + vec.len, 0, sizeof(VecNestedBufItem) * (new_size - vec.len));\n        // Clear the items in the old vec. We avoid reference count manipulation.\n        memset(vec.buf->items, 0, sizeof(VecNestedBufItem) * vec.len);\n        new.buf->items[vec.len] = x;\n        new.len = vec.len + 1;\n        VEC_DECREF(vec);\n        return new;\n    }\n}\n\n// Remove item from 'vec', stealing 'vec'. Return 'vec' with item removed.\nVecNested VecNested_Remove(VecNested self, VecNestedBufItem arg) {\n    VecNestedBufItem *items = self.buf->items;\n\n    PyObject *boxed_arg = VecNested_BoxItem(self, arg);\n    if (boxed_arg == NULL) {\n        // The input self is being consumed/stolen by this function, so on error\n        // we must decref it to avoid leaking the buffer.\n        VEC_DECREF(self);\n        return vec_error();\n    }\n\n    for (Py_ssize_t i = 0; i < self.len; i++) {\n        int match = 0;\n        if (items[i].len == arg.len && items[i].buf == arg.buf)\n            match = 1;\n        else {\n            PyObject *item = box_vec_item_by_index(self, i);\n            if (item == NULL) {\n                Py_DECREF(boxed_arg);\n                // The input self is being consumed/stolen by this function, so on error\n                // we must decref it to avoid leaking the buffer.\n                VEC_DECREF(self);\n                return vec_error();\n            }\n            int itemcmp = PyObject_RichCompareBool(item, boxed_arg, Py_EQ);\n            Py_DECREF(item);\n            if (itemcmp < 0) {\n                Py_DECREF(boxed_arg);\n                // The input self is being consumed/stolen by this function, so on error\n                // we must decref it to avoid leaking the buffer.\n                VEC_DECREF(self);\n                return vec_error();\n            }\n            match = itemcmp;\n        }\n        if (match) {\n            if (i < self.len - 1) {\n                Py_CLEAR(items[i].buf);\n                for (; i < self.len - 1; i++) {\n                    items[i] = items[i + 1];\n                }\n                Py_XINCREF(items[self.len - 1].buf);\n            }\n            self.len--;\n            Py_DECREF(boxed_arg);\n            // Return the stolen reference without INCREF\n            return self;\n        }\n    }\n    Py_DECREF(boxed_arg);\n    PyErr_SetString(PyExc_ValueError, \"vec.remove(x): x not in vec\");\n    // The input self is being consumed/stolen by this function, so on error\n    // we must decref it to avoid leaking the buffer.\n    VEC_DECREF(self);\n    return vec_error();\n}\n\n// Pop item from 'vec', stealing 'vec'. Return struct with modified 'vec' and the popped item.\nVecNestedPopResult VecNested_Pop(VecNested v, Py_ssize_t index) {\n    VecNestedPopResult result;\n\n    if (index < 0)\n        index += v.len;\n\n    if (index < 0 || index >= v.len) {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        // The input v is being consumed/stolen by this function, so on error\n        // we must decref it to avoid leaking the buffer.\n        VEC_DECREF(v);\n        result.f0 = vec_error();\n        result.f1.len = 0;\n        result.f1.buf = NULL;\n        return result;\n    }\n\n    VecNestedBufItem *items = v.buf->items;\n    result.f1 = items[index];\n    for (Py_ssize_t i = index; i < v.len - 1; i++)\n        items[i] = items[i + 1];\n    if (v.len > 0)\n        Py_XINCREF(items[v.len - 1].buf);\n    v.len--;\n    // Return the stolen reference without INCREF\n    result.f0 = v;\n    return result;\n}\n\nstatic int\nVecNested_traverse(VecNestedObject *self, visitproc visit, void *arg)\n{\n    Py_VISIT(self->vec.buf);\n    return 0;\n}\n\nstatic int\nVecNested_clear(VecNestedObject *self)\n{\n    Py_CLEAR(self->vec.buf);\n    return 0;\n}\n\nstatic void\nVecNested_dealloc(VecNestedObject *self)\n{\n    PyObject_GC_UnTrack(self);\n    Py_TRASHCAN_BEGIN(self, VecNested_dealloc)\n    Py_CLEAR(self->vec.buf);\n    Py_TYPE(self)->tp_free((PyObject *)self);\n    Py_TRASHCAN_END\n}\n\nstatic int\nVecNestedBuf_traverse(VecNestedBufObject *self, visitproc visit, void *arg)\n{\n    if (!Vec_IsMagicItemType(self->item_type))\n        Py_VISIT(VEC_BUF_ITEM_TYPE(self));\n    for (Py_ssize_t i = 0; i < VEC_BUF_SIZE(self); i++) {\n        Py_VISIT(self->items[i].buf);\n    }\n    return 0;\n}\n\nstatic inline int\nVecNestedBuf_clear(VecNestedBufObject *self)\n{\n    if (self->item_type && !Vec_IsMagicItemType(self->item_type)) {\n        Py_DECREF(VEC_BUF_ITEM_TYPE(self));\n        self->item_type = 0;\n    }\n    for (Py_ssize_t i = 0; i < VEC_BUF_SIZE(self); i++) {\n        Py_CLEAR(self->items[i].buf);\n    }\n    return 0;\n}\n\nstatic void\nVecNestedBuf_dealloc(VecNestedBufObject *self)\n{\n    PyObject_GC_UnTrack(self);\n    Py_TRASHCAN_BEGIN(self, VecNestedBuf_dealloc)\n    VecNestedBuf_clear(self);\n    Py_TYPE(self)->tp_free((PyObject *)self);\n    Py_TRASHCAN_END\n}\n\nstatic Py_ssize_t vec_ext_length(PyObject *o) {\n    return ((VecNestedObject *)o)->vec.len;\n}\n\nstatic PyMappingMethods VecNestedMapping = {\n    .mp_length = vec_ext_length,\n    .mp_subscript = vec_subscript,\n};\n\nstatic PySequenceMethods VecNestedSequence = {\n    .sq_item = vec_get_item,\n    .sq_ass_item = vec_ass_item,\n};\n\nstatic PyMethodDef vec_methods[] = {\n    {NULL, NULL, 0, NULL},  /* Sentinel */\n};\n\nPyTypeObject VecNestedBufType = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"vecbuf\",\n    .tp_doc = \"Internal data buffer used by vec objects\",\n    .tp_basicsize = sizeof(VecNestedBufObject) - sizeof(VecNestedBufItem),\n    .tp_itemsize = sizeof(VecNestedBufItem),\n    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,\n    .tp_traverse = (traverseproc)VecNestedBuf_traverse,\n    //.tp_new = vecbuf_i64_new, //??\n    .tp_free = PyObject_GC_Del,\n    .tp_clear = (inquiry)VecNestedBuf_clear,\n    .tp_dealloc = (destructor)VecNestedBuf_dealloc,\n};\n\nPyTypeObject VecNestedType = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"vec\",\n    .tp_doc = \"Mutable sequence-like container optimized for compilation with mypyc\",\n    .tp_basicsize = sizeof(VecNestedObject),\n    .tp_itemsize = 0,\n    .tp_base = &VecType,  // Inherit from base vec type for isinstance() support\n    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,\n    .tp_traverse = (traverseproc)VecNested_traverse,\n    .tp_clear = (inquiry)VecNested_clear,\n    .tp_dealloc = (destructor)VecNested_dealloc,\n    //.tp_free = PyObject_GC_Del,\n    .tp_repr = (reprfunc)vec_repr,\n    .tp_as_sequence = &VecNestedSequence,\n    .tp_as_mapping = &VecNestedMapping,\n    .tp_richcompare = vec_richcompare,\n    .tp_methods = vec_methods,\n    // TODO: free\n};\n\nPyObject *VecNested_FromIterable(size_t item_type, size_t depth, PyObject *iterable) {\n    VecNested v = vec_alloc(0, item_type, depth);\n    if (VEC_IS_ERROR(v))\n        return NULL;\n    v.len = 0;\n\n    PyObject *iter = PyObject_GetIter(iterable);\n    if (iter == NULL) {\n        VEC_DECREF(v);\n        return NULL;\n    }\n    PyObject *item;\n    while ((item = PyIter_Next(iter)) != NULL) {\n        VecNestedBufItem vecitem;\n        if (VecNested_UnboxItem(v, item, &vecitem) < 0) {\n            Py_DECREF(iter);\n            VEC_DECREF(v);\n            Py_DECREF(item);\n            return NULL;\n        }\n        v = VecNested_Append(v, vecitem);\n        Py_DECREF(item);\n        if (VEC_IS_ERROR(v)) {\n            Py_DECREF(iter);\n            VEC_DECREF(v);\n            return NULL;\n        }\n    }\n    Py_DECREF(iter);\n    if (PyErr_Occurred()) {\n        VEC_DECREF(v);\n        return NULL;\n    }\n    return VecNested_Box(v);\n}\n\nVecNestedAPI Vec_NestedAPI = {\n    &VecNestedType,\n    &VecNestedBufType,\n    VecNested_New,\n    VecNested_Box,\n    VecNested_Unbox,\n    VecNested_ConvertFromNested,\n    VecNested_Append,\n    VecNested_Pop,\n    VecNested_Remove,\n    VecNested_Slice,\n};\n\n#endif  // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/vec_t.c",
    "content": "#ifdef MYPYC_EXPERIMENTAL\n// Implementation of generic vec[t], when t is a plain type object (possibly optional).\n//\n// Examples of types supported:\n//\n//  - vec[str]\n//  - vec[str | None]\n//  - vec[object]\n//  - vec[UserClass]\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include \"librt_vecs.h\"\n#include \"vecs_internal.h\"\n\nstatic inline VecT vec_error() {\n    VecT v = { .len = -1 };\n    return v;\n}\n\nstatic inline VecTBufObject *alloc_buf(Py_ssize_t size, size_t item_type) {\n    VecTBufObject *buf = PyObject_GC_NewVar(VecTBufObject, &VecTBufType, size);\n    if (buf == NULL)\n        return NULL;\n    buf->item_type = item_type;\n    Py_INCREF(VEC_BUF_ITEM_TYPE(buf));\n    PyObject_GC_Track(buf);\n    return buf;\n}\n\n// Alloc a partially initialized vec. Caller *must* immediately initialize len, and buf->items\n// if size > 0.\nstatic VecT vec_alloc(Py_ssize_t size, size_t item_type) {\n    VecTBufObject *buf;\n\n    if (size == 0) {\n        buf = NULL;\n    } else {\n        buf = alloc_buf(size, item_type);\n        if (buf == NULL)\n            return vec_error();\n    }\n    return (VecT) { .buf = buf };\n}\n\n// Box a VecT value, stealing 'vec'. On failure, return NULL and decref 'vec'.\nPyObject *VecT_Box(VecT vec, size_t item_type) {\n    // An unboxed empty vec may have a NULL buf, but a boxed vec must have it\n    // allocated, since it contains the item type\n    if (vec.buf == NULL) {\n        vec.buf = alloc_buf(0, item_type);\n        if (vec.buf == NULL)\n            return NULL;\n    }\n    VecTObject *obj = PyObject_GC_New(VecTObject, &VecTType);\n    if (obj == NULL) {\n        // vec.buf is always defined, so no need for a NULL check\n        Py_DECREF(vec.buf);\n        return NULL;\n    }\n    obj->vec = vec;\n    PyObject_GC_Track(obj);\n    return (PyObject *)obj;\n}\n\nVecT VecT_Unbox(PyObject *obj, size_t item_type) {\n    if (obj->ob_type == &VecTType) {\n        VecT result = ((VecTObject *)obj)->vec;\n        if (result.buf->item_type == item_type) {\n            VEC_INCREF(result);  // TODO: Should we borrow instead?\n            return result;\n        }\n    }\n    // TODO: Better error message, with name of type\n    PyErr_SetString(PyExc_TypeError, \"vec[t] expected\");\n    return vec_error();\n}\n\nVecT VecT_ConvertFromNested(VecNestedBufItem item) {\n    return (VecT) { item.len, (VecTBufObject *)item.buf };\n}\n\nVecT VecT_New(Py_ssize_t size, Py_ssize_t cap, size_t item_type) {\n    if (cap < size)\n        cap = size;\n    VecT vec = vec_alloc(cap, item_type);\n    if (VEC_IS_ERROR(vec))\n        return vec;\n    for (Py_ssize_t i = 0; i < cap; i++) {\n        vec.buf->items[i] = NULL;\n    }\n    vec.len = size;\n    return vec;\n}\n\nstatic PyObject *vec_repr(PyObject *self) {\n    VecTObject *v = (VecTObject *)self;\n    return Vec_GenericRepr(self, v->vec.buf->item_type, 0, 1);\n}\n\nstatic PyObject *vec_get_item(PyObject *o, Py_ssize_t i) {\n    VecT v = ((VecTObject *)o)->vec;\n    if ((size_t)i < (size_t)v.len) {\n        PyObject *item = v.buf->items[i];\n        Py_INCREF(item);\n        return item;\n    } else if ((size_t)i + (size_t)v.len < (size_t)v.len) {\n        PyObject *item = v.buf->items[i + v.len];\n        Py_INCREF(item);\n        return item;\n    } else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        return NULL;\n    }\n}\n\nVecT VecT_Slice(VecT vec, int64_t start, int64_t end) {\n    if (start < 0)\n        start += vec.len;\n    if (end < 0)\n        end += vec.len;\n    if (start < 0)\n        start = 0;\n    if (start >= vec.len)\n        start = vec.len;\n    if (end < start)\n        end = start;\n    if (end > vec.len)\n        end = vec.len;\n    int64_t slicelength = end - start;\n    if (slicelength == 0)\n        return (VecT) { .len = 0, .buf = NULL };\n    VecT res = vec_alloc(slicelength, vec.buf->item_type);\n    if (VEC_IS_ERROR(res))\n        return res;\n    res.len = slicelength;\n    for (Py_ssize_t i = 0; i < slicelength; i++) {\n        PyObject *item = vec.buf->items[start + i];\n        Py_INCREF(item);\n        res.buf->items[i] = item;\n    }\n    return res;\n}\n\nstatic PyObject *vec_subscript(PyObject *self, PyObject *item) {\n    VecT vec = ((VecTObject *)self)->vec;\n    if (PyIndex_Check(item)) {\n        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);\n        if (i == -1 && PyErr_Occurred())\n            return NULL;\n        if ((size_t)i < (size_t)vec.len) {\n            PyObject *result = vec.buf->items[i];\n            Py_INCREF(result);\n            return result;\n        } else if ((size_t)i + (size_t)vec.len < (size_t)vec.len) {\n            PyObject *result = vec.buf->items[i + vec.len];\n            Py_INCREF(result);\n            return result;\n        } else {\n            PyErr_SetString(PyExc_IndexError, \"index out of range\");\n            return NULL;\n        }\n    } else if (PySlice_Check(item)) {\n        Py_ssize_t start, stop, step;\n        if (PySlice_Unpack(item, &start, &stop, &step) < 0)\n            return NULL;\n        Py_ssize_t slicelength = PySlice_AdjustIndices(vec.len, &start, &stop, step);\n        VecT res = vec_alloc(slicelength, vec.buf->item_type);\n        if (VEC_IS_ERROR(res))\n            return NULL;\n        res.len = slicelength;\n        Py_ssize_t j = start;\n        for (Py_ssize_t i = 0; i < slicelength; i++) {\n            PyObject *item = vec.buf->items[j];\n            Py_INCREF(item);\n            res.buf->items[i] = item;\n            j += step;\n        }\n        PyObject *result = VecT_Box(res, vec.buf->item_type);\n        if (result == NULL) {\n            VEC_DECREF(res);\n        }\n        return result;\n    } else {\n        PyErr_Format(PyExc_TypeError, \"vec indices must be integers or slices, not %.100s\",\n                     item->ob_type->tp_name);\n        return NULL;\n    }\n}\n\nstatic int vec_ass_item(PyObject *self, Py_ssize_t i, PyObject *o) {\n    VecT v = ((VecTObject *)self)->vec;\n    if (!VecT_ItemCheck(v, o, v.buf->item_type))\n        return -1;\n    if ((size_t)i < (size_t)v.len) {\n        PyObject *old = v.buf->items[i];\n        Py_INCREF(o);\n        v.buf->items[i] = o;\n        Py_XDECREF(old);\n        return 0;\n    } else if ((size_t)i + (size_t)v.len < (size_t)v.len) {\n        PyObject *old = v.buf->items[i + v.len];\n        Py_INCREF(o);\n        v.buf->items[i + v.len] = o;\n        Py_XDECREF(old);\n        return 0;\n    } else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        return -1;\n    }\n}\n\nstatic PyObject *vec_richcompare(PyObject *self, PyObject *other, int op) {\n    PyObject *res;\n    if (op == Py_EQ || op == Py_NE) {\n        if (other->ob_type != &VecTType) {\n            res = op == Py_EQ ? Py_False : Py_True;\n        } else {\n            VecT x = ((VecTObject *)self)->vec;\n            VecT y = ((VecTObject *)other)->vec;\n            if (x.buf->item_type != y.buf->item_type) {\n                res = op == Py_EQ ? Py_False : Py_True;\n            } else {\n                // TODO: why pointers to len?\n                return Vec_GenericRichcompare(&x.len, x.buf->items, &y.len, y.buf->items, op);\n            }\n        }\n    } else\n        res = Py_NotImplemented;\n    Py_INCREF(res);\n    return res;\n}\n\n// Append item to 'vec', stealing 'vec'. Return 'vec' with item appended.\nVecT VecT_Append(VecT vec, PyObject *x, size_t item_type) {\n    if (vec.buf == NULL) {\n        VecT new = vec_alloc(1, item_type);\n        if (VEC_IS_ERROR(new))\n            return new;\n        Py_INCREF(x);\n        new.len = 1;\n        new.buf->items[0] = x;\n        return new;\n    }\n    Py_ssize_t cap = VEC_CAP(vec);\n    Py_INCREF(x);\n    if (vec.len < cap) {\n        // Slot may have duplicate ref from prior remove/pop\n        Py_XSETREF(vec.buf->items[vec.len], x);\n        vec.len++;\n        return vec;\n    } else {\n        Py_ssize_t new_size = 2 * cap + 1;\n        // TODO: Avoid initializing to zero here\n        VecT new = vec_alloc(new_size, vec.buf->item_type);\n        if (VEC_IS_ERROR(new)) {\n            Py_DECREF(x);\n            // The input vec is being consumed/stolen by this function, so on error\n            // we must decref it to avoid leaking the buffer.\n            VEC_DECREF(vec);\n            return new;\n        }\n        // Copy items to new vec.\n        memcpy(new.buf->items, vec.buf->items, sizeof(PyObject *) * vec.len);\n        memset(new.buf->items + vec.len, 0, sizeof(PyObject *) * (new_size - vec.len));\n        // Clear the items in the old vec. We avoid reference count manipulation.\n        memset(vec.buf->items, 0, sizeof(PyObject *) * vec.len);\n        new.buf->items[vec.len] = x;\n        new.len = vec.len + 1;\n        VEC_DECREF(vec);\n        return new;\n    }\n}\n\n// Remove item from 'vec', stealing 'vec'. Return 'vec' with item removed.\nVecT VecT_Remove(VecT v, PyObject *arg) {\n    PyObject **items = v.buf->items;\n    for (Py_ssize_t i = 0; i < v.len; i++) {\n        int match = 0;\n        if (items[i] == arg)\n            match = 1;\n        else {\n            int itemcmp = PyObject_RichCompareBool(items[i], arg, Py_EQ);\n            if (itemcmp < 0) {\n                // The input v is being consumed/stolen by this function, so on error\n                // we must decref it to avoid leaking the buffer.\n                VEC_DECREF(v);\n                return vec_error();\n            }\n            match = itemcmp;\n        }\n        if (match) {\n            if (i < v.len - 1) {\n                Py_CLEAR(items[i]);\n                for (; i < v.len - 1; i++) {\n                    items[i] = items[i + 1];\n                }\n                // Keep a duplicate item, since there could be another reference\n                // to the buffer with a longer length, and they expect a valid reference.\n                Py_XINCREF(items[v.len - 1]);\n            }\n            v.len--;\n            // Return the stolen reference without INCREF\n            return v;\n        }\n    }\n    PyErr_SetString(PyExc_ValueError, \"vec.remove(x): x not in vec\");\n    // The input v is being consumed/stolen by this function, so on error\n    // we must decref it to avoid leaking the buffer.\n    VEC_DECREF(v);\n    return vec_error();\n}\n\n// Pop item from 'vec', stealing 'vec'. Return struct with modified 'vec' and the popped item.\nVecTPopResult VecT_Pop(VecT v, Py_ssize_t index) {\n    VecTPopResult result;\n\n    if (index < 0)\n        index += v.len;\n\n    if (index < 0 || index >= v.len) {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        // The input v is being consumed/stolen by this function, so on error\n        // we must decref it to avoid leaking the buffer.\n        VEC_DECREF(v);\n        result.f0 = vec_error();\n        result.f1 = NULL;\n        return result;\n    }\n\n    PyObject **items = v.buf->items;\n    result.f1 = items[index];\n    for (Py_ssize_t i = index; i < v.len - 1; i++)\n        items[i] = items[i + 1];\n    // Keep duplicate item, since there could be another reference\n    // to the buffer with a longer length, and they expect a valid reference.\n    Py_XINCREF(items[v.len - 1]);\n    v.len--;\n    // Return the stolen reference without INCREF\n    result.f0 = v;\n    return result;\n}\n\nstatic int\nVecT_traverse(VecTObject *self, visitproc visit, void *arg)\n{\n    Py_VISIT(self->vec.buf);\n    return 0;\n}\n\nstatic int\nVecT_clear(VecTObject *self)\n{\n    Py_CLEAR(self->vec.buf);\n    return 0;\n}\n\nstatic void\nVecT_dealloc(VecTObject *self)\n{\n    PyObject_GC_UnTrack(self);\n    Py_TRASHCAN_BEGIN(self, VecT_dealloc)\n    Py_CLEAR(self->vec.buf);\n    Py_TYPE(self)->tp_free((PyObject *)self);\n    Py_TRASHCAN_END\n}\n\nstatic int\nVecTBuf_traverse(VecTBufObject *self, visitproc visit, void *arg)\n{\n    Py_VISIT(VEC_BUF_ITEM_TYPE(self));\n    for (Py_ssize_t i = 0; i < VEC_BUF_SIZE(self); i++) {\n        Py_VISIT(self->items[i]);\n    }\n    return 0;\n}\n\nstatic inline int\nVecTBuf_clear(VecTBufObject *self)\n{\n    if (self->item_type) {\n        Py_DECREF(VEC_BUF_ITEM_TYPE(self));\n        self->item_type = 0;\n    }\n    for (Py_ssize_t i = 0; i < VEC_BUF_SIZE(self); i++) {\n        Py_CLEAR(self->items[i]);\n    }\n    return 0;\n}\n\nstatic void\nVecTBuf_dealloc(VecTBufObject *self)\n{\n    PyObject_GC_UnTrack(self);\n    Py_TRASHCAN_BEGIN(self, VecTBuf_dealloc)\n    VecTBuf_clear(self);\n    Py_TYPE(self)->tp_free((PyObject *)self);\n    Py_TRASHCAN_END\n}\n\nstatic Py_ssize_t vec_length(PyObject *o) {\n    return ((VecTObject *)o)->vec.len;\n}\n\nstatic PyMappingMethods VecTMapping = {\n    .mp_length = vec_length,\n    .mp_subscript = vec_subscript,\n};\n\nstatic PySequenceMethods VecTSequence = {\n    .sq_item = vec_get_item,\n    .sq_ass_item = vec_ass_item,\n};\n\nstatic PyMethodDef vec_methods[] = {\n    {NULL, NULL, 0, NULL},  /* Sentinel */\n};\n\nPyTypeObject VecTBufType = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"vecbuf\",\n    .tp_doc = \"Internal data buffer used by vec objects\",\n    .tp_basicsize = sizeof(VecTBufObject) - sizeof(PyObject *),\n    .tp_itemsize = sizeof(PyObject *),\n    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,\n    .tp_traverse = (traverseproc)VecTBuf_traverse,\n    //.tp_new = vecbuf_i64_new, //??\n    .tp_free = PyObject_GC_Del,\n    .tp_clear = (inquiry)VecTBuf_clear,\n    .tp_dealloc = (destructor)VecTBuf_dealloc,\n};\n\nPyTypeObject VecTType = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"vec\",\n    .tp_doc = \"Mutable sequence-like container optimized for compilation with mypyc\",\n    .tp_basicsize = sizeof(VecTObject),\n    .tp_itemsize = 0,\n    .tp_base = &VecType,  // Inherit from base vec type for isinstance() support\n    .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,\n    .tp_traverse = (traverseproc)VecT_traverse,\n    .tp_clear = (inquiry)VecT_clear,\n    .tp_dealloc = (destructor)VecT_dealloc,\n    //.tp_free = PyObject_GC_Del,\n    .tp_repr = (reprfunc)vec_repr,\n    .tp_as_sequence = &VecTSequence,\n    .tp_as_mapping = &VecTMapping,\n    .tp_richcompare = vec_richcompare,\n    .tp_methods = vec_methods,\n    // TODO: free\n};\n\nPyObject *VecT_FromIterable(size_t item_type, PyObject *iterable) {\n    VecT v = vec_alloc(0, item_type);\n    if (VEC_IS_ERROR(v))\n        return NULL;\n    v.len = 0;\n\n    PyObject *iter = PyObject_GetIter(iterable);\n    if (iter == NULL) {\n        VEC_DECREF(v);\n        return NULL;\n    }\n    PyObject *item;\n    while ((item = PyIter_Next(iter)) != NULL) {\n        if (!VecT_ItemCheck(v, item, item_type)) {\n            Py_DECREF(iter);\n            VEC_DECREF(v);\n            Py_DECREF(item);\n            return NULL;\n        }\n        v = VecT_Append(v, item, item_type);\n        Py_DECREF(item);\n        if (VEC_IS_ERROR(v)) {\n            Py_DECREF(iter);\n            VEC_DECREF(v);\n            return NULL;\n        }\n    }\n    Py_DECREF(iter);\n    if (PyErr_Occurred()) {\n        VEC_DECREF(v);\n        return NULL;\n    }\n    return VecT_Box(v, item_type);\n}\n\nVecTAPI Vec_TAPI = {\n    &VecTType,\n    &VecTBufType,\n    VecT_New,\n    VecT_Box,\n    VecT_Unbox,\n    VecT_ConvertFromNested,\n    VecT_Append,\n    VecT_Pop,\n    VecT_Remove,\n    VecT_Slice,\n};\n\n#endif  // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/vec_template.c",
    "content": "#ifdef MYPYC_EXPERIMENTAL\n// NOTE: This file can't be compiled on its own, it must be #included\n//       with certain #defines set, as described below.\n//\n// Implementation of a vec class specialized to a specific item type, such\n// as vec[i64] or vec[float]. Assume that certain #defines are provided that\n// provide all the item type specific definitions:\n//\n//   VEC             vec C type (e.g. VecI32)\n//   VEC_TYPE        boxed vec type object (e.g. VecI32Type)\n//   VEC_OBJECT      boxed Python object struct (e.g. VecI32Object)\n//   BUF_OBJECT      buffer Python object struct (e.g. VecI32BufObject)\n//   BUF_TYPE        buffer type object (e.g. VecI32BufType)\n//   NAME(suffix)    macro to create prefixed name with given suffix (e.g. VecI32##suffix)\n//   FUNC(suffix)    macro to create prefixed function name with suffix (e.g. VecI32_##suffix)\n//   ITEM_TYPE_STR   vec item type as C string literal (e.g. \"i32\")\n//   ITEM_TYPE_MAGIC integer constant corresponding to the item type (e.g. VEC_ITEM_TYPE_I32)\n//   ITEM_C_TYPE     C type used for items (e.g. int32_t)\n//   FEATURES        capsule API struct name (e.g. Vec_I32API)\n//   BOX_ITEM        C function to box item (e.g. VecI32_BoxItem)\n//   UNBOX_ITEM      C function to unbox item (e.g. VecI32_UnboxItem)\n//   IS_UNBOX_ERROR  C function to check for unbox error (e.g. VecI32_IsUnboxError)\n\n#ifndef VEC\n#error \"VEC must be defined\"\n#endif\n\n#define PY_SSIZE_T_CLEAN\n#include <Python.h>\n#include \"librt_vecs.h\"\n#include \"vecs_internal.h\"\n\ninline static VEC vec_error() {\n    VEC v = { .len = -1 };\n    return v;\n}\n\n// Alloc a partially initialized vec. Caller *must* initialize len.\nstatic VEC vec_alloc(Py_ssize_t size)\n{\n    BUF_OBJECT *buf;\n    /* TODO: Check for overflow */\n    if (size == 0) {\n        buf = NULL;\n    } else {\n        buf = PyObject_NewVar(BUF_OBJECT, &BUF_TYPE, size);\n        if (buf == NULL)\n            return vec_error();\n    }\n    VEC res = { .buf = buf };\n    return res;\n}\n\nstatic void vec_dealloc(VEC_OBJECT *self) {\n    Py_CLEAR(self->vec.buf);\n    PyObject_Del(self);\n}\n\n// Box a vec[<itemtype>] value, stealing 'vec'. On error, decref 'vec'.\nPyObject *FUNC(Box)(VEC vec) {\n    VEC_OBJECT *obj = PyObject_New(VEC_OBJECT, &VEC_TYPE);\n    if (obj == NULL) {\n        VEC_DECREF(vec);\n        return NULL;\n    }\n    obj->vec = vec;\n    return (PyObject *)obj;\n}\n\nVEC FUNC(Unbox)(PyObject *obj) {\n    if (obj->ob_type == &VEC_TYPE) {\n        VEC result = ((VEC_OBJECT *)obj)->vec;\n        VEC_INCREF(result);  // TODO: Should we borrow instead?\n        return result;\n    } else {\n        PyErr_SetString(PyExc_TypeError, \"vec[\" ITEM_TYPE_STR \"] expected\");\n        return vec_error();\n    }\n}\n\nVEC FUNC(ConvertFromNested)(VecNestedBufItem item) {\n    return (VEC) { item.len, (BUF_OBJECT *)item.buf };\n}\n\nVEC FUNC(New)(Py_ssize_t size, Py_ssize_t cap) {\n    if (cap < size)\n        size = cap;\n    VEC vec = vec_alloc(cap);\n    if (VEC_IS_ERROR(vec))\n        return vec;\n    for (Py_ssize_t i = 0; i < cap; i++) {\n        vec.buf->items[i] = 0;\n    }\n    vec.len = size;\n    return vec;\n}\n\nPyObject *FUNC(FromIterable)(PyObject *iterable) {\n    VEC v = vec_alloc(0);\n    if (VEC_IS_ERROR(v))\n        return NULL;\n    v.len = 0;\n\n    PyObject *iter = PyObject_GetIter(iterable);\n    if (iter == NULL) {\n        VEC_DECREF(v);\n        return NULL;\n    }\n    PyObject *item;\n    while ((item = PyIter_Next(iter)) != NULL) {\n        ITEM_C_TYPE x = UNBOX_ITEM(item);\n        Py_DECREF(item);\n        if (IS_UNBOX_ERROR(x)) {\n            Py_DECREF(iter);\n            VEC_DECREF(v);\n            return NULL;\n        }\n        v = FUNC(Append)(v, x);\n        if (VEC_IS_ERROR(v)) {\n            Py_DECREF(iter);\n            VEC_DECREF(v);\n            return NULL;\n        }\n    }\n    Py_DECREF(iter);\n    if (PyErr_Occurred()) {\n        VEC_DECREF(v);\n        return NULL;\n    }\n    return FUNC(Box)(v);\n}\n\nstatic PyObject *vec_new(PyTypeObject *self, PyObject *args, PyObject *kw) {\n    static char *kwlist[] = {\"\", NULL};\n    PyObject *init = NULL;\n    if (!PyArg_ParseTupleAndKeywords(args, kw, \"|O:vec\", kwlist, &init)) {\n        return NULL;\n    }\n    if (init == NULL) {\n        return FUNC(Box)(FUNC(New)(0, 0));\n    } else {\n        return (PyObject *)FUNC(FromIterable)(init);\n    }\n}\n\nstatic PyObject *vec_repr(PyObject *self) {\n    return Vec_GenericRepr(self, ITEM_TYPE_MAGIC, 0, 1);\n}\n\nstatic PyObject *vec_get_item(PyObject *o, Py_ssize_t i) {\n    VEC v = ((VEC_OBJECT *)o)->vec;\n    if ((size_t)i < (size_t)v.len) {\n        return BOX_ITEM(v.buf->items[i]);\n    } else if ((size_t)i + (size_t)v.len < (size_t)v.len) {\n        return BOX_ITEM(v.buf->items[i + v.len]);\n    } else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        return NULL;\n    }\n}\n\nVEC FUNC(Slice)(VEC vec, int64_t start, int64_t end) {\n    if (start < 0)\n        start += vec.len;\n    if (end < 0)\n        end += vec.len;\n    if (start < 0)\n        start = 0;\n    if (start >= vec.len)\n        start = vec.len;\n    if (end < start)\n        end = start;\n    if (end > vec.len)\n        end = vec.len;\n    int64_t slicelength = end - start;\n    VEC res = vec_alloc(slicelength);\n    if (VEC_IS_ERROR(res))\n        return res;\n    res.len = slicelength;\n    for (Py_ssize_t i = 0; i < slicelength; i++)\n        res.buf->items[i] = vec.buf->items[start + i];\n    return res;\n}\n\nstatic PyObject *vec_subscript(PyObject *self, PyObject *item) {\n    VEC vec = ((VEC_OBJECT *)self)->vec;\n    if (PyIndex_Check(item)) {\n        Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);\n        if (i == -1 && PyErr_Occurred())\n            return NULL;\n        if ((size_t)i < (size_t)vec.len) {\n            return BOX_ITEM(vec.buf->items[i]);\n        } else if ((size_t)i + (size_t)vec.len < (size_t)vec.len) {\n            return BOX_ITEM(vec.buf->items[i + vec.len]);\n        } else {\n            PyErr_SetString(PyExc_IndexError, \"index out of range\");\n            return NULL;\n        }\n    } else if (PySlice_Check(item)) {\n        Py_ssize_t start, stop, step;\n        if (PySlice_Unpack(item, &start, &stop, &step) < 0)\n            return NULL;\n        Py_ssize_t slicelength = PySlice_AdjustIndices(vec.len, &start, &stop, step);\n        VEC res = vec_alloc(slicelength);\n        if (VEC_IS_ERROR(res))\n            return NULL;\n        res.len = slicelength;\n        Py_ssize_t j = start;\n        for (Py_ssize_t i = 0; i < slicelength; i++) {\n            res.buf->items[i] = vec.buf->items[j];\n            j += step;\n        }\n        return FUNC(Box)(res);\n    } else {\n        PyErr_Format(PyExc_TypeError, \"vec indices must be integers or slices, not %.100s\",\n                     item->ob_type->tp_name);\n        return NULL;\n    }\n}\n\nstatic int vec_ass_item(PyObject *self, Py_ssize_t i, PyObject *o) {\n    ITEM_C_TYPE x = UNBOX_ITEM(o);\n    if (IS_UNBOX_ERROR(x))\n        return -1;\n    VEC v = ((VEC_OBJECT *)self)->vec;\n    if ((size_t)i < (size_t)v.len) {\n        v.buf->items[i] = x;\n        return 0;\n    } else if ((size_t)i + (size_t)v.len < (size_t)v.len) {\n        v.buf->items[i + v.len] = x;\n        return 0;\n    } else {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        return -1;\n    }\n}\n\nstatic Py_ssize_t vec_length(PyObject *o) {\n    return ((VEC_OBJECT *)o)->vec.len;\n}\n\nstatic PyObject *vec_richcompare(PyObject *self, PyObject *other, int op) {\n    int cmp = 1;\n    PyObject *res;\n    if (op == Py_EQ || op == Py_NE) {\n        if (other->ob_type != &VEC_TYPE)\n            cmp = 0;\n        else {\n            VEC x = ((VEC_OBJECT *)self)->vec;\n            VEC y = ((VEC_OBJECT *)other)->vec;\n            if (x.len != y.len) {\n                cmp = 0;\n            } else {\n                for (Py_ssize_t i = 0; i < x.len; i++) {\n                    if (x.buf->items[i] != y.buf->items[i]) {\n                        cmp = 0;\n                        break;\n                    }\n                }\n            }\n        }\n        if (op == Py_NE)\n            cmp = cmp ^ 1;\n        res = cmp ? Py_True : Py_False;\n    } else\n        res = Py_NotImplemented;\n    Py_INCREF(res);\n    return res;\n}\n\n// Append item to 'vec', stealing 'vec'. Return 'vec' with item appended.\nVEC FUNC(Append)(VEC vec, ITEM_C_TYPE x) {\n    if (vec.buf && vec.len < VEC_CAP(vec)) {\n        vec.buf->items[vec.len] = x;\n        vec.len++;\n        return vec;\n    } else {\n        Py_ssize_t cap = vec.buf ? VEC_CAP(vec) : 0;\n        Py_ssize_t new_size = 2 * cap + 1;\n        VEC new = vec_alloc(new_size);\n        if (VEC_IS_ERROR(new)) {\n            // The input v is being consumed/stolen by this function, so on error\n            // we must decref it to avoid leaking the buffer.\n            VEC_DECREF(vec);\n            return vec_error();\n        }\n        new.len = vec.len + 1;\n        if (vec.len > 0)\n            memcpy(new.buf->items, vec.buf->items, sizeof(ITEM_C_TYPE) * vec.len);\n        new.buf->items[vec.len] = x;\n        Py_XDECREF(vec.buf);\n        return new;\n    }\n}\n\n// Remove item from 'vec', stealing 'vec'. Return 'vec' with item removed.\nVEC FUNC(Remove)(VEC v, ITEM_C_TYPE x) {\n    for (Py_ssize_t i = 0; i < v.len; i++) {\n        if (v.buf->items[i] == x) {\n            for (; i < v.len - 1; i++) {\n                v.buf->items[i] = v.buf->items[i + 1];\n            }\n            v.len--;\n            // Return the stolen reference without INCREF\n            return v;\n        }\n    }\n    PyErr_SetString(PyExc_ValueError, \"vec.remove(x): x not in vec\");\n    // The input v is being consumed/stolen by this function, so on error\n    // we must decref it to avoid leaking the buffer.\n    VEC_DECREF(v);\n    return vec_error();\n}\n\n// Pop item from 'vec', stealing 'vec'. Return struct with modified 'vec' and the popped item.\nNAME(PopResult) FUNC(Pop)(VEC v, Py_ssize_t index) {\n    NAME(PopResult) result;\n\n    if (index < 0)\n        index += v.len;\n\n    if (index < 0 || index >= v.len) {\n        PyErr_SetString(PyExc_IndexError, \"index out of range\");\n        // The input v is being consumed/stolen by this function, so on error\n        // we must decref it to avoid leaking the buffer.\n        VEC_DECREF(v);\n        result.f0 = vec_error();\n        result.f1 = 0;\n        return result;\n    }\n\n    result.f1 = v.buf->items[index];\n    for (Py_ssize_t i = index; i < v.len - 1; i++) {\n        v.buf->items[i] = v.buf->items[i + 1];\n    }\n\n    v.len--;\n    // Return the stolen reference without INCREF\n    result.f0 = v;\n    return result;\n}\n\nstatic PyMappingMethods vec_mapping_methods = {\n    .mp_length = vec_length,\n    .mp_subscript = vec_subscript,\n};\n\nstatic PySequenceMethods vec_sequence_methods = {\n    .sq_item = vec_get_item,\n    .sq_ass_item = vec_ass_item,\n};\n\nstatic PyMethodDef vec_methods[] = {\n    {NULL, NULL, 0, NULL},  /* Sentinel */\n};\n\nPyTypeObject BUF_TYPE = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"vecbuf[\" ITEM_TYPE_STR \"]\",\n    .tp_doc = \"Internal data buffer used by vec objects\",\n    .tp_basicsize = sizeof(BUF_OBJECT) - sizeof(ITEM_C_TYPE),\n    .tp_itemsize = sizeof(ITEM_C_TYPE),\n    .tp_flags = Py_TPFLAGS_DEFAULT,\n    //.tp_new = ??\n    .tp_free = PyObject_Del,\n};\n\nPyTypeObject VEC_TYPE = {\n    PyVarObject_HEAD_INIT(NULL, 0)\n    .tp_name = \"vec[\" ITEM_TYPE_STR \"]\",\n    .tp_doc = \"Mutable sequence-like container optimized for compilation with mypyc\",\n    .tp_basicsize = sizeof(VEC_OBJECT),\n    .tp_itemsize = 0,\n    .tp_base = &VecType,  // Inherit from base vec type for isinstance() support\n    .tp_flags = Py_TPFLAGS_DEFAULT,\n    .tp_new = vec_new,\n    //.tp_free = PyObject_Del,\n    .tp_dealloc = (destructor)vec_dealloc,\n    .tp_repr = (reprfunc)vec_repr,\n    .tp_as_sequence = &vec_sequence_methods,\n    .tp_as_mapping = &vec_mapping_methods,\n    .tp_richcompare = vec_richcompare,\n    .tp_methods = vec_methods,\n};\n\nNAME(API) FEATURES = {\n    &VEC_TYPE,\n    &BUF_TYPE,\n    FUNC(New),\n    FUNC(Box),\n    FUNC(Unbox),\n    FUNC(ConvertFromNested),\n    FUNC(Append),\n    FUNC(Pop),\n    FUNC(Remove),\n    FUNC(Slice),\n};\n\n#endif  // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/vec_u8.c",
    "content": "#ifdef MYPYC_EXPERIMENTAL\n#define VEC VecU8\n#define VEC_TYPE VecU8Type\n#define VEC_OBJECT VecU8Object\n#define BUF_OBJECT VecU8BufObject\n#define BUF_TYPE VecU8BufType\n#define NAME(suffix) VecU8##suffix\n#define FUNC(suffix) VecU8_##suffix\n#define ITEM_TYPE_STR \"u8\"\n#define ITEM_TYPE_MAGIC VEC_ITEM_TYPE_U8\n#define ITEM_C_TYPE uint8_t\n#define FEATURES Vec_U8API\n\n#define BOX_ITEM VecU8_BoxItem\n#define UNBOX_ITEM VecU8_UnboxItem\n#define IS_UNBOX_ERROR VecU8_IsUnboxError\n\n#include \"vec_template.c\"\n\n#endif  // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs/vecs_internal.h",
    "content": "#ifndef VECS_INTERNAL_H_INCL\n#define VECS_INTERNAL_H_INCL\n\n// Internal header for mypyc/lib-rt/vecs implementation\n\n#include <Python.h>\n\n// The base vec type\nextern PyTypeObject VecType;\n\n#endif  // VECS_INTERNAL_H_INCL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs_extra_ops.c",
    "content": "// Primitives related to librt.vecs that get linked statically\n// with compiled modules, instead of being called via a capsule.\n\n#include \"vecs_extra_ops.h\"\n\n#ifdef MYPYC_EXPERIMENTAL\n\n// All operations are currently implemented as inline functions in vecs_extra_ops.h\n\n#endif // MYPYC_EXPERIMENTAL\n"
  },
  {
    "path": "mypyc/lib-rt/vecs_extra_ops.h",
    "content": "#ifndef BYTESWRITER_EXTRA_OPS_H\n#define BYTESWRITER_EXTRA_OPS_H\n\n#ifdef MYPYC_EXPERIMENTAL\n\n#include \"vecs/librt_vecs.h\"\n\n// Check if obj is an instance of vec (any vec type)\nstatic inline int CPyVec_Check(PyObject *obj) {\n    return PyObject_TypeCheck(obj, VecApi->get_vec_type());\n}\n\n#endif // MYPYC_EXPERIMENTAL\n\n#endif\n"
  },
  {
    "path": "mypyc/lower/__init__.py",
    "content": ""
  },
  {
    "path": "mypyc/lower/int_ops.py",
    "content": "\"\"\"Convert tagged int primitive ops to lower-level ops.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import NamedTuple\n\nfrom mypyc.ir.ops import Assign, BasicBlock, Branch, ComparisonOp, Register, Value\nfrom mypyc.ir.rtypes import bool_rprimitive, is_short_int_rprimitive\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\nfrom mypyc.lower.registry import lower_primitive_op\nfrom mypyc.primitives.int_ops import int_equal_, int_less_than_\nfrom mypyc.primitives.registry import CFunctionDescription\n\n\n# Description for building int comparison ops\n#\n# Fields:\n#   binary_op_variant: identify which IntOp to use when operands are short integers\n#   c_func_description: the C function to call when operands are tagged integers\n#   c_func_negated: whether to negate the C function call's result\n#   c_func_swap_operands: whether to swap lhs and rhs when call the function\nclass IntComparisonOpDescription(NamedTuple):\n    binary_op_variant: int\n    c_func_description: CFunctionDescription\n    c_func_negated: bool\n    c_func_swap_operands: bool\n\n\n# Provide mapping from textual op to short int's op variant and boxed int's description.\n# Note that these are not complete implementations and require extra IR.\nint_comparison_op_mapping: dict[str, IntComparisonOpDescription] = {\n    \"==\": IntComparisonOpDescription(ComparisonOp.EQ, int_equal_, False, False),\n    \"!=\": IntComparisonOpDescription(ComparisonOp.NEQ, int_equal_, True, False),\n    \"<\": IntComparisonOpDescription(ComparisonOp.SLT, int_less_than_, False, False),\n    \"<=\": IntComparisonOpDescription(ComparisonOp.SLE, int_less_than_, True, True),\n    \">\": IntComparisonOpDescription(ComparisonOp.SGT, int_less_than_, False, True),\n    \">=\": IntComparisonOpDescription(ComparisonOp.SGE, int_less_than_, True, False),\n}\n\n\ndef compare_tagged(self: LowLevelIRBuilder, lhs: Value, rhs: Value, op: str, line: int) -> Value:\n    \"\"\"Compare two tagged integers using given operator (value context).\"\"\"\n    # generate fast binary logic ops on short ints\n    if (is_short_int_rprimitive(lhs.type) or is_short_int_rprimitive(rhs.type)) and op in (\n        \"==\",\n        \"!=\",\n    ):\n        quick = True\n    else:\n        quick = is_short_int_rprimitive(lhs.type) and is_short_int_rprimitive(rhs.type)\n    if quick:\n        return self.comparison_op(lhs, rhs, int_comparison_op_mapping[op][0], line)\n    op_type, c_func_desc, negate_result, swap_op = int_comparison_op_mapping[op]\n    result = Register(bool_rprimitive)\n    short_int_block, int_block, out = BasicBlock(), BasicBlock(), BasicBlock()\n    check_lhs = self.check_tagged_short_int(lhs, line, negated=True)\n    if op in (\"==\", \"!=\"):\n        self.add(Branch(check_lhs, int_block, short_int_block, Branch.BOOL))\n    else:\n        # for non-equality logical ops (less/greater than, etc.), need to check both sides\n        short_lhs = BasicBlock()\n        self.add(Branch(check_lhs, int_block, short_lhs, Branch.BOOL))\n        self.activate_block(short_lhs)\n        check_rhs = self.check_tagged_short_int(rhs, line, negated=True)\n        self.add(Branch(check_rhs, int_block, short_int_block, Branch.BOOL))\n    self.activate_block(int_block)\n    if swap_op:\n        args = [rhs, lhs]\n    else:\n        args = [lhs, rhs]\n    call = self.call_c(c_func_desc, args, line)\n    if negate_result:\n        # TODO: introduce UnaryIntOp?\n        call_result = self.unary_op(call, \"not\", line)\n    else:\n        call_result = call\n    self.add(Assign(result, call_result, line))\n    self.goto(out)\n    self.activate_block(short_int_block)\n    eq = self.comparison_op(lhs, rhs, op_type, line)\n    self.add(Assign(result, eq, line))\n    self.goto_and_activate(out)\n    return result\n\n\n@lower_primitive_op(\"int_eq\")\ndef lower_int_eq(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    return compare_tagged(builder, args[0], args[1], \"==\", line)\n\n\n@lower_primitive_op(\"int_ne\")\ndef lower_int_ne(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    return compare_tagged(builder, args[0], args[1], \"!=\", line)\n\n\n@lower_primitive_op(\"int_lt\")\ndef lower_int_lt(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    return compare_tagged(builder, args[0], args[1], \"<\", line)\n\n\n@lower_primitive_op(\"int_le\")\ndef lower_int_le(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    return compare_tagged(builder, args[0], args[1], \"<=\", line)\n\n\n@lower_primitive_op(\"int_gt\")\ndef lower_int_gt(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    return compare_tagged(builder, args[0], args[1], \">\", line)\n\n\n@lower_primitive_op(\"int_ge\")\ndef lower_int_ge(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    return compare_tagged(builder, args[0], args[1], \">=\", line)\n"
  },
  {
    "path": "mypyc/lower/list_ops.py",
    "content": "from __future__ import annotations\n\nfrom mypyc.common import PLATFORM_SIZE\nfrom mypyc.ir.ops import GetElementPtr, Integer, IntOp, SetMem, Value\nfrom mypyc.ir.rtypes import (\n    PyListObject,\n    c_pyssize_t_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n)\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\nfrom mypyc.lower.registry import lower_primitive_op\n\n\n@lower_primitive_op(\"buf_init_item\")\ndef buf_init_item(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    \"\"\"Initialize an item in a buffer of \"PyObject *\" values at given index.\n\n    This can be used to initialize the data buffer of a freshly allocated list\n    object.\n    \"\"\"\n    base = args[0]\n    index_value = args[1]\n    value = args[2]\n    assert isinstance(index_value, Integer), index_value\n    index = index_value.numeric_value()\n    if index == 0:\n        ptr = base\n    else:\n        ptr = builder.add(\n            IntOp(\n                pointer_rprimitive,\n                base,\n                Integer(index * PLATFORM_SIZE, c_pyssize_t_rprimitive),\n                IntOp.ADD,\n                line,\n            )\n        )\n    return builder.add(SetMem(object_rprimitive, ptr, value, line))\n\n\n@lower_primitive_op(\"list_items\")\ndef list_items(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    ob_item_ptr = builder.add(GetElementPtr(args[0], PyListObject, \"ob_item\", line))\n    return builder.load_mem(ob_item_ptr, pointer_rprimitive)\n\n\ndef list_item_ptr(builder: LowLevelIRBuilder, obj: Value, index: Value, line: int) -> Value:\n    \"\"\"Get a pointer to a list item (index must be valid and non-negative).\n\n    Type of index must be c_pyssize_t_rprimitive, and obj must refer to a list object.\n    \"\"\"\n    # List items are represented as an array of pointers. Pointer to the item obj[index] is\n    # <pointer to first item> + index * <pointer size>.\n    items = list_items(builder, [obj], line)\n    delta = builder.add(\n        IntOp(\n            c_pyssize_t_rprimitive,\n            index,\n            Integer(PLATFORM_SIZE, c_pyssize_t_rprimitive),\n            IntOp.MUL,\n        )\n    )\n    return builder.add(IntOp(pointer_rprimitive, items, delta, IntOp.ADD))\n\n\n@lower_primitive_op(\"list_get_item_unsafe\")\ndef list_get_item_unsafe(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    index = builder.coerce(args[1], c_pyssize_t_rprimitive, line)\n    item_ptr = list_item_ptr(builder, args[0], index, line)\n    return builder.load_mem(item_ptr, object_rprimitive)\n"
  },
  {
    "path": "mypyc/lower/misc_ops.py",
    "content": "from __future__ import annotations\n\nfrom mypyc.ir.ops import ComparisonOp, GetElementPtr, Integer, LoadMem, Value\nfrom mypyc.ir.rtypes import PyVarObject, c_pyssize_t_rprimitive, object_rprimitive\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\nfrom mypyc.lower.registry import lower_primitive_op\n\n\n@lower_primitive_op(\"var_object_size\")\ndef var_object_size(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    elem_address = builder.add(GetElementPtr(args[0], PyVarObject, \"ob_size\"))\n    return builder.add(LoadMem(c_pyssize_t_rprimitive, elem_address, line))\n\n\n@lower_primitive_op(\"propagate_if_error\")\ndef propagate_if_error_op(builder: LowLevelIRBuilder, args: list[Value], line: int) -> Value:\n    # Return False on NULL. The primitive uses ERR_FALSE, so this is an error.\n    return builder.add(\n        ComparisonOp(args[0], Integer(0, object_rprimitive), ComparisonOp.NEQ, line)\n    )\n"
  },
  {
    "path": "mypyc/lower/registry.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Callable\nfrom typing import Final, TypeVar\n\nfrom mypyc.ir.ops import Value\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\n\nLowerFunc = Callable[[LowLevelIRBuilder, list[Value], int], Value]\nLowerFuncOpt = Callable[[LowLevelIRBuilder, list[Value], int], Value | None]\n\nlowering_registry: Final[dict[str, LowerFuncOpt]] = {}\n\nLF = TypeVar(\"LF\", LowerFunc, LowerFuncOpt)\n\n\ndef lower_primitive_op(name: str) -> Callable[[LF], LF]:\n    \"\"\"Register a handler that generates low-level IR for a primitive op.\"\"\"\n\n    def wrapper(f: LF) -> LF:\n        assert name not in lowering_registry\n        lowering_registry[name] = f\n        return f\n\n    return wrapper\n\n\n# Import various modules that set up global state.\nfrom mypyc.lower import int_ops, list_ops, misc_ops  # noqa: F401\n"
  },
  {
    "path": "mypyc/namegen.py",
    "content": "from __future__ import annotations\n\nfrom collections.abc import Iterable\n\n\nclass NameGenerator:\n    \"\"\"Utility for generating distinct C names from Python names.\n\n    Since C names can't use '.' (or unicode), some care is required to\n    make C names generated from Python names unique. Also, we want to\n    avoid generating overly long C names since they make the generated\n    code harder to read.\n\n    Note that we don't restrict ourselves to a 32-character distinguishing\n    prefix guaranteed by the C standard since all the compilers we care\n    about at the moment support longer names without issues.\n\n    For names that are exported in a shared library (not static) use\n    exported_name() instead.\n\n    Summary of the approach:\n\n    * Generate a unique name prefix from suffix of fully-qualified\n      module name used for static names. If only compiling a single\n      module, this can be empty. For example, if the modules are\n      'foo.bar' and 'foo.baz', the prefixes can be 'bar_' and 'baz_',\n      respectively. If the modules are 'bar.foo' and 'baz.foo', the\n      prefixes will be 'bar_foo_' and 'baz_foo_'.\n\n    * Replace '.' in the Python name with '___' in the C name. (And\n      replace the unlikely but possible '___' with '___3_'. This\n      collides '___' with '.3_', but this is OK because names\n      may not start with a digit.)\n\n    The generated should be internal to a build and thus the mapping is\n    arbitrary. Just generating names '1', '2', ... would be correct,\n    though not very usable. The generated names may be visible in CPU\n    profiles and when debugging using native debuggers.\n    \"\"\"\n\n    def __init__(self, groups: Iterable[list[str]], *, separate: bool = False) -> None:\n        \"\"\"Initialize with a list of modules in each compilation group.\n\n        The names of modules are used to shorten names referring to\n        modules, for convenience. Arbitrary module\n        names are supported for generated names, but uncompiled modules\n        will use long names.\n\n        If separate is True, assume separate compilation. This implies\n        that we don't have knowledge of all sources that will be linked\n        together. In this case we won't trim module prefixes, since we\n        don't have enough information to determine common module prefixes.\n        \"\"\"\n        self.module_map: dict[str, str] = {}\n        for names in groups:\n            if not separate:\n                self.module_map.update(make_module_translation_map(names))\n            else:\n                for name in names:\n                    self.module_map[name] = name + \".\"\n        self.translations: dict[tuple[str, str], str] = {}\n        self.used_names: set[str] = set()\n\n    def private_name(self, module: str, partial_name: str | None = None) -> str:\n        \"\"\"Return a C name usable for a static definition.\n\n        Return a distinct result for each (module, partial_name) pair.\n\n        The caller should add a suitable prefix to the name to avoid\n        conflicts with other C names. Only ensure that the results of\n        this function are unique, not that they aren't overlapping with\n        arbitrary names.\n\n        If a name is not specific to any module, the module argument can\n        be an empty string.\n        \"\"\"\n        # TODO: Support unicode\n        if partial_name is None:\n            return exported_name(self.module_map[module].rstrip(\".\"))\n        if (module, partial_name) in self.translations:\n            return self.translations[module, partial_name]\n        if module in self.module_map:\n            module_prefix = self.module_map[module]\n        elif module:\n            module_prefix = module + \".\"\n        else:\n            module_prefix = \"\"\n        actual = exported_name(f\"{module_prefix}{partial_name}\")\n        self.translations[module, partial_name] = actual\n        return actual\n\n\ndef exported_name(fullname: str) -> str:\n    \"\"\"Return a C name usable for an exported definition.\n\n    This is like private_name(), but the output only depends on the\n    'fullname' argument, so the names are distinct across multiple\n    builds.\n    \"\"\"\n    # TODO: Support unicode\n    return fullname.replace(\"___\", \"___3_\").replace(\".\", \"___\")\n\n\ndef make_module_translation_map(names: list[str]) -> dict[str, str]:\n    num_instances: dict[str, int] = {}\n    for name in names:\n        for suffix in candidate_suffixes(name):\n            num_instances[suffix] = num_instances.get(suffix, 0) + 1\n    result = {}\n    for name in names:\n        for suffix in candidate_suffixes(name):\n            if num_instances[suffix] == 1:\n                break\n        # Takes the last suffix if none are unique\n        result[name] = suffix\n    return result\n\n\ndef candidate_suffixes(fullname: str) -> list[str]:\n    components = fullname.split(\".\")\n    result = [\"\"]\n    for i in range(len(components)):\n        result.append(\".\".join(components[-i - 1 :]) + \".\")\n    return result\n"
  },
  {
    "path": "mypyc/options.py",
    "content": "from __future__ import annotations\n\nimport sys\n\n\nclass CompilerOptions:\n    def __init__(\n        self,\n        strip_asserts: bool = False,\n        multi_file: bool = False,\n        verbose: bool = False,\n        separate: bool = False,\n        target_dir: str | None = None,\n        include_runtime_files: bool | None = None,\n        capi_version: tuple[int, int] | None = None,\n        python_version: tuple[int, int] | None = None,\n        strict_dunder_typing: bool = False,\n        group_name: str | None = None,\n        log_trace: bool = False,\n        depends_on_librt_internal: bool = False,\n        experimental_features: bool = False,\n        strict_traceback_checks: bool = False,\n    ) -> None:\n        self.strip_asserts = strip_asserts\n        self.multi_file = multi_file\n        self.verbose = verbose\n        self.separate = separate\n        self.global_opts = not separate\n        self.target_dir = target_dir or \"build\"\n        self.include_runtime_files = (\n            include_runtime_files if include_runtime_files is not None else not multi_file\n        )\n        # The target Python C API version. Overriding this is mostly\n        # useful in IR tests, since there's no guarantee that\n        # binaries are backward compatible even if no recent API\n        # features are used.\n        self.capi_version = capi_version or sys.version_info[:2]\n        self.python_version = python_version\n        # Make possible to inline dunder methods in the generated code.\n        # Typically, the convention is the dunder methods can return `NotImplemented`\n        # even when its return type is just `bool`.\n        # By enabling this option, this convention is no longer valid and the dunder\n        # will assume the return type of the method strictly, which can lead to\n        # more optimization opportunities.\n        self.strict_dunders_typing = strict_dunder_typing\n        # Override the automatic group name derived from the hash of module names.\n        # This affects the names of generated .c, .h and shared library files.\n        # This is only supported when compiling exactly one group, and a shared\n        # library is generated (with shims). This can be used to make the output\n        # file names more predictable.\n        self.group_name = group_name\n        # If enabled, write a trace log of events based on executed operations to\n        # mypyc_trace.txt when compiled module is executed. This is useful for\n        # performance analysis.\n        self.log_trace = log_trace\n        # If enabled, add capsule imports of librt.internal API. This should be used\n        # only for mypy itself, third-party code compiled with mypyc should not use\n        # librt.internal.\n        self.depends_on_librt_internal = depends_on_librt_internal\n        # Some experimental features are only available when building librt in\n        # experimental mode (e.g. use _experimental suffix in librt run test).\n        # These can't be used with a librt wheel installed from PyPI.\n        self.experimental_features = experimental_features\n        # If enabled, mypyc will assert that every traceback it generates has a\n        # positive line number.\n        # Currently each AST node is assigned line number -1 by default to indicate\n        # that it's unset. If the line number is never set and a traceback is\n        # generated that points at such node, then the line number will be interpreted\n        # as None instead of an integer by Python and potentially crash code that\n        # expects an integer, such as pytest.\n        # The goal is to prevent the incorrect tracebacks but it will require a lot\n        # of changes across mypyc. In the meantime, this option should be enabled in\n        # tests to make sure that no new code which leads to incorrect tracebacks is\n        # added.\n        self.strict_traceback_checks = strict_traceback_checks\n"
  },
  {
    "path": "mypyc/primitives/__init__.py",
    "content": ""
  },
  {
    "path": "mypyc/primitives/bytearray_ops.py",
    "content": "\"\"\"Primitive bytearray ops.\n\nNOTE: Most of these should be added to bytearray_extra_ops.c, which requires the\n      BYTEARRAY_EXTRA_OPS primitive dependency, since these are used relatively rarely and we\n      don't want to compile them unless needed.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.deps import BYTEARRAY_EXTRA_OPS\nfrom mypyc.ir.ops import ERR_MAGIC, ERR_NEVER\nfrom mypyc.ir.rtypes import bit_rprimitive, bytearray_rprimitive, object_rprimitive\nfrom mypyc.primitives.registry import custom_primitive_op, function_op, load_address_op\n\n# Get the 'bytearray' type object.\nload_address_op(name=\"builtins.bytearray\", type=object_rprimitive, src=\"PyByteArray_Type\")\n\n# bytearray(obj)\nfunction_op(\n    name=\"builtins.bytearray\",\n    arg_types=[object_rprimitive],\n    return_type=bytearray_rprimitive,\n    c_function_name=\"PyByteArray_FromObject\",\n    error_kind=ERR_MAGIC,\n)\n\n# bytearray() -- construct empty bytearray\nfunction_op(\n    name=\"builtins.bytearray\",\n    arg_types=[],\n    return_type=bytearray_rprimitive,\n    c_function_name=\"CPyByteArray_New\",\n    error_kind=ERR_MAGIC,\n    dependencies=[BYTEARRAY_EXTRA_OPS],\n)\n\n# isinstance(obj, bytearray)\nisinstance_bytearray = custom_primitive_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PyByteArray_Check\",\n    error_kind=ERR_NEVER,\n)\n"
  },
  {
    "path": "mypyc/primitives/bytes_ops.py",
    "content": "\"\"\"Primitive bytes ops.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.deps import BYTES_EXTRA_OPS\nfrom mypyc.ir.ops import ERR_MAGIC, ERR_NEVER\nfrom mypyc.ir.rtypes import (\n    RUnion,\n    bit_rprimitive,\n    bool_rprimitive,\n    bytes_rprimitive,\n    c_int_rprimitive,\n    c_pyssize_t_rprimitive,\n    dict_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    list_rprimitive,\n    object_rprimitive,\n    str_rprimitive,\n)\nfrom mypyc.primitives.registry import (\n    ERR_NEG_INT,\n    binary_op,\n    custom_op,\n    custom_primitive_op,\n    function_op,\n    load_address_op,\n    method_op,\n)\n\n# Get the 'bytes' type object.\nload_address_op(name=\"builtins.bytes\", type=object_rprimitive, src=\"PyBytes_Type\")\n\n# bytes(obj)\nfunction_op(\n    name=\"builtins.bytes\",\n    arg_types=[RUnion([list_rprimitive, dict_rprimitive, str_rprimitive])],\n    return_type=bytes_rprimitive,\n    c_function_name=\"PyBytes_FromObject\",\n    error_kind=ERR_MAGIC,\n)\n\n# translate isinstance(obj, bytes)\nisinstance_bytes = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PyBytes_Check\",\n    error_kind=ERR_NEVER,\n)\n\n# bytes ==/!= (return -1/0/1)\nbytes_compare = custom_op(\n    arg_types=[bytes_rprimitive, bytes_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyBytes_Compare\",\n    error_kind=ERR_NEG_INT,\n)\n\n# bytes + bytes\nbinary_op(\n    name=\"+\",\n    arg_types=[bytes_rprimitive, bytes_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyBytes_Concat\",\n    error_kind=ERR_MAGIC,\n    steals=[True, False],\n)\n\n# bytes * int\nbinary_op(\n    name=\"*\",\n    arg_types=[bytes_rprimitive, int_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyBytes_Multiply\",\n    error_kind=ERR_MAGIC,\n)\n\n# int * bytes\nbinary_op(\n    name=\"*\",\n    arg_types=[int_rprimitive, bytes_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyBytes_Multiply\",\n    error_kind=ERR_MAGIC,\n    ordering=[1, 0],\n)\n\n# bytes[begin:end]\nbytes_slice_op = custom_op(\n    arg_types=[bytes_rprimitive, int_rprimitive, int_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyBytes_GetSlice\",\n    error_kind=ERR_MAGIC,\n)\n\n# bytes[index]\n# bytearray[index]\nmethod_op(\n    name=\"__getitem__\",\n    arg_types=[bytes_rprimitive, int_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyBytes_GetItem\",\n    error_kind=ERR_MAGIC,\n)\n\n# bytes.join(obj)\nmethod_op(\n    name=\"join\",\n    arg_types=[bytes_rprimitive, object_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyBytes_Join\",\n    error_kind=ERR_MAGIC,\n)\n\n# bytes.translate(table)\nmethod_op(\n    name=\"translate\",\n    arg_types=[bytes_rprimitive, object_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyBytes_Translate\",\n    error_kind=ERR_MAGIC,\n    dependencies=[BYTES_EXTRA_OPS],\n)\n\n# bytes.startswith(bytes)\nmethod_op(\n    name=\"startswith\",\n    arg_types=[bytes_rprimitive, bytes_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyBytes_Startswith\",\n    truncated_type=bool_rprimitive,\n    error_kind=ERR_MAGIC,\n)\n\n# bytes.endswith(bytes)\nmethod_op(\n    name=\"endswith\",\n    arg_types=[bytes_rprimitive, bytes_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyBytes_Endswith\",\n    truncated_type=bool_rprimitive,\n    error_kind=ERR_MAGIC,\n)\n\n# Join bytes objects and return a new bytes.\n# The first argument is the total number of the following bytes.\nbytes_build_op = custom_op(\n    arg_types=[c_pyssize_t_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyBytes_Build\",\n    error_kind=ERR_MAGIC,\n    var_arg_type=bytes_rprimitive,\n)\n\nfunction_op(\n    name=\"builtins.ord\",\n    arg_types=[bytes_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyBytes_Ord\",\n    error_kind=ERR_MAGIC,\n)\n\n# Optimized bytes.__getitem__ operations\n\n# bytes index adjustment - convert negative index to positive\nbytes_adjust_index_op = custom_primitive_op(\n    name=\"bytes_adjust_index\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=int64_rprimitive,\n    c_function_name=\"CPyBytes_AdjustIndex\",\n    error_kind=ERR_NEVER,\n    dependencies=[BYTES_EXTRA_OPS],\n)\n\n# bytes range check - check if index is in valid range\nbytes_range_check_op = custom_primitive_op(\n    name=\"bytes_range_check\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyBytes_RangeCheck\",\n    error_kind=ERR_NEVER,\n    dependencies=[BYTES_EXTRA_OPS],\n)\n\n# bytes.__getitem__() - get byte at index (no bounds checking)\nbytes_get_item_unsafe_op = custom_primitive_op(\n    name=\"bytes_get_item_unsafe\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyBytes_GetItemUnsafe\",\n    error_kind=ERR_NEVER,\n    dependencies=[BYTES_EXTRA_OPS],\n)\n"
  },
  {
    "path": "mypyc/primitives/dict_ops.py",
    "content": "\"\"\"Primitive dict ops.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.ops import ERR_FALSE, ERR_MAGIC, ERR_NEVER\nfrom mypyc.ir.rtypes import (\n    bit_rprimitive,\n    bool_rprimitive,\n    c_int_rprimitive,\n    c_pyssize_t_rprimitive,\n    dict_next_rtuple_pair,\n    dict_next_rtuple_single,\n    dict_rprimitive,\n    int_rprimitive,\n    list_rprimitive,\n    object_rprimitive,\n)\nfrom mypyc.primitives.registry import (\n    ERR_NEG_INT,\n    binary_op,\n    custom_op,\n    function_op,\n    load_address_op,\n    method_op,\n)\n\n# Get the 'dict' type object.\nload_address_op(name=\"builtins.dict\", type=object_rprimitive, src=\"PyDict_Type\")\n\n# Construct an empty dictionary via dict().\nfunction_op(\n    name=\"builtins.dict\",\n    arg_types=[],\n    return_type=dict_rprimitive,\n    c_function_name=\"PyDict_New\",\n    error_kind=ERR_MAGIC,\n)\n\n# Construct an empty dictionary.\ndict_new_op = custom_op(\n    arg_types=[], return_type=dict_rprimitive, c_function_name=\"PyDict_New\", error_kind=ERR_MAGIC\n)\n\n# Construct a dictionary from keys and values.\n# Positional argument is the number of key-value pairs\n# Variable arguments are (key1, value1, ..., keyN, valueN).\ndict_build_op = custom_op(\n    arg_types=[c_pyssize_t_rprimitive],\n    return_type=dict_rprimitive,\n    c_function_name=\"CPyDict_Build\",\n    error_kind=ERR_MAGIC,\n    var_arg_type=object_rprimitive,\n)\n\n# Construct a dictionary from another dictionary.\ndict_copy_op = function_op(\n    name=\"builtins.dict\",\n    arg_types=[dict_rprimitive],\n    return_type=dict_rprimitive,\n    c_function_name=\"PyDict_Copy\",\n    error_kind=ERR_MAGIC,\n    priority=2,\n)\n\n# Generic one-argument dict constructor: dict(obj)\ndict_copy = function_op(\n    name=\"builtins.dict\",\n    arg_types=[object_rprimitive],\n    return_type=dict_rprimitive,\n    c_function_name=\"CPyDict_FromAny\",\n    error_kind=ERR_MAGIC,\n)\n\n# translate isinstance(obj, dict)\nisinstance_dict = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PyDict_Check\",\n    error_kind=ERR_NEVER,\n)\n\n# dict[key]\ndict_get_item_op = method_op(\n    name=\"__getitem__\",\n    arg_types=[dict_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_GetItem\",\n    error_kind=ERR_MAGIC,\n)\n\n# dict[key] = value\ndict_set_item_op = method_op(\n    name=\"__setitem__\",\n    arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyDict_SetItem\",\n    error_kind=ERR_NEG_INT,\n)\n\n# dict[key] = value (exact dict only, no subclasses)\n# NOTE: this is currently for internal use only, and not used for CallExpr specialization\nexact_dict_set_item_op = custom_op(\n    arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyDict_SetItem\",\n    error_kind=ERR_NEG_INT,\n)\n\n# key in dict\nbinary_op(\n    name=\"in\",\n    arg_types=[object_rprimitive, dict_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyDict_Contains\",\n    error_kind=ERR_NEG_INT,\n    truncated_type=bool_rprimitive,\n    ordering=[1, 0],\n)\n\n# dict1.update(dict2)\ndict_update_op = method_op(\n    name=\"update\",\n    arg_types=[dict_rprimitive, dict_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyDict_Update\",\n    error_kind=ERR_NEG_INT,\n    priority=2,\n)\n\n# Operation used for **value in dict displays.\n# This is mostly like dict.update(obj), but has customized error handling.\ndict_update_in_display_op = custom_op(\n    arg_types=[dict_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyDict_UpdateInDisplay\",\n    error_kind=ERR_NEG_INT,\n)\n\n# dict.update(obj)\nmethod_op(\n    name=\"update\",\n    arg_types=[dict_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyDict_UpdateFromAny\",\n    error_kind=ERR_NEG_INT,\n)\n\n# dict.get(key, default)\nmethod_op(\n    name=\"get\",\n    arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_Get\",\n    error_kind=ERR_MAGIC,\n)\n\n# dict.get(key)\ndict_get_method_with_none = method_op(\n    name=\"get\",\n    arg_types=[dict_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_GetWithNone\",\n    error_kind=ERR_MAGIC,\n)\n\n# dict.setdefault(key, default)\ndict_setdefault_op = method_op(\n    name=\"setdefault\",\n    arg_types=[dict_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_SetDefault\",\n    error_kind=ERR_MAGIC,\n)\n\n# dict.setdefault(key)\nmethod_op(\n    name=\"setdefault\",\n    arg_types=[dict_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_SetDefaultWithNone\",\n    error_kind=ERR_MAGIC,\n)\n\n# dict.setdefault(key, empty tuple/list/set)\n# The third argument marks the data type of the second argument.\n#     1: list    2: dict    3: set\n# Other number would lead to an error.\ndict_setdefault_spec_init_op = custom_op(\n    arg_types=[dict_rprimitive, object_rprimitive, c_int_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_SetDefaultWithEmptyDatatype\",\n    error_kind=ERR_MAGIC,\n)\n\n# dict.keys()\nmethod_op(\n    name=\"keys\",\n    arg_types=[dict_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_KeysView\",\n    error_kind=ERR_MAGIC,\n)\n\n# dict.values()\nmethod_op(\n    name=\"values\",\n    arg_types=[dict_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_ValuesView\",\n    error_kind=ERR_MAGIC,\n)\n\n# dict.items()\nmethod_op(\n    name=\"items\",\n    arg_types=[dict_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_ItemsView\",\n    error_kind=ERR_MAGIC,\n)\n\n# dict.clear()\nmethod_op(\n    name=\"clear\",\n    arg_types=[dict_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyDict_Clear\",\n    error_kind=ERR_FALSE,\n)\n\n# dict.copy()\nmethod_op(\n    name=\"copy\",\n    arg_types=[dict_rprimitive],\n    return_type=dict_rprimitive,\n    c_function_name=\"CPyDict_Copy\",\n    error_kind=ERR_MAGIC,\n)\n\n# list(dict.keys())\ndict_keys_op = custom_op(\n    arg_types=[dict_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"CPyDict_Keys\",\n    error_kind=ERR_MAGIC,\n)\n\n# list(dict.values())\ndict_values_op = custom_op(\n    arg_types=[dict_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"CPyDict_Values\",\n    error_kind=ERR_MAGIC,\n)\n\n# list(dict.items())\ndict_items_op = custom_op(\n    arg_types=[dict_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"CPyDict_Items\",\n    error_kind=ERR_MAGIC,\n)\n\n# PyDict_Next() fast iteration\ndict_key_iter_op = custom_op(\n    arg_types=[dict_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_GetKeysIter\",\n    error_kind=ERR_MAGIC,\n)\n\ndict_value_iter_op = custom_op(\n    arg_types=[dict_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_GetValuesIter\",\n    error_kind=ERR_MAGIC,\n)\n\ndict_item_iter_op = custom_op(\n    arg_types=[dict_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyDict_GetItemsIter\",\n    error_kind=ERR_MAGIC,\n)\n\ndict_next_key_op = custom_op(\n    arg_types=[object_rprimitive, int_rprimitive],\n    return_type=dict_next_rtuple_single,\n    c_function_name=\"CPyDict_NextKey\",\n    error_kind=ERR_NEVER,\n)\n\ndict_next_value_op = custom_op(\n    arg_types=[object_rprimitive, int_rprimitive],\n    return_type=dict_next_rtuple_single,\n    c_function_name=\"CPyDict_NextValue\",\n    error_kind=ERR_NEVER,\n)\n\ndict_next_item_op = custom_op(\n    arg_types=[object_rprimitive, int_rprimitive],\n    return_type=dict_next_rtuple_pair,\n    c_function_name=\"CPyDict_NextItem\",\n    error_kind=ERR_NEVER,\n)\n\n# check that len(dict) == const during iteration\ndict_check_size_op = custom_op(\n    arg_types=[dict_rprimitive, c_pyssize_t_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyDict_CheckSize\",\n    error_kind=ERR_FALSE,\n)\n\ndict_ssize_t_size_op = custom_op(\n    arg_types=[dict_rprimitive],\n    return_type=c_pyssize_t_rprimitive,\n    c_function_name=\"PyDict_Size\",\n    error_kind=ERR_NEVER,\n)\n\n# Delete an item from a dict\ndict_del_item = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyDict_DelItem\",\n    error_kind=ERR_NEG_INT,\n)\n\nsupports_mapping_protocol = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyMapping_Check\",\n    error_kind=ERR_NEVER,\n)\n\nmapping_has_key = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyMapping_HasKey\",\n    error_kind=ERR_NEVER,\n)\n"
  },
  {
    "path": "mypyc/primitives/exc_ops.py",
    "content": "\"\"\"Exception-related primitive ops.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.ops import ERR_ALWAYS, ERR_FALSE, ERR_NEVER\nfrom mypyc.ir.rtypes import bit_rprimitive, exc_rtuple, object_rprimitive, void_rtype\nfrom mypyc.primitives.registry import custom_op, custom_primitive_op\n\n# If the argument is a class, raise an instance of the class. Otherwise, assume\n# that the argument is an exception object, and raise it.\nraise_exception_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=void_rtype,\n    c_function_name=\"CPy_Raise\",\n    error_kind=ERR_ALWAYS,\n)\n\n# Raise StopIteration exception with the specified value (which can be NULL).\nset_stop_iteration_value = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=void_rtype,\n    c_function_name=\"CPyGen_SetStopIterationValue\",\n    error_kind=ERR_ALWAYS,\n)\n\n# Raise exception with traceback.\n# Arguments are (exception type, exception value, traceback).\nraise_exception_with_tb_op = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=void_rtype,\n    c_function_name=\"CPyErr_SetObjectAndTraceback\",\n    error_kind=ERR_ALWAYS,\n)\n\n# Reraise the currently raised exception.\nreraise_exception_op = custom_op(\n    arg_types=[], return_type=void_rtype, c_function_name=\"CPy_Reraise\", error_kind=ERR_ALWAYS\n)\n\n# Propagate exception if the CPython error indicator is set (an exception was raised).\nno_err_occurred_op = custom_op(\n    arg_types=[],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPy_NoErrOccurred\",\n    error_kind=ERR_FALSE,\n)\n\nerr_occurred_op = custom_op(\n    arg_types=[],\n    return_type=object_rprimitive,\n    c_function_name=\"PyErr_Occurred\",\n    error_kind=ERR_NEVER,\n    is_borrowed=True,\n)\n\n# Keep propagating a raised exception by unconditionally giving an error value.\n# This doesn't actually raise an exception.\nkeep_propagating_op = custom_op(\n    arg_types=[],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPy_KeepPropagating\",\n    error_kind=ERR_FALSE,\n)\n\n# If argument is NULL, propagate currently raised exception (in this case\n# an exception must have been raised). If this can be used, it's faster\n# than using PyErr_Occurred().\npropagate_if_error_op = custom_primitive_op(\n    \"propagate_if_error\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    error_kind=ERR_FALSE,\n)\n\n# Catches a propagating exception and makes it the \"currently\n# handled exception\" (by sticking it into sys.exc_info()). Returns the\n# exception that was previously being handled, which must be restored\n# later.\nerror_catch_op = custom_op(\n    arg_types=[], return_type=exc_rtuple, c_function_name=\"CPy_CatchError\", error_kind=ERR_NEVER\n)\n\n# Restore an old \"currently handled exception\" returned from.\n# error_catch (by sticking it into sys.exc_info())\nrestore_exc_info_op = custom_op(\n    arg_types=[exc_rtuple],\n    return_type=void_rtype,\n    c_function_name=\"CPy_RestoreExcInfo\",\n    error_kind=ERR_NEVER,\n)\n\n# Checks whether the exception currently being handled matches a particular type.\nexc_matches_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPy_ExceptionMatches\",\n    error_kind=ERR_NEVER,\n)\n\n# Get the value of the exception currently being handled.\nget_exc_value_op = custom_op(\n    arg_types=[],\n    return_type=object_rprimitive,\n    c_function_name=\"CPy_GetExcValue\",\n    error_kind=ERR_NEVER,\n)\n\n# Get exception info (exception type, exception instance, traceback object).\nget_exc_info_op = custom_op(\n    arg_types=[], return_type=exc_rtuple, c_function_name=\"CPy_GetExcInfo\", error_kind=ERR_NEVER\n)\n"
  },
  {
    "path": "mypyc/primitives/float_ops.py",
    "content": "\"\"\"Primitive float ops.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.ops import ERR_MAGIC, ERR_MAGIC_OVERLAPPING, ERR_NEVER\nfrom mypyc.ir.rtypes import (\n    bit_rprimitive,\n    bool_rprimitive,\n    float_rprimitive,\n    int_rprimitive,\n    object_rprimitive,\n    str_rprimitive,\n)\nfrom mypyc.primitives.registry import binary_op, function_op, load_address_op\n\n# Get the 'builtins.float' type object.\nload_address_op(name=\"builtins.float\", type=object_rprimitive, src=\"PyFloat_Type\")\n\nbinary_op(\n    name=\"//\",\n    arg_types=[float_rprimitive, float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyFloat_FloorDivide\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\n# float(int)\nint_to_float_op = function_op(\n    name=\"builtins.float\",\n    arg_types=[int_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyFloat_FromTagged\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\n# float(str)\nfunction_op(\n    name=\"builtins.float\",\n    arg_types=[str_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyFloat_FromString\",\n    error_kind=ERR_MAGIC,\n)\n\n# abs(float)\nfunction_op(\n    name=\"builtins.abs\",\n    arg_types=[float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"fabs\",\n    error_kind=ERR_NEVER,\n)\n\n# math.sin(float)\nfunction_op(\n    name=\"math.sin\",\n    arg_types=[float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyFloat_Sin\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\n# math.cos(float)\nfunction_op(\n    name=\"math.cos\",\n    arg_types=[float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyFloat_Cos\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\n# math.tan(float)\nfunction_op(\n    name=\"math.tan\",\n    arg_types=[float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyFloat_Tan\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\n# math.sqrt(float)\nfunction_op(\n    name=\"math.sqrt\",\n    arg_types=[float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyFloat_Sqrt\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\n# math.exp(float)\nfunction_op(\n    name=\"math.exp\",\n    arg_types=[float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyFloat_Exp\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\n# math.log(float)\nfunction_op(\n    name=\"math.log\",\n    arg_types=[float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyFloat_Log\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\n# math.floor(float)\nfunction_op(\n    name=\"math.floor\",\n    arg_types=[float_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyFloat_Floor\",\n    error_kind=ERR_MAGIC,\n)\n\n# math.ceil(float)\nfunction_op(\n    name=\"math.ceil\",\n    arg_types=[float_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyFloat_Ceil\",\n    error_kind=ERR_MAGIC,\n)\n\n# math.fabs(float)\nfunction_op(\n    name=\"math.fabs\",\n    arg_types=[float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"fabs\",\n    error_kind=ERR_NEVER,\n)\n\n# math.pow(float, float)\npow_op = function_op(\n    name=\"math.pow\",\n    arg_types=[float_rprimitive, float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyFloat_Pow\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\n# math.copysign(float, float)\ncopysign_op = function_op(\n    name=\"math.copysign\",\n    arg_types=[float_rprimitive, float_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"copysign\",\n    error_kind=ERR_NEVER,\n)\n\n# math.isinf(float)\nfunction_op(\n    name=\"math.isinf\",\n    arg_types=[float_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyFloat_IsInf\",\n    error_kind=ERR_NEVER,\n)\n\n# math.isnan(float)\nfunction_op(\n    name=\"math.isnan\",\n    arg_types=[float_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyFloat_IsNaN\",\n    error_kind=ERR_NEVER,\n)\n\n# translate isinstance(obj, float)\nisinstance_float = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PyFloat_Check\",\n    error_kind=ERR_NEVER,\n)\n"
  },
  {
    "path": "mypyc/primitives/generic_ops.py",
    "content": "\"\"\"Fallback primitive operations that operate on 'object' operands.\n\nThese just call the relevant Python C API function or a thin wrapper\naround an API function. Most of these also have faster, specialized\nops that operate on some more specific types.\n\nMany of these ops are given a low priority (0) so that specialized ops\nwill take precedence. If your specialized op doesn't seem to be used,\ncheck that the priorities are configured properly.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.ops import ERR_MAGIC, ERR_NEVER\nfrom mypyc.ir.rtypes import (\n    bool_rprimitive,\n    c_int_rprimitive,\n    c_pyssize_t_rprimitive,\n    c_size_t_rprimitive,\n    int_rprimitive,\n    object_pointer_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n)\nfrom mypyc.primitives.registry import (\n    ERR_NEG_INT,\n    binary_op,\n    custom_op,\n    custom_primitive_op,\n    function_op,\n    method_op,\n    unary_op,\n)\n\n# Binary operations\n\nfor op, opid in [\n    (\"==\", 2),  # PY_EQ\n    (\"!=\", 3),  # PY_NE\n    (\"<\", 0),  # PY_LT\n    (\"<=\", 1),  # PY_LE\n    (\">\", 4),  # PY_GT\n    (\">=\", 5),\n]:  # PY_GE\n    # The result type is 'object' since that's what PyObject_RichCompare returns.\n    binary_op(\n        name=op,\n        arg_types=[object_rprimitive, object_rprimitive],\n        return_type=object_rprimitive,\n        c_function_name=\"PyObject_RichCompare\",\n        error_kind=ERR_MAGIC,\n        extra_int_constants=[(opid, c_int_rprimitive)],\n        priority=0,\n    )\n\nfor op, funcname in [\n    (\"+\", \"PyNumber_Add\"),\n    (\"-\", \"PyNumber_Subtract\"),\n    (\"*\", \"PyNumber_Multiply\"),\n    (\"//\", \"PyNumber_FloorDivide\"),\n    (\"/\", \"PyNumber_TrueDivide\"),\n    (\"%\", \"PyNumber_Remainder\"),\n    (\"<<\", \"PyNumber_Lshift\"),\n    (\">>\", \"PyNumber_Rshift\"),\n    (\"&\", \"PyNumber_And\"),\n    (\"^\", \"PyNumber_Xor\"),\n    (\"|\", \"PyNumber_Or\"),\n    (\"@\", \"PyNumber_MatrixMultiply\"),\n]:\n    binary_op(\n        name=op,\n        arg_types=[object_rprimitive, object_rprimitive],\n        return_type=object_rprimitive,\n        c_function_name=funcname,\n        error_kind=ERR_MAGIC,\n        priority=0,\n    )\n\n\nfunction_op(\n    name=\"builtins.divmod\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyNumber_Divmod\",\n    error_kind=ERR_MAGIC,\n    priority=0,\n)\n\n\nfor op, funcname in [\n    (\"+=\", \"PyNumber_InPlaceAdd\"),\n    (\"-=\", \"PyNumber_InPlaceSubtract\"),\n    (\"*=\", \"PyNumber_InPlaceMultiply\"),\n    (\"@=\", \"PyNumber_InPlaceMatrixMultiply\"),\n    (\"//=\", \"PyNumber_InPlaceFloorDivide\"),\n    (\"/=\", \"PyNumber_InPlaceTrueDivide\"),\n    (\"%=\", \"PyNumber_InPlaceRemainder\"),\n    (\"<<=\", \"PyNumber_InPlaceLshift\"),\n    (\">>=\", \"PyNumber_InPlaceRshift\"),\n    (\"&=\", \"PyNumber_InPlaceAnd\"),\n    (\"^=\", \"PyNumber_InPlaceXor\"),\n    (\"|=\", \"PyNumber_InPlaceOr\"),\n]:\n    binary_op(\n        name=op,\n        arg_types=[object_rprimitive, object_rprimitive],\n        return_type=object_rprimitive,\n        c_function_name=funcname,\n        error_kind=ERR_MAGIC,\n        priority=0,\n    )\n\nfor op, c_function in ((\"**\", \"CPyNumber_Power\"), (\"**=\", \"CPyNumber_InPlacePower\")):\n    binary_op(\n        name=op,\n        arg_types=[object_rprimitive, object_rprimitive],\n        return_type=object_rprimitive,\n        error_kind=ERR_MAGIC,\n        c_function_name=c_function,\n        priority=0,\n    )\n\nfor arg_count, c_function in ((2, \"CPyNumber_Power\"), (3, \"PyNumber_Power\")):\n    function_op(\n        name=\"builtins.pow\",\n        arg_types=[object_rprimitive] * arg_count,\n        return_type=object_rprimitive,\n        error_kind=ERR_MAGIC,\n        c_function_name=c_function,\n        priority=0,\n    )\n\nbinary_op(\n    name=\"in\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PySequence_Contains\",\n    error_kind=ERR_NEG_INT,\n    truncated_type=bool_rprimitive,\n    ordering=[1, 0],\n    priority=0,\n)\n\n\n# Unary operations\n\nfor op, funcname in [\n    (\"-\", \"PyNumber_Negative\"),\n    (\"+\", \"PyNumber_Positive\"),\n    (\"~\", \"PyNumber_Invert\"),\n]:\n    unary_op(\n        name=op,\n        arg_type=object_rprimitive,\n        return_type=object_rprimitive,\n        c_function_name=funcname,\n        error_kind=ERR_MAGIC,\n        priority=0,\n    )\n\nunary_op(\n    name=\"not\",\n    arg_type=object_rprimitive,\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyObject_Not\",\n    error_kind=ERR_NEG_INT,\n    truncated_type=bool_rprimitive,\n    priority=0,\n)\n\n# abs(obj)\nfunction_op(\n    name=\"builtins.abs\",\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyNumber_Absolute\",\n    error_kind=ERR_MAGIC,\n    priority=0,\n)\n\n# obj1[obj2]\npy_get_item_op = method_op(\n    name=\"__getitem__\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyObject_GetItem\",\n    error_kind=ERR_MAGIC,\n    priority=0,\n)\n\n# obj1[obj2] = obj3\nmethod_op(\n    name=\"__setitem__\",\n    arg_types=[object_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyObject_SetItem\",\n    error_kind=ERR_NEG_INT,\n    priority=0,\n)\n\n# del obj1[obj2]\nmethod_op(\n    name=\"__delitem__\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyObject_DelItem\",\n    error_kind=ERR_NEG_INT,\n    priority=0,\n)\n\n# hash(obj)\nfunction_op(\n    name=\"builtins.hash\",\n    arg_types=[object_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyObject_Hash\",\n    error_kind=ERR_MAGIC,\n)\n\n# getattr(obj, attr)\npy_getattr_op = function_op(\n    name=\"builtins.getattr\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyObject_GetAttr\",\n    error_kind=ERR_MAGIC,\n)\n\n# getattr(obj, attr, default)\nfunction_op(\n    name=\"builtins.getattr\",\n    arg_types=[object_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyObject_GetAttr3\",\n    error_kind=ERR_MAGIC,\n)\n\n# setattr(obj, attr, value)\npy_setattr_op = function_op(\n    name=\"builtins.setattr\",\n    arg_types=[object_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyObject_SetAttr\",\n    error_kind=ERR_NEG_INT,\n)\n\n# hasattr(obj, attr)\npy_hasattr_op = function_op(\n    name=\"builtins.hasattr\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"PyObject_HasAttr\",\n    error_kind=ERR_NEVER,\n)\n\n# del obj.attr\npy_delattr_op = function_op(\n    name=\"builtins.delattr\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyObject_DelAttr\",\n    error_kind=ERR_NEG_INT,\n)\n\n# Call callable object with N positional arguments: func(arg1, ..., argN)\n# Arguments are (func, arg1, ..., argN).\npy_call_op = custom_op(\n    arg_types=[],\n    return_type=object_rprimitive,\n    c_function_name=\"PyObject_CallFunctionObjArgs\",\n    error_kind=ERR_MAGIC,\n    var_arg_type=object_rprimitive,\n    extra_int_constants=[(0, pointer_rprimitive)],\n)\n\n# Call callable object using positional and/or keyword arguments (Python 3.8+)\npy_vectorcall_op = custom_op(\n    arg_types=[\n        object_rprimitive,  # Callable\n        object_pointer_rprimitive,  # Args (PyObject **)\n        c_size_t_rprimitive,  # Number of positional args\n        object_rprimitive,\n    ],  # Keyword arg names tuple (or NULL)\n    return_type=object_rprimitive,\n    c_function_name=\"PyObject_Vectorcall\",\n    error_kind=ERR_MAGIC,\n)\n\n# Call method using positional and/or keyword arguments (Python 3.9+)\npy_vectorcall_method_op = custom_op(\n    arg_types=[\n        object_rprimitive,  # Method name\n        object_pointer_rprimitive,  # Args, including self (PyObject **)\n        c_size_t_rprimitive,  # Number of positional args, including self\n        object_rprimitive,\n    ],  # Keyword arg names tuple (or NULL)\n    return_type=object_rprimitive,\n    c_function_name=\"PyObject_VectorcallMethod\",\n    error_kind=ERR_MAGIC,\n)\n\n# Call callable object with positional + keyword args: func(*args, **kwargs)\n# Arguments are (func, *args tuple, **kwargs dict).\npy_call_with_kwargs_op = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyObject_Call\",\n    error_kind=ERR_MAGIC,\n)\n\n# Call callable object with positional args only: func(*args)\n# Arguments are (func, *args tuple).\npy_call_with_posargs_op = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyObject_CallObject\",\n    error_kind=ERR_MAGIC,\n)\n\n# Call method with positional arguments: obj.method(arg1, ...)\n# Arguments are (object, attribute name, arg1, ...).\npy_method_call_op = custom_op(\n    arg_types=[],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyObject_CallMethodObjArgs\",\n    error_kind=ERR_MAGIC,\n    var_arg_type=object_rprimitive,\n    extra_int_constants=[(0, pointer_rprimitive)],\n)\n\n# len(obj)\ngeneric_len_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyObject_Size\",\n    error_kind=ERR_MAGIC,\n)\n\n# len(obj)\n# same as generic_len_op, however return py_ssize_t\ngeneric_ssize_t_len_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=c_pyssize_t_rprimitive,\n    c_function_name=\"PyObject_Size\",\n    error_kind=ERR_NEG_INT,\n)\n\n# iter(obj)\niter_op = function_op(\n    name=\"builtins.iter\",\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyObject_GetIter\",\n    error_kind=ERR_MAGIC,\n)\n# next(iterator)\n#\n# Although the error_kind is set to be ERR_NEVER, this can actually\n# return NULL, and thus it must be checked using Branch.IS_ERROR.\nnext_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyIter_Next\",\n    error_kind=ERR_NEVER,\n)\n# next(iterator)\n#\n# Do a next, don't swallow StopIteration, but also don't propagate an\n# error. (N.B: This can still return NULL without an error to\n# represent an implicit StopIteration, but if StopIteration is\n# *explicitly* raised this will not swallow it.)\n# Can return NULL: see next_op.\nnext_raw_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyIter_Next\",\n    error_kind=ERR_NEVER,\n)\n\n# this would be aiter(obj) if it existed\naiter_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPy_GetAIter\",\n    error_kind=ERR_MAGIC,\n)\n\n# this would be anext(obj) if it existed\nanext_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPy_GetANext\",\n    error_kind=ERR_MAGIC,\n)\n\n# x.__name__ (requires Python 3.11+)\nname_op = custom_primitive_op(\n    name=\"__name__\",\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPy_GetName\",\n    error_kind=ERR_MAGIC,\n)\n\n# look-up name in tp_dict but don't raise AttributeError on failure\ngeneric_getattr = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyObject_GenericGetAttr\",\n    error_kind=ERR_NEVER,\n    returns_null=True,\n)\n\ngeneric_setattr = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyObject_GenericSetAttr\",\n    error_kind=ERR_NEG_INT,\n)\n\nsetup_object = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPy_SetupObject\",\n    error_kind=ERR_MAGIC,\n)\n"
  },
  {
    "path": "mypyc/primitives/int_ops.py",
    "content": "\"\"\"Arbitrary-precision integer primitive ops.\n\nThese mostly operate on (usually) unboxed integers that use a tagged pointer\nrepresentation (CPyTagged) and correspond to the Python 'int' type.\n\nSee also the documentation for mypyc.rtypes.int_rprimitive.\n\nUse mypyc.ir.ops.IntOp for operations on fixed-width/C integers.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.ops import (\n    ERR_ALWAYS,\n    ERR_MAGIC,\n    ERR_MAGIC_OVERLAPPING,\n    ERR_NEVER,\n    PrimitiveDescription,\n)\nfrom mypyc.ir.rtypes import (\n    RType,\n    bit_rprimitive,\n    bool_rprimitive,\n    bytes_rprimitive,\n    c_pyssize_t_rprimitive,\n    float_rprimitive,\n    int16_rprimitive,\n    int32_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    object_rprimitive,\n    str_rprimitive,\n    void_rtype,\n)\nfrom mypyc.primitives.registry import (\n    binary_op,\n    custom_op,\n    function_op,\n    load_address_op,\n    method_op,\n    unary_op,\n)\n\n# Constructors for builtins.int and native int types have the same behavior. In\n# interpreted mode, native int types are just aliases to 'int'.\nfor int_name in (\n    \"builtins.int\",\n    \"mypy_extensions.i64\",\n    \"mypy_extensions.i32\",\n    \"mypy_extensions.i16\",\n    \"mypy_extensions.u8\",\n):\n    # These int constructors produce object_rprimitives that then need to be unboxed\n    # I guess unboxing ourselves would save a check and branch though?\n\n    # Get the type object for 'builtins.int' or a native int type.\n    # For ordinary calls to int() we use a load_address to the type.\n    # Native ints don't have a separate type object -- we just use 'builtins.int'.\n    load_address_op(name=int_name, type=object_rprimitive, src=\"PyLong_Type\")\n\n    # int(float). We could do a bit better directly.\n    function_op(\n        name=int_name,\n        arg_types=[float_rprimitive],\n        return_type=int_rprimitive,\n        c_function_name=\"CPyTagged_FromFloat\",\n        error_kind=ERR_MAGIC,\n    )\n\n    # int(string)\n    function_op(\n        name=int_name,\n        arg_types=[str_rprimitive],\n        return_type=object_rprimitive,\n        c_function_name=\"CPyLong_FromStr\",\n        error_kind=ERR_MAGIC,\n    )\n\n    # int(string, base)\n    function_op(\n        name=int_name,\n        arg_types=[str_rprimitive, int_rprimitive],\n        return_type=object_rprimitive,\n        c_function_name=\"CPyLong_FromStrWithBase\",\n        error_kind=ERR_MAGIC,\n    )\n\nfor name in (\"builtins.str\", \"builtins.repr\"):\n    # str(int) and repr(int)\n    int_to_str_op = function_op(\n        name=name,\n        arg_types=[int_rprimitive],\n        return_type=str_rprimitive,\n        c_function_name=\"CPyTagged_Str\",\n        error_kind=ERR_MAGIC,\n        priority=2,\n    )\n    # We need a specialization for str on bools also since the int one is wrong...\n    function_op(\n        name=name,\n        arg_types=[bool_rprimitive],\n        return_type=str_rprimitive,\n        c_function_name=\"CPyBool_Str\",\n        error_kind=ERR_MAGIC,\n        priority=3,\n    )\n\nint_to_ascii_op = custom_op(\n    arg_types=[int_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyTagged_AsciiBytes\",\n    error_kind=ERR_MAGIC,\n)\n\n\ndef int_binary_primitive(\n    op: str, primitive_name: str, return_type: RType = int_rprimitive, error_kind: int = ERR_NEVER\n) -> PrimitiveDescription:\n    return binary_op(\n        name=op,\n        arg_types=[int_rprimitive, int_rprimitive],\n        return_type=return_type,\n        primitive_name=primitive_name,\n        error_kind=error_kind,\n    )\n\n\nint_eq = int_binary_primitive(op=\"==\", primitive_name=\"int_eq\", return_type=bit_rprimitive)\nint_ne = int_binary_primitive(op=\"!=\", primitive_name=\"int_ne\", return_type=bit_rprimitive)\nint_lt = int_binary_primitive(op=\"<\", primitive_name=\"int_lt\", return_type=bit_rprimitive)\nint_le = int_binary_primitive(op=\"<=\", primitive_name=\"int_le\", return_type=bit_rprimitive)\nint_gt = int_binary_primitive(op=\">\", primitive_name=\"int_gt\", return_type=bit_rprimitive)\nint_ge = int_binary_primitive(op=\">=\", primitive_name=\"int_ge\", return_type=bit_rprimitive)\n\n\ndef int_binary_op(\n    name: str,\n    c_function_name: str,\n    return_type: RType = int_rprimitive,\n    error_kind: int = ERR_NEVER,\n) -> None:\n    binary_op(\n        name=name,\n        arg_types=[int_rprimitive, int_rprimitive],\n        return_type=return_type,\n        c_function_name=c_function_name,\n        error_kind=error_kind,\n    )\n\n\n# Binary, unary and augmented assignment operations that operate on CPyTagged ints\n# are implemented as C functions.\n\nint_binary_op(\"+\", \"CPyTagged_Add\")\nint_binary_op(\"-\", \"CPyTagged_Subtract\")\nint_binary_op(\"*\", \"CPyTagged_Multiply\")\nint_binary_op(\"&\", \"CPyTagged_And\")\nint_binary_op(\"|\", \"CPyTagged_Or\")\nint_binary_op(\"^\", \"CPyTagged_Xor\")\n# Divide and remainder we honestly propagate errors from because they\n# can raise ZeroDivisionError\nint_binary_op(\"//\", \"CPyTagged_FloorDivide\", error_kind=ERR_MAGIC)\nint_binary_op(\"%\", \"CPyTagged_Remainder\", error_kind=ERR_MAGIC)\n# Negative shift counts raise an exception\nint_binary_op(\">>\", \"CPyTagged_Rshift\", error_kind=ERR_MAGIC)\nint_binary_op(\"<<\", \"CPyTagged_Lshift\", error_kind=ERR_MAGIC)\n\nint_binary_op(\n    \"/\", \"CPyTagged_TrueDivide\", return_type=float_rprimitive, error_kind=ERR_MAGIC_OVERLAPPING\n)\n\n# This should work because assignment operators are parsed differently\n# and the code in irbuild that handles it does the assignment\n# regardless of whether or not the operator works in place anyway.\nint_binary_op(\"+=\", \"CPyTagged_Add\")\nint_binary_op(\"-=\", \"CPyTagged_Subtract\")\nint_binary_op(\"*=\", \"CPyTagged_Multiply\")\nint_binary_op(\"&=\", \"CPyTagged_And\")\nint_binary_op(\"|=\", \"CPyTagged_Or\")\nint_binary_op(\"^=\", \"CPyTagged_Xor\")\nint_binary_op(\"//=\", \"CPyTagged_FloorDivide\", error_kind=ERR_MAGIC)\nint_binary_op(\"%=\", \"CPyTagged_Remainder\", error_kind=ERR_MAGIC)\nint_binary_op(\">>=\", \"CPyTagged_Rshift\", error_kind=ERR_MAGIC)\nint_binary_op(\"<<=\", \"CPyTagged_Lshift\", error_kind=ERR_MAGIC)\n\n\ndef int_unary_op(name: str, c_function_name: str) -> PrimitiveDescription:\n    return unary_op(\n        name=name,\n        arg_type=int_rprimitive,\n        return_type=int_rprimitive,\n        c_function_name=c_function_name,\n        error_kind=ERR_NEVER,\n    )\n\n\nint_neg_op = int_unary_op(\"-\", \"CPyTagged_Negate\")\nint_invert_op = int_unary_op(\"~\", \"CPyTagged_Invert\")\n\n\n# Primitives related to integer comparison operations:\n\n\n# Equals operation on two boxed tagged integers\nint_equal_ = custom_op(\n    arg_types=[int_rprimitive, int_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyTagged_IsEq_\",\n    error_kind=ERR_NEVER,\n    is_pure=True,\n)\n\n# Less than operation on two boxed tagged integers\nint_less_than_ = custom_op(\n    arg_types=[int_rprimitive, int_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyTagged_IsLt_\",\n    error_kind=ERR_NEVER,\n    is_pure=True,\n)\n\nint64_divide_op = custom_op(\n    arg_types=[int64_rprimitive, int64_rprimitive],\n    return_type=int64_rprimitive,\n    c_function_name=\"CPyInt64_Divide\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\nint64_mod_op = custom_op(\n    arg_types=[int64_rprimitive, int64_rprimitive],\n    return_type=int64_rprimitive,\n    c_function_name=\"CPyInt64_Remainder\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\nint32_divide_op = custom_op(\n    arg_types=[int32_rprimitive, int32_rprimitive],\n    return_type=int32_rprimitive,\n    c_function_name=\"CPyInt32_Divide\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\nint32_mod_op = custom_op(\n    arg_types=[int32_rprimitive, int32_rprimitive],\n    return_type=int32_rprimitive,\n    c_function_name=\"CPyInt32_Remainder\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\nint16_divide_op = custom_op(\n    arg_types=[int16_rprimitive, int16_rprimitive],\n    return_type=int16_rprimitive,\n    c_function_name=\"CPyInt16_Divide\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\nint16_mod_op = custom_op(\n    arg_types=[int16_rprimitive, int16_rprimitive],\n    return_type=int16_rprimitive,\n    c_function_name=\"CPyInt16_Remainder\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\n# Convert tagged int (as PyObject *) to i64\nint_to_int64_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=int64_rprimitive,\n    c_function_name=\"CPyLong_AsInt64\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\nssize_t_to_int_op = custom_op(\n    arg_types=[c_pyssize_t_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyTagged_FromSsize_t\",\n    error_kind=ERR_MAGIC,\n)\n\nint64_to_int_op = custom_op(\n    arg_types=[int64_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyTagged_FromInt64\",\n    error_kind=ERR_MAGIC,\n)\n\n# Convert tagged int (as PyObject *) to i32\nint_to_int32_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=int32_rprimitive,\n    c_function_name=\"CPyLong_AsInt32\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\nint32_overflow = custom_op(\n    arg_types=[],\n    return_type=void_rtype,\n    c_function_name=\"CPyInt32_Overflow\",\n    error_kind=ERR_ALWAYS,\n)\n\nint16_overflow = custom_op(\n    arg_types=[],\n    return_type=void_rtype,\n    c_function_name=\"CPyInt16_Overflow\",\n    error_kind=ERR_ALWAYS,\n)\n\nuint8_overflow = custom_op(\n    arg_types=[],\n    return_type=void_rtype,\n    c_function_name=\"CPyUInt8_Overflow\",\n    error_kind=ERR_ALWAYS,\n)\n\n# translate isinstance(obj, int)\nisinstance_int = function_op(\n    name=\"builtints.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PyLong_Check\",\n    error_kind=ERR_NEVER,\n)\n\n# specialized custom_op cases for int.to_bytes\n\n# int.to_bytes(length, \"big\")\n# int.to_bytes(length, \"big\", signed=...)\nint_to_big_endian_op = custom_op(\n    arg_types=[int_rprimitive, c_pyssize_t_rprimitive, bool_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyTagged_ToBigEndianBytes\",\n    error_kind=ERR_MAGIC,\n)\n\n# int.to_bytes(length, \"little\")\n# int.to_bytes(length, \"little\", signed=...)\nint_to_little_endian_op = custom_op(\n    arg_types=[int_rprimitive, c_pyssize_t_rprimitive, bool_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyTagged_ToLittleEndianBytes\",\n    error_kind=ERR_MAGIC,\n)\n\n# int.to_bytes(length, byteorder, signed=...)\nint_to_bytes_op = custom_op(\n    arg_types=[int_rprimitive, c_pyssize_t_rprimitive, str_rprimitive, bool_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPyTagged_ToBytes\",\n    error_kind=ERR_MAGIC,\n)\n\n# int.bit_length()\nmethod_op(\n    name=\"bit_length\",\n    arg_types=[int_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyTagged_BitLength\",\n    error_kind=ERR_MAGIC,\n)\n"
  },
  {
    "path": "mypyc/primitives/librt_strings_ops.py",
    "content": "from mypyc.ir.deps import BYTES_WRITER_EXTRA_OPS, LIBRT_STRINGS, STRING_WRITER_EXTRA_OPS\nfrom mypyc.ir.ops import ERR_MAGIC, ERR_MAGIC_OVERLAPPING, ERR_NEVER\nfrom mypyc.ir.rtypes import (\n    bool_rprimitive,\n    bytearray_rprimitive,\n    bytes_rprimitive,\n    bytes_writer_rprimitive,\n    float_rprimitive,\n    int16_rprimitive,\n    int32_rprimitive,\n    int64_rprimitive,\n    none_rprimitive,\n    short_int_rprimitive,\n    str_rprimitive,\n    string_writer_rprimitive,\n    uint8_rprimitive,\n    void_rtype,\n)\nfrom mypyc.primitives.registry import custom_primitive_op, function_op, method_op\n\nfunction_op(\n    name=\"librt.strings.BytesWriter\",\n    arg_types=[],\n    return_type=bytes_writer_rprimitive,\n    c_function_name=\"LibRTStrings_BytesWriter_internal\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS],\n)\n\nmethod_op(\n    name=\"getvalue\",\n    arg_types=[bytes_writer_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"LibRTStrings_BytesWriter_getvalue_internal\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS],\n)\n\nmethod_op(\n    name=\"write\",\n    arg_types=[bytes_writer_rprimitive, bytes_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_Write\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nmethod_op(\n    name=\"write\",\n    arg_types=[bytes_writer_rprimitive, bytearray_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_Write\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nmethod_op(\n    name=\"append\",\n    arg_types=[bytes_writer_rprimitive, uint8_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_Append\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nmethod_op(\n    name=\"truncate\",\n    arg_types=[bytes_writer_rprimitive, int64_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"LibRTStrings_BytesWriter_truncate_internal\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS],\n)\n\nfunction_op(\n    name=\"builtins.len\",\n    arg_types=[bytes_writer_rprimitive],\n    return_type=short_int_rprimitive,\n    c_function_name=\"CPyBytesWriter_Len\",\n    error_kind=ERR_NEVER,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\n# BytesWriter index adjustment - convert negative index to positive\nbytes_writer_adjust_index_op = custom_primitive_op(\n    name=\"bytes_writer_adjust_index\",\n    arg_types=[bytes_writer_rprimitive, int64_rprimitive],\n    return_type=int64_rprimitive,\n    c_function_name=\"CPyBytesWriter_AdjustIndex\",\n    error_kind=ERR_NEVER,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\n# BytesWriter range check - check if index is in valid range\nbytes_writer_range_check_op = custom_primitive_op(\n    name=\"bytes_writer_range_check\",\n    arg_types=[bytes_writer_rprimitive, int64_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyBytesWriter_RangeCheck\",\n    error_kind=ERR_NEVER,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\n# BytesWriter.__getitem__() - get byte at index (no bounds checking)\nbytes_writer_get_item_unsafe_op = custom_primitive_op(\n    name=\"bytes_writer_get_item\",\n    arg_types=[bytes_writer_rprimitive, int64_rprimitive],\n    return_type=uint8_rprimitive,\n    c_function_name=\"CPyBytesWriter_GetItem\",\n    error_kind=ERR_NEVER,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\n# BytesWriter.__setitem__() - set byte at index (no bounds checking)\nbytes_writer_set_item_unsafe_op = custom_primitive_op(\n    name=\"bytes_writer_set_item\",\n    arg_types=[bytes_writer_rprimitive, int64_rprimitive, uint8_rprimitive],\n    return_type=void_rtype,\n    c_function_name=\"CPyBytesWriter_SetItem\",\n    error_kind=ERR_NEVER,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\n# i16 write/read functions\n\nfunction_op(\n    name=\"librt.strings.write_i16_le\",\n    arg_types=[bytes_writer_rprimitive, int16_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_WriteI16LE\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.write_i16_be\",\n    arg_types=[bytes_writer_rprimitive, int16_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_WriteI16BE\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.read_i16_le\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=int16_rprimitive,\n    c_function_name=\"CPyBytes_ReadI16LE\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.read_i16_be\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=int16_rprimitive,\n    c_function_name=\"CPyBytes_ReadI16BE\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\n# i32 write/read functions\n\nfunction_op(\n    name=\"librt.strings.write_i32_le\",\n    arg_types=[bytes_writer_rprimitive, int32_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_WriteI32LE\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.write_i32_be\",\n    arg_types=[bytes_writer_rprimitive, int32_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_WriteI32BE\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.read_i32_le\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=int32_rprimitive,\n    c_function_name=\"CPyBytes_ReadI32LE\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.read_i32_be\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=int32_rprimitive,\n    c_function_name=\"CPyBytes_ReadI32BE\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\n# i64 write/read functions\n\nfunction_op(\n    name=\"librt.strings.write_i64_le\",\n    arg_types=[bytes_writer_rprimitive, int64_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_WriteI64LE\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.write_i64_be\",\n    arg_types=[bytes_writer_rprimitive, int64_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_WriteI64BE\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.read_i64_le\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=int64_rprimitive,\n    c_function_name=\"CPyBytes_ReadI64LE\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.read_i64_be\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=int64_rprimitive,\n    c_function_name=\"CPyBytes_ReadI64BE\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\n# f32 write/read functions\n\nfunction_op(\n    name=\"librt.strings.write_f32_le\",\n    arg_types=[bytes_writer_rprimitive, float_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_WriteF32LE\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.write_f32_be\",\n    arg_types=[bytes_writer_rprimitive, float_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_WriteF32BE\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.read_f32_le\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyBytes_ReadF32LE\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.read_f32_be\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyBytes_ReadF32BE\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\n# f64 write/read functions\n\nfunction_op(\n    name=\"librt.strings.write_f64_le\",\n    arg_types=[bytes_writer_rprimitive, float_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_WriteF64LE\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.write_f64_be\",\n    arg_types=[bytes_writer_rprimitive, float_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyBytesWriter_WriteF64BE\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.read_f64_le\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyBytes_ReadF64LE\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"librt.strings.read_f64_be\",\n    arg_types=[bytes_rprimitive, int64_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"CPyBytes_ReadF64BE\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, BYTES_WRITER_EXTRA_OPS],\n)\n\n# StringWriter operations\n\nfunction_op(\n    name=\"librt.strings.StringWriter\",\n    arg_types=[],\n    return_type=string_writer_rprimitive,\n    c_function_name=\"LibRTStrings_StringWriter_internal\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS],\n)\n\nmethod_op(\n    name=\"getvalue\",\n    arg_types=[string_writer_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"LibRTStrings_StringWriter_getvalue_internal\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS],\n)\n\nmethod_op(\n    name=\"write\",\n    arg_types=[string_writer_rprimitive, str_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"LibRTStrings_StringWriter_write_internal\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS],\n)\n\nmethod_op(\n    name=\"append\",\n    arg_types=[string_writer_rprimitive, int32_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"CPyStringWriter_Append\",\n    error_kind=ERR_MAGIC,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, STRING_WRITER_EXTRA_OPS],\n)\n\nfunction_op(\n    name=\"builtins.len\",\n    arg_types=[string_writer_rprimitive],\n    return_type=short_int_rprimitive,\n    c_function_name=\"CPyStringWriter_Len\",\n    error_kind=ERR_NEVER,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, STRING_WRITER_EXTRA_OPS],\n)\n\n# StringWriter index adjustment - convert negative index to positive\nstring_writer_adjust_index_op = custom_primitive_op(\n    name=\"string_writer_adjust_index\",\n    arg_types=[string_writer_rprimitive, int64_rprimitive],\n    return_type=int64_rprimitive,\n    c_function_name=\"CPyStringWriter_AdjustIndex\",\n    error_kind=ERR_NEVER,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, STRING_WRITER_EXTRA_OPS],\n)\n\n# StringWriter range check - check if index is in valid range\nstring_writer_range_check_op = custom_primitive_op(\n    name=\"string_writer_range_check\",\n    arg_types=[string_writer_rprimitive, int64_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyStringWriter_RangeCheck\",\n    error_kind=ERR_NEVER,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, STRING_WRITER_EXTRA_OPS],\n)\n\n# StringWriter.__getitem__() - get character at index (no bounds checking)\nstring_writer_get_item_unsafe_op = custom_primitive_op(\n    name=\"string_writer_get_item\",\n    arg_types=[string_writer_rprimitive, int64_rprimitive],\n    return_type=int32_rprimitive,\n    c_function_name=\"CPyStringWriter_GetItem\",\n    error_kind=ERR_NEVER,\n    experimental=True,\n    dependencies=[LIBRT_STRINGS, STRING_WRITER_EXTRA_OPS],\n)\n"
  },
  {
    "path": "mypyc/primitives/librt_time_ops.py",
    "content": "from mypyc.ir.deps import LIBRT_TIME\nfrom mypyc.ir.ops import ERR_MAGIC_OVERLAPPING\nfrom mypyc.ir.rtypes import float_rprimitive\nfrom mypyc.primitives.registry import function_op\n\nfunction_op(\n    name=\"librt.time.time\",\n    arg_types=[],\n    return_type=float_rprimitive,\n    c_function_name=\"LibRTTime_time\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n    experimental=True,\n    dependencies=[LIBRT_TIME],\n)\n"
  },
  {
    "path": "mypyc/primitives/librt_vecs_ops.py",
    "content": "from mypyc.ir.deps import LIBRT_VECS, VECS_EXTRA_OPS\nfrom mypyc.ir.ops import ERR_NEVER\nfrom mypyc.ir.rtypes import bit_rprimitive, object_rprimitive\nfrom mypyc.primitives.registry import function_op\n\n# isinstance(obj, vec)\nisinstance_vec = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyVec_Check\",\n    error_kind=ERR_NEVER,\n    experimental=True,\n    dependencies=[LIBRT_VECS, VECS_EXTRA_OPS],\n)\n"
  },
  {
    "path": "mypyc/primitives/list_ops.py",
    "content": "\"\"\"List primitive ops.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.ops import ERR_FALSE, ERR_MAGIC, ERR_NEVER\nfrom mypyc.ir.rtypes import (\n    bit_rprimitive,\n    c_int_rprimitive,\n    c_pyssize_t_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    list_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    short_int_rprimitive,\n    void_rtype,\n)\nfrom mypyc.primitives.registry import (\n    ERR_NEG_INT,\n    binary_op,\n    custom_op,\n    custom_primitive_op,\n    function_op,\n    load_address_op,\n    method_op,\n)\n\n# Get the 'builtins.list' type object.\nload_address_op(name=\"builtins.list\", type=object_rprimitive, src=\"PyList_Type\")\n\n# sorted(obj)\nfunction_op(\n    name=\"builtins.sorted\",\n    arg_types=[object_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"CPySequence_Sort\",\n    error_kind=ERR_MAGIC,\n)\n\n# list(obj)\nto_list = function_op(\n    name=\"builtins.list\",\n    arg_types=[object_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"PySequence_List\",\n    error_kind=ERR_MAGIC,\n)\n\n# Construct an empty list via list().\nfunction_op(\n    name=\"builtins.list\",\n    arg_types=[],\n    return_type=list_rprimitive,\n    c_function_name=\"PyList_New\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(0, int_rprimitive)],\n)\n\n# translate isinstance(obj, list)\nisinstance_list = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PyList_Check\",\n    error_kind=ERR_NEVER,\n)\n\nnew_list_op = custom_op(\n    arg_types=[c_pyssize_t_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"PyList_New\",\n    error_kind=ERR_MAGIC,\n)\n\nlist_build_op = custom_op(\n    arg_types=[c_pyssize_t_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"CPyList_Build\",\n    error_kind=ERR_MAGIC,\n    var_arg_type=object_rprimitive,\n    steals=True,\n)\n\n# Get pointer to list items (ob_item PyListObject field)\nlist_items = custom_primitive_op(\n    name=\"list_items\",\n    arg_types=[list_rprimitive],\n    return_type=pointer_rprimitive,\n    error_kind=ERR_NEVER,\n)\n\n# list[index] (for an integer index)\nlist_get_item_op = method_op(\n    name=\"__getitem__\",\n    arg_types=[list_rprimitive, int_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyList_GetItem\",\n    error_kind=ERR_MAGIC,\n)\n\n# list[index] version with no int tag check for when it is known to be short\nmethod_op(\n    name=\"__getitem__\",\n    arg_types=[list_rprimitive, short_int_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyList_GetItemShort\",\n    error_kind=ERR_MAGIC,\n    priority=2,\n)\n\n# list[index] that produces a borrowed result\nmethod_op(\n    name=\"__getitem__\",\n    arg_types=[list_rprimitive, int_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyList_GetItemBorrow\",\n    error_kind=ERR_MAGIC,\n    is_borrowed=True,\n    priority=3,\n)\n\n# list[index] that produces a borrowed result and index is known to be short\nmethod_op(\n    name=\"__getitem__\",\n    arg_types=[list_rprimitive, short_int_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyList_GetItemShortBorrow\",\n    error_kind=ERR_MAGIC,\n    is_borrowed=True,\n    priority=4,\n)\n\n# Version with native int index\nmethod_op(\n    name=\"__getitem__\",\n    arg_types=[list_rprimitive, int64_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyList_GetItemInt64\",\n    error_kind=ERR_MAGIC,\n    priority=5,\n)\n\n# Version with native int index\nmethod_op(\n    name=\"__getitem__\",\n    arg_types=[list_rprimitive, int64_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyList_GetItemInt64Borrow\",\n    is_borrowed=True,\n    error_kind=ERR_MAGIC,\n    priority=6,\n)\n\n# This is unsafe because it assumes that the index is a non-negative integer\n# that is in-bounds for the list.\nlist_get_item_unsafe_op = custom_primitive_op(\n    name=\"list_get_item_unsafe\",\n    arg_types=[list_rprimitive, c_pyssize_t_rprimitive],\n    return_type=object_rprimitive,\n    error_kind=ERR_NEVER,\n)\n\n# list[index] = obj\nlist_set_item_op = method_op(\n    name=\"__setitem__\",\n    arg_types=[list_rprimitive, int_rprimitive, object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyList_SetItem\",\n    error_kind=ERR_FALSE,\n    steals=[False, False, True],\n)\n\n# list[index_i64] = obj\nmethod_op(\n    name=\"__setitem__\",\n    arg_types=[list_rprimitive, int64_rprimitive, object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyList_SetItemInt64\",\n    error_kind=ERR_FALSE,\n    steals=[False, False, True],\n    priority=2,\n)\n\n# PyList_SET_ITEM does no error checking,\n# and should only be used to fill in brand new lists.\nnew_list_set_item_op = custom_op(\n    arg_types=[list_rprimitive, c_pyssize_t_rprimitive, object_rprimitive],\n    return_type=void_rtype,\n    c_function_name=\"CPyList_SetItemUnsafe\",\n    error_kind=ERR_NEVER,\n    steals=[False, False, True],\n)\n\n# list.append(obj)\nlist_append_op = method_op(\n    name=\"append\",\n    arg_types=[list_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyList_Append\",\n    error_kind=ERR_NEG_INT,\n)\n\n# list.extend(obj)\nlist_extend_op = method_op(\n    name=\"extend\",\n    arg_types=[list_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyList_Extend\",\n    error_kind=ERR_MAGIC,\n)\n\n# list.pop()\nlist_pop_last = method_op(\n    name=\"pop\",\n    arg_types=[list_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyList_PopLast\",\n    error_kind=ERR_MAGIC,\n)\n\n# list.pop(index)\nmethod_op(\n    name=\"pop\",\n    arg_types=[list_rprimitive, int_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyList_Pop\",\n    error_kind=ERR_MAGIC,\n)\n\n# list.count(obj)\nmethod_op(\n    name=\"count\",\n    arg_types=[list_rprimitive, object_rprimitive],\n    return_type=short_int_rprimitive,\n    c_function_name=\"CPyList_Count\",\n    error_kind=ERR_MAGIC,\n)\n\n# list.insert(index, obj)\nmethod_op(\n    name=\"insert\",\n    arg_types=[list_rprimitive, int_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyList_Insert\",\n    error_kind=ERR_NEG_INT,\n)\n\n# list.sort()\nmethod_op(\n    name=\"sort\",\n    arg_types=[list_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyList_Sort\",\n    error_kind=ERR_NEG_INT,\n)\n\n# list.reverse()\nmethod_op(\n    name=\"reverse\",\n    arg_types=[list_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyList_Reverse\",\n    error_kind=ERR_NEG_INT,\n)\n\n# list.remove(obj)\nmethod_op(\n    name=\"remove\",\n    arg_types=[list_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyList_Remove\",\n    error_kind=ERR_NEG_INT,\n)\n\n# list.index(obj)\nmethod_op(\n    name=\"index\",\n    arg_types=[list_rprimitive, object_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyList_Index\",\n    error_kind=ERR_MAGIC,\n)\n\n# list.clear()\nmethod_op(\n    name=\"clear\",\n    arg_types=[list_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyList_Clear\",\n    error_kind=ERR_FALSE,\n)\n\n# list.copy()\nmethod_op(\n    name=\"copy\",\n    arg_types=[list_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"CPyList_Copy\",\n    error_kind=ERR_MAGIC,\n)\n\n# list + list\nbinary_op(\n    name=\"+\",\n    arg_types=[list_rprimitive, list_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"PySequence_Concat\",\n    error_kind=ERR_MAGIC,\n)\n\n# list += list\nbinary_op(\n    name=\"+=\",\n    arg_types=[list_rprimitive, object_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"PySequence_InPlaceConcat\",\n    error_kind=ERR_MAGIC,\n)\n\n# list * int\nbinary_op(\n    name=\"*\",\n    arg_types=[list_rprimitive, int_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"CPySequence_Multiply\",\n    error_kind=ERR_MAGIC,\n)\n\n# int * list\nbinary_op(\n    name=\"*\",\n    arg_types=[int_rprimitive, list_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"CPySequence_RMultiply\",\n    error_kind=ERR_MAGIC,\n)\n\n# list *= int\nbinary_op(\n    name=\"*=\",\n    arg_types=[list_rprimitive, int_rprimitive],\n    return_type=list_rprimitive,\n    c_function_name=\"CPySequence_InPlaceMultiply\",\n    error_kind=ERR_MAGIC,\n)\n\n# list[begin:end]\nlist_slice_op = custom_op(\n    arg_types=[list_rprimitive, int_rprimitive, int_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyList_GetSlice\",\n    error_kind=ERR_MAGIC,\n)\n\nsupports_sequence_protocol = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPySequence_Check\",\n    error_kind=ERR_NEVER,\n)\n\nsequence_get_item = custom_op(\n    arg_types=[object_rprimitive, c_pyssize_t_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PySequence_GetItem\",\n    error_kind=ERR_NEVER,\n)\n\nsequence_get_slice = custom_op(\n    arg_types=[object_rprimitive, c_pyssize_t_rprimitive, c_pyssize_t_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PySequence_GetSlice\",\n    error_kind=ERR_MAGIC,\n)\n"
  },
  {
    "path": "mypyc/primitives/misc_ops.py",
    "content": "\"\"\"Miscellaneous primitive ops.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.deps import LIBRT_BASE64\nfrom mypyc.ir.ops import ERR_FALSE, ERR_MAGIC, ERR_MAGIC_OVERLAPPING, ERR_NEVER\nfrom mypyc.ir.rtypes import (\n    KNOWN_NATIVE_TYPES,\n    RUnion,\n    bit_rprimitive,\n    bool_rprimitive,\n    bytes_rprimitive,\n    c_int_rprimitive,\n    c_pointer_rprimitive,\n    c_pyssize_t_rprimitive,\n    cstring_rprimitive,\n    dict_rprimitive,\n    float_rprimitive,\n    int_rprimitive,\n    none_rprimitive,\n    object_pointer_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    str_rprimitive,\n    uint8_rprimitive,\n    void_rtype,\n)\nfrom mypyc.primitives.registry import (\n    ERR_NEG_INT,\n    custom_op,\n    custom_primitive_op,\n    function_op,\n    load_address_op,\n    method_op,\n)\n\n# Get the 'bool' type object.\nload_address_op(name=\"builtins.bool\", type=object_rprimitive, src=\"PyBool_Type\")\n\n# Get the 'range' type object.\nload_address_op(name=\"builtins.range\", type=object_rprimitive, src=\"PyRange_Type\")\n\n# Get the boxed Python 'None' object\nnone_object_op = load_address_op(name=\"Py_None\", type=object_rprimitive, src=\"_Py_NoneStruct\")\n\n# Get the boxed object '...'\nellipsis_op = load_address_op(name=\"...\", type=object_rprimitive, src=\"_Py_EllipsisObject\")\n\n# Get the boxed NotImplemented object\nnot_implemented_op = load_address_op(\n    name=\"builtins.NotImplemented\", type=object_rprimitive, src=\"_Py_NotImplementedStruct\"\n)\n\n# Get the boxed StopAsyncIteration object\nstop_async_iteration_op = load_address_op(\n    name=\"builtins.StopAsyncIteration\", type=object_rprimitive, src=\"PyExc_StopAsyncIteration\"\n)\n\n# id(obj)\nfunction_op(\n    name=\"builtins.id\",\n    arg_types=[object_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyTagged_Id\",\n    error_kind=ERR_NEVER,\n)\n\n# Return the result of obj.__await()__ or obj.__iter__() (if no __await__ exists)\ncoro_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPy_GetCoro\",\n    error_kind=ERR_MAGIC,\n)\n\n# Do obj.send(value), or a next(obj) if second arg is None.\n# (This behavior is to match the PEP 380 spec for yield from.)\n# Like next_raw_op, don't swallow StopIteration,\n# but also don't propagate an error.\n# Can return NULL: see next_op.\nsend_op = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyIter_Send\",\n    error_kind=ERR_NEVER,\n)\n\n# This is sort of unfortunate but oh well: yield_from_except performs most of the\n# error handling logic in `yield from` operations. It returns a bool and passes\n# a value by address.\n# If the bool is true, then a StopIteration was received and we should return.\n# If the bool is false, then the value should be yielded.\n# The normal case is probably that it signals an exception, which gets\n# propagated.\n# Op used for \"yield from\" error handling.\n# See comment in CPy_YieldFromErrorHandle for more information.\nyield_from_except_op = custom_op(\n    arg_types=[object_rprimitive, object_pointer_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPy_YieldFromErrorHandle\",\n    error_kind=ERR_MAGIC,\n)\n\n# Create method object from a callable object and self.\nmethod_new_op = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyMethod_New\",\n    error_kind=ERR_MAGIC,\n)\n\n# Check if the current exception is a StopIteration and return its value if so.\n# Treats \"no exception\" as StopIteration with a None value.\n# If it is a different exception, re-reraise it.\ncheck_stop_op = custom_op(\n    arg_types=[],\n    return_type=object_rprimitive,\n    c_function_name=\"CPy_FetchStopIterationValue\",\n    error_kind=ERR_MAGIC,\n)\n\n# Determine the most derived metaclass and check for metaclass conflicts.\n# Arguments are (metaclass, bases).\npy_calc_meta_op = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPy_CalculateMetaclass\",\n    error_kind=ERR_MAGIC,\n    is_borrowed=True,\n)\n\n# Import a module (plain)\nimport_op = custom_op(\n    arg_types=[str_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyImport_Import\",\n    error_kind=ERR_MAGIC,\n)\n\n# Table-driven import op.\nimport_many_op = custom_op(\n    arg_types=[\n        object_rprimitive,\n        c_pointer_rprimitive,\n        object_rprimitive,\n        object_rprimitive,\n        object_rprimitive,\n        c_pointer_rprimitive,\n    ],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyImport_ImportMany\",\n    error_kind=ERR_FALSE,\n)\n\n# From import helper op\nimport_from_many_op = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyImport_ImportFromMany\",\n    error_kind=ERR_MAGIC,\n)\n\n# Get the sys.modules dictionary\nget_module_dict_op = custom_op(\n    arg_types=[],\n    return_type=dict_rprimitive,\n    c_function_name=\"PyImport_GetModuleDict\",\n    error_kind=ERR_NEVER,\n    is_borrowed=True,\n)\n\n# isinstance(obj, cls)\nslow_isinstance_op = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyObject_IsInstance\",\n    error_kind=ERR_NEG_INT,\n    truncated_type=bool_rprimitive,\n)\n\n# Faster isinstance(obj, cls) that only works with native classes and doesn't perform\n# type checking of the type argument.\nfast_isinstance_op = function_op(\n    \"builtins.isinstance\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPy_TypeCheck\",\n    error_kind=ERR_NEVER,\n    priority=0,\n)\n\n# bool(obj) with unboxed result\nbool_op = function_op(\n    name=\"builtins.bool\",\n    arg_types=[object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyObject_IsTrue\",\n    error_kind=ERR_NEG_INT,\n    truncated_type=bool_rprimitive,\n)\n\n# isinstance(obj, bool)\nisinstance_bool = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PyBool_Check\",\n    error_kind=ERR_NEVER,\n)\n\n# slice(start, stop, step)\nnew_slice_op = function_op(\n    name=\"builtins.slice\",\n    arg_types=[object_rprimitive, object_rprimitive, object_rprimitive],\n    c_function_name=\"PySlice_New\",\n    return_type=object_rprimitive,\n    error_kind=ERR_MAGIC,\n)\n\n# type(obj)\ntype_op = function_op(\n    name=\"builtins.type\",\n    arg_types=[object_rprimitive],\n    c_function_name=\"CPy_TYPE\",\n    return_type=object_rprimitive,\n    error_kind=ERR_NEVER,\n)\n\n# Get 'builtins.type' (base class of all classes)\ntype_object_op = load_address_op(name=\"builtins.type\", type=object_rprimitive, src=\"PyType_Type\")\n\n# Create a heap type based on a template non-heap type.\n# See CPyType_FromTemplate for more docs.\npytype_from_template_op = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive, str_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyType_FromTemplate\",\n    error_kind=ERR_MAGIC,\n)\n\n# Call __init_subclass__ on a type. Separated from CPyType_FromTemplate\n# so that class attributes can be set before __init_subclass__ is called.\npy_init_subclass_op = custom_op(\n    arg_types=[object_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPy_InitSubclass\",\n    error_kind=ERR_FALSE,\n)\n\n# Create a dataclass from an extension class. See\n# CPyDataclass_SleightOfHand for more docs.\ndataclass_sleight_of_hand = custom_op(\n    arg_types=[\n        object_rprimitive,\n        object_rprimitive,\n        dict_rprimitive,\n        dict_rprimitive,\n        str_rprimitive,\n    ],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyDataclass_SleightOfHand\",\n    error_kind=ERR_FALSE,\n)\n\n# Raise ValueError if length of first argument is not equal to the second argument.\n# The first argument must be a list or a variable-length tuple.\ncheck_unpack_count_op = custom_op(\n    arg_types=[object_rprimitive, c_pyssize_t_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPySequence_CheckUnpackCount\",\n    error_kind=ERR_NEG_INT,\n)\n\n\n# Register an implementation for a singledispatch function\nregister_function = custom_op(\n    arg_types=[object_rprimitive, object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPySingledispatch_RegisterFunction\",\n    error_kind=ERR_MAGIC,\n)\n\n\n# Initialize a PyObject * item in a memory buffer (steal the value)\nbuf_init_item = custom_primitive_op(\n    name=\"buf_init_item\",\n    arg_types=[pointer_rprimitive, c_pyssize_t_rprimitive, object_rprimitive],\n    return_type=void_rtype,\n    error_kind=ERR_NEVER,\n    steals=[False, False, True],\n)\n\n# Get length of PyVarObject instance (e.g. list or tuple)\nvar_object_size = custom_primitive_op(\n    name=\"var_object_size\",\n    arg_types=[object_rprimitive],\n    return_type=c_pyssize_t_rprimitive,\n    error_kind=ERR_NEVER,\n)\n\n# Set the lazy value compute function of an TypeAliasType instance (Python 3.12+).\n# This must only be used as part of initializing the object. Any existing value\n# will be cleared.\nset_type_alias_compute_function_op = custom_primitive_op(\n    name=\"set_type_alias_compute_function\",\n    c_function_name=\"CPy_SetTypeAliasTypeComputeFunction\",\n    # (alias object, value compute function)\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=void_rtype,\n    error_kind=ERR_NEVER,\n)\n\ndebug_print_op = custom_primitive_op(\n    name=\"debug_print\",\n    c_function_name=\"CPyDebug_PrintObject\",\n    arg_types=[object_rprimitive],\n    return_type=void_rtype,\n    error_kind=ERR_NEVER,\n)\n\n# Log an event to a trace log, which is written to a file during execution.\nlog_trace_event = custom_primitive_op(\n    name=\"log_trace_event\",\n    c_function_name=\"CPyTrace_LogEvent\",\n    # (fullname of function/location, line number, operation name, operation details)\n    arg_types=[cstring_rprimitive, cstring_rprimitive, cstring_rprimitive, cstring_rprimitive],\n    return_type=void_rtype,\n    error_kind=ERR_NEVER,\n)\n\n# Mark object as immortal -- it won't be freed via reference counting, as\n# the reference count won't be updated any longer. Immortal objects support\n# fast concurrent read-only access from multiple threads when using free\n# threading, since this eliminates contention from concurrent reference count\n# updates.\n#\n# Needs at least Python 3.14.\nset_immortal_op = custom_primitive_op(\n    name=\"set_immmortal\",\n    c_function_name=\"CPy_SetImmortal\",\n    arg_types=[object_rprimitive],\n    return_type=void_rtype,\n    error_kind=ERR_NEVER,\n)\n\nwrite_buffer_rprimitive = KNOWN_NATIVE_TYPES[\"librt.internal.WriteBuffer\"]\nread_buffer_rprimitive = KNOWN_NATIVE_TYPES[\"librt.internal.ReadBuffer\"]\n\n# ReadBuffer(source)\nfunction_op(\n    name=\"librt.internal.ReadBuffer\",\n    arg_types=[bytes_rprimitive],\n    return_type=read_buffer_rprimitive,\n    c_function_name=\"ReadBuffer_internal\",\n    error_kind=ERR_MAGIC,\n)\n\n# WriteBuffer()\nfunction_op(\n    name=\"librt.internal.WriteBuffer\",\n    arg_types=[],\n    return_type=write_buffer_rprimitive,\n    c_function_name=\"WriteBuffer_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nmethod_op(\n    name=\"getvalue\",\n    arg_types=[write_buffer_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"WriteBuffer_getvalue_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.write_bool\",\n    arg_types=[object_rprimitive, bool_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"write_bool_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.read_bool\",\n    arg_types=[object_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"read_bool_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.write_str\",\n    arg_types=[object_rprimitive, str_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"write_str_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.read_str\",\n    arg_types=[object_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"read_str_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.write_bytes\",\n    arg_types=[object_rprimitive, bytes_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"write_bytes_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.read_bytes\",\n    arg_types=[object_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"read_bytes_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.write_float\",\n    arg_types=[object_rprimitive, float_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"write_float_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.read_float\",\n    arg_types=[object_rprimitive],\n    return_type=float_rprimitive,\n    c_function_name=\"read_float_internal\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\nfunction_op(\n    name=\"librt.internal.write_int\",\n    arg_types=[object_rprimitive, int_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"write_int_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.read_int\",\n    arg_types=[object_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"read_int_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.write_tag\",\n    arg_types=[object_rprimitive, uint8_rprimitive],\n    return_type=none_rprimitive,\n    c_function_name=\"write_tag_internal\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"librt.internal.read_tag\",\n    arg_types=[object_rprimitive],\n    return_type=uint8_rprimitive,\n    c_function_name=\"read_tag_internal\",\n    error_kind=ERR_MAGIC_OVERLAPPING,\n)\n\nfunction_op(\n    name=\"librt.internal.cache_version\",\n    arg_types=[],\n    return_type=uint8_rprimitive,\n    c_function_name=\"cache_version_internal\",\n    error_kind=ERR_NEVER,\n)\n\nfunction_op(\n    name=\"librt.base64.b64encode\",\n    arg_types=[bytes_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"LibRTBase64_b64encode_internal\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(0, bool_rprimitive)],\n    experimental=True,\n    dependencies=[LIBRT_BASE64],\n)\n\nfunction_op(\n    name=\"librt.base64.urlsafe_b64encode\",\n    arg_types=[bytes_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"LibRTBase64_b64encode_internal\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(1, bool_rprimitive)],\n    experimental=True,\n    dependencies=[LIBRT_BASE64],\n)\n\nfunction_op(\n    name=\"librt.base64.b64decode\",\n    arg_types=[RUnion([bytes_rprimitive, str_rprimitive])],\n    return_type=bytes_rprimitive,\n    c_function_name=\"LibRTBase64_b64decode_internal\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(0, bool_rprimitive)],\n    experimental=True,\n    dependencies=[LIBRT_BASE64],\n)\n\nfunction_op(\n    name=\"librt.base64.urlsafe_b64decode\",\n    arg_types=[RUnion([bytes_rprimitive, str_rprimitive])],\n    return_type=bytes_rprimitive,\n    c_function_name=\"LibRTBase64_b64decode_internal\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(1, bool_rprimitive)],\n    experimental=True,\n    dependencies=[LIBRT_BASE64],\n)\n\ncpyfunction_get_name = function_op(\n    name=\"CPyFunction_get_name\",\n    arg_types=[object_rprimitive, c_pointer_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyFunction_get_name\",\n    error_kind=ERR_MAGIC,\n)\n\ncpyfunction_set_name = function_op(\n    name=\"CPyFunction_set_name\",\n    arg_types=[object_rprimitive, object_rprimitive, c_pointer_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyFunction_set_name\",\n    error_kind=ERR_NEG_INT,\n)\n\ncpyfunction_get_code = function_op(\n    name=\"CPyFunction_get_code\",\n    arg_types=[object_rprimitive, c_pointer_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyFunction_get_code\",\n    error_kind=ERR_MAGIC,\n)\n\ncpyfunction_get_defaults = function_op(\n    name=\"CPyFunction_get_defaults\",\n    arg_types=[object_rprimitive, c_pointer_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyFunction_get_defaults\",\n    error_kind=ERR_MAGIC,\n)\n\ncpyfunction_get_kwdefaults = function_op(\n    name=\"CPyFunction_get_kwdefaults\",\n    arg_types=[object_rprimitive, c_pointer_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyFunction_get_kwdefaults\",\n    error_kind=ERR_MAGIC,\n)\n\ncpyfunction_get_annotations = function_op(\n    name=\"CPyFunction_get_annotations\",\n    arg_types=[object_rprimitive, c_pointer_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyFunction_get_annotations\",\n    error_kind=ERR_MAGIC,\n)\n\ncpyfunction_set_annotations = function_op(\n    name=\"CPyFunction_set_annotations\",\n    arg_types=[object_rprimitive, object_rprimitive, c_pointer_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyFunction_set_annotations\",\n    error_kind=ERR_NEG_INT,\n)\n"
  },
  {
    "path": "mypyc/primitives/registry.py",
    "content": "\"\"\"Utilities for defining primitive ops.\n\nMost of the ops can be automatically generated by matching against AST\nnodes and types. For example, a func_op is automatically generated when\na specific function is called with the specific positional argument\ncount and argument types.\n\nExample op definition:\n\nlist_len_op = function_op(name='builtins.len',\n                          arg_types=[list_rprimitive],\n                          result_type=short_int_rprimitive,\n                          error_kind=ERR_NEVER,\n                          c_function_name=\"...\")\n\nThis op is automatically generated for calls to len() with a single\nlist argument. The result type is short_int_rprimitive, and this\nnever raises an exception (ERR_NEVER). The function c_function_name is\ncalled when generating C for this op.  The op can also be manually generated\nusing \"list_len_op\". Ops that are only generated automatically don't need to\nbe assigned to a module attribute.\n\nOps defined with custom[_primitive]_op are only explicitly generated in\nmypyc.irbuild and won't be generated automatically. They are always\nassigned to a module attribute, as otherwise they won't be accessible.\n\nThe actual ops are defined in other submodules of this package, grouped\nby category.\n\nMost operations have fallback implementations that apply to all possible\narguments and types. For example, there are generic implementations of\narbitrary function and method calls, and binary operators. These generic\nimplementations are typically slower than specialized ones, but we tend\nto rely on them for infrequently used ops. It's impractical to have\noptimized implementations of all ops.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final, NamedTuple\n\nfrom mypyc.ir.deps import Dependency\nfrom mypyc.ir.ops import PrimitiveDescription, StealsDescription\nfrom mypyc.ir.rtypes import RType\n\n# Error kind for functions that return negative integer on exception. This\n# is only used for primitives. We translate it away during IR building.\nERR_NEG_INT: Final = 10\n\n\nclass CFunctionDescription(NamedTuple):\n    name: str\n    arg_types: list[RType]\n    return_type: RType\n    var_arg_type: RType | None\n    truncated_type: RType | None\n    c_function_name: str\n    error_kind: int\n    steals: StealsDescription\n    is_borrowed: bool\n    ordering: list[int] | None\n    extra_int_constants: list[tuple[int, RType]]\n    priority: int\n    is_pure: bool\n    returns_null: bool\n    dependencies: list[Dependency] | None\n\n\n# A description for C load operations including LoadGlobal and LoadAddress\nclass LoadAddressDescription(NamedTuple):\n    name: str\n    type: RType\n    src: str  # name of the target to load\n\n\n# Primitive ops for method call (such as 'str.join')\nmethod_call_ops: dict[str, list[PrimitiveDescription]] = {}\n\n# Primitive ops for top level function call (such as 'builtins.list')\nfunction_ops: dict[str, list[PrimitiveDescription]] = {}\n\n# Primitive ops for binary operations\nbinary_ops: dict[str, list[PrimitiveDescription]] = {}\n\n# Primitive ops for unary ops\nunary_ops: dict[str, list[PrimitiveDescription]] = {}\n\nbuiltin_names: dict[str, tuple[RType, str]] = {}\n\n\ndef method_op(\n    name: str,\n    arg_types: list[RType],\n    return_type: RType,\n    c_function_name: str,\n    error_kind: int,\n    var_arg_type: RType | None = None,\n    truncated_type: RType | None = None,\n    ordering: list[int] | None = None,\n    extra_int_constants: list[tuple[int, RType]] | None = None,\n    steals: StealsDescription = False,\n    is_borrowed: bool = False,\n    priority: int = 1,\n    is_pure: bool = False,\n    experimental: bool = False,\n    dependencies: list[Dependency] | None = None,\n) -> PrimitiveDescription:\n    \"\"\"Define a c function call op that replaces a method call.\n\n    This will be automatically generated by matching against the AST.\n\n    Args:\n        name: short name of the method (for example, 'append')\n        arg_types: argument types; the receiver is always the first argument\n        return_type: type of the return value. Use void_rtype to represent void.\n        c_function_name: name of the C function to call\n        error_kind: how errors are represented in the result (one of ERR_*)\n        var_arg_type: type of all variable arguments\n        truncated_type: type to truncated to(See Truncate for info)\n                        if it's defined both return_type and it should be non-referenced\n                        integer types or bool type\n        ordering: optional ordering of the arguments, if defined,\n                  reorders the arguments accordingly.\n                  should never be used together with var_arg_type.\n                  all the other arguments(such as arg_types) are in the order\n                  accepted by the python syntax(before reordering)\n        extra_int_constants: optional extra integer constants as the last arguments to a C call\n        steals: description of arguments that this steals (ref count wise)\n        is_borrowed: if True, returned value is borrowed (no need to decrease refcount)\n        priority: if multiple ops match, the one with the highest priority is picked\n        is_pure: if True, declare that the C function has no side effects, takes immutable\n                 arguments, and never raises an exception\n    \"\"\"\n    if extra_int_constants is None:\n        extra_int_constants = []\n    ops = method_call_ops.setdefault(name, [])\n    desc = PrimitiveDescription(\n        name,\n        arg_types,\n        return_type,\n        var_arg_type,\n        truncated_type,\n        c_function_name,\n        error_kind,\n        steals,\n        is_borrowed,\n        ordering,\n        extra_int_constants,\n        priority,\n        is_pure=is_pure,\n        experimental=experimental,\n        dependencies=dependencies,\n    )\n    ops.append(desc)\n    return desc\n\n\ndef function_op(\n    name: str,\n    arg_types: list[RType],\n    return_type: RType,\n    c_function_name: str,\n    error_kind: int,\n    var_arg_type: RType | None = None,\n    truncated_type: RType | None = None,\n    ordering: list[int] | None = None,\n    extra_int_constants: list[tuple[int, RType]] | None = None,\n    steals: StealsDescription = False,\n    is_borrowed: bool = False,\n    priority: int = 1,\n    experimental: bool = False,\n    dependencies: list[Dependency] | None = None,\n) -> PrimitiveDescription:\n    \"\"\"Define a C function call op that replaces a function call.\n\n    This will be automatically generated by matching against the AST.\n\n    Most arguments are similar to method_op().\n\n    Args:\n        name: full name of the function\n        arg_types: positional argument types for which this applies\n    \"\"\"\n    if extra_int_constants is None:\n        extra_int_constants = []\n    ops = function_ops.setdefault(name, [])\n    desc = PrimitiveDescription(\n        name,\n        arg_types,\n        return_type,\n        var_arg_type=var_arg_type,\n        truncated_type=truncated_type,\n        c_function_name=c_function_name,\n        error_kind=error_kind,\n        steals=steals,\n        is_borrowed=is_borrowed,\n        ordering=ordering,\n        extra_int_constants=extra_int_constants,\n        priority=priority,\n        is_pure=False,\n        experimental=experimental,\n        dependencies=dependencies,\n    )\n    ops.append(desc)\n    return desc\n\n\ndef binary_op(\n    name: str,\n    arg_types: list[RType],\n    return_type: RType,\n    error_kind: int,\n    c_function_name: str | None = None,\n    primitive_name: str | None = None,\n    var_arg_type: RType | None = None,\n    truncated_type: RType | None = None,\n    ordering: list[int] | None = None,\n    extra_int_constants: list[tuple[int, RType]] | None = None,\n    steals: StealsDescription = False,\n    is_borrowed: bool = False,\n    priority: int = 1,\n    dependencies: list[Dependency] | None = None,\n) -> PrimitiveDescription:\n    \"\"\"Define a c function call op for a binary operation.\n\n    This will be automatically generated by matching against the AST.\n\n    Most arguments are similar to method_op(), but exactly two argument types\n    are expected.\n    \"\"\"\n    assert c_function_name is not None or primitive_name is not None\n    assert not (c_function_name is not None and primitive_name is not None)\n    if extra_int_constants is None:\n        extra_int_constants = []\n    ops = binary_ops.setdefault(name, [])\n    desc = PrimitiveDescription(\n        name=primitive_name or name,\n        arg_types=arg_types,\n        return_type=return_type,\n        var_arg_type=var_arg_type,\n        truncated_type=truncated_type,\n        c_function_name=c_function_name,\n        error_kind=error_kind,\n        steals=steals,\n        is_borrowed=is_borrowed,\n        ordering=ordering,\n        extra_int_constants=extra_int_constants,\n        priority=priority,\n        is_pure=False,\n        experimental=False,\n        dependencies=dependencies,\n    )\n    ops.append(desc)\n    return desc\n\n\ndef custom_op(\n    arg_types: list[RType],\n    return_type: RType,\n    c_function_name: str,\n    error_kind: int,\n    var_arg_type: RType | None = None,\n    truncated_type: RType | None = None,\n    ordering: list[int] | None = None,\n    extra_int_constants: list[tuple[int, RType]] | None = None,\n    steals: StealsDescription = False,\n    is_borrowed: bool = False,\n    *,\n    is_pure: bool = False,\n    returns_null: bool = False,\n) -> CFunctionDescription:\n    \"\"\"Create a one-off CallC op that can't be automatically generated from the AST.\n\n    Most arguments are similar to method_op().\n    \"\"\"\n    if extra_int_constants is None:\n        extra_int_constants = []\n    return CFunctionDescription(\n        \"<custom>\",\n        arg_types,\n        return_type,\n        var_arg_type,\n        truncated_type,\n        c_function_name,\n        error_kind,\n        steals,\n        is_borrowed,\n        ordering,\n        extra_int_constants,\n        0,\n        is_pure=is_pure,\n        returns_null=returns_null,\n        dependencies=None,\n    )\n\n\ndef custom_primitive_op(\n    name: str,\n    arg_types: list[RType],\n    return_type: RType,\n    error_kind: int,\n    c_function_name: str | None = None,\n    var_arg_type: RType | None = None,\n    truncated_type: RType | None = None,\n    ordering: list[int] | None = None,\n    extra_int_constants: list[tuple[int, RType]] | None = None,\n    steals: StealsDescription = False,\n    is_borrowed: bool = False,\n    is_pure: bool = False,\n    experimental: bool = False,\n    dependencies: list[Dependency] | None = None,\n) -> PrimitiveDescription:\n    \"\"\"Define a primitive op that can't be automatically generated based on the AST.\n\n    Most arguments are similar to method_op().\n    \"\"\"\n    if extra_int_constants is None:\n        extra_int_constants = []\n    return PrimitiveDescription(\n        name=name,\n        arg_types=arg_types,\n        return_type=return_type,\n        var_arg_type=var_arg_type,\n        truncated_type=truncated_type,\n        c_function_name=c_function_name,\n        error_kind=error_kind,\n        steals=steals,\n        is_borrowed=is_borrowed,\n        ordering=ordering,\n        extra_int_constants=extra_int_constants,\n        priority=0,\n        is_pure=is_pure,\n        experimental=experimental,\n        dependencies=dependencies,\n    )\n\n\ndef unary_op(\n    name: str,\n    arg_type: RType,\n    return_type: RType,\n    c_function_name: str,\n    error_kind: int,\n    truncated_type: RType | None = None,\n    ordering: list[int] | None = None,\n    extra_int_constants: list[tuple[int, RType]] | None = None,\n    steals: StealsDescription = False,\n    is_borrowed: bool = False,\n    priority: int = 1,\n    is_pure: bool = False,\n    dependencies: list[Dependency] | None = None,\n) -> PrimitiveDescription:\n    \"\"\"Define a primitive op for an unary operation.\n\n    This will be automatically generated by matching against the AST.\n\n    Most arguments are similar to method_op(), but exactly one argument type\n    is expected.\n    \"\"\"\n    if extra_int_constants is None:\n        extra_int_constants = []\n    ops = unary_ops.setdefault(name, [])\n    desc = PrimitiveDescription(\n        name,\n        [arg_type],\n        return_type,\n        var_arg_type=None,\n        truncated_type=truncated_type,\n        c_function_name=c_function_name,\n        error_kind=error_kind,\n        steals=steals,\n        is_borrowed=is_borrowed,\n        ordering=ordering,\n        extra_int_constants=extra_int_constants,\n        priority=priority,\n        is_pure=is_pure,\n        experimental=False,\n        dependencies=dependencies,\n    )\n    ops.append(desc)\n    return desc\n\n\ndef load_address_op(name: str, type: RType, src: str) -> LoadAddressDescription:\n    assert name not in builtin_names, \"already defined: %s\" % name\n    builtin_names[name] = (type, src)\n    return LoadAddressDescription(name, type, src)\n\n\n# Import various modules that set up global state.\nimport mypyc.primitives.bytearray_ops\nimport mypyc.primitives.bytes_ops\nimport mypyc.primitives.dict_ops\nimport mypyc.primitives.float_ops\nimport mypyc.primitives.int_ops\nimport mypyc.primitives.librt_strings_ops\nimport mypyc.primitives.librt_time_ops\nimport mypyc.primitives.list_ops\nimport mypyc.primitives.misc_ops\nimport mypyc.primitives.str_ops\nimport mypyc.primitives.tuple_ops\nimport mypyc.primitives.weakref_ops  # noqa: F401\n"
  },
  {
    "path": "mypyc/primitives/set_ops.py",
    "content": "\"\"\"Primitive set and frozenset ops.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.ops import ERR_FALSE, ERR_MAGIC, ERR_NEVER\nfrom mypyc.ir.rtypes import (\n    bit_rprimitive,\n    bool_rprimitive,\n    c_int_rprimitive,\n    frozenset_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    set_rprimitive,\n)\nfrom mypyc.primitives.registry import (\n    ERR_NEG_INT,\n    binary_op,\n    function_op,\n    load_address_op,\n    method_op,\n)\n\n# Get the 'builtins.set' type object.\nload_address_op(name=\"builtins.set\", type=object_rprimitive, src=\"PySet_Type\")\n\n# Get the 'builtins.frozenset' type object.\nload_address_op(name=\"builtins.frozenset\", type=object_rprimitive, src=\"PyFrozenSet_Type\")\n\n# Construct an empty set.\nnew_set_op = function_op(\n    name=\"builtins.set\",\n    arg_types=[],\n    return_type=set_rprimitive,\n    c_function_name=\"PySet_New\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(0, pointer_rprimitive)],\n)\n\n# set(obj)\nfunction_op(\n    name=\"builtins.set\",\n    arg_types=[object_rprimitive],\n    return_type=set_rprimitive,\n    c_function_name=\"PySet_New\",\n    error_kind=ERR_MAGIC,\n)\n\n# Construct an empty frozenset\nfunction_op(\n    name=\"builtins.frozenset\",\n    arg_types=[],\n    return_type=frozenset_rprimitive,\n    c_function_name=\"PyFrozenSet_New\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(0, pointer_rprimitive)],\n)\n\n# frozenset(obj)\nfunction_op(\n    name=\"builtins.frozenset\",\n    arg_types=[object_rprimitive],\n    return_type=frozenset_rprimitive,\n    c_function_name=\"PyFrozenSet_New\",\n    error_kind=ERR_MAGIC,\n)\n\n# translate isinstance(obj, set)\nisinstance_set = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PySet_Check\",\n    error_kind=ERR_NEVER,\n)\n\n# translate isinstance(obj, frozenset)\nisinstance_frozenset = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PyFrozenSet_Check\",\n    error_kind=ERR_NEVER,\n)\n\n# item in set\nset_in_op = binary_op(\n    name=\"in\",\n    arg_types=[object_rprimitive, set_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PySet_Contains\",\n    error_kind=ERR_NEG_INT,\n    truncated_type=bool_rprimitive,\n    ordering=[1, 0],\n)\n\n# item in frozenset\nbinary_op(\n    name=\"in\",\n    arg_types=[object_rprimitive, frozenset_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PySet_Contains\",\n    error_kind=ERR_NEG_INT,\n    truncated_type=bool_rprimitive,\n    ordering=[1, 0],\n)\n\n# set.remove(obj)\nmethod_op(\n    name=\"remove\",\n    arg_types=[set_rprimitive, object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPySet_Remove\",\n    error_kind=ERR_FALSE,\n)\n\n# set.discard(obj)\nmethod_op(\n    name=\"discard\",\n    arg_types=[set_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PySet_Discard\",\n    error_kind=ERR_NEG_INT,\n)\n\n# set.add(obj)\nset_add_op = method_op(\n    name=\"add\",\n    arg_types=[set_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PySet_Add\",\n    error_kind=ERR_NEG_INT,\n)\n\n# set.update(obj)\n#\n# This is not a public API but looks like it should be fine.\nset_update_op = method_op(\n    name=\"update\",\n    arg_types=[set_rprimitive, object_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"_PySet_Update\",\n    error_kind=ERR_NEG_INT,\n)\n\n# set.clear()\nmethod_op(\n    name=\"clear\",\n    arg_types=[set_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PySet_Clear\",\n    error_kind=ERR_NEG_INT,\n)\n\n# set.pop()\nmethod_op(\n    name=\"pop\",\n    arg_types=[set_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PySet_Pop\",\n    error_kind=ERR_MAGIC,\n)\n"
  },
  {
    "path": "mypyc/primitives/str_ops.py",
    "content": "\"\"\"Primitive str ops.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.deps import STR_EXTRA_OPS\nfrom mypyc.ir.ops import ERR_MAGIC, ERR_NEVER\nfrom mypyc.ir.rtypes import (\n    RType,\n    bit_rprimitive,\n    bool_rprimitive,\n    bytes_rprimitive,\n    c_int_rprimitive,\n    c_pyssize_t_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    list_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    short_int_rprimitive,\n    str_rprimitive,\n    tuple_rprimitive,\n)\nfrom mypyc.primitives.registry import (\n    ERR_NEG_INT,\n    binary_op,\n    custom_op,\n    custom_primitive_op,\n    function_op,\n    load_address_op,\n    method_op,\n)\n\n# Get the 'str' type object.\nload_address_op(name=\"builtins.str\", type=object_rprimitive, src=\"PyUnicode_Type\")\n\n# str(obj)\nstr_op = function_op(\n    name=\"builtins.str\",\n    arg_types=[object_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"PyObject_Str\",\n    error_kind=ERR_MAGIC,\n)\n\n# repr(obj)\nfunction_op(\n    name=\"builtins.repr\",\n    arg_types=[object_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"PyObject_Repr\",\n    error_kind=ERR_MAGIC,\n)\n\n# translate isinstance(obj, str)\nisinstance_str = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PyUnicode_Check\",\n    error_kind=ERR_NEVER,\n)\n\n# str1 + str2\nbinary_op(\n    name=\"+\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"PyUnicode_Concat\",\n    error_kind=ERR_MAGIC,\n)\n\n# str1 += str2\n#\n# PyUnicode_Append makes an effort to reuse the LHS when the refcount\n# is 1. This is super dodgy but oh well, the interpreter does it.\nbinary_op(\n    name=\"+=\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_Append\",\n    error_kind=ERR_MAGIC,\n    steals=[True, False],\n)\n\n# str * int\nbinary_op(\n    name=\"*\",\n    arg_types=[str_rprimitive, int_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_Multiply\",\n    error_kind=ERR_MAGIC,\n)\n\n# int * str\nbinary_op(\n    name=\"*\",\n    arg_types=[int_rprimitive, str_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_Multiply\",\n    error_kind=ERR_MAGIC,\n    ordering=[1, 0],\n)\n\n# str1 == str2 (very common operation, so we provide our own)\nstr_eq = custom_primitive_op(\n    name=\"str_eq\",\n    c_function_name=\"CPyStr_Equal\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=bool_rprimitive,\n    error_kind=ERR_NEVER,\n)\n\nstr_eq_literal = custom_primitive_op(\n    name=\"str_eq_literal\",\n    c_function_name=\"CPyStr_EqualLiteral\",\n    arg_types=[str_rprimitive, str_rprimitive, c_pyssize_t_rprimitive],\n    return_type=bool_rprimitive,\n    error_kind=ERR_NEVER,\n)\n\nunicode_compare = custom_op(\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyUnicode_Compare\",\n    error_kind=ERR_NEVER,\n)\n\n# str[index] (for an int index)\nmethod_op(\n    name=\"__getitem__\",\n    arg_types=[str_rprimitive, int_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_GetItem\",\n    error_kind=ERR_MAGIC,\n)\n\n# This is unsafe since it assumes that the index is within reasonable bounds.\n# In the future this might do no bounds checking at all.\nstr_get_item_unsafe_op = custom_op(\n    arg_types=[str_rprimitive, c_pyssize_t_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_GetItemUnsafe\",\n    error_kind=ERR_MAGIC,\n)\n\n# str[begin:end]\nstr_slice_op = custom_op(\n    arg_types=[str_rprimitive, int_rprimitive, int_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPyStr_GetSlice\",\n    error_kind=ERR_MAGIC,\n)\n\n# item in str\nbinary_op(\n    name=\"in\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"PyUnicode_Contains\",\n    error_kind=ERR_NEG_INT,\n    truncated_type=bool_rprimitive,\n    ordering=[1, 0],\n)\n\n# str.find(...) and str.rfind(...)\nstr_find_types: list[RType] = [str_rprimitive, str_rprimitive, int_rprimitive, int_rprimitive]\nstr_find_functions = [\"CPyStr_Find\", \"CPyStr_Find\", \"CPyStr_FindWithEnd\"]\nstr_find_constants: list[list[tuple[int, RType]]] = [[(0, c_int_rprimitive)], [], []]\nstr_rfind_constants: list[list[tuple[int, RType]]] = [[(0, c_int_rprimitive)], [], []]\nfor i in range(len(str_find_types) - 1):\n    method_op(\n        name=\"find\",\n        arg_types=str_find_types[0 : i + 2],\n        return_type=int_rprimitive,\n        c_function_name=str_find_functions[i],\n        extra_int_constants=str_find_constants[i] + [(1, c_int_rprimitive)],\n        error_kind=ERR_MAGIC,\n    )\n    method_op(\n        name=\"rfind\",\n        arg_types=str_find_types[0 : i + 2],\n        return_type=int_rprimitive,\n        c_function_name=str_find_functions[i],\n        extra_int_constants=str_rfind_constants[i] + [(-1, c_int_rprimitive)],\n        error_kind=ERR_MAGIC,\n    )\n\n# str.join(obj)\nmethod_op(\n    name=\"join\",\n    arg_types=[str_rprimitive, object_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"PyUnicode_Join\",\n    error_kind=ERR_MAGIC,\n)\n\nstr_build_op = custom_op(\n    arg_types=[c_pyssize_t_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_Build\",\n    error_kind=ERR_MAGIC,\n    var_arg_type=str_rprimitive,\n)\n\n# str.strip, str.lstrip, str.rstrip\nfor strip_prefix in [\"l\", \"r\", \"\"]:\n    method_op(\n        name=f\"{strip_prefix}strip\",\n        arg_types=[str_rprimitive, str_rprimitive],\n        return_type=str_rprimitive,\n        c_function_name=f\"CPyStr_{strip_prefix.upper()}Strip\",\n        error_kind=ERR_NEVER,\n    )\n    method_op(\n        name=f\"{strip_prefix}strip\",\n        arg_types=[str_rprimitive],\n        return_type=str_rprimitive,\n        c_function_name=f\"CPyStr_{strip_prefix.upper()}Strip\",\n        # This 0 below is implicitly treated as NULL in C.\n        extra_int_constants=[(0, c_int_rprimitive)],\n        error_kind=ERR_NEVER,\n    )\n\n# str.startswith(str)\nmethod_op(\n    name=\"startswith\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyStr_Startswith\",\n    truncated_type=bool_rprimitive,\n    error_kind=ERR_NEVER,\n)\n\n# str.startswith(tuple)\nmethod_op(\n    name=\"startswith\",\n    arg_types=[str_rprimitive, tuple_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyStr_Startswith\",\n    error_kind=ERR_MAGIC,\n)\n\n# str.endswith(str)\nmethod_op(\n    name=\"endswith\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=c_int_rprimitive,\n    c_function_name=\"CPyStr_Endswith\",\n    truncated_type=bool_rprimitive,\n    error_kind=ERR_NEVER,\n)\n\n# str.endswith(tuple)\nmethod_op(\n    name=\"endswith\",\n    arg_types=[str_rprimitive, tuple_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyStr_Endswith\",\n    error_kind=ERR_MAGIC,\n)\n\n# str.removeprefix(str)\nmethod_op(\n    name=\"removeprefix\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_Removeprefix\",\n    error_kind=ERR_NEVER,\n)\n\n# str.removesuffix(str)\nmethod_op(\n    name=\"removesuffix\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_Removesuffix\",\n    error_kind=ERR_NEVER,\n)\n\n# str.split(...) and str.rsplit(...)\nstr_split_types: list[RType] = [str_rprimitive, str_rprimitive, int_rprimitive]\nstr_split_functions = [\"PyUnicode_Split\", \"PyUnicode_Split\", \"CPyStr_Split\"]\nstr_rsplit_functions = [\"PyUnicode_RSplit\", \"PyUnicode_RSplit\", \"CPyStr_RSplit\"]\nstr_split_constants: list[list[tuple[int, RType]]] = [\n    [(0, pointer_rprimitive), (-1, c_int_rprimitive)],\n    [(-1, c_int_rprimitive)],\n    [],\n]\nfor i in range(len(str_split_types)):\n    method_op(\n        name=\"split\",\n        arg_types=str_split_types[0 : i + 1],\n        return_type=list_rprimitive,\n        c_function_name=str_split_functions[i],\n        extra_int_constants=str_split_constants[i],\n        error_kind=ERR_MAGIC,\n    )\n    method_op(\n        name=\"rsplit\",\n        arg_types=str_split_types[0 : i + 1],\n        return_type=list_rprimitive,\n        c_function_name=str_rsplit_functions[i],\n        extra_int_constants=str_split_constants[i],\n        error_kind=ERR_MAGIC,\n    )\n\n# str.splitlines(...)\nstr_splitlines_types: list[RType] = [str_rprimitive, bool_rprimitive]\nstr_splitlines_constants: list[list[tuple[int, RType]]] = [[(0, c_int_rprimitive)], []]\nfor i in range(2):\n    method_op(\n        name=\"splitlines\",\n        arg_types=str_splitlines_types[0 : i + 1],\n        return_type=list_rprimitive,\n        c_function_name=\"PyUnicode_Splitlines\",\n        extra_int_constants=str_splitlines_constants[i],\n        error_kind=ERR_NEVER,\n    )\n\n# str.partition(str)\nmethod_op(\n    name=\"partition\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=tuple_rprimitive,\n    c_function_name=\"PyUnicode_Partition\",\n    error_kind=ERR_MAGIC,\n)\n\n# str.rpartition(str)\nmethod_op(\n    name=\"rpartition\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=tuple_rprimitive,\n    c_function_name=\"PyUnicode_RPartition\",\n    error_kind=ERR_MAGIC,\n)\n\n# str.count(substring)\nmethod_op(\n    name=\"count\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=c_pyssize_t_rprimitive,\n    c_function_name=\"CPyStr_Count\",\n    error_kind=ERR_NEG_INT,\n    extra_int_constants=[(0, c_pyssize_t_rprimitive)],\n)\n\n# str.count(substring, start)\nmethod_op(\n    name=\"count\",\n    arg_types=[str_rprimitive, str_rprimitive, int_rprimitive],\n    return_type=c_pyssize_t_rprimitive,\n    c_function_name=\"CPyStr_Count\",\n    error_kind=ERR_NEG_INT,\n)\n\n# str.count(substring, start, end)\nmethod_op(\n    name=\"count\",\n    arg_types=[str_rprimitive, str_rprimitive, int_rprimitive, int_rprimitive],\n    return_type=c_pyssize_t_rprimitive,\n    c_function_name=\"CPyStr_CountFull\",\n    error_kind=ERR_NEG_INT,\n)\n\n# str.replace(old, new)\nmethod_op(\n    name=\"replace\",\n    arg_types=[str_rprimitive, str_rprimitive, str_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"PyUnicode_Replace\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(-1, c_int_rprimitive)],\n)\n\n# str.replace(old, new, count)\nmethod_op(\n    name=\"replace\",\n    arg_types=[str_rprimitive, str_rprimitive, str_rprimitive, int_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_Replace\",\n    error_kind=ERR_MAGIC,\n)\n\n# check if a string is true (isn't an empty string)\nstr_check_if_true = custom_op(\n    arg_types=[str_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"CPyStr_IsTrue\",\n    error_kind=ERR_NEVER,\n)\n\nstr_ssize_t_size_op = custom_op(\n    arg_types=[str_rprimitive],\n    return_type=c_pyssize_t_rprimitive,\n    c_function_name=\"CPyStr_Size_size_t\",\n    error_kind=ERR_NEG_INT,\n)\n\n# str.lower()\nmethod_op(\n    name=\"lower\",\n    arg_types=[str_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_Lower\",\n    error_kind=ERR_MAGIC,\n)\n\n# str.upper()\nmethod_op(\n    name=\"upper\",\n    arg_types=[str_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPyStr_Upper\",\n    error_kind=ERR_MAGIC,\n)\n\nmethod_op(\n    name=\"isspace\",\n    arg_types=[str_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyStr_IsSpace\",\n    error_kind=ERR_NEVER,\n)\n\nmethod_op(\n    name=\"isalnum\",\n    arg_types=[str_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyStr_IsAlnum\",\n    error_kind=ERR_NEVER,\n)\n\nmethod_op(\n    name=\"isdigit\",\n    arg_types=[str_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyStr_IsDigit\",\n    error_kind=ERR_NEVER,\n)\n\n\n# obj.decode()\nmethod_op(\n    name=\"decode\",\n    arg_types=[bytes_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPy_Decode\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(0, pointer_rprimitive), (0, pointer_rprimitive)],\n)\n\n# obj.decode(encoding)\nmethod_op(\n    name=\"decode\",\n    arg_types=[bytes_rprimitive, str_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPy_Decode\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(0, pointer_rprimitive)],\n)\n\n# bytes.decode(encoding, errors)\nmethod_op(\n    name=\"decode\",\n    arg_types=[bytes_rprimitive, str_rprimitive, str_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPy_Decode\",\n    error_kind=ERR_MAGIC,\n)\n\n# bytes.decode(encoding) - utf8 strict specialization\nbytes_decode_utf8_strict = custom_op(\n    arg_types=[bytes_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPy_DecodeUTF8\",\n    error_kind=ERR_MAGIC,\n)\n\n# bytes.decode(encoding) - ascii strict specialization\nbytes_decode_ascii_strict = custom_op(\n    arg_types=[bytes_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPy_DecodeASCII\",\n    error_kind=ERR_MAGIC,\n)\n\n# bytes.decode(encoding) - latin1 strict specialization\nbytes_decode_latin1_strict = custom_op(\n    arg_types=[bytes_rprimitive],\n    return_type=str_rprimitive,\n    c_function_name=\"CPy_DecodeLatin1\",\n    error_kind=ERR_MAGIC,\n)\n\n# str.encode()\nmethod_op(\n    name=\"encode\",\n    arg_types=[str_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPy_Encode\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(0, pointer_rprimitive), (0, pointer_rprimitive)],\n)\n\n# str.encode(encoding)\nmethod_op(\n    name=\"encode\",\n    arg_types=[str_rprimitive, str_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPy_Encode\",\n    error_kind=ERR_MAGIC,\n    extra_int_constants=[(0, pointer_rprimitive)],\n)\n\n# str.encode(encoding) - utf8 strict specialization\nstr_encode_utf8_strict = custom_op(\n    arg_types=[str_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"PyUnicode_AsUTF8String\",\n    error_kind=ERR_MAGIC,\n)\n\n# str.encode(encoding) - ascii strict specialization\nstr_encode_ascii_strict = custom_op(\n    arg_types=[str_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"PyUnicode_AsASCIIString\",\n    error_kind=ERR_MAGIC,\n)\n\n# str.encode(encoding) - latin1 strict specialization\nstr_encode_latin1_strict = custom_op(\n    arg_types=[str_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"PyUnicode_AsLatin1String\",\n    error_kind=ERR_MAGIC,\n)\n\n# str.encode(encoding, errors)\nmethod_op(\n    name=\"encode\",\n    arg_types=[str_rprimitive, str_rprimitive, str_rprimitive],\n    return_type=bytes_rprimitive,\n    c_function_name=\"CPy_Encode\",\n    error_kind=ERR_MAGIC,\n)\n\nfunction_op(\n    name=\"builtins.ord\",\n    arg_types=[str_rprimitive],\n    return_type=int_rprimitive,\n    c_function_name=\"CPyStr_Ord\",\n    error_kind=ERR_MAGIC,\n)\n\n# Optimized str indexing for ord(s[i])\n\n# str index adjustment - convert negative index to positive\nstr_adjust_index_op = custom_primitive_op(\n    name=\"str_adjust_index\",\n    arg_types=[str_rprimitive, int64_rprimitive],\n    return_type=int64_rprimitive,\n    c_function_name=\"CPyStr_AdjustIndex\",\n    error_kind=ERR_NEVER,\n    dependencies=[STR_EXTRA_OPS],\n)\n\n# str range check - check if index is in valid range\nstr_range_check_op = custom_primitive_op(\n    name=\"str_range_check\",\n    arg_types=[str_rprimitive, int64_rprimitive],\n    return_type=bool_rprimitive,\n    c_function_name=\"CPyStr_RangeCheck\",\n    error_kind=ERR_NEVER,\n    dependencies=[STR_EXTRA_OPS],\n)\n\n# str.__getitem__() as int - get character at index as int (ord value) - no bounds checking\nstr_get_item_unsafe_as_int_op = custom_primitive_op(\n    name=\"str_get_item_unsafe_as_int\",\n    arg_types=[str_rprimitive, int64_rprimitive],\n    return_type=short_int_rprimitive,\n    c_function_name=\"CPyStr_GetItemUnsafeAsInt\",\n    error_kind=ERR_NEVER,\n    dependencies=[STR_EXTRA_OPS],\n)\n"
  },
  {
    "path": "mypyc/primitives/tuple_ops.py",
    "content": "\"\"\"Primitive tuple ops for *variable-length* tuples.\n\nNote: Varying-length tuples are represented as boxed Python tuple\nobjects, i.e. tuple_rprimitive (RPrimitive), not RTuple.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.ops import ERR_MAGIC, ERR_NEVER\nfrom mypyc.ir.rtypes import (\n    bit_rprimitive,\n    c_pyssize_t_rprimitive,\n    int_rprimitive,\n    list_rprimitive,\n    object_rprimitive,\n    tuple_rprimitive,\n    void_rtype,\n)\nfrom mypyc.primitives.registry import binary_op, custom_op, function_op, load_address_op, method_op\n\n# Get the 'builtins.tuple' type object.\nload_address_op(name=\"builtins.tuple\", type=object_rprimitive, src=\"PyTuple_Type\")\n\n# tuple[index] (for an int index)\ntuple_get_item_op = method_op(\n    name=\"__getitem__\",\n    arg_types=[tuple_rprimitive, int_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPySequenceTuple_GetItem\",\n    error_kind=ERR_MAGIC,\n)\n\n# This is unsafe because it assumes that the index is a non-negative integer\n# that is in-bounds for the tuple.\ntuple_get_item_unsafe_op = custom_op(\n    arg_types=[tuple_rprimitive, c_pyssize_t_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPySequenceTuple_GetItemUnsafe\",\n    error_kind=ERR_NEVER,\n)\n\n# Construct a boxed tuple from items: (item1, item2, ...)\nnew_tuple_op = custom_op(\n    arg_types=[c_pyssize_t_rprimitive],\n    return_type=tuple_rprimitive,\n    c_function_name=\"PyTuple_Pack\",\n    error_kind=ERR_MAGIC,\n    var_arg_type=object_rprimitive,\n)\n\nnew_tuple_with_length_op = custom_op(\n    arg_types=[c_pyssize_t_rprimitive],\n    return_type=tuple_rprimitive,\n    c_function_name=\"PyTuple_New\",\n    error_kind=ERR_MAGIC,\n)\n\nload_empty_tuple_constant_op = custom_op(\n    arg_types=[],\n    return_type=tuple_rprimitive,\n    c_function_name=\"CPyTuple_LoadEmptyTupleConstant\",\n    error_kind=ERR_NEVER,\n)\n\n# PyTuple_SET_ITEM does no error checking,\n# and should only be used to fill in brand new tuples.\nnew_tuple_set_item_op = custom_op(\n    arg_types=[tuple_rprimitive, c_pyssize_t_rprimitive, object_rprimitive],\n    return_type=void_rtype,\n    c_function_name=\"CPySequenceTuple_SetItemUnsafe\",\n    error_kind=ERR_NEVER,\n    steals=[False, False, True],\n)\n\n# Construct tuple from a list.\nlist_tuple_op = function_op(\n    name=\"builtins.tuple\",\n    arg_types=[list_rprimitive],\n    return_type=tuple_rprimitive,\n    c_function_name=\"PyList_AsTuple\",\n    error_kind=ERR_MAGIC,\n    priority=2,\n)\n\n# Construct tuple from an arbitrary (iterable) object.\nsequence_tuple_op = function_op(\n    name=\"builtins.tuple\",\n    arg_types=[object_rprimitive],\n    return_type=tuple_rprimitive,\n    c_function_name=\"PySequence_Tuple\",\n    error_kind=ERR_MAGIC,\n)\n\n# translate isinstance(obj, tuple)\nisinstance_tuple = function_op(\n    name=\"builtins.isinstance\",\n    arg_types=[object_rprimitive],\n    return_type=bit_rprimitive,\n    c_function_name=\"PyTuple_Check\",\n    error_kind=ERR_NEVER,\n)\n\n# tuple + tuple\nbinary_op(\n    name=\"+\",\n    arg_types=[tuple_rprimitive, tuple_rprimitive],\n    return_type=tuple_rprimitive,\n    c_function_name=\"PySequence_Concat\",\n    error_kind=ERR_MAGIC,\n)\n\n# tuple * int\nbinary_op(\n    name=\"*\",\n    arg_types=[tuple_rprimitive, int_rprimitive],\n    return_type=tuple_rprimitive,\n    c_function_name=\"CPySequence_Multiply\",\n    error_kind=ERR_MAGIC,\n)\n\n# int * tuple\nbinary_op(\n    name=\"*\",\n    arg_types=[int_rprimitive, tuple_rprimitive],\n    return_type=tuple_rprimitive,\n    c_function_name=\"CPySequence_RMultiply\",\n    error_kind=ERR_MAGIC,\n)\n\n# tuple[begin:end]\ntuple_slice_op = custom_op(\n    arg_types=[tuple_rprimitive, int_rprimitive, int_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"CPySequenceTuple_GetSlice\",\n    error_kind=ERR_MAGIC,\n)\n"
  },
  {
    "path": "mypyc/primitives/weakref_ops.py",
    "content": "from mypyc.ir.ops import ERR_MAGIC\nfrom mypyc.ir.rtypes import object_rprimitive, pointer_rprimitive\nfrom mypyc.primitives.registry import function_op\n\n# Weakref operations\n\nnew_ref_op = function_op(\n    name=\"weakref.ReferenceType\",\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyWeakref_NewRef\",\n    extra_int_constants=[(0, pointer_rprimitive)],\n    error_kind=ERR_MAGIC,\n)\n\nnew_ref__with_callback_op = function_op(\n    name=\"weakref.ReferenceType\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyWeakref_NewRef\",\n    error_kind=ERR_MAGIC,\n)\n\nnew_proxy_op = function_op(\n    name=\"_weakref.proxy\",\n    arg_types=[object_rprimitive],\n    return_type=object_rprimitive,\n    c_function_name=\"PyWeakref_NewProxy\",\n    extra_int_constants=[(0, pointer_rprimitive)],\n    error_kind=ERR_MAGIC,\n)\n\nnew_proxy_with_callback_op = function_op(\n    name=\"_weakref.proxy\",\n    arg_types=[object_rprimitive, object_rprimitive],\n    # steals=[True, False],\n    return_type=object_rprimitive,\n    c_function_name=\"PyWeakref_NewProxy\",\n    error_kind=ERR_MAGIC,\n)\n"
  },
  {
    "path": "mypyc/py.typed",
    "content": ""
  },
  {
    "path": "mypyc/rt_subtype.py",
    "content": "\"\"\"'Runtime subtype' check for RTypes.\n\nA type S is a runtime subtype of T if a value of type S can be used at runtime\nwhen a value of type T is expected without requiring any runtime conversions.\n\nFor boxed types, runtime subtyping is the same as regular subtyping.\nUnboxed subtypes, on the other hand, are not runtime subtypes of object\n(since they require boxing to be used as an object), but short ints\nare runtime subtypes of int.\n\nSubtyping is used to determine whether an object can be in a\nparticular place and runtime subtyping is used to determine whether a\ncoercion is necessary first.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.rtypes import (\n    RArray,\n    RInstance,\n    RPrimitive,\n    RStruct,\n    RTuple,\n    RType,\n    RTypeVisitor,\n    RUnion,\n    RVec,\n    RVoid,\n    is_bit_rprimitive,\n    is_bool_rprimitive,\n    is_int_rprimitive,\n    is_short_int_rprimitive,\n)\nfrom mypyc.subtype import is_subtype\n\n\ndef is_runtime_subtype(left: RType, right: RType) -> bool:\n    if isinstance(right, RUnion) and not isinstance(left, RUnion):\n        return any(not item.is_unboxed and is_runtime_subtype(left, item) for item in right.items)\n    return left.accept(RTSubtypeVisitor(right))\n\n\nclass RTSubtypeVisitor(RTypeVisitor[bool]):\n    \"\"\"Is left a runtime subtype of right?\n\n    A few special cases such as right being 'object' are handled in\n    is_runtime_subtype and don't need to be covered here.\n    \"\"\"\n\n    def __init__(self, right: RType) -> None:\n        self.right = right\n\n    def visit_rinstance(self, left: RInstance) -> bool:\n        return is_subtype(left, self.right)\n\n    def visit_rvec(self, left: RVec) -> bool:\n        # TODO: Better implementation\n        return left == self.right\n\n    def visit_runion(self, left: RUnion) -> bool:\n        return not self.right.is_unboxed and is_subtype(left, self.right)\n\n    def visit_rprimitive(self, left: RPrimitive) -> bool:\n        if is_short_int_rprimitive(left) and is_int_rprimitive(self.right):\n            return True\n        if is_bit_rprimitive(left) and is_bool_rprimitive(self.right):\n            return True\n        return left is self.right\n\n    def visit_rtuple(self, left: RTuple) -> bool:\n        if isinstance(self.right, RTuple):\n            return len(self.right.types) == len(left.types) and all(\n                is_runtime_subtype(t1, t2) for t1, t2 in zip(left.types, self.right.types)\n            )\n        return False\n\n    def visit_rstruct(self, left: RStruct) -> bool:\n        return isinstance(self.right, RStruct) and self.right.name == left.name\n\n    def visit_rarray(self, left: RArray) -> bool:\n        return left == self.right\n\n    def visit_rvoid(self, left: RVoid) -> bool:\n        return isinstance(self.right, RVoid)\n"
  },
  {
    "path": "mypyc/sametype.py",
    "content": "\"\"\"Same type check for RTypes.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.func_ir import FuncSignature\nfrom mypyc.ir.rtypes import (\n    RArray,\n    RInstance,\n    RPrimitive,\n    RStruct,\n    RTuple,\n    RType,\n    RTypeVisitor,\n    RUnion,\n    RVec,\n    RVoid,\n)\n\n\ndef is_same_type(a: RType, b: RType) -> bool:\n    return a.accept(SameTypeVisitor(b))\n\n\ndef is_same_signature(a: FuncSignature, b: FuncSignature) -> bool:\n    return (\n        len(a.args) == len(b.args)\n        and is_same_type(a.ret_type, b.ret_type)\n        and all(\n            is_same_type(t1.type, t2.type) and t1.name == t2.name for t1, t2 in zip(a.args, b.args)\n        )\n    )\n\n\ndef is_same_method_signature(a: FuncSignature, b: FuncSignature) -> bool:\n    return (\n        len(a.args) == len(b.args)\n        and is_same_type(a.ret_type, b.ret_type)\n        and all(\n            is_same_type(t1.type, t2.type)\n            and ((t1.pos_only and t2.pos_only) or t1.name == t2.name)\n            and t1.optional == t2.optional\n            for t1, t2 in zip(a.args[1:], b.args[1:])\n        )\n    )\n\n\nclass SameTypeVisitor(RTypeVisitor[bool]):\n    def __init__(self, right: RType) -> None:\n        self.right = right\n\n    def visit_rinstance(self, left: RInstance) -> bool:\n        return isinstance(self.right, RInstance) and left.name == self.right.name\n\n    def visit_rvec(self, left: RVec) -> bool:\n        return isinstance(self.right, RVec) and left.item_type == self.right.item_type\n\n    def visit_runion(self, left: RUnion) -> bool:\n        if isinstance(self.right, RUnion):\n            items = list(self.right.items)\n            for left_item in left.items:\n                for j, right_item in enumerate(items):\n                    if is_same_type(left_item, right_item):\n                        del items[j]\n                        break\n                else:\n                    return False\n            return not items\n        return False\n\n    def visit_rprimitive(self, left: RPrimitive) -> bool:\n        return left is self.right\n\n    def visit_rtuple(self, left: RTuple) -> bool:\n        return (\n            isinstance(self.right, RTuple)\n            and len(self.right.types) == len(left.types)\n            and all(is_same_type(t1, t2) for t1, t2 in zip(left.types, self.right.types))\n        )\n\n    def visit_rstruct(self, left: RStruct) -> bool:\n        return isinstance(self.right, RStruct) and self.right.name == left.name\n\n    def visit_rarray(self, left: RArray) -> bool:\n        return left == self.right\n\n    def visit_rvoid(self, left: RVoid) -> bool:\n        return isinstance(self.right, RVoid)\n"
  },
  {
    "path": "mypyc/subtype.py",
    "content": "\"\"\"Subtype check for RTypes.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.rtypes import (\n    RArray,\n    RInstance,\n    RPrimitive,\n    RStruct,\n    RTuple,\n    RType,\n    RTypeVisitor,\n    RUnion,\n    RVec,\n    RVoid,\n    is_bit_rprimitive,\n    is_bool_rprimitive,\n    is_fixed_width_rtype,\n    is_int_rprimitive,\n    is_object_rprimitive,\n    is_short_int_rprimitive,\n    is_tagged,\n    is_tuple_rprimitive,\n)\n\n\ndef is_subtype(left: RType, right: RType, *, relaxed: bool = False) -> bool:\n    if is_object_rprimitive(right):\n        return True\n    elif isinstance(right, RUnion):\n        if isinstance(left, RUnion):\n            for left_item in left.items:\n                if not any(\n                    is_subtype(left_item, right_item, relaxed=relaxed)\n                    for right_item in right.items\n                ):\n                    return False\n            return True\n        else:\n            return any(is_subtype(left, item, relaxed=relaxed) for item in right.items)\n    return left.accept(SubtypeVisitor(right, relaxed=relaxed))\n\n\nclass SubtypeVisitor(RTypeVisitor[bool]):\n    \"\"\"Is left a subtype of right?\n\n    A few special cases such as right being 'object' are handled in\n    is_subtype and don't need to be covered here.\n    \"\"\"\n\n    def __init__(self, right: RType, *, relaxed: bool = False) -> None:\n        self.right = right\n        self.relaxed = relaxed\n\n    def visit_rinstance(self, left: RInstance) -> bool:\n        return isinstance(self.right, RInstance) and self.right.class_ir in left.class_ir.mro\n\n    def visit_rvec(self, left: RVec) -> bool:\n        # TODO: Better implementation\n        return left == self.right\n\n    def visit_runion(self, left: RUnion) -> bool:\n        return all(is_subtype(item, self.right, relaxed=self.relaxed) for item in left.items)\n\n    def visit_rprimitive(self, left: RPrimitive) -> bool:\n        right = self.right\n        if is_bool_rprimitive(left):\n            if is_tagged(right) or is_fixed_width_rtype(right):\n                return True\n        elif is_bit_rprimitive(left):\n            if is_bool_rprimitive(right) or is_tagged(right) or is_fixed_width_rtype(right):\n                return True\n        elif is_short_int_rprimitive(left):\n            if is_int_rprimitive(right):\n                return True\n            if self.relaxed and is_fixed_width_rtype(right):\n                return True\n        elif is_int_rprimitive(left):\n            if self.relaxed and is_fixed_width_rtype(right):\n                return True\n        elif is_fixed_width_rtype(left):\n            if is_int_rprimitive(right):\n                return True\n        return left is right\n\n    def visit_rtuple(self, left: RTuple) -> bool:\n        if is_tuple_rprimitive(self.right):\n            return True\n        if isinstance(self.right, RTuple):\n            return len(self.right.types) == len(left.types) and all(\n                is_subtype(t1, t2, relaxed=self.relaxed)\n                for t1, t2 in zip(left.types, self.right.types)\n            )\n        return False\n\n    def visit_rstruct(self, left: RStruct) -> bool:\n        return isinstance(self.right, RStruct) and self.right.name == left.name\n\n    def visit_rarray(self, left: RArray) -> bool:\n        return left == self.right\n\n    def visit_rvoid(self, left: RVoid) -> bool:\n        return isinstance(self.right, RVoid)\n"
  },
  {
    "path": "mypyc/test/__init__.py",
    "content": ""
  },
  {
    "path": "mypyc/test/config.py",
    "content": "from __future__ import annotations\n\nimport os\n\nprovided_prefix = os.getenv(\"MYPY_TEST_PREFIX\", None)\nif provided_prefix:\n    PREFIX = provided_prefix\nelse:\n    this_file_dir = os.path.dirname(os.path.realpath(__file__))\n    PREFIX = os.path.dirname(os.path.dirname(this_file_dir))\n\n# Location of test data files such as test case descriptions.\ntest_data_prefix = os.path.join(PREFIX, \"mypyc\", \"test-data\")\n"
  },
  {
    "path": "mypyc/test/librt_cache.py",
    "content": "\"\"\"Build and cache librt for use in tests.\n\nThis module provides a way to build librt extension modules once and cache\nthem across test runs, and across different test cases in a single run. The\ncache is invalidated when source files or details of the build environment change.\n\nNote: Tests must run in a subprocess to use the cached librt, since importing\nthis module also triggers the import of the regular installed librt.\n\nUsage:\n    from mypyc.test.librt_cache import get_librt_path, run_with_librt\n\n    # Get path to built librt (builds if needed)\n    path = get_librt_path()\n\n    # Run a test file in subprocess with built librt\n    result = run_with_librt(\"test_librt.py\")\n\"\"\"\n\nfrom __future__ import annotations\n\nimport hashlib\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport sysconfig\nfrom typing import Any\n\nimport filelock\n\nfrom mypyc.build import LIBRT_MODULES, get_cflags, include_dir\nfrom mypyc.common import RUNTIME_C_FILES\n\n\ndef _librt_build_hash(experimental: bool, opt_level: str) -> str:\n    \"\"\"Compute hash for librt build, including sources and build environment.\"\"\"\n    # Import lazily to ensure mypyc.build has ensured that distutils is correctly set up\n    from distutils import ccompiler\n\n    h = hashlib.sha256()\n    # Include experimental flag\n    h.update(b\"exp\" if experimental else b\"noexp\")\n    h.update(f\"opt={opt_level}\".encode())\n    # Include full Python version string (includes git hash for dev builds)\n    h.update(sys.version.encode())\n    # Include debug build status (gettotalrefcount only exists in debug builds)\n    is_debug = hasattr(sys, \"gettotalrefcount\")\n    h.update(b\"debug\" if is_debug else b\"release\")\n    # Include free-threading status (Python 3.13+)\n    is_free_threaded = bool(sysconfig.get_config_var(\"Py_GIL_DISABLED\"))\n    h.update(b\"freethreaded\" if is_free_threaded else b\"gil\")\n    # Include compiler type (e.g., \"unix\" or \"msvc\")\n    compiler: Any = ccompiler.new_compiler()\n    h.update(compiler.compiler_type.encode())\n    # Include environment variables that affect C compilation\n    for var in (\"CC\", \"CXX\", \"CFLAGS\", \"CPPFLAGS\", \"LDFLAGS\"):\n        val = os.environ.get(var, \"\")\n        h.update(f\"{var}={val}\".encode())\n    # Hash runtime files\n    for name in RUNTIME_C_FILES:\n        path = os.path.join(include_dir(), name)\n        h.update(name.encode() + b\"|\")\n        with open(path, \"rb\") as f:\n            h.update(f.read())\n    # Hash librt module files\n    for mod, files, extra, includes in LIBRT_MODULES:\n        for fname in files + extra:\n            path = os.path.join(include_dir(), fname)\n            h.update(fname.encode() + b\"|\")\n            with open(path, \"rb\") as f:\n                h.update(f.read())\n    return h.hexdigest()[:16]\n\n\ndef _generate_setup_py(build_dir: str, experimental: bool, opt_level: str) -> str:\n    \"\"\"Generate setup.py content for building librt directly.\n\n    We inline LIBRT_MODULES/RUNTIME_C_FILES/include_dir/cflags values to avoid\n    importing mypyc.build, which recursively imports lots of things.\n    \"\"\"\n    lib_rt_dir = include_dir()\n\n    # Get compiler flags using the shared helper\n    cflags = get_cflags(opt_level=opt_level, experimental_features=experimental)\n\n    # Serialize values to inline in generated setup.py\n    librt_modules_repr = repr(\n        [(m.module, m.c_files, m.other_files, m.include_dirs) for m in LIBRT_MODULES]\n    )\n    runtime_files_repr = repr(RUNTIME_C_FILES)\n    cflags_repr = repr(cflags)\n\n    return f\"\"\"\\\nimport os\nfrom setuptools import setup, Extension\nimport build_setup  # noqa: F401  # Monkey-patches compiler for per-file SIMD flags\n\nbuild_dir = {build_dir!r}\nlib_rt_dir = {lib_rt_dir!r}\n\nRUNTIME_C_FILES = {runtime_files_repr}\nLIBRT_MODULES = {librt_modules_repr}\nCFLAGS = {cflags_repr}\n\ndef write_file(path, contents):\n    os.makedirs(os.path.dirname(path), exist_ok=True)\n    with open(path, \"wb\") as f:\n        f.write(contents)\n\n# Copy runtime C files\nfor name in RUNTIME_C_FILES:\n    src = os.path.join(lib_rt_dir, name)\n    dst = os.path.join(build_dir, name)\n    with open(src, \"rb\") as f:\n        write_file(dst, f.read())\n\n# Build extensions for each librt module\nextensions = []\nfor mod, file_names, extra_files, includes in LIBRT_MODULES:\n    # Copy source files\n    for fname in file_names + extra_files:\n        src = os.path.join(lib_rt_dir, fname)\n        dst = os.path.join(build_dir, fname)\n        with open(src, \"rb\") as f:\n            write_file(dst, f.read())\n\n    extensions.append(Extension(\n        mod,\n        sources=[os.path.join(build_dir, f) for f in file_names + RUNTIME_C_FILES],\n        include_dirs=[lib_rt_dir] + [os.path.join(lib_rt_dir, d) for d in includes],\n        extra_compile_args=CFLAGS,\n    ))\n\nsetup(name='librt_cached', ext_modules=extensions)\n\"\"\"\n\n\ndef get_librt_path(experimental: bool = True, opt_level: str = \"0\") -> str:\n    \"\"\"Get path to librt built from the repository, building and caching if necessary.\n\n    Uses build/librt-cache/ under the repo root (gitignored). The cache is\n    keyed by a hash of sources and build environment, so it auto-invalidates\n    when relevant factors change.\n\n    Safe to call from multiple parallel pytest workers - uses file locking.\n\n    Args:\n        experimental: Whether to enable experimental features.\n        opt_level: Optimization level (\"0\"..\"3\") used when building librt.\n\n    Returns:\n        Path to directory containing built librt modules.\n    \"\"\"\n    # Use build/librt-cache/ under the repo root (gitignored)\n    repo_root = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n    cache_root = os.path.join(repo_root, \"build\", \"librt-cache\")\n    build_hash = _librt_build_hash(experimental, opt_level)\n    build_dir = os.path.join(cache_root, f\"librt-{build_hash}\")\n    lock_file = os.path.join(cache_root, f\"librt-{build_hash}.lock\")\n    marker = os.path.join(build_dir, \".complete\")\n\n    os.makedirs(cache_root, exist_ok=True)\n\n    with filelock.FileLock(lock_file, timeout=300):  # 5 min timeout\n        if os.path.exists(marker):\n            return build_dir\n\n        # Clean up any partial build\n        if os.path.exists(build_dir):\n            shutil.rmtree(build_dir)\n\n        os.makedirs(build_dir)\n\n        # Create librt package directory for --inplace to copy .so files into\n        librt_pkg = os.path.join(build_dir, \"librt\")\n        os.makedirs(librt_pkg)\n        with open(os.path.join(librt_pkg, \"__init__.py\"), \"w\") as f:\n            pass\n\n        # Copy build_setup.py for per-file SIMD compiler flags\n        build_setup_src = os.path.join(\n            os.path.dirname(os.path.dirname(os.path.abspath(__file__))), \"build_setup.py\"\n        )\n        build_setup_dst = os.path.join(build_dir, \"build_setup.py\")\n        shutil.copy(build_setup_src, build_setup_dst)\n\n        # Write setup.py\n        setup_py = os.path.join(build_dir, \"setup.py\")\n        with open(setup_py, \"w\") as f:\n            f.write(_generate_setup_py(build_dir, experimental, opt_level))\n\n        # Build (parallel builds don't work well because multiple extensions\n        # share the same runtime C files, causing race conditions)\n        result = subprocess.run(\n            [sys.executable, setup_py, \"build_ext\", \"--inplace\"],\n            cwd=build_dir,\n            capture_output=True,\n            text=True,\n        )\n        if result.returncode != 0:\n            raise RuntimeError(f\"librt build failed:\\n{result.stdout}\\n{result.stderr}\")\n\n        # Mark complete\n        with open(marker, \"w\") as f:\n            f.write(\"ok\")\n\n    return build_dir\n\n\ndef run_with_librt(\n    file_path: str, experimental: bool = True, check: bool = True, opt_level: str = \"0\"\n) -> subprocess.CompletedProcess[str]:\n    \"\"\"Run a Python file in a subprocess with built librt available.\n\n    This runs the file in a fresh Python process where the built librt\n    is at the front of sys.path, avoiding conflicts with any system librt.\n\n    Args:\n        file_path: Path to Python file to execute.\n        experimental: Whether to use experimental features.\n        check: If True, raise CalledProcessError on non-zero exit.\n        opt_level: Optimization level (\"0\"..\"3\") used when building librt.\n\n    Returns:\n        CompletedProcess with stdout, stderr, and returncode.\n    \"\"\"\n    librt_path = get_librt_path(experimental, opt_level=opt_level)\n    # Prepend librt path to PYTHONPATH\n    env = os.environ.copy()\n    existing = env.get(\"PYTHONPATH\", \"\")\n    env[\"PYTHONPATH\"] = librt_path + (os.pathsep + existing if existing else \"\")\n\n    return subprocess.run(\n        [sys.executable, file_path], capture_output=True, text=True, check=check, env=env\n    )\n"
  },
  {
    "path": "mypyc/test/test_alwaysdefined.py",
    "content": "\"\"\"Test cases for inferring always defined attributes in classes.\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\n\nfrom mypy.errors import CompileError\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypyc.test.testutil import (\n    ICODE_GEN_BUILTINS,\n    MypycDataSuite,\n    assert_test_output,\n    build_ir_for_single_file2,\n    infer_ir_build_options_from_test_name,\n    use_custom_builtins,\n)\n\nfiles = [\"alwaysdefined.test\"]\n\n\nclass TestAlwaysDefined(MypycDataSuite):\n    files = files\n    base_path = test_temp_dir\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        \"\"\"Perform a runtime checking transformation test case.\"\"\"\n        options = infer_ir_build_options_from_test_name(testcase.name)\n        if options is None:\n            # Skipped test case\n            return\n        with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):\n            try:\n                ir = build_ir_for_single_file2(testcase.input, options)[0]\n            except CompileError as e:\n                actual = e.messages\n            else:\n                actual = []\n                for cl in ir.classes:\n                    if cl.name.startswith(\"_\"):\n                        continue\n                    actual.append(\n                        \"{}: [{}]\".format(cl.name, \", \".join(sorted(cl._always_initialized_attrs)))\n                    )\n\n            assert_test_output(testcase, actual, \"Invalid test output\", testcase.output)\n"
  },
  {
    "path": "mypyc/test/test_analysis.py",
    "content": "\"\"\"Test runner for data-flow analysis test cases.\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\n\nfrom mypy.errors import CompileError\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypyc.analysis import dataflow\nfrom mypyc.common import TOP_LEVEL_NAME\nfrom mypyc.ir.func_ir import all_values\nfrom mypyc.ir.ops import Value\nfrom mypyc.ir.pprint import format_func, generate_names_for_ir\nfrom mypyc.test.testutil import (\n    ICODE_GEN_BUILTINS,\n    MypycDataSuite,\n    assert_test_output,\n    build_ir_for_single_file,\n    use_custom_builtins,\n)\nfrom mypyc.transform import exceptions\n\nfiles = [\"analysis.test\"]\n\n\nclass TestAnalysis(MypycDataSuite):\n    files = files\n    base_path = test_temp_dir\n    optional_out = True\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        \"\"\"Perform a data-flow analysis test case.\"\"\"\n\n        with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):\n            try:\n                ir = build_ir_for_single_file(testcase.input)\n            except CompileError as e:\n                actual = e.messages\n            else:\n                actual = []\n                for fn in ir:\n                    if fn.name == TOP_LEVEL_NAME and not testcase.name.endswith(\"_toplevel\"):\n                        continue\n                    exceptions.insert_exception_handling(fn, True)\n                    actual.extend(format_func(fn))\n                    cfg = dataflow.get_cfg(fn.blocks)\n                    args: set[Value] = set(fn.arg_regs)\n                    name = testcase.name\n                    if name.endswith(\"_MaybeDefined\"):\n                        # Forward, maybe\n                        analysis_result = dataflow.analyze_maybe_defined_regs(fn.blocks, cfg, args)\n                    elif name.endswith(\"_Liveness\"):\n                        # Backward, maybe\n                        analysis_result = dataflow.analyze_live_regs(fn.blocks, cfg)\n                    elif name.endswith(\"_MustDefined\"):\n                        # Forward, must\n                        analysis_result = dataflow.analyze_must_defined_regs(\n                            fn.blocks, cfg, args, regs=all_values(fn.arg_regs, fn.blocks)\n                        )\n                    elif name.endswith(\"_BorrowedArgument\"):\n                        # Forward, must\n                        analysis_result = dataflow.analyze_borrowed_arguments(fn.blocks, cfg, args)\n                    else:\n                        assert False, \"No recognized _AnalysisName suffix in test case\"\n\n                    names = generate_names_for_ir(fn.arg_regs, fn.blocks)\n\n                    for key in sorted(\n                        analysis_result.before.keys(), key=lambda x: (x[0].label, x[1])\n                    ):\n                        pre = \", \".join(sorted(names[reg] for reg in analysis_result.before[key]))\n                        post = \", \".join(sorted(names[reg] for reg in analysis_result.after[key]))\n                        actual.append(\n                            \"%-8s %-23s %s\" % ((key[0].label, key[1]), \"{%s}\" % pre, \"{%s}\" % post)\n                        )\n            assert_test_output(testcase, actual, \"Invalid source code output\")\n"
  },
  {
    "path": "mypyc/test/test_annotate.py",
    "content": "\"\"\"Test cases for annotating source code to highlight inefficiencies.\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\n\nfrom mypy.errors import CompileError\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypyc.annotate import generate_annotations, get_max_prio\nfrom mypyc.ir.pprint import format_func\nfrom mypyc.test.testutil import (\n    ICODE_GEN_BUILTINS,\n    MypycDataSuite,\n    assert_test_output,\n    build_ir_for_single_file2,\n    infer_ir_build_options_from_test_name,\n    remove_comment_lines,\n    use_custom_builtins,\n)\n\nfiles = [\"annotate-basic.test\"]\n\n\nclass TestReport(MypycDataSuite):\n    files = files\n    base_path = test_temp_dir\n    optional_out = True\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        \"\"\"Perform a runtime checking transformation test case.\"\"\"\n        options = infer_ir_build_options_from_test_name(testcase.name)\n        if options is None:\n            # Skipped test case\n            return\n        with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):\n            expected_output = remove_comment_lines(testcase.output)\n\n            # Parse \"# A: <message>\" comments.\n            for i, line in enumerate(testcase.input):\n                if \"# A:\" in line:\n                    msg = line.rpartition(\"# A:\")[2].strip()\n                    expected_output.append(f\"main:{i + 1}: {msg}\")\n\n            ir = None\n            try:\n                ir, tree, type_map, mapper = build_ir_for_single_file2(testcase.input, options)\n            except CompileError as e:\n                actual = e.messages\n            else:\n                annotations = generate_annotations(\"native.py\", tree, ir, type_map, mapper)\n                actual = []\n                for line_num, line_anns in sorted(\n                    annotations.annotations.items(), key=lambda it: it[0]\n                ):\n                    anns = get_max_prio(line_anns)\n                    str_anns = [a.message for a in anns]\n                    s = \" \".join(str_anns)\n                    actual.append(f\"main:{line_num}: {s}\")\n\n            try:\n                assert_test_output(testcase, actual, \"Invalid source code output\", expected_output)\n            except BaseException:\n                if ir:\n                    print(\"Generated IR:\\n\")\n                    for fn in ir.functions:\n                        if fn.name == \"__top_level__\":\n                            continue\n                        for s in format_func(fn):\n                            print(s)\n                raise\n"
  },
  {
    "path": "mypyc/test/test_capsule_deps.py",
    "content": "\"\"\"Test cases for capsule dependency analysis.\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\n\nfrom mypy.errors import CompileError\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypyc.analysis.capsule_deps import find_class_dependencies, find_implicit_op_dependencies\nfrom mypyc.options import CompilerOptions\nfrom mypyc.test.testutil import (\n    ICODE_GEN_BUILTINS,\n    MypycDataSuite,\n    assert_test_output,\n    build_ir_for_single_file2,\n    infer_ir_build_options_from_test_name,\n    use_custom_builtins,\n)\nfrom mypyc.transform.lower import lower_ir\n\nfiles = [\"capsule-deps.test\"]\n\n\nclass TestCapsuleDeps(MypycDataSuite):\n    files = files\n    base_path = test_temp_dir\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        options = infer_ir_build_options_from_test_name(testcase.name)\n        if options is None:\n            # Skipped test case\n            return\n        with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):\n            try:\n                module_ir, _, _, _ = build_ir_for_single_file2(testcase.input, options)\n            except CompileError as e:\n                actual = e.messages\n            else:\n                all_deps: set[str] = set()\n                for fn in module_ir.functions:\n                    compiler_options = CompilerOptions()\n                    lower_ir(fn, compiler_options)\n                    deps = find_implicit_op_dependencies(fn)\n                    if deps:\n                        for dep in deps:\n                            all_deps.add(repr(dep))\n                for cl in module_ir.classes:\n                    deps = find_class_dependencies(cl)\n                    if deps:\n                        for dep in deps:\n                            all_deps.add(repr(dep))\n                actual = sorted(all_deps) if all_deps else [\"No deps\"]\n\n            assert_test_output(testcase, actual, \"Invalid test output\", testcase.output)\n"
  },
  {
    "path": "mypyc/test/test_cheader.py",
    "content": "\"\"\"Test that C functions used in primitives are declared in a header such as CPy.h.\"\"\"\n\nfrom __future__ import annotations\n\nimport glob\nimport os\nimport re\nimport unittest\n\nfrom mypyc.ir.deps import SourceDep\nfrom mypyc.ir.ops import PrimitiveDescription\nfrom mypyc.primitives import (\n    bytearray_ops,\n    bytes_ops,\n    dict_ops,\n    exc_ops,\n    float_ops,\n    generic_ops,\n    int_ops,\n    librt_strings_ops,\n    librt_vecs_ops,\n    list_ops,\n    misc_ops,\n    registry,\n    set_ops,\n    str_ops,\n    tuple_ops,\n    weakref_ops,\n)\n\n\nclass TestHeaderInclusion(unittest.TestCase):\n    def test_primitives_included_in_header(self) -> None:\n        base_dir = os.path.join(os.path.dirname(__file__), \"..\", \"lib-rt\")\n        with open(os.path.join(base_dir, \"CPy.h\")) as f:\n            header = f.read()\n        with open(os.path.join(base_dir, \"pythonsupport.h\")) as f:\n            header += f.read()\n\n        def check_name(name: str) -> None:\n            if name.startswith(\"CPy\"):\n                assert re.search(\n                    rf\"\\b{name}\\b\", header\n                ), f'\"{name}\" is used in mypyc.primitives but not declared in CPy.h'\n\n        all_ops = []\n        for values in [\n            registry.method_call_ops.values(),\n            registry.binary_ops.values(),\n            registry.unary_ops.values(),\n            registry.function_ops.values(),\n        ]:\n            for ops in values:\n                all_ops.extend(ops)\n\n        for module in [\n            bytes_ops,\n            str_ops,\n            dict_ops,\n            list_ops,\n            bytearray_ops,\n            generic_ops,\n            int_ops,\n            misc_ops,\n            tuple_ops,\n            exc_ops,\n            float_ops,\n            set_ops,\n            weakref_ops,\n            librt_vecs_ops,\n            librt_strings_ops,\n        ]:\n            for name in dir(module):\n                val = getattr(module, name, None)\n                if isinstance(val, PrimitiveDescription):\n                    all_ops.append(val)\n\n        # Find additional headers via extra C source file dependencies.\n        for op in all_ops:\n            if op.dependencies:\n                for dep in op.dependencies:\n                    if isinstance(dep, SourceDep):\n                        header_fnam = os.path.join(base_dir, dep.get_header())\n                        if os.path.isfile(header_fnam):\n                            with open(os.path.join(base_dir, header_fnam)) as f:\n                                header += f.read()\n\n        for op in all_ops:\n            if op.c_function_name is not None:\n                check_name(op.c_function_name)\n\n        primitives_path = os.path.join(os.path.dirname(__file__), \"..\", \"primitives\")\n        for fnam in glob.glob(f\"{primitives_path}/*.py\"):\n            with open(fnam) as f:\n                content = f.read()\n            for name in re.findall(r'c_function_name=[\"\\'](CPy[A-Z_a-z0-9]+)', content):\n                check_name(name)\n"
  },
  {
    "path": "mypyc/test/test_commandline.py",
    "content": "\"\"\"Test cases for invoking mypyc on the command line.\n\nThese are slow -- do not add test cases unless you have a very good reason to do so.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport glob\nimport os\nimport os.path\nimport re\nimport subprocess\nimport sys\n\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypy.test.helpers import normalize_error_messages\nfrom mypyc.test.testutil import MypycDataSuite, assert_test_output\n\nfiles = [\"commandline.test\"]\n\n\nbase_path = os.path.join(os.path.dirname(__file__), \"..\", \"..\")\n\npython3_path = sys.executable\n\n\nclass TestCommandLine(MypycDataSuite):\n    files = files\n    base_path = test_temp_dir\n    optional_out = True\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        # Parse options from test case description (arguments must not have spaces)\n        text = \"\\n\".join(testcase.input)\n        m = re.search(r\"# *cmd: *(.*)\", text)\n        assert m is not None, 'Test case missing \"# cmd: <files>\" section'\n        args = m.group(1).split()\n\n        # Write main program to run (not compiled)\n        program = \"_%s.py\" % testcase.name\n        program_path = os.path.join(test_temp_dir, program)\n        with open(program_path, \"w\") as f:\n            f.write(text)\n\n        env = os.environ.copy()\n        env[\"PYTHONPATH\"] = base_path\n\n        out = b\"\"\n        try:\n            # Compile program\n            cmd = subprocess.run(\n                [sys.executable, \"-m\", \"mypyc\", *args],\n                stdout=subprocess.PIPE,\n                stderr=subprocess.STDOUT,\n                cwd=\"tmp\",\n                env=env,\n            )\n            if \"ErrorOutput\" in testcase.name or cmd.returncode != 0:\n                out += cmd.stdout\n            elif \"WarningOutput\" in testcase.name:\n                # Strip out setuptools build related output since we're only\n                # interested in the messages emitted during compilation.\n                messages, _, _ = cmd.stdout.partition(b\"running build_ext\")\n                out += messages\n\n            if cmd.returncode == 0:\n                # Run main program\n                out += subprocess.check_output([python3_path, program], cwd=\"tmp\")\n        finally:\n            suffix = \"pyd\" if sys.platform == \"win32\" else \"so\"\n            so_paths = glob.glob(f\"tmp/**/*.{suffix}\", recursive=True)\n            for path in so_paths:\n                os.remove(path)\n\n        # Strip out 'tmp/' from error message paths in the testcase output,\n        # due to a mismatch between this test and mypy's test suite.\n        expected = [x.replace(\"tmp/\", \"\") for x in testcase.output]\n\n        # Verify output\n        actual = normalize_error_messages(out.decode().splitlines())\n        assert_test_output(testcase, actual, \"Invalid output\", expected=expected)\n"
  },
  {
    "path": "mypyc/test/test_emit.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypyc.codegen.emit import Emitter, EmitterContext\nfrom mypyc.common import HAVE_IMMORTAL\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.ops import BasicBlock, Register, Value\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RTuple,\n    RUnion,\n    bool_rprimitive,\n    int_rprimitive,\n    list_rprimitive,\n    none_rprimitive,\n    object_rprimitive,\n    str_rprimitive,\n)\nfrom mypyc.irbuild.vtable import compute_vtable\nfrom mypyc.namegen import NameGenerator\n\n\nclass TestEmitter(unittest.TestCase):\n    def setUp(self) -> None:\n        self.n = Register(int_rprimitive, \"n\")\n        self.context = EmitterContext(NameGenerator([[\"mod\"]]), True)\n        self.emitter = Emitter(self.context, {})\n\n        ir = ClassIR(\"A\", \"mod\")\n        compute_vtable(ir)\n        ir.mro = [ir]\n        self.instance_a = RInstance(ir)\n\n    def test_label(self) -> None:\n        assert self.emitter.label(BasicBlock(4)) == \"CPyL4\"\n\n    def test_reg(self) -> None:\n        names: dict[Value, str] = {self.n: \"n\"}\n        emitter = Emitter(self.context, names)\n        assert emitter.reg(self.n) == \"cpy_r_n\"\n\n    def test_object_annotation(self) -> None:\n        assert self.emitter.object_annotation(\"hello, world\", \"line;\") == \" /* 'hello, world' */\"\n        assert self.emitter.object_annotation(list(range(30)), \"line;\") == \"\"\"\\\n /* [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,\n         23, 24, 25, 26, 27, 28, 29] */\"\"\"\n\n    def test_emit_line(self) -> None:\n        emitter = self.emitter\n        emitter.emit_line(\"line;\")\n        emitter.emit_line(\"a {\")\n        emitter.emit_line(\"f();\")\n        emitter.emit_line(\"}\")\n        assert emitter.fragments == [\"line;\\n\", \"a {\\n\", \"    f();\\n\", \"}\\n\"]\n        emitter = Emitter(self.context, {})\n        emitter.emit_line(\"CPyStatics[0];\", ann=\"hello, world\")\n        emitter.emit_line(\"CPyStatics[1];\", ann=list(range(30)))\n        assert emitter.fragments[0] == \"CPyStatics[0]; /* 'hello, world' */\\n\"\n        assert emitter.fragments[1] == \"\"\"\\\nCPyStatics[1]; /* [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,\n                  21, 22, 23, 24, 25, 26, 27, 28, 29] */\\n\"\"\"\n\n    def test_emit_undefined_value_for_simple_type(self) -> None:\n        emitter = self.emitter\n        assert emitter.c_undefined_value(int_rprimitive) == \"CPY_INT_TAG\"\n        assert emitter.c_undefined_value(str_rprimitive) == \"NULL\"\n        assert emitter.c_undefined_value(bool_rprimitive) == \"2\"\n\n    def test_emit_undefined_value_for_tuple(self) -> None:\n        emitter = self.emitter\n        assert (\n            emitter.c_undefined_value(RTuple([str_rprimitive, int_rprimitive, bool_rprimitive]))\n            == \"(tuple_T3OIC) { NULL, CPY_INT_TAG, 2 }\"\n        )\n        assert emitter.c_undefined_value(RTuple([str_rprimitive])) == \"(tuple_T1O) { NULL }\"\n        assert (\n            emitter.c_undefined_value(RTuple([RTuple([str_rprimitive]), bool_rprimitive]))\n            == \"(tuple_T2T1OC) { { NULL }, 2 }\"\n        )\n\n    def test_emit_inc_ref_object(self) -> None:\n        self.emitter.emit_inc_ref(\"x\", object_rprimitive)\n        self.assert_output(\"CPy_INCREF(x);\\n\")\n\n    def test_emit_inc_ref_int(self) -> None:\n        self.emitter.emit_inc_ref(\"x\", int_rprimitive)\n        self.assert_output(\"CPyTagged_INCREF(x);\\n\")\n\n    def test_emit_inc_ref_rare(self) -> None:\n        self.emitter.emit_inc_ref(\"x\", object_rprimitive, rare=True)\n        self.assert_output(\"CPy_INCREF(x);\\n\")\n        self.emitter.emit_inc_ref(\"x\", int_rprimitive, rare=True)\n        self.assert_output(\"CPyTagged_IncRef(x);\\n\")\n\n    def test_emit_inc_ref_list(self) -> None:\n        self.emitter.emit_inc_ref(\"x\", list_rprimitive)\n        if HAVE_IMMORTAL:\n            self.assert_output(\"CPy_INCREF_NO_IMM(x);\\n\")\n        else:\n            self.assert_output(\"CPy_INCREF(x);\\n\")\n\n    def test_emit_inc_ref_instance(self) -> None:\n        self.emitter.emit_inc_ref(\"x\", self.instance_a)\n        if HAVE_IMMORTAL:\n            self.assert_output(\"CPy_INCREF_NO_IMM(x);\\n\")\n        else:\n            self.assert_output(\"CPy_INCREF(x);\\n\")\n\n    def test_emit_inc_ref_optional(self) -> None:\n        optional = RUnion([self.instance_a, none_rprimitive])\n        self.emitter.emit_inc_ref(\"o\", optional)\n        self.assert_output(\"CPy_INCREF(o);\\n\")\n\n    def test_emit_dec_ref_object(self) -> None:\n        self.emitter.emit_dec_ref(\"x\", object_rprimitive)\n        self.assert_output(\"CPy_DECREF(x);\\n\")\n        self.emitter.emit_dec_ref(\"x\", object_rprimitive, is_xdec=True)\n        self.assert_output(\"CPy_XDECREF(x);\\n\")\n\n    def test_emit_dec_ref_int(self) -> None:\n        self.emitter.emit_dec_ref(\"x\", int_rprimitive)\n        self.assert_output(\"CPyTagged_DECREF(x);\\n\")\n        self.emitter.emit_dec_ref(\"x\", int_rprimitive, is_xdec=True)\n        self.assert_output(\"CPyTagged_XDECREF(x);\\n\")\n\n    def test_emit_dec_ref_rare(self) -> None:\n        self.emitter.emit_dec_ref(\"x\", object_rprimitive, rare=True)\n        self.assert_output(\"CPy_DecRef(x);\\n\")\n        self.emitter.emit_dec_ref(\"x\", int_rprimitive, rare=True)\n        self.assert_output(\"CPyTagged_DecRef(x);\\n\")\n\n    def test_emit_dec_ref_list(self) -> None:\n        self.emitter.emit_dec_ref(\"x\", list_rprimitive)\n        if HAVE_IMMORTAL:\n            self.assert_output(\"CPy_DECREF_NO_IMM(x);\\n\")\n        else:\n            self.assert_output(\"CPy_DECREF(x);\\n\")\n        self.emitter.emit_dec_ref(\"x\", list_rprimitive, is_xdec=True)\n        if HAVE_IMMORTAL:\n            self.assert_output(\"CPy_XDECREF_NO_IMM(x);\\n\")\n        else:\n            self.assert_output(\"CPy_XDECREF(x);\\n\")\n\n    def test_emit_dec_ref_instance(self) -> None:\n        self.emitter.emit_dec_ref(\"x\", self.instance_a)\n        if HAVE_IMMORTAL:\n            self.assert_output(\"CPy_DECREF_NO_IMM(x);\\n\")\n        else:\n            self.assert_output(\"CPy_DECREF(x);\\n\")\n        self.emitter.emit_dec_ref(\"x\", self.instance_a, is_xdec=True)\n        if HAVE_IMMORTAL:\n            self.assert_output(\"CPy_XDECREF_NO_IMM(x);\\n\")\n        else:\n            self.assert_output(\"CPy_XDECREF(x);\\n\")\n\n    def test_emit_dec_ref_optional(self) -> None:\n        optional = RUnion([self.instance_a, none_rprimitive])\n        self.emitter.emit_dec_ref(\"o\", optional)\n        self.assert_output(\"CPy_DECREF(o);\\n\")\n\n    def assert_output(self, expected: str) -> None:\n        assert \"\".join(self.emitter.fragments) == expected\n        self.emitter.fragments = []\n"
  },
  {
    "path": "mypyc/test/test_emitclass.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypyc.codegen.emitclass import getter_name, setter_name, slot_key\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.namegen import NameGenerator\n\n\nclass TestEmitClass(unittest.TestCase):\n    def test_slot_key(self) -> None:\n        attrs = [\"__add__\", \"__radd__\", \"__rshift__\", \"__rrshift__\", \"__setitem__\", \"__delitem__\"]\n        s = sorted(attrs, key=lambda x: slot_key(x))\n        # __delitem__ and reverse methods should come last.\n        assert s == [\n            \"__add__\",\n            \"__rshift__\",\n            \"__setitem__\",\n            \"__delitem__\",\n            \"__radd__\",\n            \"__rrshift__\",\n        ]\n\n    def test_setter_name(self) -> None:\n        cls = ClassIR(module_name=\"testing\", name=\"SomeClass\")\n        generator = NameGenerator([[\"mod\"]])\n\n        # This should never be `setup`, as it will conflict with the class `setup`\n        assert setter_name(cls, \"up\", generator) == \"testing___SomeClass_set_up\"\n\n    def test_getter_name(self) -> None:\n        cls = ClassIR(module_name=\"testing\", name=\"SomeClass\")\n        generator = NameGenerator([[\"mod\"]])\n\n        assert getter_name(cls, \"down\", generator) == \"testing___SomeClass_get_down\"\n"
  },
  {
    "path": "mypyc/test/test_emitfunc.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypy.test.helpers import assert_string_arrays_equal\nfrom mypyc.codegen.emit import Emitter, EmitterContext\nfrom mypyc.codegen.emitfunc import FunctionEmitterVisitor, generate_native_function\nfrom mypyc.common import HAVE_IMMORTAL, PLATFORM_SIZE\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature, RuntimeArg\nfrom mypyc.ir.ops import (\n    ERR_NEVER,\n    Assign,\n    AssignMulti,\n    BasicBlock,\n    Box,\n    Branch,\n    Call,\n    CallC,\n    Cast,\n    ComparisonOp,\n    CString,\n    DecRef,\n    Extend,\n    GetAttr,\n    GetElementPtr,\n    Goto,\n    IncRef,\n    Integer,\n    IntOp,\n    LoadAddress,\n    LoadLiteral,\n    LoadMem,\n    Op,\n    Register,\n    Return,\n    SetAttr,\n    SetElement,\n    SetMem,\n    TupleGet,\n    Unbox,\n    Undef,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.pprint import generate_names_for_ir\nfrom mypyc.ir.rtypes import (\n    RArray,\n    RInstance,\n    RStruct,\n    RTuple,\n    RType,\n    RUnion,\n    RVec,\n    bool_rprimitive,\n    c_int_rprimitive,\n    cstring_rprimitive,\n    dict_rprimitive,\n    int32_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    list_rprimitive,\n    none_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    short_int_rprimitive,\n    str_rprimitive,\n)\nfrom mypyc.irbuild.vtable import compute_vtable\nfrom mypyc.namegen import NameGenerator\nfrom mypyc.primitives.dict_ops import (\n    dict_get_item_op,\n    dict_new_op,\n    dict_set_item_op,\n    dict_update_op,\n)\nfrom mypyc.primitives.int_ops import int_neg_op\nfrom mypyc.primitives.list_ops import list_append_op, list_get_item_op, list_set_item_op\nfrom mypyc.primitives.misc_ops import none_object_op\nfrom mypyc.primitives.registry import binary_ops\nfrom mypyc.subtype import is_subtype\n\n\nclass TestFunctionEmitterVisitor(unittest.TestCase):\n    \"\"\"Test generation of fragments of C from individual IR ops.\"\"\"\n\n    def setUp(self) -> None:\n        self.registers: list[Register] = []\n\n        def add_local(name: str, rtype: RType) -> Register:\n            reg = Register(rtype, name)\n            self.registers.append(reg)\n            return reg\n\n        self.n = add_local(\"n\", int_rprimitive)\n        self.m = add_local(\"m\", int_rprimitive)\n        self.k = add_local(\"k\", int_rprimitive)\n        self.l = add_local(\"l\", list_rprimitive)\n        self.ll = add_local(\"ll\", list_rprimitive)\n        self.o = add_local(\"o\", object_rprimitive)\n        self.o2 = add_local(\"o2\", object_rprimitive)\n        self.d = add_local(\"d\", dict_rprimitive)\n        self.b = add_local(\"b\", bool_rprimitive)\n        self.s1 = add_local(\"s1\", short_int_rprimitive)\n        self.s2 = add_local(\"s2\", short_int_rprimitive)\n        self.i32 = add_local(\"i32\", int32_rprimitive)\n        self.i32_1 = add_local(\"i32_1\", int32_rprimitive)\n        self.i64 = add_local(\"i64\", int64_rprimitive)\n        self.i64_1 = add_local(\"i64_1\", int64_rprimitive)\n        self.ptr = add_local(\"ptr\", pointer_rprimitive)\n        self.t = add_local(\"t\", RTuple([int_rprimitive, bool_rprimitive]))\n        self.tt = add_local(\n            \"tt\", RTuple([RTuple([int_rprimitive, bool_rprimitive]), bool_rprimitive])\n        )\n        self.vi64 = add_local(\"vi64\", RVec(int64_rprimitive))\n        self.vi32 = add_local(\"vi32\", RVec(int32_rprimitive))\n        self.vs = add_local(\"vs\", RVec(str_rprimitive))\n        self.vs_opt = add_local(\"vs\", RVec(RUnion([str_rprimitive, none_rprimitive])))\n        self.vvs = add_local(\"vvs\", RVec(RVec(str_rprimitive)))\n        ir = ClassIR(\"A\", \"mod\")\n        ir.attributes = {\n            \"x\": bool_rprimitive,\n            \"y\": int_rprimitive,\n            \"i1\": int64_rprimitive,\n            \"i2\": int32_rprimitive,\n            \"t\": RTuple([object_rprimitive, object_rprimitive]),\n        }\n        ir.bitmap_attrs = [\"i1\", \"i2\"]\n        compute_vtable(ir)\n        ir.mro = [ir]\n        self.r = add_local(\"r\", RInstance(ir))\n        self.none = add_local(\"none\", none_rprimitive)\n\n        self.struct_type = RStruct(\n            \"Foo\", [\"b\", \"x\", \"y\"], [bool_rprimitive, int32_rprimitive, int64_rprimitive]\n        )\n        self.st = add_local(\"st\", self.struct_type)\n\n        self.context = EmitterContext(NameGenerator([[\"mod\"]]), True)\n\n    def test_goto(self) -> None:\n        self.assert_emit(Goto(BasicBlock(2)), \"goto CPyL2;\")\n\n    def test_goto_next_block(self) -> None:\n        next_block = BasicBlock(2)\n        self.assert_emit(Goto(next_block), \"\", next_block=next_block)\n\n    def test_return(self) -> None:\n        self.assert_emit(Return(self.m), \"return cpy_r_m;\")\n\n    def test_integer(self) -> None:\n        self.assert_emit(Assign(self.n, Integer(5)), \"cpy_r_n = 10;\")\n        self.assert_emit(Assign(self.i32, Integer(5, c_int_rprimitive)), \"cpy_r_i32 = 5;\")\n\n    def test_tuple_get(self) -> None:\n        self.assert_emit(TupleGet(self.t, 1, 0), \"cpy_r_r0 = cpy_r_t.f1;\")\n\n    def test_load_None(self) -> None:  # noqa: N802\n        self.assert_emit(\n            LoadAddress(none_object_op.type, none_object_op.src, 0),\n            \"cpy_r_r0 = (PyObject *)&_Py_NoneStruct;\",\n        )\n\n    def test_assign_int(self) -> None:\n        self.assert_emit(Assign(self.m, self.n), \"cpy_r_m = cpy_r_n;\")\n\n    def test_int_add(self) -> None:\n        self.assert_emit_binary_op(\n            \"+\", self.n, self.m, self.k, \"cpy_r_r0 = CPyTagged_Add(cpy_r_m, cpy_r_k);\"\n        )\n\n    def test_int_sub(self) -> None:\n        self.assert_emit_binary_op(\n            \"-\", self.n, self.m, self.k, \"cpy_r_r0 = CPyTagged_Subtract(cpy_r_m, cpy_r_k);\"\n        )\n\n    def test_int_neg(self) -> None:\n        assert int_neg_op.c_function_name is not None\n        self.assert_emit(\n            CallC(\n                int_neg_op.c_function_name,\n                [self.m],\n                int_neg_op.return_type,\n                int_neg_op.steals,\n                int_neg_op.is_borrowed,\n                int_neg_op.is_borrowed,\n                int_neg_op.error_kind,\n                55,\n            ),\n            \"cpy_r_r0 = CPyTagged_Negate(cpy_r_m);\",\n        )\n\n    def test_branch(self) -> None:\n        self.assert_emit(\n            Branch(self.b, BasicBlock(8), BasicBlock(9), Branch.BOOL),\n            \"\"\"if (cpy_r_b) {\n                                goto CPyL8;\n                            } else\n                                goto CPyL9;\n                         \"\"\",\n        )\n        b = Branch(self.b, BasicBlock(8), BasicBlock(9), Branch.BOOL)\n        b.negated = True\n        self.assert_emit(\n            b,\n            \"\"\"if (!cpy_r_b) {\n                                goto CPyL8;\n                            } else\n                                goto CPyL9;\n                         \"\"\",\n        )\n\n    def test_branch_no_else(self) -> None:\n        next_block = BasicBlock(9)\n        b = Branch(self.b, BasicBlock(8), next_block, Branch.BOOL)\n        self.assert_emit(b, \"\"\"if (cpy_r_b) goto CPyL8;\"\"\", next_block=next_block)\n        next_block = BasicBlock(9)\n        b = Branch(self.b, BasicBlock(8), next_block, Branch.BOOL)\n        b.negated = True\n        self.assert_emit(b, \"\"\"if (!cpy_r_b) goto CPyL8;\"\"\", next_block=next_block)\n\n    def test_branch_no_else_negated(self) -> None:\n        next_block = BasicBlock(1)\n        b = Branch(self.b, next_block, BasicBlock(2), Branch.BOOL)\n        self.assert_emit(b, \"\"\"if (!cpy_r_b) goto CPyL2;\"\"\", next_block=next_block)\n        next_block = BasicBlock(1)\n        b = Branch(self.b, next_block, BasicBlock(2), Branch.BOOL)\n        b.negated = True\n        self.assert_emit(b, \"\"\"if (cpy_r_b) goto CPyL2;\"\"\", next_block=next_block)\n\n    def test_branch_is_error(self) -> None:\n        b = Branch(self.b, BasicBlock(8), BasicBlock(9), Branch.IS_ERROR)\n        self.assert_emit(\n            b,\n            \"\"\"if (cpy_r_b == 2) {\n                                goto CPyL8;\n                            } else\n                                goto CPyL9;\n                         \"\"\",\n        )\n        b = Branch(self.b, BasicBlock(8), BasicBlock(9), Branch.IS_ERROR)\n        b.negated = True\n        self.assert_emit(\n            b,\n            \"\"\"if (cpy_r_b != 2) {\n                                goto CPyL8;\n                            } else\n                                goto CPyL9;\n                         \"\"\",\n        )\n\n    def test_branch_is_error_next_block(self) -> None:\n        next_block = BasicBlock(8)\n        b = Branch(self.b, next_block, BasicBlock(9), Branch.IS_ERROR)\n        self.assert_emit(b, \"\"\"if (cpy_r_b != 2) goto CPyL9;\"\"\", next_block=next_block)\n        b = Branch(self.b, next_block, BasicBlock(9), Branch.IS_ERROR)\n        b.negated = True\n        self.assert_emit(b, \"\"\"if (cpy_r_b == 2) goto CPyL9;\"\"\", next_block=next_block)\n\n    def test_branch_rare(self) -> None:\n        self.assert_emit(\n            Branch(self.b, BasicBlock(8), BasicBlock(9), Branch.BOOL, rare=True),\n            \"\"\"if (unlikely(cpy_r_b)) {\n                                goto CPyL8;\n                            } else\n                                goto CPyL9;\n                         \"\"\",\n        )\n        next_block = BasicBlock(9)\n        self.assert_emit(\n            Branch(self.b, BasicBlock(8), next_block, Branch.BOOL, rare=True),\n            \"\"\"if (unlikely(cpy_r_b)) goto CPyL8;\"\"\",\n            next_block=next_block,\n        )\n        next_block = BasicBlock(8)\n        b = Branch(self.b, next_block, BasicBlock(9), Branch.BOOL, rare=True)\n        self.assert_emit(b, \"\"\"if (likely(!cpy_r_b)) goto CPyL9;\"\"\", next_block=next_block)\n        next_block = BasicBlock(8)\n        b = Branch(self.b, next_block, BasicBlock(9), Branch.BOOL, rare=True)\n        b.negated = True\n        self.assert_emit(b, \"\"\"if (likely(cpy_r_b)) goto CPyL9;\"\"\", next_block=next_block)\n\n    def test_call(self) -> None:\n        decl = FuncDecl(\n            \"myfn\", None, \"mod\", FuncSignature([RuntimeArg(\"m\", int_rprimitive)], int_rprimitive)\n        )\n        self.assert_emit(Call(decl, [self.m], 55), \"cpy_r_r0 = CPyDef_myfn(cpy_r_m);\")\n\n    def test_call_two_args(self) -> None:\n        decl = FuncDecl(\n            \"myfn\",\n            None,\n            \"mod\",\n            FuncSignature(\n                [RuntimeArg(\"m\", int_rprimitive), RuntimeArg(\"n\", int_rprimitive)], int_rprimitive\n            ),\n        )\n        self.assert_emit(\n            Call(decl, [self.m, self.k], 55), \"cpy_r_r0 = CPyDef_myfn(cpy_r_m, cpy_r_k);\"\n        )\n\n    def test_inc_ref(self) -> None:\n        self.assert_emit(IncRef(self.o), \"CPy_INCREF(cpy_r_o);\")\n        self.assert_emit(IncRef(self.o), \"CPy_INCREF(cpy_r_o);\", rare=True)\n\n    def test_dec_ref(self) -> None:\n        self.assert_emit(DecRef(self.o), \"CPy_DECREF(cpy_r_o);\")\n        self.assert_emit(DecRef(self.o), \"CPy_DecRef(cpy_r_o);\", rare=True)\n\n    def test_inc_ref_int(self) -> None:\n        self.assert_emit(IncRef(self.m), \"CPyTagged_INCREF(cpy_r_m);\")\n        self.assert_emit(IncRef(self.m), \"CPyTagged_IncRef(cpy_r_m);\", rare=True)\n\n    def test_dec_ref_int(self) -> None:\n        self.assert_emit(DecRef(self.m), \"CPyTagged_DECREF(cpy_r_m);\")\n        self.assert_emit(DecRef(self.m), \"CPyTagged_DecRef(cpy_r_m);\", rare=True)\n\n    def test_dec_ref_tuple(self) -> None:\n        self.assert_emit(DecRef(self.t), \"CPyTagged_DECREF(cpy_r_t.f0);\")\n\n    def test_dec_ref_tuple_nested(self) -> None:\n        self.assert_emit(DecRef(self.tt), \"CPyTagged_DECREF(cpy_r_tt.f0.f0);\")\n\n    def test_list_get_item(self) -> None:\n        self.assert_emit(\n            CallC(\n                str(list_get_item_op.c_function_name),\n                [self.m, self.k],\n                list_get_item_op.return_type,\n                list_get_item_op.steals,\n                list_get_item_op.is_borrowed,\n                list_get_item_op.error_kind,\n                55,\n            ),\n            \"\"\"cpy_r_r0 = CPyList_GetItem(cpy_r_m, cpy_r_k);\"\"\",\n        )\n\n    def test_list_set_item(self) -> None:\n        self.assert_emit(\n            CallC(\n                str(list_set_item_op.c_function_name),\n                [self.l, self.n, self.o],\n                list_set_item_op.return_type,\n                list_set_item_op.steals,\n                list_set_item_op.is_borrowed,\n                list_set_item_op.error_kind,\n                55,\n            ),\n            \"\"\"cpy_r_r0 = CPyList_SetItem(cpy_r_l, cpy_r_n, cpy_r_o);\"\"\",\n        )\n\n    def test_box_int(self) -> None:\n        self.assert_emit(Box(self.n), \"\"\"cpy_r_r0 = CPyTagged_StealAsObject(cpy_r_n);\"\"\")\n\n    def test_unbox_int(self) -> None:\n        self.assert_emit(\n            Unbox(self.m, int_rprimitive, 55),\n            \"\"\"if (likely(PyLong_Check(cpy_r_m)))\n                   cpy_r_r0 = CPyTagged_FromObject(cpy_r_m);\n               else {\n                   CPy_TypeError(\"int\", cpy_r_m); cpy_r_r0 = CPY_INT_TAG;\n               }\n               \"\"\",\n        )\n\n    def test_box_i64(self) -> None:\n        self.assert_emit(Box(self.i64), \"\"\"cpy_r_r0 = PyLong_FromLongLong(cpy_r_i64);\"\"\")\n\n    def test_unbox_i64(self) -> None:\n        self.assert_emit(\n            Unbox(self.o, int64_rprimitive, 55), \"\"\"cpy_r_r0 = CPyLong_AsInt64(cpy_r_o);\"\"\"\n        )\n\n    def test_box_vec(self) -> None:\n        self.assert_emit(Box(self.vi64), \"\"\"cpy_r_r0 = VecI64Api.box(cpy_r_vi64);\"\"\")\n        self.assert_emit(Box(self.vi32), \"\"\"cpy_r_r0 = VecI32Api.box(cpy_r_vi32);\"\"\")\n        self.assert_emit(\n            Box(self.vs), \"\"\"cpy_r_r0 = VecTApi.box(cpy_r_vs, (size_t)&PyUnicode_Type);\"\"\"\n        )\n        self.assert_emit(\n            Box(self.vs_opt),\n            \"\"\"cpy_r_r0 = VecTApi.box(cpy_r_vs, ((size_t)&PyUnicode_Type | 1));\"\"\",\n        )\n        self.assert_emit(Box(self.vvs), \"\"\"cpy_r_r0 = VecNestedApi.box(cpy_r_vvs);\"\"\")\n\n    def test_unbox_vec(self) -> None:\n        self.assert_emit(\n            Unbox(self.o, RVec(int64_rprimitive), 55),\n            \"\"\"cpy_r_r0 = VecI64Api.unbox(cpy_r_o);\n               if (VEC_IS_ERROR(cpy_r_r0)) {\n                   CPy_TypeError(\"vec[i64]\", cpy_r_o); cpy_r_r0 = (VecI64) { -1, NULL };\n               }\n               \"\"\",\n        )\n        self.assert_emit(\n            Unbox(self.o, RVec(int32_rprimitive), 55),\n            \"\"\"cpy_r_r0 = VecI32Api.unbox(cpy_r_o);\n               if (VEC_IS_ERROR(cpy_r_r0)) {\n                   CPy_TypeError(\"vec[i32]\", cpy_r_o); cpy_r_r0 = (VecI32) { -1, NULL };\n               }\n               \"\"\",\n        )\n        self.assert_emit(\n            Unbox(self.o, RVec(str_rprimitive), 55),\n            \"\"\"cpy_r_r0 = VecTApi.unbox(cpy_r_o, (size_t)&PyUnicode_Type);\n               if (VEC_IS_ERROR(cpy_r_r0)) {\n                   CPy_TypeError(\"vec[str]\", cpy_r_o); cpy_r_r0 = (VecT) { -1, NULL };\n               }\n               \"\"\",\n        )\n        self.assert_emit(\n            Unbox(self.o, RVec(RUnion([str_rprimitive, none_rprimitive])), 55),\n            \"\"\"cpy_r_r0 = VecTApi.unbox(cpy_r_o, ((size_t)&PyUnicode_Type | 1));\n               if (VEC_IS_ERROR(cpy_r_r0)) {\n                   CPy_TypeError(\"vec[str | None]\", cpy_r_o); cpy_r_r0 = (VecT) { -1, NULL };\n               }\n               \"\"\",\n        )\n        self.assert_emit(\n            Unbox(self.o, RVec(self.r.type), 55),\n            \"\"\"cpy_r_r0 = VecTApi.unbox(cpy_r_o, (size_t)CPyType_A);\n               if (VEC_IS_ERROR(cpy_r_r0)) {\n                   CPy_TypeError(\"vec[mod.A]\", cpy_r_o); cpy_r_r0 = (VecT) { -1, NULL };\n               }\n               \"\"\",\n        )\n\n    def test_unbox_vec_nested(self) -> None:\n        self.assert_emit(\n            Unbox(self.o, RVec(RVec(str_rprimitive)), 55),\n            \"\"\"cpy_r_r0 = VecNestedApi.unbox(cpy_r_o, (size_t)&PyUnicode_Type, 1);\n               if (VEC_IS_ERROR(cpy_r_r0)) {\n                   CPy_TypeError(\"vec[vec[str]]\", cpy_r_o); cpy_r_r0 = (VecNested) { -1, NULL };\n               }\n               \"\"\",\n        )\n        self.assert_emit(\n            Unbox(self.o, RVec(RVec(RUnion([str_rprimitive, none_rprimitive]))), 55),\n            \"\"\"cpy_r_r0 = VecNestedApi.unbox(cpy_r_o, ((size_t)&PyUnicode_Type | 1), 1);\n               if (VEC_IS_ERROR(cpy_r_r0)) {\n                   CPy_TypeError(\"vec[vec[str | None]]\", cpy_r_o); cpy_r_r0 = (VecNested) { -1, NULL };\n               }\n               \"\"\",\n        )\n        self.assert_emit(\n            Unbox(self.o, RVec(RVec(int64_rprimitive)), 55),\n            \"\"\"cpy_r_r0 = VecNestedApi.unbox(cpy_r_o, 2, 1);\n               if (VEC_IS_ERROR(cpy_r_r0)) {\n                   CPy_TypeError(\"vec[vec[i64]]\", cpy_r_o); cpy_r_r0 = (VecNested) { -1, NULL };\n               }\n               \"\"\",\n        )\n\n    def test_list_append(self) -> None:\n        self.assert_emit(\n            CallC(\n                str(list_append_op.c_function_name),\n                [self.l, self.o],\n                list_append_op.return_type,\n                list_append_op.steals,\n                list_append_op.is_borrowed,\n                list_append_op.error_kind,\n                1,\n            ),\n            \"\"\"cpy_r_r0 = PyList_Append(cpy_r_l, cpy_r_o);\"\"\",\n        )\n\n    def test_get_attr(self) -> None:\n        self.assert_emit(\n            GetAttr(self.r, \"y\", 1),\n            \"\"\"cpy_r_r0 = ((mod___AObject *)cpy_r_r)->_y;\n               if (unlikely(cpy_r_r0 == CPY_INT_TAG)) {\n                   PyErr_SetString(PyExc_AttributeError, \"attribute 'y' of 'A' undefined\");\n               } else {\n                   CPyTagged_INCREF(cpy_r_r0);\n               }\n            \"\"\",\n        )\n\n    def test_get_attr_non_refcounted(self) -> None:\n        self.assert_emit(\n            GetAttr(self.r, \"x\", 1),\n            \"\"\"cpy_r_r0 = ((mod___AObject *)cpy_r_r)->_x;\n               if (unlikely(cpy_r_r0 == 2)) {\n                   PyErr_SetString(PyExc_AttributeError, \"attribute 'x' of 'A' undefined\");\n               }\n            \"\"\",\n        )\n\n    def test_get_attr_merged(self) -> None:\n        op = GetAttr(self.r, \"y\", 1)\n        branch = Branch(op, BasicBlock(8), BasicBlock(9), Branch.IS_ERROR)\n        branch.traceback_entry = (\"foobar\", 123)\n        self.assert_emit(\n            op,\n            \"\"\"\\\n            cpy_r_r0 = ((mod___AObject *)cpy_r_r)->_y;\n            if (unlikely(cpy_r_r0 == CPY_INT_TAG)) {\n                CPy_AttributeError(\"prog.py\", \"foobar\", \"A\", \"y\", 123, CPyStatic_prog___globals);\n                goto CPyL8;\n            }\n            CPyTagged_INCREF(cpy_r_r0);\n            goto CPyL9;\n            \"\"\",\n            next_branch=branch,\n            skip_next=True,\n        )\n\n    def test_get_attr_with_bitmap(self) -> None:\n        self.assert_emit(\n            GetAttr(self.r, \"i1\", 1),\n            \"\"\"cpy_r_r0 = ((mod___AObject *)cpy_r_r)->_i1;\n               if (unlikely(cpy_r_r0 == -113) && !(((mod___AObject *)cpy_r_r)->bitmap & 1)) {\n                   PyErr_SetString(PyExc_AttributeError, \"attribute 'i1' of 'A' undefined\");\n               }\n            \"\"\",\n        )\n\n    def test_get_attr_nullable_with_tuple(self) -> None:\n        self.assert_emit(\n            GetAttr(self.r, \"t\", 1, allow_error_value=True),\n            \"\"\"cpy_r_r0 = ((mod___AObject *)cpy_r_r)->_t;\n               if (cpy_r_r0.f0 != NULL) {\n                   CPy_INCREF(cpy_r_r0.f0);\n                   CPy_INCREF(cpy_r_r0.f1);\n               }\n            \"\"\",\n        )\n\n    def test_set_attr(self) -> None:\n        self.assert_emit(\n            SetAttr(self.r, \"y\", self.m, 1),\n            \"\"\"if (((mod___AObject *)cpy_r_r)->_y != CPY_INT_TAG) {\n                   CPyTagged_DECREF(((mod___AObject *)cpy_r_r)->_y);\n               }\n               ((mod___AObject *)cpy_r_r)->_y = cpy_r_m;\n               cpy_r_r0 = 1;\n            \"\"\",\n        )\n\n    def test_set_attr_non_refcounted(self) -> None:\n        self.assert_emit(\n            SetAttr(self.r, \"x\", self.b, 1),\n            \"\"\"((mod___AObject *)cpy_r_r)->_x = cpy_r_b;\n               cpy_r_r0 = 1;\n            \"\"\",\n        )\n\n    def test_set_attr_no_error(self) -> None:\n        op = SetAttr(self.r, \"y\", self.m, 1)\n        op.error_kind = ERR_NEVER\n        self.assert_emit(\n            op,\n            \"\"\"if (((mod___AObject *)cpy_r_r)->_y != CPY_INT_TAG) {\n                   CPyTagged_DECREF(((mod___AObject *)cpy_r_r)->_y);\n               }\n               ((mod___AObject *)cpy_r_r)->_y = cpy_r_m;\n            \"\"\",\n        )\n\n    def test_set_attr_non_refcounted_no_error(self) -> None:\n        op = SetAttr(self.r, \"x\", self.b, 1)\n        op.error_kind = ERR_NEVER\n        self.assert_emit(\n            op,\n            \"\"\"((mod___AObject *)cpy_r_r)->_x = cpy_r_b;\n            \"\"\",\n        )\n\n    def test_set_attr_with_bitmap(self) -> None:\n        # For some rtypes the error value overlaps a valid value, so we need\n        # to use a separate bitmap to track defined attributes.\n        self.assert_emit(\n            SetAttr(self.r, \"i1\", self.i64, 1),\n            \"\"\"if (unlikely(cpy_r_i64 == -113)) {\n                   ((mod___AObject *)cpy_r_r)->bitmap |= 1;\n               }\n               ((mod___AObject *)cpy_r_r)->_i1 = cpy_r_i64;\n               cpy_r_r0 = 1;\n            \"\"\",\n        )\n        self.assert_emit(\n            SetAttr(self.r, \"i2\", self.i32, 1),\n            \"\"\"if (unlikely(cpy_r_i32 == -113)) {\n                   ((mod___AObject *)cpy_r_r)->bitmap |= 2;\n               }\n               ((mod___AObject *)cpy_r_r)->_i2 = cpy_r_i32;\n               cpy_r_r0 = 1;\n            \"\"\",\n        )\n\n    def test_set_attr_init_with_bitmap(self) -> None:\n        op = SetAttr(self.r, \"i1\", self.i64, 1)\n        op.is_init = True\n        self.assert_emit(\n            op,\n            \"\"\"if (unlikely(cpy_r_i64 == -113)) {\n                   ((mod___AObject *)cpy_r_r)->bitmap |= 1;\n               }\n               ((mod___AObject *)cpy_r_r)->_i1 = cpy_r_i64;\n               cpy_r_r0 = 1;\n            \"\"\",\n        )\n\n    def test_dict_get_item(self) -> None:\n        self.assert_emit(\n            CallC(\n                str(dict_get_item_op.c_function_name),\n                [self.d, self.o2],\n                dict_get_item_op.return_type,\n                dict_get_item_op.steals,\n                dict_get_item_op.is_borrowed,\n                dict_get_item_op.error_kind,\n                1,\n            ),\n            \"\"\"cpy_r_r0 = CPyDict_GetItem(cpy_r_d, cpy_r_o2);\"\"\",\n        )\n\n    def test_dict_set_item(self) -> None:\n        self.assert_emit(\n            CallC(\n                str(dict_set_item_op.c_function_name),\n                [self.d, self.o, self.o2],\n                dict_set_item_op.return_type,\n                dict_set_item_op.steals,\n                dict_set_item_op.is_borrowed,\n                dict_set_item_op.error_kind,\n                1,\n            ),\n            \"\"\"cpy_r_r0 = CPyDict_SetItem(cpy_r_d, cpy_r_o, cpy_r_o2);\"\"\",\n        )\n\n    def test_dict_update(self) -> None:\n        self.assert_emit(\n            CallC(\n                str(dict_update_op.c_function_name),\n                [self.d, self.o],\n                dict_update_op.return_type,\n                dict_update_op.steals,\n                dict_update_op.is_borrowed,\n                dict_update_op.error_kind,\n                1,\n            ),\n            \"\"\"cpy_r_r0 = CPyDict_Update(cpy_r_d, cpy_r_o);\"\"\",\n        )\n\n    def test_new_dict(self) -> None:\n        self.assert_emit(\n            CallC(\n                dict_new_op.c_function_name,\n                [],\n                dict_new_op.return_type,\n                dict_new_op.steals,\n                dict_new_op.is_borrowed,\n                dict_new_op.error_kind,\n                1,\n            ),\n            \"\"\"cpy_r_r0 = PyDict_New();\"\"\",\n        )\n\n    def test_dict_contains(self) -> None:\n        self.assert_emit_binary_op(\n            \"in\", self.b, self.o, self.d, \"\"\"cpy_r_r0 = PyDict_Contains(cpy_r_d, cpy_r_o);\"\"\"\n        )\n\n    def test_int_op(self) -> None:\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.ADD, 1),\n            \"\"\"cpy_r_r0 = cpy_r_s1 + cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.SUB, 1),\n            \"\"\"cpy_r_r0 = cpy_r_s1 - cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.MUL, 1),\n            \"\"\"cpy_r_r0 = cpy_r_s1 * cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.DIV, 1),\n            \"\"\"cpy_r_r0 = cpy_r_s1 / cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.MOD, 1),\n            \"\"\"cpy_r_r0 = cpy_r_s1 % cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.AND, 1),\n            \"\"\"cpy_r_r0 = cpy_r_s1 & cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.OR, 1),\n            \"\"\"cpy_r_r0 = cpy_r_s1 | cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.XOR, 1),\n            \"\"\"cpy_r_r0 = cpy_r_s1 ^ cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.LEFT_SHIFT, 1),\n            \"\"\"cpy_r_r0 = cpy_r_s1 << cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.RIGHT_SHIFT, 1),\n            \"\"\"cpy_r_r0 = (Py_ssize_t)cpy_r_s1 >> (Py_ssize_t)cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            IntOp(short_int_rprimitive, self.i64, self.i64_1, IntOp.RIGHT_SHIFT, 1),\n            \"\"\"cpy_r_r0 = cpy_r_i64 >> cpy_r_i64_1;\"\"\",\n        )\n\n    def test_comparison_op(self) -> None:\n        # signed\n        self.assert_emit(\n            ComparisonOp(self.s1, self.s2, ComparisonOp.SLT, 1),\n            \"\"\"cpy_r_r0 = (Py_ssize_t)cpy_r_s1 < (Py_ssize_t)cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            ComparisonOp(self.i32, self.i32_1, ComparisonOp.SLT, 1),\n            \"\"\"cpy_r_r0 = cpy_r_i32 < cpy_r_i32_1;\"\"\",\n        )\n        self.assert_emit(\n            ComparisonOp(self.i64, self.i64_1, ComparisonOp.SLT, 1),\n            \"\"\"cpy_r_r0 = cpy_r_i64 < cpy_r_i64_1;\"\"\",\n        )\n        # unsigned\n        self.assert_emit(\n            ComparisonOp(self.s1, self.s2, ComparisonOp.ULT, 1),\n            \"\"\"cpy_r_r0 = cpy_r_s1 < cpy_r_s2;\"\"\",\n        )\n        self.assert_emit(\n            ComparisonOp(self.i32, self.i32_1, ComparisonOp.ULT, 1),\n            \"\"\"cpy_r_r0 = (uint32_t)cpy_r_i32 < (uint32_t)cpy_r_i32_1;\"\"\",\n        )\n        self.assert_emit(\n            ComparisonOp(self.i64, self.i64_1, ComparisonOp.ULT, 1),\n            \"\"\"cpy_r_r0 = (uint64_t)cpy_r_i64 < (uint64_t)cpy_r_i64_1;\"\"\",\n        )\n\n        # object type\n        self.assert_emit(\n            ComparisonOp(self.o, self.o2, ComparisonOp.EQ, 1),\n            \"\"\"cpy_r_r0 = cpy_r_o == cpy_r_o2;\"\"\",\n        )\n        self.assert_emit(\n            ComparisonOp(self.o, self.o2, ComparisonOp.NEQ, 1),\n            \"\"\"cpy_r_r0 = cpy_r_o != cpy_r_o2;\"\"\",\n        )\n\n    def test_load_mem(self) -> None:\n        self.assert_emit(LoadMem(bool_rprimitive, self.ptr), \"\"\"cpy_r_r0 = *(char *)cpy_r_ptr;\"\"\")\n\n    def test_set_mem(self) -> None:\n        self.assert_emit(\n            SetMem(bool_rprimitive, self.ptr, self.b), \"\"\"*(char *)cpy_r_ptr = cpy_r_b;\"\"\"\n        )\n\n    def test_get_element_ptr(self) -> None:\n        r = RStruct(\n            \"Foo\", [\"b\", \"i32\", \"i64\"], [bool_rprimitive, int32_rprimitive, int64_rprimitive]\n        )\n        self.assert_emit(\n            GetElementPtr(self.o, r, \"b\"), \"\"\"cpy_r_r0 = (CPyPtr)&((Foo *)cpy_r_o)->b;\"\"\"\n        )\n        self.assert_emit(\n            GetElementPtr(self.o, r, \"i32\"), \"\"\"cpy_r_r0 = (CPyPtr)&((Foo *)cpy_r_o)->i32;\"\"\"\n        )\n        self.assert_emit(\n            GetElementPtr(self.o, r, \"i64\"), \"\"\"cpy_r_r0 = (CPyPtr)&((Foo *)cpy_r_o)->i64;\"\"\"\n        )\n\n    def test_set_element(self) -> None:\n        # Use compact syntax when setting the initial element of an undefined value\n        self.assert_emit(\n            SetElement(Undef(self.struct_type), \"b\", self.b), \"\"\"cpy_r_r0.b = cpy_r_b;\"\"\"\n        )\n        # We propagate the unchanged values in subsequent assignments\n        self.assert_emit(\n            SetElement(self.st, \"x\", self.i32),\n            \"\"\"cpy_r_r0 = (Foo) { cpy_r_st.b, cpy_r_i32, cpy_r_st.y };\"\"\",\n        )\n\n    def test_load_address(self) -> None:\n        self.assert_emit(\n            LoadAddress(object_rprimitive, \"PyDict_Type\"),\n            \"\"\"cpy_r_r0 = (PyObject *)&PyDict_Type;\"\"\",\n        )\n\n    def test_assign_multi(self) -> None:\n        t = RArray(object_rprimitive, 2)\n        a = Register(t, \"a\")\n        self.registers.append(a)\n        self.assert_emit(\n            AssignMulti(a, [self.o, self.o2]), \"\"\"PyObject *cpy_r_a[2] = {cpy_r_o, cpy_r_o2};\"\"\"\n        )\n\n    def test_long_unsigned(self) -> None:\n        a = Register(int64_rprimitive, \"a\")\n        self.assert_emit(\n            Assign(a, Integer(1 << 31, int64_rprimitive)), \"\"\"cpy_r_a = 2147483648LL;\"\"\"\n        )\n        self.assert_emit(\n            Assign(a, Integer((1 << 31) - 1, int64_rprimitive)), \"\"\"cpy_r_a = 2147483647;\"\"\"\n        )\n\n    def test_long_signed(self) -> None:\n        a = Register(int64_rprimitive, \"a\")\n        self.assert_emit(\n            Assign(a, Integer(-(1 << 31) + 1, int64_rprimitive)), \"\"\"cpy_r_a = -2147483647;\"\"\"\n        )\n        self.assert_emit(\n            Assign(a, Integer(-(1 << 31), int64_rprimitive)), \"\"\"cpy_r_a = -2147483648LL;\"\"\"\n        )\n\n    def test_cast_and_branch_merge(self) -> None:\n        op = Cast(self.r, dict_rprimitive, 1)\n        next_block = BasicBlock(9)\n        branch = Branch(op, BasicBlock(8), next_block, Branch.IS_ERROR)\n        branch.traceback_entry = (\"foobar\", 123)\n        self.assert_emit(\n            op,\n            \"\"\"\\\nif (likely(PyDict_Check(cpy_r_r)))\n    cpy_r_r0 = cpy_r_r;\nelse {\n    CPy_TypeErrorTraceback(\"prog.py\", \"foobar\", 123, CPyStatic_prog___globals, \"dict\", cpy_r_r);\n    goto CPyL8;\n}\n\"\"\",\n            next_block=next_block,\n            next_branch=branch,\n            skip_next=True,\n        )\n\n    def test_cast_and_branch_no_merge_1(self) -> None:\n        op = Cast(self.r, dict_rprimitive, 1)\n        branch = Branch(op, BasicBlock(8), BasicBlock(9), Branch.IS_ERROR)\n        branch.traceback_entry = (\"foobar\", 123)\n        self.assert_emit(\n            op,\n            \"\"\"\\\n            if (likely(PyDict_Check(cpy_r_r)))\n                cpy_r_r0 = cpy_r_r;\n            else {\n                CPy_TypeError(\"dict\", cpy_r_r);\n                cpy_r_r0 = NULL;\n            }\n            \"\"\",\n            next_block=BasicBlock(10),\n            next_branch=branch,\n            skip_next=False,\n        )\n\n    def test_cast_and_branch_no_merge_2(self) -> None:\n        op = Cast(self.r, dict_rprimitive, 1)\n        next_block = BasicBlock(9)\n        branch = Branch(op, BasicBlock(8), next_block, Branch.IS_ERROR)\n        branch.negated = True\n        branch.traceback_entry = (\"foobar\", 123)\n        self.assert_emit(\n            op,\n            \"\"\"\\\n            if (likely(PyDict_Check(cpy_r_r)))\n                cpy_r_r0 = cpy_r_r;\n            else {\n                CPy_TypeError(\"dict\", cpy_r_r);\n                cpy_r_r0 = NULL;\n            }\n            \"\"\",\n            next_block=next_block,\n            next_branch=branch,\n        )\n\n    def test_cast_and_branch_no_merge_3(self) -> None:\n        op = Cast(self.r, dict_rprimitive, 1)\n        next_block = BasicBlock(9)\n        branch = Branch(op, BasicBlock(8), next_block, Branch.BOOL)\n        branch.traceback_entry = (\"foobar\", 123)\n        self.assert_emit(\n            op,\n            \"\"\"\\\n            if (likely(PyDict_Check(cpy_r_r)))\n                cpy_r_r0 = cpy_r_r;\n            else {\n                CPy_TypeError(\"dict\", cpy_r_r);\n                cpy_r_r0 = NULL;\n            }\n            \"\"\",\n            next_block=next_block,\n            next_branch=branch,\n        )\n\n    def test_cast_and_branch_no_merge_4(self) -> None:\n        op = Cast(self.r, dict_rprimitive, 1)\n        next_block = BasicBlock(9)\n        branch = Branch(op, BasicBlock(8), next_block, Branch.IS_ERROR)\n        self.assert_emit(\n            op,\n            \"\"\"\\\n            if (likely(PyDict_Check(cpy_r_r)))\n                cpy_r_r0 = cpy_r_r;\n            else {\n                CPy_TypeError(\"dict\", cpy_r_r);\n                cpy_r_r0 = NULL;\n            }\n            \"\"\",\n            next_block=next_block,\n            next_branch=branch,\n        )\n\n    def test_extend(self) -> None:\n        a = Register(int32_rprimitive, \"a\")\n        self.assert_emit(Extend(a, int64_rprimitive, signed=True), \"\"\"cpy_r_r0 = cpy_r_a;\"\"\")\n        self.assert_emit(\n            Extend(a, int64_rprimitive, signed=False), \"\"\"cpy_r_r0 = (uint32_t)cpy_r_a;\"\"\"\n        )\n        if PLATFORM_SIZE == 4:\n            self.assert_emit(\n                Extend(self.n, int64_rprimitive, signed=True),\n                \"\"\"cpy_r_r0 = (Py_ssize_t)cpy_r_n;\"\"\",\n            )\n            self.assert_emit(\n                Extend(self.n, int64_rprimitive, signed=False), \"\"\"cpy_r_r0 = cpy_r_n;\"\"\"\n            )\n        if PLATFORM_SIZE == 8:\n            self.assert_emit(Extend(a, int_rprimitive, signed=True), \"\"\"cpy_r_r0 = cpy_r_a;\"\"\")\n            self.assert_emit(\n                Extend(a, int_rprimitive, signed=False), \"\"\"cpy_r_r0 = (uint32_t)cpy_r_a;\"\"\"\n            )\n\n    def test_inc_ref_none(self) -> None:\n        b = Box(self.none)\n        self.assert_emit([b, IncRef(b)], \"\" if HAVE_IMMORTAL else \"CPy_INCREF(cpy_r_r0);\")\n\n    def test_inc_ref_bool(self) -> None:\n        b = Box(self.b)\n        self.assert_emit([b, IncRef(b)], \"\" if HAVE_IMMORTAL else \"CPy_INCREF(cpy_r_r0);\")\n\n    def test_inc_ref_int_literal(self) -> None:\n        for x in -5, 0, 1, 5, 255, 256:\n            b = LoadLiteral(x, object_rprimitive)\n            self.assert_emit([b, IncRef(b)], \"\" if HAVE_IMMORTAL else \"CPy_INCREF(cpy_r_r0);\")\n        for x in -1123355, -6, 257, 123235345:\n            b = LoadLiteral(x, object_rprimitive)\n            self.assert_emit([b, IncRef(b)], \"CPy_INCREF(cpy_r_r0);\")\n\n    def test_c_string(self) -> None:\n        s = Register(cstring_rprimitive, \"s\")\n        self.assert_emit(Assign(s, CString(b\"foo\")), \"\"\"cpy_r_s = \"foo\";\"\"\")\n        self.assert_emit(Assign(s, CString(b'foo \"o')), r\"\"\"cpy_r_s = \"foo \\\"o\";\"\"\")\n        self.assert_emit(Assign(s, CString(b\"\\x00\")), r\"\"\"cpy_r_s = \"\\x00\";\"\"\")\n        self.assert_emit(Assign(s, CString(b\"\\\\\")), r\"\"\"cpy_r_s = \"\\\\\";\"\"\")\n        for i in range(256):\n            b = bytes([i])\n            if b == b\"\\n\":\n                target = \"\\\\n\"\n            elif b == b\"\\r\":\n                target = \"\\\\r\"\n            elif b == b\"\\t\":\n                target = \"\\\\t\"\n            elif b == b'\"':\n                target = '\\\\\"'\n            elif b == b\"\\\\\":\n                target = \"\\\\\\\\\"\n            elif i < 32 or i >= 127:\n                target = \"\\\\x%.2x\" % i\n            else:\n                target = b.decode(\"ascii\")\n            self.assert_emit(Assign(s, CString(b)), f'cpy_r_s = \"{target}\";')\n\n    def assert_emit(\n        self,\n        op: Op | list[Op],\n        expected: str,\n        next_block: BasicBlock | None = None,\n        *,\n        rare: bool = False,\n        next_branch: Branch | None = None,\n        skip_next: bool = False,\n    ) -> None:\n        block = BasicBlock(0)\n        if isinstance(op, Op):\n            block.ops.append(op)\n        else:\n            block.ops.extend(op)\n            op = op[-1]\n        value_names = generate_names_for_ir(self.registers, [block])\n        emitter = Emitter(self.context, value_names)\n        declarations = Emitter(self.context, value_names)\n        emitter.fragments = []\n        declarations.fragments = []\n\n        visitor = FunctionEmitterVisitor(emitter, declarations, \"prog.py\", \"prog\")\n        visitor.next_block = next_block\n        visitor.rare = rare\n        if next_branch:\n            visitor.ops = [op, next_branch]\n        else:\n            visitor.ops = [op]\n        visitor.op_index = 0\n\n        op.accept(visitor)\n        frags = declarations.fragments + emitter.fragments\n        actual_lines = [line.strip(\" \") for line in frags]\n        assert all(line.endswith(\"\\n\") for line in actual_lines)\n        actual_lines = [line.rstrip(\"\\n\") for line in actual_lines]\n        if not expected.strip():\n            expected_lines = []\n        else:\n            expected_lines = expected.rstrip().split(\"\\n\")\n        expected_lines = [line.strip(\" \") for line in expected_lines]\n        assert_string_arrays_equal(\n            expected_lines, actual_lines, msg=\"Generated code unexpected\", traceback=True\n        )\n        if skip_next:\n            assert visitor.op_index == 1\n        else:\n            assert visitor.op_index == 0\n\n    def assert_emit_binary_op(\n        self, op: str, dest: Value, left: Value, right: Value, expected: str\n    ) -> None:\n        if op in binary_ops:\n            ops = binary_ops[op]\n            for desc in ops:\n                if is_subtype(left.type, desc.arg_types[0]) and is_subtype(\n                    right.type, desc.arg_types[1]\n                ):\n                    args = [left, right]\n                    if desc.ordering is not None:\n                        args = [args[i] for i in desc.ordering]\n                    # This only supports primitives that map to C calls\n                    assert desc.c_function_name is not None\n                    self.assert_emit(\n                        CallC(\n                            desc.c_function_name,\n                            args,\n                            desc.return_type,\n                            desc.steals,\n                            desc.is_borrowed,\n                            desc.error_kind,\n                            55,\n                        ),\n                        expected,\n                    )\n                    return\n        else:\n            assert False, \"Could not find matching op\"\n\n\nclass TestGenerateFunction(unittest.TestCase):\n    def setUp(self) -> None:\n        self.arg = RuntimeArg(\"arg\", int_rprimitive)\n        self.reg = Register(int_rprimitive, \"arg\")\n        self.block = BasicBlock(0)\n\n    def test_simple(self) -> None:\n        self.block.ops.append(Return(self.reg))\n        fn = FuncIR(\n            FuncDecl(\"myfunc\", None, \"mod\", FuncSignature([self.arg], int_rprimitive)),\n            [self.reg],\n            [self.block],\n        )\n        value_names = generate_names_for_ir(fn.arg_regs, fn.blocks)\n        emitter = Emitter(EmitterContext(NameGenerator([[\"mod\"]]), True), value_names)\n        generate_native_function(fn, emitter, \"prog.py\", \"prog\")\n        result = emitter.fragments\n        assert_string_arrays_equal(\n            [\"CPyTagged CPyDef_myfunc(CPyTagged cpy_r_arg) {\\n\", \"    return cpy_r_arg;\\n\", \"}\\n\"],\n            result,\n            msg=\"Generated code invalid\",\n        )\n\n    def test_register(self) -> None:\n        reg = Register(int_rprimitive)\n        op = Assign(reg, Integer(5))\n        self.block.ops.append(op)\n        self.block.ops.append(Unreachable())\n        fn = FuncIR(\n            FuncDecl(\"myfunc\", None, \"mod\", FuncSignature([self.arg], list_rprimitive)),\n            [self.reg],\n            [self.block],\n        )\n        value_names = generate_names_for_ir(fn.arg_regs, fn.blocks)\n        emitter = Emitter(EmitterContext(NameGenerator([[\"mod\"]]), True), value_names)\n        generate_native_function(fn, emitter, \"prog.py\", \"prog\")\n        result = emitter.fragments\n        assert_string_arrays_equal(\n            [\n                \"PyObject *CPyDef_myfunc(CPyTagged cpy_r_arg) {\\n\",\n                \"    CPyTagged cpy_r_r0;\\n\",\n                \"    cpy_r_r0 = 10;\\n\",\n                \"    CPy_Unreachable();\\n\",\n                \"}\\n\",\n            ],\n            result,\n            msg=\"Generated code invalid\",\n        )\n"
  },
  {
    "path": "mypyc/test/test_emitwrapper.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypy.test.helpers import assert_string_arrays_equal\nfrom mypyc.codegen.emit import Emitter, EmitterContext, ReturnHandler\nfrom mypyc.codegen.emitwrapper import generate_arg_check\nfrom mypyc.ir.rtypes import int_rprimitive, list_rprimitive\nfrom mypyc.namegen import NameGenerator\n\n\nclass TestArgCheck(unittest.TestCase):\n    def setUp(self) -> None:\n        self.context = EmitterContext(NameGenerator([[\"mod\"]]), True)\n\n    def test_check_list(self) -> None:\n        emitter = Emitter(self.context)\n        generate_arg_check(\"x\", list_rprimitive, emitter, ReturnHandler(\"NULL\"))\n        lines = emitter.fragments\n        self.assert_lines(\n            [\n                \"PyObject *arg_x;\",\n                \"if (likely(PyList_Check(obj_x)))\",\n                \"    arg_x = obj_x;\",\n                \"else {\",\n                '    CPy_TypeError(\"list\", obj_x);',\n                \"    return NULL;\",\n                \"}\",\n            ],\n            lines,\n        )\n\n    def test_check_int(self) -> None:\n        emitter = Emitter(self.context)\n        generate_arg_check(\"x\", int_rprimitive, emitter, ReturnHandler(\"NULL\"))\n        generate_arg_check(\"y\", int_rprimitive, emitter, ReturnHandler(\"NULL\"), optional=True)\n        lines = emitter.fragments\n        self.assert_lines(\n            [\n                \"CPyTagged arg_x;\",\n                \"if (likely(PyLong_Check(obj_x)))\",\n                \"    arg_x = CPyTagged_BorrowFromObject(obj_x);\",\n                \"else {\",\n                '    CPy_TypeError(\"int\", obj_x); return NULL;',\n                \"}\",\n                \"CPyTagged arg_y;\",\n                \"if (obj_y == NULL) {\",\n                \"    arg_y = CPY_INT_TAG;\",\n                \"} else if (likely(PyLong_Check(obj_y)))\",\n                \"    arg_y = CPyTagged_BorrowFromObject(obj_y);\",\n                \"else {\",\n                '    CPy_TypeError(\"int\", obj_y); return NULL;',\n                \"}\",\n            ],\n            lines,\n        )\n\n    def assert_lines(self, expected: list[str], actual: list[str]) -> None:\n        actual = [line.rstrip(\"\\n\") for line in actual]\n        assert_string_arrays_equal(expected, actual, \"Invalid output\")\n"
  },
  {
    "path": "mypyc/test/test_exceptions.py",
    "content": "\"\"\"Test runner for exception handling transform test cases.\n\nThe transform inserts exception handling branch operations to IR.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\n\nfrom mypy.errors import CompileError\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypyc.analysis.blockfreq import frequently_executed_blocks\nfrom mypyc.common import TOP_LEVEL_NAME\nfrom mypyc.ir.pprint import format_func\nfrom mypyc.test.testutil import (\n    ICODE_GEN_BUILTINS,\n    MypycDataSuite,\n    assert_test_output,\n    build_ir_for_single_file,\n    remove_comment_lines,\n    use_custom_builtins,\n)\nfrom mypyc.transform.exceptions import insert_exception_handling\nfrom mypyc.transform.refcount import insert_ref_count_opcodes\nfrom mypyc.transform.uninit import insert_uninit_checks\n\nfiles = [\"exceptions.test\", \"exceptions-freq.test\"]\n\n\nclass TestExceptionTransform(MypycDataSuite):\n    files = files\n    base_path = test_temp_dir\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        \"\"\"Perform a runtime checking transformation test case.\"\"\"\n        with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):\n            expected_output = remove_comment_lines(testcase.output)\n            try:\n                ir = build_ir_for_single_file(testcase.input)\n            except CompileError as e:\n                actual = e.messages\n            else:\n                actual = []\n                for fn in ir:\n                    if fn.name == TOP_LEVEL_NAME and not testcase.name.endswith(\"_toplevel\"):\n                        continue\n                    insert_uninit_checks(fn, True)\n                    insert_exception_handling(fn, True)\n                    insert_ref_count_opcodes(fn)\n                    actual.extend(format_func(fn))\n                    if testcase.name.endswith(\"_freq\"):\n                        common = frequently_executed_blocks(fn.blocks[0])\n                        actual.append(\"hot blocks: %s\" % sorted(b.label for b in common))\n\n            assert_test_output(testcase, actual, \"Invalid source code output\", expected_output)\n"
  },
  {
    "path": "mypyc/test/test_external.py",
    "content": "\"\"\"Test cases that run tests as subprocesses.\"\"\"\n\nfrom __future__ import annotations\n\nimport os\nimport subprocess\nimport sys\nimport tempfile\nimport unittest\nfrom distutils import ccompiler, sysconfig\nfrom typing import Any\n\nfrom mypyc.build import get_cflags, include_dir\n\nbase_dir = os.path.join(os.path.dirname(__file__), \"..\", \"..\")\nEXCLUDED_LIB_RT_COMPILE_FILES = [\"static_data.c\"]\n\n\nclass TestExternal(unittest.TestCase):\n    def test_lib_rt_c_files_compile_individually(self) -> None:\n        \"\"\"Compile each top-level lib-rt C file as its own translation unit.\"\"\"\n        lib_rt_dir = include_dir()\n        source_names = sorted(\n            name\n            for name in os.listdir(lib_rt_dir)\n            if name.endswith(\".c\")\n            and os.path.isfile(os.path.join(lib_rt_dir, name))\n            and name not in EXCLUDED_LIB_RT_COMPILE_FILES\n        )\n        compiler: Any = ccompiler.new_compiler()\n        sysconfig.customize_compiler(compiler)\n\n        include_dirs = [lib_rt_dir]\n        for plat_specific in (False, True):\n            path = sysconfig.get_python_inc(plat_specific=plat_specific)\n            if path and path not in include_dirs:\n                include_dirs.append(path)\n\n        with tempfile.TemporaryDirectory() as tmpdir:\n            for experimental_features in (False, True):\n                cflags = get_cflags(\n                    compiler_type=compiler.compiler_type,\n                    opt_level=\"0\",\n                    experimental_features=experimental_features,\n                )\n                output_dir = os.path.join(\n                    tmpdir, \"experimental\" if experimental_features else \"default\"\n                )\n\n                for source_name in source_names:\n                    source_path = os.path.join(lib_rt_dir, source_name)\n                    with self.subTest(source=source_name, experimental=experimental_features):\n                        try:\n                            compiler.compile(\n                                [source_path],\n                                output_dir=output_dir,\n                                include_dirs=include_dirs,\n                                extra_postargs=cflags,\n                            )\n                        except Exception as err:\n                            raise AssertionError(\n                                f\"failed to compile {source_name} \"\n                                f\"(experimental={experimental_features})\"\n                            ) from err\n\n    # TODO: Get this to work on Windows.\n    # (Or don't. It is probably not a good use of time.)\n    @unittest.skipIf(sys.platform.startswith(\"win\"), \"rt tests don't work on windows\")\n    def test_c_unit_test(self) -> None:\n        \"\"\"Run C unit tests in a subprocess.\"\"\"\n        cppflags: list[str] = []\n        env = os.environ.copy()\n        if sys.platform == \"darwin\":\n            cppflags += [\"-O0\", \"-mmacosx-version-min=10.10\", \"-stdlib=libc++\"]\n        elif sys.platform == \"linux\":\n            cppflags += [\"-O0\"]\n        env[\"CPPFLAGS\"] = \" \".join(cppflags)\n        # Build Python wrapper for C unit tests.\n\n        with tempfile.TemporaryDirectory() as tmpdir:\n            status = subprocess.check_call(\n                [\n                    sys.executable,\n                    \"setup.py\",\n                    \"build_ext\",\n                    f\"--build-lib={tmpdir}\",\n                    f\"--build-temp={tmpdir}\",\n                    \"--run-capi-tests\",\n                ],\n                env=env,\n                cwd=os.path.join(base_dir, \"mypyc\", \"lib-rt\"),\n            )\n            # Run C unit tests.\n            env = os.environ.copy()\n            if \"GTEST_COLOR\" not in os.environ:\n                env[\"GTEST_COLOR\"] = \"yes\"  # Use fancy colors\n            status = subprocess.call(\n                [sys.executable, \"-c\", \"import sys, test_capi; sys.exit(test_capi.run_tests())\"],\n                env=env,\n                cwd=tmpdir,\n            )\n            if status != 0:\n                raise AssertionError(\"make test: C unit test failure\")\n"
  },
  {
    "path": "mypyc/test/test_irbuild.py",
    "content": "\"\"\"Test cases for IR generation.\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\nimport sys\n\nfrom mypy.errors import CompileError\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypyc.common import IS_FREE_THREADED, TOP_LEVEL_NAME\nfrom mypyc.ir.pprint import format_func\nfrom mypyc.test.testutil import (\n    ICODE_GEN_BUILTINS,\n    MypycDataSuite,\n    assert_test_output,\n    build_ir_for_single_file,\n    infer_ir_build_options_from_test_name,\n    remove_comment_lines,\n    replace_word_size,\n    use_custom_builtins,\n)\n\nfiles = [\n    \"irbuild-basic.test\",\n    \"irbuild-int.test\",\n    \"irbuild-bool.test\",\n    \"irbuild-lists.test\",\n    \"irbuild-tuple.test\",\n    \"irbuild-dict.test\",\n    \"irbuild-set.test\",\n    \"irbuild-str.test\",\n    \"irbuild-bytes.test\",\n    \"irbuild-float.test\",\n    \"irbuild-frozenset.test\",\n    \"irbuild-statements.test\",\n    \"irbuild-nested.test\",\n    \"irbuild-classes.test\",\n    \"irbuild-optional.test\",\n    \"irbuild-any.test\",\n    \"irbuild-generics.test\",\n    \"irbuild-try.test\",\n    \"irbuild-strip-asserts.test\",\n    \"irbuild-i64.test\",\n    \"irbuild-i32.test\",\n    \"irbuild-i16.test\",\n    \"irbuild-u8.test\",\n    \"irbuild-vec-i64.test\",\n    \"irbuild-vec-misc.test\",\n    \"irbuild-vec-t.test\",\n    \"irbuild-vec-nested.test\",\n    \"irbuild-vectorcall.test\",\n    \"irbuild-unreachable.test\",\n    \"irbuild-isinstance.test\",\n    \"irbuild-dunders.test\",\n    \"irbuild-singledispatch.test\",\n    \"irbuild-constant-fold.test\",\n    \"irbuild-glue-methods.test\",\n    \"irbuild-math.test\",\n    \"irbuild-weakref.test\",\n    \"irbuild-librt-strings.test\",\n    \"irbuild-base64.test\",\n    \"irbuild-time.test\",\n    \"irbuild-match.test\",\n]\n\nif sys.version_info >= (3, 14):\n    files.append(\"irbuild-python314.test\")\n\n\nclass TestGenOps(MypycDataSuite):\n    files = files\n    base_path = test_temp_dir\n    optional_out = True\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        \"\"\"Perform a runtime checking transformation test case.\"\"\"\n        options = infer_ir_build_options_from_test_name(testcase.name)\n        if options is None:\n            # Skipped test case\n            return\n        if \"_withgil\" in testcase.name and IS_FREE_THREADED:\n            # Test case should only run on a non-free-threaded build.\n            return\n        with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):\n            expected_output = remove_comment_lines(testcase.output)\n            expected_output = replace_word_size(expected_output)\n            name = testcase.name\n            try:\n                ir = build_ir_for_single_file(testcase.input, options)\n            except CompileError as e:\n                actual = e.messages\n            else:\n                actual = []\n                for fn in ir:\n                    if fn.name == TOP_LEVEL_NAME and not name.endswith(\"_toplevel\"):\n                        continue\n                    actual.extend(format_func(fn))\n\n            assert_test_output(testcase, actual, \"Invalid source code output\", expected_output)\n"
  },
  {
    "path": "mypyc/test/test_ircheck.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypyc.analysis.ircheck import FnError, can_coerce_to, check_func_ir\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature\nfrom mypyc.ir.ops import (\n    Assign,\n    BasicBlock,\n    Goto,\n    Integer,\n    LoadAddress,\n    LoadLiteral,\n    Op,\n    Register,\n    Return,\n)\nfrom mypyc.ir.pprint import format_func\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RType,\n    RUnion,\n    bytes_rprimitive,\n    int32_rprimitive,\n    int64_rprimitive,\n    none_rprimitive,\n    object_rprimitive,\n    pointer_rprimitive,\n    str_rprimitive,\n)\n\n\ndef assert_has_error(fn: FuncIR, error: FnError) -> None:\n    errors = check_func_ir(fn)\n    assert errors == [error]\n\n\ndef assert_no_errors(fn: FuncIR) -> None:\n    assert not check_func_ir(fn)\n\n\nNONE_VALUE = Integer(0, rtype=none_rprimitive)\n\n\nclass TestIrcheck(unittest.TestCase):\n    def setUp(self) -> None:\n        self.label = 0\n\n    def basic_block(self, ops: list[Op]) -> BasicBlock:\n        self.label += 1\n        block = BasicBlock(self.label)\n        block.ops = ops\n        return block\n\n    def func_decl(self, name: str, ret_type: RType | None = None) -> FuncDecl:\n        if ret_type is None:\n            ret_type = none_rprimitive\n        return FuncDecl(\n            name=name,\n            class_name=None,\n            module_name=\"module\",\n            sig=FuncSignature(args=[], ret_type=ret_type),\n        )\n\n    def test_valid_fn(self) -> None:\n        assert_no_errors(\n            FuncIR(\n                decl=self.func_decl(name=\"func_1\"),\n                arg_regs=[],\n                blocks=[self.basic_block(ops=[Return(value=NONE_VALUE)])],\n            )\n        )\n\n    def test_block_not_terminated_empty_block(self) -> None:\n        block = self.basic_block([])\n        fn = FuncIR(decl=self.func_decl(name=\"func_1\"), arg_regs=[], blocks=[block])\n        assert_has_error(fn, FnError(source=block, desc=\"Block not terminated\"))\n\n    def test_valid_goto(self) -> None:\n        block_1 = self.basic_block([Return(value=NONE_VALUE)])\n        block_2 = self.basic_block([Goto(label=block_1)])\n        fn = FuncIR(decl=self.func_decl(name=\"func_1\"), arg_regs=[], blocks=[block_1, block_2])\n        assert_no_errors(fn)\n\n    def test_invalid_goto(self) -> None:\n        block_1 = self.basic_block([Return(value=NONE_VALUE)])\n        goto = Goto(label=block_1)\n        block_2 = self.basic_block([goto])\n        fn = FuncIR(\n            decl=self.func_decl(name=\"func_1\"),\n            arg_regs=[],\n            # block_1 omitted\n            blocks=[block_2],\n        )\n        assert_has_error(fn, FnError(source=goto, desc=\"Invalid control operation target: 1\"))\n\n    def test_invalid_register_source(self) -> None:\n        ret = Return(value=Register(type=none_rprimitive, name=\"r1\"))\n        block = self.basic_block([ret])\n        fn = FuncIR(decl=self.func_decl(name=\"func_1\"), arg_regs=[], blocks=[block])\n        assert_has_error(fn, FnError(source=ret, desc=\"Invalid op reference to register 'r1'\"))\n\n    def test_invalid_op_source(self) -> None:\n        ret = Return(value=LoadLiteral(value=\"foo\", rtype=str_rprimitive))\n        block = self.basic_block([ret])\n        fn = FuncIR(decl=self.func_decl(name=\"func_1\"), arg_regs=[], blocks=[block])\n        assert_has_error(\n            fn, FnError(source=ret, desc=\"Invalid op reference to op of type LoadLiteral\")\n        )\n\n    def test_invalid_return_type(self) -> None:\n        ret = Return(value=Integer(value=5, rtype=int32_rprimitive))\n        fn = FuncIR(\n            decl=self.func_decl(name=\"func_1\", ret_type=int64_rprimitive),\n            arg_regs=[],\n            blocks=[self.basic_block([ret])],\n        )\n        assert_has_error(\n            fn, FnError(source=ret, desc=\"Cannot coerce source type i32 to dest type i64\")\n        )\n\n    def test_invalid_assign(self) -> None:\n        arg_reg = Register(type=int64_rprimitive, name=\"r1\")\n        assign = Assign(dest=arg_reg, src=Integer(value=5, rtype=int32_rprimitive))\n        ret = Return(value=NONE_VALUE)\n        fn = FuncIR(\n            decl=self.func_decl(name=\"func_1\"),\n            arg_regs=[arg_reg],\n            blocks=[self.basic_block([assign, ret])],\n        )\n        assert_has_error(\n            fn, FnError(source=assign, desc=\"Cannot coerce source type i32 to dest type i64\")\n        )\n\n    def test_can_coerce_to(self) -> None:\n        cls = ClassIR(name=\"Cls\", module_name=\"cls\")\n        valid_cases = [\n            (int64_rprimitive, int64_rprimitive),\n            (str_rprimitive, str_rprimitive),\n            (str_rprimitive, object_rprimitive),\n            (object_rprimitive, str_rprimitive),\n            (RUnion([bytes_rprimitive, str_rprimitive]), str_rprimitive),\n            (str_rprimitive, RUnion([bytes_rprimitive, str_rprimitive])),\n            (RInstance(cls), object_rprimitive),\n        ]\n\n        invalid_cases = [\n            (int64_rprimitive, int32_rprimitive),\n            (RInstance(cls), str_rprimitive),\n            (str_rprimitive, bytes_rprimitive),\n        ]\n\n        for src, dest in valid_cases:\n            assert can_coerce_to(src, dest)\n        for src, dest in invalid_cases:\n            assert not can_coerce_to(src, dest)\n\n    def test_duplicate_op(self) -> None:\n        arg_reg = Register(type=int32_rprimitive, name=\"r1\")\n        assign = Assign(dest=arg_reg, src=Integer(value=5, rtype=int32_rprimitive))\n        block = self.basic_block([assign, assign, Return(value=NONE_VALUE)])\n        fn = FuncIR(decl=self.func_decl(name=\"func_1\"), arg_regs=[], blocks=[block])\n        assert_has_error(fn, FnError(source=assign, desc=\"Func has a duplicate op\"))\n\n    def test_pprint(self) -> None:\n        block_1 = self.basic_block([Return(value=NONE_VALUE)])\n        goto = Goto(label=block_1)\n        block_2 = self.basic_block([goto])\n        fn = FuncIR(\n            decl=self.func_decl(name=\"func_1\"),\n            arg_regs=[],\n            # block_1 omitted\n            blocks=[block_2],\n        )\n        errors = [(goto, \"Invalid control operation target: 1\")]\n        formatted = format_func(fn, errors)\n        assert formatted == [\n            \"def func_1():\",\n            \"L0:\",\n            \" \\U0000274c goto L1\",\n            \"    \\U0001f446 ERROR: Invalid control operation target: 1\",\n        ]\n\n    def test_load_address_declares_register(self) -> None:\n        rx = Register(str_rprimitive, \"x\")\n        ry = Register(pointer_rprimitive, \"y\")\n        load_addr = LoadAddress(pointer_rprimitive, rx)\n        assert_no_errors(\n            FuncIR(\n                decl=self.func_decl(name=\"func_1\"),\n                arg_regs=[],\n                blocks=[\n                    self.basic_block(\n                        ops=[load_addr, Assign(ry, load_addr), Return(value=NONE_VALUE)]\n                    )\n                ],\n            )\n        )\n"
  },
  {
    "path": "mypyc/test/test_literals.py",
    "content": "\"\"\"Test code geneneration for literals.\"\"\"\n\nfrom __future__ import annotations\n\nimport unittest\n\nfrom mypyc.codegen.literals import (\n    Literals,\n    _encode_bytes_values,\n    _encode_int_values,\n    _encode_str_values,\n    format_str_literal,\n)\n\n\nclass TestLiterals(unittest.TestCase):\n    def test_format_str_literal(self) -> None:\n        assert format_str_literal(\"\") == b\"\\x00\"\n        assert format_str_literal(\"xyz\") == b\"\\x03xyz\"\n        assert format_str_literal(\"x\" * 127) == b\"\\x7f\" + b\"x\" * 127\n        assert format_str_literal(\"x\" * 128) == b\"\\x81\\x00\" + b\"x\" * 128\n        assert format_str_literal(\"x\" * 131) == b\"\\x81\\x03\" + b\"x\" * 131\n\n    def test_encode_str_values(self) -> None:\n        assert _encode_str_values({}) == [b\"\"]\n        assert _encode_str_values({\"foo\": 0}) == [b\"\\x01\\x03foo\", b\"\"]\n        assert _encode_str_values({\"foo\": 0, \"b\": 1}) == [b\"\\x02\\x03foo\\x01b\", b\"\"]\n        assert _encode_str_values({\"foo\": 0, \"x\" * 70: 1}) == [\n            b\"\\x01\\x03foo\",\n            bytes([1, 70]) + b\"x\" * 70,\n            b\"\",\n        ]\n        assert _encode_str_values({\"y\" * 100: 0}) == [bytes([1, 100]) + b\"y\" * 100, b\"\"]\n\n    def test_encode_bytes_values(self) -> None:\n        assert _encode_bytes_values({}) == [b\"\"]\n        assert _encode_bytes_values({b\"foo\": 0}) == [b\"\\x01\\x03foo\", b\"\"]\n        assert _encode_bytes_values({b\"foo\": 0, b\"b\": 1}) == [b\"\\x02\\x03foo\\x01b\", b\"\"]\n        assert _encode_bytes_values({b\"foo\": 0, b\"x\" * 70: 1}) == [\n            b\"\\x01\\x03foo\",\n            bytes([1, 70]) + b\"x\" * 70,\n            b\"\",\n        ]\n        assert _encode_bytes_values({b\"y\" * 100: 0}) == [bytes([1, 100]) + b\"y\" * 100, b\"\"]\n\n    def test_encode_int_values(self) -> None:\n        assert _encode_int_values({}) == [b\"\"]\n        assert _encode_int_values({123: 0}) == [b\"\\x01123\", b\"\"]\n        assert _encode_int_values({123: 0, 9: 1}) == [b\"\\x02123\\x009\", b\"\"]\n        assert _encode_int_values({123: 0, 45: 1, 5 * 10**70: 2}) == [\n            b\"\\x02123\\x0045\",\n            b\"\\x015\" + b\"0\" * 70,\n            b\"\",\n        ]\n        assert _encode_int_values({6 * 10**100: 0}) == [b\"\\x016\" + b\"0\" * 100, b\"\"]\n\n    def test_simple_literal_index(self) -> None:\n        lit = Literals()\n        lit.record_literal(1)\n        lit.record_literal(\"y\")\n        lit.record_literal(True)\n        lit.record_literal(None)\n        lit.record_literal(False)\n        assert lit.literal_index(None) == 0\n        assert lit.literal_index(False) == 1\n        assert lit.literal_index(True) == 2\n        assert lit.literal_index(\"y\") == 3\n        assert lit.literal_index(1) == 4\n\n    def test_tuple_literal(self) -> None:\n        lit = Literals()\n        lit.record_literal((1, \"y\", None, (b\"a\", \"b\")))\n        lit.record_literal((b\"a\", \"b\"))\n        lit.record_literal(())\n        assert lit.literal_index((b\"a\", \"b\")) == 7\n        assert lit.literal_index((1, \"y\", None, (b\"a\", \"b\"))) == 8\n        assert lit.literal_index(()) == 9\n        print(lit.encoded_tuple_values())\n        assert lit.encoded_tuple_values() == [\n            \"3\",  # Number of tuples\n            \"2\",\n            \"5\",\n            \"4\",  # First tuple (length=2)\n            \"4\",\n            \"6\",\n            \"3\",\n            \"0\",\n            \"7\",  # Second tuple (length=4)\n            \"0\",  # Third tuple (length=0)\n        ]\n"
  },
  {
    "path": "mypyc/test/test_lowering.py",
    "content": "\"\"\"Runner for lowering transform tests.\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\n\nfrom mypy.errors import CompileError\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypyc.common import TOP_LEVEL_NAME\nfrom mypyc.ir.pprint import format_func\nfrom mypyc.options import CompilerOptions\nfrom mypyc.test.testutil import (\n    ICODE_GEN_BUILTINS,\n    MypycDataSuite,\n    assert_test_output,\n    build_ir_for_single_file,\n    infer_ir_build_options_from_test_name,\n    remove_comment_lines,\n    replace_word_size,\n    use_custom_builtins,\n)\nfrom mypyc.transform.exceptions import insert_exception_handling\nfrom mypyc.transform.flag_elimination import do_flag_elimination\nfrom mypyc.transform.lower import lower_ir\nfrom mypyc.transform.refcount import insert_ref_count_opcodes\nfrom mypyc.transform.uninit import insert_uninit_checks\n\n\nclass TestLowering(MypycDataSuite):\n    files = [\"lowering-int.test\", \"lowering-list.test\"]\n    base_path = test_temp_dir\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        options = infer_ir_build_options_from_test_name(testcase.name)\n        if options is None:\n            # Skipped test case\n            return\n        with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):\n            expected_output = remove_comment_lines(testcase.output)\n            expected_output = replace_word_size(expected_output)\n            try:\n                ir = build_ir_for_single_file(testcase.input, options)\n            except CompileError as e:\n                actual = e.messages\n            else:\n                actual = []\n                for fn in ir:\n                    if fn.name == TOP_LEVEL_NAME and not testcase.name.endswith(\"_toplevel\"):\n                        continue\n                    options = CompilerOptions(strict_traceback_checks=True)\n                    # Lowering happens after exception handling and ref count opcodes have\n                    # been added. Any changes must maintain reference counting semantics.\n                    insert_uninit_checks(fn, True)\n                    insert_exception_handling(fn, True)\n                    insert_ref_count_opcodes(fn)\n                    lower_ir(fn, options)\n                    do_flag_elimination(fn, options)\n                    actual.extend(format_func(fn))\n\n            assert_test_output(testcase, actual, \"Invalid source code output\", expected_output)\n"
  },
  {
    "path": "mypyc/test/test_misc.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypyc.ir.ops import BasicBlock\nfrom mypyc.ir.pprint import format_blocks, generate_names_for_ir\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\nfrom mypyc.options import CompilerOptions\n\n\nclass TestMisc(unittest.TestCase):\n    def test_debug_op(self) -> None:\n        block = BasicBlock()\n        builder = LowLevelIRBuilder(\n            errors=None, options=CompilerOptions(strict_traceback_checks=True)\n        )\n        builder.activate_block(block)\n        builder.debug_print(\"foo\")\n\n        names = generate_names_for_ir([], [block])\n        code = format_blocks([block], names, {})\n        assert code[:-1] == [\"L0:\", \"    r0 = 'foo'\", \"    CPyDebug_PrintObject(r0)\"]\n"
  },
  {
    "path": "mypyc/test/test_namegen.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypyc.namegen import (\n    NameGenerator,\n    candidate_suffixes,\n    exported_name,\n    make_module_translation_map,\n)\n\n\nclass TestNameGen(unittest.TestCase):\n    def test_candidate_suffixes(self) -> None:\n        assert candidate_suffixes(\"foo\") == [\"\", \"foo.\"]\n        assert candidate_suffixes(\"foo.bar\") == [\"\", \"bar.\", \"foo.bar.\"]\n\n    def test_exported_name(self) -> None:\n        assert exported_name(\"foo\") == \"foo\"\n        assert exported_name(\"foo.bar\") == \"foo___bar\"\n\n    def test_make_module_translation_map(self) -> None:\n        assert make_module_translation_map([\"foo\", \"bar\"]) == {\"foo\": \"foo.\", \"bar\": \"bar.\"}\n        assert make_module_translation_map([\"foo.bar\", \"foo.baz\"]) == {\n            \"foo.bar\": \"bar.\",\n            \"foo.baz\": \"baz.\",\n        }\n        assert make_module_translation_map([\"zar\", \"foo.bar\", \"foo.baz\"]) == {\n            \"foo.bar\": \"bar.\",\n            \"foo.baz\": \"baz.\",\n            \"zar\": \"zar.\",\n        }\n        assert make_module_translation_map([\"foo.bar\", \"fu.bar\", \"foo.baz\"]) == {\n            \"foo.bar\": \"foo.bar.\",\n            \"fu.bar\": \"fu.bar.\",\n            \"foo.baz\": \"baz.\",\n        }\n        assert make_module_translation_map([\"foo\", \"foo.foo\", \"bar.foo\", \"bar.foo.bar.foo\"]) == {\n            \"foo\": \"foo.\",\n            \"foo.foo\": \"foo.foo.\",\n            \"bar.foo\": \"bar.foo.\",\n            \"bar.foo.bar.foo\": \"foo.bar.foo.\",\n        }\n\n    def test_name_generator(self) -> None:\n        g = NameGenerator([[\"foo\", \"foo.zar\"]])\n        assert g.private_name(\"foo\", \"f\") == \"foo___f\"\n        assert g.private_name(\"foo\", \"C.x.y\") == \"foo___C___x___y\"\n        assert g.private_name(\"foo\", \"C.x.y\") == \"foo___C___x___y\"\n        assert g.private_name(\"foo.zar\", \"C.x.y\") == \"zar___C___x___y\"\n        assert g.private_name(\"foo\", \"C.x_y\") == \"foo___C___x_y\"\n        assert g.private_name(\"foo\", \"C_x_y\") == \"foo___C_x_y\"\n        assert g.private_name(\"foo\", \"C_x_y\") == \"foo___C_x_y\"\n        assert g.private_name(\"foo\", \"___\") == \"foo______3_\"\n\n        g = NameGenerator([[\"foo.zar\"]])\n        assert g.private_name(\"foo.zar\", \"f\") == \"f\"\n\n    def test_name_generator_with_separate(self) -> None:\n        g = NameGenerator([[\"foo\", \"foo.zar\"]], separate=True)\n        assert g.private_name(\"foo\", \"f\") == \"foo___f\"\n        assert g.private_name(\"foo\", \"C.x.y\") == \"foo___C___x___y\"\n        assert g.private_name(\"foo.zar\", \"C.x.y\") == \"foo___zar___C___x___y\"\n        assert g.private_name(\"foo\", \"C.x_y\") == \"foo___C___x_y\"\n        assert g.private_name(\"foo\", \"___\") == \"foo______3_\"\n\n        g = NameGenerator([[\"foo.zar\"]], separate=True)\n        assert g.private_name(\"foo.zar\", \"f\") == \"foo___zar___f\"\n"
  },
  {
    "path": "mypyc/test/test_optimizations.py",
    "content": "\"\"\"Runner for IR optimization tests.\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\n\nfrom mypy.errors import CompileError\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypyc.common import TOP_LEVEL_NAME\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.pprint import format_func\nfrom mypyc.options import CompilerOptions\nfrom mypyc.test.testutil import (\n    ICODE_GEN_BUILTINS,\n    MypycDataSuite,\n    assert_test_output,\n    build_ir_for_single_file,\n    remove_comment_lines,\n    use_custom_builtins,\n)\nfrom mypyc.transform.copy_propagation import do_copy_propagation\nfrom mypyc.transform.flag_elimination import do_flag_elimination\nfrom mypyc.transform.uninit import insert_uninit_checks\n\n\nclass OptimizationSuite(MypycDataSuite):\n    \"\"\"Base class for IR optimization test suites.\n\n    To use this, add a base class and define \"files\" and \"do_optimizations\".\n    \"\"\"\n\n    base_path = test_temp_dir\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):\n            expected_output = remove_comment_lines(testcase.output)\n            try:\n                ir = build_ir_for_single_file(testcase.input)\n            except CompileError as e:\n                actual = e.messages\n            else:\n                actual = []\n                for fn in ir:\n                    if fn.name == TOP_LEVEL_NAME and not testcase.name.endswith(\"_toplevel\"):\n                        continue\n                    insert_uninit_checks(fn, True)\n                    self.do_optimizations(fn)\n                    actual.extend(format_func(fn))\n\n            assert_test_output(testcase, actual, \"Invalid source code output\", expected_output)\n\n    def do_optimizations(self, fn: FuncIR) -> None:\n        raise NotImplementedError\n\n\nclass TestCopyPropagation(OptimizationSuite):\n    files = [\"opt-copy-propagation.test\"]\n\n    def do_optimizations(self, fn: FuncIR) -> None:\n        do_copy_propagation(fn, CompilerOptions(strict_traceback_checks=True))\n\n\nclass TestFlagElimination(OptimizationSuite):\n    files = [\"opt-flag-elimination.test\"]\n\n    def do_optimizations(self, fn: FuncIR) -> None:\n        do_flag_elimination(fn, CompilerOptions(strict_traceback_checks=True))\n"
  },
  {
    "path": "mypyc/test/test_pprint.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypyc.ir.ops import Assign, BasicBlock, Integer, IntOp, Op, Register, Unreachable\nfrom mypyc.ir.pprint import generate_names_for_ir\nfrom mypyc.ir.rtypes import int_rprimitive\n\n\ndef register(name: str) -> Register:\n    return Register(int_rprimitive, \"foo\", is_arg=True)\n\n\ndef make_block(ops: list[Op]) -> BasicBlock:\n    block = BasicBlock()\n    block.ops.extend(ops)\n    return block\n\n\nclass TestGenerateNames(unittest.TestCase):\n    def test_empty(self) -> None:\n        assert generate_names_for_ir([], []) == {}\n\n    def test_arg(self) -> None:\n        reg = register(\"foo\")\n        assert generate_names_for_ir([reg], []) == {reg: \"foo\"}\n\n    def test_int_op(self) -> None:\n        n1 = Integer(2)\n        n2 = Integer(4)\n        op1 = IntOp(int_rprimitive, n1, n2, IntOp.ADD)\n        op2 = IntOp(int_rprimitive, op1, n2, IntOp.ADD)\n        block = make_block([op1, op2, Unreachable()])\n        assert generate_names_for_ir([], [block]) == {op1: \"r0\", op2: \"r1\"}\n\n    def test_assign(self) -> None:\n        reg = register(\"foo\")\n        n = Integer(2)\n        op1 = Assign(reg, n)\n        op2 = Assign(reg, n)\n        block = make_block([op1, op2])\n        assert generate_names_for_ir([reg], [block]) == {reg: \"foo\"}\n"
  },
  {
    "path": "mypyc/test/test_rarray.py",
    "content": "\"\"\"Unit tests for RArray types.\"\"\"\n\nfrom __future__ import annotations\n\nimport unittest\n\nfrom mypyc.common import PLATFORM_SIZE\nfrom mypyc.ir.rtypes import (\n    RArray,\n    bool_rprimitive,\n    compute_rtype_alignment,\n    compute_rtype_size,\n    int_rprimitive,\n)\n\n\nclass TestRArray(unittest.TestCase):\n    def test_basics(self) -> None:\n        a = RArray(int_rprimitive, 10)\n        assert a.item_type == int_rprimitive\n        assert a.length == 10\n\n    def test_str_conversion(self) -> None:\n        a = RArray(int_rprimitive, 10)\n        assert str(a) == \"int[10]\"\n        assert repr(a) == \"<RArray <RPrimitive builtins.int>[10]>\"\n\n    def test_eq(self) -> None:\n        a = RArray(int_rprimitive, 10)\n        assert a == RArray(int_rprimitive, 10)\n        assert a != RArray(bool_rprimitive, 10)\n        assert a != RArray(int_rprimitive, 9)\n\n    def test_hash(self) -> None:\n        assert hash(RArray(int_rprimitive, 10)) == hash(RArray(int_rprimitive, 10))\n        assert hash(RArray(bool_rprimitive, 5)) == hash(RArray(bool_rprimitive, 5))\n\n    def test_alignment(self) -> None:\n        a = RArray(int_rprimitive, 10)\n        assert compute_rtype_alignment(a) == PLATFORM_SIZE\n        b = RArray(bool_rprimitive, 55)\n        assert compute_rtype_alignment(b) == 1\n\n    def test_size(self) -> None:\n        a = RArray(int_rprimitive, 9)\n        assert compute_rtype_size(a) == 9 * PLATFORM_SIZE\n        b = RArray(bool_rprimitive, 3)\n        assert compute_rtype_size(b) == 3\n"
  },
  {
    "path": "mypyc/test/test_refcount.py",
    "content": "\"\"\"Test runner for reference count opcode insertion transform test cases.\n\nThe transform inserts needed reference count increment/decrement\noperations to IR.\n\"\"\"\n\nfrom __future__ import annotations\n\nimport os.path\n\nfrom mypy.errors import CompileError\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypyc.common import TOP_LEVEL_NAME\nfrom mypyc.ir.pprint import format_func\nfrom mypyc.test.testutil import (\n    ICODE_GEN_BUILTINS,\n    MypycDataSuite,\n    assert_test_output,\n    build_ir_for_single_file,\n    infer_ir_build_options_from_test_name,\n    remove_comment_lines,\n    replace_word_size,\n    use_custom_builtins,\n)\nfrom mypyc.transform.refcount import insert_ref_count_opcodes\nfrom mypyc.transform.uninit import insert_uninit_checks\n\nfiles = [\"refcount.test\"]\n\n\nclass TestRefCountTransform(MypycDataSuite):\n    files = files\n    base_path = test_temp_dir\n    optional_out = True\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        \"\"\"Perform a runtime checking transformation test case.\"\"\"\n        options = infer_ir_build_options_from_test_name(testcase.name)\n        if options is None:\n            # Skipped test case\n            return\n        with use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase):\n            expected_output = remove_comment_lines(testcase.output)\n            expected_output = replace_word_size(expected_output)\n            try:\n                ir = build_ir_for_single_file(testcase.input, options)\n            except CompileError as e:\n                actual = e.messages\n            else:\n                actual = []\n                for fn in ir:\n                    if fn.name == TOP_LEVEL_NAME and not testcase.name.endswith(\"_toplevel\"):\n                        continue\n                    insert_uninit_checks(fn, True)\n                    insert_ref_count_opcodes(fn)\n                    actual.extend(format_func(fn))\n\n            assert_test_output(testcase, actual, \"Invalid source code output\", expected_output)\n"
  },
  {
    "path": "mypyc/test/test_run.py",
    "content": "\"\"\"Test cases for building an C extension and running it.\"\"\"\n\nfrom __future__ import annotations\n\nimport ast\nimport contextlib\nimport glob\nimport os.path\nimport re\nimport shutil\nimport subprocess\nimport sys\nimport time\nfrom collections.abc import Iterator\nfrom typing import Any\n\nimport pytest\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.options import Options\nfrom mypy.test.config import mypyc_output_dir, test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase\nfrom mypy.test.helpers import assert_module_equivalence, perform_file_operations\nfrom mypyc.build import construct_groups\nfrom mypyc.codegen import emitmodule\nfrom mypyc.codegen.emitmodule import collect_source_dependencies\nfrom mypyc.errors import Errors\nfrom mypyc.options import CompilerOptions\nfrom mypyc.test.config import test_data_prefix\nfrom mypyc.test.librt_cache import get_librt_path\nfrom mypyc.test.test_serialization import check_serialization_roundtrip\nfrom mypyc.test.testutil import (\n    ICODE_GEN_BUILTINS,\n    TESTUTIL_PATH,\n    MypycDataSuite,\n    assert_test_output,\n    fudge_dir_mtimes,\n    has_test_name_tag,\n    show_c,\n    use_custom_builtins,\n)\n\nfiles = [\n    \"run-async.test\",\n    \"run-misc.test\",\n    \"run-functions.test\",\n    \"run-integers.test\",\n    \"run-i64.test\",\n    \"run-i32.test\",\n    \"run-i16.test\",\n    \"run-u8.test\",\n    \"run-floats.test\",\n    \"run-math.test\",\n    \"run-bools.test\",\n    \"run-strings.test\",\n    \"run-bytes.test\",\n    \"run-tuples.test\",\n    \"run-lists.test\",\n    \"run-dicts.test\",\n    \"run-sets.test\",\n    \"run-primitives.test\",\n    \"run-loops.test\",\n    \"run-exceptions.test\",\n    \"run-imports.test\",\n    \"run-classes.test\",\n    \"run-traits.test\",\n    \"run-generators.test\",\n    \"run-generics.test\",\n    \"run-multimodule.test\",\n    \"run-bench.test\",\n    \"run-mypy-sim.test\",\n    \"run-dunders.test\",\n    \"run-dunders-special.test\",\n    \"run-singledispatch.test\",\n    \"run-attrs.test\",\n    \"run-signatures.test\",\n    \"run-weakref.test\",\n    \"run-python37.test\",\n    \"run-python38.test\",\n    \"run-librt-strings.test\",\n    \"run-base64.test\",\n    \"run-librt-time.test\",\n    \"run-match.test\",\n    \"run-vecs-i64-interp.test\",\n    \"run-vecs-misc-interp.test\",\n    \"run-vecs-t-interp.test\",\n    \"run-vecs-nested-interp.test\",\n    \"run-vecs-i64.test\",\n    \"run-vecs-misc.test\",\n    \"run-vecs-t.test\",\n    \"run-vecs-nested.test\",\n]\n\nif sys.version_info >= (3, 12):\n    files.append(\"run-python312.test\")\n\nsetup_format = \"\"\"\\\nfrom setuptools import setup\nfrom mypyc.build import mypycify\n\nsetup(name='test_run_output',\n      ext_modules=mypycify({}, separate={}, skip_cgen_input={!r}, strip_asserts=False,\n                           multi_file={}, opt_level='{}', install_librt={},\n                           experimental_features={}),\n)\n\"\"\"\n\nWORKDIR = \"build\"\n\n\ndef run_setup(script_name: str, script_args: list[str]) -> bool:\n    \"\"\"Run a setup script in a somewhat controlled environment.\n\n    This is adapted from code in distutils and our goal here is that is\n    faster to not need to spin up a python interpreter to run it.\n\n    We had to fork it because the real run_setup swallows errors\n    and KeyboardInterrupt with no way to recover them (!).\n    The real version has some extra features that we removed since\n    we weren't using them.\n\n    Returns whether the setup succeeded.\n    \"\"\"\n    save_argv = sys.argv.copy()\n    g = {\"__file__\": script_name}\n    try:\n        try:\n            sys.argv[0] = script_name\n            sys.argv[1:] = script_args\n            with open(script_name, \"rb\") as f:\n                exec(f.read(), g)\n        finally:\n            sys.argv = save_argv\n    except SystemExit as e:\n        # distutils converts KeyboardInterrupt into a SystemExit with\n        # \"interrupted\" as the argument. Convert it back so that\n        # pytest will exit instead of just failing the test.\n        if e.code == \"interrupted\":\n            raise KeyboardInterrupt from e\n\n        return e.code == 0 or e.code is None\n\n    return True\n\n\n@contextlib.contextmanager\ndef chdir_manager(target: str) -> Iterator[None]:\n    dir = os.getcwd()\n    os.chdir(target)\n    try:\n        yield\n    finally:\n        os.chdir(dir)\n\n\nclass TestRun(MypycDataSuite):\n    \"\"\"Test cases that build a C extension and run code.\"\"\"\n\n    files = files\n    base_path = test_temp_dir\n    optional_out = True\n    multi_file = False\n    separate = False  # If True, using separate (incremental) compilation\n    strict_dunder_typing = False\n\n    def run_case(self, testcase: DataDrivenTestCase) -> None:\n        with pytest.MonkeyPatch.context() as mp:\n            mp.delenv(\"CFLAGS\", raising=False)\n            # setup.py wants to be run from the root directory of the package, which we accommodate\n            # by chdiring into tmp/\n            with (\n                use_custom_builtins(os.path.join(self.data_prefix, ICODE_GEN_BUILTINS), testcase),\n                chdir_manager(\"tmp\"),\n            ):\n                self.run_case_inner(testcase)\n\n    def run_case_inner(self, testcase: DataDrivenTestCase) -> None:\n        if not os.path.isdir(WORKDIR):  # (one test puts something in build...)\n            os.mkdir(WORKDIR)\n\n        text = \"\\n\".join(testcase.input)\n\n        with open(\"native.py\", \"w\", encoding=\"utf-8\") as f:\n            f.write(text)\n        with open(\"interpreted.py\", \"w\", encoding=\"utf-8\") as f:\n            f.write(text)\n\n        shutil.copyfile(TESTUTIL_PATH, \"testutil.py\")\n\n        step = 1\n        self.run_case_step(testcase, step)\n\n        steps = testcase.find_steps()\n        if steps == [[]]:\n            steps = []\n\n        for operations in steps:\n            # To make sure that any new changes get picked up as being\n            # new by distutils, shift the mtime of all of the\n            # generated artifacts back by a second.\n            fudge_dir_mtimes(WORKDIR, -1)\n            # On some OS, changing the mtime doesn't work reliably. As\n            # a workaround, sleep.\n            # TODO: Figure out a better approach, since this slows down tests.\n            time.sleep(1.0)\n\n            step += 1\n            with chdir_manager(\"..\"):\n                perform_file_operations(operations)\n            self.run_case_step(testcase, step)\n\n    def run_case_step(self, testcase: DataDrivenTestCase, incremental_step: int) -> None:\n        benchmark_build = has_test_name_tag(testcase.name, \"benchmark\")\n        bench = testcase.config.getoption(\"--bench\", False) and (\n            benchmark_build or \"Benchmark\" in testcase.name\n        )\n\n        options = Options()\n        options.use_builtins_fixtures = True\n        options.show_traceback = True\n        options.strict_optional = True\n        options.strict_bytes = True\n        options.disable_bytearray_promotion = True\n        options.disable_memoryview_promotion = True\n        options.python_version = sys.version_info[:2]\n        options.export_types = True\n        options.preserve_asts = True\n        options.allow_empty_bodies = True\n        options.incremental = self.separate\n        options.check_untyped_defs = True\n\n        # Avoid checking modules/packages named 'unchecked', to provide a way\n        # to test interacting with code we don't have types for.\n        options.per_module_options[\"unchecked.*\"] = {\"follow_imports\": \"error\"}\n\n        source = build.BuildSource(\"native.py\", \"native\", None)\n        sources = [source]\n        module_names = [\"native\"]\n        module_paths = [\"native.py\"]\n\n        # Hard code another module name to compile in the same compilation unit.\n        to_delete = []\n        for fn, text in testcase.files:\n            fn = os.path.relpath(fn, test_temp_dir)\n\n            if os.path.basename(fn).startswith(\"other\") and fn.endswith(\".py\"):\n                name = fn.split(\".\")[0].replace(os.sep, \".\")\n                module_names.append(name)\n                sources.append(build.BuildSource(fn, name, None))\n                to_delete.append(fn)\n                module_paths.append(fn)\n\n                shutil.copyfile(fn, os.path.join(os.path.dirname(fn), name + \"_interpreted.py\"))\n\n        for source in sources:\n            options.per_module_options.setdefault(source.module, {})[\"mypyc\"] = True\n\n        separate = (\n            self.get_separate(\"\\n\".join(testcase.input), incremental_step)\n            if self.separate\n            else False\n        )\n\n        groups = construct_groups(sources, separate, len(module_names) > 1, None)\n\n        # Use _librt_internal to test mypy-specific parts of librt (they have\n        # some special-casing in mypyc), for everything else use _librt suffix.\n        librt_internal = has_test_name_tag(testcase.name, \"librt_internal\")\n        librt = has_test_name_tag(testcase.name, \"librt\")\n        # Enable experimental features (local librt build also includes experimental features)\n        experimental_features = has_test_name_tag(testcase.name, \"experimental\")\n        try:\n            compiler_options = CompilerOptions(\n                multi_file=self.multi_file,\n                separate=self.separate,\n                strict_dunder_typing=self.strict_dunder_typing,\n                depends_on_librt_internal=librt_internal,\n                experimental_features=experimental_features,\n                strict_traceback_checks=True,\n            )\n            result = emitmodule.parse_and_typecheck(\n                sources=sources,\n                options=options,\n                compiler_options=compiler_options,\n                groups=groups,\n                alt_lib_path=\".\",\n            )\n            errors = Errors(options)\n            ir, cfiles, _ = emitmodule.compile_modules_to_c(\n                result, compiler_options=compiler_options, errors=errors, groups=groups\n            )\n            deps = sorted(dep.path for dep in collect_source_dependencies(ir))\n            if errors.num_errors:\n                errors.flush_errors()\n                assert False, \"Compile error\"\n        except CompileError as e:\n            for line in e.messages:\n                print(fix_native_line_number(line, testcase.file, testcase.line))\n            assert False, \"Compile error\"\n        finally:\n            result.manager.metastore.close()\n\n        # Check that serialization works on this IR. (Only on the first\n        # step because the returned ir only includes updated code.)\n        if incremental_step == 1:\n            check_serialization_roundtrip(ir)\n\n        opt_level = 3 if benchmark_build else int(os.environ.get(\"MYPYC_OPT_LEVEL\", 0))\n\n        setup_file = os.path.abspath(os.path.join(WORKDIR, \"setup.py\"))\n        # We pass the C file information to the build script via setup.py unfortunately\n        # Note: install_librt is always False since we use cached librt from librt_cache\n        with open(setup_file, \"w\", encoding=\"utf-8\") as f:\n            f.write(\n                setup_format.format(\n                    module_paths,\n                    separate,\n                    (cfiles, deps),\n                    self.multi_file,\n                    opt_level,\n                    False,  # install_librt - use cached version instead\n                    experimental_features,\n                )\n            )\n\n        if librt:\n            # Use cached pre-built librt instead of rebuilding for each test\n            cached_librt = get_librt_path(experimental_features, opt_level=str(opt_level))\n            shutil.copytree(os.path.join(cached_librt, \"librt\"), \"librt\")\n\n        if not run_setup(setup_file, [\"build_ext\", \"--inplace\"]):\n            if testcase.config.getoption(\"--mypyc-showc\"):\n                show_c(cfiles)\n            copy_output_files(mypyc_output_dir)\n            assert False, \"Compilation failed\"\n\n        # Assert that an output file got created\n        suffix = \"pyd\" if sys.platform == \"win32\" else \"so\"\n        assert glob.glob(f\"native.*.{suffix}\") or glob.glob(f\"native.{suffix}\")\n\n        driver_path = \"driver.py\"\n        if not os.path.isfile(driver_path):\n            # No driver.py provided by test case. Use the default one\n            # (mypyc/test-data/driver/driver.py) that calls each\n            # function named test_*.\n            default_driver = os.path.join(test_data_prefix, \"driver\", \"driver.py\")\n            shutil.copy(default_driver, driver_path)\n        env = os.environ.copy()\n        env[\"MYPYC_RUN_BENCH\"] = \"1\" if bench else \"0\"\n\n        debugger = testcase.config.getoption(\"debugger\")\n        if debugger:\n            if debugger == \"lldb\":\n                subprocess.check_call([\"lldb\", \"--\", sys.executable, driver_path], env=env)\n            elif debugger == \"gdb\":\n                subprocess.check_call([\"gdb\", \"--args\", sys.executable, driver_path], env=env)\n            else:\n                assert False, \"Unsupported debugger\"\n            # TODO: find a way to automatically disable capturing\n            # stdin/stdout when in debugging mode\n            assert False, (\n                \"Test can't pass in debugging mode. \"\n                \"(Make sure to pass -s to pytest to interact with the debugger)\"\n            )\n        proc = subprocess.Popen(\n            [sys.executable, driver_path],\n            stdout=subprocess.PIPE,\n            stderr=subprocess.STDOUT,\n            env=env,\n        )\n        if sys.version_info >= (3, 12):\n            # TODO: testDecorators1 hangs on 3.12, remove this once fixed\n            proc.wait(timeout=30)\n        output = proc.communicate()[0].decode(\"utf8\")\n        output = output.replace(f'  File \"{os.getcwd()}{os.sep}', '  File \"')\n        outlines = output.splitlines()\n\n        if testcase.config.getoption(\"--mypyc-showc\"):\n            show_c(cfiles)\n        if proc.returncode != 0:\n            print()\n            signal = proc.returncode == -11\n            extra = \"\"\n            if signal:\n                extra = \" (likely segmentation fault)\"\n            print(f\"*** Exit status: {proc.returncode}{extra}\")\n            if signal and not sys.platform.startswith(\"win\"):\n                print()\n                if sys.platform == \"darwin\":\n                    debugger = \"lldb\"\n                else:\n                    debugger = \"gdb\"\n                print(\n                    f'hint: Use \"pytest -n0 -s --mypyc-debug={debugger} -k <name-substring>\" to run test in debugger'\n                )\n                print(\"hint: You may need to build a debug version of Python first and use it\")\n                print('hint: See also \"Debugging Segfaults\" in mypyc/doc/dev-intro.md')\n            copy_output_files(mypyc_output_dir)\n\n        # Verify output.\n        if bench:\n            print(\"Test output:\")\n            print(output)\n        else:\n            if incremental_step == 1:\n                msg = \"Invalid output\"\n                expected = testcase.output\n            else:\n                msg = f\"Invalid output (step {incremental_step})\"\n                expected = testcase.output2.get(incremental_step, [])\n\n            if not expected:\n                # Tweak some line numbers, but only if the expected output is empty,\n                # as tweaked output might not match expected output.\n                outlines = [\n                    fix_native_line_number(line, testcase.file, testcase.line) for line in outlines\n                ]\n            assert_test_output(testcase, outlines, msg, expected)\n\n        if incremental_step > 1 and options.incremental:\n            suffix = \"\" if incremental_step == 2 else str(incremental_step - 1)\n            expected_rechecked = testcase.expected_rechecked_modules.get(incremental_step - 1)\n            if expected_rechecked is not None:\n                assert_module_equivalence(\n                    \"rechecked\" + suffix, expected_rechecked, result.manager.rechecked_modules\n                )\n            expected_stale = testcase.expected_stale_modules.get(incremental_step - 1)\n            if expected_stale is not None:\n                assert_module_equivalence(\n                    \"stale\" + suffix, expected_stale, result.manager.stale_modules\n                )\n\n        assert proc.returncode == 0\n\n    def get_separate(self, program_text: str, incremental_step: int) -> Any:\n        template = r\"# separate{}: (\\[.*\\])$\"\n        m = re.search(template.format(incremental_step), program_text, flags=re.MULTILINE)\n        if not m:\n            m = re.search(template.format(\"\"), program_text, flags=re.MULTILINE)\n        if m:\n            return ast.literal_eval(m.group(1))\n        else:\n            return True\n\n\nclass TestRunMultiFile(TestRun):\n    \"\"\"Run the main multi-module tests in multi-file compilation mode.\n\n    In multi-file mode each module gets compiled into a separate C file,\n    but all modules (C files) are compiled together.\n    \"\"\"\n\n    multi_file = True\n    test_name_suffix = \"_multi\"\n    files = [\"run-multimodule.test\", \"run-mypy-sim.test\"]\n\n\nclass TestRunSeparate(TestRun):\n    \"\"\"Run the main multi-module tests in separate compilation mode.\n\n    In this mode there are multiple compilation groups, which are compiled\n    incrementally. Each group is compiled to a separate C file, and these C\n    files are compiled separately.\n\n    Each compiled module is placed into a separate compilation group, unless\n    overridden by a special comment. Consider this example:\n\n      # separate: [([\"other.py\", \"other_b.py\"], \"stuff\")]\n\n    This puts other.py and other_b.py into a compilation group named \"stuff\".\n    Any files not mentioned in the comment will get single-file groups.\n    \"\"\"\n\n    separate = True\n    test_name_suffix = \"_separate\"\n    files = [\"run-multimodule.test\", \"run-mypy-sim.test\"]\n\n\nclass TestRunStrictDunderTyping(TestRun):\n    \"\"\"Run the tests with strict dunder typing.\"\"\"\n\n    strict_dunder_typing = True\n    test_name_suffix = \"_dunder_typing\"\n    files = [\"run-dunders.test\", \"run-floats.test\"]\n\n\ndef fix_native_line_number(message: str, fnam: str, delta: int) -> str:\n    \"\"\"Update code locations in test case output to point to the .test file.\n\n    The description of the test case is written to native.py, and line numbers\n    in test case output often are relative to native.py. This translates the\n    line numbers to be relative to the .test file that contains the test case\n    description, and also updates the file name to the .test file name.\n\n    Args:\n        message: message to update\n        fnam: path of the .test file\n        delta: line number of the beginning of the test case in the .test file\n\n    Returns updated message (or original message if we couldn't find anything).\n    \"\"\"\n    fnam = os.path.basename(fnam)\n    message = re.sub(\n        r\"native\\.py:([0-9]+):\", lambda m: \"%s:%d:\" % (fnam, int(m.group(1)) + delta), message\n    )\n    message = re.sub(\n        r'\"native.py\", line ([0-9]+),',\n        lambda m: '\"%s\", line %d,' % (fnam, int(m.group(1)) + delta),\n        message,\n    )\n    return message\n\n\ndef copy_output_files(target_dir: str) -> None:\n    try:\n        os.mkdir(target_dir)\n    except OSError:\n        # Only copy data for the first failure, to avoid excessive output in case\n        # many tests fail\n        return\n\n    for fnam in glob.glob(\"build/*.[ch]\"):\n        shutil.copy(fnam, target_dir)\n\n    sys.stderr.write(f\"\\nGenerated files: {target_dir} (for first failure only)\\n\\n\")\n"
  },
  {
    "path": "mypyc/test/test_serialization.py",
    "content": "\"\"\"Functions to check that serialization round-tripped properly.\"\"\"\n\n# This file is named test_serialization.py even though it doesn't\n# contain its own tests so that pytest will rewrite the asserts...\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable\nfrom typing import Any\n\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FuncDecl, FuncIR, FuncSignature\nfrom mypyc.ir.module_ir import ModuleIR, deserialize_modules\nfrom mypyc.ir.ops import DeserMaps\nfrom mypyc.ir.rtypes import RType\nfrom mypyc.sametype import is_same_signature, is_same_type\n\n\ndef get_dict(x: Any) -> dict[str, Any]:\n    if hasattr(x, \"__mypyc_attrs__\"):\n        return {k: getattr(x, k) for k in x.__mypyc_attrs__ if hasattr(x, k)}\n    else:\n        return dict(x.__dict__)\n\n\ndef get_function_dict(x: FuncIR) -> dict[str, Any]:\n    \"\"\"Get a dict of function attributes safe to compare across serialization\"\"\"\n    d = get_dict(x)\n    d.pop(\"blocks\", None)\n    d.pop(\"env\", None)\n    return d\n\n\ndef assert_blobs_same(x: Any, y: Any, trail: tuple[Any, ...]) -> None:\n    \"\"\"Compare two blobs of IR as best we can.\n\n    FuncDecls, FuncIRs, and ClassIRs are compared by fullname to avoid\n    infinite recursion.\n    (More detailed comparisons should be done manually.)\n\n    Types and signatures are compared using mypyc.sametype.\n\n    Containers are compared recursively.\n\n    Anything else is compared with ==.\n\n    The `trail` argument is used in error messages.\n    \"\"\"\n\n    assert type(x) is type(y), (f\"Type mismatch at {trail}\", type(x), type(y))\n    if isinstance(x, (FuncDecl, FuncIR, ClassIR)):\n        assert x.fullname == y.fullname, f\"Name mismatch at {trail}\"\n    elif isinstance(x, dict):\n        assert len(x.keys()) == len(y.keys()), f\"Keys mismatch at {trail}\"\n        for (xk, xv), (yk, yv) in zip(x.items(), y.items()):\n            assert_blobs_same(xk, yk, trail + (\"keys\",))\n            assert_blobs_same(xv, yv, trail + (xk,))\n    elif isinstance(x, Iterable) and not isinstance(x, (str, set)):\n        # Special case iterables to generate better assert error messages.\n        # We can't use this for sets since the ordering is unpredictable,\n        # and strings should be treated as atomic values.\n        for i, (xv, yv) in enumerate(zip(x, y)):\n            assert_blobs_same(xv, yv, trail + (i,))\n    elif isinstance(x, RType):\n        assert is_same_type(x, y), f\"RType mismatch at {trail}\"\n    elif isinstance(x, FuncSignature):\n        assert is_same_signature(x, y), f\"Signature mismatch at {trail}\"\n    else:\n        assert x == y, f\"Value mismatch at {trail}\"\n\n\ndef assert_modules_same(ir1: ModuleIR, ir2: ModuleIR) -> None:\n    \"\"\"Assert that two module IRs are the same (*).\n\n    * Or rather, as much as we care about preserving across\n    serialization.  We drop the actual IR bodies of functions but try\n    to preserve everything else.\n    \"\"\"\n    assert ir1.fullname == ir2.fullname\n\n    assert ir1.imports == ir2.imports\n\n    for cls1, cls2 in zip(ir1.classes, ir2.classes):\n        assert_blobs_same(get_dict(cls1), get_dict(cls2), (ir1.fullname, cls1.fullname))\n\n    for fn1, fn2 in zip(ir1.functions, ir2.functions):\n        assert_blobs_same(\n            get_function_dict(fn1), get_function_dict(fn2), (ir1.fullname, fn1.fullname)\n        )\n        assert_blobs_same(get_dict(fn1.decl), get_dict(fn2.decl), (ir1.fullname, fn1.fullname))\n\n    assert_blobs_same(ir1.final_names, ir2.final_names, (ir1.fullname, \"final_names\"))\n\n\ndef check_serialization_roundtrip(irs: dict[str, ModuleIR]) -> None:\n    \"\"\"Check that we can serialize modules out and deserialize them to the same thing.\"\"\"\n    serialized = {k: ir.serialize() for k, ir in irs.items()}\n\n    ctx = DeserMaps({}, {})\n    irs2 = deserialize_modules(serialized, ctx)\n    assert irs.keys() == irs2.keys()\n\n    for k in irs:\n        assert_modules_same(irs[k], irs2[k])\n"
  },
  {
    "path": "mypyc/test/test_struct.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypyc.ir.rtypes import (\n    RStruct,\n    bool_rprimitive,\n    int32_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    object_rprimitive,\n)\nfrom mypyc.rt_subtype import is_runtime_subtype\n\n\nclass TestStruct(unittest.TestCase):\n    def test_struct_offsets(self) -> None:\n        # test per-member alignment\n        r = RStruct(\"\", [], [bool_rprimitive, int32_rprimitive, int64_rprimitive])\n        assert r.size == 16\n        assert r.offsets == [0, 4, 8]\n\n        # test final alignment\n        r1 = RStruct(\"\", [], [bool_rprimitive, bool_rprimitive])\n        assert r1.size == 2\n        assert r1.offsets == [0, 1]\n        r2 = RStruct(\"\", [], [int32_rprimitive, bool_rprimitive])\n        r3 = RStruct(\"\", [], [int64_rprimitive, bool_rprimitive])\n        assert r2.offsets == [0, 4]\n        assert r3.offsets == [0, 8]\n        assert r2.size == 8\n        assert r3.size == 16\n\n        r4 = RStruct(\"\", [], [bool_rprimitive, bool_rprimitive, bool_rprimitive, int32_rprimitive])\n        assert r4.size == 8\n        assert r4.offsets == [0, 1, 2, 4]\n\n        # test nested struct\n        r5 = RStruct(\"\", [], [bool_rprimitive, r])\n        assert r5.offsets == [0, 8]\n        assert r5.size == 24\n        r6 = RStruct(\"\", [], [int32_rprimitive, r5])\n        assert r6.offsets == [0, 8]\n        assert r6.size == 32\n        # test nested struct with alignment less than 8\n        r7 = RStruct(\"\", [], [bool_rprimitive, r4])\n        assert r7.offsets == [0, 4]\n        assert r7.size == 12\n\n    def test_struct_str(self) -> None:\n        r = RStruct(\"Foo\", [\"a\", \"b\"], [bool_rprimitive, object_rprimitive])\n        assert str(r) == \"Foo{a:bool, b:object}\"\n        assert (\n            repr(r) == \"<RStruct Foo{a:<RPrimitive builtins.bool>, \"\n            \"b:<RPrimitive builtins.object>}>\"\n        )\n        r1 = RStruct(\"Bar\", [\"c\"], [int32_rprimitive])\n        assert str(r1) == \"Bar{c:i32}\"\n        assert repr(r1) == \"<RStruct Bar{c:<RPrimitive i32>}>\"\n        r2 = RStruct(\"Baz\", [], [])\n        assert str(r2) == \"Baz{}\"\n        assert repr(r2) == \"<RStruct Baz{}>\"\n\n    def test_runtime_subtype(self) -> None:\n        # right type to check with\n        r = RStruct(\"Foo\", [\"a\", \"b\"], [bool_rprimitive, int_rprimitive])\n\n        # using the exact same fields\n        r1 = RStruct(\"Foo\", [\"a\", \"b\"], [bool_rprimitive, int_rprimitive])\n\n        # names different\n        r2 = RStruct(\"Bar\", [\"c\", \"b\"], [bool_rprimitive, int_rprimitive])\n\n        # name different\n        r3 = RStruct(\"Baz\", [\"a\", \"b\"], [bool_rprimitive, int_rprimitive])\n\n        # type different\n        r4 = RStruct(\"FooBar\", [\"a\", \"b\"], [bool_rprimitive, int32_rprimitive])\n\n        # number of types different\n        r5 = RStruct(\n            \"FooBarBaz\", [\"a\", \"b\", \"c\"], [bool_rprimitive, int_rprimitive, bool_rprimitive]\n        )\n\n        assert is_runtime_subtype(r1, r) is True\n        assert is_runtime_subtype(r2, r) is False\n        assert is_runtime_subtype(r3, r) is False\n        assert is_runtime_subtype(r4, r) is False\n        assert is_runtime_subtype(r5, r) is False\n\n    def test_eq_and_hash(self) -> None:\n        r = RStruct(\"Foo\", [\"a\", \"b\"], [bool_rprimitive, int_rprimitive])\n\n        # using the exact same fields\n        r1 = RStruct(\"Foo\", [\"a\", \"b\"], [bool_rprimitive, int_rprimitive])\n        assert hash(r) == hash(r1)\n        assert r == r1\n\n        # different name\n        r2 = RStruct(\"Foq\", [\"a\", \"b\"], [bool_rprimitive, int_rprimitive])\n        assert hash(r) != hash(r2)\n        assert r != r2\n\n        # different names\n        r3 = RStruct(\"Foo\", [\"a\", \"c\"], [bool_rprimitive, int_rprimitive])\n        assert hash(r) != hash(r3)\n        assert r != r3\n\n        # different type\n        r4 = RStruct(\"Foo\", [\"a\", \"b\"], [bool_rprimitive, int_rprimitive, bool_rprimitive])\n        assert hash(r) != hash(r4)\n        assert r != r4\n"
  },
  {
    "path": "mypyc/test/test_tuplename.py",
    "content": "from __future__ import annotations\n\nimport unittest\n\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.rtypes import (\n    RInstance,\n    RTuple,\n    RUnion,\n    bool_rprimitive,\n    int_rprimitive,\n    list_rprimitive,\n    object_rprimitive,\n)\n\n\nclass TestTupleNames(unittest.TestCase):\n    def setUp(self) -> None:\n        self.inst_a = RInstance(ClassIR(\"A\", \"__main__\"))\n        self.inst_b = RInstance(ClassIR(\"B\", \"__main__\"))\n\n    def test_names(self) -> None:\n        assert RTuple([int_rprimitive, int_rprimitive]).unique_id == \"T2II\"\n        assert RTuple([list_rprimitive, object_rprimitive, self.inst_a]).unique_id == \"T3OOO\"\n        assert RTuple([list_rprimitive, object_rprimitive, self.inst_b]).unique_id == \"T3OOO\"\n        assert RTuple([]).unique_id == \"T0\"\n        assert (\n            RTuple([RTuple([]), RTuple([int_rprimitive, int_rprimitive])]).unique_id == \"T2T0T2II\"\n        )\n        assert (\n            RTuple([bool_rprimitive, RUnion([bool_rprimitive, int_rprimitive])]).unique_id\n            == \"T2CO\"\n        )\n"
  },
  {
    "path": "mypyc/test/test_typeops.py",
    "content": "\"\"\"Test cases for various RType operations.\"\"\"\n\nfrom __future__ import annotations\n\nimport unittest\n\nfrom mypyc.ir.rtypes import (\n    RUnion,\n    bit_rprimitive,\n    bool_rprimitive,\n    int16_rprimitive,\n    int32_rprimitive,\n    int64_rprimitive,\n    int_rprimitive,\n    object_rprimitive,\n    short_int_rprimitive,\n    str_rprimitive,\n)\nfrom mypyc.rt_subtype import is_runtime_subtype\nfrom mypyc.subtype import is_subtype\n\nnative_int_types = [int64_rprimitive, int32_rprimitive, int16_rprimitive]\n\n\nclass TestSubtype(unittest.TestCase):\n    def test_bit(self) -> None:\n        assert is_subtype(bit_rprimitive, bool_rprimitive)\n        assert is_subtype(bit_rprimitive, int_rprimitive)\n        assert is_subtype(bit_rprimitive, short_int_rprimitive)\n        for rt in native_int_types:\n            assert is_subtype(bit_rprimitive, rt)\n\n    def test_bool(self) -> None:\n        assert not is_subtype(bool_rprimitive, bit_rprimitive)\n        assert is_subtype(bool_rprimitive, int_rprimitive)\n        assert is_subtype(bool_rprimitive, short_int_rprimitive)\n        for rt in native_int_types:\n            assert is_subtype(bool_rprimitive, rt)\n\n    def test_int64(self) -> None:\n        assert is_subtype(int64_rprimitive, int64_rprimitive)\n        assert is_subtype(int64_rprimitive, int_rprimitive)\n        assert not is_subtype(int64_rprimitive, short_int_rprimitive)\n        assert not is_subtype(int64_rprimitive, int32_rprimitive)\n        assert not is_subtype(int64_rprimitive, int16_rprimitive)\n\n    def test_int32(self) -> None:\n        assert is_subtype(int32_rprimitive, int32_rprimitive)\n        assert is_subtype(int32_rprimitive, int_rprimitive)\n        assert not is_subtype(int32_rprimitive, short_int_rprimitive)\n        assert not is_subtype(int32_rprimitive, int64_rprimitive)\n        assert not is_subtype(int32_rprimitive, int16_rprimitive)\n\n    def test_int16(self) -> None:\n        assert is_subtype(int16_rprimitive, int16_rprimitive)\n        assert is_subtype(int16_rprimitive, int_rprimitive)\n        assert not is_subtype(int16_rprimitive, short_int_rprimitive)\n        assert not is_subtype(int16_rprimitive, int64_rprimitive)\n        assert not is_subtype(int16_rprimitive, int32_rprimitive)\n\n\nclass TestRuntimeSubtype(unittest.TestCase):\n    def test_bit(self) -> None:\n        assert is_runtime_subtype(bit_rprimitive, bool_rprimitive)\n        assert not is_runtime_subtype(bit_rprimitive, int_rprimitive)\n\n    def test_bool(self) -> None:\n        assert not is_runtime_subtype(bool_rprimitive, bit_rprimitive)\n        assert not is_runtime_subtype(bool_rprimitive, int_rprimitive)\n\n    def test_union(self) -> None:\n        bool_int_mix = RUnion([bool_rprimitive, int_rprimitive])\n        assert not is_runtime_subtype(bool_int_mix, short_int_rprimitive)\n        assert not is_runtime_subtype(bool_int_mix, int_rprimitive)\n        assert not is_runtime_subtype(short_int_rprimitive, bool_int_mix)\n        assert not is_runtime_subtype(int_rprimitive, bool_int_mix)\n\n\nclass TestUnionSimplification(unittest.TestCase):\n    def test_simple_type_result(self) -> None:\n        assert RUnion.make_simplified_union([int_rprimitive]) == int_rprimitive\n\n    def test_remove_duplicate(self) -> None:\n        assert RUnion.make_simplified_union([int_rprimitive, int_rprimitive]) == int_rprimitive\n\n    def test_cannot_simplify(self) -> None:\n        assert RUnion.make_simplified_union(\n            [int_rprimitive, str_rprimitive, object_rprimitive]\n        ) == RUnion([int_rprimitive, str_rprimitive, object_rprimitive])\n\n    def test_nested(self) -> None:\n        assert RUnion.make_simplified_union(\n            [int_rprimitive, RUnion([str_rprimitive, int_rprimitive])]\n        ) == RUnion([int_rprimitive, str_rprimitive])\n        assert RUnion.make_simplified_union(\n            [int_rprimitive, RUnion([str_rprimitive, RUnion([int_rprimitive])])]\n        ) == RUnion([int_rprimitive, str_rprimitive])\n"
  },
  {
    "path": "mypyc/test/testutil.py",
    "content": "\"\"\"Helpers for writing tests\"\"\"\n\nfrom __future__ import annotations\n\nimport contextlib\nimport os\nimport os.path\nimport re\nimport shutil\nfrom collections.abc import Callable, Iterator\n\nfrom mypy import build\nfrom mypy.errors import CompileError\nfrom mypy.nodes import Expression, MypyFile\nfrom mypy.options import Options\nfrom mypy.test.config import test_temp_dir\nfrom mypy.test.data import DataDrivenTestCase, DataSuite\nfrom mypy.test.helpers import assert_string_arrays_equal\nfrom mypy.types import Type\nfrom mypyc.analysis.ircheck import assert_func_ir_valid\nfrom mypyc.common import IS_32_BIT_PLATFORM, PLATFORM_SIZE\nfrom mypyc.errors import Errors\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.module_ir import ModuleIR\nfrom mypyc.irbuild.main import build_ir\nfrom mypyc.irbuild.mapper import Mapper\nfrom mypyc.options import CompilerOptions\nfrom mypyc.test.config import test_data_prefix\n\n# The builtins stub used during icode generation test cases.\nICODE_GEN_BUILTINS = os.path.join(test_data_prefix, \"fixtures/ir.py\")\n# The testutil support library\nTESTUTIL_PATH = os.path.join(test_data_prefix, \"fixtures/testutil.py\")\n\n\nclass MypycDataSuite(DataSuite):\n    # Need to list no files, since this will be picked up as a suite of tests\n    files: list[str] = []\n    data_prefix = test_data_prefix\n\n\ndef builtins_wrapper(\n    func: Callable[[DataDrivenTestCase], None], path: str\n) -> Callable[[DataDrivenTestCase], None]:\n    \"\"\"Decorate a function that implements a data-driven test case to copy an\n    alternative builtins module implementation in place before performing the\n    test case. Clean up after executing the test case.\n    \"\"\"\n    return lambda testcase: perform_test(func, path, testcase)\n\n\n@contextlib.contextmanager\ndef use_custom_builtins(builtins_path: str, testcase: DataDrivenTestCase) -> Iterator[None]:\n    for path, _ in testcase.files:\n        if os.path.basename(path) == \"builtins.pyi\":\n            default_builtins = False\n            break\n    else:\n        # Use default builtins.\n        builtins = os.path.abspath(os.path.join(test_temp_dir, \"builtins.pyi\"))\n        shutil.copyfile(builtins_path, builtins)\n        default_builtins = True\n\n    # Actually perform the test case.\n    try:\n        yield None\n    finally:\n        if default_builtins:\n            # Clean up.\n            os.remove(builtins)\n\n\ndef perform_test(\n    func: Callable[[DataDrivenTestCase], None], builtins_path: str, testcase: DataDrivenTestCase\n) -> None:\n    for path, _ in testcase.files:\n        if os.path.basename(path) == \"builtins.py\":\n            default_builtins = False\n            break\n    else:\n        # Use default builtins.\n        builtins = os.path.join(test_temp_dir, \"builtins.py\")\n        shutil.copyfile(builtins_path, builtins)\n        default_builtins = True\n\n    # Actually perform the test case.\n    func(testcase)\n\n    if default_builtins:\n        # Clean up.\n        os.remove(builtins)\n\n\ndef build_ir_for_single_file(\n    input_lines: list[str], compiler_options: CompilerOptions | None = None\n) -> list[FuncIR]:\n    return build_ir_for_single_file2(input_lines, compiler_options)[0].functions\n\n\ndef build_ir_for_single_file2(\n    input_lines: list[str], compiler_options: CompilerOptions | None = None\n) -> tuple[ModuleIR, MypyFile, dict[Expression, Type], Mapper]:\n    program_text = \"\\n\".join(input_lines)\n\n    # By default generate IR compatible with the earliest supported Python C API.\n    # If a test needs more recent API features, this should be overridden.\n    compiler_options = compiler_options or CompilerOptions(capi_version=(3, 9))\n    options = Options()\n    options.show_traceback = True\n    options.hide_error_codes = True\n    options.use_builtins_fixtures = True\n    options.strict_optional = True\n    options.python_version = compiler_options.python_version or (3, 9)\n    options.export_types = True\n    options.preserve_asts = True\n    options.allow_empty_bodies = True\n    options.strict_bytes = True\n    options.disable_bytearray_promotion = True\n    options.disable_memoryview_promotion = True\n    options.per_module_options[\"__main__\"] = {\"mypyc\": True}\n\n    source = build.BuildSource(\"main\", \"__main__\", program_text)\n    # Construct input as a single single.\n    # Parse and type check the input program.\n    result = build.build(sources=[source], options=options, alt_lib_path=test_temp_dir)\n    result.manager.metastore.close()\n    if result.errors:\n        raise CompileError(result.errors)\n\n    errors = Errors(options)\n    mapper = Mapper({\"__main__\": None})\n    modules = build_ir(\n        [result.files[\"__main__\"]], result.graph, result.types, mapper, compiler_options, errors\n    )\n    if errors.num_errors:\n        raise CompileError(errors.new_messages())\n\n    module = list(modules.values())[0]\n    for fn in module.functions:\n        assert_func_ir_valid(fn)\n    tree = result.graph[module.fullname].tree\n    assert tree is not None\n    return module, tree, result.types, mapper\n\n\ndef update_testcase_output(testcase: DataDrivenTestCase, output: list[str]) -> None:\n    # TODO: backport this to mypy\n    assert testcase.old_cwd is not None, \"test was not properly set up\"\n    testcase_path = os.path.join(testcase.old_cwd, testcase.file)\n    with open(testcase_path) as f:\n        data_lines = f.read().splitlines()\n\n    # We can't rely on the test line numbers to *find* the test, since\n    # we might fix multiple tests in a run. So find it by the case\n    # header. Give up if there are multiple tests with the same name.\n    test_slug = f\"[case {testcase.name}]\"\n    if data_lines.count(test_slug) != 1:\n        return\n    start_idx = data_lines.index(test_slug)\n    stop_idx = start_idx + 11\n    while stop_idx < len(data_lines) and not data_lines[stop_idx].startswith(\"[case \"):\n        stop_idx += 1\n\n    test = data_lines[start_idx:stop_idx]\n    out_start = test.index(\"[out]\")\n    test[out_start + 1 :] = output\n    data_lines[start_idx:stop_idx] = test + [\"\"]\n    data = \"\\n\".join(data_lines)\n\n    with open(testcase_path, \"w\") as f:\n        print(data, file=f)\n\n\ndef assert_test_output(\n    testcase: DataDrivenTestCase,\n    actual: list[str],\n    message: str,\n    expected: list[str] | None = None,\n    formatted: list[str] | None = None,\n) -> None:\n    __tracebackhide__ = True\n\n    expected_output = expected if expected is not None else testcase.output\n    if expected_output != actual and testcase.config.getoption(\"--update-data\", False):\n        update_testcase_output(testcase, actual)\n\n    assert_string_arrays_equal(\n        expected_output, actual, f\"{message} ({testcase.file}, line {testcase.line})\"\n    )\n\n\ndef get_func_names(expected: list[str]) -> list[str]:\n    res = []\n    for s in expected:\n        m = re.match(r\"def ([_a-zA-Z0-9.*$]+)\\(\", s)\n        if m:\n            res.append(m.group(1))\n    return res\n\n\ndef remove_comment_lines(a: list[str]) -> list[str]:\n    \"\"\"Return a copy of array with comments removed.\n\n    Lines starting with '--' (but not with '---') are removed.\n    \"\"\"\n    r = []\n    for s in a:\n        if s.strip().startswith(\"--\") and not s.strip().startswith(\"---\"):\n            pass\n        else:\n            r.append(s)\n    return r\n\n\ndef print_with_line_numbers(s: str) -> None:\n    lines = s.splitlines()\n    for i, line in enumerate(lines):\n        print(\"%-4d %s\" % (i + 1, line))\n\n\ndef heading(text: str) -> None:\n    print(\"=\" * 20 + \" \" + text + \" \" + \"=\" * 20)\n\n\ndef show_c(cfiles: list[list[tuple[str, str]]]) -> None:\n    heading(\"Generated C\")\n    for group in cfiles:\n        for cfile, ctext in group:\n            print(f\"== {cfile} ==\")\n            print_with_line_numbers(ctext)\n    heading(\"End C\")\n\n\ndef fudge_dir_mtimes(dir: str, delta: int) -> None:\n    for dirpath, _, filenames in os.walk(dir):\n        for name in filenames:\n            path = os.path.join(dirpath, name)\n            new_mtime = os.stat(path).st_mtime + delta\n            os.utime(path, times=(new_mtime, new_mtime))\n\n\ndef replace_word_size(text: list[str]) -> list[str]:\n    \"\"\"Replace WORDSIZE with platform specific word sizes\"\"\"\n    result = []\n    for line in text:\n        index = line.find(\"WORD_SIZE\")\n        if index != -1:\n            # get 'WORDSIZE*n' token\n            word_size_token = line[index:].split()[0]\n            n = int(word_size_token[10:])\n            replace_str = str(PLATFORM_SIZE * n)\n            result.append(line.replace(word_size_token, replace_str))\n        else:\n            result.append(line)\n    return result\n\n\ndef infer_ir_build_options_from_test_name(name: str) -> CompilerOptions | None:\n    \"\"\"Look for magic substrings in test case name to set compiler options.\n\n    Return None if the test case should be skipped (always pass).\n\n    Supported naming conventions:\n\n      *_64bit*:\n          Run test case only on 64-bit platforms\n      *_32bit*:\n          Run test caseonly on 32-bit platforms\n      *_python3_8* (or for any Python version):\n          Use Python 3.8+ C API features (default: lowest supported version)\n      *StripAssert*:\n          Don't generate code for assert statements\n    \"\"\"\n    # If this is specific to some bit width, always pass if platform doesn't match.\n    if \"_64bit\" in name and IS_32_BIT_PLATFORM:\n        return None\n    if \"_32bit\" in name and not IS_32_BIT_PLATFORM:\n        return None\n    options = CompilerOptions(\n        strip_asserts=\"StripAssert\" in name, capi_version=(3, 9), strict_traceback_checks=True\n    )\n    # A suffix like _python3_9 is used to set the target C API version.\n    m = re.search(r\"_python([3-9]+)_([0-9]+)(_|\\b)\", name)\n    if m:\n        options.capi_version = (int(m.group(1)), int(m.group(2)))\n        options.python_version = options.capi_version\n    elif \"_py\" in name or \"_Python\" in name:\n        assert False, f\"Invalid _py* suffix (should be _pythonX_Y): {name}\"\n    if has_test_name_tag(name, \"experimental\"):\n        options.experimental_features = True\n    return options\n\n\ndef has_test_name_tag(name: str, tag: str) -> bool:\n    \"\"\"Check if a test case name contains a tag token like ``_experimental``.\n\n    A tag matches if it appears as a full underscore-delimited token:\n    ``foo_tag_bar`` or ``foo_tag``.\n    \"\"\"\n    return re.search(rf\"(?:^|_){re.escape(tag)}(?:_|$)\", name) is not None\n"
  },
  {
    "path": "mypyc/test-data/alwaysdefined.test",
    "content": "-- Test cases for always defined attributes.\n--\n-- If class C has attributes x and y that are always defined, the output will\n-- have a line like this:\n--\n--   C: [x, y]\n\n[case testAlwaysDefinedSimple]\nclass C:\n    def __init__(self, x: int) -> None:\n        self.x = x\n[out]\nC: [x]\n\n[case testAlwaysDefinedFail]\nclass MethodCall:\n    def __init__(self, x: int) -> None:\n        self.f()\n        self.x = x\n\n    def f(self) -> None:\n        pass\n\nclass FuncCall:\n    def __init__(self, x: int) -> None:\n        f(x)\n        self.x = x\n        f(self)\n        self.y = x\n\nclass GetAttr:\n    x: int\n    def __init__(self, x: int) -> None:\n        a = self.x\n        self.x = x\n\nclass _Base:\n    def  __init__(self) -> None:\n        f(self)\n\nclass CallSuper(_Base):\n    def __init__(self, x: int) -> None:\n        super().__init__()\n        self.x = x\n\nclass Lambda:\n    def __init__(self, x: int) -> None:\n        f = lambda x: x + 1\n        self.x = x\n        g = lambda x: self\n        self.y = x\n\nclass If:\n    def __init__(self, x: int) -> None:\n        self.a = 1\n        if x:\n            self.x = x\n        else:\n            self.y = 1\n\nclass Deletable:\n    __deletable__ = ('x', 'y')\n\n    def __init__(self) -> None:\n        self.x = 0\n        self.y = 1\n        self.z = 2\n\nclass PrimitiveWithSelf:\n    def __init__(self, s: str) -> None:\n        self.x = getattr(self, s)\n\ndef f(a) -> None: pass\n[out]\nMethodCall: []\nFuncCall: [x]\nGetAttr: []\nCallSuper: []\nLambda: []\nIf: [a]\nDeletable: [z]\nPrimitiveWithSelf: []\n\n[case testAlwaysDefinedConditional]\nclass IfAlways:\n    def __init__(self, x: int, y: int) -> None:\n        if x:\n            self.x = x\n            self.y = y\n        elif y:\n            self.x = y\n            self.y = x\n        else:\n            self.x = 0\n            self.y = 0\n        self.z = 0\n\nclass IfSometimes1:\n    def __init__(self, x: int, y: int) -> None:\n        if x:\n            self.x = x\n            self.y = y\n        elif y:\n            self.z = y\n            self.y = x\n        else:\n            self.y = 0\n            self.a = 0\n\nclass IfSometimes2:\n    def __init__(self, x: int, y: int) -> None:\n        if x:\n            self.x = x\n        self.y = y\n\nclass IfStopAnalysis1:\n    def __init__(self, x: int, y: int) -> None:\n        if x:\n            self.x = x\n            f(self)\n        else:\n            self.x = x\n        self.y = y\n\nclass IfStopAnalysis2:\n    def __init__(self, x: int, y: int) -> None:\n        if x:\n            self.x = x\n        else:\n            self.x = x\n            f(self)\n        self.y = y\n\nclass IfStopAnalysis3:\n    def __init__(self, x: int, y: int) -> None:\n        if x:\n            self.x = x\n        else:\n            f(self)\n            self.x = x\n        self.y = y\n\nclass IfConditionalAndNonConditional1:\n    def __init__(self, x: int) -> None:\n        self.x = 0\n        if x:\n            self.x = x\n\nclass IfConditionalAndNonConditional2:\n    def __init__(self, x: int) -> None:\n        # x is not considered always defined, since the second assignment may\n        # either initialize or update.\n        if x:\n            self.x = x\n        self.x = 0\n\ndef f(a) -> None: pass\n[out]\nIfAlways: [x, y, z]\nIfSometimes1: [y]\nIfSometimes2: [y]\nIfStopAnalysis1: [x]\nIfStopAnalysis2: [x]\nIfStopAnalysis3: []\nIfConditionalAndNonConditional1: [x]\nIfConditionalAndNonConditional2: []\n\n[case testAlwaysDefinedExpressions]\nfrom typing import Dict, Final, List, Set, Optional, cast\n\nimport other\n\nclass C: pass\n\nclass Collections:\n    def __init__(self, x: int) -> None:\n        self.l = [x]\n        self.d: Dict[str, str] = {}\n        self.s: Set[int] = set()\n        self.d2 = {'x': x}\n        self.s2 = {x}\n        self.l2 = [f(), None] * x\n        self.t = tuple(self.l2)\n\nclass Comparisons:\n    def __init__(self, y: int, c: C, s: str, o: Optional[str]) -> None:\n        self.n1 = y < 5\n        self.n2 = y == 5\n        self.c1 = y is c\n        self.c2 = y is not c\n        self.o1 = o is None\n        self.o2 = o is not None\n        self.s = s < 'x'\n\nclass BinaryOps:\n    def __init__(self, x: int, s: str) -> None:\n        self.a = x + 2\n        self.b = x & 2\n        self.c = x * 2\n        self.d = -x\n        self.e = 'x' + s\n        self.f = x << x\n\ng = 2\n\nclass LocalsAndGlobals:\n    def __init__(self, x: int) -> None:\n        t = x + 1\n        self.a = t - t\n        self.g = g\n\nclass Booleans:\n    def __init__(self, x: int, b: bool) -> None:\n        self.a = True\n        self.b = False\n        self.c = not b\n        self.d = b or b\n        self.e = b and b\n\nF: Final = 3\n\nclass ModuleFinal:\n    def __init__(self) -> None:\n        self.a = F\n        self.b = other.Y\n\nclass ClassFinal:\n    F: Final = 3\n\n    def __init__(self) -> None:\n        self.a = ClassFinal.F\n\nclass Literals:\n    def __init__(self) -> None:\n        self.a = 'x'\n        self.b = b'x'\n        self.c = 2.2\n\nclass ListComprehension:\n    def __init__(self, x: List[int]) -> None:\n        self.a = [i + 1 for i in x]\n\nclass Helper:\n    def __init__(self, arg) -> None:\n        self.x = 0\n\n    def foo(self, arg) -> int:\n        return 1\n\nclass AttrAccess:\n    def __init__(self, o: Helper) -> None:\n        self.x = o.x\n        o.x = o.x + 1\n        self.y = o.foo(self.x)\n        o.foo(self)\n        self.z = 1\n\nclass Construct:\n    def __init__(self) -> None:\n        self.x = Helper(1)\n        self.y = Helper(self)\n\nclass IsInstance:\n    def __init__(self, x: object) -> None:\n        if isinstance(x, str):\n            self.x = 0\n        elif isinstance(x, Helper):\n            self.x = 1\n        elif isinstance(x, (list, tuple)):\n            self.x = 2\n        else:\n            self.x = 3\n\nclass Cast:\n    def __init__(self, x: object) -> None:\n        self.x = cast(int, x)\n        self.s = cast(str, x)\n        self.c = cast(Cast, x)\n\nclass PropertyAccessGetter:\n    def __init__(self, other: PropertyAccessGetter) -> None:\n        self.x = other.p\n        self.y = 1\n        self.z = self.p\n\n    @property\n    def p(self) -> int:\n        return 0\n\nclass PropertyAccessSetter:\n    def __init__(self, other: PropertyAccessSetter) -> None:\n        other.p = 1\n        self.y = 1\n        self.z = self.p\n\n    @property\n    def p(self) -> int:\n        return 0\n\n    @p.setter\n    def p(self, x: int) -> None:\n        pass\n\ndef f() -> int:\n    return 0\n\n[file other.py]\n# Not compiled\nfrom typing import Final\n\nY: Final = 3\n\n[out]\nC: []\nCollections: [d, d2, l, l2, s, s2, t]\nComparisons: [c1, c2, n1, n2, o1, o2, s]\nBinaryOps: [a, b, c, d, e, f]\nLocalsAndGlobals: [a, g]\nBooleans: [a, b, c, d, e]\nModuleFinal: [a, b]\nClassFinal: [F, a]\nLiterals: [a, b, c]\nListComprehension: [a]\nHelper: [x]\nAttrAccess: [x, y]\nConstruct: [x]\nIsInstance: [x]\nCast: [c, s, x]\nPropertyAccessGetter: [x, y]\nPropertyAccessSetter: [y]\n\n[case testAlwaysDefinedExpressions2]\nfrom typing import List, Tuple\n\nclass C:\n    def __init__(self) -> None:\n        self.x = 0\n\nclass AttributeRef:\n    def __init__(self, c: C) -> None:\n        self.aa = c.x\n        self.bb = self.aa\n        if c is not None:\n            self.z = 0\n        self.cc = 0\n        self.dd = self.z\n\nclass ListOps:\n    def __init__(self, x: List[int], n: int) -> None:\n        self.a = len(x)\n        self.b = x[n]\n        self.c = [y + 1 for y in x]\n\nclass TupleOps:\n    def __init__(self, t: Tuple[int, str]) -> None:\n        x, y = t\n        self.x = x\n        self.y = t[0]\n        s = x, y\n        self.z = s\n\nclass IfExpr:\n    def __init__(self, x: int) -> None:\n        self.a = 1 if x < 5 else 2\n\nclass Base:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\nclass Derived1(Base):\n    def __init__(self, y: int) -> None:\n        self.aa = y\n        super().__init__(y)\n        self.bb = y\n\nclass Derived2(Base):\n    pass\n\nclass Conditionals:\n    def __init__(self, b: bool, n: int) -> None:\n        if not (n == 5 or n >= n + 1):\n            self.a = b\n        else:\n            self.a = not b\n        if b:\n            self.b = 2\n        else:\n            self.b = 4\n\n[out]\nC: [x]\nAttributeRef: [aa, bb, cc, dd]\nListOps: [a, b, c]\nTupleOps: [x, y, z]\nIfExpr: [a]\nBase: [x]\nDerived1: [aa, bb, x]\nDerived2: [x]\nConditionals: [a, b]\n\n[case testAlwaysDefinedStatements]\nfrom typing import Any, List, Optional, Iterable\n\nclass Return:\n    def __init__(self, x: int) -> None:\n        self.x = x\n        if x > 5:\n            self.y = 1\n            return\n        self.y = 2\n        self.z = x\n\nclass While:\n    def __init__(self, x: int) -> None:\n        n = 2\n        while x > 0:\n            n *=2\n            x -= 1\n        self.a = n\n        while x < 5:\n            self.b = 1\n            self.b += 1\n\nclass Try:\n    def __init__(self, x: List[int]) -> None:\n        self.a = 0\n        try:\n            self.b = x[0]\n        except:\n            self.c = x\n        self.d = 0\n        try:\n            self.e = x[0]\n        except:\n            self.e = 1\n\nclass TryFinally:\n    def __init__(self, x: List[int]) -> None:\n        self.a = 0\n        try:\n            self.b = x[0]\n        finally:\n            self.c = x\n        self.d = 0\n        try:\n            self.e = x[0]\n        finally:\n            self.e = 1\n\nclass Assert:\n    def __init__(self, x: Optional[str], y: int) -> None:\n        assert x is not None\n        assert y < 5\n        self.a = x\n\nclass For:\n    def __init__(self, it: Iterable[int]) -> None:\n        self.x = 0\n        for x in it:\n            self.x += x\n        for x in it:\n            self.y = x\n\nclass Assignment1:\n    def __init__(self, other: Assignment1) -> None:\n        self.x = 0\n        self = other  # Give up after assignment to self\n        self.y = 1\n\nclass Assignment2:\n    def __init__(self) -> None:\n        self.x = 0\n        other = self  # Give up after self is aliased\n        self.y = other.x\n\nclass With:\n    def __init__(self, x: Any) -> None:\n        self.a = 0\n        with x:\n            self.b = 1\n        self.c = 2\n\ndef f() -> None:\n    pass\n\n[out]\nReturn: [x, y]\nWhile: [a]\n-- We could infer 'e' as always defined, but this is tricky, since always defined attribute\n-- analysis must be performed earlier than exception handling transform. This would be\n-- easy to infer *after* exception handling transform.\nTry: [a, d]\n-- Again, 'e' could be always defined, but it would be a bit tricky to do it.\nTryFinally: [a, c, d]\nAssert: [a]\nFor: [x]\nAssignment1: [x]\nAssignment2: [x]\n-- TODO: Why is not 'b' included?\nWith: [a, c]\n\n[case testAlwaysDefinedAttributeDefaults]\nclass Basic:\n    x = 0\n\nclass ClassBodyAndInit:\n    x = 0\n    s = 'x'\n\n    def __init__(self, n: int) -> None:\n        self.n = 0\n\nclass AttrWithDefaultAndInit:\n    x = 0\n\n    def __init__(self, x: int) -> None:\n        self.x = x\n\nclass Base:\n    x = 0\n    y = 1\n\nclass Derived(Base):\n    y = 2\n    z = 3\n[out]\nBasic: [x]\nClassBodyAndInit: [n, s, x]\nAttrWithDefaultAndInit: [x]\nBase: [x, y]\nDerived: [x, y, z]\n\n[case testAlwaysDefinedWithInheritance]\nclass Base:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\nclass Deriv1(Base):\n    def __init__(self, x: int, y: str) -> None:\n        super().__init__(x)\n        self.y = y\n\nclass Deriv2(Base):\n    def __init__(self, x: int, y: str) -> None:\n        self.y = y\n        super().__init__(x)\n\nclass Deriv22(Deriv2):\n    def __init__(self, x: int, y: str, z: bool) -> None:\n        super().__init__(x, y)\n        self.z = False\n\nclass Deriv3(Base):\n    def __init__(self) -> None:\n        super().__init__(1)\n\nclass Deriv4(Base):\n    def __init__(self) -> None:\n        self.y = 1\n        self.x = 2\n\ndef f(a): pass\n\nclass BaseUnsafe:\n    def __init__(self, x: int, y: int) -> None:\n        self.x = x\n        f(self)  # Unknown function\n        self.y = y\n\nclass DerivUnsafe(BaseUnsafe):\n    def __init__(self, z: int, zz: int) -> None:\n        self.z = z\n        super().__init__(1, 2)  # Calls unknown function\n        self.zz = zz\n\nclass BaseWithDefault:\n    x = 1\n\n    def __init__(self) -> None:\n        self.y = 1\n\nclass DerivedWithDefault(BaseWithDefault):\n    def __init__(self) -> None:\n        super().__init__()\n        self.z = 1\n\nclass AlwaysDefinedInBase:\n    def __init__(self) -> None:\n        self.x = 1\n        self.y = 1\n\nclass UndefinedInDerived(AlwaysDefinedInBase):\n    def __init__(self, x: bool) -> None:\n        self.x = 1\n        if x:\n            self.y = 2\n\nclass UndefinedInDerived2(UndefinedInDerived):\n    def __init__(self, x: bool):\n        if x:\n            self.y = 2\n[out]\nBase: [x]\nDeriv1: [x, y]\nDeriv2: [x, y]\nDeriv22: [x, y, z]\nDeriv3: [x]\nDeriv4: [x, y]\nBaseUnsafe: [x]\nDerivUnsafe: [x, z]\nBaseWithDefault: [x, y]\nDerivedWithDefault: [x, y, z]\nAlwaysDefinedInBase: []\nUndefinedInDerived: []\nUndefinedInDerived2: []\n\n[case testAlwaysDefinedWithInheritance2]\nfrom mypy_extensions import trait, mypyc_attr\n\nfrom interpreted import PythonBase\n\nclass BasePartiallyDefined:\n    def __init__(self, x: int) -> None:\n        self.a = 0\n        if x:\n            self.x = x\n\nclass Derived1(BasePartiallyDefined):\n    def __init__(self, x: int) -> None:\n        super().__init__(x)\n        self.y = x\n\nclass BaseUndefined:\n    x: int\n\nclass DerivedAlwaysDefined(BaseUndefined):\n    def __init__(self) -> None:\n        super().__init__()\n        self.z = 0\n        self.x = 2\n\n@trait\nclass MyTrait:\n    def f(self) -> None: pass\n\nclass SimpleTraitImpl(MyTrait):\n    def __init__(self) -> None:\n        super().__init__()\n        self.x = 0\n\n@trait\nclass TraitWithAttr:\n    x: int\n    y: str\n\nclass TraitWithAttrImpl(TraitWithAttr):\n    def __init__(self) -> None:\n        self.y = 'x'\n\n@trait\nclass TraitWithAttr2:\n    z: int\n\nclass TraitWithAttrImpl2(TraitWithAttr, TraitWithAttr2):\n    def __init__(self) -> None:\n        self.y = 'x'\n        self.z = 2\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass BaseWithGeneralSubclassing:\n    x = 0\n    y: int\n    def __init__(self, s: str) -> None:\n        self.s = s\n\nclass Derived2(BaseWithGeneralSubclassing):\n    def __init__(self) -> None:\n        super().__init__('x')\n        self.z = 0\n\nclass SubclassPythonclass(PythonBase):\n    def __init__(self) -> None:\n        self.y = 1\n\nclass BaseWithSometimesDefined:\n    def __init__(self, b: bool) -> None:\n        if b:\n            self.x = 0\n\nclass Derived3(BaseWithSometimesDefined):\n    def __init__(self, b: bool) -> None:\n        super().__init__(b)\n        self.x = 1\n\n[file interpreted.py]\nclass PythonBase:\n    def __init__(self) -> None:\n        self.x = 0\n\n[out]\nBasePartiallyDefined: [a]\nDerived1: [a, y]\nBaseUndefined: []\nDerivedAlwaysDefined: [x, z]\nMyTrait: []\nSimpleTraitImpl: [x]\nTraitWithAttr: []\nTraitWithAttrImpl: [y]\nTraitWithAttr2: []\nTraitWithAttrImpl2: [y, z]\nBaseWithGeneralSubclassing: []\n-- TODO: 's' could also be always defined\nDerived2: [x, z]\n-- Always defined attribute analysis is turned off when inheriting a non-native class.\nSubclassPythonclass: []\nBaseWithSometimesDefined: []\n-- TODO: 'x' could also be always defined, but it is a bit tricky to support\nDerived3: []\n\n[case testAlwaysDefinedWithNesting]\nclass NestedFunc:\n    def __init__(self) -> None:\n        self.x = 0\n        def f() -> None:\n            self.y = 0\n        f()\n        self.z = 1\n[out]\n-- TODO: Support nested functions.\nNestedFunc: []\nf___init___NestedFunc_obj: []\n\n[case testAlwaysDefinedWithVecSetItem]\nfrom librt.vecs import vec\n\nclass C:\n    def __init__(self, v: vec[C]) -> None:\n        self.v = v\n        self.v[0] = self\n[out]\nC: [v]\n"
  },
  {
    "path": "mypyc/test-data/analysis.test",
    "content": "-- Test cases for data flow analysis.\n\n[case testSimple_MaybeDefined]\ndef f(a: int) -> None:\n    x = 1\n    if x == a:\n        y = 1\n    else:\n        z = 1\n[out]\ndef f(a):\n    a, x :: int\n    r0 :: bit\n    y, z :: int\nL0:\n    x = 2\n    r0 = int_eq x, a\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    y = 2\n    goto L3\nL2:\n    z = 2\nL3:\n    return 1\n(0, 0)   {a}                     {a, x}\n(0, 1)   {a, x}                  {a, x}\n(0, 2)   {a, x}                  {a, x}\n(1, 0)   {a, x}                  {a, x, y}\n(1, 1)   {a, x, y}               {a, x, y}\n(2, 0)   {a, x}                  {a, x, z}\n(2, 1)   {a, x, z}               {a, x, z}\n(3, 0)   {a, x, y, z}            {a, x, y, z}\n\n[case testSimple_Liveness]\ndef f(a: int) -> int:\n    x = 1\n    if x == 1:\n        return a\n    else:\n        return x\n[out]\ndef f(a):\n    a, x :: int\n    r0 :: bit\nL0:\n    x = 2\n    r0 = int_eq x, 2\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return a\nL2:\n    return x\nL3:\n    unreachable\n(0, 0)   {a}                     {a, x}\n(0, 1)   {a, x}                  {a, r0, x}\n(0, 2)   {a, r0, x}              {a, x}\n(1, 0)   {a}                     {}\n(2, 0)   {x}                     {}\n(3, 0)   {}                      {}\n\n[case testSpecial_Liveness]\ndef f() -> int:\n    x = 1\n    y = 1\n    x = 2\n    return x\n[out]\ndef f():\n    x, y :: int\nL0:\n    x = 2\n    y = 2\n    x = 4\n    return x\n(0, 0)   {}                      {}\n(0, 1)   {}                      {}\n(0, 2)   {}                      {x}\n(0, 3)   {x}                     {}\n\n[case testSpecial2_Liveness]\ndef f(a: int) -> int:\n    a = 1\n    a = 2\n    a = 3\n    return a\n[out]\ndef f(a):\n    a :: int\nL0:\n    a = 2\n    a = 4\n    a = 6\n    return a\n(0, 0)   {}                      {}\n(0, 1)   {}                      {}\n(0, 2)   {}                      {a}\n(0, 3)   {a}                     {}\n\n[case testSimple_MustDefined]\ndef f(a: int) -> None:\n    if a == 1:\n        y = 1\n        x = 2\n    else:\n        x = 2\n[out]\ndef f(a):\n    a :: int\n    r0 :: bit\n    y, x :: int\nL0:\n    r0 = int_eq a, 2\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    y = 2\n    x = 4\n    goto L3\nL2:\n    x = 4\nL3:\n    return 1\n(0, 0)   {a}                     {a}\n(0, 1)   {a}                     {a}\n(1, 0)   {a}                     {a, y}\n(1, 1)   {a, y}                  {a, x, y}\n(1, 2)   {a, x, y}               {a, x, y}\n(2, 0)   {a}                     {a, x}\n(2, 1)   {a, x}                  {a, x}\n(3, 0)   {a, x}                  {a, x}\n\n[case testTwoArgs_MustDefined]\ndef f(x: int, y: int) -> int:\n    return x\n[out]\ndef f(x, y):\n    x, y :: int\nL0:\n    return x\n(0, 0)   {x, y}                  {x, y}\n\n[case testLoop_MustDefined]\ndef f(n: int) -> None:\n    while n < 5:\n        n = n + 1\n        m = n\n[out]\ndef f(n):\n    n :: int\n    r0 :: bit\n    r1, m :: int\nL0:\nL1:\n    r0 = int_lt n, 10\n    if r0 goto L2 else goto L3 :: bool\nL2:\n    r1 = CPyTagged_Add(n, 2)\n    n = r1\n    m = n\n    goto L1\nL3:\n    return 1\n(0, 0)   {n}                     {n}\n(1, 0)   {n}                     {n}\n(1, 1)   {n}                     {n}\n(2, 0)   {n}                     {n}\n(2, 1)   {n}                     {n}\n(2, 2)   {n}                     {m, n}\n(2, 3)   {m, n}                  {m, n}\n(3, 0)   {n}                     {n}\n\n[case testMultiPass_Liveness]\ndef f(n: int) -> None:\n    x = 1\n    y = 1\n    while n < 1:\n        n = y\n        while n < 2:\n            n = 1\n            n = x\n[out]\ndef f(n):\n    n, x, y :: int\n    r0, r1 :: bit\nL0:\n    x = 2\n    y = 2\nL1:\n    r0 = int_lt n, 2\n    if r0 goto L2 else goto L6 :: bool\nL2:\n    n = y\nL3:\n    r1 = int_lt n, 4\n    if r1 goto L4 else goto L5 :: bool\nL4:\n    n = 2\n    n = x\n    goto L3\nL5:\n    goto L1\nL6:\n    return 1\n(0, 0)   {n}                     {n, x}\n(0, 1)   {n, x}                  {n, x, y}\n(0, 2)   {n, x, y}               {n, x, y}\n(1, 0)   {n, x, y}               {r0, x, y}\n(1, 1)   {r0, x, y}              {x, y}\n(2, 0)   {x, y}                  {n, x, y}\n(2, 1)   {n, x, y}               {n, x, y}\n(3, 0)   {n, x, y}               {n, r1, x, y}\n(3, 1)   {n, r1, x, y}           {n, x, y}\n(4, 0)   {x, y}                  {x, y}\n(4, 1)   {x, y}                  {n, x, y}\n(4, 2)   {n, x, y}               {n, x, y}\n(5, 0)   {n, x, y}               {n, x, y}\n(6, 0)   {}                      {}\n\n[case testCall_Liveness]\ndef f(x: int) -> int:\n    a = f(1)\n    return f(a) + a\n[out]\ndef f(x):\n    x, r0, a, r1, r2, r3 :: int\nL0:\n    r0 = f(2)\n    if is_error(r0) goto L3 (error at f:2) else goto L1\nL1:\n    a = r0\n    r1 = f(a)\n    if is_error(r1) goto L3 (error at f:3) else goto L2\nL2:\n    r2 = CPyTagged_Add(r1, a)\n    return r2\nL3:\n    r3 = <error> :: int\n    return r3\n(0, 0)   {}                      {r0}\n(0, 1)   {r0}                    {r0}\n(1, 0)   {r0}                    {a}\n(1, 1)   {a}                     {a, r1}\n(1, 2)   {a, r1}                 {a, r1}\n(2, 0)   {a, r1}                 {r2}\n(2, 1)   {r2}                    {}\n(3, 0)   {}                      {r3}\n(3, 1)   {r3}                    {}\n\n[case testLoop_MaybeDefined]\ndef f(a: int) -> None:\n    while a < a:\n        while a < a:\n            y = a\n        x = a\n[out]\ndef f(a):\n    a :: int\n    r0, r1 :: bit\n    y, x :: int\nL0:\nL1:\n    r0 = int_lt a, a\n    if r0 goto L2 else goto L6 :: bool\nL2:\nL3:\n    r1 = int_lt a, a\n    if r1 goto L4 else goto L5 :: bool\nL4:\n    y = a\n    goto L3\nL5:\n    x = a\n    goto L1\nL6:\n    return 1\n(0, 0)   {a}                     {a}\n(1, 0)   {a, x, y}               {a, x, y}\n(1, 1)   {a, x, y}               {a, x, y}\n(2, 0)   {a, x, y}               {a, x, y}\n(3, 0)   {a, x, y}               {a, x, y}\n(3, 1)   {a, x, y}               {a, x, y}\n(4, 0)   {a, x, y}               {a, x, y}\n(4, 1)   {a, x, y}               {a, x, y}\n(5, 0)   {a, x, y}               {a, x, y}\n(5, 1)   {a, x, y}               {a, x, y}\n(6, 0)   {a, x, y}               {a, x, y}\n\n[case testTrivial_BorrowedArgument]\ndef f(a: int, b: int) -> int:\n    return b\n[out]\ndef f(a, b):\n    a, b :: int\nL0:\n    return b\n(0, 0)   {a, b}                  {a, b}\n\n[case testSimple_BorrowedArgument]\ndef f(a: int) -> int:\n    b = a\n    a = 1\n    return a\n[out]\ndef f(a):\n    a, b :: int\nL0:\n    b = a\n    a = 2\n    return a\n(0, 0)   {a}                     {a}\n(0, 1)   {a}                     {}\n(0, 2)   {}                      {}\n\n[case testConditional_BorrowedArgument]\ndef f(a: int) -> int:\n    if a == a:\n        x = 2\n        a = 1\n    else:\n        x = 1\n    return x\n[out]\ndef f(a):\n    a :: int\n    r0 :: bit\n    x :: int\nL0:\n    r0 = int_eq a, a\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    x = 4\n    a = 2\n    goto L3\nL2:\n    x = 2\nL3:\n    return x\n(0, 0)   {a}                     {a}\n(0, 1)   {a}                     {a}\n(1, 0)   {a}                     {a}\n(1, 1)   {a}                     {}\n(1, 2)   {}                      {}\n(2, 0)   {a}                     {a}\n(2, 1)   {a}                     {a}\n(3, 0)   {}                      {}\n\n[case testLoop_BorrowedArgument]\ndef f(a: int) -> int:\n    sum = 0\n    i = 0\n    while i <= a:\n        sum = sum + i\n        i = i + 1\n    return sum\n[out]\ndef f(a):\n    a, sum, i :: int\n    r0 :: bit\n    r1, r2 :: int\nL0:\n    sum = 0\n    i = 0\nL1:\n    r0 = int_le i, a\n    if r0 goto L2 else goto L3 :: bool\nL2:\n    r1 = CPyTagged_Add(sum, i)\n    sum = r1\n    r2 = CPyTagged_Add(i, 2)\n    i = r2\n    goto L1\nL3:\n    return sum\n(0, 0)   {a}                     {a}\n(0, 1)   {a}                     {a}\n(0, 2)   {a}                     {a}\n(1, 0)   {a}                     {a}\n(1, 1)   {a}                     {a}\n(2, 0)   {a}                     {a}\n(2, 1)   {a}                     {a}\n(2, 2)   {a}                     {a}\n(2, 3)   {a}                     {a}\n(2, 4)   {a}                     {a}\n(3, 0)   {a}                     {a}\n\n[case testError]\ndef f(x: List[int]) -> None: pass # E: Name \"List\" is not defined \\\n                                  # N: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import List\")\n\n[case testExceptUndefined_Liveness]\ndef lol(x: object) -> int:\n    try:\n        st = id(x)\n    except Exception:\n        return -1\n    return st + 1\n[out]\ndef lol(x):\n    x :: object\n    r0, st :: int\n    r1 :: tuple[object, object, object]\n    r2 :: object\n    r3 :: str\n    r4 :: object\n    r5, r6 :: bit\n    r7, r8 :: int\nL0:\nL1:\n    r0 = CPyTagged_Id(x)\n    st = r0\n    goto L10\nL2:\n    r1 = CPy_CatchError()\n    r2 = builtins :: module\n    r3 = 'Exception'\n    r4 = CPyObject_GetAttr(r2, r3)\n    if is_error(r4) goto L8 (error at lol:4) else goto L3\nL3:\n    r5 = CPy_ExceptionMatches(r4)\n    if r5 goto L4 else goto L5 :: bool\nL4:\n    CPy_RestoreExcInfo(r1)\n    return -2\nL5:\n    CPy_Reraise()\n    if not 0 goto L8 else goto L6 :: bool\nL6:\n    unreachable\nL7:\n    CPy_RestoreExcInfo(r1)\n    goto L10\nL8:\n    CPy_RestoreExcInfo(r1)\n    r6 = CPy_KeepPropagating()\n    if not r6 goto L11 else goto L9 :: bool\nL9:\n    unreachable\nL10:\n    r7 = CPyTagged_Add(st, 2)\n    return r7\nL11:\n    r8 = <error> :: int\n    return r8\n(0, 0)   {x}                     {x}\n(1, 0)   {x}                     {r0}\n(1, 1)   {r0}                    {st}\n(1, 2)   {st}                    {st}\n(2, 0)   {}                      {r1}\n(2, 1)   {r1}                    {r1, r2}\n(2, 2)   {r1, r2}                {r1, r2, r3}\n(2, 3)   {r1, r2, r3}            {r1, r4}\n(2, 4)   {r1, r4}                {r1, r4}\n(3, 0)   {r1, r4}                {r1, r5}\n(3, 1)   {r1, r5}                {r1}\n(4, 0)   {r1}                    {}\n(4, 1)   {}                      {}\n(5, 0)   {r1}                    {r1}\n(5, 1)   {r1}                    {r1}\n(6, 0)   {}                      {}\n(7, 0)   {r1, st}                {st}\n(7, 1)   {st}                    {st}\n(8, 0)   {r1}                    {}\n(8, 1)   {}                      {r6}\n(8, 2)   {r6}                    {}\n(9, 0)   {}                      {}\n(10, 0)  {st}                    {r7}\n(10, 1)  {r7}                    {}\n(11, 0)  {}                      {r8}\n(11, 1)  {r8}                    {}\n"
  },
  {
    "path": "mypyc/test-data/annotate-basic.test",
    "content": "[case testAnnotateNonNativeAttribute]\nfrom typing import Any\n\ndef f1(x):\n    return x.foo  # A: Get non-native attribute \"foo\".\n\ndef f2(x: Any) -> object:\n    return x.foo  # A: Get non-native attribute \"foo\".\n\ndef f3(x):\n    x.bar = 1  # A: Set non-native attribute \"bar\".\n\nclass C:\n    foo: int\n\n    def method(self) -> int:\n        return self.foo\n\ndef good1(x: C) -> int:\n    return x.foo\n\n[case testAnnotateMethod]\nclass C:\n    def method(self, x):\n        return x + \"y\"  # A: Generic \"+\" operation.\n\n[case testAnnotateGenericBinaryOperations]\ndef generic_add(x):\n    return x + 1  # A: Generic \"+\" operation.\n\ndef generic_sub(x):\n    return x - 1  # A: Generic \"-\" operation.\n\ndef generic_mul(x):\n    return x * 1  # A: Generic \"*\" operation.\n\ndef generic_div(x):\n    return x / 1  # A: Generic \"/\" operation.\n\ndef generic_floor_div(x):\n    return x // 1  # A: Generic \"//\" operation.\n\ndef generic_unary_plus(x):\n    return +x  # A: Generic unary \"+\" operation.\n\ndef generic_unary_minus(x):\n    return -x  # A: Generic unary \"-\" operation.\n\ndef native_int_ops(x: int, y: int) -> int:\n    a = x + 1 - y\n    return x * a // y\n\n[case testAnnotateGenericBitwiseOperations]\ndef generic_and(x):\n    return x & 1  # A: Generic \"&\" operation.\n\ndef generic_or(x):\n    return x | 1  # A: Generic \"|\" operation.\n\ndef generic_xor(x):\n    return x ^ 1  # A: Generic \"^\" operation.\n\ndef generic_left_shift(x):\n    return x << 1  # A: Generic \"<<\" operation.\n\ndef generic_right_shift(x):\n    return x >> 1  # A: Generic \">>\" operation.\n\ndef generic_invert(x):\n    return ~x  # A: Generic \"~\" operation.\n\ndef native_int_ops(x: int, y: int) -> int:\n    a = (x & 1) << y\n    return (x | a) >> (y ^ 1)\n\n[case testAnnotateGenericComparisonOperations]\ndef generic_eq(x, y):\n    return x == y  # A: Generic comparison operation.\n\ndef generic_ne(x, y):\n    return x != y  # A: Generic comparison operation.\n\ndef generic_lt(x, y):\n    return x < y  # A: Generic comparison operation.\n\ndef generic_le(x, y):\n    return x <= y  # A: Generic comparison operation.\n\ndef generic_gt(x, y):\n    return x > y  # A: Generic comparison operation.\n\ndef generic_ge(x, y):\n    return x >= y  # A: Generic comparison operation.\n\ndef int_comparisons(x: int, y: int) -> int:\n    if x == y:\n        return 0\n    if x < y:\n        return 1\n    if x > y:\n        return 2\n    return 3\n\n[case testAnnotateTwoOperationsOnLine]\ndef f(x):\n    return x.foo + 1  # A: Get non-native attribute \"foo\". Generic \"+\" operation.\n\n[case testAnnotateNonNativeMethod]\nfrom typing import Any\n\ndef f1(x):\n    return x.foo()  # A: Call non-native method \"foo\" (it may be defined in a non-native class, or decorated).\n\ndef f2(x: Any) -> None:\n    x.foo(1)  # A: Call non-native method \"foo\" (it may be defined in a non-native class, or decorated).\n    x.foo(a=1)  # A: Call non-native method \"foo\" (it may be defined in a non-native class, or decorated).\n    t = (1, 'x')\n    x.foo(*t)  # A: Get non-native attribute \"foo\". Generic call operation.\n    d = {\"a\": 1}\n    x.foo(*d)  # A: Get non-native attribute \"foo\". Generic call operation.\n\nclass C:\n    def foo(self) -> int:\n        return 0\n\ndef g(c: C) -> int:\n    return c.foo()\n\n[case testAnnotateGlobalVariableAccess]\nfrom typing import Final\nimport nonnative\n\nx = 0\ny: Final = 0\n\ndef read() -> int:\n    return x  # A: Access global \"x\" through namespace dictionary (hint: access is faster if you can make it Final).\n\ndef assign(a: int) -> None:\n    global x\n    x = a  # A: Access global \"x\" through namespace dictionary (hint: access is faster if you can make it Final).\n\ndef read_final() -> int:\n    return y\n\ndef read_nonnative() -> int:\n    return nonnative.z  # A: Get non-native attribute \"z\".\n\n[file nonnative.py]\nz = 2\n\n[case testAnnotateNestedFunction]\ndef f1() -> None:\n    def g() -> None:  # A: A nested function object is allocated each time statement is executed. A module-level function would be faster.\n        pass\n\n    g()\n\ndef f2() -> int:\n    l = lambda: 1  # A: A new object is allocated for lambda each time it is evaluated. A module-level function would be faster.\n    return l()\n\n[case testAnnotateGetSetItem]\nfrom typing import List, Dict\n\ndef f1(x, y):\n    return x[y]  # A: Generic indexing operation.\n\ndef f2(x, y, z):\n    x[y] = z  # A: Generic indexed assignment.\n\ndef list_get_item(x: List[int], y: int) -> int:\n    return x[y]\n\ndef list_set_item(x: List[int], y: int) -> None:\n    x[y] = 5\n\ndef dict_get_item(d: Dict[str, str]) -> str:\n    return d['x']\n\ndef dict_set_item(d: Dict[str, str]) -> None:\n    d['x'] = 'y'\n\n[case testAnnotateStrMethods]\ndef startswith(x: str) -> bool:\n    return x.startswith('foo')\n\ndef islower(x: str) -> bool:\n    return x.islower()  # A: Call non-native method \"islower\" (it may be defined in a non-native class, or decorated).\n\n[case testAnnotateSpecificStdlibFeatures]\nimport functools\nimport itertools\nfrom functools import partial\nfrom itertools import chain, groupby, islice\n\ndef f(x: int, y: int) -> None: pass\n\ndef use_partial1() -> None:\n    p = partial(f, 1)  # A: \"functools.partial\" is inefficient in compiled code.\n    p(2)\n\ndef use_partial2() -> None:\n    p = functools.partial(f, 1)  # A: \"functools.partial\" is inefficient in compiled code.\n    p(2)\n\ndef use_chain1() -> None:\n    for x in chain([1, 3], [4, 5]):  # A: \"itertools.chain\" is inefficient in compiled code (hint: replace with for loops).\n        pass\n\ndef use_chain2() -> None:\n    for x in itertools.chain([1, 3], [4, 5]):  # A: \"itertools.chain\" is inefficient in compiled code (hint: replace with for loops).\n        pass\n\ndef use_groupby1() -> None:\n    for a, b in groupby([('A', 'B')]):  # A: \"itertools.groupby\" is inefficient in compiled code.\n        pass\n\ndef use_groupby2() -> None:\n    for a, b in itertools.groupby([('A', 'B')]):  # A: \"itertools.groupby\" is inefficient in compiled code.\n        pass\n\ndef use_islice() -> None:\n    for x in islice([1, 2, 3], 1, 2):  # A: \"itertools.islice\" is inefficient in compiled code (hint: replace with for loop over index range).\n        pass\n\n[case testAnnotateGenericForLoop]\nfrom typing import Iterable, Sequence, Iterator, List\n\ndef f1(a):\n    for x in a:  # A: For loop uses generic operations (iterable has type \"Any\").\n        pass\n\ndef f2(a: Iterable[str]) -> None:\n    for x in a:  # A: For loop uses generic operations (iterable has the abstract type \"typing.Iterable\").\n        pass\n\ndef f3(a: Sequence[str]) -> None:\n    for x in a:  # A: For loop uses generic operations (iterable has the abstract type \"typing.Sequence\").\n        pass\n\ndef f4(a: Iterator[str]) -> None:\n    for x in a:  # A: For loop uses generic operations (iterable has the abstract type \"typing.Iterator\").\n        pass\n\ndef good1(a: List[str]) -> None:\n    for x in a:\n        pass\n\nclass C:\n    def __iter__(self) -> Iterator[str]:\n        assert False\n\ndef good2(a: List[str]) -> None:\n    for x in a:\n        pass\n\n[case testAnnotateGenericComprehensionOrGenerator]\nfrom typing import List, Iterable\n\ndef f1(a):\n    return [x for x in a]  # A: Comprehension or generator uses generic operations (iterable has type \"Any\").\n\ndef f2(a: Iterable[int]):\n    return {x for x in a}  # A: Comprehension or generator uses generic operations (iterable has the abstract type \"typing.Iterable\").\n\ndef f3(a):\n    return {x: 1 for x in a}  # A: Comprehension uses generic operations (iterable has type \"Any\").\n\ndef f4(a):\n    return (x for x in a)  # A: Comprehension or generator uses generic operations (iterable has type \"Any\").\n\ndef good1(a: List[int]) -> List[int]:\n    return [x + 1 for x in a]\n\n[case testAnnotateIsinstance]\nfrom typing import Protocol, runtime_checkable, Union\n\n@runtime_checkable\nclass P(Protocol):\n    def foo(self) -> None: ...\n\nclass C: pass\n\nclass D(C):\n    def bar(self) -> None: pass\n\ndef bad1(x: object) -> bool:\n    return isinstance(x, P)  # A: Expensive isinstance() check against protocol \"P\".\n\ndef bad2(x: object) -> bool:\n    return isinstance(x, (str, P))  # A: Expensive isinstance() check against protocol \"P\".\n\ndef good1(x: C) -> bool:\n    if isinstance(x, D):\n        x.bar()\n    return isinstance(x, D)\n\ndef good2(x: Union[int, str]) -> int:\n    if isinstance(x, int):\n        return x + 1\n    else:\n        return int(x + \"1\")\n[typing fixtures/typing-full.pyi]\n\n[case testAnnotateDeepcopy]\nfrom typing import Any\nimport copy\n\ndef f(x: Any) -> Any:\n    return copy.deepcopy(x)  # A: \"copy.deepcopy\" tends to be slow. Make a shallow copy if possible.\n\n[case testAnnotateContextManager]\nfrom typing import Iterator\nfrom contextlib import contextmanager\n\n@contextmanager\ndef slow_ctx_manager() -> Iterator[None]:\n    yield\n\nclass FastCtxManager:\n    def __enter__(self) -> None: pass\n    def __exit__(self, a, b, c) -> None: pass\n\ndef f1(x) -> None:\n    with slow_ctx_manager():  # A: \"slow_ctx_manager\" uses @contextmanager, which is slow in compiled code. Use a native class with \"__enter__\" and \"__exit__\" methods instead.\n        x.foo  # A: Get non-native attribute \"foo\".\n\ndef f2(x) -> None:\n    with FastCtxManager():\n        x.foo  # A: Get non-native attribute \"foo\".\n\n[case testAnnotateAvoidNoiseAtTopLevel]\nfrom typing import Final\n\nclass C(object):\n    x = \"s\"\n    y: Final = 1\n\nx = \"s\"\ny: Final = 1\n\ndef f1() -> None:\n    x = object  # A: Get non-native attribute \"object\".\n\n[case testAnnotateCreateNonNativeInstance]\nfrom typing import NamedTuple\nfrom dataclasses import dataclass\n\nfrom nonnative import C\n\ndef f1() -> None:\n    c = C()  # A: Creating an instance of non-native class \"C\" is slow.\n    c.foo()  # A: Call non-native method \"foo\" (it may be defined in a non-native class, or decorated).\n\nclass NT(NamedTuple):\n    x: int\n    y: str\n\ndef f2() -> int:\n    o = NT(1, \"x\")  # A: Creating an instance of non-native class \"NT\" is slow.\n    return o.x\n\ndef f3() -> int:\n    o = NT(x=1, y=\"x\")  # A: Creating an instance of non-native class \"NT\" is slow.\n    a, b = o\n    return a\n\n@dataclass\nclass D:\n    x: int\n\ndef f4() -> int:\n    o = D(1)  # A: Class \"D\" is only partially native, and constructing an instance is slow.\n    return o.x\n\nclass Nat:\n    x: int\n\nclass Deriv(Nat):\n    def __init__(self, y: int) -> None:\n        self.y = y\n\ndef good1() -> int:\n    n = Nat()\n    d = Deriv(y=1)\n    return n.x + d.x + d.y\n\n[file nonnative.py]\nclass C:\n    def foo(self) -> None: pass\n\n[case testAnnotateGetAttrAndSetAttrBuiltins]\ndef f1(x, s: str):\n    return getattr(\"x\", s)  # A: Dynamic attribute lookup.\n\ndef f2(x, s: str):\n    setattr(x, s, None)  # A: Dynamic attribute set.\n\n[case testAnnotateSpecialAssignments]\nfrom typing import TypeVar, NamedTuple, List, TypedDict, NewType\n\n# Even though these are slow, we don't complain about them since there is generally\n# no better way (and at module top level these are very unlikely to be bottlenecks)\nA = List[int]\nT = TypeVar(\"T\", bound=List[int])\nNT = NamedTuple(\"NT\", [(\"x\", List[int])])\nTD = TypedDict(\"TD\", {\"x\": List[int]})\nNew = NewType(\"New\", List[int])\n[typing fixtures/typing-full.pyi]\n\n[case testAnnotateCallDecoratedNativeFunctionOrMethod]\nfrom typing import TypeVar, Callable, Any\n\nF = TypeVar(\"F\", bound=Callable[..., Any])\n\ndef mydeco(f: F) -> F:\n    return f\n\n@mydeco\ndef d(x: int) -> int:\n    return x\n\ndef f1() -> int:\n    return d(1)  # A: Calling a decorated function (\"d\") is inefficient, even if it's native.\n\nclass C:\n    @mydeco\n    def d(self) -> None:\n        pass\n\n\ndef f2() -> None:\n    c = C()\n    c.d()  # A: Call non-native method \"d\" (it may be defined in a non-native class, or decorated).\n\n[case testAnnotateCallDifferentKindsOfMethods]\nfrom abc import ABC, abstractmethod\n\nclass C:\n    @staticmethod\n    def s() -> None: ...\n\n    @classmethod\n    def c(cls) -> None: ...\n\n    @property\n    def p(self) -> int:\n        return 0\n\n    @property\n    def p2(self) -> int:\n        return 0\n\n    @p2.setter\n    def p2(self, x: int) -> None:\n        pass\n\ndef f1() -> int:\n    c = C()\n    c.s()\n    c.c()\n    c.p2 = 1\n    return c.p + c.p2\n\nclass A(ABC):\n    @abstractmethod\n    def m(self) -> int:\n        raise NotImplementedError  # A: Get non-native attribute \"NotImplementedError\".\n\nclass D(A):\n    def m(self) -> int:\n        return 1\n\ndef f2() -> int:\n    d = D()\n    return d.m()\n"
  },
  {
    "path": "mypyc/test-data/capsule-deps.test",
    "content": "[case testNoDeps]\ndef f() -> None:\n    pass\n[out]\nNo deps\n\n[case testStringsNoCapsuleDepWithoutExperimental]\n# Test case missing _experimental suffix -> no deps\nfrom librt.strings import StringWriter\n\ndef f() -> None:\n    StringWriter()\n[out]\nNo deps\n\n[case testStringsCapsuleDep_experimental]\nfrom librt.strings import StringWriter\n\ndef f() -> None:\n    StringWriter()\n[out]\nCapsule(name='librt.strings')\n\n[case testStringsCapsuleDepFromParamType_experimental]\nfrom librt.strings import StringWriter\n\ndef f(s: StringWriter) -> None:\n    pass\n[out]\nCapsule(name='librt.strings')\n\n[case testStringsCapsuleDepFromReturnType_experimental]\nfrom librt.strings import StringWriter\n\ndef f() -> StringWriter:\n    assert False\n[out]\nCapsule(name='librt.strings')\n\n[case testStringsCapsuleDepFromUnion_experimental]\nfrom typing import Union\n\nfrom librt.strings import StringWriter\n\ndef f(s: Union[StringWriter, str]) -> None:\n    pass\n[out]\nCapsule(name='librt.strings')\n\n[case testStringsCapsuleDepFromTuple_experimental]\nfrom librt.strings import StringWriter\n\ndef f(s: tuple[int, StringWriter]) -> None:\n    pass\n[out]\nCapsule(name='librt.strings')\n\n[case testExtraFileDep_experimental]\nfrom librt.strings import StringWriter\n\ndef f(s: StringWriter) -> int:\n    return s[0]\n[out]\nCapsule(name='librt.strings')\nSourceDep(path='stringwriter_extra_ops.c')\n\n[case testMultipleCapsuleDeps1_experimental]\nfrom librt.strings import StringWriter\nfrom librt.base64 import b64encode\n\ndef f() -> None:\n    StringWriter()\n\ndef g() -> bytes:\n    return b64encode(b'foo')\n[out]\nCapsule(name='librt.base64')\nCapsule(name='librt.strings')\n\n[case testMultipleCapsuleDeps2_experimental]\nfrom librt.strings import StringWriter\nfrom librt.base64 import b64encode\n\ndef f() -> bytes:\n    StringWriter()\n    return b64encode(b'foo')\n[out]\nCapsule(name='librt.base64')\nCapsule(name='librt.strings')\n\n[case testVecCapsuleDepInFunction_experimental]\nfrom librt.vecs import vec\n\ndef f() -> None:\n    vec[str]()\n[out]\nCapsule(name='librt.vecs')\n\n[case testVecCapsuleDepInMethod_experimental]\nfrom librt.vecs import vec\n\nclass C:\n    def m(self) -> None:\n        vec[str]()\n[out]\nCapsule(name='librt.vecs')\n\n[case testVecCapsuleDepAtTopLevel_experimental]\nfrom librt.vecs import vec\n\nvec[str]()\n[out]\nCapsule(name='librt.vecs')\n\n[case testVecCapsuleDepInAttributeType_experimental]\nfrom librt.vecs import vec\n\nclass C:\n    v: vec[str]\n[out]\nCapsule(name='librt.vecs')\n"
  },
  {
    "path": "mypyc/test-data/commandline.test",
    "content": "-- Test cases for invoking mypyc on the command line\n--\n-- These are slow -- do not add test cases unless you have a very good reason to do so.\n\n[case testCompileMypyc]\n# cmd: a.py b.py p/__init__.py p/q.py\nimport os.path\nimport p\nimport p.q\nimport a\nimport b\nprint('<main>', b.g(a.A()))\ntry:\n    a.f('')\nexcept TypeError:\n    pass\nelse:\n    assert False\nfor x in [a, b, p, p.q]:\n    assert os.path.splitext(x.__file__)[1] != '.py'\n[file z.py]\n\n[file a.py]\nimport b\nimport c\nfrom p import s\nfrom typing import NamedTuple\n\nprint('<a>', ord('A') == 65)  # Test full builtins\n\nclass A:\n    def __init__(self) -> None:\n        self.x = 4\n\ndef f(x: int) -> b.B:\n    return b.B(x)\n\nclass B:\n    def __init__(self, x: int, y: str) -> None:\n        self.x = x\n\nprint('<a>', f(5).x)\nprint('<c>', c.foo())\nassert s.bar(10) == 20\n\nclass NT(NamedTuple):\n    x: int\n\nprint(NT(2))\n\n[file b.py]\nimport a\nimport p.q\n\nclass B:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\ndef g(z: 'a.A') -> int:\n    return p.q.foo(z.x)\n\nprint('<b>', 'here')\n\n[file c.py]\ndef foo() -> int:\n    return 10\n\n[file p/__init__.py]\n\n[file p/q.py]\nimport p.r\ndef foo(x: int) -> int:\n    return x*p.r.foo(x)\n\n[file p/r.py]\ndef foo(x: int) -> int:\n    return x\n\n[file p/s.py]\ndef bar(x: int) -> int:\n    return x*2\n\n[out]\n<b> here\n<a> True\n<a> 5\n<c> 10\nNT(x=2)\n<main> 16\n\n-- This test is here so we can turn it on when we get nervous about\n-- this case, but is disabled for speed reasons.\n[case testCompileMypycOne-skip]\n# cmd: a.py\nimport os.path\nimport a\nassert os.path.splitext(a.__file__)[1] != '.py'\nassert a.f(10) == 100\n\n[file a.py]\ndef f(x: int) -> int:\n    return x*x\n\n[case testErrorOutput1]\n# cmd: test.py\n\n[file test.py]\nfrom functools import singledispatch\nfrom mypy_extensions import trait\nfrom typing import Any\n\ndef decorator(x: Any) -> Any:\n    return x\n\nclass NeverMetaclass(type):  # E: Inheriting from most builtin types is unimplemented \\\n                             # N: Potential workaround: @mypy_extensions.mypyc_attr(native_class=False) \\\n                             # N: https://mypyc.readthedocs.io/en/stable/native_classes.html#defining-non-native-classes\n    pass\n\nclass Concrete1:\n    pass\n\n@trait\nclass Trait1:\n    pass\n\nclass Concrete2:\n    pass\n\n@decorator\nclass NonExt(Concrete1):  # E: Non-extension classes may not inherit from extension classes\n    pass\n\nclass NopeMultipleInheritanceAndBadOrder3(Trait1, Concrete1, Concrete2):  # E: Non-trait base must appear first in parent list\n    pass\n\nclass NopeBadOrder(Trait1, Concrete2):  # E: Non-trait base must appear first in parent list\n    pass\n\nclass Foo:\n    pass\n\n@singledispatch\ndef a(arg) -> None:\n    pass\n\n@decorator # E: Calling decorator after registering function not supported\n@a.register\ndef g(arg: int) -> None:\n    pass\n\n@a.register\n@decorator\ndef h(arg: str) -> None:\n    pass\n\n@decorator\n@decorator # E: Calling decorator after registering function not supported\n@a.register\ndef i(arg: Foo) -> None:\n    pass\n\n[case testErrorOutput2]\n# cmd: test.py\n\n[file test.py]\nfrom typing import Final, List, Any, AsyncIterable\nfrom mypy_extensions import trait, mypyc_attr\n\ndef busted(b: bool) -> None:\n    for i in range(1, 10, 0):  # E: range() step can't be zero\n        try:\n            if i == 5:\n                break  # E: break inside try/finally block is unimplemented\n            elif i == 4:\n                continue  # E: continue inside try/finally block is unimplemented\n        finally:\n            print('oops')\n\nprint(sum([1,2,3]))\n\nx = [1,2]\n\nclass Foo:\n    a, b = (10, 20)  # E: Only assignment to variables is supported in class bodies\n    x[0] = 10  # E: Only assignment to variables is supported in class bodies\n    lol = 20\n    l = [10]  # W: Unsupported default attribute value\n    c = d = 50  # E: Multiple assignment in class bodies not supported\n\n    if 1+1 == 2:  # E: Unsupported statement in class body\n        x = 10\n\nFoo.lol = 50  # E: Only class variables defined as ClassVar can be assigned to\n\ndef decorator(x: Any) -> Any:\n    return x\n\nclass Concrete1:\n    pass\n\n@trait\nclass PureTrait:\n    pass\n\n@trait\nclass Trait1:\n    pass\n\nclass Concrete2:\n    pass\n\n@trait\nclass Trait2(Concrete2):\n    pass\n\nclass NopeMultipleInheritance(Concrete1, Concrete2):  # E: Multiple inheritance is not supported (except for traits)\n    pass\n\nclass NopeMultipleInheritanceAndBadOrder(Concrete1, Trait1, Concrete2):  # E: Multiple inheritance is not supported (except for traits)\n    pass\n\nclass NopeMultipleInheritanceAndBadOrder2(Concrete1, Concrete2, Trait1):  # E: Multiple inheritance is not supported (except for traits)\n    pass\n\n@decorator\nclass NonExt2:\n    @property  # E: Property setters not supported in non-extension classes\n    def test(self) -> int:\n        return 0\n\n    @test.setter\n    def test(self, x: int) -> None:\n        pass\n\niterator_warning = (i+1 for i in range(10))  # W: Treating generator comprehension as list\n\n# But we don't want warnings for these cases:\ntup = tuple(i+1 for i in range(10))\na_str = \" \".join(str(i) for i in range(10))\nwtvr = next(i for i in range(10) if i == 5)\n\nd1 = {1: 2}\n\n# Since PR 18180, the following pattern should pose no problems anymore:\ndef f(l: List[object]) -> None:\n    x = None\n    for i in l:\n        if x is None:\n            x = i\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass AllowInterp1(Concrete1):  # E: Base class \"test.Concrete1\" does not allow interpreted subclasses\n    pass\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass AllowInterp2(PureTrait):  # E: Base class \"test.PureTrait\" does not allow interpreted subclasses\n    pass\n\nasync def async_generators() -> AsyncIterable[int]:\n    yield 1  # E: async generators are unimplemented\n\n[case testOnlyWarningOutput]\n# cmd: test.py\n\n[file test.py]\nnames = (str(v) for v in [1, 2, 3])  # W: Treating generator comprehension as list\n\n[case testSubPackage]\n# cmd: pkg/sub/foo.py\nfrom pkg.sub import foo\n\n[file pkg/__init__.py]\n\n[file pkg/sub/__init__.py]\nprint(\"importing...\")\nfrom . import foo\nprint(\"done\")\n\n[file pkg/sub/foo.py]\nprint(\"imported foo\")\n\n[out]\nimporting...\nimported foo\ndone\n\n[case testImportFromInitPy]\n# cmd: foo.py\nimport foo\n\n[file pkg2/__init__.py]\n\n[file pkg2/mod2.py]\nclass A:\n    class B:\n        pass\n\n[file pkg1/__init__.py]\nfrom pkg2.mod2 import A\n\n[file foo.py]\nimport pkg1\nfrom typing import TypedDict\n\nclass Eggs(TypedDict):\n    obj1: pkg1.A.B\n\nprint(type(Eggs(obj1=pkg1.A.B())[\"obj1\"]).__name__)\nprint(type(Eggs(obj1=pkg1.A.B())[\"obj1\"]).__module__)\n\n[out]\nB\npkg2.mod2\n\n[case testStrictBytesRequired]\n# cmd: --no-strict-bytes a.py\n\n[file a.py]\ndef f(b: bytes) -> None: pass\nf(bytearray())\n\n[out]\na.py: error: Option --strict-bytes cannot be disabled when using mypyc\n"
  },
  {
    "path": "mypyc/test-data/driver/driver.py",
    "content": "\"\"\"Default driver for run tests (run-*.test).\n\nThis imports the 'native' module (containing the compiled test cases)\nand calls each function starting with test_, and reports any\nexceptions as failures.\n\nTest cases can provide a custom driver.py that overrides this file.\n\"\"\"\n\nimport sys\nimport native\nimport asyncio\nimport inspect\n\nevloop = asyncio.new_event_loop()\n\nfailures = []\ntests_run = 0\n\nfor name in dir(native):\n    if name.startswith('test_'):\n        test_func = getattr(native, name)\n        tests_run += 1\n        try:\n            if inspect.iscoroutinefunction(test_func):\n                evloop.run_until_complete(test_func())\n            else:\n                test_func()\n        except Exception as e:\n            failures.append((name, sys.exc_info()))\n\nif failures:\n    from traceback import print_exception, format_tb\n    import re\n\n    def extract_line(tb):\n        formatted = '\\n'.join(format_tb(tb))\n        m = re.search('File \"(native|driver).py\", line ([0-9]+), in (test_|<module>)', formatted)\n        if m is None:\n            return \"0\"\n        return m.group(1)\n\n    # Sort failures by line number of test function.\n    failures = sorted(failures, key=lambda e: extract_line(e[1][2]))\n\n    # If there are multiple failures, print stack traces of all but the final failure.\n    for name, e in failures[:-1]:\n        print(f'<< {name} >>')\n        sys.stdout.flush()\n        print_exception(*e)\n        print()\n        sys.stdout.flush()\n\n    # Raise exception for the last failure. Test runner will show the traceback.\n    print(f'<< {failures[-1][0]} >>')\n    sys.stdout.flush()\n    raise failures[-1][1][1]\n\nassert tests_run > 0, 'Default test driver did not find any functions prefixed \"test_\" to run.'\n"
  },
  {
    "path": "mypyc/test-data/exceptions-freq.test",
    "content": "-- Test cases for basic block execution frequency analysis.\n--\n-- These test cases are using exception transform test machinery for convenience.\n--\n-- NOTE: These must all have the _freq suffix\n\n[case testSimpleError_freq]\nfrom typing import List\ndef f(x: List[int]) -> int:\n    return x[0]\n[out]\ndef f(x):\n    x :: list\n    r0 :: object\n    r1, r2 :: int\nL0:\n    r0 = CPyList_GetItemShort(x, 0)\n    if is_error(r0) goto L3 (error at f:3) else goto L1\nL1:\n    r1 = unbox(int, r0)\n    dec_ref r0\n    if is_error(r1) goto L3 (error at f:3) else goto L2\nL2:\n    return r1\nL3:\n    r2 = <error> :: int\n    return r2\nhot blocks: [0, 1, 2]\n\n[case testHotBranch_freq]\nfrom typing import List\ndef f(x: bool) -> None:\n    if x:\n        y = 1\n    else:\n        y = 2\n[out]\ndef f(x):\n    x :: bool\n    y :: int\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    y = 2\n    dec_ref y :: int\n    goto L3\nL2:\n    y = 4\n    dec_ref y :: int\nL3:\n    return 1\nhot blocks: [0, 1, 2, 3]\n\n[case testGoto_freq]\nfrom typing import List\ndef f(x: bool) -> int:\n    if x:\n        y = 1\n    else:\n        return 2\n    return y\n[out]\ndef f(x):\n    x :: bool\n    y :: int\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    y = 2\n    goto L3\nL2:\n    return 4\nL3:\n    return y\nhot blocks: [0, 1, 2, 3]\n\n[case testFalseOnError_freq]\nfrom typing import List\ndef f(x: List[int]) -> None:\n    x[0] = 1\n[out]\ndef f(x):\n    x :: list\n    r0 :: object\n    r1 :: bit\n    r2 :: None\nL0:\n    r0 = object 1\n    inc_ref r0\n    r1 = CPyList_SetItem(x, 0, r0)\n    if not r1 goto L2 (error at f:3) else goto L1 :: bool\nL1:\n    return 1\nL2:\n    r2 = <error> :: None\n    return r2\nhot blocks: [0, 1]\n\n[case testRareBranch_freq]\nfrom typing import Final\n\nx: Final = str()\n\ndef f() -> str:\n    return x\n[out]\ndef f():\n    r0 :: str\n    r1 :: bool\n    r2 :: str\nL0:\n    r0 = __main__.x :: static\n    if is_error(r0) goto L1 else goto L3\nL1:\n    r1 = raise NameError('value for final name \"x\" was not set')\n    if not r1 goto L4 (error at f:6) else goto L2 :: bool\nL2:\n    unreachable\nL3:\n    inc_ref r0\n    return r0\nL4:\n    r2 = <error> :: str\n    return r2\nhot blocks: [0, 3]\n"
  },
  {
    "path": "mypyc/test-data/exceptions.test",
    "content": "-- Test cases for exception handling insertion transform.\n--\n-- The result includes refcount handling since these two transforms interact.\n\n[case testListGetAndUnboxError]\nfrom typing import List\ndef f(x: List[int]) -> int:\n    return x[0]\n[out]\ndef f(x):\n    x :: list\n    r0 :: object\n    r1, r2 :: int\nL0:\n    r0 = CPyList_GetItemShort(x, 0)\n    if is_error(r0) goto L3 (error at f:3) else goto L1\nL1:\n    r1 = unbox(int, r0)\n    dec_ref r0\n    if is_error(r1) goto L3 (error at f:3) else goto L2\nL2:\n    return r1\nL3:\n    r2 = <error> :: int\n    return r2\n\n[case testListAppendAndSetItemError]\nfrom typing import List\ndef f(x: List[int], y: int, z: int) -> None:\n    x.append(y)\n    x[y] = z\n[out]\ndef f(x, y, z):\n    x :: list\n    y, z :: int\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: object\n    r4 :: bit\n    r5 :: None\nL0:\n    inc_ref y :: int\n    r0 = box(int, y)\n    r1 = PyList_Append(x, r0)\n    dec_ref r0\n    r2 = r1 >= 0 :: signed\n    if not r2 goto L3 (error at f:3) else goto L1 :: bool\nL1:\n    inc_ref z :: int\n    r3 = box(int, z)\n    r4 = CPyList_SetItem(x, y, r3)\n    if not r4 goto L3 (error at f:4) else goto L2 :: bool\nL2:\n    return 1\nL3:\n    r5 = <error> :: None\n    return r5\n\n[case testOptionalHandling]\nfrom typing import Optional\n\nclass A: pass\n\ndef f(x: Optional[A]) -> int:\n    if x is None:\n        return 1\n    if x is not None:\n        return 2\n    return 3\n[out]\ndef f(x):\n    x :: union[__main__.A, None]\n    r0 :: object\n    r1 :: bit\n    r2 :: __main__.A\n    r3 :: object\n    r4 :: bit\n    r5 :: int\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    r2 = borrow cast(__main__.A, x)\n    if is_error(r2) goto L6 (error at f:8) else goto L3\nL3:\n    r3 = load_address _Py_NoneStruct\n    r4 = r2 != r3\n    if r4 goto L4 else goto L5 :: bool\nL4:\n    return 4\nL5:\n    return 6\nL6:\n    r5 = <error> :: int\n    return r5\n\n[case testListSum]\nfrom typing import List\ndef sum(a: List[int], l: int) -> int:\n    sum = 0\n    i = 0\n    while i < l:\n        sum = sum + a[i]\n        i = i + 1\n    return sum\n[out]\ndef sum(a, l):\n    a :: list\n    l, sum, i :: int\n    r0 :: bit\n    r1 :: object\n    r2, r3, r4, r5 :: int\nL0:\n    sum = 0\n    i = 0\nL1:\n    r0 = int_lt i, l\n    if r0 goto L2 else goto L7 :: bool\nL2:\n    r1 = CPyList_GetItemBorrow(a, i)\n    if is_error(r1) goto L8 (error at sum:6) else goto L3\nL3:\n    r2 = unbox(int, r1)\n    if is_error(r2) goto L8 (error at sum:6) else goto L4\nL4:\n    r3 = CPyTagged_Add(sum, r2)\n    dec_ref sum :: int\n    dec_ref r2 :: int\n    sum = r3\n    r4 = CPyTagged_Add(i, 2)\n    dec_ref i :: int\n    i = r4\n    goto L1\nL5:\n    return sum\nL6:\n    r5 = <error> :: int\n    return r5\nL7:\n    dec_ref i :: int\n    goto L5\nL8:\n    dec_ref sum :: int\n    dec_ref i :: int\n    goto L6\n\n[case testTryExcept]\ndef g() -> None:\n    try:\n        object()\n    except:\n        print(\"weeee\")\n[out]\ndef g():\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: tuple[object, object, object]\n    r5 :: str\n    r6 :: object\n    r7 :: str\n    r8 :: object\n    r9 :: object[1]\n    r10 :: object_ptr\n    r11 :: object\n    r12 :: bit\n    r13 :: None\nL0:\nL1:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    if is_error(r2) goto L3 (error at g:3) else goto L2\nL2:\n    r3 = PyObject_Vectorcall(r2, 0, 0, 0)\n    dec_ref r2\n    if is_error(r3) goto L3 (error at g:3) else goto L10\nL3:\n    r4 = CPy_CatchError()\n    r5 = 'weeee'\n    r6 = builtins :: module\n    r7 = 'print'\n    r8 = CPyObject_GetAttr(r6, r7)\n    if is_error(r8) goto L6 (error at g:5) else goto L4\nL4:\n    r9 = [r5]\n    r10 = load_address r9\n    r11 = PyObject_Vectorcall(r8, r10, 1, 0)\n    dec_ref r8\n    if is_error(r11) goto L6 (error at g:5) else goto L11\nL5:\n    CPy_RestoreExcInfo(r4)\n    dec_ref r4\n    goto L8\nL6:\n    CPy_RestoreExcInfo(r4)\n    dec_ref r4\n    r12 = CPy_KeepPropagating()\n    if not r12 goto L9 else goto L7 :: bool\nL7:\n    unreachable\nL8:\n    return 1\nL9:\n    r13 = <error> :: None\n    return r13\nL10:\n    dec_ref r3\n    goto L8\nL11:\n    dec_ref r11\n    goto L5\n\n[case testGenopsTryFinally]\ndef a() -> str:\n    try:\n        print()\n        return 'hi'\n    finally:\n        print('goodbye!')\n[out]\ndef a():\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4, r5 :: str\n    r6, r7 :: tuple[object, object, object]\n    r8 :: str\n    r9 :: tuple[object, object, object]\n    r10 :: str\n    r11 :: object\n    r12 :: str\n    r13 :: object\n    r14 :: object[1]\n    r15 :: object_ptr\n    r16 :: object\n    r17 :: bit\n    r18 :: str\nL0:\nL1:\n    r0 = builtins :: module\n    r1 = 'print'\n    r2 = CPyObject_GetAttr(r0, r1)\n    if is_error(r2) goto L5 (error at a:3) else goto L2\nL2:\n    r3 = PyObject_Vectorcall(r2, 0, 0, 0)\n    dec_ref r2\n    if is_error(r3) goto L5 (error at a:3) else goto L19\nL3:\n    r4 = 'hi'\n    inc_ref r4\n    r5 = r4\nL4:\n    r6 = <error> :: tuple[object, object, object]\n    r7 = r6\n    goto L6\nL5:\n    r8 = <error> :: str\n    r5 = r8\n    r9 = CPy_CatchError()\n    r7 = r9\nL6:\n    r10 = 'goodbye!'\n    r11 = builtins :: module\n    r12 = 'print'\n    r13 = CPyObject_GetAttr(r11, r12)\n    if is_error(r13) goto L20 (error at a:6) else goto L7\nL7:\n    r14 = [r10]\n    r15 = load_address r14\n    r16 = PyObject_Vectorcall(r13, r15, 1, 0)\n    dec_ref r13\n    if is_error(r16) goto L20 (error at a:6) else goto L21\nL8:\n    if is_error(r7) goto L11 else goto L22\nL9:\n    CPy_Reraise()\n    if not 0 goto L13 else goto L23 :: bool\nL10:\n    unreachable\nL11:\n    if is_error(r5) goto L17 else goto L12\nL12:\n    return r5\nL13:\n    if is_error(r7) goto L15 else goto L14\nL14:\n    CPy_RestoreExcInfo(r7)\n    xdec_ref r7\nL15:\n    r17 = CPy_KeepPropagating()\n    if not r17 goto L18 else goto L16 :: bool\nL16:\n    unreachable\nL17:\n    unreachable\nL18:\n    r18 = <error> :: str\n    return r18\nL19:\n    dec_ref r3\n    goto L3\nL20:\n    xdec_ref r5\n    goto L13\nL21:\n    dec_ref r16\n    goto L8\nL22:\n    xdec_ref r5\n    goto L9\nL23:\n    xdec_ref r7\n    goto L10\n\n[case testDocstring1]\ndef lol() -> None:\n    \"\"\"Hello\"\"\"\n    pass\n[out]\ndef lol():\nL0:\n    return 1\n\n[case testExceptUndefined1]\nfrom typing import Any\ndef lol(x: Any) -> object:\n    try:\n        st = x.foo\n    except:\n        return ''\n    # No uninit check should be generated, since the exception branch always returns\n    return st\n[out]\ndef lol(x):\n    x :: object\n    r0 :: str\n    r1, st :: object\n    r2 :: tuple[object, object, object]\n    r3 :: str\nL0:\nL1:\n    r0 = 'foo'\n    r1 = CPyObject_GetAttr(x, r0)\n    if is_error(r1) goto L3 (error at lol:4) else goto L2\nL2:\n    st = r1\n    goto L4\nL3:\n    r2 = CPy_CatchError()\n    r3 = ''\n    CPy_RestoreExcInfo(r2)\n    dec_ref r2\n    inc_ref r3\n    return r3\nL4:\n    return st\n\n[case testExceptUndefined2]\nfrom typing import Any\ndef lol(x: Any) -> object:\n    try:\n        a = x.foo\n        b = x.bar\n    except:\n        pass\n    # uninit checks are needed, since the exception can skip initializing the vars\n    return a + b\n[out]\ndef lol(x):\n    x, r0, a, r1, b :: object\n    r2 :: str\n    r3 :: object\n    r4 :: str\n    r5 :: object\n    r6 :: tuple[object, object, object]\n    r7, r8 :: bool\n    r9, r10 :: object\nL0:\n    r0 = <error> :: object\n    a = r0\n    r1 = <error> :: object\n    b = r1\nL1:\n    r2 = 'foo'\n    r3 = CPyObject_GetAttr(x, r2)\n    if is_error(r3) goto L4 (error at lol:4) else goto L15\nL2:\n    a = r3\n    r4 = 'bar'\n    r5 = CPyObject_GetAttr(x, r4)\n    if is_error(r5) goto L4 (error at lol:5) else goto L16\nL3:\n    b = r5\n    goto L6\nL4:\n    r6 = CPy_CatchError()\nL5:\n    CPy_RestoreExcInfo(r6)\n    dec_ref r6\nL6:\n    if is_error(a) goto L17 else goto L9\nL7:\n    r7 = raise UnboundLocalError('local variable \"a\" referenced before assignment')\n    if not r7 goto L14 (error at lol:9) else goto L8 :: bool\nL8:\n    unreachable\nL9:\n    if is_error(b) goto L18 else goto L12\nL10:\n    r8 = raise UnboundLocalError('local variable \"b\" referenced before assignment')\n    if not r8 goto L14 (error at lol:9) else goto L11 :: bool\nL11:\n    unreachable\nL12:\n    r9 = PyNumber_Add(a, b)\n    xdec_ref a\n    xdec_ref b\n    if is_error(r9) goto L14 (error at lol:9) else goto L13\nL13:\n    return r9\nL14:\n    r10 = <error> :: object\n    return r10\nL15:\n    xdec_ref a\n    goto L2\nL16:\n    xdec_ref b\n    goto L3\nL17:\n    xdec_ref b\n    goto L7\nL18:\n    xdec_ref a\n    goto L10\n\n[case testMaybeUninitVarExc]\ndef f(b: bool) -> None:\n    u = 'a'\n    while b:\n        v = 'b'\n        if v is not u:\n            break\n    print(v)\n[out]\ndef f(b):\n    b :: bool\n    r0, v, r1, u, r2 :: str\n    r3, r4 :: bit\n    r5 :: object\n    r6 :: str\n    r7 :: object\n    r8 :: bool\n    r9 :: object[1]\n    r10 :: object_ptr\n    r11 :: object\n    r12 :: bool\n    r13 :: None\nL0:\n    r0 = <error> :: str\n    v = r0\n    r1 = 'a'\n    inc_ref r1\n    u = r1\nL1:\n    if b goto L13 else goto L14 :: bool\nL2:\n    r2 = 'b'\n    inc_ref r2\n    v = r2\n    r3 = v == u\n    r4 = r3 ^ 1\n    if r4 goto L14 else goto L1 :: bool\nL3:\n    r5 = builtins :: module\n    r6 = 'print'\n    r7 = CPyObject_GetAttr(r5, r6)\n    if is_error(r7) goto L15 (error at f:7) else goto L4\nL4:\n    if is_error(v) goto L16 else goto L7\nL5:\n    r8 = raise UnboundLocalError('local variable \"v\" referenced before assignment')\n    if not r8 goto L12 (error at f:7) else goto L6 :: bool\nL6:\n    unreachable\nL7:\n    r9 = [v]\n    r10 = load_address r9\n    r11 = PyObject_Vectorcall(r7, r10, 1, 0)\n    dec_ref r7\n    if is_error(r11) goto L15 (error at f:7) else goto L17\nL8:\n    if is_error(v) goto L9 else goto L11\nL9:\n    r12 = raise UnboundLocalError('local variable \"v\" referenced before assignment')\n    if not r12 goto L12 (error at f:7) else goto L10 :: bool\nL10:\n    unreachable\nL11:\n    xdec_ref v\n    return 1\nL12:\n    r13 = <error> :: None\n    return r13\nL13:\n    xdec_ref v\n    goto L2\nL14:\n    dec_ref u\n    goto L3\nL15:\n    xdec_ref v\n    goto L12\nL16:\n    dec_ref r7\n    goto L5\nL17:\n    dec_ref r11\n    goto L8\n\n[case testExceptionWithOverlappingErrorValue]\nfrom mypy_extensions import i64\n\ndef f() -> i64:\n    return 0\n\ndef g() -> i64:\n    return f()\n[out]\ndef f():\nL0:\n    return 0\ndef g():\n    r0 :: i64\n    r1 :: bit\n    r2 :: object\n    r3 :: i64\nL0:\n    r0 = f()\n    r1 = r0 == -113\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    return r0\nL2:\n    r2 = PyErr_Occurred()\n    if not is_error(r2) goto L3 (error at g:7) else goto L1\nL3:\n    r3 = <error> :: i64\n    return r3\n\n[case testExceptionWithNativeAttributeGetAndSet]\nclass C:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\ndef foo(c: C, x: int) -> None:\n    c.x = x - c.x\n[out]\ndef C.__init__(self, x):\n    self :: __main__.C\n    x :: int\nL0:\n    inc_ref x :: int\n    self.x = x\n    return 1\ndef foo(c, x):\n    c :: __main__.C\n    x, r0, r1 :: int\n    r2 :: bool\nL0:\n    r0 = borrow c.x\n    r1 = CPyTagged_Subtract(x, r0)\n    c.x = r1\n    return 1\n\n[case testExceptionWithOverlappingFloatErrorValue]\ndef f() -> float:\n    return 0.0\n\ndef g() -> float:\n    return f()\n[out]\ndef f():\nL0:\n    return 0.0\ndef g():\n    r0 :: float\n    r1 :: bit\n    r2 :: object\n    r3 :: float\nL0:\n    r0 = f()\n    r1 = r0 == -113.0\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    return r0\nL2:\n    r2 = PyErr_Occurred()\n    if not is_error(r2) goto L3 (error at g:5) else goto L1\nL3:\n    r3 = <error> :: float\n    return r3\n\n[case testExceptionWithLowLevelIntAttribute]\nfrom mypy_extensions import i32, i64\n\nclass C:\n    def __init__(self, x: i32, y: i64) -> None:\n        self.x = x\n        self.y = y\n\ndef f(c: C) -> None:\n    c.x\n    c.y\n[out]\ndef C.__init__(self, x, y):\n    self :: __main__.C\n    x :: i32\n    y :: i64\nL0:\n    self.x = x\n    self.y = y\n    return 1\ndef f(c):\n    c :: __main__.C\n    r0 :: i32\n    r1 :: i64\nL0:\n    r0 = c.x\n    r1 = c.y\n    return 1\n\n[case testConditionallyUndefinedI64]\nfrom mypy_extensions import i64\n\ndef f(x: i64) -> i64:\n    if x:\n        y: i64 = 2\n    return y\n[out]\ndef f(x):\n    x, r0, y :: i64\n    __locals_bitmap0 :: u32\n    r1 :: bit\n    r2, r3 :: u32\n    r4 :: bit\n    r5 :: bool\n    r6 :: i64\nL0:\n    r0 = <error> :: i64\n    y = r0\n    __locals_bitmap0 = 0\n    r1 = x != 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    y = 2\n    r2 = __locals_bitmap0 | 1\n    __locals_bitmap0 = r2\nL2:\n    r3 = __locals_bitmap0 & 1\n    r4 = r3 == 0\n    if r4 goto L3 else goto L5 :: bool\nL3:\n    r5 = raise UnboundLocalError('local variable \"y\" referenced before assignment')\n    if not r5 goto L6 (error at f:6) else goto L4 :: bool\nL4:\n    unreachable\nL5:\n    return y\nL6:\n    r6 = <error> :: i64\n    return r6\n\n[case testExceptionWithFloatAttribute]\nclass C:\n    def __init__(self, x: float, y: float) -> None:\n        self.x = x\n        if x:\n            self.y = y\n\ndef f(c: C) -> float:\n    return c.x + c.y\n[out]\ndef C.__init__(self, x, y):\n    self :: __main__.C\n    x, y :: float\n    r0 :: bit\nL0:\n    self.x = x\n    r0 = x != 0.0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    self.y = y\nL2:\n    return 1\ndef f(c):\n    c :: __main__.C\n    r0, r1 :: float\n    r2 :: bit\n    r3 :: float\n    r4 :: object\n    r5 :: float\nL0:\n    r0 = c.x\n    r1 = c.y\n    r2 = r1 == -113.0\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = r0 + r1\n    return r3\nL2:\n    r4 = PyErr_Occurred()\n    if not is_error(r4) goto L3 (error at f:8) else goto L1\nL3:\n    r5 = <error> :: float\n    return r5\n\n[case testVecI64Remove]\nfrom librt.vecs import vec, remove\nfrom mypy_extensions import i64\n\ndef f(v: vec[i64], i: i64, n: i64) -> None:\n    v = remove(v, n)\n[out]\ndef f(v, i, n):\n    v :: vec[i64]\n    i, n :: i64\n    r0 :: vec[i64]\n    r1 :: None\nL0:\n    inc_ref v\n    r0 = VecI64Api.remove(v, n)\n    if is_error(r0) goto L2 (error at f:5) else goto L1\nL1:\n    v = r0\n    dec_ref v\n    return 1\nL2:\n    r1 = <error> :: None\n    return r1\n"
  },
  {
    "path": "mypyc/test-data/fixtures/ir.py",
    "content": "# These builtins stubs are used implicitly in AST to IR generation\n# test cases.\n\nimport _typeshed\nfrom typing import (\n    Self, TypeVar, Generic, List, Iterator, Iterable, Dict, Optional, Tuple, Any, Set,\n    overload, Mapping, Union, Callable, Sequence, FrozenSet, Protocol\n)\n\n_T = TypeVar('_T')\nT_co = TypeVar('T_co', covariant=True)\nT_contra = TypeVar('T_contra', contravariant=True)\n_S = TypeVar('_S')\n_K = TypeVar('_K') # for keys in mapping\n_V = TypeVar('_V') # for values in mapping\n\nclass __SupportsAbs(Protocol[T_co]):\n    def __abs__(self) -> T_co: pass\n\nclass __SupportsDivMod(Protocol[T_contra, T_co]):\n    def __divmod__(self, other: T_contra) -> T_co: ...\n\nclass __SupportsRDivMod(Protocol[T_contra, T_co]):\n    def __rdivmod__(self, other: T_contra) -> T_co: ...\n\n_M = TypeVar(\"_M\", contravariant=True)\n\nclass __SupportsPow2(Protocol[T_contra, T_co]):\n    def __pow__(self, other: T_contra) -> T_co: ...\n\nclass __SupportsPow3NoneOnly(Protocol[T_contra, T_co]):\n    def __pow__(self, other: T_contra, modulo: None = ...) -> T_co: ...\n\nclass __SupportsPow3(Protocol[T_contra, _M, T_co]):\n    def __pow__(self, other: T_contra, modulo: _M) -> T_co: ...\n\n__SupportsSomeKindOfPow = Union[\n    __SupportsPow2[Any, Any], __SupportsPow3NoneOnly[Any, Any] | __SupportsPow3[Any, Any, Any]\n]\n\nclass object:\n    __class__: type\n    def __new__(cls) -> Self: pass\n    def __init__(self) -> None: pass\n    def __init_subclass__(cls, **kwargs: object) -> None: pass\n    def __eq__(self, x: object) -> bool: pass\n    def __ne__(self, x: object) -> bool: pass\n    def __str__(self) -> str: pass\n    def __setattr__(self, k: str, v: object) -> None: pass\n    def __delattr__(self, k: str) -> None: pass\n\nclass type:\n    def __init__(self, o: object) -> None: ...\n    def __or__(self, o: object) -> Any: ...\n    def __new__(cls, *args: object) -> Any: ...\n    __name__ : str\n    __annotations__: Dict[str, Any]\n\nclass ellipsis: pass\n\n# Primitive types are special in generated code.\n\nclass int:\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x: object, base: int = 10) -> None: pass\n    def __add__(self, n: int) -> int: pass\n    def __sub__(self, n: int) -> int: pass\n    def __mul__(self, n: int) -> int: pass\n    def __pow__(self, n: int, modulo: Optional[int] = None) -> int: pass\n    def __floordiv__(self, x: int) -> int: pass\n    def __truediv__(self, x: float) -> float: pass\n    def __mod__(self, x: int) -> int: pass\n    def __divmod__(self, x: float) -> Tuple[float, float]: pass\n    def __neg__(self) -> int: pass\n    def __pos__(self) -> int: pass\n    def __abs__(self) -> int: pass\n    def __invert__(self) -> int: pass\n    def __and__(self, n: int) -> int: pass\n    def __or__(self, n: int) -> int: pass\n    def __xor__(self, n: int) -> int: pass\n    def __lshift__(self, x: int) -> int: pass\n    def __rshift__(self, x: int) -> int: pass\n    def __eq__(self, n: object) -> bool: pass\n    def __ne__(self, n: object) -> bool: pass\n    def __lt__(self, n: int) -> bool: pass\n    def __gt__(self, n: int) -> bool: pass\n    def __le__(self, n: int) -> bool: pass\n    def __ge__(self, n: int) -> bool: pass\n    def to_bytes(self, length: int, order: str, *, signed: bool = False) -> bytes: pass\n    def bit_length(self) -> int: pass\n\nclass str:\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x: object) -> None: pass\n    def __add__(self, x: str) -> str: pass\n    def __mul__(self, x: int) -> str: pass\n    def __rmul__(self, x: int) -> str: pass\n    def __eq__(self, x: object) -> bool: pass\n    def __ne__(self, x: object) -> bool: pass\n    def __lt__(self, x: str) -> bool: ...\n    def __le__(self, x: str) -> bool: ...\n    def __gt__(self, x: str) -> bool: ...\n    def __ge__(self, x: str) -> bool: ...\n    @overload\n    def __getitem__(self, i: int) -> str: pass\n    @overload\n    def __getitem__(self, i: slice) -> str: pass\n    def __contains__(self, item: str) -> bool: pass\n    def __iter__(self) -> Iterator[str]: ...\n    def find(self, sub: str, start: Optional[int] = None, end: Optional[int] = None, /) -> int: ...\n    def rfind(self, sub: str, start: Optional[int] = None, end: Optional[int] = None, /) -> int: ...\n    def split(self, sep: Optional[str] = None, maxsplit: int = -1) -> List[str]: pass\n    def rsplit(self, sep: Optional[str] = None, maxsplit: int = -1) -> List[str]: pass\n    def splitlines(self, keepends: bool = False) -> List[str]: ...\n    def strip (self, item: Optional[str] = None) -> str: pass\n    def lstrip(self, item: Optional[str] = None) -> str: pass\n    def rstrip(self, item: Optional[str] = None) -> str: pass\n    def join(self, x: Iterable[str]) -> str: pass\n    def format(self, *args: Any, **kwargs: Any) -> str: ...\n    def lower(self) -> str: ...\n    def upper(self) -> str: ...\n    def startswith(self, x: Union[str, Tuple[str, ...]], start: int=..., end: int=...) -> bool: ...\n    def endswith(self, x: Union[str, Tuple[str, ...]], start: int=..., end: int=...) -> bool: ...\n    def replace(self, old: str, new: str, maxcount: int=...) -> str: ...\n    def encode(self, encoding: str=..., errors: str=...) -> bytes: ...\n    def partition(self, sep: str, /) -> Tuple[str, str, str]: ...\n    def rpartition(self, sep: str, /) -> Tuple[str, str, str]: ...\n    def removeprefix(self, prefix: str, /) -> str: ...\n    def removesuffix(self, suffix: str, /) -> str: ...\n    def islower(self) -> bool: ...\n    def count(self, substr: str, start: Optional[int] = None, end: Optional[int] = None) -> int: pass\n    def isspace(self) -> bool: ...\n    def isalnum(self) -> bool: ...\n    def isdigit(self) -> bool: ...\n\nclass float:\n    def __init__(self, x: object) -> None: pass\n    def __add__(self, n: float) -> float: pass\n    def __radd__(self, n: float) -> float: pass\n    def __sub__(self, n: float) -> float: pass\n    def __rsub__(self, n: float) -> float: pass\n    def __mul__(self, n: float) -> float: pass\n    def __truediv__(self, n: float) -> float: pass\n    def __floordiv__(self, n: float) -> float: pass\n    def __mod__(self, n: float) -> float: pass\n    def __pow__(self, n: float) -> float: pass\n    def __neg__(self) -> float: pass\n    def __pos__(self) -> float: pass\n    def __abs__(self) -> float: pass\n    def __invert__(self) -> float: pass\n    def __eq__(self, x: object) -> bool: pass\n    def __ne__(self, x: object) -> bool: pass\n    def __lt__(self, x: float) -> bool: ...\n    def __le__(self, x: float) -> bool: ...\n    def __gt__(self, x: float) -> bool: ...\n    def __ge__(self, x: float) -> bool: ...\n\nclass complex:\n    def __init__(self, x: object, y: object = None) -> None: pass\n    def __add__(self, n: complex) -> complex: pass\n    def __radd__(self, n: float) -> complex: pass\n    def __sub__(self, n: complex) -> complex: pass\n    def __rsub__(self, n: float) -> complex: pass\n    def __mul__(self, n: complex) -> complex: pass\n    def __truediv__(self, n: complex) -> complex: pass\n    def __neg__(self) -> complex: pass\n\nclass bytes:\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, x: object) -> None: ...\n    def __add__(self, x: bytes | bytearray) -> bytes: ...\n    def __mul__(self, x: int) -> bytes: ...\n    def __rmul__(self, x: int) -> bytes: ...\n    def __eq__(self, x: object) -> bool: ...\n    def __ne__(self, x: object) -> bool: ...\n    @overload\n    def __getitem__(self, i: int) -> int: ...\n    @overload\n    def __getitem__(self, i: slice) -> bytes: ...\n    def join(self, x: Iterable[object]) -> bytes: ...\n    def decode(self, encoding: str=..., errors: str=...) -> str: ...\n    def translate(self, t: bytes | bytearray) -> bytes: ...\n    def startswith(self, t: bytes | bytearray) -> bool: ...\n    def endswith(self, t: bytes | bytearray) -> bool: ...\n    def __iter__(self) -> Iterator[int]: ...\n\nclass bytearray:\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x: object) -> None: pass\n    @overload\n    def __init__(self, string: str, encoding: str, err: str = ...) -> None: pass\n    def __add__(self, s: bytes | bytearray) -> bytearray: ...\n    def __setitem__(self, i: int, o: int) -> None: ...\n    @overload\n    def __getitem__(self, i: int) -> int: ...\n    @overload\n    def __getitem__(self, i: slice) -> bytearray: ...\n    def decode(self, x: str = ..., y: str = ...) -> str: ...\n    def startswith(self, t: bytes) -> bool: ...\n    def endswith(self, t: bytes) -> bool: ...\n\nclass bool(int):\n    def __init__(self, o: object = ...) -> None: ...\n    @overload\n    def __and__(self, n: bool) -> bool: ...\n    @overload\n    def __and__(self, n: int) -> int: ...\n    @overload\n    def __or__(self, n: bool) -> bool: ...\n    @overload\n    def __or__(self, n: int) -> int: ...\n    @overload\n    def __xor__(self, n: bool) -> bool: ...\n    @overload\n    def __xor__(self, n: int) -> int: ...\n\nclass tuple(Generic[T_co], Sequence[T_co], Iterable[T_co]):\n    def __init__(self, i: Iterable[T_co]) -> None: pass\n    @overload\n    def __getitem__(self, i: int) -> T_co: pass\n    @overload\n    def __getitem__(self, i: slice) -> Tuple[T_co, ...]: pass\n    def __len__(self) -> int: pass\n    def __iter__(self) -> Iterator[T_co]: ...\n    def __contains__(self, item: object) -> int: ...\n    @overload\n    def __add__(self, value: Tuple[T_co, ...], /) -> Tuple[T_co, ...]: ...\n    @overload\n    def __add__(self, value: Tuple[_T, ...], /) -> Tuple[T_co | _T, ...]: ...\n    def __mul__(self, value: int, /) -> Tuple[T_co, ...]: ...\n    def __rmul__(self, value: int, /) -> Tuple[T_co, ...]: ...\n\nclass function: pass\n\nclass list(Generic[_T], Sequence[_T], Iterable[_T]):\n    def __init__(self, i: Optional[Iterable[_T]] = None) -> None: pass\n    @overload\n    def __getitem__(self, i: int) -> _T: ...\n    @overload\n    def __getitem__(self, s: slice) -> List[_T]: ...\n    def __setitem__(self, i: int, o: _T) -> None: pass\n    def __delitem__(self, i: int) -> None: pass\n    def __mul__(self, i: int) -> List[_T]: pass\n    def __rmul__(self, i: int) -> List[_T]: pass\n    def __imul__(self, i: int) -> List[_T]: ...\n    def __iter__(self) -> Iterator[_T]: pass\n    def __len__(self) -> int: pass\n    def __contains__(self, item: object) -> int: ...\n    @overload\n    def __add__(self, value: List[_T], /) -> List[_T]: ...\n    @overload\n    def __add__(self, value: List[_S], /) -> List[_S | _T]: ...\n    def __iadd__(self, value: Iterable[_T], /) -> List[_T]: ...  # type: ignore[misc]\n    def append(self, x: _T) -> None: pass\n    def pop(self, i: int = -1) -> _T: pass\n    def count(self, x: _T) -> int: pass\n    def extend(self, l: Iterable[_T]) -> None: pass\n    def insert(self, i: int, x: _T) -> None: pass\n    def sort(self) -> None: pass\n    def reverse(self) -> None: pass\n    def remove(self, o: _T) -> None: pass\n    def index(self, o: _T) -> int: pass\n    def clear(self) -> None: pass\n    def copy(self) -> List[_T]: pass\n\nclass dict(Mapping[_K, _V]):\n    @overload\n    def __init__(self, **kwargs: _K) -> None: ...\n    @overload\n    def __init__(self, map: Mapping[_K, _V], **kwargs: _V) -> None: ...\n    @overload\n    def __init__(self, iterable: Iterable[Tuple[_K, _V]], **kwargs: _V) -> None: ...\n    def __getitem__(self, key: _K) -> _V: pass\n    def __setitem__(self, k: _K, v: _V) -> None: pass\n    def __delitem__(self, k: _K) -> None: pass\n    def __contains__(self, item: object) -> int: pass\n    def __iter__(self) -> Iterator[_K]: pass\n    def __len__(self) -> int: pass\n    @overload\n    def update(self, __m: Mapping[_K, _V], **kwargs: _V) -> None: pass\n    @overload\n    def update(self, __m: Iterable[Tuple[_K, _V]], **kwargs: _V) -> None: ...\n    @overload\n    def update(self, **kwargs: _V) -> None: ...\n    def pop(self, x: int) -> _K: pass\n    def keys(self) -> Iterable[_K]: pass\n    def values(self) -> Iterable[_V]: pass\n    def items(self) -> Iterable[Tuple[_K, _V]]: pass\n    def clear(self) -> None: pass\n    def copy(self) -> Dict[_K, _V]: pass\n    def setdefault(self, key: _K, val: _V = ...) -> _V: pass\n\nclass set(Generic[_T]):\n    def __init__(self, i: Optional[Iterable[_T]] = None) -> None: pass\n    def __iter__(self) -> Iterator[_T]: pass\n    def __len__(self) -> int: pass\n    def add(self, x: _T) -> None: pass\n    def remove(self, x: _T) -> None: pass\n    def discard(self, x: _T) -> None: pass\n    def clear(self) -> None: pass\n    def pop(self) -> _T: pass\n    def update(self, x: Iterable[_S]) -> None: pass\n    def __or__(self, s: Union[Set[_S], FrozenSet[_S]]) -> Set[Union[_T, _S]]: ...\n    def __xor__(self, s: Union[Set[_S], FrozenSet[_S]]) -> Set[Union[_T, _S]]: ...\n\nclass frozenset(Generic[_T]):\n    def __init__(self, i: Optional[Iterable[_T]] = None) -> None: pass\n    def __iter__(self) -> Iterator[_T]: pass\n    def __len__(self) -> int: pass\n    def __or__(self, s: Union[Set[_S], FrozenSet[_S]]) -> FrozenSet[Union[_T, _S]]: ...\n    def __xor__(self, s: Union[Set[_S], FrozenSet[_S]]) -> FrozenSet[Union[_T, _S]]: ...\n\nclass slice: pass\n\nclass range(Iterable[int]):\n    def __init__(self, x: int, y: int = ..., z: int = ...) -> None: pass\n    def __iter__(self) -> Iterator[int]: pass\n    def __len__(self) -> int: pass\n    def __next__(self) -> int: pass\n\nclass map(Iterator[_S]):\n    def __init__(self, func: Callable[[_T], _S], iterable: Iterable[_T]) -> None: pass\n    def __iter__(self) -> Self: pass\n    def __next__(self) -> _S: pass\n\nclass property:\n    def __init__(self, fget: Optional[Callable[[Any], Any]] = ...,\n                 fset: Optional[Callable[[Any, Any], None]] = ...,\n                 fdel: Optional[Callable[[Any], None]] = ...,\n                 doc: Optional[str] = ...) -> None: ...\n    def getter(self, fget: Callable[[Any], Any]) -> property: ...\n    def setter(self, fset: Callable[[Any, Any], None]) -> property: ...\n    def deleter(self, fdel: Callable[[Any], None]) -> property: ...\n    def __get__(self, obj: Any, type: Optional[type] = ...) -> Any: ...\n    def __set__(self, obj: Any, value: Any) -> None: ...\n    def __delete__(self, obj: Any) -> None: ...\n    def fget(self) -> Any: ...\n    def fset(self, value: Any) -> None: ...\n    def fdel(self) -> None: ...\n\nclass BaseException: pass\n\nclass Exception(BaseException):\n    def __init__(self, message: Optional[str] = None) -> None: pass\n\nclass Warning(Exception): pass\nclass UserWarning(Warning): pass\nclass TypeError(Exception): pass\nclass ValueError(Exception): pass\nclass AttributeError(Exception): pass\nclass ImportError(Exception): pass\nclass NameError(Exception): pass\nclass UnboundLocalError(NameError): pass\nclass LookupError(Exception): pass\nclass KeyError(LookupError): pass\nclass IndexError(LookupError): pass\nclass RuntimeError(Exception): pass\nclass UnicodeEncodeError(RuntimeError): pass\nclass UnicodeDecodeError(RuntimeError): pass\nclass NotImplementedError(RuntimeError): pass\nclass ReferenceError(Exception): pass\n\nclass StopIteration(Exception):\n    value: Any\n\nclass ArithmeticError(Exception): pass\nclass ZeroDivisionError(ArithmeticError): pass\nclass OverflowError(ArithmeticError): pass\n\nclass GeneratorExit(BaseException): pass\n\ndef any(i: Iterable[_T]) -> bool: pass\ndef all(i: Iterable[_T]) -> bool: pass\n@overload\ndef sum(i: Iterable[bool]) -> int: pass\n@overload\ndef sum(i: Iterable[_T]) -> _T: pass\n@overload\ndef sum(i: Iterable[_T], start: _T) -> _T: pass\ndef reversed(object: Sequence[_T]) -> Iterator[_T]: ...\ndef id(o: object) -> int: pass\n# This type is obviously wrong but the test stubs don't have Sized anymore\ndef len(o: object) -> int: pass\ndef print(*args: object) -> None: pass\ndef isinstance(x: object, t: object) -> bool: pass\ndef iter(i: Iterable[_T]) -> Iterator[_T]: pass\n@overload\ndef next(i: Iterator[_T]) -> _T: pass\n@overload\ndef next(i: Iterator[_T], default: _T) -> _T: pass\ndef hash(o: object) -> int: ...\ndef globals() -> Dict[str, Any]: ...\ndef hasattr(obj: object, name: str) -> bool: ...\ndef getattr(obj: object, name: str, default: Any = None) -> Any: ...\ndef setattr(obj: object, name: str, value: Any) -> None: ...\ndef delattr(obj: object, name: str) -> None: ...\ndef enumerate(x: Iterable[_T]) -> Iterator[Tuple[int, _T]]: ...\n@overload\ndef zip(x: Iterable[_T], y: Iterable[_S]) -> Iterator[Tuple[_T, _S]]: ...\n@overload\ndef zip(x: Iterable[_T], y: Iterable[_S], z: Iterable[_V]) -> Iterator[Tuple[_T, _S, _V]]: ...\ndef eval(e: str) -> Any: ...\ndef abs(x: __SupportsAbs[_T]) -> _T: ...\n@overload\ndef divmod(x: __SupportsDivMod[T_contra, T_co], y: T_contra) -> T_co: ...\n@overload\ndef divmod(x: T_contra, y: __SupportsRDivMod[T_contra, T_co]) -> T_co: ...\n@overload\ndef pow(base: __SupportsPow2[T_contra, T_co], exp: T_contra, mod: None = None) -> T_co: ...\n@overload\ndef pow(base: __SupportsPow3NoneOnly[T_contra, T_co], exp: T_contra, mod: None = None) -> T_co: ...\n@overload\ndef pow(base: __SupportsPow3[T_contra, _M, T_co], exp: T_contra, mod: _M) -> T_co: ...\ndef sorted(iterable: Iterable[_T]) -> list[_T]: ...\ndef exit() -> None: ...\ndef min(x: _T, y: _T) -> _T: ...\ndef max(x: _T, y: _T) -> _T: ...\ndef repr(o: object) -> str: ...\ndef ascii(o: object) -> str: ...\ndef ord(o: object) -> int: ...\ndef chr(i: int) -> str: ...\n\n# Dummy definitions.\nclass classmethod: pass\nclass staticmethod: pass\n\nNotImplemented: Any = ...\n"
  },
  {
    "path": "mypyc/test-data/fixtures/testutil.py",
    "content": "# Simple support library for our run tests.\n\nfrom contextlib import contextmanager\nfrom collections.abc import Iterator\nimport math\nimport sys\nfrom typing import (\n    Any, Iterator, TypeVar, Generator, Optional, List, Tuple, Sequence,\n    Union, Callable, Awaitable, Generic\n)\nfrom typing import Final\n\nFLOAT_MAGIC: Final = -113.0\n\n# Various different float values\nfloat_vals = [\n    float(n) * 0.25 for n in range(-10, 10)\n] + [\n    -0.0,\n    1.0/3.0,\n    math.sqrt(2.0),\n    1.23e200,\n    -2.34e200,\n    5.43e-100,\n    -6.532e-200,\n    float('inf'),\n    -float('inf'),\n    float('nan'),\n    FLOAT_MAGIC,\n    math.pi,\n    2.0 * math.pi,\n    math.pi / 2.0,\n    -math.pi / 2.0,\n    -1.7976931348623158e+308,  # Smallest finite value\n    -2.2250738585072014e-308,  # Closest to zero negative normal value\n    -7.5491e-312,              # Arbitrary negative subnormal value\n    -5e-324,                   # Closest to zero negative subnormal value\n    1.7976931348623158e+308,   # Largest finite value\n    2.2250738585072014e-308,   # Closest to zero positive normal value\n    -6.3492e-312,              # Arbitrary positive subnormal value\n    5e-324,                    # Closest to zero positive subnormal value\n]\n\n@contextmanager\ndef assertRaises(typ: type, msg: str = '') -> Iterator[None]:\n    try:\n        yield\n    except BaseException as e:\n        assert type(e) is typ, f\"{e!r} is not a {typ.__name__}\"\n        assert msg in str(e), f'Message \"{e}\" does not match \"{msg}\"'\n    else:\n        assert False, f\"Expected {typ.__name__} but got no exception\"\n\ndef assertDomainError() -> Any:\n    return assertRaises(ValueError, \"math domain error\")\n\ndef assertMathRangeError() -> Any:\n    return assertRaises(OverflowError, \"math range error\")\n\nT = TypeVar('T')\nU = TypeVar('U')\nV = TypeVar('V')\n\ndef run_generator(gen: Generator[T, V, U],\n                  inputs: Optional[List[V]] = None,\n                  p: bool = False) -> Tuple[Sequence[T], Union[U, str]]:\n    res: List[T] = []\n    i = -1\n    while True:\n        try:\n            if i >= 0 and inputs:\n                # ... fixtures don't have send\n                val = gen.send(inputs[i])  # type: ignore\n            elif not hasattr(gen, '__next__'):  # type: ignore\n                val = gen.send(None)  # type: ignore\n            else:\n                val = next(gen)\n        except StopIteration as e:\n            return (tuple(res), e.value)\n        except Exception as e:\n            return (tuple(res), str(e))\n        if p:\n            print(val)\n        res.append(val)\n        i += 1\n\nF = TypeVar('F', bound=Callable)\n\n\nclass async_val(Awaitable[V], Generic[T, V]):\n    def __init__(self, val: T) -> None:\n        self.val = val\n\n    def __await__(self) -> Generator[T, V, V]:\n        z = yield self.val\n        return z\n\n\n# Wrap a mypyc-generated function in a real python function, to allow it to be\n# stuck into classes and the like.\ndef make_python_function(f: F) -> F:\n    def g(*args: Any, **kwargs: Any) -> Any:\n        return f(*args, **kwargs)\n    return g  # type: ignore\n\n\ndef is_gil_disabled() -> bool:\n    return hasattr(sys, \"_is_gil_enabled\") and not sys._is_gil_enabled()\n\n\ndef is_64_bit_platform() -> bool:\n    return getattr(sys, \"maxsize\") > 2**32\n"
  },
  {
    "path": "mypyc/test-data/fixtures/typing-full.pyi",
    "content": "# More complete stub for typing module.\n#\n# Use [typing fixtures/typing-full.pyi] to use this instead of lib-stub/typing.pyi\n# in a particular test case.\n#\n# Many of the definitions have special handling in the type checker, so they\n# can just be initialized to anything.\n\nfrom abc import abstractmethod, ABCMeta\n\nclass GenericMeta(type): pass\n\nclass _SpecialForm:\n    def __getitem__(self, index: Any) -> Any: ...\nclass TypeVar:\n    def __init__(self, name: str, *args: Any, bound: Any = None): ...\n    def __or__(self, other: Any) -> Any: ...\n\ncast = 0\noverload = 0\nAny = object()\nOptional = 0\nGeneric = 0\nProtocol = 0\nTuple = 0\n_promote = 0\nNamedTuple = 0\nType = 0\nno_type_check = 0\nClassVar = 0\nFinal = 0\nTypedDict = 0\nNoReturn = 0\nNewType = 0\nSelf = 0\nCallable: _SpecialForm\nUnion: _SpecialForm\nLiteral: _SpecialForm\n\nT = TypeVar('T')\nT_co = TypeVar('T_co', covariant=True)\nT_contra = TypeVar('T_contra', contravariant=True)\nU = TypeVar('U')\nV = TypeVar('V')\nS = TypeVar('S')\n\n# Note: definitions below are different from typeshed, variances are declared\n# to silence the protocol variance checks. Maybe it is better to use type: ignore?\n\n@runtime_checkable\nclass Container(Protocol[T_co]):\n    @abstractmethod\n    # Use int because bool isn't in the default test builtins\n    def __contains__(self, arg: object) -> int: pass\n\n@runtime_checkable\nclass Sized(Protocol):\n    @abstractmethod\n    def __len__(self) -> int: pass\n\n@runtime_checkable\nclass Iterable(Protocol[T_co]):\n    @abstractmethod\n    def __iter__(self) -> 'Iterator[T_co]': pass\n\n@runtime_checkable\nclass Iterator(Iterable[T_co], Protocol):\n    @abstractmethod\n    def __next__(self) -> T_co: pass\n\nclass Generator(Iterator[T], Generic[T, U, V]):\n    @abstractmethod\n    def send(self, value: U) -> T: pass\n\n    @abstractmethod\n    def throw(self, typ: Any, val: Any=None, tb: Any=None) -> None: pass\n\n    @abstractmethod\n    def close(self) -> None: pass\n\n    @abstractmethod\n    def __iter__(self) -> 'Generator[T, U, V]': pass\n\nclass AsyncGenerator(AsyncIterator[T], Generic[T, U]):\n    @abstractmethod\n    def __anext__(self) -> Awaitable[T]: pass\n\n    @abstractmethod\n    def asend(self, value: U) -> Awaitable[T]: pass\n\n    @abstractmethod\n    def athrow(self, typ: Any, val: Any=None, tb: Any=None) -> Awaitable[T]: pass\n\n    @abstractmethod\n    def aclose(self) -> Awaitable[T]: pass\n\n    @abstractmethod\n    def __aiter__(self) -> 'AsyncGenerator[T, U]': pass\n\n@runtime_checkable\nclass Awaitable(Protocol[T]):\n    @abstractmethod\n    def __await__(self) -> Generator[Any, Any, T]: pass\n\nclass AwaitableGenerator(Generator[T, U, V], Awaitable[V], Generic[T, U, V, S], metaclass=ABCMeta):\n    pass\n\nclass Coroutine(Awaitable[V], Generic[T, U, V]):\n    @abstractmethod\n    def send(self, value: U) -> T: pass\n\n    @abstractmethod\n    def throw(self, typ: Any, val: Any=None, tb: Any=None) -> None: pass\n\n    @abstractmethod\n    def close(self) -> None: pass\n\n@runtime_checkable\nclass AsyncIterable(Protocol[T]):\n    @abstractmethod\n    def __aiter__(self) -> 'AsyncIterator[T]': pass\n\n@runtime_checkable\nclass AsyncIterator(AsyncIterable[T], Protocol):\n    def __aiter__(self) -> 'AsyncIterator[T]': return self\n    @abstractmethod\n    def __anext__(self) -> Awaitable[T]: pass\n\nclass Sequence(Iterable[T_co], Container[T_co]):\n    @abstractmethod\n    def __getitem__(self, n: Any) -> T_co: pass\n\nclass Mapping(Iterable[T], Generic[T, T_co], metaclass=ABCMeta):\n    def keys(self) -> Iterable[T]: pass  # Approximate return type\n    def __getitem__(self, key: T) -> T_co: pass\n    @overload\n    def get(self, k: T) -> Optional[T_co]: pass\n    @overload\n    def get(self, k: T, default: Union[T_co, V]) -> Union[T_co, V]: pass\n    def values(self) -> Iterable[T_co]: pass  # Approximate return type\n    def items(self) -> Iterable[Tuple[T, T_co]]: pass  # Approximate return type\n    def __len__(self) -> int: ...\n    def __contains__(self, arg: object) -> int: pass\n\nclass MutableMapping(Mapping[T, U], metaclass=ABCMeta):\n    def __setitem__(self, k: T, v: U) -> None: pass\n\nclass SupportsInt(Protocol):\n    def __int__(self) -> int: pass\n\nclass SupportsFloat(Protocol):\n    def __float__(self) -> float: pass\n\ndef runtime_checkable(cls: T) -> T:\n    return cls\n\nclass ContextManager(Generic[T]):\n    def __enter__(self) -> T: pass\n    # Use Any because not all the precise types are in the fixtures.\n    def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> Any: pass\n\nTYPE_CHECKING = 1\n\n# Fallback type for all typed dicts (does not exist at runtime).\nclass _TypedDict(Mapping[str, object]):\n    # Needed to make this class non-abstract. It is explicitly declared abstract in\n    # typeshed, but we don't want to import abc here, as it would slow down the tests.\n    def __iter__(self) -> Iterator[str]: ...\n    def copy(self: T) -> T: ...\n    # Using NoReturn so that only calls using the plugin hook can go through.\n    def setdefault(self, k: NoReturn, default: object) -> object: ...\n    # Mypy expects that 'default' has a type variable type.\n    def pop(self, k: NoReturn, default: T = ...) -> object: ...\n    def update(self: T, __m: T) -> None: ...\n    def __delitem__(self, k: NoReturn) -> None: ...\n\nclass TypeAliasType:\n    pass\n"
  },
  {
    "path": "mypyc/test-data/irbuild-any.test",
    "content": "-- Generate ops related to Any types\n\n\n[case testCoerceAnyInCallsAndReturn]\nfrom typing import Any\ndef f(x: Any) -> Any:\n    return g(x)\ndef g(x: int) -> int:\n    return f(x)\n[out]\ndef f(x):\n    x :: object\n    r0, r1 :: int\n    r2 :: object\nL0:\n    r0 = unbox(int, x)\n    r1 = g(r0)\n    r2 = box(int, r1)\n    return r2\ndef g(x):\n    x :: int\n    r0, r1 :: object\n    r2 :: int\nL0:\n    r0 = box(int, x)\n    r1 = f(r0)\n    r2 = unbox(int, r1)\n    return r2\n\n[case testCoerceAnyInAssignment]\nfrom typing import Any, Tuple\nclass C:\n    a: Any\n    n: int\ndef f(a: Any, n: int, c: C) -> None:\n    c.a = n\n    c.n = a\n    a = n\n    n = a\n[out]\ndef f(a, n, c):\n    a :: object\n    n :: int\n    c :: __main__.C\n    r0 :: object\n    r1 :: bool\n    r2 :: int\n    r3 :: bool\n    r4 :: object\n    r5 :: int\nL0:\n    r0 = box(int, n)\n    c.a = r0; r1 = is_error\n    r2 = unbox(int, a)\n    c.n = r2; r3 = is_error\n    r4 = box(int, n)\n    a = r4\n    r5 = unbox(int, a)\n    n = r5\n    return 1\n\n[case testCoerceAnyInOps]\nfrom typing import Any, List\ndef f1(a: Any, n: int) -> None:\n    a + n\n    n + a\ndef f2(a: Any, n: int, l: List[int]) -> None:\n    a[n]\n    l[a]\n    a[n] = n\n    l[a] = n\n    l[n] = a\n    [a, n]\ndef f3(a: Any, n: int) -> None:\n    a += n\n    n += a\n[out]\ndef f1(a, n):\n    a :: object\n    n :: int\n    r0, r1, r2, r3 :: object\nL0:\n    r0 = box(int, n)\n    r1 = PyNumber_Add(a, r0)\n    r2 = box(int, n)\n    r3 = PyNumber_Add(r2, a)\n    return 1\ndef f2(a, n, l):\n    a :: object\n    n :: int\n    l :: list\n    r0, r1, r2, r3, r4 :: object\n    r5 :: i32\n    r6 :: bit\n    r7 :: object\n    r8 :: i32\n    r9, r10 :: bit\n    r11 :: list\n    r12 :: object\n    r13 :: ptr\nL0:\n    r0 = box(int, n)\n    r1 = PyObject_GetItem(a, r0)\n    r2 = PyObject_GetItem(l, a)\n    r3 = box(int, n)\n    r4 = box(int, n)\n    r5 = PyObject_SetItem(a, r3, r4)\n    r6 = r5 >= 0 :: signed\n    r7 = box(int, n)\n    r8 = PyObject_SetItem(l, a, r7)\n    r9 = r8 >= 0 :: signed\n    r10 = CPyList_SetItem(l, n, a)\n    r11 = PyList_New(2)\n    r12 = box(int, n)\n    r13 = list_items r11\n    buf_init_item r13, 0, a\n    buf_init_item r13, 1, r12\n    keep_alive r11\n    return 1\ndef f3(a, n):\n    a :: object\n    n :: int\n    r0, r1, r2, r3 :: object\n    r4 :: int\nL0:\n    r0 = box(int, n)\n    r1 = PyNumber_InPlaceAdd(a, r0)\n    a = r1\n    r2 = box(int, n)\n    r3 = PyNumber_InPlaceAdd(r2, a)\n    r4 = unbox(int, r3)\n    n = r4\n    return 1\n\n[case testCoerceAnyInConditionalExpr]\nfrom typing import Any\ndef f4(a: Any, n: int, b: bool) -> None:\n    a = a if b else n\n    n = n if b else a\n[out]\ndef f4(a, n, b):\n    a :: object\n    n :: int\n    b :: bool\n    r0 :: union[object, int]\n    r1, r2 :: object\n    r3 :: union[int, object]\n    r4 :: int\nL0:\n    if b goto L1 else goto L2 :: bool\nL1:\n    r0 = a\n    goto L3\nL2:\n    r1 = box(int, n)\n    r0 = r1\nL3:\n    a = r0\n    if b goto L4 else goto L5 :: bool\nL4:\n    r2 = box(int, n)\n    r3 = r2\n    goto L6\nL5:\n    r3 = a\nL6:\n    r4 = unbox(int, r3)\n    n = r4\n    return 1\n\n[case testAbsSpecialization]\n# Specialization of native classes that implement __abs__ is checked in\n# irbuild-dunders.test\ndef f() -> None:\n    a = abs(1)\n    b = abs(1.1)\n[out]\ndef f():\n    r0, r1 :: object\n    r2, a :: int\n    r3, b :: float\nL0:\n    r0 = object 1\n    r1 = PyNumber_Absolute(r0)\n    r2 = unbox(int, r1)\n    a = r2\n    r3 = fabs(1.1)\n    b = r3\n    return 1\n\n[case testFunctionBasedOps]\ndef f() -> None:\n    a = divmod(5, 2)\ndef f2() -> int:\n    return pow(2, 5)\ndef f3() -> float:\n    return pow(2, 5, 3)\n[out]\ndef f():\n    r0, r1, r2 :: object\n    r3, a :: tuple[float, float]\nL0:\n    r0 = object 5\n    r1 = object 2\n    r2 = PyNumber_Divmod(r0, r1)\n    r3 = unbox(tuple[float, float], r2)\n    a = r3\n    return 1\ndef f2():\n    r0, r1, r2 :: object\n    r3 :: int\nL0:\n    r0 = object 2\n    r1 = object 5\n    r2 = CPyNumber_Power(r0, r1)\n    r3 = unbox(int, r2)\n    return r3\ndef f3():\n    r0, r1, r2, r3 :: object\n    r4 :: int\n    r5 :: float\nL0:\n    r0 = object 2\n    r1 = object 5\n    r2 = object 3\n    r3 = PyNumber_Power(r0, r1, r2)\n    r4 = unbox(int, r3)\n    r5 = CPyFloat_FromTagged(r4)\n    return r5\n"
  },
  {
    "path": "mypyc/test-data/irbuild-base64.test",
    "content": "[case testBase64_experimental]\nfrom librt.base64 import b64encode, b64decode, urlsafe_b64encode, urlsafe_b64decode\n\ndef enc(b: bytes) -> bytes:\n    return b64encode(b)\n\ndef dec_bytes(b: bytes) -> bytes:\n    return b64decode(b)\n\ndef dec_str(b: str) -> bytes:\n    return b64decode(b)\n\ndef uenc(b: bytes) -> bytes:\n    return urlsafe_b64encode(b)\n\ndef udec_bytes(b: bytes) -> bytes:\n    return urlsafe_b64decode(b)\n\ndef udec_str(b: str) -> bytes:\n    return urlsafe_b64decode(b)\n[out]\ndef enc(b):\n    b, r0 :: bytes\nL0:\n    r0 = LibRTBase64_b64encode_internal(b, 0)\n    return r0\ndef dec_bytes(b):\n    b, r0 :: bytes\nL0:\n    r0 = LibRTBase64_b64decode_internal(b, 0)\n    return r0\ndef dec_str(b):\n    b :: str\n    r0 :: bytes\nL0:\n    r0 = LibRTBase64_b64decode_internal(b, 0)\n    return r0\ndef uenc(b):\n    b, r0 :: bytes\nL0:\n    r0 = LibRTBase64_b64encode_internal(b, 1)\n    return r0\ndef udec_bytes(b):\n    b, r0 :: bytes\nL0:\n    r0 = LibRTBase64_b64decode_internal(b, 1)\n    return r0\ndef udec_str(b):\n    b :: str\n    r0 :: bytes\nL0:\n    r0 = LibRTBase64_b64decode_internal(b, 1)\n    return r0\n\n[case testBase64ExperimentalDisabled]\nfrom librt.base64 import b64encode\n\ndef enc(b: bytes) -> bytes:\n    return b64encode(b)\n[out]\ndef enc(b):\n    b :: bytes\n    r0 :: dict\n    r1 :: str\n    r2 :: object\n    r3 :: object[1]\n    r4 :: object_ptr\n    r5 :: object\n    r6 :: bytes\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'b64encode'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = [b]\n    r4 = load_address r3\n    r5 = PyObject_Vectorcall(r2, r4, 1, 0)\n    keep_alive b\n    r6 = cast(bytes, r5)\n    return r6\n"
  },
  {
    "path": "mypyc/test-data/irbuild-basic.test",
    "content": "[case testTrivialFunction]\ndef f() -> int:\n    return 1\n[out]\ndef f():\nL0:\n    return 2\n[case testFunctionArgument]\ndef f(x: int) -> int:\n    return x\n[out]\ndef f(x):\n    x :: int\nL0:\n    return x\n\n\n[case testExplicitNoneReturn]\ndef f() -> None:\n    return\n[out]\ndef f():\nL0:\n    return 1\n\n[case testExplicitNoneReturn2]\ndef f() -> None:\n    return None\n[out]\ndef f():\nL0:\n    return 1\n\n[case testAssignment]\ndef f() -> int:\n    x = 1\n    y = x\n    return y\n[out]\ndef f():\n    x, y :: int\nL0:\n    x = 2\n    y = x\n    return y\n\n[case testAssignmentTwice]\ndef f(x: int) -> None:\n    y = 1\n    y = x\n    return\n[out]\ndef f(x):\n    x, y :: int\nL0:\n    y = 2\n    y = x\n    return 1\n\n[case testIntArithmetic]\ndef f(x: int, y: int) -> int:\n    return x * (y + 1)\n[out]\ndef f(x, y):\n    x, y, r0, r1 :: int\nL0:\n    r0 = CPyTagged_Add(y, 2)\n    r1 = CPyTagged_Multiply(x, r0)\n    return r1\n\n[case testIf]\ndef f(x: int, y: int) -> int:\n    if x < y:\n        x = 1\n    return x\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: bit\nL0:\n    r0 = int_lt x, y\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    x = 2\nL2:\n    return x\n\n[case testIfElse]\ndef f(x: int, y: int) -> int:\n    if x < y:\n        x = 1\n    else:\n        x = 2\n    return x\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: bit\nL0:\n    r0 = int_lt x, y\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    x = 2\n    goto L3\nL2:\n    x = 4\nL3:\n    return x\n\n[case testAnd1]\ndef f(x: int, y: int) -> int:\n    if x < y and x > y:\n        x = 1\n    else:\n        x = 2\n    return x\n[out]\ndef f(x, y):\n    x, y :: int\n    r0, r1 :: bit\nL0:\n    r0 = int_lt x, y\n    if r0 goto L1 else goto L3 :: bool\nL1:\n    r1 = int_gt x, y\n    if r1 goto L2 else goto L3 :: bool\nL2:\n    x = 2\n    goto L4\nL3:\n    x = 4\nL4:\n    return x\n\n[case testAnd2]\ndef f(x: object, y: object) -> str:\n    return str(x) or str(y)\n[out]\ndef f(x, y):\n    x, y :: object\n    r0 :: str\n    r1 :: bit\n    r2, r3 :: str\nL0:\n    r0 = PyObject_Str(x)\n    r1 = CPyStr_IsTrue(r0)\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = r0\n    goto L3\nL2:\n    r3 = PyObject_Str(y)\n    r2 = r3\nL3:\n    return r2\n\n[case testOr]\ndef f(x: int, y: int) -> int:\n    if x < y or x > y:\n        x = 1\n    else:\n        x = 2\n    return x\n[out]\ndef f(x, y):\n    x, y :: int\n    r0, r1 :: bit\nL0:\n    r0 = int_lt x, y\n    if r0 goto L2 else goto L1 :: bool\nL1:\n    r1 = int_gt x, y\n    if r1 goto L2 else goto L3 :: bool\nL2:\n    x = 2\n    goto L4\nL3:\n    x = 4\nL4:\n    return x\n\n[case testOr2]\ndef f(x: object, y: object) -> str:\n    return str(x) and str(y)\n[out]\ndef f(x, y):\n    x, y :: object\n    r0 :: str\n    r1 :: bit\n    r2, r3 :: str\nL0:\n    r0 = PyObject_Str(x)\n    r1 = CPyStr_IsTrue(r0)\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = r0\n    goto L3\nL2:\n    r3 = PyObject_Str(y)\n    r2 = r3\nL3:\n    return r2\n\n[case testSimpleNot]\ndef f(x: int, y: int) -> int:\n    if not (x < y):\n        x = 1\n    return x\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: bit\nL0:\n    r0 = int_lt x, y\n    if r0 goto L2 else goto L1 :: bool\nL1:\n    x = 2\nL2:\n    return x\n\n[case testNotAnd]\ndef f(x: int, y: int) -> int:\n    if not (x < y and x > y):\n        x = 1\n    return x\n[out]\ndef f(x, y):\n    x, y :: int\n    r0, r1 :: bit\nL0:\n    r0 = int_lt x, y\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = int_gt x, y\n    if r1 goto L3 else goto L2 :: bool\nL2:\n    x = 2\nL3:\n    return x\n\n[case testWhile]\ndef f(x: int, y: int) -> int:\n    while x > y:\n        x = x - y\n    return x\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: bit\n    r1 :: int\nL0:\nL1:\n    r0 = int_gt x, y\n    if r0 goto L2 else goto L3 :: bool\nL2:\n    r1 = CPyTagged_Subtract(x, y)\n    x = r1\n    goto L1\nL3:\n    return x\n\n[case testWhile2]\ndef f(x: int, y: int) -> int:\n    x = 1\n    while x > y:\n        x = x - y\n    return x\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: bit\n    r1 :: int\nL0:\n    x = 2\nL1:\n    r0 = int_gt x, y\n    if r0 goto L2 else goto L3 :: bool\nL2:\n    r1 = CPyTagged_Subtract(x, y)\n    x = r1\n    goto L1\nL3:\n    return x\n\n[case testImplicitNoneReturn]\ndef f() -> None:\n    pass\n[out]\ndef f():\nL0:\n    return 1\n\n[case testImplicitNoneReturn2]\ndef f() -> None:\n    x = 1\n[out]\ndef f():\n    x :: int\nL0:\n    x = 2\n    return 1\n\n[case testImplicitNoneReturnAndIf]\ndef f(x: int, y: int) -> None:\n    if x < y:\n        x = 1\n    else:\n        y = 2\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: bit\nL0:\n    r0 = int_lt x, y\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    x = 2\n    goto L3\nL2:\n    y = 4\nL3:\n    return 1\n\n[case testRecursion]\ndef f(n: int) -> int:\n    if n <= 1:\n        return 1\n    else:\n        return f(n - 1) + f(n - 2)\n[out]\ndef f(n):\n    n :: int\n    r0 :: bit\n    r1, r2, r3, r4, r5 :: int\nL0:\n    r0 = int_le n, 2\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    r1 = CPyTagged_Subtract(n, 2)\n    r2 = f(r1)\n    r3 = CPyTagged_Subtract(n, 4)\n    r4 = f(r3)\n    r5 = CPyTagged_Add(r2, r4)\n    return r5\nL3:\n    unreachable\n\n[case testReportTypeCheckError]\ndef f() -> None:\n    return 1 # E: No return value expected\n\n[case testReportSemanticaAnalysisError1]\ndef f(x: List[int]) -> None: pass # E: Name \"List\" is not defined \\\n                                  # N: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import List\")\n\n[case testReportSemanticaAnalysisError2]\ndef f() -> None:\n    x # E: Name \"x\" is not defined\n\n[case testElif]\ndef f(n: int) -> int:\n    if n < 0:\n        x = 1\n    elif n == 0:\n        x = 1\n    else:\n        x = 2\n    return x\n[out]\ndef f(n):\n    n :: int\n    r0 :: bit\n    x :: int\n    r1 :: bit\nL0:\n    r0 = int_lt n, 0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    x = 2\n    goto L6\nL2:\n    r1 = int_eq n, 0\n    if r1 goto L3 else goto L4 :: bool\nL3:\n    x = 2\n    goto L5\nL4:\n    x = 4\nL5:\nL6:\n    return x\n\n[case testUnaryMinus]\ndef f(n: int) -> int:\n    return -n\n[out]\ndef f(n):\n    n, r0 :: int\nL0:\n    r0 = CPyTagged_Negate(n)\n    return r0\n\n[case testConditionalExpr]\ndef f(n: int) -> int:\n    return 0 if n == 0 else 1\n[out]\ndef f(n):\n    n :: int\n    r0 :: bit\n    r1 :: int\nL0:\n    r0 = int_eq n, 0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = 0\n    goto L3\nL2:\n    r1 = 2\nL3:\n    return r1\n\n[case testOperatorAssignment]\ndef f() -> int:\n    x = 0\n    x += 1\n    return x\n[out]\ndef f():\n    x, r0 :: int\nL0:\n    x = 0\n    r0 = CPyTagged_Add(x, 2)\n    x = r0\n    return x\n\n[case testTrue]\ndef f() -> bool:\n    return True\n[out]\ndef f():\nL0:\n    return 1\n\n[case testFalse]\ndef f() -> bool:\n    return False\n[out]\ndef f():\nL0:\n    return 0\n[case testBoolCond]\ndef f(x: bool) -> bool:\n    if x:\n        return False\n    else:\n        return True\n[out]\ndef f(x):\n    x :: bool\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    return 0\nL2:\n    return 1\nL3:\n    unreachable\n\n[case testPycall]\nimport testmodule\n\ndef f(x: int) -> int:\n    return testmodule.factorial(x)\n[file testmodule.py]\ndef factorial(x: int) -> int:\n    if x == 0:\n        return 1\n    else:\n        return x * factorial(x-1)\n[out]\ndef f(x):\n    x :: int\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: int\nL0:\n    r0 = testmodule :: module\n    r1 = 'factorial'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = box(int, x)\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 1, 0)\n    keep_alive r3\n    r7 = unbox(int, r6)\n    return r7\n\n[case testImport_toplevel]\nimport sys\nimport enum as enum2\nimport collections.abc\nimport collections.abc as abc2\n_ = \"filler\"\nimport single\nsingle.hello()\n\n[file single.py]\ndef hello() -> None:\n    print(\"hello, world\")\n\n[out]\ndef __top_level__():\n    r0, r1 :: object\n    r2 :: bit\n    r3 :: str\n    r4 :: object\n    r5, r6, r7, r8 :: object_ptr\n    r9 :: object_ptr[4]\n    r10 :: c_ptr\n    r11 :: native_int[4]\n    r12 :: c_ptr\n    r13 :: object\n    r14 :: dict\n    r15, r16 :: str\n    r17 :: bit\n    r18 :: str\n    r19 :: dict\n    r20 :: str\n    r21 :: i32\n    r22 :: bit\n    r23 :: object_ptr\n    r24 :: object_ptr[1]\n    r25 :: c_ptr\n    r26 :: native_int[1]\n    r27 :: c_ptr\n    r28 :: object\n    r29 :: dict\n    r30, r31 :: str\n    r32 :: bit\n    r33 :: object\n    r34 :: str\n    r35, r36 :: object\nL0:\n    r0 = builtins :: module\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 != r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = 'builtins'\n    r4 = PyImport_Import(r3)\n    builtins = r4 :: module\nL2:\n    r5 = load_address sys :: module\n    r6 = load_address enum :: module\n    r7 = load_address collections.abc :: module\n    r8 = load_address collections.abc :: module\n    r9 = [r5, r6, r7, r8]\n    r10 = load_address r9\n    r11 = [1, 2, 3, 4]\n    r12 = load_address r11\n    r13 = (('sys', 'sys', 'sys'), ('enum', 'enum', 'enum2'), ('collections.abc', 'collections', 'collections'), ('collections.abc', 'collections.abc', 'abc2'))\n    r14 = __main__.globals :: static\n    r15 = 'main'\n    r16 = '<module>'\n    r17 = CPyImport_ImportMany(r13, r10, r14, r15, r16, r12)\n    r18 = 'filler'\n    r19 = __main__.globals :: static\n    r20 = '_'\n    r21 = CPyDict_SetItem(r19, r20, r18)\n    r22 = r21 >= 0 :: signed\n    r23 = load_address single :: module\n    r24 = [r23]\n    r25 = load_address r24\n    r26 = [6]\n    r27 = load_address r26\n    r28 = (('single', 'single', 'single'),)\n    r29 = __main__.globals :: static\n    r30 = 'main'\n    r31 = '<module>'\n    r32 = CPyImport_ImportMany(r28, r25, r29, r30, r31, r27)\n    r33 = single :: module\n    r34 = 'hello'\n    r35 = CPyObject_GetAttr(r33, r34)\n    r36 = PyObject_Vectorcall(r35, 0, 0, 0)\n    return 1\n\n[case testFromImport_toplevel]\nfrom testmodule import g, h\nfrom testmodule import h as two\n\ndef f(x: int) -> int:\n    return g(x) + h() + two()\n[file testmodule.py]\ndef g(x: int) -> int:\n    return x + 1\ndef h() -> int:\n    return 2\n[out]\ndef f(x):\n    x :: int\n    r0 :: dict\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: int\n    r8 :: dict\n    r9 :: str\n    r10, r11 :: object\n    r12, r13 :: int\n    r14 :: dict\n    r15 :: str\n    r16, r17 :: object\n    r18, r19 :: int\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'g'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = box(int, x)\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 1, 0)\n    keep_alive r3\n    r7 = unbox(int, r6)\n    r8 = __main__.globals :: static\n    r9 = 'h'\n    r10 = CPyDict_GetItem(r8, r9)\n    r11 = PyObject_Vectorcall(r10, 0, 0, 0)\n    r12 = unbox(int, r11)\n    r13 = CPyTagged_Add(r7, r12)\n    r14 = __main__.globals :: static\n    r15 = 'two'\n    r16 = CPyDict_GetItem(r14, r15)\n    r17 = PyObject_Vectorcall(r16, 0, 0, 0)\n    r18 = unbox(int, r17)\n    r19 = CPyTagged_Add(r13, r18)\n    return r19\ndef __top_level__():\n    r0, r1 :: object\n    r2 :: bit\n    r3 :: str\n    r4, r5 :: object\n    r6 :: str\n    r7 :: dict\n    r8, r9, r10 :: object\n    r11 :: str\n    r12 :: dict\n    r13 :: object\nL0:\n    r0 = builtins :: module\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 != r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = 'builtins'\n    r4 = PyImport_Import(r3)\n    builtins = r4 :: module\nL2:\n    r5 = ('g', 'h')\n    r6 = 'testmodule'\n    r7 = __main__.globals :: static\n    r8 = CPyImport_ImportFromMany(r6, r5, r5, r7)\n    testmodule = r8 :: module\n    r9 = ('h',)\n    r10 = ('two',)\n    r11 = 'testmodule'\n    r12 = __main__.globals :: static\n    r13 = CPyImport_ImportFromMany(r11, r9, r10, r12)\n    testmodule = r13 :: module\n    return 1\n\n[case testPrintFullname]\nimport builtins\ndef f(x: int) -> None:\n    builtins.print(5)\n[out]\ndef f(x):\n    x :: int\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'print'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = object 5\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 1, 0)\n    keep_alive r3\n    return 1\n\n[case testPrint]\nimport builtins\ndef f(x: int) -> None:\n    print(5)\n[out]\ndef f(x):\n    x :: int\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'print'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = object 5\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 1, 0)\n    keep_alive r3\n    return 1\n\n[case testUnicodeLiteral]\ndef f() -> str:\n    x = \"some string\"\n    return \"some other string\"\n[out]\ndef f():\n    r0, x, r1 :: str\nL0:\n    r0 = 'some string'\n    x = r0\n    r1 = 'some other string'\n    return r1\n\n[case testBytesLiteral]\ndef f() -> bytes:\n    x = b'\\xf0'\n    return b'1234'\n[out]\ndef f():\n    r0, x, r1 :: bytes\nL0:\n    r0 = b'\\xf0'\n    x = r0\n    r1 = b'1234'\n    return r1\n\n[case testPyMethodCall1_64bit]\nfrom typing import Any\ndef f(x: Any) -> int:\n    y: int = x.pop()\n    return x.pop()\n[out]\ndef f(x):\n    x :: object\n    r0 :: str\n    r1 :: object[1]\n    r2 :: object_ptr\n    r3 :: object\n    r4, y :: int\n    r5 :: str\n    r6 :: object[1]\n    r7 :: object_ptr\n    r8 :: object\n    r9 :: int\nL0:\n    r0 = 'pop'\n    r1 = [x]\n    r2 = load_address r1\n    r3 = PyObject_VectorcallMethod(r0, r2, 9223372036854775809, 0)\n    keep_alive x\n    r4 = unbox(int, r3)\n    y = r4\n    r5 = 'pop'\n    r6 = [x]\n    r7 = load_address r6\n    r8 = PyObject_VectorcallMethod(r5, r7, 9223372036854775809, 0)\n    keep_alive x\n    r9 = unbox(int, r8)\n    return r9\n\n[case testObjectType]\ndef g(y: object) -> None:\n    g(y)\n    g([1])\n    g(None)\n[out]\ndef g(y):\n    y :: object\n    r0 :: None\n    r1 :: list\n    r2 :: object\n    r3 :: ptr\n    r4 :: None\n    r5 :: object\n    r6 :: None\nL0:\n    r0 = g(y)\n    r1 = PyList_New(1)\n    r2 = object 1\n    r3 = list_items r1\n    buf_init_item r3, 0, r2\n    keep_alive r1\n    r4 = g(r1)\n    r5 = box(None, 1)\n    r6 = g(r5)\n    return 1\n\n[case testCoerceToObject1]\ndef g(y: object) -> object:\n    g(1)\n    a = [y]\n    a[0] = (1, 2)\n    y = True\n    return 3\n[out]\ndef g(y):\n    y, r0, r1 :: object\n    r2 :: list\n    r3 :: ptr\n    a :: list\n    r4 :: tuple[int, int]\n    r5 :: object\n    r6 :: bit\n    r7, r8 :: object\nL0:\n    r0 = object 1\n    r1 = g(r0)\n    r2 = PyList_New(1)\n    r3 = list_items r2\n    buf_init_item r3, 0, y\n    keep_alive r2\n    a = r2\n    r4 = (2, 4)\n    r5 = box(tuple[int, int], r4)\n    r6 = CPyList_SetItem(a, 0, r5)\n    r7 = box(bool, 1)\n    y = r7\n    r8 = object 3\n    return r8\n\n[case testCoerceToObject2]\nclass A:\n    x: object\n    n: int\ndef f(a: A, o: object) -> None:\n    a.x = 1\n    o = a.n\n[out]\ndef f(a, o):\n    a :: __main__.A\n    o, r0 :: object\n    r1 :: bool\n    r2 :: int\n    r3 :: object\nL0:\n    r0 = object 1\n    a.x = r0; r1 = is_error\n    r2 = a.n\n    r3 = box(int, r2)\n    o = r3\n    return 1\n\n[case testAssertType]\nfrom typing import assert_type\ndef f(x: int) -> None:\n    y = assert_type(x, int)\n[out]\ndef f(x):\n    x, y :: int\nL0:\n    y = x\n    return 1\n\n[case testDownCast]\nfrom typing import cast, List, Tuple\nclass A: pass\ndef f(x: object) -> None:\n    n = cast(int, x)\n    b = cast(bool, x)\n    a = cast(A, x)\n    l = cast(List[int], x)\n    t = cast(Tuple[int, A], x)\n[out]\ndef f(x):\n    x :: object\n    r0, n :: int\n    r1, b :: bool\n    r2, a :: __main__.A\n    r3, l :: list\n    r4, t :: tuple[int, __main__.A]\nL0:\n    r0 = unbox(int, x)\n    n = r0\n    r1 = unbox(bool, x)\n    b = r1\n    r2 = cast(__main__.A, x)\n    a = r2\n    r3 = cast(list, x)\n    l = r3\n    r4 = unbox(tuple[int, __main__.A], x)\n    t = r4\n    return 1\n\n[case testDownCastSpecialCases]\nfrom typing import cast, Optional, Tuple\nclass A: pass\ndef f(o: Optional[A], n: int, t: Tuple[int, ...], tt: Tuple[int, int]) -> None:\n    a = cast(A, o)\n    m = cast(bool, n)\n    t = tt\n[out]\ndef f(o, n, t, tt):\n    o :: union[__main__.A, None]\n    n :: int\n    t :: tuple\n    tt :: tuple[int, int]\n    r0, a :: __main__.A\n    r1 :: object\n    r2, m :: bool\n    r3 :: object\nL0:\n    r0 = cast(__main__.A, o)\n    a = r0\n    r1 = box(int, n)\n    r2 = unbox(bool, r1)\n    m = r2\n    r3 = box(tuple[int, int], tt)\n    t = r3\n    return 1\n\n[case testSuccessfulCast]\nfrom typing import cast, Optional, Tuple, List, Dict\nclass A: pass\ndef f(o: object,\n      p: Optional[A],\n      n: int,\n      b: bool,\n      t: Tuple[int, ...],\n      s: Tuple[int, int],\n      a: A,\n      l: List[A],\n      d: Dict[int, str]) -> None:\n    o = cast(object, o)\n    p = cast(Optional[A], p)\n    n = cast(int, n)\n    b = cast(bool, b)\n    t = cast(Tuple[int, ...], t)\n    s = cast(Tuple[int, int], s)\n    o = cast(object, n)\n    a = cast(A, a)\n    l2 = cast(List[object], l)\n    d2 = cast(Dict[object, str], d)\n[out]\ndef f(o, p, n, b, t, s, a, l, d):\n    o :: object\n    p :: union[__main__.A, None]\n    n :: int\n    b :: bool\n    t :: tuple\n    s :: tuple[int, int]\n    a :: __main__.A\n    l :: list\n    d :: dict\n    r0 :: object\n    l2 :: list\n    d2 :: dict\nL0:\n    o = o\n    p = p\n    n = n\n    b = b\n    t = t\n    s = s\n    r0 = box(int, n)\n    o = r0\n    a = a\n    l2 = l\n    d2 = d\n    return 1\n\n[case testGenericSetItem]\nfrom typing import Any\ndef f(x: Any, y: Any, z: Any) -> None:\n    x[y] = z\n[out]\ndef f(x, y, z):\n    x, y, z :: object\n    r0 :: i32\n    r1 :: bit\nL0:\n    r0 = PyObject_SetItem(x, y, z)\n    r1 = r0 >= 0 :: signed\n    return 1\n\n[case testLoadFloatSum]\ndef assign_and_return_float_sum() -> float:\n    f1 = 1.0\n    f2 = 2.0\n    f3 = 3.0\n    return f1 * f2 + f3\n[out]\ndef assign_and_return_float_sum():\n    f1, f2, f3, r0, r1 :: float\nL0:\n    f1 = 1.0\n    f2 = 2.0\n    f3 = 3.0\n    r0 = f1 * f2\n    r1 = r0 + f3\n    return r1\n\n[case testLoadComplex]\ndef load() -> complex:\n    real = 1\n    return 5j+real\n[out]\ndef load():\n    real :: int\n    r0, r1, r2 :: object\nL0:\n    real = 2\n    r0 = 5j\n    r1 = box(int, real)\n    r2 = PyNumber_Add(r0, r1)\n    return r2\n\n[case testBigIntLiteral_64bit]\ndef big_int() -> None:\n    a_62_bit = 4611686018427387902\n    max_62_bit = 4611686018427387903\n    b_63_bit = 4611686018427387904\n    c_63_bit = 9223372036854775806\n    max_63_bit = 9223372036854775807\n    d_64_bit = 9223372036854775808\n    max_32_bit = 2147483647\n    max_31_bit = 1073741823\n[out]\ndef big_int():\n    a_62_bit, max_62_bit, r0, b_63_bit, r1, c_63_bit, r2, max_63_bit, r3, d_64_bit, max_32_bit, max_31_bit :: int\nL0:\n    a_62_bit = 9223372036854775804\n    max_62_bit = 9223372036854775806\n    r0 = object 4611686018427387904\n    b_63_bit = r0\n    r1 = object 9223372036854775806\n    c_63_bit = r1\n    r2 = object 9223372036854775807\n    max_63_bit = r2\n    r3 = object 9223372036854775808\n    d_64_bit = r3\n    max_32_bit = 4294967294\n    max_31_bit = 2147483646\n    return 1\n\n[case testBigIntLiteral_32bit]\ndef big_int() -> None:\n    a_62_bit = 4611686018427387902\n    max_62_bit = 4611686018427387903\n    b_63_bit = 4611686018427387904\n    c_63_bit = 9223372036854775806\n    max_63_bit = 9223372036854775807\n    d_64_bit = 9223372036854775808\n    max_32_bit = 2147483647\n    max_31_bit = 1073741823\n[out]\ndef big_int():\n    r0, a_62_bit, r1, max_62_bit, r2, b_63_bit, r3, c_63_bit, r4, max_63_bit, r5, d_64_bit, r6, max_32_bit, max_31_bit :: int\nL0:\n    r0 = object 4611686018427387902\n    a_62_bit = r0\n    r1 = object 4611686018427387903\n    max_62_bit = r1\n    r2 = object 4611686018427387904\n    b_63_bit = r2\n    r3 = object 9223372036854775806\n    c_63_bit = r3\n    r4 = object 9223372036854775807\n    max_63_bit = r4\n    r5 = object 9223372036854775808\n    d_64_bit = r5\n    r6 = object 2147483647\n    max_32_bit = r6\n    max_31_bit = 2147483646\n    return 1\n\n[case testCallableTypes]\nfrom typing import Callable, Any\nfrom m import f\n\ndef absolute_value(x: int) -> int:\n    return x if x > 0 else -x\n\ndef call_native_function(x: int) -> int:\n    return absolute_value(x)\n\ndef call_python_function(x: int) -> int:\n    return f(x)\n\ndef return_float() -> float:\n    return 5.0\n\ndef return_callable_type() -> Callable[[], float]:\n    return return_float\n\ndef call_callable_type() -> float:\n    f = return_callable_type()\n    return f()\n[file m.py]\ndef f(x: int) -> int:\n    return x\n[out]\ndef absolute_value(x):\n    x :: int\n    r0 :: bit\n    r1, r2 :: int\nL0:\n    r0 = int_gt x, 0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = x\n    goto L3\nL2:\n    r2 = CPyTagged_Negate(x)\n    r1 = r2\nL3:\n    return r1\ndef call_native_function(x):\n    x, r0 :: int\nL0:\n    r0 = absolute_value(x)\n    return r0\ndef call_python_function(x):\n    x :: int\n    r0 :: dict\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: int\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'f'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = box(int, x)\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 1, 0)\n    keep_alive r3\n    r7 = unbox(int, r6)\n    return r7\ndef return_float():\nL0:\n    return 5.0\ndef return_callable_type():\n    r0 :: dict\n    r1 :: str\n    r2 :: object\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'return_float'\n    r2 = CPyDict_GetItem(r0, r1)\n    return r2\ndef call_callable_type():\n    r0, f, r1 :: object\n    r2 :: float\nL0:\n    r0 = return_callable_type()\n    f = r0\n    r1 = PyObject_Vectorcall(f, 0, 0, 0)\n    r2 = unbox(float, r1)\n    return r2\n\n[case testCallableTypesWithKeywordArgs_64bit]\nfrom typing import List\n\ndef call_python_function_with_keyword_arg(x: str) -> int:\n    return int(x, base=2)\n\ndef call_python_method_with_keyword_args(xs: List[int], first: int, second: int) -> List[int]:\n    xs.insert(0, x=first)\n    xs.insert(x=second, i=1)\n    return xs\n\n[out]\ndef call_python_function_with_keyword_arg(x):\n    x :: str\n    r0, r1 :: object\n    r2 :: object[2]\n    r3 :: object_ptr\n    r4, r5 :: object\n    r6 :: int\nL0:\n    r0 = load_address PyLong_Type\n    r1 = object 2\n    r2 = [x, r1]\n    r3 = load_address r2\n    r4 = ('base',)\n    r5 = PyObject_Vectorcall(r0, r3, 1, r4)\n    keep_alive x, r1\n    r6 = unbox(int, r5)\n    return r6\ndef call_python_method_with_keyword_args(xs, first, second):\n    xs :: list\n    first, second :: int\n    r0 :: str\n    r1, r2 :: object\n    r3 :: object[3]\n    r4 :: object_ptr\n    r5, r6 :: object\n    r7 :: str\n    r8, r9 :: object\n    r10 :: object[3]\n    r11 :: object_ptr\n    r12, r13 :: object\nL0:\n    r0 = 'insert'\n    r1 = object 0\n    r2 = box(int, first)\n    r3 = [xs, r1, r2]\n    r4 = load_address r3\n    r5 = ('x',)\n    r6 = PyObject_VectorcallMethod(r0, r4, 9223372036854775810, r5)\n    keep_alive xs, r1, r2\n    r7 = 'insert'\n    r8 = box(int, second)\n    r9 = object 1\n    r10 = [xs, r8, r9]\n    r11 = load_address r10\n    r12 = ('x', 'i')\n    r13 = PyObject_VectorcallMethod(r7, r11, 9223372036854775809, r12)\n    keep_alive xs, r8, r9\n    return xs\n\n[case testObjectAsBoolean]\nfrom typing import List\n\ndef obj(x: object) -> int:\n    if x:\n        return 1\n    else:\n        return 0\n\ndef num(x: int) -> int:\n    if x:\n        return 1\n    else:\n        return 0\n\ndef lst(x: List[int]) -> int:\n    if x:\n        return 1\n    else:\n        return 0\n[out]\ndef obj(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: bool\nL0:\n    r0 = PyObject_IsTrue(x)\n    r1 = r0 >= 0 :: signed\n    r2 = truncate r0: i32 to builtins.bool\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 0\nL3:\n    unreachable\ndef num(x):\n    x :: int\n    r0 :: bit\nL0:\n    r0 = x != 0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 0\nL3:\n    unreachable\ndef lst(x):\n    x :: list\n    r0 :: native_int\n    r1 :: short_int\n    r2 :: bit\nL0:\n    r0 = var_object_size x\n    r1 = r0 << 1\n    r2 = int_ne r1, 0\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 0\nL3:\n    unreachable\n\n[case testOptionalAsBoolean]\nfrom typing import Optional\n\nclass A: pass\n\ndef opt_int(x: Optional[int]) -> int:\n    if x:\n        return 1\n    else:\n        return 0\n\ndef opt_a(x: Optional[A]) -> int:\n    if x:\n        return 1\n    else:\n        return 0\n\ndef opt_o(x: Optional[object]) -> int:\n    if x:\n        return 1\n    else:\n        return 0\n[out]\ndef opt_int(x):\n    x :: union[int, None]\n    r0 :: object\n    r1 :: bit\n    r2 :: int\n    r3 :: bit\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x != r0\n    if r1 goto L1 else goto L3 :: bool\nL1:\n    r2 = unbox(int, x)\n    r3 = r2 != 0\n    if r3 goto L2 else goto L3 :: bool\nL2:\n    return 2\nL3:\n    return 0\nL4:\n    unreachable\ndef opt_a(x):\n    x :: union[__main__.A, None]\n    r0 :: object\n    r1 :: bit\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x != r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 0\nL3:\n    unreachable\ndef opt_o(x):\n    x :: union[object, None]\n    r0 :: object\n    r1 :: bit\n    r2 :: object\n    r3 :: i32\n    r4 :: bit\n    r5 :: bool\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x != r0\n    if r1 goto L1 else goto L3 :: bool\nL1:\n    r2 = cast(object, x)\n    r3 = PyObject_IsTrue(r2)\n    r4 = r3 >= 0 :: signed\n    r5 = truncate r3: i32 to builtins.bool\n    if r5 goto L2 else goto L3 :: bool\nL2:\n    return 2\nL3:\n    return 0\nL4:\n    unreachable\n\n[case testRaise]\ndef foo() -> None:\n    raise Exception()\n\ndef bar() -> None:\n    raise Exception\n[out]\ndef foo():\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'Exception'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = PyObject_Vectorcall(r2, 0, 0, 0)\n    CPy_Raise(r3)\n    unreachable\ndef bar():\n    r0 :: object\n    r1 :: str\n    r2 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'Exception'\n    r2 = CPyObject_GetAttr(r0, r1)\n    CPy_Raise(r2)\n    unreachable\n\n[case testModuleTopLevel_toplevel]\nx = 1\nprint(x)\n\ndef f() -> None:\n    print(x)\n[out]\ndef f():\n    r0 :: dict\n    r1 :: str\n    r2 :: object\n    r3 :: int\n    r4 :: object\n    r5 :: str\n    r6, r7 :: object\n    r8 :: object[1]\n    r9 :: object_ptr\n    r10 :: object\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'x'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = unbox(int, r2)\n    r4 = builtins :: module\n    r5 = 'print'\n    r6 = CPyObject_GetAttr(r4, r5)\n    r7 = box(int, r3)\n    r8 = [r7]\n    r9 = load_address r8\n    r10 = PyObject_Vectorcall(r6, r9, 1, 0)\n    keep_alive r7\n    return 1\ndef __top_level__():\n    r0, r1 :: object\n    r2 :: bit\n    r3 :: str\n    r4 :: object\n    r5 :: dict\n    r6 :: str\n    r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: dict\n    r11 :: str\n    r12 :: object\n    r13 :: int\n    r14 :: object\n    r15 :: str\n    r16, r17 :: object\n    r18 :: object[1]\n    r19 :: object_ptr\n    r20 :: object\nL0:\n    r0 = builtins :: module\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 != r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = 'builtins'\n    r4 = PyImport_Import(r3)\n    builtins = r4 :: module\nL2:\n    r5 = __main__.globals :: static\n    r6 = 'x'\n    r7 = object 1\n    r8 = CPyDict_SetItem(r5, r6, r7)\n    r9 = r8 >= 0 :: signed\n    r10 = __main__.globals :: static\n    r11 = 'x'\n    r12 = CPyDict_GetItem(r10, r11)\n    r13 = unbox(int, r12)\n    r14 = builtins :: module\n    r15 = 'print'\n    r16 = CPyObject_GetAttr(r14, r15)\n    r17 = box(int, r13)\n    r18 = [r17]\n    r19 = load_address r18\n    r20 = PyObject_Vectorcall(r16, r19, 1, 0)\n    keep_alive r17\n    return 1\n\n[case testCallOverloaded]\nimport m\ndef f() -> str:\n    return m.f(1)\n[file m.pyi]\nfrom typing import overload\n@overload\ndef f(x: int) -> str: ...\n@overload\ndef f(x: str) -> int: ...\n[out]\ndef f():\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: str\nL0:\n    r0 = m :: module\n    r1 = 'f'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = object 1\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 1, 0)\n    keep_alive r3\n    r7 = cast(str, r6)\n    return r7\n\n[case testCallOverloadedNative]\nfrom typing import overload, Union\n\n@overload\ndef foo(x: int) -> int: ...\n\n@overload\ndef foo(x: str) -> str: ...\n\ndef foo(x: Union[int, str]) -> Union[int, str]:\n    return x\n\ndef main() -> None:\n    x = foo(0)\n[out]\ndef foo(x):\n    x :: union[int, str]\nL0:\n    return x\ndef main():\n    r0 :: object\n    r1 :: union[int, str]\n    r2, x :: int\nL0:\n    r0 = object 0\n    r1 = foo(r0)\n    r2 = unbox(int, r1)\n    x = r2\n    return 1\n\n[case testCallOverloadedNativeSubclass]\nfrom typing import overload, Union\n\nclass A:\n    x: int\nclass B(A):\n    y: int\n\n@overload\ndef foo(x: int) -> B: ...\n\n@overload\ndef foo(x: Union[int, str]) -> A: ...\n\ndef foo(x: Union[int, str]) -> A:\n    if isinstance(x, int):\n        return B()\n    return A()\n\ndef main() -> None:\n    x = foo(0)\n[out]\ndef foo(x):\n    x :: union[int, str]\n    r0 :: bit\n    r1 :: __main__.B\n    r2 :: __main__.A\nL0:\n    r0 = PyLong_Check(x)\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = B()\n    return r1\nL2:\n    r2 = A()\n    return r2\ndef main():\n    r0 :: object\n    r1 :: __main__.A\n    r2, x :: __main__.B\nL0:\n    r0 = object 0\n    r1 = foo(r0)\n    r2 = cast(__main__.B, r1)\n    x = r2\n    return 1\n\n[case testFunctionCallWithKeywordArgs]\ndef f(x: int, y: str) -> None: pass\n\ndef g() -> None:\n    f(y='a', x=0)\n    f(1, y='b')\n[out]\ndef f(x, y):\n    x :: int\n    y :: str\nL0:\n    return 1\ndef g():\n    r0 :: str\n    r1 :: None\n    r2 :: str\n    r3 :: None\nL0:\n    r0 = 'a'\n    r1 = f(0, r0)\n    r2 = 'b'\n    r3 = f(2, r2)\n    return 1\n\n[case testMethodCallWithKeywordArgs]\nclass A:\n    def f(self, x: int, y: str) -> None: pass\n\ndef g(a: A) -> None:\n    a.f(y='a', x=0)\n    a.f(1, y='b')\n[out]\ndef A.f(self, x, y):\n    self :: __main__.A\n    x :: int\n    y :: str\nL0:\n    return 1\ndef g(a):\n    a :: __main__.A\n    r0 :: str\n    r1 :: None\n    r2 :: str\n    r3 :: None\nL0:\n    r0 = 'a'\n    r1 = a.f(0, r0)\n    r2 = 'b'\n    r3 = a.f(2, r2)\n    return 1\n\n[case testStarArgs]\nfrom typing import Tuple\ndef f(a: int, b: int, c: int) -> Tuple[int, int, int]:\n    return a, b, c\ndef g() -> Tuple[int, int, int]:\n    return f(*(1, 2, 3))\ndef h() -> Tuple[int, int, int]:\n    return f(1, *(2, 3))\n[out]\ndef f(a, b, c):\n    a, b, c :: int\n    r0 :: tuple[int, int, int]\nL0:\n    r0 = (a, b, c)\n    return r0\ndef g():\n    r0 :: tuple[int, int, int]\n    r1 :: dict\n    r2 :: str\n    r3, r4, r5 :: object\n    r6 :: tuple[int, int, int]\nL0:\n    r0 = (2, 4, 6)\n    r1 = __main__.globals :: static\n    r2 = 'f'\n    r3 = CPyDict_GetItem(r1, r2)\n    r4 = box(tuple[int, int, int], r0)\n    r5 = PyObject_CallObject(r3, r4)\n    r6 = unbox(tuple[int, int, int], r5)\n    return r6\ndef h():\n    r0 :: tuple[int, int]\n    r1 :: dict\n    r2 :: str\n    r3 :: object\n    r4 :: list\n    r5 :: object\n    r6 :: ptr\n    r7, r8 :: object\n    r9 :: tuple\n    r10 :: object\n    r11 :: tuple[int, int, int]\nL0:\n    r0 = (4, 6)\n    r1 = __main__.globals :: static\n    r2 = 'f'\n    r3 = CPyDict_GetItem(r1, r2)\n    r4 = PyList_New(1)\n    r5 = object 1\n    r6 = list_items r4\n    buf_init_item r6, 0, r5\n    keep_alive r4\n    r7 = box(tuple[int, int], r0)\n    r8 = CPyList_Extend(r4, r7)\n    r9 = PyList_AsTuple(r4)\n    r10 = PyObject_CallObject(r3, r9)\n    r11 = unbox(tuple[int, int, int], r10)\n    return r11\n\n[case testStar2Args]\nfrom typing import Tuple\ndef f(a: int, b: int, c: int) -> Tuple[int, int, int]:\n    return a, b, c\ndef g() -> Tuple[int, int, int]:\n    return f(**{'a': 1, 'b': 2, 'c': 3})\ndef h() -> Tuple[int, int, int]:\n    return f(1, **{'b': 2, 'c': 3})\n[out]\ndef f(a, b, c):\n    a, b, c :: int\n    r0 :: tuple[int, int, int]\nL0:\n    r0 = (a, b, c)\n    return r0\ndef g():\n    r0, r1, r2 :: str\n    r3, r4, r5 :: object\n    r6, r7 :: dict\n    r8 :: str\n    r9 :: object\n    r10 :: tuple\n    r11 :: dict\n    r12 :: object\n    r13 :: tuple[int, int, int]\nL0:\n    r0 = 'a'\n    r1 = 'b'\n    r2 = 'c'\n    r3 = object 1\n    r4 = object 2\n    r5 = object 3\n    r6 = CPyDict_Build(3, r0, r3, r1, r4, r2, r5)\n    r7 = __main__.globals :: static\n    r8 = 'f'\n    r9 = CPyDict_GetItem(r7, r8)\n    r10 = CPyTuple_LoadEmptyTupleConstant()\n    r11 = PyDict_Copy(r6)\n    r12 = PyObject_Call(r9, r10, r11)\n    r13 = unbox(tuple[int, int, int], r12)\n    return r13\ndef h():\n    r0, r1 :: str\n    r2, r3 :: object\n    r4, r5 :: dict\n    r6 :: str\n    r7 :: object\n    r8 :: dict\n    r9 :: i32\n    r10 :: bit\n    r11 :: object\n    r12 :: tuple\n    r13 :: object\n    r14 :: tuple[int, int, int]\nL0:\n    r0 = 'b'\n    r1 = 'c'\n    r2 = object 2\n    r3 = object 3\n    r4 = CPyDict_Build(2, r0, r2, r1, r3)\n    r5 = __main__.globals :: static\n    r6 = 'f'\n    r7 = CPyDict_GetItem(r5, r6)\n    r8 = PyDict_New()\n    r9 = CPyDict_UpdateInDisplay(r8, r4)\n    r10 = r9 >= 0 :: signed\n    r11 = object 1\n    r12 = PyTuple_Pack(1, r11)\n    r13 = PyObject_Call(r7, r12, r8)\n    r14 = unbox(tuple[int, int, int], r13)\n    return r14\n\n[case testFunctionCallWithDefaultArgs]\ndef f(x: int, y: int = 3, z: str = \"test\") -> None:\n    return None\n\ndef g() -> None:\n    f(2)\n    f(y = 3, x = 6)\n[out]\ndef f(x, y, z):\n    x, y :: int\n    z, r0 :: str\nL0:\n    if is_error(y) goto L1 else goto L2\nL1:\n    y = 6\nL2:\n    if is_error(z) goto L3 else goto L4\nL3:\n    r0 = 'test'\n    z = r0\nL4:\n    return 1\ndef g():\n    r0 :: int\n    r1 :: str\n    r2 :: None\n    r3 :: str\n    r4 :: None\nL0:\n    r0 = <error> :: int\n    r1 = <error> :: str\n    r2 = f(4, r0, r1)\n    r3 = <error> :: str\n    r4 = f(12, 6, r3)\n    return 1\n\n[case testMethodCallWithDefaultArgs]\nclass A:\n    def f(self, x: int, y: int = 3, z: str = \"test\") -> None:\n        return None\n\ndef g() -> None:\n    a = A()\n    a.f(2)\n    a.f(y = 3, x = 6)\n[out]\ndef A.f(self, x, y, z):\n    self :: __main__.A\n    x, y :: int\n    z, r0 :: str\nL0:\n    if is_error(y) goto L1 else goto L2\nL1:\n    y = 6\nL2:\n    if is_error(z) goto L3 else goto L4\nL3:\n    r0 = 'test'\n    z = r0\nL4:\n    return 1\ndef g():\n    r0, a :: __main__.A\n    r1 :: int\n    r2 :: str\n    r3 :: None\n    r4 :: str\n    r5 :: None\nL0:\n    r0 = A()\n    a = r0\n    r1 = <error> :: int\n    r2 = <error> :: str\n    r3 = a.f(4, r1, r2)\n    r4 = <error> :: str\n    r5 = a.f(12, 6, r4)\n    return 1\n\n[case testListComprehension]\nfrom typing import List\n\ndef f() -> List[int]:\n    return [x*x for x in [1,2,3] if x != 2 if x != 3]\n[out]\ndef f():\n    r0, r1 :: list\n    r2, r3, r4 :: object\n    r5 :: ptr\n    r6, r7 :: native_int\n    r8 :: bit\n    r9 :: object\n    r10, x :: int\n    r11, r12 :: bit\n    r13 :: int\n    r14 :: object\n    r15 :: i32\n    r16 :: bit\n    r17 :: native_int\nL0:\n    r0 = PyList_New(0)\n    r1 = PyList_New(3)\n    r2 = object 1\n    r3 = object 2\n    r4 = object 3\n    r5 = list_items r1\n    buf_init_item r5, 0, r2\n    buf_init_item r5, 1, r3\n    buf_init_item r5, 2, r4\n    keep_alive r1\n    r6 = 0\nL1:\n    r7 = var_object_size r1\n    r8 = r6 < r7 :: signed\n    if r8 goto L2 else goto L8 :: bool\nL2:\n    r9 = list_get_item_unsafe r1, r6\n    r10 = unbox(int, r9)\n    x = r10\n    r11 = int_ne x, 4\n    if r11 goto L4 else goto L3 :: bool\nL3:\n    goto L7\nL4:\n    r12 = int_ne x, 6\n    if r12 goto L6 else goto L5 :: bool\nL5:\n    goto L7\nL6:\n    r13 = CPyTagged_Multiply(x, x)\n    r14 = box(int, r13)\n    r15 = PyList_Append(r0, r14)\n    r16 = r15 >= 0 :: signed\nL7:\n    r17 = r6 + 1\n    r6 = r17\n    goto L1\nL8:\n    return r0\n\n[case testDictComprehension]\nfrom typing import Dict\ndef f() -> Dict[int, int]:\n    return {x: x*x for x in [1,2,3] if x != 2 if x != 3}\n[out]\ndef f():\n    r0 :: dict\n    r1 :: list\n    r2, r3, r4 :: object\n    r5 :: ptr\n    r6, r7 :: native_int\n    r8 :: bit\n    r9 :: object\n    r10, x :: int\n    r11, r12 :: bit\n    r13 :: int\n    r14, r15 :: object\n    r16 :: i32\n    r17 :: bit\n    r18 :: native_int\nL0:\n    r0 = PyDict_New()\n    r1 = PyList_New(3)\n    r2 = object 1\n    r3 = object 2\n    r4 = object 3\n    r5 = list_items r1\n    buf_init_item r5, 0, r2\n    buf_init_item r5, 1, r3\n    buf_init_item r5, 2, r4\n    keep_alive r1\n    r6 = 0\nL1:\n    r7 = var_object_size r1\n    r8 = r6 < r7 :: signed\n    if r8 goto L2 else goto L8 :: bool\nL2:\n    r9 = list_get_item_unsafe r1, r6\n    r10 = unbox(int, r9)\n    x = r10\n    r11 = int_ne x, 4\n    if r11 goto L4 else goto L3 :: bool\nL3:\n    goto L7\nL4:\n    r12 = int_ne x, 6\n    if r12 goto L6 else goto L5 :: bool\nL5:\n    goto L7\nL6:\n    r13 = CPyTagged_Multiply(x, x)\n    r14 = box(int, x)\n    r15 = box(int, r13)\n    r16 = PyDict_SetItem(r0, r14, r15)\n    r17 = r16 >= 0 :: signed\nL7:\n    r18 = r6 + 1\n    r6 = r18\n    goto L1\nL8:\n    return r0\n\n[case testLoopsMultipleAssign]\nfrom typing import List, Tuple\ndef f(l: List[Tuple[int, int, int]]) -> List[int]:\n    for x, y, z in l:\n        pass\n    return [x+y+z for x, y, z in l]\n[out]\ndef f(l):\n    l :: list\n    r0, r1 :: native_int\n    r2 :: bit\n    r3 :: object\n    r4 :: tuple[int, int, int]\n    r5, x, r6, y, r7, z :: int\n    r8, r9 :: native_int\n    r10 :: list\n    r11, r12 :: native_int\n    r13 :: bit\n    r14 :: object\n    r15 :: tuple[int, int, int]\n    r16, x_2, r17, y_2, r18, z_2, r19, r20 :: int\n    r21 :: object\n    r22 :: native_int\nL0:\n    r0 = 0\nL1:\n    r1 = var_object_size l\n    r2 = r0 < r1 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = list_get_item_unsafe l, r0\n    r4 = unbox(tuple[int, int, int], r3)\n    r5 = r4[0]\n    x = r5\n    r6 = r4[1]\n    y = r6\n    r7 = r4[2]\n    z = r7\nL3:\n    r8 = r0 + 1\n    r0 = r8\n    goto L1\nL4:\n    r9 = var_object_size l\n    r10 = PyList_New(r9)\n    r11 = 0\nL5:\n    r12 = var_object_size l\n    r13 = r11 < r12 :: signed\n    if r13 goto L6 else goto L8 :: bool\nL6:\n    r14 = list_get_item_unsafe l, r11\n    r15 = unbox(tuple[int, int, int], r14)\n    r16 = r15[0]\n    x_2 = r16\n    r17 = r15[1]\n    y_2 = r17\n    r18 = r15[2]\n    z_2 = r18\n    r19 = CPyTagged_Add(x_2, y_2)\n    r20 = CPyTagged_Add(r19, z_2)\n    r21 = box(int, r20)\n    CPyList_SetItemUnsafe(r10, r11, r21)\nL7:\n    r22 = r11 + 1\n    r11 = r22\n    goto L5\nL8:\n    return r10\n\n[case testProperty]\nclass PropertyHolder:\n    @property\n    def value(self) -> int:\n        return self.left + self.right if self.is_add else self.left - self.right\n    def __init__(self, left: int, right: int, is_add: bool) -> None:\n        self.left = left\n        self.right = right\n        self.is_add = is_add\n    def twice_value(self) -> int:\n        return 2 * self.value\n[out]\ndef PropertyHolder.value(self):\n    self :: __main__.PropertyHolder\n    r0 :: bool\n    r1, r2, r3, r4, r5, r6, r7 :: int\nL0:\n    r0 = self.is_add\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = borrow self.left\n    r2 = borrow self.right\n    r3 = CPyTagged_Add(r1, r2)\n    keep_alive self, self\n    r4 = r3\n    goto L3\nL2:\n    r5 = borrow self.left\n    r6 = borrow self.right\n    r7 = CPyTagged_Subtract(r5, r6)\n    keep_alive self, self\n    r4 = r7\nL3:\n    return r4\ndef PropertyHolder.__init__(self, left, right, is_add):\n    self :: __main__.PropertyHolder\n    left, right :: int\n    is_add :: bool\nL0:\n    self.left = left\n    self.right = right\n    self.is_add = is_add\n    return 1\ndef PropertyHolder.twice_value(self):\n    self :: __main__.PropertyHolder\n    r0, r1 :: int\nL0:\n    r0 = self.value\n    r1 = CPyTagged_Multiply(4, r0)\n    return r1\n\n[case testNativeIndex]\nfrom typing import List\nclass A:\n    def __getitem__(self, index: int) -> int: pass\n\ndef g(a: A, b: List[int], c: int) -> int:\n    return a[c] + b[c]\n[out]\ndef A.__getitem__(self, index):\n    self :: __main__.A\n    index :: int\nL0:\n    unreachable\ndef g(a, b, c):\n    a :: __main__.A\n    b :: list\n    c, r0 :: int\n    r1 :: object\n    r2, r3 :: int\nL0:\n    r0 = a.__getitem__(c)\n    r1 = CPyList_GetItemBorrow(b, c)\n    r2 = unbox(int, r1)\n    r3 = CPyTagged_Add(r0, r2)\n    keep_alive b, c\n    return r3\n\n[case testTypeAlias_toplevel]\nfrom typing import List, NewType, NamedTuple\nLol = NamedTuple('Lol', (('a', int), ('b', str)))\nx = Lol(1, '')\nFoo = List[int]\nBar = NewType('Bar', Foo)\ny = Bar([1,2,3])\n[out]\ndef __top_level__():\n    r0, r1 :: object\n    r2 :: bit\n    r3 :: str\n    r4, r5 :: object\n    r6 :: str\n    r7 :: dict\n    r8 :: object\n    r9, r10 :: str\n    r11 :: object\n    r12 :: tuple[str, object]\n    r13 :: object\n    r14 :: str\n    r15 :: object\n    r16 :: tuple[str, object]\n    r17 :: object\n    r18 :: tuple[object, object]\n    r19 :: object\n    r20 :: dict\n    r21 :: str\n    r22 :: object\n    r23 :: object[2]\n    r24 :: object_ptr\n    r25 :: object\n    r26 :: dict\n    r27 :: str\n    r28 :: i32\n    r29 :: bit\n    r30 :: str\n    r31 :: dict\n    r32 :: str\n    r33, r34 :: object\n    r35 :: object[2]\n    r36 :: object_ptr\n    r37 :: object\n    r38 :: tuple\n    r39 :: dict\n    r40 :: str\n    r41 :: i32\n    r42 :: bit\n    r43 :: dict\n    r44 :: str\n    r45, r46, r47 :: object\n    r48 :: dict\n    r49 :: str\n    r50 :: i32\n    r51 :: bit\n    r52 :: str\n    r53 :: dict\n    r54 :: str\n    r55 :: object\n    r56 :: dict\n    r57 :: str\n    r58 :: object\n    r59 :: object[2]\n    r60 :: object_ptr\n    r61 :: object\n    r62 :: dict\n    r63 :: str\n    r64 :: i32\n    r65 :: bit\n    r66 :: list\n    r67, r68, r69 :: object\n    r70 :: ptr\n    r71 :: dict\n    r72 :: str\n    r73 :: i32\n    r74 :: bit\nL0:\n    r0 = builtins :: module\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 != r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = 'builtins'\n    r4 = PyImport_Import(r3)\n    builtins = r4 :: module\nL2:\n    r5 = ('List', 'NewType', 'NamedTuple')\n    r6 = 'typing'\n    r7 = __main__.globals :: static\n    r8 = CPyImport_ImportFromMany(r6, r5, r5, r7)\n    typing = r8 :: module\n    r9 = 'Lol'\n    r10 = 'a'\n    r11 = load_address PyLong_Type\n    r12 = (r10, r11)\n    r13 = box(tuple[str, object], r12)\n    r14 = 'b'\n    r15 = load_address PyUnicode_Type\n    r16 = (r14, r15)\n    r17 = box(tuple[str, object], r16)\n    r18 = (r13, r17)\n    r19 = box(tuple[object, object], r18)\n    r20 = __main__.globals :: static\n    r21 = 'NamedTuple'\n    r22 = CPyDict_GetItem(r20, r21)\n    r23 = [r9, r19]\n    r24 = load_address r23\n    r25 = PyObject_Vectorcall(r22, r24, 2, 0)\n    keep_alive r9, r19\n    r26 = __main__.globals :: static\n    r27 = 'Lol'\n    r28 = CPyDict_SetItem(r26, r27, r25)\n    r29 = r28 >= 0 :: signed\n    r30 = ''\n    r31 = __main__.globals :: static\n    r32 = 'Lol'\n    r33 = CPyDict_GetItem(r31, r32)\n    r34 = object 1\n    r35 = [r34, r30]\n    r36 = load_address r35\n    r37 = PyObject_Vectorcall(r33, r36, 2, 0)\n    keep_alive r34, r30\n    r38 = cast(tuple, r37)\n    r39 = __main__.globals :: static\n    r40 = 'x'\n    r41 = CPyDict_SetItem(r39, r40, r38)\n    r42 = r41 >= 0 :: signed\n    r43 = __main__.globals :: static\n    r44 = 'List'\n    r45 = CPyDict_GetItem(r43, r44)\n    r46 = load_address PyLong_Type\n    r47 = PyObject_GetItem(r45, r46)\n    r48 = __main__.globals :: static\n    r49 = 'Foo'\n    r50 = CPyDict_SetItem(r48, r49, r47)\n    r51 = r50 >= 0 :: signed\n    r52 = 'Bar'\n    r53 = __main__.globals :: static\n    r54 = 'Foo'\n    r55 = CPyDict_GetItem(r53, r54)\n    r56 = __main__.globals :: static\n    r57 = 'NewType'\n    r58 = CPyDict_GetItem(r56, r57)\n    r59 = [r52, r55]\n    r60 = load_address r59\n    r61 = PyObject_Vectorcall(r58, r60, 2, 0)\n    keep_alive r52, r55\n    r62 = __main__.globals :: static\n    r63 = 'Bar'\n    r64 = CPyDict_SetItem(r62, r63, r61)\n    r65 = r64 >= 0 :: signed\n    r66 = PyList_New(3)\n    r67 = object 1\n    r68 = object 2\n    r69 = object 3\n    r70 = list_items r66\n    buf_init_item r70, 0, r67\n    buf_init_item r70, 1, r68\n    buf_init_item r70, 2, r69\n    keep_alive r66\n    r71 = __main__.globals :: static\n    r72 = 'y'\n    r73 = CPyDict_SetItem(r71, r72, r66)\n    r74 = r73 >= 0 :: signed\n    return 1\n\n[case testChainedConditional]\ndef g(x: int) -> int:\n    return x\ndef f(x: int, y: int, z: int) -> bool:\n    return g(x) < g(y) > g(z)\n[out]\ndef g(x):\n    x :: int\nL0:\n    return x\ndef f(x, y, z):\n    x, y, z, r0, r1 :: int\n    r2 :: bit\n    r3 :: bool\n    r4 :: int\n    r5 :: bit\nL0:\n    r0 = g(x)\n    r1 = g(y)\n    r2 = int_lt r0, r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = r2\n    goto L3\nL2:\n    r4 = g(z)\n    r5 = int_gt r1, r4\n    r3 = r5\nL3:\n    return r3\n\n[case testEq]\nclass A:\n    def __eq__(self, x: object) -> bool:\n        return NotImplemented\n[out]\ndef A.__eq__(self, x):\n    self :: __main__.A\n    x, r0 :: object\nL0:\n    r0 = load_address _Py_NotImplementedStruct\n    return r0\ndef A.__ne__(__mypyc_self__, rhs):\n    __mypyc_self__ :: __main__.A\n    rhs, r0, r1 :: object\n    r2 :: bit\n    r3 :: object\n    r4, r5 :: bit\n    r6 :: object\n    r7 :: bit\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11 :: object\nL0:\n    r0 = __mypyc_self__.__eq__(rhs)\n    r1 = load_address _Py_NotImplementedStruct\n    r2 = r0 == r1\n    if r2 goto L7 else goto L1 :: bool\nL1:\n    r3 = load_global Py_True :: static\n    r4 = r0 == r3\n    if r4 goto L2 else goto L3 :: bool\nL2:\n    r5 = 0\n    goto L6\nL3:\n    r6 = load_global Py_False :: static\n    r7 = r0 == r6\n    if r7 goto L4 else goto L5 :: bool\nL4:\n    r5 = 1\n    goto L6\nL5:\n    r8 = PyObject_Not(r0)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    r5 = r10\nL6:\n    r11 = box(bit, r5)\n    return r11\nL7:\n    return r1\n\n[case testDecorators_toplevel]\nfrom typing import Callable\n\ndef a(f: Callable[[], None]) -> Callable[[], None]:\n    def g() -> None:\n        print('Entering')\n        f()\n        print('Exited')\n    return g\n\ndef b(f: Callable[[], None]) -> Callable[[], None]:\n    def g() -> None:\n        print('---')\n        f()\n        print('---')\n    return g\n\n@a\n@b\ndef c() -> None:\n    @a\n    @b\n    def d() -> None:\n        print('d')\n    print('c')\n    d()\n\n[out]\ndef g_a_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef g_a_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.g_a_obj\n    r0 :: __main__.a_env\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7, r8, r9 :: object\n    r10 :: str\n    r11 :: object\n    r12 :: str\n    r13 :: object\n    r14 :: object[1]\n    r15 :: object_ptr\n    r16 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = 'Entering'\n    r2 = builtins :: module\n    r3 = 'print'\n    r4 = CPyObject_GetAttr(r2, r3)\n    r5 = [r1]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r4, r6, 1, 0)\n    keep_alive r1\n    r8 = r0.f\n    r9 = PyObject_Vectorcall(r8, 0, 0, 0)\n    r10 = 'Exited'\n    r11 = builtins :: module\n    r12 = 'print'\n    r13 = CPyObject_GetAttr(r11, r12)\n    r14 = [r10]\n    r15 = load_address r14\n    r16 = PyObject_Vectorcall(r13, r15, 1, 0)\n    keep_alive r10\n    return 1\ndef a(f):\n    f :: object\n    r0 :: __main__.a_env\n    r1 :: bool\n    r2 :: __main__.g_a_obj\n    r3 :: bool\n    g :: object\nL0:\n    r0 = a_env()\n    r0.f = f; r1 = is_error\n    r2 = g_a_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    g = r2\n    return g\ndef g_b_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef g_b_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.g_b_obj\n    r0 :: __main__.b_env\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7, r8, r9 :: object\n    r10 :: str\n    r11 :: object\n    r12 :: str\n    r13 :: object\n    r14 :: object[1]\n    r15 :: object_ptr\n    r16 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = '---'\n    r2 = builtins :: module\n    r3 = 'print'\n    r4 = CPyObject_GetAttr(r2, r3)\n    r5 = [r1]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r4, r6, 1, 0)\n    keep_alive r1\n    r8 = r0.f\n    r9 = PyObject_Vectorcall(r8, 0, 0, 0)\n    r10 = '---'\n    r11 = builtins :: module\n    r12 = 'print'\n    r13 = CPyObject_GetAttr(r11, r12)\n    r14 = [r10]\n    r15 = load_address r14\n    r16 = PyObject_Vectorcall(r13, r15, 1, 0)\n    keep_alive r10\n    return 1\ndef b(f):\n    f :: object\n    r0 :: __main__.b_env\n    r1 :: bool\n    r2 :: __main__.g_b_obj\n    r3 :: bool\n    g :: object\nL0:\n    r0 = b_env()\n    r0.f = f; r1 = is_error\n    r2 = g_b_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    g = r2\n    return g\ndef d_c_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef d_c_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.d_c_obj\n    r0 :: __main__.c_env\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = 'd'\n    r2 = builtins :: module\n    r3 = 'print'\n    r4 = CPyObject_GetAttr(r2, r3)\n    r5 = [r1]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r4, r6, 1, 0)\n    keep_alive r1\n    return 1\ndef c():\n    r0 :: __main__.c_env\n    r1 :: __main__.d_c_obj\n    r2 :: bool\n    r3 :: dict\n    r4 :: str\n    r5 :: object\n    r6 :: object[1]\n    r7 :: object_ptr\n    r8 :: object\n    r9 :: dict\n    r10 :: str\n    r11 :: object\n    r12 :: object[1]\n    r13 :: object_ptr\n    r14, d :: object\n    r15 :: dict\n    r16 :: str\n    r17 :: i32\n    r18 :: bit\n    r19 :: str\n    r20 :: object\n    r21 :: str\n    r22 :: object\n    r23 :: object[1]\n    r24 :: object_ptr\n    r25, r26 :: object\nL0:\n    r0 = c_env()\n    r1 = d_c_obj()\n    r1.__mypyc_env__ = r0; r2 = is_error\n    r3 = __main__.globals :: static\n    r4 = 'b'\n    r5 = CPyDict_GetItem(r3, r4)\n    r6 = [r1]\n    r7 = load_address r6\n    r8 = PyObject_Vectorcall(r5, r7, 1, 0)\n    keep_alive r1\n    r9 = __main__.globals :: static\n    r10 = 'a'\n    r11 = CPyDict_GetItem(r9, r10)\n    r12 = [r8]\n    r13 = load_address r12\n    r14 = PyObject_Vectorcall(r11, r13, 1, 0)\n    keep_alive r8\n    d = r14\n    r15 = __main__.globals :: static\n    r16 = 'd'\n    r17 = PyDict_SetItem(r15, r16, r14)\n    r18 = r17 >= 0 :: signed\n    r19 = 'c'\n    r20 = builtins :: module\n    r21 = 'print'\n    r22 = CPyObject_GetAttr(r20, r21)\n    r23 = [r19]\n    r24 = load_address r23\n    r25 = PyObject_Vectorcall(r22, r24, 1, 0)\n    keep_alive r19\n    r26 = PyObject_Vectorcall(d, 0, 0, 0)\n    return 1\ndef __top_level__():\n    r0, r1 :: object\n    r2 :: bit\n    r3 :: str\n    r4, r5 :: object\n    r6 :: str\n    r7 :: dict\n    r8 :: object\n    r9 :: dict\n    r10 :: str\n    r11 :: object\n    r12 :: dict\n    r13 :: str\n    r14 :: object\n    r15 :: object[1]\n    r16 :: object_ptr\n    r17 :: object\n    r18 :: dict\n    r19 :: str\n    r20 :: object\n    r21 :: object[1]\n    r22 :: object_ptr\n    r23 :: object\n    r24 :: dict\n    r25 :: str\n    r26 :: i32\n    r27 :: bit\nL0:\n    r0 = builtins :: module\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 != r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = 'builtins'\n    r4 = PyImport_Import(r3)\n    builtins = r4 :: module\nL2:\n    r5 = ('Callable',)\n    r6 = 'typing'\n    r7 = __main__.globals :: static\n    r8 = CPyImport_ImportFromMany(r6, r5, r5, r7)\n    typing = r8 :: module\n    r9 = __main__.globals :: static\n    r10 = 'c'\n    r11 = CPyDict_GetItem(r9, r10)\n    r12 = __main__.globals :: static\n    r13 = 'b'\n    r14 = CPyDict_GetItem(r12, r13)\n    r15 = [r11]\n    r16 = load_address r15\n    r17 = PyObject_Vectorcall(r14, r16, 1, 0)\n    keep_alive r11\n    r18 = __main__.globals :: static\n    r19 = 'a'\n    r20 = CPyDict_GetItem(r18, r19)\n    r21 = [r17]\n    r22 = load_address r21\n    r23 = PyObject_Vectorcall(r20, r22, 1, 0)\n    keep_alive r17\n    r24 = __main__.globals :: static\n    r25 = 'c'\n    r26 = PyDict_SetItem(r24, r25, r23)\n    r27 = r26 >= 0 :: signed\n    return 1\n\n[case testDecoratorsSimple_toplevel]\nfrom typing import Callable\n\ndef a(f: Callable[[], None]) -> Callable[[], None]:\n    def g() -> None:\n        print('Entering')\n        f()\n        print('Exited')\n    return g\n\n[out]\ndef g_a_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef g_a_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.g_a_obj\n    r0 :: __main__.a_env\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7, r8, r9 :: object\n    r10 :: str\n    r11 :: object\n    r12 :: str\n    r13 :: object\n    r14 :: object[1]\n    r15 :: object_ptr\n    r16 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = 'Entering'\n    r2 = builtins :: module\n    r3 = 'print'\n    r4 = CPyObject_GetAttr(r2, r3)\n    r5 = [r1]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r4, r6, 1, 0)\n    keep_alive r1\n    r8 = r0.f\n    r9 = PyObject_Vectorcall(r8, 0, 0, 0)\n    r10 = 'Exited'\n    r11 = builtins :: module\n    r12 = 'print'\n    r13 = CPyObject_GetAttr(r11, r12)\n    r14 = [r10]\n    r15 = load_address r14\n    r16 = PyObject_Vectorcall(r13, r15, 1, 0)\n    keep_alive r10\n    return 1\ndef a(f):\n    f :: object\n    r0 :: __main__.a_env\n    r1 :: bool\n    r2 :: __main__.g_a_obj\n    r3 :: bool\n    g :: object\nL0:\n    r0 = a_env()\n    r0.f = f; r1 = is_error\n    r2 = g_a_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    g = r2\n    return g\ndef __top_level__():\n    r0, r1 :: object\n    r2 :: bit\n    r3 :: str\n    r4, r5 :: object\n    r6 :: str\n    r7 :: dict\n    r8 :: object\nL0:\n    r0 = builtins :: module\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 != r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = 'builtins'\n    r4 = PyImport_Import(r3)\n    builtins = r4 :: module\nL2:\n    r5 = ('Callable',)\n    r6 = 'typing'\n    r7 = __main__.globals :: static\n    r8 = CPyImport_ImportFromMany(r6, r5, r5, r7)\n    typing = r8 :: module\n    return 1\n\n[case testAnyAllG]\nfrom typing import Iterable\n\ndef call_any(l: Iterable[int]) -> bool:\n    return any(i == 0 for i in l)\n\ndef call_all(l: Iterable[int]) -> bool:\n    return all(i == 0 for i in l)\n\n[out]\ndef call_any(l):\n    l :: object\n    r0 :: bool\n    r1, r2 :: object\n    r3, i :: int\n    r4, r5 :: bit\nL0:\n    r0 = 0\n    r1 = PyObject_GetIter(l)\nL1:\n    r2 = PyIter_Next(r1)\n    if is_error(r2) goto L6 else goto L2\nL2:\n    r3 = unbox(int, r2)\n    i = r3\n    r4 = int_eq i, 0\n    if r4 goto L3 else goto L4 :: bool\nL3:\n    r0 = 1\n    goto L8\nL4:\nL5:\n    goto L1\nL6:\n    r5 = CPy_NoErrOccurred()\nL7:\nL8:\n    return r0\ndef call_all(l):\n    l :: object\n    r0 :: bool\n    r1, r2 :: object\n    r3, i :: int\n    r4, r5, r6 :: bit\nL0:\n    r0 = 1\n    r1 = PyObject_GetIter(l)\nL1:\n    r2 = PyIter_Next(r1)\n    if is_error(r2) goto L6 else goto L2\nL2:\n    r3 = unbox(int, r2)\n    i = r3\n    r4 = int_eq i, 0\n    r5 = r4 ^ 1\n    if r5 goto L3 else goto L4 :: bool\nL3:\n    r0 = 0\n    goto L8\nL4:\nL5:\n    goto L1\nL6:\n    r6 = CPy_NoErrOccurred()\nL7:\nL8:\n    return r0\n\n[case testSum]\nfrom typing import Callable, Iterable\n\ndef call_sum(l: Iterable[int], comparison: Callable[[int], bool]) -> int:\n    return sum(comparison(x) for x in l)\n\n[out]\ndef call_sum(l, comparison):\n    l, comparison :: object\n    r0 :: int\n    r1, r2 :: object\n    r3, x :: int\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7 :: object\n    r8, r9 :: bool\n    r10, r11 :: int\n    r12 :: bit\nL0:\n    r0 = 0\n    r1 = PyObject_GetIter(l)\nL1:\n    r2 = PyIter_Next(r1)\n    if is_error(r2) goto L4 else goto L2\nL2:\n    r3 = unbox(int, r2)\n    x = r3\n    r4 = box(int, x)\n    r5 = [r4]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(comparison, r6, 1, 0)\n    keep_alive r4\n    r8 = unbox(bool, r7)\n    r9 = r8 << 1\n    r10 = extend r9: builtins.bool to builtins.int\n    r11 = CPyTagged_Add(r0, r10)\n    r0 = r11\nL3:\n    goto L1\nL4:\n    r12 = CPy_NoErrOccurred()\nL5:\n    return r0\n\n[case testSetAttr1]\nfrom typing import Any, Dict, List\ndef lol(x: Any):\n    setattr(x, 'x', '5')\n\n[out]\ndef lol(x):\n    x :: object\n    r0, r1 :: str\n    r2 :: i32\n    r3 :: bit\n    r4 :: object\nL0:\n    r0 = 'x'\n    r1 = '5'\n    r2 = PyObject_SetAttr(x, r0, r1)\n    r3 = r2 >= 0 :: signed\n    r4 = box(None, 1)\n    return r4\n\n[case testFinalModuleInt]\nfrom typing import Final\n\nx: Final = 1\ny: Final = 2\n\ndef f(a: bool) -> int:\n    if a:\n        return x\n    else:\n        return y\n[out]\ndef f(a):\n    a :: bool\nL0:\n    if a goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 4\nL3:\n    unreachable\n\n[case testFinalModuleStr]\nfrom typing import Final\n\nx: Final = 'x'\ny: Final = 'y'\n\ndef f(a: bool) -> str:\n    if a:\n        return x\n    else:\n        return y\n[out]\ndef f(a):\n    a :: bool\n    r0, r1 :: str\nL0:\n    if a goto L1 else goto L2 :: bool\nL1:\n    r0 = 'x'\n    return r0\nL2:\n    r1 = 'y'\n    return r1\nL3:\n    unreachable\n\n[case testFinalModuleBool]\nfrom typing import Final\n\nx: Final = True\ny: Final = False\n\ndef f(a: bool) -> bool:\n    if a:\n        return x\n    else:\n        return y\n[out]\ndef f(a):\n    a :: bool\nL0:\n    if a goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    return 0\nL3:\n    unreachable\n\n[case testFinalClass]\nfrom typing import Final\n\nclass C:\n    x: Final = 1\n    y: Final = 2\n\ndef f(a: bool) -> int:\n    if a:\n        return C.x\n    else:\n        return C.y\n[out]\ndef C.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.C\nL0:\n    __mypyc_self__.x = 2\n    __mypyc_self__.y = 4\n    return 1\ndef f(a):\n    a :: bool\nL0:\n    if a goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 4\nL3:\n    unreachable\n\n[case testFinalStaticList]\nfrom typing import Final\n\nx: Final = [1]\n\ndef f() -> int:\n    return x[0]\n[out]\ndef f():\n    r0 :: list\n    r1 :: bool\n    r2 :: object\n    r3 :: int\nL0:\n    r0 = __main__.x :: static\n    if is_error(r0) goto L1 else goto L2\nL1:\n    r1 = raise NameError('value for final name \"x\" was not set')\n    unreachable\nL2:\n    r2 = CPyList_GetItemShort(r0, 0)\n    r3 = unbox(int, r2)\n    return r3\n\n[case testFinalStaticTuple]\nfrom typing import Final\n\nx: Final = (1, 2)\n\ndef f() -> int:\n    return x[0]\n[out]\ndef f():\n    r0 :: tuple[int, int]\n    r1 :: bool\n    r2 :: int\nL0:\n    r0 = __main__.x :: static\n    if is_error(r0) goto L1 else goto L2\nL1:\n    r1 = raise NameError('value for final name \"x\" was not set')\n    unreachable\nL2:\n    r2 = r0[0]\n    return r2\n\n[case testFinalStaticInt]\nfrom typing import Final\n\nx: Final = 1 + int()\n\ndef f() -> int:\n    return x - 1\n[out]\ndef f():\n    r0 :: int\n    r1 :: bool\n    r2 :: int\nL0:\n    r0 = __main__.x :: static\n    if is_error(r0) goto L1 else goto L2\nL1:\n    r1 = raise NameError('value for final name \"x\" was not set')\n    unreachable\nL2:\n    r2 = CPyTagged_Subtract(r0, 2)\n    return r2\n\n[case testFinalRestrictedTypeVar]\nfrom typing import TypeVar\nif False:\n    from typing import Final\n\nFOO = 10  # type: Final\n\nTarg = TypeVar('Targ', int, str)\ndef foo(z: Targ) -> None:\n    FOO\n[out]\ndef foo(z):\n    z :: object\nL0:\n    return 1\n\n[case testFinalLocals]\nfrom typing import Final\n\ndef inlined() -> str:\n    # XXX: the final type must be declared explicitly for Var.final_value to be set.\n    const: Final[str] = \"Oppenheimer\"\n    return const\n\ndef local() -> str:\n    const: Final[str] = inlined()\n    return const\n[out]\ndef inlined():\n    r0, const, r1 :: str\nL0:\n    r0 = 'Oppenheimer'\n    const = r0\n    r1 = 'Oppenheimer'\n    return r1\ndef local():\n    r0, const :: str\nL0:\n    r0 = inlined()\n    const = r0\n    return const\n\n[case testDirectlyCall__bool__]\nclass A:\n    def __bool__(self) -> bool:\n        return True\nclass B(A):\n    def __bool__(self) -> bool:\n        return False\n\ndef lol(x: A) -> int:\n    if x:\n        return 1\n    else:\n        return 0\n\n[out]\ndef A.__bool__(self):\n    self :: __main__.A\nL0:\n    return 1\ndef B.__bool__(self):\n    self :: __main__.B\nL0:\n    return 0\ndef lol(x):\n    x :: __main__.A\n    r0 :: bool\nL0:\n    r0 = x.__bool__()\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 0\nL3:\n    unreachable\n\n[case testRevealType]\ndef f(x: int) -> None:\n    reveal_type(x)  # type: ignore\n[out]\ndef f(x):\n    x :: int\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'reveal_type'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = box(int, x)\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 1, 0)\n    keep_alive r3\n    return 1\n\n[case testCallCWithStrJoinMethod]\nfrom typing import List\ndef f(x: str, y: List[str]) -> str:\n    return x.join(y)\n[out]\ndef f(x, y):\n    x :: str\n    y :: list\n    r0 :: str\nL0:\n    r0 = PyUnicode_Join(x, y)\n    return r0\n\n[case testCallCWithToListFunction]\nfrom typing import List, Iterable, Tuple, Dict\n# generic object\ndef f(x: Iterable[int]) -> List[int]:\n    return list(x)\n\n# need coercing\ndef g(x: Tuple[int, int, int]) -> List[int]:\n    return list(x)\n\n# non-list object\ndef h(x: Dict[int, str]) -> List[int]:\n    return list(x)\n\n[out]\ndef f(x):\n    x :: object\n    r0 :: list\nL0:\n    r0 = PySequence_List(x)\n    return r0\ndef g(x):\n    x :: tuple[int, int, int]\n    r0 :: object\n    r1 :: list\nL0:\n    r0 = box(tuple[int, int, int], x)\n    r1 = PySequence_List(r0)\n    return r1\ndef h(x):\n    x :: dict\n    r0 :: list\nL0:\n    r0 = PySequence_List(x)\n    return r0\n\n[case testBoolFunction]\ndef f(x: object) -> bool:\n    return bool(x)\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: bool\nL0:\n    r0 = PyObject_IsTrue(x)\n    r1 = r0 >= 0 :: signed\n    r2 = truncate r0: i32 to builtins.bool\n    return r2\n\n[case testLocalImports]\ndef root() -> None:\n    import dataclasses\n    import enum\n\ndef submodule() -> int:\n    import p.m\n    return p.x\n[file p/__init__.py]\nx = 1\n[file p/m.py]\n[out]\ndef root():\n    r0 :: dict\n    r1, r2 :: object\n    r3 :: bit\n    r4 :: str\n    r5 :: object\n    r6 :: str\n    r7 :: dict\n    r8 :: str\n    r9 :: object\n    r10 :: i32\n    r11 :: bit\n    r12 :: dict\n    r13, r14 :: object\n    r15 :: bit\n    r16 :: str\n    r17 :: object\n    r18 :: str\n    r19 :: dict\n    r20 :: str\n    r21 :: object\n    r22 :: i32\n    r23 :: bit\nL0:\n    r0 = __main__.globals :: static\n    r1 = dataclasses :: module\n    r2 = load_address _Py_NoneStruct\n    r3 = r1 != r2\n    if r3 goto L2 else goto L1 :: bool\nL1:\n    r4 = 'dataclasses'\n    r5 = PyImport_Import(r4)\n    dataclasses = r5 :: module\nL2:\n    r6 = 'dataclasses'\n    r7 = PyImport_GetModuleDict()\n    r8 = 'dataclasses'\n    r9 = CPyDict_GetItem(r7, r8)\n    r10 = CPyDict_SetItem(r0, r6, r9)\n    r11 = r10 >= 0 :: signed\n    r12 = __main__.globals :: static\n    r13 = enum :: module\n    r14 = load_address _Py_NoneStruct\n    r15 = r13 != r14\n    if r15 goto L4 else goto L3 :: bool\nL3:\n    r16 = 'enum'\n    r17 = PyImport_Import(r16)\n    enum = r17 :: module\nL4:\n    r18 = 'enum'\n    r19 = PyImport_GetModuleDict()\n    r20 = 'enum'\n    r21 = CPyDict_GetItem(r19, r20)\n    r22 = CPyDict_SetItem(r12, r18, r21)\n    r23 = r22 >= 0 :: signed\n    return 1\ndef submodule():\n    r0 :: dict\n    r1, r2 :: object\n    r3 :: bit\n    r4 :: str\n    r5 :: object\n    r6 :: str\n    r7 :: dict\n    r8 :: str\n    r9 :: object\n    r10 :: i32\n    r11 :: bit\n    r12 :: dict\n    r13 :: str\n    r14 :: object\n    r15 :: str\n    r16 :: object\n    r17 :: int\nL0:\n    r0 = __main__.globals :: static\n    r1 = p.m :: module\n    r2 = load_address _Py_NoneStruct\n    r3 = r1 != r2\n    if r3 goto L2 else goto L1 :: bool\nL1:\n    r4 = 'p.m'\n    r5 = PyImport_Import(r4)\n    p.m = r5 :: module\nL2:\n    r6 = 'p'\n    r7 = PyImport_GetModuleDict()\n    r8 = 'p'\n    r9 = CPyDict_GetItem(r7, r8)\n    r10 = CPyDict_SetItem(r0, r6, r9)\n    r11 = r10 >= 0 :: signed\n    r12 = PyImport_GetModuleDict()\n    r13 = 'p'\n    r14 = CPyDict_GetItem(r12, r13)\n    r15 = 'x'\n    r16 = CPyObject_GetAttr(r14, r15)\n    r17 = unbox(int, r16)\n    return r17\n\n[case testIsinstanceBool]\ndef f(x: object) -> bool:\n    return isinstance(x, bool)\n[out]\ndef f(x):\n    x :: object\n    r0 :: bit\nL0:\n    r0 = PyBool_Check(x)\n    return r0\n\n[case testRangeObject]\ndef range_object() -> None:\n    r = range(4, 12, 2)\n    sum = 0\n    for i in r:\n        sum += i\n\ndef range_in_loop() -> None:\n    sum = 0\n    for i in range(4, 12, 2):\n        sum += i\n[out]\ndef range_object():\n    r0, r1, r2, r3 :: object\n    r4 :: object[3]\n    r5 :: object_ptr\n    r6 :: object\n    r7, r :: range\n    sum :: int\n    r8, r9 :: object\n    r10, i, r11 :: int\n    r12 :: bit\nL0:\n    r0 = load_address PyRange_Type\n    r1 = object 4\n    r2 = object 12\n    r3 = object 2\n    r4 = [r1, r2, r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r0, r5, 3, 0)\n    keep_alive r1, r2, r3\n    r7 = cast(range, r6)\n    r = r7\n    sum = 0\n    r8 = PyObject_GetIter(r)\nL1:\n    r9 = PyIter_Next(r8)\n    if is_error(r9) goto L4 else goto L2\nL2:\n    r10 = unbox(int, r9)\n    i = r10\n    r11 = CPyTagged_Add(sum, i)\n    sum = r11\nL3:\n    goto L1\nL4:\n    r12 = CPy_NoErrOccurred()\nL5:\n    return 1\ndef range_in_loop():\n    sum :: int\n    r0 :: short_int\n    i :: int\n    r1 :: bit\n    r2 :: int\n    r3 :: short_int\nL0:\n    sum = 0\n    r0 = 8\n    i = r0\nL1:\n    r1 = int_lt r0, 24\n    if r1 goto L2 else goto L4 :: bool\nL2:\n    r2 = CPyTagged_Add(sum, i)\n    sum = r2\nL3:\n    r3 = r0 + 4\n    r0 = r3\n    i = r3\n    goto L1\nL4:\n    return 1\n\n[case testLocalRedefinition]\n# mypy: allow-redefinition-old\ndef f() -> None:\n    i = 0\n    i += 1\n    i = \"foo\"\n    i += i\n    i = 0.0\n[out]\ndef f():\n    i, r0 :: int\n    r1, i__redef__, r2 :: str\n    i__redef____redef__ :: float\nL0:\n    i = 0\n    r0 = CPyTagged_Add(i, 2)\n    i = r0\n    r1 = 'foo'\n    i__redef__ = r1\n    r2 = CPyStr_Append(i__redef__, i__redef__)\n    i__redef__ = r2\n    i__redef____redef__ = 0.0\n    return 1\n\n[case testNewType]\nfrom typing import NewType\n\nclass A: pass\n\nN = NewType(\"N\", A)\n\ndef f(arg: A) -> N:\n    return N(arg)\n[out]\ndef f(arg):\n    arg :: __main__.A\nL0:\n    return arg\n\n[case testTypeCheckingFlag]\nfrom typing import TYPE_CHECKING, List\n\ndef f(arg: List[int]) -> int:\n    if TYPE_CHECKING:\n        from collections.abc import Sized\n    s: Sized = arg\n    return len(s)\n\n[out]\ndef f(arg):\n    arg :: list\n    r0 :: bool\n    r1 :: int\n    r2 :: bit\n    s :: object\n    r3 :: int\nL0:\n    r0 = 0 << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    r2 = r1 != 0\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    goto L3\nL2:\nL3:\n    s = arg\n    r3 = CPyObject_Size(s)\n    return r3\n\n[case testUndefinedFunction]\ndef f():\n    non_existent_function()\n\n[out]\ndef f():\n    r0 :: bool\n    r1, r2, r3 :: object\nL0:\n    r0 = raise NameError('name \"non_existent_function\" is not defined')\n    r1 = box(None, 1)\n    r2 = PyObject_Vectorcall(r1, 0, 0, 0)\n    r3 = box(None, 1)\n    return r3\n\n[case testStarArgFastPathTuple]\nfrom typing import Any, Callable\ndef deco(fn: Callable[..., Any]) -> Callable[..., Any]:\n    def wrapper(*args: Any) -> Any:\n        return fn(*args)\n    return wrapper\n\n[out]\ndef wrapper_deco_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef wrapper_deco_obj.__call__(__mypyc_self__, args):\n    __mypyc_self__ :: __main__.wrapper_deco_obj\n    args :: tuple\n    r0 :: __main__.deco_env\n    r1, r2 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.fn\n    r2 = PyObject_CallObject(r1, args)\n    return r2\ndef deco(fn):\n    fn :: object\n    r0 :: __main__.deco_env\n    r1 :: bool\n    r2 :: __main__.wrapper_deco_obj\n    r3 :: bool\n    wrapper :: object\nL0:\n    r0 = deco_env()\n    r0.fn = fn; r1 = is_error\n    r2 = wrapper_deco_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    wrapper = r2\n    return wrapper\n\n[case testStarArgFastPathList]\nfrom typing import Any, Callable\ndef deco(fn: Callable[..., Any]) -> Callable[[list[Any]], Any]:\n    def wrapper(args: list[Any]) -> Any:\n        return fn(*args)\n    return wrapper\n\n[out]\ndef wrapper_deco_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef wrapper_deco_obj.__call__(__mypyc_self__, args):\n    __mypyc_self__ :: __main__.wrapper_deco_obj\n    args :: list\n    r0 :: __main__.deco_env\n    r1 :: object\n    r2 :: tuple\n    r3 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.fn\n    r2 = PyList_AsTuple(args)\n    r3 = PyObject_CallObject(r1, r2)\n    return r3\ndef deco(fn):\n    fn :: object\n    r0 :: __main__.deco_env\n    r1 :: bool\n    r2 :: __main__.wrapper_deco_obj\n    r3 :: bool\n    wrapper :: object\nL0:\n    r0 = deco_env()\n    r0.fn = fn; r1 = is_error\n    r2 = wrapper_deco_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    wrapper = r2\n    return wrapper\n\n[case testStarArgFastPathListWithKwargs]\nfrom typing import Any, Callable\ndef deco(fn: Callable[..., Any]) -> Callable[..., Any]:\n    def wrapper(lst: list[Any], kwargs: dict[str, Any]) -> Any:\n        return fn(*lst, **kwargs)\n    return wrapper\n\n[out]\ndef wrapper_deco_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef wrapper_deco_obj.__call__(__mypyc_self__, lst, kwargs):\n    __mypyc_self__ :: __main__.wrapper_deco_obj\n    lst :: list\n    kwargs :: dict\n    r0 :: __main__.deco_env\n    r1 :: object\n    r2 :: tuple\n    r3 :: dict\n    r4 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.fn\n    r2 = PyList_AsTuple(lst)\n    r3 = PyDict_Copy(kwargs)\n    r4 = PyObject_Call(r1, r2, r3)\n    return r4\ndef deco(fn):\n    fn :: object\n    r0 :: __main__.deco_env\n    r1 :: bool\n    r2 :: __main__.wrapper_deco_obj\n    r3 :: bool\n    wrapper :: object\nL0:\n    r0 = deco_env()\n    r0.fn = fn; r1 = is_error\n    r2 = wrapper_deco_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    wrapper = r2\n    return wrapper\n\n[case testStarArgFastPathSequence]\nfrom typing import Any, Callable\ndef deco(fn: Callable[[Any], Any]) -> Callable[[Any], Any]:\n    def wrapper(args: Any) -> Any:\n        return fn(*args)\n    return wrapper\n\n[out]\ndef wrapper_deco_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef wrapper_deco_obj.__call__(__mypyc_self__, args):\n    __mypyc_self__ :: __main__.wrapper_deco_obj\n    args :: object\n    r0 :: __main__.deco_env\n    r1 :: object\n    r2 :: tuple\n    r3 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.fn\n    r2 = PySequence_Tuple(args)\n    r3 = PyObject_CallObject(r1, r2)\n    return r3\ndef deco(fn):\n    fn :: object\n    r0 :: __main__.deco_env\n    r1 :: bool\n    r2 :: __main__.wrapper_deco_obj\n    r3 :: bool\n    wrapper :: object\nL0:\n    r0 = deco_env()\n    r0.fn = fn; r1 = is_error\n    r2 = wrapper_deco_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    wrapper = r2\n    return wrapper\n\n[case testStarArgFastPathSequenceWithKwargs]\nfrom typing import Any, Callable\ndef deco(fn: Callable[[Any], Any]) -> Callable[[Any], Any]:\n    def wrapper(args: Any, **kwargs: Any) -> Any:\n        return fn(*args, **kwargs)\n    return wrapper\n\n[out]\ndef wrapper_deco_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef wrapper_deco_obj.__call__(__mypyc_self__, args, kwargs):\n    __mypyc_self__ :: __main__.wrapper_deco_obj\n    args :: object\n    kwargs :: dict\n    r0 :: __main__.deco_env\n    r1 :: object\n    r2 :: tuple\n    r3 :: dict\n    r4 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.fn\n    r2 = PySequence_Tuple(args)\n    r3 = PyDict_Copy(kwargs)\n    r4 = PyObject_Call(r1, r2, r3)\n    return r4\ndef deco(fn):\n    fn :: object\n    r0 :: __main__.deco_env\n    r1 :: bool\n    r2 :: __main__.wrapper_deco_obj\n    r3 :: bool\n    wrapper :: object\nL0:\n    r0 = deco_env()\n    r0.fn = fn; r1 = is_error\n    r2 = wrapper_deco_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    wrapper = r2\n    return wrapper\n\n[case testStaticLength]\ndef get_length() -> int:\n    return len(\"https://w3id.org/cwl/salad#\")\n[out]\ndef get_length():\n    r0 :: str\nL0:\n    r0 = 'https://w3id.org/cwl/salad#'\n    return 54\n"
  },
  {
    "path": "mypyc/test-data/irbuild-bool.test",
    "content": "[case testBoolToAndFromInt]\nfrom mypy_extensions import i64\n\ndef bool_to_int(b: bool) -> int:\n    return b\ndef int_to_bool(n: int) -> bool:\n    return bool(n)\ndef bool_to_i64(b: bool) -> i64:\n    return b\ndef i64_to_bool(n: i64) -> bool:\n    return bool(n)\ndef bit_to_int(n1: i64, n2: i64) -> int:\n    return bool(n1 == n2)\ndef bit_to_i64(n1: i64, n2: i64) -> i64:\n    return bool(n1 == n2)\n[out]\ndef bool_to_int(b):\n    b, r0 :: bool\n    r1 :: int\nL0:\n    r0 = b << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    return r1\ndef int_to_bool(n):\n    n :: int\n    r0 :: bit\nL0:\n    r0 = n != 0\n    return r0\ndef bool_to_i64(b):\n    b :: bool\n    r0 :: i64\nL0:\n    r0 = extend b: builtins.bool to i64\n    return r0\ndef i64_to_bool(n):\n    n :: i64\n    r0 :: bit\nL0:\n    r0 = n != 0\n    return r0\ndef bit_to_int(n1, n2):\n    n1, n2 :: i64\n    r0 :: bit\n    r1 :: bool\n    r2 :: int\nL0:\n    r0 = n1 == n2\n    r1 = r0 << 1\n    r2 = extend r1: builtins.bool to builtins.int\n    return r2\ndef bit_to_i64(n1, n2):\n    n1, n2 :: i64\n    r0 :: bit\n    r1 :: i64\nL0:\n    r0 = n1 == n2\n    r1 = extend r0: bit to i64\n    return r1\n\n[case testConversionToBool]\nfrom typing import List, Optional\n\nclass C: pass\nclass D:\n    def __bool__(self) -> bool:\n        return True\n\ndef list_to_bool(l: List[str]) -> bool:\n    return bool(l)\n\ndef always_truthy_instance_to_bool(o: C) -> bool:\n    return bool(o)\n\ndef instance_to_bool(o: D) -> bool:\n    return bool(o)\n\ndef optional_truthy_to_bool(o: Optional[C]) -> bool:\n    return bool(o)\n\ndef optional_maybe_falsey_to_bool(o: Optional[D]) -> bool:\n    return bool(o)\n[out]\ndef D.__bool__(self):\n    self :: __main__.D\nL0:\n    return 1\ndef list_to_bool(l):\n    l :: list\n    r0 :: native_int\n    r1 :: short_int\n    r2 :: bit\nL0:\n    r0 = var_object_size l\n    r1 = r0 << 1\n    r2 = int_ne r1, 0\n    return r2\ndef always_truthy_instance_to_bool(o):\n    o :: __main__.C\n    r0 :: i32\n    r1 :: bit\n    r2 :: bool\nL0:\n    r0 = PyObject_IsTrue(o)\n    r1 = r0 >= 0 :: signed\n    r2 = truncate r0: i32 to builtins.bool\n    return r2\ndef instance_to_bool(o):\n    o :: __main__.D\n    r0 :: bool\nL0:\n    r0 = o.__bool__()\n    return r0\ndef optional_truthy_to_bool(o):\n    o :: union[__main__.C, None]\n    r0 :: object\n    r1 :: bit\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = o != r0\n    return r1\ndef optional_maybe_falsey_to_bool(o):\n    o :: union[__main__.D, None]\n    r0 :: object\n    r1 :: bit\n    r2 :: __main__.D\n    r3 :: bool\n    r4 :: bit\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = o != r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = cast(__main__.D, o)\n    r3 = r2.__bool__()\n    r4 = r3\n    goto L3\nL2:\n    r4 = 0\nL3:\n    return r4\n\n[case testBoolComparisons]\ndef eq(x: bool, y: bool) -> bool:\n    return x == y\n\ndef neq(x: bool, y: bool) -> bool:\n    return x != y\n\ndef lt(x: bool, y: bool) -> bool:\n    return x < y\n\ndef le(x: bool, y: bool) -> bool:\n    return x <= y\n\ndef gt(x: bool, y: bool) -> bool:\n    return x > y\n\ndef ge(x: bool, y: bool) -> bool:\n    return x >= y\n[out]\ndef eq(x, y):\n    x, y :: bool\n    r0 :: bit\nL0:\n    r0 = x == y\n    return r0\ndef neq(x, y):\n    x, y :: bool\n    r0 :: bit\nL0:\n    r0 = x != y\n    return r0\ndef lt(x, y):\n    x, y :: bool\n    r0 :: bit\nL0:\n    r0 = x < y :: signed\n    return r0\ndef le(x, y):\n    x, y :: bool\n    r0 :: bit\nL0:\n    r0 = x <= y :: signed\n    return r0\ndef gt(x, y):\n    x, y :: bool\n    r0 :: bit\nL0:\n    r0 = x > y :: signed\n    return r0\ndef ge(x, y):\n    x, y :: bool\n    r0 :: bit\nL0:\n    r0 = x >= y :: signed\n    return r0\n\n[case testBoolMixedComparisons1]\nfrom mypy_extensions import i64\n\ndef eq1(x: int, y: bool) -> bool:\n    return x == y\n\ndef eq2(x: bool, y: int) -> bool:\n    return x == y\n\ndef neq1(x: i64, y: bool) -> bool:\n    return x != y\n\ndef neq2(x: bool, y: i64) -> bool:\n    return x != y\n[out]\ndef eq1(x, y):\n    x :: int\n    y, r0 :: bool\n    r1 :: int\n    r2 :: bit\nL0:\n    r0 = y << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    r2 = int_eq x, r1\n    return r2\ndef eq2(x, y):\n    x :: bool\n    y :: int\n    r0 :: bool\n    r1 :: int\n    r2 :: bit\nL0:\n    r0 = x << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    r2 = int_eq r1, y\n    return r2\ndef neq1(x, y):\n    x :: i64\n    y :: bool\n    r0 :: i64\n    r1 :: bit\nL0:\n    r0 = extend y: builtins.bool to i64\n    r1 = x != r0\n    return r1\ndef neq2(x, y):\n    x :: bool\n    y, r0 :: i64\n    r1 :: bit\nL0:\n    r0 = extend x: builtins.bool to i64\n    r1 = r0 != y\n    return r1\n\n[case testBoolMixedComparisons2]\nfrom mypy_extensions import i64\n\ndef lt1(x: bool, y: int) -> bool:\n    return x < y\n\ndef lt2(x: int, y: bool) -> bool:\n    return x < y\n\ndef gt1(x: bool, y: i64) -> bool:\n    return x < y\n\ndef gt2(x: i64, y: bool) -> bool:\n    return x < y\n[out]\ndef lt1(x, y):\n    x :: bool\n    y :: int\n    r0 :: bool\n    r1 :: int\n    r2 :: bit\nL0:\n    r0 = x << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    r2 = int_lt r1, y\n    return r2\ndef lt2(x, y):\n    x :: int\n    y, r0 :: bool\n    r1 :: int\n    r2 :: bit\nL0:\n    r0 = y << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    r2 = int_lt x, r1\n    return r2\ndef gt1(x, y):\n    x :: bool\n    y, r0 :: i64\n    r1 :: bit\nL0:\n    r0 = extend x: builtins.bool to i64\n    r1 = r0 < y :: signed\n    return r1\ndef gt2(x, y):\n    x :: i64\n    y :: bool\n    r0 :: i64\n    r1 :: bit\nL0:\n    r0 = extend y: builtins.bool to i64\n    r1 = x < r0 :: signed\n    return r1\n\n[case testBoolBitwise]\nfrom mypy_extensions import i64\ndef bitand(x: bool, y: bool) -> bool:\n    b = x & y\n    return b\ndef bitor(x: bool, y: bool) -> bool:\n    b = x | y\n    return b\ndef bitxor(x: bool, y: bool) -> bool:\n    b = x ^ y\n    return b\ndef invert(x: bool) -> int:\n    return ~x\ndef mixed_bitand(x: i64, y: bool) -> i64:\n    return x & y\n[out]\ndef bitand(x, y):\n    x, y, r0, b :: bool\nL0:\n    r0 = x & y\n    b = r0\n    return b\ndef bitor(x, y):\n    x, y, r0, b :: bool\nL0:\n    r0 = x | y\n    b = r0\n    return b\ndef bitxor(x, y):\n    x, y, r0, b :: bool\nL0:\n    r0 = x ^ y\n    b = r0\n    return b\ndef invert(x):\n    x, r0 :: bool\n    r1, r2 :: int\nL0:\n    r0 = x << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    r2 = CPyTagged_Invert(r1)\n    return r2\ndef mixed_bitand(x, y):\n    x :: i64\n    y :: bool\n    r0, r1 :: i64\nL0:\n    r0 = extend y: builtins.bool to i64\n    r1 = x & r0\n    return r1\n\n[case testBoolArithmetic]\ndef add(x: bool, y: bool) -> int:\n    z = x + y\n    return z\ndef mixed(b: bool, n: int) -> int:\n    z = b + n\n    z -= b\n    z = z * b\n    return z\ndef negate(b: bool) -> int:\n    return -b\ndef unary_plus(b: bool) -> int:\n    x = +b\n    return x\n[out]\ndef add(x, y):\n    x, y, r0 :: bool\n    r1 :: int\n    r2 :: bool\n    r3, r4, z :: int\nL0:\n    r0 = x << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    r2 = y << 1\n    r3 = extend r2: builtins.bool to builtins.int\n    r4 = CPyTagged_Add(r1, r3)\n    z = r4\n    return z\ndef mixed(b, n):\n    b :: bool\n    n :: int\n    r0 :: bool\n    r1, r2, z :: int\n    r3 :: bool\n    r4, r5 :: int\n    r6 :: bool\n    r7, r8 :: int\nL0:\n    r0 = b << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    r2 = CPyTagged_Add(r1, n)\n    z = r2\n    r3 = b << 1\n    r4 = extend r3: builtins.bool to builtins.int\n    r5 = CPyTagged_Subtract(z, r4)\n    z = r5\n    r6 = b << 1\n    r7 = extend r6: builtins.bool to builtins.int\n    r8 = CPyTagged_Multiply(z, r7)\n    z = r8\n    return z\ndef negate(b):\n    b, r0 :: bool\n    r1, r2 :: int\nL0:\n    r0 = b << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    r2 = CPyTagged_Negate(r1)\n    return r2\ndef unary_plus(b):\n    b, r0 :: bool\n    r1, x :: int\nL0:\n    r0 = b << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    x = r1\n    return x\n\n[case testBitToBoolPromotion]\ndef bitand(x: float, y: float, z: float) -> bool:\n    b = (x == y) & (x == z)\n    return b\ndef bitor(x: float, y: float, z: float) -> bool:\n    b = (x == y) | (x == z)\n    return b\ndef bitxor(x: float, y: float, z: float) -> bool:\n    b = (x == y) ^ (x == z)\n    return b\ndef invert(x: float, y: float) -> bool:\n    return not(x == y)\n[out]\ndef bitand(x, y, z):\n    x, y, z :: float\n    r0, r1 :: bit\n    r2, b :: bool\nL0:\n    r0 = x == y\n    r1 = x == z\n    r2 = r0 & r1\n    b = r2\n    return b\ndef bitor(x, y, z):\n    x, y, z :: float\n    r0, r1 :: bit\n    r2, b :: bool\nL0:\n    r0 = x == y\n    r1 = x == z\n    r2 = r0 | r1\n    b = r2\n    return b\ndef bitxor(x, y, z):\n    x, y, z :: float\n    r0, r1 :: bit\n    r2, b :: bool\nL0:\n    r0 = x == y\n    r1 = x == z\n    r2 = r0 ^ r1\n    b = r2\n    return b\ndef invert(x, y):\n    x, y :: float\n    r0, r1 :: bit\nL0:\n    r0 = x == y\n    r1 = r0 ^ 1\n    return r1\n\n[case testUnaryNotWithPrimitiveTypes]\ndef not_obj(x: object) -> bool:\n    return not x\n\ndef not_int(x: int) -> bool:\n    return not x\n\ndef not_str(x: str) -> bool:\n    return not x\n\ndef not_list(x: list[int]) -> bool:\n    return not x\n\ndef not_tuple(x: tuple[int, ...]) -> bool:\n    return not x\n\ndef not_dict(x: dict[str, int]) -> bool:\n    return not x\n[out]\ndef not_obj(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: bool\nL0:\n    r0 = PyObject_Not(x)\n    r1 = r0 >= 0 :: signed\n    r2 = truncate r0: i32 to builtins.bool\n    return r2\ndef not_int(x):\n    x :: int\n    r0 :: bit\nL0:\n    r0 = int_eq x, 0\n    return r0\ndef not_str(x):\n    x :: str\n    r0, r1 :: bit\nL0:\n    r0 = CPyStr_IsTrue(x)\n    r1 = r0 ^ 1\n    return r1\ndef not_list(x):\n    x :: list\n    r0 :: native_int\n    r1 :: short_int\n    r2, r3 :: bit\nL0:\n    r0 = var_object_size x\n    r1 = r0 << 1\n    r2 = int_ne r1, 0\n    r3 = r2 ^ 1\n    return r3\ndef not_tuple(x):\n    x :: tuple\n    r0 :: native_int\n    r1 :: short_int\n    r2, r3 :: bit\nL0:\n    r0 = var_object_size x\n    r1 = r0 << 1\n    r2 = int_ne r1, 0\n    r3 = r2 ^ 1\n    return r3\ndef not_dict(x):\n    x :: dict\n    r0 :: native_int\n    r1 :: short_int\n    r2, r3 :: bit\nL0:\n    r0 = PyDict_Size(x)\n    r1 = r0 << 1\n    r2 = int_ne r1, 0\n    r3 = r2 ^ 1\n    return r3\n\n[case testUnaryNotWithNativeClass]\nfrom __future__ import annotations\n\nclass C:\n    def __bool__(self) -> bool:\n        return True\n\ndef not_c(x: C) -> bool:\n    return not x\n\ndef not_c_opt(x: C | None) -> bool:\n    return not x\n[out]\ndef C.__bool__(self):\n    self :: __main__.C\nL0:\n    return 1\ndef not_c(x):\n    x :: __main__.C\n    r0, r1 :: bool\nL0:\n    r0 = x.__bool__()\n    r1 = r0 ^ 1\n    return r1\ndef not_c_opt(x):\n    x :: union[__main__.C, None]\n    r0 :: object\n    r1, r2 :: bit\n    r3 :: __main__.C\n    r4, r5 :: bool\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = 1\n    goto L3\nL2:\n    r3 = unchecked borrow cast(__main__.C, x)\n    r4 = r3.__bool__()\n    r5 = r4 ^ 1\n    r2 = r5\nL3:\n    keep_alive x\n    return r2\n\n[case testUnaryNotWithOptionalPrimitiveTypes]\nfrom __future__ import annotations\n\ndef not_str(x: str | None) -> bool:\n    return not x\n\ndef not_list(x: list[int] | None) -> bool:\n    return not x\n[out]\ndef not_str(x):\n    x :: union[str, None]\n    r0 :: object\n    r1, r2 :: bit\n    r3 :: str\n    r4, r5 :: bit\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = 1\n    goto L3\nL2:\n    r3 = unchecked borrow cast(str, x)\n    r4 = CPyStr_IsTrue(r3)\n    r5 = r4 ^ 1\n    r2 = r5\nL3:\n    keep_alive x\n    return r2\ndef not_list(x):\n    x :: union[list, None]\n    r0 :: object\n    r1, r2 :: bit\n    r3 :: list\n    r4 :: native_int\n    r5 :: short_int\n    r6, r7 :: bit\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = 1\n    goto L3\nL2:\n    r3 = unchecked borrow cast(list, x)\n    r4 = var_object_size r3\n    r5 = r4 << 1\n    r6 = int_ne r5, 0\n    r7 = r6 ^ 1\n    r2 = r7\nL3:\n    keep_alive x\n    return r2\n"
  },
  {
    "path": "mypyc/test-data/irbuild-bytes.test",
    "content": "[case testBytesBasics]\ndef f(num: int, l: list, d: dict, s: str) -> None:\n    b1 = bytes()\n    b2 = bytes(num)\n    b3 = bytes(l)\n    b4 = bytes(d)\n    b5 = bytes(s)\n[out]\ndef f(num, l, d, s):\n    num :: int\n    l :: list\n    d :: dict\n    s :: str\n    r0, r1 :: object\n    r2, b1 :: bytes\n    r3, r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7 :: object\n    r8, b2, r9, b3, r10, b4, r11, b5 :: bytes\nL0:\n    r0 = load_address PyBytes_Type\n    r1 = PyObject_Vectorcall(r0, 0, 0, 0)\n    r2 = cast(bytes, r1)\n    b1 = r2\n    r3 = load_address PyBytes_Type\n    r4 = box(int, num)\n    r5 = [r4]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r3, r6, 1, 0)\n    keep_alive r4\n    r8 = cast(bytes, r7)\n    b2 = r8\n    r9 = PyBytes_FromObject(l)\n    b3 = r9\n    r10 = PyBytes_FromObject(d)\n    b4 = r10\n    r11 = PyBytes_FromObject(s)\n    b5 = r11\n    return 1\n\n[case testBytearrayBasics]\ndef f(s: str, num: int) -> None:\n    a = bytearray()\n    b = bytearray(s)\n    c = bytearray(num)\n[out]\ndef f(s, num):\n    s :: str\n    num :: int\n    r0, a, r1, b :: bytearray\n    r2 :: object\n    r3, c :: bytearray\nL0:\n    r0 = CPyByteArray_New()\n    a = r0\n    r1 = PyByteArray_FromObject(s)\n    b = r1\n    r2 = box(int, num)\n    r3 = PyByteArray_FromObject(r2)\n    c = r3\n    return 1\n\n[case testBytesEquality]\ndef eq(x: bytes, y: bytes) -> bool:\n    return x == y\n\ndef neq(x: bytes, y: bytes) -> bool:\n    return x != y\n[out]\ndef eq(x, y):\n    x, y :: bytes\n    r0 :: i32\n    r1, r2 :: bit\nL0:\n    r0 = CPyBytes_Compare(x, y)\n    r1 = r0 >= 0 :: signed\n    r2 = r0 == 1\n    return r2\ndef neq(x, y):\n    x, y :: bytes\n    r0 :: i32\n    r1, r2 :: bit\nL0:\n    r0 = CPyBytes_Compare(x, y)\n    r1 = r0 >= 0 :: signed\n    r2 = r0 != 1\n    return r2\n\n[case testBytesSlicing]\ndef f(a: bytes, start: int, end: int) -> bytes:\n    return a[start:end]\n[out]\ndef f(a, start, end):\n    a :: bytes\n    start, end :: int\n    r0 :: bytes\nL0:\n    r0 = CPyBytes_GetSlice(a, start, end)\n    return r0\n\n[case testBytesIndex]\nfrom mypy_extensions import i64\n\ndef f(a: bytes, i: i64) -> int:\n    return a[i]\n[out]\ndef f(a, i):\n    a :: bytes\n    i, r0 :: i64\n    r1, r2 :: bool\n    r3 :: int\nL0:\n    r0 = CPyBytes_AdjustIndex(a, i)\n    r1 = CPyBytes_RangeCheck(a, r0)\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = raise IndexError('index out of range')\n    unreachable\nL2:\n    r3 = CPyBytes_GetItemUnsafe(a, r0)\n    return r3\n\n[case testBytesConcat]\ndef f(a: bytes, b: bytes) -> bytes:\n    return a + b\n[out]\ndef f(a, b):\n    a, b, r0 :: bytes\nL0:\n    r0 = CPyBytes_Concat(a, b)\n    return r0\n\n[case testBytesJoin]\nfrom typing import List\ndef f(b: List[bytes]) -> bytes:\n    return b\" \".join(b)\n[out]\ndef f(b):\n    b :: list\n    r0, r1 :: bytes\nL0:\n    r0 = b' '\n    r1 = CPyBytes_Join(r0, b)\n    return r1\n\n[case testBytesLen]\ndef f(b: bytes) -> int:\n    return len(b)\n[out]\ndef f(b):\n    b :: bytes\n    r0 :: native_int\n    r1 :: short_int\nL0:\n    r0 = var_object_size b\n    r1 = r0 << 1\n    return r1\n\n[case testBytesFormatting]\ndef f(var: bytes, num: int) -> None:\n    b1 = b'aaaa%bbbbb%s' % (var, var)\n    b2 = b'aaaa%bbbbb%s%d' % (var, var, num)\n    b3 = b'%b' % var\n    b4 = b'%ssss' % var\n    b5 = b'%d' % num\n    b6 = b'%d' % 42\n    b7 = b'%d' % (67 + 2)\n[typing fixtures/typing-full.pyi]\n[out]\ndef f(var, num):\n    var :: bytes\n    num :: int\n    r0, r1, r2, b1, r3, r4, r5, r6, b2, r7, b3, r8, r9, b4, r10, r11, b5, r12, r13, b6, r14, r15, b7 :: bytes\nL0:\n    r0 = b'aaaa'\n    r1 = b'bbbb'\n    r2 = CPyBytes_Build(4, r0, var, r1, var)\n    b1 = r2\n    r3 = CPyTagged_AsciiBytes(num)\n    r4 = b'aaaa'\n    r5 = b'bbbb'\n    r6 = CPyBytes_Build(5, r4, var, r5, var, r3)\n    b2 = r6\n    r7 = CPyBytes_Build(1, var)\n    b3 = r7\n    r8 = b'sss'\n    r9 = CPyBytes_Build(2, var, r8)\n    b4 = r9\n    r10 = CPyTagged_AsciiBytes(num)\n    r11 = CPyBytes_Build(1, r10)\n    b5 = r11\n    r12 = b'42'\n    r13 = CPyBytes_Build(1, r12)\n    b6 = r13\n    r14 = b'69'\n    r15 = CPyBytes_Build(1, r14)\n    b7 = r15\n    return 1\n\n[case testOptionalBytesEquality]\nfrom typing import Optional\n\ndef non_opt_opt(x: bytes, y: Optional[bytes]) -> bool:\n    return x != y\n[out]\ndef non_opt_opt(x, y):\n    x :: bytes\n    y :: union[bytes, None]\n    r0 :: object\n    r1 :: bit\n    r2 :: bool\n    r3 :: bytes\n    r4 :: i32\n    r5, r6 :: bit\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = y == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = 1\n    goto L3\nL2:\n    r3 = unchecked borrow cast(bytes, y)\n    r4 = CPyBytes_Compare(r3, x)\n    r5 = r4 >= 0 :: signed\n    r6 = r4 != 1\n    r2 = r6\nL3:\n    keep_alive y\n    return r2\n\n[case testBytesMultiply]\ndef b_times_i(s: bytes, n: int) -> bytes:\n    return s * n\ndef i_times_b(s: bytes, n: int) -> bytes:\n    return n * s\n[out]\ndef b_times_i(s, n):\n    s :: bytes\n    n :: int\n    r0 :: bytes\nL0:\n    r0 = CPyBytes_Multiply(s, n)\n    return r0\ndef i_times_b(s, n):\n    s :: bytes\n    n :: int\n    r0 :: bytes\nL0:\n    r0 = CPyBytes_Multiply(s, n)\n    return r0\n\n[case testBytesTranslate]\ndef f(b: bytes, table: bytes) -> bytes:\n    return b.translate(table)\n[out]\ndef f(b, table):\n    b, table, r0 :: bytes\nL0:\n    r0 = CPyBytes_Translate(b, table)\n    return r0\n\n[case testBytesStartsWith]\ndef f(a: bytes, b: bytes) -> bool:\n    return a.startswith(b)\n[out]\ndef f(a, b):\n    a, b :: bytes\n    r0 :: i32\n    r1 :: bool\nL0:\n    r0 = CPyBytes_Startswith(a, b)\n    r1 = truncate r0: i32 to builtins.bool\n    return r1\n\n[case testBytesEndsWith]\ndef f(a: bytes, b: bytes) -> bool:\n    return a.endswith(b)\n[out]\ndef f(a, b):\n    a, b :: bytes\n    r0 :: i32\n    r1 :: bool\nL0:\n    r0 = CPyBytes_Endswith(a, b)\n    r1 = truncate r0: i32 to builtins.bool\n    return r1\n\n[case testBytesVsBytearray]\ndef bytes_func(b: bytes) -> None: pass\ndef bytearray_func(ba: bytearray) -> None: pass\n\ndef foo(b: bytes, ba: bytearray) -> None:\n    bytes_func(b)\n    bytearray_func(ba)\n    bytes_func(ba)\n    bytearray_func(b)\n[out]\nmain:7: error: Argument 1 to \"bytes_func\" has incompatible type \"bytearray\"; expected \"bytes\"\nmain:8: error: Argument 1 to \"bytearray_func\" has incompatible type \"bytes\"; expected \"bytearray\"\n"
  },
  {
    "path": "mypyc/test-data/irbuild-classes.test",
    "content": "[case testGetAttribute]\nclass A:\n    x: int\n\ndef f(a: A) -> int:\n    return a.x\n[out]\ndef f(a):\n    a :: __main__.A\n    r0 :: int\nL0:\n    r0 = a.x\n    return r0\n\n[case testSetAttribute]\nclass A:\n    x: int\n\ndef f(a: A) -> None:\n    a.x = 1\n[out]\ndef f(a):\n    a :: __main__.A\n    r0 :: bool\nL0:\n    a.x = 2; r0 = is_error\n    return 1\n\n[case testUserClassInList]\nclass C:\n    x: int\n\ndef f() -> int:\n    c = C()\n    c.x = 5\n    a = [c]\n    d = a[0]\n    return d.x + 1\n[out]\ndef f():\n    r0, c :: __main__.C\n    r1 :: bool\n    r2 :: list\n    r3 :: ptr\n    a :: list\n    r4 :: object\n    r5, d :: __main__.C\n    r6, r7 :: int\nL0:\n    r0 = C()\n    c = r0\n    c.x = 10; r1 = is_error\n    r2 = PyList_New(1)\n    r3 = list_items r2\n    buf_init_item r3, 0, c\n    keep_alive r2\n    a = r2\n    r4 = CPyList_GetItemShort(a, 0)\n    r5 = cast(__main__.C, r4)\n    d = r5\n    r6 = borrow d.x\n    r7 = CPyTagged_Add(r6, 2)\n    keep_alive d\n    return r7\n\n[case testMethodCall]\nclass A:\n    def f(self, x: int, y: str) -> int:\n        return x + 10\n\ndef g(a: A) -> None:\n    a.f(1, 'hi')\n[out]\ndef A.f(self, x, y):\n    self :: __main__.A\n    x :: int\n    y :: str\n    r0 :: int\nL0:\n    r0 = CPyTagged_Add(x, 20)\n    return r0\ndef g(a):\n    a :: __main__.A\n    r0 :: str\n    r1 :: int\nL0:\n    r0 = 'hi'\n    r1 = a.f(2, r0)\n    return 1\n\n[case testForwardUse]\ndef g(a: A) -> int:\n    return a.n\n\nclass A:\n    n : int\n\n[out]\ndef g(a):\n    a :: __main__.A\n    r0 :: int\nL0:\n    r0 = a.n\n    return r0\n\n[case testOptionalMember]\nfrom typing import Optional\nclass Node:\n    next: Optional[Node]\n    def length(self) -> int:\n        if self.next is not None:\n            return 1 + self.next.length()\n        return 1\n[out]\ndef Node.length(self):\n    self :: __main__.Node\n    r0 :: union[__main__.Node, None]\n    r1 :: object\n    r2 :: bit\n    r3 :: union[__main__.Node, None]\n    r4 :: __main__.Node\n    r5, r6 :: int\nL0:\n    r0 = borrow self.next\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 != r1\n    keep_alive self\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = self.next\n    r4 = cast(__main__.Node, r3)\n    r5 = r4.length()\n    r6 = CPyTagged_Add(2, r5)\n    return r6\nL2:\n    return 2\n\n[case testSubclass]\nclass A:\n    def __init__(self) -> None:\n        self.x = 10\nclass B(A):\n    def __init__(self) -> None:\n        self.x = 20\n        self.y = 30\n[out]\ndef A.__init__(self):\n    self :: __main__.A\nL0:\n    self.x = 20\n    return 1\ndef B.__init__(self):\n    self :: __main__.B\nL0:\n    self.x = 40\n    self.y = 60\n    return 1\n\n[case testAttrLvalue]\nclass O(object):\n    def __init__(self) -> None:\n        self.x = 1\n\ndef increment(o: O) -> O:\n    o.x += 1\n    return o\n[out]\ndef O.__init__(self):\n    self :: __main__.O\nL0:\n    self.x = 2\n    return 1\ndef increment(o):\n    o :: __main__.O\n    r0, r1 :: int\n    r2 :: bool\nL0:\n    r0 = borrow o.x\n    r1 = CPyTagged_Add(r0, 2)\n    o.x = r1; r2 = is_error\n    return o\n\n[case testSubclass_withgil_toplevel]\nfrom typing import TypeVar, Generic\nfrom mypy_extensions import trait\nT = TypeVar('T')\nclass C:\n    pass\n\n@trait\nclass S:\n    pass\n\nclass D(C, S, Generic[T]):\n    pass\n\n[out]\ndef __top_level__():\n    r0, r1 :: object\n    r2 :: bit\n    r3 :: str\n    r4, r5 :: object\n    r6 :: str\n    r7 :: dict\n    r8, r9 :: object\n    r10 :: str\n    r11 :: dict\n    r12 :: object\n    r13 :: str\n    r14 :: dict\n    r15 :: str\n    r16 :: object\n    r17 :: object[1]\n    r18 :: object_ptr\n    r19 :: object\n    r20 :: dict\n    r21 :: str\n    r22 :: i32\n    r23 :: bit\n    r24 :: object\n    r25 :: str\n    r26, r27 :: object\n    r28, r29 :: bool\n    r30 :: str\n    r31 :: tuple\n    r32 :: i32\n    r33 :: bit\n    r34 :: dict\n    r35 :: str\n    r36 :: i32\n    r37 :: bit\n    r38 :: bool\n    r39 :: object\n    r40 :: str\n    r41, r42 :: object\n    r43 :: str\n    r44 :: tuple\n    r45 :: i32\n    r46 :: bit\n    r47 :: dict\n    r48 :: str\n    r49 :: i32\n    r50 :: bit\n    r51 :: bool\n    r52, r53 :: object\n    r54 :: dict\n    r55 :: str\n    r56 :: object\n    r57 :: dict\n    r58 :: str\n    r59, r60 :: object\n    r61 :: tuple\n    r62 :: str\n    r63, r64 :: object\n    r65, r66 :: bool\n    r67, r68 :: str\n    r69 :: tuple\n    r70 :: i32\n    r71 :: bit\n    r72 :: dict\n    r73 :: str\n    r74 :: i32\n    r75 :: bit\n    r76 :: bool\nL0:\n    r0 = builtins :: module\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 != r1\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = 'builtins'\n    r4 = PyImport_Import(r3)\n    builtins = r4 :: module\nL2:\n    r5 = ('TypeVar', 'Generic')\n    r6 = 'typing'\n    r7 = __main__.globals :: static\n    r8 = CPyImport_ImportFromMany(r6, r5, r5, r7)\n    typing = r8 :: module\n    r9 = ('trait',)\n    r10 = 'mypy_extensions'\n    r11 = __main__.globals :: static\n    r12 = CPyImport_ImportFromMany(r10, r9, r9, r11)\n    mypy_extensions = r12 :: module\n    r13 = 'T'\n    r14 = __main__.globals :: static\n    r15 = 'TypeVar'\n    r16 = CPyDict_GetItem(r14, r15)\n    r17 = [r13]\n    r18 = load_address r17\n    r19 = PyObject_Vectorcall(r16, r18, 1, 0)\n    keep_alive r13\n    r20 = __main__.globals :: static\n    r21 = 'T'\n    r22 = CPyDict_SetItem(r20, r21, r19)\n    r23 = r22 >= 0 :: signed\n    r24 = <error> :: object\n    r25 = '__main__'\n    r26 = __main__.C_template :: type\n    r27 = CPyType_FromTemplate(r26, r24, r25)\n    r28 = C_trait_vtable_setup()\n    r29 = C_coroutine_setup(r27)\n    r30 = '__mypyc_attrs__'\n    r31 = CPyTuple_LoadEmptyTupleConstant()\n    r32 = PyObject_SetAttr(r27, r30, r31)\n    r33 = r32 >= 0 :: signed\n    __main__.C = r27 :: type\n    r34 = __main__.globals :: static\n    r35 = 'C'\n    r36 = PyDict_SetItem(r34, r35, r27)\n    r37 = r36 >= 0 :: signed\n    r38 = CPy_InitSubclass(r27)\n    r39 = <error> :: object\n    r40 = '__main__'\n    r41 = __main__.S_template :: type\n    r42 = CPyType_FromTemplate(r41, r39, r40)\n    r43 = '__mypyc_attrs__'\n    r44 = CPyTuple_LoadEmptyTupleConstant()\n    r45 = PyObject_SetAttr(r42, r43, r44)\n    r46 = r45 >= 0 :: signed\n    __main__.S = r42 :: type\n    r47 = __main__.globals :: static\n    r48 = 'S'\n    r49 = PyDict_SetItem(r47, r48, r42)\n    r50 = r49 >= 0 :: signed\n    r51 = CPy_InitSubclass(r42)\n    r52 = __main__.C :: type\n    r53 = __main__.S :: type\n    r54 = __main__.globals :: static\n    r55 = 'Generic'\n    r56 = CPyDict_GetItem(r54, r55)\n    r57 = __main__.globals :: static\n    r58 = 'T'\n    r59 = CPyDict_GetItem(r57, r58)\n    r60 = PyObject_GetItem(r56, r59)\n    r61 = PyTuple_Pack(3, r52, r53, r60)\n    r62 = '__main__'\n    r63 = __main__.D_template :: type\n    r64 = CPyType_FromTemplate(r63, r61, r62)\n    r65 = D_trait_vtable_setup()\n    r66 = D_coroutine_setup(r64)\n    r67 = '__mypyc_attrs__'\n    r68 = '__dict__'\n    r69 = PyTuple_Pack(1, r68)\n    r70 = PyObject_SetAttr(r64, r67, r69)\n    r71 = r70 >= 0 :: signed\n    __main__.D = r64 :: type\n    r72 = __main__.globals :: static\n    r73 = 'D'\n    r74 = PyDict_SetItem(r72, r73, r64)\n    r75 = r74 >= 0 :: signed\n    r76 = CPy_InitSubclass(r64)\n    return 1\n\n[case testIsInstance]\nclass A: pass\nclass B(A): pass\n\ndef f(x: A) -> B:\n    if isinstance(x, B):\n        return x\n    return B()\n[out]\ndef f(x):\n    x :: __main__.A\n    r0 :: object\n    r1 :: ptr\n    r2 :: object\n    r3 :: bit\n    r4, r5 :: __main__.B\nL0:\n    r0 = __main__.B :: type\n    r1 = get_element_ptr x ob_type :: PyObject\n    r2 = borrow load_mem r1 :: builtins.object*\n    keep_alive x\n    r3 = r2 == r0\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = cast(__main__.B, x)\n    return r4\nL2:\n    r5 = B()\n    return r5\n\n[case testIsInstanceTuple]\nfrom typing import Union\nclass R: pass\nclass A(R): pass\nclass B(R): pass\nclass C(R): pass\n\ndef f(x: R) -> Union[A, B]:\n    if isinstance(x, (A, B)):\n        return x\n    return A()\n[out]\ndef f(x):\n    x :: __main__.R\n    r0 :: object\n    r1 :: ptr\n    r2 :: object\n    r3 :: bit\n    r4 :: bool\n    r5 :: object\n    r6 :: ptr\n    r7 :: object\n    r8 :: bit\n    r9 :: union[__main__.A, __main__.B]\n    r10 :: __main__.A\nL0:\n    r0 = __main__.A :: type\n    r1 = get_element_ptr x ob_type :: PyObject\n    r2 = borrow load_mem r1 :: builtins.object*\n    keep_alive x\n    r3 = r2 == r0\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = r3\n    goto L3\nL2:\n    r5 = __main__.B :: type\n    r6 = get_element_ptr x ob_type :: PyObject\n    r7 = borrow load_mem r6 :: builtins.object*\n    keep_alive x\n    r8 = r7 == r5\n    r4 = r8\nL3:\n    if r4 goto L4 else goto L5 :: bool\nL4:\n    r9 = cast(union[__main__.A, __main__.B], x)\n    return r9\nL5:\n    r10 = A()\n    return r10\n\n[case testIsInstanceFewSubclasses]\nclass R: pass\nclass A(R): pass\n\ndef f(x: object) -> R:\n    if isinstance(x, R):\n        return x\n    return A()\n[out]\ndef f(x):\n    x, r0 :: object\n    r1 :: ptr\n    r2 :: object\n    r3 :: bit\n    r4 :: bool\n    r5 :: object\n    r6 :: ptr\n    r7 :: object\n    r8 :: bit\n    r9 :: __main__.R\n    r10 :: __main__.A\nL0:\n    r0 = __main__.A :: type\n    r1 = get_element_ptr x ob_type :: PyObject\n    r2 = borrow load_mem r1 :: builtins.object*\n    keep_alive x\n    r3 = r2 == r0\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = r3\n    goto L3\nL2:\n    r5 = __main__.R :: type\n    r6 = get_element_ptr x ob_type :: PyObject\n    r7 = borrow load_mem r6 :: builtins.object*\n    keep_alive x\n    r8 = r7 == r5\n    r4 = r8\nL3:\n    if r4 goto L4 else goto L5 :: bool\nL4:\n    r9 = cast(__main__.R, x)\n    return r9\nL5:\n    r10 = A()\n    return r10\n\n[case testIsInstanceFewSubclassesTrait]\nfrom mypy_extensions import trait\nclass B: pass\n@trait\nclass R: pass\nclass A(B, R): pass\nclass C(B, R): pass\n\ndef f(x: object) -> R:\n    if isinstance(x, R):\n        return x\n    return A()\n[out]\ndef f(x):\n    x, r0 :: object\n    r1 :: ptr\n    r2 :: object\n    r3 :: bit\n    r4 :: bool\n    r5 :: object\n    r6 :: ptr\n    r7 :: object\n    r8 :: bit\n    r9 :: __main__.R\n    r10 :: __main__.A\nL0:\n    r0 = __main__.A :: type\n    r1 = get_element_ptr x ob_type :: PyObject\n    r2 = borrow load_mem r1 :: builtins.object*\n    keep_alive x\n    r3 = r2 == r0\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = r3\n    goto L3\nL2:\n    r5 = __main__.C :: type\n    r6 = get_element_ptr x ob_type :: PyObject\n    r7 = borrow load_mem r6 :: builtins.object*\n    keep_alive x\n    r8 = r7 == r5\n    r4 = r8\nL3:\n    if r4 goto L4 else goto L5 :: bool\nL4:\n    r9 = cast(__main__.R, x)\n    return r9\nL5:\n    r10 = A()\n    return r10\n\n[case testIsInstanceManySubclasses]\nclass R: pass\nclass A(R): pass\nclass B(R): pass\nclass C(R): pass\n\ndef f(x: object) -> R:\n    if isinstance(x, R):\n        return x\n    return B()\n[out]\ndef f(x):\n    x, r0 :: object\n    r1 :: bool\n    r2 :: __main__.R\n    r3 :: __main__.B\nL0:\n    r0 = __main__.R :: type\n    r1 = CPy_TypeCheck(x, r0)\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = cast(__main__.R, x)\n    return r2\nL2:\n    r3 = B()\n    return r3\n\n[case testFakeSuper]\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\nclass B(A):\n    def __init__(self, x: int, y: int) -> None:\n        A.__init__(self, x)\n        self.y = y\n[out]\ndef A.__init__(self, x):\n    self :: __main__.A\n    x :: int\nL0:\n    self.x = x\n    return 1\ndef B.__init__(self, x, y):\n    self :: __main__.B\n    x, y :: int\n    r0 :: None\nL0:\n    r0 = A.__init__(self, x)\n    self.y = y\n    return 1\n\n[case testClassMethod]\nclass C:\n    @staticmethod\n    def foo(x: int) -> int: return 10 + x\n    @classmethod\n    def bar(cls, x: int) -> int: return 10 + x\n\ndef lol() -> int:\n    return C.foo(1) + C.bar(2)\n[out]\ndef C.foo(x):\n    x, r0 :: int\nL0:\n    r0 = CPyTagged_Add(20, x)\n    return r0\ndef C.bar(cls, x):\n    cls :: object\n    x, r0 :: int\nL0:\n    r0 = CPyTagged_Add(20, x)\n    return r0\ndef lol():\n    r0 :: int\n    r1 :: object\n    r2, r3 :: int\nL0:\n    r0 = C.foo(2)\n    r1 = __main__.C :: type\n    r2 = C.bar(r1, 4)\n    r3 = CPyTagged_Add(r0, r2)\n    return r3\n\n[case testCallClassMethodViaCls_64bit]\nclass C:\n    @classmethod\n    def f(cls, x: int) -> int:\n        return cls.g(x)\n\n    @classmethod\n    def g(cls, x: int) -> int:\n        return x\n\nclass D:\n    @classmethod\n    def f(cls, x: int) -> int:\n        # TODO: This could also be optimized, since g is not ever overridden\n        return cls.g(x)\n\n    @classmethod\n    def g(cls, x: int) -> int:\n        return x\n\nclass DD(D):\n    pass\n[out]\ndef C.f(cls, x):\n    cls :: object\n    x :: int\n    r0 :: object\n    r1 :: int\nL0:\n    r0 = __main__.C :: type\n    r1 = C.g(r0, x)\n    return r1\ndef C.g(cls, x):\n    cls :: object\n    x :: int\nL0:\n    return x\ndef D.f(cls, x):\n    cls :: object\n    x :: int\n    r0 :: str\n    r1 :: object\n    r2 :: object[2]\n    r3 :: object_ptr\n    r4 :: object\n    r5 :: int\nL0:\n    r0 = 'g'\n    r1 = box(int, x)\n    r2 = [cls, r1]\n    r3 = load_address r2\n    r4 = PyObject_VectorcallMethod(r0, r3, 9223372036854775810, 0)\n    keep_alive cls, r1\n    r5 = unbox(int, r4)\n    return r5\ndef D.g(cls, x):\n    cls :: object\n    x :: int\nL0:\n    return x\n\n[case testCannotAssignToClsArgument]\nfrom typing import Any, cast\n\nclass C:\n    @classmethod\n    def m(cls) -> None:\n        cls = cast(Any, D)  # E: Cannot assign to the first argument of classmethod\n        cls, x = cast(Any, D), 1  # E: Cannot assign to the first argument of classmethod\n        cls, x = cast(Any, [1, 2])  # E: Cannot assign to the first argument of classmethod\n        cls.m()\n\nclass D:\n    pass\n\n[case testSuper1]\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\nclass B(A):\n    def __init__(self, x: int, y: int) -> None:\n        super().__init__(x)\n        self.y = y\n[out]\ndef A.__init__(self, x):\n    self :: __main__.A\n    x :: int\nL0:\n    self.x = x\n    return 1\ndef B.__init__(self, x, y):\n    self :: __main__.B\n    x, y :: int\n    r0 :: None\nL0:\n    r0 = A.__init__(self, x)\n    self.y = y\n    return 1\n\n[case testSuper2]\nfrom mypy_extensions import trait\n@trait\nclass T:\n    def foo(self) -> None: pass\n\nclass X(T):\n    def foo(self) -> None:\n        super().foo()\n[out]\ndef T.foo(self):\n    self :: __main__.T\nL0:\n    return 1\ndef X.foo(self):\n    self :: __main__.X\n    r0 :: None\nL0:\n    r0 = T.foo(self)\n    return 1\n\n[case testSuperCallToObjectInitIsOmitted]\nclass C:\n    def __init__(self) -> None:\n        super().__init__()\nclass D: pass\nclass E(D):\n    def __init__(self) -> None:\n        super().__init__()\nclass F(C):\n    def __init__(self) -> None:\n        super().__init__()\nclass DictSubclass(dict):\n    def __init__(self) -> None:\n        super().__init__()\n[out]\ndef C.__init__(self):\n    self :: __main__.C\nL0:\n    return 1\ndef E.__init__(self):\n    self :: __main__.E\nL0:\n    return 1\ndef F.__init__(self):\n    self :: __main__.F\n    r0 :: None\nL0:\n    r0 = C.__init__(self)\n    return 1\ndef DictSubclass.__init__(self):\n    self :: dict\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[2]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: str\n    r8, r9 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'super'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = __main__.DictSubclass :: type\n    r4 = [r3, self]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 2, 0)\n    keep_alive r3, self\n    r7 = '__init__'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = PyObject_Vectorcall(r8, 0, 0, 0)\n    return 1\n\n[case testClassVariable]\nfrom typing import ClassVar\nclass A:\n    x = 10  # type: ClassVar[int]\n\ndef f() -> int:\n    return A.x\n[out]\ndef f():\n    r0 :: object\n    r1 :: str\n    r2 :: object\n    r3 :: int\nL0:\n    r0 = __main__.A :: type\n    r1 = 'x'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = unbox(int, r2)\n    return r3\n\n[case testNoEqDefined]\nclass A:\n    pass\n\ndef f(a: A, b: A) -> bool:\n    return a == b\n\ndef f2(a: A, b: A) -> bool:\n    return a != b\n\n[out]\ndef f(a, b):\n    a, b :: __main__.A\n    r0 :: bit\nL0:\n    r0 = a == b\n    return r0\ndef f2(a, b):\n    a, b :: __main__.A\n    r0 :: bit\nL0:\n    r0 = a != b\n    return r0\n\n[case testEqDefined]\nclass Base:\n    def __eq__(self, other: object) -> bool:\n        return False\nclass Derived(Base):\n    def __eq__(self, other: object) -> bool:\n        return True\n\ndef f(a: Base, b: Base) -> bool:\n    return a == b\n\ndef f2(a: Base, b: Base) -> bool:\n    return a != b\n\ndef fOpt(a: Derived, b: Derived) -> bool:\n    return a == b\n\ndef fOpt2(a: Derived, b: Derived) -> bool:\n    return a != b\n\n[out]\ndef Base.__eq__(self, other):\n    self :: __main__.Base\n    other, r0 :: object\nL0:\n    r0 = box(bool, 0)\n    return r0\ndef Base.__ne__(__mypyc_self__, rhs):\n    __mypyc_self__ :: __main__.Base\n    rhs, r0, r1 :: object\n    r2 :: bit\n    r3 :: object\n    r4, r5 :: bit\n    r6 :: object\n    r7 :: bit\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11 :: object\nL0:\n    r0 = __mypyc_self__.__eq__(rhs)\n    r1 = load_address _Py_NotImplementedStruct\n    r2 = r0 == r1\n    if r2 goto L7 else goto L1 :: bool\nL1:\n    r3 = load_global Py_True :: static\n    r4 = r0 == r3\n    if r4 goto L2 else goto L3 :: bool\nL2:\n    r5 = 0\n    goto L6\nL3:\n    r6 = load_global Py_False :: static\n    r7 = r0 == r6\n    if r7 goto L4 else goto L5 :: bool\nL4:\n    r5 = 1\n    goto L6\nL5:\n    r8 = PyObject_Not(r0)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    r5 = r10\nL6:\n    r11 = box(bit, r5)\n    return r11\nL7:\n    return r1\ndef Derived.__eq__(self, other):\n    self :: __main__.Derived\n    other, r0 :: object\nL0:\n    r0 = box(bool, 1)\n    return r0\ndef f(a, b):\n    a, b :: __main__.Base\n    r0 :: object\n    r1 :: bool\nL0:\n    r0 = PyObject_RichCompare(a, b, 2)\n    r1 = unbox(bool, r0)\n    return r1\ndef f2(a, b):\n    a, b :: __main__.Base\n    r0 :: object\n    r1 :: bool\nL0:\n    r0 = PyObject_RichCompare(a, b, 3)\n    r1 = unbox(bool, r0)\n    return r1\ndef fOpt(a, b):\n    a, b :: __main__.Derived\n    r0 :: object\n    r1 :: bool\nL0:\n    r0 = a.__eq__(b)\n    r1 = unbox(bool, r0)\n    return r1\ndef fOpt2(a, b):\n    a, b :: __main__.Derived\n    r0 :: object\n    r1 :: bool\nL0:\n    r0 = a.__ne__(b)\n    r1 = unbox(bool, r0)\n    return r1\n\n[case testEqDefinedLater_64bit]\ndef f(a: 'Base', b: 'Base') -> bool:\n    return a == b\n\ndef f2(a: 'Base', b: 'Base') -> bool:\n    return a != b\n\ndef fOpt(a: 'Derived', b: 'Derived') -> bool:\n    return a == b\n\ndef fOpt2(a: 'Derived', b: 'Derived') -> bool:\n    return a != b\n\nclass Base:\n    pass\nclass Derived(Base):\n    def __eq__(self, other: object) -> bool:\n        return True\n\n[out]\ndef f(a, b):\n    a, b :: __main__.Base\n    r0 :: object\n    r1 :: bool\nL0:\n    r0 = PyObject_RichCompare(a, b, 2)\n    r1 = unbox(bool, r0)\n    return r1\ndef f2(a, b):\n    a, b :: __main__.Base\n    r0 :: object\n    r1 :: bool\nL0:\n    r0 = PyObject_RichCompare(a, b, 3)\n    r1 = unbox(bool, r0)\n    return r1\ndef fOpt(a, b):\n    a, b :: __main__.Derived\n    r0 :: object\n    r1 :: bool\nL0:\n    r0 = a.__eq__(b)\n    r1 = unbox(bool, r0)\n    return r1\ndef fOpt2(a, b):\n    a, b :: __main__.Derived\n    r0 :: str\n    r1 :: object[2]\n    r2 :: object_ptr\n    r3 :: object\n    r4 :: bool\nL0:\n    r0 = '__ne__'\n    r1 = [a, b]\n    r2 = load_address r1\n    r3 = PyObject_VectorcallMethod(r0, r2, 9223372036854775810, 0)\n    keep_alive a, b\n    r4 = unbox(bool, r3)\n    return r4\ndef Derived.__eq__(self, other):\n    self :: __main__.Derived\n    other, r0 :: object\nL0:\n    r0 = box(bool, 1)\n    return r0\ndef Derived.__ne__(__mypyc_self__, rhs):\n    __mypyc_self__ :: __main__.Derived\n    rhs, r0, r1 :: object\n    r2 :: bit\n    r3 :: object\n    r4, r5 :: bit\n    r6 :: object\n    r7 :: bit\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11 :: object\nL0:\n    r0 = __mypyc_self__.__eq__(rhs)\n    r1 = load_address _Py_NotImplementedStruct\n    r2 = r0 == r1\n    if r2 goto L7 else goto L1 :: bool\nL1:\n    r3 = load_global Py_True :: static\n    r4 = r0 == r3\n    if r4 goto L2 else goto L3 :: bool\nL2:\n    r5 = 0\n    goto L6\nL3:\n    r6 = load_global Py_False :: static\n    r7 = r0 == r6\n    if r7 goto L4 else goto L5 :: bool\nL4:\n    r5 = 1\n    goto L6\nL5:\n    r8 = PyObject_Not(r0)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    r5 = r10\nL6:\n    r11 = box(bit, r5)\n    return r11\nL7:\n    return r1\n\n[case testDefaultVars]\nfrom typing import ClassVar, Optional\nclass A:\n    x = 10\n    def lol(self) -> None:\n        self.x = 100\n\nLOL = 'lol'\nclass B(A):\n    y = LOL\n    z: Optional[str] = None\n    b = True\n    bogus = None  # type: int\n[out]\ndef A.lol(self):\n    self :: __main__.A\n    r0 :: bool\nL0:\n    self.x = 200; r0 = is_error\n    return 1\ndef A.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.A\nL0:\n    __mypyc_self__.x = 20\n    return 1\ndef B.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.B\n    r0 :: dict\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object\nL0:\n    __mypyc_self__.x = 20\n    r0 = __main__.globals :: static\n    r1 = 'LOL'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = cast(str, r2)\n    __mypyc_self__.y = r3\n    r4 = box(None, 1)\n    __mypyc_self__.z = r4\n    __mypyc_self__.b = 1\n    return 1\n\n[case testSubclassDictSpecalized]\nfrom typing import Dict\nclass WelpDict(Dict[str, int]):\n    pass\ndef foo(x: WelpDict) -> None:\n    # we care that the specalized op gets used\n    x.update(x)\n[out]\ndef foo(x):\n    x :: dict\n    r0 :: i32\n    r1 :: bit\nL0:\n    r0 = CPyDict_Update(x, x)\n    r1 = r0 >= 0 :: signed\n    return 1\n\n[case testNoSpuriousLinearity]\n# Make sure that the non-trait MRO linearity check isn't affected by processing order\nclass A(B): pass\nclass B(C): pass\nclass C: pass\n[out]\n\n[case testDeletableSemanticAnalysis]\nclass Err1:\n    __deletable__ = 'x'  # E: \"__deletable__\" must be initialized with a list or tuple expression\nclass Err2:\n    __deletable__ = [\n        1  # E: Invalid \"__deletable__\" item; string literal expected\n    ]\nclass Err3:\n    __deletable__ = ['x', ['y'], 'z']  # E: Invalid \"__deletable__\" item; string literal expected\nclass Err4:\n    __deletable__ = (1,)  # E: Invalid \"__deletable__\" item; string literal expected\na = ['x']\nclass Err5:\n    __deletable__ = a  # E: \"__deletable__\" must be initialized with a list or tuple expression\n\nclass Ok1:\n    __deletable__ = ('x',)\n    x: int\nclass Ok2:\n    __deletable__ = ['x']\n    x: int\n\n[case testInvalidDeletableAttribute]\nclass NotDeletable:\n    __deletable__ = ['x']\n    x: int\n    y: int\n\ndef g(o: NotDeletable) -> None:\n    del o.x\n    del o.y  # E: \"y\" cannot be deleted \\\n             # N: Using \"__deletable__ = ['<attr>']\" in the class body enables \"del obj.<attr>\"\n\nclass Base:\n    x: int\n\nclass Deriv(Base):\n    __deletable__ = ['x']  # E: Attribute \"x\" not defined in \"Deriv\" (defined in \"Base\")\n\nclass UndefinedDeletable:\n    __deletable__ = ['x']  # E: Attribute \"x\" not defined\n\nclass DeletableProperty:\n    __deletable__ = ['prop']  # E: Cannot make property \"prop\" deletable\n\n    @property\n    def prop(self) -> int:\n        return 5\n\n[case testFinalDeletable]\nfrom typing import Final\n\nclass DeletableFinal1:\n    x: Final[int]  # E: Deletable attribute cannot be final\n\n    __deletable__ = ['x']\n\n    def __init__(self, x: int) -> None:\n        self.x = x\n\nclass DeletableFinal2:\n    X: Final = 0  # E: Deletable attribute cannot be final\n\n    __deletable__ = ['X']\n\n[case testNeedAnnotateClassVar]\nfrom typing import Final, ClassVar, Type\n\nclass C:\n    a = 'A'\n    b: str = 'B'\n    f: Final = 'F'\n    c: ClassVar = 'C'\n\nclass D(C):\n    pass\n\ndef f() -> None:\n    C.a  # E: Cannot access instance attribute \"a\" through class object \\\n         # N: (Hint: Use \"x: Final = ...\" or \"x: ClassVar = ...\" to define a class attribute)\n    C.b  # E: Cannot access instance attribute \"b\" through class object \\\n         # N: (Hint: Use \"x: Final = ...\" or \"x: ClassVar = ...\" to define a class attribute)\n    C.f\n    C.c\n\n    D.a  # E: Cannot access instance attribute \"a\" through class object \\\n         # N: (Hint: Use \"x: Final = ...\" or \"x: ClassVar = ...\" to define a class attribute)\n    D.b  # E: Cannot access instance attribute \"b\" through class object \\\n         # N: (Hint: Use \"x: Final = ...\" or \"x: ClassVar = ...\" to define a class attribute)\n    D.f\n    D.c\n\ndef g(c: Type[C], d: Type[D]) -> None:\n    c.a  # E: Cannot access instance attribute \"a\" through class object \\\n         # N: (Hint: Use \"x: Final = ...\" or \"x: ClassVar = ...\" to define a class attribute)\n    c.f\n    c.c\n\n    d.a  # E: Cannot access instance attribute \"a\" through class object \\\n         # N: (Hint: Use \"x: Final = ...\" or \"x: ClassVar = ...\" to define a class attribute)\n    d.f\n    d.c\n\n[case testSetAttributeWithDefaultInInit]\nclass C:\n    s = ''\n\n    def __init__(self, s: str) -> None:\n        self.s = s\n[out]\ndef C.__init__(self, s):\n    self :: __main__.C\n    s :: str\n    r0 :: bool\nL0:\n    self.s = s; r0 = is_error\n    return 1\ndef C.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.C\n    r0 :: str\nL0:\n    r0 = ''\n    __mypyc_self__.s = r0\n    return 1\n\n[case testBorrowAttribute]\ndef f(d: D) -> int:\n    return d.c.x\n\nclass C:\n    x: int\nclass D:\n    c: C\n[out]\ndef f(d):\n    d :: __main__.D\n    r0 :: __main__.C\n    r1 :: int\nL0:\n    r0 = borrow d.c\n    r1 = r0.x\n    keep_alive d\n    return r1\n\n[case testNoBorrowOverPropertyAccess]\nclass C:\n    d: D\nclass D:\n    @property\n    def e(self) -> E:\n        return E()\nclass E:\n    x: int\ndef f(c: C) -> int:\n    return c.d.e.x\n[out]\ndef D.e(self):\n    self :: __main__.D\n    r0 :: __main__.E\nL0:\n    r0 = E()\n    return r0\ndef f(c):\n    c :: __main__.C\n    r0 :: __main__.D\n    r1 :: __main__.E\n    r2 :: int\nL0:\n    r0 = c.d\n    r1 = r0.e\n    r2 = r1.x\n    return r2\n\n[case testBorrowResultOfCustomGetItemInIfStatement]\nfrom typing import List\n\nclass C:\n    def __getitem__(self, x: int) -> List[int]:\n        return []\n\ndef f(x: C) -> None:\n    # In this case the keep_alive must come before the branch, as otherwise\n    # reference count transform will get confused.\n    if x[1][0] == 2:\n        y = 1\n    else:\n        y = 2\n[out]\ndef C.__getitem__(self, x):\n    self :: __main__.C\n    x :: int\n    r0 :: list\nL0:\n    r0 = PyList_New(0)\n    return r0\ndef f(x):\n    x :: __main__.C\n    r0 :: list\n    r1 :: object\n    r2 :: int\n    r3 :: bit\n    y :: int\nL0:\n    r0 = x.__getitem__(2)\n    r1 = CPyList_GetItemShortBorrow(r0, 0)\n    r2 = unbox(int, r1)\n    r3 = int_eq r2, 4\n    keep_alive r0\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    y = 2\n    goto L3\nL2:\n    y = 4\nL3:\n    return 1\n\n[case testIncompatibleDefinitionOfAttributeInSubclass]\nfrom mypy_extensions import trait\n\nclass Base:\n    x: int\n\nclass Bad1(Base):\n    x: bool  # E: Type of \"x\" is incompatible with definition in class \"Base\"\n\nclass Good1(Base):\n    x: int\n\nclass Good2(Base):\n    x: int = 0\n\nclass Good3(Base):\n    x = 0\n\nclass Good4(Base):\n    def __init__(self) -> None:\n        self.x = 0\n\nclass Good5(Base):\n    def __init__(self) -> None:\n        self.x: int = 0\n\nclass Base2(Base):\n    pass\n\nclass Bad2(Base2):\n    x: bool = False  # E: Type of \"x\" is incompatible with definition in class \"Base\"\n\nclass Bad3(Base):\n    x = False  # E: Type of \"x\" is incompatible with definition in class \"Base\"\n\n@trait\nclass T:\n    y: object\n\nclass E(T):\n    y: str  # E: Type of \"y\" is incompatible with definition in trait \"T\"\n\n\n[case testNestedClasses]\ndef outer():\n    class Inner:  # E: Nested class definitions not supported\n        pass\n\n    return Inner\n\nif True:\n    class OtherInner:  # E: Nested class definitions not supported\n        pass\n\n[case testEnumClassAlias]\nfrom enum import Enum\nfrom typing import Literal, Union\n\nclass SomeEnum(Enum):\n    AVALUE = \"a\"\n\nALIAS = Literal[SomeEnum.AVALUE]\nALIAS2 = Union[Literal[SomeEnum.AVALUE], None]\n\n[case testMypycAttrNativeClassErrors]\nfrom mypy_extensions import mypyc_attr\n\n@mypyc_attr(native_class=False)\nclass AnnontatedNonExtensionClass:\n    pass\n\n@mypyc_attr(native_class=False)\nclass DerivedExplicitNonNativeClass(AnnontatedNonExtensionClass):\n    pass\n\n\ndef decorator(cls):\n    return cls\n\n@mypyc_attr(native_class=True)\n@decorator\nclass NonNativeClassContradiction():  # E: Class is marked as native_class=True but it can't be a native class. Classes that have decorators other than supported decorators can't be native classes.\n    pass\n\n\n@mypyc_attr(native_class=\"yes\")\nclass BadUse():  # E: native_class must be used with True or False only\n    pass\n\n[case testMypycAttrNativeClassMetaError]\nfrom mypy_extensions import mypyc_attr\n\n@mypyc_attr(native_class=True)\nclass M(type):  # E: Inheriting from most builtin types is unimplemented \\\n                # N: Potential workaround: @mypy_extensions.mypyc_attr(native_class=False) \\\n                # N: https://mypyc.readthedocs.io/en/stable/native_classes.html#defining-non-native-classes\n    pass\n\n@mypyc_attr(native_class=True)\nclass A(metaclass=M):  # E: Class is marked as native_class=True but it can't be a native class. Classes with a metaclass other than ABCMeta, TypingMeta or GenericMeta can't be native classes.\n    pass\n\n[case testReservedName]\nfrom typing import Any, overload\n\ndef decorator(cls):\n    return cls\n\nclass TestMethod:\n    def __mypyc_generator_helper__(self) -> None:  # E: Method name \"__mypyc_generator_helper__\" is reserved for mypyc internal use\n        pass\n\nclass TestDecorator:\n    @decorator  # E: Method name \"__mypyc_generator_helper__\" is reserved for mypyc internal use\n    def __mypyc_generator_helper__(self) -> None:\n        pass\n\nclass TestOverload:\n    @overload # E: Method name \"__mypyc_generator_helper__\" is reserved for mypyc internal use\n    def __mypyc_generator_helper__(self, x: int) -> int: ...\n\n    @overload\n    def __mypyc_generator_helper__(self, x: str) -> str: ...\n\n    def __mypyc_generator_helper__(self, x: Any) -> Any:\n        return x\n\n[case testNativeBufferFastPath]\nfrom typing import Final\nfrom mypy_extensions import u8\nfrom librt.internal import (\n    WriteBuffer, ReadBuffer, write_bool, read_bool, write_str, read_str, write_float, read_float,\n    write_int, read_int, write_tag, read_tag, write_bytes, read_bytes,\n    cache_version,\n)\n\nTag = u8\nTAG: Final[Tag] = 1\n\ndef foo() -> None:\n    b = WriteBuffer()\n    write_str(b, \"foo\")\n    write_bytes(b, b\"bar\")\n    write_bool(b, True)\n    write_float(b, 0.1)\n    write_int(b, 1)\n    write_tag(b, TAG)\n\n    rb = ReadBuffer(b.getvalue())\n    x = read_str(rb)\n    xb = read_bytes(rb)\n    y = read_bool(rb)\n    z = read_float(rb)\n    t = read_int(rb)\n    u = read_tag(rb)\n    v = cache_version()\n[out]\ndef foo():\n    r0, b :: librt.internal.WriteBuffer\n    r1 :: str\n    r2 :: None\n    r3 :: bytes\n    r4, r5, r6, r7, r8 :: None\n    r9 :: bytes\n    r10, rb :: librt.internal.ReadBuffer\n    r11, x :: str\n    r12, xb :: bytes\n    r13, y :: bool\n    r14, z :: float\n    r15, t :: int\n    r16, u, r17, v :: u8\nL0:\n    r0 = WriteBuffer_internal()\n    b = r0\n    r1 = 'foo'\n    r2 = write_str_internal(b, r1)\n    r3 = b'bar'\n    r4 = write_bytes_internal(b, r3)\n    r5 = write_bool_internal(b, 1)\n    r6 = write_float_internal(b, 0.1)\n    r7 = write_int_internal(b, 2)\n    r8 = write_tag_internal(b, 1)\n    r9 = WriteBuffer_getvalue_internal(b)\n    r10 = ReadBuffer_internal(r9)\n    rb = r10\n    r11 = read_str_internal(rb)\n    x = r11\n    r12 = read_bytes_internal(rb)\n    xb = r12\n    r13 = read_bool_internal(rb)\n    y = r13\n    r14 = read_float_internal(rb)\n    z = r14\n    r15 = read_int_internal(rb)\n    t = r15\n    r16 = read_tag_internal(rb)\n    u = r16\n    r17 = cache_version_internal()\n    v = r17\n    return 1\n\n[case testEnumFastPath]\nfrom enum import Enum\n\ndef test(e: E) -> bool:\n    return e.is_one()\n\nclass E(Enum):\n    ONE = 1\n    TWO = 2\n\n    def is_one(self) -> bool:\n        return self == E.ONE\n[out]\ndef test(e):\n    e :: __main__.E\n    r0 :: bool\nL0:\n    r0 = e.__mypyc_fast_is_one()\n    return r0\ndef is_one_E_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef is_one_E_obj.__call__(__mypyc_self__, self):\n    __mypyc_self__ :: __main__.is_one_E_obj\n    self, r0 :: __main__.E\n    r1 :: bool\n    r2 :: bit\nL0:\n    r0 = __main__.E.ONE :: static\n    if is_error(r0) goto L1 else goto L2\nL1:\n    r1 = raise NameError('value for final name \"ONE\" was not set')\n    unreachable\nL2:\n    r2 = self == r0\n    return r2\ndef E.__mypyc_fast_is_one(self):\n    self, r0 :: __main__.E\n    r1 :: bool\n    r2 :: bit\nL0:\n    r0 = __main__.E.ONE :: static\n    if is_error(r0) goto L1 else goto L2\nL1:\n    r1 = raise NameError('value for final name \"ONE\" was not set')\n    unreachable\nL2:\n    r2 = self == r0\n    return r2\n\n[case testTypeObjectName_python3_11]\nfrom typing import Any\n\nclass C: pass\nclass D(C): pass\n\ndef n1(t: type[object]) -> str:\n    return t.__name__\n\ndef n2(t: Any) -> str:\n    return t.__name__\n\ndef n3() -> str:\n    return C.__name__\n\ndef n4(t: type[C]) -> str:\n    return t.__name__\n[out]\ndef n1(t):\n    t, r0 :: object\n    r1 :: str\nL0:\n    r0 = CPy_GetName(t)\n    r1 = cast(str, r0)\n    return r1\ndef n2(t):\n    t, r0 :: object\n    r1 :: str\nL0:\n    r0 = CPy_GetName(t)\n    r1 = cast(str, r0)\n    return r1\ndef n3():\n    r0, r1 :: object\n    r2 :: str\nL0:\n    r0 = __main__.C :: type\n    r1 = CPy_GetName(r0)\n    r2 = cast(str, r1)\n    return r2\ndef n4(t):\n    t, r0 :: object\n    r1 :: str\nL0:\n    r0 = CPy_GetName(t)\n    r1 = cast(str, r0)\n    return r1\n\n[case testTypeOfObject]\nclass C: pass\nclass D(C): pass\n\ndef generic_type(x: object) -> type[object]:\n    return type(x)\n\ndef generic_class(x: object) -> type[object]:\n    return x.__class__\n\ndef native_type(x: C) -> type[object]:\n    return type(x)\n\ndef native_class(x: C) -> type[object]:\n    return x.__class__\n[out]\ndef generic_type(x):\n    x, r0 :: object\nL0:\n    r0 = CPy_TYPE(x)\n    return r0\ndef generic_class(x):\n    x :: object\n    r0 :: str\n    r1 :: object\nL0:\n    r0 = '__class__'\n    r1 = CPyObject_GetAttr(x, r0)\n    return r1\ndef native_type(x):\n    x :: __main__.C\n    r0 :: object\nL0:\n    r0 = CPy_TYPE(x)\n    return r0\ndef native_class(x):\n    x :: __main__.C\n    r0 :: object\nL0:\n    r0 = CPy_TYPE(x)\n    return r0\n\n[case testDunderNew]\nfrom __future__ import annotations\nfrom typing import Any\n\nclass Test:\n    val: int\n\n    def __new__(cls, val: int) -> Test:\n        obj = super().__new__(cls)\n        obj.val = val\n        return obj\n\nclass Test2:\n    def __new__(cls) -> Test2:\n        return super().__new__(cls)\n\nclass Sub(Test2):\n    pass\n\ndef fn() -> Test:\n    return Test.__new__(Test, 42)\n\nclass NewClassMethod:\n    val: int\n\n    @classmethod\n    def __new__(cls, val: int) -> NewClassMethod:\n        obj = super().__new__(cls)\n        obj.val = val\n        return obj\n\ndef fn2() -> NewClassMethod:\n    return NewClassMethod.__new__(42)\n\nclass NotTransformed:\n    def __new__(cls, val: int) -> Any:\n        return super().__new__(str)\n\n    def factory(cls: Any, val: int) -> Any:\n        cls = str\n        return super().__new__(cls)\n\n[out]\ndef Test.__new__(cls, val):\n    cls :: object\n    val :: int\n    r0, obj :: __main__.Test\n    r1 :: bool\nL0:\n    r0 = __mypyc__Test_setup(cls)\n    obj = r0\n    obj.val = val; r1 = is_error\n    return obj\ndef Test2.__new__(cls):\n    cls, r0 :: object\n    r1 :: __main__.Test2\nL0:\n    r0 = CPy_SetupObject(cls)\n    r1 = cast(__main__.Test2, r0)\n    return r1\ndef fn():\n    r0 :: object\n    r1 :: __main__.Test\nL0:\n    r0 = __main__.Test :: type\n    r1 = Test.__new__(r0, 84)\n    return r1\ndef NewClassMethod.__new__(cls, val):\n    cls :: object\n    val :: int\n    r0, obj :: __main__.NewClassMethod\n    r1 :: bool\nL0:\n    r0 = __mypyc__NewClassMethod_setup(cls)\n    obj = r0\n    obj.val = val; r1 = is_error\n    return obj\ndef fn2():\n    r0 :: object\n    r1 :: __main__.NewClassMethod\nL0:\n    r0 = __main__.NewClassMethod :: type\n    r1 = NewClassMethod.__new__(r0, 84)\n    return r1\ndef NotTransformed.__new__(cls, val):\n    cls :: object\n    val :: int\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[2]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: str\n    r8, r9 :: object\n    r10 :: object[1]\n    r11 :: object_ptr\n    r12 :: object\n    r13 :: str\nL0:\n    r0 = builtins :: module\n    r1 = 'super'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = __main__.NotTransformed :: type\n    r4 = [r3, cls]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 2, 0)\n    keep_alive r3, cls\n    r7 = '__new__'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = load_address PyUnicode_Type\n    r10 = [r9]\n    r11 = load_address r10\n    r12 = PyObject_Vectorcall(r8, r11, 1, 0)\n    keep_alive r9\n    r13 = cast(str, r12)\n    return r13\ndef NotTransformed.factory(cls, val):\n    cls :: object\n    val :: int\n    r0, r1 :: object\n    r2 :: str\n    r3, r4 :: object\n    r5 :: object[2]\n    r6 :: object_ptr\n    r7 :: object\n    r8 :: str\n    r9 :: object\n    r10 :: object[1]\n    r11 :: object_ptr\n    r12 :: object\nL0:\n    r0 = load_address PyUnicode_Type\n    cls = r0\n    r1 = builtins :: module\n    r2 = 'super'\n    r3 = CPyObject_GetAttr(r1, r2)\n    r4 = __main__.NotTransformed :: type\n    r5 = [r4, cls]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r3, r6, 2, 0)\n    keep_alive r4, cls\n    r8 = '__new__'\n    r9 = CPyObject_GetAttr(r7, r8)\n    r10 = [cls]\n    r11 = load_address r10\n    r12 = PyObject_Vectorcall(r9, r11, 1, 0)\n    keep_alive cls\n    return r12\n\n[case testObjectDunderNew_64bit]\nfrom __future__ import annotations\nfrom mypy_extensions import mypyc_attr\nfrom typing import Any\n\nclass Test:\n    val: int\n\n    def __new__(cls, val: int) -> Test:\n        obj = object.__new__(cls)\n        obj.val = val\n        return obj\n\nclass Test2:\n    def __new__(cls) -> Test2:\n        return object.__new__(cls)\n\nclass Sub(Test2):\n    pass\n\ndef fn() -> Test:\n    return Test.__new__(Test, 42)\n\nclass NewClassMethod:\n    val: int\n\n    @classmethod\n    def __new__(cls, val: int) -> NewClassMethod:\n        obj = object.__new__(cls)\n        obj.val = val\n        return obj\n\ndef fn2() -> NewClassMethod:\n    return NewClassMethod.__new__(42)\n\nclass NotTransformed:\n    def __new__(cls, val: int) -> Any:\n        return object.__new__(str)\n\n    def factory(cls: Any, val: int) -> Any:\n        cls = str\n        return object.__new__(cls)\n\n@mypyc_attr(native_class=False)\nclass NonNative:\n    def __new__(cls: Any) -> Any:\n        cls = str\n        return cls(\"str\")\n\nclass InheritsPython(dict):\n    def __new__(cls: Any) -> Any:\n        cls = dict\n        return cls({})\n\nclass ObjectNewOutsideDunderNew:\n    def __init__(self) -> None:\n        object.__new__(ObjectNewOutsideDunderNew)\n\ndef object_new_outside_class() -> None:\n    object.__new__(Test)\n\n[out]\ndef Test.__new__(cls, val):\n    cls :: object\n    val :: int\n    r0, obj :: __main__.Test\n    r1 :: bool\nL0:\n    r0 = __mypyc__Test_setup(cls)\n    obj = r0\n    obj.val = val; r1 = is_error\n    return obj\ndef Test2.__new__(cls):\n    cls, r0 :: object\n    r1 :: __main__.Test2\nL0:\n    r0 = CPy_SetupObject(cls)\n    r1 = cast(__main__.Test2, r0)\n    return r1\ndef fn():\n    r0 :: object\n    r1 :: __main__.Test\nL0:\n    r0 = __main__.Test :: type\n    r1 = Test.__new__(r0, 84)\n    return r1\ndef NewClassMethod.__new__(cls, val):\n    cls :: object\n    val :: int\n    r0, obj :: __main__.NewClassMethod\n    r1 :: bool\nL0:\n    r0 = __mypyc__NewClassMethod_setup(cls)\n    obj = r0\n    obj.val = val; r1 = is_error\n    return obj\ndef fn2():\n    r0 :: object\n    r1 :: __main__.NewClassMethod\nL0:\n    r0 = __main__.NewClassMethod :: type\n    r1 = NewClassMethod.__new__(r0, 84)\n    return r1\ndef NotTransformed.__new__(cls, val):\n    cls :: object\n    val :: int\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: str\n    r5 :: object[2]\n    r6 :: object_ptr\n    r7 :: object\n    r8 :: str\nL0:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = load_address PyUnicode_Type\n    r4 = '__new__'\n    r5 = [r2, r3]\n    r6 = load_address r5\n    r7 = PyObject_VectorcallMethod(r4, r6, 9223372036854775810, 0)\n    keep_alive r2, r3\n    r8 = cast(str, r7)\n    return r8\ndef NotTransformed.factory(cls, val):\n    cls :: object\n    val :: int\n    r0, r1 :: object\n    r2 :: str\n    r3 :: object\n    r4 :: str\n    r5 :: object[2]\n    r6 :: object_ptr\n    r7 :: object\nL0:\n    r0 = load_address PyUnicode_Type\n    cls = r0\n    r1 = builtins :: module\n    r2 = 'object'\n    r3 = CPyObject_GetAttr(r1, r2)\n    r4 = '__new__'\n    r5 = [r3, cls]\n    r6 = load_address r5\n    r7 = PyObject_VectorcallMethod(r4, r6, 9223372036854775810, 0)\n    keep_alive r3, cls\n    return r7\ndef __new___NonNative_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef __new___NonNative_obj.__call__(__mypyc_self__, cls):\n    __mypyc_self__ :: __main__.__new___NonNative_obj\n    cls, r0 :: object\n    r1 :: str\n    r2 :: object[1]\n    r3 :: object_ptr\n    r4 :: object\nL0:\n    r0 = load_address PyUnicode_Type\n    cls = r0\n    r1 = 'str'\n    r2 = [r1]\n    r3 = load_address r2\n    r4 = PyObject_Vectorcall(cls, r3, 1, 0)\n    keep_alive r1\n    return r4\ndef InheritsPython.__new__(cls):\n    cls, r0 :: object\n    r1 :: dict\n    r2 :: object[1]\n    r3 :: object_ptr\n    r4 :: object\nL0:\n    r0 = load_address PyDict_Type\n    cls = r0\n    r1 = PyDict_New()\n    r2 = [r1]\n    r3 = load_address r2\n    r4 = PyObject_Vectorcall(cls, r3, 1, 0)\n    keep_alive r1\n    return r4\ndef ObjectNewOutsideDunderNew.__init__(self):\n    self :: __main__.ObjectNewOutsideDunderNew\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: str\n    r5 :: object[2]\n    r6 :: object_ptr\n    r7 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = __main__.ObjectNewOutsideDunderNew :: type\n    r4 = '__new__'\n    r5 = [r2, r3]\n    r6 = load_address r5\n    r7 = PyObject_VectorcallMethod(r4, r6, 9223372036854775810, 0)\n    keep_alive r2, r3\n    return 1\ndef object_new_outside_class():\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: str\n    r5 :: object[2]\n    r6 :: object_ptr\n    r7 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = __main__.Test :: type\n    r4 = '__new__'\n    r5 = [r2, r3]\n    r6 = load_address r5\n    r7 = PyObject_VectorcallMethod(r4, r6, 9223372036854775810, 0)\n    keep_alive r2, r3\n    return 1\n\n[case testUnsupportedDunderNew]\nfrom __future__ import annotations\nfrom mypy_extensions import mypyc_attr\nfrom typing import Any\n\n@mypyc_attr(native_class=False)\nclass NonNative:\n    def __new__(cls) -> NonNative:\n        return super().__new__(cls)  # E: \"object.__new__()\" not supported for non-extension classes\n\nclass InheritsPython(dict):\n    def __new__(cls) -> InheritsPython:\n        return super().__new__(cls)  # E: \"object.__new__()\" not supported for classes inheriting from non-native classes\n\n@mypyc_attr(native_class=False)\nclass NonNativeObjectNew:\n    def __new__(cls) -> NonNativeObjectNew:\n        return object.__new__(cls)  # E: \"object.__new__()\" not supported for non-extension classes\n\nclass InheritsPythonObjectNew(dict):\n    def __new__(cls) -> InheritsPythonObjectNew:\n        return object.__new__(cls)  # E: \"object.__new__()\" not supported for classes inheriting from non-native classes\n\nclass ClsAssignment:\n    def __new__(cls: Any) -> Any:\n        cls = str  # E: Assignment to argument \"cls\" in \"__new__\" method unsupported\n        return super().__new__(cls)\n\nclass ClsTupleAssignment:\n    def __new__(class_i_want: Any, val: int) -> Any:\n        class_i_want, val = dict, 1  # E: Assignment to argument \"class_i_want\" in \"__new__\" method unsupported\n        return object.__new__(class_i_want)\n\nclass ClsListAssignment:\n    def __new__(cls: Any, val: str) -> Any:\n        [cls, val] = [object, \"object\"]  # E: Assignment to argument \"cls\" in \"__new__\" method unsupported\n        return object.__new__(cls)\n\nclass ClsNestedAssignment:\n    def __new__(cls: Any, val1: str, val2: int) -> Any:\n        [val1, [val2, cls]] = [\"val1\", [2, int]]  # E: Assignment to argument \"cls\" in \"__new__\" method unsupported\n        return object.__new__(cls)\n\nclass WrongNumberOfArgs:\n    def __new__(cls):\n        return super().__new__()  # E: \"object.__new__()\" supported only with 1 argument, got 0\n\nclass WrongNumberOfArgsObjectNew:\n    def __new__(cls):\n        return object.__new__(cls, 1)  # E: \"object.__new__()\" supported only with 1 argument, got 2\n\n[case testClassWithFreeList]\nfrom mypy_extensions import mypyc_attr, trait\n\n@mypyc_attr(free_list_len=1)\nclass UsesFreeList:\n    pass\n\n@mypyc_attr(free_list_len=None)\nclass NoFreeList:\n    pass\n\n@mypyc_attr(free_list_len=2)  # E: Unsupported value for \"free_list_len\": 2\nclass FreeListError:\n    pass\n\n@trait\n@mypyc_attr(free_list_len=1)  # E: \"free_list_len\" can't be used with traits\nclass NonNative:\n    pass\n\n@mypyc_attr(free_list_len=1, allow_interpreted_subclasses=True)  # E: \"free_list_len\" can't be used in a class that allows interpreted subclasses\nclass InterpSub:\n    pass\n\n[case testUnsupportedGetAttr]\nfrom mypy_extensions import mypyc_attr\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass AllowsInterpreted:\n    def __getattr__(self, attr: str) -> object:  # E: \"__getattr__\" not supported in class \"AllowsInterpreted\" because it allows interpreted subclasses\n        return 0\n\nclass InheritsInterpreted(dict):\n    def __getattr__(self, attr: str) -> object:  # E: \"__getattr__\" not supported in class \"InheritsInterpreted\" because it inherits from a non-native class\n        return 0\n\n@mypyc_attr(native_class=False)\nclass NonNative:\n    pass\n\nclass InheritsNonNative(NonNative):\n    def __getattr__(self, attr: str) -> object:  # E: \"__getattr__\" not supported in class \"InheritsNonNative\" because it inherits from a non-native class\n        return 0\n\n[case testGetAttr]\nfrom typing import ClassVar\n\nclass GetAttr:\n    class_var = \"x\"\n    class_var_annotated: ClassVar[int] = 99\n\n    def __init__(self, regular_attr: int):\n        self.regular_attr = regular_attr\n\n    def __getattr__(self, attr: str) -> object:\n        return attr\n\n    def method(self) -> int:\n        return 0\n\ndef test_getattr() -> list[object]:\n    i = GetAttr(42)\n    one = i.one\n    two = i.regular_attr\n    three = i.class_var\n    four = i.class_var_annotated\n    five = i.method()\n    return [one, two, three, four, five]\n\n[typing fixtures/typing-full.pyi]\n[out]\ndef GetAttr.__init__(self, regular_attr):\n    self :: __main__.GetAttr\n    regular_attr :: int\nL0:\n    self.regular_attr = regular_attr\n    return 1\ndef GetAttr.__getattr__(self, attr):\n    self :: __main__.GetAttr\n    attr :: str\nL0:\n    return attr\ndef GetAttr.__getattr____wrapper(__mypyc_self__, attr):\n    __mypyc_self__ :: __main__.GetAttr\n    attr, r0 :: object\n    r1 :: bit\n    r2 :: str\n    r3 :: object\nL0:\n    r0 = CPyObject_GenericGetAttr(__mypyc_self__, attr)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return r0\nL2:\n    r2 = cast(str, attr)\n    r3 = __mypyc_self__.__getattr__(r2)\n    return r3\ndef GetAttr.method(self):\n    self :: __main__.GetAttr\nL0:\n    return 0\ndef GetAttr.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.GetAttr\n    r0 :: str\nL0:\n    r0 = 'x'\n    __mypyc_self__.class_var = r0\n    return 1\ndef test_getattr():\n    r0, i :: __main__.GetAttr\n    r1 :: str\n    r2, one :: object\n    r3, two :: int\n    r4, three, r5 :: str\n    r6 :: object\n    r7, four, r8, five :: int\n    r9 :: list\n    r10, r11, r12 :: object\n    r13 :: ptr\nL0:\n    r0 = GetAttr(84)\n    i = r0\n    r1 = 'one'\n    r2 = CPyObject_GetAttr(i, r1)\n    one = r2\n    r3 = i.regular_attr\n    two = r3\n    r4 = i.class_var\n    three = r4\n    r5 = 'class_var_annotated'\n    r6 = CPyObject_GetAttr(i, r5)\n    r7 = unbox(int, r6)\n    four = r7\n    r8 = i.method()\n    five = r8\n    r9 = PyList_New(5)\n    r10 = box(int, two)\n    r11 = box(int, four)\n    r12 = box(int, five)\n    r13 = list_items r9\n    buf_init_item r13, 0, one\n    buf_init_item r13, 1, r10\n    buf_init_item r13, 2, three\n    buf_init_item r13, 3, r11\n    buf_init_item r13, 4, r12\n    keep_alive r9\n    return r9\n\n[case testUnsupportedSetAttr]\nfrom mypy_extensions import mypyc_attr\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass AllowsInterpreted:\n    def __setattr__(self, attr: str, val: object) -> None:  # E: \"__setattr__\" not supported in class \"AllowsInterpreted\" because it allows interpreted subclasses\n        pass\n\n    def __delattr__(self, attr: str) -> None:\n        pass\n\nclass InheritsInterpreted(dict):\n    def __setattr__(self, attr: str, val: object) -> None:  # E: \"__setattr__\" not supported in class \"InheritsInterpreted\" because it inherits from a non-native class\n        pass\n\n    def __delattr__(self, attr: str) -> None:\n        pass\n\n@mypyc_attr(native_class=False)\nclass NonNative:\n    def __setattr__(self, attr: str, val: object) -> None:\n        pass\n\nclass InheritsNonNative(NonNative):\n    def __setattr__(self, attr: str, val: object) -> None:  # E: \"__setattr__\" not supported in class \"InheritsNonNative\" because it inherits from a non-native class\n        pass\n\n    def __delattr__(self, attr: str) -> None:\n        pass\n\n[case testUnsupportedDelAttr]\nclass SetAttr:\n    def __setattr__(self, attr: str, val: object) -> None:\n        pass\n\nclass NoSetAttr:\n    def __delattr__(self, attr: str) -> None:  # E: \"__delattr__\" supported only in classes that also override \"__setattr__\", or inherit from a native class that overrides it.\n        pass\n\nclass InheritedSetAttr(SetAttr):\n    def __delattr__(self, attr: str) -> None:\n        pass\n\n[case testSetAttr]\nfrom typing import ClassVar\nclass SetAttr:\n    _attributes: dict[str, object]\n    regular_attr: int\n    class_var: ClassVar[str] = \"x\"\n\n    def __init__(self, regular_attr: int, extra_attrs: dict[str, object], new_attr: str, new_val: object) -> None:\n        super().__setattr__(\"_attributes\", extra_attrs)\n        object.__setattr__(self, \"regular_attr\", regular_attr)\n\n        super().__setattr__(new_attr, new_val)\n        object.__setattr__(self, new_attr, new_val)\n\n    def __setattr__(self, key: str, val: object) -> None:\n        if key == \"regular_attr\":\n            super().__setattr__(\"regular_attr\", val)\n        elif key == \"class_var\":\n            raise AttributeError()\n        else:\n            self._attributes[key] = val\n\ndef test(attr: str, val: object) -> None:\n    i = SetAttr(99, {}, attr, val)\n    i.regular_attr = 100\n    i.new_attr = 101\n\n    object.__setattr__(i, \"regular_attr\", 11)\n    object.__setattr__(i, attr, val)\n\n[typing fixtures/typing-full.pyi]\n[out]\ndef SetAttr.__init__(self, regular_attr, extra_attrs, new_attr, new_val):\n    self :: __main__.SetAttr\n    regular_attr :: int\n    extra_attrs :: dict\n    new_attr :: str\n    new_val :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: i32\n    r3 :: bit\nL0:\n    self._attributes = extra_attrs\n    self.regular_attr = regular_attr\n    r0 = CPyObject_GenericSetAttr(self, new_attr, new_val)\n    r1 = r0 >= 0 :: signed\n    r2 = CPyObject_GenericSetAttr(self, new_attr, new_val)\n    r3 = r2 >= 0 :: signed\n    return 1\ndef SetAttr.__setattr__(self, key, val):\n    self :: __main__.SetAttr\n    key :: str\n    val :: object\n    r0 :: str\n    r1 :: bool\n    r2 :: int\n    r3 :: bool\n    r4 :: str\n    r5 :: bool\n    r6 :: object\n    r7 :: str\n    r8, r9 :: object\n    r10 :: dict\n    r11 :: i32\n    r12 :: bit\nL0:\n    r0 = 'regular_attr'\n    r1 = CPyStr_EqualLiteral(key, r0, 12)\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = unbox(int, val)\n    self.regular_attr = r2; r3 = is_error\n    goto L6\nL2:\n    r4 = 'class_var'\n    r5 = CPyStr_EqualLiteral(key, r4, 9)\n    if r5 goto L3 else goto L4 :: bool\nL3:\n    r6 = builtins :: module\n    r7 = 'AttributeError'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = PyObject_Vectorcall(r8, 0, 0, 0)\n    CPy_Raise(r9)\n    unreachable\nL4:\n    r10 = self._attributes\n    r11 = CPyDict_SetItem(r10, key, val)\n    r12 = r11 >= 0 :: signed\nL5:\nL6:\n    return 1\ndef SetAttr.__setattr____wrapper(__mypyc_self__, attr, value):\n    __mypyc_self__ :: __main__.SetAttr\n    attr, value :: object\n    r0 :: bit\n    r1 :: i32\n    r2 :: bit\n    r3 :: str\n    r4 :: None\nL0:\n    r0 = value == 0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = CPyObject_GenericSetAttr(__mypyc_self__, attr, 0)\n    r2 = r1 >= 0 :: signed\n    return 0\nL2:\n    r3 = cast(str, attr)\n    r4 = __mypyc_self__.__setattr__(r3, value)\n    return 0\ndef test(attr, val):\n    attr :: str\n    val :: object\n    r0 :: dict\n    r1, i :: __main__.SetAttr\n    r2 :: str\n    r3 :: object\n    r4 :: None\n    r5 :: str\n    r6 :: object\n    r7 :: i32\n    r8 :: bit\n    r9 :: str\n    r10 :: object\n    r11 :: i32\n    r12 :: bit\n    r13 :: i32\n    r14 :: bit\nL0:\n    r0 = PyDict_New()\n    r1 = SetAttr(198, r0, attr, val)\n    i = r1\n    r2 = 'regular_attr'\n    r3 = object 100\n    r4 = i.__setattr__(r2, r3)\n    r5 = 'new_attr'\n    r6 = object 101\n    r7 = PyObject_SetAttr(i, r5, r6)\n    r8 = r7 >= 0 :: signed\n    r9 = 'regular_attr'\n    r10 = object 11\n    r11 = CPyObject_GenericSetAttr(i, r9, r10)\n    r12 = r11 >= 0 :: signed\n    r13 = CPyObject_GenericSetAttr(i, attr, val)\n    r14 = r13 >= 0 :: signed\n    return 1\n\n[case testSetAttrAndDelAttr]\nfrom typing import ClassVar\nclass SetAttr:\n    _attributes: dict[str, object]\n    regular_attr: int\n    class_var: ClassVar[str] = \"x\"\n\n    def __init__(self, regular_attr: int, extra_attrs: dict[str, object], new_attr: str, new_val: object) -> None:\n        super().__setattr__(\"_attributes\", extra_attrs)\n        object.__setattr__(self, \"regular_attr\", regular_attr)\n\n        super().__setattr__(new_attr, new_val)\n        object.__setattr__(self, new_attr, new_val)\n\n    def __setattr__(self, key: str, val: object) -> None:\n        if key == \"regular_attr\":\n            super().__setattr__(\"regular_attr\", val)\n        elif key == \"class_var\":\n            raise AttributeError()\n        else:\n            self._attributes[key] = val\n\n    def __delattr__(self, key: str) -> None:\n        del self._attributes[key]\n\n[typing fixtures/typing-full.pyi]\n[out]\ndef SetAttr.__init__(self, regular_attr, extra_attrs, new_attr, new_val):\n    self :: __main__.SetAttr\n    regular_attr :: int\n    extra_attrs :: dict\n    new_attr :: str\n    new_val :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: i32\n    r3 :: bit\nL0:\n    self._attributes = extra_attrs\n    self.regular_attr = regular_attr\n    r0 = CPyObject_GenericSetAttr(self, new_attr, new_val)\n    r1 = r0 >= 0 :: signed\n    r2 = CPyObject_GenericSetAttr(self, new_attr, new_val)\n    r3 = r2 >= 0 :: signed\n    return 1\ndef SetAttr.__setattr__(self, key, val):\n    self :: __main__.SetAttr\n    key :: str\n    val :: object\n    r0 :: str\n    r1 :: bool\n    r2 :: int\n    r3 :: bool\n    r4 :: str\n    r5 :: bool\n    r6 :: object\n    r7 :: str\n    r8, r9 :: object\n    r10 :: dict\n    r11 :: i32\n    r12 :: bit\nL0:\n    r0 = 'regular_attr'\n    r1 = CPyStr_EqualLiteral(key, r0, 12)\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = unbox(int, val)\n    self.regular_attr = r2; r3 = is_error\n    goto L6\nL2:\n    r4 = 'class_var'\n    r5 = CPyStr_EqualLiteral(key, r4, 9)\n    if r5 goto L3 else goto L4 :: bool\nL3:\n    r6 = builtins :: module\n    r7 = 'AttributeError'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = PyObject_Vectorcall(r8, 0, 0, 0)\n    CPy_Raise(r9)\n    unreachable\nL4:\n    r10 = self._attributes\n    r11 = CPyDict_SetItem(r10, key, val)\n    r12 = r11 >= 0 :: signed\nL5:\nL6:\n    return 1\ndef SetAttr.__setattr____wrapper(__mypyc_self__, attr, value):\n    __mypyc_self__ :: __main__.SetAttr\n    attr, value :: object\n    r0 :: bit\n    r1 :: str\n    r2 :: None\n    r3 :: str\n    r4 :: None\nL0:\n    r0 = value == 0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = cast(str, attr)\n    r2 = __mypyc_self__.__delattr__(r1)\n    return 0\nL2:\n    r3 = cast(str, attr)\n    r4 = __mypyc_self__.__setattr__(r3, value)\n    return 0\ndef SetAttr.__delattr__(self, key):\n    self :: __main__.SetAttr\n    key :: str\n    r0 :: dict\n    r1 :: i32\n    r2 :: bit\nL0:\n    r0 = self._attributes\n    r1 = PyObject_DelItem(r0, key)\n    r2 = r1 >= 0 :: signed\n    return 1\n\n[case testUntransformedSetAttr_64bit]\nfrom mypy_extensions import mypyc_attr\n\nclass SetAttr:\n    def super_missing_args(self):\n        super().__setattr__()\n        super().__setattr__(\"attr\")\n\n    def object_missing_args(self):\n        object.__setattr__()\n        object.__setattr__(self)\n        object.__setattr__(self, \"attr\")\n\n@mypyc_attr(native_class=False)\nclass NonNative:\n    def super_setattr(self, key: str, val: object) -> None:\n        super().__setattr__(key, val)\n\n    def object_setattr(self, key: str, val: object) -> None:\n        object.__setattr__(self, key, val)\n\nclass InheritsPython(NonNative):\n    def super_setattr(self, key: str, val: object) -> None:\n        super().__setattr__(key, val)\n\n    def object_setattr(self, key: str, val: object) -> None:\n        object.__setattr__(self, key, val)\n\nclass BuiltInBase(dict):\n    def super_setattr(self, key: str, val: object) -> None:\n        super().__setattr__(key, val)\n\n    def object_setattr(self, key: str, val: object) -> None:\n        object.__setattr__(self, key, val)\n\n[typing fixtures/typing-full.pyi]\n[out]\ndef SetAttr.super_missing_args(self):\n    self :: __main__.SetAttr\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[2]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: str\n    r8, r9, r10 :: object\n    r11 :: str\n    r12, r13 :: object\n    r14 :: object[2]\n    r15 :: object_ptr\n    r16 :: object\n    r17 :: str\n    r18 :: object\n    r19 :: str\n    r20 :: object[1]\n    r21 :: object_ptr\n    r22, r23 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'super'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = __main__.SetAttr :: type\n    r4 = [r3, self]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 2, 0)\n    keep_alive r3, self\n    r7 = '__setattr__'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = PyObject_Vectorcall(r8, 0, 0, 0)\n    r10 = builtins :: module\n    r11 = 'super'\n    r12 = CPyObject_GetAttr(r10, r11)\n    r13 = __main__.SetAttr :: type\n    r14 = [r13, self]\n    r15 = load_address r14\n    r16 = PyObject_Vectorcall(r12, r15, 2, 0)\n    keep_alive r13, self\n    r17 = '__setattr__'\n    r18 = CPyObject_GetAttr(r16, r17)\n    r19 = 'attr'\n    r20 = [r19]\n    r21 = load_address r20\n    r22 = PyObject_Vectorcall(r18, r21, 1, 0)\n    keep_alive r19\n    r23 = box(None, 1)\n    return r23\ndef SetAttr.object_missing_args(self):\n    self :: __main__.SetAttr\n    r0 :: object\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6, r7 :: object\n    r8 :: str\n    r9 :: object\n    r10 :: str\n    r11 :: object[2]\n    r12 :: object_ptr\n    r13, r14 :: object\n    r15 :: str\n    r16 :: object\n    r17, r18 :: str\n    r19 :: object[3]\n    r20 :: object_ptr\n    r21, r22 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = '__setattr__'\n    r4 = [r2]\n    r5 = load_address r4\n    r6 = PyObject_VectorcallMethod(r3, r5, 9223372036854775809, 0)\n    keep_alive r2\n    r7 = builtins :: module\n    r8 = 'object'\n    r9 = CPyObject_GetAttr(r7, r8)\n    r10 = '__setattr__'\n    r11 = [r9, self]\n    r12 = load_address r11\n    r13 = PyObject_VectorcallMethod(r10, r12, 9223372036854775810, 0)\n    keep_alive r9, self\n    r14 = builtins :: module\n    r15 = 'object'\n    r16 = CPyObject_GetAttr(r14, r15)\n    r17 = 'attr'\n    r18 = '__setattr__'\n    r19 = [r16, self, r17]\n    r20 = load_address r19\n    r21 = PyObject_VectorcallMethod(r18, r20, 9223372036854775811, 0)\n    keep_alive r16, self, r17\n    r22 = box(None, 1)\n    return r22\ndef super_setattr_NonNative_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef super_setattr_NonNative_obj.__call__(__mypyc_self__, self, key, val):\n    __mypyc_self__ :: __main__.super_setattr_NonNative_obj\n    self :: __main__.NonNative\n    key :: str\n    val, r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[2]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: str\n    r8 :: object\n    r9 :: object[2]\n    r10 :: object_ptr\n    r11 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'super'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = __main__.NonNative :: type\n    r4 = [r3, self]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 2, 0)\n    keep_alive r3, self\n    r7 = '__setattr__'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = [key, val]\n    r10 = load_address r9\n    r11 = PyObject_Vectorcall(r8, r10, 2, 0)\n    keep_alive key, val\n    return 1\ndef object_setattr_NonNative_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef object_setattr_NonNative_obj.__call__(__mypyc_self__, self, key, val):\n    __mypyc_self__ :: __main__.object_setattr_NonNative_obj\n    self :: __main__.NonNative\n    key :: str\n    val, r0 :: object\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object[4]\n    r5 :: object_ptr\n    r6 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = '__setattr__'\n    r4 = [r2, self, key, val]\n    r5 = load_address r4\n    r6 = PyObject_VectorcallMethod(r3, r5, 9223372036854775812, 0)\n    keep_alive r2, self, key, val\n    return 1\ndef InheritsPython.super_setattr(self, key, val):\n    self :: __main__.InheritsPython\n    key :: str\n    val, r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[2]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: str\n    r8 :: object\n    r9 :: object[2]\n    r10 :: object_ptr\n    r11 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'super'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = __main__.InheritsPython :: type\n    r4 = [r3, self]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 2, 0)\n    keep_alive r3, self\n    r7 = '__setattr__'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = [key, val]\n    r10 = load_address r9\n    r11 = PyObject_Vectorcall(r8, r10, 2, 0)\n    keep_alive key, val\n    return 1\ndef InheritsPython.object_setattr(self, key, val):\n    self :: __main__.InheritsPython\n    key :: str\n    val, r0 :: object\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object[4]\n    r5 :: object_ptr\n    r6 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = '__setattr__'\n    r4 = [r2, self, key, val]\n    r5 = load_address r4\n    r6 = PyObject_VectorcallMethod(r3, r5, 9223372036854775812, 0)\n    keep_alive r2, self, key, val\n    return 1\ndef BuiltInBase.super_setattr(self, key, val):\n    self :: dict\n    key :: str\n    val, r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: object[2]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: str\n    r8 :: object\n    r9 :: object[2]\n    r10 :: object_ptr\n    r11 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'super'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = __main__.BuiltInBase :: type\n    r4 = [r3, self]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 2, 0)\n    keep_alive r3, self\n    r7 = '__setattr__'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = [key, val]\n    r10 = load_address r9\n    r11 = PyObject_Vectorcall(r8, r10, 2, 0)\n    keep_alive key, val\n    return 1\ndef BuiltInBase.object_setattr(self, key, val):\n    self :: dict\n    key :: str\n    val, r0 :: object\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object[4]\n    r5 :: object_ptr\n    r6 :: object\nL0:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = '__setattr__'\n    r4 = [r2, self, key, val]\n    r5 = load_address r4\n    r6 = PyObject_VectorcallMethod(r3, r5, 9223372036854775812, 0)\n    keep_alive r2, self, key, val\n    return 1\n\n[case testInvalidMypycAttr]\nfrom mypy_extensions import mypyc_attr\n\n@mypyc_attr(\"allow_interpreted_subclasses\", \"invalid_arg\")  # E: \"invalid_arg\" is not a supported \"mypyc_attr\" \\\n                                                            # N: supported keys: \"acyclic\", \"allow_interpreted_subclasses\", \"free_list_len\", \"native_class\", \"serializable\"\nclass InvalidArg:\n    pass\n@mypyc_attr(invalid_kwarg=True)  # E: \"invalid_kwarg\" is not a supported \"mypyc_attr\" \\\n                                 # N: supported keys: \"acyclic\", \"allow_interpreted_subclasses\", \"free_list_len\", \"native_class\", \"serializable\"\nclass InvalidKwarg:\n    pass\n@mypyc_attr(str())  # E: All \"mypyc_attr\" positional arguments must be string literals.\nclass InvalidLiteral:\n    pass\n"
  },
  {
    "path": "mypyc/test-data/irbuild-constant-fold.test",
    "content": "[case testIntConstantFolding]\ndef bin_ops() -> None:\n    add = 15 + 47\n    add_mul = (2 + 3) * 5\n    sub = 7 - 11\n    div = 3 / 2\n    bit_and = 6 & 10\n    bit_or = 6 | 10\n    bit_xor = 6 ^ 10\n    lshift = 5 << 2\n    rshift = 13 >> 2\n    lshift0 = 5 << 0\n    rshift0 = 13 >> 0\ndef unary_ops() -> None:\n    neg1 = -5\n    neg2 = --1\n    neg3 = -0\n    pos = +5\n    inverted1 = ~0\n    inverted2 = ~5\n    inverted3 = ~3\ndef pow() -> None:\n    p0 = 3**0\n    p1 = 3**5\n    p2 = (-5)**3\n    p3 = 0**0\n[out]\ndef bin_ops():\n    add, add_mul, sub :: int\n    div :: float\n    bit_and, bit_or, bit_xor, lshift, rshift, lshift0, rshift0 :: int\nL0:\n    add = 124\n    add_mul = 50\n    sub = -8\n    div = 1.5\n    bit_and = 4\n    bit_or = 28\n    bit_xor = 24\n    lshift = 40\n    rshift = 6\n    lshift0 = 10\n    rshift0 = 26\n    return 1\ndef unary_ops():\n    neg1, neg2, neg3, pos, inverted1, inverted2, inverted3 :: int\nL0:\n    neg1 = -10\n    neg2 = 2\n    neg3 = 0\n    pos = 10\n    inverted1 = -2\n    inverted2 = -12\n    inverted3 = -8\n    return 1\ndef pow():\n    p0, p1, p2, p3 :: int\nL0:\n    p0 = 2\n    p1 = 486\n    p2 = -250\n    p3 = 2\n    return 1\n\n[case testIntConstantFoldingDivMod]\ndef div() -> None:\n    div1 = 25 // 5\n    div2 = 24 // 5\n    div3 = 29 // 5\n    div4 = 30 // 5\n    div_zero = 0 // 5\n    neg1 = -1 // 3\n    neg2 = -2 // 3\n    neg3 = -3 // 3\n    neg4 = -4 // 3\n    neg_neg = -765467 // -234\n    pos_neg = 983745 // -7864\ndef mod() -> None:\n    mod1 = 25 % 5\n    mod2 = 24 % 5\n    mod3 = 29 % 5\n    mod4 = 30 % 5\n    mod_zero = 0 % 5\n    neg1 = -4 % 3\n    neg2 = -5 % 3\n    neg3 = -6 % 3\n    neg4 = -7 % 3\n    neg_neg = -765467 % -234\n    pos_neg = 983745 % -7864\n[out]\ndef div():\n    div1, div2, div3, div4, div_zero, neg1, neg2, neg3, neg4, neg_neg, pos_neg :: int\nL0:\n    div1 = 10\n    div2 = 8\n    div3 = 10\n    div4 = 12\n    div_zero = 0\n    neg1 = -2\n    neg2 = -2\n    neg3 = -2\n    neg4 = -4\n    neg_neg = 6542\n    pos_neg = -252\n    return 1\ndef mod():\n    mod1, mod2, mod3, mod4, mod_zero, neg1, neg2, neg3, neg4, neg_neg, pos_neg :: int\nL0:\n    mod1 = 0\n    mod2 = 8\n    mod3 = 8\n    mod4 = 0\n    mod_zero = 0\n    neg1 = 4\n    neg2 = 2\n    neg3 = 0\n    neg4 = 4\n    neg_neg = -106\n    pos_neg = -14238\n    return 1\n\n[case testIntConstantFoldingUnsupportedCases]\ndef error_cases() -> None:\n    div_by_zero = 5 / 0\n    floor_div_by_zero = 5 // 0\n    mod_by_zero = 5 % 0\n    lshift_neg = 6 << -1\n    rshift_neg = 7 >> -1\ndef unsupported_pow() -> None:\n    p = 3 ** (-1)\n[out]\ndef error_cases():\n    r0, div_by_zero :: float\n    r1, floor_div_by_zero, r2, mod_by_zero, r3, lshift_neg, r4, rshift_neg :: int\nL0:\n    r0 = CPyTagged_TrueDivide(10, 0)\n    div_by_zero = r0\n    r1 = CPyTagged_FloorDivide(10, 0)\n    floor_div_by_zero = r1\n    r2 = CPyTagged_Remainder(10, 0)\n    mod_by_zero = r2\n    r3 = CPyTagged_Lshift(12, -2)\n    lshift_neg = r3\n    r4 = CPyTagged_Rshift(14, -2)\n    rshift_neg = r4\n    return 1\ndef unsupported_pow():\n    r0, r1, r2 :: object\n    r3, p :: float\nL0:\n    r0 = object 3\n    r1 = object -1\n    r2 = CPyNumber_Power(r0, r1)\n    r3 = unbox(float, r2)\n    p = r3\n    return 1\n\n[case testIntConstantFoldingBigIntResult_64bit]\ndef long_and_short() -> None:\n    # The smallest and largest representable short integers\n    short1 =  0x3ffffffffffffff0 + 0xf  # (1 << 62) - 1\n    short2 = -0x3fffffffffffffff - 1    # -(1 << 62)\n    short3 = -0x4000000000000000\n    # Smallest big integers by absolute value\n    big1 = 1 << 62\n    big2 = 0x4000000000000000  # 1 << 62\n    big3 = -(1 << 62) - 1\n    big4 = -0x4000000000000001  # -(1 << 62) - 1\n    big5 = 123**41\n[out]\ndef long_and_short():\n    short1, short2, short3, r0, big1, r1, big2, r2, big3, r3, big4, r4, big5 :: int\nL0:\n    short1 = 9223372036854775806\n    short2 = -9223372036854775808\n    short3 = -9223372036854775808\n    r0 = object 4611686018427387904\n    big1 = r0\n    r1 = object 4611686018427387904\n    big2 = r1\n    r2 = object -4611686018427387905\n    big3 = r2\n    r3 = object -4611686018427387905\n    big4 = r3\n    r4 = object 48541095000524544750127162673405880068636916264012200797813591925035550682238127143323\n    big5 = r4\n    return 1\n\n[case testConstantFoldFormatArgs]\n# This only tests that the callee and args are constant folded,\n# it is not intended to test the result.\nfrom typing import Any, Final\n\nFMT: Final = \"{} {}\"\n\ndef f() -> str:\n    return FMT.format(400 + 20, \"roll\" + \"up\")\n[out]\ndef f():\n    r0, r1, r2, r3 :: str\nL0:\n    r0 = CPyTagged_Str(840)\n    r1 = 'rollup'\n    r2 = ' '\n    r3 = CPyStr_Build(3, r0, r2, r1)\n    return r3\n\n[case testIntConstantFoldingFinal]\nfrom typing import Final\nX: Final = 5\nY: Final = 2 + 4\n\ndef f() -> None:\n    a = X + 1\n    a = Y + 1\n[out]\ndef f():\n    a :: int\nL0:\n    a = 12\n    a = 14\n    return 1\n\n[case testIntConstantFoldingClassFinal]\nfrom typing import Final\nclass C:\n    X: Final = 5\n\ndef f() -> None:\n    a = C.X + 1\n[out]\ndef C.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.C\nL0:\n    __mypyc_self__.X = 10\n    return 1\ndef f():\n    a :: int\nL0:\n    a = 12\n    return 1\n\n[case testFloatConstantFolding]\nfrom typing import Final\n\nN: Final = 1.5\nN2: Final = 1.5 * 2\n\ndef bin_ops() -> None:\n    add = 0.5 + 0.5\n    add_mul = (1.5 + 3.5) * 5.0\n    sub = 7.0 - 7.5\n    div = 3.0 / 2.0\n    floor_div = 3.0 // 2.0\ndef bin_ops_neg() -> None:\n    add = 0.5 + -0.5\n    add_mul = (-1.5 + 3.5) * -5.0\n    add_mul2 = (1.5 + -3.5) * -5.0\n    sub = 7.0 - -7.5\n    div = 3.0 / -2.0\n    floor_div = 3.0 // -2.0\ndef unary_ops() -> None:\n    neg1 = -5.5\n    neg2 = --1.5\n    neg3 = -0.0\n    pos = +5.5\ndef pow() -> None:\n    p0 = 16.0**0\n    p1 = 16.0**0.5\n    p2 = (-5.0)**3\n    p3 = 16.0**(-0)\n    p4 = 16.0**(-0.5)\n    p5 = (-2.0)**(-1)\ndef error_cases() -> None:\n    div = 2.0 / 0.0\n    floor_div = 2.0 // 0.0\n    power_imag = (-2.0)**0.5\n    power_imag2 = (-2.0)**(-0.5)\n    power_overflow = 2.0**10000.0\ndef final_floats() -> None:\n    add1 = N + 1.2\n    add2 = N + N2\n    add3 = -1.2 + N2\n[out]\ndef bin_ops():\n    add, add_mul, sub, div, floor_div :: float\nL0:\n    add = 1.0\n    add_mul = 25.0\n    sub = -0.5\n    div = 1.5\n    floor_div = 1.0\n    return 1\ndef bin_ops_neg():\n    add, add_mul, add_mul2, sub, div, floor_div :: float\nL0:\n    add = 0.0\n    add_mul = -10.0\n    add_mul2 = 10.0\n    sub = 14.5\n    div = -1.5\n    floor_div = -2.0\n    return 1\ndef unary_ops():\n    neg1, neg2, neg3, pos :: float\nL0:\n    neg1 = -5.5\n    neg2 = 1.5\n    neg3 = -0.0\n    pos = 5.5\n    return 1\ndef pow():\n    p0, p1, p2, p3, p4, p5 :: float\nL0:\n    p0 = 1.0\n    p1 = 4.0\n    p2 = -125.0\n    p3 = 1.0\n    p4 = 0.25\n    p5 = -0.5\n    return 1\ndef error_cases():\n    r0 :: bit\n    r1 :: bool\n    r2, div, r3, floor_div :: float\n    r4, r5, r6 :: object\n    r7, power_imag :: float\n    r8, r9, r10 :: object\n    r11, power_imag2 :: float\n    r12, r13, r14 :: object\n    r15, power_overflow :: float\nL0:\n    r0 = 0.0 == 0.0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = raise ZeroDivisionError('float division by zero')\n    unreachable\nL2:\n    r2 = 2.0 / 0.0\n    div = r2\n    r3 = CPyFloat_FloorDivide(2.0, 0.0)\n    floor_div = r3\n    r4 = box(float, -2.0)\n    r5 = box(float, 0.5)\n    r6 = CPyNumber_Power(r4, r5)\n    r7 = unbox(float, r6)\n    power_imag = r7\n    r8 = box(float, -2.0)\n    r9 = box(float, -0.5)\n    r10 = CPyNumber_Power(r8, r9)\n    r11 = unbox(float, r10)\n    power_imag2 = r11\n    r12 = box(float, 2.0)\n    r13 = box(float, 10000.0)\n    r14 = CPyNumber_Power(r12, r13)\n    r15 = unbox(float, r14)\n    power_overflow = r15\n    return 1\ndef final_floats():\n    add1, add2, add3 :: float\nL0:\n    add1 = 2.7\n    add2 = 4.5\n    add3 = 1.8\n    return 1\n\n[case testMixedFloatIntConstantFolding]\ndef bin_ops() -> None:\n    add = 1 + 0.5\n    sub = 1 - 0.5\n    mul = 0.5 * 5\n    div = 5 / 0.5\n    floor_div = 9.5 // 5\ndef error_cases() -> None:\n    div = 2.0 / 0\n    floor_div = 2.0 // 0\n    power_overflow = 2.0**10000\n[out]\ndef bin_ops():\n    add, sub, mul, div, floor_div :: float\nL0:\n    add = 1.5\n    sub = 0.5\n    mul = 2.5\n    div = 10.0\n    floor_div = 1.0\n    return 1\ndef error_cases():\n    r0 :: bit\n    r1 :: bool\n    r2, div, r3, floor_div :: float\n    r4, r5, r6 :: object\n    r7, power_overflow :: float\nL0:\n    r0 = 0.0 == 0.0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = raise ZeroDivisionError('float division by zero')\n    unreachable\nL2:\n    r2 = 2.0 / 0.0\n    div = r2\n    r3 = CPyFloat_FloorDivide(2.0, 0.0)\n    floor_div = r3\n    r4 = box(float, 2.0)\n    r5 = box(float, 10000.0)\n    r6 = CPyNumber_Power(r4, r5)\n    r7 = unbox(float, r6)\n    power_overflow = r7\n    return 1\n\n[case testStrConstantFolding]\nfrom typing import Final\n\nS: Final = 'z'\nN: Final = 2\n\ndef f() -> None:\n    x = 'foo' + 'bar'\n    y = 'x' + 'y' + S\n    mul = \"foobar\" * 2\n    mul2 = N * \"foobar\"\n[out]\ndef f():\n    r0, x, r1, y, r2, mul, r3, mul2 :: str\nL0:\n    r0 = 'foobar'\n    x = r0\n    r1 = 'xyz'\n    y = r1\n    r2 = 'foobarfoobar'\n    mul = r2\n    r3 = 'foobarfoobar'\n    mul2 = r3\n    return 1\n\n[case testBytesConstantFolding]\nfrom typing import Final\n\nN: Final = 2\n\ndef f() -> None:\n    # Unfortunately, mypy doesn't store the bytes value of final refs.\n    x = b'foo' + b'bar'\n    mul = b\"foobar\" * 2\n    mul2 = N * b\"foobar\"\n[out]\ndef f():\n    r0, x, r1, mul, r2, mul2 :: bytes\nL0:\n    r0 = b'foobar'\n    x = r0\n    r1 = b'foobarfoobar'\n    mul = r1\n    r2 = b'foobarfoobar'\n    mul2 = r2\n    return 1\n\n[case testComplexConstantFolding]\nfrom typing import Final\n\nN: Final = 1\nFLOAT_N: Final = 1.5\n\ndef integral() -> None:\n    pos = 1+2j\n    pos_2 = 2j+N\n    neg = 1-2j\n    neg_2 = 2j-N\ndef floating() -> None:\n    pos = 1.5+2j\n    pos_2 = 2j+FLOAT_N\n    neg = 1.5-2j\n    neg_2 = 2j-FLOAT_N\n[out]\ndef integral():\n    r0, pos, r1, pos_2, r2, neg, r3, neg_2 :: object\nL0:\n    r0 = (1+2j)\n    pos = r0\n    r1 = (1+2j)\n    pos_2 = r1\n    r2 = (1-2j)\n    neg = r2\n    r3 = (-1+2j)\n    neg_2 = r3\n    return 1\ndef floating():\n    r0, pos, r1, pos_2, r2, neg, r3, neg_2 :: object\nL0:\n    r0 = (1.5+2j)\n    pos = r0\n    r1 = (1.5+2j)\n    pos_2 = r1\n    r2 = (1.5-2j)\n    neg = r2\n    r3 = (-1.5+2j)\n    neg_2 = r3\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-dict.test",
    "content": "[case testDictGet]\nfrom typing import Dict\ndef f(d: Dict[int, bool]) -> bool:\n    return d[0]\n[out]\ndef f(d):\n    d :: dict\n    r0, r1 :: object\n    r2 :: bool\nL0:\n    r0 = object 0\n    r1 = CPyDict_GetItem(d, r0)\n    r2 = unbox(bool, r1)\n    return r2\n\n[case testDictSet]\nfrom typing import Dict\ndef f(d: Dict[int, bool]) -> None:\n    d[0] = False\n[out]\ndef f(d):\n    d :: dict\n    r0, r1 :: object\n    r2 :: i32\n    r3 :: bit\nL0:\n    r0 = object 0\n    r1 = box(bool, 0)\n    r2 = CPyDict_SetItem(d, r0, r1)\n    r3 = r2 >= 0 :: signed\n    return 1\n\n[case testNewEmptyDict]\nfrom typing import Dict\ndef f() -> None:\n    d = {}  # type: Dict[bool, int]\n[out]\ndef f():\n    r0, d :: dict\nL0:\n    r0 = PyDict_New()\n    d = r0\n    return 1\n\n[case testNewEmptyDictViaFunc]\nfrom typing import Dict\ndef f() -> None:\n    d: Dict[bool, int] = dict()\n\n[out]\ndef f():\n    r0, d :: dict\nL0:\n    r0 = PyDict_New()\n    d = r0\n    return 1\n\n[case testNewDictWithValues]\ndef f(x: object) -> None:\n    d = {1: 2, '': x}\n[out]\ndef f(x):\n    x :: object\n    r0 :: str\n    r1, r2 :: object\n    r3, d :: dict\nL0:\n    r0 = ''\n    r1 = object 1\n    r2 = object 2\n    r3 = CPyDict_Build(2, r1, r2, r0, x)\n    d = r3\n    return 1\n\n[case testInDict]\nfrom typing import Dict\ndef f(d: Dict[int, int]) -> bool:\n    if 4 in d:\n        return True\n    else:\n        return False\n[out]\ndef f(d):\n    d :: dict\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\nL0:\n    r0 = object 4\n    r1 = PyDict_Contains(d, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    return 0\nL3:\n    unreachable\n\n[case testNotInDict]\nfrom typing import Dict\ndef f(d: Dict[int, int]) -> bool:\n    if 4 not in d:\n        return True\n    else:\n        return False\n[out]\ndef f(d):\n    d :: dict\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3, r4 :: bool\nL0:\n    r0 = object 4\n    r1 = PyDict_Contains(d, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    r4 = r3 ^ 1\n    if r4 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    return 0\nL3:\n    unreachable\n\n[case testDictUpdate]\nfrom typing import Dict\ndef f(a: Dict[int, int], b: Dict[int, int]) -> None:\n    a.update(b)\n[out]\ndef f(a, b):\n    a, b :: dict\n    r0 :: i32\n    r1 :: bit\nL0:\n    r0 = CPyDict_Update(a, b)\n    r1 = r0 >= 0 :: signed\n    return 1\n\n[case testDictKeyLvalue]\nfrom typing import Dict\ndef increment(d: Dict[str, int]) -> Dict[str, int]:\n    for k in d:\n        d[k] += 1\n    return d\n[out]\ndef increment(d):\n    d :: dict\n    r0 :: short_int\n    r1 :: native_int\n    r2 :: object\n    r3 :: tuple[bool, short_int, object]\n    r4 :: short_int\n    r5 :: bool\n    r6 :: object\n    r7, k :: str\n    r8, r9, r10 :: object\n    r11 :: i32\n    r12, r13, r14 :: bit\nL0:\n    r0 = 0\n    r1 = PyDict_Size(d)\n    r2 = CPyDict_GetKeysIter(d)\nL1:\n    r3 = CPyDict_NextKey(r2, r0)\n    r4 = r3[1]\n    r0 = r4\n    r5 = r3[0]\n    if r5 goto L2 else goto L4 :: bool\nL2:\n    r6 = r3[2]\n    r7 = cast(str, r6)\n    k = r7\n    r8 = CPyDict_GetItem(d, k)\n    r9 = object 1\n    r10 = PyNumber_InPlaceAdd(r8, r9)\n    r11 = CPyDict_SetItem(d, k, r10)\n    r12 = r11 >= 0 :: signed\nL3:\n    r13 = CPyDict_CheckSize(d, r1)\n    goto L1\nL4:\n    r14 = CPy_NoErrOccurred()\nL5:\n    return d\n\n[case testDictDisplay]\nfrom typing import Dict\ndef f(x: str, y: Dict[str, int]) -> Dict[str, int]:\n    return {x: 2, **y, 'z': 3}\n[out]\ndef f(x, y):\n    x :: str\n    y :: dict\n    r0 :: str\n    r1 :: object\n    r2 :: dict\n    r3 :: i32\n    r4 :: bit\n    r5 :: object\n    r6 :: i32\n    r7 :: bit\nL0:\n    r0 = 'z'\n    r1 = object 2\n    r2 = CPyDict_Build(1, x, r1)\n    r3 = CPyDict_UpdateInDisplay(r2, y)\n    r4 = r3 >= 0 :: signed\n    r5 = object 3\n    r6 = CPyDict_SetItem(r2, r0, r5)\n    r7 = r6 >= 0 :: signed\n    return r2\n\n[case testDictIterationMethods]\nfrom typing import Dict, TypedDict, Union\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\ndef print_dict_methods(d1: Dict[int, int], d2: Dict[int, int]) -> None:\n    for v in d1.values():\n        if v in d2:\n            return\n    for k, v in d2.items():\n        d2[k] += v\ndef union_of_dicts(d: Union[Dict[str, int], Dict[str, str]]) -> None:\n    new = {}\n    for k, v in d.items():\n        new[k] = int(v)\ndef typeddict(d: Person) -> None:\n    for k, v in d.items():\n        if k == \"name\":\n            name = v\n[typing fixtures/typing-full.pyi]\n[out]\ndef print_dict_methods(d1, d2):\n    d1, d2 :: dict\n    r0 :: short_int\n    r1 :: native_int\n    r2 :: object\n    r3 :: tuple[bool, short_int, object]\n    r4 :: short_int\n    r5 :: bool\n    r6 :: object\n    r7, v :: int\n    r8 :: object\n    r9 :: i32\n    r10 :: bit\n    r11 :: bool\n    r12, r13 :: bit\n    r14 :: short_int\n    r15 :: native_int\n    r16 :: object\n    r17 :: tuple[bool, short_int, object, object]\n    r18 :: short_int\n    r19 :: bool\n    r20, r21 :: object\n    r22, r23, k :: int\n    r24, r25, r26, r27, r28 :: object\n    r29 :: i32\n    r30, r31, r32 :: bit\nL0:\n    r0 = 0\n    r1 = PyDict_Size(d1)\n    r2 = CPyDict_GetValuesIter(d1)\nL1:\n    r3 = CPyDict_NextValue(r2, r0)\n    r4 = r3[1]\n    r0 = r4\n    r5 = r3[0]\n    if r5 goto L2 else goto L6 :: bool\nL2:\n    r6 = r3[2]\n    r7 = unbox(int, r6)\n    v = r7\n    r8 = box(int, v)\n    r9 = PyDict_Contains(d2, r8)\n    r10 = r9 >= 0 :: signed\n    r11 = truncate r9: i32 to builtins.bool\n    if r11 goto L3 else goto L4 :: bool\nL3:\n    return 1\nL4:\nL5:\n    r12 = CPyDict_CheckSize(d1, r1)\n    goto L1\nL6:\n    r13 = CPy_NoErrOccurred()\nL7:\n    r14 = 0\n    r15 = PyDict_Size(d2)\n    r16 = CPyDict_GetItemsIter(d2)\nL8:\n    r17 = CPyDict_NextItem(r16, r14)\n    r18 = r17[1]\n    r14 = r18\n    r19 = r17[0]\n    if r19 goto L9 else goto L11 :: bool\nL9:\n    r20 = r17[2]\n    r21 = r17[3]\n    r22 = unbox(int, r20)\n    r23 = unbox(int, r21)\n    k = r22\n    v = r23\n    r24 = box(int, k)\n    r25 = CPyDict_GetItem(d2, r24)\n    r26 = box(int, v)\n    r27 = PyNumber_InPlaceAdd(r25, r26)\n    r28 = box(int, k)\n    r29 = CPyDict_SetItem(d2, r28, r27)\n    r30 = r29 >= 0 :: signed\nL10:\n    r31 = CPyDict_CheckSize(d2, r15)\n    goto L8\nL11:\n    r32 = CPy_NoErrOccurred()\nL12:\n    return 1\ndef union_of_dicts(d):\n    d, r0, new :: dict\n    r1 :: short_int\n    r2 :: native_int\n    r3 :: object\n    r4 :: tuple[bool, short_int, object, object]\n    r5 :: short_int\n    r6 :: bool\n    r7, r8 :: object\n    r9 :: str\n    r10 :: union[int, str]\n    k :: str\n    v :: union[int, str]\n    r11 :: object\n    r12 :: object[1]\n    r13 :: object_ptr\n    r14 :: object\n    r15 :: int\n    r16 :: object\n    r17 :: i32\n    r18, r19, r20 :: bit\nL0:\n    r0 = PyDict_New()\n    new = r0\n    r1 = 0\n    r2 = PyDict_Size(d)\n    r3 = CPyDict_GetItemsIter(d)\nL1:\n    r4 = CPyDict_NextItem(r3, r1)\n    r5 = r4[1]\n    r1 = r5\n    r6 = r4[0]\n    if r6 goto L2 else goto L4 :: bool\nL2:\n    r7 = r4[2]\n    r8 = r4[3]\n    r9 = cast(str, r7)\n    r10 = cast(union[int, str], r8)\n    k = r9\n    v = r10\n    r11 = load_address PyLong_Type\n    r12 = [v]\n    r13 = load_address r12\n    r14 = PyObject_Vectorcall(r11, r13, 1, 0)\n    keep_alive v\n    r15 = unbox(int, r14)\n    r16 = box(int, r15)\n    r17 = CPyDict_SetItem(new, k, r16)\n    r18 = r17 >= 0 :: signed\nL3:\n    r19 = CPyDict_CheckSize(d, r2)\n    goto L1\nL4:\n    r20 = CPy_NoErrOccurred()\nL5:\n    return 1\ndef typeddict(d):\n    d :: dict\n    r0 :: short_int\n    r1 :: native_int\n    r2 :: object\n    r3 :: tuple[bool, short_int, object, object]\n    r4 :: short_int\n    r5 :: bool\n    r6, r7 :: object\n    r8, k :: str\n    v :: object\n    r9 :: str\n    r10 :: bool\n    name :: object\n    r11, r12 :: bit\nL0:\n    r0 = 0\n    r1 = PyDict_Size(d)\n    r2 = CPyDict_GetItemsIter(d)\nL1:\n    r3 = CPyDict_NextItem(r2, r0)\n    r4 = r3[1]\n    r0 = r4\n    r5 = r3[0]\n    if r5 goto L2 else goto L6 :: bool\nL2:\n    r6 = r3[2]\n    r7 = r3[3]\n    r8 = cast(str, r6)\n    k = r8\n    v = r7\n    r9 = 'name'\n    r10 = CPyStr_EqualLiteral(k, r9, 4)\n    if r10 goto L3 else goto L4 :: bool\nL3:\n    name = v\nL4:\nL5:\n    r11 = CPyDict_CheckSize(d, r1)\n    goto L1\nL6:\n    r12 = CPy_NoErrOccurred()\nL7:\n    return 1\n\n[case testDictLoadAddress]\ndef f() -> None:\n    x = dict\n[out]\ndef f():\n    r0, x :: object\nL0:\n    r0 = load_address PyDict_Type\n    x = r0\n    return 1\n\n[case testDictClear]\nfrom typing import Dict\ndef f(d: Dict[int, int]) -> None:\n    return d.clear()\n[out]\ndef f(d):\n    d :: dict\n    r0 :: bit\nL0:\n    r0 = CPyDict_Clear(d)\n    return 1\n\n[case testDictCopy]\nfrom typing import Dict\ndef f(d: Dict[int, int]) -> Dict[int, int]:\n    return d.copy()\n[out]\ndef f(d):\n    d, r0 :: dict\nL0:\n    r0 = CPyDict_Copy(d)\n    return r0\n\n[case testDictSetdefault]\nfrom typing import Dict\ndef f(d: Dict[object, object]) -> object:\n    return d.setdefault('a', 'b')\n\ndef f2(d: Dict[object, object], flag: bool) -> object:\n    if flag:\n        return d.setdefault('a', set())\n    else:\n        return d.setdefault('a', set('b'))\n\ndef f3(d: Dict[object, object], flag: bool) -> object:\n    if flag:\n        return d.setdefault('a', [])\n    else:\n        return d.setdefault('a', [1])\n\ndef f4(d: Dict[object, object], flag: bool) -> object:\n    if flag:\n        return d.setdefault('a', {})\n    else:\n        return d.setdefault('a', {'c': 1})\n[out]\ndef f(d):\n    d :: dict\n    r0, r1 :: str\n    r2 :: object\nL0:\n    r0 = 'a'\n    r1 = 'b'\n    r2 = CPyDict_SetDefault(d, r0, r1)\n    return r2\ndef f2(d, flag):\n    d :: dict\n    flag :: bool\n    r0 :: str\n    r1 :: object\n    r2, r3 :: str\n    r4 :: set\n    r5, r6 :: object\nL0:\n    if flag goto L1 else goto L2 :: bool\nL1:\n    r0 = 'a'\n    r1 = CPyDict_SetDefaultWithEmptyDatatype(d, r0, 3)\n    return r1\nL2:\n    r2 = 'a'\n    r3 = 'b'\n    r4 = PySet_New(r3)\n    r5 = CPyDict_SetDefault(d, r2, r4)\n    return r5\nL3:\n    r6 = box(None, 1)\n    return r6\ndef f3(d, flag):\n    d :: dict\n    flag :: bool\n    r0 :: str\n    r1 :: object\n    r2 :: str\n    r3 :: list\n    r4 :: object\n    r5 :: ptr\n    r6, r7 :: object\nL0:\n    if flag goto L1 else goto L2 :: bool\nL1:\n    r0 = 'a'\n    r1 = CPyDict_SetDefaultWithEmptyDatatype(d, r0, 1)\n    return r1\nL2:\n    r2 = 'a'\n    r3 = PyList_New(1)\n    r4 = object 1\n    r5 = list_items r3\n    buf_init_item r5, 0, r4\n    keep_alive r3\n    r6 = CPyDict_SetDefault(d, r2, r3)\n    return r6\nL3:\n    r7 = box(None, 1)\n    return r7\ndef f4(d, flag):\n    d :: dict\n    flag :: bool\n    r0 :: str\n    r1 :: object\n    r2, r3 :: str\n    r4 :: object\n    r5 :: dict\n    r6, r7 :: object\nL0:\n    if flag goto L1 else goto L2 :: bool\nL1:\n    r0 = 'a'\n    r1 = CPyDict_SetDefaultWithEmptyDatatype(d, r0, 2)\n    return r1\nL2:\n    r2 = 'a'\n    r3 = 'c'\n    r4 = object 1\n    r5 = CPyDict_Build(1, r3, r4)\n    r6 = CPyDict_SetDefault(d, r2, r5)\n    return r6\nL3:\n    r7 = box(None, 1)\n    return r7\n"
  },
  {
    "path": "mypyc/test-data/irbuild-dunders.test",
    "content": "# Test cases for (some) dunder methods\n\n[case testDundersLen]\nclass C:\n    def __len__(self) -> int:\n        return 2\n\ndef f(c: C) -> int:\n    return len(c)\n[out]\ndef C.__len__(self):\n    self :: __main__.C\nL0:\n    return 4\ndef f(c):\n    c :: __main__.C\n    r0 :: int\n    r1 :: bit\n    r2 :: bool\nL0:\n    r0 = c.__len__()\n    r1 = int_ge r0, 0\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = raise ValueError('__len__() should return >= 0')\n    unreachable\nL2:\n    return r0\n\n[case testDundersSetItem]\nclass C:\n    def __setitem__(self, key: int, value: int) -> None:\n        pass\n\ndef f(c: C) -> None:\n    c[3] = 4\n[out]\ndef C.__setitem__(self, key, value):\n    self :: __main__.C\n    key, value :: int\nL0:\n    return 1\ndef f(c):\n    c :: __main__.C\n    r0 :: None\nL0:\n    r0 = c.__setitem__(6, 8)\n    return 1\n\n[case testDundersContains]\nfrom typing import Any\n\nclass C:\n    def __contains__(self, x: int) -> bool:\n        return False\n\ndef f(c: C) -> bool:\n    return 7 in c\n\ndef g(c: C) -> bool:\n    return 7 not in c\n\nclass D:\n    def __contains__(self, x: int) -> Any:\n        return 'x'\n\ndef h(d: D) -> bool:\n    return 7 not in d\n[out]\ndef C.__contains__(self, x):\n    self :: __main__.C\n    x :: int\nL0:\n    return 0\ndef f(c):\n    c :: __main__.C\n    r0 :: bool\nL0:\n    r0 = c.__contains__(14)\n    return r0\ndef g(c):\n    c :: __main__.C\n    r0, r1 :: bool\nL0:\n    r0 = c.__contains__(14)\n    r1 = r0 ^ 1\n    return r1\ndef D.__contains__(self, x):\n    self :: __main__.D\n    x :: int\n    r0 :: str\nL0:\n    r0 = 'x'\n    return r0\ndef h(d):\n    d :: __main__.D\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3, r4 :: bool\nL0:\n    r0 = d.__contains__(14)\n    r1 = PyObject_IsTrue(r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    r4 = r3 ^ 1\n    return r4\n\n[case testDundersDelItem]\nclass C:\n    def __delitem__(self, x: int) -> None:\n        pass\n\ndef f(c: C) -> None:\n    del c[5]\n[out]\ndef C.__delitem__(self, x):\n    self :: __main__.C\n    x :: int\nL0:\n    return 1\ndef f(c):\n    c :: __main__.C\n    r0 :: None\nL0:\n    r0 = c.__delitem__(10)\n    return 1\n\n[case testDundersUnary]\nclass C:\n    def __neg__(self) -> int:\n        return 1\n\n    def __invert__(self) -> int:\n        return 2\n\n    def __int__(self) -> int:\n        return 3\n\n    def __float__(self) -> float:\n        return 4.0\n\n    def __pos__(self) -> int:\n        return 5\n\n    def __abs__(self) -> int:\n        return 6\n\n    def __bool__(self) -> bool:\n        return False\n\n    def __complex__(self) -> complex:\n        return 7j\n\ndef f(c: C) -> None:\n    -c\n    ~c\n    int(c)\n    float(c)\n    +c\n    abs(c)\n    bool(c)\n    complex(c)\n[out]\ndef C.__neg__(self):\n    self :: __main__.C\nL0:\n    return 2\ndef C.__invert__(self):\n    self :: __main__.C\nL0:\n    return 4\ndef C.__int__(self):\n    self :: __main__.C\nL0:\n    return 6\ndef C.__float__(self):\n    self :: __main__.C\nL0:\n    return 4.0\ndef C.__pos__(self):\n    self :: __main__.C\nL0:\n    return 10\ndef C.__abs__(self):\n    self :: __main__.C\nL0:\n    return 12\ndef C.__bool__(self):\n    self :: __main__.C\nL0:\n    return 0\ndef C.__complex__(self):\n    self :: __main__.C\n    r0 :: object\nL0:\n    r0 = 7j\n    return r0\ndef f(c):\n    c :: __main__.C\n    r0, r1, r2 :: int\n    r3 :: float\n    r4, r5 :: int\n    r6 :: bool\n    r7 :: object\nL0:\n    r0 = c.__neg__()\n    r1 = c.__invert__()\n    r2 = c.__int__()\n    r3 = c.__float__()\n    r4 = c.__pos__()\n    r5 = c.__abs__()\n    r6 = c.__bool__()\n    r7 = c.__complex__()\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-float.test",
    "content": "[case testFloatAdd]\ndef f(x: float, y: float) -> float:\n    return x + y\ndef g(x: float) -> float:\n    z = x - 1.5\n    return 2.5 * z\n[out]\ndef f(x, y):\n    x, y, r0 :: float\nL0:\n    r0 = x + y\n    return r0\ndef g(x):\n    x, r0, z, r1 :: float\nL0:\n    r0 = x - 1.5\n    z = r0\n    r1 = 2.5 * z\n    return r1\n\n[case testFloatBoxAndUnbox]\nfrom typing import Any\ndef f(x: float) -> object:\n    return x\ndef g(x: Any) -> float:\n    return x\n[out]\ndef f(x):\n    x :: float\n    r0 :: object\nL0:\n    r0 = box(float, x)\n    return r0\ndef g(x):\n    x :: object\n    r0 :: float\nL0:\n    r0 = unbox(float, x)\n    return r0\n\n[case testFloatNegAndPos]\ndef f(x: float) -> float:\n    y = +x * -0.5\n    return -y\n[out]\ndef f(x):\n    x, r0, y, r1 :: float\nL0:\n    r0 = x * -0.5\n    y = r0\n    r1 = -y\n    return r1\n\n[case testFloatCoerceFromInt]\ndef from_int(x: int) -> float:\n    return x\n\ndef from_literal() -> float:\n    return 5\n\ndef from_literal_neg() -> float:\n    return -2\n[out]\ndef from_int(x):\n    x :: int\n    r0 :: float\nL0:\n    r0 = CPyFloat_FromTagged(x)\n    return r0\ndef from_literal():\nL0:\n    return 5.0\ndef from_literal_neg():\nL0:\n    return -2.0\n\n[case testConvertBetweenFloatAndInt]\ndef to_int(x: float) -> int:\n    return int(x)\ndef from_int(x: int) -> float:\n    return float(x)\n[out]\ndef to_int(x):\n    x :: float\n    r0 :: int\nL0:\n    r0 = CPyTagged_FromFloat(x)\n    return r0\ndef from_int(x):\n    x :: int\n    r0 :: float\nL0:\n    r0 = CPyFloat_FromTagged(x)\n    return r0\n\n[case testFloatOperatorAssignment]\ndef f(x: float, y: float) -> float:\n    x += y\n    x -= 5.0\n    return x\n[out]\ndef f(x, y):\n    x, y, r0, r1 :: float\nL0:\n    r0 = x + y\n    x = r0\n    r1 = x - 5.0\n    x = r1\n    return x\n\n[case testFloatOperatorAssignmentWithInt]\ndef f(x: float, y: int) -> None:\n    x += y\n    x -= 5\n[out]\ndef f(x, y):\n    x :: float\n    y :: int\n    r0, r1, r2 :: float\nL0:\n    r0 = CPyFloat_FromTagged(y)\n    r1 = x + r0\n    x = r1\n    r2 = x - 5.0\n    x = r2\n    return 1\n\n[case testFloatComparison]\ndef lt(x: float, y: float) -> bool:\n    return x < y\ndef eq(x: float, y: float) -> bool:\n    return x == y\n[out]\ndef lt(x, y):\n    x, y :: float\n    r0 :: bit\nL0:\n    r0 = x < y\n    return r0\ndef eq(x, y):\n    x, y :: float\n    r0 :: bit\nL0:\n    r0 = x == y\n    return r0\n\n[case testFloatOpWithLiteralInt]\ndef f(x: float) -> None:\n    y = x * 2\n    z = 1 - y\n    b = z < 3\n    c = 0 == z\n[out]\ndef f(x):\n    x, r0, y, r1, z :: float\n    r2 :: bit\n    b :: bool\n    r3 :: bit\n    c :: bool\nL0:\n    r0 = x * 2.0\n    y = r0\n    r1 = 1.0 - y\n    z = r1\n    r2 = z < 3.0\n    b = r2\n    r3 = 0.0 == z\n    c = r3\n    return 1\n\n[case testFloatCallFunctionWithLiteralInt]\ndef f(x: float) -> None: pass\n\ndef g() -> None:\n    f(3)\n    f(-2)\n[out]\ndef f(x):\n    x :: float\nL0:\n    return 1\ndef g():\n    r0, r1 :: None\nL0:\n    r0 = f(3.0)\n    r1 = f(-2.0)\n    return 1\n\n[case testFloatAsBool]\ndef f(x: float) -> int:\n    if x:\n        return 2\n    else:\n        return 5\n[out]\ndef f(x):\n    x :: float\n    r0 :: bit\nL0:\n    r0 = x != 0.0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 4\nL2:\n    return 10\nL3:\n    unreachable\n\n[case testCallSqrtViaMathModule]\nimport math\n\ndef f(x: float) -> float:\n    return math.sqrt(x)\n[out]\ndef f(x):\n    x, r0 :: float\nL0:\n    r0 = CPyFloat_Sqrt(x)\n    return r0\n\n[case testFloatFinalConstant]\nfrom typing import Final\n\nX: Final = 123.0\nY: Final = -1.0\n\ndef f() -> float:\n    a = X\n    return a + Y\n[out]\ndef f():\n    a, r0 :: float\nL0:\n    a = 123.0\n    r0 = a + -1.0\n    return r0\n\n[case testFloatDefaultArg]\ndef f(x: float = 1.5) -> float:\n    return x\n[out]\ndef f(x, __bitmap):\n    x :: float\n    __bitmap, r0 :: u32\n    r1 :: bit\nL0:\n    r0 = __bitmap & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    x = 1.5\nL2:\n    return x\n\n[case testFloatMixedOperations]\ndef f(x: float, y: int) -> None:\n    if x < y:\n        z = x + y\n        x -= y\n        z = y + z\n    if y == x:\n        x -= 1\n[out]\ndef f(x, y):\n    x :: float\n    y :: int\n    r0 :: float\n    r1 :: bit\n    r2, r3, z, r4, r5, r6, r7, r8 :: float\n    r9 :: bit\n    r10 :: float\nL0:\n    r0 = CPyFloat_FromTagged(y)\n    r1 = x < r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = CPyFloat_FromTagged(y)\n    r3 = x + r2\n    z = r3\n    r4 = CPyFloat_FromTagged(y)\n    r5 = x - r4\n    x = r5\n    r6 = CPyFloat_FromTagged(y)\n    r7 = r6 + z\n    z = r7\nL2:\n    r8 = CPyFloat_FromTagged(y)\n    r9 = r8 == x\n    if r9 goto L3 else goto L4 :: bool\nL3:\n    r10 = x - 1.0\n    x = r10\nL4:\n    return 1\n\n[case testFloatDivideSimple]\ndef f(x: float, y: float) -> float:\n    z = x / y\n    z = z / 2.0\n    return z / 3\n[out]\ndef f(x, y):\n    x, y :: float\n    r0 :: bit\n    r1 :: bool\n    r2, z, r3, r4 :: float\nL0:\n    r0 = y == 0.0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = raise ZeroDivisionError('float division by zero')\n    unreachable\nL2:\n    r2 = x / y\n    z = r2\n    r3 = z / 2.0\n    z = r3\n    r4 = z / 3.0\n    return r4\n\n[case testFloatDivideIntOperand]\ndef f(n: int, m: int) -> float:\n    return n / m\n[out]\ndef f(n, m):\n    n, m :: int\n    r0 :: float\nL0:\n    r0 = CPyTagged_TrueDivide(n, m)\n    return r0\n\n[case testFloatResultOfIntDivide]\ndef f(f: float, n: int) -> float:\n    x = f / n\n    return n / x\n[out]\ndef f(f, n):\n    f :: float\n    n :: int\n    r0 :: float\n    r1 :: bit\n    r2 :: bool\n    r3, x, r4 :: float\n    r5 :: bit\n    r6 :: bool\n    r7 :: float\nL0:\n    r0 = CPyFloat_FromTagged(n)\n    r1 = r0 == 0.0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = raise ZeroDivisionError('float division by zero')\n    unreachable\nL2:\n    r3 = f / r0\n    x = r3\n    r4 = CPyFloat_FromTagged(n)\n    r5 = x == 0.0\n    if r5 goto L3 else goto L4 :: bool\nL3:\n    r6 = raise ZeroDivisionError('float division by zero')\n    unreachable\nL4:\n    r7 = r4 / x\n    return r7\n\n[case testFloatExplicitConversions]\ndef f(f: float, n: int) -> int:\n    x = float(n)\n    y = float(x)  # no-op\n    return int(y)\n[out]\ndef f(f, n):\n    f :: float\n    n :: int\n    r0, x, y :: float\n    r1 :: int\nL0:\n    r0 = CPyFloat_FromTagged(n)\n    x = r0\n    y = x\n    r1 = CPyTagged_FromFloat(y)\n    return r1\n\n[case testFloatModulo]\ndef f(x: float, y: float) -> float:\n    return x % y\n[out]\ndef f(x, y):\n    x, y :: float\n    r0 :: bit\n    r1 :: bool\n    r2, r3 :: float\n    r4, r5, r6, r7 :: bit\n    r8, r9 :: float\nL0:\n    r0 = y == 0.0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = raise ZeroDivisionError('float modulo')\n    unreachable\nL2:\n    r2 = x % y\n    r3 = r2\n    r4 = r3 == 0.0\n    if r4 goto L5 else goto L3 :: bool\nL3:\n    r5 = x < 0.0\n    r6 = y < 0.0\n    r7 = r5 == r6\n    if r7 goto L6 else goto L4 :: bool\nL4:\n    r8 = r3 + y\n    r3 = r8\n    goto L6\nL5:\n    r9 = copysign(0.0, y)\n    r3 = r9\nL6:\n    return r3\n\n[case testFloatFloorDivide]\ndef f(x: float, y: float) -> float:\n    return x // y\ndef g(x: float, y: int) -> float:\n    return x // y\n[out]\ndef f(x, y):\n    x, y, r0 :: float\nL0:\n    r0 = CPyFloat_FloorDivide(x, y)\n    return r0\ndef g(x, y):\n    x :: float\n    y :: int\n    r0, r1 :: float\nL0:\n    r0 = CPyFloat_FromTagged(y)\n    r1 = CPyFloat_FloorDivide(x, r0)\n    return r1\n\n[case testFloatNarrowToIntDisallowed]\nclass C:\n    x: float\n\ndef narrow_local(x: float, n: int) -> int:\n    x = n  # E: Incompatible value representations in assignment (expression has type \"int\", variable has type \"float\")\n    return x\n\ndef narrow_tuple_lvalue(x: float, y: float, n: int) -> int:\n    x, y = 1.0, n  # E: Incompatible value representations in assignment (expression has type \"int\", variable has type \"float\")\n    return y\n\ndef narrow_multiple_lvalues(x: float, y: float, n: int) -> int:\n    x = a = n  # E: Incompatible value representations in assignment (expression has type \"int\", variable has type \"float\")\n    a = y = n  # E: Incompatible value representations in assignment (expression has type \"int\", variable has type \"float\")\n    return x + y\n\ndef narrow_attribute(c: C, n: int) -> int:\n    c.x = n  # E: Incompatible value representations in assignment (expression has type \"int\", variable has type \"float\")\n    return c.x\n\ndef narrow_using_int_literal(x: float) -> int:\n    x = 1  # E: Incompatible value representations in assignment (expression has type \"int\", variable has type \"float\")\n    return x\n\ndef narrow_using_declaration(n: int) -> int:\n    x: float\n    x = n  # E: Incompatible value representations in assignment (expression has type \"int\", variable has type \"float\")\n    return x\n\n[case testFloatInitializeFromInt]\ndef init(n: int) -> None:\n    # These are strictly speaking safe, since these don't narrow, but for consistency with\n    # narrowing assignments, generate errors here\n    x: float = n  # E: Incompatible value representations in assignment (expression has type \"int\", variable has type \"float\")\n    y: float = 5  # E: Incompatible value representations in assignment (expression has type \"int\", variable has type \"float\")\n\n[case testFloatCoerceTupleFromIntValues]\nfrom __future__ import annotations\n\ndef f(x: int) -> None:\n    t: tuple[float, float, float] = (x, 2.5, -7)\n[out]\ndef f(x):\n    x :: int\n    r0 :: tuple[int, float, int]\n    r1 :: int\n    r2 :: float\n    r3, t :: tuple[float, float, float]\nL0:\n    r0 = (x, 2.5, -14)\n    r1 = r0[0]\n    r2 = CPyFloat_FromTagged(r1)\n    r3 = (r2, 2.5, -7.0)\n    t = r3\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-frozenset.test",
    "content": "[case testNewFrozenSet]\nfrom typing import FrozenSet\ndef f() -> FrozenSet[int]:\n    return frozenset({1, 2, 3})\n[out]\ndef f():\n    r0 :: set\n    r1 :: object\n    r2 :: i32\n    r3 :: bit\n    r4 :: object\n    r5 :: i32\n    r6 :: bit\n    r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: frozenset\nL0:\n    r0 = PySet_New(0)\n    r1 = object 1\n    r2 = PySet_Add(r0, r1)\n    r3 = r2 >= 0 :: signed\n    r4 = object 2\n    r5 = PySet_Add(r0, r4)\n    r6 = r5 >= 0 :: signed\n    r7 = object 3\n    r8 = PySet_Add(r0, r7)\n    r9 = r8 >= 0 :: signed\n    r10 = PyFrozenSet_New(r0)\n    return r10\n\n[case testNewEmptyFrozenSet]\nfrom typing import FrozenSet\ndef f1() -> FrozenSet[int]:\n    return frozenset()\n\ndef f2() -> FrozenSet[int]:\n    return frozenset(())\n[out]\ndef f1():\n    r0 :: frozenset\nL0:\n    r0 = PyFrozenSet_New(0)\n    return r0\ndef f2():\n    r0 :: tuple[]\n    r1 :: object\n    r2 :: frozenset\nL0:\n    r0 = ()\n    r1 = box(tuple[], r0)\n    r2 = PyFrozenSet_New(r1)\n    return r2\n\n[case testNewFrozenSetFromIterable]\nfrom typing import FrozenSet, List, TypeVar\n\nT = TypeVar(\"T\")\n\ndef f(l: List[T]) -> FrozenSet[T]:\n    return frozenset(l)\n[out]\ndef f(l):\n    l :: list\n    r0 :: frozenset\nL0:\n    r0 = PyFrozenSet_New(l)\n    return r0\n\n[case testFrozenSetSize]\nfrom typing import FrozenSet\ndef f() -> int:\n    return len(frozenset((1, 2, 3)))\n[out]\ndef f():\n    r0 :: tuple[int, int, int]\n    r1 :: object\n    r2 :: frozenset\n    r3 :: ptr\n    r4 :: native_int\n    r5 :: short_int\nL0:\n    r0 = (2, 4, 6)\n    r1 = box(tuple[int, int, int], r0)\n    r2 = PyFrozenSet_New(r1)\n    r3 = get_element_ptr r2 used :: PySetObject\n    r4 = load_mem r3 :: native_int*\n    keep_alive r2\n    r5 = r4 << 1\n    return r5\n\n[case testFrozenSetContains]\nfrom typing import FrozenSet\ndef f() -> bool:\n    x = frozenset((3, 4))\n    return (5 in x)\n[out]\ndef f():\n    r0 :: tuple[int, int]\n    r1 :: object\n    r2, x :: frozenset\n    r3 :: object\n    r4 :: i32\n    r5 :: bit\n    r6 :: bool\nL0:\n    r0 = (6, 8)\n    r1 = box(tuple[int, int], r0)\n    r2 = PyFrozenSet_New(r1)\n    x = r2\n    r3 = object 5\n    r4 = PySet_Contains(x, r3)\n    r5 = r4 >= 0 :: signed\n    r6 = truncate r4: i32 to builtins.bool\n    return r6\n"
  },
  {
    "path": "mypyc/test-data/irbuild-generics.test",
    "content": "[case testGenericFunction]\nfrom typing import TypeVar, List\nT = TypeVar('T')\ndef f(x: T) -> T:\n    return x\ndef g(x: List[T]) -> List[T]:\n    return [x[0]]\ndef h(x: int, y: List[int]) -> None:\n    x = f(x)\n    y = g(y)\n[out]\ndef f(x):\n    x :: object\nL0:\n    return x\ndef g(x):\n    x :: list\n    r0 :: object\n    r1 :: list\n    r2 :: ptr\nL0:\n    r0 = CPyList_GetItemShort(x, 0)\n    r1 = PyList_New(1)\n    r2 = list_items r1\n    buf_init_item r2, 0, r0\n    keep_alive r1\n    return r1\ndef h(x, y):\n    x :: int\n    y :: list\n    r0, r1 :: object\n    r2 :: int\n    r3 :: list\nL0:\n    r0 = box(int, x)\n    r1 = f(r0)\n    r2 = unbox(int, r1)\n    x = r2\n    r3 = g(y)\n    y = r3\n    return 1\n\n[case testGenericAttrAndTypeApplication]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C(Generic[T]):\n    x: T\ndef f() -> None:\n    c = C[int]()\n    c.x = 1\n    2 + c.x\n[out]\ndef f():\n    r0, c :: __main__.C\n    r1 :: object\n    r2 :: bool\n    r3 :: object\n    r4, r5 :: int\nL0:\n    r0 = C()\n    c = r0\n    r1 = object 1\n    c.x = r1; r2 = is_error\n    r3 = borrow c.x\n    r4 = unbox(int, r3)\n    r5 = CPyTagged_Add(4, r4)\n    keep_alive c\n    return 1\n\n[case testGenericMethod]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C(Generic[T]):\n    x: T\n    def __init__(self, x: T) -> None:\n        self.x = x\n    def get(self) -> T:\n        return self.x\n    def set(self, y: T) -> None:\n        self.x = y\ndef f(x: C[int]) -> None:\n    y = x.get()\n    x.set(y + 1)\n    x = C(2)\n[out]\ndef C.__init__(self, x):\n    self :: __main__.C\n    x :: object\n    r0 :: bool\nL0:\n    self.x = x; r0 = is_error\n    return 1\ndef C.get(self):\n    self :: __main__.C\n    r0 :: object\nL0:\n    r0 = self.x\n    return r0\ndef C.set(self, y):\n    self :: __main__.C\n    y :: object\n    r0 :: bool\nL0:\n    self.x = y; r0 = is_error\n    return 1\ndef f(x):\n    x :: __main__.C\n    r0 :: object\n    r1, y, r2 :: int\n    r3 :: object\n    r4 :: None\n    r5 :: object\n    r6 :: __main__.C\nL0:\n    r0 = x.get()\n    r1 = unbox(int, r0)\n    y = r1\n    r2 = CPyTagged_Add(y, 2)\n    r3 = box(int, r2)\n    r4 = x.set(r3)\n    r5 = object 2\n    r6 = C(r5)\n    x = r6\n    return 1\n\n[case testMax]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef f(x: T, y: T) -> T:\n    return max(x, y)\n[out]\ndef f(x, y):\n    x, y, r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4 :: object\nL0:\n    r0 = PyObject_RichCompare(y, x, 4)\n    r1 = PyObject_IsTrue(r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = y\n    goto L3\nL2:\n    r4 = x\nL3:\n    return r4\n\n\n[case testParamSpec]\nfrom typing import Callable, ParamSpec\n\nP = ParamSpec(\"P\")\n\ndef execute(func: Callable[P, int], *args: P.args, **kwargs: P.kwargs) -> int:\n    return func(*args, **kwargs)\n\ndef f(x: int) -> int:\n    return x\n\nexecute(f, 1)\n[out]\ndef execute(func, args, kwargs):\n    func :: object\n    args :: tuple\n    kwargs, r0 :: dict\n    r1 :: object\n    r2 :: int\nL0:\n    r0 = PyDict_Copy(kwargs)\n    r1 = PyObject_Call(func, args, r0)\n    r2 = unbox(int, r1)\n    return r2\ndef f(x):\n    x :: int\nL0:\n    return x\n\n[case testTypeVarMappingBound]\n# Dicts are special-cased for efficient iteration.\nfrom typing import Dict, TypedDict, TypeVar, Union\n\nclass TD(TypedDict):\n    foo: int\n\nM = TypeVar(\"M\", bound=Dict[str, int])\nU = TypeVar(\"U\", bound=Union[Dict[str, int], Dict[str, str]])\nT = TypeVar(\"T\", bound=TD)\n\ndef fn_mapping(m: M) -> None:\n    [x for x in m]\n    [x for x in m.values()]\n    {x for x in m.keys()}\n    {k: v for k, v in m.items()}\n\ndef fn_union(m: U) -> None:\n    [x for x in m]\n    [x for x in m.values()]\n    {x for x in m.keys()}\n    {k: v for k, v in m.items()}\n\ndef fn_typeddict(t: T) -> None:\n    [x for x in t]\n    [x for x in t.values()]\n    {x for x in t.keys()}\n    {k: v for k, v in t.items()}\n\n[typing fixtures/typing-full.pyi]\n[out]\ndef fn_mapping(m):\n    m :: dict\n    r0 :: list\n    r1 :: short_int\n    r2 :: native_int\n    r3 :: object\n    r4 :: tuple[bool, short_int, object]\n    r5 :: short_int\n    r6 :: bool\n    r7 :: object\n    r8, x :: str\n    r9 :: i32\n    r10, r11, r12 :: bit\n    r13 :: list\n    r14 :: short_int\n    r15 :: native_int\n    r16 :: object\n    r17 :: tuple[bool, short_int, object]\n    r18 :: short_int\n    r19 :: bool\n    r20 :: object\n    r21, x_2 :: int\n    r22 :: object\n    r23 :: i32\n    r24, r25, r26 :: bit\n    r27 :: set\n    r28 :: short_int\n    r29 :: native_int\n    r30 :: object\n    r31 :: tuple[bool, short_int, object]\n    r32 :: short_int\n    r33 :: bool\n    r34 :: object\n    r35, x_3 :: str\n    r36 :: i32\n    r37, r38, r39 :: bit\n    r40 :: dict\n    r41 :: short_int\n    r42 :: native_int\n    r43 :: object\n    r44 :: tuple[bool, short_int, object, object]\n    r45 :: short_int\n    r46 :: bool\n    r47, r48 :: object\n    r49 :: str\n    r50 :: int\n    k :: str\n    v :: int\n    r51 :: object\n    r52 :: i32\n    r53, r54, r55 :: bit\nL0:\n    r0 = PyList_New(0)\n    r1 = 0\n    r2 = PyDict_Size(m)\n    r3 = CPyDict_GetKeysIter(m)\nL1:\n    r4 = CPyDict_NextKey(r3, r1)\n    r5 = r4[1]\n    r1 = r5\n    r6 = r4[0]\n    if r6 goto L2 else goto L4 :: bool\nL2:\n    r7 = r4[2]\n    r8 = cast(str, r7)\n    x = r8\n    r9 = PyList_Append(r0, x)\n    r10 = r9 >= 0 :: signed\nL3:\n    r11 = CPyDict_CheckSize(m, r2)\n    goto L1\nL4:\n    r12 = CPy_NoErrOccurred()\nL5:\n    r13 = PyList_New(0)\n    r14 = 0\n    r15 = PyDict_Size(m)\n    r16 = CPyDict_GetValuesIter(m)\nL6:\n    r17 = CPyDict_NextValue(r16, r14)\n    r18 = r17[1]\n    r14 = r18\n    r19 = r17[0]\n    if r19 goto L7 else goto L9 :: bool\nL7:\n    r20 = r17[2]\n    r21 = unbox(int, r20)\n    x_2 = r21\n    r22 = box(int, x_2)\n    r23 = PyList_Append(r13, r22)\n    r24 = r23 >= 0 :: signed\nL8:\n    r25 = CPyDict_CheckSize(m, r15)\n    goto L6\nL9:\n    r26 = CPy_NoErrOccurred()\nL10:\n    r27 = PySet_New(0)\n    r28 = 0\n    r29 = PyDict_Size(m)\n    r30 = CPyDict_GetKeysIter(m)\nL11:\n    r31 = CPyDict_NextKey(r30, r28)\n    r32 = r31[1]\n    r28 = r32\n    r33 = r31[0]\n    if r33 goto L12 else goto L14 :: bool\nL12:\n    r34 = r31[2]\n    r35 = cast(str, r34)\n    x_3 = r35\n    r36 = PySet_Add(r27, x_3)\n    r37 = r36 >= 0 :: signed\nL13:\n    r38 = CPyDict_CheckSize(m, r29)\n    goto L11\nL14:\n    r39 = CPy_NoErrOccurred()\nL15:\n    r40 = PyDict_New()\n    r41 = 0\n    r42 = PyDict_Size(m)\n    r43 = CPyDict_GetItemsIter(m)\nL16:\n    r44 = CPyDict_NextItem(r43, r41)\n    r45 = r44[1]\n    r41 = r45\n    r46 = r44[0]\n    if r46 goto L17 else goto L19 :: bool\nL17:\n    r47 = r44[2]\n    r48 = r44[3]\n    r49 = cast(str, r47)\n    r50 = unbox(int, r48)\n    k = r49\n    v = r50\n    r51 = box(int, v)\n    r52 = PyDict_SetItem(r40, k, r51)\n    r53 = r52 >= 0 :: signed\nL18:\n    r54 = CPyDict_CheckSize(m, r42)\n    goto L16\nL19:\n    r55 = CPy_NoErrOccurred()\nL20:\n    return 1\ndef fn_union(m):\n    m :: dict\n    r0 :: list\n    r1 :: short_int\n    r2 :: native_int\n    r3 :: object\n    r4 :: tuple[bool, short_int, object]\n    r5 :: short_int\n    r6 :: bool\n    r7 :: object\n    r8, x :: str\n    r9 :: i32\n    r10, r11, r12 :: bit\n    r13 :: list\n    r14 :: short_int\n    r15 :: native_int\n    r16 :: object\n    r17 :: tuple[bool, short_int, object]\n    r18 :: short_int\n    r19 :: bool\n    r20 :: object\n    r21, x_2 :: union[int, str]\n    r22 :: i32\n    r23, r24, r25 :: bit\n    r26 :: set\n    r27 :: short_int\n    r28 :: native_int\n    r29 :: object\n    r30 :: tuple[bool, short_int, object]\n    r31 :: short_int\n    r32 :: bool\n    r33 :: object\n    r34, x_3 :: str\n    r35 :: i32\n    r36, r37, r38 :: bit\n    r39 :: dict\n    r40 :: short_int\n    r41 :: native_int\n    r42 :: object\n    r43 :: tuple[bool, short_int, object, object]\n    r44 :: short_int\n    r45 :: bool\n    r46, r47 :: object\n    r48 :: str\n    r49 :: union[int, str]\n    k :: str\n    v :: union[int, str]\n    r50 :: i32\n    r51, r52, r53 :: bit\nL0:\n    r0 = PyList_New(0)\n    r1 = 0\n    r2 = PyDict_Size(m)\n    r3 = CPyDict_GetKeysIter(m)\nL1:\n    r4 = CPyDict_NextKey(r3, r1)\n    r5 = r4[1]\n    r1 = r5\n    r6 = r4[0]\n    if r6 goto L2 else goto L4 :: bool\nL2:\n    r7 = r4[2]\n    r8 = cast(str, r7)\n    x = r8\n    r9 = PyList_Append(r0, x)\n    r10 = r9 >= 0 :: signed\nL3:\n    r11 = CPyDict_CheckSize(m, r2)\n    goto L1\nL4:\n    r12 = CPy_NoErrOccurred()\nL5:\n    r13 = PyList_New(0)\n    r14 = 0\n    r15 = PyDict_Size(m)\n    r16 = CPyDict_GetValuesIter(m)\nL6:\n    r17 = CPyDict_NextValue(r16, r14)\n    r18 = r17[1]\n    r14 = r18\n    r19 = r17[0]\n    if r19 goto L7 else goto L9 :: bool\nL7:\n    r20 = r17[2]\n    r21 = cast(union[int, str], r20)\n    x_2 = r21\n    r22 = PyList_Append(r13, x_2)\n    r23 = r22 >= 0 :: signed\nL8:\n    r24 = CPyDict_CheckSize(m, r15)\n    goto L6\nL9:\n    r25 = CPy_NoErrOccurred()\nL10:\n    r26 = PySet_New(0)\n    r27 = 0\n    r28 = PyDict_Size(m)\n    r29 = CPyDict_GetKeysIter(m)\nL11:\n    r30 = CPyDict_NextKey(r29, r27)\n    r31 = r30[1]\n    r27 = r31\n    r32 = r30[0]\n    if r32 goto L12 else goto L14 :: bool\nL12:\n    r33 = r30[2]\n    r34 = cast(str, r33)\n    x_3 = r34\n    r35 = PySet_Add(r26, x_3)\n    r36 = r35 >= 0 :: signed\nL13:\n    r37 = CPyDict_CheckSize(m, r28)\n    goto L11\nL14:\n    r38 = CPy_NoErrOccurred()\nL15:\n    r39 = PyDict_New()\n    r40 = 0\n    r41 = PyDict_Size(m)\n    r42 = CPyDict_GetItemsIter(m)\nL16:\n    r43 = CPyDict_NextItem(r42, r40)\n    r44 = r43[1]\n    r40 = r44\n    r45 = r43[0]\n    if r45 goto L17 else goto L19 :: bool\nL17:\n    r46 = r43[2]\n    r47 = r43[3]\n    r48 = cast(str, r46)\n    r49 = cast(union[int, str], r47)\n    k = r48\n    v = r49\n    r50 = PyDict_SetItem(r39, k, v)\n    r51 = r50 >= 0 :: signed\nL18:\n    r52 = CPyDict_CheckSize(m, r41)\n    goto L16\nL19:\n    r53 = CPy_NoErrOccurred()\nL20:\n    return 1\ndef fn_typeddict(t):\n    t :: dict\n    r0 :: list\n    r1 :: short_int\n    r2 :: native_int\n    r3 :: object\n    r4 :: tuple[bool, short_int, object]\n    r5 :: short_int\n    r6 :: bool\n    r7 :: object\n    r8, x :: str\n    r9 :: i32\n    r10, r11, r12 :: bit\n    r13 :: list\n    r14 :: short_int\n    r15 :: native_int\n    r16 :: object\n    r17 :: tuple[bool, short_int, object]\n    r18 :: short_int\n    r19 :: bool\n    r20, x_2 :: object\n    r21 :: i32\n    r22, r23, r24 :: bit\n    r25 :: set\n    r26 :: short_int\n    r27 :: native_int\n    r28 :: object\n    r29 :: tuple[bool, short_int, object]\n    r30 :: short_int\n    r31 :: bool\n    r32 :: object\n    r33, x_3 :: str\n    r34 :: i32\n    r35, r36, r37 :: bit\n    r38 :: dict\n    r39 :: short_int\n    r40 :: native_int\n    r41 :: object\n    r42 :: tuple[bool, short_int, object, object]\n    r43 :: short_int\n    r44 :: bool\n    r45, r46 :: object\n    r47, k :: str\n    v :: object\n    r48 :: i32\n    r49, r50, r51 :: bit\nL0:\n    r0 = PyList_New(0)\n    r1 = 0\n    r2 = PyDict_Size(t)\n    r3 = CPyDict_GetKeysIter(t)\nL1:\n    r4 = CPyDict_NextKey(r3, r1)\n    r5 = r4[1]\n    r1 = r5\n    r6 = r4[0]\n    if r6 goto L2 else goto L4 :: bool\nL2:\n    r7 = r4[2]\n    r8 = cast(str, r7)\n    x = r8\n    r9 = PyList_Append(r0, x)\n    r10 = r9 >= 0 :: signed\nL3:\n    r11 = CPyDict_CheckSize(t, r2)\n    goto L1\nL4:\n    r12 = CPy_NoErrOccurred()\nL5:\n    r13 = PyList_New(0)\n    r14 = 0\n    r15 = PyDict_Size(t)\n    r16 = CPyDict_GetValuesIter(t)\nL6:\n    r17 = CPyDict_NextValue(r16, r14)\n    r18 = r17[1]\n    r14 = r18\n    r19 = r17[0]\n    if r19 goto L7 else goto L9 :: bool\nL7:\n    r20 = r17[2]\n    x_2 = r20\n    r21 = PyList_Append(r13, x_2)\n    r22 = r21 >= 0 :: signed\nL8:\n    r23 = CPyDict_CheckSize(t, r15)\n    goto L6\nL9:\n    r24 = CPy_NoErrOccurred()\nL10:\n    r25 = PySet_New(0)\n    r26 = 0\n    r27 = PyDict_Size(t)\n    r28 = CPyDict_GetKeysIter(t)\nL11:\n    r29 = CPyDict_NextKey(r28, r26)\n    r30 = r29[1]\n    r26 = r30\n    r31 = r29[0]\n    if r31 goto L12 else goto L14 :: bool\nL12:\n    r32 = r29[2]\n    r33 = cast(str, r32)\n    x_3 = r33\n    r34 = PySet_Add(r25, x_3)\n    r35 = r34 >= 0 :: signed\nL13:\n    r36 = CPyDict_CheckSize(t, r27)\n    goto L11\nL14:\n    r37 = CPy_NoErrOccurred()\nL15:\n    r38 = PyDict_New()\n    r39 = 0\n    r40 = PyDict_Size(t)\n    r41 = CPyDict_GetItemsIter(t)\nL16:\n    r42 = CPyDict_NextItem(r41, r39)\n    r43 = r42[1]\n    r39 = r43\n    r44 = r42[0]\n    if r44 goto L17 else goto L19 :: bool\nL17:\n    r45 = r42[2]\n    r46 = r42[3]\n    r47 = cast(str, r45)\n    k = r47\n    v = r46\n    r48 = PyDict_SetItem(r38, k, v)\n    r49 = r48 >= 0 :: signed\nL18:\n    r50 = CPyDict_CheckSize(t, r40)\n    goto L16\nL19:\n    r51 = CPy_NoErrOccurred()\nL20:\n    return 1\n\n[case testParamSpecComponentsAreUsable]\nfrom typing import Callable, ParamSpec\n\nP = ParamSpec(\"P\")\n\ndef deco(func: Callable[P, int]) -> Callable[P, int]:\n    def inner(*args: P.args, **kwargs: P.kwargs) -> int:\n        can_listcomp = [x for x in args]\n        can_dictcomp = {k: v for k, v in kwargs.items()}\n        can_iter = list(kwargs)\n        can_use_keys = list(kwargs.keys())\n        can_use_values = list(kwargs.values())\n        return func(*args, **kwargs)\n\n    return inner\n\n@deco\ndef f(x: int) -> int:\n    return x\n\nf(1)\n[out]\ndef inner_deco_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef inner_deco_obj.__call__(__mypyc_self__, args, kwargs):\n    __mypyc_self__ :: __main__.inner_deco_obj\n    args :: tuple\n    kwargs :: dict\n    r0 :: __main__.deco_env\n    r1 :: native_int\n    r2 :: list\n    r3 :: native_int\n    r4 :: bit\n    r5, x :: object\n    r6 :: native_int\n    can_listcomp :: list\n    r7 :: dict\n    r8 :: short_int\n    r9 :: native_int\n    r10 :: object\n    r11 :: tuple[bool, short_int, object, object]\n    r12 :: short_int\n    r13 :: bool\n    r14, r15 :: object\n    r16, k :: str\n    v :: object\n    r17 :: i32\n    r18, r19, r20 :: bit\n    can_dictcomp :: dict\n    r21, can_iter, r22, can_use_keys, r23, can_use_values :: list\n    r24 :: object\n    r25 :: dict\n    r26 :: object\n    r27 :: int\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = var_object_size args\n    r2 = PyList_New(r1)\n    r3 = 0\nL1:\n    r4 = r3 < r1 :: signed\n    if r4 goto L2 else goto L4 :: bool\nL2:\n    r5 = CPySequenceTuple_GetItemUnsafe(args, r3)\n    x = r5\n    CPyList_SetItemUnsafe(r2, r3, x)\nL3:\n    r6 = r3 + 1\n    r3 = r6\n    goto L1\nL4:\n    can_listcomp = r2\n    r7 = PyDict_New()\n    r8 = 0\n    r9 = PyDict_Size(kwargs)\n    r10 = CPyDict_GetItemsIter(kwargs)\nL5:\n    r11 = CPyDict_NextItem(r10, r8)\n    r12 = r11[1]\n    r8 = r12\n    r13 = r11[0]\n    if r13 goto L6 else goto L8 :: bool\nL6:\n    r14 = r11[2]\n    r15 = r11[3]\n    r16 = cast(str, r14)\n    k = r16\n    v = r15\n    r17 = PyDict_SetItem(r7, k, v)\n    r18 = r17 >= 0 :: signed\nL7:\n    r19 = CPyDict_CheckSize(kwargs, r9)\n    goto L5\nL8:\n    r20 = CPy_NoErrOccurred()\nL9:\n    can_dictcomp = r7\n    r21 = PySequence_List(kwargs)\n    can_iter = r21\n    r22 = CPyDict_Keys(kwargs)\n    can_use_keys = r22\n    r23 = CPyDict_Values(kwargs)\n    can_use_values = r23\n    r24 = r0.func\n    r25 = PyDict_Copy(kwargs)\n    r26 = PyObject_Call(r24, args, r25)\n    r27 = unbox(int, r26)\n    return r27\ndef deco(func):\n    func :: object\n    r0 :: __main__.deco_env\n    r1 :: bool\n    r2 :: __main__.inner_deco_obj\n    r3 :: bool\n    inner :: object\nL0:\n    r0 = deco_env()\n    r0.func = func; r1 = is_error\n    r2 = inner_deco_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    inner = r2\n    return inner\ndef f(x):\n    x :: int\nL0:\n    return x\n"
  },
  {
    "path": "mypyc/test-data/irbuild-glue-methods.test",
    "content": "# Test cases for glue methods.\n#\n# These are used when subclass method signature has a different representation\n# compared to the base class.\n\n[case testSubclassSpecialize2]\nclass A:\n    def foo(self, x: int) -> object:\n        return str(x)\nclass B(A):\n    def foo(self, x: object) -> object:\n        return x\nclass C(B):\n    def foo(self, x: object) -> int:\n        return id(x)\n\ndef use_a(x: A, y: int) -> object:\n    return x.foo(y)\n\ndef use_b(x: B, y: object) -> object:\n    return x.foo(y)\n\ndef use_c(x: C, y: object) -> int:\n    return x.foo(y)\n[out]\ndef A.foo(self, x):\n    self :: __main__.A\n    x :: int\n    r0 :: str\nL0:\n    r0 = CPyTagged_Str(x)\n    return r0\ndef B.foo(self, x):\n    self :: __main__.B\n    x :: object\nL0:\n    return x\ndef B.foo__A_glue(self, x):\n    self :: __main__.B\n    x :: int\n    r0, r1 :: object\nL0:\n    r0 = box(int, x)\n    r1 = B.foo(self, r0)\n    return r1\ndef C.foo(self, x):\n    self :: __main__.C\n    x :: object\n    r0 :: int\nL0:\n    r0 = CPyTagged_Id(x)\n    return r0\ndef C.foo__B_glue(self, x):\n    self :: __main__.C\n    x :: object\n    r0 :: int\n    r1 :: object\nL0:\n    r0 = C.foo(self, x)\n    r1 = box(int, r0)\n    return r1\ndef C.foo__A_glue(self, x):\n    self :: __main__.C\n    x :: int\n    r0 :: object\n    r1 :: int\n    r2 :: object\nL0:\n    r0 = box(int, x)\n    r1 = C.foo(self, r0)\n    r2 = box(int, r1)\n    return r2\ndef use_a(x, y):\n    x :: __main__.A\n    y :: int\n    r0 :: object\nL0:\n    r0 = x.foo(y)\n    return r0\ndef use_b(x, y):\n    x :: __main__.B\n    y, r0 :: object\nL0:\n    r0 = x.foo(y)\n    return r0\ndef use_c(x, y):\n    x :: __main__.C\n    y :: object\n    r0 :: int\nL0:\n    r0 = x.foo(y)\n    return r0\n\n[case testPropertyDerivedGen]\nfrom typing import Callable\nclass BaseProperty:\n    @property\n    def value(self) -> object:\n        return self._incrementer\n\n    @property\n    def bad_value(self) -> object:\n        return self._incrementer\n\n    @property\n    def next(self) -> BaseProperty:\n        return BaseProperty(self._incrementer + 1)\n\n    def __init__(self, value: int) -> None:\n        self._incrementer = value\n\nclass DerivedProperty(BaseProperty):\n    @property\n    def value(self) -> int:\n        return self._incrementer\n\n    @property\n    def bad_value(self) -> object:\n        return self._incrementer\n\n    @property\n    def next(self) -> DerivedProperty:\n        return DerivedProperty(self._incr_func, self._incr_func(self.value))\n\n    def __init__(self, incr_func: Callable[[int], int], value: int) -> None:\n        BaseProperty.__init__(self, value)\n        self._incr_func = incr_func\n\n\nclass AgainProperty(DerivedProperty):\n    @property\n    def next(self) -> AgainProperty:\n        return AgainProperty(self._incr_func, self._incr_func(self._incr_func(self.value)))\n\n    @property\n    def bad_value(self) -> int:\n        return self._incrementer\n[out]\ndef BaseProperty.value(self):\n    self :: __main__.BaseProperty\n    r0 :: int\n    r1 :: object\nL0:\n    r0 = self._incrementer\n    r1 = box(int, r0)\n    return r1\ndef BaseProperty.bad_value(self):\n    self :: __main__.BaseProperty\n    r0 :: int\n    r1 :: object\nL0:\n    r0 = self._incrementer\n    r1 = box(int, r0)\n    return r1\ndef BaseProperty.next(self):\n    self :: __main__.BaseProperty\n    r0, r1 :: int\n    r2 :: __main__.BaseProperty\nL0:\n    r0 = borrow self._incrementer\n    r1 = CPyTagged_Add(r0, 2)\n    keep_alive self\n    r2 = BaseProperty(r1)\n    return r2\ndef BaseProperty.__init__(self, value):\n    self :: __main__.BaseProperty\n    value :: int\nL0:\n    self._incrementer = value\n    return 1\ndef DerivedProperty.value(self):\n    self :: __main__.DerivedProperty\n    r0 :: int\nL0:\n    r0 = self._incrementer\n    return r0\ndef DerivedProperty.value__BaseProperty_glue(__mypyc_self__):\n    __mypyc_self__ :: __main__.DerivedProperty\n    r0 :: int\n    r1 :: object\nL0:\n    r0 = __mypyc_self__.value\n    r1 = box(int, r0)\n    return r1\ndef DerivedProperty.bad_value(self):\n    self :: __main__.DerivedProperty\n    r0 :: int\n    r1 :: object\nL0:\n    r0 = self._incrementer\n    r1 = box(int, r0)\n    return r1\ndef DerivedProperty.next(self):\n    self :: __main__.DerivedProperty\n    r0 :: object\n    r1 :: int\n    r2, r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: int\n    r8 :: __main__.DerivedProperty\nL0:\n    r0 = self._incr_func\n    r1 = self.value\n    r2 = self._incr_func\n    r3 = box(int, r1)\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 1, 0)\n    keep_alive r3\n    r7 = unbox(int, r6)\n    r8 = DerivedProperty(r0, r7)\n    return r8\ndef DerivedProperty.next__BaseProperty_glue(__mypyc_self__):\n    __mypyc_self__, r0 :: __main__.DerivedProperty\nL0:\n    r0 = __mypyc_self__.next\n    return r0\ndef DerivedProperty.__init__(self, incr_func, value):\n    self :: __main__.DerivedProperty\n    incr_func :: object\n    value :: int\n    r0 :: None\nL0:\n    r0 = BaseProperty.__init__(self, value)\n    self._incr_func = incr_func\n    return 1\ndef AgainProperty.next(self):\n    self :: __main__.AgainProperty\n    r0 :: object\n    r1 :: int\n    r2, r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: int\n    r8, r9 :: object\n    r10 :: object[1]\n    r11 :: object_ptr\n    r12 :: object\n    r13 :: int\n    r14 :: __main__.AgainProperty\nL0:\n    r0 = self._incr_func\n    r1 = self.value\n    r2 = self._incr_func\n    r3 = box(int, r1)\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 1, 0)\n    keep_alive r3\n    r7 = unbox(int, r6)\n    r8 = self._incr_func\n    r9 = box(int, r7)\n    r10 = [r9]\n    r11 = load_address r10\n    r12 = PyObject_Vectorcall(r8, r11, 1, 0)\n    keep_alive r9\n    r13 = unbox(int, r12)\n    r14 = AgainProperty(r0, r13)\n    return r14\ndef AgainProperty.next__DerivedProperty_glue(__mypyc_self__):\n    __mypyc_self__, r0 :: __main__.AgainProperty\nL0:\n    r0 = __mypyc_self__.next\n    return r0\ndef AgainProperty.next__BaseProperty_glue(__mypyc_self__):\n    __mypyc_self__, r0 :: __main__.AgainProperty\nL0:\n    r0 = __mypyc_self__.next\n    return r0\ndef AgainProperty.bad_value(self):\n    self :: __main__.AgainProperty\n    r0 :: int\nL0:\n    r0 = self._incrementer\n    return r0\ndef AgainProperty.bad_value__DerivedProperty_glue(__mypyc_self__):\n    __mypyc_self__ :: __main__.AgainProperty\n    r0 :: int\n    r1 :: object\nL0:\n    r0 = __mypyc_self__.bad_value\n    r1 = box(int, r0)\n    return r1\ndef AgainProperty.bad_value__BaseProperty_glue(__mypyc_self__):\n    __mypyc_self__ :: __main__.AgainProperty\n    r0 :: int\n    r1 :: object\nL0:\n    r0 = __mypyc_self__.bad_value\n    r1 = box(int, r0)\n    return r1\n\n[case testPropertyTraitSubclassing]\nfrom mypy_extensions import trait\n@trait\nclass SubclassedTrait:\n    @property\n    def this(self) -> SubclassedTrait:\n        return self\n\n    @property\n    def boxed(self) -> object:\n        return 3\n\nclass DerivingObject(SubclassedTrait):\n    @property\n    def this(self) -> DerivingObject:\n        return self\n\n    @property\n    def boxed(self) -> int:\n        return 5\n[out]\ndef SubclassedTrait.this(self):\n    self :: __main__.SubclassedTrait\nL0:\n    return self\ndef SubclassedTrait.boxed(self):\n    self :: __main__.SubclassedTrait\n    r0 :: object\nL0:\n    r0 = object 3\n    return r0\ndef DerivingObject.this(self):\n    self :: __main__.DerivingObject\nL0:\n    return self\ndef DerivingObject.this__SubclassedTrait_glue(__mypyc_self__):\n    __mypyc_self__, r0 :: __main__.DerivingObject\nL0:\n    r0 = __mypyc_self__.this\n    return r0\ndef DerivingObject.boxed(self):\n    self :: __main__.DerivingObject\nL0:\n    return 10\ndef DerivingObject.boxed__SubclassedTrait_glue(__mypyc_self__):\n    __mypyc_self__ :: __main__.DerivingObject\n    r0 :: int\n    r1 :: object\nL0:\n    r0 = __mypyc_self__.boxed\n    r1 = box(int, r0)\n    return r1\n\n[case testI64GlueWithExtraDefaultArg]\nfrom mypy_extensions import i64\n\nclass C:\n    def f(self) -> None: pass\n\nclass D(C):\n    def f(self, x: i64 = 44) -> None: pass\n[out]\ndef C.f(self):\n    self :: __main__.C\nL0:\n    return 1\ndef D.f(self, x, __bitmap):\n    self :: __main__.D\n    x :: i64\n    __bitmap, r0 :: u32\n    r1 :: bit\nL0:\n    r0 = __bitmap & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    x = 44\nL2:\n    return 1\ndef D.f__C_glue(self):\n    self :: __main__.D\n    r0 :: None\nL0:\n    r0 = D.f(self, 0, 0)\n    return r0\n\n[case testI64GlueWithSecondDefaultArg]\nfrom mypy_extensions import i64\n\nclass C:\n    def f(self, x: i64 = 11) -> None: pass\nclass D(C):\n    def f(self, x: i64 = 12, y: i64 = 13) -> None: pass\n[out]\ndef C.f(self, x, __bitmap):\n    self :: __main__.C\n    x :: i64\n    __bitmap, r0 :: u32\n    r1 :: bit\nL0:\n    r0 = __bitmap & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    x = 11\nL2:\n    return 1\ndef D.f(self, x, y, __bitmap):\n    self :: __main__.D\n    x, y :: i64\n    __bitmap, r0 :: u32\n    r1 :: bit\n    r2 :: u32\n    r3 :: bit\nL0:\n    r0 = __bitmap & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    x = 12\nL2:\n    r2 = __bitmap & 2\n    r3 = r2 == 0\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    y = 13\nL4:\n    return 1\ndef D.f__C_glue(self, x, __bitmap):\n    self :: __main__.D\n    x :: i64\n    __bitmap :: u32\n    r0 :: None\nL0:\n    r0 = D.f(self, x, 0, __bitmap)\n    return r0\n\n[case testI64GlueWithInvalidOverride]\nfrom mypy_extensions import i64\n\nclass C:\n    def f(self, x: i64, y: i64 = 5) -> None: pass\n    def ff(self, x: int) -> None: pass\nclass CC(C):\n    def f(self, x: i64 = 12, y: i64 = 5) -> None: pass  # Line 7\n    def ff(self, x: int = 12) -> None: pass\n\nclass D:\n    def f(self, x: int) -> None: pass\nclass DD(D):\n    def f(self, x: i64) -> None: pass  # Line 13\n\nclass E:\n    def f(self, x: i64) -> None: pass\nclass EE(E):\n    def f(self, x: int) -> None: pass  # Line 18\n[out]\nmain:7: error: An argument with type \"i64\" cannot be given a default value in a method override\nmain:13: error: Incompatible argument type \"i64\" (base class has type \"int\")\nmain:18: error: Incompatible argument type \"int\" (base class has type \"i64\")\n\n[case testPropertySetterShadowGlue]\nimport mypy_extensions\n\n@mypy_extensions.mypyc_attr(allow_interpreted_subclasses=True)\nclass Base:\n    _x: str = \"\"\n\n    @property\n    def x(self) -> str:\n        return self._x\n\n    @x.setter\n    def x(self, v: str) -> None:\n        self._x = v\n[out]\ndef Base.x(self):\n    self :: __main__.Base\n    r0 :: str\nL0:\n    r0 = self._x\n    return r0\ndef Base.x__Base_glue(__mypyc_self__):\n    __mypyc_self__ :: __main__.Base\n    r0 :: str\n    r1 :: object\n    r2 :: str\nL0:\n    r0 = 'x'\n    r1 = CPyObject_GetAttr(__mypyc_self__, r0)\n    r2 = cast(str, r1)\n    return r2\ndef Base.__mypyc_setter__x(self, v):\n    self :: __main__.Base\n    v :: str\n    r0 :: bool\nL0:\n    self._x = v; r0 = is_error\n    return 1\ndef Base.__mypyc_setter__x__Base_glue(self, v):\n    self :: __main__.Base\n    v, r0 :: str\n    r1 :: i32\n    r2 :: bit\nL0:\n    r0 = 'x'\n    r1 = PyObject_SetAttr(self, r0, v)\n    r2 = r1 >= 0 :: signed\n    return 1\ndef Base.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.Base\n    r0 :: str\nL0:\n    r0 = ''\n    __mypyc_self__._x = r0\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-i16.test",
    "content": "# Test cases for i16 native ints. Focus on things that are different from i64; no need to\n# duplicate all i64 test cases here.\n\n[case testI16BinaryOp]\nfrom mypy_extensions import i16\n\ndef add_op(x: i16, y: i16) -> i16:\n    x = y + x\n    y = x + 5\n    y += x\n    y += 7\n    x = 5 + y\n    return x\ndef compare(x: i16, y: i16) -> None:\n    a = x == y\n    b = x == -5\n    c = x < y\n    d = x < -5\n    e = -5 == x\n    f = -5 < x\n[out]\ndef add_op(x, y):\n    x, y, r0, r1, r2, r3, r4 :: i16\nL0:\n    r0 = y + x\n    x = r0\n    r1 = x + 5\n    y = r1\n    r2 = y + x\n    y = r2\n    r3 = y + 7\n    y = r3\n    r4 = 5 + y\n    x = r4\n    return x\ndef compare(x, y):\n    x, y :: i16\n    r0 :: bit\n    a :: bool\n    r1 :: bit\n    b :: bool\n    r2 :: bit\n    c :: bool\n    r3 :: bit\n    d :: bool\n    r4 :: bit\n    e :: bool\n    r5 :: bit\n    f :: bool\nL0:\n    r0 = x == y\n    a = r0\n    r1 = x == -5\n    b = r1\n    r2 = x < y :: signed\n    c = r2\n    r3 = x < -5 :: signed\n    d = r3\n    r4 = -5 == x\n    e = r4\n    r5 = -5 < x :: signed\n    f = r5\n    return 1\n\n[case testI16UnaryOp]\nfrom mypy_extensions import i16\n\ndef unary(x: i16) -> i16:\n    y = -x\n    x = ~y\n    y = +x\n    return y\n[out]\ndef unary(x):\n    x, r0, y, r1 :: i16\nL0:\n    r0 = 0 - x\n    y = r0\n    r1 = y ^ -1\n    x = r1\n    y = x\n    return y\n\n[case testI16DivisionByConstant]\nfrom mypy_extensions import i16\n\ndef div_by_constant(x: i16) -> i16:\n    x = x // 5\n    x //= 17\n    return x\n[out]\ndef div_by_constant(x):\n    x, r0, r1 :: i16\n    r2, r3, r4 :: bit\n    r5 :: i16\n    r6 :: bit\n    r7, r8, r9 :: i16\n    r10, r11, r12 :: bit\n    r13 :: i16\n    r14 :: bit\n    r15 :: i16\nL0:\n    r0 = x / 5\n    r1 = r0\n    r2 = x < 0 :: signed\n    r3 = 5 < 0 :: signed\n    r4 = r2 == r3\n    if r4 goto L3 else goto L1 :: bool\nL1:\n    r5 = r1 * 5\n    r6 = r5 == x\n    if r6 goto L3 else goto L2 :: bool\nL2:\n    r7 = r1 - 1\n    r1 = r7\nL3:\n    x = r1\n    r8 = x / 17\n    r9 = r8\n    r10 = x < 0 :: signed\n    r11 = 17 < 0 :: signed\n    r12 = r10 == r11\n    if r12 goto L6 else goto L4 :: bool\nL4:\n    r13 = r9 * 17\n    r14 = r13 == x\n    if r14 goto L6 else goto L5 :: bool\nL5:\n    r15 = r9 - 1\n    r9 = r15\nL6:\n    x = r9\n    return x\n\n[case testI16ModByConstant]\nfrom mypy_extensions import i16\n\ndef mod_by_constant(x: i16) -> i16:\n    x = x % 5\n    x %= 17\n    return x\n[out]\ndef mod_by_constant(x):\n    x, r0, r1 :: i16\n    r2, r3, r4, r5 :: bit\n    r6, r7, r8 :: i16\n    r9, r10, r11, r12 :: bit\n    r13 :: i16\nL0:\n    r0 = x % 5\n    r1 = r0\n    r2 = x < 0 :: signed\n    r3 = 5 < 0 :: signed\n    r4 = r2 == r3\n    if r4 goto L3 else goto L1 :: bool\nL1:\n    r5 = r1 == 0\n    if r5 goto L3 else goto L2 :: bool\nL2:\n    r6 = r1 + 5\n    r1 = r6\nL3:\n    x = r1\n    r7 = x % 17\n    r8 = r7\n    r9 = x < 0 :: signed\n    r10 = 17 < 0 :: signed\n    r11 = r9 == r10\n    if r11 goto L6 else goto L4 :: bool\nL4:\n    r12 = r8 == 0\n    if r12 goto L6 else goto L5 :: bool\nL5:\n    r13 = r8 + 17\n    r8 = r13\nL6:\n    x = r8\n    return x\n\n[case testI16DivModByVariable]\nfrom mypy_extensions import i16\n\ndef divmod(x: i16, y: i16) -> i16:\n    a = x // y\n    return a % y\n[out]\ndef divmod(x, y):\n    x, y, r0, a, r1 :: i16\nL0:\n    r0 = CPyInt16_Divide(x, y)\n    a = r0\n    r1 = CPyInt16_Remainder(a, y)\n    return r1\n\n[case testI16BinaryOperationWithOutOfRangeOperand]\nfrom mypy_extensions import i16\n\ndef out_of_range(x: i16) -> None:\n    x + (-32769)\n    (-32770) + x\n    x * 32768\n    x + 32767  # OK\n    (-32768) + x   # OK\n[out]\nmain:4: error: Value -32769 is out of range for \"i16\"\nmain:5: error: Value -32770 is out of range for \"i16\"\nmain:6: error: Value 32768 is out of range for \"i16\"\n\n[case testI16BoxAndUnbox]\nfrom typing import Any\nfrom mypy_extensions import i16\n\ndef f(x: Any) -> Any:\n    y: i16 = x\n    return y\n[out]\ndef f(x):\n    x :: object\n    r0, y :: i16\n    r1 :: object\nL0:\n    r0 = unbox(i16, x)\n    y = r0\n    r1 = box(i16, y)\n    return r1\n\n[case testI16MixedCompare1]\nfrom mypy_extensions import i16\ndef f(x: int, y: i16) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x :: int\n    y :: i16\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6 :: i16\n    r7 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = x < 65536 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = x >= -65536 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = x >> 1\n    r5 = truncate r4: native_int to i16\n    r6 = r5\n    goto L5\nL4:\n    CPyInt16_Overflow()\n    unreachable\nL5:\n    r7 = r6 == y\n    return r7\n\n[case testI16MixedCompare2]\nfrom mypy_extensions import i16\ndef f(x: i16, y: int) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x :: i16\n    y :: int\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6 :: i16\n    r7 :: bit\nL0:\n    r0 = y & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = y < 65536 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = y >= -65536 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = y >> 1\n    r5 = truncate r4: native_int to i16\n    r6 = r5\n    goto L5\nL4:\n    CPyInt16_Overflow()\n    unreachable\nL5:\n    r7 = x == r6\n    return r7\n\n[case testI16ConvertToInt]\nfrom mypy_extensions import i16\n\ndef i16_to_int(a: i16) -> int:\n    return a\n[out]\ndef i16_to_int(a):\n    a :: i16\n    r0 :: native_int\n    r1 :: int\nL0:\n    r0 = extend signed a: i16 to native_int\n    r1 = r0 << 1\n    return r1\n\n[case testI16OperatorAssignmentMixed]\nfrom mypy_extensions import i16\n\ndef f(a: i16) -> None:\n    x = 0\n    x += a\n[out]\ndef f(a):\n    a :: i16\n    x :: int\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6, r7 :: i16\n    r8 :: native_int\n    r9 :: int\nL0:\n    x = 0\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = x < 65536 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = x >= -65536 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = x >> 1\n    r5 = truncate r4: native_int to i16\n    r6 = r5\n    goto L5\nL4:\n    CPyInt16_Overflow()\n    unreachable\nL5:\n    r7 = r6 + a\n    r8 = extend signed r7: i16 to native_int\n    r9 = r8 << 1\n    x = r9\n    return 1\n\n[case testI16InitializeFromLiteral]\nfrom mypy_extensions import i16, i64\n\ndef f() -> None:\n    x: i16 = 0\n    y: i16 = -127\n    z: i16 = 5 + 7\n[out]\ndef f():\n    x, y, z :: i16\nL0:\n    x = 0\n    y = -127\n    z = 12\n    return 1\n\n[case testI16ExplicitConversionFromNativeInt]\nfrom mypy_extensions import i64, i32, i16\n\ndef from_i16(x: i16) -> i16:\n    return i16(x)\n\ndef from_i32(x: i32) -> i16:\n    return i16(x)\n\ndef from_i64(x: i64) -> i16:\n    return i16(x)\n[out]\ndef from_i16(x):\n    x :: i16\nL0:\n    return x\ndef from_i32(x):\n    x :: i32\n    r0 :: i16\nL0:\n    r0 = truncate x: i32 to i16\n    return r0\ndef from_i64(x):\n    x :: i64\n    r0 :: i16\nL0:\n    r0 = truncate x: i64 to i16\n    return r0\n\n[case testI16ExplicitConversionFromInt]\nfrom mypy_extensions import i16\n\ndef f(x: int) -> i16:\n    return i16(x)\n[out]\ndef f(x):\n    x :: int\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6 :: i16\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = x < 65536 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = x >= -65536 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = x >> 1\n    r5 = truncate r4: native_int to i16\n    r6 = r5\n    goto L5\nL4:\n    CPyInt16_Overflow()\n    unreachable\nL5:\n    return r6\n\n[case testI16ExplicitConversionFromLiteral]\nfrom mypy_extensions import i16\n\ndef f() -> None:\n    x = i16(0)\n    y = i16(11)\n    z = i16(-3)\n    a = i16(32767)\n    b = i16(32768)  # Truncate\n    c = i16(-32768)\n    d = i16(-32769)  # Truncate\n[out]\ndef f():\n    x, y, z, a, b, c, d :: i16\nL0:\n    x = 0\n    y = 11\n    z = -3\n    a = 32767\n    b = -32768\n    c = -32768\n    d = 32767\n    return 1\n\n[case testI16ExplicitConversionFromVariousTypes]\nfrom mypy_extensions import i16\n\ndef bool_to_i16(b: bool) -> i16:\n    return i16(b)\n\ndef str_to_i16(s: str) -> i16:\n    return i16(s)\n\nclass C:\n    def __int__(self) -> i16:\n        return 5\n\ndef instance_to_i16(c: C) -> i16:\n    return i16(c)\n\ndef float_to_i16(x: float) -> i16:\n    return i16(x)\n[out]\ndef bool_to_i16(b):\n    b :: bool\n    r0 :: i16\nL0:\n    r0 = extend b: builtins.bool to i16\n    return r0\ndef str_to_i16(s):\n    s :: str\n    r0 :: object\n    r1 :: i16\nL0:\n    r0 = CPyLong_FromStr(s)\n    r1 = unbox(i16, r0)\n    return r1\ndef C.__int__(self):\n    self :: __main__.C\nL0:\n    return 5\ndef instance_to_i16(c):\n    c :: __main__.C\n    r0 :: i16\nL0:\n    r0 = c.__int__()\n    return r0\ndef float_to_i16(x):\n    x :: float\n    r0 :: int\n    r1 :: native_int\n    r2, r3, r4 :: bit\n    r5 :: native_int\n    r6, r7 :: i16\nL0:\n    r0 = CPyTagged_FromFloat(x)\n    r1 = r0 & 1\n    r2 = r1 == 0\n    if r2 goto L1 else goto L4 :: bool\nL1:\n    r3 = r0 < 65536 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = r0 >= -65536 :: signed\n    if r4 goto L3 else goto L4 :: bool\nL3:\n    r5 = r0 >> 1\n    r6 = truncate r5: native_int to i16\n    r7 = r6\n    goto L5\nL4:\n    CPyInt16_Overflow()\n    unreachable\nL5:\n    return r7\n"
  },
  {
    "path": "mypyc/test-data/irbuild-i32.test",
    "content": "# Test cases for i32 native ints. Focus on things that are different from i64; no need to\n# duplicate all i64 test cases here.\n\n[case testI32BinaryOp]\nfrom mypy_extensions import i32\n\ndef add_op(x: i32, y: i32) -> i32:\n    x = y + x\n    y = x + 5\n    y += x\n    y += 7\n    x = 5 + y\n    return x\ndef compare(x: i32, y: i32) -> None:\n    a = x == y\n    b = x == -5\n    c = x < y\n    d = x < -5\n    e = -5 == x\n    f = -5 < x\n[out]\ndef add_op(x, y):\n    x, y, r0, r1, r2, r3, r4 :: i32\nL0:\n    r0 = y + x\n    x = r0\n    r1 = x + 5\n    y = r1\n    r2 = y + x\n    y = r2\n    r3 = y + 7\n    y = r3\n    r4 = 5 + y\n    x = r4\n    return x\ndef compare(x, y):\n    x, y :: i32\n    r0 :: bit\n    a :: bool\n    r1 :: bit\n    b :: bool\n    r2 :: bit\n    c :: bool\n    r3 :: bit\n    d :: bool\n    r4 :: bit\n    e :: bool\n    r5 :: bit\n    f :: bool\nL0:\n    r0 = x == y\n    a = r0\n    r1 = x == -5\n    b = r1\n    r2 = x < y :: signed\n    c = r2\n    r3 = x < -5 :: signed\n    d = r3\n    r4 = -5 == x\n    e = r4\n    r5 = -5 < x :: signed\n    f = r5\n    return 1\n\n[case testI32UnaryOp]\nfrom mypy_extensions import i32\n\ndef unary(x: i32) -> i32:\n    y = -x\n    x = ~y\n    y = +x\n    return y\n[out]\ndef unary(x):\n    x, r0, y, r1 :: i32\nL0:\n    r0 = 0 - x\n    y = r0\n    r1 = y ^ -1\n    x = r1\n    y = x\n    return y\n\n[case testI32DivisionByConstant]\nfrom mypy_extensions import i32\n\ndef div_by_constant(x: i32) -> i32:\n    x = x // 5\n    x //= 17\n    return x\n[out]\ndef div_by_constant(x):\n    x, r0, r1 :: i32\n    r2, r3, r4 :: bit\n    r5 :: i32\n    r6 :: bit\n    r7, r8, r9 :: i32\n    r10, r11, r12 :: bit\n    r13 :: i32\n    r14 :: bit\n    r15 :: i32\nL0:\n    r0 = x / 5\n    r1 = r0\n    r2 = x < 0 :: signed\n    r3 = 5 < 0 :: signed\n    r4 = r2 == r3\n    if r4 goto L3 else goto L1 :: bool\nL1:\n    r5 = r1 * 5\n    r6 = r5 == x\n    if r6 goto L3 else goto L2 :: bool\nL2:\n    r7 = r1 - 1\n    r1 = r7\nL3:\n    x = r1\n    r8 = x / 17\n    r9 = r8\n    r10 = x < 0 :: signed\n    r11 = 17 < 0 :: signed\n    r12 = r10 == r11\n    if r12 goto L6 else goto L4 :: bool\nL4:\n    r13 = r9 * 17\n    r14 = r13 == x\n    if r14 goto L6 else goto L5 :: bool\nL5:\n    r15 = r9 - 1\n    r9 = r15\nL6:\n    x = r9\n    return x\n\n[case testI32ModByConstant]\nfrom mypy_extensions import i32\n\ndef mod_by_constant(x: i32) -> i32:\n    x = x % 5\n    x %= 17\n    return x\n[out]\ndef mod_by_constant(x):\n    x, r0, r1 :: i32\n    r2, r3, r4, r5 :: bit\n    r6, r7, r8 :: i32\n    r9, r10, r11, r12 :: bit\n    r13 :: i32\nL0:\n    r0 = x % 5\n    r1 = r0\n    r2 = x < 0 :: signed\n    r3 = 5 < 0 :: signed\n    r4 = r2 == r3\n    if r4 goto L3 else goto L1 :: bool\nL1:\n    r5 = r1 == 0\n    if r5 goto L3 else goto L2 :: bool\nL2:\n    r6 = r1 + 5\n    r1 = r6\nL3:\n    x = r1\n    r7 = x % 17\n    r8 = r7\n    r9 = x < 0 :: signed\n    r10 = 17 < 0 :: signed\n    r11 = r9 == r10\n    if r11 goto L6 else goto L4 :: bool\nL4:\n    r12 = r8 == 0\n    if r12 goto L6 else goto L5 :: bool\nL5:\n    r13 = r8 + 17\n    r8 = r13\nL6:\n    x = r8\n    return x\n\n[case testI32DivModByVariable]\nfrom mypy_extensions import i32\n\ndef divmod(x: i32, y: i32) -> i32:\n    a = x // y\n    return a % y\n[out]\ndef divmod(x, y):\n    x, y, r0, a, r1 :: i32\nL0:\n    r0 = CPyInt32_Divide(x, y)\n    a = r0\n    r1 = CPyInt32_Remainder(a, y)\n    return r1\n\n[case testI32BoxAndUnbox]\nfrom typing import Any\nfrom mypy_extensions import i32\n\ndef f(x: Any) -> Any:\n    y: i32 = x\n    return y\n[out]\ndef f(x):\n    x :: object\n    r0, y :: i32\n    r1 :: object\nL0:\n    r0 = unbox(i32, x)\n    y = r0\n    r1 = box(i32, y)\n    return r1\n\n[case testI32MixedCompare1_64bit]\nfrom mypy_extensions import i32\ndef f(x: int, y: i32) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x :: int\n    y :: i32\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6 :: i32\n    r7 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = x < 4294967296 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = x >= -4294967296 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = x >> 1\n    r5 = truncate r4: native_int to i32\n    r6 = r5\n    goto L5\nL4:\n    CPyInt32_Overflow()\n    unreachable\nL5:\n    r7 = r6 == y\n    return r7\n\n[case testI32MixedCompare2_64bit]\nfrom mypy_extensions import i32\ndef f(x: i32, y: int) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x :: i32\n    y :: int\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6 :: i32\n    r7 :: bit\nL0:\n    r0 = y & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = y < 4294967296 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = y >= -4294967296 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = y >> 1\n    r5 = truncate r4: native_int to i32\n    r6 = r5\n    goto L5\nL4:\n    CPyInt32_Overflow()\n    unreachable\nL5:\n    r7 = x == r6\n    return r7\n\n[case testI32MixedCompare_32bit]\nfrom mypy_extensions import i32\ndef f(x: int, y: i32) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x :: int\n    y :: i32\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i32\n    r4 :: ptr\n    r5 :: c_ptr\n    r6 :: i32\n    r7 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = x >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = x ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt32(r5)\n    r3 = r6\n    keep_alive x\nL3:\n    r7 = r3 == y\n    return r7\n\n[case testI32ConvertToInt_64bit]\nfrom mypy_extensions import i32\n\ndef i32_to_int(a: i32) -> int:\n    return a\n[out]\ndef i32_to_int(a):\n    a :: i32\n    r0 :: native_int\n    r1 :: int\nL0:\n    r0 = extend signed a: i32 to native_int\n    r1 = r0 << 1\n    return r1\n\n[case testI32ConvertToInt_32bit]\nfrom mypy_extensions import i32\n\ndef i32_to_int(a: i32) -> int:\n    return a\n[out]\ndef i32_to_int(a):\n    a :: i32\n    r0, r1 :: bit\n    r2, r3, r4 :: int\nL0:\n    r0 = a <= 1073741823 :: signed\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = a >= -1073741824 :: signed\n    if r1 goto L3 else goto L2 :: bool\nL2:\n    r2 = CPyTagged_FromSsize_t(a)\n    r3 = r2\n    goto L4\nL3:\n    r4 = a << 1\n    r3 = r4\nL4:\n    return r3\n\n[case testI32OperatorAssignmentMixed_64bit]\nfrom mypy_extensions import i32\n\ndef f(a: i32) -> None:\n    x = 0\n    x += a\n[out]\ndef f(a):\n    a :: i32\n    x :: int\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6, r7 :: i32\n    r8 :: native_int\n    r9 :: int\nL0:\n    x = 0\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = x < 4294967296 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = x >= -4294967296 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = x >> 1\n    r5 = truncate r4: native_int to i32\n    r6 = r5\n    goto L5\nL4:\n    CPyInt32_Overflow()\n    unreachable\nL5:\n    r7 = r6 + a\n    r8 = extend signed r7: i32 to native_int\n    r9 = r8 << 1\n    x = r9\n    return 1\n\n[case testI32InitializeFromLiteral]\nfrom mypy_extensions import i32, i64\n\ndef f() -> None:\n    x: i32 = 0\n    y: i32 = -127\n    z: i32 = 5 + 7\n[out]\ndef f():\n    x, y, z :: i32\nL0:\n    x = 0\n    y = -127\n    z = 12\n    return 1\n\n[case testI32ExplicitConversionFromNativeInt]\nfrom mypy_extensions import i64, i32, i16\n\ndef from_i16(x: i16) -> i32:\n    return i32(x)\n\ndef from_i32(x: i32) -> i32:\n    return i32(x)\n\ndef from_i64(x: i64) -> i32:\n    return i32(x)\n[out]\ndef from_i16(x):\n    x :: i16\n    r0 :: i32\nL0:\n    r0 = extend signed x: i16 to i32\n    return r0\ndef from_i32(x):\n    x :: i32\nL0:\n    return x\ndef from_i64(x):\n    x :: i64\n    r0 :: i32\nL0:\n    r0 = truncate x: i64 to i32\n    return r0\n\n[case testI32ExplicitConversionFromInt_64bit]\nfrom mypy_extensions import i32\n\ndef f(x: int) -> i32:\n    return i32(x)\n[out]\ndef f(x):\n    x :: int\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6 :: i32\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = x < 4294967296 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = x >= -4294967296 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = x >> 1\n    r5 = truncate r4: native_int to i32\n    r6 = r5\n    goto L5\nL4:\n    CPyInt32_Overflow()\n    unreachable\nL5:\n    return r6\n\n[case testI32ExplicitConversionFromLiteral_64bit]\nfrom mypy_extensions import i32\n\ndef f() -> None:\n    x = i32(0)\n    y = i32(11)\n    z = i32(-3)\n    a = i32(2**31)\n[out]\ndef f():\n    x, y, z, a :: i32\nL0:\n    x = 0\n    y = 11\n    z = -3\n    a = -2147483648\n    return 1\n\n[case testI32ExplicitConversionFromVariousTypes_64bit]\nfrom mypy_extensions import i32\n\ndef bool_to_i32(b: bool) -> i32:\n    return i32(b)\n\ndef str_to_i32(s: str) -> i32:\n    return i32(s)\n\nclass C:\n    def __int__(self) -> i32:\n        return 5\n\ndef instance_to_i32(c: C) -> i32:\n    return i32(c)\n\ndef float_to_i32(x: float) -> i32:\n    return i32(x)\n[out]\ndef bool_to_i32(b):\n    b :: bool\n    r0 :: i32\nL0:\n    r0 = extend b: builtins.bool to i32\n    return r0\ndef str_to_i32(s):\n    s :: str\n    r0 :: object\n    r1 :: i32\nL0:\n    r0 = CPyLong_FromStr(s)\n    r1 = unbox(i32, r0)\n    return r1\ndef C.__int__(self):\n    self :: __main__.C\nL0:\n    return 5\ndef instance_to_i32(c):\n    c :: __main__.C\n    r0 :: i32\nL0:\n    r0 = c.__int__()\n    return r0\ndef float_to_i32(x):\n    x :: float\n    r0 :: int\n    r1 :: native_int\n    r2, r3, r4 :: bit\n    r5 :: native_int\n    r6, r7 :: i32\nL0:\n    r0 = CPyTagged_FromFloat(x)\n    r1 = r0 & 1\n    r2 = r1 == 0\n    if r2 goto L1 else goto L4 :: bool\nL1:\n    r3 = r0 < 4294967296 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = r0 >= -4294967296 :: signed\n    if r4 goto L3 else goto L4 :: bool\nL3:\n    r5 = r0 >> 1\n    r6 = truncate r5: native_int to i32\n    r7 = r6\n    goto L5\nL4:\n    CPyInt32_Overflow()\n    unreachable\nL5:\n    return r7\n\n[case testI32ExplicitConversionFromFloat_32bit]\nfrom mypy_extensions import i32\n\ndef float_to_i32(x: float) -> i32:\n    return i32(x)\n[out]\ndef float_to_i32(x):\n    x :: float\n    r0 :: int\n    r1 :: native_int\n    r2 :: bit\n    r3, r4 :: i32\n    r5 :: ptr\n    r6 :: c_ptr\n    r7 :: i32\nL0:\n    r0 = CPyTagged_FromFloat(x)\n    r1 = r0 & 1\n    r2 = r1 == 0\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = r0 >> 1\n    r4 = r3\n    goto L3\nL2:\n    r5 = r0 ^ 1\n    r6 = r5\n    r7 = CPyLong_AsInt32(r6)\n    r4 = r7\n    keep_alive r0\nL3:\n    return r4\n"
  },
  {
    "path": "mypyc/test-data/irbuild-i64.test",
    "content": "[case testI64Basics]\nfrom mypy_extensions import i64\n\ndef f() -> i64:\n    x: i64 = 5\n    y = x\n    return y\n[out]\ndef f():\n    x, y :: i64\nL0:\n    x = 5\n    y = x\n    return y\n\n[case testI64Compare]\nfrom mypy_extensions import i64\n\ndef min(x: i64, y: i64) -> i64:\n    if x < y:\n        return x\n    else:\n        return y\n\ndef all_comparisons(x: i64) -> int:\n    if x == 2:\n        y = 10\n    elif 3 != x:\n        y = 11\n    elif x > 4:\n        y = 12\n    elif 6 >= x:\n        y = 13\n    elif x < 5:\n        y = 14\n    elif 6 <= x:\n        y = 15\n    else:\n        y = 16\n    return y\n[out]\ndef min(x, y):\n    x, y :: i64\n    r0 :: bit\nL0:\n    r0 = x < y :: signed\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return x\nL2:\n    return y\nL3:\n    unreachable\ndef all_comparisons(x):\n    x :: i64\n    r0 :: bit\n    y :: int\n    r1, r2, r3, r4, r5 :: bit\nL0:\n    r0 = x == 2\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    y = 20\n    goto L18\nL2:\n    r1 = 3 != x\n    if r1 goto L3 else goto L4 :: bool\nL3:\n    y = 22\n    goto L17\nL4:\n    r2 = x > 4 :: signed\n    if r2 goto L5 else goto L6 :: bool\nL5:\n    y = 24\n    goto L16\nL6:\n    r3 = 6 >= x :: signed\n    if r3 goto L7 else goto L8 :: bool\nL7:\n    y = 26\n    goto L15\nL8:\n    r4 = x < 5 :: signed\n    if r4 goto L9 else goto L10 :: bool\nL9:\n    y = 28\n    goto L14\nL10:\n    r5 = 6 <= x :: signed\n    if r5 goto L11 else goto L12 :: bool\nL11:\n    y = 30\n    goto L13\nL12:\n    y = 32\nL13:\nL14:\nL15:\nL16:\nL17:\nL18:\n    return y\n\n[case testI64Arithmetic]\nfrom mypy_extensions import i64\n\ndef f(x: i64, y: i64) -> i64:\n    z = x + y\n    return y - z\n[out]\ndef f(x, y):\n    x, y, r0, z, r1 :: i64\nL0:\n    r0 = x + y\n    z = r0\n    r1 = y - z\n    return r1\n\n[case testI64Negation]\nfrom mypy_extensions import i64\n\ndef f() -> i64:\n    i: i64 = -3\n    return -i\n[out]\ndef f():\n    i, r0 :: i64\nL0:\n    i = -3\n    r0 = 0 - i\n    return r0\n\n[case testI64MoreUnaryOps]\nfrom mypy_extensions import i64\n\ndef unary(x: i64) -> i64:\n    y = ~x\n    x = +y\n    return x\n[out]\ndef unary(x):\n    x, r0, y :: i64\nL0:\n    r0 = x ^ -1\n    y = r0\n    x = y\n    return x\n\n[case testI64BoxingAndUnboxing]\nfrom typing import Any\nfrom mypy_extensions import i64\n\ndef f(a: Any) -> None:\n    b: i64 = a\n    a = b\n[out]\ndef f(a):\n    a :: object\n    r0, b :: i64\n    r1 :: object\nL0:\n    r0 = unbox(i64, a)\n    b = r0\n    r1 = box(i64, b)\n    a = r1\n    return 1\n\n[case testI64ListGetSetItem]\nfrom typing import List\nfrom mypy_extensions import i64\n\ndef get(a: List[i64], i: i64) -> i64:\n    return a[i]\ndef set(a: List[i64], i: i64, x: i64) -> None:\n    a[i] = x\n[out]\ndef get(a, i):\n    a :: list\n    i :: i64\n    r0 :: object\n    r1 :: i64\nL0:\n    r0 = CPyList_GetItemInt64(a, i)\n    r1 = unbox(i64, r0)\n    return r1\ndef set(a, i, x):\n    a :: list\n    i, x :: i64\n    r0 :: object\n    r1 :: bit\nL0:\n    r0 = box(i64, x)\n    r1 = CPyList_SetItemInt64(a, i, r0)\n    return 1\n\n[case testI64MixedArithmetic]\nfrom mypy_extensions import i64\n\ndef f() -> i64:\n    a: i64 = 1\n    b = a + 2\n    return 3 - b\n[out]\ndef f():\n    a, r0, b, r1 :: i64\nL0:\n    a = 1\n    r0 = a + 2\n    b = r0\n    r1 = 3 - b\n    return r1\n\n[case testI64MixedComparison]\nfrom mypy_extensions import i64\n\ndef f(a: i64) -> i64:\n    if a < 3:\n        return 1\n    elif 3 < a:\n        return 2\n    return 3\n[out]\ndef f(a):\n    a :: i64\n    r0, r1 :: bit\nL0:\n    r0 = a < 3 :: signed\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    r1 = 3 < a :: signed\n    if r1 goto L3 else goto L4 :: bool\nL3:\n    return 2\nL4:\nL5:\n    return 3\n\n[case testI64InplaceOperations]\nfrom mypy_extensions import i64\n\ndef add(a: i64) -> i64:\n    b = a\n    b += 1\n    a += b\n    return a\ndef others(a: i64, b: i64) -> i64:\n    a -= b\n    a *= b\n    a &= b\n    a |= b\n    a ^= b\n    a <<= b\n    a >>= b\n    return a\n[out]\ndef add(a):\n    a, b, r0, r1 :: i64\nL0:\n    b = a\n    r0 = b + 1\n    b = r0\n    r1 = a + b\n    a = r1\n    return a\ndef others(a, b):\n    a, b, r0, r1, r2, r3, r4, r5, r6 :: i64\nL0:\n    r0 = a - b\n    a = r0\n    r1 = a * b\n    a = r1\n    r2 = a & b\n    a = r2\n    r3 = a | b\n    a = r3\n    r4 = a ^ b\n    a = r4\n    r5 = a << b\n    a = r5\n    r6 = a >> b\n    a = r6\n    return a\n\n[case testI64BitwiseOps]\nfrom mypy_extensions import i64\n\ndef forward(a: i64, b: i64) -> i64:\n    b = a & 1\n    a = b | 2\n    b = a ^ 3\n    a = b << 4\n    b = a >> 5\n    return b\n\ndef reverse(a: i64, b: i64) -> i64:\n    b = 1 & a\n    a = 2 | b\n    b = 3 ^ a\n    a = 4 << b\n    b = 5 >> a\n    return b\n\ndef unary(a: i64) -> i64:\n    return ~a\n[out]\ndef forward(a, b):\n    a, b, r0, r1, r2, r3, r4 :: i64\nL0:\n    r0 = a & 1\n    b = r0\n    r1 = b | 2\n    a = r1\n    r2 = a ^ 3\n    b = r2\n    r3 = b << 4\n    a = r3\n    r4 = a >> 5\n    b = r4\n    return b\ndef reverse(a, b):\n    a, b, r0, r1, r2, r3, r4 :: i64\nL0:\n    r0 = 1 & a\n    b = r0\n    r1 = 2 | b\n    a = r1\n    r2 = 3 ^ a\n    b = r2\n    r3 = 4 << b\n    a = r3\n    r4 = 5 >> a\n    b = r4\n    return b\ndef unary(a):\n    a, r0 :: i64\nL0:\n    r0 = a ^ -1\n    return r0\n\n[case testI64Division]\nfrom mypy_extensions import i64\n\ndef constant_divisor(x: i64) -> i64:\n    return x // 7\ndef variable_divisor(x: i64, y: i64) -> i64:\n    return x // y\ndef constant_lhs(x: i64) -> i64:\n    return 27 // x\ndef divide_by_neg_one(x: i64) -> i64:\n    return x // -1\ndef divide_by_zero(x: i64) -> i64:\n    return x // 0\n[out]\ndef constant_divisor(x):\n    x, r0, r1 :: i64\n    r2, r3, r4 :: bit\n    r5 :: i64\n    r6 :: bit\n    r7 :: i64\nL0:\n    r0 = x / 7\n    r1 = r0\n    r2 = x < 0 :: signed\n    r3 = 7 < 0 :: signed\n    r4 = r2 == r3\n    if r4 goto L3 else goto L1 :: bool\nL1:\n    r5 = r1 * 7\n    r6 = r5 == x\n    if r6 goto L3 else goto L2 :: bool\nL2:\n    r7 = r1 - 1\n    r1 = r7\nL3:\n    return r1\ndef variable_divisor(x, y):\n    x, y, r0 :: i64\nL0:\n    r0 = CPyInt64_Divide(x, y)\n    return r0\ndef constant_lhs(x):\n    x, r0 :: i64\nL0:\n    r0 = CPyInt64_Divide(27, x)\n    return r0\ndef divide_by_neg_one(x):\n    x, r0 :: i64\nL0:\n    r0 = CPyInt64_Divide(x, -1)\n    return r0\ndef divide_by_zero(x):\n    x, r0 :: i64\nL0:\n    r0 = CPyInt64_Divide(x, 0)\n    return r0\n\n[case testI64Mod]\nfrom mypy_extensions import i64\n\ndef constant_divisor(x: i64) -> i64:\n    return x % 7\ndef variable_divisor(x: i64, y: i64) -> i64:\n    return x % y\ndef constant_lhs(x: i64) -> i64:\n    return 27 % x\ndef mod_by_zero(x: i64) -> i64:\n    return x % 0\n[out]\ndef constant_divisor(x):\n    x, r0, r1 :: i64\n    r2, r3, r4, r5 :: bit\n    r6 :: i64\nL0:\n    r0 = x % 7\n    r1 = r0\n    r2 = x < 0 :: signed\n    r3 = 7 < 0 :: signed\n    r4 = r2 == r3\n    if r4 goto L3 else goto L1 :: bool\nL1:\n    r5 = r1 == 0\n    if r5 goto L3 else goto L2 :: bool\nL2:\n    r6 = r1 + 7\n    r1 = r6\nL3:\n    return r1\ndef variable_divisor(x, y):\n    x, y, r0 :: i64\nL0:\n    r0 = CPyInt64_Remainder(x, y)\n    return r0\ndef constant_lhs(x):\n    x, r0 :: i64\nL0:\n    r0 = CPyInt64_Remainder(27, x)\n    return r0\ndef mod_by_zero(x):\n    x, r0 :: i64\nL0:\n    r0 = CPyInt64_Remainder(x, 0)\n    return r0\n\n[case testI64InPlaceDiv]\nfrom mypy_extensions import i64\n\ndef by_constant(x: i64) -> i64:\n    x //= 7\n    return x\ndef by_variable(x: i64, y: i64) -> i64:\n    x //= y\n    return x\n[out]\ndef by_constant(x):\n    x, r0, r1 :: i64\n    r2, r3, r4 :: bit\n    r5 :: i64\n    r6 :: bit\n    r7 :: i64\nL0:\n    r0 = x / 7\n    r1 = r0\n    r2 = x < 0 :: signed\n    r3 = 7 < 0 :: signed\n    r4 = r2 == r3\n    if r4 goto L3 else goto L1 :: bool\nL1:\n    r5 = r1 * 7\n    r6 = r5 == x\n    if r6 goto L3 else goto L2 :: bool\nL2:\n    r7 = r1 - 1\n    r1 = r7\nL3:\n    x = r1\n    return x\ndef by_variable(x, y):\n    x, y, r0 :: i64\nL0:\n    r0 = CPyInt64_Divide(x, y)\n    x = r0\n    return x\n\n[case testI64InPlaceMod]\nfrom mypy_extensions import i64\n\ndef by_constant(x: i64) -> i64:\n    x %= 7\n    return x\ndef by_variable(x: i64, y: i64) -> i64:\n    x %= y\n    return x\n[out]\ndef by_constant(x):\n    x, r0, r1 :: i64\n    r2, r3, r4, r5 :: bit\n    r6 :: i64\nL0:\n    r0 = x % 7\n    r1 = r0\n    r2 = x < 0 :: signed\n    r3 = 7 < 0 :: signed\n    r4 = r2 == r3\n    if r4 goto L3 else goto L1 :: bool\nL1:\n    r5 = r1 == 0\n    if r5 goto L3 else goto L2 :: bool\nL2:\n    r6 = r1 + 7\n    r1 = r6\nL3:\n    x = r1\n    return x\ndef by_variable(x, y):\n    x, y, r0 :: i64\nL0:\n    r0 = CPyInt64_Remainder(x, y)\n    x = r0\n    return x\n\n[case testI64ForRange]\nfrom mypy_extensions import i64\n\ndef g(a: i64) -> None: pass\n\ndef f(x: i64) -> None:\n    n: i64  # TODO: Infer the type\n    for n in range(x):\n        g(n)\n[out]\ndef g(a):\n    a :: i64\nL0:\n    return 1\ndef f(x):\n    x, r0, n :: i64\n    r1 :: bit\n    r2 :: None\n    r3 :: i64\nL0:\n    r0 = 0\n    n = r0\nL1:\n    r1 = r0 < x :: signed\n    if r1 goto L2 else goto L4 :: bool\nL2:\n    r2 = g(n)\nL3:\n    r3 = r0 + 1\n    r0 = r3\n    n = r3\n    goto L1\nL4:\n    return 1\n\n[case testI64ConvertFromInt_64bit]\nfrom mypy_extensions import i64\n\ndef int_to_i64(a: int) -> i64:\n    return a\n[out]\ndef int_to_i64(a):\n    a :: int\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6 :: i64\nL0:\n    r0 = a & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = a >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = a ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive a\nL3:\n    return r3\n\n[case testI64ConvertToInt_64bit]\nfrom mypy_extensions import i64\n\ndef i64_to_int(a: i64) -> int:\n    return a\n[out]\ndef i64_to_int(a):\n    a :: i64\n    r0, r1 :: bit\n    r2, r3, r4 :: int\nL0:\n    r0 = a <= 4611686018427387903 :: signed\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = a >= -4611686018427387904 :: signed\n    if r1 goto L3 else goto L2 :: bool\nL2:\n    r2 = CPyTagged_FromInt64(a)\n    r3 = r2\n    goto L4\nL3:\n    r4 = a << 1\n    r3 = r4\nL4:\n    return r3\n\n[case testI64ConvertToInt_32bit]\nfrom mypy_extensions import i64\n\ndef i64_to_int(a: i64) -> int:\n    return a\n[out]\ndef i64_to_int(a):\n    a :: i64\n    r0, r1 :: bit\n    r2, r3 :: int\n    r4 :: native_int\n    r5 :: int\nL0:\n    r0 = a <= 1073741823 :: signed\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = a >= -1073741824 :: signed\n    if r1 goto L3 else goto L2 :: bool\nL2:\n    r2 = CPyTagged_FromInt64(a)\n    r3 = r2\n    goto L4\nL3:\n    r4 = truncate a: i64 to native_int\n    r5 = r4 << 1\n    r3 = r5\nL4:\n    return r3\n\n[case testI64Tuple]\nfrom typing import Tuple\nfrom mypy_extensions import i64\n\ndef f(x: i64, y: i64) -> Tuple[i64, i64]:\n    return x, y\n\ndef g() -> Tuple[i64, i64]:\n    return 1, 2\n\ndef h() -> i64:\n    x, y = g()\n    t = g()\n    return x + y + t[0]\n[out]\ndef f(x, y):\n    x, y :: i64\n    r0 :: tuple[i64, i64]\nL0:\n    r0 = (x, y)\n    return r0\ndef g():\n    r0 :: tuple[int, int]\n    r1 :: tuple[i64, i64]\nL0:\n    r0 = (2, 4)\n    r1 = (1, 2)\n    return r1\ndef h():\n    r0 :: tuple[i64, i64]\n    r1, x, r2, y :: i64\n    r3, t :: tuple[i64, i64]\n    r4, r5, r6 :: i64\nL0:\n    r0 = g()\n    r1 = r0[0]\n    x = r1\n    r2 = r0[1]\n    y = r2\n    r3 = g()\n    t = r3\n    r4 = x + y\n    r5 = t[0]\n    r6 = r4 + r5\n    return r6\n\n[case testI64MixWithTagged1_64bit]\nfrom mypy_extensions import i64\ndef f(x: i64, y: int) -> i64:\n    return x + y\n[out]\ndef f(x, y):\n    x :: i64\n    y :: int\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6, r7 :: i64\nL0:\n    r0 = y & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = y >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = y ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive y\nL3:\n    r7 = x + r3\n    return r7\n\n[case testI64MixWithTagged2_64bit]\nfrom mypy_extensions import i64\ndef f(x: int, y: i64) -> i64:\n    return x + y\n[out]\ndef f(x, y):\n    x :: int\n    y :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6, r7 :: i64\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = x >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = x ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive x\nL3:\n    r7 = r3 + y\n    return r7\n\n[case testI64MixWithTaggedInPlace1_64bit]\nfrom mypy_extensions import i64\ndef f(y: i64) -> int:\n    x = 0\n    x += y\n    return x\n[out]\ndef f(y):\n    y :: i64\n    x :: int\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6, r7 :: i64\n    r8, r9 :: bit\n    r10, r11, r12 :: int\nL0:\n    x = 0\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = x >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = x ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive x\nL3:\n    r7 = r3 + y\n    r8 = r7 <= 4611686018427387903 :: signed\n    if r8 goto L4 else goto L5 :: bool\nL4:\n    r9 = r7 >= -4611686018427387904 :: signed\n    if r9 goto L6 else goto L5 :: bool\nL5:\n    r10 = CPyTagged_FromInt64(r7)\n    r11 = r10\n    goto L7\nL6:\n    r12 = r7 << 1\n    r11 = r12\nL7:\n    x = r11\n    return x\n\n[case testI64MixWithTaggedInPlace2_64bit]\nfrom mypy_extensions import i64\ndef f(y: int) -> i64:\n    x: i64 = 0\n    x += y\n    return x\n[out]\ndef f(y):\n    y :: int\n    x :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6, r7 :: i64\nL0:\n    x = 0\n    r0 = y & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = y >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = y ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive y\nL3:\n    r7 = x + r3\n    x = r7\n    return x\n\n[case testI64MixedCompare1_64bit]\nfrom mypy_extensions import i64\ndef f(x: int, y: i64) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x :: int\n    y :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6 :: i64\n    r7 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = x >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = x ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive x\nL3:\n    r7 = r3 == y\n    return r7\n\n[case testI64MixedCompare2_64bit]\nfrom mypy_extensions import i64\ndef f(x: i64, y: int) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x :: i64\n    y :: int\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6 :: i64\n    r7 :: bit\nL0:\n    r0 = y & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = y >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = y ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive y\nL3:\n    r7 = x == r3\n    return r7\n\n[case testI64MixedCompare_32bit]\nfrom mypy_extensions import i64\ndef f(x: int, y: i64) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x :: int\n    y :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2, r3, r4 :: i64\n    r5 :: ptr\n    r6 :: c_ptr\n    r7 :: i64\n    r8 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = extend signed x: builtins.int to i64\n    r3 = r2 >> 1\n    r4 = r3\n    goto L3\nL2:\n    r5 = x ^ 1\n    r6 = r5\n    r7 = CPyLong_AsInt64(r6)\n    r4 = r7\n    keep_alive x\nL3:\n    r8 = r4 == y\n    return r8\n\n[case testI64AsBool]\nfrom mypy_extensions import i64\ndef f(x: i64) -> i64:\n    if x:\n        return 5\n    elif not x:\n        return 6\n    return 3\ndef unary_not(x: i64) -> bool:\n    return not x\n[out]\ndef f(x):\n    x :: i64\n    r0, r1 :: bit\nL0:\n    r0 = x != 0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 5\nL2:\n    r1 = x != 0\n    if r1 goto L4 else goto L3 :: bool\nL3:\n    return 6\nL4:\nL5:\n    return 3\ndef unary_not(x):\n    x :: i64\n    r0 :: bit\nL0:\n    r0 = x == 0\n    return r0\n\n[case testI64AssignMixed_64bit]\nfrom mypy_extensions import i64\ndef f(x: i64, y: int) -> i64:\n    x = y\n    return x\ndef g(x: i64, y: int) -> int:\n    y = x\n    return y\n[out]\ndef f(x, y):\n    x :: i64\n    y :: int\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6 :: i64\nL0:\n    r0 = y & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = y >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = y ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive y\nL3:\n    x = r3\n    return x\ndef g(x, y):\n    x :: i64\n    y :: int\n    r0, r1 :: bit\n    r2, r3, r4 :: int\nL0:\n    r0 = x <= 4611686018427387903 :: signed\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = x >= -4611686018427387904 :: signed\n    if r1 goto L3 else goto L2 :: bool\nL2:\n    r2 = CPyTagged_FromInt64(x)\n    r3 = r2\n    goto L4\nL3:\n    r4 = x << 1\n    r3 = r4\nL4:\n    y = r3\n    return y\n\n[case testBorrowOverI64Arithmetic]\nfrom mypy_extensions import i64\n\ndef add_simple(c: C) -> i64:\n    return c.x + c.y\n\ndef inplace_add_simple(c: C) -> None:\n    c.x += c.y\n\ndef add_borrow(d: D) -> i64:\n    return d.c.x + d.c.y\n\nclass D:\n    c: C\n\nclass C:\n    x: i64\n    y: i64\n[out]\ndef add_simple(c):\n    c :: __main__.C\n    r0, r1, r2 :: i64\nL0:\n    r0 = c.x\n    r1 = c.y\n    r2 = r0 + r1\n    return r2\ndef inplace_add_simple(c):\n    c :: __main__.C\n    r0, r1, r2 :: i64\n    r3 :: bool\nL0:\n    r0 = c.x\n    r1 = c.y\n    r2 = r0 + r1\n    c.x = r2; r3 = is_error\n    return 1\ndef add_borrow(d):\n    d :: __main__.D\n    r0 :: __main__.C\n    r1 :: i64\n    r2 :: __main__.C\n    r3, r4 :: i64\nL0:\n    r0 = borrow d.c\n    r1 = r0.x\n    r2 = borrow d.c\n    r3 = r2.y\n    r4 = r1 + r3\n    keep_alive d, d\n    return r4\n\n[case testBorrowOverI64Bitwise]\nfrom mypy_extensions import i64\n\ndef bitwise_simple(c: C) -> i64:\n    return c.x | c.y\n\ndef inplace_bitwide_simple(c: C) -> None:\n    c.x &= c.y\n\ndef bitwise_borrow(d: D) -> i64:\n    return d.c.x ^ d.c.y\n\nclass D:\n    c: C\n\nclass C:\n    x: i64\n    y: i64\n[out]\ndef bitwise_simple(c):\n    c :: __main__.C\n    r0, r1, r2 :: i64\nL0:\n    r0 = c.x\n    r1 = c.y\n    r2 = r0 | r1\n    return r2\ndef inplace_bitwide_simple(c):\n    c :: __main__.C\n    r0, r1, r2 :: i64\n    r3 :: bool\nL0:\n    r0 = c.x\n    r1 = c.y\n    r2 = r0 & r1\n    c.x = r2; r3 = is_error\n    return 1\ndef bitwise_borrow(d):\n    d :: __main__.D\n    r0 :: __main__.C\n    r1 :: i64\n    r2 :: __main__.C\n    r3, r4 :: i64\nL0:\n    r0 = borrow d.c\n    r1 = r0.x\n    r2 = borrow d.c\n    r3 = r2.y\n    r4 = r1 ^ r3\n    keep_alive d, d\n    return r4\n\n[case testBorrowOverI64ListGetItem1]\nfrom mypy_extensions import i64\n\ndef f(n: i64) -> str:\n    a = [C()]\n    return a[n].s\n\nclass C:\n    s: str\n[out]\ndef f(n):\n    n :: i64\n    r0 :: __main__.C\n    r1 :: list\n    r2 :: ptr\n    a :: list\n    r3 :: object\n    r4 :: __main__.C\n    r5 :: str\nL0:\n    r0 = C()\n    r1 = PyList_New(1)\n    r2 = list_items r1\n    buf_init_item r2, 0, r0\n    keep_alive r1\n    a = r1\n    r3 = CPyList_GetItemInt64Borrow(a, n)\n    r4 = borrow cast(__main__.C, r3)\n    r5 = r4.s\n    keep_alive a, n, r3\n    return r5\n\n[case testBorrowOverI64ListGetItem2]\nfrom typing import List\nfrom mypy_extensions import i64\n\ndef f(a: List[i64], n: i64) -> bool:\n    if a[n] == 0:\n        return True\n    return False\n[out]\ndef f(a, n):\n    a :: list\n    n :: i64\n    r0 :: object\n    r1 :: i64\n    r2 :: bit\nL0:\n    r0 = CPyList_GetItemInt64Borrow(a, n)\n    r1 = unbox(i64, r0)\n    r2 = r1 == 0\n    keep_alive a, n\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    return 0\n\n[case testCoerceShortIntToI64]\nfrom mypy_extensions import i64\nfrom typing import List\n\ndef f(a: List[i64], y: i64) -> bool:\n    if len(a) < y:\n        return True\n    return False\n\ndef g(a: List[i64], y: i64) -> bool:\n    if y < len(a):\n        return True\n    return False\n[out]\ndef f(a, y):\n    a :: list\n    y :: i64\n    r0 :: native_int\n    r1 :: short_int\n    r2 :: i64\n    r3 :: bit\nL0:\n    r0 = var_object_size a\n    r1 = r0 << 1\n    r2 = r1 >> 1\n    r3 = r2 < y :: signed\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    return 0\ndef g(a, y):\n    a :: list\n    y :: i64\n    r0 :: native_int\n    r1 :: short_int\n    r2 :: i64\n    r3 :: bit\nL0:\n    r0 = var_object_size a\n    r1 = r0 << 1\n    r2 = r1 >> 1\n    r3 = y < r2 :: signed\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    return 0\n\n[case testMultiplyListByI64_64bit]\nfrom mypy_extensions import i64\nfrom typing import List\n\ndef f(n: i64) -> List[i64]:\n    return [n] * n\n[out]\ndef f(n):\n    n :: i64\n    r0 :: list\n    r1 :: object\n    r2 :: ptr\n    r3, r4 :: bit\n    r5, r6, r7 :: int\n    r8 :: list\nL0:\n    r0 = PyList_New(1)\n    r1 = box(i64, n)\n    r2 = list_items r0\n    buf_init_item r2, 0, r1\n    keep_alive r0\n    r3 = n <= 4611686018427387903 :: signed\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = n >= -4611686018427387904 :: signed\n    if r4 goto L3 else goto L2 :: bool\nL2:\n    r5 = CPyTagged_FromInt64(n)\n    r6 = r5\n    goto L4\nL3:\n    r7 = n << 1\n    r6 = r7\nL4:\n    r8 = CPySequence_Multiply(r0, r6)\n    return r8\n\n[case testShortIntAndI64Op]\nfrom mypy_extensions import i64\nfrom typing import List\n\ndef add_i64(a: List[i64], n: i64) -> i64:\n    return len(a) + n\ndef add_i64_2(a: List[i64], n: i64) -> i64:\n    return n + len(a)\ndef eq_i64(a: List[i64], n: i64) -> bool:\n    if len(a) == n:\n        return True\n    return False\ndef lt_i64(a: List[i64], n: i64) -> bool:\n    if n < len(a):\n        return True\n    return False\n[out]\ndef add_i64(a, n):\n    a :: list\n    n :: i64\n    r0 :: native_int\n    r1 :: short_int\n    r2, r3 :: i64\nL0:\n    r0 = var_object_size a\n    r1 = r0 << 1\n    r2 = r1 >> 1\n    r3 = r2 + n\n    return r3\ndef add_i64_2(a, n):\n    a :: list\n    n :: i64\n    r0 :: native_int\n    r1 :: short_int\n    r2, r3 :: i64\nL0:\n    r0 = var_object_size a\n    r1 = r0 << 1\n    r2 = r1 >> 1\n    r3 = n + r2\n    return r3\ndef eq_i64(a, n):\n    a :: list\n    n :: i64\n    r0 :: native_int\n    r1 :: short_int\n    r2 :: i64\n    r3 :: bit\nL0:\n    r0 = var_object_size a\n    r1 = r0 << 1\n    r2 = r1 >> 1\n    r3 = r2 == n\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    return 0\ndef lt_i64(a, n):\n    a :: list\n    n :: i64\n    r0 :: native_int\n    r1 :: short_int\n    r2 :: i64\n    r3 :: bit\nL0:\n    r0 = var_object_size a\n    r1 = r0 << 1\n    r2 = r1 >> 1\n    r3 = n < r2 :: signed\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    return 0\n\n[case testOptionalI64_64bit]\nfrom typing import Optional\nfrom mypy_extensions import i64\n\ndef f(x: Optional[i64]) -> i64:\n    if x is None:\n        return 1\n    return x\n[out]\ndef f(x):\n    x :: union[i64, None]\n    r0 :: object\n    r1 :: bit\n    r2 :: i64\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    r2 = unbox(i64, x)\n    return r2\n\n[case testI64DefaultValueSingle]\nfrom mypy_extensions import i64\n\ndef f(x: i64, y: i64 = 0) -> i64:\n    return x + y\n\ndef g() -> i64:\n    return f(7) + f(8, 9)\n[out]\ndef f(x, y, __bitmap):\n    x, y :: i64\n    __bitmap, r0 :: u32\n    r1 :: bit\n    r2 :: i64\nL0:\n    r0 = __bitmap & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    y = 0\nL2:\n    r2 = x + y\n    return r2\ndef g():\n    r0, r1, r2 :: i64\nL0:\n    r0 = f(7, 0, 0)\n    r1 = f(8, 9, 1)\n    r2 = r0 + r1\n    return r2\n\n[case testI64DefaultValueWithMultipleArgs]\nfrom mypy_extensions import i64\n\ndef f(a: i64, b: i64 = 1, c: int = 2, d: i64 = 3) -> i64:\n    return 0\n\ndef g() -> i64:\n    return f(7) + f(8, 9) + f(1, 2, 3) + f(4, 5, 6, 7)\n[out]\ndef f(a, b, c, d, __bitmap):\n    a, b :: i64\n    c :: int\n    d :: i64\n    __bitmap, r0 :: u32\n    r1 :: bit\n    r2 :: u32\n    r3 :: bit\nL0:\n    r0 = __bitmap & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    b = 1\nL2:\n    if is_error(c) goto L3 else goto L4\nL3:\n    c = 4\nL4:\n    r2 = __bitmap & 2\n    r3 = r2 == 0\n    if r3 goto L5 else goto L6 :: bool\nL5:\n    d = 3\nL6:\n    return 0\ndef g():\n    r0 :: int\n    r1 :: i64\n    r2 :: int\n    r3, r4, r5, r6, r7, r8 :: i64\nL0:\n    r0 = <error> :: int\n    r1 = f(7, 0, r0, 0, 0)\n    r2 = <error> :: int\n    r3 = f(8, 9, r2, 0, 1)\n    r4 = r1 + r3\n    r5 = f(1, 2, 6, 0, 1)\n    r6 = r4 + r5\n    r7 = f(4, 5, 12, 7, 3)\n    r8 = r6 + r7\n    return r8\n\n[case testI64MethodDefaultValue]\nfrom mypy_extensions import i64\n\nclass C:\n    def m(self, x: i64 = 5) -> None:\n        pass\n\ndef f(c: C) -> None:\n    c.m()\n    c.m(6)\n[out]\ndef C.m(self, x, __bitmap):\n    self :: __main__.C\n    x :: i64\n    __bitmap, r0 :: u32\n    r1 :: bit\nL0:\n    r0 = __bitmap & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    x = 5\nL2:\n    return 1\ndef f(c):\n    c :: __main__.C\n    r0, r1 :: None\nL0:\n    r0 = c.m(0, 0)\n    r1 = c.m(6, 1)\n    return 1\n\n[case testI64ExplicitConversionFromNativeInt]\nfrom mypy_extensions import i64, i32, i16\n\ndef from_i16(x: i16) -> i64:\n    return i64(x)\n\ndef from_i32(x: i32) -> i64:\n    return i64(x)\n\ndef from_i64(x: i64) -> i64:\n    return i64(x)\n[out]\ndef from_i16(x):\n    x :: i16\n    r0 :: i64\nL0:\n    r0 = extend signed x: i16 to i64\n    return r0\ndef from_i32(x):\n    x :: i32\n    r0 :: i64\nL0:\n    r0 = extend signed x: i32 to i64\n    return r0\ndef from_i64(x):\n    x :: i64\nL0:\n    return x\n\n[case testI64ExplicitConversionFromInt_64bit]\nfrom mypy_extensions import i64\n\ndef f(x: int) -> i64:\n    return i64(x)\n[out]\ndef f(x):\n    x :: int\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6 :: i64\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = x >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = x ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive x\nL3:\n    return r3\n\n[case testI64ExplicitConversionToInt_64bit]\nfrom mypy_extensions import i64\n\ndef f(x: i64) -> int:\n    return int(x)\n[out]\ndef f(x):\n    x :: i64\n    r0, r1 :: bit\n    r2, r3, r4 :: int\nL0:\n    r0 = x <= 4611686018427387903 :: signed\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = x >= -4611686018427387904 :: signed\n    if r1 goto L3 else goto L2 :: bool\nL2:\n    r2 = CPyTagged_FromInt64(x)\n    r3 = r2\n    goto L4\nL3:\n    r4 = x << 1\n    r3 = r4\nL4:\n    return r3\n\n[case testI64ExplicitConversionFromLiteral]\nfrom mypy_extensions import i64\n\ndef f() -> None:\n    x = i64(0)\n    y = i64(11)\n    z = i64(-3)\n[out]\ndef f():\n    x, y, z :: i64\nL0:\n    x = 0\n    y = 11\n    z = -3\n    return 1\n\n[case testI64ForLoopOverRange]\nfrom mypy_extensions import i64\n\ndef f() -> None:\n    for x in range(i64(4)):\n        y = x\n[out]\ndef f():\n    r0, x :: i64\n    r1 :: bit\n    y, r2 :: i64\nL0:\n    r0 = 0\n    x = r0\nL1:\n    r1 = r0 < 4 :: signed\n    if r1 goto L2 else goto L4 :: bool\nL2:\n    y = x\nL3:\n    r2 = r0 + 1\n    r0 = r2\n    x = r2\n    goto L1\nL4:\n    return 1\n\n[case testI64ForLoopOverRange2]\nfrom mypy_extensions import i64\n\ndef f() -> None:\n    for x in range(0, i64(4)):\n        y = x\n[out]\ndef f():\n    r0, x :: i64\n    r1 :: bit\n    y, r2 :: i64\nL0:\n    r0 = 0\n    x = r0\nL1:\n    r1 = r0 < 4 :: signed\n    if r1 goto L2 else goto L4 :: bool\nL2:\n    y = x\nL3:\n    r2 = r0 + 1\n    r0 = r2\n    x = r2\n    goto L1\nL4:\n    return 1\n\n[case testI64MethodDefaultValueOverride]\nfrom mypy_extensions import i64\n\nclass C:\n    def f(self, x: i64 = 11) -> None: pass\nclass D(C):\n    def f(self, x: i64 = 12) -> None: pass\n[out]\ndef C.f(self, x, __bitmap):\n    self :: __main__.C\n    x :: i64\n    __bitmap, r0 :: u32\n    r1 :: bit\nL0:\n    r0 = __bitmap & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    x = 11\nL2:\n    return 1\ndef D.f(self, x, __bitmap):\n    self :: __main__.D\n    x :: i64\n    __bitmap, r0 :: u32\n    r1 :: bit\nL0:\n    r0 = __bitmap & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    x = 12\nL2:\n    return 1\n\n[case testI64FinalConstants]\nfrom typing import Final\nfrom mypy_extensions import i64\n\nA: Final = -1\nB: Final = -(1 + 3*2)\nC: Final = 0\nD: Final = A - B\nE: Final[i64] = 1 + 3\n\ndef f1() -> i64:\n    return A\n\ndef f2() -> i64:\n    return A + B\n\ndef f3() -> i64:\n    return C\n\ndef f4() -> i64:\n    return D\n\ndef f5() -> i64:\n    return E\n[out]\ndef f1():\nL0:\n    return -1\ndef f2():\nL0:\n    return -8\ndef f3():\nL0:\n    return 0\ndef f4():\nL0:\n    return 6\ndef f5():\nL0:\n    return 4\n\n[case testI64OperationsWithBools]\nfrom mypy_extensions import i64\n\n# TODO: Other mixed operations\n\ndef add_bool_to_int(n: i64, b: bool) -> i64:\n    return n + b\n\ndef compare_bool_to_i64(n: i64, b: bool) -> bool:\n    if n == b:\n        return b != n\n    return True\n[out]\ndef add_bool_to_int(n, b):\n    n :: i64\n    b :: bool\n    r0, r1 :: i64\nL0:\n    r0 = extend b: builtins.bool to i64\n    r1 = n + r0\n    return r1\ndef compare_bool_to_i64(n, b):\n    n :: i64\n    b :: bool\n    r0 :: i64\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\nL0:\n    r0 = extend b: builtins.bool to i64\n    r1 = n == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = extend b: builtins.bool to i64\n    r3 = r2 != n\n    return r3\nL2:\n    return 1\n\n[case testI64Cast_64bit]\nfrom typing import cast\nfrom mypy_extensions import i64\n\ndef cast_object(o: object) -> i64:\n    return cast(i64, o)\n\ndef cast_int(x: int) -> i64:\n    return cast(i64, x)\n[out]\ndef cast_object(o):\n    o :: object\n    r0 :: i64\nL0:\n    r0 = unbox(i64, o)\n    return r0\ndef cast_int(x):\n    x :: int\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6 :: i64\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = x >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = x ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive x\nL3:\n    return r3\n\n[case testI64Cast_32bit]\nfrom typing import cast\nfrom mypy_extensions import i64\n\ndef cast_int(x: int) -> i64:\n    return cast(i64, x)\n[out]\ndef cast_int(x):\n    x :: int\n    r0 :: native_int\n    r1 :: bit\n    r2, r3, r4 :: i64\n    r5 :: ptr\n    r6 :: c_ptr\n    r7 :: i64\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = extend signed x: builtins.int to i64\n    r3 = r2 >> 1\n    r4 = r3\n    goto L3\nL2:\n    r5 = x ^ 1\n    r6 = r5\n    r7 = CPyLong_AsInt64(r6)\n    r4 = r7\n    keep_alive x\nL3:\n    return r4\n\n[case testI64ExplicitConversionFromVariousTypes_64bit]\nfrom mypy_extensions import i64\n\ndef bool_to_i64(b: bool) -> i64:\n    return i64(b)\n\ndef str_to_i64(s: str) -> i64:\n    return i64(s)\n\ndef str_to_i64_with_base(s: str) -> i64:\n    return i64(s, 2)\n\nclass C:\n    def __int__(self) -> i64:\n        return 5\n\ndef instance_to_i64(c: C) -> i64:\n    return i64(c)\n\ndef float_to_i64(x: float) -> i64:\n    return i64(x)\n[out]\ndef bool_to_i64(b):\n    b :: bool\n    r0 :: i64\nL0:\n    r0 = extend b: builtins.bool to i64\n    return r0\ndef str_to_i64(s):\n    s :: str\n    r0 :: object\n    r1 :: i64\nL0:\n    r0 = CPyLong_FromStr(s)\n    r1 = unbox(i64, r0)\n    return r1\ndef str_to_i64_with_base(s):\n    s :: str\n    r0 :: object\n    r1 :: i64\nL0:\n    r0 = CPyLong_FromStrWithBase(s, 4)\n    r1 = unbox(i64, r0)\n    return r1\ndef C.__int__(self):\n    self :: __main__.C\nL0:\n    return 5\ndef instance_to_i64(c):\n    c :: __main__.C\n    r0 :: i64\nL0:\n    r0 = c.__int__()\n    return r0\ndef float_to_i64(x):\n    x :: float\n    r0 :: int\n    r1 :: native_int\n    r2 :: bit\n    r3, r4 :: i64\n    r5 :: ptr\n    r6 :: c_ptr\n    r7 :: i64\nL0:\n    r0 = CPyTagged_FromFloat(x)\n    r1 = r0 & 1\n    r2 = r1 == 0\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = r0 >> 1\n    r4 = r3\n    goto L3\nL2:\n    r5 = r0 ^ 1\n    r6 = r5\n    r7 = CPyLong_AsInt64(r6)\n    r4 = r7\n    keep_alive r0\nL3:\n    return r4\n\n[case testI64ExplicitConversionFromFloat_32bit]\nfrom mypy_extensions import i64\n\ndef float_to_i64(x: float) -> i64:\n    return i64(x)\n[out]\ndef float_to_i64(x):\n    x :: float\n    r0 :: int\n    r1 :: native_int\n    r2 :: bit\n    r3, r4, r5 :: i64\n    r6 :: ptr\n    r7 :: c_ptr\n    r8 :: i64\nL0:\n    r0 = CPyTagged_FromFloat(x)\n    r1 = r0 & 1\n    r2 = r1 == 0\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = extend signed r0: builtins.int to i64\n    r4 = r3 >> 1\n    r5 = r4\n    goto L3\nL2:\n    r6 = r0 ^ 1\n    r7 = r6\n    r8 = CPyLong_AsInt64(r7)\n    r5 = r8\n    keep_alive r0\nL3:\n    return r5\n\n[case testI64ConvertToFloat_64bit]\nfrom mypy_extensions import i64\n\ndef i64_to_float(x: i64) -> float:\n    return float(x)\n[out]\ndef i64_to_float(x):\n    x :: i64\n    r0, r1 :: bit\n    r2, r3, r4 :: int\n    r5 :: float\nL0:\n    r0 = x <= 4611686018427387903 :: signed\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = x >= -4611686018427387904 :: signed\n    if r1 goto L3 else goto L2 :: bool\nL2:\n    r2 = CPyTagged_FromInt64(x)\n    r3 = r2\n    goto L4\nL3:\n    r4 = x << 1\n    r3 = r4\nL4:\n    r5 = CPyFloat_FromTagged(r3)\n    return r5\n\n[case testI64ConvertToFloat_32bit]\nfrom mypy_extensions import i64\n\ndef i64_to_float(x: i64) -> float:\n    return float(x)\n[out]\ndef i64_to_float(x):\n    x :: i64\n    r0, r1 :: bit\n    r2, r3 :: int\n    r4 :: native_int\n    r5 :: int\n    r6 :: float\nL0:\n    r0 = x <= 1073741823 :: signed\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = x >= -1073741824 :: signed\n    if r1 goto L3 else goto L2 :: bool\nL2:\n    r2 = CPyTagged_FromInt64(x)\n    r3 = r2\n    goto L4\nL3:\n    r4 = truncate x: i64 to native_int\n    r5 = r4 << 1\n    r3 = r5\nL4:\n    r6 = CPyFloat_FromTagged(r3)\n    return r6\n\n[case testI64IsinstanceNarrowing]\nfrom typing import Union\nfrom mypy_extensions import i64\n\nclass C:\n    a: i64\n\ndef narrow1(x: Union[C, i64]) -> i64:\n    if isinstance(x, i64):\n        return x\n    return x.a\n\ndef narrow2(x: Union[C, i64]) -> i64:\n    if isinstance(x, int):\n        return x\n    return x.a\n[out]\ndef narrow1(x):\n    x :: union[__main__.C, i64]\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4 :: i64\n    r5 :: __main__.C\n    r6 :: i64\nL0:\n    r0 = load_address PyLong_Type\n    r1 = PyObject_IsInstance(x, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = unbox(i64, x)\n    return r4\nL2:\n    r5 = borrow cast(__main__.C, x)\n    r6 = r5.a\n    keep_alive x\n    return r6\ndef narrow2(x):\n    x :: union[__main__.C, i64]\n    r0 :: bit\n    r1 :: i64\n    r2 :: __main__.C\n    r3 :: i64\nL0:\n    r0 = PyLong_Check(x)\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = unbox(i64, x)\n    return r1\nL2:\n    r2 = borrow cast(__main__.C, x)\n    r3 = r2.a\n    keep_alive x\n    return r3\n\n[case testI64ConvertBetweenTuples_64bit]\nfrom __future__ import annotations\nfrom mypy_extensions import i64\n\ndef f(t: tuple[int, i64, int]) -> None:\n    tt: tuple[int, i64, i64] = t\n\ndef g(n: int) -> None:\n    t: tuple[i64, i64] = (1, n)\n[out]\ndef f(t):\n    t :: tuple[int, i64, int]\n    r0 :: int\n    r1 :: i64\n    r2 :: int\n    r3 :: native_int\n    r4 :: bit\n    r5, r6 :: i64\n    r7 :: ptr\n    r8 :: c_ptr\n    r9 :: i64\n    r10, tt :: tuple[int, i64, i64]\nL0:\n    r0 = t[0]\n    r1 = t[1]\n    r2 = t[2]\n    r3 = r2 & 1\n    r4 = r3 == 0\n    if r4 goto L1 else goto L2 :: bool\nL1:\n    r5 = r2 >> 1\n    r6 = r5\n    goto L3\nL2:\n    r7 = r2 ^ 1\n    r8 = r7\n    r9 = CPyLong_AsInt64(r8)\n    r6 = r9\n    keep_alive r2\nL3:\n    r10 = (r0, r1, r6)\n    tt = r10\n    return 1\ndef g(n):\n    n :: int\n    r0 :: tuple[int, int]\n    r1 :: int\n    r2 :: native_int\n    r3 :: bit\n    r4, r5 :: i64\n    r6 :: ptr\n    r7 :: c_ptr\n    r8 :: i64\n    r9, t :: tuple[i64, i64]\nL0:\n    r0 = (2, n)\n    r1 = r0[1]\n    r2 = r1 & 1\n    r3 = r2 == 0\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = r1 >> 1\n    r5 = r4\n    goto L3\nL2:\n    r6 = r1 ^ 1\n    r7 = r6\n    r8 = CPyLong_AsInt64(r7)\n    r5 = r8\n    keep_alive r1\nL3:\n    r9 = (1, r5)\n    t = r9\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-int.test",
    "content": "[case testIntNeq]\ndef f(x: int, y: int) -> bool:\n    return x != y\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: bit\nL0:\n    r0 = int_ne x, y\n    return r0\n\n[case testShortIntComparisons]\ndef f(x: int) -> int:\n    if x == 3:\n        return 1\n    elif x != 4:\n        return 2\n    elif 5 == x:\n        return 3\n    elif 6 != x:\n        return 4\n    elif x < 4:\n        return 5\n    return 6\n[out]\ndef f(x):\n    x :: int\n    r0, r1, r2, r3, r4 :: bit\nL0:\n    r0 = int_eq x, 6\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    r1 = int_ne x, 8\n    if r1 goto L3 else goto L4 :: bool\nL3:\n    return 4\nL4:\n    r2 = int_eq 10, x\n    if r2 goto L5 else goto L6 :: bool\nL5:\n    return 6\nL6:\n    r3 = int_ne 12, x\n    if r3 goto L7 else goto L8 :: bool\nL7:\n    return 8\nL8:\n    r4 = int_lt x, 8\n    if r4 goto L9 else goto L10 :: bool\nL9:\n    return 10\nL10:\nL11:\nL12:\nL13:\nL14:\n    return 12\n\n[case testIntMin]\ndef f(x: int, y: int) -> int:\n    return min(x, y)\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: bit\n    r1 :: int\nL0:\n    r0 = int_lt y, x\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = y\n    goto L3\nL2:\n    r1 = x\nL3:\n    return r1\n\n[case testIntFloorDivideByPowerOfTwo]\ndef divby1(x: int) -> int:\n    return x // 1\ndef divby2(x: int) -> int:\n    return x // 2\ndef divby3(x: int) -> int:\n    return x // 3\ndef divby4(x: int) -> int:\n    return x // 4\ndef divby8(x: int) -> int:\n    return x // 8\n[out]\ndef divby1(x):\n    x, r0 :: int\nL0:\n    r0 = CPyTagged_FloorDivide(x, 2)\n    return r0\ndef divby2(x):\n    x, r0 :: int\nL0:\n    r0 = CPyTagged_Rshift(x, 2)\n    return r0\ndef divby3(x):\n    x, r0 :: int\nL0:\n    r0 = CPyTagged_FloorDivide(x, 6)\n    return r0\ndef divby4(x):\n    x, r0 :: int\nL0:\n    r0 = CPyTagged_Rshift(x, 4)\n    return r0\ndef divby8(x):\n    x, r0 :: int\nL0:\n    r0 = CPyTagged_Rshift(x, 6)\n    return r0\n\n[case testFinalConstantFolding]\nfrom typing import Final\n\nX: Final = -1\nY: Final = -(1 + 3*2)\nZ: Final = Y + 1\n\nclass C:\n    A: Final = 1\n    B: Final = -1\n\ndef f1() -> int:\n    return X\n\ndef f2() -> int:\n    return X + Y\n\ndef f3() -> int:\n    return Z\n\ndef f4() -> int:\n    return C.A\n\ndef f5() -> int:\n    return C.B\n[out]\ndef C.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.C\nL0:\n    __mypyc_self__.A = 2\n    __mypyc_self__.B = -2\n    return 1\ndef f1():\nL0:\n    return -2\ndef f2():\nL0:\n    return -16\ndef f3():\nL0:\n    return -12\ndef f4():\nL0:\n    return 2\ndef f5():\nL0:\n    return -2\n\n[case testConvertIntegralToInt]\ndef bool_to_int(b: bool) -> int:\n    return int(b)\n\ndef int_to_int(n: int) -> int:\n    return int(n)\n[out]\ndef bool_to_int(b):\n    b, r0 :: bool\n    r1 :: int\nL0:\n    r0 = b << 1\n    r1 = extend r0: builtins.bool to builtins.int\n    return r1\ndef int_to_int(n):\n    n :: int\nL0:\n    return n\n\n[case testIntUnaryOps]\ndef unary_minus(n: int) -> int:\n    x = -n\n    return x\ndef unary_plus(n: int) -> int:\n    x = +n\n    return x\ndef unary_invert(n: int) -> int:\n    x = ~n\n    return x\n[out]\ndef unary_minus(n):\n    n, r0, x :: int\nL0:\n    r0 = CPyTagged_Negate(n)\n    x = r0\n    return x\ndef unary_plus(n):\n    n, x :: int\nL0:\n    x = n\n    return x\ndef unary_invert(n):\n    n, r0, x :: int\nL0:\n    r0 = CPyTagged_Invert(n)\n    x = r0\n    return x\n\n[case testIntToBytes]\ndef f(x: int) -> bytes:\n    return x.to_bytes(2, \"big\")\ndef g(x: int) -> bytes:\n    return x.to_bytes(4, \"little\", signed=True)\ndef h(x: int, byteorder: str) -> bytes:\n    return x.to_bytes(8, byteorder)\n\n[out]\ndef f(x):\n    x :: int\n    r0 :: bytes\nL0:\n    r0 = CPyTagged_ToBigEndianBytes(x, 2, 0)\n    return r0\ndef g(x):\n    x :: int\n    r0 :: bytes\nL0:\n    r0 = CPyTagged_ToLittleEndianBytes(x, 4, 1)\n    return r0\ndef h(x, byteorder):\n    x :: int\n    byteorder :: str\n    r0 :: bytes\nL0:\n    r0 = CPyTagged_ToBytes(x, 8, byteorder, 0)\n    return r0\n\n[case testIntBitLength]\ndef f(x: int) -> int:\n    return x.bit_length()\n[out]\ndef f(x):\n    x, r0 :: int\nL0:\n    r0 = CPyTagged_BitLength(x)\n    return r0\n"
  },
  {
    "path": "mypyc/test-data/irbuild-isinstance.test",
    "content": "[case testIsinstanceInt]\ndef is_int(value: object) -> bool:\n    return isinstance(value, int)\n\n[out]\ndef is_int(value):\n    value :: object\n    r0 :: bit\nL0:\n    r0 = PyLong_Check(value)\n    return r0\n\n[case testIsinstanceNotBool1]\ndef is_not_bool(value: object) -> bool:\n    return not isinstance(value, bool)\n\n[out]\ndef is_not_bool(value):\n    value :: object\n    r0, r1 :: bit\nL0:\n    r0 = PyBool_Check(value)\n    r1 = r0 ^ 1\n    return r1\n\n[case testIsinstanceIntAndNotBool]\n# This test is to ensure that 'value' doesn't get coerced to int when we are\n# checking if it's a bool, since an int can never be an instance of a bool\ndef is_not_bool_and_is_int(value: object) -> bool:\n    return isinstance(value, int) and not isinstance(value, bool)\n\n[out]\ndef is_not_bool_and_is_int(value):\n    value :: object\n    r0 :: bit\n    r1 :: bool\n    r2, r3 :: bit\nL0:\n    r0 = PyLong_Check(value)\n    if r0 goto L2 else goto L1 :: bool\nL1:\n    r1 = r0\n    goto L3\nL2:\n    r2 = PyBool_Check(value)\n    r3 = r2 ^ 1\n    r1 = r3\nL3:\n    return r1\n\n[case testBorrowSpecialCaseWithIsinstance]\nclass C:\n    s: str\n\ndef g() -> object:\n    pass\n\ndef f() -> None:\n    x = g()\n    if isinstance(x, C):\n        x.s\n[out]\ndef g():\n    r0 :: object\nL0:\n    r0 = box(None, 1)\n    return r0\ndef f():\n    r0, x, r1 :: object\n    r2 :: ptr\n    r3 :: object\n    r4 :: bit\n    r5 :: __main__.C\n    r6 :: str\nL0:\n    r0 = g()\n    x = r0\n    r1 = __main__.C :: type\n    r2 = get_element_ptr x ob_type :: PyObject\n    r3 = borrow load_mem r2 :: builtins.object*\n    keep_alive x\n    r4 = r3 == r1\n    if r4 goto L1 else goto L2 :: bool\nL1:\n    r5 = borrow cast(__main__.C, x)\n    r6 = r5.s\n    keep_alive x\nL2:\n    return 1\n\n[case testBytes]\nfrom typing import Any\n\ndef is_bytes(x: Any) -> bool:\n    return isinstance(x, bytes)\n\ndef is_bytearray(x: Any) -> bool:\n    return isinstance(x, bytearray)\n\n[out]\ndef is_bytes(x):\n    x :: object\n    r0 :: bit\nL0:\n    r0 = PyBytes_Check(x)\n    return r0\ndef is_bytearray(x):\n    x :: object\n    r0 :: bit\nL0:\n    r0 = PyByteArray_Check(x)\n    return r0\n\n[case testDict]\nfrom typing import Any\n\ndef is_dict(x: Any) -> bool:\n    return isinstance(x, dict)\n\n[out]\ndef is_dict(x):\n    x :: object\n    r0 :: bit\nL0:\n    r0 = PyDict_Check(x)\n    return r0\n\n[case testFloat]\nfrom typing import Any\n\ndef is_float(x: Any) -> bool:\n    return isinstance(x, float)\n\n[out]\ndef is_float(x):\n    x :: object\n    r0 :: bit\nL0:\n    r0 = PyFloat_Check(x)\n    return r0\n\n[case testSet]\nfrom typing import Any\n\ndef is_set(x: Any) -> bool:\n    return isinstance(x, set)\n\ndef is_frozenset(x: Any) -> bool:\n    return isinstance(x, frozenset)\n\n[out]\ndef is_set(x):\n    x :: object\n    r0 :: bit\nL0:\n    r0 = PySet_Check(x)\n    return r0\ndef is_frozenset(x):\n    x :: object\n    r0 :: bit\nL0:\n    r0 = PyFrozenSet_Check(x)\n    return r0\n\n[case testStr]\nfrom typing import Any\n\ndef is_str(x: Any) -> bool:\n    return isinstance(x, str)\n\n[out]\ndef is_str(x):\n    x :: object\n    r0 :: bit\nL0:\n    r0 = PyUnicode_Check(x)\n    return r0\n\n[case testTuple]\nfrom typing import Any\n\ndef is_tuple(x: Any) -> bool:\n    return isinstance(x, tuple)\n\n[out]\ndef is_tuple(x):\n    x :: object\n    r0 :: bit\nL0:\n    r0 = PyTuple_Check(x)\n    return r0\n\n[case testTupleOfPrimitives]\nfrom typing import Any\n\ndef is_instance(x: Any) -> bool:\n    return isinstance(x, (str, int, bytes))\n\n[out]\ndef is_instance(x):\n    x :: object\n    r0, r1, r2 :: bit\n    r3 :: bool\nL0:\n    r0 = PyUnicode_Check(x)\n    if r0 goto L3 else goto L1 :: bool\nL1:\n    r1 = PyLong_Check(x)\n    if r1 goto L3 else goto L2 :: bool\nL2:\n    r2 = PyBytes_Check(x)\n    if r2 goto L3 else goto L4 :: bool\nL3:\n    r3 = 1\n    goto L5\nL4:\n    r3 = 0\nL5:\n    return r3\n"
  },
  {
    "path": "mypyc/test-data/irbuild-librt-strings.test",
    "content": "[case testLibrtStrings_experimental_64bit]\nfrom librt.strings import BytesWriter\nfrom mypy_extensions import u8, i64\n\ndef bytes_writer_basics() -> bytes:\n    b = BytesWriter()\n    b.append(1)\n    b.write(b'foo')\n    n = 2\n    b.truncate(n)\n    return b.getvalue()\ndef bytes_writer_len(b: BytesWriter) -> i64:\n    return len(b)\ndef bytes_writer_get_item(b: BytesWriter, i: i64) -> u8:\n    return b[i]\ndef bytes_writer_set_item(b: BytesWriter, i: i64, x: u8) -> None:\n    b[i] = x\n[out]\ndef bytes_writer_basics():\n    r0, b :: librt.strings.BytesWriter\n    r1 :: None\n    r2 :: bytes\n    r3 :: None\n    n :: int\n    r4 :: native_int\n    r5 :: bit\n    r6, r7 :: i64\n    r8 :: ptr\n    r9 :: c_ptr\n    r10 :: i64\n    r11 :: None\n    r12 :: bytes\nL0:\n    r0 = LibRTStrings_BytesWriter_internal()\n    b = r0\n    r1 = CPyBytesWriter_Append(b, 1)\n    r2 = b'foo'\n    r3 = CPyBytesWriter_Write(b, r2)\n    n = 4\n    r4 = n & 1\n    r5 = r4 == 0\n    if r5 goto L1 else goto L2 :: bool\nL1:\n    r6 = n >> 1\n    r7 = r6\n    goto L3\nL2:\n    r8 = n ^ 1\n    r9 = r8\n    r10 = CPyLong_AsInt64(r9)\n    r7 = r10\n    keep_alive n\nL3:\n    r11 = LibRTStrings_BytesWriter_truncate_internal(b, r7)\n    r12 = LibRTStrings_BytesWriter_getvalue_internal(b)\n    return r12\ndef bytes_writer_len(b):\n    b :: librt.strings.BytesWriter\n    r0 :: short_int\n    r1 :: i64\nL0:\n    r0 = CPyBytesWriter_Len(b)\n    r1 = r0 >> 1\n    return r1\ndef bytes_writer_get_item(b, i):\n    b :: librt.strings.BytesWriter\n    i, r0 :: i64\n    r1, r2 :: bool\n    r3 :: u8\nL0:\n    r0 = CPyBytesWriter_AdjustIndex(b, i)\n    r1 = CPyBytesWriter_RangeCheck(b, r0)\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = raise IndexError('index out of range')\n    unreachable\nL2:\n    r3 = CPyBytesWriter_GetItem(b, r0)\n    return r3\ndef bytes_writer_set_item(b, i, x):\n    b :: librt.strings.BytesWriter\n    i :: i64\n    x :: u8\n    r0 :: i64\n    r1, r2 :: bool\nL0:\n    r0 = CPyBytesWriter_AdjustIndex(b, i)\n    r1 = CPyBytesWriter_RangeCheck(b, r0)\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = raise IndexError('index out of range')\n    unreachable\nL2:\n    CPyBytesWriter_SetItem(b, r0, x)\n    return 1\n\n[case testLibrtStrings_write_i16_le_experimental_64bit]\nfrom librt.strings import BytesWriter, write_i16_le\nfrom mypy_extensions import i16\n\ndef test_write_i16_le(b: BytesWriter, n: i16) -> None:\n    write_i16_le(b, n)\ndef test_write_i16_le_literal(b: BytesWriter) -> None:\n    write_i16_le(b, 1234)\n[out]\ndef test_write_i16_le(b, n):\n    b :: librt.strings.BytesWriter\n    n :: i16\n    r0 :: None\nL0:\n    r0 = CPyBytesWriter_WriteI16LE(b, n)\n    return 1\ndef test_write_i16_le_literal(b):\n    b :: librt.strings.BytesWriter\n    r0 :: None\nL0:\n    r0 = CPyBytesWriter_WriteI16LE(b, 1234)\n    return 1\n\n[case testLibrtStrings_read_i16_le_experimental_64bit]\nfrom librt.strings import read_i16_le\nfrom mypy_extensions import i16, i64\n\ndef test_read_i16_le(b: bytes, i: i64) -> i16:\n    return read_i16_le(b, i)\ndef test_read_i16_le_literal(b: bytes) -> i16:\n    return read_i16_le(b, 0)\n[out]\ndef test_read_i16_le(b, i):\n    b :: bytes\n    i :: i64\n    r0 :: i16\nL0:\n    r0 = CPyBytes_ReadI16LE(b, i)\n    return r0\ndef test_read_i16_le_literal(b):\n    b :: bytes\n    r0 :: i16\nL0:\n    r0 = CPyBytes_ReadI16LE(b, 0)\n    return r0\n\n[case testLibrtStrings_i32_le_experimental_64bit]\nfrom librt.strings import BytesWriter, write_i32_le, read_i32_le\nfrom mypy_extensions import i32, i64\n\ndef test_write_i32_le(b: BytesWriter, n: i32) -> None:\n    write_i32_le(b, n)\ndef test_write_i32_le_literal(b: BytesWriter) -> None:\n    write_i32_le(b, 12345678)\ndef test_read_i32_le(b: bytes, i: i64) -> i32:\n    return read_i32_le(b, i)\ndef test_read_i32_le_literal(b: bytes) -> i32:\n    return read_i32_le(b, 0)\n[out]\ndef test_write_i32_le(b, n):\n    b :: librt.strings.BytesWriter\n    n :: i32\n    r0 :: None\nL0:\n    r0 = CPyBytesWriter_WriteI32LE(b, n)\n    return 1\ndef test_write_i32_le_literal(b):\n    b :: librt.strings.BytesWriter\n    r0 :: None\nL0:\n    r0 = CPyBytesWriter_WriteI32LE(b, 12345678)\n    return 1\ndef test_read_i32_le(b, i):\n    b :: bytes\n    i :: i64\n    r0 :: i32\nL0:\n    r0 = CPyBytes_ReadI32LE(b, i)\n    return r0\ndef test_read_i32_le_literal(b):\n    b :: bytes\n    r0 :: i32\nL0:\n    r0 = CPyBytes_ReadI32LE(b, 0)\n    return r0\n\n[case testLibrtStrings_i64_le_experimental_64bit]\nfrom librt.strings import BytesWriter, write_i64_le, read_i64_le\nfrom mypy_extensions import i64\n\ndef test_write_i64_le(b: BytesWriter, n: i64) -> None:\n    write_i64_le(b, n)\ndef test_write_i64_le_literal(b: BytesWriter) -> None:\n    write_i64_le(b, 1234567890123456789)\ndef test_read_i64_le(b: bytes, i: i64) -> i64:\n    return read_i64_le(b, i)\ndef test_read_i64_le_literal(b: bytes) -> i64:\n    return read_i64_le(b, 0)\n[out]\ndef test_write_i64_le(b, n):\n    b :: librt.strings.BytesWriter\n    n :: i64\n    r0 :: None\nL0:\n    r0 = CPyBytesWriter_WriteI64LE(b, n)\n    return 1\ndef test_write_i64_le_literal(b):\n    b :: librt.strings.BytesWriter\n    r0 :: None\nL0:\n    r0 = CPyBytesWriter_WriteI64LE(b, 1234567890123456789)\n    return 1\ndef test_read_i64_le(b, i):\n    b :: bytes\n    i, r0 :: i64\nL0:\n    r0 = CPyBytes_ReadI64LE(b, i)\n    return r0\ndef test_read_i64_le_literal(b):\n    b :: bytes\n    r0 :: i64\nL0:\n    r0 = CPyBytes_ReadI64LE(b, 0)\n    return r0\n\n[case testLibrtStrings_StringWriter_experimental_64bit]\nfrom librt.strings import StringWriter\nfrom mypy_extensions import i32, i64\n\ndef string_writer_basics() -> str:\n    s = StringWriter()\n    s.append(65)\n    s.write('foo')\n    return s.getvalue()\ndef string_writer_len(s: StringWriter) -> i64:\n    return len(s)\ndef string_writer_get_item(s: StringWriter, i: i64) -> i32:\n    return s[i]\n[out]\ndef string_writer_basics():\n    r0, s :: librt.strings.StringWriter\n    r1 :: None\n    r2 :: str\n    r3 :: None\n    r4 :: str\nL0:\n    r0 = LibRTStrings_StringWriter_internal()\n    s = r0\n    r1 = CPyStringWriter_Append(s, 65)\n    r2 = 'foo'\n    r3 = LibRTStrings_StringWriter_write_internal(s, r2)\n    r4 = LibRTStrings_StringWriter_getvalue_internal(s)\n    return r4\ndef string_writer_len(s):\n    s :: librt.strings.StringWriter\n    r0 :: short_int\n    r1 :: i64\nL0:\n    r0 = CPyStringWriter_Len(s)\n    r1 = r0 >> 1\n    return r1\ndef string_writer_get_item(s, i):\n    s :: librt.strings.StringWriter\n    i, r0 :: i64\n    r1, r2 :: bool\n    r3 :: i32\nL0:\n    r0 = CPyStringWriter_AdjustIndex(s, i)\n    r1 = CPyStringWriter_RangeCheck(s, r0)\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = raise IndexError('index out of range')\n    unreachable\nL2:\n    r3 = CPyStringWriter_GetItem(s, r0)\n    return r3\n"
  },
  {
    "path": "mypyc/test-data/irbuild-lists.test",
    "content": "[case testListGet]\nfrom typing import List\ndef f(x: List[int]) -> int:\n    return x[0]\n[out]\ndef f(x):\n    x :: list\n    r0 :: object\n    r1 :: int\nL0:\n    r0 = CPyList_GetItemShort(x, 0)\n    r1 = unbox(int, r0)\n    return r1\n\n[case testListOfListGet]\nfrom typing import List\ndef f(x: List[List[int]]) -> List[int]:\n    return x[0]\n[out]\ndef f(x):\n    x :: list\n    r0 :: object\n    r1 :: list\nL0:\n    r0 = CPyList_GetItemShort(x, 0)\n    r1 = cast(list, r0)\n    return r1\n\n[case testListOfListGet2]\nfrom typing import List\ndef f(x: List[List[int]]) -> int:\n    return x[0][1]\n[out]\ndef f(x):\n    x :: list\n    r0 :: object\n    r1 :: list\n    r2 :: object\n    r3 :: int\nL0:\n    r0 = CPyList_GetItemShortBorrow(x, 0)\n    r1 = borrow cast(list, r0)\n    r2 = CPyList_GetItemShort(r1, 2)\n    r3 = unbox(int, r2)\n    keep_alive x, r0\n    return r3\n\n[case testListSet]\nfrom typing import List\ndef f(x: List[int]) -> None:\n    x[0] = 1\n[out]\ndef f(x):\n    x :: list\n    r0 :: object\n    r1 :: bit\nL0:\n    r0 = object 1\n    r1 = CPyList_SetItem(x, 0, r0)\n    return 1\n\n[case testNewListEmpty]\nfrom typing import List\ndef f() -> None:\n    x = []  # type: List[int]\n[out]\ndef f():\n    r0, x :: list\nL0:\n    r0 = PyList_New(0)\n    x = r0\n    return 1\n\n[case testNewListEmptyViaFunc]\nfrom typing import List\ndef f() -> None:\n    x: List[int] = list()\n\n[out]\ndef f():\n    r0, x :: list\nL0:\n    r0 = PyList_New(0)\n    x = r0\n    return 1\n\n[case testNewListEmptyViaAlias]\nfrom typing import List\n\nListAlias = list\n\ndef f() -> None:\n    x: List[int] = ListAlias()\n\n[out]\ndef f():\n    r0, x :: list\nL0:\n    r0 = PyList_New(0)\n    x = r0\n    return 1\n\n[case testNewListTwoItems]\nfrom typing import List\ndef f() -> None:\n    x: List[int] = [1, 2]\n[out]\ndef f():\n    r0 :: list\n    r1, r2 :: object\n    r3 :: ptr\n    x :: list\nL0:\n    r0 = PyList_New(2)\n    r1 = object 1\n    r2 = object 2\n    r3 = list_items r0\n    buf_init_item r3, 0, r1\n    buf_init_item r3, 1, r2\n    keep_alive r0\n    x = r0\n    return 1\n\n[case testNewListTenItems]\nfrom typing import List\ndef f() -> None:\n    x: List[str] = ['a', 'b', 'c', 'd', 'e',\n                    'f', 'g', 'h', 'i', 'j']\n[out]\ndef f():\n    r0, r1, r2, r3, r4, r5, r6, r7, r8, r9 :: str\n    r10, x :: list\nL0:\n    r0 = 'a'\n    r1 = 'b'\n    r2 = 'c'\n    r3 = 'd'\n    r4 = 'e'\n    r5 = 'f'\n    r6 = 'g'\n    r7 = 'h'\n    r8 = 'i'\n    r9 = 'j'\n    r10 = CPyList_Build(10, r0, r1, r2, r3, r4, r5, r6, r7, r8, r9)\n    x = r10\n    return 1\n\n[case testListAdd]\nfrom typing import List\ndef f(a: List[int], b: List[int]) -> None:\n    c = a + b\n[out]\ndef f(a, b):\n    a, b, r0, c :: list\nL0:\n    r0 = PySequence_Concat(a, b)\n    c = r0\n    return 1\n\n[case testListIAdd]\nfrom typing import List, Any\ndef f(a: List[int], b: Any) -> None:\n    a += b\n[out]\ndef f(a, b):\n    a :: list\n    b :: object\n    r0 :: list\nL0:\n    r0 = PySequence_InPlaceConcat(a, b)\n    a = r0\n    return 1\n\n[case testListMultiply]\nfrom typing import List\ndef f(a: List[int]) -> None:\n    b = a * 2\n    b = 3 * [4]\n[out]\ndef f(a):\n    a, r0, b, r1 :: list\n    r2 :: object\n    r3 :: ptr\n    r4 :: list\nL0:\n    r0 = CPySequence_Multiply(a, 4)\n    b = r0\n    r1 = PyList_New(1)\n    r2 = object 4\n    r3 = list_items r1\n    buf_init_item r3, 0, r2\n    keep_alive r1\n    r4 = CPySequence_RMultiply(6, r1)\n    b = r4\n    return 1\n\n[case testListIMultiply]\nfrom typing import List\ndef f(a: List[int]) -> None:\n    a *= 2\n[out]\ndef f(a):\n    a, r0 :: list\nL0:\n    r0 = CPySequence_InPlaceMultiply(a, 4)\n    a = r0\n    return 1\n\n[case testListLen]\nfrom typing import List\ndef f(a: List[int]) -> int:\n    return len(a)\n[out]\ndef f(a):\n    a :: list\n    r0 :: native_int\n    r1 :: short_int\nL0:\n    r0 = var_object_size a\n    r1 = r0 << 1\n    return r1\n\n[case testListClear]\nfrom typing import List\ndef f(l: List[int]) -> None:\n    return l.clear()\n[out]\ndef f(l):\n    l :: list\n    r0 :: bit\nL0:\n    r0 = CPyList_Clear(l)\n    return 1\n\n[case testListCopy]\nfrom typing import List\nfrom typing import Any\ndef f(a: List[Any]) -> List[Any]:\n    return a.copy()\n[out]\ndef f(a):\n    a, r0 :: list\nL0:\n    r0 = CPyList_Copy(a)\n    return r0\n\n[case testListAppend]\nfrom typing import List\ndef f(a: List[int], x: int) -> None:\n    a.append(x)\n[out]\ndef f(a, x):\n    a :: list\n    x :: int\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\nL0:\n    r0 = box(int, x)\n    r1 = PyList_Append(a, r0)\n    r2 = r1 >= 0 :: signed\n    return 1\n\n[case testIndexLvalue]\nfrom typing import List\ndef increment(l: List[int]) -> List[int]:\n    for i in range(len(l)):\n        l[i] += 1\n    return l\n[out]\ndef increment(l):\n    l :: list\n    r0 :: native_int\n    r1, r2 :: short_int\n    i :: int\n    r3 :: bit\n    r4, r5, r6 :: object\n    r7 :: bit\n    r8 :: short_int\nL0:\n    r0 = var_object_size l\n    r1 = r0 << 1\n    r2 = 0\n    i = r2\nL1:\n    r3 = int_lt r2, r1\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = CPyList_GetItem(l, i)\n    r5 = object 1\n    r6 = PyNumber_InPlaceAdd(r4, r5)\n    r7 = CPyList_SetItem(l, i, r6)\nL3:\n    r8 = r2 + 2\n    r2 = r8\n    i = r8\n    goto L1\nL4:\n    return l\n\n[case testListDisplay]\nfrom typing import List\ndef f(x: List[int], y: List[int]) -> List[int]:\n    return [1, 2, *x, *y, 3]\n[out]\ndef f(x, y):\n    x, y, r0 :: list\n    r1, r2 :: object\n    r3 :: ptr\n    r4, r5, r6 :: object\n    r7 :: i32\n    r8 :: bit\nL0:\n    r0 = PyList_New(2)\n    r1 = object 1\n    r2 = object 2\n    r3 = list_items r0\n    buf_init_item r3, 0, r1\n    buf_init_item r3, 1, r2\n    keep_alive r0\n    r4 = CPyList_Extend(r0, x)\n    r5 = CPyList_Extend(r0, y)\n    r6 = object 3\n    r7 = PyList_Append(r0, r6)\n    r8 = r7 >= 0 :: signed\n    return r0\n\n[case testListIn]\nfrom typing import List\ndef f(x: List[int], y: int) -> bool:\n    return y in x\n[out]\ndef f(x, y):\n    x :: list\n    y :: int\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\nL0:\n    r0 = box(int, y)\n    r1 = PySequence_Contains(x, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    return r3\n\n[case testListInsert]\nfrom typing import List\ndef f(x: List[int], y: int) -> None:\n    x.insert(0, y)\n[out]\ndef f(x, y):\n    x :: list\n    y :: int\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\nL0:\n    r0 = box(int, y)\n    r1 = CPyList_Insert(x, 0, r0)\n    r2 = r1 >= 0 :: signed\n    return 1\n\n[case testListBuiltFromGenerator]\nfrom typing import List\ndef f(source: List[int]) -> None:\n    a = list(x + 1 for x in source)\n    b = [x + 1 for x in source]\n[out]\ndef f(source):\n    source :: list\n    r0 :: native_int\n    r1 :: list\n    r2, r3 :: native_int\n    r4 :: bit\n    r5 :: object\n    r6, x, r7 :: int\n    r8 :: object\n    r9 :: native_int\n    a :: list\n    r10 :: native_int\n    r11 :: list\n    r12, r13 :: native_int\n    r14 :: bit\n    r15 :: object\n    r16, x_2, r17 :: int\n    r18 :: object\n    r19 :: native_int\n    b :: list\nL0:\n    r0 = var_object_size source\n    r1 = PyList_New(r0)\n    r2 = 0\nL1:\n    r3 = var_object_size source\n    r4 = r2 < r3 :: signed\n    if r4 goto L2 else goto L4 :: bool\nL2:\n    r5 = list_get_item_unsafe source, r2\n    r6 = unbox(int, r5)\n    x = r6\n    r7 = CPyTagged_Add(x, 2)\n    r8 = box(int, r7)\n    CPyList_SetItemUnsafe(r1, r2, r8)\nL3:\n    r9 = r2 + 1\n    r2 = r9\n    goto L1\nL4:\n    a = r1\n    r10 = var_object_size source\n    r11 = PyList_New(r10)\n    r12 = 0\nL5:\n    r13 = var_object_size source\n    r14 = r12 < r13 :: signed\n    if r14 goto L6 else goto L8 :: bool\nL6:\n    r15 = list_get_item_unsafe source, r12\n    r16 = unbox(int, r15)\n    x_2 = r16\n    r17 = CPyTagged_Add(x_2, 2)\n    r18 = box(int, r17)\n    CPyList_SetItemUnsafe(r11, r12, r18)\nL7:\n    r19 = r12 + 1\n    r12 = r19\n    goto L5\nL8:\n    b = r11\n    return 1\n\n[case testGeneratorNext]\nfrom typing import List, Optional\n\ndef test(x: List[int]) -> None:\n    res = next((i for i in x), None)\n[out]\ndef test(x):\n    x :: list\n    r0, r1 :: native_int\n    r2 :: bit\n    r3 :: object\n    r4, i :: int\n    r5 :: object\n    r6 :: union[int, None]\n    r7 :: native_int\n    r8 :: object\n    res :: union[int, None]\nL0:\n    r0 = 0\nL1:\n    r1 = var_object_size x\n    r2 = r0 < r1 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = list_get_item_unsafe x, r0\n    r4 = unbox(int, r3)\n    i = r4\n    r5 = box(int, i)\n    r6 = r5\n    goto L5\nL3:\n    r7 = r0 + 1\n    r0 = r7\n    goto L1\nL4:\n    r8 = box(None, 1)\n    r6 = r8\nL5:\n    res = r6\n    return 1\n\n[case testSimplifyListUnion]\nfrom typing import List, Union, Optional\n\ndef narrow(a: Union[List[str], List[bytes], int]) -> int:\n    if isinstance(a, list):\n        return len(a)\n    return a\ndef loop(a: Union[List[str], List[bytes]]) -> None:\n    for x in a:\n         pass\ndef nested_union(a: Union[List[str], List[Optional[str]]]) -> None:\n    for x in a:\n        pass\n[out]\ndef narrow(a):\n    a :: union[list, int]\n    r0 :: bit\n    r1 :: list\n    r2 :: native_int\n    r3 :: short_int\n    r4 :: int\nL0:\n    r0 = PyList_Check(a)\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = borrow cast(list, a)\n    r2 = var_object_size r1\n    r3 = r2 << 1\n    keep_alive a\n    return r3\nL2:\n    r4 = unbox(int, a)\n    return r4\ndef loop(a):\n    a :: list\n    r0, r1 :: native_int\n    r2 :: bit\n    r3 :: object\n    r4, x :: union[str, bytes]\n    r5 :: native_int\nL0:\n    r0 = 0\nL1:\n    r1 = var_object_size a\n    r2 = r0 < r1 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = list_get_item_unsafe a, r0\n    r4 = cast(union[str, bytes], r3)\n    x = r4\nL3:\n    r5 = r0 + 1\n    r0 = r5\n    goto L1\nL4:\n    return 1\ndef nested_union(a):\n    a :: list\n    r0, r1 :: native_int\n    r2 :: bit\n    r3 :: object\n    r4, x :: union[str, None]\n    r5 :: native_int\nL0:\n    r0 = 0\nL1:\n    r1 = var_object_size a\n    r2 = r0 < r1 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = list_get_item_unsafe a, r0\n    r4 = cast(union[str, None], r3)\n    x = r4\nL3:\n    r5 = r0 + 1\n    r0 = r5\n    goto L1\nL4:\n    return 1\n\n[case testSorted]\nfrom typing import List, Any\ndef list_sort(a: List[int]) -> None:\n    a.sort()\ndef sort_iterable(a: Any) -> None:\n    sorted(a)\n[out]\ndef list_sort(a):\n    a :: list\n    r0 :: i32\n    r1 :: bit\nL0:\n    r0 = PyList_Sort(a)\n    r1 = r0 >= 0 :: signed\n    return 1\ndef sort_iterable(a):\n    a :: object\n    r0 :: list\nL0:\n    r0 = CPySequence_Sort(a)\n    return 1\n\n[case testListBuiltFromStr]\ndef f2(val: str) -> str:\n    return val + \"f2\"\n\ndef test() -> None:\n    source = \"abc\"\n    a = [f2(x) for x in source]\n[out]\ndef f2(val):\n    val, r0, r1 :: str\nL0:\n    r0 = 'f2'\n    r1 = PyUnicode_Concat(val, r0)\n    return r1\ndef test():\n    r0, source :: str\n    r1 :: native_int\n    r2 :: bit\n    r3 :: list\n    r4 :: native_int\n    r5 :: bit\n    r6, x, r7 :: str\n    r8 :: native_int\n    a :: list\nL0:\n    r0 = 'abc'\n    source = r0\n    r1 = CPyStr_Size_size_t(source)\n    r2 = r1 >= 0 :: signed\n    r3 = PyList_New(r1)\n    r4 = 0\nL1:\n    r5 = r4 < r1 :: signed\n    if r5 goto L2 else goto L4 :: bool\nL2:\n    r6 = CPyStr_GetItemUnsafe(source, r4)\n    x = r6\n    r7 = f2(x)\n    CPyList_SetItemUnsafe(r3, r4, r7)\nL3:\n    r8 = r4 + 1\n    r4 = r8\n    goto L1\nL4:\n    a = r3\n    return 1\n\n[case testListBuiltFromStrExpr]\ndef f2(val: str) -> str:\n    return val + \"f2\"\n\ndef test() -> None:\n    a = [f2(x) for x in \"abc\"]\n[out]\ndef f2(val):\n    val, r0, r1 :: str\nL0:\n    r0 = 'f2'\n    r1 = PyUnicode_Concat(val, r0)\n    return r1\ndef test():\n    r0 :: str\n    r1 :: list\n    r2 :: native_int\n    r3 :: bit\n    r4, x, r5 :: str\n    r6 :: native_int\n    a :: list\nL0:\n    r0 = 'abc'\n    r1 = PyList_New(3)\n    r2 = 0\n    goto L2\nL1:\n    r3 = r2 < 3 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = CPyStr_GetItemUnsafe(r0, r2)\n    x = r4\n    r5 = f2(x)\n    CPyList_SetItemUnsafe(r1, r2, r5)\nL3:\n    r6 = r2 + 1\n    r2 = r6\n    goto L1\nL4:\n    a = r1\n    return 1\n\n[case testListBuiltFromFinalStr]\nfrom typing import Final\n\nsource: Final = \"abc\"\n\ndef f2(val: str) -> str:\n    return val + \"f2\"\n\ndef test() -> None:\n    a = [f2(x) for x in source]\n[out]\ndef f2(val):\n    val, r0, r1 :: str\nL0:\n    r0 = 'f2'\n    r1 = PyUnicode_Concat(val, r0)\n    return r1\ndef test():\n    r0 :: str\n    r1 :: list\n    r2 :: native_int\n    r3 :: bit\n    r4, x, r5 :: str\n    r6 :: native_int\n    a :: list\nL0:\n    r0 = 'abc'\n    r1 = PyList_New(3)\n    r2 = 0\n    goto L2\nL1:\n    r3 = r2 < 3 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = CPyStr_GetItemUnsafe(r0, r2)\n    x = r4\n    r5 = f2(x)\n    CPyList_SetItemUnsafe(r1, r2, r5)\nL3:\n    r6 = r2 + 1\n    r2 = r6\n    goto L1\nL4:\n    a = r1\n    return 1\n\n[case testListBuiltFromBytes_64bit]\ndef f2(val: int) -> int:\n    return val + 2\n\ndef test() -> None:\n    source = b\"abc\"\n    a = [f2(x) for x in source]\n\n[out]\ndef f2(val):\n    val, r0 :: int\nL0:\n    r0 = CPyTagged_Add(val, 4)\n    return r0\ndef test():\n    r0, source :: bytes\n    r1 :: native_int\n    r2 :: list\n    r3 :: native_int\n    r4, r5, r6 :: bit\n    r7, r8, r9, r10 :: int\n    r11 :: object\n    r12, x, r13 :: int\n    r14 :: object\n    r15 :: native_int\n    a :: list\nL0:\n    r0 = b'abc'\n    source = r0\n    r1 = var_object_size source\n    r2 = PyList_New(r1)\n    r3 = 0\nL1:\n    r4 = r3 < r1 :: signed\n    if r4 goto L2 else goto L8 :: bool\nL2:\n    r5 = r3 <= 4611686018427387903 :: signed\n    if r5 goto L3 else goto L4 :: bool\nL3:\n    r6 = r3 >= -4611686018427387904 :: signed\n    if r6 goto L5 else goto L4 :: bool\nL4:\n    r7 = CPyTagged_FromInt64(r3)\n    r8 = r7\n    goto L6\nL5:\n    r9 = r3 << 1\n    r8 = r9\nL6:\n    r10 = CPyBytes_GetItem(source, r8)\n    r11 = box(int, r10)\n    r12 = unbox(int, r11)\n    x = r12\n    r13 = f2(x)\n    r14 = box(int, r13)\n    CPyList_SetItemUnsafe(r2, r3, r14)\nL7:\n    r15 = r3 + 1\n    r3 = r15\n    goto L1\nL8:\n    a = r2\n    return 1\n\n[case testListBuiltFromBytesExpr_64bit]\ndef f2(val: int) -> int:\n    return val + 2\n\ndef test() -> None:\n    a = [f2(x) for x in b\"abc\"]\n\n[out]\ndef f2(val):\n    val, r0 :: int\nL0:\n    r0 = CPyTagged_Add(val, 4)\n    return r0\ndef test():\n    r0 :: bytes\n    r1 :: list\n    r2 :: native_int\n    r3, r4, r5 :: bit\n    r6, r7, r8, r9 :: int\n    r10 :: object\n    r11, x, r12 :: int\n    r13 :: object\n    r14 :: native_int\n    a :: list\nL0:\n    r0 = b'abc'\n    r1 = PyList_New(3)\n    r2 = 0\n    goto L2\nL1:\n    r3 = r2 < 3 :: signed\n    if r3 goto L2 else goto L8 :: bool\nL2:\n    r4 = r2 <= 4611686018427387903 :: signed\n    if r4 goto L3 else goto L4 :: bool\nL3:\n    r5 = r2 >= -4611686018427387904 :: signed\n    if r5 goto L5 else goto L4 :: bool\nL4:\n    r6 = CPyTagged_FromInt64(r2)\n    r7 = r6\n    goto L6\nL5:\n    r8 = r2 << 1\n    r7 = r8\nL6:\n    r9 = CPyBytes_GetItem(r0, r7)\n    r10 = box(int, r9)\n    r11 = unbox(int, r10)\n    x = r11\n    r12 = f2(x)\n    r13 = box(int, r12)\n    CPyList_SetItemUnsafe(r1, r2, r13)\nL7:\n    r14 = r2 + 1\n    r2 = r14\n    goto L1\nL8:\n    a = r1\n    return 1\n\n[case testListBuiltFromFinalBytes_64bit]\nfrom typing import Final\n\nsource: Final = b\"abc\"\n\ndef f2(val: int) -> int:\n    return val + 2\n\ndef test() -> None:\n    a = [f2(x) for x in source]\n\n[out]\ndef f2(val):\n    val, r0 :: int\nL0:\n    r0 = CPyTagged_Add(val, 4)\n    return r0\ndef test():\n    r0 :: bytes\n    r1 :: bool\n    r2 :: native_int\n    r3 :: list\n    r4 :: native_int\n    r5, r6, r7 :: bit\n    r8, r9, r10, r11 :: int\n    r12 :: object\n    r13, x, r14 :: int\n    r15 :: object\n    r16 :: native_int\n    a :: list\nL0:\n    r0 = __main__.source :: static\n    if is_error(r0) goto L1 else goto L2\nL1:\n    r1 = raise NameError('value for final name \"source\" was not set')\n    unreachable\nL2:\n    r2 = var_object_size r0\n    r3 = PyList_New(r2)\n    r4 = 0\nL3:\n    r5 = r4 < r2 :: signed\n    if r5 goto L4 else goto L10 :: bool\nL4:\n    r6 = r4 <= 4611686018427387903 :: signed\n    if r6 goto L5 else goto L6 :: bool\nL5:\n    r7 = r4 >= -4611686018427387904 :: signed\n    if r7 goto L7 else goto L6 :: bool\nL6:\n    r8 = CPyTagged_FromInt64(r4)\n    r9 = r8\n    goto L8\nL7:\n    r10 = r4 << 1\n    r9 = r10\nL8:\n    r11 = CPyBytes_GetItem(r0, r9)\n    r12 = box(int, r11)\n    r13 = unbox(int, r12)\n    x = r13\n    r14 = f2(x)\n    r15 = box(int, r14)\n    CPyList_SetItemUnsafe(r3, r4, r15)\nL9:\n    r16 = r4 + 1\n    r4 = r16\n    goto L3\nL10:\n    a = r3\n    return 1\n\n[case testListBuiltFromStars]\nfrom typing import Final\n\nabc: Final = \"abc\"\n\ndef test() -> None:\n    a = [str(x) for x in [*abc, *\"def\", *b\"ghi\", (\"j\", \"k\"), *(\"l\", \"m\", \"n\")]]\n\n[out]\ndef test():\n    r0, r1 :: str\n    r2 :: bytes\n    r3, r4 :: str\n    r5 :: tuple[str, str]\n    r6, r7, r8 :: str\n    r9 :: tuple[str, str, str]\n    r10 :: list\n    r11, r12, r13, r14 :: object\n    r15 :: i32\n    r16 :: bit\n    r17, r18 :: object\n    r19 :: list\n    r20, r21 :: native_int\n    r22 :: bit\n    r23, x :: object\n    r24 :: str\n    r25 :: native_int\n    a :: list\nL0:\n    r0 = 'abc'\n    r1 = 'def'\n    r2 = b'ghi'\n    r3 = 'j'\n    r4 = 'k'\n    r5 = (r3, r4)\n    r6 = 'l'\n    r7 = 'm'\n    r8 = 'n'\n    r9 = (r6, r7, r8)\n    r10 = PyList_New(0)\n    r11 = CPyList_Extend(r10, r0)\n    r12 = CPyList_Extend(r10, r1)\n    r13 = CPyList_Extend(r10, r2)\n    r14 = box(tuple[str, str], r5)\n    r15 = PyList_Append(r10, r14)\n    r16 = r15 >= 0 :: signed\n    r17 = box(tuple[str, str, str], r9)\n    r18 = CPyList_Extend(r10, r17)\n    r19 = PyList_New(13)\n    r20 = 0\n    goto L2\nL1:\n    r21 = var_object_size r10\n    r22 = r20 < r21 :: signed\n    if r22 goto L2 else goto L4 :: bool\nL2:\n    r23 = list_get_item_unsafe r10, r20\n    x = r23\n    r24 = PyObject_Str(x)\n    CPyList_SetItemUnsafe(r19, r20, r24)\nL3:\n    r25 = r20 + 1\n    r20 = r25\n    goto L1\nL4:\n    a = r19\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-match.test",
    "content": "[case testMatchValuePattern_python3_10]\ndef f():\n    match 123:\n        case 123:\n            print(\"matched\")\n[out]\ndef f():\n    r0 :: bit\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7, r8 :: object\nL0:\n    r0 = int_eq 246, 246\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = 'matched'\n    r2 = builtins :: module\n    r3 = 'print'\n    r4 = CPyObject_GetAttr(r2, r3)\n    r5 = [r1]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r4, r6, 1, 0)\n    keep_alive r1\n    goto L3\nL2:\nL3:\n    r8 = box(None, 1)\n    return r8\n\n[case testMatchOrPattern_python3_10]\ndef f():\n    match 123:\n        case 123 | 456:\n            print(\"matched\")\n[out]\ndef f():\n    r0, r1 :: bit\n    r2 :: str\n    r3 :: object\n    r4 :: str\n    r5 :: object\n    r6 :: object[1]\n    r7 :: object_ptr\n    r8, r9 :: object\nL0:\n    r0 = int_eq 246, 246\n    if r0 goto L3 else goto L1 :: bool\nL1:\n    r1 = int_eq 246, 912\n    if r1 goto L3 else goto L2 :: bool\nL2:\n    goto L4\nL3:\n    r2 = 'matched'\n    r3 = builtins :: module\n    r4 = 'print'\n    r5 = CPyObject_GetAttr(r3, r4)\n    r6 = [r2]\n    r7 = load_address r6\n    r8 = PyObject_Vectorcall(r5, r7, 1, 0)\n    keep_alive r2\n    goto L5\nL4:\nL5:\n    r9 = box(None, 1)\n    return r9\n\n[case testMatchOrPatternManyPatterns_python3_10]\ndef f():\n    match 1:\n        case 1 | 2 | 3 | 4:\n            print(\"matched\")\n[out]\ndef f():\n    r0, r1, r2, r3 :: bit\n    r4 :: str\n    r5 :: object\n    r6 :: str\n    r7 :: object\n    r8 :: object[1]\n    r9 :: object_ptr\n    r10, r11 :: object\nL0:\n    r0 = int_eq 2, 2\n    if r0 goto L5 else goto L1 :: bool\nL1:\n    r1 = int_eq 2, 4\n    if r1 goto L5 else goto L2 :: bool\nL2:\n    r2 = int_eq 2, 6\n    if r2 goto L5 else goto L3 :: bool\nL3:\n    r3 = int_eq 2, 8\n    if r3 goto L5 else goto L4 :: bool\nL4:\n    goto L6\nL5:\n    r4 = 'matched'\n    r5 = builtins :: module\n    r6 = 'print'\n    r7 = CPyObject_GetAttr(r5, r6)\n    r8 = [r4]\n    r9 = load_address r8\n    r10 = PyObject_Vectorcall(r7, r9, 1, 0)\n    keep_alive r4\n    goto L7\nL6:\nL7:\n    r11 = box(None, 1)\n    return r11\n\n[case testMatchClassPattern_python3_10]\ndef f():\n    match 123:\n        case int():\n            print(\"matched\")\n[out]\ndef f():\n    r0, r1 :: object\n    r2 :: bool\n    r3 :: str\n    r4 :: object\n    r5 :: str\n    r6 :: object\n    r7 :: object[1]\n    r8 :: object_ptr\n    r9, r10 :: object\nL0:\n    r0 = load_address PyLong_Type\n    r1 = object 123\n    r2 = CPy_TypeCheck(r1, r0)\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = 'matched'\n    r4 = builtins :: module\n    r5 = 'print'\n    r6 = CPyObject_GetAttr(r4, r5)\n    r7 = [r3]\n    r8 = load_address r7\n    r9 = PyObject_Vectorcall(r6, r8, 1, 0)\n    keep_alive r3\n    goto L3\nL2:\nL3:\n    r10 = box(None, 1)\n    return r10\n[case testMatchExhaustivePattern_python3_10]\ndef f():\n    match 123:\n        case _:\n            print(\"matched\")\n[out]\ndef f():\n    r0 :: str\n    r1 :: object\n    r2 :: str\n    r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6, r7 :: object\nL0:\nL1:\n    r0 = 'matched'\n    r1 = builtins :: module\n    r2 = 'print'\n    r3 = CPyObject_GetAttr(r1, r2)\n    r4 = [r0]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r3, r5, 1, 0)\n    keep_alive r0\n    goto L3\nL2:\nL3:\n    r7 = box(None, 1)\n    return r7\n[case testMatchMultipleBodies_python3_10]\ndef f():\n    match 123:\n        case 123:\n            print(\"matched\")\n        case 456:\n            print(\"no match\")\n[out]\ndef f():\n    r0 :: bit\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7 :: object\n    r8 :: bit\n    r9 :: str\n    r10 :: object\n    r11 :: str\n    r12 :: object\n    r13 :: object[1]\n    r14 :: object_ptr\n    r15, r16 :: object\nL0:\n    r0 = int_eq 246, 246\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = 'matched'\n    r2 = builtins :: module\n    r3 = 'print'\n    r4 = CPyObject_GetAttr(r2, r3)\n    r5 = [r1]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r4, r6, 1, 0)\n    keep_alive r1\n    goto L5\nL2:\n    r8 = int_eq 246, 912\n    if r8 goto L3 else goto L4 :: bool\nL3:\n    r9 = 'no match'\n    r10 = builtins :: module\n    r11 = 'print'\n    r12 = CPyObject_GetAttr(r10, r11)\n    r13 = [r9]\n    r14 = load_address r13\n    r15 = PyObject_Vectorcall(r12, r14, 1, 0)\n    keep_alive r9\n    goto L5\nL4:\nL5:\n    r16 = box(None, 1)\n    return r16\n\n[case testMatchMultiBodyAndComplexOr_python3_10]\ndef f():\n    match 123:\n        case 1:\n            print(\"here 1\")\n        case 2 | 3:\n            print(\"here 2 | 3\")\n        case 123:\n            print(\"here 123\")\n[out]\ndef f():\n    r0 :: bit\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7 :: object\n    r8, r9 :: bit\n    r10 :: str\n    r11 :: object\n    r12 :: str\n    r13 :: object\n    r14 :: object[1]\n    r15 :: object_ptr\n    r16 :: object\n    r17 :: bit\n    r18 :: str\n    r19 :: object\n    r20 :: str\n    r21 :: object\n    r22 :: object[1]\n    r23 :: object_ptr\n    r24, r25 :: object\nL0:\n    r0 = int_eq 246, 2\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = 'here 1'\n    r2 = builtins :: module\n    r3 = 'print'\n    r4 = CPyObject_GetAttr(r2, r3)\n    r5 = [r1]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r4, r6, 1, 0)\n    keep_alive r1\n    goto L9\nL2:\n    r8 = int_eq 246, 4\n    if r8 goto L5 else goto L3 :: bool\nL3:\n    r9 = int_eq 246, 6\n    if r9 goto L5 else goto L4 :: bool\nL4:\n    goto L6\nL5:\n    r10 = 'here 2 | 3'\n    r11 = builtins :: module\n    r12 = 'print'\n    r13 = CPyObject_GetAttr(r11, r12)\n    r14 = [r10]\n    r15 = load_address r14\n    r16 = PyObject_Vectorcall(r13, r15, 1, 0)\n    keep_alive r10\n    goto L9\nL6:\n    r17 = int_eq 246, 246\n    if r17 goto L7 else goto L8 :: bool\nL7:\n    r18 = 'here 123'\n    r19 = builtins :: module\n    r20 = 'print'\n    r21 = CPyObject_GetAttr(r19, r20)\n    r22 = [r18]\n    r23 = load_address r22\n    r24 = PyObject_Vectorcall(r21, r23, 1, 0)\n    keep_alive r18\n    goto L9\nL8:\nL9:\n    r25 = box(None, 1)\n    return r25\n\n[case testMatchWithGuard_python3_10]\ndef f():\n    match 123:\n        case 123 if True:\n            print(\"matched\")\n[out]\ndef f():\n    r0 :: bit\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7, r8 :: object\nL0:\n    r0 = int_eq 246, 246\n    if r0 goto L1 else goto L3 :: bool\nL1:\n    if 1 goto L2 else goto L3 :: bool\nL2:\n    r1 = 'matched'\n    r2 = builtins :: module\n    r3 = 'print'\n    r4 = CPyObject_GetAttr(r2, r3)\n    r5 = [r1]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r4, r6, 1, 0)\n    keep_alive r1\n    goto L4\nL3:\nL4:\n    r8 = box(None, 1)\n    return r8\n\n[case testMatchSingleton_python3_10]\ndef f():\n    match 123:\n        case True:\n            print(\"value is True\")\n        case False:\n            print(\"value is False\")\n        case None:\n            print(\"value is None\")\n[out]\ndef f():\n    r0, r1 :: object\n    r2 :: bit\n    r3 :: str\n    r4 :: object\n    r5 :: str\n    r6 :: object\n    r7 :: object[1]\n    r8 :: object_ptr\n    r9, r10, r11 :: object\n    r12 :: bit\n    r13 :: str\n    r14 :: object\n    r15 :: str\n    r16 :: object\n    r17 :: object[1]\n    r18 :: object_ptr\n    r19, r20, r21 :: object\n    r22 :: bit\n    r23 :: str\n    r24 :: object\n    r25 :: str\n    r26 :: object\n    r27 :: object[1]\n    r28 :: object_ptr\n    r29, r30 :: object\nL0:\n    r0 = object 123\n    r1 = box(bool, 1)\n    r2 = r0 == r1\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = 'value is True'\n    r4 = builtins :: module\n    r5 = 'print'\n    r6 = CPyObject_GetAttr(r4, r5)\n    r7 = [r3]\n    r8 = load_address r7\n    r9 = PyObject_Vectorcall(r6, r8, 1, 0)\n    keep_alive r3\n    goto L7\nL2:\n    r10 = object 123\n    r11 = box(bool, 0)\n    r12 = r10 == r11\n    if r12 goto L3 else goto L4 :: bool\nL3:\n    r13 = 'value is False'\n    r14 = builtins :: module\n    r15 = 'print'\n    r16 = CPyObject_GetAttr(r14, r15)\n    r17 = [r13]\n    r18 = load_address r17\n    r19 = PyObject_Vectorcall(r16, r18, 1, 0)\n    keep_alive r13\n    goto L7\nL4:\n    r20 = load_address _Py_NoneStruct\n    r21 = object 123\n    r22 = r21 == r20\n    if r22 goto L5 else goto L6 :: bool\nL5:\n    r23 = 'value is None'\n    r24 = builtins :: module\n    r25 = 'print'\n    r26 = CPyObject_GetAttr(r24, r25)\n    r27 = [r23]\n    r28 = load_address r27\n    r29 = PyObject_Vectorcall(r26, r28, 1, 0)\n    keep_alive r23\n    goto L7\nL6:\nL7:\n    r30 = box(None, 1)\n    return r30\n[case testMatchRecursiveOrPattern_python3_10]\ndef f():\n    match 1:\n        case 1 | int():\n            print(\"matched\")\n[out]\ndef f():\n    r0 :: bit\n    r1, r2 :: object\n    r3 :: bool\n    r4 :: str\n    r5 :: object\n    r6 :: str\n    r7 :: object\n    r8 :: object[1]\n    r9 :: object_ptr\n    r10, r11 :: object\nL0:\n    r0 = int_eq 2, 2\n    if r0 goto L3 else goto L1 :: bool\nL1:\n    r1 = load_address PyLong_Type\n    r2 = object 1\n    r3 = CPy_TypeCheck(r2, r1)\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    goto L4\nL3:\n    r4 = 'matched'\n    r5 = builtins :: module\n    r6 = 'print'\n    r7 = CPyObject_GetAttr(r5, r6)\n    r8 = [r4]\n    r9 = load_address r8\n    r10 = PyObject_Vectorcall(r7, r9, 1, 0)\n    keep_alive r4\n    goto L5\nL4:\nL5:\n    r11 = box(None, 1)\n    return r11\n\n[case testMatchAsPattern_python3_10]\ndef f():\n    match 123:\n        case 123 as x:\n            print(x)\n[out]\ndef f():\n    r0 :: bit\n    r1, x, r2 :: object\n    r3 :: str\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7, r8 :: object\nL0:\n    r0 = int_eq 246, 246\n    r1 = object 123\n    x = r1\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r2 = builtins :: module\n    r3 = 'print'\n    r4 = CPyObject_GetAttr(r2, r3)\n    r5 = [x]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r4, r6, 1, 0)\n    keep_alive x\n    goto L3\nL2:\nL3:\n    r8 = box(None, 1)\n    return r8\n\n[case testMatchAsPatternOnOrPattern_python3_10]\ndef f():\n    match 1:\n        case (1 | 2) as x:\n            print(x)\n[out]\ndef f():\n    r0 :: bit\n    r1, x :: object\n    r2 :: bit\n    r3, r4 :: object\n    r5 :: str\n    r6 :: object\n    r7 :: object[1]\n    r8 :: object_ptr\n    r9, r10 :: object\nL0:\n    r0 = int_eq 2, 2\n    r1 = object 1\n    x = r1\n    if r0 goto L3 else goto L1 :: bool\nL1:\n    r2 = int_eq 2, 4\n    r3 = object 2\n    x = r3\n    if r2 goto L3 else goto L2 :: bool\nL2:\n    goto L4\nL3:\n    r4 = builtins :: module\n    r5 = 'print'\n    r6 = CPyObject_GetAttr(r4, r5)\n    r7 = [x]\n    r8 = load_address r7\n    r9 = PyObject_Vectorcall(r6, r8, 1, 0)\n    keep_alive x\n    goto L5\nL4:\nL5:\n    r10 = box(None, 1)\n    return r10\n\n[case testMatchAsPatternOnClassPattern_python3_10]\ndef f():\n    match 123:\n        case int() as i:\n            print(i)\n[out]\ndef f():\n    r0, r1 :: object\n    r2 :: bool\n    r3, i, r4 :: object\n    r5 :: str\n    r6 :: object\n    r7 :: object[1]\n    r8 :: object_ptr\n    r9, r10 :: object\nL0:\n    r0 = load_address PyLong_Type\n    r1 = object 123\n    r2 = CPy_TypeCheck(r1, r0)\n    if r2 goto L1 else goto L3 :: bool\nL1:\n    r3 = object 123\n    i = r3\nL2:\n    r4 = builtins :: module\n    r5 = 'print'\n    r6 = CPyObject_GetAttr(r4, r5)\n    r7 = [i]\n    r8 = load_address r7\n    r9 = PyObject_Vectorcall(r6, r8, 1, 0)\n    keep_alive i\n    goto L4\nL3:\nL4:\n    r10 = box(None, 1)\n    return r10\n\n[case testMatchClassPatternWithPositionalArgs_python3_10]\nclass Position:\n    __match_args__ = (\"x\", \"y\", \"z\")\n\n    x: int\n    y: int\n    z: int\n\ndef f(x) -> None:\n    match x:\n        case Position(1, 2, 3):\n            print(\"matched\")\n[out]\ndef Position.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.Position\n    r0, r1, r2 :: str\n    r3 :: tuple[str, str, str]\nL0:\n    r0 = 'x'\n    r1 = 'y'\n    r2 = 'z'\n    r3 = (r0, r1, r2)\n    __mypyc_self__.__match_args__ = r3\n    return 1\ndef f(x):\n    x, r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4 :: str\n    r5, r6, r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11 :: str\n    r12, r13, r14 :: object\n    r15 :: i32\n    r16 :: bit\n    r17 :: bool\n    r18 :: str\n    r19, r20, r21 :: object\n    r22 :: i32\n    r23 :: bit\n    r24 :: bool\n    r25 :: str\n    r26 :: object\n    r27 :: str\n    r28 :: object\n    r29 :: object[1]\n    r30 :: object_ptr\n    r31 :: object\nL0:\n    r0 = __main__.Position :: type\n    r1 = PyObject_IsInstance(x, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L1 else goto L5 :: bool\nL1:\n    r4 = 'x'\n    r5 = CPyObject_GetAttr(x, r4)\n    r6 = object 1\n    r7 = PyObject_RichCompare(r5, r6, 2)\n    r8 = PyObject_IsTrue(r7)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    if r10 goto L2 else goto L5 :: bool\nL2:\n    r11 = 'y'\n    r12 = CPyObject_GetAttr(x, r11)\n    r13 = object 2\n    r14 = PyObject_RichCompare(r12, r13, 2)\n    r15 = PyObject_IsTrue(r14)\n    r16 = r15 >= 0 :: signed\n    r17 = truncate r15: i32 to builtins.bool\n    if r17 goto L3 else goto L5 :: bool\nL3:\n    r18 = 'z'\n    r19 = CPyObject_GetAttr(x, r18)\n    r20 = object 3\n    r21 = PyObject_RichCompare(r19, r20, 2)\n    r22 = PyObject_IsTrue(r21)\n    r23 = r22 >= 0 :: signed\n    r24 = truncate r22: i32 to builtins.bool\n    if r24 goto L4 else goto L5 :: bool\nL4:\n    r25 = 'matched'\n    r26 = builtins :: module\n    r27 = 'print'\n    r28 = CPyObject_GetAttr(r26, r27)\n    r29 = [r25]\n    r30 = load_address r29\n    r31 = PyObject_Vectorcall(r28, r30, 1, 0)\n    keep_alive r25\n    goto L6\nL5:\nL6:\n    return 1\n\n[case testMatchClassPatternWithKeywordPatterns_python3_10]\nclass Position:\n    x: int\n    y: int\n    z: int\n\ndef f(x):\n    match x:\n        case Position(z=1, y=2, x=3):\n            print(\"matched\")\n[out]\ndef f(x):\n    x, r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4 :: str\n    r5, r6, r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11 :: str\n    r12, r13, r14 :: object\n    r15 :: i32\n    r16 :: bit\n    r17 :: bool\n    r18 :: str\n    r19, r20, r21 :: object\n    r22 :: i32\n    r23 :: bit\n    r24 :: bool\n    r25 :: str\n    r26 :: object\n    r27 :: str\n    r28 :: object\n    r29 :: object[1]\n    r30 :: object_ptr\n    r31, r32 :: object\nL0:\n    r0 = __main__.Position :: type\n    r1 = PyObject_IsInstance(x, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L1 else goto L5 :: bool\nL1:\n    r4 = 'z'\n    r5 = CPyObject_GetAttr(x, r4)\n    r6 = object 1\n    r7 = PyObject_RichCompare(r5, r6, 2)\n    r8 = PyObject_IsTrue(r7)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    if r10 goto L2 else goto L5 :: bool\nL2:\n    r11 = 'y'\n    r12 = CPyObject_GetAttr(x, r11)\n    r13 = object 2\n    r14 = PyObject_RichCompare(r12, r13, 2)\n    r15 = PyObject_IsTrue(r14)\n    r16 = r15 >= 0 :: signed\n    r17 = truncate r15: i32 to builtins.bool\n    if r17 goto L3 else goto L5 :: bool\nL3:\n    r18 = 'x'\n    r19 = CPyObject_GetAttr(x, r18)\n    r20 = object 3\n    r21 = PyObject_RichCompare(r19, r20, 2)\n    r22 = PyObject_IsTrue(r21)\n    r23 = r22 >= 0 :: signed\n    r24 = truncate r22: i32 to builtins.bool\n    if r24 goto L4 else goto L5 :: bool\nL4:\n    r25 = 'matched'\n    r26 = builtins :: module\n    r27 = 'print'\n    r28 = CPyObject_GetAttr(r26, r27)\n    r29 = [r25]\n    r30 = load_address r29\n    r31 = PyObject_Vectorcall(r28, r30, 1, 0)\n    keep_alive r25\n    goto L6\nL5:\nL6:\n    r32 = box(None, 1)\n    return r32\n[case testMatchClassPatternWithNestedPattern_python3_10]\nclass C:\n    num: int\n\ndef f(x):\n    match x:\n        case C(num=1 | 2):\n            print(\"matched\")\n[out]\ndef f(x):\n    x, r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4 :: str\n    r5, r6, r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11, r12 :: object\n    r13 :: i32\n    r14 :: bit\n    r15 :: bool\n    r16 :: str\n    r17 :: object\n    r18 :: str\n    r19 :: object\n    r20 :: object[1]\n    r21 :: object_ptr\n    r22, r23 :: object\nL0:\n    r0 = __main__.C :: type\n    r1 = PyObject_IsInstance(x, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L1 else goto L5 :: bool\nL1:\n    r4 = 'num'\n    r5 = CPyObject_GetAttr(x, r4)\n    r6 = object 1\n    r7 = PyObject_RichCompare(r5, r6, 2)\n    r8 = PyObject_IsTrue(r7)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    if r10 goto L4 else goto L2 :: bool\nL2:\n    r11 = object 2\n    r12 = PyObject_RichCompare(r5, r11, 2)\n    r13 = PyObject_IsTrue(r12)\n    r14 = r13 >= 0 :: signed\n    r15 = truncate r13: i32 to builtins.bool\n    if r15 goto L4 else goto L3 :: bool\nL3:\n    goto L5\nL4:\n    r16 = 'matched'\n    r17 = builtins :: module\n    r18 = 'print'\n    r19 = CPyObject_GetAttr(r17, r18)\n    r20 = [r16]\n    r21 = load_address r20\n    r22 = PyObject_Vectorcall(r19, r21, 1, 0)\n    keep_alive r16\n    goto L6\nL5:\nL6:\n    r23 = box(None, 1)\n    return r23\n[case testAsPatternDoesntBleedIntoSubPatterns_python3_10]\nclass C:\n    __match_args__ = (\"a\", \"b\")\n    a: int\n    b: int\n\ndef f(x) -> None:\n    match x:\n        case C(1, 2) as y:\n            print(\"matched\")\n[out]\ndef C.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.C\n    r0, r1 :: str\n    r2 :: tuple[str, str]\nL0:\n    r0 = 'a'\n    r1 = 'b'\n    r2 = (r0, r1)\n    __mypyc_self__.__match_args__ = r2\n    return 1\ndef f(x):\n    x, r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4, y :: __main__.C\n    r5 :: str\n    r6, r7, r8 :: object\n    r9 :: i32\n    r10 :: bit\n    r11 :: bool\n    r12 :: str\n    r13, r14, r15 :: object\n    r16 :: i32\n    r17 :: bit\n    r18 :: bool\n    r19 :: str\n    r20 :: object\n    r21 :: str\n    r22 :: object\n    r23 :: object[1]\n    r24 :: object_ptr\n    r25 :: object\nL0:\n    r0 = __main__.C :: type\n    r1 = PyObject_IsInstance(x, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L1 else goto L5 :: bool\nL1:\n    r4 = cast(__main__.C, x)\n    y = r4\nL2:\n    r5 = 'a'\n    r6 = CPyObject_GetAttr(x, r5)\n    r7 = object 1\n    r8 = PyObject_RichCompare(r6, r7, 2)\n    r9 = PyObject_IsTrue(r8)\n    r10 = r9 >= 0 :: signed\n    r11 = truncate r9: i32 to builtins.bool\n    if r11 goto L3 else goto L5 :: bool\nL3:\n    r12 = 'b'\n    r13 = CPyObject_GetAttr(x, r12)\n    r14 = object 2\n    r15 = PyObject_RichCompare(r13, r14, 2)\n    r16 = PyObject_IsTrue(r15)\n    r17 = r16 >= 0 :: signed\n    r18 = truncate r16: i32 to builtins.bool\n    if r18 goto L4 else goto L5 :: bool\nL4:\n    r19 = 'matched'\n    r20 = builtins :: module\n    r21 = 'print'\n    r22 = CPyObject_GetAttr(r20, r21)\n    r23 = [r19]\n    r24 = load_address r23\n    r25 = PyObject_Vectorcall(r22, r24, 1, 0)\n    keep_alive r19\n    goto L6\nL5:\nL6:\n    return 1\n\n[case testMatchClassPatternPositionalCapture_python3_10]\nclass C:\n    __match_args__ = (\"x\",)\n\n    x: int\n\ndef f(x):\n    match x:\n        case C(num):\n            print(\"matched\")\n[out]\ndef C.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.C\n    r0 :: str\n    r1 :: tuple[str]\nL0:\n    r0 = 'x'\n    r1 = (r0)\n    __mypyc_self__.__match_args__ = r1\n    return 1\ndef f(x):\n    x, r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4 :: str\n    r5, num :: object\n    r6 :: str\n    r7 :: object\n    r8 :: str\n    r9 :: object\n    r10 :: object[1]\n    r11 :: object_ptr\n    r12, r13 :: object\nL0:\n    r0 = __main__.C :: type\n    r1 = PyObject_IsInstance(x, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L1 else goto L3 :: bool\nL1:\n    r4 = 'x'\n    r5 = CPyObject_GetAttr(x, r4)\n    num = r5\nL2:\n    r6 = 'matched'\n    r7 = builtins :: module\n    r8 = 'print'\n    r9 = CPyObject_GetAttr(r7, r8)\n    r10 = [r6]\n    r11 = load_address r10\n    r12 = PyObject_Vectorcall(r9, r11, 1, 0)\n    keep_alive r6\n    goto L4\nL3:\nL4:\n    r13 = box(None, 1)\n    return r13\n\n[case testMatchMappingEmpty_python3_10]\ndef f(x):\n    match x:\n        case {}:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: str\n    r3 :: object\n    r4 :: str\n    r5 :: object\n    r6 :: object[1]\n    r7 :: object_ptr\n    r8, r9 :: object\nL0:\n    r0 = CPyMapping_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = 'matched'\n    r3 = builtins :: module\n    r4 = 'print'\n    r5 = CPyObject_GetAttr(r3, r4)\n    r6 = [r2]\n    r7 = load_address r6\n    r8 = PyObject_Vectorcall(r5, r7, 1, 0)\n    keep_alive r2\n    goto L3\nL2:\nL3:\n    r9 = box(None, 1)\n    return r9\n[case testMatchMappingPatternWithKeys_python3_10]\ndef f(x):\n    match x:\n        case {\"key\": \"value\"}:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: str\n    r3 :: i32\n    r4 :: bit\n    r5 :: object\n    r6 :: str\n    r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11 :: str\n    r12 :: object\n    r13 :: str\n    r14 :: object\n    r15 :: object[1]\n    r16 :: object_ptr\n    r17, r18 :: object\nL0:\n    r0 = CPyMapping_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = 'key'\n    r3 = PyMapping_HasKey(x, r2)\n    r4 = r3 != 0\n    if r4 goto L2 else goto L4 :: bool\nL2:\n    r5 = PyObject_GetItem(x, r2)\n    r6 = 'value'\n    r7 = PyObject_RichCompare(r5, r6, 2)\n    r8 = PyObject_IsTrue(r7)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    if r10 goto L3 else goto L4 :: bool\nL3:\n    r11 = 'matched'\n    r12 = builtins :: module\n    r13 = 'print'\n    r14 = CPyObject_GetAttr(r12, r13)\n    r15 = [r11]\n    r16 = load_address r15\n    r17 = PyObject_Vectorcall(r14, r16, 1, 0)\n    keep_alive r11\n    goto L5\nL4:\nL5:\n    r18 = box(None, 1)\n    return r18\n[case testMatchMappingPatternWithRest_python3_10]\ndef f(x):\n    match x:\n        case {**rest}:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2, rest :: dict\n    r3 :: str\n    r4 :: object\n    r5 :: str\n    r6 :: object\n    r7 :: object[1]\n    r8 :: object_ptr\n    r9, r10 :: object\nL0:\n    r0 = CPyMapping_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L3 :: bool\nL1:\n    r2 = CPyDict_FromAny(x)\n    rest = r2\nL2:\n    r3 = 'matched'\n    r4 = builtins :: module\n    r5 = 'print'\n    r6 = CPyObject_GetAttr(r4, r5)\n    r7 = [r3]\n    r8 = load_address r7\n    r9 = PyObject_Vectorcall(r6, r8, 1, 0)\n    keep_alive r3\n    goto L4\nL3:\nL4:\n    r10 = box(None, 1)\n    return r10\n[case testMatchMappingPatternWithRestPopKeys_python3_10]\ndef f(x):\n    match x:\n        case {\"key\": \"value\", **rest}:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: str\n    r3 :: i32\n    r4 :: bit\n    r5 :: object\n    r6 :: str\n    r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11, rest :: dict\n    r12 :: i32\n    r13 :: bit\n    r14 :: str\n    r15 :: object\n    r16 :: str\n    r17 :: object\n    r18 :: object[1]\n    r19 :: object_ptr\n    r20, r21 :: object\nL0:\n    r0 = CPyMapping_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L5 :: bool\nL1:\n    r2 = 'key'\n    r3 = PyMapping_HasKey(x, r2)\n    r4 = r3 != 0\n    if r4 goto L2 else goto L5 :: bool\nL2:\n    r5 = PyObject_GetItem(x, r2)\n    r6 = 'value'\n    r7 = PyObject_RichCompare(r5, r6, 2)\n    r8 = PyObject_IsTrue(r7)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    if r10 goto L3 else goto L5 :: bool\nL3:\n    r11 = CPyDict_FromAny(x)\n    rest = r11\n    r12 = PyDict_DelItem(r11, r2)\n    r13 = r12 >= 0 :: signed\nL4:\n    r14 = 'matched'\n    r15 = builtins :: module\n    r16 = 'print'\n    r17 = CPyObject_GetAttr(r15, r16)\n    r18 = [r14]\n    r19 = load_address r18\n    r20 = PyObject_Vectorcall(r17, r19, 1, 0)\n    keep_alive r14\n    goto L6\nL5:\nL6:\n    r21 = box(None, 1)\n    return r21\n[case testMatchEmptySequencePattern_python3_10]\ndef f(x):\n    match x:\n        case []:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: native_int\n    r3, r4 :: bit\n    r5 :: str\n    r6 :: object\n    r7 :: str\n    r8 :: object\n    r9 :: object[1]\n    r10 :: object_ptr\n    r11, r12 :: object\nL0:\n    r0 = CPySequence_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L3 :: bool\nL1:\n    r2 = PyObject_Size(x)\n    r3 = r2 >= 0 :: signed\n    r4 = r2 == 0\n    if r4 goto L2 else goto L3 :: bool\nL2:\n    r5 = 'matched'\n    r6 = builtins :: module\n    r7 = 'print'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = [r5]\n    r10 = load_address r9\n    r11 = PyObject_Vectorcall(r8, r10, 1, 0)\n    keep_alive r5\n    goto L4\nL3:\nL4:\n    r12 = box(None, 1)\n    return r12\n[case testMatchFixedLengthSequencePattern_python3_10]\ndef f(x):\n    match x:\n        case [1, 2]:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: native_int\n    r3, r4 :: bit\n    r5, r6, r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11, r12, r13 :: object\n    r14 :: i32\n    r15 :: bit\n    r16 :: bool\n    r17 :: str\n    r18 :: object\n    r19 :: str\n    r20 :: object\n    r21 :: object[1]\n    r22 :: object_ptr\n    r23, r24 :: object\nL0:\n    r0 = CPySequence_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L5 :: bool\nL1:\n    r2 = PyObject_Size(x)\n    r3 = r2 >= 0 :: signed\n    r4 = r2 == 2\n    if r4 goto L2 else goto L5 :: bool\nL2:\n    r5 = PySequence_GetItem(x, 0)\n    r6 = object 1\n    r7 = PyObject_RichCompare(r5, r6, 2)\n    r8 = PyObject_IsTrue(r7)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    if r10 goto L3 else goto L5 :: bool\nL3:\n    r11 = PySequence_GetItem(x, 1)\n    r12 = object 2\n    r13 = PyObject_RichCompare(r11, r12, 2)\n    r14 = PyObject_IsTrue(r13)\n    r15 = r14 >= 0 :: signed\n    r16 = truncate r14: i32 to builtins.bool\n    if r16 goto L4 else goto L5 :: bool\nL4:\n    r17 = 'matched'\n    r18 = builtins :: module\n    r19 = 'print'\n    r20 = CPyObject_GetAttr(r18, r19)\n    r21 = [r17]\n    r22 = load_address r21\n    r23 = PyObject_Vectorcall(r20, r22, 1, 0)\n    keep_alive r17\n    goto L6\nL5:\nL6:\n    r24 = box(None, 1)\n    return r24\n[case testMatchSequencePatternWithTrailingUnboundStar_python3_10]\ndef f(x):\n    match x:\n        case [1, 2, *_]:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: native_int\n    r3, r4 :: bit\n    r5, r6, r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11, r12, r13 :: object\n    r14 :: i32\n    r15 :: bit\n    r16 :: bool\n    r17 :: str\n    r18 :: object\n    r19 :: str\n    r20 :: object\n    r21 :: object[1]\n    r22 :: object_ptr\n    r23, r24 :: object\nL0:\n    r0 = CPySequence_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L5 :: bool\nL1:\n    r2 = PyObject_Size(x)\n    r3 = r2 >= 0 :: signed\n    r4 = r2 >= 2 :: signed\n    if r4 goto L2 else goto L5 :: bool\nL2:\n    r5 = PySequence_GetItem(x, 0)\n    r6 = object 1\n    r7 = PyObject_RichCompare(r5, r6, 2)\n    r8 = PyObject_IsTrue(r7)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    if r10 goto L3 else goto L5 :: bool\nL3:\n    r11 = PySequence_GetItem(x, 1)\n    r12 = object 2\n    r13 = PyObject_RichCompare(r11, r12, 2)\n    r14 = PyObject_IsTrue(r13)\n    r15 = r14 >= 0 :: signed\n    r16 = truncate r14: i32 to builtins.bool\n    if r16 goto L4 else goto L5 :: bool\nL4:\n    r17 = 'matched'\n    r18 = builtins :: module\n    r19 = 'print'\n    r20 = CPyObject_GetAttr(r18, r19)\n    r21 = [r17]\n    r22 = load_address r21\n    r23 = PyObject_Vectorcall(r20, r22, 1, 0)\n    keep_alive r17\n    goto L6\nL5:\nL6:\n    r24 = box(None, 1)\n    return r24\n[case testMatchSequencePatternWithTrailingBoundStar_python3_10]\ndef f(x):\n    match x:\n        case [1, 2, *rest]:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: native_int\n    r3, r4 :: bit\n    r5, r6, r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11, r12, r13 :: object\n    r14 :: i32\n    r15 :: bit\n    r16 :: bool\n    r17 :: native_int\n    r18 :: object\n    r19, rest :: list\n    r20 :: str\n    r21 :: object\n    r22 :: str\n    r23 :: object\n    r24 :: object[1]\n    r25 :: object_ptr\n    r26, r27 :: object\nL0:\n    r0 = CPySequence_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L6 :: bool\nL1:\n    r2 = PyObject_Size(x)\n    r3 = r2 >= 0 :: signed\n    r4 = r2 >= 2 :: signed\n    if r4 goto L2 else goto L6 :: bool\nL2:\n    r5 = PySequence_GetItem(x, 0)\n    r6 = object 1\n    r7 = PyObject_RichCompare(r5, r6, 2)\n    r8 = PyObject_IsTrue(r7)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    if r10 goto L3 else goto L6 :: bool\nL3:\n    r11 = PySequence_GetItem(x, 1)\n    r12 = object 2\n    r13 = PyObject_RichCompare(r11, r12, 2)\n    r14 = PyObject_IsTrue(r13)\n    r15 = r14 >= 0 :: signed\n    r16 = truncate r14: i32 to builtins.bool\n    if r16 goto L4 else goto L6 :: bool\nL4:\n    r17 = r2 - 0\n    r18 = PySequence_GetSlice(x, 2, r17)\n    r19 = cast(list, r18)\n    rest = r19\nL5:\n    r20 = 'matched'\n    r21 = builtins :: module\n    r22 = 'print'\n    r23 = CPyObject_GetAttr(r21, r22)\n    r24 = [r20]\n    r25 = load_address r24\n    r26 = PyObject_Vectorcall(r23, r25, 1, 0)\n    keep_alive r20\n    goto L7\nL6:\nL7:\n    r27 = box(None, 1)\n    return r27\n\n[case testMatchSequenceWithStarPatternInTheMiddle_python3_10]\ndef f(x):\n    match x:\n        case [\"start\", *rest, \"end\"]:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: native_int\n    r3, r4 :: bit\n    r5 :: object\n    r6 :: str\n    r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11 :: native_int\n    r12 :: object\n    r13 :: str\n    r14 :: object\n    r15 :: i32\n    r16 :: bit\n    r17 :: bool\n    r18 :: native_int\n    r19 :: object\n    r20, rest :: list\n    r21 :: str\n    r22 :: object\n    r23 :: str\n    r24 :: object\n    r25 :: object[1]\n    r26 :: object_ptr\n    r27, r28 :: object\nL0:\n    r0 = CPySequence_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L6 :: bool\nL1:\n    r2 = PyObject_Size(x)\n    r3 = r2 >= 0 :: signed\n    r4 = r2 >= 2 :: signed\n    if r4 goto L2 else goto L6 :: bool\nL2:\n    r5 = PySequence_GetItem(x, 0)\n    r6 = 'start'\n    r7 = PyObject_RichCompare(r5, r6, 2)\n    r8 = PyObject_IsTrue(r7)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    if r10 goto L3 else goto L6 :: bool\nL3:\n    r11 = r2 - 1\n    r12 = PySequence_GetItem(x, r11)\n    r13 = 'end'\n    r14 = PyObject_RichCompare(r12, r13, 2)\n    r15 = PyObject_IsTrue(r14)\n    r16 = r15 >= 0 :: signed\n    r17 = truncate r15: i32 to builtins.bool\n    if r17 goto L4 else goto L6 :: bool\nL4:\n    r18 = r2 - 1\n    r19 = PySequence_GetSlice(x, 1, r18)\n    r20 = cast(list, r19)\n    rest = r20\nL5:\n    r21 = 'matched'\n    r22 = builtins :: module\n    r23 = 'print'\n    r24 = CPyObject_GetAttr(r22, r23)\n    r25 = [r21]\n    r26 = load_address r25\n    r27 = PyObject_Vectorcall(r24, r26, 1, 0)\n    keep_alive r21\n    goto L7\nL6:\nL7:\n    r28 = box(None, 1)\n    return r28\n\n[case testMatchSequenceWithStarPatternAtTheStart_python3_10]\ndef f(x):\n    match x:\n        case [*rest, 1, 2]:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: native_int\n    r3, r4 :: bit\n    r5 :: native_int\n    r6, r7, r8 :: object\n    r9 :: i32\n    r10 :: bit\n    r11 :: bool\n    r12 :: native_int\n    r13, r14, r15 :: object\n    r16 :: i32\n    r17 :: bit\n    r18 :: bool\n    r19 :: native_int\n    r20 :: object\n    r21, rest :: list\n    r22 :: str\n    r23 :: object\n    r24 :: str\n    r25 :: object\n    r26 :: object[1]\n    r27 :: object_ptr\n    r28, r29 :: object\nL0:\n    r0 = CPySequence_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L6 :: bool\nL1:\n    r2 = PyObject_Size(x)\n    r3 = r2 >= 0 :: signed\n    r4 = r2 >= 2 :: signed\n    if r4 goto L2 else goto L6 :: bool\nL2:\n    r5 = r2 - 2\n    r6 = PySequence_GetItem(x, r5)\n    r7 = object 1\n    r8 = PyObject_RichCompare(r6, r7, 2)\n    r9 = PyObject_IsTrue(r8)\n    r10 = r9 >= 0 :: signed\n    r11 = truncate r9: i32 to builtins.bool\n    if r11 goto L3 else goto L6 :: bool\nL3:\n    r12 = r2 - 1\n    r13 = PySequence_GetItem(x, r12)\n    r14 = object 2\n    r15 = PyObject_RichCompare(r13, r14, 2)\n    r16 = PyObject_IsTrue(r15)\n    r17 = r16 >= 0 :: signed\n    r18 = truncate r16: i32 to builtins.bool\n    if r18 goto L4 else goto L6 :: bool\nL4:\n    r19 = r2 - 2\n    r20 = PySequence_GetSlice(x, 0, r19)\n    r21 = cast(list, r20)\n    rest = r21\nL5:\n    r22 = 'matched'\n    r23 = builtins :: module\n    r24 = 'print'\n    r25 = CPyObject_GetAttr(r23, r24)\n    r26 = [r22]\n    r27 = load_address r26\n    r28 = PyObject_Vectorcall(r25, r27, 1, 0)\n    keep_alive r22\n    goto L7\nL6:\nL7:\n    r29 = box(None, 1)\n    return r29\n\n[case testMatchBuiltinClassPattern_python3_10]\ndef f(x):\n    match x:\n        case int(y):\n            print(\"matched\")\n[out]\ndef f(x):\n    x, r0 :: object\n    r1 :: bool\n    y :: object\n    r2 :: str\n    r3 :: object\n    r4 :: str\n    r5 :: object\n    r6 :: object[1]\n    r7 :: object_ptr\n    r8, r9 :: object\nL0:\n    r0 = load_address PyLong_Type\n    r1 = CPy_TypeCheck(x, r0)\n    if r1 goto L1 else goto L3 :: bool\nL1:\n    y = x\nL2:\n    r2 = 'matched'\n    r3 = builtins :: module\n    r4 = 'print'\n    r5 = CPyObject_GetAttr(r3, r4)\n    r6 = [r2]\n    r7 = load_address r6\n    r8 = PyObject_Vectorcall(r5, r7, 1, 0)\n    keep_alive r2\n    goto L4\nL3:\nL4:\n    r9 = box(None, 1)\n    return r9\n\n[case testMatchSequenceCaptureAll_python3_10]\ndef f(x):\n    match x:\n        case [*rest]:\n            print(\"matched\")\n[out]\ndef f(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2 :: native_int\n    r3, r4 :: bit\n    r5 :: native_int\n    r6 :: object\n    r7, rest :: list\n    r8 :: str\n    r9 :: object\n    r10 :: str\n    r11 :: object\n    r12 :: object[1]\n    r13 :: object_ptr\n    r14, r15 :: object\nL0:\n    r0 = CPySequence_Check(x)\n    r1 = r0 != 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = PyObject_Size(x)\n    r3 = r2 >= 0 :: signed\n    r4 = r2 >= 0 :: signed\n    if r4 goto L2 else goto L4 :: bool\nL2:\n    r5 = r2 - 0\n    r6 = PySequence_GetSlice(x, 0, r5)\n    r7 = cast(list, r6)\n    rest = r7\nL3:\n    r8 = 'matched'\n    r9 = builtins :: module\n    r10 = 'print'\n    r11 = CPyObject_GetAttr(r9, r10)\n    r12 = [r8]\n    r13 = load_address r12\n    r14 = PyObject_Vectorcall(r11, r13, 1, 0)\n    keep_alive r8\n    goto L5\nL4:\nL5:\n    r15 = box(None, 1)\n    return r15\n\n[case testMatchTypeAnnotatedNativeClass_python3_10]\nclass A:\n    a: int\n\ndef f(x: A | int) -> int:\n    match x:\n        case A(a=a):\n            return a\n        case int():\n            return x\n[out]\ndef f(x):\n    x :: union[__main__.A, int]\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4 :: str\n    r5 :: object\n    r6, a :: int\n    r7 :: object\n    r8 :: bool\n    r9 :: int\nL0:\n    r0 = __main__.A :: type\n    r1 = PyObject_IsInstance(x, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L1 else goto L3 :: bool\nL1:\n    r4 = 'a'\n    r5 = CPyObject_GetAttr(x, r4)\n    r6 = unbox(int, r5)\n    a = r6\nL2:\n    return a\nL3:\n    r7 = load_address PyLong_Type\n    r8 = CPy_TypeCheck(x, r7)\n    if r8 goto L4 else goto L5 :: bool\nL4:\n    r9 = unbox(int, x)\n    return r9\nL5:\nL6:\n    unreachable\n\n[case testMatchLiteralMatchArgs_python3_10]\nfrom typing import Literal\n\nclass Foo:\n    __match_args__: tuple[Literal[\"foo\"]] = (\"foo\",)\n    foo: str\n\ndef f(x: Foo) -> None:\n    match x:\n        case Foo(foo):\n            print(\"foo\")\n        case _:\n            assert False, \"Unreachable\"\n[out]\ndef Foo.__mypyc_defaults_setup(__mypyc_self__):\n    __mypyc_self__ :: __main__.Foo\n    r0 :: str\n    r1 :: tuple[str]\nL0:\n    r0 = 'foo'\n    r1 = (r0)\n    __mypyc_self__.__match_args__ = r1\n    return 1\ndef f(x):\n    x :: __main__.Foo\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\n    r4 :: str\n    r5 :: object\n    r6, foo, r7 :: str\n    r8 :: object\n    r9 :: str\n    r10 :: object\n    r11 :: object[1]\n    r12 :: object_ptr\n    r13, r14 :: object\n    r15 :: i32\n    r16 :: bit\n    r17, r18 :: bool\nL0:\n    r0 = __main__.Foo :: type\n    r1 = PyObject_IsInstance(x, r0)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    if r3 goto L1 else goto L3 :: bool\nL1:\n    r4 = 'foo'\n    r5 = CPyObject_GetAttr(x, r4)\n    r6 = cast(str, r5)\n    foo = r6\nL2:\n    r7 = 'foo'\n    r8 = builtins :: module\n    r9 = 'print'\n    r10 = CPyObject_GetAttr(r8, r9)\n    r11 = [r7]\n    r12 = load_address r11\n    r13 = PyObject_Vectorcall(r10, r12, 1, 0)\n    keep_alive r7\n    goto L8\nL3:\nL4:\n    r14 = box(bool, 0)\n    r15 = PyObject_IsTrue(r14)\n    r16 = r15 >= 0 :: signed\n    r17 = truncate r15: i32 to builtins.bool\n    if r17 goto L6 else goto L5 :: bool\nL5:\n    r18 = raise AssertionError('Unreachable')\n    unreachable\nL6:\n    goto L8\nL7:\nL8:\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-math.test",
    "content": "[case testMathLiteralsAreInlined]\nimport math\nfrom math import pi, e, tau, inf, nan\n\ndef f1() -> float:\n    return pi\n\ndef f2() -> float:\n    return math.pi\n\ndef f3() -> float:\n    return math.e\n\ndef f4() -> float:\n    return math.e\n\ndef f5() -> float:\n    return math.tau\n\ndef f6() -> float:\n    return math.tau\n\ndef f7() -> float:\n    return math.inf\ndef f8() -> float:\n    return math.inf\n\ndef f9() -> float:\n    return math.nan\n\ndef f10() -> float:\n    return math.nan\n\n[out]\ndef f1():\nL0:\n    return 3.141592653589793\ndef f2():\nL0:\n    return 3.141592653589793\ndef f3():\nL0:\n    return 2.718281828459045\ndef f4():\nL0:\n    return 2.718281828459045\ndef f5():\nL0:\n    return 6.283185307179586\ndef f6():\nL0:\n    return 6.283185307179586\ndef f7():\nL0:\n    return inf\ndef f8():\nL0:\n    return inf\ndef f9():\nL0:\n    return nan\ndef f10():\nL0:\n    return nan\n"
  },
  {
    "path": "mypyc/test-data/irbuild-nested.test",
    "content": "[case testNestedFunctions]\nfrom typing import Callable\n\ndef a() -> Callable[[], object]:\n    def inner() -> object:\n        return None\n    return inner\n\ndef b() -> Callable[[], Callable[[], str]]:\n    def first() -> Callable[[], str]:\n        def second() -> str:\n            return 'b.first.second: nested function'\n        return second\n    return first\n\ndef c(num: float) -> Callable[[str], str]:\n    def inner(s: str) -> str:\n        return s + '!'\n    return inner\n\ndef d(num: float) -> str:\n    def inner(s: str) -> str:\n        return s + '?'\n    a = inner('one')\n    b = inner('two')\n    return a\n\ndef inner() -> str:\n    return 'inner: normal function'\n\ndef first() -> str:\n    return 'first: normal function'\n\ndef second() -> str:\n    return 'second: normal function'\n[out]\ndef inner_a_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef inner_a_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.inner_a_obj\n    r0 :: __main__.a_env\n    r1 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = box(None, 1)\n    return r1\ndef a():\n    r0 :: __main__.a_env\n    r1 :: __main__.inner_a_obj\n    r2 :: bool\n    inner :: object\nL0:\n    r0 = a_env()\n    r1 = inner_a_obj()\n    r1.__mypyc_env__ = r0; r2 = is_error\n    inner = r1\n    return inner\ndef second_b_first_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef second_b_first_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.second_b_first_obj\n    r0 :: __main__.first_b_env\n    r1 :: __main__.b_env\n    r2 :: str\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.__mypyc_env__\n    r2 = 'b.first.second: nested function'\n    return r2\ndef first_b_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef first_b_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.first_b_obj\n    r0 :: __main__.b_env\n    r1 :: __main__.first_b_env\n    r2 :: bool\n    r3 :: __main__.second_b_first_obj\n    r4 :: bool\n    second :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = first_b_env()\n    r1.__mypyc_env__ = r0; r2 = is_error\n    r3 = second_b_first_obj()\n    r3.__mypyc_env__ = r1; r4 = is_error\n    second = r3\n    return second\ndef b():\n    r0 :: __main__.b_env\n    r1 :: __main__.first_b_obj\n    r2 :: bool\n    first :: object\nL0:\n    r0 = b_env()\n    r1 = first_b_obj()\n    r1.__mypyc_env__ = r0; r2 = is_error\n    first = r1\n    return first\ndef inner_c_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef inner_c_obj.__call__(__mypyc_self__, s):\n    __mypyc_self__ :: __main__.inner_c_obj\n    s :: str\n    r0 :: __main__.c_env\n    r1, r2 :: str\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = '!'\n    r2 = PyUnicode_Concat(s, r1)\n    return r2\ndef c(num):\n    num :: float\n    r0 :: __main__.c_env\n    r1 :: __main__.inner_c_obj\n    r2 :: bool\n    inner :: object\nL0:\n    r0 = c_env()\n    r1 = inner_c_obj()\n    r1.__mypyc_env__ = r0; r2 = is_error\n    inner = r1\n    return inner\ndef inner_d_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef inner_d_obj.__call__(__mypyc_self__, s):\n    __mypyc_self__ :: __main__.inner_d_obj\n    s :: str\n    r0 :: __main__.d_env\n    r1, r2 :: str\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = '?'\n    r2 = PyUnicode_Concat(s, r1)\n    return r2\ndef d(num):\n    num :: float\n    r0 :: __main__.d_env\n    r1 :: __main__.inner_d_obj\n    r2 :: bool\n    inner :: object\n    r3 :: str\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\n    r7, a, r8 :: str\n    r9 :: object[1]\n    r10 :: object_ptr\n    r11 :: object\n    r12, b :: str\nL0:\n    r0 = d_env()\n    r1 = inner_d_obj()\n    r1.__mypyc_env__ = r0; r2 = is_error\n    inner = r1\n    r3 = 'one'\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(inner, r5, 1, 0)\n    keep_alive r3\n    r7 = cast(str, r6)\n    a = r7\n    r8 = 'two'\n    r9 = [r8]\n    r10 = load_address r9\n    r11 = PyObject_Vectorcall(inner, r10, 1, 0)\n    keep_alive r8\n    r12 = cast(str, r11)\n    b = r12\n    return a\ndef inner():\n    r0 :: str\nL0:\n    r0 = 'inner: normal function'\n    return r0\ndef first():\n    r0 :: str\nL0:\n    r0 = 'first: normal function'\n    return r0\ndef second():\n    r0 :: str\nL0:\n    r0 = 'second: normal function'\n    return r0\n\n[case testFreeVars]\nfrom typing import Callable\n\ndef a(num: int) -> int:\n    def inner() -> int:\n        return num\n    return inner()\n\ndef b() -> int:\n    num = 3\n    def inner() -> int:\n        nonlocal num\n        num = 4\n        foo = 6\n        return num\n    return inner() + num\n\ndef c(flag: bool) -> str:\n    if flag:\n        def inner() -> str:\n            return 'f.inner: first definition'\n    else:\n        def inner() -> str:\n            return 'f.inner: second definition'\n    return inner()\n\n[out]\ndef inner_a_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef inner_a_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.inner_a_obj\n    r0 :: __main__.a_env\n    r1 :: int\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.num\n    return r1\ndef a(num):\n    num :: int\n    r0 :: __main__.a_env\n    r1 :: bool\n    r2 :: __main__.inner_a_obj\n    r3 :: bool\n    inner, r4 :: object\n    r5 :: int\nL0:\n    r0 = a_env()\n    r0.num = num; r1 = is_error\n    r2 = inner_a_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    inner = r2\n    r4 = PyObject_Vectorcall(inner, 0, 0, 0)\n    r5 = unbox(int, r4)\n    return r5\ndef inner_b_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef inner_b_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.inner_b_obj\n    r0 :: __main__.b_env\n    r1 :: bool\n    foo, r2 :: int\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r0.num = 8; r1 = is_error\n    foo = 12\n    r2 = r0.num\n    return r2\ndef b():\n    r0 :: __main__.b_env\n    r1 :: bool\n    r2 :: __main__.inner_b_obj\n    r3 :: bool\n    inner, r4 :: object\n    r5, r6, r7 :: int\nL0:\n    r0 = b_env()\n    r0.num = 6; r1 = is_error\n    r2 = inner_b_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    inner = r2\n    r4 = PyObject_Vectorcall(inner, 0, 0, 0)\n    r5 = unbox(int, r4)\n    r6 = r0.num\n    r7 = CPyTagged_Add(r5, r6)\n    return r7\ndef inner_c_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef inner_c_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.inner_c_obj\n    r0 :: __main__.c_env\n    r1 :: str\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = 'f.inner: first definition'\n    return r1\ndef inner_c_obj_0.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef inner_c_obj_0.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.inner_c_obj_0\n    r0 :: __main__.c_env\n    r1 :: str\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = 'f.inner: second definition'\n    return r1\ndef c(flag):\n    flag :: bool\n    r0 :: __main__.c_env\n    r1 :: __main__.inner_c_obj\n    r2 :: bool\n    inner :: object\n    r3 :: __main__.inner_c_obj_0\n    r4 :: bool\n    r5 :: object\n    r6 :: str\nL0:\n    r0 = c_env()\n    if flag goto L1 else goto L2 :: bool\nL1:\n    r1 = inner_c_obj()\n    r1.__mypyc_env__ = r0; r2 = is_error\n    inner = r1\n    goto L3\nL2:\n    r3 = inner_c_obj_0()\n    r3.__mypyc_env__ = r0; r4 = is_error\n    inner = r3\nL3:\n    r5 = PyObject_Vectorcall(inner, 0, 0, 0)\n    r6 = cast(str, r5)\n    return r6\n\n[case testSpecialNested]\ndef a() -> int:\n    x = 1\n    def b() -> int:\n        x += 1\n        def c() -> int:\n            return x\n        return c()\n    return b()\n\n[out]\ndef c_a_b_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef c_a_b_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.c_a_b_obj\n    r0 :: __main__.b_a_env\n    r1 :: __main__.a_env\n    r2 :: int\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.__mypyc_env__\n    r2 = r1.x\n    return r2\ndef b_a_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef b_a_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.b_a_obj\n    r0 :: __main__.a_env\n    r1 :: __main__.b_a_env\n    r2 :: bool\n    r3, r4 :: int\n    r5 :: bool\n    r6 :: __main__.c_a_b_obj\n    r7 :: bool\n    c, r8 :: object\n    r9 :: int\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = b_a_env()\n    r1.__mypyc_env__ = r0; r2 = is_error\n    r3 = r0.x\n    r4 = CPyTagged_Add(r3, 2)\n    r0.x = r4; r5 = is_error\n    r6 = c_a_b_obj()\n    r6.__mypyc_env__ = r1; r7 = is_error\n    c = r6\n    r8 = PyObject_Vectorcall(c, 0, 0, 0)\n    r9 = unbox(int, r8)\n    return r9\ndef a():\n    r0 :: __main__.a_env\n    r1 :: bool\n    r2 :: __main__.b_a_obj\n    r3 :: bool\n    b, r4 :: object\n    r5 :: int\nL0:\n    r0 = a_env()\n    r0.x = 2; r1 = is_error\n    r2 = b_a_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    b = r2\n    r4 = PyObject_Vectorcall(b, 0, 0, 0)\n    r5 = unbox(int, r4)\n    return r5\n\n[case testNestedFunctionInsideStatements]\ndef f(flag: bool) -> str:\n    if flag:\n        def inner() -> str:\n            return 'f.inner: first definition'\n    else:\n        def inner() -> str:\n            return 'f.inner: second definition'\n    return inner()\n[out]\ndef inner_f_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef inner_f_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.inner_f_obj\n    r0 :: __main__.f_env\n    r1 :: str\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = 'f.inner: first definition'\n    return r1\ndef inner_f_obj_0.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef inner_f_obj_0.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.inner_f_obj_0\n    r0 :: __main__.f_env\n    r1 :: str\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = 'f.inner: second definition'\n    return r1\ndef f(flag):\n    flag :: bool\n    r0 :: __main__.f_env\n    r1 :: __main__.inner_f_obj\n    r2 :: bool\n    inner :: object\n    r3 :: __main__.inner_f_obj_0\n    r4 :: bool\n    r5 :: object\n    r6 :: str\nL0:\n    r0 = f_env()\n    if flag goto L1 else goto L2 :: bool\nL1:\n    r1 = inner_f_obj()\n    r1.__mypyc_env__ = r0; r2 = is_error\n    inner = r1\n    goto L3\nL2:\n    r3 = inner_f_obj_0()\n    r3.__mypyc_env__ = r0; r4 = is_error\n    inner = r3\nL3:\n    r5 = PyObject_Vectorcall(inner, 0, 0, 0)\n    r6 = cast(str, r5)\n    return r6\n\n[case testNestedFunctionsCallEachOther]\nfrom typing import Callable, List\n\ndef f(a: int) -> int:\n    def foo() -> int:\n        return a + 1\n\n    def bar() -> int:\n        return foo()\n\n    def baz(n: int) -> int:\n        if n == 0:\n            return 0\n        return n + baz(n - 1)\n\n    return bar() + baz(a)\n\n[out]\ndef foo_f_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef foo_f_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.foo_f_obj\n    r0 :: __main__.f_env\n    r1, r2 :: int\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.a\n    r2 = CPyTagged_Add(r1, 2)\n    return r2\ndef bar_f_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef bar_f_obj.__call__(__mypyc_self__):\n    __mypyc_self__ :: __main__.bar_f_obj\n    r0 :: __main__.f_env\n    r1, r2 :: object\n    r3 :: int\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.foo\n    r2 = PyObject_Vectorcall(r1, 0, 0, 0)\n    r3 = unbox(int, r2)\n    return r3\ndef baz_f_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef baz_f_obj.__call__(__mypyc_self__, n):\n    __mypyc_self__ :: __main__.baz_f_obj\n    n :: int\n    r0 :: __main__.f_env\n    r1 :: bit\n    r2 :: int\n    r3, r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7 :: object\n    r8, r9 :: int\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = int_eq n, 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return 0\nL2:\n    r2 = CPyTagged_Subtract(n, 2)\n    r3 = r0.baz\n    r4 = box(int, r2)\n    r5 = [r4]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r3, r6, 1, 0)\n    keep_alive r4\n    r8 = unbox(int, r7)\n    r9 = CPyTagged_Add(n, r8)\n    return r9\ndef f(a):\n    a :: int\n    r0 :: __main__.f_env\n    r1 :: bool\n    r2 :: __main__.foo_f_obj\n    r3, r4 :: bool\n    r5 :: __main__.bar_f_obj\n    r6, r7 :: bool\n    r8 :: __main__.baz_f_obj\n    r9, r10 :: bool\n    r11, r12 :: object\n    r13, r14 :: int\n    r15, r16 :: object\n    r17 :: object[1]\n    r18 :: object_ptr\n    r19 :: object\n    r20, r21 :: int\nL0:\n    r0 = f_env()\n    r0.a = a; r1 = is_error\n    r2 = foo_f_obj()\n    r2.__mypyc_env__ = r0; r3 = is_error\n    r0.foo = r2; r4 = is_error\n    r5 = bar_f_obj()\n    r5.__mypyc_env__ = r0; r6 = is_error\n    r0.bar = r5; r7 = is_error\n    r8 = baz_f_obj()\n    r8.__mypyc_env__ = r0; r9 = is_error\n    r0.baz = r8; r10 = is_error\n    r11 = r0.bar\n    r12 = PyObject_Vectorcall(r11, 0, 0, 0)\n    r13 = unbox(int, r12)\n    r14 = r0.a\n    r15 = r0.baz\n    r16 = box(int, r14)\n    r17 = [r16]\n    r18 = load_address r17\n    r19 = PyObject_Vectorcall(r15, r18, 1, 0)\n    keep_alive r16\n    r20 = unbox(int, r19)\n    r21 = CPyTagged_Add(r13, r20)\n    return r21\n\n[case testLambdas]\ndef f(x: int, y: int) -> None:\n    s = lambda a, b: a + b\n    t = lambda a, b: s(a, b)\n    return t(x, y)\n\n[out]\ndef __mypyc_lambda__0_f_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef __mypyc_lambda__0_f_obj.__call__(__mypyc_self__, a, b):\n    __mypyc_self__ :: __main__.__mypyc_lambda__0_f_obj\n    a, b :: object\n    r0 :: __main__.f_env\n    r1 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = PyNumber_Add(a, b)\n    return r1\ndef __mypyc_lambda__1_f_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef __mypyc_lambda__1_f_obj.__call__(__mypyc_self__, a, b):\n    __mypyc_self__ :: __main__.__mypyc_lambda__1_f_obj\n    a, b :: object\n    r0 :: __main__.f_env\n    r1 :: object\n    r2 :: object[2]\n    r3 :: object_ptr\n    r4 :: object\nL0:\n    r0 = __mypyc_self__.__mypyc_env__\n    r1 = r0.s\n    r2 = [a, b]\n    r3 = load_address r2\n    r4 = PyObject_Vectorcall(r1, r3, 2, 0)\n    keep_alive a, b\n    return r4\ndef f(x, y):\n    x, y :: int\n    r0 :: __main__.f_env\n    r1 :: __main__.__mypyc_lambda__0_f_obj\n    r2, r3 :: bool\n    r4 :: __main__.__mypyc_lambda__1_f_obj\n    r5 :: bool\n    t, r6, r7 :: object\n    r8 :: object[2]\n    r9 :: object_ptr\n    r10 :: object\n    r11 :: None\nL0:\n    r0 = f_env()\n    r1 = __mypyc_lambda__0_f_obj()\n    r1.__mypyc_env__ = r0; r2 = is_error\n    r0.s = r1; r3 = is_error\n    r4 = __mypyc_lambda__1_f_obj()\n    r4.__mypyc_env__ = r0; r5 = is_error\n    t = r4\n    r6 = box(int, x)\n    r7 = box(int, y)\n    r8 = [r6, r7]\n    r9 = load_address r8\n    r10 = PyObject_Vectorcall(t, r9, 2, 0)\n    keep_alive r6, r7\n    r11 = unbox(None, r10)\n    return r11\n\n[case testRecursiveFunction]\nfrom typing import Callable\n\ndef baz(n: int) -> int:\n    if n == 0:\n        return 0\n    return n + baz(n - 1)\n\n[out]\ndef baz(n):\n    n :: int\n    r0 :: bit\n    r1, r2, r3 :: int\nL0:\n    r0 = int_eq n, 0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 0\nL2:\n    r1 = CPyTagged_Subtract(n, 2)\n    r2 = baz(r1)\n    r3 = CPyTagged_Add(n, r2)\n    return r3\n"
  },
  {
    "path": "mypyc/test-data/irbuild-optional.test",
    "content": "[case testIsNone]\nfrom typing import Optional\n\nclass A: pass\n\ndef f(x: Optional[A]) -> int:\n    if x is None:\n        return 1\n    return 2\n[out]\ndef f(x):\n    x :: union[__main__.A, None]\n    r0 :: object\n    r1 :: bit\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 4\n\n[case testIsNotNone]\nfrom typing import Optional\n\nclass A: pass\n\ndef f(x: Optional[A]) -> int:\n    if x is not None:\n        return 1\n    return 2\n[out]\ndef f(x):\n    x :: union[__main__.A, None]\n    r0 :: object\n    r1 :: bit\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x != r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 4\n\n[case testIsTruthy]\nfrom typing import Optional\n\nclass A: pass\n\ndef f(x: Optional[A]) -> int:\n    if x:\n        return 1\n    return 2\n[out]\ndef f(x):\n    x :: union[__main__.A, None]\n    r0 :: object\n    r1 :: bit\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x != r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 4\n\n[case testIsTruthyOverride]\nfrom typing import Optional\n\nclass A: pass\n\nclass B(A):\n    def __bool__(self) -> bool:\n        return False\n\n\ndef f(x: Optional[A]) -> int:\n    if x:\n        return 1\n    return 2\n[out]\ndef B.__bool__(self):\n    self :: __main__.B\nL0:\n    return 0\ndef f(x):\n    x :: union[__main__.A, None]\n    r0 :: object\n    r1 :: bit\n    r2 :: __main__.A\n    r3 :: i32\n    r4 :: bit\n    r5 :: bool\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x != r0\n    if r1 goto L1 else goto L3 :: bool\nL1:\n    r2 = cast(__main__.A, x)\n    r3 = PyObject_IsTrue(r2)\n    r4 = r3 >= 0 :: signed\n    r5 = truncate r3: i32 to builtins.bool\n    if r5 goto L2 else goto L3 :: bool\nL2:\n    return 2\nL3:\n    return 4\n\n[case testAssignToOptional]\nfrom typing import Optional\n\nclass A:\n    a: Optional[int]\n\ndef f(x: Optional[A], y: Optional[A], z: Optional[int]) -> None:\n    x = None\n    x = A()\n    x = y\n    z = 1\n    a = A()\n    a.a = 1\n    a.a = None\n[out]\ndef f(x, y, z):\n    x, y :: union[__main__.A, None]\n    z :: union[int, None]\n    r0 :: object\n    r1 :: __main__.A\n    r2 :: object\n    r3, a :: __main__.A\n    r4 :: object\n    r5 :: bool\n    r6 :: object\n    r7 :: bool\nL0:\n    r0 = box(None, 1)\n    x = r0\n    r1 = A()\n    x = r1\n    x = y\n    r2 = object 1\n    z = r2\n    r3 = A()\n    a = r3\n    r4 = object 1\n    a.a = r4; r5 = is_error\n    r6 = box(None, 1)\n    a.a = r6; r7 = is_error\n    return 1\n\n[case testBoxOptionalListItem]\nfrom typing import List, Optional\n\ndef f(x: List[Optional[int]]) -> None:\n    x[0] = 0\n    x[1] = None\n[out]\ndef f(x):\n    x :: list\n    r0 :: object\n    r1 :: bit\n    r2 :: object\n    r3 :: bit\nL0:\n    r0 = object 0\n    r1 = CPyList_SetItem(x, 0, r0)\n    r2 = box(None, 1)\n    r3 = CPyList_SetItem(x, 2, r2)\n    return 1\n\n[case testNarrowDownFromOptional]\nfrom typing import Optional\n\nclass A: pass\n\ndef f(x: Optional[A]) -> A:\n    y = A()\n    if x is not None:\n        y = x\n        return x\n    return y\n[out]\ndef f(x):\n    x :: union[__main__.A, None]\n    r0, y :: __main__.A\n    r1 :: object\n    r2 :: bit\n    r3, r4 :: __main__.A\nL0:\n    r0 = A()\n    y = r0\n    r1 = load_address _Py_NoneStruct\n    r2 = x != r1\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = cast(__main__.A, x)\n    y = r3\n    r4 = cast(__main__.A, x)\n    return r4\nL2:\n    return y\n\n[case testPartialOptionalType]\ndef f(y: int) -> None:\n    x = None\n    if y == 1:\n        x = y\n    if x is not None:\n        y = x\n[out]\ndef f(y):\n    y :: int\n    r0 :: object\n    x :: union[int, None]\n    r1 :: bit\n    r2, r3 :: object\n    r4 :: bit\n    r5 :: int\nL0:\n    r0 = box(None, 1)\n    x = r0\n    r1 = int_eq y, 2\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = box(int, y)\n    x = r2\nL2:\n    r3 = load_address _Py_NoneStruct\n    r4 = x != r3\n    if r4 goto L3 else goto L4 :: bool\nL3:\n    r5 = unbox(int, x)\n    y = r5\nL4:\n    return 1\n\n[case testUnionType]\nfrom typing import Union\n\nclass A:\n    a: int\n\ndef f(x: Union[int, A]) -> int:\n    if isinstance(x, int):\n        return x + 1\n    else:\n        return x.a\n[out]\ndef f(x):\n    x :: union[int, __main__.A]\n    r0 :: bit\n    r1, r2 :: int\n    r3 :: __main__.A\n    r4 :: int\nL0:\n    r0 = PyLong_Check(x)\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = unbox(int, x)\n    r2 = CPyTagged_Add(r1, 2)\n    return r2\nL2:\n    r3 = borrow cast(__main__.A, x)\n    r4 = r3.a\n    keep_alive x\n    return r4\nL3:\n    unreachable\n\n[case testUnionTypeInList]\nfrom typing import List, Union\n\ndef f(x: List[Union[int, str]]) -> object:\n    return x[0]\n[out]\ndef f(x):\n    x :: list\n    r0 :: object\n    r1 :: union[int, str]\nL0:\n    r0 = CPyList_GetItemShort(x, 0)\n    r1 = cast(union[int, str], r0)\n    return r1\n\n[case testUnionAttributeAccess]\nfrom typing import Union\nclass A:\n    a: int\nclass B:\n    a: object\ndef get(o: Union[A, B]) -> None:\n    z = o.a\ndef set(o: Union[A, B], s: str) -> None:\n    o.a = s\n\n[out]\ndef get(o):\n    o :: union[__main__.A, __main__.B]\n    r0 :: object\n    r1 :: ptr\n    r2 :: object\n    r3 :: bit\n    r4 :: __main__.A\n    r5 :: int\n    r6, r7 :: object\n    r8 :: __main__.B\n    r9, z :: object\nL0:\n    r0 = __main__.A :: type\n    r1 = get_element_ptr o ob_type :: PyObject\n    r2 = borrow load_mem r1 :: builtins.object*\n    keep_alive o\n    r3 = r2 == r0\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = cast(__main__.A, o)\n    r5 = r4.a\n    r6 = box(int, r5)\n    r7 = r6\n    goto L3\nL2:\n    r8 = cast(__main__.B, o)\n    r9 = r8.a\n    r7 = r9\nL3:\n    z = r7\n    return 1\ndef set(o, s):\n    o :: union[__main__.A, __main__.B]\n    s, r0 :: str\n    r1 :: i32\n    r2 :: bit\nL0:\n    r0 = 'a'\n    r1 = PyObject_SetAttr(o, r0, s)\n    r2 = r1 >= 0 :: signed\n    return 1\n\n[case testUnionMethodCall]\nfrom typing import Union\nclass A:\n    def f(self, x: int) -> int:\n        return x\nclass B:\n    def f(self, x: object) -> object:\n        return x\nclass C:\n    def f(self, x: object) -> int:\n        return 0\ndef g(o: Union[A, B, C]) -> None:\n    z = o.f(1)\n\n[out]\ndef A.f(self, x):\n    self :: __main__.A\n    x :: int\nL0:\n    return x\ndef B.f(self, x):\n    self :: __main__.B\n    x :: object\nL0:\n    return x\ndef C.f(self, x):\n    self :: __main__.C\n    x :: object\nL0:\n    return 0\ndef g(o):\n    o :: union[__main__.A, __main__.B, __main__.C]\n    r0 :: object\n    r1 :: ptr\n    r2 :: object\n    r3 :: bit\n    r4 :: __main__.A\n    r5 :: int\n    r6, r7, r8 :: object\n    r9 :: ptr\n    r10 :: object\n    r11 :: bit\n    r12 :: __main__.B\n    r13, r14 :: object\n    r15 :: __main__.C\n    r16 :: object\n    r17 :: int\n    r18, z :: object\nL0:\n    r0 = __main__.A :: type\n    r1 = get_element_ptr o ob_type :: PyObject\n    r2 = borrow load_mem r1 :: builtins.object*\n    keep_alive o\n    r3 = r2 == r0\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = cast(__main__.A, o)\n    r5 = r4.f(2)\n    r6 = box(int, r5)\n    r7 = r6\n    goto L5\nL2:\n    r8 = __main__.B :: type\n    r9 = get_element_ptr o ob_type :: PyObject\n    r10 = borrow load_mem r9 :: builtins.object*\n    keep_alive o\n    r11 = r10 == r8\n    if r11 goto L3 else goto L4 :: bool\nL3:\n    r12 = cast(__main__.B, o)\n    r13 = object 1\n    r14 = r12.f(r13)\n    r7 = r14\n    goto L5\nL4:\n    r15 = cast(__main__.C, o)\n    r16 = object 1\n    r17 = r15.f(r16)\n    r18 = box(int, r17)\n    r7 = r18\nL5:\n    z = r7\n    return 1\n\n[case testUnionWithNonNativeItem]\nfrom typing import Union\nfrom m import B\n\nclass A:\n    x: int\n\ndef f(o: Union[A, B]) -> None:\n    o.x\n\ndef g(o: Union[B, A]) -> None:\n    o.x\n\n[file m.py]\nclass B:\n    x: int\n\n[out]\ndef f(o):\n    o :: union[__main__.A, object]\n    r0 :: object\n    r1 :: ptr\n    r2 :: object\n    r3 :: bit\n    r4 :: __main__.A\n    r5, r6 :: int\n    r7 :: object\n    r8 :: str\n    r9 :: object\n    r10 :: int\nL0:\n    r0 = __main__.A :: type\n    r1 = get_element_ptr o ob_type :: PyObject\n    r2 = borrow load_mem r1 :: builtins.object*\n    keep_alive o\n    r3 = r2 == r0\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = cast(__main__.A, o)\n    r5 = r4.x\n    r6 = r5\n    goto L3\nL2:\n    r7 = o\n    r8 = 'x'\n    r9 = CPyObject_GetAttr(r7, r8)\n    r10 = unbox(int, r9)\n    r6 = r10\nL3:\n    return 1\ndef g(o):\n    o :: union[object, __main__.A]\n    r0 :: object\n    r1 :: ptr\n    r2 :: object\n    r3 :: bit\n    r4 :: __main__.A\n    r5, r6 :: int\n    r7 :: object\n    r8 :: str\n    r9 :: object\n    r10 :: int\nL0:\n    r0 = __main__.A :: type\n    r1 = get_element_ptr o ob_type :: PyObject\n    r2 = borrow load_mem r1 :: builtins.object*\n    keep_alive o\n    r3 = r2 == r0\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = cast(__main__.A, o)\n    r5 = r4.x\n    r6 = r5\n    goto L3\nL2:\n    r7 = o\n    r8 = 'x'\n    r9 = CPyObject_GetAttr(r7, r8)\n    r10 = unbox(int, r9)\n    r6 = r10\nL3:\n    return 1\n\n[case testUnionWithNoNativeItems]\nfrom typing import Union\nfrom m import A, B\n\ndef f(o: Union[A, B]) -> None:\n    o.x\n\n[file m.py]\nclass A:\n    x: object\nclass B:\n    x: int\n\n[out]\ndef f(o):\n    o :: object\n    r0 :: str\n    r1 :: object\nL0:\n    r0 = 'x'\n    r1 = CPyObject_GetAttr(o, r0)\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-python314.test",
    "content": "[case testTemplateStringNotSupported_python3_14]\ndef f() -> object:\n    return t\"value={1}\"  # E: Template strings are not supported by mypyc\n"
  },
  {
    "path": "mypyc/test-data/irbuild-set.test",
    "content": "[case testNewSet]\nfrom typing import Set\ndef f() -> Set[int]:\n    return {1, 2, 3}\n[out]\ndef f():\n    r0 :: set\n    r1 :: object\n    r2 :: i32\n    r3 :: bit\n    r4 :: object\n    r5 :: i32\n    r6 :: bit\n    r7 :: object\n    r8 :: i32\n    r9 :: bit\nL0:\n    r0 = PySet_New(0)\n    r1 = object 1\n    r2 = PySet_Add(r0, r1)\n    r3 = r2 >= 0 :: signed\n    r4 = object 2\n    r5 = PySet_Add(r0, r4)\n    r6 = r5 >= 0 :: signed\n    r7 = object 3\n    r8 = PySet_Add(r0, r7)\n    r9 = r8 >= 0 :: signed\n    return r0\n\n[case testNewEmptySet]\nfrom typing import Set\ndef f() -> Set[int]:\n    return set()\n[out]\ndef f():\n    r0 :: set\nL0:\n    r0 = PySet_New(0)\n    return r0\n\n[case testNewSetFromIterable]\nfrom typing import Set, List, TypeVar\n\nT = TypeVar(\"T\")\n\ndef f(l: List[T]) -> Set[T]:\n    return set(l)\n[out]\ndef f(l):\n    l :: list\n    r0 :: set\nL0:\n    r0 = PySet_New(l)\n    return r0\n\n[case testNewSetFromIterable2]\ndef f(x: int) -> int:\n    return x\n\ndef test1() -> None:\n    tmp_list = [1, 3, 5]\n    a = set(f(x) for x in tmp_list)\n\ndef test2() -> None:\n    tmp_tuple = (1, 3, 5)\n    b = set(f(x) for x in tmp_tuple)\n\ndef test3() -> None:\n    tmp_dict = {1: '1', 3: '3', 5: '5'}\n    c = set(f(x) for x in tmp_dict)\n\ndef test4() -> None:\n    d = set(f(x) for x in range(1, 6, 2))\n\ndef test5() -> None:\n    e = set((f(x) for x in range(1, 6, 2)))\n[out]\ndef f(x):\n    x :: int\nL0:\n    return x\ndef test1():\n    r0 :: list\n    r1, r2, r3 :: object\n    r4 :: ptr\n    tmp_list :: list\n    r5 :: set\n    r6, r7 :: native_int\n    r8 :: bit\n    r9 :: object\n    r10, x, r11 :: int\n    r12 :: object\n    r13 :: i32\n    r14 :: bit\n    r15 :: native_int\n    a :: set\nL0:\n    r0 = PyList_New(3)\n    r1 = object 1\n    r2 = object 3\n    r3 = object 5\n    r4 = list_items r0\n    buf_init_item r4, 0, r1\n    buf_init_item r4, 1, r2\n    buf_init_item r4, 2, r3\n    keep_alive r0\n    tmp_list = r0\n    r5 = PySet_New(0)\n    r6 = 0\nL1:\n    r7 = var_object_size tmp_list\n    r8 = r6 < r7 :: signed\n    if r8 goto L2 else goto L4 :: bool\nL2:\n    r9 = list_get_item_unsafe tmp_list, r6\n    r10 = unbox(int, r9)\n    x = r10\n    r11 = f(x)\n    r12 = box(int, r11)\n    r13 = PySet_Add(r5, r12)\n    r14 = r13 >= 0 :: signed\nL3:\n    r15 = r6 + 1\n    r6 = r15\n    goto L1\nL4:\n    a = r5\n    return 1\ndef test2():\n    r0, tmp_tuple :: tuple[int, int, int]\n    r1 :: set\n    r2, r3, r4 :: object\n    r5, x, r6 :: int\n    r7 :: object\n    r8 :: i32\n    r9, r10 :: bit\n    b :: set\nL0:\n    r0 = (2, 6, 10)\n    tmp_tuple = r0\n    r1 = PySet_New(0)\n    r2 = box(tuple[int, int, int], tmp_tuple)\n    r3 = PyObject_GetIter(r2)\nL1:\n    r4 = PyIter_Next(r3)\n    if is_error(r4) goto L4 else goto L2\nL2:\n    r5 = unbox(int, r4)\n    x = r5\n    r6 = f(x)\n    r7 = box(int, r6)\n    r8 = PySet_Add(r1, r7)\n    r9 = r8 >= 0 :: signed\nL3:\n    goto L1\nL4:\n    r10 = CPy_NoErrOccurred()\nL5:\n    b = r1\n    return 1\ndef test3():\n    r0, r1, r2 :: str\n    r3, r4, r5 :: object\n    r6, tmp_dict :: dict\n    r7 :: set\n    r8 :: short_int\n    r9 :: native_int\n    r10 :: object\n    r11 :: tuple[bool, short_int, object]\n    r12 :: short_int\n    r13 :: bool\n    r14 :: object\n    r15, x, r16 :: int\n    r17 :: object\n    r18 :: i32\n    r19, r20, r21 :: bit\n    c :: set\nL0:\n    r0 = '1'\n    r1 = '3'\n    r2 = '5'\n    r3 = object 1\n    r4 = object 3\n    r5 = object 5\n    r6 = CPyDict_Build(3, r3, r0, r4, r1, r5, r2)\n    tmp_dict = r6\n    r7 = PySet_New(0)\n    r8 = 0\n    r9 = PyDict_Size(tmp_dict)\n    r10 = CPyDict_GetKeysIter(tmp_dict)\nL1:\n    r11 = CPyDict_NextKey(r10, r8)\n    r12 = r11[1]\n    r8 = r12\n    r13 = r11[0]\n    if r13 goto L2 else goto L4 :: bool\nL2:\n    r14 = r11[2]\n    r15 = unbox(int, r14)\n    x = r15\n    r16 = f(x)\n    r17 = box(int, r16)\n    r18 = PySet_Add(r7, r17)\n    r19 = r18 >= 0 :: signed\nL3:\n    r20 = CPyDict_CheckSize(tmp_dict, r9)\n    goto L1\nL4:\n    r21 = CPy_NoErrOccurred()\nL5:\n    c = r7\n    return 1\ndef test4():\n    r0 :: set\n    r1 :: short_int\n    x :: int\n    r2 :: bit\n    r3 :: int\n    r4 :: object\n    r5 :: i32\n    r6 :: bit\n    r7 :: short_int\n    d :: set\nL0:\n    r0 = PySet_New(0)\n    r1 = 2\n    x = r1\nL1:\n    r2 = int_lt r1, 12\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = f(x)\n    r4 = box(int, r3)\n    r5 = PySet_Add(r0, r4)\n    r6 = r5 >= 0 :: signed\nL3:\n    r7 = r1 + 4\n    r1 = r7\n    x = r7\n    goto L1\nL4:\n    d = r0\n    return 1\ndef test5():\n    r0 :: set\n    r1 :: short_int\n    x :: int\n    r2 :: bit\n    r3 :: int\n    r4 :: object\n    r5 :: i32\n    r6 :: bit\n    r7 :: short_int\n    e :: set\nL0:\n    r0 = PySet_New(0)\n    r1 = 2\n    x = r1\nL1:\n    r2 = int_lt r1, 12\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = f(x)\n    r4 = box(int, r3)\n    r5 = PySet_Add(r0, r4)\n    r6 = r5 >= 0 :: signed\nL3:\n    r7 = r1 + 4\n    r1 = r7\n    x = r7\n    goto L1\nL4:\n    e = r0\n    return 1\n\n[case testNewSetFromIterable3]\ndef f1(x: int) -> int:\n    return x\n\ndef f2(x: int) -> int:\n    return x * 10\n\ndef f3(x: int) -> int:\n    return x + 1\n\ndef test() -> None:\n    tmp_list = [1, 2, 3, 4, 5]\n    a = set(f3(x) for x in (f2(y) for y in (f1(z) for z in tmp_list if z < 4)))\n[out]\ndef f1(x):\n    x :: int\nL0:\n    return x\ndef f2(x):\n    x, r0 :: int\nL0:\n    r0 = CPyTagged_Multiply(x, 20)\n    return r0\ndef f3(x):\n    x, r0 :: int\nL0:\n    r0 = CPyTagged_Add(x, 2)\n    return r0\ndef test():\n    r0 :: list\n    r1, r2, r3, r4, r5 :: object\n    r6 :: ptr\n    tmp_list :: list\n    r7 :: set\n    r8, r9 :: list\n    r10, r11 :: native_int\n    r12 :: bit\n    r13 :: object\n    r14, z :: int\n    r15 :: bit\n    r16 :: int\n    r17 :: object\n    r18 :: i32\n    r19 :: bit\n    r20 :: native_int\n    r21, r22, r23 :: object\n    r24, y, r25 :: int\n    r26 :: object\n    r27 :: i32\n    r28, r29 :: bit\n    r30, r31, r32 :: object\n    r33, x, r34 :: int\n    r35 :: object\n    r36 :: i32\n    r37, r38 :: bit\n    a :: set\nL0:\n    r0 = PyList_New(5)\n    r1 = object 1\n    r2 = object 2\n    r3 = object 3\n    r4 = object 4\n    r5 = object 5\n    r6 = list_items r0\n    buf_init_item r6, 0, r1\n    buf_init_item r6, 1, r2\n    buf_init_item r6, 2, r3\n    buf_init_item r6, 3, r4\n    buf_init_item r6, 4, r5\n    keep_alive r0\n    tmp_list = r0\n    r7 = PySet_New(0)\n    r8 = PyList_New(0)\n    r9 = PyList_New(0)\n    r10 = 0\nL1:\n    r11 = var_object_size tmp_list\n    r12 = r10 < r11 :: signed\n    if r12 goto L2 else goto L6 :: bool\nL2:\n    r13 = list_get_item_unsafe tmp_list, r10\n    r14 = unbox(int, r13)\n    z = r14\n    r15 = int_lt z, 8\n    if r15 goto L4 else goto L3 :: bool\nL3:\n    goto L5\nL4:\n    r16 = f1(z)\n    r17 = box(int, r16)\n    r18 = PyList_Append(r9, r17)\n    r19 = r18 >= 0 :: signed\nL5:\n    r20 = r10 + 1\n    r10 = r20\n    goto L1\nL6:\n    r21 = PyObject_GetIter(r9)\n    r22 = PyObject_GetIter(r21)\nL7:\n    r23 = PyIter_Next(r22)\n    if is_error(r23) goto L10 else goto L8\nL8:\n    r24 = unbox(int, r23)\n    y = r24\n    r25 = f2(y)\n    r26 = box(int, r25)\n    r27 = PyList_Append(r8, r26)\n    r28 = r27 >= 0 :: signed\nL9:\n    goto L7\nL10:\n    r29 = CPy_NoErrOccurred()\nL11:\n    r30 = PyObject_GetIter(r8)\n    r31 = PyObject_GetIter(r30)\nL12:\n    r32 = PyIter_Next(r31)\n    if is_error(r32) goto L15 else goto L13\nL13:\n    r33 = unbox(int, r32)\n    x = r33\n    r34 = f3(x)\n    r35 = box(int, r34)\n    r36 = PySet_Add(r7, r35)\n    r37 = r36 >= 0 :: signed\nL14:\n    goto L12\nL15:\n    r38 = CPy_NoErrOccurred()\nL16:\n    a = r7\n    return 1\n\n[case testSetSize]\nfrom typing import Set\ndef f() -> int:\n    return len({1, 2, 3})\n[out]\ndef f():\n    r0 :: set\n    r1 :: object\n    r2 :: i32\n    r3 :: bit\n    r4 :: object\n    r5 :: i32\n    r6 :: bit\n    r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: ptr\n    r11 :: native_int\n    r12 :: short_int\nL0:\n    r0 = PySet_New(0)\n    r1 = object 1\n    r2 = PySet_Add(r0, r1)\n    r3 = r2 >= 0 :: signed\n    r4 = object 2\n    r5 = PySet_Add(r0, r4)\n    r6 = r5 >= 0 :: signed\n    r7 = object 3\n    r8 = PySet_Add(r0, r7)\n    r9 = r8 >= 0 :: signed\n    r10 = get_element_ptr r0 used :: PySetObject\n    r11 = load_mem r10 :: native_int*\n    keep_alive r0\n    r12 = r11 << 1\n    return r12\n\n[case testSetContains]\nfrom typing import Set\ndef f() -> bool:\n    x = {3, 4}\n    return (5 in x)\n[out]\ndef f():\n    r0 :: set\n    r1 :: object\n    r2 :: i32\n    r3 :: bit\n    r4 :: object\n    r5 :: i32\n    r6 :: bit\n    x :: set\n    r7 :: object\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\nL0:\n    r0 = PySet_New(0)\n    r1 = object 3\n    r2 = PySet_Add(r0, r1)\n    r3 = r2 >= 0 :: signed\n    r4 = object 4\n    r5 = PySet_Add(r0, r4)\n    r6 = r5 >= 0 :: signed\n    x = r0\n    r7 = object 5\n    r8 = PySet_Contains(x, r7)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    return r10\n\n[case testSetRemove]\nfrom typing import Set\ndef f() -> Set[int]:\n    x = set()  # type: Set[int]\n    x.remove(1)\n    return x\n[out]\ndef f():\n    r0, x :: set\n    r1 :: object\n    r2 :: bit\nL0:\n    r0 = PySet_New(0)\n    x = r0\n    r1 = object 1\n    r2 = CPySet_Remove(x, r1)\n    return x\n\n[case testSetDiscard]\nfrom typing import Set\ndef f() -> Set[int]:\n    x = set()  # type: Set[int]\n    x.discard(1)\n    return x\n[out]\ndef f():\n    r0, x :: set\n    r1 :: object\n    r2 :: i32\n    r3 :: bit\nL0:\n    r0 = PySet_New(0)\n    x = r0\n    r1 = object 1\n    r2 = PySet_Discard(x, r1)\n    r3 = r2 >= 0 :: signed\n    return x\n\n[case testSetAdd]\nfrom typing import Set\ndef f() -> Set[int]:\n    x = set()  # type: Set[int]\n    x.add(1)\n    return x\n[out]\ndef f():\n    r0, x :: set\n    r1 :: object\n    r2 :: i32\n    r3 :: bit\nL0:\n    r0 = PySet_New(0)\n    x = r0\n    r1 = object 1\n    r2 = PySet_Add(x, r1)\n    r3 = r2 >= 0 :: signed\n    return x\n\n[case testSetClear]\nfrom typing import Set\ndef f() -> Set[int]:\n    x = set()  # type: Set[int]\n    x.clear()\n    return x\n[out]\ndef f():\n    r0, x :: set\n    r1 :: i32\n    r2 :: bit\nL0:\n    r0 = PySet_New(0)\n    x = r0\n    r1 = PySet_Clear(x)\n    r2 = r1 >= 0 :: signed\n    return x\n\n[case testSetPop]\nfrom typing import Set\ndef f(s : Set[int]) -> int:\n    return s.pop()\n[out]\ndef f(s):\n    s :: set\n    r0 :: object\n    r1 :: int\nL0:\n    r0 = PySet_Pop(s)\n    r1 = unbox(int, r0)\n    return r1\n\n[case testSetUpdate]\nfrom typing import Set, List\ndef update(s: Set[int], x: List[int]) -> None:\n    s.update(x)\n[out]\ndef update(s, x):\n    s :: set\n    x :: list\n    r0 :: i32\n    r1 :: bit\nL0:\n    r0 = _PySet_Update(s, x)\n    r1 = r0 >= 0 :: signed\n    return 1\n\n[case testSetDisplay]\nfrom typing import Set\ndef f(x: Set[int], y: Set[int]) -> Set[int]:\n    return {1, 2, *x, *y, 3}\n[out]\ndef f(x, y):\n    x, y, r0 :: set\n    r1 :: object\n    r2 :: i32\n    r3 :: bit\n    r4 :: object\n    r5 :: i32\n    r6 :: bit\n    r7 :: i32\n    r8 :: bit\n    r9 :: i32\n    r10 :: bit\n    r11 :: object\n    r12 :: i32\n    r13 :: bit\nL0:\n    r0 = PySet_New(0)\n    r1 = object 1\n    r2 = PySet_Add(r0, r1)\n    r3 = r2 >= 0 :: signed\n    r4 = object 2\n    r5 = PySet_Add(r0, r4)\n    r6 = r5 >= 0 :: signed\n    r7 = _PySet_Update(r0, x)\n    r8 = r7 >= 0 :: signed\n    r9 = _PySet_Update(r0, y)\n    r10 = r9 >= 0 :: signed\n    r11 = object 3\n    r12 = PySet_Add(r0, r11)\n    r13 = r12 >= 0 :: signed\n    return r0\n\n[case testOperatorInSetLiteral]\nfrom typing import Final\n\nCONST: Final = \"daylily\"\nnon_const = 10\n\ndef precomputed(i: object) -> bool:\n    return i in {1, 2.0, 1 +2, 4j, \"foo\", b\"bar\", CONST, (None, (27,)), (), False}\ndef not_precomputed_non_final_name(i: int) -> bool:\n    return i in {non_const}\ndef not_precomputed_nested_set(i: int) -> bool:\n    return i in {frozenset({1}), 2}\n[out]\ndef precomputed(i):\n    i :: object\n    r0 :: set\n    r1 :: i32\n    r2 :: bit\n    r3 :: bool\nL0:\n    r0 = frozenset({(), (None, (27,)), 1, 2.0, 3, 4j, False, b'bar', 'daylily', 'foo'})\n    r1 = PySet_Contains(r0, i)\n    r2 = r1 >= 0 :: signed\n    r3 = truncate r1: i32 to builtins.bool\n    return r3\ndef not_precomputed_non_final_name(i):\n    i :: int\n    r0 :: dict\n    r1 :: str\n    r2 :: object\n    r3 :: int\n    r4 :: set\n    r5 :: object\n    r6 :: i32\n    r7 :: bit\n    r8 :: object\n    r9 :: i32\n    r10 :: bit\n    r11 :: bool\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'non_const'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = unbox(int, r2)\n    r4 = PySet_New(0)\n    r5 = box(int, r3)\n    r6 = PySet_Add(r4, r5)\n    r7 = r6 >= 0 :: signed\n    r8 = box(int, i)\n    r9 = PySet_Contains(r4, r8)\n    r10 = r9 >= 0 :: signed\n    r11 = truncate r9: i32 to builtins.bool\n    return r11\ndef not_precomputed_nested_set(i):\n    i :: int\n    r0 :: set\n    r1 :: object\n    r2 :: i32\n    r3 :: bit\n    r4 :: frozenset\n    r5 :: set\n    r6 :: i32\n    r7 :: bit\n    r8 :: object\n    r9 :: i32\n    r10 :: bit\n    r11 :: object\n    r12 :: i32\n    r13 :: bit\n    r14 :: bool\nL0:\n    r0 = PySet_New(0)\n    r1 = object 1\n    r2 = PySet_Add(r0, r1)\n    r3 = r2 >= 0 :: signed\n    r4 = PyFrozenSet_New(r0)\n    r5 = PySet_New(0)\n    r6 = PySet_Add(r5, r4)\n    r7 = r6 >= 0 :: signed\n    r8 = object 2\n    r9 = PySet_Add(r5, r8)\n    r10 = r9 >= 0 :: signed\n    r11 = box(int, i)\n    r12 = PySet_Contains(r5, r11)\n    r13 = r12 >= 0 :: signed\n    r14 = truncate r12: i32 to builtins.bool\n    return r14\n\n[case testForSetLiteral]\nfrom typing import Final\n\nCONST: Final = 10\nnon_const = 20\n\ndef precomputed() -> None:\n    for _ in {\"None\", \"True\", \"False\"}:\n        pass\n\ndef precomputed2() -> None:\n    for _ in {None, False, 1, 2.0, \"4\", b\"5\", (6,), 7j, CONST, CONST + 1}:\n        pass\n\ndef not_precomputed() -> None:\n    for not_optimized in {non_const}:\n        pass\n\n[out]\ndef precomputed():\n    r0 :: set\n    r1, r2 :: object\n    r3 :: str\n    _ :: object\n    r4 :: bit\nL0:\n    r0 = frozenset({'False', 'None', 'True'})\n    r1 = PyObject_GetIter(r0)\nL1:\n    r2 = PyIter_Next(r1)\n    if is_error(r2) goto L4 else goto L2\nL2:\n    r3 = cast(str, r2)\n    _ = r3\nL3:\n    goto L1\nL4:\n    r4 = CPy_NoErrOccurred()\nL5:\n    return 1\ndef precomputed2():\n    r0 :: set\n    r1, r2, _ :: object\n    r3 :: bit\nL0:\n    r0 = frozenset({(6,), 1, 10, 11, 2.0, '4', 7j, False, None, b'5'})\n    r1 = PyObject_GetIter(r0)\nL1:\n    r2 = PyIter_Next(r1)\n    if is_error(r2) goto L4 else goto L2\nL2:\n    _ = r2\nL3:\n    goto L1\nL4:\n    r3 = CPy_NoErrOccurred()\nL5:\n    return 1\ndef not_precomputed():\n    r0 :: dict\n    r1 :: str\n    r2 :: object\n    r3 :: int\n    r4 :: set\n    r5 :: object\n    r6 :: i32\n    r7 :: bit\n    r8, r9 :: object\n    r10, not_optimized :: int\n    r11 :: bit\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'non_const'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = unbox(int, r2)\n    r4 = PySet_New(0)\n    r5 = box(int, r3)\n    r6 = PySet_Add(r4, r5)\n    r7 = r6 >= 0 :: signed\n    r8 = PyObject_GetIter(r4)\nL1:\n    r9 = PyIter_Next(r8)\n    if is_error(r9) goto L4 else goto L2\nL2:\n    r10 = unbox(int, r9)\n    not_optimized = r10\nL3:\n    goto L1\nL4:\n    r11 = CPy_NoErrOccurred()\nL5:\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-singledispatch.test",
    "content": "[case testNativeCallsUsedInDispatchFunction]\nfrom functools import singledispatch\n@singledispatch\ndef f(arg) -> bool:\n    return False\n\n@f.register\ndef g(arg: int) -> bool:\n    return True\n[out]\ndef __mypyc_singledispatch_main_function_f__(arg):\n    arg :: object\nL0:\n    return 0\ndef f_obj.__init__(__mypyc_self__):\n    __mypyc_self__ :: __main__.f_obj\n    r0, r1 :: dict\n    r2 :: str\n    r3 :: i32\n    r4 :: bit\nL0:\n    r0 = PyDict_New()\n    __mypyc_self__.registry = r0\n    r1 = PyDict_New()\n    r2 = 'dispatch_cache'\n    r3 = PyObject_SetAttr(__mypyc_self__, r2, r1)\n    r4 = r3 >= 0 :: signed\n    return 1\ndef f_obj.__call__(__mypyc_self__, arg):\n    __mypyc_self__ :: __main__.f_obj\n    arg :: object\n    r0 :: ptr\n    r1 :: object\n    r2 :: dict\n    r3, r4 :: object\n    r5 :: bit\n    r6, r7 :: object\n    r8 :: str\n    r9 :: object\n    r10 :: dict\n    r11 :: object[2]\n    r12 :: object_ptr\n    r13 :: object\n    r14 :: i32\n    r15 :: bit\n    r16 :: object\n    r17 :: ptr\n    r18 :: object\n    r19 :: bit\n    r20 :: int\n    r21 :: bit\n    r22 :: int\n    r23 :: bool\n    r24 :: object[1]\n    r25 :: object_ptr\n    r26 :: object\n    r27 :: bool\nL0:\n    r0 = get_element_ptr arg ob_type :: PyObject\n    r1 = borrow load_mem r0 :: builtins.object*\n    keep_alive arg\n    r2 = __mypyc_self__.dispatch_cache\n    r3 = CPyDict_GetWithNone(r2, r1)\n    r4 = load_address _Py_NoneStruct\n    r5 = r3 != r4\n    if r5 goto L1 else goto L2 :: bool\nL1:\n    r6 = r3\n    goto L3\nL2:\n    r7 = functools :: module\n    r8 = '_find_impl'\n    r9 = CPyObject_GetAttr(r7, r8)\n    r10 = __mypyc_self__.registry\n    r11 = [r1, r10]\n    r12 = load_address r11\n    r13 = PyObject_Vectorcall(r9, r12, 2, 0)\n    keep_alive r1, r10\n    r14 = PyDict_SetItem(r2, r1, r13)\n    r15 = r14 >= 0 :: signed\n    r6 = r13\nL3:\n    r16 = load_address PyLong_Type\n    r17 = get_element_ptr r6 ob_type :: PyObject\n    r18 = borrow load_mem r17 :: builtins.object*\n    keep_alive r6\n    r19 = r18 == r16\n    if r19 goto L4 else goto L7 :: bool\nL4:\n    r20 = unbox(int, r6)\n    r21 = int_eq r20, 0\n    if r21 goto L5 else goto L6 :: bool\nL5:\n    r22 = unbox(int, arg)\n    r23 = g(r22)\n    return r23\nL6:\n    unreachable\nL7:\n    r24 = [arg]\n    r25 = load_address r24\n    r26 = PyObject_Vectorcall(r6, r25, 1, 0)\n    keep_alive arg\n    r27 = unbox(bool, r26)\n    return r27\ndef f_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef f_obj.register(__mypyc_self__, cls, func):\n    __mypyc_self__ :: __main__.f_obj\n    cls, func, r0 :: object\nL0:\n    r0 = CPySingledispatch_RegisterFunction(__mypyc_self__, cls, func)\n    return r0\ndef f(arg):\n    arg :: object\n    r0 :: dict\n    r1 :: str\n    r2 :: object\n    r3 :: bool\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'f'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = f_obj.__call__(r2, arg)\n    return r3\ndef g(arg):\n    arg :: int\nL0:\n    return 1\n\n[case testCallsToSingledispatchFunctionsAreNative]\nfrom functools import singledispatch\n\n@singledispatch\ndef f(x: object) -> None:\n    pass\n\ndef test():\n    f('a')\n[out]\ndef __mypyc_singledispatch_main_function_f__(x):\n    x :: object\nL0:\n    return 1\ndef f_obj.__init__(__mypyc_self__):\n    __mypyc_self__ :: __main__.f_obj\n    r0, r1 :: dict\n    r2 :: str\n    r3 :: i32\n    r4 :: bit\nL0:\n    r0 = PyDict_New()\n    __mypyc_self__.registry = r0\n    r1 = PyDict_New()\n    r2 = 'dispatch_cache'\n    r3 = PyObject_SetAttr(__mypyc_self__, r2, r1)\n    r4 = r3 >= 0 :: signed\n    return 1\ndef f_obj.__call__(__mypyc_self__, x):\n    __mypyc_self__ :: __main__.f_obj\n    x :: object\n    r0 :: ptr\n    r1 :: object\n    r2 :: dict\n    r3, r4 :: object\n    r5 :: bit\n    r6, r7 :: object\n    r8 :: str\n    r9 :: object\n    r10 :: dict\n    r11 :: object[2]\n    r12 :: object_ptr\n    r13 :: object\n    r14 :: i32\n    r15 :: bit\n    r16 :: object\n    r17 :: ptr\n    r18 :: object\n    r19 :: bit\n    r20 :: int\n    r21 :: object[1]\n    r22 :: object_ptr\n    r23 :: object\n    r24 :: None\nL0:\n    r0 = get_element_ptr x ob_type :: PyObject\n    r1 = borrow load_mem r0 :: builtins.object*\n    keep_alive x\n    r2 = __mypyc_self__.dispatch_cache\n    r3 = CPyDict_GetWithNone(r2, r1)\n    r4 = load_address _Py_NoneStruct\n    r5 = r3 != r4\n    if r5 goto L1 else goto L2 :: bool\nL1:\n    r6 = r3\n    goto L3\nL2:\n    r7 = functools :: module\n    r8 = '_find_impl'\n    r9 = CPyObject_GetAttr(r7, r8)\n    r10 = __mypyc_self__.registry\n    r11 = [r1, r10]\n    r12 = load_address r11\n    r13 = PyObject_Vectorcall(r9, r12, 2, 0)\n    keep_alive r1, r10\n    r14 = PyDict_SetItem(r2, r1, r13)\n    r15 = r14 >= 0 :: signed\n    r6 = r13\nL3:\n    r16 = load_address PyLong_Type\n    r17 = get_element_ptr r6 ob_type :: PyObject\n    r18 = borrow load_mem r17 :: builtins.object*\n    keep_alive r6\n    r19 = r18 == r16\n    if r19 goto L4 else goto L5 :: bool\nL4:\n    r20 = unbox(int, r6)\n    unreachable\nL5:\n    r21 = [x]\n    r22 = load_address r21\n    r23 = PyObject_Vectorcall(r6, r22, 1, 0)\n    keep_alive x\n    r24 = unbox(None, r23)\n    return r24\ndef f_obj.__get__(__mypyc_self__, instance, owner):\n    __mypyc_self__, instance, owner, r0 :: object\n    r1 :: bit\n    r2 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = instance == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    return __mypyc_self__\nL2:\n    r2 = PyMethod_New(__mypyc_self__, instance)\n    return r2\ndef f_obj.register(__mypyc_self__, cls, func):\n    __mypyc_self__ :: __main__.f_obj\n    cls, func, r0 :: object\nL0:\n    r0 = CPySingledispatch_RegisterFunction(__mypyc_self__, cls, func)\n    return r0\ndef f(x):\n    x :: object\n    r0 :: dict\n    r1 :: str\n    r2 :: object\n    r3 :: None\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'f'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = f_obj.__call__(r2, x)\n    return r3\ndef test():\n    r0 :: str\n    r1 :: None\n    r2 :: object\nL0:\n    r0 = 'a'\n    r1 = f(r0)\n    r2 = box(None, 1)\n    return r2\n\n[case registerNestedFunctionError]\nfrom functools import singledispatch\nfrom typing import Any, overload\n\ndef dec(x: Any) -> Any:\n    return x\n\ndef f() -> None:\n    @singledispatch  # E: Nested singledispatch functions not supported\n    def singledispatch_in_func(x: Any) -> None:\n        pass\n\n@dec\ndef g() -> None:\n    @singledispatch  # E: Nested singledispatch functions not supported\n    def singledispatch_in_decorated(x: Any) -> None:\n        pass\n\n@overload\ndef h(x: int) -> None:\n    pass\n@overload\ndef h(x: str) -> None:\n    pass\ndef h(x: Any) -> None:\n    @singledispatch  # E: Nested singledispatch functions not supported\n    def singledispatch_in_overload(x: Any) -> None:\n        pass\n\n@singledispatch\ndef outside(x: Any) -> None:\n    pass\n\ndef i() -> None:\n    @outside.register  # E: Registering nested functions not supported\n    def register_in_func(x: int) -> None:\n        pass\n\n@dec\ndef j() -> None:\n    @outside.register  # E: Registering nested functions not supported\n    def register_in_decorated(x: int) -> None:\n        pass\n\n@overload\ndef k(x: int) -> None:\n    pass\n@overload\ndef k(x: str) -> None:\n    pass\ndef k(x: Any) -> None:\n    @outside.register  # E: Registering nested functions not supported\n    def register_in_overload(x: int) -> None:\n        pass\n"
  },
  {
    "path": "mypyc/test-data/irbuild-statements.test",
    "content": "[case testForInRange]\ndef f() -> None:\n    x = 0\n    for i in range(5):\n        x = x + i\n[out]\ndef f():\n    x :: int\n    r0 :: short_int\n    i :: int\n    r1 :: bit\n    r2 :: int\n    r3 :: short_int\nL0:\n    x = 0\n    r0 = 0\n    i = r0\nL1:\n    r1 = int_lt r0, 10\n    if r1 goto L2 else goto L4 :: bool\nL2:\n    r2 = CPyTagged_Add(x, i)\n    x = r2\nL3:\n    r3 = r0 + 2\n    r0 = r3\n    i = r3\n    goto L1\nL4:\n    return 1\n\n[case testForInRangeVariableEndIndxe]\ndef f(a: int) -> None:\n    for i in range(a):\n        pass\n[out]\ndef f(a):\n    a, r0, i :: int\n    r1 :: bit\n    r2 :: int\nL0:\n    r0 = 0\n    i = r0\nL1:\n    r1 = int_lt r0, a\n    if r1 goto L2 else goto L4 :: bool\nL2:\nL3:\n    r2 = CPyTagged_Add(r0, 2)\n    r0 = r2\n    i = r2\n    goto L1\nL4:\n    return 1\n\n[case testForInNegativeRange]\ndef f() -> None:\n    for i in range(10, 0, -1):\n        pass\n[out]\ndef f():\n    r0 :: short_int\n    i :: int\n    r1 :: bit\n    r2 :: short_int\nL0:\n    r0 = 20\n    i = r0\nL1:\n    r1 = int_gt r0, 0\n    if r1 goto L2 else goto L4 :: bool\nL2:\nL3:\n    r2 = r0 + -2\n    r0 = r2\n    i = r2\n    goto L1\nL4:\n    return 1\n\n[case testBreak]\ndef f() -> None:\n  n = 0\n  while n < 5:\n      break\n[out]\ndef f():\n    n :: int\n    r0 :: bit\nL0:\n    n = 0\nL1:\n    r0 = int_lt n, 10\n    if r0 goto L2 else goto L3 :: bool\nL2:\nL3:\n    return 1\n\n[case testBreakFor]\ndef f() -> None:\n    for n in range(5):\n        break\n[out]\ndef f():\n    r0 :: short_int\n    n :: int\n    r1 :: bit\n    r2 :: short_int\nL0:\n    r0 = 0\n    n = r0\nL1:\n    r1 = int_lt r0, 10\n    if r1 goto L2 else goto L4 :: bool\nL2:\n    goto L4\nL3:\n    r2 = r0 + 2\n    r0 = r2\n    n = r2\n    goto L1\nL4:\n    return 1\n\n[case testBreakNested]\ndef f() -> None:\n    n = 0\n    while n < 5:\n        while n < 4:\n            break\n        break\n[out]\ndef f():\n    n :: int\n    r0, r1 :: bit\nL0:\n    n = 0\nL1:\n    r0 = int_lt n, 10\n    if r0 goto L2 else goto L6 :: bool\nL2:\nL3:\n    r1 = int_lt n, 8\n    if r1 goto L4 else goto L5 :: bool\nL4:\nL5:\nL6:\n    return 1\n\n[case testContinue]\ndef f() -> None:\n  n = 0\n  while n < 5:\n      continue\n[out]\ndef f():\n    n :: int\n    r0 :: bit\nL0:\n    n = 0\nL1:\n    r0 = int_lt n, 10\n    if r0 goto L2 else goto L3 :: bool\nL2:\n    goto L1\nL3:\n    return 1\n\n[case testContinueFor]\ndef f() -> None:\n    for n in range(5):\n        continue\n[out]\ndef f():\n    r0 :: short_int\n    n :: int\n    r1 :: bit\n    r2 :: short_int\nL0:\n    r0 = 0\n    n = r0\nL1:\n    r1 = int_lt r0, 10\n    if r1 goto L2 else goto L4 :: bool\nL2:\nL3:\n    r2 = r0 + 2\n    r0 = r2\n    n = r2\n    goto L1\nL4:\n    return 1\n\n[case testContinueNested]\ndef f() -> None:\n    n = 0\n    while n < 5:\n        while n < 4:\n            continue\n        continue\n[out]\ndef f():\n    n :: int\n    r0, r1 :: bit\nL0:\n    n = 0\nL1:\n    r0 = int_lt n, 10\n    if r0 goto L2 else goto L6 :: bool\nL2:\nL3:\n    r1 = int_lt n, 8\n    if r1 goto L4 else goto L5 :: bool\nL4:\n    goto L3\nL5:\n    goto L1\nL6:\n    return 1\n\n[case testForList]\nfrom typing import List\n\ndef f(ls: List[int]) -> int:\n    y = 0\n    for x in ls:\n        y = y + x\n    return y\n[out]\ndef f(ls):\n    ls :: list\n    y :: int\n    r0, r1 :: native_int\n    r2 :: bit\n    r3 :: object\n    r4, x, r5 :: int\n    r6 :: native_int\nL0:\n    y = 0\n    r0 = 0\nL1:\n    r1 = var_object_size ls\n    r2 = r0 < r1 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = list_get_item_unsafe ls, r0\n    r4 = unbox(int, r3)\n    x = r4\n    r5 = CPyTagged_Add(y, x)\n    y = r5\nL3:\n    r6 = r0 + 1\n    r0 = r6\n    goto L1\nL4:\n    return y\n\n[case testForDictBasic]\nfrom typing import Dict\n\ndef f(d: Dict[int, int]) -> None:\n    for key in d:\n        d[key]\n[out]\ndef f(d):\n    d :: dict\n    r0 :: short_int\n    r1 :: native_int\n    r2 :: object\n    r3 :: tuple[bool, short_int, object]\n    r4 :: short_int\n    r5 :: bool\n    r6 :: object\n    r7, key :: int\n    r8, r9 :: object\n    r10 :: int\n    r11, r12 :: bit\nL0:\n    r0 = 0\n    r1 = PyDict_Size(d)\n    r2 = CPyDict_GetKeysIter(d)\nL1:\n    r3 = CPyDict_NextKey(r2, r0)\n    r4 = r3[1]\n    r0 = r4\n    r5 = r3[0]\n    if r5 goto L2 else goto L4 :: bool\nL2:\n    r6 = r3[2]\n    r7 = unbox(int, r6)\n    key = r7\n    r8 = box(int, key)\n    r9 = CPyDict_GetItem(d, r8)\n    r10 = unbox(int, r9)\nL3:\n    r11 = CPyDict_CheckSize(d, r1)\n    goto L1\nL4:\n    r12 = CPy_NoErrOccurred()\nL5:\n    return 1\n\n[case testForDictContinue]\nfrom typing import Dict\n\ndef sum_over_even_values(d: Dict[int, int]) -> int:\n    s = 0\n    for key in d:\n        if d[key] % 2:\n            continue\n        s = s + d[key]\n    return s\n[out]\ndef sum_over_even_values(d):\n    d :: dict\n    s :: int\n    r0 :: short_int\n    r1 :: native_int\n    r2 :: object\n    r3 :: tuple[bool, short_int, object]\n    r4 :: short_int\n    r5 :: bool\n    r6 :: object\n    r7, key :: int\n    r8, r9 :: object\n    r10, r11 :: int\n    r12 :: bit\n    r13, r14 :: object\n    r15, r16 :: int\n    r17, r18 :: bit\nL0:\n    s = 0\n    r0 = 0\n    r1 = PyDict_Size(d)\n    r2 = CPyDict_GetKeysIter(d)\nL1:\n    r3 = CPyDict_NextKey(r2, r0)\n    r4 = r3[1]\n    r0 = r4\n    r5 = r3[0]\n    if r5 goto L2 else goto L6 :: bool\nL2:\n    r6 = r3[2]\n    r7 = unbox(int, r6)\n    key = r7\n    r8 = box(int, key)\n    r9 = CPyDict_GetItem(d, r8)\n    r10 = unbox(int, r9)\n    r11 = CPyTagged_Remainder(r10, 4)\n    r12 = r11 != 0\n    if r12 goto L3 else goto L4 :: bool\nL3:\n    goto L5\nL4:\n    r13 = box(int, key)\n    r14 = CPyDict_GetItem(d, r13)\n    r15 = unbox(int, r14)\n    r16 = CPyTagged_Add(s, r15)\n    s = r16\nL5:\n    r17 = CPyDict_CheckSize(d, r1)\n    goto L1\nL6:\n    r18 = CPy_NoErrOccurred()\nL7:\n    return s\n\n[case testMultipleAssignmentWithNoUnpacking]\nfrom typing import Tuple\n\ndef f(x: int, y: int) -> Tuple[int, int]:\n    x, y = y, x\n    return (x, y)\n\ndef f2(x: int, y: str, z: float) -> Tuple[float, str, int]:\n    a, b, c = x, y, z\n    return (c, b, a)\n\ndef f3(x: int, y: int) -> Tuple[int, int]:\n    [x, y] = [y, x]\n    return (x, y)\n[out]\ndef f(x, y):\n    x, y, r0, r1 :: int\n    r2 :: tuple[int, int]\nL0:\n    r0 = y\n    r1 = x\n    x = r0\n    y = r1\n    r2 = (x, y)\n    return r2\ndef f2(x, y, z):\n    x :: int\n    y :: str\n    z :: float\n    r0 :: int\n    r1 :: str\n    r2 :: float\n    a :: int\n    b :: str\n    c :: float\n    r3 :: tuple[float, str, int]\nL0:\n    r0 = x\n    r1 = y\n    r2 = z\n    a = r0\n    b = r1\n    c = r2\n    r3 = (c, b, a)\n    return r3\ndef f3(x, y):\n    x, y, r0, r1 :: int\n    r2 :: tuple[int, int]\nL0:\n    r0 = y\n    r1 = x\n    x = r0\n    y = r1\n    r2 = (x, y)\n    return r2\n\n[case testMultipleAssignmentBasicUnpacking]\nfrom typing import Tuple, Any\n\ndef from_tuple(t: Tuple[bool, None]) -> None:\n    x, y = t\n\ndef from_any(a: Any) -> None:\n    x, y = a\n[out]\ndef from_tuple(t):\n    t :: tuple[bool, None]\n    r0, x :: bool\n    r1, y :: None\nL0:\n    r0 = t[0]\n    x = r0\n    r1 = t[1]\n    y = r1\n    return 1\ndef from_any(a):\n    a, r0, r1 :: object\n    r2 :: bool\n    x, r3 :: object\n    r4 :: bool\n    y, r5 :: object\n    r6 :: bool\nL0:\n    r0 = PyObject_GetIter(a)\n    r1 = PyIter_Next(r0)\n    if is_error(r1) goto L1 else goto L2\nL1:\n    r2 = raise ValueError('not enough values to unpack')\n    unreachable\nL2:\n    x = r1\n    r3 = PyIter_Next(r0)\n    if is_error(r3) goto L3 else goto L4\nL3:\n    r4 = raise ValueError('not enough values to unpack')\n    unreachable\nL4:\n    y = r3\n    r5 = PyIter_Next(r0)\n    if is_error(r5) goto L6 else goto L5\nL5:\n    r6 = raise ValueError('too many values to unpack')\n    unreachable\nL6:\n    return 1\n\n[case testMultiAssignmentCoercions]\nfrom typing import Tuple, Any\n\ndef from_tuple(t: Tuple[int, Any]) -> None:\n    x: object\n    y: int\n    x, y = t\n\ndef from_any(a: Any) -> None:\n    x: int\n    x, y = a\n[out]\ndef from_tuple(t):\n    t :: tuple[int, object]\n    r0 :: int\n    r1 :: object\n    r2 :: int\n    r3, x, r4 :: object\n    r5, y :: int\nL0:\n    r0 = borrow t[0]\n    r1 = borrow t[1]\n    keep_alive steal t\n    r2 = unborrow r0\n    r3 = box(int, r2)\n    x = r3\n    r4 = unborrow r1\n    r5 = unbox(int, r4)\n    y = r5\n    return 1\ndef from_any(a):\n    a, r0, r1 :: object\n    r2 :: bool\n    r3, x :: int\n    r4 :: object\n    r5 :: bool\n    y, r6 :: object\n    r7 :: bool\nL0:\n    r0 = PyObject_GetIter(a)\n    r1 = PyIter_Next(r0)\n    if is_error(r1) goto L1 else goto L2\nL1:\n    r2 = raise ValueError('not enough values to unpack')\n    unreachable\nL2:\n    r3 = unbox(int, r1)\n    x = r3\n    r4 = PyIter_Next(r0)\n    if is_error(r4) goto L3 else goto L4\nL3:\n    r5 = raise ValueError('not enough values to unpack')\n    unreachable\nL4:\n    y = r4\n    r6 = PyIter_Next(r0)\n    if is_error(r6) goto L6 else goto L5\nL5:\n    r7 = raise ValueError('too many values to unpack')\n    unreachable\nL6:\n    return 1\n\n[case testMultiAssignmentNested]\nfrom typing import Tuple, Any, List\n\nclass A:\n    x: int\n\ndef multi_assign(t: Tuple[int, Tuple[str, Any]], a: A, l: List[str]) -> None:\n    z: int\n    a.x, (l[0], z) = t\n[out]\ndef multi_assign(t, a, l):\n    t :: tuple[int, tuple[str, object]]\n    a :: __main__.A\n    l :: list\n    r0 :: int\n    r1 :: bool\n    r2 :: tuple[str, object]\n    r3 :: str\n    r4 :: bit\n    r5 :: object\n    r6, z :: int\nL0:\n    r0 = t[0]\n    a.x = r0; r1 = is_error\n    r2 = t[1]\n    r3 = r2[0]\n    r4 = CPyList_SetItem(l, 0, r3)\n    r5 = r2[1]\n    r6 = unbox(int, r5)\n    z = r6\n    return 1\n\n[case testMultipleAssignmentUnpackFromSequence]\nfrom typing import List, Tuple\n\ndef f(l: List[int], t: Tuple[int, ...]) -> None:\n    x: object\n    y: int\n    x, y = l\n    x, y = t\n[out]\ndef f(l, t):\n    l :: list\n    t :: tuple\n    r0 :: i32\n    r1 :: bit\n    r2, r3, x :: object\n    r4, y :: int\n    r5 :: i32\n    r6 :: bit\n    r7, r8 :: object\n    r9 :: int\nL0:\n    r0 = CPySequence_CheckUnpackCount(l, 2)\n    r1 = r0 >= 0 :: signed\n    r2 = list_get_item_unsafe l, 0\n    r3 = list_get_item_unsafe l, 1\n    x = r2\n    r4 = unbox(int, r3)\n    y = r4\n    r5 = CPySequence_CheckUnpackCount(t, 2)\n    r6 = r5 >= 0 :: signed\n    r7 = CPySequenceTuple_GetItemUnsafe(t, 0)\n    r8 = CPySequenceTuple_GetItemUnsafe(t, 1)\n    x = r7\n    r9 = unbox(int, r8)\n    y = r9\n    return 1\n\n[case testAssert]\nfrom typing import Optional\n\ndef no_msg(x: bool) -> int:\n    assert x\n    return 1\n\ndef literal_msg(x: object) -> int:\n    assert x, 'message'\n    return 2\n\ndef complex_msg(x: Optional[str], s: str) -> None:\n    assert x, s\n[out]\ndef no_msg(x):\n    x, r0 :: bool\nL0:\n    if x goto L2 else goto L1 :: bool\nL1:\n    r0 = raise AssertionError\n    unreachable\nL2:\n    return 2\ndef literal_msg(x):\n    x :: object\n    r0 :: i32\n    r1 :: bit\n    r2, r3 :: bool\nL0:\n    r0 = PyObject_IsTrue(x)\n    r1 = r0 >= 0 :: signed\n    r2 = truncate r0: i32 to builtins.bool\n    if r2 goto L2 else goto L1 :: bool\nL1:\n    r3 = raise AssertionError('message')\n    unreachable\nL2:\n    return 4\ndef complex_msg(x, s):\n    x :: union[str, None]\n    s :: str\n    r0 :: object\n    r1 :: bit\n    r2 :: str\n    r3 :: bit\n    r4 :: object\n    r5 :: str\n    r6 :: object\n    r7 :: object[1]\n    r8 :: object_ptr\n    r9 :: object\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x != r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = cast(str, x)\n    r3 = CPyStr_IsTrue(r2)\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = builtins :: module\n    r5 = 'AssertionError'\n    r6 = CPyObject_GetAttr(r4, r5)\n    r7 = [s]\n    r8 = load_address r7\n    r9 = PyObject_Vectorcall(r6, r8, 1, 0)\n    keep_alive s\n    CPy_Raise(r9)\n    unreachable\nL3:\n    return 1\n\n[case testDelList]\ndef delList() -> None:\n    l = [1, 2]\n    del l[1]\ndef delListMultiple() -> None:\n    l = [1, 2, 3, 4, 5, 6, 7]\n    del l[1], l[2], l[3]\n[out]\ndef delList():\n    r0 :: list\n    r1, r2 :: object\n    r3 :: ptr\n    l :: list\n    r4 :: object\n    r5 :: i32\n    r6 :: bit\nL0:\n    r0 = PyList_New(2)\n    r1 = object 1\n    r2 = object 2\n    r3 = list_items r0\n    buf_init_item r3, 0, r1\n    buf_init_item r3, 1, r2\n    keep_alive r0\n    l = r0\n    r4 = object 1\n    r5 = PyObject_DelItem(l, r4)\n    r6 = r5 >= 0 :: signed\n    return 1\ndef delListMultiple():\n    r0 :: list\n    r1, r2, r3, r4, r5, r6, r7 :: object\n    r8 :: ptr\n    l :: list\n    r9 :: object\n    r10 :: i32\n    r11 :: bit\n    r12 :: object\n    r13 :: i32\n    r14 :: bit\n    r15 :: object\n    r16 :: i32\n    r17 :: bit\nL0:\n    r0 = PyList_New(7)\n    r1 = object 1\n    r2 = object 2\n    r3 = object 3\n    r4 = object 4\n    r5 = object 5\n    r6 = object 6\n    r7 = object 7\n    r8 = list_items r0\n    buf_init_item r8, 0, r1\n    buf_init_item r8, 1, r2\n    buf_init_item r8, 2, r3\n    buf_init_item r8, 3, r4\n    buf_init_item r8, 4, r5\n    buf_init_item r8, 5, r6\n    buf_init_item r8, 6, r7\n    keep_alive r0\n    l = r0\n    r9 = object 1\n    r10 = PyObject_DelItem(l, r9)\n    r11 = r10 >= 0 :: signed\n    r12 = object 2\n    r13 = PyObject_DelItem(l, r12)\n    r14 = r13 >= 0 :: signed\n    r15 = object 3\n    r16 = PyObject_DelItem(l, r15)\n    r17 = r16 >= 0 :: signed\n    return 1\n\n[case testDelDict]\ndef delDict() -> None:\n    d = {\"one\":1, \"two\":2}\n    del d[\"one\"]\ndef delDictMultiple() -> None:\n    d = {\"one\":1, \"two\":2, \"three\":3, \"four\":4}\n    del d[\"one\"], d[\"four\"]\n[out]\ndef delDict():\n    r0, r1 :: str\n    r2, r3 :: object\n    r4, d :: dict\n    r5 :: str\n    r6 :: i32\n    r7 :: bit\nL0:\n    r0 = 'one'\n    r1 = 'two'\n    r2 = object 1\n    r3 = object 2\n    r4 = CPyDict_Build(2, r0, r2, r1, r3)\n    d = r4\n    r5 = 'one'\n    r6 = PyObject_DelItem(d, r5)\n    r7 = r6 >= 0 :: signed\n    return 1\ndef delDictMultiple():\n    r0, r1, r2, r3 :: str\n    r4, r5, r6, r7 :: object\n    r8, d :: dict\n    r9, r10 :: str\n    r11 :: i32\n    r12 :: bit\n    r13 :: i32\n    r14 :: bit\nL0:\n    r0 = 'one'\n    r1 = 'two'\n    r2 = 'three'\n    r3 = 'four'\n    r4 = object 1\n    r5 = object 2\n    r6 = object 3\n    r7 = object 4\n    r8 = CPyDict_Build(4, r0, r4, r1, r5, r2, r6, r3, r7)\n    d = r8\n    r9 = 'one'\n    r10 = 'four'\n    r11 = PyObject_DelItem(d, r9)\n    r12 = r11 >= 0 :: signed\n    r13 = PyObject_DelItem(d, r10)\n    r14 = r13 >= 0 :: signed\n    return 1\n\n[case testDelAttribute]\nclass Dummy():\n    __deletable__ = ('x', 'y')\n    def __init__(self, x: int, y: int) -> None:\n        self.x = x\n        self.y = y\ndef delAttribute() -> None:\n    dummy = Dummy(1, 2)\n    del dummy.x\ndef delAttributeMultiple() -> None:\n    dummy = Dummy(1, 2)\n    del dummy.x, dummy.y\n[out]\ndef Dummy.__init__(self, x, y):\n    self :: __main__.Dummy\n    x, y :: int\nL0:\n    self.x = x\n    self.y = y\n    return 1\ndef delAttribute():\n    r0, dummy :: __main__.Dummy\n    r1 :: str\n    r2 :: i32\n    r3 :: bit\nL0:\n    r0 = Dummy(2, 4)\n    dummy = r0\n    r1 = 'x'\n    r2 = PyObject_DelAttr(dummy, r1)\n    r3 = r2 >= 0 :: signed\n    return 1\ndef delAttributeMultiple():\n    r0, dummy :: __main__.Dummy\n    r1 :: str\n    r2 :: i32\n    r3 :: bit\n    r4 :: str\n    r5 :: i32\n    r6 :: bit\nL0:\n    r0 = Dummy(2, 4)\n    dummy = r0\n    r1 = 'x'\n    r2 = PyObject_DelAttr(dummy, r1)\n    r3 = r2 >= 0 :: signed\n    r4 = 'y'\n    r5 = PyObject_DelAttr(dummy, r4)\n    r6 = r5 >= 0 :: signed\n    return 1\n\n[case testForEnumerate]\nfrom typing import List, Iterable\n\ndef f(a: List[int]) -> None:\n    for i, x in enumerate(a):\n        i + x\ndef g(x: Iterable[int]) -> None:\n    for i, n in enumerate(x):\n        pass\n[out]\ndef f(a):\n    a :: list\n    r0 :: short_int\n    r1, r2 :: native_int\n    r3 :: bit\n    i :: int\n    r4 :: object\n    r5, x, r6 :: int\n    r7 :: short_int\n    r8 :: native_int\nL0:\n    r0 = 0\n    r1 = 0\nL1:\n    r2 = var_object_size a\n    r3 = r1 < r2 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    i = r0\n    r4 = list_get_item_unsafe a, r1\n    r5 = unbox(int, r4)\n    x = r5\n    r6 = CPyTagged_Add(i, x)\nL3:\n    r7 = r0 + 2\n    r0 = r7\n    r8 = r1 + 1\n    r1 = r8\n    goto L1\nL4:\nL5:\n    return 1\ndef g(x):\n    x :: object\n    r0 :: short_int\n    r1, r2 :: object\n    i, r3, n :: int\n    r4 :: short_int\n    r5 :: bit\nL0:\n    r0 = 0\n    r1 = PyObject_GetIter(x)\nL1:\n    r2 = PyIter_Next(r1)\n    if is_error(r2) goto L4 else goto L2\nL2:\n    i = r0\n    r3 = unbox(int, r2)\n    n = r3\nL3:\n    r4 = r0 + 2\n    r0 = r4\n    goto L1\nL4:\n    r5 = CPy_NoErrOccurred()\nL5:\n    return 1\n\n[case testForZip]\nfrom typing import List, Iterable, Sequence\n\ndef f(a: List[int], b: Sequence[bool]) -> None:\n    for x, y in zip(a, b):\n        if b:\n            x = 1\n\ndef g(a: Iterable[bool], b: List[int]) -> None:\n    for x, y, z in zip(a, b, range(5)):\n        x = False\n[out]\ndef f(a, b):\n    a :: list\n    b :: object\n    r0 :: native_int\n    r1 :: object\n    r2 :: native_int\n    r3 :: bit\n    r4, r5 :: object\n    r6, x :: int\n    r7, y :: bool\n    r8 :: i32\n    r9 :: bit\n    r10 :: bool\n    r11 :: native_int\n    r12 :: bit\nL0:\n    r0 = 0\n    r1 = PyObject_GetIter(b)\nL1:\n    r2 = var_object_size a\n    r3 = r0 < r2 :: signed\n    if r3 goto L2 else goto L7 :: bool\nL2:\n    r4 = PyIter_Next(r1)\n    if is_error(r4) goto L7 else goto L3\nL3:\n    r5 = list_get_item_unsafe a, r0\n    r6 = unbox(int, r5)\n    x = r6\n    r7 = unbox(bool, r4)\n    y = r7\n    r8 = PyObject_IsTrue(b)\n    r9 = r8 >= 0 :: signed\n    r10 = truncate r8: i32 to builtins.bool\n    if r10 goto L4 else goto L5 :: bool\nL4:\n    x = 2\nL5:\nL6:\n    r11 = r0 + 1\n    r0 = r11\n    goto L1\nL7:\n    r12 = CPy_NoErrOccurred()\nL8:\n    return 1\ndef g(a, b):\n    a :: object\n    b :: list\n    r0 :: object\n    r1 :: native_int\n    r2 :: short_int\n    z :: int\n    r3 :: object\n    r4 :: native_int\n    r5, r6 :: bit\n    r7, x :: bool\n    r8 :: object\n    r9, y :: int\n    r10 :: native_int\n    r11 :: short_int\n    r12 :: bit\nL0:\n    r0 = PyObject_GetIter(a)\n    r1 = 0\n    r2 = 0\n    z = r2\nL1:\n    r3 = PyIter_Next(r0)\n    if is_error(r3) goto L6 else goto L2\nL2:\n    r4 = var_object_size b\n    r5 = r1 < r4 :: signed\n    if r5 goto L3 else goto L6 :: bool\nL3:\n    r6 = int_lt r2, 10\n    if r6 goto L4 else goto L6 :: bool\nL4:\n    r7 = unbox(bool, r3)\n    x = r7\n    r8 = list_get_item_unsafe b, r1\n    r9 = unbox(int, r8)\n    y = r9\n    x = 0\nL5:\n    r10 = r1 + 1\n    r1 = r10\n    r11 = r2 + 2\n    r2 = r11\n    z = r11\n    goto L1\nL6:\n    r12 = CPy_NoErrOccurred()\nL7:\n    return 1\n\n[case testConditionalFunctionDefinition]\nif int():\n    def foo() -> int:\n        return 0\nelse:\n    def foo() -> int:  # E\n        return 1\n\ndef bar() -> int:\n    return 0\n\nif int():\n    def bar() -> int:  # E\n        return 1\n[out]\nmain:5: error: Duplicate definition of \"foo\" not supported by mypyc\nmain:12: error: Duplicate definition of \"bar\" not supported by mypyc\n\n[case testRepeatedUnderscoreFunctions]\ndef _(arg): pass\ndef _(arg): pass\n[out]\nmain:2: error: Duplicate definition of \"_\" not supported by mypyc\n"
  },
  {
    "path": "mypyc/test-data/irbuild-str.test",
    "content": "[case testStrSplit]\nfrom typing import NewType, Optional, List, Union\nNewStr = NewType(\"NewStr\", str)\n\ndef do_split(s: Union[str, NewStr], sep: Optional[str] = None, max_split: Optional[int] = None) -> List[str]:\n    if sep is not None:\n        if max_split is not None:\n            return s.split(sep, max_split)\n        else:\n            return s.split(sep)\n    return s.split()\n[typing fixtures/typing-full.pyi]\n[out]\ndef do_split(s, sep, max_split):\n    s :: str\n    sep :: union[str, None]\n    max_split :: union[int, None]\n    r0, r1, r2 :: object\n    r3 :: bit\n    r4 :: object\n    r5 :: bit\n    r6 :: str\n    r7 :: int\n    r8 :: list\n    r9 :: str\n    r10, r11 :: list\nL0:\n    if is_error(sep) goto L1 else goto L2\nL1:\n    r0 = box(None, 1)\n    sep = r0\nL2:\n    if is_error(max_split) goto L3 else goto L4\nL3:\n    r1 = box(None, 1)\n    max_split = r1\nL4:\n    r2 = load_address _Py_NoneStruct\n    r3 = sep != r2\n    if r3 goto L5 else goto L9 :: bool\nL5:\n    r4 = load_address _Py_NoneStruct\n    r5 = max_split != r4\n    if r5 goto L6 else goto L7 :: bool\nL6:\n    r6 = cast(str, sep)\n    r7 = unbox(int, max_split)\n    r8 = CPyStr_Split(s, r6, r7)\n    return r8\nL7:\n    r9 = cast(str, sep)\n    r10 = PyUnicode_Split(s, r9, -1)\n    return r10\nL8:\nL9:\n    r11 = PyUnicode_Split(s, 0, -1)\n    return r11\n\n\n[case testStrEquality]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef eq(x: str, y: str) -> bool:\n    return x == y\n\ndef neq(x: str, y: Union[str, NewStr]) -> bool:\n    return x != y\n\n[typing fixtures/typing-full.pyi]\n[out]\ndef eq(x, y):\n    x, y :: str\n    r0 :: bool\nL0:\n    r0 = CPyStr_Equal(x, y)\n    return r0\ndef neq(x, y):\n    x, y :: str\n    r0 :: bool\n    r1 :: bit\nL0:\n    r0 = CPyStr_Equal(x, y)\n    r1 = r0 == 0\n    return r1\n\n[case testStrReplace]\nfrom typing import NewType, Optional, Union\nNewStr = NewType(\"NewStr\", str)\ndef do_replace(s: Union[str, NewStr], old_substr: str, new_substr: str, max_count: Optional[int] = None) -> str:\n    if max_count is not None:\n        return s.replace(old_substr, new_substr, max_count)\n    else:\n        return s.replace(old_substr, new_substr)\n[typing fixtures/typing-full.pyi]\n[out]\ndef do_replace(s, old_substr, new_substr, max_count):\n    s, old_substr, new_substr :: str\n    max_count :: union[int, None]\n    r0, r1 :: object\n    r2 :: bit\n    r3 :: int\n    r4, r5 :: str\nL0:\n    if is_error(max_count) goto L1 else goto L2\nL1:\n    r0 = box(None, 1)\n    max_count = r0\nL2:\n    r1 = load_address _Py_NoneStruct\n    r2 = max_count != r1\n    if r2 goto L3 else goto L4 :: bool\nL3:\n    r3 = unbox(int, max_count)\n    r4 = CPyStr_Replace(s, old_substr, new_substr, r3)\n    return r4\nL4:\n    r5 = PyUnicode_Replace(s, old_substr, new_substr, -1)\n    return r5\nL5:\n    unreachable\n\n[case testStrStartswithEndswithTuple]\nfrom typing import NewType, Tuple, Union\nNewStr = NewType(\"NewStr\", str)\n\ndef do_startswith(s1: Union[str, NewStr], s2: Tuple[str, ...]) -> bool:\n    return s1.startswith(s2)\n\ndef do_endswith(s1: Union[str, NewStr], s2: Tuple[str, ...]) -> bool:\n    return s1.endswith(s2)\n\ndef do_tuple_literal_args(s1: Union[str, NewStr]) -> None:\n    x = s1.startswith((\"a\", \"b\"))\n    y = s1.endswith((\"a\", \"b\"))\n[typing fixtures/typing-full.pyi]\n[out]\ndef do_startswith(s1, s2):\n    s1 :: str\n    s2 :: tuple\n    r0 :: bool\nL0:\n    r0 = CPyStr_Startswith(s1, s2)\n    return r0\ndef do_endswith(s1, s2):\n    s1 :: str\n    s2 :: tuple\n    r0 :: bool\nL0:\n    r0 = CPyStr_Endswith(s1, s2)\n    return r0\ndef do_tuple_literal_args(s1):\n    s1, r0, r1 :: str\n    r2 :: tuple[str, str]\n    r3 :: object\n    r4, x :: bool\n    r5, r6 :: str\n    r7 :: tuple[str, str]\n    r8 :: object\n    r9, y :: bool\nL0:\n    r0 = 'a'\n    r1 = 'b'\n    r2 = (r0, r1)\n    r3 = box(tuple[str, str], r2)\n    r4 = CPyStr_Startswith(s1, r3)\n    x = r4\n    r5 = 'a'\n    r6 = 'b'\n    r7 = (r5, r6)\n    r8 = box(tuple[str, str], r7)\n    r9 = CPyStr_Endswith(s1, r8)\n    y = r9\n    return 1\n\n[case testStrToBool]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef is_true(x: Union[str, NewStr]) -> bool:\n    if x:\n        return True\n    else:\n        return False\n[typing fixtures/typing-full.pyi]\n[out]\ndef is_true(x):\n    x :: str\n    r0 :: bit\nL0:\n    r0 = CPyStr_IsTrue(x)\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    return 0\nL3:\n    unreachable\n\n[case testStringFormatMethod]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef f(s: Union[str, NewStr], num: int) -> None:\n    s1 = \"Hi! I'm {}, and I'm {} years old.\".format(s, num)\n    s2 = ''.format()\n    s3 = 'abc'.format()\n    s4 = '}}{}{{{}}}{{{}'.format(num, num, num)\n[typing fixtures/typing-full.pyi]\n[out]\ndef f(s, num):\n    s :: str\n    num :: int\n    r0, r1, r2, r3, r4, s1, r5, s2, r6, s3, r7, r8, r9, r10, r11, r12, r13, s4 :: str\nL0:\n    r0 = CPyTagged_Str(num)\n    r1 = \"Hi! I'm \"\n    r2 = \", and I'm \"\n    r3 = ' years old.'\n    r4 = CPyStr_Build(5, r1, s, r2, r0, r3)\n    s1 = r4\n    r5 = ''\n    s2 = r5\n    r6 = 'abc'\n    s3 = r6\n    r7 = CPyTagged_Str(num)\n    r8 = CPyTagged_Str(num)\n    r9 = CPyTagged_Str(num)\n    r10 = '}'\n    r11 = '{'\n    r12 = '}{'\n    r13 = CPyStr_Build(6, r10, r7, r11, r8, r12, r9)\n    s4 = r13\n    return 1\n\n[case testFStrings_64bit]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef f(var: Union[str, NewStr], num: int) -> None:\n    s1 = f\"Hi! I'm {var}. I am {num} years old.\"\n    s2 = f'Hello {var:>{num}}'\n    s3 = f''\n    s4 = f'abc'\n[typing fixtures/typing-full.pyi]\n[out]\ndef f(var, num):\n    var :: str\n    num :: int\n    r0, r1, r2, r3, r4, s1, r5, r6, r7, r8, r9, r10, r11 :: str\n    r12 :: object[3]\n    r13 :: object_ptr\n    r14 :: object\n    r15 :: str\n    r16 :: list\n    r17 :: ptr\n    r18, s2, r19, s3, r20, s4 :: str\nL0:\n    r0 = \"Hi! I'm \"\n    r1 = '. I am '\n    r2 = CPyTagged_Str(num)\n    r3 = ' years old.'\n    r4 = CPyStr_Build(5, r0, var, r1, r2, r3)\n    s1 = r4\n    r5 = ''\n    r6 = 'Hello '\n    r7 = '{:{}}'\n    r8 = '>'\n    r9 = CPyTagged_Str(num)\n    r10 = CPyStr_Build(2, r8, r9)\n    r11 = 'format'\n    r12 = [r7, var, r10]\n    r13 = load_address r12\n    r14 = PyObject_VectorcallMethod(r11, r13, 9223372036854775811, 0)\n    keep_alive r7, var, r10\n    r15 = cast(str, r14)\n    r16 = PyList_New(2)\n    r17 = list_items r16\n    buf_init_item r17, 0, r6\n    buf_init_item r17, 1, r15\n    keep_alive r16\n    r18 = PyUnicode_Join(r5, r16)\n    s2 = r18\n    r19 = ''\n    s3 = r19\n    r20 = 'abc'\n    s4 = r20\n    return 1\n\n[case testStringFormattingCStyle]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef f(var: Union[str, NewStr], num: int) -> None:\n    s1 = \"Hi! I'm %s.\" % var\n    s2 = \"I am %d years old.\" % num\n    s3 = \"Hi! I'm %s. I am %d years old.\" % (var, num)\n    s4 = \"Float: %f\" % num\n[typing fixtures/typing-full.pyi]\n[out]\ndef f(var, num):\n    var :: str\n    num :: int\n    r0, r1, r2, s1, r3, r4, r5, r6, s2, r7, r8, r9, r10, r11, s3, r12 :: str\n    r13, r14 :: object\n    r15, s4 :: str\nL0:\n    r0 = \"Hi! I'm \"\n    r1 = '.'\n    r2 = CPyStr_Build(3, r0, var, r1)\n    s1 = r2\n    r3 = CPyTagged_Str(num)\n    r4 = 'I am '\n    r5 = ' years old.'\n    r6 = CPyStr_Build(3, r4, r3, r5)\n    s2 = r6\n    r7 = CPyTagged_Str(num)\n    r8 = \"Hi! I'm \"\n    r9 = '. I am '\n    r10 = ' years old.'\n    r11 = CPyStr_Build(5, r8, var, r9, r7, r10)\n    s3 = r11\n    r12 = 'Float: %f'\n    r13 = box(int, num)\n    r14 = PyNumber_Remainder(r12, r13)\n    r15 = cast(str, r14)\n    s4 = r15\n    return 1\n\n[case testDecode]\ndef f(b: bytes) -> None:\n    b.decode()\n    b.decode('Utf_8')\n    b.decode('utf-8')\n    b.decode('UTF8')\n    b.decode('latin1')\n    b.decode('Latin-1')\n    b.decode('ascii')\n    encoding = 'utf-8'\n    b.decode(encoding)\n    b.decode('utf-8', 'backslashreplace')\ndef variants(b: bytes) -> None:\n    b.decode(encoding=\"UTF_8\")\n    b.decode(\"ascii\", errors=\"strict\")\n[out]\ndef f(b):\n    b :: bytes\n    r0, r1, r2, r3, r4, r5, r6, r7, encoding, r8, r9, r10, r11 :: str\nL0:\n    r0 = CPy_DecodeUTF8(b)\n    r1 = CPy_DecodeUTF8(b)\n    r2 = CPy_DecodeUTF8(b)\n    r3 = CPy_DecodeUTF8(b)\n    r4 = CPy_DecodeLatin1(b)\n    r5 = CPy_DecodeLatin1(b)\n    r6 = CPy_DecodeASCII(b)\n    r7 = 'utf-8'\n    encoding = r7\n    r8 = CPy_Decode(b, encoding, 0)\n    r9 = 'utf-8'\n    r10 = 'backslashreplace'\n    r11 = CPy_Decode(b, r9, r10)\n    return 1\ndef variants(b):\n    b :: bytes\n    r0, r1 :: str\nL0:\n    r0 = CPy_DecodeUTF8(b)\n    r1 = CPy_DecodeASCII(b)\n    return 1\n\n[case testEncode_64bit]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef f(s: Union[str, NewStr]) -> None:\n    s.encode()\n    s.encode('utf-8')\n    s.encode('utf8', 'strict')\n    s.encode('latin1', errors='strict')\n    s.encode(encoding='ascii')\n    s.encode(errors='strict', encoding='latin-1')\n    s.encode('utf-8', 'backslashreplace')\n    s.encode('ascii', 'backslashreplace')\n    encoding = 'utf8'\n    s.encode(encoding)\n    errors = 'strict'\n    s.encode('utf8', errors)\n    s.encode('utf8', errors=errors)\n    s.encode(errors=errors)\n    s.encode(encoding=encoding, errors=errors)\n    s.encode('latin2')\n\n[typing fixtures/typing-full.pyi]\n[out]\ndef f(s):\n    s :: str\n    r0, r1, r2, r3, r4, r5 :: bytes\n    r6, r7 :: str\n    r8 :: bytes\n    r9, r10 :: str\n    r11 :: bytes\n    r12, encoding :: str\n    r13 :: bytes\n    r14, errors, r15 :: str\n    r16 :: bytes\n    r17, r18 :: str\n    r19 :: object[3]\n    r20 :: object_ptr\n    r21, r22 :: object\n    r23 :: str\n    r24 :: object[2]\n    r25 :: object_ptr\n    r26, r27 :: object\n    r28 :: str\n    r29 :: object[3]\n    r30 :: object_ptr\n    r31, r32 :: object\n    r33 :: str\n    r34 :: bytes\nL0:\n    r0 = PyUnicode_AsUTF8String(s)\n    r1 = PyUnicode_AsUTF8String(s)\n    r2 = PyUnicode_AsUTF8String(s)\n    r3 = PyUnicode_AsLatin1String(s)\n    r4 = PyUnicode_AsASCIIString(s)\n    r5 = PyUnicode_AsLatin1String(s)\n    r6 = 'utf-8'\n    r7 = 'backslashreplace'\n    r8 = CPy_Encode(s, r6, r7)\n    r9 = 'ascii'\n    r10 = 'backslashreplace'\n    r11 = CPy_Encode(s, r9, r10)\n    r12 = 'utf8'\n    encoding = r12\n    r13 = CPy_Encode(s, encoding, 0)\n    r14 = 'strict'\n    errors = r14\n    r15 = 'utf8'\n    r16 = CPy_Encode(s, r15, errors)\n    r17 = 'utf8'\n    r18 = 'encode'\n    r19 = [s, r17, errors]\n    r20 = load_address r19\n    r21 = ('errors',)\n    r22 = PyObject_VectorcallMethod(r18, r20, 9223372036854775810, r21)\n    keep_alive s, r17, errors\n    r23 = 'encode'\n    r24 = [s, errors]\n    r25 = load_address r24\n    r26 = ('errors',)\n    r27 = PyObject_VectorcallMethod(r23, r25, 9223372036854775809, r26)\n    keep_alive s, errors\n    r28 = 'encode'\n    r29 = [s, encoding, errors]\n    r30 = load_address r29\n    r31 = ('encoding', 'errors')\n    r32 = PyObject_VectorcallMethod(r28, r30, 9223372036854775809, r31)\n    keep_alive s, encoding, errors\n    r33 = 'latin2'\n    r34 = CPy_Encode(s, r33, 0)\n    return 1\n\n[case testOrd]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef str_ord(x: Union[str, NewStr]) -> int:\n    return ord(x)\ndef str_ord_literal() -> int:\n    return ord(\"a\")\ndef bytes_ord(x: bytes) -> int:\n    return ord(x)\ndef bytes_ord_literal() -> int:\n    return ord(b\"a\")\ndef any_ord(x) -> int:\n    return ord(x)\n[typing fixtures/typing-full.pyi]\n[out]\ndef str_ord(x):\n    x :: str\n    r0 :: int\nL0:\n    r0 = CPyStr_Ord(x)\n    return r0\ndef str_ord_literal():\nL0:\n    return 194\ndef bytes_ord(x):\n    x :: bytes\n    r0 :: int\nL0:\n    r0 = CPyBytes_Ord(x)\n    return r0\ndef bytes_ord_literal():\nL0:\n    return 194\ndef any_ord(x):\n    x, r0 :: object\n    r1 :: str\n    r2 :: object\n    r3 :: object[1]\n    r4 :: object_ptr\n    r5 :: object\n    r6 :: int\nL0:\n    r0 = builtins :: module\n    r1 = 'ord'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = [x]\n    r4 = load_address r3\n    r5 = PyObject_Vectorcall(r2, r4, 1, 0)\n    keep_alive x\n    r6 = unbox(int, r5)\n    return r6\n\n[case testOrdOfStrIndex_64bit]\nfrom mypy_extensions import i64, i32, i16, u8\ndef ord_str_index(s: str, i: int) -> int:\n    return ord(s[i])\ndef ord_str_index_i64(s: str, i: i64) -> int:\n    return ord(s[i])\ndef ord_str_index_to_i32(s: str, i: i64) -> i32:\n    return ord(s[i])\ndef ord_str_index_to_i16(s: str, i: i64) -> i16:\n    return ord(s[i])\ndef ord_str_index_to_u8(s: str, i: i64) -> u8:\n    return ord(s[i])\ndef ord_str_index_to_i64(s: str, i: i64) -> i64:\n    return ord(s[i])\n[typing fixtures/typing-full.pyi]\n[out]\ndef ord_str_index(s, i):\n    s :: str\n    i :: int\n    r0 :: native_int\n    r1 :: bit\n    r2, r3 :: i64\n    r4 :: ptr\n    r5 :: c_ptr\n    r6, r7 :: i64\n    r8, r9 :: bool\n    r10 :: short_int\nL0:\n    r0 = i & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = i >> 1\n    r3 = r2\n    goto L3\nL2:\n    r4 = i ^ 1\n    r5 = r4\n    r6 = CPyLong_AsInt64(r5)\n    r3 = r6\n    keep_alive i\nL3:\n    r7 = CPyStr_AdjustIndex(s, r3)\n    r8 = CPyStr_RangeCheck(s, r7)\n    if r8 goto L5 else goto L4 :: bool\nL4:\n    r9 = raise IndexError('index out of range')\n    unreachable\nL5:\n    r10 = CPyStr_GetItemUnsafeAsInt(s, r7)\n    return r10\ndef ord_str_index_i64(s, i):\n    s :: str\n    i, r0 :: i64\n    r1, r2 :: bool\n    r3 :: short_int\nL0:\n    r0 = CPyStr_AdjustIndex(s, i)\n    r1 = CPyStr_RangeCheck(s, r0)\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = raise IndexError('index out of range')\n    unreachable\nL2:\n    r3 = CPyStr_GetItemUnsafeAsInt(s, r0)\n    return r3\ndef ord_str_index_to_i32(s, i):\n    s :: str\n    i, r0 :: i64\n    r1, r2 :: bool\n    r3 :: short_int\n    r4, r5 :: bit\n    r6 :: native_int\n    r7, r8 :: i32\nL0:\n    r0 = CPyStr_AdjustIndex(s, i)\n    r1 = CPyStr_RangeCheck(s, r0)\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = raise IndexError('index out of range')\n    unreachable\nL2:\n    r3 = CPyStr_GetItemUnsafeAsInt(s, r0)\n    r4 = r3 < 4294967296 :: signed\n    if r4 goto L3 else goto L5 :: bool\nL3:\n    r5 = r3 >= -4294967296 :: signed\n    if r5 goto L4 else goto L5 :: bool\nL4:\n    r6 = r3 >> 1\n    r7 = truncate r6: native_int to i32\n    r8 = r7\n    goto L6\nL5:\n    CPyInt32_Overflow()\n    unreachable\nL6:\n    return r8\ndef ord_str_index_to_i16(s, i):\n    s :: str\n    i, r0 :: i64\n    r1, r2 :: bool\n    r3 :: short_int\n    r4, r5 :: bit\n    r6 :: native_int\n    r7, r8 :: i16\nL0:\n    r0 = CPyStr_AdjustIndex(s, i)\n    r1 = CPyStr_RangeCheck(s, r0)\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = raise IndexError('index out of range')\n    unreachable\nL2:\n    r3 = CPyStr_GetItemUnsafeAsInt(s, r0)\n    r4 = r3 < 65536 :: signed\n    if r4 goto L3 else goto L5 :: bool\nL3:\n    r5 = r3 >= -65536 :: signed\n    if r5 goto L4 else goto L5 :: bool\nL4:\n    r6 = r3 >> 1\n    r7 = truncate r6: native_int to i16\n    r8 = r7\n    goto L6\nL5:\n    CPyInt16_Overflow()\n    unreachable\nL6:\n    return r8\ndef ord_str_index_to_u8(s, i):\n    s :: str\n    i, r0 :: i64\n    r1, r2 :: bool\n    r3 :: short_int\n    r4, r5 :: bit\n    r6 :: native_int\n    r7, r8 :: u8\nL0:\n    r0 = CPyStr_AdjustIndex(s, i)\n    r1 = CPyStr_RangeCheck(s, r0)\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = raise IndexError('index out of range')\n    unreachable\nL2:\n    r3 = CPyStr_GetItemUnsafeAsInt(s, r0)\n    r4 = r3 < 512 :: signed\n    if r4 goto L3 else goto L5 :: bool\nL3:\n    r5 = r3 >= 0 :: signed\n    if r5 goto L4 else goto L5 :: bool\nL4:\n    r6 = r3 >> 1\n    r7 = truncate r6: native_int to u8\n    r8 = r7\n    goto L6\nL5:\n    CPyUInt8_Overflow()\n    unreachable\nL6:\n    return r8\ndef ord_str_index_to_i64(s, i):\n    s :: str\n    i, r0 :: i64\n    r1, r2 :: bool\n    r3 :: short_int\n    r4 :: i64\nL0:\n    r0 = CPyStr_AdjustIndex(s, i)\n    r1 = CPyStr_RangeCheck(s, r0)\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = raise IndexError('index out of range')\n    unreachable\nL2:\n    r3 = CPyStr_GetItemUnsafeAsInt(s, r0)\n    r4 = r3 >> 1\n    return r4\n\n[case testStrip]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef do_strip(s: Union[str, NewStr]) -> None:\n    s.lstrip(\"x\")\n    s.strip(\"y\")\n    s.rstrip(\"z\")\n    s.lstrip()\n    s.strip()\n    s.rstrip()\n[typing fixtures/typing-full.pyi]\n[out]\ndef do_strip(s):\n    s, r0, r1, r2, r3, r4, r5, r6, r7, r8 :: str\nL0:\n    r0 = 'x'\n    r1 = CPyStr_LStrip(s, r0)\n    r2 = 'y'\n    r3 = CPyStr_Strip(s, r2)\n    r4 = 'z'\n    r5 = CPyStr_RStrip(s, r4)\n    r6 = CPyStr_LStrip(s, 0)\n    r7 = CPyStr_Strip(s, 0)\n    r8 = CPyStr_RStrip(s, 0)\n    return 1\n\n[case testCountAll_64bit]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef do_count(s: str) -> int:\n    return s.count(\"x\")\n[typing fixtures/typing-full.pyi]\n[out]\ndef do_count(s):\n    s, r0 :: str\n    r1 :: native_int\n    r2, r3, r4 :: bit\n    r5, r6, r7 :: int\nL0:\n    r0 = 'x'\n    r1 = CPyStr_Count(s, r0, 0)\n    r2 = r1 >= 0 :: signed\n    r3 = r1 <= 4611686018427387903 :: signed\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = r1 >= -4611686018427387904 :: signed\n    if r4 goto L3 else goto L2 :: bool\nL2:\n    r5 = CPyTagged_FromInt64(r1)\n    r6 = r5\n    goto L4\nL3:\n    r7 = r1 << 1\n    r6 = r7\nL4:\n    return r6\n\n[case testCountStart_64bit]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef do_count(s: str, start: int) -> int:\n    return s.count(\"x\", start)\n[typing fixtures/typing-full.pyi]\n[out]\ndef do_count(s, start):\n    s :: str\n    start :: int\n    r0 :: str\n    r1 :: native_int\n    r2, r3, r4 :: bit\n    r5, r6, r7 :: int\nL0:\n    r0 = 'x'\n    r1 = CPyStr_Count(s, r0, start)\n    r2 = r1 >= 0 :: signed\n    r3 = r1 <= 4611686018427387903 :: signed\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = r1 >= -4611686018427387904 :: signed\n    if r4 goto L3 else goto L2 :: bool\nL2:\n    r5 = CPyTagged_FromInt64(r1)\n    r6 = r5\n    goto L4\nL3:\n    r7 = r1 << 1\n    r6 = r7\nL4:\n    return r6\n\n[case testCountStartEnd_64bit]\nfrom typing import NewType, Union\nNewStr = NewType(\"NewStr\", str)\ndef do_count(s: str, start: int, end: int) -> int:\n    return s.count(\"x\", start, end)\n[typing fixtures/typing-full.pyi]\n[out]\ndef do_count(s, start, end):\n    s :: str\n    start, end :: int\n    r0 :: str\n    r1 :: native_int\n    r2, r3, r4 :: bit\n    r5, r6, r7 :: int\nL0:\n    r0 = 'x'\n    r1 = CPyStr_CountFull(s, r0, start, end)\n    r2 = r1 >= 0 :: signed\n    r3 = r1 <= 4611686018427387903 :: signed\n    if r3 goto L1 else goto L2 :: bool\nL1:\n    r4 = r1 >= -4611686018427387904 :: signed\n    if r4 goto L3 else goto L2 :: bool\nL2:\n    r5 = CPyTagged_FromInt64(r1)\n    r6 = r5\n    goto L4\nL3:\n    r7 = r1 << 1\n    r6 = r7\nL4:\n    return r6\n\n[case testFStringFromConstants]\nfrom typing import Final\nstring: Final = \"abc\"\ninteger: Final = 123\nfloating: Final = 3.14\nboolean: Final = True\n\ndef test(x: str) -> str:\n    return f\"{string}{integer}{floating}{boolean}{x}{boolean}{floating}{integer}{string}{x}{string}{integer}{floating}{boolean}\"\ndef test2(x: str) -> str:\n    return f\"{string}{integer}{floating}{boolean}{x}{boolean}{floating}{integer}{string}{x}{string}{integer}{floating}{boolean}{x}\"\ndef test3(x: str) -> str:\n    return f\"{x}{string}{integer}{floating}{boolean}{x}{boolean}{floating}{integer}{string}{x}{string}{integer}{floating}{boolean}{x}\"\n\n[out]\ndef test(x):\n    x, r0, r1, r2, r3 :: str\nL0:\n    r0 = 'abc1233.14True'\n    r1 = 'True3.14123abc'\n    r2 = 'abc1233.14True'\n    r3 = CPyStr_Build(5, r0, x, r1, x, r2)\n    return r3\ndef test2(x):\n    x, r0, r1, r2, r3 :: str\nL0:\n    r0 = 'abc1233.14True'\n    r1 = 'True3.14123abc'\n    r2 = 'abc1233.14True'\n    r3 = CPyStr_Build(6, r0, x, r1, x, r2, x)\n    return r3\ndef test3(x):\n    x, r0, r1, r2, r3 :: str\nL0:\n    r0 = 'abc1233.14True'\n    r1 = 'True3.14123abc'\n    r2 = 'abc1233.14True'\n    r3 = CPyStr_Build(7, x, r0, x, r1, x, r2, x)\n    return r3\n\n[case testOptionalStrEquality1]\nfrom typing import Optional\n\ndef opt_opt(x: Optional[str], y: Optional[str]) -> bool:\n    return x == y\n[out]\ndef opt_opt(x, y):\n    x, y :: union[str, None]\n    r0 :: object\n    r1 :: bit\n    r2 :: object\n    r3 :: bit\n    r4 :: bool\n    r5 :: object\n    r6 :: bit\n    r7, r8 :: str\n    r9 :: bool\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = load_address _Py_NoneStruct\n    r3 = y == r2\n    r4 = r3\n    goto L5\nL2:\n    r5 = load_address _Py_NoneStruct\n    r6 = y == r5\n    if r6 goto L3 else goto L4 :: bool\nL3:\n    r4 = 0\n    goto L5\nL4:\n    r7 = unchecked borrow cast(str, x)\n    r8 = unchecked borrow cast(str, y)\n    r9 = CPyStr_Equal(r7, r8)\n    r4 = r9\nL5:\n    keep_alive x, y\n    return r4\n\n[case testOptionalStrEquality2]\nfrom typing import Optional\n\ndef opt_non_opt(x: Optional[str], y: str) -> bool:\n    return x == y\n[out]\ndef opt_non_opt(x, y):\n    x :: union[str, None]\n    y :: str\n    r0 :: object\n    r1 :: bit\n    r2 :: bool\n    r3 :: str\n    r4 :: bool\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x == r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = 0\n    goto L3\nL2:\n    r3 = unchecked borrow cast(str, x)\n    r4 = CPyStr_Equal(r3, y)\n    r2 = r4\nL3:\n    keep_alive x\n    return r2\n\n[case testStrEqLiteral]\nfrom typing import Final\nliteral: Final = \"literal\"\ndef literal_rhs(x: str) -> bool:\n    return x == literal\ndef literal_lhs(x: str) -> bool:\n    return literal == x\ndef literal_both() -> bool:\n    return literal == \"literal\"\n[out]\ndef literal_rhs(x):\n    x, r0 :: str\n    r1 :: bool\nL0:\n    r0 = 'literal'\n    r1 = CPyStr_EqualLiteral(x, r0, 7)\n    return r1\ndef literal_lhs(x):\n    x, r0 :: str\n    r1 :: bool\nL0:\n    r0 = 'literal'\n    r1 = CPyStr_EqualLiteral(x, r0, 7)\n    return r1\ndef literal_both():\n    r0, r1 :: str\nL0:\n    r0 = 'literal'\n    r1 = 'literal'\n    return 1\n\n[case testStrMultiply]\ndef s_times_i(s: str, n: int) -> str:\n    return s * n\ndef i_times_s(s: str, n: int) -> str:\n    return n * s\n[out]\ndef s_times_i(s, n):\n    s :: str\n    n :: int\n    r0 :: str\nL0:\n    r0 = CPyStr_Multiply(s, n)\n    return r0\ndef i_times_s(s, n):\n    s :: str\n    n :: int\n    r0 :: str\nL0:\n    r0 = CPyStr_Multiply(s, n)\n    return r0\n\n[case testStrLower]\ndef do_lower(s: str) -> str:\n    return s.lower()\n[out]\ndef do_lower(s):\n    s, r0 :: str\nL0:\n    r0 = CPyStr_Lower(s)\n    return r0\n\n[case testStrUpper]\ndef do_upper(s: str) -> str:\n    return s.upper()\n[out]\ndef do_upper(s):\n    s, r0 :: str\nL0:\n    r0 = CPyStr_Upper(s)\n    return r0\n\n[case testStrIsSpace]\ndef is_space(x: str) -> bool:\n    return x.isspace()\n[out]\ndef is_space(x):\n    x :: str\n    r0 :: bool\nL0:\n    r0 = CPyStr_IsSpace(x)\n    return r0\n\n[case testStrIsAlnum]\ndef is_alnum(x: str) -> bool:\n    return x.isalnum()\n[out]\ndef is_alnum(x):\n    x :: str\n    r0 :: bool\nL0:\n    r0 = CPyStr_IsAlnum(x)\n    return r0\n\n[case testStrIsDigit]\ndef is_digit(x: str) -> bool:\n    return x.isdigit()\n[out]\ndef is_digit(x):\n    x :: str\n    r0 :: bool\nL0:\n    r0 = CPyStr_IsDigit(x)\n    return r0\n"
  },
  {
    "path": "mypyc/test-data/irbuild-strip-asserts.test",
    "content": "[case testStripAssert1]\ndef g():\n  x = 1 + 2\n  assert x < 5\n  return x\n[out]\ndef g():\n    r0, x :: object\nL0:\n    r0 = object 3\n    x = r0\n    return x\n"
  },
  {
    "path": "mypyc/test-data/irbuild-time.test",
    "content": "[case testTime_experimental]\nfrom librt.time import time\nimport librt.time\n\ndef t1() -> float:\n    return time()\n\ndef t2() -> float:\n    return librt.time.time()\n[out]\ndef t1():\n    r0 :: float\nL0:\n    r0 = LibRTTime_time()\n    return r0\ndef t2():\n    r0 :: float\nL0:\n    r0 = LibRTTime_time()\n    return r0\n\n[case testTimeExperimentalDisabled]\nfrom librt.time import time\n\ndef get_time() -> float:\n    return time()\n[out]\ndef get_time():\n    r0 :: dict\n    r1 :: str\n    r2, r3 :: object\n    r4 :: float\nL0:\n    r0 = __main__.globals :: static\n    r1 = 'time'\n    r2 = CPyDict_GetItem(r0, r1)\n    r3 = PyObject_Vectorcall(r2, 0, 0, 0)\n    r4 = unbox(float, r3)\n    return r4\n"
  },
  {
    "path": "mypyc/test-data/irbuild-try.test",
    "content": "[case testTryExcept1]\ndef g() -> None:\n    try:\n        object()\n    except:\n        print(\"weeee\")\n[out]\ndef g():\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4 :: tuple[object, object, object]\n    r5 :: str\n    r6 :: object\n    r7 :: str\n    r8 :: object\n    r9 :: object[1]\n    r10 :: object_ptr\n    r11 :: object\n    r12 :: bit\nL0:\nL1:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = PyObject_Vectorcall(r2, 0, 0, 0)\n    goto L5\nL2: (handler for L1)\n    r4 = CPy_CatchError()\n    r5 = 'weeee'\n    r6 = builtins :: module\n    r7 = 'print'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = [r5]\n    r10 = load_address r9\n    r11 = PyObject_Vectorcall(r8, r10, 1, 0)\n    keep_alive r5\nL3:\n    CPy_RestoreExcInfo(r4)\n    goto L5\nL4: (handler for L2)\n    CPy_RestoreExcInfo(r4)\n    r12 = CPy_KeepPropagating()\n    unreachable\nL5:\n    return 1\n\n[case testTryExcept2]\ndef g(b: bool) -> None:\n    try:\n        if b:\n            object()\n        else:\n            str('hi')\n    except:\n        print(\"weeee\")\n[out]\ndef g(b):\n    b :: bool\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\n    r4, r5 :: str\n    r6 :: tuple[object, object, object]\n    r7 :: str\n    r8 :: object\n    r9 :: str\n    r10 :: object\n    r11 :: object[1]\n    r12 :: object_ptr\n    r13 :: object\n    r14 :: bit\nL0:\nL1:\n    if b goto L2 else goto L3 :: bool\nL2:\n    r0 = builtins :: module\n    r1 = 'object'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = PyObject_Vectorcall(r2, 0, 0, 0)\n    goto L4\nL3:\n    r4 = 'hi'\n    r5 = PyObject_Str(r4)\nL4:\n    goto L8\nL5: (handler for L1, L2, L3, L4)\n    r6 = CPy_CatchError()\n    r7 = 'weeee'\n    r8 = builtins :: module\n    r9 = 'print'\n    r10 = CPyObject_GetAttr(r8, r9)\n    r11 = [r7]\n    r12 = load_address r11\n    r13 = PyObject_Vectorcall(r10, r12, 1, 0)\n    keep_alive r7\nL6:\n    CPy_RestoreExcInfo(r6)\n    goto L8\nL7: (handler for L5)\n    CPy_RestoreExcInfo(r6)\n    r14 = CPy_KeepPropagating()\n    unreachable\nL8:\n    return 1\n\n[case testTryExcept3]\ndef g() -> None:\n    try:\n        print('a')\n        try:\n            object()\n        except AttributeError as e:\n            print('b', e)\n    except:\n        print(\"weeee\")\n[out]\ndef g():\n    r0 :: str\n    r1 :: object\n    r2 :: str\n    r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6, r7 :: object\n    r8 :: str\n    r9, r10 :: object\n    r11 :: tuple[object, object, object]\n    r12 :: object\n    r13 :: str\n    r14 :: object\n    r15 :: bit\n    r16, e :: object\n    r17 :: str\n    r18 :: object\n    r19 :: str\n    r20 :: object\n    r21 :: object[2]\n    r22 :: object_ptr\n    r23 :: object\n    r24 :: bit\n    r25 :: tuple[object, object, object]\n    r26 :: str\n    r27 :: object\n    r28 :: str\n    r29 :: object\n    r30 :: object[1]\n    r31 :: object_ptr\n    r32 :: object\n    r33 :: bit\nL0:\nL1:\n    r0 = 'a'\n    r1 = builtins :: module\n    r2 = 'print'\n    r3 = CPyObject_GetAttr(r1, r2)\n    r4 = [r0]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r3, r5, 1, 0)\n    keep_alive r0\nL2:\n    r7 = builtins :: module\n    r8 = 'object'\n    r9 = CPyObject_GetAttr(r7, r8)\n    r10 = PyObject_Vectorcall(r9, 0, 0, 0)\n    goto L8\nL3: (handler for L2)\n    r11 = CPy_CatchError()\n    r12 = builtins :: module\n    r13 = 'AttributeError'\n    r14 = CPyObject_GetAttr(r12, r13)\n    r15 = CPy_ExceptionMatches(r14)\n    if r15 goto L4 else goto L5 :: bool\nL4:\n    r16 = CPy_GetExcValue()\n    e = r16\n    r17 = 'b'\n    r18 = builtins :: module\n    r19 = 'print'\n    r20 = CPyObject_GetAttr(r18, r19)\n    r21 = [r17, e]\n    r22 = load_address r21\n    r23 = PyObject_Vectorcall(r20, r22, 2, 0)\n    keep_alive r17, e\n    goto L6\nL5:\n    CPy_Reraise()\n    unreachable\nL6:\n    CPy_RestoreExcInfo(r11)\n    goto L8\nL7: (handler for L3, L4, L5)\n    CPy_RestoreExcInfo(r11)\n    r24 = CPy_KeepPropagating()\n    unreachable\nL8:\n    goto L12\nL9: (handler for L1, L6, L7, L8)\n    r25 = CPy_CatchError()\n    r26 = 'weeee'\n    r27 = builtins :: module\n    r28 = 'print'\n    r29 = CPyObject_GetAttr(r27, r28)\n    r30 = [r26]\n    r31 = load_address r30\n    r32 = PyObject_Vectorcall(r29, r31, 1, 0)\n    keep_alive r26\nL10:\n    CPy_RestoreExcInfo(r25)\n    goto L12\nL11: (handler for L9)\n    CPy_RestoreExcInfo(r25)\n    r33 = CPy_KeepPropagating()\n    unreachable\nL12:\n    return 1\n\n[case testTryExcept4]\ndef g() -> None:\n    try:\n        pass\n    except KeyError:\n        print(\"weeee\")\n    except IndexError:\n        print(\"yo\")\n[out]\ndef g():\n    r0 :: tuple[object, object, object]\n    r1 :: object\n    r2 :: str\n    r3 :: object\n    r4 :: bit\n    r5 :: str\n    r6 :: object\n    r7 :: str\n    r8 :: object\n    r9 :: object[1]\n    r10 :: object_ptr\n    r11, r12 :: object\n    r13 :: str\n    r14 :: object\n    r15 :: bit\n    r16 :: str\n    r17 :: object\n    r18 :: str\n    r19 :: object\n    r20 :: object[1]\n    r21 :: object_ptr\n    r22 :: object\n    r23 :: bit\nL0:\nL1:\n    goto L9\nL2: (handler for L1)\n    r0 = CPy_CatchError()\n    r1 = builtins :: module\n    r2 = 'KeyError'\n    r3 = CPyObject_GetAttr(r1, r2)\n    r4 = CPy_ExceptionMatches(r3)\n    if r4 goto L3 else goto L4 :: bool\nL3:\n    r5 = 'weeee'\n    r6 = builtins :: module\n    r7 = 'print'\n    r8 = CPyObject_GetAttr(r6, r7)\n    r9 = [r5]\n    r10 = load_address r9\n    r11 = PyObject_Vectorcall(r8, r10, 1, 0)\n    keep_alive r5\n    goto L7\nL4:\n    r12 = builtins :: module\n    r13 = 'IndexError'\n    r14 = CPyObject_GetAttr(r12, r13)\n    r15 = CPy_ExceptionMatches(r14)\n    if r15 goto L5 else goto L6 :: bool\nL5:\n    r16 = 'yo'\n    r17 = builtins :: module\n    r18 = 'print'\n    r19 = CPyObject_GetAttr(r17, r18)\n    r20 = [r16]\n    r21 = load_address r20\n    r22 = PyObject_Vectorcall(r19, r21, 1, 0)\n    keep_alive r16\n    goto L7\nL6:\n    CPy_Reraise()\n    unreachable\nL7:\n    CPy_RestoreExcInfo(r0)\n    goto L9\nL8: (handler for L2, L3, L4, L5, L6)\n    CPy_RestoreExcInfo(r0)\n    r23 = CPy_KeepPropagating()\n    unreachable\nL9:\n    return 1\n\n[case testTryFinally]\ndef a(b: bool) -> None:\n    try:\n        if b:\n            raise Exception('hi')\n    finally:\n        print('finally')\n[out]\ndef a(b):\n    b :: bool\n    r0 :: str\n    r1 :: object\n    r2 :: str\n    r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\n    r7, r8, r9 :: tuple[object, object, object]\n    r10 :: str\n    r11 :: object\n    r12 :: str\n    r13 :: object\n    r14 :: object[1]\n    r15 :: object_ptr\n    r16 :: object\n    r17 :: bit\nL0:\nL1:\n    if b goto L2 else goto L3 :: bool\nL2:\n    r0 = 'hi'\n    r1 = builtins :: module\n    r2 = 'Exception'\n    r3 = CPyObject_GetAttr(r1, r2)\n    r4 = [r0]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r3, r5, 1, 0)\n    keep_alive r0\n    CPy_Raise(r6)\n    unreachable\nL3:\nL4:\nL5:\n    r7 = <error> :: tuple[object, object, object]\n    r8 = r7\n    goto L7\nL6: (handler for L1, L2, L3)\n    r9 = CPy_CatchError()\n    r8 = r9\nL7:\n    r10 = 'finally'\n    r11 = builtins :: module\n    r12 = 'print'\n    r13 = CPyObject_GetAttr(r11, r12)\n    r14 = [r10]\n    r15 = load_address r14\n    r16 = PyObject_Vectorcall(r13, r15, 1, 0)\n    keep_alive r10\n    if is_error(r8) goto L9 else goto L8\nL8:\n    CPy_Reraise()\n    unreachable\nL9:\n    goto L13\nL10: (handler for L7, L8)\n    if is_error(r8) goto L12 else goto L11\nL11:\n    CPy_RestoreExcInfo(r8)\nL12:\n    r17 = CPy_KeepPropagating()\n    unreachable\nL13:\n    return 1\n\n[case testWith]\nfrom typing import Any\ndef foo(x: Any) -> None:\n    with x() as y:\n        print('hello')\n[out]\ndef foo(x):\n    x, r0, r1 :: object\n    r2 :: str\n    r3 :: object\n    r4 :: str\n    r5 :: object\n    r6 :: object[1]\n    r7 :: object_ptr\n    r8 :: object\n    r9 :: bool\n    y :: object\n    r10 :: str\n    r11 :: object\n    r12 :: str\n    r13 :: object\n    r14 :: object[1]\n    r15 :: object_ptr\n    r16 :: object\n    r17, r18 :: tuple[object, object, object]\n    r19, r20, r21 :: object\n    r22 :: object[4]\n    r23 :: object_ptr\n    r24 :: object\n    r25 :: i32\n    r26 :: bit\n    r27 :: bool\n    r28 :: bit\n    r29, r30, r31 :: tuple[object, object, object]\n    r32 :: object\n    r33 :: object[4]\n    r34 :: object_ptr\n    r35 :: object\n    r36 :: bit\nL0:\n    r0 = PyObject_Vectorcall(x, 0, 0, 0)\n    r1 = CPy_TYPE(r0)\n    r2 = '__exit__'\n    r3 = CPyObject_GetAttr(r1, r2)\n    r4 = '__enter__'\n    r5 = CPyObject_GetAttr(r1, r4)\n    r6 = [r0]\n    r7 = load_address r6\n    r8 = PyObject_Vectorcall(r5, r7, 1, 0)\n    keep_alive r0\n    r9 = 1\nL1:\nL2:\n    y = r8\n    r10 = 'hello'\n    r11 = builtins :: module\n    r12 = 'print'\n    r13 = CPyObject_GetAttr(r11, r12)\n    r14 = [r10]\n    r15 = load_address r14\n    r16 = PyObject_Vectorcall(r13, r15, 1, 0)\n    keep_alive r10\n    goto L8\nL3: (handler for L2)\n    r17 = CPy_CatchError()\n    r9 = 0\n    r18 = CPy_GetExcInfo()\n    r19 = r18[0]\n    r20 = r18[1]\n    r21 = r18[2]\n    r22 = [r0, r19, r20, r21]\n    r23 = load_address r22\n    r24 = PyObject_Vectorcall(r3, r23, 4, 0)\n    keep_alive r0, r19, r20, r21\n    r25 = PyObject_IsTrue(r24)\n    r26 = r25 >= 0 :: signed\n    r27 = truncate r25: i32 to builtins.bool\n    if r27 goto L5 else goto L4 :: bool\nL4:\n    CPy_Reraise()\n    unreachable\nL5:\nL6:\n    CPy_RestoreExcInfo(r17)\n    goto L8\nL7: (handler for L3, L4, L5)\n    CPy_RestoreExcInfo(r17)\n    r28 = CPy_KeepPropagating()\n    unreachable\nL8:\nL9:\nL10:\n    r29 = <error> :: tuple[object, object, object]\n    r30 = r29\n    goto L12\nL11: (handler for L1, L6, L7, L8)\n    r31 = CPy_CatchError()\n    r30 = r31\nL12:\n    if r9 goto L13 else goto L14 :: bool\nL13:\n    r32 = load_address _Py_NoneStruct\n    r33 = [r0, r32, r32, r32]\n    r34 = load_address r33\n    r35 = PyObject_Vectorcall(r3, r34, 4, 0)\n    keep_alive r0, r32, r32, r32\nL14:\n    if is_error(r30) goto L16 else goto L15\nL15:\n    CPy_Reraise()\n    unreachable\nL16:\n    goto L20\nL17: (handler for L12, L13, L14, L15)\n    if is_error(r30) goto L19 else goto L18\nL18:\n    CPy_RestoreExcInfo(r30)\nL19:\n    r36 = CPy_KeepPropagating()\n    unreachable\nL20:\n    return 1\n\n[case testWithNativeSimple]\nclass DummyContext:\n    def __enter__(self) -> None:\n        pass\n    def __exit__(self, exc_type, exc_val, exc_tb) -> None:\n        pass\n\ndef foo(x: DummyContext) -> None:\n    with x:\n        print('hello')\n[out]\ndef DummyContext.__enter__(self):\n    self :: __main__.DummyContext\nL0:\n    return 1\ndef DummyContext.__exit__(self, exc_type, exc_val, exc_tb):\n    self :: __main__.DummyContext\n    exc_type, exc_val, exc_tb :: object\nL0:\n    return 1\ndef foo(x):\n    x :: __main__.DummyContext\n    r0 :: None\n    r1 :: bool\n    r2 :: str\n    r3 :: object\n    r4 :: str\n    r5 :: object\n    r6 :: object[1]\n    r7 :: object_ptr\n    r8 :: object\n    r9, r10 :: tuple[object, object, object]\n    r11, r12, r13 :: object\n    r14 :: None\n    r15 :: object\n    r16 :: i32\n    r17 :: bit\n    r18 :: bool\n    r19 :: bit\n    r20, r21, r22 :: tuple[object, object, object]\n    r23 :: object\n    r24 :: None\n    r25 :: bit\nL0:\n    r0 = x.__enter__()\n    r1 = 1\nL1:\nL2:\n    r2 = 'hello'\n    r3 = builtins :: module\n    r4 = 'print'\n    r5 = CPyObject_GetAttr(r3, r4)\n    r6 = [r2]\n    r7 = load_address r6\n    r8 = PyObject_Vectorcall(r5, r7, 1, 0)\n    keep_alive r2\n    goto L8\nL3: (handler for L2)\n    r9 = CPy_CatchError()\n    r1 = 0\n    r10 = CPy_GetExcInfo()\n    r11 = r10[0]\n    r12 = r10[1]\n    r13 = r10[2]\n    r14 = x.__exit__(r11, r12, r13)\n    r15 = box(None, r14)\n    r16 = PyObject_IsTrue(r15)\n    r17 = r16 >= 0 :: signed\n    r18 = truncate r16: i32 to builtins.bool\n    if r18 goto L5 else goto L4 :: bool\nL4:\n    CPy_Reraise()\n    unreachable\nL5:\nL6:\n    CPy_RestoreExcInfo(r9)\n    goto L8\nL7: (handler for L3, L4, L5)\n    CPy_RestoreExcInfo(r9)\n    r19 = CPy_KeepPropagating()\n    unreachable\nL8:\nL9:\nL10:\n    r20 = <error> :: tuple[object, object, object]\n    r21 = r20\n    goto L12\nL11: (handler for L1, L6, L7, L8)\n    r22 = CPy_CatchError()\n    r21 = r22\nL12:\n    if r1 goto L13 else goto L14 :: bool\nL13:\n    r23 = load_address _Py_NoneStruct\n    r24 = x.__exit__(r23, r23, r23)\nL14:\n    if is_error(r21) goto L16 else goto L15\nL15:\n    CPy_Reraise()\n    unreachable\nL16:\n    goto L20\nL17: (handler for L12, L13, L14, L15)\n    if is_error(r21) goto L19 else goto L18\nL18:\n    CPy_RestoreExcInfo(r21)\nL19:\n    r25 = CPy_KeepPropagating()\n    unreachable\nL20:\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-tuple.test",
    "content": "[case testTupleGet]\nfrom typing import Tuple\n\ndef f(x: Tuple[Tuple[int, bool], bool]) -> int:\n    return x[0][0]\n[out]\ndef f(x):\n    x :: tuple[tuple[int, bool], bool]\n    r0 :: tuple[int, bool]\n    r1 :: int\nL0:\n    r0 = x[0]\n    r1 = r0[0]\n    return r1\n\n[case testTupleNew]\nfrom typing import Tuple\n\ndef f() -> int:\n    t = (True, 1)\n    return t[1]\n[out]\ndef f():\n    r0, t :: tuple[bool, int]\n    r1 :: int\nL0:\n    r0 = (1, 2)\n    t = r0\n    r1 = t[1]\n    return r1\n\n[case testTupleLen]\nfrom typing import Tuple\ndef f(x: Tuple[bool, bool, int]) -> int:\n    return len(x)\n[out]\ndef f(x):\n    x :: tuple[bool, bool, int]\nL0:\n    return 6\n\n[case testSequenceTuple]\nfrom typing import List\ndef f(x: List[bool]) -> bool:\n    return tuple(x)[1]\n[out]\ndef f(x):\n    x :: list\n    r0 :: tuple\n    r1 :: object\n    r2 :: bool\nL0:\n    r0 = PyList_AsTuple(x)\n    r1 = CPySequenceTuple_GetItem(r0, 2)\n    r2 = unbox(bool, r1)\n    return r2\n\n[case testSequenceTupleLen]\nfrom typing import Tuple\ndef f(x: Tuple[int, ...]) -> int:\n  return len(x)\n[out]\ndef f(x):\n    x :: tuple\n    r0 :: native_int\n    r1 :: short_int\nL0:\n    r0 = var_object_size x\n    r1 = r0 << 1\n    return r1\n\n[case testSequenceTupleForced]\nfrom typing import Tuple\ndef f() -> int:\n    t = (1, 2) # type: Tuple[int, ...]\n    return t[1]\n[out]\ndef f():\n    r0 :: tuple[int, int]\n    r1 :: object\n    t :: tuple\n    r2 :: object\n    r3 :: int\nL0:\n    r0 = (2, 4)\n    r1 = box(tuple[int, int], r0)\n    t = r1\n    r2 = CPySequenceTuple_GetItem(t, 2)\n    r3 = unbox(int, r2)\n    return r3\n\n[case testTupleDisplay]\nfrom typing import Sequence, Tuple\ndef f(x: Sequence[int], y: Sequence[int]) -> Tuple[int, ...]:\n    return (1, 2, *x, *y, 3)\n[out]\ndef f(x, y):\n    x, y :: object\n    r0 :: list\n    r1, r2 :: object\n    r3 :: ptr\n    r4, r5, r6 :: object\n    r7 :: i32\n    r8 :: bit\n    r9 :: tuple\nL0:\n    r0 = PyList_New(2)\n    r1 = object 1\n    r2 = object 2\n    r3 = list_items r0\n    buf_init_item r3, 0, r1\n    buf_init_item r3, 1, r2\n    keep_alive r0\n    r4 = CPyList_Extend(r0, x)\n    r5 = CPyList_Extend(r0, y)\n    r6 = object 3\n    r7 = PyList_Append(r0, r6)\n    r8 = r7 >= 0 :: signed\n    r9 = PyList_AsTuple(r0)\n    return r9\n\n[case testTupleFor]\nfrom typing import Tuple, List\ndef f(xs: Tuple[str, ...]) -> None:\n    for x in xs:\n        pass\n[out]\ndef f(xs):\n    xs :: tuple\n    r0, r1 :: native_int\n    r2 :: bit\n    r3 :: object\n    r4, x :: str\n    r5 :: native_int\nL0:\n    r0 = var_object_size xs\n    r1 = 0\nL1:\n    r2 = r1 < r0 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = CPySequenceTuple_GetItemUnsafe(xs, r1)\n    r4 = cast(str, r3)\n    x = r4\nL3:\n    r5 = r1 + 1\n    r1 = r5\n    goto L1\nL4:\n    return 1\n\n[case testNamedTupleAttribute]\nfrom typing import NamedTuple\n\nNT = NamedTuple('NT', [('x', int), ('y', int)])\n\ndef f(nt: NT, b: bool) -> int:\n    if b:\n        return nt.x\n    return nt.y\n[out]\ndef f(nt, b):\n    nt :: tuple\n    b :: bool\n    r0 :: object\n    r1 :: int\n    r2 :: object\n    r3 :: int\nL0:\n    if b goto L1 else goto L2 :: bool\nL1:\n    r0 = CPySequenceTuple_GetItem(nt, 0)\n    r1 = unbox(int, r0)\n    return r1\nL2:\n    r2 = CPySequenceTuple_GetItem(nt, 2)\n    r3 = unbox(int, r2)\n    return r3\n\n\n[case testTupleOperatorIn]\ndef f(i: int) -> bool:\n    return i in [1, 2, 3]\n[out]\ndef f(i):\n    i :: int\n    r0, r1, r2 :: bit\n    r3 :: bool\nL0:\n    r0 = int_eq i, 2\n    if r0 goto L4 else goto L1 :: bool\nL1:\n    r1 = int_eq i, 4\n    if r1 goto L4 else goto L2 :: bool\nL2:\n    r2 = int_eq i, 6\n    if r2 goto L4 else goto L3 :: bool\nL3:\n    r3 = 0\n    goto L5\nL4:\n    r3 = 1\nL5:\n    return r3\n\n[case testTupleOperatorNotIn]\ndef x() -> int:\n    return 1\ndef y() -> int:\n    return 2\ndef z() -> int:\n    return 3\n\ndef f() -> bool:\n    return z() not in (x(), y())\n[out]\ndef x():\nL0:\n    return 2\ndef y():\nL0:\n    return 4\ndef z():\nL0:\n    return 6\ndef f():\n    r0, r1, r2 :: int\n    r3, r4 :: bit\n    r5 :: bool\nL0:\n    r0 = z()\n    r1 = x()\n    r2 = y()\n    r3 = int_ne r0, r1\n    if r3 goto L1 else goto L3 :: bool\nL1:\n    r4 = int_ne r0, r2\n    if r4 goto L2 else goto L3 :: bool\nL2:\n    r5 = 1\n    goto L4\nL3:\n    r5 = 0\nL4:\n    return r5\n\n[case testTupleOperatorInFinalTuple]\nfrom typing import Final\n\ntt: Final = (1, 2)\n\ndef f(x: int) -> bool:\n    return x in tt\n[out]\ndef f(x):\n    x :: int\n    r0 :: tuple[int, int]\n    r1 :: bool\n    r2, r3 :: int\n    r4, r5 :: bit\n    r6 :: bool\nL0:\n    r0 = __main__.tt :: static\n    if is_error(r0) goto L1 else goto L2\nL1:\n    r1 = raise NameError('value for final name \"tt\" was not set')\n    unreachable\nL2:\n    r2 = r0[0]\n    r3 = r0[1]\n    r4 = int_eq x, r2\n    if r4 goto L5 else goto L3 :: bool\nL3:\n    r5 = int_eq x, r3\n    if r5 goto L5 else goto L4 :: bool\nL4:\n    r6 = 0\n    goto L6\nL5:\n    r6 = 1\nL6:\n    return r6\n\n[case testTupleBuiltFromList]\ndef f(val: int) -> bool:\n    return val % 2 == 0\n\ndef test() -> None:\n    source = [1, 2, 3]\n    a = tuple(f(x) for x in source)\n[out]\ndef f(val):\n    val, r0 :: int\n    r1 :: bit\nL0:\n    r0 = CPyTagged_Remainder(val, 4)\n    r1 = int_eq r0, 0\n    return r1\ndef test():\n    r0 :: list\n    r1, r2, r3 :: object\n    r4 :: ptr\n    source :: list\n    r5 :: native_int\n    r6 :: tuple\n    r7, r8 :: native_int\n    r9 :: bit\n    r10 :: object\n    r11, x :: int\n    r12 :: bool\n    r13 :: object\n    r14 :: native_int\n    a :: tuple\nL0:\n    r0 = PyList_New(3)\n    r1 = object 1\n    r2 = object 2\n    r3 = object 3\n    r4 = list_items r0\n    buf_init_item r4, 0, r1\n    buf_init_item r4, 1, r2\n    buf_init_item r4, 2, r3\n    keep_alive r0\n    source = r0\n    r5 = var_object_size source\n    r6 = PyTuple_New(r5)\n    r7 = 0\nL1:\n    r8 = var_object_size source\n    r9 = r7 < r8 :: signed\n    if r9 goto L2 else goto L4 :: bool\nL2:\n    r10 = list_get_item_unsafe source, r7\n    r11 = unbox(int, r10)\n    x = r11\n    r12 = f(x)\n    r13 = box(bool, r12)\n    CPySequenceTuple_SetItemUnsafe(r6, r7, r13)\nL3:\n    r14 = r7 + 1\n    r7 = r14\n    goto L1\nL4:\n    a = r6\n    return 1\n\n[case testTupleBuiltFromStr]\ndef f2(val: str) -> str:\n    return val + \"f2\"\n\ndef test() -> None:\n    source = \"abc\"\n    a = tuple(f2(x) for x in source)\n[out]\ndef f2(val):\n    val, r0, r1 :: str\nL0:\n    r0 = 'f2'\n    r1 = PyUnicode_Concat(val, r0)\n    return r1\ndef test():\n    r0, source :: str\n    r1 :: native_int\n    r2 :: bit\n    r3 :: tuple\n    r4 :: native_int\n    r5 :: bit\n    r6, x, r7 :: str\n    r8 :: native_int\n    a :: tuple\nL0:\n    r0 = 'abc'\n    source = r0\n    r1 = CPyStr_Size_size_t(source)\n    r2 = r1 >= 0 :: signed\n    r3 = PyTuple_New(r1)\n    r4 = 0\nL1:\n    r5 = r4 < r1 :: signed\n    if r5 goto L2 else goto L4 :: bool\nL2:\n    r6 = CPyStr_GetItemUnsafe(source, r4)\n    x = r6\n    r7 = f2(x)\n    CPySequenceTuple_SetItemUnsafe(r3, r4, r7)\nL3:\n    r8 = r4 + 1\n    r4 = r8\n    goto L1\nL4:\n    a = r3\n    return 1\n\n[case testTupleBuiltFromStrExpr]\ndef f2(val: str) -> str:\n    return val + \"f2\"\n\ndef test() -> None:\n    a = tuple(f2(x) for x in \"abc\")\n\n[out]\ndef f2(val):\n    val, r0, r1 :: str\nL0:\n    r0 = 'f2'\n    r1 = PyUnicode_Concat(val, r0)\n    return r1\ndef test():\n    r0 :: str\n    r1 :: tuple\n    r2 :: native_int\n    r3 :: bit\n    r4, x, r5 :: str\n    r6 :: native_int\n    a :: tuple\nL0:\n    r0 = 'abc'\n    r1 = PyTuple_New(3)\n    r2 = 0\n    goto L2\nL1:\n    r3 = r2 < 3 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = CPyStr_GetItemUnsafe(r0, r2)\n    x = r4\n    r5 = f2(x)\n    CPySequenceTuple_SetItemUnsafe(r1, r2, r5)\nL3:\n    r6 = r2 + 1\n    r2 = r6\n    goto L1\nL4:\n    a = r1\n    return 1\n\n[case testTupleBuiltFromConstantFolding]\nfrom typing import Final\n\nc: Final = \"c\"\n\ndef f2(val: str) -> str:\n    return val + \"f2\"\n\ndef test() -> None:\n    # `\"ab\" + c` should constant fold to \"abc\"\n    a = tuple(f2(x) for x in \"ab\" + c)\n\n[out]\ndef f2(val):\n    val, r0, r1 :: str\nL0:\n    r0 = 'f2'\n    r1 = PyUnicode_Concat(val, r0)\n    return r1\ndef test():\n    r0 :: str\n    r1 :: tuple\n    r2 :: native_int\n    r3 :: bit\n    r4, x, r5 :: str\n    r6 :: native_int\n    a :: tuple\nL0:\n    r0 = 'abc'\n    r1 = PyTuple_New(3)\n    r2 = 0\n    goto L2\nL1:\n    r3 = r2 < 3 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = CPyStr_GetItemUnsafe(r0, r2)\n    x = r4\n    r5 = f2(x)\n    CPySequenceTuple_SetItemUnsafe(r1, r2, r5)\nL3:\n    r6 = r2 + 1\n    r2 = r6\n    goto L1\nL4:\n    a = r1\n    return 1\n\n[case testTupleBuiltFromFinalStr]\nfrom typing import Final\n\nsource: Final = \"abc\"\n\ndef f2(val: str) -> str:\n    return val + \"f2\"\n\ndef test() -> None:\n    a = tuple(f2(x) for x in source)\n[out]\ndef f2(val):\n    val, r0, r1 :: str\nL0:\n    r0 = 'f2'\n    r1 = PyUnicode_Concat(val, r0)\n    return r1\ndef test():\n    r0 :: str\n    r1 :: tuple\n    r2 :: native_int\n    r3 :: bit\n    r4, x, r5 :: str\n    r6 :: native_int\n    a :: tuple\nL0:\n    r0 = 'abc'\n    r1 = PyTuple_New(3)\n    r2 = 0\n    goto L2\nL1:\n    r3 = r2 < 3 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = CPyStr_GetItemUnsafe(r0, r2)\n    x = r4\n    r5 = f2(x)\n    CPySequenceTuple_SetItemUnsafe(r1, r2, r5)\nL3:\n    r6 = r2 + 1\n    r2 = r6\n    goto L1\nL4:\n    a = r1\n    return 1\n\n[case testTupleBuiltFromBytes_64bit]\ndef f2(val: int) -> int:\n    return val + 2\n\ndef test() -> None:\n    source = b\"abc\"\n    a = tuple(f2(x) for x in source)\n\n[out]\ndef f2(val):\n    val, r0 :: int\nL0:\n    r0 = CPyTagged_Add(val, 4)\n    return r0\ndef test():\n    r0, source :: bytes\n    r1 :: native_int\n    r2 :: tuple\n    r3 :: native_int\n    r4, r5, r6 :: bit\n    r7, r8, r9, r10 :: int\n    r11 :: object\n    r12, x, r13 :: int\n    r14 :: object\n    r15 :: native_int\n    a :: tuple\nL0:\n    r0 = b'abc'\n    source = r0\n    r1 = var_object_size source\n    r2 = PyTuple_New(r1)\n    r3 = 0\nL1:\n    r4 = r3 < r1 :: signed\n    if r4 goto L2 else goto L8 :: bool\nL2:\n    r5 = r3 <= 4611686018427387903 :: signed\n    if r5 goto L3 else goto L4 :: bool\nL3:\n    r6 = r3 >= -4611686018427387904 :: signed\n    if r6 goto L5 else goto L4 :: bool\nL4:\n    r7 = CPyTagged_FromInt64(r3)\n    r8 = r7\n    goto L6\nL5:\n    r9 = r3 << 1\n    r8 = r9\nL6:\n    r10 = CPyBytes_GetItem(source, r8)\n    r11 = box(int, r10)\n    r12 = unbox(int, r11)\n    x = r12\n    r13 = f2(x)\n    r14 = box(int, r13)\n    CPySequenceTuple_SetItemUnsafe(r2, r3, r14)\nL7:\n    r15 = r3 + 1\n    r3 = r15\n    goto L1\nL8:\n    a = r2\n    return 1\n\n[case testTupleBuiltFromBytesExpr_64bit]\ndef f2(val: int) -> int:\n    return val + 2\n\ndef test() -> None:\n    a = tuple(f2(x) for x in b\"abc\")\n\n[out]\ndef f2(val):\n    val, r0 :: int\nL0:\n    r0 = CPyTagged_Add(val, 4)\n    return r0\ndef test():\n    r0 :: bytes\n    r1 :: tuple\n    r2 :: native_int\n    r3, r4, r5 :: bit\n    r6, r7, r8, r9 :: int\n    r10 :: object\n    r11, x, r12 :: int\n    r13 :: object\n    r14 :: native_int\n    a :: tuple\nL0:\n    r0 = b'abc'\n    r1 = PyTuple_New(3)\n    r2 = 0\n    goto L2\nL1:\n    r3 = r2 < 3 :: signed\n    if r3 goto L2 else goto L8 :: bool\nL2:\n    r4 = r2 <= 4611686018427387903 :: signed\n    if r4 goto L3 else goto L4 :: bool\nL3:\n    r5 = r2 >= -4611686018427387904 :: signed\n    if r5 goto L5 else goto L4 :: bool\nL4:\n    r6 = CPyTagged_FromInt64(r2)\n    r7 = r6\n    goto L6\nL5:\n    r8 = r2 << 1\n    r7 = r8\nL6:\n    r9 = CPyBytes_GetItem(r0, r7)\n    r10 = box(int, r9)\n    r11 = unbox(int, r10)\n    x = r11\n    r12 = f2(x)\n    r13 = box(int, r12)\n    CPySequenceTuple_SetItemUnsafe(r1, r2, r13)\nL7:\n    r14 = r2 + 1\n    r2 = r14\n    goto L1\nL8:\n    a = r1\n    return 1\n\n[case testTupleBuiltFromFinalBytes_64bit]\nfrom typing import Final\n\nsource: Final = b\"abc\"\n\ndef f2(val: int) -> int:\n    return val + 2\n\ndef test() -> None:\n    a = tuple(f2(x) for x in source)\n\n[out]\ndef f2(val):\n    val, r0 :: int\nL0:\n    r0 = CPyTagged_Add(val, 4)\n    return r0\ndef test():\n    r0 :: bytes\n    r1 :: bool\n    r2 :: native_int\n    r3 :: tuple\n    r4 :: native_int\n    r5, r6, r7 :: bit\n    r8, r9, r10, r11 :: int\n    r12 :: object\n    r13, x, r14 :: int\n    r15 :: object\n    r16 :: native_int\n    a :: tuple\nL0:\n    r0 = __main__.source :: static\n    if is_error(r0) goto L1 else goto L2\nL1:\n    r1 = raise NameError('value for final name \"source\" was not set')\n    unreachable\nL2:\n    r2 = var_object_size r0\n    r3 = PyTuple_New(r2)\n    r4 = 0\nL3:\n    r5 = r4 < r2 :: signed\n    if r5 goto L4 else goto L10 :: bool\nL4:\n    r6 = r4 <= 4611686018427387903 :: signed\n    if r6 goto L5 else goto L6 :: bool\nL5:\n    r7 = r4 >= -4611686018427387904 :: signed\n    if r7 goto L7 else goto L6 :: bool\nL6:\n    r8 = CPyTagged_FromInt64(r4)\n    r9 = r8\n    goto L8\nL7:\n    r10 = r4 << 1\n    r9 = r10\nL8:\n    r11 = CPyBytes_GetItem(r0, r9)\n    r12 = box(int, r11)\n    r13 = unbox(int, r12)\n    x = r13\n    r14 = f2(x)\n    r15 = box(int, r14)\n    CPySequenceTuple_SetItemUnsafe(r3, r4, r15)\nL9:\n    r16 = r4 + 1\n    r4 = r16\n    goto L3\nL10:\n    a = r3\n    return 1\n\n[case testTupleBuiltFromFixedLengthTuple]\ndef f(val: int) -> bool:\n    return val % 2 == 0\n\ndef test() -> None:\n    source = (1, 2, 3)\n    a = tuple(f(x) for x in source)\n[out]\ndef f(val):\n    val, r0 :: int\n    r1 :: bit\nL0:\n    r0 = CPyTagged_Remainder(val, 4)\n    r1 = int_eq r0, 0\n    return r1\ndef test():\n    r0, source :: tuple[int, int, int]\n    r1, r2, r3 :: int\n    r4, r5, r6 :: object\n    r7, r8 :: tuple\n    r9 :: native_int\n    r10 :: bit\n    r11 :: object\n    r12, x :: int\n    r13 :: bool\n    r14 :: object\n    r15 :: native_int\n    a :: tuple\nL0:\n    r0 = (2, 4, 6)\n    source = r0\n    r1 = source[0]\n    r2 = source[1]\n    r3 = source[2]\n    r4 = box(int, r1)\n    r5 = box(int, r2)\n    r6 = box(int, r3)\n    r7 = PyTuple_Pack(3, r4, r5, r6)\n    r8 = PyTuple_New(3)\n    r9 = 0\n    goto L2\nL1:\n    r10 = r9 < 3 :: signed\n    if r10 goto L2 else goto L4 :: bool\nL2:\n    r11 = CPySequenceTuple_GetItemUnsafe(r7, r9)\n    r12 = unbox(int, r11)\n    x = r12\n    r13 = f(x)\n    r14 = box(bool, r13)\n    CPySequenceTuple_SetItemUnsafe(r8, r9, r14)\nL3:\n    r15 = r9 + 1\n    r9 = r15\n    goto L1\nL4:\n    a = r8\n    return 1\n\n[case testTupleBuiltFromFinalFixedLengthTuple]\nfrom typing import Final\n\nsource: Final = (1, 2, 3)\n\ndef f(val: int) -> bool:\n    return val % 2 == 0\n\ndef test() -> None:\n    a = tuple(f(x) for x in source)\n[out]\ndef f(val):\n    val, r0 :: int\n    r1 :: bit\nL0:\n    r0 = CPyTagged_Remainder(val, 4)\n    r1 = int_eq r0, 0\n    return r1\ndef test():\n    r0 :: tuple[int, int, int]\n    r1 :: bool\n    r2, r3, r4 :: int\n    r5, r6, r7 :: object\n    r8, r9 :: tuple\n    r10 :: native_int\n    r11 :: bit\n    r12 :: object\n    r13, x :: int\n    r14 :: bool\n    r15 :: object\n    r16 :: native_int\n    a :: tuple\nL0:\n    r0 = __main__.source :: static\n    if is_error(r0) goto L1 else goto L2\nL1:\n    r1 = raise NameError('value for final name \"source\" was not set')\n    unreachable\nL2:\n    r2 = r0[0]\n    r3 = r0[1]\n    r4 = r0[2]\n    r5 = box(int, r2)\n    r6 = box(int, r3)\n    r7 = box(int, r4)\n    r8 = PyTuple_Pack(3, r5, r6, r7)\n    r9 = PyTuple_New(3)\n    r10 = 0\n    goto L4\nL3:\n    r11 = r10 < 3 :: signed\n    if r11 goto L4 else goto L6 :: bool\nL4:\n    r12 = CPySequenceTuple_GetItemUnsafe(r8, r10)\n    r13 = unbox(int, r12)\n    x = r13\n    r14 = f(x)\n    r15 = box(bool, r14)\n    CPySequenceTuple_SetItemUnsafe(r9, r10, r15)\nL5:\n    r16 = r10 + 1\n    r10 = r16\n    goto L3\nL6:\n    a = r9\n    return 1\n\n[case testTupleBuiltFromVariableLengthTuple]\nfrom typing import Tuple\n\ndef f(val: bool) -> bool:\n    return not val\n\ndef test(source: Tuple[bool, ...]) -> None:\n    a = tuple(f(x) for x in source)\n[out]\ndef f(val):\n    val, r0 :: bool\nL0:\n    r0 = val ^ 1\n    return r0\ndef test(source):\n    source :: tuple\n    r0 :: native_int\n    r1 :: tuple\n    r2 :: native_int\n    r3 :: bit\n    r4 :: object\n    r5, x, r6 :: bool\n    r7 :: object\n    r8 :: native_int\n    a :: tuple\nL0:\n    r0 = var_object_size source\n    r1 = PyTuple_New(r0)\n    r2 = 0\nL1:\n    r3 = r2 < r0 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = CPySequenceTuple_GetItemUnsafe(source, r2)\n    r5 = unbox(bool, r4)\n    x = r5\n    r6 = f(x)\n    r7 = box(bool, r6)\n    CPySequenceTuple_SetItemUnsafe(r1, r2, r7)\nL3:\n    r8 = r2 + 1\n    r2 = r8\n    goto L1\nL4:\n    a = r1\n    return 1\n\n[case testTupleBuiltFromLengthCheckable]\nfrom typing import Tuple\n\ndef f(val: bool) -> bool:\n    return not val\n\ndef test() -> None:\n    # this tuple is created from a very complex genexp but we can still compute the length and preallocate the tuple\n    a = tuple(\n        x\n        for x\n        in zip(\n            map(str, range(5)),\n            enumerate(sorted(reversed(tuple(\"abcdefg\"))))\n        )\n    )\n[out]\ndef f(val):\n    val, r0 :: bool\nL0:\n    r0 = val ^ 1\n    return r0\ndef test():\n    r0 :: list\n    r1, r2, r3 :: object\n    r4 :: object[1]\n    r5 :: object_ptr\n    r6 :: object\n    r7 :: range\n    r8 :: object\n    r9 :: str\n    r10 :: object\n    r11 :: object[2]\n    r12 :: object_ptr\n    r13 :: object\n    r14 :: str\n    r15 :: tuple\n    r16 :: object\n    r17 :: str\n    r18 :: object\n    r19 :: object[1]\n    r20 :: object_ptr\n    r21 :: object\n    r22 :: list\n    r23 :: object\n    r24 :: str\n    r25 :: object\n    r26 :: object[1]\n    r27 :: object_ptr\n    r28, r29 :: object\n    r30 :: str\n    r31 :: object\n    r32 :: object[2]\n    r33 :: object_ptr\n    r34, r35, r36 :: object\n    r37, x :: tuple[str, tuple[int, str]]\n    r38 :: object\n    r39 :: i32\n    r40, r41 :: bit\n    r42, a :: tuple\nL0:\n    r0 = PyList_New(0)\n    r1 = load_address PyUnicode_Type\n    r2 = load_address PyRange_Type\n    r3 = object 5\n    r4 = [r3]\n    r5 = load_address r4\n    r6 = PyObject_Vectorcall(r2, r5, 1, 0)\n    keep_alive r3\n    r7 = cast(range, r6)\n    r8 = builtins :: module\n    r9 = 'map'\n    r10 = CPyObject_GetAttr(r8, r9)\n    r11 = [r1, r7]\n    r12 = load_address r11\n    r13 = PyObject_Vectorcall(r10, r12, 2, 0)\n    keep_alive r1, r7\n    r14 = 'abcdefg'\n    r15 = PySequence_Tuple(r14)\n    r16 = builtins :: module\n    r17 = 'reversed'\n    r18 = CPyObject_GetAttr(r16, r17)\n    r19 = [r15]\n    r20 = load_address r19\n    r21 = PyObject_Vectorcall(r18, r20, 1, 0)\n    keep_alive r15\n    r22 = CPySequence_Sort(r21)\n    r23 = builtins :: module\n    r24 = 'enumerate'\n    r25 = CPyObject_GetAttr(r23, r24)\n    r26 = [r22]\n    r27 = load_address r26\n    r28 = PyObject_Vectorcall(r25, r27, 1, 0)\n    keep_alive r22\n    r29 = builtins :: module\n    r30 = 'zip'\n    r31 = CPyObject_GetAttr(r29, r30)\n    r32 = [r13, r28]\n    r33 = load_address r32\n    r34 = PyObject_Vectorcall(r31, r33, 2, 0)\n    keep_alive r13, r28\n    r35 = PyObject_GetIter(r34)\nL1:\n    r36 = PyIter_Next(r35)\n    if is_error(r36) goto L4 else goto L2\nL2:\n    r37 = unbox(tuple[str, tuple[int, str]], r36)\n    x = r37\n    r38 = box(tuple[str, tuple[int, str]], x)\n    r39 = PyList_Append(r0, r38)\n    r40 = r39 >= 0 :: signed\nL3:\n    goto L1\nL4:\n    r41 = CPy_NoErrOccurred()\nL5:\n    r42 = PyList_AsTuple(r0)\n    a = r42\n    return 1\n\n[case testTupleBuiltFromStars]\nfrom typing import Final\n\nabc: Final = \"abc\"\n\ndef test() -> None:\n    a = tuple(str(x) for x in [*abc, *\"def\", *b\"ghi\", (\"j\", \"k\"), *(\"l\", \"m\", \"n\")])\n\n[out]\ndef test():\n    r0, r1 :: str\n    r2 :: bytes\n    r3, r4 :: str\n    r5 :: tuple[str, str]\n    r6, r7, r8 :: str\n    r9 :: tuple[str, str, str]\n    r10 :: list\n    r11, r12, r13, r14 :: object\n    r15 :: i32\n    r16 :: bit\n    r17, r18 :: object\n    r19 :: tuple\n    r20, r21 :: native_int\n    r22 :: bit\n    r23, x :: object\n    r24 :: str\n    r25 :: native_int\n    a :: tuple\nL0:\n    r0 = 'abc'\n    r1 = 'def'\n    r2 = b'ghi'\n    r3 = 'j'\n    r4 = 'k'\n    r5 = (r3, r4)\n    r6 = 'l'\n    r7 = 'm'\n    r8 = 'n'\n    r9 = (r6, r7, r8)\n    r10 = PyList_New(0)\n    r11 = CPyList_Extend(r10, r0)\n    r12 = CPyList_Extend(r10, r1)\n    r13 = CPyList_Extend(r10, r2)\n    r14 = box(tuple[str, str], r5)\n    r15 = PyList_Append(r10, r14)\n    r16 = r15 >= 0 :: signed\n    r17 = box(tuple[str, str, str], r9)\n    r18 = CPyList_Extend(r10, r17)\n    r19 = PyTuple_New(13)\n    r20 = 0\n    goto L2\nL1:\n    r21 = var_object_size r10\n    r22 = r20 < r21 :: signed\n    if r22 goto L2 else goto L4 :: bool\nL2:\n    r23 = list_get_item_unsafe r10, r20\n    x = r23\n    r24 = PyObject_Str(x)\n    CPySequenceTuple_SetItemUnsafe(r19, r20, r24)\nL3:\n    r25 = r20 + 1\n    r20 = r25\n    goto L1\nL4:\n    a = r19\n    return 1\n\n[case testTupleAdd]\nfrom typing import Tuple\ndef f(a: Tuple[int, ...], b: Tuple[int, ...]) -> None:\n    c = a + b\n    d = a + (1, 2)\ndef g(a: Tuple[int, int], b: Tuple[int, int]) -> None:\n    c = a + b\n[out]\ndef f(a, b):\n    a, b, r0, c :: tuple\n    r1 :: tuple[int, int]\n    r2 :: object\n    r3, d :: tuple\nL0:\n    r0 = PySequence_Concat(a, b)\n    c = r0\n    r1 = (2, 4)\n    r2 = box(tuple[int, int], r1)\n    r3 = PySequence_Concat(a, r2)\n    d = r3\n    return 1\ndef g(a, b):\n    a, b :: tuple[int, int]\n    r0, r1 :: object\n    r2 :: tuple\n    r3, c :: tuple[int, int, int, int]\nL0:\n    r0 = box(tuple[int, int], a)\n    r1 = box(tuple[int, int], b)\n    r2 = PySequence_Concat(r0, r1)\n    r3 = unbox(tuple[int, int, int, int], r2)\n    c = r3\n    return 1\n\n[case testTupleMultiply]\nfrom typing import Tuple\ndef f(a: Tuple[int]) -> None:\n    b = a * 2\n    c = 3 * (2,)\ndef g(a: Tuple[int, ...]) -> None:\n    b = a * 2\n[out]\ndef f(a):\n    a :: tuple[int]\n    r0 :: object\n    r1 :: tuple\n    r2, b :: tuple[int, int]\n    r3 :: tuple[int]\n    r4 :: object\n    r5 :: tuple\n    r6, c :: tuple[int, int, int]\nL0:\n    r0 = box(tuple[int], a)\n    r1 = CPySequence_Multiply(r0, 4)\n    r2 = unbox(tuple[int, int], r1)\n    b = r2\n    r3 = (4)\n    r4 = box(tuple[int], r3)\n    r5 = CPySequence_RMultiply(6, r4)\n    r6 = unbox(tuple[int, int, int], r5)\n    c = r6\n    return 1\ndef g(a):\n    a, r0, b :: tuple\nL0:\n    r0 = CPySequence_Multiply(a, 4)\n    b = r0\n    return 1\n\n[case testTupleFloatElementComparison]\ndef f(x: tuple[float], y: tuple[float]) -> bool:\n    return x == y\n\n[out]\ndef f(x, y):\n    x, y :: tuple[float]\n    r0, r1 :: float\n    r2 :: bit\n    r3 :: bool\nL0:\n    r0 = x[0]\n    r1 = y[0]\n    r2 = r0 == r1\n    if not r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = 0\n    goto L3\nL2:\n    r3 = 1\nL3:\n    return r3\n"
  },
  {
    "path": "mypyc/test-data/irbuild-u8.test",
    "content": "# Test cases for u8 native ints. Focus on things that are different from i64; no need to\n# duplicate all i64 test cases here.\n\n[case testU8BinaryOp]\nfrom mypy_extensions import u8\n\ndef add_op(x: u8, y: u8) -> u8:\n    x = y + x\n    y = x + 5\n    y += x\n    y += 7\n    x = 5 + y\n    return x\ndef compare(x: u8, y: u8) -> None:\n    a = x == y\n    b = x == 5\n    c = x < y\n    d = x < 5\n    e = 5 == x\n    f = 5 < x\n[out]\ndef add_op(x, y):\n    x, y, r0, r1, r2, r3, r4 :: u8\nL0:\n    r0 = y + x\n    x = r0\n    r1 = x + 5\n    y = r1\n    r2 = y + x\n    y = r2\n    r3 = y + 7\n    y = r3\n    r4 = 5 + y\n    x = r4\n    return x\ndef compare(x, y):\n    x, y :: u8\n    r0 :: bit\n    a :: bool\n    r1 :: bit\n    b :: bool\n    r2 :: bit\n    c :: bool\n    r3 :: bit\n    d :: bool\n    r4 :: bit\n    e :: bool\n    r5 :: bit\n    f :: bool\nL0:\n    r0 = x == y\n    a = r0\n    r1 = x == 5\n    b = r1\n    r2 = x < y :: unsigned\n    c = r2\n    r3 = x < 5 :: unsigned\n    d = r3\n    r4 = 5 == x\n    e = r4\n    r5 = 5 < x :: unsigned\n    f = r5\n    return 1\n\n[case testU8UnaryOp]\nfrom mypy_extensions import u8\n\ndef unary(x: u8) -> u8:\n    y = -x\n    x = ~y\n    y = +x\n    return y\n[out]\ndef unary(x):\n    x, r0, y, r1 :: u8\nL0:\n    r0 = 0 - x\n    y = r0\n    r1 = y ^ 255\n    x = r1\n    y = x\n    return y\n\n[case testU8DivisionByConstant]\nfrom mypy_extensions import u8\n\ndef div_by_constant(x: u8) -> u8:\n    x = x // 5\n    x //= 17\n    return x\n[out]\ndef div_by_constant(x):\n    x, r0, r1 :: u8\nL0:\n    r0 = x / 5\n    x = r0\n    r1 = x / 17\n    x = r1\n    return x\n\n[case testU8ModByConstant]\nfrom mypy_extensions import u8\n\ndef mod_by_constant(x: u8) -> u8:\n    x = x % 5\n    x %= 17\n    return x\n[out]\ndef mod_by_constant(x):\n    x, r0, r1 :: u8\nL0:\n    r0 = x % 5\n    x = r0\n    r1 = x % 17\n    x = r1\n    return x\n\n[case testU8DivModByVariable]\nfrom mypy_extensions import u8\n\ndef divmod(x: u8, y: u8) -> u8:\n    a = x // y\n    return a % y\n[out]\ndef divmod(x, y):\n    x, y :: u8\n    r0 :: bit\n    r1 :: bool\n    r2, a :: u8\n    r3 :: bit\n    r4 :: bool\n    r5 :: u8\nL0:\n    r0 = y == 0\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = raise ZeroDivisionError('integer division or modulo by zero')\n    unreachable\nL2:\n    r2 = x / y\n    a = r2\n    r3 = y == 0\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = raise ZeroDivisionError('integer division or modulo by zero')\n    unreachable\nL4:\n    r5 = a % y\n    return r5\n\n[case testU8BinaryOperationWithOutOfRangeOperand]\nfrom mypy_extensions import u8\n\ndef out_of_range(x: u8) -> None:\n    x + (-1)\n    (-2) + x\n    x * 256\n    -1 < x\n    x > -5\n    x == 1000\n    x + 255  # OK\n    255 + x   # OK\n[out]\nmain:4: error: Value -1 is out of range for \"u8\"\nmain:5: error: Value -2 is out of range for \"u8\"\nmain:6: error: Value 256 is out of range for \"u8\"\nmain:7: error: Value -1 is out of range for \"u8\"\nmain:8: error: Value -5 is out of range for \"u8\"\nmain:9: error: Value 1000 is out of range for \"u8\"\n\n[case testU8DetectMoreOutOfRangeLiterals]\nfrom mypy_extensions import u8\n\ndef out_of_range() -> None:\n    a: u8 = 256\n    b: u8 = -1\n    f(256)\n    # The following are ok\n    c: u8 = 0\n    d: u8 = 255\n    f(0)\n    f(255)\n\ndef f(x: u8) -> None: pass\n[out]\nmain:4: error: Value 256 is out of range for \"u8\"\nmain:5: error: Value -1 is out of range for \"u8\"\nmain:6: error: Value 256 is out of range for \"u8\"\n\n[case testU8BoxAndUnbox]\nfrom typing import Any\nfrom mypy_extensions import u8\n\ndef f(x: Any) -> Any:\n    y: u8 = x\n    return y\n[out]\ndef f(x):\n    x :: object\n    r0, y :: u8\n    r1 :: object\nL0:\n    r0 = unbox(u8, x)\n    y = r0\n    r1 = box(u8, y)\n    return r1\n\n[case testU8MixedCompare1]\nfrom mypy_extensions import u8\ndef f(x: int, y: u8) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x :: int\n    y :: u8\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6 :: u8\n    r7 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = x < 512 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = x >= 0 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = x >> 1\n    r5 = truncate r4: native_int to u8\n    r6 = r5\n    goto L5\nL4:\n    CPyUInt8_Overflow()\n    unreachable\nL5:\n    r7 = r6 == y\n    return r7\n\n[case testU8MixedCompare2]\nfrom mypy_extensions import u8\ndef f(x: u8, y: int) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x :: u8\n    y :: int\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6 :: u8\n    r7 :: bit\nL0:\n    r0 = y & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = y < 512 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = y >= 0 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = y >> 1\n    r5 = truncate r4: native_int to u8\n    r6 = r5\n    goto L5\nL4:\n    CPyUInt8_Overflow()\n    unreachable\nL5:\n    r7 = x == r6\n    return r7\n\n[case testU8ConvertToInt]\nfrom mypy_extensions import u8\n\ndef u8_to_int(a: u8) -> int:\n    return a\n[out]\ndef u8_to_int(a):\n    a :: u8\n    r0 :: native_int\n    r1 :: int\nL0:\n    r0 = extend a: u8 to native_int\n    r1 = r0 << 1\n    return r1\n\n[case testU8OperatorAssignmentMixed]\nfrom mypy_extensions import u8\n\ndef f(a: u8) -> None:\n    x = 0\n    x += a\n[out]\ndef f(a):\n    a :: u8\n    x :: int\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6, r7 :: u8\n    r8 :: native_int\n    r9 :: int\nL0:\n    x = 0\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = x < 512 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = x >= 0 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = x >> 1\n    r5 = truncate r4: native_int to u8\n    r6 = r5\n    goto L5\nL4:\n    CPyUInt8_Overflow()\n    unreachable\nL5:\n    r7 = r6 + a\n    r8 = extend r7: u8 to native_int\n    r9 = r8 << 1\n    x = r9\n    return 1\n\n[case testU8InitializeFromLiteral]\nfrom mypy_extensions import u8, i64\n\ndef f() -> None:\n    x: u8 = 0\n    y: u8 = 255\n    z: u8 = 5 + 7\n[out]\ndef f():\n    x, y, z :: u8\nL0:\n    x = 0\n    y = 255\n    z = 12\n    return 1\n\n[case testU8ExplicitConversionFromNativeInt]\nfrom mypy_extensions import i64, i32, i16, u8\n\ndef from_u8(x: u8) -> u8:\n    return u8(x)\n\ndef from_i16(x: i16) -> u8:\n    return u8(x)\n\ndef from_i32(x: i32) -> u8:\n    return u8(x)\n\ndef from_i64(x: i64) -> u8:\n    return u8(x)\n[out]\ndef from_u8(x):\n    x :: u8\nL0:\n    return x\ndef from_i16(x):\n    x :: i16\n    r0 :: u8\nL0:\n    r0 = truncate x: i16 to u8\n    return r0\ndef from_i32(x):\n    x :: i32\n    r0 :: u8\nL0:\n    r0 = truncate x: i32 to u8\n    return r0\ndef from_i64(x):\n    x :: i64\n    r0 :: u8\nL0:\n    r0 = truncate x: i64 to u8\n    return r0\n\n[case testU8ExplicitConversionToNativeInt]\nfrom mypy_extensions import i64, i32, i16, u8\n\ndef to_i16(x: u8) -> i16:\n    return i16(x)\n\ndef to_i32(x: u8) -> i32:\n    return i32(x)\n\ndef to_i64(x: u8) -> i64:\n    return i64(x)\n[out]\ndef to_i16(x):\n    x :: u8\n    r0 :: i16\nL0:\n    r0 = extend x: u8 to i16\n    return r0\ndef to_i32(x):\n    x :: u8\n    r0 :: i32\nL0:\n    r0 = extend x: u8 to i32\n    return r0\ndef to_i64(x):\n    x :: u8\n    r0 :: i64\nL0:\n    r0 = extend x: u8 to i64\n    return r0\n\n[case testU8ExplicitConversionFromInt]\nfrom mypy_extensions import u8\n\ndef f(x: int) -> u8:\n    return u8(x)\n[out]\ndef f(x):\n    x :: int\n    r0 :: native_int\n    r1, r2, r3 :: bit\n    r4 :: native_int\n    r5, r6 :: u8\nL0:\n    r0 = x & 1\n    r1 = r0 == 0\n    if r1 goto L1 else goto L4 :: bool\nL1:\n    r2 = x < 512 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = x >= 0 :: signed\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    r4 = x >> 1\n    r5 = truncate r4: native_int to u8\n    r6 = r5\n    goto L5\nL4:\n    CPyUInt8_Overflow()\n    unreachable\nL5:\n    return r6\n\n[case testU8ExplicitConversionFromLiteral]\nfrom mypy_extensions import u8\n\ndef f() -> None:\n    x = u8(0)\n    y = u8(11)\n    z = u8(-3)  # Truncate\n    zz = u8(258)  # Truncate\n    a = u8(255)\n[out]\ndef f():\n    x, y, z, zz, a :: u8\nL0:\n    x = 0\n    y = 11\n    z = 253\n    zz = 2\n    a = 255\n    return 1\n\n[case testU8ExplicitConversionFromVariousTypes]\nfrom mypy_extensions import u8\n\ndef bool_to_u8(b: bool) -> u8:\n    return u8(b)\n\ndef str_to_u8(s: str) -> u8:\n    return u8(s)\n\nclass C:\n    def __int__(self) -> u8:\n        return 5\n\ndef instance_to_u8(c: C) -> u8:\n    return u8(c)\n\ndef float_to_u8(x: float) -> u8:\n    return u8(x)\n[out]\ndef bool_to_u8(b):\n    b :: bool\n    r0 :: u8\nL0:\n    r0 = extend b: builtins.bool to u8\n    return r0\ndef str_to_u8(s):\n    s :: str\n    r0 :: object\n    r1 :: u8\nL0:\n    r0 = CPyLong_FromStr(s)\n    r1 = unbox(u8, r0)\n    return r1\ndef C.__int__(self):\n    self :: __main__.C\nL0:\n    return 5\ndef instance_to_u8(c):\n    c :: __main__.C\n    r0 :: u8\nL0:\n    r0 = c.__int__()\n    return r0\ndef float_to_u8(x):\n    x :: float\n    r0 :: int\n    r1 :: native_int\n    r2, r3, r4 :: bit\n    r5 :: native_int\n    r6, r7 :: u8\nL0:\n    r0 = CPyTagged_FromFloat(x)\n    r1 = r0 & 1\n    r2 = r1 == 0\n    if r2 goto L1 else goto L4 :: bool\nL1:\n    r3 = r0 < 512 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = r0 >= 0 :: signed\n    if r4 goto L3 else goto L4 :: bool\nL3:\n    r5 = r0 >> 1\n    r6 = truncate r5: native_int to u8\n    r7 = r6\n    goto L5\nL4:\n    CPyUInt8_Overflow()\n    unreachable\nL5:\n    return r7\n"
  },
  {
    "path": "mypyc/test-data/irbuild-unreachable.test",
    "content": "# Test cases for unreachable expressions and statements\n\n[case testUnreachableMemberExpr]\nimport sys\n\ndef f() -> None:\n    y = sys.platform == \"x\" and sys.version_info > (3, 5)\n[out]\ndef f():\n    r0 :: object\n    r1 :: str\n    r2 :: object\n    r3, r4 :: str\n    r5, r6, r7 :: bool\n    r8 :: object\n    r9, y :: bool\nL0:\n    r0 = sys :: module\n    r1 = 'platform'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = cast(str, r2)\n    r4 = 'x'\n    r5 = CPyStr_EqualLiteral(r3, r4, 1)\n    if r5 goto L2 else goto L1 :: bool\nL1:\n    r6 = r5\n    goto L3\nL2:\n    r7 = raise RuntimeError('mypyc internal error: should be unreachable')\n    r8 = box(None, 1)\n    r9 = unbox(bool, r8)\n    r6 = r9\nL3:\n    y = r6\n    return 1\n\n[case testUnreachableNameExpr]\nimport sys\n\ndef f() -> None:\n    y = sys.platform == 'x' and foobar\n[out]\ndef f():\n    r0 :: object\n    r1 :: str\n    r2 :: object\n    r3, r4 :: str\n    r5, r6, r7 :: bool\n    r8 :: object\n    r9, y :: bool\nL0:\n    r0 = sys :: module\n    r1 = 'platform'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = cast(str, r2)\n    r4 = 'x'\n    r5 = CPyStr_EqualLiteral(r3, r4, 1)\n    if r5 goto L2 else goto L1 :: bool\nL1:\n    r6 = r5\n    goto L3\nL2:\n    r7 = raise RuntimeError('mypyc internal error: should be unreachable')\n    r8 = box(None, 1)\n    r9 = unbox(bool, r8)\n    r6 = r9\nL3:\n    y = r6\n    return 1\n\n[case testUnreachableFinalNameExpr]\nfrom typing import Final\n\nZERO: Final = 0\n\ndef f(x: int) -> int:\n    if x is None:\n        return ZERO\n    return ZERO\n[out]\ndef f(x):\n    x :: int\n    r0, r1 :: object\n    r2 :: bit\n    r3 :: object\n    r4 :: int\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = box(int, x)\n    r2 = r1 == r0\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = object 0\n    r4 = unbox(int, r3)\n    return r4\nL2:\n    return 0\n\n[case testUnreachableStatementAfterReturn]\ndef f(x: bool) -> int:\n    if x:\n        return 1\n        f(False)\n    return 2\n[out]\ndef f(x):\n    x :: bool\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 4\n\n[case testUnreachableStatementAfterContinue]\ndef c() -> bool:\n    return False\n\ndef f() -> None:\n    n = True\n    while n:\n        if c():\n            continue\n            if int():\n                f()\n        n = False\n[out]\ndef c():\nL0:\n    return 0\ndef f():\n    n, r0 :: bool\nL0:\n    n = 1\nL1:\n    if n goto L2 else goto L5 :: bool\nL2:\n    r0 = c()\n    if r0 goto L3 else goto L4 :: bool\nL3:\n    goto L1\nL4:\n    n = 0\n    goto L1\nL5:\n    return 1\n\n[case testUnreachableStatementAfterBreak]\ndef c() -> bool:\n    return False\n\ndef f() -> None:\n    n = True\n    while n:\n        if c():\n            break\n            if int():\n                f()\n        n = False\n[out]\ndef c():\nL0:\n    return 0\ndef f():\n    n, r0 :: bool\nL0:\n    n = 1\nL1:\n    if n goto L2 else goto L5 :: bool\nL2:\n    r0 = c()\n    if r0 goto L3 else goto L4 :: bool\nL3:\n    goto L5\nL4:\n    n = 0\n    goto L1\nL5:\n    return 1\n\n[case testUnreachableStatementAfterRaise]\ndef f(x: bool) -> int:\n    if x:\n        raise ValueError()\n        print('hello')\n    return 2\n[out]\ndef f(x):\n    x :: bool\n    r0 :: object\n    r1 :: str\n    r2, r3 :: object\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    r0 = builtins :: module\n    r1 = 'ValueError'\n    r2 = CPyObject_GetAttr(r0, r1)\n    r3 = PyObject_Vectorcall(r2, 0, 0, 0)\n    CPy_Raise(r3)\n    unreachable\nL2:\n    return 4\n\n[case testUnreachableStatementAfterAssertFalse]\ndef f(x: bool) -> int:\n    if x:\n        assert False\n        print('hello')\n    return 2\n[out]\ndef f(x):\n    x, r0 :: bool\n    r1 :: str\n    r2 :: object\n    r3 :: str\n    r4 :: object\n    r5 :: object[1]\n    r6 :: object_ptr\n    r7 :: object\nL0:\n    if x goto L1 else goto L4 :: bool\nL1:\n    if 0 goto L3 else goto L2 :: bool\nL2:\n    r0 = raise AssertionError\n    unreachable\nL3:\n    r1 = 'hello'\n    r2 = builtins :: module\n    r3 = 'print'\n    r4 = CPyObject_GetAttr(r2, r3)\n    r5 = [r1]\n    r6 = load_address r5\n    r7 = PyObject_Vectorcall(r4, r6, 1, 0)\n    keep_alive r1\nL4:\n    return 4\n"
  },
  {
    "path": "mypyc/test-data/irbuild-vec-i64.test",
    "content": "-- Test cases for vec[i64]. These also partially cover other unboxed item types,\n-- which use a similar runtime representation.\n\n[case testVecI64CreateEmpty]\nfrom librt.vecs import vec, append\nfrom mypy_extensions import i64\n\ndef f() -> vec[i64]:\n    return vec[i64]()\n[out]\ndef f():\n    r0 :: vec[i64]\nL0:\n    r0 = VecI64Api.alloc(0, 0)\n    return r0\n\n[case testVecI64Len_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[i64]) -> i64:\n    l = len(v)\n    return l\n[out]\ndef f(v):\n    v :: vec[i64]\n    r0 :: native_int\n    l :: i64\nL0:\n    r0 = v.len\n    l = r0\n    return l\n\n[case testVecI64Len_32bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[i64]) -> i64:\n    l = len(v)\n    return l\n[out]\ndef f(v):\n    v :: vec[i64]\n    r0 :: native_int\n    r1, l :: i64\nL0:\n    r0 = v.len\n    r1 = extend signed r0: native_int to i64\n    l = r1\n    return l\n\n[case testVecI64GetItem_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[i64], i: i64) -> i64:\n    return v[i]\n[out]\ndef f(v, i):\n    v :: vec[i64]\n    i :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: i64\nL0:\n    r0 = v.len\n    r1 = i < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = i + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = i\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecI64BufObject\n    r8 = r5 * 8\n    r9 = r7 + r8\n    r10 = load_mem r9 :: i64*\n    keep_alive v\n    return r10\n\n[case testVecI64GetItem_32bit]\n# The IR is quite verbose, but it's acceptable since 32-bit targets are not common any more\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[i64], i: i64) -> i64:\n    return v[i]\n[out]\ndef f(v, i):\n    v :: vec[i64]\n    i :: i64\n    r0 :: native_int\n    r1 :: i64\n    r2 :: bit\n    r3 :: i64\n    r4 :: bit\n    r5 :: bool\n    r6 :: i64\n    r7, r8 :: bit\n    r9 :: native_int\n    r10 :: object\n    r11 :: ptr\n    r12 :: native_int\n    r13 :: ptr\n    r14 :: i64\nL0:\n    r0 = v.len\n    r1 = extend signed r0: native_int to i64\n    r2 = i < r1 :: unsigned\n    if r2 goto L4 else goto L1 :: bool\nL1:\n    r3 = i + r1\n    r4 = r3 < r1 :: unsigned\n    if r4 goto L3 else goto L2 :: bool\nL2:\n    r5 = raise IndexError\n    unreachable\nL3:\n    r6 = r3\n    goto L5\nL4:\n    r6 = i\nL5:\n    r7 = r6 < 2147483648 :: signed\n    if r7 goto L6 else goto L8 :: bool\nL6:\n    r8 = r6 >= -2147483648 :: signed\n    if r8 goto L7 else goto L8 :: bool\nL7:\n    r9 = truncate r6: i64 to native_int\n    goto L9\nL8:\n    CPyInt32_Overflow()\n    unreachable\nL9:\n    r10 = v.buf\n    r11 = get_element_ptr r10 items :: VecI64BufObject\n    r12 = r9 * 8\n    r13 = r11 + r12\n    r14 = load_mem r13 :: i64*\n    keep_alive v\n    return r14\n\n[case testVecI64Append]\nfrom librt.vecs import vec, append\nfrom mypy_extensions import i64\n\ndef f(v: vec[i64], i: i64) -> vec[i64]:\n    return append(v, i)\n[out]\ndef f(v, i):\n    v :: vec[i64]\n    i :: i64\n    r0 :: vec[i64]\nL0:\n    r0 = VecI64Api.append(v, i)\n    return r0\n\n[case testVecI64SetItem_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[i64], i: i64, x: i64) -> None:\n    v[i] = x\n[out]\ndef f(v, i, x):\n    v :: vec[i64]\n    i, x :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\nL0:\n    r0 = v.len\n    r1 = i < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = i + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = i\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecI64BufObject\n    r8 = r5 * 8\n    r9 = r7 + r8\n    set_mem r9, x :: i64*\n    keep_alive v\n    return 1\n\n[case testVecI64ConstructFromListExpr]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f() -> vec[i64]:\n    return vec[i64]([1, 5, 14])\n[out]\ndef f():\n    r0 :: vec[i64]\n    r1 :: object\n    r2, r3, r4, r5 :: ptr\nL0:\n    r0 = VecI64Api.alloc(3, 3)\n    r1 = r0.buf\n    r2 = get_element_ptr r1 items :: VecI64BufObject\n    set_mem r2, 1 :: i64*\n    r3 = r2 + 8\n    set_mem r3, 5 :: i64*\n    r4 = r3 + 8\n    set_mem r4, 14 :: i64*\n    r5 = r4 + 8\n    keep_alive r0\n    return r0\n\n[case testVecI64ConstructFromListMultiply_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(n: i64) -> vec[i64]:\n    return vec[i64]([3] * n)\n[out]\ndef f(n):\n    n :: i64\n    r0 :: vec[i64]\n    r1 :: object\n    r2 :: ptr\n    r3 :: i64\n    r4, r5 :: ptr\n    r6 :: bit\n    r7 :: ptr\nL0:\n    r0 = VecI64Api.alloc(n, n)\n    r1 = r0.buf\n    r2 = get_element_ptr r1 items :: VecI64BufObject\n    r3 = n * 8\n    r4 = r2 + r3\n    r5 = r2\nL1:\n    r6 = r5 < r4 :: unsigned\n    if r6 goto L2 else goto L3 :: bool\nL2:\n    set_mem r5, 3 :: i64*\n    r7 = r5 + 8\n    r5 = r7\n    goto L1\nL3:\n    keep_alive r0\n    return r0\n\n[case testVecI64ConstructFromListMultiply2]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(n: i64, x: i64) -> vec[i64]:\n    return vec[i64]([x] * 3)\n[out]\ndef f(n, x):\n    n, x :: i64\n    r0 :: vec[i64]\n    r1 :: object\n    r2 :: ptr\n    r3 :: native_int\n    r4, r5 :: ptr\n    r6 :: bit\n    r7 :: ptr\nL0:\n    r0 = VecI64Api.alloc(3, 3)\n    r1 = r0.buf\n    r2 = get_element_ptr r1 items :: VecI64BufObject\n    r3 = 3 * 8\n    r4 = r2 + r3\n    r5 = r2\nL1:\n    r6 = r5 < r4 :: unsigned\n    if r6 goto L2 else goto L3 :: bool\nL2:\n    set_mem r5, x :: i64*\n    r7 = r5 + 8\n    r5 = r7\n    goto L1\nL3:\n    keep_alive r0\n    return r0\n\n[case testVecI64ConstructFromListComprehension]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(n: i64) -> vec[i64]:\n    # TODO: Can we pre-allocate a vec with capacity 5?\n    return vec[i64]([x + 1 for x in range(i64(5))])\n[out]\ndef f(n):\n    n :: i64\n    r0, r1 :: vec[i64]\n    r2, x :: i64\n    r3 :: bit\n    r4 :: i64\n    r5 :: vec[i64]\n    r6 :: i64\nL0:\n    r0 = VecI64Api.alloc(0, 0)\n    r1 = r0\n    r2 = 0\n    x = r2\nL1:\n    r3 = r2 < 5 :: signed\n    if r3 goto L2 else goto L4 :: bool\nL2:\n    r4 = x + 1\n    r5 = VecI64Api.append(r1, r4)\n    r1 = r5\nL3:\n    r6 = r2 + 1\n    r2 = r6\n    x = r6\n    goto L1\nL4:\n    return r1\n\n[case testVecI64FastComprehensionFromList]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\nfrom typing import List\n\ndef f(n: i64, l: List[i64]) -> vec[i64]:\n    return vec[i64]([x + 1 for x in l])\n[out]\ndef f(n, l):\n    n :: i64\n    l :: list\n    r0 :: native_int\n    r1 :: vec[i64]\n    r2, r3 :: native_int\n    r4 :: bit\n    r5 :: object\n    r6, x, r7 :: i64\n    r8 :: object\n    r9 :: ptr\n    r10 :: native_int\n    r11 :: ptr\n    r12 :: native_int\nL0:\n    r0 = var_object_size l\n    r1 = VecI64Api.alloc(r0, r0)\n    r2 = 0\nL1:\n    r3 = var_object_size l\n    r4 = r2 < r3 :: signed\n    if r4 goto L2 else goto L4 :: bool\nL2:\n    r5 = list_get_item_unsafe l, r2\n    r6 = unbox(i64, r5)\n    x = r6\n    r7 = x + 1\n    r8 = r1.buf\n    r9 = get_element_ptr r8 items :: VecI64BufObject\n    r10 = r2 * 8\n    r11 = r9 + r10\n    set_mem r11, r7 :: i64*\n    keep_alive r1\nL3:\n    r12 = r2 + 1\n    r2 = r12\n    goto L1\nL4:\n    return r1\n\n[case testVecI64FastComprehensionFromVec]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\nfrom typing import List\n\ndef f(n: i64, v: vec[i64]) -> vec[i64]:\n    return vec[i64]([x + 1 for x in v])\n[out]\ndef f(n, v):\n    n :: i64\n    v :: vec[i64]\n    r0 :: native_int\n    r1 :: vec[i64]\n    r2, r3 :: native_int\n    r4 :: bit\n    r5 :: object\n    r6 :: ptr\n    r7 :: native_int\n    r8 :: ptr\n    r9, x, r10 :: i64\n    r11 :: object\n    r12 :: ptr\n    r13 :: native_int\n    r14 :: ptr\n    r15 :: native_int\nL0:\n    r0 = v.len\n    r1 = VecI64Api.alloc(r0, r0)\n    r2 = 0\nL1:\n    r3 = v.len\n    r4 = r2 < r3 :: signed\n    if r4 goto L2 else goto L4 :: bool\nL2:\n    r5 = v.buf\n    r6 = get_element_ptr r5 items :: VecI64BufObject\n    r7 = r2 * 8\n    r8 = r6 + r7\n    r9 = load_mem r8 :: i64*\n    x = r9\n    keep_alive v\n    r10 = x + 1\n    r11 = r1.buf\n    r12 = get_element_ptr r11 items :: VecI64BufObject\n    r13 = r2 * 8\n    r14 = r12 + r13\n    set_mem r14, r10 :: i64*\n    keep_alive r1\nL3:\n    r15 = r2 + 1\n    r2 = r15\n    goto L1\nL4:\n    return r1\n\n[case testVecI64ConstructFromRange]\nfrom librt.vecs import vec, pop\nfrom mypy_extensions import i64\n\ndef f() -> vec[i64]:\n    # TODO: Can we pre-allocate a vec with capacity 7?\n    return vec[i64](range(7))\n[out]\ndef f():\n    r0, r1 :: vec[i64]\n    r2 :: short_int\n    r3, ___tmp_6 :: i64\n    r4 :: bit\n    r5 :: vec[i64]\n    r6 :: short_int\n    r7 :: i64\nL0:\n    r0 = VecI64Api.alloc(0, 0)\n    r1 = r0\n    r2 = 0\n    r3 = r2 >> 1\n    ___tmp_6 = r3\nL1:\n    r4 = int_lt r2, 14\n    if r4 goto L2 else goto L4 :: bool\nL2:\n    r5 = VecI64Api.append(r1, ___tmp_6)\n    r1 = r5\nL3:\n    r6 = r2 + 2\n    r2 = r6\n    r7 = r6 >> 1\n    ___tmp_6 = r7\n    goto L1\nL4:\n    return r1\n\n[case testVecI64ForLoop]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[i64]) -> i64:\n    t: i64 = 0\n    for x in v:\n        t += 1\n    return t\n[out]\ndef f(v):\n    v :: vec[i64]\n    t :: i64\n    r0, r1 :: native_int\n    r2 :: bit\n    r3 :: object\n    r4 :: ptr\n    r5 :: native_int\n    r6 :: ptr\n    r7, x, r8 :: i64\n    r9 :: native_int\nL0:\n    t = 0\n    r0 = 0\nL1:\n    r1 = v.len\n    r2 = r0 < r1 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = v.buf\n    r4 = get_element_ptr r3 items :: VecI64BufObject\n    r5 = r0 * 8\n    r6 = r4 + r5\n    r7 = load_mem r6 :: i64*\n    x = r7\n    keep_alive v\n    r8 = t + 1\n    t = r8\nL3:\n    r9 = r0 + 1\n    r0 = r9\n    goto L1\nL4:\n    return t\n\n[case testVecI64Contains]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef contains(v: vec[i64], n: i64) -> bool:\n    return n in v\n[out]\ndef contains(v, n):\n    v :: vec[i64]\n    n :: i64\n    r0 :: native_int\n    r1 :: object\n    r2 :: ptr\n    r3 :: native_int\n    r4, r5 :: ptr\n    r6 :: bit\n    r7 :: i64\n    r8 :: bit\n    r9 :: ptr\n    r10 :: bool\nL0:\n    r0 = v.len\n    r1 = v.buf\n    r2 = get_element_ptr r1 items :: VecI64BufObject\n    r3 = r0 * 8\n    r4 = r2 + r3\n    r5 = r2\nL1:\n    r6 = r5 < r4 :: unsigned\n    if r6 goto L2 else goto L4 :: bool\nL2:\n    r7 = load_mem r5 :: i64*\n    r8 = r7 == n\n    if r8 goto L5 else goto L3 :: bool\nL3:\n    r9 = r5 + 8\n    r5 = r9\n    goto L1\nL4:\n    keep_alive v\n    r10 = 0\n    goto L6\nL5:\n    r10 = 1\nL6:\n    return r10\n\n[case testVecI64GetItemWithInt_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[i64]) -> i64:\n    return v[0]\n[out]\ndef f(v):\n    v :: vec[i64]\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: i64\nL0:\n    r0 = v.len\n    r1 = 0 < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = 0 + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = 0\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecI64BufObject\n    r8 = r5 * 8\n    r9 = r7 + r8\n    r10 = load_mem r9 :: i64*\n    keep_alive v\n    return r10\n\n[case testVecI64Slicing_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[i64], n: i64, m: i64) -> None:\n    a = v[:]\n    b = v[n:]\n    c = v[n:m]\n    d = v[:m]\n    e = v[1:-2]\n[out]\ndef f(v, n, m):\n    v :: vec[i64]\n    n, m :: i64\n    r0, a, r1, b, r2, c, r3, d, r4, e :: vec[i64]\nL0:\n    r0 = VecI64Api.slice(v, 0, 4611686018427387903)\n    a = r0\n    r1 = VecI64Api.slice(v, n, 4611686018427387903)\n    b = r1\n    r2 = VecI64Api.slice(v, n, m)\n    c = r2\n    r3 = VecI64Api.slice(v, 0, m)\n    d = r3\n    r4 = VecI64Api.slice(v, 1, -2)\n    e = r4\n    return 1\n\n[case testVecI64Remove]\nfrom librt.vecs import vec, remove\nfrom mypy_extensions import i64\n\ndef rem(v: vec[i64], n: i64) -> None:\n    v = remove(v, n)\n[out]\ndef rem(v, n):\n    v :: vec[i64]\n    n :: i64\n    r0 :: vec[i64]\nL0:\n    r0 = VecI64Api.remove(v, n)\n    v = r0\n    return 1\n\n[case testVecI64PopLast]\nfrom typing import Tuple\nfrom librt.vecs import vec, pop\nfrom mypy_extensions import i64\n\ndef pop_last(v: vec[i64]) -> Tuple[vec[i64], i64]:\n    return pop(v)\n[out]\ndef pop_last(v):\n    v :: vec[i64]\n    r0 :: tuple[vec[i64], i64]\nL0:\n    r0 = VecI64Api.pop(v, -1)\n    return r0\n\n[case testVecI64PopNth_64bit]\nfrom typing import Tuple\nfrom librt.vecs import vec, pop\nfrom mypy_extensions import i64\n\ndef pop_nth(v: vec[i64], n: i64) -> Tuple[vec[i64], i64]:\n    return pop(v, n)\n[out]\ndef pop_nth(v, n):\n    v :: vec[i64]\n    n :: i64\n    r0 :: tuple[vec[i64], i64]\nL0:\n    r0 = VecI64Api.pop(v, n)\n    return r0\n\n[case testVecI64InPlaceOp_64bit]\nfrom librt.vecs import vec, remove\nfrom mypy_extensions import i64\n\ndef inplace(v: vec[i64], n: i64, m: i64) -> None:\n    v[n] += m\n[out]\ndef inplace(v, n, m):\n    v :: vec[i64]\n    n, m :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10, r11 :: i64\n    r12 :: native_int\n    r13 :: bit\n    r14 :: i64\n    r15 :: bit\n    r16 :: bool\n    r17 :: i64\n    r18 :: object\n    r19 :: ptr\n    r20 :: i64\n    r21 :: ptr\nL0:\n    r0 = v.len\n    r1 = n < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = n + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = n\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecI64BufObject\n    r8 = r5 * 8\n    r9 = r7 + r8\n    r10 = load_mem r9 :: i64*\n    keep_alive v\n    r11 = r10 + m\n    r12 = v.len\n    r13 = n < r12 :: unsigned\n    if r13 goto L9 else goto L6 :: bool\nL6:\n    r14 = n + r12\n    r15 = r14 < r12 :: unsigned\n    if r15 goto L8 else goto L7 :: bool\nL7:\n    r16 = raise IndexError\n    unreachable\nL8:\n    r17 = r14\n    goto L10\nL9:\n    r17 = n\nL10:\n    r18 = v.buf\n    r19 = get_element_ptr r18 items :: VecI64BufObject\n    r20 = r17 * 8\n    r21 = r19 + r20\n    set_mem r21, r11 :: i64*\n    keep_alive v\n    return 1\n\n[case testVecI64Narrow]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\nfrom typing import Optional, Union\n\ndef f(x: Optional[vec[i64]]) -> None:\n    if x is not None:\n        len(x)\n\ndef g(x: Union[vec[i64], str]) -> None:\n    if isinstance(x, vec):\n        len(x)\n[out]\ndef f(x):\n    x :: union[vec[i64], None]\n    r0 :: object\n    r1 :: bit\n    r2 :: vec[i64]\n    r3 :: native_int\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x != r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = unbox(vec[i64], x)\n    r3 = r2.len\nL2:\n    return 1\ndef g(x):\n    x :: union[vec[i64], str]\n    r0 :: bit\n    r1 :: vec[i64]\n    r2 :: native_int\nL0:\n    r0 = CPyVec_Check(x)\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    r1 = unbox(vec[i64], x)\n    r2 = r1.len\nL2:\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-vec-misc.test",
    "content": "-- Test cases for packed/specialized vec item types other than i64, such as\n-- vec[i32] and vec[float]. Since many of the code paths are the same as for\n-- vec[i64], only test a subset of functionality.\n--\n-- vec[i64] test cases are in irbuild-vec-i64.test.\n\n[case testVecMiscCreateEmpty]\nfrom librt.vecs import vec\n\nfrom mypy_extensions import i32, i16, u8\n\ndef create_float() -> vec[float]:\n    return vec[float]()\n\ndef create_i32() -> vec[i32]:\n    return vec[i32]()\n\ndef create_i16() -> vec[i16]:\n    return vec[i16]()\n\ndef create_u8() -> vec[u8]:\n    return vec[u8]()\n\ndef create_bool() -> vec[bool]:\n    return vec[bool]()\n[out]\ndef create_float():\n    r0 :: vec[float]\nL0:\n    r0 = VecFloatApi.alloc(0, 0)\n    return r0\ndef create_i32():\n    r0 :: vec[i32]\nL0:\n    r0 = VecI32Api.alloc(0, 0)\n    return r0\ndef create_i16():\n    r0 :: vec[i16]\nL0:\n    r0 = VecI16Api.alloc(0, 0)\n    return r0\ndef create_u8():\n    r0 :: vec[u8]\nL0:\n    r0 = VecU8Api.alloc(0, 0)\n    return r0\ndef create_bool():\n    r0 :: vec[bool]\nL0:\n    r0 = VecBoolApi.alloc(0, 0)\n    return r0\n\n[case testVecMiscCreateFromList]\nfrom librt.vecs import vec\n\nfrom mypy_extensions import i64, i32\n\ndef create_i32() -> vec[i32]:\n    return vec[i32]([1, -5])\n[out]\ndef create_i32():\n    r0 :: vec[i32]\n    r1 :: object\n    r2, r3, r4 :: ptr\nL0:\n    r0 = VecI32Api.alloc(2, 2)\n    r1 = r0.buf\n    r2 = get_element_ptr r1 items :: VecI32BufObject\n    set_mem r2, 1 :: i32*\n    r3 = r2 + 4\n    set_mem r3, -5 :: i32*\n    r4 = r3 + 4\n    keep_alive r0\n    return r0\n\n[case testVecMiscLen_64bit]\nfrom librt.vecs import vec\n\nfrom mypy_extensions import i64, i32\n\ndef len_i32(v: vec[i32]) -> i64:\n    return len(v)\n[out]\ndef len_i32(v):\n    v :: vec[i32]\n    r0 :: native_int\nL0:\n    r0 = v.len\n    return r0\n\n[case testVecMiscAppend]\nfrom librt.vecs import vec, append\n\nfrom mypy_extensions import i32\n\ndef append_float(v: vec[float]) -> vec[float]:\n    return append(v, 1.5)\n\ndef append_i32(v: vec[i32]) -> vec[i32]:\n    return append(v, 123)\n[out]\ndef append_float(v):\n    v, r0 :: vec[float]\nL0:\n    r0 = VecFloatApi.append(v, 1.5)\n    return r0\ndef append_i32(v):\n    v, r0 :: vec[i32]\nL0:\n    r0 = VecI32Api.append(v, 123)\n    return r0\n\n[case testVecMiscGetItem_64bit]\nfrom librt.vecs import vec\n\nfrom mypy_extensions import i64\n\ndef get_item_bool(v: vec[bool], i: i64) -> bool:\n    return v[i]\n[out]\ndef get_item_bool(v, i):\n    v :: vec[bool]\n    i :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: bool\nL0:\n    r0 = v.len\n    r1 = i < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = i + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = i\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecBoolBufObject\n    r8 = r5 * 1\n    r9 = r7 + r8\n    r10 = load_mem r9 :: builtins.bool*\n    keep_alive v\n    return r10\n\n[case testVecMiscPop]\nfrom librt.vecs import vec, pop\n\nfrom mypy_extensions import i64\n\ndef pop_float(v: vec[float], i: i64) -> float:\n    v, x = pop(v)\n    return x\n[out]\ndef pop_float(v, i):\n    v :: vec[float]\n    i :: i64\n    r0 :: tuple[vec[float], float]\n    r1 :: vec[float]\n    r2 :: float\n    r3 :: vec[float]\n    r4, x :: float\nL0:\n    r0 = VecFloatApi.pop(v, -1)\n    r1 = borrow r0[0]\n    r2 = borrow r0[1]\n    keep_alive steal r0\n    r3 = unborrow r1\n    v = r3\n    r4 = unborrow r2\n    x = r4\n    return x\n\n[case testVecMiscRemove]\nfrom librt.vecs import vec, remove\n\ndef remove_float(v: vec[float]) -> vec[float]:\n    return remove(v, 1.5)\n[out]\ndef remove_float(v):\n    v, r0 :: vec[float]\nL0:\n    r0 = VecFloatApi.remove(v, 1.5)\n    return r0\n\n[case testVecMiscSlice]\nfrom librt.vecs import vec, remove\n\nfrom mypy_extensions import i64\n\ndef remove_float(v: vec[float], x: i64, y: i64) -> vec[float]:\n    return v[x:y]\n[out]\ndef remove_float(v, x, y):\n    v :: vec[float]\n    x, y :: i64\n    r0 :: vec[float]\nL0:\n    r0 = VecFloatApi.slice(v, x, y)\n    return r0\n\n[case testVecMiscForLoop]\nfrom librt.vecs import vec, remove\n\nfrom mypy_extensions import i64, i16\n\ndef for_bool(v: vec[i16]) -> i16:\n    s: i16 = 0\n    for x in v:\n        s += x\n    return s\n[out]\ndef for_bool(v):\n    v :: vec[i16]\n    s :: i16\n    r0, r1 :: native_int\n    r2 :: bit\n    r3 :: object\n    r4 :: ptr\n    r5 :: native_int\n    r6 :: ptr\n    r7, x, r8 :: i16\n    r9 :: native_int\nL0:\n    s = 0\n    r0 = 0\nL1:\n    r1 = v.len\n    r2 = r0 < r1 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = v.buf\n    r4 = get_element_ptr r3 items :: VecI16BufObject\n    r5 = r0 * 2\n    r6 = r4 + r5\n    r7 = load_mem r6 :: i16*\n    x = r7\n    keep_alive v\n    r8 = s + x\n    s = r8\nL3:\n    r9 = r0 + 1\n    r0 = r9\n    goto L1\nL4:\n    return s\n\n[case testVecMiscNestedGetItem_64bit]\nfrom librt.vecs import vec\n\nfrom mypy_extensions import i64, i32\n\ndef get_item_nested(v: vec[vec[i32]], i: i64) -> vec[i32]:\n    return v[i]\n[out]\ndef get_item_nested(v, i):\n    v :: vec[vec[i32]]\n    i :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: vec[i32]\nL0:\n    r0 = v.len\n    r1 = i < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = i + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = i\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecNestedBufObject\n    r8 = r5 * 16\n    r9 = r7 + r8\n    r10 = load_mem r9 :: vec[i32]*\n    keep_alive v\n    return r10\n\n[case testVecMiscNestedPop_64bit]\nfrom librt.vecs import vec, pop\n\nfrom mypy_extensions import i64, i32\n\ndef get_item_nested(v: vec[vec[i32]], i: i64) -> vec[i32]:\n    v, x = pop(v, i)\n    return x\n[out]\ndef get_item_nested(v, i):\n    v :: vec[vec[i32]]\n    i :: i64\n    r0 :: tuple[vec[vec[i32]], VecNestedBufItem{len:native_int, buf:object_nrc}]\n    r1, r2 :: vec[vec[i32]]\n    r3, r4 :: VecNestedBufItem{len:native_int, buf:object_nrc}\n    r5 :: vec[i32]\n    r6 :: tuple[vec[vec[i32]], vec[i32]]\n    r7 :: vec[vec[i32]]\n    r8 :: vec[i32]\n    r9 :: vec[vec[i32]]\n    r10, x :: vec[i32]\nL0:\n    r0 = VecNestedApi.pop(v, i)\n    r1 = borrow r0[0]\n    r2 = unborrow r1\n    r3 = borrow r0[1]\n    r4 = unborrow r3\n    r5 = VecI32Api.convert_from_nested(r4)\n    r6 = (r2, r5)\n    keep_alive steal r0\n    r7 = borrow r6[0]\n    r8 = borrow r6[1]\n    keep_alive steal r6\n    r9 = unborrow r7\n    v = r9\n    r10 = unborrow r8\n    x = r10\n    return x\n"
  },
  {
    "path": "mypyc/test-data/irbuild-vec-nested.test",
    "content": "-- Test cases for nested vecs\n\n[case testVecNestedCreateEmpty]\nfrom librt.vecs import vec, append\nfrom mypy_extensions import i64\n\ndef f() -> vec[vec[str]]:\n    return vec[vec[str]]()\n\ndef g() -> vec[vec[i64]]:\n    return vec[vec[i64]]()\n[out]\ndef f():\n    r0 :: object\n    r1 :: ptr\n    r2 :: vec[vec[str]]\nL0:\n    r0 = load_address PyUnicode_Type\n    r1 = r0\n    r2 = VecNestedApi.alloc(0, 0, r1, 1)\n    return r2\ndef g():\n    r0 :: vec[vec[i64]]\nL0:\n    r0 = VecNestedApi.alloc(0, 0, 2, 1)\n    return r0\n\n[case testVecNestedAppend]\nfrom librt.vecs import vec, append\n\ndef f(v: vec[vec[str]], vv: vec[str]) -> vec[vec[str]]:\n    return append(v, vv)\n[out]\ndef f(v, vv):\n    v :: vec[vec[str]]\n    vv :: vec[str]\n    r0 :: native_int\n    r1 :: object\n    r2, r3 :: VecNestedBufItem{len:native_int, buf:object_nrc}\n    r4 :: vec[vec[str]]\nL0:\n    r0 = vv.len\n    r1 = vv.buf\n    r2 = set_element undef VecNestedBufItem, len, r0\n    r3 = set_element r2, buf, r1\n    r4 = VecNestedApi.append(v, r3)\n    keep_alive vv\n    return r4\n\n[case testVecNestedVecI64Append]\nfrom librt.vecs import vec, append\nfrom mypy_extensions import i64\n\ndef f(v: vec[vec[i64]], vv: vec[i64]) -> vec[vec[i64]]:\n    return append(v, vv)\n[out]\ndef f(v, vv):\n    v :: vec[vec[i64]]\n    vv :: vec[i64]\n    r0 :: native_int\n    r1 :: object\n    r2, r3 :: VecNestedBufItem{len:native_int, buf:object_nrc}\n    r4 :: vec[vec[i64]]\nL0:\n    r0 = vv.len\n    r1 = vv.buf\n    r2 = set_element undef VecNestedBufItem, len, r0\n    r3 = set_element r2, buf, r1\n    r4 = VecNestedApi.append(v, r3)\n    keep_alive vv\n    return r4\n\n[case testVecNestedLen_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\nfrom typing import Optional\n\ndef f(v: vec[vec[str]]) -> i64:\n    return len(v)\n\ndef g(v: vec[vec[i64]]) -> i64:\n    return len(v)\n[out]\ndef f(v):\n    v :: vec[vec[str]]\n    r0 :: native_int\nL0:\n    r0 = v.len\n    return r0\ndef g(v):\n    v :: vec[vec[i64]]\n    r0 :: native_int\nL0:\n    r0 = v.len\n    return r0\n\n[case testVecNestedGetItem_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[vec[str]], n: i64) -> vec[str]:\n    return v[n]\n[out]\ndef f(v, n):\n    v :: vec[vec[str]]\n    n :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: vec[str]\nL0:\n    r0 = v.len\n    r1 = n < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = n + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = n\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecNestedBufObject\n    r8 = r5 * 16\n    r9 = r7 + r8\n    r10 = load_mem r9 :: vec[str]*\n    keep_alive v\n    return r10\n\n[case testVecNestedI64GetItem_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[vec[i64]], n: i64) -> vec[i64]:\n    return v[n]\n[out]\ndef f(v, n):\n    v :: vec[vec[i64]]\n    n :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: vec[i64]\nL0:\n    r0 = v.len\n    r1 = n < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = n + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = n\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecNestedBufObject\n    r8 = r5 * 16\n    r9 = r7 + r8\n    r10 = load_mem r9 :: vec[i64]*\n    keep_alive v\n    return r10\n\n[case testVecNestedI64GetItemWithBorrow_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[vec[i64]], n: i64) -> i64:\n    return v[n][n]\n[out]\ndef f(v, n):\n    v :: vec[vec[i64]]\n    n :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: vec[i64]\n    r11 :: native_int\n    r12 :: bit\n    r13 :: i64\n    r14 :: bit\n    r15 :: bool\n    r16 :: i64\n    r17 :: object\n    r18 :: ptr\n    r19 :: i64\n    r20 :: ptr\n    r21 :: i64\nL0:\n    r0 = v.len\n    r1 = n < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = n + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = n\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecNestedBufObject\n    r8 = r5 * 16\n    r9 = r7 + r8\n    r10 = borrow load_mem r9 :: vec[i64]*\n    r11 = r10.len\n    r12 = n < r11 :: unsigned\n    if r12 goto L9 else goto L6 :: bool\nL6:\n    r13 = n + r11\n    r14 = r13 < r11 :: unsigned\n    if r14 goto L8 else goto L7 :: bool\nL7:\n    r15 = raise IndexError\n    unreachable\nL8:\n    r16 = r13\n    goto L10\nL9:\n    r16 = n\nL10:\n    r17 = r10.buf\n    r18 = get_element_ptr r17 items :: VecI64BufObject\n    r19 = r16 * 8\n    r20 = r18 + r19\n    r21 = load_mem r20 :: i64*\n    keep_alive v, r10\n    return r21\n\n[case testVecDoublyNestedGetItem_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[vec[vec[str]]], n: i64) -> vec[vec[str]]:\n    return v[n]\n[out]\ndef f(v, n):\n    v :: vec[vec[vec[str]]]\n    n :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: vec[vec[str]]\nL0:\n    r0 = v.len\n    r1 = n < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = n + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = n\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecNestedBufObject\n    r8 = r5 * 16\n    r9 = r7 + r8\n    r10 = load_mem r9 :: vec[vec[str]]*\n    keep_alive v\n    return r10\n"
  },
  {
    "path": "mypyc/test-data/irbuild-vec-t.test",
    "content": "-- Test cases for vec[t] where t is a boxed, non-vec type (PyObject *).\n-- Also tests for vec[t | None], which uses the same representation.\n\n[case testVecTCreateEmpty]\nfrom librt.vecs import vec, append\n\nclass C: pass\n\ndef primitive() -> vec[str]:\n    return vec[str]()\n\ndef native_class() -> vec[C]:\n    return vec[C]()\n[out]\ndef primitive():\n    r0 :: object\n    r1 :: ptr\n    r2 :: vec[str]\nL0:\n    r0 = load_address PyUnicode_Type\n    r1 = r0\n    r2 = VecTApi.alloc(0, 0, r1)\n    return r2\ndef native_class():\n    r0 :: object\n    r1 :: ptr\n    r2 :: vec[__main__.C]\nL0:\n    r0 = __main__.C :: type\n    r1 = r0\n    r2 = VecTApi.alloc(0, 0, r1)\n    return r2\n\n[case testVecTAppend]\nfrom librt.vecs import vec, append\n\ndef f(v: vec[str]) -> vec[str]:\n    return append(v, 'x')\n[out]\ndef f(v):\n    v :: vec[str]\n    r0 :: str\n    r1 :: object\n    r2 :: ptr\n    r3 :: vec[str]\nL0:\n    r0 = 'x'\n    r1 = load_address PyUnicode_Type\n    r2 = r1\n    r3 = VecTApi.append(v, r0, r2)\n    return r3\n\n[case testVecTOptionalCreateEmpty]\nfrom librt.vecs import vec, append\nfrom typing import Optional\n\nclass C: pass\n\ndef primitive() -> vec[Optional[str]]:\n    return vec[Optional[str]]()\n\ndef native_class() -> vec[Optional[C]]:\n    return vec[Optional[C]]()\n[out]\ndef primitive():\n    r0 :: object\n    r1, r2 :: ptr\n    r3 :: vec[str | None]\nL0:\n    r0 = load_address PyUnicode_Type\n    r1 = r0\n    r2 = r1 | 1\n    r3 = VecTApi.alloc(0, 0, r2)\n    return r3\ndef native_class():\n    r0 :: object\n    r1, r2 :: ptr\n    r3 :: vec[__main__.C | None]\nL0:\n    r0 = __main__.C :: type\n    r1 = r0\n    r2 = r1 | 1\n    r3 = VecTApi.alloc(0, 0, r2)\n    return r3\n\n[case testVecTOptionalAppend]\nfrom librt.vecs import vec, append\nfrom typing import Optional\n\ndef f(v: vec[Optional[str]]) -> vec[Optional[str]]:\n    v = append(v, 'x')\n    return append(v, None)\n[out]\ndef f(v):\n    v :: vec[str | None]\n    r0 :: str\n    r1 :: object\n    r2, r3 :: ptr\n    r4 :: vec[str | None]\n    r5, r6 :: object\n    r7, r8 :: ptr\n    r9 :: vec[str | None]\nL0:\n    r0 = 'x'\n    r1 = load_address PyUnicode_Type\n    r2 = r1\n    r3 = r2 | 1\n    r4 = VecTApi.append(v, r0, r3)\n    v = r4\n    r5 = box(None, 1)\n    r6 = load_address PyUnicode_Type\n    r7 = r6\n    r8 = r7 | 1\n    r9 = VecTApi.append(v, r5, r8)\n    return r9\n\n[case testVecTLen_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\nfrom typing import Optional\n\ndef f(v: vec[str]) -> i64:\n    return len(v)\n\ndef g(v: vec[Optional[str]]) -> i64:\n    return len(v)\n[out]\ndef f(v):\n    v :: vec[str]\n    r0 :: native_int\nL0:\n    r0 = v.len\n    return r0\ndef g(v):\n    v :: vec[str | None]\n    r0 :: native_int\nL0:\n    r0 = v.len\n    return r0\n\n[case testVecTGetItem_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[str], n: i64) -> str:\n    return v[n]\n[out]\ndef f(v, n):\n    v :: vec[str]\n    n :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: str\nL0:\n    r0 = v.len\n    r1 = n < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = n + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = n\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecTBufObject\n    r8 = r5 * 8\n    r9 = r7 + r8\n    r10 = load_mem r9 :: builtins.str*\n    keep_alive v\n    return r10\n\n[case testVecTOptionalGetItem_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\nfrom typing import Optional\n\ndef f(v: vec[Optional[str]], n: i64) -> Optional[str]:\n    return v[n]\n[out]\ndef f(v, n):\n    v :: vec[str | None]\n    n :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: union[str, None]\nL0:\n    r0 = v.len\n    r1 = n < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = n + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = n\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecTBufObject\n    r8 = r5 * 8\n    r9 = r7 + r8\n    r10 = load_mem r9 :: union*\n    keep_alive v\n    return r10\n\n[case testNewTPopLast]\nfrom typing import Tuple\nfrom librt.vecs import vec, pop\n\ndef pop_last(v: vec[str]) -> Tuple[vec[str], str]:\n    return pop(v)\n[out]\ndef pop_last(v):\n    v :: vec[str]\n    r0 :: tuple[vec[str], str]\nL0:\n    r0 = VecTApi.pop(v, -1)\n    return r0\n\n[case testVecTConstructFromListComprehension]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(n: i64) -> vec[str]:\n    return vec[str](['x' for x in range(i64(5))])\n[out]\ndef f(n):\n    n :: i64\n    r0 :: object\n    r1 :: ptr\n    r2, r3 :: vec[str]\n    r4, x :: i64\n    r5 :: bit\n    r6 :: str\n    r7 :: object\n    r8 :: ptr\n    r9 :: vec[str]\n    r10 :: i64\nL0:\n    r0 = load_address PyUnicode_Type\n    r1 = r0\n    r2 = VecTApi.alloc(0, 0, r1)\n    r3 = r2\n    r4 = 0\n    x = r4\nL1:\n    r5 = r4 < 5 :: signed\n    if r5 goto L2 else goto L4 :: bool\nL2:\n    r6 = 'x'\n    r7 = load_address PyUnicode_Type\n    r8 = r7\n    r9 = VecTApi.append(r3, r6, r8)\n    r3 = r9\nL3:\n    r10 = r4 + 1\n    r4 = r10\n    x = r10\n    goto L1\nL4:\n    return r3\n\n[case testVecTCheckItemType]\nfrom librt.vecs import vec\nfrom typing import Tuple, Any, List, TypeVar\n\ndef bad1(v: vec[Tuple[str, str]]) -> None: pass\ndef bad2(v: vec[int]) -> None: pass\ndef bad3(v: vec) -> None: pass\ndef bad4(v: vec[Any]) -> None: pass\nT = TypeVar(\"T\")\ndef bad5(v: vec[T]) -> None: pass\n\ndef ok1(v: vec[str], v2: vec[bytes]) -> None: pass\ndef ok2(v: vec[Tuple[str, ...]]) -> None: pass\ndef ok3(v: vec[object]) -> None: pass\ndef ok4(v: vec[List[Any]]) -> None: pass\ndef ok5(v: vec[vec[str]]) -> None: pass\n[out]\nmain:4: error: Invalid item type for \"vec\"\nmain:5: error: Invalid item type for \"vec\"\nmain:6: error: Invalid item type for \"vec\"\nmain:7: error: Invalid item type for \"vec\"\nmain:9: error: Invalid item type for \"vec\"\n\n[case testVecTCheckItemTypeUnion]\nfrom librt.vecs import vec\nfrom typing import Tuple, Union, Optional, Any, TypeVar\nfrom mypy_extensions import i64\n\ndef bad1(v: vec[Union[str, bytes]]) -> None: pass\ndef bad2(v: vec[Union[str, bytes, None]]) -> None: pass\ndef bad3(v: vec[Union[int, None]]) -> None: pass\ndef bad4(v: vec[Union[None, int]]) -> None: pass\ndef bad5(v: vec[Union[i64, None]]) -> None: pass\ndef bad6(v: vec[Union[None, i64]]) -> None: pass\ndef bad7(v: vec[Union[bool, None]]) -> None: pass\ndef bad9(v: vec[Union[float, None]]) -> None: pass\ndef bad10(v: vec[Union[vec[str], None]]) -> None: pass\ndef bad11(v: vec[Optional[vec[str]]]) -> None: pass\ndef bad12(v: vec[Union[str, Any]]) -> None: pass\nT = TypeVar(\"T\")\ndef bad13(v: vec[Union[str, T]]) -> None: pass\n\ndef ok1(v: vec[Union[str, None]]) -> None: pass\ndef ok2(v: vec[Union[None, str]]) -> None: pass\n[out]\nmain:5: error: Invalid item type for \"vec\"\nmain:6: error: Invalid item type for \"vec\"\nmain:7: error: Invalid item type for \"vec\"\nmain:8: error: Invalid item type for \"vec\"\nmain:9: error: Invalid item type for \"vec\"\nmain:10: error: Invalid item type for \"vec\"\nmain:11: error: Invalid item type for \"vec\"\nmain:12: error: Invalid item type for \"vec\"\nmain:13: error: Invalid item type for \"vec\"\nmain:14: error: Invalid item type for \"vec\"\nmain:15: error: Invalid item type for \"vec\"\nmain:17: error: Invalid item type for \"vec\"\n\n[case testVecTCheckItemTypeDuringConstruction]\nfrom librt.vecs import vec\nfrom typing import Optional, Union\n\ndef f() -> None:\n    vec[Optional[int]]()\n    vec[Union[str, bytes]]()\n    vec[Optional[vec[str]]]()\n\n[out]\nmain:5: error: Invalid item type for \"vec\"\nmain:6: error: Invalid item type for \"vec\"\nmain:7: error: Invalid item type for \"vec\"\n"
  },
  {
    "path": "mypyc/test-data/irbuild-vectorcall.test",
    "content": "-- Test cases for calls using the vectorcall API (Python 3.8+)\n--\n-- Vectorcalls are faster than the legacy API, especially with keyword arguments,\n-- since there is no need to allocate a temporary dictionary for keyword args.\n\n[case testeVectorcallBasic]\nfrom typing import Any\n\ndef f(c: Any) -> None:\n    c()\n    c('x', 'y')\n[out]\ndef f(c):\n    c, r0 :: object\n    r1, r2 :: str\n    r3 :: object[2]\n    r4 :: object_ptr\n    r5 :: object\nL0:\n    r0 = PyObject_Vectorcall(c, 0, 0, 0)\n    r1 = 'x'\n    r2 = 'y'\n    r3 = [r1, r2]\n    r4 = load_address r3\n    r5 = PyObject_Vectorcall(c, r4, 2, 0)\n    keep_alive r1, r2\n    return 1\n\n[case testVectorcallKeywords]\nfrom typing import Any\n\ndef f(c: Any) -> None:\n    c(x='a')\n    c('x', a='y', b='z')\n[out]\ndef f(c):\n    c :: object\n    r0 :: str\n    r1 :: object[1]\n    r2 :: object_ptr\n    r3, r4 :: object\n    r5, r6, r7 :: str\n    r8 :: object[3]\n    r9 :: object_ptr\n    r10, r11 :: object\nL0:\n    r0 = 'a'\n    r1 = [r0]\n    r2 = load_address r1\n    r3 = ('x',)\n    r4 = PyObject_Vectorcall(c, r2, 0, r3)\n    keep_alive r0\n    r5 = 'x'\n    r6 = 'y'\n    r7 = 'z'\n    r8 = [r5, r6, r7]\n    r9 = load_address r8\n    r10 = ('a', 'b')\n    r11 = PyObject_Vectorcall(c, r9, 1, r10)\n    keep_alive r5, r6, r7\n    return 1\n\n[case testVectorcallMethod_64bit]\nfrom typing import Any\n\ndef f(o: Any) -> None:\n    # Python 3.9 has a new API for calling methods\n    o.m('x')\n    o.m('x', 'y', a='z')\n[out]\ndef f(o):\n    o :: object\n    r0, r1 :: str\n    r2 :: object[2]\n    r3 :: object_ptr\n    r4 :: object\n    r5, r6, r7, r8 :: str\n    r9 :: object[4]\n    r10 :: object_ptr\n    r11, r12 :: object\nL0:\n    r0 = 'x'\n    r1 = 'm'\n    r2 = [o, r0]\n    r3 = load_address r2\n    r4 = PyObject_VectorcallMethod(r1, r3, 9223372036854775810, 0)\n    keep_alive o, r0\n    r5 = 'x'\n    r6 = 'y'\n    r7 = 'z'\n    r8 = 'm'\n    r9 = [o, r5, r6, r7]\n    r10 = load_address r9\n    r11 = ('a',)\n    r12 = PyObject_VectorcallMethod(r8, r10, 9223372036854775811, r11)\n    keep_alive o, r5, r6, r7\n    return 1\n\n[case testVectorcallMethod_32bit]\nfrom typing import Any\n\ndef f(o: Any) -> None:\n   # The IR is slightly different on 32-bit platforms\n    o.m('x', a='y')\n[out]\ndef f(o):\n    o :: object\n    r0, r1, r2 :: str\n    r3 :: object[3]\n    r4 :: object_ptr\n    r5, r6 :: object\nL0:\n    r0 = 'x'\n    r1 = 'y'\n    r2 = 'm'\n    r3 = [o, r0, r1]\n    r4 = load_address r3\n    r5 = ('a',)\n    r6 = PyObject_VectorcallMethod(r2, r4, 2147483650, r5)\n    keep_alive o, r0, r1\n    return 1\n"
  },
  {
    "path": "mypyc/test-data/irbuild-weakref.test",
    "content": "[case testWeakrefRef]\nimport weakref\nfrom typing import Any, Callable\ndef f(x: object) -> object:\n    return weakref.ref(x)\n\n[out]\ndef f(x):\n    x, r0 :: object\nL0:\n    r0 = PyWeakref_NewRef(x, 0)\n    return r0\n\n[case testWeakrefRefCallback]\nimport weakref\nfrom typing import Any, Callable\ndef f(x: object, cb: Callable[[object], Any]) -> object:\n    return weakref.ref(x, cb)\n\n[out]\ndef f(x, cb):\n    x, cb, r0 :: object\nL0:\n    r0 = PyWeakref_NewRef(x, cb)\n    return r0\n\n[case testFromWeakrefRef]\nfrom typing import Any, Callable\nfrom weakref import ref\ndef f(x: object) -> object:\n    return ref(x)\n\n[out]\ndef f(x):\n    x, r0 :: object\nL0:\n    r0 = PyWeakref_NewRef(x, 0)\n    return r0\n\n[case testFromWeakrefRefCallback]\nfrom typing import Any, Callable\nfrom weakref import ref\ndef f(x: object, cb: Callable[[object], Any]) -> object:\n    return ref(x, cb)\n\n[out]\ndef f(x, cb):\n    x, cb, r0 :: object\nL0:\n    r0 = PyWeakref_NewRef(x, cb)\n    return r0\n\n[case testWeakrefProxy]\nimport weakref\nfrom typing import Any, Callable\ndef f(x: object) -> object:\n    return weakref.proxy(x)\n\n[out]\ndef f(x):\n    x, r0 :: object\nL0:\n    r0 = PyWeakref_NewProxy(x, 0)\n    return r0\n\n[case testWeakrefProxyCallback]\nimport weakref\nfrom typing import Any, Callable\ndef f(x: object, cb: Callable[[object], Any]) -> object:\n    return weakref.proxy(x, cb)\n\n[out]\ndef f(x, cb):\n    x, cb, r0 :: object\nL0:\n    r0 = PyWeakref_NewProxy(x, cb)\n    return r0\n\n[case testFromWeakrefProxy]\nfrom typing import Any, Callable\nfrom weakref import proxy\ndef f(x: object) -> object:\n    return proxy(x)\n\n[out]\ndef f(x):\n    x, r0 :: object\nL0:\n    r0 = PyWeakref_NewProxy(x, 0)\n    return r0\n\n[case testFromWeakrefProxyCallback]\nfrom typing import Any, Callable\nfrom weakref import proxy\ndef f(x: object, cb: Callable[[object], Any]) -> object:\n    return proxy(x, cb)\n\n[out]\ndef f(x, cb):\n    x, cb, r0 :: object\nL0:\n    r0 = PyWeakref_NewProxy(x, cb)\n    return r0\n"
  },
  {
    "path": "mypyc/test-data/lowering-int.test",
    "content": "-- Test cases for converting high-level IR to lower-level IR (lowering).\n\n[case testLowerIntEq]\ndef f(x: int, y: int) -> int:\n    if x == y:\n        return 1\n    else:\n        return 2\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: native_int\n    r1, r2, r3 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 != 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = CPyTagged_IsEq_(x, y)\n    if r2 goto L3 else goto L4 :: bool\nL2:\n    r3 = x == y\n    if r3 goto L3 else goto L4 :: bool\nL3:\n    return 2\nL4:\n    return 4\n\n[case testLowerIntNe]\ndef f(x: int, y: int) -> int:\n    if x != y:\n        return 1\n    else:\n        return 2\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: native_int\n    r1, r2, r3, r4 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 != 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = CPyTagged_IsEq_(x, y)\n    r3 = r2 ^ 1\n    if r3 goto L3 else goto L4 :: bool\nL2:\n    r4 = x != y\n    if r4 goto L3 else goto L4 :: bool\nL3:\n    return 2\nL4:\n    return 4\n\n[case testLowerIntEqWithConstant]\ndef f(x: int, y: int) -> int:\n    if x == 2:\n        return 1\n    elif -1 == x:\n        return 2\n    return 3\n[out]\ndef f(x, y):\n    x, y :: int\n    r0, r1 :: bit\nL0:\n    r0 = x == 4\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    r1 = -2 == x\n    if r1 goto L3 else goto L4 :: bool\nL3:\n    return 4\nL4:\n    return 6\n\n[case testLowerIntNeWithConstant]\ndef f(x: int, y: int) -> int:\n    if x != 2:\n        return 1\n    elif -1 != x:\n        return 2\n    return 3\n[out]\ndef f(x, y):\n    x, y :: int\n    r0, r1 :: bit\nL0:\n    r0 = x != 4\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    r1 = -2 != x\n    if r1 goto L3 else goto L4 :: bool\nL3:\n    return 4\nL4:\n    return 6\n\n[case testLowerIntEqValueContext]\ndef f(x: int, y: int) -> bool:\n    return x == y\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: native_int\n    r1, r2 :: bit\n    r3 :: bool\n    r4 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 != 0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = CPyTagged_IsEq_(x, y)\n    r3 = r2\n    goto L3\nL2:\n    r4 = x == y\n    r3 = r4\nL3:\n    return r3\n\n[case testLowerIntLt]\ndef f(x: int, y: int) -> int:\n    if x < y:\n        return 1\n    else:\n        return 2\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: native_int\n    r1 :: bit\n    r2 :: native_int\n    r3, r4, r5 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 != 0\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = y & 1\n    r3 = r2 != 0\n    if r3 goto L2 else goto L3 :: bool\nL2:\n    r4 = CPyTagged_IsLt_(x, y)\n    if r4 goto L4 else goto L5 :: bool\nL3:\n    r5 = x < y :: signed\n    if r5 goto L4 else goto L5 :: bool\nL4:\n    return 2\nL5:\n    return 4\n\n[case testLowerIntLe]\ndef f(x: int, y: int) -> int:\n    if x <= y:\n        return 1\n    else:\n        return 2\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: native_int\n    r1 :: bit\n    r2 :: native_int\n    r3, r4, r5, r6 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 != 0\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = y & 1\n    r3 = r2 != 0\n    if r3 goto L2 else goto L3 :: bool\nL2:\n    r4 = CPyTagged_IsLt_(y, x)\n    r5 = r4 ^ 1\n    if r5 goto L4 else goto L5 :: bool\nL3:\n    r6 = x <= y :: signed\n    if r6 goto L4 else goto L5 :: bool\nL4:\n    return 2\nL5:\n    return 4\n\n[case testLowerIntGt]\ndef f(x: int, y: int) -> int:\n    if x > y:\n        return 1\n    else:\n        return 2\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: native_int\n    r1 :: bit\n    r2 :: native_int\n    r3, r4, r5 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 != 0\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = y & 1\n    r3 = r2 != 0\n    if r3 goto L2 else goto L3 :: bool\nL2:\n    r4 = CPyTagged_IsLt_(y, x)\n    if r4 goto L4 else goto L5 :: bool\nL3:\n    r5 = x > y :: signed\n    if r5 goto L4 else goto L5 :: bool\nL4:\n    return 2\nL5:\n    return 4\n\n[case testLowerIntGe]\ndef f(x: int, y: int) -> int:\n    if x >= y:\n        return 1\n    else:\n        return 2\n[out]\ndef f(x, y):\n    x, y :: int\n    r0 :: native_int\n    r1 :: bit\n    r2 :: native_int\n    r3, r4, r5, r6 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 != 0\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = y & 1\n    r3 = r2 != 0\n    if r3 goto L2 else goto L3 :: bool\nL2:\n    r4 = CPyTagged_IsLt_(x, y)\n    r5 = r4 ^ 1\n    if r5 goto L4 else goto L5 :: bool\nL3:\n    r6 = x >= y :: signed\n    if r6 goto L4 else goto L5 :: bool\nL4:\n    return 2\nL5:\n    return 4\n\n[case testLowerIntLtShort]\ndef both() -> int:\n    if 3 < 5:\n        return 1\n    else:\n        return 2\n\ndef rhs_only(x: int) -> int:\n    if x < 5:\n        return 1\n    else:\n        return 2\n\ndef lhs_only(x: int) -> int:\n    if 5 < x:\n        return 1\n    else:\n        return 2\n[out]\ndef both():\n    r0 :: bit\nL0:\n    r0 = 6 < 10 :: signed\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 4\ndef rhs_only(x):\n    x :: int\n    r0 :: native_int\n    r1 :: bit\n    r2 :: native_int\n    r3, r4, r5 :: bit\nL0:\n    r0 = x & 1\n    r1 = r0 != 0\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = 10 & 1\n    r3 = r2 != 0\n    if r3 goto L2 else goto L3 :: bool\nL2:\n    r4 = CPyTagged_IsLt_(x, 10)\n    if r4 goto L4 else goto L5 :: bool\nL3:\n    r5 = x < 10 :: signed\n    if r5 goto L4 else goto L5 :: bool\nL4:\n    return 2\nL5:\n    return 4\ndef lhs_only(x):\n    x :: int\n    r0 :: native_int\n    r1 :: bit\n    r2 :: native_int\n    r3, r4, r5 :: bit\nL0:\n    r0 = 10 & 1\n    r1 = r0 != 0\n    if r1 goto L2 else goto L1 :: bool\nL1:\n    r2 = x & 1\n    r3 = r2 != 0\n    if r3 goto L2 else goto L3 :: bool\nL2:\n    r4 = CPyTagged_IsLt_(10, x)\n    if r4 goto L4 else goto L5 :: bool\nL3:\n    r5 = 10 < x :: signed\n    if r5 goto L4 else goto L5 :: bool\nL4:\n    return 2\nL5:\n    return 4\n\n[case testLowerIntForLoop_64bit]\nfrom __future__ import annotations\n\ndef f(l: list[int]) -> None:\n    for x in l:\n        pass\n[out]\ndef f(l):\n    l :: list\n    r0 :: native_int\n    r1 :: ptr\n    r2 :: native_int\n    r3 :: bit\n    r4, r5 :: ptr\n    r6 :: native_int\n    r7 :: ptr\n    r8 :: object\n    r9, x :: int\n    r10 :: native_int\n    r11 :: None\nL0:\n    r0 = 0\nL1:\n    r1 = get_element_ptr l ob_size :: PyVarObject\n    r2 = load_mem r1 :: native_int*\n    r3 = r0 < r2 :: signed\n    if r3 goto L2 else goto L5 :: bool\nL2:\n    r4 = get_element_ptr l ob_item :: PyListObject\n    r5 = load_mem r4 :: ptr*\n    r6 = r0 * 8\n    r7 = r5 + r6\n    r8 = load_mem r7 :: builtins.object*\n    r9 = unbox(int, r8)\n    dec_ref r8\n    if is_error(r9) goto L6 (error at f:4) else goto L3\nL3:\n    x = r9\n    dec_ref x :: int\nL4:\n    r10 = r0 + 1\n    r0 = r10\n    goto L1\nL5:\n    return 1\nL6:\n    r11 = <error> :: None\n    return r11\n"
  },
  {
    "path": "mypyc/test-data/lowering-list.test",
    "content": "[case testLowerListDisplay]\ndef f() -> None:\n    a = [4, 6, 7]\n[out]\ndef f():\n    r0 :: list\n    r1, r2, r3 :: object\n    r4, r5, r6, r7 :: ptr\n    a :: list\n    r8 :: None\nL0:\n    r0 = PyList_New(3)\n    if is_error(r0) goto L2 (error at f:2) else goto L1\nL1:\n    r1 = object 4\n    r2 = object 6\n    r3 = object 7\n    r4 = get_element_ptr r0 ob_item :: PyListObject\n    r5 = load_mem r4 :: ptr*\n    inc_ref r1\n    set_mem r5, r1 :: builtins.object*\n    inc_ref r2\n    r6 = r5 + WORD_SIZE*1\n    set_mem r6, r2 :: builtins.object*\n    inc_ref r3\n    r7 = r5 + WORD_SIZE*2\n    set_mem r7, r3 :: builtins.object*\n    a = r0\n    dec_ref a\n    return 1\nL2:\n    r8 = <error> :: None\n    return r8\n"
  },
  {
    "path": "mypyc/test-data/opt-copy-propagation.test",
    "content": "-- Test cases for copy propagation optimization.  This also tests IR transforms in general,\n-- as copy propagation was the first IR transform that was implemented.\n\n[case testCopyPropagationSimple]\ndef g() -> int:\n    return 1\n\ndef f() -> int:\n    y = g()\n    return y\n[out]\ndef g():\nL0:\n    return 2\ndef f():\n    r0 :: int\nL0:\n    r0 = g()\n    return r0\n\n[case testCopyPropagationChain]\ndef f(x: int) -> int:\n    y = x\n    z = y\n    return z\n[out]\ndef f(x):\n    x :: int\nL0:\n    return x\n\n[case testCopyPropagationChainPartial]\ndef f(x: int) -> int:\n    y = x\n    z = y\n    x = 2\n    return z\n[out]\ndef f(x):\n    x, y :: int\nL0:\n    y = x\n    x = 4\n    return y\n\n[case testCopyPropagationChainBad]\ndef f(x: int) -> int:\n    y = x\n    z = y\n    y = 2\n    return z\n[out]\ndef f(x):\n    x, y, z :: int\nL0:\n    y = x\n    z = y\n    y = 4\n    return z\n\n[case testCopyPropagationMutatedSource1]\ndef f(x: int) -> int:\n    y = x\n    x = 1\n    return y\n[out]\ndef f(x):\n    x, y :: int\nL0:\n    y = x\n    x = 2\n    return y\n\n[case testCopyPropagationMutatedSource2]\ndef f() -> int:\n    z = 1\n    y = z\n    z = 2\n    return y\n[out]\ndef f():\n    z, y :: int\nL0:\n    z = 2\n    y = z\n    z = 4\n    return y\n\n[case testCopyPropagationTooComplex]\ndef f(b: bool, x: int) -> int:\n    if b:\n        y = x\n        return y\n    else:\n        y = 1\n        return y\n[out]\ndef f(b, x):\n    b :: bool\n    x, y :: int\nL0:\n    if b goto L1 else goto L2 :: bool\nL1:\n    y = x\n    return y\nL2:\n    y = 2\n    return y\n\n[case testCopyPropagationArg]\ndef f(x: int) -> int:\n    x = 2\n    return x\n[out]\ndef f(x):\n    x :: int\nL0:\n    x = 4\n    return x\n\n[case testCopyPropagationPartiallyDefined1]\ndef f(b: bool) -> int:\n    if b:\n        x = 1\n    y = x\n    return y\n[out]\ndef f(b):\n    b :: bool\n    r0, x :: int\n    r1 :: bool\n    y :: int\nL0:\n    r0 = <error> :: int\n    x = r0\n    if b goto L1 else goto L2 :: bool\nL1:\n    x = 2\nL2:\n    if is_error(x) goto L3 else goto L4\nL3:\n    r1 = raise UnboundLocalError('local variable \"x\" referenced before assignment')\n    unreachable\nL4:\n    y = x\n    return y\n\n-- The remaining test cases test basic IRTransform functionality and are not\n-- all needed for testing copy propagation as such.\n\n[case testIRTransformBranch]\nfrom mypy_extensions import i64\n\ndef f(x: bool) -> int:\n    y = x\n    if y:\n        return 1\n    else:\n        return 2\n[out]\ndef f(x):\n    x :: bool\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 4\n\n[case testIRTransformAssignment]\ndef f(b: bool, x: int) -> int:\n    y = x\n    if b:\n        return y\n    else:\n        return 1\n[out]\ndef f(b, x):\n    b :: bool\n    x :: int\nL0:\n    if b goto L1 else goto L2 :: bool\nL1:\n    return x\nL2:\n    return 2\n\n[case testIRTransformRegisterOps1]\nfrom __future__ import annotations\nfrom typing import cast\n\nclass C:\n    a: int\n\n    def m(self, x: int) -> None: pass\n\ndef get_attr(x: C) -> int:\n    y = x\n    return y.a\n\ndef set_attr(x: C) -> None:\n    y = x\n    y.a = 1\n\ndef tuple_get(x: tuple[int, int]) -> int:\n    y = x\n    return y[0]\n\ndef tuple_set(x: int, xx: int) -> tuple[int, int]:\n    y = x\n    z = xx\n    return y, z\n\ndef call(x: int) -> int:\n    y = x\n    return call(y)\n\ndef method_call(c: C, x: int) -> None:\n    y = x\n    c.m(y)\n\ndef cast_op(x: object) -> str:\n    y = x\n    return cast(str, y)\n\ndef box(x: int) -> object:\n    y = x\n    return y\n\ndef unbox(x: object) -> int:\n    y = x\n    return cast(int, y)\n\ndef call_c(x: list[str]) -> None:\n    y = x\n    y.append(\"x\")\n\ndef keep_alive(x: C) -> int:\n    y = x\n    return y.a + 1\n[out]\ndef C.m(self, x):\n    self :: __main__.C\n    x :: int\nL0:\n    return 1\ndef get_attr(x):\n    x :: __main__.C\n    r0 :: int\nL0:\n    r0 = x.a\n    return r0\ndef set_attr(x):\n    x :: __main__.C\n    r0 :: bool\nL0:\n    x.a = 2; r0 = is_error\n    return 1\ndef tuple_get(x):\n    x :: tuple[int, int]\n    r0 :: int\nL0:\n    r0 = x[0]\n    return r0\ndef tuple_set(x, xx):\n    x, xx :: int\n    r0 :: tuple[int, int]\nL0:\n    r0 = (x, xx)\n    return r0\ndef call(x):\n    x, r0 :: int\nL0:\n    r0 = call(x)\n    return r0\ndef method_call(c, x):\n    c :: __main__.C\n    x :: int\n    r0 :: None\nL0:\n    r0 = c.m(x)\n    return 1\ndef cast_op(x):\n    x :: object\n    r0 :: str\nL0:\n    r0 = cast(str, x)\n    return r0\ndef box(x):\n    x :: int\n    r0 :: object\nL0:\n    r0 = box(int, x)\n    return r0\ndef unbox(x):\n    x :: object\n    r0 :: int\nL0:\n    r0 = unbox(int, x)\n    return r0\ndef call_c(x):\n    x :: list\n    r0 :: str\n    r1 :: i32\n    r2 :: bit\nL0:\n    r0 = 'x'\n    r1 = PyList_Append(x, r0)\n    r2 = r1 >= 0 :: signed\n    return 1\ndef keep_alive(x):\n    x :: __main__.C\n    r0, r1 :: int\nL0:\n    r0 = borrow x.a\n    r1 = CPyTagged_Add(r0, 2)\n    keep_alive x\n    return r1\n\n[case testIRTransformRegisterOps2]\nfrom mypy_extensions import i32, i64\n\ndef truncate(x: i64) -> i32:\n    y = x\n    return i32(y)\n\ndef extend(x: i32) -> i64:\n    y = x\n    return i64(y)\n\ndef int_op(x: i64, xx: i64) -> i64:\n    y = x\n    z = xx\n    return y + z\n\ndef comparison_op(x: i64, xx: i64) -> bool:\n    y = x\n    z = xx\n    return y == z\n\ndef float_op(x: float, xx: float) -> float:\n    y = x\n    z = xx\n    return y + z\n\ndef float_neg(x: float) -> float:\n    y = x\n    return -y\n\ndef float_comparison_op(x: float, xx: float) -> bool:\n    y = x\n    z = xx\n    return y == z\n[out]\ndef truncate(x):\n    x :: i64\n    r0 :: i32\nL0:\n    r0 = truncate x: i64 to i32\n    return r0\ndef extend(x):\n    x :: i32\n    r0 :: i64\nL0:\n    r0 = extend signed x: i32 to i64\n    return r0\ndef int_op(x, xx):\n    x, xx, r0 :: i64\nL0:\n    r0 = x + xx\n    return r0\ndef comparison_op(x, xx):\n    x, xx :: i64\n    r0 :: bit\nL0:\n    r0 = x == xx\n    return r0\ndef float_op(x, xx):\n    x, xx, r0 :: float\nL0:\n    r0 = x + xx\n    return r0\ndef float_neg(x):\n    x, r0 :: float\nL0:\n    r0 = -x\n    return r0\ndef float_comparison_op(x, xx):\n    x, xx :: float\n    r0 :: bit\nL0:\n    r0 = x == xx\n    return r0\n\n-- Note that transforms of these ops aren't tested here:\n-- * LoadMem\n-- * SetMem\n-- * GetElementPtr\n-- * LoadAddress\n-- * Unborrow\n"
  },
  {
    "path": "mypyc/test-data/opt-flag-elimination.test",
    "content": "-- Test cases for \"flag elimination\" optimization.  Used to optimize away\n-- registers that are always used immediately after assignment as branch conditions.\n\n[case testFlagEliminationSimple]\ndef c() -> bool:\n    return True\ndef d() -> bool:\n    return True\n\ndef f(x: bool) -> int:\n    if x:\n        b = c()\n    else:\n        b = d()\n    if b:\n        return 1\n    else:\n        return 2\n[out]\ndef c():\nL0:\n    return 1\ndef d():\nL0:\n    return 1\ndef f(x):\n    x, r0, r1 :: bool\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    r0 = c()\n    if r0 goto L3 else goto L4 :: bool\nL2:\n    r1 = d()\n    if r1 goto L3 else goto L4 :: bool\nL3:\n    return 2\nL4:\n    return 4\n\n[case testFlagEliminationOneAssignment]\ndef c() -> bool:\n    return True\n\ndef f(x: bool) -> int:\n    # Not applied here\n    b = c()\n    if b:\n        return 1\n    else:\n        return 2\n[out]\ndef c():\nL0:\n    return 1\ndef f(x):\n    x, r0, b :: bool\nL0:\n    r0 = c()\n    b = r0\n    if b goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 4\n\n[case testFlagEliminationThreeCases]\ndef c(x: int) -> bool:\n    return True\n\ndef f(x: bool, y: bool) -> int:\n    if x:\n        b = c(1)\n    elif y:\n        b = c(2)\n    else:\n        b = c(3)\n    if b:\n        return 1\n    else:\n        return 2\n[out]\ndef c(x):\n    x :: int\nL0:\n    return 1\ndef f(x, y):\n    x, y, r0, r1, r2 :: bool\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    r0 = c(2)\n    if r0 goto L5 else goto L6 :: bool\nL2:\n    if y goto L3 else goto L4 :: bool\nL3:\n    r1 = c(4)\n    if r1 goto L5 else goto L6 :: bool\nL4:\n    r2 = c(6)\n    if r2 goto L5 else goto L6 :: bool\nL5:\n    return 2\nL6:\n    return 4\n\n[case testFlagEliminationAssignmentNotLastOp]\ndef f(x: bool) -> int:\n    y = 0\n    if x:\n        b = True\n        y = 1\n    else:\n        b = False\n    if b:\n        return 1\n    else:\n        return 2\n[out]\ndef f(x):\n    x :: bool\n    y :: int\n    b :: bool\nL0:\n    y = 0\n    if x goto L1 else goto L2 :: bool\nL1:\n    b = 1\n    y = 2\n    goto L3\nL2:\n    b = 0\nL3:\n    if b goto L4 else goto L5 :: bool\nL4:\n    return 2\nL5:\n    return 4\n\n[case testFlagEliminationAssignmentNoDirectGoto]\ndef f(x: bool) -> int:\n    if x:\n        b = True\n    else:\n        b = False\n    if x:\n        if b:\n            return 1\n        else:\n            return 2\n    return 4\n[out]\ndef f(x):\n    x, b :: bool\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    b = 1\n    goto L3\nL2:\n    b = 0\nL3:\n    if x goto L4 else goto L7 :: bool\nL4:\n    if b goto L5 else goto L6 :: bool\nL5:\n    return 2\nL6:\n    return 4\nL7:\n    return 8\n\n[case testFlagEliminationBranchNotNextOpAfterGoto]\ndef f(x: bool) -> int:\n    if x:\n        b = True\n    else:\n        b = False\n    y = 1  # Prevents the optimization\n    if b:\n        return 1\n    else:\n        return 2\n[out]\ndef f(x):\n    x, b :: bool\n    y :: int\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    b = 1\n    goto L3\nL2:\n    b = 0\nL3:\n    y = 2\n    if b goto L4 else goto L5 :: bool\nL4:\n    return 2\nL5:\n    return 4\n\n[case testFlagEliminationFlagReadTwice]\ndef f(x: bool) -> bool:\n    if x:\n        b = True\n    else:\n        b = False\n    if b:\n        return b  # Prevents the optimization\n    else:\n        return False\n[out]\ndef f(x):\n    x, b :: bool\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    b = 1\n    goto L3\nL2:\n    b = 0\nL3:\n    if b goto L4 else goto L5 :: bool\nL4:\n    return b\nL5:\n    return 0\n\n[case testFlagEliminationArgumentNotEligible]\ndef f(x: bool, b: bool) -> bool:\n    if x:\n        b = True\n    else:\n        b = False\n    if b:\n        return True\n    else:\n        return False\n[out]\ndef f(x, b):\n    x, b :: bool\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    b = 1\n    goto L3\nL2:\n    b = 0\nL3:\n    if b goto L4 else goto L5 :: bool\nL4:\n    return 1\nL5:\n    return 0\n\n[case testFlagEliminationFlagNotAlwaysDefined]\ndef f(x: bool, y: bool) -> bool:\n    if x:\n        b = True\n    elif y:\n        b = False\n    else:\n        bb = False  # b not assigned here -> can't optimize\n    if b:\n        return True\n    else:\n        return False\n[out]\ndef f(x, y):\n    x, y, r0, b, bb, r1 :: bool\nL0:\n    r0 = <error> :: bool\n    b = r0\n    if x goto L1 else goto L2 :: bool\nL1:\n    b = 1\n    goto L5\nL2:\n    if y goto L3 else goto L4 :: bool\nL3:\n    b = 0\n    goto L5\nL4:\n    bb = 0\nL5:\n    if is_error(b) goto L6 else goto L7\nL6:\n    r1 = raise UnboundLocalError('local variable \"b\" referenced before assignment')\n    unreachable\nL7:\n    if b goto L8 else goto L9 :: bool\nL8:\n    return 1\nL9:\n    return 0\n"
  },
  {
    "path": "mypyc/test-data/refcount.test",
    "content": "-- Test cases for reference count  insertion.\n\n[case testReturnLiteral]\ndef f() -> int:\n    return 1\n[out]\ndef f():\nL0:\n    return 2\n\n[case testReturnLocal]\ndef f() -> int:\n    x = 1\n    return x\n[out]\ndef f():\n    x :: int\nL0:\n    x = 2\n    return x\n\n[case testLocalVars]\ndef f() -> int:\n    x = 1\n    y = x\n    x = y\n    return x\n[out]\ndef f():\n    x, y :: int\nL0:\n    x = 2\n    y = x\n    x = y\n    return x\n\n[case testLocalVars2]\ndef f() -> int:\n    x = 1\n    y = x\n    z = x\n    return y + z\n[out]\ndef f():\n    x, y, z, r0 :: int\nL0:\n    x = 2\n    inc_ref x :: int\n    y = x\n    z = x\n    r0 = CPyTagged_Add(y, z)\n    dec_ref y :: int\n    dec_ref z :: int\n    return r0\n\n[case testFreeAtReturn]\ndef f() -> int:\n    x = 1\n    y = 2\n    if x == 1:\n        return x\n    return y\n[out]\ndef f():\n    x, y :: int\n    r0 :: bit\nL0:\n    x = 2\n    y = 4\n    r0 = int_eq x, 2\n    if r0 goto L3 else goto L4 :: bool\nL1:\n    return x\nL2:\n    return y\nL3:\n    dec_ref y :: int\n    goto L1\nL4:\n    dec_ref x :: int\n    goto L2\n\n[case testArgumentsInOps]\ndef f(a: int, b: int) -> int:\n    x = a + 1\n    y = x + a\n    return y\n[out]\ndef f(a, b):\n    a, b, r0, x, r1, y :: int\nL0:\n    r0 = CPyTagged_Add(a, 2)\n    x = r0\n    r1 = CPyTagged_Add(x, a)\n    dec_ref x :: int\n    y = r1\n    return y\n\n[case testArgumentsInAssign]\ndef f(a: int) -> int:\n    x = a\n    y = a\n    x = 1\n    return x + y\n[out]\ndef f(a):\n    a, x, y, r0 :: int\nL0:\n    inc_ref a :: int\n    x = a\n    dec_ref x :: int\n    inc_ref a :: int\n    y = a\n    x = 2\n    r0 = CPyTagged_Add(x, y)\n    dec_ref x :: int\n    dec_ref y :: int\n    return r0\n\n[case testAssignToArgument1]\ndef f(a: int) -> int:\n    a = 1\n    y = a\n    return y\n[out]\ndef f(a):\n    a, y :: int\nL0:\n    a = 2\n    y = a\n    return y\n\n[case testAssignToArgument2]\ndef f(a: int) -> int:\n    a = 1\n    a = 2\n    a = 3\n    return a\n[out]\ndef f(a):\n    a :: int\nL0:\n    a = 2\n    dec_ref a :: int\n    a = 4\n    dec_ref a :: int\n    a = 6\n    return a\n\n[case testAssignToArgument3]\ndef f(a: int) -> int:\n    x = 1\n    a = x\n    y = x\n    return a\n[out]\ndef f(a):\n    a, x, y :: int\nL0:\n    x = 2\n    inc_ref x :: int\n    a = x\n    y = x\n    dec_ref y :: int\n    return a\n\n[case testReturnArgument]\ndef f(a: int) -> int:\n    return a\n[out]\ndef f(a):\n    a :: int\nL0:\n    inc_ref a :: int\n    return a\n\n[case testConditionalAssignToArgument1]\ndef f(a: int) -> int:\n    if a == a:\n        a = 1\n    else:\n        x = 2\n    y = a + 1\n    return y\n[out]\ndef f(a):\n    a :: int\n    r0 :: bit\n    x, r1, y :: int\nL0:\n    r0 = int_eq a, a\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    a = 2\n    goto L3\nL2:\n    x = 4\n    dec_ref x :: int\n    goto L4\nL3:\n    r1 = CPyTagged_Add(a, 2)\n    dec_ref a :: int\n    y = r1\n    return y\nL4:\n    inc_ref a :: int\n    goto L3\n\n[case testConditionalAssignToArgument2]\ndef f(a: int) -> int:\n    if a == a:\n        x = 2\n    else:\n        a = 1\n    y = a + 1\n    return y\n[out]\ndef f(a):\n    a :: int\n    r0 :: bit\n    x, r1, y :: int\nL0:\n    r0 = int_eq a, a\n    if r0 goto L1 else goto L2 :: bool\nL1:\n    x = 4\n    dec_ref x :: int\n    goto L4\nL2:\n    a = 2\nL3:\n    r1 = CPyTagged_Add(a, 2)\n    dec_ref a :: int\n    y = r1\n    return y\nL4:\n    inc_ref a :: int\n    goto L3\n\n[case testConditionalAssignToArgument3]\ndef f(a: int) -> int:\n    if a == a:\n        a = 1\n    return a\n[out]\ndef f(a):\n    a :: int\n    r0 :: bit\nL0:\n    r0 = int_eq a, a\n    if r0 goto L1 else goto L3 :: bool\nL1:\n    a = 2\nL2:\n    return a\nL3:\n    inc_ref a :: int\n    goto L2\n\n[case testAssignRegisterToItself]\ndef f(a: int) -> int:\n    a = a\n    x = 1\n    x = x\n    return x + a\n-- This is correct but bad code\n[out]\ndef f(a):\n    a, x, r0 :: int\nL0:\n    inc_ref a :: int\n    a = a\n    x = 2\n    inc_ref x :: int\n    dec_ref x :: int\n    x = x\n    r0 = CPyTagged_Add(x, a)\n    dec_ref x :: int\n    dec_ref a :: int\n    return r0\n\n[case testIncrement1]\ndef f(a: int) -> int:\n    a = a + 1\n    x = 1\n    x = x + 1\n    return a + x\n[out]\ndef f(a):\n    a, r0, x, r1, r2 :: int\nL0:\n    r0 = CPyTagged_Add(a, 2)\n    a = r0\n    x = 2\n    r1 = CPyTagged_Add(x, 2)\n    dec_ref x :: int\n    x = r1\n    r2 = CPyTagged_Add(a, x)\n    dec_ref a :: int\n    dec_ref x :: int\n    return r2\n\n[case testIncrement2]\ndef f() -> None:\n    x = 1\n    x = x + 1\n[out]\ndef f():\n    x, r0 :: int\nL0:\n    x = 2\n    r0 = CPyTagged_Add(x, 2)\n    dec_ref x :: int\n    x = r0\n    dec_ref x :: int\n    return 1\n\n[case testAdd1]\ndef f() -> None:\n    y = 1\n    x = y + 1\n[out]\ndef f():\n    y, r0, x :: int\nL0:\n    y = 2\n    r0 = CPyTagged_Add(y, 2)\n    dec_ref y :: int\n    x = r0\n    dec_ref x :: int\n    return 1\n\n[case testAdd2]\ndef f(a: int) -> int:\n    a = a + a\n    x = a\n    x = x + x\n    return x\n[out]\ndef f(a):\n    a, r0, x, r1 :: int\nL0:\n    r0 = CPyTagged_Add(a, a)\n    a = r0\n    x = a\n    r1 = CPyTagged_Add(x, x)\n    dec_ref x :: int\n    x = r1\n    return x\n\n[case testAdd3]\ndef f(a: int) -> int:\n    x = a + a\n    y = x + x\n    return y\n[out]\ndef f(a):\n    a, r0, x, r1, y :: int\nL0:\n    r0 = CPyTagged_Add(a, a)\n    x = r0\n    r1 = CPyTagged_Add(x, x)\n    dec_ref x :: int\n    y = r1\n    return y\n\n[case testAdd4]\ndef f(a: int) -> None:\n    x = a + a\n    y = 1\n    z = y + y\n[out]\ndef f(a):\n    a, r0, x, y, r1, z :: int\nL0:\n    r0 = CPyTagged_Add(a, a)\n    x = r0\n    dec_ref x :: int\n    y = 2\n    r1 = CPyTagged_Add(y, y)\n    dec_ref y :: int\n    z = r1\n    dec_ref z :: int\n    return 1\n\n[case testAdd5]\ndef f(a: int) -> None:\n    a = a + a\n    x = 1\n    x = x + x\n[out]\ndef f(a):\n    a, r0, x, r1 :: int\nL0:\n    r0 = CPyTagged_Add(a, a)\n    a = r0\n    dec_ref a :: int\n    x = 2\n    r1 = CPyTagged_Add(x, x)\n    dec_ref x :: int\n    x = r1\n    dec_ref x :: int\n    return 1\n\n[case testReturnInMiddleOfFunction]\ndef f() -> int:\n    x = 1\n    y = 2\n    z = 3\n    if z == z:\n        return z\n    a = 1\n    return x + y - a\n[out]\ndef f():\n    x, y, z :: int\n    r0 :: bit\n    a, r1, r2 :: int\nL0:\n    x = 2\n    y = 4\n    z = 6\n    r0 = int_eq z, z\n    if r0 goto L3 else goto L4 :: bool\nL1:\n    return z\nL2:\n    a = 2\n    r1 = CPyTagged_Add(x, y)\n    dec_ref x :: int\n    dec_ref y :: int\n    r2 = CPyTagged_Subtract(r1, a)\n    dec_ref r1 :: int\n    dec_ref a :: int\n    return r2\nL3:\n    dec_ref x :: int\n    dec_ref y :: int\n    goto L1\nL4:\n    dec_ref z :: int\n    goto L2\n\n[case testLoop]\ndef f(a: int) -> int:\n    sum = 0\n    i = 0\n    while i <= a:\n        sum = sum + i\n        i = i + 1\n    return sum\n[out]\ndef f(a):\n    a, sum, i :: int\n    r0 :: bit\n    r1, r2 :: int\nL0:\n    sum = 0\n    i = 0\nL1:\n    r0 = int_le i, a\n    if r0 goto L2 else goto L4 :: bool\nL2:\n    r1 = CPyTagged_Add(sum, i)\n    dec_ref sum :: int\n    sum = r1\n    r2 = CPyTagged_Add(i, 2)\n    dec_ref i :: int\n    i = r2\n    goto L1\nL3:\n    return sum\nL4:\n    dec_ref i :: int\n    goto L3\n\n[case testCall]\ndef f(a: int) -> int:\n    return f(a + 1)\n[out]\ndef f(a):\n    a, r0, r1 :: int\nL0:\n    r0 = CPyTagged_Add(a, 2)\n    r1 = f(r0)\n    dec_ref r0 :: int\n    return r1\n\n[case testError]\ndef f(x: List[int]) -> None: pass # E: Name \"List\" is not defined \\\n                                  # N: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import List\")\n\n[case testNewList]\ndef f() -> int:\n    a = [0, 1]\n    return 0\n[out]\ndef f():\n    r0 :: list\n    r1, r2 :: object\n    r3 :: ptr\n    a :: list\nL0:\n    r0 = PyList_New(2)\n    r1 = object 0\n    r2 = object 1\n    r3 = list_items r0\n    inc_ref r1\n    buf_init_item r3, 0, r1\n    inc_ref r2\n    buf_init_item r3, 1, r2\n    a = r0\n    dec_ref a\n    return 0\n\n[case testListSet]\nfrom typing import List\ndef f(a: List[int], b: List[int]) -> None:\n    a[0] = b[0]\n[out]\ndef f(a, b):\n    a, b :: list\n    r0 :: object\n    r1 :: int\n    r2 :: object\n    r3 :: bit\nL0:\n    r0 = CPyList_GetItemShort(b, 0)\n    r1 = unbox(int, r0)\n    dec_ref r0\n    r2 = box(int, r1)\n    r3 = CPyList_SetItem(a, 0, r2)\n    return 1\n\n[case testTupleRefcount]\nfrom typing import Tuple\ndef f(x: Tuple[Tuple[int, bool], bool]) -> int:\n    return x[0][0]\n[out]\ndef f(x):\n    x :: tuple[tuple[int, bool], bool]\n    r0 :: tuple[int, bool]\n    r1 :: int\nL0:\n    r0 = x[0]\n    r1 = r0[0]\n    dec_ref r0\n    return r1\n\n[case testUserClassRefCount]\nclass C:\n    x: 'C'\ndef f() -> None:\n    c = C()\n    c.x = C()\n[out]\ndef f():\n    r0, c, r1 :: __main__.C\n    r2 :: bool\nL0:\n    r0 = C()\n    c = r0\n    r1 = C()\n    c.x = r1; r2 = is_error\n    dec_ref c\n    return 1\n\n[case testCastRefCount]\nclass C: pass\n\ndef f() -> None:\n    a = [C()]\n    d = a[0]\n[out]\ndef f():\n    r0 :: __main__.C\n    r1 :: list\n    r2 :: ptr\n    a :: list\n    r3 :: object\n    r4, d :: __main__.C\nL0:\n    r0 = C()\n    r1 = PyList_New(1)\n    r2 = list_items r1\n    buf_init_item r2, 0, r0\n    a = r1\n    r3 = CPyList_GetItemShort(a, 0)\n    dec_ref a\n    r4 = cast(__main__.C, r3)\n    d = r4\n    dec_ref d\n    return 1\n\n[case testUnaryBranchSpecialCase]\ndef f(x: bool) -> int:\n    if x:\n        return 1\n    return 2\n[out]\ndef f(x):\n    x :: bool\nL0:\n    if x goto L1 else goto L2 :: bool\nL1:\n    return 2\nL2:\n    return 4\n\n[case testReturnTuple]\nfrom typing import Tuple\n\nclass C: pass\ndef f() -> Tuple[C, C]:\n    a = C()\n    b = C()\n    return a, b\n[out]\ndef f():\n    r0, a, r1, b :: __main__.C\n    r2 :: tuple[__main__.C, __main__.C]\nL0:\n    r0 = C()\n    a = r0\n    r1 = C()\n    b = r1\n    r2 = (a, b)\n    return r2\n\n[case testDecomposeTuple]\nfrom typing import Tuple\n\nclass C:\n    a: int\n\ndef f() -> int:\n    x, y = g()\n    return x.a + y.a\n\ndef g() -> Tuple[C, C]:\n    return C(), C()\n[out]\ndef f():\n    r0 :: tuple[__main__.C, __main__.C]\n    r1, r2, r3, x, r4, y :: __main__.C\n    r5, r6, r7 :: int\nL0:\n    r0 = g()\n    r1 = borrow r0[0]\n    r2 = borrow r0[1]\n    r3 = unborrow r1\n    x = r3\n    r4 = unborrow r2\n    y = r4\n    r5 = borrow x.a\n    r6 = borrow y.a\n    r7 = CPyTagged_Add(r5, r6)\n    dec_ref x\n    dec_ref y\n    return r7\ndef g():\n    r0, r1 :: __main__.C\n    r2 :: tuple[__main__.C, __main__.C]\nL0:\n    r0 = C()\n    r1 = C()\n    r2 = (r0, r1)\n    return r2\n\n[case testUnicodeLiteral]\ndef f() -> str:\n    return \"some string\"\n[out]\ndef f():\n    r0 :: str\nL0:\n    r0 = 'some string'\n    inc_ref r0\n    return r0\n\n[case testPyMethodCall]\ndef g(x: str) -> int:\n    return int(x, base=2)\n[out]\ndef g(x):\n    x :: str\n    r0, r1 :: object\n    r2 :: object[2]\n    r3 :: object_ptr\n    r4, r5 :: object\n    r6 :: int\nL0:\n    r0 = load_address PyLong_Type\n    r1 = object 2\n    r2 = [x, r1]\n    r3 = load_address r2\n    r4 = ('base',)\n    r5 = PyObject_Vectorcall(r0, r3, 1, r4)\n    r6 = unbox(int, r5)\n    dec_ref r5\n    return r6\n\n[case testListAppend]\nfrom typing import List\ndef f(a: List[int], x: int) -> None:\n    a.append(x)\n[out]\ndef f(a, x):\n    a :: list\n    x :: int\n    r0 :: object\n    r1 :: i32\n    r2 :: bit\nL0:\n    inc_ref x :: int\n    r0 = box(int, x)\n    r1 = PyList_Append(a, r0)\n    dec_ref r0\n    r2 = r1 >= 0 :: signed\n    return 1\n\n[case testForDict]\nfrom typing import Dict\n\ndef f(d: Dict[int, int]) -> None:\n    for key in d:\n        d[key]\n[out]\ndef f(d):\n    d :: dict\n    r0 :: short_int\n    r1 :: native_int\n    r2 :: object\n    r3 :: tuple[bool, short_int, object]\n    r4 :: short_int\n    r5 :: bool\n    r6 :: object\n    r7, key :: int\n    r8, r9 :: object\n    r10 :: int\n    r11, r12 :: bit\nL0:\n    r0 = 0\n    r1 = PyDict_Size(d)\n    r2 = CPyDict_GetKeysIter(d)\nL1:\n    r3 = CPyDict_NextKey(r2, r0)\n    r4 = r3[1]\n    r0 = r4\n    r5 = r3[0]\n    if r5 goto L2 else goto L6 :: bool\nL2:\n    r6 = r3[2]\n    dec_ref r3\n    r7 = unbox(int, r6)\n    dec_ref r6\n    key = r7\n    r8 = box(int, key)\n    r9 = CPyDict_GetItem(d, r8)\n    dec_ref r8\n    r10 = unbox(int, r9)\n    dec_ref r9\n    dec_ref r10 :: int\nL3:\n    r11 = CPyDict_CheckSize(d, r1)\n    goto L1\nL4:\n    r12 = CPy_NoErrOccurred()\nL5:\n    return 1\nL6:\n    dec_ref r2\n    dec_ref r3\n    goto L4\n\n[case testBorrowRefs]\ndef make_garbage(arg: object) -> None:\n    b = True\n    while b:\n        arg = None\n        b = False\n[out]\ndef make_garbage(arg):\n    arg :: object\n    b :: bool\n    r0 :: object\nL0:\n    b = 1\nL1:\n    if b goto L2 else goto L3 :: bool\nL2:\n    r0 = box(None, 1)\n    inc_ref r0\n    arg = r0\n    dec_ref arg\n    b = 0\n    goto L1\nL3:\n    return 1\n\n[case testTupleUnpackUnused]\nfrom typing import Tuple\n\ndef f(x: Tuple[str, int]) -> int:\n    a, xi = x\n    return 0\n[out]\ndef f(x):\n    x :: tuple[str, int]\n    r0 :: str\n    r1 :: int\n    r2, a :: str\n    r3, xi :: int\nL0:\n    r0 = borrow x[0]\n    r1 = borrow x[1]\n    inc_ref x\n    r2 = unborrow r0\n    a = r2\n    dec_ref a\n    r3 = unborrow r1\n    xi = r3\n    dec_ref xi :: int\n    return 0\n\n[case testGetElementPtrLifeTime]\nfrom typing import List\n\ndef f() -> int:\n    x: List[str] = []\n    return len(x)\n[out]\ndef f():\n    r0, x :: list\n    r1 :: native_int\n    r2 :: short_int\nL0:\n    r0 = PyList_New(0)\n    x = r0\n    r1 = var_object_size x\n    dec_ref x\n    r2 = r1 << 1\n    return r2\n\n[case testSometimesUninitializedVariable]\ndef f(x: bool) -> int:\n    if x:\n        y = 1\n    else:\n        z = 2\n    return y + z\n[out]\ndef f(x):\n    x :: bool\n    r0, y, r1, z :: int\n    r2, r3 :: bool\n    r4 :: int\nL0:\n    r0 = <error> :: int\n    y = r0\n    r1 = <error> :: int\n    z = r1\n    if x goto L8 else goto L9 :: bool\nL1:\n    y = 2\n    goto L3\nL2:\n    z = 4\nL3:\n    if is_error(y) goto L10 else goto L5\nL4:\n    r2 = raise UnboundLocalError('local variable \"y\" referenced before assignment')\n    unreachable\nL5:\n    if is_error(z) goto L11 else goto L7\nL6:\n    r3 = raise UnboundLocalError('local variable \"z\" referenced before assignment')\n    unreachable\nL7:\n    r4 = CPyTagged_Add(y, z)\n    xdec_ref y :: int\n    xdec_ref z :: int\n    return r4\nL8:\n    xdec_ref y :: int\n    goto L1\nL9:\n    xdec_ref z :: int\n    goto L2\nL10:\n    xdec_ref z :: int\n    goto L4\nL11:\n    xdec_ref y :: int\n    goto L6\n\n[case testVectorcall]\nfrom typing import Any\n\ndef call(f: Any, x: int) -> int:\n    return f(x)\n[out]\ndef call(f, x):\n    f :: object\n    x :: int\n    r0 :: object\n    r1 :: object[1]\n    r2 :: object_ptr\n    r3 :: object\n    r4 :: int\nL0:\n    inc_ref x :: int\n    r0 = box(int, x)\n    r1 = [r0]\n    r2 = load_address r1\n    r3 = PyObject_Vectorcall(f, r2, 1, 0)\n    dec_ref r0\n    r4 = unbox(int, r3)\n    dec_ref r3\n    return r4\n\n[case testVectorcallMethod_64bit]\nfrom typing import Any\n\ndef call(o: Any, x: int) -> int:\n    return o.m(x)\n[out]\ndef call(o, x):\n    o :: object\n    x :: int\n    r0 :: str\n    r1 :: object\n    r2 :: object[2]\n    r3 :: object_ptr\n    r4 :: object\n    r5 :: int\nL0:\n    r0 = 'm'\n    inc_ref x :: int\n    r1 = box(int, x)\n    r2 = [o, r1]\n    r3 = load_address r2\n    r4 = PyObject_VectorcallMethod(r0, r3, 9223372036854775810, 0)\n    dec_ref r1\n    r5 = unbox(int, r4)\n    dec_ref r4\n    return r5\n\n[case testBorrowAttribute]\ndef g() -> int:\n    d = D()\n    return d.c.x\n\ndef f(d: D) -> int:\n    return d.c.x\n\nclass C:\n    x: int\nclass D:\n    c: C\n[out]\ndef g():\n    r0, d :: __main__.D\n    r1 :: __main__.C\n    r2 :: int\nL0:\n    r0 = D()\n    d = r0\n    r1 = borrow d.c\n    r2 = r1.x\n    dec_ref d\n    return r2\ndef f(d):\n    d :: __main__.D\n    r0 :: __main__.C\n    r1 :: int\nL0:\n    r0 = borrow d.c\n    r1 = r0.x\n    return r1\n\n[case testBorrowAttributeTwice]\ndef f(e: E) -> int:\n    return e.d.c.x\n\nclass C:\n    x: int\nclass D:\n    c: C\nclass E:\n    d: D\n[out]\ndef f(e):\n    e :: __main__.E\n    r0 :: __main__.D\n    r1 :: __main__.C\n    r2 :: int\nL0:\n    r0 = borrow e.d\n    r1 = borrow r0.c\n    r2 = r1.x\n    return r2\n\n[case testBorrowAttributeIsNone]\nfrom typing import Optional\n\ndef f(c: C) -> bool:\n    return c.x is not None\n\ndef g(c: C) -> bool:\n    return c.x is None\n\nclass C:\n    x: Optional[str]\n[out]\ndef f(c):\n    c :: __main__.C\n    r0 :: union[str, None]\n    r1 :: object\n    r2 :: bit\nL0:\n    r0 = borrow c.x\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 != r1\n    return r2\ndef g(c):\n    c :: __main__.C\n    r0 :: union[str, None]\n    r1 :: object\n    r2 :: bit\nL0:\n    r0 = borrow c.x\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 == r1\n    return r2\n\n[case testBorrowAttributeNarrowOptional]\nfrom typing import Optional\n\ndef f(c: C) -> bool:\n    if c.x is not None:\n        return c.x.b\n    return False\n\nclass C:\n    x: Optional[D]\n\nclass D:\n    b: bool\n[out]\ndef f(c):\n    c :: __main__.C\n    r0 :: union[__main__.D, None]\n    r1 :: object\n    r2 :: bit\n    r3 :: union[__main__.D, None]\n    r4 :: __main__.D\n    r5 :: bool\nL0:\n    r0 = borrow c.x\n    r1 = load_address _Py_NoneStruct\n    r2 = r0 != r1\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = borrow c.x\n    r4 = borrow cast(__main__.D, r3)\n    r5 = r4.b\n    return r5\nL2:\n    return 0\n\n[case testBorrowLenArgument]\nfrom typing import List\n\ndef f(x: C) -> int:\n    return len(x.a)\n\nclass C:\n    a: List[str]\n[out]\ndef f(x):\n    x :: __main__.C\n    r0 :: list\n    r1 :: native_int\n    r2 :: short_int\nL0:\n    r0 = borrow x.a\n    r1 = var_object_size r0\n    r2 = r1 << 1\n    return r2\n\n[case testBorrowIsinstanceArgument]\nfrom typing import List\n\ndef f(x: C) -> bool:\n    if isinstance(x.a, D):\n        return x.a.b\n    else:\n        return True\n\nclass C:\n    a: object\n\nclass D:\n    b: bool\n[out]\ndef f(x):\n    x :: __main__.C\n    r0, r1 :: object\n    r2 :: ptr\n    r3 :: object\n    r4 :: bit\n    r5 :: object\n    r6 :: __main__.D\n    r7 :: bool\nL0:\n    r0 = borrow x.a\n    r1 = __main__.D :: type\n    r2 = get_element_ptr r0 ob_type :: PyObject\n    r3 = borrow load_mem r2 :: builtins.object*\n    r4 = r3 == r1\n    if r4 goto L1 else goto L2 :: bool\nL1:\n    r5 = borrow x.a\n    r6 = borrow cast(__main__.D, r5)\n    r7 = r6.b\n    return r7\nL2:\n    return 1\n\n[case testBorrowListGetItem1]\nfrom typing import List\n\ndef literal_index(x: C) -> str:\n    return x.a[0]\n\ndef negative_index(x: C) -> str:\n    return x.a[-1]\n\ndef lvar_index(x: C, n: int) -> str:\n    return x.a[n]\n\nclass C:\n    a: List[str]\n\n[out]\ndef literal_index(x):\n    x :: __main__.C\n    r0 :: list\n    r1 :: object\n    r2 :: str\nL0:\n    r0 = borrow x.a\n    r1 = CPyList_GetItemShort(r0, 0)\n    r2 = cast(str, r1)\n    return r2\ndef negative_index(x):\n    x :: __main__.C\n    r0 :: list\n    r1 :: object\n    r2 :: str\nL0:\n    r0 = borrow x.a\n    r1 = CPyList_GetItemShort(r0, -2)\n    r2 = cast(str, r1)\n    return r2\ndef lvar_index(x, n):\n    x :: __main__.C\n    n :: int\n    r0 :: list\n    r1 :: object\n    r2 :: str\nL0:\n    r0 = borrow x.a\n    r1 = CPyList_GetItem(r0, n)\n    r2 = cast(str, r1)\n    return r2\n\n[case testBorrowListGetItem2]\nfrom typing import List\n\ndef attr_before_index(x: C) -> str:\n    return x.a[x.n]\n\ndef attr_after_index(a: List[C], i: int) -> int:\n    return a[i].n\n\ndef attr_after_index_literal(a: List[C]) -> int:\n    return a[0].n\n\nclass C:\n    a: List[str]\n    n: int\n[out]\ndef attr_before_index(x):\n    x :: __main__.C\n    r0 :: list\n    r1 :: int\n    r2 :: object\n    r3 :: str\nL0:\n    r0 = borrow x.a\n    r1 = borrow x.n\n    r2 = CPyList_GetItem(r0, r1)\n    r3 = cast(str, r2)\n    return r3\ndef attr_after_index(a, i):\n    a :: list\n    i :: int\n    r0 :: object\n    r1 :: __main__.C\n    r2 :: int\nL0:\n    r0 = CPyList_GetItemBorrow(a, i)\n    r1 = borrow cast(__main__.C, r0)\n    r2 = r1.n\n    return r2\ndef attr_after_index_literal(a):\n    a :: list\n    r0 :: object\n    r1 :: __main__.C\n    r2 :: int\nL0:\n    r0 = CPyList_GetItemShortBorrow(a, 0)\n    r1 = borrow cast(__main__.C, r0)\n    r2 = r1.n\n    return r2\n\n[case testCannotBorrowListGetItem]\nfrom typing import List\n\ndef func_index(x: C) -> str:\n    return x.a[f()]\n\ndef f() -> int: return 0\n\nclass C:\n    a: List[str]\n[out]\ndef func_index(x):\n    x :: __main__.C\n    r0 :: list\n    r1 :: int\n    r2 :: object\n    r3 :: str\nL0:\n    r0 = x.a\n    r1 = f()\n    r2 = CPyList_GetItem(r0, r1)\n    dec_ref r0\n    dec_ref r1 :: int\n    r3 = cast(str, r2)\n    return r3\ndef f():\nL0:\n    return 0\n\n[case testBorrowListGetItemKeepAlive]\nfrom typing import List\n\ndef f() -> str:\n    a = [C()]\n    return a[0].s\n\nclass C:\n    s: str\n[out]\ndef f():\n    r0 :: __main__.C\n    r1 :: list\n    r2 :: ptr\n    a :: list\n    r3 :: object\n    r4 :: __main__.C\n    r5 :: str\nL0:\n    r0 = C()\n    r1 = PyList_New(1)\n    r2 = list_items r1\n    buf_init_item r2, 0, r0\n    a = r1\n    r3 = CPyList_GetItemShortBorrow(a, 0)\n    r4 = borrow cast(__main__.C, r3)\n    r5 = r4.s\n    dec_ref a\n    return r5\n\n[case testBorrowSetAttrObject]\nfrom typing import Optional\n\ndef f(x: Optional[C]) -> None:\n    if x is not None:\n        x.b = True\n\ndef g(x: D) -> None:\n    x.c.b = False\n\nclass C:\n    b: bool\n\nclass D:\n    c: C\n[out]\ndef f(x):\n    x :: union[__main__.C, None]\n    r0 :: object\n    r1 :: bit\n    r2 :: __main__.C\n    r3 :: bool\nL0:\n    r0 = load_address _Py_NoneStruct\n    r1 = x != r0\n    if r1 goto L1 else goto L2 :: bool\nL1:\n    r2 = borrow cast(__main__.C, x)\n    r2.b = 1; r3 = is_error\nL2:\n    return 1\ndef g(x):\n    x :: __main__.D\n    r0 :: __main__.C\n    r1 :: bool\nL0:\n    r0 = borrow x.c\n    r0.b = 0; r1 = is_error\n    return 1\n\n[case testBorrowIntEquality]\ndef add(c: C) -> bool:\n    return c.x == c.y\n\nclass C:\n    x: int\n    y: int\n[out]\ndef add(c):\n    c :: __main__.C\n    r0, r1 :: int\n    r2 :: bit\nL0:\n    r0 = borrow c.x\n    r1 = borrow c.y\n    r2 = int_eq r0, r1\n    return r2\n\n[case testBorrowIntLessThan]\ndef add(c: C) -> bool:\n    return c.x < c.y\n\nclass C:\n    x: int\n    y: int\n[out]\ndef add(c):\n    c :: __main__.C\n    r0, r1 :: int\n    r2 :: bit\nL0:\n    r0 = borrow c.x\n    r1 = borrow c.y\n    r2 = int_lt r0, r1\n    return r2\n\n[case testBorrowIntCompareFinal]\nfrom typing import Final\n\nX: Final = 10\n\ndef add(c: C) -> bool:\n    return c.x == X\n\nclass C:\n    x: int\n[out]\ndef add(c):\n    c :: __main__.C\n    r0 :: int\n    r1 :: bit\nL0:\n    r0 = borrow c.x\n    r1 = int_eq r0, 20\n    return r1\n\n[case testBorrowIntArithmetic]\ndef add(c: C) -> int:\n    return c.x + c.y\n\ndef sub(c: C) -> int:\n    return c.x - c.y\n\nclass C:\n    x: int\n    y: int\n[out]\ndef add(c):\n    c :: __main__.C\n    r0, r1, r2 :: int\nL0:\n    r0 = borrow c.x\n    r1 = borrow c.y\n    r2 = CPyTagged_Add(r0, r1)\n    return r2\ndef sub(c):\n    c :: __main__.C\n    r0, r1, r2 :: int\nL0:\n    r0 = borrow c.x\n    r1 = borrow c.y\n    r2 = CPyTagged_Subtract(r0, r1)\n    return r2\n\n[case testBorrowIntComparisonInIf]\ndef add(c: C, n: int) -> bool:\n    if c.x == c.y:\n        return True\n    return False\n\nclass C:\n    x: int\n    y: int\n[out]\ndef add(c, n):\n    c :: __main__.C\n    n, r0, r1 :: int\n    r2 :: bit\nL0:\n    r0 = borrow c.x\n    r1 = borrow c.y\n    r2 = int_eq r0, r1\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    return 1\nL2:\n    return 0\n\n[case testBorrowIntInPlaceOp]\ndef add(c: C, n: int) -> None:\n    c.x += n\n\ndef sub(c: C, n: int) -> None:\n    c.x -= c.y\n\nclass C:\n    x: int\n    y: int\n[out]\ndef add(c, n):\n    c :: __main__.C\n    n, r0, r1 :: int\n    r2 :: bool\nL0:\n    r0 = borrow c.x\n    r1 = CPyTagged_Add(r0, n)\n    c.x = r1; r2 = is_error\n    return 1\ndef sub(c, n):\n    c :: __main__.C\n    n, r0, r1, r2 :: int\n    r3 :: bool\nL0:\n    r0 = borrow c.x\n    r1 = borrow c.y\n    r2 = CPyTagged_Subtract(r0, r1)\n    c.x = r2; r3 = is_error\n    return 1\n\n[case testCoerceIntToI64_64bit]\nfrom mypy_extensions import i64\n\ndef f(x: int) -> i64:\n    # TODO: On the fast path we shouldn't have a decref. Once we have high-level IR,\n    #       coercion from int to i64 can be a single op, which makes it easier to\n    #       generate optimal refcount handling for this case.\n    return x + 1\n[out]\ndef f(x):\n    x, r0 :: int\n    r1 :: native_int\n    r2 :: bit\n    r3, r4 :: i64\n    r5 :: ptr\n    r6 :: c_ptr\n    r7 :: i64\nL0:\n    r0 = CPyTagged_Add(x, 2)\n    r1 = r0 & 1\n    r2 = r1 == 0\n    if r2 goto L1 else goto L2 :: bool\nL1:\n    r3 = r0 >> 1\n    dec_ref r0 :: int\n    r4 = r3\n    goto L3\nL2:\n    r5 = r0 ^ 1\n    r6 = r5\n    r7 = CPyLong_AsInt64(r6)\n    r4 = r7\n    dec_ref r0 :: int\nL3:\n    return r4\n\n[case testVecTSetItem_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[str], i: i64, x: str) -> None:\n    v[i] = x\n[out]\ndef f(v, i, x):\n    v :: vec[str]\n    i :: i64\n    x :: str\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: str\nL0:\n    r0 = v.len\n    r1 = i < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = i + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = i\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecTBufObject\n    r8 = r5 * 8\n    r9 = r7 + r8\n    r10 = borrow load_mem r9 :: builtins.str*\n    dec_ref r10\n    inc_ref x\n    set_mem r9, x :: builtins.str*\n    return 1\n\n[case testVecTConstructFromListMultiply_64bit]\nfrom typing import Optional\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(n: i64) -> vec[Optional[str]]:\n    return vec[Optional[str]]([None] * n)\n[out]\ndef f(n):\n    n :: i64\n    r0, r1 :: object\n    r2, r3 :: ptr\n    r4 :: vec[str | None]\n    r5 :: object\n    r6 :: ptr\n    r7 :: i64\n    r8, r9 :: ptr\n    r10 :: bit\n    r11 :: ptr\nL0:\n    r0 = box(None, 1)\n    r1 = load_address PyUnicode_Type\n    r2 = r1\n    r3 = r2 | 1\n    r4 = VecTApi.alloc(n, n, r3)\n    r5 = r4.buf\n    r6 = get_element_ptr r5 items :: VecTBufObject\n    r7 = n * 8\n    r8 = r6 + r7\n    r9 = r6\nL1:\n    r10 = r9 < r8 :: unsigned\n    if r10 goto L2 else goto L3 :: bool\nL2:\n    inc_ref r0\n    set_mem r9, r0 :: union*\n    r11 = r9 + 8\n    r9 = r11\n    goto L1\nL3:\n    return r4\n\n[case testVecTForLoop_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[str]) -> i64:\n    t: i64 = 0\n    for s in v:\n        g(s)\n    return t\n\ndef g(s: str) -> None: pass\n[out]\ndef f(v):\n    v :: vec[str]\n    t :: i64\n    r0, r1 :: native_int\n    r2 :: bit\n    r3 :: object\n    r4 :: ptr\n    r5 :: native_int\n    r6 :: ptr\n    r7, s :: str\n    r8 :: None\n    r9 :: native_int\nL0:\n    t = 0\n    r0 = 0\nL1:\n    r1 = v.len\n    r2 = r0 < r1 :: signed\n    if r2 goto L2 else goto L4 :: bool\nL2:\n    r3 = v.buf\n    r4 = get_element_ptr r3 items :: VecTBufObject\n    r5 = r0 * 8\n    r6 = r4 + r5\n    r7 = load_mem r6 :: builtins.str*\n    s = r7\n    r8 = g(s)\n    dec_ref s\nL3:\n    r9 = r0 + 1\n    r0 = r9\n    goto L1\nL4:\n    return t\ndef g(s):\n    s :: str\nL0:\n    return 1\n\n[case testVecTConstructFromListExpr_64bit]\nfrom librt.vecs import vec\n\ndef f() -> vec[str]:\n    return vec[str](['x', 'y'])\n[out]\ndef f():\n    r0, r1 :: str\n    r2 :: object\n    r3 :: ptr\n    r4 :: vec[str]\n    r5 :: object\n    r6, r7, r8 :: ptr\nL0:\n    r0 = 'x'\n    r1 = 'y'\n    r2 = load_address PyUnicode_Type\n    r3 = r2\n    r4 = VecTApi.alloc(2, 2, r3)\n    r5 = r4.buf\n    r6 = get_element_ptr r5 items :: VecTBufObject\n    inc_ref r0\n    set_mem r6, r0 :: builtins.str*\n    r7 = r6 + 8\n    inc_ref r1\n    set_mem r7, r1 :: builtins.str*\n    r8 = r7 + 8\n    return r4\n\n[case testVecI64GetItemBorrowVec_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\nclass C:\n    v: vec[i64]\n\n    def f(self, x: i64) -> i64:\n        return self.v[x]\n[out]\ndef C.f(self, x):\n    self :: __main__.C\n    x :: i64\n    r0 :: vec[i64]\n    r1 :: native_int\n    r2 :: bit\n    r3 :: i64\n    r4 :: bit\n    r5 :: bool\n    r6 :: i64\n    r7 :: object\n    r8 :: ptr\n    r9 :: i64\n    r10 :: ptr\n    r11 :: i64\nL0:\n    r0 = borrow self.v\n    r1 = r0.len\n    r2 = x < r1 :: unsigned\n    if r2 goto L4 else goto L1 :: bool\nL1:\n    r3 = x + r1\n    r4 = r3 < r1 :: unsigned\n    if r4 goto L3 else goto L2 :: bool\nL2:\n    r5 = raise IndexError\n    unreachable\nL3:\n    r6 = r3\n    goto L5\nL4:\n    r6 = x\nL5:\n    r7 = r0.buf\n    r8 = get_element_ptr r7 items :: VecI64BufObject\n    r9 = r6 * 8\n    r10 = r8 + r9\n    r11 = load_mem r10 :: i64*\n    return r11\n\n[case testVecI64LenBorrowVec_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\nclass C:\n    v: vec[i64]\n\n    def f(self, x: i64) -> i64:\n        return len(self.v)\n[out]\ndef C.f(self, x):\n    self :: __main__.C\n    x :: i64\n    r0 :: vec[i64]\n    r1 :: native_int\nL0:\n    r0 = borrow self.v\n    r1 = r0.len\n    return r1\n\n[case testVecNestedAppend]\nfrom librt.vecs import vec, append\n\ndef f(vv: vec[vec[str]], v: vec[str]) -> vec[vec[str]]:\n    return append(vv, v)\n[out]\ndef f(vv, v):\n    vv :: vec[vec[str]]\n    v :: vec[str]\n    r0 :: native_int\n    r1 :: object\n    r2, r3 :: VecNestedBufItem{len:native_int, buf:object_nrc}\n    r4 :: vec[vec[str]]\nL0:\n    r0 = v.len\n    r1 = v.buf\n    r2 = set_element undef VecNestedBufItem, len, r0\n    r3 = set_element r2, buf, r1\n    inc_ref vv\n    r4 = VecNestedApi.append(vv, r3)\n    return r4\n\n[case testVecTGetItem_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[str], n: i64) -> str:\n    return v[n]\n[out]\ndef f(v, n):\n    v :: vec[str]\n    n :: i64\n    r0 :: native_int\n    r1 :: bit\n    r2 :: i64\n    r3 :: bit\n    r4 :: bool\n    r5 :: i64\n    r6 :: object\n    r7 :: ptr\n    r8 :: i64\n    r9 :: ptr\n    r10 :: str\nL0:\n    r0 = v.len\n    r1 = n < r0 :: unsigned\n    if r1 goto L4 else goto L1 :: bool\nL1:\n    r2 = n + r0\n    r3 = r2 < r0 :: unsigned\n    if r3 goto L3 else goto L2 :: bool\nL2:\n    r4 = raise IndexError\n    unreachable\nL3:\n    r5 = r2\n    goto L5\nL4:\n    r5 = n\nL5:\n    r6 = v.buf\n    r7 = get_element_ptr r6 items :: VecTBufObject\n    r8 = r5 * 8\n    r9 = r7 + r8\n    r10 = load_mem r9 :: builtins.str*\n    return r10\n\n[case testVecNestedGetItem_64bit]\nfrom librt.vecs import vec\nfrom mypy_extensions import i64\n\ndef f(v: vec[vec[str]], n: i64) -> None:\n    vv = vec[vec[str]]()[n]\n[out]\ndef f(v, n):\n    v :: vec[vec[str]]\n    n :: i64\n    r0 :: object\n    r1 :: ptr\n    r2 :: vec[vec[str]]\n    r3 :: native_int\n    r4 :: bit\n    r5 :: i64\n    r6 :: bit\n    r7 :: bool\n    r8 :: i64\n    r9 :: object\n    r10 :: ptr\n    r11 :: i64\n    r12 :: ptr\n    r13, vv :: vec[str]\nL0:\n    r0 = load_address PyUnicode_Type\n    r1 = r0\n    r2 = VecNestedApi.alloc(0, 0, r1, 1)\n    r3 = r2.len\n    r4 = n < r3 :: unsigned\n    if r4 goto L4 else goto L1 :: bool\nL1:\n    r5 = n + r3\n    r6 = r5 < r3 :: unsigned\n    if r6 goto L3 else goto L6 :: bool\nL2:\n    r7 = raise IndexError\n    unreachable\nL3:\n    r8 = r5\n    goto L5\nL4:\n    r8 = n\nL5:\n    r9 = r2.buf\n    r10 = get_element_ptr r9 items :: VecNestedBufObject\n    r11 = r8 * 16\n    r12 = r10 + r11\n    r13 = load_mem r12 :: vec[str]*\n    dec_ref r2\n    vv = r13\n    dec_ref vv\n    return 1\nL6:\n    dec_ref r2\n    goto L2\n\n[case testVecPop]\nfrom librt.vecs import vec, pop, append\nfrom mypy_extensions import i64\n\ndef f() -> vec[i64]:\n    v = vec[i64]()\n    v = append(v, 7)\n    v, x = pop(v)\n    return v\n[out]\ndef f():\n    r0, v, r1 :: vec[i64]\n    r2 :: tuple[vec[i64], i64]\n    r3 :: vec[i64]\n    r4 :: i64\n    r5 :: vec[i64]\n    r6, x :: i64\nL0:\n    r0 = VecI64Api.alloc(0, 0)\n    v = r0\n    r1 = VecI64Api.append(v, 7)\n    v = r1\n    r2 = VecI64Api.pop(v, -1)\n    r3 = borrow r2[0]\n    r4 = borrow r2[1]\n    r5 = unborrow r3\n    v = r5\n    r6 = unborrow r4\n    x = r6\n    return v\n\n[case testVecNestedPop]\nfrom librt.vecs import vec, pop\n\ndef f(v: vec[vec[str]]) -> vec[str]:\n    vv, x = pop(v)\n    return x\n[out]\ndef f(v):\n    v :: vec[vec[str]]\n    r0 :: tuple[vec[vec[str]], VecNestedBufItem{len:native_int, buf:object_nrc}]\n    r1, r2 :: vec[vec[str]]\n    r3, r4 :: VecNestedBufItem{len:native_int, buf:object_nrc}\n    r5 :: vec[str]\n    r6 :: tuple[vec[vec[str]], vec[str]]\n    r7 :: vec[vec[str]]\n    r8 :: vec[str]\n    r9, vv :: vec[vec[str]]\n    r10, x :: vec[str]\nL0:\n    inc_ref v\n    r0 = VecNestedApi.pop(v, -1)\n    r1 = borrow r0[0]\n    r2 = unborrow r1\n    r3 = borrow r0[1]\n    r4 = unborrow r3\n    r5 = VecTApi.convert_from_nested(r4)\n    r6 = (r2, r5)\n    r7 = borrow r6[0]\n    r8 = borrow r6[1]\n    r9 = unborrow r7\n    vv = r9\n    dec_ref vv\n    r10 = unborrow r8\n    x = r10\n    return x\n"
  },
  {
    "path": "mypyc/test-data/run-async.test",
    "content": "# async test cases (compile and run)\n\n[case testRunAsyncBasics]\nimport asyncio\nfrom typing import Callable, Awaitable\n\nfrom testutil import assertRaises\n\nasync def h() -> int:\n    return 1\n\nasync def g() -> int:\n    await asyncio.sleep(0)\n    return await h()\n\nasync def f() -> int:\n    return await g() + 2\n\nasync def f2() -> int:\n    x = 0\n    for i in range(2):\n        x += i + await f() + await g()\n    return x\n\nasync def test_simple_call() -> None:\n    result = await f()\n    assert result == 3\n\nasync def test_multiple_awaits_in_expression() -> None:\n    result = await f2()\n    assert result == 9\n\nclass MyError(Exception):\n    pass\n\nasync def exc1() -> None:\n    await asyncio.sleep(0)\n    raise MyError()\n\nasync def exc2() -> None:\n    await asyncio.sleep(0)\n    raise MyError()\n\nasync def exc3() -> None:\n    await exc1()\n\nasync def exc4() -> None:\n    await exc2()\n\nasync def exc5() -> int:\n    try:\n        await exc1()\n    except MyError:\n        return 3\n    return 4\n\nasync def exc6() -> int:\n    try:\n        await exc4()\n    except MyError:\n        return 3\n    return 4\n\nasync def test_exception() -> None:\n    with assertRaises(MyError):\n        await exc1()\n    with assertRaises(MyError):\n        await exc2()\n    with assertRaises(MyError):\n        await exc3()\n    with assertRaises(MyError):\n        await exc4()\n    assert await exc5() == 3\n    assert await exc6() == 3\n\nasync def indirect_call(x: int, c: Callable[[int], Awaitable[int]]) -> int:\n    return await c(x)\n\nasync def indirect_call_2(a: Awaitable[None]) -> None:\n    await a\n\nasync def indirect_call_3(a: Awaitable[float]) -> float:\n    return (await a) + 1.0\n\nasync def inc(x: int) -> int:\n    await asyncio.sleep(0)\n    return x + 1\n\nasync def ident(x: float, err: bool = False) -> float:\n    await asyncio.sleep(0.0)\n    if err:\n        raise MyError()\n    return x + float(\"0.0\")\n\nasync def test_indirect_call() -> None:\n    assert await indirect_call(3, inc) == 4\n\n    with assertRaises(MyError):\n        await indirect_call_2(exc1())\n\n    assert await indirect_call_3(ident(2.0)) == 3.0\n    assert await indirect_call_3(ident(-113.0)) == -112.0\n    assert await indirect_call_3(ident(-114.0)) == -113.0\n\n    with assertRaises(MyError):\n        await indirect_call_3(ident(1.0, True))\n    with assertRaises(MyError):\n        await indirect_call_3(ident(-113.0, True))\n\nclass C:\n    def __init__(self, n: int) -> None:\n        self.n = n\n\n    async def add(self, x: int, err: bool = False) -> int:\n        await asyncio.sleep(0)\n        if err:\n            raise MyError()\n        return x + self.n\n\nasync def method_call(x: int) -> int:\n    c = C(5)\n    return await c.add(x)\n\nasync def method_call_exception() -> int:\n    c = C(5)\n    return await c.add(3, err=True)\n\nasync def test_async_method_call() -> None:\n    assert await method_call(3) == 8\n    with assertRaises(MyError):\n        await method_call_exception()\n\n[file asyncio/__init__.pyi]\nasync def sleep(t: float) -> None: ...\n\n[typing fixtures/typing-full.pyi]\n\n[case testRunAsyncAwaitInVariousPositions]\nfrom typing import cast, Any\n\nimport asyncio\n\nasync def one() -> int:\n    await asyncio.sleep(0.0)\n    return int() + 1\n\nasync def true() -> bool:\n    return bool(int() + await one())\n\nasync def branch_await() -> int:\n    if bool(int() + 1) == await true():\n        return 3\n    return 2\n\nasync def branch_await_not() -> int:\n    if bool(int() + 1) == (not await true()):\n        return 3\n    return 2\n\nasync def test_branch() -> None:\n    assert await branch_await() == 3\n    assert await branch_await_not() == 2\n\nasync def assign_multi() -> int:\n    _, x = int(), await one()\n    return x + 1\n\nasync def test_assign_multi() -> None:\n    assert await assign_multi() == 2\n\nclass C:\n    def __init__(self, s: str) -> None:\n        self.s = s\n\n    def concat(self, s: str) -> str:\n        return self.s + s\n\nasync def make_c(s: str) -> C:\n    await one()\n    return C(s)\n\nasync def concat(s: str, t: str) -> str:\n    await one()\n    return s + t\n\nasync def set_attr(s: str) -> None:\n    (await make_c(\"xyz\")).s = await concat(s, \"!\")\n\nasync def test_set_attr() -> None:\n    await set_attr(\"foo\")  # Just check that it compiles and runs\n\ndef concat2(x: str, y: str) -> str:\n    return x + y\n\nasync def call1(s: str) -> str:\n    return concat2(str(int()), await concat(s, \"a\"))\n\nasync def call2(s: str) -> str:\n    return await concat(str(int()), await concat(s, \"b\"))\n\nasync def test_call() -> None:\n    assert await call1(\"foo\") == \"0fooa\"\n    assert await call2(\"foo\") == \"0foob\"\n\nasync def method_call(s: str) -> str:\n    return C(\"<\").concat(await concat(s, \">\"))\n\nasync def test_method_call() -> None:\n    assert await method_call(\"foo\") == \"<foo>\"\n\nclass D:\n    def __init__(self, a: str, b: str) -> None:\n        self.a = a\n        self.b = b\n\nasync def construct(s: str) -> str:\n    c = D(await concat(s, \"!\"), await concat(s, \"?\"))\n    return c.a + c.b\n\nasync def test_construct() -> None:\n    assert await construct(\"foo\") == \"foo!foo?\"\n\n[file asyncio/__init__.pyi]\nasync def sleep(t: float) -> None: ...\n\n[typing fixtures/typing-full.pyi]\n\n\n[case testAsyncWith]\nfrom testutil import async_val\nfrom typing import Any\n\nclass async_ctx:\n    async def __aenter__(self) -> str:\n        await async_val(\"enter\")\n        return \"test\"\n\n    async def __aexit__(self, x, y, z) -> None:\n        await async_val(\"exit\")\n\n\nasync def async_with() -> str:\n    async with async_ctx() as x:\n        return await async_val(\"body\")\n\nasync def async_with_vectorcall() -> str:\n    ctx: Any = async_ctx()\n    async with ctx:\n        return await async_val(\"vc\")\n\n[file driver.py]\nfrom native import async_with, async_with_vectorcall\nfrom testutil import run_generator\n\nyields, val = run_generator(async_with(), [None, 'x', None])\nassert yields == ('enter', 'body', 'exit'), yields\nassert val == 'x', val\n\nyields, val = run_generator(async_with_vectorcall(), [None, 'x', None])\nassert yields == ('enter', 'vc', 'exit'), yields\nassert val == 'x', val\n\n[case testAsyncReturn]\nfrom testutil import async_val\n\nasync def async_return() -> str:\n    try:\n        return 'test'\n    finally:\n        await async_val('foo')\n\n[file driver.py]\nfrom native import async_return\nfrom testutil import run_generator\n\nyields, val = run_generator(async_return())\nassert yields == ('foo',)\nassert val == 'test', val\n\n[case testAsyncFor]\nfrom typing import AsyncIterable, List, Set, Dict\n\nasync def async_iter(xs: AsyncIterable[int]) -> List[int]:\n    ys = []\n    async for x in xs:\n        ys.append(x)\n    return ys\n\nasync def async_comp(xs: AsyncIterable[int]) -> List[int]:\n    ys = [x async for x in xs]\n    return ys\n\nasync def async_comp_set(xs: AsyncIterable[int]) -> Set[int]:\n    return {x async for x in xs}\n\nasync def async_comp_dict(xs: AsyncIterable[int]) -> Dict[int, str]:\n    return {x: str(x) async for x in xs}\n\n[typing fixtures/typing-full.pyi]\n\n[file driver.py]\nfrom native import async_iter, async_comp, async_comp_set, async_comp_dict\nfrom testutil import run_generator, async_val\nfrom typing import AsyncIterable, List\n\n# defined here since we couldn't do it inside the test yet...\nasync def foo() -> AsyncIterable[int]:\n    for x in range(3):\n        await async_val(x)\n        yield x\n\nyields, val = run_generator(async_iter(foo()))\nassert val == [0,1,2], val\nassert yields == (0,1,2), yields\n\nyields, val = run_generator(async_comp(foo()))\nassert val == [0,1,2], val\nassert yields == (0,1,2), yields\n\nyields, val = run_generator(async_comp_set(foo()))\nassert val == {0,1,2}, val\nassert yields == (0,1,2), yields\n\nyields, val = run_generator(async_comp_dict(foo()))\nassert val == {0: '0',1: '1', 2: '2'}, val\nassert yields == (0,1,2), yields\n\n[case testAsyncFor2]\nfrom typing import AsyncIterable, List\n\nasync def async_iter(xs: AsyncIterable[int]) -> List[int]:\n    ys = []\n    async for x in xs:\n        ys.append(x)\n    return ys\n\n[typing fixtures/typing-full.pyi]\n\n[file driver.py]\nfrom native import async_iter\nfrom testutil import run_generator, async_val\nfrom typing import AsyncIterable, List\n\n# defined here since we couldn't do it inside the test yet...\nasync def foo() -> AsyncIterable[int]:\n    for x in range(3):\n        await async_val(x)\n        yield x\n    raise Exception('lol no')\n\nyields, val = run_generator(async_iter(foo()))\nassert yields == (0,1,2), yields\nassert val == 'lol no', val\n\n[case testAsyncWithVarReuse]\nclass ConMan:\n    async def __aenter__(self) -> int:\n        return 1\n    async def __aexit__(self, *exc: object):\n        pass\n\nclass ConManB:\n    async def __aenter__(self) -> int:\n        return 2\n    async def __aexit__(self, *exc: object):\n        pass\n\nasync def test_x() -> None:\n    value = 2\n    async with ConMan() as f:\n        value += f\n    assert value == 3, value\n    async with ConManB() as f:\n        value += f\n    assert value == 5, value\n\n[case testRunAsyncSpecialCases]\nimport asyncio\n\nasync def t() -> tuple[int, str, str]:\n    return (1, \"x\", \"y\")\n\nasync def f() -> tuple[int, str, str]:\n    return await t()\n\nasync def test_tuple_return() -> None:\n    result = await f()\n    assert result == (1, \"x\", \"y\")\n\nasync def e() -> ValueError:\n    return ValueError(\"foo\")\n\nasync def g() -> ValueError:\n    return await e()\n\nasync def test_exception_return() -> None:\n    result = await g()\n    assert isinstance(result, ValueError)\n\n[file asyncio/__init__.pyi]\nasync def sleep(t: float) -> None: ...\n\n[typing fixtures/typing-full.pyi]\n\n[case testRunAsyncRefCounting]\nimport asyncio\nimport gc\nimport platform\n\nasync def sleep() -> None:\n    # Non-zero value hangs on Windows.\n    time = 0 if platform.system() == \"Windows\" else 0.0001\n    await asyncio.sleep(time)\n\nasync def assert_no_leaks(fn, max_new):\n    # Warm-up, in case asyncio allocates something on first use\n    await fn()\n\n    gc.collect()\n    old_objs = gc.get_objects()\n\n    for i in range(10):\n        await fn()\n\n    gc.collect()\n    new_objs = gc.get_objects()\n\n    delta = len(new_objs) - len(old_objs)\n    # Often a few persistent objects get allocated, which may be unavoidable.\n    # The main thing we care about is that each iteration does not leak an\n    # additional object.\n    assert delta <= max_new, delta\n\nasync def concat_one(x: str) -> str:\n    return x + \"1\"\n\nasync def foo(n: int) -> str:\n    s = \"\"\n    while len(s) < n:\n        s = await concat_one(s)\n    return s\n\nasync def test_trivial() -> None:\n    await assert_no_leaks(lambda: foo(1000), 5)\n\nasync def make_list(a: list[int]) -> list[int]:\n    await concat_one(\"foobar\")\n    return [a[0]]\n\nasync def spill() -> list[int]:\n    a: list[int] = []\n    for i in range(5):\n        await sleep()\n        a = (await make_list(a + [1])) + a + (await make_list(a + [2]))\n    return a\n\nasync def bar(n: int) -> None:\n    for i in range(n):\n        await spill()\n\nasync def test_spilled() -> None:\n    await assert_no_leaks(lambda: bar(80), 13)\n\nasync def raise_deep(n: int) -> str:\n    if n == 0:\n        await sleep()\n        raise TypeError(str(n))\n    else:\n        if n == 2:\n            await sleep()\n        return await raise_deep(n - 1)\n\nasync def maybe_raise(n: int) -> str:\n    if n % 3 == 0:\n        await raise_deep(5)\n    elif n % 29 == 0:\n        await sleep()\n    return str(n)\n\nasync def exc(n: int) -> list[str]:\n    a = []\n    for i in range(n):\n        try:\n            a.append(str(int()) + await maybe_raise(n))\n        except TypeError:\n            a.append(str(int() + 5))\n    return a\n\nasync def test_exception() -> None:\n    await assert_no_leaks(lambda: exc(50), 2)\n\nclass C:\n    def __init__(self, s: str) -> None:\n        self.s = s\n\nasync def id(c: C) -> C:\n    return c\n\nasync def stolen_helper(c: C, s: str) -> str:\n    await sleep()\n    (await id(c)).s = await concat_one(s)\n    await sleep()\n    return c.s\n\nasync def stolen(n: int) -> int:\n    for i in range(n):\n        c = C(str(i))\n        s = await stolen_helper(c, str(i + 2))\n        assert s == str(i + 2) + \"1\"\n    return n\n\nasync def test_stolen() -> None:\n    await assert_no_leaks(lambda: stolen(200), 16)\n\n[file asyncio/__init__.pyi]\nasync def sleep(t: float) -> None: ...\n\n[case testRunAsyncMiscTypesInEnvironment]\n# Here we test that values of various kinds of types can be spilled to the\n# environment. In particular, types with \"overlapping error values\" such as\n# i64 can be tricky, since they require extra work to support undefined\n# attribute values (which raise AttributeError when accessed). For these,\n# the object struct has a bitfield which keeps track of whether certain\n# attributes have an assigned value.\n#\n# In practice we mark these attributes as \"always defined\", which causes these\n# checks to be skipped on attribute access, and thus we don't require the\n# bitfield to exist.\n#\n# See the comment of RType.error_overlap for more information.\n\nimport asyncio\n\nfrom mypy_extensions import i64, i32, i16, u8\n\nasync def inc_float(x: float) -> float:\n    return x + 1.0\n\nasync def inc_i64(x: i64) -> i64:\n    return x + 1\n\nasync def inc_i32(x: i32) -> i32:\n    return x + 1\n\nasync def inc_i16(x: i16) -> i16:\n    return x + 1\n\nasync def inc_u8(x: u8) -> u8:\n    return x + 1\n\nasync def inc_tuple(x: tuple[i64, float]) -> tuple[i64, float]:\n    return x[0] + 1, x[1] + 1.5\n\nasync def neg_bool(b: bool) -> bool:\n    return not b\n\nasync def float_ops(x: float) -> float:\n    n = x\n    n = await inc_float(n)\n    n = float(\"0.5\") + await inc_float(n)\n    return n\n\nasync def test_float() -> None:\n    assert await float_ops(2.5) == 5.0\n\nasync def i64_ops(x: i64) -> i64:\n    n = x\n    n = await inc_i64(n)\n    n = i64(\"1\") + await inc_i64(n)\n    return n\n\nasync def test_i64() -> None:\n    assert await i64_ops(2) == 5\n\nasync def i32_ops(x: i32) -> i32:\n    n = x\n    n = await inc_i32(n)\n    n = i32(\"1\") + await inc_i32(n)\n    return n\n\nasync def test_i32() -> None:\n    assert await i32_ops(3) == 6\n\nasync def i16_ops(x: i16) -> i16:\n    n = x\n    n = await inc_i16(n)\n    n = i16(\"1\") + await inc_i16(n)\n    return n\n\nasync def test_i16() -> None:\n    assert await i16_ops(4) == 7\n\nasync def u8_ops(x: u8) -> u8:\n    n = x\n    n = await inc_u8(n)\n    n = u8(\"1\") + await inc_u8(n)\n    return n\n\nasync def test_u8() -> None:\n    assert await u8_ops(5) == 8\n\nasync def tuple_ops(x: tuple[i64, float]) -> tuple[i64, float]:\n    n = x\n    n = await inc_tuple(n)\n    m = ((i64(\"1\"), float(\"0.5\")), await inc_tuple(n))\n    return m[1]\n\nasync def test_tuple() -> None:\n    assert await tuple_ops((1, 2.5)) == (3, 5.5)\n\nasync def bool_ops(x: bool) -> bool:\n    n = x\n    n = await neg_bool(n)\n    m = (bool(\"1\"), await neg_bool(n))\n    return m[0] and m[1]\n\nasync def test_bool() -> None:\n    assert await bool_ops(True) is True\n    assert await bool_ops(False) is False\n\n[file asyncio/__init__.pyi]\ndef run(x: object) -> object: ...\n\n[case testRunAsyncNestedFunctions]\nfrom __future__ import annotations\n\nimport asyncio\nfrom typing import cast, Iterator, overload, Awaitable, Any, TypeVar\n\nfrom testutil import assertRaises\n\ndef normal_contains_async_def(x: int) -> int:\n    async def f(y: int) -> int:\n        return x + y\n\n    return 5 + cast(int, asyncio.run(f(6)))\n\ndef test_def_contains_async_def() -> None:\n    assert normal_contains_async_def(3) == 14\n\nasync def inc(x: int) -> int:\n    return x + 1\n\nasync def async_def_contains_normal(x: int) -> int:\n    def nested(y: int, z: int) -> int:\n        return x + y + z\n\n    a = x\n    a += nested((await inc(3)), (await inc(4)))\n    return a\n\nasync def test_async_def_contains_normal() -> None:\n    assert await async_def_contains_normal(2) == (2 + 2 + 4 + 5)\n\nasync def async_def_contains_async_def(x: int) -> int:\n    async def f(y: int) -> int:\n        return (await inc(x)) + (await inc(y))\n\n    return (await f(1)) + (await f(2))\n\nasync def test_async_def_contains_async_def() -> None:\n    assert await async_def_contains_async_def(3) == (3 + 1 + 1 + 1) + (3 + 1 + 2 + 1)\n\nasync def async_def_contains_generator(x: int) -> tuple[int, int, int]:\n    def gen(y: int) -> Iterator[int]:\n        yield x + 1\n        yield x + y\n\n    it = gen(4)\n    res = x + 10, next(it), next(it)\n\n    with assertRaises(StopIteration):\n        next(it)\n\n    return res\n\nasync def test_async_def_contains_generator() -> None:\n    assert await async_def_contains_generator(3) == (13, 4, 7)\n\ndef generator_contains_async_def(x: int) -> Iterator[int]:\n    async def f(y: int) -> int:\n        return (await inc(x)) + (await inc(y))\n\n    yield cast(int, asyncio.run(f(2)))\n    yield cast(int, asyncio.run(f(3)))\n    yield x + 10\n\ndef test_generator_contains_async_def() -> None:\n    assert list(generator_contains_async_def(5)) == [6 + 3, 6 + 4, 15]\n\nasync def async_def_contains_two_nested_functions(x: int, y: int) -> tuple[int, int]:\n    def f(a: int) -> int:\n        return x + a\n\n    def g(b: int, c: int) -> int:\n        return y + b + c\n\n    return (await inc(f(3))), (await inc(g(4, 10)))\n\nasync def test_async_def_contains_two_nested_functions() -> None:\n    assert await async_def_contains_two_nested_functions(5, 7) == (\n        (5 + 3 + 1), (7 + 4 + 10 + 1)\n    )\n\nasync def async_def_contains_overloaded_async_def(n: int) -> int:\n    @overload\n    async def f(x: int) -> int: ...\n\n    @overload\n    async def f(x: str) -> str: ...\n\n    async def f(x: int | str) -> Any:\n        return x\n\n    return (await f(n)) + 1\n\n\nasync def test_async_def_contains_overloaded_async_def() -> None:\n    assert await async_def_contains_overloaded_async_def(5) == 6\n\nT = TypeVar(\"T\")\n\ndef deco(f: T) -> T:\n    return f\n\nasync def async_def_contains_decorated_async_def(n: int) -> int:\n    @deco\n    async def f(x: int) -> int:\n        return x + 2\n\n    return (await f(n)) + 1\n\n\nasync def test_async_def_contains_decorated_async_def() -> None:\n    assert await async_def_contains_decorated_async_def(7) == 10\n\n[file asyncio/__init__.pyi]\ndef run(x: object) -> object: ...\n\n[case testAsyncTryFinallyMixedReturn]\n# This used to raise an AttributeError, when:\n# - the try block contains multiple paths\n# - at least one of those explicitly returns\n# - at least one of those does not explicitly return\n# - the non-returning path is taken at runtime\n\nasync def mixed_return(b: bool) -> bool:\n  try:\n      if b:\n          return b\n  finally:\n      pass\n  return b\n\n\nasync def test_async_try_finally_mixed_return() -> None:\n  # Test return path\n  result1 = await mixed_return(True)\n  assert result1 == True\n\n  # Test non-return path\n  result2 = await mixed_return(False)\n  assert result2 == False\n\n[case testAsyncWithMixedReturn]\n# This used to raise an AttributeError, related to\n# testAsyncTryFinallyMixedReturn, this is essentially\n# a far more extensive version of that test surfacing\n# more edge cases\n\nfrom typing import Optional, Type, Literal\n\n\nclass AsyncContextManager:\n    async def __aenter__(self) -> \"AsyncContextManager\":\n        return self\n\n    async def __aexit__(\n        self,\n        t: Optional[Type[BaseException]],\n        v: Optional[BaseException],\n        tb: object,\n    ) -> Literal[False]:\n        return False\n\n\n# Simple async functions (generator class)\nasync def gen_1(b: bool) -> bool:\n    async with AsyncContextManager():\n        if b:\n            return b\n    return b\n\n\nasync def gen_2(b: bool) -> bool:\n    async with AsyncContextManager():\n        if b:\n            return b\n        else:\n            return b\n\n\nasync def gen_3(b: bool) -> bool:\n    async with AsyncContextManager():\n        if b:\n            return b\n        else:\n            pass\n    return b\n\n\nasync def gen_4(b: bool) -> bool:\n    ret: bool\n    async with AsyncContextManager():\n        if b:\n            ret = b\n        else:\n            ret = b\n    return ret\n\n\nasync def gen_5(i: int) -> int:\n    async with AsyncContextManager():\n        if i == 1:\n            return i\n        elif i == 2:\n            pass\n        elif i == 3:\n            return i\n    return i\n\n\nasync def gen_6(i: int) -> int:\n    async with AsyncContextManager():\n        if i == 1:\n            return i\n        elif i == 2:\n            return i\n        elif i == 3:\n            return i\n    return i\n\n\nasync def gen_7(i: int) -> int:\n    async with AsyncContextManager():\n        if i == 1:\n            return i\n        elif i == 2:\n            return i\n        elif i == 3:\n            return i\n        else:\n            return i\n\n\n# Async functions with nested functions (environment class)\nasync def env_1(b: bool) -> bool:\n    def helper() -> bool:\n        return True\n\n    async with AsyncContextManager():\n        if b:\n            return helper()\n    return b\n\n\nasync def env_2(b: bool) -> bool:\n    def helper() -> bool:\n        return True\n\n    async with AsyncContextManager():\n        if b:\n            return helper()\n        else:\n            return b\n\n\nasync def env_3(b: bool) -> bool:\n    def helper() -> bool:\n        return True\n\n    async with AsyncContextManager():\n        if b:\n            return helper()\n        else:\n            pass\n    return b\n\n\nasync def env_4(b: bool) -> bool:\n    def helper() -> bool:\n        return True\n\n    ret: bool\n    async with AsyncContextManager():\n        if b:\n            ret = helper()\n        else:\n            ret = b\n    return ret\n\n\nasync def env_5(i: int) -> int:\n    def helper() -> int:\n        return 1\n\n    async with AsyncContextManager():\n        if i == 1:\n            return helper()\n        elif i == 2:\n            pass\n        elif i == 3:\n            return i\n    return i\n\n\nasync def env_6(i: int) -> int:\n    def helper() -> int:\n        return 1\n\n    async with AsyncContextManager():\n        if i == 1:\n            return helper()\n        elif i == 2:\n            return i\n        elif i == 3:\n            return i\n    return i\n\n\nasync def env_7(i: int) -> int:\n    def helper() -> int:\n        return 1\n\n    async with AsyncContextManager():\n        if i == 1:\n            return helper()\n        elif i == 2:\n            return i\n        elif i == 3:\n            return i\n        else:\n            return i\n\n\nasync def test_async_with_mixed_return() -> None:\n    # Test simple async functions (generator class)\n    # env_1: mixed return/no-return\n    assert await gen_1(True) is True\n    assert await gen_1(False) is False\n\n    # gen_2: all branches return\n    assert await gen_2(True) is True\n    assert await gen_2(False) is False\n\n    # gen_3: mixed return/pass\n    assert await gen_3(True) is True\n    assert await gen_3(False) is False\n\n    # gen_4: no returns in async with\n    assert await gen_4(True) is True\n    assert await gen_4(False) is False\n\n    # gen_5: multiple branches, some return\n    assert await gen_5(0) == 0\n    assert await gen_5(1) == 1\n    assert await gen_5(2) == 2\n    assert await gen_5(3) == 3\n\n    # gen_6: all explicit branches return, implicit fallthrough\n    assert await gen_6(0) == 0\n    assert await gen_6(1) == 1\n    assert await gen_6(2) == 2\n    assert await gen_6(3) == 3\n\n    # gen_7: all branches return including else\n    assert await gen_7(0) == 0\n    assert await gen_7(1) == 1\n    assert await gen_7(2) == 2\n    assert await gen_7(3) == 3\n\n    # Test async functions with nested functions (environment class)\n    # env_1: mixed return/no-return\n    assert await env_1(True) is True\n    assert await env_1(False) is False\n\n    # env_2: all branches return\n    assert await env_2(True) is True\n    assert await env_2(False) is False\n\n    # env_3: mixed return/pass\n    assert await env_3(True) is True\n    assert await env_3(False) is False\n\n    # env_4: no returns in async with\n    assert await env_4(True) is True\n    assert await env_4(False) is False\n\n    # env_5: multiple branches, some return\n    assert await env_5(0) == 0\n    assert await env_5(1) == 1\n    assert await env_5(2) == 2\n    assert await env_5(3) == 3\n\n    # env_6: all explicit branches return, implicit fallthrough\n    assert await env_6(0) == 0\n    assert await env_6(1) == 1\n    assert await env_6(2) == 2\n    assert await env_6(3) == 3\n\n    # env_7: all branches return including else\n    assert await env_7(0) == 0\n    assert await env_7(1) == 1\n    assert await env_7(2) == 2\n    assert await env_7(3) == 3\n\n[case testAsyncTryExceptFinallyAwait]\nimport asyncio\nfrom testutil import assertRaises\n\nclass TestError(Exception):\n    pass\n\n# Test 0: Simplest case - just try/finally with raise and await\nasync def simple_try_finally_await() -> None:\n    try:\n        raise ValueError(\"simple error\")\n    finally:\n        await asyncio.sleep(0)\n\n# Test 1: Raise inside try, catch in except, don't re-raise\nasync def async_try_except_no_reraise() -> int:\n    try:\n        raise ValueError(\"test error\")\n        return 1  # Never reached\n    except ValueError:\n        return 2  # Should return this\n    finally:\n        await asyncio.sleep(0)\n    return 3  # Should not reach this\n\n# Test 2: Raise inside try, catch in except, re-raise\nasync def async_try_except_reraise() -> int:\n    try:\n        raise ValueError(\"test error\")\n        return 1  # Never reached\n    except ValueError:\n        raise  # Re-raise the exception\n    finally:\n        await asyncio.sleep(0)\n    return 2  # Should not reach this\n\n# Test 3: Raise inside try, catch in except, raise different error\nasync def async_try_except_raise_different() -> int:\n    try:\n        raise ValueError(\"original error\")\n        return 1  # Never reached\n    except ValueError:\n        raise RuntimeError(\"different error\")\n    finally:\n        await asyncio.sleep(0)\n    return 2  # Should not reach this\n\n# Test 4: Another try/except block inside finally\nasync def async_try_except_inside_finally() -> int:\n    try:\n        raise ValueError(\"outer error\")\n        return 1  # Never reached\n    finally:\n        await asyncio.sleep(0)\n        try:\n            raise RuntimeError(\"inner error\")\n        except RuntimeError:\n            pass  # Catch inner error\n    return 2  # What happens after finally with inner exception handled?\n\n# Test 5: Another try/finally block inside finally\nasync def async_try_finally_inside_finally() -> int:\n    try:\n        raise ValueError(\"outer error\")\n        return 1  # Never reached\n    finally:\n        await asyncio.sleep(0)\n        try:\n            raise RuntimeError(\"inner error\")\n        finally:\n            await asyncio.sleep(0)\n    return 2  # Should not reach this\n\n# Control case: No await in finally - should work correctly\nasync def async_exception_no_await_in_finally() -> None:\n    \"\"\"Control case: This works correctly - exception propagates\"\"\"\n    try:\n        raise TestError(\"This exception will propagate!\")\n    finally:\n        pass  # No await here\n\n# Test function with no exception to check normal flow\nasync def async_no_exception_with_await_in_finally() -> int:\n    try:\n        return 1  # Normal return\n    finally:\n        await asyncio.sleep(0)\n    return 2  # Should not reach this\n\nasync def test_async_try_except_finally_await() -> None:\n    # Test 0: Simplest case - just try/finally with exception\n    # Expected: ValueError propagates\n    with assertRaises(ValueError):\n        await simple_try_finally_await()\n\n    # Test 1: Exception caught, not re-raised\n    # Expected: return 2 (from except block)\n    result = await async_try_except_no_reraise()\n    assert result == 2, f\"Expected 2, got {result}\"\n\n    # Test 2: Exception caught and re-raised\n    # Expected: ValueError propagates\n    with assertRaises(ValueError):\n        await async_try_except_reraise()\n\n    # Test 3: Exception caught, different exception raised\n    # Expected: RuntimeError propagates\n    with assertRaises(RuntimeError):\n        await async_try_except_raise_different()\n\n    # Test 4: Try/except inside finally\n    # Expected: ValueError propagates (outer exception)\n    with assertRaises(ValueError):\n        await async_try_except_inside_finally()\n\n    # Test 5: Try/finally inside finally\n    # Expected: RuntimeError propagates (inner error)\n    with assertRaises(RuntimeError):\n        await async_try_finally_inside_finally()\n\n    # Control case: No await in finally (should work correctly)\n    with assertRaises(TestError):\n        await async_exception_no_await_in_finally()\n\n    # Test normal flow (no exception)\n    # Expected: return 1\n    result = await async_no_exception_with_await_in_finally()\n    assert result == 1, f\"Expected 1, got {result}\"\n\n[file asyncio/__init__.pyi]\nasync def sleep(t: float) -> None: ...\n\n[case testAsyncContextManagerExceptionHandling]\nimport asyncio\nfrom typing import Optional, Type\nfrom testutil import assertRaises\n\n# Test 1: Basic async context manager that doesn't suppress exceptions\nclass AsyncContextManager:\n    async def __aenter__(self) -> 'AsyncContextManager':\n        return self\n\n    async def __aexit__(self, exc_type: Optional[Type[BaseException]],\n                       exc_val: Optional[BaseException],\n                       exc_tb: object) -> None:\n        # This await in __aexit__ is like await in finally\n        await asyncio.sleep(0)\n        # Don't suppress the exception (return None/False)\n\nasync def func_with_async_context_manager() -> str:\n    async with AsyncContextManager():\n        raise ValueError(\"Exception inside async with\")\n        return \"should not reach\"  # Never reached\n    return \"should not reach either\"  # Never reached\n\nasync def test_basic_exception() -> str:\n    try:\n        await func_with_async_context_manager()\n        return \"func_a returned normally - bug!\"\n    except ValueError:\n        return \"caught ValueError - correct!\"\n    except Exception as e:\n        return f\"caught different exception: {type(e).__name__}\"\n\n# Test 2: Async context manager that raises a different exception in __aexit__\nclass AsyncContextManagerRaisesInExit:\n    async def __aenter__(self) -> 'AsyncContextManagerRaisesInExit':\n        return self\n\n    async def __aexit__(self, exc_type: Optional[Type[BaseException]],\n                       exc_val: Optional[BaseException],\n                       exc_tb: object) -> None:\n        # This await in __aexit__ is like await in finally\n        await asyncio.sleep(0)\n        # Raise a different exception - this should replace the original exception\n        raise RuntimeError(\"Exception in __aexit__\")\n\nasync def func_with_raising_context_manager() -> str:\n    async with AsyncContextManagerRaisesInExit():\n        raise ValueError(\"Original exception\")\n        return \"should not reach\"  # Never reached\n    return \"should not reach either\"  # Never reached\n\nasync def test_exception_in_aexit() -> str:\n    try:\n        await func_with_raising_context_manager()\n        return \"func returned normally - unexpected!\"\n    except RuntimeError:\n        return \"caught RuntimeError - correct!\"\n    except ValueError:\n        return \"caught ValueError - original exception not replaced!\"\n    except Exception as e:\n        return f\"caught different exception: {type(e).__name__}\"\n\nasync def test_async_context_manager_exception_handling() -> None:\n    # Test 1: Basic exception propagation\n    result = await test_basic_exception()\n    # Expected: \"caught ValueError - correct!\"\n    assert result == \"caught ValueError - correct!\", f\"Expected exception to propagate, got: {result}\"\n\n    # Test 2: Exception raised in __aexit__ replaces original exception\n    result = await test_exception_in_aexit()\n    # Expected: \"caught RuntimeError - correct!\"\n    # (The RuntimeError from __aexit__ should replace the ValueError)\n    assert result == \"caught RuntimeError - correct!\", f\"Expected RuntimeError from __aexit__, got: {result}\"\n\n[file asyncio/__init__.pyi]\nasync def sleep(t: float) -> None: ...\n\n[case testCallableArgWithSameNameAsHelperMethod]\nimport asyncio\nfrom typing import Awaitable, Callable\n\n\nMyCallable = Callable[[int, int], Awaitable[int]]\n\nasync def add(a: int, b: int) -> int:\n    return a + b\n\nasync def await_send(send: MyCallable) -> int:\n    return await send(1, 2)\n\nasync def await_throw(throw: MyCallable) -> int:\n    return await throw(3, 4)\n\nasync def tests() -> None:\n    assert await await_send(add) == 3\n    assert await await_throw(add) == 7\n\ndef test_callable_arg_same_name_as_helper() -> None:\n    asyncio.run(tests())\n\n[file asyncio/__init__.pyi]\ndef run(x: object) -> object: ...\n\n[case testRunAsyncCancelFinallySpecialCase]\nimport asyncio\n\nfrom testutil import assertRaises\n\n# Greatly simplified from asyncio.Condition\nclass Condition:\n    async def acquire(self) -> None: pass\n\n    async def wait(self) -> bool:\n         l = asyncio.get_running_loop()\n         fut = l.create_future()\n         a = []\n         try:\n             try:\n                 a.append(fut)\n                 try:\n                     await fut\n                     return True\n                 finally:\n                     a.pop()\n             finally:\n                err = None\n                while True:\n                    try:\n                        await self.acquire()\n                        break\n                    except asyncio.CancelledError as e:\n                        err = e\n\n                if err is not None:\n                    try:\n                        raise err\n                    finally:\n                        err = None\n         except BaseException:\n             raise\n\nasync def do_cancel() -> None:\n    cond = Condition()\n    wait = asyncio.create_task(cond.wait())\n    asyncio.get_running_loop().call_soon(wait.cancel)\n    with assertRaises(asyncio.CancelledError):\n        await wait\n\ndef test_cancel_special_case() -> None:\n    asyncio.run(do_cancel())\n\n[file asyncio/__init__.pyi]\nfrom typing import Any\n\nclass CancelledError(Exception): ...\n\ndef run(x: object) -> object: ...\ndef get_running_loop() -> Any: ...\ndef create_task(x: object) -> Any: ...\n\n[case testAsyncInheritance1]\nfrom typing import final, Coroutine, Any, TypeVar\n\nimport asyncio\n\nfrom mypy_extensions import trait\n\nclass Base1:\n    async def foo(self) -> int:\n        return 1\n\nclass Derived1(Base1):\n    async def foo(self) -> int:\n        return await super().foo() + 1\n\nasync def base1_foo(b: Base1) -> int:\n    return await b.foo()\n\nasync def derived1_foo(b: Derived1) -> int:\n    return await b.foo()\n\ndef test_async_inheritance() -> None:\n     assert asyncio.run(base1_foo(Base1())) == 1\n     assert asyncio.run(base1_foo(Derived1())) == 2\n     assert asyncio.run(derived1_foo(Derived1())) == 2\n\n@final\nclass FinalClass:\n    async def foo(self) -> int:\n        return 3\n\nasync def final_class_foo(b: FinalClass) -> int:\n    return await b.foo()\n\ndef test_final_class() -> None:\n     assert asyncio.run(final_class_foo(FinalClass())) == 3\n\nclass Base2:\n    async def foo(self) -> int:\n        return 4\n\n    async def bar(self) -> int:\n        return 5\n\nclass Derived2(Base2):\n    # Does not override \"foo\"\n    async def bar(self) -> int:\n        return 6\n\nasync def base2_foo(b: Base2) -> int:\n    return await b.foo()\n\ndef test_no_override() -> None:\n     assert asyncio.run(base2_foo(Base2())) == 4\n     assert asyncio.run(base2_foo(Derived2())) == 4\n\nclass Base3:\n    async def foo(self) -> int:\n        return 7\n\nclass Derived3(Base3):\n    def foo(self) -> Coroutine[Any, Any, int]:\n        async def inner() -> int:\n            return 8\n        return inner()\n\nasync def base3_foo(b: Base3) -> int:\n    return await b.foo()\n\ndef test_override_non_async() -> None:\n     assert asyncio.run(base3_foo(Base3())) == 7\n     assert asyncio.run(base3_foo(Derived3())) == 8\n\nclass Base4: pass\n\n@trait\nclass TraitBase:\n    async def foo(self, value: int) -> int:\n        raise NotImplementedError()\n\nclass DerivedFromTrait(Base4, TraitBase):\n    async def foo(self, value: int) -> int:\n        return value + 3\n\nasync def trait_foo(o: TraitBase, x: int) -> int:\n    return await o.foo(x)\n\ndef test_override_trait() -> None:\n    assert asyncio.run(trait_foo(DerivedFromTrait(), 7)) == 10\n\nclass Base5:\n    def __init__(self) -> None:\n        self._name = \"test\"\n\n    async def foo(self, x: int) -> int:\n        assert self._name == \"test\"\n        return x + 11\n\nclass Derived5(Base5):\n    async def foo(self, x: int) -> int:\n        return await super().foo(x) + 22\n\ndef test_call_using_super() -> None:\n    assert asyncio.run(Derived5().foo(5)) == 38\n\n[file asyncio/__init__.pyi]\ndef run(x: object) -> object: ...\n\n[case testAsyncIntrospection]\nimport asyncio\nimport inspect\nimport sys\nimport weakref\n\nfrom functools import wraps\nfrom typing import Any, Callable, TypeVar, cast\n\ndef identity(val: int) -> int:\n    return val\n\nasync def identity_async(val: int) -> int:\n    return val\n\nF = TypeVar(\"F\", bound=Callable[..., Any])\n\ndef wrap(fn: F) -> F:\n    if is_coroutine(fn):\n        @wraps(fn)\n        async def wrapper_async(*args) -> Any:\n            return await fn(*args) + await fn(*args)\n\n        return cast(F, wrapper_async)\n\n    @wraps(fn)\n    def wrapper(*args) -> Any:\n        return fn(*args) + fn(*args)\n\n    return cast(F, wrapper)\n\n@wrap\ndef wrapped(val: int) -> int:\n    return val\n\n@wrap\ndef wrapped2(val: int) -> int:\n    return val * 2\n\n@wrap\nasync def wrapped_async(val: int) -> int:\n    return val\n\n@wrap\nasync def wrapped2_async(val: int) -> int:\n    return val * 2\n\nclass T:\n    def returns_one(self) -> int:\n        return 1\n\n    async def returns_one_async(self) -> int:\n        return 1\n\n    @wrap\n    def returns_two(self) -> int:\n        return 1\n\n    @wrap\n    async def returns_two_async(self) -> int:\n        return 1\n\n    @staticmethod\n    def static() -> int:\n        return 2\n\n    @staticmethod\n    async def static_async() -> int:\n        return 2\n\n    @classmethod\n    def class_method(cls) -> int:\n        return 3\n\n    @classmethod\n    async def class_method_async(cls) -> int:\n        return 3\n\ndef is_coroutine(fn):\n    if sys.version_info >= (3, 10):  # type: ignore[operator]\n        return inspect.iscoroutinefunction(fn)\n\n    # inspect on older python versions does not support function-like objects.\n    # Below is a simplified implementation of iscoroutinefunction.\n    if not hasattr(fn, \"__code__\"):\n        return False\n    CO_COROUTINE = 0x0080\n    return bool(fn.__code__.co_flags & CO_COROUTINE)\n\ndef test_function() -> None:\n    assert not is_coroutine(identity)\n    assert is_coroutine(identity_async)\n    assert str(identity_async).startswith(\"<function identity_async\"), str(identity_async)\n    assert asyncio.run(identity_async(42)) == 42\n\n    wr = weakref.ref(identity_async)\n    f = wr()\n    assert f\n    assert asyncio.run(f(43)) == 43\n\n    assert getattr(identity_async, \"__name__\") == \"identity_async\", getattr(identity_async, \"__name__\")\n    setattr(identity_async, \"__name__\", \"some custom name\")\n    assert getattr(identity_async, \"__name__\") == \"some custom name\", getattr(identity_async, \"__name__\")\n    assert getattr(identity_async, \"__code__\") != None, getattr(identity_async, \"__code__\")\n    assert getattr(identity_async, \"__defaults__\") == None, getattr(identity_async, \"__defaults__\")\n    assert getattr(identity_async, \"__kwdefaults__\") == None, getattr(identity_async, \"__kwdefaults__\")\n    assert getattr(identity_async, \"__annotations__\") == None, getattr(identity_async, \"__annotations__\")\n\n    assert not is_coroutine(wrapped)\n    assert is_coroutine(wrapped_async)\n    assert asyncio.run(wrapped_async(22)) == 44\n\n    assert getattr(wrapped, \"__name__\") == \"wrapped\", getattr(wrapped, \"__name__\")\n    assert getattr(wrapped2, \"__name__\") == \"wrapped2\", getattr(wrapped2, \"__name__\")\n\n    assert getattr(wrapped_async, \"__name__\") == \"wrapped_async\", getattr(wrapped_async, \"__name__\")\n    assert getattr(wrapped2_async, \"__name__\") == \"wrapped2_async\", getattr(wrapped2_async, \"__name__\")\n\n    setattr(wrapped_async, \"__name__\", \"new name\")\n    assert getattr(wrapped_async, \"__name__\") == \"new name\", getattr(wrapped_async, \"__name__\")\n    assert getattr(wrapped2_async, \"__name__\") == \"wrapped2_async\", getattr(wrapped2_async, \"__name__\")\n\ndef test_method() -> None:\n    assert not is_coroutine(T.returns_one)\n    assert is_coroutine(T.returns_one_async)\n    assert str(T.returns_one_async).startswith(\"<function T.returns_one_async\"), str(T.returns_one_async)\n\n    t = T()\n    # Call through variable to make sure the call is through vectorcall and not optimized to a native call.\n    f: Any = t.returns_one_async\n    assert asyncio.run(f()) == 1\n\n    assert not is_coroutine(T.returns_two)\n    assert is_coroutine(T.returns_two_async)\n    assert asyncio.run(t.returns_two_async()) == 2\n\n    assert not is_coroutine(T.static)\n    assert is_coroutine(T.static_async)\n    assert asyncio.run(T.static_async()) == 2\n\n    assert not is_coroutine(T.class_method)\n    assert is_coroutine(T.class_method_async)\n    assert asyncio.run(T.class_method_async()) == 3\n\ndef test_nested() -> None:\n    def nested() -> int:\n        return 1\n\n    async def nested_async() -> int:\n        return 1\n\n    @wrap\n    def nested_wrapped() -> int:\n        return 2\n\n    @wrap\n    async def nested_wrapped_async() -> int:\n        return 2\n\n    assert not is_coroutine(nested)\n    assert is_coroutine(nested_async)\n    assert asyncio.run(nested_async()) == 1\n\n    assert getattr(nested_async, \"__name__\") == \"nested_async\", getattr(nested_async, \"__name__\")\n    setattr(nested_async, \"__name__\", \"some custom name\")\n    assert getattr(nested_async, \"__name__\") == \"some custom name\", getattr(nested_async, \"__name__\")\n    assert getattr(nested_async, \"__code__\") != None, getattr(nested_async, \"__code__\")\n    assert getattr(nested_async, \"__defaults__\") == None, getattr(nested_async, \"__defaults__\")\n    assert getattr(nested_async, \"__kwdefaults__\") == None, getattr(nested_async, \"__kwdefaults__\")\n    assert getattr(nested_async, \"__annotations__\") == None, getattr(nested_async, \"__annotations__\")\n\n    assert not is_coroutine(nested_wrapped)\n    assert is_coroutine(nested_wrapped_async)\n    assert asyncio.run(nested_wrapped_async()) == 4\n\n[file asyncio/__init__.pyi]\ndef run(x: object) -> object: ...\n\n[case testFuture]\nimport asyncio\nfrom typing import Any, Awaitable\n\nfrom testutil import assertRaises\n\nfrom m import (\n    m_future_with_result,\n    m_future_with_exception,\n    m_future_with_caught_exception,\n    m_future_with_reraised_exception\n)\n\nasync def set_result(fut: asyncio.Future, result: Any) -> None:\n    if isinstance(result, Exception):\n        fut.set_exception(result)\n    else:\n        fut.set_result(result)\n\ndef make_future(result: Any) -> asyncio.Future:\n    loop = asyncio.get_running_loop()\n    fut = loop.create_future()\n    loop.create_task(set_result(fut, result))\n    return fut\n\nasync def future_with_result(result: int) -> int:\n    return await make_future(result)\n\nasync def future_with_exception(exception: Exception) -> Any:\n    return await make_future(exception)\n\nasync def future_with_caught_exception(exception: Exception) -> None:\n    try:\n        return await make_future(exception)\n    except type(exception):\n        return None\n\nasync def future_with_reraised_exception(first_exc: Exception, second_exc: Exception) -> Any:\n    try:\n        return await make_future(first_exc)\n    except type(first_exc):\n        raise second_exc\n\ndef test_future() -> None:\n    assert asyncio.run(future_with_result(42)) == 42\n\n    with assertRaises(ValueError, \"error\"):\n        asyncio.run(future_with_exception(ValueError(\"error\")))\n\n    assert asyncio.run(future_with_caught_exception(ValueError(\"error\"))) == None\n\n    with assertRaises(RuntimeError, \"reraised\"):\n        asyncio.run(future_with_reraised_exception(ValueError(\"error\"), RuntimeError(\"reraised\")))\n\nclass ctx_man:\n    def __enter__(self) -> None:\n        pass\n\n    def __exit__(self, *args: Any) -> None:\n        pass\n\nasync def wrap(f: Awaitable) -> Any:\n    with ctx_man():\n        return await f\n\ndef test_future_with_context_manager() -> None:\n    assert asyncio.run(wrap(future_with_result(42))) == 42\n\n    with assertRaises(ValueError, \"error\"):\n        asyncio.run(wrap(future_with_exception(ValueError(\"error\"))))\n\n    assert asyncio.run(wrap(future_with_caught_exception(ValueError(\"error\")))) == None\n\n    with assertRaises(RuntimeError, \"reraised\"):\n        asyncio.run(wrap(future_with_reraised_exception(ValueError(\"error\"), RuntimeError(\"reraised\"))))\n\ndef test_interpreted_future() -> None:\n    assert asyncio.run(m_future_with_result(42)) == 42\n\n    with assertRaises(ValueError, \"error\"):\n        asyncio.run(m_future_with_exception(ValueError(\"error\")))\n\n    assert asyncio.run(m_future_with_caught_exception(ValueError(\"error\"))) == None\n\n    with assertRaises(RuntimeError, \"reraised\"):\n        asyncio.run(m_future_with_reraised_exception(ValueError(\"error\"), RuntimeError(\"reraised\")))\n\ndef test_interpreted_future_with_context_manager() -> None:\n    assert asyncio.run(wrap(m_future_with_result(42))) == 42\n\n    with assertRaises(ValueError, \"error\"):\n        asyncio.run(wrap(m_future_with_exception(ValueError(\"error\"))))\n\n    assert asyncio.run(wrap(m_future_with_caught_exception(ValueError(\"error\")))) == None\n\n    with assertRaises(RuntimeError, \"reraised\"):\n        asyncio.run(wrap(m_future_with_reraised_exception(ValueError(\"error\"), RuntimeError(\"reraised\"))))\n\n[file asyncio/__init__.pyi]\nfrom typing import Any, Generator\n\ndef run(x: object) -> object: ...\n\nclass Future:\n    def set_result(self, result: object) -> None: ...\n    def set_exception(self, exception: object) -> None: ...\n    def __await__(self) -> Generator[Any, Any, Any]: ...\n\nclass Loop:\n    def create_future(self) -> Future: ...\n    def create_task(self, x: object) -> None: ...\n\ndef get_running_loop() -> Loop: ...\n\n[file m.py]\nimport asyncio\nfrom typing import Any\n\nasync def set_result(fut: asyncio.Future, result: Any) -> None:\n    if isinstance(result, Exception):\n        fut.set_exception(result)\n    else:\n        fut.set_result(result)\n\ndef make_future(result: Any) -> asyncio.Future:\n    loop = asyncio.get_running_loop()\n    fut = loop.create_future()\n    loop.create_task(set_result(fut, result))\n    return fut\n\nasync def m_future_with_result(result: int) -> int:\n    return await make_future(result)\n\nasync def m_future_with_exception(exception: Exception) -> Any:\n    return await make_future(exception)\n\nasync def m_future_with_caught_exception(exception: Exception) -> None:\n    try:\n        return await make_future(exception)\n    except type(exception):\n        return None\n\nasync def m_future_with_reraised_exception(first_exc: Exception, second_exc: Exception) -> Any:\n    try:\n        return await make_future(first_exc)\n    except type(first_exc):\n        raise second_exc\n\n[case testCPyFunctionWithFreedInstance]\nimport asyncio\n\nfrom functools import wraps\nfrom typing import Any\n\nclass ctx_man:\n    async def __aenter__(self) -> None:\n        pass\n\n    async def __aexit__(self, *args: Any) -> None:\n        pass\n\ndef with_ctx_man():\n    def decorator(f):\n        @wraps(f)\n        async def inner():\n            async with ctx_man():\n                return await f()\n\n        return inner\n\n    return decorator\n\nasync def func() -> int:\n    return 33\n\nasync def run_wrapped():\n    wrapped = with_ctx_man()(func)\n    return await wrapped()\n\ndef test_native():\n    assert asyncio.run(run_wrapped()) == 33\n\n[file driver.py]\nimport asyncio\n\nfrom native import test_native, with_ctx_man\n\nasync def func() -> int:\n    return 42\n\nasync def run_wrapped():\n    wrapped = with_ctx_man()(func)\n    return await wrapped()\n\ndef test_interpreted():\n    assert asyncio.run(run_wrapped()) == 42\n\n# Run multiple times to test that the CPyFunction attribute is still\n# set correctly after reusing a freed instance of the inner callable class object.\nfor i in range(10):\n    test_interpreted()\n    test_native()\n\n[file asyncio/__init__.pyi]\nfrom typing import Any, Generator\n\ndef run(x: object) -> object: ...\n\n[case testNestedCoroutineCallsAnotherNestedFunction]\nimport asyncio\nimport functools\nimport inspect\nfrom typing import Any, Callable, TypeVar, cast\n\nF = TypeVar(\"F\", bound=Callable[..., Any])\n\n\ndef mult_different_wrapper_names(x: int) -> Callable[[F], F]:\n    def decorate(fn: F) -> F:\n        def get_multiplier() -> int:\n            return x\n\n        if inspect.iscoroutinefunction(fn):\n            @functools.wraps(fn)\n            async def wrapper_async(*args, **kwargs) -> Any:\n                return get_multiplier() * await fn(*args, **kwargs)\n            wrapper = wrapper_async\n        else:\n            @functools.wraps(fn)\n            def wrapper_non_async(*args, **kwargs) -> Any:\n                return get_multiplier() * fn(*args, **kwargs)\n            wrapper = wrapper_non_async\n\n        return cast(F, wrapper)\n\n    return decorate\n\ndef mult_same_wrapper_names(x: int) -> Callable[[F], F]:\n    def decorate(fn: F) -> F:\n        def get_multiplier() -> int:\n            return x\n\n        if inspect.iscoroutinefunction(fn):\n            @functools.wraps(fn)\n            async def wrapper(*args, **kwargs) -> Any:\n                return get_multiplier() * await fn(*args, **kwargs)\n        else:\n            @functools.wraps(fn)\n            def wrapper(*args, **kwargs) -> Any:\n                return get_multiplier() * fn(*args, **kwargs)\n\n        return cast(F, wrapper)\n\n    return decorate\n\n@mult_different_wrapper_names(3)\ndef identity(x: int):\n    return x\n\n@mult_different_wrapper_names(5)\nasync def async_identity(x: int):\n    return x\n\n@mult_same_wrapper_names(2)\ndef times_two(x: int):\n    return x * 2\n\n@mult_same_wrapper_names(4)\nasync def async_times_two(x: int):\n    return x * 2\n\ndef test_nested_coroutine_calls_another_nested_function():\n    assert identity(1) == 3\n    assert asyncio.run(async_identity(2)) == 10\n\n    assert times_two(3) == 12\n    assert asyncio.run(async_times_two(4)) == 32\n\n[file asyncio/__init__.pyi]\nfrom typing import Any, Generator\n\ndef run(x: object) -> object: ...\n"
  },
  {
    "path": "mypyc/test-data/run-attrs.test",
    "content": "-- Test cases for dataclasses based on the attrs library, where auto_attribs=True\n\n[case testRunAttrsclass]\nimport attr\nfrom typing import Set, List, Callable, Any\n\n@attr.s(auto_attribs=True)\nclass Person1:\n    age : int\n    name : str\n\n    def __bool__(self) -> bool:\n        return self.name == 'robot'\n\ndef testBool(p: Person1) -> bool:\n    if p:\n        return True\n    else:\n        return False\n\n@attr.s(auto_attribs=True)\nclass Person1b(Person1):\n    id: str = '000'\n\n@attr.s(auto_attribs=True)\nclass Person2:\n    age : int\n    name : str = attr.ib(default='robot')\n\n@attr.s(auto_attribs=True, order=True)\nclass Person3:\n    age : int = attr.ib(default = 6)\n    friendIDs : List[int] = attr.ib(factory = list)\n\n    def get_age(self) -> int:\n        return (self.age)\n\n    def set_age(self, new_age : int) -> None:\n        self.age = new_age\n\n    def add_friendID(self, fid : int) -> None:\n        self.friendIDs.append(fid)\n\n    def get_friendIDs(self) -> List[int]:\n        return self.friendIDs\n\ndef get_next_age(g: Callable[[Any], int]) -> Callable[[Any], int]:\n    def f(a: Any) -> int:\n        return g(a) + 1\n    return f\n\n@attr.s(auto_attribs=True)\nclass Person4:\n    age : int\n    _name : str = 'Bot'\n\n    @get_next_age\n    def get_age(self) -> int:\n        return self.age\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n@attr.s(auto_attribs=True)\nclass Point:\n     x : int = attr.ib(converter=int)\n     y : int = attr.ib(init=False)\n\n     def __attrs_post_init__(self):\n         self.y = self.x + 1\n\n\n[file other.py]\nfrom native import Person1, Person1b, Person2, Person3, Person4, testBool, Point\ni1 = Person1(age = 5, name = 'robot')\nassert i1.age == 5\nassert i1.name == 'robot'\nassert testBool(i1) == True\nassert testBool(Person1(age = 5, name = 'robo')) == False\ni1b = Person1b(age = 5, name = 'robot')\nassert i1b.age == 5\nassert i1b.name == 'robot'\nassert i1b.id == '000'\nassert testBool(i1b) == True\nassert testBool(Person1b(age = 5, name = 'robo')) == False\ni1c = Person1b(age = 20, name = 'robot', id = 'test')\nassert i1c.age == 20\nassert i1c.id == 'test'\n\ni2 = Person2(age = 5)\nassert i2.age == 5\nassert i2.name == 'robot'\ni3 = Person2(age = 5, name = 'new_robot')\nassert i3.age == 5\nassert i3.name == 'new_robot'\ni4 = Person3()\nassert i4.age == 6\nassert i4.friendIDs == []\ni5 = Person3(age = 5)\nassert i5.age == 5\nassert i5.friendIDs == []\ni6 = Person3(age = 5, friendIDs = [1,2,3])\nassert i6.age == 5\nassert i6.friendIDs == [1,2,3]\nassert i6.get_age() == 5\ni6.set_age(10)\nassert i6.get_age() == 10\ni6.add_friendID(4)\nassert i6.get_friendIDs() == [1,2,3,4]\ni7 = Person4(age = 5)\nassert i7.get_age() == 6\ni7.age += 3\nassert i7.age == 8\nassert i7.name == 'Bot'\ni8 = Person3(age = 1, friendIDs = [1,2])\ni9 = Person3(age = 1, friendIDs = [1,2])\nassert i8 == i9\ni8.age = 2\nassert i8 > i9\n\nassert Person1.__annotations__ == {'age': int, 'name': str}\nassert Person2.__annotations__ == {'age': int, 'name': str}\n\np1 = Point(2)\nassert p1.x == 2\nassert p1.y == 3\np2 = Point('2')\nassert p2.x == 2\nassert p2.y == 3\n\nassert Point.__annotations__ == {'x': int, 'y': int}\n\n[file driver.py]\nimport sys\n\n# PEP 526 introduced in 3.6\nversion = sys.version_info[:2]\nif version[0] < 3 or version[1] < 6:\n    exit()\n\n# Run the tests in both interpreted and compiled mode\nimport other\nimport other_interpreted\n\n# Test for an exceptional cases\nfrom testutil import assertRaises\nfrom native import Person1, Person1b, Person3\nfrom types import BuiltinMethodType\n\nwith assertRaises(TypeError, \"missing 1 required positional argument\"):\n    Person1(0)\n\nwith assertRaises(TypeError, \"missing 2 required positional arguments\"):\n    Person1b()\n\nwith assertRaises(TypeError, \"int object expected; got str\"):\n    Person1('nope', 'test')\n\np = Person1(0, 'test')\nwith assertRaises(TypeError, \"int object expected; got str\"):\n    p.age = 'nope'\n\nassert isinstance(Person3().get_age, BuiltinMethodType)\n\n\n[case testRunAttrsclassNonAuto]\nimport attr\nfrom typing import Set, List, Callable, Any\n\n@attr.s\nclass Person1:\n    age = attr.ib(type=int)\n    name = attr.ib(type=str)\n\n    def __bool__(self) -> bool:\n        return self.name == 'robot'\n\ndef testBool(p: Person1) -> bool:\n    if p:\n        return True\n    else:\n        return False\n\n@attr.s\nclass Person1b(Person1):\n    id = attr.ib(type=str, default='000')\n\n@attr.s\nclass Person2:\n    age = attr.ib(type=int)\n    name = attr.ib(type=str, default='robot')\n\n@attr.s(order=True)\nclass Person3:\n    age = attr.ib(type=int, default=6)\n    friendIDs = attr.ib(factory=list, type=List[int])\n\n    def get_age(self) -> int:\n        return (self.age)\n\n    def set_age(self, new_age : int) -> None:\n        self.age = new_age\n\n    def add_friendID(self, fid : int) -> None:\n        self.friendIDs.append(fid)\n\n    def get_friendIDs(self) -> List[int]:\n        return self.friendIDs\n\ndef get_next_age(g: Callable[[Any], int]) -> Callable[[Any], int]:\n    def f(a: Any) -> int:\n        return g(a) + 1\n    return f\n\n@attr.s\nclass Person4:\n    age = attr.ib(type=int)\n    _name = attr.ib(type=str, default='Bot')\n\n    @get_next_age\n    def get_age(self) -> int:\n        return self.age\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n@attr.s\nclass Point:\n     x = attr.ib(type=int, converter=int)\n     y = attr.ib(type=int, init=False)\n\n     def __attrs_post_init__(self):\n         self.y = self.x + 1\n\n\n[file other.py]\nfrom native import Person1, Person1b, Person2, Person3, Person4, testBool, Point\ni1 = Person1(age = 5, name = 'robot')\nassert i1.age == 5\nassert i1.name == 'robot'\nassert testBool(i1) == True\nassert testBool(Person1(age = 5, name = 'robo')) == False\ni1b = Person1b(age = 5, name = 'robot')\nassert i1b.age == 5\nassert i1b.name == 'robot'\nassert i1b.id == '000'\nassert testBool(i1b) == True\nassert testBool(Person1b(age = 5, name = 'robo')) == False\ni1c = Person1b(age = 20, name = 'robot', id = 'test')\nassert i1c.age == 20\nassert i1c.id == 'test'\n\ni2 = Person2(age = 5)\nassert i2.age == 5\nassert i2.name == 'robot'\ni3 = Person2(age = 5, name = 'new_robot')\nassert i3.age == 5\nassert i3.name == 'new_robot'\ni4 = Person3()\nassert i4.age == 6\nassert i4.friendIDs == []\ni5 = Person3(age = 5)\nassert i5.age == 5\nassert i5.friendIDs == []\ni6 = Person3(age = 5, friendIDs = [1,2,3])\nassert i6.age == 5\nassert i6.friendIDs == [1,2,3]\nassert i6.get_age() == 5\ni6.set_age(10)\nassert i6.get_age() == 10\ni6.add_friendID(4)\nassert i6.get_friendIDs() == [1,2,3,4]\ni7 = Person4(age = 5)\nassert i7.get_age() == 6\ni7.age += 3\nassert i7.age == 8\nassert i7.name == 'Bot'\ni8 = Person3(age = 1, friendIDs = [1,2])\ni9 = Person3(age = 1, friendIDs = [1,2])\nassert i8 == i9\ni8.age = 2\nassert i8 > i9\n\np1 = Point(2)\nassert p1.x == 2\nassert p1.y == 3\np2 = Point('2')\nassert p2.x == 2\nassert p2.y == 3\n\n[file driver.py]\nimport sys\n\n# Run the tests in both interpreted and compiled mode\nimport other\nimport other_interpreted\n\n# Test for an exceptional cases\nfrom testutil import assertRaises\nfrom native import Person1, Person1b, Person3\nfrom types import BuiltinMethodType\n\nwith assertRaises(TypeError, \"missing 1 required positional argument\"):\n    Person1(0)\n\nwith assertRaises(TypeError, \"missing 2 required positional arguments\"):\n    Person1b()\n\nwith assertRaises(TypeError, \"int object expected; got str\"):\n    Person1('nope', 'test')\n\np = Person1(0, 'test')\nwith assertRaises(TypeError, \"int object expected; got str\"):\n    p.age = 'nope'\n\nassert isinstance(Person3().get_age, BuiltinMethodType)\n"
  },
  {
    "path": "mypyc/test-data/run-base64.test",
    "content": "[case testAllBase64Features_librt]\nfrom typing import Any, cast\nimport base64\nimport binascii\nimport random\n\nfrom librt.base64 import b64encode, b64decode, urlsafe_b64encode, urlsafe_b64decode\n\nfrom testutil import assertRaises\n\nrand_values = [random.randbytes(random.randint(1, 2000)) for _ in range(2000)]\n\ndef test_encode_basic() -> None:\n    assert b64encode(b\"x\") == b\"eA==\"\n\n    with assertRaises(TypeError):\n        b64encode(cast(Any, bytearray(b\"x\")))\n\ndef check_encode(b: bytes) -> None:\n     assert b64encode(b) == getattr(base64, \"b64encode\")(b)\n\ndef test_encode_different_strings() -> None:\n    for i in range(256):\n        check_encode(bytes([i]))\n        check_encode(bytes([i]) + b\"x\")\n        check_encode(bytes([i]) + b\"xy\")\n        check_encode(bytes([i]) + b\"xyz\")\n        check_encode(bytes([i]) + b\"xyza\")\n        check_encode(b\"x\" + bytes([i]))\n        check_encode(b\"xy\" + bytes([i]))\n        check_encode(b\"xyz\" + bytes([i]))\n        check_encode(b\"xyza\" + bytes([i]))\n\n    b = b\"a\\x00\\xb7\" * 1000\n    for i in range(1000):\n        check_encode(b[:i])\n\n    for b in b\"\", b\"ab\", b\"bac\", b\"1234\", b\"xyz88\", b\"abc\" * 200:\n        check_encode(b)\n\n    for b in rand_values:\n        check_encode(b)\n\ndef test_encode_wrappers() -> None:\n    funcs: list[Any] = [b64encode, urlsafe_b64encode]\n    for enc in funcs:\n        assert enc(b\"x\") == b\"eA==\"\n\n        with assertRaises(TypeError):\n            enc()\n\n        with assertRaises(TypeError):\n            enc(b\"x\", b\"y\")\n\ndef test_decode_basic() -> None:\n    assert b64decode(b\"eA==\") == b\"x\"\n\n    with assertRaises(TypeError):\n        b64decode(cast(Any, bytearray(b\"eA==\")))\n\n    for non_ascii in \"\\x80\", \"foo\\u100bar\", \"foo\\ua1234bar\":\n        with assertRaises(ValueError):\n            b64decode(non_ascii)\n\ndef check_decode(b: bytes, encoded: bool = False) -> None:\n     if encoded:\n         enc = b\n     else:\n         enc = b64encode(b)\n     assert b64decode(enc) == getattr(base64, \"b64decode\")(enc)\n     if getattr(enc, \"isascii\")():  # Test stub has no \"isascii\"\n        enc_str = enc.decode(\"ascii\")\n        assert b64decode(enc_str) == getattr(base64, \"b64decode\")(enc_str)\n\ndef test_decode_different_strings() -> None:\n    for i in range(256):\n        check_decode(bytes([i]))\n        check_decode(bytes([i]) + b\"x\")\n        check_decode(bytes([i]) + b\"xy\")\n        check_decode(bytes([i]) + b\"xyz\")\n        check_decode(bytes([i]) + b\"xyza\")\n        check_decode(b\"x\" + bytes([i]))\n        check_decode(b\"xy\" + bytes([i]))\n        check_decode(b\"xyz\" + bytes([i]))\n        check_decode(b\"xyza\" + bytes([i]))\n\n    b = b\"a\\x00\\xb7\" * 1000\n    for i in range(1000):\n        check_decode(b[:i])\n\n    for b in b\"\", b\"ab\", b\"bac\", b\"1234\", b\"xyz88\", b\"abc\" * 200:\n        check_decode(b)\n\n    for b in rand_values:\n        check_decode(b)\n\ndef is_base64_char(x: int) -> bool:\n    c = chr(x)\n    return ('a' <= c <= 'z') or ('A' <= c <= 'Z') or ('0' <= c <= '9') or c in '+/='\n\ndef test_decode_with_non_base64_chars() -> None:\n    # For stdlib compatibility, non-base64 characters should be ignored.\n\n    # Invalid characters as a suffix use a fast path.\n    check_decode(b\"eA== \", encoded=True)\n    check_decode(b\"eA==\\n\", encoded=True)\n    check_decode(b\"eA== \\t\\n\", encoded=True)\n    check_decode(b\"\\n\", encoded=True)\n\n    check_decode(b\" e  A = = \", encoded=True)\n\n    # Special case: Two different encodings of the same data\n    check_decode(b\"eAa=\", encoded=True)\n    check_decode(b\"eAY=\", encoded=True)\n\n    for x in range(256):\n        if not is_base64_char(x):\n            b = bytes([x])\n            check_decode(b, encoded=True)\n            check_decode(b\"eA==\" + b, encoded=True)\n            check_decode(b\"e\" + b + b\"A==\", encoded=True)\n            check_decode(b\"eA=\" + b + b\"=\", encoded=True)\n\ndef check_decode_error(b: bytes, ignore_stdlib: bool = False) -> None:\n    if not ignore_stdlib:\n        with assertRaises(binascii.Error):\n            getattr(base64, \"b64decode\")(b)\n\n    # The raised error is different, since librt shouldn't depend on binascii\n    with assertRaises(ValueError):\n        b64decode(b)\n\ndef test_decode_with_invalid_padding() -> None:\n    check_decode_error(b\"eA\")\n    check_decode_error(b\"eA=\")\n    check_decode_error(b\"eHk\")\n    check_decode_error(b\"eA = \")\n\n    # Here stdlib behavior seems nonsensical, so we don't try to duplicate it\n    check_decode_error(b\"eA=a=\", ignore_stdlib=True)\n\ndef test_decode_with_extra_data_after_padding() -> None:\n    check_decode(b\"=\", encoded=True)\n    check_decode(b\"==\", encoded=True)\n    check_decode(b\"===\", encoded=True)\n    check_decode(b\"====\", encoded=True)\n    check_decode(b\"eA===\", encoded=True)\n    check_decode(b\"eHk==\", encoded=True)\n    check_decode(b\"eA==x\", encoded=True)\n    check_decode(b\"eHk=x\", encoded=True)\n    check_decode(b\"eA==abc=======efg\", encoded=True)\n\ndef test_decode_wrappers() -> None:\n    funcs: list[Any] = [b64decode, urlsafe_b64decode]\n    for dec in funcs:\n        assert dec(b\"eA==\") == b\"x\"\n\n        with assertRaises(TypeError):\n            dec()\n\n        with assertRaises(TypeError):\n            dec(b\"x\", b\"y\")\n\ndef check_urlsafe_encode(b: bytes) -> None:\n    assert urlsafe_b64encode(b) == getattr(base64, \"urlsafe_b64encode\")(b)\n\ndef test_urlsafe_b64encode() -> None:\n    check_urlsafe_encode(b\"\")\n    check_urlsafe_encode(b\"a\")\n    check_urlsafe_encode(b\"\\xf8\")\n    check_urlsafe_encode(b\"\\xfc\")\n    check_urlsafe_encode(b\"\\xfcx\")\n    check_urlsafe_encode(b\"\\xfcxy\")\n    check_urlsafe_encode(b\"\\xfcxyz\")\n    check_urlsafe_encode(bytes([x for x in range(256)]))\n\n    for b in rand_values:\n        check_urlsafe_encode(b)\n\ndef check_urlsafe_decode(b: bytes) -> None:\n    enc = urlsafe_b64encode(b)\n    assert urlsafe_b64decode(enc) == getattr(base64, \"urlsafe_b64decode\")(enc)\n    enc2 = b64encode(b)\n    assert urlsafe_b64decode(enc2) == getattr(base64, \"urlsafe_b64decode\")(enc2)\n\ndef test_urlsafe_b64decode() -> None:\n    # Don't test everything, since the implementation is mostly shared with b64decode.\n    check_urlsafe_decode(b\"\")\n    check_urlsafe_decode(b\"a\")\n    check_urlsafe_decode(b\"\\xf8\")\n    check_urlsafe_decode(b\"\\xfc\")\n    check_urlsafe_decode(b\"\\xfcx\")\n    check_urlsafe_decode(b\"\\xfcxy\")\n    check_urlsafe_decode(b\"\\xfcxyz\")\n    check_urlsafe_decode(bytes([x for x in range(256)]))\n\n    for b in rand_values:\n        check_urlsafe_decode(b)\n\n    assert urlsafe_b64decode(b\" e A = == !\") == b\"x\"\n\ndef test_urlsafe_b64decode_errors() -> None:\n    for b in b\"eA\", b\"eA=\", b\"eHk\":\n        with assertRaises(ValueError):\n            b64decode(b)\n\n[case testBase64UsedAtTopLevelOnly_librt]\nfrom librt.base64 import b64encode\n\n# The only reference to b64encode is at module top level\nencoded = b64encode(b\"x\")\n\ndef test_top_level_only_encode() -> None:\n    assert encoded == b\"eA==\"\n"
  },
  {
    "path": "mypyc/test-data/run-bench.test",
    "content": "-- TODO: build some generic benchmark harness\n[case testBenchmarkTree]\nfrom typing import Optional\nclass Node:\n    def __init__(self, value: int) -> None:\n        self.value = value\n        self.left = None  # type: Optional[Node]\n        self.right = None  # type: Optional[Node]\n    def sum(self) -> int:\n        left = 0\n        if self.left is not None:\n            left = self.left.sum()\n        right = 0\n        if self.right is not None:\n            right = self.right.sum()\n        return self.value + left + right\ndef sum_tree(x: Optional[Node]) -> int:\n    if x is None:\n        return 0\n    return x.value + sum_tree(x.left) + sum_tree(x.right)\ndef build(n: int) -> Optional[Node]:\n    if n == 0:\n        return None\n    x = Node(n)\n    x.left = build(n - 1)\n    x.right = x.left\n    return x\n\ndef bench_sum(x: Optional[Node]) -> None:\n    for i in range(1000000):\n        sum_tree(x)\ndef bench_sum_method(x: Node) -> None:\n    for i in range(1000000):\n        x.sum()\n[file driver.py]\nfrom typing import Optional\nimport native\nimport interpreted\nfrom timeit import timeit\nfrom time import time\nimport os\n\ndef dumb_time(f):\n    t0 = time()\n    f()\n    t1 = time()\n    return t1 - t0\n\ndef basic_test(m):\n    tree = m.build(5)\n    assert(m.sum_tree(tree) == 57)\n    assert(tree.sum() == 57)\n    return tree\n\ndef test(m):\n    tree = basic_test(m)\n\n    g = {**globals(), **locals()}\n    sum = timeit('m.sum_tree(tree)', globals=g)\n    sum2 = timeit('tree.sum()', globals=g)\n    fsum = dumb_time(lambda: m.bench_sum(tree))\n    fsum2 = dumb_time(lambda: m.bench_sum_method(tree))\n    build = timeit('m.build(5)', globals=g)\n    return (sum, sum2, fsum, fsum2, build)\n\n# Basic functionality test\nbasic_test(native)\n\n# Benchmark if we are benchmarking\nif os.environ.get('MYPYC_RUN_BENCH') == '1':\n    nsum, nsum2, nfsum, nfsum2, nbuild = test(native)\n    isum, isum2, ifsum, ifsum2, ibuild = test(interpreted)\n    print(nsum, nsum2, nfsum, nbuild)\n    print(\"Sum speedup:\", isum/nsum)\n    print(\"Sum method speedup:\", isum2/nsum2)\n    print(\"Sum (fast) speedup:\", ifsum/nfsum)\n    print(\"Sum (fast) method speedup:\", ifsum2/nfsum2)\n    print(\"Build speedup:\", ibuild/nbuild)\n\n[case testBenchmarkVisitorTree]\nfrom mypy_extensions import trait\nfrom typing import cast, Generic, TypeVar, Any\n\nT = TypeVar('T')\nclass Tree:\n    def accept(self, v: 'TreeVisitor[T]') -> T:\n        pass\nclass Leaf(Tree):\n    def accept(self, v: 'TreeVisitor[T]') -> T:\n        return v.visit_leaf(self)\nclass Node(Tree):\n    def __init__(self, value: int, left: Tree, right: Tree) -> None:\n        self.value = value\n        self.left = left\n        self.right = right\n    def accept(self, v: 'TreeVisitor[T]') -> T:\n        return v.visit_node(self)\n\n@trait\nclass TreeVisitor(Generic[T]):\n    def visit_leaf(self, x: Leaf) -> T: return cast(T, None)\n    def visit_node(self, x: Node) -> T: return cast(T, None)\n\nclass SumVisitor(TreeVisitor[int]):\n    def sum(self, x: Tree) -> int:\n        return x.accept(self)\n    def visit_leaf(self, x: Leaf) -> int:\n        return 0\n    def visit_node(self, x: Node) -> int:\n        return x.value + self.sum(x.left) + self.sum(x.right)\n\ndef equal(x: Tree, y: Tree) -> bool:\n    return EqualVisitor(x).equal(y)\n\nclass EqualVisitor(TreeVisitor[bool]):\n    def __init__(self, left: Tree) -> None:\n        self.left = left\n    def equal(self, right: Tree) -> bool:\n        return right.accept(self)\n    def visit_leaf(self, right: Leaf) -> bool:\n        return isinstance(self.left, Leaf)\n    def visit_node(self, right: Node) -> bool:\n        if isinstance(self.left, Node):\n            # our boolean stuff is crap\n            if (self.left.value == right.value and equal(self.left.left, right.left)\n                    and equal(self.left.right, right.right)):\n                return True\n        return False\n\ndef sum_tree(x: Tree) -> int:\n    return SumVisitor().sum(x)\n\ndef build(n: int) -> Tree:\n    if n == 0:\n        return Leaf()\n    return Node(n, build(n - 1), build(n - 1))\n\ndef bench_sum_tree(x: Tree) -> None:\n    for i in range(100000):\n        sum_tree(x)\ndef bench_equal_tree(x: Tree, y: Tree) -> None:\n    for i in range(100000):\n        equal(x, y)\n\n[file driver.py]\nfrom typing import Optional\nimport interpreted\nimport native\nfrom timeit import timeit\nfrom time import time\nimport os\nimport sys\n\n# Side test: some stuff about MROs and generics\nif sys.version_info[:3] > (3, 5, 2):\n    assert tuple(x.__name__ for x in interpreted.SumVisitor.mro()) == ('SumVisitor', 'TreeVisitor', 'Generic', 'object')\n    assert tuple(x.__name__ for x in native.SumVisitor.mro()) == ('SumVisitor', 'TreeVisitor', 'Generic', 'object')\n    assert str(native.TreeVisitor[native.T]) == \"native.TreeVisitor[~T]\"\n\nassert native.TreeVisitor.__name__ == \"TreeVisitor\"\nassert native.SumVisitor.__name__ == \"SumVisitor\"\n\ndef dumb_time(f):\n    t0 = time()\n    f()\n    t1 = time()\n    return t1 - t0\n\ndef basic_test(m):\n    tree = m.build(5)\n    tree2 = m.build(5)\n    tree2.right.right.right.value = 10\n    assert m.sum_tree(tree) == 57\n    assert m.equal(tree, tree)\n    assert not m.equal(tree, tree2)\n\n    assert isinstance(native.SumVisitor(), native.TreeVisitor)\n\n    return tree\n\ndef test(m):\n    tree = basic_test(m)\n\n    g = {**globals(), **locals()}\n    fsum = dumb_time(lambda: m.bench_sum_tree(tree))\n    feq = dumb_time(lambda: m.bench_equal_tree(tree, tree))\n    return fsum, feq\n\nbasic_test(native)\n\nif os.environ.get('MYPYC_RUN_BENCH') == '1':\n    nfsum, nfeq = test(native)\n    ifsum, ifeq = test(interpreted)\n    print(nfsum)\n    print(\"Sum speedup:\", ifsum/nfsum)\n    print(\"Equal speedup:\", ifeq/nfeq)\n"
  },
  {
    "path": "mypyc/test-data/run-bools.test",
    "content": "# Test cases for booleans (compile and run)\n\n[case testTrueAndFalse]\ndef t() -> bool:\n    return True\n\ndef f() -> bool:\n    return False\n[file driver.py]\nfrom native import t, f\nprint(t())\nprint(f())\n[out]\nTrue\nFalse\n\n[case testBoolOps]\nfrom __future__ import annotations\n\nfrom typing import Optional, Any\nMYPY = False\nif MYPY:\n    from mypy_extensions import i64\n\ndef f(x: bool) -> bool:\n    if x:\n        return False\n    else:\n        return True\n\ndef test_if() -> None:\n    assert f(True) is False\n    assert f(False) is True\n\ndef test_bitwise_and() -> None:\n    # Use eval() to avoid constant folding\n    t: bool = eval('True')\n    f: bool = eval('False')\n    assert t & t == True\n    assert t & f == False\n    assert f & t == False\n    assert f & f == False\n    t &= t\n    assert t == True\n    t &= f\n    assert t == False\n\ndef test_bitwise_or() -> None:\n    # Use eval() to avoid constant folding\n    t: bool = eval('True')\n    f: bool = eval('False')\n    assert t | t == True\n    assert t | f == True\n    assert f | t == True\n    assert f | f == False\n    t |= f\n    assert t == True\n    f |= t\n    assert f == True\n\ndef test_bitwise_xor() -> None:\n    # Use eval() to avoid constant folding\n    t: bool = eval('True')\n    f: bool = eval('False')\n    assert t ^ t == False\n    assert t ^ f == True\n    assert f ^ t == True\n    assert f ^ f == False\n    t ^= f\n    assert t == True\n    t ^= t\n    assert t == False\n    f ^= f\n    assert f == False\n\ndef test_isinstance_bool() -> None:\n    a = True\n    b = 1.0\n    c = 1\n    d = False\n    assert isinstance(a, bool) == True\n    assert isinstance(b, bool) == False\n    assert isinstance(c, bool) == False\n    assert isinstance(d, bool) == True\n\nclass C: pass\nclass D:\n    def __init__(self, b: bool) -> None:\n        self.b = b\n\n    def __bool__(self) -> bool:\n        return self.b\n\nclass E: pass\nclass F(E):\n    def __init__(self, b: bool) -> None:\n        self.b = b\n\n    def __bool__(self) -> bool:\n        return self.b\n\ndef optional_to_bool1(o: Optional[C]) -> bool:\n    return bool(o)\n\ndef optional_to_bool2(o: Optional[D]) -> bool:\n    return bool(o)\n\ndef optional_to_bool3(o: Optional[E]) -> bool:\n    return bool(o)\n\ndef test_optional_to_bool() -> None:\n    assert not optional_to_bool1(None)\n    assert optional_to_bool1(C())\n    assert not optional_to_bool2(None)\n    assert not optional_to_bool2(D(False))\n    assert optional_to_bool2(D(True))\n    assert not optional_to_bool3(None)\n    assert optional_to_bool3(E())\n    assert not optional_to_bool3(F(False))\n    assert optional_to_bool3(F(True))\n\ndef not_c(c: C) -> bool:\n    return not c\n\ndef not_c_opt(c: C | None) -> bool:\n    return not c\n\ndef not_d(d: D) -> bool:\n    return not d\n\ndef not_d_opt(d: D | None) -> bool:\n    return not d\n\ndef test_not_instance() -> None:\n    assert not not_c(C())\n    assert not_c_opt(None)\n    assert not not_c_opt(C())\n\n    assert not_d(D(False))\n    assert not not_d(D(True))\n    assert not_d_opt(D(False))\n    assert not_d_opt(None)\n    assert not not_d_opt(D(True))\n\ndef test_any_to_bool() -> None:\n    a: Any = int()\n    b: Any = a + 1\n    assert not bool(a)\n    assert bool(b)\n\ndef eq(x: bool, y: bool) -> bool:\n    return x == y\n\ndef ne(x: bool, y: bool) -> bool:\n    return x != y\n\ndef lt(x: bool, y: bool) -> bool:\n    return x < y\n\ndef le(x: bool, y: bool) -> bool:\n    return x <= y\n\ndef gt(x: bool, y: bool) -> bool:\n    return x > y\n\ndef ge(x: bool, y: bool) -> bool:\n    return x >= y\n\ndef test_comparisons() -> None:\n    for x in True, False:\n        for y in True, False:\n            x2: Any = x\n            y2: Any = y\n            assert eq(x, y) == (x2 == y2)\n            assert ne(x, y) == (x2 != y2)\n            assert lt(x, y) == (x2 < y2)\n            assert le(x, y) == (x2 <= y2)\n            assert gt(x, y) == (x2 > y2)\n            assert ge(x, y) == (x2 >= y2)\n\ndef eq_mixed(x: bool, y: int) -> bool:\n    return x == y\n\ndef neq_mixed(x: int, y: bool) -> bool:\n    return x != y\n\ndef lt_mixed(x: bool, y: int) -> bool:\n    return x < y\n\ndef gt_mixed(x: int, y: bool) -> bool:\n    return x > y\n\ndef test_mixed_comparisons() -> None:\n    for x in True, False:\n        for n in -(1 << 70), -123, 0, 1, 1753, 1 << 70:\n            assert eq_mixed(x, n) == (int(x) == n)\n            assert neq_mixed(n, x) == (n != int(x))\n            assert lt_mixed(x, n) == (int(x) < n)\n            assert gt_mixed(n, x) == (n > int(x))\n\ndef add(x: bool, y: bool) -> int:\n    return x + y\n\ndef add_mixed(b: bool, n: int) -> int:\n    return b + n\n\ndef sub_mixed(n: int, b: bool) -> int:\n    return n - b\n\ndef test_arithmetic() -> None:\n    for x in True, False:\n        for y in True, False:\n            assert add(x, y) == int(x) + int(y)\n        for n in -(1 << 70), -123, 0, 1, 1753, 1 << 70:\n            assert add_mixed(x, n) == int(x) + n\n            assert sub_mixed(n, x) == n - int(x)\n\ndef add_mixed_i64(b: bool, n: i64) -> i64:\n    return b + n\n\ndef sub_mixed_i64(n: i64, b: bool) -> i64:\n    return n - b\n\ndef test_arithmetic_i64() -> None:\n    for x in True, False:\n        for n in -(1 << 62), -123, 0, 1, 1753, 1 << 62:\n            assert add_mixed_i64(x, n) == int(x) + n\n            assert sub_mixed_i64(n, x) == n - int(x)\n\ndef eq_mixed_i64(x: bool, y: i64) -> bool:\n    return x == y\n\ndef neq_mixed_i64(x: i64, y: bool) -> bool:\n    return x != y\n\ndef lt_mixed_i64(x: bool, y: i64) -> bool:\n    return x < y\n\ndef gt_mixed_i64(x: i64, y: bool) -> bool:\n    return x > y\n\ndef test_mixed_comparisons_i64() -> None:\n    for x in True, False:\n        for n in -(1 << 62), -123, 0, 1, 1753, 1 << 62:\n            assert eq_mixed_i64(x, n) == (int(x) == n)\n            assert neq_mixed_i64(n, x) == (n != int(x))\n            assert lt_mixed_i64(x, n) == (int(x) < n)\n            assert gt_mixed_i64(n, x) == (n > int(x))\n\ndef not_object(x: object) -> bool:\n    return not x\n\ndef not_str(x: str) -> bool:\n    return not x\n\ndef not_int(x: int) -> bool:\n    return not x\n\ndef not_list(x: list[int]) -> bool:\n    return not x\n\ndef not_tuple(x: tuple[int, ...]) -> bool:\n    return not x\n\ndef not_dict(x: dict[str, int]) -> bool:\n    return not x\n\ndef test_not_object() -> None:\n    assert not_object(None)\n    assert not_object([])\n    assert not_object(0)\n    assert not not_object(1)\n    assert not not_object([1])\n\ndef test_not_str() -> None:\n    assert not_str(str())\n    assert not not_str('x' + str())\n\ndef test_not_int() -> None:\n    assert not_int(int('0'))\n    assert not not_int(int('1'))\n    assert not not_int(int('-1'))\n\ndef test_not_list() -> None:\n    assert not_list([])\n    assert not not_list([1])\n\ndef test_not_tuple() -> None:\n    assert not_tuple(())\n    assert not not_tuple((1,))\n\ndef test_not_dict() -> None:\n    assert not_dict({})\n    assert not not_dict({'x': 1})\n\ndef not_str_opt(x: str | None) -> bool:\n    return not x\n\ndef not_int_opt(x: int | None) -> bool:\n    return not x\n\ndef not_list_opt(x: list[int] | None) -> bool:\n    return not x\n\ndef not_tuple_opt(x: tuple[int, ...] | None) -> bool:\n    return not x\n\ndef not_dict_opt(x: dict[str, int] | None) -> bool:\n    return not x\n\ndef test_not_str_opt() -> None:\n    assert not_str_opt(str())\n    assert not_str_opt(None)\n    assert not not_str_opt('x' + str())\n\ndef test_not_int_opt() -> None:\n    assert not_int_opt(int('0'))\n    assert not_int_opt(None)\n    assert not not_int_opt(int('1'))\n    assert not not_int_opt(int('-1'))\n\ndef test_not_list_opt() -> None:\n    assert not_list_opt([])\n    assert not_list_opt(None)\n    assert not not_list_opt([1])\n\ndef test_not_tuple_opt() -> None:\n    assert not_tuple_opt(())\n    assert not_tuple_opt(None)\n    assert not not_tuple_opt((1,))\n\ndef test_not_dict_opt() -> None:\n    assert not_dict_opt({})\n    assert not_dict_opt(None)\n    assert not not_dict_opt({'x': 1})\n\n[case testBoolMixInt]\ndef test_mix() -> None:\n    y = False\n    print((y or 0) and True)\n[out]\n0\n\n[case testIsInstance]\nfrom typing import Any\ndef test_built_in() -> None:\n    true: Any = True\n    false: Any = False\n    assert isinstance(true, bool)\n    assert isinstance(false, bool)\n\n    assert not isinstance(set(), bool)\n    assert not isinstance((), bool)\n    assert not isinstance((True, False), bool)\n    assert not isinstance({False, True}, bool)\n    assert not isinstance(int() + 1, bool)\n    assert not isinstance(str() + 'False', bool)\n\ndef test_user_defined() -> None:\n    from userdefinedbool import bool\n\n    b: Any = True\n    assert isinstance(bool(), bool)\n    assert not isinstance(b, bool)\n\n[file userdefinedbool.py]\nclass bool:\n    pass\n"
  },
  {
    "path": "mypyc/test-data/run-bytes.test",
    "content": "# Bytes test cases (compile and run)\n\n[case testBytesBasics]\n# Note: Add tests for additional operations to testBytesOps or in a new test case\n\ndef f(x: bytes) -> bytes:\n    return x\n\ndef eq(a: bytes, b: bytes) -> bool:\n    return a == b\n\ndef neq(a: bytes, b: bytes) -> bool:\n    return a != b\n[file driver.py]\nfrom native import f, eq, neq\nassert f(b'123') == b'123'\nassert f(b'\\x07 \\x0b \" \\t \\x7f \\xf0') == b'\\x07 \\x0b \" \\t \\x7f \\xf0'\nassert eq(b'123', b'123')\nassert not eq(b'123', b'1234')\nassert not eq(b'123', b'124')\nassert not eq(b'123', b'223')\nassert neq(b'123', b'1234')\ntry:\n    f('x')\n    assert False\nexcept TypeError:\n    pass\n\n[case testBytesInit]\ndef test_bytes_init() -> None:\n    b1 = bytes([5])\n    assert b1 == b'\\x05'\n    b2 = bytes([5, 10, 12])\n    assert b2 == b'\\x05\\n\\x0c'\n    b3 = bytes(bytearray(b'foo'))\n    assert b3 == b'foo'\n    b4 = bytes(b'aaa')\n    assert b4 == b'aaa'\n    b5 = bytes(5)\n    assert b5 == b'\\x00\\x00\\x00\\x00\\x00'\n    try:\n        bytes('x')\n        assert False\n    except TypeError:\n        pass\n\n[case testBytesOps]\nfrom testutil import assertRaises\n\ndef test_indexing() -> None:\n    # Use bytes() to avoid constant folding\n    b = b'asdf' + bytes()\n    assert b[0] == 97\n    assert b[1] == 115\n    assert b[3] == 102\n    assert b[-1] == 102\n    b = b'\\xae\\x80\\xfe\\x15' + bytes()\n    assert b[0] == 174\n    assert b[1] == 128\n    assert b[2] == 254\n    assert b[3] == 21\n    assert b[-4] == 174\n    with assertRaises(IndexError, \"index out of range\"):\n        b[4]\n    with assertRaises(IndexError, \"index out of range\"):\n        b[-5]\n    with assertRaises(IndexError, \"index out of range\"):\n        b[2**26]\n\ndef test_concat() -> None:\n    b1 = b'123' + bytes()\n    b2 = b'456' + bytes()\n    assert b1 + b2 == b'123456'\n    b3 = b1 + b2\n    b3 = b3 + b1\n    assert b3 == b'123456123'\n    assert b1 == b'123'\n    assert b2 == b'456'\n    assert type(b1) == bytes\n    assert type(b2) == bytes\n    assert type(b3) == bytes\n    brr1 = bytearray(3)\n    brr2 = bytearray(range(5))\n    b4 = b1 + brr1\n    assert b4 == b'123\\x00\\x00\\x00'\n    assert type(brr1) == bytearray\n    assert type(b4) == bytes\n    brr3 = brr1 + brr2\n    assert brr3 == bytearray(b'\\x00\\x00\\x00\\x00\\x01\\x02\\x03\\x04')\n    assert len(brr3) == 8\n    assert type(brr3) == bytearray\n    brr3 = brr3 + bytearray([10])\n    assert brr3 == bytearray(b'\\x00\\x00\\x00\\x00\\x01\\x02\\x03\\x04\\n')\n    b5 = brr2 + b2\n    assert b5 == bytearray(b'\\x00\\x01\\x02\\x03\\x04456')\n    assert type(b5) == bytearray\n    b6 = b2 + brr2\n    assert b6 == b'456\\x00\\x01\\x02\\x03\\x04'\n    assert type(b6) == bytes\n\ndef test_join() -> None:\n    seq = (b'1', b'\"', b'\\xf0')\n    assert b'\\x07'.join(seq) == b'1\\x07\"\\x07\\xf0'\n    assert b', '.join(()) == b''\n    assert b', '.join([bytes() + b'ab']) == b'ab'\n    assert b', '.join([bytes() + b'ab', b'cd']) == b'ab, cd'\n\ndef test_len() -> None:\n    # Use bytes() to avoid constant folding\n    b = b'foo' + bytes()\n    assert len(b) == 3\n    assert len(bytes()) == 0\n\ndef test_ord() -> None:\n    assert ord(b'a') == ord('a')\n    assert ord(b'a' + bytes()) == ord('a')\n    assert ord(b'\\x00') == 0\n    assert ord(b'\\x00' + bytes()) == 0\n    assert ord(b'\\xfe') == 254\n    assert ord(b'\\xfe' + bytes()) == 254\n\n    with assertRaises(TypeError):\n        ord(b'aa')\n    with assertRaises(TypeError):\n        ord(b'')\n\ndef test_ord_bytesarray() -> None:\n    assert ord(bytearray(b'a')) == ord('a')\n    assert ord(bytearray(b'\\x00')) == 0\n    assert ord(bytearray(b'\\xfe')) == 254\n\n    with assertRaises(TypeError):\n        ord(bytearray(b'aa'))\n    with assertRaises(TypeError):\n        ord(bytearray(b''))\n\ndef test_multiply() -> None:\n    # Use bytes() and int() to avoid constant folding\n    b = b'ab' + bytes()\n    zero = int()\n    one = 1 + zero\n    three = 3 + zero\n    neg_one = -1 + zero\n\n    assert b * zero == b''\n    assert b * one == b'ab'\n    assert b * three == b'ababab'\n    assert b * neg_one == b''\n    assert zero * b == b''\n    assert one * b == b'ab'\n    assert three * b == b'ababab'\n    assert neg_one * b == b''\n\n    # Test with empty bytes\n    empty = bytes()\n    five = 5 + zero\n    assert empty * five == b''\n    assert five * empty == b''\n\n    # Test with single byte\n    single = b'\\xff' + bytes()\n    four = 4 + zero\n    assert single * four == b'\\xff\\xff\\xff\\xff'\n    assert four * single == b'\\xff\\xff\\xff\\xff'\n\n    # Test type preservation\n    two = 2 + zero\n    result = b * two\n    assert type(result) == bytes\n\ndef test_translate() -> None:\n    # Identity translation table (fast path - exact bytes)\n    identity = bytes(range(256))\n    b = b'hello world' + bytes()\n    assert b.translate(identity) == b'hello world'\n\n    # ROT13-like translation for lowercase letters\n    table = bytearray(range(256))\n    for i in range(ord('a'), ord('z') + 1):\n        table[i] = ord('a') + (i - ord('a') + 13) % 26\n    table_bytes = bytes(table)\n    assert b'hello'.translate(table_bytes) == b'uryyb'\n    assert (b'abc' + bytes()).translate(table_bytes) == b'nop'\n\n    # Test with special characters\n    assert b'\\x00\\x01\\xff'.translate(identity) == b'\\x00\\x01\\xff'\n\n    # Test with bytearray table (slow path - fallback to Python method)\n    bytearray_table = bytearray(range(256))\n    assert b'hello'.translate(bytearray_table) == b'hello'\n    # Modify bytearray table to uppercase\n    for i in range(ord('a'), ord('z') + 1):\n        bytearray_table[i] = ord('A') + (i - ord('a'))\n    assert b'hello world'.translate(bytearray_table) == b'HELLO WORLD'\n    assert (b'test' + bytes()).translate(bytearray_table) == b'TEST'\n\n    # Test error on wrong table size\n    with assertRaises(ValueError, \"translation table must be 256 characters long\"):\n        b'test'.translate(b'short')\n    with assertRaises(ValueError, \"translation table must be 256 characters long\"):\n        b'test'.translate(bytes(100))\n\ndef test_startswith() -> None:\n    # Test default behavior\n    test = b'some string'\n    assert test.startswith(b'some')\n    assert test.startswith(b'some string')\n    assert not test.startswith(b'other')\n    assert not test.startswith(b'some string but longer')\n\n    # Test empty cases\n    assert test.startswith(b'')\n    assert b''.startswith(b'')\n    assert not b''.startswith(test)\n\n    # Test bytearray to verify slow paths\n    assert test.startswith(bytearray(b'some'))\n    assert not test.startswith(bytearray(b'other'))\n\n    test2 = bytearray(b'some string')\n    assert test2.startswith(b'some')\n    assert not test2.startswith(b'other')\n\ndef test_endswith() -> None:\n    # Test default behavior\n    test = b'some string'\n    assert test.endswith(b'string')\n    assert test.endswith(b'some string')\n    assert not test.endswith(b'other')\n    assert not test.endswith(b'some string but longer')\n\n    # Test empty cases\n    assert test.endswith(b'')\n    assert b''.endswith(b'')\n    assert not b''.endswith(test)\n\n    # Test bytearray to verify slow paths\n    assert test.endswith(bytearray(b'string'))\n    assert not test.endswith(bytearray(b'other'))\n\n    test2 = bytearray(b'some string')\n    assert test2.endswith(b'string')\n    assert not test2.endswith(b'other')\n\n[case testBytesSlicing]\ndef test_bytes_slicing() -> None:\n    b = b'abcdefg'\n    zero = int()\n    ten = 10 + zero\n    two = 2 + zero\n    five = 5 + zero\n    seven = 7 + zero\n    assert b[:ten] == b'abcdefg'\n    assert b[0:seven] == b'abcdefg'\n    assert b[0:(len(b)+1)] == b'abcdefg'\n    assert b[two:five] == b'cde'\n    assert b[two:two] == b''\n    assert b[-two:-two] == b''\n    assert b[-ten:(-ten+1)] == b''\n    assert b[:-two] == b'abcde'\n    assert b[:two] == b'ab'\n    assert b[:] == b'abcdefg'\n    assert b[-two:] == b'fg'\n    assert b[zero:] == b'abcdefg'\n    assert b[:zero] == b''\n    assert b[-ten:] == b'abcdefg'\n    assert b[-ten:ten] == b'abcdefg'\n    big_ints = [1000 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000, 2**24, 2**63]\n    for big_int in big_ints:\n        assert b[1:big_int] == b'bcdefg'\n        assert b[big_int:] == b''\n        assert b[-big_int:-1] == b'abcdef'\n        assert b[-big_int:big_int] == b'abcdefg'\n        assert type(b[-big_int:-1]) == bytes\n    assert type(b[-ten:]) == bytes\n    assert type(b[:]) == bytes\n\n[case testBytearrayBasics]\nfrom typing import Any\n\nfrom testutil import assertRaises\n\ndef test_basics() -> None:\n    brr0 = bytearray()\n    assert brr0 == bytearray(b'')\n    assert brr0 == b''\n    assert len(brr0) == 0\n    brr1 = bytearray(3)\n    assert brr1 == bytearray(b'\\x00\\x00\\x00')\n    assert brr1 == b'\\x00\\x00\\x00'\n    l = [10, 20, 30, 40]\n    brr2 = bytearray(l)\n    assert brr2 == bytearray(b'\\n\\x14\\x1e(')\n    assert brr2 == b'\\n\\x14\\x1e('\n    brr3 = bytearray(range(5))\n    assert brr3 == bytearray(b'\\x00\\x01\\x02\\x03\\x04')\n    assert brr3 == b'\\x00\\x01\\x02\\x03\\x04'\n    brr4 = bytearray('string', 'utf-8')\n    assert brr4 == bytearray(b'string')\n    assert brr4 == b'string'\n    assert len(brr1) == 3\n    assert len(brr2) == 4\n\ndef test_bytearray_type_object() -> None:\n    b = bytearray()\n    assert type(b) is bytearray\n\ndef fb(b: bytes) -> str:\n    return \"xy\"\n\ndef test_bytearray_passed_into_bytes() -> None:\n    brr1: Any = bytearray()\n    with assertRaises(TypeError, \"bytes object expected; got bytearray\"):\n        fb(brr1)\n    with assertRaises(TypeError, \"bytes object expected; got bytearray\"):\n        b: bytes = brr1\n\ndef fba(brr: bytearray) -> str:\n    return \"xy\"\n\ndef test_bytes_passed_into_bytearray() -> None:\n    b: Any = b\"foo\"\n    with assertRaises(TypeError, \"bytearray object expected; got bytes\"):\n        fba(b)\n    with assertRaises(TypeError, \"bytearray object expected; got bytes\"):\n        brr: bytearray = b\n\n[case testBytearraySlicing]\ndef test_bytearray_slicing() -> None:\n    b = bytearray(b'abcdefg')\n    zero = int()\n    ten = 10 + zero\n    two = 2 + zero\n    five = 5 + zero\n    seven = 7 + zero\n    assert b[:ten] == b'abcdefg'\n    assert b[0:seven] == b'abcdefg'\n    assert b[two:five] == b'cde'\n    assert b[two:two] == b''\n    assert b[-two:-two] == b''\n    assert b[-ten:(-ten+1)] == b''\n    assert b[:-two] == b'abcde'\n    assert b[:two] == b'ab'\n    assert b[:] == b'abcdefg'\n    assert b[-two:] == b'fg'\n    assert b[zero:] == b'abcdefg'\n    assert b[:zero] == b''\n    assert b[-ten:] == b'abcdefg'\n    assert b[-ten:ten] == b'abcdefg'\n    big_ints = [1000 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000, 2**24, 2**63]\n    for big_int in big_ints:\n        assert b[1:big_int] == b'bcdefg'\n        assert b[big_int:] == b''\n        assert b[-big_int:-1] == b'abcdef'\n        assert b[-big_int:big_int] == b'abcdefg'\n        assert type(b[-big_int:-1]) == bytearray\n    assert type(b[-ten:]) == bytearray\n    assert type(b[:]) == bytearray\n\n[case testBytearrayIndexing]\nfrom testutil import assertRaises\n\ndef test_bytearray_indexing() -> None:\n    b = bytearray(b'\\xae\\x80\\xfe\\x15')\n    assert b[0] == 174\n    assert b[1] == 128\n    assert b[2] == 254\n    assert b[3] == 21\n    assert b[-4] == 174\n    with assertRaises(IndexError, \"index out of range\"):\n        b[4]\n    with assertRaises(IndexError, \"index out of range\"):\n        b[-5]\n    b2 = bytearray([175, 255, 128, 22])\n    assert b2[0] == 175\n    assert b2[1] == 255\n    assert b2[-1] == 22\n    assert b2[2] == 128\n    with assertRaises(ValueError, \"byte must be in range(0, 256)\"):\n        b2[0] = -1\n    with assertRaises(ValueError, \"byte must be in range(0, 256)\"):\n        b2[0] = 256\n\n[case testBytesJoin]\nfrom typing import Any\nfrom testutil import assertRaises\nfrom a import bytes_subclass\n\ndef test_bytes_join() -> None:\n    assert b' '.join([b'a', b'b']) == b'a b'\n    assert b' '.join([]) == b''\n\n    y: bytes = bytes_subclass()\n    assert y.join([]) == b'spook'\n\n    n: Any = 5\n    with assertRaises(TypeError, \"can only join an iterable\"):\n        assert b' '.join(n)\n\n[file a.py]\nclass bytes_subclass(bytes):\n    def join(self, iter):\n        return b'spook'\n\n[case testBytesFormatting]\nfrom testutil import assertRaises\n\n# https://www.python.org/dev/peps/pep-0461/\ndef test_bytes_formatting() -> None:\n    val = 10\n    assert b\"%x\" % val == b'a'\n    assert b'%4x' % val == b'   a'\n    assert b'%#4x' % val == b' 0xa'\n    assert b'%04X' % val == b'000A'\n    assert b'%d' % val == b'10'\n    assert b'%d' % (val + 2) == b'12'\n    assert b'%d' % 0 == b'0'\n    assert b'%d' % -3 == b'-3'\n    assert b'folded: %d' % (4 - 2) == b'folded: 2'\n\n    large_num = 2**65\n    assert b'number: %d' % large_num == b'number: 36893488147419103232'\n    assert b'negative integer: %d' % (-large_num) == b'negative integer: -36893488147419103232'\n\n    assert b'%c' % 48 == b'0'\n    assert b'%c' % b'a' == b'a'\n    assert b'%c%c' % (48, b'a') == b'0a'\n\n    assert b'%b' % b'abc' == b'abc'\n    assert b'%b' % 'some string'.encode('utf8') == b'some string'\n\n    assert b'%a' % 3.14 == b'3.14'\n    assert b'%a' % b'abc' == b\"b'abc'\"\n    assert b'%a' % 'def' == b\"'def'\"\n\ndef test_bytes_formatting_2() -> None:\n    var = b'bb'\n    num = 10\n    assert b'aaa%bbbb%s' % (var, var) == b'aaabbbbbbb'\n    assert b'aaa%dbbb%b' % (num, var) == b'aaa10bbbbb'\n    assert b'%s%b' % (var, var) == b'bbbb'\n    assert b'%b' % bytes() == b''\n    assert b'%b' % b'' == b''\n\n    assert b'\\xff%s' % b'\\xff' == b'\\xff\\xff'\n    assert b'\\xff%b' % '你好'.encode() == b'\\xff\\xe4\\xbd\\xa0\\xe5\\xa5\\xbd'\n\n    aa = b'\\xe4\\xbd\\xa0\\xe5\\xa5\\xbd%b' % b'\\xe4\\xbd\\xa0\\xe5\\xa5\\xbd'\n    assert aa == b'\\xe4\\xbd\\xa0\\xe5\\xa5\\xbd\\xe4\\xbd\\xa0\\xe5\\xa5\\xbd'\n    assert aa.decode() == '你好你好'\n[typing fixtures/typing-full.pyi]\n\n\nclass A:\n    def __bytes__(self):\n        return b'aaa'\n\ndef test_bytes_dunder() -> None:\n    assert b'%b' % A() == b'aaa'\n    assert b'%s' % A() == b'aaa'\n\n[case testIsInstance]\nfrom copysubclass import subbytes, subbytearray\nfrom typing import Any\ndef test_bytes() -> None:\n    b: Any = b''\n    assert isinstance(b, bytes)\n    assert isinstance(b + b'123', bytes)\n    assert isinstance(b + b'\\xff', bytes)\n    assert isinstance(subbytes(), bytes)\n    assert isinstance(subbytes(b + b'123'), bytes)\n    assert isinstance(subbytes(b + b'\\xff'), bytes)\n\n    assert not isinstance(set(), bytes)\n    assert not isinstance((), bytes)\n    assert not isinstance((b'1',b'2',b'3'), bytes)\n    assert not isinstance({b'a',b'b'}, bytes)\n    assert not isinstance(int() + 1, bytes)\n    assert not isinstance(str() + 'a', bytes)\n\ndef test_user_defined_bytes() -> None:\n    from userdefinedbytes import bytes\n\n    assert isinstance(bytes(), bytes)\n    assert not isinstance(b'\\x7f', bytes)\n\ndef test_bytearray() -> None:\n    assert isinstance(bytearray(), bytearray)\n    assert isinstance(bytearray(b'123'), bytearray)\n    assert isinstance(bytearray(b'\\xff'), bytearray)\n    assert isinstance(subbytearray(), bytearray)\n    assert isinstance(subbytearray(bytearray(b'123')), bytearray)\n    assert isinstance(subbytearray(bytearray(b'\\xff')), bytearray)\n\n    assert not isinstance(set(), bytearray)\n    assert not isinstance((), bytearray)\n    assert not isinstance((bytearray(b'1'),bytearray(b'2'),bytearray(b'3')), bytearray)\n    assert not isinstance([bytearray(b'a'),bytearray(b'b')], bytearray)\n    assert not isinstance(int() + 1, bytearray)\n    assert not isinstance(str() + 'a', bytearray)\n\n[file copysubclass.py]\nclass subbytes(bytes):\n    pass\n\nclass subbytearray(bytearray):\n    pass\n\n[file userdefinedbytes.py]\nclass bytes:\n    pass\n\n[case testBytesOptionalEquality]\nfrom __future__ import annotations\n\ndef eq_b_opt_b(x: bytes | None, y: bytes) -> bool:\n    return x == y\n\ndef ne_b_b_opt(x: bytes, y: bytes | None) -> bool:\n    return x != y\n\ndef test_optional_eq() -> None:\n    b = b'x'\n    assert eq_b_opt_b(b, b)\n    assert eq_b_opt_b(b + bytes([int()]), b + bytes([int()]))\n\n    assert not eq_b_opt_b(b'x', b'y')\n    assert not eq_b_opt_b(b'y', b'x')\n    assert not eq_b_opt_b(None, b'x')\n\ndef test_optional_ne() -> None:\n    b = b'x'\n    assert not ne_b_b_opt(b, b)\n    assert not ne_b_b_opt(b + b'y', b + bytes() + b'y')\n\n    assert ne_b_b_opt(b'x', b'y')\n    assert ne_b_b_opt(b'y', b'x')\n    assert ne_b_b_opt(b'x', None)\n"
  },
  {
    "path": "mypyc/test-data/run-classes.test",
    "content": "[case testEmptyClass]\nclass Empty: pass\n\ndef f(e: Empty) -> Empty:\n    return e\n\nclass EmptyEllipsis: ...\n\ndef g(e: EmptyEllipsis) -> EmptyEllipsis:\n    return e\n[file driver.py]\nfrom native import Empty, EmptyEllipsis, f, g\n\nprint(isinstance(Empty, type))\nprint(Empty)\nprint(str(Empty())[:20])\n\ne = Empty()\nprint(f(e) is e)\n\nprint(isinstance(EmptyEllipsis, type))\nprint(EmptyEllipsis)\nprint(str(EmptyEllipsis())[:28])\n\ne2 = EmptyEllipsis()\nprint(g(e2) is e2)\n[out]\nTrue\n<class 'native.Empty'>\n<native.Empty object\nTrue\nTrue\n<class 'native.EmptyEllipsis'>\n<native.EmptyEllipsis object\nTrue\n\n[case testClassWithFields]\nclass C:\n    x: int\n    y: int\n    z: 'D'\nclass D:\n    pass\n[file driver.py]\nfrom native import C\nfrom testutil import assertRaises\n\nc = C()\nassert not hasattr(c, 'x')\nassert not hasattr(c, 'y')\nc.x = 1\nc.y = 2\nprint(c.x)\nprint(c.y)\nc.x = 10**30\nprint(c.x)\nc.x = 10**30+1\nprint(c.x)\nassert hasattr(c, 'x')\nassert hasattr(c, 'y')\nassert not hasattr(c, 'z')\nwith assertRaises(AttributeError, \"'C' object attribute 'x' cannot be deleted\"):\n    del c.x\nassert hasattr(c, 'x')\nassert hasattr(c, 'y')\nwith assertRaises(AttributeError, \"'C' object attribute 'y' cannot be deleted\"):\n    del c.y\nassert hasattr(c, 'y')\nc.x = 10**30+2\nprint(c.x)\nassert hasattr(c, 'x')\n[out]\n1\n2\n1000000000000000000000000000000\n1000000000000000000000000000001\n1000000000000000000000000000002\n\n[case testTypedDictWithFields]\nimport collections\nimport json\nfrom typing import TypedDict\nclass C(TypedDict):\n    x: collections.deque\n    spam: json.JSONDecoder\n[file driver.py]\nfrom native import C\nfrom collections import deque\nfrom json import JSONDecoder\n\nprint(C.__annotations__[\"x\"] is deque)\nprint(C.__annotations__[\"spam\"] is JSONDecoder)\n[typing fixtures/typing-full.pyi]\n[out]\nTrue\nTrue\n\n[case testTypedDictWithFieldsAs]\nimport json as _json\nfrom typing import TypedDict\n\nclass C(TypedDict):\n    spam: _json.JSONDecoder\n[file driver.py]\nfrom native import C\nfrom json import JSONDecoder\n\nprint(C.__annotations__[\"spam\"] is JSONDecoder)\n[typing fixtures/typing-full.pyi]\n[out]\nTrue\n\n[case testTypedDictWithFieldsFrom]\nfrom json import decoder\nfrom typing import TypedDict\n\nclass C(TypedDict):\n    spam: decoder.JSONDecoder\n[file driver.py]\nfrom native import C\nfrom json import JSONDecoder\n\nprint(C.__annotations__[\"spam\"] is JSONDecoder)\n[typing fixtures/typing-full.pyi]\n[out]\nTrue\n\n[case testClassWithDeletableAttributes]\nfrom typing import Any, cast\nfrom testutil import assertRaises\n\nclass C:\n    __deletable__ = ['x', 'y']\n    x: int\n    y: int\n    z: int\n\ndef test_delete() -> None:\n    c = C()\n    c.x = 1\n    c.y = 2\n    c.z = 3\n    del c.x\n    del c.y\n    assert c.z == 3\n    with assertRaises(AttributeError, \"attribute 'x' of 'C' undefined\"):\n        c.x\n    with assertRaises(AttributeError, \"attribute 'y' of 'C' undefined\"):\n        c.y\n\ndef test_delete_any() -> None:\n    c: Any = C()\n    c.x = 1\n    c.y = 2\n    c.z = 3\n    del c.x\n    del c.y\n    with assertRaises(AttributeError, \"'C' object attribute 'z' cannot be deleted\"):\n        del c.z\n    assert c.z == 3\n    with assertRaises(AttributeError):\n        c.x\n    with assertRaises(AttributeError):\n        c.y\n\nclass Base:\n    __deletable__ = ['a']\n    a: int\n    b: int\n\nclass Deriv(Base):\n    __deletable__ = ('c',)\n    c: str\n    d: str\n\ndef test_delete_with_inheritance() -> None:\n    d = Deriv()\n    d.a = 0\n    d.b = 1\n    d.c = 'X'\n    d.d = 'Y'\n    del d.a\n    with assertRaises(AttributeError):\n        d.a\n    del d.c\n    with assertRaises(AttributeError):\n        d.c\n    assert d.b == 1\n    assert d.d == 'Y'\n\ndef test_delete_with_inheritance_any() -> None:\n    d: Any = Deriv()\n    d.a = 0\n    d.b = 1\n    d.c = 'X'\n    d.d = 'Y'\n    del d.a\n    with assertRaises(AttributeError):\n        d.a\n    del d.c\n    with assertRaises(AttributeError):\n        d.c\n    with assertRaises(AttributeError):\n        del d.b\n    assert d.b == 1\n    with assertRaises(AttributeError):\n        del d.d\n    assert d.d == 'Y'\n\ndef decorator(cls):\n    return cls\n\n@decorator\nclass NonExt:\n    x: int\n    y: int\n\n    # No effect in a non-native class\n    __deletable__ = ['x']\n\ndef test_non_ext() -> None:\n    n = NonExt()\n    n.x = 2\n    n.y = 3\n    del n.x\n    del n.y\n    with assertRaises(AttributeError):\n        n.x\n    with assertRaises(AttributeError):\n        n.y\n\ndef test_non_ext_any() -> None:\n    n: Any = NonExt()\n    n.x = 2\n    n.y = 3\n    del n.x\n    del n.y\n    with assertRaises(AttributeError):\n        n.x\n    with assertRaises(AttributeError):\n        n.y\n\n[case testNonExtMisc]\nfrom typing import Any, overload\n\ndef decorator(cls) -> Any:\n    return cls\n\n@decorator\nclass C:\n    def __init__(self) -> None:\n        self.c = 3\n\n    def get_c(self) -> int:\n        return self.c\n\n@decorator\nclass B(C):\n    def __init__(self) -> None:\n        super().__init__()\n        self.b = 2\n\n    def get_b(self) -> int:\n        return self.b\n\n@decorator\nclass A(B):\n    def __init__(self) -> None:\n        super().__init__()\n        self.a = 1\n\n    @classmethod\n    def constant(cls) -> int:\n        return 4\n\n    def get_a(self) -> int:\n        return self.a\n\n@decorator\nclass Overload:\n    @overload\n    def get(self, index: int) -> int: ...\n\n    @overload\n    def get(self, index: str) -> str: ...\n\n    def get(self, index: Any) -> Any:\n        return index\n\ndef get(c: Overload, s: str) -> str:\n    return c.get(s)\n\n@decorator\nclass Var:\n    x = 'xy'\n\ndef get_class_var() -> str:\n    return Var.x\n\n[file driver.py]\nfrom native import A, Overload, get, get_class_var\na = A()\nassert a.a == 1\nassert a.b == 2\nassert a.c == 3\nassert a.get_a() == 1\nassert a.get_b() == 2\nassert a.get_c() == 3\nassert A.constant() == 4\n\no = Overload()\nassert get(o, \"test\") == \"test\"\nassert o.get(20) == 20\n\nassert get_class_var() == 'xy'\n\n[case testEnum]\nfrom enum import Enum\n\nclass TestEnum(Enum):\n    _order_ = \"a b\"\n    a = 1\n    b = 2\n\n    @classmethod\n    def test(cls) -> int:\n        return 3\n\nassert TestEnum.test() == 3\n\nimport enum\n\nclass Pokemon(enum.Enum):\n    magikarp = 1\n    squirtle = 2\n    slowbro = 3\n\nassert Pokemon.magikarp.value == 1\nassert Pokemon.squirtle.name == 'squirtle'\n\n[file other.py]\n# Force a multi-module test to make sure we can compile multi-file with\n# non-extension classes\n\n[file driver.py]\nimport sys\n# \"_order_\" isn't supported in 3.5\nif sys.version_info[:2] > (3, 5):\n    from native import TestEnum\n    assert TestEnum.a.name == 'a'\n    assert TestEnum.a.value == 1\n    assert TestEnum.b.name == 'b'\n    assert TestEnum.b.value == 2\n\n[case testRunSuperYieldFromDict]\nfrom typing import Any, Iterator\n\nclass DictSubclass(dict):\n    def items(self) -> Iterator[Any]:\n        yield 1\n        yield from super().items()\n\ndef test_sub_dict() -> None:\n    assert list(DictSubclass().items()) == [1]\n\n[case testGetAttribute]\nclass C:\n    x: int\n    y: int\n\ndef getx(c: C) -> int:\n    return c.x\n\ndef gety(c: C) -> int:\n    return c.y\n[file driver.py]\nfrom native import C, getx, gety\nc = C()\nc.x = 10**30\nc.y = 10**30 + 1\nprint(getx(c))\nprint(gety(c))\n[out]\n1000000000000000000000000000000\n1000000000000000000000000000001\n\n[case testSetAttribute]\nclass C:\n    x: int\n    y: int\n\ndef setx(c: C, v: int) -> None:\n    c.x = v\n\ndef sety(c: C, v: int) -> None:\n    c.y = v\n[file driver.py]\nfrom native import C, setx, sety\nc = C()\nsetx(c, 10**30)\nsety(c, 10**30 + 1)\nprint(c.x)\nprint(c.y)\nsetx(c, 4)\nsety(c, 5)\nprint(c.x, c.y)\nsetx(c, 10**30 + 2)\nsety(c, 10**30 + 3)\nprint(c.x)\nprint(c.y)\n[out]\n1000000000000000000000000000000\n1000000000000000000000000000001\n4 5\n1000000000000000000000000000002\n1000000000000000000000000000003\n\n[case testAttributeTypes]\nfrom typing import List, Tuple\nclass C:\n    a: List[int]\n    b: bool\n    c: C\n    d: object\n    e: int\n\ndef setattrs(o: C, a: List[int], b: bool, c: C) -> None:\n    o.a = a\n    o.b = b\n    o.c = c\n\ndef getattrs(o: C) -> Tuple[List[int], bool, C]:\n    return o.a, o.b, o.c\n[file driver.py]\nfrom native import C, setattrs, getattrs\nfrom testutil import assertRaises\n\nc1 = C()\nc2 = C()\naa = [2]\nsetattrs(c1, aa, True, c2)\na, b, c = getattrs(c1)\nassert a is aa\nassert b is True\nassert c is c2\n\no = object()\nc1.d = o\nassert c1.d is o\n\nc3 = C()\nwith assertRaises(AttributeError, \"attribute 'a' of 'C' undefined\"):\n    c3.a\nwith assertRaises(AttributeError, \"attribute 'b' of 'C' undefined\"):\n    c3.b\nwith assertRaises(AttributeError, \"attribute 'c' of 'C' undefined\"):\n    c3.c\nwith assertRaises(AttributeError, \"attribute 'd' of 'C' undefined\"):\n    c3.d\nwith assertRaises(AttributeError, \"attribute 'e' of 'C' undefined\"):\n    c3.e\n\n[case testInitMethodWithMissingNoneReturnAnnotation]\nclass C:\n    def __init__(self):\n        self.x = 42\n[file driver.py]\nfrom native import C\nc = C()\nassert c is not None\nassert c.x == 42\n\n[case testConstructClassWithDefaultConstructor]\nclass C:\n    a: int\n    b: int\n\ndef f() -> C:\n    c = C()\n    c.a = 13\n    return c\n[file driver.py]\nfrom native import f, C\nc = f()\nassert c.a == 13\nassert type(c) == C\nassert not hasattr(c, 'b')\n\n[case testCastUserClass]\nfrom typing import List\n\nclass C:\n    x: int\n\ndef f(a: List[C]) -> C:\n    return a[0]\n[file driver.py]\nfrom native import f, C\nc = C()\nassert f([c]) is c\n\n[case testClass1]\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\n    def foo(self) -> int:\n        return self.x+1\ndef foo() -> int:\n    a = A(20)\n    return a.foo()\n[file driver.py]\nfrom native import A, foo\na = A(10)\nassert a.foo() == 11\nassert foo() == 21\n\n[case testClassKwargs]\nclass X:\n    def __init__(self, msg: str, **variables: int) -> None:\n         self.msg = msg\n         self.variables = variables\n\n[file driver.py]\nimport traceback\nfrom native import X\nx = X('hello', a=0, b=1)\nassert x.msg == 'hello'\nassert x.variables == {'a': 0, 'b': 1}\ntry:\n    X('hello', msg='hello')\nexcept TypeError as e:\n    print(f\"{type(e).__name__}: {e}\")\n[out]\nTypeError: argument for __init__() given by name ('msg') and position (1)\n\n[case testGenericClass]\nfrom typing import TypeVar, Generic, Sequence\nT = TypeVar('T')\nclass C(Generic[T]):\n    x: T\n    def __init__(self, x: T) -> None:\n        self.x = x\n    def get(self) -> T:\n        return self.x\n    def set(self, y: T) -> None:\n        self.x = y\n\n# Test subclassing generic classes both with and without a generic param\nclass A(Sequence[int]):\n    pass\nclass B(Sequence[T]):\n    pass\n\ndef f(c: C[int]) -> int:\n    y = c.get()\n    d = C[int](2)\n    c.set(c.get() + 1 + d.get())\n    c.x = c.x + 2\n    return c.x\n\n[file driver.py]\nfrom native import C, f\nc = C(6)\nassert f(c) == 11\nc.x = 'x'\nassert c.x == 'x'\nc.set([1])\nassert c.x == [1]\nassert c.get() == [1]\n\n[case testSubclass1]\nfrom typing import Tuple\n\nclass A:\n    def __init__(self) -> None:\n        self.x = 10\n    def hi(self, suffix: str) -> str:\n        return str(self.x) + suffix\nclass B(A):\n    def __init__(self) -> None:\n        self.x = 20\n        self.y = 'world'\n    def hi(self, suffix: str) -> str:\n        return 'hello ' + str(self.y) + suffix\n\ndef use_a(x: A) -> Tuple[int, str]:\n    return (x.x, x.hi(''))\ndef use_b(x: B) -> str:\n    return x.hi('')\n\n[file driver.py]\nfrom native import A, B, use_a, use_b\na = A()\nb = B()\nassert use_a(a) == (10, '10')\nassert use_a(b) == (20, 'hello world')\nassert a.x == 10\nassert b.x == 20\nassert b.y == 'world'\nassert a.hi('!') == '10!'\nassert b.hi('!') == 'hello world!'\nassert use_b(b) == 'hello world'\n\n[case testSubclassSpecialize1]\nclass A:\n    def foo(self, x: int) -> object:\n        print('A')\n        return str(x)\n    def bar(self, x: int) -> None:\n        print(x + 1)\nclass B(A):\n    def foo(self, x: object) -> int:\n        print('B')\n        return id(x)\n    def bar(self, x: object) -> None:\n        print(x)\n\ndef use_a(x: A, y: int) -> object:\n    x.bar(10)\n    return x.foo(y)\n\ndef use_b(x: B, y: object) -> int:\n    return x.foo(y)\n\n[file driver.py]\nfrom native import A, B, use_a, use_b\na = A()\nb = B()\no = object()\ni = 10\nassert a.foo(10) == '10'\nassert b.foo(o) == id(o)\nassert use_a(a, 10) == '10'\nassert use_b(b, o) == id(o)\nassert use_a(b, i) == id(i)\n[out]\nA\nB\n11\nA\nB\n10\nB\n\n[case testSubclassSpecialize2]\nclass A:\n    def foo(self, x: int) -> object:\n        print('A')\n        return str(x)\nclass B(A):\n    def foo(self, x: object) -> object:\n        print('B')\n        return x\nclass C(B):\n    def foo(self, x: object) -> int:\n        print('C')\n        return id(x)\n\ndef use_a(x: A, y: int) -> object:\n    return x.foo(y)\n\ndef use_b(x: B, y: object) -> object:\n    return x.foo(y)\n\ndef use_c(x: C, y: object) -> int:\n    return x.foo(y)\n\n[file driver.py]\nfrom native import A, B, C, use_a, use_b, use_c\na = A()\nb = B()\nc = C()\no = object()\ni = 10\nassert a.foo(10) == '10'\nassert b.foo(o) == o\nassert c.foo(o) == id(o)\nassert use_a(a, 10) == '10'\nassert use_a(b, i) is i\nassert use_a(c, i) == id(i)\nassert use_b(b, o) == o\nassert use_b(c, o) == id(o)\nassert use_c(c, o) == id(o)\n[out]\nA\nB\nC\nA\nB\nC\nB\nC\nC\n\n[case testIsInstance]\nfrom typing import Optional\nclass X: pass\nclass A(X): pass\nclass B(A): pass\n\ndef isa(x: object) -> bool:\n    return isinstance(x, A)\ndef isint(x: object) -> bool:\n    return isinstance(x, int)\ndef isstr(x: object) -> bool:\n    return isinstance(x, str)\ndef islist(x: object) -> bool:\n    return isinstance(x, list)\ndef ist(x: object, t: object) -> bool:  # TODO: Second argument should be 'type'\n    return isinstance(x, t)\ndef pointless(x: Optional[X]) -> str:\n    if isinstance(x, A):\n        return str(x)\n    return ''\n[file driver.py]\nfrom native import X, A, B, isa, isint, isstr, islist, ist\nassert isa(1) == False\nassert isa(A()) == True\nassert isa(B()) == True\nassert isa(X()) == False\n\nassert isint(1) == True\nassert isint('') == False\nassert isint(A()) == False\n\nassert isstr(1) == False\nassert isstr('') == True\n\nassert islist(1) == False\nassert islist([]) == True\n\nassert ist(1, int) == True\nassert ist(1, str) == False\ntry:\n    ist(1, 2)\nexcept TypeError:\n    pass\nelse:\n    assert False\n\n[case testSubclassUninitAttr]\nclass X:\n    x: int\nclass A(X):\n    pass\n[file driver.py]\nimport traceback\nfrom native import A\ntry:\n    A().x\nexcept AttributeError:\n    traceback.print_exc()\n[out]\nTraceback (most recent call last):\n  File \"driver.py\", line 4, in <module>\n    A().x\nAttributeError: attribute 'x' of 'X' undefined\n\n[case testClassMethods]\nfrom typing import ClassVar, Any, final\nfrom mypy_extensions import mypyc_attr\n\nfrom interp import make_interpreted_subclass\n\nclass C:\n    lurr: ClassVar[int] = 9\n    @staticmethod\n    def foo(x: int) -> int:\n        return 10 + x\n    @classmethod\n    def bar(cls, x: int) -> int:\n        return cls.lurr + x\n    @staticmethod\n    def baz(x: int, y: int = 10) -> int:\n        return y - x\n    @classmethod\n    def quux(cls, x: int, y: int = 10) -> int:\n        return y - x\n    @classmethod\n    def call_other(cls, x: int) -> int:\n        return cls.quux(x, 3)\n\nclass D(C):\n    def f(self) -> int:\n        return super().foo(1) + super().bar(2) + super().baz(10) + super().quux(10)\n\ndef ctest1() -> int:\n    return C.foo(1) + C.bar(2) + C.baz(10) + C.quux(10) + C.quux(y=10, x=9)\n\ndef ctest2() -> int:\n    c = C()\n    return c.foo(1) + c.bar(2) + c.baz(10)\n\nCAny: Any = C\n\ndef test_classmethod_using_any() -> None:\n    assert CAny.foo(10) == 20\n    assert CAny.bar(10) == 19\n\ndef test_classmethod_on_instance() -> None:\n    c = C()\n    assert c.foo(10) == 20\n    assert c.bar(10) == 19\n    assert c.call_other(1) == 2\n\ndef test_classmethod_misc() -> None:\n    assert ctest1() == 23\n    assert ctest2() == 22\n    assert C.call_other(2) == 1\n\ndef test_classmethod_using_super() -> None:\n    d = D()\n    assert d.f() == 22\n\n@final\nclass F1:\n    @classmethod\n    def f(cls, x: int) -> int:\n        return cls.g(x)\n\n    @classmethod\n    def g(cls, x: int) -> int:\n        return x + 1\n\nclass F2:  # Implicitly final (no subclasses)\n    @classmethod\n    def f(cls, x: int) -> int:\n        return cls.g(x)\n\n    @classmethod\n    def g(cls, x: int) -> int:\n        return x + 1\n\ndef test_classmethod_of_final_class() -> None:\n    assert F1.f(5) == 6\n    assert F2.f(7) == 8\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass CI:\n    @classmethod\n    def f(cls, x: int) -> int:\n        return cls.g(x)\n\n    @classmethod\n    def g(cls, x: int) -> int:\n        return x + 1\n\ndef test_classmethod_with_allow_interpreted() -> None:\n    assert CI.f(4) == 5\n    sub = make_interpreted_subclass(CI)\n    assert sub.f(4) == 7\n\n[file interp.py]\ndef make_interpreted_subclass(base):\n    class Sub(base):  # type: ignore[misc, valid-type]\n        @classmethod\n        def g(cls, x: int) -> int:\n            return x + 3\n    return Sub\n\n[case testSuper]\nfrom mypy_extensions import trait\nfrom typing import List\n\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def foo(self, x: int) -> int:\n        return x\n\nclass B(A):\n    def __init__(self, x: int, y: int) -> None:\n        super().__init__(x)\n        self.y = y\n\n    def foo(self, x: int) -> int:\n        return super().foo(x+1)\n\nclass C(B):\n    def __init__(self, x: int, y: int) -> None:\n        super(C, self).__init__(x, y + 1)\n\n    def foo(self, x: int) -> int:\n        # should go to A, not B\n        return super(B, self).foo(x+1)\n\nclass X:\n    def __init__(self, x: int) -> None:\n        self.x = x\nclass Y(X):\n    pass\nclass Z(Y):\n    def __init__(self, x: int, y: int) -> None:\n        super().__init__(x)\n        self.y = y\n\n@trait\nclass T:\n    def v_int(self, x: int) -> None: pass\n    def v_list(self, x: List[int]) -> None:\n        if x:\n            self.v_int(x[0])\n            self.v_list(x[1:])\n\nclass PrintList(T):\n    def v_int(self, x: int) -> None:\n        print(x)\n    def v_list(self, x: List[int]) -> None:\n        print('yo!')\n        super().v_list(x)\n\n[file driver.py]\nimport traceback\nfrom native import *\nb = B(10, 20)\nassert b.x == 10 and b.y == 20\nc = C(10, 20)\nassert c.x == 10 and c.y == 21\nz = Z(10, 20)\nassert z.x == 10 and z.y == 20\n\nassert c.foo(10) == 11\n\nPrintList().v_list([1,2,3])\n[out]\nyo!\n1\nyo!\n2\nyo!\n3\nyo!\n\n[case testSubclassException]\nclass Failure(Exception):\n    def __init__(self, x: int) -> None:\n        self.x = x\n\ndef foo() -> None:\n    raise Failure(10)\n\ndef heyo() -> int:\n    try:\n        foo()\n    except Failure as e:\n        return e.x\n    return -1\n\n[file driver.py]\nfrom native import foo, heyo, Failure\ntry:\n    foo()\nexcept Failure as e:\n    assert str(e) == '10'\n    assert e.x == 10\nheyo()\n\n[case testSubclassDict]\nfrom typing import Dict\nclass WelpDict(Dict[str, int]):\n    def __init__(self) -> None:\n        self.emarhavil = 3\n    def foo(self) -> int:\n        return self.emarhavil\n\ndef welp() -> int:\n    x = WelpDict()\n    x['a'] = 10\n    x['b'] = 15\n    x.emarhavil = 5\n    return x['a'] + x['b'] + x.emarhavil + x.foo()\n\n[file driver.py]\nfrom native import welp\nassert welp() == 35\n\n[case testSubclassUnsupportedException]\nfrom mypy_extensions import mypyc_attr\n\n@mypyc_attr(native_class=False)\nclass MyError(ZeroDivisionError):\n    pass\n\n@mypyc_attr(native_class=False)\nclass MyError2(ZeroDivisionError):\n    def __init__(self, s: str) -> None:\n        super().__init__(s + \"!\")\n        self.x = s.upper()\n\ndef f() -> None:\n    raise MyError(\"foobar\")\n\ndef test_non_native_exception_subclass_basics() -> None:\n    e = MyError()\n    assert isinstance(e, MyError)\n    assert isinstance(e, ZeroDivisionError)\n    assert isinstance(e, Exception)\n\n    e = MyError(\"x\")\n    assert repr(e) == \"MyError('x')\"\n\n    e2 = MyError2(\"ab\")\n    assert repr(e2) == \"MyError2('ab!')\", repr(e2)\n    assert e2.x == \"AB\"\n\ndef test_raise_non_native_exception_subclass_1() -> None:\n    try:\n        f()\n    except MyError:\n        x = True\n    else:\n        assert False\n    assert x\n\ndef test_raise_non_native_exception_subclass_2() -> None:\n    try:\n        f()\n    except ZeroDivisionError:\n        x = True\n    else:\n        assert False\n    assert x\n\n[case testSubclassPy]\nfrom b import B, V\nclass A(B):\n    def __init__(self, x: int, y: int) -> None:\n        super().__init__(y)\n        self.x = x\n\n    def foo(self, x: int) -> int:\n        print(\"hi\", x)\n        return x+1\n\nclass C(V[int]):\n    def f(self) -> int: return 10\n\nassert isinstance(C(), V)\n\ndef f(x: A) -> None:\n    print(x.x)\n    print(x.y)\n    print(x.foo(20))\n\n[file b.py]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass B:\n    def __init__(self, y: int) -> None:\n        self.y = y\n    def foo(self, x: int) -> int:\n        print(\"parent!\")\n        return x + self.y\n    def bar(self) -> None:\n        print(\"hello!\", self.y)\n\nclass V(Generic[T]):\n    def f(self) -> T:\n        raise Exception('unimplemented')\n[file driver.py]\nimport native\na = native.A(10, 20)\na.foo(10)\na.bar()\nnative.f(a)\n[out]\nhi 10\nhello! 20\n10\n20\nhi 20\n21\n\n[case testDisallowSubclassFromPy]\n# We'll want to allow this at some point but right now we need to\n# disallow it because it doesn't work.\nclass A:\n    pass\n[file b.py]\nfrom native import A\n\n# It would be better if we disallowed it at class decl time but it is\n# really easy to do in __new__\n\nclass B(A):\n    pass\n\n[file driver.py]\nfrom b import B\ntry:\n    B()\nexcept TypeError:\n    pass\nelse:\n    assert False, \"instantiating was supposed to fail\"\n\n[case testClassVariable]\nMYPY = False\nif MYPY:\n    from typing import ClassVar\nclass A:\n    x = 10  # type: ClassVar[int]\n\ndef g(x: int) -> None:\n    A.x = 10\ndef f() -> int:\n    return A.x\n[file driver.py]\nfrom native import A, f\nassert f() == 10\nA.x = 200\nassert f() == 200\n\n[case testInitSubclassWithClassVar]\nfrom typing import ClassVar\n\nclass Base:\n    name: ClassVar[str] = \"base\"\n    required: ClassVar[int] = -1\n\n    def __init_subclass__(cls, **kwargs: object) -> None:\n        cls.required = len(cls.name)\n\nclass Child(Base):\n    name: ClassVar[str] = \"child\"\n\nclass GrandChild(Child):\n    name: ClassVar[str] = \"grandchild\"\n\nclass NoOverride(Base):\n    pass\n\n[file driver.py]\nfrom native import Base, Child, GrandChild, NoOverride\n\n# __init_subclass__ should see the subclass's own ClassVar values\nassert Child.name == \"child\"\nassert Child.required == 5, f\"expected 5, got {Child.required}\"\n\nassert GrandChild.name == \"grandchild\"\nassert GrandChild.required == 10, f\"expected 10, got {GrandChild.required}\"\n\n# No override should use inherited value\nassert NoOverride.name == \"base\"\nassert NoOverride.required == 4, f\"expected 4, got {NoOverride.required}\"\n\n[case testDefaultVars]\nfrom typing import Optional\nclass A:\n    x = 10\n    w: object = 10\n    def lol(self) -> None:\n        self.x = 100\n\nLOL = 'lol'\nclass B(A):\n    y = LOL\n    z = None  # type: Optional[str]\n    b = True\n    bogus = None  # type: int\n\ndef g() -> None:\n    a = A()\n    assert a.x == 10\n    a.x = 20\n    assert a.x == 20\n    b = B()\n    assert b.x == 10\n    b.x = 20\n    assert b.x == 20\n    assert b.y == 'lol'\n    b.y = 'rofl'\n    assert b.y == 'rofl'\n    assert b.z is None\n[file driver.py]\nfrom native import *\ng()\n\na = A()\nassert a.x == 10\na.x = 20\nassert a.x == 20\nb = B()\nassert b.x == 10\nb.x = 20\nassert b.x == 20\nassert b.y == 'lol'\nb.y = 'rofl'\nassert b.y == 'rofl'\nassert b.z is None\n# N.B: this doesn't match cpython\nassert not hasattr(b, 'bogus')\n\n[case testProtocol]\nfrom typing import Protocol\n\nclass Proto(Protocol):\n    def foo(self, x: int) -> None:\n        pass\n\n    def bar(self, x: int) -> None:\n        pass\n\nclass A:\n    def foo(self, x: int) -> None:\n        print(\"A:\", x)\n\n    def bar(self, *args: int, **kwargs: int) -> None:\n        print(\"A:\", args, kwargs)\n\nclass B(A, Proto):\n    def foo(self, x: int) -> None:\n        print(\"B:\", x)\n\n    def bar(self, *args: int, **kwargs: int) -> None:\n        print(\"B:\", args, kwargs)\n\ndef f(x: Proto) -> None:\n    x.foo(20)\n    x.bar(x=20)\n\n[file driver.py]\nfrom native import A, B, f\n\nf(A())\nf(B())\n\n# ... this exploits a bug in glue methods to distinguish whether we\n# are making a direct call or a pycall...\n[out]\nA: 20\nA: () {'x': 20}\nB: 20\nB: (20,) {}\n\n[case testMethodOverrideDefault1]\nclass A:\n    def foo(self, x: int) -> None:\n        pass\nclass B(A):\n    def foo(self, x: int, y: int = 10) -> None:\n        print(x, y)\n\ndef a(x: A) -> None:\n    x.foo(1)\ndef b(x: B) -> None:\n    x.foo(2)\n    x.foo(2, 3)\n\n[file driver.py]\nfrom native import B, a, b\na(B())\nb(B())\n[out]\n1 10\n2 10\n2 3\n\n[case testMethodOverrideDefault2]\nclass A:\n    def foo(self, *, x: int = -1) -> None:\n        pass\n    def bar(self, *, x: int = -1, y: int = -1) -> None:\n        pass\n    def baz(self, x: int = -1) -> None:\n        pass\nclass B(A):\n    def foo(self, *, y: int = 0, x: int = 0) -> None:\n        print(x, y)\n    def bar(self, *, y: int = 0, x: int = 0) -> None:\n        print(x, y)\n    def baz(self, x: int = 0, *, y: int = 0) -> None:\n        print(x, y)\n\ndef a(x: A) -> None:\n    x.foo(x=1)\n    x.bar(x=1, y=2)\n    x.bar(x=2, y=1)\n    x.baz()\n    x.baz(1)\n    x.baz(x=2)\n\n[file driver.py]\nfrom native import B, a\na(B())\n[out]\n1 0\n1 2\n2 1\n0 0\n1 0\n2 0\n\n[case testMethodOverrideDefault3]\nclass A:\n    @classmethod\n    def foo(cls, *, x: int = 0) -> None:\n        pass\n    @staticmethod\n    def bar(*, x: int = 0) -> None:\n        pass\n    @staticmethod\n    def baz() -> object:\n        pass\nclass B(A):\n    @classmethod\n    def foo(cls, *, y: int = 0, x: int = 0) -> None:\n        print(x, y)\n        print(cls.__name__)  # type: ignore\n    @staticmethod\n    def bar(*, y: int = 0, x: int = 0) -> None:\n        print(x, y)\n    @staticmethod\n    def baz() -> int:\n        return 10\n\n# This is just to make sure that this stuff works even when the\n# methods might be overridden.\nclass C(B):\n    @classmethod\n    def foo(cls, *, y: int = 0, x: int = 0) -> None:\n        pass\n    @staticmethod\n    def bar(*, y: int = 0, x: int = 0) -> None:\n        pass\n    @staticmethod\n    def baz() -> int:\n        return 10\n\ndef a(x: A) -> None:\n    x.foo(x=1)\n    x.bar(x=1)\n    print(x.baz())\n\n[file driver.py]\nfrom native import B, a\na(B())\n[out]\n1 0\nB\n1 0\n10\n\n[case testMethodOverrideDefault4]\nclass Foo:\n    def f(self, x: int=20, *, z: int=10) -> None:\n        pass\n\nclass Bar(Foo):\n    def f(self, *args: int, **kwargs: int) -> None:\n        print(\"stuff\", args, kwargs)\n\ndef test_override() -> None:\n    z: Foo = Bar()\n    z.f(1, z=50)\n    z.f()\n\n[out]\nstuff (1,) {'z': 50}\nstuff () {}\n\n[case testMethodOverrideDefault5]\nfrom testutil import make_python_function\nfrom mypy_extensions import mypyc_attr\nfrom typing import TypeVar, Any\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass Foo:\n    def f(self, x: int=20, *, z: int=10) -> None:\n        print(\"Foo\", x, z)\n\n@make_python_function\ndef baz_f(self: Any, *args: int, **kwargs: int) -> None:\n    print(\"Baz\", args, kwargs)\n\ndef test_override() -> None:\n    # Make an \"interpreted\" subtype of Foo\n    type2: Any = type\n    Bar = type2('Bar', (Foo,), {})\n    Baz = type2('Baz', (Foo,), {'f': baz_f})\n\n    y: Foo = Bar()\n    y.f(1, z=2)\n    y.f()\n\n    z: Foo = Baz()\n    z.f(1, z=2)\n    z.f()\n\n[out]\nFoo 1 2\nFoo 20 10\nBaz (1,) {'z': 2}\nBaz () {}\n\n[case testMethodOverrideDefault6]\nfrom typing import Optional\n\nclass Foo:\n    def f(self, x: int=20) -> None:\n        pass\n\nclass Bar(Foo):\n    def f(self, x: Optional[int]=None) -> None:\n        print(x)\n\ndef test_override() -> None:\n    z: Foo = Bar()\n    z.f(1)\n    z.f()\n\n[out]\n1\nNone\n\n[case testMethodOverrideDefault7]\nfrom typing import TypeVar, Any\n\nclass Foo:\n    def f(self, x: int, *args: int, **kwargs: int) -> None:\n        print(\"Foo\", x, args, kwargs)\n\nclass Bar(Foo):\n    def f(self, *args: int, **kwargs: int) -> None:\n        print(\"Bar\", args, kwargs)\n\ndef test_override() -> None:\n    z: Foo = Bar()\n    z.f(1, z=2)\n    z.f(1, 2, 3)\n    # z.f(x=5)  # Not tested because we (knowingly) do the wrong thing and pass it as positional\n\n[out]\nBar (1,) {'z': 2}\nBar (1, 2, 3) {}\n--Bar () {'x': 5}\n\n[case testMethodOverrideDefault8]\nfrom typing import TypeVar, Any\n\nclass Foo:\n    def f(self, *args: int, **kwargs: int) -> None:\n        print(\"Foo\", args, kwargs)\n\nclass Bar(Foo):\n    def f(self, x: int = 10, *args: int, **kwargs: int) -> None:\n        print(\"Bar\", x, args, kwargs)\n\ndef test_override() -> None:\n    z: Foo = Bar()\n    z.f(1, z=2)\n    z.f(1, 2, 3)\n    z.f()\n\n[out]\nBar 1 () {'z': 2}\nBar 1 (2, 3) {}\nBar 10 () {}\n\n[case testMethodOverrideDefault9]\nfrom testutil import make_python_function\nfrom mypy_extensions import mypyc_attr\nfrom typing import TypeVar, Any\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass Foo:\n    def f(self, x: int=20, y: int=40) -> None:\n        print(\"Foo\", x, y)\n\n# This sort of argument renaming is dodgy and not really sound but we\n# shouldn't break it when they aren't actually used by name...\n# (They *ought* to be positional only!)\n@make_python_function\ndef baz_f(self, a: int=30, y: int=50) -> None:\n    print(\"Baz\", a, y)\n\ndef test_override() -> None:\n    # Make an \"interpreted\" subtype of Foo\n    type2: Any = type\n    Baz = type2('Baz', (Foo,), {'f': baz_f})\n\n    z: Foo = Baz()\n    z.f()\n    z.f(y=1)\n    z.f(1, 2)\n    # Not tested because we don't (and probably won't) match cpython here\n    # from testutil import assertRaises\n    # with assertRaises(TypeError):\n    #     z.f(x=7)\n\n[out]\nBaz 30 50\nBaz 30 1\nBaz 1 2\n\n[case testOverride]\nclass A:\n    def f(self) -> int:\n        return 0\n    def g(self) -> int:\n        return 1\n\nclass B(A):\n    def g(self) -> int:\n        return 2\n\nclass C(B):\n    def f(self) -> int:\n        return 3\n\ndef test() -> None:\n    ba: A = B()\n    ca: A = C()\n    assert ba.f() == 0\n    assert ba.g() == 2\n    assert ca.f() == 3\n    assert ca.g() == 2\n    cc = C()\n    assert cc.f() == 3\n    assert cc.g() == 2\n    print('ok')\n[file driver.py]\nimport native\nnative.test()\n[out]\nok\n\n[case testNoMetaclass]\nfrom foo import Base\n\nclass Nothing(Base):  # type: ignore\n    pass\n\n[file foo.py]\nfrom typing import Any\nclass Meta(type):\n    pass\n\nclass _Base(metaclass=Meta):\n    pass\nBase = _Base  # type: Any\n\n[file driver.py]\ntry:\n    import native\nexcept TypeError as e:\n    assert(str(e) == \"mypyc classes can't have a metaclass\")\n\n[case testMetaclass]\nfrom meta import Meta\n\nclass Nothing(metaclass=Meta):\n    pass\n\ndef ident(x): return x\n\n@ident\nclass Test:\n    pass\n\n[file meta.py]\nclass Meta(type):\n    def __new__(mcs, name, bases, dct):\n        dct['X'] = 10\n        return super().__new__(mcs, name, bases, dct)\n\n\n[file driver.py]\nfrom native import Nothing\nassert Nothing.X == 10\n\n[case testPickling]\nfrom mypy_extensions import trait, mypyc_attr\nfrom typing import Any, TypeVar, Generic\n\ndef dec(x: Any) -> Any:\n    return x\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass A:\n    x: int\n    y: str\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass B(A):\n    z: bool\n\n    def __init__(self, x: int, y: str, z: bool) -> None:\n        self.x = x\n        self.y = y\n        self.z = z\n\n@trait\nclass T:\n    a: str\n\nclass C(B, T):\n    w: object\n\n    # property shouldn't go in\n    @property\n    def foo(self) -> int:\n        return 0\n\n@dec\nclass D:\n    x: int\n\nclass E(D):\n    y: int\n\n\nU = TypeVar('U')\n\nclass F(Generic[U]):\n    y: int\n\nclass G(F[int]):\n    pass\n\n[file driver.py]\nfrom native import A, B, T, C, D, E, F, G\n\nimport copy\nimport pickle\n\nassert A.__mypyc_attrs__ == ('x', 'y')\nassert B.__mypyc_attrs__ == ('z', 'x', 'y')\nassert T.__mypyc_attrs__ == ('a',)\nassert C.__mypyc_attrs__ == ('w', 'z', 'x', 'y', 'a')\nassert not hasattr(D, '__mypyc_attrs__')\nassert E.__mypyc_attrs__ == ('y', '__dict__')\nassert F.__mypyc_attrs__ == ('y', '__dict__')\nassert G.__mypyc_attrs__ == ('y', '__dict__')\n\nb = B(10, '20', False)\nassert b.__getstate__() == {'z': False, 'x': 10, 'y': '20'}\nb2 = copy.copy(b)\nassert b is not b2 and b.y == b2.y\n\nb3 = pickle.loads(pickle.dumps(b))\nassert b is not b3 and b.y == b3.y\n\ne = E()\ne.x = 10\ne.y = 20\n\nassert e.__getstate__() == {'y': 20, '__dict__': {'x': 10}}\ne2 = pickle.loads(pickle.dumps(e))\nassert e is not e2 and e.x == e2.x and e.y == e2.y\n\n\n[case testInterpretedParentInit]\nfrom interp import C\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef dec(x: T) -> T:\n    return x\n\n@dec\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\nclass B(A):\n    s = 'test'\n\ndef b(x: int) -> B: return B(x)\n\nclass D(C):\n    s = 'test'\n\ndef d(x: int) -> D: return D(x)\n\n\n[file interp.py]\nclass C:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n[file driver.py]\nfrom native import b, d, B, D\n\ndef test(f, v):\n    x = f(v)\n    assert x.x == v\n    assert x.s == 'test'\n\ntest(b, 20)\ntest(d, 30)\ntest(B, -1)\ntest(D, -2)\n\n[case testInterpretedInherit]\nfrom typing import TypeVar, Any, overload\nfrom mypy_extensions import mypyc_attr, trait\n\nT = TypeVar('T')\ndef dec(x: T) -> T: return x\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass Top:\n    def spam(self) -> str:\n        return \"grandparent\"\n\n@mypyc_attr(allow_interpreted_subclasses=True)\n@trait\nclass Trait:\n    def trait_method(self) -> str:\n        return \"trait\"\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass Foo(Top, Trait):\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def foo(self) -> str:\n        return \"parent foo: \" + self.bar(self.x)\n\n    def bar(self, x: int) -> str:\n        return \"parent bar: {}\".format(x + self.x)\n\n    @dec\n    def decorated(self) -> str:\n        return \"decorated parent\"\n\n    @property\n    def read_property(self) -> str:\n        return \"parent prop\"\n\n    @overload\n    def overloaded(self, index: int) -> int: ...\n\n    @overload\n    def overloaded(self, index: str) -> str: ...\n\n    def overloaded(self, index: Any) -> Any:\n        return index\n\ndef foo(x: Foo) -> str:\n    return x.foo()\n\ndef bar(x: Foo, y: int) -> str:\n    return x.bar(y)\n\ndef spam(x: Top) -> str:\n    return x.spam()\n\ndef decorated(x: Foo) -> str:\n    return x.decorated()\n\ndef prop(x: Foo) -> str:\n    return x.read_property\n\ndef trait_method(x: Trait) -> str:\n    return x.trait_method()\n\ndef overloaded(x: Foo, s: str) -> str:\n    return x.overloaded(s)\n\n[file interp.py]\nfrom typing import Any\nfrom native import Foo\n\nclass Bar(Foo):\n    def bar(self, x: int) -> str:\n        return \"child bar: {}\".format(x + self.x)\n\n    def spam(self) -> str:\n        assert super().spam() == \"grandparent\"\n        return \"child\"\n\n    @property\n    def read_property(self) -> str:\n        return \"child prop\"\n\n    def decorated(self) -> str:\n        return \"decorated child\"\n\n    def trait_method(self) -> str:\n        return \"child\"\n\n    def overloaded(self, index: Any) -> Any:\n        return index + index\n\n\nclass InterpBase:\n    def eggs(self) -> str:\n        return \"eggs\"\n\nclass Baz(InterpBase, Bar):\n    def __init__(self) -> None:\n        super().__init__(1000)\n        self.z = self.read_property\n\n[file driver.py]\nfrom native import Foo, foo, bar, spam, decorated, overloaded, prop, trait_method\nfrom interp import Bar, Baz\nfrom unittest.mock import patch\nfrom testutil import assertRaises\n\nx = Foo(10)\ny = Bar(20)\nz = Baz()\n\nassert isinstance(y, Bar)\nassert y.x == 20\nassert y.bar(10) == \"child bar: 30\"\nassert y.foo() == \"parent foo: child bar: 40\"\nassert foo(y) == \"parent foo: child bar: 40\"\nassert bar(y, 30) == \"child bar: 50\"\ny.x = 30\nassert bar(y, 30) == \"child bar: 60\"\n\nassert spam(y) == \"child\"\nassert y.read_property == \"child prop\"\nassert prop(x) == \"parent prop\"\nassert prop(y) == \"child prop\"\nassert y.decorated() == \"decorated child\"\nassert decorated(y) == \"decorated child\"\nassert y.overloaded(\"test\") == \"testtest\"\nassert overloaded(y, \"test\") == \"testtest\"\n\nassert y.trait_method() == \"child\"\nassert trait_method(y) == \"child\"\n\nassert z.bar(10) == \"child bar: 1010\"\nassert bar(z, 10) == \"child bar: 1010\"\nassert z.z == \"child prop\"\nassert z.eggs() == \"eggs\"\n\nwith patch(\"interp.Bar.spam\", lambda self: \"monkey patched\"):\n    assert y.spam() == \"monkey patched\"\n    spam(y) == \"monkey patched\"\n\nwith patch(\"interp.Bar.spam\", lambda self: 20):\n    assert y.spam() == 20\n    with assertRaises(TypeError, \"str object expected; got int\"):\n        spam(y)\n\nwith assertRaises(TypeError, \"int object expected; got str\"):\n    y.x = \"test\"\n\n[case testProperty]\nfrom typing import Callable\nfrom mypy_extensions import trait\nclass Temperature:\n    @property\n    def celsius(self) -> float:\n        return 5.0 * (self.fahrenheit - 32.0) / 9.0\n\n    def __init__(self, fahrenheit: float) -> None:\n        self.fahrenheit = fahrenheit\n\n    def print_temp(self) -> None:\n        print(\"F:\", self.fahrenheit, \"C:\", self.celsius)\n\n    @property\n    def rankine(self) -> float:\n        raise NotImplementedError\n\nclass Access:\n    @property\n    def number_of_accesses(self) -> int:\n        self._count += 1\n        return self._count\n    def __init__(self) -> None:\n        self._count = 0\n\nfrom typing import Callable\nclass BaseProperty:\n    @property\n    def doc(self) -> str:\n        return \"Represents a sequence of values. Updates itself by next, which is a new value.\"\n\n    @property\n    def value(self) -> object:\n        return self._incrementer\n\n    @property\n    def bad_value(self) -> object:\n        return self._incrementer\n\n    @property\n    def next(self) -> BaseProperty:\n        return BaseProperty(self._incrementer + 1)\n\n    def __init__(self, value: int) -> None:\n        self._incrementer = value\n\nclass DerivedProperty(BaseProperty):\n    @property\n    def value(self) -> int:\n        return self._incrementer\n\n    @property\n    def bad_value(self) -> object:\n        return self._incrementer\n\n    def __init__(self, incr_func: Callable[[int], int], value: int) -> None:\n        BaseProperty.__init__(self, value)\n        self._incr_func = incr_func\n\n    @property\n    def next(self) -> DerivedProperty:\n        return DerivedProperty(self._incr_func, self._incr_func(self.value))\n\nclass AgainProperty(DerivedProperty):\n    @property\n    def next(self) -> AgainProperty:\n        return AgainProperty(self._incr_func, self._incr_func(self._incr_func(self.value)))\n\n    @property\n    def bad_value(self) -> int:\n        return self._incrementer\n\ndef print_first_n(n: int, thing: BaseProperty) -> None:\n    vals = []\n    cur_thing = thing\n    for _ in range(n):\n        vals.append(cur_thing.value)\n        cur_thing = cur_thing.next\n    print ('', vals)\n\n@trait\nclass Trait:\n    @property\n    def value(self) -> int:\n        return 3\n\nclass Printer(Trait):\n    def print_value(self) -> None:\n        print(self.value)\n\n[file driver.py]\nfrom native import Temperature, Access\nimport traceback\nx = Temperature(32.0)\ntry:\n    print (x.rankine)\nexcept NotImplementedError as e:\n    traceback.print_exc()\nprint (x.celsius)\nx.print_temp()\n\ny = Temperature(212.0)\nprint (y.celsius)\ny.print_temp()\n\nz = Access()\nprint (z.number_of_accesses)\nprint (z.number_of_accesses)\nprint (z.number_of_accesses)\nprint (z.number_of_accesses)\n\nfrom native import BaseProperty, DerivedProperty, AgainProperty, print_first_n\na = BaseProperty(7)\nb = DerivedProperty((lambda x: x // 2 if (x % 2 == 0) else 3 * x + 1), 7)\nc = AgainProperty((lambda x: x // 2 if (x % 2 == 0) else 3 * x + 1), 7)\n\ndef py_print_first_n(n: int, thing: BaseProperty) -> None:\n    vals = []\n    cur_thing = thing\n    for _ in range(n):\n        vals.append(cur_thing.value)\n        cur_thing = cur_thing.next\n    print ('', vals)\n\npy_print_first_n(20, a)\npy_print_first_n(20, b)\npy_print_first_n(20, c)\n\nprint(a.next.next.next.bad_value)\nprint(b.next.next.next.bad_value)\nprint(c.next.next.next.bad_value)\n\nprint_first_n(20, a)\nprint_first_n(20, b)\nprint_first_n(20, c)\n\nprint (a.doc)\nprint (b.doc)\nprint (c.doc)\n\nfrom native import Printer\nPrinter().print_value()\nprint (Printer().value)\n[out]\nTraceback (most recent call last):\n  File \"driver.py\", line 5, in <module>\n    print (x.rankine)\n  File \"native.py\", line 16, in rankine\n    raise NotImplementedError\nNotImplementedError\n0.0\nF: 32.0 C: 0.0\n100.0\nF: 212.0 C: 100.0\n1\n2\n3\n4\n [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]\n [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]\n [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]\n10\n34\n26\n [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]\n [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]\n [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]\nRepresents a sequence of values. Updates itself by next, which is a new value.\nRepresents a sequence of values. Updates itself by next, which is a new value.\nRepresents a sequence of values. Updates itself by next, which is a new value.\n3\n3\n[out version>=3.11]\nTraceback (most recent call last):\n  File \"driver.py\", line 5, in <module>\n    print (x.rankine)\n           ^^^^^^^^^\n  File \"native.py\", line 16, in rankine\n    raise NotImplementedError\nNotImplementedError\n0.0\nF: 32.0 C: 0.0\n100.0\nF: 212.0 C: 100.0\n1\n2\n3\n4\n [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]\n [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]\n [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]\n10\n34\n26\n [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]\n [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2, 1, 4, 2, 1]\n [7, 11, 17, 26, 40, 10, 16, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4, 1, 2, 4]\nRepresents a sequence of values. Updates itself by next, which is a new value.\nRepresents a sequence of values. Updates itself by next, which is a new value.\nRepresents a sequence of values. Updates itself by next, which is a new value.\n3\n3\n\n[case testPropertySetters]\n\nfrom mypy_extensions import trait\n\nclass Foo():\n    def __init__(self) -> None:\n        self.attr = \"unmodified\"\n\nclass A:\n    def __init__(self) -> None:\n        self._x = 0\n        self._foo = Foo()\n\n    @property\n    def x(self) -> int:\n        return self._x\n\n    @x.setter\n    def x(self, val : int) -> None:\n        self._x = val\n\n    @property\n    def foo(self) -> Foo:\n        return self._foo\n\n    @foo.setter\n    def foo(self, val : Foo) -> None:\n        self._foo = val\n\n# Overrides base property setters and getters\nclass B(A):\n    def __init__(self) -> None:\n        self._x = 10\n\n    @property\n    def x(self) -> int:\n        return self._x + 1\n\n    @x.setter\n    def x(self, val : int) -> None:\n        self._x = val + 1\n\n# Inherits base property setters and getters\nclass C(A):\n    def __init__(self) -> None:\n        A.__init__(self)\n\n@trait\nclass D():\n    def __init__(self) -> None:\n        self._x = 0\n\n    @property\n    def x(self) -> int:\n        return self._x\n\n    @x.setter\n    def x(self, val : int) -> None:\n        self._x = val\n\n#Inherits trait property setters and getters\nclass E(D):\n    def __init__(self) -> None:\n        D.__init__(self)\n\n#Overrides trait property setters and getters\nclass F(D):\n    def __init__(self) -> None:\n        self._x = 10\n\n    @property\n    def x(self) -> int:\n        return self._x + 10\n\n    @x.setter\n    def x(self, val : int) -> None:\n        self._x = val + 10\n\n# # Property setter and getter are subtypes of base property setters and getters\n# # class G(A):\n# #   def __init__(self) -> None:\n# #       A.__init__(self)\n\n# #   @property\n# #   def y(self) -> int:\n# #       return self._y\n\n# #   @y.setter\n# #   def y(self, val : object) -> None:\n# #       self._y = val\n\n# No inheritance, just plain setter/getter\nclass G:\n    def __init__(self, x: int) -> None:\n        self._x = x\n\n    @property\n    def x(self) -> int:\n        return self._x\n\n    @x.setter\n    def x(self, x: int) -> None:\n        self._x = x\n\nclass H:\n    def __init__(self, g: G) -> None:\n        self.g = g\n        self.g.x = 5  # Should not be treated as initialization\n\n[file other.py]\n# Run in both interpreted and compiled mode\n\nfrom native import A, B, C, D, E, F, G\n\na = A()\nassert a.x == 0\nassert a._x == 0\na.x = 1\nassert a.x == 1\nassert a._x == 1\na._x = 0\nassert a.x == 0\nassert a._x == 0\nb = B()\nassert b.x == 11\nassert b._x == 10\nb.x = 11\nassert b.x == 13\nb._x = 11\nassert b.x == 12\nc = C()\nassert c.x == 0\nc.x = 1000\nassert c.x == 1000\ne = E()\nassert e.x == 0\ne.x = 1000\nassert e.x == 1000\nf = F()\nassert f.x == 20\nf.x = 30\nassert f.x == 50\ng = G(4)\ng.x = 20\nassert g.x == 20\n\n[file driver.py]\n# Run the tests in both interpreted and compiled mode\nimport other\nimport other_interpreted\n\n[out]\n\n[case testAttributeOverridesProperty]\nfrom typing import Any\nfrom mypy_extensions import trait\n\n@trait\nclass T1:\n    @property\n    def x(self) -> int: ...\n    @property\n    def y(self) -> int: ...\n\nclass C1(T1):\n    x: int = 1\n    y: int = 4\n\ndef test_read_only_property_in_trait_implemented_as_attribute() -> None:\n    c = C1()\n    c.x = 5\n    assert c.x == 5\n    assert c.y == 4\n    c.y = 6\n    assert c.y == 6\n    t: T1 = C1()\n    assert t.y == 4\n    t = c\n    assert t.x == 5\n    assert t.y == 6\n    a: Any = c\n    assert a.x == 5\n    assert a.y == 6\n    a.x = 7\n    a.y = 8\n    assert a.x == 7\n    assert a.y == 8\n\nclass B2:\n    @property\n    def x(self) -> int:\n        return 11\n\n    @property\n    def y(self) -> int:\n        return 25\n\nclass C2(B2):\n    x: int = 1\n    y: int = 4\n\ndef test_read_only_property_in_class_implemented_as_attribute() -> None:\n    c = C2()\n    c.x = 5\n    assert c.x == 5\n    assert c.y == 4\n    c.y = 6\n    assert c.y == 6\n    b: B2 = C2()\n    assert b.y == 4\n    b = c\n    assert b.x == 5\n    assert b.y == 6\n    a: Any = c\n    assert a.x == 5\n    assert a.y == 6\n    a.x = 7\n    a.y = 8\n    assert a.x == 7\n    assert a.y == 8\n\n@trait\nclass T3:\n    @property\n    def x(self) -> int: ...\n    @property\n    def y(self) -> int: ...\n\nclass B3:\n    x: int = 1\n    y: int = 4\n\nclass C3(B3, T3):\n    pass\n\ndef test_read_only_property_implemented_as_attribute_indirectly() -> None:\n    c = C3()\n    c.x = 5\n    assert c.x == 5\n    assert c.y == 4\n    c.y = 6\n    assert c.y == 6\n    t: T3 = C3()\n    assert t.y == 4\n    t = c\n    assert t.x == 5\n    assert t.y == 6\n    a: Any = c\n    assert a.x == 5\n    assert a.y == 6\n    a.x = 7\n    a.y = 8\n    assert a.x == 7\n    assert a.y == 8\n\n@trait\nclass T4:\n    @property\n    def x(self) -> int: ...\n    @x.setter\n    def x(self, v1: int) -> None: ...\n\n    @property\n    def y(self) -> int: ...\n    @y.setter\n    def y(self, v2: int) -> None: ...\n\nclass C4(T4):\n    x: int = 1\n    y: int = 4\n\ndef test_read_write_property_implemented_as_attribute() -> None:\n    c = C4()\n    c.x = 5\n    assert c.x == 5\n    assert c.y == 4\n    c.y = 6\n    assert c.y == 6\n    t: T4 = C4()\n    assert t.y == 4\n    t.x = 5\n    assert t.x == 5\n    t.y = 6\n    assert t.y == 6\n    a: Any = c\n    assert a.x == 5\n    assert a.y == 6\n    a.x = 7\n    a.y = 8\n    assert a.x == 7\n    assert a.y == 8\n\n@trait\nclass T5:\n    @property\n    def x(self) -> int: ...\n    @x.setter\n    def x(self, v1: int) -> None: ...\n\n    @property\n    def y(self) -> int: ...\n    @y.setter\n    def y(self, v2: int) -> None: ...\n\nclass B5:\n    x: int = 1\n    y: int = 4\n\nclass BB5(B5):\n    pass\n\nclass C5(BB5, T5):\n    pass\n\ndef test_read_write_property_indirectly_implemented_as_attribute() -> None:\n    c = C5()\n    c.x = 5\n    assert c.x == 5\n    assert c.y == 4\n    c.y = 6\n    assert c.y == 6\n    t: T5 = C5()\n    assert t.y == 4\n    t.x = 5\n    assert t.x == 5\n    t.y = 6\n    assert t.y == 6\n    a: Any = c\n    assert a.x == 5\n    assert a.y == 6\n    a.x = 7\n    a.y = 8\n    assert a.x == 7\n    assert a.y == 8\n\n[case testSubclassAttributeAccess]\nfrom mypy_extensions import trait\n\nclass A:\n    v = 0\n\nclass B(A):\n    v = 1\n\nclass C(B):\n    v = 2\n\n[file driver.py]\nfrom native import A, B, C\n\na = A()\nb = B()\nc = C()\n\n[case testCopyAlwaysDefinedAttributes]\nimport copy\nfrom typing import Union\n\nclass A: pass\n\nclass C:\n    def __init__(self, n: int = 0) -> None:\n        self.n = n\n        self.s = \"\"\n        self.t = (\"\", 0)\n        self.u: Union[str, bytes] = ''\n        self.a = A()\n\ndef test_copy() -> None:\n    c1 = C()\n    c1.n = 1\n    c1.s = \"x\"\n    c2 = copy.copy(c1)\n    assert c2.n == 1\n    assert c2.s == \"x\"\n    assert c2.t == (\"\", 0)\n    assert c2.u == ''\n    assert c2.a is c1.a\n\n[case testNonNativeCallsToDunderNewAndInit]\nfrom typing import Any\nfrom testutil import assertRaises\n\ncount_c = 0\n\nclass C:\n    def __init__(self) -> None:\n        self.x = 'a'  # Always defined attribute\n        global count_c\n        count_c += 1\n\n    def get(self) -> str:\n        return self.x\n\ndef test_no_init_args() -> None:\n    global count_c\n    count_c = 0\n\n    # Use Any to get non-native semantics\n    cls: Any = C\n    # __new__ implicitly calls __init__ for native classes\n    obj = cls.__new__(cls)\n    assert obj.get() == 'a'\n    assert count_c == 1\n    # Make sure we don't call __init__ twice\n    obj2 = cls()\n    assert obj2.get() == 'a'\n    assert count_c == 2\n\ncount_d = 0\n\nclass D:\n    def __init__(self, x: str) -> None:\n        self.x = x  # Always defined attribute\n        global count_d\n        count_d += 1\n\n    def get(self) -> str:\n        return self.x\n\ndef test_init_arg() -> None:\n    global count_d\n    count_d = 0\n\n    # Use Any to get non-native semantics\n    cls: Any = D\n    # __new__ implicitly calls __init__ for native classes\n    obj = cls.__new__(cls, 'abc')\n    assert obj.get() == 'abc'\n    assert count_d == 1\n    # Make sure we don't call __init__ twice\n    obj2 = cls('x')\n    assert obj2.get() == 'x'\n    assert count_d == 2\n    # Keyword args should work\n    obj = cls.__new__(cls, x='abc')\n    assert obj.get() == 'abc'\n    assert count_d == 3\n\ndef test_invalid_init_args() -> None:\n    # Use Any to get non-native semantics\n    cls: Any = D\n    with assertRaises(TypeError):\n        cls()\n    with assertRaises(TypeError):\n        cls(y='x')\n    with assertRaises(TypeError):\n        cls(1)\n\n[case testTryDeletingAlwaysDefinedAttribute]\nfrom typing import Any\nfrom testutil import assertRaises\n\nclass C:\n    def __init__(self) -> None:\n        self.x = 0\n\nclass D(C):\n    pass\n\ndef test_try_deleting_always_defined_attr() -> None:\n    c: Any = C()\n    with assertRaises(AttributeError):\n        del c.x\n    d: Any = D()\n    with assertRaises(AttributeError):\n        del d.x\n\n[case testAlwaysDefinedAttributeAndAllowInterpretedSubclasses]\nfrom mypy_extensions import mypyc_attr\n\nfrom m import define_interpreted_subclass\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass Base:\n    x = 5\n    y: int\n    def __init__(self, s: str) -> None:\n        self.s = s\n\nclass DerivedNative(Base):\n    def __init__(self) -> None:\n        super().__init__('x')\n        self.z = 3\n\ndef test_native_subclass() -> None:\n    o = DerivedNative()\n    assert o.x == 5\n    assert o.s == 'x'\n    assert o.z == 3\n\ndef test_interpreted_subclass() -> None:\n    define_interpreted_subclass(Base)\n\n[file m.py]\nfrom testutil import assertRaises\n\ndef define_interpreted_subclass(b):\n    class DerivedInterpreted1(b):  # type: ignore[misc, valid-type]\n        def __init__(self):\n            # Don't call base class __init__\n            pass\n    d1 = DerivedInterpreted1()\n    assert d1.x == 5\n    with assertRaises(AttributeError):\n        d1.y\n    with assertRaises(AttributeError):\n        d1.s\n    with assertRaises(AttributeError):\n        del d1.x\n\n    class DerivedInterpreted2(b):  # type: ignore[misc, valid-type]\n        def __init__(self):\n            super().__init__('y')\n    d2 = DerivedInterpreted2()\n    assert d2.x == 5\n    assert d2.s == 'y'\n    with assertRaises(AttributeError):\n        d2.y\n    with assertRaises(AttributeError):\n        del d2.x\n\n[case testBaseClassSometimesDefinesAttribute]\nclass C:\n    def __init__(self, b: bool) -> None:\n        if b:\n            self.x = [1]\n\nclass D(C):\n    def __init__(self, b: bool) -> None:\n        super().__init__(b)\n        self.x = [2]\n\ndef test_base_class() -> None:\n    c = C(True)\n    assert c.x == [1]\n    c = C(False)\n    try:\n        c.x\n    except AttributeError:\n        return\n    assert False\n\ndef test_subclass() -> None:\n    d = D(True)\n    assert d.x == [2]\n    d = D(False)\n    assert d.x == [2]\n\n[case testSerializableClass]\nfrom mypy_extensions import mypyc_attr\nfrom typing import Any\nimport copy\nfrom testutil import assertRaises\n\n@mypyc_attr(serializable=True)\nclass Base:\n    def __init__(self, s: str) -> None:\n        self.s = s\n\nclass Derived(Base):\n    def __init__(self, s: str, n: int) -> None:\n        super().__init__(s)\n        self.n = n\n\ndef test_copy_base() -> None:\n    o = Base('xyz')\n    o2 = copy.copy(o)\n    assert isinstance(o2, Base)\n    assert o2 is not o\n    assert o2.s == 'xyz'\n\ndef test_copy_derived() -> None:\n    d = Derived('xyz', 5)\n    d2 = copy.copy(d)\n    assert isinstance(d2, Derived)\n    assert d2 is not d\n    assert d2.s == 'xyz'\n    assert d2.n == 5\n\nclass NonSerializable:\n    def __init__(self, s: str) -> None:\n        self.s = s\n\n@mypyc_attr(serializable=True)\nclass SerializableSub(NonSerializable):\n    def __init__(self, s: str, n: int) -> None:\n        super().__init__(s)\n        self.n = n\n\ndef test_serializable_sub_class() -> None:\n    n = NonSerializable('xyz')\n    assert n.s == 'xyz'\n\n    with assertRaises(TypeError):\n        copy.copy(n)\n\n    s = SerializableSub('foo', 6)\n    s2 = copy.copy(s)\n    assert s2 is not s\n    assert s2.s == 'foo'\n    assert s2.n == 6\n\ndef test_serializable_sub_class_call_new() -> None:\n    t: Any = SerializableSub\n    sub: SerializableSub = t.__new__(t)\n    with assertRaises(AttributeError):\n        sub.s\n    with assertRaises(AttributeError):\n        sub.n\n    base: NonSerializable = sub\n    with assertRaises(AttributeError):\n        base.s\n\n[case testClassWithInherited__call__]\nclass Base:\n    def __call__(self) -> int:\n        return 1\n\nclass Derived(Base):\n    pass\n\ndef test_inherited() -> None:\n    assert Derived()() == 1\n\n[case testClassWithFinalAttribute]\nfrom typing import Final\n\nclass C:\n    A: Final = -1\n    a: Final = [A]\n\ndef test_final_attribute() -> None:\n    assert C.A == -1\n    assert C.a == [-1]\n\n[case testClassWithFinalDecorator]\nfrom typing import final\n\n@final\nclass C:\n    def a(self) -> int:\n        return 1\n\ndef test_class_final_attribute() -> None:\n    assert C().a() == 1\n\n\n[case testClassWithFinalDecoratorCtor]\nfrom typing import final\n\n@final\nclass C:\n    def __init__(self) -> None:\n        self.a = 1\n\n    def b(self) -> int:\n        return 2\n\n    @property\n    def c(self) -> int:\n        return 3\n\ndef test_class_final_attribute() -> None:\n    assert C().a == 1\n    assert C().b() == 2\n    assert C().c == 3\n\n[case testClassWithFinalDecoratorInheritedWithProperties]\nfrom typing import final\n\nclass B:\n    def a(self) -> int:\n        return 2\n\n    @property\n    def b(self) -> int:\n        return self.a() + 2\n\n    @property\n    def c(self) -> int:\n        return 3\n\ndef test_class_final_attribute_basic() -> None:\n    assert B().a() == 2\n    assert B().b == 4\n    assert B().c == 3\n\n@final\nclass C(B):\n    def a(self) -> int:\n        return 1\n\n    @property\n    def b(self) -> int:\n        return self.a() + 1\n\ndef fn(cl: B) -> int:\n    return cl.a()\n\ndef test_class_final_attribute_inherited() -> None:\n    assert C().a() == 1\n    assert fn(C()) == 1\n    assert B().a() == 2\n    assert fn(B()) == 2\n\n    assert B().b == 4\n    assert C().b == 2\n    assert B().c == 3\n    assert C().c == 3\n\n[case testClassWithFinalAttributeAccess]\nfrom typing import Final\n\nclass C:\n    a: Final = {'x': 'y'}\n    b: Final = C.a\n\ndef test_final_attribute() -> None:\n    assert C.a['x'] == 'y'\n    assert C.b['x'] == 'y'\n    assert C.a is C.b\n\n[case testClassDerivedFromIntEnum]\nfrom enum import IntEnum, auto\n\nclass Player(IntEnum):\n    MIN = auto()\n\nprint(f'{Player.MIN = }')\n[file driver.py]\nfrom native import Player\n[out]\nPlayer.MIN = <Player.MIN: 1>\n\n[case testBufferRoundTrip_librt_internal]\nfrom __future__ import annotations\n\nfrom typing import Final, Any\nfrom mypy_extensions import u8\nfrom librt.internal import (\n    ReadBuffer, WriteBuffer, write_bool, read_bool, write_str, read_str, write_float, read_float,\n    write_int, read_int, write_tag, read_tag, write_bytes, read_bytes,\n    cache_version,\n)\n\nfrom testutil import assertRaises\n\nTag = u8\nTAG_A: Final[Tag] = 33\nTAG_B: Final[Tag] = 255\nTAG_SPECIAL: Final[Tag] = 239\n\ndef test_buffer_basic() -> None:\n    assert cache_version() == 0\n    w = WriteBuffer()\n    write_str(w, \"foo\")\n    r = ReadBuffer(w.getvalue())\n    assert read_str(r) == \"foo\"\n\ndef test_buffer_grow() -> None:\n    w = WriteBuffer()\n    n = 100 * 1000\n    for i in range(n):\n        write_int(w, i & 63)\n    r = ReadBuffer(w.getvalue())\n    for i in range(n):\n        assert read_int(r) == (i & 63)\n    with assertRaises(ValueError):\n        read_int(r)\n\ndef test_buffer_primitive_types() -> None:\n    a1: Any = WriteBuffer()\n    w: WriteBuffer = a1\n    write_str(w, \"foo\")\n    data = w.getvalue()\n    assert read_str(ReadBuffer(data)) == \"foo\"\n    a2: Any = ReadBuffer(b\"foo\")\n    with assertRaises(TypeError):\n        w2: WriteBuffer = a2\n\n    a3: Any = ReadBuffer(data)\n    r: ReadBuffer = a3\n    assert read_str(r) == \"foo\"\n    a4: Any = WriteBuffer()\n    with assertRaises(TypeError):\n        r2: ReadBuffer = a4\n\ndef test_type_check_args_in_write_functions() -> None:\n    # Test calling wrapper functions with invalid arg types\n    from librt import internal\n    alias: Any = internal\n    w = WriteBuffer()\n    with assertRaises(TypeError):\n        alias.write_str(None, \"foo\")\n    with assertRaises(TypeError):\n        alias.write_str(w, None)\n    with assertRaises(TypeError):\n        alias.write_bool(None, True)\n    with assertRaises(TypeError):\n        alias.write_bool(w, None)\n    with assertRaises(TypeError):\n        alias.write_bytes(None, b\"foo\")\n    with assertRaises(TypeError):\n        alias.write_bytes(w, None)\n    with assertRaises(TypeError):\n        alias.write_float(None, 1.5)\n    with assertRaises(TypeError):\n        alias.write_float(w, None)\n    with assertRaises(TypeError):\n        alias.write_int(None, 15)\n    with assertRaises(TypeError):\n        alias.write_int(w, None)\n    with assertRaises(TypeError):\n        alias.write_tag(None, 15)\n    with assertRaises(TypeError):\n        alias.write_tag(w, None)\n\ndef test_type_check_buffer_in_read_functions() -> None:\n    # Test calling wrapper functions with invalid arg types\n    from librt import internal\n    alias: Any = internal\n    with assertRaises(TypeError):\n        alias.read_str(None)\n    with assertRaises(TypeError):\n        alias.read_bool(None)\n    with assertRaises(TypeError):\n        alias.read_bytes(None)\n    with assertRaises(TypeError):\n        alias.read_float(None)\n    with assertRaises(TypeError):\n        alias.read_int(None)\n    with assertRaises(TypeError):\n        alias.read_tag(None)\n\ndef test_buffer_roundtrip() -> None:\n    b: WriteBuffer | ReadBuffer\n    b = WriteBuffer()\n    write_str(b, \"foo\")\n    write_bool(b, True)\n    write_str(b, \"bar\" * 1000)\n    write_bool(b, False)\n    write_bytes(b, b\"bar\")\n    write_bytes(b, b\"bar\" * 100)\n    write_bytes(b, b\"\")\n    write_bytes(b, b\"a\" * 117)\n    write_bytes(b, b\"a\" * 118)\n    write_float(b, 0.1)\n    write_float(b, -1.0)\n    write_float(b, -113.0)\n    write_int(b, 0)\n    write_int(b, 1)\n    write_tag(b, TAG_A)\n    write_tag(b, TAG_SPECIAL)\n    write_tag(b, TAG_B)\n    write_int(b, 2)\n    write_int(b, 2 ** 85)\n    write_int(b, 255)\n    write_int(b, -1)\n    write_int(b, -255)\n    write_int(b, 536860911)\n    write_int(b, 536860912)\n    write_int(b, 1234567891)\n\n    b = ReadBuffer(b.getvalue())\n    assert read_str(b) == \"foo\"\n    assert read_bool(b) is True\n    assert read_str(b) == \"bar\" * 1000\n    assert read_bool(b) is False\n    assert read_bytes(b) == b\"bar\"\n    assert read_bytes(b) == b\"bar\" * 100\n    assert read_bytes(b) == b\"\"\n    assert read_bytes(b) == b\"a\" * 117\n    assert read_bytes(b) == b\"a\" * 118\n    assert read_float(b) == 0.1\n    assert read_float(b) == -1.0\n    assert read_float(b) == -113.0\n    assert read_int(b) == 0\n    assert read_int(b) == 1\n    assert read_tag(b) == TAG_A\n    assert read_tag(b) == TAG_SPECIAL\n    assert read_tag(b) == TAG_B\n    assert read_int(b) == 2\n    assert read_int(b) == 2 ** 85\n    assert read_int(b) == 255\n    assert read_int(b) == -1\n    assert read_int(b) == -255\n    assert read_int(b) == 536860911\n    assert read_int(b) == 536860912\n    assert read_int(b) == 1234567891\n\ndef test_buffer_int_size() -> None:\n    b: WriteBuffer | ReadBuffer\n    for i in (-10, -9, 0, 116, 117):\n        b = WriteBuffer()\n        write_int(b, i)\n        assert len(b.getvalue()) == 1\n        b = ReadBuffer(b.getvalue())\n        assert read_int(b) == i\n    for i in (-100, -11, 118, 12344, 16283):\n        b = WriteBuffer()\n        write_int(b, i)\n        assert len(b.getvalue()) == 2\n        b = ReadBuffer(b.getvalue())\n        assert read_int(b) == i\n    for i in (-10000, 16284, 123456789):\n        b = WriteBuffer()\n        write_int(b, i)\n        assert len(b.getvalue()) == 4\n        b = ReadBuffer(b.getvalue())\n        assert read_int(b) == i\n\ndef test_buffer_int_powers() -> None:\n    # 0, 1, 2 are tested above\n    for p in range(2, 200):\n        b = WriteBuffer()\n        write_int(b, 1 << p)\n        write_int(b, (1 << p) - 1)\n        write_int(b, -1 << p)\n        write_int(b, (-1 << p) + 1)\n        rb = ReadBuffer(b.getvalue())\n        assert read_int(rb) == 1 << p\n        assert read_int(rb) == (1 << p) - 1\n        assert read_int(rb) == -1 << p\n        assert read_int(rb) == (-1 << p) + 1\n\ndef test_positive_long_int_serialized_bytes() -> None:\n    b = WriteBuffer()\n    n = 0x123456789ab\n    write_int(b, n)\n    x = b.getvalue()\n    # Two prefix bytes, followed by little endian encoded integer in variable-length format\n    assert x == b\"\\x0f\\x2c\\xab\\x89\\x67\\x45\\x23\\x01\"\n    rb = ReadBuffer(x)\n    assert read_int(rb) == n\n\ndef test_negative_long_int_serialized_bytes() -> None:\n    b = WriteBuffer()\n    n = -0x123456789abcde\n    write_int(b, n)\n    x = b.getvalue()\n    assert x == b\"\\x0f\\x32\\xde\\xbc\\x9a\\x78\\x56\\x34\\x12\"\n    rb = ReadBuffer(x)\n    assert read_int(rb) == n\n\ndef test_buffer_str_size() -> None:\n    b: WriteBuffer | ReadBuffer\n    for s in (\"\", \"a\", \"a\" * 117):\n        b = WriteBuffer()\n        write_str(b, s)\n        assert len(b.getvalue()) == len(s) + 1\n        b = ReadBuffer(b.getvalue())\n        assert read_str(b) == s\n\n    for s in (\"a\" * 118, \"a\" * 16283):\n        b = WriteBuffer()\n        write_str(b, s)\n        assert len(b.getvalue()) == len(s) + 2\n        b = ReadBuffer(b.getvalue())\n        assert read_str(b) == s\n\n[file driver.py]\nfrom native import *\n\ntest_buffer_basic()\ntest_buffer_grow()\ntest_buffer_primitive_types()\ntest_type_check_args_in_write_functions()\ntest_type_check_buffer_in_read_functions()\ntest_buffer_roundtrip()\ntest_buffer_int_size()\ntest_buffer_str_size()\ntest_buffer_int_powers()\ntest_positive_long_int_serialized_bytes()\ntest_negative_long_int_serialized_bytes()\n\ndef test_buffer_basic_interpreted() -> None:\n    b = WriteBuffer()\n    write_str(b, \"foo\")\n    b = ReadBuffer(b.getvalue())\n    assert read_str(b) == \"foo\"\n\ndef test_buffer_roundtrip_interpreted() -> None:\n    b = WriteBuffer()\n    write_str(b, \"foo\")\n    write_bool(b, True)\n    write_str(b, \"bar\" * 1000)\n    write_bool(b, False)\n    write_bytes(b, b\"bar\")\n    write_bytes(b, b\"bar\" * 100)\n    write_bytes(b, b\"\")\n    write_bytes(b, b\"a\" * 117)\n    write_bytes(b, b\"a\" * 118)\n    write_float(b, 0.1)\n    write_int(b, 0)\n    write_int(b, 1)\n    write_tag(b, 33)\n    write_tag(b, 239)\n    write_tag(b, 255)\n    write_int(b, 2)\n    write_int(b, 2 ** 85)\n    write_int(b, 255)\n    write_int(b, -1)\n    write_int(b, -255)\n    write_int(b, 536860911)\n    write_int(b, 536860912)\n    write_int(b, 1234567891)\n\n    b = ReadBuffer(b.getvalue())\n    assert read_str(b) == \"foo\"\n    assert read_bool(b) is True\n    assert read_str(b) == \"bar\" * 1000\n    assert read_bool(b) is False\n    assert read_bytes(b) == b\"bar\"\n    assert read_bytes(b) == b\"bar\" * 100\n    assert read_bytes(b) == b\"\"\n    assert read_bytes(b) == b\"a\" * 117\n    assert read_bytes(b) == b\"a\" * 118\n    assert read_float(b) == 0.1\n    assert read_int(b) == 0\n    assert read_int(b) == 1\n    assert read_tag(b) == 33\n    assert read_tag(b) == 239\n    assert read_tag(b) == 255\n    assert read_int(b) == 2\n    assert read_int(b) == 2 ** 85\n    assert read_int(b) == 255\n    assert read_int(b) == -1\n    assert read_int(b) == -255\n    assert read_int(b) == 536860911\n    assert read_int(b) == 536860912\n    assert read_int(b) == 1234567891\n\ndef test_buffer_int_size_interpreted() -> None:\n    for i in (-10, -9, 0, 116, 117):\n        b = WriteBuffer()\n        write_int(b, i)\n        assert len(b.getvalue()) == 1\n        b = ReadBuffer(b.getvalue())\n        assert read_int(b) == i\n    for i in (-100, -11, 118, 12344, 16283):\n        b = WriteBuffer()\n        write_int(b, i)\n        assert len(b.getvalue()) == 2\n        b = ReadBuffer(b.getvalue())\n        assert read_int(b) == i\n    for i in (-10000, 16284, 123456789):\n        b = WriteBuffer()\n        write_int(b, i)\n        assert len(b.getvalue()) == 4\n        b = ReadBuffer(b.getvalue())\n        assert read_int(b) == i\n\ndef test_buffer_int_powers_interpreted() -> None:\n    # 0, 1, 2 are tested above\n    for p in range(2, 9):\n        b = WriteBuffer()\n        write_int(b, 1 << p)\n        write_int(b, -1 << p)\n        b = ReadBuffer(b.getvalue())\n        assert read_int(b) == 1 << p\n        assert read_int(b) == -1 << p\n\ndef test_buffer_str_size_interpreted() -> None:\n    for s in (\"\", \"a\", \"a\" * 117):\n        b = WriteBuffer()\n        write_str(b, s)\n        assert len(b.getvalue()) == len(s) + 1\n        b = ReadBuffer(b.getvalue())\n        assert read_str(b) == s\n\n    for s in (\"a\" * 118, \"a\" * 16283):\n        b = WriteBuffer()\n        write_str(b, s)\n        assert len(b.getvalue()) == len(s) + 2\n        b = ReadBuffer(b.getvalue())\n        assert read_str(b) == s\n\ntest_buffer_basic_interpreted()\ntest_buffer_roundtrip_interpreted()\ntest_buffer_int_size_interpreted()\ntest_buffer_str_size_interpreted()\ntest_buffer_int_powers_interpreted()\n\n[case testBufferEmpty_librt_internal]\nfrom librt.internal import WriteBuffer, ReadBuffer, write_int, read_int\n\ndef test_empty() -> None:\n    b = WriteBuffer()\n    write_int(b, 42)\n    b1 = ReadBuffer(b.getvalue())\n    assert read_int(b1) == 42\n\n[case testEnumMethodCalls]\nfrom enum import Enum\nfrom typing import overload, Optional, Union\n\nclass C:\n    def foo(self, x: Test) -> bool:\n        assert Test.ONE.is_one()\n        assert x.next(2) == Test.THREE\n        assert x.prev(2) == Test.ONE\n        assert x.enigma(22)\n        assert x.enigma(\"22\") == 22\n        return x.is_one(inverse=True)\n\nclass Test(Enum):\n    ONE = 1\n    TWO = 2\n    THREE = 3\n\n    def is_one(self, *, inverse: bool = False) -> bool:\n        if inverse:\n            return self != Test.ONE\n        return self == Test.ONE\n\n    @classmethod\n    def next(cls, val: int) -> Test:\n        return cls(val + 1)\n\n    @staticmethod\n    def prev(val: int) -> Test:\n        return Test(val - 1)\n\n    @overload\n    def enigma(self, val: int) -> bool: ...\n    @overload\n    def enigma(self, val: Optional[str] = None) -> int: ...\n    def enigma(self, val: Union[int, str, None] = None) -> Union[int, bool]:\n        if isinstance(val, int):\n            return self.is_one()\n        return 22\n[file driver.py]\nfrom native import Test, C\n\nassert Test.ONE.is_one()\nassert Test.TWO.is_one(inverse=True)\nassert not C().foo(Test.ONE)\nassert Test.next(2) == Test.THREE\nassert Test.prev(2) == Test.ONE\nassert Test.ONE.enigma(22)\nassert Test.ONE.enigma(\"22\") == 22\n\n[case testStaticCallsWithUnpackingArgs]\nfrom typing import Tuple\n\nclass Foo:\n  @staticmethod\n  def static(a: int, b: int, c: int) -> Tuple[int, int, int]:\n    return (c+1, a+2, b+3)\n\n  @classmethod\n  def clsmethod(cls, a: int, b: int, c: int) -> Tuple[int, int, int]:\n    return (c+1, a+2, b+3)\n\n\nprint(Foo.static(*[10, 20, 30]))\nprint(Foo.static(*(40, 50), *[60]))\nassert Foo.static(70, 80, *[90]) == Foo.clsmethod(70, *(80, 90))\n\n[file driver.py]\nimport native\n\n[out]\n(31, 12, 23)\n(61, 42, 53)\n\n[case testDataclassInitVar]\nimport dataclasses\n\n@dataclasses.dataclass\nclass C:\n    init_v: dataclasses.InitVar[int]\n    v: float = dataclasses.field(init=False)\n\n    def __post_init__(self, init_v):\n        self.v = init_v + 0.1\n\n[file driver.py]\nimport native\nprint(native.C(22).v)\n\n[out]\n22.1\n\n[case testLastParentEnum]\nfrom enum import Enum\n\nclass ColorCode(str, Enum):\n    OKGREEN = \"okgreen\"\n\n[file driver.py]\nimport native\nprint(native.ColorCode.OKGREEN.value)\n\n[out]\nokgreen\n\n[case testAttrWithSlots]\nimport attr\n\n@attr.s(slots=True)\nclass A:\n    ints: list[int] = attr.ib()\n\n[file driver.py]\nimport native\nprint(native.A(ints=[1, -17]).ints)\n\n[out]\n\\[1, -17]\n\n[case testDataclassClassReference]\nfrom __future__ import annotations\nfrom dataclasses import dataclass\n\nclass BackwardDefinedClass:\n    pass\n\n@dataclass\nclass Data:\n    bitem: BackwardDefinedClass\n    bitems: 'BackwardDefinedClass'\n    fitem: ForwardDefinedClass\n    fitems: 'ForwardDefinedClass'\n\nclass ForwardDefinedClass:\n    pass\n\ndef test_function():\n    d = Data(\n        bitem=BackwardDefinedClass(),\n        bitems=BackwardDefinedClass(),\n        fitem=ForwardDefinedClass(),\n        fitems=ForwardDefinedClass(),\n    )\n    assert(isinstance(d.bitem, BackwardDefinedClass))\n    assert(isinstance(d.bitems, BackwardDefinedClass))\n    assert(isinstance(d.fitem, ForwardDefinedClass))\n    assert(isinstance(d.fitems, ForwardDefinedClass))\n\n[case testDelForDictSubclass-xfail]\n# The crash in issue mypy#19175 is fixed.\n# But, for classes that derive from built-in Python classes, user-defined __del__ method is not\n# being invoked.\nclass DictSubclass(dict):\n    def __del__(self):\n        print(\"deleting DictSubclass...\")\n\n[file driver.py]\nimport native\nnative.DictSubclass()\n\n[out]\ndeleting DictSubclass...\n\n[case testDel]\nclass A:\n    def __del__(self):\n        print(\"deleting A...\")\n\nclass B:\n    def __del__(self):\n        print(\"deleting B...\")\n\nclass C(B):\n    def __init__(self):\n        self.a = A()\n\n    def __del__(self):\n        print(\"deleting C...\")\n        super().__del__()\n\nclass D(A):\n    pass\n\n# Just make sure that this class compiles (see issue mypy#19175). testDelForDictSubclass tests for\n# correct output.\nclass NormDict(dict):\n    def __del__(self) -> None:\n        pass\n\n[file driver.py]\nimport native\nnative.C()\nnative.D()\n\n[out]\ndeleting C...\ndeleting B...\ndeleting A...\ndeleting A...\n\n[case testDelCircular]\nimport dataclasses\nimport typing\n\ni: int = 1\n\n@dataclasses.dataclass\nclass C:\n    var: typing.Optional[\"C\"] = dataclasses.field(default=None)\n\n    def __del__(self):\n        global i\n        print(f\"deleting C{i}...\")\n        i = i + 1\n\n[file driver.py]\nimport native\nimport gc\n\nc1 = native.C()\nc2 = native.C()\nc1.var = c2\nc2.var = c1\ndel c1\ndel c2\ngc.collect()\n\n[out]\ndeleting C1...\ndeleting C2...\n\n[case testDelException]\n# The error message in the expected output of this test does not match CPython's error message due to the way mypyc compiles Python classes. If the error message is fixed, the expected output of this test will also change.\nclass F:\n    def __del__(self):\n        if True:\n            raise Exception(\"e2\")\n\n[file driver.py]\nimport native\nf = native.F()\ndel f\n\n[out]\nException ignored in: <native.F object at 0x000000000000>\nTraceback (most recent call last):\n  File \"native.py\", line 5, in __del__\n    raise Exception(\"e2\")\nException: e2\n\n[case testMypycAttrNativeClass]\nfrom mypy_extensions import mypyc_attr\nfrom testutil import assertRaises\n\n@mypyc_attr(native_class=False)\nclass AnnontatedNonExtensionClass:\n    pass\n\nclass DerivedClass(AnnontatedNonExtensionClass):\n    pass\n\nclass ImplicitExtensionClass():\n    pass\n\n@mypyc_attr(native_class=True)\nclass AnnotatedExtensionClass():\n    pass\n\ndef test_function():\n    setattr(AnnontatedNonExtensionClass, 'attr_class', 5)\n    assert(hasattr(AnnontatedNonExtensionClass, 'attr_class') == True)\n    assert(getattr(AnnontatedNonExtensionClass, 'attr_class') == 5)\n    delattr(AnnontatedNonExtensionClass, 'attr_class')\n    assert(hasattr(AnnontatedNonExtensionClass, 'attr_class') == False)\n\n    inst = AnnontatedNonExtensionClass()\n    setattr(inst, 'attr_instance', 6)\n    assert(hasattr(inst, 'attr_instance') == True)\n    assert(getattr(inst, 'attr_instance') == 6)\n    delattr(inst, 'attr_instance')\n    assert(hasattr(inst, 'attr_instance') == False)\n\n    setattr(DerivedClass, 'attr_class', 5)\n    assert(hasattr(DerivedClass, 'attr_class') == True)\n    assert(getattr(DerivedClass, 'attr_class') == 5)\n    delattr(DerivedClass, 'attr_class')\n    assert(hasattr(DerivedClass, 'attr_class') == False)\n\n    derived_inst = DerivedClass()\n    setattr(derived_inst, 'attr_instance', 6)\n    assert(hasattr(derived_inst, 'attr_instance') == True)\n    assert(getattr(derived_inst, 'attr_instance') == 6)\n    delattr(derived_inst, 'attr_instance')\n    assert(hasattr(derived_inst, 'attr_instance') == False)\n\n    ext_inst = ImplicitExtensionClass()\n    with assertRaises(AttributeError):\n        setattr(ext_inst, 'attr_instance', 6)\n\n    explicit_ext_inst = AnnotatedExtensionClass()\n    with assertRaises(AttributeError):\n        setattr(explicit_ext_inst, 'attr_instance', 6)\n\n[case testMypycAttrNativeClassDunder]\nfrom mypy_extensions import mypyc_attr\nfrom typing import Generic, Optional, TypeVar\n\n_T = TypeVar(\"_T\")\n\nget_count = set_count = del_count = 0\n\n@mypyc_attr(native_class=False)\nclass Bar(Generic[_T]):\n    # Note the lack of __deletable__\n    def __init__(self) -> None:\n        self.value: str = 'start'\n    def __get__(self, instance: _T, owner: Optional[type[_T]] = None) -> str:\n        global get_count\n        get_count += 1\n        return self.value\n    def __set__(self, instance: _T, value: str) -> None:\n        global set_count\n        set_count += 1\n        self.value = value\n    def __delete__(self, instance: _T) -> None:\n        global del_count\n        del_count += 1\n        del self.value\n\n@mypyc_attr(native_class=False)\nclass Foo(object):\n    bar: Bar = Bar()\n\n[file driver.py]\nimport native\n\nf = native.Foo()\nassert(hasattr(f, 'bar'))\nassert(native.get_count == 1)\nassert(f.bar == 'start')\nassert(native.get_count == 2)\nf.bar = 'test'\nassert(f.bar == 'test')\nassert(native.set_count == 1)\ndel f.bar\nassert(not hasattr(f, 'bar'))\nassert(native.del_count == 1)\n\n[case testMypycAttrNativeClassMeta]\nfrom mypy_extensions import mypyc_attr\nfrom typing import ClassVar, TypeVar\n\n_T = TypeVar(\"_T\")\n\n@mypyc_attr(native_class=False)\nclass M(type):\n    count: ClassVar[int] = 0\n    def make(cls: type[_T]) -> _T:\n        M.count += 1\n        return cls()\n\n# implicit native_class=False\n# see testMypycAttrNativeClassMetaError for when trying to set it True\nclass A(metaclass=M):\n    pass\n\n[file driver.py]\nimport native\n\na: native.A = native.A.make()\nassert(native.A.count == 1)\n\nclass B(native.A):\n    pass\n\nb: B = B.make()\nassert(B.count == 2)\n\n[case testTypeVarNarrowing]\nfrom typing import TypeVar\n\nclass B:\n    def __init__(self, x: int) -> None:\n        self.x = x\nclass C(B):\n    def __init__(self, x: int, y: str) -> None:\n        self.x = x\n        self.y = y\n\nT = TypeVar(\"T\", bound=B)\ndef f(x: T) -> T:\n    if isinstance(x, C):\n        print(\"C\", x.y)\n        return x\n    print(\"B\", x.x)\n    return x\n\n[file driver.py]\nfrom native import f, B, C\n\nf(B(1))\nf(C(1, \"yes\"))\n[out]\nB 1\nC yes\n\n[case testTypeObjectName]\nfrom typing import Any\nimport re\n\nfrom dynamic import E, foo, Thing\n\nclass C: pass\nclass D(C): pass\n\ndef type_name(t: type[object]) -> str:\n    return t.__name__\n\ndef any_name(x: Any) -> str:\n    return x.__name__\n\ndef assert_type_name(x: Any) -> None:\n    assert type_name(x) == getattr(x, \"__name__\")\n    assert any_name(x) == getattr(x, \"__name__\")\n\ndef assert_any_name(x: Any) -> None:\n    assert any_name(x) == getattr(x, \"__name__\")\n\ndef test_type_name() -> None:\n    assert_type_name(C)\n    assert_type_name(D)\n    assert_type_name(int)\n    assert_type_name(E)\n    assert_type_name(re.Pattern)\n\ndef test_module_name() -> None:\n    assert_any_name(re)\n\ndef test_function_name() -> None:\n    assert_any_name(any_name)\n    assert_any_name(foo)\n\ndef test_obj_name() -> None:\n    assert_any_name(Thing())\n\n[file dynamic.py]\nclass E: pass\n\ndef foo(): pass\n\nclass Thing:\n    def __init__(self):\n        self.__name__ = \"xyz\"\n\n[case testTypeOfObject]\nfrom typing import Any\n\nfrom dynamic import Dyn\n\nclass Foo: pass\nclass Bar(Foo): pass\n\ndef generic_type(x) -> type[object]:\n    return x.__class__\n\ndef test_built_in_type() -> None:\n    i: Any = int\n    l: Any = list\n    assert type(i()) is i().__class__\n    assert type(i()) is int\n    assert type(l()) is list\n    n = 5\n    assert n.__class__ is i\n\ndef test_native_class() -> None:\n    f_any: Any = Foo()\n    b_any: Any = Bar()\n    f: Foo = f_any\n    b: Foo = b_any\n    if int(\"1\"):  # use int(\"1\") to avoid constant folding\n        assert type(f) is Foo\n        assert type(b) is Bar\n    if int(\"2\"):\n        assert f.__class__ is Foo\n        assert b.__class__ is Bar\n    if int(\"3\"):\n        assert f_any.__class__ is Foo\n        assert b_any.__class__ is Bar\n    if int(\"4\"):\n        assert type(f_any) is Foo\n        assert type(b_any) is Bar\n\ndef test_python_class() -> None:\n    d = Dyn()\n    assert type(d) is Dyn\n    assert d.__class__ is Dyn\n\n[file dynamic.py]\nclass Dyn: pass\n\n[case testDunderNew]\nfrom __future__ import annotations\nfrom typing import Any, Union\n\nfrom testutil import assertRaises\n\nclass Add:\n    l: IntLike\n    r: IntLike\n\n    def __new__(cls, l: IntLike, r: IntLike) -> Any:\n        return (\n            l if r == 0 else\n            r if l == 0 else\n            super().__new__(cls)\n        )\n\n    def __init__(self, l: IntLike, r: IntLike):\n        self.l = l\n        self.r = r\n\nIntLike = Union[int, Add]\n\nclass RaisesException:\n    def __new__(cls, val: int) -> RaisesException:\n        if val == 0:\n            raise RuntimeError(\"Invalid value!\")\n        return super().__new__(cls)\n\n    def __init__(self, val: int) -> None:\n        self.val = val\n\nclass ClsArgNotPassed:\n    def __new__(cls) -> Any:\n        return super().__new__(str)\n\ndef test_dunder_new() -> None:\n    add_instance: Any = Add(1, 5)\n    assert type(add_instance) == Add\n    assert add_instance.l == 1\n    assert add_instance.r == 5\n\n    # TODO: explicit types should not be needed but mypy does not use\n    # the return type of __new__ which makes mypyc add casts to Add.\n    right_int: Any = Add(0, 5)\n    assert type(right_int) == int\n    assert right_int == 5\n\n    left_int: Any = Add(1, 0)\n    assert type(left_int) == int\n    assert left_int == 1\n\n    with assertRaises(RuntimeError, \"Invalid value!\"):\n        raised = RaisesException(0)\n\n    not_raised = RaisesException(1)\n    assert not_raised.val == 1\n\n    with assertRaises(TypeError, \"object.__new__(str) is not safe, use str.__new__()\"):\n        str_as_cls = ClsArgNotPassed()\n\n\n[case testDunderNewInInterpreted]\nfrom __future__ import annotations\nfrom typing import Any, Union\n\nclass Add:\n    l: IntLike\n    r: IntLike\n\n    def __new__(cls, l: IntLike, r: IntLike) -> Any:\n        print(f'running __new__ with {l} and {r}')\n\n        return (\n            l if r == 0 else\n            r if l == 0 else\n            super().__new__(cls)\n        )\n\n    def __init__(self, l: IntLike, r: IntLike):\n        self.l = l\n        self.r = r\n\n    def __repr__(self) -> str:\n        return f'({self.l} + {self.r})'\n\nIntLike = Union[int, Add]\n\nclass RaisesException:\n    def __new__(cls, val: int) -> RaisesException:\n        if val == 0:\n            raise RuntimeError(\"Invalid value!\")\n        return super().__new__(cls)\n\n    def __init__(self, val: int) -> None:\n        self.val = val\n\nclass ClsArgNotPassed:\n    def __new__(cls) -> Any:\n        return super().__new__(str)\n\n[file driver.py]\nfrom native import Add, ClsArgNotPassed, RaisesException\n\nfrom testutil import assertRaises\n\nprint(f'{Add(1, 5)=}')\nprint(f'{Add(0, 5)=}')\nprint(f'{Add(1, 0)=}')\n\nwith assertRaises(RuntimeError, \"Invalid value!\"):\n    raised = RaisesException(0)\n\nnot_raised = RaisesException(1)\nassert not_raised.val == 1\n\nwith assertRaises(TypeError, \"object.__new__(str) is not safe, use str.__new__()\"):\n    str_as_cls = ClsArgNotPassed()\n\n[out]\nrunning __new__ with 1 and 5\nAdd(1, 5)=(1 + 5)\nrunning __new__ with 0 and 5\nAdd(0, 5)=5\nrunning __new__ with 1 and 0\nAdd(1, 0)=1\n\n[case testObjectDunderNew]\nfrom __future__ import annotations\nfrom typing import Any, Union\n\nfrom testutil import assertRaises\n\nclass Add:\n    l: IntLike\n    r: IntLike\n\n    def __new__(cls, l: IntLike, r: IntLike) -> Any:\n        return (\n            l if r == 0 else\n            r if l == 0 else\n            object.__new__(cls)\n        )\n\n    def __init__(self, l: IntLike, r: IntLike):\n        self.l = l\n        self.r = r\n\nIntLike = Union[int, Add]\n\nclass RaisesException:\n    def __new__(cls, val: int) -> RaisesException:\n        if val == 0:\n            raise RuntimeError(\"Invalid value!\")\n        return object.__new__(cls)\n\n    def __init__(self, val: int) -> None:\n        self.val = val\n\nclass ClsArgNotPassed:\n    def __new__(cls) -> Any:\n        return object.__new__(str)\n\nclass SkipsBase(Add):\n    def __new__(cls) -> Any:\n        obj = object.__new__(cls)\n        obj.l = 0\n        obj.r = 0\n        return obj\n\ndef test_dunder_new() -> None:\n    add_instance: Any = Add(1, 5)\n    assert type(add_instance) == Add\n    assert add_instance.l == 1\n    assert add_instance.r == 5\n\n    # TODO: explicit types should not be needed but mypy does not use\n    # the return type of __new__ which makes mypyc add casts to Add.\n    right_int: Any = Add(0, 5)\n    assert type(right_int) == int\n    assert right_int == 5\n\n    left_int: Any = Add(1, 0)\n    assert type(left_int) == int\n    assert left_int == 1\n\n    with assertRaises(RuntimeError, \"Invalid value!\"):\n        _ = RaisesException(0)\n\n    not_raised = RaisesException(1)\n    assert not_raised.val == 1\n\n    with assertRaises(TypeError, \"object.__new__(str) is not safe, use str.__new__()\"):\n        _ = ClsArgNotPassed()\n\n    skip = SkipsBase.__new__(SkipsBase)\n    assert type(skip) == SkipsBase\n    assert skip.l == 0\n    assert skip.r == 0\n\n[case testObjectDunderNewInInterpreted]\nfrom __future__ import annotations\nfrom typing import Any, Union\n\nclass Add:\n    l: IntLike\n    r: IntLike\n\n    def __new__(cls, l: IntLike, r: IntLike) -> Any:\n        print(f'running __new__ with {l} and {r}')\n\n        return (\n            l if r == 0 else\n            r if l == 0 else\n            object.__new__(cls)\n        )\n\n    def __init__(self, l: IntLike, r: IntLike):\n        self.l = l\n        self.r = r\n\n    def __repr__(self) -> str:\n        return f'({self.l} + {self.r})'\n\nIntLike = Union[int, Add]\n\nclass RaisesException:\n    def __new__(cls, val: int) -> RaisesException:\n        if val == 0:\n            raise RuntimeError(\"Invalid value!\")\n        return object.__new__(cls)\n\n    def __init__(self, val: int) -> None:\n        self.val = val\n\nclass ClsArgNotPassed:\n    def __new__(cls) -> Any:\n        return object.__new__(str)\n\nclass SkipsBase(Add):\n    def __new__(cls) -> Any:\n        obj = object.__new__(cls)\n        obj.l = 0\n        obj.r = 0\n        return obj\n\n[file driver.py]\nfrom native import Add, ClsArgNotPassed, RaisesException, SkipsBase\n\nfrom testutil import assertRaises\n\nprint(f'{Add(1, 5)=}')\nprint(f'{Add(0, 5)=}')\nprint(f'{Add(1, 0)=}')\n\nwith assertRaises(RuntimeError, \"Invalid value!\"):\n    raised = RaisesException(0)\n\nnot_raised = RaisesException(1)\nassert not_raised.val == 1\n\nwith assertRaises(TypeError, \"object.__new__(str) is not safe, use str.__new__()\"):\n    str_as_cls = ClsArgNotPassed()\n\nskip = SkipsBase.__new__(SkipsBase)\nassert type(skip) == SkipsBase\nassert skip.l == 0\nassert skip.r == 0\n\n[out]\nrunning __new__ with 1 and 5\nAdd(1, 5)=(1 + 5)\nrunning __new__ with 0 and 5\nAdd(0, 5)=5\nrunning __new__ with 1 and 0\nAdd(1, 0)=1\n\n[case testInheritedDunderNew]\nfrom __future__ import annotations\nfrom mypy_extensions import mypyc_attr\nfrom testutil import assertRaises\nfrom typing_extensions import Self\n\nfrom m import interpreted_subclass\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass Base:\n    val: int\n\n    def __new__(cls, val: int) -> Self:\n        obj = super().__new__(cls)\n        obj.val = val + 1\n        return obj\n\n    def __init__(self, val: int) -> None:\n        self.init_val = val\n\n    def method(self) -> int:\n        raise NotImplementedError\n\nclass Sub(Base):\n\n    def __new__(cls, val: int) -> Self:\n        return super().__new__(cls, val + 1)\n\n    def __init__(self, val: int) -> None:\n        super().__init__(val)\n        self.init_val = self.init_val * 2\n\n    def method(self) -> int:\n        return 0\n\nclass SubWithoutNew(Base):\n    sub_only_str = \"\"\n    sub_only_int: int\n\n    def __init__(self, val: int) -> None:\n        super().__init__(val)\n        self.init_val = self.init_val * 2\n\n    def method(self) -> int:\n        return 1\n\nclass BaseWithoutInterpretedSubclasses:\n    val: int\n\n    def __new__(cls, val: int) -> Self:\n        obj = super().__new__(cls)\n        obj.val = val + 1\n        return obj\n\n    def __init__(self, val: int) -> None:\n        self.init_val = val\n\n    def method(self) -> int:\n        raise NotImplementedError\n\nclass SubNoInterpreted(BaseWithoutInterpretedSubclasses):\n    def __new__(cls, val: int) -> Self:\n        return super().__new__(cls, val + 1)\n\n    def __init__(self, val: int) -> None:\n        super().__init__(val)\n        self.init_val = self.init_val * 2\n\n    def method(self) -> int:\n        return 0\n\nclass SubNoInterpretedWithoutNew(BaseWithoutInterpretedSubclasses):\n    def __init__(self, val: int) -> None:\n        super().__init__(val)\n        self.init_val = self.init_val * 2\n\n    def method(self) -> int:\n        return 1\n\ndef test_inherited_dunder_new() -> None:\n    b = Base(42)\n    assert type(b) == Base\n    assert b.val == 43\n    assert b.init_val == 42\n    with assertRaises(NotImplementedError):\n        b.method()\n\n    s = Sub(42)\n    assert type(s) == Sub\n    assert s.val == 44\n    assert s.init_val == 84\n    assert s.method() == 0\n\n    s2 = SubWithoutNew(42)\n    assert type(s2) == SubWithoutNew\n    assert s2.val == 43\n    assert s2.init_val == 84\n    assert s2.method() == 1\n    assert s2.sub_only_str == \"\"\n    with assertRaises(AttributeError):\n        s2.sub_only_int\n    s2.sub_only_int = 11\n    assert s2.sub_only_int == 11\n\ndef test_inherited_dunder_new_without_interpreted_subclasses() -> None:\n    b = BaseWithoutInterpretedSubclasses(42)\n    assert type(b) == BaseWithoutInterpretedSubclasses\n    assert b.val == 43\n    assert b.init_val == 42\n    with assertRaises(NotImplementedError):\n        b.method()\n\n    s = SubNoInterpreted(42)\n    assert type(s) == SubNoInterpreted\n    assert s.val == 44\n    assert s.init_val == 84\n    assert s.method() == 0\n\n    s2 = SubNoInterpretedWithoutNew(42)\n    assert type(s2) == SubNoInterpretedWithoutNew\n    assert s2.val == 43\n    assert s2.init_val == 84\n    assert s2.method() == 1\n\ndef test_interpreted_subclass() -> None:\n    interpreted_subclass(Base)\n\n[file m.py]\nfrom __future__ import annotations\nfrom testutil import assertRaises\nfrom typing_extensions import Self\n\ndef interpreted_subclass(base) -> None:\n    b = base(42)\n    assert type(b) == base\n    assert b.val == 43\n    assert b.init_val == 42\n    with assertRaises(NotImplementedError):\n        b.method()\n\n    class InterpretedSub(base):\n        def __new__(cls, val: int) -> Self:\n            return super().__new__(cls, val + 1)\n\n        def __init__(self, val: int) -> None:\n            super().__init__(val)\n            self.init_val : int = self.init_val * 2\n\n        def method(self) -> int:\n            return 3\n\n    s = InterpretedSub(42)\n    assert type(s) == InterpretedSub\n    assert s.val == 44\n    assert s.init_val == 84\n    assert s.method() == 3\n\n    class InterpretedSubWithoutNew(base):\n        sub_only_str = \"\"\n        sub_only_int: int\n\n        def __init__(self, val: int) -> None:\n            super().__init__(val)\n            self.init_val : int = self.init_val * 2\n\n        def method(self) -> int:\n            return 4\n\n    s2 = InterpretedSubWithoutNew(42)\n    assert type(s2) == InterpretedSubWithoutNew\n    assert s2.val == 43\n    assert s2.init_val == 84\n    assert s2.method() == 4\n    assert s2.sub_only_str == \"\"\n    with assertRaises(AttributeError):\n        s2.sub_only_int\n    s2.sub_only_int = 11\n    assert s2.sub_only_int == 11\n\n[typing fixtures/typing-full.pyi]\n\n[case testDunderNewInitArgMismatch]\nfrom __future__ import annotations\nfrom testutil import assertRaises\n\nclass Test0:\n    @classmethod\n    def __new__(cls, val: int = 42) -> Test0:\n        obj = super().__new__(cls)\n        obj.val = val\n        return obj\n\n    def __init__(self) -> None:\n        self.val = 0\n\nclass Test1:\n    def __new__(cls, val: int) -> Test1:\n        obj = super().__new__(cls)\n        obj.val = val\n        return obj\n\n    def __init__(self) -> None:\n        self.val = 0\n\nclass Test2:\n    def __new__(cls) -> Test2:\n        obj = super().__new__(cls)\n        return obj\n\n    def __init__(self, val: int) -> None:\n        self.val = val\n\ndef test_arg_mismatch() -> None:\n    t0 = Test0()\n    assert t0.val == 0\n    t0 = Test0.__new__(1)\n    assert t0.val == 1\n    with assertRaises(TypeError, \"__new__() missing required argument 'val'\"):\n        t1 = Test1()\n    t1 = Test1.__new__(Test1, 2)\n    assert t1.val == 2\n    with assertRaises(TypeError, \"__new__() takes at most 0 arguments\"):\n        t2 = Test2(42)\n    t2 = Test2.__new__(Test2)\n    with assertRaises(AttributeError, \"attribute 'val' of 'Test2' undefined\"):\n        print(t2.val)\n\n[case testDunderNewInitArgMismatchInInterpreted]\nfrom __future__ import annotations\n\nclass Test0:\n    # TODO: It should be possible to annotate '@classmethod' here\n    # but when it's added calling __new__ in interpreted code\n    # without the explicit type param results in a TypeError.\n    def __new__(cls, val: int = 42) -> Test0:\n        obj = super().__new__(cls)\n        obj.val = val\n        return obj\n\n    def __init__(self) -> None:\n        self.val = 0\n\nclass Test1:\n    def __new__(cls, val: int) -> Test1:\n        obj = super().__new__(cls)\n        obj.val = val\n        return obj\n\n    def __init__(self) -> None:\n        self.val = 0\n\nclass Test2:\n    def __new__(cls) -> Test2:\n        obj = super().__new__(cls)\n        return obj\n\n    def __init__(self, val: int) -> None:\n        self.val = val\n\n[file driver.py]\nfrom native import Test0, Test1, Test2\nfrom testutil import assertRaises\n\nt0 = Test0()\nassert t0.val == 0\nt0 = Test0.__new__(Test0, 1)\nassert t0.val == 1\nwith assertRaises(TypeError, \"__new__() missing required argument 'val'\"):\n    t1 = Test1()\nt1 = Test1.__new__(Test1, 2)\nassert t1.val == 2\nwith assertRaises(TypeError, \"__new__() takes at most 0 arguments\"):\n    t2 = Test2(42)\nt2 = Test2.__new__(Test2)\nwith assertRaises(AttributeError, \"attribute 'val' of 'Test2' undefined\"):\n    print(t2.val)\n\n[case testDunderNewAttributeAccess]\nfrom __future__ import annotations\n\nfrom mypy_extensions import u8\nfrom testutil import assertRaises\n\nclass Test:\n    native: int\n    generic: object\n    bitfield: u8\n    default: int = 5\n\n    def __new__(cls, native: int, generic: object, bitfield: u8) -> Test:\n        obj = super().__new__(cls)\n\n        with assertRaises(AttributeError, \"attribute 'native' of 'Test' undefined\"):\n            print(obj.native)\n        with assertRaises(AttributeError, \"attribute 'generic' of 'Test' undefined\"):\n            print(obj.generic)\n        with assertRaises(AttributeError, \"attribute 'bitfield' of 'Test' undefined\"):\n            print(obj.bitfield)\n\n        obj.native = native\n        obj.generic = generic\n        obj.bitfield = bitfield\n\n        obj.native = obj.native + 1\n        obj.generic = obj.generic.__str__()\n        obj.bitfield = obj.bitfield & 0x0F\n        obj.default = obj.default * 2\n        return obj\n\ndef test_attribute_access() -> None:\n    t = Test(42, {}, 0xCC)\n    assert t.native == 43\n    assert t.generic == \"{}\"\n    assert t.bitfield == 0x0C\n    assert t.default == 10\n\n[case testDunderNewAttributeAccessInInterpreted]\nfrom __future__ import annotations\n\nfrom mypy_extensions import u8\nfrom testutil import assertRaises\n\nclass Test:\n    native: int\n    generic: object\n    bitfield: u8\n    default: int = 5\n\n    def __new__(cls, native: int, generic: object, bitfield: u8) -> Test:\n        obj = super().__new__(cls)\n\n        with assertRaises(AttributeError, \"attribute 'native' of 'Test' undefined\"):\n            print(obj.native)\n        with assertRaises(AttributeError, \"attribute 'generic' of 'Test' undefined\"):\n            print(obj.generic)\n        with assertRaises(AttributeError, \"attribute 'bitfield' of 'Test' undefined\"):\n            print(obj.bitfield)\n\n        obj.native = native\n        obj.generic = generic\n        obj.bitfield = bitfield\n\n        obj.native = obj.native + 1\n        obj.generic = obj.generic.__str__()\n        obj.bitfield = obj.bitfield & 0x0F\n        obj.default = obj.default * 2\n        return obj\n\n[file driver.py]\nfrom native import Test\n\nt = Test(42, {}, 0xCC)\nassert t.native == 43\nassert t.generic == \"{}\"\nassert t.bitfield == 0x0C\nassert t.default == 10\n\n[case testUntransformedDunderNewCalls]\nfrom testutil import assertRaises\nfrom typing import Any\n\nclass TestStrCls:\n    def __new__(cls):\n        return str.__new__(cls)\n\n    @classmethod\n    def factory(cls):\n        return str.__new__(cls)\n\nclass TestStrStr:\n    def __new__(cls):\n        return str.__new__(str)\n\n    @classmethod\n    def factory(cls):\n        return str.__new__(str)\n\nclass TestStrInt:\n    def __new__(cls):\n        return str.__new__(int)\n\n    @classmethod\n    def factory(cls):\n        return str.__new__(int)\n\ndef test_untransformed_dunder_new() -> None:\n    with assertRaises(TypeError, \"str.__new__(TestStrCls): TestStrCls is not a subtype of str\"):\n        i = TestStrCls()\n\n    j: Any = TestStrStr()\n    assert j == \"\"\n\n    with assertRaises(TypeError, \"str.__new__(int): int is not a subtype of str\"):\n        k = TestStrInt()\n\n    with assertRaises(TypeError, \"str.__new__(TestStrCls): TestStrCls is not a subtype of str\"):\n        i = TestStrCls.factory()\n\n    j = TestStrStr.factory()\n    assert j == \"\"\n\n    with assertRaises(TypeError, \"str.__new__(int): int is not a subtype of str\"):\n        k = TestStrInt.factory()\n\n[case testPerTypeFreeList]\nfrom __future__ import annotations\n\nfrom mypy_extensions import mypyc_attr\n\na = []\n\n@mypyc_attr(free_list_len=1)\nclass Foo:\n    def __init__(self, x: int) -> None:\n        self.x = x\n        a.append(x)\n\ndef test_alloc() -> None:\n    x: Foo | None\n    y: Foo | None\n\n    x = Foo(1)\n    assert x.x == 1\n    x = None\n\n    x = Foo(2)\n    assert x.x == 2\n    y = Foo(3)\n    assert x.x == 2\n    assert y.x == 3\n    x = None\n    y = None\n    assert a == [1, 2, 3]\n\n    x = Foo(4)\n    assert x.x == 4\n    y = Foo(5)\n    assert x.x == 4\n    assert y.x == 5\n\n@mypyc_attr(free_list_len=1)\nclass Base:\n    def __init__(self, x: str) -> None:\n        self.x = x\n\nclass Deriv(Base):\n    def __init__(self, x: str, y: str) -> None:\n        super().__init__(x)\n        self.y = y\n\n@mypyc_attr(free_list_len=1)\nclass Deriv2(Base):\n    def __init__(self, x: str, y: str) -> None:\n        super().__init__(x)\n        self.y = y\n\ndef test_inheritance() -> None:\n    x: Base | None\n    y: Base | None\n    x = Base('x' + str())\n    y = Base('y' + str())\n    y = None\n    d = Deriv('a' + str(), 'b' + str())\n    assert type(d) is Deriv\n    assert d.x == 'a'\n    assert d.y == 'b'\n    assert x.x == 'x'\n    y = Base('z' + str())\n    assert d.x == 'a'\n    assert d.y == 'b'\n    assert y.x == 'z'\n    x = None\n    y = None\n\ndef test_inheritance_2() -> None:\n    x: Base | None\n    y: Base | None\n    d: Deriv2 | None\n    x = Base('x' + str())\n    y = Base('y' + str())\n    y = None\n    d = Deriv2('a' + str(), 'b' + str())\n    assert type(d) is Deriv2\n    assert d.x == 'a'\n    assert d.y == 'b'\n    assert x.x == 'x'\n    d = None\n    d = Deriv2('c' + str(), 'd' + str())\n    assert type(d) is Deriv2\n    assert d.x == 'c'\n    assert d.y == 'd'\n    assert x.x == 'x'\n    y = Base('z' + str())\n    assert type(y) is Base\n    assert d.x == 'c'\n    assert d.y == 'd'\n    assert y.x == 'z'\n    x = None\n    y = None\n    d = None\n\n[case testDunderGetAttr]\nfrom mypy_extensions import mypyc_attr\nfrom typing import ClassVar\n\nclass GetAttr:\n    class_var = \"x\"\n\n    def __init__(self, extra_attrs: dict[str, object], regular_attr: int):\n        self.extra_attrs = extra_attrs\n        self.regular_attr = regular_attr\n\n    def __getattr__(self, attr: str) -> object:\n        return self.extra_attrs.get(attr)\n\nclass GetAttrDefault:\n    class_var: ClassVar[str] = \"x\"\n\n    def __init__(self, extra_attrs: dict[str, object], regular_attr: int):\n        self.extra_attrs = extra_attrs\n        self.regular_attr = regular_attr\n\n    def __getattr__(self, attr: str, default: int = 8, mult: int = 1) -> object:\n        return self.extra_attrs.get(attr, default * mult)\n\nclass GetAttrInherited(GetAttr):\n    subclass_var = \"y\"\n\n    def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):\n        super().__init__(extra_attrs, regular_attr)\n        self.sub_attr = sub_attr\n\nclass GetAttrOverridden(GetAttr):\n    subclass_var: ClassVar[str] = \"y\"\n\n    def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):\n        super().__init__(extra_attrs, regular_attr)\n        self.sub_attr = sub_attr\n\n    def __getattr__(self, attr: str) -> str:\n        return attr\n\n@mypyc_attr(native_class=False)\nclass GetAttrNonNative:\n    class_var = \"x\"\n\n    def __init__(self, extra_attrs: dict[str, object], regular_attr: int):\n        self.extra_attrs = extra_attrs\n        self.regular_attr = regular_attr\n\n    def __getattr__(self, attr: str) -> object:\n        return self.extra_attrs.get(attr)\n\ndef test_getattr() -> None:\n    i = GetAttr({\"one\": 1, \"two\": \"two\", \"three\": 3.14}, 42)\n    assert i.__getattr__(\"one\") == 1\n    assert i.__getattr__(\"regular_attr\") == None\n    assert i.__getattr__(\"class_var\") == None\n    assert i.__getattr__(\"four\") == None\n\n    assert getattr(i, \"two\") == \"two\"\n    assert getattr(i, \"regular_attr\") == 42\n    assert getattr(i, \"class_var\") == \"x\"\n    assert getattr(i, \"four\") == None\n\n    assert i.three == 3.14\n    assert i.regular_attr == 42\n    assert i.class_var == \"x\"\n    assert i.four == None\n\n    assert i.__class__ == GetAttr\n\n    i.extra_attrs[\"regular_attr\"] = (4, 4, 4)\n    assert i.__getattr__(\"regular_attr\") == (4, 4, 4)\n    assert getattr(i, \"regular_attr\") == 42\n    assert i.regular_attr == 42\n\ndef test_getattr_default() -> None:\n    i = GetAttrDefault({\"one\": 1, \"two\": \"two\", \"three\": 3.14}, 42)\n    assert i.__getattr__(\"one\") == 1\n    assert i.__getattr__(\"regular_attr\") == 8\n    assert i.__getattr__(\"class_var\") == 8\n    assert i.__getattr__(\"four\", 4, 3) == 12\n\n    assert getattr(i, \"two\") == \"two\"\n    assert getattr(i, \"regular_attr\") == 42\n    assert getattr(i, \"class_var\") == \"x\"\n    assert getattr(i, \"four\") == 8\n\n    assert i.three == 3.14\n    assert i.regular_attr == 42\n    assert i.class_var == \"x\"\n    assert i.four == 8\n\n    assert i.__class__ == GetAttrDefault\n\n    i.extra_attrs[\"class_var\"] = (4, 4, 4)\n    assert i.__getattr__(\"class_var\") == (4, 4, 4)\n    assert getattr(i, \"class_var\") == \"x\"\n    assert i.class_var == \"x\"\n\ndef test_getattr_inherited() -> None:\n    i = GetAttrInherited({\"one\": 1, \"two\": \"two\", \"three\": 3.14}, 42, 24)\n    assert i.__getattr__(\"one\") == 1\n    assert i.__getattr__(\"regular_attr\") == None\n    assert i.__getattr__(\"sub_attr\") == None\n    assert i.__getattr__(\"class_var\") == None\n    assert i.__getattr__(\"subclass_var\") == None\n    assert i.__getattr__(\"four\") == None\n\n    assert getattr(i, \"two\") == \"two\"\n    assert getattr(i, \"regular_attr\") == 42\n    assert getattr(i, \"sub_attr\") == 24\n    assert getattr(i, \"class_var\") == \"x\"\n    assert getattr(i, \"subclass_var\") == \"y\"\n    assert getattr(i, \"four\") == None\n\n    assert i.three == 3.14\n    assert i.regular_attr == 42\n    assert i.sub_attr == 24\n    assert i.class_var == \"x\"\n    assert i.subclass_var == \"y\"\n    assert i.four == None\n\n    assert i.__class__ == GetAttrInherited\n\n    i.extra_attrs[\"sub_attr\"] = (4, 4, 4)\n    assert i.__getattr__(\"sub_attr\") == (4, 4, 4)\n    assert getattr(i, \"sub_attr\") == 24\n    assert i.sub_attr == 24\n\n    base_ref: GetAttr = i\n    assert getattr(base_ref, \"sub_attr\") == 24\n    assert base_ref.sub_attr == 24\n\n    assert getattr(base_ref, \"subclass_var\") == \"y\"\n    assert base_ref.subclass_var == \"y\"\n\n    assert getattr(base_ref, \"new\") == None\n    assert base_ref.new == None\n\n    assert base_ref.__class__ == GetAttrInherited\n\n\ndef test_getattr_overridden() -> None:\n    i = GetAttrOverridden({\"one\": 1, \"two\": \"two\", \"three\": 3.14}, 42, 24)\n    assert i.__getattr__(\"one\") == \"one\"\n    assert i.__getattr__(\"regular_attr\") == \"regular_attr\"\n    assert i.__getattr__(\"sub_attr\") == \"sub_attr\"\n    assert i.__getattr__(\"class_var\") == \"class_var\"\n    assert i.__getattr__(\"subclass_var\") == \"subclass_var\"\n    assert i.__getattr__(\"four\") == \"four\"\n\n    assert getattr(i, \"two\") == \"two\"\n    assert getattr(i, \"regular_attr\") == 42\n    assert getattr(i, \"sub_attr\") == 24\n    assert getattr(i, \"class_var\") == \"x\"\n    assert getattr(i, \"subclass_var\") == \"y\"\n    assert getattr(i, \"four\") == \"four\"\n\n    assert i.three == \"three\"\n    assert i.regular_attr == 42\n    assert i.sub_attr == 24\n    assert i.class_var == \"x\"\n    assert i.subclass_var == \"y\"\n    assert i.four == \"four\"\n\n    assert i.__class__ == GetAttrOverridden\n\n    i.extra_attrs[\"subclass_var\"] = (4, 4, 4)\n    assert i.__getattr__(\"subclass_var\") == \"subclass_var\"\n    assert getattr(i, \"subclass_var\") == \"y\"\n    assert i.subclass_var == \"y\"\n\n    base_ref: GetAttr = i\n    assert getattr(base_ref, \"sub_attr\") == 24\n    assert base_ref.sub_attr == 24\n\n    assert getattr(base_ref, \"subclass_var\") == \"y\"\n    assert base_ref.subclass_var == \"y\"\n\n    assert getattr(base_ref, \"new\") == \"new\"\n    assert base_ref.new == \"new\"\n\n    assert base_ref.__class__ == GetAttrOverridden\n\ndef test_getattr_nonnative() -> None:\n    i = GetAttr({\"one\": 1, \"two\": \"two\", \"three\": 3.14}, 42)\n    assert i.__getattr__(\"one\") == 1\n    assert i.__getattr__(\"regular_attr\") == None\n    assert i.__getattr__(\"class_var\") == None\n    assert i.__getattr__(\"four\") == None\n\n    assert getattr(i, \"two\") == \"two\"\n    assert getattr(i, \"regular_attr\") == 42\n    assert getattr(i, \"class_var\") == \"x\"\n    assert getattr(i, \"four\") == None\n\n    assert i.three == 3.14\n    assert i.regular_attr == 42\n    assert i.class_var == \"x\"\n    assert i.four == None\n\n    assert i.__class__ == GetAttr\n\n    i.extra_attrs[\"regular_attr\"] = (4, 4, 4)\n    assert i.__getattr__(\"regular_attr\") == (4, 4, 4)\n    assert getattr(i, \"regular_attr\") == 42\n    assert i.regular_attr == 42\n\n[typing fixtures/typing-full.pyi]\n\n[case testDunderGetAttrInterpreted]\nfrom mypy_extensions import mypyc_attr\nfrom typing import ClassVar\n\nclass GetAttr:\n    class_var = \"x\"\n\n    def __init__(self, extra_attrs: dict[str, object], regular_attr: int):\n        self.extra_attrs = extra_attrs\n        self.regular_attr = regular_attr\n\n    def __getattr__(self, attr: str) -> object:\n        return self.extra_attrs.get(attr)\n\nclass GetAttrDefault:\n    class_var: ClassVar[str] = \"x\"\n\n    def __init__(self, extra_attrs: dict[str, object], regular_attr: int):\n        self.extra_attrs = extra_attrs\n        self.regular_attr = regular_attr\n\n    def __getattr__(self, attr: str, default: int = 8, mult: int = 1) -> object:\n        return self.extra_attrs.get(attr, default * mult)\n\nclass GetAttrInherited(GetAttr):\n    subclass_var = \"y\"\n\n    def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):\n        super().__init__(extra_attrs, regular_attr)\n        self.sub_attr = sub_attr\n\nclass GetAttrOverridden(GetAttr):\n    subclass_var: ClassVar[str] = \"y\"\n\n    def __init__(self, extra_attrs: dict[str, object], regular_attr: int, sub_attr: int):\n        super().__init__(extra_attrs, regular_attr)\n        self.sub_attr = sub_attr\n\n    def __getattr__(self, attr: str) -> str:\n        return attr\n\n@mypyc_attr(native_class=False)\nclass GetAttrNonNative:\n    class_var = \"x\"\n\n    def __init__(self, extra_attrs: dict[str, object], regular_attr: int):\n        self.extra_attrs = extra_attrs\n        self.regular_attr = regular_attr\n\n    def __getattr__(self, attr: str) -> object:\n        return self.extra_attrs.get(attr)\n\n[file driver.py]\nfrom native import GetAttr, GetAttrDefault, GetAttrInherited, GetAttrOverridden, GetAttrNonNative\n\ndef test_getattr() -> None:\n    i = GetAttr({\"one\": 1, \"two\": \"two\", \"three\": 3.14}, 42)\n    assert i.__getattr__(\"one\") == 1\n    assert i.__getattr__(\"regular_attr\") == None\n    assert i.__getattr__(\"class_var\") == None\n    assert i.__getattr__(\"four\") == None\n\n    assert getattr(i, \"two\") == \"two\"\n    assert getattr(i, \"regular_attr\") == 42\n    assert getattr(i, \"class_var\") == \"x\"\n    assert getattr(i, \"four\") == None\n\n    assert i.three == 3.14\n    assert i.regular_attr == 42\n    assert i.class_var == \"x\"\n    assert i.four == None\n\n    assert i.__class__ == GetAttr\n\n    i.extra_attrs[\"regular_attr\"] = (4, 4, 4)\n    assert i.__getattr__(\"regular_attr\") == (4, 4, 4)\n    assert getattr(i, \"regular_attr\") == 42\n    assert i.regular_attr == 42\n\ndef test_getattr_default() -> None:\n    i = GetAttrDefault({\"one\": 1, \"two\": \"two\", \"three\": 3.14}, 42)\n    assert i.__getattr__(\"one\") == 1\n    assert i.__getattr__(\"regular_attr\") == 8\n    assert i.__getattr__(\"class_var\") == 8\n    assert i.__getattr__(\"four\", 4, 3) == 12\n\n    assert getattr(i, \"two\") == \"two\"\n    assert getattr(i, \"regular_attr\") == 42\n    assert getattr(i, \"class_var\") == \"x\"\n    assert getattr(i, \"four\") == 8\n\n    assert i.three == 3.14\n    assert i.regular_attr == 42\n    assert i.class_var == \"x\"\n    assert i.four == 8\n\n    assert i.__class__ == GetAttrDefault\n\n    i.extra_attrs[\"class_var\"] = (4, 4, 4)\n    assert i.__getattr__(\"class_var\") == (4, 4, 4)\n    assert getattr(i, \"class_var\") == \"x\"\n    assert i.class_var == \"x\"\n\ndef test_getattr_inherited() -> None:\n    i = GetAttrInherited({\"one\": 1, \"two\": \"two\", \"three\": 3.14}, 42, 24)\n    assert i.__getattr__(\"one\") == 1\n    assert i.__getattr__(\"regular_attr\") == None\n    assert i.__getattr__(\"sub_attr\") == None\n    assert i.__getattr__(\"class_var\") == None\n    assert i.__getattr__(\"subclass_var\") == None\n    assert i.__getattr__(\"four\") == None\n\n    assert getattr(i, \"two\") == \"two\"\n    assert getattr(i, \"regular_attr\") == 42\n    assert getattr(i, \"sub_attr\") == 24\n    assert getattr(i, \"class_var\") == \"x\"\n    assert getattr(i, \"subclass_var\") == \"y\"\n    assert getattr(i, \"four\") == None\n\n    assert i.three == 3.14\n    assert i.regular_attr == 42\n    assert i.sub_attr == 24\n    assert i.class_var == \"x\"\n    assert i.subclass_var == \"y\"\n    assert i.four == None\n\n    assert i.__class__ == GetAttrInherited\n\n    i.extra_attrs[\"sub_attr\"] = (4, 4, 4)\n    assert i.__getattr__(\"sub_attr\") == (4, 4, 4)\n    assert getattr(i, \"sub_attr\") == 24\n    assert i.sub_attr == 24\n\n    base_ref: GetAttr = i\n    assert getattr(base_ref, \"sub_attr\") == 24\n    assert base_ref.sub_attr == 24\n\n    assert getattr(base_ref, \"subclass_var\") == \"y\"\n    assert base_ref.subclass_var == \"y\"\n\n    assert getattr(base_ref, \"new\") == None\n    assert base_ref.new == None\n\n    assert base_ref.__class__ == GetAttrInherited\n\n\ndef test_getattr_overridden() -> None:\n    i = GetAttrOverridden({\"one\": 1, \"two\": \"two\", \"three\": 3.14}, 42, 24)\n    assert i.__getattr__(\"one\") == \"one\"\n    assert i.__getattr__(\"regular_attr\") == \"regular_attr\"\n    assert i.__getattr__(\"sub_attr\") == \"sub_attr\"\n    assert i.__getattr__(\"class_var\") == \"class_var\"\n    assert i.__getattr__(\"subclass_var\") == \"subclass_var\"\n    assert i.__getattr__(\"four\") == \"four\"\n\n    assert getattr(i, \"two\") == \"two\"\n    assert getattr(i, \"regular_attr\") == 42\n    assert getattr(i, \"sub_attr\") == 24\n    assert getattr(i, \"class_var\") == \"x\"\n    assert getattr(i, \"subclass_var\") == \"y\"\n    assert getattr(i, \"four\") == \"four\"\n\n    assert i.three == \"three\"\n    assert i.regular_attr == 42\n    assert i.sub_attr == 24\n    assert i.class_var == \"x\"\n    assert i.subclass_var == \"y\"\n    assert i.four == \"four\"\n\n    assert i.__class__ == GetAttrOverridden\n\n    i.extra_attrs[\"subclass_var\"] = (4, 4, 4)\n    assert i.__getattr__(\"subclass_var\") == \"subclass_var\"\n    assert getattr(i, \"subclass_var\") == \"y\"\n    assert i.subclass_var == \"y\"\n\n    base_ref: GetAttr = i\n    assert getattr(base_ref, \"sub_attr\") == 24\n    assert base_ref.sub_attr == 24\n\n    assert getattr(base_ref, \"subclass_var\") == \"y\"\n    assert base_ref.subclass_var == \"y\"\n\n    assert getattr(base_ref, \"new\") == \"new\"\n    assert base_ref.new == \"new\"\n\n    assert base_ref.__class__ == GetAttrOverridden\n\ndef test_getattr_nonnative() -> None:\n    i = GetAttr({\"one\": 1, \"two\": \"two\", \"three\": 3.14}, 42)\n    assert i.__getattr__(\"one\") == 1\n    assert i.__getattr__(\"regular_attr\") == None\n    assert i.__getattr__(\"class_var\") == None\n    assert i.__getattr__(\"four\") == None\n\n    assert getattr(i, \"two\") == \"two\"\n    assert getattr(i, \"regular_attr\") == 42\n    assert getattr(i, \"class_var\") == \"x\"\n    assert getattr(i, \"four\") == None\n\n    assert i.three == 3.14\n    assert i.regular_attr == 42\n    assert i.class_var == \"x\"\n    assert i.four == None\n\n    assert i.__class__ == GetAttr\n\n    i.extra_attrs[\"regular_attr\"] = (4, 4, 4)\n    assert i.__getattr__(\"regular_attr\") == (4, 4, 4)\n    assert getattr(i, \"regular_attr\") == 42\n    assert i.regular_attr == 42\n\ntest_getattr()\ntest_getattr_default()\ntest_getattr_inherited()\ntest_getattr_overridden()\ntest_getattr_nonnative()\n\n[typing fixtures/typing-full.pyi]\n\n[case testDunderSetAttr]\nfrom mypy_extensions import mypyc_attr\nfrom testutil import assertRaises\nfrom typing import ClassVar\n\nclass SetAttr:\n    _attributes: dict[str, object]\n    regular_attr: int\n    class_var: ClassVar[str] = \"x\"\n    const: int = 42\n\n    def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:\n        super().__setattr__(\"_attributes\", extra_attrs)\n        super().__setattr__(\"regular_attr\", regular_attr)\n\n    def __setattr__(self, key: str, val: object) -> None:\n        if key == \"regular_attr\":\n            super().__setattr__(\"regular_attr\", val)\n        elif key == \"class_var\" or key == \"const\":\n            raise AttributeError()\n        else:\n            self._attributes[key] = val\n\n    def __getattr__(self, key: str) -> object:\n        return self._attributes.get(key)\n\nclass SetAttrInherited(SetAttr):\n    def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:\n        super().__init__(regular_attr, extra_attrs)\n\nclass SetAttrOverridden(SetAttr):\n    sub_attr: int\n    subclass_var: ClassVar[str] = \"y\"\n\n    def __init__(self, regular_attr: int, sub_attr: int, extra_attrs: dict[str, object]) -> None:\n        super().__init__(regular_attr, extra_attrs)\n        object.__setattr__(self, \"sub_attr\", sub_attr)\n\n    def __setattr__(self, key: str, val: object) -> None:\n        if key == \"sub_attr\":\n            object.__setattr__(self, \"sub_attr\", val)\n        elif key == \"subclass_var\":\n            raise AttributeError()\n        else:\n            super().__setattr__(key, val)\n\n    def __delattr__(self, key: str) -> None:\n        del self._attributes[key]\n\n@mypyc_attr(native_class=False)\nclass SetAttrNonNative:\n    _attributes: dict[str, object]\n    regular_attr: int\n    class_var: ClassVar[str] = \"x\"\n    const: int = 42\n\n    def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:\n        super().__setattr__(\"_attributes\", extra_attrs)\n        super().__setattr__(\"regular_attr\", regular_attr)\n\n    def __setattr__(self, key: str, val: object) -> None:\n        if key == \"regular_attr\":\n            super().__setattr__(\"regular_attr\", val)\n        elif key == \"class_var\" or key == \"const\":\n            raise AttributeError()\n        else:\n            self._attributes[key] = val\n\n    def __getattr__(self, key: str) -> object:\n        return self._attributes.get(key)\n\nclass NoSetAttr:\n    def __init__(self, attr: int) -> None:\n        self.attr = attr\n\n    def object_setattr(self, attr: str, val: object) -> None:\n        object.__setattr__(self, attr, val)\n\n    def super_setattr(self, attr: str, val: object) -> None:\n        super().__setattr__(attr, val)\n\n@mypyc_attr(native_class=False)\nclass NoSetAttrNonNative:\n    def __init__(self, attr: int) -> None:\n        self.attr = attr\n\n    def object_setattr(self, attr: str, val: object) -> None:\n        object.__setattr__(self, attr, val)\n\n    def super_setattr(self, attr: str, val: object) -> None:\n        super().__setattr__(attr, val)\n\n    def __getattr__(self, attr: str) -> object:\n        pass\n\ndef test_setattr() -> None:\n    i = SetAttr(99, {\"one\": 1})\n    assert i.class_var == \"x\"\n    assert i.regular_attr == 99\n    assert i.one == 1\n    assert i.two == None\n    assert i.const == 42\n    i = i\n\n    i.__setattr__(\"two\", \"2\")\n    assert i.two == \"2\"\n    i.__setattr__(\"regular_attr\", 101)\n    assert i.regular_attr == 101\n    with assertRaises(AttributeError):\n        i.__setattr__(\"class_var\", \"y\")\n    with assertRaises(AttributeError):\n        i.__setattr__(\"const\", 43)\n\n    setattr(i, \"three\", (3,3,3))\n    assert i.three == (3,3,3)\n    setattr(i, \"regular_attr\", 102)\n    assert i.regular_attr == 102\n    with assertRaises(AttributeError):\n        setattr(i, \"class_var\", \"z\")\n    with assertRaises(AttributeError):\n        setattr(i, \"const\", 44)\n\n    i.four = [4,4]\n    assert i.four == [4,4]\n    i.regular_attr = 103\n    assert i.regular_attr == 103\n    with assertRaises(AttributeError):\n        i.const = 45\n\n    # Doesn't work because there's no __delattr__.\n    with assertRaises(AttributeError):\n        del i.four\n\ndef test_setattr_inherited() -> None:\n    i = SetAttrInherited(99, {\"one\": 1})\n    assert i.class_var == \"x\"\n    assert i.regular_attr == 99\n    assert i.one == 1\n    assert i.two == None\n    assert i.const == 42\n    i = i\n\n    i.__setattr__(\"two\", \"2\")\n    assert i.two == \"2\"\n    i.__setattr__(\"regular_attr\", 101)\n    assert i.regular_attr == 101\n    with assertRaises(AttributeError):\n        i.__setattr__(\"class_var\", \"y\")\n    with assertRaises(AttributeError):\n        i.__setattr__(\"const\", 43)\n\n    setattr(i, \"three\", (3,3,3))\n    assert i.three == (3,3,3)\n    setattr(i, \"regular_attr\", 102)\n    assert i.regular_attr == 102\n    with assertRaises(AttributeError):\n        setattr(i, \"class_var\", \"z\")\n    with assertRaises(AttributeError):\n        setattr(i, \"const\", 44)\n\n    i.four = [4,4]\n    assert i.four == [4,4]\n    i.regular_attr = 103\n    assert i.regular_attr == 103\n    with assertRaises(AttributeError):\n        i.const = 45\n\n    # Doesn't work because there's no __delattr__.\n    with assertRaises(AttributeError):\n        del i.four\n\ndef test_setattr_overridden() -> None:\n    i = SetAttrOverridden(99, 1, {\"one\": 1})\n    assert i.class_var == \"x\"\n    assert i.subclass_var == \"y\"\n    assert i.regular_attr == 99\n    assert i.sub_attr == 1\n    assert i.one == 1\n    assert i.two == None\n    assert i.const == 42\n    i = i\n\n    i.__setattr__(\"two\", \"2\")\n    assert i.two == \"2\"\n    i.__setattr__(\"regular_attr\", 101)\n    assert i.regular_attr == 101\n    i.__setattr__(\"sub_attr\", 2)\n    assert i.sub_attr == 2\n    with assertRaises(AttributeError):\n        i.__setattr__(\"class_var\", \"y\")\n    with assertRaises(AttributeError):\n        i.__setattr__(\"subclass_var\", \"a\")\n    with assertRaises(AttributeError):\n        i.__setattr__(\"const\", 43)\n\n    setattr(i, \"three\", (3,3,3))\n    assert i.three == (3,3,3)\n    setattr(i, \"regular_attr\", 102)\n    assert i.regular_attr == 102\n    setattr(i, \"sub_attr\", 3)\n    assert i.sub_attr == 3\n    with assertRaises(AttributeError):\n        setattr(i, \"class_var\", \"z\")\n    with assertRaises(AttributeError):\n        setattr(i, \"subclass_var\", \"b\")\n    with assertRaises(AttributeError):\n        setattr(i, \"const\", 44)\n\n    i.four = [4,4]\n    assert i.four == [4,4]\n    i.regular_attr = 103\n    assert i.regular_attr == 103\n    i.sub_attr = 4\n    assert i.sub_attr == 4\n    with assertRaises(AttributeError):\n        i.const = 45\n\n    del i.four\n    assert \"four\" not in i._attributes\n\n    delattr(i, \"three\")\n    assert \"three\" not in i._attributes\n\n    i.__delattr__(\"two\")\n    assert \"two\" not in i._attributes\n\n    base_ref: SetAttr = i\n    setattr(base_ref, \"sub_attr\", 5)\n    assert base_ref.sub_attr == 5\n\n    base_ref.sub_attr = 6\n    assert base_ref.sub_attr == 6\n\n    with assertRaises(AttributeError):\n        setattr(base_ref, \"subclass_var\", \"c\")\n\n    base_ref.new_attr = \"new_attr\"\n    assert base_ref.new_attr == \"new_attr\"\n\n    del base_ref.new_attr\n    assert \"new_attr\" not in base_ref._attributes\n\ndef test_setattr_nonnative() -> None:\n    i = SetAttrNonNative(99, {\"one\": 1})\n    assert i.class_var == \"x\"\n    assert i.regular_attr == 99\n    assert i.one == 1\n    assert i.two == None\n    assert i.const == 42\n    i = i\n\n    i.__setattr__(\"two\", \"2\")\n    assert i.two == \"2\"\n    i.__setattr__(\"regular_attr\", 101)\n    assert i.regular_attr == 101\n    with assertRaises(AttributeError):\n        i.__setattr__(\"class_var\", \"y\")\n    with assertRaises(AttributeError):\n        i.__setattr__(\"const\", 43)\n\n    setattr(i, \"three\", (3,3,3))\n    assert i.three == (3,3,3)\n    setattr(i, \"regular_attr\", 102)\n    assert i.regular_attr == 102\n    with assertRaises(AttributeError):\n        setattr(i, \"class_var\", \"z\")\n    with assertRaises(AttributeError):\n        setattr(i, \"const\", 44)\n\n    i.four = [4,4]\n    assert i.four == [4,4]\n    i.regular_attr = 103\n    assert i.regular_attr == 103\n    with assertRaises(AttributeError):\n        i.const = 45\n\n    # Doesn't work because there's no __delattr__.\n    with assertRaises(AttributeError):\n        del i.four\n\ndef test_no_setattr() -> None:\n    i = NoSetAttr(99)\n    i.super_setattr(\"attr\", 100)\n    assert i.attr == 100\n\n    i.object_setattr(\"attr\", 101)\n    assert i.attr == 101\n\n    object.__setattr__(i, \"attr\", 102)\n    assert i.attr == 102\n\n    with assertRaises(AttributeError):\n        i.super_setattr(\"not_attr\", 100)\n\n    with assertRaises(AttributeError):\n        i.object_setattr(\"not_attr\", 101)\n\n    with assertRaises(AttributeError):\n        object.__setattr__(i, \"not_attr\", 102)\n\ndef test_no_setattr_nonnative() -> None:\n    i = NoSetAttrNonNative(99)\n    i.super_setattr(\"attr\", 100)\n    assert i.attr == 100\n\n    i.object_setattr(\"attr\", 101)\n    assert i.attr == 101\n\n    object.__setattr__(i, \"attr\", 102)\n    assert i.attr == 102\n\n    i.super_setattr(\"one\", 100)\n    assert i.one == 100\n\n    i.object_setattr(\"two\", 101)\n    assert i.two == 101\n\n    object.__setattr__(i, \"three\", 102)\n    assert i.three == 102\n\n    i = i\n\n    del i.three\n    assert i.three == None\n\n    delattr(i, \"two\")\n    assert i.two == None\n\n    object.__delattr__(i, \"one\")\n    assert i.one == None\n\n[typing fixtures/typing-full.pyi]\n\n[case testDunderSetAttrInterpreted]\nfrom mypy_extensions import mypyc_attr\nfrom typing import ClassVar\n\nclass SetAttr:\n    _attributes: dict[str, object]\n    regular_attr: int\n    class_var: ClassVar[str] = \"x\"\n    const: int = 42\n\n    def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:\n        super().__setattr__(\"_attributes\", extra_attrs)\n        super().__setattr__(\"regular_attr\", regular_attr)\n\n    def __setattr__(self, key: str, val: object) -> None:\n        if key == \"regular_attr\":\n            super().__setattr__(\"regular_attr\", val)\n        elif key == \"class_var\" or key == \"const\":\n            raise AttributeError()\n        else:\n            self._attributes[key] = val\n\n    def __getattr__(self, key: str) -> object:\n        return self._attributes.get(key)\n\nclass SetAttrInherited(SetAttr):\n    def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:\n        super().__init__(regular_attr, extra_attrs)\n\nclass SetAttrOverridden(SetAttr):\n    sub_attr: int\n    subclass_var: ClassVar[str] = \"y\"\n\n    def __init__(self, regular_attr: int, sub_attr: int, extra_attrs: dict[str, object]) -> None:\n        super().__init__(regular_attr, extra_attrs)\n        object.__setattr__(self, \"sub_attr\", sub_attr)\n\n    def __setattr__(self, key: str, val: object) -> None:\n        if key == \"sub_attr\":\n            object.__setattr__(self, \"sub_attr\", val)\n        elif key == \"subclass_var\":\n            raise AttributeError()\n        else:\n            super().__setattr__(key, val)\n\n    def __delattr__(self, key: str) -> None:\n        del self._attributes[key]\n\n@mypyc_attr(native_class=False)\nclass SetAttrNonNative:\n    _attributes: dict[str, object]\n    regular_attr: int\n    class_var: ClassVar[str] = \"x\"\n    const: int = 42\n\n    def __init__(self, regular_attr: int, extra_attrs: dict[str, object]) -> None:\n        super().__setattr__(\"_attributes\", extra_attrs)\n        super().__setattr__(\"regular_attr\", regular_attr)\n\n    def __setattr__(self, key: str, val: object) -> None:\n        if key == \"regular_attr\":\n            super().__setattr__(\"regular_attr\", val)\n        elif key == \"class_var\" or key == \"const\":\n            raise AttributeError()\n        else:\n            self._attributes[key] = val\n\n    def __getattr__(self, key: str) -> object:\n        return self._attributes.get(key)\n\nclass NoSetAttr:\n    def __init__(self, attr: int) -> None:\n        self.attr = attr\n\n    def object_setattr(self, attr: str, val: object) -> None:\n        object.__setattr__(self, attr, val)\n\n    def super_setattr(self, attr: str, val: object) -> None:\n        super().__setattr__(attr, val)\n\n@mypyc_attr(native_class=False)\nclass NoSetAttrNonNative:\n    def __init__(self, attr: int) -> None:\n        self.attr = attr\n\n    def object_setattr(self, attr: str, val: object) -> None:\n        object.__setattr__(self, attr, val)\n\n    def super_setattr(self, attr: str, val: object) -> None:\n        super().__setattr__(attr, val)\n\n    def __getattr__(self, attr: str) -> object:\n        pass\n\n[file driver.py]\nfrom native import SetAttr, SetAttrInherited, SetAttrOverridden, SetAttrNonNative, NoSetAttr, NoSetAttrNonNative\nfrom testutil import assertRaises\n\ndef test_setattr() -> None:\n    i = SetAttr(99, {\"one\": 1})\n    assert i.class_var == \"x\"\n    assert i.regular_attr == 99\n    assert i.one == 1\n    assert i.two == None\n    assert i.const == 42\n\n    i.__setattr__(\"two\", \"2\")\n    assert i.two == \"2\"\n    i.__setattr__(\"regular_attr\", 101)\n    assert i.regular_attr == 101\n    with assertRaises(AttributeError):\n        i.__setattr__(\"class_var\", \"y\")\n    with assertRaises(AttributeError):\n        i.__setattr__(\"const\", 43)\n\n    setattr(i, \"three\", (3,3,3))\n    assert i.three == (3,3,3)\n    setattr(i, \"regular_attr\", 102)\n    assert i.regular_attr == 102\n    with assertRaises(AttributeError):\n        setattr(i, \"class_var\", \"z\")\n    with assertRaises(AttributeError):\n        setattr(i, \"const\", 44)\n\n    i.four = [4,4]\n    assert i.four == [4,4]\n    i.regular_attr = 103\n    assert i.regular_attr == 103\n    with assertRaises(AttributeError):\n        i.const = 45\n\n    # Doesn't work because there's no __delattr__.\n    with assertRaises(AttributeError):\n        del i.four\n\ndef test_setattr_inherited() -> None:\n    i = SetAttrInherited(99, {\"one\": 1})\n    assert i.class_var == \"x\"\n    assert i.regular_attr == 99\n    assert i.one == 1\n    assert i.two == None\n    assert i.const == 42\n\n    i.__setattr__(\"two\", \"2\")\n    assert i.two == \"2\"\n    i.__setattr__(\"regular_attr\", 101)\n    assert i.regular_attr == 101\n    with assertRaises(AttributeError):\n        i.__setattr__(\"class_var\", \"y\")\n    with assertRaises(AttributeError):\n        i.__setattr__(\"const\", 43)\n\n    setattr(i, \"three\", (3,3,3))\n    assert i.three == (3,3,3)\n    setattr(i, \"regular_attr\", 102)\n    assert i.regular_attr == 102\n    with assertRaises(AttributeError):\n        setattr(i, \"class_var\", \"z\")\n    with assertRaises(AttributeError):\n        setattr(i, \"const\", 44)\n\n    i.four = [4,4]\n    assert i.four == [4,4]\n    i.regular_attr = 103\n    assert i.regular_attr == 103\n    with assertRaises(AttributeError):\n        i.const = 45\n\n    # Doesn't work because there's no __delattr__.\n    with assertRaises(AttributeError):\n        del i.four\n\ndef test_setattr_overridden() -> None:\n    i = SetAttrOverridden(99, 1, {\"one\": 1})\n    assert i.class_var == \"x\"\n    assert i.subclass_var == \"y\"\n    assert i.regular_attr == 99\n    assert i.sub_attr == 1\n    assert i.one == 1\n    assert i.two == None\n    assert i.const == 42\n\n    i.__setattr__(\"two\", \"2\")\n    assert i.two == \"2\"\n    i.__setattr__(\"regular_attr\", 101)\n    assert i.regular_attr == 101\n    i.__setattr__(\"sub_attr\", 2)\n    assert i.sub_attr == 2\n    with assertRaises(AttributeError):\n        i.__setattr__(\"class_var\", \"y\")\n    with assertRaises(AttributeError):\n        i.__setattr__(\"subclass_var\", \"a\")\n    with assertRaises(AttributeError):\n        i.__setattr__(\"const\", 43)\n\n    setattr(i, \"three\", (3,3,3))\n    assert i.three == (3,3,3)\n    setattr(i, \"regular_attr\", 102)\n    assert i.regular_attr == 102\n    setattr(i, \"sub_attr\", 3)\n    assert i.sub_attr == 3\n    with assertRaises(AttributeError):\n        setattr(i, \"class_var\", \"z\")\n    with assertRaises(AttributeError):\n        setattr(i, \"subclass_var\", \"b\")\n    with assertRaises(AttributeError):\n        setattr(i, \"const\", 44)\n\n    i.four = [4,4]\n    assert i.four == [4,4]\n    i.regular_attr = 103\n    assert i.regular_attr == 103\n    i.sub_attr = 4\n    assert i.sub_attr == 4\n    with assertRaises(AttributeError):\n        i.const = 45\n\n    del i.four\n    assert \"four\" not in i._attributes\n\n    delattr(i, \"three\")\n    assert \"three\" not in i._attributes\n\n    i.__delattr__(\"two\")\n    assert \"two\" not in i._attributes\n\n    base_ref: SetAttr = i\n    setattr(base_ref, \"sub_attr\", 5)\n    assert base_ref.sub_attr == 5\n\n    base_ref.sub_attr = 6\n    assert base_ref.sub_attr == 6\n\n    with assertRaises(AttributeError):\n        setattr(base_ref, \"subclass_var\", \"c\")\n\n    base_ref.new_attr = \"new_attr\"\n    assert base_ref.new_attr == \"new_attr\"\n\n    del base_ref.new_attr\n    assert \"new_attr\" not in base_ref._attributes\n\ndef test_setattr_nonnative() -> None:\n    i = SetAttrNonNative(99, {\"one\": 1})\n    assert i.class_var == \"x\"\n    assert i.regular_attr == 99\n    assert i.one == 1\n    assert i.two == None\n    assert i.const == 42\n\n    i.__setattr__(\"two\", \"2\")\n    assert i.two == \"2\"\n    i.__setattr__(\"regular_attr\", 101)\n    assert i.regular_attr == 101\n    with assertRaises(AttributeError):\n        i.__setattr__(\"class_var\", \"y\")\n    with assertRaises(AttributeError):\n        i.__setattr__(\"const\", 43)\n\n    setattr(i, \"three\", (3,3,3))\n    assert i.three == (3,3,3)\n    setattr(i, \"regular_attr\", 102)\n    assert i.regular_attr == 102\n    with assertRaises(AttributeError):\n        setattr(i, \"class_var\", \"z\")\n    with assertRaises(AttributeError):\n        setattr(i, \"const\", 44)\n\n    i.four = [4,4]\n    assert i.four == [4,4]\n    i.regular_attr = 103\n    assert i.regular_attr == 103\n    with assertRaises(AttributeError):\n        i.const = 45\n\n    # Doesn't work because there's no __delattr__.\n    with assertRaises(AttributeError):\n        del i.four\n\ndef test_no_setattr() -> None:\n    i = NoSetAttr(99)\n    i.super_setattr(\"attr\", 100)\n    assert i.attr == 100\n\n    i.object_setattr(\"attr\", 101)\n    assert i.attr == 101\n\n    object.__setattr__(i, \"attr\", 102)\n    assert i.attr == 102\n\n    with assertRaises(AttributeError):\n        i.super_setattr(\"not_attr\", 100)\n\n    with assertRaises(AttributeError):\n        i.object_setattr(\"not_attr\", 101)\n\n    with assertRaises(AttributeError):\n        object.__setattr__(i, \"not_attr\", 102)\n\ndef test_no_setattr_nonnative() -> None:\n    i = NoSetAttrNonNative(99)\n    i.super_setattr(\"attr\", 100)\n    assert i.attr == 100\n\n    i.object_setattr(\"attr\", 101)\n    assert i.attr == 101\n\n    object.__setattr__(i, \"attr\", 102)\n    assert i.attr == 102\n\n    i.super_setattr(\"one\", 100)\n    assert i.one == 100\n\n    i.object_setattr(\"two\", 101)\n    assert i.two == 101\n\n    object.__setattr__(i, \"three\", 102)\n    assert i.three == 102\n\n    del i.three\n    assert i.three == None\n\n    delattr(i, \"two\")\n    assert i.two == None\n\n    object.__delattr__(i, \"one\")\n    assert i.one == None\n\ntest_setattr()\ntest_setattr_inherited()\ntest_setattr_overridden()\ntest_setattr_nonnative()\ntest_no_setattr()\ntest_no_setattr_nonnative()\n\n[typing fixtures/typing-full.pyi]\n\n[case testDelAttrWithDeletableAttr]\nfrom testutil import assertRaises\n\nclass DelAttr:\n    __deletable__ = [\"del_counter\"]\n\n    _attributes: dict[str, object]\n    del_counter: int = 0\n\n    def __init__(self) -> None:\n        object.__setattr__(self, \"_attributes\", {})\n\n    def __setattr__(self, key: str, val: object) -> None:\n        if key == \"del_counter\":\n            object.__setattr__(self, \"del_counter\", val)\n        else:\n            self._attributes[key] = val\n\n    def __delattr__(self, key: str) -> None:\n        if key == \"del_counter\":\n            self.del_counter += 1\n        else:\n            del self._attributes[key]\n\ndef test_deletable_attr() -> None:\n    i = DelAttr()\n    assert i.del_counter == 0\n    del i.del_counter\n    assert i.del_counter == 1\n\n[case testDelAttrWithDeletableAttrInterpreted]\nclass DelAttr:\n    __deletable__ = [\"del_counter\"]\n\n    _attributes: dict[str, object]\n    del_counter: int = 0\n\n    def __init__(self) -> None:\n        object.__setattr__(self, \"_attributes\", {})\n\n    def __setattr__(self, key: str, val: object) -> None:\n        if key == \"del_counter\":\n            object.__setattr__(self, \"del_counter\", val)\n        else:\n            self._attributes[key] = val\n\n    def __delattr__(self, key: str) -> None:\n        if key == \"del_counter\":\n            self.del_counter += 1\n        else:\n            del self._attributes[key]\n\n[file driver.py]\nfrom native import DelAttr\nfrom testutil import assertRaises\n\ndef test_deletable_attr() -> None:\n    i = DelAttr()\n    assert i.del_counter == 0\n    del i.del_counter\n    assert i.del_counter == 1\n\ntest_deletable_attr()\n\n[case testBufferCorruptedData_librt_internal]\nfrom librt.internal import (\n    ReadBuffer, read_bool, read_str, read_float, read_int, read_tag, read_bytes\n)\nfrom random import randbytes\n\ndef check(data: bytes) -> None:\n    b = ReadBuffer(data)\n    try:\n        while True:\n            read_bool(b)\n    except ValueError:\n        pass\n    b = ReadBuffer(data)\n    read_tag(b)  # Always succeeds\n    try:\n        while True:\n            read_int(b)\n    except ValueError:\n        pass\n    b = ReadBuffer(data)\n    try:\n        while True:\n            read_str(b)\n    except ValueError:\n        pass\n    b = ReadBuffer(data)\n    try:\n        while True:\n            read_bytes(b)\n    except ValueError:\n        pass\n    b = ReadBuffer(data)\n    try:\n        while True:\n            read_float(b)\n    except ValueError:\n        pass\n\nimport time\n\ndef test_read_corrupted_data() -> None:\n    # Test various deterministic byte sequences (1 to 4 bytes).\n    t0 = time.time()\n    for a in range(256):\n        check(bytes([a]))\n    for a in range(256):\n        for b in range(256):\n            check(bytes([a, b]))\n    for a in range(32):\n        for b in range(48):\n            for c in range(48):\n                check(bytes([a, b, c]))\n    for a in range(32):\n        for b in (0, 5, 17, 34):\n            for c in (0, 5, 17, 34):\n                for d in (0, 5, 17, 34):\n                    check(bytes([a, b, c, d]))\n    # Also test some random data.\n    for i in range(20000):\n        data = randbytes(16)\n        try:\n            check(data)\n        except BaseException as e:\n            print(\"RANDOMIZED TEST FAILURE -- please open an issue with the following context:\")\n            print(\">>>\", e, data)\n            raise\n\n[case testAcyclicClass]\nimport gc\nfrom mypy_extensions import mypyc_attr\n\n@mypyc_attr(acyclic=True)\nclass Leaf:\n    def __init__(self, x: int, s: str) -> None:\n        self.x = x\n        self.s = s\n\ndef test_basic() -> None:\n    o = Leaf(5, \"hello\")\n    assert o.x == 5\n    assert o.s == \"hello\"\n    o.x = 10\n    assert o.x == 10\n\ndef test_gc_not_tracked() -> None:\n    o = Leaf(1, \"a\")\n    assert not gc.is_tracked(o)\n\ndef test_dealloc() -> None:\n    for i in range(1000):\n        o = Leaf(i, str(i))\n    # Just verify no crash or leak during repeated alloc/dealloc\n\n@mypyc_attr(acyclic=True)\nclass AcyclicBase:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\nclass DerivedNotAcyclic(AcyclicBase):\n    \"\"\"Derived without acyclic -- still participates in GC.\"\"\"\n    def __init__(self, x: int, y: str) -> None:\n        super().__init__(x)\n        self.y = y\n\n@mypyc_attr(acyclic=True)\nclass DerivedAcyclic(AcyclicBase):\n    \"\"\"Derived with acyclic -- also opts out of GC.\"\"\"\n    def __init__(self, x: int, y: str) -> None:\n        super().__init__(x)\n        self.y = y\n\ndef test_derived_not_acyclic() -> None:\n    d = DerivedNotAcyclic(3, \"hi\")\n    assert d.x == 3\n    assert d.y == \"hi\"\n    # Subclass without @mypyc_attr(acyclic=True) still participates in GC\n    assert gc.is_tracked(d)\n\ndef test_derived_acyclic() -> None:\n    d = DerivedAcyclic(3, \"hi\")\n    assert d.x == 3\n    assert d.y == \"hi\"\n    assert not gc.is_tracked(d)\n\n[case testTraitVtableGrandparentMethod]\nfrom typing import Any\nfrom mypy_extensions import trait\n\n@trait\nclass Base:\n    def value(self) -> Any:\n        return 42\n\n@trait\nclass Middle(Base):\n    pass\n\n@trait\nclass Child(Middle):\n    def derived(self) -> Any:\n        return self.value()\n\nclass Concrete(Child):\n    pass\n\nclass Sub(Concrete):\n    def value(self) -> Any:\n        return 99\n\n[file driver.py]\nfrom native import Concrete, Sub\nc = Concrete()\nassert c.value() == 42\nassert c.derived() == 42\ns = Sub()\nassert s.value() == 99\nassert s.derived() == 99\n\n[case testTraitVtableGrandparentMethodAllowInterpretedSubclasses]\nfrom typing import Any\nfrom mypy_extensions import trait, mypyc_attr\n\n@mypyc_attr(allow_interpreted_subclasses=True)\n@trait\nclass Base:\n    def value(self) -> Any:\n        return 42\n\n@mypyc_attr(allow_interpreted_subclasses=True)\n@trait\nclass Middle(Base):\n    pass\n\n@mypyc_attr(allow_interpreted_subclasses=True)\n@trait\nclass Child(Middle):\n    def derived(self) -> Any:\n        return self.value()\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass Concrete(Child):\n    pass\n\n[file driver.py]\nfrom native import Concrete\nc = Concrete()\nassert c.value() == 42\nassert c.derived() == 42\n\n[case testPropertyShadowVtableGlue]\nfrom typing import List\nimport mypy_extensions\n\n@mypy_extensions.mypyc_attr(allow_interpreted_subclasses=True)\nclass Base:\n    _x: str\n    _y: List[int]\n    def __init__(self) -> None:\n        self._x = \"\"\n        self._y = []\n\n    @property\n    def x(self) -> str:\n        return self._x\n\n    @x.setter\n    def x(self, v: str) -> None:\n        self._x = v\n\n    @property\n    def y(self) -> List[int]:\n        return self._y\n\n    @y.setter\n    def y(self, v: List[int]) -> None:\n        self._y = v\n\n    def method(self) -> str:\n        self.x = \"a\"\n        self.y = [1]\n        return self.x + str(len(self.y))\n\n[file driver.py]\nfrom native import Base\n\nSub = type(\"Sub\", (Base,), {})\ns = Sub()\nassert s.method() == \"a1\"\n"
  },
  {
    "path": "mypyc/test-data/run-dicts.test",
    "content": "# Test cases for dicts (compile and run)\n\n[case testDictStuff]\nfrom typing import Dict, Any, List, Set, Tuple\nfrom defaultdictwrap import make_dict\n\ndef f(x: int) -> int:\n    dict1 = {} # type: Dict[int, int]\n    dict1[1] = 1\n    dict2 = {} # type: Dict[int, int]\n    dict2[x] = 2\n    dict1.update(dict2)\n\n    l = [(5, 2)]  # type: Any\n    dict1.update(l)\n    d2 = {6: 4}  # type: Any\n    dict1.update(d2)\n\n    return dict1[1]\n\ndef g() -> int:\n    d = make_dict()\n    d['a'] = 10\n    d['a'] += 10\n    d['b'] += 10\n    l = [('c', 2)]  # type: Any\n    d.update(l)\n    d2 = {'d': 4}  # type: Any\n    d.update(d2)\n    return d['a'] + d['b']\n\ndef h() -> None:\n    d = {}  # type: Dict[Any, Any]\n    d[{}]\n\ndef update_dict(x: Dict[Any, Any], y: Any):\n    x.update(y)\n\ndef make_dict1(x: Any) -> Dict[Any, Any]:\n    return dict(x)\n\ndef make_dict2(x: Dict[Any, Any]) -> Dict[Any, Any]:\n    return dict(x)\n\ndef u(x: int) -> int:\n    d = {} # type: Dict[str, int]\n    d.update(x=x)\n    return d['x']\n\ndef get_content(d: Dict[int, int]) -> Tuple[List[int], List[int], List[Tuple[int, int]]]:\n    return list(d.keys()), list(d.values()), list(d.items())\n\ndef get_content_set(d: Dict[int, int]) -> Tuple[Set[int], Set[int], Set[Tuple[int, int]]]:\n    return set(d.keys()), set(d.values()), set(d.items())\n[file defaultdictwrap.py]\nfrom typing import Dict\nfrom collections import defaultdict  # type: ignore\ndef make_dict() -> Dict[str, int]:\n    return defaultdict(int)\n\n[file driver.py]\nfrom collections import OrderedDict\nfrom native import (\n    f, g, h, u, make_dict1, make_dict2, update_dict, get_content, get_content_set\n)\nassert f(1) == 2\nassert f(2) == 1\nassert g() == 30\n# Make sure we get a TypeError from indexing with unhashable and not KeyError\ntry:\n    h()\nexcept TypeError:\n    pass\nelse:\n    assert False\nd = {'a': 1, 'b': 2}\nassert make_dict1(d) == d\nassert make_dict1(d.items()) == d\nassert make_dict2(d) == d\n# object.__dict__ is a \"mappingproxy\" and not a dict\nassert make_dict1(object.__dict__) == dict(object.__dict__)\nd = {}\nupdate_dict(d, object.__dict__)\nassert d == dict(object.__dict__)\n\nassert u(10) == 10\nassert get_content({1: 2}) == ([1], [2], [(1, 2)])\nod = OrderedDict([(1, 2), (3, 4)])\nassert get_content(od) == ([1, 3], [2, 4], [(1, 2), (3, 4)])\nod.move_to_end(1)\nassert get_content(od) == ([3, 1], [4, 2], [(3, 4), (1, 2)])\nassert get_content_set({1: 2}) == ({1}, {2}, {(1, 2)})\nassert get_content_set(od) == ({1, 3}, {2, 4}, {(1, 2), (3, 4)})\n\n[typing fixtures/typing-full.pyi]\n\n[case testDictIterationMethodsRun]\nfrom typing import Dict, TypedDict, Union\n\nclass ExtensionDict(TypedDict):\n    python: str\n    c: str\n\ndef print_dict_methods(d1: Dict[int, int],\n                       d2: Dict[int, int],\n                       d3: Dict[int, int]) -> None:\n    for k in d1.keys():\n        print(k)\n    for k, v in d2.items():\n        print(k)\n        print(v)\n    for v in d3.values():\n        print(v)\n\ndef print_dict_methods_special(d1: Union[Dict[int, int], Dict[str, str]],\n                               d2: ExtensionDict) -> None:\n    for k in d1.keys():\n        print(k)\n    for k, v in d1.items():\n        print(k)\n        print(v)\n    for v2 in d2.values():\n        print(v2)\n    for k2, v2 in d2.items():\n        print(k2)\n        print(v2)\n\n\ndef clear_during_iter(d: Dict[int, int]) -> None:\n    for k in d:\n        d.clear()\n\nclass Custom(Dict[int, int]): pass\n[file driver.py]\nfrom native import print_dict_methods, print_dict_methods_special, Custom, clear_during_iter\nfrom collections import OrderedDict\nprint_dict_methods({}, {}, {})\nprint_dict_methods({1: 2}, {3: 4, 5: 6}, {7: 8})\nprint('==')\nc = Custom({0: 1})\nprint_dict_methods(c, c, c)\nprint('==')\nd = OrderedDict([(1, 2), (3, 4)])\nprint_dict_methods(d, d, d)\nprint('==')\nprint_dict_methods_special({1: 2}, {\"python\": \".py\", \"c\": \".c\"})\nd.move_to_end(1)\nprint_dict_methods(d, d, d)\nclear_during_iter({})  # OK\ntry:\n    clear_during_iter({1: 2, 3: 4})\nexcept RuntimeError as e:\n    assert str(e) == \"dictionary changed size during iteration\"\nelse:\n    assert False\ntry:\n    clear_during_iter(d)\nexcept RuntimeError as e:\n    assert str(e) in (\n        \"OrderedDict changed size during iteration\",\n        # Error message changed in Python 3.13 and some 3.12 patch version\n        \"OrderedDict mutated during iteration\",\n    )\nelse:\n    assert False\n\nclass CustomMad(dict):\n    def __iter__(self):\n        return self\n    def __next__(self):\n        raise ValueError\nm = CustomMad()\ntry:\n    clear_during_iter(m)\nexcept ValueError:\n    pass\nelse:\n    assert False\n\nclass CustomBad(dict):\n    def items(self):\n        return [(1, 2, 3)]  # Oops\nb = CustomBad()\ntry:\n    print_dict_methods(b, b, b)\nexcept TypeError as e:\n    assert str(e) == \"a tuple of length 2 expected\"\nelse:\n    assert False\n[typing fixtures/typing-full.pyi]\n[out]\n1\n3\n4\n5\n6\n8\n==\n0\n0\n1\n1\n==\n1\n3\n1\n2\n3\n4\n2\n4\n==\n1\n1\n2\n.py\n.c\npython\n.py\nc\n.c\n3\n1\n3\n4\n1\n2\n4\n2\n\n[case testDictMethods]\nfrom collections import defaultdict\nfrom typing import Dict, Optional, List, Set\n\ndef test_dict_clear() -> None:\n    d = {'a': 1, 'b': 2}\n    d.clear()\n    assert d == {}\n    dd: Dict[str, int] = defaultdict(int)\n    dd['a'] = 1\n    dd.clear()\n    assert dd == {}\n\ndef test_dict_copy() -> None:\n    d: Dict[str, int] = {}\n    assert d.copy() == d\n    d = {'a': 1, 'b': 2}\n    assert d.copy() == d\n    assert d.copy() is not d\n    dd: Dict[str, int] = defaultdict(int)\n    dd['a'] = 1\n    assert dd.copy() == dd\n    assert isinstance(dd.copy(), defaultdict)\n\nclass MyDict(dict):\n    def __init__(self, *args, **kwargs):\n        self.update(*args, **kwargs)\n\n    def setdefault(self, k, v=None):\n        if v is None:\n            if k in self.keys():\n                return self[k]\n            else:\n                return None\n        else:\n            return super().setdefault(k, v) + 10\n\ndef test_dict_setdefault() -> None:\n    d: Dict[str, Optional[int]] = {'a': 1, 'b': 2}\n    assert d.setdefault('a', 2) == 1\n    assert d.setdefault('b', 2) == 2\n    assert d.setdefault('c', 3) == 3\n    assert d['a'] == 1\n    assert d['c'] == 3\n    assert d.setdefault('a') == 1\n    assert d.setdefault('e') == None\n    assert d.setdefault('e', 100) == None\n\ndef test_dict_subclass_setdefault() -> None:\n    d = MyDict()\n    d['a'] = 1\n    assert d.setdefault('a', 2) == 11\n    assert d.setdefault('b', 2) == 12\n    assert d.setdefault('c', 3) == 13\n    assert d['a'] == 1\n    assert d['c'] == 3\n    assert d.setdefault('a') == 1\n    assert d.setdefault('e') == None\n    assert d.setdefault('e', 100) == 110\n\ndef test_dict_empty_collection_setdefault() -> None:\n    d1: Dict[str, List[int]] = {'a': [1, 2, 3]}\n    assert d1.setdefault('a', []) == [1, 2, 3]\n    assert d1.setdefault('b', []) == []\n    assert 'b' in d1\n    d1.setdefault('b', []).append(3)\n    assert d1['b'] == [3]\n    assert d1.setdefault('c', [1]) == [1]\n\n    d2: Dict[str, Dict[str, int]] = {'a': {'a': 1}}\n    assert d2.setdefault('a', {}) == {'a': 1}\n    assert d2.setdefault('b', {}) == {}\n    assert 'b' in d2\n    d2.setdefault('b', {})['aa'] = 2\n    d2.setdefault('b', {})['bb'] = 3\n    assert d2['b'] == {'aa': 2, 'bb': 3}\n    assert d2.setdefault('c', {'cc': 1}) == {'cc': 1}\n\n    d3: Dict[str, Set[str]] = {'a': set('a')}\n    assert d3.setdefault('a', set()) == {'a'}\n    assert d3.setdefault('b', set()) == set()\n    d3.setdefault('b', set()).add('b')\n    d3.setdefault('b', set()).add('c')\n    assert d3['b'] == {'b', 'c'}\n    assert d3.setdefault('c', set('d')) == {'d'}\n\n[case testDictToBool]\nfrom typing import Dict, List\n\ndef is_true(x: dict) -> bool:\n    if x:\n        return True\n    else:\n        return False\n\ndef is_false(x: dict) -> bool:\n    if not x:\n        return True\n    else:\n        return False\n\ndef test_dict_to_bool() -> None:\n    assert is_false({})\n    assert not is_true({})\n    tmp_list: List[Dict] = [{2: bool}, {'a': 'b'}]\n    for x in tmp_list:\n        assert is_true(x)\n        assert not is_false(x)\n\n[case testIsInstance]\nfrom copysubclass import subc\ndef test_built_in() -> None:\n    assert isinstance({}, dict)\n    assert isinstance({'one': 1, 'two': 2}, dict)\n    assert isinstance({1: 1, 'two': 2}, dict)\n    assert isinstance(subc(), dict)\n    assert isinstance(subc({'a': 1, 'b': 2}), dict)\n    assert isinstance(subc({1: 'a', 2: 'b'}), dict)\n\n    assert not isinstance(set(), dict)\n    assert not isinstance((), dict)\n    assert not isinstance((1,2,3), dict)\n    assert not isinstance({'a','b'}, dict)\n    assert not isinstance(int() + 1, dict)\n    assert not isinstance(str() + 'a', dict)\n\ndef test_user_defined() -> None:\n    from userdefineddict import dict\n\n    assert isinstance(dict(), dict)\n    assert not isinstance({1: dict()}, dict)\n\n[file copysubclass.py]\nfrom typing import Any\nclass subc(dict[Any, Any]):\n    pass\n\n[file userdefineddict.py]\nclass dict:\n    pass\n"
  },
  {
    "path": "mypyc/test-data/run-dunders-special.test",
    "content": "[case testDundersNotImplemented]\n# This case is special because it tests the behavior of NotImplemented\n# used in a typed function which return type is bool.\n# This is a convention that can be overridden by the user.\nclass UsesNotImplemented:\n    def __eq__(self, b: object) -> bool:\n        return NotImplemented\n\ndef test_not_implemented() -> None:\n    assert UsesNotImplemented() != object()\n    x = UsesNotImplemented() == object()\n    assert not x\n"
  },
  {
    "path": "mypyc/test-data/run-dunders.test",
    "content": "# Test cases for (some) dunder methods (compile and run)\n\n[case testDundersMisc]\n# Legacy test case for dunders (don't add more here)\n\nfrom typing import Any\nclass Item:\n    def __init__(self, value: str) -> None:\n        self.value = value\n\n    def __hash__(self) -> int:\n        return hash(self.value)\n\n    def __eq__(self, rhs: object) -> bool:\n        return isinstance(rhs, Item) and self.value == rhs.value\n\n    def __lt__(self, x: 'Item') -> bool:\n        return self.value < x.value\n\nclass Subclass1(Item):\n    def __bool__(self) -> bool:\n        return bool(self.value)\n\nclass NonBoxedThing:\n    def __getitem__(self, index: Item) -> Item:\n        return Item(\"2 * \" + index.value + \" + 1\")\n\nclass BoxedThing:\n    def __getitem__(self, index: int) -> int:\n        return 2 * index + 1\n\nclass Subclass2(BoxedThing):\n    pass\n\ndef index_into(x : Any, y : Any) -> Any:\n    return x[y]\n\ndef internal_index_into() -> None:\n    x = BoxedThing()\n    print (x[3])\n    y = NonBoxedThing()\n    z = Item(\"3\")\n    print(y[z].value)\n\ndef is_truthy(x: Item) -> bool:\n    return True if x else False\n\n[file driver.py]\nfrom native import *\nx = BoxedThing()\ny = 3\nprint(x[y], index_into(x, y))\n\nx = Subclass2()\ny = 3\nprint(x[y], index_into(x, y))\n\nz = NonBoxedThing()\nw = Item(\"3\")\nprint(z[w].value, index_into(z, w).value)\n\ni1 = Item('lolol')\ni2 = Item('lol' + 'ol')\ni3 = Item('xyzzy')\nassert hash(i1) == hash(i2)\n\nassert i1 == i2\nassert not i1 != i2\nassert not i1 == i3\nassert i1 != i3\nassert i2 < i3\nassert not i1 < i2\nassert i1 == Subclass1('lolol')\n\nassert is_truthy(Item(''))\nassert is_truthy(Item('a'))\nassert not is_truthy(Subclass1(''))\nassert is_truthy(Subclass1('a'))\n\ninternal_index_into()\n[out]\n7 7\n7 7\n2 * 3 + 1 2 * 3 + 1\n7\n2 * 3 + 1\n\n[case testDundersContainer]\n# Sequence/mapping dunder methods\n\nfrom typing import Any\n\nclass Seq:\n    def __init__(self) -> None:\n        self.key = 0\n        self.value = 0\n\n    def __len__(self) -> int:\n        return 5\n\n    def __setitem__(self, key: int, value: int) -> None:\n        self.key = key\n        self.value = value\n\n    def __contains__(self, x: int) -> bool:\n        return x == 3\n\n    def __delitem__(self, key: int) -> None:\n        self.key = key\n\nclass Plain: pass\n\ndef any_seq() -> Any:\n    \"\"\"Return Any-typed Seq.\"\"\"\n    return Seq()\n\ndef any_plain() -> Any:\n    \"\"\"Return Any-typed Seq.\"\"\"\n    return Plain()\n\ndef test_len() -> None:\n    assert len(any_seq()) == 5\n    assert len(Seq()) == 5\n\ndef test_len_error() -> None:\n    try:\n        len(any_plain())\n    except TypeError:\n        pass\n    else:\n        assert False\n\ndef test_set_item() -> None:\n    s = any_seq()\n    s[44] = 66\n    assert s.key == 44 and s.value == 66\n    ss = Seq()\n    ss[33] = 55\n    assert ss.key == 33 and ss.value == 55\n\ndef test_contains() -> None:\n    assert 3 in any_seq()\n    assert 4 not in any_seq()\n    assert 2 not in any_seq()\n    assert 3 in Seq()\n    assert 4 not in Seq()\n    assert 2 not in Seq()\n\ndef test_delitem() -> None:\n    s = any_seq()\n    del s[55]\n    assert s.key == 55\n\nclass SeqAny:\n    def __contains__(self, x: Any) -> Any:\n        return x == 3\n\n    def __setitem__(self, x: Any, y: Any) -> Any:\n        self.x = x\n        return 'x'\n\ndef test_contains_any() -> None:\n    assert (3 in SeqAny()) is True\n    assert (2 in SeqAny()) is False\n    assert (3 not in SeqAny()) is False\n    assert (2 not in SeqAny()) is True\n    s = SeqAny()  # type: Any\n    assert (3 in s) is True\n    assert (2 in s) is False\n    assert (3 not in s) is False\n    assert (2 not in s) is True\n\ndef test_set_item_any() -> None:\n    s = SeqAny()\n    s[4] = 6\n    assert s.x == 4\n    ss = SeqAny()  # type: Any\n    ss[5] = 7\n    assert ss.x == 5\n\nclass SeqError:\n    def __setitem__(self, key: int, value: int) -> None:\n        raise RuntimeError()\n\n    def __contains__(self, x: int) -> bool:\n        raise RuntimeError()\n\n    def __len__(self) -> int:\n        return -5\n\ndef any_seq_error() -> Any:\n    return SeqError()\n\ndef test_set_item_error_propagate() -> None:\n    s = any_seq_error()\n    try:\n        s[44] = 66\n    except RuntimeError:\n        pass\n    else:\n        assert False\n\ndef test_contains_error_propagate() -> None:\n    s = any_seq_error()\n    try:\n        3 in s\n    except RuntimeError:\n        pass\n    else:\n        assert False\n\ndef test_negative_len() -> None:\n    try:\n        len(SeqError())\n    except ValueError:\n        pass\n    else:\n        assert False\n\nclass DelItemNoSetItem:\n    def __delitem__(self, x: int) -> None:\n        self.key = x\n\ndef test_del_item_with_no_set_item() -> None:\n    o = DelItemNoSetItem()\n    del o[22]\n    assert o.key == 22\n    a = o  # type: Any\n    del a[12]\n    assert a.key == 12\n    try:\n        a[1] = 2\n    except TypeError as e:\n        assert str(e) == \"'DelItemNoSetItem' object does not support item assignment\"\n    else:\n        assert False\n\nclass SetItemOverride(dict):\n    # Only override __setitem__, __delitem__ comes from dict\n\n    def __setitem__(self, x: int, y: int) -> None:\n        self.key = x\n        self.value = y\n\ndef test_set_item_override() -> None:\n    o = SetItemOverride({'x': 12, 'y': 13})\n    o[2] = 3\n    assert o.key == 2 and o.value == 3\n    a = o  # type: Any\n    o[4] = 5\n    assert o.key == 4 and o.value == 5\n    assert o['x'] == 12\n    assert o['y'] == 13\n    del o['x']\n    assert 'x' not in o and 'y' in o\n    del a['y']\n    assert 'y' not in a and 'x' not in a\n\nclass DelItemOverride(dict):\n    # Only override __delitem__, __setitem__ comes from dict\n\n    def __delitem__(self, x: int) -> None:\n        self.key = x\n\ndef test_del_item_override() -> None:\n    o = DelItemOverride()\n    del o[2]\n    assert o.key == 2\n    a = o  # type: Any\n    del o[5]\n    assert o.key == 5\n    o['x'] = 12\n    assert o['x'] == 12\n    a['y'] = 13\n    assert a['y'] == 13\n\nclass SetItemOverrideNative(Seq):\n    def __setitem__(self, key: int, value: int) -> None:\n        self.key = key + 1\n        self.value = value + 1\n\ndef test_native_set_item_override() -> None:\n    o = SetItemOverrideNative()\n    o[1] = 4\n    assert o.key == 2 and o.value == 5\n    del o[6]\n    assert o.key == 6\n    a = o  # type: Any\n    a[10] = 12\n    assert a.key == 11 and a.value == 13\n    del a[16]\n    assert a.key == 16\n\nclass DelItemOverrideNative(Seq):\n    def __delitem__(self, key: int) -> None:\n        self.key = key + 2\n\ndef test_native_del_item_override() -> None:\n    o = DelItemOverrideNative()\n    o[1] = 4\n    assert o.key == 1 and o.value == 4\n    del o[6]\n    assert o.key == 8\n    a = o  # type: Any\n    a[10] = 12\n    assert a.key == 10 and a.value == 12\n    del a[16]\n    assert a.key == 18\n\n[case testDundersNumber]\nfrom typing import Any\n\nclass C:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def __neg__(self) -> int:\n        return self.x + 1\n\n    def __invert__(self) -> int:\n        return self.x + 2\n\n    def __int__(self) -> int:\n        return self.x + 3\n\n    def __float__(self) -> float:\n        return float(self.x + 4)\n\n    def __pos__(self) -> int:\n        return self.x + 5\n\n    def __abs__(self) -> int:\n        return abs(self.x) + 6\n\n\ndef test_unary_dunders_generic() -> None:\n    a: Any = C(10)\n\n    assert -a == 11\n    assert ~a == 12\n    assert int(a) == 13\n    assert float(a) == 14.0\n    assert +a == 15\n    assert abs(a) == 16\n\ndef test_unary_dunders_native() -> None:\n    c = C(10)\n\n    assert -c == 11\n    assert ~c == 12\n    assert int(c) == 13\n    assert float(c) == 14.0\n    assert +c == 15\n    assert abs(c) == 16\n\n[case testDundersBinarySimple]\nfrom typing import Any\n\nclass C:\n    def __init__(self) -> None:\n        self.x = 5\n\n    def __add__(self, y: int) -> int:\n        return self.x + y\n\n    def __sub__(self, y: int) -> int:\n        return self.x - y\n\n    def __mul__(self, y: int) -> int:\n        return self.x * y\n\n    def __mod__(self, y: int) -> int:\n        return self.x % y\n\n    def __lshift__(self, y: int) -> int:\n        return self.x << y\n\n    def __rshift__(self, y: int) -> int:\n        return self.x >> y\n\n    def __and__(self, y: int) -> int:\n        return self.x & y\n\n    def __or__(self, y: int) -> int:\n        return self.x | y\n\n    def __xor__(self, y: int) -> int:\n        return self.x ^ y\n\n    def __matmul__(self, y: int) -> int:\n        return self.x + y + 10\n\n    def __truediv__(self, y: int) -> int:\n        return self.x + y + 20\n\n    def __floordiv__(self, y: int) -> int:\n        return self.x + y + 30\n\n    def __divmod__(self, y: int) -> int:\n        return self.x + y + 40\n\n    def __pow__(self, y: int) -> int:\n        return self.x + y + 50\n\ndef test_generic() -> None:\n    a: Any = C()\n    assert a + 3 == 8\n    assert a - 3 == 2\n    assert a * 5 == 25\n    assert a % 2 == 1\n    assert a << 4 == 80\n    assert a >> 0 == 5\n    assert a >> 1 == 2\n    assert a & 1 == 1\n    assert a | 3 == 7\n    assert a ^ 3 == 6\n    assert a @ 3 == 18\n    assert a / 2 == 27\n    assert a // 2 == 37\n    assert divmod(a, 2) == 47\n    assert a ** 2 == 57\n\ndef test_native() -> None:\n    c = C()\n    assert c + 3 == 8\n    assert c - 3 == 2\n    assert divmod(c, 3) == 48\n    assert c ** 3 == 58\n\ndef test_error() -> None:\n    a: Any = C()\n    try:\n        a + 'x'\n    except TypeError as e:\n        assert str(e) == \"unsupported operand type(s) for +: 'C' and 'str'\"\n    else:\n        assert False\n    try:\n        a - 'x'\n    except TypeError as e:\n        assert str(e) == \"unsupported operand type(s) for -: 'C' and 'str'\"\n    else:\n        assert False\n    try:\n        a ** 'x'\n    except TypeError as e:\n        assert str(e) == \"unsupported operand type(s) for **: 'C' and 'str'\"\n    else:\n        assert False\n\n[case testDundersBinaryReverse]\nfrom typing import Any\n\nclass C:\n    def __init__(self) -> None:\n        self.x = 5\n\n    def __add__(self, y: int) -> int:\n        return self.x + y\n\n    def __radd__(self, y: int) -> int:\n        return self.x + y + 1\n\n    def __sub__(self, y: int) -> int:\n        return self.x - y\n\n    def __rsub__(self, y: int) -> int:\n        return self.x - y - 1\n\n    def __pow__(self, y: int) -> int:\n        return self.x**y\n\n    def __rpow__(self, y: int) -> int:\n        return self.x**y + 1\n\ndef test_generic() -> None:\n    a: Any = C()\n    assert a + 3 == 8\n    assert 4 + a == 10\n    assert a - 3 == 2\n    assert 4 - a == 0\n    assert a**3 == 125\n    assert 4**a == 626\n\ndef test_native() -> None:\n    c = C()\n    assert c + 3 == 8\n    assert 4 + c == 10\n    assert c - 3 == 2\n    assert 4 - c == 0\n    assert c**3 == 125\n    assert 4**c == 626\n\ndef test_errors() -> None:\n    a: Any = C()\n    try:\n        a + 'x'\n    except TypeError as e:\n        assert str(e) == \"unsupported operand type(s) for +: 'C' and 'str'\"\n    else:\n        assert False\n    try:\n        a - 'x'\n    except TypeError as e:\n        assert str(e) == \"unsupported operand type(s) for -: 'C' and 'str'\"\n    else:\n        assert False\n    try:\n        'x' + a\n    except TypeError as e:\n        assert str(e) in ('can only concatenate str (not \"C\") to str',\n                          'must be str, not C')\n    else:\n        assert False\n    try:\n        'x' ** a\n    except TypeError as e:\n        assert str(e) == \"unsupported operand type(s) for ** or pow(): 'str' and 'C'\"\n    else:\n        assert False\n\n\nclass F:\n    def __add__(self, x: int) -> int:\n        return 5\n\n    def __pow__(self, x: int) -> int:\n        return -5\n\nclass G:\n    def __add__(self, x: int) -> int:\n        return 33\n\n    def __pow__(self, x: int) -> int:\n        return -33\n\n    def __radd__(self, x: F) -> int:\n        return 6\n\n    def __rpow__(self, x: F) -> int:\n        return -6\n\ndef test_type_mismatch_fall_back_to_reverse() -> None:\n    assert F() + G() == 6\n    assert F()**G() == -6\n\n[case testDundersBinaryNotImplemented]\n# mypy: allow-untyped-defs\nfrom typing import Any, Union\nfrom testutil import assertRaises\n\nclass C:\n    def __init__(self, v: int) -> None:\n        self.v = v\n\n    def __add__(self, y: int) -> Union[int, Any]:\n        if y == 1:\n            return self.v\n        return NotImplemented\n\ndef test_any_add() -> None:\n    a: Any = C(4)\n    assert a + 1 == 4\n    try:\n        a + 2\n    except TypeError:\n        pass\n    else:\n        assert False\n\nclass D:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def __add__(self, e: E) -> Union[int, Any]:\n        if e.x == 1:\n            return 2\n        return NotImplemented\n\nclass E:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def __radd__(self, d: D) -> Union[int, Any]:\n        if d.x == 3:\n            return 4\n        return NotImplemented\n\ndef test_any_radd() -> None:\n    d1: Any = D(1)\n    d3: Any = D(3)\n    e1: Any = E(1)\n    e3: Any = E(3)\n    assert d1 + e1 == 2\n    assert d3 + e1 == 2\n    assert d3 + e3 == 4\n\nclass F:\n    def __init__(self, v):\n        self.v = v\n\n    def __add__(self, x):\n        if isinstance(x, int):\n            return self.v + x\n        return NotImplemented\n\nclass G:\n    def __radd__(self, x):\n        if isinstance(x, F):\n            return x.v + 1\n        if isinstance(x, str):\n            return 'a'\n        return NotImplemented\n\ndef test_unannotated_add() -> None:\n    o = F(4)\n    assert o + 5 == 9\n    with assertRaises(TypeError, \"unsupported operand type(s) for +: 'F' and 'str'\"):\n        o + 'x'\n\n    o2: Any = F(4)\n    assert o2 + 5 == 9\n    with assertRaises(TypeError, \"unsupported operand type(s) for +: 'F' and 'str'\"):\n        o2 + 'x'\n\ndef test_unannotated_add_and_radd_1() -> None:\n    o = F(4)\n    assert o + G() == 5\n\n    o2: Any = F(4)\n    assert o2 + G() == 5\n\ndef test_unannotated_radd() -> None:\n    assert 'x' + G() == 'a'\n    with assertRaises(TypeError, \"unsupported operand type(s) for +: 'int' and 'G'\"):\n        1 + G()\n\n    o: Any = G()\n    assert 'x' + o == 'a'\n    with assertRaises(TypeError, \"unsupported operand type(s) for +: 'int' and 'G'\"):\n        1 + o\n\nclass H:\n    def __add__(self, x):\n        if isinstance(x, int):\n            return x + 1\n        return NotImplemented\n\n    def __radd__(self, x):\n        if isinstance(x, str):\n            return 22\n        return NotImplemented\n\ndef test_unannotated_add_and_radd_2() -> None:\n    h = H()\n    assert h + 5 == 6\n    assert 'x' + h == 22\n    with assertRaises(TypeError, \"unsupported operand type(s) for +: 'int' and 'H'\"):\n        1 + h\n\n    h2: Any = H()\n    assert h + 5 == 6\n    assert 'x' + h == 22\n    with assertRaises(TypeError, \"unsupported operand type(s) for +: 'int' and 'H'\"):\n        1 + h\n\n# TODO: Inheritance\n\n[case testDifferentReverseDunders]\nfrom typing import Any\n\nclass C:\n    # __radd__ and __rsub__ are tested elsewhere\n\n    def __rmul__(self, x: Any) -> int:\n        return 1\n\n    def __rtruediv__(self, x: Any) -> int:\n        return 2\n\n    def __rmod__(self, x: Any) -> int:\n        return 3\n\n    def __rfloordiv__(self, x: Any) -> int:\n        return 4\n\n    def __rlshift__(self, x: Any) -> int:\n        return 5\n\n    def __rrshift__(self, x: Any) -> int:\n        return 6\n\n    def __rand__(self, x: Any) -> int:\n        return 7\n\n    def __ror__(self, x: Any) -> int:\n        return 8\n\n    def __rxor__(self, x: Any) -> int:\n        return 9\n\n    def __rmatmul__(self, x: Any) -> int:\n        return 10\n\ndef test_reverse_dunders() -> None:\n    x = 0\n    c = C()\n    assert x * c == 1\n    assert x / c == 2\n    assert x % c == 3\n    assert x // c == 4\n    assert x << c == 5\n    assert x >> c == 6\n    assert x & c == 7\n    assert x | c == 8\n    assert x ^ c == 9\n    assert x @ c == 10\n\n[case testDundersInplace]\nfrom typing import Any\nfrom testutil import assertRaises\n\nclass C:\n    def __init__(self) -> None:\n        self.x = 5\n\n    def __iadd__(self, y: int) -> C:\n        self.x += y\n        return self\n\n    def __isub__(self, y: int) -> C:\n        self.x -= y\n        return self\n\n    def __imul__(self, y: int) -> C:\n        self.x *= y\n        return self\n\n    def __imod__(self, y: int) -> C:\n        self.x %= y\n        return self\n\n    def __itruediv__(self, y: int) -> C:\n        self.x += y + 10\n        return self\n\n    def __ifloordiv__(self, y: int) -> C:\n        self.x += y + 20\n        return self\n\n    def __ilshift__(self, y: int) -> C:\n        self.x <<= y\n        return self\n\n    def __irshift__(self, y: int) -> C:\n        self.x >>= y\n        return self\n\n    def __iand__(self, y: int) -> C:\n        self.x &= y\n        return self\n\n    def __ior__(self, y: int) -> C:\n        self.x |= y\n        return self\n\n    def __ixor__(self, y: int) -> C:\n        self.x ^= y\n        return self\n\n    def __imatmul__(self, y: int) -> C:\n        self.x += y + 5\n        return self\n\n    def __ipow__(self, y: int, __mod_throwaway: None = None) -> C:\n        self.x **= y\n        return self\n\ndef test_generic_1() -> None:\n    c: Any = C()\n    c += 3\n    assert c.x == 8\n    c -= 5\n    assert c.x == 3\n    c *= 3\n    assert c.x == 9\n    c %= 4\n    assert c.x == 1\n    c /= 5\n    assert c.x == 16\n    c //= 4\n    assert c.x == 40\n    c **= 2\n    assert c.x == 1600\n\ndef test_generic_2() -> None:\n    c: Any = C()\n    c <<= 4\n    assert c.x == 80\n    c >>= 3\n    assert c.x == 10\n    c &= 3\n    assert c.x == 2\n    c |= 6\n    assert c.x == 6\n    c ^= 12\n    assert c.x == 10\n    c @= 3\n    assert c.x == 18\n\ndef test_native() -> None:\n    c = C()\n    c += 3\n    assert c.x == 8\n    c -= 5\n    assert c.x == 3\n    c *= 3\n    assert c.x == 9\n    c **= 2\n    assert c.x == 81\n\ndef test_error() -> None:\n    c: Any = C()\n    with assertRaises(TypeError, \"int object expected; got str\"):\n        c += 'x'\n\nclass BadInplaceAdd:\n    def __init__(self) -> None:\n        self.x = 0\n\n    def __iadd__(self, x: int) -> Any:\n        self.x += x\n\ndef test_in_place_operator_returns_none() -> None:\n    o = BadInplaceAdd()\n    with assertRaises(TypeError, \"native.BadInplaceAdd object expected; got None\"):\n        o += 5\n\n[case testDunderMinMax]\nclass SomeItem:\n    def __init__(self, val: int) -> None:\n        self.val = val\n\n    def __lt__(self, x: 'SomeItem') -> bool:\n        return self.val < x.val\n\n    def __gt__(self, x: 'SomeItem') -> bool:\n        return self.val > x.val\n\nclass AnotherItem:\n    def __init__(self, val: str) -> None:\n        self.val = val\n\n    def __lt__(self, x: 'AnotherItem') -> bool:\n        return True\n\n    def __gt__(self, x: 'AnotherItem') -> bool:\n        return True\n\ndef test_dunder_min() -> None:\n    x = SomeItem(5)\n    y = SomeItem(10)\n    z = SomeItem(15)\n    assert min(x, y).val == 5\n    assert min(y, z).val == 10\n    assert max(x, y).val == 10\n    assert max(y, z).val == 15\n    x2 = AnotherItem('xxx')\n    y2 = AnotherItem('yyy')\n    z2 = AnotherItem('zzz')\n    assert min(x2, y2).val == 'yyy'\n    assert min(y2, x2).val == 'xxx'\n    assert max(x2, y2).val == 'yyy'\n    assert max(y2, x2).val == 'xxx'\n    assert min(y2, z2).val == 'zzz'\n    assert max(x2, z2).val == 'zzz'\n\n\n[case testDundersPowerSpecial]\nimport sys\nfrom typing import Any, Optional\nfrom testutil import assertRaises\n\nclass Forward:\n    def __pow__(self, exp: int, mod: Optional[int] = None) -> int:\n        if mod is None:\n            return 2**exp\n        else:\n            return 2**exp % mod\n\nclass ForwardModRequired:\n    def __pow__(self, exp: int, mod: int) -> int:\n        return 2**exp % mod\n\nclass ForwardNotImplemented:\n    def __pow__(self, exp: int, mod: Optional[object] = None) -> Any:\n        return NotImplemented\n\nclass Reverse:\n    def __rpow__(self, exp: int) -> int:\n        return 2**exp + 1\n\nclass Both:\n    def __pow__(self, exp: int, mod: Optional[int] = None) -> int:\n        if mod is None:\n            return 2**exp\n        else:\n            return 2**exp % mod\n\n    def __rpow__(self, exp: int) -> int:\n        return 2**exp + 1\n\nclass Child(ForwardNotImplemented):\n    def __rpow__(self, exp: object) -> int:\n        return 50\n\nclass Inplace:\n    value = 2\n\n    def __ipow__(self, exp: int, mod: Optional[int] = None) -> \"Inplace\":\n        self.value **= exp - (mod or 0)\n        return self\n\ndef test_native() -> None:\n    f = Forward()\n    assert f**3 == 8\n    assert pow(f, 3) == 8\n    assert pow(f, 3, 3) == 2\n    assert pow(ForwardModRequired(), 3, 3) == 2\n    b = Both()\n    assert b**3 == 8\n    assert 3**b == 9\n    assert pow(b, 3) == 8\n    assert pow(b, 3, 3) == 2\n    i = Inplace()\n    i **= 2\n    assert i.value == 4\n\ndef test_errors() -> None:\n    if sys.version_info[0] >= 3 and sys.version_info[1] >= 10:\n        op = \"** or pow()\"\n    else:\n        op = \"pow()\"\n\n    f = Forward()\n    with assertRaises(TypeError, f\"unsupported operand type(s) for {op}: 'Forward', 'int', 'str'\"):\n        pow(f, 3, \"x\")  # type: ignore\n    with assertRaises(TypeError, \"unsupported operand type(s) for **: 'Forward' and 'str'\"):\n        f**\"x\"  # type: ignore\n    r = Reverse()\n    with assertRaises(TypeError, \"unsupported operand type(s) for ** or pow(): 'str' and 'Reverse'\"):\n        \"x\"**r  # type: ignore\n    with assertRaises(TypeError, f\"unsupported operand type(s) for {op}: 'int', 'Reverse', 'int'\"):\n        # Ternary pow() does not fallback to __rpow__ if LHS's __pow__ returns NotImplemented.\n        pow(3, r, 3)  # type: ignore\n    with assertRaises(TypeError, f\"unsupported operand type(s) for {op}: 'ForwardNotImplemented', 'Child', 'int'\"):\n        # Ternary pow() does not try RHS's __rpow__ first when it's a subclass and redefines\n        # __rpow__ unlike other ops.\n        pow(ForwardNotImplemented(), Child(), 3)  # type: ignore\n    with assertRaises(TypeError, \"unsupported operand type(s) for ** or pow(): 'ForwardModRequired' and 'int'\"):\n        ForwardModRequired()**3  # type: ignore\n\n[case testDundersWithFinal]\nfrom typing import final\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def __add__(self, y: int) -> int:\n        return self.x + y\n\n    def __lt__(self, x: 'A') -> bool:\n        return self.x < x.x\n\n@final\nclass B(A):\n    def __add__(self, y: int) -> int:\n        return self.x + y + 1\n\n    def __lt__(self, x: 'A') -> bool:\n        return self.x < x.x + 1\n\ndef test_final() -> None:\n    a = A(5)\n    b = B(5)\n    assert a + 3 == 8\n    assert b + 3 == 9\n    assert (a < A(5)) is False\n    assert (b < A(5)) is True\n\n[case testDundersEq]\nclass Eq:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def __eq__(self, other: object) -> bool:\n        if not isinstance(other, Eq):\n            return NotImplemented\n        return self.x == other.x\n\ndef eq(x: Eq, y: Eq) -> bool:\n    return x == y\n\ndef ne(x: Eq, y: Eq) -> bool:\n    return x != y\n\ndef test_equality_with_implicit_ne() -> None:\n    assert eq(Eq(1), Eq(1))\n    assert not eq(Eq(1), Eq(2))\n    assert ne(Eq(1), Eq(2))\n    assert not ne(Eq(1), Eq(1))\n"
  },
  {
    "path": "mypyc/test-data/run-exceptions.test",
    "content": "# Test cases for exceptions (compile and run)\n\n[case testException]\nfrom typing import List\ndef f(x: List[int]) -> None:\n    g(x)\n\ndef g(x: List[int]) -> bool:\n    x[5] = 2\n    return True\n\ndef r1() -> None:\n    q1()\n\ndef q1() -> None:\n    raise Exception(\"test\")\n\ndef r2() -> None:\n    q2()\n\ndef q2() -> None:\n    raise Exception\n\nclass A:\n    def __init__(self) -> None:\n        raise Exception\n\ndef hey() -> None:\n    A()\n\n[file driver.py]\nfrom native import f, r1, r2, hey\nimport traceback\ntry:\n    f([])\nexcept IndexError:\n    traceback.print_exc()\ntry:\n    r1()\nexcept Exception:\n    traceback.print_exc()\ntry:\n    r2()\nexcept Exception:\n    traceback.print_exc()\ntry:\n    hey()\nexcept Exception:\n    traceback.print_exc()\n[out]\nTraceback (most recent call last):\n  File \"driver.py\", line 4, in <module>\n    f([])\n  File \"native.py\", line 3, in f\n    g(x)\n  File \"native.py\", line 6, in g\n    x[5] = 2\nIndexError: list assignment index out of range\nTraceback (most recent call last):\n  File \"driver.py\", line 8, in <module>\n    r1()\n  File \"native.py\", line 10, in r1\n    q1()\n  File \"native.py\", line 13, in q1\n    raise Exception(\"test\")\nException: test\nTraceback (most recent call last):\n  File \"driver.py\", line 12, in <module>\n    r2()\n  File \"native.py\", line 16, in r2\n    q2()\n  File \"native.py\", line 19, in q2\n    raise Exception\nException\nTraceback (most recent call last):\n  File \"driver.py\", line 16, in <module>\n    hey()\n  File \"native.py\", line 26, in hey\n    A()\n  File \"native.py\", line 23, in __init__\n    raise Exception\nException\n[out version>=3.13]\nTraceback (most recent call last):\n  File \"driver.py\", line 4, in <module>\n    f([])\n    ~^^^^\n  File \"native.py\", line 3, in f\n    g(x)\n  File \"native.py\", line 6, in g\n    x[5] = 2\nIndexError: list assignment index out of range\nTraceback (most recent call last):\n  File \"driver.py\", line 8, in <module>\n    r1()\n    ~~^^\n  File \"native.py\", line 10, in r1\n    q1()\n  File \"native.py\", line 13, in q1\n    raise Exception(\"test\")\nException: test\nTraceback (most recent call last):\n  File \"driver.py\", line 12, in <module>\n    r2()\n    ~~^^\n  File \"native.py\", line 16, in r2\n    q2()\n  File \"native.py\", line 19, in q2\n    raise Exception\nException\nTraceback (most recent call last):\n  File \"driver.py\", line 16, in <module>\n    hey()\n    ~~~^^\n  File \"native.py\", line 26, in hey\n    A()\n  File \"native.py\", line 23, in __init__\n    raise Exception\nException\n\n[case testTryExcept]\nfrom typing import Any, Iterator\nimport wrapsys\ndef g(b: bool) -> None:\n    try:\n        if b:\n            x = [0]\n            x[1]\n        else:\n            raise Exception('hi')\n    except:\n        print(\"caught!\")\n\ndef r(x: int) -> None:\n    if x == 0:\n        [0][1]\n    elif x == 1:\n        raise Exception('hi')\n    elif x == 2:\n        {1: 1}[0]\n    elif x == 3:\n        a = object()  # type: Any\n        a.lol\n\ndef f(b: bool) -> None:\n    try:\n        r(int(b))\n    except AttributeError:\n        print('no')\n    except:\n        print(str(wrapsys.exc_info()[1]))\n    print(str(wrapsys.exc_info()[1]))\n\ndef h() -> None:\n    while True:\n        try:\n            raise Exception('gonna break')\n        except:\n            print(str(wrapsys.exc_info()[1]))\n            break\n    print(str(wrapsys.exc_info()[1]))\n\ndef i() -> None:\n    try:\n        r(0)\n    except:\n        print(type(wrapsys.exc_info()[1]))\n        raise\n\ndef j(n: int) -> None:\n    try:\n        r(n)\n    except (IndexError, KeyError):\n        print(\"lookup!\")\n    except AttributeError as e:\n        print(\"attr! --\", e)\n\ndef k() -> None:\n    try:\n        r(1)\n    except:\n        r(0)\n\ndef l() -> None:\n    try:\n        r(0)\n    except IndexError:\n        try:\n            r(2)\n        except KeyError as e:\n            print(\"key! --\", e)\n\ndef m(x: object) -> int:\n    try:\n        st = id(x)\n    except Exception:\n        return -1\n    return st + 1\n\ndef iter_exception() -> Iterator[str]:\n    try:\n        r(0)\n    except KeyError as e:\n        yield 'lol'\n\n[file wrapsys.py]\n# This is a gross hack around some limitations of the test system/mypyc.\nfrom typing import Any\nimport sys\ndef exc_info() -> Any:\n    return sys.exc_info()  # type: ignore\n\n[file driver.py]\nimport sys, traceback\nfrom native import g, f, h, i, j, k, l, m, iter_exception\nfrom testutil import assertRaises\nprint(\"== i ==\")\ntry:\n    i()\nexcept:\n    traceback.print_exc(file=sys.stdout)\n\nprint(\"== k ==\")\ntry:\n    k()\nexcept:\n    traceback.print_exc(file=sys.stdout)\n\nprint(\"== g ==\")\ng(True)\ng(False)\n\nprint(\"== f ==\")\nf(True)\nf(False)\n\nprint(\"== h ==\")\nh()\n\nprint(\"== j ==\")\nj(0)\nj(2)\nj(3)\ntry:\n    j(1)\nexcept:\n    print(\"out!\")\n\nprint(\"== l ==\")\nl()\n\nm('lol')\n\nwith assertRaises(IndexError):\n    list(iter_exception())\n\n[out]\n== i ==\n<class 'IndexError'>\nTraceback (most recent call last):\n  File \"driver.py\", line 6, in <module>\n    i()\n  File \"native.py\", line 44, in i\n    r(0)\n  File \"native.py\", line 15, in r\n    [0][1]\nIndexError: list index out of range\n== k ==\nTraceback (most recent call last):\n  File \"native.py\", line 59, in k\n    r(1)\n  File \"native.py\", line 17, in r\n    raise Exception('hi')\nException: hi\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"driver.py\", line 12, in <module>\n    k()\n  File \"native.py\", line 61, in k\n    r(0)\n  File \"native.py\", line 15, in r\n    [0][1]\nIndexError: list index out of range\n== g ==\ncaught!\ncaught!\n== f ==\nhi\nNone\nlist index out of range\nNone\n== h ==\ngonna break\nNone\n== j ==\nlookup!\nlookup!\nattr! -- 'object' object has no attribute 'lol'\nout!\n== l ==\nkey! -- 0\n[out version>=3.13]\n== i ==\n<class 'IndexError'>\nTraceback (most recent call last):\n  File \"driver.py\", line 6, in <module>\n    i()\n    ~^^\n  File \"native.py\", line 44, in i\n    r(0)\n  File \"native.py\", line 15, in r\n    [0][1]\nIndexError: list index out of range\n== k ==\nTraceback (most recent call last):\n  File \"native.py\", line 59, in k\n    r(1)\n  File \"native.py\", line 17, in r\n    raise Exception('hi')\nException: hi\n\nDuring handling of the above exception, another exception occurred:\n\nTraceback (most recent call last):\n  File \"driver.py\", line 12, in <module>\n    k()\n    ~^^\n  File \"native.py\", line 61, in k\n    r(0)\n  File \"native.py\", line 15, in r\n    [0][1]\nIndexError: list index out of range\n== g ==\ncaught!\ncaught!\n== f ==\nhi\nNone\nlist index out of range\nNone\n== h ==\ngonna break\nNone\n== j ==\nlookup!\nlookup!\nattr! -- 'object' object has no attribute 'lol'\nout!\n== l ==\nkey! -- 0\n\n[case testTryFinally]\nfrom typing import Any\nimport wrapsys\n\ndef a(b1: bool, b2: int) -> None:\n    try:\n        if b1:\n            raise Exception('hi')\n    finally:\n        print('finally:', str(wrapsys.exc_info()[1]))\n        if b2 == 2:\n            return\n        if b2 == 1:\n            raise Exception('again!')\n\ndef b(b1: int, b2: int) -> str:\n    try:\n        if b1 == 1:\n            raise Exception('hi')\n        elif b1 == 2:\n            [0][1]\n        elif b1 == 3:\n            return 'try'\n    except IndexError:\n        print('except')\n    finally:\n        print('finally:', str(wrapsys.exc_info()[1]))\n        if b2 == 2:\n            return 'finally'\n        if b2 == 1:\n            raise Exception('again!')\n    return 'outer'\n\ndef c() -> str:\n    try:\n        try:\n            return 'wee'\n        finally:\n            print(\"out a\")\n    finally:\n        print(\"out b\")\n\n\n[file wrapsys.py]\n# This is a gross hack around some limitations of the test system/mypyc.\nfrom typing import Any\nimport sys\ndef exc_info() -> Any:\n    return sys.exc_info()  # type: ignore\n\n[file driver.py]\nimport traceback\nimport sys\nfrom native import a, b, c\n\ndef run(f):\n    try:\n        x = f()\n        if x:\n            print(\"returned:\", x)\n    except Exception as e:\n        print(\"caught:\", type(e).__name__ + \": \" + str(e))\n\nprint(\"== a ==\")\nfor i in range(3):\n    for b1 in [False, True]:\n        run(lambda: a(b1, i))\n\nprint(\"== b ==\")\nfor i in range(4):\n    for j in range(3):\n        run(lambda: b(i, j))\n\nprint(\"== b ==\")\nprint(c())\n\n[out]\n== a ==\nfinally: None\nfinally: hi\ncaught: Exception: hi\nfinally: None\ncaught: Exception: again!\nfinally: hi\ncaught: Exception: again!\nfinally: None\nfinally: hi\n== b ==\nfinally: None\nreturned: outer\nfinally: None\ncaught: Exception: again!\nfinally: None\nreturned: finally\nfinally: hi\ncaught: Exception: hi\nfinally: hi\ncaught: Exception: again!\nfinally: hi\nreturned: finally\nexcept\nfinally: None\nreturned: outer\nexcept\nfinally: None\ncaught: Exception: again!\nexcept\nfinally: None\nreturned: finally\nfinally: None\nreturned: try\nfinally: None\ncaught: Exception: again!\nfinally: None\nreturned: finally\n== b ==\nout a\nout b\nwee\n\n[case testCustomException]\nfrom typing import List\n\nclass ListOutOfBounds(IndexError):\n    pass\n\nclass UserListWarning(UserWarning):\n    pass\n\ndef f(l: List[int], k: int) -> int:\n    try:\n        return l[k]\n    except IndexError:\n        raise ListOutOfBounds(\"Ruh-roh from f!\")\n\ndef g(l: List[int], k: int) -> int:\n    try:\n        return f([1,2,3], 3)\n    except ListOutOfBounds:\n        raise ListOutOfBounds(\"Ruh-roh from g!\")\n\ndef k(l: List[int], k: int) -> int:\n    try:\n        return g([1,2,3], 3)\n    except IndexError:\n        raise UserListWarning(\"Ruh-roh from k!\")\n\ndef h() -> int:\n    try:\n        return k([1,2,3], 3)\n    except UserWarning:\n        return -1\n\n[file driver.py]\nfrom native import h\nassert h() == -1\n\n[case testExceptionAtModuleTopLevel]\nfrom typing import Any\n\ndef f(x: int) -> None: pass\n\ny: Any = ''\nf(y)\n\n[file driver.py]\nimport traceback\ntry:\n    import native\nexcept TypeError:\n    traceback.print_exc()\nelse:\n    assert False\n\n[out]\nTraceback (most recent call last):\n  File \"driver.py\", line 3, in <module>\n    import native\n  File \"native.py\", line 6, in <module>\n    f(y)\nTypeError: int object expected; got str\n"
  },
  {
    "path": "mypyc/test-data/run-floats.test",
    "content": "# Test cases for floats (compile and run)\n\n[case testFloatOps]\nfrom __future__ import annotations\nfrom typing import Final, Any, cast\nfrom testutil import assertRaises, float_vals, FLOAT_MAGIC\nimport math\n\ndef test_arithmetic() -> None:\n    zero = float(0.0)\n    one = zero + 1.0\n    x = one + one / 2.0\n    assert x == 1.5\n    assert x - one == 0.5\n    assert x * x == 2.25\n    assert x / 2.0 == 0.75\n    assert x * (-0.5) == -0.75\n    assert -x == -1.5\n    for x in float_vals:\n        assert repr(-x) == repr(getattr(x, \"__neg__\")())\n\n        for y in float_vals:\n            assert repr(x + y) == repr(getattr(x, \"__add__\")(y))\n            assert repr(x - y) == repr(getattr(x, \"__sub__\")(y))\n            assert repr(x * y) == repr(getattr(x, \"__mul__\")(y))\n            if y != 0:\n                assert repr(x / y) == repr(getattr(x, \"__truediv__\")(y))\n\ndef test_mod() -> None:\n    zero = float(0.0)\n    one = zero + 1.0\n    x = one + one / 2.0\n    assert x % 0.4 == 0.29999999999999993\n    assert (-x) % 0.4 == 0.10000000000000009\n    assert x % -0.4 == -0.10000000000000009\n    assert (-x) % -0.4 == -0.29999999999999993\n    for x in float_vals:\n        for y in float_vals:\n            if y != 0:\n                assert repr(x % y) == repr(getattr(x, \"__mod__\")(y))\n\ndef test_floor_div() -> None:\n    for x in float_vals:\n        for y in float_vals:\n            if y != 0:\n                assert repr(x // y) == repr(getattr(x, \"__floordiv__\")(y))\n            else:\n                with assertRaises(ZeroDivisionError, \"float floor division by zero\"):\n                    x // y\n\ndef test_mixed_arithmetic() -> None:\n    zf = float(0.0)\n    zn = int()\n    assert (zf + 5.5) + (zn + 1) == 6.5\n    assert (zn - 2) - (zf - 5.5) == 3.5\n    x = zf + 3.4\n    x += zn + 2\n    assert x == 5.4\n\ndef test_arithmetic_errors() -> None:\n    zero = float(0.0)\n    one = zero + 1.0\n    with assertRaises(ZeroDivisionError, \"float division by zero\"):\n        print(one / zero)\n    with assertRaises(ZeroDivisionError, \"float modulo\"):\n        print(one % zero)\n\ndef test_comparisons() -> None:\n    zero = float(0.0)\n    one = zero + 1.0\n    x = one + one / 2.0\n    assert x < (1.51 + zero)\n    assert not (x < (1.49 + zero))\n    assert x > (1.49 + zero)\n    assert not (x > (1.51 + zero))\n    assert x <= (1.5 + zero)\n    assert not (x <= (1.49 + zero))\n    assert x >= (1.5 + zero)\n    assert not (x >= (1.51 + zero))\n    for x in float_vals:\n        for y in float_vals:\n            assert (x <= y) == getattr(x, \"__le__\")(y)\n            assert (x < y) == getattr(x, \"__lt__\")(y)\n            assert (x >= y) == getattr(x, \"__ge__\")(y)\n            assert (x > y) == getattr(x, \"__gt__\")(y)\n            assert (x == y) == getattr(x, \"__eq__\")(y)\n            assert (x != y) == getattr(x, \"__ne__\")(y)\n\ndef test_mixed_comparisons() -> None:\n    zf = float(0.0)\n    zn = int()\n    if (zf + 1.0) == (zn + 1):\n        assert True\n    else:\n        assert False\n    if (zf + 1.1) == (zn + 1):\n        assert False\n    else:\n        assert True\n    assert (zf + 1.1) != (zn + 1)\n    assert (zf + 1.1) > (zn + 1)\n    assert not (zf + 0.9) > (zn + 1)\n    assert (zn + 1) < (zf + 1.1)\n\ndef test_boxing_and_unboxing() -> None:\n    x = 1.5\n    boxed: Any = x\n    assert repr(boxed) == \"1.5\"\n    assert type(boxed) is float\n    y: float = boxed\n    assert y == x\n    boxed_int: Any = 5\n    assert [type(boxed_int)] == [int]  # Avoid mypy type narrowing\n    z: float = boxed_int\n    assert z == 5.0\n    for xx in float_vals:\n        bb: Any = xx\n        yy: float = bb\n        assert repr(xx) == repr(bb)\n        assert repr(xx) == repr(yy)\n    for b in True, False:\n        boxed_bool: Any = b\n        assert type(boxed_bool) is bool\n        zz: float = boxed_bool\n        assert zz == int(b)\n\ndef test_unboxing_failure() -> None:\n    boxed: Any = '1.5'\n    with assertRaises(TypeError):\n        x: float = boxed\n\ndef identity(x: float) -> float:\n    return x\n\ndef test_coerce_from_int_literal() -> None:\n    assert identity(34) == 34.0\n    assert identity(-1) == -1.0\n\ndef test_coerce_from_short_tagged_int() -> None:\n    n = int() - 17\n    assert identity(n) == -17.0\n    for i in range(-300, 300):\n        assert identity(i) == float(i)\n\ndef test_coerce_from_long_tagged_int() -> None:\n    n = int() + 2**100\n    x = identity(n)\n    assert repr(x) == '1.2676506002282294e+30'\n    n = int() - 2**100\n    y = identity(n)\n    assert repr(y) == '-1.2676506002282294e+30'\n\ndef test_coerce_from_very_long_tagged_int() -> None:\n    n = int() + 10**1000\n    with assertRaises(OverflowError, \"int too large to convert to float\"):\n        identity(n)\n    with assertRaises(OverflowError, \"int too large to convert to float\"):\n        identity(int(n))\n    n = int() - 10**1000\n    with assertRaises(OverflowError, \"int too large to convert to float\"):\n        identity(n)\n    with assertRaises(OverflowError, \"int too large to convert to float\"):\n        identity(int(n))\n\ndef test_explicit_conversion_from_int() -> None:\n    float_any: Any = float\n    a = [0, 1, 2, 3, -1, -2, 13257, -928745]\n    for n in range(1, 100):\n        for delta in -1, 0, 1, 2342345:\n            a.append(2**n + delta)\n            a.append(-2**n + delta)\n    for x in a:\n        assert repr(float(x)) == repr(float_any(x))\n\ndef test_explicit_conversion_to_int() -> None:\n    int_any: Any = int\n    for x in float_vals:\n        if math.isinf(x):\n            with assertRaises(OverflowError, \"cannot convert float infinity to integer\"):\n                int(x)\n        elif math.isnan(x):\n            with assertRaises(ValueError, \"cannot convert float NaN to integer\"):\n                int(x)\n        else:\n            assert repr(int(x)) == repr(int_any(x))\n\n    # Test some edge cases\n    assert 2**30 == int(2.0**30 + int())\n    assert 2**30 - 1 == int(1073741823.9999999 + int())  # math.nextafter(2.0**30, 0))\n    assert -2**30 - 1 == int(-2.0**30 - 1 + int())\n    assert -2**30 == int(-1073741824.9999998 + int())  # math.nextafter(-2.0**30 - 1, 0)\n    assert 2**62 == int(2.0**62 + int())\n    assert 2**62 == int(2.0**62 - 1 + int())\n    assert -2**62 == int(-2.0**62 + int())\n    assert -2**62 == int(-2.0**62 - 1 + int())\n\ndef str_to_float(x: str) -> float:\n    return float(x)\n\ndef test_str_to_float() -> None:\n    assert str_to_float(\"1\") == 1.0\n    assert str_to_float(\"1.234567\") == 1.234567\n    assert str_to_float(\"44324\") == 44324.0\n    assert str_to_float(\"23.4\") == 23.4\n    assert str_to_float(\"-43.44e-4\") == -43.44e-4\n    assert str_to_float(\"-43.44e-4\") == -43.44e-4\n    assert math.isinf(str_to_float(\"inf\"))\n    assert math.isinf(str_to_float(\"-inf\"))\n    assert str_to_float(\"inf\") > 0.0\n    assert str_to_float(\"-inf\") < 0.0\n    assert math.isnan(str_to_float(\"nan\"))\n    assert math.isnan(str_to_float(\"NaN\"))\n    assert repr(str_to_float(\"-0.0\")) == \"-0.0\"\n\ndef test_abs() -> None:\n    assert abs(0.0) == 0.0\n    assert abs(-1.234567) == 1.234567\n    assert abs(44324.732) == 44324.732\n    assert abs(-23.4) == 23.4\n    assert abs(-43.44e-4) == 43.44e-4\n    abs_any: Any = abs\n    for x in float_vals:\n        assert repr(abs(x)) == repr(abs_any(x))\n\ndef test_float_min_max() -> None:\n    for x in float_vals:\n        for y in float_vals:\n            min_any: Any = min\n            assert repr(min(x, y)) == repr(min_any(x, y))\n            max_any: Any = max\n            assert repr(max(x, y)) == repr(max_any(x, y))\n\ndef default(x: float = 2) -> float:\n    return x + 1\n\ndef test_float_default_value() -> None:\n    assert default(1.2) == 2.2\n    for i in range(-200, 200):\n        assert default(float(i)) == i + 1\n    assert default() == 3.0\n\ndef test_float_default_value_wrapper() -> None:\n    f: Any = default\n    assert f(1.2) == 2.2\n    for i in range(-200, 200):\n        assert f(float(i)) == i + 1\n    assert f() == 3.0\n\nclass C:\n    def __init__(self, x: float) -> None:\n        self.x = x\n\ndef test_float_attr() -> None:\n    for i in range(-200, 200):\n        f = float(i)\n        c = C(f)\n        assert c.x == f\n        a: Any = c\n        assert a.x == f\n        c.x = FLOAT_MAGIC\n        assert c.x == FLOAT_MAGIC\n        assert a.x == FLOAT_MAGIC\n        a.x = 1.0\n        assert a.x == 1.0\n        a.x = FLOAT_MAGIC\n        assert a.x == FLOAT_MAGIC\n\nclass D:\n    def __init__(self, x: float) -> None:\n        if x:\n            self.x = x\n\ndef test_float_attr_maybe_undefned() -> None:\n    for i in range(-200, 200):\n        if i == 0:\n            d = D(0.0)\n            with assertRaises(AttributeError):\n                d.x\n            a: Any = d\n            with assertRaises(AttributeError):\n                a.x\n            d.x = FLOAT_MAGIC\n            assert d.x == FLOAT_MAGIC\n            assert a.x == FLOAT_MAGIC\n            d.x = 0.0\n            assert d.x == 0.0\n            assert a.x == 0.0\n            a.x = FLOAT_MAGIC\n            assert a.x == FLOAT_MAGIC\n            d = D(0.0)\n            a = cast(Any, d)\n            a.x = FLOAT_MAGIC\n            assert d.x == FLOAT_MAGIC\n        else:\n            f = float(i)\n            d = D(f)\n            assert d.x == f\n            a2: Any = d\n            assert a2.x == f\n\ndef f(x: float) -> float:\n    return x + 1\n\ndef test_return_values() -> None:\n    a: Any = f\n    for i in range(-200, 200):\n        x = float(i)\n        assert f(x) == x + 1\n        assert a(x) == x + 1\n    for x in float_vals:\n        if not math.isnan(x):\n            assert f(x) == x + 1\n        else:\n            assert math.isnan(f(x))\n\ndef exc() -> float:\n    raise IndexError('x')\n\ndef test_exception() -> None:\n    with assertRaises(IndexError):\n        exc()\n    a: Any = exc\n    with assertRaises(IndexError):\n        a()\n\ndef test_undefined_local_var() -> None:\n    if not int():\n        x = -113.0\n    assert x == -113.0\n    if int():\n        y = -113.0\n    with assertRaises(UnboundLocalError, 'local variable \"y\" referenced before assignment'):\n        print(y)\n    if not int():\n        x2 = -1.0\n    assert x2 == -1.0\n    if int():\n        y2 = -1.0\n    with assertRaises(UnboundLocalError, 'local variable \"y2\" referenced before assignment'):\n        print(y2)\n\ndef test_tuples() -> None:\n    t1: tuple[float, float] = (1.5, 2.5)\n    assert t1 == tuple([1.5, 2.5])\n    n = int() + 5\n    t2: tuple[float, float, float, float] = (n, 1.5, -7, -113)\n    assert t2 == tuple([5.0, 1.5, -7.0, -113.0])\n\n[case testFloatGlueMethodsAndInheritance]\nfrom typing import Final, Any\n\nfrom mypy_extensions import trait\n\nfrom testutil import assertRaises\n\nMAGIC: Final = -113.0\n\nclass Base:\n    def foo(self) -> float:\n        return 5.0\n\n    def bar(self, x: float = 2.0) -> float:\n        return x + 1\n\n    def hoho(self, x: float) -> float:\n        return x - 1\n\nclass Derived(Base):\n    def foo(self, x: float = 5.0) -> float:\n        return x + 10\n\n    def bar(self, x: float = 3, y: float = 20) -> float:\n        return x + y + 2\n\n    def hoho(self, x: float = 7) -> float:\n        return x - 2\n\ndef test_derived_adds_bitmap() -> None:\n    b: Base = Derived()\n    assert b.foo() == 15\n\ndef test_derived_adds_another_default_arg() -> None:\n    b: Base = Derived()\n    assert b.bar() == 25\n    assert b.bar(1) == 23\n    assert b.bar(MAGIC) == MAGIC + 22\n\ndef test_derived_switches_arg_to_have_default() -> None:\n    b: Base = Derived()\n    assert b.hoho(5) == 3\n    assert b.hoho(MAGIC) == MAGIC - 2\n\n@trait\nclass T:\n    @property\n    def x(self) -> float: ...\n    @property\n    def y(self) -> float: ...\n\nclass C(T):\n    x: float = 1.0\n    y: float = 4\n\ndef test_read_only_property_in_trait_implemented_as_attribute() -> None:\n    c = C()\n    c.x = 5.5\n    assert c.x == 5.5\n    c.x = MAGIC\n    assert c.x == MAGIC\n    assert c.y == 4\n    c.y = 6.5\n    assert c.y == 6.5\n    t: T = C()\n    assert t.y == 4\n    t = c\n    assert t.x == MAGIC\n    c.x = 55.5\n    assert t.x == 55.5\n    assert t.y == 6.5\n    a: Any = c\n    assert a.x == 55.5\n    assert a.y == 6.5\n    a.x = 7.0\n    a.y = 8.0\n    assert a.x == 7\n    assert a.y == 8\n\nclass D(T):\n    xx: float\n\n    @property\n    def x(self) -> float:\n        return self.xx\n\n    @property\n    def y(self) -> float:\n        raise TypeError\n\ndef test_read_only_property_in_trait_implemented_as_property() -> None:\n    d = D()\n    d.xx = 5.0\n    assert d.x == 5\n    d.xx = MAGIC\n    assert d.x == MAGIC\n    with assertRaises(TypeError):\n        d.y\n    t: T = d\n    assert t.x == MAGIC\n    d.xx = 6.0\n    assert t.x == 6\n    with assertRaises(TypeError):\n        t.y\n\n@trait\nclass T2:\n    x: float\n    y: float\n\nclass C2(T2):\n    pass\n\ndef test_inherit_trait_attribute() -> None:\n    c = C2()\n    c.x = 5.0\n    assert c.x == 5\n    c.x = MAGIC\n    assert c.x == MAGIC\n    with assertRaises(AttributeError):\n        c.y\n    c.y = 6.0\n    assert c.y == 6.0\n    t: T2 = C2()\n    with assertRaises(AttributeError):\n        t.y\n    t = c\n    assert t.x == MAGIC\n    c.x = 55.0\n    assert t.x == 55\n    assert t.y == 6\n    a: Any = c\n    assert a.x == 55\n    assert a.y == 6\n    a.x = 7.0\n    a.y = 8.0\n    assert a.x == 7\n    assert a.y == 8\n\nclass D2(T2):\n    x: float\n    y: float = 4\n\ndef test_implement_trait_attribute() -> None:\n    d = D2()\n    d.x = 5.0\n    assert d.x == 5\n    d.x = MAGIC\n    assert d.x == MAGIC\n    assert d.y == 4\n    d.y = 6.0\n    assert d.y == 6\n    t: T2 = D2()\n    assert t.y == 4\n    t = d\n    assert t.x == MAGIC\n    d.x = 55.0\n    assert t.x == 55\n    assert t.y == 6\n    a: Any = d\n    assert a.x == 55\n    assert a.y == 6\n    a.x = 7.0\n    a.y = 8.0\n    assert a.x == 7\n    assert a.y == 8\n\n[case testIsInstance]\nfrom copysubclass import subc\nfrom testutil import float_vals\nfrom typing import Any\ndef test_built_in() -> None:\n    for f in float_vals:\n        assert isinstance(float(0) + f, float)\n        assert isinstance(subc(f), float)\n\n    assert not isinstance(set(), float)\n    assert not isinstance((), float)\n    assert not isinstance((1.0, 2.0), float)\n    assert not isinstance({3.14}, float)\n    assert not isinstance(int() + 1, float)\n    assert not isinstance(str() + '4.2', float)\n\ndef test_user_defined() -> None:\n    from userdefinedfloat import float\n\n    f: Any = 3.14\n    assert isinstance(float(), float)\n    assert not isinstance(f, float)\n\n[file copysubclass.py]\nclass subc(float):\n    pass\n\n[file userdefinedfloat.py]\nclass float:\n    pass\n"
  },
  {
    "path": "mypyc/test-data/run-functions.test",
    "content": "# Test cases for functions and calls (compile and run)\n\n[case testCallTrivialFunction]\ndef f(x: int) -> int:\n    return x\n[file driver.py]\nfrom native import f\nprint(f(3))\nprint(f(-157))\nprint(f(10**20))\nprint(f(-10**20))\n[out]\n3\n-157\n100000000000000000000\n-100000000000000000000\n\n[case testRecursiveFibonacci]\ndef fib(n: int) -> int:\n    if n <= 1:\n        return 1\n    else:\n        return fib(n - 1) + fib(n - 2)\n[file driver.py]\nfrom native import fib\nprint(fib(0))\nprint(fib(1))\nprint(fib(2))\nprint(fib(6))\n[out]\n1\n1\n2\n13\n\n[case testNestedFunctions]\nfrom typing import Callable, List\n\ndef a() -> Callable[[], object]:\n    def inner() -> object:\n        return None\n    return inner\n\ndef b() -> Callable[[], Callable[[], str]]:\n    def first() -> Callable[[], str]:\n        def second() -> str:\n            return 'b.first.second: nested function'\n        return second\n    return first\n\ndef c(num: float) -> Callable[[str], str]:\n    def inner(s: str) -> str:\n        return s + '!'\n    return inner\n\ndef d(num: float) -> str:\n    def inner(s: str) -> str:\n        return s + '?'\n    a = inner('one')\n    b = inner('two')\n    return a\n\ndef e() -> int:\n    return 0\n\ndef f() -> int:\n    def inner() -> int:\n        return e()\n    return inner()\n\ndef g() -> Callable[[], Callable[[], int]]:\n    def inner() -> Callable[[], int]:\n        return e\n    return inner\n\ndef h(num: int) -> int:\n    def inner() -> int:\n        return num\n    return inner()\n\ndef i() -> int:\n    num = 3\n    def inner() -> int:\n        return num\n    return inner()\n\ndef j(num: int) -> int:\n    x = 1\n    y = 2\n    def inner() -> int:\n        nonlocal x\n        x = 3\n        return num + x + y\n    return inner()\n\ndef k() -> int:\n    num = 3\n    def inner() -> int:\n        nonlocal num\n        num = 5\n        return num\n    return inner() + num\n\ndef l() -> int:\n    num = 3\n    def inner() -> int:\n        num = 5\n        return num\n    return inner() + num\n\ndef m() -> Callable[[], int]:\n    num = 1\n    def inner() -> int:\n        num += 1\n        return num\n    num += 1\n    return inner\n\ndef n() -> int:\n    x = 1\n    def add_one() -> None:\n        x += 1\n    def add_two() -> None:\n        x += 2\n    add_one()\n    add_two()\n    return x\n\ndef triple(a: int) -> Callable[[], Callable[[int], int]]:\n    x = 1\n    def outer() -> Callable[[int], int]:\n        nonlocal x\n        x += 1\n        x += a\n        a += 1\n        def inner(b: int) -> int:\n            x += b\n            return x\n        return inner\n    return outer\n\ndef if_else(flag: int) -> str:\n    def dummy_function() -> str:\n        return 'if_else.dummy_function'\n\n    if flag < 0:\n        def inner() -> str:\n            return 'if_else.inner: first definition'\n    elif flag > 0:\n        def inner() -> str:\n            return 'if_else.inner: second definition'\n    else:\n        def inner() -> str:\n            return 'if_else.inner: third definition'\n    return inner()\n\ndef wrap(f: Callable[[], str]):\n    def inner():\n        return 'wrapped ' + f()\n    return inner\n\ndef if_else_all_decorated(flag: int) -> str:\n    def dummy_function() -> str:\n        return 'if_else.dummy_function'\n\n    if flag < 0:\n        @wrap\n        def inner() -> str:\n            return 'if_else.inner: first definition'\n    elif flag > 0:\n        @wrap\n        def inner() -> str:\n            return 'if_else.inner: second definition'\n    else:\n        @wrap\n        def inner() -> str:\n            return 'if_else.inner: third definition'\n    return inner()\n\ndef if_else_first_decorated(flag: int) -> str:\n    def dummy_function() -> str:\n        return 'if_else.dummy_function'\n\n    if flag < 0:\n        @wrap\n        def inner() -> str:\n            return 'if_else.inner: first definition'\n    elif flag > 0:\n        def inner() -> str:\n            return 'if_else.inner: second definition'\n    else:\n        def inner() -> str:\n            return 'if_else.inner: third definition'\n    return inner()\n\ndef if_else_all_but_first_decorated(flag: int) -> str:\n    def dummy_function() -> str:\n        return 'if_else.dummy_function'\n\n    if flag < 0:\n        def inner() -> str:\n            return 'if_else.inner: first definition'\n    elif flag > 0:\n        @wrap\n        def inner() -> str:\n            return 'if_else.inner: second definition'\n    else:\n        @wrap\n        def inner() -> str:\n            return 'if_else.inner: third definition'\n    return inner()\n\ndef for_loop() -> int:\n    def dummy_function() -> str:\n        return 'for_loop.dummy_function'\n\n    for i in range(5):\n        def inner(i: int) -> int:\n            return i\n        if i == 3:\n            return inner(i)\n    return 0\n\ndef while_loop() -> int:\n    def dummy_function() -> str:\n        return 'while_loop.dummy_function'\n\n    i = 0\n    while i < 5:\n        def inner(i: int) -> int:\n            return i\n        if i == 3:\n            return inner(i)\n        i += 1\n    return 0\n\ndef free_vars(foo: int, bar: int) -> int:\n    x = 1\n    y = 2\n    def g():  # type: ignore  # missing type annotation for testing\n        nonlocal y\n        y = 3\n        nonlocal bar\n        bar += y\n    z = 3\n    g()\n    return bar\n\ndef lambdas(x: int, y: int) -> int:\n    s = lambda a, b: a + b + x + y\n    return s(1, 2)\n\ndef outer() -> str:\n    return 'outer: normal function'\n\ndef inner() -> str:\n    return 'inner: normal function'\n\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def outer(self, num: int) -> int:\n        y = 5\n        def inner() -> int:\n            return self.x + y + num\n        return inner()\n\ndef o() -> int:\n    a = [0, 0]\n    b = 0\n    def b_incr() -> List[int]:\n        b += 10\n        return a\n    c = 0\n    def c_incr() -> int:\n        c += 1\n        return c\n\n    # x = 1, y = 1\n    x = y = c_incr()\n\n    # a = [2, 2], b = 20\n    b_incr()[0] = b_incr()[1] = c_incr()\n    # Should return 26.\n    return x + y + a[0] + a[1] + b\n\nglobal_upvar = 20\n\ntoplevel_lambda = lambda x: 10 + global_upvar + x\n\n[file driver.py]\nfrom native import (\n    a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, triple, if_else, if_else_all_decorated,\n    if_else_first_decorated, if_else_all_but_first_decorated,\n    for_loop, while_loop, free_vars, lambdas, outer, inner, A, toplevel_lambda\n)\n\nassert a()() == None\nassert b()()() == 'b.first.second: nested function'\nassert c(5.0)('c') == 'c!'\nassert d(4.0) == 'one?'\nassert e() == 0\nassert f() == 0\nassert g()()() == 0\nassert h(3) == 3\nassert i() == 3\nassert j(3) == 8\nassert k() == 10\nassert l() == 8\nassert m()() == 3\nassert n() == 4\nassert o() == 26\n\ntriple_outer = triple(2)\ntriple_inner = triple_outer()\n\nassert triple_inner(4) == 8\nassert triple_inner(4) == 12\nassert triple_outer()(4) == 20\n\nassert if_else(-1) == 'if_else.inner: first definition'\nassert if_else(1) == 'if_else.inner: second definition'\nassert if_else(0) == 'if_else.inner: third definition'\n\nassert if_else_all_decorated(-1) == 'wrapped if_else.inner: first definition'\nassert if_else_all_decorated(1) == 'wrapped if_else.inner: second definition'\nassert if_else_all_decorated(0) == 'wrapped if_else.inner: third definition'\n\nassert if_else_first_decorated(-1) == 'wrapped if_else.inner: first definition'\nassert if_else_first_decorated(1) == 'if_else.inner: second definition'\nassert if_else_first_decorated(0) == 'if_else.inner: third definition'\n\nassert if_else_all_but_first_decorated(-1) == 'if_else.inner: first definition'\nassert if_else_all_but_first_decorated(1) == 'wrapped if_else.inner: second definition'\nassert if_else_all_but_first_decorated(0) == 'wrapped if_else.inner: third definition'\n\nassert for_loop() == 3\nassert while_loop() == 3\n\nassert free_vars(1, 2) == 5\nassert lambdas(3, 4) == 10\n\nassert outer() == 'outer: normal function'\nassert inner() == 'inner: normal function'\n\nassert A(3).outer(4) == 12\n\nassert toplevel_lambda(5) == 35\n\n[case testNestedFunctions2]\nfrom typing import Callable\n\ndef outer() -> Callable[[], object]:\n    def inner() -> object:\n        return None\n    return inner\n\ndef first() -> Callable[[], Callable[[], str]]:\n    def second() -> Callable[[], str]:\n        def third() -> str:\n            return 'third: nested function'\n        return third\n    return second\n\ndef f1() -> int:\n        x = 1\n        def f2() -> int:\n                y = 2\n                def f3() -> int:\n                        z = 3\n                        return y\n                return f3()\n        return f2()\n\ndef outer_func() -> int:\n    def inner_func() -> int:\n        return x\n    x = 1\n    return inner_func()\n\ndef mutual_recursion(start : int) -> int:\n    def f1(k : int) -> int:\n        if k <= 0:\n            return 0\n        k -= 1\n        return f2(k)\n\n    def f2(k : int) -> int:\n        if k <= 0:\n            return 0\n        k -= 1\n        return f1(k)\n    return f1(start)\n\ndef topLayer() -> int:\n    def middleLayer() -> int:\n        def bottomLayer() -> int:\n            return x\n\n        return bottomLayer()\n\n    x = 1\n    return middleLayer()\n\ndef nest1() -> str:\n    def nest2() -> str:\n        def nest3() -> str:\n            def mut1(val: int) -> str:\n                if val <= 0:\n                    return \"bottomed\"\n                val -= 1\n                return mut2(val)\n            def mut2(val: int) -> str:\n                if val <= 0:\n                        return \"bottomed\"\n                val -= 1\n                return mut1(val)\n            return mut1(start)\n        return nest3()\n    start = 3\n    return nest2()\n\ndef uno(num: float) -> Callable[[str], str]:\n    def dos(s: str) -> str:\n        return s + '!'\n    return dos\n\ndef eins(num: float) -> str:\n    def zwei(s: str) -> str:\n        return s + '?'\n    a = zwei('eins')\n    b = zwei('zwei')\n    return a\n\ndef call_other_inner_func(a: int) -> int:\n    def foo() -> int:\n        return a + 1\n\n    def bar() -> int:\n        return foo()\n\n    def baz(n: int) -> int:\n        if n == 0:\n            return 0\n        return n + baz(n - 1)\n\n    return bar() + baz(a)\n\ndef inner() -> str:\n    return 'inner: normal function'\n\ndef second() -> str:\n    return 'second: normal function'\n\ndef third() -> str:\n    return 'third: normal function'\n\n[file driver.py]\nfrom native import (outer, inner, first, uno, eins, call_other_inner_func,\nsecond, third, f1, outer_func, mutual_recursion, topLayer, nest1)\n\nassert outer()() == None\nassert inner() == 'inner: normal function'\nassert first()()() == 'third: nested function'\nassert uno(5.0)('uno') == 'uno!'\nassert eins(4.0) == 'eins?'\nassert call_other_inner_func(5) == 21\nassert second() == 'second: normal function'\nassert third() == 'third: normal function'\nassert f1() == 2\nassert outer_func() == 1\nassert mutual_recursion(5) == 0\nassert topLayer() == 1\nassert nest1() == \"bottomed\"\n\n[case testFunctionCallWithDefaultArgs]\nfrom typing import Tuple, List, Optional, Callable, Any\ndef f(x: int, y: int = 3, s: str = \"test\", z: object = 5) -> Tuple[int, str]:\n    def inner() -> int:\n        return x + y\n    return inner(), s\ndef g() -> None:\n    assert f(2) == (5, \"test\")\n    assert f(s = \"123\", x = -2) == (1, \"123\")\ndef h(a: Optional[object] = None, b: Optional[str] = None) -> Tuple[object, Optional[str]]:\n    return (a, b)\n\ndef same(x: object = object()) -> object:\n    return x\n\na_lambda: Callable[..., Any] = lambda n=20: n\n\ndef nested_funcs(n: int) -> List[Callable[..., Any]]:\n    ls: List[Callable[..., Any]] = []\n    for i in range(n):\n        def f(i: int = i) -> int:\n            return i\n        ls.append(f)\n    return ls\n\ndef bool_default(x: bool = False, y: bool = True) -> str:\n    return str(x) + '-' + str(y)\n\n[file driver.py]\nfrom native import f, g, h, same, nested_funcs, a_lambda, bool_default\ng()\nassert f(2) == (5, \"test\")\nassert f(s = \"123\", x = -2) == (1, \"123\")\nassert h() == (None, None)\nassert h(10) == (10, None)\nassert h(b='a') == (None, 'a')\nassert h(10, 'a') == (10, 'a')\nassert same() == same()\n\nassert [f() for f in nested_funcs(10)] == list(range(10))\n\nassert a_lambda(10) == 10\nassert a_lambda() == 20\n\nassert bool_default() == 'False-True'\nassert bool_default(True) == 'True-True'\nassert bool_default(True, False) == 'True-False'\n\n[case testMethodCallWithDefaultArgs]\nfrom typing import Tuple, List\nclass A:\n    def f(self, x: int, y: int = 3, s: str = \"test\") -> Tuple[int, str]:\n        def inner() -> int:\n            return x + y\n        return inner(), s\ndef g() -> None:\n    a = A()\n    assert a.f(2) == (5, \"test\")\n    assert a.f(s = \"123\", x = -2) == (1, \"123\")\n[file driver.py]\nfrom native import A, g\ng()\na = A()\nassert a.f(2) == (5, \"test\")\nassert a.f(s = \"123\", x = -2) == (1, \"123\")\n\n[case testMethodCallOrdering]\nclass A:\n    def __init__(self, s: str) -> None:\n        print(s)\n    def f(self, x: 'A', y: 'A') -> None:\n        pass\n\ndef g() -> None:\n    A('A!').f(A('hello'), A('world'))\n[file driver.py]\nfrom native import g\ng()\n[out]\nA!\nhello\nworld\n\n[case testPyMethodCall]\nfrom typing import List\ndef f(x: List[int]) -> int:\n    return x.pop()\ndef g(x: List[int], y: List[int]) -> None:\n    x.extend(y)\n[file driver.py]\nfrom native import f, g\nl = [1, 2]\nassert f(l) == 2\ng(l, [10])\nassert l == [1, 10]\nassert f(l) == 10\nassert f(l) == 1\ng(l, [11, 12])\nassert l == [11, 12]\n\n[case testMethodCallWithKeywordArgs]\nfrom typing import Tuple\nimport testmodule\nclass A:\n    def echo(self, a: int, b: int, c: int) -> Tuple[int, int, int]:\n        return a, b, c\ndef test_native_method_call_with_kwargs() -> None:\n    a = A()\n    assert a.echo(1, c=3, b=2) == (1, 2, 3)\n    assert a.echo(c = 3, a = 1, b = 2) == (1, 2, 3)\ndef test_module_method_call_with_kwargs() -> None:\n    a = testmodule.A()\n    assert a.echo(1, c=3, b=2) == (1, 2, 3)\n    assert a.echo(c = 3, a = 1, b = 2) == (1, 2, 3)\n[file testmodule.py]\nfrom typing import Tuple\nclass A:\n    def echo(self, a: int, b: int, c: int) -> Tuple[int, int, int]:\n        return a, b, c\n[file driver.py]\nimport native\nnative.test_native_method_call_with_kwargs()\nnative.test_module_method_call_with_kwargs()\n\n[case testAnyCall]\nfrom typing import Any\ndef call(f: Any) -> Any:\n    return f(1, 'x')\n[file driver.py]\nfrom native import call\ndef f(x, y):\n    return (x, y)\ndef g(x): pass\n\nassert call(f) == (1, 'x')\nfor bad in g, 1:\n    try:\n        call(bad)\n    except TypeError:\n        pass\n    else:\n        assert False, bad\n\n[case testCallableTypes]\nfrom typing import Callable\ndef absolute_value(x: int) -> int:\n    return x if x > 0 else -x\n\ndef call_native_function(x: int) -> int:\n    return absolute_value(x)\n\ndef call_python_function(x: int) -> int:\n    return int(x)\n\ndef return_float() -> float:\n    return 5.0\n\ndef return_callable_type() -> Callable[[], float]:\n    return return_float\n\ndef call_callable_type() -> float:\n    f = return_callable_type()\n    return f()\n\ndef return_passed_in_callable_type(f: Callable[[], float]) -> Callable[[], float]:\n    return f\n\ndef call_passed_in_callable_type(f: Callable[[], float]) -> float:\n    return f()\n\n[file driver.py]\nfrom native import call_native_function, call_python_function, return_float, return_callable_type, call_callable_type, return_passed_in_callable_type, call_passed_in_callable_type\na = call_native_function(1)\nb = call_python_function(1)\nc = return_callable_type()\nd = call_callable_type()\ne = return_passed_in_callable_type(return_float)\nf = call_passed_in_callable_type(return_float)\nassert a == 1\nassert b == 1\nassert c() == 5.0\nassert d == 5.0\nassert e() == 5.0\nassert f == 5.0\n\n[case testKeywordArgs]\nfrom typing import Tuple\nimport testmodule\n\ndef g(a: int, b: int, c: int) -> Tuple[int, int, int]:\n    return a, b, c\n\ndef test_call_native_function_with_keyword_args() -> None:\n    assert g(1, c = 3, b = 2) == (1, 2, 3)\n    assert g(c = 3, a = 1, b = 2) == (1, 2, 3)\n\ndef test_call_module_function_with_keyword_args() -> None:\n    assert testmodule.g(1, c = 3, b = 2) == (1, 2, 3)\n    assert testmodule.g(c = 3, a = 1, b = 2) == (1, 2, 3)\n\ndef test_call_python_function_with_keyword_args() -> None:\n    assert int(\"11\", base=2) == 3\n\ndef test_call_lambda_function_with_keyword_args() -> None:\n    g = testmodule.get_lambda_function()\n    assert g(1, c = 3, b = 2) == (1, 2, 3)\n    assert g(c = 3, a = 1, b = 2) == (1, 2, 3)\n\n[file testmodule.py]\nfrom typing import Tuple\n\ndef g(a: int, b: int, c: int) -> Tuple[int, int, int]:\n    return a, b, c\n\ndef get_lambda_function():\n    return (lambda a, b, c: (a, b, c))\n\n[file driver.py]\nimport native\nnative.test_call_native_function_with_keyword_args()\nnative.test_call_module_function_with_keyword_args()\nnative.test_call_python_function_with_keyword_args()\nnative.test_call_lambda_function_with_keyword_args()\n\n[case testStarArgs]\nfrom typing import Tuple\n\ndef g(a: int, b: int, c: int) -> Tuple[int, int, int]:\n    return a, b, c\n\ndef test_star_args() -> None:\n    assert g(*[1, 2, 3]) == (1, 2, 3)\n    assert g(*(1, 2, 3)) == (1, 2, 3)\n    assert g(*(1,), *[2, 3]) == (1, 2, 3)\n    assert g(*(), *(1,), *(), *(2,), *(3,), *()) == (1, 2, 3)\n    assert g(*range(3)) == (0, 1, 2)\n\n[file driver.py]\nimport native\nnative.test_star_args()\n\n[case testStar2Args]\nfrom typing import Tuple\n\ndef g(a: int, b: int, c: int) -> Tuple[int, int, int]:\n    return a, b, c\n\ndef test_star2_args() -> None:\n    assert g(**{'a': 1, 'b': 2, 'c': 3}) == (1, 2, 3)\n    assert g(**{'c': 3, 'a': 1, 'b': 2}) == (1, 2, 3)\n    assert g(b=2, **{'a': 1, 'c': 3}) == (1, 2, 3)\n\ndef test_star2_args_bad(v: dict) -> bool:\n    return g(a=1, b=2, **v) == (1, 2, 3)\n[file driver.py]\nimport native\nnative.test_star2_args()\n\n# this should raise TypeError due to duplicate kwarg, but currently it doesn't\nassert native.test_star2_args_bad({'b': 2, 'c': 3})\n\n[case testStarAndStar2Args]\nfrom typing import Tuple\ndef g(a: int, b: int, c: int) -> Tuple[int, int, int]:\n    return a, b, c\n\nclass C:\n    def g(self, a: int, b: int, c: int) -> Tuple[int, int, int]:\n        return a, b, c\n\ndef test_star_and_star2_args() -> None:\n    assert g(1, *(2,), **{'c': 3}) == (1, 2, 3)\n    assert g(*[1], **{'b': 2, 'c': 3}) == (1, 2, 3)\n    c = C()\n    assert c.g(1, *(2,), **{'c': 3}) == (1, 2, 3)\n    assert c.g(*[1], **{'b': 2, 'c': 3}) == (1, 2, 3)\n\n[file driver.py]\nimport native\nnative.test_star_and_star2_args()\n\n[case testAllTheArgCombinations]\nfrom typing import Tuple\ndef g(a: int, b: int, c: int, d: int = -1) -> Tuple[int, int, int, int]:\n    return a, b, c, d\n\nclass C:\n    def g(self, a: int, b: int, c: int, d: int = -1) -> Tuple[int, int, int, int]:\n        return a, b, c, d\n\ndef test_all_the_arg_combinations() -> None:\n    assert g(1, *(2,), **{'c': 3}) == (1, 2, 3, -1)\n    assert g(*[1], **{'b': 2, 'c': 3, 'd': 4}) == (1, 2, 3, 4)\n    c = C()\n    assert c.g(1, *(2,), **{'c': 3}) == (1, 2, 3, -1)\n    assert c.g(*[1], **{'b': 2, 'c': 3, 'd': 4}) == (1, 2, 3, 4)\n\n[file driver.py]\nimport native\nnative.test_all_the_arg_combinations()\n\n[case testOverloads]\nfrom typing import overload, Union, Tuple\n\n@overload\ndef foo(x: int) -> int: ...\n\n@overload\ndef foo(x: str) -> str: ...\n\ndef foo(x: Union[int, str]) -> Union[int, str]:\n    return x\n\nclass A:\n    @overload\n    def foo(self, x: int) -> int: ...\n\n    @overload\n    def foo(self, x: str) -> str: ...\n\n    def foo(self, x: Union[int, str]) -> Union[int, str]:\n        return x\n\ndef call1() -> Tuple[int, str]:\n    return (foo(10), foo('10'))\ndef call2() -> Tuple[int, str]:\n    x = A()\n    return (x.foo(10), x.foo('10'))\n\n[file driver.py]\nfrom native import *\nassert call1() == (10, '10')\nassert call2() == (10, '10')\n\n[case testDecorators1]\nfrom typing import Generator, Callable, Iterator\nfrom contextlib import contextmanager\n\ndef a(f: Callable[[], None]) -> Callable[[], None]:\n    def g() -> None:\n        print('Entering')\n        f()\n        print('Exited')\n    return g\n\ndef b(f: Callable[[], None]) -> Callable[[], None]:\n    def g() -> None:\n        print('***')\n        f()\n        print('***')\n    return g\n\n@contextmanager\ndef foo() -> Iterator[int]:\n    try:\n        print('started')\n        yield 0\n    finally:\n        print('finished')\n\n@contextmanager\ndef catch() -> Iterator[None]:\n    try:\n        print('started')\n        yield\n    except IndexError:\n        print('index')\n        raise\n    except Exception:\n        print('lol')\n\ndef thing() -> None:\n    c()\n\n@a\n@b\ndef c() -> None:\n    @a\n    @b\n    def d() -> None:\n        print('d')\n    print('c')\n    d()\n\ndef hm() -> None:\n    x = [1]\n    with catch():\n        x[2]\n\n[file driver.py]\nfrom native import foo, c, thing, hm\n\nwith foo() as f:\n    print('hello')\n\nc()\nthing()\nprint('==')\ntry:\n    hm()\nexcept IndexError:\n    pass\nelse:\n    assert False\n\n[out]\nstarted\nhello\nfinished\nEntering\n***\nc\nEntering\n***\nd\n***\nExited\n***\nExited\nEntering\n***\nc\nEntering\n***\nd\n***\nExited\n***\nExited\n==\nstarted\nindex\n\n[case testDecoratorsMethods]\nfrom typing import Any, Callable, Iterator, TypeVar\nfrom contextlib import contextmanager\n\nT = TypeVar('T')\ndef dec(f: T) -> T:\n    return f\n\ndef a(f: Callable[[Any], None]) -> Callable[[Any], None]:\n    def g(a: Any) -> None:\n        print('Entering')\n        f(a)\n        print('Exited')\n    return g\n\nclass A:\n    @a\n    def foo(self) -> None:\n        print('foo')\n\n    @contextmanager\n    def generator(self) -> Iterator[int]:\n        try:\n            print('contextmanager: entering')\n            yield 0\n        finally:\n            print('contextmanager: exited')\n\nclass Lol:\n    @staticmethod\n    def foo() -> None:\n        Lol.bar()\n        Lol.baz()\n\n    @staticmethod\n    @dec\n    def bar() -> None:\n        pass\n\n    @classmethod\n    @dec\n    def baz(cls) -> None:\n        pass\n\ndef inside() -> None:\n    with A().generator() as g:\n        print('hello!')\n\nwith A().generator() as g:\n    print('hello!')\n\ndef lol() -> None:\n    with A().generator() as g:\n        raise Exception\n\n[file driver.py]\nfrom native import A, lol\n\nA.foo(A())\nA().foo()\nwith A().generator() as g:\n    print('hello!')\ntry:\n    lol()\nexcept:\n    pass\nelse:\n    assert False\n\n[out]\ncontextmanager: entering\nhello!\ncontextmanager: exited\nEntering\nfoo\nExited\nEntering\nfoo\nExited\ncontextmanager: entering\nhello!\ncontextmanager: exited\ncontextmanager: entering\ncontextmanager: exited\n\n[case testUnannotatedFunction]\ndef g(x: int) -> int:\n    return x * 2\n\ndef f(x):\n    return g(x)\n[file driver.py]\nfrom native import f\nassert f(3) == 6\n\n[case testUnannotatedModuleLevelInitFunction]\n# Ensure that adding an implicit `-> None` annotation only applies to `__init__`\n# _methods_ specifically (not module-level `__init__` functions).\ndef __init__():\n    return 42\n[file driver.py]\nfrom native import __init__\nassert __init__() == 42\n\n[case testDifferentArgCountsFromInterpreted]\n# Test various signatures from interpreted code.\ndef noargs() -> int:\n    return 5\n\ndef onearg(x: int) -> int:\n    return x + 1\n\ndef twoargs(x: int, y: str) -> int:\n    return x + len(y)\n\ndef one_or_two(x: int, y: str = 'a') -> int:\n    return x + len(y)\n\n[file driver.py]\nfrom native import noargs, onearg, twoargs, one_or_two\nfrom testutil import assertRaises\n\nassert noargs() == 5\nt = ()\nassert noargs(*t) == 5\nd = {}\nassert noargs(**d) == 5\nassert noargs(*t, **d) == 5\n\nassert onearg(12) == 13\nassert onearg(x=8) == 9\nt = (1,)\nassert onearg(*t) == 2\nd = {'x': 5}\nassert onearg(**d) == 6\n\n# Test a bogus call to twoargs before any correct calls are made\nwith assertRaises(TypeError, \"twoargs() missing required argument 'x' (pos 1)\"):\n    twoargs()\n\nassert twoargs(5, 'foo') == 8\nassert twoargs(4, y='foo') == 7\nassert twoargs(y='foo', x=7) == 10\nt = (1, 'xy')\nassert twoargs(*t) == 3\nd = {'y': 'xy'}\nassert twoargs(2, **d) == 4\n\nassert one_or_two(5) == 6\nassert one_or_two(x=3) == 4\nassert one_or_two(6, 'xy') == 8\nassert one_or_two(7, y='xy') == 9\nassert one_or_two(y='xy', x=2) == 4\nassert one_or_two(*t) == 3\nd = {'x': 5}\nassert one_or_two(**d) == 6\nassert one_or_two(y='xx', **d) == 7\nd = {'y': 'abc'}\nassert one_or_two(1, **d) == 4\n\nwith assertRaises(TypeError, 'noargs() takes at most 0 arguments (1 given)'):\n    noargs(1)\nwith assertRaises(TypeError, 'noargs() takes at most 0 keyword arguments (1 given)'):\n    noargs(x=1)\n\nwith assertRaises(TypeError, \"onearg() missing required argument 'x' (pos 1)\"):\n    onearg()\nwith assertRaises(TypeError, 'onearg() takes at most 1 argument (2 given)'):\n    onearg(1, 2)\nwith assertRaises(TypeError, \"onearg() missing required argument 'x' (pos 1)\"):\n    onearg(y=1)\nwith assertRaises(TypeError, \"onearg() takes at most 1 argument (2 given)\"):\n    onearg(1, y=1)\n\nwith assertRaises(TypeError, \"twoargs() missing required argument 'x' (pos 1)\"):\n    twoargs()\nwith assertRaises(TypeError, \"twoargs() missing required argument 'y' (pos 2)\"):\n    twoargs(1)\nwith assertRaises(TypeError, 'twoargs() takes at most 2 arguments (3 given)'):\n    twoargs(1, 'x', 2)\nwith assertRaises(TypeError, 'twoargs() takes at most 2 arguments (3 given)'):\n    twoargs(1, 'x', y=2)\n\nwith assertRaises(TypeError, \"one_or_two() missing required argument 'x' (pos 1)\"):\n    one_or_two()\nwith assertRaises(TypeError, 'one_or_two() takes at most 2 arguments (3 given)'):\n    one_or_two(1, 'x', 2)\nwith assertRaises(TypeError, 'one_or_two() takes at most 2 arguments (3 given)'):\n    one_or_two(1, 'x', y=2)\n\n[case testComplicatedArgs]\nfrom typing import Tuple, Dict\n\ndef kwonly1(x: int = 0, *, y: int) -> Tuple[int, int]:\n    return x, y\n\ndef kwonly2(*, x: int = 0, y: int) -> Tuple[int, int]:\n    return x, y\n\ndef kwonly3(a: int, b: int = 0, *, y: int, x: int = 1) -> Tuple[int, int, int, int]:\n    return a, b, x, y\n\ndef kwonly4(*, x: int, y: int) -> Tuple[int, int]:\n    return x, y\n\ndef varargs1(*args: int) -> Tuple[int, ...]:\n    return args\n\ndef varargs2(*args: int, **kwargs: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:\n    return args, kwargs\n\ndef varargs3(**kwargs: int) -> Dict[str, int]:\n    return kwargs\n\ndef varargs4(a: int, b: int = 0,\n             *args: int, y: int, x: int = 1,\n             **kwargs: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:\n    return (a, b, *args), {'x': x, 'y': y, **kwargs}\n\nclass A:\n    def f(self, x: int) -> Tuple[int, ...]:\n        return (x,)\n    def g(self, x: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:\n        return (x,), {}\n\nclass B(A):\n    def f(self, *args: int) -> Tuple[int, ...]:\n        return args\n    def g(self, *args: int, **kwargs: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:\n        return args, kwargs\n\n[file other.py]\n# This file is imported in both compiled and interpreted mode in order to\n# test both native calls and calls via the C API.\n\nfrom native import (\n    kwonly1, kwonly2, kwonly3, kwonly4,\n    varargs1, varargs2, varargs3, varargs4,\n    A, B\n)\n\n# kwonly arg tests\nassert kwonly1(10, y=20) == (10, 20)\nassert kwonly1(y=20) == (0, 20)\n\nassert kwonly2(x=10, y=20) == (10, 20)\nassert kwonly2(y=20) == (0, 20)\n\nassert kwonly3(10, y=20) == (10, 0, 1, 20)\nassert kwonly3(a=10, y=20) == (10, 0, 1, 20)\nassert kwonly3(10, 30, y=20) == (10, 30, 1, 20)\nassert kwonly3(10, b=30, y=20) == (10, 30, 1, 20)\nassert kwonly3(a=10, b=30, y=20) == (10, 30, 1, 20)\n\nassert kwonly3(10, x=40, y=20) == (10, 0, 40, 20)\nassert kwonly3(a=10, x=40, y=20) == (10, 0, 40, 20)\nassert kwonly3(10, 30, x=40, y=20) == (10, 30, 40, 20)\nassert kwonly3(10, b=30, x=40, y=20) == (10, 30, 40, 20)\nassert kwonly3(a=10, b=30, x=40, y=20) == (10, 30, 40, 20)\n\nassert kwonly4(x=1, y=2) == (1, 2)\nassert kwonly4(y=2, x=1) == (1, 2)\n\n# varargs tests\nassert varargs1() == ()\nassert varargs1(1, 2, 3) == (1, 2, 3)\nassert varargs1(1, *[2, 3, 4], 5, *[6, 7, 8], 9) == (1, 2, 3, 4, 5, 6, 7, 8, 9)\nassert varargs2(1, 2, 3) == ((1, 2, 3), {})\nassert varargs2(1, 2, 3, x=4) == ((1, 2, 3), {'x': 4})\nassert varargs2(x=4) == ((), {'x': 4})\nassert varargs3() == {}\nassert varargs3(x=4) == {'x': 4}\nassert varargs3(x=4, y=5) == {'x': 4, 'y': 5}\n\nassert varargs4(-1, y=2) == ((-1, 0), {'x': 1, 'y': 2})\nassert varargs4(-1, 2, y=2) == ((-1, 2), {'x': 1, 'y': 2})\nassert varargs4(-1, 2, 3, y=2) == ((-1, 2, 3), {'x': 1, 'y': 2})\nassert varargs4(-1, 2, 3, x=10, y=2) == ((-1, 2, 3), {'x': 10, 'y': 2})\nassert varargs4(-1, x=10, y=2) == ((-1, 0), {'x': 10, 'y': 2})\nassert varargs4(-1, y=2, z=20) == ((-1, 0), {'x': 1, 'y': 2, 'z': 20})\nassert varargs4(-1, 2, y=2, z=20) == ((-1, 2), {'x': 1, 'y': 2, 'z': 20})\nassert varargs4(-1, 2, 3, y=2, z=20) == ((-1, 2, 3), {'x': 1, 'y': 2, 'z': 20})\nassert varargs4(-1, 2, 3, x=10, y=2, z=20) == ((-1, 2, 3), {'x': 10, 'y': 2, 'z': 20})\nassert varargs4(-1, x=10, y=2, z=20) == ((-1, 0), {'x': 10, 'y': 2, 'z': 20})\n\nx = B()  # type: A\nassert x.f(1) == (1,)\nassert x.g(1) == ((1,), {})\n# This one is really funny! When we make native calls we lose\n# track of which arguments are positional or keyword, so the glue\n# calls them all positional unless they are keyword only...\n# It would be possible to fix this by dynamically tracking which\n# arguments were passed by keyword (for example, by passing a bitmask\n# to functions indicating this), but paying a speed, size, and complexity\n# cost for something so deeply marginal seems like a bad choice.\n# assert x.g(x=1) == ((), {'x': 1})\n\n[file driver.py]\nfrom testutil import assertRaises\nfrom native import (\n    kwonly1, kwonly2, kwonly3, kwonly4,\n    varargs1, varargs2, varargs3, varargs4,\n)\n\n# Run the non-exceptional tests in both interpreted and compiled mode\nimport other\nimport other_interpreted\n\n\n# And the tests for errors at the interfaces in interpreted only\nwith assertRaises(TypeError, \"missing required keyword-only argument 'y'\"):\n    kwonly1()\nwith assertRaises(TypeError, \"takes at most 1 positional argument (2 given)\"):\n    kwonly1(10, 20)\n\nwith assertRaises(TypeError, \"missing required keyword-only argument 'y'\"):\n    kwonly2()\nwith assertRaises(TypeError, \"takes no positional arguments\"):\n    kwonly2(10, 20)\n\nwith assertRaises(TypeError, \"missing required argument 'a'\"):\n    kwonly3(b=30, x=40, y=20)\nwith assertRaises(TypeError, \"missing required keyword-only argument 'y'\"):\n    kwonly3(10)\n\nwith assertRaises(TypeError, \"missing required keyword-only argument 'y'\"):\n    kwonly4(x=1)\nwith assertRaises(TypeError, \"missing required keyword-only argument 'x'\"):\n    kwonly4(y=1)\nwith assertRaises(TypeError, \"missing required keyword-only argument 'x'\"):\n    kwonly4()\n\nwith assertRaises(TypeError, \"'x' is an invalid keyword argument for varargs1()\"):\n    varargs1(x=10)\nwith assertRaises(TypeError, \"'x' is an invalid keyword argument for varargs1()\"):\n    varargs1(1, x=10)\nwith assertRaises(TypeError, \"varargs3() takes no positional arguments\"):\n    varargs3(10)\nwith assertRaises(TypeError, \"varargs3() takes no positional arguments\"):\n    varargs3(10, x=10)\n\nwith assertRaises(TypeError, \"varargs4() missing required argument 'a' (pos 1)\"):\n    varargs4()\nwith assertRaises(TypeError, \"varargs4() missing required keyword-only argument 'y'\"):\n    varargs4(1, 2)\nwith assertRaises(TypeError, \"varargs4() missing required keyword-only argument 'y'\"):\n    varargs4(1, 2, x=1)\nwith assertRaises(TypeError, \"varargs4() missing required keyword-only argument 'y'\"):\n    varargs4(1, 2, 3)\nwith assertRaises(TypeError, \"varargs4() missing required argument 'a' (pos 1)\"):\n    varargs4(y=20)\n\n[case testDecoratorName]\ndef dec(f): return f\n\n@dec\ndef foo(): pass\n\ndef test_decorator_name():\n    assert foo.__name__ == \"foo\"\n\n[case testLambdaArgToOverloaded]\nfrom lib import sub\n\ndef test_str_overload() -> None:\n    assert sub('x', lambda m: m) == 'x'\n\ndef test_bytes_overload() -> None:\n    assert sub(b'x', lambda m: m) == b'x'\n\n[file lib.py]\nfrom typing import overload, Callable, TypeVar, Generic\n\nT = TypeVar(\"T\")\n\nclass Match(Generic[T]):\n    def __init__(self, x: T) -> None:\n        self.x = x\n\n    def group(self, n: int) -> T:\n        return self.x\n\n@overload\ndef sub(s: str, f: Callable[[str], str]) -> str: ...\n@overload\ndef sub(s: bytes, f: Callable[[bytes], bytes]) -> bytes: ...\ndef sub(s, f):\n    return f(s)\n\n[case testContextManagerSpecialCase]\nfrom typing import Generator, Callable, Iterator\nfrom contextlib import contextmanager\n\n@contextmanager\ndef f() -> Iterator[None]:\n    yield\n\ndef test_special_case() -> None:\n    a = ['']\n    with f():\n        a.pop()\n\n[case testUnpackKwargsCompiled]\nfrom typing import TypedDict\nfrom typing_extensions import Unpack\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\ndef foo(**kwargs: Unpack[Person]) -> None:\n    print(kwargs[\"name\"])\n\ndef test_unpack() -> None:\n    # This is not really supported yet, just test that we behave reasonably.\n    foo(name='Jennifer', age=38)\n[typing fixtures/typing-full.pyi]\n[out]\nJennifer\n\n[case testNestedFunctionDunderDict312]\nimport sys\n\ndef foo() -> None:\n    def inner() -> str: return \"bar\"\n    print(inner.__dict__)  # type: ignore[attr-defined]\n    inner.__dict__.update({\"x\": 1})  # type: ignore[attr-defined]\n    print(inner.__dict__)  # type: ignore[attr-defined]\n    print(inner.x)  # type: ignore[attr-defined]\n\ndef test_nested() -> None:\n    if sys.version_info >= (3, 12):  # type: ignore\n        foo()\n[out]\n[out version>=3.12]\n{}\n{'x': 1}\n1\n\n[case testFunctoolsUpdateWrapper]\nimport functools\n\ndef bar() -> None:\n    def inner() -> str: return \"bar\"\n    functools.update_wrapper(inner, bar)  # type: ignore\n    print(inner.__dict__)  # type: ignore\n\ndef test_update() -> None:\n    bar()\n[typing fixtures/typing-full.pyi]\n[out]\n{'__module__': 'native', '__name__': 'bar', '__qualname__': 'bar', '__doc__': None, '__wrapped__': <built-in function bar>}\n\n[case testCallNestedFunctionWithNamed]\ndef f() -> None:\n    def a() -> None:\n        pass\n    def b() -> None:\n        a()\n    b()\n[file driver.py]\nfrom native import f\nf()\n\n[case testCallNestedFunctionWithLambda]\ndef f(x: int) -> int:\n    def inc(x: int) -> int:\n        return x + 1\n    return (lambda x: inc(x))(1)\n[file driver.py]\nfrom native import f\nprint(f(1))\n[out]\n2\n\n[case testStarArgFastPaths]\nfrom typing import Any, Mapping\ndef fn(x: str, y: int) -> str:\n    return x * y\ndef star_tuple(*args: Any) -> str:\n    return fn(*args)\ndef star_list(args: list[Any]) -> str:\n    return fn(*args)\ndef star_generic(args: dict[Any, Any]) -> str:\n    return fn(*args)\ndef star2(**kwargs: Any) -> str:\n    return fn(**kwargs)\ndef star2_generic(kwargs: Mapping[Any, Any]) -> str:\n    return fn(**kwargs)\n\ndef test_star_fastpath_tuple() -> None:\n    assert star_tuple(\"a\", 3) == \"aaa\"\ndef test_star_fastpath_list() -> None:\n    assert star_list([\"a\", 3]) == \"aaa\"\ndef test_star_fastpath_generic() -> None:\n    assert star_generic({\"a\": None, 3: None}) == \"aaa\"\ndef test_star2_fastpath() -> None:\n    assert star2(x=\"a\", y=3) == \"aaa\"\ndef test_star2_fastpath_generic() -> None:\n    assert star2_generic({\"x\": \"a\", \"y\": 3}) == \"aaa\"\n\n[case testLambdaInListComprehension]\n# Lambda inside list comprehension at module level\nfuncs_list = [lambda x, i=i: x + i for i in range(3)]\n\ndef test_module_level() -> None:\n    assert [f(10) for f in funcs_list] == [10, 11, 12]\n\ndef test_in_function() -> None:\n    funcs = [lambda x, i=i: x + i for i in range(3)]\n    assert [f(10) for f in funcs] == [10, 11, 12]\n    # Different parameter name than loop variable\n    funcs2 = [lambda x, n=i: x + n for i in range(3)]\n    assert [f(10) for f in funcs2] == [10, 11, 12]\n\n[case testLambdaInDictComprehension]\n# Lambda inside dict comprehension at module level\nfuncs_dict = {k: lambda x, k=k: x + k for k in range(3)}\n\ndef test_module_level() -> None:\n    assert funcs_dict[0](10) == 10\n    assert funcs_dict[1](10) == 11\n    assert funcs_dict[2](10) == 12\n\ndef test_in_function() -> None:\n    d = {k: (lambda k=k: k * 2) for k in range(3)}\n    assert d[0]() == 0\n    assert d[1]() == 2\n    assert d[2]() == 4\n    # Different parameter name than loop variable\n    d2 = {k: (lambda n=k: n * 2) for k in range(3)}\n    assert d2[0]() == 0\n    assert d2[1]() == 2\n    assert d2[2]() == 4\n\n[case testLambdaInSetComprehension]\ndef test_set_comp() -> None:\n    funcs = {(lambda i=i: i) for i in range(3)}\n    results = {f() for f in funcs}\n    assert results == {0, 1, 2}\n    # Different parameter name than loop variable\n    funcs2 = {(lambda n=i: n) for i in range(3)}\n    results2 = {f() for f in funcs2}\n    assert results2 == {0, 1, 2}\n\n[case testLambdaInComprehensionCaptureOuter]\n# Lambda capturing both loop var and outer function var\ndef test_capture_outer_and_loop() -> None:\n    base = 100\n    funcs = [lambda i=i: i + base for i in range(3)]\n    assert funcs[0]() == 100\n    assert funcs[1]() == 101\n    assert funcs[2]() == 102\n    # Different parameter name than loop variable\n    funcs2 = [lambda n=i: n + base for i in range(3)]\n    assert funcs2[0]() == 100\n    assert funcs2[1]() == 101\n    assert funcs2[2]() == 102\n\n[case testLambdaInDictComprehensionLateBind]\n# Dict comprehension with late-binding lambda (no default arg)\ndef test_dict_comp_late_bind() -> None:\n    d = {name: (lambda: name) for name in (\"a\", \"b\")}\n    # Late binding: all lambdas see the final value of 'name'\n    assert d[\"a\"]() == \"b\"\n    assert d[\"b\"]() == \"b\"\n\n[case testLambdaInComprehensionClassLevel]\n# Lambda inside comprehension at class level\nfrom typing import ClassVar\nclass Foo:\n    A: ClassVar[object] = {name: (lambda: name) for name in (\"a\", \"b\")}\n\n[file driver.py]\nfrom native import Foo\nassert Foo.A[\"a\"]() == \"b\"\nassert Foo.A[\"b\"]() == \"b\"\n\n[case testLambdaInGeneratorExpression]\ndef test_generator_with_lambda_default() -> None:\n    result = list((lambda i=i: i * 2) for i in range(4))\n    assert [f() for f in result] == [0, 2, 4, 6]\n    # Different parameter name than loop variable\n    result2 = list((lambda n=i: n * 2) for i in range(4))\n    assert [f() for f in result2] == [0, 2, 4, 6]\n\n[case testLambdaInComprehensionWithParamIterable]\n# Lambda inside comprehension where the iterable is a function parameter.\n# The comprehension scope must be able to read variables from the enclosing\n# function scope (not just the comprehension's own env class).\nfrom typing import List, Callable\n\ndef transform(items: List[int]) -> List[Callable[[], int]]:\n    return [(lambda i=i: i * 2) for i in items]  # type: ignore[misc]\n\ndef transform_different_name(items: List[int]) -> List[Callable[[], int]]:\n    return [(lambda n=i: n * 2) for i in items]  # type: ignore[misc]\n\ndef uses_multiple_params(items: List[str], sep: str) -> List[Callable[[], str]]:\n    return [(lambda s=s: s + sep) for s in items]  # type: ignore[misc]\n\ndef uses_multiple_params_different_name(items: List[str], sep: str) -> List[Callable[[], str]]:\n    return [(lambda t=s: t + sep) for s in items]  # type: ignore[misc]\n\ndef test_param_iterable() -> None:\n    funcs = transform([1, 2, 3])\n    assert [f() for f in funcs] == [2, 4, 6]\n    # Different parameter name than loop variable\n    funcs2 = transform_different_name([1, 2, 3])\n    assert [f() for f in funcs2] == [2, 4, 6]\n\ndef test_multiple_params() -> None:\n    funcs = uses_multiple_params([\"a\", \"b\"], \"!\")\n    assert [f() for f in funcs] == [\"a!\", \"b!\"]\n    # Different parameter name than loop variable\n    funcs2 = uses_multiple_params_different_name([\"a\", \"b\"], \"!\")\n    assert [f() for f in funcs2] == [\"a!\", \"b!\"]\n"
  },
  {
    "path": "mypyc/test-data/run-generators.test",
    "content": "# Test cases for generators and yield (compile and run)\n\n[case testYield]\nfrom typing import Generator, Iterable, Union, Tuple, Dict\n\ndef yield_three_times() -> Iterable[int]:\n    yield 1\n    yield 2\n    yield 3\n\ndef yield_twice_and_return() -> Generator[int, None, int]:\n    yield 1\n    yield 2\n    return 4\n\ndef yield_while_loop() -> Generator[int, None, int]:\n    i = 0\n    while i < 5:\n        if i == 3:\n            return i\n        yield i\n        i += 1\n    return -1\n\ndef yield_for_loop() -> Iterable[int]:\n    l = [i for i in range(3)]\n    for i in l:\n        yield i\n\n    d = {k: None for k in range(3)}\n    for k in d:\n        yield k\n\n    for i in range(3):\n        yield i\n\n    for i in range(three()):\n        yield i\n\ndef yield_with_except() -> Generator[int, None, None]:\n    yield 10\n    try:\n        return\n    except:\n        print('Caught exception inside generator function')\n\ndef complex_yield(a: int, b: str, c: float) -> Generator[Union[str, int], None, float]:\n    x = 2\n    while x < a:\n        if x % 2 == 0:\n            dummy_var = 1\n            yield str(x) + ' ' + b\n            dummy_var = 1\n        else:\n            dummy_var = 1\n            yield x\n            dummy_var = 1\n        x += 1\n    return c\n\ndef yield_with_default(x: bool = False) -> Iterable[int]:\n    if x:\n        yield 0\n\ndef yield_dict_methods(d1: Dict[int, int],\n                       d2: Dict[int, int],\n                       d3: Dict[int, int]) -> Iterable[int]:\n    for k in d1.keys():\n        yield k\n    for k, v in d2.items():\n        yield k\n        yield v\n    for v in d3.values():\n        yield v\n\ndef three() -> int:\n    return 3\n\nclass A(object):\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def generator(self) -> Iterable[int]:\n        yield self.x\n\ndef return_tuple() -> Generator[int, None, Tuple[int, int]]:\n    yield 0\n    return 1, 2\n\n[file driver.py]\nfrom native import (\n    yield_three_times,\n    yield_twice_and_return,\n    yield_while_loop,\n    yield_for_loop,\n    yield_with_except,\n    complex_yield,\n    yield_with_default,\n    A,\n    return_tuple,\n    yield_dict_methods,\n)\nfrom testutil import run_generator\nfrom collections import defaultdict\n\nassert run_generator(yield_three_times()) == ((1, 2, 3), None)\nassert run_generator(yield_twice_and_return()) == ((1, 2), 4)\nassert run_generator(yield_while_loop()) == ((0, 1, 2), 3)\nassert run_generator(yield_for_loop()) == (tuple(4 * [i for i in range(3)]), None)\nassert run_generator(yield_with_except()) == ((10,), None)\nassert run_generator(complex_yield(5, 'foo', 1.0)) == (('2 foo', 3, '4 foo'), 1.0)\nassert run_generator(yield_with_default()) == ((), None)\nassert run_generator(A(0).generator()) == ((0,), None)\nassert run_generator(return_tuple()) == ((0,), (1, 2))\nassert run_generator(yield_dict_methods({}, {}, {})) == ((), None)\nassert run_generator(yield_dict_methods({1: 2}, {3: 4}, {5: 6})) == ((1, 3, 4, 6), None)\ndd = defaultdict(int, {0: 1})\nassert run_generator(yield_dict_methods(dd, dd, dd)) == ((0, 0, 1, 1), None)\n\nfor i in yield_twice_and_return():\n    print(i)\n\nfor i in yield_while_loop():\n    print(i)\n\n[out]\n1\n2\n0\n1\n2\n\n[case testYieldTryFinallyWith]\nfrom typing import Generator, Any\n\nclass Thing:\n    def __init__(self, x: str) -> None:\n        self.x = x\n    def __enter__(self) -> str:\n        print('enter!', self.x)\n        if self.x == 'crash':\n            raise Exception('ohno')\n        return self.x\n    def __exit__(self, x: Any, y: Any, z: Any) -> None:\n        print('exit!', self.x, y)\n\ndef yield_try_finally() -> Generator[int, None, str]:\n    try:\n        yield 1\n        yield 2\n        return 'lol'\n    except Exception:\n        raise\n    finally:\n        print('goodbye!')\n\ndef yield_with(i: int) -> Generator[int, None, int]:\n    with Thing('a') as x:\n        yield 1\n        print(\"yooo?\", x)\n        if i == 0:\n            yield 2\n            return 10\n        elif i == 1:\n            raise Exception('exception!')\n    return -1\n\n[file driver.py]\nfrom native import yield_try_finally, yield_with\nfrom testutil import run_generator\n\nprint(run_generator(yield_try_finally(), p=True))\nprint(run_generator(yield_with(0), p=True))\nprint(run_generator(yield_with(1), p=True))\n[out]\n1\n2\ngoodbye!\n((1, 2), 'lol')\nenter! a\n1\nyooo? a\n2\nexit! a None\n((1, 2), 10)\nenter! a\n1\nyooo? a\nexit! a exception!\n((1,), 'exception!')\n\n[case testYieldNested]\nfrom typing import Callable, Generator, Iterator, TypeVar, overload\n\nfrom testutil import run_generator\n\ndef normal(a: int, b: float) -> Callable:\n    def generator(x: int, y: str) -> Generator:\n        yield a\n        yield b\n        yield x\n        yield y\n    return generator\n\ndef generator(a: int) -> Generator:\n    def normal(x: int) -> int:\n        return a + x\n    for i in range(3):\n        yield normal(i)\n\ndef triple() -> Callable:\n    def generator() -> Generator:\n        x = 0\n        def inner() -> int:\n            x += 1\n            return x\n        while x < 3:\n            yield inner()\n    return generator\n\ndef another_triple() -> Callable:\n    def generator() -> Generator:\n        x = 0\n        def inner_generator() -> Generator:\n            x += 1\n            yield x\n        yield next(inner_generator())\n    return generator\n\ndef outer() -> Generator:\n    def recursive(n: int) -> Generator:\n        if n < 10:\n            for i in range(n):\n                yield i\n            return\n        for i in recursive(5):\n            yield i\n    return recursive(10)\n\ndef test_return_nested_generator() -> None:\n    assert run_generator(normal(1, 2.0)(3, '4.00')) == ((1, 2.0, 3, '4.00'), None)\n    assert run_generator(generator(1)) == ((1, 2, 3), None)\n    assert run_generator(triple()()) == ((1, 2, 3), None)\n    assert run_generator(another_triple()()) == ((1,), None)\n    assert run_generator(outer()) == ((0, 1, 2, 3, 4), None)\n\ndef call_nested(x: int) -> list[int]:\n    def generator() -> Iterator[int]:\n        n = int() + 2\n        yield x\n        yield n * x\n\n    a = []\n    for x in generator():\n        a.append(x)\n    return a\n\nT = TypeVar(\"T\")\n\ndef deco(f: T) -> T:\n    return f\n\ndef call_nested_decorated(x: int) -> list[int]:\n    @deco\n    def generator() -> Iterator[int]:\n        n = int() + 3\n        yield x\n        yield n * x\n\n    a = []\n    for x in generator():\n        a.append(x)\n    return a\n\ndef call_nested_recursive(x: int) -> Iterator:\n    def recursive(x: int) -> Iterator:\n        if x > 0:\n            yield from recursive(x - 1)\n        yield x\n\n    yield from recursive(x)\n\ndef test_call_nested_generator_in_function() -> None:\n    assert call_nested_decorated(5) == [5, 15]\n    assert list(call_nested_recursive(5)) == [0, 1, 2, 3, 4, 5]\n\n[case testYieldThrow]\nfrom typing import Generator, Iterable, Any, Union\nfrom traceback import print_tb\nfrom contextlib import contextmanager\nimport wrapsys\n\ndef generator() -> Generator[int, None, Union[int, None]]:\n    try:\n        yield 1\n        yield 2\n        yield 3\n    except Exception as e:\n        print_tb(wrapsys.exc_info()[2])\n        s = str(e)\n        if s:\n            print('caught exception with value ' + s)\n        else:\n            print('caught exception without value')\n        return 0\n    return None\n\ndef no_except() -> Iterable[int]:\n    yield 1\n    yield 2\n\ndef raise_something() -> Iterable[int]:\n    yield 1\n    yield 2\n    raise Exception('failure')\n\ndef wrapper(x: Any) -> Any:\n    return (yield from x)\n\ndef foo() -> Generator[int, None, None]:\n    try:\n        yield 1\n    except Exception as e:\n        print(str(e))\n    finally:\n        print('goodbye')\n\nctx_manager = contextmanager(foo)\n\n[file wrapsys.py]\n# This is a gross hack around some limitations of the test system/mypyc.\nfrom typing import Any\nimport sys\ndef exc_info() -> Any:\n    return sys.exc_info()  # type: ignore\n\n[file driver.py]\nimport sys\nfrom typing import Generator, Tuple, TypeVar, Sequence\nfrom native import generator, ctx_manager, wrapper, no_except, raise_something\n\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef run_generator_and_throw(gen: Generator[T, None, U],\n                            num_times: int,\n                            value: object = None,\n                            traceback: object = None) -> Tuple[Sequence[T], U]:\n    res = []\n    try:\n        for i in range(num_times):\n            res.append(next(gen))\n        if value is not None and traceback is not None:\n            gen.throw(Exception, value, traceback)\n        elif value is not None:\n            gen.throw(Exception, value)\n        else:\n            gen.throw(Exception)\n    except StopIteration as e:\n        return (tuple(res), e.value)\n    except Exception as e:\n        return (tuple(res), str(e))\n\nassert run_generator_and_throw(generator(), 0, 'hello') == ((), 'hello')\nassert run_generator_and_throw(generator(), 3) == ((1, 2, 3), 0)\nassert run_generator_and_throw(generator(), 2, 'some string') == ((1, 2), 0)\ntry:\n    raise Exception\nexcept Exception as e:\n    tb = sys.exc_info()[2]\n    assert run_generator_and_throw(generator(), 1, 'some other string', tb) == ((1,), 0)\n\nassert run_generator_and_throw(wrapper(generator()), 0, 'hello') == ((), 'hello')\nassert run_generator_and_throw(wrapper(generator()), 3) == ((1, 2, 3), 0)\nassert run_generator_and_throw(wrapper(generator()), 2, 'some string') == ((1, 2), 0)\n# Make sure we aren't leaking exc_info\nassert sys.exc_info()[0] is None\n\nassert run_generator_and_throw(wrapper([1, 2, 3]), 3, 'lol') == ((1, 2, 3), 'lol')\nassert run_generator_and_throw(wrapper(no_except()), 2, 'lol') == ((1, 2), 'lol')\n\nassert run_generator_and_throw(wrapper(raise_something()), 3) == ((1, 2), 'failure')\n\nwith ctx_manager() as c:\n    raise Exception('exception')\n\n[out]\n  File \"native.py\", line 10, in generator\n    yield 3\n  File \"native.py\", line 9, in generator\n    yield 2\n  File \"native.py\", line 8, in generator\n    yield 1\n  File \"driver.py\", line 31, in <module>\n    raise Exception\n  File \"native.py\", line 10, in generator\n    yield 3\n  File \"native.py\", line 31, in wrapper\n    return (yield from x)\n  File \"native.py\", line 9, in generator\n    yield 2\n  File \"native.py\", line 31, in wrapper\n    return (yield from x)\ncaught exception without value\ncaught exception with value some string\ncaught exception with value some other string\ncaught exception without value\ncaught exception with value some string\nexception\ngoodbye\n\n[case testYieldSend]\nfrom typing import Generator\n\ndef basic() -> Generator[int, int, int]:\n    x = yield 1\n    y = yield (x + 1)\n    return y\n\ndef use_from() -> Generator[int, int, int]:\n    return (yield from basic())\n\n[file driver.py]\nfrom native import basic, use_from\nfrom testutil import run_generator\n\nassert run_generator(basic(), [5, 50]) == ((1, 6), 50)\nassert run_generator(use_from(), [5, 50]) == ((1, 6), 50)\n\n[case testYieldFrom]\nfrom typing import Generator, Iterator, List\n\ndef basic() -> Iterator[int]:\n    yield from [1, 2, 3]\n\ndef call_next() -> int:\n    x = []  # type: List[int]\n    return next(iter(x))\n\ndef inner(b: bool) -> Generator[int, None, int]:\n    if b:\n        yield from [1, 2, 3]\n    return 10\n\ndef with_return(b: bool) -> Generator[int, None, int]:\n    x = yield from inner(b)\n    for a in [1, 2]:\n        pass\n    return x\n\n[file driver.py]\nfrom native import basic, call_next, with_return\nfrom testutil import run_generator, assertRaises\n\nassert run_generator(basic()) == ((1, 2, 3), None)\n\nwith assertRaises(StopIteration):\n    call_next()\n\nassert run_generator(with_return(True)) == ((1, 2, 3), 10)\nassert run_generator(with_return(False)) == ((), 10)\n\n[case testNextGenerator]\nfrom typing import Iterable\n\ndef f(x: int) -> int:\n    print(x)\n    return x\n\ndef call_next_loud(l: Iterable[int], val: int) -> int:\n    return next(i for i in l if f(i) == val)\n\ndef call_next_default(l: Iterable[int], val: int) -> int:\n    return next((i*2 for i in l if i == val), -1)\n\ndef call_next_default_list(l: Iterable[int], val: int) -> int:\n    return next((i*2 for i in l if i == val), -1)\n[file driver.py]\nfrom native import call_next_loud, call_next_default, call_next_default_list\nfrom testutil import assertRaises\n\nassert call_next_default([0, 1, 2], 0) == 0\nassert call_next_default([0, 1, 2], 1) == 2\nassert call_next_default([0, 1, 2], 2) == 4\nassert call_next_default([0, 1, 2], 3) == -1\nassert call_next_default([], 0) == -1\nassert call_next_default_list([0, 1, 2], 0) == 0\nassert call_next_default_list([0, 1, 2], 1) == 2\nassert call_next_default_list([0, 1, 2], 2) == 4\nassert call_next_default_list([0, 1, 2], 3) == -1\nassert call_next_default_list([], 0) == -1\n\nassert call_next_loud([0, 1, 2], 0) == 0\nassert call_next_loud([0, 1, 2], 1) == 1\nassert call_next_loud([0, 1, 2], 2) == 2\nwith assertRaises(StopIteration):\n    call_next_loud([42], 3)\nwith assertRaises(StopIteration):\n    call_next_loud([], 3)\n\n[out]\n0\n0\n1\n0\n1\n2\n42\n\n[case testGeneratorSuper]\nfrom typing import Iterator, Callable, Any\n\nclass A():\n    def testA(self) -> int:\n        return 2\n\nclass B(A):\n    def testB(self) -> Iterator[int]:\n        x = super().testA()\n        while True:\n            yield x\n\ndef testAsserts():\n    b = B()\n    b_gen = b.testB()\n    assert next(b_gen) == 2\n\n[file driver.py]\nfrom native import testAsserts\n\ntestAsserts()\n\n[case testNameClashIssues]\nclass A:\n    def foo(self) -> object:\n        yield\nclass B:\n    def foo(self) -> object:\n        yield\n\nclass C:\n    def foo(self) -> None:\n        def bar(self) -> None:\n            pass\n\ndef C___foo() -> None: pass\n\nclass D:\n    def foo(self) -> None:\n        def bar(self) -> None:\n            pass\n\nclass E:\n    default: int\n    switch: int\n\n[file driver.py]\n# really I only care it builds\n\n[case testCloseStopIterationRaised]\ndef g() -> object:\n    try:\n        yield 1\n    except GeneratorExit:\n        raise\n\n[file driver.py]\nfrom native import g\n\ngen = g()\nnext(gen)\ngen.close()\n\n[case testCloseGeneratorExitRaised]\ndef g() -> object:\n    yield 1\n\n[file driver.py]\nfrom native import g\n\ngen = g()\nnext(gen)\ngen.close()\n\n[case testCloseGeneratorExitIgnored]\ndef g() -> object:\n    try:\n        yield 1\n    except GeneratorExit:\n        pass\n\n    yield 2\n\n[file driver.py]\nfrom native import g\n\ngen = g()\nnext(gen)\ntry:\n    gen.close()\nexcept RuntimeError as e:\n    assert str(e) == 'generator ignored GeneratorExit'\nelse:\n    assert False\n\n[case testCloseGeneratorRaisesAnotherException]\ndef g() -> object:\n    try:\n        yield 1\n    except GeneratorExit:\n        raise RuntimeError(\"error\")\n\n[file driver.py]\nfrom native import g\n\ngen = g()\nnext(gen)\ntry:\n    gen.close()\nexcept RuntimeError as e:\n    assert str(e) == 'error'\nelse:\n    assert False\n\n[case testBorrowingInGeneratorNearYield]\nfrom typing import Iterator\n\nclass Foo:\n    flag = False\n\nclass C:\n    foo = Foo()\n\n    def genf(self) -> Iterator[None]:\n        self.foo.flag = True\n        yield\n        self.foo.flag = False\n\ndef test_near_yield() -> None:\n    c = C()\n    for x in c.genf():\n        pass\n    assert c.foo.flag == False\n\n[case testGeneratorEarlyReturnWithBorrows]\nfrom typing import Iterator\nclass Bar:\n    bar = 0\nclass Foo:\n    bar = Bar()\n    def f(self) -> Iterator[int]:\n        if self:\n            self.bar.bar += 1\n            return\n        yield 0\n\ndef test_early_return() -> None:\n    foo = Foo()\n    for x in foo.f():\n        pass\n    assert foo.bar.bar == 1\n\n[case testBorrowingInGeneratorInTupleAssignment]\nfrom typing import Iterator\n\nclass Foo:\n    flag1: bool\n    flag2: bool\n\nclass C:\n    foo: Foo\n\n    def genf(self) -> Iterator[None]:\n        self.foo.flag1, self.foo.flag2 = True, True\n        yield\n        self.foo.flag1, self.foo.flag2 = False, False\n\ndef test_generator() -> None:\n    c = C()\n    c.foo = Foo()\n    gen = c.genf()\n    next(gen)\n    assert c.foo.flag1 == c.foo.flag2 == True\n    assert list(gen) == []\n    assert c.foo.flag1 == c.foo.flag2 == False\n\n\n[case testYieldInFinally]\nfrom typing import Generator\n\ndef finally_yield() -> Generator[str, None, str]:\n    try:\n        return 'test'\n    finally:\n        yield 'x'\n\n\n[file driver.py]\nfrom native import finally_yield\nfrom testutil import run_generator\n\nyields, val = run_generator(finally_yield())\nassert yields == ('x',)\nassert val == 'test', val\n\n[case testUnreachableComprehensionNoCrash]\nfrom typing import List\n\ndef list_comp() -> List[int]:\n    if True:\n        return [5]\n    return [i for i in [5]]\n\n[file driver.py]\nfrom native import list_comp\nassert list_comp() == [5]\n\n[case testWithNative]\nclass DummyContext:\n    def __init__(self) -> None:\n        self.x = 0\n\n    def __enter__(self) -> None:\n        self.x += 1\n\n    def __exit__(self, exc_type, exc_value, exc_tb) -> None:\n        self.x -= 1\n\ndef test_basic() -> None:\n    context = DummyContext()\n    with context:\n        assert context.x == 1\n    assert context.x == 0\n\n[case testYieldSpill]\nfrom typing import Generator\nfrom testutil import run_generator\n\ndef f() -> int:\n    return 1\n\ndef yield_spill() -> Generator[str, int, int]:\n    return f() + (yield \"foo\")\n\ndef test_basic() -> None:\n    x = run_generator(yield_spill(), [2])\n    yields, val = x\n    assert yields == ('foo',)\n    assert val == 3, val\n\n[case testGeneratorReuse]\nfrom typing import Iterator, Any\n\ndef gen(x: list[int]) -> Iterator[list[int]]:\n    y = [9]\n    for z in x:\n        yield y + [z]\n    yield y\n\ndef gen_range(n: int) -> Iterator[int]:\n    for x in range(n):\n        yield x\n\ndef test_use_generator_multiple_times_one_at_a_time() -> None:\n    for i in range(100):\n        a = []\n        for x in gen([2, i]):\n            a.append(x)\n        assert a == [[9, 2], [9, i], [9]]\n\ndef test_use_multiple_generator_instances_at_same_time() -> None:\n    a = []\n    for x in gen([2]):\n        a.append(x)\n        for y in gen([3, 4]):\n            a.append(y)\n    assert a == [[9, 2], [9, 3], [9, 4], [9], [9], [9, 3], [9, 4], [9]]\n\ndef test_use_multiple_generator_instances_at_same_time_2() -> None:\n    a = []\n    for x in gen_range(2):\n        a.append(x)\n        b = []\n        for y in gen_range(3):\n            b.append(y)\n            c = []\n            for z in gen_range(4):\n                c.append(z)\n            assert c == [0, 1, 2, 3]\n        assert b == [0, 1, 2]\n    assert a == [0, 1]\n    assert list(gen_range(5)) == list(range(5))\n\ndef gen_a(x: int) -> Iterator[int]:\n    yield x + 1\n\ndef gen_b(x: int) -> Iterator[int]:\n    yield x + 2\n\ndef test_generator_identities() -> None:\n    # Sanity check: two distinct live objects can't reuse the same memory location\n    g1 = gen_a(1)\n    g2 = gen_a(1)\n    assert g1 is not g2\n\n    # If two generators have non-overlapping lifetimes, they should reuse a memory location\n    g3 = gen_b(1)\n    id1 = id(g3)\n    g3 = gen_b(1)\n    assert id(g3) == id1\n\n    # More complex case of reuse: allocate other objects in between\n    g4: Any = gen_a(1)\n    id2 = id(g4)\n    g4 = gen_b(1)\n    g4 = [gen_b(n) for n in range(100)]\n    g4 = gen_a(1)\n    assert id(g4) == id2\n\n[case testGeneratorReuseWithGilDisabled]\nimport sys\nimport threading\nfrom typing import Iterator\n\ndef gen() -> Iterator[int]:\n    yield 1\n\ndef is_gil_disabled() -> bool:\n    return hasattr(sys, \"_is_gil_enabled\") and not sys._is_gil_enabled()\n\ndef test_each_thread_gets_separate_instance() -> None:\n    if not is_gil_disabled():\n        # This only makes sense if GIL is disabled\n        return\n\n    g = gen()\n    id1 = id(g)\n\n    id2 = 0\n\n    def run() -> None:\n        nonlocal id2\n        g = gen()\n        id2 = id(g)\n\n    t = threading.Thread(target=run)\n    t.start()\n    t.join()\n\n    # Each thread should get a separate reused instance\n    assert id1 != id2\n\n[case testGeneratorWithUndefinedLocalInEnvironment]\nfrom typing import Iterator\n\nfrom testutil import assertRaises\n\ndef gen(set: bool) -> Iterator[float]:\n    if set:\n        y = float(\"-113.0\")\n    yield 1.0\n    yield y\n\ndef test_bitmap_is_cleared_when_object_is_reused() -> None:\n    # This updates the bitmap of the shared instance.\n    list(gen(True))\n\n    # Ensure bitmap has been cleared.\n    with assertRaises(AttributeError):  # TODO: Should be UnboundLocalError\n      list(gen(False))\n\ndef gen2(set: bool) -> Iterator[int]:\n    if set:\n        y = int(\"5\")\n    yield 1\n    yield y\n\ndef test_undefined_int_in_environment() -> None:\n    list(gen2(True))\n\n    with assertRaises(AttributeError):  # TODO: Should be UnboundLocalError\n      list(gen2(False))\n\n[case testVariableWithSameNameAsHelperMethod]\nfrom testutil import assertRaises\nfrom typing import Iterator\n\ndef gen_send() -> Iterator[int]:\n    send = 1\n    yield send + 1\n\ndef gen_throw() -> Iterator[int]:\n    throw = 42\n    yield throw * 2\n\ndef undefined() -> Iterator[int]:\n    if int():\n        send = 1\n    yield send + 1\n\ndef test_same_names() -> None:\n    assert list(gen_send()) == [2]\n    assert list(gen_throw()) == [84]\n\n    with assertRaises(AttributeError, \"attribute 'send' of 'undefined_gen' undefined\"):\n        # TODO: Should be UnboundLocalError, this test verifies that the attribute name\n        # matches the variable name in the input code, since internally it's generated\n        # with a prefix.\n        list(undefined())\n\n[case testGeneratorInheritance]\nfrom typing import Iterator\n\nclass Base1:\n    def foo(self) -> Iterator[int]:\n        yield 1\n\nclass Derived1(Base1):\n    def foo(self) -> Iterator[int]:\n        yield 2\n        yield 3\n\ndef base1_foo(b: Base1) -> list[int]:\n    a = []\n    for x in b.foo():\n        a.append(x)\n    return a\n\ndef derived1_foo(b: Derived1) -> list[int]:\n    a = []\n    for x in b.foo():\n        a.append(x)\n    return a\n\ndef test_generator_override() -> None:\n     assert base1_foo(Base1()) == [1]\n     assert base1_foo(Derived1()) == [2, 3]\n     assert derived1_foo(Derived1()) == [2, 3]\n\n[case testGeneratorEmptyTuple]\nfrom collections.abc import Generator\nfrom typing import Optional, Union\n\ndef test_compiledGeneratorEmptyTuple() -> None:\n    jobs: Generator[Optional[str], None, None] = (_ for _ in ())\n    assert list(jobs) == []\n"
  },
  {
    "path": "mypyc/test-data/run-generics.test",
    "content": "[case testTypeVarMappingBound]\n# Dicts are special-cased for efficient iteration.\nfrom typing import Dict, TypedDict, TypeVar, Union\n\nclass TD(TypedDict):\n    foo: int\n\nM = TypeVar(\"M\", bound=Dict[str, int])\nU = TypeVar(\"U\", bound=Union[Dict[str, int], Dict[str, str]])\nT = TypeVar(\"T\", bound=TD)\n\ndef fn_mapping(m: M) -> None:\n    print([x for x in m])\n    print([x for x in m.values()])\n    print([x for x in m.keys()])\n    print({k: v for k, v in m.items()})\n\ndef fn_union(m: U) -> None:\n    print([x for x in m])\n    print([x for x in m.values()])\n    print([x for x in m.keys()])\n    print({k: v for k, v in m.items()})\n\ndef fn_typeddict(t: T) -> None:\n    print([x for x in t])\n    print([x for x in t.values()])\n    print([x for x in t.keys()])\n    print({k: v for k, v in t.items()})\n\ndef test_mapping() -> None:\n    fn_mapping({})\n    print(\"=====\")\n    fn_mapping({\"a\": 1, \"b\": 2})\n    print(\"=====\")\n\n    fn_union({\"a\": 1, \"b\": 2})\n    print(\"=====\")\n    fn_union({\"a\": \"1\", \"b\": \"2\"})\n    print(\"=====\")\n\n    orig: Union[Dict[str, int], Dict[str, str]] = {\"a\": 1, \"b\": 2}\n    fn_union(orig)\n    print(\"=====\")\n\n    td: TD = {\"foo\": 1}\n    fn_typeddict(td)\n[typing fixtures/typing-full.pyi]\n[out]\n\\[]\n\\[]\n\\[]\n{}\n=====\n\\['a', 'b']\n\\[1, 2]\n\\['a', 'b']\n{'a': 1, 'b': 2}\n=====\n\\['a', 'b']\n\\[1, 2]\n\\['a', 'b']\n{'a': 1, 'b': 2}\n=====\n\\['a', 'b']\n\\['1', '2']\n\\['a', 'b']\n{'a': '1', 'b': '2'}\n=====\n\\['a', 'b']\n\\[1, 2]\n\\['a', 'b']\n{'a': 1, 'b': 2}\n=====\n\\['foo']\n\\[1]\n\\['foo']\n{'foo': 1}\n\n[case testParamSpecComponentsAreUsable]\nfrom typing import Callable\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\n\ndef deco(func: Callable[P, int]) -> Callable[P, int]:\n    def inner(*args: P.args, **kwargs: P.kwargs) -> int:\n        print([x for x in args])\n        print({k: v for k, v in kwargs.items()})\n        print(list(kwargs))\n        print(list(kwargs.keys()))\n        print(list(kwargs.values()))\n        return func(*args, **kwargs)\n\n    return inner\n\n@deco\ndef f(x: int, y: str) -> int:\n    return x\n\ndef test_usable() -> None:\n    assert f(1, 'a') == 1\n    assert f(2, y='b') == 2\n[out]\n\\[1, 'a']\n{}\n\\[]\n\\[]\n\\[]\n\\[2]\n{'y': 'b'}\n\\['y']\n\\['y']\n\\['b']\n"
  },
  {
    "path": "mypyc/test-data/run-i16.test",
    "content": "[case testI16BasicOps]\nfrom typing import Any, Tuple\n\nfrom mypy_extensions import i16, i32, i64\n\nfrom testutil import assertRaises\n\ndef test_box_and_unbox() -> None:\n    values = (list(range(-2**15, -2**15 + 100)) +\n              list(range(-1000, 1000)) +\n              list(range(2**15 - 100, 2**15)))\n    for i in values:\n        o: Any = i\n        x: i16 = o\n        o2: Any = x\n        assert o == o2\n        assert x == i\n    with assertRaises(ValueError, \"int too large to convert to i16\"):\n        o = 2**15\n        x2: i16 = o\n    with assertRaises(ValueError, \"int too large to convert to i16\"):\n        o = -2**15 - 1\n        x3: i16 = o\n\ndef div_by_7(x: i16) -> i16:\n    return x // 7\ndef div_by_neg_7(x: i16) -> i16:\n    return x // -7\n\ndef div(x: i16, y: i16) -> i16:\n    return x // y\n\ndef test_divide_by_constant() -> None:\n    for i in range(-1000, 1000):\n        assert div_by_7(i) == i // 7\n    for i in range(-2**15, -2**15 + 1000):\n        assert div_by_7(i) == i // 7\n    for i in range(2**15 - 1000, 2**15):\n        assert div_by_7(i) == i // 7\n\ndef test_divide_by_negative_constant() -> None:\n    for i in range(-1000, 1000):\n        assert div_by_neg_7(i) == i // -7\n    for i in range(-2**15, -2**15 + 1000):\n        assert div_by_neg_7(i) == i // -7\n    for i in range(2**15 - 1000, 2**15):\n        assert div_by_neg_7(i) == i // -7\n\ndef test_divide_by_variable() -> None:\n    values = (list(range(-50, 50)) +\n              list(range(-2**15, -2**15 + 10)) +\n              list(range(2**15 - 10, 2**15)))\n    for x in values:\n        for y in values:\n            if y != 0:\n                if x // y == 2**15:\n                    with assertRaises(OverflowError, \"integer division overflow\"):\n                        div(x, y)\n                else:\n                    assert div(x, y) == x // y\n            else:\n                with assertRaises(ZeroDivisionError, \"integer division or modulo by zero\"):\n                    div(x, y)\n\ndef mod_by_7(x: i16) -> i16:\n    return x % 7\n\ndef mod_by_neg_7(x: i16) -> i16:\n    return x // -7\n\ndef mod(x: i16, y: i16) -> i16:\n    return x % y\n\ndef test_mod_by_constant() -> None:\n    for i in range(-1000, 1000):\n        assert mod_by_7(i) == i % 7\n    for i in range(-2**15, -2**15 + 1000):\n        assert mod_by_7(i) == i % 7\n    for i in range(2**15 - 1000, 2**15):\n        assert mod_by_7(i) == i % 7\n\ndef test_mod_by_negative_constant() -> None:\n    for i in range(-1000, 1000):\n        assert mod_by_neg_7(i) == i // -7\n    for i in range(-2**15, -2**15 + 1000):\n        assert mod_by_neg_7(i) == i // -7\n    for i in range(2**15 - 1000, 2**15):\n        assert mod_by_neg_7(i) == i // -7\n\ndef test_mod_by_variable() -> None:\n    values = (list(range(-50, 50)) +\n              list(range(-2**15, -2**15 + 10)) +\n              list(range(2**15 - 10, 2**15)))\n    for x in values:\n        for y in values:\n            if y != 0:\n                assert mod(x, y) == x % y\n            else:\n                with assertRaises(ZeroDivisionError, \"integer division or modulo by zero\"):\n                    mod(x, y)\n\ndef test_simple_arithmetic_ops() -> None:\n    zero: i16 = int()\n    one: i16 = zero + 1\n    two: i16 = one + 1\n    neg_one: i16 = -one\n    assert one + one == 2\n    assert one + two == 3\n    assert one + neg_one == 0\n    assert one - one == 0\n    assert one - two == -1\n    assert one * one == 1\n    assert one * two == 2\n    assert two * two == 4\n    assert two * neg_one == -2\n    assert neg_one * one == -1\n    assert neg_one * neg_one == 1\n    assert two * 0 == 0\n    assert 0 * two == 0\n    assert -one == -1\n    assert -two == -2\n    assert -neg_one == 1\n    assert -zero == 0\n\ndef test_bitwise_ops() -> None:\n    x: i16 = 13855 + int()\n    y: i16 = 367 + int()\n    z: i16 = -11091 + int()\n    zero: i16 = int()\n    one: i16 = zero + 1\n    two: i16 = zero + 2\n    neg_one: i16 = -one\n\n    assert x & y == 15\n    assert x & z == 5133\n    assert z & z == z\n    assert x & zero == 0\n\n    assert x | y == 14207\n    assert x | z == -2369\n    assert z | z == z\n    assert x | 0 == x\n\n    assert x ^ y == 14192\n    assert x ^ z == -7502\n    assert z ^ z == 0\n    assert z ^ 0 == z\n\n    assert x << one == 27710\n    assert x << two == -10116\n    assert z << two == 21172\n    assert z << 0 == z\n\n    assert x >> one == 6927\n    assert x >> two == 3463\n    assert z >> two == -2773\n    assert z >> 0 == z\n\n    assert ~x == -13856\n    assert ~z == 11090\n    assert ~zero == -1\n    assert ~neg_one == 0\n\ndef eq(x: i16, y: i16) -> bool:\n    return x == y\n\ndef test_eq() -> None:\n    assert eq(int(), int())\n    assert eq(5 + int(), 5 + int())\n    assert eq(-5 + int(), -5 + int())\n    assert not eq(int(), 1 + int())\n    assert not eq(5 + int(), 6 + int())\n    assert not eq(-5 + int(), -6 + int())\n    assert not eq(-5 + int(), 5 + int())\n\ndef test_comparisons() -> None:\n    one: i16 = 1 + int()\n    one2: i16 = 1 + int()\n    two: i16 = 2 + int()\n    assert one < two\n    assert not (one < one2)\n    assert not (two < one)\n    assert two > one\n    assert not (one > one2)\n    assert not (one > two)\n    assert one <= two\n    assert one <= one2\n    assert not (two <= one)\n    assert two >= one\n    assert one >= one2\n    assert not (one >= two)\n    assert one == one2\n    assert not (one == two)\n    assert one != two\n    assert not (one != one2)\n\ndef test_mixed_comparisons() -> None:\n    i16_3: i16 = int() + 3\n    int_5 = int() + 5\n    assert i16_3 < int_5\n    assert int_5 > i16_3\n    b = i16_3 > int_5\n    assert not b\n\n    int_largest = int() + (1 << 15) - 1\n    assert int_largest > i16_3\n    int_smallest = int() - (1 << 15)\n    assert i16_3 > int_smallest\n\n    int_too_big = int() + (1 << 15)\n    int_too_small = int() - (1 << 15) - 1\n    with assertRaises(ValueError):\n        assert i16_3 < int_too_big\n    with assertRaises(ValueError):\n        assert int_too_big < i16_3\n    with assertRaises(ValueError):\n        assert i16_3 > int_too_small\n    with assertRaises(ValueError):\n        assert int_too_small < i16_3\n\ndef test_mixed_arithmetic_and_bitwise_ops() -> None:\n    i16_3: i16 = int() + 3\n    int_5 = int() + 5\n    assert i16_3 + int_5 == 8\n    assert int_5 - i16_3 == 2\n    assert i16_3 << int_5 == 96\n    assert int_5 << i16_3  == 40\n    assert i16_3 ^ int_5 == 6\n    assert int_5 | i16_3  == 7\n\n    int_largest = int() + (1 << 15) - 1\n    assert int_largest - i16_3 == 32764\n    int_smallest = int() - (1 << 15)\n    assert int_smallest + i16_3 == -32765\n\n    int_too_big = int() + (1 << 15)\n    int_too_small = int() - (1 << 15) - 1\n    with assertRaises(ValueError):\n        assert i16_3 & int_too_big\n    with assertRaises(ValueError):\n        assert int_too_small & i16_3\n\ndef test_coerce_to_and_from_int() -> None:\n    for shift in range(0, 16):\n        for sign in 1, -1:\n            for delta in range(-5, 5):\n                n = sign * (1 << shift) + delta\n                if -(1 << 15) <= n < (1 << 15):\n                    x: i16 = n\n                    m: int = x\n                    assert m == n\n\ndef test_explicit_conversion_to_i16() -> None:\n    x = i16(5)\n    assert x == 5\n    y = int() - 113\n    x = i16(y)\n    assert x == -113\n    n64: i64 = 1733\n    x = i16(n64)\n    assert x == 1733\n    n32: i32 = -1733\n    x = i16(n32)\n    assert x == -1733\n    z = i16(x)\n    assert z == -1733\n\ndef test_explicit_conversion_overflow() -> None:\n    max_i16 = int() + 2**15 - 1\n    x = i16(max_i16)\n    assert x == 2**15 - 1\n    assert int(x) == max_i16\n\n    min_i16 = int() - 2**15\n    y = i16(min_i16)\n    assert y == -2**15\n    assert int(y) == min_i16\n\n    too_big = int() + 2**15\n    with assertRaises(ValueError):\n        x = i16(too_big)\n\n    too_small = int() - 2**15 - 1\n    with assertRaises(ValueError):\n        x = i16(too_small)\n\ndef test_i16_from_large_small_literal() -> None:\n    x = i16(2**15 - 1)\n    assert x == 2**15 - 1\n    x = i16(-2**15)\n    assert x == -2**15\n\ndef test_i16_truncate_from_i64() -> None:\n    large = i64(2**32 + 65536 + 157 + int())\n    x = i16(large)\n    assert x == 157\n    small = i64(-2**32 - 65536 - 157 + int())\n    x = i16(small)\n    assert x == -157\n    large2 = i64(2**15 + int())\n    x = i16(large2)\n    assert x == -2**15\n    small2 = i64(-2**15 - 1 - int())\n    x = i16(small2)\n    assert x == 2**15 - 1\n\ndef test_i16_truncate_from_i32() -> None:\n    large = i32(2**16 + 2**30 + 5 + int())\n    assert i16(large) == 5\n    small = i32(-2**16 - 2**30 - 1 + int())\n    assert i16(small) == -1\n\ndef from_float(x: float) -> i16:\n    return i16(x)\n\ndef test_explicit_conversion_from_float() -> None:\n    assert from_float(0.0) == 0\n    assert from_float(1.456) == 1\n    assert from_float(-1234.567) == -1234\n    assert from_float(2**15 - 1) == 2**15 - 1\n    assert from_float(-2**15) == -2**15\n    # The error message could be better, but this is acceptable\n    with assertRaises(ValueError, \"int too large to convert to i16\"):\n        assert from_float(float(2**15))\n    with assertRaises(ValueError, \"int too large to convert to i16\"):\n        # One ulp below the lowest valid i64 value\n        from_float(float(-2**15 - 1))\n\ndef test_tuple_i16() -> None:\n    a: i16 = 1\n    b: i16 = 2\n    t = (a, b)\n    a, b = t\n    assert a == 1\n    assert b == 2\n    x: Any = t\n    tt: Tuple[i16, i16] = x\n    assert tt == (1, 2)\n"
  },
  {
    "path": "mypyc/test-data/run-i32.test",
    "content": "[case testI32BasicOps]\nfrom typing import Any, Tuple\n\nfrom mypy_extensions import i16, i32, i64\n\nfrom testutil import assertRaises\n\ndef test_box_and_unbox() -> None:\n    values = (list(range(-2**31, -2**31 + 100)) +\n              list(range(-1000, 1000)) +\n              list(range(2**31 - 100, 2**31)))\n    for i in values:\n        o: Any = i\n        x: i32 = o\n        o2: Any = x\n        assert o == o2\n        assert x == i\n    with assertRaises(ValueError, \"int too large to convert to i32\"):\n        o = 2**31\n        x2: i32 = o\n    with assertRaises(ValueError, \"int too large to convert to i32\"):\n        o = -2**32 - 1\n        x3: i32 = o\n\ndef div_by_7(x: i32) -> i32:\n    return x // 7\ndef div_by_neg_7(x: i32) -> i32:\n    return x // -7\n\ndef div(x: i32, y: i32) -> i32:\n    return x // y\n\ndef test_divide_by_constant() -> None:\n    for i in range(-1000, 1000):\n        assert div_by_7(i) == i // 7\n    for i in range(-2**31, -2**31 + 1000):\n        assert div_by_7(i) == i // 7\n    for i in range(2**31 - 1000, 2**31):\n        assert div_by_7(i) == i // 7\n\ndef test_divide_by_negative_constant() -> None:\n    for i in range(-1000, 1000):\n        assert div_by_neg_7(i) == i // -7\n    for i in range(-2**31, -2**31 + 1000):\n        assert div_by_neg_7(i) == i // -7\n    for i in range(2**31 - 1000, 2**31):\n        assert div_by_neg_7(i) == i // -7\n\ndef test_divide_by_variable() -> None:\n    values = (list(range(-50, 50)) +\n              list(range(-2**31, -2**31 + 10)) +\n              list(range(2**31 - 10, 2**31)))\n    for x in values:\n        for y in values:\n            if y != 0:\n                if x // y == 2**31:\n                    with assertRaises(OverflowError, \"integer division overflow\"):\n                        div(x, y)\n                else:\n                    assert div(x, y) == x // y\n            else:\n                with assertRaises(ZeroDivisionError, \"integer division or modulo by zero\"):\n                    div(x, y)\n\ndef mod_by_7(x: i32) -> i32:\n    return x % 7\n\ndef mod_by_neg_7(x: i32) -> i32:\n    return x // -7\n\ndef mod(x: i32, y: i32) -> i32:\n    return x % y\n\ndef test_mod_by_constant() -> None:\n    for i in range(-1000, 1000):\n        assert mod_by_7(i) == i % 7\n    for i in range(-2**31, -2**31 + 1000):\n        assert mod_by_7(i) == i % 7\n    for i in range(2**31 - 1000, 2**31):\n        assert mod_by_7(i) == i % 7\n\ndef test_mod_by_negative_constant() -> None:\n    for i in range(-1000, 1000):\n        assert mod_by_neg_7(i) == i // -7\n    for i in range(-2**31, -2**31 + 1000):\n        assert mod_by_neg_7(i) == i // -7\n    for i in range(2**31 - 1000, 2**31):\n        assert mod_by_neg_7(i) == i // -7\n\ndef test_mod_by_variable() -> None:\n    values = (list(range(-50, 50)) +\n              list(range(-2**31, -2**31 + 10)) +\n              list(range(2**31 - 10, 2**31)))\n    for x in values:\n        for y in values:\n            if y != 0:\n                assert mod(x, y) == x % y\n            else:\n                with assertRaises(ZeroDivisionError, \"integer division or modulo by zero\"):\n                    mod(x, y)\n\ndef test_simple_arithmetic_ops() -> None:\n    zero: i32 = int()\n    one: i32 = zero + 1\n    two: i32 = one + 1\n    neg_one: i32 = -one\n    assert one + one == 2\n    assert one + two == 3\n    assert one + neg_one == 0\n    assert one - one == 0\n    assert one - two == -1\n    assert one * one == 1\n    assert one * two == 2\n    assert two * two == 4\n    assert two * neg_one == -2\n    assert neg_one * one == -1\n    assert neg_one * neg_one == 1\n    assert two * 0 == 0\n    assert 0 * two == 0\n    assert -one == -1\n    assert -two == -2\n    assert -neg_one == 1\n    assert -zero == 0\n\ndef test_bitwise_ops() -> None:\n    x: i32 = 1920687484 + int()\n    y: i32 = 383354614 + int()\n    z: i32 = -1879040563 + int()\n    zero: i32 = int()\n    one: i32 = zero + 1\n    two: i32 = zero + 2\n    neg_one: i32 = -one\n\n    assert x & y == 307823732\n    assert x & z == 268442956\n    assert z & z == z\n    assert x & zero == 0\n\n    assert x | y == 1996218366\n    assert x | z == -226796035\n    assert z | z == z\n    assert x | 0 == x\n\n    assert x ^ y == 1688394634\n    assert x ^ z == -495238991\n    assert z ^ z == 0\n    assert z ^ 0 == z\n\n    assert x << one == -453592328\n    assert x << two == -907184656\n    assert z << two == 1073772340\n    assert z << 0 == z\n\n    assert x >> one == 960343742\n    assert x >> two == 480171871\n    assert z >> two == -469760141\n    assert z >> 0 == z\n\n    assert ~x == -1920687485\n    assert ~z == 1879040562\n    assert ~zero == -1\n    assert ~neg_one == 0\n\ndef eq(x: i32, y: i32) -> bool:\n    return x == y\n\ndef test_eq() -> None:\n    assert eq(int(), int())\n    assert eq(5 + int(), 5 + int())\n    assert eq(-5 + int(), -5 + int())\n    assert not eq(int(), 1 + int())\n    assert not eq(5 + int(), 6 + int())\n    assert not eq(-5 + int(), -6 + int())\n    assert not eq(-5 + int(), 5 + int())\n\ndef test_comparisons() -> None:\n    one: i32 = 1 + int()\n    one2: i32 = 1 + int()\n    two: i32 = 2 + int()\n    assert one < two\n    assert not (one < one2)\n    assert not (two < one)\n    assert two > one\n    assert not (one > one2)\n    assert not (one > two)\n    assert one <= two\n    assert one <= one2\n    assert not (two <= one)\n    assert two >= one\n    assert one >= one2\n    assert not (one >= two)\n    assert one == one2\n    assert not (one == two)\n    assert one != two\n    assert not (one != one2)\n\ndef test_mixed_comparisons() -> None:\n    i32_3: i32 = int() + 3\n    int_5 = int() + 5\n    assert i32_3 < int_5\n    assert int_5 > i32_3\n    b = i32_3 > int_5\n    assert not b\n\n    int_largest = int() + (1 << 31) - 1\n    assert int_largest > i32_3\n    int_smallest = int() - (1 << 31)\n    assert i32_3 > int_smallest\n\n    int_too_big = int() + (1 << 31)\n    int_too_small = int() - (1 << 31) - 1\n    with assertRaises(ValueError):\n        assert i32_3 < int_too_big\n    with assertRaises(ValueError):\n        assert int_too_big < i32_3\n    with assertRaises(ValueError):\n        assert i32_3 > int_too_small\n    with assertRaises(ValueError):\n        assert int_too_small < i32_3\n\ndef test_mixed_arithmetic_and_bitwise_ops() -> None:\n    i32_3: i32 = int() + 3\n    int_5 = int() + 5\n    assert i32_3 + int_5 == 8\n    assert int_5 - i32_3 == 2\n    assert i32_3 << int_5 == 96\n    assert int_5 << i32_3  == 40\n    assert i32_3 ^ int_5 == 6\n    assert int_5 | i32_3  == 7\n\n    int_largest = int() + (1 << 31) - 1\n    assert int_largest - i32_3 == 2147483644\n    int_smallest = int() - (1 << 31)\n    assert int_smallest + i32_3 == -2147483645\n\n    int_too_big = int() + (1 << 31)\n    int_too_small = int() - (1 << 31) - 1\n    with assertRaises(ValueError):\n        assert i32_3 & int_too_big\n    with assertRaises(ValueError):\n        assert int_too_small & i32_3\n\ndef test_coerce_to_and_from_int() -> None:\n    for shift in range(0, 32):\n        for sign in 1, -1:\n            for delta in range(-5, 5):\n                n = sign * (1 << shift) + delta\n                if -(1 << 31) <= n < (1 << 31):\n                    x: i32 = n\n                    m: int = x\n                    assert m == n\n\ndef test_explicit_conversion_to_i32() -> None:\n    x = i32(5)\n    assert x == 5\n    y = int() - 113\n    x = i32(y)\n    assert x == -113\n    n64: i64 = 1733\n    x = i32(n64)\n    assert x == 1733\n    n32: i32 = -1733\n    x = i32(n32)\n    assert x == -1733\n    z = i32(x)\n    assert z == -1733\n    a: i16 = int() + 19764\n    assert i32(a) == 19764\n    a = int() - 1\n    assert i32(a) == -1\n\ndef test_explicit_conversion_overflow() -> None:\n    max_i32 = int() + 2**31 - 1\n    x = i32(max_i32)\n    assert x == 2**31 - 1\n    assert int(x) == max_i32\n\n    min_i32 = int() - 2**31\n    y = i32(min_i32)\n    assert y == -2**31\n    assert int(y) == min_i32\n\n    too_big = int() + 2**31\n    with assertRaises(ValueError):\n        x = i32(too_big)\n\n    too_small = int() - 2**31 - 1\n    with assertRaises(ValueError):\n        x = i32(too_small)\n\ndef test_i32_from_large_small_literal() -> None:\n    x = i32(2**31 - 1)\n    assert x == 2**31 - 1\n    x = i32(-2**31)\n    assert x == -2**31\n\ndef test_i32_truncate_from_i64() -> None:\n    large = i64(2**32 + 157 + int())\n    x = i32(large)\n    assert x == 157\n    small = i64(-2**32 - 157 + int())\n    x = i32(small)\n    assert x == -157\n    large2 = i64(2**31 + int())\n    x = i32(large2)\n    assert x == -2**31\n    small2 = i64(-2**31 - 1 - int())\n    x = i32(small2)\n    assert x == 2**31 - 1\n\ndef from_float(x: float) -> i32:\n    return i32(x)\n\ndef test_explicit_conversion_from_float() -> None:\n    assert from_float(0.0) == 0\n    assert from_float(1.456) == 1\n    assert from_float(-1234.567) == -1234\n    assert from_float(2**31 - 1) == 2**31 - 1\n    assert from_float(-2**31) == -2**31\n    # The error message could be better, but this is acceptable\n    with assertRaises(ValueError, \"int too large to convert to i32\"):\n        assert from_float(float(2**31))\n    with assertRaises(ValueError, \"int too large to convert to i32\"):\n        # One ulp below the lowest valid i64 value\n        from_float(float(-2**31 - 2048))\n\ndef test_tuple_i32() -> None:\n    a: i32 = 1\n    b: i32 = 2\n    t = (a, b)\n    a, b = t\n    assert a == 1\n    assert b == 2\n    x: Any = t\n    tt: Tuple[i32, i32] = x\n    assert tt == (1, 2)\n"
  },
  {
    "path": "mypyc/test-data/run-i64.test",
    "content": "[case testI64BasicOps]\nfrom typing import List, Any, Tuple, Union\n\nfrom mypy_extensions import i64, i32, i16\n\nfrom testutil import assertRaises\n\ndef inc(n: i64) -> i64:\n    return n + 1\n\ndef test_inc() -> None:\n    # Use int() to avoid constant folding\n    n = 1 + int()\n    m = 2 + int()\n    assert inc(n) == m\n\ndef min_ll(x: i64, y: i64) -> i64:\n    if x < y:\n        return x\n    else:\n        return y\n\ndef test_min() -> None:\n    assert min_ll(1 + int(), 2) == 1\n    assert min_ll(2 + int(), 1) == 1\n    assert min_ll(1 + int(), 1) == 1\n    assert min_ll(-2 + int(), 1) == -2\n    assert min_ll(1 + int(), -2) == -2\n\ndef eq(x: i64, y: i64) -> bool:\n    return x == y\n\ndef test_eq() -> None:\n    assert eq(int(), int())\n    assert eq(5 + int(), 5 + int())\n    assert eq(-5 + int(), -5 + int())\n    assert not eq(int(), 1 + int())\n    assert not eq(5 + int(), 6 + int())\n    assert not eq(-5 + int(), -6 + int())\n    assert not eq(-5 + int(), 5 + int())\n\ndef test_comparisons() -> None:\n    one: i64 = 1 + int()\n    one2: i64 = 1 + int()\n    two: i64 = 2 + int()\n    assert one < two\n    assert not (one < one2)\n    assert not (two < one)\n    assert two > one\n    assert not (one > one2)\n    assert not (one > two)\n    assert one <= two\n    assert one <= one2\n    assert not (two <= one)\n    assert two >= one\n    assert one >= one2\n    assert not (one >= two)\n    assert one == one2\n    assert not (one == two)\n    assert one != two\n    assert not (one != one2)\n\ndef is_true(x: i64) -> bool:\n    if x:\n        return True\n    else:\n        return False\n\ndef is_true2(x: i64) -> bool:\n    return bool(x)\n\ndef is_false(x: i64) -> bool:\n    if not x:\n        return True\n    else:\n        return False\n\ndef test_i64_as_bool() -> None:\n    assert not is_true(0)\n    assert not is_true2(0)\n    assert is_false(0)\n    for x in 1, 55, -1, -7, 1 << 40, -(1 << 50):\n        assert is_true(x)\n        assert is_true2(x)\n        assert not is_false(x)\n\ndef bool_as_i64(b: bool) -> i64:\n    return b\n\ndef test_bool_as_i64() -> None:\n    assert bool_as_i64(False) == 0\n    assert bool_as_i64(True) == 1\n\ndef div_by_3(x: i64) -> i64:\n    return x // 3\n\ndef div_by_neg_3(x: i64) -> i64:\n    return x // -3\n\ndef div(x: i64, y: i64) -> i64:\n    return x // y\n\ndef test_divide_by_constant() -> None:\n    for i in range(-1000, 1000):\n        assert div_by_3(i) == i // 3\n    for i in range(-2**63, -2**63 + 1000):\n        assert div_by_3(i) == i // 3\n    for i in range(2**63 - 1000, 2**63):\n        assert div_by_3(i) == i // 3\n\ndef test_divide_by_negative_constant() -> None:\n    for i in range(-1000, 1000):\n        assert div_by_neg_3(i) == i // -3\n    for i in range(-2**63, -2**63 + 1000):\n        assert div_by_neg_3(i) == i // -3\n    for i in range(2**63 - 1000, 2**63):\n        assert div_by_neg_3(i) == i // -3\n\ndef test_divide_by_variable() -> None:\n    values = (list(range(-50, 50)) +\n              list(range(-2**63, -2**63 + 10)) +\n              list(range(2**63 - 10, 2**63)))\n    for x in values:\n        for y in values:\n            if y != 0:\n                if x // y == 2**63:\n                    with assertRaises(OverflowError, \"integer division overflow\"):\n                        div(x, y)\n                else:\n                    assert div(x, y) == x // y\n            else:\n                with assertRaises(ZeroDivisionError, \"integer division or modulo by zero\"):\n                    div(x, y)\n\ndef mod_by_7(x: i64) -> i64:\n    return x % 7\n\ndef mod_by_neg_7(x: i64) -> i64:\n    return x // -7\n\ndef mod(x: i64, y: i64) -> i64:\n    return x % y\n\ndef test_mod_by_constant() -> None:\n    for i in range(-1000, 1000):\n        assert mod_by_7(i) == i % 7\n    for i in range(-2**63, -2**63 + 1000):\n        assert mod_by_7(i) == i % 7\n    for i in range(2**63 - 1000, 2**63):\n        assert mod_by_7(i) == i % 7\n\ndef test_mod_by_negative_constant() -> None:\n    for i in range(-1000, 1000):\n        assert mod_by_neg_7(i) == i // -7\n    for i in range(-2**63, -2**63 + 1000):\n        assert mod_by_neg_7(i) == i // -7\n    for i in range(2**63 - 1000, 2**63):\n        assert mod_by_neg_7(i) == i // -7\n\ndef test_mod_by_variable() -> None:\n    values = (list(range(-50, 50)) +\n              list(range(-2**63, -2**63 + 10)) +\n              list(range(2**63 - 10, 2**63)))\n    for x in values:\n        for y in values:\n            if y != 0:\n                assert mod(x, y) == x % y\n            else:\n                with assertRaises(ZeroDivisionError, \"integer division or modulo by zero\"):\n                    mod(x, y)\n\ndef get_item(a: List[i64], n: i64) -> i64:\n    return a[n]\n\ndef test_get_list_item() -> None:\n    a = [1, 6, -2]\n    assert get_item(a, 0) == 1\n    assert get_item(a, 1) == 6\n    assert get_item(a, 2) == -2\n    assert get_item(a, -1) == -2\n    assert get_item(a, -2) == 6\n    assert get_item(a, -3) == 1\n    with assertRaises(IndexError, \"list index out of range\"):\n        get_item(a, 3)\n    with assertRaises(IndexError, \"list index out of range\"):\n        get_item(a, -4)\n    # TODO: Very large/small values and indexes\n\ndef test_simple_arithmetic_ops() -> None:\n    zero: i64 = int()\n    one: i64 = zero + 1\n    two: i64 = one + 1\n    neg_one: i64 = -one\n    assert one + one == 2\n    assert one + two == 3\n    assert one + neg_one == 0\n    assert one - one == 0\n    assert one - two == -1\n    assert one * one == 1\n    assert one * two == 2\n    assert two * two == 4\n    assert two * neg_one == -2\n    assert neg_one * one == -1\n    assert neg_one * neg_one == 1\n    assert two * 0 == 0\n    assert 0 * two == 0\n    assert -one == -1\n    assert -two == -2\n    assert -neg_one == 1\n    assert -zero == 0\n\ndef test_bitwise_ops() -> None:\n    x: i64 = 7997307308812232241 + int()\n    y: i64 = 4333433528471475340 + int()\n    z: i64 = -2462230749488444526 + int()\n    zero: i64 = int()\n    one: i64 = zero + 1\n    two: i64 = zero + 2\n    neg_one: i64 = -one\n\n    assert x & y == 3179577071592752128\n    assert x & z == 5536089561888850448\n    assert z & z == z\n    assert x & zero == 0\n\n    assert x | y == 9151163765690955453\n    assert x | z == -1013002565062733\n    assert z | z == z\n    assert x | 0 == x\n\n    assert x ^ y == 5971586694098203325\n    assert x ^ z == -5537102564453913181\n    assert z ^ z == 0\n    assert z ^ 0 == z\n\n    assert x << one == -2452129456085087134\n    assert x << two == -4904258912170174268\n    assert z << two == 8597821075755773512\n    assert z << 0 == z\n\n    assert x >> one == 3998653654406116120\n    assert x >> two == 1999326827203058060\n    assert z >> two == -615557687372111132\n    assert z >> 0 == z\n\n    assert ~x == -7997307308812232242\n    assert ~z == 2462230749488444525\n    assert ~zero == -1\n    assert ~neg_one == 0\n\ndef test_coerce_to_and_from_int() -> None:\n    for shift in range(0, 64):\n        for sign in 1, -1:\n            for delta in range(-5, 5):\n                n = sign * (1 << shift) + delta\n                if -(1 << 63) <= n < (1 << 63):\n                    x: i64 = n\n                    m: int = x\n                    assert m == n\n\ndef test_coerce_to_and_from_int2() -> None:\n    for shift in range(0, 64):\n        for sign in 1, -1:\n            for delta in range(-5, 5):\n                n = sign * (1 << shift) + delta\n                if -(1 << 63) <= n < (1 << 63):\n                    x: i64 = i64(n)\n                    m: int = int(x)\n                    assert m == n\n\ndef test_explicit_conversion_to_i64() -> None:\n    x = i64(5)\n    assert x == 5\n    y = int() - 113\n    x = i64(y)\n    assert x == -113\n    n32: i32 = 1733\n    x = i64(n32)\n    assert x == 1733\n    n32 = -1733\n    x = i64(n32)\n    assert x == -1733\n    z = i64(x)\n    assert z == -1733\n    a: i16 = int() + 19764\n    assert i64(a) == 19764\n    a = int() - 1\n    assert i64(a) == -1\n\ndef test_explicit_conversion_overflow() -> None:\n    max_i64 = int() + 2**63 - 1\n    x = i64(max_i64)\n    assert x == 2**63 - 1\n    assert int(x) == max_i64\n\n    min_i64 = int() - 2**63\n    y = i64(min_i64)\n    assert y == -2**63\n    assert int(y) == min_i64\n\n    too_big = int() + 2**63\n    with assertRaises(ValueError):\n        x = i64(too_big)\n\n    too_small = int() - 2**63 - 1\n    with assertRaises(ValueError):\n        x = i64(too_small)\n\ndef test_i64_from_large_small_literal() -> None:\n    x = i64(2**63 - 1)\n    assert x == 2**63 - 1\n    x = i64(-2**63)\n    assert x == -2**63\n\ndef from_float(x: float) -> i64:\n    return i64(x)\n\ndef test_explicit_conversion_from_float() -> None:\n    assert from_float(0.0) == 0\n    assert from_float(1.456) == 1\n    assert from_float(-1234.567) == -1234\n    # Subtract 1024 due to limited precision of 64-bit floats\n    assert from_float(2**63 - 1024) == 2**63 - 1024\n    assert from_float(-2**63) == -2**63\n    # The error message could be better, but this is acceptable\n    with assertRaises(ValueError, \"int too large to convert to i64\"):\n        assert from_float(float(2**63))\n    with assertRaises(ValueError, \"int too large to convert to i64\"):\n        # One ulp below the lowest valid i64 value\n        from_float(float(-2**63 - 2048))\n\ndef from_str(s: str) -> i64:\n    return i64(s)\n\ndef test_explicit_conversion_from_str() -> None:\n    assert from_str(\"0\") == 0\n    assert from_str(\"1\") == 1\n    assert from_str(\"-1234\") == -1234\n    with assertRaises(ValueError):\n        from_str(\"1.2\")\n\ndef from_str_with_base(s: str, base: int) -> i64:\n    return i64(s, base)\n\ndef test_explicit_conversion_from_str_with_base() -> None:\n    assert from_str_with_base(\"101\", 2) == 5\n    assert from_str_with_base(\"109\", 10) == 109\n    assert from_str_with_base(\"-f0A\", 16) == -3850\n    assert from_str_with_base(\"0x1a\", 16) == 26\n    assert from_str_with_base(\"0X1A\", 16) == 26\n    with assertRaises(ValueError):\n        from_str_with_base(\"1.2\", 16)\n\ndef from_bool(b: bool) -> i64:\n    return i64(b)\n\ndef test_explicit_conversion_from_bool() -> None:\n    assert from_bool(True) == 1\n    assert from_bool(False) == 0\n\nclass IntConv:\n    def __init__(self, x: i64) -> None:\n        self.x = x\n\n    def __int__(self) -> i64:\n        return self.x + 1\n\ndef test_explicit_conversion_from_instance() -> None:\n    assert i64(IntConv(0)) == 1\n    assert i64(IntConv(12345)) == 12346\n    assert i64(IntConv(-23)) == -22\n\ndef test_explicit_conversion_from_any() -> None:\n    # This can't be specialized\n    a: Any = \"101\"\n    assert i64(a, base=2) == 5\n\ndef test_tuple_i64() -> None:\n    a: i64 = 1\n    b: i64 = 2\n    t = (a, b)\n    a, b = t\n    assert a == 1\n    assert b == 2\n    x: Any = t\n    tt: Tuple[i64, i64] = x\n    assert tt == (1, 2)\n\ndef test_list_set_item() -> None:\n    a: List[i64] = [0, 2, 6]\n    z: i64 = int()\n    a[z] = 1\n    assert a == [1, 2, 6]\n    a[z + 2] = 9\n    assert a == [1, 2, 9]\n    a[-(z + 1)] = 10\n    assert a == [1, 2, 10]\n    a[-(z + 3)] = 3\n    assert a == [3, 2, 10]\n    with assertRaises(IndexError):\n        a[z + 3] = 0\n    with assertRaises(IndexError):\n        a[-(z + 4)] = 0\n    assert a == [3, 2, 10]\n\nclass C:\n    def __init__(self, x: i64) -> None:\n        self.x = x\n\ndef test_attributes() -> None:\n    i: i64\n    for i in range(-1000, 1000):\n        c = C(i)\n        assert c.x == i\n        c.x = i + 1\n        assert c.x == i + 1\n\ndef test_mixed_comparisons() -> None:\n    i64_3: i64 = int() + 3\n    int_5 = int() + 5\n    assert i64_3 < int_5\n    assert int_5 > i64_3\n    b = i64_3 > int_5\n    assert not b\n\n    int_largest = int() + (1 << 63) - 1\n    assert int_largest > i64_3\n    int_smallest = int() - (1 << 63)\n    assert i64_3 > int_smallest\n\n    int_too_big = int() + (1 << 63)\n    int_too_small = int() - (1 << 63) - 1\n    with assertRaises(ValueError):\n        assert i64_3 < int_too_big\n    with assertRaises(ValueError):\n        assert int_too_big < i64_3\n    with assertRaises(ValueError):\n        assert i64_3 > int_too_small\n    with assertRaises(ValueError):\n        assert int_too_small < i64_3\n\ndef test_mixed_comparisons_32bit() -> None:\n    # Test edge cases on 32-bit platforms\n    i64_3: i64 = int() + 3\n    int_5 = int() + 5\n\n    int_largest_short = int() + (1 << 30) - 1\n    int_largest_short_i64: i64 = int_largest_short\n    assert int_largest_short > i64_3\n    int_smallest_short = int() - (1 << 30)\n    int_smallest_short_i64: i64 = int_smallest_short\n    assert i64_3 > int_smallest_short\n\n    int_big = int() + (1 << 30)\n    assert int_big > i64_3\n    int_small = int() - (1 << 30) - 1\n    assert i64_3 > int_small\n\n    assert int_smallest_short_i64 > int_small\n    assert int_largest_short_i64 < int_big\n\ndef test_mixed_arithmetic_and_bitwise_ops() -> None:\n    i64_3: i64 = int() + 3\n    int_5 = int() + 5\n    assert i64_3 + int_5 == 8\n    assert int_5 - i64_3 == 2\n    assert i64_3 << int_5 == 96\n    assert int_5 << i64_3  == 40\n    assert i64_3 ^ int_5 == 6\n    assert int_5 | i64_3  == 7\n\n    int_largest = int() + (1 << 63) - 1\n    assert int_largest - i64_3 == 9223372036854775804\n    int_smallest = int() - (1 << 63)\n    assert int_smallest + i64_3 == -9223372036854775805\n\n    int_too_big = int() + (1 << 63)\n    int_too_small = int() - (1 << 63) - 1\n    with assertRaises(ValueError):\n        assert i64_3 & int_too_big\n    with assertRaises(ValueError):\n        assert int_too_small & i64_3\n\ndef test_for_loop() -> None:\n    n: i64 = 0\n    for i in range(i64(5 + int())):\n        n += i\n    assert n == 10\n    n = 0\n    for i in range(i64(5)):\n        n += i\n    assert n == 10\n    n = 0\n    for i in range(i64(2 + int()), 5 + int()):\n        n += i\n    assert n == 9\n    n = 0\n    for i in range(2, i64(5 + int())):\n        n += i\n    assert n == 9\n    assert sum([x * x for x in range(i64(4 + int()))]) == 1 + 4 + 9\n\ndef narrow1(x: Union[str, i64]) -> i64:\n    if isinstance(x, i64):\n        return x\n    return len(x)\n\ndef narrow2(x: Union[str, i64]) -> i64:\n    if isinstance(x, int):\n        return x\n    return len(x)\n\ndef test_isinstance() -> None:\n    assert narrow1(123) == 123\n    assert narrow1(\"foobar\") == 6\n    assert narrow2(123) == 123\n    assert narrow2(\"foobar\") == 6\n\n[case testI64ErrorValuesAndUndefined]\nfrom typing import Any, Final, Tuple\nimport sys\n\nfrom mypy_extensions import mypyc_attr, i64\n\nfrom testutil import assertRaises\n\ndef maybe_raise(n: i64, error: bool) -> i64:\n    if error:\n        raise ValueError()\n    return n\n\ndef test_error_value() -> None:\n    for i in range(-1000, 1000):\n        assert maybe_raise(i, False) == i\n    with assertRaises(ValueError):\n        maybe_raise(0, True)\n\nclass C:\n    def maybe_raise(self, n: i64, error: bool) -> i64:\n        if error:\n            raise ValueError()\n        return n\n\ndef test_method_error_value() -> None:\n    for i in range(-1000, 1000):\n        assert C().maybe_raise(i, False) == i\n    with assertRaises(ValueError):\n        C().maybe_raise(0, True)\n\ndef maybe_raise_tuple(n: i64, error: bool) -> Tuple[i64, i64]:\n    if error:\n        raise ValueError()\n    return n, n+ 1\n\ndef test_tuple_error_value() -> None:\n    for i in range(-1000, 1000):\n        assert maybe_raise_tuple(i, False) == (i, i + 1)\n    with assertRaises(ValueError):\n        maybe_raise_tuple(0, True)\n    f: Any = maybe_raise_tuple\n    for i in range(-1000, 1000):\n        assert f(i, False) == (i, i + 1)\n    with assertRaises(ValueError):\n        f(0, True)\n\ndef maybe_raise_tuple2(n: i64, error: bool) -> Tuple[i64, int]:\n    if error:\n        raise ValueError()\n    return n, n+ 1\n\ndef test_tuple_error_value_2() -> None:\n    for i in range(-1000, 1000):\n        assert maybe_raise_tuple2(i, False) == (i, i + 1)\n    with assertRaises(ValueError):\n        maybe_raise_tuple(0, True)\n\ndef test_unbox_int() -> None:\n    for i in list(range(-1000, 1000)) + [-(1 << 63), (1 << 63) - 1]:\n        o: Any = i\n        x: i64 = i\n        assert x == i\n        y: i64 = o\n        assert y == i\n\ndef test_unbox_int_fails() -> None:\n    o: Any = 'x'\n    if sys.version_info[0] == 3 and sys.version_info[1] < 10:\n        msg = \"an integer is required (got type str)\"\n    else:\n        msg = \"'str' object cannot be interpreted as an integer\"\n    with assertRaises(TypeError, msg):\n        x: i64 = o\n    o2: Any = 1 << 63\n    with assertRaises(ValueError, \"int too large to convert to i64\"):\n        y: i64 = o2\n    o3: Any = -(1 << 63 + 1)\n    with assertRaises(ValueError, \"int too large to convert to i64\"):\n        z: i64 = o3\n\nclass Uninit:\n    x: i64\n    y: i64 = 0\n    z: i64\n\nclass Derived(Uninit):\n    a: i64 = 1\n    b: i64\n    c: i64 = 2\n\nclass Derived2(Derived):\n    h: i64\n\ndef test_uninitialized_attr() -> None:\n    o = Uninit()\n    assert o.y == 0\n    with assertRaises(AttributeError):\n        o.x\n    with assertRaises(AttributeError):\n        o.z\n    o.x = 1\n    assert o.x == 1\n    with assertRaises(AttributeError):\n        o.z\n    o.z = 2\n    assert o.z == 2\n\n# This is the error value, but it's also a valid normal value\nMAGIC: Final = -113\n\ndef test_magic_value() -> None:\n    o = Uninit()\n    o.x = MAGIC\n    assert o.x == MAGIC\n    with assertRaises(AttributeError):\n        o.z\n    o.z = MAGIC\n    assert o.x == MAGIC\n    assert o.z == MAGIC\n\ndef test_magic_value_via_any() -> None:\n    o: Any = Uninit()\n    with assertRaises(AttributeError):\n        o.x\n    with assertRaises(AttributeError):\n        o.z\n    o.x = MAGIC\n    assert o.x == MAGIC\n    with assertRaises(AttributeError):\n        o.z\n    o.z = MAGIC\n    assert o.z == MAGIC\n\ndef test_magic_value_and_inheritance() -> None:\n    o = Derived2()\n    o.x = MAGIC\n    assert o.x == MAGIC\n    with assertRaises(AttributeError):\n        o.z\n    with assertRaises(AttributeError):\n        o.b\n    with assertRaises(AttributeError):\n        o.h\n    o.z = MAGIC\n    assert o.z == MAGIC\n    with assertRaises(AttributeError):\n        o.b\n    with assertRaises(AttributeError):\n        o.h\n    o.h = MAGIC\n    assert o.h == MAGIC\n    with assertRaises(AttributeError):\n        o.b\n    o.b = MAGIC\n    assert o.b == MAGIC\n\n@mypyc_attr(allow_interpreted_subclasses=True)\nclass MagicInit:\n    x: i64 = MAGIC\n\ndef test_magic_value_as_initializer() -> None:\n    o = MagicInit()\n    assert o.x == MAGIC\n\nclass ManyUninit:\n    a1: i64\n    a2: i64\n    a3: i64\n    a4: i64\n    a5: i64\n    a6: i64\n    a7: i64\n    a8: i64\n    a9: i64\n    a10: i64\n    a11: i64\n    a12: i64\n    a13: i64\n    a14: i64\n    a15: i64\n    a16: i64\n    a17: i64\n    a18: i64\n    a19: i64\n    a20: i64\n    a21: i64\n    a22: i64\n    a23: i64\n    a24: i64\n    a25: i64\n    a26: i64\n    a27: i64\n    a28: i64\n    a29: i64\n    a30: i64\n    a31: i64\n    a32: i64\n    a33: i64\n    a34: i64\n    a35: i64\n    a36: i64\n    a37: i64\n    a38: i64\n    a39: i64\n    a40: i64\n    a41: i64\n    a42: i64\n    a43: i64\n    a44: i64\n    a45: i64\n    a46: i64\n    a47: i64\n    a48: i64\n    a49: i64\n    a50: i64\n    a51: i64\n    a52: i64\n    a53: i64\n    a54: i64\n    a55: i64\n    a56: i64\n    a57: i64\n    a58: i64\n    a59: i64\n    a60: i64\n    a61: i64\n    a62: i64\n    a63: i64\n    a64: i64\n    a65: i64\n    a66: i64\n    a67: i64\n    a68: i64\n    a69: i64\n    a70: i64\n    a71: i64\n    a72: i64\n    a73: i64\n    a74: i64\n    a75: i64\n    a76: i64\n    a77: i64\n    a78: i64\n    a79: i64\n    a80: i64\n    a81: i64\n    a82: i64\n    a83: i64\n    a84: i64\n    a85: i64\n    a86: i64\n    a87: i64\n    a88: i64\n    a89: i64\n    a90: i64\n    a91: i64\n    a92: i64\n    a93: i64\n    a94: i64\n    a95: i64\n    a96: i64\n    a97: i64\n    a98: i64\n    a99: i64\n    a100: i64\n\ndef test_many_uninitialized_attributes() -> None:\n    o = ManyUninit()\n    with assertRaises(AttributeError):\n        o.a1\n    with assertRaises(AttributeError):\n        o.a10\n    with assertRaises(AttributeError):\n        o.a20\n    with assertRaises(AttributeError):\n        o.a30\n    with assertRaises(AttributeError):\n        o.a31\n    with assertRaises(AttributeError):\n        o.a32\n    with assertRaises(AttributeError):\n        o.a33\n    with assertRaises(AttributeError):\n        o.a40\n    with assertRaises(AttributeError):\n        o.a50\n    with assertRaises(AttributeError):\n        o.a60\n    with assertRaises(AttributeError):\n        o.a62\n    with assertRaises(AttributeError):\n        o.a63\n    with assertRaises(AttributeError):\n        o.a64\n    with assertRaises(AttributeError):\n        o.a65\n    with assertRaises(AttributeError):\n        o.a80\n    with assertRaises(AttributeError):\n        o.a100\n    o.a30 = MAGIC\n    assert o.a30 == MAGIC\n    o.a31 = MAGIC\n    assert o.a31 == MAGIC\n    o.a32 = MAGIC\n    assert o.a32 == MAGIC\n    o.a33 = MAGIC\n    assert o.a33 == MAGIC\n    with assertRaises(AttributeError):\n        o.a34\n    o.a62 = MAGIC\n    assert o.a62 == MAGIC\n    o.a63 = MAGIC\n    assert o.a63 == MAGIC\n    o.a64 = MAGIC\n    assert o.a64 == MAGIC\n    o.a65 = MAGIC\n    assert o.a65 == MAGIC\n    with assertRaises(AttributeError):\n        o.a66\n\nclass BaseNoBitmap:\n    x: int = 5\n\nclass DerivedBitmap(BaseNoBitmap):\n    # Subclass needs a bitmap, but base class doesn't have it.\n    y: i64\n\ndef test_derived_adds_bitmap() -> None:\n    d = DerivedBitmap()\n    d.x = 643\n    b: BaseNoBitmap = d\n    assert b.x == 643\n\nclass Delete:\n    __deletable__ = ['x', 'y']\n    x: i64\n    y: i64\n\ndef test_del() -> None:\n    o = Delete()\n    o.x = MAGIC\n    o.y = -1\n    assert o.x == MAGIC\n    assert o.y == -1\n    del o.x\n    with assertRaises(AttributeError):\n        o.x\n    assert o.y == -1\n    del o.y\n    with assertRaises(AttributeError):\n        o.y\n    o.x = 5\n    assert o.x == 5\n    with assertRaises(AttributeError):\n        o.y\n    del o.x\n    with assertRaises(AttributeError):\n        o.x\n\nclass UndefinedTuple:\n    def __init__(self, x: i64, y: i64) -> None:\n        if x != 0:\n            self.t = (x, y)\n\ndef test_undefined_native_int_tuple() -> None:\n    o = UndefinedTuple(MAGIC, MAGIC)\n    assert o.t[0] == MAGIC\n    assert o.t[1] == MAGIC\n    o = UndefinedTuple(0, 0)\n    with assertRaises(AttributeError):\n        o.t\n    o = UndefinedTuple(-13, 45)\n    assert o.t == (-13, 45)\n\ndef test_undefined_native_int_tuple_via_any() -> None:\n    cls: Any = UndefinedTuple\n    o: Any = cls(MAGIC, MAGIC)\n    assert o.t[0] == MAGIC\n    assert o.t[1] == MAGIC\n    o = cls(0, 0)\n    with assertRaises(AttributeError):\n        o.t\n    o = UndefinedTuple(-13, 45)\n    assert o.t == (-13, 45)\n\n[case testI64DefaultArgValues]\nfrom typing import Any, Final, Iterator, Tuple\n\nMAGIC: Final = -113\n\nfrom mypy_extensions import i64\n\ndef f(x: i64, y: i64 = 5) -> i64:\n    return x + y\n\ndef test_simple_default_arg() -> None:\n    assert f(3) == 8\n    assert f(4, 9) == 13\n    assert f(5, MAGIC) == -108\n    for i in range(-1000, 1000):\n        assert f(1, i) == 1 + i\n    f2: Any = f\n    assert f2(3) == 8\n    assert f2(4, 9) == 13\n    assert f2(5, MAGIC) == -108\n\ndef g(a: i64, b: i64 = 1, c: int = 2, d: i64 = 3) -> i64:\n    return a + b + c + d\n\ndef test_two_default_args() -> None:\n    assert g(10) == 16\n    assert g(10, 2) == 17\n    assert g(10, 2, 3) == 18\n    assert g(10, 2, 3, 4) == 19\n    g2: Any = g\n    assert g2(10) == 16\n    assert g2(10, 2) == 17\n    assert g2(10, 2, 3) == 18\n    assert g2(10, 2, 3, 4) == 19\n\nclass C:\n    def __init__(self) -> None:\n        self.i: i64 = 1\n\n    def m(self, a: i64, b: i64 = 1, c: int = 2, d: i64 = 3) -> i64:\n        return self.i + a + b + c + d\n\nclass D(C):\n    def m(self, a: i64, b: i64 = 2, c: int = 3, d: i64 = 4) -> i64:\n        return self.i + a + b + c + d\n\n    def mm(self, a: i64 = 2, b: i64 = 1) -> i64:\n        return self.i + a + b\n\n    @staticmethod\n    def s(a: i64 = 2, b: i64 = 1) -> i64:\n        return a + b\n\n    @classmethod\n    def c(cls, a: i64 = 2, b: i64 = 3) -> i64:\n        assert cls is D\n        return a + b\n\ndef test_method_default_args() -> None:\n    a = [C(), D()]\n    assert a[0].m(4) == 11\n    d = D()\n    assert d.mm() == 4\n    assert d.mm(5) == 7\n    assert d.mm(MAGIC) == MAGIC + 2\n    assert d.mm(b=5) == 8\n    assert D.mm(d) == 4\n    assert D.mm(d, 6) == 8\n    assert D.mm(d, MAGIC) == MAGIC + 2\n    assert D.mm(d, b=6) == 9\n    dd: Any = d\n    assert dd.mm() == 4\n    assert dd.mm(5) == 7\n    assert dd.mm(MAGIC) == MAGIC + 2\n    assert dd.mm(b=5) == 8\n\ndef test_static_method_default_args() -> None:\n    d = D()\n    assert d.s() == 3\n    assert d.s(5) == 6\n    assert d.s(MAGIC) == MAGIC + 1\n    assert d.s(5, 6) == 11\n    assert D.s() == 3\n    assert D.s(5) == 6\n    assert D.s(MAGIC) == MAGIC + 1\n    assert D.s(5, 6) == 11\n    dd: Any = d\n    assert dd.s() == 3\n    assert dd.s(5) == 6\n    assert dd.s(MAGIC) == MAGIC + 1\n    assert dd.s(5, 6) == 11\n\ndef test_class_method_default_args() -> None:\n    d = D()\n    assert d.c() == 5\n    assert d.c(5) == 8\n    assert d.c(MAGIC) == MAGIC + 3\n    assert d.c(b=5) == 7\n    assert D.c() == 5\n    assert D.c(5) == 8\n    assert D.c(MAGIC) == MAGIC + 3\n    assert D.c(b=5) == 7\n    dd: Any = d\n    assert dd.c() == 5\n    assert dd.c(5) == 8\n    assert dd.c(MAGIC) == MAGIC + 3\n    assert dd.c(b=5) == 7\n\nclass Init:\n    def __init__(self, x: i64 = 2, y: i64 = 5) -> None:\n        self.x = x\n        self.y = y\n\ndef test_init_default_args() -> None:\n    o = Init()\n    assert o.x == 2\n    assert o.y == 5\n    o = Init(7, 8)\n    assert o.x == 7\n    assert o.y == 8\n    o = Init(4)\n    assert o.x == 4\n    assert o.y == 5\n    o = Init(MAGIC, MAGIC)\n    assert o.x == MAGIC\n    assert o.y == MAGIC\n    o = Init(3, MAGIC)\n    assert o.x == 3\n    assert o.y == MAGIC\n    o = Init(MAGIC, 11)\n    assert o.x == MAGIC\n    assert o.y == 11\n    o = Init(MAGIC)\n    assert o.x == MAGIC\n    assert o.y == 5\n    o = Init(y=MAGIC)\n    assert o.x == 2\n    assert o.y == MAGIC\n\ndef kw_only(*, a: i64 = 1, b: int = 2, c: i64 = 3) -> i64:\n    return a + b + c * 2\n\ndef test_kw_only_default_args() -> None:\n    assert kw_only() == 9\n    assert kw_only(a=2) == 10\n    assert kw_only(b=4) == 11\n    assert kw_only(c=11) == 25\n    assert kw_only(a=2, c=4) == 12\n    assert kw_only(c=4, a=2) == 12\n    kw_only2: Any = kw_only\n    assert kw_only2() == 9\n    assert kw_only2(a=2) == 10\n    assert kw_only2(b=4) == 11\n    assert kw_only2(c=11) == 25\n    assert kw_only2(a=2, c=4) == 12\n    assert kw_only2(c=4, a=2) == 12\n\ndef tuples(t: Tuple[i64, i64] = (MAGIC, MAGIC)) -> i64:\n    return t[0] + t[1]\n\ndef test_tuple_arg_defaults() -> None:\n    assert tuples() == 2 * MAGIC\n    assert tuples((1, 2)) == 3\n    assert tuples((MAGIC, MAGIC)) == 2 * MAGIC\n    tuples2: Any = tuples\n    assert tuples2() == 2 * MAGIC\n    assert tuples2((1, 2)) == 3\n    assert tuples2((MAGIC, MAGIC)) == 2 * MAGIC\n\nclass TupleInit:\n    def __init__(self, t: Tuple[i64, i64] = (MAGIC, MAGIC)) -> None:\n        self.t = t[0] + t[1]\n\ndef test_tuple_init_arg_defaults() -> None:\n    assert TupleInit().t == 2 * MAGIC\n    assert TupleInit((1, 2)).t == 3\n    assert TupleInit((MAGIC, MAGIC)).t == 2 * MAGIC\n    o: Any = TupleInit\n    assert o().t == 2 * MAGIC\n    assert o((1, 2)).t == 3\n    assert o((MAGIC, MAGIC)).t == 2 * MAGIC\n\ndef many_args(\n    a1: i64 = 0,\n    a2: i64 = 1,\n    a3: i64 = 2,\n    a4: i64 = 3,\n    a5: i64 = 4,\n    a6: i64 = 5,\n    a7: i64 = 6,\n    a8: i64 = 7,\n    a9: i64 = 8,\n    a10: i64 = 9,\n    a11: i64 = 10,\n    a12: i64 = 11,\n    a13: i64 = 12,\n    a14: i64 = 13,\n    a15: i64 = 14,\n    a16: i64 = 15,\n    a17: i64 = 16,\n    a18: i64 = 17,\n    a19: i64 = 18,\n    a20: i64 = 19,\n    a21: i64 = 20,\n    a22: i64 = 21,\n    a23: i64 = 22,\n    a24: i64 = 23,\n    a25: i64 = 24,\n    a26: i64 = 25,\n    a27: i64 = 26,\n    a28: i64 = 27,\n    a29: i64 = 28,\n    a30: i64 = 29,\n    a31: i64 = 30,\n    a32: i64 = 31,\n    a33: i64 = 32,\n    a34: i64 = 33,\n) -> i64:\n    return a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8 + a9 + a10 + a11 + a12 + a13 + a14 + a15 + a16 + a17 + a18 + a19 + a20 + a21 + a22 + a23 + a24 + a25 + a26 + a27 + a28 + a29 + a30 + a31 + a32 + a33 + a34\n\ndef test_many_args() -> None:\n    assert many_args() == 561\n    assert many_args(a1=100) == 661\n    assert many_args(a2=101) == 661\n    assert many_args(a15=114) == 661\n    assert many_args(a31=130) == 661\n    assert many_args(a32=131) == 661\n    assert many_args(a33=232) == 761\n    assert many_args(a34=333) == 861\n    assert many_args(a1=100, a33=232) == 861\n    f: Any = many_args\n    assert f() == 561\n    assert f(a1=100) == 661\n    assert f(a2=101) == 661\n    assert f(a15=114) == 661\n    assert f(a31=130) == 661\n    assert f(a32=131) == 661\n    assert f(a33=232) == 761\n    assert f(a34=333) == 861\n    assert f(a1=100, a33=232) == 861\n\ndef test_nested_function_defaults() -> None:\n    a: i64 = 1\n\n    def nested(x: i64 = 2, y: i64 = 3) -> i64:\n        return a + x + y\n\n    assert nested() == 6\n    assert nested(3) == 7\n    assert nested(y=5) == 8\n    assert nested(MAGIC) == MAGIC + 4\n    a = 11\n    assert nested() == 16\n\n\ndef test_nested_function_defaults_via_any() -> None:\n    a: i64 = 1\n\n    def nested_native(x: i64 = 2, y: i64 = 3) -> i64:\n        return a + x + y\n\n    nested: Any = nested_native\n\n    assert nested() == 6\n    assert nested(3) == 7\n    assert nested(y=5) == 8\n    assert nested(MAGIC) == MAGIC + 4\n    a = 11\n    assert nested() == 16\n\ndef gen(x: i64 = 1, y: i64 = 2) -> Iterator[i64]:\n    yield x + y\n\ndef test_generator() -> None:\n    g = gen()\n    assert next(g) == 3\n    g = gen(2)\n    assert next(g) == 4\n    g = gen(2, 3)\n    assert next(g) == 5\n    a: Any = gen\n    g = a()\n    assert next(g) == 3\n    g = a(2)\n    assert next(g) == 4\n    g = a(2, 3)\n    assert next(g) == 5\n\ndef magic_default(x: i64 = MAGIC) -> i64:\n    return x\n\ndef test_magic_default() -> None:\n    assert magic_default() == MAGIC\n    assert magic_default(1) == 1\n    assert magic_default(MAGIC) == MAGIC\n    a: Any = magic_default\n    assert a() == MAGIC\n    assert a(1) == 1\n    assert a(MAGIC) == MAGIC\n\n[case testI64UndefinedLocal]\nfrom typing import Final\n\nfrom mypy_extensions import i64, i32\n\nfrom testutil import assertRaises\n\nMAGIC: Final = -113\n\n\ndef test_conditionally_defined_local() -> None:\n    x = not int()\n    if x:\n        y: i64 = 5\n        z: i32 = 6\n    assert y == 5\n    assert z == 6\n\ndef test_conditionally_undefined_local() -> None:\n    x = int()\n    if x:\n        y: i64 = 5\n        z: i32 = 6\n    else:\n        ok: i64 = 7\n    assert ok == 7\n    try:\n        print(y)\n    except NameError as e:\n        assert str(e) == 'local variable \"y\" referenced before assignment'\n    else:\n        assert False\n    try:\n        print(z)\n    except NameError as e:\n        assert str(e) == 'local variable \"z\" referenced before assignment'\n    else:\n        assert False\n\ndef test_assign_error_value_conditionally() -> None:\n    x = int()\n    if not x:\n        y: i64 = MAGIC\n        z: i32 = MAGIC\n    assert y == MAGIC\n    assert z == MAGIC\n\ndef tuple_case(x: i64, y: i64) -> None:\n    if not int():\n        t = (x, y)\n    assert t == (x, y)\n    if int():\n        t2 = (x, y)\n    try:\n        print(t2)\n    except NameError as e:\n        assert str(e) == 'local variable \"t2\" referenced before assignment'\n    else:\n        assert False\n\ndef test_conditionally_undefined_tuple() -> None:\n    tuple_case(2, 3)\n    tuple_case(-2, -3)\n    tuple_case(MAGIC, MAGIC)\n\ndef test_many_locals() -> None:\n    x = int()\n    if x:\n        a0: i64 = 0\n        a1: i64 = 1\n        a2: i64 = 2\n        a3: i64 = 3\n        a4: i64 = 4\n        a5: i64 = 5\n        a6: i64 = 6\n        a7: i64 = 7\n        a8: i64 = 8\n        a9: i64 = 9\n        a10: i64 = 10\n        a11: i64 = 11\n        a12: i64 = 12\n        a13: i64 = 13\n        a14: i64 = 14\n        a15: i64 = 15\n        a16: i64 = 16\n        a17: i64 = 17\n        a18: i64 = 18\n        a19: i64 = 19\n        a20: i64 = 20\n        a21: i64 = 21\n        a22: i64 = 22\n        a23: i64 = 23\n        a24: i64 = 24\n        a25: i64 = 25\n        a26: i64 = 26\n        a27: i64 = 27\n        a28: i64 = 28\n        a29: i64 = 29\n        a30: i64 = 30\n        a31: i64 = 31\n        a32: i64 = 32\n        a33: i64 = 33\n    with assertRaises(UnboundLocalError):\n        print(a0)\n    with assertRaises(UnboundLocalError):\n        print(a31)\n    with assertRaises(UnboundLocalError):\n        print(a32)\n    with assertRaises(UnboundLocalError):\n        print(a33)\n    a0 = 5\n    assert a0 == 5\n    with assertRaises(UnboundLocalError):\n        print(a31)\n    with assertRaises(UnboundLocalError):\n        print(a32)\n    with assertRaises(UnboundLocalError):\n        print(a33)\n    a32 = 55\n    assert a0 == 5\n    assert a32 == 55\n    with assertRaises(UnboundLocalError):\n        print(a31)\n    with assertRaises(UnboundLocalError):\n        print(a33)\n    a31 = 10\n    a33 = 20\n    assert a0 == 5\n    assert a31 == 10\n    assert a32 == 55\n    assert a33 == 20\n\n[case testI64GlueMethodsAndInheritance]\nfrom typing import Final, Any\n\nfrom mypy_extensions import i64, trait\n\nfrom testutil import assertRaises\n\nMAGIC: Final = -113\n\nclass Base:\n    def foo(self) -> i64:\n        return 5\n\n    def bar(self, x: i64 = 2) -> i64:\n        return x + 1\n\n    def hoho(self, x: i64) -> i64:\n        return x - 1\n\nclass Derived(Base):\n    def foo(self, x: i64 = 5) -> i64:\n        return x + 10\n\n    def bar(self, x: i64 = 3, y: i64 = 20) -> i64:\n        return x + y + 2\n\n    def hoho(self, x: i64 = 7) -> i64:\n        return x - 2\n\ndef test_derived_adds_bitmap() -> None:\n    b: Base = Derived()\n    assert b.foo() == 15\n\ndef test_derived_adds_another_default_arg() -> None:\n    b: Base = Derived()\n    assert b.bar() == 25\n    assert b.bar(1) == 23\n    assert b.bar(MAGIC) == MAGIC + 22\n\ndef test_derived_switches_arg_to_have_default() -> None:\n    b: Base = Derived()\n    assert b.hoho(5) == 3\n    assert b.hoho(MAGIC) == MAGIC - 2\n\n@trait\nclass T:\n    @property\n    def x(self) -> i64: ...\n    @property\n    def y(self) -> i64: ...\n\nclass C(T):\n    x: i64 = 1\n    y: i64 = 4\n\ndef test_read_only_property_in_trait_implemented_as_attribute() -> None:\n    c = C()\n    c.x = 5\n    assert c.x == 5\n    c.x = MAGIC\n    assert c.x == MAGIC\n    assert c.y == 4\n    c.y = 6\n    assert c.y == 6\n    t: T = C()\n    assert t.y == 4\n    t = c\n    assert t.x == MAGIC\n    c.x = 55\n    assert t.x == 55\n    assert t.y == 6\n    a: Any = c\n    assert a.x == 55\n    assert a.y == 6\n    a.x = 7\n    a.y = 8\n    assert a.x == 7\n    assert a.y == 8\n\nclass D(T):\n    xx: i64\n\n    @property\n    def x(self) -> i64:\n        return self.xx\n\n    @property\n    def y(self) -> i64:\n        raise TypeError\n\ndef test_read_only_property_in_trait_implemented_as_property() -> None:\n    d = D()\n    d.xx = 5\n    assert d.x == 5\n    d.xx = MAGIC\n    assert d.x == MAGIC\n    with assertRaises(TypeError):\n        d.y\n    t: T = d\n    assert t.x == MAGIC\n    d.xx = 6\n    assert t.x == 6\n    with assertRaises(TypeError):\n        t.y\n\n@trait\nclass T2:\n    x: i64\n    y: i64\n\nclass C2(T2):\n    pass\n\ndef test_inherit_trait_attribute() -> None:\n    c = C2()\n    c.x = 5\n    assert c.x == 5\n    c.x = MAGIC\n    assert c.x == MAGIC\n    with assertRaises(AttributeError):\n        c.y\n    c.y = 6\n    assert c.y == 6\n    t: T2 = C2()\n    with assertRaises(AttributeError):\n        t.y\n    t = c\n    assert t.x == MAGIC\n    c.x = 55\n    assert t.x == 55\n    assert t.y == 6\n    a: Any = c\n    assert a.x == 55\n    assert a.y == 6\n    a.x = 7\n    a.y = 8\n    assert a.x == 7\n    assert a.y == 8\n\nclass D2(T2):\n    x: i64\n    y: i64 = 4\n\ndef test_implement_trait_attribute() -> None:\n    d = D2()\n    d.x = 5\n    assert d.x == 5\n    d.x = MAGIC\n    assert d.x == MAGIC\n    assert d.y == 4\n    d.y = 6\n    assert d.y == 6\n    t: T2 = D2()\n    assert t.y == 4\n    t = d\n    assert t.x == MAGIC\n    d.x = 55\n    assert t.x == 55\n    assert t.y == 6\n    a: Any = d\n    assert a.x == 55\n    assert a.y == 6\n    a.x = 7\n    a.y = 8\n    assert a.x == 7\n    assert a.y == 8\n\nclass DunderErr:\n    def __contains__(self, i: i64) -> bool:\n        raise IndexError()\n\ndef test_dunder_arg_check() -> None:\n    o: Any = DunderErr()\n    with assertRaises(TypeError):\n        'x' in o\n    with assertRaises(TypeError):\n        2**63 in o\n    with assertRaises(IndexError):\n        1 in o\n"
  },
  {
    "path": "mypyc/test-data/run-imports.test",
    "content": "# Test cases for imports and related features (compile and run)\n\n[case testImports]\nimport testmodule\nimport pkg2.mod\nimport pkg2.mod2 as mm2\n\ndef f(x: int) -> int:\n    return testmodule.factorial(5)\n\ndef g(x: int) -> int:\n    from welp import foo\n    return foo(x)\n\ndef test_import_basics() -> None:\n    assert f(5) == 120\n    assert g(5) == 5\n    assert \"pkg2.mod\" not in globals(), \"the root module should be in globals!\"\n    assert pkg2.mod.x == 1\n    assert \"mod2\" not in globals(), \"pkg2.mod2 is aliased to mm2!\"\n    assert mm2.y == 2\n\ndef test_import_submodule_within_function() -> None:\n    import pkg.mod\n    assert pkg.x == 1\n    assert pkg.mod.y == 2\n    assert \"pkg.mod\" not in globals(), \"the root module should be in globals!\"\n\ndef test_import_as_submodule_within_function() -> None:\n    import pkg.mod as mm\n    assert mm.y == 2\n    assert \"pkg.mod\" not in globals(), \"the root module should be in globals!\"\n\n# TODO: Don't add local imports to globals()\n#\n# def test_local_import_not_in_globals() -> None:\n#     import nob\n#     assert 'nob' not in globals()\n\ndef test_import_module_without_stub_in_function() -> None:\n    # 'psutil' must not have a stub in typeshed for this test case\n    import psutil  # type: ignore\n    # TODO: We shouldn't add local imports to globals()\n    # assert 'psutil' not in globals()\n    assert isinstance(psutil.__name__, str)\n\ndef test_import_as_module_without_stub_in_function() -> None:\n    # 'psutil' must not have a stub in typeshed for this test case\n    import psutil as pp  # type: ignore\n    assert 'psutil' not in globals()\n    # TODO: We shouldn't add local imports to globals()\n    # assert 'pp' not in globals()\n    assert isinstance(pp.__name__, str)\n\n[file testmodule.py]\ndef factorial(x: int) -> int:\n    if x == 0:\n        return 1\n    else:\n        return x * factorial(x-1)\n[file welp.py]\ndef foo(x: int) -> int:\n    return x\n[file pkg/__init__.py]\nx = 1\n[file pkg/mod.py]\ny = 2\n[file pkg2/__init__.py]\n[file pkg2/mod.py]\nx = 1\n[file pkg2/mod2.py]\ny = 2\n[file nob.py]\nz = 3\n\n[case testImportMissing]\n# The unchecked module is configured by the test harness to not be\n# picked up by mypy, so we can test that we do that right thing when\n# calling library modules without stubs.\nimport unchecked  # type: ignore\nimport unchecked as lol  # type: ignore\nassert unchecked.x == 10\nassert lol.x == 10\n[file unchecked.py]\nx = 10\n\n[file driver.py]\nimport native\n\n[case testFromImport]\nfrom testmodule import g\n\ndef f(x: int) -> int:\n    return g(x)\n[file testmodule.py]\ndef g(x: int) -> int:\n    return x + 1\n[file driver.py]\nfrom native import f\nassert f(1) == 2\n\n[case testFromImportWithUntypedModule]\n\n# avoid including an __init__.py and use type: ignore to test what happens\n# if mypy can't tell if mod isn't a module\nfrom pkg import mod # type: ignore\n\ndef test_import() -> None:\n    assert mod.h(8) == 24\n\n[file pkg/mod.py]\ndef h(x):\n    return x * 3\n\n[case testFromImportWithKnownModule]\nfrom pkg import mod1\nfrom pkg import mod2 as modmod\nfrom pkg.mod2 import g as gg\nfrom pkg.mod3 import h as h2, g as g2\n\ndef test_import() -> None:\n    assert mod1.h(8) == 24\n    assert modmod.g(1) == 1\n    assert gg(2) == 2\n    assert h2(10) == 12\n    assert g2(10) == 13\n\n[file pkg/__init__.py]\n[file pkg/mod1.py]\ndef h(x: int) -> int:\n    return x * 3\n\n[file pkg/mod2.py]\ndef g(x: int) -> int:\n    return x\n\n[file pkg/mod3.py]\ndef h(x: int) -> int:\n    return x + 2\n\ndef g(x: int) -> int:\n    return x + 3\n\n[case testFromImportWithUnKnownModule]\ndef test_import() -> None:\n    try:\n        from pkg import a # type: ignore\n    except ImportError:\n        pass\n\n[file pkg/__init__.py]\n\n[case testMultipleFromImportsWithSamePackageButDifferentModules]\nfrom pkg import a\nfrom pkg import b\n\ndef test_import() -> None:\n    assert a.g() == 4\n    assert b.h() == 39\n\n[file pkg/__init__.py]\n[file pkg/a.py]\n\ndef g() -> int:\n    return 4\n\n[file pkg/b.py]\n\ndef h() -> int:\n    return 39\n\n[case testReexport]\n# Test that we properly handle accessing values that have been reexported\nimport a\ndef f(x: int) -> int:\n    return a.g(x) + a.foo + a.b.foo\n\nwhatever = a.A()\n\n[file a.py]\nfrom b import g as g, A as A, foo as foo\nimport b\n\n[file b.py]\ndef g(x: int) -> int:\n    return x + 1\n\nclass A:\n    pass\n\nfoo = 20\n\n[file driver.py]\nfrom native import f, whatever\nimport b\n\nassert f(20) == 61\nassert isinstance(whatever, b.A)\n\n[case testAssignModule]\nimport a\nassert a.x == 20\na.x = 10\n[file a.py]\nx = 20\n[file driver.py]\nimport native\n\n[case testLazyImport]\nimport shared\n\ndef do_import() -> None:\n    import a\n\ndef test_lazy() -> None:\n    assert shared.counter == 0\n    do_import()\n    assert shared.counter == 1\n\n[file a.py]\nimport shared\nshared.counter += 1\n\n[file shared.py]\ncounter = 0\n\n[case testDelayedImport]\ndef test_delayed() -> None:\n    import a\n    print(\"inbetween\")\n    import b\n\n[file a.py]\nprint(\"first\")\n\n[file b.py]\nprint(\"last\")\n\n[out]\nfirst\ninbetween\nlast\n\n[case testImportErrorLineNumber]\ndef test_error() -> None:\n    try:\n        import enum\n        import dataclasses, missing  # type: ignore[import]\n    except ImportError as e:\n        line = e.__traceback__.tb_lineno # type: ignore[attr-defined]\n        assert line == 4, f\"traceback's line number is {line}, expected 4\"\n\n[case testImportGroupIsolation]\ndef func() -> None:\n    import second\n\ndef test_isolation() -> None:\n    import first\n    func()\n\n[file first.py]\nprint(\"first\")\n\n[file second.py]\nprint(\"second\")\n\n[out]\nfirst\nsecond\n"
  },
  {
    "path": "mypyc/test-data/run-integers.test",
    "content": "# Test cases for integers (compile and run)\n\n[case testInc]\ndef inc(x: int) -> int:\n    return x + 1\n[file driver.py]\nfrom native import inc\nprint(inc(3))\nprint(inc(-5))\nprint(inc(10**20))\n[out]\n4\n-4\n100000000000000000001\n\n[case testCount]\ndef count(n: int) -> int:\n    i = 1\n    while i <= n:\n        i = i + 1\n    return i\n[file driver.py]\nfrom native import count\nprint(count(0))\nprint(count(1))\nprint(count(5))\n[out]\n1\n2\n6\n\n[case testIntMathOps]\n# This tests integer math things that are either easier to test in Python than\n# in our C tests or are tested here because (for annoying reasons) we don't run\n# the C unit tests in our 32-bit CI.\ndef multiply(x: int, y: int) -> int:\n    return x * y\n\n# these stringify their outputs because that will catch if exceptions are mishandled\ndef floor_div(x: int, y: int) -> str:\n    return str(x // y)\ndef remainder(x: int, y: int) -> str:\n    return str(x % y)\n\n[file driver.py]\nfrom native import multiply, floor_div, remainder\n\ndef test_multiply(x, y):\n    assert multiply(x, y) == x * y\ndef test_floor_div(x, y):\n    assert floor_div(x, y) == str(x // y)\ndef test_remainder(x, y):\n    assert remainder(x, y) == str(x % y)\n\ntest_multiply(10**6, 10**6)\ntest_multiply(2**15, 2**15-1)\ntest_multiply(2**14, 2**14)\n\ntest_multiply(10**12, 10**12)\ntest_multiply(2**30, 2**30-1)\ntest_multiply(2**29, 2**29)\n\ntest_floor_div(-2**62, -1)\ntest_floor_div(-2**30, -1)\ntry:\n    floor_div(10, 0)\nexcept ZeroDivisionError:\n    pass\nelse:\n    assert False, \"Expected ZeroDivisionError\"\n\ntest_remainder(-2**62, -1)\ntest_remainder(-2**30, -1)\ntry:\n    remainder(10, 0)\nexcept ZeroDivisionError:\n    pass\nelse:\n    assert False, \"Expected ZeroDivisionError\"\n\n[case testBigIntLiteral]\ndef big_int() -> None:\n    a_62_bit = 4611686018427387902\n    max_62_bit = 4611686018427387903\n    b_63_bit = 4611686018427387904\n    c_63_bit = 9223372036854775806\n    max_63_bit = 9223372036854775807\n    d_64_bit = 9223372036854775808\n    max_32_bit = 2147483647\n    max_32_bit_plus1 = 2147483648\n    max_31_bit = 1073741823\n    max_31_bit_plus1 = 1073741824\n    neg = -1234567\n    min_signed_63_bit = -4611686018427387904\n    underflow = -4611686018427387905\n    min_signed_64_bit = -9223372036854775808\n    min_signed_31_bit = -1073741824\n    min_signed_31_bit_plus1 = -1073741823\n    min_signed_31_bit_minus1 = -1073741825\n    min_signed_32_bit = -2147483648\n    print(a_62_bit)\n    print(max_62_bit)\n    print(b_63_bit)\n    print(c_63_bit)\n    print(max_63_bit)\n    print(d_64_bit)\n    print('==')\n    print(max_32_bit)\n    print(max_32_bit_plus1)\n    print(max_31_bit)\n    print(max_31_bit_plus1)\n    print(neg)\n    print(min_signed_63_bit)\n    print(underflow)\n    print(min_signed_64_bit)\n    print(min_signed_31_bit)\n    print(min_signed_31_bit_plus1)\n    print(min_signed_31_bit_minus1)\n    print(min_signed_32_bit)\n[file driver.py]\nfrom native import big_int\nbig_int()\n[out]\n4611686018427387902\n4611686018427387903\n4611686018427387904\n9223372036854775806\n9223372036854775807\n9223372036854775808\n==\n2147483647\n2147483648\n1073741823\n1073741824\n-1234567\n-4611686018427387904\n-4611686018427387905\n-9223372036854775808\n-1073741824\n-1073741823\n-1073741825\n-2147483648\n\n[case testNeg]\ndef neg(x: int) -> int:\n    return -x\n[file driver.py]\nfrom native import neg\nassert neg(5) == -5\nassert neg(-5) == 5\nassert neg(1073741823) == -1073741823\nassert neg(-1073741823) == 1073741823\nassert neg(1073741824) == -1073741824\nassert neg(-1073741824) == 1073741824\nassert neg(2147483647) == -2147483647\nassert neg(-2147483647) == 2147483647\nassert neg(2147483648) == -2147483648\nassert neg(-2147483648) == 2147483648\nassert neg(4611686018427387904) == -4611686018427387904\nassert neg(-4611686018427387904) == 4611686018427387904\nassert neg(9223372036854775807) == -9223372036854775807\nassert neg(-9223372036854775807) == 9223372036854775807\nassert neg(9223372036854775808) == -9223372036854775808\nassert neg(-9223372036854775808) == 9223372036854775808\n\n[case testIsinstanceIntAndNotBool]\ndef test_isinstance_int_and_not_bool(value: object) -> bool:\n    return isinstance(value, int) and not isinstance(value, bool)\n[file driver.py]\nfrom native import test_isinstance_int_and_not_bool\nassert test_isinstance_int_and_not_bool(True) == False\nassert test_isinstance_int_and_not_bool(1) == True\n\n[case testIntOps]\nfrom typing import Any\nfrom testutil import assertRaises\n\ndef check_and(x: int, y: int) -> None:\n    # eval() can be trusted to calculate expected result\n    expected = eval('{} & {}'.format(x, y))\n    actual = x & y\n    assert actual == expected, '{} & {}: got {}, expected {}'.format(x, y, actual, expected)\n\ndef check_or(x: int, y: int) -> None:\n    # eval() can be trusted to calculate expected result\n    expected = eval('{} | {}'.format(x, y))\n    actual = x | y\n    assert actual == expected, '{} | {}: got {}, expected {}'.format(x, y, actual, expected)\n\ndef check_xor(x: int, y: int) -> None:\n    # eval() can be trusted to calculate expected result\n    expected = eval('{} ^ {}'.format(x, y))\n    actual = x ^ y\n    assert actual == expected, '{} ^ {}: got {}, expected {}'.format(x, y, actual, expected)\n\ndef check_bitwise(x: int, y: int) -> None:\n    for l, r in (x, y), (y, x):\n        for ll, rr in (l, r), (-l, r), (l, -r), (-l, -r):\n            check_and(ll, rr)\n            check_or(ll, rr)\n            check_xor(ll, rr)\n\nSHIFT = 30\nDIGIT0a = 615729753\nDIGIT0b = 832796681\nDIGIT1a = 744342356 << SHIFT\nDIGIT1b = 321006080 << SHIFT\nDIGIT2a = 643582106 << (SHIFT * 2)\nDIGIT2b = 656420725 << (SHIFT * 2)\nDIGIT50 = 315723472 << (SHIFT * 50)\nDIGIT100a = 1020652627 << (SHIFT * 100)\nDIGIT100b = 923752451 << (SHIFT * 100)\nBIG_SHORT = 3491190729721336556\nMAX_SHORT = (1 << 62) - 1\nMIN_SHORT = -(1 << 62)\nMAX_SHORT_32 = (1 << 30) - 1\nMIN_SHORT_32 = -(1 << 30)\n\ndef test_and_or_xor() -> None:\n    check_bitwise(0, 0)\n    check_bitwise(0, 1)\n    check_bitwise(1, 1)\n    check_bitwise(DIGIT0a, DIGIT0b)\n    check_bitwise(DIGIT1a, DIGIT1b)\n    check_bitwise(DIGIT2a, DIGIT2b)\n    check_bitwise(DIGIT100a, DIGIT100b)\n    check_bitwise(DIGIT0a, DIGIT0b + DIGIT2a)\n    check_bitwise(DIGIT0a, DIGIT0b + DIGIT50)\n    check_bitwise(DIGIT50 + DIGIT1a, DIGIT100a + DIGIT2b)\n    check_bitwise(BIG_SHORT, DIGIT0a)\n    check_bitwise(BIG_SHORT, DIGIT0a + DIGIT1a)\n    check_bitwise(BIG_SHORT, DIGIT0a + DIGIT1a + DIGIT2a)\n    check_bitwise(BIG_SHORT, DIGIT0a + DIGIT1a + DIGIT2a + DIGIT50)\n\n    for x in range(-25, 25):\n        for y in range(-25, 25):\n            check_bitwise(x, y)\n\ndef test_bitwise_inplace() -> None:\n    # Basic sanity checks; these should use the same code as the non-in-place variants\n    for x, y in (DIGIT0a, DIGIT1a), (DIGIT2a, DIGIT0a + DIGIT2b):\n        n = x\n        n &= y\n        assert n == x & y\n        n = x\n        n |= y\n        assert n == x | y\n        n = x\n        n ^= y\n        assert n == x ^ y\n\ndef check_invert(x: int) -> None:\n    # Use eval() as the source of truth\n    assert ~x == eval('~{}'.format(x))\n    assert ~(-x) == eval('~({})'.format(-x))\n\ndef test_invert() -> None:\n    check_invert(0)\n    check_invert(1)\n    check_invert(DIGIT0a)\n    check_invert(DIGIT0a + DIGIT1a)\n    check_invert(DIGIT0a + DIGIT1a + DIGIT2a)\n    check_invert(DIGIT0a + DIGIT1a + DIGIT2a + DIGIT50)\n    check_invert(BIG_SHORT)\n    for delta in -1, 0, 1:\n        check_invert(MAX_SHORT + delta)\n        check_invert(MIN_SHORT + delta)\n        check_invert(MAX_SHORT_32 + delta)\n        check_invert(MIN_SHORT_32 + delta)\n\ndef check_right_shift(x: int, n: int) -> None:\n    if n < 0:\n        try:\n            x >> n\n        except ValueError:\n            return\n        assert False, \"no exception raised\"\n    # Use eval() as the source of truth\n    expected = eval('{} >> {}'.format(x, n))\n    actual = x >> n\n    assert actual == expected, \"{} >> {}: got {}, expected {}\".format(x, n, actual, expected)\n\ndef test_right_shift() -> None:\n    for x in 0, 1, 1235, DIGIT0a, DIGIT0a + DIGIT1a, DIGIT0a + DIGIT50:\n        for n in 0, 1, 2, 3, 4, 10, 40, 10000, DIGIT1a, -1, -1334444, -DIGIT1a:\n            check_right_shift(x, n)\n            check_right_shift(-x, n)\n    x = DIGIT0a\n    x >>= 1\n    assert x == DIGIT0a >> 1\n    x = DIGIT50\n    x >>= 5\n    assert x == DIGIT50 >> 5\n    for i in range(256):\n        check_right_shift(1, i)\n        check_right_shift(137, i)\n        check_right_shift(MAX_SHORT, i)\n        check_right_shift(MAX_SHORT_32, i)\n        check_right_shift(MAX_SHORT + 1, i)\n        check_right_shift(MAX_SHORT_32 + 1, i)\n    for x in 1, DIGIT50:\n        try:\n            # It's okay if this raises an exception\n            assert x >> DIGIT2a == 0\n        except Exception:\n            pass\n        try:\n            x >> -DIGIT2a\n            assert False\n        except Exception:\n            pass\n\ndef check_left_shift(x: int, n: int) -> None:\n    if n < 0:\n        try:\n            x << n\n        except ValueError:\n            return\n        assert False, \"no exception raised\"\n    # Use eval() as the source of truth\n    expected = eval('{} << {}'.format(x, n))\n    actual = x << n\n    assert actual == expected, \"{} << {}: got {}, expected {}\".format(x, n, actual, expected)\n\ndef test_left_shift() -> None:\n    for x in 0, 1, 1235, DIGIT0a, DIGIT0a + DIGIT1a, DIGIT0a + DIGIT50:\n        for n in 0, 1, 2, 10, 40, 10000, -1, -1334444:\n            check_left_shift(x, n)\n            check_left_shift(-x, n)\n    x = DIGIT0a\n    x <<= 1\n    assert x == DIGIT0a << 1\n    x = DIGIT50\n    x <<= 5\n    assert x == DIGIT50 << 5\n    for shift in range(256):\n        check_left_shift(1, shift)\n        check_left_shift(137, shift)\n    for x in 1, DIGIT50:\n        try:\n            x << DIGIT50\n            assert False\n        except Exception:\n            pass\n        try:\n            x << -DIGIT50\n            assert False\n        except Exception:\n            pass\n\ndef is_true(x: int) -> bool:\n    if x:\n        return True\n    else:\n        return False\n\ndef is_true2(x: int) -> bool:\n    return bool(x)\n\ndef is_false(x: int) -> bool:\n    if not x:\n        return True\n    else:\n        return False\n\ndef test_int_as_bool() -> None:\n    assert not is_true(0)\n    assert not is_true2(0)\n    assert is_false(0)\n    for x in 1, 55, -1, -7, 1 << 50, 1 << 101, -(1 << 50), -(1 << 101):\n        assert is_true(x)\n        assert is_true2(x)\n        assert not is_false(x)\n\ndef bool_as_int(b: bool) -> int:\n    return b\n\ndef bool_as_int2(b: bool) -> int:\n    return int(b)\n\ndef test_bool_as_int() -> None:\n    assert bool_as_int(False) == 0\n    assert bool_as_int(True) == 1\n    assert bool_as_int2(False) == 0\n    assert bool_as_int2(True) == 1\n\ndef no_op_conversion(n: int) -> int:\n    return int(n)\n\ndef test_no_op_conversion() -> None:\n    for x in 1, 55, -1, -7, 1 << 50, 1 << 101, -(1 << 50), -(1 << 101):\n        assert no_op_conversion(x) == x\n\ndef test_floor_divide() -> None:\n    for x in range(-100, 100):\n        for y in range(-100, 100):\n            if y != 0:\n                assert x // y == getattr(x, \"__floordiv__\")(y)\n\ndef test_mod() -> None:\n    for x in range(-100, 100):\n        for y in range(-100, 100):\n            if y != 0:\n                assert x % y == getattr(x, \"__mod__\")(y)\n\ndef test_constant_fold() -> None:\n    assert str(-5 + 3) == \"-2\"\n    assert str(15 - 3) == \"12\"\n    assert str(1000 * 1000) == \"1000000\"\n    assert str(12325 // 12 ) == \"1027\"\n    assert str(87645 % 321) == \"12\"\n    assert str(674253 | 76544) == \"748493\"\n    assert str(765 ^ 82) == \"687\"\n    assert str(6546 << 3) == \"52368\"\n    assert str(6546 >> 7) == \"51\"\n    assert str(3**5) == \"243\"\n    assert str(~76) == \"-77\"\n    try:\n        2 / 0\n    except ZeroDivisionError:\n        pass\n    else:\n        assert False, \"no exception raised\"\n\n    x = int()\n    y = int() - 1\n    assert x == -1 or y != -3\n    assert -1 <= x\n    assert -1 == y\n\n    # Use int() to avoid constant propagation\n    i30 = (1 << 30) + int()\n    assert i30 == 1 << 30\n    i31 = (1 << 31) + int()\n    assert i31 == 1 << 31\n    i32 = (1 << 32) + int()\n    assert i32 == 1 << 32\n    i62 = (1 << 62) + int()\n    assert i62 == 1 << 62\n    i63 = (1 << 63) + int()\n    assert i63 == 1 << 63\n    i64 = (1 << 64) + int()\n    assert i64 == 1 << 64\n\n    n30 = -(1 << 30) + int()\n    assert n30 == -(1 << 30)\n    n31 = -(1 << 31) + int()\n    assert n31 == -(1 << 31)\n    n32 = -(1 << 32) + int()\n    assert n32 == -(1 << 32)\n    n62 = -(1 << 62) + int()\n    assert n62 == -(1 << 62)\n    n63 = -(1 << 63) + int()\n    assert n63 == -(1 << 63)\n    n64 = -(1 << 64) + int()\n    assert n64 == -(1 << 64)\n\ndef div_by_2(x: int) -> int:\n    return x // 2\n\ndef div_by_3(x: int) -> int:\n    return x // 3\n\ndef div_by_4(x: int) -> int:\n    return x // 4\n\ndef test_floor_divide_by_literal() -> None:\n    for i in range(-100, 100):\n        i_boxed: Any = i\n        assert div_by_2(i) == i_boxed // int('2')\n        assert div_by_3(i) == i_boxed // int('3')\n        assert div_by_4(i) == i_boxed // int('4')\n\ndef test_true_divide() -> None:\n    for x in range(-150, 100):\n        for y in range(-150, 100):\n            if y != 0:\n                assert x / y == getattr(x, \"__truediv__\")(y)\n    large1 = (123 + int())**123\n    large2 = (121 + int())**121\n    assert large1 / large2 == getattr(large1, \"__truediv__\")(large2)\n    assert large1 / 135 == getattr(large1, \"__truediv__\")(135)\n    assert large1 / -2 == getattr(large1, \"__truediv__\")(-2)\n    assert 17 / large2 == getattr(17, \"__truediv__\")(large2)\n\n    huge = 10**1000 + int()\n    with assertRaises(OverflowError, \"integer division result too large for a float\"):\n        huge / 2\n    with assertRaises(OverflowError, \"integer division result too large for a float\"):\n        huge / -2\n    assert 1 / huge == 0.0\n\n[case testIntMinMax]\ndef test_int_min_max() -> None:\n    x: int = 200\n    y: int = 30\n    assert min(x, y) == 30\n    assert max(x, y) == 200\n    assert min(y, x) == 30\n    assert max(y, x) == 200\n\ndef test_int_hybrid_min_max() -> None:\n    from typing import Any\n\n    x: object = 30\n    y: Any = 20.0\n    assert min(x, y) == 20.0\n    assert max(x, y) == 30\n\n    u: object = 20\n    v: float = 30.0\n    assert min(u, v) == 20\n    assert max(u, v) == 30.0\n\ndef test_int_incompatible_min_max() -> None:\n    x: int = 2\n    y: str = 'aaa'\n    try:\n        print(min(x, y))\n    except TypeError as e:\n        assert str(e) == \"'<' not supported between instances of 'str' and 'int'\"\n    try:\n        print(max(x, y))\n    except TypeError as e:\n        assert str(e) == \"'>' not supported between instances of 'str' and 'int'\"\n\ndef test_int_bool_min_max() -> None:\n    x: int = 2\n    y: bool = False\n    z: bool = True\n    assert min(x, y) == False\n    assert min(x, z) == True\n    assert max(x, y) == 2\n    assert max(x, z) == 2\n\n    u: int = -10\n    assert min(u, y) == -10\n    assert min(u, z) == -10\n    assert max(u, y) == False\n    assert max(u, z) == True\n\n[case testIsInstance]\nfrom copysubclass import subc\nfrom typing import Any\ndef test_built_in() -> None:\n    i: Any = 0\n    assert isinstance(i + 0, int)\n    assert isinstance(i + 9223372036854775808, int)\n    assert isinstance(i + -9223372036854775808, int)\n    assert isinstance(subc(), int)\n    assert isinstance(subc(9223372036854775808), int)\n    assert isinstance(subc(-9223372036854775808), int)\n\n    assert not isinstance(set(), int)\n    assert not isinstance((), int)\n    assert not isinstance((1,2,3), int)\n    assert not isinstance({1,2}, int)\n    assert not isinstance(float(0) + 1.0, int)\n    assert not isinstance(str() + '1', int)\n\ndef test_user_defined() -> None:\n    from userdefinedint import int\n\n    i: Any = 42\n    assert isinstance(int(), int)\n    assert not isinstance(i, int)\n\n[file copysubclass.py]\nclass subc(int):\n    pass\n\n[file userdefinedint.py]\nclass int:\n    pass\n\n[case testIntToBytes]\nfrom testutil import assertRaises\ndef to_bytes(n: int, length: int, byteorder: str, signed: bool = False) -> bytes:\n    return n.to_bytes(length, byteorder, signed=signed)\ndef test_to_bytes() -> None:\n    assert to_bytes(255, 2, \"big\") == b'\\x00\\xff', to_bytes(255, 2, \"big\")\n    assert to_bytes(255, 2, \"little\") == b'\\xff\\x00', to_bytes(255, 2, \"little\")\n    assert to_bytes(-1, 2, \"big\", True) == b'\\xff\\xff', to_bytes(-1, 2, \"big\", True)\n    assert to_bytes(0, 1, \"big\") == b'\\x00', to_bytes(0, 1, \"big\")\n    # test with a value that does not fit in 64 bits\n    assert to_bytes(10**30, 16, \"big\") == b'\\x00\\x00\\x00\\x0c\\x9f,\\x9c\\xd0Ft\\xed\\xea@\\x00\\x00\\x00', to_bytes(10**30, 16, \"big\")\n    # unsigned, too large for 1 byte\n    with assertRaises(OverflowError):\n        to_bytes(256, 1, \"big\")\n    # signed, too small for 1 byte\n    with assertRaises(OverflowError):\n        to_bytes(-129, 1, \"big\", True)\n    # signed, too large for 1 byte\n    with assertRaises(OverflowError):\n        to_bytes(128, 1, \"big\", True)\n\n[case testBitLength]\ndef bit_length(n: int) -> int:\n    return n.bit_length()\ndef bit_length_python(n: int) -> int:\n    return getattr(n, \"bit_length\")()\ndef test_bit_length() -> None:\n    for n in range(256):\n        i = 1 << n\n        assert bit_length(i) == bit_length_python(i)\n        assert bit_length(-(i)) == bit_length_python(-(i))\n        i -= 1\n        assert bit_length(i) == bit_length_python(i)\n        assert bit_length(-(i)) == bit_length_python(-(i))\n"
  },
  {
    "path": "mypyc/test-data/run-librt-strings.test",
    "content": "[case testLibrtStrings_librt_experimental]\nfrom typing import Any\nimport base64\nimport binascii\nimport random\nimport struct\n\nfrom librt.strings import BytesWriter, StringWriter, write_i16_le, write_i16_be, read_i16_le, read_i16_be, write_i32_le, write_i32_be, read_i32_le, read_i32_be, write_i64_le, write_i64_be, read_i64_le, read_i64_be, write_f64_le, read_f64_le, write_f64_be, read_f64_be, write_f32_le, write_f32_be, read_f32_le, read_f32_be\n\nfrom testutil import assertRaises\n\n# Test values for i16 write/read operations, organized by byte size\nI16_TEST_VALUES: list[int] = [\n    # 1-byte values (0 to 127, and -128 to -1 in terms of low byte pattern)\n    0, 1, 127, -1, -113, -128,  # -113 is mypyc overlapping error value\n    # 2-byte values (128 to 32767, -32768 to -129)\n    128, 255, 256, 0x1234, 32767, -129, -256, -32768,\n]\n\n# Test values for i32 write/read operations: i16 test values plus 3-4 byte values\nI32_TEST_VALUES: list[int] = I16_TEST_VALUES + [\n    # 3-byte values (32768 to 8388607, -8388608 to -32769)\n    32768, 65535, 65536, 8388607, -32769, -65536, -8388608,\n    # 4-byte values (8388608 to 2147483647, -2147483648 to -8388609)\n    8388608, 16777215, 16777216, 2147483647, -8388609, -16777216, -2147483648,\n]\n\n# Test values for i64 write/read operations: i32 test values plus 5-8 byte values\nI64_TEST_VALUES: list[int] = I32_TEST_VALUES + [\n    # 5-8 byte values (beyond i32 range)\n    2147483648,           # 2^31, just above i32 max\n    4294967295,           # 2^32 - 1\n    4294967296,           # 2^32\n    1099511627775,        # 2^40 - 1\n    281474976710655,      # 2^48 - 1\n    72057594037927935,    # 2^56 - 1\n    9223372036854775807,  # max i64\n    -2147483649,          # just below i32 min\n    -4294967296,          # -2^32\n    -9223372036854775808, # min i64\n]\n\n# Test values for f64 write/read operations\nF64_TEST_VALUES: list[float] = [\n    0.0, -0.0, 1.0, -1.0,\n    -113.0,  # mypyc overlapping error value\n    0.5, -0.5, 0.1, -0.1,\n    1.5, 255.0, 256.0,\n    1e10, -1e10, 1e100, -1e100,\n    1e-10, 1e-100,\n    1.7976931348623157e+308,   # max float\n    -1.7976931348623157e+308,  # min float\n    2.2250738585072014e-308,   # min positive normal\n    5e-324,                    # min positive subnormal\n    float('inf'), float('-inf'),\n    float('nan'),\n]\n\n# Test values for f32 write/read operations (values that fit in 32-bit float)\nF32_TEST_VALUES: list[float] = [\n    0.0, -0.0, 1.0, -1.0,\n    -113.0,  # mypyc overlapping error value\n    0.5, -0.5, 0.1, -0.1,\n    1.5, 255.0, 256.0,\n    1e10, -1e10,\n    1e-10,\n    3.4028235e+38,    # max float32\n    -3.4028235e+38,   # min float32\n    1.1754944e-38,    # min positive normal float32\n    float('inf'), float('-inf'),\n    float('nan'),\n]\n\ndef test_bytes_writer_basics() -> None:\n    w = BytesWriter()\n    assert w.getvalue() == b\"\"\n    assert len(w) == 0\n    assert repr(w) == \"BytesWriter(b'')\"\n\n    w = BytesWriter()\n    w.append(ord('a'))\n    w.write(b'bc')\n    assert w.getvalue() == b\"abc\"\n    assert repr(w) == \"BytesWriter(b'abc')\"\n\ndef test_bytes_writer_get_item() -> None:\n    w = BytesWriter()\n    w.write(b\"foobar\")\n    assert w[0] == ord(\"f\")\n    assert w[5] == ord(\"r\")\n    assert w[-1] == ord(\"r\")\n    assert w[-2] == ord(\"a\")\n    assert w[-6] == ord(\"f\")\n\n    with assertRaises(IndexError):\n        w[6]\n    with assertRaises(IndexError):\n        w[-7]\n    with assertRaises(IndexError):\n        w[1 << 50]\n    with assertRaises(IndexError):\n        w[-(1 << 50)]\n\ndef test_bytes_writer_set_item() -> None:\n    w = BytesWriter()\n    w.write(b\"foobar\")\n    w[0] = 255\n    assert w[0] == 255\n    w[5] = 0\n    assert w[5] == 0\n    assert w.getvalue() == b\"\\xffooba\\x00\"\n\n    with assertRaises(IndexError):\n        w[6] = 0\n    with assertRaises(IndexError):\n        w[-7] = 0\n    with assertRaises(IndexError):\n        w[1 << 50] = 0\n    with assertRaises(IndexError):\n        w[-(1 << 50)] = 0\n\n    with assertRaises(ValueError):\n        w[0] = int() - 1\n    with assertRaises(ValueError):\n        w[0] = int() + 256\n\n    # Grow BytesWriter\n    w.write(b\"xy\" * 512)\n    w[1024 + 5] = 66\n    assert w[1024 + 5] == 66\n    assert w[0] == 255\n\ndef test_bytes_writer_append_grow() -> None:\n    w = BytesWriter()\n    for i in range(16384):\n        w.append((i ^ (i >> 8)) & 255)\n        assert len(w) == i + 1\n    b = w.getvalue()\n    for i in range(16384):\n        assert b[i] == (i ^ (i >> 8)) & 255\n\ndef test_bytes_writer_write_grow() -> None:\n    w = BytesWriter()\n    for i in range(16384):\n        w.write(bytes([(i ^ (i >> 8)) & 255]))\n    b = w.getvalue()\n    for i in range(16384):\n        assert b[i] == (i ^ (i >> 8)) & 255\n        assert b[i] == w[i]\n\n    w = BytesWriter()\n    a = []\n    for i in range(16384):\n        w.write(bytes())\n        if i & 1 == 0:\n            segment = b\"foobarz\"\n        else:\n            segment = b\"\\x7f\\x00ab!\"\n        w.write(segment)\n        a.append(segment)\n    assert w.getvalue() == b\"\".join(a)\n\ndef test_bytes_writer_truncate() -> None:\n    b = BytesWriter()\n    b.write(b\"foobar\")\n    b.truncate(6)  # No-op\n    assert len(b) == 6\n    assert b.getvalue() == b\"foobar\"\n    b.truncate(5)\n    assert len(b) == 5\n    assert b.getvalue() == b\"fooba\"\n    b.truncate(0)\n    assert len(b) == 0\n    assert b.getvalue() == b\"\"\n\n    with assertRaises(ValueError):\n        b.truncate(1)\n\n    b = BytesWriter()\n    b.write(b\"foobar\")\n    with assertRaises(ValueError):\n        b.truncate(-1)\n\ndef test_bytes_writer_write_i16_le() -> None:\n    # Test various i16 values from 1-byte to 2-byte range\n    w = BytesWriter()\n    for v in I16_TEST_VALUES:\n        write_i16_le(w, v)\n    assert w.getvalue() == b\"\".join(struct.pack(\"<h\", v) for v in I16_TEST_VALUES)\n\n    # Test mixing with other operations and buffer growth\n    w = BytesWriter()\n    w.append(0xFF)\n    for i in range(1000):\n        write_i16_le(w, i)\n    w.append(0xEE)\n    result = w.getvalue()\n    assert len(result) == 2002\n    assert result[0] == 0xFF\n    assert result[-1] == 0xEE\n    # Check a few values in the middle\n    assert result[1:3] == b\"\\x00\\x00\"  # i=0\n    assert result[3:5] == b\"\\x01\\x00\"  # i=1\n    assert result[1999:2001] == b\"\\xe7\\x03\"  # i=999\n\ndef test_write_i16_via_any() -> None:\n    # Test write_i16_le/be via Any to ensure C extension wrapper works\n    # (tests fallback path when not using mypyc primitives)\n    for write_func, fmt in zip((write_i16_le, write_i16_be), (\"<h\", \">h\")):\n        w: Any = BytesWriter()\n\n        # Test 8-bit and 16-bit operations\n        w.append(0x42)\n        write_func(w, 0x1234)\n        w.append(0xFF)\n        assert w.getvalue() == b\"\\x42\" + struct.pack(fmt, 0x1234) + b\"\\xFF\"\n\n        # Test buffer growth\n        w2: Any = BytesWriter()\n        for i in range(150):\n            write_func(w2, i)\n        result = w2.getvalue()\n        assert len(result) == 300\n        assert result[0:2] == struct.pack(fmt, 0)    # i=0\n        assert result[2:4] == struct.pack(fmt, 1)    # i=1\n        assert result[298:300] == struct.pack(fmt, 149)  # i=149\n\n        # Test values that don't fit in i16\n        w3: Any = BytesWriter()\n        with assertRaises(ValueError, \"int too large to convert to i16\"):\n            write_func(w3, 32768 + int())\n        with assertRaises(ValueError, \"int too large to convert to i16\"):\n            write_func(w3, -32769 + int())\n        with assertRaises(ValueError, \"int too large to convert to i16\"):\n            write_func(w3, 100000 + int())\n\ndef test_bytes_reader_read_i16_le() -> None:\n    # Test various i16 values from 1-byte to 2-byte range\n    data = b\"\".join(struct.pack(\"<h\", v) for v in I16_TEST_VALUES)\n    for i, v in enumerate(I16_TEST_VALUES):\n        assert read_i16_le(data, i * 2) == v\n\n    # Test round-trip with write_i16_le\n    w = BytesWriter()\n    for v in I16_TEST_VALUES:\n        write_i16_le(w, v)\n    result = w.getvalue()\n    for i, v in enumerate(I16_TEST_VALUES):\n        assert read_i16_le(result, i * 2) == v\n\n    # Test unaligned offset\n    data2 = b\"\\xFF\" + struct.pack(\"<h\", 0x1234) + b\"\\xFF\"\n    assert read_i16_le(data2, 1) == 0x1234\n\n    # Test barely out of bounds (only 1 byte available, need 2)\n    with assertRaises(IndexError):\n        read_i16_le(data, len(data) - 1)\n\ndef test_bytes_reader_read_i16_be() -> None:\n    # Test various i16 values from 1-byte to 2-byte range\n    data = b\"\".join(struct.pack(\">h\", v) for v in I16_TEST_VALUES)\n    for i, v in enumerate(I16_TEST_VALUES):\n        assert read_i16_be(data, i * 2) == v\n\n    # Test round-trip with write_i16_be\n    w = BytesWriter()\n    for v in I16_TEST_VALUES:\n        write_i16_be(w, v)\n    result = w.getvalue()\n    for i, v in enumerate(I16_TEST_VALUES):\n        assert read_i16_be(result, i * 2) == v\n\n    # Test unaligned offset\n    data2 = b\"\\xFF\" + struct.pack(\">h\", 0x1234) + b\"\\xFF\"\n    assert read_i16_be(data2, 1) == 0x1234\n\n    # Test barely out of bounds (only 1 byte available, need 2)\n    with assertRaises(IndexError):\n        read_i16_be(data, len(data) - 1)\n\ndef test_read_i16_via_any() -> None:\n    # Test read_i16_le/be via Any to ensure C extension wrapper works\n    for read_func, fmt in zip((read_i16_le, read_i16_be), (\"<h\", \">h\")):\n        data: Any = struct.pack(fmt, 0x1234) + struct.pack(fmt, -1) + struct.pack(fmt, 0)\n        assert read_func(data, 0) == 0x1234\n        assert read_func(data, 2) == -1\n        assert read_func(data, 4) == 0\n\n        # Test error cases\n        # Index out of range\n        with assertRaises(IndexError, \"index 10 out of range for bytes of length 6\"):\n            read_func(data, 10 + int())\n        with assertRaises(IndexError, \"index 5 out of range for bytes of length 6\"):\n            read_func(data, 5 + int())  # Not enough bytes for i16\n\n        # Negative index\n        with assertRaises(ValueError, \"index must be non-negative\"):\n            read_func(data, -1 + int())\n\n        # Wrong type for bytes argument\n        with assertRaises(TypeError):\n            bad: Any = \"not bytes\"\n            read_func(bad, 0 + int())\n        with assertRaises(TypeError):\n            bad2: Any = bytearray(b\"\\x00\\x00\")\n            read_func(bad2, 0 + int())\n\ndef test_bytes_writer_write_i16_be() -> None:\n    # Test various i16 values from 1-byte to 2-byte range\n    w = BytesWriter()\n    for v in I16_TEST_VALUES:\n        write_i16_be(w, v)\n    assert w.getvalue() == b\"\".join(struct.pack(\">h\", v) for v in I16_TEST_VALUES)\n\n    # Test mixing with other operations and buffer growth\n    w = BytesWriter()\n    w.append(0xFF)\n    for i in range(1000):\n        write_i16_be(w, i)\n    w.append(0xEE)\n    result = w.getvalue()\n    assert len(result) == 2002\n    assert result[0] == 0xFF\n    assert result[-1] == 0xEE\n    # Check a few values in the middle\n    assert result[1:3] == b\"\\x00\\x00\"  # i=0\n    assert result[3:5] == b\"\\x00\\x01\"  # i=1\n    assert result[1999:2001] == b\"\\x03\\xe7\"  # i=999\n\ndef test_bytes_writer_write_i32_le() -> None:\n    # Test various i32 values from 1-byte to 4-byte range\n    w = BytesWriter()\n    for v in I32_TEST_VALUES:\n        write_i32_le(w, v)\n    assert w.getvalue() == b\"\".join(struct.pack(\"<i\", v) for v in I32_TEST_VALUES)\n\n    # Test mixing with other operations and buffer growth\n    w = BytesWriter()\n    w.append(0xFF)\n    for i in range(500):\n        write_i32_le(w, i * 1000)\n    w.append(0xEE)\n    result = w.getvalue()\n    assert len(result) == 2002\n    assert result[0] == 0xFF\n    assert result[-1] == 0xEE\n    # Check a few values in the middle\n    assert result[1:5] == struct.pack(\"<i\", 0)\n    assert result[5:9] == struct.pack(\"<i\", 1000)\n    assert result[1997:2001] == struct.pack(\"<i\", 499000)\n\ndef test_bytes_writer_write_i32_be() -> None:\n    # Test various i32 values from 1-byte to 4-byte range\n    w = BytesWriter()\n    for v in I32_TEST_VALUES:\n        write_i32_be(w, v)\n    assert w.getvalue() == b\"\".join(struct.pack(\">i\", v) for v in I32_TEST_VALUES)\n\n    # Test mixing with other operations and buffer growth\n    w = BytesWriter()\n    w.append(0xFF)\n    for i in range(500):\n        write_i32_be(w, i * 1000)\n    w.append(0xEE)\n    result = w.getvalue()\n    assert len(result) == 2002\n    assert result[0] == 0xFF\n    assert result[-1] == 0xEE\n    # Check a few values in the middle\n    assert result[1:5] == struct.pack(\">i\", 0)\n    assert result[5:9] == struct.pack(\">i\", 1000)\n    assert result[1997:2001] == struct.pack(\">i\", 499000)\n\ndef test_write_i32_via_any() -> None:\n    # Test write_i32_le/be via Any to ensure C extension wrapper works\n    # (tests fallback path when not using mypyc primitives)\n    for write_func, fmt in zip((write_i32_le, write_i32_be), (\"<i\", \">i\")):\n        w: Any = BytesWriter()\n\n        # Test 8-bit and 32-bit operations\n        w.append(0x42)\n        write_func(w, 0x12345678)\n        w.append(0xFF)\n        assert w.getvalue() == b\"\\x42\" + struct.pack(fmt, 0x12345678) + b\"\\xFF\"\n\n        # Test buffer growth\n        w2: Any = BytesWriter()\n        for i in range(100):\n            write_func(w2, i * 10000)\n        result = w2.getvalue()\n        assert len(result) == 400\n        assert result[0:4] == struct.pack(fmt, 0)\n        assert result[4:8] == struct.pack(fmt, 10000)\n        assert result[396:400] == struct.pack(fmt, 990000)\n\n        # Test values that don't fit in i32\n        w3: Any = BytesWriter()\n        with assertRaises(ValueError, \"int too large to convert to i32\"):\n            write_func(w3, 2147483648 + int())\n        with assertRaises(ValueError, \"int too large to convert to i32\"):\n            write_func(w3, -2147483649 + int())\n        with assertRaises(ValueError, \"int too large to convert to i32\"):\n            write_func(w3, 10000000000 + int())\n\ndef test_bytes_reader_read_i32_le() -> None:\n    # Test various i32 values from 1-byte to 4-byte range\n    data = b\"\".join(struct.pack(\"<i\", v) for v in I32_TEST_VALUES)\n    for i, v in enumerate(I32_TEST_VALUES):\n        assert read_i32_le(data, i * 4) == v\n\n    # Test round-trip with write_i32_le\n    w = BytesWriter()\n    for v in I32_TEST_VALUES:\n        write_i32_le(w, v)\n    result = w.getvalue()\n    for i, v in enumerate(I32_TEST_VALUES):\n        assert read_i32_le(result, i * 4) == v\n\n    # Test unaligned offset\n    data2 = b\"\\xFF\" + struct.pack(\"<i\", 0x12345678) + b\"\\xFF\"\n    assert read_i32_le(data2, 1) == 0x12345678\n\n    # Test barely out of bounds (only 3 bytes available, need 4)\n    with assertRaises(IndexError):\n        read_i32_le(data, len(data) - 3)\n\ndef test_bytes_reader_read_i32_be() -> None:\n    # Test various i32 values from 1-byte to 4-byte range\n    data = b\"\".join(struct.pack(\">i\", v) for v in I32_TEST_VALUES)\n    for i, v in enumerate(I32_TEST_VALUES):\n        assert read_i32_be(data, i * 4) == v\n\n    # Test round-trip with write_i32_be\n    w = BytesWriter()\n    for v in I32_TEST_VALUES:\n        write_i32_be(w, v)\n    result = w.getvalue()\n    for i, v in enumerate(I32_TEST_VALUES):\n        assert read_i32_be(result, i * 4) == v\n\n    # Test unaligned offset\n    data2 = b\"\\xFF\" + struct.pack(\">i\", 0x12345678) + b\"\\xFF\"\n    assert read_i32_be(data2, 1) == 0x12345678\n\n    # Test barely out of bounds (only 3 bytes available, need 4)\n    with assertRaises(IndexError):\n        read_i32_be(data, len(data) - 3)\n\ndef test_read_i32_via_any() -> None:\n    # Test read_i32_le/be via Any to ensure C extension wrapper works\n    for read_func, fmt in zip((read_i32_le, read_i32_be), (\"<i\", \">i\")):\n        data: Any = struct.pack(fmt, 0x12345678) + struct.pack(fmt, -1) + struct.pack(fmt, 0)\n        assert read_func(data, 0) == 0x12345678\n        assert read_func(data, 4) == -1\n        assert read_func(data, 8) == 0\n\n        # Test error cases\n        # Index out of range\n        with assertRaises(IndexError, \"index 20 out of range for bytes of length 12\"):\n            read_func(data, 20 + int())\n        with assertRaises(IndexError, \"index 9 out of range for bytes of length 12\"):\n            read_func(data, 9 + int())  # Not enough bytes for i32\n\n        # Negative index\n        with assertRaises(ValueError, \"index must be non-negative\"):\n            read_func(data, -1 + int())\n\n        # Wrong type for bytes argument\n        with assertRaises(TypeError):\n            bad: Any = \"not bytes\"\n            read_func(bad, 0 + int())\n        with assertRaises(TypeError):\n            bad2: Any = bytearray(b\"\\x00\\x00\\x00\\x00\")\n            read_func(bad2, 0 + int())\n\ndef test_bytes_writer_write_i64_le() -> None:\n    # Test all i64 values (includes all i32 values plus 5-8 byte values)\n    w = BytesWriter()\n    for v in I64_TEST_VALUES:\n        write_i64_le(w, v)\n    assert w.getvalue() == b\"\".join(struct.pack(\"<q\", v) for v in I64_TEST_VALUES)\n\n    # Test mixing with other operations and buffer growth\n    w = BytesWriter()\n    w.append(0xFF)\n    for i in range(200):\n        write_i64_le(w, i * 1000000000)\n    w.append(0xEE)\n    result = w.getvalue()\n    assert len(result) == 1602\n    assert result[0] == 0xFF\n    assert result[-1] == 0xEE\n    assert result[1:9] == struct.pack(\"<q\", 0)\n    assert result[9:17] == struct.pack(\"<q\", 1000000000)\n    assert result[1593:1601] == struct.pack(\"<q\", 199000000000)\n\ndef test_bytes_writer_write_i64_be() -> None:\n    # Test all i64 values (includes all i32 values plus 5-8 byte values)\n    w = BytesWriter()\n    for v in I64_TEST_VALUES:\n        write_i64_be(w, v)\n    assert w.getvalue() == b\"\".join(struct.pack(\">q\", v) for v in I64_TEST_VALUES)\n\n    # Test mixing with other operations and buffer growth\n    w = BytesWriter()\n    w.append(0xFF)\n    for i in range(200):\n        write_i64_be(w, i * 1000000000)\n    w.append(0xEE)\n    result = w.getvalue()\n    assert len(result) == 1602\n    assert result[0] == 0xFF\n    assert result[-1] == 0xEE\n    assert result[1:9] == struct.pack(\">q\", 0)\n    assert result[9:17] == struct.pack(\">q\", 1000000000)\n    assert result[1593:1601] == struct.pack(\">q\", 199000000000)\n\ndef test_write_i64_via_any() -> None:\n    # Test write_i64_le/be via Any to ensure C extension wrapper works\n    for write_func, fmt in zip((write_i64_le, write_i64_be), (\"<q\", \">q\")):\n        w: Any = BytesWriter()\n\n        w.append(0x42)\n        write_func(w, 0x123456789ABCDEF0)\n        w.append(0xFF)\n        assert w.getvalue() == b\"\\x42\" + struct.pack(fmt, 0x123456789ABCDEF0) + b\"\\xFF\"\n\n        # Test buffer growth\n        w2: Any = BytesWriter()\n        for i in range(50):\n            write_func(w2, i * 10000000000)\n        result = w2.getvalue()\n        assert len(result) == 400\n        assert result[0:8] == struct.pack(fmt, 0)\n        assert result[8:16] == struct.pack(fmt, 10000000000)\n        assert result[392:400] == struct.pack(fmt, 490000000000)\n\ndef test_bytes_reader_read_i64_le() -> None:\n    # Test all i64 values (includes all i32 values plus 5-8 byte values)\n    data = b\"\".join(struct.pack(\"<q\", v) for v in I64_TEST_VALUES)\n    for i, v in enumerate(I64_TEST_VALUES):\n        assert read_i64_le(data, i * 8) == v\n\n    # Test round-trip with write_i64_le\n    w = BytesWriter()\n    for v in I64_TEST_VALUES:\n        write_i64_le(w, v)\n    result = w.getvalue()\n    for i, v in enumerate(I64_TEST_VALUES):\n        assert read_i64_le(result, i * 8) == v\n\n    # Test unaligned offset\n    data2 = b\"\\xFF\" + struct.pack(\"<q\", 0x123456789ABCDEF0) + b\"\\xFF\"\n    assert read_i64_le(data2, 1) == 0x123456789ABCDEF0\n\n    # Test barely out of bounds (only 7 bytes available, need 8)\n    with assertRaises(IndexError):\n        read_i64_le(data, len(data) - 7)\n\ndef test_bytes_reader_read_i64_be() -> None:\n    # Test all i64 values (includes all i32 values plus 5-8 byte values)\n    data = b\"\".join(struct.pack(\">q\", v) for v in I64_TEST_VALUES)\n    for i, v in enumerate(I64_TEST_VALUES):\n        assert read_i64_be(data, i * 8) == v\n\n    # Test round-trip with write_i64_be\n    w = BytesWriter()\n    for v in I64_TEST_VALUES:\n        write_i64_be(w, v)\n    result = w.getvalue()\n    for i, v in enumerate(I64_TEST_VALUES):\n        assert read_i64_be(result, i * 8) == v\n\n    # Test unaligned offset\n    data2 = b\"\\xFF\" + struct.pack(\">q\", 0x123456789ABCDEF0) + b\"\\xFF\"\n    assert read_i64_be(data2, 1) == 0x123456789ABCDEF0\n\n    # Test barely out of bounds (only 7 bytes available, need 8)\n    with assertRaises(IndexError):\n        read_i64_be(data, len(data) - 7)\n\ndef test_read_i64_via_any() -> None:\n    # Test read_i64_le/be via Any to ensure C extension wrapper works\n    for read_func, fmt in zip((read_i64_le, read_i64_be), (\"<q\", \">q\")):\n        data: Any = struct.pack(fmt, 0x123456789ABCDEF0) + struct.pack(fmt, -1) + struct.pack(fmt, 0)\n        assert read_func(data, 0) == 0x123456789ABCDEF0\n        assert read_func(data, 8) == -1\n        assert read_func(data, 16) == 0\n\n        # Test error cases\n        # Index out of range\n        with assertRaises(IndexError, \"index 30 out of range for bytes of length 24\"):\n            read_func(data, 30 + int())\n        with assertRaises(IndexError, \"index 17 out of range for bytes of length 24\"):\n            read_func(data, 17 + int())  # Not enough bytes for i64\n\n        # Negative index\n        with assertRaises(ValueError, \"index must be non-negative\"):\n            read_func(data, -1 + int())\n\n        # Wrong type for bytes argument\n        with assertRaises(TypeError):\n            bad: Any = \"not bytes\"\n            read_func(bad, 0 + int())\n        with assertRaises(TypeError):\n            bad2: Any = bytearray(b\"\\x00\" * 8)\n            read_func(bad2, 0 + int())\n\ndef test_bytes_writer_write_f64_le() -> None:\n    # Test various f64 values\n    w = BytesWriter()\n    for v in F64_TEST_VALUES:\n        write_f64_le(w, v)\n    result = w.getvalue()\n    expected = b\"\".join(struct.pack(\"<d\", v) for v in F64_TEST_VALUES)\n    # Compare byte-by-byte (NaN != NaN but bytes should match)\n    assert result == expected\n\n    # Test mixing with other operations and buffer growth\n    w = BytesWriter()\n    w.append(0xFF)\n    for i in range(200):\n        write_f64_le(w, float(i) * 1.5)\n    w.append(0xEE)\n    result = w.getvalue()\n    assert len(result) == 1602\n    assert result[0] == 0xFF\n    assert result[-1] == 0xEE\n    assert result[1:9] == struct.pack(\"<d\", 0.0)\n    assert result[9:17] == struct.pack(\"<d\", 1.5)\n    assert result[1593:1601] == struct.pack(\"<d\", 199.0 * 1.5)\n\ndef test_bytes_writer_write_f64_be() -> None:\n    # Test various f64 values\n    w = BytesWriter()\n    for v in F64_TEST_VALUES:\n        write_f64_be(w, v)\n    result = w.getvalue()\n    expected = b\"\".join(struct.pack(\">d\", v) for v in F64_TEST_VALUES)\n    # Compare byte-by-byte (NaN != NaN but bytes should match)\n    assert result == expected\n\n    # Test mixing with other operations and buffer growth\n    w = BytesWriter()\n    w.append(0xFF)\n    for i in range(200):\n        write_f64_be(w, float(i) * 1.5)\n    w.append(0xEE)\n    result = w.getvalue()\n    assert len(result) == 1602\n    assert result[0] == 0xFF\n    assert result[-1] == 0xEE\n    assert result[1:9] == struct.pack(\">d\", 0.0)\n    assert result[9:17] == struct.pack(\">d\", 1.5)\n    assert result[1593:1601] == struct.pack(\">d\", 199.0 * 1.5)\n\ndef test_bytes_reader_read_f64_le() -> None:\n    import math\n    # Test various f64 values\n    data = b\"\".join(struct.pack(\"<d\", v) for v in F64_TEST_VALUES)\n    for i, v in enumerate(F64_TEST_VALUES):\n        result = read_f64_le(data, i * 8)\n        if math.isnan(v):\n            assert math.isnan(result)\n        else:\n            assert result == v\n\n    # Test round-trip with write_f64_le\n    w = BytesWriter()\n    for v in F64_TEST_VALUES:\n        write_f64_le(w, v)\n    result_bytes = w.getvalue()\n    for i, v in enumerate(F64_TEST_VALUES):\n        result = read_f64_le(result_bytes, i * 8)\n        if math.isnan(v):\n            assert math.isnan(result)\n        else:\n            assert result == v\n\n    # Test unaligned offset\n    data2 = b\"\\xFF\" + struct.pack(\"<d\", 1.5) + b\"\\xFF\"\n    assert read_f64_le(data2, 1) == 1.5\n\n    # Test barely out of bounds (only 7 bytes available, need 8)\n    with assertRaises(IndexError):\n        read_f64_le(data, len(data) - 7)\n\ndef test_bytes_reader_read_f64_be() -> None:\n    import math\n    # Test various f64 values\n    data = b\"\".join(struct.pack(\">d\", v) for v in F64_TEST_VALUES)\n    for i, v in enumerate(F64_TEST_VALUES):\n        result = read_f64_be(data, i * 8)\n        if math.isnan(v):\n            assert math.isnan(result)\n        else:\n            assert result == v\n\n    # Test round-trip with write_f64_be\n    w = BytesWriter()\n    for v in F64_TEST_VALUES:\n        write_f64_be(w, v)\n    result_bytes = w.getvalue()\n    for i, v in enumerate(F64_TEST_VALUES):\n        result = read_f64_be(result_bytes, i * 8)\n        if math.isnan(v):\n            assert math.isnan(result)\n        else:\n            assert result == v\n\n    # Test unaligned offset\n    data2 = b\"\\xFF\" + struct.pack(\">d\", 1.5) + b\"\\xFF\"\n    assert read_f64_be(data2, 1) == 1.5\n\n    # Test barely out of bounds (only 7 bytes available, need 8)\n    with assertRaises(IndexError):\n        read_f64_be(data, len(data) - 7)\n\ndef test_read_f64_via_any() -> None:\n    import math\n    # Test read_f64_le/be via Any to ensure C extension wrapper works\n    for read_func, fmt in zip((read_f64_le, read_f64_be), (\"<d\", \">d\")):\n        data: Any = struct.pack(fmt, 1.5) + struct.pack(fmt, -113.0) + struct.pack(fmt, 0.0)\n        assert read_func(data, 0) == 1.5\n        assert read_func(data, 8) == -113.0\n        assert read_func(data, 16) == 0.0\n\n        # Test special values\n        data2: Any = struct.pack(fmt, float('inf')) + struct.pack(fmt, float('nan'))\n        assert read_func(data2, 0) == float('inf')\n        assert math.isnan(read_func(data2, 8))\n\n        # Test error cases\n        # Index out of range\n        with assertRaises(IndexError, \"index 30 out of range for bytes of length 24\"):\n            read_func(data, 30 + int())\n        with assertRaises(IndexError, \"index 17 out of range for bytes of length 24\"):\n            read_func(data, 17 + int())  # Not enough bytes for f64\n\n        # Negative index\n        with assertRaises(ValueError, \"index must be non-negative\"):\n            read_func(data, -1 + int())\n\n        # Wrong type for bytes argument\n        with assertRaises(TypeError):\n            bad: Any = \"not bytes\"\n            read_func(bad, 0 + int())\n        with assertRaises(TypeError):\n            bad2: Any = bytearray(b\"\\x00\" * 8)\n            read_func(bad2, 0 + int())\n\ndef test_write_f64_via_any() -> None:\n    import math\n    # Test write_f64_le/be via Any to ensure C extension wrapper works\n    for write_func, fmt in zip((write_f64_le, write_f64_be), (\"<d\", \">d\")):\n        w: Any = BytesWriter()\n\n        w.append(0x42)\n        write_func(w, 1.5)\n        w.append(0xFF)\n        assert w.getvalue() == b\"\\x42\" + struct.pack(fmt, 1.5) + b\"\\xFF\"\n\n        # Test buffer growth\n        w2: Any = BytesWriter()\n        for i in range(50):\n            write_func(w2, float(i) * 0.25)\n        result = w2.getvalue()\n        assert len(result) == 400\n        assert result[0:8] == struct.pack(fmt, 0.0)\n        assert result[8:16] == struct.pack(fmt, 0.25)\n        assert result[392:400] == struct.pack(fmt, 49.0 * 0.25)\n\n        # Test special values\n        w3: Any = BytesWriter()\n        write_func(w3, float('inf'))\n        write_func(w3, float('-inf'))\n        write_func(w3, float('nan'))\n        result = w3.getvalue()\n        assert result[0:8] == struct.pack(fmt, float('inf'))\n        assert result[8:16] == struct.pack(fmt, float('-inf'))\n        assert math.isnan(struct.unpack(fmt, result[16:24])[0])\n\n        # Test wrong type\n        w4: Any = BytesWriter()\n        with assertRaises(TypeError):\n            bad: Any = \"not a float\" + str()\n            write_func(w4, bad)\n\ndef test_bytes_writer_write_f32_le() -> None:\n    import struct as s\n    # Test various f32 values\n    w = BytesWriter()\n    for v in F32_TEST_VALUES:\n        write_f32_le(w, v)\n    result = w.getvalue()\n    expected = b\"\".join(s.pack(\"<f\", v) for v in F32_TEST_VALUES)\n    # Compare byte-by-byte (NaN != NaN but bytes should match)\n    assert result == expected\n\n    # Test mixing with other operations and buffer growth\n    w = BytesWriter()\n    w.append(0xFF)\n    for i in range(200):\n        write_f32_le(w, float(i) * 1.5)\n    w.append(0xEE)\n    result = w.getvalue()\n    assert len(result) == 802\n    assert result[0] == 0xFF\n    assert result[-1] == 0xEE\n    assert result[1:5] == s.pack(\"<f\", 0.0)\n    assert result[5:9] == s.pack(\"<f\", 1.5)\n    assert result[797:801] == s.pack(\"<f\", 199.0 * 1.5)\n\ndef test_bytes_writer_write_f32_be() -> None:\n    import struct as s\n    # Test various f32 values\n    w = BytesWriter()\n    for v in F32_TEST_VALUES:\n        write_f32_be(w, v)\n    result = w.getvalue()\n    expected = b\"\".join(s.pack(\">f\", v) for v in F32_TEST_VALUES)\n    # Compare byte-by-byte (NaN != NaN but bytes should match)\n    assert result == expected\n\n    # Test mixing with other operations and buffer growth\n    w = BytesWriter()\n    w.append(0xFF)\n    for i in range(200):\n        write_f32_be(w, float(i) * 1.5)\n    w.append(0xEE)\n    result = w.getvalue()\n    assert len(result) == 802\n    assert result[0] == 0xFF\n    assert result[-1] == 0xEE\n    assert result[1:5] == s.pack(\">f\", 0.0)\n    assert result[5:9] == s.pack(\">f\", 1.5)\n    assert result[797:801] == s.pack(\">f\", 199.0 * 1.5)\n\ndef test_write_f32_via_any() -> None:\n    import math\n    # Test write_f32_le/be via Any to ensure C extension wrapper works\n    for write_func, fmt in zip((write_f32_le, write_f32_be), (\"<f\", \">f\")):\n        w: Any = BytesWriter()\n\n        w.append(0x42)\n        write_func(w, 1.5)\n        w.append(0xFF)\n        assert w.getvalue() == b\"\\x42\" + struct.pack(fmt, 1.5) + b\"\\xFF\"\n\n        # Test buffer growth\n        w2: Any = BytesWriter()\n        for i in range(100):\n            write_func(w2, float(i) * 0.25)\n        result = w2.getvalue()\n        assert len(result) == 400\n        assert result[0:4] == struct.pack(fmt, 0.0)\n        assert result[4:8] == struct.pack(fmt, 0.25)\n        assert result[396:400] == struct.pack(fmt, 99.0 * 0.25)\n\n        # Test special values\n        w3: Any = BytesWriter()\n        write_func(w3, float('inf'))\n        write_func(w3, float('-inf'))\n        write_func(w3, float('nan'))\n        result = w3.getvalue()\n        assert result[0:4] == struct.pack(fmt, float('inf'))\n        assert result[4:8] == struct.pack(fmt, float('-inf'))\n        assert math.isnan(struct.unpack(fmt, result[8:12])[0])\n\n        # Test wrong type\n        w4: Any = BytesWriter()\n        with assertRaises(TypeError):\n            bad: Any = \"not a float\" + str()\n            write_func(w4, bad)\n\ndef test_bytes_reader_read_f32_le() -> None:\n    import math\n    import struct as s\n    # Test various f32 values (compare against f32-rounded expected value,\n    # since some f64 values like 0.1 lose precision when stored as f32)\n    data = b\"\".join(s.pack(\"<f\", v) for v in F32_TEST_VALUES)\n    for i, v in enumerate(F32_TEST_VALUES):\n        result = read_f32_le(data, i * 4)\n        expected = s.unpack(\"<f\", s.pack(\"<f\", v))[0]\n        if math.isnan(v):\n            assert math.isnan(result)\n        else:\n            assert result == expected\n\n    # Test round-trip with write_f32_le\n    w = BytesWriter()\n    for v in F32_TEST_VALUES:\n        write_f32_le(w, v)\n    result_bytes = w.getvalue()\n    for i, v in enumerate(F32_TEST_VALUES):\n        result = read_f32_le(result_bytes, i * 4)\n        expected = s.unpack(\"<f\", s.pack(\"<f\", v))[0]\n        if math.isnan(v):\n            assert math.isnan(result)\n        else:\n            assert result == expected\n\n    # Test unaligned offset\n    data2 = b\"\\xFF\" + s.pack(\"<f\", 1.5) + b\"\\xFF\"\n    assert read_f32_le(data2, 1) == 1.5\n\n    # Test barely out of bounds (only 3 bytes available, need 4)\n    with assertRaises(IndexError):\n        read_f32_le(data, len(data) - 3)\n\ndef test_bytes_reader_read_f32_be() -> None:\n    import math\n    import struct as s\n    # Test various f32 values (compare against f32-rounded expected value,\n    # since some f64 values like 0.1 lose precision when stored as f32)\n    data = b\"\".join(s.pack(\">f\", v) for v in F32_TEST_VALUES)\n    for i, v in enumerate(F32_TEST_VALUES):\n        result = read_f32_be(data, i * 4)\n        expected = s.unpack(\">f\", s.pack(\">f\", v))[0]\n        if math.isnan(v):\n            assert math.isnan(result)\n        else:\n            assert result == expected\n\n    # Test round-trip with write_f32_be\n    w = BytesWriter()\n    for v in F32_TEST_VALUES:\n        write_f32_be(w, v)\n    result_bytes = w.getvalue()\n    for i, v in enumerate(F32_TEST_VALUES):\n        result = read_f32_be(result_bytes, i * 4)\n        expected = s.unpack(\">f\", s.pack(\">f\", v))[0]\n        if math.isnan(v):\n            assert math.isnan(result)\n        else:\n            assert result == expected\n\n    # Test unaligned offset\n    data2 = b\"\\xFF\" + s.pack(\">f\", 1.5) + b\"\\xFF\"\n    assert read_f32_be(data2, 1) == 1.5\n\n    # Test barely out of bounds (only 3 bytes available, need 4)\n    with assertRaises(IndexError):\n        read_f32_be(data, len(data) - 3)\n\ndef test_read_f32_via_any() -> None:\n    import math\n    # Test read_f32_le/be via Any to ensure C extension wrapper works\n    for read_func, fmt in zip((read_f32_le, read_f32_be), (\"<f\", \">f\")):\n        data: Any = struct.pack(fmt, 1.5) + struct.pack(fmt, -113.0) + struct.pack(fmt, 0.0)\n        assert read_func(data, 0) == 1.5\n        assert read_func(data, 4) == -113.0\n        assert read_func(data, 8) == 0.0\n\n        # Test special values\n        data2: Any = struct.pack(fmt, float('inf')) + struct.pack(fmt, float('nan'))\n        assert read_func(data2, 0) == float('inf')\n        assert math.isnan(read_func(data2, 4))\n\n        # Test error cases\n        # Index out of range\n        with assertRaises(IndexError, \"index 20 out of range for bytes of length 12\"):\n            read_func(data, 20 + int())\n        with assertRaises(IndexError, \"index 9 out of range for bytes of length 12\"):\n            read_func(data, 9 + int())  # Not enough bytes for f32\n\n        # Negative index\n        with assertRaises(ValueError, \"index must be non-negative\"):\n            read_func(data, -1 + int())\n\n        # Wrong type for bytes argument\n        with assertRaises(TypeError):\n            bad: Any = \"not bytes\"\n            read_func(bad, 0 + int())\n        with assertRaises(TypeError):\n            bad2: Any = bytearray(b\"\\x00\" * 4)\n            read_func(bad2, 0 + int())\n\ndef test_write_bytearray() -> None:\n    w = BytesWriter()\n    w.write(bytearray(b\"foobar\"))\n    w.write(bytearray(b\"\"))\n    w.write(bytearray(b\"\\x00\\xf8\"))\n    assert w.getvalue() == b\"foobar\\x00\\xf8\"\n\ndef test_cast_bytes_writer() -> None:\n    a: Any = BytesWriter()\n    b: BytesWriter = a\n    assert b.getvalue() == b\"\"\n\n    a2: Any = \"x\"\n    with assertRaises(TypeError):\n        b = a2\n\ndef test_bytes_writer_wrapper_functions() -> None:\n    cls: Any = BytesWriter\n    b: Any = cls()\n    assert repr(b) == \"BytesWriter(b'')\"\n    assert len(b) == 0\n    b.append(ord('a'))\n    b.append(0)\n    b.append(255)\n    b.write(b\"foo\")\n    b.write(bytearray(b\"bar\"))\n    assert b.getvalue() == b\"a\\x00\\xfffoobar\"\n    assert len(b) == 9\n\n    assert b[0] == ord('a')\n    assert b[8] == ord('r')\n    assert b[-1] == ord('r')\n    assert b[-9] == ord('a')\n\n    b[0] = 215\n    b[8] = 0\n    assert b[0] == 215\n    assert b[8] == 0\n    b[-1] = 1\n    assert b[8] == 1\n    b[-9] = 2\n    assert b[0] == 2\n\n    assert isinstance(b, cls)\n\n    with assertRaises(TypeError):\n        b.append(\"x\")\n\n    with assertRaises(TypeError):\n        b.write(\"foo\")\n\n    with assertRaises(TypeError):\n        b.append(256)\n\n    with assertRaises(TypeError):\n        b.append(-1)\n\n    with assertRaises(IndexError):\n        b[9]\n    with assertRaises(IndexError):\n        b[-10]\n    with assertRaises(IndexError):\n        b[9] = 0\n    with assertRaises(IndexError):\n        b[-10] = 0\n\n    with assertRaises(TypeError):\n        b[0] = -1\n    with assertRaises(TypeError):\n        b[0] = 256\n\ndef test_string_writer_basics() -> None:\n    w = StringWriter()\n    assert w.getvalue() == \"\"\n\ndef test_string_writer_repr() -> None:\n    # Kind 1 (ASCII)\n    w = StringWriter()\n    assert repr(w) == \"StringWriter('')\"\n    w.append(ord('h'))\n    w.append(ord('i'))\n    assert repr(w) == \"StringWriter('hi')\"\n\n    # Kind 2 (UCS-2)\n    w2 = StringWriter()\n    w2.append(0x100)\n    w2.append(0x200)\n    assert repr(w2) == \"StringWriter('\" + chr(0x100) + chr(0x200) + \"')\"\n\n    # Kind 4 (UCS-4)\n    w3 = StringWriter()\n    w3.append(0x10000)\n    expected = \"StringWriter('\" + chr(0x10000) + \"')\"\n    assert repr(w3) == expected\n\ndef test_string_writer_repr_escaping() -> None:\n    # Kind 1: Test escaping of newline, nul, tab, backslash\n    w = StringWriter()\n    w.append(ord('a'))\n    w.append(ord('\\n'))\n    w.append(0)\n    w.append(ord('\\t'))\n    w.append(ord('\\\\'))\n    assert repr(w) == \"StringWriter('a\\\\n\\\\x00\\\\t\\\\\\\\')\"\n\n    # Kind 2: escaping with UCS-2\n    w2 = StringWriter()\n    w2.append(0x100)\n    w2.append(ord('\\n'))\n    assert repr(w2) == \"StringWriter('\" + chr(0x100) + \"\\\\n')\"\n\n    # Kind 4: escaping with UCS-4\n    w3 = StringWriter()\n    w3.append(0x10000)\n    w3.append(0)\n    assert repr(w3) == \"StringWriter('\" + chr(0x10000) + \"\\\\x00')\"\n\ndef test_string_writer_len() -> None:\n    # Kind 1 (ASCII)\n    w = StringWriter()\n    assert len(w) == 0\n    w.append(ord('a'))\n    assert len(w) == 1\n    w.append(ord('b'))\n    w.append(ord('c'))\n    assert len(w) == 3\n\n    # Kind 2 (UCS-2)\n    w2 = StringWriter()\n    w2.append(0x100)\n    assert len(w2) == 1\n    for i in range(10):\n        w2.append(0x200 + i)\n    assert len(w2) == 11\n\n    # Kind 4 (UCS-4)\n    w3 = StringWriter()\n    w3.append(0x10000)\n    assert len(w3) == 1\n    w3.append(0x10001)\n    w3.append(0x10002)\n    assert len(w3) == 3\n\n    # Test len after growing buffer\n    w4 = StringWriter()\n    for i in range(500):\n        w4.append(ord('X'))\n    assert len(w4) == 500\n\ndef test_string_writer_get_item() -> None:\n    # Kind 1 (ASCII)\n    w = StringWriter()\n    w.append(ord('f'))\n    w.append(ord('o'))\n    w.append(ord('o'))\n    assert w[0 + int()] == ord('f')\n    assert w[1 + int()] == ord('o')\n    assert w[2 + int()] == ord('o')\n    assert w[-1 + int()] == ord('o')\n    assert w[-2 + int()] == ord('o')\n    assert w[-3 + int()] == ord('f')\n\n    with assertRaises(IndexError):\n        w[3 + int()]\n    with assertRaises(IndexError):\n        w[-4 + int()]\n    with assertRaises(IndexError):\n        w[1 << 50]\n    with assertRaises(IndexError):\n        w[-(1 << 50)]\n\n    # Kind 2 (UCS-2)\n    w2 = StringWriter()\n    w2.append(0x100)\n    w2.append(0x200)\n    w2.append(0x300)\n    assert w2[0 + int()] == 0x100\n    assert w2[1 + int()] == 0x200\n    assert w2[2 + int()] == 0x300\n    assert w2[-1 + int()] == 0x300\n    assert w2[-2 + int()] == 0x200\n    assert w2[-3 + int()] == 0x100\n\n    with assertRaises(IndexError):\n        w2[3 + int()]\n    with assertRaises(IndexError):\n        w2[-4 + int()]\n\n    # Kind 4 (UCS-4)\n    w3 = StringWriter()\n    w3.append(0x10000)\n    w3.append(0x10001)\n    w3.append(0x10002)\n    assert w3[0 + int()] == 0x10000\n    assert w3[1 + int()] == 0x10001\n    assert w3[2 + int()] == 0x10002\n    assert w3[-1 + int()] == 0x10002\n    assert w3[-2 + int()] == 0x10001\n    assert w3[-3 + int()] == 0x10000\n\n    with assertRaises(IndexError):\n        w3[3 + int()]\n    with assertRaises(IndexError):\n        w3[-4 + int()]\n\n    # Test get_item after buffer growth\n    w4 = StringWriter()\n    for i in range(1000):\n        w4.append(ord('a') + (i % 26))\n    assert w4[0 + int()] == ord('a')\n    assert w4[999 + int()] == ord('a') + (999 % 26)\n    assert w4[500 + int()] == ord('a') + (500 % 26)\n    assert w4[-1 + int()] == ord('a') + (999 % 26)\n    assert w4[-1000 + int()] == ord('a')\n\ndef test_string_writer_append() -> None:\n    w = StringWriter()\n    w.append(ord('a'))\n    assert w.getvalue() == \"a\"\n    w.append(0xff)\n    assert w.getvalue() == \"a\\xff\"\n\n    # Switch kind 1->2\n    w.append(0x100)\n    assert w.getvalue() == \"a\\xff\\u0100\", w.getvalue()\n    w.append(0xffff)\n    assert w.getvalue() == \"a\\xff\\u0100\\uffff\"\n\n    # Switch kind 2->4\n    w.append(0x10000)\n    assert w.getvalue() == \"a\\xff\\u0100\\uffff\" + chr(0x10000)\n\n    # Maximum valid Unicode code point (0x10FFFF = 1114111)\n    w2 = StringWriter()\n    w2.append(0x10FFFF)\n    assert w2.getvalue() == chr(0x10FFFF)\n\n    # Invalid code points\n    w3 = StringWriter()\n    with assertRaises(ValueError, \"code point 1114112 is outside valid Unicode range (0-1114111)\"):\n        w3.append(0x110000)\n\n    w4 = StringWriter()\n    with assertRaises(ValueError, \"code point -1 is outside valid Unicode range (0-1114111)\"):\n        w4.append(-1)\n\n    w5 = StringWriter()\n    with assertRaises(ValueError, \"code point 2097152 is outside valid Unicode range (0-1114111)\"):\n        w5.append(0x200000)\n\ndef test_string_writer_write() -> None:\n    # Kind 1: Write ASCII strings\n    w = StringWriter()\n    w.write(\"hello\")\n    assert w.getvalue() == \"hello\"\n    w.write(\" world\")\n    assert w.getvalue() == \"hello world\"\n\n    # Write empty string\n    w.write(\"\")\n    assert w.getvalue() == \"hello world\"\n\n    # Kind 1 -> Kind 2: Write string with UCS-2 characters\n    w2 = StringWriter()\n    w2.write(\"abc\")\n    assert w2.getvalue() == \"abc\"\n    w2.write(chr(0x100) + chr(0x200))\n    assert w2.getvalue() == \"abc\" + chr(0x100) + chr(0x200)\n    w2.write(\"xyz\")\n    assert w2.getvalue() == \"abc\" + chr(0x100) + chr(0x200) + \"xyz\"\n\n    # Kind 2: Write all UCS-2\n    w3 = StringWriter()\n    w3.append(0x100)\n    w3.write(chr(0x200) + chr(0x300))\n    assert w3.getvalue() == chr(0x100) + chr(0x200) + chr(0x300)\n\n    # Kind 2 -> Kind 4: Write string with UCS-4 characters\n    w4 = StringWriter()\n    w4.write(chr(0x100))\n    w4.write(chr(0x10000))\n    assert w4.getvalue() == chr(0x100) + chr(0x10000)\n\n    # Kind 4: Write mixed\n    w5 = StringWriter()\n    w5.append(0x10000)\n    w5.write(\"abc\")\n    w5.write(chr(0x200))\n    w5.write(chr(0x10001))\n    assert w5.getvalue() == chr(0x10000) + \"abc\" + chr(0x200) + chr(0x10001)\n\n    # Test with longer strings to trigger buffer growth\n    w6 = StringWriter()\n    for _ in range(100):\n        w6.write(\"hello\")\n    assert w6.getvalue() == \"hello\" * 100\n    assert len(w6) == 500\n\ndef test_string_writer_append_grow_same_kind() -> None:\n    # Test growing buffer while staying in kind 1 (ASCII)\n    w = StringWriter()\n    # Append enough ASCII characters to grow beyond embedded buffer\n    for i in range(1000):\n        w.append(ord('a') + (i % 26))\n        assert len(w) == i + 1\n    result = w.getvalue()\n    assert len(result) == 1000\n    for i in range(1000):\n        assert result[i] == chr(ord('a') + (i % 26))\n\n    # Test growing buffer while staying in kind 2\n    w2 = StringWriter()\n    w2.append(0x100)  # Switch to kind 2\n    for i in range(1000):\n        w2.append(0x100 + (i % 100))\n        assert len(w2) == i + 2\n    result2 = w2.getvalue()\n    assert len(result2) == 1001\n    assert result2[0] == chr(0x100)\n    for i in range(1000):\n        assert result2[i + 1] == chr(0x100 + (i % 100))\n\n    # Test growing buffer while staying in kind 4\n    w3 = StringWriter()\n    w3.append(0x10000)  # Switch to kind 4\n    for i in range(500):\n        w3.append(0x10000 + (i % 100))\n        assert len(w3) == i + 2\n    result3 = w3.getvalue()\n    assert len(result3) == 501\n    assert result3[0] == chr(0x10000)\n    for i in range(500):\n        assert result3[i + 1] == chr(0x10000 + (i % 100))\n\ndef test_string_writer_append_grow_and_switch_kind() -> None:\n    # Test growing buffer AND switching from kind 1 to kind 2\n    w = StringWriter()\n    # Fill with ASCII to grow buffer\n    for i in range(500):\n        w.append(ord('A'))\n    assert len(w) == 500\n    # Now append non-ASCII that requires kind 2, triggering both grow and kind switch\n    for i in range(500):\n        w.append(0x100 + i)\n    result = w.getvalue()\n    assert len(result) == 1000\n    for i in range(500):\n        assert result[i] == 'A'\n    for i in range(500):\n        assert result[500 + i] == chr(0x100 + i)\n\n    # Test growing buffer AND switching from kind 2 to kind 4\n    w2 = StringWriter()\n    w2.append(0x100)  # Switch to kind 2\n    # Fill with kind 2 characters to grow buffer\n    for i in range(300):\n        w2.append(0x200 + (i % 100))\n    assert len(w2) == 301\n    # Now append characters that require kind 4, triggering both grow and kind switch\n    for i in range(300):\n        w2.append(0x10000 + i)\n    result2 = w2.getvalue()\n    assert len(result2) == 601\n    assert result2[0] == chr(0x100)\n    for i in range(300):\n        assert result2[1 + i] == chr(0x200 + (i % 100))\n    for i in range(300):\n        assert result2[301 + i] == chr(0x10000 + i)\n\n    # Test switching kind 1->4 with buffer growth\n    w3 = StringWriter()\n    for i in range(300):\n        w3.append(ord('X'))\n    # Jump directly to kind 4\n    w3.append(0x10000)\n    result3 = w3.getvalue()\n    assert len(result3) == 301\n    for i in range(300):\n        assert result3[i] == 'X'\n    assert result3[300] == chr(0x10000)\n\ndef test_string_writer_wrapper_functions() -> None:\n    cls: Any = StringWriter\n    s: Any = cls()\n    assert repr(s) == \"StringWriter('')\"\n    assert len(s) == 0\n    s.append(ord('a'))\n    s.append(0x100)\n    s.append(0x10000)\n    s.write(\"foo\")\n    assert s.getvalue() == \"a\" + chr(0x100) + chr(0x10000) + \"foo\"\n    assert len(s) == 6\n\n    assert s[0] == ord('a')\n    assert s[1] == 0x100\n    assert s[2] == 0x10000\n    assert s[-1] == ord('o')\n    assert s[-6] == ord('a')\n\n    assert isinstance(s, cls)\n\n    with assertRaises(TypeError):\n        s.append(\"x\")\n\n    with assertRaises(TypeError):\n        s.write(b\"foo\")\n\n    with assertRaises(ValueError):\n        s.append(0x110000)\n\n    with assertRaises(ValueError):\n        s.append(-1)\n\n    with assertRaises(IndexError):\n        s[6]\n    with assertRaises(IndexError):\n        s[-7]\n\n[case testStringsFeaturesNotAvailableInNonExperimentalBuild_librt]\n# This also ensures librt.strings can be built without experimental features\nimport librt.strings\n\ndef test_bytes_writer_not_available() -> None:\n    assert not hasattr(librt.strings, \"BytesWriter\")\n"
  },
  {
    "path": "mypyc/test-data/run-librt-time.test",
    "content": "[case testTimeBasic_librt_experimental]\nimport time as stdlib_time\nfrom librt.time import time\n\ndef test_time_returns_float() -> None:\n    result = time()\n    assert isinstance(result, float)\n\ndef test_time_is_reasonable() -> None:\n    # Should return a Unix timestamp, which should be a large positive number\n    result = time()\n    # Check it's after year 2020 (timestamp > 1577836800)\n    assert result > 1577836800.0\n    # Check it's before year 2100 (timestamp < 4102444800)\n    assert result < 4102444800.0\n\ndef test_time_increments() -> None:\n    t1 = time()\n    t2 = time()\n    # Time should not go backwards (allowing for same value due to precision)\n    assert t2 >= t1\n\ndef test_time_comparable_to_stdlib() -> None:\n    # Our time() should return similar values to stdlib time.time()\n    our_time = time()\n    std_time = stdlib_time.time()\n    # Should be within 0.25 seconds of each other (usually should be much less,\n    # but keep it relatively high to avoid test flakiness in CI)\n    assert abs(our_time - std_time) < 0.25\n\n[case testTimeNotAvailableInNonExperimentalBuild_librt_time]\n# This also ensures librt.time can be built without experimental features\nimport librt.time\n\ndef test_time_not_available() -> None:\n    assert not hasattr(librt.time, \"time\")\n\n[case testTimeUsedAtTopLevelOnly_librt_experimental]\nfrom librt.time import time\n\n# The only reference to time() is at module top level\ncurrent_time = time()\n\ndef test_top_level_only_time() -> None:\n    assert isinstance(current_time, float)\n    assert current_time > 0.0\n"
  },
  {
    "path": "mypyc/test-data/run-lists.test",
    "content": "# Test cases for lists (compile and run)\n\n[case testListPlusEquals]\nfrom typing import Any\ndef append(x: Any) -> None:\n    x += [1]\n\n[file driver.py]\nfrom native import append\nx = []\nappend(x)\nassert x == [1]\n\n[case testListSum]\nfrom typing import List\ndef sum(a: List[int], l: int) -> int:\n    sum = 0\n    i = 0\n    while i < l:\n        sum = sum + a[i]\n        i = i + 1\n    return sum\n[file driver.py]\nfrom native import sum\nprint(sum([], 0))\nprint(sum([3], 1))\nprint(sum([5, 6, -4], 3))\nprint(sum([2**128 + 5, -2**127 - 8], 2))\n[out]\n0\n3\n7\n170141183460469231731687303715884105725\n\n[case testListSet]\nfrom typing import List\ndef copy(a: List[int], b: List[int], l: int) -> int:\n    i = 0\n    while i < l:\n        a[i] = b[i]\n        i = i + 1\n    return 0\n[file driver.py]\nfrom native import copy\na = [0, '']\ncopy(a, [-1, 5], 2)\nprint(1, a)\ncopy(a, [2**128 + 5, -2**127 - 8], 2)\nprint(2, a)\n[out]\n1 [-1, 5]\n2 [340282366920938463463374607431768211461, -170141183460469231731687303715884105736]\n\n[case testListClear]\nfrom typing import List, Any\nfrom copysubclass import subc\n\ndef test_list_clear() -> None:\n    l1 = [1, 2, 3, -4, 5]\n    l1.clear()\n    assert l1 == []\n    l1.clear()\n    assert l1 == []\n    l2: List[Any] = []\n    l2.clear()\n    assert l2 == []\n    l3 = [1, 2, 3, \"abcdef\"]\n    l3.clear()\n    assert l3 == []\n    # subclass testing\n    l4: subc = subc([1, 2, 3])\n    l4.clear()\n    assert l4 == []\n\n[file copysubclass.py]\nfrom typing import Any\nclass subc(list[Any]):\n    pass\n\n[case testListCopy]\nfrom typing import List\nfrom copysubclass import subc\n\ndef test_list_copy() -> None:\n    l1 = [1, 2, 3, -4, 5]\n    l2 = l1.copy()\n    assert l1.copy() == l1\n    assert l1.copy() == l2\n    assert l1 == l2\n    assert l1.copy() == l2.copy()\n    l1 = l2.copy()\n    assert l1 == l2\n    assert l1.copy() == l2\n    assert l1 == [1, 2, 3, -4, 5]\n    l2 = [1, 2, -3]\n    l1 = []\n    assert l1.copy() == []\n    assert l2.copy() != l1\n    assert l2 == l2.copy()\n    l1 = l2\n    assert l1.copy().copy() == l2.copy().copy().copy()\n    assert l1.copy() == l2.copy()\n    l1 == [1, 2, -3].copy()\n    assert l1 == l2\n    l2 = [1, 2, 3].copy()\n    assert l2 != l1\n    l1 = [1, 2, 3]\n    assert l1.copy() == l2.copy()\n    l3 = [1, 2 , 3, \"abcdef\"]\n    assert l3 == l3.copy()\n    l4 = [\"abc\", 5, 10]\n    l4 = l3.copy()\n    assert l4 == l3\n    #subclass testing\n    l5: subc = subc([1, 2, 3])\n    l6 = l5.copy()\n    assert l6 == l5\n    l6 = [1, 2, \"3\", 4, 5]\n    l5 = subc([1,2,\"3\",4,5])\n    assert l5.copy() == l6.copy()\n    l6 = l5.copy()\n    assert l5 == l6\n\n[file copysubclass.py]\nfrom typing import Any\nclass subc(list[Any]):\n    pass\n\n[case testSieve]\nfrom typing import List\n\ndef primes(n: int) -> List[int]:\n    a = [1] * (n + 1)\n    a[0] = 0\n    a[1] = 0\n    i = 0\n    while i < n:\n        if a[i] == 1:\n            j = i * i\n            while j < n:\n                a[j] = 0\n                j = j + i\n        i = i + 1\n    return a\n[file driver.py]\nfrom native import primes\nprint(primes(3))\nprint(primes(13))\n[out]\n\\[0, 0, 1, 1]\n\\[0, 0, 1, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1]\n\n[case testListPrimitives]\nfrom testutil import assertRaises\n\ndef test_list_build() -> None:\n    # Currently LIST_BUILDING_EXPANSION_THRESHOLD equals to 10\n    # long list built by list_build_op\n    l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]\n    l1.pop()\n    l1.append(100)\n    assert l1 == [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 100]\n    # short list built by Setmem\n    l2 = [1, 2]\n    l2.append(3)\n    l2.pop()\n    l2.pop()\n    assert l2 == [1]\n    # empty list\n    l3 = []\n    l3.append('a')\n    assert l3 == ['a']\n\ndef test_append() -> None:\n    l = [1, 2]\n    l.append(10)\n    assert l == [1, 2, 10]\n    l.append(3)\n    l.append(4)\n    l.append(5)\n    assert l == [1, 2, 10, 3, 4, 5]\n\ndef test_pop_last() -> None:\n    l = [1, 2, 10, 3, 4, 5]\n    l.pop()\n    l.pop()\n    assert l == [1, 2, 10, 3]\n\ndef test_pop_index() -> None:\n    l = [1, 2, 10, 3]\n    assert l.pop(2) == 10\n    assert l == [1, 2, 3]\n    assert l.pop(-2) == 2\n    assert l == [1, 3]\n    assert l.pop(-2) == 1\n    assert l.pop(0) == 3\n    assert l == []\n    l = [int() + 1000, int() + 1001, int() + 1002]\n    assert l.pop(0) == 1000\n    assert l.pop(-1) == 1002\n    assert l == [1001]\n\ndef test_pop_index_errors() -> None:\n    l = [int() + 1000]\n    with assertRaises(IndexError):\n        l.pop(1)\n    with assertRaises(IndexError):\n        l.pop(-2)\n    with assertRaises(OverflowError):\n        l.pop(1 << 100)\n    with assertRaises(OverflowError):\n        l.pop(-(1 << 100))\n\ndef test_count() -> None:\n    l = [1, 3]\n    assert l.count(1) == 1\n    assert l.count(2) == 0\n\ndef test_insert() -> None:\n    l = [1, 3]\n    l.insert(0, 0)\n    assert l == [0, 1, 3]\n    l.insert(2, 2)\n    assert l == [0, 1, 2, 3]\n    l.insert(4, 4)\n    assert l == [0, 1, 2, 3, 4]\n    l.insert(-1, 5)\n    assert l == [0, 1, 2, 3, 5, 4]\n    l = [1, 3]\n    l.insert(100, 5)\n    assert l == [1, 3, 5]\n    l.insert(-100, 6)\n    assert l == [6, 1, 3, 5]\n    for long_int in 1 << 100, -(1 << 100):\n        try:\n            l.insert(long_int, 5)\n        except Exception as e:\n            # The error message is used by CPython\n            assert type(e).__name__ == 'OverflowError'\n            assert str(e) == 'Python int too large to convert to C ssize_t'\n        else:\n            assert False\n\ndef test_sort() -> None:\n    l = [1, 4, 3, 6, -1]\n    l.sort()\n    assert l == [-1, 1, 3, 4, 6]\n    l.sort()\n    assert l == [-1, 1, 3, 4, 6]\n    l = []\n    l.sort()\n    assert l == []\n\ndef test_reverse() -> None:\n    l = [1, 4, 3, 6, -1]\n    l.reverse()\n    assert l == [-1, 6, 3, 4, 1]\n    l.reverse()\n    assert l == [1, 4, 3, 6, -1]\n    l = []\n    l.reverse()\n    assert l == []\n\ndef test_remove() -> None:\n    l = [1, 3, 4, 3]\n    l.remove(3)\n    assert l == [1, 4, 3]\n    l.remove(3)\n    assert l == [1, 4]\n    try:\n        l.remove(3)\n    except ValueError:\n        pass\n    else:\n        assert False\n\ndef test_index() -> None:\n    l = [1, 3, 4, 3]\n    assert l.index(1) == 0\n    assert l.index(3) == 1\n    assert l.index(4) == 2\n    try:\n        l.index(0)\n    except ValueError:\n        pass\n    else:\n        assert False\n\n[case testListOfUserDefinedClass]\nclass C:\n    x: int\n\ndef f() -> int:\n    c = C()\n    c.x = 5\n    a = [c]\n    d = a[0]\n    return d.x + 1\n\ndef g() -> int:\n    a = [C()]\n    a[0].x = 3\n    return a[0].x + 4\n[file driver.py]\nfrom native import f, g\nprint(f())\nprint(g())\n[out]\n6\n7\n\n[case testListOps]\nfrom typing import Any, cast\nfrom testutil import assertRaises\n\ndef test_slicing() -> None:\n    # Use dummy adds to avoid constant folding\n    zero = int()\n    two = zero + 2\n    s = [\"f\", \"o\", \"o\", \"b\", \"a\", \"r\"]\n    assert s[two:] == [\"o\", \"b\", \"a\", \"r\"]\n    assert s[:two] == [\"f\", \"o\"]\n    assert s[two:-two] == [\"o\", \"b\"]\n    assert s[two:two] == []\n    assert s[two:two + 1] == [\"o\"]\n    assert s[-two:] == [\"a\", \"r\"]\n    assert s[:-two] == [\"f\", \"o\", \"o\", \"b\"]\n    assert s[:] == [\"f\", \"o\", \"o\", \"b\", \"a\", \"r\"]\n    assert s[two:333] == [\"o\", \"b\", \"a\", \"r\"]\n    assert s[333:two] == []\n    assert s[two:-333] == []\n    assert s[-333:two] == [\"f\", \"o\"]\n    long_int: int = 1000 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000\n    assert s[1:long_int] == [\"o\", \"o\", \"b\", \"a\", \"r\"]\n    assert s[long_int:] == []\n    assert s[-long_int:-1] == [\"f\", \"o\", \"o\", \"b\", \"a\"]\n\ndef in_place_add(l2: Any) -> list[Any]:\n    l1 = [1, 2]\n    l1 += l2\n    return l1\n\ndef test_add() -> None:\n    res = [1, 2, 3, 4]\n    assert [1, 2] + [3, 4] == res\n    with assertRaises(TypeError, 'can only concatenate list (not \"tuple\") to list'):\n        assert [1, 2] + cast(Any, (3, 4)) == res\n    l1 = [1, 2]\n    id_l1 = id(l1)\n    l1 += [3, 4]\n    assert l1 == res\n    assert id_l1 == id(l1)\n    assert in_place_add([3, 4]) == res\n    assert in_place_add((3, 4)) == res\n    assert in_place_add({3, 4}) == res\n    assert in_place_add({3: \"\", 4: \"\"}) == res\n    assert in_place_add(range(3, 5)) == res\n\ndef test_multiply() -> None:\n    l1 = [1]\n    assert l1 * 3 == [1, 1, 1]\n    assert 3 * l1 == [1, 1, 1]\n    l1 *= 3\n    assert l1 == [1, 1, 1]\n\n[case testOperatorInExpression]\ndef tuple_in_int0(i: int) -> bool:\n    return i in []\n\ndef tuple_in_int1(i: int) -> bool:\n    return i in (1,)\n\ndef tuple_in_int3(i: int) -> bool:\n    return i in (1, 2, 3)\n\ndef tuple_not_in_int0(i: int) -> bool:\n    return i not in []\n\ndef tuple_not_in_int1(i: int) -> bool:\n    return i not in (1,)\n\ndef tuple_not_in_int3(i: int) -> bool:\n    return i not in (1, 2, 3)\n\ndef tuple_in_str(s: \"str\") -> bool:\n    return s in (\"foo\", \"bar\", \"baz\")\n\ndef tuple_not_in_str(s: \"str\") -> bool:\n    return s not in (\"foo\", \"bar\", \"baz\")\n\ndef list_in_int0(i: int) -> bool:\n    return i in []\n\ndef list_in_int1(i: int) -> bool:\n    return i in (1,)\n\ndef list_in_int3(i: int) -> bool:\n    return i in (1, 2, 3)\n\ndef list_not_in_int0(i: int) -> bool:\n    return i not in []\n\ndef list_not_in_int1(i: int) -> bool:\n    return i not in (1,)\n\ndef list_not_in_int3(i: int) -> bool:\n    return i not in (1, 2, 3)\n\ndef list_in_str(s: \"str\") -> bool:\n    return s in (\"foo\", \"bar\", \"baz\")\n\ndef list_not_in_str(s: \"str\") -> bool:\n    return s not in (\"foo\", \"bar\", \"baz\")\n\ndef list_in_mixed(i: object):\n    return i in [[], (), \"\", 0, 0.0, False, 0j, {}, set(), type]\n\ndef test_in_operator_various_cases() -> None:\n    assert not tuple_in_int0(0)\n    assert not tuple_in_int1(0)\n    assert tuple_in_int1(1)\n    assert not tuple_in_int3(0)\n    assert tuple_in_int3(1)\n    assert tuple_in_int3(2)\n    assert tuple_in_int3(3)\n    assert not tuple_in_int3(4)\n\n    assert tuple_not_in_int0(0)\n    assert tuple_not_in_int1(0)\n    assert not tuple_not_in_int1(1)\n    assert tuple_not_in_int3(0)\n    assert not tuple_not_in_int3(1)\n    assert not tuple_not_in_int3(2)\n    assert not tuple_not_in_int3(3)\n    assert tuple_not_in_int3(4)\n\n    assert tuple_in_str(\"foo\")\n    assert tuple_in_str(\"bar\")\n    assert tuple_in_str(\"baz\")\n    assert not tuple_in_str(\"apple\")\n    assert not tuple_in_str(\"pie\")\n    assert not tuple_in_str(\"\\0\")\n    assert not tuple_in_str(\"\")\n\n    assert not list_in_int0(0)\n    assert not list_in_int1(0)\n    assert list_in_int1(1)\n    assert not list_in_int3(0)\n    assert list_in_int3(1)\n    assert list_in_int3(2)\n    assert list_in_int3(3)\n    assert not list_in_int3(4)\n\n    assert list_not_in_int0(0)\n    assert list_not_in_int1(0)\n    assert not list_not_in_int1(1)\n    assert list_not_in_int3(0)\n    assert not list_not_in_int3(1)\n    assert not list_not_in_int3(2)\n    assert not list_not_in_int3(3)\n    assert list_not_in_int3(4)\n\n    assert list_in_str(\"foo\")\n    assert list_in_str(\"bar\")\n    assert list_in_str(\"baz\")\n    assert not list_in_str(\"apple\")\n    assert not list_in_str(\"pie\")\n    assert not list_in_str(\"\\0\")\n    assert not list_in_str(\"\")\n\n    assert list_in_mixed(0)\n    assert list_in_mixed([])\n    assert list_in_mixed({})\n    assert list_in_mixed(())\n    assert list_in_mixed(False)\n    assert list_in_mixed(0.0)\n    assert not list_in_mixed([1])\n    assert not list_in_mixed(object)\n    assert list_in_mixed(type)\n\n[case testListBuiltFromGenerator]\nfrom typing import Final\nabc: Final = \"abc\"\ndef test_from_gen() -> None:\n    source_a = [\"a\", \"b\", \"c\"]\n    a = list(x + \"f2\" for x in source_a)\n    assert a == [\"af2\", \"bf2\", \"cf2\"]\n    source_b = [1, 2, 3, 4, 5]\n    b = [x * 2 for x in source_b]\n    assert b == [2, 4, 6, 8, 10]\n    source_c = [10, 20, 30]\n    c = [x + \"f4\" for x in (str(y) + \"yy\" for y in source_c)]\n    assert c == [\"10yyf4\", \"20yyf4\", \"30yyf4\"]\n    source_d = [True, False]\n    d = [not x for x in source_d]\n    assert d == [False, True]\n    source_e = [0, 1, 2]\n    e = list((x ** 2) for x in (y + 2 for y in source_e))\n    assert e == [4, 9, 16]\n    source_str = \"abcd\"\n    f = list(\"str:\" + x for x in source_str)\n    assert f == [\"str:a\", \"str:b\", \"str:c\", \"str:d\"]\ndef test_known_length() -> None:\n    # not built from generator but doesnt need its own test either\n    built = [str(x) for x in [*abc, *\"def\", *b\"ghi\", (\"j\", \"k\"), *(\"l\", \"m\", \"n\")]]\n    assert built == ['a', 'b', 'c', 'd', 'e', 'f', '103', '104', '105', \"('j', 'k')\", 'l', 'm', 'n']\n\n[case testNext]\nfrom typing import List\n\ndef get_next(x: List[int]) -> int:\n    return next((i for i in x), -1)\n\ndef test_next() -> None:\n    assert get_next([]) == -1\n    assert get_next([1]) == 1\n    assert get_next([3,2,1]) == 3\n\n[case testListGetItemWithBorrow]\nfrom typing import List\n\nclass D:\n    def __init__(self, n: int) -> None:\n        self.n = n\n\nclass C:\n    def __init__(self, d: D) -> None:\n        self.d = d\n\ndef test_index_with_literal() -> None:\n    d1 = D(1)\n    d2 = D(2)\n    a = [C(d1), C(d2)]\n    d = a[0].d\n    assert d is d1\n    d = a[1].d\n    assert d is d2\n    d = a[-1].d\n    assert d is d2\n    d = a[-2].d\n    assert d is d1\n\n[case testSorted]\nfrom typing import List\n\ndef test_list_sort() -> None:\n    l1 = [2, 1, 3]\n    id_l1 = id(l1)\n    l1.sort()\n    assert l1 == [1, 2, 3]\n    assert id_l1 == id(l1)\n\ndef test_sorted() -> None:\n    res = [1, 2, 3]\n    l1 = [2, 1, 3]\n    id_l1 = id(l1)\n    s_l1 = sorted(l1)\n    assert s_l1 == res\n    assert id_l1 != id(s_l1)\n    assert l1 == [2, 1, 3]\n    assert sorted((2, 1, 3)) == res\n    assert sorted({2, 1, 3}) == res\n    assert sorted({2: \"\", 1: \"\", 3: \"\"}) == res\n\n[case testIsInstance]\nfrom copysubclass import subc\ndef test_built_in() -> None:\n    assert isinstance([], list)\n    assert isinstance([1,2,3], list)\n    assert isinstance(['a','b'], list)\n    assert isinstance(subc(), list)\n    assert isinstance(subc([1,2,3]), list)\n    assert isinstance(subc(['a','b']), list)\n\n    assert not isinstance({}, list)\n    assert not isinstance((), list)\n    assert not isinstance((1,2,3), list)\n    assert not isinstance(('a','b'), list)\n    assert not isinstance(1, list)\n    assert not isinstance('a', list)\n\ndef test_user_defined() -> None:\n    from userdefinedlist import list\n\n    assert isinstance(list(), list)\n    assert not isinstance([list()], list)\n\n[file copysubclass.py]\nfrom typing import Any\nclass subc(list[Any]):\n    pass\n\n[file userdefinedlist.py]\nclass list:\n    pass\n"
  },
  {
    "path": "mypyc/test-data/run-loops.test",
    "content": "# Test cases for \"range\" objects, \"for\" and \"while\" loops (compile and run)\n\n[case testFor]\nfrom typing import Any, List, Tuple\ndef count(n: int) -> None:\n    for i in range(n):\n        print(i)\ndef count_between(n: int, k: int) -> None:\n    for i in range(n, k):\n        print(i)\n    print('n=', n)\ndef count_down(n: int, k: int) -> None:\n    for i in range(n, k, -1):\n        print(i)\ndef count_double(n: int, k: int) -> None:\n    for i in range(n, k, 2):\n        print(i)\ndef list_iter(l: List[int]) -> None:\n    for i in l:\n        print(i)\ndef tuple_iter(l: Tuple[int, ...]) -> None:\n    for i in l:\n        print(i)\ndef empty_tuple_iter(l: Tuple[()]) -> None:\n    i: Any\n    for i in l:\n        print(i)\ndef str_iter(l: str) -> None:\n    for i in l:\n        print(i)\ndef list_rev_iter(l: List[int]) -> None:\n    for i in reversed(l):\n        print(i)\ndef list_rev_iter_lol(l: List[int]) -> None:\n    for i in reversed(l):\n        print(i)\n        if i == 3:\n            while l:\n                l.pop()\ndef count_down_short() -> None:\n    for i in range(10, 0, -1):\n        print(i)\n[file driver.py]\nfrom native import (\n    count, list_iter, list_rev_iter, list_rev_iter_lol, count_between, count_down, count_double,\n    count_down_short, tuple_iter, empty_tuple_iter, str_iter,\n)\ncount(5)\nlist_iter(list(reversed(range(5))))\nlist_rev_iter(list(reversed(range(5))))\ncount_between(11, 15)\ncount_between(10**20, 10**20+3)\ncount_down(20, 10)\ncount_double(10, 15)\ncount_down_short()\nprint('==')\nlist_rev_iter_lol(list(reversed(range(5))))\ntuple_iter((1, 2, 3))\nempty_tuple_iter(())\nstr_iter(\"abc\")\n[out]\n0\n1\n2\n3\n4\n4\n3\n2\n1\n0\n0\n1\n2\n3\n4\n11\n12\n13\n14\nn= 11\n100000000000000000000\n100000000000000000001\n100000000000000000002\nn= 100000000000000000000\n20\n19\n18\n17\n16\n15\n14\n13\n12\n11\n10\n12\n14\n10\n9\n8\n7\n6\n5\n4\n3\n2\n1\n==\n0\n1\n2\n3\n1\n2\n3\na\nb\nc\n\n[case testLoopElse]\nfrom typing import Iterator\ndef run_for_range(n: int) -> None:\n    for i in range(n):\n        if i == 3:\n            break\n        print(i)\n    else:\n        print(n+1)\n\ndef run_for_list(n: int) -> None:\n    for i in list(range(n)):\n        if i == 3:\n            break\n        print(i)\n    else:\n        print(n+1)\n\ndef run_for_iter(n: int) -> None:\n    def identity(x: Iterator[int]) -> Iterator[int]:\n        return x\n    for i in identity(range(n)):\n        if i == 3:\n            break\n        print(i)\n    else:\n        print(n+1)\n\ndef count(n: int) -> int:\n    i = 1\n    while i <= n:\n        i = i + 1\n        if i == 5:\n            break\n    else:\n        i *= -1\n    return i\n\ndef nested_while() -> int:\n    while True:\n        while False:\n            pass\n        else:\n            break\n    else:\n        return -1\n    return 0\n\ndef nested_for() -> int:\n    for x in range(1000):\n        for y in [1,2,3]:\n            pass\n        else:\n            break\n    else:\n        return -1\n    return 0\n\n[file driver.py]\nfrom native import run_for_range, run_for_list, run_for_iter, count, nested_while, nested_for\nassert nested_while() == 0\nassert nested_for() == 0\nassert count(0) == -1\nassert count(1) == -2\nassert count(5) == 5\nassert count(6) == 5\nrun_for_range(3)\nrun_for_range(5)\nprint('==')\nrun_for_list(3)\nrun_for_list(5)\nprint('==')\nrun_for_iter(3)\nrun_for_iter(5)\n[out]\n0\n1\n2\n4\n0\n1\n2\n==\n0\n1\n2\n4\n0\n1\n2\n==\n0\n1\n2\n4\n0\n1\n2\n\n[case testNestedLoopSameIdx]\nfrom typing import List, Generator\n\ndef nested_enumerate() -> None:\n    l1 = [0,1,2]\n    l2 = [0,1,2]\n    outer_seen = []\n    outer = 0\n    for i, j in enumerate(l1):\n        assert i == outer\n        outer_seen.append(i)\n        inner = 0\n        for i, k in enumerate(l2):\n            assert i == inner\n            inner += 1\n        outer += 1\n    assert i == 2\n    assert outer_seen == l1\n\ndef nested_range() -> None:\n    outer = 0\n    outer_seen = []\n    for i in range(3):\n        assert i == outer\n        outer_seen.append(i)\n        inner = 0\n        for i in range(3):\n            assert i == inner\n            inner += 1\n        outer += 1\n    assert outer_seen == [0,1,2]\n\ndef nested_list() -> None:\n    l1 = [0,1,2]\n    l2 = [0,1,2]\n    outer_seen = []\n    outer = 0\n    for i in l1:\n        assert i == outer\n        outer_seen.append(i)\n        inner = 0\n        for i in l2:\n            assert i == inner\n            inner += 1\n        outer += 1\n    assert outer_seen == l1\n\ndef nested_yield() -> Generator:\n    for i in range(3):\n        for i in range(3):\n            yield i\n        yield i\n\n\n[file driver.py]\nfrom native import nested_enumerate, nested_range, nested_list, nested_yield\nnested_enumerate()\nnested_range()\nnested_list()\ngen = nested_yield()\nfor k in range(12):\n    assert next(gen) == k % 4\n[out]\n\n[case testForIterable]\nfrom typing import Iterable, Dict, Any, Tuple, TypeVar\n\nT = TypeVar(\"T\")\n\ndef iterate_over_any(a: Any) -> None:\n    for element in a:\n        print(element)\n\ndef iterate_over_iterable(iterable: Iterable[T]) -> None:\n    for element in iterable:\n        print(element)\n\ndef iterate_and_delete(d: Dict[int, int]) -> None:\n    for key in d:\n        d.pop(key)\n\ndef sum_over_values(d: Dict[int, int]) -> int:\n    s = 0\n    for key in d:\n        s = s + d[key]\n    return s\n\ndef sum_over_even_values(d: Dict[int, int]) -> int:\n    s = 0\n    for key in d:\n        if d[key] % 2:\n            continue\n        s = s + d[key]\n    return s\n\ndef sum_over_two_values(d: Dict[int, int]) -> int:\n    s = 0\n    i = 0\n    for key in d:\n        if i == 2:\n            break\n        s = s + d[key]\n        i = i + 1\n    return s\n\ndef iterate_over_tuple(iterable: Tuple[int, int, int]) -> None:\n    for element in iterable:\n        print(element)\n\n[file driver.py]\nfrom native import iterate_over_any, iterate_over_iterable, iterate_and_delete, sum_over_values, sum_over_even_values, sum_over_two_values, iterate_over_tuple\nimport traceback\ndef broken_generator(n):\n    num = 0\n    while num < n:\n        yield num\n        num += 1\n    raise Exception('Exception Manually Raised')\n\nd = {1:1, 2:2, 3:3, 4:4, 5:5}\nprint(sum_over_values(d))\nprint(sum_over_even_values(d))\nprint(sum_over_two_values(d))\n\ntry:\n    iterate_over_any(5)\nexcept TypeError:\n    traceback.print_exc()\ntry:\n    iterate_over_iterable(broken_generator(5))\nexcept Exception:\n    traceback.print_exc()\ntry:\n    iterate_and_delete(d)\nexcept RuntimeError:\n    traceback.print_exc()\n\niterate_over_tuple((1, 2, 3))\n[out]\nTraceback (most recent call last):\n  File \"driver.py\", line 16, in <module>\n    iterate_over_any(5)\n  File \"native.py\", line 6, in iterate_over_any\n    for element in a:\nTypeError: 'int' object is not iterable\nTraceback (most recent call last):\n  File \"driver.py\", line 20, in <module>\n    iterate_over_iterable(broken_generator(5))\n  File \"native.py\", line 10, in iterate_over_iterable\n    for element in iterable:\n  File \"driver.py\", line 8, in broken_generator\n    raise Exception('Exception Manually Raised')\nException: Exception Manually Raised\nTraceback (most recent call last):\n  File \"driver.py\", line 24, in <module>\n    iterate_and_delete(d)\n  File \"native.py\", line 14, in iterate_and_delete\n    for key in d:\nRuntimeError: dictionary changed size during iteration\n15\n6\n3\n0\n1\n2\n3\n4\n1\n2\n3\n[out version>=3.13]\nTraceback (most recent call last):\n  File \"driver.py\", line 16, in <module>\n    iterate_over_any(5)\n    ~~~~~~~~~~~~~~~~^^^\n  File \"native.py\", line 6, in iterate_over_any\n    for element in a:\nTypeError: 'int' object is not iterable\nTraceback (most recent call last):\n  File \"driver.py\", line 20, in <module>\n    iterate_over_iterable(broken_generator(5))\n    ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^\n  File \"native.py\", line 10, in iterate_over_iterable\n    for element in iterable:\n  File \"driver.py\", line 8, in broken_generator\n    raise Exception('Exception Manually Raised')\nException: Exception Manually Raised\nTraceback (most recent call last):\n  File \"driver.py\", line 24, in <module>\n    iterate_and_delete(d)\n    ~~~~~~~~~~~~~~~~~~^^^\n  File \"native.py\", line 14, in iterate_and_delete\n    for key in d:\nRuntimeError: dictionary changed size during iteration\n15\n6\n3\n0\n1\n2\n3\n4\n1\n2\n3\n\n[case testContinueFor]\ndef f() -> None:\n    for n in range(5):\n        continue\n[file driver.py]\nfrom native import f\nf()\n\n[case testMultipleVarsWithLoops]\n# Test comprehensions and for loops with multiple index variables\nl = [(1, 2, 'a'), (3, 4, 'b'), (5, 6, 'c')]\nl2 = [str(a*100+b)+' '+c for a, b, c in l]\nl3 = []\nfor a, b, c in l:\n    l3.append(str(a*1000+b)+' '+c)\n[file driver.py]\nfrom native import l, l2, l3\nfor a in l2 + l3:\n    print(a)\n[out]\n102 a\n304 b\n506 c\n1002 a\n3004 b\n5006 c\n\n[case testForZipAndEnumerate]\nfrom typing import Iterable, List, Any\ndef f(a: Iterable[int], b: List[int]) -> List[Any]:\n    res = []\n    for (x, y), z in zip(enumerate(a), b):\n        res.append((x, y, z))\n    return res\ndef g(a: Iterable[int], b: Iterable[str]) -> List[Any]:\n    res = []\n    for x, (y, z) in enumerate(zip(a, b)):\n        res.append((x, y, z))\n    return res\n\n[file driver.py]\nfrom native import f, g\n\nassert f([6, 7], [8, 9]) == [(0, 6, 8), (1, 7, 9)]\nassert g([6, 7], ['a', 'b']) == [(0, 6, 'a'), (1, 7, 'b')]\nassert f([6, 7], [8]) == [(0, 6, 8)]\nassert f([6], [8, 9]) == [(0, 6, 8)]\n\n[case testEnumerateEmptyList]\nfrom typing import List\n\ndef get_enumerate_locals(iterable: List[int]) -> int:\n    for i, j in enumerate(iterable):\n        pass\n    try:\n        return i\n    except NameError:\n        return -100\n\n[file driver.py]\nfrom native import get_enumerate_locals\n\nprint(get_enumerate_locals([]))\nprint(get_enumerate_locals([55]))\nprint(get_enumerate_locals([551, 552]))\n\n[out]\n-100\n0\n1\n\n[case testIterTypeTrickiness]\n# Test inferring the type of a for loop body doesn't cause us grief\n# Extracted from somethings that broke in mypy\n\nfrom typing import Optional\n\n# really I only care that this one build\ndef foo(x: object) -> None:\n    if isinstance(x, dict):\n        for a in x:\n            pass\n\ndef bar(x: Optional[str]) -> None:\n    vars = (\n        (\"a\", 'lol'),\n        (\"b\", 'asdf'),\n        (\"lol\", x),\n        (\"an int\", 10),\n    )\n    for name, value in vars:\n        pass\n\n[file driver.py]\nfrom native import bar\nbar(None)\n\n[case testRangeObject]\nfrom typing import Any\n\ndef f(x: range) -> int:\n    sum = 0\n    for i in x:\n        sum += i\n    return sum\n\ndef test_range_object() -> None:\n    r1 = range(4, 12, 2)\n    tmp_list = [x for x in r1]\n    assert tmp_list == [4, 6, 8, 10]\n    assert f(r1) == 28\n    r2: Any = range(10)\n    assert f(r2) == 45\n    r3: Any = 'x'\n    try:\n        f(r3)\n    except TypeError as e:\n        assert \"range object expected; got str\" in str(e)\n    try:\n        ff: Any = f\n        ff(r3)\n    except TypeError as e:\n        assert \"range object expected; got str\" in str(e)\n    try:\n        r4 = range(4, 12, 0)\n    except ValueError as e:\n        assert \"range() arg 3 must not be zero\" in str(e)\n\n[case testNamedTupleLoop]\nfrom collections.abc import Iterable\nfrom typing import NamedTuple, Any\nfrom typing_extensions import Self\n\n\nclass Vector2(NamedTuple):\n    x: int\n    y: float\n\n    @classmethod\n    def from_iter(cls, iterable: Iterable[Any]) -> Self:\n        return cls(*iter(iterable))\n\n    def __neg__(self) -> Self:\n        return self.from_iter(-c for c in self)\n\n[file driver.py]\nimport native\nprint(-native.Vector2(2, -3.1))\nprint([x for x in native.Vector2(4, -5.2)])\n\n[out]\nVector2(x=-2, y=3.1)\n\\[4, -5.2]\n"
  },
  {
    "path": "mypyc/test-data/run-match.test",
    "content": "[case testTheBigMatch_python3_10]\nclass Person:\n    __match_args__ = (\"name\", \"age\")\n\n    name: str\n    age: int\n\n    def __init__(self, name: str, age: int) -> None:\n        self.name = name\n        self.age = age\n\n    def __str__(self) -> str:\n        return f\"Person(name={self.name!r}, age={self.age})\"\n\n\ndef f(x: object) -> None:\n    match x:\n        case 123:\n            print(\"test 1\")\n\n        case 456 | 789:\n            print(\"test 2\")\n\n        case True | False | None:\n            print(\"test 3\")\n\n        case Person(\"bob\" as name, age):\n            print(f\"test 4 ({name=}, {age=})\")\n\n        case num if num == 5:\n            print(\"test 5\")\n\n        case 6 as num:\n            print(f\"test 6 ({num=})\")\n\n        case (7 | \"7\") as value:\n            print(f\"test 7 ({value=})\")\n\n        case Person(\"alice\", age=123):\n            print(\"test 8\")\n\n        case Person(\"charlie\", age=123 | 456):\n            print(\"test 9\")\n\n        case Person(\"dave\", 123) as dave:\n            print(f\"test 10 {dave}\")\n\n        case {\"test\": 11}:\n            print(\"test 11\")\n\n        case {\"test\": 12, **rest}:\n            print(f\"test 12 (rest={rest})\")\n\n        case {}:\n            print(\"test map final\")\n\n        case [\"test\", 13]:\n            print(\"test 13\")\n\n        case [\"test\", 13, _]:\n            print(\"test 13b\")\n\n        case [\"test\", 14, *_]:\n            print(\"test 14\")\n\n        # TODO: Fix \"rest\" being used here coliding with above \"rest\"\n        case [\"test\", 15, *rest2]:\n            print(f\"test 15 ({rest2})\")\n\n        case [\"test\", *rest3, 16]:\n            print(f\"test 16 ({rest3})\")\n\n        case [*rest4, \"test\", 17]:\n            print(f\"test 17 ({rest4})\")\n\n        case [*rest4, \"test\", 18, \"some\", \"fluff\"]:\n            print(f\"test 18 ({rest4})\")\n\n        case str(\"test 19\"):\n            print(\"test 19\")\n\n        case str(test_20) if test_20.startswith(\"test 20\"):\n            print(f\"test 20 ({test_20[7:]!r})\")\n\n        case (\"test 21\" as value) | (\"test 21 as well\" as value):\n            print(f\"test 21 ({value[7:]!r})\")\n\n        case []:\n            print(\"test sequence final\")\n\n        case _:\n            print(\"test final\")\n[file driver.py]\nfrom native import f, Person\n\n# test 1\nf(123)\n\n# test 2\nf(456)\nf(789)\n\n# test 3\nf(True)\nf(False)\nf(None)\n\n# test 4\nf(Person(\"bob\", 123))\n\n# test 5\nf(5)\n\n# test 6\nf(6)\n\n# test 7\nf(7)\nf(\"7\")\n\n# test 8\nf(Person(\"alice\", 123))\n\n# test 9\nf(Person(\"charlie\", 123))\nf(Person(\"charlie\", 456))\n\n# test 10\nf(Person(\"dave\", 123))\n\n# test 11\nf({\"test\": 11})\nf({\"test\": 11, \"some\": \"key\"})\n\n# test 12\nf({\"test\": 12})\nf({\"test\": 12, \"key\": \"value\"})\nf({\"test\": 12, \"key\": \"value\", \"abc\": \"123\"})\n\n# test map final\nf({})\n\n# test 13\nf([\"test\", 13])\n\n# test 13b\nf([\"test\", 13, \"fail\"])\n\n# test 14\nf([\"test\", 14])\nf([\"test\", 14, \"something\"])\n\n# test 15\nf([\"test\", 15])\nf([\"test\", 15, \"something\"])\n\n# test 16\nf([\"test\", 16])\nf([\"test\", \"filler\", 16])\nf([\"test\", \"more\", \"filler\", 16])\n\n# test 17\nf([\"test\", 17])\nf([\"stuff\", \"test\", 17])\nf([\"more\", \"stuff\", \"test\", 17])\n\n# test 18\nf([\"test\", 18, \"some\", \"fluff\"])\nf([\"stuff\", \"test\", 18, \"some\", \"fluff\"])\nf([\"more\", \"stuff\", \"test\", 18, \"some\", \"fluff\"])\n\n# test 19\nf(\"test 19\")\n\n# test 20\nf(\"test 20\")\nf(\"test 20 something else\")\n\n# test 21\nf(\"test 21\")\nf(\"test 21 as well\")\n\n# test sequence final\nf([])\n\n# test final\nf(\"\")\n\n[out]\ntest 1\ntest 2\ntest 2\ntest 3\ntest 3\ntest 3\ntest 4 (name='bob', age=123)\ntest 5\ntest 6 (num=6)\ntest 7 (value=7)\ntest 7 (value='7')\ntest 8\ntest 9\ntest 9\ntest 10 Person(name='dave', age=123)\ntest 11\ntest 11\ntest 12 (rest={})\ntest 12 (rest={'key': 'value'})\ntest 12 (rest={'key': 'value', 'abc': '123'})\ntest map final\ntest 13\ntest 13b\ntest 14\ntest 14\ntest 15 ([])\ntest 15 (['something'])\ntest 16 ([])\ntest 16 (['filler'])\ntest 16 (['more', 'filler'])\ntest 17 ([])\ntest 17 (['stuff'])\ntest 17 (['more', 'stuff'])\ntest 18 ([])\ntest 18 (['stuff'])\ntest 18 (['more', 'stuff'])\ntest 19\ntest 20 ('')\ntest 20 (' something else')\ntest 21 ('')\ntest 21 (' as well')\ntest sequence final\ntest final\n[case testCustomMappingAndSequenceObjects_python3_10]\ndef f(x: object) -> None:\n    match x:\n        case {\"key\": \"value\", **rest}:\n            print(rest, type(rest))\n\n        case [1, 2, *rest2]:\n            print(rest2, type(rest2))\n\n[file driver.py]\nfrom collections.abc import Mapping, Sequence\n\nfrom native import f\n\nclass CustomMapping(Mapping):\n    inner: dict\n\n    def __init__(self, inner: dict) -> None:\n        self.inner = inner\n\n    def __getitem__(self, key):\n        return self.inner[key]\n\n    def __iter__(self):\n        return iter(self.inner)\n\n    def __len__(self) -> int:\n        return len(self.inner)\n\n\nclass CustomSequence(Sequence):\n    inner: list\n\n    def __init__(self, inner: list) -> None:\n        self.inner = inner\n\n    def __getitem__(self, index: int) -> None:\n        return self.inner[index]\n\n    def __len__(self) -> int:\n        return len(self.inner)\n\nmapping = CustomMapping({\"key\": \"value\", \"some\": \"data\"})\nsequence = CustomSequence([1, 2, 3])\n\nf(mapping)\nf(sequence)\n\n[out]\n{'some': 'data'} <class 'dict'>\n[3] <class 'list'>\n"
  },
  {
    "path": "mypyc/test-data/run-math.test",
    "content": "# Test cases for the math module (compile and run)\n\n[case testMathOps]\nfrom typing import Any, Callable, Final\nimport math\nfrom math import pi, e, tau, inf, nan\nfrom testutil import assertRaises, float_vals, assertDomainError, assertMathRangeError\n\npymath: Any = math\n\ndef validate_one_arg(test: Callable[[float], float], validate: Callable[[float], float]) -> None:\n    \"\"\"Ensure that test and validate behave the same for various float args.\"\"\"\n    for x in float_vals:\n        try:\n            expected = validate(x)\n        except Exception as e:\n            try:\n                test(x)\n                assert False, f\"no exception raised for {x!r}, expected {e!r}\"\n            except Exception as e2:\n                assert repr(e) == repr(e2), f\"actual for {x!r}: {e2!r}, expected: {e!r}\"\n                continue\n        actual = test(x)\n        assert repr(actual) == repr(expected), (\n            f\"actual for {x!r}: {actual!r}, expected {expected!r}\")\n\ndef validate_two_arg(test: Callable[[float, float], float],\n                     validate: Callable[[float, float], float]) -> None:\n    \"\"\"Ensure that test and validate behave the same for various float args.\"\"\"\n    for x in float_vals:\n        for y in float_vals:\n            args = f\"({x!r}, {y!r})\"\n            try:\n                expected = validate(x, y)\n            except Exception as e:\n                try:\n                    test(x, y)\n                    assert False, f\"no exception raised for {args}, expected {e!r}\"\n                except Exception as e2:\n                    assert repr(e) == repr(e2), f\"actual for {args}: {e2!r}, expected: {e!r}\"\n                    continue\n            try:\n                actual = test(x, y)\n            except Exception as e:\n                assert False, f\"no exception expected for {args}, got {e!r}\"\n            assert repr(actual) == repr(expected), (\n                f\"actual for {args}: {actual!r}, expected {expected!r}\")\n\ndef test_sqrt() -> None:\n    validate_one_arg(lambda x: math.sqrt(x), pymath.sqrt)\n\ndef test_sin() -> None:\n    validate_one_arg(lambda x: math.sin(x), pymath.sin)\n\ndef test_cos() -> None:\n    validate_one_arg(lambda x: math.cos(x), pymath.cos)\n\ndef test_tan() -> None:\n    validate_one_arg(lambda x: math.tan(x), pymath.tan)\n\ndef test_exp() -> None:\n    validate_one_arg(lambda x: math.exp(x), pymath.exp)\n\ndef test_log() -> None:\n    validate_one_arg(lambda x: math.log(x), pymath.log)\n\ndef test_floor() -> None:\n    validate_one_arg(lambda x: math.floor(x), pymath.floor)\n\ndef test_ceil() -> None:\n    validate_one_arg(lambda x: math.ceil(x), pymath.ceil)\n\ndef test_fabs() -> None:\n    validate_one_arg(lambda x: math.fabs(x), pymath.fabs)\n\ndef test_pow() -> None:\n    validate_two_arg(lambda x, y: math.pow(x, y), pymath.pow)\n\ndef test_copysign() -> None:\n    validate_two_arg(lambda x, y: math.copysign(x, y), pymath.copysign)\n\ndef test_isinf() -> None:\n    for x in float_vals:\n        assert repr(math.isinf(x)) == repr(pymath.isinf(x))\n\ndef test_isnan() -> None:\n    for x in float_vals:\n        assert repr(math.isnan(x)) == repr(pymath.isnan(x))\n\n\ndef test_pi_is_inlined_correctly() -> None:\n    assert math.pi == pi == 3.141592653589793\n\ndef test_e_is_inlined_correctly() -> None:\n    assert math.e == e == 2.718281828459045\n\ndef test_tau_is_inlined_correctly() -> None:\n    assert math.tau == tau == 6.283185307179586\n\ndef test_inf_is_inlined_correctly() -> None:\n    assert math.inf == inf == float(\"inf\")\n\ndef test_nan_is_inlined_correctly() -> None:\n    assert math.isnan(math.nan)\n    assert math.isnan(nan)\n"
  },
  {
    "path": "mypyc/test-data/run-misc.test",
    "content": "[case testMaybeUninitVar]\nclass C:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\ndef f(b: bool) -> None:\n    u = C(1)\n    while b:\n        v = C(2)\n        if v is not u:\n            break\n    print(v.x)\n[file driver.py]\nfrom native import f\nf(True)\n[out]\n2\n\n[case testUninitBoom]\ndef f(a: bool, b: bool) -> None:\n    if a:\n        x = 'lol'\n    if b:\n        print(x)\n\ndef g() -> None:\n    try:\n        [0][1]\n        y = 1\n    except Exception:\n        pass\n    print(y)\n\n[file driver.py]\nfrom native import f, g\nfrom testutil import assertRaises\n\nf(True, True)\nf(False, False)\nwith assertRaises(UnboundLocalError):\n    f(False, True)\nwith assertRaises(UnboundLocalError):\n    g()\n[out]\nlol\n\n[case testBuiltins]\ny = 10\ndef f(x: int) -> None:\n    print(5)\n    d = globals()\n    assert d['y'] == 10\n    d['y'] = 20\n    assert y == 20\n[file driver.py]\nfrom native import f\nf(5)\n[out]\n5\n\n[case testOptional]\nfrom typing import Optional\n\nclass A: pass\n\ndef f(x: Optional[A]) -> Optional[A]:\n    return x\n\ndef g(x: Optional[A]) -> int:\n    if x is None:\n        return 1\n    if x is not None:\n        return 2\n    return 3\n\ndef h(x: Optional[int], y: Optional[bool]) -> None:\n    pass\n\n[file driver.py]\nfrom native import f, g, A\na = A()\nassert f(None) is None\nassert f(a) is a\nassert g(None) == 1\nassert g(a) == 2\n\n[case testInferredOptionalAssignment]\nfrom typing import Any, Generator\n\ndef f(b: bool) -> Any:\n    if b:\n        x = None\n    else:\n        x = 1\n\n    if b:\n        y = 1\n    else:\n        y = None\n\n    m = 1 if b else None\n    n = None if b else 1\n    return ((x, y), (m, n))\n\ndef gen(b: bool) -> Generator[Any, None, None]:\n    if b:\n        y = 1\n    else:\n        y = None\n    yield y\n\ndef test_inferred() -> None:\n    assert f(False) == ((1, None), (None, 1))\n    assert f(True) == ((None, 1), (1, None))\n    assert next(gen(False)) is None\n    assert next(gen(True)) == 1\n\n[case testWith]\nfrom typing import Any\nclass Thing:\n    def __init__(self, x: str) -> None:\n        self.x = x\n    def __enter__(self) -> str:\n        print('enter!', self.x)\n        if self.x == 'crash':\n            raise Exception('ohno')\n        return self.x\n    def __exit__(self, x: Any, y: Any, z: Any) -> None:\n        print('exit!', self.x, y)\n\ndef foo(i: int) -> int:\n    with Thing('a') as x:\n        print(\"yooo?\", x)\n        if i == 0:\n            return 10\n        elif i == 1:\n            raise Exception('exception!')\n    return -1\n\ndef bar() -> None:\n    with Thing('a') as x, Thing('b') as y:\n        print(\"yooo?\", x, y)\n\ndef baz() -> None:\n    with Thing('a') as x, Thing('crash') as y:\n        print(\"yooo?\", x, y)\n\n[file driver.py]\nfrom native import foo, bar, baz\nassert foo(0) == 10\nprint('== foo ==')\ntry:\n    foo(1)\nexcept Exception:\n    print('caught')\nassert foo(2) == -1\n\nprint('== bar ==')\nbar()\n\nprint('== baz ==')\ntry:\n    baz()\nexcept Exception:\n    print('caught')\n\n[out]\nenter! a\nyooo? a\nexit! a None\n== foo ==\nenter! a\nyooo? a\nexit! a exception!\ncaught\nenter! a\nyooo? a\nexit! a None\n== bar ==\nenter! a\nenter! b\nyooo? a b\nexit! b None\nexit! a None\n== baz ==\nenter! a\nenter! crash\nexit! a ohno\ncaught\n\n[case testDisplays]\nfrom typing import List, Set, Tuple, Sequence, Dict, Any, Mapping\n\ndef listDisplay(x: List[int], y: List[int]) -> List[int]:\n    return [1, 2, *x, *y, 3]\n\ndef setDisplay(x: Set[int], y: Set[int]) -> Set[int]:\n    return {1, 2, *x, *y, 3}\n\ndef tupleDisplay(x: Sequence[str], y: Sequence[str]) -> Tuple[str, ...]:\n    return ('1', '2', *x, *y, '3')\n\ndef dictDisplay(x: str, y1: Dict[str, int], y2: Dict[str, int]) -> Dict[str, int]:\n    return {x: 2, **y1, 'z': 3, **y2}\n\ndef dictDisplayUnpackMapping(obj: Mapping[str, str]) -> Dict[str, str]:\n    return {**obj, \"env\": \"value\"}\n\n[file driver.py]\nimport os\nfrom native import listDisplay, setDisplay, tupleDisplay, dictDisplay, dictDisplayUnpackMapping\nassert listDisplay([4], [5, 6]) == [1, 2, 4, 5, 6, 3]\nassert setDisplay({4}, {5}) == {1, 2, 3, 4, 5}\nassert tupleDisplay(['4', '5'], ['6']) == ('1', '2', '4', '5', '6', '3')\nassert dictDisplay('x', {'y1': 1}, {'y2': 2, 'z': 5}) == {'x': 2, 'y1': 1, 'y2': 2, 'z': 5}\nassert dictDisplayUnpackMapping(os.environ) == {**os.environ, \"env\": \"value\"}\n\n[case testArbitraryLvalues]\nfrom typing import List, Dict, Any\n\nclass O(object):\n    def __init__(self) -> None:\n        self.x = 1\n\ndef increment_attr(a: Any) -> Any:\n    a.x += 1\n    return a\n\ndef increment_attr_o(o: O) -> O:\n    o.x += 1\n    return o\n\ndef increment_all_indices(l: List[int]) -> List[int]:\n    for i in range(len(l)):\n        l[i] += 1\n    return l\n\ndef increment_all_keys(d: Dict[str, int]) -> Dict[str, int]:\n    for k in d:\n        d[k] += 1\n    return d\n\n[file driver.py]\nfrom native import O, increment_attr, increment_attr_o, increment_all_indices, increment_all_keys\n\nclass P(object):\n    def __init__(self) -> None:\n        self.x = 0\n\nassert increment_attr(P()).x == 1\nassert increment_attr_o(O()).x == 2\nassert increment_all_indices([1, 2, 3]) == [2, 3, 4]\nassert increment_all_keys({'a':1, 'b':2, 'c':3}) == {'a':2, 'b':3, 'c':4}\n\n[case testControlFlowExprs]\nfrom typing import Tuple\ndef foo() -> object:\n    print('foo')\n    return 'foo'\ndef bar() -> object:\n    print('bar')\n    return 'bar'\ndef t(x: int) -> int:\n    print(x)\n    return x\n\ndef f(b: bool) -> Tuple[object, object, object]:\n    x = foo() if b else bar()\n    y = b or foo()\n    z = b and foo()\n    return (x, y, z)\ndef g() -> Tuple[object, object]:\n    return (foo() or bar(), foo() and bar())\n\ndef nand(p: bool, q: bool) -> bool:\n    if not (p and q):\n        return True\n    return False\n\ndef chained(x: int, y: int, z: int) -> bool:\n    return t(x) < t(y) > t(z)\n\ndef chained2(x: int, y: int, z: int, w: int) -> bool:\n    return t(x) < t(y) < t(z) < t(w)\n[file driver.py]\nfrom native import f, g, nand, chained, chained2\nassert f(True) == ('foo', True, 'foo')\nprint()\nassert f(False) == ('bar', 'foo', False)\nprint()\nassert g() == ('foo', 'bar')\n\nassert nand(True, True) == False\nassert nand(True, False) == True\nassert nand(False, True) == True\nassert nand(False, False) == True\n\nprint()\nassert chained(10, 20, 15) == True\nprint()\nassert chained(10, 20, 30) == False\nprint()\nassert chained(21, 20, 30) == False\nprint()\nassert chained2(1, 2, 3, 4) == True\nprint()\nassert chained2(1, 0, 3, 4) == False\nprint()\nassert chained2(1, 2, 0, 4) == False\n[out]\nfoo\nfoo\n\nbar\nfoo\n\nfoo\nfoo\nbar\n\n10\n20\n15\n\n10\n20\n30\n\n21\n20\n\n1\n2\n3\n4\n\n1\n0\n\n1\n2\n0\n\n[case testMultipleAssignment]\nfrom typing import Tuple, List, Any\n\ndef from_tuple(t: Tuple[int, str]) -> List[Any]:\n    x, y = t\n    return [y, x]\n\ndef from_tuple_sequence(t: Tuple[int, ...]) -> List[int]:\n    x, y, z = t\n    return [z, y, x]\n\ndef from_list(l: List[int]) -> List[int]:\n    x, y = l\n    return [y, x]\n\ndef from_list_complex(l: List[int]) -> List[int]:\n    ll = l[:]\n    ll[1], ll[0] = l\n    return ll\n\ndef from_any(o: Any) -> List[Any]:\n    x, y = o\n    return [y, x]\n\ndef multiple_assignments(t: Tuple[int, str]) -> List[Any]:\n    a, b = c, d = t\n    e, f = g, h = 1, 2\n    return [a, b, c, d, e, f, g, h]\n[file driver.py]\nfrom native import (\n    from_tuple, from_tuple_sequence, from_list, from_list_complex, from_any, multiple_assignments\n)\n\nassert from_tuple((1, 'x')) == ['x', 1]\n\nassert from_tuple_sequence((1, 5, 4)) == [4, 5, 1]\ntry:\n    from_tuple_sequence((1, 5))\nexcept ValueError as e:\n    assert 'not enough values to unpack (expected 3, got 2)' in str(e)\nelse:\n    assert False\n\nassert from_list([3, 4]) == [4, 3]\ntry:\n    from_list([5, 4, 3])\nexcept ValueError as e:\n    assert 'too many values to unpack (expected 2)' in str(e)\nelse:\n    assert False\n\nassert from_list_complex([7, 6]) == [6, 7]\ntry:\n    from_list_complex([5, 4, 3])\nexcept ValueError as e:\n    assert 'too many values to unpack (expected 2)' in str(e)\nelse:\n    assert False\n\nassert from_any('xy') == ['y', 'x']\n\nassert multiple_assignments((4, 'x')) == [4, 'x', 4, 'x', 1, 2, 1, 2]\n\n[case testUnpack]\nfrom typing import List\n\na, *b = [1, 2, 3, 4, 5]\n\n*c, d = [1, 2, 3, 4, 5]\n\ne, *f = [1,2]\n\nj, *k, l = [1, 2, 3]\n\nm, *n, o = [1, 2, 3, 4, 5, 6]\n\np, q, r, *s, t = [1,2,3,4,5,6,7,8,9,10]\n\ntup = (1,2,3)\ny, *z = tup\n\ndef unpack1(l : List[int]) -> None:\n    *v1, v2, v3 = l\n\ndef unpack2(l : List[int]) -> None:\n    v1, *v2, v3 = l\n\ndef unpack3(l : List[int]) -> None:\n    v1, v2, *v3 = l\n\n[file driver.py]\nfrom native import a, b, c, d, e, f, j, k, l, m, n, o, p, q, r, s, t, y, z\nfrom native import unpack1, unpack2, unpack3\nfrom testutil import assertRaises\n\nassert a == 1\nassert b == [2,3,4,5]\nassert c == [1,2,3,4]\nassert d == 5\nassert e == 1\nassert f == [2]\nassert j == 1\nassert k == [2]\nassert l == 3\nassert m == 1\nassert n == [2,3,4,5]\nassert o == 6\nassert p == 1\nassert q == 2\nassert r == 3\nassert s == [4,5,6,7,8,9]\nassert t == 10\nassert y == 1\nassert z == [2,3]\n\nwith assertRaises(ValueError, \"not enough values to unpack\"):\n    unpack1([1])\n\nwith assertRaises(ValueError, \"not enough values to unpack\"):\n    unpack2([1])\n\nwith assertRaises(ValueError, \"not enough values to unpack\"):\n    unpack3([1])\n\n[out]\n\n[case testModuleTopLevel]\nx = 1\nprint(x)\n\ndef f() -> None:\n    print(x + 1)\n\ndef g() -> None:\n    global x\n    x = 77\n\n[file driver.py]\nimport native\nnative.f()\nnative.x = 5\nnative.f()\nnative.g()\nprint(native.x)\n\n[out]\n1\n2\n6\n77\n\n[case testComprehensions]\nfrom typing import List\n\n# A list comprehension\nl = [str(x) + \"     \" + str(y) + \"   \" + str(x*y) for x in range(10)\n     if x != 6 if x != 5 for y in range(x) if y*x != 8]\n\n# Test short-circuiting as well\ndef pred(x: int) -> bool:\n    if x > 6:\n        raise Exception()\n    return x > 3\n# If we fail to short-circuit, pred(x) will be called with x=7\n# eventually and will raise an exception.\nl2 = [x for x in range(10) if x <= 6 if pred(x)]\n\nsrc = ['x']\n\ndef f() -> List[str]:\n    global src\n    res = src\n    src = []\n    return res\n\nl3 = [s for s in f()]\nl4 = [s for s in f()]\n\n# A dictionary comprehension\nd = {k: k*k for k in range(10) if k != 5 if k != 6}\n\n# A set comprehension\ns = {str(x) + \"     \" + str(y) + \"   \" + str(x*y) for x in range(10)\n     if x != 6 if x != 5 for y in range(x) if y*x != 8}\n\n[file driver.py]\nfrom native import l, l2, l3, l4, d, s\nfor a in l:\n    print(a)\nprint(tuple(l2))\nassert l3 == ['x']\nassert l4 == []\nfor k in sorted(d):\n    print(k, d[k])\nfor a in sorted(s):\n    print(a)\n[out]\n1     0   0\n2     0   0\n2     1   2\n3     0   0\n3     1   3\n3     2   6\n4     0   0\n4     1   4\n4     3   12\n7     0   0\n7     1   7\n7     2   14\n7     3   21\n7     4   28\n7     5   35\n7     6   42\n8     0   0\n8     2   16\n8     3   24\n8     4   32\n8     5   40\n8     6   48\n8     7   56\n9     0   0\n9     1   9\n9     2   18\n9     3   27\n9     4   36\n9     5   45\n9     6   54\n9     7   63\n9     8   72\n(4, 5, 6)\n0 0\n1 1\n2 4\n3 9\n4 16\n7 49\n8 64\n9 81\n1     0   0\n2     0   0\n2     1   2\n3     0   0\n3     1   3\n3     2   6\n4     0   0\n4     1   4\n4     3   12\n7     0   0\n7     1   7\n7     2   14\n7     3   21\n7     4   28\n7     5   35\n7     6   42\n8     0   0\n8     2   16\n8     3   24\n8     4   32\n8     5   40\n8     6   48\n8     7   56\n9     0   0\n9     1   9\n9     2   18\n9     3   27\n9     4   36\n9     5   45\n9     6   54\n9     7   63\n9     8   72\n\n[case testDummyTypes]\nfrom typing import Tuple, List, Dict, Literal, NamedTuple, NewType, TypedDict\n\nclass A:\n    pass\n\nT = List[A]\nU = List[Tuple[int, str]]\nZ = List[List[int]]\nD = Dict[int, List[int]]\nN = NewType('N', int)\nG = Tuple[int, str]\ndef foo(x: N) -> int:\n    return x\nfoo(N(10))\nz = N(10)\nLol = NamedTuple('Lol', (('a', int), ('b', T)))\nx = Lol(1, [])\ndef take_lol(x: Lol) -> int:\n    return x.a\n\nTD = TypedDict('TD', {'a': int})\ndef take_typed_dict(x: TD) -> int:\n    return x['a']\n\ndef take_literal(x: Literal[1, 2, 3]) -> None:\n    print(x)\n\n[file driver.py]\nimport sys\nfrom native import *\n\nif sys.version_info[:3] > (3, 5, 2):\n    assert \"%s %s %s %s\" % (T, U, Z, D) == \"typing.List[native.A] typing.List[typing.Tuple[int, str]] typing.List[typing.List[int]] typing.Dict[int, typing.List[int]]\"\nprint(x)\nprint(z)\nprint(take_lol(x))\nprint(take_typed_dict({'a': 20}))\ntry:\n    take_typed_dict(None)\nexcept Exception as e:\n    print(type(e).__name__)\n\n\ntake_literal(1)\n# We check that the type is the real underlying type\ntry:\n    take_literal(None)\nexcept Exception as e:\n    print(type(e).__name__)\n# ... but not that it is a valid literal value\ntake_literal(10)\n[typing fixtures/typing-full.pyi]\n[out]\nLol(a=1, b=[])\n10\n1\n20\nTypeError\n1\nTypeError\n10\n\n[case testClassBasedTypedDict]\nfrom typing import TypedDict\n\nclass TD(TypedDict):\n    a: int\n\nclass TD2(TD):\n    b: int\n\nclass TD3(TypedDict, total=False):\n    c: int\n\nclass TD4(TD3, TD2, total=False):\n    d: int\n\ndef test_typed_dict() -> None:\n    d = TD(a=5)\n    assert d['a'] == 5\n    assert type(d) == dict\n    # TODO: This doesn't work yet\n    # assert TD.__annotations__ == {'a': int}\n\ndef test_inherited_typed_dict() -> None:\n    d = TD2(a=5, b=3)\n    assert d['a'] == 5\n    assert d['b'] == 3\n    assert type(d) == dict\n\ndef test_non_total_typed_dict() -> None:\n    d3 = TD3(c=3)\n    d4 = TD4(a=1, b=2, c=3, d=4)\n    assert d3['c'] == 3\n    assert d4['d'] == 4\n[typing fixtures/typing-full.pyi]\n\n[case testClassBasedNamedTuple]\nfrom typing import NamedTuple\nimport sys\n\n# Class-based NamedTuple requires Python 3.6+\nversion = sys.version_info[:2]\nif version[0] == 3 and version[1] < 6:\n    exit()\n\nclass NT(NamedTuple):\n    a: int\n\ndef test_named_tuple() -> None:\n    t = NT(a=1)\n    assert t.a == 1\n    assert type(t) is NT\n    assert isinstance(t, tuple)\n    assert not isinstance(tuple([1]), NT)\n\n[case testUnion]\nfrom typing import Union\n\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\n    def f(self, y: int) -> int:\n        return y + self.x\n\nclass B:\n    def __init__(self, x: object) -> None:\n        self.x = x\n    def f(self, y: object) -> object:\n        return y\n\ndef f(x: Union[A, str]) -> object:\n    if isinstance(x, A):\n        return x.x\n    else:\n        return x + 'x'\n\ndef g(x: int) -> Union[A, int]:\n    if x == 0:\n        return A(1)\n    else:\n        return x + 1\n\ndef get(x: Union[A, B]) -> object:\n    return x.x\n\ndef call(x: Union[A, B]) -> object:\n    return x.f(5)\n\n[file driver.py]\nfrom native import A, B, f, g, get, call\nassert f('a') == 'ax'\nassert f(A(4)) == 4\nassert isinstance(g(0), A)\nassert g(2) == 3\nassert get(A(5)) == 5\nassert get(B('x')) == 'x'\nassert call(A(4)) == 9\nassert call(B('x')) == 5\ntry:\n    f(1)\nexcept TypeError:\n    pass\nelse:\n    assert False\n\n[case testAnyAll]\nfrom typing import Iterable\n\ndef call_any_nested(l: Iterable[Iterable[int]], val: int = 0) -> int:\n    res = any(i == val for l2 in l for i in l2)\n    return 0 if res else 1\n\ndef call_any(l: Iterable[int], val: int = 0) -> int:\n    res = any(i == val for i in l)\n    return 0 if res else 1\n\ndef call_all(l: Iterable[int], val: int = 0) -> int:\n    res = all(i == val for i in l)\n    return 0 if res else 1\n\n[file driver.py]\nfrom native import call_any, call_all, call_any_nested\n\nzeros = [0, 0, 0]\nones = [1, 1, 1]\nmixed_001 = [0, 0, 1]\nmixed_010 = [0, 1, 0]\nmixed_100 = [1, 0, 0]\nmixed_011 = [0, 1, 1]\nmixed_101 = [1, 0, 1]\nmixed_110 = [1, 1, 0]\n\nassert call_any([]) == 1\nassert call_any(zeros) == 0\nassert call_any(ones) == 1\nassert call_any(mixed_001) == 0\nassert call_any(mixed_010) == 0\nassert call_any(mixed_100) == 0\nassert call_any(mixed_011) == 0\nassert call_any(mixed_101) == 0\nassert call_any(mixed_110) == 0\n\nassert call_all([]) == 0\nassert call_all(zeros) == 0\nassert call_all(ones) == 1\nassert call_all(mixed_001) == 1\nassert call_all(mixed_010) == 1\nassert call_all(mixed_100) == 1\nassert call_all(mixed_011) == 1\nassert call_all(mixed_101) == 1\nassert call_all(mixed_110) == 1\n\nassert call_any_nested([[1, 1, 1], [1, 1], []]) == 1\nassert call_any_nested([[1, 1, 1], [0, 1], []]) == 0\n\n[case testSum]\nfrom typing import List\n\nempty: List[int] = []\ndef test_sum_of_numbers() -> None:\n    assert sum(x for x in [1, 2, 3]) == 6\n    assert sum(x for x in [0.0, 1.2, 2]) == 3.2\n    assert sum(x for x in [1, 1j]) == 1 + 1j\n\ndef test_sum_callables() -> None:\n    assert sum((lambda x: x == 0)(x) for x in empty) == 0\n    assert sum((lambda x: x == 0)(x) for x in [0]) == 1\n    assert sum((lambda x: x == 0)(x) for x in [0, 0, 0]) == 3\n    assert sum((lambda x: x == 0)(x) for x in [0, 1, 0]) == 2\n    assert sum((lambda x: x % 2 == 0)(x) for x in range(2**10)) == 2**9\n\ndef test_sum_comparisons() -> None:\n    assert sum(x == 0 for x in empty) == 0\n    assert sum(x == 0 for x in [0]) == 1\n    assert sum(x == 0 for x in [0, 0, 0]) == 3\n    assert sum(x == 0 for x in [0, 1, 0]) == 2\n    assert sum(x % 2 == 0 for x in range(2**10)) == 2**9\n\ndef test_sum_multi() -> None:\n    assert sum(i + j == 0 for i, j in zip([0, 0, 0], [0, 1, 0])) == 2\n\ndef test_sum_misc() -> None:\n    # misc cases we do optimize (note, according to sum's helptext, we don't need to support\n    # non-numeric cases, but CPython and mypyc both do anyway)\n    assert sum(c == 'd' for c in 'abcdd') == 2\n    # misc cases we do not optimize\n    assert sum([0, 1]) == 1\n    assert sum([0, 1], 1) == 2\n\ndef test_sum_start_given() -> None:\n    a = 1\n    assert sum((x == 0 for x in [0, 1]), a) == 2\n    assert sum(((lambda x: x == 0)(x) for x in empty), 1) == 1\n    assert sum(((lambda x: x == 0)(x) for x in [0]), 1) == 2\n    assert sum(((lambda x: x == 0)(x) for x in [0, 0, 0]), 1) == 4\n    assert sum(((lambda x: x == 0)(x) for x in [0, 1, 0]), 1) == 3\n    assert sum(((lambda x: x % 2 == 0)(x) for x in range(2**10)), 1) == 2**9 + 1\n    assert sum((x for x in [1, 1j]), 2j) == 1 + 3j\n    assert sum((c == 'd' for c in 'abcdd'), 1) == 3\n[typing fixtures/typing-full.pyi]\n\n[case testNoneStuff]\nfrom typing import Optional\nclass A:\n    x: int\n\ndef lol(x: A) -> None:\n    setattr(x, 'x', 5)\n\ndef none() -> None:\n    return\n\ndef arg(x: Optional[A]) -> bool:\n    return x is None\n\n[file driver.py]\nimport native\nnative.lol(native.A())\n\n# Catch refcounting failures\nfor i in range(10000):\n    native.none()\n    native.arg(None)\n\n[case testBorrowRefs]\ndef make_garbage(arg: object) -> None:\n    b = True\n    while b:\n        arg = None\n        b = False\n\n[file driver.py]\nfrom native import make_garbage\nimport sys\n\ndef test():\n    x = object()\n    r0 = sys.getrefcount(x)\n    make_garbage(x)\n    r1 = sys.getrefcount(x)\n    assert r0 == r1\n\ntest()\n\n[case testFinalStaticRunFail]\nif False:\n    from typing import Final\n\nif bool():\n    x: 'Final' = [1]\n\ndef f() -> int:\n    return x[0]\n\n[file driver.py]\nfrom native import f\ntry:\n    print(f())\nexcept NameError as e:\n    print(e.args[0])\n[out]\nvalue for final name \"x\" was not set\n\n[case testFinalStaticRunListTupleInt]\nif False:\n    from typing import Final\n\nx: 'Final' = [1]\ny: 'Final' = (1, 2)\nz: 'Final' = 1 + 1\n\ndef f() -> int:\n    return x[0]\ndef g() -> int:\n    return y[0]\ndef h() -> int:\n    return z - 1\n\n[file driver.py]\nfrom native import f, g, h, x, y, z\nprint(f())\nprint(x[0])\nprint(g())\nprint(y)\nprint(h())\nprint(z)\n[out]\n1\n1\n1\n(1, 2)\n1\n2\n\n[case testCheckVersion]\nimport sys\n\nif sys.version_info[:2] == (3, 14):\n    def version() -> int:\n        return 14\nelif sys.version_info[:2] == (3, 13):\n    def version() -> int:\n        return 13\nelif sys.version_info[:2] == (3, 12):\n    def version() -> int:\n        return 12\nelif sys.version_info[:2] == (3, 11):\n    def version() -> int:\n        return 11\nelif sys.version_info[:2] == (3, 10):\n    def version() -> int:\n        return 10\nelif sys.version_info[:2] == (3, 9):\n    def version() -> int:\n        return 9\nelse:\n    raise Exception(\"we don't support this version yet!\")\n\n\n[file driver.py]\nimport sys\nversion = sys.version_info[:2]\n\nimport native\nassert native.version() == sys.version_info[1]\n\n[case testTypeErrorMessages]\nfrom typing import Tuple\nclass A:\n    pass\nclass B:\n    pass\n\ndef f(x: B) -> None:\n    pass\ndef g(x: Tuple[int, A]) -> None:\n    pass\n[file driver.py]\nfrom testutil import assertRaises\nfrom native import A, f, g\n\nclass Busted:\n    pass\nBusted.__module__ = None\n\nwith assertRaises(TypeError, \"int\"):\n    f(0)\nwith assertRaises(TypeError, \"native.A\"):\n    f(A())\nwith assertRaises(TypeError, \"tuple[None, native.A]\"):\n    f((None, A()))\nwith assertRaises(TypeError, \"tuple[tuple[int, str], native.A]\"):\n    f(((1, \"ha\"), A()))\nwith assertRaises(TypeError, \"tuple[<50 items>]\"):\n    f(tuple(range(50)))\n\nwith assertRaises(TypeError, \"errored formatting real type!\"):\n    f(Busted())\n\nwith assertRaises(TypeError, \"tuple[int, native.A] object expected; got tuple[int, int]\"):\n    g((20, 30))\n\n[case testComprehensionShadowBinder]\ndef foo(x: object) -> object:\n    if isinstance(x, list):\n        return tuple(x for x in x), x\n    return None\n\n[file driver.py]\nfrom native import foo\n\nassert foo(None) == None\nassert foo([1, 2, 3]) == ((1, 2, 3), [1, 2, 3])\n\n[case testAllLiterals]\n# Test having all sorts of literals in a single file\n\ndef test_str() -> None:\n    assert '' == eval(\"''\")\n    assert len('foo bar' + str()) == 7\n    assert 'foo bar' == eval(\"'foo bar'\")\n    assert 'foo\\u1245\\0bar' == eval(\"'foo' + chr(0x1245) + chr(0) + 'bar'\")\n    assert 'foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345' == eval(\"'foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345'\")\n    assert 'Zoobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar123' == eval(\"'Zoobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar123'\")\n\ndef test_bytes() -> None:\n    assert b'' == eval(\"b''\")\n    assert b'foo bar' == eval(\"b'foo bar'\")\n    assert b'\\xafde' == eval(r\"b'\\xafde'\")\n    assert b'foo\\xde\\0bar' == eval(\"b'foo' + bytes([0xde, 0]) + b'bar'\")\n    assert b'foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345' == eval(\"b'foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345foobar12345'\")\n\ndef test_int() -> None:\n    assert 2875872359823758923758923759 == eval('2875872359823758923758923759')\n    assert -552875872359823758923758923759 == eval('-552875872359823758923758923759')\n\ndef test_float() -> None:\n    assert 1.5 == eval('1.5')\n    assert -3.75 == eval('-3.75')\n    assert 2.5e10 == eval('2.5e10')\n    assert 2.5e50 == eval('2.5e50')\n    assert 2.5e1000 == eval('2.5e1000')\n    assert -2.5e1000 == eval('-2.5e1000')\n\ndef test_complex() -> None:\n    assert 1.5j == eval('1.5j')\n    assert 1.5j + 2.5 == eval('2.5 + 1.5j')\n    assert -3.75j == eval('-3.75j')\n    assert 2.5e10j == eval('2.5e10j')\n    assert 2.5e50j == eval('2.5e50j')\n    assert 2.5e1000j == eval('2.5e1000j')\n    assert 2.5e1000j + 3.5e2000 == eval('3.5e2000 + 2.5e1000j')\n    assert -2.5e1000j == eval('-2.5e1000j')\n\n[case testUnreachableExpressions]\nfrom typing import cast\nimport sys\n\ndef test_unreachable() -> None:\n    A = sys.platform == 'x' and foobar\n    B = sys.platform == 'x' and sys.foobar\n    C = sys.platform == 'x' and f(a, -b, 'y') > [c + e, g(y=2)]\n    C = sys.platform == 'x' and cast(a, b[c])\n    C = sys.platform == 'x' and (lambda x: y + x)\n    C = sys.platform == 'x' and (x for y in z)\n    C = sys.platform == 'x' and [x for y in z]\n    C = sys.platform == 'x' and {x: x for y in z}\n    C = sys.platform == 'x' and {x for y in z}\n\n    assert not A\n    assert not B\n    assert not C\n\n[case testDoesntSegfaultWhenTopLevelFails]\n# make the initial import fail\nassert False\n\n[file driver.py]\n# load native, cause PyInit to be run, create the module but don't finish initializing the globals\nfor _ in range(2):\n    try:\n        import native\n        raise RuntimeError('exception expected')\n    except AssertionError:\n        pass\n\n[case testUnderscoreFunctionsInMethods]\n\nclass A:\n    def _(arg): pass\n    def _(arg): pass\nclass B(A):\n    def _(arg): pass\n    def _(arg): pass\n\ndef test_underscore() -> None:\n    A()\n    B()\n\n[case testGlobalRedefinition_toplevel]\n# mypy: allow-redefinition-old\ni = 0\ni += 1\ni = \"foo\"\ni += i\ni = b\"foo\"\n\ndef test_redefinition() -> None:\n    assert i == b\"foo\"\n\n[case testWithNative]\nclass DummyContext:\n    def __init__(self):\n        self.c = 0\n    def __enter__(self) -> None:\n        self.c += 1\n    def __exit__(self, exc_type, exc_val, exc_tb) -> None:\n        self.c -= 1\n\ndef test_dummy_context() -> None:\n    c = DummyContext()\n    with c:\n        assert c.c == 1\n    assert c.c == 0\n\n[case testWithNativeVarArgs]\nclass DummyContext:\n    def __init__(self):\n        self.c = 0\n    def __enter__(self) -> None:\n        self.c += 1\n    def __exit__(self, *args: object) -> None:\n        self.c -= 1\n\ndef test_dummy_context() -> None:\n    c = DummyContext()\n    with c:\n        assert c.c == 1\n    assert c.c == 0\n\n[case testIsInstanceTuple]\nfrom typing import Any\n\ndef isinstance_empty(x: Any) -> bool:\n    return isinstance(x, ())\ndef isinstance_single(x: Any) -> bool:\n    return isinstance(x, (str,))\ndef isinstance_multi(x: Any) -> bool:\n    return isinstance(x, (str, int))\n\ndef test_isinstance_empty() -> None:\n    assert isinstance_empty(\"a\") is False\n    assert isinstance_empty(1) is False\n    assert isinstance_empty(None) is False\ndef test_isinstance_single() -> None:\n    assert isinstance_single(\"a\") is True\n    assert isinstance_single(1) is False\n    assert isinstance_single(None) is False\ndef test_isinstance_multi() -> None:\n    assert isinstance_multi(\"a\") is True\n    assert isinstance_multi(1) is True\n    assert isinstance_multi(None) is False\n"
  },
  {
    "path": "mypyc/test-data/run-multimodule.test",
    "content": "-- These test cases compile two or more modules at a time.\n-- Any file prefixed with \"other\" is compiled.\n--\n-- Note that these are run in three compilation modes: regular,\n-- multi-file and separate. See the docstrings of\n-- mypyc.test.test_run.TestRunMultiFile and\n-- mypyc.test.test_run.TestRunSeparate for more information.\n--\n-- Some of these files perform multiple incremental runs. See\n-- test-data/unit/check-incremental.test for more information\n-- about how this is specified (e.g. .2 file name suffixes).\n\n[case testMultiModulePackage]\nfrom p.other import g, _i as i\ndef f(x: int) -> int:\n    from p.other import h\n    return i(h(g(x + 1)))\n[file p/__init__.py]\n[file p/other.py]\ndef g(x: int) -> int:\n    return x + 2\ndef h(x: int) -> int:\n    return x + 1\ndef _i(x: int) -> int:\n    return x + 3\n[file driver.py]\nimport native\nfrom native import f\nfrom p.other import g\nassert f(3) == 10\nassert g(2) == 4\ntry:\n    f(1.1)\nexcept TypeError:\n    pass\nelse:\n    assert False\ntry:\n    g(1.1)\nexcept TypeError:\n    pass\nelse:\n    assert False\n\n[case testMultiModuleFastpaths]\n[file other_main.py]\n\n[file other_main.py.2]\nfrom other_b import A, func\n\nclass B(A):\n    pass\n\ndef test() -> None:\n    a = A()\n    assert func() == 12\n    assert a.method() == \"test\"\n\ntest()\n\n[file other_b.py]\nclass A:\n    def method(self) -> str:\n        return \"test\"\n\ndef func() -> int:\n    return 12\n\n# Remove all the methods and functions from globals to ensure that\n# they get called via the fastpaths even when doing incremental\n# compilation.\nsetattr(A, 'method', None)\nsetattr(A, '__init__', None)\nglobals()['func'] = None\nglobals()['A'] = None\n\n[file driver.py]\nimport other_main\n\n[case testMultiModuleSameNames]\n# Use same names in both modules\nimport other\ndef f() -> int:\n    return 0\nclass C:\n    x: int\n    def __init__(self) -> None:\n        self.x = 1\n    def f(self, x: int) -> int:\n        return self.x + x\nclass D(C): pass\n\ndef g(x: 'other.C') -> None:\n    pass\n\n[file other.py]\ndef f(x: int) -> int:\n    return x + 1\nclass C:\n    x: int\n    def __init__(self) -> None:\n        self.x = 2\n    def f(self, x: int) -> int:\n        return self.x + x + 1\nclass D(C): pass\n[file driver.py]\nimport native, other\nassert native.f() == 0\nassert other.f(3) == 4\nc1 = native.C()\nc1.x += 3\nc2 = other.C()\nc2.x += 6\nassert c1.f(9) == 1 + 3 + 9\nassert c2.f(7) == 2 + 6 + 7 + 1\nassert isinstance(native.D(), native.C)\nassert isinstance(other.D(), other.C)\nassert not isinstance(native.D(), other.C)\nassert not isinstance(other.D(), native.C)\n\n[case testMultiModuleInitializeImportedModules]\nfrom other import f\n\ndef g() -> int:\n    return f(1)\n[file other.py]\ndef f(x: int) -> int:\n    return x + 4\n[file driver.py]\nimport sys\nassert 'other' not in sys.modules\nfrom native import g\nassert 'other' in sys.modules\nassert g() == 5\nf = sys.modules['other'].f\nassert f(1) == 5\ntry:\n    f(1.1)\nexcept TypeError:\n    pass\nelse:\n    assert False\n\n[case testMultiModuleImportClass]\nfrom typing import cast\nfrom other import C, a_global\n\nclass D(C):\n    def __init__(self, x: int) -> None:\n        self.x = x\n\ndef f(c: C) -> int:\n    d = D(3)\n    o: object = c\n    c = cast(C, o)\n    return a_global + c.x + c.f() + d.x + d.f() + 1\n[file other.py]\nfrom typing import Final\na_global: Final = int('5')\n\nclass C:\n    x: int\n\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def __hash__(self) -> int:\n        return self.x\n\n    def __str__(self) -> str:\n        return str(self.x)\n\n    def f(self) -> int:\n        return 2\n\n    def check(self) -> None:\n        assert isinstance(self, C)\n\n[file driver.py]\nfrom native import f, D\nfrom other import C\nc = C(4)\nassert f(c) == 5 + 4 + 2 + 3 + 2 + 1\nassert str(D(10)) == '10'\nassert hash(10) == 10\ntry:\n    f(1)\nexcept TypeError:\n    pass\nelse:\n    assert False\n\nassert isinstance(D(10), C)\n\nc.check()\nD(10).check()\n\n[case testMultiModuleSpecialize]\nfrom other import A\n\nclass B(A):\n    def foo(self, x: object) -> int:\n        print(2)\n        return id(x)\n[file other.py]\nclass A:\n    def foo(self, x: int) -> object:\n        print(1)\n        return str(x)\n\ndef use_a(x: A, y: int) -> object:\n    return x.foo(y)\n\n[file driver.py]\nfrom native import B\nfrom other import A, use_a\na = A()\nb = B()\no = object()\ni = 10\nassert a.foo(10) == '10'\nassert b.foo(o) == id(o)\nassert use_a(a, 10) == '10'\nassert use_a(b, i) == id(i)\n[out]\n1\n2\n1\n2\n\n[case testMultiModuleLiterals]\nfrom other import gs, gi, gf\n\ndef fs() -> str:\n    return 'f' + gs()\ndef fi() -> int:\n    return 10001000100010001000 + gi()\ndef ff() -> float:\n    return 2.0 + gf()\n[file other.py]\ndef gi() -> int:\n    return 20001000100010001000\ndef gs() -> str:\n    return 'g'\ndef gf() -> float:\n    return 3.0\n[file driver.py]\nfrom native import fs, fi, ff\nassert fs() == 'fg'\nassert fi() == 30002000200020002000\nassert ff() == 5.0\n\n[case testMultiModuleTraceback]\nfrom other import fail2\n\ndef fail() -> None:\n    fail2()\n[file other.py]\ndef fail2() -> None:\n    x = [1]\n    x[2] = 2\n[file driver.py]\nimport traceback\nimport sys\nimport native\nimport other\ntry:\n    other.fail2()\nexcept IndexError:\n    tb = sys.exc_info()[2]\n    assert tb.tb_next.tb_frame.f_globals is other.__dict__\n    traceback.print_exc()\ntry:\n    native.fail()\nexcept IndexError:\n    tb = sys.exc_info()[2]\n    assert tb.tb_next.tb_frame.f_globals is native.__dict__\n    traceback.print_exc()\n[out]\nTraceback (most recent call last):\n  File \"driver.py\", line 6, in <module>\n    other.fail2()\n  File \"other.py\", line 3, in fail2\n    x[2] = 2\nIndexError: list assignment index out of range\nTraceback (most recent call last):\n  File \"driver.py\", line 12, in <module>\n    native.fail()\n  File \"native.py\", line 4, in fail\n    fail2()\n  File \"other.py\", line 3, in fail2\n    x[2] = 2\nIndexError: list assignment index out of range\n[out version>=3.13]\nTraceback (most recent call last):\n  File \"driver.py\", line 6, in <module>\n    other.fail2()\n    ~~~~~~~~~~~^^\n  File \"other.py\", line 3, in fail2\n    x[2] = 2\nIndexError: list assignment index out of range\nTraceback (most recent call last):\n  File \"driver.py\", line 12, in <module>\n    native.fail()\n    ~~~~~~~~~~~^^\n  File \"native.py\", line 4, in fail\n    fail2()\n  File \"other.py\", line 3, in fail2\n    x[2] = 2\nIndexError: list assignment index out of range\n\n[case testMultiModuleCycle]\nif False:\n    from typing import Final\nimport other\n\nx = int('0')  # type: Final\n\ndef f1() -> int:\n    return other.f2() + other.x\n\ndef f3() -> int:\n    return 5\n[file other.py]\nif False:\n    from typing import Final\nimport native\n\nx = int('0')  # type: Final\n\ndef f2() -> int:\n    return native.f3() + native.x\n[file driver.py]\nfrom native import f1\nassert f1() == 5\n\n[case testMultiModuleCycleWithClasses]\nimport other\n\nclass D: pass\n\ndef f() -> other.C:\n    return other.C()\n\ndef g(c: other.C) -> D:\n    return c.d\n\n[file other.py]\nimport native\n\nclass C:\n    def __init__(self) -> None:\n        self.d = native.D()\n\ndef h(d: native.D) -> None:\n    pass\n\n[file driver.py]\nfrom native import f, g\nfrom other import C, h\n\nc = f()\nassert isinstance(c, C)\nassert g(c) is c.d\nh(c.d)\n\ntry:\n    g(1)\nexcept TypeError:\n    pass\nelse:\n    assert False\n\ntry:\n    h(1)\nexcept TypeError:\n    pass\nelse:\n    assert False\n\n[case testMultiModuleCycleWithInheritance]\nimport other\n\nclass Deriv1(other.Base1):\n    def __init__(self) -> None:\n        super().__init__()\n\nclass Base2:\n    y: int\n    def __init__(self) -> None:\n        self.y = 2\n\n[file other.py]\nfrom typing import Tuple\nimport native\n\nclass Base1:\n    a: Tuple[int, int]\n    x: int\n    def __init__(self) -> None:\n        self.x = 1\n\ndef make_2() -> native.Base2:\n    return native.Base2()\n\n[file driver.py]\nfrom native import Deriv1\nfrom other import make_2\na = Deriv1()\nassert a.x == 1\nb = make_2()\nassert b.y == 2\n\n[case testMultiModuleTraitInheritance]\nfrom other import Base1, Base2\n\nclass Deriv1(Base1, Base2):\n    pass\n\n[file other.py]\nfrom mypy_extensions import trait\n\n@trait\nclass Base1:\n    def foo(self) -> int: return 10\n@trait\nclass Base2:\n    def bar(self) -> int: return 12\n\n[file driver.py]\nfrom native import Deriv1\na = Deriv1()\nassert a.foo() == 10 and a.bar() == 12\n\n\n[case testImportCycleWithNonCompiledModule]\nimport m\n\nclass C: pass\n\ndef f1() -> int:\n    m.D()\n    return m.f2()\n\ndef f3() -> int:\n    return 2\n\n[file m.py]\n# This module is NOT compiled\nimport native\n\nclass D: pass\n\ndef f2() -> int:\n    native.C()\n    return native.f3()\n\n[file driver.py]\nfrom native import f1\n\nassert f1() == 2\n\n[case testImportCycleWithTopLevelStatements]\nimport other\nx = 1\nprint(x)\n\n[file other.py]\nimport native\nx = 2\nprint(x)\n\n[file driver.py]\nimport other\nprint('-')\nimport native\nprint('>', native.x)\nprint('>', other.x)\n\n[out]\n1\n2\n-\n> 1\n> 2\n\n[case testMultiModuleCycleIfMypy1]\nfrom other import foo, bar\n\nclass Foo:\n    def foo(self) -> None:\n        foo(self)\nclass Bar:\n    def bar(self) -> None:\n        bar(self)\n\n[file other.py]\nfrom typing import TYPE_CHECKING\nMYPY = False\nif MYPY:\n    from native import Foo\nif TYPE_CHECKING:\n    from native import Bar\n\ndef foo(x: 'Foo') -> None:\n    pass\ndef bar(x: 'Bar') -> None:\n    pass\n\n[file driver.py]\nfrom native import Foo, Bar\nFoo().foo()\nBar().bar()\n\n[case testMultiModuleCycleIfMypy2]\nMYPY = False\nif MYPY:\n    from other import C\n\nclass D:\n    def __init__(self) -> None:\n        self.y = 1\n\ndef f(c: 'C') -> int:\n    return c.x\n\n[file other.py]\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    from native import D\n\nclass C:\n    def __init__(self) -> None:\n        self.x = 2\n\ndef g(d: 'D') -> int:\n    return d.y\n\n[file driver.py]\nfrom native import f, D\nfrom other import g, C\n\nassert f(C()) == 2\nassert g(D()) == 1\n\ntry:\n    f(D())\nexcept TypeError:\n    pass\nelse:\n    assert False\n\ntry:\n    g(C())\nexcept TypeError:\n    pass\nelse:\n    assert False\n\n[case testMultiModuleRelative]\nfrom package.a import f\n[file package/__init__.py]\n[file package/a.py]\nfrom . import b\nfrom .c import c3\ndef f() -> None:\n    print(\"Hello \" + b.b2())\n    print(\"Hello \" + c3())\n[file package/b.py]\ndef b2() -> str:\n    return \"moon!\"\n[file package/c.py]\ndef c3() -> str:\n    return \"sun!\"\n\n[file driver.py]\nfrom native import f\nf()\n[out]\nHello moon!\nHello sun!\n\n[case testMultiModuleCrash]\nb = False\nif b:\n    import other\n\ndef foo() -> None:\n    try:\n        other.x\n    except:\n        pass\n    else:\n        assert False\n\n[file other.py]\nx = 10\n\n[file driver.py]\nfrom native import foo\nfoo()\n\n[case testTrivialIncremental]\n# separate: [([\"other.py\", \"other_b.py\"], \"stuff\")]\nfrom other import x\nfrom other_b import z\ny = x + z\n[file other.py]\nx = 1\n[file other.py.2]\nx = 2\n[file other_b.py]\nz = 1\n\n[file driver.py]\nfrom native import y\nprint(y)\n[out]\n2\n[out2]\n3\n[rechecked other, other_b]\n\n[case testIncrementalCompilation1]\nimport non_native\nfrom other_a import A\nfrom other_b import z\n\na = A()\nassert a.y == z\n\nassert non_native.foo() == 0\n\n[file other_a.py]\nfrom other_b import z\nfrom typing import Iterable\n\nclass A:\n    def __init__(self) -> None:\n        self.y = z\n[file other_a.py.2]\nfrom other_b import z\nfrom typing import Iterable\n\nclass A:\n    def __init__(self) -> None:\n        self.x = 'test'\n        self.y = z\n[file other_b.py]\nimport other_a\n\nz = 10\n\ndef foo() -> 'other_a.A':\n    return other_a.A()\n[file other_b.py.3]\nimport other_a\n\nz = 20\n\ndef foo() -> 'other_a.A':\n    return other_a.A()\n\n[file non_native.py]\nimport other_a\n\ndef foo() -> int:\n    return 0\n\n[file non_native.py.4]\nimport other_a\n\ndef foo() -> float:\n    return 0\n\n[file driver.py]\nfrom native import a\nprint(a.y, getattr(a, 'x', None))\n\n[out]\n10 None\n[out2]\n10 test\n[out3]\n20 test\n[out4]\n20 test\n\n[rechecked other_a, other_b, native, non_native]\n[rechecked2 other_a, other_b]\n[rechecked3 native, non_native]\n\n\n-- This one tests a group that is not an SCC.\n[case testIncrementalCompilation2]\n# separate: [([\"other_a.py\", \"other_b.py\"], \"stuff\")]\nfrom other_a import A\nfrom other_b import z\n\na = A()\nassert a.y == z\n\n[file other_a.py]\nfrom other_b import z\n\nclass A:\n    def __init__(self) -> None:\n        self.y = z\n[file other_a.py.2]\nfrom other_b import z\n\nclass A:\n    def __init__(self) -> None:\n        self.x = 'test'\n        self.y = z\n\n[file other_b.py]\nz = 10\n\n[file driver.py]\nfrom native import a\nprint(a.y, getattr(a, 'x', None))\n\n[out]\n10 None\n[out2]\n10 test\n\n[rechecked other_a, other_b, native]\n\n[case testIncrementalCompilation3]\nfrom other import X\nY = X\ndef foo() -> int:\n    return X\n\n[file other.py]\nfrom typing import Final\nX: Final = 10\n\n[file other.py.2]\nfrom typing import Final\nX: Final = 20\n\n[file driver.py]\nimport native\nimport other\nassert native.Y == other.X\nassert native.foo() == other.X\n\n[rechecked native, other]\n\n-- This one tests a group changing\n[case testIncrementalCompilation4]\n# separate: [([\"other_a.py\", \"other_b.py\"], \"stuff\")]\n# separate2: []\nfrom other_a import A\nfrom other_b import z\n\na = A()\nassert a.y == z\n\n[file other_a.py]\nfrom other_b import z\n\nclass A:\n    def __init__(self) -> None:\n        self.y = z\n\n[file other_b.py]\nz = 10\n\n[file wtvr.py.2]\n\n[file driver.py]\nfrom native import a\nprint(a.y, getattr(a, 'x', None))\n\n[out]\n10 None\n[out2]\n10 None\n\n[rechecked other_a, other_b, native]\n\n-- This one tests cases where other modules *do not* need rechecked\n[case testIncrementalCompilation5]\nimport other_a\n[file other_a.py]\nfrom other_b import f\nassert f(10) == 20\n[file other_a.py.2]\nfrom other_b import f\nassert f(20) == 40\n\n[file other_b.py]\ndef f(x: int) -> int:\n    return x * 2\n\n[file driver.py]\nimport native\n\n[rechecked other_a]\n\n-- Delete one of the C files and make sure this forces recompilation\n[case testIncrementalCompilation6]\nimport other_a\nassert other_a.foo() == 10\n[file other_a.py]\ndef foo() -> int: return 10\n\n[file build/__native_other_a.c]\n\n[delete build/__native_other_a.c.2]\n\n[file driver.py]\nimport native\n\n[rechecked other_a]\n\n[case testSeparateCompilationWithUndefinedAttribute]\nfrom other_a import A\n\ndef f() -> None:\n    a = A()\n    if a.x == 5:\n        print(a.y)\n        print(a.m())\n    else:\n        assert a.x == 6\n        try:\n            print(a.y)\n        except AttributeError:\n            print('y undefined')\n        else:\n            assert False\n\n        try:\n            print(a.m())\n        except AttributeError:\n            print('y undefined')\n        else:\n            assert False\n\n[file other_a.py]\nfrom other_b import B\n\nclass A(B):\n    def __init__(self) -> None:\n        self.y = 9\n\n[file other_a.py.2]\nfrom other_b import B\n\nclass A(B):\n    x = 6\n\n    def __init__(self) -> None:\n        pass\n\n[file other_b.py]\nclass B:\n    x = 5\n\n    def __init__(self) -> None:\n        self.y = 7\n\n    def m(self) -> int:\n        return self.y\n\n[file driver.py]\nfrom native import f\nf()\n\n[rechecked native, other_a]\n\n[out]\n9\n9\n[out2]\ny undefined\ny undefined\n\n[case testIncrementalCompilationWithDeletable]\nimport other_a\n[file other_a.py]\nfrom other_b import C\n[file other_a.py.2]\nfrom other_b import C\nc = C()\nprint(getattr(c, 'x', None))\ndel c.x\nprint(getattr(c, 'x', None))\n[file other_b.py]\nclass C:\n    __deletable__ = ['x']\n    def __init__(self) -> None:\n        self.x = 0\n[file driver.py]\nimport native\n[out]\n[out2]\n0\nNone\n\n[case testIncrementalCompilationWithNonClassTypeDef]\nimport other_a\n[file other_a.py]\nfrom other_b import MyInt\n[file other_a.py.2]\nfrom other_b import MyInt, NT, TD\ni = MyInt(42)\n\ndef f(x: MyInt) -> int:\n    return x + 1\n\ndef g(x: int) -> MyInt:\n    return MyInt(x + 2)\n\nprint(i)\nprint(f(i))\nprint(g(13))\n\ndef make_nt(x: int) -> NT:\n    return NT(x=MyInt(x))\n\nprint(make_nt(4))\n\ndef make_td(x: int) -> TD:\n    return {\"x\": MyInt(x)}\n\nprint(make_td(5))\n\n[file other_b.py]\nfrom typing import NewType, NamedTuple, TypedDict\nfrom enum import Enum\n\nMyInt = NewType(\"MyInt\", int)\nNT = NamedTuple(\"NT\", [(\"x\", MyInt)])\nTD = TypedDict(\"TD\", {\"x\": MyInt})\n\n[file driver.py]\nimport native\n\n[typing fixtures/typing-full.pyi]\n[out]\n[out2]\n42\n43\n15\nNT(x=4)\n{'x': 5}\n\n[case testExtraLibRtSourceFileDep]\ntable_list = list(range(256))\ntable_list[ord('A')] = ord('B')\ntable = bytes(table_list)\n\ndef translate(b: bytes) -> bytes:\n    # The primimitive for bytes.translate requires an optional C file from lib-rt\n    return b.translate(table)\n[file driver.py]\nimport native\nassert native.translate(b'ABCD') == b'BBCD'\n"
  },
  {
    "path": "mypyc/test-data/run-mypy-sim.test",
    "content": "-- Some test code that tries to simulate important/interesting parts of mypy itself!\n[case testSimulateMypy]\nfrom mypy_extensions import trait\nfrom typing import List, TypeVar, cast, Generic\nfrom abc import abstractmethod\nimport other_strconv as strconv\n#from other_visitor import ExpressionVisitor, StatementVisitor, NodeVisitor\nimport other_visitor as visitor\n\nT = TypeVar('T')\n\n############ nodes.py\n\nclass Context:\n    def __init__(self) -> None:\n        self.line = -1\n    def set_line(self, line: int) -> None:\n        self.line = line\n\nclass Node(Context):\n    def accept(self, visitor: visitor.NodeVisitor[T]) -> T: return cast(T, None)\n    def to_str(self) -> str:\n        return self.accept(strconv.StrConv())\n\n@trait\nclass Statement(Node):\n    def accept(self, visitor: visitor.StatementVisitor[T]) -> T: return cast(T, None)\n\n@trait\nclass Expression(Node):\n    def accept(self, visitor: visitor.ExpressionVisitor[T]) -> T: return cast(T, None)\n\n@trait\nclass SymbolNode(Node):\n    \"\"\"Nodes that can be stored in a symbol table.\"\"\"\n    @abstractmethod\n    def name(self) -> str: return cast(str, None)\n\nclass FuncBase(Node):\n    def __init__(self) -> None:\n        super().__init__()\n        self.is_static = False\n\nclass Block(Statement):\n    def __init__(self, stmts: List[Statement]) -> None:\n        self.stmts = stmts\n\n    def accept(self, visitor: visitor.StatementVisitor[T]) -> T:\n        return visitor.visit_block(self)\n\nclass ExprStmt(Statement):\n    def __init__(self, expr: Expression) -> None:\n        self.expr = expr\n\n    def accept(self, visitor: visitor.StatementVisitor[T]) -> T:\n        return visitor.visit_expr_stmt(self)\n\nclass FuncItem(FuncBase):\n    def __init__(self, body: Block) -> None:\n        self.body = body\n\nclass FuncDef(FuncItem, SymbolNode, Statement):\n    def __init__(self, name: str, body: Block) -> None:\n        super().__init__(body)\n        self._name = name\n    def accept(self, visitor: visitor.StatementVisitor[T]) -> T:\n        return visitor.visit_func_def(self)\n    def name(self) -> str:\n        return self._name\n\nclass LambdaExpr(FuncItem, Expression):\n    def accept(self, visitor: visitor.ExpressionVisitor[T]) -> T:\n        return visitor.visit_lambda_expr(self)\n\ndef lol(x: Statement) -> int:\n    return x.line\n\n[file other_visitor.py]\nfrom mypy_extensions import trait\nfrom typing import TypeVar, cast, Generic\nfrom abc import abstractmethod\nimport native as nodes\n\nT = TypeVar('T')\n\n@trait\nclass ExpressionVisitor(Generic[T]):\n    @abstractmethod\n    def visit_lambda_expr(self, o: 'nodes.LambdaExpr') -> T:\n        return cast(T, None)\n\n@trait\nclass StatementVisitor(Generic[T]):\n    @abstractmethod\n    def visit_block(self, o: 'nodes.Block') -> T:\n        return cast(T, None)\n\n    @abstractmethod\n    def visit_func_def(self, o: 'nodes.FuncDef') -> T:\n        return cast(T, None)\n\n    @abstractmethod\n    def visit_expr_stmt(self, o: 'nodes.ExprStmt') -> T:\n        return cast(T, None)\n\n@trait\nclass NodeVisitor(Generic[T], ExpressionVisitor[T], StatementVisitor[T]):\n    pass\n\n[file other_strconv.py]\nfrom typing import List\nimport native as nodes\nfrom other_visitor import NodeVisitor\n\nclass StrConv(NodeVisitor[str]):\n    def visit_block(self, b: nodes.Block) -> str:\n        # we really need comprehensions!\n        # TODO: PartialType unsupported\n        things = []  # type: List[str]\n        for s in b.stmts:\n            things.append(s.accept(self))\n        return \"{\" + \"; \".join(things) + \"}\"\n\n    def visit_func_def(self, f: nodes.FuncDef) -> str:\n        return \"def \" + f.name() + \"(): \" + f.body.accept(self)\n\n    def visit_expr_stmt(self, e: nodes.ExprStmt) -> str:\n        return e.expr.accept(self)\n\n    def visit_lambda_expr(self, b: nodes.LambdaExpr) -> str:\n        return \"(fn: \" + b.body.accept(self) + \")\"\n\n[file driver.py]\nfrom native import *\n\nblock = Block([Block([]), ExprStmt(LambdaExpr(Block([])))])\nfn = FuncDef('test', block)\nassert fn.to_str() == \"def test(): {{}; (fn: {})}\"\n"
  },
  {
    "path": "mypyc/test-data/run-primitives.test",
    "content": "# Test cases for misc primitives (compile and run)\n#\n# Please only add tests that don't have an obvious place in type-specific test\n# files such as run-strings.test, run-lists.test, etc.\n\n[case testGenericEquality]\ndef eq(a: object, b: object) -> bool:\n    if a == b:\n        return True\n    else:\n        return False\ndef ne(a: object, b: object) -> bool:\n    if a != b:\n        return True\n    else:\n        return False\ndef f(o: object) -> bool:\n    if [1, 2] == o:\n        return True\n    else:\n        return False\n[file driver.py]\nfrom native import eq, ne, f\nassert eq('xz', 'x' + 'z')\nassert not eq('x', 'y')\nassert not ne('xz', 'x' + 'z')\nassert ne('x', 'y')\nassert f([1, 2])\nassert not f([2, 2])\nassert not f(1)\n\n[case testGenericBinaryOps]\nfrom typing import Any\ndef add(x: Any, y: Any) -> Any:\n    return x + y\ndef subtract(x: Any, y: Any) -> Any:\n    return x - y\ndef multiply(x: Any, y: Any) -> Any:\n    return x * y\ndef floor_div(x: Any, y: Any) -> Any:\n    return x // y\ndef true_div(x: Any, y: Any) -> Any:\n    return x / y\ndef remainder(x: Any, y: Any) -> Any:\n    return x % y\ndef power(x: Any, y: Any) -> Any:\n    return x ** y\ndef lshift(x: Any, y: Any) -> Any:\n    return x << y\ndef rshift(x: Any, y: Any) -> Any:\n    return x >> y\ndef num_and(x: Any, y: Any) -> Any:\n    return x & y\ndef num_xor(x: Any, y: Any) -> Any:\n    return x ^ y\ndef num_or(x: Any, y: Any) -> Any:\n    return x | y\ndef lt(x: Any, y: Any) -> Any:\n    if x < y:\n        return True\n    else:\n        return False\ndef le(x: Any, y: Any) -> Any:\n    if x <= y:\n        return True\n    else:\n        return False\ndef gt(x: Any, y: Any) -> Any:\n    if x > y:\n        return True\n    else:\n        return False\ndef ge(x: Any, y: Any) -> Any:\n    if x >= y:\n        return True\n    else:\n        return False\ndef contains(x: Any, y: Any) -> Any:\n    if x in y:\n        return True\n    else:\n        return False\ndef identity(x: Any, y: Any) -> Any:\n    if x is y:\n        return True\n    else:\n        return False\ndef disidentity(x: Any, y: Any) -> Any:\n    if x is not y:\n        return True\n    else:\n        return False\ndef not_eq_cond(a: Any, b: Any) -> bool:\n    if not (a == b):\n        return True\n    else:\n        return False\ndef eq2(a: Any, b: Any) -> bool:\n    return a == b\ndef slice1(x: Any) -> Any:\n    return x[:]\ndef slice2(x: Any, y: Any) -> Any:\n    return x[y:]\ndef slice3(x: Any, y: Any) -> Any:\n    return x[:y]\ndef slice4(x: Any, y: Any, z: Any) -> Any:\n    return x[y:z]\ndef slice5(x: Any, y: Any, z: Any, zz: Any) -> Any:\n    return x[y:z:zz]\n[file driver.py]\nfrom native import *\nassert add(5, 6) == 11\nassert add('x', 'y') == 'xy'\nassert subtract(8, 3) == 5\nassert multiply(8, 3) == 24\nassert floor_div(8, 3) == 2\nassert true_div(7, 2) == 3.5\nassert remainder(11, 4) == 3\nassert remainder('%.3d', 5) == '005'\nassert remainder('%d-%s', (5, 'xy')) == '5-xy'\nassert power(3, 4) == 81\nassert lshift(5, 3) == 40\nassert rshift(41, 3) == 5\nassert num_and(99, 56) == 32\nassert num_xor(99, 56) == 91\nassert num_or(99, 56) == 123\nassert lt('a', 'b')\nassert not lt('a', 'a')\nassert not lt('b', 'a')\nassert not gt('a', 'b')\nassert not gt('a', 'a')\nassert gt('b', 'a')\nassert le('a', 'b')\nassert le('a', 'a')\nassert not le('b', 'a')\nassert not ge('a', 'b')\nassert ge('a', 'a')\nassert ge('b', 'a')\nassert contains('x', 'axb')\nassert not contains('X', 'axb')\nassert contains('x', {'x', 'y'})\na = [1, 3, 5]\nassert slice1(a) == a\nassert slice1(a) is not a\nassert slice2(a, 1) == [3, 5]\nassert slice3(a, -1) == [1, 3]\nassert slice4(a, 1, -1) == [3]\nassert slice5(a, 2, 0, -1) == [5, 3]\no1, o2 = object(), object()\nassert identity(o1, o1)\nassert not identity(o1, o2)\nassert not disidentity(o1, o1)\nassert disidentity(o1, o2)\nassert eq2('xz', 'x' + 'z')\nassert not eq2('x', 'y')\nassert not not_eq_cond('xz', 'x' + 'z')\nassert not_eq_cond('x', 'y')\n\n[case testGenericMiscOps]\nfrom typing import Any\ndef neg(x: Any) -> Any:\n    return -x\ndef pos(x: Any) -> Any:\n    return +x\ndef invert(x: Any) -> Any:\n    return ~x\ndef get_item(o: Any, k: Any) -> Any:\n    return o[k]\ndef set_item(o: Any, k: Any, v: Any) -> Any:\n    o[k] = v\n[file driver.py]\nfrom native import *\nassert neg(6) == -6\nassert pos(6) == 6\nassert invert(6) == -7\nd = {'x': 5}\nassert get_item(d, 'x') == 5\nset_item(d, 'y', 6)\nassert d['y'] == 6\n\n[case testAnyAttributeAndMethodAccess]\nfrom typing import Any, List\nclass C:\n    a: int\n    def m(self, x: int, a: List[int]) -> int:\n        return self.a + x + a[0]\ndef get_a(x: Any) -> Any:\n    return x.a\ndef set_a(x: Any, y: Any) -> None:\n    x.a = y\ndef call_m(x: Any) -> Any:\n    return x.m(1, [3])\n[file driver.py]\nfrom native import C, get_a, set_a, call_m\nclass D:\n    def m(self, x, a):\n        return self.a + x + a[0]\n\nc = C()\nc.a = 6\nd = D()\nd.a = 2\nassert get_a(c) == 6\nassert get_a(d) == 2\nassert call_m(c) == 10\nassert call_m(d) == 6\nset_a(c, 5)\nassert c.a == 5\nset_a(d, 4)\nassert d.a == 4\ntry:\n    get_a(object())\nexcept AttributeError:\n    pass\nelse:\n    assert False\ntry:\n    call_m(object())\nexcept AttributeError:\n    pass\nelse:\n    assert False\ntry:\n    set_a(object(), 5)\nexcept AttributeError:\n    pass\nelse:\n    assert False\n\n[case testFloat]\ndef assign_and_return_float_sum() -> float:\n    f1 = 1.0\n    f2 = 2.0\n    f3 = 3.0\n    return f1 * f2 + f3\n\ndef from_int(i: int) -> float:\n    return float(i)\n\ndef to_int(x: float) -> int:\n    return int(x)\n\ndef get_complex() -> complex:\n    return 5.2j + 3.5 + 1j\n\n[file driver.py]\nfrom native import assign_and_return_float_sum, from_int, to_int, get_complex\nsum = 0.0\nfor i in range(10):\n    sum += assign_and_return_float_sum()\nassert sum == 50.0\n\nassert str(from_int(10)) == '10.0'\nassert str(to_int(3.14)) == '3'\nassert str(to_int(3)) == '3'\nassert get_complex() == 3.5 + 6.2j\n\n[case testDel]\nfrom typing import List\nfrom testutil import assertRaises\n\ndef printDict(dict) -> None:\n    l = list(dict.keys()) # type: List[str]\n    l.sort()\n    for key in l:\n        print(key, dict[key])\n    print(\"#########\")\n\ndef delList() -> None:\n    l = [1, 2, 3]\n    print(tuple(l))\n    del l[1]\n    print(tuple(l))\n\ndef delDict() -> None:\n    d = {\"one\":1, \"two\":2}\n    printDict(d)\n    del d[\"one\"]\n    printDict(d)\n\ndef delListMultiple() -> None:\n    l = [1, 2, 3, 4, 5, 6, 7]\n    print(tuple(l))\n    del l[1], l[2], l[3]\n    print(tuple(l))\n\ndef delDictMultiple() -> None:\n    d = {\"one\":1, \"two\":2, \"three\":3, \"four\":4}\n    printDict(d)\n    del d[\"two\"], d[\"four\"]\n    printDict(d)\n\nclass Dummy():\n    __deletable__ = ('x', 'y')\n\n    def __init__(self, x: int, y: int) -> None:\n        self.x = x\n        self.y = y\n\ndef delAttribute() -> None:\n    dummy = Dummy(1, 2)\n    del dummy.x\n    with assertRaises(AttributeError):\n        dummy.x\n\ndef delAttributeMultiple() -> None:\n    dummy = Dummy(1, 2)\n    del dummy.x, dummy.y\n    with assertRaises(AttributeError):\n        dummy.x\n    with assertRaises(AttributeError):\n        dummy.y\n\ndef delLocal(b: bool) -> int:\n    dummy = 10\n    if b:\n        del dummy\n    return dummy\n\ndef delLocalLoop() -> None:\n    # Try deleting a local in a loop to make sure the control flow analysis works\n    dummy = 1\n    for i in range(10):\n        print(dummy)\n        dummy *= 2\n        if i == 4:\n            del dummy\n\nglobal_var = 10\ndel global_var\n\n[file driver.py]\nfrom native import (\n    delList, delDict, delListMultiple, delDictMultiple, delAttribute,\n    delAttributeMultiple, delLocal, delLocalLoop,\n)\nimport native\nfrom testutil import assertRaises\n\ndelList()\ndelDict()\ndelListMultiple()\ndelDictMultiple()\ndelAttribute()\ndelAttributeMultiple()\nwith assertRaises(AttributeError):\n    native.global_var\nwith assertRaises(UnboundLocalError, 'local variable \"dummy\" referenced before assignment'):\n    delLocal(True)\nassert delLocal(False) == 10\nwith assertRaises(UnboundLocalError, 'local variable \"dummy\" referenced before assignment'):\n    delLocalLoop()\n[out]\n(1, 2, 3)\n(1, 3)\none 1\ntwo 2\n#########\ntwo 2\n#########\n(1, 2, 3, 4, 5, 6, 7)\n(1, 3, 5, 7)\nfour 4\none 1\nthree 3\ntwo 2\n#########\none 1\nthree 3\n#########\n1\n2\n4\n8\n16\n"
  },
  {
    "path": "mypyc/test-data/run-python312.test",
    "content": "[case testPEP695Basics]\nfrom enum import Enum\nfrom typing import Any, Literal, TypeAliasType, cast\n\nfrom testutil import assertRaises\n\ndef id[T](x: T) -> T:\n    return x\n\ndef test_call_generic_function() -> None:\n    assert id(2) == 2\n    assert id('x') == 'x'\n\nclass C[T]:\n    x: T\n\n    def __init__(self, x: T) -> None:\n        self.x = x\n\nclass D[T, S]:\n    x: T\n    y: S\n\n    def __init__(self, x: T, y: S) -> None:\n        self.x = x\n        self.y = y\n\n    def set(self, x: object, y: object) -> None:\n        self.x = cast(T, x)\n        self.y = cast(S, y)\n\ndef test_generic_class() -> None:\n    c = C(5)\n    assert c.x == 5\n    c2 = C[str]('x')\n    assert c2.x == 'x'\n    d = D[str, int]('a', 5)\n    assert d.x == 'a'\n    assert d.y == 5\n    d.set('b', 6)\n    assert d.x == 'b'\n    assert d.y == 6\n\ndef test_generic_class_via_any() -> None:\n    c_any: Any = C\n    c = c_any(2)\n    assert c.x == 2\n    c2 = c_any[str]('y')\n    assert c2.x == 'y'\n    assert str(c_any[str]) == 'native.C[str]'\n\n    d_any: Any = D\n    d = d_any(1, 'x')\n    assert d.x == 1\n    assert d.y == 'x'\n    d2 = d_any[int, str](2, 'y')\n    assert d2.x == 2\n    assert d2.y == 'y'\n\n    with assertRaises(TypeError):\n        c_any[int, str]\n    with assertRaises(TypeError):\n        d_any[int]\n\nclass E[*Ts]: pass\n\ndef test_type_var_tuple() -> None:\n    e: E[int, str] = E()\n    e_any: Any = E\n    assert isinstance(e_any(), E)\n    assert isinstance(e_any[int](), E)\n    assert isinstance(e_any[int, str](), E)\n\nclass F[**P]: pass\n\ndef test_param_spec() -> None:\n    f: F[[int, str]] = F()\n    f_any: Any = F\n    assert isinstance(f_any(), F)\n    assert isinstance(f_any[[int, str]](), F)\n\nclass SubC[S](C[S]):\n    def __init__(self, x: S) -> None:\n       super().__init__(x)\n\ndef test_generic_subclass() -> None:\n    s = SubC(1)\n    assert s.x == 1\n    s2 = SubC[str]('y')\n    assert s2.x == 'y'\n    sub_any: Any = SubC\n    assert sub_any(1).x == 1\n    assert sub_any[str]('x').x == 'x'\n    assert isinstance(s, SubC)\n    assert isinstance(s, C)\n\nclass SubD[\n           T,  # Put everything on separate lines\n           S](\n              D[T,\n                S]): pass\n\ndef test_generic_subclass_two_params() -> None:\n    s = SubD(3, 'y')\n    assert s.x == 3\n    assert s.y == 'y'\n    s2 = SubD[str, int]('z', 4)\n    assert s2.x == 'z'\n    assert s2.y == 4\n    sub_any: Any = SubD\n    assert sub_any(3, 'y').y == 'y'\n    assert sub_any[int, str](3, 'y').y == 'y'\n    assert isinstance(s, SubD)\n    assert isinstance(s, D)\n\nclass SubE[*Ts](E[*Ts]): pass\n\ndef test_type_var_tuple_subclass() -> None:\n    sub_any: Any = SubE\n    assert isinstance(sub_any(), SubE)\n    assert isinstance(sub_any(), E)\n    assert isinstance(sub_any[int](), SubE)\n    assert isinstance(sub_any[int, str](), SubE)\n\n\nclass SubF[**P](F[P]): pass\n\ndef test_param_spec_subclass() -> None:\n    sub_any: Any = SubF\n    assert isinstance(sub_any(), SubF)\n    assert isinstance(sub_any(), F)\n    assert isinstance(sub_any[[int]](), SubF)\n    assert isinstance(sub_any[[int, str]](), SubF)\n\n# We test that upper bounds and restricted values can be used, but not that\n# they are introspectable\n\ndef bound[T: C](x: T) -> T:\n    return x\n\ndef test_function_with_upper_bound() -> None:\n    c = C(1)\n    assert bound(c) is c\n\ndef restriction[T: (int, str)](x: T) -> T:\n    return x\n\ndef test_function_with_value_restriction() -> None:\n    assert restriction(1) == 1\n    assert restriction('x') == 'x'\n\nclass Bound[T: C]:\n     def __init__(self, x: T) -> None:\n         self.x = x\n\ndef test_class_with_upper_bound() -> None:\n    c = C(1)\n    b = Bound(c)\n    assert b.x is c\n    b2 = Bound[C](c)\n    assert b2.x is c\n\nclass Restriction[T: (int, str)]:\n    def __init__(self, x: T) -> None:\n        self.x = x\n\ndef test_class_with_value_restriction() -> None:\n    r = Restriction(1)\n    assert r.x == 1\n    r2 = Restriction[str]('a')\n    assert r2.x == 'a'\n\ntype A = int\n\ndef test_simple_type_alias() -> None:\n    assert isinstance(A, TypeAliasType)\n    assert getattr(A, \"__value__\") is int\n    assert str(A) == \"A\"\n\ntype B = Fwd[int]\nFwd = list\n\ndef test_forward_reference_in_alias() -> None:\n    assert isinstance(B, TypeAliasType)\n    assert getattr(B, \"__value__\") == list[int]\n\ntype R = int | list[R]\n\ndef test_recursive_type_alias() -> None:\n    assert isinstance(R, TypeAliasType)\n    assert getattr(R, \"__value__\") == (int | list[R])\n\nclass SomeEnum(Enum):\n    AVALUE = \"a\"\n\ntype EnumLiteralAlias1 = Literal[SomeEnum.AVALUE]\ntype EnumLiteralAlias2 = Literal[SomeEnum.AVALUE] | None\nEnumLiteralAlias3 = Literal[SomeEnum.AVALUE] | None\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695GenericTypeAlias]\nfrom typing import Callable\nfrom types import GenericAlias\n\nfrom testutil import assertRaises\n\ntype A[T] = list[T]\n\ndef test_generic_alias() -> None:\n    assert type(A[str]) is GenericAlias\n    assert str(A[str]) == \"A[str]\"\n    assert str(getattr(A, \"__value__\")) == \"list[T]\"\n\ntype B[T, S] = dict[S, T]\n\ndef test_generic_alias_with_two_args() -> None:\n    assert str(B[str, int]) == \"B[str, int]\"\n    assert str(getattr(B, \"__value__\")) == \"dict[S, T]\"\n\ntype C[*Ts] = tuple[*Ts]\n\ndef test_type_var_tuple_type_alias() -> None:\n    assert str(C[int, str]) == \"C[int, str]\"\n    assert str(getattr(C, \"__value__\")) == \"tuple[typing.Unpack[Ts]]\"\n\ntype D[**P] = Callable[P, int]\n\ndef test_param_spec_type_alias() -> None:\n    assert str(D[[int, str]]) == \"D[[int, str]]\"\n    assert str(getattr(D, \"__value__\")) == \"typing.Callable[P, int]\"\n[typing fixtures/typing-full.pyi]\n"
  },
  {
    "path": "mypyc/test-data/run-python37.test",
    "content": "-- Test cases for Python 3.7 features\n\n[case testRunDataclass]\nimport dataclasses\nfrom dataclasses import dataclass, field\nfrom typing import Set, FrozenSet, List, Callable, Any\n\n@dataclass\nclass Person1:\n    age : int\n    name : str\n\n    def __bool__(self) -> bool:\n        return self.name == 'robot'\n\ndef testBool(p: Person1) -> bool:\n    if p:\n        return True\n    else:\n        return False\n\n@dataclass\nclass Person1b(Person1):\n    id: str = '000'\n\n@dataclass\nclass Person2:\n    age : int\n    name : str = field(default='robot')\n\n@dataclasses.dataclass\nclass Person2b:\n    age : int\n    name : str = dataclasses.field(default='robot')\n\n@dataclass(order = True)\nclass Person3:\n    age : int = field(default = 6)\n    friendIDs : List[int] = field(default_factory = list)\n\n    def get_age(self) -> int:\n        return (self.age)\n\n    def set_age(self, new_age : int) -> None:\n        self.age = new_age\n\n    def add_friendID(self, fid : int) -> None:\n        self.friendIDs.append(fid)\n\n    def get_friendIDs(self) -> List[int]:\n        return self.friendIDs\n\ndef get_next_age(g: Callable[[Any], int]) -> Callable[[Any], int]:\n    def f(a: Any) -> int:\n        return g(a) + 1\n    return f\n\n@dataclass\nclass Person4:\n    age : int\n    _name : str = 'Bot'\n\n    @get_next_age\n    def get_age(self) -> int:\n        return self.age\n\n    @property\n    def name(self) -> str:\n        return self._name\n\n@dataclass\nclass Person5:\n    weight: float\n    friends: Set[str] = field(default_factory=set)\n    parents: FrozenSet[str] = frozenset()\n\n[file other.py]\nfrom native import Person1, Person1b, Person2, Person3, Person4, Person5, testBool\ni1 = Person1(age = 5, name = 'robot')\nassert i1.age == 5\nassert i1.name == 'robot'\nassert testBool(i1) == True\nassert testBool(Person1(age = 5, name = 'robo')) == False\ni1b = Person1b(age = 5, name = 'robot')\nassert i1b.age == 5\nassert i1b.name == 'robot'\nassert testBool(i1b) == True\nassert testBool(Person1b(age = 5, name = 'robo')) == False\ni1c = Person1b(age = 20, name = 'robot', id = 'test')\nassert i1c.age == 20\nassert i1c.id == 'test'\n\ni2 = Person2(age = 5)\nassert i2.age == 5\nassert i2.name == 'robot'\ni3 = Person2(age = 5, name = 'new_robot')\nassert i3.age == 5\nassert i3.name == 'new_robot'\ni4 = Person3()\nassert i4.age == 6\nassert i4.friendIDs == []\ni5 = Person3(age = 5)\nassert i5.age == 5\nassert i5.friendIDs == []\ni6 = Person3(age = 5, friendIDs = [1,2,3])\nassert i6.age == 5\nassert i6.friendIDs == [1,2,3]\nassert i6.get_age() == 5\ni6.set_age(10)\nassert i6.get_age() == 10\ni6.add_friendID(4)\nassert i6.get_friendIDs() == [1,2,3,4]\ni7 = Person4(age = 5)\nassert i7.get_age() == 6\ni7.age += 3\nassert i7.age == 8\nassert i7.name == 'Bot'\ni8 = Person3(age = 1, friendIDs = [1,2])\ni9 = Person3(age = 1, friendIDs = [1,2])\nassert i8 == i9\ni8.age = 2\nassert i8 > i9\n\nassert Person1.__annotations__ == {'age': int, 'name': str}\nassert Person2.__annotations__ == {'age': int, 'name': str}\nassert Person5.__annotations__ == {'weight': float, 'friends': set,\n                                       'parents': frozenset}\n\n[file driver.py]\nimport sys\n\n# Dataclasses introduced in 3.7\nversion = sys.version_info[:2]\nif version[0] < 3 or version[1] < 7:\n    exit()\n\n# Run the tests in both interpreted and compiled mode\nimport other\nimport other_interpreted\n\n# Test for an exceptional cases\nfrom testutil import assertRaises\nfrom native import Person1, Person1b, Person3\nfrom types import BuiltinMethodType\n\nwith assertRaises(TypeError, \"missing 1 required positional argument\"):\n    Person1(0)\n\nwith assertRaises(TypeError, \"missing 2 required positional arguments\"):\n    Person1b()\n\nwith assertRaises(TypeError, \"int object expected; got str\"):\n    Person1('nope', 'test')\n\np = Person1(0, 'test')\nwith assertRaises(TypeError, \"int object expected; got str\"):\n    p.age = 'nope'\n\nassert isinstance(Person3().get_age, BuiltinMethodType)\n"
  },
  {
    "path": "mypyc/test-data/run-python38.test",
    "content": "-- Test cases for Python 3.8 features\n\n[case testWalrus1]\nfrom typing import Optional\n\ndef foo(x: int) -> Optional[int]:\n    if x < 0:\n        return None\n    return x\n\ndef test(x: int) -> str:\n    if (n := foo(x)) is not None:\n        return str(x)\n    else:\n        return \"<fail>\"\n\n[file driver.py]\nfrom native import test\n\nassert test(10) == \"10\"\nassert test(-1) == \"<fail>\"\n\n\n[case testWalrus2]\nfrom typing import Optional, Tuple, List\n\nclass Node:\n    def __init__(self, val: int, next: Optional['Node']) -> None:\n        self.val = val\n        self.next = next\n\ndef pairs(nobe: Optional[Node]) -> List[Tuple[int, int]]:\n    if nobe is None:\n        return []\n    l = []\n    while next := nobe.next:\n        l.append((nobe.val, next.val))\n        nobe = next\n    return l\n\ndef make(l: List[int]) -> Optional[Node]:\n    cur: Optional[Node] = None\n    for x in reversed(l):\n        cur = Node(x, cur)\n    return cur\n\n[file driver.py]\nfrom native import Node, make, pairs\n\nassert pairs(make([1,2,3])) == [(1,2), (2,3)]\nassert pairs(make([1])) == []\nassert pairs(make([])) == []\n\n[case testFStrings]\nfrom datetime import datetime\n\ndef test_fstring_equal_sign() -> None:\n    today = datetime(year=2017, month=1, day=27)\n    assert f\"{today=:%B %d, %Y}\" == 'today=January 27, 2017' # using date format specifier and debugging\n\n    foo = \"bar\"\n    assert f\"{ foo = }\" == \" foo = 'bar'\" # preserves whitespace\n\n    line = \"The mill's closed\"\n    assert f\"{line = }\" == 'line = \"The mill\\'s closed\"'\n    assert f\"{line = :20}\" == \"line = The mill's closed   \"\n    assert f\"{line = !r:20}\" == 'line = \"The mill\\'s closed\" '\n\n[case testMethodOverrideDefaultPosOnly1]\nclass Foo:\n    def f(self, x: int=20, /, *, z: int=10) -> None:\n        pass\n\nclass Bar(Foo):\n    def f(self, *args: int, **kwargs: int) -> None:\n        print(\"stuff\", args, kwargs)\n\ndef test_pos_only() -> None:\n    z: Foo = Bar()\n    z.f(1, z=50)\n    z.f()\n    z.f(1)\n    z.f(z=50)\n\n[out]\nstuff (1,) {'z': 50}\nstuff () {}\nstuff (1,) {}\nstuff () {'z': 50}\n"
  },
  {
    "path": "mypyc/test-data/run-sets.test",
    "content": "# Test cases for sets (compile and run)\n\n[case testSets]\nfrom typing import Set, List\ndef instantiateLiteral() -> Set[int]:\n    return {1, 2, 3, 5, 8}\n\ndef fromIterator() -> List[Set[int]]:\n    a = set([1, 3, 5])\n    b = set((1, 3, 5))\n    c = set({1: '1', 3: '3', 5: '5'})\n    d = set(x for x in range(1, 6, 2))\n    e = set((x for x in range(1, 6, 2)))\n    return [a, b, c, d, e]\n\ndef fromIterator2() -> Set[int]:\n    tmp_list = [1, 2, 3, 4, 5]\n    return set((x + 1) for x in ((y * 10) for y in (z for z in tmp_list if z < 4)))\n\ndef addIncrementing(s : Set[int]) -> None:\n    for a in [1, 2, 3]:\n        if a not in s:\n            s.add(a)\n            return\n\ndef replaceWith1(s : Set[int]) -> None:\n    s.clear()\n    s.add(1)\n\ndef remove1(s : Set[int]) -> None:\n    s.remove(1)\n\ndef discard1(s: Set[int]) -> None:\n    s.discard(1)\n\ndef pop(s : Set[int]) -> int:\n    return s.pop()\n\ndef update(s: Set[int], x: List[int]) -> None:\n    s.update(x)\n\n[file driver.py]\nfrom native import instantiateLiteral\nfrom testutil import assertRaises\n\nval = instantiateLiteral()\nassert 1 in val\nassert 2 in val\nassert 3 in val\nassert 5 in val\nassert 8 in val\nassert len(val) == 5\nassert val == {1, 2, 3, 5, 8}\ns = 0\nfor i in val:\n    s += i\nassert s == 19\n\nfrom native import fromIterator\nsets = fromIterator()\nfor s in sets:\n    assert s == {1, 3, 5}\n\nfrom native import fromIterator2\ns = fromIterator2()\nassert s == {11, 21, 31}\n\nfrom native import addIncrementing\ns = set()\naddIncrementing(s)\nassert s == {1}\naddIncrementing(s)\nassert s == {1, 2}\naddIncrementing(s)\nassert s == {1, 2, 3}\n\nfrom native import replaceWith1\ns = {3, 7, 12}\nreplaceWith1(s)\nassert s == {1}\n\nfrom native import remove1\nimport traceback\ns = {1, 4, 6}\nremove1(s)\nassert s == {4, 6}\nwith assertRaises(KeyError, '1'):\n    remove1(s)\n\nfrom native import discard1\ns = {1, 4, 6}\ndiscard1(s)\nassert s == {4, 6}\ndiscard1(s)\nassert s == {4, 6}\n\nfrom native import pop\ns = {1, 2, 3}\nx = pop(s)\nassert len(s) == 2\nassert x in [1, 2, 3]\ny = pop(s)\nassert len(s) == 1\nassert y in [1, 2, 3]\nassert x != y\nz = pop(s)\nassert len(s) == 0\nassert z in [1, 2, 3]\nassert x != z\nassert y != z\nwith assertRaises(KeyError, 'pop from an empty set'):\n    pop(s)\n\nfrom native import update\ns = {1, 2, 3}\nupdate(s, [5, 4, 3])\nassert s == {1, 2, 3, 4, 5}\n\n[case testFrozenSets]\nfrom typing import FrozenSet, List, Any, cast\nfrom testutil import assertRaises\n\ndef instantiateLiteral() -> FrozenSet[int]:\n    return frozenset((1, 2, 3, 5, 8))\n\ndef emptyFrozenSet1() -> FrozenSet[int]:\n    return frozenset()\n\ndef emptyFrozenSet2() -> FrozenSet[int]:\n    return frozenset(())\n\ndef fromIterator() -> List[FrozenSet[int]]:\n    a = frozenset([1, 3, 5])\n    b = frozenset((1, 3, 5))\n    c = frozenset({1, 3, 5})\n    d = frozenset({1: '1', 3: '3', 5: '5'})\n    e = frozenset(x for x in range(1, 6, 2))\n    f = frozenset((x for x in range(1, 6, 2)))\n    return [a, b, c, d, e, f]\n\ndef fromIterator2() -> FrozenSet[int]:\n    tmp_list = [1, 2, 3, 4, 5]\n    return frozenset((x + 1) for x in ((y * 10) for y in (z for z in tmp_list if z < 4)))\n\ndef castFrozenSet() -> FrozenSet[int]:\n    x: Any = frozenset((1, 2, 3, 5, 8))\n    return cast(FrozenSet, x)\n\ndef castFrozenSetError() -> FrozenSet[int]:\n    x: Any = {1, 2, 3, 5, 8}\n    return cast(FrozenSet, x)\n\ndef test_frozen_sets() -> None:\n    val = instantiateLiteral()\n    assert 1 in val\n    assert 2 in val\n    assert 3 in val\n    assert 5 in val\n    assert 8 in val\n    assert len(val) == 5\n    assert val == {1, 2, 3, 5, 8}\n    s = 0\n    for i in val:\n        s += i\n    assert s == 19\n\n    empty_set1 = emptyFrozenSet1()\n    assert empty_set1 == frozenset()\n\n    empty_set2 = emptyFrozenSet2()\n    assert empty_set2 == frozenset()\n\n    sets = fromIterator()\n    for s2 in sets:\n        assert s2 == {1, 3, 5}\n\n    s3 = fromIterator2()\n    assert s3 == {11, 21, 31}\n\n    val2 = castFrozenSet()\n    assert val2 == {1, 2, 3, 5, 8}\n\n    with assertRaises(TypeError, \"frozenset object expected; got set\"):\n        castFrozenSetError()\n\n[case testFrozenSetsFromIterables]\nfrom typing import FrozenSet\n\ndef f(x: int) -> int:\n    return x\n\ndef f1() -> FrozenSet[int]:\n    tmp_list = [1, 3, 5]\n    return frozenset(f(x) for x in tmp_list)\n\ndef f2() -> FrozenSet[int]:\n    tmp_tuple = (1, 3, 5)\n    return frozenset(f(x) for x in tmp_tuple)\n\ndef f3() -> FrozenSet[int]:\n    tmp_set = {1, 3, 5}\n    return frozenset(f(x) for x in tmp_set)\n\ndef f4() -> FrozenSet[int]:\n    tmp_dict = {1: '1', 3: '3', 5: '5'}\n    return frozenset(f(x) for x in tmp_dict)\n\ndef f5() -> FrozenSet[int]:\n    return frozenset(f(x) for x in range(1, 6, 2))\n\ndef f6() -> FrozenSet[int]:\n    return frozenset((f(x) for x in range(1, 6, 2)))\n\ndef g1(x: int) -> int:\n    return x\n\ndef g2(x: int) -> int:\n    return x * 10\n\ndef g3(x: int) -> int:\n    return x + 1\n\ndef g4() -> FrozenSet[int]:\n    tmp_list = [1, 2, 3, 4, 5]\n    return frozenset(g3(x) for x in (g2(y) for y in (g1(z) for z in tmp_list if z < 4)))\n\ndef test_frozen_sets_from_iterables() -> None:\n    val = frozenset({1, 3, 5})\n    assert f1() == val\n    assert f2() == val\n    assert f3() == val\n    assert f4() == val\n    assert f5() == val\n    assert f6() == val\n    assert g4() == frozenset({11, 21, 31})\n\n[case testPrecomputedFrozenSets]\nfrom typing import Final, Any\n\nCONST: Final = \"CONST\"\nnon_const = \"non_const\"\n\ndef main_set(item: Any) -> bool:\n    return item in {None, False, 1, 2.0, \"3\", b\"4\", 5j, (6,), ((7,),), (), CONST}\n\ndef main_negated_set(item: Any) -> bool:\n    return item not in {None, False, 1, 2.0, \"3\", b\"4\", 5j, (6,), ((7,),), (), CONST}\n\ndef non_final_name_set(item: Any) -> bool:\n    return item in {non_const}\n\ns = set()\nfor i in {None, False, 1, 2.0, \"3\", b\"4\", 5j, (6,), CONST}:\n    s.add(i)\n\ndef test_in_set() -> None:\n    for item in (None, False, 1, 2.0, \"3\", b\"4\", 5j, (6,), ((7,),), (), CONST):\n        assert main_set(item), f\"{item!r} should be in set_main\"\n        assert not main_negated_set(item), item\n\n    global non_const\n    assert non_final_name_set(non_const)\n    non_const = \"updated\"\n    assert non_final_name_set(\"updated\")\n\ndef test_for_set() -> None:\n    assert not s ^ {None, False, 1, 2.0, \"3\", b\"4\", 5j, (6,), CONST}, s\n\n[case testIsInstance]\nfrom copysubclass import subset, subfrozenset\ndef test_built_in_set() -> None:\n    assert isinstance(set(), set)\n    assert isinstance({'one', 'two'}, set)\n    assert isinstance({'a', 1}, set)\n    assert isinstance(subset(), set)\n    assert isinstance(subset({'one', 'two'}), set)\n    assert isinstance(subset({'a', 1}), set)\n\n    assert not isinstance(frozenset(), set)\n    assert not isinstance({}, set)\n    assert not isinstance([], set)\n    assert not isinstance((1,2,3), set)\n    assert not isinstance({1:'a', 2:'b'}, set)\n    assert not isinstance(int() + 1, set)\n    assert not isinstance(str() + 'a', set)\n\ndef test_user_defined_set() -> None:\n    from userdefinedset import set\n\n    assert isinstance(set(), set)\n    assert not isinstance({set()}, set)\n\ndef test_built_in_frozenset() -> None:\n    assert isinstance(frozenset(), frozenset)\n    assert isinstance(frozenset({'one', 'two'}), frozenset)\n    assert isinstance(frozenset({'a', 1}), frozenset)\n    assert isinstance(subfrozenset(), frozenset)\n    assert isinstance(subfrozenset({'one', 'two'}), frozenset)\n    assert isinstance(subfrozenset({'a', 1}), frozenset)\n\n    assert not isinstance(set(), frozenset)\n    assert not isinstance({}, frozenset)\n    assert not isinstance([], frozenset)\n    assert not isinstance((1,2,3), frozenset)\n    assert not isinstance({1:'a', 2:'b'}, frozenset)\n    assert not isinstance(int() + 1, frozenset)\n    assert not isinstance(str() + 'a', frozenset)\n\n[file copysubclass.py]\nfrom typing import Any\nclass subset(set[Any]):\n    pass\n\nclass subfrozenset(frozenset[Any]):\n    pass\n\n[file userdefinedset.py]\nclass set:\n    pass\n"
  },
  {
    "path": "mypyc/test-data/run-signatures.test",
    "content": "[case testSignaturesBasic]\ndef f1(): pass\ndef f2(x): pass\ndef f3(x, /): pass\ndef f4(*, x): pass\ndef f5(*x): pass\ndef f6(**x): pass\ndef f7(x=None): pass\ndef f8(x=None, /): pass\ndef f9(*, x=None): pass\ndef f10(a, /, b, c=None, *args, d=None, **h): pass\n\n[file driver.py]\nimport inspect\nfrom native import *\n\nassert str(inspect.signature(f1)) == \"()\"\nassert str(inspect.signature(f2)) == \"(x)\"\nassert str(inspect.signature(f3)) == \"(x, /)\"\nassert str(inspect.signature(f4)) == \"(*, x)\"\nassert str(inspect.signature(f5)) == \"(*x)\"\nassert str(inspect.signature(f6)) == \"(**x)\"\nassert str(inspect.signature(f7)) == \"(x=None)\"\nassert str(inspect.signature(f8)) == \"(x=None, /)\"\nassert str(inspect.signature(f9)) == \"(*, x=None)\"\nassert str(inspect.signature(f10)) == \"(a, /, b, c=None, *args, d=None, **h)\"\n\nfor fn in [f1, f2, f3, f4, f5, f6, f7, f8, f9, f10]:\n    assert getattr(fn, \"__doc__\") is None\n\n[case testSignaturesValidDefaults]\nfrom typing import Final\nA: Final = 1\n\ndef default_int(x=1): pass\ndef default_str(x=\"a\"): pass\ndef default_float(x=1.0): pass\ndef default_true(x=True): pass\ndef default_false(x=False): pass\ndef default_none(x=None): pass\ndef default_tuple_empty(x=()): pass\ndef default_tuple_literals(x=(1, \"a\", 1.0, False, True, None, (), (1,2,(3,4)))): pass\ndef default_tuple_singleton(x=(1,)): pass\ndef default_named_constant(x=A): pass\n\n[file driver.py]\nimport inspect\nfrom native import *\n\nassert str(inspect.signature(default_int)) == \"(x=1)\"\nassert str(inspect.signature(default_str)) == \"(x='a')\"\nassert str(inspect.signature(default_float)) == \"(x=1.0)\"\nassert str(inspect.signature(default_true)) == \"(x=True)\"\nassert str(inspect.signature(default_false)) == \"(x=False)\"\nassert str(inspect.signature(default_none)) == \"(x=None)\"\nassert str(inspect.signature(default_tuple_empty)) == \"(x=())\"\nassert str(inspect.signature(default_tuple_literals)) == \"(x=(1, 'a', 1.0, False, True, None, (), (1, 2, (3, 4))))\"\nassert str(inspect.signature(default_named_constant)) == \"(x=1)\"\n\n# Check __text_signature__ directly since inspect.signature produces\n# an incorrect signature for 1-tuple default arguments prior to\n# Python 3.12 (cpython#102379).\n# assert str(inspect.signature(default_tuple_singleton)) == \"(x=(1,))\"\nassert getattr(default_tuple_singleton, \"__text_signature__\") == \"(x=(1,))\"\n\n[case testSignaturesStringDefaults]\ndef f1(x=\"'foo\"): pass\ndef f2(x='\"foo'): pass\ndef f3(x=\"\"\"\"Isn\\'t,\" they said.\"\"\"): pass\ndef f4(x=\"\\\\ \\a \\b \\f \\n \\r \\t \\v \\x00\"): pass\ndef f5(x=\"\\N{BANANA}sv\"): pass\n\n[file driver.py]\nimport inspect\nfrom native import *\n\nassert str(inspect.signature(f1)) == \"\"\"(x=\"'foo\")\"\"\"\nassert str(inspect.signature(f2)) == \"\"\"(x='\"foo')\"\"\"\nassert str(inspect.signature(f3)) == r\"\"\"(x='\"Isn\\'t,\" they said.')\"\"\"\nassert str(inspect.signature(f4)) == r\"\"\"(x='\\\\ \\x07 \\x08 \\x0c \\n \\r \\t \\x0b \\x00')\"\"\"\nassert str(inspect.signature(f5)) == \"\"\"(x='\\N{BANANA}sv')\"\"\"\n\n[case testSignaturesIrrepresentableDefaults]\nimport enum\nclass Color(enum.Enum):\n    RED = 1\nmisc = object()\n\n# Default arguments that cannot be represented in a __text_signature__\ndef bad_object(x=misc): pass\ndef bad_list_nonliteral(x=[misc]): pass\ndef bad_dict_nonliteral(x={'a': misc}): pass\ndef bad_set_nonliteral(x={misc}): pass\ndef bad_set_empty(x=set()): pass  # supported by ast.literal_eval, but not by inspect._signature_fromstr\ndef bad_nan(x=float(\"nan\")): pass\ndef bad_enum(x=Color.RED): pass\n\n# TODO: Default arguments that could potentially be represented in a\n# __text_signature__, but which are not currently supported.\n# See 'inspect._signature_fromstr' for what default values are supported at runtime.\ndef bad_complex(x=1+2j): pass\ndef bad_list_empty(x=[]): pass\ndef bad_list_literals(x=[1, 2, 3]): pass\ndef bad_dict_empty(x={}): pass\ndef bad_dict_literals(x={'a': 1}): pass\ndef bad_set_literals(x={1, 2, 3}): pass\ndef bad_tuple_literals(x=([1, 2, 3], {'a': 1}, {1, 2, 3})): pass\ndef bad_ellipsis(x=...): pass\ndef bad_literal_fold(x=1+2): pass\n\n[file driver.py]\nimport inspect\nfrom testutil import assertRaises\nimport native\n\nall_bad = [fn for name, fn in vars(native).items() if name.startswith(\"bad_\")]\nassert all_bad\n\nfor bad in all_bad:\n    assert bad.__text_signature__ is None, f\"{bad.__name__} has unexpected __text_signature__\"\n    with assertRaises(ValueError, \"no signature found for builtin\"):\n        inspect.signature(bad)\n\n[case testSignaturesMethods]\nclass Foo:\n    def f1(self, x): pass\n    @classmethod\n    def f2(cls, x): pass\n    @staticmethod\n    def f3(x): pass\n    def __eq__(self, x: object): pass\n\n[file driver.py]\nimport inspect\nfrom native import *\n\nassert str(inspect.signature(Foo.f1)) == \"(self, /, x)\"\nassert str(inspect.signature(Foo().f1)) == \"(x)\"\n\nassert str(inspect.signature(Foo.f2)) == \"(x)\"\nassert str(inspect.signature(Foo().f2)) == \"(x)\"\n\nassert str(inspect.signature(Foo.f3)) == \"(x)\"\nassert str(inspect.signature(Foo().f3)) == \"(x)\"\n\nassert str(inspect.signature(Foo.__eq__)) == \"(self, value, /)\"\nassert str(inspect.signature(Foo().__eq__)) == \"(value, /)\"\n\n[case testSignaturesConstructors]\nclass Empty: pass\n\nclass HasInit:\n    def __init__(self, x) -> None: pass\n\nclass InheritedInit(HasInit): pass\n\nclass HasInitBad:\n    def __init__(self, x=[]) -> None: pass\n\n[file driver.py]\nimport inspect\nfrom testutil import assertRaises\nfrom native import *\n\nassert str(inspect.signature(Empty)) == \"()\"\nassert str(inspect.signature(Empty.__init__)) == \"(self, /, *args, **kwargs)\"\n\nassert str(inspect.signature(HasInit)) == \"(x)\"\nassert str(inspect.signature(HasInit.__init__)) == \"(self, /, *args, **kwargs)\"\n\nassert str(inspect.signature(InheritedInit)) == \"(x)\"\nassert str(inspect.signature(InheritedInit.__init__)) == \"(self, /, *args, **kwargs)\"\n\nassert getattr(HasInitBad, \"__text_signature__\") is None\nwith assertRaises(ValueError, \"no signature found for builtin\"):\n    inspect.signature(HasInitBad)\n\n# CPython detail note: type objects whose tp_doc contains only a text signature behave\n# differently from method objects whose ml_doc contains only a test signature: type\n# objects will have __doc__=\"\" whereas method objects will have __doc__=None. This\n# difference stems from the former using _PyType_GetDocFromInternalDoc(...) and the\n# latter using PyUnicode_FromString(_PyType_DocWithoutSignature(...)).\nfor cls in [Empty, HasInit, InheritedInit]:\n    assert getattr(cls, \"__doc__\") == \"\"\nassert getattr(HasInitBad, \"__doc__\") is None\n\n[case testSignaturesConstructorsNonExt]\nfrom mypy_extensions import mypyc_attr\n\n@mypyc_attr(native_class=False)\nclass NonExt:\n    def __init__(self, x) -> None: pass\n\n[file driver.py]\nimport inspect\nfrom testutil import assertRaises\nfrom native import *\n\n# TODO: support constructor signatures for non-extension classes\nwith assertRaises(ValueError, \"no signature found for builtin\"):\n    inspect.signature(NonExt)\n\n[case testSignaturesHistoricalPositionalOnly]\nimport inspect\n\ndef f1(__x): pass\ndef f2(__x, y): pass\ndef f3(*, __y): pass\ndef f4(x, *, __y): pass\ndef f5(__x, *, __y): pass\n\nclass A:\n    def func(self, __x): pass\n\ndef test_historical_positional_only() -> None:\n    assert str(inspect.signature(f1)) == \"(__x, /)\"\n    assert str(inspect.signature(f2)) == \"(__x, /, y)\"\n    assert str(inspect.signature(f3)) == \"(*, __y)\"\n    assert str(inspect.signature(f4)) == \"(x, *, __y)\"\n    assert str(inspect.signature(f5)) == \"(__x, /, *, __y)\"\n\n    assert str(inspect.signature(A.func)) == \"(self, __x, /)\"\n    assert str(inspect.signature(A().func)) == \"(__x, /)\"\n"
  },
  {
    "path": "mypyc/test-data/run-singledispatch.test",
    "content": "# Test cases related to the functools.singledispatch decorator\n# Most of these tests are marked as xfails because mypyc doesn't support singledispatch yet\n# (These tests will be re-enabled when mypyc supports singledispatch)\n\n[case testSpecializedImplementationUsed]\nfrom functools import singledispatch\nfrom typing import Any\n\n@singledispatch\ndef fun(arg: Any) -> bool:\n    return False\n\n@fun.register\ndef fun_specialized(arg: str) -> bool:\n    return True\n\ndef test_specialize() -> None:\n    assert fun('a')\n    assert not fun(3)\n\n[case testSubclassesOfExpectedTypeUseSpecialized]\nfrom functools import singledispatch\nfrom typing import Any\n\nclass A: pass\nclass B(A): pass\n\n@singledispatch\ndef fun(arg: Any) -> bool:\n    return False\n\n@fun.register\ndef fun_specialized(arg: A) -> bool:\n    return True\n\ndef test_specialize() -> None:\n    assert fun(B())\n    assert fun(A())\n\n[case testSuperclassImplementationNotUsedWhenSubclassHasImplementation]\nfrom functools import singledispatch\nfrom typing import Any\n\nclass A: pass\nclass B(A): pass\n\n@singledispatch\ndef fun(arg: Any) -> bool:\n    # shouldn't be using this\n    assert False\n\n@fun.register\ndef fun_specialized(arg: A) -> bool:\n    return False\n\n@fun.register\ndef fun_specialized2(arg: B) -> bool:\n    return True\n\ndef test_specialize() -> None:\n    assert fun(B())\n    assert not fun(A())\n\n[case testMultipleUnderscoreFunctionsIsntError]\nfrom functools import singledispatch\nfrom typing import Any\n\n@singledispatch\ndef fun(arg: Any) -> str:\n    return 'default'\n\n@fun.register\ndef _(arg: str) -> str:\n    return 'str'\n\n@fun.register\ndef _(arg: int) -> str:\n    return 'int'\n\n# extra function to make sure all 3 underscore functions aren't treated as one OverloadedFuncDef\ndef a(b: Any) -> Any: pass\n\n@fun.register\ndef _(arg: list) -> str:\n    return 'list'\n\ndef test_singledispatch() -> None:\n    assert fun(0) == 'int'\n    assert fun('a') == 'str'\n    assert fun([1, 2]) == 'list'\n    assert fun({'a': 'b'}) == 'default'\n\n[case testCanRegisterCompiledClasses]\nfrom functools import singledispatch\nfrom typing import Any\n\nclass A: pass\n\n@singledispatch\ndef fun(arg: Any) -> bool:\n    return False\n@fun.register\ndef fun_specialized(arg: A) -> bool:\n    return True\n\ndef test_singledispatch() -> None:\n    assert fun(A())\n    assert not fun(1)\n\n[case testTypeUsedAsArgumentToRegister]\nfrom functools import singledispatch\nfrom typing import Any\n\n@singledispatch\ndef fun(arg: Any) -> bool:\n    return False\n\n@fun.register(int)\ndef fun_specialized(arg: Any) -> bool:\n    return True\n\ndef test_singledispatch() -> None:\n    assert fun(1)\n    assert not fun('a')\n\n[case testUseRegisterAsAFunction]\nfrom functools import singledispatch\nfrom typing import Any\n\n@singledispatch\ndef fun(arg: Any) -> bool:\n    return False\n\ndef fun_specialized_impl(arg: Any) -> bool:\n    return True\n\nfun.register(int, fun_specialized_impl)\n\ndef test_singledispatch() -> None:\n    assert fun(0)\n    assert not fun('a')\n\n[case testRegisterDoesntChangeFunction]\nfrom functools import singledispatch\nfrom typing import Any\n\n@singledispatch\ndef fun(arg: Any) -> bool:\n    return False\n\n@fun.register(int)\ndef fun_specialized(arg: Any) -> bool:\n    return True\n\ndef test_singledispatch() -> None:\n    assert fun_specialized('a')\n\n# TODO: turn this into a mypy error\n[case testNoneIsntATypeWhenUsedAsArgumentToRegister]\nfrom functools import singledispatch\nfrom typing import Any\n\n@singledispatch\ndef fun(arg: Any) -> bool:\n    return False\n\ndef test_argument() -> None:\n    try:\n        @fun.register\n        def fun_specialized(arg: None) -> bool:\n            return True\n        assert False, \"expected to raise an exception\"\n    except TypeError:\n        pass\n\n[case testRegisteringTheSameFunctionSeveralTimes]\nfrom functools import singledispatch\nfrom typing import Any\n\n@singledispatch\ndef fun(arg: Any) -> bool:\n    return False\n\n@fun.register(int)\n@fun.register(str)\ndef fun_specialized(arg: Any) -> bool:\n    return True\n\ndef test_singledispatch() -> None:\n    assert fun(0)\n    assert fun('a')\n    assert not fun([1, 2])\n\n[case testTypeIsAnABC]\n# mypy: allow-untyped-defs\nfrom functools import singledispatch\nfrom collections.abc import Mapping\n\n@singledispatch\ndef fun(arg) -> bool:\n    # TODO: Adding an Any parameter annotation breaks the test case\n    return False\n\n@fun.register\ndef fun_specialized(arg: Mapping) -> bool:\n    return True\n\ndef test_singledispatch() -> None:\n    assert not fun(1)\n    assert fun({'a': 'b'})\n\n[case testSingleDispatchMethod-xfail]\nfrom functools import singledispatchmethod\nclass A:\n    @singledispatchmethod\n    def fun(self, arg) -> str:\n        return 'default'\n\n    @fun.register\n    def fun_int(self, arg: int) -> str:\n        return 'int'\n\n    @fun.register\n    def fun_str(self, arg: str) -> str:\n        return 'str'\n\ndef test_singledispatchmethod() -> None:\n    x = A()\n    assert x.fun(5) == 'int'\n    assert x.fun('a') == 'str'\n    assert x.fun([1, 2]) == 'default'\n\n[case testSingleDispatchMethodWithOtherDecorator-xfail]\nfrom functools import singledispatchmethod\nclass A:\n    @singledispatchmethod\n    @staticmethod\n    def fun(arg) -> str:\n        return 'default'\n\n    @fun.register\n    @staticmethod\n    def fun_int(arg: int) -> str:\n        return 'int'\n\n    @fun.register\n    @staticmethod\n    def fun_str(arg: str) -> str:\n        return 'str'\n\ndef test_singledispatchmethod() -> None:\n    x = A()\n    assert x.fun(5) == 'int'\n    assert x.fun('a') == 'str'\n    assert x.fun([1, 2]) == 'default'\n\n[case testSingledispatchTreeSumAndEqual]\nfrom functools import singledispatch\nfrom typing import cast\n\nclass Tree:\n    pass\nclass Leaf(Tree):\n    pass\nclass Node(Tree):\n    def __init__(self, value: int, left: Tree, right: Tree) -> None:\n        self.value = value\n        self.left = left\n        self.right = right\n\n@singledispatch\ndef calc_sum(x: Tree) -> int:\n    raise TypeError('invalid type for x')\n\n@calc_sum.register\ndef _(x: Leaf) -> int:\n    return 0\n\n@calc_sum.register\ndef _(x: Node) -> int:\n    return x.value + calc_sum(x.left) + calc_sum(x.right)\n\n@singledispatch\ndef equal(to_compare: Tree, known: Tree) -> bool:\n    raise TypeError('invalid type for x')\n\n@equal.register\ndef _(to_compare: Leaf, known: Tree) -> bool:\n    return isinstance(known, Leaf)\n\n@equal.register\ndef _(to_compare: Node, known: Tree) -> bool:\n    if isinstance(known, Node):\n        if to_compare.value != known.value:\n            return False\n        else:\n            return equal(to_compare.left, known.left) and equal(to_compare.right, known.right)\n    return False\n\ndef build(n: int) -> Tree:\n    if n == 0:\n        return Leaf()\n    return Node(n, build(n - 1), build(n - 1))\n\ndef test_sum_and_equal() -> None:\n    tree = build(5)\n    tree2 = build(5)\n    cast(Node, cast(Node, cast(Node, cast(Node, tree2).right).right).right).value = 10\n    assert calc_sum(tree) == 57\n    assert calc_sum(tree2) == 65\n    assert equal(tree, tree)\n    assert not equal(tree, tree2)\n    tree3 = build(4)\n    assert not equal(tree, tree3)\n\n[case testSimulateMypySingledispatch]\nfrom functools import singledispatch\nfrom mypy_extensions import trait\nfrom typing import Iterator, Union, TypeVar, Any, List, Type\n# based on use of singledispatch in stubtest.py\nclass Error:\n    def __init__(self, msg: str) -> None:\n        self.msg = msg\n\n@trait\nclass Node: pass\n\nclass MypyFile(Node): pass\nclass TypeInfo(Node): pass\n\n\n@trait\nclass SymbolNode(Node): pass\n@trait\nclass Expression(Node): pass\nclass TypeVarLikeExpr(SymbolNode, Expression): pass\nclass TypeVarExpr(TypeVarLikeExpr): pass\nclass TypeAlias(SymbolNode): pass\n\nclass Missing: pass\nMISSING = Missing()\n\nT = TypeVar(\"T\")\n\nMaybeMissing = Union[T, Missing]\n\n@singledispatch\ndef verify(stub: Node, a: MaybeMissing[Any], b: List[str]) -> Iterator[Error]:\n    yield Error('unknown node type')\n\n@verify.register(MypyFile)\ndef verify_mypyfile(stub: MypyFile, a: MaybeMissing[int], b: List[str]) -> Iterator[Error]:\n    if isinstance(a, Missing):\n        yield Error(\"shouldn't be missing\")\n        return\n    if not isinstance(a, int):\n        # this check should be unnecessary because of the type signature and the previous check,\n        # but stubtest.py has this check\n        yield Error(\"should be an int\")\n        return\n    yield from verify(TypeInfo(), str, ['abc', 'def'])\n\n@verify.register(TypeInfo)\ndef verify_typeinfo(stub: TypeInfo, a: MaybeMissing[Type[Any]], b: List[str]) -> Iterator[Error]:\n    yield Error('in TypeInfo')\n    yield Error('hello')\n\n@verify.register(TypeVarExpr)\ndef verify_typevarexpr(stub: TypeVarExpr, a: MaybeMissing[Any], b: List[str]) -> Iterator[Error]:\n    if False:\n        yield None\n\ndef verify_list(stub: Any, a: Any, b: Any) -> List[str]:\n    \"\"\"Helper function that converts iterator of errors to list of messages\"\"\"\n    return list(err.msg for err in verify(stub, a, b))\n\ndef test_verify() -> None:\n    assert verify_list(TypeAlias(), 'a', ['a', 'b']) == ['unknown node type']\n    assert verify_list(MypyFile(), MISSING, ['a', 'b']) == [\"shouldn't be missing\"]\n    assert verify_list(MypyFile(), 5, ['a', 'b']) == ['in TypeInfo', 'hello']\n    assert verify_list(TypeInfo(), str, ['a', 'b']) == ['in TypeInfo', 'hello']\n    assert verify_list(TypeVarExpr(), 'a', ['x', 'y']) == []\n\n\n[case testArgsInRegisteredImplNamedDifferentlyFromMainFunction]\nfrom functools import singledispatch\nfrom typing import Any\n\n@singledispatch\ndef f(a: Any) -> bool:\n    return False\n\n@f.register\ndef g(b: int) -> bool:\n    return True\n\ndef test_singledispatch() -> None:\n    assert f(5)\n    assert not f('a')\n\n[case testKeywordArguments]\nfrom functools import singledispatch\nfrom typing import Any\n\n@singledispatch\ndef f(arg: Any, *, kwarg: int = 0) -> int:\n    return kwarg + 10\n\n@f.register\ndef g(arg: int, *, kwarg: int = 5) -> int:\n    return kwarg - 10\n\ndef test_keywords() -> None:\n    assert f('a') == 10\n    assert f('a', kwarg=3) == 13\n    assert f('a', kwarg=7) == 17\n\n    assert f(1) == -5\n    assert f(1, kwarg=4) == -6\n    assert f(1, kwarg=6) == -4\n\n[case testGeneratorAndMultipleTypesOfIterable]\nfrom functools import singledispatch\nfrom typing import *\n\n@singledispatch\ndef f(arg: Any) -> Iterable[int]:\n    yield 1\n\n@f.register\ndef g(arg: str) -> Iterable[int]:\n    return [0]\n\ndef test_iterables() -> None:\n    assert f(1) != [1]\n    assert list(f(1)) == [1]\n    assert f('a') == [0]\n\n[case testRegisterUsedAtSameTimeAsOtherDecorators]\nfrom functools import singledispatch\nfrom typing import TypeVar, Any\n\nclass A: pass\nclass B: pass\n\nT = TypeVar('T')\n\ndef decorator(f: T) -> T:\n    return f\n\n@singledispatch\ndef f(arg: Any) -> int:\n    return 0\n\n@f.register\n@decorator\ndef h(arg: str) -> int:\n    return 2\n\ndef test_singledispatch() -> None:\n    assert f(1) == 0\n    assert f('a') == 2\n\n[case testDecoratorModifiesFunction]\nfrom functools import singledispatch\nfrom typing import Callable, Any\n\nclass A: pass\n\ndef decorator(f: Callable[[Any], int]) -> Callable[[Any], int]:\n    def wrapper(x: Any) -> int:\n        return f(x) * 7\n    return wrapper\n\n@singledispatch\ndef f(arg: Any) -> int:\n    return 10\n\n@f.register\n@decorator\ndef h(arg: str) -> int:\n    return 5\n\n\ndef test_singledispatch() -> None:\n    assert f('a') == 35\n    assert f(A()) == 10\n\n[case testMoreSpecificTypeBeforeLessSpecificType]\nfrom functools import singledispatch\nfrom typing import Any\n\nclass A: pass\nclass B(A): pass\n\n@singledispatch\ndef f(arg: Any) -> str:\n    return 'default'\n\n@f.register\ndef g(arg: B) -> str:\n    return 'b'\n\n@f.register\ndef h(arg: A) -> str:\n    return 'a'\n\ndef test_singledispatch() -> None:\n    assert f(B()) == 'b'\n    assert f(A()) == 'a'\n    assert f(5) == 'default'\n\n[case testMultipleRelatedClassesBeingRegistered]\nfrom functools import singledispatch\nfrom typing import Any\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\n@singledispatch\ndef f(arg: Any) -> str: return 'default'\n\n@f.register\ndef _(arg: A) -> str: return 'a'\n\n@f.register\ndef _(arg: C) -> str: return 'c'\n\n@f.register\ndef _(arg: B) -> str: return 'b'\n\ndef test_singledispatch() -> None:\n    assert f(A()) == 'a'\n    assert f(B()) == 'b'\n    assert f(C()) == 'c'\n    assert f(1) == 'default'\n\n[case testRegisteredImplementationsInDifferentFiles]\nfrom other_a import f, A, B, C\n@f.register\ndef a(arg: A) -> int:\n    return 2\n\n@f.register\ndef _(arg: C) -> int:\n    return 3\n\ndef test_singledispatch() -> None:\n    assert f(B()) == 1\n    assert f(A()) == 2\n    assert f(C()) == 3\n    assert f(1) == 0\n\n[file other_a.py]\nfrom functools import singledispatch\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\n@singledispatch\ndef f(arg: object) -> int:\n    return 0\n\n@f.register\ndef g(arg: B) -> int:\n    return 1\n\n[case testOrderCanOnlyBeDeterminedFromMRONotIsinstanceChecks]\nfrom mypy_extensions import trait\nfrom functools import singledispatch\nfrom typing import Any\n\n@trait\nclass A: pass\n@trait\nclass B: pass\nclass AB(A, B): pass\nclass BA(B, A): pass\n\n@singledispatch\ndef f(arg: Any) -> str:\n    return \"default\"\n\n@f.register\ndef fa(arg: A) -> str:\n    return \"a\"\n\n@f.register\ndef fb(arg: B) -> str:\n    return \"b\"\n\ndef test_singledispatch() -> None:\n    assert f(AB()) == \"a\"\n    assert f(BA()) == \"b\"\n\n[case testCallingFunctionBeforeAllImplementationsRegistered]\nfrom functools import singledispatch\nfrom typing import Any\n\nclass A: pass\nclass B(A): pass\n\n@singledispatch\ndef f(arg: Any) -> str:\n    return 'default'\n\nassert f(A()) == 'default'\nassert f(B()) == 'default'\nassert f(1) == 'default'\n\n@f.register\ndef g(arg: A) -> str:\n    return 'a'\n\nassert f(A()) == 'a'\nassert f(B()) == 'a'\nassert f(1) == 'default'\n\n@f.register\ndef _(arg: B) -> str:\n    return 'b'\n\n# TODO: Move whole testcase to a function when mypyc#1118 is fixed.\ndef test_final() -> None:\n    assert f(A()) == 'a'\n    assert f(B()) == 'b'\n    assert f(1) == 'default'\n\n\n[case testDynamicallyRegisteringFunctionFromInterpretedCode]\nfrom functools import singledispatch\nfrom typing import Any\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\nclass D(C): pass\n\n@singledispatch\ndef f(arg: Any) -> str:\n    return \"default\"\n\n@f.register\ndef _(arg: B) -> str:\n    return 'b'\n\n[file register_impl.py]\nfrom native import f, A, B, C\n\n@f.register(A)\ndef a(arg) -> str:\n    return 'a'\n\n@f.register\ndef c(arg: C) -> str:\n    return 'c'\n\n[file driver.py]\nfrom native import f, A, B, C\nfrom register_impl import a, c\n# We need a custom driver here because register_impl has to be run before we test this (so that the\n# additional implementations are registered)\nassert f(C()) == 'c'\nassert f(A()) == 'a'\nassert f(B()) == 'b'\nassert a(C()) == 'a'\nassert c(A()) == 'c'\n\n[case testMalformedDynamicRegisterCall]\nfrom functools import singledispatch\nfrom typing import Any\n\n@singledispatch\ndef f(arg: Any) -> None:\n    pass\n[file register.py]\nfrom native import f\nfrom testutil import assertRaises\n\nwith assertRaises(TypeError, 'Invalid first argument to `register()`'):\n    @f.register\n    def _():\n        pass\n\n[file driver.py]\nimport register\n\n[case testCacheClearedWhenNewFunctionRegistered]\nfrom functools import singledispatch\n\n@singledispatch\ndef f(arg: object) -> str:\n    return 'default'\n\n[file register.py]\nfrom native import f\nclass A: pass\nclass B: pass\nclass C: pass\n\n# annotated function\nassert f(A()) == 'default'\n@f.register\ndef _(arg: A) -> str:\n    return 'a'\nassert f(A()) == 'a'\n\n# type passed as argument\nassert f(B()) == 'default'\n@f.register(B)\ndef _(arg: B) -> str:\n    return 'b'\nassert f(B()) == 'b'\n\n# 2 argument form\nassert f(C()) == 'default'\ndef c(arg) -> str:\n    return 'c'\nf.register(C, c)\nassert f(C()) == 'c'\n\n\n[file driver.py]\nimport register\n"
  },
  {
    "path": "mypyc/test-data/run-strings.test",
    "content": "# Test cases for strings (compile and run)\n\n[case testStrBasics]\nfrom typing import Tuple\nclass A:\n    def __str__(self) -> str:\n        return \"A-str\"\n    def __repr__(self) -> str:\n        return \"A-repr\"\ndef f() -> str:\n    return 'some string'\ndef g() -> str:\n    return 'some\\a \\v \\t \\x7f \" \\n \\0string 🐍'\ndef tostr(x: int) -> str:\n    return str(x)\ndef booltostr(x: bool) -> str:\n    return str(x)\ndef clstostr(x: A) -> str:\n    return str(x)\ndef torepr(x: int) -> str:\n    return repr(x)\ndef booltorepr(x: bool) -> str:\n    return repr(x)\ndef clstorepr(x: A) -> str:\n    return repr(x)\ndef concat(x: str, y: str) -> str:\n    return x + y\ndef eq(x: str) -> int:\n    if x == 'foo':\n        return 0\n    elif x != 'bar':\n        return 1\n    return 2\ndef match(x: str, y: str) -> Tuple[bool, bool]:\n    return (x.startswith(y), x.endswith(y))\ndef match_tuple(x: str, y: Tuple[str, ...]) -> Tuple[bool, bool]:\n    return (x.startswith(y), x.endswith(y))\ndef match_tuple_literal_args(x: str, y: str, z: str) -> Tuple[bool, bool]:\n    return (x.startswith((y, z)), x.endswith((y, z)))\ndef remove_prefix_suffix(x: str, y: str) -> Tuple[str, str]:\n    return (x.removeprefix(y), x.removesuffix(y))\n\n[file driver.py]\nfrom native import (\n    f, g, A, tostr, booltostr, clstostr, concat, eq, match, match_tuple,\n    match_tuple_literal_args, remove_prefix_suffix,\n    torepr, booltorepr, clstorepr\n)\nimport sys\nfrom testutil import assertRaises\n\nassert f() == 'some string'\nassert f() is sys.intern('some string')\nassert g() == 'some\\a \\v \\t \\x7f \" \\n \\0string 🐍'\nassert tostr(57) == '57'\nassert concat('foo', 'bar') == 'foobar'\nassert booltostr(True) == 'True'\nassert booltostr(False) == 'False'\nassert clstostr(A()) == \"A-str\"\nassert eq('foo') == 0\nassert eq('zar') == 1\nassert eq('bar') == 2\n\nassert torepr(57) == '57'\nassert booltorepr(True) == 'True'\nassert booltorepr(False) == 'False'\nassert clstorepr(A()) == \"A-repr\"\n\nassert int(tostr(0)) == 0\nassert int(tostr(20)) == 20\nassert int(torepr(0)) == 0\nassert int(torepr(20)) == 20\nassert match('', '') == (True, True)\nassert match('abc', '') == (True, True)\nassert match('abc', 'a') == (True, False)\nassert match('abc', 'c') == (False, True)\nassert match('', 'abc') == (False, False)\nassert match_tuple('abc', ('d', 'e')) == (False, False)\nassert match_tuple('abc', ('a', 'c')) == (True, True)\nassert match_tuple('abc', ('a',)) == (True, False)\nassert match_tuple('abc', ('c',)) == (False, True)\nassert match_tuple('abc', ('x', 'y', 'z')) == (False, False)\nassert match_tuple('abc', ('x', 'y', 'z', 'a', 'c')) == (True, True)\nwith assertRaises(TypeError, \"tuple for startswith must only contain str\"):\n    assert match_tuple('abc', (None,))\nwith assertRaises(TypeError, \"tuple for endswith must only contain str\"):\n    assert match_tuple('abc', ('a', None))\nassert match_tuple_literal_args('abc', 'z', 'a') == (True, False)\nassert match_tuple_literal_args('abc', 'z', 'c') == (False, True)\n\nassert remove_prefix_suffix('', '') == ('', '')\nassert remove_prefix_suffix('abc', 'a') == ('bc', 'abc')\nassert remove_prefix_suffix('abc', 'c') == ('abc', 'ab')\n\n[case testStringEquality]\ndef eq(a: str, b: str) -> bool:\n    return a == b\ndef ne(a: str, b: str) -> bool:\n    return a != b\n\ndef test_basic() -> None:\n    xy = \"xy\"\n    xy2 = str().join([\"x\", \"y\"])\n    xx = \"xx\"\n    yy = \"yy\"\n    xxx = \"xxx\"\n\n    assert eq(\"\", str())\n    assert not ne(\"\", str())\n\n    assert eq(\"x\", \"x\" + str())\n    assert ne(\"x\", \"y\")\n\n    assert eq(xy, xy)\n    assert eq(xy, xy2)\n    assert not eq(xy, yy)\n    assert ne(xy, xx)\n    assert not ne(xy, xy)\n    assert not ne(xy, xy2)\n\n    assert ne(xx, xxx)\n    assert ne(xxx, xx)\n    assert ne(\"x\", \"\")\n    assert ne(\"\", \"x\")\n\n    assert ne(\"XX\", xx)\n    assert ne(yy, xy)\n\ndef test_unicode() -> None:\n    assert eq(chr(200), chr(200) + str())\n    assert ne(chr(200), chr(201))\n\n    assert eq(chr(1234), chr(1234) + str())\n    assert ne(chr(1234), chr(1235))\n\n    assert eq(\"\\U0001f4a9\", \"\\U0001f4a9\" + str())\n    assert eq(\"\\U0001f4a9\", \"\\U0001F4A9\" + str())\n    assert ne(\"\\U0001f4a9\", \"\\U0002f4a9\" + str())\n    assert ne(\"\\U0001f4a9\", \"\\U0001f5a9\" + str())\n    assert ne(\"\\U0001f4a9\", \"\\U0001f4a8\" + str())\n\n    assert eq(\"foobar\\u1234\", \"foobar\\u1234\" + str())\n    assert eq(\"\\u1234foobar\", \"\\u1234foobar\" + str())\n    assert ne(\"foobar\\uf234\", \"foobar\\uf235\")\n    assert ne(\"foobar\\uf234\", \"foobar\\uf334\")\n    assert ne(\"foobar\\u1234\", \"Foobar\\u1234\" + str())\n\n    assert eq(\"foo\\U0001f4a9\", \"foo\\U0001f4a9\" + str())\n    assert eq(\"\\U0001f4a9foo\", \"\\U0001f4a9foo\" + str())\n    assert ne(\"foo\\U0001f4a9\", \"foo\\U0001f4a8\" + str())\n    assert ne(\"\\U0001f4a9foo\", \"\\U0001f4a8foo\" + str())\n\n[case testStringOps]\nfrom typing import List, Optional, Tuple\nfrom testutil import assertRaises\n\ndef do_split(s: str, sep: Optional[str] = None, max_split: Optional[int] = None) -> List[str]:\n    if sep is not None:\n        if max_split is not None:\n            return s.split(sep, max_split)\n        else:\n            return s.split(sep)\n    return s.split()\n\ndef do_rsplit(s: str, sep: Optional[str] = None, max_split: Optional[int] = None) -> List[str]:\n    if sep is not None:\n        if max_split is not None:\n            return s.rsplit(sep, max_split)\n        else:\n            return s.rsplit(sep)\n    return s.rsplit()\n\nss = \"abc abcd abcde abcdef\"\n\ndef test_split() -> None:\n    assert do_split(ss) == [\"abc\", \"abcd\", \"abcde\", \"abcdef\"]\n    assert do_split(ss, \" \") == [\"abc\", \"abcd\", \"abcde\", \"abcdef\"]\n    assert do_split(ss, \"-\") == [\"abc abcd abcde abcdef\"]\n    assert do_split(ss, \" \", -1) == [\"abc\", \"abcd\", \"abcde\", \"abcdef\"]\n    assert do_split(ss, \" \", 0) == [\"abc abcd abcde abcdef\"]\n    assert do_split(ss, \" \", 1) == [\"abc\", \"abcd abcde abcdef\"]\n    assert do_split(ss, \" \", 2) == [\"abc\", \"abcd\", \"abcde abcdef\"]\n\ndef test_rsplit() -> None:\n    assert do_rsplit(ss) == [\"abc\", \"abcd\", \"abcde\", \"abcdef\"]\n    assert do_rsplit(ss, \" \") == [\"abc\", \"abcd\", \"abcde\", \"abcdef\"]\n    assert do_rsplit(ss, \"-\") == [\"abc abcd abcde abcdef\"]\n    assert do_rsplit(ss, \" \", -1) == [\"abc\", \"abcd\", \"abcde\", \"abcdef\"]\n    assert do_rsplit(ss, \" \", 0) == [\"abc abcd abcde abcdef\"]\n    assert do_rsplit(ss, \" \", 1) == [\"abc abcd abcde\", \"abcdef\"]  # different to do_split\n    assert do_rsplit(ss, \" \", 2) == [\"abc abcd\", \"abcde\", \"abcdef\"]  # different to do_split\n\ndef splitlines(s: str, keepends: Optional[bool] = None) -> List[str]:\n    if keepends is not None:\n        return s.splitlines(keepends)\n    return s.splitlines()\n\ns_text = \"This\\nis\\n\\nsome\\nlong\\ntext.\\n\"\n\ndef test_splitlines() -> None:\n    assert splitlines(s_text) == [\"This\", \"is\", \"\", \"some\", \"long\", \"text.\"]\n    assert splitlines(s_text, False) == [\"This\", \"is\", \"\", \"some\", \"long\", \"text.\"]\n    assert splitlines(s_text, True) == [\"This\\n\", \"is\\n\", \"\\n\", \"some\\n\", \"long\\n\", \"text.\\n\"]\n\ns_partition = \"Some long text\"\n\ndef partition(s: str, sep: str) -> Tuple[str, str, str]:\n    return s.partition(sep)\n\ndef rpartition(s: str, sep: str) -> Tuple[str, str, str]:\n    return s.rpartition(sep)\n\ndef test_partition() -> None:\n    assert partition(s_partition, \" \") == (\"Some\", \" \", \"long text\")\n    assert partition(s_partition, \"Hello\") == (\"Some long text\", \"\", \"\")\n    assert rpartition(s_partition, \" \") == (\"Some long\", \" \", \"text\")\n    assert rpartition(s_partition, \"Hello\") == (\"\", \"\", \"Some long text\")\n    with assertRaises(ValueError, \"empty separator\"):\n        partition(s_partition, \"\")\n    with assertRaises(ValueError, \"empty separator\"):\n        rpartition(s_partition, \"\")\n\ndef contains(s: str, o: str) -> bool:\n    return o in s\n\ndef getitem(s: str, index: int) -> str:\n    return s[index]\n\ndef find(s: str, substr: str, start: Optional[int] = None, end: Optional[int] = None) -> int:\n    if start is not None:\n        if end is not None:\n            return s.find(substr, start, end)\n        return s.find(substr, start)\n    return s.find(substr)\n\ndef rfind(s: str, substr: str, start: Optional[int] = None, end: Optional[int] = None) -> int:\n    if start is not None:\n        if end is not None:\n            return s.rfind(substr, start, end)\n        return s.rfind(substr, start)\n    return s.rfind(substr)\n\ns = \"abc\"\n\ndef test_contains() -> None:\n    assert contains(s, \"a\") is True\n    assert contains(s, \"abc\") is True\n    assert contains(s, \"Hello\") is False\n    assert contains(s, \"bc\") is True\n    assert contains(s, \"abcd\") is False\n    assert contains(s, \"bb\") is False\n    assert contains(s, \"\") is True\n    assert contains(s, \" \") is False\n\ndef test_getitem() -> None:\n    assert getitem(s, 0) == \"a\"\n    assert getitem(s, 1) == \"b\"\n    assert getitem(s, 2) == \"c\"\n    assert getitem(s, -3) == \"a\"\n    assert getitem(s, -2) == \"b\"\n    assert getitem(s, -1) == \"c\"\n    with assertRaises(IndexError, \"string index out of range\"):\n        getitem(s, 4)\n    with assertRaises(IndexError, \"string index out of range\"):\n        getitem(s, -4)\n\ndef test_getitem_unicode() -> None:\n    # ASCII - cached by CPython's Latin-1 table\n    ascii_s = \"Hello\"\n    assert getitem(ascii_s, 0) == \"H\"\n    assert getitem(ascii_s, 4) == \"o\"\n\n    # Latin-1 (>127, <256) - also cached\n    latin1_s = \"\\xe9\\xfc\\xf1\"  # éüñ\n    assert getitem(latin1_s, 0) == \"\\xe9\"\n    assert getitem(latin1_s, 1) == \"\\xfc\"\n    assert getitem(latin1_s, 2) == \"\\xf1\"\n\n    # BMP (>255) - not cached, allocated fresh\n    bmp_s = \"\\u4e2d\\u6587\"  # 中文\n    assert getitem(bmp_s, 0) == \"\\u4e2d\"\n    assert getitem(bmp_s, 1) == \"\\u6587\"\n\n    # Supplementary plane (>65535)\n    emoji_s = \"\\U0001f600\\U0001f601\"  # 😀😁\n    assert getitem(emoji_s, 0) == \"\\U0001f600\"\n    assert getitem(emoji_s, 1) == \"\\U0001f601\"\n\n    # Mixed string with all kinds\n    mixed = \"A\\xe9\\u4e2d\\U0001f600\"\n    assert getitem(mixed, 0) == \"A\"\n    assert getitem(mixed, 1) == \"\\xe9\"\n    assert getitem(mixed, 2) == \"\\u4e2d\"\n    assert getitem(mixed, 3) == \"\\U0001f600\"\n\n    # Identity check: ASCII/Latin-1 chars should return cached objects\n    a1 = getitem(\"abc\", 0)\n    a2 = getitem(\"axyz\", 0)\n    assert a1 is a2  # both 'a', should be same cached object\n\ndef test_find() -> None:\n    s = \"abcab\"\n    assert find(s, \"Hello\") == -1\n    assert find(s, \"abc\") == 0\n    assert find(s, \"b\") == 1\n    assert find(s, \"b\", 1) == 1\n    assert find(s, \"b\", 1, 2) == 1\n    assert find(s, \"b\", 3) == 4\n    assert find(s, \"b\", 3, 5) == 4\n    assert find(s, \"b\", 3, 4) == -1\n\n    assert rfind(s, \"Hello\") == -1\n    assert rfind(s, \"abc\") == 0\n    assert rfind(s, \"b\") == 4\n    assert rfind(s, \"b\", 1) == 4\n    assert rfind(s, \"b\", 1, 2) == 1\n    assert rfind(s, \"b\", 3) == 4\n    assert rfind(s, \"b\", 3, 5) == 4\n    assert rfind(s, \"b\", 3, 4) == -1\n\ndef str_to_int(s: str, base: Optional[int] = None) -> int:\n    if base:\n        return int(s, base)\n    else:\n        return int(s)\n\ndef test_str_to_int() -> None:\n    assert str_to_int(\"1\") == 1\n    assert str_to_int(\"10\") == 10\n    assert str_to_int(\"a\", 16) == 10\n    assert str_to_int(\"1a\", 16) == 26\n    with assertRaises(ValueError, \"invalid literal for int() with base 10: 'xyz'\"):\n        str_to_int(\"xyz\")\n\ndef test_slicing() -> None:\n    # Use dummy adds to avoid constant folding\n    zero = int()\n    two = zero + 2\n    s = \"foobar\" + str()\n    assert s[two:] == \"obar\"\n    assert s[:two] == \"fo\"\n    assert s[two:-two] == \"ob\"\n    assert s[two:two] == \"\"\n    assert s[two:two + 1] == \"o\"\n    assert s[-two:] == \"ar\"\n    assert s[:-two] == \"foob\"\n    assert s[:] == \"foobar\"\n    assert s[two:333] == \"obar\"\n    assert s[333:two] == \"\"\n    assert s[two:-333] == \"\"\n    assert s[-333:two] == \"fo\"\n    big_int: int = 1000 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000\n    assert s[1:big_int] == \"oobar\"\n    assert s[big_int:] == \"\"\n    assert s[-big_int:-1] == \"fooba\"\n\ndef test_str_replace() -> None:\n    a = \"foofoofoo\"\n    assert a.replace(\"foo\", \"bar\") == \"barbarbar\"\n    assert a.replace(\"foo\", \"bar\", -1) == \"barbarbar\"\n    assert a.replace(\"foo\", \"bar\", 1) == \"barfoofoo\"\n    assert a.replace(\"foo\", \"bar\", 4) == \"barbarbar\"\n    assert a.replace(\"aaa\", \"bar\") == \"foofoofoo\"\n    assert a.replace(\"ofo\", \"xyzw\") == \"foxyzwxyzwo\"\n\ndef is_true(x: str) -> bool:\n    if x:\n        return True\n    else:\n        return False\n\ndef is_true2(x: str) -> bool:\n    return bool(x)\n\ndef is_false(x: str) -> bool:\n    if not x:\n        return True\n    else:\n        return False\n\ndef test_str_to_bool() -> None:\n    assert is_false('')\n    assert not is_true('')\n    assert not is_true2('')\n    for x in 'a', 'foo', 'bar', 'some string':\n        assert is_true(x)\n        assert is_true2(x)\n        assert not is_false(x)\n\ndef test_str_min_max() -> None:\n    x: str = 'aaa'\n    y: str = 'bbb'\n    z: str = 'aa'\n    assert min(x, y) == 'aaa'\n    assert min(x, z) == 'aa'\n    assert max(x, y) == 'bbb'\n    assert max(x, z) == 'aaa'\n\ndef test_multiply() -> None:\n    # Use str() and int() to avoid constant folding\n    s = 'ab' + str()\n    zero = int()\n    one = 1 + zero\n    three = 3 + zero\n    neg_one = -1 + zero\n\n    assert s * zero == ''\n    assert s * one == 'ab'\n    assert s * three == 'ababab'\n    assert s * neg_one == ''\n    assert zero * s == ''\n    assert one * s == 'ab'\n    assert three * s == 'ababab'\n    assert neg_one * s == ''\n\n    # Test with empty string\n    empty = str()\n    five = 5 + zero\n    assert empty * five == ''\n    assert five * empty == ''\n\n    # Test with single character\n    single = 'x' + str()\n    four = 4 + zero\n    assert single * four == 'xxxx'\n    assert four * single == 'xxxx'\n\n    # Test type preservation\n    two = 2 + zero\n    result = s * two\n    assert type(result) == str\n\n[case testStringFormattingCStyle]\nfrom typing import Tuple\n\nvar = 'mypyc'\nnum = 20\n\ndef test_basics() -> None:\n    assert 'Hello %s, this is a test' % var == \"Hello mypyc, this is a test\"\n    assert 'Hello %s %d, this is a test' % (var, num) == \"Hello mypyc 20, this is a test\"\n    t: Tuple[str, int] = (var, num)\n    assert 'Hello %s %d, this is a test' % t == \"Hello mypyc 20, this is a test\"\n\n    large_num = 2**65\n    assert 'number: %d' % large_num == 'number: 36893488147419103232'\n    neg_num = -3\n    assert 'negative integer: %d' % neg_num == 'negative integer: -3'\n    assert 'negative integer: %d' % (-large_num) == 'negative integer: -36893488147419103232'\n\n    bool_var1 = True\n    bool_var2 = False\n    assert 'bool: %s, %s' % (bool_var1, bool_var2) == 'bool: True, False'\n\n    float_num = 123.4\n    assert '%f' % float_num == '123.400000'\n    assert '%.2f' % float_num == '123.40'\n    assert '%.5f' % float_num == '123.40000'\n    assert '%10.2f' % float_num == '    123.40'\n    assert '%10.5f' % float_num == ' 123.40000'\n    assert '%010.5f' % float_num == '0123.40000'\n    assert '%015.5f' % float_num == '000000123.40000'\n    assert '%e' % float_num == '1.234000e+02'\n    large_float = 1.23e30\n    large_float2 = 1234123412341234123400000000000000000\n    small_float = 1.23e-20\n    assert '%f, %f, %f' % (small_float, large_float, large_float2) == \\\n           '0.000000, 1229999999999999959718843908096.000000, 1234123412341234169005079998930878464.000000'\n    assert '%s, %s, %s' % (small_float, large_float, large_float2) == \\\n           '1.23e-20, 1.23e+30, 1234123412341234123400000000000000000'\n    assert '%d, %d, %d' % (small_float, large_float, large_float2) == \\\n           '0, 1229999999999999959718843908096, 1234123412341234123400000000000000000'\n\n    nan_num = float('nan')\n    inf_num = float('inf')\n    assert '%s, %s' % (nan_num, inf_num) == 'nan, inf'\n    assert '%f, %f' % (nan_num, inf_num) == 'nan, inf'\n[typing fixtures/typing-full.pyi]\n\n[case testFStrings]\nimport decimal\nfrom datetime import datetime\nfrom typing import Final\n\nvar = 'mypyc'\nnum = 20\nfinal_known_at_compile_time: Final = 'hello'\n\ndef final_value_setter() -> str:\n    return 'goodbye'\n\nfinal_unknown_at_compile_time: Final = final_value_setter()\n\ndef test_fstring_basics() -> None:\n    assert f'Hello {var}, this is a test' == \"Hello mypyc, this is a test\"\n\n    large_num = 2**65\n    assert f'number: {large_num}' == 'number: 36893488147419103232'\n    neg_num = -3\n    assert f'negative integer: {neg_num}' == 'negative integer: -3'\n    assert f'negative integer: {-large_num}' == 'negative integer: -36893488147419103232'\n\n    bool_var1 = True\n    bool_var2 = False\n    assert f'bool: {bool_var1}, {bool_var2}' == 'bool: True, False'\n\n    x = bytes([1, 2, 3, 4])\n    # assert f'bytes: {x}' == \"bytes: b'\\\\x01\\\\x02\\\\x03\\\\x04'\"\n    # error: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). Otherwise, decode the bytes\n\n    float_num = 123.4\n    assert f'{float_num}' == '123.4'\n    assert f'{float_num:.2f}' == '123.40'\n    assert f'{float_num:.5f}' == '123.40000'\n    assert f'{float_num:>10.2f}' == '    123.40'\n    assert f'{float_num:>10.5f}' == ' 123.40000'\n    assert f'{float_num:>010.5f}' == '0123.40000'\n    assert f'{float_num:>015.5f}' == '000000123.40000'\n    assert f'{float_num:e}' == '1.234000e+02'\n\n    large_float = 1.23e30\n    large_float2 = 1234123412341234123400000000000000000\n    small_float = 1.23e-20\n    assert f'{small_float}, {large_float}, {large_float2}' == '1.23e-20, 1.23e+30, 1234123412341234123400000000000000000'\n    nan_num = float('nan')\n    inf_num = float('inf')\n    assert f'{nan_num}, {inf_num}' == 'nan, inf'\n\n    assert f'{final_known_at_compile_time} {final_unknown_at_compile_time}' == 'hello goodbye'\n\n# F-strings would be translated into ''.join[string literals, format method call, ...] in mypy AST.\n# Currently we are using a str.join specializer for f-string speed up. We might not cover all cases\n# and the rest ones should fall back to a normal str.join method call.\n# TODO: Once we have a new pipeline for f-strings, this test case can be moved to testStringOps.\ndef test_str_join() -> None:\n    var = 'mypyc'\n    num = 10\n    assert ''.join(['a', 'b', '{}'.format(var), 'c']) == 'abmypycc'\n    assert ''.join(['a', 'b', '{:{}}'.format(var, ''), 'c']) == 'abmypycc'\n    assert ''.join(['a', 'b', '{:{}}'.format(var, '>10'), 'c']) == 'ab     mypycc'\n    assert ''.join(['a', 'b', '{:{}}'.format(var, '>{}'.format(num)), 'c']) == 'ab     mypycc'\n    assert var.join(['a', '{:{}}'.format(var, ''), 'b']) == 'amypycmypycmypycb'\n    assert ','.join(['a', '{:{}}'.format(var, ''), 'b']) == 'a,mypyc,b'\n    assert ''.join(['x', var]) == 'xmypyc'\n\nclass A:\n    def __init__(self, name, age):\n        self.name = name\n        self.age = age\n\n    def __repr__(self):\n        return f'{self.name} is {self.age} years old.'\n\ndef test_fstring_datatype() -> None:\n    u = A('John Doe', 14)\n    assert f'{u}' == 'John Doe is 14 years old.'\n    d = {'name': 'John Doe', 'age': 14}\n    assert f'{d}' == \"{'name': 'John Doe', 'age': 14}\"\n\ndef test_fstring_escape() -> None:\n    assert f\"{'inside'}\" == 'inside'\n    assert f'{\"inside\"}' == 'inside'\n    assert f\"\"\"inside\"\"\" == 'inside'\n    assert f'''inside''' == 'inside'\n    assert f\"\\\"{'inside'}\\\"\" == '\"inside\"'\n    assert f'\\'{\"inside\"}\\'' == \"'inside'\"\n\n    assert f'{{10}}' == '{10}'\n    assert f'{{10 + 10}}' == '{10 + 10}'\n    assert f'{{{10 + 10}}}' == '{20}'\n    assert f'{{{{10 + 10}}}}' == '{{10 + 10}}'\n\ndef test_fstring_conversion() -> None:\n    assert f'Hello {var!r}' == \"Hello 'mypyc'\"\n    # repr() is equivalent to !r\n    assert f'Hello {repr(var)}' == \"Hello 'mypyc'\"\n\n    assert f'Hello {var!a}' == \"Hello 'mypyc'\"\n    # ascii() is equivalent to !a\n    assert f'Hello {ascii(var)}' == \"Hello 'mypyc'\"\n\n    tmp_str = \"\"\"this\n    is a new line.\"\"\"\n    assert f'Test: {tmp_str!a}' == \"Test: 'this\\\\n    is a new line.'\"\n\n    s = 'test: āĀēĒčČ..šŠūŪžŽ'\n    assert f'{s}' == 'test: āĀēĒčČ..šŠūŪžŽ'\n    assert f'{s!a}' == \"'test: \\\\u0101\\\\u0100\\\\u0113\\\\u0112\\\\u010d\\\\u010c..\\\\u0161\\\\u0160\\\\u016b\\\\u016a\\\\u017e\\\\u017d'\"\n\n    assert f'Hello {var!s}' == 'Hello mypyc'\n    assert f'Hello {num!s}' == 'Hello 20'\n\ndef test_fstring_align() -> None:\n    assert f'Hello {var:>20}' == \"Hello                mypyc\"\n    assert f'Hello {var!r:>20}' == \"Hello              'mypyc'\"\n    assert f'Hello {var:>{num}}' == \"Hello                mypyc\"\n    assert f'Hello {var!r:>{num}}' == \"Hello              'mypyc'\"\n\ndef test_fstring_multi() -> None:\n    assert f'Hello {var}, hello again {var}' == \"Hello mypyc, hello again mypyc\"\n    a = 'py'\n    s = f'my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}my{a}'\n    assert s == 'mypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypymypy'\n\ndef test_fstring_python_doc() -> None:\n    name = 'Fred'\n    assert f\"He said his name is {name!r}.\" == \"He said his name is 'Fred'.\"\n    assert f\"He said his name is {repr(name)}.\" == \"He said his name is 'Fred'.\"\n\n    width = 10\n    precision = 4\n    value = decimal.Decimal('12.34567')\n    assert f'result: {value:{width}.{precision}}' == 'result:      12.35' # nested field\n\n    today = datetime(year=2017, month=1, day=27)\n    assert f'{today:%B %d, %Y}' == 'January 27, 2017'  # using date format specifier\n\n    number = 1024\n    assert f'{number:#0x}' == '0x400' # using integer format specifier\n\n[case testStringFormatMethod]\nfrom typing import Tuple\n\ndef test_format_method_basics() -> None:\n    x = str()\n    assert 'x{}'.format(x) == 'x'\n    assert 'ā{}'.format(x) == 'ā'\n    assert '😀{}'.format(x) == '😀'\n    assert ''.format() == ''\n    assert 'abc'.format() == 'abc'\n    assert '{}{}'.format(1, 2) == '12'\n\n    name = 'Eric'\n    age = 14\n    assert \"My name is {name}, I'm {age}.\".format(name=name, age=age) == \"My name is Eric, I'm 14.\"\n    assert \"My name is {A}, I'm {B}.\".format(A=name, B=age) == \"My name is Eric, I'm 14.\"\n    assert \"My name is {}, I'm {B}.\".format(name, B=age) == \"My name is Eric, I'm 14.\"\n\n    bool_var1 = True\n    bool_var2 = False\n    assert 'bool: {}, {}'.format(bool_var1, bool_var2) == 'bool: True, False'\n\ndef test_format_method_empty_braces() -> None:\n    name = 'Eric'\n    age = 14\n\n    assert 'Hello, {}!'.format(name) == 'Hello, Eric!'\n    assert '{}'.format(name) == 'Eric'\n    assert '{}! Hi!'.format(name) == 'Eric! Hi!'\n    assert '{}, Hi, {}'.format(name, name) == 'Eric, Hi, Eric'\n    assert 'Hi! {}'.format(name) == 'Hi! Eric'\n    assert \"Hi, I'm {}. I'm {}.\".format(name, age) == \"Hi, I'm Eric. I'm 14.\"\n\n    assert '{{}}'.format() == '{}'\n    assert '{{{{}}}}'.format() == '{{}}'\n    assert '{{}}{}'.format(name) == '{}Eric'\n    assert 'Hi! {{{}}}'.format(name) == 'Hi! {Eric}'\n    assert 'Hi! {{ {}'.format(name) == 'Hi! { Eric'\n    assert 'Hi! {{ {} }}}}'.format(name) == 'Hi! { Eric }}'\n\ndef test_format_method_numbers() -> None:\n    s = 'int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}'.format(-233)\n    assert s == 'int: -233;  hex: -e9;  oct: -351;  bin: -11101001'\n    num = 2**65\n    s = 'int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}'.format(num)\n    assert s == 'int: 36893488147419103232;  hex: 20000000000000000;  oct: 4000000000000000000000;  bin: 100000000000000000000000000000000000000000000000000000000000000000'\n    s = 'int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}'.format(-num)\n    assert s == 'int: -36893488147419103232;  hex: -20000000000000000;  oct: -4000000000000000000000;  bin: -100000000000000000000000000000000000000000000000000000000000000000'\n\n    large_num = 2**65\n    assert 'number: {}'.format(large_num) == 'number: 36893488147419103232'\n    neg_num = -3\n    assert 'negative integer: {}'.format(neg_num) == 'negative integer: -3'\n    assert 'negative integer: {}'.format(-large_num) == 'negative integer: -36893488147419103232'\n\n    large_float = 1.23e30\n    large_float2 = 1234123412341234123400000000000000000\n    small_float = 1.23e-20\n    assert '{}, {}, {}'.format(small_float, large_float, large_float2) == '1.23e-20, 1.23e+30, 1234123412341234123400000000000000000'\n    nan_num = float('nan')\n    inf_num = float('inf')\n    assert '{}, {}'.format(nan_num, inf_num) == 'nan, inf'\n\ndef format_args(*args: int) -> str:\n    return 'x{}y{}'.format(*args)\ndef format_kwargs(**kwargs: int) -> str:\n    return 'c{x}d{y}'.format(**kwargs)\ndef format_args_self(*args: int) -> str:\n    return '{}'.format(args)\ndef format_kwargs_self(**kwargs: int) -> str:\n    return '{}'.format(kwargs)\n\ndef test_format_method_args() -> None:\n    assert format_args(10, 2) == 'x10y2'\n    assert format_args_self(10, 2) == '(10, 2)'\n    assert format_kwargs(x=10, y=2) == 'c10d2'\n    assert format_kwargs(x=10, y=2, z=1) == 'c10d2'\n    assert format_kwargs_self(x=10, y=2, z=1) == \"{'x': 10, 'y': 2, 'z': 1}\"\n\ndef test_format_method_different_kind() -> None:\n    s1 = \"Literal['😀']\"\n    assert 'Revealed type is {}'.format(s1) == \"Revealed type is Literal['😀']\"\n    s2 = \"Revealed type is\"\n    assert \"{} Literal['😀']\".format(s2) == \"Revealed type is Literal['😀']\"\n    s3 = \"测试：\"\n    assert \"{}{} {}\".format(s3, s2, s1) == \"测试：Revealed type is Literal['😀']\"\n    assert \"Test: {}{}\".format(s3, s1) == \"Test: 测试：Literal['😀']\"\n    assert \"Test: {}{}\".format(s3, s2) == \"Test: 测试：Revealed type is\"\n\ndef test_format_method_nested() -> None:\n    var = 'mypyc'\n    num = 10\n    assert '{:{}}'.format(var, '') == 'mypyc'\n    assert '{:{}}'.format(var, '>10') == '     mypyc'\n    assert '{:{}}'.format(var, '>{}'.format(num)) == '     mypyc'\n\nclass Point:\n    def __init__(self, x, y):\n        self.x, self.y = x, y\n    def __str__(self):\n        return 'Point({self.x}, {self.y})'.format(self=self)\n\n# Format examples from Python doc\n# https://docs.python.org/3/library/string.html#formatexamples\ndef test_format_method_python_doc() -> None:\n    # Accessing arguments by position:\n    assert '{0}, {1}, {2}'.format('a', 'b', 'c') == 'a, b, c'\n    assert '{}, {}, {}'.format('a', 'b', 'c') == 'a, b, c'\n    assert '{2}, {1}, {0}'.format('a', 'b', 'c') == 'c, b, a'\n    assert '{2}, {1}, {0}'.format(*'abc') == 'c, b, a'        # unpacking argument sequence\n    # assert '{0}{1}{0}'.format('abra', 'cad') = 'abracadabra'  # arguments' indices can be repeated\n\n    # Accessing arguments by name:\n    s = 'Coordinates: {latitude}, {longitude}'.format(latitude='37.24N', longitude='-115.81W')\n    assert s == 'Coordinates: 37.24N, -115.81W'\n    coord = {'latitude': '37.24N', 'longitude': '-115.81W'}\n    assert 'Coordinates: {latitude}, {longitude}'.format(**coord) == 'Coordinates: 37.24N, -115.81W'\n\n    # Accessing arguments’ attributes:\n    assert str(Point(4, 2)) == 'Point(4, 2)'\n\n    # Accessing arguments’ items:\n    coord2 = (3, 5)\n    assert 'X: {0[0]};  Y: {0[1]}'.format(coord2) == 'X: 3;  Y: 5'\n\n    # Replacing %s and %r:\n    s = \"repr() shows quotes: {!r}; str() doesn't: {!s}\".format('test1', 'test2')\n    assert s == \"repr() shows quotes: 'test1'; str() doesn't: test2\"\n\n    # Aligning the text and specifying a width:\n    assert '{:<30}'.format('left aligned') == 'left aligned                  '\n    assert '{:>30}'.format('right aligned') == '                 right aligned'\n    assert '{:^30}'.format('centered') == '           centered           '\n    assert '{:*^30}'.format('centered') == '***********centered***********' # use '*' as a fill char\n\n    # Replacing %+f, %-f, and % f and specifying a sign:\n    assert '{:+f}; {:+f}'.format(3.14, -3.14) == '+3.140000; -3.140000' # show it always\n    assert '{: f}; {: f}'.format(3.14, -3.14) == ' 3.140000; -3.140000' # show a space for positive numbers\n    assert '{:-f}; {:-f}'.format(3.14, -3.14) == '3.140000; -3.140000' # show only the minus -- same as '{:f}; {:f}'\n\n    # Replacing %x and %o and converting the value to different bases:\n    s = 'int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}'.format(42) # format also supports binary numbers\n    assert s == 'int: 42;  hex: 2a;  oct: 52;  bin: 101010'\n    s = 'int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}'.format(42) # with 0x, 0o, or 0b as prefix:\n    assert s == 'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'\n\n    # Using the comma as a thousands separator:\n    assert '{:,}'.format(1234567890) == '1,234,567,890'\n\n    # Expressing a percentage:\n    points = 19.0\n    total = 22.0\n    assert 'Correct answers: {:.2%}'.format(points/total) == 'Correct answers: 86.36%'\n\n    # Using type-specific formatting:\n    import datetime\n    d = datetime.datetime(2010, 7, 4, 12, 15, 58)\n    assert '{:%Y-%m-%d %H:%M:%S}'.format(d) == '2010-07-04 12:15:58'\n\n    # Nesting arguments and more complex examples:\n    tmp_strs = []\n    for align, text in zip('<^>', ['left', 'center', 'right']):\n        tmp_strs.append('{0:{fill}{align}16}'.format(text, fill=align, align=align))\n    assert tmp_strs == ['left<<<<<<<<<<<<', '^^^^^center^^^^^', '>>>>>>>>>>>right']\n\n    octets = [192, 168, 0, 1]\n    assert '{:02X}{:02X}{:02X}{:02X}'.format(*octets) == 'C0A80001'\n\n    width = 5\n    tmp_strs = []\n    for num in range(5,12):\n        tmp_str = ''\n        for base in 'dXob':\n            tmp_str += ('{0:{width}{base}}'.format(num, base=base, width=width))\n        tmp_strs.append(tmp_str)\n    assert tmp_strs == ['    5    5    5  101',\\\n                        '    6    6    6  110',\\\n                        '    7    7    7  111',\\\n                        '    8    8   10 1000',\\\n                        '    9    9   11 1001',\\\n                        '   10    A   12 1010',\\\n                        '   11    B   13 1011']\n\n[case testChr]\n# Some test cases are from https://docs.python.org/3/howto/unicode.html\n\ndef try_invalid(x: int) -> bool:\n    try:\n        chr(x + int())\n        return False\n    except ValueError:\n        return True\n\ndef test_chr() -> None:\n    assert chr(57344) == '\\ue000'\n    assert chr(0) == '\\x00'\n    assert chr(65) == 'A'\n    assert chr(150) == '\\x96'\n    try:\n        chr(-1)\n        assert False\n    except ValueError:\n        pass\n    try:\n        chr(1114112)\n        assert False\n    except ValueError:\n        pass\n    assert chr(1114111) == '\\U0010ffff'\n    x = 0\n    assert chr(x + int()) == '\\x00'\n    x = 100\n    assert chr(x + int()) == 'd'\n    x = 150\n    assert chr(x + int()) == '\\x96'\n    x = 257\n    assert chr(x + int()) == 'ā'\n    x = 65537\n    assert chr(x + int()) == '𐀁'\n    assert try_invalid(-1)\n    assert try_invalid(1114112)\n\n[case testOrd]\nfrom testutil import assertRaises\nfrom mypy_extensions import i64, i32, i16, u8\n\ndef test_ord() -> None:\n    assert ord(' ') == 32\n    assert ord(' ' + str()) == 32\n    assert ord('\\x00') == 0\n    assert ord('\\x00' + str()) == 0\n    assert ord('\\ue000') == 57344\n    assert ord('\\ue000' + str()) == 57344\n    s = \"a\\xac\\u1234\\u20ac\\U00010000\"\n    #     ^^^^ two-digit hex escape\n    #         ^^^^^^ four-digit Unicode escape\n    #                     ^^^^^^^^^^ eight-digit Unicode escape\n    l1 = [ord(c) for c in s]\n    assert l1 == [97, 172, 4660, 8364, 65536]\n    u = 'abcdé'\n    assert ord(u[-1]) == 233\n    assert ord(b'a') == 97\n    assert ord(b'a' + bytes()) == 97\n    u2 = '\\U0010ffff' + str()\n    assert ord(u2) == 1114111\n    assert ord('\\U0010ffff') == 1114111\n    with assertRaises(TypeError, \"ord() expected a character, but a string of length 2 found\"):\n        ord('aa')\n    with assertRaises(TypeError):\n        ord('')\n\ndef test_ord_str_index() -> None:\n    # ASCII\n    s1 = \"hello\"\n    assert ord(s1[0 + int()]) == 104  # 'h'\n    assert ord(s1[1 + int()]) == 101  # 'e'\n    assert ord(s1[4 + int()]) == 111  # 'o'\n    assert ord(s1[-1 + int()]) == 111  # 'o'\n    assert ord(s1[-5 + int()]) == 104  # 'h'\n\n    # Latin-1 (8 bits)\n    s2 = \"café\"\n    assert ord(s2[0 + int()]) == 99   # 'c'\n    assert ord(s2[3 + int()]) == 233  # 'é' (U+00E9)\n    assert ord(s2[-1 + int()]) == 233\n\n    # 16-bit unicode\n    s3 = \"你好\"  # Chinese\n    assert ord(s3[0 + int()]) == 20320  # '你' (U+4F60)\n    assert ord(s3[1 + int()]) == 22909  # '好' (U+597D)\n    assert ord(s3[-1 + int()]) == 22909\n    assert ord(s3[-2 + int()]) == 20320\n\n    # 4-byte unicode\n    s5 = \"a😀b\"  # Emoji between ASCII chars\n    assert ord(s5[0 + int()]) == 97    # 'a'\n    assert ord(s5[1 + int()]) == 128512  # '😀' (U+1F600)\n    assert ord(s5[2 + int()]) == 98    # 'b'\n    assert ord(s5[-1 + int()]) == 98\n    assert ord(s5[-2 + int()]) == 128512\n    assert ord(s5[-3 + int()]) == 97\n\n    with assertRaises(IndexError, \"index out of range\"):\n        ord(s1[5 + int()])\n    with assertRaises(IndexError, \"index out of range\"):\n        ord(s1[100 + int()])\n    with assertRaises(IndexError, \"index out of range\"):\n        ord(s1[-6 + int()])\n    with assertRaises(IndexError, \"index out of range\"):\n        ord(s1[-100 + int()])\n\n    s_empty = \"\"\n    with assertRaises(IndexError, \"index out of range\"):\n        ord(s_empty[0 + int()])\n    with assertRaises(IndexError, \"index out of range\"):\n        ord(s_empty[-1 + int()])\n\ndef test_ord_str_index_i64() -> None:\n    s = \"hello\"\n\n    idx_i64: i64 = 2 + int()\n    assert ord(s[idx_i64]) == 108  # 'l'\n\n    idx_i64_neg: i64 = -1 + int()\n    assert ord(s[idx_i64_neg]) == 111  # 'o'\n\n    idx_overflow: i64 = 10 + int()\n    with assertRaises(IndexError, \"index out of range\"):\n        ord(s[idx_overflow])\n\n    idx_underflow: i64 = -10 + int()\n    with assertRaises(IndexError, \"index out of range\"):\n        ord(s[idx_underflow])\n\ndef test_ord_str_index_unicode_mix() -> None:\n    # Mix of 1-byte, 2-byte, 3-byte, and 4-byte characters\n    s = \"a\\u00e9\\u4f60😀\"  # 'a', 'é', '你', '😀'\n    assert ord(s[0 + int()]) == 97      # 1-byte\n    assert ord(s[1 + int()]) == 233     # 2-byte\n    assert ord(s[2 + int()]) == 20320   # 3-byte\n    assert ord(s[3 + int()]) == 128512  # 4-byte\n\ndef test_ord_str_index_to_fixed_width() -> None:\n    # Test i32 coercion (signed 32-bit: -2^31 to 2^31-1)\n    # All valid Unicode code points fit in i32, so test min/max boundaries\n    s_i32_min = chr(0)\n    assert i32(ord(s_i32_min[0 + int()])) == 0\n\n    s_i32_max = chr(0x10FFFF)  # Max Unicode code point\n    assert i32(ord(s_i32_max[0 + int()])) == 0x10FFFF\n\n    # Test i16 coercion (signed 16-bit: -2^15 to 2^15-1, i.e., -32768 to 32767)\n    # ord() returns non-negative, so test 0 to 32767\n    s_i16_min = chr(0)\n    assert i16(ord(s_i16_min[0 + int()])) == 0\n\n    s_i16_max = chr(32767)  # 2^15 - 1\n    assert i16(ord(s_i16_max[0 + int()])) == 32767\n\n    s_i16_overflow = chr(32768)  # 2^15\n    with assertRaises(ValueError, \"int too large to convert to i16\"):\n        i16(ord(s_i16_overflow[0 + int()]))\n\n    s_i16_overflow2 = chr(32769)  # 2^15 + 1\n    with assertRaises(ValueError, \"int too large to convert to i16\"):\n        i16(ord(s_i16_overflow2[0 + int()]))\n\n    # Test u8 coercion (unsigned 8-bit: 0 to 2^8-1, i.e., 0 to 255)\n    s_u8_min = chr(0)\n    assert u8(ord(s_u8_min[0 + int()])) == 0\n\n    s_u8_max = chr(255)\n    assert u8(ord(s_u8_max[0 + int()])) == 255\n\n    s_u8_overflow = chr(256)\n    with assertRaises(ValueError, \"int too large or small to convert to u8\"):\n        u8(ord(s_u8_overflow[0 + int()]))\n\n    s_u8_overflow2 = chr(257)\n    with assertRaises(ValueError, \"int too large or small to convert to u8\"):\n        u8(ord(s_u8_overflow2[0 + int()]))\n\n[case testDecode]\nfrom testutil import assertRaises\n\ndef test_decode() -> None:\n    assert \"\\N{GREEK CAPITAL LETTER DELTA}\" == '\\u0394'\n    assert \"\\u0394\" == \"\\u0394\"\n    assert \"\\U00000394\" == '\\u0394'\n    assert b'\\x80abc'.decode('utf-8', 'replace') == '\\ufffdabc'\n    assert b'\\x80abc'.decode('utf-8', 'backslashreplace') == '\\\\x80abc'\n    assert b''.decode() == ''\n    assert b'a'.decode() == 'a'\n    assert b'abc'.decode() == 'abc'\n    assert b'abc'.decode('utf-8') == 'abc'\n    assert b'abc'.decode('utf-8' + str()) == 'abc'\n    assert b'abc\\x00\\xce'.decode('latin-1') == 'abc\\x00\\xce'\n    assert b'abc\\x00\\xce'.decode('latin-1' + str()) == 'abc\\x00\\xce'\n    assert b'abc\\x00\\x7f'.decode('ascii') == 'abc\\x00\\x7f'\n    assert b'abc\\x00\\x7f'.decode('ascii' + str()) == 'abc\\x00\\x7f'\n    assert b'\\x80abc'.decode('utf-8', 'ignore') == 'abc'\n    assert b'\\x80abc'.decode('UTF-8', 'ignore') == 'abc'\n    assert b'\\x80abc'.decode('Utf-8', 'ignore') == 'abc'\n    assert b'\\x80abc'.decode('utf_8', 'ignore') == 'abc'\n    assert b'\\x80abc'.decode('latin1', 'ignore') == '\\x80abc'\n    assert b'\\xd2\\xbb\\xb6\\xfe\\xc8\\xfd'.decode('gbk', 'ignore') == '一二三'\n    assert b'\\xd2\\xbb\\xb6\\xfe\\xc8\\xfd'.decode('latin1', 'ignore') == 'Ò»¶þÈý'\n    assert b'Z\\xc3\\xbcrich'.decode(\"utf-8\") == 'Zürich'\n    assert b'Z\\xc3\\xbcrich'.decode(\"utf-8\" + str()) == 'Zürich'\n\n    assert bytearray(range(5)).decode() == '\\x00\\x01\\x02\\x03\\x04'\n    b = bytearray(b'\\xe4\\xbd\\xa0\\xe5\\xa5\\xbd')\n    assert b.decode() == '你好'\n    assert b.decode('gbk') == '浣犲ソ'\n    assert b.decode('latin1') == 'ä½\\xa0å¥½'\n    assert b.decode('latin1' + str()) == 'ä½\\xa0å¥½'\n\ndef test_decode_error() -> None:\n    try:\n        b'Z\\xc3\\xbcrich'.decode('ascii')\n        assert False\n    except UnicodeDecodeError:\n        pass\n    try:\n        b'Z\\xc3\\xbcrich'.decode('ascii' + str())\n        assert False\n    except UnicodeDecodeError:\n        pass\n    try:\n        b'Z\\xc3y'.decode('utf8')\n        assert False\n    except UnicodeDecodeError:\n        pass\n    try:\n        b'Z\\xc3y'.decode('utf8' + str())\n        assert False\n    except UnicodeDecodeError:\n        pass\n\ndef test_decode_bytearray() -> None:\n    b = bytearray(b'foo\\x00bar')\n    assert b.decode() == 'foo\\x00bar'\n    assert b.decode('utf-8') == 'foo\\x00bar'\n    assert b.decode('latin-1') == 'foo\\x00bar'\n    assert b.decode('ascii') == 'foo\\x00bar'\n    assert b.decode('utf-8' + str()) == 'foo\\x00bar'\n    assert b.decode('latin-1' + str()) == 'foo\\x00bar'\n    assert b.decode('ascii' + str()) == 'foo\\x00bar'\n    b2 = bytearray(b'foo\\x00bar\\xbe')\n    assert b2.decode('latin-1') == 'foo\\x00bar\\xbe'\n    with assertRaises(UnicodeDecodeError):\n        b2.decode('ascii')\n    with assertRaises(UnicodeDecodeError):\n        b2.decode('ascii' + str())\n    with assertRaises(UnicodeDecodeError):\n        b2.decode('utf-8')\n    with assertRaises(UnicodeDecodeError):\n        b2.decode('utf-8' + str())\n    b3 = bytearray(b'Z\\xc3\\xbcrich')\n    assert b3.decode(\"utf-8\") == 'Zürich'\n\ndef test_invalid_encoding() -> None:\n    try:\n        b\"foo\".decode(\"ut-f-8\")\n        assert False\n    except Exception as e:\n        assert repr(e).startswith(\"LookupError\")\n    try:\n        encoding = \"ut-f-8\"\n        b\"foo\".decode(encoding)\n        assert False\n    except Exception as e:\n        assert repr(e).startswith(\"LookupError\")\n\n[case testEncode]\nfrom testutil import assertRaises\n\ndef test_encode() -> None:\n    u = chr(40960) + 'abcd' + chr(1972)\n    assert u.encode() == b'\\xea\\x80\\x80abcd\\xde\\xb4'\n    assert u.encode('utf-8') == b'\\xea\\x80\\x80abcd\\xde\\xb4'\n    with assertRaises(UnicodeEncodeError):\n        u.encode('ascii')\n    with assertRaises(LookupError):\n        u.encode('aaa')\n    assert u.encode('utf-8', 'aaaaaa') == b'\\xea\\x80\\x80abcd\\xde\\xb4'\n    assert u.encode('ascii', 'ignore') == b'abcd'\n    assert u.encode('ASCII', 'ignore') == b'abcd'\n    assert u.encode('ascii', 'replace') == b'?abcd?'\n    assert u.encode('ascii', 'xmlcharrefreplace') == b'&#40960;abcd&#1972;'\n    assert u.encode('ascii', 'backslashreplace') == b'\\\\ua000abcd\\\\u07b4'\n    assert u.encode('ascii', 'namereplace') == b'\\\\N{YI SYLLABLE IT}abcd\\\\u07b4'\n    assert 'pythön!'.encode() == b'pyth\\xc3\\xb6n!'\n    assert '一二三'.encode('gbk') == b'\\xd2\\xbb\\xb6\\xfe\\xc8\\xfd'\n    assert u.encode('UTF-8', 'ignore') == b'\\xea\\x80\\x80abcd\\xde\\xb4'\n    assert u.encode('Utf_8') == b'\\xea\\x80\\x80abcd\\xde\\xb4'\n    assert u.encode('UTF_8') == b'\\xea\\x80\\x80abcd\\xde\\xb4'\n    assert u'\\u00E1'.encode('latin1') == b'\\xe1'\n    with assertRaises(UnicodeEncodeError):\n        u.encode('latin1')\n\n[case testUnicodeSurrogate]\ndef f() -> str:\n    return \"\\ud800\"\n\ndef test_surrogate() -> None:\n    assert ord(f()) == 0xd800\n    assert ord(\"\\udfff\") == 0xdfff\n    assert repr(\"foobar\\x00\\xab\\ud912\\U00012345\") == r\"'foobar\\x00«\\ud912𒍅'\"\n\n[case testStrip]\ndef test_all_strips_default() -> None:\n    s = \" a1\\t\"\n    assert s.lstrip() == \"a1\\t\"\n    assert s.strip() == \"a1\"\n    assert s.rstrip() == \" a1\"\ndef test_all_strips() -> None:\n    s = \"xxb2yy\"\n    assert s.lstrip(\"xy\") == \"b2yy\"\n    assert s.strip(\"xy\") == \"b2\"\n    assert s.rstrip(\"xy\") == \"xxb2\"\ndef test_unicode_whitespace() -> None:\n    assert \"\\u200A\\u000D\\u2009\\u2020\\u000Dtt\\u0085\\u000A\".strip() == \"\\u2020\\u000Dtt\"\ndef test_unicode_range() -> None:\n    assert \"\\u2029 \\U00107581 \".lstrip() == \"\\U00107581 \"\n    assert \"\\u2029 \\U0010AAAA\\U00104444B\\u205F \".strip() == \"\\U0010AAAA\\U00104444B\"\n    assert \" \\u3000\\u205F \".strip() == \"\"\n    assert \"\\u2029 \\U00102865\\u205F \".rstrip() == \"\\u2029 \\U00102865\"\n\n[case testCount]\n# mypy: disable-error-code=\"attr-defined\"\ndef test_count() -> None:\n    string = \"abcbcb\"\n    assert string.count(\"a\") == 1\n    assert string.count(\"b\") == 3\n    assert string.count(\"c\") == 2\ndef test_count_start() -> None:\n    string = \"abcbcb\"\n    assert string.count(\"a\", 2) == string.count(\"a\", -4) == 0, (string.count(\"a\", 2), string.count(\"a\", -4))\n    assert string.count(\"b\", 2) == string.count(\"b\", -4) == 2, (string.count(\"b\", 2), string.count(\"b\", -4))\n    assert string.count(\"c\", 2) == string.count(\"c\", -4) == 2, (string.count(\"c\", 2), string.count(\"c\", -4))\n    # out of bounds\n    assert string.count(\"a\", 8) == 0\n    assert string.count(\"a\", -8) == 1\n    assert string.count(\"b\", 8) == 0\n    assert string.count(\"b\", -8) == 3\n    assert string.count(\"c\", 8) == 0\n    assert string.count(\"c\", -8) == 2\ndef test_count_start_end() -> None:\n    string = \"abcbcb\"\n    assert string.count(\"a\", 0, 4) == 1, string.count(\"a\", 0, 4)\n    assert string.count(\"b\", 0, 4) == 2, string.count(\"b\", 0, 4)\n    assert string.count(\"c\", 0, 4) == 1, string.count(\"c\", 0, 4)\ndef test_count_multi() -> None:\n    string = \"aaabbbcccbbbcccbbb\"\n    assert string.count(\"aaa\") == 1, string.count(\"aaa\")\n    assert string.count(\"bbb\") == 3, string.count(\"bbb\")\n    assert string.count(\"ccc\") == 2, string.count(\"ccc\")\ndef test_count_multi_start() -> None:\n    string = \"aaabbbcccbbbcccbbb\"\n    assert string.count(\"aaa\", 6) == string.count(\"aaa\", -12) == 0, (string.count(\"aaa\", 6), string.count(\"aaa\", -12))\n    assert string.count(\"bbb\", 6) == string.count(\"bbb\", -12) == 2, (string.count(\"bbb\", 6), string.count(\"bbb\", -12))\n    assert string.count(\"ccc\", 6) == string.count(\"ccc\", -12) == 2, (string.count(\"ccc\", 6), string.count(\"ccc\", -12))\n    # out of bounds\n    assert string.count(\"aaa\", 20) == 0\n    assert string.count(\"aaa\", -20) == 1\n    assert string.count(\"bbb\", 20) == 0\n    assert string.count(\"bbb\", -20) == 3\n    assert string.count(\"ccc\", 20) == 0\n    assert string.count(\"ccc\", -20) == 2\ndef test_count_multi_start_end() -> None:\n    string = \"aaabbbcccbbbcccbbb\"\n    assert string.count(\"aaa\", 0, 12) == 1, string.count(\"aaa\", 0, 12)\n    assert string.count(\"bbb\", 0, 12) == 2, string.count(\"bbb\", 0, 12)\n    assert string.count(\"ccc\", 0, 12) == 1, string.count(\"ccc\", 0, 12)\ndef test_count_emoji() -> None:\n    string = \"😴🚀ñ🚀ñ🚀\"\n    assert string.count(\"😴\") == 1, string.count(\"😴\")\n    assert string.count(\"🚀\") == 3, string.count(\"🚀\")\n    assert string.count(\"ñ\") == 2, string.count(\"ñ\")\ndef test_count_start_emoji() -> None:\n    string = \"😴🚀ñ🚀ñ🚀\"\n    assert string.count(\"😴\", 2) == string.count(\"😴\", -4) == 0, (string.count(\"😴\", 2), string.count(\"😴\", -4))\n    assert string.count(\"🚀\", 2) == string.count(\"🚀\", -4) == 2, (string.count(\"🚀\", 2), string.count(\"🚀\", -4))\n    assert string.count(\"ñ\", 2) == string.count(\"ñ\", -4) == 2, (string.count(\"ñ\", 2), string.count(\"ñ\", -4))\n    # Out of bounds\n    assert string.count(\"😴\", 8) == 0, string.count(\"😴\", 8)\n    assert string.count(\"😴\", -8) == 1, string.count(\"😴\", -8)\n    assert string.count(\"🚀\", 8) == 0, string.count(\"🚀\", 8)\n    assert string.count(\"🚀\", -8) == 3, string.count(\"🚀\", -8)\n    assert string.count(\"ñ\", 8) == 0, string.count(\"ñ\", 8)\n    assert string.count(\"ñ\", -8) == 2, string.count(\"ñ\", -8)\ndef test_count_start_end_emoji() -> None:\n    string = \"😴🚀ñ🚀ñ🚀\"\n    assert string.count(\"😴\", 0, 4) == 1, string.count(\"😴\", 0, 4)\n    assert string.count(\"🚀\", 0, 4) == 2, string.count(\"🚀\", 0, 4)\n    assert string.count(\"ñ\", 0, 4) == 1, string.count(\"ñ\", 0, 4)\ndef test_count_multi_emoji() -> None:\n    string = \"😴😴😴🚀🚀🚀ñññ🚀🚀🚀ñññ🚀🚀🚀\"\n    assert string.count(\"😴😴😴\") == 1, string.count(\"😴😴😴\")\n    assert string.count(\"🚀🚀🚀\") == 3, string.count(\"🚀🚀🚀\")\n    assert string.count(\"ñññ\") == 2, string.count(\"ñññ\")\ndef test_count_multi_start_emoji() -> None:\n    string = \"😴😴😴🚀🚀🚀ñññ🚀🚀🚀ñññ🚀🚀🚀\"\n    assert string.count(\"😴😴😴\", 6) == string.count(\"😴😴😴\", -12) == 0, (string.count(\"😴😴😴\", 6), string.count(\"😴😴😴\", -12))\n    assert string.count(\"🚀🚀🚀\", 6) == string.count(\"🚀🚀🚀\", -12) == 2, (string.count(\"🚀🚀🚀\", 6), string.count(\"🚀🚀🚀\", -12))\n    assert string.count(\"ñññ\", 6) == string.count(\"ñññ\", -12) == 2, (string.count(\"ñññ\", 6), string.count(\"ñññ\", -12))\n    # Out of bounds\n    assert string.count(\"😴😴😴\", 20) == 0, string.count(\"😴😴😴\", 20)\n    assert string.count(\"😴😴😴\", -20) == 1, string.count(\"😴😴😴\", -20)\n    assert string.count(\"🚀🚀🚀\", 20) == 0, string.count(\"🚀🚀🚀\", 20)\n    assert string.count(\"🚀🚀🚀\", -20) == 3, string.count(\"🚀🚀🚀\", -20)\n    assert string.count(\"ñññ\", 20) == 0, string.count(\"ñññ\", 20)\n    assert string.count(\"ñññ\", -20) == 2, string.count(\"ñññ\", -20)\ndef test_count_multi_start_end_emoji() -> None:\n    string = \"😴😴😴🚀🚀🚀ñññ🚀🚀🚀ñññ🚀🚀🚀\"\n    assert string.count(\"😴😴😴\", 0, 12) == 1, string.count(\"😴😴😴\", 0, 12)\n    assert string.count(\"🚀🚀🚀\", 0, 12) == 2, string.count(\"🚀🚀🚀\", 0, 12)\n    assert string.count(\"ñññ\", 0, 12) == 1, string.count(\"ñññ\", 0, 12)\n\n[case testIsInstance]\nfrom copysubclass import subc\nfrom typing import Any\ndef test_built_in() -> None:\n    s: Any = str()\n    assert isinstance(s, str)\n    assert isinstance(s + \"test\", str)\n    assert isinstance(s + \"ñññ\", str)\n    assert isinstance(subc(), str)\n    assert isinstance(subc(\"test\"), str)\n    assert isinstance(subc(\"ñññ\"), str)\n\n    assert not isinstance(set(), str)\n    assert not isinstance((), str)\n    assert not isinstance(('a','b'), str)\n    assert not isinstance({'a','b'}, str)\n    assert not isinstance(int() + 1, str)\n    assert not isinstance(['a','b'], str)\n\ndef test_user_defined() -> None:\n    from userdefinedstr import str\n\n    s: Any = \"str\"\n    assert isinstance(str(), str)\n    assert not isinstance(s, str)\n\n[file copysubclass.py]\nfrom typing import Any\nclass subc(str):\n    pass\n\n[file userdefinedstr.py]\nclass str:\n    pass\n\n[case testStrOptionalEquality]\nfrom __future__ import annotations\n\ndef eq_s_opt_s_opt(x: str | None, y: str | None) -> bool:\n    return x == y\n\ndef ne_s_opt_s_opt(x: str | None, y: str | None) -> bool:\n    return x != y\n\ndef test_optional_eq() -> None:\n    s = 'x'\n    assert eq_s_opt_s_opt(s, s)\n    assert eq_s_opt_s_opt(s + str(int()), s + str(int()))\n    assert eq_s_opt_s_opt(None, None)\n\n    assert not eq_s_opt_s_opt('x', 'y')\n    assert not eq_s_opt_s_opt('y', 'x')\n    assert not eq_s_opt_s_opt(None, 'x')\n    assert not eq_s_opt_s_opt('x', None)\n\ndef test_optional_ne() -> None:\n    s = 'x'\n    assert not ne_s_opt_s_opt(s, s)\n    assert not ne_s_opt_s_opt(s + str(int()), s+ str(int()))\n    assert not ne_s_opt_s_opt(None, None)\n\n    assert ne_s_opt_s_opt('x', 'y')\n    assert ne_s_opt_s_opt('y', 'x')\n    assert ne_s_opt_s_opt(None, 'x')\n    assert ne_s_opt_s_opt('x', None)\n\n[case testConstantFoldFormatArgs]\nfrom typing import Final\n\nFMT: Final = \"{} {}\"\n\ndef test_format() -> None:\n    assert FMT.format(400 + 20, \"roll\" + \"up\") == \"420 rollup\"\n\n[case testLowerAndUpper]\nfrom typing import Any\n\ndef test_lower_basic() -> None:\n    assert \"\".lower() == \"\"\n    assert \"hello\".lower() == \"hello\"\n    assert \"HELLO\".lower() == \"hello\"\n    assert \"Hello World\".lower() == \"hello world\"\n    assert \"123\".lower() == \"123\"\n    assert \"ABC123\".lower() == \"abc123\"\n\ndef test_upper_basic() -> None:\n    assert \"\".upper() == \"\"\n    assert \"HELLO\".upper() == \"HELLO\"\n    assert \"hello\".upper() == \"HELLO\"\n    assert \"Hello World\".upper() == \"HELLO WORLD\"\n    assert \"123\".upper() == \"123\"\n    assert \"abc123\".upper() == \"ABC123\"\n\ndef test_lower_unicode() -> None:\n    assert \"\\u00C9\".lower() == \"\\u00E9\"                # É -> é\n    assert \"\\u0391\\u0392\".lower() == \"\\u03B1\\u03B2\"    # ΑΒ -> αβ\n    assert \"\\u4E2D\\u6587\".lower() == \"\\u4E2D\\u6587\"    # CJK (no case)\n    assert \"\\U0001F600\".lower() == \"\\U0001F600\"         # Emoji (no case)\n\ndef test_upper_unicode() -> None:\n    assert \"\\u00E9\".upper() == \"\\u00C9\"                # é -> É\n    assert \"\\u03B1\\u03B2\".upper() == \"\\u0391\\u0392\"    # αβ -> ΑΒ\n    assert \"\\u4E2D\\u6587\".upper() == \"\\u4E2D\\u6587\"    # CJK (no case)\n    assert \"\\U0001F600\".upper() == \"\\U0001F600\"         # Emoji (no case)\n\ndef test_expansion() -> None:\n    # 1-to-N expansion cases\n    assert \"\\u0130\".lower() == \"\\u0069\\u0307\"  # İ -> i + combining dot above\n    assert \"\\uFB03\".lower() == \"\\uFB03\"        # ffi ligature stays lowercase\n    assert \"\\u00DF\".upper() == \"SS\"            # ß -> SS\n    assert \"\\uFB03\".upper() == \"FFI\"           # ffi ligature -> FFI\n\ndef test_comprehensive() -> None:\n    for i in range(0x110000):\n        c = chr(i)\n        a: Any = c\n        assert c.lower() == a.lower(), f\"lower mismatch at U+{i:04X}\"\n        assert c.upper() == a.upper(), f\"upper mismatch at U+{i:04X}\"\n\n[case testIsSpace]\nfrom typing import Any\n\ndef test_isspace() -> None:\n    # Verify correctness across all Unicode codepoints.\n    # Exercises UCS-1 (0x00-0xFF), UCS-2 (0x100-0xFFFF), and UCS-4 (0x10000-x10FFFF inclusive) string kinds.\n    # Any forces generic dispatch so we compare our primitive against stdlib's\n    for i in range(0x110000):\n        c = chr(i)\n        a: Any = c\n        assert c.isspace() == a.isspace()\n\n[case testIsAlnum]\ndef test_isalnum_basic() -> None:\n    assert \"abc\".isalnum()\n    assert \"ABC\".isalnum()\n    assert \"abc123\".isalnum()\n    assert \"123\".isalnum()\n    assert not \"\".isalnum()\n    assert not \" \".isalnum()\n    assert not \"abc!\".isalnum()\n    assert not \"hello world\".isalnum()\n    assert not \"abc-123\".isalnum()\n\ndef test_isalnum_unicode() -> None:\n    # Single chars: letters and digits from various scripts\n    assert \"\\u00E9\".isalnum()        # é  (UCS-1 Latin letter)\n    assert \"\\u0660\".isalnum()        # ٠  (UCS-2 Arabic-Indic digit)\n    assert \"\\u4E2D\".isalnum()        # 中 (UCS-2 CJK ideograph)\n    assert \"\\U00010400\".isalnum()    # 𐐀 (UCS-4 Deseret capital letter long I)\n    assert not \"\\u2000\".isalnum()    # EN QUAD (whitespace)\n    assert not \"\\u0021\".isalnum()    # !\n    assert not \"\\u00B6\".isalnum()    # ¶  (pilcrow sign, punctuation)\n\n    # Mixed Unicode letters and digits — all alnum\n    assert \"\\u00E9\\u0660\".isalnum()         # é٠\n    assert \"\\u4E2D\\u0041\\u0660\".isalnum()   # 中A٠\n\n    # Unicode letter/digit mixed with punctuation — not alnum\n    assert not \"\\u00E9!\".isalnum()\n    assert not \"\\u4E2D\\u2000\".isalnum()     # CJK + whitespace\n\n[case testIsDigit]\nfrom typing import Any\n\ndef test_isdigit() -> None:\n    for i in range(0x110000):\n        c = chr(i)\n        a: Any = c\n        assert c.isdigit() == a.isdigit()\n\ndef test_isdigit_strings() -> None:\n    # ASCII digits\n    assert \"0123456789\".isdigit()\n    assert not \"\".isdigit()\n    assert not \" \".isdigit()\n    assert not \"a\".isdigit()\n    assert not \"abc\".isdigit()\n    assert not \"!@#\".isdigit()\n\n    # Mixed ASCII\n    assert not \"123abc\".isdigit()\n    assert not \"abc123\".isdigit()\n    assert not \"12 34\".isdigit()\n    assert not \"123!\".isdigit()\n\n    # Unicode digits\n    assert \"\\u0660\\u0661\\u0662\".isdigit()\n    assert \"\\u00b2\\u00b3\".isdigit()\n    assert \"123\\U0001d7ce\\U0001d7cf\\U0001d7d0\".isdigit()\n\n    # Mixed digits and Unicode non-digits\n    assert not \"\\u00e9\\u00e8\".isdigit()\n    assert not \"123\\u00e9\".isdigit()\n    assert not \"\\U0001d7ce!\".isdigit()\n"
  },
  {
    "path": "mypyc/test-data/run-traits.test",
    "content": "[case testTraitBasic1]\nfrom mypy_extensions import trait\n\nclass A:\n    line: int\n    def foo(self) -> None:\n        print(\"foo\")\n\n@trait\nclass T:\n    def bar(self) -> None:\n        print(\"bar\")\n    def baz(self) -> object:\n        return None\n\nclass C(A, T):\n    def baz(self) -> int:\n        return 10\n\ndef use_t(t: T) -> object:\n    t.bar()\n    return t.baz()\n\ndef use_c(c: C) -> int:\n    use_t(c)\n    c.foo()\n    c.bar()\n    return c.baz()\n\nuse_t(C())\n\n# This trait is dead code but there's no reason it shouldn't compile\n@trait\nclass ChildlessTrait:\n    def __init__(self) -> None:\n        pass\n\n[file driver.py]\nfrom native import A, T, C, use_c, use_t\nc = C()\nc.foo()\nc.bar()\nassert c.baz() == 10\nassert use_c(c) == 10\nassert use_t(c) == 10\n[out]\nbar\nfoo\nbar\nbar\nfoo\nbar\nbar\n\n[case testTraitBasic2]\nfrom mypy_extensions import trait\n\nclass A:\n    line: int\n    def foo(self) -> None:\n        print(\"foo\")\n\n@trait\nclass T:\n    def bar(self) -> None:\n        print(\"bar\", self.baz())\n    def baz(self) -> int:\n        return -1\n\n@trait\nclass T2:\n    line: int\n    def baz(self) -> int:\n        return -2\n\nclass C(A, T):\n    def __init__(self) -> None:\n        self.line = 1337\n        self.x = 12\n    def baz(self) -> int:\n        return self.x\n\nclass D(C, T2):\n    def __init__(self) -> None:\n        self.line = 1337\n        self.x = 13\n\n@trait\nclass T3:\n    def baz(self) -> int:\n        return -2\n\nclass E(T3):\n    def __init__(self) -> None:\n        pass\n\n\ndef use_t(t: T) -> None:\n    t.bar()\ndef use_t2(t: T2) -> int:\n    t.line = t.line\n    return t.line\n\ndef use_c(c: C) -> int:\n    use_t(c)\n    c.foo()\n    c.bar()\n    return c.line\n\ndef use_d(d: D) -> int:\n    return d.baz()\n\n[file driver.py]\nfrom native import A, T, C, D, use_c, use_t, use_d, use_t2\nc = C()\nd = D()\nc.foo()\nc.bar()\nprint(\"baz\", c.baz())\nprint(\"baz\", d.baz())\nuse_c(c)\nuse_t(c)\nuse_c(d)\nuse_t(d)\nassert use_d(d) == 13\nprint(d.line)\nassert d.line == 1337\nassert use_t2(d) == 1337\n[out]\nfoo\nbar 12\nbaz 12\nbaz 13\nbar 12\nfoo\nbar 12\nbar 12\nbar 13\nfoo\nbar 13\nbar 13\n1337\n\n[case testTrait3]\nfrom mypy_extensions import trait\nfrom typing import Generic, TypeVar\n\n@trait\nclass T1: pass\n@trait\nclass T2: pass\n\nT = TypeVar('T')\n\nclass C(Generic[T], T1, T2):\n    pass\n\n@trait\nclass S1(Generic[T]):\n    def foo(self) -> None: pass\n    def bar(self, x: T) -> T: raise Exception\n\n@trait\nclass S2(S1[T]):\n    def bar(self, x: T) -> T: return x\n\n@trait\nclass S3(S2[T]):\n    def bar(self, x: T) -> T: return x\n\nclass D(S3[bool]):\n    def bar(self, x: bool) -> bool: return x\n\n\n[file driver.py]\nimport native\n\n[case testTrait4]\nfrom mypy_extensions import trait\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\n\n@trait\nclass S1(Generic[T]):\n    def bar(self) -> T: raise Exception\n\nclass S2(S1[bool]):\n    def bar(self) -> bool: return False\n\nclass D(S2):\n    pass\n\ndef lol(x: S1) -> None:\n    x.bar()\n\n[file driver.py]\nimport native\nnative.lol(native.D())\n\n[case testTraitOrdering]\nimport other_b\n# Regression test for a bug where inheriting from a class that\n# inherited from a trait that got processed later on the command line\n# filed to compile.\n[file other_b.py]\nfrom other_c import Plugin\n\nclass Whatever(Plugin):\n    pass\n\n[file other_c.py]\nfrom mypy_extensions import trait\n\n@trait\nclass Base:\n    x: int\n\nclass Plugin(Base):\n    def __init__(self) -> None:\n        self.x = 10\n\n[file driver.py]\nfrom native import *\n\n[case testDiamond]\nfrom mypy_extensions import trait\n\n@trait\nclass Base:\n    def get_value(self) -> str:\n        return \"Base\"\n\n@trait\nclass Trait(Base):\n    def get_value(self) -> str:\n        return \"Trait\"\n\nclass Message(Base):\n    def show_message(self) -> None:\n        print(\"I am a \" + self.get_value())\n\nclass DerivedMessage(Message, Trait):\n    pass\n\n[file driver.py]\nfrom native import *\na = Message()\na.show_message()\nb = DerivedMessage()\nb.show_message()\n\n[out]\nI am a Base\nI am a Trait\n\n[case testTraitAttrsSubTrait]\nfrom mypy_extensions import trait\n\nclass A:\n    a: int\n\n@trait\nclass T1:\n    x: int\n\n@trait\nclass T2(T1):\n    y: int\n\nclass C(A, T2):\n    c: int\n\ndef f(t1: T1, t2: T2) -> None:\n    t1.x, t2.x = t2.x, t1.x\n\ndef g(t1: T1, t2: T2) -> None:\n    t2.y = t1.x\n\ndef get_x(c: C) -> int:\n    return c.x\n\ndef get_y(c: C) -> int:\n    return c.y\n\n[file driver.py]\nfrom native import C, f, g, get_x, get_y\n\nc1 = C()\nc2 = C()\n\nc1.x = 1\nc1.y = 0\nc2.x = 2\nc2.y = 0\n\nf(c1, c2)\nassert c1.x == 2\nassert c2.x == 1\nassert get_x(c1) == 2\nassert get_x(c2) == 1\n\nassert get_y(c2) == 0\ng(c1, c2)\nassert get_y(c2) == 2\n[out]\n\n[case testTraitAttrsTriangle]\nfrom mypy_extensions import trait\n\nclass A:\n    a: int\n\n@trait\nclass T(A):\n    x: int\n    def meth(self) -> int:\n        return self.a\n\nclass B(A):\n    b: int\n\nclass C(B, T):\n    pass\n\ndef take_t(t: T) -> int:\n    return t.x + t.meth()\n\ndef take_c(c: C) -> int:\n    return c.x + c.meth()\n\n[file driver.py]\nfrom native import C, take_t, take_c\n\nc = C()\nc.a = 1\nc.x = 10\n\nassert take_t(c) == take_c(c) == 11\n[out]\n\n[case testTraitAttrsTree]\nfrom mypy_extensions import trait\n\nclass A:\n    a: int\n\n@trait\nclass T1:\n    x: int\n\nclass B(A, T1):\n    b: int\n\n@trait\nclass T2:\n    x: int\n\nclass C(B, T2):\n    pass\n\ndef f(t1: T1, t2: T2) -> None:\n    t1.x, t2.x = t2.x, t1.x\n\ndef g(c1: C, c2: C) -> None:\n    c1.x, c2.x = c2.x, c1.x\n\n[file driver.py]\nfrom native import C, f, g\n\nc1 = C()\nc2 = C()\n\nc1.x = 1\nc2.x = 2\n\nf(c1, c2)\nassert c1.x == 2\nassert c2.x == 1\n\ng(c1, c2)\nassert c1.x == 1\nassert c2.x == 2\n[out]\n\n[case testTraitErrorMessages]\nfrom mypy_extensions import trait\n\n@trait\nclass Trait:\n    pass\n\ndef create() -> Trait:\n    return Trait()\n\n[file driver.py]\nfrom native import Trait, create\nfrom testutil import assertRaises\n\nwith assertRaises(TypeError, \"traits may not be directly created\"):\n    Trait()\n\nwith assertRaises(TypeError, \"traits may not be directly created\"):\n    create()\n\nclass Sub(Trait):\n    pass\n\nwith assertRaises(TypeError, \"interpreted classes cannot inherit from compiled traits\"):\n    Sub()\n"
  },
  {
    "path": "mypyc/test-data/run-tuples.test",
    "content": "# Test cases for tuples (compile and run)\n\n[case testTuple]\nfrom typing import List, Optional, Tuple\nfrom typing import Tuple\ndef f(x: Tuple[int, int]) -> Tuple[int,int]:\n    return x\n\ndef lurr(x: List[Optional[Tuple[int, str]]]) -> object:\n    return x[0]\n\ndef asdf(x: Tuple[int, str]) -> None:\n    pass\n[file driver.py]\nfrom testutil import assertRaises\nfrom native import f, lurr, asdf\n\nassert f((1,2)) == (1, 2)\nassert lurr([(1, '2')]) == (1, '2')\n\nwith assertRaises(TypeError):\n    print(lurr([(1, 2)]))\n\nwith assertRaises(TypeError):\n    asdf((1, 2))\n\n[case testTupleGet]\nfrom typing import Tuple\ndef f(x: Tuple[Tuple[int, bool], int]) -> int:\n    return x[0][0]\n[file driver.py]\nfrom native import f\nprint(f(((1,True),2)))\nbig_number = pow(2, 80)\nprint(f(((big_number,True),2)))\n[out]\n1\n1208925819614629174706176\n\n[case testSequenceTupleArg]\nfrom typing import Tuple\ndef f(x: Tuple[int, ...]) -> int:\n    return x[1]\n[file driver.py]\nfrom native import f\nprint(f((1,2,3,4)))\n[out]\n2\n\n[case testTupleAttr]\nfrom typing import Tuple\nclass C:\n    b: Tuple[Tuple[Tuple[int, int], int], int, str, object]\n    c: Tuple[()]\ndef f() -> None:\n    c = C()\n    c.b = (((1, 2), 2), 1, 'hi', 'hi2')\n    print(c.b)\n\ndef g() -> None:\n    try:\n        h()\n    except Exception:\n        print('caught the exception')\n\ndef h() -> Tuple[Tuple[Tuple[int, int], int], int, str, object]:\n    raise Exception('Intentional exception')\n[file driver.py]\nfrom native import f, g, C\nf()\ng()\nassert not hasattr(C(), 'c')\n[out]\n(((1, 2), 2), 1, 'hi', 'hi2')\ncaught the exception\n\n[case testNamedTupleAttributeRun]\nfrom typing import NamedTuple\n\nNT = NamedTuple('NT', [('x', int), ('y', int)])\n\ndef f(nt: NT) -> int:\n    if nt.x > nt.y:\n        return nt.x\n    return nt.y\n\nnt = NT(1, 2)\n[file driver.py]\nfrom native import NT, nt, f\n\nassert f(nt) == 2\nassert f(NT(3, 2)) == 3\n\nclass Sub(NT):\n    pass\nassert f(Sub(3, 2)) == 3\n\n-- Ref: https://github.com/mypyc/mypyc/issues/924\n[case testNamedTupleClassSyntax]\nfrom typing import Dict, List, NamedTuple, Optional, Tuple, Union, final\n\nclass FuncIR: pass\n\nStealsDescription = Union[bool, List[bool]]\n\nclass Record(NamedTuple):\n    st_mtime: float\n    st_size: int\n    is_borrowed: bool\n    hash: str\n    python_path: Tuple[str, ...]\n    type: 'ClassIR'\n    method: FuncIR\n    shadow_method: Optional[FuncIR]\n    classes: Dict[str, 'ClassIR']\n    steals: StealsDescription\n    ordering: Optional[List[int]]\n    extra_int_constants: List[Tuple[int]]\n\n# Make sure mypyc loads the annotation string for this forward reference.\n# Ref: https://github.com/mypyc/mypyc/issues/938\nclass ClassIR: pass\n\n# Ref: https://github.com/mypyc/mypyc/issues/927\n@final\nclass Inextensible(NamedTuple):\n    x: int\n\n[file driver.py]\nimport sys\nfrom typing import Optional\nfrom native import ClassIR, FuncIR, Record\n\nHAVE_TEST = False\nif sys.version_info >= (3, 14):\n    try:\n        from test.support import EqualToForwardRef\n        type_forward_ref = EqualToForwardRef\n        HAVE_TEST = True\n    except ImportError as e:\n        # catch the case of a pymanager installed Python\n        # without the test module. It is excluded by default\n        # on Windows.\n        msg = 'Missing \"test\" module.'\n        if sys.platform == \"win32\":\n            msg += (' Please install a version of Python with the test module.'\n                   ' If you are using pymanager, try running pymanager install --force PythonTest\\\\<version>')\n        raise ImportError(msg) from e\n\nif not HAVE_TEST:\n    from typing import ForwardRef\n    type_forward_ref = ForwardRef\n\nassert Record.__annotations__ == {\n    'st_mtime': float,\n    'st_size': int,\n    'is_borrowed': bool,\n    'hash': str,\n    'python_path': tuple,\n    'type': type_forward_ref('ClassIR'),\n    'method': FuncIR,\n    'shadow_method': type,\n    'classes': dict,\n    'steals': type,\n    'ordering': type,\n    'extra_int_constants': list,\n}, Record.__annotations__\n\n[case testTupleOps]\nfrom typing import Tuple, Final, List, Any, Optional, cast\nfrom testutil import assertRaises\n\ndef f() -> Tuple[()]:\n    return ()\n\ndef test_empty_tuple() -> None:\n    assert f() == ()\n\ndef f2() -> Any:\n    return ()\n\ndef test_empty_tuple_with_any_type():\n    assert f2() == ()\n\ndef f3() -> int:\n    x = (False, 1)\n    return x[1]\n\ndef test_new_tuple() -> None:\n    assert f3() == 1\n\ndef f4(y: int) -> int:\n    x = (False, y)\n    return x[1]\n\ndef test_new_tuple_boxed_int() -> None:\n    big_number = 1208925819614629174706176\n    assert f4(big_number) == big_number\n\ndef f5(x: List[int]) -> int:\n    return tuple(x)[1]\n\ndef test_sequence_tuple() -> None:\n    assert f5([1,2,3,4]) == 2\n\ndef f6(x: List[int]) -> int:\n    return len(tuple(x))\n\ndef test_sequence_tuple_len() -> None:\n    assert f6([1,2,3,4]) == 4\n\ndef f7(x: List[Tuple[int, int]]) -> int:\n    a, b = x[0]\n    return a + b\n\ndef test_unbox_tuple() -> None:\n    assert f7([(5, 6)]) == 11\n\ndef test_comparison() -> None:\n    assert ('x','y') == ('x','y')\n    assert not(('x','y') != ('x','y'))\n\n    assert ('x','y') != ('x','y',1)\n    assert not(('x','y') == ('x','y',1))\n\n    assert ('x','y',1) != ('x','y')\n    assert not(('x','y',1) == ('x','y'))\n\n    assert ('x','y') != ()\n    assert not(('x','y') == ())\n\n    assert () != ('x','y')\n    assert not(() == ('x','y'))\n\n# Test that order is irrelevant to unions. Really I only care that this builds.\n\nclass A:\n    pass\n\ndef lol() -> A:\n    return A()\n\ndef foo(x: bool, y: bool) -> Tuple[Optional[A], bool]:\n    z = lol()\n\n    return None if y else z, x\n\ndef test_slicing() -> None:\n    # Use dummy adds to avoid constant folding\n    zero = int()\n    two = zero + 2\n    s: Tuple[str, ...] = (\"f\", \"o\", \"o\", \"b\", \"a\", \"r\")\n    assert s[two:] == (\"o\", \"b\", \"a\", \"r\")\n    assert s[:two] == (\"f\", \"o\")\n    assert s[two:-two] == (\"o\", \"b\")\n    assert s[two:two] == ()\n    assert s[two:two + 1] == (\"o\",)\n    assert s[-two:] == (\"a\", \"r\")\n    assert s[:-two] == (\"f\", \"o\", \"o\", \"b\")\n    assert s[:] == (\"f\", \"o\", \"o\", \"b\", \"a\", \"r\")\n    assert s[two:333] == (\"o\", \"b\", \"a\", \"r\")\n    assert s[333:two] == ()\n    assert s[two:-333] == ()\n    assert s[-333:two] == (\"f\", \"o\")\n    long_int: int = 1000 * 1000 * 1000 * 1000 * 1000 * 1000 * 1000\n    assert s[1:long_int] == (\"o\", \"o\", \"b\", \"a\", \"r\")\n    assert s[long_int:] == ()\n    assert s[-long_int:-1] == (\"f\", \"o\", \"o\", \"b\", \"a\")\n\ndef f8(val: int) -> bool:\n    return val % 2 == 0\n\nabc: Final = \"abc\"\n\ndef known_length() -> tuple[str, ...]:\n    return tuple(str(x) for x in [*abc, *\"def\", *b\"ghi\", (\"j\", \"k\"), *(\"l\", \"m\", \"n\")])\n\ndef test_sequence_generator() -> None:\n    source_list = [1, 2, 3]\n    a = tuple(f8(x) for x in source_list)\n    assert a == (False, True, False)\n\n    source_tuple: Tuple[int, ...] = (1, 2, 3)\n    a = tuple(f8(x) for x in source_tuple)\n    assert a == (False, True, False)\n\n    source_fixed_length_tuple = (1, 2, 3, 4)\n    a = tuple(f8(x) for x in source_fixed_length_tuple)\n    assert a == (False, True, False, True)\n\n    source_str = 'abbc'\n    b = tuple('s:' + x for x in source_str)\n    assert b == ('s:a', 's:b', 's:b', 's:c')\n\n    assert known_length() == ('a', 'b', 'c', 'd', 'e', 'f', '103', '104', '105', \"('j', 'k')\", 'l', 'm', 'n')\n\nTUPLE: Final[Tuple[str, ...]] = ('x', 'y')\n\ndef test_final_boxed_tuple() -> None:\n    t = TUPLE\n    assert t == ('x', 'y')\n    assert 'x' in TUPLE\n    assert 'y' in TUPLE\n    b: object = 'z' in TUPLE\n    assert not b\n    assert 'z' not in TUPLE\n    b2: object = 'x' not in TUPLE\n    assert not b2\n    b3: object = 'y' not in TUPLE\n    assert not b3\n\nTUP2: Final = ('x', 'y')\nTUP1: Final = ('x',)\nTUP0: Final = ()\n\ndef test_final_tuple_in() -> None:\n    assert 'x' + str() in TUP2\n    assert 'y' + str() in TUP2\n    b: object = 'z' + str() in TUP2\n    assert not b\n\n    assert 'x' + str() in TUP1\n    b2: object = 'y' in TUP1\n    assert not b2\n\n    b3: object = 'x' in TUP0\n    assert not b3\n\ndef test_final_tuple_not_in() -> None:\n    assert 'z' + str() not in TUP2\n    b: object = 'x' + str() not in TUP2\n    assert not b\n    b2: object = 'y' + str() not in TUP2\n    assert not b2\n\n    assert 'y' + str() not in TUP1\n    b3: object = 'x' not in TUP1\n    assert not b2\n\n    assert 'x' not in TUP0\n\nlog = []\n\ndef f_a() -> str:\n    log.append('f_a')\n    return 'a'\n\ndef f_a2() -> str:\n    log.append('f_a2')\n    return 'a'\n\ndef f_b() -> str:\n    log.append('f_b')\n    return 'b'\n\ndef f_c() -> str:\n    log.append('f_c')\n    return 'c'\n\ndef test_tuple_in_order_of_evaluation() -> None:\n    log.clear()\n    assert f_a() in (f_b(), f_a2())\n    assert log ==[\"f_a\", \"f_b\", \"f_a2\"]\n\n    log.clear()\n    assert f_a() not in (f_b(), f_c())\n    assert log ==[\"f_a\", \"f_b\", \"f_c\"]\n\n    log.clear()\n    assert f_a() in (f_b(), f_a2(), f_c())\n    assert log ==[\"f_a\", \"f_b\", \"f_a2\", \"f_c\"]\n\ndef f_t() -> tuple[str, ...]:\n    log.append('f_t')\n    return ('x', 'a')\n\ndef test_tuple_in_non_specialized() -> None:\n    log.clear()\n    assert f_a() in f_t()\n    assert log == [\"f_a\", \"f_t\"]\n\n    log.clear()\n    assert f_b() not in f_t()\n    assert log == [\"f_b\", \"f_t\"]\n\ndef test_add() -> None:\n    res = (1, 2, 3, 4)\n    assert (1, 2) + (3, 4) == res\n    with assertRaises(TypeError, 'can only concatenate tuple (not \"list\") to tuple'):\n        assert (1, 2) + cast(Any, [3, 4]) == res\n\ndef multiply(a: Tuple[Any, ...], b: int) -> Tuple[Any, ...]:\n    return a * b\n\ndef test_multiply() -> None:\n    res = (1, 1, 1)\n    assert (1,) * 3 == res\n    assert 3 * (1,) == res\n    assert multiply((1,), 3) == res\n\n[case testIsInstance]\nfrom copysubclass import subc\ndef test_built_in() -> None:\n    assert isinstance((), tuple)\n    assert isinstance((1, 2), tuple)\n    assert isinstance(('a', 'b', 'c'), tuple)\n    assert isinstance(subc(()), tuple)\n    assert isinstance(subc((1, 2)), tuple)\n    assert isinstance(subc(('a', 'b', 'c')), tuple)\n\n    assert not isinstance(set(), tuple)\n    assert not isinstance({}, tuple)\n    assert not isinstance([1,2,3], tuple)\n    assert not isinstance({'a','b'}, tuple)\n    assert not isinstance(int() + 1, tuple)\n    assert not isinstance(str() + 'a', tuple)\n\ndef test_user_defined() -> None:\n    from userdefinedtuple import tuple\n\n    assert isinstance(tuple(), tuple)\n    assert not isinstance((1, tuple()), tuple)\n\n[file copysubclass.py]\nfrom typing import Any\nclass subc(tuple[Any]):\n    pass\n\n[file userdefinedtuple.py]\nclass tuple:\n    pass\n"
  },
  {
    "path": "mypyc/test-data/run-u8.test",
    "content": "[case testU8BasicOps]\nfrom typing import Any, Final, Tuple\n\nfrom mypy_extensions import u8, i16, i32, i64\n\nfrom testutil import assertRaises\n\nERROR: Final = 239\n\ndef test_box_and_unbox() -> None:\n    for i in range(0, 256):\n        o: Any = i\n        x: u8 = o\n        o2: Any = x\n        assert o == o2\n        assert x == i\n    with assertRaises(ValueError, \"int too large or small to convert to u8\"):\n        o = 256\n        x2: u8 = o\n    with assertRaises(ValueError, \"int too large or small to convert to u8\"):\n        o = -1\n        x3: u8 = o\n\ndef div_by_7(x: u8) -> u8:\n    return x // 7\n\ndef div(x: u8, y: u8) -> u8:\n    return x // y\n\ndef test_divide_by_constant() -> None:\n    for i in range(0, 256):\n        assert div_by_7(i) == i // 7\n\ndef test_divide_by_variable() -> None:\n    for x in range(0, 256):\n        for y in range(0, 256):\n            if y != 0:\n                assert div(x, y) == x // y\n            else:\n                with assertRaises(ZeroDivisionError, \"integer division or modulo by zero\"):\n                    div(x, y)\n\ndef mod_by_7(x: u8) -> u8:\n    return x % 7\n\ndef mod(x: u8, y: u8) -> u8:\n    return x % y\n\ndef test_mod_by_constant() -> None:\n    for i in range(0, 256):\n        assert mod_by_7(i) == i % 7\n\ndef test_mod_by_variable() -> None:\n    for x in range(0, 256):\n        for y in range(0, 256):\n            if y != 0:\n                assert mod(x, y) == x % y\n            else:\n                with assertRaises(ZeroDivisionError, \"integer division or modulo by zero\"):\n                    mod(x, y)\n\ndef test_simple_arithmetic_ops() -> None:\n    zero: u8 = int()\n    one: u8 = zero + 1\n    two: u8 = one + 1\n    neg_one: u8 = -one\n    assert neg_one == 255\n    assert one + one == 2\n    assert one + two == 3\n    assert one + neg_one == 0\n    assert one - one == 0\n    assert one - two == 255\n    assert one * one == 1\n    assert one * two == 2\n    assert two * two == 4\n    assert two * neg_one == 254\n    assert neg_one * one == 255\n    assert neg_one * neg_one == 1\n    assert two * 0 == 0\n    assert 0 * two == 0\n    assert -one == 255\n    assert -two == 254\n    assert -neg_one == 1\n    assert -zero == 0\n\ndef test_bitwise_ops() -> None:\n    x: u8 = 184 + int()\n    y: u8 = 79 + int()\n    z: u8 = 113 + int()\n    zero: u8 = int()\n    one: u8 = zero + 1\n    two: u8 = zero + 2\n    neg_one: u8 = -one\n\n    assert x & y == 8\n    assert x & z == 48\n    assert z & z == z\n    assert x & zero == 0\n\n    assert x | y == 255\n    assert x | z == 249\n    assert z | z == z\n    assert x | 0 == x\n\n    assert x ^ y == 247\n    assert x ^ z == 201\n    assert z ^ z == 0\n    assert z ^ 0 == z\n\n    assert x << one == 112\n    assert x << two == 224\n    assert z << two == 196\n    assert z << 0 == z\n\n    assert x >> one == 92\n    assert x >> two == 46\n    assert z >> two == 28\n    assert z >> 0 == z\n\n    for i in range(256):\n        t: u8 = i\n        assert ~t == (~(i + int()) & 0xff)\n\ndef eq(x: u8, y: u8) -> bool:\n    return x == y\n\ndef test_eq() -> None:\n    assert eq(int(), int())\n    assert eq(5 + int(), 5 + int())\n    assert not eq(int(), 1 + int())\n    assert not eq(5 + int(), 6 + int())\n\ndef test_comparisons() -> None:\n    one: u8 = 1 + int()\n    one2: u8 = 1 + int()\n    two: u8 = 2 + int()\n    assert one < two\n    assert not (one < one2)\n    assert not (two < one)\n    assert two > one\n    assert not (one > one2)\n    assert not (one > two)\n    assert one <= two\n    assert one <= one2\n    assert not (two <= one)\n    assert two >= one\n    assert one >= one2\n    assert not (one >= two)\n    assert one == one2\n    assert not (one == two)\n    assert one != two\n    assert not (one != one2)\n\ndef test_mixed_comparisons() -> None:\n    u8_3: u8 = int() + 3\n    int_5 = int() + 5\n    assert u8_3 < int_5\n    assert int_5 > u8_3\n    b = u8_3 > int_5\n    assert not b\n\n    int_largest = int() + 255\n    assert int_largest > u8_3\n    int_smallest = int()\n    assert u8_3 > int_smallest\n\n    int_too_big = int() + 256\n    int_too_small = int() -1\n    with assertRaises(ValueError):\n        assert u8_3 < int_too_big\n    with assertRaises(ValueError):\n        assert int_too_big < u8_3\n    with assertRaises(ValueError):\n        assert u8_3 > int_too_small\n    with assertRaises(ValueError):\n        assert int_too_small < u8_3\n\ndef test_mixed_arithmetic_and_bitwise_ops() -> None:\n    u8_3: u8 = int() + 3\n    int_5 = int() + 5\n    assert u8_3 + int_5 == 8\n    assert int_5 - u8_3 == 2\n    assert u8_3 << int_5 == 96\n    assert int_5 << u8_3  == 40\n    assert u8_3 ^ int_5 == 6\n    assert int_5 | u8_3  == 7\n\n    int_largest = int() + 255\n    assert int_largest - u8_3 == 252\n    int_smallest = int()\n    assert int_smallest + u8_3 == 3\n\n    int_too_big = int() + 256\n    int_too_small = int() - 1\n    with assertRaises(ValueError):\n        assert u8_3 & int_too_big\n    with assertRaises(ValueError):\n        assert int_too_small & u8_3\n\ndef test_coerce_to_and_from_int() -> None:\n    for n in range(0, 256):\n        x: u8 = n\n        m: int = x\n        assert m == n\n\ndef test_explicit_conversion_to_u8() -> None:\n    x = u8(5)\n    assert x == 5\n    y = int() + ERROR\n    x = u8(y)\n    assert x == ERROR\n    n64: i64 = 233\n    x = u8(n64)\n    assert x == 233\n    n32: i32 = 234\n    x = u8(n32)\n    assert x == 234\n    z = u8(x)\n    assert z == 234\n    n16: i16 = 231\n    x = u8(n16)\n    assert x == 231\n\ndef test_explicit_conversion_overflow() -> None:\n    max_u8 = int() + 255\n    x = u8(max_u8)\n    assert x == 255\n    assert int(x) == max_u8\n\n    min_u8 = int()\n    y = u8(min_u8)\n    assert y == 0\n    assert int(y) == min_u8\n\n    too_big = int() + 256\n    with assertRaises(ValueError):\n        x = u8(too_big)\n\n    too_small = int() - 1\n    with assertRaises(ValueError):\n        x = u8(too_small)\n\ndef test_u8_from_large_small_literal() -> None:\n    x = u8(255) # XXX u8(2**15 - 1)\n    assert x == 255\n    x = u8(0)\n    assert x == 0\n\ndef test_u8_truncate_from_i64() -> None:\n    large = i64(2**32 + 256 + 157 + int())\n    x = u8(large)\n    assert x == 157\n    small = i64(-2**32 - 256 - 157 + int())\n    x = u8(small)\n    assert x == 256 - 157\n    large2 = i64(2**8 + int())\n    x = u8(large2)\n    assert x == 0\n    small2 = i64(-2**8 - 1 - int())\n    x = u8(small2)\n    assert x == 255\n\ndef test_u8_truncate_from_i32() -> None:\n    large = i32(2**16 + 2**8 + 5 + int())\n    assert u8(large) == 5\n    small = i32(-2**16 - 2**8 - 1 + int())\n    assert u8(small) == 255\n\ndef from_float(x: float) -> u8:\n    return u8(x)\n\ndef test_explicit_conversion_from_float() -> None:\n    assert from_float(0.0) == 0\n    assert from_float(1.456) == 1\n    assert from_float(234.567) == 234\n    assert from_float(255) == 255\n    assert from_float(0) == 0\n    assert from_float(-0.999) == 0\n    # The error message could be better, but this is acceptable\n    with assertRaises(ValueError, \"int too large or small to convert to u8\"):\n        assert from_float(float(256))\n    with assertRaises(ValueError, \"int too large or small to convert to u8\"):\n        # One ulp below the lowest valid i64 value\n        from_float(float(-1.0))\n\ndef test_tuple_u8() -> None:\n    a: u8 = 1\n    b: u8 = 2\n    t = (a, b)\n    a, b = t\n    assert a == 1\n    assert b == 2\n    x: Any = t\n    tt: Tuple[u8, u8] = x\n    assert tt == (1, 2)\n\ndef test_convert_u8_to_native_int() -> None:\n    for i in range(256):\n        x: u8 = i\n        assert i16(x) == i\n        assert i32(x) == i\n        assert i64(x) == i\n"
  },
  {
    "path": "mypyc/test-data/run-vecs-i64-interp.test",
    "content": "[case testLibrtVecsI64Interpreted_librt_experimental]\n# Test cases for vec[i64], using generic operations (simulates use from interpreted code).\n#\n# These also act as test cases for specialized vec types in general (e.g. vec[float]),\n# since much of the implementation is shared between all of them.\n#\n# There is also run-vecs-misc-interp.test with limited test coverage for vec[float] etc.\n\nimport sys\nfrom typing import Any\nimport typing\n\nimport librt.vecs\nimport mypy_extensions\n\nfrom testutil import assertRaises, is_gil_disabled, is_64_bit_platform\n\n# Access via Any references to force generic operations\nvec: Any = librt.vecs.vec\nappend: Any = librt.vecs.append\nremove: Any = librt.vecs.remove\npop: Any = librt.vecs.pop\ngetsizeof: Any = getattr(sys, \"getsizeof\")\ni64: Any = mypy_extensions.i64\n\n# Work around test stub limitations\nOptional: Any = getattr(getattr(sys, \"modules\")[\"typing\"], \"Optional\")\n\ndef test_construct_from_initializer() -> None:\n    v = vec[i64]([123])\n    assert len(v) == 1\n    assert v[0] == 123\n    v = vec[i64](x + 1 for x in [5, 7, -8, 10])\n    assert len(v) == 4\n    assert v[0] == 6\n    assert v[1] == 8\n    assert v[2] == -7\n    assert v[3] == 11\n    with assertRaises(TypeError):\n        vec[i64](1)\n    with assertRaises(TypeError):\n        vec[i64](['1'])\n    with assertRaises(TypeError):\n        vec[i64]([None])\n\ndef test_append() -> None:\n    v = vec[i64]()\n    v = append(v, 1)\n    assert str(v) == \"vec[i64]([1])\"\n    for n in range(2, 10):\n        v = append(v, n)\n    assert str(v) == \"vec[i64]([1, 2, 3, 4, 5, 6, 7, 8, 9])\"\n    v = vec[i64]()\n    v = append(v, 2**63 - 1)\n    v = append(v, -2**63)\n    assert v[0] == 2**63 - 1\n    assert v[1] == -2**63\n    v = vec[i64]()\n    for i in range(10000):\n        v = append(v, i)\n    for i in range(10000):\n        assert v[i] == i\n\ndef test_append_error() -> None:\n    v: Any = vec[i64]()\n    with assertRaises(OverflowError):\n        v = append(v, 2**63)\n    with assertRaises(OverflowError):\n        v = append(v, -2**63 - 1)\n    assert len(v) == 0\n    with assertRaises(TypeError):\n        v = append(v, 'x')\n    with assertRaises(TypeError):\n        v = append(v, 1.5)\n    assert len(v) == 0\n\ndef test_repr() -> None:\n    assert str(vec[i64]()) == \"vec[i64]([])\"\n    assert str(vec[i64]([123])) == \"vec[i64]([123])\"\n    assert str(vec[i64]([123, -987654321])) == \"vec[i64]([123, -987654321])\"\n\ndef test_size() -> None:\n    v = vec[i64]()\n    # Only test on 64-bit, non-free-threading builds\n    if not is_gil_disabled() and is_64_bit_platform():\n        assert getsizeof(v) == 32\n        v = append(v, 123)\n        assert getsizeof(v) == 32\n\ndef test_get_item() -> None:\n    v = append(vec[i64](), 44)\n    assert v[0] == 44\n    v = append(v, 56)\n    assert v[0] == 44\n    assert v[1] == 56\n\ndef test_get_item_error() -> None:\n    v = append(vec[i64](), 1)\n    v = append(v, 2)\n    v = append(v, 3)\n    with assertRaises(IndexError):\n        v[3]\n    with assertRaises(IndexError):\n        v[-4]\n    n = 2 ** 100\n    with assertRaises(IndexError):\n        v[n]\n\ndef test_get_item_negative() -> None:\n    v = vec[i64]([2, 5, 7])\n    assert v[-1] == 7\n    assert v[-2] == 5\n    assert v[-3] == 2\n    with assertRaises(IndexError):\n        v[-4]\n    with assertRaises(IndexError):\n        v[-2**62]\n\ndef test_len() -> None:\n    v = vec[i64]()\n    assert len(v) == 0\n    v = append(v, 1)\n    assert len(v) == 1\n    v = append(v, 2)\n    assert len(v) == 2\n    for i in range(100):\n        v = append(v, i)\n        assert len(v) == i + 3\n\ndef test_set_item() -> None:\n    v = vec[i64]()\n    v = append(v, 1)\n    v = append(v, 2)\n    v[0] = 3\n    assert v[0] == 3\n    assert v[1] == 2\n    v[1] = 5\n    assert v[0] == 3\n    assert v[1] == 5\n\ndef test_set_item_error() -> None:\n    v = append(vec[i64](), 1)\n    v = append(v, 2)\n    v = append(v, 3)\n    with assertRaises(IndexError):\n        v[3] = 1\n    v[0] = 2**63 - 1\n    assert v[0] == 2**63 - 1\n    with assertRaises(OverflowError):\n        v[0] = 2**63\n    v[0] = -2**63\n    assert v[0] == -2**63\n    with assertRaises(OverflowError):\n        v[0] = -2**63 - 1\n    with assertRaises(TypeError):\n        v[0] = \"x\"\n    with assertRaises(TypeError):\n        v[0] = 1.5\n\ndef test_set_item_negative() -> None:\n    v = vec[i64]()\n    v = append(v, 1)\n    v = append(v, 2)\n    v[-2] = 3\n    assert v[0] == 3\n    assert v[1] == 2\n    v[-1] = 5\n    assert v[0] == 3\n    assert v[1] == 5\n    with assertRaises(IndexError):\n        v[-3] = 1\n\ndef test_equality() -> None:\n    assert_eq(vec[i64](), vec[i64]())\n    assert_eq(vec[i64]([1]), vec[i64]([1]))\n    v = vec[i64]([1])\n    assert_eq(v, v)\n    assert_eq(vec[i64]([1, 2]), vec[i64]([1, 2]))\n\n    assert_neq(vec[i64](), vec[i64]([1]))\n    assert_neq(vec[i64]([1, 2]), vec[i64]([1]))\n    assert_neq(vec[i64]([1]), vec[i64]([2]))\n    assert_neq(vec[i64]([1, 2]), vec[i64]([2, 2]))\n    assert_neq(vec[i64]([1, 2]), vec[i64]([1, 1]))\n\ndef test_equality_different_types() -> None:\n    assert_neq(vec[i64]([1]), None)\n    assert_neq(vec[i64]([1]), [1])\n    assert_neq(vec[i64]([1]), (1,))\n    assert_neq(vec[i64]([1]), vec[object]([1]))\n    assert_neq(vec[i64](), vec[object]())\n\ndef assert_eq(x: object, y: object) -> None:\n    assert x == y\n    assert y == x\n    b = x != y\n    assert not b\n    b = y != x\n    assert not b\n\ndef assert_neq(x: object, y: object) -> None:\n    assert x != y\n    assert y != x\n    b = x == y\n    assert not b\n    b = y == x\n    assert not b\n\ndef test_iteration() -> None:\n    for x in vec[i64]():\n        assert False\n    a = []\n    for x in vec[i64]([11]):\n        a.append(x)\n    assert a == [11]\n    a = []\n    for x in vec[i64]([11, 23, 45, 64]):\n        a.append(x)\n    assert a == [11, 23, 45, 64]\n\ndef test_iteration_nested() -> None:\n    v = vec[i64]()\n    v = append(v, 2)\n    v = append(v, 5)\n    v = append(v, 7)\n    a = []\n    for x in v:\n        for y in v:\n            a.append((x, y))\n    assert a == [(2, 2), (2, 5), (2, 7),\n                 (5, 2), (5, 5), (5, 7),\n                 (7, 2), (7, 5), (7, 7)]\n\ndef test_slicing() -> None:\n    v = vec[i64](range(5))\n    assert v[1:4] == vec[i64]([1, 2, 3])\n    assert v[2:-1] == vec[i64]([2, 3])\n    assert v[-2:-1] == vec[i64]([3])\n    assert v[1:] == vec[i64]([1, 2, 3, 4])\n    assert v[:-1] == vec[i64]([0, 1, 2, 3])\n    assert v[:] == v\n    assert v[:] is not v\n    assert v[5:] == vec[i64]()\n    assert v[100:] == vec[i64]()\n    assert v[0:5] ==v\n    assert v[0:5] is not v\n    assert v[2:100] == vec[i64]([2, 3, 4])\n    assert v[-100:2] == vec[i64]([0, 1])\n    assert v[5:100] == vec[i64]([])\n    assert v[50:100] == vec[i64]([])\n    assert v[-100:-50] == vec[i64]([])\n\ndef test_slicing_with_step() -> None:\n    v = vec[i64](range(10))\n    assert v[1:5:2] == vec[i64]([1, 3])\n    assert v[1:6:2] == vec[i64]([1, 3, 5])\n    assert v[5:1:-2] == vec[i64]([5, 3])\n    assert v[6:1:-2] == vec[i64]([6, 4, 2])\n    v = vec[i64](range(5))\n    assert v[::-1] == vec[i64]([4, 3, 2, 1, 0])\n    with assertRaises(ValueError):\n        v[1:3:0]\n\ndef test_contains() -> None:\n    v = vec[i64](range(2, 7))\n    for i in range(2, 7):\n        assert i in v\n    assert 1 not in v\n    assert 7 not in v\n    assert -1 not in v\n    assert 1233453452 not in v\n    assert -1233453452 not in v\n    vv = vec[i64]()\n    assert 3 not in vv\n\ndef test_remove() -> None:\n    a = [4, 7, 9]\n    for i in a:\n        v = vec[i64](a)\n        v = remove(v, i)\n        assert v == vec[i64]([j for j in a if j != i])\n    v = vec[i64](a)\n    v = remove(v, 4)\n    v = remove(v, 7)\n    v = remove(v, 9)\n    assert v == vec[i64]()\n    with assertRaises(ValueError):\n        remove(v, 4)\n    v = append(v, 5)\n    with assertRaises(ValueError):\n        remove(v, 7)\n    v = remove(v, 5)\n    assert len(v) == 0\n    v = vec[i64]([1, 1, 1])\n    v = remove(v, 1)\n    assert v == vec[i64]([1, 1])\n    v = remove(v, 1)\n    assert v == vec[i64]([1])\n    v = remove(v, 1)\n    assert v == vec[i64]()\n    f: Any = 1.1\n    with assertRaises(TypeError):\n        remove(v, f)\n    s: Any = 'x'\n    with assertRaises(TypeError):\n        remove(v, s)\n\ndef test_pop_last() -> None:\n    v = vec[i64]([4, 7, 9])\n    v, n = pop(v)\n    assert n == 9\n    assert v == vec[i64]([4, 7])\n    v, n = pop(v)\n    assert n == 7\n    assert v == vec[i64]([4])\n    v, n = pop(v)\n    assert n == 4\n    assert v == vec[i64]()\n    with assertRaises(IndexError):\n       pop(v)\n\ndef test_pop_index() -> None:\n    v = vec[i64]([4, 7, 9, 15, 22])\n    v, n = pop(v, 0)\n    assert n == 4\n    assert v == vec[i64]([7, 9, 15, 22])\n    v, n = pop(v, -1)\n    assert n == 22\n    assert v == vec[i64]([7, 9, 15])\n    v, n = pop(v, 1)\n    assert n == 9\n    assert v == vec[i64]([7, 15])\n\n    with assertRaises(IndexError):\n       pop(v, 2)\n\n    with assertRaises(IndexError):\n       pop(v, -3)\n\n    v, n = pop(v, -2)\n    assert n == 7\n    assert v == vec[i64]([15])\n    v, n = pop(v, 0)\n    assert n == 15\n    assert v == vec[i64]()\n"
  },
  {
    "path": "mypyc/test-data/run-vecs-i64.test",
    "content": "-- Test cases for vec[i64]. These also partially cover other unboxed item types,\n-- which use a similar runtime representation.\n\n[case testVecI64BasicOps_librt_experimental]\nfrom typing import Final, Any, Iterable, Tuple\n\nfrom mypy_extensions import i64, i32\nfrom librt.vecs import vec, append, remove, pop\n\nfrom testutil import assertRaises\n\nERROR: Final = -113\n\ndef test_create_empty() -> None:\n    v = vec[i64]()\n    assert len(v) == 0\n\ndef test_create_from_list_and_get_item() -> None:\n    v = vec[i64]([])\n    assert len(v) == 0\n\n    v = vec[i64]([ERROR, 0, 255, int() + (2**63 - 1)])\n    assert len(v) == 4\n    assert v[0] == -113\n    assert v[1] == 0\n    assert v[2] == 255\n    assert v[3] == 2**63 - 1\n\n    v = vec[i64]([1, 2, 3, 4, 5, 6, 7, 8, 9])\n    assert len(v) == 9\n    for i in range(i64(9)):\n        assert v[i] == i + 1\n\ndef test_append() -> None:\n    v = vec[i64]()\n    v = append(v, int() + 3)\n    assert len(v) == 1\n    x: i64 = ERROR + int()\n    v = append(v, x)\n    assert len(v) == 2\n    assert v[0] == 3\n    assert v[1] == ERROR\n    v = vec[i64]()\n    for i in range(1024):\n        v = append(v, i * 3)\n    assert len(v) == 1024\n    for i in range(1024):\n        assert v[i] == i * 3\n\ndef test_get_item() -> None:\n    v = vec[i64]([3, 4])\n    x: i64 = int()\n    assert v[x] == 3\n    assert v[int()] == 3\n    x += 1\n    assert v[x] == 4\n    assert v[int() + 1] == 4\n    with assertRaises(IndexError):\n        v[x + 1]\n    with assertRaises(IndexError):\n        v[2]\n    with assertRaises(IndexError):\n        v[2**63 - 1]\n\ndef test_get_item_negative() -> None:\n    v = vec[i64]([3, 4])\n    x: i64 = int() - 1\n    assert v[x] == 4\n    assert v[int() - 2] == 3\n    x -= 1\n    assert v[x] == 3\n    assert v[int() - 1] == 4\n    with assertRaises(IndexError):\n        v[x - 1]\n    with assertRaises(IndexError):\n        v[-3]\n    with assertRaises(IndexError):\n        v[-2**63]\n    with assertRaises(IndexError):\n        v[int() - 3]\n\ndef test_set_item() -> None:\n    v = vec[i64]([3, 4])\n    v[0] = 0\n    assert v[0] == 0\n\n    x: i64 = int()\n\n    v[x] = 4\n    assert v[x] == 4\n\n    v[int()] = 5\n    assert v[int()] == 5\n\n    x += 1\n\n    v[x] = -5\n    assert v[x] == -5\n\n    v[1 + int()] = ERROR\n    assert v[1] == ERROR\n\n    with assertRaises(IndexError):\n        v[1 + x] = 6\n    with assertRaises(IndexError):\n        v[2 + int()] = 6\n\ndef test_set_item_negative() -> None:\n    v = vec[i64]([3, 4])\n    v[-1] = 0\n    assert v[-1] == 0\n\n    x: i64 = int() - 1\n\n    v[x] = 4\n    assert v[x] == 4\n\n    v[int() - 2] = 5\n    assert v[int() - 2] == 5\n\n    x -= 1\n\n    v[x] = -5\n    assert v[x] == -5\n\n    v[-1 + int()] = ERROR\n    assert v[-1] == ERROR\n\n    with assertRaises(IndexError):\n        v[x - 1] = 6\n    with assertRaises(IndexError):\n        v[int() - 3] = 6\n\ndef test_operator_assignment() -> None:\n    v = vec[i64]([3, 4])\n    x: i64 = int()\n    v[x] += 2\n    assert v[0] == 5\n    v[x + 1] -= 10\n    assert v[1] == -6\n    y = int()\n    v[y] += 6\n    assert v[y] == 11\n    v[y + 1] *= 2\n    assert v[1 + y] == -12\n\ndef test_box_and_unbox() -> None:\n    v = vec[i64]([3, 5])\n    o: Any = v\n    assert len(o) == 2\n    assert o[0] == 3\n    assert o[1] == 5\n    o[1] = 6\n    v2: vec[i64] = o\n    assert len(v2) == 2\n    assert v2[0] == 3\n    assert v2[1] == 6\n    o2: Any = \"x\"\n    with assertRaises(TypeError, \"vec[i64] object expected; got str\"):\n        v2 = o2\n    o3: Any = vec[str]([])\n    # TODO: Better message\n    with assertRaises(TypeError, \"vec[i64] object expected; got vec\"):\n        v2 = o3\n\ndef check_opt(x: vec[i64] | None, is_none: bool) -> None:\n    if is_none:\n        assert x is None\n    else:\n        # If statements ensure type narrowing doesn't leak between blocks\n        if int() + 1:\n            assert x is not None\n            assert len(x) == 1\n            assert x[0] == 5\n        if int() + 2:\n            assert isinstance(x, vec)\n            assert len(x) == 1\n            assert x[0] == 5\n    if isinstance(x, vec):\n        assert x[0] == 5\n        assert not is_none\n    else:\n        assert is_none\n\ndef test_vec_optional() -> None:\n    v = vec[i64]([5])\n    check_opt(None, True)\n    check_opt(v, False)\n    a1: Any = None\n    check_opt(a1, True)\n    a2: Any = v\n    check_opt(a2, False)\n    a3: Any = str\n    with assertRaises(TypeError):\n        check_opt(a3, False)\n\ndef check_union(x: vec[i64] | str, is_str: bool) -> None:\n    if is_str:\n        assert isinstance(x, str)\n        assert x == \"ss\"\n    else:\n        if int() + 1:\n            assert not isinstance(x, str)\n            assert len(x) == 1\n            assert x[0] == 5\n        if int() + 2:\n            assert isinstance(x, vec)\n            assert len(x) == 1\n            assert x[0] == 5\n    if isinstance(x, vec):\n        assert x[0] == 5\n        assert not is_str\n    else:\n        assert is_str\n        assert x == \"ss\"\n\ndef test_vec_union() -> None:\n    v = vec[i64]([5])\n    check_union(\"ss\", True)\n    check_union(v, False)\n    a1: Any = \"ss\"\n    check_union(a1, True)\n    a2: Any = v\n    check_union(a2, False)\n    a3: Any = b\"ss\"\n    with assertRaises(TypeError):\n        check_union(a3, False)\n    a4: Any = vec[i32]()\n    with assertRaises(TypeError, 'union[vec[i64], str] object expected; got vec[i32]'):\n        check_union(a4, False)\n\ndef test_construct_from_list_multiply() -> None:\n    for i in range(50):\n        v = vec[i64]([i + 1] * i)\n        assert len(v) == i\n        for j in range(i):\n            assert v[j] == i + 1\n    for i in range(50):\n        v = vec[i64](i * [i - 1])\n        assert len(v) == i\n        for j in range(i):\n            assert v[j] == i - 1\n\ndef test_construct_from_list_comprehension() -> None:\n    for i in range(50):\n        l = [i * i for i in range(i)]\n        v = vec[i64]([n + 5 for n in l])\n        assert len(v) == i\n        for j in range(i):\n            assert v[j] == j * j + 5\n\ndef test_construct_from_range() -> None:\n    v = vec[i64](range(0))\n    assert v == vec[i64]()\n    v = vec[i64](range(5))\n    assert v == vec[i64]([0, 1, 2, 3, 4])\n    v = vec[i64](range(2, 5))\n    assert v == vec[i64]([2, 3, 4])\n\ndef test_construct_from_iterable() -> None:\n    for i in range(50):\n        it: Iterable[i64] = iter([i * i for i in range(i)])\n        v = vec[i64](it)\n        assert len(v) == i\n        for j in range(i):\n            assert v[j] == j * j\n    for i in range(50):\n        it2: Iterable[int] = iter([i * i for i in range(i)])\n        v = vec[i64](it2)\n        assert len(v) == i\n        for j in range(i):\n            assert v[j] == j * j\n\ndef test_equality() -> None:\n    v0 = vec[i64]()\n    v0b = vec[i64]()\n    v1 = vec[i64]([1])\n    v1b = vec[i64]([3])\n    assert v0 == v0\n    assert v1 == v1\n    assert v0 == v0b\n    assert v0 != v1\n    assert v1 != v1b\n    assert v1 != v0\n\ndef test_str_conversion() -> None:\n    v = vec[i64]()\n    assert str(v) == \"vec[i64]([])\"\n    assert repr(v) == \"vec[i64]([])\"\n    v = vec[i64]([126])\n    assert str(v) == \"vec[i64]([126])\"\n    v = append(v, -5)\n    assert str(v) == \"vec[i64]([126, -5])\"\n    v = append(v, ERROR)\n    assert str(v) == \"vec[i64]([126, -5, -113])\"\n\ndef test_for_loop() -> None:\n    for n in vec[i64]():\n        assert False\n    a = []\n    for n in vec[i64]([5]):\n        a.append(n)\n    assert a == [5]\n    v = vec[i64]([ERROR, 9, 8])\n    a = []\n    for n in v:\n        a.append(n)\n    assert a == [ERROR, 9, 8]\n    assert len(v) == 3\n\ndef test_contains() -> None:\n    v = vec[i64]()\n    x: i64 = int()\n    assert x not in v\n    v = vec[i64]([0])\n    assert x in v\n    assert x + 1 not in v\n    v2 = vec[i64]([ERROR, 7, 9])\n    assert x + ERROR in v2\n    assert x + 7 in v2\n    assert int() + 9 in v2\n    assert x not in v2\n    assert int() not in v2\n\ndef test_slicing() -> None:\n    v = vec[i64]()\n    assert v[:] == vec[i64]([])\n    assert v[1:] == vec[i64]([])\n    assert v[:-5] == vec[i64]([])\n    v = vec[i64]([0, 1, 2, 3, 4])\n    assert v[1:4] == vec[i64]([1, 2, 3])\n    assert v[2:-1] == vec[i64]([2, 3])\n    assert v[-2:-1] == vec[i64]([3])\n    assert v[1:] == vec[i64]([1, 2, 3, 4])\n    assert v[:-1] == vec[i64]([0, 1, 2, 3])\n    assert v[:] == v\n    assert v[:] is not v\n    assert v[5:] == vec[i64]()\n    assert v[100:] == vec[i64]()\n    assert v[0:5] ==v\n    assert v[0:5] is not v\n    assert v[2:100] == vec[i64]([2, 3, 4])\n    assert v[-100:2] == vec[i64]([0, 1])\n    assert v[5:100] == vec[i64]([])\n    assert v[50:100] == vec[i64]([])\n    assert v[-100:-50] == vec[i64]([])\n\ndef test_slicing_with_step() -> None:\n    v = vec[i64]([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n    assert v[1:5:2] == vec[i64]([1, 3])\n    assert v[1:6:2] == vec[i64]([1, 3, 5])\n    assert v[5:1:-2] == vec[i64]([5, 3])\n    assert v[6:1:-2] == vec[i64]([6, 4, 2])\n    v = vec[i64]([0, 1, 2, 3, 4])\n    assert v[::-1] == vec[i64]([4, 3, 2, 1, 0])\n    with assertRaises(ValueError):\n        v[1:3:0]\n\ndef test_remove() -> None:\n    a = [4, 7, ERROR]\n    for i in a:\n        v = vec[i64](a)\n        v = remove(v, i)\n        assert v == vec[i64]([j for j in a if j != i])\n    v = vec[i64](a)\n    v = remove(v, 4)\n    v = remove(v, 7)\n    v = remove(v, ERROR)\n    assert v == vec[i64]()\n    with assertRaises(ValueError):\n        remove(v, 4)\n    v = append(v, 5)\n    with assertRaises(ValueError):\n        remove(v, 7)\n    v = remove(v, 5)\n    assert len(v) == 0\n    v = vec[i64]([1, 1, 1])\n    v = remove(v, 1)\n    assert v == vec[i64]([1, 1])\n    v = remove(v, 1)\n    assert v == vec[i64]([1])\n    v = remove(v, 1)\n    assert v == vec[i64]()\n    f: Any = 1.1\n    with assertRaises(TypeError):\n        remove(v, f)\n    s: Any = 'x'\n    with assertRaises(TypeError):\n        remove(v, s)\n\ndef test_pop_last() -> None:\n    v = vec[i64]([4, 7, ERROR])\n    v, n = pop(v)\n    assert n == ERROR\n    assert v == vec[i64]([4, 7])\n    v, n = pop(v)\n    assert n == 7\n    assert v == vec[i64]([4])\n    v, n = pop(v)\n    assert n == 4\n    assert v == vec[i64]()\n    with assertRaises(IndexError):\n       pop(v)\n\ndef test_pop_index() -> None:\n    v = vec[i64]([4, 7, 9, 15, 22])\n    v, n = pop(v, 0)\n    assert n == 4\n    assert v == vec[i64]([7, 9, 15, 22])\n    v, n = pop(v, -1)\n    assert n == 22\n    assert v == vec[i64]([7, 9, 15])\n    v, n = pop(v, 1)\n    assert n == 9\n    assert v == vec[i64]([7, 15])\n\n    with assertRaises(IndexError):\n       pop(v, 2)\n\n    with assertRaises(IndexError):\n       pop(v, -3)\n\n    v, n = pop(v, -2)\n    assert n == 7\n    assert v == vec[i64]([15])\n    v, n = pop(v, 0)\n    assert n == 15\n    assert v == vec[i64]()\n\ndef f(x: vec[i64]) -> None:\n    pass\n\ndef test_wrapper_arg_check() -> None:\n    f_any: Any = f\n    with assertRaises(TypeError):\n        f_any([])\n\nv: Final = vec[i64]([5, 6])\n\ndef test_final() -> None:\n    assert v == vec[i64]([5, 6])\n\ndef fdefault(v: vec[i64] = vec[i64]([5])) -> vec[i64]:\n    return v\n\ndef test_default_arg() -> None:\n    assert fdefault() == vec[i64]([5])\n    assert fdefault(vec[i64]()) == vec[i64]()\n    f_any: Any = fdefault\n    assert f_any() == vec[i64]([5])\n    assert f_any(vec[i64]([6])) == vec[i64]([6])\n\ndef ftuple(b: bool) -> Tuple[vec[i64], vec[i64]]:\n    if b:\n        raise RuntimeError()\n    return vec[i64]([5]), vec[i64]()\n\ndef test_tuple() -> None:\n    t = ftuple(False)\n    assert len(t) == 2\n    assert t[0] == vec[i64]([5])\n    assert t[1] == vec[i64]()\n    a, b = t\n    assert a == t[0]\n    assert b == t[1]\n    with assertRaises(RuntimeError):\n        ftuple(True)\n"
  },
  {
    "path": "mypyc/test-data/run-vecs-misc-interp.test",
    "content": "[case testLibrtVecsMiscInterpreted_librt_experimental]\n# Test cases for vec[<value primitive type>]. using generic operations.\n# This simulates use from interpreted code.\n#\n# All specialized vec types share most of the implementation, so we don't try to\n# duplicate all tests in run-vecs-i64-interp.test, which acts also as a more detailed\n# test suite for specialized vec types.\n\nimport sys\nfrom typing import Any\nimport typing\n\nimport librt.vecs\nimport mypy_extensions\n\nfrom testutil import assertRaises\n\n# Access via Any references to force generic operations\nvec: Any = librt.vecs.vec\nappend: Any = librt.vecs.append\nremove: Any = librt.vecs.remove\npop: Any = librt.vecs.pop\nu8: Any = mypy_extensions.u8\ni16: Any = mypy_extensions.i16\ni32: Any = mypy_extensions.i32\ni64: Any = mypy_extensions.i64\n\n# Work around test stub limitations\nOptional: Any = getattr(getattr(sys, \"modules\")[\"typing\"], \"Optional\")\n\n# TODO: Add some nested vec tests\n\nITEM_TYPES = [i64, u8, i16, i32, float, bool]\n\n# Common tests for all item types\n\ndef test_bare_vec_cannot_be_constructed() -> None:\n    with assertRaises(TypeError):\n        vec()\n    with assertRaises(TypeError):\n        vec([])\n\ndef test_vec_indexing() -> None:\n    for t in ITEM_TYPES:\n        assert type(vec[t]) is type\n        t1 = vec[t]\n        t2 = vec[t]\n        assert type(vec[t1]) is type(vec[t2])\n        _ = [t1, t2]  # Ensure t1 and t2 are live here\n\n        assert vec[t] is not vec\n        if t is not i64:\n            assert vec[t] is not vec[i64]\n        else:\n            assert vec[t] is not vec[i32]\n\n        with assertRaises(TypeError):\n            vec[Optional[t]]  # Not supported\n\ndef test_type_str() -> None:\n    for t in ITEM_TYPES:\n        name = t.__name__\n        assert str(vec[t]) == f\"<class 'vec[{name}]'>\"\n        assert repr(vec[t]) == f\"<class 'vec[{name}]'>\"\n\ndef test_construct_empty() -> None:\n    for t in ITEM_TYPES:\n        v = vec[t]()\n        assert type(v) is vec[t]\n        assert len(v) == 0\n\ndef test_isinstance() -> None:\n    for t in ITEM_TYPES:\n        v = vec[t]()\n        assert isinstance(v, vec)\n        assert not isinstance(vec[t], vec)\n    assert not isinstance(\"x\", vec)\n    assert not isinstance(vec, vec)\n\ndef test_basic_int_operations() -> None:\n    # All of the non-bool item types support int values 0 to 255\n    for t in ITEM_TYPES:\n        if t is bool:\n            continue\n        v = vec[t]([0, 4, 255])\n        assert len(v) == 3\n        assert v[0] == 0\n        assert v[1] == 4\n        assert v[2] == 255\n        assert v[-1] == 255\n        assert v[-2] == 4\n        assert v[-3] == 0\n        for bad_index in 3, -4, 1 << 100, -1 << 100:\n            with assertRaises(IndexError):\n                v[bad_index]\n        with assertRaises(TypeError):\n            v[\"0\"]\n        with assertRaises(TypeError):\n            append(v, \"0\")\n\ndef test_equality() -> None:\n    for t1 in ITEM_TYPES:\n        for t2 in ITEM_TYPES:\n            assert vec[t1]() != []\n            if t1 is t2:\n                assert vec[t1]() == vec[t2]()\n            else:\n                assert vec[t1]() != vec[t2]()\n\ndef test_repr() -> None:\n    for t in ITEM_TYPES:\n        name = t.__name__\n        assert repr(vec[t]()) == f\"vec[{name}]([])\"\n\n# vec[float] tests\n\ndef test_float_construct_from_initializer() -> None:\n    v = vec[float]([123.5])\n    assert len(v) == 1\n    assert v[0] == 123.5\n    v = vec[float](x + 1 for x in [5, 7.5, -8.5, 10])\n    assert len(v) == 4\n    assert v[0] == 6\n    assert v[1] == 8.5\n    assert v[2] == -7.5\n    assert v[3] == 11\n    with assertRaises(TypeError):\n        vec[float](1)\n    with assertRaises(TypeError):\n        vec[float](['1'])\n    with assertRaises(TypeError):\n        vec[float]([None])\n\ndef test_float_append() -> None:\n    v = vec[float]()\n    v = append(v, 1.5)\n    assert str(v) == \"vec[float]([1.5])\"\n    v = append(v, -2)\n    assert str(v) == \"vec[float]([1.5, -2.0])\"\n\ndef test_float_get_item() -> None:\n    v = append(vec[float](), 44.5)\n    assert v[0] == 44.5\n    v = append(v, -56.5)\n    assert v[0] == 44.5\n    assert v[1] == -56.5\n\ndef test_float_remove() -> None:\n    a = [4.5, 7, 9]\n    for x in a:\n        v = vec[float](a)\n        v = remove(v, x)\n        assert v == vec[float]([y for y in a if y != x])\n\ndef test_float_pop() -> None:\n    v = vec[float]([4.5, 7, 9.5])\n    v, n = pop(v)\n    assert n == 9.5\n    assert v == vec[float]([4.5, 7])\n\n# vec[u8] tests\n\ndef test_u8_construct_from_initializer() -> None:\n    v = vec[u8]([123])\n    assert len(v) == 1\n    assert v[0] == 123\n    v = vec[u8](x for x in [0, 5, 255, 10])\n    assert len(v) == 4\n    assert v[0] == 0\n    assert v[1] == 5\n    assert v[2] == 255\n    assert v[3] == 10\n    with assertRaises(TypeError):\n        vec[u8](1)\n    with assertRaises(TypeError):\n        vec[u8](['1'])\n    with assertRaises(TypeError):\n        vec[u8]([None])\n\ndef test_u8_append() -> None:\n    v = vec[u8]()\n    v = append(v, 5)\n    assert str(v) == \"vec[u8]([5])\"\n    v = append(v, 255)\n    assert str(v) == \"vec[u8]([5, 255])\"\n\ndef test_u8_item_overflow() -> None:\n    with assertRaises(OverflowError):\n        vec[u8]([256])\n    with assertRaises(OverflowError):\n        vec[u8]([-1])\n    with assertRaises(OverflowError):\n        vec[u8]([2**100])\n    with assertRaises(OverflowError):\n        vec[u8]([-2**100])\n\ndef test_u8_get_item() -> None:\n    v = append(vec[u8](), 44)\n    assert v[0] == 44\n    v = append(v, 238)\n    assert v[0] == 44\n    assert v[1] == 238\n\ndef test_u8_remove() -> None:\n    a = [0, 7, 255]\n    for x in a:\n        v = vec[u8](a)\n        v = remove(v, x)\n        assert v == vec[u8]([y for y in a if y != x])\n\ndef test_u8_pop() -> None:\n    v = vec[u8]([0, 7, 255])\n    v, n = pop(v)\n    assert n == 255\n    assert v == vec[u8]([0, 7])\n\n# vec[i16] tests\n\ndef test_i16_construct_from_initializer() -> None:\n    v = vec[i16]([123])\n    assert len(v) == 1\n    assert v[0] == 123\n    v = vec[i16](x for x in [0, 5, 32767, -32768])\n    assert len(v) == 4\n    assert v[0] == 0\n    assert v[1] == 5\n    assert v[2] == 32767\n    assert v[3] == -32768\n    with assertRaises(TypeError):\n        vec[i16](1)\n    with assertRaises(TypeError):\n        vec[i16](['1'])\n    with assertRaises(TypeError):\n        vec[i16]([None])\n\ndef test_i16_append() -> None:\n    v = vec[i16]()\n    v = append(v, 5)\n    assert str(v) == \"vec[i16]([5])\"\n    v = append(v, 32767)\n    assert str(v) == \"vec[i16]([5, 32767])\"\n\ndef test_i16_item_overflow() -> None:\n    with assertRaises(OverflowError):\n        vec[i16]([32768])\n    with assertRaises(OverflowError):\n        vec[i16]([-32769])\n    with assertRaises(OverflowError):\n        vec[i16]([2**100])\n    with assertRaises(OverflowError):\n        vec[i16]([-2**100])\n\ndef test_i16_get_item() -> None:\n    v = append(vec[i16](), 44)\n    assert v[0] == 44\n    v = append(v, -238)\n    assert v[0] == 44\n    assert v[1] == -238\n\ndef test_i16_remove() -> None:\n    a = [0, 7, -532, 32767]\n    for x in a:\n        v = vec[i16](a)\n        v = remove(v, x)\n        assert v == vec[i16]([y for y in a if y != x])\n\ndef test_i16_pop() -> None:\n    v = vec[i16]([0, -7, 32767])\n    v, n = pop(v)\n    assert n == 32767\n    assert v == vec[i16]([0, -7])\n\n# vec[i32] tests\n\ndef test_i32_construct_from_initializer() -> None:\n    v = vec[i32]([123])\n    assert len(v) == 1\n    assert v[0] == 123\n    v = vec[i32](x for x in [0, 5, 2**31 - 1, -2**31])\n    assert len(v) == 4\n    assert v[0] == 0\n    assert v[1] == 5\n    assert v[2] == 2**31 - 1\n    assert v[3] == -2**31\n    with assertRaises(TypeError):\n        vec[i32](1)\n    with assertRaises(TypeError):\n        vec[i32](['1'])\n    with assertRaises(TypeError):\n        vec[i32]([None])\n\ndef test_i32_append() -> None:\n    v = vec[i32]()\n    v = append(v, 5)\n    assert str(v) == \"vec[i32]([5])\"\n    v = append(v, 2**31 - 1)\n    assert str(v) == \"vec[i32]([5, 2147483647])\"\n\ndef test_i32_item_overflow() -> None:\n    with assertRaises(OverflowError):\n        vec[i32]([2**31])\n    with assertRaises(OverflowError):\n        vec[i32]([-2**31 - 1])\n    with assertRaises(OverflowError):\n        vec[i32]([2**100])\n    with assertRaises(OverflowError):\n        vec[i32]([-2**100])\n\ndef test_i32_get_item() -> None:\n    v = append(vec[i32](), 44)\n    assert v[0] == 44\n    v = append(v, -238)\n    assert v[0] == 44\n    assert v[1] == -238\n\ndef test_i32_remove() -> None:\n    a = [0, 7, -532, 2**31 - 1]\n    for x in a:\n        v = vec[i32](a)\n        v = remove(v, x)\n        assert v == vec[i32]([y for y in a if y != x])\n\ndef test_i32_pop() -> None:\n    v = vec[i32]([0, -7, 2**31 - 1])\n    v, n = pop(v)\n    assert n == 2**31 - 1\n    assert v == vec[i32]([0, -7])\n\n# vec[bool] tests\n\ndef test_bool_construct_from_initializer() -> None:\n    v = vec[bool]([True])\n    assert len(v) == 1\n    assert v[0] == True\n    v = vec[bool](x for x in [True, False, True])\n    assert len(v) == 3\n    assert v[0] is True\n    assert v[1] is False\n    assert v[2] is True\n    with assertRaises(TypeError):\n        vec[bool](1)\n    with assertRaises(TypeError):\n        vec[bool](['1'])\n    with assertRaises(TypeError):\n        vec[bool]([1])\n    with assertRaises(TypeError):\n        vec[bool]([None])\n\ndef test_bool_append() -> None:\n    v = vec[bool]()\n    v = append(v, False)\n    assert str(v) == \"vec[bool]([False])\"\n    v = append(v, True)\n    assert str(v) == \"vec[bool]([False, True])\"\n\ndef test_bool_get_item() -> None:\n    v = append(vec[bool](), True)\n    assert v[0] is True\n    v = append(v, False)\n    assert v[0] is True\n    assert v[1] is False\n\ndef test_bool_remove() -> None:\n    a = [True, False]\n    for x in a:\n        v = vec[bool](a)\n        v = remove(v, x)\n        assert v == vec[bool]([y for y in a if y != x])\n\ndef test_bool_pop() -> None:\n    v = vec[bool]([True, False, True])\n    v, n = pop(v)\n    assert n is True\n    assert v == vec[bool]([True, False])\n\n[case testLibrtVecsFeaturesNotAvailableInNonExperimentalBuild_librt]\n# This also ensures librt.vecs can be built without experimental features\nimport librt.vecs\n\ndef test_features_not_available() -> None:\n    vecs: object = getattr(librt, \"vecs\")\n    assert not hasattr(vecs, \"vec\")\n    assert not hasattr(vecs, \"append\")\n    assert not hasattr(vecs, \"remove\")\n    assert not hasattr(vecs, \"pop\")\n"
  },
  {
    "path": "mypyc/test-data/run-vecs-misc.test",
    "content": "-- Test cases for packed/specialized vec item types other than i64, such as\n-- vec[i32] and vec[float]. Since many of the code paths are the same as for\n-- vec[i64], only test a subset of functionality.\n--\n-- vec[i64] test cases are in run-vecs-i64.test.\n\n[case testVecMiscBasicOps_librt_experimental]\n# mypy: allow-redefinition-old\n\nfrom typing import Any, cast\nfrom mypy_extensions import i64, i32, i16, u8\nfrom librt.vecs import vec, append, remove, pop\nfrom testutil import assertRaises\n\ndef test_create_empty() -> None:\n    assert str(vec[i32]()) == \"vec[i32]([])\"\n    assert str(vec[i16]()) == \"vec[i16]([])\"\n    assert str(vec[u8]()) == \"vec[u8]([])\"\n    assert str(vec[float]()) == \"vec[float]([])\"\n    assert str(vec[bool]()) == \"vec[bool]([])\"\n\ndef test_create_from_values() -> None:\n    assert str(vec[i32]([5, -12])) == \"vec[i32]([5, -12])\"\n    assert str(vec[i16]([6, -8])) == \"vec[i16]([6, -8])\"\n    assert str(vec[u8]([0, 123, 255])) == \"vec[u8]([0, 123, 255])\"\n    assert str(vec[float]([1.5, -3.5])) == \"vec[float]([1.5, -3.5])\"\n    assert str(vec[bool]([False, True])) == \"vec[bool]([False, True])\"\n\ndef test_get_item() -> None:\n    assert vec[i32]([5, -12])[1] == -12\n    assert vec[i16]([6, -8])[1] == -8\n    assert vec[u8]([0, 123, 255])[2] == 255\n    assert vec[float]([1.5, -3.5])[1] == -3.5\n    assert vec[bool]([False, True])[1] == True\n\ndef test_get_item_negative() -> None:\n    assert vec[i32]([5, -12])[-2] == 5\n    assert vec[i16]([6, -8])[-2] == 6\n    assert vec[u8]([0, 123, 255])[-2] == 123\n    assert vec[float]([1.5, -3.5])[-2] == 1.5\n    assert vec[bool]([False, True])[-2] == False\n\ndef test_append() -> None:\n    assert append(vec[i32](), 123) == vec[i32]([123])\n    assert append(vec[i16](), 123) == vec[i16]([123])\n    assert append(vec[u8](), 123) == vec[u8]([123])\n    assert append(vec[float](), 123.5) == vec[float]([123.5])\n    assert append(vec[bool](), True) == vec[bool]([True])\n\ndef test_unbox() -> None:\n    v: vec[i64]\n\n    a = cast(Any, vec[i32]([1, 2]))\n    v_i32: vec[i32] = a\n    assert v_i32 == vec[i32]([1, 2])\n    with assertRaises(TypeError):\n        v = a\n\n    a = cast(Any, vec[i16]([1, 2]))\n    v_i16: vec[i16] = a\n    assert v_i16 == vec[i16]([1, 2])\n    with assertRaises(TypeError):\n        v = a\n\n    a = cast(Any, vec[u8]([1, 2]))\n    v_u8: vec[u8] = a\n    assert v_u8 == vec[u8]([1, 2])\n    with assertRaises(TypeError):\n        v = a\n\n    a = cast(Any, vec[float]([1, 2]))\n    v_float: vec[float] = a\n    assert v_float == vec[float]([1, 2])\n    with assertRaises(TypeError):\n        v = a\n\n    a = cast(Any, vec[bool]([True, False]))\n    v_bool: vec[bool] = a\n    assert v_bool == vec[bool]([True, False])\n    with assertRaises(TypeError):\n        v = a\n\ndef test_set_item() -> None:\n    v = vec[i32]([5, -12])\n    v[1] = 55\n    assert v[0] == 5 and v[1] == 55\n\n    v = vec[i16]([5, -12])\n    v[1] = 55\n    assert v[0] == 5 and v[1] == 55\n\n    v = vec[u8]([5, 237])\n    v[1] = 55\n    assert v[0] == 5 and v[1] == 55\n\n    v = vec[float]([1.5, -3.5])\n    v[1] = 5.5\n    assert v[0] == 1.5 and v[1] == 5.5\n\n    v = vec[bool]([True, False])\n    v[1] = True\n    assert v[0] and v[1]\n\ndef test_set_item_negative() -> None:\n    v = vec[i32]([5, -12])\n    v[-1] = 55\n    assert v[0] == 5 and v[1] == 55\n\n    v = vec[i16]([5, -12])\n    v[-1] = 55\n    assert v[0] == 5 and v[1] == 55\n\n    v = vec[u8]([5, 237])\n    v[-1] = 55\n    assert v[0] == 5 and v[1] == 55\n\n    v = vec[float]([1.5, -3.5])\n    v[-1] = 5.5\n    assert v[0] == 1.5 and v[1] == 5.5\n\n    v = vec[bool]([True, False])\n    v[-1] = True\n    assert v[0] and v[1]\n\ndef test_for_loop() -> None:\n    a: Any = []\n    for x in vec[float]([1.5, -3.5]):\n        a.append(x)\n    assert a == [1.5, -3.5]\n\n    a = []\n    for x in vec[bool]([True, False, False, True]):\n        a.append(x)\n    assert a == [True, False, False, True]\n\n    a = []\n    for x in vec[u8]([0, 5, 237, 255]):\n        a.append(x)\n    assert a == [0, 5, 237, 255]\n\ndef test_comprehension() -> None:\n    v = vec[i32]([x + 1 for x in [1, 4, -5]])\n    assert list(v) == [2, 5, -4]\n\n    v = vec[float]([x + 1.5 for x in range(4)])\n    assert list(v) == [1.5, 2.5, 3.5, 4.5]\n\ndef len_union(x: vec[i64] | vec[i32]) -> int:\n    return len(x)\n\ndef test_union_of_vecs() -> None:\n    assert len_union(vec[i64]()) == 0\n    assert len_union(vec[i64]([7, 8])) == 2\n    assert len_union(vec[i32]([7, 8, 9])) == 3\n    with assertRaises(TypeError):\n        a1: Any = vec[i16]()\n        len_union(a1)\n    with assertRaises(TypeError):\n        a2: Any = []\n        len_union(a2)\n\ndef test_nested_basics() -> None:\n    v = vec[vec[i32]]([vec[i32]([5, 6]),\n                       vec[i32]([-12])])\n    assert str(v) == \"vec[vec[i32]]([[5, 6], [-12]])\"\n    assert v[0][1] == 6\n    assert v[1][0] == -12\n\n    v = vec[vec[i16]]([vec[i16]([5, 6]),\n                       vec[i16]([-12])])\n    assert str(v) == \"vec[vec[i16]]([[5, 6], [-12]])\"\n    assert v[0][1] == 6\n    assert v[1][0] == -12\n\n    v = vec[vec[u8]]([vec[u8]([5, 6]),\n                      vec[u8]([237])])\n    assert str(v) == \"vec[vec[u8]]([[5, 6], [237]])\"\n    assert v[0][1] == 6\n    assert v[1][0] == 237\n\n    v = vec[vec[float]]([vec[float]([1.5, -3.5]),\n                         vec[float]([3.0])])\n    assert str(v) == \"vec[vec[float]]([[1.5, -3.5], [3.0]])\"\n    assert v[0][1] == -3.5\n    assert v[1][0] == 3.0\n\n    v = vec[vec[bool]]([vec[bool]([False, True]),\n                        vec[bool]([False])])\n    assert str(v) == \"vec[vec[bool]]([[False, True], [False]])\"\n    assert v[0][1] == True\n    assert v[1][0] == False\n\ndef test_nested_unbox() -> None:\n    vv: vec[vec[i64]]\n\n    a = cast(Any, vec[vec[i32]]([vec[i32]([5])]))\n    v_i32: vec[vec[i32]] = a\n    assert str(v_i32) == \"vec[vec[i32]]([[5]])\"\n    with assertRaises(TypeError):\n        vv = a\n\n    a = cast(Any, vec[vec[i16]]([vec[i16]([5])]))\n    v_i16: vec[vec[i16]] = a\n    with assertRaises(TypeError):\n        vv = a\n\n    a = cast(Any, vec[vec[u8]]([vec[u8]([5])]))\n    v_u8: vec[vec[u8]] = a\n    with assertRaises(TypeError):\n        vv = a\n\n    a = cast(Any, vec[vec[float]]([vec[float]([5])]))\n    v_float: vec[vec[float]] = a\n    with assertRaises(TypeError):\n        vv = a\n\n    a = cast(Any, vec[vec[bool]]([vec[bool]([True])]))\n    v_bool: vec[vec[bool]] = a\n    with assertRaises(TypeError):\n        vv = a\n\ndef test_nested_misc() -> None:\n    v = vec[vec[float]]()\n    assert len(v) == 0\n    v = append(v, vec[float]([1.5]))\n    assert len(v) == 1\n    for x in v:\n        assert x == vec[float]([1.5])\n    vv, x = pop(v)\n    assert vv == vec[vec[float]]()\n    assert x == vec[float]([1.5])\n\n    # Since pop doesn't change the length of v, the following should work\n    v[0] = vec[float]([-2.5])\n    assert v[0] == vec[float]([-2.5])\n    v[0][0] = 3.5\n    assert v[0] == vec[float]([3.5])\n    assert v[:5] == vec[vec[float]]([vec[float]([3.5])])\n"
  },
  {
    "path": "mypyc/test-data/run-vecs-nested-interp.test",
    "content": "[case testLibrtVecsNestedInterpreted_librt_experimental]\n# Test cases for nested vecs, using generic operations (simulates use from interpreted code).\n\nimport sys\nfrom typing import Any\nimport typing\n\nimport librt.vecs\nimport mypy_extensions\n\nfrom testutil import assertRaises, is_gil_disabled, is_64_bit_platform\n\nvec: Any = librt.vecs.vec\nappend: Any = librt.vecs.append\nremove: Any = librt.vecs.remove\npop: Any = librt.vecs.pop\ngetsizeof: Any = getattr(sys, \"getsizeof\")\ni64: Any = mypy_extensions.i64\n\n# Work around test stub limitations\nOptional: Any = getattr(getattr(sys, \"modules\")[\"typing\"], \"Optional\")\n\n\ndef test_vec_indexing() -> None:\n    assert type(vec[vec[str]]) is type(vec[str])\n    assert type(vec[vec[Optional[str]]]) is type(vec[str])\n    assert type(vec[vec[i64]]) is type(vec[str])\n    assert type(vec[vec[vec[vec[vec[vec[str]]]]]]) is type(vec[str])\n    with assertRaises(TypeError):\n        vec[Optional[vec[str]]]\n    with assertRaises(TypeError):\n        vec[Optional[vec[Optional[str]]]]\n\ndef test_type_str() -> None:\n    assert str(vec[Optional[str]]) == \"<class_proxy 'vec[str | None]'>\"\n    assert str(vec[vec[str]]) == \"<class_proxy 'vec[vec[str]]'>\"\n    assert str(vec[vec[i64]]) == \"<class_proxy 'vec[vec[i64]]'>\"\n    assert str(vec[vec[vec[vec[vec[str]]]]]) == \"<class_proxy 'vec[vec[vec[vec[vec[str]]]]]'>\"\n    assert str(\n        vec[vec[vec[Optional[str]]]]) == \"<class_proxy 'vec[vec[vec[str | None]]]'>\"\n\ndef test_construct_empty_nested() -> None:\n    v = vec[vec[str]]()\n    assert len(v) == 0\n    v2 = vec[vec[vec[vec[vec[str]]]]]()\n    assert len(v2) == 0\n    v3 = vec[vec[i64]]()\n    assert len(v3) == 0\n\ndef test_construct_empty_nested_optional() -> None:\n    v = vec[vec[Optional[str]]]()\n    assert len(v) == 0\n\ndef test_construct_from_initializer_nested() -> None:\n    v = vec[vec[str]]([vec[str](['xyz'])])\n    assert len(v) == 1\n    assert v[0][0] == 'xyz'\n    with assertRaises(TypeError):\n        vec[str](1)\n    with assertRaises(TypeError):\n        vec[str]([1])\n    with assertRaises(TypeError):\n        vec[str]([vec[bytes]()])\n\ndef test_isinstance() -> None:\n    assert isinstance(vec[vec[str]](), vec)\n    assert isinstance(vec[vec[Optional[str]]](), vec)\n\ndef test_repr() -> None:\n    assert str(vec[vec[str]]()) == \"vec[vec[str]]([])\"\n    assert str(vec[vec[Optional[str]]]()) == \"vec[vec[str | None]]([])\"\n\ndef test_append_nested() -> None:\n    v = vec[vec[str]]()\n    vv = append(vec[str](), '1')\n    v = append(v, vv)\n    assert str(v) == \"vec[vec[str]]([['1']])\"\n    for n in range(2, 10):\n        vv = append(vec[str](), str(n))\n        v = append(v, vv)\n    assert str(v) == (\n        \"vec[vec[str]]([['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9']])\"\n    )\n\ndef test_append_i64() -> None:\n    v = vec[vec[i64]]()\n    vv = append(vec[i64](), 1)\n    v = append(v, vv)\n    assert str(v) == \"vec[vec[i64]]([[1]])\"\n    for n in range(2, 10):\n        vv = append(vec[i64](), n)\n        v = append(v, vv)\n    assert str(v) == (\n        \"vec[vec[i64]]([[1], [2], [3], [4], [5], [6], [7], [8], [9]])\"\n    )\n\ndef test_append_nested_optional() -> None:\n    v = vec[vec[Optional[str]]]()\n    v = append(v, vec[Optional[str]]())\n    v = append(v, vec[Optional[str]](['x', None]))\n    assert str(v) == \"vec[vec[str | None]]([[], ['x', None]])\"\n\ndef test_size() -> None:\n    # Only test on 64-bit, non-free-threading builds\n    if not is_gil_disabled() and is_64_bit_platform():\n        v = vec[vec[str]]()\n        assert getsizeof(v) == 48\n        v = append(v, vec[str]())\n        assert getsizeof(v) == 48\n\ndef test_get_item() -> None:\n    v = append(vec[vec[str]](), append(vec[str](), 'x'))\n    assert repr(v[0]) == \"vec[str](['x'])\"\n    v = append(v, append(vec[str](), 'y'))\n    assert repr(v[0]) == \"vec[str](['x'])\"\n    assert repr(v[1]) == \"vec[str](['y'])\"\n    vv = append(vec[vec[Optional[str]]](), vec[Optional[str]]())\n    assert vv[0] == vec[Optional[str]]()\n\ndef test_get_item_error() -> None:\n    v = append(vec[vec[str]](), vec[str](['1']))\n    v = append(v, vec[str](['2']))\n    v = append(v, vec[str](['3']))\n    with assertRaises(IndexError):\n        v[3]\n    with assertRaises(IndexError):\n        v[4]\n    n = 2 ** 100\n    with assertRaises(IndexError):\n        v[n]\n\ndef test_get_item_negative() -> None:\n    v = vec[vec[str]]([vec[str](['2']), vec[str](['5']), vec[str](['7'])])\n    assert v[-1] == vec[str](['7'])\n    assert v[-2] == vec[str](['5'])\n    assert v[-3] == vec[str](['2'])\n    with assertRaises(IndexError):\n        v[-4]\n    with assertRaises(IndexError):\n        v[-2**62]\n\ndef test_len() -> None:\n    v = vec[vec[str]]()\n    assert len(v) == 0\n    v = append(v, vec[str](['1']))\n    assert len(v) == 1\n    v = append(v, vec[str]())\n    assert len(v) == 2\n    for i in range(100):\n        v = append(v, vec[str](['i']))\n        assert len(v) == i + 3\n\ndef test_set_item() -> None:\n    v = vec[vec[str]]()\n    v = append(v, vec[str](['1']))\n    v = append(v, vec[str](['2']))\n    v[0] = vec[str](['3'])\n    assert v[0] == vec[str](['3'])\n    assert v[1] == vec[str](['2'])\n    v[1] = vec[str](['5'])\n    assert v[0] == vec[str](['3'])\n    assert v[1] == vec[str](['5'])\n\ndef test_set_item_error_nested() -> None:\n    v = append(vec[vec[str]](), vec[str]())\n    v = append(v, vec[str]())\n    v = append(v, vec[str]())\n    with assertRaises(IndexError):\n        v[3] = vec[str]()\n    with assertRaises(TypeError):\n        v[0] = 'x'\n    with assertRaises(TypeError):\n        v[0] = vec[vec[str]]()\n    with assertRaises(TypeError):\n        v[0] = vec[Optional[str]]()\n    assert repr(v[0]) == 'vec[str]([])'\n\ndef test_set_item_negative() -> None:\n    v = vec[vec[str]]()\n    v = append(v, vec[str](['1']))\n    v = append(v, vec[str](['2']))\n    v[-2] = vec[str](['3'])\n    assert v[0] == vec[str](['3'])\n    assert v[1] == vec[str](['2'])\n    v[-1] = vec[str](['5'])\n    assert v[0] == vec[str](['3'])\n    assert v[1] == vec[str](['5'])\n    with assertRaises(IndexError):\n        v[-3] = vec[str](['5'])\n\ndef test_equality() -> None:\n    assert_eq(vec[vec[str]](), vec[vec[str]]())\n    assert_eq(vec[vec[str]]([vec[str](['x'])]), vec[vec[str]]([vec[str](['x'])]))\n    assert_neq(vec[vec[str]]([vec[str](['x'])]), vec[vec[str]]())\n    assert_neq(vec[vec[str]]([vec[str](['x'])]), vec[vec[str]]([vec[str](['y'])]))\n\ndef test_equality_different_types() -> None:\n    assert_neq(vec[vec[str]](), vec[str]())\n    assert_neq(vec[vec[str]](), vec[vec[vec[str]]]())\n    assert_neq(vec[vec[Optional[str]]](), vec[vec[str]]())\n\ndef assert_eq(x: object, y: object) -> None:\n    assert x == y\n    assert y == x\n    b = x != y\n    assert not b\n    b = y != x\n    assert not b\n\ndef assert_neq(x: object, y: object) -> None:\n    assert x != y\n    assert y != x\n    b = x == y\n    assert not b\n    b = y == x\n    assert not b\n\ndef test_slicing() -> None:\n    v = vec[vec[str]](vec[str]([str(i)]) for i in range(5))\n    assert v[1:4] == vec[vec[str]]([v[1], v[2], v[3]])\n    assert v[2:-1] == vec[vec[str]]([v[2], v[3]])\n    assert v[-2:-1] == vec[vec[str]]([v[3]])\n    assert v[1:] == vec[vec[str]]([v[1], v[2], v[3], v[4]])\n    assert v[:-1] == vec[vec[str]]([v[0], v[1], v[2], v[3]])\n    assert v[:] == v\n    assert v[:] is not v\n    assert v[0:5] ==v\n    assert v[0:5] is not v\n    assert v[2:100] == vec[vec[str]]([v[2], v[3], v[4]])\n    assert v[-100:2] == vec[vec[str]]([v[0], v[1]])\n    assert v[5:100] == vec[vec[str]]([])\n    assert v[50:100] == vec[vec[str]]([])\n    assert v[-100:-50] == vec[vec[str]]([])\n\ndef test_slicing_with_step() -> None:\n    v = vec[vec[str]](vec[str]([str(i)]) for i in range(10))\n    assert v[1:5:2] == vec[vec[str]]([v[1], v[3]])\n    assert v[1:6:2] == vec[vec[str]]([v[1], v[3], v[5]])\n    assert v[5:1:-2] == vec[vec[str]]([v[5], v[3]])\n    assert v[6:1:-2] == vec[vec[str]]([v[6], v[4], v[2]])\n    v = vec[vec[str]](vec[str]([str(i)]) for i in range(5))\n    assert v[::-1] == vec[vec[str]]([v[4], v[3], v[2], v[1], v[0]])\n    with assertRaises(ValueError):\n        v[1:3:0]\n\ndef test_slicing_with_different_item_types() -> None:\n    v = vec[Optional[str]](['x', None, 'y'])\n    assert v[1:] == vec[Optional[str]]([None, 'y'])\n    vv = vec[vec[str]]([vec[str](['x']), vec[str](['y'])])\n    assert vv[1:] == vec[vec[str]]([vec[str](['y'])])\n\ndef test_remove() -> None:\n    a = ['4x', '7x', '9x']\n    vv = [vec[str]([s]) for s in a]\n    for i, s in enumerate(a):\n        v = vec[vec[str]](vv)\n        v = remove(v, vv[i])\n        assert v == vec[vec[str]]([j for j in vv if j != vv[i]])\n        v = vec[vec[str]](vv)\n        # Make sure we have a different object identity\n        v = remove(v, vec[str]([a[i]]))\n        assert v == vec[vec[str]]([j for j in vv if j != vv[i]])\n    v = vec[vec[str]](vv)\n    v = remove(v, vv[0])\n    v = remove(v, vv[1])\n    v = remove(v, vv[2])\n    assert v == vec[vec[str]]()\n    with assertRaises(ValueError):\n        remove(v, vec[str](['4']))\n    v = append(v, vec[str](['5']))\n    with assertRaises(ValueError):\n        remove(v, vec[str](['7']))\n    v = remove(v, vec[str](['5']))\n    assert len(v) == 0\n    v = v0 = vec[vec[str]]([vec[str](['x']) for _ in range(3)])\n    v = remove(v, vec[str](['x']))\n    assert v == v0[1:]\n    v = remove(v, vec[str](['x']))\n    assert v == v0[2:]\n    v = remove(v, vec[str](['x']))\n    assert v == vec[vec[str]]()\n    vb: Any = vec[bytes]([b'x'])\n    with assertRaises(TypeError):\n        remove(v, vb)\n\ndef test_pop_last() -> None:\n    v = vec[vec[str]]([vec[str](['4']), vec[str](['5']), vec[str](['9'])])\n    v, item = pop(v)\n    assert item == vec[str](['9'])\n    assert v == vec[vec[str]]([vec[str](['4']), vec[str](['5'])])\n    v, item = pop(v)\n    assert item == vec[str](['5'])\n    assert v == vec[vec[str]]([vec[str](['4'])])\n    v, item = pop(v)\n    assert item == vec[str](['4'])\n    assert v == vec[vec[str]]()\n    with assertRaises(IndexError):\n        pop(v)\n\ndef test_pop_index() -> None:\n    v = vec[vec[str]](vec[str]([s]) for s in ['4', '7', '9', '15', '22'])\n    v, item = pop(v, 0)\n    assert item == vec[str](['4'])\n    assert v == vec[vec[str]](vec[str]([s]) for s in ['7', '9', '15', '22'])\n    v, item = pop(v, -1)\n    assert item == vec[str](['22'])\n    assert v == vec[vec[str]](vec[str]([s]) for s in ['7', '9', '15'])\n    v, item = pop(v, 1)\n    assert item == vec[str](['9'])\n    assert v == vec[vec[str]](vec[str]([s]) for s in ['7', '15'])\n\n    with assertRaises(IndexError):\n        pop(v, 2)\n\n    with assertRaises(IndexError):\n        pop(v, -3)\n\n    v, item = pop(v, -2)\n    assert item == vec[str](['7'])\n    assert v == vec[vec[str]]([vec[str](['15'])])\n    v, item = pop(v, 0)\n    assert item == vec[str](['15'])\n    assert v == vec[vec[str]]()\n"
  },
  {
    "path": "mypyc/test-data/run-vecs-nested.test",
    "content": "[case testVecNestedBasicOps_librt_experimental]\nfrom typing import Final, Any, Iterable, Optional, Tuple\nimport sys\n\nfrom mypy_extensions import i64, i32\nfrom librt.vecs import vec, append, remove, pop\n\nfrom testutil import assertRaises\n\ndef test_construct_empty_nested() -> None:\n    v = vec[vec[str]]()\n    assert len(v) == 0\n    v2 = vec[vec[vec[vec[vec[str]]]]]()\n    assert len(v2) == 0\n    v3 = vec[vec[i64]]()\n    assert len(v3) == 0\n\ndef test_construct_empty_nested_optional() -> None:\n    v = vec[vec[Optional[str]]]()\n    assert len(v) == 0\n\ndef test_construct_from_initializer_nested() -> None:\n    v = vec[vec[str]]([vec[str](['xyz', 'a'])])\n    assert len(v) == 1\n    assert len(v[0]) == 2\n    assert v[0][0] == 'xyz'\n    assert v[0][1] == 'a'\n\ndef test_repr() -> None:\n    assert str(vec[vec[str]]()) == \"vec[vec[str]]([])\"\n    assert str(vec[vec[Optional[str]]]()) == \"vec[vec[str | None]]([])\"\n    if sys.version_info[1] >= 10:\n        assert str(vec[vec[str | None]]()) == \"vec[vec[str | None]]([])\"\n\ndef test_append_nested() -> None:\n    v = vec[vec[str]]()\n    vv = append(vec[str](), '1')\n    v = append(v, vv)\n    assert str(v) == \"vec[vec[str]]([['1']])\"\n    for n in range(2, 10):\n        vv = append(vec[str](), str(n))\n        v = append(v, vv)\n    assert str(v) == (\n        \"vec[vec[str]]([['1'], ['2'], ['3'], ['4'], ['5'], ['6'], ['7'], ['8'], ['9']])\"\n    )\n\ndef test_append_i64() -> None:\n    v = vec[vec[i64]]()\n    vv = append(vec[i64](), 1)\n    v = append(v, vv)\n    assert str(v) == \"vec[vec[i64]]([[1]])\"\n    for n in range(2, 10):\n        vv = append(vec[i64](), n)\n        v = append(v, vv)\n    assert str(v) == (\n        \"vec[vec[i64]]([[1], [2], [3], [4], [5], [6], [7], [8], [9]])\"\n    )\n\ndef test_append_nested_optional() -> None:\n    v = vec[vec[Optional[str]]]()\n    v = append(v, vec[Optional[str]]())\n    v[0] = append(v[0], None)\n    v[0] = append(v[0], 'x')\n    assert str(v) == \"vec[vec[str | None]]([[None, 'x']])\"\n\ndef test_get_item() -> None:\n    v = append(vec[vec[str]](), append(vec[str](), 'x'))\n    vv = v[0]\n    assert vv == vec[str](['x'])\n    v = append(v, append(vec[str](), 'y'))\n    assert repr(v[0]) == \"vec[str](['x'])\"\n    assert repr(v[1]) == \"vec[str](['y'])\"\n\ndef test_get_item_error() -> None:\n    v = append(vec[vec[str]](), vec[str](['1']))\n    v = append(v, vec[str](['3']))\n    with assertRaises(IndexError):\n        v[2]\n    with assertRaises(IndexError):\n        v[-3]\n\ndef test_len() -> None:\n    v = vec[vec[str]]()\n    assert len(v) == 0\n    v = append(v, vec[str](['1']))\n    assert len(v) == 1\n    v = append(v, vec[str]())\n    assert len(v) == 2\n    for i in range(100):\n        v = append(v, vec[str](['i']))\n        assert len(v) == i + 3\n\ndef test_set_item_error_nested() -> None:\n    v = append(vec[vec[str]](), vec[str]())\n    v = append(v, vec[str]())\n    v = append(v, vec[str]())\n    with assertRaises(IndexError):\n        v[3] = vec[str]()\n    with assertRaises(IndexError):\n        v[-4] = vec[str]()\n    assert repr(v[0]) == 'vec[str]([])'\n\ndef test_equality() -> None:\n    assert vec[vec[str]]() == vec[vec[str]]()\n    assert vec[vec[str]]([vec[str](['x'])]) == vec[vec[str]]([vec[str](['x'])])\n    assert vec[vec[str]]([vec[str](['x'])]) != vec[vec[str]]()\n    assert vec[vec[str]]([vec[str](['x'])]) != vec[vec[str]]([vec[str](['y'])])\n\ndef test_equality_different_types() -> None:\n    a = vec[vec[str]]()\n    b = vec[str]()\n    assert a == a\n    assert b == b\n    assert b != a\n    assert a != b\n\n    c = vec[vec[vec[str]]]()\n    assert c != a\n    assert a != c\n    assert c == c\n\n    d = vec[vec[Optional[str]]]()\n    assert d != a\n    assert a != d\n    assert d == d\n\n    assert vec[vec[str]]() != vec[vec[bytes]]()\n    assert vec[vec[str]]() != vec[vec[i64]]()\n\ndef test_slicing() -> None:\n    v = vec[vec[str]](vec[str]([str(i)]) for i in range(5))\n    assert v[1:4] == vec[vec[str]]([v[1], v[2], v[3]])\n    assert v[2:-1] == vec[vec[str]]([v[2], v[3]])\n    assert v[-2:-1] == vec[vec[str]]([v[3]])\n    assert v[1:] == vec[vec[str]]([v[1], v[2], v[3], v[4]])\n    assert v[:-1] == vec[vec[str]]([v[0], v[1], v[2], v[3]])\n    assert v[:] == v\n    assert v[:] is not v\n    assert v[0:5] ==v\n    assert v[0:5] is not v\n    assert v[2:100] == vec[vec[str]]([v[2], v[3], v[4]])\n    assert v[-100:2] == vec[vec[str]]([v[0], v[1]])\n    assert v[5:100] == vec[vec[str]]([])\n    assert v[50:100] == vec[vec[str]]([])\n    assert v[-100:-50] == vec[vec[str]]([])\n\ndef test_slicing_with_step() -> None:\n    v = vec[vec[str]](vec[str]([str(i)]) for i in range(10))\n    assert v[1:5:2] == vec[vec[str]]([v[1], v[3]])\n    assert v[1:6:2] == vec[vec[str]]([v[1], v[3], v[5]])\n    assert v[5:1:-2] == vec[vec[str]]([v[5], v[3]])\n    assert v[6:1:-2] == vec[vec[str]]([v[6], v[4], v[2]])\n    v = vec[vec[str]](vec[str]([str(i)]) for i in range(5))\n    assert v[::-1] == vec[vec[str]]([v[4], v[3], v[2], v[1], v[0]])\n    with assertRaises(ValueError):\n        v[1:3:0]\n\ndef test_slicing_with_different_item_types() -> None:\n    v = vec[vec[i64]]([vec[i64]([11]), vec[i64]([22])])\n    assert v[1:] == vec[vec[i64]]([vec[i64]([22])])\n\ndef test_remove() -> None:\n    a = ['4x', '7x', '9x']\n    vv = [vec[str]([s]) for s in a]\n    for i, s in enumerate(a):\n        v = vec[vec[str]](vv)\n        v = remove(v, vv[i])\n        assert v == vec[vec[str]]([j for j in vv if j != vv[i]])\n        v = vec[vec[str]](vv)\n        # Make sure we have a different object identity\n        v = remove(v, vec[str]([a[i]]))\n        assert v == vec[vec[str]]([j for j in vv if j != vv[i]])\n    v = vec[vec[str]](vv)\n    v = remove(v, vv[0])\n    v = remove(v, vv[1])\n    v = remove(v, vv[2])\n    assert v == vec[vec[str]]()\n    with assertRaises(ValueError):\n        remove(v, vec[str](['4']))\n    v = append(v, vec[str](['5']))\n    with assertRaises(ValueError):\n        remove(v, vec[str](['7']))\n    v = remove(v, vec[str](['5']))\n    assert len(v) == 0\n    v = v0 = vec[vec[str]]([vec[str](['x']) for _ in range(3)])\n    v = remove(v, vec[str](['x']))\n    assert v == v0[1:]\n    v = remove(v, vec[str](['x']))\n    assert v == v0[2:]\n    v = remove(v, vec[str](['x']))\n    assert v == vec[vec[str]]()\n    vb: Any = vec[bytes]([b'x'])\n    with assertRaises(TypeError):\n        remove(v, vb)\n\ndef test_pop_last() -> None:\n    v = vec[vec[str]]([vec[str](['4']), vec[str](['6']), vec[str](['9'])])\n    v, item = pop(v)\n    assert item == vec[str](['9'])\n    assert v == vec[vec[str]]([vec[str](['4']), vec[str](['6'])])\n    v, item = pop(v)\n    assert item == vec[str](['6'])\n    assert v == vec[vec[str]]([vec[str](['4'])])\n    v, item = pop(v)\n    assert item == vec[str](['4'])\n    assert v == vec[vec[str]]()\n    with assertRaises(IndexError):\n        pop(v)\n\ndef test_pop_index() -> None:\n    v = vec[vec[str]](vec[str]([s]) for s in ['4', '7', '9', '15', '22'])\n    v, item = pop(v, 0)\n    assert item == vec[str](['4'])\n    assert v == vec[vec[str]](vec[str]([s]) for s in ['7', '9', '15', '22'])\n    v, item = pop(v, -1)\n    assert item == vec[str](['22'])\n    assert v == vec[vec[str]](vec[str]([s]) for s in ['7', '9', '15'])\n    v, item = pop(v, 1)\n    assert item == vec[str](['9'])\n    assert v == vec[vec[str]](vec[str]([s]) for s in ['7', '15'])\n\n    with assertRaises(IndexError):\n        pop(v, 2)\n\n    with assertRaises(IndexError):\n        pop(v, -3)\n\n    v, item = pop(v, -2)\n    assert item == vec[str](['7'])\n    assert v == vec[vec[str]]([vec[str](['15'])])\n    v, item = pop(v, 0)\n    assert item == vec[str](['15'])\n    assert v == vec[vec[str]]()\n\ndef test_doubly_nested_operations() -> None:\n    a = vec[vec[str]]([vec[str]([\"x\"])])\n    b = vec[vec[str]]([vec[str]()])\n    v = vec[vec[vec[str]]]()\n\n    # append\n    v = append(v, a)\n    assert repr(v) == \"vec[vec[vec[str]]]([[['x']]])\"\n    v = append(v, b)\n    assert len(v) == 2\n\n    # get item\n    assert v[0] == a\n    assert v[1] == b\n\n    # set item\n    v[0] = b\n    assert v[0] == b\n    v[0] = a\n    with assertRaises(IndexError):\n        v[2 + int()]\n    with assertRaises(IndexError):\n        v[2 + int()] = a\n\n    # slicing\n    vv = v[:1]\n    assert len(vv) == 1\n    assert vv[0] == a\n    vv = v[1:]\n    assert len(vv) == 1\n    assert vv[0] == b\n\n    # remove\n    v = remove(v, a)\n    assert len(v) == 1\n    assert v[0] == b\n    v = remove(v, b)\n    assert len(v) == 0\n\n    # pop last\n    v = append(v, a)\n    v = append(v, b)\n    v, x = pop(v)\n    assert len(v) == 1\n    assert v[0] == a\n    assert x == b\n    v, x = pop(v)\n    assert len(v) == 0\n    assert x == a\n    with assertRaises(IndexError):\n        pop(v)\n\n    # pop index\n    v = append(v, a)\n    v = append(v, b)\n    v, x = pop(v, 0)\n    assert len(v) == 1\n    assert v[0] == b\n    assert x == a\n\n    # TODO: box/unbox\n\ndef test_vec_i64_nested_operations() -> None:\n    a = vec[i64]([11])\n    b = vec[i64]()\n    v = vec[vec[i64]]()\n\n    # append\n    v = append(v, a)\n    assert repr(v) == \"vec[vec[i64]]([[11]])\"\n    v = append(v, b)\n    assert len(v) == 2\n\n    # get item\n    assert v[0] == a\n    assert v[1] == b\n\n    # set item\n    v[0] = b\n    assert v[0] == b\n    v[0] = a\n    with assertRaises(IndexError):\n        v[2 + int()]\n    with assertRaises(IndexError):\n        v[2 + int()] = a\n\n    # slicing\n    vv = v[:1]\n    assert len(vv) == 1\n    assert vv[0] == a\n    vv = v[1:]\n    assert len(vv) == 1\n    assert vv[0] == b\n\n    # remove\n    v = remove(v, a)\n    assert len(v) == 1\n    assert v[0] == b\n    v = remove(v, b)\n    assert len(v) == 0\n\n    # pop last\n    v = append(v, a)\n    v = append(v, b)\n    v, x = pop(v)\n    assert len(v) == 1\n    assert v[0] == a\n    assert x == b\n    v, x = pop(v)\n    assert len(v) == 0\n    assert x == a\n    with assertRaises(IndexError):\n        pop(v)\n\n    # pop index\n    v = append(v, a)\n    v = append(v, b)\n    v, x = pop(v, 0)\n    assert len(v) == 1\n    assert v[0] == b\n    assert x == a\n\n    # TODO: box/unbox\n\ndef test_doubly_nested_vec_i64_operations() -> None:\n    a = vec[vec[i64]]([vec[i64]([11])])\n    b = vec[vec[i64]]([vec[i64]()])\n    v = vec[vec[vec[i64]]]()\n\n    # append\n    v = append(v, a)\n    assert repr(v) == \"vec[vec[vec[i64]]]([[[11]]])\"\n    v = append(v, b)\n    assert len(v) == 2\n\n    # get item\n    assert v[0] == a\n    assert v[1] == b\n\n    # set item\n    v[0] = b\n    assert v[0] == b\n    v[0] = a\n    with assertRaises(IndexError):\n        v[2 + int()]\n    with assertRaises(IndexError):\n        v[2 + int()] = a\n\n    # slicing\n    vv = v[:1]\n    assert len(vv) == 1\n    assert vv[0] == a\n    vv = v[1:]\n    assert len(vv) == 1\n    assert vv[0] == b\n\n    # remove\n    v = remove(v, a)\n    assert len(v) == 1\n    assert v[0] == b\n    v = remove(v, b)\n    assert len(v) == 0\n\n    # pop last\n    v = append(v, a)\n    v = append(v, b)\n    v, x = pop(v)\n    assert len(v) == 1\n    assert v[0] == a\n    assert x == b\n    v, x = pop(v)\n    assert len(v) == 0\n    assert x == a\n    with assertRaises(IndexError):\n        pop(v)\n\n    # pop index\n    v = append(v, a)\n    v = append(v, b)\n    v, x = pop(v, 0)\n    assert len(v) == 1\n    assert v[0] == b\n    assert x == a\n\n    # TODO: box/unbox\n\ndef f(x: vec[vec[str]]) -> None:\n    pass\n\ndef test_wrapper_arg_check() -> None:\n    f_any: Any = f\n    with assertRaises(TypeError):\n        f_any(vec[str]())\n    with assertRaises(TypeError):\n        f_any(None)\n    with assertRaises(TypeError):\n        f_any([])\n\nv: Final = vec[vec[str]]([vec[str]([\"x\"])])\n\ndef test_final() -> None:\n    assert v == vec[vec[str]]([vec[str]([\"x\"])])\n\ndef fdefault(v: vec[vec[str]] = vec[vec[str]]()) -> vec[vec[str]]:\n    return v\n\ndef test_default_arg() -> None:\n    assert fdefault() == vec[vec[str]]()\n    v = vec[vec[str]]([vec[str]([\"x\"])])\n    assert fdefault(v) == v\n    f_any: Any = fdefault\n    assert f_any() == vec[vec[str]]()\n    assert f_any(v) == v\n\ndef ftuple(b: bool) -> Tuple[vec[vec[str]], vec[vec[str]]]:\n    if b:\n        raise RuntimeError()\n    return vec[vec[str]]([vec[str]()]), vec[vec[str]]()\n\ndef test_tuple() -> None:\n    t = ftuple(False)\n    assert len(t) == 2\n    assert t[0] == vec[vec[str]]([vec[str]()])\n    assert t[1] == vec[vec[str]]()\n    a, b = t\n    assert a == t[0]\n    assert b == t[1]\n    with assertRaises(RuntimeError):\n        ftuple(True)\n    f_any: Any = ftuple\n    t2 = f_any(False)\n    assert t == t2\n    with assertRaises(RuntimeError):\n        f_any(True)\n\ndef len_union(x: vec[vec[i64]] | vec[vec[Optional[str]]]) -> int:\n    return len(x)\n\ndef test_union_of_nested_vecs() -> None:\n    assert len_union(vec[vec[i64]]()) == 0\n    assert len_union(vec[vec[i64]]([vec[i64]([1, 2])])) == 1\n    assert len_union(vec[vec[Optional[str]]]([vec[Optional[str]]([\"x\", None])])) == 1\n    # Wrong inner item type (i32 instead of i64)\n    with assertRaises(TypeError):\n        a1: Any = vec[vec[i32]]()\n        len_union(a1)\n    # Wrong inner item type (str instead of str | None)\n    with assertRaises(TypeError):\n        a2: Any = vec[vec[str]]()\n        len_union(a2)\n    # Not a nested vec\n    with assertRaises(TypeError):\n        a3: Any = vec[i64]()\n        len_union(a3)\n    # Plain list\n    with assertRaises(TypeError):\n        a4: Any = []\n        len_union(a4)\n    # Too deeply nested\n    with assertRaises(TypeError):\n        a5: Any = vec[vec[vec[i64]]]()\n        len_union(a5)\n"
  },
  {
    "path": "mypyc/test-data/run-vecs-t-interp.test",
    "content": "[case testLibrtVecsTInterpreted_librt_experimental]\n# Test cases for vec[<ref type>], using generic operations (simulates use from interpreted code).\nimport sys\nfrom typing import cast, List, Any\nimport typing\n\nimport librt.vecs\nimport mypy_extensions\n\nfrom testutil import assertRaises, is_gil_disabled, is_64_bit_platform\nfrom helpers import ClassWithCustomMeta\n\nvec: Any = librt.vecs.vec\nappend: Any = librt.vecs.append\nremove: Any = librt.vecs.remove\npop: Any = librt.vecs.pop\ngetsizeof: Any = getattr(sys, \"getsizeof\")\ni64: Any = mypy_extensions.i64\nversion_info: Any = sys.version_info\n\n# Work around test stub limitations\nOptional: Any = getattr(getattr(sys, \"modules\")[\"typing\"], \"Optional\")\n\ndef assert_eq(x: object, y: object) -> None:\n    assert x == y\n    assert y == x\n    b = x != y\n    assert not b\n    b = y != x\n    assert not b\n\ndef assert_neq(x: object, y: object) -> None:\n    assert x != y\n    assert y != x\n    b = x == y\n    assert not b\n    b = y == x\n    assert not b\n\n@mypy_extensions.mypyc_attr(native_class=False)\nclass StringSubclass(str):\n    pass\n\nclass ClassWithRaisingEq:\n    def __eq__(self, other):\n        raise RuntimeError()\n\ndef test_vec_indexing() -> None:\n    assert vec[str] is not vec[i64]\n    assert type(vec[str]) is not type\n    assert type(vec[Optional[str]]) is type(vec[str])\n\ndef test_type_str() -> None:\n    assert str(vec[str]) == \"<class_proxy 'vec[str]'>\"\n    assert str(vec[Optional[str]]) == \"<class_proxy 'vec[str | None]'>\"\n\ndef test_construct_empty() -> None:\n    v = vec[str]()\n    assert len(v) == 0\n    v2 = vec[Optional[str]]()\n    assert len(v2) == 0\n    assert type(v) is type(v2)\n\ndef test_construct_or_union() -> None:\n    if version_info >= (3, 10):\n        v = vec[str | None]()\n        assert len(v) == 0\n        assert str(v) == 'vec[str | None]([])'\n\ndef test_construct_from_initializer() -> None:\n    v = vec[str](['xyz'])\n    assert len(v) == 1\n    assert v[0] == 'xyz'\n    v = vec[str](x + '!' for x in ['x', '', 'foo', 'bar'])\n    assert len(v) == 4\n    assert v[0] == 'x!'\n    assert v[1] == '!'\n    assert v[2] == 'foo!'\n    assert v[3] == 'bar!'\n    with assertRaises(TypeError):\n        vec[str](1)\n    with assertRaises(TypeError):\n        vec[str]([1])\n    with assertRaises(TypeError):\n        vec[str]([None])\n\ndef test_construct_from_initializer_optional() -> None:\n    v = vec[Optional[str]]([None, 'xyz'])\n    assert len(v) == 2\n    assert v[0] is None\n    assert v[1] == 'xyz'\n    v = vec[Optional[str]](x for x in ['x', None, 'foo', 'bar'])\n    assert len(v) == 4\n    assert v[0] == 'x'\n    assert v[1] is None\n    assert v[2] == 'foo'\n    assert v[3] == 'bar'\n    with assertRaises(TypeError):\n        vec[Optional[str]](1)\n    with assertRaises(TypeError):\n        vec[Optional[str]]([1])\n\ndef test_isinstance() -> None:\n    assert isinstance(vec[str](), vec)\n    assert isinstance(vec[Optional[str]](), vec)\n\ndef test_append() -> None:\n    v = vec[str]()\n    v = append(v, '1')\n    assert str(v) == \"vec[str](['1'])\"\n    for n in range(2, 10):\n        v = append(v, str(n))\n    assert str(v) == \"vec[str](['1', '2', '3', '4', '5', '6', '7', '8', '9'])\"\n\n    v2 = vec[Optional[str]]()\n    v2 = append(v2, 'x')\n    v2 = append(v2, None)\n    assert str(v2) == \"vec[str | None](['x', None])\"\n\ndef test_append_error() -> None:\n    v: Any = vec[str]()\n    with assertRaises(TypeError):\n        v = append(v, b'x')\n    with assertRaises(TypeError):\n        v = append(v, ['x'])\n    with assertRaises(TypeError):\n        v = append(v, None)\n    assert len(v) == 0\n\n    v2: Any = vec[Optional[str]]()\n    with assertRaises(TypeError):\n        v2 = append(v2, b'x')\n\ndef test_repr() -> None:\n    assert str(vec[str]()) == \"vec[str]([])\"\n    assert str(vec[Optional[str]]([None, 'x'])) == \"vec[str | None]([None, 'x'])\"\n\ndef test_size() -> None:\n    # Only test on 64-bit, non-free-threading builds\n    if not is_gil_disabled() and is_64_bit_platform():\n        v = vec[str]()\n        assert getsizeof(v) == 48\n        v = append(v, '123')\n        assert getsizeof(v) == 48\n\ndef test_get_item() -> None:\n    v = append(vec[str](), '44')\n    assert v[0] == '44'\n    v = append(v, '56')\n    assert v[0] == '44'\n    assert v[1] == '56'\n\n    v2 = vec[Optional[str]]([None, '12'])\n    assert v2[0] is None\n    assert v2[1] == '12'\n\ndef test_get_item_error() -> None:\n    v = append(vec[str](), '1')\n    v = append(v, '2')\n    v = append(v, '3')\n    with assertRaises(IndexError):\n        v[3]\n    with assertRaises(IndexError):\n        v[-4]\n    n = 2 ** 100\n    with assertRaises(IndexError):\n        v[n]\n\ndef test_get_item_negative() -> None:\n    v = vec[str](['2', '5', '7'])\n    assert v[-1] == '7'\n    assert v[-2] == '5'\n    assert v[-3] == '2'\n    with assertRaises(IndexError):\n        v[-4]\n    with assertRaises(IndexError):\n        v[-2**62]\n\ndef test_len() -> None:\n    v = vec[str]()\n    assert len(v) == 0\n    v = append(v, '1')\n    assert len(v) == 1\n    v = append(v, '2')\n    assert len(v) == 2\n    for i in range(100):\n        v = append(v, 'i')\n        assert len(v) == i + 3\n\ndef test_set_item() -> None:\n    v = vec[str]()\n    v = append(v, '1')\n    v = append(v, '2')\n    v[0] = '3'\n    assert v[0] == '3'\n    assert v[1] == '2'\n    v[1] = '5'\n    assert v[0] == '3'\n    assert v[1] == '5'\n\ndef test_set_item_optional() -> None:\n    v = vec[Optional[str]]()\n    v = append(v, '1')\n    v = append(v, None)\n    v[0] = '3'\n    assert v[0] == '3'\n    assert v[1 + int()] is None  # TODO: The '+ int()' is due to mypy type narrowing bug\n    v[1] = '5'\n    assert v[0] == '3'\n    assert v[1] == '5'\n    v[1] = None\n    assert v[0] == '3'\n    assert v[1] is None\n\ndef test_set_item_error() -> None:\n    v = append(vec[str](), '1')\n    v = append(v, '2')\n    v = append(v, '3')\n    with assertRaises(IndexError):\n        v[3] = '1'\n    with assertRaises(TypeError):\n        v[0] = b'x'\n    with assertRaises(TypeError):\n        v[0] = vec[str]()\n    with assertRaises(TypeError):\n        v[0] = None\n    assert v[0] == '1'\n\ndef test_set_item_error_optional() -> None:\n    v = append(vec[Optional[str]](), '1')\n    v = append(v, None)\n    v = append(v, '3')\n    with assertRaises(IndexError):\n        v[3] = '1'\n    with assertRaises(IndexError):\n        v[3] = None\n    with assertRaises(IndexError):\n        v[-4] = '1'\n    with assertRaises(IndexError):\n        v[-4] = None\n    with assertRaises(TypeError):\n        v[0] = b'x'\n    with assertRaises(TypeError):\n        v[0] = vec[str]()\n    with assertRaises(TypeError):\n        v[0] = vec[Optional[str]]()\n    assert v[0] == '1'\n\ndef test_set_item_negative() -> None:\n    v = vec[str]()\n    v = append(v, '1')\n    v = append(v, '2')\n    v[-2] = '3'\n    assert v[0] == '3'\n    assert v[1] == '2'\n    v[-1] = '5'\n    assert v[0] == '3'\n    assert v[1] == '5'\n    with assertRaises(IndexError):\n        v[-3] = '1'\n\ndef test_nested_in_type() -> None:\n    cast(List[vec[str]], [])\n\ndef test_cannot_overload_isinstance() -> None:\n    assert isinstance('', ClassWithCustomMeta)\n    v = vec[ClassWithCustomMeta]()\n    v = append(v, ClassWithCustomMeta())\n    with assertRaises(TypeError):\n        v = append(v, '')\n    with assertRaises(TypeError):\n        v[0] = ''\n\ndef test_add_subclass_instance() -> None:\n    v = vec[str]()\n    v = append(v, StringSubclass())\n    v[0] = StringSubclass()\n\n    v2 = vec[StringSubclass]()\n    with assertRaises(TypeError):\n        v2 = append(v2, '')\n\ndef test_equality() -> None:\n    assert_eq(vec[str](), vec[str]())\n    assert_eq(vec[str](['x']), vec[str](['x']))\n    v = vec[str](['x'])\n    assert_eq(v, v)\n    assert_eq(vec[str](['x', 'y']), vec[str](['x', 'y']))\n\n    assert_neq(vec[str](), vec[str](['x']))\n    assert_neq(vec[str](['x', 'y']), vec[str](['x']))\n    assert_neq(vec[str](['x']), vec[str](['y']))\n    assert_neq(vec[str](['x', 'y']), vec[str](['y', 'y']))\n    assert_neq(vec[str](['x', 'y']), vec[str](['x', 'x']))\n\n    assert_eq(vec[Optional[str]](), vec[Optional[str]]())\n    assert_eq(vec[Optional[str]](['x', None]), vec[Optional[str]](['x', None]))\n    assert_neq(vec[Optional[str]](['x', None]), vec[Optional[str]](['x', 'y']))\n\ndef test_equality_different_types() -> None:\n    assert_neq(vec[str](['x']), ['x'])\n    assert_neq(vec[str](['x']), ('x',))\n    assert_neq(vec[str](['x']), vec[object](['x']))\n    assert_neq(vec[str](), vec[object]())\n    assert_neq(vec[str](), vec[Optional[str]]())\n\ndef test_exception_from_eq() -> None:\n    with assertRaises(RuntimeError):\n        vec[ClassWithRaisingEq]([ClassWithRaisingEq()]) == vec[ClassWithRaisingEq]([ClassWithRaisingEq()])\n\ndef test_iteration() -> None:\n    for x in vec[str]():\n        assert False\n    a = []\n    for x in vec[str](['x']):\n        a.append(x)\n    assert a == ['x']\n    a = []\n    for x in vec[str](['11', '23', '45', '64']):\n        a.append(x)\n    assert a == ['11', '23', '45', '64']\n    a = []\n    for x in vec[Optional[str]](['11', None, '45', '64']):\n        a.append(x)\n    assert a == ['11', None, '45', '64']\n\ndef test_slicing() -> None:\n    v = vec[str](str(i) for i in range(5))\n    assert v[1:4] == vec[str](['1', '2', '3'])\n    assert v[2:-1] == vec[str](['2', '3'])\n    assert v[-2:-1] == vec[str](['3'])\n    assert v[1:] == vec[str](['1', '2', '3', '4'])\n    assert v[:-1] == vec[str](['0', '1', '2', '3'])\n    assert v[:] == v\n    assert v[:] is not v\n    assert v[0:5] ==v\n    assert v[0:5] is not v\n    assert v[2:100] == vec[str](['2', '3', '4'])\n    assert v[-100:2] == vec[str](['0', '1'])\n    assert v[5:100] == vec[str]([])\n    assert v[50:100] == vec[str]([])\n    assert v[-100:-50] == vec[str]([])\n\ndef test_slicing_optional() -> None:\n    v = vec[Optional[str]](['x', None, 'y'])\n    assert v[:2] == vec[Optional[str]](['x', None])\n\ndef test_slicing_with_step() -> None:\n    v = vec[str](str(i) for i in range(10))\n    assert v[1:5:2] == vec[str](['1', '3'])\n    assert v[1:6:2] == vec[str](['1', '3', '5'])\n    assert v[5:1:-2] == vec[str](['5', '3'])\n    assert v[6:1:-2] == vec[str](['6', '4', '2'])\n    v = vec[str](str(i) for i in range(5))\n    assert v[::-1] == vec[str](['4', '3', '2', '1', '0'])\n    with assertRaises(ValueError):\n        v[1:3:0]\n\ndef test_contains() -> None:\n    v = vec[str](str(i) for i in range(2, 7))\n    for i in range(2, 7):\n        assert str(i) in v\n    assert 'x' not in v\n    assert '22' not in v\n    vv = vec[str]()\n    assert '3' not in vv\n\n    v2 = vec[Optional[str]]()\n    assert '3' not in v2\n    assert None not in v2\n    v2 = vec[Optional[str]](['3', None])\n    assert '3' in v2\n    assert None in v2\n    assert '4' not in v2\n\ndef test_remove() -> None:\n    a = ['4x', '7x', '9x']\n    for i in a:\n        v = vec[str](a)\n        v = remove(v, i)\n        assert v == vec[str]([j for j in a if j != i])\n        v = vec[str](a)\n        # Make sure we have a different id\n        v = remove(v, (i + 'x')[:-1])\n        assert v == vec[str]([j for j in a if j != i])\n    v = vec[str](a)\n    v = remove(v, '4x')\n    v = remove(v, '7x')\n    v = remove(v, '9x')\n    assert v == vec[str]()\n    with assertRaises(ValueError):\n        remove(v, '4')\n    v = append(v, '5')\n    with assertRaises(ValueError):\n        remove(v, '7')\n    v = remove(v, '5')\n    assert len(v) == 0\n    v = vec[str](['x', 'x', 'x'])\n    v = remove(v, 'x')\n    assert v == vec[str](['x', 'x'])\n    v = remove(v, 'x')\n    assert v == vec[str](['x'])\n    v = remove(v, 'x')\n    assert v == vec[str]()\n    b: Any = b'x'\n    with assertRaises(TypeError):\n        remove(v, b)\n\ndef test_remove_optional() -> None:\n    v = vec[Optional[str]](['x', None])\n    v = remove(v, 'x')\n    assert str(v) == \"vec[str | None]([None])\"\n    v = remove(v, None)\n    assert str(v) == \"vec[str | None]([])\"\n\ndef test_pop_last() -> None:\n    v = vec[str](['4', '7', '9'])\n    v, item = pop(v)\n    assert item == '9'\n    assert v == vec[str](['4', '7'])\n    v, item = pop(v)\n    assert item == '7'\n    assert v == vec[str](['4'])\n    v, item = pop(v)\n    assert item == '4'\n    assert v == vec[str]()\n    with assertRaises(IndexError):\n        pop(v)\n\ndef test_pop_index() -> None:\n    v = vec[str](['4', '7', '9', '15', '22'])\n    v, item = pop(v, 0)\n    assert item == '4'\n    assert v == vec[str](['7', '9', '15', '22'])\n    v, item = pop(v, -1)\n    assert item == '22'\n    assert v == vec[str](['7', '9', '15'])\n    v, item = pop(v, 1)\n    assert item == '9'\n    assert v == vec[str](['7', '15'])\n\n    with assertRaises(IndexError):\n        pop(v, 2)\n\n    with assertRaises(IndexError):\n        pop(v, -3)\n\n    v, item = pop(v, -2)\n    assert item == '7'\n    assert v == vec[str](['15'])\n    v, item = pop(v, 0)\n    assert item == '15'\n    assert v == vec[str]()\n\n[file helpers.py]\n# Test helper classes\n\nclass MetaWithInstanceCheck(type):\n    def __instancecheck__(cls, instance):\n        return isinstance(instance, str)\n\nclass ClassWithCustomMeta(metaclass=MetaWithInstanceCheck):\n    pass\n"
  },
  {
    "path": "mypyc/test-data/run-vecs-t.test",
    "content": "-- Test cases for vec[t] where t is a boxed, non-vec type (PyObject *).\n-- Also tests for vec[t | None], which uses the same representation.\n\n[case testVecTBasicOps_librt_experimental]\nfrom typing import Final, Any, Iterable, Optional, Tuple\n\nfrom mypy_extensions import i64\nfrom librt.vecs import vec, append, remove, pop\n\nfrom testutil import assertRaises\n\ndef test_create_empty() -> None:\n    v = vec[str]()\n    assert len(v) == 0\n    v2 = vec[Optional[str]]()\n    assert len(v2) == 0\n\ndef test_create_from_list_and_get_item() -> None:\n    v = vec[str]([])\n    assert len(v) == 0\n\n    v = vec[str]([\"xyz\", \"0\" + str(), str(), \"foo\"])\n    assert len(v) == 4\n    assert v[0] == \"xyz\"\n    assert v[1] == \"0\"\n    assert v[2] == \"\"\n    assert v[3] == \"foo\"\n\n    v = vec[str]([\"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"])\n    assert len(v) == 9\n    for i in range(i64(9)):\n        assert v[i] == str(i + 1)\n\ndef test_create_optional_and_get_item() -> None:\n    v = vec[Optional[str]]([\"xyz\", None])\n    assert len(v) == 2\n    assert v[0] == \"xyz\"\n    assert v[1] is None\n\ndef test_append() -> None:\n    v = vec[str]()\n    v = append(v, str() + \"3\")\n    assert len(v) == 1\n    x = \"xyz\" + str()\n    v = append(v, x)\n    assert len(v) == 2\n    assert v[0] == \"3\"\n    assert v[1] == \"xyz\"\n    v = vec[str]()\n    for i in range(1024):\n        v = append(v, str(i * 3))\n    assert len(v) == 1024\n    for i in range(1024):\n        assert v[i] == str(i * 3)\n\ndef test_get_item() -> None:\n    v = vec[str]([\"3\", \"4\"])\n    x: i64 = int()\n    assert v[x] == \"3\"\n    assert v[int()] == \"3\"\n    x += 1\n    assert v[x] == \"4\"\n    assert v[int() + 1] == \"4\"\n    with assertRaises(IndexError):\n        v[x + 1]\n    with assertRaises(IndexError):\n        v[2]\n    with assertRaises(IndexError):\n        v[2**63 - 1]\n\ndef test_set_item() -> None:\n    v = vec[str]([\"3\", \"4\"])\n    v[0] = \"0\"\n    assert v[0] == \"0\"\n\n    x: i64 = int()\n\n    v[x] = \"4\"\n    assert v[x] == \"4\"\n\n    v[int()] = \"5\"\n    assert v[int()] == \"5\"\n\n    x += 1\n\n    v[x] = \"-5\"\n    assert v[x] == \"-5\"\n\n    v[1 + int()] = \"xyz\"\n    assert v[1] == \"xyz\"\n\n    with assertRaises(IndexError):\n        v[1 + x] = \"6\"\n    with assertRaises(IndexError):\n        v[2 + int()] = \"6\"\n\ndef test_set_item_optional() -> None:\n    v = vec[Optional[str]]([\"3\", None])\n    v[1] = str() + \"a\"\n    assert v[1] == \"a\"\n    v[0] = None\n    assert v[0] is None\n\ndef test_box_and_unbox() -> None:\n    v = vec[str]([\"3\", \"5\"])\n    o: Any = v\n    assert len(o) == 2\n    assert o[0] == \"3\"\n    assert o[1] == \"5\"\n    o[1] = \"6\"\n    v2: vec[str] = o\n    assert len(v2) == 2\n    assert v2[0] == \"3\"\n    assert v2[1] == \"6\"\n    o2: Any = None\n    with assertRaises(TypeError, \"vec[str] object expected; got None\"):\n        v2 = o2\n    o3: Any = vec[bytes]([])\n    with assertRaises(TypeError, \"vec[str] object expected; got vec\"):\n        v2 = o3\n\ndef test_box_and_unbox_optional() -> None:\n    v = vec[Optional[str]]([\"3\", \"4\"])\n    o: Any = v\n    o[0] = None\n    v = o\n    assert v == vec[Optional[str]]([None, \"4\"])\n\n    v2 = vec[str]([\"4\"])\n    o2: Any = v2\n    o2[0] = \"5\"\n    v2 = o2\n    assert v2 == vec[str]([\"5\"])\n\n    o3: Any = vec[str]()\n    with assertRaises(TypeError, \"vec[str | None] object expected; got vec\"):\n        v = o3\n\n    o4: Any = vec[Optional[str]]([\"3\"])\n    with assertRaises(TypeError, \"vec[str] object expected; got vec\"):\n        v2 = o4\n\ndef test_construct_from_list_multiply() -> None:\n    for i in range(50):\n        v = vec[str]([str(i + 1)] * i)\n        assert len(v) == i\n        for j in range(i):\n            assert v[j] == str(i + 1)\n    for i in range(50):\n        v = vec[str](i * [str(i - 1)])\n        assert len(v) == i\n        for j in range(i):\n            assert v[j] == str(i - 1)\n\ndef test_construct_from_list_comprehension() -> None:\n    for i in range(50):\n        l = [i * i for i in range(i)]\n        v = vec[str]([str(n + 5) for n in l])\n        assert len(v) == i\n        for j in range(i):\n            assert v[j] == str(j * j + 5)\n\ndef test_construct_from_iterable() -> None:\n    for i in range(50):\n        it: Iterable[str] = iter([str(i * i) for i in range(i)])\n        v = vec[str](it)\n        assert len(v) == i\n        for j in range(i):\n            assert v[j] == str(j * j)\n\ndef test_equality() -> None:\n    v0 = vec[str]()\n    v0b = vec[str]()\n    v1 = vec[str]([\"1\"])\n    v1b = vec[str]([\"3\"])\n    assert v0 == v0\n    assert v1 == v1\n    assert v0 == v0b\n    assert v0 != v1\n    assert v1 != v1b\n    assert v1 != v0\n\ndef test_equality_optional() -> None:\n    v = vec[str]()\n    vo = vec[Optional[str]]()\n    assert v != vo\n    assert vo == vo\n    vo2 = vec[Optional[str]]([\"x\", None])\n    assert vo2 == vec[Optional[str]]([\"x\", None])\n    assert vo2 != vec[Optional[str]]([\"x\", \"y\"])\n    assert vo2 != vec[Optional[str]]([None, None])\n    assert vo2 != vec[Optional[str]]([\"x\", None, None])\n\ndef test_str_conversion() -> None:\n    v = vec[str]()\n    assert str(v) == \"vec[str]([])\"\n    assert repr(v) == \"vec[str]([])\"\n    v = vec[str]([\"126\"])\n    assert str(v) == \"vec[str](['126'])\"\n    v = append(v, \"5\")\n    assert str(v) == \"vec[str](['126', '5'])\"\n    v = append(v, \"xyz\")\n    assert str(v) == \"vec[str](['126', '5', 'xyz'])\"\n    v2 = vec[Optional[str]]()\n    assert str(v2) == \"vec[str | None]([])\"\n    v2 = vec[Optional[str]]([\"x\", None])\n    assert str(v2) == \"vec[str | None](['x', None])\"\n\ndef test_for_loop() -> None:\n    for n in vec[str]():\n        assert False\n    a = []\n    for n in vec[str]([\"5\"]):\n        a.append(n)\n    assert a == [\"5\"]\n    v = vec[str]([\"xyz\", \"9\", \"8\"])\n    a = []\n    for n in v:\n        a.append(n)\n    assert a == [\"xyz\", \"9\", \"8\"]\n    assert len(v) == 3\n\ndef test_contains() -> None:\n    v = vec[str]()\n    x = str()\n    assert x not in v\n    v = vec[str]([\"x\"])\n    assert x + \"x\" in v\n    assert x not in v\n    v2 = vec[str]([\"xyz\", \"7\", \"9\"])\n    assert x + \"xyz\" in v2\n    assert x + \"7\" in v2\n    assert x + \"9\" in v2\n    assert x not in v2\n    assert x + \"x\" not in v2\n\ndef test_slicing() -> None:\n    v = vec[str]()\n    assert v[:] == vec[str]([])\n    assert v[1:] == vec[str]([])\n    assert v[:-5] == vec[str]([])\n    v = vec[str]([\"0\", \"1\", \"2\", \"3\", \"4\"])\n    assert v[1:4] == vec[str]([\"1\", \"2\", \"3\"])\n    assert v[2:-1] == vec[str]([\"2\", \"3\"])\n    assert v[-2:-1] == vec[str]([\"3\"])\n    assert v[1:] == vec[str]([\"1\", \"2\", \"3\", \"4\"])\n    assert v[:-1] == vec[str]([\"0\", \"1\", \"2\", \"3\"])\n    assert v[:] == v\n    assert v[:] is not v\n    assert v[5:] == vec[str]()\n    assert v[100:] == vec[str]()\n    assert v[0:5] ==v\n    assert v[0:5] is not v\n    assert v[2:100] == vec[str]([\"2\", \"3\", \"4\"])\n    assert v[-100:2] == vec[str]([\"0\", \"1\"])\n    assert v[5:100] == vec[str]([])\n    assert v[50:100] == vec[str]([])\n    assert v[-100:-50] == vec[str]([])\n\ndef test_slicing_with_step() -> None:\n    v = vec[str]([\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"])\n    assert v[1:5:2] == vec[str]([\"1\", \"3\"])\n    assert v[1:6:2] == vec[str]([\"1\", \"3\", \"5\"])\n    assert v[5:1:-2] == vec[str]([\"5\", \"3\"])\n    assert v[6:1:-2] == vec[str]([\"6\", \"4\", \"2\"])\n    v = vec[str]([\"0\", \"1\", \"2\", \"3\", \"4\"])\n    assert v[::-1] == vec[str]([\"4\", \"3\", \"2\", \"1\", \"0\"])\n    with assertRaises(ValueError):\n        v[1:3:0]\n\ndef test_remove() -> None:\n    a = [\"4\", \"7\", \"xyz\"]\n    for i in a:\n        v = vec[str](a)\n        v = remove(v, i)\n        assert v == vec[str]([j for j in a if j != i])\n    v = vec[str](a)\n    v = remove(v, \"4\")\n    v = remove(v, \"7\")\n    v = remove(v, \"xyz\")\n    assert v == vec[str]()\n    with assertRaises(ValueError):\n        remove(v, \"4\")\n    v = append(v, \"5\")\n    with assertRaises(ValueError):\n        remove(v, \"7\")\n    v = remove(v, \"5\")\n    assert len(v) == 0\n    v = vec[str]([\"1\", \"1\", \"1\"])\n    v = remove(v, \"1\")\n    assert v == vec[str]([\"1\", \"1\"])\n    v = remove(v, \"1\")\n    assert v == vec[str]([\"1\"])\n    v = remove(v, \"1\")\n    assert v == vec[str]()\n    f: Any = 1.1\n    with assertRaises(TypeError):\n        remove(v, f)\n    s: Any = None\n    with assertRaises(TypeError):\n        remove(v, s)\n\ndef test_pop_last() -> None:\n    v = vec[str]([\"4\", \"7\", \"xyz\"])\n    v, n = pop(v)\n    assert n == \"xyz\"\n    assert v == vec[str]([\"4\", \"7\"])\n    v, n = pop(v)\n    assert n == \"7\"\n    assert v == vec[str]([\"4\"])\n    v, n = pop(v)\n    assert n == \"4\"\n    assert v == vec[str]()\n    with assertRaises(IndexError):\n       pop(v)\n\ndef test_pop_index() -> None:\n    v = vec[str]([\"4\", \"7\", \"9\", \"15\", \"22\"])\n    v, n = pop(v, 0)\n    assert n == \"4\"\n    assert v == vec[str]([\"7\", \"9\", \"15\", \"22\"])\n    v, n = pop(v, -1)\n    assert n == \"22\"\n    assert v == vec[str]([\"7\", \"9\", \"15\"])\n    v, n = pop(v, 1)\n    assert n == \"9\"\n    assert v == vec[str]([\"7\", \"15\"])\n\n    with assertRaises(IndexError):\n       pop(v, 2)\n\n    with assertRaises(IndexError):\n       pop(v, -3)\n\n    v, n = pop(v, -2)\n    assert n == \"7\"\n    assert v == vec[str]([\"15\"])\n    v, n = pop(v, 0)\n    assert n == \"15\"\n    assert v == vec[str]()\n\ndef test_pop_optional() -> None:\n    v = vec[Optional[str]]([\"x\" + str(), None])\n    v, s = pop(v)\n    assert s is None\n    v, s = pop(v)\n    assert s == \"x\"\n    assert len(v) == 0\n    v = vec[Optional[str]]([\"x\" + str(), None])\n    v, s = pop(v, 0)\n    assert s == \"x\"\n    v, s = pop(v, -1)\n    assert s is None\n\ndef f(x: vec[str]) -> None:\n    pass\n\ndef test_wrapper_arg_check() -> None:\n    f_any: Any = f\n    with assertRaises(TypeError):\n        f_any([])\n\nv: Final = vec[str]([\"x\", \"y\"])\n\ndef test_final() -> None:\n    assert v == vec[str]([\"x\", \"y\"])\n\ndef fdefault(v: vec[str] = vec[str]([\"x\"])) -> vec[str]:\n    return v\n\ndef test_default_arg() -> None:\n    assert fdefault() == vec[str]([\"x\"])\n    assert fdefault(vec[str]([\"y\"])) == vec[str]([\"y\"])\n    f_any: Any = fdefault\n    assert f_any() == vec[str]([\"x\"])\n    assert f_any(vec[str]([\"y\"])) == vec[str]([\"y\"])\n\ndef ftuple(b: bool) -> Tuple[vec[str], vec[str]]:\n    if b:\n        raise RuntimeError()\n    return vec[str]([\"x\"]), vec[str]()\n\ndef test_tuple() -> None:\n    t = ftuple(False)\n    assert len(t) == 2\n    assert t[0] == vec[str]([\"x\"])\n    assert t[1] == vec[str]()\n    a, b = t\n    assert a == t[0]\n    assert b == t[1]\n    with assertRaises(RuntimeError):\n        ftuple(True)\n    f_any: Any = ftuple\n    t2 = f_any(False)\n    assert t == t2\n    with assertRaises(RuntimeError):\n        f_any(True)\n\ndef test_optional_item_new_syntax() -> None:\n    v = vec[str | None]()\n    assert len(v) == 0\n    assert str(v) == \"vec[str | None]([])\"\n    v = append(v, 'x')\n    v = append(v, None)\n    assert str(v) == \"vec[str | None](['x', None])\"\n\nclass Foo:\n    def __init__(self, s: str) -> None:\n        self.s = s\n\ndef len_union(x: vec[str] | vec[Optional[Foo]]) -> int:\n    return len(x)\n\ndef test_union_of_vecs() -> None:\n    assert len_union(vec[str]()) == 0\n    assert len_union(vec[str]([\"x\", \"y\"])) == 2\n    assert len_union(vec[Optional[Foo]]([Foo(\"x\"), None, Foo(\"y\")])) == 3\n    with assertRaises(TypeError):\n        a1: Any = vec[Optional[str]]()\n        len_union(a1)\n    with assertRaises(TypeError):\n        a2: Any = []\n        len_union(a2)\n    with assertRaises(TypeError):\n        a3: Any = vec[bytes]()\n        len_union(a3)\n    with assertRaises(TypeError):\n        a4: Any = vec[Foo]()\n        len_union(a4)\n"
  },
  {
    "path": "mypyc/test-data/run-weakref.test",
    "content": "# Test cases for weakrefs (compile and run)\n\n[case testWeakrefRef]\n# mypy: disable-error-code=\"union-attr\"\nfrom weakref import proxy, ref\nfrom mypy_extensions import mypyc_attr\nfrom testutil import assertRaises\nfrom typing import Optional\n\n@mypyc_attr(native_class=False)\nclass Object:\n    \"\"\"some random weakreffable object\"\"\"\n    def some_meth(self) -> int:\n        return 1\n\n_callback_called_cache = {\"ref\": False, \"proxy\": False}\n\ndef test_weakref_ref() -> None:\n    obj: Optional[Object] = Object()\n    r = ref(obj)\n    assert r() is obj\n    obj = None\n    assert r() is None, r()\n\ndef test_weakref_ref_with_callback() -> None:\n    obj: Optional[Object] = Object()\n    r = ref(obj, lambda x: _callback_called_cache.__setitem__(\"ref\", True))\n    assert r() is obj\n    obj = None\n    assert r() is None, r()\n    assert _callback_called_cache[\"ref\"] is True\n\ndef test_weakref_proxy() -> None:\n    obj: Optional[Object] = Object()\n    p = proxy(obj)\n    assert obj.some_meth() == 1\n    assert p.some_meth() == 1\n    obj.some_meth()\n    obj = None\n    with assertRaises(ReferenceError):\n        p.some_meth()\n\ndef test_weakref_proxy_with_callback() -> None:\n    obj: Optional[Object] = Object()\n    p = proxy(obj, lambda x: _callback_called_cache.__setitem__(\"proxy\", True))\n    assert obj.some_meth() == 1\n    assert p.some_meth() == 1\n    obj.some_meth()\n    obj = None\n    with assertRaises(ReferenceError):\n        p.some_meth()\n    assert _callback_called_cache[\"proxy\"] is True\n"
  },
  {
    "path": "mypyc/transform/__init__.py",
    "content": ""
  },
  {
    "path": "mypyc/transform/copy_propagation.py",
    "content": "\"\"\"Simple copy propagation optimization.\n\nExample input:\n\n    x = f()\n    y = x\n\nThe register x is redundant and we can directly assign its value to y:\n\n    y = f()\n\nThis can optimize away registers that are assigned to once.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.ops import Assign, AssignMulti, LoadAddress, LoadErrorValue, Register, Value\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\nfrom mypyc.options import CompilerOptions\nfrom mypyc.sametype import is_same_type\nfrom mypyc.transform.ir_transform import IRTransform\n\n\ndef do_copy_propagation(fn: FuncIR, options: CompilerOptions) -> None:\n    \"\"\"Perform copy propagation optimization for fn.\"\"\"\n\n    # Anything with an assignment count >1 will not be optimized\n    # here, as it would be require data flow analysis and we want to\n    # keep this simple and fast, at least until we've made data flow\n    # analysis much faster.\n    counts: dict[Value, int] = {}\n    replacements: dict[Value, Value] = {}\n    for arg in fn.arg_regs:\n        # Arguments are always assigned to initially\n        counts[arg] = 1\n\n    for block in fn.blocks:\n        for op in block.ops:\n            if isinstance(op, Assign):\n                c = counts.get(op.dest, 0)\n                counts[op.dest] = c + 1\n                # Does this look like a supported assignment?\n                # TODO: Something needs LoadErrorValue assignments to be preserved?\n                if (\n                    c == 0\n                    and is_same_type(op.dest.type, op.src.type)\n                    and not isinstance(op.src, LoadErrorValue)\n                ):\n                    replacements[op.dest] = op.src\n                elif c == 1:\n                    # Too many assignments -- don't replace this one\n                    replacements.pop(op.dest, 0)\n            elif isinstance(op, AssignMulti):\n                # Copy propagation not supported for AssignMulti destinations\n                counts[op.dest] = 2\n                replacements.pop(op.dest, 0)\n            elif isinstance(op, LoadAddress):\n                # We don't support taking the address of an arbitrary Value,\n                # so we'll need to preserve the operands of LoadAddress.\n                if isinstance(op.src, Register):\n                    counts[op.src] = 2\n                    replacements.pop(op.src, 0)\n\n    # Follow chains of propagation with more than one assignment.\n    for src, dst in list(replacements.items()):\n        if counts.get(dst, 0) > 1:\n            # Not supported\n            del replacements[src]\n        else:\n            while dst in replacements:\n                dst = replacements[dst]\n                if counts.get(dst, 0) > 1:\n                    # Not supported\n                    del replacements[src]\n        if src in replacements:\n            replacements[src] = dst\n\n    builder = LowLevelIRBuilder(None, options)\n    transform = CopyPropagationTransform(builder, replacements)\n    transform.transform_blocks(fn.blocks)\n    fn.blocks = builder.blocks\n\n\nclass CopyPropagationTransform(IRTransform):\n    def __init__(self, builder: LowLevelIRBuilder, map: dict[Value, Value]) -> None:\n        super().__init__(builder)\n        self.op_map.update(map)\n        self.removed = set(map)\n\n    def visit_assign(self, op: Assign) -> Value | None:\n        if op.dest in self.removed:\n            return None\n        return self.add(op)\n"
  },
  {
    "path": "mypyc/transform/exceptions.py",
    "content": "\"\"\"Transform that inserts error checks after opcodes.\n\nWhen initially building the IR, the code doesn't perform error checks\nfor exceptions. This module is used to insert all required error checks\nafterwards. Each Op describes how it indicates an error condition (if\nat all).\n\nWe need to split basic blocks on each error check since branches can\nonly be placed at the end of a basic block.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.ops import (\n    ERR_ALWAYS,\n    ERR_FALSE,\n    ERR_MAGIC,\n    ERR_MAGIC_OVERLAPPING,\n    ERR_NEVER,\n    NO_TRACEBACK_LINE_NO,\n    BasicBlock,\n    Branch,\n    CallC,\n    ComparisonOp,\n    Float,\n    GetAttr,\n    Integer,\n    LoadErrorValue,\n    Op,\n    RegisterOp,\n    Return,\n    SetAttr,\n    TupleGet,\n    Value,\n)\nfrom mypyc.ir.rtypes import RTuple, bool_rprimitive, is_float_rprimitive\nfrom mypyc.primitives.exc_ops import err_occurred_op\nfrom mypyc.primitives.registry import CFunctionDescription\n\n\ndef insert_exception_handling(ir: FuncIR, strict_traceback_checks: bool) -> None:\n    # Generate error block if any ops may raise an exception. If an op\n    # fails without its own error handler, we'll branch to this\n    # block. The block just returns an error value.\n    error_label: BasicBlock | None = None\n    for block in ir.blocks:\n        adjust_error_kinds(block)\n        if error_label is None and any(op.can_raise() for op in block.ops):\n            error_label = add_default_handler_block(ir)\n    if error_label:\n        ir.blocks = split_blocks_at_errors(\n            ir.blocks, error_label, ir.traceback_name, strict_traceback_checks\n        )\n\n\ndef add_default_handler_block(ir: FuncIR) -> BasicBlock:\n    block = BasicBlock()\n    ir.blocks.append(block)\n    op = LoadErrorValue(ir.ret_type)\n    block.ops.append(op)\n    block.ops.append(Return(op))\n    return block\n\n\ndef split_blocks_at_errors(\n    blocks: list[BasicBlock],\n    default_error_handler: BasicBlock,\n    func_name: str | None,\n    strict_traceback_checks: bool,\n) -> list[BasicBlock]:\n    new_blocks: list[BasicBlock] = []\n\n    # First split blocks on ops that may raise.\n    for block in blocks:\n        ops = block.ops\n        block.ops = []\n        cur_block = block\n        new_blocks.append(cur_block)\n\n        # If the block has an error handler specified, use it. Otherwise\n        # fall back to the default.\n        error_label = block.error_handler or default_error_handler\n        block.error_handler = None\n\n        for op in ops:\n            target: Value = op\n            cur_block.ops.append(op)\n            if isinstance(op, RegisterOp) and op.error_kind != ERR_NEVER:\n                # Split\n                new_block = BasicBlock()\n                new_blocks.append(new_block)\n\n                if op.error_kind == ERR_MAGIC:\n                    # Op returns an error value on error that depends on result RType.\n                    variant = Branch.IS_ERROR\n                    negated = False\n                elif op.error_kind == ERR_FALSE:\n                    # Op returns a C false value on error.\n                    variant = Branch.BOOL\n                    negated = True\n                elif op.error_kind == ERR_ALWAYS:\n                    variant = Branch.BOOL\n                    negated = True\n                    # this is a hack to represent the always fail\n                    # semantics, using a temporary bool with value false\n                    target = Integer(0, bool_rprimitive)\n                elif op.error_kind == ERR_MAGIC_OVERLAPPING:\n                    comp = insert_overlapping_error_value_check(cur_block.ops, target)\n                    new_block2 = BasicBlock()\n                    new_blocks.append(new_block2)\n                    branch = Branch(\n                        comp,\n                        true_label=new_block2,\n                        false_label=new_block,\n                        op=Branch.BOOL,\n                        rare=True,\n                    )\n                    cur_block.ops.append(branch)\n                    cur_block = new_block2\n                    target = primitive_call(err_occurred_op, [], target.line)\n                    cur_block.ops.append(target)\n                    variant = Branch.IS_ERROR\n                    negated = True\n                else:\n                    assert False, \"unknown error kind %d\" % op.error_kind\n\n                # Void ops can't generate errors since error is always\n                # indicated by a special value stored in a register.\n                if op.error_kind != ERR_ALWAYS:\n                    assert not op.is_void, \"void op generating errors?\"\n\n                branch = Branch(\n                    target, true_label=error_label, false_label=new_block, op=variant, line=op.line\n                )\n                branch.negated = negated\n                if op.line != NO_TRACEBACK_LINE_NO and func_name is not None:\n                    if strict_traceback_checks:\n                        assert (\n                            op.line >= 0\n                        ), f\"Cannot add a traceback entry with a negative line number for op {op}\"\n                    branch.traceback_entry = (func_name, op.line)\n                cur_block.ops.append(branch)\n                cur_block = new_block\n\n    return new_blocks\n\n\ndef primitive_call(desc: CFunctionDescription, args: list[Value], line: int) -> CallC:\n    return CallC(\n        desc.c_function_name,\n        [],\n        desc.return_type,\n        desc.steals,\n        desc.is_borrowed,\n        desc.error_kind,\n        line,\n        dependencies=desc.dependencies,\n    )\n\n\ndef adjust_error_kinds(block: BasicBlock) -> None:\n    \"\"\"Infer more precise error_kind attributes for ops.\n\n    We have access here to more information than what was available\n    when the IR was initially built.\n    \"\"\"\n    for op in block.ops:\n        if isinstance(op, GetAttr):\n            if op.class_type.class_ir.is_always_defined(op.attr):\n                op.error_kind = ERR_NEVER\n        if isinstance(op, SetAttr):\n            if op.class_type.class_ir.is_always_defined(op.attr):\n                op.error_kind = ERR_NEVER\n\n\ndef insert_overlapping_error_value_check(ops: list[Op], target: Value) -> ComparisonOp:\n    \"\"\"Append to ops to check for an overlapping error value.\"\"\"\n    typ = target.type\n    if isinstance(typ, RTuple):\n        item = TupleGet(target, 0)\n        ops.append(item)\n        return insert_overlapping_error_value_check(ops, item)\n    else:\n        errvalue: Value\n        if is_float_rprimitive(target.type):\n            errvalue = Float(float(typ.c_undefined))\n        else:\n            errvalue = Integer(int(typ.c_undefined), rtype=typ)\n        op = ComparisonOp(target, errvalue, ComparisonOp.EQ)\n        ops.append(op)\n        return op\n"
  },
  {
    "path": "mypyc/transform/flag_elimination.py",
    "content": "\"\"\"Bool register elimination optimization.\n\nExample input:\n\n  L1:\n    r0 = f()\n    b = r0\n    goto L3\n  L2:\n    r1 = g()\n    b = r1\n    goto L3\n  L3:\n    if b goto L4 else goto L5\n\nThe register b is redundant and we replace the assignments with two copies of\nthe branch in L3:\n\n  L1:\n    r0 = f()\n    if r0 goto L4 else goto L5\n  L2:\n    r1 = g()\n    if r1 goto L4 else goto L5\n\nThis helps generate simpler IR for tagged integers comparisons, for example.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.ops import Assign, BasicBlock, Branch, Goto, Register, Unreachable\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\nfrom mypyc.options import CompilerOptions\nfrom mypyc.transform.ir_transform import IRTransform\n\n\ndef do_flag_elimination(fn: FuncIR, options: CompilerOptions) -> None:\n    # Find registers that are used exactly once as source, and in a branch.\n    counts: dict[Register, int] = {}\n    branches: dict[Register, Branch] = {}\n    labels: dict[Register, BasicBlock] = {}\n    for block in fn.blocks:\n        for i, op in enumerate(block.ops):\n            for src in op.sources():\n                if isinstance(src, Register):\n                    counts[src] = counts.get(src, 0) + 1\n            if i == 0 and isinstance(op, Branch) and isinstance(op.value, Register):\n                branches[op.value] = op\n                labels[op.value] = block\n\n    # Based on these we can find the candidate registers.\n    candidates: set[Register] = {\n        r for r in branches if counts.get(r, 0) == 1 and r not in fn.arg_regs\n    }\n\n    # Remove candidates with invalid assignments.\n    for block in fn.blocks:\n        for i, op in enumerate(block.ops):\n            if isinstance(op, Assign) and op.dest in candidates:\n                next_op = block.ops[i + 1]\n                if not (isinstance(next_op, Goto) and next_op.label is labels[op.dest]):\n                    # Not right\n                    candidates.remove(op.dest)\n\n    builder = LowLevelIRBuilder(None, options)\n    transform = FlagEliminationTransform(\n        builder, {x: y for x, y in branches.items() if x in candidates}\n    )\n    transform.transform_blocks(fn.blocks)\n    fn.blocks = builder.blocks\n\n\nclass FlagEliminationTransform(IRTransform):\n    def __init__(self, builder: LowLevelIRBuilder, branch_map: dict[Register, Branch]) -> None:\n        super().__init__(builder)\n        self.branch_map = branch_map\n        self.branches = set(branch_map.values())\n\n    def visit_assign(self, op: Assign) -> None:\n        if old_branch := self.branch_map.get(op.dest):\n            # Replace assignment with a copy of the old branch, which is in a\n            # separate basic block. The old branch will be deleted in visit_branch.\n            new_branch = Branch(\n                op.src,\n                old_branch.true,\n                old_branch.false,\n                old_branch.op,\n                old_branch.line,\n                rare=old_branch.rare,\n            )\n            new_branch.negated = old_branch.negated\n            new_branch.traceback_entry = old_branch.traceback_entry\n            self.add(new_branch)\n        else:\n            self.add(op)\n\n    def visit_goto(self, op: Goto) -> None:\n        # This is a no-op if basic block already terminated\n        self.builder.goto(op.label)\n\n    def visit_branch(self, op: Branch) -> None:\n        if op in self.branches:\n            # This branch is optimized away\n            self.add(Unreachable())\n        else:\n            self.add(op)\n"
  },
  {
    "path": "mypyc/transform/ir_transform.py",
    "content": "\"\"\"Helpers for implementing generic IR to IR transforms.\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final\n\nfrom mypyc.ir.ops import (\n    Assign,\n    AssignMulti,\n    BasicBlock,\n    Box,\n    Branch,\n    Call,\n    CallC,\n    Cast,\n    ComparisonOp,\n    DecRef,\n    Extend,\n    FloatComparisonOp,\n    FloatNeg,\n    FloatOp,\n    GetAttr,\n    GetElement,\n    GetElementPtr,\n    Goto,\n    IncRef,\n    InitStatic,\n    IntOp,\n    KeepAlive,\n    LoadAddress,\n    LoadErrorValue,\n    LoadGlobal,\n    LoadLiteral,\n    LoadMem,\n    LoadStatic,\n    MethodCall,\n    Op,\n    OpVisitor,\n    PrimitiveOp,\n    RaiseStandardError,\n    Return,\n    SetAttr,\n    SetElement,\n    SetMem,\n    Truncate,\n    TupleGet,\n    TupleSet,\n    Unborrow,\n    Unbox,\n    Unreachable,\n    Value,\n)\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\n\n\nclass IRTransform(OpVisitor[Value | None]):\n    \"\"\"Identity transform.\n\n    Subclass and override to perform changes to IR.\n\n    Subclass IRTransform and override any OpVisitor visit_* methods\n    that perform any IR changes. The default implementations implement\n    an identity transform.\n\n    A visit method can return None to remove ops. In this case the\n    transform must ensure that no op uses the original removed op\n    as a source after the transform.\n\n    You can retain old BasicBlock and op references in ops. The transform\n    will automatically patch these for you as needed.\n    \"\"\"\n\n    def __init__(self, builder: LowLevelIRBuilder) -> None:\n        self.builder = builder\n        # Subclasses add additional op mappings here. A None value indicates\n        # that the op/register is deleted.\n        self.op_map: dict[Value, Value | None] = {}\n\n    def transform_blocks(self, blocks: list[BasicBlock]) -> None:\n        \"\"\"Transform basic blocks that represent a single function.\n\n        The result of the transform will be collected at self.builder.blocks.\n        \"\"\"\n        block_map: dict[BasicBlock, BasicBlock] = {}\n        op_map = self.op_map\n        empties = set()\n        for block in blocks:\n            new_block = BasicBlock()\n            block_map[block] = new_block\n            self.builder.activate_block(new_block)\n            new_block.error_handler = block.error_handler\n            for op in block.ops:\n                new_op = op.accept(self)\n                if new_op is not op:\n                    op_map[op] = new_op\n            # A transform can produce empty blocks which can be removed.\n            if is_empty_block(new_block) and not is_empty_block(block):\n                empties.add(new_block)\n        self.builder.blocks = [block for block in self.builder.blocks if block not in empties]\n        # Update all op/block references to point to the transformed ones.\n        patcher = PatchVisitor(op_map, block_map)\n        for block in self.builder.blocks:\n            for op in block.ops:\n                op.accept(patcher)\n            if block.error_handler is not None:\n                block.error_handler = block_map.get(block.error_handler, block.error_handler)\n\n    def add(self, op: Op) -> Value:\n        return self.builder.add(op)\n\n    def visit_goto(self, op: Goto) -> None:\n        self.add(op)\n\n    def visit_branch(self, op: Branch) -> None:\n        self.add(op)\n\n    def visit_return(self, op: Return) -> None:\n        self.add(op)\n\n    def visit_unreachable(self, op: Unreachable) -> None:\n        self.add(op)\n\n    def visit_assign(self, op: Assign) -> Value | None:\n        if op.src in self.op_map and self.op_map[op.src] is None:\n            # Special case: allow removing register initialization assignments\n            return None\n        return self.add(op)\n\n    def visit_assign_multi(self, op: AssignMulti) -> Value | None:\n        return self.add(op)\n\n    def visit_load_error_value(self, op: LoadErrorValue) -> Value | None:\n        return self.add(op)\n\n    def visit_load_literal(self, op: LoadLiteral) -> Value | None:\n        return self.add(op)\n\n    def visit_get_attr(self, op: GetAttr) -> Value | None:\n        return self.add(op)\n\n    def visit_set_attr(self, op: SetAttr) -> Value | None:\n        return self.add(op)\n\n    def visit_load_static(self, op: LoadStatic) -> Value | None:\n        return self.add(op)\n\n    def visit_init_static(self, op: InitStatic) -> Value | None:\n        return self.add(op)\n\n    def visit_tuple_get(self, op: TupleGet) -> Value | None:\n        return self.add(op)\n\n    def visit_tuple_set(self, op: TupleSet) -> Value | None:\n        return self.add(op)\n\n    def visit_inc_ref(self, op: IncRef) -> Value | None:\n        return self.add(op)\n\n    def visit_dec_ref(self, op: DecRef) -> Value | None:\n        return self.add(op)\n\n    def visit_call(self, op: Call) -> Value | None:\n        return self.add(op)\n\n    def visit_method_call(self, op: MethodCall) -> Value | None:\n        return self.add(op)\n\n    def visit_cast(self, op: Cast) -> Value | None:\n        return self.add(op)\n\n    def visit_box(self, op: Box) -> Value | None:\n        return self.add(op)\n\n    def visit_unbox(self, op: Unbox) -> Value | None:\n        return self.add(op)\n\n    def visit_raise_standard_error(self, op: RaiseStandardError) -> Value | None:\n        return self.add(op)\n\n    def visit_call_c(self, op: CallC) -> Value | None:\n        return self.add(op)\n\n    def visit_primitive_op(self, op: PrimitiveOp) -> Value | None:\n        return self.add(op)\n\n    def visit_truncate(self, op: Truncate) -> Value | None:\n        return self.add(op)\n\n    def visit_extend(self, op: Extend) -> Value | None:\n        return self.add(op)\n\n    def visit_load_global(self, op: LoadGlobal) -> Value | None:\n        return self.add(op)\n\n    def visit_int_op(self, op: IntOp) -> Value | None:\n        return self.add(op)\n\n    def visit_comparison_op(self, op: ComparisonOp) -> Value | None:\n        return self.add(op)\n\n    def visit_float_op(self, op: FloatOp) -> Value | None:\n        return self.add(op)\n\n    def visit_float_neg(self, op: FloatNeg) -> Value | None:\n        return self.add(op)\n\n    def visit_float_comparison_op(self, op: FloatComparisonOp) -> Value | None:\n        return self.add(op)\n\n    def visit_load_mem(self, op: LoadMem) -> Value | None:\n        return self.add(op)\n\n    def visit_set_mem(self, op: SetMem) -> Value | None:\n        return self.add(op)\n\n    def visit_get_element(self, op: GetElement) -> Value | None:\n        return self.add(op)\n\n    def visit_get_element_ptr(self, op: GetElementPtr) -> Value | None:\n        return self.add(op)\n\n    def visit_set_element(self, op: SetElement) -> Value | None:\n        return self.add(op)\n\n    def visit_load_address(self, op: LoadAddress) -> Value | None:\n        return self.add(op)\n\n    def visit_keep_alive(self, op: KeepAlive) -> Value | None:\n        return self.add(op)\n\n    def visit_unborrow(self, op: Unborrow) -> Value | None:\n        return self.add(op)\n\n\nclass PatchVisitor(OpVisitor[None]):\n    def __init__(\n        self, op_map: dict[Value, Value | None], block_map: dict[BasicBlock, BasicBlock]\n    ) -> None:\n        self.op_map: Final = op_map\n        self.block_map: Final = block_map\n\n    def fix_op(self, op: Value) -> Value:\n        new = self.op_map.get(op, op)\n        assert new is not None, \"use of removed op\"\n        return new\n\n    def fix_block(self, block: BasicBlock) -> BasicBlock:\n        return self.block_map.get(block, block)\n\n    def visit_goto(self, op: Goto) -> None:\n        op.label = self.fix_block(op.label)\n\n    def visit_branch(self, op: Branch) -> None:\n        op.value = self.fix_op(op.value)\n        op.true = self.fix_block(op.true)\n        op.false = self.fix_block(op.false)\n\n    def visit_return(self, op: Return) -> None:\n        op.value = self.fix_op(op.value)\n\n    def visit_unreachable(self, op: Unreachable) -> None:\n        pass\n\n    def visit_assign(self, op: Assign) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_assign_multi(self, op: AssignMulti) -> None:\n        op.src = [self.fix_op(s) for s in op.src]\n\n    def visit_load_error_value(self, op: LoadErrorValue) -> None:\n        pass\n\n    def visit_load_literal(self, op: LoadLiteral) -> None:\n        pass\n\n    def visit_get_attr(self, op: GetAttr) -> None:\n        op.obj = self.fix_op(op.obj)\n\n    def visit_set_attr(self, op: SetAttr) -> None:\n        op.obj = self.fix_op(op.obj)\n        op.src = self.fix_op(op.src)\n\n    def visit_load_static(self, op: LoadStatic) -> None:\n        pass\n\n    def visit_init_static(self, op: InitStatic) -> None:\n        op.value = self.fix_op(op.value)\n\n    def visit_tuple_get(self, op: TupleGet) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_tuple_set(self, op: TupleSet) -> None:\n        op.items = [self.fix_op(item) for item in op.items]\n\n    def visit_inc_ref(self, op: IncRef) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_dec_ref(self, op: DecRef) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_call(self, op: Call) -> None:\n        op.args = [self.fix_op(arg) for arg in op.args]\n\n    def visit_method_call(self, op: MethodCall) -> None:\n        op.obj = self.fix_op(op.obj)\n        op.args = [self.fix_op(arg) for arg in op.args]\n\n    def visit_cast(self, op: Cast) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_box(self, op: Box) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_unbox(self, op: Unbox) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_raise_standard_error(self, op: RaiseStandardError) -> None:\n        if isinstance(op.value, Value):\n            op.value = self.fix_op(op.value)\n\n    def visit_call_c(self, op: CallC) -> None:\n        op.args = [self.fix_op(arg) for arg in op.args]\n\n    def visit_primitive_op(self, op: PrimitiveOp) -> None:\n        op.args = [self.fix_op(arg) for arg in op.args]\n\n    def visit_truncate(self, op: Truncate) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_extend(self, op: Extend) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_load_global(self, op: LoadGlobal) -> None:\n        pass\n\n    def visit_int_op(self, op: IntOp) -> None:\n        op.lhs = self.fix_op(op.lhs)\n        op.rhs = self.fix_op(op.rhs)\n\n    def visit_comparison_op(self, op: ComparisonOp) -> None:\n        op.lhs = self.fix_op(op.lhs)\n        op.rhs = self.fix_op(op.rhs)\n\n    def visit_float_op(self, op: FloatOp) -> None:\n        op.lhs = self.fix_op(op.lhs)\n        op.rhs = self.fix_op(op.rhs)\n\n    def visit_float_neg(self, op: FloatNeg) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_float_comparison_op(self, op: FloatComparisonOp) -> None:\n        op.lhs = self.fix_op(op.lhs)\n        op.rhs = self.fix_op(op.rhs)\n\n    def visit_load_mem(self, op: LoadMem) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_set_mem(self, op: SetMem) -> None:\n        op.dest = self.fix_op(op.dest)\n        op.src = self.fix_op(op.src)\n\n    def visit_get_element(self, op: GetElement) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_get_element_ptr(self, op: GetElementPtr) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_set_element(self, op: SetElement) -> None:\n        op.src = self.fix_op(op.src)\n\n    def visit_load_address(self, op: LoadAddress) -> None:\n        if isinstance(op.src, LoadStatic):\n            new = self.fix_op(op.src)\n            assert isinstance(new, LoadStatic), new\n            op.src = new\n\n    def visit_keep_alive(self, op: KeepAlive) -> None:\n        op.src = [self.fix_op(s) for s in op.src]\n\n    def visit_unborrow(self, op: Unborrow) -> None:\n        op.src = self.fix_op(op.src)\n\n\ndef is_empty_block(block: BasicBlock) -> bool:\n    return len(block.ops) == 1 and isinstance(block.ops[0], Unreachable)\n"
  },
  {
    "path": "mypyc/transform/log_trace.py",
    "content": "\"\"\"This optional pass adds logging of various executed operations.\n\nSome subset of the executed operations are logged to the mypyc_trace.txt file.\n\nThis is useful for performance analysis. For example, it's possible\nto identify how frequently various primitive functions are called,\nand in which code locations they are called.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom typing import Final\n\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.ops import (\n    Box,\n    Call,\n    CallC,\n    Cast,\n    CString,\n    DecRef,\n    GetAttr,\n    IncRef,\n    LoadLiteral,\n    LoadStatic,\n    Op,\n    PrimitiveOp,\n    SetAttr,\n    Unbox,\n    Value,\n)\nfrom mypyc.ir.rtypes import none_rprimitive\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\nfrom mypyc.options import CompilerOptions\nfrom mypyc.primitives.misc_ops import log_trace_event\nfrom mypyc.transform.ir_transform import IRTransform\n\n\ndef insert_event_trace_logging(fn: FuncIR, options: CompilerOptions) -> None:\n    builder = LowLevelIRBuilder(None, options)\n    transform = LogTraceEventTransform(builder, fn.decl.fullname)\n    transform.transform_blocks(fn.blocks)\n    fn.blocks = builder.blocks\n\n\ndef get_load_global_name(op: CallC) -> str | None:\n    name = op.function_name\n    if name == \"CPyDict_GetItem\":\n        arg = op.args[0]\n        if (\n            isinstance(arg, LoadStatic)\n            and arg.namespace == \"static\"\n            and arg.identifier == \"globals\"\n            and isinstance(op.args[1], LoadLiteral)\n        ):\n            return str(op.args[1].value)\n    return None\n\n\n# These primitives perform an implicit IncRef for the return value. Only some of the most common ones\n# are included, and mostly ops that could be switched to use borrowing in some contexts.\nprimitives_that_inc_ref: Final = {\n    \"list_get_item_unsafe\",\n    \"CPyList_GetItemShort\",\n    \"CPyDict_GetWithNone\",\n    \"CPyList_GetItem\",\n    \"CPyDict_GetItem\",\n    \"CPyList_PopLast\",\n}\n\n\nclass LogTraceEventTransform(IRTransform):\n    def __init__(self, builder: LowLevelIRBuilder, fullname: str) -> None:\n        super().__init__(builder)\n        self.fullname = fullname.encode(\"utf-8\")\n\n    def visit_call(self, op: Call) -> Value:\n        # TODO: Use different op name when constructing an instance\n        return self.log(op, \"call\", op.fn.fullname)\n\n    def visit_primitive_op(self, op: PrimitiveOp) -> Value:\n        value = self.log(op, \"primitive_op\", op.desc.name)\n        if op.desc.name in primitives_that_inc_ref:\n            self.log_inc_ref(value)\n        return value\n\n    def visit_call_c(self, op: CallC) -> Value:\n        if global_name := get_load_global_name(op):\n            return self.log(op, \"globals_dict_get_item\", global_name)\n\n        func_name = op.function_name\n        if func_name == \"PyObject_Vectorcall\" and isinstance(op.args[0], CallC):\n            if global_name := get_load_global_name(op.args[0]):\n                return self.log(op, \"python_call_global\", global_name)\n        elif func_name == \"CPyObject_GetAttr\" and isinstance(op.args[1], LoadLiteral):\n            return self.log(op, \"python_get_attr\", str(op.args[1].value))\n        elif func_name == \"PyObject_VectorcallMethod\" and isinstance(op.args[0], LoadLiteral):\n            return self.log(op, \"python_call_method\", str(op.args[0].value))\n\n        value = self.log(op, \"call_c\", func_name)\n        if func_name in primitives_that_inc_ref:\n            self.log_inc_ref(value)\n        return value\n\n    def visit_get_attr(self, op: GetAttr) -> Value:\n        value = self.log(op, \"get_attr\", f\"{op.class_type.name}.{op.attr}\")\n        if not op.is_borrowed and op.type.is_refcounted:\n            self.log_inc_ref(op)\n        return value\n\n    def visit_set_attr(self, op: SetAttr) -> Value:\n        name = \"set_attr\" if not op.is_init else \"set_attr_init\"\n        return self.log(op, name, f\"{op.class_type.name}.{op.attr}\")\n\n    def visit_box(self, op: Box) -> Value:\n        if op.src.type is none_rprimitive:\n            # Boxing 'None' is a very quick operation, so we don't log it.\n            return self.add(op)\n        else:\n            return self.log(op, \"box\", str(op.src.type))\n\n    def visit_unbox(self, op: Unbox) -> Value:\n        return self.log(op, \"unbox\", str(op.type))\n\n    def visit_cast(self, op: Cast) -> Value | None:\n        value = self.log(op, \"cast\", str(op.type))\n        if not op.is_borrowed:\n            self.log_inc_ref(value)\n        return value\n\n    def visit_inc_ref(self, op: IncRef) -> Value:\n        return self.log(op, \"inc_ref\", str(op.src.type))\n\n    def visit_dec_ref(self, op: DecRef) -> Value:\n        return self.log(op, \"dec_ref\", str(op.src.type))\n\n    def log_inc_ref(self, value: Value) -> None:\n        self.log_event(\"inc_ref\", str(value.type), value.line)\n\n    def log(self, op: Op, name: str, details: str) -> Value:\n        self.log_event(name, details, op.line)\n        return self.add(op)\n\n    def log_event(self, name: str, details: str, line: int) -> None:\n        if line >= 0:\n            line_str = str(line)\n        else:\n            line_str = \"\"\n        self.builder.primitive_op(\n            log_trace_event,\n            [\n                CString(self.fullname),\n                CString(line_str.encode(\"ascii\")),\n                CString(name.encode(\"utf-8\")),\n                CString(details.encode(\"utf-8\")),\n            ],\n            line,\n        )\n"
  },
  {
    "path": "mypyc/transform/lower.py",
    "content": "\"\"\"Transform IR to lower-level ops.\n\nHigher-level ops are used in earlier compiler passes, as they make\nvarious analyses, optimizations and transforms easier to implement.\nLater passes use lower-level ops, as they are easier to generate code\nfrom, and they help with lower-level optimizations.\n\nLowering of various primitive ops is implemented in the mypyc.lower\npackage.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.ops import PrimitiveOp, Value\nfrom mypyc.irbuild.ll_builder import LowLevelIRBuilder\nfrom mypyc.lower.registry import lowering_registry\nfrom mypyc.options import CompilerOptions\nfrom mypyc.transform.ir_transform import IRTransform\n\n\ndef lower_ir(ir: FuncIR, options: CompilerOptions) -> None:\n    builder = LowLevelIRBuilder(None, options)\n    visitor = LoweringVisitor(builder)\n    visitor.transform_blocks(ir.blocks)\n    ir.blocks = builder.blocks\n\n\nclass LoweringVisitor(IRTransform):\n    def visit_primitive_op(self, op: PrimitiveOp) -> Value | None:\n        # The lowering implementation functions of various primitive ops are stored\n        # in a registry, which is populated using function decorators. The name\n        # of op (such as \"int_eq\") is used as the key.\n        lower_fn = lowering_registry[op.desc.name]\n        return lower_fn(self.builder, op.args, op.line)\n"
  },
  {
    "path": "mypyc/transform/refcount.py",
    "content": "\"\"\"Transformation for inserting refrecence count inc/dec opcodes.\n\nThis transformation happens towards the end of compilation. Before this\ntransformation, reference count management is not explicitly handled at all.\nBy postponing this pass, the previous passes are simpler as they don't have\nto update reference count opcodes.\n\nThe approach is to decrement reference counts soon after a value is no\nlonger live, to quickly free memory (and call __del__ methods), though\nthere are no strict guarantees -- other than that local variables are\nfreed before return from a function.\n\nFunction arguments are a little special. They are initially considered\n'borrowed' from the caller and their reference counts don't need to be\ndecremented before returning. An assignment to a borrowed value turns it\ninto a regular, owned reference that needs to freed before return.\n\"\"\"\n\nfrom __future__ import annotations\n\nfrom collections.abc import Iterable\n\nfrom mypyc.analysis.dataflow import (\n    AnalysisDict,\n    analyze_borrowed_arguments,\n    analyze_live_regs,\n    analyze_must_defined_regs,\n    cleanup_cfg,\n    get_cfg,\n)\nfrom mypyc.ir.func_ir import FuncIR, all_values\nfrom mypyc.ir.ops import (\n    Assign,\n    BasicBlock,\n    Branch,\n    CallC,\n    ControlOp,\n    DecRef,\n    Goto,\n    IncRef,\n    Integer,\n    KeepAlive,\n    LoadAddress,\n    Op,\n    Register,\n    RegisterOp,\n    Undef,\n    Value,\n)\n\nDecs = tuple[tuple[Value, bool], ...]\nIncs = tuple[Value, ...]\n\n# A cache of basic blocks that decrement and increment specific values\n# and then jump to some target block. This lets us cut down on how\n# much code we generate in some circumstances.\nBlockCache = dict[tuple[BasicBlock, Decs, Incs], BasicBlock]\n\n\ndef insert_ref_count_opcodes(ir: FuncIR) -> None:\n    \"\"\"Insert reference count inc/dec opcodes to a function.\n\n    This is the entry point to this module.\n    \"\"\"\n    cfg = get_cfg(ir.blocks)\n    values = all_values(ir.arg_regs, ir.blocks)\n\n    borrowed = {value for value in values if value.is_borrowed}\n    args: set[Value] = set(ir.arg_regs)\n    live = analyze_live_regs(ir.blocks, cfg)\n    borrow = analyze_borrowed_arguments(ir.blocks, cfg, borrowed)\n    defined = analyze_must_defined_regs(ir.blocks, cfg, args, values, strict_errors=True)\n    ordering = make_value_ordering(ir)\n    cache: BlockCache = {}\n    for block in ir.blocks.copy():\n        if isinstance(block.ops[-1], (Branch, Goto)):\n            insert_branch_inc_and_decrefs(\n                block,\n                cache,\n                ir.blocks,\n                live.before,\n                borrow.before,\n                borrow.after,\n                defined.after,\n                ordering,\n            )\n        transform_block(block, live.before, live.after, borrow.before, defined.after)\n\n    cleanup_cfg(ir.blocks)\n\n\ndef is_maybe_undefined(post_must_defined: set[Value], src: Value) -> bool:\n    return (isinstance(src, Register) and src not in post_must_defined) or (\n        isinstance(src, CallC) and src.returns_null\n    )\n\n\ndef maybe_append_dec_ref(\n    ops: list[Op], dest: Value, defined: AnalysisDict[Value], key: tuple[BasicBlock, int]\n) -> None:\n    if dest.type.is_refcounted and not isinstance(dest, (Integer, Undef)):\n        ops.append(DecRef(dest, is_xdec=is_maybe_undefined(defined[key], dest)))\n\n\ndef maybe_append_inc_ref(ops: list[Op], dest: Value) -> None:\n    if dest.type.is_refcounted:\n        ops.append(IncRef(dest))\n\n\ndef transform_block(\n    block: BasicBlock,\n    pre_live: AnalysisDict[Value],\n    post_live: AnalysisDict[Value],\n    pre_borrow: AnalysisDict[Value],\n    post_must_defined: AnalysisDict[Value],\n) -> None:\n    old_ops = block.ops\n    ops: list[Op] = []\n    for i, op in enumerate(old_ops):\n        key = (block, i)\n\n        assert op not in pre_live[key]\n        dest = op.dest if isinstance(op, Assign) else op\n        stolen = op.stolen()\n\n        # Incref any references that are being stolen that stay live, were borrowed,\n        # or are stolen more than once by this operation.\n        for j, src in enumerate(stolen):\n            if src in post_live[key] or src in pre_borrow[key] or src in stolen[:j]:\n                maybe_append_inc_ref(ops, src)\n                # For assignments to registers that were already live,\n                # decref the old value.\n                if dest not in pre_borrow[key] and dest in pre_live[key]:\n                    assert isinstance(op, Assign), op\n                    maybe_append_dec_ref(ops, dest, post_must_defined, key)\n\n        # Strip KeepAlive. Its only purpose is to help with this transform.\n        if not isinstance(op, KeepAlive):\n            ops.append(op)\n\n        # Control ops don't have any space to insert ops after them, so\n        # their inc/decrefs get inserted by insert_branch_inc_and_decrefs.\n        if isinstance(op, ControlOp):\n            continue\n\n        for src in op.unique_sources():\n            # Decrement source that won't be live afterwards.\n            if src not in post_live[key] and src not in pre_borrow[key] and src not in stolen:\n                maybe_append_dec_ref(ops, src, post_must_defined, key)\n        # Decrement the destination if it is dead after the op and\n        # wasn't a borrowed RegisterOp\n        if (\n            not dest.is_void\n            and dest not in post_live[key]\n            and not (isinstance(op, RegisterOp) and dest.is_borrowed)\n        ):\n            maybe_append_dec_ref(ops, dest, post_must_defined, key)\n    block.ops = ops\n\n\ndef insert_branch_inc_and_decrefs(\n    block: BasicBlock,\n    cache: BlockCache,\n    blocks: list[BasicBlock],\n    pre_live: AnalysisDict[Value],\n    pre_borrow: AnalysisDict[Value],\n    post_borrow: AnalysisDict[Value],\n    post_must_defined: AnalysisDict[Value],\n    ordering: dict[Value, int],\n) -> None:\n    \"\"\"Insert inc_refs and/or dec_refs after a branch/goto.\n\n    Add dec_refs for registers that become dead after a branch.\n    Add inc_refs for registers that become unborrowed after a branch or goto.\n\n    Branches are special as the true and false targets may have a different\n    live and borrowed register sets. Add new blocks before the true/false target\n    blocks that tweak reference counts.\n\n    Example where we need to add an inc_ref:\n\n      def f(a: int) -> None\n          if a:\n              a = 1\n          return a  # a is borrowed if condition is false and unborrowed if true\n    \"\"\"\n    prev_key = (block, len(block.ops) - 1)\n    source_live_regs = pre_live[prev_key]\n    source_borrowed = post_borrow[prev_key]\n    source_defined = post_must_defined[prev_key]\n\n    term = block.terminator\n    for i, target in enumerate(term.targets()):\n        # HAX: After we've checked against an error value the value we must not touch the\n        #      refcount since it will be a null pointer. The correct way to do this would be\n        #      to perform data flow analysis on whether a value can be null (or is always\n        #      null).\n        omitted: Iterable[Value]\n        if isinstance(term, Branch) and term.op == Branch.IS_ERROR and i == 0:\n            omitted = (term.value,)\n        else:\n            omitted = ()\n\n        decs = after_branch_decrefs(\n            target, pre_live, source_defined, source_borrowed, source_live_regs, ordering, omitted\n        )\n        incs = after_branch_increfs(target, pre_live, pre_borrow, source_borrowed, ordering)\n        term.set_target(i, add_block(decs, incs, cache, blocks, target))\n\n\ndef after_branch_decrefs(\n    label: BasicBlock,\n    pre_live: AnalysisDict[Value],\n    source_defined: set[Value],\n    source_borrowed: set[Value],\n    source_live_regs: set[Value],\n    ordering: dict[Value, int],\n    omitted: Iterable[Value],\n) -> tuple[tuple[Value, bool], ...]:\n    target_pre_live = pre_live[label, 0]\n    decref = source_live_regs - target_pre_live - source_borrowed\n    if decref:\n        return tuple(\n            (reg, is_maybe_undefined(source_defined, reg))\n            for reg in sorted(decref, key=lambda r: ordering[r])\n            if reg.type.is_refcounted and reg not in omitted\n        )\n    return ()\n\n\ndef after_branch_increfs(\n    label: BasicBlock,\n    pre_live: AnalysisDict[Value],\n    pre_borrow: AnalysisDict[Value],\n    source_borrowed: set[Value],\n    ordering: dict[Value, int],\n) -> tuple[Value, ...]:\n    target_pre_live = pre_live[label, 0]\n    target_borrowed = pre_borrow[label, 0]\n    incref = (source_borrowed - target_borrowed) & target_pre_live\n    if incref:\n        return tuple(\n            reg for reg in sorted(incref, key=lambda r: ordering[r]) if reg.type.is_refcounted\n        )\n    return ()\n\n\ndef add_block(\n    decs: Decs, incs: Incs, cache: BlockCache, blocks: list[BasicBlock], label: BasicBlock\n) -> BasicBlock:\n    if not decs and not incs:\n        return label\n\n    # TODO: be able to share *partial* results\n    if (label, decs, incs) in cache:\n        return cache[label, decs, incs]\n\n    block = BasicBlock()\n    blocks.append(block)\n    block.ops.extend(DecRef(reg, is_xdec=xdec) for reg, xdec in decs)\n    block.ops.extend(IncRef(reg) for reg in incs)\n    block.ops.append(Goto(label))\n    cache[label, decs, incs] = block\n    return block\n\n\ndef make_value_ordering(ir: FuncIR) -> dict[Value, int]:\n    \"\"\"Create a ordering of values that allows them to be sorted.\n\n    This omits registers that are only ever read.\n    \"\"\"\n    # TODO: Never initialized values??\n    result: dict[Value, int] = {}\n    n = 0\n\n    for arg in ir.arg_regs:\n        result[arg] = n\n        n += 1\n\n    for block in ir.blocks:\n        for op in block.ops:\n            if (\n                isinstance(op, LoadAddress)\n                and isinstance(op.src, Register)\n                and op.src not in result\n            ):\n                # Taking the address of a register allows initialization.\n                result[op.src] = n\n                n += 1\n            if isinstance(op, Assign):\n                if op.dest not in result:\n                    result[op.dest] = n\n                    n += 1\n            elif op not in result:\n                result[op] = n\n                n += 1\n\n    return result\n"
  },
  {
    "path": "mypyc/transform/spill.py",
    "content": "\"\"\"Insert spills for values that are live across yields.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.analysis.dataflow import AnalysisResult, analyze_live_regs, get_cfg\nfrom mypyc.common import TEMP_ATTR_NAME\nfrom mypyc.ir.class_ir import ClassIR\nfrom mypyc.ir.func_ir import FuncIR\nfrom mypyc.ir.ops import (\n    BasicBlock,\n    Branch,\n    DecRef,\n    GetAttr,\n    IncRef,\n    LoadErrorValue,\n    Register,\n    SetAttr,\n    Value,\n)\n\n\ndef insert_spills(ir: FuncIR, env: ClassIR) -> None:\n    cfg = get_cfg(ir.blocks, use_yields=True)\n    live = analyze_live_regs(ir.blocks, cfg)\n    entry_live = live.before[ir.blocks[0], 0]\n\n    entry_live = {op for op in entry_live if not (isinstance(op, Register) and op.is_arg)}\n    # TODO: Actually for now, no Registers at all -- we keep the manual spills\n    entry_live = {op for op in entry_live if not isinstance(op, Register)}\n\n    ir.blocks = spill_regs(ir.blocks, env, entry_live, live, ir.arg_regs[0])\n\n\ndef spill_regs(\n    blocks: list[BasicBlock],\n    env: ClassIR,\n    to_spill: set[Value],\n    live: AnalysisResult[Value],\n    self_reg: Register,\n) -> list[BasicBlock]:\n    env_reg: Value\n    for op in blocks[0].ops:\n        if isinstance(op, GetAttr) and op.attr == \"__mypyc_env__\":\n            env_reg = op\n            break\n    else:\n        # Environment has been merged into generator object\n        env_reg = self_reg\n\n    spill_locs = {}\n    for i, val in enumerate(to_spill):\n        name = f\"{TEMP_ATTR_NAME}2_{i}\"\n        env.attributes[name] = val.type\n        if val.type.error_overlap:\n            # We can safely treat as always initialized, since the type has no pointers.\n            # This way we also don't need to manage the defined attribute bitfield.\n            env._always_initialized_attrs.add(name)\n        spill_locs[val] = name\n\n    for block in blocks:\n        ops = block.ops\n        block.ops = []\n\n        for i, op in enumerate(ops):\n            to_decref = []\n\n            if isinstance(op, IncRef) and op.src in spill_locs:\n                raise AssertionError(\"not sure what to do with an incref of a spill...\")\n            if isinstance(op, DecRef) and op.src in spill_locs:\n                # When we decref a spilled value, we turn that into\n                # NULLing out the attribute, but only if the spilled\n                # value is not live *when we include yields in the\n                # CFG*. (The original decrefs are computed without that.)\n                #\n                # We also skip a decref is the env register is not\n                # live. That should only happen when an exception is\n                # being raised, so everything should be handled there.\n                if op.src not in live.after[block, i] and env_reg in live.after[block, i]:\n                    # Skip the DecRef but null out the spilled location\n                    null = LoadErrorValue(op.src.type)\n                    block.ops.extend([null, SetAttr(env_reg, spill_locs[op.src], null, op.line)])\n                continue\n\n            if (\n                any(src in spill_locs for src in op.sources())\n                # N.B: IS_ERROR should be before a spill happens\n                # XXX: but could we have a regular branch?\n                and not (isinstance(op, Branch) and op.op == Branch.IS_ERROR)\n            ):\n                new_sources: list[Value] = []\n                stolen = op.stolen()\n                for src in op.sources():\n                    if src in spill_locs:\n                        read = GetAttr(env_reg, spill_locs[src], op.line)\n                        block.ops.append(read)\n                        new_sources.append(read)\n                        if src.type.is_refcounted and src not in stolen:\n                            to_decref.append(read)\n                    else:\n                        new_sources.append(src)\n\n                op.set_sources(new_sources)\n\n            block.ops.append(op)\n\n            for dec in to_decref:\n                block.ops.append(DecRef(dec))\n\n            if op in spill_locs:\n                # XXX: could we set uninit?\n                block.ops.append(SetAttr(env_reg, spill_locs[op], op, op.line))\n\n    return blocks\n"
  },
  {
    "path": "mypyc/transform/uninit.py",
    "content": "\"\"\"Insert checks for uninitialized values.\"\"\"\n\nfrom __future__ import annotations\n\nfrom mypyc.analysis.dataflow import AnalysisDict, analyze_must_defined_regs, cleanup_cfg, get_cfg\nfrom mypyc.common import BITMAP_BITS\nfrom mypyc.ir.func_ir import FuncIR, all_values\nfrom mypyc.ir.ops import (\n    Assign,\n    BasicBlock,\n    Branch,\n    ComparisonOp,\n    Integer,\n    IntOp,\n    LoadAddress,\n    LoadErrorValue,\n    Op,\n    RaiseStandardError,\n    Register,\n    Unreachable,\n    Value,\n)\nfrom mypyc.ir.rtypes import bitmap_rprimitive\n\n\ndef insert_uninit_checks(ir: FuncIR, strict_traceback_checks: bool) -> None:\n    # Remove dead blocks from the CFG, which helps avoid spurious\n    # checks due to unused error handling blocks.\n    cleanup_cfg(ir.blocks)\n\n    cfg = get_cfg(ir.blocks)\n    must_defined = analyze_must_defined_regs(\n        ir.blocks, cfg, set(ir.arg_regs), all_values(ir.arg_regs, ir.blocks)\n    )\n\n    ir.blocks = split_blocks_at_uninits(ir.blocks, must_defined.before, strict_traceback_checks)\n\n\ndef split_blocks_at_uninits(\n    blocks: list[BasicBlock], pre_must_defined: AnalysisDict[Value], strict_traceback_checks: bool\n) -> list[BasicBlock]:\n    new_blocks: list[BasicBlock] = []\n\n    init_registers = []\n    init_registers_set = set()\n    bitmap_registers: list[Register] = []  # Init status bitmaps\n    bitmap_backed: list[Register] = []  # These use bitmaps to track init status\n\n    # First split blocks on ops that may raise.\n    for block in blocks:\n        ops = block.ops\n        block.ops = []\n        cur_block = block\n        new_blocks.append(cur_block)\n\n        for i, op in enumerate(ops):\n            defined = pre_must_defined[block, i]\n            for src in op.unique_sources():\n                # If a register operand is not guaranteed to be\n                # initialized is an operand to something other than a\n                # check that it is defined, insert a check.\n\n                # Note that for register operand in a LoadAddress op,\n                # we should be able to use it without initialization\n                # as we may need to use its address to update itself\n                if (\n                    isinstance(src, Register)\n                    and src not in defined\n                    and not (isinstance(op, Branch) and op.op == Branch.IS_ERROR)\n                    and not isinstance(op, LoadAddress)\n                ):\n                    if src not in init_registers_set:\n                        init_registers.append(src)\n                        init_registers_set.add(src)\n\n                    # XXX: if src.name is empty, it should be a\n                    # temp... and it should be OK??\n                    if not src.name:\n                        continue\n\n                    new_block, error_block = BasicBlock(), BasicBlock()\n                    new_block.error_handler = error_block.error_handler = cur_block.error_handler\n                    new_blocks += [error_block, new_block]\n\n                    if not src.type.error_overlap:\n                        cur_block.ops.append(\n                            Branch(\n                                src,\n                                true_label=error_block,\n                                false_label=new_block,\n                                op=Branch.IS_ERROR,\n                                line=op.line,\n                            )\n                        )\n                    else:\n                        # We need to use bitmap for this one.\n                        check_for_uninit_using_bitmap(\n                            cur_block.ops,\n                            src,\n                            bitmap_registers,\n                            bitmap_backed,\n                            error_block,\n                            new_block,\n                            op.line,\n                        )\n\n                    if strict_traceback_checks:\n                        assert (\n                            op.line >= 0\n                        ), f\"Cannot raise an error with a negative line number for op {op}\"\n                    raise_std = RaiseStandardError(\n                        RaiseStandardError.UNBOUND_LOCAL_ERROR,\n                        f'local variable \"{src.name}\" referenced before assignment',\n                        op.line,\n                    )\n                    error_block.ops.append(raise_std)\n                    error_block.ops.append(Unreachable())\n                    cur_block = new_block\n            cur_block.ops.append(op)\n\n    if bitmap_backed:\n        update_register_assignments_to_set_bitmap(new_blocks, bitmap_registers, bitmap_backed)\n\n    if init_registers:\n        new_ops: list[Op] = []\n        for reg in init_registers:\n            err = LoadErrorValue(reg.type, undefines=True)\n            new_ops.append(err)\n            new_ops.append(Assign(reg, err))\n        for reg in bitmap_registers:\n            new_ops.append(Assign(reg, Integer(0, bitmap_rprimitive)))\n        new_blocks[0].ops[0:0] = new_ops\n\n    return new_blocks\n\n\ndef check_for_uninit_using_bitmap(\n    ops: list[Op],\n    src: Register,\n    bitmap_registers: list[Register],\n    bitmap_backed: list[Register],\n    error_block: BasicBlock,\n    ok_block: BasicBlock,\n    line: int,\n) -> None:\n    \"\"\"Check if src is defined using a bitmap.\n\n    Modifies ops, bitmap_registers and bitmap_backed.\n    \"\"\"\n    if src not in bitmap_backed:\n        # Set up a new bitmap backed register.\n        bitmap_backed.append(src)\n        n = (len(bitmap_backed) - 1) // BITMAP_BITS\n        if len(bitmap_registers) <= n:\n            bitmap_registers.append(Register(bitmap_rprimitive, f\"__locals_bitmap{n}\"))\n\n    index = bitmap_backed.index(src)\n    masked = IntOp(\n        bitmap_rprimitive,\n        bitmap_registers[index // BITMAP_BITS],\n        Integer(1 << (index & (BITMAP_BITS - 1)), bitmap_rprimitive),\n        IntOp.AND,\n        line,\n    )\n    ops.append(masked)\n    chk = ComparisonOp(masked, Integer(0, bitmap_rprimitive), ComparisonOp.EQ)\n    ops.append(chk)\n    ops.append(Branch(chk, error_block, ok_block, Branch.BOOL))\n\n\ndef update_register_assignments_to_set_bitmap(\n    blocks: list[BasicBlock], bitmap_registers: list[Register], bitmap_backed: list[Register]\n) -> None:\n    \"\"\"Update some assignments to registers to also set a bit in a bitmap.\n\n    The bitmaps are used to track if a local variable has been assigned to.\n\n    Modifies blocks.\n    \"\"\"\n    for block in blocks:\n        if any(isinstance(op, Assign) and op.dest in bitmap_backed for op in block.ops):\n            new_ops: list[Op] = []\n            for op in block.ops:\n                if isinstance(op, Assign) and op.dest in bitmap_backed:\n                    index = bitmap_backed.index(op.dest)\n                    new_ops.append(op)\n                    reg = bitmap_registers[index // BITMAP_BITS]\n                    new = IntOp(\n                        bitmap_rprimitive,\n                        reg,\n                        Integer(1 << (index & (BITMAP_BITS - 1)), bitmap_rprimitive),\n                        IntOp.OR,\n                        op.line,\n                    )\n                    new_ops.append(new)\n                    new_ops.append(Assign(reg, new))\n                else:\n                    new_ops.append(op)\n            block.ops = new_ops\n"
  },
  {
    "path": "pyproject.toml",
    "content": "[build-system]\nrequires = [\n    # NOTE: this needs to be kept in sync with mypy-requirements.txt\n    # and build-requirements.txt, because those are both needed for\n    # self-typechecking :/\n    \"setuptools >= 77.0.3\",\n    # the following is from mypy-requirements.txt/setup.py\n    \"typing_extensions>=4.6.0\",\n    \"mypy_extensions>=1.0.0\",\n    \"pathspec>=1.0.0\",\n    \"tomli>=1.1.0; python_version<'3.11'\",\n    \"librt>=0.8.0; platform_python_implementation != 'PyPy'\",\n    # the following is from build-requirements.txt\n    \"types-psutil\",\n    \"types-setuptools\",\n]\nbuild-backend = \"setuptools.build_meta\"\n\n[project]\nname = \"mypy\"\ndescription = \"Optional static typing for Python\"\nreadme = {text = \"\"\"\nMypy -- Optional Static Typing for Python\n=========================================\n\nAdd type annotations to your Python programs, and use mypy to type\ncheck them.  Mypy is essentially a Python linter on steroids, and it\ncan catch many programming errors by analyzing your program, without\nactually having to run it.  Mypy has a powerful type system with\nfeatures such as type inference, gradual typing, generics and union\ntypes.\n\"\"\", content-type = \"text/x-rst\"}\nauthors = [{name = \"Jukka Lehtosalo\", email = \"jukka.lehtosalo@iki.fi\"}]\nlicense = \"MIT\"\nlicense-files = [\"LICENSE\", \"mypy/typeshed/LICENSE\"]\nclassifiers = [\n  \"Development Status :: 5 - Production/Stable\",\n  \"Environment :: Console\",\n  \"Intended Audience :: Developers\",\n  \"Programming Language :: Python :: 3\",\n  \"Programming Language :: Python :: 3.10\",\n  \"Programming Language :: Python :: 3.11\",\n  \"Programming Language :: Python :: 3.12\",\n  \"Programming Language :: Python :: 3.13\",\n  \"Programming Language :: Python :: 3.14\",\n  \"Topic :: Software Development\",\n  \"Typing :: Typed\",\n]\nrequires-python = \">=3.10\"\ndependencies = [\n  # When changing this, also update build-system.requires and mypy-requirements.txt\n  \"typing_extensions>=4.6.0\",\n  \"mypy_extensions>=1.0.0\",\n  \"pathspec>=1.0.0\",\n  \"tomli>=1.1.0; python_version<'3.11'\",\n  \"librt>=0.8.0; platform_python_implementation != 'PyPy'\",\n]\ndynamic = [\"version\"]\n\n[project.optional-dependencies]\ndmypy = [\"psutil>=4.0\"]\nmypyc = [\"setuptools>=50\"]\npython2 = []\nreports = [\"lxml\"]\ninstall-types = [\"pip\"]\nfaster-cache = [\"orjson\"]\nnative-parse = [\"ast-serialize>=0.1.1,<1.0.0\"]\n\n[project.urls]\nHomepage = \"https://www.mypy-lang.org/\"\nDocumentation = \"https://mypy.readthedocs.io/en/stable/index.html\"\nRepository = \"https://github.com/python/mypy\"\nChangelog = \"https://github.com/python/mypy/blob/master/CHANGELOG.md\"\nIssues = \"https://github.com/python/mypy/issues\"\n\n[project.scripts]\nmypy = \"mypy.__main__:console_entry\"\nstubgen = \"mypy.stubgen:main\"\nstubtest = \"mypy.stubtest:main\"\ndmypy = \"mypy.dmypy.client:console_entry\"\nmypyc = \"mypyc.__main__:main\"\n\n[tool.setuptools.packages.find]\ninclude = [\"mypy*\", \"mypyc*\", \"*__mypyc*\"]\nexclude = [\"mypyc.test-data*\"]\nnamespaces = false\n\n[tool.setuptools.package-data]\nmypy = [\n  \"py.typed\",\n  \"typeshed/**/*.py\",\n  \"typeshed/**/*.pyi\",\n  \"typeshed/stdlib/VERSIONS\",\n  \"xml/*.xsd\",\n  \"xml/*.xslt\",\n  \"xml/*.css\",\n]\n[tool.setuptools.exclude-package-data]\nmypyc = [\n  \"README.md\",\n  \"doc/**\",\n  \"external/**\",\n  \"lib-rt/test_capi.cc\",\n  \"lib-rt/setup.py\",\n  \"test-data/**\",\n]\n\n[tool.black]\nline-length = 99\ntarget-version = [\"py310\", \"py311\", \"py312\", \"py313\", \"py314\"]\nskip-magic-trailing-comma = true\nforce-exclude = '''\n^/mypy/typeshed|\n^/mypyc/test-data|\n^/test-data\n'''\n\n[tool.ruff]\nline-length = 99\ntarget-version = \"py310\"\nfix = true\n\nextend-exclude = [\n  \"@*\",\n  # Sphinx configuration is irrelevant\n  \"docs/source/conf.py\",\n  \"mypyc/doc/conf.py\",\n  # tests have more relaxed styling requirements\n  # fixtures have their own .pyi-specific configuration\n  \"test-data/*\",\n  \"mypyc/test-data/*\",\n  # typeshed has its own .pyi-specific configuration\n  \"mypy/typeshed/*\",\n]\n\n[tool.ruff.lint]\nselect = [\n  \"E\",       # pycodestyle (error)\n  \"F\",       # pyflakes\n  \"W\",       # pycodestyle (warning)\n  \"B\",       # flake8-bugbear\n  \"I\",       # isort\n  \"N\",       # pep8-naming\n  \"PIE\",     # flake8-pie\n  \"PLE\",     # pylint error\n  \"RUF100\",  # Unused noqa comments\n  \"PGH004\",  # blanket noqa comments\n  \"UP\",      # pyupgrade\n  \"C4\",      # flake8-comprehensions\n  \"SIM101\",  # merge duplicate isinstance calls\n  \"SIM201\", \"SIM202\", \"SIM222\", \"SIM223\",  # flake8-simplify\n  \"FURB168\", # Prefer is operator over isinstance for None checks\n  \"FURB169\", # Do not use is comparison with type(None). Use None\n  \"FURB187\", # avoid list reverse copy\n  \"FURB188\", # use str.remove(pre|suf)fix\n  \"ISC001\",  # implicitly concatenated string\n  \"RET501\", \"RET502\",  # better return None handling\n]\n\nignore = [\n  \"B007\",  # Loop control variable not used within the loop body.\n  \"B011\",  # Don't use assert False\n  \"B023\",  # Function definition does not bind loop variable\n  \"B905\",  # zip-without-explicit-strict\n  \"E2\",    # conflicts with black\n  \"E402\",  # module level import not at top of file\n  \"E501\",  # conflicts with black\n  \"E721\",  # Use `is` and `is not` for type comparisons, or `isinstance()` for isinstance checks\n  \"E731\",  # Do not assign a `lambda` expression, use a `def`\n  \"E741\",  # Ambiguous variable name\n  \"N818\",  # Exception should be named with an Error suffix\n  \"N806\",  # UPPER_CASE used for constant local variables\n  \"UP031\", # Use format specifiers instead of percent format\n  \"UP032\", # 'f-string always preferable to format' is controversial\n  \"C409\",  # https://github.com/astral-sh/ruff/issues/12912\n  \"C420\",  # reads a little worse. fromkeys predates dict comprehensions\n  \"C416\",  # There are a few cases where it's nice to have names for the dict items\n  \"PIE790\", # there's nothing wrong with pass\n]\n\nunfixable = [\n    \"F841\",  # unused variable. ruff keeps the call, but mostly we want to get rid of it all\n    \"F601\",  # automatic fix might obscure issue\n    \"F602\",  # automatic fix might obscure issue\n    \"B018\",  # automatic fix might obscure issue\n    \"UP036\", # sometimes it's better to just noqa this\n    \"SIM222\", # automatic fix might obscure issue\n    \"SIM223\", # automatic fix might obscure issue\n]\n\n[tool.ruff.lint.per-file-ignores]\n# Mixed case variable and function names.\n\"mypy/fastparse.py\" = [\"N802\", \"N816\"]\n\n[tool.ruff.lint.isort]\ncombine-as-imports = true\nextra-standard-library = [\"typing_extensions\"]\n\n[tool.check-manifest]\nignore = [\"**/.readthedocs.yaml\"]\n\n[tool.pytest.ini_options]\nminversion = \"7.0.0\"\ntestpaths = [\"mypy/test\", \"mypyc/test\"]\npython_files = 'test*.py'\n\n# Where do the test cases come from?  We provide our own collection\n# logic by implementing `pytest_pycollect_makeitem` in mypy.test.data;\n# the test files import that module, and pytest sees the magic name\n# and invokes it at the relevant moment.  See\n# https://doc.pytest.org/en/latest/how-to/writing_plugins.html#collection-hooks\n\n# Both our plugin and unittest provide their own collection logic,\n# So we can disable the default python collector by giving it empty\n# patterns to search for.\n# Note that unittest requires that no \"Test*\" classes exist.\npython_classes = []\npython_functions = []\n\n# always run in parallel (requires pytest-xdist, see test-requirements.txt)\n# and enable strict mode: require all markers\n# to be defined and raise on invalid config values\naddopts = \"-nauto --strict-markers --strict-config\"\n\n# treat xpasses as test failures so they get converted to regular tests as soon as possible\nxfail_strict = true\n\n# Force warnings as errors\nfilterwarnings = [\n  \"error\",\n]\n\n[tool.coverage.run]\nbranch = true\nsource = [\"mypy\"]\nparallel = true\n\n[tool.coverage.report]\nshow_missing = true\nskip_covered = true\nomit = ['mypy/test/*']\nexclude_lines = [\n  '\\#\\s*pragma: no cover',\n  '^\\s*raise AssertionError\\b',\n  '^\\s*raise NotImplementedError\\b',\n  '^\\s*return NotImplemented\\b',\n  '^\\s*raise$',\n  '^assert False\\b',\n  '''^if __name__ == ['\"]__main__['\"]:$''',\n]\n"
  },
  {
    "path": "runtests.py",
    "content": "#!/usr/bin/env python3\n\nfrom __future__ import annotations\n\nimport subprocess\nfrom subprocess import Popen\nfrom sys import argv, executable, exit\n\n# Slow test suites\nCMDLINE = \"PythonCmdline\"\nPEP561 = \"PEP561Suite\"\nEVALUATION = \"PythonEvaluation\"\nDAEMON = \"testdaemon\"\nSTUBGEN_CMD = \"StubgenCmdLine\"\nSTUBGEN_PY = \"StubgenPythonSuite\"\nMYPYC_RUN = \"TestRun\"\nMYPYC_RUN_MULTI = \"TestRunMultiFile\"\nMYPYC_EXTERNAL = \"TestExternal\"\nMYPYC_COMMAND_LINE = \"TestCommandLine\"\nMYPYC_SEPARATE = \"TestRunSeparate\"\nMYPYC_MULTIMODULE = \"multimodule\"  # Subset of mypyc run tests that are slow\nERROR_STREAM = \"ErrorStreamSuite\"\nDIFF_CACHE = \"DiffCacheIntegrationTests\"\n\n\nALL_NON_FAST = [\n    CMDLINE,\n    PEP561,\n    EVALUATION,\n    DAEMON,\n    STUBGEN_CMD,\n    STUBGEN_PY,\n    MYPYC_RUN,\n    MYPYC_RUN_MULTI,\n    MYPYC_EXTERNAL,\n    MYPYC_COMMAND_LINE,\n    MYPYC_SEPARATE,\n    ERROR_STREAM,\n    DIFF_CACHE,\n]\n\n\n# This must be enabled by explicitly including 'pytest-extra' on the command line\nPYTEST_OPT_IN = [PEP561]\n\n\n# These must be enabled by explicitly including 'mypyc-extra' on the command line.\nMYPYC_OPT_IN = [MYPYC_RUN, MYPYC_RUN_MULTI, MYPYC_SEPARATE]\n\n# These mypyc test filters cover most slow test cases\nMYPYC_SLOW = [MYPYC_RUN_MULTI, MYPYC_COMMAND_LINE, MYPYC_SEPARATE, MYPYC_MULTIMODULE]\n\n\n# We split the pytest run into three parts to improve test\n# parallelization. Each run should have tests that each take a roughly similar\n# time to run.\ncmds = {\n    # Self type check\n    \"self\": [\n        executable,\n        \"-m\",\n        \"mypy\",\n        \"--config-file\",\n        \"mypy_self_check.ini\",\n        \"-p\",\n        \"mypy\",\n        \"-p\",\n        \"mypyc\",\n    ],\n    # Type check setup.py as well\n    \"self-packaging\": [\n        executable,\n        \"-m\",\n        \"mypy\",\n        \"--config-file\",\n        \"mypy_self_check.ini\",\n        \"setup.py\",\n    ],\n    # Lint\n    \"lint\": [\"pre-commit\", \"run\", \"--all-files\"],\n    # Fast test cases only (this is the bulk of the test suite)\n    \"pytest-fast\": [\"pytest\", \"-q\", \"-k\", f\"not ({' or '.join(ALL_NON_FAST)})\"],\n    # Test cases that invoke mypy (with small inputs)\n    \"pytest-cmdline\": [\n        \"pytest\",\n        \"-q\",\n        \"-k\",\n        \" or \".join([CMDLINE, EVALUATION, STUBGEN_CMD, STUBGEN_PY]),\n    ],\n    # Test cases that may take seconds to run each\n    \"pytest-slow\": [\n        \"pytest\",\n        \"-q\",\n        \"-k\",\n        \" or \".join([DAEMON, MYPYC_EXTERNAL, MYPYC_COMMAND_LINE, ERROR_STREAM, DIFF_CACHE]),\n    ],\n    \"mypyc-fast\": [\"pytest\", \"-q\", \"mypyc\", \"-k\", f\"not ({' or '.join(MYPYC_SLOW)})\"],\n    # Test cases that might take minutes to run\n    \"pytest-extra\": [\"pytest\", \"-q\", \"-k\", \" or \".join(PYTEST_OPT_IN)],\n    # Mypyc tests that aren't run by default, since they are slow and rarely\n    # fail for commits that don't touch mypyc\n    \"mypyc-extra\": [\"pytest\", \"-q\", \"-k\", \" or \".join(MYPYC_OPT_IN)],\n}\n\n# Stop run immediately if these commands fail\nFAST_FAIL = [\"self\", \"lint\"]\n\nEXTRA_COMMANDS = (\"pytest-extra\", \"mypyc-fast\", \"mypyc-extra\")\nDEFAULT_COMMANDS = [cmd for cmd in cmds if cmd not in EXTRA_COMMANDS]\n\nassert all(cmd in cmds for cmd in FAST_FAIL)\n\n\ndef run_cmd(name: str) -> int:\n    status = 0\n    if name in cmds:\n        cmd = cmds[name]\n    else:\n        if name.endswith(\".test\"):\n            cmd = [\"pytest\", f\"mypy/test/testcheck.py::TypeCheckSuite::{name}\"]\n        else:\n            cmd = [\"pytest\", \"-n0\", \"-k\", name]\n    print(f\"run {name}: {cmd}\")\n    proc = subprocess.run(cmd, stderr=subprocess.STDOUT)\n    if proc.returncode:\n        print(\"\\nFAILED: %s\" % name)\n        status = proc.returncode\n        if name in FAST_FAIL:\n            exit(status)\n    return status\n\n\ndef start_background_cmd(name: str) -> Popen:\n    cmd = cmds[name]\n    proc = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE)\n    return proc\n\n\ndef wait_background_cmd(name: str, proc: Popen) -> int:\n    output = proc.communicate()[0]\n    status = proc.returncode\n    print(f\"run {name}: {cmds[name]}\")\n    if status:\n        print(output.decode().rstrip())\n        print(\"\\nFAILED:\", name)\n        if name in FAST_FAIL:\n            exit(status)\n    return status\n\n\ndef main() -> None:\n    prog, *args = argv\n\n    if not set(args).issubset(cmds):\n        print(\n            \"usage:\",\n            prog,\n            \" \".join(f\"[{k}]\" for k in cmds),\n            \"[names of individual tests and files...]\",\n        )\n        print()\n        print(\n            \"Run the given tests. If given no arguments, run everything except\"\n            + \" pytest-extra and mypyc-extra. Unrecognized arguments will be\"\n            + \" interpreted as individual test names / substring expressions\"\n            + \" (or, if they end in .test, individual test files)\"\n            + \" and this script will try to run them.\"\n        )\n        if \"-h\" in args or \"--help\" in args:\n            exit(1)\n\n    if not args:\n        args = DEFAULT_COMMANDS.copy()\n\n    status = 0\n\n    if \"self\" in args and \"lint\" in args:\n        # Perform lint and self check in parallel as it's faster.\n        proc = start_background_cmd(\"lint\")\n        cmd_status = run_cmd(\"self\")\n        if cmd_status:\n            status = cmd_status\n        cmd_status = wait_background_cmd(\"lint\", proc)\n        if cmd_status:\n            status = cmd_status\n        args = [arg for arg in args if arg not in (\"self\", \"lint\")]\n\n    for arg in args:\n        cmd_status = run_cmd(arg)\n        if cmd_status:\n            status = cmd_status\n\n    exit(status)\n\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "setup.py",
    "content": "#!/usr/bin/env python\n\nfrom __future__ import annotations\n\nimport glob\nimport os\nimport os.path\nimport sys\nfrom typing import TYPE_CHECKING, Any\n\nif sys.version_info < (3, 10, 0):  # noqa: UP036, RUF100\n    sys.stderr.write(\"ERROR: You need Python 3.10 or later to use mypy.\\n\")\n    exit(1)\n\n# we'll import stuff from the source tree, let's ensure is on the sys path\nsys.path.insert(0, os.path.dirname(os.path.realpath(__file__)))\n\n# This requires setuptools when building; setuptools is not needed\n# when installing from a wheel file (though it is still needed for\n# alternative forms of installing, as suggested by README.md).\nfrom setuptools import Extension, setup\nfrom setuptools.command.build_py import build_py\n\nfrom mypy.version import __version__ as version\n\nif TYPE_CHECKING:\n    from typing import TypeGuard\n\n\ndef is_list_of_setuptools_extension(items: list[Any]) -> TypeGuard[list[Extension]]:\n    return all(isinstance(item, Extension) for item in items)\n\n\ndef find_package_data(base: str, globs: list[str], root: str = \"mypy\") -> list[str]:\n    \"\"\"Find all interesting data files, for setup(package_data=)\n\n    Arguments:\n      root:  The directory to search in.\n      globs: A list of glob patterns to accept files.\n    \"\"\"\n\n    rv_dirs = [root for root, dirs, files in os.walk(base)]\n    rv = []\n    for rv_dir in rv_dirs:\n        files = []\n        for pat in globs:\n            files += glob.glob(os.path.join(rv_dir, pat))\n        if not files:\n            continue\n        rv.extend([os.path.relpath(f, root) for f in files])\n    return rv\n\n\nclass CustomPythonBuild(build_py):\n    def pin_version(self) -> None:\n        path = os.path.join(self.build_lib, \"mypy\")\n        self.mkpath(path)\n        with open(os.path.join(path, \"version.py\"), \"w\") as stream:\n            stream.write(f'__version__ = \"{version}\"\\n')\n\n    def run(self) -> None:\n        self.execute(self.pin_version, ())\n        build_py.run(self)\n\n\ncmdclass = {\"build_py\": CustomPythonBuild}\n\nUSE_MYPYC = False\n# To compile with mypyc, a mypyc checkout must be present on the PYTHONPATH\nif len(sys.argv) > 1 and \"--use-mypyc\" in sys.argv:\n    sys.argv.remove(\"--use-mypyc\")\n    USE_MYPYC = True\nif os.getenv(\"MYPY_USE_MYPYC\", None) == \"1\":\n    USE_MYPYC = True\n\nif USE_MYPYC:\n    MYPYC_BLACKLIST = tuple(\n        os.path.join(\"mypy\", x)\n        for x in (\n            # Need to be runnable as scripts\n            \"__main__.py\",\n            \"pyinfo.py\",\n            os.path.join(\"dmypy\", \"__main__.py\"),\n            os.path.join(\"build_worker\", \"__main__.py\"),\n            \"exportjson.py\",\n            # Uses __getattr__/__setattr__\n            \"split_namespace.py\",\n            # Lies to mypy about code reachability\n            \"bogus_type.py\",\n            # We don't populate __file__ properly at the top level or something?\n            # Also I think there would be problems with how we generate version.py.\n            \"version.py\",\n            # Skip these to reduce the size of the build\n            \"stubtest.py\",\n            \"stubgenc.py\",\n            \"stubdoc.py\",\n        )\n    ) + (\n        # Don't want to grab this accidentally\n        os.path.join(\"mypyc\", \"lib-rt\", \"setup.py\"),\n        os.path.join(\"mypyc\", \"lib-rt\", \"build_setup.py\"),\n        # Uses __file__ at top level https://github.com/mypyc/mypyc/issues/700\n        os.path.join(\"mypyc\", \"__main__.py\"),\n        os.path.join(\"mypyc\", \"build_setup.py\"),  # for monkeypatching\n    )\n\n    everything = [os.path.join(\"mypy\", x) for x in find_package_data(\"mypy\", [\"*.py\"])] + [\n        os.path.join(\"mypyc\", x) for x in find_package_data(\"mypyc\", [\"*.py\"], root=\"mypyc\")\n    ]\n    # Start with all the .py files\n    all_real_pys = [\n        x for x in everything if not x.startswith(os.path.join(\"mypy\", \"typeshed\") + os.sep)\n    ]\n    # Strip out anything in our blacklist\n    mypyc_targets = [x for x in all_real_pys if x not in MYPYC_BLACKLIST]\n    # Strip out any test code\n    mypyc_targets = [\n        x\n        for x in mypyc_targets\n        if not x.startswith(\n            (\n                os.path.join(\"mypy\", \"test\") + os.sep,\n                os.path.join(\"mypyc\", \"test\") + os.sep,\n                os.path.join(\"mypyc\", \"doc\") + os.sep,\n                os.path.join(\"mypyc\", \"test-data\") + os.sep,\n            )\n        )\n    ]\n    # ... and add back in the one test module we need\n    mypyc_targets.append(os.path.join(\"mypy\", \"test\", \"visitors.py\"))\n\n    # The targets come out of file system apis in an unspecified\n    # order. Sort them so that the mypyc output is deterministic.\n    mypyc_targets.sort()\n\n    use_other_mypyc = os.getenv(\"ALTERNATE_MYPYC_PATH\", None)\n    if use_other_mypyc:\n        # This bit is super unfortunate: we want to use a different\n        # mypy/mypyc version, but we've already imported parts, so we\n        # remove the modules that we've imported already, which will\n        # let the right versions be imported by mypyc.\n        del sys.modules[\"mypy\"]\n        del sys.modules[\"mypy.version\"]\n        del sys.modules[\"mypy.git\"]\n        sys.path.insert(0, use_other_mypyc)\n\n    from mypyc.build import mypycify\n\n    opt_level = os.getenv(\"MYPYC_OPT_LEVEL\", \"3\")\n    debug_level = os.getenv(\"MYPYC_DEBUG_LEVEL\", \"1\")\n    force_multifile = os.getenv(\"MYPYC_MULTI_FILE\", \"\") == \"1\"\n    log_trace = bool(int(os.getenv(\"MYPYC_LOG_TRACE\", \"0\")))\n    ext_modules = mypycify(\n        mypyc_targets + [\"--config-file=mypy_bootstrap.ini\"],\n        opt_level=opt_level,\n        debug_level=debug_level,\n        # Use multi-file compilation mode on windows because without it\n        # our Appveyor builds run out of memory sometimes.\n        multi_file=sys.platform == \"win32\" or force_multifile,\n        log_trace=log_trace,\n        # Mypy itself is allowed to use native_internal extension.\n        depends_on_librt_internal=True,\n    )\n\nelse:\n    ext_modules = []\n\nassert is_list_of_setuptools_extension(ext_modules), \"Expected mypycify to use setuptools\"\n\nsetup(version=version, ext_modules=ext_modules, cmdclass=cmdclass)\n"
  },
  {
    "path": "test-data/packages/modulefinder/nsx-pkg1/nsx/a/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/nsx-pkg2/nsx/b/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/nsx-pkg3/nsx/c/c",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/nsx-pkg3/nsx/c/c.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/nsy-pkg1/nsy/a/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/nsy-pkg1/nsy/a/__init__.pyi",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/nsy-pkg2/nsy/b/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/nsy-pkg2/nsy/b.pyi",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/nsy-pkg2/nsy/c.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/nsy-pkg2/nsy/c.pyi",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/pkg1/a",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/pkg1/a.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/pkg2/b/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder/readme.txt",
    "content": "Samples for testing modulefinder.FindModuleCache.\n\nContains three packages for the `nsx` namespace, and two packages\nproviding `a` and `b`.\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/baz/baz_pkg/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/baz/baz_pkg/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/baz/ns_baz_pkg/a.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/baz/ns_baz_pkg/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/foo/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/foo/bar.py",
    "content": "bar_var = \"bar\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/foo-stubs/__init__.pyi",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/foo-stubs/bar.pyi",
    "content": "bar_var: str\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/foo-stubs/qux.pyi",
    "content": "qux_var: int\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/ns_pkg_typed/a.py",
    "content": "a_var = \"a\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/ns_pkg_typed/b/c.py",
    "content": "c_var = \"c\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/ns_pkg_typed/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/ns_pkg_untyped/a.py",
    "content": "a_var = \"a\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/ns_pkg_untyped/b/c.py",
    "content": "c_var = \"c\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/ns_pkg_w_stubs/typed/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/ns_pkg_w_stubs/typed_inline/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/ns_pkg_w_stubs/typed_inline/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/ns_pkg_w_stubs/untyped/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/ns_pkg_w_stubs-stubs/typed/__init__.pyi",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed/__init__.py",
    "content": "pkg_typed_var = \"pkg_typed\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed/a.py",
    "content": "a_var = \"a\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed/b/__init__.py",
    "content": "b_var = \"b\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed/b/c.py",
    "content": "c_var = \"c\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed_w_stubs/__init__.py",
    "content": "pkg_typed_w_stubs_var = \"pkg_typed_w_stubs\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed_w_stubs/__init__.pyi",
    "content": "pkg_typed_w_stubs_var: object\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed_w_stubs/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed_w_stubs/spam.py",
    "content": "spam_var = \"spam\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed_w_stubs/spam.pyi",
    "content": "spam_var: object\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed_w_stubs-stubs/__init__.pyi",
    "content": "pkg_typed_w_stubs_var: str = ...\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_typed_w_stubs-stubs/spam.pyi",
    "content": "spam_var: str\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_untyped/__init__.py",
    "content": "pkg_untyped_var = \"pkg_untyped\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_untyped/a.py",
    "content": "a_var = \"a\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_untyped/b/__init__.py",
    "content": "b_var = \"b\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/pkg_untyped/b/c.py",
    "content": "c_var = \"c\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-site-packages/standalone.py",
    "content": "standalone_var = \"standalone\"\n"
  },
  {
    "path": "test-data/packages/modulefinder-src/neighbor_pkg/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-src/neighbor_pkg/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-src/ns_neighbor_pkg/a.py",
    "content": ""
  },
  {
    "path": "test-data/packages/modulefinder-src/ns_neighbor_pkg/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg/pyproject.toml",
    "content": "[project]\nname = 'typedpkg'\nversion = '0.1'\ndescription = 'test'\n\n[build-system]\nrequires = [\"hatchling==1.18\"]\nbuild-backend = \"hatchling.build\"\n"
  },
  {
    "path": "test-data/packages/typedpkg/typedpkg/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg/typedpkg/dne.py",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg/typedpkg/pkg/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg/typedpkg/pkg/aaa.py",
    "content": "def af(a: str) -> str:\n    return a + \" nested\"\n"
  },
  {
    "path": "test-data/packages/typedpkg/typedpkg/pkg/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg/typedpkg/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg/typedpkg/sample.py",
    "content": "from typing import Iterable, Tuple\n\n\ndef ex(a):\n    # type: (Iterable[str]) -> Tuple[str, ...]\n    \"\"\"Example typed package.\"\"\"\n    return list(a)\n"
  },
  {
    "path": "test-data/packages/typedpkg-stubs/pyproject.toml",
    "content": "[project]\nname = 'typedpkg-stubs'\nversion = '0.1'\ndescription = 'test'\n\n[tool.hatch.build]\ninclude = [\"**/*.pyi\"]\n\n[build-system]\nrequires = [\"hatchling==1.18\"]\nbuild-backend = \"hatchling.build\"\n"
  },
  {
    "path": "test-data/packages/typedpkg-stubs/typedpkg-stubs/__init__.pyi",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg-stubs/typedpkg-stubs/py.typed",
    "content": "partial\n"
  },
  {
    "path": "test-data/packages/typedpkg-stubs/typedpkg-stubs/sample.pyi",
    "content": "from typing import Iterable, List\ndef ex(a: Iterable[str]) -> List[str]: ...\n"
  },
  {
    "path": "test-data/packages/typedpkg_ns_a/pyproject.toml",
    "content": "[project]\nname = 'typedpkg_namespace.alpha'\nversion = '0.1'\ndescription = 'test'\n\n[tool.hatch.build]\ninclude = [\"**/*.py\", \"**/*.pyi\", \"**/py.typed\"]\n\n[build-system]\nrequires = [\"hatchling==1.18\"]\nbuild-backend = \"hatchling.build\"\n"
  },
  {
    "path": "test-data/packages/typedpkg_ns_a/typedpkg_ns/__init__.py",
    "content": "# namespace pkg\n__import__(\"pkg_resources\").declare_namespace(__name__)\n"
  },
  {
    "path": "test-data/packages/typedpkg_ns_a/typedpkg_ns/a/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg_ns_a/typedpkg_ns/a/bbb.py",
    "content": "def bf(a: bool) -> bool:\n    return not a\n"
  },
  {
    "path": "test-data/packages/typedpkg_ns_a/typedpkg_ns/a/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg_ns_b/pyproject.toml",
    "content": "[project]\nname = 'typedpkg_namespace.beta'\nversion = '0.1'\ndescription = 'test'\n\n[build-system]\nrequires = [\"hatchling==1.18\"]\nbuild-backend = \"hatchling.build\"\n"
  },
  {
    "path": "test-data/packages/typedpkg_ns_b/typedpkg_ns/__init__.py",
    "content": "# namespace pkg\n__import__(\"pkg_resources\").declare_namespace(__name__)\n"
  },
  {
    "path": "test-data/packages/typedpkg_ns_b/typedpkg_ns/b/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg_ns_b/typedpkg_ns/b/bbb.py",
    "content": "def bf(a):\n    return not a\n"
  },
  {
    "path": "test-data/packages/typedpkg_ns_b-stubs/pyproject.toml",
    "content": "[project]\nname = 'typedpkg_ns-stubs'\nversion = '0.1'\ndescription = 'test'\n\n[tool.hatch.build]\ninclude = [\"**/*.pyi\"]\n\n[build-system]\nrequires = [\"hatchling==1.18\"]\nbuild-backend = \"hatchling.build\"\n"
  },
  {
    "path": "test-data/packages/typedpkg_ns_b-stubs/typedpkg_ns-stubs/b/__init__.pyi",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg_ns_b-stubs/typedpkg_ns-stubs/b/bbb.pyi",
    "content": "def bf(a: bool) -> bool: ...\n"
  },
  {
    "path": "test-data/packages/typedpkg_ns_nested/pyproject.toml",
    "content": "[project]\nname = 'typedpkg_namespace.nested'\nversion = '0.1'\ndescription = 'Two namespace packages, one of them typed'\n\n[tool.hatch.build]\ninclude = [\"**/*.py\", \"**/*.pyi\", \"**/py.typed\"]\n\n[build-system]\nrequires = [\"hatchling==1.18\"]\nbuild-backend = \"hatchling.build\"\n"
  },
  {
    "path": "test-data/packages/typedpkg_ns_nested/typedpkg_ns/a/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg_ns_nested/typedpkg_ns/a/py.typed",
    "content": ""
  },
  {
    "path": "test-data/packages/typedpkg_ns_nested/typedpkg_ns/b/__init__.py",
    "content": ""
  },
  {
    "path": "test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/__init__.pyi",
    "content": "import pathlib\nimport typing\nfrom . import demo as demo\nfrom typing import overload\n\nclass StaticMethods:\n    def __init__(self, *args, **kwargs) -> None: ...\n    @overload\n    @staticmethod\n    def overloaded_static_method(value: typing.SupportsInt) -> int: ...\n    @overload\n    @staticmethod\n    def overloaded_static_method(value: typing.SupportsFloat) -> float: ...\n    @staticmethod\n    def some_static_method(a: typing.SupportsInt, b: typing.SupportsInt) -> int: ...\n\nclass TestStruct:\n    field_readwrite: int\n    field_readwrite_docstring: int\n    def __init__(self, *args, **kwargs) -> None: ...\n    @property\n    def field_readonly(self) -> int: ...\n\ndef func_incomplete_signature(*args, **kwargs): ...\ndef func_returning_optional() -> int | None: ...\ndef func_returning_pair() -> tuple[int, float]: ...\ndef func_returning_path() -> pathlib.Path: ...\ndef func_returning_vector() -> list[float]: ...\n"
  },
  {
    "path": "test-data/pybind11_fixtures/expected_stubs_no_docs/pybind11_fixtures/demo.pyi",
    "content": "import typing\nfrom typing import ClassVar, overload\n\nPI: float\n__version__: str\n\nclass Point:\n    class AngleUnit:\n        __members__: ClassVar[dict] = ...  # read-only\n        __entries: ClassVar[dict] = ...\n        degree: ClassVar[Point.AngleUnit] = ...\n        radian: ClassVar[Point.AngleUnit] = ...\n        def __init__(self, value: typing.SupportsInt) -> None: ...\n        def __eq__(self, other: object) -> bool: ...\n        def __hash__(self) -> int: ...\n        def __index__(self) -> int: ...\n        def __int__(self) -> int: ...\n        def __ne__(self, other: object) -> bool: ...\n        @property\n        def name(self) -> str: ...\n        @property\n        def value(self) -> int: ...\n\n    class LengthUnit:\n        __members__: ClassVar[dict] = ...  # read-only\n        __entries: ClassVar[dict] = ...\n        inch: ClassVar[Point.LengthUnit] = ...\n        mm: ClassVar[Point.LengthUnit] = ...\n        pixel: ClassVar[Point.LengthUnit] = ...\n        def __init__(self, value: typing.SupportsInt) -> None: ...\n        def __eq__(self, other: object) -> bool: ...\n        def __hash__(self) -> int: ...\n        def __index__(self) -> int: ...\n        def __int__(self) -> int: ...\n        def __ne__(self, other: object) -> bool: ...\n        @property\n        def name(self) -> str: ...\n        @property\n        def value(self) -> int: ...\n    angle_unit: ClassVar[Point.AngleUnit] = ...\n    length_unit: ClassVar[Point.LengthUnit] = ...\n    x_axis: ClassVar[Point] = ...  # read-only\n    y_axis: ClassVar[Point] = ...  # read-only\n    origin: ClassVar[Point] = ...\n    x: float\n    y: float\n    @overload\n    def __init__(self) -> None: ...\n    @overload\n    def __init__(self, x: typing.SupportsFloat, y: typing.SupportsFloat) -> None: ...\n    def as_list(self) -> list[float]: ...\n    @overload\n    def distance_to(self, x: typing.SupportsFloat, y: typing.SupportsFloat) -> float: ...\n    @overload\n    def distance_to(self, other: Point) -> float: ...\n    @property\n    def length(self) -> float: ...\n\ndef answer() -> int: ...\ndef midpoint(left: typing.SupportsFloat, right: typing.SupportsFloat) -> float: ...\ndef sum(arg0: typing.SupportsInt, arg1: typing.SupportsInt) -> int: ...\ndef weighted_midpoint(left: typing.SupportsFloat, right: typing.SupportsFloat, alpha: typing.SupportsFloat = ...) -> float: ...\n"
  },
  {
    "path": "test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/__init__.pyi",
    "content": "import pathlib\nimport typing\nfrom . import demo as demo\nfrom typing import overload\n\nclass StaticMethods:\n    def __init__(self, *args, **kwargs) -> None:\n        \"\"\"Initialize self.  See help(type(self)) for accurate signature.\"\"\"\n    @overload\n    @staticmethod\n    def overloaded_static_method(value: typing.SupportsInt) -> int:\n        \"\"\"overloaded_static_method(*args, **kwargs)\n        Overloaded function.\n\n        1. overloaded_static_method(value: typing.SupportsInt) -> int\n\n        2. overloaded_static_method(value: typing.SupportsFloat) -> float\n        \"\"\"\n    @overload\n    @staticmethod\n    def overloaded_static_method(value: typing.SupportsFloat) -> float:\n        \"\"\"overloaded_static_method(*args, **kwargs)\n        Overloaded function.\n\n        1. overloaded_static_method(value: typing.SupportsInt) -> int\n\n        2. overloaded_static_method(value: typing.SupportsFloat) -> float\n        \"\"\"\n    @staticmethod\n    def some_static_method(a: typing.SupportsInt, b: typing.SupportsInt) -> int:\n        \"\"\"some_static_method(a: typing.SupportsInt, b: typing.SupportsInt) -> int\n\n        None\n        \"\"\"\n\nclass TestStruct:\n    field_readwrite: int\n    field_readwrite_docstring: int\n    def __init__(self, *args, **kwargs) -> None:\n        \"\"\"Initialize self.  See help(type(self)) for accurate signature.\"\"\"\n    @property\n    def field_readonly(self) -> int:\n        \"\"\"some docstring\n        (arg0: pybind11_fixtures.TestStruct) -> int\n        \"\"\"\n\ndef func_incomplete_signature(*args, **kwargs):\n    \"\"\"func_incomplete_signature() -> dummy_sub_namespace::HasNoBinding\"\"\"\ndef func_returning_optional() -> int | None:\n    \"\"\"func_returning_optional() -> int | None\"\"\"\ndef func_returning_pair() -> tuple[int, float]:\n    \"\"\"func_returning_pair() -> tuple[int, float]\"\"\"\ndef func_returning_path() -> pathlib.Path:\n    \"\"\"func_returning_path() -> pathlib.Path\"\"\"\ndef func_returning_vector() -> list[float]:\n    \"\"\"func_returning_vector() -> list[float]\"\"\"\n"
  },
  {
    "path": "test-data/pybind11_fixtures/expected_stubs_with_docs/pybind11_fixtures/demo.pyi",
    "content": "import typing\nfrom typing import ClassVar, overload\n\nPI: float\n__version__: str\n\nclass Point:\n    class AngleUnit:\n        \"\"\"Members:\n\n          radian\n\n          degree\"\"\"\n        __members__: ClassVar[dict] = ...  # read-only\n        __entries: ClassVar[dict] = ...\n        degree: ClassVar[Point.AngleUnit] = ...\n        radian: ClassVar[Point.AngleUnit] = ...\n        def __init__(self, value: typing.SupportsInt) -> None:\n            \"\"\"__init__(self: pybind11_fixtures.demo.Point.AngleUnit, value: typing.SupportsInt) -> None\"\"\"\n        def __eq__(self, other: object) -> bool:\n            \"\"\"__eq__(self: object, other: object, /) -> bool\"\"\"\n        def __hash__(self) -> int:\n            \"\"\"__hash__(self: object, /) -> int\"\"\"\n        def __index__(self) -> int:\n            \"\"\"__index__(self: pybind11_fixtures.demo.Point.AngleUnit, /) -> int\"\"\"\n        def __int__(self) -> int:\n            \"\"\"__int__(self: pybind11_fixtures.demo.Point.AngleUnit, /) -> int\"\"\"\n        def __ne__(self, other: object) -> bool:\n            \"\"\"__ne__(self: object, other: object, /) -> bool\"\"\"\n        @property\n        def name(self) -> str:\n            \"\"\"name(self: object, /) -> str\n\n            name(self: object, /) -> str\n            \"\"\"\n        @property\n        def value(self) -> int:\n            \"\"\"(arg0: pybind11_fixtures.demo.Point.AngleUnit) -> int\"\"\"\n\n    class LengthUnit:\n        \"\"\"Members:\n\n          mm\n\n          pixel\n\n          inch\"\"\"\n        __members__: ClassVar[dict] = ...  # read-only\n        __entries: ClassVar[dict] = ...\n        inch: ClassVar[Point.LengthUnit] = ...\n        mm: ClassVar[Point.LengthUnit] = ...\n        pixel: ClassVar[Point.LengthUnit] = ...\n        def __init__(self, value: typing.SupportsInt) -> None:\n            \"\"\"__init__(self: pybind11_fixtures.demo.Point.LengthUnit, value: typing.SupportsInt) -> None\"\"\"\n        def __eq__(self, other: object) -> bool:\n            \"\"\"__eq__(self: object, other: object, /) -> bool\"\"\"\n        def __hash__(self) -> int:\n            \"\"\"__hash__(self: object, /) -> int\"\"\"\n        def __index__(self) -> int:\n            \"\"\"__index__(self: pybind11_fixtures.demo.Point.LengthUnit, /) -> int\"\"\"\n        def __int__(self) -> int:\n            \"\"\"__int__(self: pybind11_fixtures.demo.Point.LengthUnit, /) -> int\"\"\"\n        def __ne__(self, other: object) -> bool:\n            \"\"\"__ne__(self: object, other: object, /) -> bool\"\"\"\n        @property\n        def name(self) -> str:\n            \"\"\"name(self: object, /) -> str\n\n            name(self: object, /) -> str\n            \"\"\"\n        @property\n        def value(self) -> int:\n            \"\"\"(arg0: pybind11_fixtures.demo.Point.LengthUnit) -> int\"\"\"\n    angle_unit: ClassVar[Point.AngleUnit] = ...\n    length_unit: ClassVar[Point.LengthUnit] = ...\n    x_axis: ClassVar[Point] = ...  # read-only\n    y_axis: ClassVar[Point] = ...  # read-only\n    origin: ClassVar[Point] = ...\n    x: float\n    y: float\n    @overload\n    def __init__(self) -> None:\n        \"\"\"__init__(*args, **kwargs)\n        Overloaded function.\n\n        1. __init__(self: pybind11_fixtures.demo.Point) -> None\n\n        2. __init__(self: pybind11_fixtures.demo.Point, x: typing.SupportsFloat, y: typing.SupportsFloat) -> None\n        \"\"\"\n    @overload\n    def __init__(self, x: typing.SupportsFloat, y: typing.SupportsFloat) -> None:\n        \"\"\"__init__(*args, **kwargs)\n        Overloaded function.\n\n        1. __init__(self: pybind11_fixtures.demo.Point) -> None\n\n        2. __init__(self: pybind11_fixtures.demo.Point, x: typing.SupportsFloat, y: typing.SupportsFloat) -> None\n        \"\"\"\n    def as_list(self) -> list[float]:\n        \"\"\"as_list(self: pybind11_fixtures.demo.Point) -> list[float]\"\"\"\n    @overload\n    def distance_to(self, x: typing.SupportsFloat, y: typing.SupportsFloat) -> float:\n        \"\"\"distance_to(*args, **kwargs)\n        Overloaded function.\n\n        1. distance_to(self: pybind11_fixtures.demo.Point, x: typing.SupportsFloat, y: typing.SupportsFloat) -> float\n\n        2. distance_to(self: pybind11_fixtures.demo.Point, other: pybind11_fixtures.demo.Point) -> float\n        \"\"\"\n    @overload\n    def distance_to(self, other: Point) -> float:\n        \"\"\"distance_to(*args, **kwargs)\n        Overloaded function.\n\n        1. distance_to(self: pybind11_fixtures.demo.Point, x: typing.SupportsFloat, y: typing.SupportsFloat) -> float\n\n        2. distance_to(self: pybind11_fixtures.demo.Point, other: pybind11_fixtures.demo.Point) -> float\n        \"\"\"\n    @property\n    def length(self) -> float:\n        \"\"\"(arg0: pybind11_fixtures.demo.Point) -> float\"\"\"\n\ndef answer() -> int:\n    '''answer() -> int\n\n    answer docstring, with end quote\"\n    '''\ndef midpoint(left: typing.SupportsFloat, right: typing.SupportsFloat) -> float:\n    \"\"\"midpoint(left: typing.SupportsFloat, right: typing.SupportsFloat) -> float\"\"\"\ndef sum(arg0: typing.SupportsInt, arg1: typing.SupportsInt) -> int:\n    '''sum(arg0: typing.SupportsInt, arg1: typing.SupportsInt) -> int\n\n    multiline docstring test, edge case quotes \"\"\"\\'\\'\\'\n    '''\ndef weighted_midpoint(left: typing.SupportsFloat, right: typing.SupportsFloat, alpha: typing.SupportsFloat = ...) -> float:\n    \"\"\"weighted_midpoint(left: typing.SupportsFloat, right: typing.SupportsFloat, alpha: typing.SupportsFloat = 0.5) -> float\"\"\"\n"
  },
  {
    "path": "test-data/pybind11_fixtures/pyproject.toml",
    "content": "[build-system]\nrequires = [\n    \"setuptools>=42\",\n    \"wheel\",\n    # Officially supported pybind11 version. This is pinned to guarantee 100% reproducible CI.\n    # As a result, the version needs to be bumped manually at will.\n    \"pybind11==3.0.1\",\n]\n\nbuild-backend = \"setuptools.build_meta\"\n"
  },
  {
    "path": "test-data/pybind11_fixtures/setup.py",
    "content": "# pybind11 is available at setup time due to pyproject.toml\nfrom pybind11.setup_helpers import Pybind11Extension\nfrom setuptools import setup\n\n# Documentation: https://pybind11.readthedocs.io/en/stable/compiling.html\next_modules = [\n    Pybind11Extension(\n        \"pybind11_fixtures\",\n        [\"src/main.cpp\"],\n        cxx_std=17,\n    ),\n]\n\nsetup(\n    name=\"pybind11_fixtures\",\n    version=\"0.0.1\",\n    ext_modules=ext_modules,\n)\n"
  },
  {
    "path": "test-data/pybind11_fixtures/src/main.cpp",
    "content": "/**\n * This file contains the pybind11 reference implementation for the stugen tests,\n * and was originally inspired by:\n *\n * https://github.com/sizmailov/pybind11-mypy-demo\n *\n * Copyright (c) 2016 The Pybind Development Team, All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n *    list of conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n *    this list of conditions and the following disclaimer in the documentation\n *    and/or other materials provided with the distribution.\n *\n * 3. Neither the name of the copyright holder nor the names of its contributors\n *    may be used to endorse or promote products derived from this software\n *    without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * You are under no obligation whatsoever to provide any bug fixes, patches, or\n * upgrades to the features, functionality or performance of the source code\n * (\"Enhancements\") to anyone; however, if you choose to make your Enhancements\n * available either publicly, or directly to the author of this software, without\n * imposing a separate written license agreement for such Enhancements, then you\n * hereby grant the following license: a non-exclusive, royalty-free perpetual\n * license to install, use, modify, prepare derivative works, incorporate into\n * other computer software, distribute, and sublicense such enhancements or\n * derivative works thereof, in binary and source code form.\n */\n\n#include <cmath>\n#include <filesystem>\n#include <optional>\n#include <utility>\n#include <vector>\n\n#include <pybind11/pybind11.h>\n#include <pybind11/stl.h>\n#include <pybind11/stl/filesystem.h>\n\nnamespace py = pybind11;\n\n// ----------------------------------------------------------------------------\n// Dedicated test cases\n// ----------------------------------------------------------------------------\n\nstd::vector<float> funcReturningVector()\n{\n  return std::vector<float>{1.0, 2.0, 3.0};\n}\n\nstd::pair<int, float> funcReturningPair()\n{\n  return std::pair{42, 1.0};\n}\n\nstd::optional<int> funcReturningOptional()\n{\n  return std::nullopt;\n}\n\nstd::filesystem::path funcReturningPath()\n{\n  return std::filesystem::path{\"foobar\"};\n}\n\nnamespace dummy_sub_namespace {\n  struct HasNoBinding{};\n}\n\n// We can enforce the case of an incomplete signature by referring to a type in\n// some namespace that doesn't have a pybind11 binding.\ndummy_sub_namespace::HasNoBinding funcIncompleteSignature()\n{\n  return dummy_sub_namespace::HasNoBinding{};\n}\n\nstruct TestStruct\n{\n  int field_readwrite;\n  int field_readwrite_docstring;\n  int field_readonly;\n};\n\nstruct StaticMethods\n{\n  static int some_static_method(int a, int b) { return 42; }\n  static int overloaded_static_method(int value) { return 42; }\n  static double overloaded_static_method(double value) { return 1.0; }\n};\n\n// Bindings\n\nvoid bind_test_cases(py::module& m) {\n  m.def(\"func_returning_vector\", &funcReturningVector);\n  m.def(\"func_returning_pair\", &funcReturningPair);\n  m.def(\"func_returning_optional\", &funcReturningOptional);\n  m.def(\"func_returning_path\", &funcReturningPath);\n\n  m.def(\"func_incomplete_signature\", &funcIncompleteSignature);\n\n  py::class_<TestStruct>(m, \"TestStruct\")\n      .def_readwrite(\"field_readwrite\", &TestStruct::field_readwrite)\n      .def_readwrite(\"field_readwrite_docstring\", &TestStruct::field_readwrite_docstring, \"some docstring\")\n      .def_property_readonly(\n          \"field_readonly\",\n          [](const TestStruct& x) {\n            return x.field_readonly;\n          },\n          \"some docstring\");\n\n  // Static methods\n  py::class_<StaticMethods> pyStaticMethods(m, \"StaticMethods\");\n\n  pyStaticMethods\n    .def_static(\n      \"some_static_method\",\n      &StaticMethods::some_static_method, R\"#(None)#\", py::arg(\"a\"), py::arg(\"b\"))\n    .def_static(\n      \"overloaded_static_method\",\n      py::overload_cast<int>(&StaticMethods::overloaded_static_method), py::arg(\"value\"))\n    .def_static(\n      \"overloaded_static_method\",\n      py::overload_cast<double>(&StaticMethods::overloaded_static_method), py::arg(\"value\"));\n}\n\n// ----------------------------------------------------------------------------\n// Original demo\n// ----------------------------------------------------------------------------\n\nnamespace demo {\n\nint answer() {\n  return 42;\n}\n\nint sum(int a, int b) {\n  return a + b;\n}\n\ndouble midpoint(double left, double right){\n  return left + (right - left)/2;\n}\n\ndouble weighted_midpoint(double left, double right, double alpha=0.5) {\n  return left + (right - left) * alpha;\n}\n\nstruct Point {\n\n  enum class LengthUnit {\n    mm=0,\n    pixel,\n    inch\n  };\n\n  enum class AngleUnit {\n    radian=0,\n    degree\n  };\n\n  Point() : Point(0, 0) {}\n  Point(double x, double y) : x(x), y(y) {}\n\n  static const Point origin;\n  static const Point x_axis;\n  static const Point y_axis;\n\n  static LengthUnit length_unit;\n  static AngleUnit angle_unit;\n\n  double length() const {\n    return std::sqrt(x * x + y * y);\n  }\n\n  double distance_to(double other_x, double other_y) const {\n    double dx = x - other_x;\n    double dy = y - other_y;\n    return std::sqrt(dx*dx + dy*dy);\n  }\n\n  double distance_to(const Point& other) const {\n    return distance_to(other.x, other.y);\n  }\n\n  std::vector<double> as_vector()\n  {\n    return std::vector<double>{x, y};\n  }\n\n  double x, y;\n};\n\nconst Point Point::origin = Point(0, 0);\nconst Point Point::x_axis = Point(1, 0);\nconst Point Point::y_axis = Point(0, 1);\n\nPoint::LengthUnit Point::length_unit = Point::LengthUnit::mm;\nPoint::AngleUnit Point::angle_unit = Point::AngleUnit::radian;\n\n} // namespace: demo\n\n// Bindings\n\nvoid bind_demo(py::module& m) {\n\n  using namespace demo;\n\n  // Functions\n  m.def(\"answer\", &answer, \"answer docstring, with end quote\\\"\"); // tests explicit docstrings\n  m.def(\"sum\", &sum, \"multiline docstring test, edge case quotes \\\"\\\"\\\"'''\");\n  m.def(\"midpoint\", &midpoint, py::arg(\"left\"), py::arg(\"right\"));\n  m.def(\"weighted_midpoint\", weighted_midpoint, py::arg(\"left\"), py::arg(\"right\"), py::arg(\"alpha\")=0.5);\n\n  // Classes\n  py::class_<Point> pyPoint(m, \"Point\");\n  py::enum_<Point::LengthUnit> pyLengthUnit(pyPoint, \"LengthUnit\");\n  py::enum_<Point::AngleUnit> pyAngleUnit(pyPoint, \"AngleUnit\");\n\n  pyPoint\n    .def(py::init<>())\n    .def(py::init<double, double>(), py::arg(\"x\"), py::arg(\"y\"))\n    .def(\"distance_to\", py::overload_cast<double, double>(&Point::distance_to, py::const_), py::arg(\"x\"), py::arg(\"y\"))\n    .def(\"distance_to\", py::overload_cast<const Point&>(&Point::distance_to, py::const_), py::arg(\"other\"))\n    .def(\"as_list\", &Point::as_vector)\n    .def_readwrite(\"x\", &Point::x, \"some docstring\")\n    .def_property(\"y\",\n        [](Point& self){ return self.y; },\n        [](Point& self, double value){ self.y = value; }\n    )\n    .def_property_readonly(\"length\", &Point::length)\n    .def_property_readonly_static(\"x_axis\", [](py::object cls){return Point::x_axis;})\n    .def_property_readonly_static(\"y_axis\", [](py::object cls){return Point::y_axis;}, \"another docstring\")\n    .def_readwrite_static(\"length_unit\", &Point::length_unit)\n    .def_property_static(\"angle_unit\",\n        [](py::object& /*cls*/){ return Point::angle_unit; },\n        [](py::object& /*cls*/, Point::AngleUnit value){ Point::angle_unit = value; }\n     );\n\n  pyPoint.attr(\"origin\") = Point::origin;\n\n  pyLengthUnit\n    .value(\"mm\", Point::LengthUnit::mm)\n    .value(\"pixel\", Point::LengthUnit::pixel)\n    .value(\"inch\", Point::LengthUnit::inch);\n\n  pyAngleUnit\n    .value(\"radian\", Point::AngleUnit::radian)\n    .value(\"degree\", Point::AngleUnit::degree);\n\n  // Module-level attributes\n  m.attr(\"PI\") = std::acos(-1);\n  m.attr(\"__version__\") = \"0.0.1\";\n}\n\n// ----------------------------------------------------------------------------\n// Module entry point\n// ----------------------------------------------------------------------------\n\nPYBIND11_MODULE(pybind11_fixtures, m) {\n  bind_test_cases(m);\n\n  auto demo = m.def_submodule(\"demo\");\n  bind_demo(demo);\n}\n"
  },
  {
    "path": "test-data/unit/README.md",
    "content": "Tests\n=====\n\n\nQuick Start\n-----------\n\nTo add a simple unit test for a new feature you developed, open or create a\n`test-data/unit/check-*.test` file with a name that roughly relates to the\nfeature you added. If you added a new `check-*.test` file, it will be autodiscovered during unittests run.\n\nAdd the test in this format anywhere in the file:\n\n    [case testNewSyntaxBasics]\n    # flags: --python-version 3.10\n    x: int\n    x = 5\n    y: int = 5\n\n    a: str\n    a = 5  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    b: str = 5  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n    zzz: int\n    zzz: str  # E: Name \"zzz\" already defined\n\n- no code here is executed, just type checked\n- optional `# flags: ` indicates which flags to use for this unit test\n- `# E: abc...` indicates that this line should result in type check error\nwith text \"abc...\"\n- note a space after `E:` and `flags:`\n- `# E:12` adds column number to the expected error\n- use `\\` to escape the `#` character and indicate that the rest of the line is part of\nthe error message\n- repeating `# E: ` several times in one line indicates multiple expected errors in one line\n- `W: ...` and `N: ...` works exactly like `E: ...`, but report a warning and a note respectively\n- lines that don't contain the above should cause no type check errors\n- optional `[builtins fixtures/...]` tells the type checker to use\n`builtins` stubs from the indicated file (see Fixtures section below)\n- optional `[out]` is an alternative to the `# E: ` notation: it indicates that\nany text after it contains the expected type checking error messages.\nUsually, `# E: ` is preferred because it makes it easier to associate the\nerrors with the code generating them at a glance, and to change the code of\nthe test without having to change line numbers in `[out]`\n- an empty `[out]` section has no effect\n- to add tests for a feature that hasn't been implemented yet, append `-xfail`\n  to the end of the test name\n- to run just this test, use `pytest -n0 -k testNewSyntaxBasics`\n\n\nFixtures\n--------\n\nThe unit tests use minimal stubs for builtins, so a lot of operations are not\npossible. You should generally define any needed classes within the test case\ninstead of relying on builtins, though clearly this is not always an option\n(see below for more about stubs in test cases). This way tests run much\nfaster and don't break if the stubs change. If your test crashes mysteriously\neven though the code works when run manually, you should make sure you have\nall the stubs you need for your test case, including built-in classes such as\n`list` or `dict`, as these are not included by default.\n\nWhere the stubs for builtins come from for a given test:\n\n- The builtins used by default in unit tests live in\n  `test-data/unit/lib-stub`.\n\n- Individual test cases can override the `builtins` stubs by using\n  `[builtins fixtures/foo.pyi]`; this targets files in `test-data/unit/fixtures`.\n  Feel free to modify existing files there or create new ones as you deem fit.\n\n- Test cases can also use `[typing fixtures/typing-full.pyi]` to use a more\n  complete stub for `typing` that contains the async types, among other things.\n\n- Feel free to add additional stubs to that `fixtures` directory, but\n  generally don't expand files in `lib-stub` without first discussing the\n  addition with other mypy developers, as additions could slow down the test\n  suite.\n\n- Some tests choose to customize the standard library in a way that's local to the test:\n  ```\n  [case testFoo]\n  ...\n  [file builtins.py]\n  class int:\n    def next_fibonacci() -> int: pass\n  ```\n  Another possible syntax is:\n  ```\n  [fixture builtins.py]\n  ```\n  Whether you use `[file ...]` or `[fixture ...]` depends on whether you want\n  the file to be part of the tested corpus (e.g. contribute to `[out]` section)\n  or only support the test.\n\nRunning tests and linting\n-------------------------\n\nFirst install any additional dependencies needed for testing:\n\n    python3 -m pip install -U -r test-requirements.txt\n\nConfigure `pre-commit` to run the linters automatically when you commit:\n\n    pre-commit install\n\nThe unit test suites are driven by the `pytest` framework. To run all mypy tests,\nrun `pytest` in the mypy repository:\n\n    pytest -q mypy\n\nThis will run all tests, including integration and regression tests,\nand will verify that all stubs are valid. This may take several\nminutes to run, so you don't want to use this all the time while doing\ndevelopment. (The `-q` option activates less verbose output that looks\nbetter when running tests using many CPU cores.)\n\nTest suites for individual components are in the files `mypy/test/test*.py`.\n\nNote that some tests will be disabled for older python versions.\n\nIf you work on mypyc, you will want to also run mypyc tests:\n\n    pytest -q mypyc\n\nYou can run tests from a specific module directly, a specific suite within a\nmodule, or a test in a suite (even if it's data-driven):\n\n    pytest -q mypy/test/testdiff.py\n\n    pytest -q mypy/test/testsemanal.py::SemAnalTypeInfoSuite\n\n    pytest -n0 mypy/test/testargs.py::ArgSuite::test_coherence\n\n    pytest -n0 mypy/test/testcheck.py::TypeCheckSuite::testCallingVariableWithFunctionType\n\nTo control which tests are run and how, you can use the `-k` switch:\n\n    pytest -q -k \"MethodCall\"\n\nYou can also run the type checker for manual testing without\ninstalling it by setting up the Python module search path suitably:\n\n    export PYTHONPATH=$PWD\n    python3 -m mypy PROGRAM.py\n\nYou will have to manually install the `typing` module if you're running Python\n3.4 or earlier.\n\nYou can also execute mypy as a module\n\n    python3 -m mypy PROGRAM.py\n\nYou can check a module or string instead of a file:\n\n    python3 -m mypy PROGRAM.py\n    python3 -m mypy -m MODULE\n    python3 -m mypy -c 'import MODULE'\n\nTo run mypy on itself:\n\n    python3 -m mypy --config-file mypy_self_check.ini -p mypy\n\nTo run the linter (this commands just wraps `pre-commit`, so you can also\ninvoke it directly like `pre-commit run -a`, and this will also run when you\n`git commit` if enabled):\n\n    python3 runtests.py lint\n\nYou can also run all of the above tests using `runtests.py` (this includes\ntype checking mypy and linting):\n\n    python3 runtests.py\n\nBy default, this runs everything except some mypyc tests. You can give it\narguments to control what gets run, such as `self` to run mypy on itself:\n\n    python3 runtests.py self\n\nRun `python3 runtests.py mypyc-extra` to run mypyc tests that are not\nenabled by default. This is typically only needed if you work on mypyc.\n\nMany test suites store test case descriptions in text files\n(`test-data/unit/*.test`). The module `mypy.test.data` parses these\ndescriptions.\n\nPython evaluation test cases are a little different from unit tests\n(`mypy/test/testpythoneval.py`, `test-data/unit/pythoneval.test`). These\ntype check programs and run them. Unlike the unit tests, these use the\nfull builtins and library stubs instead of minimal ones. Run them using\n`pytest -k testpythoneval`.\n\n`pytest` determines the number of processes to use. The default (set in\n`./pytest.ini`) is the number of logical cores; this can be overridden using\n`-n` option. To run a single process, use `pytest -n0`.\n\nNote that running more processes than logical cores is likely to\nsignificantly decrease performance.\n\nTo run tests with coverage:\n\n    python3 -m pytest --cov mypy --cov-config setup.cfg  --cov-report=term-missing:skip-covered --cov-report=html\n\n\nDebugging\n---------\n\nYou can use interactive debuggers like `pdb` to debug failing tests. You\nneed to pass the `-n0` option to disable parallelization:\n\n    pytest -n0 --pdb -k MethodCall\n\nYou can also write `import pdb; pdb.set_trace()` in code to enter the\ndebugger.\n\nThe `--mypy-verbose` flag can be used to enable additional debug output from\nmost tests (as if `--verbose` had been passed to mypy):\n\n    pytest -n0 --mypy-verbose -k MethodCall\n\nCoverage reports\n----------------\n\nThere is an experimental feature to generate coverage reports.  To use\nthis feature, you need to `pip install -U lxml`.  This is an extension\nmodule and requires various library headers to install; on a\nDebian-derived system the command\n  `apt-get install python3-dev libxml2-dev libxslt1-dev`\nmay provide the necessary dependencies.\n\nTo use the feature, pass e.g. `--txt-report \"$(mktemp -d)\"`.\n"
  },
  {
    "path": "test-data/unit/check-abstract.test",
    "content": "-- Type checker test cases for abstract classes.\n\n\n-- Subtyping with abstract classes\n-- -------------------------------\n\n\n[case testAbstractClassSubclasses]\n\nfrom abc import abstractmethod, ABCMeta\n\ni: I\nj: J\na: A\nb: B\nc: C\n\ndef f(): i, j, a, b, c # Prevent redefinition\n\nj = c  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"J\")\na = i  # E: Incompatible types in assignment (expression has type \"I\", variable has type \"A\")\na = j  # E: Incompatible types in assignment (expression has type \"J\", variable has type \"A\")\nb = i  # E: Incompatible types in assignment (expression has type \"I\", variable has type \"B\")\n\ni = a\ni = b\ni = c\nj = a\nj = b\na = b\n\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self): pass\nclass J(metaclass=ABCMeta):\n    @abstractmethod\n    def g(self): pass\nclass A(I, J): pass\nclass B(A): pass\nclass C(I): pass\n[builtins fixtures/tuple.pyi]\n\n[case testAbstractClassSubtypingViaExtension]\n\nfrom abc import abstractmethod, ABCMeta\n\ni: I\nj: J\na: A\no: object\n\ndef f(): i, j, a, o # Prevent redefinition\n\nj = i # E: Incompatible types in assignment (expression has type \"I\", variable has type \"J\")\na = i # E: Incompatible types in assignment (expression has type \"I\", variable has type \"A\")\na = j # E: Incompatible types in assignment (expression has type \"J\", variable has type \"A\")\ni = o # E: Incompatible types in assignment (expression has type \"object\", variable has type \"I\")\nj = o # E: Incompatible types in assignment (expression has type \"object\", variable has type \"J\")\n\ni = a\nj = a\ni = j\no = i\no = j\n\nclass I(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self): pass\nclass J(I): pass\nclass A(J): pass\n[builtins fixtures/tuple.pyi]\n\n[case testInheritingAbstractClassInSubclass]\nfrom abc import abstractmethod, ABCMeta\n\ni: I\na: A\nb: B\n\nif int():\n    i = a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"I\")\nif int():\n    b = a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\nif int():\n    a = b\nif int():\n    i = b\n\nclass I(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self): pass\nclass A: pass\nclass B(A, I): pass\n\n\n-- Abstract class objects\n-- ----------------------\n\n\n[case testAbstractClassAsTypeObject]\n\nfrom abc import abstractmethod, ABCMeta\n\nclass I(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self): pass\n\no: object\nt: type\n\no = I\nt = I\n\n[case testAbstractClassInCasts]\nfrom typing import cast\nfrom abc import abstractmethod, ABCMeta\n\nclass I(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self): pass\nclass A(I): pass\nclass B: pass\n\ni: I\na: A\nb: B\no: object\n\nif int():\n    a = cast(I, o) # E: Incompatible types in assignment (expression has type \"I\", variable has type \"A\")\nif int():\n    b = cast(B, i) # Ok; a subclass of B might inherit I\nif int():\n    i = cast(I, b) # Ok; a subclass of B might inherit I\n\nif int():\n    i = cast(I, o)\nif int():\n    i = cast(I, a)\n[builtins fixtures/tuple.pyi]\n\n[case testInstantiatingClassThatImplementsAbstractMethod]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass A(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self): pass\nclass B(A):\n  def f(self): pass\nB()\n[out]\n\n[case testInstantiatingAbstractClass]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass A(metaclass=ABCMeta): pass\nclass B(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self): pass\nA() # OK\nB() # E: Cannot instantiate abstract class \"B\" with abstract attribute \"f\"\n[out]\n\n[case testInstantiatingClassWithInheritedAbstractMethod]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass A(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self): pass\n  @abstractmethod\n  def g(self): pass\nclass B(A): pass\nB() # E: Cannot instantiate abstract class \"B\" with abstract attributes \"f\" and \"g\"\n[out]\n\n[case testInstantiationAbstractsInTypeForFunctions]\nfrom typing import Type\nfrom abc import abstractmethod\n\nclass A:\n    @abstractmethod\n    def m(self) -> None: pass\nclass B(A): pass\nclass C(B):\n    def m(self) -> None:\n        pass\n\ndef f(cls: Type[A]) -> A:\n    return cls()  # OK\ndef g() -> A:\n    return A()  # E: Cannot instantiate abstract class \"A\" with abstract attribute \"m\"\n\nf(A)  # E: Only concrete class can be given where \"type[A]\" is expected\nf(B)  # E: Only concrete class can be given where \"type[A]\" is expected\nf(C)  # OK\nx: Type[B]\nf(x)  # OK\n[out]\n\n[case testAbstractTypeInADict]\nfrom typing import Dict, Type\nfrom abc import abstractmethod\n\nclass Class:\n    @abstractmethod\n    def method(self) -> None:\n        pass\n\nmy_dict_init: Dict[int, Type[Class]] = {0: Class}  # E: Only concrete class can be given where \"tuple[int, type[Class]]\" is expected\n\nclass Child(Class):\n    def method(self) -> None: ...\n\nother_dict_init: Dict[int, Type[Class]] = {0: Child}  # ok\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testInstantiationAbstractsInTypeForAliases]\nfrom typing import Type\nfrom abc import abstractmethod\n\nclass A:\n    @abstractmethod\n    def m(self) -> None: pass\nclass B(A): pass\nclass C(B):\n    def m(self) -> None:\n        pass\n\ndef f(cls: Type[A]) -> A:\n    return cls()  # OK\n\nAlias = A\nGoodAlias = C\nAlias()  # E: Cannot instantiate abstract class \"A\" with abstract attribute \"m\"\nGoodAlias()\nf(Alias)  # E: Only concrete class can be given where \"type[A]\" is expected\nf(GoodAlias)\n[out]\n\n[case testInstantiationAbstractsInTypeForVariables]\n# flags: --no-strict-optional\nfrom typing import Type, overload\nfrom abc import abstractmethod\n\nclass A:\n    @abstractmethod\n    def m(self) -> None: pass\nclass B(A): pass\nclass C(B):\n    def m(self) -> None:\n        pass\n\nvar: Type[A]\nvar()\nif int():\n    var = A # E: Can only assign concrete classes to a variable of type \"type[A]\"\nif int():\n    var = B # E: Can only assign concrete classes to a variable of type \"type[A]\"\nif int():\n    var = C # OK\n\nvar_old = None # type: Type[A] # Old syntax for variable annotations\nvar_old()\nif int():\n    var_old = A # E: Can only assign concrete classes to a variable of type \"type[A]\"\nif int():\n    var_old = B # E: Can only assign concrete classes to a variable of type \"type[A]\"\nif int():\n    var_old = C # OK\n\nclass D(A):\n    @overload\n    def __new__(cls, a) -> \"D\": ...\n    @overload\n    def __new__(cls) -> \"D\": ...\n    def __new__(cls, a=None) -> \"D\": ...\nif int():\n    var = D # E: Can only assign concrete classes to a variable of type \"type[A]\"\n[out]\n\n[case testInstantiationAbstractsInTypeForClassMethods]\nfrom typing import Type\nfrom abc import abstractmethod\n\nclass Logger:\n    @staticmethod\n    def log(a: Type[C]):\n        pass\nclass C:\n    @classmethod\n    def action(cls) -> None:\n        cls() #OK for classmethods\n        Logger.log(cls)  #OK for classmethods\n    @abstractmethod\n    def m(self) -> None:\n        pass\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testInstantiatingClassWithInheritedAbstractMethodAndSuppression]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def a(self): pass\n    @abstractmethod\n    def b(self): pass\n    @abstractmethod\n    def c(self): pass\n    @abstractmethod\n    def d(self): pass\n    @abstractmethod\n    def e(self): pass\n    @abstractmethod\n    def f(self): pass\n    @abstractmethod\n    def g(self): pass\n    @abstractmethod\n    def h(self): pass\n    @abstractmethod\n    def i(self): pass\n    @abstractmethod\n    def j(self): pass\na = A() # E: Cannot instantiate abstract class \"A\" with abstract attributes \"a\", \"b\", ... and \"j\" (7 methods suppressed)\n[out]\n\n\n-- Implementing abstract methods\n-- -----------------------------\n\n\n[case testImplementingAbstractMethod]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self, x: int) -> int: pass\n    @abstractmethod\n    def g(self, x: int) -> int: pass\nclass B(A):\n    def f(self, x: str) -> int: \\\n            # E: Argument 1 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\" \\\n            # N: This violates the Liskov substitution principle \\\n            # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n        return 0\n    def g(self, x: int) -> int: return 0\n[out]\n\n[case testImplementingAbstractMethodWithMultipleBaseClasses]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self, x: int) -> int: pass\nclass J(metaclass=ABCMeta):\n    @abstractmethod\n    def g(self, x: str) -> str: pass\nclass A(I, J):\n    def f(self, x: str) -> int: return 0 \\\n        # E: Argument 1 of \"f\" is incompatible with supertype \"I\"; supertype defines the argument type as \"int\" \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n    def g(self, x: str) -> int: return 0 \\\n        # E: Return type \"int\" of \"g\" incompatible with return type \"str\" in supertype \"J\"\n    def h(self) -> int: return 0 # Not related to any base class\n[out]\n\n[case testImplementingAbstractMethodWithExtension]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass J(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self, x: int) -> int: pass\nclass I(J): pass\nclass A(I):\n    def f(self, x: str) -> int: return 0 \\\n        # E: Argument 1 of \"f\" is incompatible with supertype \"J\"; supertype defines the argument type as \"int\" \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n[out]\n\n[case testInvalidOverridingAbstractMethod]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass J(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self, x: 'J') -> None: pass\nclass I(J):\n    @abstractmethod\n    def f(self, x: 'I') -> None: pass # E: Argument 1 of \"f\" is incompatible with supertype \"J\"; supertype defines the argument type as \"J\" \\\n                                      # N: This violates the Liskov substitution principle \\\n                                      # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n[out]\n\n[case testAbstractClassCoAndContraVariance]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self, a: A) -> 'I': pass\n    @abstractmethod\n    def g(self, a: A) -> 'I': pass\n    @abstractmethod\n    def h(self, a: 'I') -> A: pass\nclass A(I):\n    def h(self, a: 'A') -> 'I': # Fail\n        return A()\n    def f(self, a: 'I') -> 'I':\n        return A()\n    def g(self, a: 'A') -> 'A':\n        return A()\n[out]\nmain:11: error: Return type \"I\" of \"h\" incompatible with return type \"A\" in supertype \"I\"\nmain:11: error: Argument 1 of \"h\" is incompatible with supertype \"I\"; supertype defines the argument type as \"I\"\nmain:11: note: This violates the Liskov substitution principle\nmain:11: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n\n\n-- Accessing abstract members\n-- --------------------------\n\n\n[case testAccessingAbstractMethod]\nfrom abc import abstractmethod, ABCMeta\n\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self, a: int) -> str: pass\n\ni: I\na: int\nb: str\n\nif int():\n    a = i.f(a) # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    b = i.f(b) # E: Argument 1 to \"f\" of \"I\" has incompatible type \"str\"; expected \"int\"\ni.g()      # E: \"I\" has no attribute \"g\"\n\nif int():\n    b = i.f(a)\n[builtins fixtures/tuple.pyi]\n\n[case testAccessingInheritedAbstractMethod]\nfrom abc import abstractmethod, ABCMeta\n\nclass J(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self, a: int) -> str: pass\nclass I(J): pass\n\ni: I\na: int\nb: str\n\nif int():\n    a = i.f(1) # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    b = i.f(1)\n\n\n-- Any (dynamic) types\n-- -------------------\n[builtins fixtures/tuple.pyi]\n\n\n[case testAbstractClassWithAllDynamicTypes]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self, x): pass\n    @abstractmethod\n    def g(self, x): pass\nclass A(I):\n    def f(self, x): pass\n    def g(self, x, y) -> None: pass  # Fail\n[out]\nmain:10: error: Signature of \"g\" incompatible with supertype \"I\"\nmain:10: note:      Superclass:\nmain:10: note:          def g(self, x: Any) -> Any\nmain:10: note:      Subclass:\nmain:10: note:          def g(self, x: Any, y: Any) -> None\n\n[case testAbstractClassWithAllDynamicTypes2]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self, x): pass\n    @abstractmethod\n    def g(self, x): pass\nclass A(I):\n    def f(self, x): pass\n    def g(self, x, y): pass\n[out]\n\n[case testAbstractClassWithImplementationUsingDynamicTypes]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass I(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self, x: int) -> None: pass\n    @abstractmethod\n    def g(self, x: int) -> None: pass\nclass A(I):\n    def f(self, x): pass\n    def g(self, x, y): pass\n[out]\n\n\n-- Special cases\n-- -------------\n\n\n[case testMultipleAbstractBases]\nfrom abc import abstractmethod, ABCMeta\nimport typing\nclass A(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self) -> None: pass\nclass B(metaclass=ABCMeta):\n  @abstractmethod\n  def g(self) -> None: pass\nclass C(A, B):\n  @abstractmethod\n  def h(self) -> None: pass\n\n[case testMemberAccessWithMultipleAbstractBaseClasses]\n\nfrom abc import abstractmethod, ABCMeta\n\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self) -> None: pass\nclass B(metaclass=ABCMeta):\n    @abstractmethod\n    def g(self) -> None: pass\nclass C(A, B): pass\nx: C\nx.f()\nx.g()\nx.f(x) # E: Too many arguments for \"f\" of \"A\"\nx.g(x) # E: Too many arguments for \"g\" of \"B\"\n\n[case testInstantiatingAbstractClassWithMultipleBaseClasses]\n\nfrom abc import abstractmethod, ABCMeta\n\nclass A(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self) -> None: pass\nclass B(metaclass=ABCMeta):\n  @abstractmethod\n  def g(self) -> None: pass\nclass C(A, B):\n  def f(self) -> None: pass\nclass D(A, B):\n  def g(self) -> None: pass\nclass E(A, B):\n  def f(self) -> None: pass\n  def g(self) -> None: pass\nC() # E: Cannot instantiate abstract class \"C\" with abstract attribute \"g\"\nD() # E: Cannot instantiate abstract class \"D\" with abstract attribute \"f\"\nE()\n\n[case testInconsistentMro]\nfrom abc import abstractmethod, ABCMeta\nimport typing\n\nclass A(metaclass=ABCMeta): pass\nclass B(object, A, metaclass=ABCMeta): # E: Cannot determine consistent method resolution order (MRO) for \"B\"\n    pass\n\nclass C(object, A):  # E: Cannot determine consistent method resolution order (MRO) for \"C\" \\\n                     # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases\n    pass\n\n[case testOverloadedAbstractMethod]\nfrom foo import *\n[file foo.pyi]\nfrom abc import abstractmethod, ABCMeta\nfrom typing import overload\n\nclass A(metaclass=ABCMeta):\n  @abstractmethod\n  @overload\n  def f(self, x: int) -> int: pass\n  @abstractmethod\n  @overload\n  def f(self, x: str) -> str: pass\n\nclass B(A):\n  @overload\n  def f(self, x: int) -> int: pass\n  @overload\n  def f(self, x: str) -> str: pass\nA() # E: Cannot instantiate abstract class \"A\" with abstract attribute \"f\"\nB()\nB().f(1)\na = B() # type: A\na.f(1)\na.f('')\na.f(B()) # E: No overload variant of \"f\" of \"A\" matches argument type \"B\" \\\n         # N: Possible overload variants: \\\n         # N:     def f(self, x: int) -> int \\\n         # N:     def f(self, x: str) -> str\n\n[case testOverloadedAbstractMethodWithAlternativeDecoratorOrder]\nfrom foo import *\n[file foo.pyi]\nfrom abc import abstractmethod, ABCMeta\nfrom typing import overload\n\nclass A(metaclass=ABCMeta):\n  @overload\n  @abstractmethod\n  def f(self, x: int) -> int: pass\n  @overload\n  @abstractmethod\n  def f(self, x: str) -> str: pass\n\nclass B(A):\n  @overload\n  def f(self, x: int) -> int: pass\n  @overload\n  def f(self, x: str) -> str: pass\nA() # E: Cannot instantiate abstract class \"A\" with abstract attribute \"f\"\nB()\nB().f(1)\na = B() # type: A\na.f(1)\na.f('')\na.f(B()) # E: No overload variant of \"f\" of \"A\" matches argument type \"B\" \\\n         # N: Possible overload variants: \\\n         # N:     def f(self, x: int) -> int \\\n         # N:     def f(self, x: str) -> str\n\n[case testOverloadedAbstractMethodVariantMissingDecorator0]\nfrom foo import *\n[file foo.pyi]\nfrom abc import abstractmethod, ABCMeta\nfrom typing import overload\n\nclass A(metaclass=ABCMeta):\n  @abstractmethod \\\n    # E: Overloaded method has both abstract and non-abstract variants\n  @overload\n  def f(self, x: int) -> int: pass\n  @overload\n  def f(self, x: str) -> str: pass\n[out]\n\n[case testOverloadedAbstractMethodVariantMissingDecorator1]\nfrom foo import *\n[file foo.pyi]\nfrom abc import abstractmethod, ABCMeta\nfrom typing import overload\n\nclass A(metaclass=ABCMeta):\n  @overload \\\n    # E: Overloaded method has both abstract and non-abstract variants\n  def f(self, x: int) -> int: pass\n  @abstractmethod\n  @overload\n  def f(self, x: str) -> str: pass\n[out]\n\n[case testMultipleInheritanceAndAbstractMethod]\nimport typing\nfrom abc import abstractmethod, ABCMeta\nclass A:\n  def f(self, x: str) -> None: pass\nclass B(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self, x: str) -> None: pass\nclass C(A, B): pass\n\n[case testMultipleInheritanceAndAbstractMethod2]\nimport typing\nfrom abc import abstractmethod, ABCMeta\nclass A:\n  def f(self, x: str) -> None: pass\nclass B(metaclass=ABCMeta):\n  @abstractmethod\n  def f(self, x: int) -> None: pass\nclass C(A, B): pass\n[out]\nmain:8: error: Definition of \"f\" in base class \"A\" is incompatible with definition in base class \"B\"\n\n[case testCallAbstractMethodBeforeDefinition]\nimport typing\nfrom abc import abstractmethod, ABCMeta\nclass A(metaclass=ABCMeta):\n    def f(self) -> None:\n        self.g(1) # E: Argument 1 to \"g\" of \"A\" has incompatible type \"int\"; expected \"str\"\n    @abstractmethod\n    def g(self, x: str) -> None: pass\n[out]\n\n[case testAbstractOperatorMethods1]\nimport typing\nfrom abc import abstractmethod, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def __lt__(self, other: 'A') -> int: pass\n    @abstractmethod\n    def __gt__(self, other: 'A') -> int: pass\n\n[case testAbstractOperatorMethods2]\nfrom typing import cast, Any\nfrom abc import abstractmethod, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def __radd__(self, other: 'C') -> str: pass # Error\nclass B:\n    @abstractmethod\n    def __add__(self, other: 'A') -> int: pass\nclass C:\n    def __add__(self, other: int) -> B:\n        return cast(Any, None)\n[out]\n\n[case testAbstractClassWithAnyBase]\nfrom typing import Any\nfrom abc import abstractmethod, ABCMeta\n\nA: Any\n\nclass D(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self) -> None: pass\n\nclass C(A, D):\n    pass\n\nC()  # A might implement 'f'\n\n\n-- Abstract properties\n-- -------------------\n\n\n[case testReadOnlyAbstractProperty]\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\ndef f(a: A) -> None:\n    a.x() # E: \"int\" not callable\n    a.x = 1  # E: Property \"x\" defined in \"A\" is read-only\n[out]\n\n[case testReadOnlyAbstractPropertyForwardRef]\nfrom abc import abstractproperty, ABCMeta\ndef f(a: A) -> None:\n    a.x() # E: \"int\" not callable\n    a.x = 1  # E: Property \"x\" defined in \"A\" is read-only\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\n[out]\n\n[case testReadWriteAbstractProperty]\nfrom abc import abstractproperty, ABCMeta\ndef f(a: A) -> None:\n    a.x.y # E: \"int\" has no attribute \"y\"\n    a.x = 1\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\n    @x.setter\n    def x(self, x: int) -> None: pass\n\n[case testReadWriteDeleteAbstractProperty]\n# flags: --no-strict-optional\nfrom abc import ABC, abstractmethod\nclass Abstract(ABC):\n    @property\n    @abstractmethod\n    def prop(self) -> str: ...\n\n    @prop.setter\n    @abstractmethod\n    def prop(self, code: str) -> None: ...\n\n    @prop.deleter\n    @abstractmethod\n    def prop(self) -> None: ...\n\nclass Good(Abstract):\n    @property\n    def prop(self) -> str: ...\n    @prop.setter\n    def prop(self, code: str) -> None: ...\n    @prop.deleter\n    def prop(self) -> None: ...\n\nclass Bad1(Abstract):\n    @property  # E: Read-only property cannot override read-write property\n    def prop(self) -> str: ...\n\nclass ThisShouldProbablyError(Abstract):\n    @property\n    def prop(self) -> str: ...\n    @prop.setter\n    def prop(self, code: str) -> None: ...\n\na = Good()\nreveal_type(a.prop)  # N: Revealed type is \"builtins.str\"\na.prop = 123  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[builtins fixtures/property.pyi]\n\n[case testInstantiateClassWithReadOnlyAbstractProperty]\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\nclass B(A): pass\nb = B() # E: Cannot instantiate abstract class \"B\" with abstract attribute \"x\"\n\n[case testInstantiateClassWithReadWriteAbstractProperty]\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\n    @x.setter\n    def x(self, x: int) -> None: pass\nclass B(A): pass\nb = B() # E: Cannot instantiate abstract class \"B\" with abstract attribute \"x\"\n\n[case testImplementAbstractPropertyViaProperty]\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\nclass B(A):\n    @property\n    def x(self) -> int: return 0\nb = B()\nb.x() # E: \"int\" not callable\n[builtins fixtures/property.pyi]\n\n[case testImplementReadWriteAbstractPropertyViaProperty]\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\n    @x.setter\n    def x(self, v: int) -> None: pass\nclass B(A):\n    @property\n    def x(self) -> int: return 0\n    @x.setter\n    def x(self, v: int) -> None: pass\nb = B()\nb.x.y # E: \"int\" has no attribute \"y\"\n[builtins fixtures/property.pyi]\n\n[case testImplementAbstractPropertyViaPropertyInvalidType]\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\nclass B(A):\n    @property\n    def x(self) -> str: return \"no\" # E: Signature of \"x\" incompatible with supertype \"A\" \\\n                                    # N:      Superclass: \\\n                                    # N:          int \\\n                                    # N:      Subclass: \\\n                                    # N:          str\nb = B()\nb.x() # E: \"str\" not callable\n[builtins fixtures/property.pyi]\n\n[case testCantImplementAbstractPropertyViaInstanceVariable]\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\nclass B(A):\n    def __init__(self) -> None:\n        self.x = 1 # E\nb = B() # E\nb.x.y # E\n[builtins fixtures/property.pyi]\n[out]\nmain:7: error: Property \"x\" defined in \"A\" is read-only\nmain:8: error: Cannot instantiate abstract class \"B\" with abstract attribute \"x\"\nmain:9: error: \"int\" has no attribute \"y\"\n\n[case testSuperWithAbstractProperty]\n# flags: --no-strict-optional\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\nclass B(A):\n    @property\n    def x(self) -> int:\n        return super().x.y  # E: Call to abstract method \"x\" of \"A\" with trivial body via super() is unsafe \\\n                            # E: \"int\" has no attribute \"y\"\n[builtins fixtures/property.pyi]\n\n[case testSuperWithReadWriteAbstractProperty]\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\n    @x.setter\n    def x(self, v: int) -> None: pass\nclass B(A):\n    @property\n    def x(self) -> int:\n        return super().x.y # E\n    @x.setter\n    def x(self, v: int) -> None:\n        super().x = '' # E\n[builtins fixtures/property.pyi]\n[out]\nmain:10: error: \"int\" has no attribute \"y\"\nmain:13: error: Invalid assignment target\n\n[case testOnlyImplementGetterOfReadWriteAbstractProperty]\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self) -> int: pass\n    @x.setter\n    def x(self, v: int) -> None: pass\nclass B(A):\n    @property # E\n    def x(self) -> int: return 0\nb = B()\nb.x.y # E\n[builtins fixtures/property.pyi]\n[out]\nmain:8: error: Read-only property cannot override read-write property\nmain:11: error: \"int\" has no attribute \"y\"\n\n[case testDynamicallyTypedReadOnlyAbstractProperty]\nfrom abc import abstractproperty, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self): pass\ndef f(a: A) -> None:\n    a.x.y\n    a.x = 1  # E: Property \"x\" defined in \"A\" is read-only\n[out]\n\n[case testDynamicallyTypedReadOnlyAbstractPropertyForwardRef]\nfrom abc import abstractproperty, ABCMeta\ndef f(a: A) -> None:\n    a.x.y\n    a.x = 1  # E: Property \"x\" defined in \"A\" is read-only\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self): pass\n[out]\n\n[case testDynamicallyTypedReadWriteAbstractProperty]\nfrom abc import abstractproperty, ABCMeta\ndef f(a: A) -> None:\n    a.x.y\n    a.x = 1\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def x(self): pass\n    @x.setter\n    def x(self, x): pass\n[out]\n\n[case testMixinTypedAbstractProperty]\nfrom abc import ABCMeta, abstractproperty\nclass A(metaclass=ABCMeta):\n    @abstractproperty\n    def foo(cls) -> str:\n        pass\nclass Mixin:\n    foo = \"foo\"\nclass C(Mixin, A):\n    pass\n[out]\n\n[case testMixinTypedProperty]\nclass A:\n    @property\n    def foo(cls) -> str:\n        return \"yes\"\nclass Mixin:\n    foo = \"foo\"\nclass C(Mixin, A):\n    pass\n[builtins fixtures/property.pyi]\n\n[case testMixinSubtypedProperty]\nclass X:\n    pass\nclass Y(X):\n    pass\nclass A:\n    @property\n    def foo(cls) -> X:\n        return X()\nclass Mixin:\n    foo = Y()\nclass C(Mixin, A):\n    pass\n[builtins fixtures/property.pyi]\n\n[case testMixinTypedPropertyReversed]\nclass A:\n    @property\n    def foo(cls) -> str:\n        return \"no\"\nclass Mixin:\n    foo = \"foo\"\nclass C(A, Mixin): # E: Cannot override writeable attribute \"foo\" in base \"Mixin\" with read-only property in base \"A\"\n    pass\n[builtins fixtures/property.pyi]\n\n-- Special cases\n-- -------------\n\n\n[case testNestedAbstractClass]\nfrom abc import abstractmethod, ABCMeta\n\nclass A:\n    class B(metaclass=ABCMeta):\n        @abstractmethod\n        def f(self) -> None: pass\n\n    class C(B): pass\n\nA.B()  # E: Cannot instantiate abstract class \"B\" with abstract attribute \"f\"\nA.C()  # E: Cannot instantiate abstract class \"C\" with abstract attribute \"f\"\n\n[case testAbstractNewTypeAllowed]\nfrom typing import NewType, Mapping\n\nConfig = NewType('Config', Mapping[str, str])\n\nbad = Mapping[str, str]()  # E: Cannot instantiate abstract class \"Mapping\" with abstract attribute \"__iter__\"\ndefault = Config({'cannot': 'modify'})  # OK\n\ndefault[1] = 2  # E: Unsupported target for indexed assignment (\"Config\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testSubclassOfABCFromDictionary]\nfrom abc import abstractmethod, ABCMeta\n\nclass MyAbstractType(metaclass=ABCMeta):\n  @abstractmethod\n  def do(self): pass\n\nclass MyConcreteA(MyAbstractType):\n  def do(self):\n    print('A')\n\nclass MyConcreteB(MyAbstractType):\n  def do(self):\n    print('B')\n\nclass MyAbstractA(MyAbstractType):\n  @abstractmethod\n  def do(self): pass\n\nclass MyAbstractB(MyAbstractType):\n  @abstractmethod\n  def do(self): pass\n\nmy_concrete_types = {\n  'A': MyConcreteA,\n  'B': MyConcreteB,\n}\n\nmy_abstract_types = {\n  'A': MyAbstractA,\n  'B': MyAbstractB,\n}\n\nreveal_type(my_concrete_types)  # N: Revealed type is \"builtins.dict[builtins.str, def () -> __main__.MyAbstractType]\"\nreveal_type(my_abstract_types)  # N: Revealed type is \"builtins.dict[builtins.str, def () -> __main__.MyAbstractType]\"\n\na = my_concrete_types['A']()\na.do()\nb = my_concrete_types['B']()\nb.do()\n\nc = my_abstract_types['A']()  # E: Cannot instantiate abstract class \"MyAbstractType\" with abstract attribute \"do\"\nc.do()\nd = my_abstract_types['B']()  # E: Cannot instantiate abstract class \"MyAbstractType\" with abstract attribute \"do\"\nd.do()\n\n[builtins fixtures/dict.pyi]\n\n[case testAbstractClassesWorkWithGenericDecorators]\nfrom abc import abstractmethod, ABCMeta\nfrom typing import Type, TypeVar\n\nT = TypeVar(\"T\")\ndef deco(cls: Type[T]) -> Type[T]: return cls\n\n@deco\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def foo(self, x: int) -> None: ...\n\n[case testAbstractPropertiesAllowed]\nfrom abc import abstractmethod\n\nclass B:\n    @property\n    @abstractmethod\n    def x(self) -> int: ...\n    @property\n    @abstractmethod\n    def y(self) -> int: ...\n    @y.setter\n    @abstractmethod\n    def y(self, value: int) -> None: ...\n\nB()  # E: Cannot instantiate abstract class \"B\" with abstract attributes \"x\" and \"y\"\nb: B\nb.x = 1  # E: Property \"x\" defined in \"B\" is read-only\nb.y = 1\n[builtins fixtures/property.pyi]\n\n\n-- Treatment of empty bodies in ABCs and protocols\n-- -----------------------------------------------\n\n[case testEmptyBodyProhibitedFunction]\nfrom typing import overload, Union\n\ndef func1(x: str) -> int: pass  # E: Missing return statement\ndef func2(x: str) -> int: ...  # E: Missing return statement\ndef func3(x: str) -> int:  # E: Missing return statement\n    \"\"\"Some function.\"\"\"\n\n@overload\ndef func4(x: int) -> int: ...\n@overload\ndef func4(x: str) -> str: ...\ndef func4(x: Union[int, str]) -> Union[int, str]:  # E: Missing return statement\n    pass\n\n@overload\ndef func5(x: int) -> int: ...\n@overload\ndef func5(x: str) -> str: ...\ndef func5(x: Union[int, str]) -> Union[int, str]:  # E: Missing return statement\n    \"\"\"Some function.\"\"\"\n\n[case testEmptyBodyProhibitedMethodNonAbstract]\nfrom typing import overload, Union\n\nclass A:\n    def func1(self, x: str) -> int: pass  # E: Missing return statement\n    def func2(self, x: str) -> int: ...  # E: Missing return statement\n    def func3(self, x: str) -> int:  # E: Missing return statement\n        \"\"\"Some function.\"\"\"\n\nclass B:\n    @classmethod\n    def func1(cls, x: str) -> int: pass  # E: Missing return statement\n    @classmethod\n    def func2(cls, x: str) -> int: ...  # E: Missing return statement\n    @classmethod\n    def func3(cls, x: str) -> int:  # E: Missing return statement\n        \"\"\"Some function.\"\"\"\n\nclass C:\n    @overload\n    def func4(self, x: int) -> int: ...\n    @overload\n    def func4(self, x: str) -> str: ...\n    def func4(self, x: Union[int, str]) -> Union[int, str]:  # E: Missing return statement\n        pass\n\n    @overload\n    def func5(self, x: int) -> int: ...\n    @overload\n    def func5(self, x: str) -> str: ...\n    def func5(self, x: Union[int, str]) -> Union[int, str]:  # E: Missing return statement\n        \"\"\"Some function.\"\"\"\n[builtins fixtures/classmethod.pyi]\n\n[case testEmptyBodyProhibitedPropertyNonAbstract]\nclass A:\n    @property\n    def x(self) -> int: ...  # E: Missing return statement\n    @property\n    def y(self) -> int: ...  # E: Missing return statement\n    @y.setter\n    def y(self, value: int) -> None: ...\n\nclass B:\n    @property\n    def x(self) -> int: pass  # E: Missing return statement\n    @property\n    def y(self) -> int: pass  # E: Missing return statement\n    @y.setter\n    def y(self, value: int) -> None: pass\n\nclass C:\n    @property\n    def x(self) -> int:  # E: Missing return statement\n       \"\"\"Some property.\"\"\"\n    @property\n    def y(self) -> int:  # E: Missing return statement\n        \"\"\"Some property.\"\"\"\n    @y.setter\n    def y(self, value: int) -> None: pass\n[builtins fixtures/property.pyi]\n\n[case testEmptyBodyNoteABCMeta]\nfrom abc import ABC\n\nclass A(ABC):\n    def foo(self) -> int:  # E: Missing return statement \\\n                           # N: If the method is meant to be abstract, use @abc.abstractmethod\n        ...\n\n[case testEmptyBodyAllowedFunctionStub]\nimport stub\n[file stub.pyi]\nfrom typing import overload, Union\n\ndef func1(x: str) -> int: pass\ndef func2(x: str) -> int: ...\ndef func3(x: str) -> int:\n    \"\"\"Some function.\"\"\"\n\n[case testEmptyBodyAllowedMethodNonAbstractStub]\nimport stub\n[file stub.pyi]\nfrom typing import overload, Union\n\nclass A:\n    def func1(self, x: str) -> int: pass\n    def func2(self, x: str) -> int: ...\n    def func3(self, x: str) -> int:\n        \"\"\"Some function.\"\"\"\n\nclass B:\n    @classmethod\n    def func1(cls, x: str) -> int: pass\n    @classmethod\n    def func2(cls, x: str) -> int: ...\n    @classmethod\n    def func3(cls, x: str) -> int:\n        \"\"\"Some function.\"\"\"\n[builtins fixtures/classmethod.pyi]\n\n[case testEmptyBodyAllowedPropertyNonAbstractStub]\nimport stub\n[file stub.pyi]\nclass A:\n    @property\n    def x(self) -> int: ...\n    @property\n    def y(self) -> int: ...\n    @y.setter\n    def y(self, value: int) -> None: ...\n\nclass B:\n    @property\n    def x(self) -> int: pass\n    @property\n    def y(self) -> int: pass\n    @y.setter\n    def y(self, value: int) -> None: pass\n\nclass C:\n    @property\n    def x(self) -> int:\n       \"\"\"Some property.\"\"\"\n    @property\n    def y(self) -> int:\n        \"\"\"Some property.\"\"\"\n    @y.setter\n    def y(self, value: int) -> None: pass\n[builtins fixtures/property.pyi]\n\n[case testEmptyBodyAllowedMethodAbstract]\nfrom typing import overload, Union\nfrom abc import abstractmethod\n\nclass A:\n    @abstractmethod\n    def func1(self, x: str) -> int: pass\n    @abstractmethod\n    def func2(self, x: str) -> int: ...\n    @abstractmethod\n    def func3(self, x: str) -> int:\n        \"\"\"Some function.\"\"\"\n\nclass B:\n    @classmethod\n    @abstractmethod\n    def func1(cls, x: str) -> int: pass\n    @classmethod\n    @abstractmethod\n    def func2(cls, x: str) -> int: ...\n    @classmethod\n    @abstractmethod\n    def func3(cls, x: str) -> int:\n        \"\"\"Some function.\"\"\"\n\nclass C:\n    @overload\n    @abstractmethod\n    def func4(self, x: int) -> int: ...\n    @overload\n    @abstractmethod\n    def func4(self, x: str) -> str: ...\n    @abstractmethod\n    def func4(self, x: Union[int, str]) -> Union[int, str]:\n        pass\n\n    @overload\n    @abstractmethod\n    def func5(self, x: int) -> int: ...\n    @overload\n    @abstractmethod\n    def func5(self, x: str) -> str: ...\n    @abstractmethod\n    def func5(self, x: Union[int, str]) -> Union[int, str]:\n        \"\"\"Some function.\"\"\"\n[builtins fixtures/classmethod.pyi]\n\n[case testEmptyBodyAllowedPropertyAbstract]\nfrom abc import abstractmethod\nclass A:\n    @property\n    @abstractmethod\n    def x(self) -> int: ...\n    @property\n    @abstractmethod\n    def y(self) -> int: ...\n    @y.setter\n    @abstractmethod\n    def y(self, value: int) -> None: ...\n\nclass B:\n    @property\n    @abstractmethod\n    def x(self) -> int: pass\n    @property\n    @abstractmethod\n    def y(self) -> int: pass\n    @y.setter\n    @abstractmethod\n    def y(self, value: int) -> None: pass\n\nclass C:\n    @property\n    @abstractmethod\n    def x(self) -> int:\n       \"\"\"Some property.\"\"\"\n    @property\n    @abstractmethod\n    def y(self) -> int:\n        \"\"\"Some property.\"\"\"\n    @y.setter\n    @abstractmethod\n    def y(self, value: int) -> None: pass\n[builtins fixtures/property.pyi]\n\n[case testEmptyBodyImplicitlyAbstractProtocol]\nfrom typing import Protocol, overload, Union\n\nclass P1(Protocol):\n    def meth(self) -> int: ...\nclass B1(P1): ...\nclass C1(P1):\n    def meth(self) -> int:\n        return 0\nB1()  # E: Cannot instantiate abstract class \"B1\" with abstract attribute \"meth\"\nC1()\n\nclass P2(Protocol):\n    @classmethod\n    def meth(cls) -> int: ...\nclass B2(P2): ...\nclass C2(P2):\n    @classmethod\n    def meth(cls) -> int:\n        return 0\nB2()  # E: Cannot instantiate abstract class \"B2\" with abstract attribute \"meth\"\nC2()\n\nclass P3(Protocol):\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\nclass B3(P3): ...\nclass C3(P3):\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n    def meth(self, x: Union[int, str]) -> Union[int, str]:\n        return 0\nB3()  # E: Cannot instantiate abstract class \"B3\" with abstract attribute \"meth\"\nC3()\n[builtins fixtures/classmethod.pyi]\n\n[case testEmptyBodyImplicitlyAbstractProtocolProperty]\nfrom typing import Protocol\n\nclass P1(Protocol):\n    @property\n    def attr(self) -> int: ...\nclass B1(P1): ...\nclass C1(P1):\n    @property\n    def attr(self) -> int:\n        return 0\nB1()  # E: Cannot instantiate abstract class \"B1\" with abstract attribute \"attr\"\nC1()\n\nclass P2(Protocol):\n    @property\n    def attr(self) -> int: ...\n    @attr.setter\n    def attr(self, value: int) -> None: ...\nclass B2(P2): ...\nclass C2(P2):\n    @property\n    def attr(self) -> int: return 0\n    @attr.setter\n    def attr(self, value: int) -> None: pass\nB2()  # E: Cannot instantiate abstract class \"B2\" with abstract attribute \"attr\"\nC2()\n[builtins fixtures/property.pyi]\n\n[case testEmptyBodyImplicitlyAbstractProtocolStub]\nfrom stub import P1, P2, P3, P4\n\nclass B1(P1): ...\nclass B2(P2): ...\nclass B3(P3): ...\nclass B4(P4): ...\n\nB1()\nB2()\nB3()\nB4()  # E: Cannot instantiate abstract class \"B4\" with abstract attribute \"meth\"\n\n[file stub.pyi]\nfrom typing import Protocol, overload, Union\nfrom abc import abstractmethod\n\nclass P1(Protocol):\n    def meth(self) -> int: ...\n\nclass P2(Protocol):\n    @classmethod\n    def meth(cls) -> int: ...\n\nclass P3(Protocol):\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n\nclass P4(Protocol):\n    @abstractmethod\n    def meth(self) -> int: ...\n[builtins fixtures/classmethod.pyi]\n\n[case testEmptyBodyUnsafeAbstractSuper]\nfrom stub import StubProto, StubAbstract\nfrom typing import Protocol\nfrom abc import abstractmethod\n\nclass Proto(Protocol):\n    def meth(self) -> int: ...\nclass ProtoDef(Protocol):\n    def meth(self) -> int: return 0\n\nclass Abstract:\n    @abstractmethod\n    def meth(self) -> int: ...\nclass AbstractDef:\n    @abstractmethod\n    def meth(self) -> int: return 0\n\nclass SubProto(Proto):\n    def meth(self) -> int:\n        return super().meth()  # E: Call to abstract method \"meth\" of \"Proto\" with trivial body via super() is unsafe\nclass SubProtoDef(ProtoDef):\n    def meth(self) -> int:\n        return super().meth()\n\nclass SubAbstract(Abstract):\n    def meth(self) -> int:\n        return super().meth()  # E: Call to abstract method \"meth\" of \"Abstract\" with trivial body via super() is unsafe\nclass SubAbstractDef(AbstractDef):\n    def meth(self) -> int:\n        return super().meth()\n\nclass SubStubProto(StubProto):\n    def meth(self) -> int:\n        return super().meth()\nclass SubStubAbstract(StubAbstract):\n    def meth(self) -> int:\n        return super().meth()\n\n[file stub.pyi]\nfrom typing import Protocol\nfrom abc import abstractmethod\n\nclass StubProto(Protocol):\n    def meth(self) -> int: ...\nclass StubAbstract:\n    @abstractmethod\n    def meth(self) -> int: ...\n\n[case testEmptyBodyUnsafeAbstractSuperProperty]\nfrom stub import StubProto, StubAbstract\nfrom typing import Protocol\nfrom abc import abstractmethod\n\nclass Proto(Protocol):\n    @property\n    def attr(self) -> int: ...\nclass SubProto(Proto):\n    @property\n    def attr(self) -> int: return super().attr  # E: Call to abstract method \"attr\" of \"Proto\" with trivial body via super() is unsafe\n\nclass ProtoDef(Protocol):\n    @property\n    def attr(self) -> int: return 0\nclass SubProtoDef(ProtoDef):\n    @property\n    def attr(self) -> int: return super().attr\n\nclass Abstract:\n    @property\n    @abstractmethod\n    def attr(self) -> int: ...\nclass SubAbstract(Abstract):\n    @property\n    @abstractmethod\n    def attr(self) -> int: return super().attr # E: Call to abstract method \"attr\" of \"Abstract\" with trivial body via super() is unsafe\n\nclass AbstractDef:\n    @property\n    @abstractmethod\n    def attr(self) -> int: return 0\nclass SubAbstractDef(AbstractDef):\n    @property\n    @abstractmethod\n    def attr(self) -> int: return super().attr\n\nclass SubStubProto(StubProto):\n    @property\n    def attr(self) -> int: return super().attr\nclass SubStubAbstract(StubAbstract):\n    @property\n    def attr(self) -> int: return super().attr\n\n[file stub.pyi]\nfrom typing import Protocol\nfrom abc import abstractmethod\n\nclass StubProto(Protocol):\n    @property\n    def attr(self) -> int: ...\nclass StubAbstract:\n    @property\n    @abstractmethod\n    def attr(self) -> int: ...\n[builtins fixtures/property.pyi]\n\n[case testEmptyBodyUnsafeAbstractSuperOverloads]\nfrom stub import StubProto\nfrom typing import Protocol, overload, Union\n\nclass ProtoEmptyImpl(Protocol):\n    @overload\n    def meth(self, x: str) -> str: ...\n    @overload\n    def meth(self, x: int) -> int: ...\n    def meth(self, x: Union[int, str]) -> Union[int, str]:\n        raise NotImplementedError\nclass ProtoDefImpl(Protocol):\n    @overload\n    def meth(self, x: str) -> str: ...\n    @overload\n    def meth(self, x: int) -> int: ...\n    def meth(self, x: Union[int, str]) -> Union[int, str]:\n        return 0\nclass ProtoNoImpl(Protocol):\n    @overload\n    def meth(self, x: str) -> str: ...\n    @overload\n    def meth(self, x: int) -> int: ...\n\nclass SubProtoEmptyImpl(ProtoEmptyImpl):\n    @overload\n    def meth(self, x: str) -> str: ...\n    @overload\n    def meth(self, x: int) -> int: ...\n    def meth(self, x: Union[int, str]) -> Union[int, str]:\n        return super().meth(0)  # E: Call to abstract method \"meth\" of \"ProtoEmptyImpl\" with trivial body via super() is unsafe\nclass SubProtoDefImpl(ProtoDefImpl):\n    @overload\n    def meth(self, x: str) -> str: ...\n    @overload\n    def meth(self, x: int) -> int: ...\n    def meth(self, x: Union[int, str]) -> Union[int, str]:\n        return super().meth(0)\nclass SubStubProto(StubProto):\n    @overload\n    def meth(self, x: str) -> str: ...\n    @overload\n    def meth(self, x: int) -> int: ...\n    def meth(self, x: Union[int, str]) -> Union[int, str]:\n        return super().meth(0)\n\n# TODO: it would be good to also give an error in this case.\nclass SubProtoNoImpl(ProtoNoImpl):\n    @overload\n    def meth(self, x: str) -> str: ...\n    @overload\n    def meth(self, x: int) -> int: ...\n    def meth(self, x: Union[int, str]) -> Union[int, str]:\n        return super().meth(0)\n\n[file stub.pyi]\nfrom typing import Protocol, overload\n\nclass StubProto(Protocol):\n    @overload\n    def meth(self, x: str) -> str: ...\n    @overload\n    def meth(self, x: int) -> int: ...\n\n[builtins fixtures/exception.pyi]\n\n[case testEmptyBodyNoSuperWarningWithoutStrict]\n# flags: --no-strict-optional\nfrom typing import Protocol\nfrom abc import abstractmethod\n\nclass Proto(Protocol):\n    def meth(self) -> int: ...\nclass Abstract:\n    @abstractmethod\n    def meth(self) -> int: ...\n\nclass SubProto(Proto):\n    def meth(self) -> int:\n        return super().meth()  # E: Call to abstract method \"meth\" of \"Proto\" with trivial body via super() is unsafe\nclass SubAbstract(Abstract):\n    def meth(self) -> int:\n        return super().meth()  # E: Call to abstract method \"meth\" of \"Abstract\" with trivial body via super() is unsafe\n\n[case testEmptyBodyNoSuperWarningOptionalReturn]\nfrom typing import Protocol, Optional\nfrom abc import abstractmethod\n\nclass Proto(Protocol):\n    def meth(self) -> Optional[int]: pass\nclass Abstract:\n    @abstractmethod\n    def meth(self) -> Optional[int]: pass\n\nclass SubProto(Proto):\n    def meth(self) -> Optional[int]:\n        return super().meth()  # E: Call to abstract method \"meth\" of \"Proto\" with trivial body via super() is unsafe\nclass SubAbstract(Abstract):\n    def meth(self) -> Optional[int]:\n        return super().meth()  # E: Call to abstract method \"meth\" of \"Abstract\" with trivial body via super() is unsafe\n\n[case testEmptyBodyTypeCheckingOnly]\nfrom typing import TYPE_CHECKING\n\nclass C:\n    if TYPE_CHECKING:\n        def dynamic(self) -> int: ...  # OK\n"
  },
  {
    "path": "test-data/unit/check-annotated.test",
    "content": "[case testAnnotated0]\nfrom typing_extensions import Annotated\nx: Annotated[int, ...]\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotated1]\nfrom typing import Union\nfrom typing_extensions import Annotated\nx: Annotated[Union[int, str], ...]\nreveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotated2]\nfrom typing_extensions import Annotated\nx: Annotated[int, THESE, ARE, IGNORED, FOR, NOW]\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotated3_no_native_parse]\nfrom typing_extensions import Annotated\nx: Annotated[int, -+~12.3, \"som\"[e], more(anno+a+ions, that=[are]), (b\"ignored\",), 4, N.O.W, ...]\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedBadType]\nfrom typing_extensions import Annotated\nx: Annotated[XXX, ...]  # E: Name \"XXX\" is not defined\nreveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedBadNoArgs]\nfrom typing_extensions import Annotated\nx: Annotated  # E: Annotated[...] must have exactly one type argument and at least one annotation\nreveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedBadOneArg]\nfrom typing_extensions import Annotated\nx: Annotated[int]  # E: Annotated[...] must have exactly one type argument and at least one annotation\nreveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedNested0]\nfrom typing_extensions import Annotated\nx: Annotated[Annotated[int, ...], ...]\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedNested1]\nfrom typing import Union\nfrom typing_extensions import Annotated\nx: Annotated[Annotated[Union[int, str], ...], ...]\nreveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedNestedBadType]\nfrom typing_extensions import Annotated\nx: Annotated[Annotated[XXX, ...], ...]  # E: Name \"XXX\" is not defined\nreveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedNestedBadNoArgs]\nfrom typing_extensions import Annotated\nx: Annotated[Annotated, ...]  # E: Annotated[...] must have exactly one type argument and at least one annotation\nreveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedNestedBadOneArg]\nfrom typing_extensions import Annotated\nx: Annotated[Annotated[int], ...]  # E: Annotated[...] must have exactly one type argument and at least one annotation\nreveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedNoImport]\nx: Annotated[int, ...]  # E: Name \"Annotated\" is not defined\nreveal_type(x)  # N: Revealed type is \"Any\"\n\n[case testAnnotatedDifferentName]\nfrom typing_extensions import Annotated as An\nx: An[int, ...]\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedAliasSimple]\nfrom typing import Tuple\nfrom typing_extensions import Annotated\nAlias = Annotated[Tuple[int, ...], ...]\nx: Alias\nreveal_type(x)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedAliasTypeVar]\nfrom typing import TypeVar\nfrom typing_extensions import Annotated\nT = TypeVar('T')\nAlias = Annotated[T, ...]\nx: Alias[int]\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedAliasGenericTuple]\nfrom typing import TypeVar, Tuple\nfrom typing_extensions import Annotated\nT = TypeVar('T')\nAlias = Annotated[Tuple[T, T], ...]\nx: Alias[int]\nreveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedAliasGenericUnion]\nfrom typing import TypeVar, Union\nfrom typing_extensions import Annotated\nT = TypeVar('T')\nAlias = Annotated[Union[T, str], ...]\nx: Alias[int]\nreveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedSecondParamNonType]\nfrom typing_extensions import Annotated\n\nclass Meta:\n    ...\n\nx = Annotated[int, Meta()]\nreveal_type(x)  # N: Revealed type is \"def () -> builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testAnnotatedStringLiteralInFunc]\nfrom typing import TypeVar\nfrom typing_extensions import Annotated\ndef f1(a: Annotated[str, \"metadata\"]):\n    pass\nreveal_type(f1)  # N: Revealed type is \"def (a: builtins.str) -> Any\"\ndef f2(a: Annotated[\"str\", \"metadata\"]):\n    pass\nreveal_type(f2)  # N: Revealed type is \"def (a: builtins.str) -> Any\"\ndef f3(a: Annotated[\"notdefined\", \"metadata\"]): # E: Name \"notdefined\" is not defined\n    pass\nT = TypeVar('T')\ndef f4(a: Annotated[T, \"metadata\"]):\n    pass\nreveal_type(f4)  # N: Revealed type is \"def [T] (a: T`-1) -> Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testSliceAnnotated]\nfrom typing_extensions import Annotated\na: Annotated[int, 1:2]\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-assert-type-fail.test",
    "content": "[case testAssertTypeFail1]\nimport typing\nimport array as arr\nclass array:\n    pass\ndef f(si: arr.array[int]):\n    typing.assert_type(si, array) # E: Expression is of type \"array.array[int]\", not \"__main__.array\"\n[builtins fixtures/tuple.pyi]\n\n[case testAssertTypeFail2]\nimport typing\nimport array as arr\nclass array:\n    class array:\n        i = 1\ndef f(si: arr.array[int]):\n    typing.assert_type(si, array.array) # E: Expression is of type \"array.array[int]\", not \"__main__.array.array\"\n[builtins fixtures/tuple.pyi]\n\n[case testAssertTypeFail3]\nimport typing\nimport array as arr\nclass array:\n    class array:\n        i = 1\ndef f(si: arr.array[int]):\n    typing.assert_type(si, int) # E: Expression is of type \"array[int]\", not \"int\"\n[builtins fixtures/tuple.pyi]\n\n[case testAssertTypeFailCallableArgKind]\nfrom typing import assert_type, Callable\ndef myfunc(arg: int) -> None: pass\nassert_type(myfunc, Callable[[int], None])  # E: Expression is of type \"def myfunc(arg: int) -> None\", not \"Callable[[int], None]\"\n\n[case testAssertTypeOverload]\nfrom typing import assert_type, overload\n\nclass Foo:\n    @overload\n    def __new__(cls, x: int) -> Foo: ...\n    @overload\n    def __new__(cls, x: str) -> Foo: ...\n    def __new__(cls, x: \"int | str\") -> Foo:\n        return cls(0)\n\nassert_type(Foo, type[Foo])\nA = Foo\nassert_type(A, type[Foo])\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-async-await.test",
    "content": "-- Tests for async def and await (PEP 492)\n-- ---------------------------------------\n\n[case testAsyncDefPass]\n\nasync def f() -> int:\n    pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncDefReturn]\n\nasync def f() -> int:\n    return 0\n_ = reveal_type(f())  # N: Revealed type is \"typing.Coroutine[Any, Any, builtins.int]\"\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncDefMissingReturn]\n# flags: --warn-no-return\nasync def f() -> int:\n    make_this_not_trivial = 1\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\nmain:2: error: Missing return statement\n\n[case testAsyncDefReturnWithoutValue]\n\nasync def f() -> int:\n    make_this_not_trivial = 1\n    return\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\nmain:4: error: Return value expected\n\n[case testAwaitCoroutine]\n\nasync def f() -> int:\n    x = await f()\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    return x\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\n\n[case testAwaitDefaultContext]\n\nfrom typing import TypeVar\nT = TypeVar('T')\nasync def f(x: T) -> T:\n    y = await f(x)\n    reveal_type(y)\n    return y\n[typing fixtures/typing-async.pyi]\n[out]\nmain:6: note: Revealed type is \"T`-1\"\n\n[case testAwaitAnyContext]\n\nfrom typing import Any, TypeVar\nT = TypeVar('T')\nasync def f(x: T) -> T:\n    y = await f(x)  # type: Any\n    reveal_type(y)\n    return y\n[typing fixtures/typing-async.pyi]\n[out]\nmain:6: note: Revealed type is \"Any\"\n\n[case testAwaitExplicitContext]\n\nfrom typing import TypeVar\nT = TypeVar('T')\nasync def f(x: T) -> T:\n    y = await f(x)  # type: int\n    reveal_type(y)\n    return x\n[typing fixtures/typing-async.pyi]\n[out]\nmain:5: error: Argument 1 to \"f\" has incompatible type \"T\"; expected \"int\"\nmain:6: note: Revealed type is \"builtins.int\"\n\n[case testAwaitGeneratorError]\n\nfrom typing import Any, Generator\ndef g() -> Generator[int, None, str]:\n    yield 0\n    return ''\nasync def f() -> int:\n    x = await g()\n    return x\n[typing fixtures/typing-async.pyi]\n[out]\nmain:7: error: Incompatible types in \"await\" (actual type \"Generator[int, None, str]\", expected type \"Awaitable[Any]\")\n\n[case testAwaitIteratorError]\n\nfrom typing import Any, Iterator\ndef g() -> Iterator[Any]:\n    yield\nasync def f() -> int:\n    x = await g()\n    return x\n[typing fixtures/typing-async.pyi]\n[out]\nmain:6: error: Incompatible types in \"await\" (actual type \"Iterator[Any]\", expected type \"Awaitable[Any]\")\n\n[case testAwaitArgumentError]\n\ndef g() -> int:\n    return 0\nasync def f() -> int:\n    x = await g()\n    return x\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\nmain:5: error: Incompatible types in \"await\" (actual type \"int\", expected type \"Awaitable[Any]\")\n\n[case testAwaitResultError]\n\nasync def g() -> int:\n    return 0\nasync def f() -> str:\n    x = await g()  # type: str\n    return x\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\nmain:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAwaitReturnError]\n\nasync def g() -> int:\n    return 0\nasync def f() -> str:\n    x = await g()\n    return x\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\nmain:6: error: Incompatible return value type (got \"int\", expected \"str\")\n\n[case testAsyncFor]\n\nfrom typing import AsyncIterator\nclass C(AsyncIterator[int]):\n    async def __anext__(self) -> int: return 0\nasync def f() -> None:\n    async for x in C():\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncForError]\n\nfrom typing import AsyncIterator\nasync def f() -> None:\n    async for x in [1]:\n        pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\nmain:4: error: \"list[int]\" has no attribute \"__aiter__\" (not async iterable)\n\n[case testAsyncForErrorNote]\n\nfrom typing import AsyncIterator, AsyncGenerator\nasync def g() -> AsyncGenerator[str, None]:\n    pass\n\nasync def f() -> None:\n    async for x in g():\n        pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\nmain:7: error: \"Coroutine[Any, Any, AsyncGenerator[str, None]]\" has no attribute \"__aiter__\" (not async iterable)\nmain:7: note: Maybe you forgot to use \"await\"?\n\n[case testAsyncForErrorCanBeIgnored]\n\nfrom typing import AsyncIterator, AsyncGenerator\nasync def g() -> AsyncGenerator[str, None]:\n    pass\n\nasync def f() -> None:\n    async for x in g():  # type: ignore[attr-defined]\n        pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncForTypeComments_no_native_parse]\n\nfrom typing import AsyncIterator, Union\nclass C(AsyncIterator[int]):\n    async def __anext__(self) -> int: return 0\nasync def f() -> None:\n    async for x in C():  # type: str  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        pass\n\n    async for y in C():  # type: int\n        pass\n\n    async for z in C():  # type: Union[int, str]\n        reveal_type(z)  # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncForComprehension]\nfrom typing import Generic, Iterable, TypeVar, AsyncIterator, Tuple\n\nT = TypeVar('T')\n\nclass asyncify(Generic[T], AsyncIterator[T]):\n    def __init__(self, iterable: Iterable[T]) -> None:\n        self.iterable = iter(iterable)\n    def __aiter__(self) -> AsyncIterator[T]:\n        return self\n    async def __anext__(self) -> T:\n        try:\n            return next(self.iterable)\n        except StopIteration:\n            raise StopAsyncIteration\n\nasync def listcomp(obj: Iterable[int]):\n    lst = [i async for i in asyncify(obj)]\n    reveal_type(lst)  # N: Revealed type is \"builtins.list[builtins.int]\"\n    lst2 = [i async for i in asyncify(obj) for j in obj]\n    reveal_type(lst2)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nasync def setcomp(obj: Iterable[int]):\n    lst = {i async for i in asyncify(obj)}\n    reveal_type(lst)  # N: Revealed type is \"builtins.set[builtins.int]\"\n\nasync def dictcomp(obj: Iterable[Tuple[int, str]]):\n    lst = {i: j async for i, j in asyncify(obj)}\n    reveal_type(lst)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n\nasync def generatorexp(obj: Iterable[int]):\n    lst = (i async for i in asyncify(obj))\n    reveal_type(lst)  # N: Revealed type is \"typing.AsyncGenerator[builtins.int, None]\"\n    lst2 = (i async for i in asyncify(obj) for i in obj)\n    reveal_type(lst2)  # N: Revealed type is \"typing.AsyncGenerator[builtins.int, None]\"\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncForComprehensionErrors]\nfrom typing import Generic, Iterable, TypeVar, AsyncIterator, Tuple\n\nT = TypeVar('T')\n\nclass asyncify(Generic[T], AsyncIterator[T]):\n    def __init__(self, iterable: Iterable[T]) -> None:\n        self.iterable = iter(iterable)\n    def __aiter__(self) -> AsyncIterator[T]:\n        return self\n    async def __anext__(self) -> T:\n        try:\n            return next(self.iterable)\n        except StopIteration:\n            raise StopAsyncIteration\n\nasync def wrong_iterable(obj: Iterable[int]):\n    [i async for i in obj]  # E: \"Iterable[int]\" has no attribute \"__aiter__\" (not async iterable)\n    [i for i in asyncify(obj)]  # E: \"asyncify[int]\" has no attribute \"__iter__\"; maybe \"__aiter__\"? (not iterable)\n    {i: i async for i in obj}  # E: \"Iterable[int]\" has no attribute \"__aiter__\" (not async iterable)\n    {i: i for i in asyncify(obj)}  # E: \"asyncify[int]\" has no attribute \"__iter__\"; maybe \"__aiter__\"? (not iterable)\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncWith]\n\nclass C:\n    async def __aenter__(self) -> int: pass\n    async def __aexit__(self, x, y, z) -> None: pass\nasync def f() -> None:\n    async with C() as x:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n\n[case testAsyncWithError]\n\nclass C:\n    def __enter__(self) -> int: pass\n    def __exit__(self, x, y, z) -> None: pass\nasync def f() -> None:\n    async with C() as x:\n        pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\nmain:6: error: \"C\" has no attribute \"__aenter__\"; maybe \"__enter__\"?\nmain:6: error: \"C\" has no attribute \"__aexit__\"; maybe \"__exit__\"?\n\n[case testAsyncWithErrorBadAenter]\n\nclass C:\n    def __aenter__(self) -> int: pass\n    async def __aexit__(self, x, y, z) -> None: pass\nasync def f() -> None:\n    async with C() as x:  # E: Incompatible types in \"async with\" for \"__aenter__\" (actual type \"int\", expected type \"Awaitable[Any]\")\n        pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncWithErrorBadAenter2]\n# flags: --no-strict-optional\nclass C:\n    def __aenter__(self) -> None: pass\n    async def __aexit__(self, x, y, z) -> None: pass\nasync def f() -> None:\n    async with C() as x:  # E: \"None\" has no attribute \"__await__\"\n        pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncWithErrorBadAexit]\n\nclass C:\n    async def __aenter__(self) -> int: pass\n    def __aexit__(self, x, y, z) -> int: pass\nasync def f() -> None:\n    async with C() as x: # E: Incompatible types in \"async with\" for \"__aexit__\" (actual type \"int\", expected type \"Awaitable[Any]\")\n        pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncWithErrorBadAexit2]\n# flags: --no-strict-optional\nclass C:\n    async def __aenter__(self) -> int: pass\n    def __aexit__(self, x, y, z) -> None: pass\nasync def f() -> None:\n    async with C() as x: # E: \"None\" has no attribute \"__await__\"\n        pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncWithTypeComments_no_native_parse]\n\nclass C:\n    async def __aenter__(self) -> int: pass\n    async def __aexit__(self, x, y, z) -> None: pass\nasync def f() -> None:\n    async with C() as x:  # type: int\n        pass\n\n    async with C() as y, C() as z:  # type: str, int  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        pass\n\n    async with C() as a:  # type: int, int  # E: Syntax error in type annotation # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\n        pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testNoYieldFromInAsyncDef]\n\nasync def f():\n    yield from []\nasync def g():\n    x = yield from []\n[builtins fixtures/async_await.pyi]\n[out]\nmain:3: error: \"yield from\" in async function\nmain:5: error: \"yield from\" in async function\n\n[case testYieldFromNoAwaitable]\n\nfrom typing import Any, Generator\nasync def f() -> str:\n    return ''\ndef g() -> Generator[Any, None, str]:\n    x = yield from f()\n    return x\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\nmain:6: error: \"yield from\" can't be applied to \"Coroutine[Any, Any, str]\"\n\n[case testAwaitableSubclass]\n\nfrom typing import Any, AsyncIterator, Awaitable, Generator\nclass A(Awaitable[int]):\n    def __await__(self) -> Generator[Any, None, int]:\n        yield\n        return 0\nclass C:\n    def __aenter__(self) -> A:\n        return A()\n    def __aexit__(self, *a) -> A:\n        return A()\nclass I(AsyncIterator[int]):\n    def __aiter__(self) -> 'I':\n        return self\n    def __anext__(self) -> A:\n        return A()\nasync def main() -> None:\n    x = await A()\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    async with C() as y:\n        reveal_type(y)  # N: Revealed type is \"builtins.int\"\n    async for z in I():\n        reveal_type(z)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testYieldTypeCheckInDecoratedCoroutine]\n\nfrom typing import Generator\nfrom types import coroutine\n@coroutine\ndef f() -> Generator[int, str, int]:\n    x = yield 0\n    x = yield ''  # E: Incompatible types in \"yield\" (actual type \"str\", expected type \"int\")\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    if x:\n        return 0\n    else:\n        return ''  # E: Incompatible return value type (got \"str\", expected \"int\")\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n-- Async generators (PEP 525), some test cases adapted from the PEP text\n-- ---------------------------------------------------------------------\n\n[case testAsyncGenerator]\nfrom typing import AsyncGenerator, Generator\n\nasync def f() -> int:\n    return 42\n\nasync def g() -> AsyncGenerator[int, None]:\n    value = await f()\n    reveal_type(value)  # N: Revealed type is \"builtins.int\"\n    yield value\n\n    yield 'not an int'  # E: Incompatible types in \"yield\" (actual type \"str\", expected type \"int\")\n    # return without a value is fine\n    return\nreveal_type(g)  # N: Revealed type is \"def () -> typing.AsyncGenerator[builtins.int, None]\"\nreveal_type(g())  # N: Revealed type is \"typing.AsyncGenerator[builtins.int, None]\"\n\nasync def h() -> None:\n    async for item in g():\n        reveal_type(item)  # N: Revealed type is \"builtins.int\"\n\nasync def wrong_return() -> Generator[int, None, None]:  # E: The return type of an async generator function should be \"AsyncGenerator\" or one of its supertypes\n    yield 3\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncGeneratorReturnIterator]\nfrom typing import AsyncIterator\n\nasync def gen() -> AsyncIterator[int]:\n    yield 3\n\n    yield 'not an int'  # E: Incompatible types in \"yield\" (actual type \"str\", expected type \"int\")\n\nasync def use_gen() -> None:\n    async for item in gen():\n        reveal_type(item)  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncGeneratorManualIter]\nfrom typing import AsyncGenerator\n\nasync def genfunc() -> AsyncGenerator[int, None]:\n    yield 1\n    yield 2\n\nasync def user() -> None:\n    gen = genfunc()\n\n    reveal_type(gen.__aiter__())  # N: Revealed type is \"typing.AsyncGenerator[builtins.int, None]\"\n\n    reveal_type(await gen.__anext__())  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncGeneratorAsend]\nfrom typing import AsyncGenerator\n\nasync def f() -> None:\n    pass\n\nasync def gen() -> AsyncGenerator[int, str]:\n    await f()\n    v = yield 42\n    reveal_type(v)  # N: Revealed type is \"builtins.str\"\n    await f()\n\nasync def h() -> None:\n    g = gen()\n    await g.asend(())  # E: Argument 1 to \"asend\" of \"AsyncGenerator\" has incompatible type \"tuple[()]\"; expected \"str\"\n    reveal_type(await g.asend('hello'))  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncGeneratorAthrow]\nfrom typing import AsyncGenerator\n\nasync def gen() -> AsyncGenerator[str, int]:\n    try:\n        yield 'hello'\n    except BaseException:\n        yield 'world'\n\nasync def h() -> None:\n    g = gen()\n    v = await g.asend(1)\n    reveal_type(v)  # N: Revealed type is \"builtins.str\"\n    reveal_type(await g.athrow(BaseException))  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncGeneratorNoSyncIteration]\nfrom typing import AsyncGenerator\n\nasync def gen() -> AsyncGenerator[int, None]:\n    for i in [1, 2, 3]:\n        yield i\n\ndef h() -> None:\n    for i in gen():  # E: \"AsyncGenerator[int, None]\" has no attribute \"__iter__\"; maybe \"__aiter__\"? (not iterable)\n        pass\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncGeneratorNoYieldFrom]\nfrom typing import AsyncGenerator\n\nasync def f() -> AsyncGenerator[int, None]:\n    pass\n\nasync def gen() -> AsyncGenerator[int, None]:\n    yield from f()  # E: \"yield from\" in async function\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncGeneratorNoReturnWithValue]\nfrom typing import AsyncGenerator\n\nasync def return_int() -> AsyncGenerator[int, None]:\n    yield 1\n    return 42  # E: \"return\" with value in async generator is not allowed\n\nasync def return_none() -> AsyncGenerator[int, None]:\n    yield 1\n    return None  # E: \"return\" with value in async generator is not allowed\n\ndef f() -> None:\n    return\n\nasync def return_f() -> AsyncGenerator[int, None]:\n    yield 1\n    return f()  # E: \"return\" with value in async generator is not allowed\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testImplicitAsyncGenerator]\nfrom typing import List\n\nasync def get_list() -> List[int]:\n    return [1]\n\nasync def predicate() -> bool:\n    return True\n\nasync def test_implicit_generators() -> None:\n    reveal_type(await predicate() for _ in [1])  # N: Revealed type is \"typing.AsyncGenerator[builtins.bool, None]\"\n    reveal_type(x for x in [1] if await predicate())  # N: Revealed type is \"typing.AsyncGenerator[builtins.int, None]\"\n    reveal_type(x for x in await get_list())  # N: Revealed type is \"typing.Generator[builtins.int, None, None]\"\n    reveal_type(x for _ in [1] for x in await get_list())  # N: Revealed type is \"typing.AsyncGenerator[builtins.int, None]\"\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-async.pyi]\n\n\n-- The full matrix of coroutine compatibility\n-- ------------------------------------------\n\n[case testFullCoroutineMatrix]\n\nfrom typing import Any, AsyncIterator, Awaitable, Generator, Iterator\nfrom types import coroutine\n\n# The various things you might try to use in `await` or `yield from`.\n\ndef plain_generator() -> Generator[str, None, int]:\n    yield 'a'\n    return 1\n\nasync def plain_coroutine() -> int:\n    return 1\n\n@coroutine\ndef decorated_generator() -> Generator[str, None, int]:\n    yield 'a'\n    return 1\n\n@coroutine\nasync def decorated_coroutine() -> int:\n    return 1\n\nclass It(Iterator[str]):\n    def __iter__(self) -> 'It':\n        return self\n    def __next__(self) -> str:\n        return 'a'\n\ndef other_iterator() -> It:\n    return It()\n\nclass Aw(Awaitable[int]):\n    def __await__(self) -> Generator[str, Any, int]:\n        yield 'a'\n        return 1\n\ndef other_coroutine() -> Aw:\n    return Aw()\n\n# The various contexts in which `await` or `yield from` might occur.\n\ndef plain_host_generator() -> Generator[str, None, None]:\n    yield 'a'\n    x = 0\n    x = yield from plain_generator()\n    x = yield from plain_coroutine()  # E: \"yield from\" can't be applied to \"Coroutine[Any, Any, int]\"\n    x = yield from decorated_generator()\n    x = yield from decorated_coroutine()  # E: \"yield from\" can't be applied to \"AwaitableGenerator[Any, Any, int, Coroutine[Any, Any, int]]\"\n    x = yield from other_iterator()\n    x = yield from other_coroutine()  # E: \"yield from\" can't be applied to \"Aw\"\n\nasync def plain_host_coroutine() -> None:\n    x = 0\n    x = await plain_generator()  # E: Incompatible types in \"await\" (actual type \"Generator[str, None, int]\", expected type \"Awaitable[Any]\")\n    x = await plain_coroutine()\n    x = await decorated_generator()\n    x = await decorated_coroutine()\n    x = await other_iterator()  # E: Incompatible types in \"await\" (actual type \"It\", expected type \"Awaitable[Any]\")\n    x = await other_coroutine()\n\n@coroutine\ndef decorated_host_generator() -> Generator[str, None, None]:\n    yield 'a'\n    x = 0\n    x = yield from plain_generator()\n    x = yield from plain_coroutine()\n    x = yield from decorated_generator()\n    x = yield from decorated_coroutine()\n    x = yield from other_iterator()\n    x = yield from other_coroutine()  # E: \"yield from\" can't be applied to \"Aw\"\n\n@coroutine\nasync def decorated_host_coroutine() -> None:\n    x = 0\n    x = await plain_generator()  # E: Incompatible types in \"await\" (actual type \"Generator[str, None, int]\", expected type \"Awaitable[Any]\")\n    x = await plain_coroutine()\n    x = await decorated_generator()\n    x = await decorated_coroutine()\n    x = await other_iterator()  # E: Incompatible types in \"await\" (actual type \"It\", expected type \"Awaitable[Any]\")\n    x = await other_coroutine()\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\n\n[case testAsyncGenDisallowUntyped]\n# flags: --disallow-untyped-defs\n# These should not crash\nfrom typing import AsyncGenerator, Any\n\nasync def f() -> AsyncGenerator[int, None]:\n    yield 0\n\nasync def g() -> AsyncGenerator[Any, None]:\n    yield 0\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\n\n[case testAsyncGenDisallowUntypedTriggers]\n# flags: --disallow-untyped-defs\nfrom typing import AsyncGenerator, Any\n\nasync def f() -> AsyncGenerator[Any, Any]:\n    yield None\n\nasync def h() -> Any:\n    yield 0\n\nasync def g():  # E: Function is missing a return type annotation\n    yield 0\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n[out]\n\n[case testAsyncOverloadedFunction]\nfrom typing import overload\n\n@overload\nasync def f(x: int) -> int: ...\n@overload\nasync def f(x: str) -> str: ...\nasync def f(x):\n    pass\n\nreveal_type(f) # N: Revealed type is \"Overload(def (x: builtins.int) -> typing.Coroutine[Any, Any, builtins.int], def (x: builtins.str) -> typing.Coroutine[Any, Any, builtins.str])\"\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncForwardRefInBody]\n\nasync def f() -> None:\n    forwardref: C\n    class C: pass\n\ndef dec(x): pass\n\n@dec\nasync def g() -> None:\n    forwardref: C\n    class C: pass\n\nreveal_type(f) # N: Revealed type is \"def () -> typing.Coroutine[Any, Any, None]\"\nreveal_type(g) # N: Revealed type is \"Any\"\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncDeferredAnalysis]\n\ndef t() -> None:\n    async def f() -> int:\n        return 1\n\n    def g() -> int:\n        return next(iter(x))\n\n    x = [1]\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncWithInGenericClass]\nfrom typing import Generic, AsyncContextManager, TypeVar\n\nT = TypeVar('T', str, int)\n\nclass Foo(Generic[T]):\n    async def foo(self, manager: AsyncContextManager):\n        async with manager:\n            pass\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAwaitOverloadSpecialCase]\nfrom typing import Any, Awaitable, Iterable, overload, Tuple, List, TypeVar, Generic\n\nT = TypeVar(\"T\")\nFT = TypeVar(\"FT\", bound='Future[Any]')\n\nclass Future(Awaitable[T], Iterable[T]):\n    pass\n\nclass Task(Future[T]):\n    pass\n\n@overload\ndef wait(fs: Iterable[FT]) -> Future[Tuple[List[FT], List[FT]]]: ...  \\\n    # E: Overloaded function signatures 1 and 2 overlap with incompatible return types \\\n    # N: Flipping the order of overloads will fix this error\n@overload\ndef wait(fs: Iterable[Awaitable[T]]) -> Future[Tuple[List[Task[T]], List[Task[T]]]]: ...\ndef wait(fs: Any) -> Any:\n    pass\n\nasync def imprecise1(futures: Iterable[Task[Any]]) -> None:\n    done: Any\n    pending: Any\n    done, pending = await wait(futures)\n    reveal_type(done)  # N: Revealed type is \"Any\"\n\nasync def imprecise2(futures: Iterable[Awaitable[Any]]) -> None:\n    done, pending = await wait(futures)\n    reveal_type(done)  # N: Revealed type is \"builtins.list[__main__.Task[Any]]\"\n\nasync def precise1(futures: Iterable[Future[int]]) -> None:\n    done, pending = await wait(futures)\n    reveal_type(done)  # N: Revealed type is \"builtins.list[__main__.Future[builtins.int]]\"\n\nasync def precise2(futures: Iterable[Awaitable[int]]) -> None:\n    done, pending = await wait(futures)\n    reveal_type(done)  # N: Revealed type is \"builtins.list[__main__.Task[builtins.int]]\"\n\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testUnusedAwaitable]\n# flags: --show-error-codes --enable-error-code unused-awaitable\nfrom typing import Iterable\n\nasync def foo() -> None:\n    pass\n\nclass A:\n    def __await__(self) -> Iterable[int]:\n        yield 5\n\n# Things with __getattr__ should not simply be considered awaitable.\nclass B:\n    def __getattr__(self, attr) -> object:\n        return 0\n\ndef bar() -> None:\n    A()  # E: Value of type \"A\" must be used  [unused-awaitable] \\\n         # N: Are you missing an await?\n    foo()  # E: Value of type \"Coroutine[Any, Any, None]\" must be used  [unused-coroutine] \\\n           # N: Are you missing an await?\n    B()\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncForOutsideCoroutine]\nasync def g():\n    yield 0\n\ndef f() -> None:\n    [x async for x in g()] # E: \"async for\" outside async function\n    {x async for x in g()} # E: \"async for\" outside async function\n    {x: True async for x in g()} # E: \"async for\" outside async function\n    (x async for x in g())\n    async for x in g(): ... # E: \"async for\" outside async function\n\n[x async for x in g()] # E: \"async for\" outside async function\n{x async for x in g()} # E: \"async for\" outside async function\n{x: True async for x in g()} # E: \"async for\" outside async function\n(x async for x in g())\nasync for x in g(): ... # E: \"async for\" outside async function\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncWithOutsideCoroutine]\nclass C:\n    async def __aenter__(self): pass\n    async def __aexit__(self, x, y, z): pass\n\ndef f() -> None:\n    async with C() as x: # E: \"async with\" outside async function\n        pass\n\nasync with C() as x: # E: \"async with\" outside async function\n    pass\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAwaitMissingNote]\nfrom typing import Generic, TypeVar, Generator, Any, Awaitable, Type\n\nclass C:\n    x: int\nclass D(C): ...\n\nasync def foo() -> D: ...\ndef g(x: C) -> None: ...\n\nT = TypeVar(\"T\")\nclass Custom(Generic[T]):\n    def __await__(self) -> Generator[Any, Any, T]: ...\n\nclass Sub(Custom[T]): ...\n\nasync def test(x: Sub[D], tx: Type[Sub[D]]) -> None:\n    foo().x  # E: \"Coroutine[Any, Any, D]\" has no attribute \"x\" \\\n             # N: Maybe you forgot to use \"await\"?\n    (await foo()).x\n    foo().bad  # E: \"Coroutine[Any, Any, D]\" has no attribute \"bad\"\n\n    g(foo())  # E: Argument 1 to \"g\" has incompatible type \"Coroutine[Any, Any, D]\"; expected \"C\" \\\n              # N: Maybe you forgot to use \"await\"?\n    g(await foo())\n    unknown: Awaitable[Any]\n    g(unknown)  # E: Argument 1 to \"g\" has incompatible type \"Awaitable[Any]\"; expected \"C\"\n\n    x.x  # E: \"Sub[D]\" has no attribute \"x\" \\\n         # N: Maybe you forgot to use \"await\"?\n    (await x).x\n    x.bad  # E: \"Sub[D]\" has no attribute \"bad\"\n\n    a: C = x  # E: Incompatible types in assignment (expression has type \"Sub[D]\", variable has type \"C\") \\\n              # N: Maybe you forgot to use \"await\"?\n    b: C = await x\n    unknown2: Awaitable[Any]\n    d: C = unknown2  # E: Incompatible types in assignment (expression has type \"Awaitable[Any]\", variable has type \"C\")\n\n    # The notes are not show for type[...] (because awaiting them will not work)\n    tx.x  # E: \"type[Sub[D]]\" has no attribute \"x\"\n    a2: C = tx  # E: Incompatible types in assignment (expression has type \"type[Sub[D]]\", variable has type \"C\")\n\nclass F:\n    def __await__(self: T) -> Generator[Any, Any, T]: ...\nclass G(F): ...\n\n# This should not crash.\nx: int = G()  # E: Incompatible types in assignment (expression has type \"G\", variable has type \"int\")\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncGeneratorExpressionAwait]\nfrom typing import AsyncGenerator\n\nasync def f() -> AsyncGenerator[int, None]:\n    async def g(x: int) -> int:\n        return x\n\n    return (await g(x) for x in [1, 2, 3])\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAwaitUnion]\nfrom typing import overload, Union\n\nclass A: ...\nclass B: ...\n\n@overload\nasync def foo(x: A) -> B: ...\n@overload\nasync def foo(x: B) -> A: ...\nasync def foo(x): ...\n\nasync def bar(x: Union[A, B]) -> None:\n    reveal_type(await foo(x))  # N: Revealed type is \"__main__.B | __main__.A\"\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncIteratorWithIgnoredErrors]\nimport m\n\nasync def func(l: m.L) -> None:\n    reveal_type(l.get_iterator)  # N: Revealed type is \"def () -> typing.AsyncIterator[builtins.str]\"\n    reveal_type(l.get_iterator2)  # N: Revealed type is \"def () -> typing.AsyncIterator[builtins.str]\"\n    async for i in l.get_iterator():\n        reveal_type(i)  # N: Revealed type is \"builtins.str\"\n\n    reveal_type(m.get_generator)  # N: Revealed type is \"def () -> typing.AsyncGenerator[builtins.int, None]\"\n    async for i2 in m.get_generator():\n        reveal_type(i2)  # N: Revealed type is \"builtins.int\"\n\n[file m.py]\n# mypy: ignore-errors=True\nfrom typing import AsyncIterator, AsyncGenerator\n\nclass L:\n    async def some_func(self, i: int) -> str:\n        return 'x'\n\n    async def get_iterator(self) -> AsyncIterator[str]:\n        yield await self.some_func(0)\n\n    async def get_iterator2(self) -> AsyncIterator[str]:\n        if self:\n            a = (yield 'x')\n\nasync def get_generator() -> AsyncGenerator[int, None]:\n    yield 1\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncIteratorWithIgnoredErrorsAndYieldFrom]\nfrom m import L\n\nasync def func(l: L) -> None:\n    reveal_type(l.get_iterator)\n\n[file m.py]\n# mypy: ignore-errors=True\nfrom typing import AsyncIterator\n\nclass L:\n    async def get_iterator(self) -> AsyncIterator[str]:\n        yield from ['x']  # E: \"yield from\" in async function\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testInvalidComprehensionNoCrash]\n# flags: --show-error-codes\nasync def foo(x: int) -> int: ...\n\n# These are allowed in some cases:\ntop_level = await foo(1)  # E: \"await\" outside function  [top-level-await]\ncrasher = [await foo(x) for x in [1, 2, 3]]  # E: \"await\" outside function  [top-level-await]\n\ndef bad() -> None:\n    # These are always critical / syntax issues:\n    y = [await foo(x) for x in [1, 2, 3]]  # E: \"await\" outside coroutine (\"async def\")  [await-not-async]\nasync def good() -> None:\n    y = [await foo(x) for x in [1, 2, 3]]  # OK\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testNestedAsyncFunctionAndTypeVarAvalues]\nfrom typing import TypeVar\n\nT = TypeVar('T', int, str)\n\ndef f(x: T) -> None:\n    async def g() -> T:\n        return x\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testNestedAsyncGeneratorAndTypeVarAvalues]\nfrom typing import AsyncGenerator, TypeVar\n\nT = TypeVar('T', int, str)\n\ndef f(x: T) -> None:\n    async def g() -> AsyncGenerator[T, None]:\n        yield x\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testNestedDecoratedCoroutineAndTypeVarValues]\nfrom typing import Generator, TypeVar\nfrom types import coroutine\n\nT = TypeVar('T', int, str)\n\ndef f(x: T) -> None:\n    @coroutine\n    def inner() -> Generator[T, None, None]:\n        yield x\n    reveal_type(inner)  # N: Revealed type is \"def () -> typing.AwaitableGenerator[builtins.int, None, None, typing.Generator[builtins.int, None, None]]\" \\\n        # N: Revealed type is \"def () -> typing.AwaitableGenerator[builtins.str, None, None, typing.Generator[builtins.str, None, None]]\"\n\n@coroutine\ndef coro() -> Generator[int, None, None]:\n    yield 1\nreveal_type(coro)  # N: Revealed type is \"def () -> typing.AwaitableGenerator[builtins.int, None, None, typing.Generator[builtins.int, None, None]]\"\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case asyncIteratorInProtocol]\nfrom typing import AsyncIterator, Protocol\n\nclass P(Protocol):\n    async def launch(self) -> AsyncIterator[int]:\n        raise BaseException\n\nclass Launcher(P):\n    def launch(self) -> AsyncIterator[int]:  # E: Return type \"AsyncIterator[int]\" of \"launch\" incompatible with return type \"Coroutine[Any, Any, AsyncIterator[int]]\" in supertype \"P\" \\\n                                             # N: Consider declaring \"launch\" in supertype \"P\" without \"async\" \\\n                                             # N: See https://mypy.readthedocs.io/en/stable/more_types.html#asynchronous-iterators\n        raise BaseException\n\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testInvalidAsyncForInComprehensionNoCrash]\n# a # is at the end to mark these not as section headers\n[[5 async for _ in [5]] for _ in []]#  # E: \"async for\" outside async function \\\n                                       # E: \"list[int]\" has no attribute \"__aiter__\" (not async iterable)\n[{5 async for _ in [5]} for _ in []]#  # E: \"async for\" outside async function \\\n                                       # E: \"list[int]\" has no attribute \"__aiter__\" (not async iterable)\n[{5: 5 async for _ in [5]} for _ in []]#  # E: \"async for\" outside async function \\\n                                          # E: \"list[int]\" has no attribute \"__aiter__\" (not async iterable)\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n"
  },
  {
    "path": "test-data/unit/check-basic.test",
    "content": "[case testEmptyFile]\n[out]\n\n[case testAssignmentAndVarDef]\na: A\nb: B\nif int():\n    a = a\nif int():\n    a = b # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nclass A: pass\nclass B: pass\n\n[case testConstructionAndAssignment]\nclass A:\n    def __init__(self): pass\nclass B:\n    def __init__(self): pass\n\nx: A\nx = A()\nif int():\n    x = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[case testInheritInitFromObject]\nclass A(object): pass\nclass B(object): pass\nx: A\nif int():\n    x = A()\nif int():\n    x = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[case testImplicitInheritInitFromObject]\nclass A: pass\nclass B: pass\nx: A\no: object\nif int():\n    x = o # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nif int():\n    x = A()\nif int():\n    o = x\n[case testTooManyConstructorArgs]\nimport typing\nobject(object())\n[out]\nmain:2: error: Too many arguments for \"object\"\n\n[case testVarDefWithInit]\nimport typing\nclass A: pass\na = A() # type: A\nb = object() # type: A  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n[case testInheritanceBasedSubtyping]\nimport typing\nclass A: pass\nclass B(A): pass\nx = B() # type: A\ny = A() # type: B  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n[case testDeclaredVariableInParentheses]\n\n(x) = 2 # type: int\nif int():\n    x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    x = 1\n\n\n[case testIncompatibleAssignmentAmbiguousShortnames]\n\nclass Any: pass\nclass List: pass\nclass Dict: pass\nclass Iterator: pass\n\nx = Any()\nx = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"__main__.Any\")\n\ny = List()\ny = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"__main__.List\")\n\nz = Dict()\nz = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"__main__.Dict\")\n\nw = Iterator()\nw = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"__main__.Iterator\")\n\n\n-- Simple functions and calling\n-- ----------------------------\n\n\n[case testFunction]\nimport typing\nclass A: pass\nclass B: pass\ndef f(x: 'A') -> None: pass\nf(A())\nf(B()) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\n[case testNotCallable]\nimport typing\nclass A: pass\nA()()  # E: \"A\" not callable\n[case testSubtypeArgument]\nimport typing\nclass A: pass\nclass B(A): pass\ndef f(x: 'A', y: 'B') -> None: pass\nf(B(), A()) # E: Argument 2 to \"f\" has incompatible type \"A\"; expected \"B\"\nf(B(), B())\n[case testInvalidArgumentCount]\nimport typing\ndef f(x, y) -> None: pass\nf(object())\nf(object(), object(), object())\n[out]\nmain:3: error: Missing positional argument \"y\" in call to \"f\"\nmain:4: error: Too many arguments for \"f\"\n\n[case testMissingPositionalArguments]\nclass Foo:\n    def __init__(self, bar: int):\n        pass\nc = Foo()\ndef foo(baz: int, bas: int):pass\nfoo()\n[out]\nmain:4: error: Missing positional argument \"bar\" in call to \"Foo\"\nmain:6: error: Missing positional arguments \"baz\", \"bas\" in call to \"foo\"\n\n\n-- Locals\n-- ------\n\n\n[case testLocalVariables]\ndef f() -> None:\n  x: A\n  y: B\n  if int():\n      x = x\n      x = y # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nclass A: pass\nclass B: pass\n\n[case testLocalVariableScope]\ndef f() -> None:\n  x: A\n  x = A()\ndef g() -> None:\n  x: B\n  x = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nclass A: pass\nclass B: pass\n\n[case testFunctionArguments]\nimport typing\ndef f(x: 'A', y: 'B') -> None:\n  if int():\n    x = y # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    x = x\n    y = B()\nclass A: pass\nclass B: pass\n\n[case testLocalVariableInitialization]\nimport typing\ndef f() -> None:\n  a = A() # type: A\n  b = B() # type: A # Fail\nclass A: pass\nclass B: pass\n[out]\nmain:4: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\n[case testVariableInitializationWithSubtype]\nimport typing\nclass A: pass\nclass B(A): pass\nx = B() # type: A\ny = A() # type: B # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n\n-- Misc\n-- ----\n\n\n[case testInvalidReturn]\nimport typing\ndef f() -> 'A':\n  return B()\nclass A: pass\nclass B: pass\n[out]\nmain:3: error: Incompatible return value type (got \"B\", expected \"A\")\n\n[case testTopLevelContextAndInvalidReturn]\nimport typing\nclass A: pass\nclass B: pass\ndef f() -> 'A':\n  return B()  # E: Incompatible return value type (got \"B\", expected \"A\")\na = B() # type: A  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[case testEmptyReturnInAnyTypedFunction]\nfrom typing import Any\ndef f() -> Any:\n  return\n\n[case testEmptyYieldInAnyTypedFunction]\nfrom typing import Any\ndef f() -> Any:\n  yield\n\n[case testModuleImplicitAttributes]\nimport typing\nclass A: pass\nreveal_type(__name__)         # N: Revealed type is \"builtins.str\"\nreveal_type(__doc__)          # N: Revealed type is \"builtins.str\"\nreveal_type(__file__)         # N: Revealed type is \"builtins.str\"\nreveal_type(__package__)      # N: Revealed type is \"builtins.str\"\nreveal_type(__annotations__)  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\n# This will actually reveal Union[importlib.machinery.ModuleSpec, None]\nreveal_type(__spec__)         # N: Revealed type is \"builtins.object | None\"\n\nimport module\nreveal_type(module.__name__)  # N: Revealed type is \"builtins.str\"\n# This will actually reveal importlib.machinery.ModuleSpec\nreveal_type(module.__spec__)  # N: Revealed type is \"builtins.object\"\n[file module.py]\n[builtins fixtures/primitives.pyi]\n\n\n-- Scoping and shadowing\n-- ---------------------\n\n\n[case testLocalVariableShadowing]\nclass A: pass\nclass B: pass\na: A\nif int():\n    a = B()  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    a = A()\ndef f() -> None:\n  a: B\n  if int():\n      a = A()     # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n      a = B()\na = B()       # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\na = A()\n[case testGlobalDefinedInBlockWithType]\nclass A: pass\nwhile 1:\n    a: A\n    if int():\n        a = A()\n        a = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n\n\n-- # type: signatures\n-- ------------------\n\n\n[case testFunctionSignatureAsComment]\ndef f(x): # type: (int) -> str\n    return 1\nf('')\n[out]\nmain:2: error: Incompatible return value type (got \"int\", expected \"str\")\nmain:3: error: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\n[case testMethodSignatureAsComment]\nclass A:\n    def f(self, x):\n        # type: (int) -> str\n        self.f('') # Fail\n        return 1\nA().f('') # Fail\n[out]\nmain:4: error: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\nmain:5: error: Incompatible return value type (got \"int\", expected \"str\")\nmain:6: error: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\n[case testTrailingCommaParsing]\nx = 1\nx in 1,  # E: Unsupported right operand type for in (\"int\")\n[builtins fixtures/tuple.pyi]\n\n[case testTrailingCommaInIfParsing_no_native_parse]\nif x in 1, : pass\n[out]\nmain:1: error: Invalid syntax\n\n[case testInitReturnTypeError]\nclass C:\n    def __init__(self):\n        # type: () -> int\n        pass\n[out]\nmain:2: error: The return type of \"__init__\" must be None\n\n-- WritesCache signals to testcheck to do the cache validation\n[case testWritesCache-writescache]\nimport a\nimport d\n[file a.py]\nimport b\nimport c\n[file b.py]\n[file c.py]\n[file d.py]\n\n[case testWritesCacheErrors-writescache]\nimport a\nimport d\n[file a.py]\nimport b\nimport c\n[file b.py]\n[file c.py]\n[file d.py]\nimport e\n[file e.py]\n1+'no'  # E: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testModuleAsTypeNoCrash]\n\nimport mock\nfrom typing import Union\n\nclass A: ...\nclass B: ...\n\nx: Union[mock, A]  # E: Module \"mock\" is not valid as a type \\\n                   # N: Perhaps you meant to use a protocol matching the module structure?\n\nif isinstance(x, B):\n    pass\n[file mock.py]\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testModuleAsTypeNoCrash2]\n\nimport mock\nfrom typing import overload, Any, Union\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: str) -> Union[mock, str]: ...  # E: Module \"mock\" is not valid as a type \\\n                                        # N: Perhaps you meant to use a protocol matching the module structure?\ndef f(x):\n    pass\n\nx: Any\nf(x)\n[file mock.py]\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testPartialTypeComments]\ndef foo(\n    a,  # type: str\n    b,\n    args=None,\n):\n    # type: (...) -> None\n    pass\n\n[case testNoneHasBool]\ndef main() -> None:\n    none = None\n    b = none.__bool__()\n    reveal_type(b)  # N: Revealed type is \"Literal[False]\"\n[builtins fixtures/bool.pyi]\n\n[case testAssignmentInvariantNoteForList]\nfrom typing import List\nx: List[int]\ny: List[float]\ny = x # E: Incompatible types in assignment (expression has type \"list[int]\", variable has type \"list[float]\") \\\n     # N: \"list\" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \\\n     # N: Consider using \"Sequence\" instead, which is covariant\n[builtins fixtures/list.pyi]\n\n[case testAssignmentInvariantNoteForDict]\nfrom typing import Dict\nx: Dict[str, int]\ny: Dict[str, float]\ny = x # E: Incompatible types in assignment (expression has type \"dict[str, int]\", variable has type \"dict[str, float]\") \\\n     # N: \"dict\" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \\\n     # N: Consider using \"Mapping\" instead, which is covariant in the value type\n[builtins fixtures/dict.pyi]\n\n[case testDistinctTypes]\nimport b\n\n[file a.py]\nfrom typing import NamedTuple, TypedDict\nfrom enum import Enum\nclass A: pass\nN = NamedTuple('N', [('x', int)])\nD = TypedDict('D', {'x': int})\nclass B(Enum):\n    b = 10\n\n[file b.py]\nfrom typing import Final, List, Literal, Optional, Union, Sequence, NamedTuple, Tuple, Type, TypedDict\nfrom enum import Enum\nimport a\nclass A: pass\nN = NamedTuple('N', [('x', int)])\nclass B(Enum):\n    b = 10\nD = TypedDict('D', {'y': int})\n\ndef foo() -> Optional[A]:\n    b = True\n    return a.A() if b else None  # E: Incompatible return value type (got \"a.A | None\", expected \"b.A | None\")\n\ndef bar() -> List[A]:\n    l = [a.A()]\n    return l  # E: Incompatible return value type (got \"list[a.A]\", expected \"list[b.A]\")\n\ndef baz() -> Union[A, int]:\n    b = True\n    return a.A() if b else 10  # E: Incompatible return value type (got \"a.A | int\", expected \"b.A | int\")\n\ndef spam() -> Optional[A]:\n    return a.A()  # E: Incompatible return value type (got \"a.A\", expected \"b.A | None\")\n\ndef eggs() -> Sequence[A]:\n    x = [a.A()]\n    return x  # E: Incompatible return value type (got \"list[a.A]\", expected \"Sequence[b.A]\")\n\ndef eggs2() -> Sequence[N]:\n    x = [a.N(0)]\n    return x  # E: Incompatible return value type (got \"list[a.N]\", expected \"Sequence[b.N]\")\n\ndef asdf1() -> Sequence[Tuple[a.A, A]]:\n    x = [(a.A(), a.A())]\n    return x  # E: Incompatible return value type (got \"list[tuple[a.A, a.A]]\", expected \"Sequence[tuple[a.A, b.A]]\")\n\ndef asdf2() -> Sequence[Tuple[A, a.A]]:\n    x = [(a.A(), a.A())]\n    return x  # E: Incompatible return value type (got \"list[tuple[a.A, a.A]]\", expected \"Sequence[tuple[b.A, a.A]]\")\n\ndef arg() -> Tuple[A, A]:\n    return A()  # E: Incompatible return value type (got \"A\", expected \"tuple[A, A]\")\n\ndef types() -> Sequence[Type[A]]:\n    x = [a.A]\n    return x  # E: Incompatible return value type (got \"list[type[a.A]]\", expected \"Sequence[type[b.A]]\")\n\ndef literal() -> Sequence[Literal[B.b]]:\n    x = [a.B.b]  # type: List[Literal[a.B.b]]\n    return x  # E: Incompatible return value type (got \"list[Literal[a.B.b]]\", expected \"Sequence[Literal[b.B.b]]\")\n\ndef typeddict() -> Sequence[D]:\n    x = [{'x': 0}]  # type: List[a.D]\n    return x  # E: Incompatible return value type (got \"list[a.D]\", expected \"Sequence[b.D]\")\n\na = (a.A(), A())\na.x  # E: \"tuple[a.A, b.A]\" has no attribute \"x\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testReturnAnyFromFunctionDeclaredToReturnObject]\n# flags: --warn-return-any\nfrom typing import Any\n\ndef f() -> object:\n    x: Any = 1\n    return x\n\n[case testImportModuleAsClassMember]\nimport test\n\nclass A:\n    def __init__(self) -> None:\n        self.test = test\n\n    def __call__(self) -> None:\n      self.test.foo(\"Message\")\n\n[file test.py]\ndef foo(s: str) -> None: ...\n\n[case testLocalImportModuleAsClassMember]\nclass A:\n    def __init__(self) -> None:\n        import test\n\n        self.test = test\n\n    def __call__(self) -> None:\n      self.test.foo(\"Message\")\n\n[file test.py]\ndef foo(s: str) -> None: ...\n\n[case testInlineAssertions]\nimport a, b\ns1: str = 42  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[file a.py]\ns2: str = 42  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[file b.py]\ns3: str = 42  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[file c.py]\ns3: str = 'foo'\n\n[case testMultilineQuotedAnnotation]\nx: \"\"\"\n\n   int |\n   str\n\n\"\"\"\nreveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n\ny: \"\"\"(\n    int |\n    str\n)\n\"\"\"\nreveal_type(y)  # N: Revealed type is \"builtins.int | builtins.str\"\n"
  },
  {
    "path": "test-data/unit/check-bound.test",
    "content": "-- Enforcement of upper bounds\n-- ---------------------------\n\n\n[case testBoundOnGenericFunction]\nfrom typing import TypeVar\n\nclass A: pass\nclass B(A): pass\nclass C(A): pass\nclass D: pass\n\nT = TypeVar('T', bound=A)\nU = TypeVar('U')\ndef f(x: T) -> T: pass\ndef g(x: U) -> U:\n    return f(x) # E: Value of type variable \"T\" of \"f\" cannot be \"U\"\n\nf(A())\nf(B())\nf(D()) # E: Value of type variable \"T\" of \"f\" cannot be \"D\"\n\nb = B()\nif int():\n    b = f(b)\nif int():\n    b = f(C()) # E: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\n\n\n[case testBoundOnGenericClass]\nfrom typing import TypeVar, Generic\n\nclass A: pass\nclass B(A): pass\nT = TypeVar('T', bound=A)\n\nclass G(Generic[T]):\n    def __init__(self, x: T) -> None: pass\n\nv: G[A]\nw: G[B]\nx: G[str]  # E: Type argument \"str\" of \"G\" must be a subtype of \"A\"\ny = G('a') # E: Value of type variable \"T\" of \"G\" cannot be \"str\"\nz = G(A())\nz = G(B())\n\n\n[case testBoundVoid]\n# flags: --no-strict-optional --no-local-partial-types\nfrom typing import TypeVar, Generic\nT = TypeVar('T', bound=int)\nclass C(Generic[T]):\n    t = None # type: T\n    def get(self) -> T:\n        return self.t\nc1 = None # type: C[None]\nc1.get()\nd = c1.get()\nreveal_type(d)  # N: Revealed type is \"None\"\n\n\n[case testBoundAny]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', bound=int)\nclass C(Generic[T]):\n    def __init__(self, x: T) -> None: pass\ndef f(x: T) -> T:\n    return x\n\ndef g(): pass\n\nf(g())\nC(g())\nz: C\n\n\n[case testBoundHigherOrderWithVoid]\n# flags: --no-strict-optional --no-local-partial-types\nfrom typing import TypeVar, Callable\nclass A: pass\nT = TypeVar('T', bound=A)\ndef f(g: Callable[[], T]) -> T:\n    return g()\ndef h() -> None: pass\nf(h)\na = f(h)\nreveal_type(a)  # N: Revealed type is \"None\"\n\n\n[case testBoundInheritance]\nfrom typing import TypeVar, Generic\nclass A: pass\nT = TypeVar('T')\nTA = TypeVar('TA', bound=A)\n\nclass C(Generic[TA]): pass\nclass D0(C[TA], Generic[TA]): pass\nclass D1(C[T], Generic[T]): pass # E: Type argument \"T\" of \"C\" must be a subtype of \"A\"\nclass D2(C[A]): pass\nclass D3(C[str]): pass # E: Type argument \"str\" of \"C\" must be a subtype of \"A\"\n\n\n-- Using information from upper bounds\n-- -----------------------------------\n\n\n[case testBoundGenericFunctions]\nfrom typing import TypeVar\nclass A: pass\nclass B(A): pass\n\nT = TypeVar('T')\nTA = TypeVar('TA', bound=A)\nTB = TypeVar('TB', bound=B)\n\ndef f(x: T) -> T:\n    return x\ndef g(x: TA) -> TA:\n    return f(x)\ndef h(x: TB) -> TB:\n    return g(x)\ndef g2(x: TA) -> TA:\n    return h(x) # Fail\n\ndef j(x: TA) -> A:\n    return x\ndef k(x: TA) -> B:\n    return x # Fail\n[out]\nmain:16: error: Value of type variable \"TB\" of \"h\" cannot be \"TA\"\nmain:21: error: Incompatible return value type (got \"TA\", expected \"B\")\n\n\n[case testBoundMethodUsage]\nfrom typing import TypeVar\nclass A0:\n    def foo(self) -> None: pass\nclass A(A0):\n    def bar(self) -> None: pass\n    a = 1\n    @property\n    def b(self) -> int:\n        return self.a\nclass B(A):\n    def baz(self) -> None: pass\n\nT = TypeVar('T', bound=A)\n\ndef f(x: T) -> T:\n    x.foo()\n    x.bar()\n    x.baz()  # E: \"T\" has no attribute \"baz\"\n    x.a\n    x.b\n    return x\n\nb = f(B())\n[builtins fixtures/property.pyi]\n[out]\n\n[case testBoundClassMethod]\nfrom typing import TypeVar\nclass A0:\n    @classmethod\n    def foo(cls, x: int) -> int: pass\nclass A(A0): pass\n\nT = TypeVar('T', bound=A)\ndef f(x: T) -> int:\n    return x.foo(22)\n[builtins fixtures/classmethod.pyi]\n\n\n[case testBoundClassMethodWithNamedTupleBase]\nfrom typing import NamedTuple, Type, TypeVar\nclass A(NamedTuple):\n    @classmethod\n    def foo(cls) -> None: ...\n\nT = TypeVar('T', bound=A)\ndef f(x: Type[T]) -> None:\n    reveal_type(x.foo)  # N: Revealed type is \"def ()\"\n    x.foo()\n[builtins fixtures/classmethod.pyi]\n\n\n[case testBoundStaticMethod]\nfrom typing import TypeVar\nclass A0:\n    @staticmethod\n    def foo(x: int) -> int: pass\nclass A(A0): pass\n\nT = TypeVar('T', bound=A)\ndef f(x: T) -> int:\n    return x.foo(22)\n[builtins fixtures/staticmethod.pyi]\n\n\n[case testBoundOnDecorator]\nfrom typing import TypeVar, Callable, Any, cast\nT = TypeVar('T', bound=Callable[..., Any])\n\ndef twice(f: T) -> T:\n    def result(*args, **kwargs) -> Any:\n        f(*args, **kwargs)\n        return f(*args, **kwargs)\n    return cast(T, result)\n\n@twice\ndef foo(x: int) -> int:\n    return x\n\na = 1\nb = foo(a)\nif int():\n    b = 'a' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ntwice(a) # E: Value of type variable \"T\" of \"twice\" cannot be \"int\"\n[builtins fixtures/args.pyi]\n\n\n[case testIterableBoundUnpacking]\nfrom typing import Tuple, TypeVar\nTupleT = TypeVar(\"TupleT\", bound=Tuple[int, ...])\ndef f(t: TupleT) -> None:\n    a, *b = t\n    reveal_type(a)  # N: Revealed type is \"builtins.int\"\n    reveal_type(b)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-callable.test",
    "content": "[case testCallableDef]\ndef f() -> None: pass\n\nif callable(f):\n    f()\nelse:\n    f += 5\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableLambda]\nf = lambda: None\n\nif callable(f):\n    f()\nelse:\n    f += 5\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableNotCallable]\nx = 5\n\nif callable(x):\n    x()\nelse:\n    x += 5\n\n[builtins fixtures/callable.pyi]\n\n[case testUnion]\nfrom typing import Callable, Union\n\nx = 5  # type: Union[int, Callable[[], str]]\n\nif callable(x):\n    y = x() + 'test'\nelse:\n    z = x + 6\n\n[builtins fixtures/callable.pyi]\n\n[case testUnionMultipleReturnTypes]\nfrom typing import Callable, Union\n\nx = 5  # type: Union[int, Callable[[], str], Callable[[], int]]\n\nif callable(x):\n    y = x() + 2 # E: Unsupported operand types for + (\"str\" and \"int\") \\\n                # N: Left operand is of type \"str | int\"\nelse:\n    z = x + 6\n\n[builtins fixtures/callable.pyi]\n\n[case testUnionMultipleNonCallableTypes]\nfrom typing import Callable, Union\n\nx = 5  # type: Union[int, str, Callable[[], str]]\n\nif callable(x):\n    y = x() + 'test'\nelse:\n    z = x + 6  # E: Unsupported operand types for + (\"str\" and \"int\") \\\n               # N: Left operand is of type \"int | str\"\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableThenIsinstance]\nfrom typing import Callable, Union\n\nx = 5  # type: Union[int, str, Callable[[], str], Callable[[], int]]\n\nif callable(x):\n    y = x()\n    if isinstance(y, int):\n        b1 = y + 2\n    else:\n        b2 = y + 'test'\nelse:\n    if isinstance(x, int):\n        b3 = x + 3\n    else:\n        b4 = x + 'test2'\n\n[builtins fixtures/callable.pyi]\n\n[case testIsinstanceThenCallable]\nfrom typing import Callable, Union\n\nx = 5  # type: Union[int, str, Callable[[], str], Callable[[], int]]\n\nif isinstance(x, int):\n    b1 = x + 1\nelse:\n    if callable(x):\n        y = x()\n        if isinstance(y, int):\n            b2 = y + 1\n        else:\n            b3 = y + 'test'\n    else:\n        b4 = x + 'test2'\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableWithDifferentArgTypes]\nfrom typing import Callable, Union\n\nx = 5  # type: Union[int, Callable[[], None], Callable[[int], None]]\n\nif callable(x):\n    x()  # E: Too few arguments\n\n[builtins fixtures/callable.pyi]\n\n[case testClassInitializer]\nfrom typing import Callable, Union\n\nclass A:\n    x = 5\n\na = A  # type: Union[A, Callable[[], A]]\n\nif callable(a):\n    a = a()\n\na.x + 6\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableVariables]\nfrom typing import Union\n\nclass A:\n    x = 5\n\nclass B:\n    x = int\n\nx = A()  # type: Union[A, B]\n\nif callable(x.x):\n    y = x.x()\nelse:\n    y = x.x + 5\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableAnd]\nfrom typing import Union, Callable\n\nx = 5  # type: Union[int, Callable[[], str]]\n\nif callable(x) and x() == 'test':\n    x()\nelse:\n    x + 5  # E: Unsupported left operand type for + (\"Callable[[], str]\") \\\n           # N: Left operand is of type \"int | Callable[[], str]\"\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableOr]\nfrom typing import Union, Callable\n\nx = 5  # type: Union[int, Callable[[], str]]\n\nif callable(x) or x() == 'test':  # E: \"int\" not callable\n    x()  # E: \"int\" not callable\nelse:\n    x + 5\n[builtins fixtures/callable.pyi]\n\n[case testCallableOrOtherType]\nfrom typing import Union, Callable\n\nx = 5  # type: Union[int, Callable[[], str]]\n\nif callable(x) or x == 2:\n    pass\nelse:\n    pass\n[builtins fixtures/callable.pyi]\n\n[case testAnyCallable]\nfrom typing import Any\n\nx = 5  # type: Any\n\nif callable(x):\n    reveal_type(x)  # N: Revealed type is \"Any\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/callable.pyi]\n\n[case testCallableCallableClasses]\nfrom typing import Union\n\n\nclass A:\n    pass\n\n\nclass B:\n    def __call__(self) -> None:\n        pass\n\n\na = A()  # type: A\nb = B()  # type: B\nc = A()  # type: Union[A, B]\n\nif callable(a):\n    5 + 'test'  # E: Unsupported operand types for + (\"int\" and \"str\")\n\nif not callable(b):\n    5 + 'test'\n\nif callable(c):\n    reveal_type(c)  # N: Revealed type is \"__main__.B\"\nelse:\n    reveal_type(c)  # N: Revealed type is \"__main__.A\"\n\n[builtins fixtures/callable.pyi]\n\n[case testDecoratedCallMethods]\nfrom typing import Any, Callable, Union, TypeVar\n\nF = TypeVar('F', bound=Callable)\n\ndef decorator(f: F) -> F:\n    pass\ndef change(f: Callable) -> Callable[[Any], str]:\n    pass\ndef untyped(f):\n    pass\n\nclass Some1:\n    @decorator\n    def __call__(self) -> int:\n        pass\nclass Some2:\n    @change\n    def __call__(self) -> int:\n        pass\nclass Some3:\n    @untyped\n    def __call__(self) -> int:\n        pass\nclass Some4:\n    __call__: Any\n\ns1: Some1\ns2: Some2\ns3: Some3\ns4: Some4\n\nif callable(s1):\n    1 + 'a'  # E: Unsupported operand types for + (\"int\" and \"str\")\nelse:\n    2 + 'b'\nif callable(s2):\n    1 + 'a'  # E: Unsupported operand types for + (\"int\" and \"str\")\nelse:\n    2 + 'b'\nif callable(s3):\n    1 + 'a'  # E: Unsupported operand types for + (\"int\" and \"str\")\nelse:\n    2 + 'b'  # E: Unsupported operand types for + (\"int\" and \"str\")\nif callable(s4):\n    1 + 'a'  # E: Unsupported operand types for + (\"int\" and \"str\")\nelse:\n    2 + 'b'  # E: Unsupported operand types for + (\"int\" and \"str\")\n[builtins fixtures/callable.pyi]\n\n[case testCallableNestedUnions]\nfrom typing import Callable, Union\n\nT = Union[Union[int, Callable[[], int]], Union[str, Callable[[], str]]]\n\ndef f(t: T) -> None:\n    if callable(t):\n        reveal_type(t())  # N: Revealed type is \"builtins.int | builtins.str\"\n    else:\n        reveal_type(t)  # N: Revealed type is \"builtins.int | builtins.str\"\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableTypeVarEmpty]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef f(t: T) -> T:\n    if callable(t):\n        return 5  # E: Incompatible return value type (got \"int\", expected \"T\")\n    else:\n        return t\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableTypeVarUnion]\nfrom typing import Callable, TypeVar, Union\n\nT = TypeVar('T', int, Callable[[], int], Union[str, Callable[[], str]])\n\ndef f(t: T) -> None:\n    if callable(t):\n        reveal_type(t())  # N: Revealed type is \"Any\"  \\\n            # N: Revealed type is \"builtins.int\"  \\\n            # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(t)  # N: Revealed type is \"builtins.int\"  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableTypeVarBound]\nfrom typing import TypeVar\n\n\nclass A:\n    def __call__(self) -> str:\n        return 'hi'\n\n\nT = TypeVar('T', bound=A)\n\ndef f(t: T) -> str:\n    if callable(t):\n        return t()\n    else:\n        return 5\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableTypeType]\nfrom typing import Type\n\n\nclass A:\n    pass\n\n\nT = Type[A]\n\ndef f(t: T) -> A:\n    if callable(t):\n        return t()\n    else:\n        return 5\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableTypeUnion]\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Type, Union\n\n\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self) -> None:\n        pass\n\n\nclass B:\n    pass\n\n\nx = B  # type: Union[Type[A], Type[B]]\nif callable(x):\n    # Abstract classes raise an error when called, but are indeed `callable`\n    pass\nelse:\n    'test' + 5\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableUnionOfTypes]\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Type, Union\n\n\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self) -> None:\n        pass\n\n\nclass B:\n    pass\n\n\nx = B  # type: Type[Union[A, B]]\nif callable(x):\n    # Abstract classes raise an error when called, but are indeed `callable`\n    pass\nelse:\n    'test' + 5\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableObject]\n\ndef f(o: object) -> None:\n    if callable(o):\n        o(1,2,3)\n        1 + 'boom'  # E: Unsupported operand types for + (\"int\" and \"str\")\n        o('hi') + 12\n        reveal_type(o)  # N: Revealed type is \"__main__.<callable subtype of object>\"\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableObject2]\n\nclass Foo(object):\n    def bar(self) -> None:\n        pass\n\ndef g(o: Foo) -> None:\n    o.bar()\n    if callable(o):\n        o.foo()  # E: \"Foo\" has no attribute \"foo\"\n        o.bar()\n        o(1,2,3)\n    else:\n        o.bar()\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableObjectAny]\n\nfrom typing import Any\n\nclass Foo(Any):\n    def bar(self) -> None:\n        pass\n\ndef g(o: Foo) -> None:\n    o.bar()\n    o.baz()\n    if callable(o):\n        o('test')\n        o.lurr(1,2,3)\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableObjectGeneric]\n\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nclass Test(Generic[T]):\n    def __self__(self, x: T) -> None:\n        self.x = x\n\ndef g(o: Test[T], x: T) -> T:\n    if callable(o):\n        o.foo()  # E: \"Test[T]\" has no attribute \"foo\"\n        o(1,2,3)\n        o.x = x\n        o.x = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"T\")\n        1 + o.x  # E: Unsupported operand types for + (\"int\" and \"T\")\n        return o.x\n\n    return x\n\n[builtins fixtures/callable.pyi]\n\n[case testCallablePromote]\n\ndef take_float(f: float) -> None:\n    pass\n\ndef g(o: int) -> None:\n    if callable(o):\n        take_float(o)\n        o(1,2,3)\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableTuple]\n\nfrom typing import NamedTuple\n\nThing = NamedTuple('Thing', [('s', str), ('n', int)])\n\ndef g(o: Thing) -> None:\n    if callable(o):\n        o.s + o.n  # E: Unsupported operand types for + (\"str\" and \"int\")\n        i, s = o\n        i + s  # E: Unsupported operand types for + (\"str\" and \"int\")\n        o(1,2,3)\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableNoArgs]\n\nif callable():  # E: Missing positional argument \"x\" in call to \"callable\"\n    pass\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableWithAnyArgs]\n\ndef main(fn: object) -> None:\n    if callable(fn):\n        fn()\n        fn(1, 2, 3)\n        fn(take=\"that\")\n\n[builtins fixtures/callable.pyi]\n\n[case testCallableUnionOfNoneAndCallable]\n\nfrom typing import Union, Callable\n\ndef f() -> int:\n    return 42\n\nfn = f  # type: Union[None, Callable[[], int]]\n\nif callable(fn):\n    reveal_type(fn) # N: Revealed type is \"def () -> builtins.int\"\nelse:\n    reveal_type(fn) # N: Revealed type is \"None\"\n\n[builtins fixtures/callable.pyi]\n\n[case testBuiltinsTypeAsCallable]\nfrom __future__ import annotations\n\nreveal_type(type)  # N: Revealed type is \"def (x: Any) -> builtins.type\"\n_TYPE = type\nreveal_type(_TYPE)  # N: Revealed type is \"def (x: Any) -> builtins.type\"\n_TYPE('bar')\n\n[builtins fixtures/callable.pyi]\n\n[case testErrorMessageAboutSelf]\n# https://github.com/python/mypy/issues/11309\nclass Some:\n    def method(self, a) -> None: pass\n    @classmethod\n    def cls_method(cls, a) -> None: pass\n    @staticmethod\n    def st_method(a) -> None: pass\n\n    def bad_method(a) -> None: pass\n    @classmethod\n    def bad_cls_method(a) -> None: pass\n    @staticmethod\n    def bad_st_method() -> None: pass\n\ns: Some\n\ns.method(1)\ns.cls_method(1)\nSome.cls_method(1)\ns.st_method(1)\nSome.st_method(1)\n\ns.method(1, 2)  # E: Too many arguments for \"method\" of \"Some\"\ns.cls_method(1, 2)  # E: Too many arguments for \"cls_method\" of \"Some\"\nSome.cls_method(1, 2)  # E: Too many arguments for \"cls_method\" of \"Some\"\ns.st_method(1, 2)  # E: Too many arguments for \"st_method\" of \"Some\"\nSome.st_method(1, 2)  # E: Too many arguments for \"st_method\" of \"Some\"\n\ns.bad_method(1)  # E: Too many arguments for \"bad_method\" of \"Some\" \\\n                 # N: Looks like the first special argument in a method is not named \"self\", \"cls\", or \"mcs\", maybe it is missing?\ns.bad_cls_method(1)  # E: Too many arguments for \"bad_cls_method\" of \"Some\" \\\n                     # N: Looks like the first special argument in a method is not named \"self\", \"cls\", or \"mcs\", maybe it is missing?\nSome.bad_cls_method(1)  # E: Too many arguments for \"bad_cls_method\" of \"Some\" \\\n                        # N: Looks like the first special argument in a method is not named \"self\", \"cls\", or \"mcs\", maybe it is missing?\ns.bad_st_method(1)  # E: Too many arguments for \"bad_st_method\" of \"Some\"\nSome.bad_st_method(1)  # E: Too many arguments for \"bad_st_method\" of \"Some\"\n[builtins fixtures/callable.pyi]\n\n[case testClassMethodAliasStub]\nfrom a import f\nf(\"no\")  # E: Argument 1 has incompatible type \"str\"; expected \"int\"\n[file a.pyi]\nfrom b import C\nf = C.f\n[file b.pyi]\nimport a\nclass C(B):\n    @classmethod\n    def f(self, x: int) -> C: ...\nclass B: ...\n[builtins fixtures/classmethod.pyi]\n\n[case testClassMethodAliasInClass]\nfrom typing import overload\n\nclass C:\n    @classmethod\n    def foo(cls) -> int: ...\n\n    bar = foo\n\n    @overload\n    @classmethod\n    def foo2(cls, x: int) -> int: ...\n    @overload\n    @classmethod\n    def foo2(cls, x: str) -> str: ...\n    @classmethod\n    def foo2(cls, x):\n        ...\n\n    bar2 = foo2\n\nreveal_type(C.bar)  # N: Revealed type is \"def () -> builtins.int\"\nreveal_type(C().bar)  # N: Revealed type is \"def () -> builtins.int\"\nreveal_type(C.bar2)  # N: Revealed type is \"Overload(def (x: builtins.int) -> builtins.int, def (x: builtins.str) -> builtins.str)\"\nreveal_type(C().bar2)  # N: Revealed type is \"Overload(def (x: builtins.int) -> builtins.int, def (x: builtins.str) -> builtins.str)\"\n[builtins fixtures/classmethod.pyi]\n\n[case testPropertyAliasInClassBody]\nclass A:\n    @property\n    def f(self) -> int: ...\n\n    g = f\n\n    @property\n    def f2(self) -> int: ...\n    @f2.setter\n    def f2(self, val: int) -> None: ...\n\n    g2 = f2\n\nreveal_type(A().g)  # N: Revealed type is \"builtins.int\"\nreveal_type(A().g2)  # N: Revealed type is \"builtins.int\"\nA().g = 1  # E: Property \"g\" defined in \"A\" is read-only\nA().g2 = 1\nA().g2 = \"no\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/property.pyi]\n\n[case testCallableUnionCallback]\nfrom typing import Union, Callable, TypeVar\n\nTA = TypeVar(\"TA\", bound=\"A\")\nclass A:\n    def __call__(self: TA, other: Union[Callable, TA]) -> TA: ...\na: A\na()  # E: Missing positional argument \"other\" in call to \"__call__\" of \"A\"\na(a)\na(lambda: None)\n\n[case testCallableSubtypingTrivialSuffix]\nfrom typing import Any, Protocol\n\nclass Call(Protocol):\n    def __call__(self, x: int, *args: Any, **kwargs: Any) -> None: ...\n\ndef f1() -> None: ...\na1: Call = f1  # E: Incompatible types in assignment (expression has type \"Callable[[], None]\", variable has type \"Call\") \\\n               # N: \"Call.__call__\" has type \"def __call__(self, x: int, *args: Any, **kwargs: Any) -> None\"\ndef f2(x: str) -> None: ...\na2: Call = f2  # E: Incompatible types in assignment (expression has type \"Callable[[str], None]\", variable has type \"Call\") \\\n               # N: \"Call.__call__\" has type \"def __call__(self, x: int, *args: Any, **kwargs: Any) -> None\"\ndef f3(y: int) -> None: ...\na3: Call = f3  # E: Incompatible types in assignment (expression has type \"Callable[[int], None]\", variable has type \"Call\") \\\n               # N: \"Call.__call__\" has type \"def __call__(self, x: int, *args: Any, **kwargs: Any) -> None\"\ndef f4(x: int) -> None: ...\na4: Call = f4\n\ndef f5(x: int, y: int) -> None: ...\na5: Call = f5\n\ndef f6(x: int, y: int = 0) -> None: ...\na6: Call = f6\n\ndef f7(x: int, *, y: int) -> None: ...\na7: Call = f7\n\ndef f8(x: int, *args: int, **kwargs: str) -> None: ...\na8: Call = f8\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-class-namedtuple.test",
    "content": "[case testNewNamedTupleNoUnderscoreFields]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    _y: int  # E: NamedTuple field name cannot start with an underscore: _y\n    _z: int  # E: NamedTuple field name cannot start with an underscore: _z\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleAccessingAttributes]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y: str\n\nx: X\nx.x\nx.y\nx.z # E: \"X\" has no attribute \"z\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleAttributesAreReadOnly]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n\nx: X\nx.x = 5 # E: Property \"x\" defined in \"X\" is read-only\nx.y = 5 # E: \"X\" has no attribute \"y\"\n\nclass A(X): pass\na: A\na.x = 5 # E: Property \"x\" defined in \"X\" is read-only\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleCreateWithPositionalArguments]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y: str\n\nx = X(1, '2')\nx.x\nx.z      # E: \"X\" has no attribute \"z\"\nx = X(1) # E: Missing positional argument \"y\" in call to \"X\"\nx = X(1, '2', 3)  # E: Too many arguments for \"X\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleShouldBeSingleBase]\nfrom typing import NamedTuple\n\nclass A: ...\nclass X(NamedTuple, A):  # E: NamedTuple should be a single base\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testCreateNewNamedTupleWithKeywordArguments]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y: str\n\nx = X(x=1, y='x')\nx = X(1, y='x')\nx = X(x=1, z=1) # E: Unexpected keyword argument \"z\" for \"X\"\nx = X(y='x') # E: Missing positional argument \"x\" in call to \"X\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleCreateAndUseAsTuple]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y: str\n\nx = X(1, 'x')\na, b = x\na, b, c = x  # E: Need more than 2 values to unpack (3 expected)\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleWithItemTypes]\nfrom typing import NamedTuple\n\nclass N(NamedTuple):\n    a: int\n    b: str\n\nn = N(1, 'x')\ns: str = n.a  # E: Incompatible types in assignment (expression has type \"int\", \\\n                          variable has type \"str\")\ni: int = n.b  # E: Incompatible types in assignment (expression has type \"str\", \\\n                          variable has type \"int\")\nx, y = n\nif int():\n    x = y  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleConstructorArgumentTypes]\nfrom typing import NamedTuple\n\nclass N(NamedTuple):\n    a: int\n    b: str\n\nn = N('x', 'x') # E: Argument 1 to \"N\" has incompatible type \"str\"; expected \"int\"\nn = N(1, b=2)   # E: Argument \"b\" to \"N\" has incompatible type \"int\"; expected \"str\"\nN(1, 'x')\nN(b='x', a=1)\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleAsBaseClass]\nfrom typing import NamedTuple\n\nclass N(NamedTuple):\n    a: int\n    b: str\n\nclass X(N):\n    pass\nx = X(1, 2)  # E: Argument 2 to \"X\" has incompatible type \"int\"; expected \"str\"\ns = ''\ni = 0\nif int():\n    s = x.a  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nif int():\n    i, s = x\nif int():\n    s, s = x # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleSelfTypeWithNamedTupleAsBase]\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    a: int\n    b: str\n\nclass B(A):\n    def f(self, x: int) -> None:\n        self.f(self.a)\n        self.f(self.b)  # E: Argument 1 to \"f\" of \"B\" has incompatible type \"str\"; expected \"int\"\n        i = 0\n        s = ''\n        if int():\n            i, s = self\n            i, i = self  # E: Incompatible types in assignment (expression has type \"str\", \\\n                              variable has type \"int\")\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNewNamedTupleTypeReferenceToClassDerivedFrom]\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    a: int\n    b: str\n\nclass B(A):\n    def f(self, x: 'B') -> None:\n        i = 0\n        s = ''\n        if int():\n            self = x\n            i, s = x\n            i, s = x.a, x.b\n            i, s = x.a, x.a  # E: Incompatible types in assignment (expression has type \"int\", \\\n                                  variable has type \"str\")\n            i, i = self  # E: Incompatible types in assignment (expression has type \"str\", \\\n                              variable has type \"int\")\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleSubtyping]\nfrom typing import NamedTuple, Tuple\n\nclass A(NamedTuple):\n    a: int\n    b: str\n\nclass B(A): pass\na = A(1, '')\nb = B(1, '')\nt: Tuple[int, str]\nif int():\n    b = a  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    a = t  # E: Incompatible types in assignment (expression has type \"tuple[int, str]\", variable has type \"A\")\nif int():\n    b = t  # E: Incompatible types in assignment (expression has type \"tuple[int, str]\", variable has type \"B\")\nif int():\n    t = a\nif int():\n    t = (1, '')\nif int():\n    t = b\nif int():\n    a = b\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleSimpleTypeInference]\nfrom typing import NamedTuple, Tuple\n\nclass A(NamedTuple):\n    a: int\n\nl = [A(1), A(2)]\na = A(1)\na = l[0]\n(i,) = l[0]\ni, i = l[0]  # E: Need more than 1 value to unpack (2 expected)\nl = [A(1)]\na = (1,)  # E: Incompatible types in assignment (expression has type \"tuple[int]\", \\\n               variable has type \"A\")\n[builtins fixtures/list.pyi]\n\n[case testNewNamedTupleMissingClassAttribute]\nfrom typing import NamedTuple\n\nclass MyNamedTuple(NamedTuple):\n    a: int\n    b: str\n\nMyNamedTuple.x # E: \"type[MyNamedTuple]\" has no attribute \"x\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleEmptyItems]\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    ...\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleForwardRef]\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    b: 'B'\n\nclass B: ...\n\na = A(B())\na = A(1)  # E: Argument 1 to \"A\" has incompatible type \"int\"; expected \"B\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleProperty36]\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    a: int\n\nclass B(A):\n    @property\n    def b(self) -> int:\n        return self.a\nclass C(B): pass\nB(1).b\nC(2).b\n\n[builtins fixtures/property.pyi]\n\n[case testNewNamedTupleAsDict]\nfrom typing import NamedTuple, Any\n\nclass X(NamedTuple):\n    x: Any\n    y: Any\n\nx: X\nreveal_type(x._asdict())  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\n\n[builtins fixtures/dict.pyi]\n\n[case testNewNamedTupleReplaceTyped]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y: str\n\nx: X\nreveal_type(x._replace())  # N: Revealed type is \"tuple[builtins.int, builtins.str, fallback=__main__.X]\"\nx._replace(x=5)\nx._replace(y=5)  # E: Argument \"y\" to \"_replace\" of \"X\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleFields]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y: str\n\nreveal_type(X._fields)  # N: Revealed type is \"tuple[builtins.str, builtins.str]\"\nreveal_type(X._field_types)  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\nreveal_type(X._field_defaults)  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\n\n# In typeshed's stub for builtins.pyi, __annotations__ is `dict[str, Any]`,\n# but it's inferred as `Mapping[str, object]` here due to the fixture we're using\nreveal_type(X.__annotations__)  # N: Revealed type is \"typing.Mapping[builtins.str, builtins.object]\"\n\n[builtins fixtures/dict-full.pyi]\n\n[case testNewNamedTupleUnit]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    pass\n\nx: X = X()\nx._replace()\nx._fields[0]  # E: Tuple index out of range\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleJoinNamedTuple]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y: str\nclass Y(NamedTuple):\n    x: int\n    y: str\n\nreveal_type([X(3, 'b'), Y(1, 'a')])  # N: Revealed type is \"builtins.list[tuple[builtins.int, builtins.str]]\"\n\n[builtins fixtures/list.pyi]\n\n[case testNewNamedTupleJoinTuple]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y: str\n\nreveal_type([(3, 'b'), X(1, 'a')])  # N: Revealed type is \"builtins.list[tuple[builtins.int, builtins.str]]\"\nreveal_type([X(1, 'a'), (3, 'b')])  # N: Revealed type is \"builtins.list[tuple[builtins.int, builtins.str]]\"\n\n[builtins fixtures/list.pyi]\n\n[case testNewNamedTupleWithTooManyArguments]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y = z = 2  # E: Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\"\n    def f(self): pass\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleWithInvalidItems2]\nimport typing\n\nclass X(typing.NamedTuple):\n    x: int\n    y = 1  # E: Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\"\n    x.x: int  # E: Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\"\n    z: str = 'z'\n    aa: int  # E: Non-default NamedTuple fields cannot follow default fields\n[builtins fixtures/list.pyi]\n\n[case testNewNamedTupleWithoutTypesSpecified]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y = 2  # E: Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeUsingTypeCNamedTuple]\nfrom typing import NamedTuple, Type\n\nclass N(NamedTuple):\n    x: int\n    y: str\n\ndef f(a: Type[N]):\n    a()  # E: Missing positional arguments \"x\", \"y\" in call to \"N\"\n[builtins fixtures/list.pyi]\n\n[case testNewNamedTupleWithDefaults]\nfrom typing import List, NamedTuple, Optional\n\nclass X(NamedTuple):\n    x: int\n    y: int = 2\n\nreveal_type(X(1))  # N: Revealed type is \"tuple[builtins.int, builtins.int, fallback=__main__.X]\"\nreveal_type(X(1, 2))  # N: Revealed type is \"tuple[builtins.int, builtins.int, fallback=__main__.X]\"\n\nX(1, 'a')  # E: Argument 2 to \"X\" has incompatible type \"str\"; expected \"int\"\nX(1, z=3)  # E: Unexpected keyword argument \"z\" for \"X\"\n\nclass HasNone(NamedTuple):\n    x: int\n    y: Optional[int] = None\n\nreveal_type(HasNone(1))  # N: Revealed type is \"tuple[builtins.int, builtins.int | None, fallback=__main__.HasNone]\"\n\nclass Parameterized(NamedTuple):\n    x: int\n    y: List[int] = [1] + [2]\n    z: List[int] = []\n\nreveal_type(Parameterized(1))  # N: Revealed type is \"tuple[builtins.int, builtins.list[builtins.int], builtins.list[builtins.int], fallback=__main__.Parameterized]\"\nParameterized(1, ['not an int'])  # E: List item 0 has incompatible type \"str\"; expected \"int\"\n\nclass Default:\n    pass\n\nclass UserDefined(NamedTuple):\n    x: Default = Default()\n\nreveal_type(UserDefined())  # N: Revealed type is \"tuple[__main__.Default, fallback=__main__.UserDefined]\"\nreveal_type(UserDefined(Default()))  # N: Revealed type is \"tuple[__main__.Default, fallback=__main__.UserDefined]\"\nUserDefined(1)  # E: Argument 1 to \"UserDefined\" has incompatible type \"int\"; expected \"Default\"\n\n[builtins fixtures/list.pyi]\n\n[case testNewNamedTupleWithDefaultsStrictOptional]\nfrom typing import List, NamedTuple, Optional\n\nclass HasNone(NamedTuple):\n    x: int\n    y: Optional[int] = None\n\nreveal_type(HasNone(1))  # N: Revealed type is \"tuple[builtins.int, builtins.int | None, fallback=__main__.HasNone]\"\nHasNone(None)  # E: Argument 1 to \"HasNone\" has incompatible type \"None\"; expected \"int\"\nHasNone(1, y=None)\nHasNone(1, y=2)\n\nclass CannotBeNone(NamedTuple):\n    x: int\n    y: int = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\n[builtins fixtures/list.pyi]\n\n[case testNewNamedTupleWrongType]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int\n    y: int = 'not an int'  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleErrorInDefault]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: int = 1 + '1'  # E: Unsupported left operand type for + (\"int\")\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleInheritance]\nfrom typing import NamedTuple\n\nclass X(NamedTuple):\n    x: str\n    y: int = 3\n\nclass Y(X):\n    def method(self) -> str:\n        self.y\n        return self.x\n\nreveal_type(Y('a'))  # N: Revealed type is \"tuple[builtins.str, builtins.int, fallback=__main__.Y]\"\nY(y=1, x='1').method()\n\nclass CallsBaseInit(X):\n    def __init__(self, x: str) -> None:\n        super().__init__(x) # E: Too many arguments for \"__init__\" of \"object\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleWithMethods]\nfrom typing import NamedTuple\n\nclass XMeth(NamedTuple):\n    x: int\n    def double(self) -> int:\n        return self.x\n    async def asyncdouble(self) -> int:\n        return self.x\n\nclass XRepr(NamedTuple):\n    x: int\n    y: int = 1\n    def __str__(self) -> str:\n        return 'string'\n    def __sub__(self, other: XRepr) -> int:\n        return 0\n\nreveal_type(XMeth(1).double()) # N: Revealed type is \"builtins.int\"\n_ = reveal_type(XMeth(1).asyncdouble())  # N: Revealed type is \"typing.Coroutine[Any, Any, builtins.int]\"\nreveal_type(XMeth(42).x)  # N: Revealed type is \"builtins.int\"\nreveal_type(XRepr(42).__str__())  # N: Revealed type is \"builtins.str\"\nreveal_type(XRepr(1, 2).__sub__(XRepr(3)))  # N: Revealed type is \"builtins.int\"\n[typing fixtures/typing-async.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleOverloading]\nfrom typing import NamedTuple, overload\n\nclass Overloader(NamedTuple):\n    x: int\n    @overload\n    def method(self, y: str) -> str: pass\n    @overload\n    def method(self, y: int) -> int: pass\n    def method(self, y):\n        return y\n\nreveal_type(Overloader(1).method('string'))  # N: Revealed type is \"builtins.str\"\nreveal_type(Overloader(1).method(1))  # N: Revealed type is \"builtins.int\"\nOverloader(1).method(('tuple',))  # E: No overload variant of \"method\" of \"Overloader\" matches argument type \"tuple[str]\" \\\n                                  # N: Possible overload variants: \\\n                                  # N:     def method(self, y: str) -> str \\\n                                  # N:     def method(self, y: int) -> int\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleMethodInheritance]\nfrom typing import NamedTuple, TypeVar\n\nT = TypeVar('T')\n\nclass Base(NamedTuple):\n    x: int\n    def copy(self: T) -> T:\n        reveal_type(self)  # N: Revealed type is \"T`-1\"\n        return self\n    def good_override(self) -> int:\n        reveal_type(self)  # N: Revealed type is \"tuple[builtins.int, fallback=__main__.Base]\"\n        reveal_type(self[0])  # N: Revealed type is \"builtins.int\"\n        self[0] = 3  # E: Unsupported target for indexed assignment (\"Base\")\n        reveal_type(self.x)  # N: Revealed type is \"builtins.int\"\n        self.x = 3  # E: Property \"x\" defined in \"Base\" is read-only\n        self[1]  # E: Tuple index out of range\n        reveal_type(self[T])  # N: Revealed type is \"builtins.int\" \\\n                              # E: No overload variant of \"__getitem__\" of \"tuple\" matches argument type \"TypeVar\" \\\n                              # N: Possible overload variants: \\\n                              # N:     def __getitem__(self, int, /) -> int \\\n                              # N:     def __getitem__(self, slice, /) -> tuple[int, ...]\n        return self.x\n    def bad_override(self) -> int:\n        return self.x\n\nclass Child(Base):\n    def new_method(self) -> int:\n        reveal_type(self)  # N: Revealed type is \"tuple[builtins.int, fallback=__main__.Child]\"\n        reveal_type(self[0])  # N: Revealed type is \"builtins.int\"\n        self[0] = 3  # E: Unsupported target for indexed assignment (\"Child\")\n        reveal_type(self.x)  # N: Revealed type is \"builtins.int\"\n        self.x = 3  # E: Property \"x\" defined in \"Base\" is read-only\n        self[1]  # E: Tuple index out of range\n        return self.x\n    def good_override(self) -> int:\n        return 0\n    def bad_override(self) -> str:  # E: Return type \"str\" of \"bad_override\" incompatible with return type \"int\" in supertype \"Base\"\n        return 'incompatible'\n\ndef takes_base(base: Base) -> int:\n    return base.x\n\nreveal_type(Base(1).copy())  # N: Revealed type is \"tuple[builtins.int, fallback=__main__.Base]\"\nreveal_type(Child(1).copy())  # N: Revealed type is \"tuple[builtins.int, fallback=__main__.Child]\"\nreveal_type(Base(1).good_override())  # N: Revealed type is \"builtins.int\"\nreveal_type(Child(1).good_override())  # N: Revealed type is \"builtins.int\"\nreveal_type(Base(1).bad_override())  # N: Revealed type is \"builtins.int\"\nreveal_type(takes_base(Base(1)))  # N: Revealed type is \"builtins.int\"\nreveal_type(takes_base(Child(1)))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testNewNamedTupleIllegalNames]\nfrom typing import Callable, NamedTuple\n\nclass XMethBad(NamedTuple):\n    x: int\n    def _fields(self):  # E: Cannot overwrite NamedTuple attribute \"_fields\"\n        return 'no chance for this'\n\nclass MagicalFields(NamedTuple):\n    x: int\n    def __slots__(self) -> None: pass  # E: Cannot overwrite NamedTuple attribute \"__slots__\"\n    def __new__(cls) -> MagicalFields: pass  # E: Cannot overwrite NamedTuple attribute \"__new__\"\n    def _source(self) -> int: pass  # E: Cannot overwrite NamedTuple attribute \"_source\"\n    __annotations__ = {'x': float}  # E: NamedTuple field name cannot start with an underscore: __annotations__ \\\n        # E: Invalid statement in NamedTuple definition; expected \"field_name: field_type [= default]\" \\\n        # E: Cannot overwrite NamedTuple attribute \"__annotations__\"\n\nclass AnnotationsAsAMethod(NamedTuple):\n    x: int\n    # This fails at runtime because typing.py assumes that __annotations__ is a dictionary.\n    def __annotations__(self) -> float:  # E: Cannot overwrite NamedTuple attribute \"__annotations__\"\n        return 1.0\n\nclass ReuseNames(NamedTuple):\n    x: int\n    def x(self) -> str:  # E: Name \"x\" already defined on line 22\n        return ''\n\n    def y(self) -> int:\n        return 0\n    y: str  # E: Name \"y\" already defined on line 26\n\nclass ReuseCallableNamed(NamedTuple):\n    z: Callable[[ReuseNames], int]\n    def z(self) -> int:  # E: Name \"z\" already defined on line 31\n        return 0\n\n[builtins fixtures/dict.pyi]\n\n[case testNewNamedTupleDocString]\nfrom typing import NamedTuple\n\nclass Documented(NamedTuple):\n    \"\"\"This is a docstring.\"\"\"\n    x: int\n\nreveal_type(Documented.__doc__)  # N: Revealed type is \"builtins.str\"\nreveal_type(Documented(1).x)  # N: Revealed type is \"builtins.int\"\n\nclass BadDoc(NamedTuple):\n    x: int\n    def __doc__(self) -> str:\n        return ''\n\nreveal_type(BadDoc(1).__doc__())  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewNamedTupleClassMethod]\nfrom typing import NamedTuple\n\nclass HasClassMethod(NamedTuple):\n    x: str\n\n    @classmethod\n    def new(cls, f: str) -> 'HasClassMethod':\n        reveal_type(cls)  # N: Revealed type is \"type[tuple[builtins.str, fallback=__main__.HasClassMethod]]\"\n        reveal_type(HasClassMethod)  # N: Revealed type is \"def (x: builtins.str) -> tuple[builtins.str, fallback=__main__.HasClassMethod]\"\n        return cls(x=f)\n\n[builtins fixtures/classmethod.pyi]\n\n[case testNewNamedTupleStaticMethod]\nfrom typing import NamedTuple\n\nclass HasStaticMethod(NamedTuple):\n    x: str\n\n    @staticmethod\n    def new(f: str) -> 'HasStaticMethod':\n        return HasStaticMethod(x=f)\n\n[builtins fixtures/classmethod.pyi]\n\n[case testNewNamedTupleProperty]\nfrom typing import NamedTuple\n\nclass HasStaticMethod(NamedTuple):\n    x: str\n\n    @property\n    def size(self) -> int:\n        reveal_type(self)  # N: Revealed type is \"tuple[builtins.str, fallback=__main__.HasStaticMethod]\"\n        return 4\n\n[builtins fixtures/property.pyi]\n\n[case testTypingExtensionsNamedTuple]\nfrom typing_extensions import NamedTuple\n\nclass Point(NamedTuple):\n    x: int\n    y: int\n\nbad_point = Point('foo') # E: Missing positional argument \"y\" in call to \"Point\" \\\n                         # E: Argument 1 to \"Point\" has incompatible type \"str\"; expected \"int\"\npoint = Point(1, 2)\nx, y = point\nx = point.x\nreveal_type(x) # N: Revealed type is \"builtins.int\"\nreveal_type(y) # N: Revealed type is \"builtins.int\"\npoint.y = 6 # E: Property \"y\" defined in \"Point\" is read-only\n\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-classes.test",
    "content": "-- Methods\n-- -------\n\n\n[case testMethodCall]\nclass A:\n    def foo(self, x: 'A') -> None: pass\nclass B:\n    def bar(self, x: 'B', y: A) -> None: pass\n\na: A\nb: B\n\na.foo(B())  # E: Argument 1 to \"foo\" of \"A\" has incompatible type \"B\"; expected \"A\"\na.bar(B(), A())  # E: \"A\" has no attribute \"bar\"\n\na.foo(A())\nb.bar(B(), A())\n\n[case testMethodCallWithSubtype]\nclass A:\n    def foo(self, x: 'A') -> None: pass\n    def bar(self, x: 'B') -> None: pass\nclass B(A): pass\n\na: A\na.foo(A())\na.foo(B())\na.bar(A()) # E: Argument 1 to \"bar\" of \"A\" has incompatible type \"A\"; expected \"B\"\na.bar(B())\n\n[case testInheritingMethod]\nclass A:\n    def foo(self, x: 'B') -> None: pass\nclass B(A): pass\n\na: B\na.foo(A()) # Fail\na.foo(B())\n\n[targets __main__, __main__.A.foo]\n[out]\nmain:6: error: Argument 1 to \"foo\" of \"A\" has incompatible type \"A\"; expected \"B\"\n\n[case testMethodCallWithInvalidNumberOfArguments]\nclass A:\n    def foo(self, x: 'A') -> None: pass\n\na: A\na.foo()               # Fail\na.foo(object(), A())  # Fail\n[out]\nmain:5: error: Missing positional argument \"x\" in call to \"foo\" of \"A\"\nmain:6: error: Too many arguments for \"foo\" of \"A\"\nmain:6: error: Argument 1 to \"foo\" of \"A\" has incompatible type \"object\"; expected \"A\"\n\n[case testMethodBody]\nimport typing\nclass A:\n    def f(self) -> None:\n        a = object() # type: A    # Fail\n[out]\nmain:4: error: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n\n[case testMethodArguments]\nimport typing\nclass A:\n    def f(self, a: 'A', b: 'B') -> None:\n        if int():\n            a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n            b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n            a = A()\n            b = B()\n            a = a\n            a = b # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nclass B: pass\n[out]\n\n[case testReturnFromMethod]\nimport typing\nclass A:\n    def f(self) -> 'A':\n        return B() # Fail\n        return A()\nclass B: pass\n[out]\nmain:4: error: Incompatible return value type (got \"B\", expected \"A\")\n\n[case testSelfArgument]\nimport typing\nclass A:\n    def f(self) -> None:\n        o = self # type: B    # Fail\n        self.g()      # Fail\n        a = self # type: A\n        self.f()\nclass B: pass\n[out]\nmain:4: error: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nmain:5: error: \"A\" has no attribute \"g\"\n\n[case testAssignToMethodViaInstance]\nimport typing\nclass A:\n    def f(self): pass\nA().f = None  # E: Cannot assign to a method \\\n              # E: Incompatible types in assignment (expression has type \"None\", variable has type \"Callable[[], Any]\")\n\n\n[case testOverrideAttributeWithMethod]\n# This was crashing:\n# https://github.com/python/mypy/issues/10134\nfrom typing import Protocol\n\nclass Base:\n    __hash__: None = None\n\nclass Derived(Base):\n    def __hash__(self) -> int:  # E: Signature of \"__hash__\" incompatible with supertype \"Base\" \\\n                                # N:      Superclass: \\\n                                # N:          None \\\n                                # N:      Subclass: \\\n                                # N:          def __hash__(self) -> int\n        pass\n\n# Correct:\n\nclass CallableProtocol(Protocol):\n    def __call__(self, arg: int) -> int:\n        pass\n\nclass CorrectBase:\n    attr: CallableProtocol\n\nclass CorrectDerived(CorrectBase):\n    def attr(self, arg: int) -> int:\n        pass\n\n[case testOverrideMethodWithAttribute]\n# The reverse should not crash as well:\nfrom typing import Callable\n\nclass Base:\n    def __hash__(self) -> int:\n        pass\n\nclass Derived(Base):\n    __hash__ = 1  # E: Incompatible types in assignment (expression has type \"int\", base class \"Base\" defined the type as \"Callable[[], int]\")\n\n[case testOverridePartialAttributeWithMethod]\n# This was crashing: https://github.com/python/mypy/issues/11686.\nclass Base:\n    def __init__(self, arg: int):\n        self.partial_type = []  # E: Need type annotation for \"partial_type\" (hint: \"partial_type: list[<type>] = ...\")\n        self.force_deferral = []\n\n    # Force inference of the `force_deferral` attribute in `__init__` to be\n    # deferred to a later pass by providing a definition in another context,\n    # which means `partial_type` remains only partially inferred.\n    force_deferral = []  # E: Need type annotation for \"force_deferral\" (hint: \"force_deferral: list[<type>] = ...\")\n\n\nclass Derived(Base):\n    def partial_type(self) -> int:  # E: Signature of \"partial_type\" incompatible with supertype \"Base\" \\\n                                    # N:      Superclass: \\\n                                    # N:          list[Any] \\\n                                    # N:      Subclass: \\\n                                    # N:          def partial_type(self) -> int\n        ...\n\n\n-- Attributes\n-- ----------\n\n\n[case testReferToInvalidAttribute]\n\nclass A:\n    def __init__(self) -> None:\n        self.x = object()\na: A\na.y  # E: \"A\" has no attribute \"y\"\na.y = object()  # E: \"A\" has no attribute \"y\"\na.x\na.x = object()\n\n[case testReferToInvalidAttributeUnannotatedInit]\nclass A:\n    def __init__(self):\n        self.x = object()\n\na: A\na.y  # E: \"A\" has no attribute \"y\"\na.y = object()  # E: \"A\" has no attribute \"y\"\na.x\na.x = object()\n\n[case testArgumentTypeInference]\n\nclass A:\n    def __init__(self, aa: 'A', bb: 'B') -> None:\n        self.a = aa\n        self.b = bb\nclass B: pass\na: A\nb: B\na.a = b # Fail\na.b = a # Fail\nb.a     # Fail\na.a = a\na.b = b\n[out]\nmain:9: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nmain:10: error: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nmain:11: error: \"B\" has no attribute \"a\"\n\n[case testExplicitAttributeInBody]\n\nclass A:\n  x: A\na: A\na.x = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\na.x = A()\n\n[case testAttributeDefinedInNonInitMethod]\nimport typing\nclass A:\n    def f(self) -> None:\n        self.x = 1\n        self.y = ''\n        self.x = 1\na = A()\na.x = 1\na.y = ''\na.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\na.z = 0  # E: \"A\" has no attribute \"z\"\n\n[case testInheritanceAndAttributeAssignment]\nimport typing\nclass A:\n    def f(self) -> None:\n        self.x = 0\nclass B(A):\n    def f(self) -> None:\n        self.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[targets __main__, __main__.A.f, __main__.B.f]\n\n[case testAssignmentToAttributeInMultipleMethods]\nimport typing\nclass A:\n    def f(self) -> None:\n        self.x = 0\n    def g(self) -> None:\n        self.x = '' # Fail\n    def __init__(self) -> None:\n        self.x = '' # Fail\n[out]\nmain:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nmain:8: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testClassNamesDefinedOnSelUsedInClassBody]\nclass A(object):\n    def f(self):\n        self.attr = 1\n    attr = 0\n\nclass B(object):\n    attr = 0\n    def f(self):\n        self.attr = 1\n\nclass C(object):\n    attr = 0\n    def f(self):\n        self.attr = 1\n    attr = 0\n\nclass D(object):\n    def g(self):\n        self.attr = 1\n    attr = 0\n    def f(self):\n        self.attr = 1\n[out]\n\n[case testClassNamesDefinedOnSelUsedInClassBodyReveal]\n\nclass A(object):\n    def f(self) -> None:\n        self.attr = 1\n    attr  # E: Name \"attr\" is not defined\n\nclass B(object):\n    attr = 0\n    def f(self) -> None:\n        reveal_type(self.attr)  # N: Revealed type is \"builtins.int\"\n[out]\n\n\n-- Method overriding\n-- -----------------\n\n\n[case testMethodOverridingWithIdenticalSignature]\nimport typing\nclass A:\n    def f(self, x: 'A') -> None: pass\n    def g(self, x: 'B' , y: object) -> 'A': pass\n    def h(self) -> None: pass\nclass B(A):\n    def f(self, x: A) -> None: pass\n    def g(self, x: 'B' , y: object) -> A: pass\n    def h(self) -> None: pass\n[out]\n\n[case testMethodOverridingWithCovariantType]\nimport typing\nclass A:\n  def f(self, x: 'A', y: 'B') -> 'A': pass\n  def g(self, x: 'A', y: 'B') -> 'A': pass\nclass B(A):\n  def f(self, x: A, y: 'B') -> 'B': pass\n  def g(self, x: A, y: A) -> 'A': pass\n[out]\n\n[case testMethodOverridingWithIncompatibleTypes]\nimport typing\nclass A:\n  def f(self, x: 'A', y: 'B') -> 'A': pass\n  def g(self, x: 'A', y: 'B') -> 'A': pass\n  def h(self, x: 'A', y: 'B') -> 'A': pass\nclass B(A):\n  def f(self, x: 'B', y: 'B') -> A: pass  # Fail\n  def g(self, x: A, y: A) -> A: pass\n  def h(self, x: A, y: 'B') -> object: pass  # Fail\n[out]\nmain:7: error: Argument 1 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"A\"\nmain:7: note: This violates the Liskov substitution principle\nmain:7: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\nmain:9: error: Return type \"object\" of \"h\" incompatible with return type \"A\" in supertype \"A\"\n\n[case testMethodOverridingWithIncompatibleTypesOnMultipleLines]\nclass A:\n    def f(self, x: int, y: str) -> None: pass\nclass B(A):\n    def f(\n        self,\n        x: int,\n        y: bool,\n    ) -> None:\n        pass\n[out]\nmain:7: error: Argument 2 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"str\"\nmain:7: note: This violates the Liskov substitution principle\nmain:7: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n\n[case testMultiLineMethodOverridingWithIncompatibleTypesIgnorableAtArgument]\nclass A:\n    def f(self, x: int, y: str) -> None: pass\n\nclass B(A):\n    def f(\n        self,\n        x: int,\n        y: bool,  # type: ignore[override]\n    ) -> None:\n        pass\n\n[case testMultiLineMethodOverridingWithIncompatibleTypesIgnorableAtDefinition]\nclass A:\n    def f(self, x: int, y: str) -> None: pass\nclass B(A):\n    def f(  # type: ignore[override]\n        self,\n        x: int,\n        y: bool,\n    ) -> None:\n        pass\n\n[case testMultiLineMethodOverridingWithIncompatibleTypesWrongIgnore]\nclass A:\n    def f(self, x: int, y: str) -> None: pass\nclass B(A):\n    def f(  # type: ignore[return-type]\n        self,\n        x: int,\n        y: bool,\n    ) -> None:\n        pass\n[out]\nmain:7: error: Argument 2 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"str\"\nmain:7: note: This violates the Liskov substitution principle\nmain:7: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n\n[case testEqMethodsOverridingWithNonObjects]\nclass A:\n  def __eq__(self, other: A) -> bool: pass  # Fail\n[builtins fixtures/plugin_attrs.pyi]\n[out]\nmain:2: error: Argument 1 of \"__eq__\" is incompatible with supertype \"builtins.object\"; supertype defines the argument type as \"object\"\nmain:2: note: This violates the Liskov substitution principle\nmain:2: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\nmain:2: note: It is recommended for \"__eq__\" to work with arbitrary objects, for example:\nmain:2: note:     def __eq__(self, other: object) -> bool:\nmain:2: note:         if not isinstance(other, A):\nmain:2: note:             return NotImplemented\nmain:2: note:         return <logic to compare two A instances>\n\n[case testMethodOverridingWithIncompatibleArgumentCount]\nimport typing\nclass A:\n    def f(self, x: 'A') -> None: pass\n    def g(self, x: 'A', y: 'B') -> 'A': pass\nclass B(A):\n    def f(self, x: A, y: A) -> None: pass # Fail\n    def g(self, x: A) -> A: pass # Fail\n[out]\nmain:6: error: Signature of \"f\" incompatible with supertype \"A\"\nmain:6: note:      Superclass:\nmain:6: note:          def f(self, x: A) -> None\nmain:6: note:      Subclass:\nmain:6: note:          def f(self, x: A, y: A) -> None\nmain:7: error: Signature of \"g\" incompatible with supertype \"A\"\nmain:7: note:      Superclass:\nmain:7: note:          def g(self, x: A, y: B) -> A\nmain:7: note:      Subclass:\nmain:7: note:          def g(self, x: A) -> A\n\n[case testMethodOverridingAcrossDeepInheritanceHierarchy1]\nimport typing\nclass A:\n    def f(self, x: 'B') -> None: pass\nclass B(A): pass\nclass C(B): # with gap in implementations\n    def f(self, x: 'C') -> None:  # Fail\n        pass\n[out]\nmain:6: error: Argument 1 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"B\"\nmain:6: note: This violates the Liskov substitution principle\nmain:6: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n\n[case testMethodOverridingAcrossDeepInheritanceHierarchy2]\nimport typing\nclass A:\n    def f(self) -> 'B': pass\nclass B(A):\n    def f(self) -> 'C': pass\nclass C(B): # with multiple implementations\n    def f(self) -> B:  # Fail\n        pass\n[out]\nmain:7: error: Return type \"B\" of \"f\" incompatible with return type \"C\" in supertype \"B\"\n\n[case testMethodOverridingWithVoidReturnValue]\nimport typing\nclass A:\n    def f(self) -> None: pass\n    def g(self) -> 'A': pass\nclass B(A):\n    def f(self) -> A: pass  # Fail\n    def g(self) -> None: pass  # Fail\n[out]\nmain:6: error: Return type \"A\" of \"f\" incompatible with return type \"None\" in supertype \"A\"\nmain:7: error: Return type \"None\" of \"g\" incompatible with return type \"A\" in supertype \"A\"\n\n[case testOverride__new__WithDifferentSignature]\nclass A:\n    def __new__(cls, x: int) -> A:\n        pass\n\nclass B(A):\n    def __new__(cls) -> B:\n        pass\n\n[case testOverride__new__WithLiteralReturnPassing]\nfrom typing import Literal\n\nclass Falsy:\n    def __bool__(self) -> Literal[False]: pass\n\nreveal_type(bool(Falsy()))  # N: Revealed type is \"Literal[False]\"\nreveal_type(int())  # N: Revealed type is \"Literal[0]\"\n\n[builtins fixtures/literal__new__.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverride__new__WithLiteralReturnFailing]\nfrom typing import Literal\n\nclass Foo:\n    def __new__(cls) -> Literal[1]: pass # E: Incompatible return type for \"__new__\" (returns \"Literal[1]\", but must return a subtype of \"Foo\")\n\n[builtins fixtures/__new__.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testOverride__new__AndCallObject]\nfrom typing import TypeVar, Generic\n\nclass A:\n    def __new__(cls, x: int) -> 'A':\n        return object.__new__(cls)\n\nT = TypeVar('T')\nclass B(Generic[T]):\n    def __new__(cls, foo: T) -> 'B[T]':\n        x = object.__new__(cls)\n        # object.__new__ doesn't have a great type :(\n        reveal_type(x)  # N: Revealed type is \"Any\"\n        return x\n\n[builtins fixtures/__new__.pyi]\n\n[case testInnerFunctionNotOverriding]\nclass A:\n    def f(self) -> int: pass\n\nclass B(A):\n    def g(self) -> None:\n        def f(self) -> str: pass\n\n[case testOverride__init_subclass__WithDifferentSignature]\nclass A:\n    def __init_subclass__(cls, x: int) -> None: pass\nclass B(A):  # E: Missing positional argument \"x\" in call to \"__init_subclass__\" of \"A\"\n    def __init_subclass__(cls) -> None: pass\n\n[case testOverrideWithDecorator]\nfrom typing import Callable\n\ndef int_to_none(f: Callable[..., int]) -> Callable[..., None]: ...\ndef str_to_int(f: Callable[..., str]) -> Callable[..., int]: ...\n\nclass A:\n    def f(self) -> None: pass\n    def g(self) -> str: pass\n    def h(self) -> None: pass\n\nclass B(A):\n    @int_to_none\n    def f(self) -> int: pass\n    @str_to_int\n    def g(self) -> str: pass # Fail\n    @int_to_none\n    @str_to_int\n    def h(self) -> str: pass\n[out]\nmain:15: error: Signature of \"g\" incompatible with supertype \"A\"\nmain:15: note:      Superclass:\nmain:15: note:          def g(self) -> str\nmain:15: note:      Subclass:\nmain:15: note:          def g(*Any, **Any) -> int\n\n[case testOverrideDecorated]\nfrom typing import Callable\n\ndef str_to_int(f: Callable[..., str]) -> Callable[..., int]: ...\n\nclass A:\n    @str_to_int\n    def f(self) -> str: pass\n    @str_to_int\n    def g(self) -> str: pass\n    @str_to_int\n    def h(self) -> str: pass\n\nclass B(A):\n    def f(self) -> int: pass\n    def g(self) -> str: pass # Fail\n    @str_to_int\n    def h(self) -> str: pass\n[out]\nmain:15: error: Signature of \"g\" incompatible with supertype \"A\"\nmain:15: note:      Superclass:\nmain:15: note:          def g(*Any, **Any) -> int\nmain:15: note:      Subclass:\nmain:15: note:          def g(self) -> str\n\n[case testOverrideWithDecoratorReturningAny]\ndef dec(f): pass\n\nclass A:\n    def f(self) -> str: pass\n\nclass B(A):\n    @dec\n    def f(self) -> int: pass\n\n[case testOverrideWithDecoratorReturningCallable]\nfrom typing import Any, Callable, TypeVar\n\nclass Base:\n    def get(self, a: str) -> None: ...\n\ndef dec(fn: Any) -> Callable[[Any, int], None]: ...\n\nclass Derived(Base):\n    @dec\n    def get(self) -> None: ...  # E: Argument 1 of \"get\" is incompatible with supertype \"Base\"; supertype defines the argument type as \"str\" \\\n                                # N: This violates the Liskov substitution principle \\\n                                # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n[builtins fixtures/tuple.pyi]\n\n[case testOverrideWithDecoratorReturningCallable2]\n# flags: --pretty\nfrom typing import Any, Callable, TypeVar\n\n_C = TypeVar(\"_C\", bound=Callable[..., Any])\n\ndef infer_signature(f: _C) -> Callable[[Any], _C]: ...\n\nclass Base:\n    def get(self, a: str, b: str, c: str) -> None: ...\n    def post(self, a: str, b: str) -> None: ...\n\n# Third argument incompatible\ndef get(self, a: str, b: str, c: int) -> None: ...\n\n# Second argument incompatible - still should not map to **kwargs\ndef post(self, a: str, b: int) -> None: ...\n\nclass Derived(Base):\n    @infer_signature(get)\n    def get(self, *args: Any, **kwargs: Any) -> None: ...\n\n    @infer_signature(post)\n    def post(self, *args: Any, **kwargs: Any) -> None: ...\n[builtins fixtures/tuple.pyi]\n[out]\nmain:20: error: Argument 3 of \"get\" is incompatible with supertype \"Base\"; supertype defines the argument type as \"str\"\n        def get(self, *args: Any, **kwargs: Any) -> None: ...\n        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmain:20: note: This violates the Liskov substitution principle\nmain:20: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\nmain:23: error: Argument 2 of \"post\" is incompatible with supertype \"Base\"; supertype defines the argument type as \"str\"\n        def post(self, *args: Any, **kwargs: Any) -> None: ...\n        ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\nmain:23: note: This violates the Liskov substitution principle\nmain:23: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n\n[case testOverrideWithDecoratorReturningInstance]\ndef dec(f) -> str: pass\n\nclass A:\n    def f(self) -> str: pass\n    @dec\n    def g(self) -> int: pass\n    @dec\n    def h(self) -> int: pass\n\nclass B(A):\n    @dec\n    def f(self) -> int: pass # E: Signature of \"f\" incompatible with supertype \"A\" \\\n                             # N:      Superclass: \\\n                             # N:          def f(self) -> str \\\n                             # N:      Subclass: \\\n                             # N:          str\n    def g(self) -> int: pass # E: Signature of \"g\" incompatible with supertype \"A\" \\\n                             # N:      Superclass: \\\n                             # N:          str \\\n                             # N:      Subclass: \\\n                             # N:          def g(self) -> int\n    @dec\n    def h(self) -> str: pass\n\n[case testOverrideIncompatibleWithMultipleSupertypes]\nclass A:\n    def f(self, *, a: int) -> None:\n        return\n\nclass B(A):\n    def f(self, *, b: int) -> None:  # E: Signature of \"f\" incompatible with supertype \"A\" \\\n                                     # N:      Superclass: \\\n                                     # N:          def f(self, *, a: int) -> None \\\n                                     # N:      Subclass: \\\n                                     # N:          def f(self, *, b: int) -> None\n        return\n\nclass C(B):\n    def f(self, *, c: int) -> None:  # E: Signature of \"f\" incompatible with supertype \"B\" \\\n                                     # N:      Superclass: \\\n                                     # N:          def f(self, *, b: int) -> None \\\n                                     # N:      Subclass: \\\n                                     # N:          def f(self, *, c: int) -> None \\\n                                     # E: Signature of \"f\" incompatible with supertype \"A\" \\\n                                     # N:      Superclass: \\\n                                     # N:          def f(self, *, a: int) -> None \\\n                                     # N:      Subclass: \\\n                                     # N:          def f(self, *, c: int) -> None\n        return\n\n[case testOverrideStaticMethodWithStaticMethod]\nclass A:\n    @staticmethod\n    def f(x: int, y: str) -> None: pass\n    @staticmethod\n    def g(x: int, y: str) -> None: pass\n\nclass B(A):\n    @staticmethod\n    def f(x: int, y: str) -> None: pass\n    @staticmethod\n    def g(x: str, y: str) -> None: pass # E: Argument 1 of \"g\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\" \\\n                                        # N: This violates the Liskov substitution principle \\\n                                        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n[builtins fixtures/classmethod.pyi]\n\n[case testOverrideClassMethodWithClassMethod]\nclass A:\n    @classmethod\n    def f(cls, x: int, y: str) -> None: pass\n    @classmethod\n    def g(cls, x: int, y: str) -> None: pass\n\nclass B(A):\n    @classmethod\n    def f(cls, x: int, y: str) -> None: pass\n    @classmethod\n    def g(cls, x: str, y: str) -> None: pass # E: Argument 1 of \"g\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\" \\\n                                             # N: This violates the Liskov substitution principle \\\n                                             # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n[builtins fixtures/classmethod.pyi]\n\n[case testOverrideClassMethodWithStaticMethod]\nclass A:\n    @classmethod\n    def f(cls, x: int) -> None: pass\n    @classmethod\n    def g(cls, x: int) -> int: pass\n    @classmethod\n    def h(cls) -> int: pass\n\nclass B(A):\n    @staticmethod\n    def f(x: int) -> None: pass\n    @staticmethod\n    def g(x: str) -> int: pass # E: Argument 1 of \"g\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\" \\\n                               # N: This violates the Liskov substitution principle \\\n                               # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n    @staticmethod\n    def h() -> int: pass\n[builtins fixtures/classmethod.pyi]\n\n[case testOverrideStaticMethodWithClassMethod]\nclass A:\n    @staticmethod\n    def f(x: int) -> None: pass\n    @staticmethod\n    def g(x: str) -> int: pass\n    @staticmethod\n    def h() -> int: pass\n\nclass B(A):\n    @classmethod\n    def f(cls, x: int) -> None: pass\n    @classmethod\n    def g(cls, x: int) -> int: pass # E: Argument 1 of \"g\" is incompatible with supertype \"A\"; supertype defines the argument type as \"str\" \\\n                                    # N: This violates the Liskov substitution principle \\\n                                    # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n    @classmethod\n    def h(cls) -> int: pass\n[builtins fixtures/classmethod.pyi]\n\n[case testOverrideReplaceMethod]\n# flags: --show-error-codes\nfrom typing import Optional\nfrom typing_extensions import Self\nclass A:\n    def __replace__(self, x: Optional[str]) -> Self: pass\n\nclass B(A):\n    def __replace__(self, x: str) -> Self: pass # E: \\\n        # E: Argument 1 of \"__replace__\" is incompatible with supertype \"A\"; supertype defines the argument type as \"str | None\"  [override] \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n[builtins fixtures/tuple.pyi]\n\n[case testAllowCovarianceInReadOnlyAttributes]\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T')\n\nclass X:\n    pass\n\n\nclass Y(X):\n    pass\n\ndef dec(f: Callable[..., T]) -> T: pass\n\nclass A:\n    @dec\n    def f(self) -> X: pass\n\nclass B(A):\n    @dec\n    def f(self) -> Y: pass\n\n[case testOverrideCallableAttributeWithMethod]\nfrom typing import Callable\n\nclass A:\n    f1: Callable[[str], None]\n    f2: Callable[[str], None]\n    f3: Callable[[str], None]\n\nclass B(A):\n    def f1(self, x: object) -> None:\n        pass\n\n    @classmethod\n    def f2(cls, x: object) -> None:\n        pass\n\n    @staticmethod\n    def f3(x: object) -> None:\n        pass\n[builtins fixtures/classmethod.pyi]\n\n[case testOverrideCallableAttributeWithMethodMutableOverride]\n# flags: --enable-error-code=mutable-override\nfrom typing import Callable\n\nclass A:\n    f1: Callable[[str], None]\n    f2: Callable[[str], None]\n    f3: Callable[[str], None]\n\nclass B(A):\n    def f1(self, x: object) -> None: pass   # E: Covariant override of a mutable attribute (base class \"A\" defined the type as \"Callable[[str], None]\", override has type \"Callable[[object], None]\")\n\n    @classmethod\n    def f2(cls, x: object) -> None: pass    # E: Covariant override of a mutable attribute (base class \"A\" defined the type as \"Callable[[str], None]\", override has type \"Callable[[object], None]\")\n\n    @staticmethod\n    def f3(x: object) -> None: pass         # E: Covariant override of a mutable attribute (base class \"A\" defined the type as \"Callable[[str], None]\", override has type \"Callable[[object], None]\")\n[builtins fixtures/classmethod.pyi]\n\n[case testOverrideCallableAttributeWithSettableProperty]\nfrom typing import Callable\n\nclass A:\n    f: Callable[[str], None]\n\nclass B(A):\n    @property\n    def f(self) -> Callable[[object], None]: pass\n    @f.setter\n    def f(self, x: object) -> None: pass\n[builtins fixtures/property.pyi]\n\n[case testOverrideCallableAttributeWithSettablePropertyMutableOverride]\n# flags: --enable-error-code=mutable-override\nfrom typing import Callable\n\nclass A:\n    f: Callable[[str], None]\n\nclass B(A):\n    @property\n    def f(self) -> Callable[[object], None]: pass\n    @f.setter\n    def f(self, x: object) -> None: pass\n[builtins fixtures/property.pyi]\n\n[case testOverrideCallableUnionAttributeWithMethod]\nfrom typing import Callable, Union\n\nclass A:\n    f1: Union[Callable[[str], str], str]\n    f2: Union[Callable[[str], str], str]\n    f3: Union[Callable[[str], str], str]\n    f4: Union[Callable[[str], str], str]\n\nclass B(A):\n    def f1(self, x: str) -> str:\n        pass\n\n    def f2(self, x: object) -> str:\n        pass\n\n    @classmethod\n    def f3(cls, x: str) -> str:\n        pass\n\n    @staticmethod\n    def f4(x: str) -> str:\n        pass\n[builtins fixtures/classmethod.pyi]\n\n[case testOverrideCallableUnionAttributeWithMethodMutableOverride]\n# flags: --enable-error-code=mutable-override\nfrom typing import Callable, Union\n\nclass A:\n    f1: Union[Callable[[str], str], str]\n    f2: Union[Callable[[str], str], str]\n    f3: Union[Callable[[str], str], str]\n    f4: Union[Callable[[str], str], str]\n\nclass B(A):\n    def f1(self, x: str) -> str:     # E: Covariant override of a mutable attribute (base class \"A\" defined the type as \"Callable[[str], str] | str\", override has type \"Callable[[str], str]\")\n        pass\n\n    def f2(self, x: object) -> str:  # E: Covariant override of a mutable attribute (base class \"A\" defined the type as \"Callable[[str], str] | str\", override has type \"Callable[[object], str]\")\n        pass\n\n    @classmethod\n    def f3(cls, x: str) -> str:      # E: Covariant override of a mutable attribute (base class \"A\" defined the type as \"Callable[[str], str] | str\", override has type \"Callable[[str], str]\")\n        pass\n\n    @staticmethod\n    def f4(x: str) -> str:           # E: Covariant override of a mutable attribute (base class \"A\" defined the type as \"Callable[[str], str] | str\", override has type \"Callable[[str], str]\")\n        pass\n[builtins fixtures/classmethod.pyi]\n\n-- Constructors\n-- ------------\n\n\n[case testTrivialConstructor]\nclass A:\n    def __init__(self) -> None: pass\n\na = A() # type: A\nb = A() # type: B # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nclass B: pass\n[case testConstructor]\nclass A:\n    def __init__(self, x: 'B') -> None: pass\nclass B: pass\n\na = A(B()) # type: A\naa = A(object()) # type: A  # E: Argument 1 to \"A\" has incompatible type \"object\"; expected \"B\"\nb = A(B()) # type: B # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n[case testConstructorWithTwoArguments]\nclass A:\n    def __init__(self, x: 'B', y: 'C') -> None: pass\nclass B: pass\nclass C(B): pass\n\na = A(C(), B()) # type: A  # E: Argument 2 to \"A\" has incompatible type \"B\"; expected \"C\"\n\n[case testInheritedConstructor]\nclass B(A): pass\nclass C: pass\nclass D: pass\n\nb = B(C()) # type: B\na = B(D()) # type: A # E: Argument 1 to \"B\" has incompatible type \"D\"; expected \"C\"\nclass A:\n    def __init__(self, x: 'C') -> None: pass\n\n[case testOverridingWithIncompatibleConstructor]\nclass A:\n    def __init__(self, x: 'C') -> None: pass\nclass B(A):\n    def __init__(self) -> None: pass\nclass C: pass\n\nA()    # E: Missing positional argument \"x\" in call to \"A\"\nB(C()) # E: Too many arguments for \"B\"\nA(C())\nB()\n\n[case testConstructorWithReturnValueType]\nimport typing\nclass A:\n    def __init__(self) -> 'A': pass\n[out]\nmain:3: error: The return type of \"__init__\" must be None\n\n[case testConstructorWithImplicitReturnValueType]\nimport typing\nclass A:\n    def __init__(self, x: int): pass\n[out]\n\n[case testDecoratedConstructorWithImplicitReturnValueType]\nimport typing\nfrom typing import Callable\n\ndef deco(fn: Callable) -> Callable:\n    return fn\n\nclass A:\n    @deco\n    def __init__(self, x: int): pass\n[out]\n\n[case testOverloadedConstructorWithImplicitReturnValueType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass Foo:\n    @overload\n    def __init__(self, a: int):\n        pass\n\n    @overload\n    def __init__(self, a: str):\n        pass\n\n[case testConstructorWithAnyReturnValueType]\nimport typing\nfrom typing import Any\nclass A:\n    def __init__(self) -> Any: pass # E: The return type of \"__init__\" must be None\n\n[case testDecoratedConstructorWithAnyReturnValueType]\nimport typing\nfrom typing import Callable, Any\n\ndef deco(fn: Callable) -> Callable:\n    return fn\n\nclass A:\n    @deco\n    def __init__(self) -> Any: pass # E: The return type of \"__init__\" must be None\n\n[case testOverloadedConstructorWithAnyReturnValueType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Any\nclass Foo:\n    @overload\n    def __init__(self, a: int) -> Any: # E: The return type of \"__init__\" must be None\n        pass\n\n    @overload\n    def __init__(self, a: str) -> Any: # E: The return type of \"__init__\" must be None\n        pass\n\n[case testInitSubclassWithReturnValueType]\nimport typing\nclass A:\n    def __init_subclass__(cls) -> 'A': pass\n[out]\nmain:3: error: The return type of \"__init_subclass__\" must be None\n\n[case testInitSubclassWithImplicitReturnValueType]\nimport typing\nclass A:\n    def __init_subclass__(cls, x: int=1): pass\n[out]\n\n[case testDecoratedInitSubclassWithImplicitReturnValueType]\nimport typing\nfrom typing import Callable\n\ndef deco(fn: Callable) -> Callable:\n    return fn\n\nclass A:\n    @deco\n    def __init_subclass__(cls, x: int=1): pass\n[out]\n\n[case testOverloadedInitSubclassWithImplicitReturnValueType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass Foo:\n    @overload\n    def __init_subclass__(cls, a: int):\n        pass\n\n    @overload\n    def __init_subclass__(cls, a: str):\n        pass\n\n[case testInitSubclassWithAnyReturnValueType]\nimport typing\nfrom typing import Any\nclass A:\n    def __init_subclass__(cls) -> Any: pass # E: The return type of \"__init_subclass__\" must be None\n\n[case testDecoratedInitSubclassWithAnyReturnValueType]\nimport typing\nfrom typing import Callable, Any\n\ndef deco(fn: Callable) -> Callable:\n    return fn\n\nclass A:\n    @deco\n    def __init_subclass__(cls) -> Any: pass # E: The return type of \"__init_subclass__\" must be None\n[out]\n\n[case testOverloadedInitSubclassWithAnyReturnValueType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Any\nclass Foo:\n    @overload\n    def __init_subclass__(cls, a: int) -> Any: # E: The return type of \"__init_subclass__\" must be None\n        pass\n\n    @overload\n    def __init_subclass__(cls, a: str) -> Any: # E: The return type of \"__init_subclass__\" must be None\n        pass\n\n[case testGlobalFunctionInitWithReturnType]\nclass A: pass\nclass B: pass\ndef __init__() -> 'A': pass\n\na = __init__() # type: A\nb = __init__() # type: B # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n[case testAccessingInit]\nfrom typing import Any, cast\nclass A:\n    def __init__(self, a: 'A') -> None: pass\na: A\na.__init__(a)  # E: Accessing \"__init__\" on an instance is unsound, since instance.__init__ could be from an incompatible subclass\n(cast(Any, a)).__init__(a)\n\n[case testDeepInheritanceHierarchy]\nclass A: pass\nclass B(A): pass\nclass C(B): pass\nclass D(C): pass\nclass D2(C): pass\n\nd = C() # type: D  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"D\")\nif int():\n    d = B()      # E: Incompatible types in assignment (expression has type \"B\", variable has type \"D\")\nif int():\n    d = A()      # E: Incompatible types in assignment (expression has type \"A\", variable has type \"D\")\nif int():\n    d = D2()     # E: Incompatible types in assignment (expression has type \"D2\", variable has type \"D\")\na = D() # type: A\nif int():\n    a = D2()\nb = D() # type: B\nif int():\n    b = D2()\n\n[case testConstructorJoinsWithCustomMetaclass]\nfrom typing import TypeVar\nimport abc\n\ndef func() -> None: pass\nclass NormalClass: pass\nclass WithMetaclass(metaclass=abc.ABCMeta): pass\n\nT = TypeVar('T')\ndef join(x: T, y: T) -> T: pass\n\nf1 = join(func, WithMetaclass)\nreveal_type(f1())  # N: Revealed type is \"__main__.WithMetaclass | None\"\n\nf2 = join(WithMetaclass, func)\nreveal_type(f2())  # N: Revealed type is \"__main__.WithMetaclass | None\"\n\n-- Attribute access in class body\n-- ------------------------------\n\n\n[case testDataAttributeRefInClassBody]\nimport typing\nclass B: pass\nclass A:\n    x = B()\n    y = x\n    b = x # type: B\n    if int():\n        b = x\n    c = x # type: A # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    if int():\n        c = b   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[out]\n\n[case testMethodRefInClassBody]\nfrom typing import Callable\nclass B: pass\nclass A:\n    def f(self) -> None: pass\n    g = f\n    h = f # type: Callable[[A], None]\n    if int():\n        h = f\n        g = h\n    ff = f # type: Callable[[B], None]  # E: Incompatible types in assignment (expression has type \"Callable[[A], None]\", variable has type \"Callable[[B], None]\")\n    if int():\n        g = ff  # E: Incompatible types in assignment (expression has type \"Callable[[B], None]\", variable has type \"Callable[[A], None]\")\n[out]\n\n\n-- Arbitrary statements in class body\n-- ----------------------------------\n\n\n[case testStatementsInClassBody]\nimport typing\nclass B: pass\nclass A:\n    for x in [A()]:\n        y = x\n        if int():\n            y = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    if int():\n        x = A()\n    if int():\n        y = A()\n    if int():\n        x = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[builtins fixtures/for.pyi]\n[out]\n\n\n-- Class attributes\n-- ----------------\n\n\n[case testAccessMethodViaClass]\nimport typing\nclass A:\n    def f(self) -> None: pass\nA.f(A())\nA.f(object())     # E: Argument 1 to \"f\" of \"A\" has incompatible type \"object\"; expected \"A\"\nA.f()             # E: Missing positional argument \"self\" in call to \"f\" of \"A\"\nA.f(None, None)   # E: Too many arguments for \"f\" of \"A\" \\\n                  # E: Argument 1 to \"f\" of \"A\" has incompatible type \"None\"; expected \"A\"\n\n[case testAccessAttributeViaClass]\nimport typing\nclass B: pass\nclass A:\n    x: A\na = A.x # type: A\nb = A.x # type: B # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n[case testAccessingUndefinedAttributeViaClass]\nimport typing\nclass A: pass\nA.x # E: \"type[A]\" has no attribute \"x\"\n\n[case testAccessingUndefinedAttributeViaClassWithOverloadedInit]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A:\n    @overload\n    def __init__(self): pass\n    @overload\n    def __init__(self, x): pass\nA.x # E: \"type[A]\" has no attribute \"x\"\n\n[case testAccessMethodOfClassWithOverloadedInit]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Any\nclass A:\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x: Any) -> None: pass\n    def f(self) -> None: pass\nA.f(A())\nA.f()    # E: Missing positional argument \"self\" in call to \"f\" of \"A\"\n\n[case testAssignmentToClassDataAttribute]\nimport typing\nclass B: pass\nclass A:\n    x: B\nA.x = B()\nA.x = object()  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"B\")\n\n[case testAssignmentToInferredClassDataAttribute]\nimport typing\nclass B: pass\nclass A:\n     x = B()\nA.x = B()\nA.x = A()   # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n[case testInitMethodUnbound]\n\nclass B: pass\nclass A:\n    def __init__(self, b: B) -> None: pass\na: A\nb: B\nA.__init__(a, b)\nA.__init__(b, b) # E: Argument 1 to \"__init__\" of \"A\" has incompatible type \"B\"; expected \"A\"\nA.__init__(a, a) # E: Argument 2 to \"__init__\" of \"A\" has incompatible type \"A\"; expected \"B\"\n\n[case testAssignToMethodViaClass]\nimport typing\nclass A:\n    def f(self): pass\nA.f = None  # E: Cannot assign to a method \\\n            # E: Incompatible types in assignment (expression has type \"None\", variable has type \"Callable[[A], Any]\")\n\n[case testAssignToNestedClassViaClass]\nimport typing\nclass A:\n    class B: pass\nA.B = None  # E: Cannot assign to a type \\\n            # E: Incompatible types in assignment (expression has type \"None\", variable has type \"type[B]\")\n[targets __main__]\n\n[case testAccessingClassAttributeWithTypeInferenceIssue]\nx = C.x # E: Cannot determine type of \"x\" # E: Name \"C\" is used before definition\ndef f() -> int: return 1\nclass C:\n    x = f()\n[builtins fixtures/list.pyi]\n\n[case testAccessingClassAttributeWithTypeInferenceIssue2]\nclass C:\n    x = []\nx = C.x\n[builtins fixtures/list.pyi]\n[out]\nmain:2: error: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n\n[case testAccessingGenericClassAttribute]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nclass A(Generic[T]):\n    x: T\nA.x  # E: Access to generic instance variables via class is ambiguous\nA[int].x  # E: Access to generic instance variables via class is ambiguous\n[targets __main__]\n\n[case testAccessingNestedGenericClassAttribute]\nfrom typing import Generic, List, TypeVar, Union\nT = TypeVar('T')\nU = TypeVar('U')\nclass A(Generic[T, U]):\n    x: Union[T, List[U]]\nA.x  # E: Access to generic instance variables via class is ambiguous\nA[int, int].x  # E: Access to generic instance variables via class is ambiguous\n[builtins fixtures/list.pyi]\n\n\n-- Nested classes\n-- --------------\n\n\n[case testClassWithinFunction]\ndef f() -> None:\n    class A:\n        def g(self) -> None: pass\n    a: A\n    a.g()\n    a.g(a) # E: Too many arguments for \"g\" of \"A\"\n[targets __main__, __main__.f]\n\n[case testGenericClassWithinFunction]\nfrom typing import TypeVar\n\ndef test() -> None:\n    T = TypeVar('T', bound='Foo')\n    class Foo:\n        def returns_int(self) -> int:\n            return 0\n\n        def bar(self, foo: T) -> T:\n            x: T = foo\n            reveal_type(x)  # N: Revealed type is \"T`-1\"\n            reveal_type(x.returns_int())  # N: Revealed type is \"builtins.int\"\n            return foo\n    reveal_type(Foo.bar)  # N: Revealed type is \"def [T <: __main__.Foo@5] (self: __main__.Foo@5, foo: T`1) -> T`1\"\n\n[case testGenericClassWithInvalidTypevarUseWithinFunction]\nfrom typing import TypeVar\n\ndef test() -> None:\n    T = TypeVar('T', bound='Foo')\n    class Foo:\n        invalid: T  # E: Type variable \"T\" is unbound \\\n                    # N: (Hint: Use \"Generic[T]\" or \"Protocol[T]\" base class to bind \"T\" inside a class) \\\n                    # N: (Hint: Use \"T\" in function signature to bind \"T\" inside a function)\n\n        def bar(self, foo: T) -> T:\n            pass\n\n[case testConstructNestedClass]\nimport typing\nclass A:\n    class B: pass\n    b = B()\n    if int():\n        b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    if int():\n        b = B(b) # E: Too many arguments for \"B\"\n[out]\n\n[case testConstructNestedClassWithCustomInit]\nimport typing\nclass A:\n    def f(self) -> None:\n        class B:\n            def __init__(self, a: 'A') -> None: pass\n        b = B(A())\n        if int():\n            b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n            b = B() # E: Missing positional argument \"a\" in call to \"B\"\n[out]\n\n[case testDeclareVariableWithNestedClassType]\n\ndef f() -> None:\n    class A: pass\n    a: A\n    if int():\n        a = A()\n        a = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n[out]\n\n[case testExternalReferenceToClassWithinClass]\nclass A:\n    class B: pass\nb: A.B\nif int():\n    b = A.B()\nif int():\n    b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    b = A.B(b) # E: Too many arguments for \"B\"\n\n[case testAliasNestedClass]\nclass Outer:\n    class Inner:\n        def make_int(self) -> int: return 1\n    reveal_type(Inner().make_int)  # N: Revealed type is \"def () -> builtins.int\"\n    some_int = Inner().make_int()\n\nreveal_type(Outer.Inner.make_int)  # N: Revealed type is \"def (self: __main__.Outer.Inner) -> builtins.int\"\nreveal_type(Outer().some_int) # N: Revealed type is \"builtins.int\"\nBar = Outer.Inner\nreveal_type(Bar.make_int)  # N: Revealed type is \"def (self: __main__.Outer.Inner) -> builtins.int\"\nx = Bar()  # type: Bar\ndef produce() -> Bar:\n    reveal_type(Bar().make_int)  # N: Revealed type is \"def () -> builtins.int\"\n    return Bar()\n\n[case testInnerClassPropertyAccess]\nclass Foo:\n    class Meta:\n        name = 'Bar'\n    meta = Meta\n\nreveal_type(Foo.Meta)  # N: Revealed type is \"def () -> __main__.Foo.Meta\"\nreveal_type(Foo.meta)  # N: Revealed type is \"def () -> __main__.Foo.Meta\"\nreveal_type(Foo.Meta.name)  # N: Revealed type is \"builtins.str\"\nreveal_type(Foo.meta.name)  # N: Revealed type is \"builtins.str\"\nreveal_type(Foo().Meta)  # N: Revealed type is \"def () -> __main__.Foo.Meta\"\nreveal_type(Foo().meta)  # N: Revealed type is \"def () -> __main__.Foo.Meta\"\nreveal_type(Foo().meta.name)  # N: Revealed type is \"builtins.str\"\nreveal_type(Foo().Meta.name)  # N: Revealed type is \"builtins.str\"\n\n-- Declaring attribute type in method\n-- ----------------------------------\n\n\n[case testDeclareAttributeTypeInInit]\n\nclass A:\n    def __init__(self):\n        self.x: int  # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs\na: A\na.x = 1\na.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testAccessAttributeDeclaredInInitBeforeDeclaration]\n\na: A\na.x = 1\na.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nclass A:\n    def __init__(self):\n        self.x: int  # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs\n\n\n-- Special cases\n-- -------------\n\n\n[case testMultipleClassDefinition]\nclass A: pass\nclass A: pass  # E: Name \"A\" already defined on line 1\nA()\n[case testDocstringInClass]\nimport typing\nclass A:\n    \"\"\"Foo\"\"\"\nclass B:\n    'x'\n    y = B()\n[builtins fixtures/primitives.pyi]\n\n[case testErrorMessageInFunctionNestedWithinMethod]\nimport typing\nclass A:\n    def f(self) -> None:\n        def g() -> None:\n            \"\" + 1  # E: Unsupported operand types for + (\"str\" and \"int\")\n        \"\" + 1  # E: Unsupported operand types for + (\"str\" and \"int\")\n[builtins fixtures/primitives.pyi]\n\n-- Static methods\n-- --------------\n\n\n[case testSimpleStaticMethod]\nimport typing\nclass A:\n  @staticmethod\n  def f(x: int) -> None: pass\nA.f(1)\nA().f(1)\nA.f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\nA().f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/staticmethod.pyi]\n\n[case testBuiltinStaticMethod]\nimport typing\nint.from_bytes(b'', '')\nint.from_bytes('', '') # E: Argument 1 to \"from_bytes\" of \"int\" has incompatible type \"str\"; expected \"bytes\"\n[builtins fixtures/staticmethod.pyi]\n\n[case testAssignStaticMethodOnInstance]\nimport typing\nclass A:\n  @staticmethod\n  def f(x: int) -> None: pass\nA().f = A.f # E: Cannot assign to a method\n[builtins fixtures/staticmethod.pyi]\n\n\n-- Class methods\n-- -------------\n\n\n[case testSimpleClassMethod]\nimport typing\nclass A:\n  @classmethod\n  def f(cls, x: int) -> None: pass\nA.f(1)\nA().f(1)\nA.f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\nA().f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/classmethod.pyi]\n[targets __main__, __main__.A.f]\n\n[case testBuiltinClassMethod]\nimport typing\nint.from_bytes(b'', '')\nint.from_bytes('', '') # E: Argument 1 to \"from_bytes\" of \"int\" has incompatible type \"str\"; expected \"bytes\"\n[builtins fixtures/classmethod.pyi]\n\n[case testAssignClassMethodOnClass]\nimport typing\nclass A:\n  @classmethod\n  def f(cls, x: int) -> None: pass\nA.f = A.f # E: Cannot assign to a method\n[builtins fixtures/classmethod.pyi]\n\n[case testAssignClassMethodOnInstance]\nimport typing\nclass A:\n  @classmethod\n  def f(cls, x: int) -> None: pass\nA().f = A.f # E: Cannot assign to a method\n[builtins fixtures/classmethod.pyi]\n\n[case testClassMethodCalledInClassMethod]\nimport typing\nclass C:\n  @classmethod\n  def foo(cls) -> None: pass\n  @classmethod\n  def bar(cls) -> None:\n    cls()\n    cls(1)      # E: Too many arguments for \"C\"\n    cls.bar()\n    cls.bar(1)  # E: Too many arguments for \"bar\" of \"C\"\n    cls.bozo()  # E: \"type[C]\" has no attribute \"bozo\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testClassMethodCalledOnClass]\nimport typing\nclass C:\n  @classmethod\n  def foo(cls) -> None: pass\nC.foo()\nC.foo(1)  # E: Too many arguments for \"foo\" of \"C\"\nC.bozo()  # E: \"type[C]\" has no attribute \"bozo\"\n[builtins fixtures/classmethod.pyi]\n\n[case testClassMethodCalledOnInstance]\nimport typing\nclass C:\n  @classmethod\n  def foo(cls) -> None: pass\nC().foo()\nC().foo(1)  # E: Too many arguments for \"foo\" of \"C\"\nC.bozo()    # E: \"type[C]\" has no attribute \"bozo\"\n[builtins fixtures/classmethod.pyi]\n\n[case testClassMethodMayCallAbstractMethod]\nfrom abc import abstractmethod\nimport typing\nclass C:\n  @classmethod\n  def foo(cls) -> None:\n      cls().bar()\n  @abstractmethod\n  def bar(self) -> None:\n      pass\n[builtins fixtures/classmethod.pyi]\n\n[case testClassMethodSubclassing]\nclass A:\n    @classmethod\n    def f(cls) -> None: pass\n\n    def g(self) -> None: pass\n\nclass B(A):\n    def f(self) -> None: pass  # Fail\n\n    @classmethod\n    def g(cls) -> None: pass\n\nclass C(A):\n    @staticmethod\n    def f() -> None: pass\n[builtins fixtures/classmethod.pyi]\n[out]\nmain:8: error: Signature of \"f\" incompatible with supertype \"A\"\nmain:8: note:      Superclass:\nmain:8: note:          @classmethod\nmain:8: note:          def f(cls) -> None\nmain:8: note:      Subclass:\nmain:8: note:          def f(self) -> None\n\n[case testClassMethodAndStaticMethod]\nclass C:\n  @classmethod  # E: Cannot have both classmethod and staticmethod\n  @staticmethod\n  def foo(cls) -> None: pass\n[builtins fixtures/classmethod.pyi]\n\n-- Properties\n-- ----------\n\n\n[case testAccessingReadOnlyProperty]\nimport typing\nclass A:\n    @property\n    def f(self) -> str: pass\na = A()\nreveal_type(a.f)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/property.pyi]\n\n[case testAssigningToReadOnlyProperty]\nimport typing\nclass A:\n    @property\n    def f(self) -> str: pass\nA().f = '' # E: Property \"f\" defined in \"A\" is read-only\n[builtins fixtures/property.pyi]\n\n[case testAssigningToInheritedReadOnlyProperty]\nclass A:\n    @property\n    def f(self) -> str: pass\nclass B(A): pass\nclass C(A):\n    @property\n    def f(self) -> str: pass\n\nA().f = '' # E: Property \"f\" defined in \"A\" is read-only\nB().f = '' # E: Property \"f\" defined in \"A\" is read-only\nC().f = '' # E: Property \"f\" defined in \"C\" is read-only\n[builtins fixtures/property.pyi]\n\n[case testPropertyGetterBody]\nimport typing\nclass A:\n    @property\n    def f(self) -> str:\n        self.x = 1\n        self.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        return ''\n[builtins fixtures/property.pyi]\n\n[case testPropertyNameIsChecked]\nclass A:\n    @property\n    def f(self) -> str: ...\n    @not_f.setter  # E: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n    def f(self, val: str) -> None: ...\n\na = A()\nreveal_type(a.f)  # N: Revealed type is \"builtins.str\"\na.f = ''  # E: Property \"f\" defined in \"A\" is read-only\n\nclass B:\n    @property\n    def f(self) -> str: ...\n    @not_f.deleter  # E: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n    def f(self) -> None: ...\n\nclass C:\n    @property\n    def f(self) -> str: ...\n    @not_f.setter  # E: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n    def f(self, val: str) -> None: ...\n    @not_f.deleter  # E: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n    def f(self) -> None: ...\n[builtins fixtures/property.pyi]\n\n[case testPropertyAttributeIsChecked]\nclass A:\n    @property\n    def f(self) -> str: ...\n    @f.unknown  # E: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n    def f(self, val: str) -> None: ...\n    @f.bad.setter  # E: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n    def f(self, val: str) -> None: ...\n    @f  # E: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n    def f(self, val: str) -> None: ...\n    @int  # E: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n    def f(self, val: str) -> None: ...\n[builtins fixtures/property.pyi]\n\n[case testPropertyNameAndAttributeIsCheckedPretty]\n# flags: --pretty\nclass A:\n    @property\n    def f(self) -> str: ...\n    @not_f.setter\n    def f(self, val: str) -> None: ...\n    @not_f.deleter\n    def f(self) -> None: ...\n\nclass B:\n    @property\n    def f(self) -> str: ...\n    @f.unknown\n    def f(self, val: str) -> None: ...\n[builtins fixtures/property.pyi]\n[out]\nmain:5: error: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n        @not_f.setter\n         ^~~~~~~~~~~~\nmain:7: error: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n        @not_f.deleter\n         ^~~~~~~~~~~~~\nmain:13: error: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n        @f.unknown\n         ^~~~~~~~~\n\n[case testPropertyGetterDecoratorIsRejected]\nclass A:\n    @property\n    def f(self) -> str: ...\n    @f.getter  # E: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n    def f(self, val: str) -> None: ...\n[builtins fixtures/property.pyi]\n\n[case testDynamicallyTypedProperty]\nimport typing\nclass A:\n    @property\n    def f(self): pass\na = A()\na.f.xx\na.f = '' # E: Property \"f\" defined in \"A\" is read-only\n[builtins fixtures/property.pyi]\n\n[case testPropertyWithSetter]\nimport typing\nclass A:\n    @property\n    def f(self) -> int:\n        return 1\n    @f.setter\n    def f(self, x: int) -> None:\n        pass\na = A()\na.f = a.f\na.f.x # E: \"int\" has no attribute \"x\"\na.f = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\na.f = 1\nreveal_type(a.f)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/property.pyi]\n\n[case testPropertyWithDeleterButNoSetter]\nimport typing\nclass A:\n    @property\n    def f(self) -> int:\n        return 1\n    @f.deleter\n    def f(self, x) -> None:\n        pass\na = A()\na.f = a.f # E: Property \"f\" defined in \"A\" is read-only\na.f.x # E: \"int\" has no attribute \"x\"\n[builtins fixtures/property.pyi]\n\n-- Descriptors\n-- -----------\n\n\n[case testAccessingNonDataDescriptor]\nfrom typing import Any\nclass D:\n    def __get__(self, inst: Any, own: Any) -> str: return 's'\nclass A:\n    f = D()\na = A()\nreveal_type(a.f)  # N: Revealed type is \"builtins.str\"\n\n[case testSettingNonDataDescriptor]\nfrom typing import Any\nclass D:\n    def __get__(self, inst: Any, own: Any) -> str: return 's'\nclass A:\n    f = D()\na = A()\na.f = 'foo'\na.f = D()  # E: Incompatible types in assignment (expression has type \"D\", variable has type \"str\")\n\n[case testSettingDataDescriptor]\nfrom typing import Any\nclass D:\n    def __get__(self, inst: Any, own: Any) -> str: return 's'\n    def __set__(self, inst: Any, value: str) -> None: pass\nclass A:\n    f = D()\na = A()\na.f = ''\na.f = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testSettingDescriptorWithOverloadedDunderSet1]\nfrom typing import Any, overload, Union\nclass D:\n    @overload\n    def __set__(self, inst: Any, value: str) -> None: pass\n    @overload\n    def __set__(self, inst: Any, value: int) -> None: pass\n    def __set__(self, inst: Any, value: Union[str, int]) -> None: pass\nclass A:\n    f = D()\na = A()\na.f = ''\na.f = 1\na.f = 1.5  # E\n[out]\nmain:13: error: No overload variant of \"__set__\" of \"D\" matches argument types \"A\", \"float\"\nmain:13: note: Possible overload variants:\nmain:13: note:     def __set__(self, inst: Any, value: str) -> None\nmain:13: note:     def __set__(self, inst: Any, value: int) -> None\n\n[case testSettingDescriptorWithOverloadedDunderSet2]\nfrom typing import overload, Union\nclass D:\n    @overload\n    def __set__(self, inst: A, value: str) -> None: pass\n    @overload\n    def __set__(self, inst: B, value: int) -> None: pass\n    def __set__(self, inst: Union[A, B], value: Union[str, int]) -> None: pass\nclass A:\n    f = D()\nclass B:\n    f = D()\na = A()\nb = B()\na.f = ''\nb.f = 1\na.f = 1   # E\nb.f = ''  # E\n[out]\nmain:16: error: No overload variant of \"__set__\" of \"D\" matches argument types \"A\", \"int\"\nmain:16: note: Possible overload variants:\nmain:16: note:     def __set__(self, inst: A, value: str) -> None\nmain:16: note:     def __set__(self, inst: B, value: int) -> None\nmain:17: error: No overload variant of \"__set__\" of \"D\" matches argument types \"B\", \"str\"\nmain:17: note: Possible overload variants:\nmain:17: note:     def __set__(self, inst: A, value: str) -> None\nmain:17: note:     def __set__(self, inst: B, value: int) -> None\n\n[case testReadingDescriptorWithoutDunderGet]\nfrom typing import Union, Any\nclass D:\n    def __set__(self, inst: Any, value: str) -> None: pass\nclass A:\n    f = D()\n    def __init__(self): self.f = 's'\na = A()\nreveal_type(a.f)  # N: Revealed type is \"__main__.D\"\n\n[case testAccessingDescriptorFromClass]\nfrom d import D, Base\nclass A(Base):\n    f = D()\nreveal_type(A.f)  # N: Revealed type is \"d.D\"\nreveal_type(A().f)  # N: Revealed type is \"builtins.str\"\n[file d.pyi]\nfrom typing import TypeVar, Type, Generic, overload\nclass Base: pass\nclass D:\n    def __init__(self) -> None: pass\n    @overload\n    def __get__(self, inst: None, own: Type[Base]) -> D: pass\n    @overload\n    def __get__(self, inst: Base, own: Type[Base]) -> str: pass\n[builtins fixtures/bool.pyi]\n\n[case testAccessingDescriptorFromClassWrongBase]\nfrom d import D, Base\nclass A:\n    f = D()\nreveal_type(A.f)\nreveal_type(A().f)\n[file d.pyi]\nfrom typing import TypeVar, Type, Generic, overload\nclass Base: pass\nclass D:\n    def __init__(self) -> None: pass\n    @overload\n    def __get__(self, inst: None, own: Type[Base]) -> D: pass\n    @overload\n    def __get__(self, inst: Base, own: Type[Base]) -> str: pass\n[builtins fixtures/bool.pyi]\n[out]\nmain:4: error: Argument 2 to \"__get__\" of \"D\" has incompatible type \"type[A]\"; expected \"type[Base]\"\nmain:4: note: Revealed type is \"d.D\"\nmain:5: error: No overload variant of \"__get__\" of \"D\" matches argument types \"A\", \"type[A]\"\nmain:5: note: Possible overload variants:\nmain:5: note:     def __get__(self, inst: None, own: type[Base]) -> D\nmain:5: note:     def __get__(self, inst: Base, own: type[Base]) -> str\nmain:5: note: Revealed type is \"Any\"\n\n[case testAccessingGenericNonDataDescriptor]\nfrom typing import TypeVar, Type, Generic, Any\nV = TypeVar('V')\nclass D(Generic[V]):\n    def __init__(self, v: V) -> None: self.v = v\n    def __get__(self, inst: Any, own: Type) -> V: return self.v\nclass A:\n    f = D(10)\n    g = D('10')\na = A()\nreveal_type(a.f)  # N: Revealed type is \"builtins.int\"\nreveal_type(a.g)  # N: Revealed type is \"builtins.str\"\n\n[case testSettingGenericDataDescriptor]\nfrom typing import TypeVar, Type, Generic, Any\nV = TypeVar('V')\nclass D(Generic[V]):\n    def __init__(self, v: V) -> None: self.v = v\n    def __get__(self, inst: Any, own: Type) -> V: return self.v\n    def __set__(self, inst: Any, v: V) -> None: pass\nclass A:\n    f = D(10)\n    g = D('10')\na = A()\na.f = 1\na.f = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\na.g = ''\na.g = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testAccessingGenericDescriptorFromClass]\nfrom d import D\nclass A:\n    f = D(10)  # type: D[A, int]\n    g = D('10')  # type: D[A, str]\nreveal_type(A.f)  # N: Revealed type is \"d.D[__main__.A, builtins.int]\"\nreveal_type(A.g)  # N: Revealed type is \"d.D[__main__.A, builtins.str]\"\nreveal_type(A().f)  # N: Revealed type is \"builtins.int\"\nreveal_type(A().g)  # N: Revealed type is \"builtins.str\"\n[file d.pyi]\nfrom typing import TypeVar, Type, Generic, overload\nT = TypeVar('T')\nV = TypeVar('V')\nclass D(Generic[T, V]):\n    def __init__(self, v: V) -> None: pass\n    @overload\n    def __get__(self, inst: None, own: Type[T]) -> 'D[T, V]': pass\n    @overload\n    def __get__(self, inst: T, own: Type[T]) -> V: pass\n[builtins fixtures/bool.pyi]\n\n[case testAccessingGenericDescriptorFromInferredClass]\nfrom typing import Type\nfrom d import D\nclass A:\n    f = D(10)  # type: D[A, int]\n    g = D('10')  # type: D[A, str]\ndef f(some_class: Type[A]):\n    reveal_type(some_class.f)\n    reveal_type(some_class.g)\n[file d.pyi]\nfrom typing import TypeVar, Type, Generic, overload\nT = TypeVar('T')\nV = TypeVar('V')\nclass D(Generic[T, V]):\n    def __init__(self, v: V) -> None: pass\n    @overload\n    def __get__(self, inst: None, own: Type[T]) -> 'D[T, V]': pass\n    @overload\n    def __get__(self, inst: T, own: Type[T]) -> V: pass\n[builtins fixtures/bool.pyi]\n[out]\nmain:7: note: Revealed type is \"d.D[__main__.A, builtins.int]\"\nmain:8: note: Revealed type is \"d.D[__main__.A, builtins.str]\"\n\n[case testAccessingGenericDescriptorFromClassBadOverload]\nfrom d import D\nclass A:\n    f = D(10)  # type: D[A, int]\nreveal_type(A.f)\n[file d.pyi]\nfrom typing import TypeVar, Type, Generic, overload\nT = TypeVar('T')\nV = TypeVar('V')\nclass D(Generic[T, V]):\n    def __init__(self, v: V) -> None: pass\n    @overload\n    def __get__(self, inst: None, own: None) -> 'D[T, V]': pass\n    @overload\n    def __get__(self, inst: T, own: Type[T]) -> V: pass\n[builtins fixtures/bool.pyi]\n[out]\nmain:4: error: No overload variant of \"__get__\" of \"D\" matches argument types \"None\", \"type[A]\"\nmain:4: note: Possible overload variants:\nmain:4: note:     def __get__(self, inst: None, own: None) -> D[A, int]\nmain:4: note:     def __get__(self, inst: A, own: type[A]) -> int\nmain:4: note: Revealed type is \"Any\"\n\n[case testAccessingNonDataDescriptorSubclass]\nfrom typing import Any\nclass C:\n    def __get__(self, inst: Any, own: Any) -> str: return 's'\nclass D(C): pass\nclass A:\n    f = D()\na = A()\nreveal_type(a.f)  # N: Revealed type is \"builtins.str\"\n\n[case testSettingDataDescriptorSubclass]\nfrom typing import Any\nclass C:\n    def __get__(self, inst: Any, own: Any) -> str: return 's'\n    def __set__(self, inst: Any, v: str) -> None: pass\nclass D(C): pass\nclass A:\n    f = D()\na = A()\na.f = ''\na.f = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testReadingDescriptorSubclassWithoutDunderGet]\nfrom typing import Union, Any\nclass C:\n    def __set__(self, inst: Any, v: str) -> None: pass\nclass D(C): pass\nclass A:\n    f = D()\n    def __init__(self): self.f = 's'\na = A()\nreveal_type(a.f)  # N: Revealed type is \"__main__.D\"\n\n[case testAccessingGenericNonDataDescriptorSubclass]\nfrom typing import TypeVar, Type, Generic, Any\nV = TypeVar('V')\nclass C(Generic[V]):\n    def __init__(self, v: V) -> None: self.v = v\n    def __get__(self, inst: Any, own: Type) -> V: return self.v\nclass D(C[V], Generic[V]): pass\nclass A:\n    f = D(10)\n    g = D('10')\na = A()\nreveal_type(a.f)  # N: Revealed type is \"builtins.int\"\nreveal_type(a.g)  # N: Revealed type is \"builtins.str\"\n\n[case testSettingGenericDataDescriptorSubclass]\nfrom typing import TypeVar, Type, Generic\nT = TypeVar('T')\nV = TypeVar('V')\nclass C(Generic[T, V]):\n    def __init__(self, v: V) -> None: self.v = v\n    def __get__(self, inst: T, own: Type[T]) -> V: return self.v\n    def __set__(self, inst: T, v: V) -> None: pass\nclass D(C[T, V], Generic[T, V]): pass\nclass A:\n    f = D(10)  # type: D[A, int]\n    g = D('10')  # type: D[A, str]\na = A()\na.f = 1\na.f = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\na.g = ''\na.g = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testSetDescriptorOnClass]\nfrom typing import TypeVar, Type, Generic\nT = TypeVar('T')\nV = TypeVar('V')\nclass D(Generic[T, V]):\n    def __init__(self, v: V) -> None: self.v = v\n    def __get__(self, inst: T, own: Type[T]) -> V: return self.v\n    def __set__(self, inst: T, v: V) -> None: pass\nclass A:\n    f = D(10)  # type: D[A, int]\nA.f = D(20)\nA.f = D('some string')  # E: Argument 1 to \"D\" has incompatible type \"str\"; expected \"int\"\n\n[case testSetDescriptorOnInferredClass]\nfrom typing import TypeVar, Type, Generic, Any\nV = TypeVar('V')\nclass D(Generic[V]):\n    def __init__(self, v: V) -> None: self.v = v\n    def __get__(self, inst: Any, own: Type) -> V: return self.v\n    def __set__(self, inst: Any, v: V) -> None: pass\nclass A:\n    f = D(10)\ndef f(some_class: Type[A]):\n    A.f = D(20)\n    A.f = D('some string')\n[out]\nmain:11: error: Argument 1 to \"D\" has incompatible type \"str\"; expected \"int\"\n\n[case testDescriptorUncallableDunderSet]\nclass D:\n    __set__ = 's'\nclass A:\n    f = D()\nA().f = 'x'  # E: __main__.D.__set__ is not callable\n\n[case testDescriptorDunderSetTooFewArgs]\nclass D:\n    def __set__(self, inst): pass\nclass A:\n    f = D()\nA().f = 'x'  # E: Too many arguments for \"__set__\"\n\n[case testDescriptorDunderSetTooManyArgs]\nclass D:\n    def __set__(self, inst, v, other): pass\nclass A:\n    f = D()\nA().f = 'x'  # E: Too few arguments for \"__set__\"\n\n[case testDescriptorDunderSetWrongArgTypes]\nclass D:\n    def __set__(self, inst: str, v:str) -> None: pass\nclass A:\n    f = D()\nA().f = 'x'  # E: Argument 1 to \"__set__\" of \"D\" has incompatible type \"A\"; expected \"str\"\n\n[case testDescriptorUncallableDunderGet]\nclass D:\n    __get__ = 's'\nclass A:\n    f = D()\nA().f  # E: __main__.D.__get__ is not callable\n\n[case testDescriptorDunderGetTooFewArgs]\nclass D:\n    def __get__(self, inst): pass\nclass A:\n    f = D()\nA().f  # E: Too many arguments for \"__get__\"\n\n[case testDescriptorDunderGetTooManyArgs]\nclass D:\n    def __get__(self, inst, own, other): pass\nclass A:\n    f = D()\nA().f = 'x'  # E: Too few arguments for \"__get__\"\n\n[case testDescriptorDunderGetWrongArgTypeForInstance]\nfrom typing import Any\nclass D:\n    def __get__(self, inst: str, own: Any) -> Any: pass\nclass A:\n    f = D()\nA().f  # E: Argument 1 to \"__get__\" of \"D\" has incompatible type \"A\"; expected \"str\"\n\n[case testDescriptorDunderGetWrongArgTypeForOwner]\nfrom typing import Any\nclass D:\n    def __get__(self, inst: Any, own: str) -> Any: pass\nclass A:\n    f = D()\nA().f  # E: Argument 2 to \"__get__\" of \"D\" has incompatible type \"type[A]\"; expected \"str\"\n\n[case testDescriptorGetSetDifferentTypes]\nfrom typing import Any\nclass D:\n    def __get__(self, inst: Any, own: Any) -> str: return 's'\n    def __set__(self, inst: Any, v: int) -> None: pass\nclass A:\n    f = D()\na = A()\na.f = 1\nreveal_type(a.f)  # N: Revealed type is \"builtins.str\"\n\n[case testDescriptorGetUnion]\nfrom typing import Any, Union\nclass String:\n    def __get__(self, inst: Any, owner: Any) -> str:\n        return ''\n\nclass A:\n    attr: str\n\nclass B:\n    attr = String()\n\ndef foo(x: Union[A, B]) -> None:\n    reveal_type(x.attr)  # N: Revealed type is \"builtins.str\"\n\n[case testDescriptorGetUnionRestricted]\nfrom typing import Any, Union\n\nclass getter:\n    def __get__(self, instance: X1, owner: Any) -> str: ...\n\nclass X1:\n    prop = getter()\n\nclass X2:\n    prop: str\n\ndef foo(x: Union[X1, X2]) -> None:\n    reveal_type(x.prop)  # N: Revealed type is \"builtins.str\"\n\n[case testDescriptorGetUnionType]\nfrom typing import Any, Union, Type, overload\n\nclass getter:\n    @overload\n    def __get__(self, instance: None, owner: Any) -> getter: ...\n    @overload\n    def __get__(self, instance: object, owner: Any) -> str: ...\n    def __get__(self, instance, owner):\n        ...\n\nclass X1:\n    prop = getter()\nclass X2:\n    prop = getter()\n\ndef foo(x: Type[Union[X1, X2]]) -> None:\n    reveal_type(x.prop)  # N: Revealed type is \"__main__.getter\"\n\n\n-- _promote decorators\n-- -------------------\n\n\n[case testSimpleDucktypeDecorator]\nfrom typing import _promote\nclass A: pass\n@_promote(A)\nclass B: pass\na: A\nb: B\nif int():\n    b = a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    a = b\n[typing fixtures/typing-medium.pyi]\n\n[case testDucktypeTransitivityDecorator]\nfrom typing import _promote\nclass A: pass\n@_promote(A)\nclass B: pass\n@_promote(B)\nclass C: pass\na: A\nc: C\nif int():\n    c = a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"C\")\n    a = c\n[typing fixtures/typing-medium.pyi]\n\n\n-- Hard coded type promotions\n-- --------------------------\n\n[case testHardCodedTypePromotions]\nimport typing\ndef f(x: float) -> None: pass\ndef g(x: complex) -> None: pass\nf(1)\ng(1)\ng(1.1)\n[builtins fixtures/complex.pyi]\n\n\n-- Operator methods\n-- ----------------\n\n\n[case testOperatorMethodOverrideIntroducingOverloading]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A:\n    def __add__(self, x: int) -> int: pass\nclass B(A):\n    @overload  # Fail\n    def __add__(self, x: int) -> int: pass\n    @overload\n    def __add__(self, x: str) -> str: pass\n[out]\ntmp/foo.pyi:5: error: Signature of \"__add__\" incompatible with supertype \"A\"\ntmp/foo.pyi:5: note:      Superclass:\ntmp/foo.pyi:5: note:          def __add__(self, int, /) -> int\ntmp/foo.pyi:5: note:      Subclass:\ntmp/foo.pyi:5: note:          @overload\ntmp/foo.pyi:5: note:          def __add__(self, int, /) -> int\ntmp/foo.pyi:5: note:          @overload\ntmp/foo.pyi:5: note:          def __add__(self, str, /) -> str\ntmp/foo.pyi:5: note: Overloaded operator methods can't have wider argument types in overrides\n\n[case testOperatorMethodOverrideWideningArgumentType]\nimport typing\nclass A:\n    def __add__(self, x: int) -> int: pass\nclass B(A):\n    def __add__(self, x: object) -> int: pass\n[out]\n\n[case testOperatorMethodOverrideNarrowingReturnType]\nimport typing\nclass A:\n    def __add__(self, x: int) -> 'A': pass\nclass B(A):\n    def __add__(self, x: int) -> 'B': pass\n\n[case testOperatorMethodOverrideWithDynamicallyTyped]\nimport typing\nclass A:\n    def __add__(self, x: int) -> 'A': pass\nclass B(A):\n    def __add__(self, x): pass\n\n[case testOperatorMethodAgainstSameType]\nclass A:\n    def __add__(self, x: int) -> 'A':\n        if isinstance(x, int):\n            return A()\n        else:\n            return NotImplemented\n\n    def __radd__(self, x: 'A') -> 'A':\n        if isinstance(x, A):\n            return A()\n        else:\n            return NotImplemented\n\nclass B(A): pass\n\n# Note: This is a runtime error. If we run x.__add__(y)\n# where x and y are *not* the same type, Python will not try\n# calling __radd__.\nA() + A()               # E: Unsupported operand types for + (\"A\" and \"A\")\n\n# Here, Python *will* call __radd__(...)\nreveal_type(B() + A())  # N: Revealed type is \"__main__.A\"\nreveal_type(A() + B())  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testBinaryOperatorMethodPositionalArgumentsOnly]\nclass A:\n    def __add__(self, other: int) -> int: pass\n    def __iadd__(self, other: int) -> int: pass\n    def __radd__(self, other: int) -> int: pass\n\nreveal_type(A.__add__)  # N: Revealed type is \"def (__main__.A, builtins.int) -> builtins.int\"\nreveal_type(A.__iadd__) # N: Revealed type is \"def (__main__.A, builtins.int) -> builtins.int\"\nreveal_type(A.__radd__) # N: Revealed type is \"def (__main__.A, builtins.int) -> builtins.int\"\n\n[case testOperatorMethodOverrideWithIdenticalOverloadedType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A:\n    @overload\n    def __add__(self, x: int) -> 'A': pass\n    @overload\n    def __add__(self, x: str) -> 'A': pass\nclass B(A):\n    @overload\n    def __add__(self, x: int) -> 'A': pass\n    @overload\n    def __add__(self, x: str) -> 'A': pass\n\n[case testOverloadedOperatorMethodOverrideWithDynamicallyTypedMethod]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Any\nclass A:\n    @overload\n    def __add__(self, x: int) -> 'A': pass\n    @overload\n    def __add__(self, x: str) -> 'A': pass\nclass B(A):\n    def __add__(self, x): pass\nclass C(A):\n    def __add__(self, x: Any) -> A: pass\n\n[case testOverloadedOperatorMethodOverrideWithNewItem]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Any\nclass A:\n    @overload\n    def __add__(self, x: int) -> 'A': pass\n    @overload\n    def __add__(self, x: str) -> 'A': pass\nclass B(A):\n    @overload  # Fail\n    def __add__(self, x: int) -> A: pass\n    @overload\n    def __add__(self, x: str) -> A: pass\n    @overload\n    def __add__(self, x: type) -> A: pass\n[out]\ntmp/foo.pyi:8: error: Signature of \"__add__\" incompatible with supertype \"A\"\ntmp/foo.pyi:8: note:      Superclass:\ntmp/foo.pyi:8: note:          @overload\ntmp/foo.pyi:8: note:          def __add__(self, int, /) -> A\ntmp/foo.pyi:8: note:          @overload\ntmp/foo.pyi:8: note:          def __add__(self, str, /) -> A\ntmp/foo.pyi:8: note:      Subclass:\ntmp/foo.pyi:8: note:          @overload\ntmp/foo.pyi:8: note:          def __add__(self, int, /) -> A\ntmp/foo.pyi:8: note:          @overload\ntmp/foo.pyi:8: note:          def __add__(self, str, /) -> A\ntmp/foo.pyi:8: note:          @overload\ntmp/foo.pyi:8: note:          def __add__(self, type, /) -> A\ntmp/foo.pyi:8: note: Overloaded operator methods can't have wider argument types in overrides\n\n[case testOverloadedOperatorMethodOverrideWithSwitchedItemOrder]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Any\nclass A:\n    @overload\n    def __add__(self, x: 'B') -> 'B': pass\n    @overload\n    def __add__(self, x: 'A') -> 'A': pass\nclass B(A):\n    @overload\n    def __add__(self, x: 'A') -> 'A': pass\n    @overload\n    def __add__(self, x: 'B') -> 'B': pass\nclass C(A):\n    @overload\n    def __add__(self, x: 'B') -> 'B': pass\n    @overload\n    def __add__(self, x: 'A') -> 'A': pass\n[out]\ntmp/foo.pyi:8: error: Signature of \"__add__\" incompatible with supertype \"A\"\ntmp/foo.pyi:8: note: Overload variants must be defined in the same order as they are in \"A\"\ntmp/foo.pyi:11: error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n[case testReverseOperatorMethodArgumentType]\nfrom typing import Any\nclass A: pass\nclass B:\n    def __radd__(self, x: A) -> int: pass # Error\nclass C:\n    def __radd__(self, x: A) -> Any: pass\nclass D:\n    def __radd__(self, x: A) -> object: pass\n[out]\n\n[case testReverseOperatorMethodArgumentType2]\nfrom typing import Any, Tuple, Callable\nclass A:\n    def __radd__(self, x: Tuple[int, str]) -> int: pass\nclass B:\n    def __radd__(self, x: Callable[[], int]) -> int: pass\nclass C:\n    def __radd__(self, x: Any) -> int: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testReverseOperatorMethodInvalid]\nfrom foo import *\n[file foo.pyi]\nclass A: ...\nclass B:\n    def __rmul__(self) -> A: ...\nclass C:\n    def __radd__(self, other, oops) -> int: ...\n[out]\ntmp/foo.pyi:3: error: Invalid signature \"Callable[[B], A]\"\ntmp/foo.pyi:5: error: Invalid signature \"Callable[[C, Any, Any], int]\"\n\n[case testReverseOperatorOrderingCase1]\nclass A:\n    def __radd__(self, other: 'A') -> int: ...\n\n# Note: Python only tries calling __add__ and never __radd__, even though it's present\nA() + A()  # E: Unsupported left operand type for + (\"A\")\n\n[case testReverseOperatorOrderingCase2]\nclass A:\n    def __lt__(self, other: object) -> bool: ...\n\n# Not all operators have the above shortcut though.\nreveal_type(A() > A())   # N: Revealed type is \"builtins.bool\"\nreveal_type(A() < A())   # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/bool.pyi]\n\n[case testReverseOperatorOrderingCase3]\nclass A:\n    def __add__(self, other: B) -> int: ...\n\nclass B:\n    def __radd__(self, other: A) -> str: ...  # E: Signatures of \"__radd__\" of \"B\" and \"__add__\" of \"A\" are unsafely overlapping\n\n# Normally, we try calling __add__ before __radd__\nreveal_type(A() + B())  # N: Revealed type is \"builtins.int\"\n\n[case testReverseOperatorOrderingCase4]\nclass A:\n    def __add__(self, other: B) -> int: ...\n\nclass B(A):\n    def __radd__(self, other: A) -> str: ...  # E: Signatures of \"__radd__\" of \"B\" and \"__add__\" of \"A\" are unsafely overlapping\n\n# However, if B is a subtype of A, we try calling __radd__ first.\nreveal_type(A() + B())  # N: Revealed type is \"builtins.str\"\n\n[case testReverseOperatorOrderingCase5]\n# Note: these two methods are not unsafely overlapping because __radd__ is\n# never called -- see case 1.\nclass A:\n    def __add__(self, other: B) -> int: ...\n    def __radd__(self, other: A) -> str: ...\n\nclass B(A): pass\n\n# ...but only if B specifically defines a new __radd__.\nreveal_type(A() + B())  # N: Revealed type is \"builtins.int\"\n\n[case testReverseOperatorOrderingCase6]\nclass A:\n    def __add__(self, other: B) -> int: ...\n    def __radd__(self, other: A) -> str: ...\n\nclass B(A):\n    # Although A.__radd__ can never be called, B.__radd__ *can* be -- so the\n    # unsafe overlap check kicks in here.\n    def __radd__(self, other: A) -> str: ...  # E: Signatures of \"__radd__\" of \"B\" and \"__add__\" of \"A\" are unsafely overlapping\n\nreveal_type(A() + B())  # N: Revealed type is \"builtins.str\"\n\n[case testReverseOperatorOrderingCase7]\nclass A:\n    def __add__(self, other: B) -> int: ...\n    def __radd__(self, other: A) -> str: ...\n\nclass B(A):\n    def __radd__(self, other: A) -> str: ...  # E: Signatures of \"__radd__\" of \"B\" and \"__add__\" of \"A\" are unsafely overlapping\n\nclass C(B): pass\n\n# A refinement made by a parent also counts\nreveal_type(A() + C())  # N: Revealed type is \"builtins.str\"\n\n[case testReverseOperatorWithOverloads1]\nfrom typing import overload\n\nclass A:\n    def __add__(self, other: C) -> int: ...\n\nclass B:\n    def __add__(self, other: C) -> int: ...\n\nclass C:\n    @overload\n    def __radd__(self, other: A) -> str: ...   # E: Signatures of \"__radd__\" of \"C\" and \"__add__\" of \"A\" are unsafely overlapping\n    @overload\n    def __radd__(self, other: B) -> str: ...   # E: Signatures of \"__radd__\" of \"C\" and \"__add__\" of \"B\" are unsafely overlapping\n    def __radd__(self, other): pass\n\nreveal_type(A() + C())   # N: Revealed type is \"builtins.int\"\nreveal_type(B() + C())   # N: Revealed type is \"builtins.int\"\n\n[case testReverseOperatorWithOverloads2]\nfrom typing import overload, Union\n\nclass Num1:\n    def __add__(self, other: Num1) -> Num1: ...\n    def __radd__(self, other: Num1) -> Num1: ...\n\nclass Num2(Num1):\n    @overload\n    def __add__(self, other: Num2) -> Num2: ...\n    @overload\n    def __add__(self, other: Num1) -> Num2: ...\n    def __add__(self, other): pass\n\n    @overload\n    def __radd__(self, other: Num2) -> Num2: ...\n    @overload\n    def __radd__(self, other: Num1) -> Num2: ...\n    def __radd__(self, other): pass\n\nclass Num3(Num1):\n    def __add__(self, other: Union[Num1, Num3]) -> Num3: ...\n    def __radd__(self, other: Union[Num1, Num3]) -> Num3: ...\n\nreveal_type(Num1() + Num2())  # N: Revealed type is \"__main__.Num2\"\nreveal_type(Num2() + Num1())  # N: Revealed type is \"__main__.Num2\"\n\nreveal_type(Num1() + Num3())  # N: Revealed type is \"__main__.Num3\"\nreveal_type(Num3() + Num1())  # N: Revealed type is \"__main__.Num3\"\n\nreveal_type(Num2() + Num3())  # N: Revealed type is \"__main__.Num2\"\nreveal_type(Num3() + Num2())  # N: Revealed type is \"__main__.Num3\"\n\n[case testReverseOperatorWithOverloads3]\nfrom typing import Union, overload\n\nclass A:\n    def __mul__(self, value: A, /) -> A: ...\n    def __rmul__(self, value: A, /) -> A: ...\n\nclass B:\n    @overload\n    def __mul__(self, other: B, /) -> B: ...\n    @overload\n    def __mul__(self, other: A, /) -> str: ...\n    def __mul__(self, other: Union[B, A], /) -> Union[B, str]: pass\n\n    @overload\n    def __rmul__(self, other: B, /) -> B: ...\n    @overload\n    def __rmul__(self, other: A, /) -> str: ...\n    def __rmul__(self, other: Union[B, A], /) -> Union[B, str]: pass\n\n[case testReverseOperatorWithOverloadsNested]\nfrom typing import Union, overload\n\nclass A:\n    def __mul__(self, value: A, /) -> A: ...\n    def __rmul__(self, value: A, /) -> A: ...\n\nclass B:\n    @overload\n    def __mul__(self, other: B, /) -> B: ...\n    @overload\n    def __mul__(self, other: A, /) -> str: ...\n    def __mul__(self, other: Union[B, A], /) -> Union[B, str]: pass\n\n    @overload\n    def __rmul__(self, other: B, /) -> B: ...\n    @overload\n    def __rmul__(self, other: A, /) -> str: ...\n    def __rmul__(self, other: Union[B, A], /) -> Union[B, str]:\n        class A1:\n            def __add__(self, other: C1) -> int: ...\n\n        class B1:\n            def __add__(self, other: C1) -> int: ...\n\n        class C1:\n            @overload\n            def __radd__(self, other: A1) -> str: ...   # E: Signatures of \"__radd__\" of \"C1\" and \"__add__\" of \"A1\" are unsafely overlapping\n            @overload\n            def __radd__(self, other: B1) -> str: ...   # E: Signatures of \"__radd__\" of \"C1\" and \"__add__\" of \"B1\" are unsafely overlapping\n            def __radd__(self, other): pass\n\n        return \"\"\n\n[case testDivReverseOperator]\n# No error: __div__ has no special meaning in Python 3\nclass A1:\n    def __div__(self, x: B1) -> int: ...\nclass B1:\n    def __rdiv__(self, x: A1) -> str: ...\n\nclass A2:\n    def __truediv__(self, x: B2) -> int: ...\nclass B2:\n    def __rtruediv__(self, x: A2) -> str: ...  # E: Signatures of \"__rtruediv__\" of \"B2\" and \"__truediv__\" of \"A2\" are unsafely overlapping\n\nA1() / B1()                 # E: Unsupported left operand type for / (\"A1\")\nreveal_type(A2() / B2())    # N: Revealed type is \"builtins.int\"\n\n[case testReverseOperatorMethodForwardIsAny]\nfrom typing import Any\ndef deco(f: Any) -> Any: return f\nclass C:\n    @deco\n    def __add__(self, other: C) -> C: return C()\n    def __radd__(self, other: C) -> C: return C()\n[out]\n\n[case testReverseOperatorMethodForwardIsAny2]\nfrom typing import Any\ndef deco(f: Any) -> Any: return f\nclass C:\n    __add__ = None  # type: Any\n    def __radd__(self, other: C) -> C: return C()\n[out]\n\n[case testReverseOperatorMethodForwardIsAny3]\nfrom typing import Any\ndef deco(f: Any) -> Any: return f\nclass C:\n    __add__ = 42\n    def __radd__(self, other: C) -> C: return C()\n[out]\nmain:5: error: Forward operator \"__add__\" is not callable\n\n[case testOverloadedReverseOperatorMethodArgumentType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, Any\nclass A:\n    @overload\n    def __radd__(self, x: 'A') -> str: pass\n    @overload\n    def __radd__(self, x: 'A') -> Any: pass  # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n[out]\n\n[case testReverseOperatorMethodArgumentTypeAndOverloadedMethod]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A:\n    @overload\n    def __add__(self, x: int) -> int: pass\n    @overload\n    def __add__(self, x: str) -> int: pass\n    def __radd__(self, x: 'A') -> str: pass\n\n[case testReverseOperatorStar]\nclass B:\n    def __radd__(*self) -> int: pass\n    def __rsub__(*self: 'B') -> int: pass\n[builtins fixtures/tuple.pyi]\n\n[case testReverseOperatorTypeVar1]\nfrom typing import TypeVar\nT = TypeVar(\"T\", bound='Real')\nclass Real:\n    def __add__(self, other: object) -> str: ...\nclass Fraction(Real):\n    def __radd__(self, other: T) -> T: ...  # E: Signatures of \"__radd__\" of \"Fraction\" and \"__add__\" of \"T\" are unsafely overlapping\n\n# Note: When doing A + B and if B is a subtype of A, we will always call B.__radd__(A) first\n# and only try A.__add__(B) second if necessary.\nreveal_type(Real() + Fraction())      # N: Revealed type is \"__main__.Real\"\n\n# Note: When doing A + A, we only ever call A.__add__(A), never A.__radd__(A).\nreveal_type(Fraction() + Fraction())  # N: Revealed type is \"builtins.str\"\n\n[case testReverseOperatorTypeVar2a]\nfrom typing import TypeVar\nT = TypeVar(\"T\", bound='Real')\nclass Real:\n    def __add__(self, other: Fraction) -> str: ...\nclass Fraction(Real):\n    def __radd__(self, other: T) -> T: ...  # E: Signatures of \"__radd__\" of \"Fraction\" and \"__add__\" of \"T\" are unsafely overlapping\n\nreveal_type(Real() + Fraction())      # N: Revealed type is \"__main__.Real\"\nreveal_type(Fraction() + Fraction())  # N: Revealed type is \"builtins.str\"\n\n\n[case testReverseOperatorTypeVar2b]\nfrom typing import TypeVar\nT = TypeVar(\"T\", \"Real\", \"Fraction\")\nclass Real:\n    def __add__(self, other: Fraction) -> str: ...\nclass Fraction(Real):\n    def __radd__(self, other: T) -> T: ...  # E: Signatures of \"__radd__\" of \"Fraction\" and \"__add__\" of \"Real\" are unsafely overlapping\n\nreveal_type(Real() + Fraction())      # N: Revealed type is \"__main__.Real\"\nreveal_type(Fraction() + Fraction())  # N: Revealed type is \"builtins.str\"\n\n[case testReverseOperatorTypeVar3]\nfrom typing import TypeVar\nT = TypeVar(\"T\", bound='Real')\nclass Real:\n    def __add__(self, other: FractionChild) -> str: ...\nclass Fraction(Real):\n    def __radd__(self, other: T) -> T: ...  # E: Signatures of \"__radd__\" of \"Fraction\" and \"__add__\" of \"T\" are unsafely overlapping\nclass FractionChild(Fraction): pass\n\nreveal_type(Real() + Fraction())                # N: Revealed type is \"__main__.Real\"\nreveal_type(FractionChild() + Fraction())       # N: Revealed type is \"__main__.FractionChild\"\nreveal_type(FractionChild() + FractionChild())  # N: Revealed type is \"builtins.str\"\n\n# Runtime error: we try calling __add__, it doesn't match, and we don't try __radd__ since\n# the LHS and the RHS are not the same.\nFraction() + Fraction()                         # E: Unsupported operand types for + (\"Fraction\" and \"Fraction\")\n\n[case testReverseOperatorTypeType]\nfrom typing import TypeVar, Type\nclass Real(type):\n    def __add__(self, other: FractionChild) -> str: ...\nclass Fraction(Real):\n    def __radd__(self, other: Type['A']) -> Real: ...  # E: Signatures of \"__radd__\" of \"Fraction\" and \"__add__\" of \"type[A]\" are unsafely overlapping\nclass FractionChild(Fraction): pass\n\nclass A(metaclass=Real): pass\n\n[case testOperatorDoubleUnionIntFloat]\nfrom typing import Union\n\na: Union[int, float]\nb: int\nc: float\n\nreveal_type(a + a)  # N: Revealed type is \"builtins.int | builtins.float\"\nreveal_type(a + b)  # N: Revealed type is \"builtins.int | builtins.float\"\nreveal_type(b + a)  # N: Revealed type is \"builtins.int | builtins.float\"\nreveal_type(a + c)  # N: Revealed type is \"builtins.float\"\nreveal_type(c + a)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/ops.pyi]\n\n[case testOperatorDoubleUnionStandardSubtyping]\nfrom typing import Union\n\nclass Parent:\n    def __add__(self, x: Parent) -> Parent: pass\n    def __radd__(self, x: Parent) -> Parent: pass\n\nclass Child(Parent):\n    def __add__(self, x: Parent) -> Child: pass\n    def __radd__(self, x: Parent) -> Child: pass\n\na: Union[Parent, Child]\nb: Parent\nc: Child\n\nreveal_type(a + a)  # N: Revealed type is \"__main__.Parent\"\nreveal_type(a + b)  # N: Revealed type is \"__main__.Parent\"\nreveal_type(b + a)  # N: Revealed type is \"__main__.Parent\"\nreveal_type(a + c)  # N: Revealed type is \"__main__.Child\"\nreveal_type(c + a)  # N: Revealed type is \"__main__.Child\"\n\n[case testOperatorDoubleUnionNoRelationship1]\nfrom typing import Union\n\nclass Foo:\n    def __add__(self, x: Foo) -> Foo: pass\n    def __radd__(self, x: Foo) -> Foo: pass\n\nclass Bar:\n    def __add__(self, x: Bar) -> Bar: pass\n    def __radd__(self, x: Bar) -> Bar: pass\n\na: Union[Foo, Bar]\nb: Foo\nc: Bar\n\na + a  # E: Unsupported operand types for + (\"Foo\" and \"Bar\") \\\n       # E: Unsupported operand types for + (\"Bar\" and \"Foo\") \\\n       # N: Both left and right operands are unions\n\na + b  # E: Unsupported operand types for + (\"Bar\" and \"Foo\") \\\n       # N: Left operand is of type \"Foo | Bar\"\n\nb + a  # E: Unsupported operand types for + (\"Foo\" and \"Bar\") \\\n       # N: Right operand is of type \"Foo | Bar\"\n\na + c  # E: Unsupported operand types for + (\"Foo\" and \"Bar\") \\\n       # N: Left operand is of type \"Foo | Bar\"\n\nc + a  # E: Unsupported operand types for + (\"Bar\" and \"Foo\") \\\n       # N: Right operand is of type \"Foo | Bar\"\n\n[case testOperatorDoubleUnionNoRelationship2]\nfrom typing import Union\n\nclass Foo:\n    def __add__(self, x: Foo) -> Foo: pass\n    def __radd__(self, x: Foo) -> Foo: pass\n\nclass Bar:\n    def __add__(self, x: Union[Foo, Bar]) -> Bar: pass\n    def __radd__(self, x: Union[Foo, Bar]) -> Bar: pass\n\na: Union[Foo, Bar]\nb: Foo\nc: Bar\n\nreveal_type(a + a)  # N: Revealed type is \"__main__.Foo | __main__.Bar\"\nreveal_type(a + b)  # N: Revealed type is \"__main__.Foo | __main__.Bar\"\nreveal_type(b + a)  # N: Revealed type is \"__main__.Foo | __main__.Bar\"\nreveal_type(a + c)  # N: Revealed type is \"__main__.Bar\"\nreveal_type(c + a)  # N: Revealed type is \"__main__.Bar\"\n\n[case testOperatorDoubleUnionNaiveAdd]\nfrom typing import Union\n\nclass A: pass\nclass B: pass\nclass C:\n    def __radd__(self, x: A) -> int: pass\nclass D:\n    def __radd__(self, x: B) -> str: pass\n\nx: Union[A, B]\ny: Union[C, D]\n\nx + y  # E: Unsupported operand types for + (\"A\" and \"D\") \\\n       # E: Unsupported operand types for + (\"B\" and \"C\") \\\n       # N: Both left and right operands are unions\n\n[case testOperatorDoubleUnionInterwovenUnionAdd]\nfrom typing import Union\n\nclass Out1: pass\nclass Out2: pass\nclass Out3: pass\nclass Out4: pass\n\nclass A:\n    def __add__(self, x: D) -> Out1: pass\nclass B:\n    def __add__(self, x: C) -> Out2: pass\nclass C:\n    def __radd__(self, x: A) -> Out3: pass\nclass D:\n    def __radd__(self, x: B) -> Out4: pass\n\nx: Union[A, B]\ny: Union[C, D]\n\nreveal_type(x + y)    # N: Revealed type is \"__main__.Out3 | __main__.Out1 | __main__.Out2 | __main__.Out4\"\nreveal_type(A() + y)  # N: Revealed type is \"__main__.Out3 | __main__.Out1\"\nreveal_type(B() + y)  # N: Revealed type is \"__main__.Out2 | __main__.Out4\"\nreveal_type(x + C())  # N: Revealed type is \"__main__.Out3 | __main__.Out2\"\nreveal_type(x + D())  # N: Revealed type is \"__main__.Out1 | __main__.Out4\"\n\n[case testOperatorDoubleUnionDivision]\nfrom typing import Union\ndef f(a):\n    # type: (Union[int, float]) -> None\n    a /= 1.1\n    b = a / 1.1\n    reveal_type(b)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/ops.pyi]\n\n[case testOperatorWithInference]\nfrom typing import TypeVar, Iterable, Union\n\nT = TypeVar('T')\ndef sum(x: Iterable[T]) -> Union[T, int]: ...\n\ndef len(x: Iterable[T]) -> int: ...\n\nx = [1.1, 2.2, 3.3]\nreveal_type(sum(x))  # N: Revealed type is \"builtins.float | builtins.int\"\nreveal_type(sum(x) / len(x))  # N: Revealed type is \"builtins.float | builtins.int\"\n[builtins fixtures/floatdict.pyi]\n\n[case testOperatorWithEmptyListAndSum]\nfrom typing import TypeVar, Iterable, Union, overload\n\nT = TypeVar('T')\nS = TypeVar('S')\n@overload\ndef sum(x: Iterable[T]) -> Union[T, int]: ...\n@overload\ndef sum(x: Iterable[T], default: S) -> Union[T, S]: ...\ndef sum(*args): pass\n\nx = [\"a\", \"b\", \"c\"]\nreveal_type(x + sum([x, x, x], []))  # N: Revealed type is \"builtins.list[builtins.str]\"\n[builtins fixtures/floatdict.pyi]\n\n[case testAbstractReverseOperatorMethod]\nimport typing\nfrom abc import abstractmethod\nclass A:\n    @abstractmethod\n    def __lt__(self, x: 'A') -> int: pass\nclass B:\n    @abstractmethod\n    def __lt__(self, x: 'B') -> int: pass\n    @abstractmethod\n    def __gt__(self, x: 'B') -> int: pass\n[out]\n\n[case testOperatorMethodsAndOverloadingSpecialCase]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A:\n    @overload\n    def __add__(self, x: 'A') -> int: pass\n    @overload\n    def __add__(self, x: str) -> int: pass\nclass B:\n    def __radd__(self, x: 'A') -> str: pass\n[out]\n\n[case testUnsafeOverlappingWithOperatorMethodsAndOverloading2]\nfrom foo import A, B\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A:\n    def __add__(self, x: 'A') -> int: pass\nclass B:\n    @overload\n    def __radd__(self, x: 'X') -> str: pass # Error\n    @overload\n    def __radd__(self, x: A) -> str: pass   # Error\nclass X:\n    def __add__(self, x: B) -> int: pass\n[out]\ntmp/foo.pyi:6: error: Signatures of \"__radd__\" of \"B\" and \"__add__\" of \"X\" are unsafely overlapping\n\n[case testUnsafeOverlappingNotWithAny]\nfrom typing import TypeVar\nclass Real:\n    def __add__(self, other) -> str: ...\nclass Fraction(Real):\n    def __radd__(self, other: Real) -> Real: ...\n\n[case testOverlappingNormalAndInplaceOperatorMethod]\nimport typing\nclass A:\n    # Incompatible (potential trouble with __radd__)\n    def __add__(self, x: 'A') -> int: pass\n    def __iadd__(self, x: 'B') -> int: pass\nclass B:\n    # Safe\n    def __add__(self, x: 'C') -> int: pass\n    def __iadd__(self, x: A) -> int: pass\nclass C(A): pass\n[out]\nmain:5: error: Signatures of \"__iadd__\" and \"__add__\" are incompatible\n\n[case testOverloadedNormalAndInplaceOperatorMethod]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass A:\n    @overload\n    def __add__(self, x: int) -> int: pass\n    @overload\n    def __add__(self, x: str) -> int: pass\n    @overload # Error\n    def __iadd__(self, x: int) -> int: pass\n    @overload\n    def __iadd__(self, x: object) -> int: pass\nclass B:\n    @overload\n    def __add__(self, x: int) -> int: pass\n    @overload\n    def __add__(self, x: str) -> str: pass\n    @overload\n    def __iadd__(self, x: int) -> int: pass\n    @overload\n    def __iadd__(self, x: str) -> str: pass\n[out]\ntmp/foo.pyi:7: error: Signatures of \"__iadd__\" and \"__add__\" are incompatible\n\n[case testIntroducingInplaceOperatorInSubclass]\nimport typing\nclass A:\n    def __add__(self, x: 'A') -> 'B': pass\nclass B(A):\n    # __iadd__ effectively partially overrides __add__\n    def __iadd__(self, x: 'A') -> 'A': pass # Error\nclass C(A):\n    def __iadd__(self, x: int) -> 'B': pass # Error\nclass D(A):\n    def __iadd__(self, x: 'A') -> 'B': pass\n[out]\nmain:6: error: Return type \"A\" of \"__iadd__\" incompatible with return type \"B\" in \"__add__\" of supertype \"A\"\nmain:8: error: Signatures of \"__iadd__\" and \"__add__\" are incompatible\nmain:8: error: Argument 1 of \"__iadd__\" is incompatible with \"__add__\" of supertype \"A\"; supertype defines the argument type as \"A\"\nmain:8: note: This violates the Liskov substitution principle\nmain:8: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n\n[case testGetattribute]\na: A\nb: B\nclass A:\n    def __getattribute__(self, x: str) -> A:\n        return A()\nclass B: pass\n\na = a.foo\nb = a.bar\n[builtins fixtures/tuple.pyi]\n[out]\nmain:9: error: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n[case testDecoratedGetAttribute]\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T', bound=Callable)\n\ndef decorator(f: T) -> T:\n    return f\n\ndef bad(f: Callable) -> Callable[..., int]:\n    return f\n\nclass A:\n    @decorator\n    def __getattribute__(self, x: str) -> A:\n        return A()\nclass B:\n    @bad  # We test that type will be taken from decorated type, not node itself\n    def __getattribute__(self, x: str) -> A:\n        return A()\n\na: A\nb: B\n\na1: A = a.foo\nb1: B = a.bar  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\na2: A = b.baz  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"A\")\nb2: B = b.roo  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"B\")\n[builtins fixtures/tuple.pyi]\n\n[case testGetattributeSignature]\nclass A:\n    def __getattribute__(self, x: str) -> A: pass\nclass B:\n    def __getattribute__(self, x: A) -> B: pass\nclass C:\n    def __getattribute__(self, x: str, y: str) -> C: pass\nclass D:\n    def __getattribute__(self, x: str) -> None: pass\n[out]\nmain:4: error: Invalid signature \"Callable[[B, A], B]\" for \"__getattribute__\"\nmain:6: error: Invalid signature \"Callable[[C, str, str], C]\" for \"__getattribute__\"\n\n[case testGetattr]\na: A\nb: B\nclass A:\n    def __getattr__(self, x: str) -> A:\n        return A()\nclass B: pass\n\na = a.foo\nb = a.bar\n[builtins fixtures/tuple.pyi]\n[out]\nmain:9: error: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n[case testDecoratedGetattr]\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T', bound=Callable)\n\ndef decorator(f: T) -> T:\n    return f\n\ndef bad(f: Callable) -> Callable[..., int]:\n    return f\n\nclass A:\n    @decorator\n    def __getattr__(self, x: str) -> A:\n        return A()\nclass B:\n    @bad  # We test that type will be taken from decorated type, not node itself\n    def __getattr__(self, x: str) -> A:\n        return A()\n\na: A\nb: B\n\na1: A = a.foo\nb1: B = a.bar  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\na2: A = b.baz  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"A\")\nb2: B = b.roo  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"B\")\n[builtins fixtures/tuple.pyi]\n\n[case testGetattrWithGetitem]\nclass A:\n    def __getattr__(self, x: str) -> 'A':\n        return A()\n\na = A()\na[0]  # E: Value of type \"A\" is not indexable\n\n[case testGetattrWithCall]\nclass A:\n    def __getattr__(self, x: str) -> 'A':\n        return A()\n\na = A()\na.y()  # E: \"A\" not callable\n\n[case testGetattrWithCallable]\nfrom typing import Callable, Any\n\nclass C:\n    def __getattr__(self, attr: str) -> C: ...\n\ndef do(cd: Callable[..., Any]) -> None: ...\n\ndo(C())  # E: Argument 1 to \"do\" has incompatible type \"C\"; expected \"Callable[..., Any]\"\n\n[case testGetattrWithCallableTypeVar]\nfrom typing import Callable, Any, TypeVar\n\nclass C:\n    def __getattr__(self, attr: str) -> C: ...\n\nT = TypeVar('T', bound=Callable[..., Any])\n\ndef do(cd: T) -> T: ...\n\ndo(C())  # E: Value of type variable \"T\" of \"do\" cannot be \"C\"\n\n[case testNestedGetattr]\ndef foo() -> object:\n    def __getattr__() -> None:  # no error because not in a class\n        pass\n    return __getattr__\n\nclass X:\n    def foo(self) -> object:\n        def __getattr__() -> None:  # no error because not directly inside a class\n            pass\n        return __getattr__\n\n[case testGetattrSignature]\nclass A:\n    def __getattr__(self, x: str) -> A: pass\nclass B:\n    def __getattr__(self, x: A) -> B: pass\nclass C:\n    def __getattr__(self, x: str, y: str) -> C: pass\nclass D:\n    def __getattr__(self, x: str) -> None: pass\n[out]\nmain:4: error: Invalid signature \"Callable[[B, A], B]\" for \"__getattr__\"\nmain:6: error: Invalid signature \"Callable[[C, str, str], C]\" for \"__getattr__\"\n\n[case testSetattr]\nfrom typing import Union, Any\nclass A:\n    def __setattr__(self, name: str, value: Any) -> None: ...\n\na = A()\na.test = 'hello'\n\nclass B:\n   def __setattr__(self, name: str, value: Union[int, str]) -> None: ...\n\nb = B()\nb.both = 1\nb.work = '2'\n\nclass C:\n    def __setattr__(self, name: str, value: str) -> None: ...\n\nc = C()\nc.fail = 4  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\nclass D:\n    __setattr__ = 'hello'  # E: Invalid signature \"str\" for \"__setattr__\"\n\nd = D()\nd.crash = 4  # E: \"D\" has no attribute \"crash\"\n\nclass Ex:\n    def __setattr__(self, name: str, value: int) -> None:...\n    test = '42'  # type: str\ne = Ex()\ne.test = 'hello'\ne.t = 4\n\nclass Super:\n    def __setattr__(self, name: str, value: int) -> None: ...\n\nclass Sub(Super):\n    ...\ns = Sub()\ns.success = 4\ns.fail = 'fail'  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testDecoratedSetattr]\nfrom typing import Any, Callable, TypeVar\n\nT = TypeVar('T', bound=Callable)\n\ndef decorator(f: T) -> T:\n    return f\n\ndef bad(f: Callable) -> Callable[[Any, str, int], None]:\n    return f\n\nclass A:\n    @decorator\n    def __setattr__(self, k: str, v: str) -> None:\n        pass\nclass B:\n    @bad  # We test that type will be taken from decorated type, not node itself\n    def __setattr__(self, k: str, v: str) -> None:\n        pass\n\na: A\na.foo = 'a'\na.bar = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\nb: B\nb.good = 1\nb.bad = 'a'  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/tuple.pyi]\n\n[case testSetattrSignature]\nfrom typing import Any\n\nclass Test:\n    def __setattr__() -> None: ... \\\n        # E: Invalid signature \"Callable[[], None]\" for \"__setattr__\" \\\n        # E: Method must have at least one argument. Did you forget the \"self\" argument?\n\nt = Test()\nt.crash = 'test'  # E: Attribute function \"__setattr__\" with type \"Callable[[], None]\" does not accept self argument \\\n                  # E: \"Test\" has no attribute \"crash\"\n\nclass A:\n    def __setattr__(self): ...  # E: Invalid signature \"Callable[[A], Any]\" for \"__setattr__\"\na = A()\na.test = 4  # E: \"A\" has no attribute \"test\"\n\nclass B:\n    def __setattr__(self, name, value: int): ...\nb = B()\nb.integer = 5\n\nclass C:\n    def __setattr__(self, name: int, value: int) -> None: ...  # E: Invalid signature \"Callable[[C, int, int], None]\" for \"__setattr__\"\nc = C()\nc.check = 13\n\nclass X:\n    __setattr__ = ...  # type: Any\n\n[case testGetattrAndSetattr]\nfrom typing import Any\nclass A:\n    def __setattr__(self, name: str, value: Any) -> None: ...\n    def __getattr__(self, name: str) -> Any: ...\na = A()\na.test = 4\nt = a.test\n\nclass B:\n    def __setattr__(self, name: str, value: int) -> None: ...\n    def __getattr__(self, name: str) -> str: ...\ninteger = 0\nb = B()\nb.at = '3'  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    integer = b.at  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testSetattrKeywordArg]\nfrom typing import Any\n\nclass C:\n    def __setattr__(self, key: str, value: Any, p: bool = False) -> None: ...\n\nc: C\nc.__setattr__(\"x\", 42, p=True)\n\n-- CallableType objects\n-- ----------------\n\n\n[case testCallableObject]\nclass A:\n    def __call__(self, x: 'A') -> 'A':\n        pass\nclass B: pass\n\na = A()\nb = B()\n\na()  # E: Missing positional argument \"x\" in call to \"__call__\" of \"A\"\na(a, a)  # E: Too many arguments for \"__call__\" of \"A\"\nif int():\n    a = a(a)\nif int():\n    a = a(b)  # E: Argument 1 to \"__call__\" of \"A\" has incompatible type \"B\"; expected \"A\"\nif int():\n    b = a(a)  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n\n-- __new__\n-- --------\n\n\n[case testConstructInstanceWith__new__]\nfrom typing import Optional\nclass C:\n    def __new__(cls, foo: Optional[int] = None) -> 'C':\n        obj = object.__new__(cls)\n        return obj\n\nx = C(foo=12)\nx.a # E: \"C\" has no attribute \"a\"\nC(foo='') # E: Argument \"foo\" to \"C\" has incompatible type \"str\"; expected \"int | None\"\n[builtins fixtures/__new__.pyi]\n\n[case testConstructInstanceWithDynamicallyTyped__new__]\nclass C:\n    def __new__(cls, foo):\n        obj = object.__new__(cls)\n        return obj\n\nx = C(foo=12)\nx = C(foo='x')\nx.a # E: \"C\" has no attribute \"a\"\nC(bar='') # E: Unexpected keyword argument \"bar\" for \"C\"\n[builtins fixtures/__new__.pyi]\n\n[case testClassWith__new__AndCompatibilityWithType]\nfrom typing import Optional\nclass C:\n    def __new__(cls, foo: Optional[int] = None) -> 'C':\n        obj = object.__new__(cls)\n        return obj\ndef f(x: type) -> None: pass\ndef g(x: int) -> None: pass\nf(C)\ng(C) # E: Argument 1 to \"g\" has incompatible type \"type[C]\"; expected \"int\"\n[builtins fixtures/__new__.pyi]\n\n[case testClassWith__new__AndCompatibilityWithType2]\nclass C:\n    def __new__(cls, foo):\n        obj = object.__new__(cls)\n        return obj\ndef f(x: type) -> None: pass\ndef g(x: int) -> None: pass\nf(C)\ng(C) # E: Argument 1 to \"g\" has incompatible type \"type[C]\"; expected \"int\"\n[builtins fixtures/__new__.pyi]\n\n[case testGenericClassWith__new__]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C(Generic[T]):\n    def __new__(cls, foo: T) -> 'C[T]':\n        obj = object.__new__(cls)\n        return obj\n    def set(self, x: T) -> None: pass\nc = C('')\nc.set('')\nc.set(1) # E: Argument 1 to \"set\" of \"C\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/__new__.pyi]\n\n[case testOverloaded__new__]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass C:\n    @overload\n    def __new__(cls, foo: int) -> 'C':\n        obj = object.__new__(cls)\n        return obj\n    @overload\n    def __new__(cls, x: str, y: str) -> 'C':\n        obj = object.__new__(cls)\n        return obj\nc = C(1)\nc.a # E: \"C\" has no attribute \"a\"\nC('', '')\nC('') # E: No overload variant of \"C\" matches argument type \"str\" \\\n      # N: Possible overload variants: \\\n      # N:     def C(foo: int) -> C \\\n      # N:     def C(x: str, y: str) -> C\n[builtins fixtures/__new__.pyi]\n\n\n-- Special cases\n-- -------------\n\n\n[case testSubclassInt]\nimport typing\nclass A(int): pass\nn = 0\nif int():\n    n = A()\na = A()\nif int():\n    a = 0 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"A\")\n\n[case testForwardReferenceToNestedClass]\ndef f(o: 'B.C') -> None:\n    o.f('') # E: Argument 1 to \"f\" of \"C\" has incompatible type \"str\"; expected \"int\"\n\nclass B:\n    class C:\n        def f(self, x: int) -> None: pass\n[out]\n\n[case testForwardReferenceToNestedClassDeep]\ndef f(o: 'B.C.D') -> None:\n    o.f('') # E: Argument 1 to \"f\" of \"D\" has incompatible type \"str\"; expected \"int\"\n\nclass B:\n    class C:\n        class D:\n            def f(self, x: int) -> None: pass\n[out]\n\n[case testForwardReferenceToNestedClassWithinClass]\nclass B:\n    def f(self, o: 'C.D') -> None:\n        o.f('') # E: Argument 1 to \"f\" of \"D\" has incompatible type \"str\"; expected \"int\"\n\n    class C:\n        class D:\n            def f(self, x: int) -> None: pass\n[out]\n\n[case testClassVsInstanceDisambiguation]\nclass A: pass\ndef f(x: A) -> None: pass\nf(A) # E: Argument 1 to \"f\" has incompatible type \"type[A]\"; expected \"A\"\n[out]\n\n-- TODO\n--   attribute inherited from superclass; assign in __init__\n--   refer to attribute before type has been inferred (the initialization in\n--   __init__ has not been analyzed)\n\n[case testAnyBaseClassUnconstrainedConstructor]\nfrom typing import Any\nB = None  # type: Any\nclass C(B): pass\nC(0)\nC(arg=0)\n[out]\n\n[case testErrorMapToSupertype]\nimport typing\nclass X(Nope): pass  # E: Name \"Nope\" is not defined\na, b = X()  # Used to crash here (#2244)\n\n\n-- Class-valued attributes\n-- -----------------------\n\n[case testClassValuedAttributesBasics]\nclass A: ...\nclass B:\n    a = A\n    bad = lambda: 42\n\nB().bad() # E: Attribute function \"bad\" with type \"Callable[[], int]\" does not accept self argument\nreveal_type(B.a) # N: Revealed type is \"def () -> __main__.A\"\nreveal_type(B().a) # N: Revealed type is \"def () -> __main__.A\"\nreveal_type(B().a()) # N: Revealed type is \"__main__.A\"\n\nclass C:\n    a = A\n    def __init__(self) -> None:\n        self.aa = self.a()\n\nreveal_type(C().aa) # N: Revealed type is \"__main__.A\"\n[out]\n\n[case testClassValuedAttributesGeneric]\nfrom typing import Generic, TypeVar, Type\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    def __init__(self, x: T) -> None:\n        self.x = x\nclass B(Generic[T]):\n    a: Type[A[T]] = A\n\nreveal_type(B[int]().a) # N: Revealed type is \"type[__main__.A[builtins.int]]\"\nB[int]().a('hi') # E: Argument 1 to \"A\" has incompatible type \"str\"; expected \"int\"\n\nclass C(Generic[T]):\n    a = A\n    def __init__(self) -> None:\n        self.aa = self.a(42)\n\nreveal_type(C().aa) # N: Revealed type is \"__main__.A[builtins.int]\"\n[out]\n\n[case testClassValuedAttributesAlias]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass A(Generic[T, S]): ...\n\nSameA = A[T, T]\n\nclass B:\n    a_any = SameA\n    a_int = SameA[int]\n\nreveal_type(B().a_any) # N: Revealed type is \"def () -> __main__.A[Any, Any]\"\nreveal_type(B().a_int()) # N: Revealed type is \"__main__.A[builtins.int, builtins.int]\"\n\nclass C:\n    a_int = SameA[int]\n    def __init__(self) -> None:\n        self.aa = self.a_int()\n\nreveal_type(C().aa) # N: Revealed type is \"__main__.A[builtins.int, builtins.int]\"\n[out]\n\n\n-- Type[C]\n-- -------\n\n\n[case testTypeUsingTypeCBasic]\nfrom typing import Type\nclass User: pass\nclass ProUser(User): pass\ndef new_user(user_class: Type[User]) -> User:\n    return user_class()\nreveal_type(new_user(User))  # N: Revealed type is \"__main__.User\"\nreveal_type(new_user(ProUser))  # N: Revealed type is \"__main__.User\"\n[out]\n\n[case testTypeUsingTypeCDefaultInit]\nfrom typing import Type\nclass B:\n    pass\ndef f(A: Type[B]) -> None:\n    A(0)  # E: Too many arguments for \"B\"\n    A()\n[out]\n\n[case testTypeUsingTypeCInitWithArg]\nfrom typing import Type\nclass B:\n    def __init__(self, a: int) -> None: pass\ndef f(A: Type[B]) -> None:\n    A(0)\n    A()  # E: Missing positional argument \"a\" in call to \"B\"\n[out]\n\n[case testTypeUsingTypeCTypeVar]\nfrom typing import Type, TypeVar\nclass User: pass\nclass ProUser(User): pass\nU = TypeVar('U', bound=User)\ndef new_user(user_class: Type[U]) -> U:\n    user = user_class()\n    reveal_type(user)\n    return user\npro_user = new_user(ProUser)\nreveal_type(pro_user)\n[out]\nmain:7: note: Revealed type is \"U`-1\"\nmain:10: note: Revealed type is \"__main__.ProUser\"\n\n[case testTypeUsingTypeCTypeVarDefaultInit]\nfrom typing import Type, TypeVar\nclass B:\n    pass\nT = TypeVar('T', bound=B)\ndef f(A: Type[T]) -> None:\n    A()\n    A(0)  # E: Too many arguments for \"B\"\n[out]\n\n[case testTypeUsingTypeCTypeVarWithInit]\nfrom typing import Type, TypeVar\nclass B:\n    def __init__(self, a: int) -> None: pass\nT = TypeVar('T', bound=B)\ndef f(A: Type[T]) -> None:\n    A()  # E: Missing positional argument \"a\" in call to \"B\"\n    A(0)\n[out]\n\n[case testTypeUsingTypeCTwoTypeVars]\nfrom typing import Type, TypeVar\nclass User: pass\nclass ProUser(User): pass\nclass WizUser(ProUser): pass\nU = TypeVar('U', bound=User)\ndef new_user(u_c: Type[U]) -> U: pass\nP = TypeVar('P', bound=ProUser)\ndef new_pro(pro_c: Type[P]) -> P:\n    return new_user(pro_c)\nwiz = new_pro(WizUser)\nreveal_type(wiz)\ndef error(u_c: Type[U]) -> P: # Error here, see below\n    return new_pro(u_c)  # Error here, see below\n[out]\nmain:11: note: Revealed type is \"__main__.WizUser\"\nmain:12: error: A function returning TypeVar should receive at least one argument containing the same TypeVar\nmain:12: note: Consider using the upper bound \"ProUser\" instead\nmain:13: error: Value of type variable \"P\" of \"new_pro\" cannot be \"U\"\nmain:13: error: Incompatible return value type (got \"U\", expected \"P\")\n\n[case testTypeUsingTypeCCovariance]\nfrom typing import Type, TypeVar\nclass User: pass\nclass ProUser(User): pass\ndef new_user(user_class: Type[User]) -> User:\n    return user_class()\ndef new_pro_user(user_class: Type[ProUser]):\n    new_user(user_class)\n[out]\n\n[case testAllowCovariantArgsInConstructor]\nfrom typing import Generic, TypeVar\n\nT_co = TypeVar('T_co', covariant=True)\n\nclass C(Generic[T_co]):\n    def __init__(self, x: T_co) -> None: # This should be allowed\n        self.x = x\n    def meth(self) -> None:\n        reveal_type(self.x) # N: Revealed type is \"T_co`1\"\n\nreveal_type(C(1).x) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/property.pyi]\n[out]\n\n[case testTypeUsingTypeCErrorCovariance]\nfrom typing import Type, TypeVar\nclass User: pass\ndef new_user(user_class: Type[User]):\n    return user_class()\ndef foo(arg: Type[int]):\n    new_user(arg)  # E: Argument 1 to \"new_user\" has incompatible type \"type[int]\"; expected \"type[User]\"\n[out]\n\n[case testTypeUsingTypeCUnionOverload]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, Union, overload\nclass X:\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, a: int) -> None: pass\nclass Y:\n    def __init__(self) -> None: pass\ndef bar(o: Type[Union[X, Y]]): pass\nbar(X)\nbar(Y)\n[out]\n\n[case testTypeUsingTypeCTypeAny]\nfrom typing import Type, Any\ndef foo(arg: Type[Any]):\n    x = arg()\n    x = arg(0)\n    x = arg('', ())\n    reveal_type(x)  # N: Revealed type is \"Any\"\n    x.foo\nclass X: pass\nfoo(X)\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTypeUsingTypeCTypeAnyMember]\nfrom typing import Type, Any\ndef foo(arg: Type[Any]):\n    x = arg.member_name\n    arg.new_member_name = 42\n    # Member access is ok and types as Any\n    reveal_type(x)  # N: Revealed type is \"Any\"\n    # But type[Any] is distinct from Any\n    y: int = arg  # E: Incompatible types in assignment (expression has type \"type[Any]\", variable has type \"int\")\n[out]\n\n[case testTypeUsingTypeCTypeAnyMemberFallback]\nfrom typing import Type, Any\ndef foo(arg: Type[Any]):\n    reveal_type(arg.__str__)  # N: Revealed type is \"def () -> builtins.str\"\n    reveal_type(arg.mro())  # N: Revealed type is \"builtins.list[builtins.type]\"\n[builtins fixtures/type.pyi]\n[out]\n\n[case testTypeUsingTypeCTypeNoArg]\nfrom typing import Type\ndef foo(arg: Type):\n    x = arg()\n    reveal_type(x)  # N: Revealed type is \"Any\"\nclass X: pass\nfoo(X)\n[out]\n\n[case testTypeUsingTypeCBuiltinType]\nfrom typing import Type\ndef foo(arg: type): pass\nclass X: pass\ndef bar(arg: Type[X]):\n    foo(arg)\nfoo(X)\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTypeUsingTypeCClassMethod]\nfrom typing import Type\nclass User:\n    @classmethod\n    def foo(cls) -> int: pass\n    def bar(self) -> int: pass\ndef process(cls: Type[User]):\n    reveal_type(cls.foo())  # N: Revealed type is \"builtins.int\"\n    obj = cls()\n    reveal_type(cls.bar(obj))  # N: Revealed type is \"builtins.int\"\n    cls.mro()  # Defined in class type\n    cls.error  # E: \"type[User]\" has no attribute \"error\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testTypeUsingTypeCClassMethodUnion]\nfrom typing import Type, Union\nclass User:\n    @classmethod\n    def foo(cls) -> int: pass\n    def bar(self) -> int: pass\nclass ProUser(User): pass\nclass BasicUser(User): pass\ndef process(cls: Type[Union[BasicUser, ProUser]]):\n    cls.foo()\n    obj = cls()\n    cls.bar(obj)\n    cls.mro()  # Defined in class type\n    cls.error  # E: Item \"type\" of \"type[BasicUser] | type[ProUser]\" has no attribute \"error\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testTypeUsingTypeCClassMethodFromTypeVar]\nfrom typing import Type, TypeVar\nclass User:\n    @classmethod\n    def foo(cls) -> int: pass\n    def bar(self) -> int: pass\nU = TypeVar('U', bound=User)\ndef process(cls: Type[U]):\n    reveal_type(cls.foo())  # N: Revealed type is \"builtins.int\"\n    obj = cls()\n    reveal_type(cls.bar(obj))  # N: Revealed type is \"builtins.int\"\n    cls.mro()  # Defined in class type\n    cls.error  # E: \"type[U]\" has no attribute \"error\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testTypeUsingTypeCClassMethodFromTypeVarUnionBound]\n# Ideally this would work, but not worth the effort; just don't crash\nfrom typing import Type, TypeVar, Union\nclass User:\n    @classmethod\n    def foo(cls) -> int: pass\n    def bar(self) -> int: pass\nclass ProUser(User): pass\nclass BasicUser(User): pass\nU = TypeVar('U', bound=Union[ProUser, BasicUser])\ndef process(cls: Type[U]):\n    cls.foo()\n    obj = cls()\n    cls.bar(obj)\n    cls.mro()  # Defined in class type\n    cls.error  # E: \"type[U]\" has no attribute \"error\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testTypeUsingTypeCErrorUnsupportedType]\nfrom typing import Type, Tuple\ndef foo(arg: Type[Tuple[int]]):\n    arg()  # E: Cannot instantiate type \"type[tuple[int]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeUsingTypeCOverloadedClass]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, TypeVar, overload\nclass User:\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, arg: int) -> None: pass\n    @classmethod\n    def foo(cls) -> None: pass\nU = TypeVar('U', bound=User)\ndef new(uc: Type[U]) -> U:\n    uc.foo()\n    u = uc()\n    u.foo()\n    if 1:\n        u = uc(0)\n        u.foo()\n        uc('')  # Error\n        u.foo(0)  # Error\n        return uc()\nu = new(User)\n[builtins fixtures/classmethod.pyi]\n[out]\ntmp/foo.pyi:17: error: No overload variant of \"User\" matches argument type \"str\"\ntmp/foo.pyi:17: note: Possible overload variants:\ntmp/foo.pyi:17: note:     def User() -> U\ntmp/foo.pyi:17: note:     def User(arg: int) -> U\ntmp/foo.pyi:18: error: Too many arguments for \"foo\" of \"User\"\n\n[case testTypeUsingTypeCInUpperBound]\nfrom typing import TypeVar, Type\nclass B: pass\nT = TypeVar('T', bound=Type[B])\ndef f(a: T): pass\n[out]\n\n[case testTypeUsingTypeCTuple]\nfrom typing import Type, Tuple\ndef f(a: Type[Tuple[int, int]]):\n    a()  # E: Cannot instantiate type \"type[tuple[int, int]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeUsingTypeCNamedTuple]\nfrom typing import Type, NamedTuple\nN = NamedTuple('N', [('x', int), ('y', int)])\ndef f(a: Type[N]):\n    a()\n[builtins fixtures/list.pyi]\n[out]\nmain:4: error: Missing positional arguments \"x\", \"y\" in call to \"N\"\n\n[case testTypeUsingTypeCJoin]\nfrom typing import Type\nclass B: pass\nclass C(B): pass\nclass D(B): pass\ndef foo(c: Type[C], d: Type[D]) -> None:\n    x = [c, d]\n    reveal_type(x)\n\n[builtins fixtures/list.pyi]\n[out]\nmain:7: note: Revealed type is \"builtins.list[type[__main__.B]]\"\n\n[case testTypeEquivalentTypeAny]\nfrom typing import Type, Any\n\na: Type[Any]\nb = a # type: type\n\nx: type\ny = x # type: Type[Any]\n\nclass C: ...\n\np: type\nq = p # type: Type[C]\n\n[builtins fixtures/list.pyi]\n[out]\n\n[case testTypeEquivalentTypeAny2]\nfrom typing import Type, Any, TypeVar, Generic\n\nclass C: ...\nx: type\ny: Type[Any]\nz: Type[C]\n\nlst = [x, y, z]\nreveal_type(lst) # N: Revealed type is \"builtins.list[builtins.type]\"\n\nT1 = TypeVar('T1', bound=type)\nT2 = TypeVar('T2', bound=Type[Any])\nclass C1(Generic[T1]): ...\nclass C2(Generic[T2]): ...\n\nC1[Type[Any]], C2[type] # both these should not fail\n[builtins fixtures/list.pyi]\n[out]\n\n[case testTypeEquivalentTypeAnyEdgeCase]\nclass C:\n    pass\n\nclass M(type):\n    def __init__(cls, x) -> None:\n        type.__init__(cls, x)\n\nclass Mbad(type):\n    def __init__(cls, x) -> None:\n        type.__init__(C(), x) # E: Argument 1 to \"__init__\" of \"type\" has incompatible type \"C\"; expected \"type\"\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testTypeMatchesOverloadedFunctions]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload, Any\n\nclass User: pass\nUserType = User  # type: Type[User]\n\n@overload\ndef f(a: int) -> Any: pass\n@overload\ndef f(a: object) -> int: pass\n\nreveal_type(f(User))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(UserType))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testTypeMatchesGeneralTypeInOverloadedFunctions]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload\n\nclass User: pass\nUserType = User  # type: Type[User]\n\n@overload\ndef f(a: type) -> int:\n    return 1\n@overload\ndef f(a: int) -> str:\n    return \"a\"\n\nreveal_type(f(User))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(UserType))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(1))  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testTypeMatchesSpecificTypeInOverloadedFunctions]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload\n\nclass User: pass\nUserType = User  # type: Type[User]\n\n@overload\ndef f(a: User) -> User:\n    return User()\n@overload\ndef f(a: Type[User]) -> int:\n    return 1\n@overload\ndef f(a: int) -> str:\n    return \"a\"\n\nreveal_type(f(User))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(UserType))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(User()))  # N: Revealed type is \"foo.User\"\nreveal_type(f(1))  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testMixingTypeTypeInOverloadedFunctions]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload\n\nclass User: pass\n\n@overload\ndef f(a: User) -> Type[User]:\n    return User\n@overload\ndef f(a: Type[User]) -> User:\n    return a()\n@overload\ndef f(a: int) -> Type[User]:\n    return User\n@overload\ndef f(a: str) -> User:\n    return User()\n\nreveal_type(f(User()))  # N: Revealed type is \"type[foo.User]\"\nreveal_type(f(User))  # N: Revealed type is \"foo.User\"\nreveal_type(f(3))  # N: Revealed type is \"type[foo.User]\"\nreveal_type(f(\"hi\"))  # N: Revealed type is \"foo.User\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testGeneralTypeMatchesSpecificTypeInOverloadedFunctions]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, Any, overload\n\nclass User: pass\n\n@overload\ndef f(a: Type[User]) -> None: pass\n@overload\ndef f(a: int) -> None: pass\n\ndef mock_1() -> type: return User\ndef mock_2() -> Type[Any]: return User\n\nf(User)\nf(mock_1())\nf(mock_2())\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testNonTypeDoesNotMatchOverloadedFunctions]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload\n\nclass User: pass\n\n@overload\ndef f(a: Type[User]) -> None: pass\n@overload\ndef f(a: type) -> None: pass\n\nf(3)  # E: No overload variant of \"f\" matches argument type \"int\" \\\n      # N: Possible overload variants: \\\n      # N:     def f(a: type[User]) -> None \\\n      # N:     def f(a: type) -> None\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testInstancesDoNotMatchTypeInOverloadedFunctions]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload\n\nclass User: pass\n\n@overload\ndef f(a: Type[User]) -> None: pass\n@overload\ndef f(a: int) -> None: pass\n\nf(User)\nf(User())  # E: No overload variant of \"f\" matches argument type \"User\" \\\n           # N: Possible overload variants: \\\n           # N:     def f(a: type[User]) -> None \\\n           # N:     def f(a: int) -> None\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testTypeCovarianceWithOverloadedFunctions]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\nAType = A  # type: Type[A]\nBType = B  # type: Type[B]\nCType = C  # type: Type[C]\n\n@overload\ndef f(a: Type[B]) -> None: pass\n@overload\ndef f(a: int) -> None: pass\n\nf(A)  # E: Argument 1 to \"f\" has incompatible type \"type[A]\"; expected \"type[B]\"\nf(B)\nf(C)\nf(AType)  # E: Argument 1 to \"f\" has incompatible type \"type[A]\"; expected \"type[B]\"\nf(BType)\nf(CType)\n[builtins fixtures/classmethod.pyi]\n[out]\n\n\n[case testOverloadedCovariantTypesFail]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload\n\nclass A: pass\nclass B(A): pass\n\n@overload\ndef f(a: Type[B]) -> int: pass  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(a: Type[A]) -> str: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testDistinctOverloadedCovariantTypesSucceed]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload\n\nclass A: pass\nclass AChild(A): pass\nclass B: pass\nclass BChild(B): pass\n\n@overload\ndef f(a: Type[A]) -> int: pass\n@overload\ndef f(a: Type[B]) -> str: pass\n@overload\ndef f(a: A) -> A: pass\n@overload\ndef f(a: B) -> B: pass\n\nreveal_type(f(A))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(AChild))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(B))  # N: Revealed type is \"builtins.str\"\nreveal_type(f(BChild))  # N: Revealed type is \"builtins.str\"\n\nreveal_type(f(A()))  # N: Revealed type is \"foo.A\"\nreveal_type(f(AChild()))  # N: Revealed type is \"foo.A\"\nreveal_type(f(B()))  # N: Revealed type is \"foo.B\"\nreveal_type(f(BChild()))  # N: Revealed type is \"foo.B\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testSubtypeWithMoreOverloadsThanSupertypeSucceeds]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n\n\nclass X: pass\nclass Y: pass\nclass Z: pass\n\n\nclass A:\n    @overload\n    def f(self, x: X) -> X: pass\n    @overload\n    def f(self, y: Y) -> Y: pass\n\nclass B(A):\n    @overload\n    def f(self, x: X) -> X: pass\n    @overload\n    def f(self, y: Y) -> Y: pass\n    @overload\n    def f(self, z: Z) -> Z: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testSubtypeOverloadCoveringMultipleSupertypeOverloadsSucceeds]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n\n\nclass A: pass\nclass B(A): pass\nclass C(A): pass\nclass D: pass\n\n\nclass Super:\n    @overload\n    def foo(self, a: B) -> C: pass\n    @overload\n    def foo(self, a: C) -> A: pass\n    @overload\n    def foo(self, a: D) -> D: pass\n\nclass Sub(Super):\n    @overload\n    def foo(self, a: A) -> C: pass\n    @overload\n    def foo(self, a: D) -> D: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testSubtypeOverloadWithOverlappingArgumentsButWrongReturnType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n\n\nclass A: pass\nclass B(A): pass\nclass C: pass\n\n\nclass Super:\n    @overload\n    def foo(self, a: A) -> A: pass\n    @overload\n    def foo(self, a: C) -> C: pass\n\nclass Sub(Super):\n    @overload\n    def foo(self, a: A) -> A: pass\n    @overload\n    def foo(self, a: B) -> C: pass  # Fail\n    @overload\n    def foo(self, a: C) -> C: pass\n\nclass Sub2(Super):\n    @overload\n    def foo(self, a: B) -> C: pass  # Fail\n    @overload\n    def foo(self, a: A) -> A: pass\n    @overload\n    def foo(self, a: C) -> C: pass\n\nclass Sub3(Super):\n    @overload\n    def foo(self, a: A) -> int: pass\n    @overload\n    def foo(self, a: A) -> A: pass\n    @overload\n    def foo(self, a: C) -> C: pass\n[builtins fixtures/classmethod.pyi]\n[out]\ntmp/foo.pyi:19: error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\ntmp/foo.pyi:24: error: Signature of \"foo\" incompatible with supertype \"Super\"\ntmp/foo.pyi:24: note:      Superclass:\ntmp/foo.pyi:24: note:          @overload\ntmp/foo.pyi:24: note:          def foo(self, a: A) -> A\ntmp/foo.pyi:24: note:          @overload\ntmp/foo.pyi:24: note:          def foo(self, a: C) -> C\ntmp/foo.pyi:24: note:      Subclass:\ntmp/foo.pyi:24: note:          @overload\ntmp/foo.pyi:24: note:          def foo(self, a: B) -> C\ntmp/foo.pyi:24: note:          @overload\ntmp/foo.pyi:24: note:          def foo(self, a: A) -> A\ntmp/foo.pyi:24: note:          @overload\ntmp/foo.pyi:24: note:          def foo(self, a: C) -> C\ntmp/foo.pyi:25: error: Overloaded function signatures 1 and 2 overlap with incompatible return types\ntmp/foo.pyi:32: error: Signature of \"foo\" incompatible with supertype \"Super\"\ntmp/foo.pyi:32: note:      Superclass:\ntmp/foo.pyi:32: note:          @overload\ntmp/foo.pyi:32: note:          def foo(self, a: A) -> A\ntmp/foo.pyi:32: note:          @overload\ntmp/foo.pyi:32: note:          def foo(self, a: C) -> C\ntmp/foo.pyi:32: note:      Subclass:\ntmp/foo.pyi:32: note:          @overload\ntmp/foo.pyi:32: note:          def foo(self, a: A) -> int\ntmp/foo.pyi:32: note:          @overload\ntmp/foo.pyi:32: note:          def foo(self, a: A) -> A\ntmp/foo.pyi:32: note:          @overload\ntmp/foo.pyi:32: note:          def foo(self, a: C) -> C\ntmp/foo.pyi:35: error: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader\n\n[case testTypeTypeOverlapsWithObjectAndType]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload\n\nclass User: pass\n\n@overload\ndef f(a: Type[User]) -> int: pass  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(a: object) -> str: pass\n\n# Note: plain type is equivalent to Type[Any] so no error here\n@overload\ndef g(a: Type[User]) -> int: pass\n@overload\ndef g(a: type) -> str: pass\n\n@overload\ndef h(a: Type[User]) -> int: pass  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef h(a: Type[object]) -> str: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testTypeOverlapsWithObject]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Type, overload\n\nclass User: pass\n\n@overload\ndef f(a: type) -> int: pass  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef f(a: object) -> str: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testTypeConstructorReturnsTypeType]\nclass User:\n    @classmethod\n    def test_class_method(cls) -> int: pass\n    @staticmethod\n    def test_static_method() -> str: pass\n    def test_instance_method(self) -> None: pass\n\nu = User()\n\nreveal_type(type(u))  # N: Revealed type is \"type[__main__.User]\"\nreveal_type(type(u).test_class_method())  # N: Revealed type is \"builtins.int\"\nreveal_type(type(u).test_static_method())  # N: Revealed type is \"builtins.str\"\ntype(u).test_instance_method()  # E: Missing positional argument \"self\" in call to \"test_instance_method\" of \"User\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testObfuscatedTypeConstructorReturnsTypeType]\nfrom typing import TypeVar\nclass User: pass\n\nf1 = type\n\nA = TypeVar('A')\ndef f2(func: A) -> A:\n    return func\n\nu = User()\n\nreveal_type(f1(u))  # N: Revealed type is \"type[__main__.User]\"\nreveal_type(f2(type)(u))  # N: Revealed type is \"type[__main__.User]\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testTypeConstructorLookalikeFails]\nclass User: pass\n\ndef fake1(a: object) -> type:\n    return User\ndef fake2(a: int) -> type:\n    return User\n\nreveal_type(type(User()))  # N: Revealed type is \"type[__main__.User]\"\nreveal_type(fake1(User()))  # N: Revealed type is \"builtins.type\"\nreveal_type(fake2(3))  # N: Revealed type is \"builtins.type\"\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testOtherTypeConstructorsSucceed]\ndef foo(self) -> int: return self.attr\n\nUser = type('User', (object,), {'foo': foo, 'attr': 3})\nreveal_type(User)  # N: Revealed type is \"builtins.type\"\n[builtins fixtures/args.pyi]\n[out]\n\n[case testTypeTypeComparisonWorks]\nclass User: pass\n\nUser == User\nUser == type(User())\ntype(User()) == User\ntype(User()) == type(User())\n\nUser != User\nUser != type(User())\ntype(User()) != User\ntype(User()) != type(User())\n\nint == int\nint == type(3)\ntype(3) == int\ntype(3) == type(3)\n\nint != int\nint != type(3)\ntype(3) != int\ntype(3) != type(3)\n\nUser is User\nUser is type(User)\ntype(User) is User\ntype(User) is type(User)\n\nint is int\nint is type(3)\ntype(3) is int\ntype(3) is type(3)\n\nint.__eq__(int)\nint.__eq__(3, 4)\n[builtins fixtures/args.pyi]\n[out]\nmain:33: error: Too few arguments for \"__eq__\" of \"int\"\nmain:33: error: Unsupported operand types for == (\"type[int]\" and \"type[int]\")\n\n[case testDupBaseClasses]\nclass A:\n    def method(self) -> str: ...\n\nclass B(A, A):  # E: Duplicate base class \"A\"\n    attr: int\n\nb: B\n\nreveal_type(b.method())  # N: Revealed type is \"Any\"\nreveal_type(b.missing())  # N: Revealed type is \"Any\"\nreveal_type(b.attr)  # N: Revealed type is \"builtins.int\"\n\n[case testDupBaseClassesGeneric]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\nclass A(Generic[T]):\n    def method(self) -> T: ...\n\nclass B(A[int], A[str]):  # E: Duplicate base class \"A\"\n    attr: int\n\nreveal_type(B().method())  # N: Revealed type is \"Any\"\nreveal_type(B().attr)   # N: Revealed type is \"builtins.int\"\n\n[case testCannotDetermineMro]\nclass A: pass\nclass B(A): pass\nclass C(B): pass\nclass D(A, B): pass # E: Cannot determine consistent method resolution order (MRO) for \"D\"\nclass E(C, D): pass\n\n[case testInconsistentMroLocalRef]\nclass A: pass\nclass B(object, A): # E: Cannot determine consistent method resolution order (MRO) for \"B\"\n    def readlines(self): pass\n    __iter__ = readlines\n\n[case testDynamicMetaclass]\nclass C(metaclass=int()):  # E: Dynamic metaclass not supported for \"C\"\n    pass\n\n[case testDynamicMetaclassCrash]\nclass C(metaclass=int().x):  # E: Dynamic metaclass not supported for \"C\"\n    pass\n\n[case testVariableSubclass]\nclass A:\n    a = 1  # type: int\nclass B(A):\n    a = 1\n[out]\n\n[case testVariableSubclassAssignMismatch]\nclass A:\n    a = 1  # type: int\nclass B(A):\n    a = \"a\"\n[out]\nmain:4: error: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\n\n[case testVariableSubclassAssignment]\nclass A:\n    a: int\nclass B(A):\n    def __init__(self) -> None:\n        self.a = \"a\"\n[out]\nmain:5: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testVariableSubclassTypeOverwrite]\nclass A:\n    a: int\nclass B(A):\n    a: str\nclass C(B):\n    a = \"a\"\n[out]\nmain:4: error: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\n\n[case testVariableSubclassTypeOverwriteImplicit]\nclass A:\n    a = 1\nclass B(A):\n    a: str\n[out]\nmain:4: error: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\n\n[case testVariableSuperUsage]\nclass A:\n    a = []  # type: list\nclass B(A):\n    a = [1, 2]\nclass C(B):\n    a = B.a + [3]\n[builtins fixtures/list.pyi]\n[out]\n\n[case testClassAllBases]\nfrom typing import Union\nclass A:\n    a: Union[int, str]\nclass B(A):\n    a = 1\nclass C(B):\n    a = \"str\"\nclass D(A):\n    a = \"str\"\n[out]\nmain:7: error: Incompatible types in assignment (expression has type \"str\", base class \"B\" defined the type as \"int\")\n\n[case testVariableTypeVar]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    a: T\nclass B(A[int]):\n    a = 1\n\n[case testVariableTypeVarInvalid]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    a: T\nclass B(A[int]):\n    a = \"abc\"\n[out]\nmain:6: error: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\n\n[case testVariableTypeVarIndirectly]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    a: T\nclass B(A[int]):\n    pass\nclass C(B):\n    a = \"a\"\n[out]\nmain:8: error: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\n\n[case testVariableTypeVarList]\nfrom typing import List, TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    a: List[T]\n    b: List[T]\nclass B(A[int]):\n    a = [1]\n    b = ['']\n[builtins fixtures/list.pyi]\n[out]\nmain:8: error: List item 0 has incompatible type \"str\"; expected \"int\"\n\n[case testVariableMethod]\nclass A:\n    def a(self) -> None: pass\n    b = 1\nclass B(A):\n    a = 1  # E: Incompatible types in assignment (expression has type \"int\", base class \"A\" defined the type as \"Callable[[], None]\")\n    def b(self) -> None: pass  # E: Signature of \"b\" incompatible with supertype \"A\" \\\n                               # N:      Superclass: \\\n                               # N:          int \\\n                               # N:      Subclass: \\\n                               # N:          def b(self) -> None\n\n[case testVariableProperty]\nclass A:\n    @property\n    def a(self) -> bool: pass\nclass B(A):\n    a: bool\nclass C(A):\n    a = True\nclass D(A):\n    a = 1\n[builtins fixtures/property.pyi]\n[out]\nmain:9: error: Incompatible types in assignment (expression has type \"int\", base class \"A\" defined the type as \"bool\")\n\n[case testVariableOverwriteAny]\nfrom typing import Any\nclass A:\n    a = 1\nclass B(A):\n    a = 'x'  # type: Any\n[out]\n\n[case testInstanceMethodOverwrite]\nclass B():\n    def n(self, a: int) -> None: pass\nclass C(B):\n    def m(self, a: int) -> None: pass\n    n = m\n[out]\n\n[case testInstanceMethodOverwriteError]\nclass B():\n    def n(self, a: int) -> None: pass\nclass C(B):\n    def m(self, a: str) -> None: pass\n    n = m\n[out]\nmain:5: error: Incompatible types in assignment (expression has type \"Callable[[str], None]\", base class \"B\" defined the type as \"Callable[[int], None]\")\n\n[case testInstanceMethodOverwriteTypevar]\nfrom typing import Generic, TypeVar\nT = TypeVar(\"T\")\nclass B(Generic[T]):\n    def n(self, a: T) -> None: pass\nclass C(B[int]):\n    def m(self, a: int) -> None: pass\n    n = m\n\n[case testInstanceMethodOverwriteTwice]\nclass I:\n    def foo(self) -> None: pass\nclass A(I):\n    def foo(self) -> None: pass\nclass B(A):\n    def bar(self) -> None: pass\n    foo = bar\nclass C(B):\n    def bar(self) -> None: pass\n    foo = bar\n\n[case testClassMethodOverwrite]\nclass B():\n    @classmethod\n    def n(self, a: int) -> None: pass\nclass C(B):\n    @classmethod\n    def m(self, a: int) -> None: pass\n    n = m\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testClassMethodOverwriteError]\nclass B():\n    @classmethod\n    def n(self, a: int) -> None: pass\nclass C(B):\n    @classmethod\n    def m(self, a: str) -> None: pass\n    n = m\n[builtins fixtures/classmethod.pyi]\n[out]\nmain:7: error: Incompatible types in assignment (expression has type \"Callable[[str], None]\", base class \"B\" defined the type as \"Callable[[int], None]\")\n\n[case testClassSpec]\nfrom typing import Callable\nclass A():\n    b: Callable[[int], int]\nclass B(A):\n    def c(self, a: int) -> int: pass\n    b = c\nreveal_type(A().b)  # N: Revealed type is \"def (builtins.int) -> builtins.int\"\nreveal_type(B().b)  # N: Revealed type is \"def (a: builtins.int) -> builtins.int\"\n\n[case testClassSpecError]\nfrom typing import Callable\nclass A():\n    b: Callable[[int], int]\nclass B(A):\n    def c(self, a: str) -> int: pass\n    b = c  # E: Incompatible types in assignment (expression has type \"Callable[[str], int]\", base class \"A\" defined the type as \"Callable[[int], int]\")\n\n[case testClassStaticMethod]\nclass A():\n    @staticmethod\n    def a(a: int) -> None: pass\nclass B(A):\n    @staticmethod\n    def b(a: str) -> None: pass\n    a = b\n[builtins fixtures/staticmethod.pyi]\n[out]\nmain:7: error: Incompatible types in assignment (expression has type \"Callable[[str], None]\", base class \"A\" defined the type as \"Callable[[int], None]\")\n\n[case testClassStaticMethodIndirect]\nclass A():\n    @staticmethod\n    def a(a: int) -> None: pass\n    c = a\nclass B(A):\n    @staticmethod\n    def b(a: str) -> None: pass\n    c = b  # E: Incompatible types in assignment (expression has type \"Callable[[str], None]\", base class \"A\" defined the type as \"Callable[[int], None]\")\na: A\nreveal_type(a.a)  # N: Revealed type is \"def (a: builtins.int)\"\nreveal_type(a.c)  # N: Revealed type is \"def (a: builtins.int)\"\n[builtins fixtures/staticmethod.pyi]\n\n[case testClassStaticMethodIndirectOverloaded]\nfrom typing import overload\nclass A:\n    @overload\n    @staticmethod\n    def a(x: int) -> int: ...\n    @overload\n    @staticmethod\n    def a(x: str) -> str: ...\n    @staticmethod\n    def a(x):\n        ...\n    c = a\nreveal_type(A.c)  # N: Revealed type is \"Overload(def (x: builtins.int) -> builtins.int, def (x: builtins.str) -> builtins.str)\"\nreveal_type(A().c)  # N: Revealed type is \"Overload(def (x: builtins.int) -> builtins.int, def (x: builtins.str) -> builtins.str)\"\n[builtins fixtures/staticmethod.pyi]\n\n[case testClassStaticMethodSubclassing]\nclass A:\n    @staticmethod\n    def a() -> None: pass\n\n    def b(self) -> None: pass\n\n    @staticmethod\n    def c() -> None: pass\n\nclass B(A):\n    def a(self) -> None: pass  # Fail\n\n    @classmethod\n    def b(cls) -> None: pass\n\n    @staticmethod\n    def c() -> None: pass\n[builtins fixtures/classmethod.pyi]\n[out]\nmain:11: error: Signature of \"a\" incompatible with supertype \"A\"\nmain:11: note:      Superclass:\nmain:11: note:          @staticmethod\nmain:11: note:          def a() -> None\nmain:11: note:      Subclass:\nmain:11: note:          def a(self) -> None\n\n[case testTempNode]\nclass A():\n    def a(self) -> None: pass\nclass B(A):\n    def b(self) -> None: pass\n    a = c = b\n\n[case testListObject]\nfrom typing import List\nclass A:\n    x = []  # type: List[object]\nclass B(A):\n    x = [1]\n[builtins fixtures/list.pyi]\n\n[case testClassMemberObject]\nclass A:\n    x = object()\nclass B(A):\n    x = 1\nclass C(B):\n    x = ''\n[out]\nmain:6: error: Incompatible types in assignment (expression has type \"str\", base class \"B\" defined the type as \"int\")\n\n[case testSlots]\nclass A:\n    __slots__ = (\"a\")\nclass B(A):\n    __slots__ = (\"a\", \"b\")\n[builtins fixtures/tuple.pyi]\n\n[case testClassOrderOfError]\nclass A:\n    x = 1\nclass B(A):\n    x = \"a\"  # E: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\nclass C(B):\n    x = object()  # E: Incompatible types in assignment (expression has type \"object\", base class \"B\" defined the type as \"str\")\n\n[case testClassOneErrorPerLine]\nclass A:\n    x = 1\nclass B(A):\n    x: str = \"\"  # E: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\n    x = 1.0  # E: Incompatible types in assignment (expression has type \"float\", variable has type \"str\")\nclass BInfer(A):\n    x = \"\"  # E: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\n    x = 1.0  # E: Incompatible types in assignment (expression has type \"float\", variable has type \"str\") \\\n             # E: Incompatible types in assignment (expression has type \"float\", base class \"A\" defined the type as \"int\")\n\n[case testClassIgnoreType_RedefinedAttributeAndGrandparentAttributeTypesNotIgnored]\nclass A:\n    x = 0\nclass B(A):\n    x = ''  # type: ignore\nclass C(B):\n    x = ''\n\n[case testClassIgnoreType_RedefinedAttributeTypeIgnoredInChildren]\nclass A:\n    x = 0\nclass B(A):\n    x = ''  # type: ignore\nclass C(B):\n    x = ''  # type: ignore\n\n[case testInvalidMetaclassStructure]\nclass X(type): pass\nclass Y(type): pass\nclass A(metaclass=X): pass\nclass B(A, metaclass=Y): pass  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                               # N: \"__main__.Y\" (metaclass of \"__main__.B\") conflicts with \"__main__.X\" (metaclass of \"__main__.A\")\n[case testMetaclassNoTypeReveal]\nclass M:\n    x = 0  # type: int\n\nclass A(metaclass=M): pass  # E: Metaclasses not inheriting from \"type\" are not supported\n\nA.x  # E: \"type[A]\" has no attribute \"x\"\n\n[case testMetaclassTypeReveal]\nfrom typing import Type\nclass M(type):\n    x = 0  # type: int\n\nclass A(metaclass=M): pass\n\ndef f(TA: Type[A]):\n    reveal_type(TA)  # N: Revealed type is \"type[__main__.A]\"\n    reveal_type(TA.x)  # N: Revealed type is \"builtins.int\"\n\n[case testMetaclassConflictingInstanceVars]\nfrom typing import ClassVar\n\nclass Meta(type):\n    foo: int\n    bar: int\n    eggs: ClassVar[int] = 42\n    spam: ClassVar[int] = 42\n\nclass Foo(metaclass=Meta):\n    foo: str\n    bar: ClassVar[str] = 'bar'\n    eggs: str\n    spam: ClassVar[str] = 'spam'\n\nreveal_type(Foo.foo)  # N: Revealed type is \"builtins.int\"\nreveal_type(Foo.bar)  # N: Revealed type is \"builtins.str\"\nreveal_type(Foo.eggs)  # N: Revealed type is \"builtins.int\"\nreveal_type(Foo.spam)  # N: Revealed type is \"builtins.str\"\n\nclass MetaSub(Meta): ...\n\nclass Bar(metaclass=MetaSub):\n    foo: str\n    bar: ClassVar[str] = 'bar'\n    eggs: str\n    spam: ClassVar[str] = 'spam'\n\nreveal_type(Bar.foo)  # N: Revealed type is \"builtins.int\"\nreveal_type(Bar.bar)  # N: Revealed type is \"builtins.str\"\nreveal_type(Bar.eggs)  # N: Revealed type is \"builtins.int\"\nreveal_type(Bar.spam)  # N: Revealed type is \"builtins.str\"\n\n[case testSubclassMetaclass]\nclass M1(type):\n    x = 0\nclass M2(M1): pass\nclass C(metaclass=M2):\n    pass\nreveal_type(C.x) # N: Revealed type is \"builtins.int\"\n\n[case testMetaclassSubclass]\nfrom typing import Type\nclass M(type):\n    x = 0  # type: int\n\nclass A(metaclass=M): pass\nclass B(A): pass\n\ndef f(TB: Type[B]):\n    reveal_type(TB)  # N: Revealed type is \"type[__main__.B]\"\n    reveal_type(TB.x)  # N: Revealed type is \"builtins.int\"\n\n[case testMetaclassAsAny]\nfrom typing import Any, ClassVar, Type\n\nMyAny: Any\nclass WithMeta(metaclass=MyAny):\n    x: ClassVar[int]\n\nreveal_type(WithMeta.a)   # N: Revealed type is \"Any\"\nreveal_type(WithMeta.m)   # N: Revealed type is \"Any\"\nreveal_type(WithMeta.x)   # N: Revealed type is \"builtins.int\"\nreveal_type(WithMeta().x) # N: Revealed type is \"builtins.int\"\nWithMeta().m              # E: \"WithMeta\" has no attribute \"m\"\nWithMeta().a              # E: \"WithMeta\" has no attribute \"a\"\nt: Type[WithMeta]\nt.unknown  # OK\n\n[case testMetaclassAsAnyWithAFlag]\n# flags: --disallow-subclassing-any\nfrom typing import Any, ClassVar, Type\n\nMyAny: Any\nclass WithMeta(metaclass=MyAny):  # E: Class cannot use \"MyAny\" as a metaclass (has type \"Any\")\n    x: ClassVar[int]\n\nreveal_type(WithMeta.a)   # N: Revealed type is \"Any\"\nreveal_type(WithMeta.m)   # N: Revealed type is \"Any\"\nreveal_type(WithMeta.x)   # N: Revealed type is \"builtins.int\"\nreveal_type(WithMeta().x) # N: Revealed type is \"builtins.int\"\nWithMeta().m              # E: \"WithMeta\" has no attribute \"m\"\nWithMeta().a              # E: \"WithMeta\" has no attribute \"a\"\nt: Type[WithMeta]\nt.unknown  # OK\n\n[case testUnpackIterableClassWithOverloadedIter]\nfrom typing import Generic, overload, Iterator, TypeVar, Union\n\nAnyNum = TypeVar('AnyNum', int, float)\n\nclass Foo(Generic[AnyNum]):\n    @overload\n    def __iter__(self: Foo[int]) -> Iterator[float]: ...\n    @overload\n    def __iter__(self: Foo[float]) -> Iterator[int]: ...\n    def __iter__(self) -> Iterator[Union[float, int]]:\n        ...\n\na, b, c = Foo[int]()\nreveal_type(a)  # N: Revealed type is \"builtins.float\"\nreveal_type(b)  # N: Revealed type is \"builtins.float\"\nreveal_type(c)  # N: Revealed type is \"builtins.float\"\n\nx, y = Foo[float]()\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testUnpackIterableClassWithOverloadedIter2]\nfrom typing import Union, TypeVar, Generic, overload, Iterator\n\nX = TypeVar('X')\n\nclass Foo(Generic[X]):\n    @overload\n    def __iter__(self: Foo[str]) -> Iterator[int]: ...  # type: ignore\n    @overload\n    def __iter__(self: Foo[X]) -> Iterator[str]: ...\n    def __iter__(self) -> Iterator[Union[int, str]]:\n        ...\n\na, b, c = Foo[str]()\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\nreveal_type(b)  # N: Revealed type is \"builtins.int\"\nreveal_type(c)  # N: Revealed type is \"builtins.int\"\n\nx, y = Foo[float]()\nreveal_type(x)  # N: Revealed type is \"builtins.str\"\nreveal_type(y)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testUnpackIterableRegular]\nfrom typing import TypeVar, Generic, Iterator\n\nX = TypeVar('X')\n\nclass Foo(Generic[X]):\n    def __iter__(self) -> Iterator[X]:\n        ...\n\na, b = Foo[int]()\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\nreveal_type(b)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testUnpackNotIterableClass]\nclass Foo: ...\n\na, b, c = Foo()  # E: \"Foo\" object is not iterable\n[builtins fixtures/list.pyi]\n\n[case testMetaclassIterable]\nfrom typing import Iterable, Iterator\n\nclass ImplicitMeta(type):\n    def __iter__(self) -> Iterator[int]: yield 1\n\nclass Implicit(metaclass=ImplicitMeta): pass\n\nfor _ in Implicit: pass\nreveal_type(list(Implicit))  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nclass ExplicitMeta(type, Iterable[int]):\n    def __iter__(self) -> Iterator[int]: yield 1\n\nclass Explicit(metaclass=ExplicitMeta): pass\nfor _ in Explicit: pass\nreveal_type(list(Explicit))  # N: Revealed type is \"builtins.list[builtins.int]\"\n\n[builtins fixtures/list.pyi]\n\n[case testMetaclassTuple]\nfrom typing import Tuple\n\nclass M(Tuple[int]): pass\nclass C(metaclass=M): pass  # E: Invalid metaclass \"M\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testMetaclassOperatorBeforeReversed]\nclass X:\n    def __radd__(self, x: int) -> int: ...\n\nclass Meta(type):\n    def __add__(cls, x: X) -> str: ...\n\nclass Concrete(metaclass=Meta):\n    pass\n\nreveal_type(Concrete + X())  # N: Revealed type is \"builtins.str\"\nConcrete + \"hello\"  # E: Unsupported operand types for + (\"type[Concrete]\" and \"str\")\n\n[case testMetaclassOperatorTypeVar]\nfrom typing import Type, TypeVar\n\nclass MetaClass(type):\n    def __mul__(cls, other: int) -> str:\n        return \"\"\n\nclass Test(metaclass=MetaClass):\n    pass\n\nS = TypeVar(\"S\", bound=Test)\n\ndef f(x: Type[Test]) -> str:\n    return x * 0\ndef g(x: Type[S]) -> str:\n    return reveal_type(x * 0)  # N: Revealed type is \"builtins.str\"\n\n[case testMetaclassGetitem]\nimport types\n\nclass M(type):\n    def __getitem__(self, key) -> int: return 1\n\nclass A(metaclass=M): pass\n\nreveal_type(A[M])  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testMetaclassSelfType]\nfrom typing import TypeVar, Type\n\nclass M(type): pass\nT = TypeVar('T')\n\nclass M1(M):\n    def foo(cls: Type[T]) -> T: ...\n\nclass A(metaclass=M1): pass\nreveal_type(A.foo())  # N: Revealed type is \"__main__.A\"\n\n[case testMetaclassAndSkippedImport]\n# flags: --ignore-missing-imports\nfrom missing import M\nclass A(metaclass=M):\n    y = 0\nreveal_type(A.y) # N: Revealed type is \"builtins.int\"\nreveal_type(A.x) # N: Revealed type is \"Any\"\n\n[case testValidTypeAliasAsMetaclass]\nfrom typing_extensions import TypeAlias\n\nExplicit: TypeAlias = type\nImplicit = type\n\nclass E(metaclass=Explicit): ...\nclass I(metaclass=Implicit): ...\n[builtins fixtures/classmethod.pyi]\n\n[case testValidTypeAliasOfTypeAliasAsMetaclass]\nfrom typing_extensions import TypeAlias\n\nExplicit: TypeAlias = type\nImplicit = type\n\nA1: TypeAlias = Explicit\nA2 = Explicit\nA3: TypeAlias = Implicit\nA4 = Implicit\n\nclass C1(metaclass=A1): ...\nclass C2(metaclass=A2): ...\nclass C3(metaclass=A3): ...\nclass C4(metaclass=A4): ...\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeAliasWithArgsAsMetaclass]\nfrom typing import Generic, TypeVar\nfrom typing_extensions import TypeAlias\n\nT = TypeVar('T')\nclass Meta(Generic[T]): ...\n\nExplicit: TypeAlias = Meta[T]\nImplicit = Meta[T]\n\nclass E(metaclass=Explicit): ...  # E: Invalid metaclass \"Explicit\"\nclass I(metaclass=Implicit): ...  # E: Invalid metaclass \"Implicit\"\n[builtins fixtures/classmethod.pyi]\n\n[case testTypeAliasNonTypeAsMetaclass]\nfrom typing_extensions import TypeAlias\n\nExplicit: TypeAlias = int\nImplicit = int\n\nclass E(metaclass=Explicit): ...  # E: Metaclasses not inheriting from \"type\" are not supported\nclass I(metaclass=Implicit): ...  # E: Metaclasses not inheriting from \"type\" are not supported\n[builtins fixtures/classmethod.pyi]\n\n[case testInvalidVariableAsMetaclass]\nfrom typing import Any\nM = 0  # type: int\nMM = 0\nclass A(metaclass=M): # E: Invalid metaclass \"M\"\n    y = 0\nclass B(metaclass=MM): # E: Invalid metaclass \"MM\"\n    y = 0\nreveal_type(A.y) # N: Revealed type is \"builtins.int\"\nA.x # E: \"type[A]\" has no attribute \"x\"\n\n[case testAnyAsBaseOfMetaclass]\nfrom typing import Any, Type\nM = None  # type: Any\nclass MM(M): pass\n\nclass A(metaclass=MM):\n    y = 0\n    @classmethod\n    def f(cls) -> None: pass\n    def g(self) -> None: pass\n\ndef h(a: Type[A], b: Type[object]) -> None:\n    h(a, a)\n    h(b, a) # E: Argument 1 to \"h\" has incompatible type \"type[object]\"; expected \"type[A]\"\n    a.f(1) # E: Too many arguments for \"f\" of \"A\"\n    reveal_type(a.y) # N: Revealed type is \"builtins.int\"\n\nx = A # type: MM\nreveal_type(A.y) # N: Revealed type is \"builtins.int\"\nreveal_type(A.x) # N: Revealed type is \"Any\"\nA.f(1) # E: Too many arguments for \"f\" of \"A\"\nA().g(1) # E: Too many arguments for \"g\" of \"A\"\n[builtins fixtures/classmethod.pyi]\n\n[case testMetaclassTypeCallable]\nclass M(type):\n    x = 5\n\nclass A(metaclass=M): pass\nreveal_type(type(A).x)  # N: Revealed type is \"builtins.int\"\n\n[case testMetaclassStrictSupertypeOfTypeWithClassmethods]\nfrom typing import Type, TypeVar\nTA = TypeVar('TA', bound='A')\nTTA = TypeVar('TTA', bound='Type[A]')\nTM = TypeVar('TM', bound='M')\n\nclass M(type):\n    def g1(cls: 'Type[A]') -> A: pass  # E: The erased type of self \"type[__main__.A]\" is not a supertype of its class \"__main__.M\"\n    def g2(cls: Type[TA]) -> TA: pass  # E: The erased type of self \"type[__main__.A]\" is not a supertype of its class \"__main__.M\"\n    def g3(cls: TTA) -> TTA: pass  # E: The erased type of self \"type[__main__.A]\" is not a supertype of its class \"__main__.M\"\n    def g4(cls: TM) -> TM: pass\nm: M\n\nclass A(metaclass=M):\n    def foo(self): pass\n\nreveal_type(A.g1)  # N: Revealed type is \"def () -> __main__.A\"\nreveal_type(A.g2)  # N: Revealed type is \"def () -> __main__.A\"\nreveal_type(A.g3)  # N: Revealed type is \"def () -> def () -> __main__.A\"\nreveal_type(A.g4)  # N: Revealed type is \"def () -> def () -> __main__.A\"\n\nclass B(metaclass=M):\n    def foo(self): pass\n\nB.g1  # E: Invalid self argument \"type[B]\" to attribute function \"g1\" with type \"Callable[[type[A]], A]\"\nB.g2  # E: Invalid self argument \"type[B]\" to attribute function \"g2\" with type \"Callable[[type[TA]], TA]\"\nB.g3  # E: Invalid self argument \"type[B]\" to attribute function \"g3\" with type \"Callable[[TTA], TTA]\"\nreveal_type(B.g4)  # N: Revealed type is \"def () -> def () -> __main__.B\"\n\n# 4 examples of unsoundness - instantiation, classmethod, staticmethod and ClassVar:\n\nta: Type[A] = m  # E: Incompatible types in assignment (expression has type \"M\", variable has type \"type[A]\")\na: A = ta()\nreveal_type(ta.g1)  # N: Revealed type is \"def () -> __main__.A\"\nreveal_type(ta.g2)  # N: Revealed type is \"def () -> __main__.A\"\nreveal_type(ta.g3)  # N: Revealed type is \"def () -> type[__main__.A]\"\nreveal_type(ta.g4)  # N: Revealed type is \"def () -> type[__main__.A]\"\n\nx: M = ta\nx.g1  # E: Invalid self argument \"M\" to attribute function \"g1\" with type \"Callable[[type[A]], A]\"\nx.g2  # E: Invalid self argument \"M\" to attribute function \"g2\" with type \"Callable[[type[TA]], TA]\"\nx.g3  # E: Invalid self argument \"M\" to attribute function \"g3\" with type \"Callable[[TTA], TTA]\"\nreveal_type(x.g4)  # N: Revealed type is \"def () -> __main__.M\"\n\ndef r(ta: Type[TA], tta: TTA) -> None:\n    x: M = ta\n    y: M = tta\n\nclass Class(metaclass=M):\n    @classmethod\n    def f1(cls: Type[Class]) -> None: pass\n    @classmethod\n    def f2(cls: M) -> None: pass\ncl: Type[Class] = m  # E: Incompatible types in assignment (expression has type \"M\", variable has type \"type[Class]\")\nreveal_type(cl.f1)  # N: Revealed type is \"def ()\"\nreveal_type(cl.f2)  # N: Revealed type is \"def ()\"\nx1: M = cl\n\nclass Static(metaclass=M):\n    @staticmethod\n    def f() -> None: pass\ns: Type[Static] = m  # E: Incompatible types in assignment (expression has type \"M\", variable has type \"type[Static]\")\nreveal_type(s.f)  # N: Revealed type is \"def ()\"\nx2: M = s\n\nfrom typing import ClassVar\nclass Cvar(metaclass=M):\n    x = 1  # type: ClassVar[int]\ncv: Type[Cvar] = m  # E: Incompatible types in assignment (expression has type \"M\", variable has type \"type[Cvar]\")\ncv.x\nx3: M = cv\n\n[builtins fixtures/classmethod.pyi]\n\n[case testMetaclassOverloadResolution]\nfrom typing import Type, overload\nclass A: pass\n\nclass EM(type): pass\nclass E(metaclass=EM): pass\n\nclass EM1(type): pass\nclass E1(metaclass=EM1): pass\n\n@overload\ndef f(x: EM) -> int: ...\n@overload\ndef f(x: EM1) -> A: ...\n@overload\ndef f(x: str) -> str: ...\ndef f(x: object) -> object: return ''\n\ne: EM\nreveal_type(f(e))  # N: Revealed type is \"builtins.int\"\n\net: Type[E]\nreveal_type(f(et))  # N: Revealed type is \"builtins.int\"\n\ne1: EM1\nreveal_type(f(e1))  # N: Revealed type is \"__main__.A\"\n\ne1t: Type[E1]\nreveal_type(f(e1t))  # N: Revealed type is \"__main__.A\"\n\nreveal_type(f(''))  # N: Revealed type is \"builtins.str\"\n\n[case testTypeCErasesGenericsFromC]\nfrom typing import Generic, Type, TypeVar\n\nK = TypeVar('K')\nV = TypeVar('V')\nclass ExampleDict(Generic[K, V]): ...\n\nD = TypeVar('D')\ndef mkdict(dict_type: Type[D]) -> D: ...\nreveal_type(mkdict(ExampleDict))  # N: Revealed type is \"__main__.ExampleDict[Any, Any]\"\n\n[case testTupleForwardBase]\nfrom m import a\na[0]()  # E: \"int\" not callable\n\n[file m.py]\nfrom typing import Tuple\na: A\nclass A(Tuple[int, str]): pass\n[builtins fixtures/tuple.pyi]\n\n-- Synthetic types crashes\n-- -----------------------\n\n[case testCrashOnSelfRecursiveNamedTupleVar]\nfrom typing import NamedTuple\n\ndef test() -> None:\n    N = NamedTuple('N', [('x', N)]) # E: Cannot resolve name \"N\" (possible cyclic definition) \\\n                                    # N: Recursive types are not allowed at function scope\n    n: N\n    reveal_type(n) # N: Revealed type is \"tuple[Any, fallback=__main__.N@4]\"\n[builtins fixtures/tuple.pyi]\n\n[case testCrashOnSelfRecursiveTypedDictVar]\nfrom typing import TypedDict\n\nA = TypedDict('A', {'a': 'A'})  # type: ignore\na: A\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCrashInJoinOfSelfRecursiveNamedTuples]\n\nfrom typing import NamedTuple\n\nclass N(NamedTuple):\n    x: N # type: ignore\nclass M(NamedTuple):\n    x: M # type: ignore\n\nn: N\nm: M\nlst = [n, m]\n[builtins fixtures/isinstancelist.pyi]\n\n[case testCorrectJoinOfSelfRecursiveTypedDicts]\nfrom typing import TypedDict\n\ndef test() -> None:\n    class N(TypedDict):\n        x: N  # E: Cannot resolve name \"N\" (possible cyclic definition) \\\n              # N: Recursive types are not allowed at function scope\n    class M(TypedDict):\n        x: M  # E: Cannot resolve name \"M\" (possible cyclic definition) \\\n              # N: Recursive types are not allowed at function scope\n\n    n: N\n    m: M\n    lst = [n, m]\n    reveal_type(lst[0]['x'])  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCrashInForwardRefToNamedTupleWithIsinstance]\nfrom typing import Dict, NamedTuple\n\nNameDict = Dict[str, 'NameInfo']\nclass NameInfo(NamedTuple):\n    ast: bool\n\ndef parse_ast(name_dict: NameDict) -> None:\n    if isinstance(name_dict[''], int):\n        pass\n    reveal_type(name_dict['test']) # N: Revealed type is \"tuple[builtins.bool, fallback=__main__.NameInfo]\"\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCrashInForwardRefToTypedDictWithIsinstance]\nfrom typing import Dict, TypedDict\n\nNameDict = Dict[str, 'NameInfo']\nclass NameInfo(TypedDict):\n    ast: bool\n\ndef parse_ast(name_dict: NameDict) -> None:\n    if isinstance(name_dict[''], int):\n        pass\n    reveal_type(name_dict['']['ast'])  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testCorrectIsinstanceInForwardRefToNewType]\nfrom typing import Dict, NewType\n\nNameDict = Dict[str, 'NameInfo']\nclass Base:\n    ast: bool\nNameInfo = NewType('NameInfo', Base)\n\ndef parse_ast(name_dict: NameDict) -> None:\n    if isinstance(name_dict[''], int):\n        pass\n    x = name_dict['']\n    reveal_type(x) # N: Revealed type is \"__main__.NameInfo\"\n    if int():\n        x = NameInfo(Base()) # OK\n        x = Base() # E: Incompatible types in assignment (expression has type \"Base\", variable has type \"NameInfo\")\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testNoCrashForwardRefToBrokenDoubleNewType]\nfrom typing import Any, Dict, List, NewType\n\nFoo = NewType('NotFoo', int) # E: String argument 1 \"NotFoo\" to NewType(...) does not match variable name \"Foo\"\nFoos = NewType('Foos', List[Foo]) # type: ignore\n\ndef frob(foos: Dict[Any, Foos]) -> None:\n    foo = foos.get(1)\n    assert foo\n    dict(foo)\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testNoCrashForwardRefToBrokenDoubleNewTypeClass]\nfrom typing import Any, Dict, List, NewType\n\nFoo = NewType('NotFoo', int) # type: ignore\nFoos = NewType('Foos', List[Foo]) # type: ignore\n\nx: C\nclass C:\n    def frob(self, foos: Dict[Any, Foos]) -> None:\n        foo = foos.get(1)\n        assert foo\n        dict(foo)\n\nreveal_type(x.frob) # N: Revealed type is \"def (foos: builtins.dict[Any, __main__.Foos])\"\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testNewTypeFromForwardNamedTuple]\nfrom typing import NewType, NamedTuple, Tuple\n\nNT = NewType('NT', 'N')\nclass N(NamedTuple):\n    x: int\n\nx: NT = N(1) # E: Incompatible types in assignment (expression has type \"N\", variable has type \"NT\")\nx = NT(N(1))\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNewTypeFromForwardTypedDict]\n\nfrom typing import NewType, Tuple, TypedDict\n\nNT = NewType('NT', 'N') # E: Argument 2 to NewType(...) must be subclassable (got \"N\")\nclass N(TypedDict):\n    x: int\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testCorrectAttributeInForwardRefToNamedTuple]\nfrom typing import NamedTuple\nproc: Process\nreveal_type(proc.state)  # N: Revealed type is \"builtins.int\"\n\ndef get_state(proc: 'Process') -> int:\n    return proc.state\nclass Process(NamedTuple):\n     state: int\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCorrectItemTypeInForwardRefToTypedDict]\nfrom typing import TypedDict\nproc: Process\nreveal_type(proc['state'])  # N: Revealed type is \"builtins.int\"\n\ndef get_state(proc: 'Process') -> int:\n    return proc['state']\nclass Process(TypedDict):\n     state: int\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testCorrectDoubleForwardNamedTuple]\nfrom typing import NamedTuple\n\nx: A\nclass A(NamedTuple):\n    one: 'B'\n    other: int\nclass B(NamedTuple):\n    attr: str\ny: A\ny = x\nreveal_type(x.one.attr)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCrashOnDoubleForwardTypedDict]\nfrom typing import TypedDict\n\nx: A\nclass A(TypedDict):\n    one: 'B'\n    other: int\nclass B(TypedDict):\n    attr: str\n\nreveal_type(x['one']['attr'])  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testCrashOnForwardUnionOfNamedTuples]\nfrom typing import Union, NamedTuple\n\nNode = Union['Foo', 'Bar']\nclass Foo(NamedTuple):\n    x: int\nclass Bar(NamedTuple):\n    x: int\n\ndef foo(node: Node) -> int:\n    x = node\n    reveal_type(node) # N: Revealed type is \"tuple[builtins.int, fallback=__main__.Foo] | tuple[builtins.int, fallback=__main__.Bar]\"\n    return x.x\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCrashOnForwardUnionOfTypedDicts]\nfrom typing import TypedDict, Union\n\nNodeType = Union['Foo', 'Bar']\nclass Foo(TypedDict):\n    x: int\nclass Bar(TypedDict):\n    x: int\n\ndef foo(node: NodeType) -> int:\n    x = node\n    return x['x']\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testSupportForwardUnionOfNewTypes]\nfrom typing import Union, NewType\nx: Node\nreveal_type(x.x) # N: Revealed type is \"builtins.int\"\n\nclass A:\n    x: int\nclass B:\n    x: int\n\nNode = Union['Foo', 'Bar']\nFoo = NewType('Foo', A)\nBar = NewType('Bar', B)\n\ndef foo(node: Node) -> Node:\n    x = node\n    return Foo(A())\n[out]\n\n[case testForwardReferencesInNewTypeMRORecomputed]\nfrom typing import NewType\nx: Foo\nFoo = NewType('Foo', 'B')\nclass A:\n    x: int\nclass B(A):\n    pass\n\nreveal_type(x.x) # N: Revealed type is \"builtins.int\"\n[out]\n\n[case testCrashOnComplexNamedTupleUnionProperty]\nfrom typing import NamedTuple, Union\n\nx: AOrB\nAOrB = Union['A', 'B']\nclass A(NamedTuple):\n    x: int\n\nclass B(object):\n    def __init__(self, a: AOrB) -> None:\n        self.a = a\n    @property\n    def x(self) -> int:\n        return self.a.x\n\nreveal_type(x.x) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/property.pyi]\n[out]\n\n[case testCorrectIsinstanceWithForwardUnion]\nfrom typing import Union, NamedTuple\n\nForwardUnion = Union['TP', int]\nclass TP(NamedTuple('TP', [('x', int)])): pass\n\ndef f(x: ForwardUnion) -> None:\n  reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, fallback=__main__.TP] | builtins.int\"\n  if isinstance(x, TP):\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, fallback=__main__.TP]\"\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testCrashInvalidArgsSyntheticClassSyntax]\nfrom typing import List, NamedTuple, TypedDict\nclass TD(TypedDict):\n    x: List[int, str] # E: \"list\" expects 1 type argument, but 2 given\nclass NM(NamedTuple):\n    x: List[int, str] # E: \"list\" expects 1 type argument, but 2 given\n\n# These two should never crash, reveals are in the next test\nTD({'x': []})\nNM(x=[])\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testCrashInvalidArgsSyntheticClassSyntaxReveals]\nfrom typing import List, NamedTuple, TypedDict\nclass TD(TypedDict):\n    x: List[int, str] # E: \"list\" expects 1 type argument, but 2 given\nclass NM(NamedTuple):\n    x: List[int, str] # E: \"list\" expects 1 type argument, but 2 given\n\nx: TD\nx1 = TD({'x': []})\ny: NM\ny1 = NM(x=[])\nreveal_type(x) # N: Revealed type is \"TypedDict('__main__.TD', {'x': builtins.list[Any]})\"\nreveal_type(x1) # N: Revealed type is \"TypedDict('__main__.TD', {'x': builtins.list[Any]})\"\nreveal_type(y) # N: Revealed type is \"tuple[builtins.list[Any], fallback=__main__.NM]\"\nreveal_type(y1) # N: Revealed type is \"tuple[builtins.list[Any], fallback=__main__.NM]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testCrashInvalidArgsSyntheticFunctionSyntax]\nfrom typing import List, NewType, NamedTuple, TypedDict\nTD = TypedDict('TD', {'x': List[int, str]}) # E: \"list\" expects 1 type argument, but 2 given\nNM = NamedTuple('NM', [('x', List[int, str])]) # E: \"list\" expects 1 type argument, but 2 given\nNT = NewType('NT', List[int, str]) # E: \"list\" expects 1 type argument, but 2 given\n\n# These three should not crash\nTD({'x': []})\nNM(x=[])\nNT([])\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testCrashForwardSyntheticClassSyntax]\nfrom typing import NamedTuple, TypedDict\nclass A1(NamedTuple):\n    b: 'B'\n    x: int\nclass A2(TypedDict):\n    b: 'B'\n    x: int\nclass B:\n    pass\nx: A1\ny: A2\nreveal_type(x.b) # N: Revealed type is \"__main__.B\"\nreveal_type(y['b']) # N: Revealed type is \"__main__.B\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testCrashForwardSyntheticFunctionSyntax]\nfrom typing import NamedTuple, TypedDict\nA1 = NamedTuple('A1', [('b', 'B'), ('x', int)])\nA2 = TypedDict('A2', {'b': 'B', 'x': int})\nclass B:\n    pass\nx: A1\ny: A2\nreveal_type(x.b) # N: Revealed type is \"__main__.B\"\nreveal_type(y['b']) # N: Revealed type is \"__main__.B\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n-- Special support for six\n-- -----------------------\n\n[case testSixMetaclass]\nimport six\nclass M(type):\n    x = 5\nclass A(six.with_metaclass(M)): pass\n@six.add_metaclass(M)\nclass B: pass\nreveal_type(type(A).x)  # N: Revealed type is \"builtins.int\"\nreveal_type(type(B).x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testFromSixMetaclass]\nfrom six import with_metaclass, add_metaclass\nclass M(type):\n    x = 5\nclass A(with_metaclass(M)): pass\n@add_metaclass(M)\nclass B: pass\nreveal_type(type(A).x)  # N: Revealed type is \"builtins.int\"\nreveal_type(type(B).x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testSixMetaclassImportFrom]\nimport six\nfrom metadefs import M\nclass A(six.with_metaclass(M)): pass\n@six.add_metaclass(M)\nclass B: pass\nreveal_type(type(A).x)  # N: Revealed type is \"builtins.int\"\nreveal_type(type(B).x)  # N: Revealed type is \"builtins.int\"\n[file metadefs.py]\nclass M(type):\n    x = 5\n[builtins fixtures/tuple.pyi]\n\n[case testSixMetaclassImport]\nimport six\nimport metadefs\nclass A(six.with_metaclass(metadefs.M)): pass\n@six.add_metaclass(metadefs.M)\nclass B: pass\nreveal_type(type(A).x)  # N: Revealed type is \"builtins.int\"\nreveal_type(type(B).x)  # N: Revealed type is \"builtins.int\"\n[file metadefs.py]\nclass M(type):\n    x = 5\n[builtins fixtures/tuple.pyi]\n\n[case testSixMetaclassAndBase]\nfrom typing import Iterable, Iterator\nimport six\nclass M(type, Iterable[int]):\n    x = 5\n    def __iter__(self) -> Iterator[int]: ...\nclass A:\n    def foo(self): pass\nclass B:\n    def bar(self): pass\nclass C1(six.with_metaclass(M, A)): pass\n@six.add_metaclass(M)\nclass D1(A): pass\nclass C2(six.with_metaclass(M, A, B)): pass\n@six.add_metaclass(M)\nclass D2(A, B): pass\nreveal_type(type(C1).x)  # N: Revealed type is \"builtins.int\"\nreveal_type(type(D1).x)  # N: Revealed type is \"builtins.int\"\nreveal_type(type(C2).x)  # N: Revealed type is \"builtins.int\"\nreveal_type(type(D2).x)  # N: Revealed type is \"builtins.int\"\nC1().foo()\nD1().foo()\nC1().bar()  # E: \"C1\" has no attribute \"bar\"\nD1().bar()  # E: \"D1\" has no attribute \"bar\"\nfor x in C1: reveal_type(x)  # N: Revealed type is \"builtins.int\"\nfor x in C2: reveal_type(x)  # N: Revealed type is \"builtins.int\"\nC2().foo()\nD2().foo()\nC2().bar()\nD2().bar()\nC2().baz()  # E: \"C2\" has no attribute \"baz\"\nD2().baz()  # E: \"D2\" has no attribute \"baz\"\n[builtins fixtures/tuple.pyi]\n\n[case testSixMetaclassGenerics]\nfrom typing import Generic, GenericMeta, TypeVar\nimport six\nclass DestroyableMeta(type):\n    pass\nclass Destroyable(six.with_metaclass(DestroyableMeta)):\n    pass\nT_co = TypeVar('T_co', bound='Destroyable', covariant=True)\nclass ArcMeta(GenericMeta, DestroyableMeta):\n    pass\nclass Arc(six.with_metaclass(ArcMeta, Generic[T_co], Destroyable)):\n    pass\n@six.add_metaclass(ArcMeta)\nclass Arc1(Generic[T_co], Destroyable):\n    pass\nclass MyDestr(Destroyable):\n    pass\nreveal_type(Arc[MyDestr]())  # N: Revealed type is \"__main__.Arc[__main__.MyDestr]\"\nreveal_type(Arc1[MyDestr]())  # N: Revealed type is \"__main__.Arc1[__main__.MyDestr]\"\n[builtins fixtures/bool.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testSixMetaclassErrors]\n\nimport six\nclass M(type): pass\nclass A(object): pass\ndef f() -> type: return M\nclass C1(six.with_metaclass(M), object): pass  # E: Unsupported dynamic base class \"six.with_metaclass\"\nclass C2(C1, six.with_metaclass(M)): pass  # E: Unsupported dynamic base class \"six.with_metaclass\"\nclass C3(six.with_metaclass(A)): pass  # E: Metaclasses not inheriting from \"type\" are not supported\n@six.add_metaclass(A)  # E: Metaclasses not inheriting from \"type\" are not supported \\\n                       # E: Argument 1 to \"add_metaclass\" has incompatible type \"type[A]\"; expected \"type[type]\"\n\nclass D3(A): pass\nclass C4(six.with_metaclass(M), metaclass=M): pass  # E: Multiple metaclass definitions\n@six.add_metaclass(M)\nclass D4(metaclass=M): pass  # E: Multiple metaclass definitions\nclass C5(six.with_metaclass(f())): pass  # E: Dynamic metaclass not supported for \"C5\"\n@six.add_metaclass(f())  # E: Dynamic metaclass not supported for \"D5\"\nclass D5: pass\n\n@six.add_metaclass(M)\nclass CD(six.with_metaclass(M)): pass  # E: Multiple metaclass definitions\n\nclass M1(type): pass\nclass Q1(metaclass=M1): pass\n@six.add_metaclass(M)\nclass CQA(Q1): pass  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                     # N: \"__main__.M\" (metaclass of \"__main__.CQA\") conflicts with \"__main__.M1\" (metaclass of \"__main__.Q1\")\nclass CQW(six.with_metaclass(M, Q1)): pass  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                                            # N: \"__main__.M\" (metaclass of \"__main__.CQW\") conflicts with \"__main__.M1\" (metaclass of \"__main__.Q1\")\n[builtins fixtures/tuple.pyi]\n\n[case testSixMetaclassAny]\nimport t  # type: ignore\nimport six\nclass E(metaclass=t.M): pass\nclass F(six.with_metaclass(t.M)): pass\n@six.add_metaclass(t.M)\nclass G: pass\n[builtins fixtures/tuple.pyi]\n\n[case testSixMetaclassGenericBase]\nimport six\nimport abc\nfrom typing import TypeVar, Generic\n\nT = TypeVar(\"T\")\n\nclass C(six.with_metaclass(abc.ABCMeta, Generic[T])):\n    pass\nclass D(six.with_metaclass(abc.ABCMeta, C[T])):\n    pass\n[builtins fixtures/tuple.pyi]\n\n-- Special support for future.utils\n-- --------------------------------\n\n[case testFutureMetaclass]\nimport future.utils\nclass M(type):\n    x = 5\nclass A(future.utils.with_metaclass(M)): pass\nreveal_type(type(A).x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testFromFutureMetaclass]\nfrom future.utils import with_metaclass\nclass M(type):\n    x = 5\nclass A(with_metaclass(M)): pass\nreveal_type(type(A).x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testFutureMetaclassImportFrom]\nimport future.utils\nfrom metadefs import M\nclass A(future.utils.with_metaclass(M)): pass\nreveal_type(type(A).x)  # N: Revealed type is \"builtins.int\"\n[file metadefs.py]\nclass M(type):\n    x = 5\n[builtins fixtures/tuple.pyi]\n\n[case testFutureMetaclassImport]\nimport future.utils\nimport metadefs\nclass A(future.utils.with_metaclass(metadefs.M)): pass\nreveal_type(type(A).x)  # N: Revealed type is \"builtins.int\"\n[file metadefs.py]\nclass M(type):\n    x = 5\n[builtins fixtures/tuple.pyi]\n\n[case testFutureMetaclassAndBase]\nfrom typing import Iterable, Iterator\nimport future.utils\nclass M(type, Iterable[int]):\n    x = 5\n    def __iter__(self) -> Iterator[int]: ...\nclass A:\n    def foo(self): pass\nclass B:\n    def bar(self): pass\nclass C1(future.utils.with_metaclass(M, A)): pass\nclass C2(future.utils.with_metaclass(M, A, B)): pass\nreveal_type(type(C1).x)  # N: Revealed type is \"builtins.int\"\nreveal_type(type(C2).x)  # N: Revealed type is \"builtins.int\"\nC1().foo()\nC1().bar()  # E: \"C1\" has no attribute \"bar\"\nfor x in C1: reveal_type(x)  # N: Revealed type is \"builtins.int\"\nfor x in C2: reveal_type(x)  # N: Revealed type is \"builtins.int\"\nC2().foo()\nC2().bar()\nC2().baz()  # E: \"C2\" has no attribute \"baz\"\n[builtins fixtures/tuple.pyi]\n\n[case testFutureMetaclassGenerics]\nfrom typing import Generic, GenericMeta, TypeVar\nimport future.utils\nclass DestroyableMeta(type):\n    pass\nclass Destroyable(future.utils.with_metaclass(DestroyableMeta)):\n    pass\nT_co = TypeVar('T_co', bound='Destroyable', covariant=True)\nclass ArcMeta(GenericMeta, DestroyableMeta):\n    pass\nclass Arc(future.utils.with_metaclass(ArcMeta, Generic[T_co], Destroyable)):\n    pass\nclass MyDestr(Destroyable):\n    pass\nreveal_type(Arc[MyDestr]())  # N: Revealed type is \"__main__.Arc[__main__.MyDestr]\"\n[builtins fixtures/bool.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testFutureMetaclassErrors]\nimport future.utils\nclass M(type): pass\nclass A(object): pass\ndef f() -> type: return M\nclass C1(future.utils.with_metaclass(M), object): pass  # E: Unsupported dynamic base class \"future.utils.with_metaclass\"\nclass C2(C1, future.utils.with_metaclass(M)): pass  # E: Unsupported dynamic base class \"future.utils.with_metaclass\"\nclass C3(future.utils.with_metaclass(A)): pass  # E: Metaclasses not inheriting from \"type\" are not supported\nclass C4(future.utils.with_metaclass(M), metaclass=M): pass  # E: Multiple metaclass definitions\nclass C5(future.utils.with_metaclass(f())): pass  # E: Dynamic metaclass not supported for \"C5\"\n\nclass M1(type): pass\nclass Q1(metaclass=M1): pass\nclass CQW(future.utils.with_metaclass(M, Q1)): pass  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                                                     # N: \"__main__.M\" (metaclass of \"__main__.CQW\") conflicts with \"__main__.M1\" (metaclass of \"__main__.Q1\")\n[builtins fixtures/tuple.pyi]\n\n[case testFutureMetaclassAny]\nimport t  # type: ignore\nimport future.utils\nclass E(metaclass=t.M): pass\nclass F(future.utils.with_metaclass(t.M)): pass\n\n-- Misc\n-- ----\n[builtins fixtures/tuple.pyi]\n\n[case testCorrectEnclosingClassPushedInDeferred]\nclass C:\n    def __getattr__(self, attr: str) -> int:\n        x: F\n        return x.f\n\nclass F:\n    def __init__(self, f: int) -> None:\n        self.f = f\n[out]\n\n[case testCorrectEnclosingClassPushedInDeferred2]\nfrom typing import TypeVar\nT = TypeVar('T', bound='C')\nclass C:\n    def m(self: T) -> T:\n        class Inner:\n            x: F\n            f = x.f\n        return self\n\nclass F:\n    def __init__(self, f: int) -> None:\n        self.f = f\n[out]\n\n[case testCorrectEnclosingClassPushedInDeferred3]\nclass A:\n    def f(self) -> None:\n        def g(x: int) -> int:\n            return y\n\ny = int()\n[out]\n\n[case testMetaclassMemberAccessViaType]\nfrom typing import Type\nclass M(type):\n    def m(cls, x: int) -> int:\n        pass\n\nclass C(metaclass=M):\n    pass\nx = C\ny: Type[C] = C\n\nreveal_type(type(C).m) # N: Revealed type is \"def (cls: __main__.M, x: builtins.int) -> builtins.int\"\nreveal_type(type(x).m) # N: Revealed type is \"def (cls: __main__.M, x: builtins.int) -> builtins.int\"\nreveal_type(type(y).m) # N: Revealed type is \"def (cls: __main__.M, x: builtins.int) -> builtins.int\"\n[out]\n\n[case testMetaclassMemberAccessViaType2]\nfrom typing import Any, Type\nclass M(type):\n    def m(cls, x: int) -> int:\n        pass\nB: Any\nclass C(B, metaclass=M):\n    pass\n\nx: Type[C]\nreveal_type(x.m) # N: Revealed type is \"def (x: builtins.int) -> builtins.int\"\nreveal_type(x.whatever) # N: Revealed type is \"Any\"\n[out]\n\n[case testMetaclassMemberAccessViaType3]\nfrom typing import Any, Type, TypeVar\nT = TypeVar('T')\nclass C(Any):\n    def bar(self: T) -> Type[T]: pass\n    def foo(self) -> None:\n        reveal_type(self.bar()) # N: Revealed type is \"type[__main__.C]\"\n        reveal_type(self.bar().__name__) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/type.pyi]\n[out]\n\n[case testClassDecoratorIsTypeChecked]\nfrom typing import Callable, Type\ndef decorate(x: int) -> Callable[[type], type]:\n    ...\ndef decorate_forward_ref() -> Callable[[Type[A]], Type[A]]:\n    ...\n@decorate(y=17)    # E: Unexpected keyword argument \"y\" for \"decorate\"\n@decorate()        # E: Missing positional argument \"x\" in call to \"decorate\"\n@decorate(22, 25)  # E: Too many arguments for \"decorate\"\n@decorate_forward_ref()\n@decorate(11)\nclass A: pass\n\n@decorate  # E: Argument 1 to \"decorate\" has incompatible type \"type[A2]\"; expected \"int\"\nclass A2: pass\n\n[case testClassDecoratorIncorrect]\ndef not_a_class_decorator(x: int) -> int: ...\n@not_a_class_decorator(7)\nclass A3: pass  # E: \"int\" not callable\n\nnot_a_function = 17\n@not_a_function()  # E: \"int\" not callable\nclass B: pass\n\n@not_a_function\nclass B2: pass    # E: \"int\" not callable\n\nb = object()\n@b.nothing         # E: \"object\" has no attribute \"nothing\"\nclass C: pass\n\n@undefined         # E: Name \"undefined\" is not defined\nclass D: pass\n\n[case testSlotsCompatibility]\nclass A:\n    __slots__ = ()\nclass B(A):\n    __slots__ = ('a', 'b')\nclass C:\n    __slots__ = ('x',)\nclass D(B, C):  # E: Class \"D\" has incompatible disjoint bases\n    __slots__ = ('aa', 'bb', 'cc')\n[builtins fixtures/tuple.pyi]\n\n[case testRevealLocalsOnClassVars]\nclass C1(object):\n    t = 'a'\n    y = 3.0\n    class Inner(object): pass\n    reveal_locals()\n\n[out]\nmain:5: note: Revealed local types are:\nmain:5: note:     t: builtins.str\nmain:5: note:     y: builtins.float\n\n[case testAbstractClasses]\nimport a\nimport b\n\n[file a.pyi]\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Protocol\n\nclass A:  # OK, has @abstractmethod\n    @abstractmethod\n    def f(self) -> None:\n        pass\n\nclass B(A):  # E: Class a.B has abstract attributes \"f\"  # N: If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass\n    pass\n\nclass C(A, metaclass=ABCMeta):  # OK, has ABCMeta as a metaclass\n    pass\n\nclass D(A):  # OK, implements the abstract method\n    def f(self) -> None:\n        pass\n\nclass E(Protocol):  # OK, is a protocol\n    @abstractmethod\n    def f(self) -> None:\n        pass\n\nclass F(E, Protocol):  # OK, is a protocol\n    pass\n\n# Custom metaclass subclassing `ABCMeta`, see #13561\nclass CustomMeta(ABCMeta):\n    pass\n\nclass G(A, metaclass=CustomMeta):  # Ok, has CustomMeta as a metaclass\n    pass\n\n[file b.py]\n# All of these are OK because this is not a stub file.\nfrom abc import ABCMeta, abstractmethod\nfrom typing import Protocol\n\nclass A:\n    @abstractmethod\n    def f(self) -> None:\n        pass\n\nclass B(A):\n    pass\n\nclass C(A, metaclass=ABCMeta):\n    pass\n\nclass D(A):\n    def f(self) -> None:\n        pass\n\nclass E(Protocol):\n    @abstractmethod\n    def f(self) -> None:\n        pass\n\nclass F(E, Protocol):\n    pass\n\nclass CustomMeta(ABCMeta):\n    pass\n\nclass G(A, metaclass=CustomMeta):\n    pass\n\n[case testClassMethodOverride]\nfrom typing import Callable, Any\n\ndef deco(f: Callable[..., Any]) -> Callable[..., Any]: ...\n\nclass B:\n    @classmethod\n    def meth(cls, x: int) -> int: ...\n\nclass C(B):\n    @classmethod\n    @deco\n    def meth(cls, x: int) -> int: ...\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testGetAttrImportAnnotation]\nimport a\nx: a.A\ny: a.A.B.C\nreveal_type(x)  # N: Revealed type is \"Any\"\nreveal_type(y)  # N: Revealed type is \"Any\"\n[file a.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[builtins fixtures/module.pyi]\n[out]\n\n[case testGetAttrImportBaseClass]\nimport a\nclass B(a.A): ...\n[file a.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[builtins fixtures/module.pyi]\n[out]\n\n[case testGetAttrDescriptor]\nfrom typing import TypeVar, Generic, Any\n\nT = TypeVar('T')\nclass C(Generic[T]):\n    normal: T\n    def __getattr__(self, attr: str) -> T: ...\n\nclass Descr:\n    def __get__(self, inst: Any, owner: Any) -> int: ...\n\nclass D(C[Descr]):\n    other: Descr\n\nd: D\nreveal_type(d.normal)  # N: Revealed type is \"builtins.int\"\nreveal_type(d.dynamic)  # N: Revealed type is \"__main__.Descr\"\nreveal_type(D.other)  # N: Revealed type is \"builtins.int\"\nD.dynamic  # E: \"type[D]\" has no attribute \"dynamic\"\n[out]\n\n[case testSelfDescriptorAssign]\nfrom typing import Any\n\nclass Descr:\n    def __get__(self, inst: Any, owner: Any) -> int: ...\n\nclass C:\n    def __init__(self, x: Descr) -> None:\n        self.x = x\n\nc = C(Descr())\nreveal_type(c.x)  # N: Revealed type is \"__main__.Descr\"\n[out]\n\n[case testForwardInstanceWithWrongArgCount]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nclass G(Generic[T]): ...\n\nA = G\nx: A[B[int, int]]  # E: \"G\" expects 1 type argument, but 2 given\nB = G\n[out]\n\n[case testForwardInstanceWithNoArgs]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nclass G(Generic[T]): ...\n\nA = G\nx: A[B]\nreveal_type(x)  # N: Revealed type is \"__main__.G[__main__.G[Any]]\"\nB = G\n[out]\n\n[case testForwardInstanceWithBound]\n# flags: --show-column-numbers\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T', bound=str)\nclass G(Generic[T]): ...\n\nA = G\nx: A[B[int]] # E\nB = G\n[out]\nmain:8:6: error: Type argument \"G[int]\" of \"G\" must be a subtype of \"str\"\nmain:8:8: error: Type argument \"int\" of \"G\" must be a subtype of \"str\"\n\n[case testExtremeForwardReferencing]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T', covariant=True)\nclass B(Generic[T]): ...\n\ny: A\nz: A[int]\nx = [y, z]\nreveal_type(x)  # N: Revealed type is \"builtins.list[__main__.B[Any]]\"\n\nA = B\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNoneAnyFallback]\nfrom typing import Any\ndynamic: Any\nclass C(dynamic): pass\nx: None = C()  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"None\")\n[out]\n\n[case testNoneAnyFallbackDescriptor]\nfrom typing import Any\nfrom d import Descr\n\ndynamic: Any\nclass C(dynamic):\n    id = Descr(int)\n    name = Descr(str)\n\nc: C\nreveal_type(c.id)  # N: Revealed type is \"builtins.int\"\nreveal_type(C.name)  # N: Revealed type is \"d.Descr[builtins.str]\"\n\n[file d.pyi]\nfrom typing import Any, overload, Generic, TypeVar, Type\n\nT = TypeVar('T')\nclass Descr(Generic[T]):\n    def __init__(self, tp: Type[T]) -> None: ...\n    @overload\n    def __get__(self, inst: None, owner: Any) -> Descr[T]: ...\n    @overload\n    def __get__(self, inst: object, owner: Any) -> T: ...\n[out]\n\n[case testClassCustomPropertyWorks]\nfrom typing import TypeVar, Generic, Callable, Any\n\nV = TypeVar('V')\n\nclass classproperty(Generic[V]):\n    def __init__(self, getter: Callable[[Any], V]) -> None:\n        self.getter = getter\n    def __get__(self, instance: Any, owner: Any) -> V:\n        return self.getter(owner)\n\nclass C:\n    @classproperty\n    def foo(cls) -> int:\n        return 42\n\nreveal_type(C.foo)  # N: Revealed type is \"builtins.int\"\nreveal_type(C().foo)  # N: Revealed type is \"builtins.int\"\n[out]\n\n[case testMultipleInheritanceCycle]\nimport b\n[file a.py]\nfrom b import B\nclass A: ...\nclass C(A, B): ...\nclass D(C): ...\nclass Other: ...\n[file b.py]\nfrom a import Other\nclass B: ...\n[out]\n\n[case testMultipleInheritanceCycle2]\nimport b\n[file a.py]\nfrom b import B\nclass A: ...\nclass C(A, B): ...\nclass D(C): ...\nclass Other: ...\na: A\nb: B\nc: C\nd: D\nd = A()  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"D\")\nif int():\n    d = B()  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"D\")\nif int():\n    d = C()  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"D\")\na = D()\nb = D()\nc = D()\n[file b.py]\nfrom a import Other\nclass B: ...\n[out]\n\n[case testAllowPropertyAndInit1]\nclass C:\n    def __init__(self, x: int) -> None:\n        self.x = x\n    @property\n    def x(self) -> int: pass\n    @x.setter\n    def x(self, x: int) -> None: pass\n[builtins fixtures/property.pyi]\n[out]\n\n[case testAllowPropertyAndInit2]\nclass C:\n    @property\n    def x(self) -> int: pass\n    @x.setter\n    def x(self, x: int) -> None: pass\n    def __init__(self, x: int) -> None:\n        self.x = x\n[builtins fixtures/property.pyi]\n\n[case testAllowPropertyAndInit3]\nclass C:\n    def __init__(self, x: int) -> None:\n        self.x = x  # type: ignore\n    @property  # Should be no error here\n    def x(self) -> int: pass\n[builtins fixtures/property.pyi]\n[out]\n\n[case testClassMethodBeforeInit1]\nclass Foo:\n    @classmethod\n    def bar(cls) -> Foo:\n        return cls(\"bar\")\n\n    def __init__(self, baz: str) -> None:\n        self.baz = baz\n[builtins fixtures/classmethod.pyi]\n\n[case testClassMethodBeforeInit2]\nclass Foo:\n    @classmethod\n    def bar(cls) -> Foo:\n        return cls(Bar())\n\n    def __init__(self, baz: 'Bar') -> None:\n        self.baz = baz\n\nclass Bar: pass\n[builtins fixtures/classmethod.pyi]\n\n[case testClassMethodBeforeInit3]\nfrom typing import overload\nclass Foo:\n    @classmethod\n    @overload\n    def bar(cls, x: int) -> Foo: ...\n    @classmethod\n    @overload\n    def bar(cls, x: str) -> Foo: ...\n    @classmethod\n    def bar(cls, x: object) -> Foo:\n        return cls(x)\n\n    def __init__(self, baz: object) -> None:\n        self.baz = baz\n\n[builtins fixtures/classmethod.pyi]\n\n[case testNewAndInit1]\nclass A:\n    def __init__(self, x: int) -> None:\n        pass\n\nclass B(A):\n    def __new__(cls) -> B:\n        pass\n\nB()\n\n[case testNewAndInit2]\nfrom typing import Any\n\nclass A:\n    def __new__(cls, *args: Any) -> 'A':\n        ...\n\nclass B(A):\n    def __init__(self, x: int) -> None:\n        pass\n\nreveal_type(B)  # N: Revealed type is \"def (x: builtins.int) -> __main__.B\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAndInit3]\nfrom typing import Any\n\nclass A:\n    def __new__(cls, *args: Any) -> 'A':\n        ...\n    def __init__(self, x: int) -> None:\n        pass\n\nreveal_type(A)  # N: Revealed type is \"def (x: builtins.int) -> __main__.A\"\n[builtins fixtures/tuple.pyi]\n\n[case testCyclicDecorator]\nimport b\n[file a.py]\nimport b\nimport c\n\nclass A(b.B):\n    @c.deco\n    def meth(self) -> int: ...\n[file b.py]\nimport a\nimport c\n\nclass B:\n    @c.deco\n    def meth(self) -> int: ...\n[file c.py]\nfrom typing import TypeVar, Tuple, Callable\nT = TypeVar('T')\ndef deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCyclicOverload]\nimport b\n[file a.pyi]\nimport b\nfrom typing import overload\n\nclass A(b.B):\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n[file b.pyi]\nimport a\nfrom typing import overload\n\nclass B:\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n[out]\n\n[case testCyclicOverloadDeferred]\nimport b\n[file a.py]\nimport b\nfrom typing import overload, Union\n\nclass A(b.B):\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n    def meth(self, x) -> Union[int, str]:\n        reveal_type(other.x)  # N: Revealed type is \"builtins.int\"\n        return 0\n\nother: Other\nclass Other:\n    def __init__(self) -> None:\n        self.x = f()\ndef f() -> int: ...\n[file b.py]\nimport a\nfrom typing import overload\n\nclass B:\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n    def meth(self, x):\n        pass\n[out]\n\n[case testCyclicOverrideAny]\nimport a\n[file b.py]\nimport a\nclass Sub(a.Base):\n    def x(self) -> int: pass\n\n[file a.py]\nimport b\nclass Base:\n    def __init__(self):\n        self.x = 1\n[out]\n\n[case testCyclicOverrideChecked]\nimport a\n[file b.py]\nimport a\nclass Sub(a.Base):\n    def x(self) -> int: pass  # E: Signature of \"x\" incompatible with supertype \"Base\" \\\n                              # N:      Superclass: \\\n                              # N:          int \\\n                              # N:      Subclass: \\\n                              # N:          def x(self) -> int\n\n[file a.py]\nimport b\nclass Base:\n    def __init__(self) -> None:\n        self.x = 1\n[out]\n\n[case testCyclicOverrideCheckedDecorator]\nimport a\n[file b.py]\nimport a\nimport c\nclass Sub(a.Base):\n    @c.deco\n    def x(self) -> int: pass  # E: Signature of \"x\" incompatible with supertype \"Base\" \\\n                              # N:      Superclass: \\\n                              # N:          int \\\n                              # N:      Subclass: \\\n                              # N:          def x(*Any, **Any) -> tuple[int, int]\n\n[file a.py]\nimport b\nimport c\nclass Base:\n    def __init__(self) -> None:\n        self.x = 1\n[file c.py]\nfrom typing import TypeVar, Tuple, Callable\nT = TypeVar('T')\ndef deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCyclicOverrideCheckedDecoratorDeferred]\nimport a\n[file b.py]\nimport a\nimport c\nclass Sub(a.Base):\n    @c.deco\n    def x(self) -> int: pass  # E: Signature of \"x\" incompatible with supertype \"Base\" \\\n                              # N:      Superclass: \\\n                              # N:          int \\\n                              # N:      Subclass: \\\n                              # N:          def x(*Any, **Any) -> tuple[int, int]\n\n[file a.py]\nimport b\nimport c\nclass Base:\n    def __init__(self) -> None:\n        self.x = f()\n\ndef f() -> int: ...\n[file c.py]\nfrom typing import TypeVar, Tuple, Callable\nT = TypeVar('T')\ndef deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCyclicOverrideAnyDecoratorDeferred]\nimport a\n[file b.py]\nimport a\nimport c\nclass Sub(a.Base):\n    @c.deco\n    def x(self) -> int: pass\n\n[file a.py]\nfrom b import Sub\nimport c\nclass Base:\n    def __init__(self) -> None:\n        self.x = f()\n\ndef f() -> int: ...\n[file c.py]\nfrom typing import Any, Callable\ndef deco(f: Callable[..., Any]) -> Any: ...\n[out]\n\n[case testCyclicDecoratorDoubleDeferred]\nimport b\n[file a.py]\nimport b\nimport c\n\nclass A(b.B):\n    @c.deco\n    def meth(self) -> int:\n        reveal_type(other.x)  # N: Revealed type is \"builtins.int\"\n        return 0\n\nother: Other\nclass Other:\n    def __init__(self) -> None:\n        self.x = f()\ndef f() -> int: ...\n[file b.py]\nfrom a import A\nimport c\n\nclass B:\n    @c.deco\n    def meth(self) -> int:\n        pass\n[file c.py]\nfrom typing import TypeVar, Tuple, Callable\nT = TypeVar('T')\ndef deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCyclicDecoratorSuper]\nimport b\n[file a.py]\nimport b\nimport c\n\nclass A(b.B):\n    @c.deco\n    def meth(self) -> int:\n        y = super().meth()\n        reveal_type(y)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n        return 0\n[file b.py]\nfrom a import A\nimport c\n\nclass B:\n    @c.deco\n    def meth(self) -> int:\n        pass\n[file c.py]\nfrom typing import TypeVar, Tuple, Callable\nT = TypeVar('T')\ndef deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCyclicDecoratorBothDeferred]\nimport b\n[file a.py]\nimport b\nimport c\n\nclass A(b.B):\n    @c.deco\n    def meth(self) -> int:\n        pass\n[file b.py]\nfrom a import A\nimport c\n\nclass B:\n    @c.deco\n    def meth(self) -> int:\n        reveal_type(other.x)  # N: Revealed type is \"builtins.int\"\n        return 0\n\nother: Other\nclass Other:\n    def __init__(self) -> None:\n        self.x = f()\ndef f() -> int: ...\n[file c.py]\nfrom typing import TypeVar, Tuple, Callable\nT = TypeVar('T')\ndef deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCyclicDecoratorSuperDeferred]\nimport b\n[file a.py]\nimport b\nimport c\n\nclass A(b.B):\n    @c.deco\n    def meth(self) -> int:\n        y = super().meth()\n        reveal_type(y)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n        reveal_type(other.x)  # N: Revealed type is \"builtins.int\"\n        return 0\n\nother: Other\nclass Other:\n    def __init__(self) -> None:\n        self.x = f()\ndef f() -> int: ...\n[file b.py]\nfrom a import A\nimport c\n\nclass B:\n    @c.deco\n    def meth(self) -> int:\n        pass\n[file c.py]\nfrom typing import TypeVar, Tuple, Callable\nT = TypeVar('T')\ndef deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...\n[builtins fixtures/tuple.pyi]\n\n[case testOverrideWithUntypedNotChecked]\nclass Parent:\n    def foo(self, x):\n        ...\n    def bar(self, x):\n        ...\n    def baz(self, x: int) -> str:\n        return \"\"\n\nclass Child(Parent):\n    def foo(self, y):  # OK: names not checked\n        ...\n    def bar(self, x, y):\n        ...\n    def baz(self, x, y):\n        return \"\"\n[builtins fixtures/tuple.pyi]\n\n[case testOverrideWithUntypedCheckedWithCheckUntypedDefs]\n# flags: --check-untyped-defs\nclass Parent:\n    def foo(self, x):\n        ...\n    def bar(self, x):\n        ...\n    def baz(self, x: int) -> str:\n        return \"\"\n\nclass Child(Parent):\n    def foo(self, y):  # OK: names not checked\n        ...\n    def bar(self, x, y) -> None:  # E: Signature of \"bar\" incompatible with supertype \"Parent\" \\\n                                  # N:      Superclass: \\\n                                  # N:          def bar(self, x: Any) -> Any \\\n                                  # N:      Subclass: \\\n                                  # N:          def bar(self, x: Any, y: Any) -> None\n        ...\n    def baz(self, x, y):  # E: Signature of \"baz\" incompatible with supertype \"Parent\" \\\n                          # N:      Superclass: \\\n                          # N:          def baz(self, x: int) -> str \\\n                          # N:      Subclass: \\\n                          # N:          def baz(self, x: Any, y: Any) -> Any\n        return \"\"\n[builtins fixtures/tuple.pyi]\n\n[case testOptionalDescriptorsBinder]\nfrom typing import Type, TypeVar, Optional\nT = TypeVar('T')\n\nclass IntDescr:\n    def __get__(self, obj: T, typ: Type[T]) -> Optional[int]: ...\n    def __set__(self, obj: T, value: Optional[int]) -> None: ...\n\nclass C:\n    spec = IntDescr()\n\n    def meth_spec(self) -> None:\n        if self.spec is None:\n            self.spec = 0\n        reveal_type(self.spec)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/bool.pyi]\n\n[case testUnionDescriptorsBinder]\nfrom typing import Type, TypeVar, Union\nT = TypeVar('T')\n\nclass A: ...\nclass B: ...\n\nclass UnionDescr:\n    def __get__(self, obj: T, typ: Type[T]) -> Union[A, B]: ...\n    def __set__(self, obj: T, value: Union[A, B]) -> None: ...\n\nclass C:\n    spec = UnionDescr()\n\n    def meth_spec(self) -> None:\n        self.spec = A()\n        reveal_type(self.spec)  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/bool.pyi]\n\n[case testSubclassDescriptorsBinder]\nfrom typing import Type, TypeVar, Optional\nT = TypeVar('T')\n\nclass A: ...\nclass B(A): ...\n\nclass SubDescr:\n    def __get__(self, obj: T, typ: Type[T]) -> A: ...\n    def __set__(self, obj: T, value: A) -> None: ...\n\nclass C:\n    spec = SubDescr()\n\n    def meth_spec(self) -> None:\n        self.spec = B()\n        reveal_type(self.spec)  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/bool.pyi]\n\n[case testDecoratedDunderGet]\nfrom typing import Any, Callable, TypeVar, Type\n\nF = TypeVar('F', bound=Callable)\nT = TypeVar('T')\n\ndef decorator(f: F) -> F:\n    return f\n\ndef change(f: Callable) -> Callable[..., int]:\n    pass\n\ndef untyped(f):\n    return f\n\nclass A: ...\n\nclass Descr1:\n    @decorator\n    def __get__(self, obj: T, typ: Type[T]) -> A: ...\nclass Descr2:\n    @change\n    def __get__(self, obj: T, typ: Type[T]) -> A: ...\nclass Descr3:\n    @untyped\n    def __get__(self, obj: T, typ: Type[T]) -> A: ...\n\nclass C:\n    spec1 = Descr1()\n    spec2 = Descr2()\n    spec3 = Descr3()\n\nc: C\nreveal_type(c.spec1)  # N: Revealed type is \"__main__.A\"\nreveal_type(c.spec2)  # N: Revealed type is \"builtins.int\"\nreveal_type(c.spec3)  # N: Revealed type is \"Any\"\n[builtins fixtures/bool.pyi]\n\n[case testDecoratedDunderSet]\nfrom typing import Any, Callable, TypeVar, Type\n\nF = TypeVar('F', bound=Callable)\nT = TypeVar('T')\n\ndef decorator(f: F) -> F:\n    return f\n\ndef change(f: Callable) -> Callable[[Any, Any, int], None]:\n    pass\n\ndef untyped(f):\n    return f\n\nclass A: ...\n\nclass Descr1:\n    @decorator\n    def __set__(self, obj: T, value: A) -> None: ...\nclass Descr2:\n    @change\n    def __set__(self, obj: T, value: A) -> None: ...\nclass Descr3:\n    @untyped\n    def __set__(self, obj: T, value: A) -> None: ...\n\nclass C:\n    spec1 = Descr1()\n    spec2 = Descr2()\n    spec3 = Descr3()\n\nc: C\nc.spec1 = A()\nc.spec1 = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"A\")\nc.spec2 = A()  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"int\")\nc.spec2 = 1\nc.spec3 = A()\nc.spec3 = 1\n[builtins fixtures/bool.pyi]\n\n[case testClassLevelImport]\n# flags: --ignore-missing-imports\nclass Test:\n    import a\n    def __init__(self) -> None:\n        some_module = self.a\n[out]\n\n[case testIsInstanceTypeVsMetaclass]\nfrom typing import Type\nclass Meta(type):\n    pass\nclass Thing(metaclass=Meta):\n    pass\n\ndef foo(x: Type[Thing]) -> Type[Thing]:\n    assert isinstance(x, Meta)\n    return x\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceTypeVsUnionOfType]\nfrom typing import Type, Union\n\nclass AA: pass\nclass AB: pass\n\nclass M: pass\n\nclass A(M, AA): pass\nclass B(M, AB): pass\n\nAOrB = Union[A, B]\n\nclass T(object):\n    def __init__(self, typ: Type[AOrB] = A) -> None:\n        assert isinstance(typ, type(M))\n        self.typ: Type[AOrB] = typ\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceTypeIsSubclass]\nfrom typing import Union, Type\n\nclass C: ...\n\nx: Union[C, Type[C]]\n\nif isinstance(x, type) and issubclass(x, C):\n    reveal_type(x)  # N: Revealed type is \"type[__main__.C]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceTypeByAssert]\nclass A:\n    x = 42\n\ni: type = A\nassert issubclass(i, A)\nreveal_type(i.x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceTypeTypeVar]\nfrom typing import Type, TypeVar, Generic, ClassVar\n\nclass Base: ...\nclass Sub(Base):\n    other: ClassVar[int]\n\nT = TypeVar('T', bound=Base)\n\nclass C(Generic[T]):\n    def meth(self, cls: Type[T]) -> None:\n        if not issubclass(cls, Sub):\n            return\n        reveal_type(cls)  # N: Revealed type is \"type[T`1]\"\n        reveal_type(cls.other)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceTypeSubclass]\nfrom typing import Type, Optional\nclass Base: ...\nclass One(Base):\n    x: int\nclass Other(Base):\n    x: int\n\ndef test() -> None:\n    x: Optional[Type[Base]]\n    if int():\n        x = One\n    elif int():\n        x = Other\n    else:\n        return\n    reveal_type(x)  # N: Revealed type is \"(def () -> __main__.One) | (def () -> __main__.Other)\"\n    reveal_type(x.x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testMemberRedefinition]\nclass C:\n    def __init__(self) -> None:\n        self.foo = 12\n        self.foo: int = 12  # E: Attribute \"foo\" already defined on line 3\n\n[case testMemberRedefinitionDefinedInClass]\nclass C:\n    foo = 12\n    def __init__(self) -> None:\n        self.foo: int = 12  # E: Attribute \"foo\" already defined on line 2\n\n[case testAbstractInit]\nfrom abc import abstractmethod, ABCMeta\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def __init__(self, a: int) -> None:\n        pass\nclass B(A):\n    pass\nclass C(B):\n    def __init__(self, a: int) -> None:\n        self.c = a\na = A(1) # E: Cannot instantiate abstract class \"A\" with abstract attribute \"__init__\"\nA.c # E: \"type[A]\" has no attribute \"c\"\nb = B(2) # E: Cannot instantiate abstract class \"B\" with abstract attribute \"__init__\"\nB.c # E: \"type[B]\" has no attribute \"c\"\nc = C(3)\nc.c\nC.c  # E: Cannot access instance-only attribute \"c\" on class object\n\n[case testAccessInstanceVarOnClass]\nclass A:\n    def __init__(self) -> None:\n        self.x = 0\n\nA.x  # E: Cannot access instance-only attribute \"x\" on class object\nA.x = 1  # We allow this, since it works at runtime, even though it is weird\n\nclass B:\n    x = 1\nclass C(B):\n    def __init__(self) -> None:\n        self.x: int = 2\nC.x # Again, this works at runtime, so we don't prohibit this\n\n[case testDecoratedConstructors]\nfrom typing import TypeVar, Callable, Any\n\nF = TypeVar('F', bound=Callable[..., Any])\n\ndef dec(f: F) -> F: ...\n\nclass A:\n    @dec\n    def __init__(self, x: int) -> None: ...\n\nclass B:\n    @dec\n    def __new__(cls, x: int) -> B: ...\n\nreveal_type(A)  # N: Revealed type is \"def (x: builtins.int) -> __main__.A\"\nreveal_type(B)  # N: Revealed type is \"def (x: builtins.int) -> __main__.B\"\n\n[case testDecoratedConstructorsBad]\nfrom typing import Callable, Any\n\ndef dec(f: Callable[[Any, int], Any]) -> int: ...\n\nclass A:\n    @dec  # E: Unsupported decorated constructor type\n    def __init__(self, x: int) -> None: ...\n\nclass B:\n    @dec  # E: Unsupported decorated constructor type\n    def __new__(cls, x: int) -> B: ...\n\n[case testIgnorePrivateAttributesTypeCheck]\nclass B:\n    __foo_: int\nclass C(B):\n    __foo_: str\n[out]\n\n[case testIgnorePrivateMethodsTypeCheck]\nclass B:\n    def __foo_(self) -> int: ...\nclass C(B):\n    def __foo_(self) -> str: ...\n[out]\n\n[case testCheckForPrivateMethodsWhenPublicCheck]\nclass B:\n    __foo__: int\nclass C(B):\n    __foo__: str\n[out]\nmain:4: error: Incompatible types in assignment (expression has type \"str\", base class \"B\" defined the type as \"int\")\n\n[case testIgnorePrivateMethodsTypeCheck2]\nclass A:\n    def __foo_(self) -> int: ...\nclass B:\n    def __foo_(self) -> str: ...\n\nclass C(A, B): pass\n[out]\n\n[case testAttributeDefOrder1]\nimport a\n\n[file a.py]\nfrom b import C\n\nclass D(C):\n    def g(self) -> None:\n        self.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n    def f(self) -> None:\n        reveal_type(self.x) # N: Revealed type is \"builtins.int\"\n\n\n[file b.py]\nimport a\n\nclass C:\n    def __init__(self) -> None:\n        self.x = 0\n\n[targets b, a, b.C.__init__, a.D.g, a.D.f, __main__]\n\n[case testAttributeDefOrder2]\nclass D(C):\n    def g(self) -> None:\n        self.x = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n    def f(self) -> None:\n        reveal_type(self.x) # N: Revealed type is \"builtins.int\"\n\n\nclass C:\n    def __init__(self) -> None:\n        self.x = 0\n\nclass E(C):\n    def g(self) -> None:\n        self.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n    def f(self) -> None:\n        reveal_type(self.x) # N: Revealed type is \"builtins.int\"\n\n[targets __main__, __main__, __main__.C.__init__, __main__.D.g, __main__.D.f, __main__.E.g, __main__.E.f]\n\n[case testNewReturnType1]\nclass A:\n    def __new__(cls) -> B:\n        pass\n\nclass B(A): pass\n\nreveal_type(A())  # N: Revealed type is \"__main__.B\"\nreveal_type(B())  # N: Revealed type is \"__main__.B\"\n\n[case testNewReturnType2]\nfrom typing import Any\n\n# make sure that __new__ method that return Any are ignored when\n# determining the return type\nclass A:\n    def __new__(cls):\n        pass\n\nclass B:\n    def __new__(cls) -> Any:\n        pass\n\nreveal_type(A())  # N: Revealed type is \"__main__.A\"\nreveal_type(B())  # N: Revealed type is \"__main__.B\"\n\n[case testNewReturnType3]\n\n# Check for invalid __new__ typing\n\nclass A:\n    def __new__(cls) -> int:  # E: Incompatible return type for \"__new__\" (returns \"int\", but must return a subtype of \"A\")\n        pass\n\nreveal_type(A())  # N: Revealed type is \"__main__.A\"\n\n[case testNewReturnType4]\nfrom typing import TypeVar, Type\n\n# Check for __new__ using type vars\n\nTX = TypeVar('TX', bound='X')\nclass X:\n    def __new__(lol: Type[TX], x: int) -> TX:\n        pass\nclass Y(X): pass\n\nreveal_type(X(20))  # N: Revealed type is \"__main__.X\"\nreveal_type(Y(20))  # N: Revealed type is \"__main__.Y\"\n\n[case testNewReturnType5]\nfrom typing import Any, TypeVar, Generic, overload\n\nT = TypeVar('T')\nclass O(Generic[T]):\n    @overload\n    def __new__(cls) -> O[int]:\n        pass\n    @overload\n    def __new__(cls, x: int) -> O[str]:\n        pass\n    def __new__(cls, x: int = 0) -> O[Any]:\n        pass\n\nreveal_type(O())  # N: Revealed type is \"__main__.O[builtins.int]\"\nreveal_type(O(10))  # N: Revealed type is \"__main__.O[builtins.str]\"\n\n[case testNewReturnType6]\nfrom typing import Tuple, Optional\n\n# Check for some cases that aren't allowed\n\nclass X:\n    def __new__(cls) -> Optional[Y]:  # E: \"__new__\" must return a class instance (got \"Y | None\")\n        pass\nclass Y:\n    def __new__(cls) -> Optional[int]:  # E: \"__new__\" must return a class instance (got \"int | None\")\n        pass\n\n\n[case testNewReturnType7]\nfrom typing import NamedTuple\n\n# ... test __new__ returning tuple type\nclass A:\n    def __new__(cls) -> 'B':\n        pass\n\nN = NamedTuple('N', [('x', int)])\nclass B(A, N): pass\n\nreveal_type(A())  # N: Revealed type is \"tuple[builtins.int, fallback=__main__.B]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewReturnType8]\nfrom typing import TypeVar, Any\n\n# test type var from a different argument\nTX = TypeVar('TX', bound='X')\nclass X:\n    def __new__(cls, x: TX) -> TX:  # E: \"__new__\" must return a class instance (got \"TX\")\n        pass\n\n[case testNewReturnType9]\nclass A:\n    def __new__(cls) -> A:\n        pass\n\nclass B(A):\n    pass\n\nreveal_type(B())  # N: Revealed type is \"__main__.B\"\n\n[case testNewReturnType10]\n# https://github.com/python/mypy/issues/11398\nfrom typing import Type\n\nclass MyMetaClass(type):\n    def __new__(cls, name, bases, attrs) -> Type['MyClass']:\n        pass\n\nclass MyClass(metaclass=MyMetaClass):\n    pass\n\n[case testNewReturnType11]\n# https://github.com/python/mypy/issues/11398\nclass MyMetaClass(type):\n    def __new__(cls, name, bases, attrs) -> type:\n        pass\n\nclass MyClass(metaclass=MyMetaClass):\n    pass\n\n[case testNewReturnType12]\n# https://github.com/python/mypy/issues/11398\nfrom typing import Type\n\nclass MyMetaClass(type):\n    def __new__(cls, name, bases, attrs) -> int:  # E: Incompatible return type for \"__new__\" (returns \"int\", but must return a subtype of \"type\")\n        pass\n\nclass MyClass(metaclass=MyMetaClass):\n    pass\n\n\n[case testMetaclassPlaceholderNode]\nfrom sympy.assumptions import ManagedProperties\nfrom sympy.ops import AssocOp\nreveal_type(AssocOp.x)  # N: Revealed type is \"sympy.basic.Basic\"\nreveal_type(AssocOp.y)  # N: Revealed type is \"builtins.int\"\n\n[file sympy/__init__.py]\n\n[file sympy/assumptions.py]\nfrom .basic import Basic\nclass ManagedProperties(type):\n    x: Basic\n    y: int\n# The problem is with the next line,\n# it creates the following order (classname, metaclass):\n# 1. Basic NameExpr(ManagedProperties)\n# 2. AssocOp None\n# 3. ManagedProperties None\n# 4. Basic NameExpr(ManagedProperties [sympy.assumptions.ManagedProperties])\n# So, `AssocOp` will still have `metaclass_type` as `None`\n# and all its `mro` types will have `declared_metaclass` as `None`.\nfrom sympy.ops import AssocOp\n\n[file sympy/basic.py]\nfrom .assumptions import ManagedProperties\nclass Basic(metaclass=ManagedProperties): ...\n\n[file sympy/ops.py]\nfrom sympy.basic import Basic\nclass AssocOp(Basic): ...\n\n[case testMetaclassSubclassSelf]\n# This does not make much sense, but we must not crash:\nimport a\n[file m.py]\nfrom a import A  # E: Module \"a\" has no attribute \"A\"\nclass Meta(A): pass\n[file a.py]\nfrom m import Meta\nclass A(metaclass=Meta): pass\n\n[case testMetaclassConflict]\nclass MyMeta1(type): ...\nclass MyMeta2(type): ...\nclass MyMeta3(type): ...\nclass A(metaclass=MyMeta1): ...\nclass B(metaclass=MyMeta2): ...\nclass C(metaclass=type): ...\nclass A1(A): ...\nclass E: ...\n\nclass CorrectMeta(MyMeta1, MyMeta2): ...\nclass CorrectSubclass1(A1, B, E, metaclass=CorrectMeta): ...\nclass CorrectSubclass2(A, B, E, metaclass=CorrectMeta): ...\nclass CorrectSubclass3(B, A, metaclass=CorrectMeta): ...\n\nclass ChildOfCorrectSubclass1(CorrectSubclass1): ...\n\nclass CorrectWithType1(C, A1): ...\nclass CorrectWithType2(B, C): ...\n\nclass Conflict1(A1, B, E): ...  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                                # N: \"__main__.MyMeta1\" (metaclass of \"__main__.A\") conflicts with \"__main__.MyMeta2\" (metaclass of \"__main__.B\")\nclass Conflict2(A, B): ...  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                            # N: \"__main__.MyMeta1\" (metaclass of \"__main__.A\") conflicts with \"__main__.MyMeta2\" (metaclass of \"__main__.B\")\nclass Conflict3(B, A): ...  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                            # N: \"__main__.MyMeta2\" (metaclass of \"__main__.B\") conflicts with \"__main__.MyMeta1\" (metaclass of \"__main__.A\")\n\nclass ChildOfConflict1(Conflict3): ...\nclass ChildOfConflict2(Conflict3, metaclass=CorrectMeta): ...\n\nclass ConflictingMeta(MyMeta1, MyMeta3): ...\nclass Conflict4(A1, B, E, metaclass=ConflictingMeta): ...  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                                                           # N: \"__main__.ConflictingMeta\" (metaclass of \"__main__.Conflict4\") conflicts with \"__main__.MyMeta2\" (metaclass of \"__main__.B\")\n\nclass ChildOfCorrectButWrongMeta(CorrectSubclass1, metaclass=ConflictingMeta):  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                                                                                # N: \"__main__.ConflictingMeta\" (metaclass of \"__main__.ChildOfCorrectButWrongMeta\") conflicts with \"__main__.CorrectMeta\" (metaclass of \"__main__.CorrectSubclass1\")\n    ...\n\n[case testMetaClassConflictIssue14033]\nclass M1(type): pass\nclass M2(type): pass\nclass Mx(M1, M2): pass\n\nclass A1(metaclass=M1): pass\nclass A2(A1): pass\n\nclass B1(metaclass=M2): pass\n\nclass C1(metaclass=Mx): pass\n\nclass TestABC(A2, B1, C1): pass  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                                 # N: \"__main__.M1\" (metaclass of \"__main__.A1\") conflicts with \"__main__.M2\" (metaclass of \"__main__.B1\")\nclass TestBAC(B1, A2, C1): pass  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases \\\n                                 # N: \"__main__.M2\" (metaclass of \"__main__.B1\") conflicts with \"__main__.M1\" (metaclass of \"__main__.A1\")\n\n# should not warn again for children\nclass ChildOfTestABC(TestABC): pass\n\n# no metaclass is assumed if super class has a metaclass conflict\nclass ChildOfTestABCMetaMx(TestABC, metaclass=Mx): pass\nclass ChildOfTestABCMetaM1(TestABC, metaclass=M1): pass\n\nclass TestABCMx(A2, B1, C1, metaclass=Mx): pass\nclass TestBACMx(B1, A2, C1, metaclass=Mx): pass\n\nclass TestACB(A2, C1, B1): pass\nclass TestBCA(B1, C1, A2): pass\n\nclass TestCAB(C1, A2, B1): pass\nclass TestCBA(C1, B1, A2): pass\n\n[case testGenericOverride]\nfrom typing import Generic, TypeVar, Any\n\nT = TypeVar('T')\n\nclass B(Generic[T]):\n    x: T\n\nclass C(B):\n    def __init__(self) -> None:\n        self.x: Any\n\n[case testGenericOverridePreciseInvalid]\nfrom typing import Generic, TypeVar, Any\n\nT = TypeVar('T')\n\nclass B(Generic[T]):\n    x: T\n\nclass C(B[str]):\n    def __init__(self) -> None:\n        self.x: int  # E: Incompatible types in assignment (expression has type \"int\", base class \"B\" defined the type as \"str\")\n\n[case testGenericOverridePreciseValid]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass B(Generic[T]):\n    x: T\n\nclass C(B[float]):\n    def __init__(self) -> None:\n        self.x: int  # We currently allow covariant overriding.\n\n[case testGenericOverrideGeneric]\nfrom typing import Generic, TypeVar, List\n\nT = TypeVar('T')\n\nclass B(Generic[T]):\n    x: T\n\nclass C(B[T]):\n    def __init__(self) -> None:\n        self.x: List[T]  # E: Incompatible types in assignment (expression has type \"list[T]\", base class \"B\" defined the type as \"T\")\n[builtins fixtures/list.pyi]\n\n[case testGenericOverrideGenericChained]\nfrom typing import Generic, TypeVar, Tuple\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass A(Generic[T]):\n    x: T\n\nclass B(A[Tuple[T, S]]): ...\n\nclass C(B[int, T]):\n    def __init__(self) -> None:\n        # TODO: error message could be better.\n        self.x: Tuple[str, T]  # E: Incompatible types in assignment (expression has type \"tuple[str, T]\", base class \"A\" defined the type as \"tuple[int, T]\")\n[builtins fixtures/tuple.pyi]\n\n[case testInitSubclassWrongType]\nclass Base:\n    default_name: str\n\n    def __init_subclass__(cls, default_name: str):\n        super().__init_subclass__()\n        cls.default_name = default_name\n        return\n\nclass Child(Base, default_name=5):  # E: Argument \"default_name\" to \"__init_subclass__\" of \"Base\" has incompatible type \"int\"; expected \"str\"\n    pass\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testInitSubclassTooFewArgs]\nclass Base:\n    default_name: str\n\n    def __init_subclass__(cls, default_name: str, **kwargs):\n        super().__init_subclass__()\n        cls.default_name = default_name\n        return\n\nclass Child(Base):  # E: Missing positional argument \"default_name\" in call to \"__init_subclass__\" of \"Base\"\n    pass\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testInitSubclassTooFewArgs2]\nclass Base:\n    default_name: str\n\n    def __init_subclass__(cls, default_name: str, thing: int):\n        super().__init_subclass__()\n        cls.default_name = default_name\n        return\n# TODO implement this, so that no error is raised?\nd = {\"default_name\": \"abc\", \"thing\": 0}\nclass Child(Base, **d):  # E: Missing positional arguments \"default_name\", \"thing\" in call to \"__init_subclass__\" of \"Base\"\n    pass\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testInitSubclassOK]\nclass Base:\n    default_name: str\n    thing: int\n\n    def __init_subclass__(cls, default_name: str, thing:int, **kwargs):\n        super().__init_subclass__()\n        cls.default_name = default_name\n        return\n\nclass Child(Base, thing=5, default_name=\"\"):\n    pass\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testInitSubclassWithMetaclassOK]\nclass Base:\n    thing: int\n\n    def __init_subclass__(cls, thing: int):\n        cls.thing = thing\n\nclass Child(Base, metaclass=type, thing=0):\n    pass\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testInitSubclassWithCustomMetaclassOK]\nclass M(type): ...\nclass Child(metaclass=M, thing=0):\n    pass\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testTooManyArgsForObject]\nclass A(thing=5):\n    pass\n[out]\nmain:1: error: Unexpected keyword argument \"thing\" for \"__init_subclass__\" of \"object\"\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testInitSubclassWithImports]\nfrom init_subclass.a import Base\nclass Child(Base, thing=5):  # E: Missing positional argument \"default_name\" in call to \"__init_subclass__\" of \"Base\"\n    pass\n[file init_subclass/a.py]\nclass Base:\n    default_name: str\n    thing: int\n\n    def __init_subclass__(cls, default_name: str, thing:int, **kwargs):\n        pass\n[file init_subclass/__init__.py]\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testInitSubclassWithImportsOK]\nfrom init_subclass.a import MidBase\nclass Main(MidBase, test=True): pass\n[file init_subclass/a.py]\nclass Base:\n    def __init_subclass__(cls, **kwargs) -> None: pass\nclass MidBase(Base): pass\n[file init_subclass/__init__.py]\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testInitSubclassUnannotated]\nclass A:\n    def __init_subclass__(cls, *args, **kwargs):\n        super().__init_subclass__(*args, **kwargs)\n\nclass B(A):\n    pass\n\nreveal_type(A.__init_subclass__)  # N: Revealed type is \"def (*args: Any, **kwargs: Any) -> Any\"\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testInitSubclassUnannotatedMulti]\nfrom typing import ClassVar, List, Type\n\nclass A:\n    registered_classes: ClassVar[List[Type[A]]] = []\n    def __init_subclass__(cls, *args, register=True, **kwargs):\n        if register:\n            cls.registered_classes.append(cls)\n        super().__init_subclass__(*args, **kwargs)\n\nclass B(A): ...\nclass C(A, register=False): ...\nclass D(C): ...\n[builtins fixtures/object_with_init_subclass.pyi]\n\n[case testClassMethodUnannotated]\nclass C:\n    def __new__(cls): ...\n    @classmethod\n    def meth(cls): ...\n\nreveal_type(C.meth)  # N: Revealed type is \"def () -> Any\"\nreveal_type(C.__new__)  # N: Revealed type is \"def (cls: type[__main__.C]) -> Any\"\n[builtins fixtures/classmethod.pyi]\n\n[case testOverrideGenericSelfClassMethod]\nfrom typing import Generic, TypeVar, Type, List\n\nT = TypeVar('T', bound='A')\n\nclass A:\n    @classmethod\n    def meth(cls: Type[T]) -> List[T]: ...\n\nclass B(A):\n    @classmethod\n    def meth(cls: Type[T]) -> List[T]: ...\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testCheckUntypedDefsSelf1]\n# flags: --check-untyped-defs\n\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass Desc:\n    def __get__(self, x, y):\n        # type: (...) -> bool\n        pass\n\nclass Foo:\n    y = Desc()\n\n    def __init__(self):\n        self.x = 0\n\n    def foo(self):\n        reveal_type(self.x)  # N: Revealed type is \"builtins.int\"\n        reveal_type(self.y)  # N: Revealed type is \"builtins.bool\"\n        self.bar()\n        self.baz()  # E: \"Foo\" has no attribute \"baz\"\n\n    @classmethod\n    def bar(cls):\n        cls.baz()  # E: \"type[Foo]\" has no attribute \"baz\"\n\nclass C(Generic[T]):\n    x: T\n    def meth(self):\n        self.x + 1  # E: Unsupported left operand type for + (\"T\")\n[builtins fixtures/classmethod.pyi]\n\n[case testCheckUntypedDefsSelf2]\n# flags: --check-untyped-defs\n\nclass Foo:\n    def __init__(self):\n        self.x = None\n        self.y = []\n\nreveal_type(Foo().x)  # N: Revealed type is \"Any | None\"\nreveal_type(Foo().y)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testCheckUntypedDefsSelf3]\n# flags: --check-untyped-defs\n\nclass Foo:\n    def bad():  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n        self.x = 0  # E: Name \"self\" is not defined\n\n[case testMethodSelfArgumentChecks]\nfrom typing import Callable, ParamSpec, TypeVar\n\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\n\ndef to_number_1(fn: Callable[[], int]) -> int:\n    return 0\n\ndef to_number_2(fn: Callable[[int], int]) -> int:\n    return 0\n\ndef to_same_callable(fn: Callable[P, T]) -> Callable[P, T]:\n    return fn\n\nclass A:\n    def undecorated() -> None: ...  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n\n    def undecorated_not_self(x: int) -> None: ...  # E: \"self\" parameter missing for a non-static method (or an invalid type for self)\n\n    def undecorated_not_self_2(self: int) -> None: ...  # E: The erased type of self \"builtins.int\" is not a supertype of its class \"__main__.A\"\n\n    @to_number_1\n    def fn1() -> int:\n        return 0\n\n    @to_number_1  # E: Argument 1 to \"to_number_1\" has incompatible type \"Callable[[int], int]\"; expected \"Callable[[], int]\"\n    def fn2(_x: int) -> int:\n        return 0\n\n    @to_number_2  # E: Argument 1 to \"to_number_2\" has incompatible type \"Callable[[], int]\"; expected \"Callable[[int], int]\"\n    def fn3() -> int:\n        return 0\n\n    @to_number_2\n    def fn4(_x: int) -> int:\n        return 0\n\n    @to_number_2  # E: Argument 1 to \"to_number_2\" has incompatible type \"Callable[[str], int]\"; expected \"Callable[[int], int]\"\n    def fn5(_x: str) -> int:\n        return 0\n\n    @to_same_callable\n    def g1() -> None: ...  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n\n    @to_same_callable\n    def g2(x: int) -> None: ...  # E: \"self\" parameter missing for a non-static method (or an invalid type for self)\n\n    @to_same_callable\n    def g3(self: int) -> None: ...  # E: The erased type of self \"builtins.int\" is not a supertype of its class \"__main__.A\"\n\nreveal_type(A().fn1)  # N: Revealed type is \"builtins.int\"\nreveal_type(A().fn2)  # N: Revealed type is \"builtins.int\"\nreveal_type(A().fn3)  # N: Revealed type is \"builtins.int\"\nreveal_type(A().fn4)  # N: Revealed type is \"builtins.int\"\nreveal_type(A().fn5)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(A().g1)  # E: Attribute function \"g1\" with type \"Callable[[], None]\" does not accept self argument \\\n                     # N: Revealed type is \"def ()\"\nreveal_type(A().g2)  # E: Invalid self argument \"A\" to attribute function \"g2\" with type \"Callable[[int], None]\" \\\n                     # N: Revealed type is \"def ()\"\nreveal_type(A().g3)  # E: Invalid self argument \"A\" to attribute function \"g3\" with type \"Callable[[int], None]\" \\\n                     # N: Revealed type is \"def ()\"\n[builtins fixtures/tuple.pyi]\n\n[case testMethodSelfArgumentChecksConcatenate]\nfrom typing import Callable, ParamSpec, TypeVar\nfrom typing_extensions import Concatenate\n\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\ndef to_same_callable(fn: Callable[Concatenate[T, P], R]) -> Callable[Concatenate[T, P], R]:\n    return fn\n\ndef remove_first(fn: Callable[Concatenate[T, P], R]) -> Callable[P, R]:\n    ...\n\ndef add_correct_first(fn: Callable[P, R]) -> Callable[Concatenate[\"C\", P], R]:\n    ...\n\ndef add_wrong_first(fn: Callable[P, R]) -> Callable[Concatenate[int, P], R]:\n    ...\n\nclass A:\n    @to_same_callable  # E: Argument 1 to \"to_same_callable\" has incompatible type \"Callable[[], int]\"; expected \"Callable[[T], int]\"\n    def fn1() -> int:\n        return 0\n\n    @to_same_callable\n    def fn2(_x: int) -> int:  # E: \"self\" parameter missing for a non-static method (or an invalid type for self)\n        return 0\n\n    @to_same_callable\n    def fn3(self, _x: int) -> int:\n        return 0\n\nreveal_type(A().fn1)  # N: Revealed type is \"def () -> builtins.int\"\nreveal_type(A().fn2)  # E: Invalid self argument \"A\" to attribute function \"fn2\" with type \"Callable[[int], int]\" \\\n                      # N: Revealed type is \"def () -> builtins.int\"\nreveal_type(A().fn3)  # N: Revealed type is \"def (_x: builtins.int) -> builtins.int\"\n\nclass B:\n    @remove_first  # E: Argument 1 to \"remove_first\" has incompatible type \"Callable[[], int]\"; expected \"Callable[[T], int]\"\n    def fn1() -> int:  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n        return 0\n\n    @remove_first\n    def fn2(_x: int) -> int:  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n        return 0\n\n    @remove_first\n    def fn3(self, _x: int) -> int:  # E: \"self\" parameter missing for a non-static method (or an invalid type for self)\n        return 0\n\n    @remove_first\n    def fn4(self, new_self: 'B') -> int:\n        return 0\n\nreveal_type(B().fn1)  # E: Attribute function \"fn1\" with type \"Callable[[], int]\" does not accept self argument \\\n                      # N: Revealed type is \"def () -> builtins.int\"\nreveal_type(B().fn2)  # E: Attribute function \"fn2\" with type \"Callable[[], int]\" does not accept self argument \\\n                      # N: Revealed type is \"def () -> builtins.int\"\nreveal_type(B().fn3)  # E: Invalid self argument \"B\" to attribute function \"fn3\" with type \"Callable[[int], int]\" \\\n                      # N: Revealed type is \"def () -> builtins.int\"\nreveal_type(B().fn4)  # N: Revealed type is \"def () -> builtins.int\"\n\nclass C:\n    @add_correct_first\n    def fn1() -> int:\n        return 0\n\n    @add_correct_first\n    def fn2(_x: int) -> int:\n        return 0\n\n    @add_correct_first\n    def fn3(self, _x: int) -> int:\n        return 0\n\nreveal_type(C().fn1)  # N: Revealed type is \"def () -> builtins.int\"\nreveal_type(C().fn2)  # N: Revealed type is \"def (_x: builtins.int) -> builtins.int\"\nreveal_type(C().fn3)  # N: Revealed type is \"def (self: __main__.C, _x: builtins.int) -> builtins.int\"\n\nclass D:\n    @add_wrong_first\n    def fn1() -> int:  # E: \"self\" parameter missing for a non-static method (or an invalid type for self)\n        return 0\n\n    @add_wrong_first\n    def fn2(_x: int) -> int:  # E: \"self\" parameter missing for a non-static method (or an invalid type for self)\n        return 0\n\n    @add_wrong_first\n    def fn3(self, _x: int) -> int:  # E: \"self\" parameter missing for a non-static method (or an invalid type for self)\n        return 0\n\nreveal_type(D().fn1)  # E: Invalid self argument \"D\" to attribute function \"fn1\" with type \"Callable[[int], int]\" \\\n                      # N: Revealed type is \"def () -> builtins.int\"\nreveal_type(D().fn2)  # E: Invalid self argument \"D\" to attribute function \"fn2\" with type \"Callable[[int, int], int]\" \\\n                      # N: Revealed type is \"def (_x: builtins.int) -> builtins.int\"\nreveal_type(D().fn3)  # E: Invalid self argument \"D\" to attribute function \"fn3\" with type \"Callable[[int, D, int], int]\" \\\n                      # N: Revealed type is \"def (self: __main__.D, _x: builtins.int) -> builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testMethodSelfArgumentChecksInUntyped]\nfrom typing import Callable, ParamSpec, TypeVar\n\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\n\ndef to_same_callable(fn: Callable[P, T]) -> Callable[P, T]:\n    return fn\n\ndef unchecked():\n    class Bad:\n        def fn() -> None: ...  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n        def fn2(x: int) -> None: ...  # E: \"self\" parameter missing for a non-static method (or an invalid type for self)\n\n        # TODO: would be nice to make this error, but now we see the func\n        # being decorated as Any, not as a callable\n        @to_same_callable\n        def gaaa() -> None: ...\n        @to_same_callable\n        def gaaa2(x: int) -> None: ...\n\n    class Ok:\n        def fn(): ...\n        def fn2(x): ...\n\n        @to_same_callable\n        def g(): ...\n        @to_same_callable\n        def g2(x): ...\n\ndef checked() -> None:\n    class Bad:\n        def fn() -> None: ...  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n        def fn2(x: int) -> None: ...  # E: \"self\" parameter missing for a non-static method (or an invalid type for self)\n\n        @to_same_callable\n        def g() -> None: ...  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n        @to_same_callable\n        def g2(x: int) -> None: ...  # E: \"self\" parameter missing for a non-static method (or an invalid type for self)\n\n    class AlsoBad:\n        def fn(): ...  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n        def fn2(x): ...\n\n        @to_same_callable\n        def g(): ...  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n        @to_same_callable\n        def g2(x): ...\n\nclass Ok:\n    def fn(): ...  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n    def fn2(x): ...\n\n    @to_same_callable\n    def g(): ...  # E: Method must have at least one argument. Did you forget the \"self\" argument?\n    @to_same_callable\n    def g2(x): ...\n[builtins fixtures/tuple.pyi]\n\n[case testTypeAfterAttributeAccessWithDisallowAnyExpr]\n# flags: --disallow-any-expr\n\ndef access_before_declaration(self) -> None:\n    obj = Foo('bar')\n    obj.value\n    x = 1\n\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    x = x + 1\n\nclass Foo:\n    def __init__(self, value: str) -> None:\n        self.value = value\n\ndef access_after_declaration(self) -> None:\n    obj = Foo('bar')\n    obj.value\n    x = 1\n\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    x = x + 1\n\n[case testIsSubClassNarrowDownTypesOfTypeVariables]\nfrom typing import Type, TypeVar, Generic\n\nclass Base:\n    field: int = 42\n\nTypeT = TypeVar(\"TypeT\", bound=type)\n\nTypeT1 = TypeVar(\"TypeT1\", bound=Type[Base])\n\nclass C1:\n    def method(self, other: type) -> int:\n        if issubclass(other, Base):\n            reveal_type(other)  # N: Revealed type is \"type[__main__.Base]\"\n            return other.field\n        return 0\n\nclass C2(Generic[TypeT]):\n    def method(self, other: TypeT) -> int:\n        if issubclass(other, Base):\n            reveal_type(other)  # N: Revealed type is \"TypeT`1\"\n            return other.field\n        return 0\n\nclass C3(Generic[TypeT1]):\n    def method(self, other: TypeT1) -> int:\n        if issubclass(other, Base):\n            reveal_type(other)  # N: Revealed type is \"TypeT1`1\"\n            return other.field\n        return 0\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testPropertyWithExtraMethod]\ndef dec(f):\n    return f\n\nclass A:\n    @property\n    def x(self): ...\n    @x.setter\n    def x(self, value) -> None: ...\n    def x(self) -> None: ...  # E: Unexpected definition for property \"x\"\n\n    @property\n    def y(self) -> int: ...\n    @y.setter\n    def y(self, value: int) -> None: ...\n    @dec  # E: Only supported top decorators are \"@y.setter\" and \"@y.deleter\"\n    def y(self) -> None: ...\n\nreveal_type(A().y)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/property.pyi]\n\n[case testEnclosingScopeLambdaNoCrash]\nclass C:\n    x = lambda x: x.y.g()\n\n[case testEnclosingScopeLambdaNoCrashExplicit]\nfrom typing import Callable\nclass C:\n    x: Callable[[C], int] = lambda x: x.y.g()  # E: \"C\" has no attribute \"y\"\n\n[case testOpWithInheritedFromAny-xfail]\nfrom typing import Any\nC: Any\nclass D(C):\n    pass\n\nclass D1(C):\n    def __add__(self, rhs: float) -> D1:\n        return self\n\nreveal_type(0.5 + C)  # N: Revealed type is \"Any\"\n\nreveal_type(0.5 + D())  # N: Revealed type is \"Any\"\nreveal_type(D() + 0.5)  # N: Revealed type is \"Any\"\nreveal_type(\"str\" + D())  # N: Revealed type is \"builtins.str\"\nreveal_type(D() + \"str\")  # N: Revealed type is \"Any\"\n\n\nreveal_type(0.5 + D1())  # N: Revealed type is \"Any\"\nreveal_type(D1() + 0.5)  # N: Revealed type is \"__main__.D1\"\n[builtins fixtures/primitives.pyi]\n\n[case testRefMethodWithDecorator]\nfrom typing import Type, final\n\nclass A:\n    pass\n\nclass B:\n    @staticmethod\n    def A() -> Type[A]: ...\n    @staticmethod\n    def B() -> Type[A]:  # E: Function \"__main__.B.A\" is not valid as a type \\\n                         # N: Perhaps you need \"Callable[...]\" or a callback protocol?\n        return A\n\nclass C:\n    @final\n    @staticmethod\n    def A() -> Type[A]:\n        return A\n\n[builtins fixtures/staticmethod.pyi]\n\n[case testRefMethodWithOverloadDecorator]\nfrom typing import Type, overload\n\nclass A:\n    pass\n\nclass B:\n    @classmethod\n    @overload\n    def A(cls, x: int) -> Type[A]: ...\n    @classmethod\n    @overload\n    def A(cls, x: str) -> Type[A]: ...\n    @classmethod\n    def A(cls, x: object) -> Type[A]: ...\n    def B(cls, x: int) -> Type[A]: ...  # E: Function \"__main__.B.A\" is not valid as a type \\\n                                        # N: Perhaps you need \"Callable[...]\" or a callback protocol?\n\n[builtins fixtures/classmethod.pyi]\n\n[case testFinalClassWithAbstractAttributes]\nfrom abc import abstractmethod, ABCMeta\nfrom typing import final\n\n@final\nclass A(metaclass=ABCMeta):  # E: Final class __main__.A has abstract attributes \"bar\", \"foo\"\n    @abstractmethod\n    def foo(self):\n        pass\n\n    @property\n    @abstractmethod\n    def bar(self):\n        pass\n\n[builtins fixtures/property.pyi]\n\n[case testFinalClassWithoutABCMeta]\nfrom abc import abstractmethod\nfrom typing import final\n\n@final\nclass A():  # E: Final class __main__.A has abstract attributes \"bar\", \"foo\"\n    @abstractmethod\n    def foo(self):\n        pass\n\n    @property\n    @abstractmethod\n    def bar(self):\n        pass\n\n[builtins fixtures/property.pyi]\n\n[case testFinalClassInheritedAbstractAttributes]\nfrom abc import abstractmethod, ABCMeta\nfrom typing import final\n\nclass A(metaclass=ABCMeta):\n    @abstractmethod\n    def foo(self):\n        pass\n\n@final\nclass B(A):  # E: Final class __main__.B has abstract attributes \"foo\"\n    pass\n\n[case testUndefinedBaseclassInNestedClass]\nclass C:\n    class C1(XX): pass  # E: Name \"XX\" is not defined\n\n[case testArgsKwargsInheritance]\nfrom typing import Any\n\nclass A(object):\n    def f(self, *args: Any, **kwargs: Any) -> int: ...\n\nclass B(A):\n    def f(self, x: int) -> int: ...\n[builtins fixtures/dict.pyi]\n\n[case testClassScopeImports]\nclass Foo:\n    from mod import plain_function  # E: Unsupported class scoped import\n    from mod import plain_var\n\nreveal_type(Foo.plain_function)  # N: Revealed type is \"Any\"\nreveal_type(Foo().plain_function)  # N: Revealed type is \"Any\"\n\nreveal_type(Foo.plain_var)  # N: Revealed type is \"builtins.int\"\nreveal_type(Foo().plain_var)  # N: Revealed type is \"builtins.int\"\n\n[file mod.py]\ndef plain_function(x: int, y: int) -> int: ...\nplain_var: int\n\n[case testClassScopeImportModule]\nclass Foo:\n    import mod\n\nreveal_type(Foo.mod)  # N: Revealed type is \"builtins.object\"\nreveal_type(Foo.mod.foo)  # N: Revealed type is \"builtins.int\"\n[file mod.py]\nfoo: int\n\n[case testClassScopeImportAlias]\nclass Foo:\n    from mod import function  # E: Unsupported class scoped import\n    foo = function\n\n    from mod import var1\n    bar = var1\n\n    from mod import var2\n    baz = var2\n\n    from mod import var3\n    qux = var3\n\nreveal_type(Foo.foo)  # N: Revealed type is \"Any\"\nreveal_type(Foo.function)  # N: Revealed type is \"Any\"\n\nreveal_type(Foo.bar)  # N: Revealed type is \"builtins.int\"\nreveal_type(Foo.var1)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(Foo.baz)  # N: Revealed type is \"mod.C\"\nreveal_type(Foo.var2)  # N: Revealed type is \"mod.C\"\n\nreveal_type(Foo.qux)  # N: Revealed type is \"builtins.int\"\nreveal_type(Foo.var3)  # N: Revealed type is \"builtins.int\"\n\n[file mod.py]\ndef function(x: int, y: int) -> int: ...\nvar1: int\n\nclass C: ...\nvar2: C\n\nA = int\nvar3: A\n\n\n[case testClassScopeImportModuleStar]\nclass Foo:\n    from mod import *  # E: Unsupported class scoped import\n\nreveal_type(Foo.foo)  # N: Revealed type is \"builtins.int\"\nreveal_type(Foo.bar)  # N: Revealed type is \"Any\"\nreveal_type(Foo.baz)  # E: \"type[Foo]\" has no attribute \"baz\" \\\n                      # N: Revealed type is \"Any\"\n\n[file mod.py]\nfoo: int\ndef bar(x: int) -> int: ...\n\n[case testClassScopeImportAccessibleInMethods]\nclass A:\n    import mod\n    from mod import var\n\n    def __new__(cls) -> \"A\":\n        reveal_type(cls.mod)  # N: Revealed type is \"types.ModuleType\"\n        reveal_type(cls.var)  # N: Revealed type is \"builtins.int\"\n        reveal_type(cls.mod.var)  # N: Revealed type is \"builtins.int\"\n        return cls()\n\n    def pos_or_named_self(self) -> None:\n        reveal_type(self.mod)  # N: Revealed type is \"types.ModuleType\"\n        reveal_type(self.var)  # N: Revealed type is \"builtins.int\"\n        reveal_type(self.mod.var)  # N: Revealed type is \"builtins.int\"\n\n    def pos_only_self(self, /) -> None:\n        reveal_type(self.mod)  # N: Revealed type is \"types.ModuleType\"\n        reveal_type(self.var)  # N: Revealed type is \"builtins.int\"\n        reveal_type(self.mod.var)  # N: Revealed type is \"builtins.int\"\n\n    @classmethod\n    def clsmethod(cls) -> None:\n        reveal_type(cls.mod)  # N: Revealed type is \"types.ModuleType\"\n        reveal_type(cls.var)  # N: Revealed type is \"builtins.int\"\n        reveal_type(cls.mod.var)  # N: Revealed type is \"builtins.int\"\n\n[file mod.py]\nvar = 1\n[builtins fixtures/module.pyi]\n\n[case testClassScopeImportFunctionNested]\nclass Foo:\n    class Bar:\n        from mod import baz  # E: Unsupported class scoped import\n\nreveal_type(Foo.Bar.baz)  # N: Revealed type is \"Any\"\nreveal_type(Foo.Bar().baz)  # N: Revealed type is \"Any\"\n\n[file mod.py]\ndef baz(x: int) -> int: ...\n\n[case testClassScopeImportUndefined]\nclass Foo:\n    from unknown import foo  # E: Cannot find implementation or library stub for module named \"unknown\" \\\n                             # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\nreveal_type(Foo.foo)  # N: Revealed type is \"Any\"\nreveal_type(Foo().foo)  # N: Revealed type is \"Any\"\n\n[case testClassScopeImportWithFollowImports]\n# flags: --follow-imports=skip\nclass Foo:\n    from mod import foo\n\nreveal_type(Foo().foo)  # N: Revealed type is \"Any\"\n[file mod.py]\ndef foo(x: int, y: int) -> int: ...\n\n[case testClassScopeImportVarious]\nclass Foo:\n    from mod1 import foo  # E: Unsupported class scoped import\n    from mod2 import foo\n\n    from mod1 import meth1  # E: Unsupported class scoped import\n    def meth1(self, a: str) -> str: ...  # E: Name \"meth1\" already defined on line 5\n\n    def meth2(self, a: str) -> str: ...\n    from mod1 import meth2  # E: Incompatible import of \"meth2\" (imported name has type \"Callable[[int], int]\", local name has type \"Callable[[Foo, str], str]\")\n\nclass Bar:\n    from mod1 import foo  # E: Unsupported class scoped import\n\nimport mod1\nreveal_type(Foo.foo)  # N: Revealed type is \"Any\"\nreveal_type(Bar.foo)  # N: Revealed type is \"Any\"\nreveal_type(mod1.foo)  # N: Revealed type is \"def (x: builtins.int, y: builtins.int) -> builtins.int\"\n\n[file mod1.py]\ndef foo(x: int, y: int) -> int: ...\ndef meth1(x: int) -> int: ...\ndef meth2(x: int) -> int: ...\n[file mod2.py]\ndef foo(z: str) -> int: ...\n\n\n[case testClassScopeImportWithError]\nclass Foo:\n    from mod import meth1  # E: Unsupported class scoped import\n    from mod import meth2  # E: Unsupported class scoped import\n    from mod import T\n\nreveal_type(Foo.T)  # N: Revealed type is \"typing.TypeVar\"\n\n[file mod.pyi]\nfrom typing import Any, TypeVar, overload\n\n@overload\ndef meth1(self: Any, y: int) -> int: ...\n@overload\ndef meth1(self: Any, y: str) -> str: ...\n\nT = TypeVar(\"T\")\ndef meth2(self: Any, y: T) -> T: ...\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testNewAndInitNoReturn]\nfrom typing import NoReturn\n\nclass A:\n    def __new__(cls) -> NoReturn: ...\n\nclass B:\n    def __init__(self) -> NoReturn: ...\n\nclass C:\n    def __new__(cls) -> \"C\": ...\n    def __init__(self) -> NoReturn: ...\n\nclass D:\n    def __new__(cls) -> NoReturn: ...\n    def __init__(self) -> NoReturn: ...\n\nif object():\n    reveal_type(A())  # N: Revealed type is \"Never\"\nif object():\n    reveal_type(B())  # N: Revealed type is \"Never\"\nif object():\n    reveal_type(C())  # N: Revealed type is \"Never\"\nif object():\n    reveal_type(D())  # N: Revealed type is \"Never\"\n\n[case testOverloadedNewAndInitNoReturn]\nfrom typing import NoReturn, overload\n\nclass A:\n    @overload\n    def __new__(cls) -> NoReturn: ...\n    @overload\n    def __new__(cls, a: int) -> \"A\": ...\n    def __new__(cls, a: int = ...) -> \"A\": ...\n\nclass B:\n    @overload\n    def __init__(self) -> NoReturn: ...\n    @overload\n    def __init__(self, a: int) -> None: ...\n    def __init__(self, a: int = ...) -> None: ...\n\nclass C:\n    def __new__(cls, a: int = ...) -> \"C\": ...\n    @overload\n    def __init__(self) -> NoReturn: ...\n    @overload\n    def __init__(self, a: int) -> None: ...\n    def __init__(self, a: int = ...) -> None: ...\n\nclass D:\n    @overload\n    def __new__(cls) -> NoReturn: ...\n    @overload\n    def __new__(cls, a: int) -> \"D\": ...\n    def __new__(cls, a: int = ...) -> \"D\": ...\n    @overload\n    def __init__(self) -> NoReturn: ...\n    @overload\n    def __init__(self, a: int) -> None: ...\n    def __init__(self, a: int = ...) -> None: ...\n\nif object():\n    reveal_type(A())  # N: Revealed type is \"Never\"\nreveal_type(A(1))  # N: Revealed type is \"__main__.A\"\n\nif object():\n    reveal_type(B())  # N: Revealed type is \"Never\"\nreveal_type(B(1))  # N: Revealed type is \"__main__.B\"\n\nif object():\n    reveal_type(C())  # N: Revealed type is \"Never\"\nreveal_type(C(1))  # N: Revealed type is \"__main__.C\"\n\nif object():\n    reveal_type(D())  # N: Revealed type is \"Never\"\nreveal_type(D(1))  # N: Revealed type is \"__main__.D\"\n\n[case testClassScopeImportWithWrapperAndError]\nclass Foo:\n    from mod import foo # E: Unsupported class scoped import\n\n[file mod.py]\nfrom typing import Any, Callable, TypeVar\n\nFuncT = TypeVar(\"FuncT\", bound=Callable[..., Any])\ndef identity_wrapper(func: FuncT) -> FuncT:\n    return func\n\n@identity_wrapper\ndef foo(self: Any) -> str:\n    return \"\"\n\n[case testParentClassWithTypeAliasAndSubclassWithMethod]\nfrom typing import Any, Callable, TypeVar\n\nclass Parent:\n    foo = Callable[..., int]\n    class bar:\n        pass\n    import typing as baz\n    foobar = TypeVar(\"foobar\")\n\nclass Child(Parent):\n    def foo(self, val: int) -> int:  # E: Signature of \"foo\" incompatible with supertype \"Parent\" \\\n                                     # N:      Superclass: \\\n                                     # N:          <typing special form> \\\n                                     # N:      Subclass: \\\n                                     # N:          def foo(self, val: int) -> int\n        return val\n    def bar(self, val: str) -> str:  # E: Signature of \"bar\" incompatible with supertype \"Parent\" \\\n                                     # N:      Superclass: \\\n                                     # N:          def bar() -> bar \\\n                                     # N:      Subclass: \\\n                                     # N:          def bar(self, val: str) -> str\n        return val\n    def baz(self, val: float) -> float:  # E: Signature of \"baz\" incompatible with supertype \"Parent\" \\\n                                         # N:      Superclass: \\\n                                         # N:          Module \\\n                                         # N:      Subclass: \\\n                                         # N:          def baz(self, val: float) -> float\n        return val\n    def foobar(self) -> bool:  # E: Signature of \"foobar\" incompatible with supertype \"Parent\" \\\n                               # N:      Superclass: \\\n                               # N:          TypeVar \\\n                               # N:      Subclass: \\\n                               # N:          def foobar(self) -> bool\n        return False\n\nx: Parent.foo = lambda: 5\ny: Parent.bar = Parent.bar()\nz: Parent.baz.Any = 1\nchild = Child()\na: int = child.foo(1)\nb: str = child.bar(\"abc\")\nc: float = child.baz(3.4)\nd: bool = child.foobar()\n[builtins fixtures/module.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testGenericTupleTypeCreation]\nfrom typing import Generic, Tuple, TypeVar\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nclass C(Tuple[T, S]):\n    def __init__(self, x: T, y: S) -> None: ...\n    def foo(self, arg: T) -> S: ...\n\ncis: C[int, str]\nreveal_type(cis)  # N: Revealed type is \"tuple[builtins.int, builtins.str, fallback=__main__.C[builtins.int, builtins.str]]\"\ncii = C(0, 1)\nreveal_type(cii)  # N: Revealed type is \"tuple[builtins.int, builtins.int, fallback=__main__.C[builtins.int, builtins.int]]\"\nreveal_type(cis.foo)  # N: Revealed type is \"def (arg: builtins.int) -> builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testGenericTupleTypeSubclassing]\nfrom typing import Generic, Tuple, TypeVar, List\n\nT = TypeVar(\"T\")\nclass C(Tuple[T, T]): ...\nclass D(C[List[T]]): ...\n\ndi: D[int]\nreveal_type(di)  # N: Revealed type is \"tuple[builtins.list[builtins.int], builtins.list[builtins.int], fallback=__main__.D[builtins.int]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testOverrideAttrWithSettableProperty]\nclass Foo:\n    def __init__(self) -> None:\n        self.x = 42\n\nclass Bar(Foo):\n    @property\n    def x(self) -> int: ...\n    @x.setter\n    def x(self, value: int) -> None: ...\n[builtins fixtures/property.pyi]\n\n[case testOverrideAttrWithSettablePropertyAnnotation]\nclass Foo:\n    x: int\n\nclass Bar(Foo):\n    @property\n    def x(self) -> int: ...\n    @x.setter\n    def x(self, value: int) -> None: ...\n[builtins fixtures/property.pyi]\n\n[case testOverridePropertyDifferentSetterBoth]\nclass B: ...\nclass C(B): ...\n\nclass B1:\n    @property\n    def foo(self) -> str: ...\n    @foo.setter\n    def foo(self, x: C) -> None: ...\nclass C1(B1):\n    @property\n    def foo(self) -> str: ...\n    @foo.setter\n    def foo(self, x: B) -> None: ...\n\nclass B2:\n    @property\n    def foo(self) -> str: ...\n    @foo.setter\n    def foo(self, x: B) -> None: ...\nclass C2(B2):\n    @property\n    def foo(self) -> str: ...\n    @foo.setter  # E: Incompatible override of a setter type \\\n                 # N:  (base class \"B2\" defined the type as \"B\", \\\n                 # N:  override has type \"C\") \\\n                 # N:  Setter types should behave contravariantly\n    def foo(self, x: C) -> None: ...\n\nclass B3:\n    @property\n    def foo(self) -> C: ...\n    @foo.setter\n    def foo(self, x: C) -> None: ...\nclass C3(B3):\n    @property\n    def foo(self) -> C: ...\n    @foo.setter\n    def foo(self, x: B) -> None: ...\n\nclass B4:\n    @property\n    def foo(self) -> C: ...\n    @foo.setter\n    def foo(self, x: B) -> None: ...\nclass C4(B4):\n    @property\n    def foo(self) -> C: ...\n    @foo.setter  # E: Incompatible override of a setter type \\\n                 # N:  (base class \"B4\" defined the type as \"B\", \\\n                 # N:  override has type \"C\") \\\n                 # N:  Setter types should behave contravariantly\n    def foo(self, x: C) -> None: ...\n\nclass B5:\n    @property\n    def foo(self) -> str: ...\n    @foo.setter\n    def foo(self, x: B) -> None: ...\nclass C5(B5):\n    @property  # E: Signature of \"foo\" incompatible with supertype \"B5\" \\\n               # N:      Superclass: \\\n               # N:          str \\\n               # N:      Subclass: \\\n               # N:          C\n    def foo(self) -> C: ...\n    @foo.setter  # E: Incompatible override of a setter type \\\n                 # N:  (base class \"B5\" defined the type as \"B\", \\\n                 # N:  override has type \"str\")\n    def foo(self, x: str) -> None: ...\n\nclass B6:\n    @property\n    def foo(self) -> B: ...\n    @foo.setter\n    def foo(self, x: B) -> None: ...\nclass C6(B6):\n    @property\n    def foo(self) -> C: ...\n    @foo.setter\n    def foo(self, x: B) -> None: ...\n[builtins fixtures/property.pyi]\n\n[case testOverridePropertyDifferentSetterVarSuper]\nclass B: ...\nclass C(B): ...\n\nclass B1:\n    foo: B\nclass C1(B1):\n    @property\n    def foo(self) -> B: ...\n    @foo.setter  # E: Incompatible override of a setter type \\\n                 # N:  (base class \"B1\" defined the type as \"B\", \\\n                 # N:  override has type \"C\") \\\n                 # N:  Setter types should behave contravariantly\n    def foo(self, x: C) -> None: ...\n\nclass B2:\n    foo: C\nclass C2(B2):\n    @property\n    def foo(self) -> C: ...\n    @foo.setter\n    def foo(self, x: B) -> None: ...\n\nclass B3:\n    foo: B\nclass C3(B3):\n    @property\n    def foo(self) -> C: ...\n    @foo.setter\n    def foo(self, x: B) -> None: ...\n[builtins fixtures/property.pyi]\n\n[case testOverridePropertyDifferentSetterVarSub]\nclass B: ...\nclass C(B): ...\n\nclass B1:\n    @property\n    def foo(self) -> B: ...\n    @foo.setter\n    def foo(self, x: C) -> None: ...\nclass C1(B1):\n    foo: C\n\nclass B2:\n    @property\n    def foo(self) -> B: ...\n    @foo.setter\n    def foo(self, x: C) -> None: ...\nclass C2(B2):\n    foo: B\n\nclass B3:\n    @property\n    def foo(self) -> C: ...\n    @foo.setter\n    def foo(self, x: B) -> None: ...\nclass C3(B3):\n    foo: C  # E: Incompatible override of a setter type \\\n            # N:  (base class \"B3\" defined the type as \"B\", \\\n            # N:  override has type \"C\") \\\n            # N:  Setter types should behave contravariantly\n[builtins fixtures/property.pyi]\n\n[case testOverridePropertyInvalidSetter]\nclass B1:\n    @property\n    def foo(self) -> int: ...\n    @foo.setter\n    def foo(self, x: str) -> None: ...\nclass C1(B1):\n    @property\n    def foo(self) -> int: ...\n    @foo.setter\n    def foo(self) -> None: ...  # E: Invalid property setter signature\n\nclass B2:\n    @property\n    def foo(self) -> int: ...\n    @foo.setter\n    def foo(self) -> None: ...  # E: Invalid property setter signature\nclass C2(B2):\n    @property\n    def foo(self) -> int: ...\n    @foo.setter\n    def foo(self, x: str) -> None: ...\n\nclass B3:\n    @property\n    def foo(self) -> int: ...\n    @foo.setter\n    def foo(self) -> None: ...  # E: Invalid property setter signature\nclass C3(B3):\n    foo: int\n[builtins fixtures/property.pyi]\n\n[case testOverridePropertyGeneric]\nfrom typing import TypeVar, Generic\n\nT = TypeVar(\"T\")\n\nclass B1(Generic[T]):\n    @property\n    def foo(self) -> int: ...\n    @foo.setter\n    def foo(self, x: T) -> None: ...\nclass C1(B1[str]):\n    @property\n    def foo(self) -> int: ...\n    @foo.setter  # E: Incompatible override of a setter type \\\n                 # N:  (base class \"B1\" defined the type as \"str\", \\\n                 # N:  override has type \"int\")\n    def foo(self, x: int) -> None: ...\n\nclass B2:\n    @property\n    def foo(self) -> int: ...\n    @foo.setter\n    def foo(self: T, x: T) -> None: ...\nclass C2(B2):\n    @property\n    def foo(self) -> int: ...\n    @foo.setter  # E: Incompatible override of a setter type \\\n                 # N:  (base class \"B2\" defined the type as \"C2\", \\\n                 # N:  override has type \"int\")\n    def foo(self, x: int) -> None: ...\n[builtins fixtures/property.pyi]\n\n[case testOverrideMethodProperty]\nclass B:\n    def foo(self) -> int:\n        ...\nclass C(B):\n    @property\n    def foo(self) -> int:  # E: Signature of \"foo\" incompatible with supertype \"B\" \\\n                           # N:      Superclass: \\\n                           # N:          def foo(self) -> int \\\n                           # N:      Subclass: \\\n                           # N:          int\n        ...\n[builtins fixtures/property.pyi]\n\n[case testOverridePropertyMethod]\nclass B:\n    @property\n    def foo(self) -> int:\n        ...\nclass C(B):\n    def foo(self) -> int:  # E: Signature of \"foo\" incompatible with supertype \"B\" \\\n                           # N:      Superclass: \\\n                           # N:          int \\\n                           # N:      Subclass: \\\n                           # N:          def foo(self) -> int\n        ...\n[builtins fixtures/property.pyi]\n\n[case testAllowArgumentAsBaseClass]\nfrom typing import Any, Type\n\ndef e(b) -> None:\n    class D(b): ...\n\ndef f(b: Any) -> None:\n    class D(b): ...\n\ndef g(b: Type[Any]) -> None:\n    class D(b): ...\n\ndef h(b: type) -> None:\n    class D(b): ...\n\n[case testNoCrashOnSelfWithForwardRefGenericClass]\nfrom typing import Generic, Sequence, TypeVar, Self\n\n_T = TypeVar('_T', bound=\"Foo\")\n\nclass Foo:\n    foo: int\n\nclass Element(Generic[_T]):\n    elements: Sequence[Self]\n\nclass Bar(Foo): ...\ne: Element[Bar]\nreveal_type(e.elements)  # N: Revealed type is \"typing.Sequence[__main__.Element[__main__.Bar]]\"\n\n[case testIterableUnpackingWithGetAttr]\nfrom typing import Union, Tuple\n\nclass C:\n    def __getattr__(self, name):\n        pass\n\nclass D:\n    def f(self) -> C:\n        return C()\n\n    def g(self) -> None:\n        # iter(x) looks up `__iter__` on the type of x rather than x itself,\n        # so this is correct behaviour.\n        # Instances of C should not be treated as being iterable,\n        # despite having a __getattr__ method\n        # that could allow for arbitrary attributes to be accessed on instances,\n        # since `type(C()).__iter__` still raises AttributeError at runtime,\n        # and that's what matters.\n        a, b = self.f()  # E: \"C\" has no attribute \"__iter__\" (not iterable)\n[builtins fixtures/tuple.pyi]\n\n[case testUsingNumbersType]\nfrom numbers import Number, Complex, Real, Rational, Integral\n\ndef f1(x: Number) -> None: pass\nf1(1)  # E: Argument 1 to \"f1\" has incompatible type \"int\"; expected \"Number\" \\\n       # N: Types from \"numbers\" are not supported for static type checking \\\n       # N: See https://peps.python.org/pep-0484/#the-numeric-tower \\\n       # N: Consider using a protocol instead, such as typing.SupportsFloat\n\ndef f2(x: Complex) -> None: pass\nf2(1)  # E: Argument 1 to \"f2\" has incompatible type \"int\"; expected \"Complex\" \\\n       # N: Types from \"numbers\" are not supported for static type checking \\\n       # N: See https://peps.python.org/pep-0484/#the-numeric-tower \\\n       # N: Consider using a protocol instead, such as typing.SupportsFloat\n\ndef f3(x: Real) -> None: pass\nf3(1)  # E: Argument 1 to \"f3\" has incompatible type \"int\"; expected \"Real\" \\\n       # N: Types from \"numbers\" are not supported for static type checking \\\n       # N: See https://peps.python.org/pep-0484/#the-numeric-tower \\\n       # N: Consider using a protocol instead, such as typing.SupportsFloat\n\ndef f4(x: Rational) -> None: pass\nf4(1)  # E: Argument 1 to \"f4\" has incompatible type \"int\"; expected \"Rational\" \\\n       # N: Types from \"numbers\" are not supported for static type checking \\\n       # N: See https://peps.python.org/pep-0484/#the-numeric-tower \\\n       # N: Consider using a protocol instead, such as typing.SupportsFloat\n\ndef f5(x: Integral) -> None: pass\nf5(1)  # E: Argument 1 to \"f5\" has incompatible type \"int\"; expected \"Integral\" \\\n       # N: Types from \"numbers\" are not supported for static type checking \\\n       # N: See https://peps.python.org/pep-0484/#the-numeric-tower \\\n       # N: Consider using a protocol instead, such as typing.SupportsFloat\n\n[case testImplicitClassScopedNames]\nclass C:\n    reveal_type(__module__)  # N: Revealed type is \"builtins.str\"\n    reveal_type(__qualname__)  # N: Revealed type is \"builtins.str\"\n    def f(self) -> None:\n        __module__  # E: Name \"__module__\" is not defined\n        __qualname__  # E: Name \"__qualname__\" is not defined\n\n    x: __module__  # E: Variable \"__main__.C.__module__\" is not valid as a type \\\n                   # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n    y: __qualname__  # E: Variable \"__main__.C.__qualname__\" is not valid as a type \\\n                     # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n\n[case testPropertySetterType]\nclass A:\n    @property\n    def f(self) -> int:\n        return 1\n    @f.setter\n    def f(self, x: str) -> None:\n        pass\na = A()\na.f = ''  # OK\nreveal_type(a.f)  # N: Revealed type is \"builtins.int\"\na.f = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nreveal_type(a.f)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/property.pyi]\n\n[case testPropertySetterTypeGeneric]\nfrom typing import TypeVar, Generic, List\n\nT = TypeVar(\"T\")\n\nclass B(Generic[T]):\n    @property\n    def foo(self) -> int: ...\n    @foo.setter\n    def foo(self, x: T) -> None: ...\n\nclass C(B[List[T]]): ...\n\na = C[str]()\na.foo = [\"foo\", \"bar\"]\nreveal_type(a.foo)  # N: Revealed type is \"builtins.int\"\na.foo = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"list[str]\")\nreveal_type(a.foo)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/property.pyi]\n\n[case testPropertyDeleterNoSetterOK]\nclass C:\n    @property\n    def x(self) -> int:\n        return 0\n    @x.deleter\n    def x(self) -> None:\n        pass\n[builtins fixtures/property.pyi]\n\n[case testPropertySetterSuperclassDeferred]\nfrom typing import Callable, TypeVar\n\nclass B:\n    def __init__(self) -> None:\n        self.foo = f()\n\nclass C(B):\n    @property\n    def foo(self) -> str: ...\n    @foo.setter  # E: Incompatible override of a setter type \\\n                 # N:  (base class \"B\" defined the type as \"str\", \\\n                 # N:  override has type \"int\")\n    def foo(self, x: int) -> None: ...\n\nT = TypeVar(\"T\")\ndef deco(fn: Callable[[], list[T]]) -> Callable[[], T]: ...\n\n@deco\ndef f() -> list[str]: ...\n[builtins fixtures/property.pyi]\n\n[case testPropertySetterSuperclassDeferred2]\nimport a\n[file a.py]\nimport b\nclass D(b.C):\n    @property\n    def foo(self) -> str: ...\n    @foo.setter  # E: Incompatible override of a setter type \\\n                 # N:  (base class \"C\" defined the type as \"str\", \\\n                 # N:  override has type \"int\")\n    def foo(self, x: int) -> None: ...\n[file b.py]\nfrom a import D\nclass C:\n    @property\n    def foo(self) -> str: ...\n    @foo.setter\n    def foo(self, x: str) -> None: ...\n[builtins fixtures/property.pyi]\n\n[case testPropertySetterDecorated]\nfrom typing import Callable, TypeVar, Generic\n\nclass B:\n    def __init__(self) -> None:\n        self.foo: str\n        self.bar: int\n\nclass C(B):\n    @property\n    def foo(self) -> str: ...\n    @foo.setter  # E: Incompatible override of a setter type \\\n                 # N:  (base class \"B\" defined the type as \"str\", \\\n                 # N:  override has type \"int\")\n    @deco\n    def foo(self, x: int, y: int) -> None: ...\n\n    @property\n    def bar(self) -> int: ...\n    @bar.setter\n    @deco\n    def bar(self, x: int, y: int) -> None: ...\n\n    @property\n    def baz(self) -> int: ...\n    @baz.setter\n    @deco_untyped\n    def baz(self, x: int) -> None: ...\n\n    @property\n    def tricky(self) -> int: ...\n    @tricky.setter\n    @deco_instance\n    def tricky(self, x: int) -> None: ...\n\nc: C\nc.baz = \"yes\"  # OK, because of untyped decorator\nc.tricky = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"list[int]\")\n\nT = TypeVar(\"T\")\ndef deco(fn: Callable[[T, int, int], None]) -> Callable[[T, int], None]: ...\ndef deco_untyped(fn): ...\n\nclass Wrapper(Generic[T]):\n    def __call__(self, s: T, x: list[int]) -> None: ...\ndef deco_instance(fn: Callable[[T, int], None]) -> Wrapper[T]: ...\n[builtins fixtures/property.pyi]\n\n[case testPropertyDeleterBodyChecked]\nclass C:\n    @property\n    def foo(self) -> int: ...\n    @foo.deleter\n    def foo(self) -> None:\n        1()  # E: \"int\" not callable\n\n    @property\n    def bar(self) -> int: ...\n    @bar.setter\n    def bar(self, x: str) -> None: ...\n    @bar.deleter\n    def bar(self) -> None:\n        1()  # E: \"int\" not callable\n[builtins fixtures/property.pyi]\n\n[case testSettablePropertyGetterDecorated]\nfrom typing import Callable, TypeVar, Generic\n\nclass C:\n    @property\n    @deco\n    def foo(self, ok: int) -> str: ...\n    @foo.setter\n    def foo(self, x: str) -> None: ...\n\n    @property\n    @deco_instance\n    def bar(self, ok: int) -> int: ...\n    @bar.setter\n    def bar(self, x: int) -> None: ...\n\n    @property\n    @deco_untyped\n    def baz(self) -> int: ...\n    @baz.setter\n    def baz(self, x: int) -> None: ...\n\nc: C\nreveal_type(c.foo)  # N: Revealed type is \"builtins.list[builtins.str]\"\nreveal_type(c.bar)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(c.baz)  # N: Revealed type is \"Any\"\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\ndef deco(fn: Callable[[T, int], R]) -> Callable[[T], list[R]]: ...\ndef deco_untyped(fn): ...\n\nclass Wrapper(Generic[T, R]):\n    def __call__(self, s: T) -> list[R]: ...\ndef deco_instance(fn: Callable[[T, int], R]) -> Wrapper[T, R]: ...\n[builtins fixtures/property.pyi]\n\n[case testOverridePropertyWithDescriptor]\nfrom typing import Any\n\nclass StrProperty:\n    def __get__(self, instance: Any, owner: Any) -> str: ...\n\nclass Base:\n    @property\n    def id(self) -> str: ...\n\nclass BadBase:\n    @property\n    def id(self) -> int: ...\n\nclass Derived(Base):\n    id = StrProperty()\n\nclass BadDerived(BadBase):\n    id = StrProperty()  # E: Incompatible types in assignment (expression has type \"str\", base class \"BadBase\" defined the type as \"int\")\n[builtins fixtures/property.pyi]\n\n[case testLambdaInOverrideInference]\nclass B:\n    def f(self, x: int) -> int: ...\nclass C(B):\n    f = lambda s, x: x\n\nreveal_type(C().f)  # N: Revealed type is \"def (x: builtins.int) -> builtins.int\"\n\n[case testGenericDecoratorInOverrideInference]\nfrom typing import Any, Callable, TypeVar\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\ndef wrap(f: Callable[Concatenate[Any, P], T]) -> Callable[Concatenate[Any, P], T]: ...\n\nclass Base:\n    def g(self, a: int) -> int:\n        return a + 1\n\nclass Derived(Base):\n    def _g(self, a: int) -> int:\n        return a + 2\n    g = wrap(_g)\n\nreveal_type(Derived().g)  # N: Revealed type is \"def (a: builtins.int) -> builtins.int\"\n[builtins fixtures/paramspec.pyi]\n\n[case testClassVarOverrideWithSubclass]\nclass A: ...\nclass B(A): ...\nclass AA:\n    cls = A\nclass BB(AA):\n    cls = B\n\n[case testSelfReferenceWithinMethodFunction]\nclass B:\n    x: str\nclass C(B):\n    def meth(self) -> None:\n        def cb() -> None:\n            self.x: int = 1  # E: Incompatible types in assignment (expression has type \"int\", base class \"B\" defined the type as \"str\")\n\n[case testOverloadedDescriptorSelected]\nfrom typing import Generic, TypeVar, Any, overload\n\nT_co = TypeVar(\"T_co\", covariant=True)\nclass Field(Generic[T_co]):\n    @overload\n    def __get__(self: Field[bool], instance: None, owner: Any) -> BoolField: ...\n    @overload\n    def __get__(self: Field[int], instance: None, owner: Any) -> NumField: ...\n    @overload\n    def __get__(self: Field[Any], instance: None, owner: Any) -> AnyField[T_co]: ...\n    @overload\n    def __get__(self, instance: Any, owner: Any) -> T_co: ...\n\n    def __get__(self, instance: Any, owner: Any) -> Any:\n        pass\n\nclass BoolField(Field[bool]): ...\nclass NumField(Field[int]): ...\nclass AnyField(Field[T_co]): ...\nclass Custom: ...\n\nclass Fields:\n    bool_f: Field[bool]\n    int_f: Field[int]\n    custom_f: Field[Custom]\n\nreveal_type(Fields.bool_f)  # N: Revealed type is \"__main__.BoolField\"\nreveal_type(Fields.int_f)  # N: Revealed type is \"__main__.NumField\"\nreveal_type(Fields.custom_f)  # N: Revealed type is \"__main__.AnyField[__main__.Custom]\"\n\n[case testRecursivePropertyWithInvalidSetterNoCrash]\nclass NoopPowerResource:\n    _hardware_type: int\n\n    @property\n    def hardware_type(self) -> int:\n        return self._hardware_type\n\n    @hardware_type.setter\n    def hardware_type(self) -> None:  # E: Invalid property setter signature\n        self.hardware_type = None  # Note: intentionally recursive\n[builtins fixtures/property.pyi]\n\n[case testOverrideErrorReportingNoDuplicates]\nfrom typing import Callable, TypeVar\n\ndef nested() -> None:\n    class B:\n        def meth(self, x: str) -> int: ...\n    class C(B):\n        def meth(self) -> str:  # E: Signature of \"meth\" incompatible with supertype \"B\" \\\n                # N:      Superclass: \\\n                # N:          def meth(self, x: str) -> int \\\n                # N:      Subclass: \\\n                # N:          def meth(self) -> str\n            pass\n    x = defer()\n\nT = TypeVar(\"T\")\ndef deco(fn: Callable[[], T]) -> Callable[[], list[T]]: ...\n\n@deco\ndef defer() -> int: ...\n[builtins fixtures/list.pyi]\n\n[case testPropertyAllowsDeleterBeforeSetter]\nclass C:\n    @property\n    def foo(self) -> str: ...\n    @foo.deleter\n    def foo(self) -> None: ...\n    @foo.setter\n    def foo(self, val: int) -> None: ...\n\n    @property\n    def bar(self) -> int: ...\n    @bar.deleter\n    def bar(self) -> None: ...\n    @bar.setter\n    def bar(self, value: int, val: int) -> None: ...  # E: Invalid property setter signature\n\nC().foo = \"no\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nC().bar = \"fine\"\n[builtins fixtures/property.pyi]\n\n[case testCorrectConstructorTypeWithAnyFallback]\nfrom typing import Generic, TypeVar\n\nclass B(Unknown):  # type: ignore\n    def __init__(self) -> None: ...\nclass C(B): ...\n\nreveal_type(C)  # N: Revealed type is \"def () -> __main__.C\"\n\nT = TypeVar(\"T\")\nclass BG(Generic[T], Unknown):  # type: ignore\n    def __init__(self) -> None: ...\nclass CGI(BG[int]): ...\nclass CGT(BG[T]): ...\n\nreveal_type(CGI)  # N: Revealed type is \"def () -> __main__.CGI\"\nreveal_type(CGT)  # N: Revealed type is \"def [T] () -> __main__.CGT[T`1]\"\n\n[case testSettablePropertyAlias]\nfrom typing import Any, TypeVar\n\nclass A:\n    @property\n    def prop(self: Any) -> str: ...\n    @prop.setter\n    def prop(self, val: str) -> None: ...\n\nT = TypeVar(\"T\")\nclass AT:\n    @property\n    def prop(self: T) -> T: ...\n    @prop.setter\n    def prop(self: T, val: list[T]) -> None: ...\n\nclass B:\n    prop: str\n    prop_t: str\n\nclass C(B):\n    prop = A.prop\n    prop_t = AT.prop  # E: Incompatible types in assignment (expression has type \"C\", base class \"B\" defined the type as \"str\")\n\nreveal_type(C().prop)  # N: Revealed type is \"builtins.str\"\nC().prop = \"no\"  # E: Invalid self argument \"C\" to attribute function \"prop\" with type \"Callable[[A, str], None]\"\nreveal_type(C().prop_t)  # N: Revealed type is \"__main__.C\"\nC().prop_t = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"list[C]\")\n[builtins fixtures/property.pyi]\n\n[case testClassEqDecoratedAbstractNote]\nfrom abc import abstractmethod\n\nclass C:\n    @abstractmethod\n    def __eq__(self, other: C) -> bool: ...\n[builtins fixtures/plugin_attrs.pyi]\n[out]\nmain:5: error: Argument 1 of \"__eq__\" is incompatible with supertype \"builtins.object\"; supertype defines the argument type as \"object\"\nmain:5: note: This violates the Liskov substitution principle\nmain:5: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\nmain:5: note: It is recommended for \"__eq__\" to work with arbitrary objects, for example:\nmain:5: note:     def __eq__(self, other: object) -> bool:\nmain:5: note:         if not isinstance(other, C):\nmain:5: note:             return NotImplemented\nmain:5: note:         return <logic to compare two C instances>\n\n[case testLambdaInAttributeCallValue]\n# https://github.com/python/mypy/issues/19632\nimport foo\n\ndef nop(fn: object) -> foo.Bar:\n    return foo.Bar()\n\nclass Bar:\n    foo: foo.Bar = nop(\n        lambda: 0\n    )\n[file foo.py]\nclass Bar:\n    ...\n\n[case testConstructorWithoutStrictOptionalNoCache]\nimport mod\na = mod.NT(x=None)  # OK\n\n[file typ.py]\nfrom typing import NamedTuple, Optional\nNT = NamedTuple(\"NT\", [(\"x\", Optional[str])])\n\n[file mod.py]\n# mypy: no-strict-optional\nfrom typ import NT\n\ndef f() -> NT:\n    return NT(x='')\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-classvar.test",
    "content": "[case testAssignmentOnClass]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\nA.x = 2\n\n[case testAssignmentOnInstance]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\nA().x = 2\n[out]\nmain:4: error: Cannot assign to class variable \"x\" via instance\n\n[case testAssignmentOnSubclassInstance]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\nclass B(A):\n    pass\nB().x = 2\n[out]\nmain:6: error: Cannot assign to class variable \"x\" via instance\n\n[case testOverrideOnSelf]\nfrom typing import ClassVar\nclass A:\n    x: ClassVar[int]\n    def __init__(self) -> None:\n        self.x = 0\n[out]\nmain:5: error: Cannot assign to class variable \"x\" via instance\n\n[case testOverrideOnSelfInSubclass]\nfrom typing import ClassVar\nclass A:\n    x: ClassVar[int]\nclass B(A):\n    def __init__(self) -> None:\n        self.x = 0\n[out]\nmain:6: error: Cannot assign to class variable \"x\" via instance\n\n[case testReadingFromInstance]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\nA().x\nreveal_type(A().x)\n[out]\nmain:5: note: Revealed type is \"builtins.int\"\n\n[case testReadingFromSelf]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\n    def __init__(self) -> None:\n        reveal_type(self.x)\n[out]\nmain:5: note: Revealed type is \"builtins.int\"\n\n[case testTypecheckSimple]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\ny = A.x  # type: int\n\n[case testTypecheckWithUserType]\nfrom typing import ClassVar\nclass A:\n    pass\nclass B:\n    x = A()  # type: ClassVar[A]\n\n[case testTypeCheckOnAssignment]\nfrom typing import ClassVar\nclass A:\n    pass\nclass B:\n    pass\nclass C:\n    x: ClassVar[A]\nC.x = B()\n[out]\nmain:8: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\n[case testTypeCheckWithOverridden]\nfrom typing import ClassVar\nclass A:\n    pass\nclass B(A):\n    pass\nclass C:\n    x = A()  # type: ClassVar[A]\nC.x = B()\n\n[case testRevealType]\nfrom typing import ClassVar\nclass A:\n    x: ClassVar[int]\nreveal_type(A.x)\n[out]\nmain:4: note: Revealed type is \"builtins.int\"\n\n[case testInfer]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\ny = A.x\nreveal_type(y)\n[out]\nmain:5: note: Revealed type is \"builtins.int\"\n\n[case testAssignmentOnUnion]\nfrom typing import ClassVar, Union\nclass A:\n    x: int\nclass B:\n    x: ClassVar[int]\nc = A()  # type: Union[A, B]\nc.x = 1\n[out]\nmain:7: error: Cannot assign to class variable \"x\" via instance\n\n[case testAssignmentOnInstanceFromType]\nfrom typing import ClassVar, Type\nclass A:\n    x: ClassVar[int]\ndef f(a: Type[A]) -> None:\n    a().x = 0\n[out]\nmain:5: error: Cannot assign to class variable \"x\" via instance\n\n[case testAssignmentOnInstanceFromSubclassType]\nfrom typing import ClassVar, Type\nclass A:\n    x: ClassVar[int]\nclass B(A):\n    pass\ndef f(b: Type[B]) -> None:\n    b().x = 0\n[out]\nmain:7: error: Cannot assign to class variable \"x\" via instance\n\n[case testClassVarWithList]\nfrom typing import ClassVar, List\nclass A:\n    x: ClassVar[List[int]]\nA.x = ['a']\nA().x.append(1)\nA().x.append('')\n[builtins fixtures/list.pyi]\n[out]\nmain:4: error: List item 0 has incompatible type \"str\"; expected \"int\"\nmain:6: error: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\n\n[case testClassVarWithUnion]\nfrom typing import ClassVar, Union\nclass A:\n    x: ClassVar[Union[int, str]]\nclass B:\n    pass\nA.x = 0\nA.x = 'a'\nA.x = B()\nreveal_type(A().x)\n[out]\nmain:8: error: Incompatible types in assignment (expression has type \"B\", variable has type \"int | str\")\nmain:9: note: Revealed type is \"builtins.int | builtins.str\"\n\n[case testOverrideWithNarrowedUnion]\nfrom typing import ClassVar, Union\nclass A: pass\nclass B: pass\nclass C: pass\nclass D:\n    x: ClassVar[Union[A, B, C]]\nclass E(D):\n    x: ClassVar[Union[A, B]]\n\n[case testOverrideWithExtendedUnion]\nfrom typing import ClassVar, Union\nclass A: pass\nclass B: pass\nclass C: pass\nclass D:\n    x: ClassVar[Union[A, B]]\nclass E(D):\n    x: ClassVar[Union[A, B, C]]\n[out]\nmain:8: error: Incompatible types in assignment (expression has type \"A | B | C\", base class \"D\" defined the type as \"A | B\")\n\n[case testAssignmentToCallableRet]\nfrom typing import ClassVar\nclass A:\n    x: ClassVar[int]\ndef f() -> A:\n    return A()\nf().x = 0\n[out]\nmain:6: error: Cannot assign to class variable \"x\" via instance\n\n[case testOverrideWithIncompatibleType]\nfrom typing import ClassVar\nclass A:\n    x: ClassVar[int]\nclass B(A):\n    x: ClassVar[str]\n[out]\nmain:5: error: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\n\n[case testOverrideWithNormalAttribute]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\nclass B(A):\n    x = 2  # type: int\n[out]\nmain:5: error: Cannot override class variable (previously declared on base class \"A\") with instance variable\n\n[case testOverrideWithAttributeWithClassVar]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: int\nclass B(A):\n    x = 2  # type: ClassVar[int]\n[out]\nmain:5: error: Cannot override instance variable (previously declared on base class \"A\") with class variable\n\n[case testOverrideClassVarManyBases]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\nclass B:\n    x = 2  # type: int\nclass C(A, B):\n    x = 3  # type: ClassVar[int]\n[out]\nmain:7: error: Cannot override instance variable (previously declared on base class \"B\") with class variable\n\n[case testOverrideClassVarWithClassVar]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\nclass B(A):\n    x = 2  # type: ClassVar[int]\n\n[case testOverrideClassVarWithImplicitClassVar]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\nclass B(A):\n    x = 2\n\n[case testOverrideClassVarWithImplicitThenExplicit]\nfrom typing import ClassVar\nclass A:\n    x = 1  # type: ClassVar[int]\nclass B(A):\n    x = 2\nclass C(B):\n    x = 3  # type: ClassVar[int]\n\n[case testOverrideOnABCSubclass]\nfrom abc import ABCMeta\nfrom typing import ClassVar\nclass A(metaclass=ABCMeta):\n    x: ClassVar[int]\nclass B(A):\n    x = 0  # type: ClassVar[int]\n\n[case testAcrossModules]\nimport m\nreveal_type(m.A().x)\nm.A().x = 0\n[file m.py]\nfrom typing import ClassVar\nclass A:\n    x: ClassVar[int]\n[out]\nmain:2: note: Revealed type is \"builtins.int\"\nmain:3: error: Cannot assign to class variable \"x\" via instance\n\n[case testClassVarWithGeneric]\nfrom typing import ClassVar, Generic, TypeVar\nT = TypeVar('T')\nclass A(Generic[T]):\n    x: ClassVar[T]  # Error reported at access site\n    @classmethod\n    def foo(cls) -> T:\n        return cls.x  # OK\n\nA.x  # E: Access to generic class variables is ambiguous\nA.x = 1  # E: Access to generic class variables is ambiguous\nA[int].x  # E: Access to generic class variables is ambiguous\n\nclass Bad(A[int]):\n    pass\nBad.x  # E: Access to generic class variables is ambiguous\n\nclass Good(A[int]):\n    x = 42\nreveal_type(Good.x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testClassVarWithNestedGeneric]\nfrom typing import ClassVar, Generic, Tuple, TypeVar, Union, Type\nT = TypeVar('T')\nU = TypeVar('U')\nclass A(Generic[T, U]):\n    x: ClassVar[Union[T, Tuple[U, Type[U]]]]  # Error reported at access site\n    @classmethod\n    def foo(cls) -> Union[T, Tuple[U, Type[U]]]:\n        return cls.x  # OK\n\nA.x  # E: Access to generic class variables is ambiguous\nA.x = 1  # E: Access to generic class variables is ambiguous\nA[int, str].x  # E: Access to generic class variables is ambiguous\n\nclass Bad(A[int, str]):\n    pass\nreveal_type(Bad.x)  # E: Access to generic class variables is ambiguous \\\n                    # N: Revealed type is \"builtins.int | tuple[builtins.str, type[builtins.str]]\"\nreveal_type(Bad().x)  # N: Revealed type is \"builtins.int | tuple[builtins.str, type[builtins.str]]\"\n\nclass Good(A[int, str]):\n    x = 42\nreveal_type(Good.x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testSuggestClassVarOnTooFewArgumentsMethod]\nfrom typing import Callable\n\nclass C:\n    foo: Callable[[C], int]\nc:C\nc.foo()  # E: Too few arguments \\\n         # N: \"foo\" is considered instance variable, to make it class variable use ClassVar[...]\n\n[case testClassVarUnionBoundOnInstance]\nfrom typing import Union, Callable, ClassVar\n\nclass C:\n    def f(self) -> int: ...\n    g: ClassVar[Union[Callable[[C], int], int]] = f\n\nreveal_type(C().g)  # N: Revealed type is \"(def () -> builtins.int) | builtins.int\"\n\n[case testGenericSubclassAccessNoLeak]\nfrom typing import ClassVar, Generic, TypeVar\n\nT = TypeVar(\"T\")\nclass B(Generic[T]):\n    x: T\n    y: ClassVar[T]\n\nclass C(B[T]): ...\n\nreveal_type(C.x)  # E: Access to generic instance variables via class is ambiguous \\\n                  # N: Revealed type is \"Any\"\nreveal_type(C.y)  # E: Access to generic class variables is ambiguous \\\n                  # N: Revealed type is \"Any\"\n\n[case testClassVarBareAnnotation]\nfrom typing import ClassVar\n\nclass C:\n    x: ClassVar = 1\n    y: ClassVar\n\nreveal_type(C.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(C().x)  # N: Revealed type is \"builtins.int\"\nreveal_type(C.y)  # N: Revealed type is \"Any\"\nreveal_type(C().y)  # N: Revealed type is \"Any\"\n\n[case testClassVarBareAnnotationDisabled]\n# flags: --disallow-any-generics\nfrom typing import ClassVar\n\nclass C:\n    x: ClassVar = 1\n    y: ClassVar  # E: ClassVar without type argument becomes Any\n"
  },
  {
    "path": "test-data/unit/check-columns.test",
    "content": "# Test column numbers in messages. --show-column-numbers is enabled implicitly by test runner.\n\n[case testColumnsSyntaxError_no_native_parse]\nf()\n1 +\n[out]\nmain:2:5: error: Invalid syntax\n\n[case testColumnsNestedFunctions]\nimport typing\ndef f() -> 'A':\n    def g() -> 'B':\n        return A() # E:16: Incompatible return value type (got \"A\", expected \"B\")\n    return B() # E:12: Incompatible return value type (got \"B\", expected \"A\")\nclass A: pass\nclass B: pass\n\n[case testColumnsMethodDefaultArgumentsAndSignatureAsComment]\nimport typing\nclass A:\n    def f(self, x = 1, y = 'hello'): # type: (int, str) -> str\n        pass\nA().f()\nA().f(1)\nA().f('') # E:7: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\nA().f(1, 1) # E:10: Argument 2 to \"f\" of \"A\" has incompatible type \"int\"; expected \"str\"\n(A().f(1, 'hello', 'hi')) # E:2: Too many arguments for \"f\" of \"A\"\n\n[case testColumnsInvalidArgumentType]\ndef f(x: int, y: str) -> None: ...\ndef g(*x: int) -> None: pass\ndef h(**x: int) -> None: pass\ndef ff(x: int) -> None: pass\n\nclass A:\n    x: str\n    def __neg__(self) -> str: pass\n    def __add__(self, other: int) -> str: pass\n    def __lt__(self, other: int) -> str: pass\n\nf(\n y=0, x=0) # E:4: Argument \"y\" to \"f\" has incompatible type \"int\"; expected \"str\"\nf(x=0,\n   y=None) # E:6: Argument \"y\" to \"f\" has incompatible type \"None\"; expected \"str\"\ng(1, '', 2) # E:6: Argument 2 to \"g\" has incompatible type \"str\"; expected \"int\"\naaa: str\nh(x=1, y=aaa, z=2) # E:10: Argument \"y\" to \"h\" has incompatible type \"str\"; expected \"int\"\na: A\nff(a.x) # E:4: Argument 1 to \"ff\" has incompatible type \"str\"; expected \"int\"\nff([1]) # E:4: Argument 1 to \"ff\" has incompatible type \"list[int]\"; expected \"int\"\n# TODO: Different column in Python 3.8+\n#ff([1 for x in [1]]) # Argument 1 to \"ff\" has incompatible type \"list[int]\"; expected \"int\"\nff({1: 2}) # E:4: Argument 1 to \"ff\" has incompatible type \"dict[int, int]\"; expected \"int\"\nff(1.1) # E:4: Argument 1 to \"ff\" has incompatible type \"float\"; expected \"int\"\n# TODO: Different column in Python 3.8+\n#ff( ( 1, 1)) # Argument 1 to \"ff\" has incompatible type \"tuple[int, int]\"; expected \"int\"\nff(-a) # E:4: Argument 1 to \"ff\" has incompatible type \"str\"; expected \"int\"\nff(a + 1) # E:4: Argument 1 to \"ff\" has incompatible type \"str\"; expected \"int\"\nff(a < 1) # E:4: Argument 1 to \"ff\" has incompatible type \"str\"; expected \"int\"\nff([''][0]) # E:4: Argument 1 to \"ff\" has incompatible type \"str\"; expected \"int\"\n\nclass B(A):\n    def f(self) -> None:\n        ff(super().__neg__()) # E:12: Argument 1 to \"ff\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testColumnsInvalidArgumentTypeVarArgs]\ndef f(*x: int) -> None: pass\ndef g(**x: int) -> None: pass\n\na = ['']\nf(*a)  # E:4: Argument 1 to \"f\" has incompatible type \"*list[str]\"; expected \"int\"\nb = {'x': 'y'}\ng(**b) # E:5: Argument 1 to \"g\" has incompatible type \"**dict[str, str]\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testColumnsMultipleStatementsPerLine]\nx = 15\ny = 'hello'\nif int():\n    x = 2; y = x; y += 1\n[builtins fixtures/primitives.pyi]\n[out]\nmain:4:16: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nmain:4:24: error: Unsupported operand types for + (\"str\" and \"int\")\n\n[case testColumnsAssignment]\nclass A:\n    x = 0\n\nA().x = ''  # E:9: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\na = [0]\na[0] = ''  # E:8: Incompatible types in assignment (expression has type \"str\", target has type \"int\")\nb = 0\nc = 0\nb, c = 0, ''  # E:11: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nb, c = '', 0  # E:8: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\nt = 0, ''\nb, c = t  # E:8: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\nclass B(A):\n    x = ''  # E:9: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")\n[builtins fixtures/list.pyi]\n\n[case testColumnsAttributeIncompatibleWithBaseClassUsingAnnotation]\nclass A:\n    x: str\n\nclass B(A):\n    x: int  # E:5: Incompatible types in assignment (expression has type \"int\", base class \"A\" defined the type as \"str\")\n\n[case testColumnsSimpleIsinstance]\nimport typing\ndef f(x: object, n: int, s: str) -> None:\n    if int():\n        n = x # E:13: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n        if isinstance(x, int):\n            n = x\n            s = x # E:17: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        n = x # E:13: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\n[builtins fixtures/isinstance.pyi]\n\n[case testColumnHasNoAttribute]\nimport m\nif int():\n    from m import foobaz # E:5: Module \"m\" has no attribute \"foobaz\"; maybe \"foobar\"?\n1 .x # E:1: \"int\" has no attribute \"x\"\n(m.foobaz()) # E:2: Module has no attribute \"foobaz\"; maybe \"foobar\"?\n\n[file m.py]\ndef foobar(): pass\n\n[builtins fixtures/module.pyi]\n\n[case testColumnUnexpectedOrMissingKeywordArg]\ndef f(): pass\n# TODO: Point to \"x\" instead\n(f(x=1)) # E:2: Unexpected keyword argument \"x\" for \"f\"\ndef g(*, x: int) -> None: pass\n(g())  # E:2: Missing named argument \"x\" for \"g\"\n\n[case testColumnDefinedHere]\nclass A: pass\nif int():\n    def f(a: 'A') -> None: pass\n    (f(b=object())) # E:6: Unexpected keyword argument \"b\" for \"f\"\n\n[case testColumnInvalidType_no_native_parse]\n\nfrom typing import Iterable\n\nbad = 0\n\ndef f(x: bad): # E:10: Variable \"__main__.bad\" is not valid as a type \\\n               # N:10: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n    y: bad # E:8: Variable \"__main__.bad\" is not valid as a type \\\n           # N:8: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n\nif int():\n    def g(x): # E:5: Variable \"__main__.bad\" is not valid as a type \\\n              # N:5: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n        # type: (bad) -> None\n        y = 0  # type: bad  # E:9: Variable \"__main__.bad\" is not valid as a type \\\n                            # N:9: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n\nz: Iterable[bad] # E:13: Variable \"__main__.bad\" is not valid as a type \\\n                 # N:13: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\nh: bad[int] # E:4: Variable \"__main__.bad\" is not valid as a type \\\n            # N:4: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n\n[case testColumnFunctionMissingTypeAnnotation]\n# flags: --disallow-untyped-defs\nif int():\n    def f(x: int): # E:5: Function is missing a return type annotation\n        pass\n\n    def g(x): # E:5: Function is missing a type annotation\n        pass\n\n[case testColumnNameIsNotDefined]\n((x)) # E:3: Name \"x\" is not defined\n\n[case testColumnNeedTypeAnnotation]\nif 1:\n    x = [] # E:5: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n[builtins fixtures/list.pyi]\n\n[case testColumnCallToUntypedFunction]\n# flags: --disallow-untyped-calls\ndef f() -> None:\n    (g(1))  # E:6: Call to untyped function \"g\" in typed context\n\ndef g(x):\n    pass\n\n[case testColumnInvalidArguments]\ndef f(x, y): pass\n(f()) # E:2: Missing positional arguments \"x\", \"y\" in call to \"f\"\n(f(y=1)) # E:2: Missing positional argument \"x\" in call to \"f\"\n\n[case testColumnListOrDictItemHasIncompatibleType]\nfrom typing import List, Dict\nx: List[int] = [\n    'x',  # E:5: List item 0 has incompatible type \"str\"; expected \"int\"\n      1.1]  # E:7: List item 1 has incompatible type \"float\"; expected \"int\"\ny: Dict[int, int] = {\n    'x': 1  # E:5: Dict entry 0 has incompatible type \"str\": \"int\"; expected \"int\": \"int\"\n}\n[builtins fixtures/dict.pyi]\n\n[case testColumnCannotDetermineType]\n# flags: --no-local-partial-types\n(x)  # E:2: Cannot determine type of \"x\"  # E:2: Name \"x\" is used before definition\nx = None\n\n[case testColumnInvalidIndexing]\nfrom typing import List\n([1]['']) # E:6: Invalid index type \"str\" for \"list[int]\"; expected type \"int\"\n(1[1]) # E:2: Value of type \"int\" is not indexable\ndef f() -> None:\n    1[1] = 1 # E:5: Unsupported target for indexed assignment (\"int\")\n[builtins fixtures/list.pyi]\n\n[case testColumnTypedDict]\nfrom typing import TypedDict\nclass D(TypedDict):\n    x: int\nt: D = {'x':\n    'y'} # E:5: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")\ns: str\n\nif int():\n    del t[s]    # E:11: Expected TypedDict key to be string literal\n    del t[\"x\"]  # E:11: Key \"x\" of TypedDict \"D\" cannot be deleted\n    del t[\"y\"]  # E:11: TypedDict \"D\" has no key \"y\"\n\nt.pop(s)    # E:7: Expected TypedDict key to be string literal\nt.pop(\"y\")  # E:7: TypedDict \"D\" has no key \"y\"\n\nt.setdefault(s, 123)    # E:14: Expected TypedDict key to be string literal\nt.setdefault(\"x\", \"a\")  # E:19: Argument 2 to \"setdefault\" of \"TypedDict\" has incompatible type \"str\"; expected \"int\"\nt.setdefault(\"y\", 123)  # E:14: TypedDict \"D\" has no key \"y\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testColumnSignatureIncompatibleWithSuperType]\nclass A:\n    def f(self, x: int) -> None: pass\nclass B(A):\n    def f(self, x: str) -> None: pass # E:17: Argument 1 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\" \\\n                                      # N:17: This violates the Liskov substitution principle \\\n                                      # N:17: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\nclass C(A):\n    def f(self, x: int) -> int: pass # E:5: Return type \"int\" of \"f\" incompatible with return type \"None\" in supertype \"A\"\nclass D(A):\n    def f(self) -> None: pass # E:5: Signature of \"f\" incompatible with supertype \"A\" \\\n                              # N:5:      Superclass: \\\n                              # N:5:          def f(self, x: int) -> None \\\n                              # N:5:      Subclass: \\\n                              # N:5:          def f(self) -> None\n\n[case testColumnMissingTypeParameters]\n# flags: --disallow-any-generics\nfrom typing import List, Callable\ndef f(x: List) -> None: pass # E:10: Missing type arguments for generic type \"List\"\ndef g(x: list) -> None: pass # E:10: Missing type arguments for generic type \"list\"\nif int():\n    c: Callable # E:8: Missing type arguments for generic type \"Callable\"\n[builtins fixtures/list.pyi]\n\n[case testColumnIncompatibleDefault]\nif int():\n    def f(x: int = '') -> None: # E:20: Incompatible default for parameter \"x\" (default has type \"str\", parameter has type \"int\")\n        pass\n\n[case testColumnMissingProtocolMember]\nfrom typing import Protocol\n\nclass P(Protocol):\n    x: int\n    y: int\n\nclass C:\n    x: int\n\np: P\nif int():\n    p = C() # E:9: Incompatible types in assignment (expression has type \"C\", variable has type \"P\") \\\n      # N:9: \"C\" is missing following \"P\" protocol member: \\\n      # N:9:     y\n\n[case testColumnRedundantCast]\n# flags: --warn-redundant-casts\nfrom typing import cast\ny = 1\nx = cast(int, y) # E:5: Redundant cast to \"int\"\n\n[case testColumnTypeSignatureHasTooFewArguments]\nif int():\n    def f(x, y): # E:5: Type signature has too few parameters\n        # type: (int) -> None\n        pass\n\n[case testColumnRevealedType]\nif int():\n    reveal_type(1) # N:17: Revealed type is \"Literal[1]?\"\n\n[case testColumnNonOverlappingEqualityCheck]\n# flags: --strict-equality\nif 1 == '': # E:4: Non-overlapping equality check (left operand type: \"Literal[1]\", right operand type: \"Literal['']\")\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testColumnValueOfTypeVariableCannotBe]\n\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T', int, str)\n\nclass C(Generic[T]):\n    pass\n\ndef f(c: C[object]) -> None: pass # E:12: Value of type variable \"T\" of \"C\" cannot be \"object\"\n(C[object]()) # E:2: Value of type variable \"T\" of \"C\" cannot be \"object\"\n\n[case testColumnInvalidLocationForParamSpec]\nfrom typing import List\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\ndef foo(x: List[P]): pass  # E:17: Invalid location for ParamSpec \"P\" \\\n                           # N:17: You can use ParamSpec as the first argument to Callable, e.g., \"Callable[P, int]\"\n[builtins fixtures/list.pyi]\n\n[case testColumnSyntaxErrorInTypeAnnotation]\nif int():\n    def f(x # type: int,\n          ):\n        pass\n[out]\nmain:2:11: error: Syntax error in type annotation\nmain:2:11: note: Suggestion: Is there a spurious trailing comma?\n\n[case testColumnSyntaxErrorInTypeAnnotation2_no_native_parse]\nif int():\n    # TODO: It would be better to point to the type comment\n    xyz = 0  # type: blurbnard blarb\n[out]\nmain:3:5: error: Syntax error in type comment \"blurbnard blarb\"\n\n[case testColumnProperty]\nclass A:\n    @property\n    def x(self) -> int: pass\n\n    @x.setter\n    def x(self, x: int) -> None: pass\n\nclass B(A):\n    @property  # E:6: Read-only property cannot override read-write property\n    def x(self) -> int: pass\n[builtins fixtures/property.pyi]\n\n[case testColumnOverloaded]\nfrom typing import overload, Any\nclass A:\n    @overload # E:6: An overloaded function outside a stub file must have an implementation\n    def f(self, x: int) -> int: pass\n    @overload\n    def f(self, x: str) -> str: pass\n\n[case testColumnFunctionWithTypeVarValues]\nfrom typing import TypeVar, List\n\nT = TypeVar('T', int, str)\n\ndef g(x): pass\n\ndef f(x: T) -> T:\n    (x.bad) # E:6: \"int\" has no attribute \"bad\" \\\n            # E:6: \"str\" has no attribute \"bad\"\n    g(y=x) # E:5: Unexpected keyword argument \"y\" for \"g\"\n    y: List[int, str] # E:8: \"list\" expects 1 type argument, but 2 given\n    del 1[0] # E:5: \"int\" has no attribute \"__delitem__\"\n    bb: List[int] = [''] # E:22: List item 0 has incompatible type \"str\"; expected \"int\"\n    aa: List[int] = ['' for x in [1]] # E:22: List comprehension has incompatible type List[str]; expected List[int]\n    cc = 1 .bad # E:10: \"int\" has no attribute \"bad\"\n    n: int = '' # E:14: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    return x\n[builtins fixtures/list.pyi]\n\n[case testColumnReturnValueExpected]\ndef f() -> int:\n    return  # E:5: Return value expected\n\n[case testCheckEndColumnPositions]\n# flags: --show-error-end\nx: int = \"no way\"\n\ndef g() -> int: ...\ndef f(x: str) -> None: ...\nf(g(\n))\nx[0]\n[out]\nmain:2:10:2:17: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nmain:6:3:7:1: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\nmain:8:1:8:4: error: Value of type \"int\" is not indexable\n\n[case testEndColumnsWithTooManyTypeVars]\n# flags: --pretty\nimport typing\n\nx1: typing.List[typing.List[int, int]]\nx2: list[list[int, int]]\n[out]\nmain:4:17: error: \"list\" expects 1 type argument, but 2 given\n    x1: typing.List[typing.List[int, int]]\n                    ^~~~~~~~~~~~~~~~~~~~~\nmain:5:10: error: \"list\" expects 1 type argument, but 2 given\n    x2: list[list[int, int]]\n             ^~~~~~~~~~~~~~\n"
  },
  {
    "path": "test-data/unit/check-ctypes.test",
    "content": "[case testCtypesArrayStandardElementType]\nimport ctypes\n\nclass MyCInt(ctypes.c_int):\n    pass\n\nintarr4 = ctypes.c_int * 4\na = intarr4(1, ctypes.c_int(2), MyCInt(3), 4)\nintarr4(1, 2, 3, \"invalid\")  # E: Array constructor argument 4 of type \"str\" is not convertible to the array element type \"c_int\"\nreveal_type(a)  # N: Revealed type is \"_ctypes.Array[ctypes.c_int]\"\nreveal_type(a[0])  # N: Revealed type is \"builtins.int\"\nreveal_type(a[1:3])  # N: Revealed type is \"builtins.list[builtins.int]\"\na[0] = 42\na[1] = ctypes.c_int(42)\na[2] = MyCInt(42)\na[3] = b\"bytes\"  # E: No overload variant of \"__setitem__\" of \"Array\" matches argument types \"int\", \"bytes\" \\\n                 # N: Possible overload variants: \\\n                 # N:     def __setitem__(self, int, c_int | int, /) -> None \\\n                 # N:     def __setitem__(self, slice, list[c_int | int], /) -> None\nfor x in a:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesArrayCustomElementType]\nimport ctypes\nfrom typing import Union, List\n\nclass MyCInt(ctypes.c_int):\n    pass\n\nmyintarr4 = MyCInt * 4\nmya = myintarr4(1, 2, MyCInt(3), 4)\nmyintarr4(1, ctypes.c_int(2), MyCInt(3), \"invalid\")  # E: Array constructor argument 2 of type \"c_int\" is not convertible to the array element type \"MyCInt\" \\\n                                                     # E: Array constructor argument 4 of type \"str\" is not convertible to the array element type \"MyCInt\"\nreveal_type(mya)  # N: Revealed type is \"_ctypes.Array[__main__.MyCInt]\"\nreveal_type(mya[0])  # N: Revealed type is \"__main__.MyCInt\"\nreveal_type(mya[1:3])  # N: Revealed type is \"builtins.list[__main__.MyCInt]\"\nmya[0] = 42\nmya[1] = ctypes.c_int(42)  # E: No overload variant of \"__setitem__\" of \"Array\" matches argument types \"int\", \"c_int\" \\\n                           # N: Possible overload variants: \\\n                           # N:     def __setitem__(self, int, MyCInt | int, /) -> None \\\n                           # N:     def __setitem__(self, slice, list[MyCInt | int], /) -> None\nmya[2] = MyCInt(42)\nmya[3] = b\"bytes\"  # E: No overload variant of \"__setitem__\" of \"Array\" matches argument types \"int\", \"bytes\" \\\n                   # N: Possible overload variants: \\\n                   # N:     def __setitem__(self, int, MyCInt | int, /) -> None \\\n                   # N:     def __setitem__(self, slice, list[MyCInt | int], /) -> None\nfor myx in mya:\n    reveal_type(myx)  # N: Revealed type is \"__main__.MyCInt\"\n\nmyu: Union[ctypes.Array[ctypes.c_int], List[str]]\nfor myi in myu:\n    reveal_type(myi)  # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesArrayUnionElementType]\nimport ctypes\nfrom typing import Union\n\nclass MyCInt(ctypes.c_int):\n    pass\n\nmya: ctypes.Array[Union[MyCInt, ctypes.c_uint]]\nreveal_type(mya)  # N: Revealed type is \"_ctypes.Array[__main__.MyCInt | ctypes.c_uint]\"\nreveal_type(mya[0])  # N: Revealed type is \"__main__.MyCInt | builtins.int\"\nreveal_type(mya[1:3])  # N: Revealed type is \"builtins.list[__main__.MyCInt | builtins.int]\"\n# The behavior here is not strictly correct, but intentional.\n# See the comment in mypy.plugins.ctypes._autoconvertible_to_cdata for details.\nmya[0] = 42\nmya[1] = ctypes.c_uint(42)\nmya[2] = MyCInt(42)\nmya[3] = b\"bytes\"  # E: No overload variant of \"__setitem__\" of \"Array\" matches argument types \"int\", \"bytes\" \\\n                   # N: Possible overload variants: \\\n                   # N:     def __setitem__(self, int, MyCInt | int | c_uint, /) -> None \\\n                   # N:     def __setitem__(self, slice, list[MyCInt | int | c_uint], /) -> None\nfor myx in mya:\n    reveal_type(myx)  # N: Revealed type is \"__main__.MyCInt | builtins.int\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesCharArrayAttrs]\nimport ctypes\n\nca = (ctypes.c_char * 4)(b'a', b'b', b'c', b'\\x00')\nreveal_type(ca.value)  # N: Revealed type is \"builtins.bytes\"\nreveal_type(ca.raw)  # N: Revealed type is \"builtins.bytes\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesCharPArrayDoesNotCrash]\nimport ctypes\n\n# The following line used to crash with \"Could not find builtin symbol 'NoneType'\"\nca = (ctypes.c_char_p * 0)()\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesWcharArrayAttrs]\nimport ctypes\n\nwca = (ctypes.c_wchar * 4)('a', 'b', 'c', '\\x00')\nreveal_type(wca.value)  # N: Revealed type is \"builtins.str\"\nwca.raw  # E: Array attribute \"raw\" is only available with element type \"c_char\", not \"c_wchar\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesCharUnionArrayAttrs]\nimport ctypes\nfrom typing import Union\n\ncua: ctypes.Array[Union[ctypes.c_char, ctypes.c_wchar]]\nreveal_type(cua.value)  # N: Revealed type is \"builtins.bytes | builtins.str\"\ncua.raw  # E: Array attribute \"raw\" is only available with element type \"c_char\", not \"c_char | c_wchar\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesAnyUnionArrayAttrs]\nimport ctypes\nfrom typing import Any, Union\n\ncaa: ctypes.Array[Union[ctypes.c_char, Any]]\nreveal_type(caa.value)  # N: Revealed type is \"builtins.bytes | Any\"\nreveal_type(caa.raw)  # N: Revealed type is \"builtins.bytes\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesOtherUnionArrayAttrs]\nimport ctypes\nfrom typing import Union\n\ncua: ctypes.Array[Union[ctypes.c_char, ctypes.c_int]]\ncua.value  # E: Array attribute \"value\" is only available with element type \"c_char\" or \"c_wchar\", not \"c_char | c_int\"\ncua.raw  # E: Array attribute \"raw\" is only available with element type \"c_char\", not \"c_char | c_int\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesAnyArrayAttrs]\nimport ctypes\nfrom typing import Any\n\naa: ctypes.Array[Any]\nreveal_type(aa.value)  # N: Revealed type is \"Any\"\nreveal_type(aa.raw)  # N: Revealed type is \"builtins.bytes\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesOtherArrayAttrs]\nimport ctypes\n\noa = (ctypes.c_int * 4)(1, 2, 3, 4)\noa.value  # E: Array attribute \"value\" is only available with element type \"c_char\" or \"c_wchar\", not \"c_int\"\noa.raw  # E: Array attribute \"raw\" is only available with element type \"c_char\", not \"c_int\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesArrayConstructorStarargs]\nimport ctypes\n\nintarr4 = ctypes.c_int * 4\nintarr6 = ctypes.c_int * 6\nint_values = [1, 2, 3, 4]\nc_int_values = [ctypes.c_int(1), ctypes.c_int(2), ctypes.c_int(3), ctypes.c_int(4)]\nreveal_type(intarr4(*int_values))  # N: Revealed type is \"_ctypes.Array[ctypes.c_int]\"\nreveal_type(intarr4(*c_int_values))  # N: Revealed type is \"_ctypes.Array[ctypes.c_int]\"\nreveal_type(intarr6(1, ctypes.c_int(2), *int_values))  # N: Revealed type is \"_ctypes.Array[ctypes.c_int]\"\nreveal_type(intarr6(1, ctypes.c_int(2), *c_int_values))  # N: Revealed type is \"_ctypes.Array[ctypes.c_int]\"\n\nfloat_values = [1.0, 2.0, 3.0, 4.0]\nintarr4(*float_values) # E: Array constructor argument 1 of type \"list[float]\" is not convertible to the array element type \"Iterable[c_int]\"\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testCtypesArrayConstructorKwargs]\nimport ctypes\nintarr4 = ctypes.c_int * 4\n\nx = {\"a\": 1, \"b\": 2}\nintarr4(**x)\n\n[builtins fixtures/floatdict.pyi]\n[typing fixtures/typing-medium.pyi]\n"
  },
  {
    "path": "test-data/unit/check-custom-plugin.test",
    "content": "-- Test cases for user-defined plugins\n--\n-- Note: Plugins used by tests live under test-data/unit/plugins. Defining\n--       plugin files in test cases does not work reliably.\n\n[case testFunctionPluginFile]\n# flags: --config-file tmp/mypy.ini\ndef f() -> str: ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/fnplugin.py\n\n[case testFunctionPluginFilePyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\ndef f() -> str: ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\n[file pyproject.toml]\n\\[tool.mypy]\nplugins='<ROOT>/test-data/unit/plugins/fnplugin.py'\n\n[case testFunctionPlugin]\n# flags: --config-file tmp/mypy.ini\ndef f() -> str: ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\n[file mypy.ini]\n\\[mypy]\nplugins=fnplugin\n\n[case testFunctionPluginPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\ndef f() -> str: ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\n[file pyproject.toml]\n\\[tool.mypy]\nplugins = 'fnplugin'\n\n[case testFunctionPluginFullnameIsNotNone]\n# flags: --config-file tmp/mypy.ini\nfrom typing import Callable, TypeVar\nf: Callable[[], None]\nT = TypeVar('T')\ndef g(x: T) -> T: return x  # This strips out the name of a callable\ng(f)()\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/fnplugin.py\n\n[case testFunctionPluginFullnameIsNotNonePyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nfrom typing import Callable, TypeVar\nf: Callable[[], None]\nT = TypeVar('T')\ndef g(x: T) -> T: return x  # This strips out the name of a callable\ng(f)()\n[file pyproject.toml]\n\\[tool.mypy]\nplugins=\"<ROOT>/test-data/unit/plugins/fnplugin.py\"\n\n[case testTwoPlugins]\n# flags: --config-file tmp/mypy.ini\ndef f(): ...\ndef g(): ...\ndef h(): ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\nreveal_type(g())  # N: Revealed type is \"builtins.str\"\nreveal_type(h())  # N: Revealed type is \"Any\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/fnplugin.py,\n  <ROOT>/test-data/unit/plugins/plugin2.py\n\n[case testTwoPluginsPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\ndef f(): ...\ndef g(): ...\ndef h(): ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\nreveal_type(g())  # N: Revealed type is \"builtins.str\"\nreveal_type(h())  # N: Revealed type is \"Any\"\n[file pyproject.toml]\n\\[tool.mypy]\nplugins=['<ROOT>/test-data/unit/plugins/fnplugin.py',\n  '<ROOT>/test-data/unit/plugins/plugin2.py'\n]\n\n[case testTwoPluginsMixedType]\n# flags: --config-file tmp/mypy.ini\ndef f(): ...\ndef g(): ...\ndef h(): ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\nreveal_type(g())  # N: Revealed type is \"builtins.str\"\nreveal_type(h())  # N: Revealed type is \"Any\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/fnplugin.py, plugin2\n\n[case testTwoPluginsMixedTypePyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\ndef f(): ...\ndef g(): ...\ndef h(): ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\nreveal_type(g())  # N: Revealed type is \"builtins.str\"\nreveal_type(h())  # N: Revealed type is \"Any\"\n[file pyproject.toml]\n\\[tool.mypy]\nplugins=['<ROOT>/test-data/unit/plugins/fnplugin.py', 'plugin2']\n\n[case testMissingPluginFile]\n# flags: --config-file tmp/mypy.ini\n[file mypy.ini]\n\\[mypy]\nplugins=missing.py\n[out]\ntmp/mypy.ini:2: error: Can't find plugin \"tmp/missing.py\"\n--' (work around syntax highlighting)\n\n[case testMissingPlugin]\n# flags: --config-file tmp/mypy.ini\n[file mypy.ini]\n\\[mypy]\nplugins=missing\n[out]\ntmp/mypy.ini:2: error: Error importing plugin \"missing\": No module named 'missing'\n\n[case testMultipleSectionsDefinePlugin]\n# flags: --config-file tmp/mypy.ini\n[file mypy.ini]\n\\[acme]\nplugins=acmeplugin\n\\[mypy]\nplugins=missing.py\n\\[another]\nplugins=another_plugin\n[out]\ntmp/mypy.ini:4: error: Can't find plugin \"tmp/missing.py\"\n--' (work around syntax highlighting)\n\n[case testInvalidPluginExtension]\n# flags: --config-file tmp/mypy.ini\n[file mypy.ini]\n\\[mypy]\nplugins=dir/badext.pyi\n[file dir/badext.pyi]\n[out]\ntmp/mypy.ini:2: error: Plugin \"badext.pyi\" does not have a .py extension\n\n[case testMissingPluginEntryPoint]\n# flags: --config-file tmp/mypy.ini\n[file mypy.ini]\n\\[mypy]\n plugins = <ROOT>/test-data/unit/plugins/noentry.py\n[out]\ntmp/mypy.ini:2: error: Plugin \"<ROOT>/test-data/unit/plugins/noentry.py\" does not define entry point function \"plugin\"\n\n[case testCustomPluginEntryPointFile]\n# flags: --config-file tmp/mypy.ini\ndef f() -> str: ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/customentry.py:register\n\n[case testCustomPluginEntryPointFileTrailingComma]\n# flags: --config-file tmp/mypy.ini\ndef f() -> str: ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\n[file mypy.ini]\n\\[mypy]\nplugins =\n    <ROOT>/test-data/unit/plugins/customentry.py:register,\n\n[case testCustomPluginEntryPoint]\n# flags: --config-file tmp/mypy.ini\ndef f() -> str: ...\nreveal_type(f())  # N: Revealed type is \"builtins.int\"\n[file mypy.ini]\n\\[mypy]\nplugins=customentry:register\n\n[case testInvalidPluginEntryPointReturnValue]\n# flags: --config-file tmp/mypy.ini\ndef f(): pass\nf()\n[file mypy.ini]\n\\[mypy]\n\nplugins=<ROOT>/test-data/unit/plugins/badreturn.py\n[out]\ntmp/mypy.ini:3: error: Type object expected as the return value of \"plugin\"; got None (in <ROOT>/test-data/unit/plugins/badreturn.py)\n\n[case testInvalidPluginEntryPointReturnValue2]\n# flags: --config-file tmp/mypy.ini\ndef f(): pass\nf()\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/badreturn2.py\n[out]\ntmp/mypy.ini:2: error: Return value of \"plugin\" must be a subclass of \"mypy.plugin.Plugin\" (in <ROOT>/test-data/unit/plugins/badreturn2.py)\n\n[case testAttributeTypeHookPlugin]\n# flags: --config-file tmp/mypy.ini\nfrom typing import Callable\nfrom m import Signal, DerivedSignal\ns: Signal[Callable[[int], None]] = Signal()\ns(1)\ns('') # E: Argument 1 has incompatible type \"str\"; expected \"int\"\n\nds: DerivedSignal[Callable[[int], None]] = DerivedSignal()\nds('') # E: Argument 1 has incompatible type \"str\"; expected \"int\"\n[file m.py]\nfrom typing import TypeVar, Generic, Callable\nT = TypeVar('T', bound=Callable[..., None])\nclass Signal(Generic[T]):\n    __call__: Callable[..., None]  # This type is replaced by the plugin\n\nclass DerivedSignal(Signal[T]): ...\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/attrhook.py\n\n[case testAttributeTypeHookPluginUntypedDecoratedGetattr]\n# flags: --config-file tmp/mypy.ini\nfrom m import Magic, DerivedMagic\n\nmagic = Magic()\nreveal_type(magic.magic_field)  # N: Revealed type is \"builtins.str\"\nreveal_type(magic.non_magic_method())  # N: Revealed type is \"builtins.int\"\nreveal_type(magic.non_magic_field)  # N: Revealed type is \"builtins.int\"\nmagic.nonexistent_field  # E: Field does not exist\nreveal_type(magic.fallback_example)  # N: Revealed type is \"Any\"\nreveal_type(magic.no_assignment_field)  # N: Revealed type is \"builtins.float\"\nmagic.no_assignment_field = \"bad\"  # E: Cannot assign to field\n\nderived = DerivedMagic()\nreveal_type(derived.magic_field)  # N: Revealed type is \"builtins.str\"\nderived.nonexistent_field  # E: Field does not exist\nreveal_type(derived.fallback_example)  # N: Revealed type is \"Any\"\n\n[file m.py]\nfrom typing import Any, Callable\n\ndef decorator(f):\n    pass\n\nclass Magic:\n    # Triggers plugin infrastructure:\n    @decorator\n    def __getattr__(self, x: Any) -> Any: ...\n    def non_magic_method(self) -> int: ...\n    non_magic_field: int\n    no_assignment_field: float\n\nclass DerivedMagic(Magic): ...\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/attrhook2.py\n\n[case testAttributeTypeHookPluginDecoratedGetattr]\n# flags: --config-file tmp/mypy.ini\nfrom m import Magic, DerivedMagic\n\nmagic = Magic()\nreveal_type(magic.magic_field)  # N: Revealed type is \"builtins.str\"\nreveal_type(magic.non_magic_method())  # N: Revealed type is \"builtins.int\"\nreveal_type(magic.non_magic_field)  # N: Revealed type is \"builtins.int\"\nmagic.nonexistent_field  # E: Field does not exist\nreveal_type(magic.fallback_example)  # N: Revealed type is \"builtins.bool\"\n\nderived = DerivedMagic()\nreveal_type(derived.magic_field)  # N: Revealed type is \"builtins.str\"\nderived.nonexistent_field  # E: Field does not exist\nreveal_type(derived.fallback_example)  # N: Revealed type is \"builtins.bool\"\n\n[file m.py]\nfrom typing import Any, Callable\n\ndef decorator(f: Callable) -> Callable[[Any, str], bool]:\n    pass\n\nclass Magic:\n    # Triggers plugin infrastructure:\n    @decorator\n    def __getattr__(self, x: Any) -> Any: ...\n    def non_magic_method(self) -> int: ...\n    non_magic_field: int\n\nclass DerivedMagic(Magic): ...\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/attrhook2.py\n\n[case testAttributeHookPluginForDynamicClass]\n# flags: --config-file tmp/mypy.ini\nfrom m import Magic, DerivedMagic\n\nmagic = Magic()\nreveal_type(magic.magic_field)  # N: Revealed type is \"builtins.str\"\nreveal_type(magic.non_magic_method())  # N: Revealed type is \"builtins.int\"\nreveal_type(magic.non_magic_field)  # N: Revealed type is \"builtins.int\"\nmagic.nonexistent_field  # E: Field does not exist\nreveal_type(magic.fallback_example)  # N: Revealed type is \"Any\"\n\nderived = DerivedMagic()\nreveal_type(derived.magic_field)  # N: Revealed type is \"builtins.str\"\nderived.nonexistent_field  # E: Field does not exist\nreveal_type(magic.fallback_example)  # N: Revealed type is \"Any\"\n\n[file m.py]\nfrom typing import Any\nclass Magic:\n    # Triggers plugin infrastructure:\n    def __getattr__(self, x: Any) -> Any: ...\n    def non_magic_method(self) -> int: ...\n    non_magic_field: int\n\nclass DerivedMagic(Magic): ...\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/attrhook2.py\n\n[case testTypeAnalyzeHookPlugin]\n# flags: --config-file tmp/mypy.ini\nfrom typing import Callable\nfrom mypy_extensions import DefaultArg\nfrom m import Signal\ns: Signal[[int, DefaultArg(str, 'x')]] = Signal()\nreveal_type(s) # N: Revealed type is \"m.Signal[def (builtins.int, x: builtins.str =)]\"\ns.x # E: \"Signal[Callable[[int, str], None]]\" has no attribute \"x\"\nss: Signal[int, str] # E: Invalid \"Signal\" type (expected \"Signal[[t, ...]]\")\n[file m.py]\nfrom typing import TypeVar, Generic, Callable\nT = TypeVar('T', bound=Callable[..., None])\nclass Signal(Generic[T]):\n    __call__: Callable[..., None]\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/type_anal_hook.py\n[builtins fixtures/dict.pyi]\n\n[case testFunctionPluginHookForClass]\n# flags: --config-file tmp/mypy.ini\nimport mod\nfrom mod import AttrInt\n\nAlias = AttrInt\nAnotherAlias = mod.Attr\n\nclass C:\n    x = Alias()\n    y = mod.AttrInt(required=True)\n    z = AnotherAlias(int, required=False)\n\nc = C()\nreveal_type(c.x)  # N: Revealed type is \"builtins.int | None\"\nreveal_type(c.y)  # N: Revealed type is \"builtins.int\"\nreveal_type(c.z)  # N: Revealed type is \"builtins.int | None\"\n\n[file mod.py]\nfrom typing import Generic, TypeVar, Type\nT = TypeVar('T')\n\nclass Attr(Generic[T]):\n    def __init__(self, tp: Type[T], required: bool = False) -> None:\n        pass\n    def __get__(self, instance: object, owner: type) -> T:\n        pass\n\nclass AttrInt(Attr[int]):\n    def __init__(self, required: bool = False) -> None:\n        pass\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/class_callable.py\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testFunctionPluginHookForReturnedCallable]\n# flags: --config-file tmp/mypy.ini\nfrom m import decorator1, decorator2\n@decorator1()\ndef f() -> None: pass\n@decorator2()\ndef g() -> None: pass\nreveal_type(f) # N: Revealed type is \"def (*Any, **Any) -> builtins.str\"\nreveal_type(g) # N: Revealed type is \"def (*Any, **Any) -> builtins.int\"\n[file m.py]\nfrom typing import Callable\ndef decorator1() -> Callable[..., Callable[..., int]]: pass\ndef decorator2() -> Callable[..., Callable[..., int]]: pass\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/named_callable.py\n\n[case testFunctionMethodContextsHasArgNames]\n# flags: --config-file tmp/mypy.ini\nfrom mod import Class, func\n\nreveal_type(Class().method(arg1=1, arg2=2, classname='builtins.str'))  # N: Revealed type is \"builtins.str\"\nreveal_type(Class.myclassmethod(arg1=1, arg2=2, classname='builtins.str'))  # N: Revealed type is \"builtins.str\"\nreveal_type(Class.mystaticmethod(arg1=1, arg2=2, classname='builtins.str'))  # N: Revealed type is \"builtins.str\"\nreveal_type(Class.method(self=Class(), arg1=1, arg2=2, classname='builtins.str'))  # N: Revealed type is \"builtins.str\"\nreveal_type(func(arg1=1, arg2=2, classname='builtins.str'))  # N: Revealed type is \"builtins.str\"\n\n[file mod.py]\nfrom typing import Any\nclass Class:\n    def method(self, classname: str, arg1: Any, arg2: Any) -> Any:\n        pass\n    @classmethod\n    def myclassmethod(cls, classname: str, arg1: Any, arg2: Any):\n        pass\n    @staticmethod\n    def mystaticmethod(classname: str, arg1: Any, arg2: Any):\n        pass\ndef func(classname: str, arg1: Any, arg2: Any) -> Any:\n    pass\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/arg_names.py\n[builtins fixtures/classmethod.pyi]\n\n[case testFunctionMethodContextsHasArgNamesPositionals]\n# flags: --config-file tmp/mypy.ini\nfrom mod import Class, func\n\nreveal_type(Class().method('builtins.str', arg1=1, arg2=2))  # N: Revealed type is \"builtins.str\"\nreveal_type(Class.myclassmethod('builtins.str', arg1=1, arg2=2))  # N: Revealed type is \"builtins.str\"\nreveal_type(Class.mystaticmethod('builtins.str', arg1=1, arg2=2))  # N: Revealed type is \"builtins.str\"\nreveal_type(Class.method(Class(), 'builtins.str', arg1=1, arg2=2))  # N: Revealed type is \"builtins.str\"\nreveal_type(func('builtins.str', arg1=1, arg2=2))  # N: Revealed type is \"builtins.str\"\n\n[file mod.py]\nfrom typing import Any\nclass Class:\n    def method(self, classname: str, arg1: Any, arg2: Any) -> Any:\n        pass\n    @classmethod\n    def myclassmethod(cls, classname: str, arg1: Any, arg2: Any):\n        pass\n    @staticmethod\n    def mystaticmethod(classname: str, arg1: Any, arg2: Any):\n        pass\ndef func(classname: str, arg1: Any, arg2: Any) -> Any:\n    pass\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/arg_names.py\n[builtins fixtures/classmethod.pyi]\n\n[case testFunctionMethodContextsHasArgNamesInitMethod]\n# flags: --config-file tmp/mypy.ini\nfrom mod import ClassInit, Outer\n\nreveal_type(ClassInit('builtins.str'))  # N: Revealed type is \"builtins.str\"\nreveal_type(ClassInit(classname='builtins.str'))  # N: Revealed type is \"builtins.str\"\nreveal_type(Outer.NestedClassInit(classname='builtins.str'))  # N: Revealed type is \"builtins.str\"\n[file mod.py]\nfrom typing import Any\nclass ClassInit:\n    def __init__(self, classname: str):\n        pass\nclass Outer:\n    class NestedClassInit:\n        def __init__(self, classname: str):\n            pass\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/arg_names.py\n\n[case testFunctionMethodContextsHasArgNamesUnfilledArguments]\n# flags: --config-file tmp/mypy.ini\nfrom mod import ClassUnfilled, func_unfilled\n\nreveal_type(ClassUnfilled().method(classname='builtins.str', arg1=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(ClassUnfilled().method(arg2=1, classname='builtins.str'))  # N: Revealed type is \"builtins.str\"\nreveal_type(ClassUnfilled().method('builtins.str'))  # N: Revealed type is \"builtins.str\"\nreveal_type(func_unfilled(classname='builtins.str', arg1=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(func_unfilled(arg2=1, classname='builtins.str'))  # N: Revealed type is \"builtins.str\"\nreveal_type(func_unfilled('builtins.str'))  # N: Revealed type is \"builtins.str\"\n\n[file mod.py]\nfrom typing import Any\nclass ClassUnfilled:\n    def method(self, classname: str, arg1: Any = None, arg2: Any = None) -> Any:\n        pass\ndef func_unfilled(classname: str, arg1: Any = None, arg2: Any = None) -> Any:\n    pass\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/arg_names.py\n\n[case testFunctionMethodContextsHasArgNamesStarExpressions]\n# flags: --config-file tmp/mypy.ini\nfrom mod import ClassStarExpr, func_star_expr\n\nreveal_type(ClassStarExpr().method(classname='builtins.str', arg1=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(ClassStarExpr().method('builtins.str', arg1=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(ClassStarExpr().method('builtins.str', arg1=1, arg2=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(ClassStarExpr().method('builtins.str', 2, 3, 4, arg1=1, arg2=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(func_star_expr(classname='builtins.str', arg1=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(func_star_expr('builtins.str', arg1=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(func_star_expr('builtins.str', 2, 3, 4, arg1=1, arg2=2))  # N: Revealed type is \"builtins.str\"\n\n[file mod.py]\nfrom typing import Any\nclass ClassStarExpr:\n    def method(self, classname: str, *args, **kwargs) -> Any:\n        pass\ndef func_star_expr(classname: str, *args, **kwargs) -> Any:\n    pass\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/arg_names.py\n[builtins fixtures/dict.pyi]\n\n[case testFunctionMethodContextArgNamesForInheritedMethods]\n# flags: --config-file tmp/mypy.ini\nfrom mod import ClassChild\n\nreveal_type(ClassChild().method(classname='builtins.str', arg1=1, arg2=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(ClassChild().method(arg1=1, classname='builtins.str', arg2=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(ClassChild().method('builtins.str', arg1=1, arg2=1))  # N: Revealed type is \"builtins.str\"\nreveal_type(ClassChild.myclassmethod('builtins.str'))  # N: Revealed type is \"builtins.str\"\n[file mod.py]\nfrom typing import Any\nclass Base:\n    def method(self, classname: str, arg1: Any, arg2: Any) -> Any:\n        pass\n    @classmethod\n    def myclassmethod(cls, classname: str) -> Any:\n        pass\nclass ClassChild(Base):\n    pass\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/arg_names.py\n[builtins fixtures/classmethod.pyi]\n\n[case testMethodSignatureHook]\n# flags: --config-file tmp/mypy.ini\nfrom typing import Iterator\n\nclass Foo:\n    # Test that method signature hooks are applied in various cases: explicit method calls, and\n    # implicit dunder method calls through language syntax.\n    # The plugin's method signature hook should turn all str occurrences into int.\n    def __init__(self) -> None: ...\n    def __getitem__(self, index: str) -> str: ...\n    def __setitem__(self, index: str, value: str) -> None: ...\n    def __iter__(self) -> Iterator[str]: ...\n    def __next__(self) -> str: ...\n    def __call__(self, *args: str) -> str: ...\n    def m(self, arg: str) -> str: ...\n\nfoo = Foo()\nreveal_type(foo.m(2)) # N: Revealed type is \"builtins.int\"\nreveal_type(foo[3]) # N: Revealed type is \"builtins.int\"\nreveal_type(foo(4, 5, 6)) # N: Revealed type is \"builtins.int\"\nfoo[4] = 5\nfor x in foo:\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/method_sig_hook.py\n[builtins fixtures/tuple.pyi]\n\n[case testMethodSignatureHookNamesFullyQualified]\n# flags: --config-file tmp/mypy.ini\nfrom typing import NamedTuple, TypedDict\n\nclass FullyQualifiedTestClass:\n    @classmethod\n    def class_method(self) -> str: ...\n    def instance_method(self) -> str: ...\n\nclass FullyQualifiedTestTypedDict(TypedDict):\n    foo: str\n\nFullyQualifiedTestNamedTuple = NamedTuple('FullyQualifiedTestNamedTuple', [('foo', str)])\n\n# Check the return types to ensure that the method signature hook is called in each case\nreveal_type(FullyQualifiedTestClass.class_method()) # N: Revealed type is \"builtins.int\"\nreveal_type(FullyQualifiedTestClass().instance_method()) # N: Revealed type is \"builtins.int\"\nreveal_type(FullyQualifiedTestNamedTuple('')._asdict()) # N: Revealed type is \"builtins.int\"\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/fully_qualified_test_hook.py\n[builtins fixtures/classmethod.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDynamicClassPlugin]\n# flags: --config-file tmp/mypy.ini\nfrom mod import declarative_base, Column, Instr\n\nBase = declarative_base()\n\nclass Model(Base):\n    x: Column[int]\nclass Other:\n    x: Column[int]\n\nreveal_type(Model().x)  # N: Revealed type is \"mod.Instr[builtins.int]\"\nreveal_type(Other().x)  # N: Revealed type is \"mod.Column[builtins.int]\"\n[file mod.py]\nfrom typing import Generic, TypeVar\ndef declarative_base(): ...\n\nT = TypeVar('T')\n\nclass Column(Generic[T]): ...\nclass Instr(Generic[T]): ...\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/dyn_class.py\n\n[case testDynamicClassPluginChainCall]\n# flags: --config-file tmp/mypy.ini\nfrom mod import declarative_base, Column, Instr\n\nBase = declarative_base().with_optional_xxx()\n\nclass Model(Base):\n    x: Column[int]\n\nreveal_type(Model().x)  # N: Revealed type is \"mod.Instr[builtins.int]\"\n[file mod.py]\nfrom typing import Generic, TypeVar\n\nclass Base:\n    def with_optional_xxx(self) -> Base: ...\n\ndef declarative_base() -> Base: ...\n\nT = TypeVar('T')\n\nclass Column(Generic[T]): ...\nclass Instr(Generic[T]): ...\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/dyn_class.py\n\n[case testDynamicClassPluginChainedAssignment]\n# flags: --config-file tmp/mypy.ini\nfrom mod import declarative_base\n\nBase1 = Base2 = declarative_base()\n\nclass C1(Base1): ...\nclass C2(Base2): ...\n[file mod.py]\ndef declarative_base(): ...\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/dyn_class.py\n\n[case testDynamicClassPluginNegatives]\n# flags: --config-file tmp/mypy.ini\nfrom mod import non_declarative_base\n\nBad1 = non_declarative_base()\n\nclass C1(Bad1): ...  # E: Variable \"__main__.Bad1\" is not valid as a type \\\n                     # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases \\\n                     # E: Invalid base class \"Bad1\"\n[file mod.py]\ndef non_declarative_base(): ...\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/dyn_class.py\n\n[case testDynamicClassHookFromClassMethod]\n# flags: --config-file tmp/mypy.ini\n\nfrom mod import QuerySet, Manager, GenericQuerySet\n\nMyManager = Manager.from_queryset(QuerySet)\nManagerFromGenericQuerySet = GenericQuerySet[int].as_manager()\n\nreveal_type(MyManager())  # N: Revealed type is \"__main__.MyManager\"\nreveal_type(MyManager().attr)  # N: Revealed type is \"builtins.str\"\nreveal_type(ManagerFromGenericQuerySet())  # N: Revealed type is \"__main__.ManagerFromGenericQuerySet\"\nreveal_type(ManagerFromGenericQuerySet().attr)  # N: Revealed type is \"builtins.int\"\nqueryset: GenericQuerySet[int] = ManagerFromGenericQuerySet()\n\ndef func(manager: MyManager) -> None:\n    reveal_type(manager)   # N: Revealed type is \"__main__.MyManager\"\n    reveal_type(manager.attr)   # N: Revealed type is \"builtins.str\"\n\nfunc(MyManager())\n\n[file mod.py]\nfrom typing import Generic, TypeVar, Type\nclass QuerySet:\n    attr: str\nclass Manager:\n    @classmethod\n    def from_queryset(cls, queryset_cls: Type[QuerySet]): ...\nT = TypeVar(\"T\")\nclass GenericQuerySet(Generic[T]):\n    attr: T\n\n    @classmethod\n    def as_manager(cls): ...\n\n[builtins fixtures/classmethod.pyi]\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/dyn_class_from_method.py\n\n[case testBaseClassPluginHookWorksIncremental]\n# flags: --config-file tmp/mypy.ini\nimport a\n\n[file a.py]\nfrom base import Base\nclass C(Base): ...\n\n[file a.py.2]\nfrom base import Base\nclass C(Base): ...\nreveal_type(C().__magic__)\nBase.__magic__\n\n[file base.py]\nfrom lib import declarative_base\nBase = declarative_base()\n\n[file lib.py]\nfrom typing import Any\ndef declarative_base() -> Any: ...\n\n[file mypy.ini]\n\\[mypy]\npython_version=3.6\nplugins=<ROOT>/test-data/unit/plugins/common_api_incremental.py\n[out]\n[out2]\ntmp/a.py:3: note: Revealed type is \"builtins.str\"\ntmp/a.py:4: error: \"type[Base]\" has no attribute \"__magic__\"\n\n[case testArgKindsMethod]\n# flags: --config-file tmp/mypy.ini\nclass Class:\n    def method(self, *args, **kwargs):\n        pass\n\nClass().method(1, *[2], **{'a': 1})  # E: [[0, 2], [4]]\n[builtins fixtures/dict.pyi]\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/arg_kinds.py\n\n[case testArgKindsFunction]\n# flags: --config-file tmp/mypy.ini\ndef func(*args, **kwargs):\n    pass\n\nfunc(1, 2, [3, 4], *[5, 6, 7], **{'a': 1})  # E: [[0, 0, 0, 2], [4]]\n[builtins fixtures/dict.pyi]\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/arg_kinds.py\n\n[case testHookCallableInstance]\n# flags: --config-file tmp/mypy.ini\nfrom typing import Generic, TypeVar\nT = TypeVar(\"T\")\nclass Class(Generic[T]):\n    def __init__(self, one: T): ...\n    def __call__(self, two: T) -> int: ...\nreveal_type(Class(\"hi\")(\"there\"))  # N: Revealed type is \"builtins.str\"\ninstance = Class(3.14)\nreveal_type(instance(2))  # N: Revealed type is \"builtins.float\"\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/callable_instance.py\n\n[case testGetMethodHooksOnUnions]\n# flags: --config-file tmp/mypy.ini --no-strict-optional\nfrom typing import Union\n\nclass Foo:\n    def meth(self, x: str) -> str: ...\nclass Bar:\n    def meth(self, x: int) -> float: ...\nclass Other:\n    meth: int\n\nx: Union[Foo, Bar, Other]\nif isinstance(x.meth, int):\n    reveal_type(x.meth)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x.meth(int()))  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/isinstancelist.pyi]\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/union_method.py\n\n[case testGetMethodHooksOnUnionsStrictOptional]\n# flags: --config-file tmp/mypy.ini\nfrom typing import Union\n\nclass Foo:\n    def meth(self, x: str) -> str: ...\nclass Bar:\n    def meth(self, x: int) -> float: ...\nclass Other:\n    meth: int\n\nx: Union[Foo, Bar, Other]\nif isinstance(x.meth, int):\n    reveal_type(x.meth)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x.meth(int()))  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/isinstancelist.pyi]\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/union_method.py\n\n[case testGetMethodHooksOnUnionsSpecial]\n# flags: --config-file tmp/mypy.ini\nfrom typing import Union\n\nclass Foo:\n    def __getitem__(self, x: str) -> str: ...\nclass Bar:\n    def __getitem__(self, x: int) -> float: ...\n\nx: Union[Foo, Bar]\nreveal_type(x[int()])  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/isinstancelist.pyi]\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/union_method.py\n\n[case testPluginDependencies]\n# flags: --config-file tmp/mypy.ini\n\n# The top level file here doesn't do anything, but the plugin should add\n# a dependency on err that will cause err to be processed and an error reported.\n\n[file err.py]\n1 + 'lol'  # E: Unsupported operand types for + (\"int\" and \"str\")\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/depshook.py\n\n[case testCustomizeMroTrivial]\n# flags: --config-file tmp/mypy.ini\nclass A: pass\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/customize_mro.py\n\n[case testDescriptorMethods]\n# flags: --config-file tmp/mypy.ini\n\nclass Desc:\n    def __get__(self, obj, cls):\n        pass\n\n    def __set__(self, obj, val):\n        pass\n\nclass Cls:\n    attr = Desc()\n\nreveal_type(Cls().attr)  # N: Revealed type is \"builtins.int\"\nreveal_type(Cls.attr)  # N: Revealed type is \"builtins.str\"\n\nCls().attr = 3\nCls().attr = \"foo\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/descriptor.py\n\n[case testFunctionSigPluginFile]\n# flags: --config-file tmp/mypy.ini\n\ndef dynamic_signature(arg1: str) -> str: ...\na: int = 1\nreveal_type(dynamic_signature(a))  # N: Revealed type is \"builtins.int\"\nb: bytes = b'foo'\nreveal_type(dynamic_signature(b))  # N: Revealed type is \"builtins.bytes\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/function_sig_hook.py\n\n[case testPluginCalledCorrectlyWhenMethodInDecorator]\n# flags: --config-file tmp/mypy.ini\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\nclass Foo:\n    def a(self, x: Callable[[], T]) -> Callable[[], T]: ...\n\nb = Foo()\n\n@b.a\ndef f() -> None:\n    pass\n\nreveal_type(f())  # N: Revealed type is \"builtins.str\"\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/method_in_decorator.py\n\n[case testClassAttrPluginClassVar]\n# flags: --config-file tmp/mypy.ini\n\nfrom typing import Type\n\nclass Cls:\n    attr = 'test'\n    unchanged = 'test'\n\nreveal_type(Cls().attr)  # N: Revealed type is \"builtins.str\"\nreveal_type(Cls.attr)  # N: Revealed type is \"builtins.int\"\nreveal_type(Cls.unchanged)  # N: Revealed type is \"builtins.str\"\nx: Type[Cls]\nreveal_type(x.attr)  # N: Revealed type is \"builtins.int\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/class_attr_hook.py\n\n[case testClassAttrPluginMethod]\n# flags: --config-file tmp/mypy.ini\n\nclass Cls:\n    def attr(self) -> None:\n        pass\n\nreveal_type(Cls.attr)  # N: Revealed type is \"builtins.int\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/class_attr_hook.py\n\n[case testClassAttrPluginEnum]\n# flags: --config-file tmp/mypy.ini\n\nimport enum\n\nclass Cls(enum.Enum):\n    attr = 'test'\n\nreveal_type(Cls.attr)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/enum.pyi]\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/class_attr_hook.py\n\n[case testClassAttrPluginMetaclassAnyBase]\n# flags: --config-file tmp/mypy.ini\n\nfrom typing import Any, Type\nclass M(type):\n    attr = 'test'\n\nB: Any\nclass Cls(B, metaclass=M):\n    pass\n\nreveal_type(Cls.attr) # N: Revealed type is \"builtins.int\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/class_attr_hook.py\n\n[case testClassAttrPluginMetaclassRegularBase]\n# flags: --config-file tmp/mypy.ini\n\nfrom typing import Any, Type\nclass M(type):\n    attr = 'test'\n\nclass B:\n    attr = None\n\nclass Cls(B, metaclass=M):\n    pass\n\nreveal_type(Cls.attr) # N: Revealed type is \"builtins.int\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/class_attr_hook.py\n\n[case testClassAttrPluginPartialType]\n# flags: --config-file tmp/mypy.ini --no-local-partial-types\n\nclass Cls:\n    attr = None\n    def f(self) -> int:\n        return Cls.attr + 1\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/class_attr_hook.py\n\n[case testAddClassMethodPlugin]\n# flags: --config-file tmp/mypy.ini\nclass BaseAddMethod: pass\n\nclass MyClass(BaseAddMethod):\n    pass\n\nreveal_type(MyClass.foo_classmethod)  # N: Revealed type is \"def ()\"\nreveal_type(MyClass.foo_staticmethod)  # N: Revealed type is \"def (builtins.int) -> builtins.str\"\n\nmy_class = MyClass()\nreveal_type(my_class.foo_classmethod)  # N: Revealed type is \"def ()\"\nreveal_type(my_class.foo_staticmethod)  # N: Revealed type is \"def (builtins.int) -> builtins.str\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/add_classmethod.py\n\n[case testAddOverloadedMethodPlugin]\n# flags: --config-file tmp/mypy.ini\nclass AddOverloadedMethod: pass\n\nclass MyClass(AddOverloadedMethod):\n    pass\n\nreveal_type(MyClass.method)  # N: Revealed type is \"Overload(def (self: __main__.MyClass, arg: builtins.int) -> builtins.str, def (self: __main__.MyClass, arg: builtins.str) -> builtins.int)\"\nreveal_type(MyClass.clsmethod)  # N: Revealed type is \"Overload(def (arg: builtins.int) -> builtins.str, def (arg: builtins.str) -> builtins.int)\"\nreveal_type(MyClass.stmethod)  # N: Revealed type is \"Overload(def (arg: builtins.int) -> builtins.str, def (arg: builtins.str) -> builtins.int)\"\n\nmy_class = MyClass()\nreveal_type(my_class.method)  # N: Revealed type is \"Overload(def (arg: builtins.int) -> builtins.str, def (arg: builtins.str) -> builtins.int)\"\nreveal_type(my_class.clsmethod)  # N: Revealed type is \"Overload(def (arg: builtins.int) -> builtins.str, def (arg: builtins.str) -> builtins.int)\"\nreveal_type(my_class.stmethod)  # N: Revealed type is \"Overload(def (arg: builtins.int) -> builtins.str, def (arg: builtins.str) -> builtins.int)\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/add_overloaded_method.py\n\n[case testAddMethodPluginExplicitOverride]\n# flags: --python-version 3.12 --config-file tmp/mypy.ini\nfrom typing import override, TypeVar\n\nT = TypeVar('T', bound=type)\n\ndef inject_foo(t: T) -> T:\n    # Imitates:\n    # t.foo_implicit = some_method\n    return t\n\nclass BaseWithoutFoo: pass\n\n@inject_foo\nclass ChildWithFoo(BaseWithoutFoo): pass\nreveal_type(ChildWithFoo.foo_implicit)  # N: Revealed type is \"def (self: __main__.ChildWithFoo)\"\n\n@inject_foo\nclass SomeWithFoo(ChildWithFoo): pass\nreveal_type(SomeWithFoo.foo_implicit)  # N: Revealed type is \"def (self: __main__.SomeWithFoo)\"\n\nclass ExplicitOverride(SomeWithFoo):\n    @override\n    def foo_implicit(self) -> None: pass\n\nclass ImplicitOverride(SomeWithFoo):\n    def foo_implicit(self) -> None: pass  # E: Method \"foo_implicit\" is not using @override but is overriding a method in class \"__main__.SomeWithFoo\"\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/add_method.py\nenable_error_code = explicit-override\n[typing fixtures/typing-override.pyi]\n\n[case testCustomErrorCodePlugin]\n# flags: --config-file tmp/mypy.ini  --show-error-codes\ndef main() -> int:\n    return 2\n\nmain()  # E: Custom error  [custom]\nreveal_type(1)  # N: Revealed type is \"Literal[1]?\"\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/custom_errorcode.py\n\n\n[case testPyprojectPluginsTrailingComma]\n# flags: --config-file tmp/pyproject.toml\n[file pyproject.toml]\n# This test checks that trailing commas in string-based `plugins` are allowed.\n\\[tool.mypy]\nplugins = \"\"\"\n  <ROOT>/test-data/unit/plugins/function_sig_hook.py,\n  <ROOT>/test-data/unit/plugins/method_in_decorator.py,\n\"\"\"\n[out]\n\n\n\n[case magicMethodReverse]\n# flags: --config-file tmp/mypy.ini\nfrom typing import Literal\n\nop1: Literal[3] = 3\nop2: Literal[4] = 4\nc = op1 + op2\nreveal_type(c) # N: Revealed type is \"Literal[7]\"\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/magic_method.py\n[builtins fixtures/ops.pyi]\n"
  },
  {
    "path": "test-data/unit/check-dataclass-transform.test",
    "content": "[case testDataclassTransformReusesDataclassLogic]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type\n\n@dataclass_transform()\ndef my_dataclass(cls: Type) -> Type:\n    return cls\n\n@my_dataclass\nclass Person:\n    name: str\n    age: int\n\n    def summary(self):\n        return \"%s is %d years old.\" % (self.name, self.age)\n\nreveal_type(Person)  # N: Revealed type is \"def (name: builtins.str, age: builtins.int) -> __main__.Person\"\nPerson('John', 32)\nPerson('Jonh', 21, None)  # E: Too many arguments for \"Person\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformIsFoundInTypingExtensions]\nfrom typing import Type\nfrom typing_extensions import dataclass_transform\n\n@dataclass_transform()\ndef my_dataclass(cls: Type) -> Type:\n    return cls\n\n@my_dataclass\nclass Person:\n    name: str\n    age: int\n\n    def summary(self):\n        return \"%s is %d years old.\" % (self.name, self.age)\n\nreveal_type(Person)  # N: Revealed type is \"def (name: builtins.str, age: builtins.int) -> __main__.Person\"\nPerson('John', 32)\nPerson('Jonh', 21, None)  # E: Too many arguments for \"Person\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformParametersAreApplied]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Callable, Type\n\n@dataclass_transform()\ndef my_dataclass(*, eq: bool, order: bool) -> Callable[[Type], Type]:\n    def transform(cls: Type) -> Type:\n        return cls\n    return transform\n\n@my_dataclass(eq=False, order=True)  # E: \"eq\" must be True if \"order\" is True\nclass Person:\n    name: str\n    age: int\n\nreveal_type(Person)  # N: Revealed type is \"def (name: builtins.str, age: builtins.int) -> __main__.Person\"\nPerson('John', 32)\nPerson('John', 21, None)  # E: Too many arguments for \"Person\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformParametersMustBeBoolLiterals]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Callable, Type\n\n@dataclass_transform()\ndef my_dataclass(*, eq: bool = True, order: bool = False) -> Callable[[Type], Type]:\n    def transform(cls: Type) -> Type:\n        return cls\n    return transform\n@dataclass_transform()\nclass BaseClass:\n    def __init_subclass__(cls, *, eq: bool): ...\n@dataclass_transform()\nclass Metaclass(type): ...\n\nBOOL_CONSTANT = True\n@my_dataclass(eq=BOOL_CONSTANT)  # E: \"eq\" argument must be a True or False literal\nclass A: ...\n@my_dataclass(order=not False)  # E: \"order\" argument must be a True or False literal\nclass B: ...\nclass C(BaseClass, eq=BOOL_CONSTANT): ...  # E: \"eq\" argument must be a True or False literal\nclass D(metaclass=Metaclass, order=not False): ...  # E: \"order\" argument must be a True or False literal\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformDefaultParamsMustBeLiterals]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type, Final\n\nBOOLEAN_CONSTANT = True\nFINAL_BOOLEAN: Final = True\n\n@dataclass_transform(eq_default=BOOLEAN_CONSTANT) # E: \"eq_default\" argument must be a True or False literal\ndef foo(cls: Type) -> Type:\n    return cls\n@dataclass_transform(eq_default=(not True)) # E: \"eq_default\" argument must be a True or False literal\ndef bar(cls: Type) -> Type:\n    return cls\n@dataclass_transform(eq_default=FINAL_BOOLEAN) # E: \"eq_default\" argument must be a True or False literal\ndef baz(cls: Type) -> Type:\n    return cls\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformUnrecognizedParamsAreErrors]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type\n\nBOOLEAN_CONSTANT = True\n\n@dataclass_transform(nonexistent=True) # E: Unrecognized dataclass_transform parameter \"nonexistent\"\ndef foo(cls: Type) -> Type:\n    return cls\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n\n[case testDataclassTransformDefaultParams]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type, Callable\n\n@dataclass_transform(eq_default=False)\ndef no_eq(*, order: bool = False) -> Callable[[Type], Type]:\n    return lambda cls: cls\n@no_eq()\nclass Foo: ...\n@no_eq(order=True)  # E: \"eq\" must be True if \"order\" is True\nclass Bar: ...\n\n\n@dataclass_transform(kw_only_default=True)\ndef always_use_kw(cls: Type) -> Type:\n    return cls\n@always_use_kw\nclass Baz:\n    x: int\nBaz(x=5)\nBaz(5)  # E: Too many positional arguments for \"Baz\"\n\n@dataclass_transform(order_default=True)\ndef ordered(*, eq: bool = True) -> Callable[[Type], Type]:\n    return lambda cls: cls\n@ordered()\nclass A:\n    x: int\nA(1) > A(2)\n\n@dataclass_transform(frozen_default=True)\ndef frozen(cls: Type) -> Type:\n    return cls\n@frozen\nclass B:\n    x: int\nb = B(x=1)\nb.x = 2  # E: Property \"x\" defined in \"B\" is read-only\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformDefaultsCanBeOverridden]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Callable, Type\n\n@dataclass_transform(kw_only_default=True)\ndef my_dataclass(*, kw_only: bool = True) -> Callable[[Type], Type]:\n    return lambda cls: cls\n\n@my_dataclass()\nclass KwOnly:\n    x: int\n@my_dataclass(kw_only=False)\nclass KwOptional:\n    x: int\n\nKwOnly(5)  # E: Too many positional arguments for \"KwOnly\"\nKwOptional(5)\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformFieldSpecifiersDefaultsToEmpty]\n# flags: --python-version 3.11\nfrom dataclasses import field, dataclass\nfrom typing import dataclass_transform, Type\n\n@dataclass_transform()\ndef my_dataclass(cls: Type) -> Type:\n    return cls\n\n@my_dataclass\nclass Foo:\n    foo: int = field(kw_only=True)\n\n# Does not cause a type error because `dataclasses.field` is not a recognized field specifier by\n# default\nFoo(5)\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformFieldSpecifierRejectMalformed]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Any, Callable, Final, Type\n\ndef some_type() -> Type: ...\ndef some_function() -> Callable[[], None]: ...\n\ndef field(*args, **kwargs): ...\ndef fields_tuple() -> tuple[type | Callable[..., Any], ...]: return (field,)\nCONSTANT: Final = (field,)\n\n@dataclass_transform(field_specifiers=(some_type(),))  # E: \"field_specifiers\" must only contain identifiers\ndef bad_dataclass1() -> None: ...\n@dataclass_transform(field_specifiers=(some_function(),))  # E: \"field_specifiers\" must only contain identifiers\ndef bad_dataclass2() -> None: ...\n@dataclass_transform(field_specifiers=CONSTANT)  # E: \"field_specifiers\" argument must be a tuple literal\ndef bad_dataclass3() -> None: ...\n@dataclass_transform(field_specifiers=fields_tuple())  # E: \"field_specifiers\" argument must be a tuple literal\ndef bad_dataclass4() -> None: ...\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformFieldSpecifierParams]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Any, Callable, Type, Final\n\ndef field(\n    *,\n    init: bool = True,\n    kw_only: bool = False,\n    alias: str | None = None,\n    default: Any | None = None,\n    default_factory: Callable[[], Any] | None = None,\n    factory: Callable[[], Any] | None = None,\n): ...\n@dataclass_transform(field_specifiers=(field,))\ndef my_dataclass(cls: Type) -> Type:\n    return cls\n\nB: Final = 'b_'\n@my_dataclass\nclass Foo:\n    a: int = field(alias='a_')\n    b: int = field(alias=B)\n    # cannot be passed as a positional\n    kwonly: int = field(kw_only=True, default=0)\n    # Safe to omit from constructor, error to pass\n    noinit: int = field(init=False, default=1)\n    # It should be safe to call the constructor without passing any of these\n    unused1: int = field(default=0)\n    unused2: int = field(factory=lambda: 0)\n    unused3: int = field(default_factory=lambda: 0)\n\nFoo(a=5, b_=1)  # E: Unexpected keyword argument \"a\" for \"Foo\"\nFoo(a_=1, b_=1, noinit=1)  # E: Unexpected keyword argument \"noinit\" for \"Foo\"\nFoo(1, 2, 3) # (a, b, unused1)\nfoo = Foo(1, 2, kwonly=3)\nreveal_type(foo.noinit)  # N: Revealed type is \"builtins.int\"\nreveal_type(foo.unused1)  # N: Revealed type is \"builtins.int\"\nFoo(a_=5, b_=1, unused1=2, unused2=3, unused3=4)\n\ndef some_str() -> str: ...\ndef some_bool() -> bool: ...\n@my_dataclass\nclass Bad:\n    bad1: int = field(alias=some_str())  # E: \"alias\" argument to dataclass field must be a string literal\n    bad2: int = field(kw_only=some_bool())  # E: \"kw_only\" argument must be a boolean literal\n\nreveal_type(Foo.__dataclass_fields__)  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformFieldSpecifierExtraArgs]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform\n\ndef field(extra1, *, kw_only=False, extra2=0): ...\n@dataclass_transform(field_specifiers=(field,))\ndef my_dataclass(cls):\n    return cls\n\n@my_dataclass\nclass Good:\n    a: int = field(5)\n    b: int = field(5, extra2=1)\n    c: int = field(5, kw_only=True)\n\n@my_dataclass\nclass Bad:\n    a: int = field(kw_only=True)  # E: Missing positional argument \"extra1\" in call to \"field\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformMultipleFieldSpecifiers]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform\n\ndef field1(*, default: int) -> int: ...\ndef field2(*, default: str) -> str: ...\n\n@dataclass_transform(field_specifiers=(field1, field2))\ndef my_dataclass(cls): return cls\n\n@my_dataclass\nclass Foo:\n    a: int = field1(default=0)\n    b: str = field2(default='hello')\n\nreveal_type(Foo)  # N: Revealed type is \"def (a: builtins.int =, b: builtins.str =) -> __main__.Foo\"\nFoo()\nFoo(a=1, b='bye')\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformFieldSpecifierImplicitInit]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Literal, overload\n\ndef init(*, init: Literal[True] = True): ...\ndef no_init(*, init: Literal[False] = False): ...\n\n@overload\ndef field_overload(*, custom: None, init: Literal[True] = True): ...\n@overload\ndef field_overload(*, custom: str, init: Literal[False] = False): ...\ndef field_overload(*, custom, init): ...\n\n@dataclass_transform(field_specifiers=(init, no_init, field_overload))\ndef my_dataclass(cls): return cls\n\n@my_dataclass\nclass Foo:\n    a: int = init()\n    b: int = field_overload(custom=None)\n\n    bad1: int = no_init()\n    bad2: int = field_overload(custom=\"bad2\")\n\nreveal_type(Foo)  # N: Revealed type is \"def (a: builtins.int, b: builtins.int) -> __main__.Foo\"\nFoo(a=1, b=2)\nFoo(a=1, b=2, bad1=0)  # E: Unexpected keyword argument \"bad1\" for \"Foo\"\nFoo(a=1, b=2, bad2=0)  # E: Unexpected keyword argument \"bad2\" for \"Foo\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformOverloadsDecoratorOnOverload]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, overload, Any, Callable, Type, Literal\n\n@overload\ndef my_dataclass(*, foo: str) -> Callable[[Type], Type]: ...\n@overload\n@dataclass_transform(frozen_default=True)\ndef my_dataclass(*, foo: int) -> Callable[[Type], Type]: ...\ndef my_dataclass(*, foo: Any) -> Callable[[Type], Type]:\n    return lambda cls: cls\n@my_dataclass(foo=\"hello\")\nclass A:\n    a: int\n@my_dataclass(foo=5)\nclass B:\n    b: int\n\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int) -> __main__.A\"\nreveal_type(B)  # N: Revealed type is \"def (b: builtins.int) -> __main__.B\"\nA(1, \"hello\")  # E: Too many arguments for \"A\"\na = A(1)\na.a = 2  # E: Property \"a\" defined in \"A\" is read-only\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformOverloadsDecoratorOnImpl]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, overload, Any, Callable, Type, Literal\n\n@overload\ndef my_dataclass(*, foo: str) -> Callable[[Type], Type]: ...\n@overload\ndef my_dataclass(*, foo: int) -> Callable[[Type], Type]: ...\n@dataclass_transform(frozen_default=True)\ndef my_dataclass(*, foo: Any) -> Callable[[Type], Type]:\n    return lambda cls: cls\n@my_dataclass(foo=\"hello\")\nclass A:\n    a: int\n@my_dataclass(foo=5)\nclass B:\n    b: int\n\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int) -> __main__.A\"\nreveal_type(B)  # N: Revealed type is \"def (b: builtins.int) -> __main__.B\"\nA(1, \"hello\")  # E: Too many arguments for \"A\"\na = A(1)\na.a = 2  # E: Property \"a\" defined in \"A\" is read-only\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformViaBaseClass]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform\n\n@dataclass_transform(frozen_default=True)\nclass Dataclass:\n    def __init_subclass__(cls, *, kw_only: bool = False): ...\n\nclass Person(Dataclass, kw_only=True):\n    name: str\n    age: int\n\nreveal_type(Person)  # N: Revealed type is \"def (*, name: builtins.str, age: builtins.int) -> __main__.Person\"\nPerson('Jonh', 21)  # E: Too many positional arguments for \"Person\"\nperson = Person(name='John', age=32)\nperson.name = \"John Smith\"  # E: Property \"name\" defined in \"Person\" is read-only\n\nclass Contact(Person):\n    email: str\n\nreveal_type(Contact)  # N: Revealed type is \"def (email: builtins.str, *, name: builtins.str, age: builtins.int) -> __main__.Contact\"\nContact('john@john.com', name='John', age=32)\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformViaMetaclass]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform\n\n@dataclass_transform(frozen_default=True)\nclass Dataclass(type): ...\n\n# Note that PEP 681 states that a class that directly specifies a dataclass_transform-decorated\n# metaclass should be treated as neither frozen nor unfrozen. For Person to have frozen semantics,\n# it may not directly specify the metaclass.\nclass BaseDataclass(metaclass=Dataclass): ...\nclass Person(BaseDataclass, kw_only=True):\n    name: str\n    age: int\n\nreveal_type(Person)  # N: Revealed type is \"def (*, name: builtins.str, age: builtins.int) -> __main__.Person\"\nPerson('Jonh', 21)  # E: Too many positional arguments for \"Person\"\nperson = Person(name='John', age=32)\nperson.name = \"John Smith\"  # E: Property \"name\" defined in \"Person\" is read-only\n\nclass Contact(Person):\n    email: str\n\nreveal_type(Contact)  # N: Revealed type is \"def (email: builtins.str, *, name: builtins.str, age: builtins.int) -> __main__.Contact\"\nContact('john@john.com', name='John', age=32)\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformViaSubclassOfMetaclass]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform\n\n@dataclass_transform(frozen_default=True)\nclass BaseMeta(type): ...\nclass SubMeta(BaseMeta): ...\n\n# MyPy does *not* recognize this as a dataclass because the metaclass is not directly decorated with\n# dataclass_transform\nclass Foo(metaclass=SubMeta):\n    foo: int\n\nreveal_type(Foo)  # N: Revealed type is \"def () -> __main__.Foo\"\nFoo(1)  # E: Too many arguments for \"Foo\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformTypeCheckingInFunction]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type, TYPE_CHECKING\n\n@dataclass_transform()\ndef model(cls: Type) -> Type:\n    return cls\n\n@model\nclass FunctionModel:\n    if TYPE_CHECKING:\n        string_: str\n        integer_: int\n    else:\n        string_: tuple\n        integer_: tuple\n\nFunctionModel(string_=\"abc\", integer_=1)\nFunctionModel(string_=\"abc\", integer_=tuple())  # E: Argument \"integer_\" to \"FunctionModel\" has incompatible type \"tuple[Never, ...]\"; expected \"int\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformNegatedTypeCheckingInFunction]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type, TYPE_CHECKING\n\n@dataclass_transform()\ndef model(cls: Type) -> Type:\n    return cls\n\n@model\nclass FunctionModel:\n    if not TYPE_CHECKING:\n        string_: tuple\n        integer_: tuple\n    else:\n        string_: str\n        integer_: int\n\nFunctionModel(string_=\"abc\", integer_=1)\nFunctionModel(string_=\"abc\", integer_=tuple())  # E: Argument \"integer_\" to \"FunctionModel\" has incompatible type \"tuple[Never, ...]\"; expected \"int\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n\n[case testDataclassTransformTypeCheckingInBaseClass]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, TYPE_CHECKING\n\n@dataclass_transform()\nclass ModelBase:\n    ...\n\nclass BaseClassModel(ModelBase):\n    if TYPE_CHECKING:\n        string_: str\n        integer_: int\n    else:\n        string_: tuple\n        integer_: tuple\n\nBaseClassModel(string_=\"abc\", integer_=1)\nBaseClassModel(string_=\"abc\", integer_=tuple())  # E: Argument \"integer_\" to \"BaseClassModel\" has incompatible type \"tuple[Never, ...]\"; expected \"int\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformNegatedTypeCheckingInBaseClass]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, TYPE_CHECKING\n\n@dataclass_transform()\nclass ModelBase:\n    ...\n\nclass BaseClassModel(ModelBase):\n    if not TYPE_CHECKING:\n        string_: tuple\n        integer_: tuple\n    else:\n        string_: str\n        integer_: int\n\nBaseClassModel(string_=\"abc\", integer_=1)\nBaseClassModel(string_=\"abc\", integer_=tuple())  # E: Argument \"integer_\" to \"BaseClassModel\" has incompatible type \"tuple[Never, ...]\"; expected \"int\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformTypeCheckingInMetaClass]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type, TYPE_CHECKING\n\n@dataclass_transform()\nclass ModelMeta(type):\n    ...\n\nclass ModelBaseWithMeta(metaclass=ModelMeta):\n    ...\n\nclass MetaClassModel(ModelBaseWithMeta):\n    if TYPE_CHECKING:\n        string_: str\n        integer_: int\n    else:\n        string_: tuple\n        integer_: tuple\n\nMetaClassModel(string_=\"abc\", integer_=1)\nMetaClassModel(string_=\"abc\", integer_=tuple())  # E: Argument \"integer_\" to \"MetaClassModel\" has incompatible type \"tuple[Never, ...]\"; expected \"int\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformNegatedTypeCheckingInMetaClass]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type, TYPE_CHECKING\n\n@dataclass_transform()\nclass ModelMeta(type):\n    ...\n\nclass ModelBaseWithMeta(metaclass=ModelMeta):\n    ...\n\nclass MetaClassModel(ModelBaseWithMeta):\n    if not TYPE_CHECKING:\n        string_: tuple\n        integer_: tuple\n    else:\n        string_: str\n        integer_: int\n\nMetaClassModel(string_=\"abc\", integer_=1)\nMetaClassModel(string_=\"abc\", integer_=tuple())  # E: Argument \"integer_\" to \"MetaClassModel\" has incompatible type \"tuple[Never, ...]\"; expected \"int\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformStaticConditionalAttributes]\n# flags: --python-version 3.11 --always-true TRUTH\nfrom typing import dataclass_transform, Type, TYPE_CHECKING\n\nTRUTH = False  # Is set to --always-true\n\n@dataclass_transform()\ndef model(cls: Type) -> Type:\n    return cls\n\n@model\nclass FunctionModel:\n    if TYPE_CHECKING:\n        present_1: int\n    else:\n        skipped_1: int\n    if True:  # Mypy does not know if it is True or False, so the block is used\n        present_2: int\n    if False:  # Mypy does not know if it is True or False, so the block is used\n        present_3: int\n    if not TRUTH:\n        skipped_2: int\n    else:\n        present_4: int\n\nFunctionModel(\n    present_1=1,\n    present_2=2,\n    present_3=3,\n    present_4=4,\n)\nFunctionModel()  # E: Missing positional arguments \"present_1\", \"present_2\", \"present_3\", \"present_4\" in call to \"FunctionModel\"\nFunctionModel(   # E: Unexpected keyword argument \"skipped_1\" for \"FunctionModel\"\n    present_1=1,\n    present_2=2,\n    present_3=3,\n    present_4=4,\n    skipped_1=5,\n)\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n\n[case testDataclassTransformStaticDeterministicConditionalElifAttributes]\n# flags: --python-version 3.11 --always-true TRUTH --always-false LIE\nfrom typing import dataclass_transform, Type, TYPE_CHECKING\n\nTRUTH = False  # Is set to --always-true\nLIE = True  # Is set to --always-false\n\n@dataclass_transform()\ndef model(cls: Type) -> Type:\n    return cls\n\n@model\nclass FunctionModel:\n    if TYPE_CHECKING:\n        present_1: int\n    elif TRUTH:\n        skipped_1: int\n    else:\n        skipped_2: int\n    if LIE:\n        skipped_3: int\n    elif TRUTH:\n        present_2: int\n    else:\n        skipped_4: int\n    if LIE:\n        skipped_5: int\n    elif LIE:\n        skipped_6: int\n    else:\n        present_3: int\n\nFunctionModel(\n    present_1=1,\n    present_2=2,\n    present_3=3,\n)\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformStaticNotDeterministicConditionalElifAttributes]\n# flags: --python-version 3.11 --always-true TRUTH --always-false LIE\nfrom typing import dataclass_transform, Type, TYPE_CHECKING\n\nTRUTH = False  # Is set to --always-true\nLIE = True  # Is set to --always-false\n\n@dataclass_transform()\ndef model(cls: Type) -> Type:\n    return cls\n\n@model\nclass FunctionModel:\n    if 123:  # Mypy does not know if it is True or False, so this block is used\n        present_1: int\n    elif TRUTH:  # Mypy does not know if previous condition is True or False, so it uses also this block\n        present_2: int\n    else:  # Previous block is for sure True, so this block is skipped\n        skipped_1: int\n    if 123:\n        present_3: int\n    elif 123:\n        present_4: int\n    else:\n        present_5: int\n    if 123:  # Mypy does not know if it is True or False, so this block is used\n        present_6: int\n    elif LIE:  # This is for sure False, so the block is skipped used\n        skipped_2: int\n    else:  # None of the conditions above for sure True, so this block is used\n        present_7: int\n\nFunctionModel(\n    present_1=1,\n    present_2=2,\n    present_3=3,\n    present_4=4,\n    present_5=5,\n    present_6=6,\n    present_7=7,\n)\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformFunctionConditionalAttributes]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type\n\n@dataclass_transform()\ndef model(cls: Type) -> Type:\n    return cls\n\ndef condition() -> bool:\n    return True\n\n@model\nclass FunctionModel:\n    if condition():\n        x: int\n        y: int\n        z1: int\n    else:\n        x: str  # E: Name \"x\" already defined on line 14\n        y: int  # E: Name \"y\" already defined on line 15\n        z2: int\n\nFunctionModel(x=1, y=2, z1=3, z2=4)\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n\n[case testDataclassTransformNegatedFunctionConditionalAttributes]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type\n\n@dataclass_transform()\ndef model(cls: Type) -> Type:\n    return cls\n\ndef condition() -> bool:\n    return True\n\n@model\nclass FunctionModel:\n    if not condition():\n        x: int\n        y: int\n        z1: int\n    else:\n        x: str  # E: Name \"x\" already defined on line 14\n        y: int  # E: Name \"y\" already defined on line 15\n        z2: int\n\nFunctionModel(x=1, y=2, z1=3, z2=4)\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformDirectMetaclassNeitherFrozenNorNotFrozen]\n# flags: --python-version 3.11\nfrom typing import dataclass_transform, Type\n\n@dataclass_transform()\nclass Meta(type): ...\nclass Base(metaclass=Meta):\n    base: int\nclass Foo(Base, frozen=True):\n    foo: int\nclass Bar(Base, frozen=False):\n    bar: int\n\n\nfoo = Foo(0, 1)\nfoo.foo = 5  # E: Property \"foo\" defined in \"Foo\" is read-only\nfoo.base = 6\nreveal_type(foo.base)  # N: Revealed type is \"builtins.int\"\nbar = Bar(0, 1)\nbar.bar = 5\nbar.base = 6\nreveal_type(bar.base)  # N: Revealed type is \"builtins.int\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformReplace]\nfrom dataclasses import replace\nfrom typing import dataclass_transform, Type\n\n@dataclass_transform()\ndef my_dataclass(cls: Type) -> Type:\n    return cls\n\n@my_dataclass\nclass Person:\n    name: str\n\np = Person('John')\ny = replace(p, name='Bob')\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformSimpleDescriptor]\n# flags: --python-version 3.11\n\nfrom typing import dataclass_transform, overload, Any\n\n@dataclass_transform()\ndef my_dataclass(cls): ...\n\nclass Desc:\n    @overload\n    def __get__(self, instance: None, owner: Any) -> Desc: ...\n    @overload\n    def __get__(self, instance: object, owner: Any) -> str: ...\n    def __get__(self, instance: object | None, owner: Any) -> Desc | str: ...\n\n    def __set__(self, instance: Any, value: str) -> None: ...\n\n@my_dataclass\nclass C:\n    x: Desc\n    y: int\n\nC(x='x', y=1)\nC(x=1, y=1)  # E: Argument \"x\" to \"C\" has incompatible type \"int\"; expected \"str\"\nreveal_type(C(x='x', y=1).x)  # N: Revealed type is \"builtins.str\"\nreveal_type(C(x='x', y=1).y)  # N: Revealed type is \"builtins.int\"\nreveal_type(C.x)  # N: Revealed type is \"__main__.Desc\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformUnannotatedDescriptor]\n# flags: --python-version 3.11\n\nfrom typing import dataclass_transform, overload, Any\n\n@dataclass_transform()\ndef my_dataclass(cls): ...\n\nclass Desc:\n    @overload\n    def __get__(self, instance: None, owner: Any) -> Desc: ...\n    @overload\n    def __get__(self, instance: object, owner: Any) -> str: ...\n    def __get__(self, instance: object | None, owner: Any) -> Desc | str: ...\n\n    def __set__(*args, **kwargs): ...\n\n@my_dataclass\nclass C:\n    x: Desc\n    y: int\n\nC(x='x', y=1)\nC(x=1, y=1)\nreveal_type(C(x='x', y=1).x)  # N: Revealed type is \"builtins.str\"\nreveal_type(C(x='x', y=1).y)  # N: Revealed type is \"builtins.int\"\nreveal_type(C.x)  # N: Revealed type is \"__main__.Desc\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformGenericDescriptor]\n# flags: --python-version 3.11\n\nfrom typing import dataclass_transform, overload, Any, TypeVar, Generic\n\n@dataclass_transform()\ndef my_dataclass(frozen: bool = False): ...\n\nT = TypeVar(\"T\")\n\nclass Desc(Generic[T]):\n    @overload\n    def __get__(self, instance: None, owner: Any) -> Desc[T]: ...\n    @overload\n    def __get__(self, instance: object, owner: Any) -> T: ...\n    def __get__(self, instance: object | None, owner: Any) -> Desc | T: ...\n\n    def __set__(self, instance: Any, value: T) -> None: ...\n\n@my_dataclass()\nclass C:\n    x: Desc[str]\n\nC(x='x')\nC(x=1)  # E: Argument \"x\" to \"C\" has incompatible type \"int\"; expected \"str\"\nreveal_type(C(x='x').x)  # N: Revealed type is \"builtins.str\"\nreveal_type(C.x)  # N: Revealed type is \"__main__.Desc[builtins.str]\"\n\n@my_dataclass()\nclass D(C):\n    y: Desc[int]\n\nd = D(x='x', y=1)\nreveal_type(d.x)  # N: Revealed type is \"builtins.str\"\nreveal_type(d.y)  # N: Revealed type is \"builtins.int\"\nreveal_type(D.x)  # N: Revealed type is \"__main__.Desc[builtins.str]\"\nreveal_type(D.y)  # N: Revealed type is \"__main__.Desc[builtins.int]\"\n\n@my_dataclass(frozen=True)\nclass F:\n    x: Desc[str] = Desc()\n\nF(x='x')\nF(x=1)  # E: Argument \"x\" to \"F\" has incompatible type \"int\"; expected \"str\"\nreveal_type(F(x='x').x)  # N: Revealed type is \"builtins.str\"\nreveal_type(F.x)  # N: Revealed type is \"__main__.Desc[builtins.str]\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformGenericDescriptorWithInheritance]\n# flags: --python-version 3.11\n\nfrom typing import dataclass_transform, overload, Any, TypeVar, Generic\n\n@dataclass_transform()\ndef my_dataclass(cls): ...\n\nT = TypeVar(\"T\")\n\nclass Desc(Generic[T]):\n    @overload\n    def __get__(self, instance: None, owner: Any) -> Desc[T]: ...\n    @overload\n    def __get__(self, instance: object, owner: Any) -> T: ...\n    def __get__(self, instance: object | None, owner: Any) -> Desc | T: ...\n\n    def __set__(self, instance: Any, value: T) -> None: ...\n\nclass Desc2(Desc[str]):\n    pass\n\n@my_dataclass\nclass C:\n    x: Desc2\n\nC(x='x')\nC(x=1)  # E: Argument \"x\" to \"C\" has incompatible type \"int\"; expected \"str\"\nreveal_type(C(x='x').x)  # N: Revealed type is \"builtins.str\"\nreveal_type(C.x)  # N: Revealed type is \"__main__.Desc[builtins.str]\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformDescriptorWithDifferentGetSetTypes]\n# flags: --python-version 3.11\n\nfrom typing import dataclass_transform, overload, Any\n\n@dataclass_transform()\ndef my_dataclass(cls): ...\n\nclass Desc:\n    @overload\n    def __get__(self, instance: None, owner: Any) -> int: ...\n    @overload\n    def __get__(self, instance: object, owner: Any) -> str: ...\n    def __get__(self, instance, owner): ...\n\n    def __set__(self, instance: Any, value: bytes | None) -> None: ...\n\n@my_dataclass\nclass C:\n    x: Desc\n\nc = C(x=b'x')\nc = C(x=None)\nC(x=1)  # E: Argument \"x\" to \"C\" has incompatible type \"int\"; expected \"bytes | None\"\nreveal_type(c.x)  # N: Revealed type is \"builtins.str\"\nreveal_type(C.x)  # N: Revealed type is \"builtins.int\"\nc.x = b'x'\nc.x = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"bytes | None\")\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTransformUnsupportedDescriptors]\n# flags: --python-version 3.11\n\nfrom typing import dataclass_transform, overload, Any\n\n@dataclass_transform()\ndef my_dataclass(cls): ...\n\nclass Desc:\n    @overload\n    def __get__(self, instance: None, owner: Any) -> int: ...\n    @overload\n    def __get__(self, instance: object, owner: Any) -> str: ...\n    def __get__(self, instance, owner): ...\n\n    def __set__(*args, **kwargs) -> None: ...\n\nclass Desc2:\n    @overload\n    def __get__(self, instance: None, owner: Any) -> int: ...\n    @overload\n    def __get__(self, instance: object, owner: Any) -> str: ...\n    def __get__(self, instance, owner): ...\n\n    @overload\n    def __set__(self, instance: Any, value: bytes) -> None: ...\n    @overload\n    def __set__(self) -> None: ...\n    def __set__(self, *args, **kawrga) -> None: ...\n\n@my_dataclass\nclass C:\n    x: Desc  # E: Unsupported signature for \"__set__\" in \"Desc\"\n    y: Desc2  # E: Unsupported \"__set__\" in \"Desc2\"\n\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/dataclasses.pyi]\n"
  },
  {
    "path": "test-data/unit/check-dataclasses.test",
    "content": "[case testDataclassesBasic]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Person:\n    name: str\n    age: int\n\n    def summary(self):\n        return \"%s is %d years old.\" % (self.name, self.age)\n\nreveal_type(Person)  # N: Revealed type is \"def (name: builtins.str, age: builtins.int) -> __main__.Person\"\nPerson('John', 32)\nPerson('Jonh', 21, None)  # E: Too many arguments for \"Person\"\n\n[builtins fixtures/dataclasses.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testDataclassesCustomInit]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    a: int\n\n    def __init__(self, a: str) -> None:\n        pass\n\nA('1')\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesBasicInheritance]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Mammal:\n    age: int\n\n@dataclass\nclass Person(Mammal):\n    name: str\n\n    def summary(self):\n        return \"%s is %d years old.\" % (self.name, self.age)\n\nreveal_type(Person)  # N: Revealed type is \"def (age: builtins.int, name: builtins.str) -> __main__.Person\"\nMammal(10)\nPerson(32, 'John')\nPerson(21, 'Jonh', None)  # E: Too many arguments for \"Person\"\n\n[builtins fixtures/dataclasses.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testDataclassesDeepInheritance]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    a: int\n\n@dataclass\nclass B(A):\n    b: int\n\n@dataclass\nclass C(B):\n    c: int\n\n@dataclass\nclass D(C):\n    d: int\n\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int) -> __main__.A\"\nreveal_type(B)  # N: Revealed type is \"def (a: builtins.int, b: builtins.int) -> __main__.B\"\nreveal_type(C)  # N: Revealed type is \"def (a: builtins.int, b: builtins.int, c: builtins.int) -> __main__.C\"\nreveal_type(D)  # N: Revealed type is \"def (a: builtins.int, b: builtins.int, c: builtins.int, d: builtins.int) -> __main__.D\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesMultipleInheritance]\nfrom dataclasses import dataclass, field, InitVar\n@dataclass\nclass A:\n    a: bool\n\n@dataclass\nclass B:\n    b: InitVar[bool]\n    _b: bool = field(init=False)\n\n    def __post_init__(self, b: bool):\n        self._b = b\n\n@dataclass\nclass C(A, B):\n    pass\n\nreveal_type(C)  # N: Revealed type is \"def (b: builtins.bool, a: builtins.bool) -> __main__.C\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesDeepInitVarInheritance]\nfrom dataclasses import dataclass, field, InitVar\n@dataclass\nclass A:\n    a: bool\n\n@dataclass\nclass B:\n    b: InitVar[bool]\n    _b: bool = field(init=False)\n\n    def __post_init__(self, b: bool):\n        self._b = b\n\n@dataclass(init=False)\nclass C(B):\n    def __init__(self):\n        super().__init__(True)\n\n@dataclass\nclass D(C):\n    pass\n\nreveal_type(C)  # N: Revealed type is \"def () -> __main__.C\"\nreveal_type(D)  # N: Revealed type is \"def (b: builtins.bool) -> __main__.D\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesOverriding]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Mammal:\n    age: int\n\n@dataclass\nclass Person(Mammal):\n    name: str\n    age: int\n\n@dataclass\nclass SpecialPerson(Person):\n    special_factor: float\n\n@dataclass\nclass ExtraSpecialPerson(SpecialPerson):\n    age: int\n    special_factor: float\n    name: str\n\nreveal_type(Person)  # N: Revealed type is \"def (age: builtins.int, name: builtins.str) -> __main__.Person\"\nreveal_type(SpecialPerson)  # N: Revealed type is \"def (age: builtins.int, name: builtins.str, special_factor: builtins.float) -> __main__.SpecialPerson\"\nreveal_type(ExtraSpecialPerson)  # N: Revealed type is \"def (age: builtins.int, name: builtins.str, special_factor: builtins.float) -> __main__.ExtraSpecialPerson\"\nPerson(32, 'John')\nPerson(21, 'John', None)  # E: Too many arguments for \"Person\"\nSpecialPerson(21, 'John', 0.5)\nExtraSpecialPerson(21, 'John', 0.5)\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesOverridingWithDefaults]\n# Issue #5681 https://github.com/python/mypy/issues/5681\nfrom dataclasses import dataclass\nfrom typing import Any\n\n@dataclass\nclass Base:\n    some_int: Any\n    some_str: str = 'foo'\n\n\n@dataclass\nclass C(Base):\n    some_int: int\n\nreveal_type(C)  # N: Revealed type is \"def (some_int: builtins.int, some_str: builtins.str =) -> __main__.C\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassIncompatibleOverrides]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Base:\n    foo: int\n\n@dataclass\nclass BadDerived1(Base):\n    def foo(self) -> int:  # E: Dataclass attribute may only be overridden by another attribute \\\n                           # E: Signature of \"foo\" incompatible with supertype \"Base\" \\\n                           # N:      Superclass: \\\n                           # N:          int \\\n                           # N:      Subclass: \\\n                           # N:          def foo(self) -> int\n        return 1\n\n@dataclass\nclass BadDerived2(Base):\n    @property              # E: Dataclass attribute may only be overridden by another attribute\n    def foo(self) -> int:  # E: Cannot override writeable attribute with read-only property\n        return 2\n\n@dataclass\nclass BadDerived3(Base):\n    class foo: pass  # E: Dataclass attribute may only be overridden by another attribute\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassMultipleInheritance]\nfrom dataclasses import dataclass\n\nclass Unrelated:\n    foo: str\n\n@dataclass\nclass Base:\n    bar: int\n\n@dataclass\nclass Derived(Base, Unrelated):\n    pass\n\nd = Derived(3)\nreveal_type(d.foo)  # N: Revealed type is \"builtins.str\"\nreveal_type(d.bar)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassIncompatibleFrozenOverride]\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Base:\n    foo: int\n\n@dataclass(frozen=True)\nclass BadDerived(Base):\n    @property  # E: Dataclass attribute may only be overridden by another attribute\n    def foo(self) -> int:\n        return 3\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesFreezing]\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass Person:\n    name: str\n\njohn = Person('John')\njohn.name = 'Ben'  # E: Property \"name\" defined in \"Person\" is read-only\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesInconsistentFreezing]\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass FrozenBase:\n    pass\n\n@dataclass\nclass BadNormalDerived(FrozenBase):  # E: Non-frozen dataclass cannot inherit from a frozen dataclass\n    pass\n\n@dataclass\nclass NormalBase:\n    pass\n\n@dataclass(frozen=True)\nclass BadFrozenDerived(NormalBase):  # E: Frozen dataclass cannot inherit from a non-frozen dataclass\n    pass\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesFields]\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass Person:\n    name: str\n    age: int = field(default=0, init=False)\n\nreveal_type(Person)  # N: Revealed type is \"def (name: builtins.str) -> __main__.Person\"\njohn = Person('John')\njohn.age = 'invalid'  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\njohn.age = 24\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesBadInit]\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass Person:\n    name: str\n    age: int = field(init=None)  # E: No overload variant of \"field\" matches argument type \"None\" \\\n                                 # N: Possible overload variants: \\\n                                 # N:     def [_T] field(*, default: _T, init: bool = ..., repr: bool = ..., hash: bool | None = ..., compare: bool = ..., metadata: Mapping[str, Any] | None = ..., kw_only: bool = ...) -> _T \\\n                                 # N:     def [_T] field(*, default_factory: Callable[[], _T], init: bool = ..., repr: bool = ..., hash: bool | None = ..., compare: bool = ..., metadata: Mapping[str, Any] | None = ..., kw_only: bool = ...) -> _T \\\n                                 # N:     def field(*, init: bool = ..., repr: bool = ..., hash: bool | None = ..., compare: bool = ..., metadata: Mapping[str, Any] | None = ..., kw_only: bool = ...) -> Any\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesMultiInit]\nfrom dataclasses import dataclass, field\nfrom typing import List\n\n@dataclass\nclass Person:\n    name: str\n    age: int = field(init=False)\n    friend_names: List[str] = field(init=True)\n    enemy_names: List[str]\n\nreveal_type(Person)  # N: Revealed type is \"def (name: builtins.str, friend_names: builtins.list[builtins.str], enemy_names: builtins.list[builtins.str]) -> __main__.Person\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesMultiInitDefaults]\nfrom dataclasses import dataclass, field\nfrom typing import List, Optional\n\n@dataclass\nclass Person:\n    name: str\n    age: int = field(init=False)\n    friend_names: List[str] = field(init=True)\n    enemy_names: List[str]\n    nickname: Optional[str] = None\n\nreveal_type(Person)  # N: Revealed type is \"def (name: builtins.str, friend_names: builtins.list[builtins.str], enemy_names: builtins.list[builtins.str], nickname: builtins.str | None =) -> __main__.Person\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesDefaults]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Application:\n    name: str = 'Unnamed'\n    rating: int = 0\n\nreveal_type(Application)  # N: Revealed type is \"def (name: builtins.str =, rating: builtins.int =) -> __main__.Application\"\napp = Application()\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesDefaultFactories]\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass Application:\n    name: str = 'Unnamed'\n    rating: int = field(default_factory=int)\n    rating_count: int = field()  # E: Attributes without a default cannot follow attributes with one\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesDefaultFactoryTypeChecking]\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass Application:\n    name: str = 'Unnamed'\n    rating: int = field(default_factory=str)  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesDefaultOrdering]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Application:\n    name: str = 'Unnamed'\n    rating: int  # E: Attributes without a default cannot follow attributes with one\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesOrderingKwOnly]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n\n@dataclass(kw_only=True)\nclass Application:\n    name: str = 'Unnamed'\n    rating: int\n\nApplication(rating=5)\nApplication(name='name', rating=5)\nApplication()  # E: Missing named argument \"rating\" for \"Application\"\nApplication('name')  # E: Too many positional arguments for \"Application\" # E: Missing named argument \"rating\" for \"Application\"\nApplication('name', 123)  # E: Too many positional arguments for \"Application\"\nApplication('name', rating=123)  # E: Too many positional arguments for \"Application\"\nApplication(name=123, rating='name') # E: Argument \"name\" to \"Application\" has incompatible type \"int\"; expected \"str\" # E: Argument \"rating\" to \"Application\" has incompatible type \"str\"; expected \"int\"\nApplication(rating='name', name=123) # E: Argument \"rating\" to \"Application\" has incompatible type \"str\"; expected \"int\" # E: Argument \"name\" to \"Application\" has incompatible type \"int\"; expected \"str\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesOrderingKwOnlyOnField]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass Application:\n    name: str = 'Unnamed'\n    rating: int = field(kw_only=True)\n\nApplication(rating=5)\nApplication('name', rating=123)\nApplication(name='name', rating=5)\nApplication()  # E: Missing named argument \"rating\" for \"Application\"\nApplication('name')  # E: Missing named argument \"rating\" for \"Application\"\nApplication('name', 123)  # E: Too many positional arguments for \"Application\"\nApplication(123, rating='name') # E: Argument 1 to \"Application\" has incompatible type \"int\"; expected \"str\" # E: Argument \"rating\" to \"Application\" has incompatible type \"str\"; expected \"int\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesOrderingKwOnlyOnFieldFalse]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass Application:\n    name: str = 'Unnamed'\n    rating: int = field(kw_only=False)  # E: Attributes without a default cannot follow attributes with one\n\nApplication(name='name', rating=5)\nApplication('name', 123)\nApplication('name', rating=123)\nApplication()  # E: Missing positional argument \"name\" in call to \"Application\"\nApplication('name')  # E: Too few arguments for \"Application\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesOrderingKwOnlyWithSentinel]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass, KW_ONLY\n\n@dataclass\nclass Application:\n    _: KW_ONLY\n    name: str = 'Unnamed'\n    rating: int\n\nApplication(rating=5)\nApplication(name='name', rating=5)\nApplication()  # E: Missing named argument \"rating\" for \"Application\"\nApplication('name')  # E: Too many positional arguments for \"Application\" # E: Missing named argument \"rating\" for \"Application\"\nApplication('name', 123)  # E: Too many positional arguments for \"Application\"\nApplication('name', rating=123)  # E: Too many positional arguments for \"Application\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesOrderingKwOnlyWithSentinelAndFieldOverride]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass, field, KW_ONLY\n\n@dataclass\nclass Application:\n    _: KW_ONLY\n    name: str = 'Unnamed'\n    rating: int = field(kw_only=False)\n\nApplication(name='name', rating=5)\nApplication()  # E: Missing positional argument \"rating\" in call to \"Application\"\nApplication(123)\nApplication('name')  # E: Argument 1 to \"Application\" has incompatible type \"str\"; expected \"int\"\nApplication('name', 123)  # E: Too many positional arguments for \"Application\" \\\n                          # E: Argument 1 to \"Application\" has incompatible type \"str\"; expected \"int\" \\\n                          # E: Argument 2 to \"Application\" has incompatible type \"int\"; expected \"str\"\nApplication(123, rating=123)  # E: \"Application\" gets multiple values for keyword argument \"rating\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesOrderingKwOnlyWithSentinelAndSubclass]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass, field, KW_ONLY\n\n@dataclass\nclass Base:\n    x: str\n    _: KW_ONLY\n    y: int = 0\n    w: int = 1\n\n@dataclass\nclass D(Base):\n    z: str\n    a: str = \"a\"\n\nD(\"Hello\", \"World\")\nD(x=\"Hello\", z=\"World\")\nD(\"Hello\", \"World\", y=1, w=2, a=\"b\")\nD(\"Hello\")  # E: Missing positional argument \"z\" in call to \"D\"\nD()  # E: Missing positional arguments \"x\", \"z\" in call to \"D\"\nD(123, \"World\")  # E: Argument 1 to \"D\" has incompatible type \"int\"; expected \"str\"\nD(\"Hello\", False)  # E: Argument 2 to \"D\" has incompatible type \"bool\"; expected \"str\"\nD(123, False)  # E: Argument 1 to \"D\" has incompatible type \"int\"; expected \"str\" # E: Argument 2 to \"D\" has incompatible type \"bool\"; expected \"str\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesOrderingKwOnlyWithMultipleSentinel]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass, field, KW_ONLY\n\n@dataclass\nclass Base:\n    x: str\n    _: KW_ONLY\n    y: int = 0\n    __: KW_ONLY  # E: There may not be more than one field with the KW_ONLY type\n    w: int = 1\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesClassmethods]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Application:\n    name: str\n\n    @classmethod\n    def parse(cls, request: str) -> \"Application\":\n        return cls(name='...')\n\napp = Application.parse('')\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesOverloadsAndClassmethods]\nfrom dataclasses import dataclass\nfrom typing import overload, Union\n\n@dataclass\nclass A:\n    a: int\n    b: str\n\n    @classmethod\n    def other(cls) -> str:\n        return \"...\"\n\n    @overload\n    @classmethod\n    def foo(cls, x: int) -> int: ...\n\n    @overload\n    @classmethod\n    def foo(cls, x: str) -> str: ...\n\n    @classmethod\n    def foo(cls, x: Union[int, str]) -> Union[int, str]:\n        reveal_type(cls)            # N: Revealed type is \"type[__main__.A]\"\n        reveal_type(cls.other())    # N: Revealed type is \"builtins.str\"\n        return x\n\nreveal_type(A.foo(3))      # N: Revealed type is \"builtins.int\"\nreveal_type(A.foo(\"foo\"))  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testClassmethodShadowingFieldDoesNotCrash]\nfrom dataclasses import dataclass\n\n# This used to crash -- see #6217\n@dataclass\nclass Foo:\n    bar: str\n    @classmethod  # E: Name \"bar\" already defined on line 6\n    def bar(cls) -> \"Foo\":\n        return cls('asdf')\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesClassVars]\nfrom dataclasses import dataclass\nfrom typing import ClassVar\n\n@dataclass\nclass Application:\n  name: str\n\n  COUNTER: ClassVar[int] = 0\n\nreveal_type(Application)  # N: Revealed type is \"def (name: builtins.str) -> __main__.Application\"\napplication = Application(\"example\")\napplication.COUNTER = 1  # E: Cannot assign to class variable \"COUNTER\" via instance\nApplication.COUNTER = 1\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testTypeAliasInDataclassDoesNotCrash]\nfrom dataclasses import dataclass\nfrom typing import Callable\nfrom typing_extensions import TypeAlias\n\n@dataclass\nclass Foo:\n    x: int\n\n@dataclass\nclass One:\n    S: TypeAlias = Foo  # E: Type aliases inside dataclass definitions are not supported at runtime\n\na = One()\nreveal_type(a.S)  # N: Revealed type is \"def (x: builtins.int) -> __main__.Foo\"\na.S()  # E: Missing positional argument \"x\" in call to \"Foo\"\nreveal_type(a.S(5))  # N: Revealed type is \"__main__.Foo\"\n\n@dataclass\nclass Two:\n    S: TypeAlias = Callable[[int], str]  # E: Type aliases inside dataclass definitions are not supported at runtime\n\nc = Two()\nx = c.S\nreveal_type(x)  # N: Revealed type is \"typing._SpecialForm\"\n[builtins fixtures/dataclasses.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testDataclassOrdering]\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass Application:\n  name: str\n  rating: int\n\napp1 = Application('example-1', 5)\napp2 = Application('example-2', 5)\napp1 < app2\napp1 > app2\napp1 <= app2\napp1 >= app2\napp1 < 5  # E: Unsupported operand types for < (\"Application\" and \"int\")\napp1 > 5  # E: Unsupported operand types for > (\"Application\" and \"int\")\napp1 <= 5  # E: Unsupported operand types for <= (\"Application\" and \"int\")\napp1 >= 5  # E: Unsupported operand types for >= (\"Application\" and \"int\")\n\nclass SpecializedApplication(Application):\n  ...\n\napp3 = SpecializedApplication('example-3', 5)\napp1 < app3\napp1 > app3\napp1 <= app3\napp1 >= app3\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassOrderingWithoutEquality]\nfrom dataclasses import dataclass\n\n@dataclass(eq=False, order=True)  # E: \"eq\" must be True if \"order\" is True\nclass Application:\n   ...\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassOrderingWithCustomMethods]\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass Application:\n  def __lt__(self, other: 'Application') -> bool: # E: You may not have a custom \"__lt__\" method when \"order\" is True\n    ...\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassDefaultsInheritance]\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n@dataclass(order=True)\nclass Application:\n  id: Optional[int]\n  name: str\n\n@dataclass\nclass SpecializedApplication(Application):\n  rating: int = 0\n\nreveal_type(SpecializedApplication)  # N: Revealed type is \"def (id: builtins.int | None, name: builtins.str, rating: builtins.int =) -> __main__.SpecializedApplication\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassGenerics]\nfrom dataclasses import dataclass\nfrom typing import Generic, List, Optional, TypeVar\n\nT = TypeVar('T')\n\n@dataclass\nclass A(Generic[T]):\n  x: T\n  y: T\n  z: List[T]\n\n  def foo(self) -> List[T]:\n    return [self.x, self.y]\n\n  def bar(self) -> T:\n    return self.z[0]\n\n  def problem(self) -> T:\n    return self.z  # E: Incompatible return value type (got \"list[T]\", expected \"T\")\n\nreveal_type(A)  # N: Revealed type is \"def [T] (x: T`1, y: T`1, z: builtins.list[T`1]) -> __main__.A[T`1]\"\nA(1, 2, [\"a\", \"b\"])  # E: Cannot infer value of type parameter \"T\" of \"A\"\na = A(1, 2, [1, 2])\nreveal_type(a)  # N: Revealed type is \"__main__.A[builtins.int]\"\nreveal_type(a.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(a.y)  # N: Revealed type is \"builtins.int\"\nreveal_type(a.z)  # N: Revealed type is \"builtins.list[builtins.int]\"\ns: str = a.bar()  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassGenericCovariant]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\n\nT_co = TypeVar(\"T_co\", covariant=True)\n\n@dataclass\nclass MyDataclass(Generic[T_co]):\n    a: T_co\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassUntypedGenericInheritance]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass Base(Generic[T]):\n    attr: T\n\n@dataclass\nclass Sub(Base):\n    pass\n\nsub = Sub(attr=1)\nreveal_type(sub)  # N: Revealed type is \"__main__.Sub\"\nreveal_type(sub.attr)  # N: Revealed type is \"Any\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassGenericSubtype]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass Base(Generic[T]):\n    attr: T\n\nS = TypeVar(\"S\")\n\n@dataclass\nclass Sub(Base[S]):\n    pass\n\nsub_int = Sub[int](attr=1)\nreveal_type(sub_int)  # N: Revealed type is \"__main__.Sub[builtins.int]\"\nreveal_type(sub_int.attr)  # N: Revealed type is \"builtins.int\"\n\nsub_str = Sub[str](attr='ok')\nreveal_type(sub_str)  # N: Revealed type is \"__main__.Sub[builtins.str]\"\nreveal_type(sub_str.attr)  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassGenericInheritance]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\n@dataclass\nclass Base(Generic[T1, T2, T3]):\n    one: T1\n    two: T2\n    three: T3\n\n@dataclass\nclass Sub(Base[int, str, float]):\n    pass\n\nsub = Sub(one=1, two='ok', three=3.14)\nreveal_type(sub)  # N: Revealed type is \"__main__.Sub\"\nreveal_type(sub.one)  # N: Revealed type is \"builtins.int\"\nreveal_type(sub.two)  # N: Revealed type is \"builtins.str\"\nreveal_type(sub.three)  # N: Revealed type is \"builtins.float\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassMultiGenericInheritance]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass Base(Generic[T]):\n    base_attr: T\n\nS = TypeVar(\"S\")\n\n@dataclass\nclass Middle(Base[int], Generic[S]):\n    middle_attr: S\n\n@dataclass\nclass Sub(Middle[str]):\n    pass\n\nsub = Sub(base_attr=1, middle_attr='ok')\nreveal_type(sub)  # N: Revealed type is \"__main__.Sub\"\nreveal_type(sub.base_attr)  # N: Revealed type is \"builtins.int\"\nreveal_type(sub.middle_attr)  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassGenericsClassmethod]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\n@dataclass\nclass A(Generic[T]):\n  x: T\n\n  @classmethod\n  def foo(cls) -> None:\n      reveal_type(cls)  # N: Revealed type is \"type[__main__.A[T`1]]\"\n      cls.x  # E: Cannot access instance-only attribute \"x\" on class object \\\n             # E: Access to generic instance variables via class is ambiguous\n\n  @classmethod\n  def other(cls, x: T) -> A[T]: ...\n\nreveal_type(A(0).other)  # N: Revealed type is \"def (x: builtins.int) -> __main__.A[builtins.int]\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesForwardRefs]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n  b: 'B'\n\n@dataclass\nclass B:\n  x: int\n\nreveal_type(A)  # N: Revealed type is \"def (b: __main__.B) -> __main__.A\"\nA(b=B(42))\nA(b=42)  # E: Argument \"b\" to \"A\" has incompatible type \"int\"; expected \"B\"\n\n[builtins fixtures/dataclasses.pyi]\n\n\n[case testDataclassesInitVars]\nfrom dataclasses import InitVar, dataclass\n\n@dataclass\nclass Application:\n  name: str\n  database_name: InitVar[str]\n\nreveal_type(Application)  # N: Revealed type is \"def (name: builtins.str, database_name: builtins.str) -> __main__.Application\"\napp = Application(\"example\", 42)  # E: Argument 2 to \"Application\" has incompatible type \"int\"; expected \"str\"\napp = Application(\"example\", \"apps\")\napp.name\napp.database_name  # E: \"Application\" has no attribute \"database_name\"\n\n\n@dataclass\nclass SpecializedApplication(Application):\n  rating: int\n\nreveal_type(SpecializedApplication)  # N: Revealed type is \"def (name: builtins.str, database_name: builtins.str, rating: builtins.int) -> __main__.SpecializedApplication\"\napp = SpecializedApplication(\"example\", \"apps\", \"five\")  # E: Argument 3 to \"SpecializedApplication\" has incompatible type \"str\"; expected \"int\"\napp = SpecializedApplication(\"example\", \"apps\", 5)\napp.name\napp.rating\napp.database_name  # E: \"SpecializedApplication\" has no attribute \"database_name\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesInitVarsAndDefer]\nfrom dataclasses import InitVar, dataclass\n\ndefer: Yes\n\n@dataclass\nclass Application:\n  name: str\n  database_name: InitVar[str]\n\nreveal_type(Application)  # N: Revealed type is \"def (name: builtins.str, database_name: builtins.str) -> __main__.Application\"\napp = Application(\"example\", 42)  # E: Argument 2 to \"Application\" has incompatible type \"int\"; expected \"str\"\napp = Application(\"example\", \"apps\")\napp.name\napp.database_name  # E: \"Application\" has no attribute \"database_name\"\n\nclass Yes: ...\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesNoInitInitVarInheritance]\nfrom dataclasses import dataclass, field, InitVar\n\n@dataclass\nclass Super:\n    foo: InitVar = field(init=False)\n\n@dataclass\nclass Sub(Super):\n    bar: int\n\nsub = Sub(5)\nsub.foo  # E: \"Sub\" has no attribute \"foo\"\nsub.bar\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassFactory]\nfrom typing import Type, TypeVar\nfrom dataclasses import dataclass\n\nT = TypeVar('T', bound='A')\n\n@dataclass\nclass A:\n    @classmethod\n    def make(cls: Type[T]) -> T:\n        reveal_type(cls)  # N: Revealed type is \"type[T`-1]\"\n        reveal_type(cls())  # N: Revealed type is \"T`-1\"\n        return cls()\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesInitVarOverride]\nimport dataclasses\n\n@dataclasses.dataclass\nclass A:\n    a: dataclasses.InitVar[int]\n    _a: int = dataclasses.field(init=False)\n\n    def __post_init__(self, a):\n        self._a = a\n\n@dataclasses.dataclass(init=False)\nclass B(A):\n    b: dataclasses.InitVar[int]\n    _b: int = dataclasses.field(init=False)\n\n    def __init__(self, b):\n        super().__init__(b+1)\n        self._b = b\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesInitVarNoOverride]\nimport dataclasses\n\n@dataclasses.dataclass\nclass A:\n    a: dataclasses.InitVar[int]\n    _a: int = dataclasses.field(init=False)\n\n    def __post_init__(self, a):\n        self._a = a\n\n@dataclasses.dataclass(init=True)\nclass B(A):\n    b: dataclasses.InitVar[int]\n    _b: int = dataclasses.field(init=False)\n\n    def __post_init__(self, a, b):\n        self._a = a\n        self._b = b\n\nB(1, 2)\nB(1, 'a') # E: Argument 2 to \"B\" has incompatible type \"str\"; expected \"int\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesInitVarPostInitOverride]\nimport dataclasses\n\n@dataclasses.dataclass\nclass A:\n    a: dataclasses.InitVar[int]\n    _a: int = dataclasses.field(init=False)\n\n    def __post_init__(self, a: int) -> None:\n        self._a = a\n\n@dataclasses.dataclass\nclass B(A):\n    b: int = dataclasses.field(init=False)\n\n    def __post_init__(self, a: int) -> None:\n        super().__post_init__(a)\n        self.b = a + 1\n\n@dataclasses.dataclass(init=False)\nclass C(B):\n    c: int\n\n    def __init__(self, a: int, c: int) -> None:\n        super().__init__(a)\n        self.c = c + self.b\n\nA(1)\nB(1)\nB(1, 2)  # E: Too many arguments for \"B\"\nC(1, 2)\nC(1, 'a')  # E: Argument 2 to \"C\" has incompatible type \"str\"; expected \"int\"\n\n[builtins fixtures/primitives.pyi]\n\n[case testDataclassesInitVarIncremental]\nimport a\n\n[file a.py]\nimport dataclasses\nfrom b import A\n\n@dataclasses.dataclass\nclass B(A):\n    b: int = dataclasses.field(init=False)\n\n    def __post_init__(self, a: int) -> None:\n        super().__post_init__(a)\n        self.b = a + 1\n\n[file a.py.2]\nimport dataclasses\nfrom b import A\n\n@dataclasses.dataclass\nclass B(A):\n    b: int = dataclasses.field(init=False)\n\n    def __post_init__(self, a: int) -> None:\n        super().__post_init__(a)\n        self.b = a + 2\n\nreveal_type(B)\n\n[file b.py]\nimport dataclasses\n\n@dataclasses.dataclass\nclass A:\n    a: dataclasses.InitVar[int]\n    _a: int = dataclasses.field(init=False)\n\n    def __post_init__(self, a: int) -> None:\n        self._a = a\n[out2]\ntmp/a.py:12: note: Revealed type is \"def (a: builtins.int) -> a.B\"\n\n[builtins fixtures/primitives.pyi]\n\n\n[case testNoComplainFieldNone]\n# flags: --no-strict-optional\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n@dataclass\nclass Foo:\n    bar: Optional[int] = field(default=None)\n[builtins fixtures/dataclasses.pyi]\n[out]\n\n[case testNoComplainFieldNoneStrict]\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\n@dataclass\nclass Foo:\n    bar: Optional[int] = field(default=None)\n[builtins fixtures/dataclasses.pyi]\n[out]\n\n[case testDisallowUntypedWorksForward]\n# flags: --disallow-untyped-defs\nfrom dataclasses import dataclass\nfrom typing import List\n\n@dataclass\nclass B:\n    x: C\n\nclass C(List[C]):\n    pass\n\nreveal_type(B)  # N: Revealed type is \"def (x: __main__.C) -> __main__.B\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDisallowUntypedWorksForwardBad]\n# flags: --disallow-untyped-defs\nfrom dataclasses import dataclass\n\n@dataclass\nclass B:\n    x: Undefined  # E: Name \"Undefined\" is not defined\n    y = undefined()  # E: Name \"undefined\" is not defined\n\nreveal_type(B)  # N: Revealed type is \"def (x: Any) -> __main__.B\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testMemberExprWorksAsField]\nimport dataclasses\n\n@dataclasses.dataclass\nclass A:\n    x: int = dataclasses.field(metadata={\"doc\": \"foo\"})\n    y: str\n\n@dataclasses.dataclass\nclass B:\n    x: int = dataclasses.field(init=False, default=1)\n    y: str\n\n@dataclasses.dataclass\nclass C:\n    x: int = dataclasses.field(default=1)\n    y: str = dataclasses.field(metadata={\"doc\": \"foo\"})  # E: Attributes without a default cannot follow attributes with one\n[builtins fixtures/dict.pyi]\n\n[case testDataclassOrderingDeferred]\nfrom dataclasses import dataclass\n\ndefer: Yes\n\n@dataclass(order=True)\nclass Application:\n  name: str\n  rating: int\n\na = Application('', 0)\nb = Application('', 0)\na < b\n\nclass Yes: ...\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassFieldDeferred]\nfrom dataclasses import field, dataclass\n\n@dataclass\nclass C:\n    x: int = field(default=func())\n\ndef func() -> int: ...\nC('no')  # E: Argument 1 to \"C\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassFieldDeferredFrozen]\nfrom dataclasses import field, dataclass\n\n@dataclass(frozen=True)\nclass C:\n    x: int = field(default=func())\n\ndef func() -> int: ...\nc: C\nc.x = 1  # E: Property \"x\" defined in \"C\" is read-only\n[builtins fixtures/dataclasses.pyi]\n\n[case testTypeInDataclassDeferredStar]\nimport lib\n[file lib.py]\nfrom dataclasses import dataclass\nMYPY = False\nif MYPY:  # Force deferral\n    from other import *\n\n@dataclass\nclass C:\n    total: int\n\nC()  # E: Missing positional argument \"total\" in call to \"C\"\nC('no')  # E: Argument 1 to \"C\" has incompatible type \"str\"; expected \"int\"\n[file other.py]\nimport lib\n[builtins fixtures/dataclasses.pyi]\n\n[case testDeferredDataclassInitSignature]\n# flags: --no-strict-optional\nfrom dataclasses import dataclass\nfrom typing import Optional, Type\n\n@dataclass\nclass C:\n    x: Optional[int] = None\n    y: Type[Deferred] = Deferred\n\n    @classmethod\n    def default(cls) -> C:\n        return cls(x=None, y=None)\n\nclass Deferred: pass\n[builtins fixtures/dataclasses.pyi]\n\n[case testDeferredDataclassInitSignatureSubclass]\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n@dataclass\nclass B:\n    x: Optional[C]\n\n@dataclass\nclass C(B):\n    y: str\n\na = C(None, 'abc')\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesDefaultsIncremental]\nimport a\n\n[file a.py]\nfrom dataclasses import dataclass\nfrom b import Person\n\n@dataclass\nclass Asdf(Person):\n    c: str = 'test'\n\n[file a.py.2]\nfrom dataclasses import dataclass\nfrom b import Person\n\n@dataclass\nclass Asdf(Person):\n    c: str = 'test'\n\n# asdf\n\n[file b.py]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Person:\n    b: int\n    a: str = 'test'\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesDefaultsMroOtherFile]\nimport a\n\n[file a.py]\nfrom dataclasses import dataclass\nfrom b import A1, A2\n\n@dataclass\nclass Asdf(A1, A2):  # E: Attributes without a default cannot follow attributes with one\n    pass\n\n[file b.py]\nfrom dataclasses import dataclass\n\n# a bunch of blank lines to make sure the error doesn't accidentally line up...\n\n\n\n@dataclass\nclass A1:\n    a: int\n\n@dataclass\nclass A2:\n    b: str = 'test'\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesInheritingDuplicateField]\n# see mypy issue #7792\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    x: int = 0\n    x: int = 0  # E: Name \"x\" already defined on line 6\n\n@dataclass\nclass B(A):\n    pass\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassInheritanceNoAnnotation]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    foo: int\n\nx = 0\n@dataclass\nclass B(A):\n    foo = x\n\nreveal_type(B)  # N: Revealed type is \"def (foo: builtins.int) -> __main__.B\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassInheritanceNoAnnotation2]\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass A:\n    foo: int\n\n@dataclass(frozen=True)\nclass B(A):\n    @property  # E: Dataclass attribute may only be overridden by another attribute\n    def foo(self) -> int: pass\n\nreveal_type(B)  # N: Revealed type is \"def (foo: builtins.int) -> __main__.B\"\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassHasAttributeWithFields]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    pass\n\nreveal_type(A.__dataclass_fields__)  # N: Revealed type is \"builtins.dict[builtins.str, dataclasses.Field[Any]]\"\n\n[builtins fixtures/dict.pyi]\n\n[case testDataclassCallableFieldAccess]\nfrom dataclasses import dataclass\nfrom typing import Callable\n\n@dataclass\nclass A:\n    x: Callable[[int], int]\n    y: Callable[[int], int] = lambda i: i\n\na = A(lambda i:i)\nx: int = a.x(0)\ny: str = a.y(0) # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nreveal_type(a.x)  # N: Revealed type is \"def (builtins.int) -> builtins.int\"\nreveal_type(a.y)  # N: Revealed type is \"def (builtins.int) -> builtins.int\"\nreveal_type(A.y)  # N: Revealed type is \"def (builtins.int) -> builtins.int\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassCallableFieldAssignment]\nfrom dataclasses import dataclass\nfrom typing import Callable\n\n@dataclass\nclass A:\n    x: Callable[[int], int]\n\ndef x(i: int) -> int:\n    return i\ndef x2(s: str) -> str:\n    return s\n\na = A(lambda i:i)\na.x = x\na.x = x2 # E: Incompatible types in assignment (expression has type \"Callable[[str], str]\", variable has type \"Callable[[int], int]\")\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassFieldDoesNotFailOnKwargsUnpacking]\n# https://github.com/python/mypy/issues/10879\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass Foo:\n    bar: float = field(**{\"repr\": False})\n[out]\nmain:6: error: Unpacking **kwargs in \"field()\" is not supported\nmain:6: error: No overload variant of \"field\" matches argument type \"dict[str, bool]\"\nmain:6: note: Possible overload variants:\nmain:6: note:     def [_T] field(*, default: _T, init: bool = ..., repr: bool = ..., hash: bool | None = ..., compare: bool = ..., metadata: Mapping[str, Any] | None = ..., kw_only: bool = ...) -> _T\nmain:6: note:     def [_T] field(*, default_factory: Callable[[], _T], init: bool = ..., repr: bool = ..., hash: bool | None = ..., compare: bool = ..., metadata: Mapping[str, Any] | None = ..., kw_only: bool = ...) -> _T\nmain:6: note:     def field(*, init: bool = ..., repr: bool = ..., hash: bool | None = ..., compare: bool = ..., metadata: Mapping[str, Any] | None = ..., kw_only: bool = ...) -> Any\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassFieldWithPositionalArguments]\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass C:\n    x: int = field(0)  # E: \"field()\" does not accept positional arguments \\\n                       # E: No overload variant of \"field\" matches argument type \"int\" \\\n                       # N: Possible overload variants: \\\n                       # N:     def [_T] field(*, default: _T, init: bool = ..., repr: bool = ..., hash: bool | None = ..., compare: bool = ..., metadata: Mapping[str, Any] | None = ..., kw_only: bool = ...) -> _T \\\n                       # N:     def [_T] field(*, default_factory: Callable[[], _T], init: bool = ..., repr: bool = ..., hash: bool | None = ..., compare: bool = ..., metadata: Mapping[str, Any] | None = ..., kw_only: bool = ...) -> _T \\\n                       # N:     def field(*, init: bool = ..., repr: bool = ..., hash: bool | None = ..., compare: bool = ..., metadata: Mapping[str, Any] | None = ..., kw_only: bool = ...) -> Any\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassFieldWithTypedDictUnpacking]\nfrom dataclasses import dataclass, field\nfrom typing import TypedDict\n\nclass FieldKwargs(TypedDict):\n    repr: bool\n\nfield_kwargs: FieldKwargs = {\"repr\": False}\n\n@dataclass\nclass Foo:\n    bar: float = field(**field_kwargs)  # E: Unpacking **kwargs in \"field()\" is not supported\n\nreveal_type(Foo(bar=1.5))  # N: Revealed type is \"__main__.Foo\"\n[builtins fixtures/dataclasses.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDataclassWithSlotsArg]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n\n@dataclass(slots=True)\nclass Some:\n    x: int\n\n    def __init__(self, x: int) -> None:\n        self.x = x\n        self.y = 0  # E: Trying to assign name \"y\" that is not in \"__slots__\" of type \"__main__.Some\"\n\n    def __post_init__(self) -> None:\n        self.y = 1  # E: Trying to assign name \"y\" that is not in \"__slots__\" of type \"__main__.Some\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassWithSlotsDef]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n\n@dataclass(slots=False)\nclass Some:\n    __slots__ = ('x',)\n    x: int\n\n    def __init__(self, x: int) -> None:\n        self.x = x\n        self.y = 0  # E: Trying to assign name \"y\" that is not in \"__slots__\" of type \"__main__.Some\"\n\n    def __post_init__(self) -> None:\n        self.y = 1  # E: Trying to assign name \"y\" that is not in \"__slots__\" of type \"__main__.Some\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassWithSlotsDerivedFromNonSlot]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n\nclass A:\n    pass\n\n@dataclass(slots=True)\nclass B(A):\n    x: int\n\n    def __post_init__(self) -> None:\n        self.y = 42\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassWithSlotsConflict]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n\n@dataclass(slots=True)\nclass Some:  # E: \"Some\" both defines \"__slots__\" and is used with \"slots=True\"\n    __slots__ = ('x',)\n    x: int\n\n@dataclass(slots=True)\nclass EmptyDef:  # E: \"EmptyDef\" both defines \"__slots__\" and is used with \"slots=True\"\n    __slots__ = ()\n    x: int\n\nslots = ('x',)\n\n@dataclass(slots=True)\nclass DynamicDef:  # E: \"DynamicDef\" both defines \"__slots__\" and is used with \"slots=True\"\n    __slots__ = slots\n    x: int\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassWithSlotsArgBefore310]\n# flags: --python-version 3.9\nfrom dataclasses import dataclass\n\n@dataclass(slots=True)  # E: Keyword argument \"slots\" for \"dataclass\" is only valid in Python 3.10 and higher\nclass Some:\n    x: int\n\n# Possible conflict:\n@dataclass(slots=True)  # E: Keyword argument \"slots\" for \"dataclass\" is only valid in Python 3.10 and higher\nclass Other:\n    __slots__ = ('x',)\n    x: int\n[builtins fixtures/dataclasses.pyi]\n\n\n[case testDataclassWithSlotsRuntimeAttr]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n\n@dataclass(slots=True)\nclass Some:\n    x: int\n    y: str\n    z: bool\n\nreveal_type(Some.__slots__)  # N: Revealed type is \"tuple[builtins.str, builtins.str, builtins.str]\"\n\n@dataclass(slots=True)\nclass Other:\n    x: int\n    y: str\n\nreveal_type(Other.__slots__)  # N: Revealed type is \"tuple[builtins.str, builtins.str]\"\n\n\n@dataclass\nclass NoSlots:\n    x: int\n    y: str\n\nNoSlots.__slots__  # E: \"type[NoSlots]\" has no attribute \"__slots__\"\n[builtins fixtures/dataclasses.pyi]\n\n\n[case testSlotsDefinitionWithTwoPasses1]\n# flags: --python-version 3.10\n# https://github.com/python/mypy/issues/11821\nfrom typing import TypeVar, Protocol, Generic\nfrom dataclasses import dataclass\n\nC = TypeVar(\"C\", bound=\"Comparable\")\n\nclass Comparable(Protocol):\n    pass\n\nV = TypeVar(\"V\", bound=Comparable)\n\n@dataclass(slots=True)\nclass Node(Generic[V]):  # Error was here\n    data: V\n[builtins fixtures/dataclasses.pyi]\n\n[case testSlotsDefinitionWithTwoPasses2]\n# flags: --python-version 3.10\nfrom typing import TypeVar, Protocol, Generic\nfrom dataclasses import dataclass\n\nC = TypeVar(\"C\", bound=\"Comparable\")\n\nclass Comparable(Protocol):\n    pass\n\nV = TypeVar(\"V\", bound=Comparable)\n\n@dataclass(slots=True)  # Explicit slots are still not ok:\nclass Node(Generic[V]):  # E: \"Node\" both defines \"__slots__\" and is used with \"slots=True\"\n    __slots__ = ('data',)\n    data: V\n[builtins fixtures/dataclasses.pyi]\n\n[case testSlotsDefinitionWithTwoPasses3]\n# flags: --python-version 3.10\nfrom typing import TypeVar, Protocol, Generic\nfrom dataclasses import dataclass\n\nC = TypeVar(\"C\", bound=\"Comparable\")\n\nclass Comparable(Protocol):\n    pass\n\nV = TypeVar(\"V\", bound=Comparable)\n\n@dataclass(slots=True)  # Explicit slots are still not ok, even empty ones:\nclass Node(Generic[V]):  # E: \"Node\" both defines \"__slots__\" and is used with \"slots=True\"\n    __slots__ = ()\n    data: V\n[builtins fixtures/dataclasses.pyi]\n\n[case testSlotsDefinitionWithTwoPasses4]\n# flags: --python-version 3.10\nimport dataclasses as dtc\n\nPublishedMessagesVar = dict[int, 'PublishedMessages']\n\n@dtc.dataclass(frozen=True, slots=True)\nclass PublishedMessages:\n    left: int\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassSlotsWithDeferredBase]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n\n@dataclass\nclass A(B): ...\n\n@dataclass\nclass B: ...\n\n@dataclass(slots=True)\nclass C: ...\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesAnyInherit]\nfrom dataclasses import dataclass\nfrom typing import Any\nB: Any\n@dataclass\nclass A(B):\n    a: int\n@dataclass\nclass C(B):\n    generated_args: int\n    generated_kwargs: int\n\nA(a=1, b=2)\nA(1)\nA(a=\"foo\")  # E: Argument \"a\" to \"A\" has incompatible type \"str\"; expected \"int\"\nC(generated_args=\"foo\", generated_kwargs=\"bar\")  # E: Argument \"generated_args\" to \"C\" has incompatible type \"str\"; expected \"int\" \\\n                                                 # E: Argument \"generated_kwargs\" to \"C\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesCallableFrozen]\nfrom dataclasses import dataclass\nfrom typing import Any, Callable\n@dataclass(frozen=True)\nclass A:\n    a: Callable[..., None]\n\ndef func() -> None:\n    pass\n\nreveal_type(A.a)  # N: Revealed type is \"def (*Any, **Any)\"\nA(a=func).a()\nA(a=func).a = func  # E: Property \"a\" defined in \"A\" is read-only\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassInFunctionDoesNotCrash]\nfrom dataclasses import dataclass\n\ndef foo() -> None:\n    @dataclass\n    class Foo:\n        foo: int\n        # This used to crash (see #8703)\n        # The return type of __call__ here needs to be something undefined\n        # In order to trigger the crash that existed prior to #12762\n        def __call__(self) -> asdf: ...  # E: Name \"asdf\" is not defined\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesMultipleInheritanceWithNonDataclass]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    prop_a: str\n\n@dataclass\nclass B:\n    prop_b: bool\n\nclass Derived(A, B):\n    pass\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassGenericInheritance2]\nfrom dataclasses import dataclass\nfrom typing import Any, Callable, Generic, TypeVar, List\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\n@dataclass\nclass Parent(Generic[T]):\n    f: Callable[[T], Any]\n\n@dataclass\nclass Child(Parent[T]): ...\n\nclass A: ...\ndef func(obj: A) -> bool: ...\n\nreveal_type(Child[A](func).f)  # N: Revealed type is \"def (__main__.A) -> Any\"\n\n@dataclass\nclass Parent2(Generic[T]):\n    a: List[T]\n\n@dataclass\nclass Child2(Generic[T, S], Parent2[S]):\n    b: List[T]\n\nreveal_type(Child2([A()], [1]).a)  # N: Revealed type is \"builtins.list[__main__.A]\"\nreveal_type(Child2[int, A]([A()], [1]).b)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassInheritOptionalType]\nfrom dataclasses import dataclass\nfrom typing import Any, Callable, Generic, TypeVar, List, Optional\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass Parent(Generic[T]):\n    x: Optional[str]\n@dataclass\nclass Child(Parent):\n    y: Optional[int]\nChild(x=1, y=1)  # E: Argument \"x\" to \"Child\" has incompatible type \"int\"; expected \"str | None\"\nChild(x='', y='')  # E: Argument \"y\" to \"Child\" has incompatible type \"str\"; expected \"int | None\"\nChild(x='', y=1)\nChild(x=None, y=None)\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassGenericInheritanceSpecialCase1]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar, List\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass Parent(Generic[T]):\n    x: List[T]\n\n@dataclass\nclass Child1(Parent[\"Child2\"]): ...\n\n@dataclass\nclass Child2(Parent[\"Child1\"]): ...\n\ndef f(c: Child2) -> None:\n    reveal_type(Child1([c]).x)  # N: Revealed type is \"builtins.list[__main__.Child2]\"\n\ndef g(c: Child1) -> None:\n    reveal_type(Child2([c]).x)  # N: Revealed type is \"builtins.list[__main__.Child1]\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassGenericInheritanceSpecialCase2]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n# A subclass might be analyzed before base in import cycles.  They are\n# defined here in reversed order to simulate this.\n\n@dataclass\nclass Child1(Parent[\"Child2\"]):\n    x: int\n\n@dataclass\nclass Child2(Parent[\"Child1\"]):\n    y: int\n\n@dataclass\nclass Parent(Generic[T]):\n    key: str\n\nChild1(x=1, key='')\nChild2(y=1, key='')\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassGenericWithBound]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\", bound=\"C\")\n\n@dataclass\nclass C(Generic[T]):\n    x: int\n\nc: C[C]\nd: C[str]  # E: Type argument \"str\" of \"C\" must be a subtype of \"C[Any]\"\nC(x=2)\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassGenericBoundToInvalidTypeVarDoesNotCrash]\nimport dataclasses\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\", bound=\"NotDefined\")  # E: Name \"NotDefined\" is not defined\n\n@dataclasses.dataclass\nclass C(Generic[T]):\n    x: float\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassInitVarCannotBeSet]\nfrom dataclasses import dataclass, InitVar\n\n@dataclass\nclass C:\n    x: InitVar[int] = 0\n    y: InitVar[str] = ''\n\n    def f(self) -> None:\n        # This works at runtime, but it seems like an abuse of the InitVar\n        # feature and thus we don't support it\n        self.x = 1  # E: \"C\" has no attribute \"x\"\n        self.y: str = 'x'  # E: \"C\" has no attribute \"y\"\n\nc = C()\nc2 = C(x=1)\nc.x  # E: \"C\" has no attribute \"x\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassCheckTypeVarBounds]\nfrom dataclasses import dataclass\nfrom typing import ClassVar, Protocol, Dict, TypeVar, Generic\n\nclass DataclassProtocol(Protocol):\n    __dataclass_fields__: ClassVar[Dict]\n\nT = TypeVar(\"T\", bound=DataclassProtocol)\n\n@dataclass\nclass MyDataclass:\n    x: int = 1\n\nclass MyGeneric(Generic[T]): ...\nclass MyClass(MyGeneric[MyDataclass]): ...\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassWithMatchArgs]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n@dataclass\nclass One:\n    bar: int\n    baz: str\no: One\nreveal_type(o.__match_args__)  # N: Revealed type is \"tuple[Literal['bar'], Literal['baz']]\"\n@dataclass(match_args=True)\nclass Two:\n    bar: int\nt: Two\nreveal_type(t.__match_args__)  # N: Revealed type is \"tuple[Literal['bar']]\"\n@dataclass\nclass Empty:\n    ...\ne: Empty\nreveal_type(e.__match_args__)  # N: Revealed type is \"tuple[()]\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassWithMatchArgsAndKwOnly]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass, field\n@dataclass(kw_only=True)\nclass One:\n    a: int\n    b: str\nreveal_type(One.__match_args__)  # N: Revealed type is \"tuple[()]\"\n\n@dataclass(kw_only=True)\nclass Two:\n    a: int = field(kw_only=False)\n    b: str\nreveal_type(Two.__match_args__)  # N: Revealed type is \"tuple[Literal['a']]\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassWithoutMatchArgs]\n# flags: --python-version 3.10\nfrom dataclasses import dataclass\n@dataclass(match_args=False)\nclass One:\n    bar: int\n    baz: str\no: One\nreveal_type(o.__match_args__)  # E: \"One\" has no attribute \"__match_args__\" \\\n                               # N: Revealed type is \"Any\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassWithMatchArgsOldVersion]\n# flags: --python-version 3.9\nfrom dataclasses import dataclass\n@dataclass(match_args=True)\nclass One:\n    bar: int\no: One\nreveal_type(o.__match_args__)  # E: \"One\" has no attribute \"__match_args__\" \\\n                               # N: Revealed type is \"Any\"\n@dataclass\nclass Two:\n    bar: int\nt: Two\nreveal_type(t.__match_args__)  # E: \"Two\" has no attribute \"__match_args__\" \\\n                               # N: Revealed type is \"Any\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testFinalInDataclass]\nfrom dataclasses import dataclass\nfrom typing import Final\n\n@dataclass\nclass FirstClass:\n    FIRST_CONST: Final = 3  # OK\n\n@dataclass\nclass SecondClass:\n    SECOND_CONST: Final = FirstClass.FIRST_CONST  # E: Need type argument for Final[...] with non-literal default in dataclass\n\nreveal_type(FirstClass().FIRST_CONST)  # N: Revealed type is \"Literal[3]?\"\nFirstClass().FIRST_CONST = 42  # E: Cannot assign to final attribute \"FIRST_CONST\"\nreveal_type(SecondClass().SECOND_CONST)  # N: Revealed type is \"Literal[3]?\"\nSecondClass().SECOND_CONST = 42  # E: Cannot assign to final attribute \"SECOND_CONST\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassFieldsProtocol]\nfrom dataclasses import dataclass\nfrom typing import Any, Protocol\n\nclass ConfigProtocol(Protocol):\n    __dataclass_fields__: dict[str, Any]\n\ndef takes_cp(cp: ConfigProtocol): ...\n\n@dataclass\nclass MyDataclass:\n    x: int = 3\n\ntakes_cp(MyDataclass)\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassTypeAnnotationAliasUpdated]\nimport a\n[file a.py]\nfrom dataclasses import dataclass\nfrom b import B\n\n@dataclass\nclass D:\n    x: B\n\nreveal_type(D)  # N: Revealed type is \"def (x: builtins.list[b.C]) -> a.D\"\n[file b.py]\nfrom typing import List\nimport a\nclass CC: ...\nclass C(CC): ...\nB = List[C]\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassSelfType]\nfrom dataclasses import dataclass\nfrom typing import Self, TypeVar, Generic, Optional\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass LinkedList(Generic[T]):\n    value: T\n    next: Optional[Self] = None\n\n    def meth(self) -> None:\n        reveal_type(self.next)  # N: Revealed type is \"Self`0 | None\"\n\nl_int: LinkedList[int] = LinkedList(1, LinkedList(\"no\", None))  # E: Argument 1 to \"LinkedList\" has incompatible type \"str\"; expected \"int\"\n\n@dataclass\nclass SubLinkedList(LinkedList[int]): ...\n\nlst = SubLinkedList(1, LinkedList(2))  # E: Argument 2 to \"SubLinkedList\" has incompatible type \"LinkedList[int]\"; expected \"SubLinkedList | None\"\nreveal_type(lst.next)  # N: Revealed type is \"__main__.SubLinkedList | None\"\nreveal_type(SubLinkedList)  # N: Revealed type is \"def (value: builtins.int, next: __main__.SubLinkedList | None =) -> __main__.SubLinkedList\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testNoCrashOnNestedGenericCallable]\nfrom dataclasses import dataclass\nfrom typing import Generic, TypeVar, Callable\n\nT = TypeVar('T')\nR = TypeVar('R')\nX = TypeVar('X')\n\n@dataclass\nclass Box(Generic[T]):\n    inner: T\n\n@dataclass\nclass Cont(Generic[R]):\n    run: Box[Callable[[X], R]]\n\ndef const_two(x: T) -> str:\n    return \"two\"\n\nc = Cont(Box(const_two))\nreveal_type(c)  # N: Revealed type is \"__main__.Cont[builtins.str]\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testNoCrashOnSelfWithForwardRefGenericDataclass]\nfrom typing import Generic, Sequence, TypeVar, Self\nfrom dataclasses import dataclass\n\n_T = TypeVar('_T', bound=\"Foo\")\n\n@dataclass\nclass Foo:\n    foo: int\n\n@dataclass\nclass Element(Generic[_T]):\n    elements: Sequence[Self]\n\n@dataclass\nclass Bar(Foo): ...\ne: Element[Bar]\nreveal_type(e.elements)  # N: Revealed type is \"typing.Sequence[__main__.Element[__main__.Bar]]\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testIfConditionsInDefinition]\n# flags: --python-version 3.11 --always-true TRUTH\nfrom dataclasses import dataclass\nfrom typing import TYPE_CHECKING\n\nTRUTH = False  # Is set to --always-true\n\n@dataclass\nclass Foo:\n    if TYPE_CHECKING:\n        present_1: int\n    else:\n        skipped_1: int\n    if True:  # Mypy does not know if it is True or False, so the block is used\n        present_2: int\n    if False:  # Mypy does not know if it is True or False, so the block is used\n        present_3: int\n    if not TRUTH:\n        skipped_2: int\n    elif 123:\n        present_4: int\n    elif TRUTH:\n        present_5: int\n    else:\n        skipped_3: int\n\nFoo(\n    present_1=1,\n    present_2=2,\n    present_3=3,\n    present_4=4,\n    present_5=5,\n)\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testReplace]\nfrom dataclasses import dataclass, replace, InitVar\nfrom typing import ClassVar\n\n@dataclass\nclass A:\n    x: int\n    q: InitVar[int]\n    q2: InitVar[int] = 0\n    c: ClassVar[int]\n\n\na = A(x=42, q=7)\na2 = replace(a)  # E: Missing named argument \"q\" for \"replace\" of \"A\"\na2 = replace(a, q=42)\na2 = replace(a, x=42, q=42)\na2 = replace(a, x=42, q=42, c=7)  # E: Unexpected keyword argument \"c\" for \"replace\" of \"A\"\na2 = replace(a, x='42', q=42)  # E: Argument \"x\" to \"replace\" of \"A\" has incompatible type \"str\"; expected \"int\"\na2 = replace(a, q='42')  # E: Argument \"q\" to \"replace\" of \"A\" has incompatible type \"str\"; expected \"int\"\nreveal_type(a2)  # N: Revealed type is \"__main__.A\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testReplaceUnion]\nfrom typing import Generic, Union, TypeVar\nfrom dataclasses import dataclass, replace, InitVar\n\nT = TypeVar('T')\n\n@dataclass\nclass A(Generic[T]):\n    x: T  # exercises meet(T=int, int) = int\n    y: bool  # exercises meet(bool, int) = bool\n    z: str  # exercises meet(str, bytes) = Never\n    w: dict  # exercises meet(dict, Never) = Never\n    init_var: InitVar[int]  # exercises (non-optional, optional) = non-optional\n\n@dataclass\nclass B:\n    x: int\n    y: int\n    z: bytes\n    init_var: int\n\n\na_or_b: Union[A[int], B]\n_ = replace(a_or_b, x=42, y=True, init_var=42)\n_ = replace(a_or_b, x=42, y=True)  # E: Missing named argument \"init_var\" for \"replace\" of \"A[int] | B\"\n_ = replace(a_or_b, x=42, y=True, z='42', init_var=42)  # E: Argument \"z\" to \"replace\" of \"A[int] | B\" has incompatible type \"str\"; expected \"Never\"\n_ = replace(a_or_b, x=42, y=True, w={}, init_var=42)  # E: Argument \"w\" to \"replace\" of \"A[int] | B\" has incompatible type \"dict[Never, Never]\"; expected \"Never\"\n_ = replace(a_or_b, y=42, init_var=42)  # E: Argument \"y\" to \"replace\" of \"A[int] | B\" has incompatible type \"int\"; expected \"bool\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testReplaceUnionOfTypeVar]\nfrom typing import Generic, Union, TypeVar\nfrom dataclasses import dataclass, replace\n\n@dataclass\nclass A:\n    x: int\n    y: int\n    z: str\n    w: dict\n\nclass B:\n    pass\n\nTA = TypeVar('TA', bound=A)\nTB = TypeVar('TB', bound=B)\n\ndef f(b_or_t: Union[TA, TB, int]) -> None:\n    a2 = replace(b_or_t)   # E: Value of type variable \"_DataclassT\" of \"replace\" cannot be \"TA | TB | int\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testReplaceTypeVarBoundNotDataclass]\nfrom dataclasses import dataclass, replace\nfrom typing import Union, TypeVar\n\nTInt = TypeVar('TInt', bound=int)\nTAny = TypeVar('TAny')\nTNone = TypeVar('TNone', bound=None)\nTUnion = TypeVar('TUnion', bound=Union[str, int])\n\ndef f1(t: TInt) -> None:\n    _ = replace(t, x=42)  # E: Value of type variable \"_DataclassT\" of \"replace\" cannot be \"TInt\"\n\ndef f2(t: TAny) -> TAny:\n    return replace(t, x='spam')  # E: Value of type variable \"_DataclassT\" of \"replace\" cannot be \"TAny\"\n\ndef f3(t: TNone) -> TNone:\n    return replace(t, x='spam')  # E: Value of type variable \"_DataclassT\" of \"replace\" cannot be \"TNone\"\n\ndef f4(t: TUnion) -> TUnion:\n    return replace(t, x='spam')  # E: Value of type variable \"_DataclassT\" of \"replace\" cannot be \"TUnion\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testReplaceTypeVarBound]\nfrom dataclasses import dataclass, replace\nfrom typing import TypeVar\n\n@dataclass\nclass A:\n    x: int\n\n@dataclass\nclass B(A):\n    pass\n\nTA = TypeVar('TA', bound=A)\n\ndef f(t: TA) -> TA:\n    t2 = replace(t, x=42)\n    reveal_type(t2)  # N: Revealed type is \"TA`-1\"\n    _ = replace(t, x='42')  # E: Argument \"x\" to \"replace\" of \"TA\" has incompatible type \"str\"; expected \"int\"\n    return t2\n\nf(A(x=42))\nf(B(x=42))\n\n[builtins fixtures/tuple.pyi]\n\n[case testReplaceAny]\nfrom dataclasses import replace\nfrom typing import Any\n\na: Any\na2 = replace(a)\nreveal_type(a2)  # N: Revealed type is \"Any\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testReplaceNotDataclass]\nfrom dataclasses import replace\n\nreplace(5)  # E: Value of type variable \"_DataclassT\" of \"replace\" cannot be \"int\"\n\nclass C:\n    pass\n\nreplace(C())  # E: Value of type variable \"_DataclassT\" of \"replace\" cannot be \"C\"\n\nreplace(None)  # E: Value of type variable \"_DataclassT\" of \"replace\" cannot be \"None\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testReplaceIsDataclass]\nfrom dataclasses import is_dataclass, replace\n\ndef f(x: object) -> None:\n  _ = replace(x)  # E: Value of type variable \"_DataclassT\" of \"replace\" cannot be \"object\"\n  if is_dataclass(x):\n    _ = replace(x)  # E: Value of type variable \"_DataclassT\" of \"replace\" cannot be \"DataclassInstance | type[DataclassInstance]\"\n    if not isinstance(x, type):\n      _ = replace(x)\n\n[builtins fixtures/tuple.pyi]\n\n[case testReplaceGeneric]\nfrom dataclasses import dataclass, replace, InitVar\nfrom typing import ClassVar, Generic, TypeVar\n\nT = TypeVar('T')\n\n@dataclass\nclass A(Generic[T]):\n    x: T\n\na = A(x=42)\nreveal_type(a)  # N: Revealed type is \"__main__.A[builtins.int]\"\na2 = replace(a, x=42)\nreveal_type(a2)  # N: Revealed type is \"__main__.A[builtins.int]\"\na2 = replace(a, x='42')  # E: Argument \"x\" to \"replace\" of \"A[int]\" has incompatible type \"str\"; expected \"int\"\nreveal_type(a2)  # N: Revealed type is \"__main__.A[builtins.int]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testPostInitNotMethod]\ndef __post_init__() -> None:\n    pass\n\n[case testPostInitCorrectSignature]\nfrom typing import Any, Generic, TypeVar, Callable, Self\nfrom dataclasses import dataclass, InitVar\n\n@dataclass\nclass Test1:\n    x: int\n    def __post_init__(self) -> None: ...\n\n@dataclass\nclass Test2:\n    x: int\n    y: InitVar[int]\n    z: str\n    def __post_init__(self, y: int) -> None: ...\n\n@dataclass\nclass Test3:\n    x: InitVar[int]\n    y: InitVar[str]\n    def __post_init__(self, x: int, y: str) -> None: ...\n\n@dataclass\nclass Test4:\n    x: int\n    y: InitVar[str]\n    z: InitVar[bool] = True\n    def __post_init__(self, y: str, z: bool) -> None: ...\n\n@dataclass\nclass Test5:\n    y: InitVar[str] = 'a'\n    z: InitVar[bool] = True\n    def __post_init__(self, y: str = 'a', z: bool = True) -> None: ...\n\nF = TypeVar('F', bound=Callable[..., Any])\ndef identity(f: F) -> F: return f\n\n@dataclass\nclass Test6:\n    y: InitVar[str]\n    @identity  # decorated method works\n    def __post_init__(self, y: str) -> None: ...\n\nT = TypeVar('T')\n\n@dataclass\nclass Test7(Generic[T]):\n    t: InitVar[T]\n    def __post_init__(self, t: T) -> None: ...\n\n@dataclass\nclass Test8:\n    s: InitVar[Self]\n    def __post_init__(self, s: Self) -> None: ...\n[builtins fixtures/dataclasses.pyi]\n\n[case testPostInitSubclassing]\nfrom dataclasses import dataclass, InitVar\n\n@dataclass\nclass Base:\n    a: str\n    x: InitVar[int]\n    def __post_init__(self, x: int) -> None: ...\n\n@dataclass\nclass Child(Base):\n    b: str\n    y: InitVar[str]\n    def __post_init__(self, x: int, y: str) -> None: ...\n\n@dataclass\nclass GrandChild(Child):\n    c: int\n    z: InitVar[str] = \"a\"\n    def __post_init__(self, x: int, y: str, z: str) -> None: ...\n[builtins fixtures/dataclasses.pyi]\n\n[case testPostInitNotADataclassCheck]\nfrom dataclasses import dataclass, InitVar\n\nclass Regular:\n    __post_init__ = 1  # can be whatever\n\nclass Base:\n    x: InitVar[int]\n    def __post_init__(self) -> None: ...  # can be whatever\n\n@dataclass\nclass Child(Base):\n    y: InitVar[str]\n    def __post_init__(self, y: str) -> None: ...\n[builtins fixtures/dataclasses.pyi]\n\n[case testPostInitMissingParam]\nfrom dataclasses import dataclass, InitVar\n\n@dataclass\nclass Child:\n    y: InitVar[str]\n    def __post_init__(self) -> None: ...\n[builtins fixtures/dataclasses.pyi]\n[out]\nmain:6: error: Signature of \"__post_init__\" incompatible with supertype \"dataclass\"\nmain:6: note:      Superclass:\nmain:6: note:          def __post_init__(self: Child, y: str) -> None\nmain:6: note:      Subclass:\nmain:6: note:          def __post_init__(self: Child) -> None\n\n[case testPostInitWrongTypeAndName]\nfrom dataclasses import dataclass, InitVar\n\n@dataclass\nclass Test1:\n    y: InitVar[str]\n    def __post_init__(self, x: int) -> None: ...  # E: Argument 2 of \"__post_init__\" is incompatible with supertype \"dataclass\"; supertype defines the argument type as \"str\"\n\n@dataclass\nclass Test2:\n    y: InitVar[str] = 'a'\n    def __post_init__(self, x: int) -> None: ...  # E: Argument 2 of \"__post_init__\" is incompatible with supertype \"dataclass\"; supertype defines the argument type as \"str\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testPostInitExtraParam]\nfrom dataclasses import dataclass, InitVar\n\n@dataclass\nclass Child:\n    y: InitVar[str]\n    def __post_init__(self, y: str, z: int) -> None: ...\n[builtins fixtures/dataclasses.pyi]\n[out]\nmain:6: error: Signature of \"__post_init__\" incompatible with supertype \"dataclass\"\nmain:6: note:      Superclass:\nmain:6: note:          def __post_init__(self: Child, y: str) -> None\nmain:6: note:      Subclass:\nmain:6: note:          def __post_init__(self: Child, y: str, z: int) -> None\n\n[case testPostInitReturnType]\nfrom dataclasses import dataclass, InitVar\n\n@dataclass\nclass Child:\n    y: InitVar[str]\n    def __post_init__(self, y: str) -> int: ...  # E: Return type \"int\" of \"__post_init__\" incompatible with return type \"None\" in supertype \"dataclass\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testPostInitDecoratedMethodError]\nfrom dataclasses import dataclass, InitVar\nfrom typing import Any, Callable, TypeVar\n\nF = TypeVar('F', bound=Callable[..., Any])\ndef identity(f: F) -> F: return f\n\n@dataclass\nclass Klass:\n    y: InitVar[str]\n    @identity\n    def __post_init__(self) -> None: ...\n[builtins fixtures/dataclasses.pyi]\n[out]\nmain:11: error: Signature of \"__post_init__\" incompatible with supertype \"dataclass\"\nmain:11: note:      Superclass:\nmain:11: note:          def __post_init__(self: Klass, y: str) -> None\nmain:11: note:      Subclass:\nmain:11: note:          def __post_init__(self: Klass) -> None\n\n[case testPostInitIsNotAFunction]\nfrom dataclasses import dataclass, InitVar\n\n@dataclass\nclass Test:\n    y: InitVar[str]\n    __post_init__ = 1  # E: \"__post_init__\" method must be an instance method\n[builtins fixtures/dataclasses.pyi]\n\n[case testPostInitClassMethod]\nfrom dataclasses import dataclass, InitVar\n\n@dataclass\nclass Test:\n    y: InitVar[str]\n    @classmethod\n    def __post_init__(cls) -> None: ...\n[builtins fixtures/dataclasses.pyi]\n[out]\nmain:7: error: Signature of \"__post_init__\" incompatible with supertype \"dataclass\"\nmain:7: note:      Superclass:\nmain:7: note:          def __post_init__(self: Test, y: str) -> None\nmain:7: note:      Subclass:\nmain:7: note:          @classmethod\nmain:7: note:          def __post_init__(cls: type[Test]) -> None\n\n[case testPostInitStaticMethod]\nfrom dataclasses import dataclass, InitVar\n\n@dataclass\nclass Test:\n    y: InitVar[str]\n    @staticmethod\n    def __post_init__() -> None: ...\n[builtins fixtures/dataclasses.pyi]\n[out]\nmain:7: error: Signature of \"__post_init__\" incompatible with supertype \"dataclass\"\nmain:7: note:      Superclass:\nmain:7: note:          def __post_init__(self: Test, y: str) -> None\nmain:7: note:      Subclass:\nmain:7: note:          @staticmethod\nmain:7: note:          def __post_init__() -> None\n\n[case testProtocolNoCrash]\nfrom typing import Protocol, Union, ClassVar\nfrom dataclasses import dataclass, field\n\nDEFAULT = 0\n\n@dataclass\nclass Test(Protocol):\n    x: int\n    def reset(self) -> None:\n        self.x = DEFAULT\n[builtins fixtures/dataclasses.pyi]\n\n[case testProtocolNoCrashOnJoining]\nfrom dataclasses import dataclass\nfrom typing import Protocol\n\n@dataclass\nclass MyDataclass(Protocol): ...\n\na: MyDataclass\nb = [a, a]  # trigger joining the types\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testPropertyAndFieldRedefinitionNoCrash]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Foo:\n    @property\n    def c(self) -> int:\n        return 0\n\n    c: int  # E: Name \"c\" already defined on line 5\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassInheritanceWorksWithExplicitOverrides]\n# flags: --enable-error-code explicit-override\nfrom dataclasses  import dataclass\n\n@dataclass\nclass Base:\n    x: int\n\n@dataclass\nclass Child(Base):\n    y: int\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesInitVarsWithProperty]\nfrom dataclasses import InitVar, dataclass, field\n\n@dataclass\nclass Test:\n    foo: InitVar[str]\n    _foo: str = field(init=False)\n\n    def __post_init__(self, foo: str) -> None:\n        self._foo = foo\n\n    @property\n    def foo(self) -> str:\n        return self._foo\n\n    @foo.setter\n    def foo(self, value: str) -> None:\n        self._foo = value\n\nreveal_type(Test)  # N: Revealed type is \"def (foo: builtins.str) -> __main__.Test\"\ntest = Test(42)  # E: Argument 1 to \"Test\" has incompatible type \"int\"; expected \"str\"\ntest = Test(\"foo\")\ntest.foo\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesDefaultValueInitVarWithProperty]\nfrom dataclasses import InitVar, dataclass, field\n\n@dataclass\nclass Test:\n    foo: InitVar[str] = \"foo\"\n    _foo: str = field(init=False)\n\n    def __post_init__(self, foo: str) -> None:\n        self._foo = foo\n\n    @property  # E: InitVar with default value cannot be redefined\n    def foo(self) -> str:\n        return self._foo\n\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassesWithProperty]\nfrom dataclasses import dataclass\n\n@dataclass\nclass Test:\n    @property\n    def foo(self) -> str:\n        return \"a\"\n\n    @foo.setter\n    def foo(self, value: str) -> None:\n        pass\n[builtins fixtures/dataclasses.pyi]\n\n[case testDataclassInheritanceWorksWithExplicitOverridesAndOrdering]\n# flags: --enable-error-code explicit-override\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass Base:\n    x: int\n\n@dataclass(order=True)\nclass Child(Base):\n    y: int\n[builtins fixtures/dataclasses.pyi]\n\n[case testDunderReplacePresent]\n# flags: --python-version 3.13\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass Coords:\n    x: int\n    y: int\n    # non-init fields are not allowed with replace:\n    z: int = field(init=False)\n\n\nreplaced = Coords(2, 4).__replace__(x=2, y=5)\nreveal_type(replaced)  # N: Revealed type is \"__main__.Coords\"\n\nreplaced = Coords(2, 4).__replace__(x=2)\nreveal_type(replaced)  # N: Revealed type is \"__main__.Coords\"\n\nCoords(2, 4).__replace__(x=\"asdf\")  # E: Argument \"x\" to \"__replace__\" of \"Coords\" has incompatible type \"str\"; expected \"int\"\nCoords(2, 4).__replace__(23)          # E: Too many positional arguments for \"__replace__\" of \"Coords\"\nCoords(2, 4).__replace__(23, 25)      # E: Too many positional arguments for \"__replace__\" of \"Coords\"\nCoords(2, 4).__replace__(x=23, y=25, z=42)  # E: Unexpected keyword argument \"z\" for \"__replace__\" of \"Coords\"\n\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\n@dataclass\nclass Gen(Generic[T]):\n    x: T\n\nreplaced_2 = Gen(2).__replace__(x=2)\nreveal_type(replaced_2)  # N: Revealed type is \"__main__.Gen[builtins.int]\"\nGen(2).__replace__(x=\"not an int\")  # E: Argument \"x\" to \"__replace__\" of \"Gen\" has incompatible type \"str\"; expected \"int\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testDunderReplaceCovariantOverride]\n# flags: --python-version 3.13  --enable-error-code mutable-override\nfrom dataclasses import dataclass\nfrom typing import Optional\nfrom typing_extensions import dataclass_transform\n\n@dataclass\nclass Base:\n    a: Optional[int]\n\n@dataclass\nclass Child(Base):\n    a: int  # E: Covariant override of a mutable attribute (base class \"Base\" defined the type as \"int | None\", expression has type \"int\")\n\n@dataclass\nclass Other(Base):\n    a: str  # E: Incompatible types in assignment (expression has type \"str\", base class \"Base\" defined the type as \"int | None\")\n\n@dataclass_transform(kw_only_default=True)\nclass DCMeta(type): ...\n\nclass X(metaclass=DCMeta):\n    a: Optional[int]\n\nclass Y(X):\n    a: int  # E: Covariant override of a mutable attribute (base class \"X\" defined the type as \"int | None\", expression has type \"int\")\n[builtins fixtures/tuple.pyi]\n\n\n[case testFrozenWithFinal]\nfrom dataclasses import dataclass\nfrom typing import Final\n\n@dataclass(frozen=True)\nclass My:\n    a: Final = 1\n    b: Final[int] = 2\n\nreveal_type(My.a)  # N: Revealed type is \"Literal[1]?\"\nreveal_type(My.b)  # N: Revealed type is \"builtins.int\"\nMy.a = 1  # E: Cannot assign to final attribute \"a\"\nMy.b = 2  # E: Cannot assign to final attribute \"b\"\n\nm = My()\nreveal_type(m.a)  # N: Revealed type is \"Literal[1]?\"\nreveal_type(m.b)  # N: Revealed type is \"builtins.int\"\n\nm.a = 1  # E: Cannot assign to final attribute \"a\"\nm.b = 2  # E: Cannot assign to final attribute \"b\"\n[builtins fixtures/tuple.pyi]\n\n[case testNoCrashForDataclassNamedTupleCombination]\n# flags: --python-version 3.13\nfrom dataclasses import dataclass\nfrom typing import NamedTuple\n\n@dataclass\nclass A(NamedTuple):  # E: A NamedTuple cannot be a dataclass\n    i: int\n\nclass B1(NamedTuple):\n    i: int\n@dataclass\nclass B2(B1):  # E: A NamedTuple cannot be a dataclass\n    pass\n\n[builtins fixtures/tuple.pyi]\n\n[case testDataclassesTypeGuard]\nimport dataclasses\n\nraw_target: object\n\nif isinstance(raw_target, type) and dataclasses.is_dataclass(raw_target):\n    reveal_type(raw_target)  # N: Revealed type is \"type[dataclasses.DataclassInstance]\"\n[builtins fixtures/tuple.pyi]\n\n[case testDataclassKwOnlyArgsLast]\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass User:\n    id: int = field(kw_only=True)\n    name: str\n\nUser(\"Foo\", id=0)\n[builtins fixtures/tuple.pyi]\n\n[case testDataclassKwOnlyArgsDefaultAllowedNonLast]\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass User:\n    id: int = field(kw_only=True, default=0)\n    name: str\n\nUser()  # E: Missing positional argument \"name\" in call to \"User\"\nUser(\"\")\nUser(0)  # E: Argument 1 to \"User\" has incompatible type \"int\"; expected \"str\"\nUser(\"\", 0)  # E: Too many positional arguments for \"User\"\nUser(\"\", id=0)\nUser(\"\", name=\"\")  # E: \"User\" gets multiple values for keyword argument \"name\"\n[builtins fixtures/tuple.pyi]\n\n[case testDataclassDefaultFactoryTypedDict]\nfrom dataclasses import dataclass, field\nfrom mypy_extensions import TypedDict\n\nclass Person(TypedDict, total=False):\n    name: str\n\n@dataclass\nclass Job:\n    person: Person = field(default_factory=Person)\n\nclass PersonBad(TypedDict):\n    name: str\n\n@dataclass\nclass JobBad:\n    person: PersonBad = field(default_factory=PersonBad)  # E: Argument \"default_factory\" to \"field\" has incompatible type \"type[PersonBad]\"; expected \"Callable[[], PersonBad]\"\n[builtins fixtures/dict.pyi]\n\n[case testDataclassInitVarRedefinitionNoCrash]\n# https://github.com/python/mypy/issues/19443\nfrom dataclasses import InitVar, dataclass\n\nclass ClassA:\n    def value(self) -> int:\n        return 0\n\n@dataclass\nclass ClassB(ClassA):\n    value: InitVar[int]\n\n    def value(self) -> int:\n        return 0\n[builtins fixtures/dict.pyi]\n"
  },
  {
    "path": "test-data/unit/check-deprecated.test",
    "content": "-- Type checker test cases for reporting deprecations.\n\n\n[case testDeprecatedDisabled]\n\nfrom typing_extensions import deprecated\n\n@deprecated(\"use f2 instead\")\ndef f() -> None: ...\n\nf()\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedAsNoteWithErrorCode]\n# flags: --enable-error-code=deprecated --show-error-codes --report-deprecated-as-note\n\nfrom typing_extensions import deprecated\n\n@deprecated(\"use f2 instead\")\ndef f() -> None: ...\n\nf() # type: ignore[deprecated]\nf() # N: function __main__.f is deprecated: use f2 instead  [deprecated]\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedAsErrorWithErrorCode]\n# flags: --enable-error-code=deprecated --show-error-codes\n\nfrom typing_extensions import deprecated\n\n@deprecated(\"use f2 instead\")\ndef f() -> None: ...\n\nf() # type: ignore[deprecated]\nf() # E: function __main__.f is deprecated: use f2 instead  [deprecated]\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedFunction]\n# flags: --enable-error-code=deprecated\n\nfrom typing_extensions import deprecated\n\n@deprecated(\"use f2 instead\")\ndef f() -> None: ...\n\nf  # E: function __main__.f is deprecated: use f2 instead  # type: ignore[deprecated]\nf(1)  # E: function __main__.f is deprecated: use f2 instead \\\n      # E: Too many arguments for \"f\"\nf[1]  # E: function __main__.f is deprecated: use f2 instead \\\n      # E: Value of type \"Callable[[], None]\" is not indexable\ng = f  # E: function __main__.f is deprecated: use f2 instead\ng()\nt = (f, f, g)  # E: function __main__.f is deprecated: use f2 instead\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedFunctionDifferentModule]\n# flags: --enable-error-code=deprecated\n\nimport m\nimport p.s\nimport m as n\nimport p.s as ps\nfrom m import f  # E: function m.f is deprecated: use f2 instead\nfrom p.s import g  # E: function p.s.g is deprecated: use g2 instead\nfrom k import *\n\nm.f()  # E: function m.f is deprecated: use f2 instead\np.s.g()  # E: function p.s.g is deprecated: use g2 instead\nn.f()  # E: function m.f is deprecated: use f2 instead\nps.g()  # E: function p.s.g is deprecated: use g2 instead\nf()\ng()\nh()  # E: function k.h is deprecated: use h2 instead\n\n[file m.py]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use f2 instead\")\ndef f() -> None: ...\n\n[file p/s.py]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use g2 instead\")\ndef g() -> None: ...\n\n[file k.py]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use h2 instead\")\ndef h() -> None: ...\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedClass]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Callable, List, Optional, Tuple, Union\nfrom typing_extensions import deprecated, TypeAlias, TypeVar\n\n@deprecated(\"use C2 instead\")\nclass C: ...\n\nc: C  # E: class __main__.C is deprecated: use C2 instead\nC()  # E: class __main__.C is deprecated: use C2 instead\nC.missing()  # E: class __main__.C is deprecated: use C2 instead \\\n             # E: \"type[C]\" has no attribute \"missing\"\nC.__init__(c)  # E: class __main__.C is deprecated: use C2 instead\nC(1)  # E: class __main__.C is deprecated: use C2 instead \\\n      # E: Too many arguments for \"C\"\n\nD = C  # E: class __main__.C is deprecated: use C2 instead\nD()\nt = (C, C, D)  # E: class __main__.C is deprecated: use C2 instead\n\nu1: Union[C, int] = 1  # E: class __main__.C is deprecated: use C2 instead\nu1 = 1\nu2 = 1  # type: Union[C, int]  # E: class __main__.C is deprecated: use C2 instead\nu2 = 1\n\nc1 = c2 = C()  # E: class __main__.C is deprecated: use C2 instead\ni, c3 = 1, C()  # E: class __main__.C is deprecated: use C2 instead\n\nclass E: ...\n\nx1: Optional[C]  # E: class __main__.C is deprecated: use C2 instead\nx2: Union[D, C, E]  # E: class __main__.C is deprecated: use C2 instead\nx3: Union[D, Optional[C], E]  # E: class __main__.C is deprecated: use C2 instead\nx4: Tuple[D, C, E]  # E: class __main__.C is deprecated: use C2 instead\nx5: Tuple[Tuple[D, C], E]  # E: class __main__.C is deprecated: use C2 instead\nx6: List[C]  # E: class __main__.C is deprecated: use C2 instead\nx7: List[List[C]]  # E: class __main__.C is deprecated: use C2 instead\nx8: List[Optional[Tuple[Union[List[C], int]]]]  # E: class __main__.C is deprecated: use C2 instead\nx9: Callable[[int], C]  # E: class __main__.C is deprecated: use C2 instead\nx10: Callable[[int, C, int], int]  # E: class __main__.C is deprecated: use C2 instead\n\nT = TypeVar(\"T\")\nA1: TypeAlias = Optional[C]  # E: class __main__.C is deprecated: use C2 instead\nx11: A1\nA2: TypeAlias = List[Union[A2, C]]  # E: class __main__.C is deprecated: use C2 instead\nx12: A2\nA3: TypeAlias = List[Optional[T]]\nx13: A3[C]  # E: class __main__.C is deprecated: use C2 instead\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedBaseClass]\n# flags: --enable-error-code=deprecated\n\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C2 instead\")\nclass C: ...\n\nclass D(C): ...  # E: class __main__.C is deprecated: use C2 instead\nclass E(D): ...\nclass F(D, C): ...  # E: class __main__.C is deprecated: use C2 instead\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedClassInTypeVar]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Generic, TypeVar\nfrom typing_extensions import deprecated\n\nclass B: ...\n@deprecated(\"use C2 instead\")\nclass C: ...\n\nT = TypeVar(\"T\", bound=C)  # E: class __main__.C is deprecated: use C2 instead\ndef f(x: T) -> T: ...\nclass D(Generic[T]): ...\n\nV = TypeVar(\"V\", B, C)  # E: class __main__.C is deprecated: use C2 instead\ndef g(x: V) -> V: ...\nclass E(Generic[V]): ...\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedClassInCast]\n# flags: --enable-error-code=deprecated\n\nfrom typing import cast, Generic\nfrom typing_extensions import deprecated\n\nclass B: ...\n@deprecated(\"use C2 instead\")\nclass C: ...\n\nc = C()  # E: class __main__.C is deprecated: use C2 instead\nb = cast(B, c)\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedInstanceInFunctionDefinition]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Generic, List, Optional, TypeVar\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C2 instead\")\nclass C: ...\n\ndef f1(c: C) -> None:  # E: class __main__.C is deprecated: use C2 instead\n    def g1() -> None: ...\n\ndef f2(c: List[Optional[C]]) -> None:  # E: class __main__.C is deprecated: use C2 instead\n    def g2() -> None: ...\n\ndef f3() -> C:  # E: class __main__.C is deprecated: use C2 instead\n    def g3() -> None: ...\n    return C()  # E: class __main__.C is deprecated: use C2 instead\n\ndef f4() -> List[Optional[C]]:  # E: class __main__.C is deprecated: use C2 instead\n    def g4() -> None: ...\n    return []\n\ndef f5() -> None:\n    def g5(c: C) -> None: ...  # E: class __main__.C is deprecated: use C2 instead\n\ndef f6() -> None:\n    def g6() -> C: ...  # E: class __main__.C is deprecated: use C2 instead\n\n\n@deprecated(\"use D2 instead\")\nclass D:\n\n    def f1(self, c: C) -> None:  # E: class __main__.C is deprecated: use C2 instead\n        def g1() -> None: ...\n\n    def f2(self, c: List[Optional[C]]) -> None:  # E: class __main__.C is deprecated: use C2 instead\n        def g2() -> None: ...\n\n    def f3(self) -> None:\n        def g3(c: C) -> None: ...  # E: class __main__.C is deprecated: use C2 instead\n\n    def f4(self) -> None:\n        def g4() -> C: ...  # E: class __main__.C is deprecated: use C2 instead\n\nT = TypeVar(\"T\")\n\n@deprecated(\"use E2 instead\")\nclass E(Generic[T]):\n\n    def f1(self: E[C]) -> None: ...  # E: class __main__.C is deprecated: use C2 instead\n    def f2(self, e: E[C]) -> None: ...  # E: class __main__.C is deprecated: use C2 instead\n    def f3(self) -> E[C]: ...  # E: class __main__.C is deprecated: use C2 instead\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedClassDifferentModule]\n# flags: --enable-error-code=deprecated\n\nimport m\nimport p.s\nimport m as n\nimport p.s as ps\nfrom m import B, C  # E: class m.B is deprecated: use B2 instead \\\n                    # E: class m.C is deprecated: use C2 instead\nfrom p.s import D  # E: class p.s.D is deprecated: use D2 instead\nfrom k import *\n\nm.C()  # E: class m.C is deprecated: use C2 instead\np.s.D()  # E: class p.s.D is deprecated: use D2 instead\nn.C()  # E: class m.C is deprecated: use C2 instead\nps.D()  # E: class p.s.D is deprecated: use D2 instead\nC()\nD()\nE()  # E: class k.E is deprecated: use E2 instead\n\nx1: m.A  # E: class m.A is deprecated: use A2 instead\nx2: m.A = m.A()  # E: class m.A is deprecated: use A2 instead\ny1: B\ny2: B = B()\n\n[file m.py]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use A2 instead\")\nclass A: ...\n\n@deprecated(\"use B2 instead\")\nclass B: ...\n\n@deprecated(\"use C2 instead\")\nclass C: ...\n\n[file p/s.py]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use D2 instead\")\nclass D: ...\n\n[file k.py]\nfrom typing_extensions import deprecated\n\n@deprecated(\"use E2 instead\")\nclass E: ...\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedClassInitMethod]\n# flags: --enable-error-code=deprecated\n\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C2 instead\")\nclass C:\n    def __init__(self) -> None: ...\n\nc: C  # E: class __main__.C is deprecated: use C2 instead\nC()  # E: class __main__.C is deprecated: use C2 instead\nC.__init__(c)  # E: class __main__.C is deprecated: use C2 instead\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedSpecialMethods]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Iterator\nfrom typing_extensions import deprecated\n\nclass A:\n    @deprecated(\"no A + int\")\n    def __add__(self, v: int) -> None: ...\n\n    @deprecated(\"no int + A\")\n    def __radd__(self, v: int) -> None: ...\n\n    @deprecated(\"no A = A + int\")\n    def __iadd__(self, v: int) -> A: ...\n\n    @deprecated(\"no iteration\")\n    def __iter__(self) -> Iterator[int]: ...\n\n    @deprecated(\"no in\")\n    def __contains__(self, v: int) -> int: ...\n\n    @deprecated(\"no integer\")\n    def __int__(self) -> int: ...\n\n    @deprecated(\"no inversion\")\n    def __invert__(self) -> A: ...\n\nclass B:\n    @deprecated(\"still no in\")\n    def __contains__(self, v: int) -> int: ...\n\na = A()\nb = B()\na + 1  # E: function __main__.A.__add__ is deprecated: no A + int\n1 + a  # E: function __main__.A.__radd__ is deprecated: no int + A\na += 1  # E: function __main__.A.__iadd__ is deprecated: no A = A + int\nfor i in a:  # E: function __main__.A.__iter__ is deprecated: no iteration\n    reveal_type(i)  # N: Revealed type is \"builtins.int\"\n1 in a  # E: function __main__.A.__contains__ is deprecated: no in\n1 in b  # E: function __main__.B.__contains__ is deprecated: still no in\n~a  # E: function __main__.A.__invert__ is deprecated: no inversion\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedOverloadedInstanceMethods]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Iterator, Union, overload\nfrom typing_extensions import deprecated\n\nclass A:\n    @overload\n    @deprecated(\"pass `str` instead\")\n    def f(self, v: int) -> None: ...\n    @overload\n    def f(self, v: str) -> None: ...\n    def f(self, v: Union[int, str]) -> None: ...\n\n    @overload\n    def g(self, v: int) -> None: ...\n    @overload\n    @deprecated(\"pass `int` instead\")\n    def g(self, v: str) -> None: ...\n    def g(self, v: Union[int, str]) -> None: ...\n\n    @overload\n    def h(self, v: int) -> A: ...\n    @overload\n    def h(self, v: str) -> A: ...\n    @deprecated(\"use `h2` instead\")\n    def h(self, v: Union[int, str]) -> A: ...\n\nclass B(A): ...\n\na = A()\na.f(1)  # E: overload def (self: __main__.A, v: builtins.int) of function __main__.A.f is deprecated: pass `str` instead\na.f(\"x\")\na.g(1)\na.g(\"x\")  # E: overload def (self: __main__.A, v: builtins.str) of function __main__.A.g is deprecated: pass `int` instead\na.h(1)  # E: function __main__.A.h is deprecated: use `h2` instead\na.h(\"x\")  # E: function __main__.A.h is deprecated: use `h2` instead\n\nb = B()\nb.f(1)  # E: overload def (self: __main__.A, v: builtins.int) of function __main__.A.f is deprecated: pass `str` instead\nb.f(\"x\")\nb.g(1)\nb.g(\"x\")  # E: overload def (self: __main__.A, v: builtins.str) of function __main__.A.g is deprecated: pass `int` instead\nb.h(1)  # E: function __main__.A.h is deprecated: use `h2` instead\nb.h(\"x\")  # E: function __main__.A.h is deprecated: use `h2` instead\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedOverloadedClassMethods]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Iterator, Union, overload\nfrom typing_extensions import deprecated\n\nclass A:\n    @overload\n    @classmethod\n    @deprecated(\"pass `str` instead\")\n    def f(cls, v: int) -> None: ...\n    @overload\n    @classmethod\n    def f(cls, v: str) -> None: ...\n    @classmethod\n    def f(cls, v: Union[int, str]) -> None: ...\n\n    @overload\n    @classmethod\n    def g(cls, v: int) -> None: ...\n    @overload\n    @classmethod\n    @deprecated(\"pass `int` instead\")\n    def g(cls, v: str) -> None: ...\n    @classmethod\n    def g(cls, v: Union[int, str]) -> None: ...\n\n    @overload\n    @classmethod\n    def h(cls, v: int) -> A: ...\n    @overload\n    @classmethod\n    def h(cls, v: str) -> A: ...\n    @deprecated(\"use `h2`  instead\")\n    @classmethod\n    def h(cls, v: Union[int, str]) -> A: ...\n\nclass B(A): ...\n\na = A()\na.f(1)  # E: overload def (cls: type[__main__.A], v: builtins.int) of function __main__.A.f is deprecated: pass `str` instead\na.f(\"x\")\na.g(1)\na.g(\"x\")  # E: overload def (cls: type[__main__.A], v: builtins.str) of function __main__.A.g is deprecated: pass `int` instead\na.h(1)  # E: function __main__.A.h is deprecated: use `h2`  instead\na.h(\"x\")  # E: function __main__.A.h is deprecated: use `h2`  instead\n\nb = B()\nb.f(1)  # E: overload def (cls: type[__main__.A], v: builtins.int) of function __main__.A.f is deprecated: pass `str` instead\nb.f(\"x\")\nb.g(1)\nb.g(\"x\")  # E: overload def (cls: type[__main__.A], v: builtins.str) of function __main__.A.g is deprecated: pass `int` instead\nb.h(1)  # E: function __main__.A.h is deprecated: use `h2`  instead\nb.h(\"x\")  # E: function __main__.A.h is deprecated: use `h2`  instead\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedOverloadedStaticMethods]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Iterator, Union, overload\nfrom typing_extensions import deprecated\n\nclass A:\n    @overload\n    @staticmethod\n    @deprecated(\"pass `str` instead\")\n    def f(v: int) -> None: ...\n    @overload\n    @staticmethod\n    def f(v: str) -> None: ...\n    @staticmethod\n    def f(v: Union[int, str]) -> None: ...\n\n    @overload\n    @staticmethod\n    def g(v: int) -> None: ...\n    @overload\n    @staticmethod\n    @deprecated(\"pass `int` instead\")\n    def g(v: str) -> None: ...\n    @staticmethod\n    def g(v: Union[int, str]) -> None: ...\n\n    @overload\n    @staticmethod\n    def h(v: int) -> A: ...\n    @overload\n    @staticmethod\n    def h(v: str) -> A: ...\n    @deprecated(\"use `h2`  instead\")\n    @staticmethod\n    def h(v: Union[int, str]) -> A: ...\n\nclass B(A): ...\n\na = A()\na.f(1)  # E: overload def (v: builtins.int) of function __main__.A.f is deprecated: pass `str` instead\na.f(\"x\")\na.g(1)\na.g(\"x\")  # E: overload def (v: builtins.str) of function __main__.A.g is deprecated: pass `int` instead\na.h(1)  # E: function __main__.A.h is deprecated: use `h2`  instead\na.h(\"x\")  # E: function __main__.A.h is deprecated: use `h2`  instead\n\nb = B()\nb.f(1)  # E: overload def (v: builtins.int) of function __main__.A.f is deprecated: pass `str` instead\nb.f(\"x\")\nb.g(1)\nb.g(\"x\")  # E: overload def (v: builtins.str) of function __main__.A.g is deprecated: pass `int` instead\nb.h(1)  # E: function __main__.A.h is deprecated: use `h2`  instead\nb.h(\"x\")  # E: function __main__.A.h is deprecated: use `h2`  instead\n\n[builtins fixtures/classmethod.pyi]\n\n\n[case testDeprecatedOverloadedSpecialMethods]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Iterator, Union, overload\nfrom typing_extensions import deprecated\n\nclass A:\n    @overload\n    @deprecated(\"no A + int\")\n    def __add__(self, v: int) -> None: ...\n    @overload\n    def __add__(self, v: str) -> None: ...\n    def __add__(self, v: Union[int, str]) -> None: ...\n\n    @overload\n    def __radd__(self, v: int) -> None: ...\n    @overload\n    @deprecated(\"no str + A\")\n    def __radd__(self, v: str) -> None: ...\n    def __radd__(self, v: Union[int, str]) -> None: ...\n\n    @overload\n    def __iadd__(self, v: int) -> A: ...\n    @overload\n    def __iadd__(self, v: str) -> A: ...\n    @deprecated(\"no A += Any\")\n    def __iadd__(self, v: Union[int, str]) -> A: ...\n\na = A()\na + 1  # E: overload def (__main__.A, builtins.int) of function __main__.A.__add__ is deprecated: no A + int\na + \"x\"\n1 + a\n\"x\" + a  # E: overload def (__main__.A, builtins.str) of function __main__.A.__radd__ is deprecated: no str + A\na += 1  # E: function __main__.A.__iadd__ is deprecated: no A += Any\na += \"x\"  # E: function __main__.A.__iadd__ is deprecated: no A += Any\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testDeprecatedMethod]\n# flags: --enable-error-code=deprecated\n\nfrom typing_extensions import deprecated\n\nclass C:\n    @deprecated(\"use g instead\")\n    def f(self) -> None: ...\n\n    def g(self) -> None: ...\n\n    @staticmethod\n    @deprecated(\"use g instead\")\n    def h() -> None: ...\n\n    @deprecated(\"use g instead\")\n    @staticmethod\n    def k() -> None: ...\n\nC.f  # E: function __main__.C.f is deprecated: use g instead\nC().f  # E: function __main__.C.f is deprecated: use g instead\nC().f()  # E: function __main__.C.f is deprecated: use g instead\nC().f(1)  # E: function __main__.C.f is deprecated: use g instead \\\n          # E: Too many arguments for \"f\" of \"C\"\nf = C().f  # E: function __main__.C.f is deprecated: use g instead\nf()\nt = (C.f, C.f, C.g)  # E: function __main__.C.f is deprecated: use g instead\n\nC().g()\nC().h()  # E: function __main__.C.h is deprecated: use g instead\nC().k()  # E: function __main__.C.k is deprecated: use g instead\n\n[builtins fixtures/callable.pyi]\n\n\n[case testDeprecatedClassWithDeprecatedMethod]\n# flags: --enable-error-code=deprecated\n\nfrom typing_extensions import deprecated\n\n@deprecated(\"use D instead\")\nclass C:\n    @deprecated(\"use g instead\")\n    def f(self) -> None: ...\n    def g(self) -> None: ...\n\nC().f()  # E: class __main__.C is deprecated: use D instead \\\n         # E: function __main__.C.f is deprecated: use g instead\nC().g()  # E: class __main__.C is deprecated: use D instead\n\n[builtins fixtures/callable.pyi]\n\n\n[case testDeprecatedProperty]\n# flags: --enable-error-code=deprecated\n\nfrom typing_extensions import deprecated\n\nclass C:\n    @property\n    @deprecated(\"use f2 instead\")\n    def f(self) -> int: ...\n\n    @property\n    def g(self) -> int: ...\n    @g.setter\n    @deprecated(\"use g2 instead\")\n    def g(self, v: int) -> None: ...\n\n\nC.f  # E: function __main__.C.f is deprecated: use f2 instead\nC().f  # E: function __main__.C.f is deprecated: use f2 instead\nC().f()  # E: function __main__.C.f is deprecated: use f2 instead \\\n         # E: \"int\" not callable\nC().f = 1  # E: function __main__.C.f is deprecated: use f2 instead \\\n           # E: Property \"f\" defined in \"C\" is read-only\n\n\nC.g\nC().g\nC().g = 1  # E: function __main__.C.g is deprecated: use g2 instead\nC().g = \"x\"  # E: function __main__.C.g is deprecated: use g2 instead \\\n             # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[builtins fixtures/property.pyi]\n\n\n[case testDeprecatedDescriptor]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Any, Generic, Optional, overload, TypeVar, Union\nfrom typing_extensions import deprecated\n\nT = TypeVar(\"T\")\n\n@deprecated(\"use E1 instead\")\nclass D1:\n    def __get__(self, obj: Optional[C], objtype: Any) -> Union[D1, int]: ...\n\nclass D2:\n    @deprecated(\"use E2.__get__ instead\")\n    def __get__(self, obj: Optional[C], objtype: Any) -> Union[D2, int]: ...\n\n    @deprecated(\"use E2.__set__ instead\")\n    def __set__(self, obj: C, value: int) -> None: ...\n\nclass D3:\n    @overload\n    @deprecated(\"use E3.__get__ instead\")\n    def __get__(self, obj: None, objtype: Any) -> D3: ...\n    @overload\n    @deprecated(\"use E3.__get__ instead\")\n    def __get__(self, obj: C, objtype: Any) -> int: ...\n    def __get__(self, obj: Optional[C], objtype: Any) -> Union[D3, int]: ...\n\n    @overload\n    def __set__(self, obj: C, value: int) -> None: ...\n    @overload\n    @deprecated(\"use E3.__set__ instead\")\n    def __set__(self, obj: C, value: str) -> None: ...\n    def __set__(self, obj: C, value: Union[int, str]) -> None: ...\n\nclass D4(Generic[T]):\n    @overload\n    def __get__(self, obj: None, objtype: Any) -> T: ...\n    @overload\n    @deprecated(\"deprecated instance access\")\n    def __get__(self, obj: C, objtype: Any) -> T: ...\n    def __get__(self, obj: Optional[C], objtype: Any) -> T: ...\n\nclass C:\n    d1 = D1()  # E: class __main__.D1 is deprecated: use E1 instead\n    d2 = D2()\n    d3 = D3()\n    d4 = D4[int]()\n\nc: C\nC.d1\nc.d1\nc.d1 = 1\n\nC.d2  # E: function __main__.D2.__get__ is deprecated: use E2.__get__ instead\nc.d2  # E: function __main__.D2.__get__ is deprecated: use E2.__get__ instead\nc.d2 = 1  # E: function __main__.D2.__set__ is deprecated: use E2.__set__ instead\n\nC.d3  # E: overload def (self: __main__.D3, obj: None, objtype: Any) -> __main__.D3 of function __main__.D3.__get__ is deprecated: use E3.__get__ instead\nc.d3  # E: overload def (self: __main__.D3, obj: __main__.C, objtype: Any) -> builtins.int of function __main__.D3.__get__ is deprecated: use E3.__get__ instead\nc.d3 = 1\nc.d3 = \"x\"  # E: overload def (self: __main__.D3, obj: __main__.C, value: builtins.str) of function __main__.D3.__set__ is deprecated: use E3.__set__ instead\n\nC.d4\nc.d4  # E: overload def (self: __main__.D4[T`1], obj: __main__.C, objtype: Any) -> T`1 of function __main__.D4.__get__ is deprecated: deprecated instance access\n[builtins fixtures/property.pyi]\n\n\n[case testDeprecatedOverloadedFunction]\n# flags: --enable-error-code=deprecated\n\nfrom typing import Any, overload, Union\nfrom typing_extensions import deprecated\n\nint_or_str: Union[int, str]\nany: Any\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: str) -> str: ...\n@deprecated(\"use f2 instead\")\ndef f(x: Union[int, str]) -> Union[int, str]: ...\n\nf  # E: function __main__.f is deprecated: use f2 instead\nf(1)  # E: function __main__.f is deprecated: use f2 instead\nf(\"x\")  # E: function __main__.f is deprecated: use f2 instead\nf(int_or_str)  # E: function __main__.f is deprecated: use f2 instead\nf(any)  # E: function __main__.f is deprecated: use f2 instead\nf(1.0)  # E: function __main__.f is deprecated: use f2 instead \\\n        # E: No overload variant of \"f\" matches argument type \"float\" \\\n        # N: Possible overload variants: \\\n        # N:     def f(x: int) -> int \\\n        # N:     def f(x: str) -> str\n\n@overload\n@deprecated(\"work with str instead\")\ndef g(x: int) -> int: ...\n@overload\ndef g(x: str) -> str: ...\ndef g(x: Union[int, str]) -> Union[int, str]: ...\n\ng\ng(1)  # E: overload def (x: builtins.int) -> builtins.int of function __main__.g is deprecated: work with str instead\ng(\"x\")\ng(int_or_str)  # E: overload def (x: builtins.int) -> builtins.int of function __main__.g is deprecated: work with str instead\ng(any)\ng(1.0)  # E: No overload variant of \"g\" matches argument type \"float\" \\\n        # N: Possible overload variants: \\\n        # N:     def g(x: int) -> int \\\n        # N:     def g(x: str) -> str\n\n@overload\ndef h(x: int) -> int: ...\n@deprecated(\"work with int instead\")\n@overload  # N: @overload should be placed before @deprecated\ndef h(x: str) -> str: ...\ndef h(x: Union[int, str]) -> Union[int, str]: ...\n\nh\nh(1)\nh(\"x\")  # E: overload def (x: builtins.str) -> builtins.str of function __main__.h is deprecated: work with int instead\nh(int_or_str)  # E: overload def (x: builtins.str) -> builtins.str of function __main__.h is deprecated: work with int instead\nh(any)\nh(1.0)  # E: No overload variant of \"h\" matches argument type \"float\" \\\n        # N: Possible overload variants: \\\n        # N:     def h(x: int) -> int \\\n        # N:     def h(x: str) -> str\n\n@overload\ndef i(x: int) -> int: ...\n@overload\n@deprecated(\"work with int instead\")\ndef i(x: str) -> str: ...\n@overload\ndef i(x: Any) -> Any: ...\ndef i(x: Union[int, str]) -> Union[int, str]: ...\n\ni\ni(1)\ni(\"x\")  # E: overload def (x: builtins.str) -> builtins.str of function __main__.i is deprecated: work with int instead\ni(int_or_str)  # E: overload def (x: builtins.str) -> builtins.str of function __main__.i is deprecated: work with int instead\ni(any)\ni(1.0)\n\n@overload\ndef j(x: int) -> int: ...\n@overload\ndef j(x: str) -> str: ...\n@overload\n@deprecated(\"work with int or str instead\")\ndef j(x: Any) -> Any: ...\ndef j(x: Union[int, str]) -> Union[int, str]: ...\n\nj\nj(1)\nj(\"x\")\nj(int_or_str)\nj(any)\nj(1.0)  # E: overload def (x: Any) -> Any of function __main__.j is deprecated: work with int or str instead\n\n@overload\n@deprecated(\"work with str instead\")\ndef k(x: int) -> int: ...\n@overload\ndef k(x: str) -> str: ...\n@overload\n@deprecated(\"work with str instead\")\ndef k(x: object) -> Any: ...\ndef k(x: object) -> Union[int, str]: ...\n\nk\nk(1)  # E: overload def (x: builtins.int) -> builtins.int of function __main__.k is deprecated: work with str instead\nk(\"x\")\nk(int_or_str)  # E: overload def (x: builtins.int) -> builtins.int of function __main__.k is deprecated: work with str instead\nk(any)\nk(1.0)  # E: overload def (x: builtins.object) -> Any of function __main__.k is deprecated: work with str instead\n[builtins fixtures/tuple.pyi]\n\n[case testDeprecatedImportedOverloadedFunction]\n# flags: --enable-error-code=deprecated\n\nimport m\n\nm.g\nm.g(1)  # E: overload def (x: builtins.int) -> builtins.int of function m.g is deprecated: work with str instead\nm.g(\"x\")\n\n[file m.py]\n\nfrom typing import Union, overload\nfrom typing_extensions import deprecated\n\n@overload\n@deprecated(\"work with str instead\")\ndef g(x: int) -> int: ...\n@overload\ndef g(x: str) -> str: ...\ndef g(x: Union[int, str]) -> Union[int, str]: ...\n[builtins fixtures/tuple.pyi]\n\n[case testDeprecatedExclude]\n# flags: --enable-error-code=deprecated --deprecated-calls-exclude=m.C --deprecated-calls-exclude=m.D --deprecated-calls-exclude=m.E.f --deprecated-calls-exclude=m.E.g --deprecated-calls-exclude=m.E.__add__\nfrom m import C, D, E\n\n[file m.py]\nfrom typing import Union, overload\nfrom typing_extensions import deprecated\n\n@deprecated(\"use C2 instead\")\nclass C:\n    def __init__(self) -> None: ...\n\nc: C\nC()\nC.__init__(c)\n\nclass D:\n    @deprecated(\"use D.g instead\")\n    def f(self) -> None: ...\n\n    def g(self) -> None: ...\n\nD.f\nD().f\nD().f()\n\nclass E:\n    @overload\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: str) -> str: ...\n    @deprecated(\"use E.f2 instead\")\n    def f(self, x: Union[int, str]) -> Union[int, str]: ...\n\n    @deprecated(\"use E.h instead\")\n    def g(self) -> None: ...\n\n    @overload\n    @deprecated(\"no A + int\")\n    def __add__(self, v: int) -> None: ...\n    @overload\n    def __add__(self, v: str) -> None: ...\n    def __add__(self, v: Union[int, str]) -> None: ...\n\nE().f(1)\nE().f(\"x\")\n\ne = E()\ne.g()\ne + 1\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-dynamic-typing.test",
    "content": "-- Assignment\n-- ----------\n\n\n[case testAssignmentWithDynamic]\nfrom typing import Any\nd: Any\na: A\n\nif int():\n    a = d # Everything ok\nif int():\n    d = a\nif int():\n    d = d\nd.x = a\nd.x = d\n\nclass A: pass\n\n[case testMultipleAssignmentWithDynamic]\nfrom typing import Any\nd: Any\na: A\nb: B\n\nif int():\n    d, a = b, b    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    d, d = d, d, d # E: Too many values to unpack (2 expected, 3 provided)\n\nif int():\n    a, b = d, d\nif int():\n    d, d = a, b\nif int():\n    a, b = d\ns, t = d\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n\n-- Expressions\n-- -----------\n\n\n[case testCallingFunctionWithDynamicArgumentTypes]\nfrom typing import Any\n\ndef f(x: Any) -> 'A':\n    pass\n\na: A\nb: B\n\nif int():\n    b = f(a) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\nif int():\n    a = f(a)\nif int():\n    a = f(b)\nif int():\n    a = f(None)\nif int():\n    a = f(f)\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testCallingWithDynamicReturnType]\nfrom typing import Any\n\ndef f(x: 'A') -> Any:\n    pass\n\na: A\nb: B\n\na = f(b) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\n\na = f(a)\nb = f(a)\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testBinaryOperationsWithDynamicLeftOperand]\nfrom typing import Any\nd: Any\na: A\nc: C\nb: bool\nn = 0\n\nd in a  # E: Unsupported right operand type for in (\"A\")\nd and a\nd or a\nif int():\n    c = d and b # E: Incompatible types in assignment (expression has type \"Any | bool\", variable has type \"C\")\nif int():\n    c = d or b  # E: Incompatible types in assignment (expression has type \"Any | bool\", variable has type \"C\")\n\nif int():\n    c = d + a\nif int():\n    c = d - a\nif int():\n    c = d * a\nif int():\n    c = d / a\nif int():\n    c = d // a\nif int():\n    c = d % a\nif int():\n    c = d ** a\nif int():\n    b = d == a\nif int():\n    b = d != a\nif int():\n    b = d < a\nif int():\n    b = d <= a\nif int():\n    b = d > a\nif int():\n    b = d >= a\nif int():\n    b = d in c\nif int():\n    b = d and b\nif int():\n    b = d or b\n\nclass A: pass\nclass C:\n    def __contains__(self, a: A) -> bool:\n        pass\n[file builtins.py]\nclass object:\n  def __init__(self): pass\nclass bool: pass\nclass int: pass\nclass type: pass\nclass function: pass\nclass str: pass\nclass dict: pass\n\n[case testBinaryOperationsWithDynamicAsRightOperand]\nfrom typing import Any\nd: Any\na: A\nc: C\nb: bool\nn = 0\n\na and d\na or d\nif int():\n    c = a in d  # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"C\")\nif int():\n    c = b and d # E: Incompatible types in assignment (expression has type \"Literal[False] | Any\", variable has type \"C\")\nif int():\n    c = b or d  # E: Incompatible types in assignment (expression has type \"Literal[True] | Any\", variable has type \"C\")\nif int():\n    b = a + d\nif int():\n    b = a / d\n\nif int():\n    c = a + d\nif int():\n    c = a - d\nif int():\n    c = a * d\nif int():\n    c = a / d\nif int():\n    c = a // d\nif int():\n    c = a % d\nif int():\n    c = a ** d\nif int():\n    b = a in d\nif int():\n    b = b and d\nif int():\n    b = b or d\n\nclass A:\n    def __add__(self, a: 'A') -> 'C':\n        pass\n    def __sub__(self, a: 'A') -> 'C':\n        pass\n    def __mul__(self, a: 'A') -> 'C':\n        pass\n    def __truediv__(self, a: 'A') -> 'C':\n        pass\n    def __floordiv__(self, a: 'A') -> 'C':\n        pass\n    def __mod__(self, a: 'A') -> 'C':\n        pass\n    def __pow__(self, a: 'A') -> 'C':\n        pass\n    def _lt(self, a: 'A') -> bool:\n        pass\n    def _gt(self, a: 'A') -> bool:\n        pass\n\nclass C: pass\n[file builtins.py]\nclass object:\n  def __init__(self): pass\nclass bool: pass\nclass int: pass\nclass type: pass\nclass function: pass\nclass str: pass\nclass dict: pass\n\n[case testDynamicWithUnaryExpressions]\nfrom typing import Any\nd: Any\na: A\nb: bool\nif int():\n    a = not d # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    b = not d\n    a = -d\nclass A: pass\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testDynamicWithMemberAccess]\nfrom typing import Any\nd: Any\na: A\n\nif int():\n    a = d.foo(a()) # E: \"A\" not callable\n\nif int():\n    a = d.x\nif int():\n    a = d.foo(a, a)\nd.x = a\nd.x.y.z\n\nclass A: pass\n[out]\n\n[case testIndexingWithDynamic]\nfrom typing import Any\nd: Any\na: A\n\nif int():\n    a = d[a()] # E: \"A\" not callable\nd[a()] = a # E: \"A\" not callable\n\nif int():\n    a = d[a]\nd[a] = a\nd[a], d[a] = a, a\n\nclass A: pass\n\n[case testTupleExpressionsWithDynamic]\nfrom typing import Tuple, Any\nt2: Tuple[A, A]\nd: Any\n\nif int():\n    t2 = (d, d, d)  # E: Incompatible types in assignment (expression has type \"tuple[Any, Any, Any]\", variable has type \"tuple[A, A]\")\nif int():\n    t2 = (d, d)\n\nclass A: pass\n[builtins fixtures/tuple.pyi]\n\n[case testCastsWithDynamicType]\nfrom typing import Any, cast\nclass A: pass\nclass B: pass\ndef f() -> None: pass\n\nd: Any\na: A\nb: B\nif int():\n    b = cast(A, d) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    a = cast(A, d)\nif int():\n    b = cast(Any, d)\nif int():\n    a = cast(Any, f())\n[case testCompatibilityOfDynamicWithOtherTypes]\nfrom typing import Any, Tuple\n\ndef g(a: 'A') -> None:\n    pass\n\nclass A: pass\nclass B: pass\n\nd: Any\nt: Tuple[A, A]\n# TODO: callable types, overloaded functions\n\nd = None # All ok\nd = t\nd = g\nd = A\n\nd1: Any\nt = d1\nf = d1\n[builtins fixtures/tuple.pyi]\n\n\n-- Statements\n-- ----------\n\n\n[case testDynamicCondition]\nfrom typing import Any\nd = None # type: Any\nwhile d:\n    pass\nif d:\n    pass\nelif d:\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testRaiseWithDynamic]\nfrom typing import Any\nd = None # type: Any\nraise d\n[builtins fixtures/exception.pyi]\n\n[case testReturnWithDynamic]\nfrom typing import Any\nd = None # type: Any\n\ndef f() -> None:\n    return d # Ok\n\ndef g() -> 'A':\n    return d # Ok\n\nclass A: pass\n\n\n-- Implicit dynamic types for functions\n-- ------------------------------------\n\n\n[case testImplicitGlobalFunctionSignature]\nfrom typing import Any, Callable\nx: Any\na: A\ng: Callable[[], None]\nh: Callable[[A], None]\n\ndef f(x): pass\n\nf()     # E: Missing positional argument \"x\" in call to \"f\"\nf(x, x) # E: Too many arguments for \"f\"\nif int():\n    g = f   # E: Incompatible types in assignment (expression has type \"Callable[[Any], Any]\", variable has type \"Callable[[], None]\")\nf(a)\nf(x)\nif int():\n    a = f(a)\nif int():\n    h = f\n\nclass A: pass\n\n[case testImplicitGlobalFunctionSignatureWithDifferentArgCounts]\nfrom typing import Callable\ng0: Callable[[], None]\ng1: Callable[[A], None]\ng2: Callable[[A, A], None]\na: A\n\ndef f0(): pass\ndef f2(x, y): pass\n\nif int():\n    g1 = f0 # E: Incompatible types in assignment (expression has type \"Callable[[], Any]\", variable has type \"Callable[[A], None]\")\nif int():\n    g2 = f0 # E: Incompatible types in assignment (expression has type \"Callable[[], Any]\", variable has type \"Callable[[A, A], None]\")\nif int():\n    g0 = f2 # E: Incompatible types in assignment (expression has type \"Callable[[Any, Any], Any]\", variable has type \"Callable[[], None]\")\nif int():\n    g1 = f2 # E: Incompatible types in assignment (expression has type \"Callable[[Any, Any], Any]\", variable has type \"Callable[[A], None]\")\n\nif int():\n    g0 = g0\nif int():\n    g2 = f2\nf0()\nf2(a, a)\n\nclass A: pass\n\n[case testImplicitGlobalFunctionSignatureWithDefaultArgs]\nfrom typing import Callable\nclass A: pass\nclass B: pass\n\na: A\nb: B\n\ndef f01(x = b): pass\ndef f13(x, y = b, z = b): pass\n\ng0: Callable[[], None]\ng1: Callable[[A], None]\ng2: Callable[[A, A], None]\ng3: Callable[[A, A, A], None]\ng4: Callable[[A, A, A, A], None]\n\nf01(a, a)       # E: Too many arguments for \"f01\"\nf13()           # E: Missing positional argument \"x\" in call to \"f13\"\nf13(a, a, a, a) # E: Too many arguments for \"f13\"\nif int():\n    g2 = f01 # E: Incompatible types in assignment (expression has type \"Callable[[Any], Any]\", variable has type \"Callable[[A, A], None]\")\nif int():\n    g0 = f13 # E: Incompatible types in assignment (expression has type \"Callable[[Any, Any, Any], Any]\", variable has type \"Callable[[], None]\")\nif int():\n    g4 = f13 # E: Incompatible types in assignment (expression has type \"Callable[[Any, Any, Any], Any]\", variable has type \"Callable[[A, A, A, A], None]\")\n\nf01()\nf01(a)\nf13(a)\nf13(a, a)\nf13(a, a, a)\n\nif int():\n    g0 = f01\nif int():\n    g1 = f01\nif int():\n    g1 = f13\nif int():\n    g2 = f13\nif int():\n    g3 = f13\n\n[builtins fixtures/tuple.pyi]\n\n[case testSkipTypeCheckingWithImplicitSignature]\na: A\ndef f():\n    a()\ndef g(x):\n    a()\n    a.x\n    a + a\n    if a():\n        a()\nclass A: pass\n[builtins fixtures/bool.pyi]\n\n[case testSkipTypeCheckingWithImplicitSignatureAndDefaultArgs]\na: A\ndef f(x=a()):\n    a()\ndef g(x, y=a, z=a()):\n    a()\nclass A: pass\n\n[case testImplicitMethodSignature]\nfrom typing import Callable\ng0: Callable[[], None]\ng1: Callable[[A], None]\ng2: Callable[[A, A], None]\na: A\n\nif int():\n    g0 = a.f # E: Incompatible types in assignment (expression has type \"Callable[[Any], Any]\", variable has type \"Callable[[], None]\")\nif int():\n    g2 = a.f # E: Incompatible types in assignment (expression has type \"Callable[[Any], Any]\", variable has type \"Callable[[A, A], None]\")\nif int():\n    a = a.f  # E: Incompatible types in assignment (expression has type \"Callable[[Any], Any]\", variable has type \"A\")\n\nclass A:\n    def g(self) -> None:\n        a = self.f(a)\n    def f(self, x): pass\n\nif int():\n    g1 = a.f\nif int():\n    a = a.f(a)\n\n[case testSkipTypeCheckingImplicitMethod]\n\na: A\nclass A:\n    def f(self):\n        a()\n    def g(self, x, y=a()):\n        a()\n\n[case testImplicitInheritedMethod]\nfrom typing import Callable\ng0: Callable[[], None]\ng1: Callable[[A], None]\na: A\n\nif int():\n    g0 = a.f # E: Incompatible types in assignment (expression has type \"Callable[[Any], Any]\", variable has type \"Callable[[], None]\")\n\nif int():\n    g1 = a.f\nif int():\n    a = a.f(a)\n\nclass B:\n    def f(self, x):\n        pass\nclass A(B):\n    def g(self) -> None:\n        a = self.f(a)\n\n[case testEmptyReturnWithImplicitSignature]\nimport typing\ndef f():\n    return\nclass A:\n    def g(self):\n        return\n\n[case testVarArgsWithImplicitSignature]\nfrom typing import Any\no = None # type: Any\ndef f(x, *a): pass\nf() # E: Missing positional argument \"x\" in call to \"f\"\nf(o)\nf(o, o)\nf(o, o, o)\n[builtins fixtures/list.pyi]\n\n\n-- Implicit types for constructors\n-- -------------------------------\n\n\n[case testInitMethodWithImplicitSignature]\nfrom typing import Callable\n\nclass A:\n  def __init__(self, a, b): pass\n\nf1: Callable[[A], A]\nf2: Callable[[A, A], A]\na: A\n\nA(a)   # E: Missing positional argument \"b\" in call to \"A\"\nif int():\n    f1 = A # E: Incompatible types in assignment (expression has type \"type[A]\", variable has type \"Callable[[A], A]\")\n\nA(a, a)\nif int():\n    f2 = A\n\n[case testUsingImplicitTypeObjectWithIs]\nclass A: pass\nclass B:\n    def __init__(self): pass\n\nt: type\nt = A\nt = B\n-- Type compatibility\n-- ------------------\n\n\n[case testTupleTypeCompatibility]\nfrom typing import Any, Tuple\nt1: Tuple[Any, A]\nt2: Tuple[A, Any]\nt3: Tuple[Any, Any]\nt4: Tuple[A, A]\nt5: Tuple[Any, Any, Any]\n\ndef f(): t1, t2, t3, t4, t5 # Prevent redefinition\n\nt3 = t5 # E: Incompatible types in assignment (expression has type \"tuple[Any, Any, Any]\", variable has type \"tuple[Any, Any]\")\nt5 = t4 # E: Incompatible types in assignment (expression has type \"tuple[A, A]\", variable has type \"tuple[Any, Any, Any]\")\n\nt1 = t1\nt1 = t2\nt1 = t3\nt1 = t4\nt2 = t1\nt2 = t3\nt2 = t4\nt3 = t1\nt3 = t2\nt3 = t4\nt4 = t1\nt4 = t2\nt4 = t3\n\nclass A: pass\n[builtins fixtures/tuple.pyi]\n\n[case testFunctionTypeCompatibilityAndReturnTypes]\nfrom typing import Any, Callable, Optional\nf1: Callable[[], Any]\nf11: Callable[[], Any]\nf2: Callable[[], Optional[A]]\nf3: Callable[[], None]\n\nf2 = f3\n\nf1 = f2\nf1 = f3\nf2 = f11\nf3 = f11\n\nclass A: pass\n\n[case testFunctionTypeCompatibilityAndArgumentTypes]\nfrom typing import Any, Callable\nf1: Callable[[A, Any], None]\nf2: Callable[[Any, A], None]\nf3: Callable[[A, A], None]\n\nf1 = f1\nf1 = f2\nf1 = f3\n\nf2 = f1\nf2 = f2\nf2 = f3\n\nf3 = f1\nf3 = f2\nf3 = f3\n\nclass A: pass\n\n[case testFunctionTypeCompatibilityAndArgumentCounts]\nfrom typing import Any, Callable\nf1: Callable[[Any], None]\nf2: Callable[[Any, Any], None]\n\nif int():\n    f1 = f2 # E: Incompatible types in assignment (expression has type \"Callable[[Any, Any], None]\", variable has type \"Callable[[Any], None]\")\n\n\n-- Overriding\n-- ----------\n\n\n[case testOverridingMethodWithDynamicTypes]\nfrom typing import Any\na: A\nb: B\n\nb.f(b) # E: Argument 1 to \"f\" of \"B\" has incompatible type \"B\"; expected \"A\"\na = a.f(b)\n\nclass B:\n    def f(self, x: 'A') -> 'B':\n        pass\n    def g(self, x: 'B') -> None:\n        pass\nclass A(B):\n    def f(self, x: Any) -> Any:\n        pass\n    def g(self, x: Any) -> None:\n        pass\n[builtins fixtures/tuple.pyi]\n\n[case testOverridingMethodWithImplicitDynamicTypes]\na: A\nb: B\n\nb.f(b) # E: Argument 1 to \"f\" of \"B\" has incompatible type \"B\"; expected \"A\"\na = a.f(b)\n\nclass B:\n    def f(self, x: 'A') -> 'B':\n        pass\n    def g(self, x: 'B') -> None:\n        pass\nclass A(B):\n    def f(self, x):\n        pass\n    def g(self, x):\n        pass\n[builtins fixtures/tuple.pyi]\n\n[case testOverridingMethodAcrossHierarchy]\nimport typing\nclass C:\n    def f(self, a: 'A') -> None: pass\nclass B(C):\n    def f(self, a): pass\nclass A(B):\n    def f(self, a: 'D') -> None: # E: Argument 1 of \"f\" is incompatible with supertype \"C\"; supertype defines the argument type as \"A\" \\\n                                 # N: This violates the Liskov substitution principle \\\n                                 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n        pass\nclass D: pass\n[out]\n\n[case testInvalidOverrideArgumentCountWithImplicitSignature1]\nimport typing\nclass B:\n    def f(self, x: A) -> None: pass\nclass A(B):\n    def f(self, x, y): # dynamic function not type checked\n        x()\n[out]\n\n[case testInvalidOverrideArgumentCountWithImplicitSignature2]\nimport typing\nclass B:\n    def f(self, x, y): pass\nclass A(B):\n    def f(self, x: 'A') -> None:  # Fail\n        pass\n[out]\nmain:5: error: Signature of \"f\" incompatible with supertype \"B\"\nmain:5: note:      Superclass:\nmain:5: note:          def f(self, x: Any, y: Any) -> Any\nmain:5: note:      Subclass:\nmain:5: note:          def f(self, x: A) -> None\n\n[case testInvalidOverrideArgumentCountWithImplicitSignature3]\nimport typing\nclass B:\n    def f(self, x: A) -> None: pass\nclass A(B):\n    def f(self, x, y) -> None:  # Fail\n        x()\n[out]\nmain:5: error: Signature of \"f\" incompatible with supertype \"B\"\nmain:5: note:      Superclass:\nmain:5: note:          def f(self, x: A) -> None\nmain:5: note:      Subclass:\nmain:5: note:          def f(self, x: Any, y: Any) -> None\n\n[case testInvalidOverrideArgumentCountWithImplicitSignature4]\n# flags: --check-untyped-defs\nimport typing\nclass B:\n    def f(self, x: A) -> None: pass\nclass A(B):\n    def f(self, x, y):\n        x()\n[out]\nmain:6: error: Signature of \"f\" incompatible with supertype \"B\"\nmain:6: note:      Superclass:\nmain:6: note:          def f(self, x: A) -> None\nmain:6: note:      Subclass:\nmain:6: note:          def f(self, x: Any, y: Any) -> Any\n\n[case testInvalidOverrideWithImplicitSignatureAndClassMethod1]\nclass B:\n    @classmethod\n    def f(cls, x, y): pass\nclass A(B):\n    @classmethod\n    def f(cls, x, y, z): pass # No error since no annotations\n[builtins fixtures/classmethod.pyi]\n\n[case testInvalidOverrideWithImplicitSignatureAndClassMethod2]\nclass B:\n    @classmethod\n    def f(cls, x: int, y): pass\nclass A(B):\n    @classmethod\n    def f(cls, x, y, z): pass # No error since no annotations\n[builtins fixtures/classmethod.pyi]\n\n[case testInvalidOverrideWithImplicitSignatureAndStaticMethod1]\nclass B:\n    @staticmethod\n    def f(x, y): pass\nclass A(B):\n    @staticmethod\n    def f(x, y, z): pass # No error since no annotations\n[builtins fixtures/classmethod.pyi]\n\n[case testInvalidOverrideWithImplicitSignatureAndStaticMethod2]\nclass B:\n    @staticmethod\n    def f(self, x: int, y): pass\nclass A(B):\n    @staticmethod\n    def f(self, x, y, z): pass # No error since no annotations\n[builtins fixtures/classmethod.pyi]\n\n\n-- Don't complain about too few/many arguments in dynamic functions\n-- ----------------------------------------------------------------\n\n[case testTooManyArgsInDynamic]\ndef f() -> None: pass\ndef g():\n    f(1) # Silent\n[out]\n\n[case testTooFewArgsInDynamic]\ndef f(a: int) -> None: pass\ndef g():\n    f() # Silent\n[out]\n\n[case testJustRightInDynamic]\ndef f(a: int) -> None: pass\ndef g():\n    f('') # Silent\n[out]\n"
  },
  {
    "path": "test-data/unit/check-enum.test",
    "content": "-- This test file checks Enum\n\n[case testEnumBasics]\nfrom enum import Enum\nclass Medal(Enum):\n    gold = 1\n    silver = 2\n    bronze = 3\nreveal_type(Medal.bronze)  # N: Revealed type is \"Literal[__main__.Medal.bronze]?\"\nm = Medal.gold\nif int():\n    m = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Medal\")\n\n[builtins fixtures/enum.pyi]\n\n-- Creation from Enum call\n-- -----------------------\n\n[case testEnumCreatedFromStringLiteral]\nfrom enum import Enum\nfrom typing import Literal\n\nx: Literal['ANT BEE CAT DOG'] = 'ANT BEE CAT DOG'\nAnimal = Enum('Animal', x)\nreveal_type(Animal.ANT)  # N: Revealed type is \"Literal[__main__.Animal.ANT]?\"\nreveal_type(Animal.BEE)  # N: Revealed type is \"Literal[__main__.Animal.BEE]?\"\nreveal_type(Animal.CAT)  # N: Revealed type is \"Literal[__main__.Animal.CAT]?\"\nreveal_type(Animal.DOG)  # N: Revealed type is \"Literal[__main__.Animal.DOG]?\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testEnumCreatedFromFinalValue]\nfrom enum import Enum\nfrom typing import Final\n\nx: Final['str'] = 'ANT BEE CAT DOG'\nAnimal = Enum('Animal', x)\nreveal_type(Animal.ANT)  # N: Revealed type is \"Literal[__main__.Animal.ANT]?\"\nreveal_type(Animal.BEE)  # N: Revealed type is \"Literal[__main__.Animal.BEE]?\"\nreveal_type(Animal.CAT)  # N: Revealed type is \"Literal[__main__.Animal.CAT]?\"\nreveal_type(Animal.DOG)  # N: Revealed type is \"Literal[__main__.Animal.DOG]?\"\n\n[builtins fixtures/tuple.pyi]\n\n-- Creation from EnumMeta\n-- ----------------------\n\n[case testEnumFromEnumMetaBasics]\nfrom enum import EnumMeta\nclass Medal(metaclass=EnumMeta):\n    gold = 1\n    silver = \"hello\"\n    bronze = None\n    # Without __init__ the definition fails at runtime, but we want to verify that mypy\n    # uses `enum.EnumMeta` and not `enum.Enum` as the definition of what is enum.\n    def __init__(self, *args): pass\nreveal_type(Medal.bronze)  # N: Revealed type is \"Literal[__main__.Medal.bronze]?\"\nm = Medal.gold\nif int():\n    m = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Medal\")\n[builtins fixtures/tuple.pyi]\n\n[case testEnumFromEnumMetaSubclass]\nfrom enum import EnumMeta\nclass Achievement(metaclass=EnumMeta): pass\nclass Medal(Achievement):\n    gold = 1\n    silver = \"hello\"\n    bronze = None\n    # See comment in testEnumFromEnumMetaBasics\n    def __init__(self, *args): pass\nreveal_type(Medal.bronze)  # N: Revealed type is \"Literal[__main__.Medal.bronze]?\"\nm = Medal.gold\nif int():\n    m = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Medal\")\n[builtins fixtures/tuple.pyi]\n\n[case testEnumFromEnumMetaGeneric]\nfrom enum import EnumMeta\nfrom typing import Generic, TypeVar\nT = TypeVar(\"T\")\nclass Medal(Generic[T], metaclass=EnumMeta):  # E: Enum class cannot be generic\n    q = None\n[builtins fixtures/enum.pyi]\n\n[case testEnumNameAndValue]\nfrom enum import Enum\nclass Truth(Enum):\n    true = True\n    false = False\nx = ''\nx = Truth.true.name\nreveal_type(Truth.true.name)    # N: Revealed type is \"Literal['true']?\"\nreveal_type(Truth.false.value)  # N: Revealed type is \"Literal[False]?\"\n[builtins fixtures/bool.pyi]\n\n[case testEnumValueExtended]\nfrom enum import Enum\nclass Truth(Enum):\n    true = True\n    false = False\n\ndef infer_truth(truth: Truth) -> None:\n    reveal_type(truth.value) # N: Revealed type is \"Literal[True]? | Literal[False]?\"\n[builtins fixtures/bool.pyi]\n\n[case testEnumValueAllAuto]\nfrom enum import Enum, auto\nclass Truth(Enum):\n    true = auto()\n    false = auto()\n\ndef infer_truth(truth: Truth) -> None:\n    reveal_type(truth.value) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/primitives.pyi]\n\n[case testEnumValueSomeAuto]\nfrom enum import Enum, auto\nclass Truth(Enum):\n    true = 8675309\n    false = auto()\n\ndef infer_truth(truth: Truth) -> None:\n    reveal_type(truth.value) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/primitives.pyi]\n\n[case testEnumValueExtraMethods]\nfrom enum import Enum\nclass Truth(Enum):\n    true = True\n    false = False\n\n    def foo(self) -> str:\n        return 'bar'\n\ndef infer_truth(truth: Truth) -> None:\n    reveal_type(truth.value) # N: Revealed type is \"Literal[True]? | Literal[False]?\"\n[builtins fixtures/bool.pyi]\n\n[case testEnumValueCustomAuto]\nfrom enum import Enum, auto\nclass AutoName(Enum):\n\n    # In `typeshed`, this is a staticmethod and has more arguments,\n    # but I have lied a bit to keep the test stubs lean.\n    def _generate_next_value_(self) -> str:\n        return \"name\"\n\nclass Truth(AutoName):\n    true = auto()\n    false = auto()\n\ndef infer_truth(truth: Truth) -> None:\n    reveal_type(truth.value) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/primitives.pyi]\n\n[case testEnumValueInhomogeneous]\nfrom enum import Enum\nclass Truth(Enum):\n    true = 'True'\n    false = 0\n\ndef cannot_infer_truth(truth: Truth) -> None:\n    reveal_type(truth.value) # N: Revealed type is \"Any\"\n[builtins fixtures/bool.pyi]\n\n[case testEnumValueSameType]\nfrom enum import Enum\n\ndef newbool() -> bool:\n    ...\n\nclass Truth(Enum):\n    true = newbool()\n    false = newbool()\n\ndef infer_truth(truth: Truth) -> None:\n    reveal_type(truth.value) # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/bool.pyi]\n\n[case testEnumTruthyness]\n# mypy: warn-unreachable\nimport enum\nfrom typing import Literal\n\nclass E(enum.Enum):\n    zero = 0\n    one = 1\n\ndef print(s: str) -> None: ...\n\nif E.zero:\n    print(\"zero is true\")\nif not E.zero:\n    print(\"zero is false\")  # E: Statement is unreachable\n\nif E.one:\n    print(\"one is true\")\nif not E.one:\n    print(\"one is false\")  # E: Statement is unreachable\n\ndef main(zero: Literal[E.zero], one: Literal[E.one]) -> None:\n    if zero:\n        print(\"zero is true\")\n    if not zero:\n        print(\"zero is false\")  # E: Statement is unreachable\n    if one:\n        print(\"one is true\")\n    if not one:\n        print(\"one is false\")  # E: Statement is unreachable\n[builtins fixtures/tuple.pyi]\n\n[case testEnumTruthynessCustomDunderBool]\n# mypy: warn-unreachable\nimport enum\nfrom typing import Literal\n\nclass E(enum.Enum):\n    zero = 0\n    one = 1\n    def __bool__(self) -> Literal[False]:\n        return False\n\ndef print(s: str) -> None: ...\n\nif E.zero:\n    print(\"zero is true\")  # E: Statement is unreachable\nif not E.zero:\n    print(\"zero is false\")\n\nif E.one:\n    print(\"one is true\")  # E: Statement is unreachable\nif not E.one:\n    print(\"one is false\")\n\ndef main(zero: Literal[E.zero], one: Literal[E.one]) -> None:\n    if zero:\n        print(\"zero is true\")  # E: Statement is unreachable\n    if not zero:\n        print(\"zero is false\")\n    if one:\n        print(\"one is true\")  # E: Statement is unreachable\n    if not one:\n        print(\"one is false\")\n[builtins fixtures/enum.pyi]\n\n[case testEnumTruthynessStrEnum]\n# mypy: warn-unreachable\nimport enum\nfrom typing import Literal\n\nclass E(enum.StrEnum):\n    empty = \"\"\n    not_empty = \"asdf\"\n\ndef print(s: str) -> None: ...\n\nif E.empty:\n    print(\"empty is true\")\nif not E.empty:\n    print(\"empty is false\")\n\nif E.not_empty:\n    print(\"not_empty is true\")\nif not E.not_empty:\n    print(\"not_empty is false\")\n\ndef main(empty: Literal[E.empty], not_empty: Literal[E.not_empty]) -> None:\n    if empty:\n        print(\"empty is true\")\n    if not empty:\n        print(\"empty is false\")\n    if not_empty:\n        print(\"not_empty is true\")\n    if not not_empty:\n        print(\"not_empty is false\")\n[builtins fixtures/enum.pyi]\n\n[case testEnumUnique]\nimport enum\n@enum.unique\nclass E(enum.Enum):\n    x = 1\n    y = 1  # NOTE: This duplicate value is not detected by mypy at the moment\nx = 1\nx = E.x\n[builtins fixtures/enum.pyi]\n[out]\nmain:7: error: Incompatible types in assignment (expression has type \"E\", variable has type \"int\")\n\n[case testIntEnum_assignToIntVariable]\nfrom enum import IntEnum\nclass N(IntEnum):\n    x = 1\n    y = 1\nn = 1\nif int():\n    n = N.x  # Subclass of int, so it's okay\ns = ''\nif int():\n    s = N.y # E: Incompatible types in assignment (expression has type \"N\", variable has type \"str\")\n[builtins fixtures/enum.pyi]\n\n[case testIntEnum_functionTakingIntEnum]\nfrom enum import IntEnum\nclass SomeIntEnum(IntEnum):\n    x = 1\ndef takes_some_int_enum(n: SomeIntEnum):\n    pass\ntakes_some_int_enum(SomeIntEnum.x)\ntakes_some_int_enum(1)  # Error\ntakes_some_int_enum(SomeIntEnum(1))  # How to deal with the above\n[builtins fixtures/enum.pyi]\n[out]\nmain:7: error: Argument 1 to \"takes_some_int_enum\" has incompatible type \"int\"; expected \"SomeIntEnum\"\n\n[case testIntEnum_functionTakingInt]\nfrom enum import IntEnum\nclass SomeIntEnum(IntEnum):\n    x = 1\ndef takes_int(i: int):\n    pass\ntakes_int(SomeIntEnum.x)\ntakes_int(2)\n[builtins fixtures/enum.pyi]\n\n[case testIntEnum_functionReturningIntEnum]\nfrom enum import IntEnum\nclass SomeIntEnum(IntEnum):\n    x = 1\ndef returns_some_int_enum() -> SomeIntEnum:\n    return SomeIntEnum.x\nan_int = 1\nan_int = returns_some_int_enum()\n\nan_enum = SomeIntEnum.x\nan_enum = returns_some_int_enum()\n[builtins fixtures/enum.pyi]\n[out]\n\n[case testStrEnumCreation]\n# flags: --python-version 3.11\nfrom enum import StrEnum\n\nclass MyStrEnum(StrEnum):\n    x = 'x'\n    y = 'y'\n\nreveal_type(MyStrEnum.x)  # N: Revealed type is \"Literal[__main__.MyStrEnum.x]?\"\nreveal_type(MyStrEnum.x.value)  # N: Revealed type is \"Literal['x']?\"\nreveal_type(MyStrEnum.y)  # N: Revealed type is \"Literal[__main__.MyStrEnum.y]?\"\nreveal_type(MyStrEnum.y.value)  # N: Revealed type is \"Literal['y']?\"\n[builtins fixtures/enum.pyi]\n[out]\n\n[case testEnumMethods]\nfrom enum import Enum\n\nclass Color(Enum):\n    red = 1\n    green = 2\n\n    def m(self, x: int): pass\n    @staticmethod\n    def m2(x: int): pass\n\nColor.red.m('')\nColor.m2('')\n[builtins fixtures/staticmethod.pyi]\n[out]\nmain:11: error: Argument 1 to \"m\" of \"Color\" has incompatible type \"str\"; expected \"int\"\nmain:12: error: Argument 1 to \"m2\" of \"Color\" has incompatible type \"str\"; expected \"int\"\n\n[case testIntEnum_ExtendedIntEnum_functionTakingExtendedIntEnum]\nfrom enum import IntEnum\nclass ExtendedIntEnum(IntEnum):\n    pass\nclass SomeExtIntEnum(ExtendedIntEnum):\n    x = 1\n\ndef takes_int(i: int):\n    pass\ntakes_int(SomeExtIntEnum.x)\n\ndef takes_some_ext_int_enum(s: SomeExtIntEnum):\n    pass\ntakes_some_ext_int_enum(SomeExtIntEnum.x)\n[builtins fixtures/enum.pyi]\n\n[case testNamedTupleEnum]\nfrom typing import NamedTuple\nfrom enum import Enum\n\nN = NamedTuple('N', [('bar', int)])\n\nclass E(N, Enum):\n    X = N(1)\n\ndef f(x: E) -> None: pass\n\nf(E.X)\n[builtins fixtures/tuple.pyi]\n\n[case testEnumCall]\nfrom enum import IntEnum\nclass E(IntEnum):\n    a = 1\nx: int\nreveal_type(E(x))\n[builtins fixtures/tuple.pyi]\n[out]\nmain:5: note: Revealed type is \"__main__.E\"\n\n[case testEnumIndex]\nfrom enum import IntEnum\nclass E(IntEnum):\n    a = 1\ns: str\nreveal_type(E[s])\n[builtins fixtures/enum.pyi]\n[out]\nmain:5: note: Revealed type is \"__main__.E\"\n\n[case testEnumIndexError]\nfrom enum import IntEnum\nclass E(IntEnum):\n    a = 1\nE[1]  # E: Enum index should be a string (actual index type \"int\")\nx = E[1]  # E: Enum index should be a string (actual index type \"int\")\n[builtins fixtures/enum.pyi]\n\n[case testEnumIndexIsNotAnAlias]\nfrom enum import Enum\n\nclass E(Enum):\n    a = 1\n    b = 2\nreveal_type(E['a'])  # N: Revealed type is \"__main__.E\"\nE['a']\nx = E['a']\nreveal_type(x)  # N: Revealed type is \"__main__.E\"\n\ndef get_member(name: str) -> E:\n    val = E[name]\n    return val\n\nreveal_type(get_member('a'))  # N: Revealed type is \"__main__.E\"\n[builtins fixtures/enum.pyi]\n\n[case testGenericEnum]\nfrom enum import Enum\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass F(Generic[T], Enum):  # E: Enum class cannot be generic\n    x: T\n    y: T\n\nreveal_type(F[int].x)  # E: Access to generic instance variables via class is ambiguous \\\n                       # N: Revealed type is \"builtins.int\"\n[builtins fixtures/enum.pyi]\n\n[case testEnumFlag]\nfrom enum import Flag\nclass C(Flag):\n    a = 1\n    b = 2\nx = C.a\nif int():\n    x = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"C\")\nif int():\n    x = x | C.b\n[builtins fixtures/enum.pyi]\n\n[case testEnumIntFlag]\nfrom enum import IntFlag\nclass C(IntFlag):\n    a = 1\n    b = 2\nx = C.a\nif int():\n    x = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"C\")\nif int():\n    x = x | C.b\n[builtins fixtures/enum.pyi]\n\n[case testAnonymousEnum]\nfrom enum import Enum\nclass A:\n    def f(self) -> None:\n        class E(Enum):\n            a = 1\n        self.x = E.a\na = A()\nreveal_type(a.x)\n[builtins fixtures/enum.pyi]\n[out]\nmain:8: note: Revealed type is \"__main__.E@4\"\n\n[case testEnumInClassBody]\nfrom enum import Enum\nclass A:\n    class E(Enum):\n        a = 1\nclass B:\n    class E(Enum):\n        a = 1\nx = A.E.a\ny = B.E.a\nif int():\n    x = y # E: Incompatible types in assignment (expression has type \"__main__.B.E\", variable has type \"__main__.A.E\")\n[builtins fixtures/enum.pyi]\n\n[case testFunctionalEnumString]\nfrom enum import Enum, IntEnum\nE = Enum('E', 'foo bar')\nI = IntEnum('I', ' bar, baz ')\nreveal_type(E.foo)\nreveal_type(E.bar.value)\nreveal_type(I.bar)\nreveal_type(I.baz.value)\n[builtins fixtures/enum.pyi]\n[out]\nmain:4: note: Revealed type is \"Literal[__main__.E.foo]?\"\nmain:5: note: Revealed type is \"Any\"\nmain:6: note: Revealed type is \"Literal[__main__.I.bar]?\"\nmain:7: note: Revealed type is \"builtins.int\"\n\n[case testFunctionalEnumListOfStrings]\nfrom enum import Enum, IntEnum\nE = Enum('E', ('foo', 'bar'))\nF = IntEnum('F', ['bar', 'baz'])\nreveal_type(E.foo)\nreveal_type(F.baz)\n[builtins fixtures/enum.pyi]\n[out]\nmain:4: note: Revealed type is \"Literal[__main__.E.foo]?\"\nmain:5: note: Revealed type is \"Literal[__main__.F.baz]?\"\n\n[case testFunctionalEnumListOfPairs]\nfrom enum import Enum, IntEnum\nE = Enum('E', [('foo', 1), ['bar', 2]])\nF = IntEnum('F', (['bar', 1], ('baz', 2)))\nreveal_type(E.foo)\nreveal_type(F.baz)\nreveal_type(E.foo.value)\nreveal_type(F.bar.name)\n[builtins fixtures/enum.pyi]\n[out]\nmain:4: note: Revealed type is \"Literal[__main__.E.foo]?\"\nmain:5: note: Revealed type is \"Literal[__main__.F.baz]?\"\nmain:6: note: Revealed type is \"Literal[1]?\"\nmain:7: note: Revealed type is \"Literal['bar']?\"\n\n[case testFunctionalEnumDict]\nfrom enum import Enum, IntEnum\nE = Enum('E', {'foo': 1, 'bar': 2})\nF = IntEnum('F', {'bar': 1, 'baz': 2})\nreveal_type(E.foo)\nreveal_type(F.baz)\nreveal_type(E.foo.value)\nreveal_type(F.bar.name)\n[builtins fixtures/enum.pyi]\n[out]\nmain:4: note: Revealed type is \"Literal[__main__.E.foo]?\"\nmain:5: note: Revealed type is \"Literal[__main__.F.baz]?\"\nmain:6: note: Revealed type is \"Literal[1]?\"\nmain:7: note: Revealed type is \"Literal['bar']?\"\n\n\n[case testEnumKeywordsArgs]\nfrom enum import Enum, IntEnum\n\nPictureSize = Enum('PictureSize', 'P0 P1 P2 P3 P4 P5 P6 P7 P8', type=str, module=__name__)\nfake_enum1 = Enum('fake_enum1', ['a', 'b'])\nfake_enum2 = Enum('fake_enum2', names=['a', 'b'])\nfake_enum3 = Enum(value='fake_enum3', names=['a', 'b'])\nfake_enum4 = Enum(value='fake_enum4', names=['a', 'b'] , module=__name__)\n[builtins fixtures/enum.pyi]\n\n[case testFunctionalEnumErrors]\nfrom enum import Enum, IntEnum\nA = Enum('A')  # E: Too few arguments for Enum()\nB = Enum('B', 42)  # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members\nC = Enum('C', 'a b', 'x', 'y', 'z', 'p', 'q')  # E: Too many arguments for Enum()\nD = Enum('D', foo)  # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members \\\n                    # E: Name \"foo\" is not defined\nbar = 'x y z'\nE = Enum('E', bar)  # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members\nI = IntEnum('I')  # E: Too few arguments for IntEnum()\nJ = IntEnum('I', 42)  # E: Second argument of IntEnum() must be string, tuple, list or dict literal for mypy to determine Enum members\nK = IntEnum('I', 'p q', 'x', 'y', 'z', 'p', 'q')  # E: Too many arguments for IntEnum()\nL = Enum('L', ' ')  # E: Enum() needs at least one item\nM = Enum('M', ())  # E: Enum() needs at least one item\nN = IntEnum('M', [])  # E: IntEnum() needs at least one item\nP = Enum('P', [42])  # E: Enum() with tuple or list expects strings or (name, value) pairs\nQ = Enum('Q', [('a', 42, 0)])  # E: Enum() with tuple or list expects strings or (name, value) pairs\nR = IntEnum('R', [[0, 42]])  # E: IntEnum() with tuple or list expects strings or (name, value) pairs\nS = Enum('S', {1: 1})  # E: Enum() with dict literal requires string literals\nT = Enum('T', keyword='a b')  # E: Unexpected keyword argument \"keyword\"\nU = Enum('U', *['a'])  # E: Unexpected arguments to Enum()\nV = Enum('U', **{'a': 1})  # E: Unexpected arguments to Enum()\nW = Enum('W', 'a b')\nW.c  # E: \"type[W]\" has no attribute \"c\"\nX = Enum('Something', 'a b')  # E: String argument 1 \"Something\" to enum.Enum(...) does not match variable name \"X\"\nreveal_type(X.a)  # N: Revealed type is \"Literal[__main__.Something@23.a]?\"\nX.asdf  # E: \"type[Something@23]\" has no attribute \"asdf\"\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testFunctionalEnumFlag]\nfrom enum import Flag, IntFlag\nA = Flag('A', 'x y')\nB = IntFlag('B', 'a b')\nreveal_type(A.x)        # N: Revealed type is \"Literal[__main__.A.x]?\"\nreveal_type(B.a)        # N: Revealed type is \"Literal[__main__.B.a]?\"\nreveal_type(A.x.name)   # N: Revealed type is \"Literal['x']?\"\nreveal_type(B.a.name)   # N: Revealed type is \"Literal['a']?\"\n\nreveal_type(A.x.value)  # N: Revealed type is \"builtins.int\"\nreveal_type(B.a.value)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/enum.pyi]\n\n[case testAnonymousFunctionalEnum]\nfrom enum import Enum\nclass A:\n    def f(self) -> None:\n        E = Enum('E', 'a b')\n        self.x = E.a\na = A()\nreveal_type(a.x)\n[builtins fixtures/enum.pyi]\n[out]\nmain:7: note: Revealed type is \"__main__.A.E@4\"\n\n[case testFunctionalEnumInClassBody]\nfrom enum import Enum\nclass A:\n    E = Enum('E', 'a b')\nclass B:\n    E = Enum('E', 'a b')\nx = A.E.a\ny = B.E.a\nif int():\n    x = y # E: Incompatible types in assignment (expression has type \"__main__.B.E\", variable has type \"__main__.A.E\")\n[builtins fixtures/enum.pyi]\n\n[case testFunctionalEnumProtocols]\nfrom enum import IntEnum\nColor = IntEnum('Color', 'red green blue')\nreveal_type(Color['green'])  # N: Revealed type is \"__main__.Color\"\nfor c in Color:\n    reveal_type(c)  # N: Revealed type is \"__main__.Color\"\nreveal_type(list(Color))  # N: Revealed type is \"builtins.list[__main__.Color]\"\n\n[builtins fixtures/list.pyi]\n\n[case testEnumWorkWithForward]\nfrom enum import Enum\na: E = E.x  # type: ignore[used-before-def]\nclass E(Enum):\n    x = 1\n    y = 2\n[builtins fixtures/enum.pyi]\n[out]\n\n[case testEnumWorkWithForward2]\nfrom enum import Enum\nb: F\nF = Enum('F', {'x': 1, 'y': 2})\n\ndef fn(x: F) -> None:\n    pass\nfn(b)\n[builtins fixtures/enum.pyi]\n[out]\n\n[case testFunctionalEnum]\n# TODO: Needs to have enum34 stubs somehow\nfrom enum import Enum\nEu = Enum(u'Eu', u'a b')\nEb = Enum(b'Eb', b'a b')  # E: Enum() expects a string literal as the first argument\nGu = Enum(u'Gu', {u'a': 1})\nGb = Enum(b'Gb', {b'a': 1})  # E: Enum() expects a string literal as the first argument\nHu = Enum(u'Hu', [u'a'])\nHb = Enum(b'Hb', [b'a'])  # E: Enum() expects a string literal as the first argument\nEu.a\nEb.a\nGu.a\nGb.a\nHu.a\nHb.a\n[builtins fixtures/enum.pyi]\n[out]\n\n[case testEnumIncremental]\nimport m\nreveal_type(m.E.a)\nreveal_type(m.F.b)\n[file m.py]\nfrom enum import Enum\nclass E(Enum):\n    a = 1\n    b = 2\nF = Enum('F', 'a b')\n[builtins fixtures/enum.pyi]\n[rechecked]\n[stale]\n[out1]\nmain:2: note: Revealed type is \"Literal[m.E.a]?\"\nmain:3: note: Revealed type is \"Literal[m.F.b]?\"\n[out2]\nmain:2: note: Revealed type is \"Literal[m.E.a]?\"\nmain:3: note: Revealed type is \"Literal[m.F.b]?\"\n\n[case testEnumAuto]\nfrom enum import Enum, auto\nclass Test(Enum):\n    a = auto()\n    b = auto()\n\nreveal_type(Test.a)  # N: Revealed type is \"Literal[__main__.Test.a]?\"\n[builtins fixtures/primitives.pyi]\n\n[case testEnumAttributeAccessMatrix]\nfrom enum import Enum, IntEnum, IntFlag, Flag, EnumMeta, auto\nfrom typing import Literal\n\ndef is_x(val: Literal['x']) -> None: pass\n\nA1 = Enum('A1', 'x')\nclass A2(Enum):\n    x = auto()\nclass A3(Enum):\n    x = 1\n\nis_x(reveal_type(A1.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(A1.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(A1.x.value)         # N: Revealed type is \"Any\"\nreveal_type(A1.x._value_)       # N: Revealed type is \"Any\"\nis_x(reveal_type(A2.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(A2.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(A2.x.value)         # N: Revealed type is \"builtins.int\"\nreveal_type(A2.x._value_)       # N: Revealed type is \"builtins.int\"\nis_x(reveal_type(A3.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(A3.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(A3.x.value)         # N: Revealed type is \"Literal[1]?\"\nreveal_type(A3.x._value_)       # N: Revealed type is \"Literal[1]?\"\n\nB1 = IntEnum('B1', 'x')\nclass B2(IntEnum):\n    x = auto()\nclass B3(IntEnum):\n    x = 1\n\nis_x(reveal_type(B1.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(B1.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(B1.x.value)         # N: Revealed type is \"builtins.int\"\nreveal_type(B1.x._value_)       # N: Revealed type is \"builtins.int\"\nis_x(reveal_type(B2.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(B2.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(B2.x.value)         # N: Revealed type is \"builtins.int\"\nreveal_type(B2.x._value_)       # N: Revealed type is \"builtins.int\"\nis_x(reveal_type(B3.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(B3.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(B3.x.value)         # N: Revealed type is \"Literal[1]?\"\nreveal_type(B3.x._value_)       # N: Revealed type is \"Literal[1]?\"\n\nC1 = IntFlag('C1', 'x')\nclass C2(IntFlag):\n    x = auto()\nclass C3(IntFlag):\n    x = 1\n\nis_x(reveal_type(C1.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(C1.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(C1.x.value)         # N: Revealed type is \"builtins.int\"\nreveal_type(C1.x._value_)       # N: Revealed type is \"builtins.int\"\nis_x(reveal_type(C2.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(C2.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(C2.x.value)         # N: Revealed type is \"builtins.int\"\nreveal_type(C2.x._value_)       # N: Revealed type is \"builtins.int\"\nis_x(reveal_type(C3.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(C3.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(C3.x.value)         # N: Revealed type is \"Literal[1]?\"\nreveal_type(C3.x._value_)       # N: Revealed type is \"Literal[1]?\"\n\nD1 = Flag('D1', 'x')\nclass D2(Flag):\n    x = auto()\nclass D3(Flag):\n    x = 1\n\nis_x(reveal_type(D1.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(D1.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(D1.x.value)         # N: Revealed type is \"builtins.int\"\nreveal_type(D1.x._value_)       # N: Revealed type is \"builtins.int\"\nis_x(reveal_type(D2.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(D2.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(D2.x.value)         # N: Revealed type is \"builtins.int\"\nreveal_type(D2.x._value_)       # N: Revealed type is \"builtins.int\"\nis_x(reveal_type(D3.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(D3.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(D3.x.value)         # N: Revealed type is \"Literal[1]?\"\nreveal_type(D3.x._value_)       # N: Revealed type is \"Literal[1]?\"\n\n# TODO: Generalize our enum functional API logic to work with subclasses of Enum\n# See https://github.com/python/mypy/issues/6037\n\nclass Parent(Enum): pass\n# E1 = Parent('E1', 'x')  # See above TODO\nclass E2(Parent):\n    x = auto()\nclass E3(Parent):\n    x = 1\n\nis_x(reveal_type(E2.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(E2.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(E2.x.value)         # N: Revealed type is \"builtins.int\"\nreveal_type(E2.x._value_)       # N: Revealed type is \"builtins.int\"\nis_x(reveal_type(E3.x.name))    # N: Revealed type is \"Literal['x']\"\nis_x(reveal_type(E3.x._name_))  # N: Revealed type is \"Literal['x']\"\nreveal_type(E3.x.value)         # N: Revealed type is \"Literal[1]?\"\nreveal_type(E3.x._value_)       # N: Revealed type is \"Literal[1]?\"\n\n\n# TODO: Figure out if we can construct enums using EnumMetas using the functional API.\n# Also figure out if we even care about supporting that use case.\nclass F2(metaclass=EnumMeta):\n    x = auto()\nclass F3(metaclass=EnumMeta):\n    x = 1\n\nF2.x.name      # E: \"F2\" has no attribute \"name\"\nF2.x._name_    # E: \"F2\" has no attribute \"_name_\"\nF2.x.value     # E: \"F2\" has no attribute \"value\"\nF2.x._value_   # E: \"F2\" has no attribute \"_value_\"\nF3.x.name      # E: \"F3\" has no attribute \"name\"\nF3.x._name_    # E: \"F3\" has no attribute \"_name_\"\nF3.x.value     # E: \"F3\" has no attribute \"value\"\nF3.x._value_   # E: \"F3\" has no attribute \"_value_\"\n[builtins fixtures/primitives.pyi]\n\n[case testEnumAttributeChangeIncremental]\nfrom a import SomeEnum\nreveal_type(SomeEnum.a.value)\n\n[file a.py]\nfrom b import SomeEnum\n\n[file b.py]\nfrom enum import Enum\nclass SomeEnum(Enum):\n    a = 1\n\n[file b.py.2]\nfrom enum import Enum\nclass SomeEnum(Enum):\n    a = \"foo\"\n[builtins fixtures/enum.pyi]\n[out]\nmain:2: note: Revealed type is \"Literal[1]?\"\n[out2]\nmain:2: note: Revealed type is \"Literal['foo']?\"\n\n[case testEnumReachabilityChecksBasic]\n# flags: --warn-unreachable\nfrom enum import Enum\nfrom typing import Literal\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nx: Literal[Foo.A, Foo.B, Foo.C]\nif x is Foo.A:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelif x is Foo.B:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelif x is Foo.C:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.C]\"\nelse:\n    reveal_type(x)  # E: Statement is unreachable\nreveal_type(x) # N: Revealed type is \"Literal[__main__.Foo.A] | Literal[__main__.Foo.B] | Literal[__main__.Foo.C]\"\n\nif Foo.A is x:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelif Foo.B is x:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelif Foo.C is x:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.C]\"\nelse:\n    reveal_type(x)  # E: Statement is unreachable\nreveal_type(x) # N: Revealed type is \"Literal[__main__.Foo.A] | Literal[__main__.Foo.B] | Literal[__main__.Foo.C]\"\n\ny: Foo\nif y is Foo.A:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelif y is Foo.B:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelif y is Foo.C:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.C]\"\nelse:\n    reveal_type(y)  # E: Statement is unreachable\nreveal_type(y) # N: Revealed type is \"__main__.Foo\"\n\nif Foo.A is y:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelif Foo.B is y:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelif Foo.C is y:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.C]\"\nelse:\n    reveal_type(y)  # E: Statement is unreachable\nreveal_type(y) # N: Revealed type is \"__main__.Foo\"\n[builtins fixtures/bool.pyi]\n\n[case testEnumReachabilityChecksWithOrdering]\n# flags: --warn-unreachable\nfrom enum import Enum\nfrom typing import Literal\n\nclass Foo(Enum):\n    _order_ = \"A B\"\n    A = 1\n    B = 2\n\nFoo._order_  # E: \"type[Foo]\" has no attribute \"_order_\"\n\nx: Literal[Foo.A, Foo.B]\nif x is Foo.A:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelif x is Foo.B:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelse:\n    reveal_type(x)  # E: Statement is unreachable\n\nclass Bar(Enum):\n    __order__ = \"A B\"\n    A = 1\n    B = 2\n\nBar.__order__  # E: \"type[Bar]\" has no attribute \"__order__\"\n\ny: Literal[Bar.A, Bar.B]\nif y is Bar.A:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Bar.A]\"\nelif y is Bar.B:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Bar.B]\"\nelse:\n    reveal_type(y)  # E: Statement is unreachable\n\nx2: Foo\nif x2 is Foo.A:\n    reveal_type(x2)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelif x2 is Foo.B:\n    reveal_type(x2)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelse:\n    reveal_type(x2)  # E: Statement is unreachable\n\ny2: Bar\nif y2 is Bar.A:\n    reveal_type(y2)  # N: Revealed type is \"Literal[__main__.Bar.A]\"\nelif y2 is Bar.B:\n    reveal_type(y2)  # N: Revealed type is \"Literal[__main__.Bar.B]\"\nelse:\n    reveal_type(y2)  # E: Statement is unreachable\n[builtins fixtures/tuple.pyi]\n\n[case testEnumReachabilityChecksIndirect]\n# flags: --warn-unreachable\nfrom enum import Enum\nfrom typing import Final, Literal\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n    C = 3\n\ndef accepts_foo_a(x: Literal[Foo.A]) -> None: ...\n\nx: Foo\ny: Literal[Foo.A]\nz: Final = Foo.A\n\nif x is y:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.B] | Literal[__main__.Foo.C]\"\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nreveal_type(x) # N: Revealed type is \"__main__.Foo\"\nif y is x:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.B] | Literal[__main__.Foo.C]\"\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nreveal_type(x) # N: Revealed type is \"__main__.Foo\"\n\nif x is z:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(z)  # N: Revealed type is \"Literal[__main__.Foo.A]?\"\n    accepts_foo_a(z)\nelse:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.B] | Literal[__main__.Foo.C]\"\n    reveal_type(z)  # N: Revealed type is \"Literal[__main__.Foo.A]?\"\n    accepts_foo_a(z)\nreveal_type(x) # N: Revealed type is \"__main__.Foo\"\nif z is x:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(z)  # N: Revealed type is \"Literal[__main__.Foo.A]?\"\n    accepts_foo_a(z)\nelse:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.B] | Literal[__main__.Foo.C]\"\n    reveal_type(z)  # N: Revealed type is \"Literal[__main__.Foo.A]?\"\n    accepts_foo_a(z)\nreveal_type(x) # N: Revealed type is \"__main__.Foo\"\n\nif y is z:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(z)  # N: Revealed type is \"Literal[__main__.Foo.A]?\"\n    accepts_foo_a(z)\nelse:\n    reveal_type(y)  # E: Statement is unreachable\n    reveal_type(z)\nif z is y:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(z)  # N: Revealed type is \"Literal[__main__.Foo.A]?\"\n    accepts_foo_a(z)\nelse:\n    reveal_type(y)  # E: Statement is unreachable\n    reveal_type(z)\n[builtins fixtures/bool.pyi]\n\n[case testEnumReachabilityNarrowingForUnionMessiness]\n# flags: --warn-unreachable\nfrom enum import Enum\nfrom typing import Literal\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nx: Foo\ny: Literal[Foo.A, Foo.B]\nz: Literal[Foo.B, Foo.C]\n\nif x is y:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A] | Literal[__main__.Foo.B]\"\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A] | Literal[__main__.Foo.B]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo\"\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A] | Literal[__main__.Foo.B]\"\n\nif y is z:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\n    reveal_type(z)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A] | Literal[__main__.Foo.B]\"\n    reveal_type(z)  # N: Revealed type is \"Literal[__main__.Foo.B] | Literal[__main__.Foo.C]\"\n[builtins fixtures/bool.pyi]\n\n[case testEnumReachabilityWithNone]\n# flags: --warn-unreachable\nfrom enum import Enum\nfrom typing import Optional\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nx: Optional[Foo]\nif x:\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"None\"\n\nif x is not None:\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"None\"\n\nif x is Foo.A:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.B] | Literal[__main__.Foo.C] | None\"\nreveal_type(x) # N: Revealed type is \"__main__.Foo | None\"\n[builtins fixtures/enum.pyi]\n\n[case testEnumReachabilityWithMultipleEnums]\n# flags: --warn-unreachable\nfrom enum import Enum\nfrom typing import Literal, Union\n\nclass Foo(Enum):\n    A = 1\n    B = 2\nclass Bar(Enum):\n    A = 1\n    B = 2\n\nx1: Union[Foo, Bar]\nif x1 is Foo.A:\n    reveal_type(x1)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelse:\n    reveal_type(x1)  # N: Revealed type is \"Literal[__main__.Foo.B] | __main__.Bar\"\nreveal_type(x1) # N: Revealed type is \"__main__.Foo | __main__.Bar\"\n\nx2: Union[Foo, Bar]\nif x2 is Bar.A:\n    reveal_type(x2)  # N: Revealed type is \"Literal[__main__.Bar.A]\"\nelse:\n    reveal_type(x2)  # N: Revealed type is \"__main__.Foo | Literal[__main__.Bar.B]\"\nreveal_type(x2) # N: Revealed type is \"__main__.Foo | __main__.Bar\"\n\nx3: Union[Foo, Bar]\nif x3 is Foo.A or x3 is Bar.A:\n    reveal_type(x3)  # N: Revealed type is \"Literal[__main__.Foo.A] | Literal[__main__.Bar.A]\"\nelse:\n    reveal_type(x3)  # N: Revealed type is \"Literal[__main__.Foo.B] | Literal[__main__.Bar.B]\"\nreveal_type(x3) # N: Revealed type is \"__main__.Foo | __main__.Bar\"\n\n[builtins fixtures/bool.pyi]\n\n[case testEnumReachabilityPEP484ExampleWithFinal]\n# flags: --warn-unreachable\nfrom typing import Final, Union\nfrom enum import Enum\n\nclass Empty(Enum):\n    token = 0\n_empty: Final = Empty.token\n\ndef func(x: Union[int, None, Empty] = _empty) -> int:\n    boom = x + 42       # E: Unsupported left operand type for + (\"None\") \\\n                        # E: Unsupported left operand type for + (\"Empty\") \\\n                        # N: Left operand is of type \"int | Empty | None\"\n    if x is _empty:\n        reveal_type(x)  # N: Revealed type is \"Literal[__main__.Empty.token]\"\n        return 0\n    elif x is None:\n        reveal_type(x)  # N: Revealed type is \"None\"\n        return 1\n    else:  # At this point typechecker knows that x can only have type int\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n        return x + 2\n[builtins fixtures/primitives.pyi]\n\n[case testEnumReachabilityPEP484ExampleWithMultipleValues]\n# flags: --warn-unreachable\nfrom typing import Union\nfrom enum import Enum\n\nclass Reason(Enum):\n    timeout = 1\n    error = 2\n\ndef process(response: Union[str, Reason] = '') -> str:\n    if response is Reason.timeout:\n        reveal_type(response)  # N: Revealed type is \"Literal[__main__.Reason.timeout]\"\n        return 'TIMEOUT'\n    elif response is Reason.error:\n        reveal_type(response)  # N: Revealed type is \"Literal[__main__.Reason.error]\"\n        return 'ERROR'\n    else:\n        # response can be only str, all other possible values exhausted\n        reveal_type(response)  # N: Revealed type is \"builtins.str\"\n        return 'PROCESSED: ' + response\n[builtins fixtures/primitives.pyi]\n\n\n[case testEnumReachabilityPEP484ExampleSingleton]\n# flags: --warn-unreachable\nfrom typing import Final, Union\nfrom enum import Enum\n\nclass Empty(Enum):\n    token = 0\n_empty = Empty.token\n\ndef func(x: Union[int, None, Empty] = _empty) -> int:\n    boom = x + 42       # E: Unsupported left operand type for + (\"None\") \\\n                        # E: Unsupported left operand type for + (\"Empty\") \\\n                        # N: Left operand is of type \"int | Empty | None\"\n    if x is _empty:\n        reveal_type(x)  # N: Revealed type is \"Literal[__main__.Empty.token]\"\n        return 0\n    elif x is None:\n        reveal_type(x)  # N: Revealed type is \"None\"\n        return 1\n    else:  # At this point typechecker knows that x can only have type int\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n        return x + 2\n[builtins fixtures/primitives.pyi]\n\n[case testEnumReachabilityPEP484ExampleSingletonWithMethod]\n# flags: --python-version 3.11 --warn-unreachable\nfrom typing import Final, Union\nfrom enum import Enum, member\n\nclass Empty(Enum):\n    # note, that without `member` we cannot tell that `token` is a member:\n    token = member(lambda x: x)\n\n    def f(self) -> int:\n        return 1\n\n_empty = Empty.token\nreveal_type(_empty)  # N: Revealed type is \"__main__.Empty\"\nreveal_type(Empty.f) # N: Revealed type is \"def (self: __main__.Empty) -> builtins.int\"\n\ndef func(x: Union[int, None, Empty] = _empty) -> int:\n    boom = x + 42       # E: Unsupported left operand type for + (\"None\") \\\n                        # E: Unsupported left operand type for + (\"Empty\") \\\n                        # N: Left operand is of type \"int | Empty | None\"\n    if x is _empty:\n        reveal_type(x)  # N: Revealed type is \"Literal[__main__.Empty.token]\"\n        return 0\n    elif x is None:\n        reveal_type(x)  # N: Revealed type is \"None\"\n        return 1\n    else:  # At this point typechecker knows that x can only have type int\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n        return x + 2\n[builtins fixtures/primitives.pyi]\n\n[case testAssignEnumAsAttribute]\nfrom enum import Enum\n\nclass A:\n    def __init__(self) -> None:\n        self.b = Enum(\"b\", [(\"foo\", \"bar\")])  # E: Enum type as attribute is not supported\n\nreveal_type(A().b)  # N: Revealed type is \"Any\"\n[builtins fixtures/enum.pyi]\n\n[case testEnumReachabilityWithChaining]\n# flags: --warn-unreachable\nfrom enum import Enum\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n\nx: Foo\ny: Foo\n\n# We can't narrow anything in the else cases -- what if\n# x is Foo.A and y is Foo.B or vice versa, for example?\nif x is y is Foo.A:\n    reveal_type(x)   # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(y)   # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelif x is y is Foo.B:\n    reveal_type(x)   # N: Revealed type is \"Literal[__main__.Foo.B]\"\n    reveal_type(y)   # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelse:\n    reveal_type(x)   # N: Revealed type is \"__main__.Foo\"\n    reveal_type(y)   # N: Revealed type is \"__main__.Foo\"\nreveal_type(x)       # N: Revealed type is \"__main__.Foo\"\nreveal_type(y)       # N: Revealed type is \"__main__.Foo\"\n\nif x is Foo.A is y:\n    reveal_type(x)   # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(y)   # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelif x is Foo.B is y:\n    reveal_type(x)   # N: Revealed type is \"Literal[__main__.Foo.B]\"\n    reveal_type(y)   # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelse:\n    reveal_type(x)   # N: Revealed type is \"__main__.Foo\"\n    reveal_type(y)   # N: Revealed type is \"__main__.Foo\"\nreveal_type(x)       # N: Revealed type is \"__main__.Foo\"\nreveal_type(y)       # N: Revealed type is \"__main__.Foo\"\n\nif Foo.A is x is y:\n    reveal_type(x)   # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(y)   # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelif Foo.B is x is y:\n    reveal_type(x)   # N: Revealed type is \"Literal[__main__.Foo.B]\"\n    reveal_type(y)   # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelse:\n    reveal_type(x)   # N: Revealed type is \"__main__.Foo\"\n    reveal_type(y)   # N: Revealed type is \"__main__.Foo\"\nreveal_type(x)       # N: Revealed type is \"__main__.Foo\"\nreveal_type(y)       # N: Revealed type is \"__main__.Foo\"\n\n[builtins fixtures/primitives.pyi]\n\n[case testEnumReachabilityWithChainingDisjoint]\n# flags: --warn-unreachable\nfrom enum import Enum\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n\n    # Used to divide up a chained comparison into multiple identity groups\n    def __lt__(self, other: object) -> bool: return True\n\nx: Foo\ny: Foo\n\n# No conflict\nif x is Foo.A < y is Foo.B:\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelse:\n    # Note: we can't narrow in this case. What if both x and y\n    # are Foo.A, for example?\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo\"\n    reveal_type(y)  # N: Revealed type is \"__main__.Foo\"\nreveal_type(x)      # N: Revealed type is \"__main__.Foo\"\nreveal_type(y)      # N: Revealed type is \"__main__.Foo\"\n\n# The standard output when we end up inferring two disjoint facts about the same expr\nif x is Foo.A and x is Foo.B:\n    reveal_type(x)  # E: Statement is unreachable\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo\"\nreveal_type(x)      # N: Revealed type is \"__main__.Foo\"\n\n# ..and we get the same result if we have two disjoint groups within the same comp expr\nif x is Foo.A < x is Foo.B:\n    reveal_type(x)  # E: Statement is unreachable\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo\"\nreveal_type(x)      # N: Revealed type is \"__main__.Foo\"\n[builtins fixtures/primitives.pyi]\n\n[case testEnumReachabilityWithChainingDirectConflict]\n# flags: --warn-unreachable\nfrom enum import Enum\nfrom typing import Final, Literal\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nx: Foo\nif x is Foo.A is Foo.B:\n   reveal_type(x)   # E: Statement is unreachable\nelse:\n   reveal_type(x)   # N: Revealed type is \"__main__.Foo\"\nreveal_type(x)      # N: Revealed type is \"__main__.Foo\"\n\nliteral_a: Literal[Foo.A]\nliteral_b: Literal[Foo.B]\nif x is literal_a is literal_b:\n   reveal_type(x)   # E: Statement is unreachable\nelse:\n   reveal_type(x)   # N: Revealed type is \"__main__.Foo\"\nreveal_type(x)      # N: Revealed type is \"__main__.Foo\"\n\nfinal_a: Final = Foo.A\nfinal_b: Final = Foo.B\nif x is final_a is final_b:\n   reveal_type(x)   # E: Statement is unreachable\nelse:\n   reveal_type(x)   # N: Revealed type is \"__main__.Foo\"\nreveal_type(x)      # N: Revealed type is \"__main__.Foo\"\n\n[builtins fixtures/primitives.pyi]\n\n[case testEnumReachabilityWithChainingBigDisjoints]\n# flags: --warn-unreachable\nfrom enum import Enum\nfrom typing import Final, Literal\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n    C = 3\n\n    def __lt__(self, other: object) -> bool: return True\n\nx0: Foo\nx1: Foo\nx2: Foo\nx3: Foo\nx4: Foo\nx5: Foo\n\nif x0 is x1 is Foo.A is x2 < x3 is Foo.B is x4 is x5:\n    reveal_type(x0)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(x1)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n    reveal_type(x2)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n\n    reveal_type(x3)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\n    reveal_type(x4)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\n    reveal_type(x5)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\nelse:\n    # We unfortunately can't narrow away anything. For example,\n    # what if x0 == Foo.A and x1 == Foo.B or vice versa?\n    reveal_type(x0)  # N: Revealed type is \"__main__.Foo\"\n    reveal_type(x1)  # N: Revealed type is \"__main__.Foo\"\n    reveal_type(x2)  # N: Revealed type is \"__main__.Foo\"\n\n    reveal_type(x3)  # N: Revealed type is \"__main__.Foo\"\n    reveal_type(x4)  # N: Revealed type is \"__main__.Foo\"\n    reveal_type(x5)  # N: Revealed type is \"__main__.Foo\"\n[builtins fixtures/primitives.pyi]\n\n[case testPrivateAttributeNotAsEnumMembers]\nimport enum\n\nclass Comparator(enum.Enum):\n    LessThan = \"<\"\n    LessThanOrEqualTo = \"<=\"\n    EqualTo = \"==\"\n    NotEqualTo = \"!=\"\n    GreaterThanOrEqualTo = \">=\"\n    GreaterThan = \">\"\n\n    __foo__ = {\n        LessThan: 1,\n        LessThanOrEqualTo: 2,\n        EqualTo: 3,\n        NotEqualTo: 4,\n        GreaterThanOrEqualTo: 5,\n        GreaterThan: 6,\n    }\n\n    def foo(self) -> int:\n        return Comparator.__foo__[self.value]\n\nreveal_type(Comparator.__foo__)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n[builtins fixtures/dict.pyi]\n\n[case testEnumClassAttributeUnannotated]\nimport enum\nfrom typing import ClassVar, Literal\n\nclass MyEnum(enum.Enum):\n    foo: ClassVar[str]\n    bar: str\n\n    VALUE_A = 1\n    VALUE_B = 2\n\nreveal_type(MyEnum.foo)  # N: Revealed type is \"builtins.str\"\nreveal_type(MyEnum.bar)  # N: Revealed type is \"builtins.str\"\nx: Literal[MyEnum.foo]  # E: Parameter 1 of Literal[...] is invalid\ny: Literal[MyEnum.bar]  # E: Parameter 1 of Literal[...] is invalid\n[builtins fixtures/enum.pyi]\n\n[case testEnumAttributesInheritedFromMixin]\nfrom enum import Enum\nfrom typing import TYPE_CHECKING, ClassVar, Final, Literal\n\nclass A:\n    var1 = 1\n    var2: ClassVar[str]\n    var3: Final[int] = 3\n    var4: str\n\nclass E(A, Enum):\n    mem = 1\n\nreveal_type(E.var1)  # N: Revealed type is \"builtins.int\"\nreveal_type(E.var2)  # N: Revealed type is \"builtins.str\"\nreveal_type(E.var3)  # N: Revealed type is \"builtins.int\"\nreveal_type(E.var4)  # N: Revealed type is \"builtins.str\"\nreveal_type(E.mem)  # N: Revealed type is \"Literal[__main__.E.mem]?\"\n\nE.var1.value  # E: \"int\" has no attribute \"value\"\nE.var2.name  # E: \"str\" has no attribute \"name\"\nE.mem.name\n\nx1: Literal[E.var1]  # E: Parameter 1 of Literal[...] is invalid\nx2: Literal[E.var2]  # E: Parameter 1 of Literal[...] is invalid\nx3: Literal[E.var3]  # E: Parameter 1 of Literal[...] is invalid\nx4: Literal[E.var4]  # E: Parameter 1 of Literal[...] is invalid\nm: Literal[E.mem]\n[builtins fixtures/enum.pyi]\n\n[case testEnumWithInstanceAttributes]\nfrom enum import Enum\nclass Foo(Enum):\n    def __init__(self, value: int) -> None:\n        self.foo = \"bar\"\n    A = 1\n    B = 2\n\na = Foo.A\nreveal_type(a.value)    # N: Revealed type is \"Literal[1]? | Literal[2]?\"\nreveal_type(a._value_)  # N: Revealed type is \"Literal[1]? | Literal[2]?\"\n[builtins fixtures/enum.pyi]\n\n[case testNewSetsUnexpectedValueType]\nfrom enum import Enum\n\nclass bytes:\n    def __new__(cls): pass\n\nclass Foo(bytes, Enum):\n    def __new__(cls, value: int) -> 'Foo':\n        obj = bytes.__new__(cls)\n        obj._value_ = \"Number %d\" % value\n        return obj\n    A = 1\n    B = 2\n\na = Foo.A\nreveal_type(a.value)    # N: Revealed type is \"Any\"\nreveal_type(a._value_)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testValueTypeWithNewInParentClass]\nfrom enum import Enum\n\nclass bytes:\n    def __new__(cls): pass\n\nclass Foo(bytes, Enum):\n    def __new__(cls, value: int) -> 'Foo':\n        obj = bytes.__new__(cls)\n        obj._value_ = \"Number %d\" % value\n        return obj\n\nclass Bar(Foo):\n    A = 1\n    B = 2\n\na = Bar.A\nreveal_type(a.value)    # N: Revealed type is \"Any\"\nreveal_type(a._value_)  # N: Revealed type is \"Any\"\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testValueTypeWithUserDataType]\nfrom enum import Enum\nfrom typing import Any\n\nclass Data:\n    def __new__(cls, value: Any) -> Data: pass\n\nclass DataEnum(Data, Enum):\n    A = Data(1)\n\nreveal_type(DataEnum.A)          # N: Revealed type is \"Literal[__main__.DataEnum.A]?\"\nreveal_type(DataEnum.A.value)    # N: Revealed type is \"__main__.Data\"\nreveal_type(DataEnum.A._value_)  # N: Revealed type is \"__main__.Data\"\n[builtins fixtures/tuple.pyi]\n\n[case testEnumNarrowedToTwoLiterals]\n# Regression test: two literals of an enum would be joined\n# as the full type, regardless of the amount of elements\n# the enum contains.\nfrom enum import Enum\nfrom typing import Literal, Union\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n    C = 3\n\ndef f(x: Foo):\n    if x is Foo.A:\n        return x\n    if x is Foo.B:\n        pass\n    reveal_type(x) # N: Revealed type is \"Literal[__main__.Foo.B] | Literal[__main__.Foo.C]\"\n\n[builtins fixtures/bool.pyi]\n\n[case testEnumTypeCompatibleWithLiteralUnion]\nfrom enum import Enum\nfrom typing import Literal\n\nclass E(Enum):\n    A = 1\n    B = 2\n    C = 3\n\ne: E\na: Literal[E.A, E.B, E.C] = e\nb: Literal[E.A, E.B] = e  # E: Incompatible types in assignment (expression has type \"E\", variable has type \"Literal[E.A, E.B]\")\nc: Literal[E.A, E.C] = e  # E: Incompatible types in assignment (expression has type \"E\", variable has type \"Literal[E.A, E.C]\")\nb = a  # E: Incompatible types in assignment (expression has type \"Literal[E.A, E.B, E.C]\", variable has type \"Literal[E.A, E.B]\")\n[builtins fixtures/bool.pyi]\n\n[case testIntEnumWithNewTypeValue]\nfrom typing import NewType\nfrom enum import IntEnum\n\nN = NewType(\"N\", int)\n\nclass E(IntEnum):\n    A = N(0)\n\nreveal_type(E.A.value) # N: Revealed type is \"__main__.N\"\n[builtins fixtures/enum.pyi]\n\n\n[case testEnumFinalValues]\nfrom enum import Enum\nclass Medal(Enum):\n    gold = 1\n    silver = 2\n\n# Another value:\nMedal.gold = 0  # E: Cannot assign to final attribute \"gold\"\n# Same value:\nMedal.silver = 2  # E: Cannot assign to final attribute \"silver\"\n[builtins fixtures/enum.pyi]\n\n\n[case testEnumFinalValuesCannotRedefineValueProp]\nfrom enum import Enum\nclass Types(Enum):\n    key = 0\n    value = 1\n[builtins fixtures/enum.pyi]\n\n\n[case testEnumReusedKeys]\n# https://github.com/python/mypy/issues/11248\nfrom enum import Enum\nclass Correct(Enum):\n    x = 'y'\n    y = 'x'\nclass Correct2(Enum):\n    x = 'y'\n    __z = 'y'\n    __z = 'x'\nclass Foo(Enum):\n    A = 1\n    A = 'a'  # E: Attempted to reuse member name \"A\" in Enum definition \"Foo\" \\\n             # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nreveal_type(Foo.A.value)  # N: Revealed type is \"Literal[1]?\"\n\nclass Bar(Enum):\n    A = 1\n    B = A = 2  # E: Attempted to reuse member name \"A\" in Enum definition \"Bar\"\nclass Baz(Enum):\n    A = 1\n    B, A = (1, 2)  # E: Attempted to reuse member name \"A\" in Enum definition \"Baz\"\n[builtins fixtures/tuple.pyi]\n\n[case testEnumReusedKeysOverlapWithLocalVar]\nfrom enum import Enum\nx = 1\nclass Foo(Enum):\n    x = 2\n    def method(self) -> None:\n        x = 3\nx = 4\n[builtins fixtures/bool.pyi]\n\n[case testEnumImplicitlyFinalForSubclassing]\nfrom enum import Enum, IntEnum, Flag, IntFlag\n\nclass NonEmptyEnum(Enum):\n    x = 1\nclass NonEmptyIntEnum(IntEnum):\n    x = 1\nclass NonEmptyFlag(Flag):\n    x = 1\nclass NonEmptyIntFlag(IntFlag):\n    x = 1\n\nclass ErrorEnumWithValue(NonEmptyEnum):  # E: Cannot extend enum with existing members: \"NonEmptyEnum\"\n    x = 1  # E: Cannot override final attribute \"x\" (previously declared in base class \"NonEmptyEnum\")\nclass ErrorIntEnumWithValue(NonEmptyIntEnum):  # E: Cannot extend enum with existing members: \"NonEmptyIntEnum\"\n    x = 1  # E: Cannot override final attribute \"x\" (previously declared in base class \"NonEmptyIntEnum\")\nclass ErrorFlagWithValue(NonEmptyFlag):  # E: Cannot extend enum with existing members: \"NonEmptyFlag\"\n    x = 1  # E: Cannot override final attribute \"x\" (previously declared in base class \"NonEmptyFlag\")\nclass ErrorIntFlagWithValue(NonEmptyIntFlag):  # E: Cannot extend enum with existing members: \"NonEmptyIntFlag\"\n    x = 1  # E: Cannot override final attribute \"x\" (previously declared in base class \"NonEmptyIntFlag\")\n\nclass ErrorEnumWithoutValue(NonEmptyEnum):  # E: Cannot extend enum with existing members: \"NonEmptyEnum\"\n    pass\nclass ErrorIntEnumWithoutValue(NonEmptyIntEnum):  # E: Cannot extend enum with existing members: \"NonEmptyIntEnum\"\n    pass\nclass ErrorFlagWithoutValue(NonEmptyFlag):  # E: Cannot extend enum with existing members: \"NonEmptyFlag\"\n    pass\nclass ErrorIntFlagWithoutValue(NonEmptyIntFlag):  # E: Cannot extend enum with existing members: \"NonEmptyIntFlag\"\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testEnumImplicitlyFinalForSubclassingWithCallableMember]\n# flags: --python-version 3.11\nfrom enum import Enum, IntEnum, Flag, IntFlag, member\n\nclass NonEmptyEnum(Enum):\n    @member\n    def call(self) -> None: ...\nclass NonEmptyIntEnum(IntEnum):\n    @member\n    def call(self) -> None: ...\nclass NonEmptyFlag(Flag):\n    @member\n    def call(self) -> None: ...\nclass NonEmptyIntFlag(IntFlag):\n    @member\n    def call(self) -> None: ...\n\nclass ErrorEnumWithoutValue(NonEmptyEnum):  # E: Cannot extend enum with existing members: \"NonEmptyEnum\"\n    pass\nclass ErrorIntEnumWithoutValue(NonEmptyIntEnum):  # E: Cannot extend enum with existing members: \"NonEmptyIntEnum\"\n    pass\nclass ErrorFlagWithoutValue(NonEmptyFlag):  # E: Cannot extend enum with existing members: \"NonEmptyFlag\"\n    pass\nclass ErrorIntFlagWithoutValue(NonEmptyIntFlag):  # E: Cannot extend enum with existing members: \"NonEmptyIntFlag\"\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testEnumCanExtendEnumsWithNonMembers]\n# flags: --python-version 3.11\nfrom enum import Enum, IntEnum, Flag, IntFlag, nonmember\n\nclass NonEmptyEnum(Enum):\n    x = nonmember(1)\nclass NonEmptyIntEnum(IntEnum):\n    x = nonmember(1)\nclass NonEmptyFlag(Flag):\n    x = nonmember(1)\nclass NonEmptyIntFlag(IntFlag):\n    x = nonmember(1)\n\nclass ErrorEnumWithoutValue(NonEmptyEnum):\n    pass\nclass ErrorIntEnumWithoutValue(NonEmptyIntEnum):\n    pass\nclass ErrorFlagWithoutValue(NonEmptyFlag):\n    pass\nclass ErrorIntFlagWithoutValue(NonEmptyIntFlag):\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testLambdaIsNotEnumMember]\nfrom enum import Enum\n\nclass My(Enum):\n    x = lambda a: a\n\nclass Other(My): ...\n[builtins fixtures/bool.pyi]\n\n[case testSubclassingNonFinalEnums]\nfrom enum import Enum, IntEnum, Flag, IntFlag, EnumMeta\n\ndef decorator(func):\n    return func\n\nclass EmptyEnum(Enum):\n    pass\nclass EmptyIntEnum(IntEnum):\n    pass\nclass EmptyFlag(Flag):\n    pass\nclass EmptyIntFlag(IntFlag):\n    pass\nclass EmptyEnumMeta(EnumMeta):\n    pass\n\nclass NonEmptyEnumSub(EmptyEnum):\n    x = 1\nclass NonEmptyIntEnumSub(EmptyIntEnum):\n    x = 1\nclass NonEmptyFlagSub(EmptyFlag):\n    x = 1\nclass NonEmptyIntFlagSub(EmptyIntFlag):\n    x = 1\nclass NonEmptyEnumMetaSub(EmptyEnumMeta):\n    x = 1\n\nclass EmptyEnumSub(EmptyEnum):\n    def method(self) -> None: pass\n    @decorator\n    def other(self) -> None: pass\nclass EmptyIntEnumSub(EmptyIntEnum):\n    def method(self) -> None: pass\nclass EmptyFlagSub(EmptyFlag):\n    def method(self) -> None: pass\nclass EmptyIntFlagSub(EmptyIntFlag):\n    def method(self) -> None: pass\nclass EmptyEnumMetaSub(EmptyEnumMeta):\n    def method(self) -> None: pass\n\nclass NestedEmptyEnumSub(EmptyEnumSub):\n    x = 1\nclass NestedEmptyIntEnumSub(EmptyIntEnumSub):\n    x = 1\nclass NestedEmptyFlagSub(EmptyFlagSub):\n    x = 1\nclass NestedEmptyIntFlagSub(EmptyIntFlagSub):\n    x = 1\nclass NestedEmptyEnumMetaSub(EmptyEnumMetaSub):\n    x = 1\n[builtins fixtures/bool.pyi]\n\n[case testEnumExplicitlyAndImplicitlyFinal]\nfrom typing import final\nfrom enum import Enum, IntEnum, Flag, IntFlag, EnumMeta\n\n@final\nclass EmptyEnum(Enum):\n    pass\n@final\nclass EmptyIntEnum(IntEnum):\n    pass\n@final\nclass EmptyFlag(Flag):\n    pass\n@final\nclass EmptyIntFlag(IntFlag):\n    pass\n@final\nclass EmptyEnumMeta(EnumMeta):\n    pass\n\nclass EmptyEnumSub(EmptyEnum):  # E: Cannot inherit from final class \"EmptyEnum\"\n    pass\nclass EmptyIntEnumSub(EmptyIntEnum):  # E: Cannot inherit from final class \"EmptyIntEnum\"\n    pass\nclass EmptyFlagSub(EmptyFlag):  # E: Cannot inherit from final class \"EmptyFlag\"\n    pass\nclass EmptyIntFlagSub(EmptyIntFlag):  # E: Cannot inherit from final class \"EmptyIntFlag\"\n    pass\nclass EmptyEnumMetaSub(EmptyEnumMeta):  # E: Cannot inherit from final class \"EmptyEnumMeta\"\n    pass\n\n@final\nclass NonEmptyEnum(Enum):\n    x = 1\n@final\nclass NonEmptyIntEnum(IntEnum):\n    x = 1\n@final\nclass NonEmptyFlag(Flag):\n    x = 1\n@final\nclass NonEmptyIntFlag(IntFlag):\n    x = 1\n@final\nclass NonEmptyEnumMeta(EnumMeta):\n    x = 1\n\nclass ErrorEnumWithoutValue(NonEmptyEnum):  # E: Cannot inherit from final class \"NonEmptyEnum\" \\\n                                            # E: Cannot extend enum with existing members: \"NonEmptyEnum\"\n    pass\nclass ErrorIntEnumWithoutValue(NonEmptyIntEnum):  # E: Cannot inherit from final class \"NonEmptyIntEnum\" \\\n                                                  # E: Cannot extend enum with existing members: \"NonEmptyIntEnum\"\n    pass\nclass ErrorFlagWithoutValue(NonEmptyFlag):  # E: Cannot inherit from final class \"NonEmptyFlag\" \\\n                                            # E: Cannot extend enum with existing members: \"NonEmptyFlag\"\n    pass\nclass ErrorIntFlagWithoutValue(NonEmptyIntFlag):  # E: Cannot inherit from final class \"NonEmptyIntFlag\" \\\n                                                  # E: Cannot extend enum with existing members: \"NonEmptyIntFlag\"\n    pass\nclass ErrorEnumMetaWithoutValue(NonEmptyEnumMeta):  # E: Cannot inherit from final class \"NonEmptyEnumMeta\"\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testEnumFinalSubtypingEnumMetaSpecialCase]\nfrom enum import EnumMeta\n# `EnumMeta` types are not `Enum`s\nclass SubMeta(EnumMeta):\n    x = 1\nclass SubSubMeta(SubMeta):\n    x = 2\n[builtins fixtures/bool.pyi]\n\n[case testEnumFinalSubtypingOverloadedSpecialCase]\nfrom typing import overload\nfrom enum import Enum, IntEnum, Flag, IntFlag, EnumMeta\n\nclass EmptyEnum(Enum):\n    @overload\n    def method(self, arg: int) -> int:\n        pass\n    @overload\n    def method(self, arg: str) -> str:\n        pass\n    def method(self, arg):\n        pass\nclass EmptyIntEnum(IntEnum):\n    @overload\n    def method(self, arg: int) -> int:\n        pass\n    @overload\n    def method(self, arg: str) -> str:\n        pass\n    def method(self, arg):\n        pass\nclass EmptyFlag(Flag):\n    @overload\n    def method(self, arg: int) -> int:\n        pass\n    @overload\n    def method(self, arg: str) -> str:\n        pass\n    def method(self, arg):\n        pass\nclass EmptyIntFlag(IntFlag):\n    @overload\n    def method(self, arg: int) -> int:\n        pass\n    @overload\n    def method(self, arg: str) -> str:\n        pass\n    def method(self, arg):\n        pass\nclass EmptyEnumMeta(EnumMeta):\n    @overload\n    def method(self, arg: int) -> int:\n        pass\n    @overload\n    def method(self, arg: str) -> str:\n        pass\n    def method(self, arg):\n        pass\n\nclass NonEmptyEnumSub(EmptyEnum):\n    x = 1\nclass NonEmptyIntEnumSub(EmptyIntEnum):\n    x = 1\nclass NonEmptyFlagSub(EmptyFlag):\n    x = 1\nclass NonEmptyIntFlagSub(EmptyIntFlag):\n    x = 1\nclass NonEmptyEnumMetaSub(EmptyEnumMeta):\n    x = 1\n[builtins fixtures/bool.pyi]\n\n[case testEnumFinalSubtypingMethodAndValueSpecialCase]\nfrom enum import Enum, IntEnum, Flag, IntFlag, EnumMeta\n\ndef decorator(func):\n    return func\n\nclass NonEmptyEnum(Enum):\n    x = 1\n    def method(self) -> None: pass\n    @decorator\n    def other(self) -> None: pass\nclass NonEmptyIntEnum(IntEnum):\n    x = 1\n    def method(self) -> None: pass\nclass NonEmptyFlag(Flag):\n    x = 1\n    def method(self) -> None: pass\nclass NonEmptyIntFlag(IntFlag):\n    x = 1\n    def method(self) -> None: pass\n\nclass ErrorEnumWithoutValue(NonEmptyEnum):  # E: Cannot extend enum with existing members: \"NonEmptyEnum\"\n    pass\nclass ErrorIntEnumWithoutValue(NonEmptyIntEnum):  # E: Cannot extend enum with existing members: \"NonEmptyIntEnum\"\n    pass\nclass ErrorFlagWithoutValue(NonEmptyFlag):  # E: Cannot extend enum with existing members: \"NonEmptyFlag\"\n    pass\nclass ErrorIntFlagWithoutValue(NonEmptyIntFlag):  # E: Cannot extend enum with existing members: \"NonEmptyIntFlag\"\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testFinalEnumWithClassDef]\nfrom enum import Enum\n\nclass A(Enum):\n    class Inner: pass\nclass B(A): pass  # E: Cannot extend enum with existing members: \"A\"\n\nclass A1(Enum):\n    class __Inner: pass\nclass B1(A1): pass\n[builtins fixtures/bool.pyi]\n\n[case testEnumFinalSpecialProps]\n# https://github.com/python/mypy/issues/11699\n# https://github.com/python/mypy/issues/11820\nfrom enum import Enum, IntEnum\n\nclass BaseWithSpecials:\n    __slots__ = ()\n    __doc__ = 'doc'\n    __module__ = 'module'\n    __annotations__ = {'a': int}\n    __dict__ = {'a': 1}\n\nclass E(BaseWithSpecials, Enum):\n    name = 'a'\n    value = 'b'\n    _name_ = 'a1'\n    _value_ = 'b2'\n    _order_ = 'X Y'\n    __order__ = 'X Y'\n    __slots__ = ()\n    __doc__ = 'doc'\n    __module__ = 'module'\n    __annotations__ = {'a': int}\n    __dict__ = {'a': 1}\n\nclass EI(IntEnum):\n    name = 'a'\n    value = 1\n    _name_ = 'a1'\n    _value_ = 2\n    _order_ = 'X Y'\n    __order__ = 'X Y'\n    __slots__ = ()\n    __doc__ = 'doc'\n    __module__ = 'module'\n    __annotations__ = {'a': int}\n    __dict__ = {'a': 1}\n\nE._order_ = 'a'  # E: Cannot assign to final attribute \"_order_\"\nEI.value = 2     # E: Cannot assign to final attribute \"value\"\n[builtins fixtures/dict.pyi]\n\n[case testEnumNotFinalWithMethodsAndUninitializedValues]\n# https://github.com/python/mypy/issues/11578\nfrom enum import Enum\nfrom typing import Final\n\nclass A(Enum):\n    x: int\n    def method(self) -> int: pass\nclass B(A):\n    x = 1  # E: Cannot override writable attribute \"x\" with a final one \\\n           # E: Incompatible types in assignment (expression has type \"B\", base class \"A\" defined the type as \"int\")\n\nclass A1(Enum):\n    x: int = 1  # E: Enum members must be left unannotated \\\n                # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members\nclass B1(A1):  # E: Cannot extend enum with existing members: \"A1\"\n    pass\n\nclass A2(Enum):\n    x = 2\nclass B2(A2):  # E: Cannot extend enum with existing members: \"A2\"\n    pass\n\n# We leave this `Final` without a value,\n# because we need to test annotation only mode:\nclass A3(Enum):\n    x: Final[int]  # type: ignore\nclass B3(A3):\n    x = 1  # E: Cannot override final attribute \"x\" (previously declared in base class \"A3\") \\\n           # E: Incompatible types in assignment (expression has type \"B3\", base class \"A3\" defined the type as \"int\")\n[builtins fixtures/bool.pyi]\n\n[case testEnumNotFinalWithMethodsAndUninitializedValuesStub]\nimport lib\n\n[file lib.pyi]\nfrom enum import Enum\nclass A(Enum):  # E: Detected enum \"lib.A\" in a type stub with zero members. There is a chance this is due to a recent change in the semantics of enum membership. If so, use `member = value` to mark an enum member, instead of `member: type` \\\n                # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members\n    x: int\nclass B(A):\n    x = 1    # E: Cannot override writable attribute \"x\" with a final one \\\n             # E: Incompatible types in assignment (expression has type \"B\", base class \"A\" defined the type as \"int\")\n\nclass C(Enum):\n    x = 1\nclass D(C):  # E: Cannot extend enum with existing members: \"C\" \\\n             # E: Detected enum \"lib.D\" in a type stub with zero members. There is a chance this is due to a recent change in the semantics of enum membership. If so, use `member = value` to mark an enum member, instead of `member: type` \\\n             # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members\n    x: int   # E: Incompatible types in assignment (expression has type \"int\", base class \"C\" defined the type as \"C\") \\\n             # E: Cannot assign to final name \"x\"\n[builtins fixtures/bool.pyi]\n\n[case testEnumNotFinalWithMethodsAndUninitializedValuesStubMember]\n# flags: --python-version 3.11\n# This was added in 3.11\nimport lib\n\n[file lib.pyi]\nfrom enum import Enum, member\nclass A(Enum):\n    @member\n    def x(self) -> None: ...\n[builtins fixtures/bool.pyi]\n\n[case testEnumLiteralValues]\nfrom enum import Enum\n\nclass A(Enum):\n    str = \"foo\"\n    int = 1\n    bool = False\n    tuple = (1,)\n\nreveal_type(A.str.value)  # N: Revealed type is \"Literal['foo']?\"\nreveal_type(A.int.value)  # N: Revealed type is \"Literal[1]?\"\nreveal_type(A.bool.value)  # N: Revealed type is \"Literal[False]?\"\nreveal_type(A.tuple.value)  # N: Revealed type is \"tuple[Literal[1]?]\"\n[builtins fixtures/tuple.pyi]\n\n[case testFinalWithPrivateAssignment]\nimport enum\nclass Some(enum.Enum):\n    __priv = 1\n\nclass Other(Some):  # Should pass\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testFinalWithDunderAssignment]\nimport enum\nclass Some(enum.Enum):\n    __some__ = 1\n\nclass Other(Some):  # Should pass\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testFinalWithSunderAssignment]\nimport enum\nclass Some(enum.Enum):\n    _some_ = 1\n\nclass Other(Some):  # Should pass\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testFinalWithMethodAssignment]\nimport enum\nfrom typing import overload\nclass Some(enum.Enum):\n    def lor(self, other) -> bool:\n        pass\n\n    ror = lor\n\nclass Other(Some):  # Should pass\n    pass\n\n\nclass WithOverload(enum.IntEnum):\n    @overload\n    def meth(self, arg: int) -> int: pass\n    @overload\n    def meth(self, arg: str) -> str: pass\n    def meth(self, arg): pass\n\n    alias = meth\n\nclass SubWithOverload(WithOverload):  # Should pass\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testEnumBaseClassesOrder]\nimport enum\n\n# Base types:\n\nclass First:\n    def __new__(cls, val):\n        pass\n\nclass Second:\n    def __new__(cls, val):\n        pass\n\nclass Third:\n    def __new__(cls, val):\n        pass\n\nclass Mixin:\n    pass\n\nclass EnumWithCustomNew(enum.Enum):\n    def __new__(cls, val):\n        pass\n\nclass SecondEnumWithCustomNew(enum.Enum):\n    def __new__(cls, val):\n        pass\n\n# Correct Enums:\n\nclass Correct0(enum.Enum):\n    pass\n\nclass Correct1(Mixin, First, enum.Enum):\n    pass\n\nclass Correct2(First, enum.Enum):\n    pass\n\nclass Correct3(Mixin, enum.Enum):\n    pass\n\nclass RegularClass(Mixin, First, Second):\n    pass\n\nclass Correct5(enum.Enum):\n    pass\n\n# Correct inheritance:\n\nclass _InheritingDataAndMixin(Correct1):\n    pass\n\nclass _CorrectWithData(First, Correct0):\n    pass\n\nclass _CorrectWithDataAndMixin(Mixin, First, Correct0):\n    pass\n\nclass _CorrectWithMixin(Mixin, Correct2):\n    pass\n\nclass _CorrectMultipleEnumBases(Correct0, Correct5):\n    pass\n\nclass _MultipleEnumBasesAndMixin(int, Correct0, enum.Flag):\n    pass\n\nclass _MultipleEnumBasesWithCustomNew(int, EnumWithCustomNew, SecondEnumWithCustomNew):\n    pass\n\n# Wrong Enums:\n\nclass TwoDataTypesViaInheritance(Second, Correct2):  # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.Correct2\"\n    pass\n\nclass TwoDataTypesViaInheritanceAndMixin(Second, Correct2, Mixin):  # E: No non-enum mixin classes are allowed after \"__main__.Correct2\" \\\n                                                                    # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.Correct2\"\n    pass\n\nclass MixinAfterEnum1(enum.Enum, Mixin):  # E: No non-enum mixin classes are allowed after \"enum.Enum\"\n    pass\n\nclass MixinAfterEnum2(First, enum.Enum, Mixin):  # E: No non-enum mixin classes are allowed after \"enum.Enum\"\n    pass\n\nclass TwoDataTypes(First, Second, enum.Enum):  # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.Second\"\n    pass\n\nclass TwoDataTypesAndIntEnumMixin(First, Second, enum.IntEnum, Mixin):  # E: No non-enum mixin classes are allowed after \"enum.IntEnum\" \\\n                                                                        # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.Second\"\n    pass\n\nclass ThreeDataTypes(First, Second, Third, enum.Enum):  # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.Second\" \\\n                                                        # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.Third\"\n    pass\n\nclass ThreeDataTypesAndMixin(First, Second, Third, enum.Enum, Mixin):  # E: No non-enum mixin classes are allowed after \"enum.Enum\" \\\n                                                                       # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.Second\" \\\n                                                                       # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.Third\"\n    pass\n\nclass FromEnumAndOther1(Correct2, Second, enum.Enum):  # E: No non-enum mixin classes are allowed after \"__main__.Correct2\" \\\n                                                       # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.Second\"\n    pass\n\nclass FromEnumAndOther2(Correct2, Second):  # E: No non-enum mixin classes are allowed after \"__main__.Correct2\" \\\n                                            # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.Second\"\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testRegression12258]\nfrom enum import Enum\n\nclass MyEnum(Enum): ...\n\nclass BytesEnum(bytes, MyEnum): ...  # Should be ok\n[builtins fixtures/tuple.pyi]\n\n[case testEnumWithNewHierarchy]\nimport enum\n\nclass A:\n    def __new__(cls, val): ...\nclass B(A):\n    def __new__(cls, val): ...\nclass C:\n    def __new__(cls, val): ...\n\nclass E1(A, enum.Enum): ...\nclass E2(B, enum.Enum): ...\n\n# Errors:\n\nclass W1(C, E1): ...  # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.E1\"\nclass W2(C, E2): ...  # E: Only a single data type mixin is allowed for Enum subtypes, found extra \"__main__.E2\"\n[builtins fixtures/tuple.pyi]\n\n[case testEnumValueUnionSimplification]\nfrom enum import IntEnum\nfrom typing import Any\n\nclass C(IntEnum):\n    X = 0\n    Y = 1\n    Z = 2\n\ndef f1(c: C) -> None:\n    x = {'x': c.value}\n    reveal_type(x)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n\ndef f2(c: C, a: Any) -> None:\n    x = {'x': c.value, 'y': a}\n    reveal_type(x)  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\n    y = {'y': a, 'x': c.value}\n    reveal_type(y)  # N: Revealed type is \"builtins.dict[builtins.str, Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testEnumIgnoreIsDeleted]\nfrom enum import Enum\n\nclass C(Enum):\n    _ignore_ = 'X'\n\nC._ignore_ # E: \"type[C]\" has no attribute \"_ignore_\"\n[builtins fixtures/enum.pyi]\n\n[case testCanOverrideDunderAttributes]\nimport typing\nfrom enum import Enum, Flag\n\nclass BaseEnum(Enum):\n    __dunder__ = 1\n    __labels__: typing.Dict[int, str]\n\nclass Override(BaseEnum):\n    __dunder__ = 2\n    __labels__ = {1: \"1\"}\n\nOverride.__dunder__ = 3\nBaseEnum.__dunder__ = 3\nOverride.__labels__ = {2: \"2\"}\n\nclass FlagBase(Flag):\n    __dunder__ = 1\n    __labels__: typing.Dict[int, str]\n\nclass FlagOverride(FlagBase):\n    __dunder__ = 2\n    __labels = {1: \"1\"}\n\nFlagOverride.__dunder__ = 3\nFlagBase.__dunder__ = 3\nFlagOverride.__labels__ = {2: \"2\"}\n[builtins fixtures/dict.pyi]\n\n[case testCanNotInitialize__members__]\nimport typing\nfrom enum import Enum\n\nclass WritingMembers(Enum):\n    __members__: typing.Dict[Enum, Enum] = {}  # E: Assigned \"__members__\" will be overridden by \"Enum\" internally\n\nclass OnlyAnnotatedMembers(Enum):\n    __members__: typing.Dict[Enum, Enum]\n[builtins fixtures/dict.pyi]\n\n[case testCanOverrideDunderOnNonFirstBaseEnum]\nimport typing\nfrom enum import Enum\n\nclass Some:\n    __labels__: typing.Dict[int, str]\n\nclass A(Some, Enum):\n    __labels__ = {1: \"1\"}\n[builtins fixtures/dict.pyi]\n\n[case testEnumWithPartialTypes]\nfrom enum import Enum\n\nclass Mixed(Enum):\n    a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n    b = None\n\n    def check(self) -> None:\n        reveal_type(Mixed.a.value)  # N: Revealed type is \"builtins.list[Any]\"\n        reveal_type(Mixed.b.value)  # N: Revealed type is \"None\"\n\n        # Inferring Any here instead of a union seems to be a deliberate\n        # choice; see the testEnumValueInhomogeneous case above.\n        reveal_type(self.value)  # N: Revealed type is \"Any\"\n\n        for field in Mixed:\n            reveal_type(field.value)  # N: Revealed type is \"Any\"\n            if field.value is None:\n                pass\n\nclass AllPartialList(Enum):\n    a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n    b = []  # E: Need type annotation for \"b\" (hint: \"b: list[<type>] = ...\")\n\n    def check(self) -> None:\n        reveal_type(self.value)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/tuple.pyi]\n\n[case testEnumPrivateAttributeNotMember]\nfrom enum import Enum\n\nclass MyEnum(Enum):\n    A = 1\n    B = 2\n    __my_dict = {A: \"ham\", B: \"spam\"}\n\n# TODO: change the next line to use MyEnum._MyEnum__my_dict when mypy implements name mangling\nx: MyEnum = MyEnum.__my_dict  # E: Incompatible types in assignment (expression has type \"dict[int, str]\", variable has type \"MyEnum\")\n[builtins fixtures/enum.pyi]\n\n[case testEnumWithPrivateAttributeReachability]\n# flags: --warn-unreachable\nfrom enum import Enum\n\nclass MyEnum(Enum):\n    A = 1\n    B = 2\n    __my_dict = {A: \"ham\", B: \"spam\"}\n\ne: MyEnum\nif e == MyEnum.A:\n    reveal_type(e)  # N: Revealed type is \"Literal[__main__.MyEnum.A]\"\nelif e == MyEnum.B:\n    reveal_type(e)  # N: Revealed type is \"Literal[__main__.MyEnum.B]\"\nelse:\n    reveal_type(e)  # E: Statement is unreachable\n[builtins fixtures/dict.pyi]\n\n\n[case testEnumNonMemberSupport]\n# flags: --python-version 3.11\n# This was added in 3.11\nfrom enum import Enum, nonmember\n\nclass My(Enum):\n    a = 1\n    b = 2\n    c = nonmember(3)\n\nreveal_type(My.a)  # N: Revealed type is \"Literal[__main__.My.a]?\"\nreveal_type(My.b)  # N: Revealed type is \"Literal[__main__.My.b]?\"\nreveal_type(My.c)  # N: Revealed type is \"builtins.int\"\n\ndef accepts_my(my: My):\n    reveal_type(my.value)  # N: Revealed type is \"Literal[1]? | Literal[2]?\"\n\nclass Other(Enum):\n    a = 1\n    @nonmember\n    class Support:\n        b = 2\n\nreveal_type(Other.a)  # N: Revealed type is \"Literal[__main__.Other.a]?\"\nreveal_type(Other.Support.b)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n\n\n[case testEnumMemberSupport]\n# flags: --python-version 3.11\n# This was added in 3.11\nfrom enum import Enum, member\n\nclass A(Enum):\n    x = member(1)\n    y = 2\n\nreveal_type(A.x)  # N: Revealed type is \"Literal[__main__.A.x]?\"\nreveal_type(A.x.value)  # N: Revealed type is \"Literal[1]?\"\nreveal_type(A.y)  # N: Revealed type is \"Literal[__main__.A.y]?\"\nreveal_type(A.y.value)  # N: Revealed type is \"Literal[2]?\"\n\ndef some_a(a: A):\n    reveal_type(a.value)  # N: Revealed type is \"Literal[1]? | Literal[2]?\"\n[builtins fixtures/dict.pyi]\n\n\n[case testEnumMemberAndNonMemberSupport]\n# flags: --python-version 3.11 --warn-unreachable\n# This was added in 3.11\nfrom enum import Enum, member, nonmember\n\nclass A(Enum):\n    x = 1\n    y = member(2)\n    z = nonmember(3)\n\ndef some_a(a: A):\n    if a is not A.x and a is not A.z:\n        reveal_type(a)  # N: Revealed type is \"Literal[__main__.A.y]\"\n    if a is not A.y and a is not A.z:\n        reveal_type(a)  # N: Revealed type is \"Literal[__main__.A.x]\"\n    if a is not A.x:\n        reveal_type(a)  # N: Revealed type is \"Literal[__main__.A.y]\"\n    if a is not A.y:\n        reveal_type(a)  # N: Revealed type is \"Literal[__main__.A.x]\"\n[builtins fixtures/dict.pyi]\n\n[case testEnumAccessFromInstance]\n# flags: --python-version 3.11 --warn-unreachable\n# This was added in 3.11\nfrom enum import Enum, member, nonmember\n\nclass A(Enum):\n    x = 1\n    y = member(2)\n    z = nonmember(3)\n\nreveal_type(A.x)  # N: Revealed type is \"Literal[__main__.A.x]?\"\nreveal_type(A.y)  # N: Revealed type is \"Literal[__main__.A.y]?\"\nreveal_type(A.z)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(A.x.x)  # N: Revealed type is \"Literal[__main__.A.x]?\"\nreveal_type(A.x.x.x)  # N: Revealed type is \"Literal[__main__.A.x]?\"\nreveal_type(A.x.y)  # N: Revealed type is \"Literal[__main__.A.y]?\"\nreveal_type(A.x.y.y)  # N: Revealed type is \"Literal[__main__.A.y]?\"\nreveal_type(A.x.z)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(A.y.x)  # N: Revealed type is \"Literal[__main__.A.x]?\"\nreveal_type(A.y.y)  # N: Revealed type is \"Literal[__main__.A.y]?\"\nreveal_type(A.y.z)  # N: Revealed type is \"builtins.int\"\n\nA.z.x  # E: \"int\" has no attribute \"x\"\n\nclass B(Enum):\n    x = 1\n    value = 2\n\nreveal_type(B.x)  # N: Revealed type is \"Literal[__main__.B.x]?\"\nreveal_type(B.x.value)  # N: Revealed type is \"Literal[2]?\"\nreveal_type(B.x.x.value)  # N: Revealed type is \"Literal[2]?\"\nB.x.value.value  # E: \"int\" has no attribute \"value\"\nB.x.value.value.value  # E: \"int\" has no attribute \"value\"\nreveal_type(B.value)  # N: Revealed type is \"Literal[__main__.B.value]?\"\nreveal_type(B.value.x)  # N: Revealed type is \"Literal[__main__.B.x]?\"\nreveal_type(B.value.x.x)  # N: Revealed type is \"Literal[__main__.B.x]?\"\nreveal_type(B.value.x.value)  # N: Revealed type is \"Literal[2]?\"\nB.value.x.value.value  # E: \"int\" has no attribute \"value\"\nB.value.value.value  # E: \"int\" has no attribute \"value\"\n[builtins fixtures/dict.pyi]\n\n\n[case testErrorOnAnnotatedMember]\nfrom enum import Enum\n\nclass Medal(Enum):\n    gold: int = 1  # E: Enum members must be left unannotated \\\n                   # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members\n    silver: str = 2  # E: Enum members must be left unannotated \\\n                     # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \\\n                     # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    bronze = 3\n[builtins fixtures/enum.pyi]\n\n[case testEnumMemberWithPlaceholder]\nfrom enum import Enum\n\nclass Pet(Enum):\n    CAT = ...\n    DOG: str = ...  # E: Enum members must be left unannotated \\\n                    # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \\\n                    # E: Incompatible types in assignment (expression has type \"ellipsis\", variable has type \"str\")\n[builtins fixtures/enum.pyi]\n\n[case testEnumValueWithPlaceholderNodeType]\n# https://github.com/python/mypy/issues/11971\nfrom enum import Enum\nfrom typing import Any, Callable, Dict\nclass Foo(Enum):\n    Bar: Foo = Callable[[str], None]  # E: Enum members must be left unannotated \\\n                                      # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \\\n                                      # E: Incompatible types in assignment (expression has type \"<typing special form>\", variable has type \"Foo\")\n    Baz: Any = Callable[[Dict[str, \"Missing\"]], None]  # E: Enum members must be left unannotated \\\n                                                       # N: See https://typing.readthedocs.io/en/latest/spec/enums.html#defining-members \\\n                                                       # E: Type application targets a non-generic function or class \\\n                                                       # E: Name \"Missing\" is not defined\n\nreveal_type(Foo.Bar)  # N: Revealed type is \"Literal[__main__.Foo.Bar]?\"\nreveal_type(Foo.Bar.value)  # N: Revealed type is \"__main__.Foo\"\nreveal_type(Foo.Baz)  # N: Revealed type is \"Literal[__main__.Foo.Baz]?\"\nreveal_type(Foo.Baz.value)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n\n[case testEnumWithOnlyImplicitMembersUsingAnnotationOnly]\n# flags: --warn-unreachable\nimport enum\n\n\nclass E(enum.IntEnum):\n    A: int\n    B: int\n\n\ndef do_check(value: E) -> None:\n    reveal_type(value)  # N: Revealed type is \"__main__.E\"\n    # this is a nonmember check, not an emum member check, and it should not narrow the value\n    if value is E.A:\n        return\n\n    reveal_type(value)  # N: Revealed type is \"__main__.E\"\n    \"should be reachable\"\n\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrEnumClassCorrectIterable]\nfrom enum import StrEnum\nfrom typing import Type, TypeVar\n\nclass Choices(StrEnum):\n    LOREM = \"lorem\"\n    IPSUM = \"ipsum\"\n\nvar = list(Choices)\nreveal_type(var)  # N: Revealed type is \"builtins.list[__main__.Choices]\"\n\ne: type[StrEnum]\nreveal_type(list(e))  # N: Revealed type is \"builtins.list[enum.StrEnum]\"\n\nT = TypeVar(\"T\", bound=StrEnum)\ndef list_vals(e: Type[T]) -> list[T]:\n    reveal_type(list(e))  # N: Revealed type is \"builtins.list[T`-1]\"\n    return list(e)\n\nreveal_type(list_vals(Choices))  # N: Revealed type is \"builtins.list[__main__.Choices]\"\n[builtins fixtures/enum.pyi]\n\n[case testEnumAsClassMemberNoCrash]\n# https://github.com/python/mypy/issues/18736\nfrom enum import Enum\n\nclass Base:\n    def __init__(self, namespace: tuple[str, ...]) -> None:\n        # Not a bug: trigger defer\n        names = [name for name in namespace if fail]  # E: Name \"fail\" is not defined\n        self.o = Enum(\"o\", names)  # E: Enum type as attribute is not supported \\\n                                   # E: Second argument of Enum() must be string, tuple, list or dict literal for mypy to determine Enum members\n[builtins fixtures/tuple.pyi]\n\n[case testSingleUnderscoreNameEnumMember]\n# flags: --warn-unreachable\n\n# https://github.com/python/mypy/issues/19271\nfrom enum import Enum\n\nclass Things(Enum):\n    _ = \"under score\"\n\ndef check(thing: Things) -> None:\n    if thing is Things._:\n        return None\n    return None  # E: Statement is unreachable\n[builtins fixtures/enum.pyi]\n\n[case testSunderValueTypeEllipsis]\nfrom foo.bar import (\n    Basic, FromStub, InheritedInt, InheritedStr, InheritedFlag,\n    InheritedIntFlag, Wrapper\n)\n\nreveal_type(Basic.FOO)  # N: Revealed type is \"Literal[foo.bar.Basic.FOO]?\"\nreveal_type(Basic.FOO.value)  # N: Revealed type is \"Literal[1]?\"\nreveal_type(Basic.FOO._value_)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(FromStub.FOO)  # N: Revealed type is \"Literal[foo.bar.FromStub.FOO]?\"\nreveal_type(FromStub.FOO.value)  # N: Revealed type is \"builtins.int\"\nreveal_type(FromStub.FOO._value_)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(Wrapper.Nested.FOO)  # N: Revealed type is \"Literal[foo.bar.Wrapper.Nested.FOO]?\"\nreveal_type(Wrapper.Nested.FOO.value)  # N: Revealed type is \"builtins.int\"\nreveal_type(Wrapper.Nested.FOO._value_)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(InheritedInt.FOO)  # N: Revealed type is \"Literal[foo.bar.InheritedInt.FOO]?\"\nreveal_type(InheritedInt.FOO.value)  # N: Revealed type is \"builtins.int\"\nreveal_type(InheritedInt.FOO._value_)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(InheritedStr.FOO)  # N: Revealed type is \"Literal[foo.bar.InheritedStr.FOO]?\"\nreveal_type(InheritedStr.FOO.value)  # N: Revealed type is \"builtins.str\"\nreveal_type(InheritedStr.FOO._value_)  # N: Revealed type is \"builtins.str\"\n\nreveal_type(InheritedFlag.FOO)  # N: Revealed type is \"Literal[foo.bar.InheritedFlag.FOO]?\"\nreveal_type(InheritedFlag.FOO.value)  # N: Revealed type is \"builtins.int\"\nreveal_type(InheritedFlag.FOO._value_)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(InheritedIntFlag.FOO)  # N: Revealed type is \"Literal[foo.bar.InheritedIntFlag.FOO]?\"\nreveal_type(InheritedIntFlag.FOO.value)  # N: Revealed type is \"builtins.int\"\nreveal_type(InheritedIntFlag.FOO._value_)  # N: Revealed type is \"builtins.int\"\n\n[file foo/__init__.pyi]\n[file foo/bar/__init__.pyi]\nfrom enum import Enum, IntEnum, StrEnum, Flag, IntFlag\n\nclass Basic(Enum):\n    _value_: int\n    FOO = 1\n\nclass FromStub(Enum):\n    _value_: int\n    FOO = ...\n\nclass Wrapper:\n    class Nested(Enum):\n        _value_: int\n        FOO = ...\n\nclass InheritedInt(IntEnum):\n    FOO = ...\n\nclass InheritedStr(StrEnum):\n    FOO = ...\n\nclass InheritedFlag(Flag):\n    FOO = ...\n\nclass InheritedIntFlag(IntFlag):\n    FOO = ...\n[builtins fixtures/enum.pyi]\n\n[case testSunderValueTypeEllipsisNonStub]\nfrom enum import Enum, StrEnum\n\nclass Basic(Enum):\n    _value_: int\n    FOO = 1\n\nreveal_type(Basic.FOO)  # N: Revealed type is \"Literal[__main__.Basic.FOO]?\"\nreveal_type(Basic.FOO.value)  # N: Revealed type is \"Literal[1]?\"\nreveal_type(Basic.FOO._value_)  # N: Revealed type is \"builtins.int\"\n\n# TODO: this and below should produce diagnostics, Ellipsis is not assignable to int\n# Now we do not check members against _value_ at all.\n\nclass FromStub(Enum):\n    _value_: int\n    FOO = ...\n\nreveal_type(FromStub.FOO)  # N: Revealed type is \"Literal[__main__.FromStub.FOO]?\"\nreveal_type(FromStub.FOO.value)  # N: Revealed type is \"builtins.ellipsis\"\nreveal_type(FromStub.FOO._value_)  # N: Revealed type is \"builtins.int\"\n\nclass InheritedStr(StrEnum):\n    FOO = ...\n\nreveal_type(InheritedStr.FOO)  # N: Revealed type is \"Literal[__main__.InheritedStr.FOO]?\"\nreveal_type(InheritedStr.FOO.value)  # N: Revealed type is \"builtins.ellipsis\"\nreveal_type(InheritedStr.FOO._value_)  # N: Revealed type is \"builtins.ellipsis\"\n\nclass Wrapper:\n    class Nested(StrEnum):\n        FOO = ...\n\nreveal_type(Wrapper.Nested.FOO)  # N: Revealed type is \"Literal[__main__.Wrapper.Nested.FOO]?\"\nreveal_type(Wrapper.Nested.FOO.value)  # N: Revealed type is \"builtins.ellipsis\"\nreveal_type(Wrapper.Nested.FOO._value_)  # N: Revealed type is \"builtins.ellipsis\"\n[builtins fixtures/enum.pyi]\n\n[case testStrEnumEqualityReachability]\n# flags: --strict-equality --warn-unreachable\n\nfrom __future__ import annotations\nimport enum\n\n# https://github.com/python/mypy/issues/17162\n\nclass MyEnum(str, enum.Enum):\n    A = 'a'\n\nclass MyEnum2(enum.StrEnum):\n    A = 'a'\n\ndef f1():\n    if MyEnum.A == 'a':\n        1 + ''\n\n    if MyEnum2.A == 'a':\n        1 + ''\n[builtins fixtures/primitives.pyi]\n\n[case testStrEnumEqualityNarrowing]\n# flags: --strict-equality --warn-unreachable\n\nfrom __future__ import annotations\nimport enum\nfrom typing import Literal\n\n# https://github.com/python/mypy/issues/18029\n\nclass Foo(enum.StrEnum):\n    FOO = 'a'\n\ndef f1(a: Foo | Literal['foo']) -> Foo:\n    if a == 'foo':\n        # Ideally this is narrowed to just Literal['foo'] (if we learn to narrow based on enum value)\n        reveal_type(a)  # N: Revealed type is \"__main__.Foo | Literal['foo']\"\n        return Foo.FOO\n\n    # Ideally this passes\n    reveal_type(a)  # N: Revealed type is \"__main__.Foo | Literal['foo']\"\n    return a  # E: Incompatible return value type (got \"Foo | Literal['foo']\", expected \"Foo\")\n[builtins fixtures/primitives.pyi]\n\n[case testStrEnumEqualityAlias]\n# flags: --strict-equality --warn-unreachable\n# https://github.com/python/mypy/issues/16830\nfrom __future__ import annotations\nfrom enum import Enum, auto\n\n# https://github.com/python/mypy/issues/16830\n\nclass TrafficLight(Enum):\n    RED = auto()\n    AMBER = auto()\n    GREEN = auto()\n\n    YELLOW = AMBER  # alias\n\n# Behaviour here is not yet ideal, because we don't model enum aliases\n\ndef demo1(inst: TrafficLight) -> None:\n    if inst is TrafficLight.AMBER:\n        reveal_type(inst)  # N: Revealed type is \"Literal[__main__.TrafficLight.AMBER]\"\n    else:\n        reveal_type(inst)  # N: Revealed type is \"Literal[__main__.TrafficLight.RED] | Literal[__main__.TrafficLight.GREEN] | Literal[__main__.TrafficLight.YELLOW]\"\n\n    if inst == TrafficLight.AMBER:\n        reveal_type(inst)  # N: Revealed type is \"Literal[__main__.TrafficLight.AMBER]\"\n    else:\n        reveal_type(inst)  # N: Revealed type is \"Literal[__main__.TrafficLight.RED] | Literal[__main__.TrafficLight.GREEN] | Literal[__main__.TrafficLight.YELLOW]\"\n\ndef demo2() -> None:\n    if TrafficLight.AMBER is TrafficLight.YELLOW:  # E: Non-overlapping identity check (left operand type: \"Literal[TrafficLight.AMBER]\", right operand type: \"Literal[TrafficLight.YELLOW]\")\n        1 + ''  # E: Unsupported operand types for + (\"int\" and \"str\")\n    else:\n        1 + ''  # E: Unsupported operand types for + (\"int\" and \"str\")\n[builtins fixtures/primitives.pyi]\n\n\n[case testEnumEqualityNarrowing]\n# flags: --strict-equality --warn-unreachable\n\nfrom __future__ import annotations\nfrom typing import cast\nfrom enum import Enum, StrEnum\n\n# https://github.com/python/mypy/issues/16830\n\nclass E(Enum):\n    A = \"a\"\n    B = \"b\"\n    C = \"c\"\n\nclass Custom:\n    def __eq__(self, other: object) -> bool: return True\n\nclass SE(StrEnum):\n    A = \"a\"\n    B = \"b\"\n    C = \"c\"\n\ndef f1(x: int | str | E):\n    if x == E.A:\n        reveal_type(x)  # N: Revealed type is \"Literal[__main__.E.A]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | Literal[__main__.E.B] | Literal[__main__.E.C]\"\n\n    if x in cast(list[E], []):\n        reveal_type(x)  # N: Revealed type is \"__main__.E\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | __main__.E\"\n\n    if x == str():\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | __main__.E\"\n\ndef f2(x: int | Custom | E):\n    if x == E.A:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | Literal[__main__.E.A]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | __main__.Custom | Literal[__main__.E.B] | Literal[__main__.E.C]\"\n\n    if x in cast(list[E], []):\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | __main__.E\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | __main__.Custom | __main__.E\"\n\n    if x == str():\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | __main__.Custom | __main__.E\"\n\ndef f3_simple(x: str | SE):\n    if x == SE.A:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | __main__.SE\"\n\ndef f3(x: int | str | SE):\n    # Ideally we filter out some of these ints\n    if x == SE.A:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | __main__.SE\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | __main__.SE\"\n\n    if x in cast(list[SE], []):\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | __main__.SE\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | __main__.SE\"\n\n    if x == str():\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | __main__.SE\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | __main__.SE\"\n\ndef f4(x: int | Custom | SE):\n    if x == SE.A:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | Literal[__main__.SE.A]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | __main__.Custom | Literal[__main__.SE.B] | Literal[__main__.SE.C]\"\n\n    if x in cast(list[SE], []):\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | __main__.SE\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | __main__.Custom | __main__.SE\"\n\n    if x == str():\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | __main__.SE\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | __main__.Custom | __main__.SE\"\n\ndef f5(x: str | Custom | SE):\n    if x == SE.A:\n        reveal_type(x)  # N: Revealed type is \"Literal[__main__.SE.A] | __main__.Custom\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | __main__.Custom\"\n\n    if x in cast(list[SE], []):\n        reveal_type(x)  # N: Revealed type is \"__main__.SE | __main__.Custom\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | __main__.Custom | __main__.SE\"\n\n    if x == str():\n        reveal_type(x)  # N: Revealed type is \"builtins.str | __main__.Custom\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | __main__.Custom | __main__.SE\"\n\n[builtins fixtures/primitives.pyi]\n"
  },
  {
    "path": "test-data/unit/check-errorcodes.test",
    "content": "-- Tests for error codes and ignoring errors using error codes\n--\n-- These implicitly use --show-error-codes.\n\n[case testErrorCodeNoAttribute]\nimport m\nm.x  # E: Module has no attribute \"x\"  [attr-defined]\n'x'.foobar  # E: \"str\" has no attribute \"foobar\"  [attr-defined]\nfrom m import xx  # E: Module \"m\" has no attribute \"xx\"  [attr-defined]\nfrom m import think  # E: Module \"m\" has no attribute \"think\"; maybe \"thing\"?  [attr-defined]\nfor x in 1:  # E: \"int\" has no attribute \"__iter__\" (not iterable)  [attr-defined]\n    pass\n[file m.py]\nthing = 0\n[builtins fixtures/module.pyi]\n\n[case testErrorCodeUndefinedName]\nx # E: Name \"x\" is not defined  [name-defined]\ndef f() -> None:\n    y # E: Name \"y\" is not defined  [name-defined]\n[file m.py]\n[builtins fixtures/module.pyi]\n\n[case testErrorCodeUnclassifiedError]\nclass A:\n    def __init__(self) -> int: \\\n        # E: The return type of \"__init__\" must be None  [misc]\n        pass\n\n[case testErrorCodeNoteHasNoCode]\nreveal_type(1) # N: Revealed type is \"Literal[1]?\"\n\n[case testErrorCodeSyntaxError_no_native_parse]\n1 ''\n[out]\nmain:1: error: Invalid syntax  [syntax]\n[out version==3.10.0]\nmain:1: error: Invalid syntax. Perhaps you forgot a comma?  [syntax]\n\n[case testErrorCodeSyntaxError2_no_native_parse]\ndef f(): # E: Type signature has too many parameters  [syntax]\n    # type: (int) -> None\n    1\n\nx = 0  # type: x y  # E: Syntax error in type comment \"x y\"  [syntax]\n\n[case testErrorCodeSyntaxError3_no_native_parse]\n# This is a bit inconsistent -- syntax error would be more logical?\nx: 'a b'  # E: Invalid type comment or annotation  [valid-type]\nfor v in x:  # type: int, int  # E: Syntax error in type annotation  [syntax] \\\n    # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\n    pass\n\n[case testErrorCodeSyntaxErrorIgnoreNote]\n# This is a bit inconsistent -- syntax error would be more logical?\nx: 'a b'  # type: ignore[valid-type]\nfor v in x:  # type: int, int  # type: ignore[syntax]\n    pass\n\n[case testErrorCodeIgnore1]\n'x'.foobar  # type: ignore[attr-defined]\n'x'.foobar  # type: ignore[xyz]  # E: \"str\" has no attribute \"foobar\"  [attr-defined] \\\n    # N: Error code \"attr-defined\" not covered by \"type: ignore\" comment\n'x'.foobar  # type: ignore\n\n[case testErrorCodeIgnore2]\na = 'x'.foobar  # type: int  # type: ignore[attr-defined]\nb = 'x'.foobar  # type: int  # type: ignore[xyz]  # E: \"str\" has no attribute \"foobar\"  [attr-defined] \\\n    # N: Error code \"attr-defined\" not covered by \"type: ignore\" comment\nc = 'x'.foobar  # type: int  # type: ignore\n\n[case testErrorCodeIgnoreMultiple1]\na = 'x'.foobar(b)  # type: ignore[name-defined, attr-defined]\na = 'x'.foobar(b)  # type: ignore[name-defined, xyz]  # E: \"str\" has no attribute \"foobar\"  [attr-defined] \\\n    # N: Error code \"attr-defined\" not covered by \"type: ignore\" comment\na = 'x'.foobar(b)  # type: ignore[xyz, w, attr-defined]  # E: Name \"b\" is not defined  [name-defined] \\\n    # N: Error code \"name-defined\" not covered by \"type: ignore\" comment\n\n[case testErrorCodeIgnoreMultiple2]\na = 'x'.foobar(c) # type: int # type: ignore[name-defined, attr-defined]\nb = 'x'.foobar(c) # type: int # type: ignore[name-defined, xyz]  # E: \"str\" has no attribute \"foobar\"  [attr-defined] \\\n    # N: Error code \"attr-defined\" not covered by \"type: ignore\" comment\n\n[case testErrorCodeWarnUnusedIgnores1]\n# flags: --warn-unused-ignores\nx # type: ignore[name-defined, attr-defined] # E: Unused \"type: ignore[attr-defined]\" comment  [unused-ignore]\n\n[case testErrorCodeWarnUnusedIgnores2]\n# flags: --warn-unused-ignores\n\"x\".foobar(y) # type: ignore[name-defined, attr-defined]\n\n[case testErrorCodeWarnUnusedIgnores3]\n# flags: --warn-unused-ignores\n\"x\".foobar(y) # type: ignore[name-defined, attr-defined, xyz] # E: Unused \"type: ignore[xyz]\" comment  [unused-ignore]\n\n[case testErrorCodeWarnUnusedIgnores4]\n# flags: --warn-unused-ignores\n\"x\".foobar(y) # type: ignore[name-defined, attr-defined, valid-type] # E: Unused \"type: ignore[valid-type]\" comment  [unused-ignore]\n\n[case testErrorCodeWarnUnusedIgnores5]\n# flags: --warn-unused-ignores\n\"x\".foobar(y) # type: ignore[name-defined, attr-defined, valid-type, xyz] # E: Unused \"type: ignore[valid-type, xyz]\" comment  [unused-ignore]\n\n[case testErrorCodeWarnUnusedIgnores6_NoDetailWhenSingleErrorCode]\n# flags: --warn-unused-ignores\n\"x\" # type: ignore[name-defined] # E: Unused \"type: ignore\" comment  [unused-ignore]\n\n[case testErrorCodeWarnUnusedIgnores7_WarnWhenErrorCodeDisabled]\n# flags: --warn-unused-ignores --disable-error-code name-defined\nx              # type: ignore                              # E: Unused \"type: ignore\" comment  [unused-ignore]\nx              # type: ignore[name-defined]                # E: Unused \"type: ignore\" comment  [unused-ignore]\n\"x\".foobar(y)  # type: ignore[name-defined, attr-defined]  # E: Unused \"type: ignore[name-defined]\" comment  [unused-ignore]\n\n[case testErrorCodeWarnUnusedIgnores8_IgnoreUnusedIgnore]\n# flags: --warn-unused-ignores --disable-error-code name-defined\n\"x\"  # type: ignore[unused-ignore]\n\"x\"  # type: ignore[name-defined, unused-ignore]\n\"x\"  # type: ignore[xyz, unused-ignore]\nx    # type: ignore[name-defined, unused-ignore]\n\n[case testErrorCodeWarnUnusedIgnores9_SloppyFormattingNotEmptyBrackets]\n# flags: --warn-unused-ignores\n1 + \"ok\" + \"ok\".foo # type: ignore[  operator,attr-defined]\n1 + \"ok\" + \"ok\".foo # type: ignore[  ,operator,attr-defined]\n1 + \"ok\" + \"ok\".foo # type: ignore[  operator,attr-defined,]\n1 + \"ok\" + \"ok\".foo # type: ignore[  operator,attr-defined,,]\n\n[case testErrorCodeWarnUnusedIgnores10_SloppyFormattingEmptyBrackets]\n# flags: --warn-unused-ignores\n1+1 # type: ignore    # E: Unused \"type: ignore\" comment  [unused-ignore]\n1+1 # type: ignore[]  # E: Unused \"type: ignore\" comment  [unused-ignore]\n1+1 # type: ignore[ ] # E: Unused \"type: ignore\" comment  [unused-ignore]\n1+1 # type: ignore[,,, ] # E: Unused \"type: ignore\" comment  [unused-ignore]\n\n[case testErrorCodeMissingWhenRequired]\n# flags: --enable-error-code ignore-without-code\n\"x\" # type: ignore # E: \"type: ignore\" comment without error code  [ignore-without-code]\ny # type: ignore # E: \"type: ignore\" comment without error code (consider \"type: ignore[name-defined]\" instead)  [ignore-without-code]\nz # type: ignore[name-defined]\n\"a\" # type: ignore[ignore-without-code]\n\n[case testErrorCodeMissingDoesntTrampleUnusedIgnoresWarning]\n# flags: --enable-error-code ignore-without-code --warn-unused-ignores\n\"x\" # type: ignore # E: Unused \"type: ignore\" comment  [unused-ignore]\n\"y\" # type: ignore[ignore-without-code] # E: Unused \"type: ignore\" comment  [unused-ignore]\nz # type: ignore[ignore-without-code] # E: Unused \"type: ignore\" comment  [unused-ignore] \\\n                                      # E: Name \"z\" is not defined  [name-defined] \\\n                                      # N: Error code \"name-defined\" not covered by \"type: ignore\" comment\n\n[case testErrorCodeMissingWholeFileIgnores]\n# flags: --enable-error-code ignore-without-code\n# type: ignore  # whole file ignore\nx\ny # type: ignore  # ignore the lack of error code since we ignore the whole file\n\n[case testErrorCodeMissingMultiple]\n# flags: --enable-error-code ignore-without-code\nfrom __future__ import annotations\nclass A:\n    attr: int\n    def func(self, var: int) -> A | None: ...\n\na: A | None\n# 'union-attr' should only be listed once (instead of twice) and list should be sorted\na.func(\"invalid string\").attr  # type: ignore  # E: \"type: ignore\" comment without error code (consider \"type: ignore[arg-type, union-attr]\" instead)  [ignore-without-code]\n[builtins fixtures/tuple.pyi]\n\n[case testErrorCodeIgnoreWithExtraSpace]\nx  # type: ignore   [name-defined]\nx2 # type: ignore   [ name-defined ]\nx3 # type: ignore   [ xyz , name-defined ]\nx4 # type: ignore[xyz,name-defined]\ny  # type: ignore   [xyz]  # E: Name \"y\" is not defined  [name-defined] \\\n    # N: Error code \"name-defined\" not covered by \"type: ignore\" comment\ny  # type: ignore[  xyz  ]  # E: Name \"y\" is not defined  [name-defined] \\\n    # N: Error code \"name-defined\" not covered by \"type: ignore\" comment\ny  # type: ignore[ xyz , foo  ]  # E: Name \"y\" is not defined  [name-defined] \\\n    # N: Error code \"name-defined\" not covered by \"type: ignore\" comment\n\na = z  # type: int  # type: ignore  [name-defined]\nb = z2  # type: int  # type: ignore  [ name-defined ]\nc = z2  # type: int  # type: ignore  [ name-defined , xyz ]\nd = zz # type: int  # type: ignore  [xyz]  # E: Name \"zz\" is not defined  [name-defined] \\\n    # N: Error code \"name-defined\" not covered by \"type: ignore\" comment\ne = zz # type: int  # type: ignore  [ xyz ]  # E: Name \"zz\" is not defined  [name-defined] \\\n    # N: Error code \"name-defined\" not covered by \"type: ignore\" comment\nf = zz # type: int  # type: ignore  [ xyz,foo ]  # E: Name \"zz\" is not defined  [name-defined] \\\n    # N: Error code \"name-defined\" not covered by \"type: ignore\" comment\n\n[case testErrorCodeIgnoreAfterArgComment]\ndef f(x  # type: xyz  # type: ignore[name-defined]  # Comment\n      ):\n    # type () -> None\n    pass\n\ndef g(x  # type: xyz  # type: ignore  # Comment\n      ):\n    # type () -> None\n    pass\n\ndef h(x  # type: xyz  # type: ignore[foo]  # E: Name \"xyz\" is not defined  [name-defined] \\\n      # N: Error code \"name-defined\" not covered by \"type: ignore\" comment\n      ):\n    # type () -> None\n    pass\n\n[case testErrorCodeIgnoreWithNote]\nimport nostub  # type: ignore[import]\nfrom defusedxml import xyz  # type: ignore[import]\n\n[case testErrorCodeBadIgnore_no_native_parse]\nimport nostub # type: ignore xyz  # E: Invalid \"type: ignore\" comment  [syntax] \\\n                                  # E: Cannot find implementation or library stub for module named \"nostub\"  [import-not-found] \\\n                                  # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nimport nostub # type: ignore[  # E: Invalid \"type: ignore\" comment  [syntax]\nimport nostub # type: ignore[foo  # E: Invalid \"type: ignore\" comment  [syntax]\nimport nostub # type: ignore[foo,  # E: Invalid \"type: ignore\" comment  [syntax]\nimport nostub # type: ignore[foo]]  # E: Invalid \"type: ignore\" comment  [syntax]\nimport nostub # type: ignore[foo][bar]  # E: Invalid \"type: ignore\" comment  [syntax]\nimport nostub # type: ignore[foo] [bar]  # E: Invalid \"type: ignore\" comment  [syntax]\n\nx = 0  # type: ignore[  # E: Invalid \"type: ignore\" comment  [syntax]\n\ndef f(x,  # type: int  # type: ignore[  # E: Invalid \"type: ignore\" comment  [syntax]\n      ):\n    # type: (...) -> None\n    pass\n\n[case testErrorCodeBadIgnoreNoExtraComment_no_native_parse]\n# Omit the E: ... comments, as they affect parsing\nimport nostub # type: ignore xyz\nimport nostub # type: ignore[xyz\nimport nostub # type: ignore[xyz][xyz]\nx = 0  # type: ignore[\ndef f(x,  # type: int  # type: ignore[\n      ):\n    # type: (...) -> None\n    pass\n[out]\nmain:2: error: Invalid \"type: ignore\" comment  [syntax]\nmain:2: error: Cannot find implementation or library stub for module named \"nostub\"  [import-not-found]\nmain:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:3: error: Invalid \"type: ignore\" comment  [syntax]\nmain:4: error: Invalid \"type: ignore\" comment  [syntax]\nmain:5: error: Invalid \"type: ignore\" comment  [syntax]\nmain:6: error: Invalid \"type: ignore\" comment  [syntax]\n\n[case testErrorCodeArgKindAndCount]\ndef f(x: int) -> None: pass\nf()  # E: Missing positional argument \"x\" in call to \"f\"  [call-arg]\nf(1, 2)  # E: Too many arguments for \"f\"  [call-arg]\nf(y=1)  # E: Unexpected keyword argument \"y\" for \"f\"  [call-arg]\n\ndef g(*, x: int) -> None: pass\ng()  # E: Missing named argument \"x\" for \"g\"  [call-arg]\n\ndef h(x: int, y: int, z: int) -> None: pass\nh(y=1, z=1)  # E: Missing positional argument \"x\" in call to \"h\"  [call-arg]\nh(y=1)  # E: Missing positional arguments \"x\", \"z\" in call to \"h\"  [call-arg]\n\n[case testErrorCodeArgType]\ndef f(x: int) -> None: pass\nf('')  # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"  [arg-type]\n\nclass A:\n    def g(self, *, x: int) -> None: pass\n\nA().g(x='')  # E: Argument \"x\" to \"g\" of \"A\" has incompatible type \"str\"; expected \"int\"  [arg-type]\n\n[case testErrorCodeInvalidType]\ndef f(): pass\n\nx: f  # E: Function \"__main__.f\" is not valid as a type  [valid-type] \\\n      # N: Perhaps you need \"Callable[...]\" or a callback protocol?\n\nimport sys\ny: sys  # E: Module \"sys\" is not valid as a type  [valid-type] \\\n        # N: Perhaps you meant to use a protocol matching the module structure?\nz: y  # E: Variable \"__main__.y\" is not valid as a type  [valid-type] \\\n      # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n[builtins fixtures/tuple.pyi]\n\n[case testErrorCodeNeedTypeAnnotation]\nfrom typing import TypeVar\n\nT = TypeVar('T')\ndef f() -> T: pass # E: A function returning TypeVar should receive at least one argument containing the same TypeVar  [type-var]\nx = f()  # E: Need type annotation for \"x\"  [var-annotated]\ny = []  # E: Need type annotation for \"y\" (hint: \"y: list[<type>] = ...\")  [var-annotated]\n[builtins fixtures/list.pyi]\n\n[case testErrorCodeBadOverride]\nfrom typing import overload\n\nclass A:\n    def f(self) -> int:\n        return 0\nclass B(A):\n    def f(self) -> str:  # E: Return type \"str\" of \"f\" incompatible with return type \"int\" in supertype \"A\"  [override]\n        return ''\nclass C(A):\n    def f(self, x: int) -> int:  # E: Signature of \"f\" incompatible with supertype \"A\"  [override] \\\n                                 # N:      Superclass: \\\n                                 # N:          def f(self) -> int \\\n                                 # N:      Subclass: \\\n                                 # N:          def f(self, x: int) -> int\n        return 0\nclass D:\n    def f(self, x: int) -> int:\n        return 0\nclass E(D):\n    def f(self, x: str) -> int:  # E: Argument 1 of \"f\" is incompatible with supertype \"D\"; supertype defines the argument type as \"int\"  [override] \\\n                                 # N: This violates the Liskov substitution principle \\\n                                 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n        return 0\n\nclass O:\n    @overload\n    def f(self, x: int) -> None: pass\n    @overload\n    def f(self, x: str) -> None: pass\n    def f(self, x):\n        pass\n\nclass OO(O):\n    @overload  # E: Signature of \"f\" incompatible with supertype \"O\"  [override] \\\n               # N: Overload variants must be defined in the same order as they are in \"O\"\n    def f(self, x: str) -> None: pass\n    @overload\n    def f(self, x: int) -> None: pass\n    def f(self, x):\n        pass\n\n[case testErrorCodeReturnValue]\ndef f() -> int:\n    return ''  # E: Incompatible return value type (got \"str\", expected \"int\")  [return-value]\n\n[case testErrorCodeMissingReturnValueInReturnStatement]\ndef f() -> int:\n    return  # E: Return value expected  [return-value]\n\n[case testErrorCodeAssignment]\nx: str = 0  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")  [assignment]\n\ndef f(x: str = 0) -> None:  # E: Incompatible default for parameter \"x\" (default has type \"int\", parameter has type \"str\")  [assignment]\n    pass\n\nclass A:\n    x = 0\n\nclass B(A):\n    x = ''  # E: Incompatible types in assignment (expression has type \"str\", base class \"A\" defined the type as \"int\")  [assignment]\n\na: A\na.x = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")  [assignment]\n\n[case testErrorCodeMissingTypeArg]\n# flags: --disallow-any-generics\nfrom typing import List, TypeVar\nx: List  # E: Missing type arguments for generic type \"List\"  [type-arg]\ny: list  # E: Missing type arguments for generic type \"list\"  [type-arg]\nT = TypeVar('T')\nL = List[List[T]]\nz: L  # E: Missing type arguments for generic type \"L\"  [type-arg]\n[builtins fixtures/list.pyi]\n\n[case testErrorCodeUnionAttribute]\nfrom typing import Union\nclass A:\n    x: int\nclass B:\n    y: str\na: Union[A, B]\na.x  # E: Item \"B\" of \"A | B\" has no attribute \"x\"  [union-attr]\n\n[case testErrorCodeFunctionHasNoAnnotation]\n# flags: --disallow-untyped-defs\n\ndef f(x):  # E: Function is missing a type annotation  [no-untyped-def]\n    pass\n\ndef g(x: int):  # E: Function is missing a return type annotation  [no-untyped-def]\n    pass\n\ndef h(x) -> None:  # E: Function is missing a type annotation for one or more parameters  [no-untyped-def]\n    pass\n\ndef gen():  # E: Function is missing a return type annotation  [no-untyped-def]\n    yield 1\n\ndef gen2(x: int):  # E: Function is missing a return type annotation  [no-untyped-def]\n    yield 1\n\nasync def asyncf():  # E: Function is missing a return type annotation  [no-untyped-def]\n    return 0\n\nasync def asyncf2(x: int):  # E: Function is missing a return type annotation  [no-untyped-def]\n    return 0\n[typing fixtures/typing-async.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testErrorCodeCallUntypedFunction]\n# flags: --disallow-untyped-calls\n\ndef f() -> None:\n    g()  # E: Call to untyped function \"g\" in typed context  [no-untyped-call]\n\ndef g():\n    pass\n\n[case testErrorCodeUntypedDecorator]\n# flags: --disallow-untyped-decorators --warn-unused-ignores\ndef d(f): return f\n\n@d  # E: Untyped decorator makes function \"x\" untyped  [untyped-decorator]\ndef x() -> int: return 1\n@d  # type: ignore\ndef y() -> int: return 2\n@d  # type: ignore[untyped-decorator]\ndef best() -> int: return 3\n@d  # type: ignore[misc]  # E: Unused \"type: ignore\" comment  [unused-ignore] \\\n                          # E: Untyped decorator makes function \"z\" untyped  [untyped-decorator] \\\n                          # N: Error code \"untyped-decorator\" not covered by \"type: ignore\" comment\ndef z() -> int: return 4\n\n[case testErrorCodeIndexing]\nfrom typing import Dict\nx: Dict[int, int]\nx['']  # E: Invalid index type \"str\" for \"dict[int, int]\"; expected type \"int\"  [index]\n1['']  # E: Value of type \"int\" is not indexable  [index]\n1[''] = 1  # E: Unsupported target for indexed assignment (\"int\")  [index]\n[builtins fixtures/dict.pyi]\n\n[case testErrorCodeInvalidTypeArg]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T', int, str)\nTT = TypeVar('TT', int, None)\nS = TypeVar('S', bound=str)\n\ndef f(x: T) -> T:\n    return x\n\nf(object())  # E: Value of type variable \"T\" of \"f\" cannot be \"object\"  [type-var]\n\ndef g(x: S) -> S:\n    return x\n\ng(1)  # E: Value of type variable \"S\" of \"g\" cannot be \"int\"  [type-var]\n\nclass C(Generic[T]): pass\nclass D(Generic[S]): pass\nclass E(Generic[S, T]): pass\n\nx: C[object]  # E: Value of type variable \"T\" of \"C\" cannot be \"object\"  [type-var]\ny: D[int]  # E: Type argument \"int\" of \"D\" must be a subtype of \"str\"  [type-var]\nz: D[int, int]  # E: \"D\" expects 1 type argument, but 2 given  [type-arg]\n\ndef h(a: TT, s: S) -> None:\n    b: C[TT]  # E: Invalid type argument value for \"C\"  [type-var]\n    c: C[S]  # E: Type variable \"S\" not valid as type argument value for \"C\"  [type-var]\n\n[case testErrorCodeOperators]\nclass A: pass\nA() + 1  # E: Unsupported left operand type for + (\"A\")  [operator]\n1 in A()  # E: Unsupported right operand type for in (\"A\")  [operator]\nA() < 1  # E: Unsupported left operand type for < (\"A\")  [operator]\n-A()  # E: Unsupported operand type for unary - (\"A\")  [operator]\n+A()  # E: Unsupported operand type for unary + (\"A\")  [operator]\n~A()  # E: Unsupported operand type for ~ (\"A\")  [operator]\n\nclass B:\n    def __add__(self, other: int) -> 'B':\n        return self\n    def __radd__(self, other: int) -> 'B':\n        return self\n    def __contains__(self, other: int) -> int:\n        return 0\n\nB() + ''  # E: Unsupported operand types for + (\"B\" and \"str\")  [operator]\n'' + B()  # E: Unsupported operand types for + (\"str\" and \"B\")  [operator]\n'' in B()  # E: Unsupported operand types for in (\"str\" and \"B\")  [operator]\n\n1()  # E: \"int\" not callable  [operator]\n[builtins fixtures/tuple.pyi]\n\n[case testErrorCodeListOrDictItem]\nfrom typing import List, Dict\nx: List[int] = ['']  # E: List item 0 has incompatible type \"str\"; expected \"int\"  [list-item]\ny: Dict[int, int] = {1: ''}  # E: Dict entry 0 has incompatible type \"int\": \"str\"; expected \"int\": \"int\"  [dict-item]\n[builtins fixtures/dict.pyi]\n\n[case testErrorCodeTypedDict]\nfrom typing import TypedDict\nclass D(TypedDict):\n    x: int\nclass E(TypedDict):\n    x: int\n    y: int\n\na: D = {'x': ''}  # E: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")  [typeddict-item]\nb: D = {'y': ''}  # E: Missing key \"x\" for TypedDict \"D\"  [typeddict-item] \\\n                  # E: Extra key \"y\" for TypedDict \"D\"  [typeddict-unknown-key]\nc = D(x=0) if int() else E(x=0, y=0)\nc = {}  # E: Missing key \"x\" for TypedDict \"D\"  [typeddict-item]\nd: D = {'x': '', 'y': 1}  # E: Extra key \"y\" for TypedDict \"D\"  [typeddict-unknown-key] \\\n                          # E: Incompatible types (expression has type \"str\", TypedDict item \"x\" has type \"int\")  [typeddict-item]\n\n\na['y'] = 1  # E: TypedDict \"D\" has no key \"y\"  [typeddict-unknown-key]\na['x'] = 'x'  # E: Value of \"x\" has incompatible type \"str\"; expected \"int\"  [typeddict-item]\na['y']  # E: TypedDict \"D\" has no key \"y\"  [typeddict-item]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testErrorCodeTypedDictNoteIgnore]\nfrom typing import TypedDict\nclass A(TypedDict):\n    one_commonpart: int\n    two_commonparts: int\n\na: A = {'one_commonpart': 1, 'two_commonparts': 2}\na['other_commonpart'] = 3  # type: ignore[typeddict-unknown-key]\nnot_exist = a['not_exist'] # type: ignore[typeddict-item]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testErrorCodeTypedDictSubCodeIgnore]\nfrom typing import TypedDict\nclass D(TypedDict):\n    x: int\nd: D = {'x': 1, 'y': 2}  # type: ignore[typeddict-item]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testErrorCodeCannotDetermineType]\ny = x  # E: Cannot determine type of \"x\"  [has-type] \\\n       # E: Name \"x\" is used before definition  [used-before-def]\nreveal_type(y)  # N: Revealed type is \"Any\"\nx = None\n\n[case testErrorCodeRedundantCast]\n# flags: --warn-redundant-casts\nfrom typing import cast\n\nx = cast(int, int())  # E: Redundant cast to \"int\"  [redundant-cast]\n\n[case testErrorCodeInvalidCommentSignature]\ndef f(x):  # E: Type signature has too few parameters  [syntax]\n    # type: () -> None\n    pass\n\ndef g(x):  # E: Type signature has too many parameters  [syntax]\n    # type: (int, int) -> None\n    pass\n\n[case testErrorCodeNonOverlappingEquality]\n# flags: --strict-equality\nif int() == str():  # E: Non-overlapping equality check (left operand type: \"int\", right operand type: \"str\")  [comparison-overlap]\n    pass\nif int() != str():  # E: Non-overlapping equality check (left operand type: \"int\", right operand type: \"str\")  [comparison-overlap]\n    pass\nif int() is str():  # E: Non-overlapping identity check (left operand type: \"int\", right operand type: \"str\")  [comparison-overlap]\n    pass\n[builtins fixtures/primitives.pyi]\n\n[case testErrorCodeMissingModule]\nfrom defusedxml import xyz  # E: Library stubs not installed for \"defusedxml\"  [import-untyped] \\\n                            # N: Hint: \"python3 -m pip install types-defusedxml\" \\\n                            # N: (or run \"mypy --install-types\" to install all missing stub packages)\nfrom nonexistent import foobar  # E: Cannot find implementation or library stub for module named \"nonexistent\"  [import-not-found]\nimport nonexistent2  # E: Cannot find implementation or library stub for module named \"nonexistent2\"  [import-not-found]\nfrom nonexistent3 import *  # E: Cannot find implementation or library stub for module named \"nonexistent3\"  [import-not-found]\nfrom pkg import bad  # E: Module \"pkg\" has no attribute \"bad\"  [attr-defined]\nfrom pkg.bad2 import bad3  # E: Cannot find implementation or library stub for module named \"pkg.bad2\"  [import-not-found] \\\n                           # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[file pkg/__init__.py]\n\n[case testErrorCodeAlreadyDefined]\nx: int\nx: str  # E: Name \"x\" already defined on line 1  [no-redef]\n\ndef f():\n    pass\ndef f(): # E: Name \"f\" already defined on line 4  [no-redef]\n    pass\n\n[case testErrorCodeMissingReturn]\ndef f() -> int:  # E: Missing return statement  [return]\n    x = 0\n\n[case testErrorCodeReturnValueNotExpected]\ndef f() -> None:\n    return 1  # E: No return value expected  [return-value]\n\n[case testErrorCodeFunctionDoesNotReturnValue]\nfrom typing import Callable\n\ndef f() -> None: pass\n\nclass A:\n    def g(self) -> None: pass\n\nc: Callable[[], None]\n\ndef main() -> None:\n    x = f()  # E: \"f\" does not return a value (it only ever returns None)  [func-returns-value]\n    y = A().g()  # E: \"g\" of \"A\" does not return a value (it only ever returns None)  [func-returns-value]\n    z = c()  # E: Function does not return a value (it only ever returns None)  [func-returns-value]\n\n[case testErrorCodeInstantiateAbstract]\nfrom abc import abstractmethod\n\nclass A:\n    @abstractmethod\n    def f(self): pass\n\nclass B(A):\n    pass\n\nB()  # E: Cannot instantiate abstract class \"B\" with abstract attribute \"f\"  [abstract]\n\n[case testErrorCodeNewTypeNotSubclassable]\nfrom typing import Union, NewType\n\nX = NewType('X', Union[int, str])  # E: Argument 2 to NewType(...) must be subclassable (got \"int | str\")  [valid-newtype]\n\n[case testErrorCodeOverloadVariant]\nfrom typing import overload\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: str) -> str: ...\ndef f(x):\n    return x\n\nf(object())  # E: No overload variant of \"f\" matches argument type \"object\"  [call-overload] \\\n  # N: Possible overload variants: \\\n  # N:     def f(x: int) -> int \\\n  # N:     def f(x: str) -> str\n\nf()  # E: All overload variants of \"f\" require at least one argument  [call-overload] \\\n  # N: Possible overload variants: \\\n  # N:     def f(x: int) -> int \\\n  # N:     def f(x: str) -> str\n\nf(1, 1)  # E: No overload variant of \"f\" matches argument types \"int\", \"int\"  [call-overload] \\\n  # N: Possible overload variants: \\\n  # N:     def f(x: int) -> int \\\n  # N:     def f(x: str) -> str\n\n[case testErrorCodeOverloadVariantIgnore]\nfrom typing import overload\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: str) -> str: ...\ndef f(x):\n    return x\n\nf(object())  # type: ignore[call-overload]\n\n[case testErrorCodeAnyFromUnfollowedImport]\n# flags: --disallow-any-unimported\nfrom m import C  # type: ignore\ndef f(x: C) -> None:  # E: Argument 1 to \"f\" becomes \"Any\" due to an unfollowed import  [no-any-unimported]\n    pass\n\ndef g() -> C: ...  # E: Return type becomes \"Any\" due to an unfollowed import  [no-any-unimported]\n\n[case testErrorCodeReturnAny]\n# flags: --warn-return-any\ndef f(): pass\n\ndef g() -> int:\n    return f()  # E: Returning Any from function declared to return \"int\"  [no-any-return]\n\n[case testErrorCodeFormatCall]\n'{:d}'.format('no')  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\")  [str-format]\n'{!x}'.format('Hm...')  # E: Invalid conversion type \"x\", must be one of \"r\", \"s\" or \"a\"  [str-format]\n'}{'.format()  # E: Invalid conversion specifier in format string: unexpected }  [str-format]\n\n'%d' % 'no'  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float | SupportsInt\")  [str-format]\n'%d + %d' % (1, 2, 3)  # E: Not all arguments converted during string formatting  [str-format]\n\n'{}'.format(b'abc')  # E: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). Otherwise, decode the bytes  [str-bytes-safe]\n'%s' % b'abc'  # E: If x = b'abc' then \"%s\" % x produces \"b'abc'\", not \"abc\". If this is desired behavior use \"%r\" % x. Otherwise, decode the bytes  [str-bytes-safe]\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testErrorCodeIgnoreNamedDefinedNote]\nx: List[int]  # type: ignore[name-defined]\n\n[case testErrorCodeProtocolProblemsIgnore]\nfrom typing import Protocol\n\nclass P(Protocol):\n    def f(self, x: str) -> None: ...\n\nclass A:\n    def f(self, x: int) -> None: ...\n\ndef g(p: P) -> None: pass\n\np: A\ng(p)  # type: ignore[arg-type]\n[builtins fixtures/tuple.pyi]\n\n[case testErrorCodeNoneReturnNoteIgnore]\n# flags: --disallow-untyped-defs\n\ndef f():  # type: ignore[no-untyped-def]\n    pass\n\n[case testErrorCodeVarianceNoteIgnore]\nfrom typing import List\ndef f(x: List[object]) -> None: pass\na = [1]\nf(a)  # type: ignore[arg-type]\n[builtins fixtures/list.pyi]\n\n[case testErrorCodeAssignToMethod]\nclass A:\n    def f(self) -> None: pass\n\ndef g(self: A) -> None: pass\n\nA.f = g  # E: Cannot assign to a method  [method-assign]\n\n[case testErrorCodeDefinedHereNoteIgnore]\nimport m\nm.f(kw=1)  # type: ignore[call-arg]\n[file m.py]\ndef f() -> None: pass\n\n[case testErrorCodeUnionNoteIgnore]\nfrom typing import Union\n\nclass Foo:\n    def __add__(self, x: Foo) -> Foo: pass\n    def __radd__(self, x: Foo) -> Foo: pass\n\nclass Bar:\n    def __add__(self, x: Bar) -> Bar: pass\n    def __radd__(self, x: Bar) -> Bar: pass\n\na: Union[Foo, Bar]\n\na + a  # type: ignore[operator]\na + Foo()  # type: ignore[operator]\nFoo() + a  # type: ignore[operator]\n\n[case testErrorCodeTypeIgnoreMisspelled1]\nx = y  # type: ignored[foo]\nxx = y  # type: ignored [foo]\n[out]\nmain:1: error: Name \"ignored\" is not defined  [name-defined]\nmain:1: error: Name \"y\" is not defined  [name-defined]\nmain:2: error: Name \"ignored\" is not defined  [name-defined]\nmain:2: error: Name \"y\" is not defined  [name-defined]\n\n[case testErrorCodeTypeIgnoreMisspelled2_no_native_parse]\nx = y  # type: int  # type: ignored[foo]\nx = y  # type: int  # type: ignored [foo]\n[out]\nmain:1: error: Syntax error in type comment \"int\"  [syntax]\nmain:2: error: Syntax error in type comment \"int\"  [syntax]\n\n[case testErrorCode__exit__Return]\nclass InvalidReturn:\n    def __exit__(self, x, y, z) -> bool:  # E: \"bool\" is invalid as return type for \"__exit__\" that always returns False  [exit-return] \\\n# N: Use \"typing.Literal[False]\" as the return type or change it to \"None\" \\\n# N: If return type of \"__exit__\" implies that it may return True, the context manager may swallow exceptions\n        return False\n[builtins fixtures/bool.pyi]\n\n[case testErrorCodeOverloadedOperatorMethod]\nfrom typing import Optional, overload\n\nclass A:\n    @overload\n    def __add__(self, x: int) -> A: ...\n    @overload\n    def __add__(self, x: str) -> str: ...\n    def __add__(self, x): pass\n\nclass B:\n    pass\n\nx: Optional[B]\nA() + x  # type: ignore[operator]\n\nclass C:\n    @overload\n    def __rsub__(self, x: int) -> A: ...\n    @overload\n    def __rsub__(self, x: str) -> str: ...\n    def __rsub__(self, x): pass\n\nx - C()  # type: ignore[operator]\n\n[case testErrorCodeMultiLineBinaryOperatorOperand]\nfrom typing import Optional\n\nclass C: pass\n\ndef f() -> Optional[C]:\n    return None\n\nf(  # type: ignore[operator]\n) + C()\n\n[case testErrorCodeSpecialArgTypeErrors]\nfrom typing import TypedDict\n\nclass C(TypedDict):\n    x: int\n\nc: C\nc.setdefault('x', '1')  # type: ignore[typeddict-item]\n\nclass A:\n    pass\n\nclass B(A):\n    def f(self) -> None:\n        super(1, self).foo()  # type: ignore[arg-type]\n\ndef f(**x: int) -> None:\n    pass\n\nf(**1)  # type: ignore[arg-type]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testRedundantExpressions]\n# flags: --enable-error-code redundant-expr\ndef foo() -> bool: ...\n\nlst = [1, 2, 3, 4]\n\nb = False or foo()                       # E: Left operand of \"or\" is always false  [redundant-expr]\nc = True and foo()                       # E: Left operand of \"and\" is always true  [redundant-expr]\ng = 3 if True else 4                     # E: If condition is always true  [redundant-expr]\nh = 3 if False else 4                    # E: If condition is always false  [redundant-expr]\ni = [x for x in lst if True]             # E: If condition in comprehension is always true  [redundant-expr]\nj = [x for x in lst if False]            # E: If condition in comprehension is always false  [redundant-expr]\nk = [x for x in lst if isinstance(x, int) or foo()]  # E: If condition in comprehension is always true  [redundant-expr]\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRedundantExprTruthiness]\n# flags: --enable-error-code redundant-expr\nfrom typing import List\n\ndef maybe() -> bool: ...\n\nclass Foo:\n    def __init__(self, x: List[int]) -> None:\n        self.x = x or []\n\n    def method(self) -> int:\n        if not self.x or maybe():\n            return 1\n        return 2\n[builtins fixtures/list.pyi]\n\n[case testRedundantExpressionsUnionWithAny]\n# flags: --enable-error-code redundant-expr\nfrom typing import Any, Awaitable, Union\nok_list: list[Union[Any, Awaitable]]\nfor y in ok_list:\n    z = 1 if isinstance(y, Awaitable) else 2\n\nbad_list: list[Awaitable]\nfor y in bad_list:\n    z = 1 if isinstance(y, Awaitable) else 2  # E: If condition is always true  [redundant-expr]\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-full.pyi]\n\n\n[case testNamedTupleNameMismatch]\nfrom typing import NamedTuple\n\nFoo = NamedTuple(\"Bar\", [])  # E: First argument to namedtuple() should be \"Foo\", not \"Bar\"  [name-match]\n[builtins fixtures/tuple.pyi]\n\n[case testTypedDictNameMismatch]\nfrom typing import TypedDict\n\nFoo = TypedDict(\"Bar\", {})  # E: First argument \"Bar\" to TypedDict() does not match variable name \"Foo\"  [name-match]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testTruthyBool]\n# flags: --enable-error-code truthy-bool --no-local-partial-types\nfrom typing import List, Union, Any\n\nclass Foo:\n    pass\nclass Bar:\n    pass\n\nfoo = Foo()\nif foo:  # E: \"__main__.foo\" has type \"Foo\" which does not implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]\n    pass\n\nnot foo  # E: \"__main__.foo\" has type \"Foo\" which does not implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]\n\nzero = 0\nif zero:\n    pass\n\nnot zero\n\nfalse = False\nif false:\n    pass\n\nnot false\n\nnull = None\nif null:\n    pass\n\nnot null\n\ns = ''\nif s:\n    pass\n\nnot s\n\ngood_union: Union[str, int] = 5\nif good_union:\n    pass\nif not good_union:\n    pass\n\nnot good_union\n\nbad_union: Union[Foo, Bar] = Foo()\nif bad_union:  # E: \"__main__.bad_union\" has type \"Foo | Bar\" of which no members implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]\n    pass\nif not bad_union:  # E: \"__main__.bad_union\" has type \"Foo | Bar\" of which no members implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]\n    pass\n\nnot bad_union  # E: \"__main__.bad_union\" has type \"Foo | Bar\" of which no members implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]\n\n# 'object' is special and is treated as potentially falsy\nobj: object = Foo()\nif obj:\n    pass\nif not obj:\n    pass\n\nnot obj\n\nlst: List[int] = []\nif lst:\n    pass\n\nnot lst\n\na: Any\nif a:\n    pass\n\nnot a\n\nany_or_object: Union[object, Any]\nif any_or_object:\n    pass\n\nnot any_or_object\n\nif (my_foo := Foo()):  # E: \"__main__.my_foo\" has type \"Foo\" which does not implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]\n    pass\n\nif my_a := (a or Foo()):  # E: \"__main__.Foo\" returns \"Foo\" which does not implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]\n    pass\n[builtins fixtures/list.pyi]\n\n[case testTruthyFunctions]\ndef f():\n    pass\nif f:  # E: Function \"f\" could always be true in boolean context  [truthy-function]\n    pass\nif not f:  # E: Function \"f\" could always be true in boolean context  [truthy-function]\n    pass\nconditional_result = 'foo' if f else 'bar'  # E: Function \"f\" could always be true in boolean context  [truthy-function]\n\nnot f  # E: Function \"f\" could always be true in boolean context  [truthy-function]\n\n[case testTruthyIterable]\n# flags: --enable-error-code truthy-iterable\nfrom typing import Iterable\ndef func(var: Iterable[str]) -> None:\n    if var:  # E: \"var\" has type \"Iterable[str]\" which can always be true in boolean context. Consider using \"Collection[str]\" instead.  [truthy-iterable]\n        ...\n\n    not var  # E: \"var\" has type \"Iterable[str]\" which can always be true in boolean context. Consider using \"Collection[str]\" instead.  [truthy-iterable]\n\n[case testNoOverloadImplementation]\nfrom typing import overload\n\n@overload  # E: An overloaded function outside a stub file must have an implementation  [no-overload-impl]\ndef f(arg: int) -> int:\n    ...\n\n@overload\ndef f(arg: str) -> str:\n    ...\n\n[case testSliceInDictBuiltin_no_native_parse]\n# flags: --show-column-numbers\nb: dict[int, x:y]\nc: dict[x:y]\n\n[builtins fixtures/dict.pyi]\n[out]\nmain:2:14: error: Invalid type comment or annotation  [valid-type]\nmain:2:14: note: did you mean to use ',' instead of ':' ?\nmain:3:4: error: \"dict\" expects 2 type arguments, but 1 given  [type-arg]\nmain:3:9: error: Invalid type comment or annotation  [valid-type]\nmain:3:9: note: did you mean to use ',' instead of ':' ?\n\n[case testSliceInDictTyping_no_native_parse]\n# flags: --show-column-numbers\nfrom typing import Dict\nb: Dict[int, x:y]\nc: Dict[x:y]\n\n[builtins fixtures/dict.pyi]\n[out]\nmain:3:14: error: Invalid type comment or annotation  [valid-type]\nmain:3:14: note: did you mean to use ',' instead of ':' ?\nmain:4:4: error: \"dict\" expects 2 type arguments, but 1 given  [type-arg]\nmain:4:9: error: Invalid type comment or annotation  [valid-type]\nmain:4:9: note: did you mean to use ',' instead of ':' ?\n\n\n[case testSliceInCustomTensorType]\n# syntactically mimics torchtyping.TensorType\nclass TensorType: ...\nt: TensorType[\"batch\":..., float]  # type: ignore\nreveal_type(t)  # N: Revealed type is \"__main__.TensorType\"\n[builtins fixtures/tuple.pyi]\n\n[case testNoteAboutChangedTypedDictErrorCode]\nfrom typing import TypedDict\nclass D(TypedDict):\n    x: int\n\ndef f(d: D, s: str) -> None:\n    d[s]  # type: ignore[xyz] \\\n    # E: TypedDict key must be a string literal; expected one of (\"x\")  [literal-required] \\\n    # N: Error code \"literal-required\" not covered by \"type: ignore\" comment\n    d[s] # E: TypedDict key must be a string literal; expected one of (\"x\")  [literal-required]\n    d[s]  # type: ignore[misc]  \\\n    # E: TypedDict key must be a string literal; expected one of (\"x\")  [literal-required] \\\n    # N: Error code changed to literal-required; \"type: ignore\" comment may be out of date\n    d[s]  # type: ignore[literal-required]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testRecommendErrorCode]\n# type: ignore[whatever]  # E: Type ignore with error code is not supported for modules; use `# mypy: disable-error-code=\"whatever\"`  [syntax]\n1 + \"asdf\"\n\n[case testRecommendErrorCode2]\n# type: ignore[whatever, other]  # E: Type ignore with error code is not supported for modules; use `# mypy: disable-error-code=\"whatever, other\"`  [syntax]\n1 + \"asdf\"\n\n[case testShowErrorCodesInConfig]\n# flags: --config-file tmp/mypy.ini\n# Test 'show_error_codes = True' in config doesn't raise an exception\nvar: int = \"\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")  [assignment]\n\n[file mypy.ini]\n\\[mypy]\nshow_error_codes = True\n\n[case testErrorCodeUnsafeSuper_no_empty]\nfrom abc import abstractmethod\n\nclass Base:\n    @abstractmethod\n    def meth(self) -> int:\n        raise NotImplementedError()\nclass Sub(Base):\n    def meth(self) -> int:\n        return super().meth()  # E: Call to abstract method \"meth\" of \"Base\" with trivial body via super() is unsafe  [safe-super]\n[builtins fixtures/exception.pyi]\n\n[case testDedicatedErrorCodeForEmpty_no_empty]\nfrom typing import Optional\ndef foo() -> int: ...  # E: Missing return statement  [empty-body]\ndef bar() -> None: ...\n# This is inconsistent with how --warn-no-return behaves in general\n# but we want to minimize fallout of finally handling empty bodies.\ndef baz() -> Optional[int]: ...  # OK\n\n[case testDedicatedErrorCodeTypeAbstract]\nimport abc\nfrom typing import TypeVar, Type\n\nclass C(abc.ABC):\n    @abc.abstractmethod\n    def foo(self) -> None: ...\n\nT = TypeVar(\"T\")\ndef test(tp: Type[T]) -> T: ...\ntest(C)  # E: Only concrete class can be given where \"type[C]\" is expected  [type-abstract]\n\nclass D(C):\n    @abc.abstractmethod\n    def bar(self) -> None: ...\ncls: Type[C] = D  # E: Can only assign concrete classes to a variable of type \"type[C]\"  [type-abstract]\n\n[case testUncheckedAnnotationCodeShown]\ndef f():\n    x: int = \"no\"  # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs  [annotation-unchecked]\n\n[case testUncheckedAnnotationSuppressed]\n# flags: --disable-error-code=annotation-unchecked\ndef f():\n    x: int = \"no\"  # No warning here\n\n[case testMethodAssignmentSuppressed]\n# flags: --disable-error-code=method-assign\nclass A:\n    def f(self) -> None: pass\n    def g(self) -> None: pass\n\ndef h(self: A) -> None: pass\n\nA.f = h\n# This actually works at runtime, but there is no way to express this in current type system\nA.f = A().g  # E: Incompatible types in assignment (expression has type \"Callable[[], None]\", variable has type \"Callable[[A], None]\")  [assignment]\n\n[case testMethodAssignCoveredByAssignmentIgnore]\nclass A:\n    def f(self) -> None: pass\ndef h(self: A) -> None: pass\nA.f = h  # type: ignore[assignment]\n\n[case testMethodAssignCoveredByAssignmentFlag]\n# flags: --disable-error-code=assignment\nclass A:\n    def f(self) -> None: pass\ndef h(self: A) -> None: pass\nA.f = h  # OK\n\n[case testMethodAssignCoveredByAssignmentUnused]\n# flags: --warn-unused-ignores\nclass A:\n    def f(self) -> None: pass\ndef h(self: A) -> None: pass\nA.f = h  # type: ignore[assignment]  # E: Unused \"type: ignore\" comment, use narrower [method-assign] instead of [assignment] code  [unused-ignore]\n\n[case testUnusedIgnoreEnableCode]\n# flags: --enable-error-code=unused-ignore\nx = 1  # type: ignore  # E: Unused \"type: ignore\" comment  [unused-ignore]\n\n[case testErrorCodeUnsafeOverloadError]\nfrom typing import overload, Union\n\n@overload\ndef unsafe_func(x: int) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types  [overload-overlap]\n@overload\ndef unsafe_func(x: object) -> str: ...\ndef unsafe_func(x: object) -> Union[int, str]:\n    if isinstance(x, int):\n        return 42\n    else:\n        return \"some string\"\n[builtins fixtures/isinstancelist.pyi]\n\n\n###\n# unimported-reveal\n###\n\n[case testUnimportedRevealType]\n# flags: --enable-error-code=unimported-reveal\nx = 1\nreveal_type(x)\n[out]\nmain:3: error: Name \"reveal_type\" is not defined  [unimported-reveal]\nmain:3: note: Did you forget to import it from \"typing_extensions\"? (Suggestion: \"from typing_extensions import reveal_type\")\nmain:3: note: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnimportedRevealTypePy311]\n# flags: --enable-error-code=unimported-reveal --python-version=3.11\nx = 1\nreveal_type(x)\n[out]\nmain:3: error: Name \"reveal_type\" is not defined  [unimported-reveal]\nmain:3: note: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import reveal_type\")\nmain:3: note: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnimportedRevealTypeInUncheckedFunc]\n# flags: --enable-error-code=unimported-reveal\ndef unchecked():\n    x = 1\n    reveal_type(x)\n[out]\nmain:4: error: Name \"reveal_type\" is not defined  [unimported-reveal]\nmain:4: note: Did you forget to import it from \"typing_extensions\"? (Suggestion: \"from typing_extensions import reveal_type\")\nmain:4: note: Revealed type is \"Any\"\nmain:4: note: 'reveal_type' always outputs 'Any' in unchecked functions\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnimportedRevealTypeImportedTypingExtensions]\n# flags: --enable-error-code=unimported-reveal\nfrom typing_extensions import reveal_type\nx = 1\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnimportedRevealTypeImportedTyping311]\n# flags: --enable-error-code=unimported-reveal --python-version=3.11\nfrom typing import reveal_type\nx = 1\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testUnimportedRevealLocals]\n# flags: --enable-error-code=unimported-reveal\nx = 1\nreveal_locals()\n[out]\nmain:3: note: Revealed local types are:\nmain:3: note:     x: builtins.int\nmain:3: error: Name \"reveal_locals\" is not defined  [unimported-reveal]\n[builtins fixtures/isinstancelist.pyi]\n\n[case testCovariantMutableOverride]\n# flags: --enable-error-code=mutable-override\nfrom typing import Any\n\nclass C:\n    x: float\n    y: float\n    z: float\n    w: Any\n    @property\n    def foo(self) -> float: ...\n    @property\n    def bar(self) -> float: ...\n    @bar.setter\n    def bar(self, val: float) -> None: ...\n    baz: float\n    bad1: float\n    bad2: float\nclass D(C):\n    x: int  # E: Covariant override of a mutable attribute (base class \"C\" defined the type as \"float\", expression has type \"int\")  [mutable-override]\n    y: float\n    z: Any\n    w: float\n    foo: int\n    bar: int  # E: Covariant override of a mutable attribute (base class \"C\" defined the type as \"float\", expression has type \"int\")  [mutable-override]\n    def one(self) -> None:\n        self.baz = 5\n    bad1 = 5  # E: Covariant override of a mutable attribute (base class \"C\" defined the type as \"float\", expression has type \"int\")  [mutable-override]\n    def other(self) -> None:\n        self.bad2: int = 5  # E: Covariant override of a mutable attribute (base class \"C\" defined the type as \"float\", expression has type \"int\")  [mutable-override]\n[builtins fixtures/property.pyi]\n\n[case testNarrowedTypeNotSubtype]\nfrom typing_extensions import TypeIs\n\ndef f(x: str) -> TypeIs[int]:  # E: Narrowed type \"int\" is not a subtype of input type \"str\"  [narrowed-type-not-subtype]\n    pass\n\n[builtins fixtures/tuple.pyi]\n\n[case testDynamicMetaclass]\nclass A(metaclass=type(tuple)): pass  # E: Dynamic metaclass not supported for \"A\"  [metaclass]\n[builtins fixtures/tuple.pyi]\n\n[case testMetaclassOfTypeAny]\n# mypy: disallow-subclassing-any=True\nfrom typing import Any\nfoo: Any = ...\nclass A(metaclass=foo): pass  # E: Class cannot use \"foo\" as a metaclass (has type \"Any\")  [metaclass]\n\n[case testMetaclassOfWrongType]\nclass Foo:\n    bar = 1\nclass A2(metaclass=Foo.bar): pass  # E: Invalid metaclass \"Foo.bar\"  [metaclass]\n\n[case testMetaclassNotTypeSubclass]\nclass M: pass\nclass A(metaclass=M): pass  # E: Metaclasses not inheriting from \"type\" are not supported  [metaclass]\n\n[case testMultipleMetaclasses]\nimport six\nclass M1(type): pass\n\n@six.add_metaclass(M1)\nclass A1(metaclass=M1): pass  # E: Multiple metaclass definitions  [metaclass]\n\nclass A2(six.with_metaclass(M1), metaclass=M1): pass  # E: Multiple metaclass definitions  [metaclass]\n\n@six.add_metaclass(M1)\nclass A3(six.with_metaclass(M1)): pass  # E: Multiple metaclass definitions  [metaclass]\n[builtins fixtures/tuple.pyi]\n\n[case testInvalidMetaclassStructure]\nclass X(type): pass\nclass Y(type): pass\nclass A(metaclass=X): pass\nclass B(A, metaclass=Y): pass  # E: Metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases  [metaclass] \\\n                               # N: \"__main__.Y\" (metaclass of \"__main__.B\") conflicts with \"__main__.X\" (metaclass of \"__main__.A\")\n\n\n\n\n[case testOverloadedFunctionSignature]\nfrom typing import overload, Union\n\n@overload\ndef process(response1: float,response2: float) -> float:\n    ...\n@overload\ndef process(response1: int,response2: int) -> int: # E: Overloaded function signature 2 will never be matched: signature 1's parameter type(s) are the same or broader  [overload-cannot-match]\n    ...\n\ndef process(response1,response2)-> Union[float,int]:\n   return response1 + response2\n"
  },
  {
    "path": "test-data/unit/check-expressions.test",
    "content": "-- Test cases for simple expressions.\n--\n-- See also:\n--  * check-functions.test contains test cases for calls.\n--  * check-varargs.test contains test cases for *args.\n--  * check-dynamic.test contains test cases related to 'Any' type.\n--  * check-generics.test contains test cases for generic values.\n\n\n-- None expression\n-- ---------------\n\n\n[case testNoneAsRvalue]\nimport typing\na: A\nclass A: pass\n[out]\n\n[case testNoneAsArgument]\n# flags: --no-strict-optional\nimport typing\ndef f(x: 'A', y: 'B') -> None: pass\nf(None, None)\nclass A: pass\nclass B(A): pass\n[out]\n\n\n-- Simple expressions\n-- ------------------\n\n\n[case testIntLiteral]\na = 0\nb: A\nif int():\n    b = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"A\")\nif int():\n    a = 1\nclass A:\n    pass\n\n[case testStrLiteral]\na = ''\nb: A\nif int():\n    b = 'x' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"A\")\nif int():\n    a = 'x'\nif int():\n    a = r\"x\"\nif int():\n    a = \"\"\"foo\"\"\"\nclass A:\n    pass\n\n[case testFloatLiteral]\na = 0.0\nb: A\nif str():\n    b = 1.1 # E: Incompatible types in assignment (expression has type \"float\", variable has type \"A\")\nif str():\n    a = 1.1\nclass A:\n    pass\n[builtins fixtures/dict.pyi]\n\n[case testComplexLiteral]\na = 0.0j\nb: A\nif str():\n    b = 1.1j # E: Incompatible types in assignment (expression has type \"complex\", variable has type \"A\")\nif str():\n    a = 1.1j\nclass A:\n    pass\n[builtins fixtures/dict.pyi]\n\n[case testBytesLiteral]\nb: bytes\na: A\nif str():\n    b = b'foo'\nif str():\n    b = br\"foo\"\nif str():\n    b = b'''foo'''\nif str():\n    a = b'foo' # E: Incompatible types in assignment (expression has type \"bytes\", variable has type \"A\")\nclass A: pass\n[builtins fixtures/dict.pyi]\n\n[case testUnicodeLiteralInPython3]\ns: str\nif int():\n    s = u'foo'\nb: bytes\nif int():\n    b = u'foo' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"bytes\")\n[builtins fixtures/primitives.pyi]\n\n\n-- Binary operators\n-- ----------------\n\n\n[case testAdd]\na: A\nb: B\nc: C\nif int():\n    c = a + c  # E: Unsupported operand types for + (\"A\" and \"C\")\nif int():\n    a = a + b  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A\")\nif int():\n    c = b + a  # E: Unsupported left operand type for + (\"B\")\nif int():\n    c = a + b\n\nclass A:\n    def __add__(self, x: 'B') -> 'C':\n        pass\nclass B:\n    pass\nclass C:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testSub]\na: A\nb: B\nc: C\nif int():\n    c = a - c  # E: Unsupported operand types for - (\"A\" and \"C\")\nif int():\n    a = a - b  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A\")\nif int():\n    c = b - a  # E: Unsupported left operand type for - (\"B\")\nif int():\n    c = a - b\n\nclass A:\n    def __sub__(self, x: 'B') -> 'C':\n        pass\nclass B:\n    pass\nclass C:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testMul]\na: A\nb: B\nc: C\nif int():\n    c = a * c  # E: Unsupported operand types for * (\"A\" and \"C\")\nif int():\n    a = a * b  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A\")\nif int():\n    c = b * a  # E: Unsupported left operand type for * (\"B\")\nif int():\n    c = a * b\n\nclass A:\n    def __mul__(self, x: 'B') -> 'C':\n        pass\nclass B:\n    pass\nclass C:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testMatMul]\na: A\nb: B\nc: C\nif int():\n    c = a @ c  # E: Unsupported operand types for @ (\"A\" and \"C\")\nif int():\n    a = a @ b  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A\")\nif int():\n    c = b @ a  # E: Unsupported left operand type for @ (\"B\")\nif int():\n    c = a @ b\n\nclass A:\n    def __matmul__(self, x: 'B') -> 'C':\n        pass\nclass B:\n    pass\nclass C:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testDiv]\na: A\nb: B\nc: C\nif int():\n    c = a / c  # E: Unsupported operand types for / (\"A\" and \"C\")\n    a = a / b  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A\")\nif int():\n    c = b / a  # E: Unsupported left operand type for / (\"B\")\nif int():\n    c = a / b\n\nclass A:\n    def __truediv__(self, x: 'B') -> 'C':\n        pass\nclass B:\n    pass\nclass C:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testIntDiv]\na: A\nb: B\nc: C\nif int():\n    c = a // c  # E: Unsupported operand types for // (\"A\" and \"C\")\n    a = a // b  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A\")\nif int():\n    c = b // a  # E: Unsupported left operand type for // (\"B\")\nif int():\n    c = a // b\n\nclass A:\n    def __floordiv__(self, x: 'B') -> 'C':\n        pass\nclass B:\n    pass\nclass C:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testMod]\na: A\nb: B\nc: C\nif int():\n    c = a % c  # E: Unsupported operand types for % (\"A\" and \"C\")\nif int():\n    a = a % b  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A\")\nif int():\n    c = b % a  # E: Unsupported left operand type for % (\"B\")\nif int():\n    c = a % b\n\nclass A:\n    def __mod__(self, x: 'B') -> 'C':\n        pass\nclass B:\n    pass\nclass C:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testPow]\na: A\nb: B\nc: C\nif int():\n    c = a ** c  # E: Unsupported operand types for ** (\"A\" and \"C\")\nif int():\n    a = a ** b  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A\")\nif int():\n    c = b ** a  # E: Unsupported left operand type for ** (\"B\")\nif int():\n    c = a ** b\n\nclass A:\n    def __pow__(self, x: 'B') -> 'C':\n        pass\nclass B:\n    pass\nclass C:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testMiscBinaryOperators]\na: A\nb: B\nb = a & a  # Fail\nb = a | b  # Fail\nb = a ^ a  # Fail\nb = a << b # Fail\nb = a >> a # Fail\n\nb = a & b\nb = a | a\nb = a ^ b\nb = a << a\nb = a >> b\nclass A:\n  def __and__(self, x: 'B') -> 'B': pass\n  def __or__(self, x: 'A') -> 'B': pass\n  def __xor__(self, x: 'B') -> 'B': pass\n  def __lshift__(self, x: 'A') -> 'B': pass\n  def __rshift__(self, x: 'B') -> 'B': pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:3: error: Unsupported operand types for & (\"A\" and \"A\")\nmain:4: error: Unsupported operand types for | (\"A\" and \"B\")\nmain:5: error: Unsupported operand types for ^ (\"A\" and \"A\")\nmain:6: error: Unsupported operand types for << (\"A\" and \"B\")\nmain:7: error: Unsupported operand types for >> (\"A\" and \"A\")\n\n[case testBooleanAndOr]\na: A\nb: bool\nif int():\n    b = b and b\nif int():\n    b = b or b\nif int():\n    b = b and a # E: Incompatible types in assignment (expression has type \"Literal[False] | A\", variable has type \"bool\")\nif int():\n    b = a and b # E: Incompatible types in assignment (expression has type \"A | bool\", variable has type \"bool\")\nif int():\n    b = b or a  # E: Incompatible types in assignment (expression has type \"Literal[True] | A\", variable has type \"bool\")\nif int():\n    b = a or b  # E: Incompatible types in assignment (expression has type \"A | bool\", variable has type \"bool\")\nclass A: pass\n\n[builtins fixtures/bool.pyi]\n\n[case testRestrictedTypeAnd]\n\nb: bool\ni: str\nj = not b and i\nif j:\n    reveal_type(j) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/bool.pyi]\n\n[case testRestrictedTypeOr]\n\nb: bool\ni: str\nj = b or i\nif not j:\n    reveal_type(j) # N: Revealed type is \"Literal['']\"\n[builtins fixtures/bool.pyi]\n\n[case testAndOr]\n\ns = \"\"\nb = bool()\nreveal_type(s and b or b)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/bool.pyi]\n\n[case testRestrictedBoolAndOrWithGenerics]\nfrom typing import List\n\ndef f(a: List[str], b: bool) -> bool:\n    x = a and b\n    y: bool\n    return reveal_type(x or y)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/list.pyi]\n\n[case testNonBooleanOr]\nc: C\nd: D\nb: bool\nif int():\n    c = c or c\nif int():\n    c = c or d\nif int():\n    c = d or c\nif int():\n    b = c or c # E: Incompatible types in assignment (expression has type \"C\", variable has type \"bool\")\nif int():\n    d = c or d # E: Incompatible types in assignment (expression has type \"C\", variable has type \"D\")\nif int():\n    d = d or c # E: Incompatible types in assignment (expression has type \"C\", variable has type \"D\")\nclass C: pass\nclass D(C): pass\n[builtins fixtures/bool.pyi]\n\n[case testInOperator]\nfrom typing import Iterator, Iterable, Any\na: A\nb: B\nc: bool\nd: D\ne: Any\nif int():\n    c = c in a  # E: Unsupported operand types for in (\"bool\" and \"A\")\nif int():\n    a = b in a  # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    c = a in b  # E: Unsupported right operand type for in (\"B\")\nif int():\n    c = b in d  # E: Unsupported operand types for in (\"B\" and \"D\")\nif int():\n    c = b in a\nif int():\n    c = a in d\nif int():\n    c = e in d\nif int():\n    c = a in e\n\nclass A:\n    def __contains__(self, x: 'B') -> bool: pass\nclass B: pass\nclass D(Iterable[A]):\n    def __iter__(self) -> Iterator[A]: pass\n[builtins fixtures/bool.pyi]\n\n[case testNotInOperator]\nfrom typing import Iterator, Iterable, Any\na: A\nb: B\nc: bool\nd: D\ne: Any\nif int():\n    c = c not in a  # E: Unsupported operand types for in (\"bool\" and \"A\")\nif int():\n    a = b not in a  # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    c = a not in b  # E: Unsupported right operand type for in (\"B\")\nif int():\n    c = b not in d  # E: Unsupported operand types for in (\"B\" and \"D\")\nif int():\n    c = b not in a\nif int():\n    c = a not in d\nif int():\n    c = e in d\nif int():\n    c = a in e\n\nclass A:\n    def __contains__(self, x: 'B') -> bool: pass\nclass B: pass\nclass D(Iterable[A]):\n    def __iter__(self) -> Iterator[A]: pass\n[builtins fixtures/bool.pyi]\n\n[case testNonBooleanContainsReturnValue]\na: A\nb: bool\nc: str\nif int():\n    b = a not in a\nif int():\n    b = a in a\nif int():\n    c = a not in a  # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"str\")\nif int():\n    c = a in a  # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"str\")\n\nclass A:\n  def __contains__(self, x: 'A') -> str: pass\n[builtins fixtures/bool.pyi]\n\n[case testInWithInvalidArgs]\na = 1 in ([1] + ['x'])  # E: List item 0 has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testEq]\na: A\nb: bool\nif int():\n    a = a == b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    a = a != b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    b = a == b\nif int():\n    b = a != b\n\nclass A:\n  def __eq__(self, o: object) -> bool: pass\n  def __ne__(self, o: object) -> bool: pass\n[builtins fixtures/bool.pyi]\n\n[case testLtAndGt]\na: A\nb: B\nbo: bool\nif int():\n    a = a < b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    a = a > b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    bo = a < b\nif int():\n    bo = a > b\n\nclass A:\n    def __lt__(self, o: 'B') -> bool: pass\n    def __gt__(self, o: 'B') -> bool: pass\nclass B:\n    def __lt__(self, o: 'B') -> bool: pass\n    def __gt__(self, o: 'B') -> bool: pass\n[builtins fixtures/bool.pyi]\n\n[case cmpIgnoredPy3]\na: A\nb: B\nbo: bool\nbo = a <= b # E: Unsupported left operand type for <= (\"A\")\n\nclass A:\n    def __cmp__(self, o: 'B') -> bool: pass\nclass B:\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testLeAndGe]\na: A\nb: B\nbo: bool\nif int():\n    a = a <= b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    a = a >= b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    bo = a <= b\nif int():\n    bo = a >= b\n\nclass A:\n    def __le__(self, o: 'B') -> bool: pass\n    def __ge__(self, o: 'B') -> bool: pass\nclass B:\n    def __le__(self, o: 'B') -> bool: pass\n    def __ge__(self, o: 'B') -> bool: pass\n[builtins fixtures/bool.pyi]\n\n[case testChainedComp]\na: A\nb: B\nbo: bool\na < a < b < b # Fail\na < b < b < b\na < a > a < b # Fail\n\nclass A:\n    def __lt__(self, o: 'B') -> bool: pass\n    def __gt__(self, o: 'B') -> bool: pass\nclass B:\n    def __lt__(self, o: 'B') -> bool: pass\n    def __gt__(self, o: 'B') -> bool: pass\n[builtins fixtures/bool.pyi]\n[out]\nmain:4: error: Unsupported operand types for < (\"A\" and \"A\")\nmain:6: error: Unsupported operand types for < (\"A\" and \"A\")\nmain:6: error: Unsupported operand types for > (\"A\" and \"A\")\n\n\n[case testChainedCompBoolRes]\na: A\nb: B\nbo: bool\nif int():\n    bo = a < b < b\nif int():\n    a = a < b < b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\n\nclass A:\n    def __lt__(self, o: 'B') -> bool: pass\n    def __gt__(self, o: 'B') -> bool: pass\nclass B:\n    def __lt__(self, o: 'B') -> bool: pass\n    def __gt__(self, o: 'B') -> bool: pass\n[builtins fixtures/bool.pyi]\n\n\n[case testChainedCompResTyp]\nx: X\ny: Y\na: A\nb: B\np: P\nbo: bool\nif int():\n    b = y == y == y\nif int():\n    bo = y == y == y # E: Incompatible types in assignment (expression has type \"B\", variable has type \"bool\")\nif int():\n    a = x < y\nif int():\n    a = x < y == y # E: Incompatible types in assignment (expression has type \"P\", variable has type \"A\")\nif int():\n    p = x < y == y\n\nclass P:\n    pass\nclass A(P):\n    pass\nclass B(P):\n    pass\n\nclass X:\n    def __lt__(self, o: 'Y') -> A: pass\n    def __gt__(self, o: 'Y') -> A: pass\nclass Y:\n    def __lt__(self, o: 'Y') -> A: pass\n    def __gt__(self, o: 'Y') -> A: pass\n    def __eq__(self, o: 'Y') -> B: pass  # type: ignore\n[builtins fixtures/bool.pyi]\n\n\n[case testIs]\na: A\nb: bool\nif int():\n    a = a is b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    b = a is b\nif int():\n    b = b is a\nif int():\n    b = a is None\nclass A: pass\n[builtins fixtures/bool.pyi]\n\n[case testIsNot]\na: A\nb: bool\nif int():\n    a = a is not b # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    b = a is not b\nif int():\n    b = b is not a\nif int():\n    b = a is not None\nclass A: pass\n[builtins fixtures/bool.pyi]\n\n[case testIsRightOperand]\n\n1 is 1()\n[builtins fixtures/bool.pyi]\n[out]\nmain:2: error: \"int\" not callable\n\n[case testReverseBinaryOperator]\n\nclass A:\n    def __add__(self, x: int) -> int: pass\nclass B:\n    def __radd__(self, x: A) -> str: pass\ns: str\nn: int\nif int():\n    n = A() + 1\nif int():\n    s = A() + B()\nif int():\n    n = A() + B() # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testReverseBinaryOperator2]\nclass A:\n    def __add__(self, x: 'A') -> object: pass\nclass B:\n    def __radd__(self, x: A) -> str: pass\ns: str\nn: int\nif int():\n    s = A() + B()\n    n = A() + B() # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testReverseBinaryOperator3]\n\nclass N:\n    def __add__(self, x: 'N') -> object: pass\nclass A:\n    def __add__(self, x: N) -> int: pass\nclass B:\n    def __radd__(self, x: N) -> str: pass\ns: str\ns = A() + B() # E: Unsupported operand types for + (\"A\" and \"B\")\n\n\n[case testReverseBinaryOperator4]\nfrom typing import assert_type, Never\n\nclass Size(tuple[int, ...]):\n    def __add__(self, other: tuple[int, ...], /) -> \"Size\": return Size()  # type: ignore[override]\n    def __radd__(self, other: tuple[int, ...], /) -> \"Size\": return Size()\n\nsize: Size = Size([3, 4])\ntup0: tuple[()] = ()\ntup1: tuple[int] = (1,)\ntup2: tuple[int, int] = (1, 2)\ntupN: tuple[int, ...] = (1, 2, 3)\ntupX: tuple[Never, ...] = ()\n\nassert_type(tup0 + size, Size)\nassert_type(tup1 + size, Size)\nassert_type(tup2 + size, Size)\nassert_type(tupN + size, Size)\nassert_type(tupX + size, Size)\n\n[builtins fixtures/tuple-typeshed.pyi]\n\n[case testBinaryOperatorWithAnyRightOperand]\nfrom typing import Any, cast\nclass A: pass\nA() + cast(Any, 1)\n\n[case testReverseComparisonOperator]\nclass C:\n    def __gt__(self, x: 'A') -> object: pass\nclass A:\n    def __lt__(self, x: C) -> int: pass  # E: Signatures of \"__lt__\" of \"A\" and \"__gt__\" of \"C\" are unsafely overlapping\nclass B:\n    def __gt__(self, x: A) -> str: pass\ns: str\nn: int\nif int():\n    n = A() < C()\n    s = A() < B()\nif int():\n    n = A() < B() # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    s = object() < B() # E: Unsupported operand types for > (\"B\" and \"object\")\n\n[case testReversibleComparisonWithExtraArgument]\nclass C:\n    def __lt__(self, o: object, x: str = \"\") -> int: ...\n\n[case testErrorContextAndBinaryOperators]\nimport typing\nclass A:\n    def __getitem__(self, i: str) -> int: pass\ndef f() -> None:\n    A()[1] # Error\nclass B:\n    A()[1] # Error\nA()[1] # Error\n[out]\nmain:5: error: Invalid index type \"int\" for \"A\"; expected type \"str\"\nmain:7: error: Invalid index type \"int\" for \"A\"; expected type \"str\"\nmain:8: error: Invalid index type \"int\" for \"A\"; expected type \"str\"\n\n[case testErrorContextAndBinaryOperators2]\nimport m\n[file m.py]\nimport typing\nclass A:\n    def __getitem__(self, i: str) -> int: pass\ndef f() -> None:\n    A()[1] # Error\nclass B:\n    A()[1] # Error\nA()[1] # Error\n[out]\ntmp/m.py:5: error: Invalid index type \"int\" for \"A\"; expected type \"str\"\ntmp/m.py:7: error: Invalid index type \"int\" for \"A\"; expected type \"str\"\ntmp/m.py:8: error: Invalid index type \"int\" for \"A\"; expected type \"str\"\n\n\n[case testDivmod]\n# flags: --disable-error-code=used-before-def\nfrom typing import Tuple, Union, SupportsInt\n_Decimal = Union[Decimal, int]\nclass Decimal(SupportsInt):\n    def __init__(self, int) -> None: ...\n    def __divmod__(self, other: _Decimal) -> Tuple[Decimal, Decimal]: ...\n    def __rdivmod__(self, other: _Decimal) -> Tuple[Decimal, Decimal]: ...\n\ni = 8\nf = 8.0\nd = Decimal(8)\n\nreveal_type(divmod(i, i))  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\nreveal_type(divmod(f, i))  # N: Revealed type is \"tuple[builtins.float, builtins.float]\"\nreveal_type(divmod(d, i))  # N: Revealed type is \"tuple[__main__.Decimal, __main__.Decimal]\"\n\nreveal_type(divmod(i, f))  # N: Revealed type is \"tuple[builtins.float, builtins.float]\"\nreveal_type(divmod(f, f))  # N: Revealed type is \"tuple[builtins.float, builtins.float]\"\ndivmod(d, f)  # E: Unsupported operand types for divmod (\"Decimal\" and \"float\")\n\nreveal_type(divmod(i, d))  # N: Revealed type is \"tuple[__main__.Decimal, __main__.Decimal]\"\ndivmod(f, d)  # E: Unsupported operand types for divmod (\"float\" and \"Decimal\")\nreveal_type(divmod(d, d))  # N: Revealed type is \"tuple[__main__.Decimal, __main__.Decimal]\"\n\n# Now some bad calls\ndivmod()  # E: \"divmod\" expects 2 arguments \\\n          # E: Missing positional arguments \"_x\", \"_y\" in call to \"divmod\"\ndivmod(7)  # E: \"divmod\" expects 2 arguments \\\n           # E: Missing positional argument \"_y\" in call to \"divmod\"\ndivmod(7, 8, 9)  # E: \"divmod\" expects 2 arguments \\\n                 # E: Too many arguments for \"divmod\"\ndivmod(_x=7, _y=9)  # E: \"divmod\" must be called with 2 positional arguments\n\ndivmod('foo', 'foo')  # E: Unsupported left operand type for divmod (\"str\")\ndivmod(i, 'foo')  # E: Unsupported operand types for divmod (\"int\" and \"str\")\ndivmod(f, 'foo')  # E: Unsupported operand types for divmod (\"float\" and \"str\")\ndivmod(d, 'foo')  # E: Unsupported operand types for divmod (\"Decimal\" and \"str\")\n\ndivmod('foo', i)  # E: Unsupported operand types for divmod (\"str\" and \"int\")\ndivmod('foo', f)  # E: Unsupported operand types for divmod (\"str\" and \"float\")\ndivmod('foo', d)  # E: Unsupported operand types for divmod (\"str\" and \"Decimal\")\n\n[builtins fixtures/divmod.pyi]\n[typing fixtures/typing-medium.pyi]\n\n\n-- Unary operators\n-- ---------------\n\n\n[case testUnaryMinus]\na: A\nb: B\nif int():\n    a = -a   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    b = -b   # E: Unsupported operand type for unary - (\"B\")\nif int():\n    b = -a\n\nclass A:\n    def __neg__(self) -> 'B':\n        pass\nclass B:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testUnaryPlus]\na: A\nb: B\nif int():\n    a = +a   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    b = +b   # E: Unsupported operand type for unary + (\"B\")\nif int():\n    b = +a\n\nclass A:\n    def __pos__(self) -> 'B':\n        pass\nclass B:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testUnaryNot]\na: A\nb: bool\nif int():\n    a = not b  # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"A\")\nif int():\n    b = not a\nif int():\n    b = not b\nclass A:\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testUnaryBitwiseNeg]\na: A\nb: B\nif int():\n    a = ~a   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    b = ~b   # E: Unsupported operand type for ~ (\"B\")\nif int():\n    b = ~a\n\nclass A:\n    def __invert__(self) -> 'B':\n        pass\nclass B:\n    pass\n\n\n-- Indexing\n-- --------\n[builtins fixtures/tuple.pyi]\n\n\n[case testIndexing]\na: A\nb: B\nc: C\nif int():\n    c = a[c]  # E: Invalid index type \"C\" for \"A\"; expected type \"B\"\nif int():\n    a = a[b]  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A\")\nif int():\n    c = b[a]  # E: Value of type \"B\" is not indexable\nif int():\n    c = a[b]\n\nclass A:\n    def __getitem__(self, x: 'B') -> 'C':\n        pass\nclass B: pass\nclass C: pass\n[builtins fixtures/tuple.pyi]\n\n[case testIndexingAsLvalue]\na: A\nb: B\nc: C\na[c] = c  # Fail\na[b] = a  # Fail\nb[a] = c  # Fail\na[b] = c\n\nclass A:\n    def __setitem__(self, x: 'B', y: 'C') -> None:\n        pass\nclass B:\n    pass\nclass C:\n    pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:4: error: Invalid index type \"C\" for \"A\"; expected type \"B\"\nmain:5: error: Incompatible types in assignment (expression has type \"A\", target has type \"C\")\nmain:6: error: Unsupported target for indexed assignment (\"B\")\n\n[case testOverloadedIndexing]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\na: A\nb: B\nc: C\na[b]\na[c]\na[1]  # E: No overload variant of \"__getitem__\" of \"A\" matches argument type \"int\" \\\n      # N: Possible overload variants: \\\n      # N:     def __getitem__(self, B, /) -> int \\\n      # N:     def __getitem__(self, C, /) -> str\n\ni: int\ns: str\nif int():\n    i = a[b]\nif int():\n    s = a[b]  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nif int():\n    i = a[c]  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    s = a[c]\n\nclass A:\n    @overload\n    def __getitem__(self, x: 'B') -> int:\n        pass\n    @overload\n    def __getitem__(self, x: 'C') -> str:\n        pass\nclass B: pass\nclass C: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n\n-- Cast expression\n-- ---------------\n\n\n[case testCastExpressions]\nfrom typing import cast, Any\nclass A: pass\nclass B: pass\nclass C(A): pass\na: A\nb: B\nc: C\n\nif int():\n    a = cast(A, a())       # E: \"A\" not callable\nif int():\n    a = cast(Any, a())     # E: \"A\" not callable\n    b = cast(A, a)         # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\nif int():\n    a = cast(A, b)\nif int():\n    a = cast(A, a)\n    c = cast(C, a)\nif int():\n    a = cast(A, c)\nif int():\n    a = cast(Any, b)\n    b = cast(Any, a)\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testAnyCast]\nfrom typing import cast, Any\na: A\nb: B\na = cast(Any, a())     # Fail\na = cast(Any, b)\nb = cast(Any, a)\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:4: error: \"A\" not callable\n\n-- assert_type()\n\n[case testAssertType]\nfrom typing import assert_type, Any, Literal\na: int = 1\nreturned = assert_type(a, int)\nreveal_type(returned)  # N: Revealed type is \"builtins.int\"\nassert_type(a, str)  # E: Expression is of type \"int\", not \"str\"\nassert_type(a, Any)  # E: Expression is of type \"int\", not \"Any\"\nassert_type(a, Literal[1])  # E: Expression is of type \"int\", not \"Literal[1]\"\nassert_type(42, Literal[42])\nassert_type(42, int)  # E: Expression is of type \"Literal[42]\", not \"int\"\n[builtins fixtures/tuple.pyi]\n\n[case testAssertTypeGeneric]\nfrom typing import assert_type, Literal, TypeVar, Generic\nT = TypeVar(\"T\")\ndef f(x: T) -> T: return x\nassert_type(f(1), int)\nclass Gen(Generic[T]):\n    def __new__(cls, obj: T) -> Gen[T]: ...\nassert_type(Gen(1), Gen[int])\n# With type context, it infers Gen[Literal[1]] instead.\ny: Gen[Literal[1]] = assert_type(Gen(1), Gen[Literal[1]])\n\n[builtins fixtures/tuple.pyi]\n\n[case testAssertTypeUncheckedFunction]\nfrom typing import Literal, assert_type\ndef f():\n    x = 42\n    assert_type(x, Literal[42])\n[out]\nmain:4: error: Expression is of type \"Any\", not \"Literal[42]\"\nmain:4: note: \"assert_type\" expects everything to be \"Any\" in unchecked functions\n[builtins fixtures/tuple.pyi]\n\n[case testAssertTypeUncheckedFunctionWithUntypedCheck]\n# flags: --check-untyped-defs\nfrom typing import Literal, assert_type\ndef f():\n    x = 42\n    assert_type(x, Literal[42])\n[out]\nmain:5: error: Expression is of type \"int\", not \"Literal[42]\"\n[builtins fixtures/tuple.pyi]\n\n[case testAssertTypeNoPromoteUnion]\nfrom typing import Union, assert_type\n\nScalar = Union[int, bool, bytes, bytearray]\n\n\ndef reduce_it(s: Scalar) -> Scalar:\n    return s\n\nassert_type(reduce_it(True), Scalar)\n[builtins fixtures/tuple.pyi]\n\n[case testAssertTypeWithDeferredNodes]\nfrom typing import Callable, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\ndef dec(f: Callable[[], T]) -> Callable[[], T]:\n    return f\n\ndef func() -> None:\n    some = _inner_func()\n    assert_type(some, int)\n\n@dec\ndef _inner_func() -> int:\n    return 1\n[builtins fixtures/tuple.pyi]\n\n-- None return type\n-- ----------------\n\n\n[case testNoneReturnTypeBasics]\ndef f() -> None:\n    pass\n\nclass A:\n    def g(self, x: object) -> None:\n        pass\n    def __call__(self) -> None:\n        pass\n\na: A\no: object\nif int():\n    a = f()         # E: \"f\" does not return a value (it only ever returns None) \\\n                    # E: Incompatible types in assignment (expression has type \"None\", variable has type \"A\")\nif int():\n    o = a()         # E: Function does not return a value (it only ever returns None)\nif int():\n    o = A().g(a)    # E: \"g\" of \"A\" does not return a value (it only ever returns None)\nif int():\n    o = A.g(a, a)   # E: \"g\" of \"A\" does not return a value (it only ever returns None)\nA().g(f())      # E: \"f\" does not return a value (it only ever returns None)\nx: A = f()      # E: \"f\" does not return a value (it only ever returns None) \\\n                # E: Incompatible types in assignment (expression has type \"None\", variable has type \"A\")\nf()\nA().g(a)\n[builtins fixtures/tuple.pyi]\n\n[case testNoneReturnTypeWithStatements]\nimport typing\ndef f() -> None: pass\n\nif f():   # E: \"f\" does not return a value (it only ever returns None)\n    pass\nelif f(): # E: \"f\" does not return a value (it only ever returns None)\n    pass\nwhile f(): # E: \"f\" does not return a value (it only ever returns None)\n    pass\ndef g() -> object:\n    return f() # E: \"f\" does not return a value (it only ever returns None)\nraise f() # E: Exception must be derived from BaseException \\\n          # E: \"f\" does not return a value (it only ever returns None)\n[builtins fixtures/exception.pyi]\n\n[case testNoneReturnTypeWithExpressions]\nfrom typing import cast\n\ndef f() -> None: pass\nclass A:\n    def __add__(self, x: 'A') -> 'A': pass\n\na: A\n[f()]       # E: \"f\" does not return a value (it only ever returns None)\nf() + a     # E: \"f\" does not return a value (it only ever returns None) \\\n            # E: Unsupported left operand type for + (\"None\")\na + f()     # E: \"f\" does not return a value (it only ever returns None) \\\n            # E: Unsupported operand types for + (\"A\" and \"None\")\nf() == a    # E: \"f\" does not return a value (it only ever returns None)\na != f()    # E: Unsupported left operand type for != (\"A\") \\\n            # E: \"f\" does not return a value (it only ever returns None)\ncast(A, f())\nf().foo     # E: \"f\" does not return a value (it only ever returns None) \\\n            # E: \"None\" has no attribute \"foo\"\n[builtins fixtures/list.pyi]\n\n[case testNoneReturnTypeWithExpressions2]\nimport typing\n\ndef f() -> None: pass\nclass A:\n    def __add__(self, x: 'A') -> 'A':\n        pass\n\na: A\nb: bool\nf() in a   # E: \"f\" does not return a value (it only ever returns None) \\\n           # E: Unsupported right operand type for in (\"A\")\na < f()    # E: Unsupported left operand type for < (\"A\") \\\n           # E: \"f\" does not return a value (it only ever returns None)\nf() <= a   # E: \"f\" does not return a value (it only ever returns None) \\\n           # E: Unsupported left operand type for <= (\"None\")\na in f()   # E: Unsupported right operand type for in (\"None\") \\\n           # E: \"f\" does not return a value (it only ever returns None)\n-f()       # E: Unsupported operand type for unary - (\"None\") \\\n           # E: \"f\" does not return a value (it only ever returns None)\nnot f()    # E: \"f\" does not return a value (it only ever returns None)\nf() and b  # E: \"f\" does not return a value (it only ever returns None)\nb or f()   # E: \"f\" does not return a value (it only ever returns None)\n[builtins fixtures/bool.pyi]\n\n\n-- Slicing\n-- -------\n\n\n[case testGetSlice]\na: A\nb: B\nif int():\n    a = a[1:2] # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    a = a[1:]  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    a = a[:2]  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    a = a[:]   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\nif int():\n    b = a[1:2]\nif int():\n    b = a[1:]\nif int():\n    b = a[:2]\nif int():\n    b = a[:]\n\nclass A:\n  def __getitem__(self, s: slice) -> 'B': pass\nclass B: pass\n[builtins fixtures/slice.pyi]\n\n[case testSlicingWithInvalidBase]\n\na: A\na[1:2] # E: Invalid index type \"slice[int, int, None]\" for \"A\"; expected type \"int\"\na[:]   # E: Invalid index type \"slice[None, None, None]\" for \"A\"; expected type \"int\"\nclass A:\n  def __getitem__(self, n: int) -> 'A': pass\n[builtins fixtures/slice.pyi]\n\n[case testSlicingWithNonindexable]\n\no: object\no[1:2] # E: Value of type \"object\" is not indexable\no[:]   # E: Value of type \"object\" is not indexable\n[builtins fixtures/slice.pyi]\n\n[case testNonIntSliceBounds]\nfrom typing import Any\na: Any\no: object\na[o:1] # E: Slice index must be an integer, SupportsIndex or None\na[1:o] # E: Slice index must be an integer, SupportsIndex or None\na[o:]  # E: Slice index must be an integer, SupportsIndex or None\na[:o]  # E: Slice index must be an integer, SupportsIndex or None\n[builtins fixtures/slice.pyi]\n\n[case testSliceSupportsIndex]\nimport typing_extensions\nclass Index:\n    def __init__(self, value: int) -> None:\n        self.value = value\n    def __index__(self) -> int:\n        return self.value\n\nc = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nreveal_type(c[Index(0):Index(5)])  # N: Revealed type is \"builtins.list[builtins.int]\"\n[file typing_extensions.pyi]\nfrom typing import Protocol\nclass SupportsIndex(Protocol):\n    def __index__(self) -> int: ...\n[builtins fixtures/slice.pyi]\n\n[case testNoneSliceBounds]\nfrom typing import Any\na: Any\na[None:1]\na[1:None]\na[None:]\na[:None]\n[builtins fixtures/slice.pyi]\n\n[case testNoneSliceBoundsWithStrictOptional]\nfrom typing import Any\na: Any\na[None:1]\na[1:None]\na[None:]\na[:None]\n[builtins fixtures/slice.pyi]\n\n\n-- Lambdas\n-- -------\n\n\n[case testTrivialLambda]\nfrom typing import Callable\nf = lambda: 1 # type: Callable[[], int]\nif int():\n    f = lambda: ''.x # E: \"str\" has no attribute \"x\"\nif int():\n    f = lambda: '' \\\n        # E: Incompatible types in assignment (expression has type \"Callable[[], str]\", variable has type \"Callable[[], int]\") \\\n        # E: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testVoidLambda]\nimport typing\ndef void() -> None:\n    pass\nx = lambda: void() # type: typing.Callable[[], None]\n\n[case testNoCrashOnLambdaGenerator]\n# flags: --no-strict-optional\nfrom typing import Iterator, Callable\n\n# These should not crash\nlambda: (yield)\n\ngen: Callable[[], Iterator[str]]\ngen = (lambda: (yield 1))  # E: Incompatible types in \"yield\" (actual type \"int\", expected type \"str\")\n\ndef fun(cb: Callable[[], Iterator[str]]) -> None:\n    pass\nfun(lambda: (yield from [1]))  # E: Incompatible types in \"yield from\" (actual type \"int\", expected type \"str\")\n[builtins fixtures/list.pyi]\n[out]\n\n[case testLambdaAndReachability]\ndef f() -> None:\n    aa = []\n    y = lambda x: 1\n    aa.append(1)\n    1()  # E: \"int\" not callable\n[builtins fixtures/list.pyi]\n\n\n-- List comprehensions\n-- -------------------\n\n\n[case testSimpleListComprehension]\nfrom typing import List\na: List[A]\na = [x for x in a]\nb = [x for x in a] # type: List[B] # E: List comprehension has incompatible type List[A]; expected List[B]\nclass A: pass\nclass B: pass\n[builtins fixtures/for.pyi]\n\n[case testSimpleListComprehensionNestedTuples]\nfrom typing import List, Tuple\nl: List[Tuple[A, Tuple[A, B]]]\na = [a2 for a1, (a2, b1) in l] # type: List[A]\nb = [a2 for a1, (a2, b1) in l] # type: List[B] # E: List comprehension has incompatible type List[A]; expected List[B]\nclass A: pass\nclass B: pass\n[builtins fixtures/for.pyi]\n\n[case testSimpleListComprehensionNestedTuples2]\nfrom typing import List, Tuple\nl: List[Tuple[int, Tuple[int, str]]]\na = [f(d) for d, (i, s) in l]\nb = [f(s) for d, (i, s) in l] # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\ndef f(x: int): pass\n[builtins fixtures/for.pyi]\n\n[case testListComprehensionWithNonDirectMapping]\nfrom typing import List\na: List[A]\nb: List[B]\nif int():\n    b = [f(x) for x in a]\nif int():\n    a = [f(x) for x in a] # E: List comprehension has incompatible type List[B]; expected List[A]\n([f(x) for x in b])   # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\nclass A: pass\nclass B: pass\ndef f(a: A) -> B: pass\n[builtins fixtures/for.pyi]\n\n[case testErrorInListComprehensionCondition]\nfrom typing import List\na: List[A]\na = [x for x in a if x()] # E: \"A\" not callable\nclass A: pass\n[builtins fixtures/for.pyi]\n\n[case testTypeInferenceOfListComprehension]\nfrom typing import List\na: List[A]\no = [x for x in a] # type: List[object]\nclass A: pass\n[builtins fixtures/for.pyi]\n\n[case testSimpleListComprehensionInClassBody]\nfrom typing import List\nclass A:\n    a: List[A]\n    a = [x for x in a]\n    b = [x for x in a] # type: List[B] # E: List comprehension has incompatible type List[A]; expected List[B]\nclass B: pass\n[builtins fixtures/for.pyi]\n[out]\n\n\n-- Set comprehension\n-- -----------------\n\n\n[case testSimpleSetComprehension]\nfrom typing import Set\na: Set[A]\na = {x for x in a}\nb = {x for x in a} # type: Set[B] # E: Set comprehension has incompatible type Set[A]; expected Set[B]\nclass A: pass\nclass B: pass\n[builtins fixtures/set.pyi]\n\n\n-- Dictionary comprehension\n-- ------------------------\n\n\n[case testSimpleDictionaryComprehension]\nfrom typing import Dict, List, Tuple\nabd: Dict[A, B]\nabl: List[Tuple[A, B]]\nabd = {a: b for a, b in abl}\nx = {a: b for a, b in abl} # type: Dict[B, A]\ny = {a: b for a, b in abl} # type: A\nclass A: pass\nclass B: pass\n[builtins fixtures/dict.pyi]\n[out]\nmain:5: error: Key expression in dictionary comprehension has incompatible type \"A\"; expected type \"B\"\nmain:5: error: Value expression in dictionary comprehension has incompatible type \"B\"; expected type \"A\"\nmain:6: error: Incompatible types in assignment (expression has type \"dict[A, B]\", variable has type \"A\")\n\n\n[case testDictionaryComprehensionWithNonDirectMapping]\nfrom typing import Dict, List, Tuple\nabd: Dict[A, B]\nabl: List[Tuple[A, B]]\nabd = {a: f(b) for a, b in abl}\nclass A: pass\nclass B: pass\nclass C: pass\ndef f(b: A) -> C: pass\n[builtins fixtures/dict.pyi]\n[out]\nmain:4: error: Value expression in dictionary comprehension has incompatible type \"C\"; expected type \"B\"\nmain:4: error: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\n\n\n-- Generator expressions\n-- ---------------------\n\n\n[case testSimpleGeneratorExpression]\nfrom typing import Iterator\n# The implementation is mostly identical to list comprehensions, so only a few\n# test cases is ok.\na: Iterator[int]\nif int():\n    a = (x for x in a)\nb: Iterator[str]\nif int():\n    b = (x for x in a) # E: Generator has incompatible item type \"int\"; expected \"str\"\n[builtins fixtures/for.pyi]\n\n[case testGeneratorIncompatibleErrorMessage]\nfrom typing import Callable, Iterator, List\n\na = []  # type: List[Callable[[], str]]\nb: Iterator[Callable[[], int]]\nif int():\n    b = (x for x in a)  # E: Generator has incompatible item type \"Callable[[], str]\"; expected \"Callable[[], int]\"\n[builtins fixtures/list.pyi]\n\n[case testGeneratorNoSpuriousError_no_native_parse]\nfrom typing import Iterable, overload\n\n@overload\ndef take_iterable(iterable: Iterable[bool], /) -> None: ...\n@overload\ndef take_iterable(iterable: Iterable[int], /) -> None: ...\ndef take_iterable(iterable): pass\n\ntake_iterable(1 for _ in [])\ntake_iterable(reveal_type(1 for _ in [])) # N: Revealed type is \"typing.Generator[builtins.int, None, None]\"\n\n# NOTE: Type is revealed for every overload tried\n# TODO: Overload shouldn't fail if expression contains an error that shouldn't affect the inferred type.\ntake_iterable(reveal_type(1 if (-\"\") else 1 for _ in [])) # N: Revealed type is \"typing.Generator[builtins.int, None, None]\" \\\n                                                          # N: Revealed type is \"typing.Generator[builtins.bool, None, None]\" \\\n                                                          # E: Generator has incompatible item type \"int\"; expected \"bool\" \\\n                                                          # E: Unsupported operand type for unary - (\"str\")\n\n[builtins fixtures/for.pyi]\n\n-- Conditional expressions\n-- -----------------------\n\n\n[case testSimpleConditionalExpression]\nimport typing\ny = ''\nx = 1 if y else 2\nif int():\n    x = 3\nif int():\n    x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testConditionalExpressionWithEmptyCondition]\nimport typing\ndef f() -> None: pass\nx = 1 if f() else 2 # E: \"f\" does not return a value (it only ever returns None)\n\n[case testConditionalExpressionWithSubtyping]\nimport typing\nclass A: pass\nclass B(A): pass\nx = B() if bool() else A()\nif int():\n    x = A()\nif int():\n    x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"A\")\ny = A() if bool() else B()\nif int():\n    y = A()\nif int():\n    y = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"A\")\n[builtins fixtures/bool.pyi]\n\n[case testConditionalExpressionAndTypeContext]\nimport typing\nx = [1] if bool() else []\nif int():\n    x = [1]\nif int():\n    x = ['x'] # E: List item 0 has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testConditionalExpressionUnion]\nfrom typing import Union\nreveal_type(1 if bool() else 2) # N: Revealed type is \"Literal[1]? | Literal[2]?\"\nreveal_type(1 if bool() else '') # N: Revealed type is \"Literal[1]? | Literal['']?\"\nx: Union[int, str] = reveal_type(1 if bool() else '') # N: Revealed type is \"Literal[1]? | Literal['']?\"\nclass A:\n    pass\nclass B(A):\n    pass\nclass C:\n    pass\nclass D(A):\n    pass\na = A()\nb = B()\nc = C()\nd = D()\nreveal_type(a if bool() else b) # N: Revealed type is \"__main__.A\"\nreveal_type(b if bool() else c) # N: Revealed type is \"__main__.B | __main__.C\"\nreveal_type(c if bool() else b) # N: Revealed type is \"__main__.C | __main__.B\"\nreveal_type(c if bool() else a) # N: Revealed type is \"__main__.C | __main__.A\"\nreveal_type(d if bool() else b) # N: Revealed type is \"__main__.D | __main__.B\"\n[builtins fixtures/bool.pyi]\n\n[case testConditionalExpressionUnionWithAny]\nfrom typing import Union, Any\na: Any\nx: Union[int, str] = reveal_type(a if int() else 1)  # N: Revealed type is \"Any | Literal[1]?\"\nreveal_type(a if int() else 1)  # N: Revealed type is \"Any | Literal[1]?\"\n\n[case testConditionalExpressionStatementNoReturn]\nfrom typing import List, Union\nx = []\ny = \"\"\nx.append(y) if bool() else x.append(y)\nz = x.append(y) if bool() else x.append(y) # E: \"append\" of \"list\" does not return a value (it only ever returns None)\n[builtins fixtures/list.pyi]\n\n[case testConditionalExpressionWithUnreachableBranches]\nfrom typing import TypeVar\nT = TypeVar(\"T\", int, str)\ndef foo(x: T) -> T:\n    return x + 1 if isinstance(x, int) else x + \"a\"\n[builtins fixtures/isinstancelist.pyi]\n\n-- Special cases\n-- -------------\n\n\n[case testOperationsWithNonInstanceTypes]\nfrom typing import cast\nclass A:\n    def __add__(self, a: 'A') -> 'A': pass\ndef f() -> None:\n    pass\na: A\nNone + a   # E: Unsupported left operand type for + (\"None\")\nf + a      # E: Unsupported left operand type for + (\"Callable[[], None]\")\na + f      # E: Unsupported operand types for + (\"A\" and \"Callable[[], None]\")\ncast(A, f)\n[case testOperatorMethodWithInvalidArgCount]\n\na: A\na + a  # Fail\n\nclass A:\n    def __add__(self) -> 'A':\n        pass\n[out]\nmain:3: error: Too many arguments for \"__add__\" of \"A\"\n\n[case testOperatorMethodAsVar]\nfrom typing import Any\nclass A:\n    def __init__(self, _add: Any) -> None:\n        self.__add__ = _add\na: A\na + a\n[out]\n\n[case testOperatorMethodAsVar2]\n\nclass A:\n    def f(self, x: int) -> str: pass\n    __add__ = f\ns: str\ns = A() + 1\nA() + (A() + 1)\n[out]\nmain:7: error: Argument 1 has incompatible type \"str\"; expected \"int\"\n\n[case testIndexedLvalueWithSubtypes]\na: A\nb: B\nc: C\na[c] = c\na[b] = c\na[c] = b\n\nclass A:\n    def __setitem__(self, x: 'B', y: 'B') -> None:\n        pass\nclass B:\n    pass\nclass C(B):\n    pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n\n-- Ellipsis\n-- --------\n\n\n[case testEllipsis]\n\na: A\nif str():\n    a = ...  # E: Incompatible types in assignment (expression has type \"ellipsis\", variable has type \"A\")\nb = ...\nc = ...\nif str():\n    b = c\n....__class__\n....a  # E: \"ellipsis\" has no attribute \"a\"\n\nclass A: pass\n[builtins fixtures/dict-full.pyi]\n\n\n-- Yield expression\n-- ----------------\n\n\n[case testYieldExpression]\ndef f(x: int) -> None:\n    x = yield f('')\n    x = 1\n[builtins fixtures/for.pyi]\n[out]\nmain:1: error: The return type of a generator function should be \"Generator\" or one of its supertypes\nmain:2: error: \"f\" does not return a value (it only ever returns None)\nmain:2: error: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\n[case testYieldExpressionWithNone]\nfrom typing import Iterator\ndef f(x: int) -> Iterator[None]:\n    (yield)\n[builtins fixtures/for.pyi]\n[out]\n\n\n-- Yield from expression\n-- ----------------\n\n\n[case testYieldFromIteratorHasNoValue]\nfrom typing import Iterator\ndef f() -> Iterator[int]:\n    yield 5\ndef g() -> Iterator[int]:\n    a = yield from f()  # E: Function does not return a value (it only ever returns None)\n\n[case testYieldFromGeneratorHasValue]\nfrom typing import Iterator, Generator\ndef f() -> Generator[int, None, str]:\n    yield 5\n    return \"ham\"\ndef g() -> Iterator[int]:\n    a = \"string\"\n    a = yield from f()\n[out]\n\n[case testYieldFromTupleExpression]\nfrom typing import Generator\ndef g() -> Generator[int, None, None]:\n    x = yield from ()  # E: Function does not return a value (it only ever returns None)\n    x = yield from (0, 1, 2)  # E: Function does not return a value (it only ever returns None)\n    x = yield from (0, \"ERROR\")  # E: Incompatible types in \"yield from\" (actual type \"int | str\", expected type \"int\") \\\n                                 # E: Function does not return a value (it only ever returns None)\n    x = yield from (\"ERROR\",)  # E: Incompatible types in \"yield from\" (actual type \"str\", expected type \"int\") \\\n                               # E: Function does not return a value (it only ever returns None)\n[builtins fixtures/tuple.pyi]\n\n-- dict(...)\n-- ---------\n\n\n-- Note that the stub used in unit tests does not have all overload\n-- variants, but it should not matter.\n\n[case testDictWithKeywordArgsOnly]\nfrom typing import Dict, Any\nd1 = dict(a=1, b=2) # type: Dict[str, int]\nd2 = dict(a=1, b='') # type: Dict[str, int] # E: Dict entry 1 has incompatible type \"str\": \"str\"; expected \"str\": \"int\"\nd3 = dict(a=1) # type: Dict[int, int] # E: Dict entry 0 has incompatible type \"str\": \"int\"; expected \"int\": \"int\"\nd4 = dict(a=1, b=1)\nd4.xyz # E: \"dict[str, int]\" has no attribute \"xyz\"\nd5 = dict(a=1, b='') # type: Dict[str, Any]\n[builtins fixtures/dict.pyi]\n\n[case testDictWithoutKeywordArgs]\nfrom typing import Dict\nd = dict() # E: Need type annotation for \"d\" (hint: \"d: dict[<type>, <type>] = ...\")\nd2 = dict() # type: Dict[int, str]\ndict(undefined) # E: Name \"undefined\" is not defined\n[builtins fixtures/dict.pyi]\n\n[case testDictFromList]\nfrom typing import Dict\nd = dict([(1, 'x'), (2, 'y')])\nd() # E: \"dict[int, str]\" not callable\nd2 = dict([(1, 'x')]) # type: Dict[str, str] # E: List item 0 has incompatible type \"tuple[int, str]\"; expected \"tuple[str, str]\"\n[builtins fixtures/dict.pyi]\n\n[case testDictFromIterableAndKeywordArg]\nfrom typing import Dict\nit = [('x', 1)]\n\nd = dict(it, x=1)\nd() # E: \"dict[str, int]\" not callable\n\nd2 = dict(it, x='')\nd2() # E: \"dict[str, object]\" not callable\n\nd3 = dict(it, x='') # type: Dict[str, int] # E: Argument \"x\" to \"dict\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testDictFromIterableAndKeywordArg2]\nit = [(1, 'x')]\ndict(it, x='y') # E: Keyword argument only valid with \"str\" key type in call to \"dict\"\n[builtins fixtures/dict.pyi]\n\n[case testDictFromIterableAndKeywordArg3]\nd = dict([], x=1)\nd() # E: \"dict[str, int]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testDictFromIterableAndStarStarArgs]\nfrom typing import Dict\nit = [('x', 1)]\n\nkw = {'x': 1}\nd = dict(it, **kw)\nd() # E: \"dict[str, int]\" not callable\n\nkw2 = {'x': ''}\nd2 = dict(it, **kw2)\nd2() # E: \"dict[str, object]\" not callable\n\nd3 = dict(it, **kw2) # type: Dict[str, int] # E: Argument 2 to \"dict\" has incompatible type \"**dict[str, str]\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testDictFromIterableAndStarStarArgs2]\nit = [(1, 'x')]\nkw = {'x': 'y'}\nd = dict(it, **kw) # E: Keyword argument only valid with \"str\" key type in call to \"dict\"\nd() # E: \"dict[int, str]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testUserDefinedClassNamedDict]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\nclass dict(Generic[T, S]):\n    def __init__(self, x: T, **kwargs: T) -> None: pass\ndict(1, y=1)\n[builtins fixtures/dict.pyi]\n\n[case testSpecialSignatureForSubclassOfDict]\nfrom typing import TypeVar, Dict, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass D1(dict): pass # Implicit base class Dict[Any, Any]\nD1([(1, 2)], x=1)\nclass D2(Dict[T, S], Generic[T, S]): pass\nda = D2([('x', 2)], x=1)\nda() # E: \"D2[str, int]\" not callable\nD2([(1, 2)], x=1) # E: Keyword argument only valid with \"str\" key type in call to \"dict\"\ndb = D2(x=1)\ndb() # E: \"D2[str, int]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testSpecialSignatureForSubclassOfDict2]\nfrom typing import TypeVar, Dict, Generic\nT = TypeVar('T')\nclass D(Dict[str, T], Generic[T]): pass\nD([('x', 1)], x=1)\n[builtins fixtures/dict.pyi]\n\n[case testOverridingSpecialSignatureInSubclassOfDict]\nfrom typing import TypeVar, Dict, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass D(Dict[T, S], Generic[T, S]):\n    def __init__(self, x: S, y: T) -> None: pass\nd = D(1, y='')\nd() # E: \"D[str, int]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testRevealType]\nreveal_type(1) # N: Revealed type is \"Literal[1]?\"\n\n[case testRevealLocals]\nx = 1\ny = 2\nz = x + y\nreveal_locals()\n[out]\nmain:4: note: Revealed local types are:\nmain:4: note:     x: builtins.int\nmain:4: note:     y: builtins.int\nmain:4: note:     z: builtins.int\n\n[case testUndefinedRevealType]\nreveal_type(x)\n[out]\nmain:1: error: Name \"x\" is not defined\nmain:1: note: Revealed type is \"Any\"\n\n[case testUserDefinedRevealType]\ndef reveal_type(x: int) -> None: pass\nreveal_type(\"foo\") # E: Argument 1 to \"reveal_type\" has incompatible type \"str\"; expected \"int\"\n\n[case testTypingRevealType]\nfrom typing import reveal_type\nfrom typing import reveal_type as show_me_the_type\n\nreveal_type(1) # N: Revealed type is \"Literal[1]?\"\nshow_me_the_type(1) # N: Revealed type is \"Literal[1]?\"\n\n[case testTypingExtensionsRevealType]\nfrom typing_extensions import reveal_type\nfrom typing_extensions import reveal_type as show_me_the_type\n\nreveal_type(1) # N: Revealed type is \"Literal[1]?\"\nshow_me_the_type(1) # N: Revealed type is \"Literal[1]?\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testRevealTypeVar]\nreveal_type = 1\n1 + \"foo\" # E: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testRevealForward]\ndef f() -> None:\n    reveal_type(x)\nx = 1 + int()\n[out]\nmain:2: note: Revealed type is \"builtins.int\"\n\n[case testRevealUncheckedFunction]\ndef f():\n    x = 42\n    reveal_type(x)\n[out]\nmain:3: note: Revealed type is \"Any\"\nmain:3: note: 'reveal_type' always outputs 'Any' in unchecked functions\n\n[case testRevealCheckUntypedDefs]\n# flags: --check-untyped-defs\ndef f():\n    x = 42\n    reveal_type(x)\n[out]\nmain:4: note: Revealed type is \"builtins.int\"\n\n[case testRevealTypedDef]\ndef f() -> None:\n    x = 42\n    reveal_type(x)\n[out]\nmain:3: note: Revealed type is \"builtins.int\"\n\n[case testLambdaTypedContext]\ndef f() -> None:\n    lambda: 'a'.missing()  # E: \"str\" has no attribute \"missing\"\n\n[case testLambdaUnypedContext]\ndef f():\n    lambda: 'a'.missing()\n\n[case testLambdaCheckUnypedContext]\n# flags: --check-untyped-defs\ndef f():\n    lambda: 'a'.missing()  # E: \"str\" has no attribute \"missing\"\n\n[case testEqNone]\nNone == None\n[builtins fixtures/ops.pyi]\n\n[case testLtNone]\nNone < None  # E: Unsupported left operand type for < (\"None\")\n[builtins fixtures/ops.pyi]\n\n[case testDictWithStarExpr_no_native_parse]\n\nb = {'z': 26, *a}  # E: Invalid syntax\n[builtins fixtures/dict.pyi]\n\n[case testDictWithStarStarExpr]\n\nfrom typing import Dict, Iterable\n\nclass Thing:\n    def keys(self) -> Iterable[str]:\n        ...\n    def __getitem__(self, key: str) -> int:\n        ...\n\na = {'a': 1}\nb = {'z': 26, **a}\nc = {**b}\nd = {**a, **b, 'c': 3}\ne = {1: 'a', **a}  # E: Cannot infer value of type parameter \"KT\" of <dict> \\\n                   # N: Try assigning the literal to a variable annotated as dict[<key>, <val>]\nf = {**b}  # type: Dict[int, int]  # E: Unpacked dict entry 0 has incompatible type \"dict[str, int]\"; expected \"SupportsKeysAndGetItem[int, int]\"\ng = {**Thing()}\nh = {**a, **Thing()}\ni = {**Thing()}  # type: Dict[int, int]  # E: Unpacked dict entry 0 has incompatible type \"Thing\"; expected \"SupportsKeysAndGetItem[int, int]\" \\\n                 # N: Following member(s) of \"Thing\" have conflicts: \\\n                 # N:     Expected: \\\n                 # N:         def __getitem__(self, int, /) -> int \\\n                 # N:     Got: \\\n                 # N:         def __getitem__(self, str, /) -> int \\\n                 # N:     Expected: \\\n                 # N:         def keys(self) -> Iterable[int] \\\n                 # N:     Got: \\\n                 # N:         def keys(self) -> Iterable[str]\nj = {1: 'a', **Thing()}  # E: Cannot infer value of type parameter \"KT\" of <dict> \\\n                         # N: Try assigning the literal to a variable annotated as dict[<key>, <val>]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testDictIncompatibleTypeErrorMessage]\nfrom typing import Dict, Callable\n\ndef things() -> int:\n    return 42\n\nstuff: Dict[int, Callable[[], str]] = {\n    1: things  # E: Dict entry 0 has incompatible type \"int\": \"Callable[[], int]\"; expected \"int\": \"Callable[[], str]\"\n}\n[builtins fixtures/dict.pyi]\n\n[case testDictIncompatibleKeyVerbosity]\nfrom typing import Dict\nimport mod\n\nclass A: ...\nclass B(A): ...\n\nd: Dict[A, B] = {A(): mod.B()}  # E: Dict entry 0 has incompatible type \"A\": \"mod.B\"; expected \"A\": \"__main__.B\"\n\n[file mod.py]\nclass B: ...\n\n[builtins fixtures/dict.pyi]\n\n[case testDictIncompatibleValueVerbosity]\nfrom typing import Dict\nimport mod\n\nclass A: ...\nclass B(A): ...\n\nd: Dict[B, A] = {mod.B(): A()}  # E: Dict entry 0 has incompatible type \"mod.B\": \"A\"; expected \"__main__.B\": \"A\"\n\n[file mod.py]\nclass B: ...\n\n[builtins fixtures/dict.pyi]\n\n[case testTypeAnnotationNeededMultipleAssignment]\nx, y = [], [] # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\") \\\n            # E: Need type annotation for \"y\" (hint: \"y: list[<type>] = ...\")\n[builtins fixtures/list.pyi]\n\n[case testStrictEqualityEq]\n# flags: --strict-equality\nclass A: ...\nclass B: ...\nclass C(B): ...\n\nA() == B()  # E: Non-overlapping equality check (left operand type: \"A\", right operand type: \"B\")\nB() == C()\nC() == B()\nA() != B()  # E: Non-overlapping equality check (left operand type: \"A\", right operand type: \"B\")\nB() != C()\nC() != B()\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityIs]\n# flags: --strict-equality\nclass A: ...\nclass B: ...\nclass C(B): ...\n\nA() is B()  # E: Non-overlapping identity check (left operand type: \"A\", right operand type: \"B\")\nB() is C()\nC() is B()\nA() is not B()  # E: Non-overlapping identity check (left operand type: \"A\", right operand type: \"B\")\nB() is not C()\nC() is not B()\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityContains]\n# flags: --strict-equality\nclass A: ...\nclass B: ...\nclass C(B): ...\n\nA() in [B()]  # E: Non-overlapping container check (element type: \"A\", container item type: \"B\")\nB() in [C()]\nC() in [B()]\nA() not in [B()]  # E: Non-overlapping container check (element type: \"A\", container item type: \"B\")\nB() not in [C()]\nC() not in [B()]\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrictEqualityUnions]\n# flags: --strict-equality\nfrom typing import Container, Union\n\nclass A: ...\nclass B: ...\n\na: Union[int, str]\nb: Union[A, B]\n\na == int()\nb == int()  # E: Non-overlapping equality check (left operand type: \"A | B\", right operand type: \"int\")\n\na is int()\nb is int()  # E: Non-overlapping identity check (left operand type: \"A | B\", right operand type: \"int\")\n\nca: Union[Container[int], Container[str]]\ncb: Union[Container[A], Container[B]]\n\n42 in ca\n42 in cb  # E: Non-overlapping container check (element type: \"int\", container item type: \"A | B\")\n[builtins fixtures/bool.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrictEqualityBytesSpecial]\n# flags: --strict-equality\nb'abc' in b'abcde'\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStrictEqualityBytesSpecialUnion]\n# flags: --strict-equality\nfrom typing import Union\nx: Union[bytes, str]\n\nb'abc' in x\nx in b'abc'\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStrictEqualityByteArraySpecial]\n# flags: --strict-equality\nb'abc' in bytearray(b'abcde')\nbytearray(b'abc') in b'abcde'  # OK on Python 3\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStrictEqualityNoPromotePy3]\n# flags: --strict-equality\n'a' == b'a'  # E: Non-overlapping equality check (left operand type: \"Literal['a']\", right operand type: \"Literal[b'a']\")\nb'a' in 'abc'  # E: Non-overlapping container check (element type: \"bytes\", container item type: \"str\")\n\nx: str\ny: bytes\nx != y  # E: Non-overlapping equality check (left operand type: \"str\", right operand type: \"bytes\")\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrictEqualityOkPromote]\n# flags: --strict-equality\nfrom typing import Container\nc: Container[int]\n\n1 == 1.0  # OK\n1.0 in c  # OK\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrictEqualityAny]\n# flags: --strict-equality\nfrom typing import Any, Container\n\nx: Any\nc: Container[str]\nx in c\nx == 42\nx is 42\n[builtins fixtures/bool.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrictEqualityStrictOptional]\n# flags: --strict-equality\n\nx: str\nif x is not None:  # OK even with strict-optional\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityNoStrictOptional]\n# flags: --strict-equality --no-strict-optional\n\nx: str\nif x is not None:  # OK without strict-optional\n    pass\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityEqNoOptionalOverlap]\n# flags: --strict-equality\nfrom typing import Optional\n\nx: Optional[str]\ny: Optional[int]\nif x == y:  # E: Non-overlapping equality check (left operand type: \"str | None\", right operand type: \"int | None\")\n    ...\n[builtins fixtures/bool.pyi]\n\n[case testCustomEqCheckStrictEquality]\n# flags: --strict-equality\nclass A:\n    def __eq__(self, other: A) -> bool:  # type: ignore\n        ...\nclass B:\n    def __eq__(self, other: B) -> bool:  # type: ignore\n        ...\n\n# Don't report non-overlapping check if there is already and error.\nA() == B()  # E: Unsupported operand types for == (\"A\" and \"B\")\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualitySequenceAndCustomEq]\n# flags: --strict-equality\nfrom typing import Tuple\n\nclass C: pass\nclass D:\n    def __eq__(self, other): return True\n\na = [C()]\nb = [D()]\na == b\nb == a\nt1: Tuple[C, ...]\nt2: Tuple[D, ...]\nt1 == t2\nt2 == t1\n[builtins fixtures/bool.pyi]\n\n[case testCustomEqCheckStrictEqualityOKInstance]\n# flags: --strict-equality\nclass A:\n    def __eq__(self, other: object) -> bool:\n        ...\nclass B:\n    def __eq__(self, other: object) -> bool:\n        ...\n\nA() == int()  # OK\nint() != B()  # OK\n[builtins fixtures/bool.pyi]\n\n[case testCustomEqCheckStrictEqualityOKUnion]\n# flags: --strict-equality\nfrom typing import Union\nclass A:\n    def __eq__(self, other: object) -> bool:\n        ...\n\nx: Union[A, str]\nx == int()\n[builtins fixtures/bool.pyi]\n\n[case testCustomEqCheckStrictEqualityTuple]\n# flags: --strict-equality\nfrom typing import NamedTuple\n\nclass Base(NamedTuple):\n    attr: int\n\nclass Custom(Base):\n    def __eq__(self, other: object) -> bool: ...\n\nBase(int()) == int()  # E: Non-overlapping equality check (left operand type: \"Base\", right operand type: \"int\")\nBase(int()) == tuple()\nCustom(int()) == int()\n[builtins fixtures/bool.pyi]\n\n[case testCustomEqCheckStrictEqualityMeta]\n# flags: --strict-equality\nclass CustomMeta(type):\n    def __eq__(self, other: object) -> bool: ...\n\nclass Normal: ...\nclass Custom(metaclass=CustomMeta): ...\n\nNormal == int()  # E: Non-overlapping equality check (left operand type: \"type[Normal]\", right operand type: \"int\")\nNormal == Normal\nCustom == int()\n\nn: type[Normal] = Normal\nc: type[Custom] = Custom\n\nn == int()  # E: Non-overlapping equality check (left operand type: \"type[Normal]\", right operand type: \"int\")\nn == n\nc == int()\n\n[builtins fixtures/bool.pyi]\n\n[case testCustomContainsCheckStrictEquality]\n# flags: --strict-equality\nclass A:\n    def __contains__(self, other: A) -> bool:\n        ...\n\n# Don't report non-overlapping check if there is already and error.\n42 in A()  # E: Unsupported operand types for in (\"int\" and \"A\")\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityTypeVsCallable]\n# flags: --strict-equality\nfrom typing import Type, List\nclass C: ...\nclass D(C): ...\nclass Bad: ...\n\nsubclasses: List[Type[C]]\nobject in subclasses\nD in subclasses\nBad in subclasses  # E: Non-overlapping container check (element type: \"type[Bad]\", container item type: \"type[C]\")\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrictEqualityMetaclass]\n# flags: --strict-equality\nfrom typing import List, Type, Any\n\nclass Meta(type): ...\nclass OtherMeta(type): ...\n\nclass A(metaclass=Meta): ...\nclass B(metaclass=Meta): ...\nclass C(metaclass=OtherMeta): ...\n\no: Type[object]\na: Type[Any]\naa: type\nexp: List[Meta]\n\nA in exp\nB in exp\nC in exp  # E: Non-overlapping container check (element type: \"type[C]\", container item type: \"Meta\")\n\no in exp\na in exp\naa in exp\n\na in [A, B]\naa in [A, B]\n\nclass AA: ...\nclass BB: ...\na in [AA, BB]\naa in [AA, BB]\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testEmptyListOverlap]\n# mypy: strict-equality\nfrom typing import List\n\nx: List[int]\nx == []\n[builtins fixtures/isinstancelist.pyi]\n\n[case testCustomEqDecoratedStrictEquality]\n# flags: --strict-equality\nfrom typing import TypeVar, Callable, Any\n\nF = TypeVar('F', bound=Callable[..., Any])\n\ndef deco(f: F) -> F: ...\n\nclass Custom:\n    @deco\n    def __eq__(self, other: object) -> bool: ...\n\nCustom() == int()\n[builtins fixtures/bool.pyi]\n\n[case testCustomEqVarStrictEquality]\n# flags: --strict-equality\n\nclass Custom:\n    def compare(self, other: object) -> bool: ...\n    __eq__ = compare\n\nCustom() == int()\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityDisabledWithTypeVarRestrictions]\n# flags: --strict-equality\nfrom typing import TypeVar\n\nT = TypeVar('T', str, int)\n\ndef f(x: T) -> T:\n    if x == int():  # OK\n        ...\n    return x\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityWithALiteral]\n# flags: --strict-equality\nfrom typing import Final, Literal\n\ndef returns_a_or_b() -> Literal['a', 'b']:\n    ...\ndef returns_1_or_2() -> Literal[1, 2]:\n    ...\nTHREE: Final = 3\n\nif returns_a_or_b() == 'c':  # E: Non-overlapping equality check (left operand type: \"Literal['a', 'b']\", right operand type: \"Literal['c']\")\n    ...\nif returns_1_or_2() is THREE:  # E: Non-overlapping identity check (left operand type: \"Literal[1, 2]\", right operand type: \"Literal[3]\")\n    ...\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityWithALiteralNewType]\n# flags: --strict-equality\nfrom typing import NewType\n\nUserId = NewType('UserId', int)\nFileId = NewType('FileId', str)\n\nu: UserId\nf: FileId\n\nif u == 0:  # OK\n    ...\nif f == 0:  # E: Non-overlapping equality check (left operand type: \"FileId\", right operand type: \"Literal[0]\")\n    ...\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityWithFixedLengthTupleInCheck]\n# flags: --strict-equality\nif 1 in ('x', 'y'):  # E: Non-overlapping container check (element type: \"int\", container item type: \"str\")\n    pass\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testOverlappingAnyTypeWithoutStrictOptional]\n# flags: --no-strict-optional --strict-equality\nfrom typing import Any, Optional\n\nx: Optional[Any]\n\nif x in (1, 2):\n    pass\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n\n[case testOverlappingClassCallables]\n# flags: --strict-equality\nfrom typing import Any, Callable, Type\n\nx: Type[int]\ny: Callable[[], Any]\nx == y\ny == x\nint == y\ny == int\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityAndEnumWithCustomEq]\n# flags: --strict-equality\nfrom enum import Enum\n\nclass E1(Enum):\n    X = 0\n    Y = 1\n\nclass E2(Enum):\n    X = 0\n    Y = 1\n\n    def __eq__(self, other: object) -> bool:\n        return bool()\n\nE1.X == E1.Y  # E: Non-overlapping equality check (left operand type: \"Literal[E1.X]\", right operand type: \"Literal[E1.Y]\")\nE2.X == E2.Y\n[builtins fixtures/bool.pyi]\n\n[case testStrictEqualityWithBytesContains]\n# flags: --strict-equality\ndata = b\"xy\"\nb\"x\" in data\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrictEqualityWithDifferentMapTypes]\n# flags: --strict-equality\nfrom typing import Mapping\n\nclass A(Mapping[int, str]): ...\nclass B(Mapping[int, str]): ...\n\na: A\nb: B\nassert a == b\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrictEqualityWithRecursiveMapTypes]\n# flags: --strict-equality\nfrom typing import Dict\n\nR = Dict[str, R]\n\na: R\nb: R\nassert a == b\n\nR2 = Dict[int, R2]\nc: R2\nassert a == c  # E: Non-overlapping equality check (left operand type: \"dict[str, R]\", right operand type: \"dict[int, R2]\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrictEqualityWithRecursiveListTypes]\n# flags: --strict-equality\nfrom typing import List, Union\n\nR = List[Union[str, R]]\n\na: R\nb: R\nassert a == b\n\nR2 = List[Union[int, R2]]\nc: R2\nassert a == c\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStrictEqualityForNone]\n# flags: --strict-equality --strict-equality-for-none\n\nclass A: ...\n\ndef a1(x: A) -> None:\n    assert x is None  # E: Non-overlapping identity check (left operand type: \"A\", right operand type: \"None\")\ndef a2(x: A) -> None:\n    x is not None  # E: Non-overlapping identity check (left operand type: \"A\", right operand type: \"None\")\ndef a3(x: A) -> None:\n    None == x  # E: Non-overlapping equality check (left operand type: \"None\", right operand type: \"A\")\ndef a4(x: list[A]) -> None:\n    None in x  # E: Non-overlapping container check (element type: \"None\", container item type: \"A\")\n\nclass B:\n    def __eq__(self, x: object) -> bool: ...\n\ndef b1(x: B) -> None:\n    assert x is None  # E: Non-overlapping identity check (left operand type: \"B\", right operand type: \"None\")\ndef b2(x: B) -> None:\n    x is not None  # E: Non-overlapping identity check (left operand type: \"B\", right operand type: \"None\")\ndef b3(x: B) -> None:\n    x == None\ndef b4(x: list[B]) -> None:\n    None in x\n\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testUnimportedHintAny]\ndef f(x: Any) -> None:  # E: Name \"Any\" is not defined \\\n                        # N: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import Any\")\n    pass\n\n\n[case testUnimportedHintAnyLower]\ndef f(x: any) -> None:  # E: Name \"any\" is not defined \\\n                        # N: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import Any\")\n    pass\n\n\n[case testUnimportedHintOptional]\ndef f(x: Optional[str]) -> None:  # E: Name \"Optional\" is not defined \\\n                                  # N: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import Optional\")\n    pass\n\n[case testAssertionLazilyWithIsNone]\nfrom typing import Optional, List\nli: Optional[List] = []\nassert li is None, li[0]\n[builtins fixtures/list.pyi]\n\n\n[case testAssertionLazilyWithIsInstance]\nfrom typing import Optional, List\nli: Optional[List] = []\nassert not isinstance(li,list), li[0]\n[builtins fixtures/isinstancelist.pyi]\n\n[case testAssertCurrentFrameIsNotUnreachable]\ndef f() -> int:  # E: Missing return statement\n    x: int\n    assert isinstance(x, int), '...'\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeVarAsValue]\nfrom typing import TypeVar\nT = TypeVar(\"T\")\nx: int\nx + T  # E: Unsupported left operand type for + (\"int\")\nT()  # E: \"TypeVar\" not callable\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testStringDisallowedUnpacking]\nd: dict[str, str]\n\nfor a1, b1 in d: # E: Unpacking a string is disallowed\n    reveal_type(a1)  # N: Revealed type is \"builtins.str\"\n    reveal_type(b1)  # N: Revealed type is \"builtins.str\"\n\ns = \"foo\"\na2, b2 = s # E: Unpacking a string is disallowed\nreveal_type(a2)  # N: Revealed type is \"builtins.str\"\nreveal_type(b2)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/primitives.pyi]\n\n[case testStringLiteralUnpacking]\nfrom typing import Literal, Final\n\ndef takes_literal(xy: Literal[\"xy\"]):\n    x, y = xy\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    reveal_type(y)  # N: Revealed type is \"builtins.str\"\n\n    x, y, z = xy  # E: Unpacking a string is disallowed\n    reveal_type(z)  # N: Revealed type is \"builtins.str\"\n\ndef last_known_value() -> None:\n    xy: Final = \"xy\"\n    x, y = xy\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    reveal_type(y)  # N: Revealed type is \"builtins.str\"\n\n    x, y, z = xy  # E: Unpacking a string is disallowed\n    reveal_type(z)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/primitives.pyi]\n"
  },
  {
    "path": "test-data/unit/check-fastparse.test",
    "content": "[case testFastParseSyntaxError_no_native_parse]\n\n1 +  # E: Invalid syntax\n\n[case testFastParseTypeCommentSyntaxError_no_native_parse]\n\nx = None # type: a : b  # E: Syntax error in type comment \"a : b\"\n\n[case testFastParseInvalidTypeComment]\n\nx = None # type: a + b  # E: Invalid type comment or annotation\n\n-- Function type comments are attributed to the function def line.\n-- This happens in both parsers.\n[case testFastParseFunctionAnnotationSyntaxError_no_native_parse]\n\ndef f():  # E: Syntax error in type comment \"None -> None\" # N: Suggestion: wrap argument types in parentheses\n  # type: None -> None\n  pass\n\n[case testFastParseFunctionAnnotationSyntaxErrorSpaces_no_native_parse]\n\ndef f():  # E: Syntax error in type comment \"None -> None\" # N: Suggestion: wrap argument types in parentheses\n  # type:             None -> None\n  pass\n\n[case testFastParseInvalidFunctionAnnotation]\n\ndef f(x):  # E: Invalid type comment or annotation\n  # type: (a + b) -> None\n  pass\n\n[case testFastParseInvalidTypes3]\n# All of these should not crash\nfrom typing import Callable, Tuple, Iterable\n\nx: Tuple[int, str].x # E: Invalid type comment or annotation\na: Iterable[x].x # E: Invalid type comment or annotation\nb: Tuple[x][x] # E: Invalid type comment or annotation\nc: Iterable[x][x] # E: Invalid type comment or annotation\nd: Callable[..., int][x] # E: Invalid type comment or annotation\ne: Callable[..., int].x # E: Invalid type comment or annotation\n\nf = None # type: Tuple[int, str].x # E: Invalid type comment or annotation\ng = None # type: Iterable[x].x # E: Invalid type comment or annotation\nh = None # type: Tuple[x][x] # E: Invalid type comment or annotation\ni = None # type: Iterable[x][x] # E: Invalid type comment or annotation\nj = None # type: Callable[..., int][x] # E: Invalid type comment or annotation\nk = None # type: Callable[..., int].x # E: Invalid type comment or annotation\n\ndef f1(x: Tuple[int, str].x) -> None: pass # E: Invalid type comment or annotation\ndef f2(x: Iterable[x].x) -> None: pass # E: Invalid type comment or annotation\ndef f3(x: Tuple[x][x]) -> None: pass # E: Invalid type comment or annotation\ndef f4(x: Iterable[x][x]) -> None: pass # E: Invalid type comment or annotation\ndef f5(x: Callable[..., int][x]) -> None: pass # E: Invalid type comment or annotation\ndef f6(x: Callable[..., int].x) -> None: pass # E: Invalid type comment or annotation\n\n[case testFastParseTypeWithIgnore]\ndef f(x,  # type: x  # type: ignore\n      ):\n    # type: (...) -> None\n    pass\n\n[case testFastParseVariableTypeWithIgnore]\n\nx = 1 # type: str # type: ignore\n\n[case testFastParseVariableTypeWithIgnoreNoSpace]\n\nx = 1 # type: str #type:ignore\n\n[case testFastParseVariableTypeWithIgnoreAndComment]\n\nx = 1 # type: str # type: ignore # comment\n\n[case testFastParseTypeWithIgnoreWithStmt]\nwith open('test', 'r') as f:  # type: int  # type: ignore\n    pass\n\n[case testFastParseTypeWithIgnoreForStmt]\nfor i in (1, 2, 3, 100):  # type: str # type: ignore\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testFastParseVariableCommentThenIgnore]\na=\"test\" # type: int #comment # type: ignore  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testFastParseProperty]\n\nclass C:\n  @property\n  def x(self) -> str: pass\n  @x.setter\n  def x(self, value: str) -> None: pass\n[builtins fixtures/property.pyi]\n\n[case testFastParseConditionalProperty]\n\nclass C:\n  if bool():\n    @property\n    def x(self) -> str: pass\n    @x.setter\n    def x(self, value: str) -> None: pass\n[builtins fixtures/property.pyi]\n\n[case testFastParsePerArgumentAnnotations]\n# flags: --implicit-optional\n\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\nclass E: pass\nclass F: pass\ndef f(a,        # type: A\n      b = None, # type: B\n      *args,    # type: C\n      d = None, # type: D\n      e,        # type: E\n      **kwargs  # type: F\n      ):\n    reveal_type(a)      # N: Revealed type is \"__main__.A\"\n    reveal_type(b)      # N: Revealed type is \"__main__.B | None\"\n    reveal_type(args)   # N: Revealed type is \"builtins.tuple[__main__.C, ...]\"\n    reveal_type(d)      # N: Revealed type is \"__main__.D | None\"\n    reveal_type(e)      # N: Revealed type is \"__main__.E\"\n    reveal_type(kwargs) # N: Revealed type is \"builtins.dict[builtins.str, __main__.F]\"\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testFastParsePerArgumentAnnotationsWithReturn]\n# flags: --implicit-optional\n\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\nclass E: pass\nclass F: pass\ndef f(a,        # type: A\n      b = None, # type: B\n      *args,    # type: C\n      d = None, # type: D\n      e,        # type: E\n      **kwargs  # type: F\n      ):\n      # type: (...) -> int\n    reveal_type(a)      # N: Revealed type is \"__main__.A\"\n    reveal_type(b)      # N: Revealed type is \"__main__.B | None\"\n    reveal_type(args)   # N: Revealed type is \"builtins.tuple[__main__.C, ...]\"\n    reveal_type(d)      # N: Revealed type is \"__main__.D | None\"\n    reveal_type(e)      # N: Revealed type is \"__main__.E\"\n    reveal_type(kwargs) # N: Revealed type is \"builtins.dict[builtins.str, __main__.F]\"\n    return \"not an int\"  # E: Incompatible return value type (got \"str\", expected \"int\")\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testFastParsePerArgumentAnnotationsWithAnnotatedBareStar_no_native_parse]\n\ndef f(*, # type: int  # E: Bare * has associated type comment\n      x  # type: str\n      ):\n      # type: (...) -> int\n    pass\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testFastParsePerArgumentAnnotationsWithReturnAndBareStar]\n\ndef f(*,\n      x  # type: str\n      ):\n      # type: (...) -> int\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n    return \"not an int\"  # E: Incompatible return value type (got \"str\", expected \"int\")\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testFasterParseTooManyArgumentsAnnotation]\ndef f():  # E: Type signature has too many parameters\n    # type: (int) -> None\n    pass\n\nf()\nf(1) # E: Too many arguments for \"f\"\n\n[case testFasterParseTooFewArgumentsAnnotation]\ndef f(x, y):  # E: Type signature has too few parameters\n    # type: (int) -> None\n    x()\n    y()\n\nf(1, 2)\nf(1) # E: Missing positional argument \"y\" in call to \"f\"\n\n[case testFasterParseTypeErrorCustom_no_native_parse]\n\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass Foo(Generic[T]):\n  pass\n\ndef f(a: Foo(int)) -> int:\n    pass\n[out]\nmain:7: error: Invalid type comment or annotation\nmain:7: note: Suggestion: use Foo[...] instead of Foo(...)\n\n[case testFastParseMatMul]\n\nfrom typing import Any\nx = None  # type: Any\nx @ 1\nx @= 1\n\n[case testFastParserShowsMultipleErrors]\ndef f(x):  # E: Type signature has too few parameters\n    # type: () -> None\n    pass\ndef g():  # E: Type signature has too many parameters\n    # type: (int) -> None\n    pass\n\n[case testFastParseMalformedAssert]\n\nassert 1, 2\nassert (1, 2)  # E: Assertion is always true, perhaps remove parentheses?\nassert (1, 2), 3  # E: Assertion is always true, perhaps remove parentheses?\nassert (1,)  # E: Assertion is always true, perhaps remove parentheses?\nassert ()\n[builtins fixtures/tuple.pyi]\n\n[case testFastParseAssertMessage]\n\nassert 1\nassert 1, 2\nassert 1, 1+2\nassert 1, 1+'test'  # E: Unsupported operand types for + (\"int\" and \"str\")\nassert 1, f()  # E: Name \"f\" is not defined\n\n[case testFastParserConsistentFunctionTypes]\n\ndef f1(x, y, z):\n  # type: (int, int, int) -> int\n  pass\n\ndef f2(x,  # type: int  # E: Function has duplicate type signatures\n      y,  # type: int\n      z   # type: int\n    ):\n    # type: (int, int, int) -> int\n    pass\n\ndef f3(x,  # type: int\n      y,  # type: int\n      z   # type: int\n    ):\n    # type: (...) -> int\n    pass\n\ndef f4(x, y, z):\n  # type: (int, int, int) -> int\n  pass\n\ndef f5(x) -> int:  # E: Function has duplicate type signatures\n  # type: (int) -> int\n  pass\n\ndef f6(x: int, y: int, z: int):\n  # type: (...) -> int\n  pass\n\ndef f7(x: int):  # E: Function has duplicate type signatures\n  # type: (int) -> int\n  pass\n\n[case testFastParserDuplicateNames_no_native_parse]\n\ndef f(x, y, z):\n  pass\n\ndef g(x, y, x):  # E: Duplicate parameter \"x\" in function definition\n  pass\n\ndef h(x, y, *x):  # E: Duplicate parameter \"x\" in function definition\n  pass\n\ndef i(x, y, *z, **z):  # E: Duplicate parameter \"z\" in function definition\n  pass\n\ndef j(x: int, y: int, *, x: int = 3):  # E: Duplicate parameter \"x\" in function definition\n  pass\n\ndef k(*, y, z, y):  # E: Duplicate parameter \"y\" in function definition\n  pass\n\nlambda x, y, x: ...  # E: Duplicate parameter \"x\" in function definition\n\n[case testNoCrashOnImportFromStar]\nfrom pack import *\n[file pack/__init__.py]\nfrom . import *\n\n[case testNoCrashOnImportFromStarNested]\n\nimport blamodule\n[file blamodule/__init__.py]\nfrom . import command\nfrom . import backends\n\n[file blamodule/backends/__init__.py]\nfrom .Bla import Bla\nBla().method()\n\n[file blamodule/backends/Bla.py]\nfrom .. import *\n\nclass Bla:\n    def method(self) -> str:\n        return command.call()\n\n[file blamodule/command.py]\ndef call() -> str: pass\n\n[builtins fixtures/module.pyi]\n\n[case testInvalidEscapeSequenceWarningsSuppressed]\n# flags: --python-version 3.14 --enable-incomplete-feature=TypeForm\n# Test that SyntaxWarnings for invalid escape sequences are suppressed\n# when parsing potential type expressions containing regex patterns or\n# similar strings. Callable arguments are always potential type expressions.\nfrom typing import TypeForm\n\ndef identity(typx: TypeForm) -> TypeForm:\n    return typx\n\n# This should not generate SyntaxWarning despite invalid escape sequence\nidentity(r\"re\\.match\")  # E: Argument 1 to \"identity\" has incompatible type \"str\"; expected \"TypeForm[Any]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n"
  },
  {
    "path": "test-data/unit/check-final.test",
    "content": "-- Test cases for final qualifier\n--\n\n-- Definitions\n\n[case testFinalDefiningModuleVar]\nfrom typing import Final\n\nx: Final = int()\ny: Final[float] = int()\nz: Final[int] = int()\nbad: Final[str] = int()  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\nreveal_type(y)  # N: Revealed type is \"builtins.float\"\nreveal_type(z)  # N: Revealed type is \"builtins.int\"\n[out]\n\n[case testFinalDefiningInstanceVar]\nfrom typing import Final\n\nclass C:\n    x: Final = int()\n    y: Final[float] = int()\n    z: Final[int] = int()\n    bad: Final[str] = int()  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nclass D(C): pass\n\nreveal_type(D.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(D.y)  # N: Revealed type is \"builtins.float\"\nreveal_type(D.z)  # N: Revealed type is \"builtins.int\"\nreveal_type(D().x)  # N: Revealed type is \"builtins.int\"\nreveal_type(D().y)  # N: Revealed type is \"builtins.float\"\nreveal_type(D().z)  # N: Revealed type is \"builtins.int\"\n[out]\n\n[case testFinalDefiningInstanceVarImplicit]\nfrom typing import Final, Tuple, Any\n\nclass C:\n    def __init__(self, x: Tuple[int, Any]) -> None:\n        self.x: Final = x\n        self.y: Final[float] = 1\nreveal_type(C((1, 2)).x)  # N: Revealed type is \"tuple[builtins.int, Any]\"\nreveal_type(C((1, 2)).y)  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFinalBadDefinitionTooManyArgs]\nfrom typing import Final\n\nx: Final[int, str]  # E: Final name must be initialized with a value \\\n                    # E: Final[...] takes at most one type argument\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nclass C:\n    def __init__(self) -> None:\n        self.x: Final[float, float] = 1  # E: Final[...] takes at most one type argument\nreveal_type(C().x)  # N: Revealed type is \"builtins.float\"\n[out]\n\n[case testFinalInvalidDefinitions]\n\n# Errors are shown in a different order with the new analyzer.\nfrom typing import Final, Any\n\nx = y = 1  # type: Final[float]  # E: Invalid final declaration\nz: Any\nz[0]: Final[int]  # E: Invalid final declaration \\\n                  # E: Unexpected type declaration\n[out]\n\n[case testFinalDefiningInstanceVarStubs]\n# Allow skipping r.h.s.\nimport mod\n[file mod.pyi]\nfrom typing import Final\n\nx: Final  # E: Type in Final[...] can only be omitted if there is an initializer\ny: Final[int]\nclass C:\n    x: Final  # E: Type in Final[...] can only be omitted if there is an initializer\n    y: Final[int]\n    def __init__(self) -> None:\n        self.z: Final  # E: Type in Final[...] can only be omitted if there is an initializer\n\nreveal_type(x)  # N: Revealed type is \"Any\"\nreveal_type(C.x)  # N: Revealed type is \"Any\"\nv: C\nreveal_type(v.z)  # N: Revealed type is \"Any\"\n[out]\n\n[case testFinalDefiningFunc]\nfrom typing import final\n\n@final  # E: @final cannot be used with non-method functions\ndef f(x: int) -> None: ...\n[out]\n\n[case testFinalDefiningFuncOverloaded]\nfrom typing import final, overload\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: str) -> str: ...\n@final  # E: @final cannot be used with non-method functions\ndef f(x):\n    pass\n[out]\n\n[case testFinalDefiningMeth]\nfrom typing import final\n\nclass C:\n    @final\n    def f(self, x: int) -> None: ...\nreveal_type(C().f)  # N: Revealed type is \"def (x: builtins.int)\"\n[out]\n\n[case testFinalDefiningMethOverloaded]\nfrom typing import final, overload\n\nclass C:\n    @overload\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: str) -> str: ...\n    @final\n    def f(self, x):\n        pass\n\n    @overload\n    def bad(self, x: int) -> int: ...\n    @final  # E: @final should be applied only to overload implementation\n    @overload\n    def bad(self, x: str) -> str: ...\n    def bad(self, x):\n        pass\n\nreveal_type(C().f)  # N: Revealed type is \"Overload(def (x: builtins.int) -> builtins.int, def (x: builtins.str) -> builtins.str)\"\n[out]\n\n[case testFinalDefiningMethOverloadedStubs]\nfrom mod import C\n\nreveal_type(C().f)\n[file mod.pyi]\nfrom typing import final, overload\n\nclass C:\n    @final\n    @overload\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: str) -> str: ...\n\n    @overload\n    def bad(self, x: int) -> int: ...\n    @final  # Error!\n    @overload\n    def bad(self, x: str) -> str: ...\n[out]\ntmp/mod.pyi:12: error: In a stub file @final must be applied only to the first overload\nmain:3: note: Revealed type is \"Overload(def (x: builtins.int) -> builtins.int, def (x: builtins.str) -> builtins.str)\"\n\n[case testFinalDefiningProperty]\nfrom typing import final\n\nclass C:\n    @final\n    @property\n    def f(self) -> int: pass\n    @property\n    @final\n    def g(self) -> int: pass\nreveal_type(C().f)  # N: Revealed type is \"builtins.int\"\nreveal_type(C().g)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalDefiningOuterOnly]\nfrom typing import Final, Callable, Tuple, Any\nx: Tuple[Final]  # E: Final can be only used as an outermost qualifier in a variable annotation\ny: Callable[[], Tuple[Final[int]]]  # E: Final can be only used as an outermost qualifier in a variable annotation\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFinalDefiningNotInMethod]\nfrom typing import Final\n\ndef f(x: Final[int]) -> int: ...  # E: Final can be only used as an outermost qualifier in a variable annotation\ndef g(x: int) -> Final[int]: ...  # E: Final can be only used as an outermost qualifier in a variable annotation\n[out]\n\n[case testFinalDefiningNotInMethodExtensions]\n# flags: --python-version 3.14\nfrom typing_extensions import Final\n\ndef f(x: Final[int]) -> int: ...  # E: Final can be only used as an outermost qualifier in a variable annotation\ndef g(x: int) -> Final[int]: ...  # E: Final can be only used as an outermost qualifier in a variable annotation\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFinalDefiningNoRhs]\nfrom typing import Final\nx: Final  # E: Type in Final[...] can only be omitted if there is an initializer\ny: Final[int]  # E: Final name must be initialized with a value\nclass C:\n    x: Final  # E: Type in Final[...] can only be omitted if there is an initializer\n    y: Final[int]  # E: Final name must be initialized with a value\n    def __init__(self) -> None:\n        self.z: Final  # E: Type in Final[...] can only be omitted if there is an initializer\nreveal_type(x)  # N: Revealed type is \"Any\"\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\nreveal_type(C().x)  # N: Revealed type is \"Any\"\nreveal_type(C().y)  # N: Revealed type is \"builtins.int\"\nreveal_type(C().z)  # N: Revealed type is \"Any\"\n[out]\n\n[case testFinalDefiningNoRhsSubclass]\nfrom typing import Final\n\nclass A:\n    x: Final[int]  # E: Final name must be initialized with a value\n\nclass B(A):\n    x = 1  # E: Cannot assign to final name \"x\"\n    def __init__(self) -> None:\n        self.x = 1  # E: Cannot assign to final attribute \"x\"\n[out]\n\n[case testFinalDefiningNoTypevarsExplicit]\nfrom typing import Final, TypeVar, Generic, Tuple, Any\n\nT = TypeVar('T')\nd: Any\n\nclass C(Generic[T]):\n    x: Final[Tuple[T, T]] = d  # E: Final name declared in class body cannot depend on type variables\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFinalDefiningTypevarsImplicit]\nfrom typing import Final, TypeVar, Generic, Tuple, Any\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    def __init__(self, x: Tuple[T, T]) -> None:\n        self.x: Final = x\n        self.y: Final = 1\n\nreveal_type(C((1, 2)).x)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\nC.x  # E: Cannot access final instance attribute \"x\" on class object \\\n     # E: Access to generic instance variables via class is ambiguous\nC.y  # E: Cannot access final instance attribute \"y\" on class object\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFinalDefiningNotInOtherMethod]\nfrom typing import Final, Any, Tuple\n\nclass C:\n    def meth(self, x: Tuple[int, Any]) -> None:\n        self.x: Final = x  # E: Can only declare a final attribute in class body or __init__\n        self.y: Final[float] = 1  # E: Can only declare a final attribute in class body or __init__\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFinalDefiningOnlyOnSelf]\nfrom typing import Final, Any, Tuple\n\nclass U:\n    x: Any\n    y: Any\nclass C:\n    def __init__(self, x: Tuple[int, Any]) -> None:\n        slf = U()\n        slf.x: Final = x  # E: Final can be only applied to a name or an attribute on self\n        slf.y: Final[float] = 1  # E: Type cannot be declared in assignment to non-self attribute \\\n                                 # E: Final can be only applied to a name or an attribute on self\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFinalNotInProtocol]\nfrom typing import Final, final, Protocol, overload\n\nclass P(Protocol):\n    x: Final[float] = 1  # E: Protocol member cannot be final\n    @final  # E: Protocol member cannot be final\n    def meth(self, x) -> int:\n        pass\n    @overload\n    def other(self, x: int) -> int: ...\n    @overload\n    def other(self, x: str) -> str: ...\n    @final  # E: Protocol member cannot be final\n    def other(self, x):\n        pass\n[out]\n\n[case testFinalInProtocol]\nfrom typing import Final, Protocol, final\n\nclass P(Protocol):\n    var1 : Final[int] = 0 # E: Protocol member cannot be final\n\n    @final # E: Protocol member cannot be final\n    def meth1(self) -> None:\n        var2: Final = 0\n\n    def meth2(self) -> None:\n        var3: Final = 0\n\n    def meth3(self) -> None:\n        class Inner:\n            var3: Final = 0  # OK\n\n            @final\n            def inner(self) -> None: ...\n\n    class Inner:\n        var3: Final = 0  # OK\n\n        @final\n        def inner(self) -> None: ...\n\n[out]\n\n[case testFinalWithClassVarInProtocol]\nfrom typing import Protocol, Final, final, ClassVar\n\nclass P(Protocol):\n    var1 : Final[ClassVar[int]] = 0 # E: Variable should not be annotated with both ClassVar and Final\n    var2: ClassVar[int] = 1\n\n    @final # E: Protocol member cannot be final\n    def meth1(self) -> None:\n        ...\n\n    def meth2(self) -> None:\n        var3: Final[ClassVar[int]] = 0 # E: Variable should not be annotated with both ClassVar and Final # E: ClassVar can only be used for assignments in class body\n\n[out]\n\n[case testFinalNotInLoops]\nfrom typing import Final\n\nfor i in [1, 2, 3]:\n    x: Final = i  # E: Cannot use Final inside a loop\n\nwhile True:\n    y: Final = True  # E: Cannot use Final inside a loop\n[builtins fixtures/list.pyi]\n[out]\n\n[case testFinalDelayedDefinition]\nfrom typing import Final\n\nclass C:\n    x: Final[int]  # OK, defined in __init__\n    bad: Final[int]  # E: Final name must be initialized with a value\n\n    def __init__(self, x: int) -> None:\n        self.x = x  # OK, deferred definition\n        self.x = 2  # E: Cannot assign to final attribute \"x\"\n\n    def meth(self) -> None:\n        self.x = 2  # E: Cannot assign to final attribute \"x\"\n\nc: C\nc.x = 3  # E: Cannot assign to final attribute \"x\"\nclass D(C):\n    x = 4  # E: Cannot assign to final name \"x\"\nd: D\nd.x = 5  # E: Cannot assign to final attribute \"x\"\n[out]\n\n[case testFinalDelayedDefinitionOtherMethod]\nfrom typing import Final\n\nclass C:\n    x: Final[int]  # E: Final name must be initialized with a value\n\n    def meth(self) -> None:\n        self.x = 2  # E: Cannot assign to final attribute \"x\"\n[out]\n\n-- Reassignments\n\n[case testFinalReassignModuleVar]\n# flags: --allow-redefinition\nfrom typing import Final\n\nx: Final = 1\nx\nx = 2  # E: Cannot assign to final name \"x\"\ndef f() -> int:\n    global x\n    x = 3  # No error here is okay since we reported an error above\n    return x\n\nx2: Final = 1\nx2\ndef f2() -> None:\n    global x2\n    x2 = 1  # E: Cannot assign to final name \"x2\"\n\ny = 1\ny\ny: Final = 2  # E: Cannot redefine an existing name as final\ny = 3  # E: Cannot assign to final name \"y\"\n\nz: Final = 1\nz: Final = 2  # E: Cannot redefine an existing name as final\nz = 3  # E: Cannot assign to final name \"z\"\n\n[case testFinalReassignModuleVar2]\n# flags: --allow-redefinition\nfrom typing import Final\n\nx: Final = 1\nx\ndef f() -> int:\n    global x\n    x = 3  # E: Cannot assign to final name \"x\"\n    return x\n\ny = 1\ny\ny = 2\ny\ny: Final = 3  # E: Cannot redefine an existing name as final\n\n[case testFinalReassignModuleVar3]\n# flags: --disallow-redefinition\n# Error formatting is subtly different with new analyzer.\nfrom typing import Final\n\nx: Final = 1\nx\nx = 2  # E: Cannot assign to final name \"x\"\ndef f() -> int:\n    global x\n    x = 3  # E: Cannot assign to final name \"x\"\n    return x\n\nx2: Final = 1\nx2\ndef f2() -> None:\n    global x2\n    x2 = 1  # E: Cannot assign to final name \"x2\"\n\ny = 1 # E: Cannot assign to final name \"y\"\ny\ny: Final = 2  # E: Cannot redefine an existing name as final\ny = 3  # E: Cannot assign to final name \"y\"\n\nz: Final = 1\nz: Final = 2  # E: Cannot redefine an existing name as final\nz = 3  # E: Cannot assign to final name \"z\"\n\n[case testFinalReassignModuleReexport]\n\n# Error formatting is subtly different with the new analyzer.\nfrom typing import Final\n\nfrom lib import X\nfrom lib.mod import ID\n\nX = 1  # Error!\nID: Final = 1  # Two errors!\nID = 1  # Error!\n[file lib/__init__.pyi]\nfrom lib.const import X as X\n\n[file lib/mod.pyi]\nfrom lib.const import *\n\n[file lib/const.pyi]\nfrom typing import Final\n\nID: Final  # Error!\nX: Final[int]\n[out]\ntmp/lib/const.pyi:3: error: Type in Final[...] can only be omitted if there is an initializer\nmain:8: error: Cannot assign to final name \"X\"\nmain:9: error: Cannot redefine an existing name as final\nmain:10: error: Cannot assign to final name \"ID\"\n\n[case testFinalReassignFuncScope]\nfrom typing import Final\n\ndef f() -> None:\n    nl: Final = 0\n    x: Final = 1\n    x = 1  # E: Cannot assign to final name \"x\"\n\n    y: Final = 1\n    y: Final = 2  # E: Cannot redefine an existing name as final\n    def nested() -> None:\n        nonlocal nl\n        nl = 1  # E: Cannot assign to final name \"nl\"\n[out]\n\n[case testFinalReassignModuleVarExternal]\nimport mod\nmod.x = 2  # E: Cannot assign to final name \"x\"\n[file mod.pyi]\nfrom typing import Final\nx: Final[int]\n[out]\n\n[case testFinalReassignInstanceVarClassBody]\nfrom typing import Final\n\nclass C:\n    x: Final = 1\n    x = 2  # E: Cannot assign to final name \"x\"\n\n    y = 1  # E: Cannot assign to final name \"y\"\n    y: Final = 2  # E: Cannot redefine an existing name as final\n[out]\n\n[case testFinalReassignInstanceVarInit]\nfrom typing import Final\n\nclass C:\n    def __init__(self) -> None:\n        self.x: Final = 1\n        self.y = 1\n        self.y: Final = 2  # E: Cannot redefine an existing name as final\n    def meth(self) -> None:\n        self.x = 2  # E: Cannot assign to final attribute \"x\"\n[out]\n\n[case testFinalReassignInstanceVarClassVsInit]\n\nfrom typing import Final\n\nclass C:\n    y: Final = 1\n    def __init__(self) -> None:\n        # Methods are processed after top-level in new analyzer.\n        self.x: Final = 1  # E: Cannot redefine an existing name as final\n        self.y = 2  # E: Cannot assign to final attribute \"y\"\n    x = 2\n[out]\n\n[case testFinalReassignInstanceVarMethod]\nfrom typing import Final\n\nclass C:\n    x: Final = 1\n    def __init__(self) -> None:\n        self.y: Final = 1\n    def meth(self) -> None:\n        self.x = 2  # E: Cannot assign to final attribute \"x\"\n        self.y = 2  # E: Cannot assign to final attribute \"y\"\n    def other(self) -> None:\n        self.x = 2  # E: Cannot assign to final attribute \"x\"\n        self.y = 2  # E: Cannot assign to final attribute \"y\"\n    @classmethod\n    def cm(cls) -> None:\n        cls.x = 2  # E: Cannot assign to final attribute \"x\"\n        cls.y  # E: Cannot access final instance attribute \"y\" on class object\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testFinalReassignInstanceVarExternalClass]\nfrom typing import Final\n\nclass C:\n    x: Final = 1\n    def __init__(self) -> None:\n        self.y: Final = 1\n\nclass D(C): pass\n\nC.x = 2  # E: Cannot assign to final attribute \"x\"\nD.x = 2  # E: Cannot assign to final attribute \"x\"\nD.y = 2  # E: Cannot access final instance attribute \"y\" on class object \\\n         # E: Cannot assign to final attribute \"y\"\n[out]\n\n[case testFinalReassignInstanceVarExternalInstance]\nfrom typing import Final\n\nclass C:\n    x: Final = 1\n    def __init__(self) -> None:\n        self.y: Final = 1\n\nclass D(C): pass\n\nC().x = 2  # E: Cannot assign to final attribute \"x\"\nD().x = 2  # E: Cannot assign to final attribute \"x\"\nD().y = 2  # E: Cannot assign to final attribute \"y\"\n[out]\n\n[case testFinalWorksWithComplexTargets]\nfrom typing import Final, Any\n\ny: Final[Any] = 1\nx = a, (b, y), c = 2, (2, 2), 2  # E: Cannot assign to final name \"y\"\nt, *y, s = u = [2, 2, 2]  # E: Cannot assign to final name \"y\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testFinalInplaceAssign]\nfrom typing import Final\n\nclass A:  # no such things in fixtures\n    def __add__(self, other: A) -> A: ...\nclass B:\n    def __add__(self, other: B) -> B: ...\n    def __iadd__(self, other: B) -> B: ...\n\na: Final = A()\nb: Final = B()\nclass C:\n    a: Final = A()\n    b: Final = B()\nclass D(C):\n    pass\n\na += A()  # E: Cannot assign to final name \"a\"\nb += B()  # E: Cannot assign to final name \"b\"\nD().a += A()  # E: Cannot assign to final attribute \"a\"\nD().b += B()  # E: Cannot assign to final attribute \"b\"\n[out]\n\n-- Overriding\n\n[case testFinalOverridingVarClassBody]\nfrom typing import Final\n\n# We use properties in this tests and below because we want to check\n# that any existing variable before final doesn't affect logic of\n# subsequent overrides but writable attributes cannot be overridden by final.\nclass A:\n    @property\n    def x(self) -> int: ...\n    @property\n    def y(self) -> int: ...\n\nclass B(A):\n    x: Final = 1\n    def __init__(self) -> None:\n        self.y: Final = 1\nclass C(B):\n    x: int = 2  # E: Cannot assign to final name \"x\"\n    y: int = 2  # E: Cannot assign to final name \"y\"\n    x = 3  # E: Cannot assign to final name \"x\"\n    y = 3  # E: Cannot assign to final name \"y\"\nclass D(C):\n    pass\nD.x = 4  # E: Cannot assign to final attribute \"x\"\nD.y = 4  # E: Cannot assign to final attribute \"y\"\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalOverridingVarClassBodyExplicit]\nfrom typing import Final\n\nclass A:\n    @property\n    def x(self) -> int: ...\n    @property\n    def y(self) -> int: ...\nclass B(A):\n    x: Final = 1\n    def __init__(self) -> None:\n        self.y: Final = 1\nclass C(B):\n    x: Final = 2  # E: Cannot override final attribute \"x\" (previously declared in base class \"B\")\n    y: Final = 2  # E: Cannot override final attribute \"y\" (previously declared in base class \"B\")\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalOverridingVarInit]\nfrom typing import Final\n\nclass A:\n    @property\n    def x(self) -> int: ...\n    @property\n    def y(self) -> int: ...\nclass B(A):\n    x: Final = 1\n    def __init__(self) -> None:\n        self.y: Final = 1\nclass C(B):\n    def __init__(self) -> None:\n        self.x = 2  # E: Cannot assign to final attribute \"x\"\n        self.y = 2  # E: Cannot assign to final attribute \"y\"\n    def meth(self) -> None:\n        self.x = 3  # E: Cannot assign to final attribute \"x\"\n        self.y = 3  # E: Cannot assign to final attribute \"y\"\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalOverridingVarInit2]\nfrom typing import Final\n\nclass A:\n    @property\n    def x(self) -> int: ...\n    @property\n    def y(self) -> int: ...\nclass B(A):\n    x: Final = 1\n    def __init__(self) -> None:\n        self.y: Final = 1\nclass C(B):\n    def __init__(self) -> None:\n        self.x: Final = 2  # E: Cannot override final attribute \"x\" (previously declared in base class \"B\")\n        self.y: Final = 2  # E: Cannot override final attribute \"y\" (previously declared in base class \"B\")\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalOverridingVarOtherMethod]\nfrom typing import Final\n\nclass A:\n    @property\n    def x(self) -> int: ...\n    @property\n    def y(self) -> int: ...\nclass B(A):\n    x: Final = 1\n    def __init__(self) -> None:\n        self.y: Final = 1\nclass C(B):\n    def meth(self) -> None:\n        self.x: int = 2    # E: Cannot assign to final attribute \"x\"\n        self.y: int = 2    # E: Cannot assign to final attribute \"y\"\n\n        self.x = 3  # E: Cannot assign to final attribute \"x\"\n        self.y = 3  # E: Cannot assign to final attribute \"y\"\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalOverridingVarMultipleInheritanceClass]\nfrom typing import Final, Any\n\nclass A:\n    x: Final[Any] = 1\nclass B:\n    @property\n    def x(self) -> int: ...\nclass C(A, B): ...\nclass D(B, A): ...  # E: Cannot override final attribute \"x\" (previously declared in base class \"A\")\nC.x = 3  # E: Cannot assign to final attribute \"x\"\nC().x = 4  # E: Cannot assign to final attribute \"x\"\nD().x = 4  # E: Cannot assign to final attribute \"x\" \\\n           # E: Property \"x\" defined in \"B\" is read-only\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalOverridingVarMultipleInheritanceInit]\nfrom typing import Final, Any\n\nclass A:\n    def __init__(self) -> None:\n        self.x: Final[Any] = 1\nclass B:\n    @property\n    def x(self) -> int: ...\nclass C(A, B): ...\nclass D(B, A): ...  # E: Cannot override final attribute \"x\" (previously declared in base class \"A\")\nC.x = 3  # E: Cannot access final instance attribute \"x\" on class object \\\n         # E: Cannot assign to final attribute \"x\"\nC().x = 4  # E: Cannot assign to final attribute \"x\"\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalOverridingVarMultipleInheritanceMixed]\nfrom typing import Final\n\nclass A:\n    x: Final = 1\nclass B:\n    def __init__(self) -> None:\n        self.x = 2\nclass C(A, B): ...  # E: Cannot override writable attribute \"x\" with a final one\nclass D(B, A): ...  # E: Cannot override final attribute \"x\" (previously declared in base class \"A\")\nC.x = 3  # E: Cannot assign to final attribute \"x\"\nD.x = 3  # E: Cannot assign to final attribute \"x\"\nC().x = 4  # E: Cannot assign to final attribute \"x\"\nD().x = 4  # E: Cannot assign to final attribute \"x\"\n[out]\n\n[case testFinalOverridingVarWithMethod]\nfrom typing import Final, Any\n\nclass A:\n    x: Final[Any] = 1\n    def __init__(self) -> None:\n        self.y: Final[Any] = 1\n\nclass B(A):\n    def x(self) -> None: pass  # E: Cannot override final attribute \"x\" (previously declared in base class \"A\")\n    def y(self) -> None: pass  # E: Cannot override final attribute \"y\" (previously declared in base class \"A\")\n\nclass C(A):\n    @property  # E: Cannot override final attribute \"x\" (previously declared in base class \"A\")\n    def x(self) -> None: pass\n    @property  # E: Cannot override final attribute \"y\" (previously declared in base class \"A\")\n    def y(self) -> None: pass\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalOverridingVarWithMethodClass]\nfrom typing import Final, Any\n\nclass A:\n    x: Final[Any] = 1\n    def __init__(self) -> None:\n        self.y: Final[Any] = 1\n\nclass B(A):\n    @classmethod  # E: Cannot override final attribute \"x\" (previously declared in base class \"A\")\n    def x(self) -> None: pass\n    @classmethod  # E: Cannot override final attribute \"y\" (previously declared in base class \"A\")\n    def y(self) -> None: pass\n\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testFinalOverridingMethodRegular]\nfrom typing import final\n\nclass B:\n    @final\n    def meth(self) -> None: ...\nclass C(B):\n    def meth(self) -> None: ...  # E: Cannot override final attribute \"meth\" (previously declared in base class \"B\")\n[out]\n\n[case testFinalOverridingMethodInitNew]\nfrom typing import final\n\nclass B:\n    @final\n    def __init__(self) -> None: ...\n    @final\n    def __new__(cls) -> B: ...\nclass C(B):\n    def __init__(self) -> None: ...  # E: Cannot override final attribute \"__init__\" (previously declared in base class \"B\")\n    def __new__(cls) -> C: ...  # E: Cannot override final attribute \"__new__\" (previously declared in base class \"B\")\n[out]\n\n[case testFinalOverridingMethodWithVar]\nfrom typing import final, Final, Any\n\na: Any\n\nclass A:\n    @final\n    def f(self) -> None: pass\n    @final\n    @property\n    def p(self) -> int: pass\n\nclass B(A):\n    f = a  # E: Cannot override final attribute \"f\" (previously declared in base class \"A\")\n    p = a  # E: Cannot override final attribute \"p\" (previously declared in base class \"A\")\nclass C(A):\n    f: Any  # E: Cannot override final attribute \"f\" (previously declared in base class \"A\")\n    p: Any  # E: Cannot override final attribute \"p\" (previously declared in base class \"A\")\nclass D(A):\n    f: Final = a  # E: Cannot override final attribute \"f\" (previously declared in base class \"A\")\n    p: Final = a  # E: Cannot override final attribute \"p\" (previously declared in base class \"A\")\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalOverridingMethodWithVarImplicit]\nfrom typing import final, Any, Final\n\na: Any\n\nclass A:\n    @final\n    def f(self) -> None: pass\n    @final\n    @classmethod\n    def c(cls) -> int: pass\n\nclass B(A):\n    def __init__(self) -> None:\n        self.f: Any  # E: Cannot assign to final attribute \"f\" \\\n                     # E: Cannot override final attribute \"f\" (previously declared in base class \"A\")\n        self.c: Any  # E: Cannot assign to final attribute \"c\" \\\n                     # E: Cannot override final attribute \"c\" (previously declared in base class \"A\")\n\nB().f = a  # E: Cannot assign to final attribute \"f\"\nB().c = a  # E: Cannot assign to final attribute \"c\"\n\nclass C(A):\n    def __init__(self) -> None:\n        self.f: Final = a  # E: Cannot override final attribute \"f\" (previously declared in base class \"A\")\n        self.c: Final = a  # E: Cannot override final attribute \"c\" (previously declared in base class \"A\")\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testFinalCanOverrideMethodWithFinal]\nfrom typing import final\n\nclass B:\n    def meth(self) -> None: ...\nclass C(B):\n    @final  # OK\n    def meth(self) -> None: ...\n[out]\n\n[case testFinalOverridingMethodMultipleInheritance]\nfrom typing import final\n\nclass A:\n    def m(self) -> int: pass\nclass B:\n    @final\n    def m(self) -> int: pass\n\nclass C(A, B): pass  # E: Cannot override final attribute \"m\" (previously declared in base class \"B\")\nclass D(B, A): pass\n[out]\n\n[case testFinalOverridingMethodMultipleInheritanceVar]\nfrom typing import final, Any\n\nclass A:\n    m: Any\nclass B:\n    @final\n    def m(self) -> int: pass\n\nclass C(A, B): pass  # E: Cannot override final attribute \"m\" (previously declared in base class \"B\")\nclass D(B, A): pass  # E: Cannot override writable attribute \"m\" with a final one\n[out]\n\n[case testFinalOverridingClassMethod]\nfrom typing import final\n\nclass B:\n    @classmethod\n    @final\n    def f(cls) -> int: pass\n\nclass C(B):\n    @classmethod  # E: Cannot override final attribute \"f\" (previously declared in base class \"B\")\n    def f(cls) -> int: pass\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testFinalOverridingStaticMethod]\nfrom typing import final\n\nclass B:\n    @staticmethod\n    @final\n    def f() -> int: pass\n    @final\n    @staticmethod\n    def g() -> int: pass\n\nclass C(B):\n    @staticmethod  # E: Cannot override final attribute \"f\" (previously declared in base class \"B\")\n    def f() -> int: pass\n    @staticmethod  # E: Cannot override final attribute \"g\" (previously declared in base class \"B\")\n    def g() -> int: pass\n[builtins fixtures/staticmethod.pyi]\n[out]\n\n[case testFinalOverridingProperty]\nfrom typing import final\n\nclass B:\n    @final\n    @property\n    def f(self) -> int: pass\n    @property\n    @final\n    def g(self) -> int: pass\n\nclass C(B):\n    @property  # E: Cannot override final attribute \"f\" (previously declared in base class \"B\")\n    def f(self) -> int: pass\n    @property  # E: Cannot override final attribute \"g\" (previously declared in base class \"B\")\n    def g(self) -> int: pass\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalOverridingMethodOverloads]\nfrom typing import final, overload\n\nclass B:\n    @overload\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: str) -> str: ...\n    @final\n    def f(self, x):\n        pass\n\nclass C(B):\n    @overload  # E: Cannot override final attribute \"f\" (previously declared in base class \"B\")\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: str) -> str: ...\n    def f(self, x):\n        pass\n[out]\n\n[case testFinalClassNoInheritance]\nfrom typing import final\n\n@final\nclass B: ...\nclass C(B):  # E: Cannot inherit from final class \"B\"\n    pass\nclass D(C):  # E: Cannot inherit from final class \"B\"\n    pass\n[out]\n\n[case testFinalClassNoInheritanceMulti]\nfrom typing import final\n\nclass A: ...\n@final\nclass B: ...\nclass C(B, A):  # E: Cannot inherit from final class \"B\"\n    pass\nclass D(A, B):  # E: Cannot inherit from final class \"B\"\n    pass\n[out]\n\n[case testFinalCantOverrideWriteable]\nfrom typing import Any, Final, final\n\nclass B:\n    x: Any\n    @property\n    def y(self) -> Any: ...\n    @y.setter\n    def y(self, x: Any) -> None: ...\n\nclass C(B):\n    x: Final = 1  # E: Cannot override writable attribute \"x\" with a final one\n    y: Final = 1  # E: Cannot override writable attribute \"y\" with a final one\n\nclass D(B):\n    @final  # E: Cannot override writable attribute \"x\" with a final one\n    def x(self) -> int: ...\n    @final  # E: Cannot override writable attribute \"y\" with a final one\n    def y(self) -> int: ...\n[builtins fixtures/property.pyi]\n[out]\n\n[case testFinalCanUseTypingExtensions]\nfrom typing_extensions import final, Final\n\nx: Final = 1\nx = 2  # E: Cannot assign to final name \"x\"\n\nclass S:\n    x: Final = 1\nS.x = 2  # E: Cannot assign to final attribute \"x\"\n\nclass B:\n    @final\n    def meth(self) -> None: ...\nclass C(B):\n    def meth(self) -> None: ...  # E: Cannot override final attribute \"meth\" (previously declared in base class \"B\")\n\n@final\nclass F: ...\nclass E(F): ...  # E: Cannot inherit from final class \"F\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFinalCanUseTypingExtensionsAliased]\nfrom typing_extensions import final as f, Final as F\n\nx: F = 1\nx = 2  # E: Cannot assign to final name \"x\"\n\nclass S:\n    x: F = 1\nS.x = 2  # E: Cannot assign to final attribute \"x\"\n\nclass B:\n    @f\n    def meth(self) -> None: ...\nclass C(B):\n    def meth(self) -> None: ...  # E: Cannot override final attribute \"meth\" (previously declared in base class \"B\")\n\n@f\nclass D(C): ...\nclass E(D): ...  # E: Cannot inherit from final class \"D\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testFinalMultiassignAllowed]\nfrom typing import Final\n\nclass A:\n    x: Final[int]\n    y: Final[int]\n    def __init__(self) -> None:\n        self.x, self.y = 1, 2\n\nclass B:\n    x: Final[int]\n    y: Final[int]\n    def __init__(self) -> None:\n        self.x = self.y = 1\n[out]\n\n[case testFinalInDeferredMethod]\nfrom typing import Final\n\nclass A:\n    def __init__(self) -> None:\n        self.x = 10  # type: Final\n        undefined  # type: ignore\n[builtins fixtures/tuple.pyi]\n\n[case testFinalUsedWithClassVar]\n# flags: --python-version 3.12\nfrom typing import Final, ClassVar\n\nclass A:\n    a: Final[ClassVar[int]]  # E: Variable should not be annotated with both ClassVar and Final\n    b: ClassVar[Final[int]]  # E: Final can be only used as an outermost qualifier in a variable annotation\n    c: ClassVar[Final] = 1  # E: Final can be only used as an outermost qualifier in a variable annotation\n[out]\n\n[case testFinalUsedWithClassVarAfterPy313]\n# flags: --python-version 3.13\nfrom typing import Final, ClassVar\n\nclass A:\n    a: Final[ClassVar[int]] = 1\n    b: ClassVar[Final[int]] = 1\n    c: ClassVar[Final] = 1\n\n[case testFinalClassWithAbstractMethod]\nfrom typing import final\nfrom abc import ABC, abstractmethod\n\n@final\nclass A(ABC): # E: Final class __main__.A has abstract attributes \"B\"\n    @abstractmethod\n    def B(self) -> None: ...\n\n[case testFinalDefiningFuncWithAbstractMethod]\nfrom typing import final\nfrom abc import ABC, abstractmethod\n\nclass A(ABC):\n    @final # E: Method B is both abstract and final\n    @abstractmethod\n    def B(self) -> None: ...\n\n[case testFinalClassVariableRedefinitionDoesNotCrash]\n# This used to crash -- see #12950\nfrom typing import Final\n\nclass MyClass:\n    a: None\n    a: Final[int] = 1  # E: Cannot redefine an existing name as final  # E: Name \"a\" already defined on line 5\n\n[case testFinalOverrideAllowedForPrivate]\nfrom typing import Final, final\n\nclass Parent:\n    __foo: Final[int] = 0\n    @final\n    def __bar(self) -> None: ...\n\nclass Child(Parent):\n    __foo: Final[int] = 1\n    @final\n    def __bar(self) -> None: ...\n\n[case testFinalWithoutBool]\nfrom typing import Literal, final\n\nclass A:\n    pass\n\n@final\nclass B:\n    pass\n\n@final\nclass C:\n    def __len__(self) -> Literal[1]: return 1\n\nreveal_type(A() and 42)  # N: Revealed type is \"__main__.A | Literal[42]?\"\nreveal_type(B() and 42)  # N: Revealed type is \"Literal[42]?\"\nreveal_type(C() and 42)  # N: Revealed type is \"Literal[42]?\"\n\n[builtins fixtures/bool.pyi]\n\n[case testFinalWithoutBoolButWithLen]\nfrom typing import Literal, final\n\n# Per Python data model, __len__ is called if __bool__ does not exist.\n# In a @final class, __bool__ would not exist.\n\n@final\nclass A:\n    def __len__(self) -> int: ...\n\n@final\nclass B:\n    def __len__(self) -> Literal[1]: return 1\n\n@final\nclass C:\n    def __len__(self) -> Literal[0]: return 0\n\nreveal_type(A() and 42)  # N: Revealed type is \"__main__.A | Literal[42]?\"\nreveal_type(B() and 42)  # N: Revealed type is \"Literal[42]?\"\nreveal_type(C() and 42)  # N: Revealed type is \"__main__.C\"\n\n[builtins fixtures/bool.pyi]\n\n[case testCanAccessFinalClassInit]\nfrom typing import final\n\n@final\nclass FinalClass:\n    pass\n\ndef check_final_class() -> None:\n    new_instance = FinalClass()\n    new_instance.__init__()\n\nclass FinalInit:\n    @final\n    def __init__(self) -> None:\n        pass\n\ndef check_final_init() -> None:\n    new_instance = FinalInit()\n    new_instance.__init__()\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingOfFinalPersistsInFunctions]\nfrom typing import Final, Union\n\ndef _init() -> Union[int, None]:\n    return 0\n\nFOO: Final = _init()\n\nclass Example:\n\n    if FOO is not None:\n        reveal_type(FOO)  # N: Revealed type is \"builtins.int\"\n\n        def fn(self) -> int:\n            return FOO\n\nif FOO is not None:\n    reveal_type(FOO)  # N: Revealed type is \"builtins.int\"\n\n    def func() -> int:\n        return FOO\n\n[case testDisjointBase]\nfrom typing_extensions import disjoint_base\n\n@disjoint_base\nclass Disjoint1: pass\n\n@disjoint_base\nclass Disjoint2: pass\n\n@disjoint_base\nclass DisjointChild(Disjoint1): pass\n\nclass C1: pass\nclass C2(Disjoint1, C1): pass\nclass C3(DisjointChild, Disjoint1): pass\n\nclass C4(Disjoint1, Disjoint2):  # E: Class \"C4\" has incompatible disjoint bases\n    pass\n\nclass C5(Disjoint2, Disjoint1):  # E: Class \"C5\" has incompatible disjoint bases\n    pass\n\nclass C6(Disjoint2, DisjointChild):  # E: Class \"C6\" has incompatible disjoint bases\n    pass\n\nclass C7(DisjointChild, Disjoint2):  # E: Class \"C7\" has incompatible disjoint bases\n    pass\n\nclass C8(DisjointChild, Disjoint1, Disjoint2):  # E: Class \"C8\" has incompatible disjoint bases\n    pass\n\nclass C9(C2, Disjoint2):  # E: Class \"C9\" has incompatible disjoint bases\n    pass\n\nclass C10(C3, Disjoint2):  # E: Class \"C10\" has incompatible disjoint bases\n    pass\n\n[builtins fixtures/tuple.pyi]\n[case testDisjointBaseSlots]\nclass S1:\n    __slots__ = (\"a\",)\n\nclass S2:\n    __slots__ = (\"b\",)\n\nclass S3:\n    __slots__ = ()\n\nclass S4(S1):\n    __slots__ = (\"c\",)\n\nclass S5(S1, S2):  # E: Class \"S5\" has incompatible disjoint bases\n    pass\n\nclass S6(S1, S3): pass  # OK\nclass S7(S3, S1): pass  # OK\n\nclass S8(S4, S1): pass  # OK\n\nclass S9(S2, S4):  # E: Class \"S9\" has incompatible disjoint bases\n    pass\n\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-flags.test",
    "content": "[case testUnannotatedFunction]\n# flags: --disallow-untyped-defs\ndef f(x): pass\n[out]\nmain:2: error: Function is missing a type annotation\n\n[case testUnannotatedArgument]\n# flags: --disallow-untyped-defs\ndef f(x) -> int: pass\n[out]\nmain:2: error: Function is missing a type annotation for one or more parameters\n\n[case testNoArgumentFunction]\n# flags: --disallow-untyped-defs\ndef f() -> int: pass\n[out]\n\n[case testUnannotatedReturn]\n# flags: --disallow-untyped-defs\ndef f(x: int): pass\n[out]\nmain:2: error: Function is missing a return type annotation\n\n[case testUnannotatedReturnWithFastParser]\n# flags: --disallow-untyped-defs\ndef f(x: int): pass\n[out]\nmain:2: error: Function is missing a return type annotation\n\n[case testLambda]\n# flags: --disallow-untyped-defs\nlambda x: x\n[out]\n\n[case testUntypedDef]\n# flags: --disallow-untyped-defs\ndef f():\n    1 + \"str\"\n[out]\nmain:2: error: Function is missing a return type annotation\nmain:2: note: Use \"-> None\" if function does not return a value\n\n[case testUnannotatedReturnWithOnlySelfArgument]\n# flags: --disallow-untyped-defs\ndef f(self): pass\n[out]\nmain:2: error: Function is missing a return type annotation\nmain:2: note: Use \"-> None\" if function does not return a value\n\n[case testUnannotatedReturnWithNontrivialReturn]\n# flags: --disallow-untyped-defs\ndef f(): return 1\n[out]\nmain:2: error: Function is missing a return type annotation\n\n[case testUntypedAsyncDef]\n# flags: --disallow-untyped-defs\nasync def f():  # E: Function is missing a return type annotation \\\n                # N: Use \"-> None\" if function does not return a value\n    pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testAsyncUnannotatedArgument]\n# flags: --disallow-untyped-defs\nasync def f(x) -> None:  # E: Function is missing a type annotation for one or more parameters\n    pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testAsyncUnannotatedReturn]\n# flags: --disallow-untyped-defs\nfrom typing import Any\nasync def f(x: int):  # E: Function is missing a return type annotation\n    pass\n# Make sure explicit Any is allowed.\nasync def g(x: int) -> Any:\n    pass\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testDisallowUntypedDefsAndGeneric]\n# flags: --disallow-untyped-defs --disallow-any-generics\ndef get_tasks(self):\n    return 'whatever'\n[out]\nmain:2: error: Function is missing a return type annotation\n\n[case testDisallowUntypedDefsUntypedDecorator]\n# flags: --disallow-untyped-decorators\ndef d(p):\n    return p\n\n@d  # E: Untyped decorator makes function \"f\" untyped\ndef f(i: int) -> int:\n    return i\n\n[case testDisallowUntypedDecoratorsUnresolvedDecorator]\n# flags: --disallow-untyped-decorators --ignore-missing-imports\nfrom nonexistent import d\n\n@d  # E: Untyped decorator makes function \"f\" untyped\ndef f(i: int) -> int:\n    return i\n\n[case testDisallowUntypedDecoratorUntypedDef]\n# flags: --disallow-untyped-decorators\n\ndef d(p):\n    return p\n\n@d  # no error\ndef f(): pass\n\n[case testDisallowUntypedDecoratorsPartialFunction]\n# flags: --disallow-untyped-decorators\n\ndef d(p):\n    return p\n\n@d  # E: Untyped decorator makes function \"f\" untyped\ndef f(x) -> None: pass\n\n@d  # E: Untyped decorator makes function \"g\" untyped\ndef g(x, y: int): pass\n\n@d  # E: Untyped decorator makes function \"h\" untyped\ndef h(x: int): pass\n\n[case testDisallowUntypedDecoratorsImpreciseDecorator]\n# flags: --disallow-untyped-decorators\nfrom typing import Any\n\ndef d(p) -> Any:\n    return p\n\n@d  # no error\ndef f() -> None: pass\n\n[case testDisallowUntypedDecoratorsMultipleDecorators]\n# flags: --disallow-untyped-decorators\nfrom typing import Any\n\ndef d1(p):\n    return p\ndef d2(p):\n    return p\ndef d3(p) -> Any:\n    return p\n\n@d1  # E: Untyped decorator makes function \"f\" untyped\n@d2  # E: Untyped decorator makes function \"f\" untyped\n@d3  # no error\n@d1  # E: Untyped decorator makes function \"f\" untyped\ndef f() -> None: pass\n\n[case testDisallowUntypedDecoratorsCallableInstance]\n# flags: --disallow-untyped-decorators\nfrom typing import Callable\n\nclass TypedDecorator:\n    def __call__(self, c: Callable) -> Callable:\n        return function\n\nclass UntypedDecorator:\n    def __call__(self, c):\n        return function\n\n@TypedDecorator()\ndef f() -> None: pass\n\n@UntypedDecorator()  # E: Untyped decorator makes function \"g\" untyped\ndef g() -> None: pass\n\n@TypedDecorator()\n@UntypedDecorator()  # E: Untyped decorator makes function \"h\" untyped\ndef h() -> None: pass\n\n@UntypedDecorator()  # E: Untyped decorator makes function \"i\" untyped\n@TypedDecorator()\ndef i() -> None: pass\n\nreveal_type(f)  # N: Revealed type is \"def (*Any, **Any) -> Any\"\nreveal_type(g)  # N: Revealed type is \"Any\"\nreveal_type(h)  # N: Revealed type is \"def (*Any, **Any) -> Any\"\nreveal_type(i)  # N: Revealed type is \"Any\"\n\n[case testDisallowUntypedDecoratorsCallableInstanceDecoratedCall]\n# flags: --disallow-untyped-decorators\nfrom typing import Callable, TypeVar\n\nC = TypeVar('C', bound=Callable)\n\ndef typed_decorator(c: C) -> C:\n    return c\n\ndef untyped_decorator(c):\n    return c\n\nclass TypedDecorator:\n    @typed_decorator\n    def __call__(self, c: Callable) -> Callable:\n        return function\n\nclass UntypedDecorator1:\n    @untyped_decorator\n    def __call__(self, c):\n        return function\n\nclass UntypedDecorator2:\n    @untyped_decorator  # E: Untyped decorator makes function \"__call__\" untyped\n    def __call__(self, c: Callable) -> Callable:\n        return function\n\nclass UntypedDecorator3:\n    @typed_decorator\n    @untyped_decorator  # E: Untyped decorator makes function \"__call__\" untyped\n    def __call__(self, c: Callable) -> Callable:\n        return function\n\nclass UntypedDecorator4:\n    @untyped_decorator  # E: Untyped decorator makes function \"__call__\" untyped\n    @typed_decorator\n    def __call__(self, c: Callable) -> Callable:\n        return function\n\n@TypedDecorator()\ndef f() -> None: pass\n\n@UntypedDecorator1()  # E: Untyped decorator makes function \"g1\" untyped\ndef g1() -> None: pass\n\n@UntypedDecorator2()  # E: Untyped decorator makes function \"g2\" untyped\ndef g2() -> None: pass\n\n@UntypedDecorator3()  # E: Untyped decorator makes function \"g3\" untyped\ndef g3() -> None: pass\n\n@UntypedDecorator4()  # E: Untyped decorator makes function \"g4\" untyped\ndef g4() -> None: pass\n\nreveal_type(f)  # N: Revealed type is \"def (*Any, **Any) -> Any\"\nreveal_type(g1)  # N: Revealed type is \"Any\"\nreveal_type(g2)  # N: Revealed type is \"Any\"\nreveal_type(g3)  # N: Revealed type is \"Any\"\nreveal_type(g4)  # N: Revealed type is \"Any\"\n[builtins fixtures/bool.pyi]\n\n[case testDisallowUntypedDecoratorsNonCallableInstance]\n# flags: --disallow-untyped-decorators\nclass Decorator:\n    pass\n\n@Decorator()  # E: \"Decorator\" not callable\ndef f() -> None: pass\n\n[case testSubclassingAny]\n# flags: --disallow-subclassing-any\nfrom typing import Any\nFakeClass = None  # type: Any\nclass Foo(FakeClass): pass  # E: Class cannot subclass \"FakeClass\" (has type \"Any\")\n[out]\n\n[case testSubclassingAnyMultipleBaseClasses]\n# flags: --disallow-subclassing-any\nfrom typing import Any\nFakeClass = None  # type: Any\nclass ActualClass: pass\nclass Foo(ActualClass, FakeClass): pass  # E: Class cannot subclass \"FakeClass\" (has type \"Any\")\n[out]\n\n[case testSubclassingAnySilentImports]\n# flags: --disallow-subclassing-any --follow-imports=skip\n# cmd: mypy -m main\n\n[file main.py]\nfrom ignored_module import BaseClass\nclass Foo(BaseClass): pass\n\n[file ignored_module.py]\nclass BaseClass: pass\n\n[out]\ntmp/main.py:2: error: Class cannot subclass \"BaseClass\" (has type \"Any\")\n\n[case testSubclassingAnySilentImports2]\n# flags: --disallow-subclassing-any --follow-imports=skip\n# cmd: mypy -m main\n\n[file main.py]\nimport ignored_module\nclass Foo(ignored_module.BaseClass): pass\n\n[file ignored_module.py]\nclass BaseClass: pass\n\n[out]\ntmp/main.py:2: error: Class cannot subclass \"BaseClass\" (has type \"Any\")\n\n[case testWarnNoReturnIgnoresTrivialFunctions]\n# flags: --warn-no-return\ndef f() -> int:\n  pass\ndef g() -> int:\n  ...\ndef h() -> int:\n  \"\"\"with docstring\"\"\"\n  pass\ndef i() -> int:\n  \"\"\"with docstring\"\"\"\n  ...\ndef j() -> int:\n  u\"\"\"with unicode docstring\"\"\"\n  pass\ndef k() -> int:\n  \"\"\"docstring only\"\"\"\n\n[case testWarnNoReturnWorksWithAlwaysTrue]\n# flags: --warn-no-return\nPY3 = True\ndef f() -> int:\n    if PY3:\n        return 0\n    else:\n        return 0\n[builtins fixtures/bool.pyi]\n\n[case testWarnNoReturnWorksWithAlwaysFalse]\n# flags: --warn-no-return\nPY2 = False\ndef f() -> int:\n    if PY2:\n        return 0\n    else:\n        return 0\n[builtins fixtures/bool.pyi]\n\n[case testWarnNoReturnWorksWithMypyTrue]\n# flags: --warn-no-return\nMYPY = False\ndef f() -> int:\n    if MYPY:\n        return 0\n    else:\n        return 0\n[builtins fixtures/bool.pyi]\n\n[case testNoReturnDisallowsReturn]\n# flags: --warn-no-return\nfrom typing import NoReturn\n\ndef f() -> NoReturn:\n  if bool():\n    return 5  # E: Return statement in function which does not return\n  else:\n    return  # E: Return statement in function which does not return\n[builtins fixtures/dict.pyi]\n\n[case testNoReturnWithoutImplicitReturn]\n# flags: --warn-no-return\nfrom typing import NoReturn\n\ndef no_return() -> NoReturn: pass\ndef f() -> NoReturn:\n  no_return()\n[builtins fixtures/dict.pyi]\n\n[case testNoReturnDisallowsImplicitReturn]\n# flags: --warn-no-return\nfrom typing import NoReturn\n\ndef f() -> NoReturn:  # E: Implicit return in function which does not return\n  non_trivial_function = 1\n[builtins fixtures/dict.pyi]\n\n[case testNoReturnImplicitReturnCheckInDeferredNode]\n# flags: --warn-no-return\nfrom typing import NoReturn\n\ndef exit() -> NoReturn: ...\n\ndef force_forward_reference() -> int:\n    return 4\n\ndef f() -> NoReturn:\n    x\n    exit()\n\nx = force_forward_reference()\n[builtins fixtures/exception.pyi]\n\n[case testNoReturnNoWarnNoReturn]\n# flags: --warn-no-return\nfrom typing import NoReturn\n\ndef no_return() -> NoReturn: pass\ndef f() -> int:\n  if bool():\n    return 0\n  else:\n    no_return()\n[builtins fixtures/dict.pyi]\n\n[case testNoReturnInExpr]\n# flags: --warn-no-return\nfrom typing import NoReturn\n\ndef no_return() -> NoReturn: pass\ndef f() -> int:\n  return 0\nreveal_type(f() or no_return())  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n\n[case testNoReturnVariable]\n# flags: --warn-no-return\nfrom typing import NoReturn\n\nx = 0  # type: NoReturn  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Never\")\n[builtins fixtures/dict.pyi]\n\n[case testNoReturnAsync]\n# flags: --warn-no-return\nfrom typing import NoReturn\n\nasync def f() -> NoReturn: ...\n\nasync def g() -> NoReturn:\n  await f()\n\nasync def h() -> NoReturn:  # E: Implicit return in function which does not return\n  # Purposely not evaluating coroutine\n  _ = f()\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testNoWarnNoReturn]\n# flags: --no-warn-no-return\nimport typing\n\ndef implicit_optional_return(arg) -> typing.Optional[str]:\n    if arg:\n        return \"false\"\n\ndef unsound_implicit_return(arg) -> str:  # E: Incompatible return value type (implicitly returns \"None\", expected \"str\")\n    if arg:\n        return \"false\"\n\ndef implicit_return_gen(arg) -> typing.Generator[int, None, typing.Optional[str]]:\n    yield 1\n\ndef unsound_implicit_return_gen(arg) -> typing.Generator[int, None, str]:  # E: Incompatible return value type (implicitly returns \"None\", expected \"str\")\n    yield 1\n[builtins fixtures/dict.pyi]\n\n[case testNoWarnNoReturnNoStrictOptional]\n# flags: --no-warn-no-return --no-strict-optional\nimport typing\n\ndef implicit_optional_return(arg) -> typing.Optional[str]:\n    if arg:\n        return \"false\"\n\ndef unsound_implicit_return(arg) -> str:\n    if arg:\n        return \"false\"\n\ndef implicit_return_gen(arg) -> typing.Generator[int, None, typing.Optional[str]]:\n    yield 1\n\ndef unsound_implicit_return_gen(arg) -> typing.Generator[int, None, str]:\n    yield 1\n[builtins fixtures/dict.pyi]\n\n[case testNoReturnImportFromTyping]\nfrom typing import NoReturn\n\ndef h() -> NoReturn:\n  if bool():\n    return 5  # E: Return statement in function which does not return\n  else:\n    return  # E: Return statement in function which does not return\n\ndef no_return() -> NoReturn: pass\ndef f() -> NoReturn:\n  no_return()\n\nx: NoReturn = 0 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Never\")\n[builtins fixtures/dict.pyi]\n\n[case testShowErrorContextFunction]\n# flags: --show-error-context\ndef f() -> None:\n  0 + \"\"\n[out]\nmain: note: In function \"f\":\nmain:3: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testShowErrorContextClass]\n# flags: --show-error-context\nclass A:\n  0 + \"\"\n[out]\nmain: note: In class \"A\":\nmain:3: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testShowErrorContextMember]\n# flags: --show-error-context\nclass A:\n  def f(self, x: int) -> None:\n    self.f(\"\")\n[out]\nmain: note: In member \"f\" of class \"A\":\nmain:4: error: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\n[case testShowErrorContextModule]\n# flags: --show-error-context\nimport m\n[file m.py]\n0 + \"\"\n[out]\nmain:2: note: In module imported here:\ntmp/m.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testShowErrorContextTopLevel]\n# flags: --show-error-context\ndef f() -> None:\n  0 + \"\"\n0 + \"\"\n[out]\nmain: note: In function \"f\":\nmain:3: error: Unsupported operand types for + (\"int\" and \"str\")\nmain: note: At top level:\nmain:4: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testShowErrorContextFromHere]\n# flags: --show-error-context\nimport a\n[file a.py]\nimport b\n[file b.py]\n0 + \"\"\n[out]\ntmp/a.py:1: note: In module imported here,\nmain:2: note: ... from here:\ntmp/b.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testFollowImportsNormal]\n# flags: --follow-imports=normal\nfrom mod import x\nx + 0\nx + \"\"  # E: Unsupported operand types for + (\"int\" and \"str\")\nimport mod\nmod.x + 0\nmod.x + \"\"  # E: Unsupported operand types for + (\"int\" and \"str\")\nmod.y  # E: \"object\" has no attribute \"y\"\nmod + 0  # E: Unsupported left operand type for + (\"object\")\n[file mod.py]\n1 + \"\"  # E: Unsupported operand types for + (\"int\" and \"str\")\nx = 0\nx += \"\"  # E: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testFollowImportsSilent]\n# flags: --follow-imports=silent\nfrom mod import x\nx + \"\"  # E: Unsupported operand types for + (\"int\" and \"str\")\nimport mod\nmod.x + \"\"  # E: Unsupported operand types for + (\"int\" and \"str\")\nmod.y  # E: \"object\" has no attribute \"y\"\nmod + 0  # E: Unsupported left operand type for + (\"object\")\n[file mod.py]\n1 + \"\"\nx = 0\nx += \"\"\n\n[case testFollowImportsSilentTypeIgnore]\n# flags: --warn-unused-ignores --follow-imports=silent\nimport mod\n[file mod.py]\nx = 3  # type: ignore\n\n[case testFollowImportsSkip]\n# flags: --follow-imports=skip\nfrom mod import x\nreveal_type(x)  # N: Revealed type is \"Any\"\nx + \"\"\nimport mod\nreveal_type(mod.x)  # N: Revealed type is \"Any\"\n[file mod.py]\nthis deliberate syntax error will not be reported\n\n[case testFollowImportsError]\n# flags: --follow-imports=error\nfrom mod import x  # E: Import of \"mod\" ignored \\\n                   # N: (Using --follow-imports=error, module not passed on command line)\nx + \"\"\nreveal_type(x)  # N: Revealed type is \"Any\"\nimport mod\nreveal_type(mod.x) # N: Revealed type is \"Any\"\n[file mod.py]\ndeliberate syntax error\n\n[case testFollowImportsSelective]\n# flags: --config-file tmp/mypy.ini\nimport normal\nimport silent\nimport skip\nimport error  # E: Import of \"error\" ignored \\\n              # N: (Using --follow-imports=error, module not passed on command line)\nreveal_type(normal.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(silent.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(skip)  # N: Revealed type is \"Any\"\nreveal_type(error)  # N: Revealed type is \"Any\"\n[file mypy.ini]\n\\[mypy]\n\\[mypy-normal]\nfollow_imports = normal\n\\[mypy-silent]\nfollow_imports = silent\n\\[mypy-skip]\nfollow_imports = skip\n\\[mypy-error]\nfollow_imports = error\n[file normal.py]\nx = 0\nx += ''  # E: Unsupported operand types for + (\"int\" and \"str\")\n[file silent.py]\nx = 0\nx += ''\n[file skip.py]\nbla bla\n[file error.py]\nbla bla\n\n[case testFlagsFile]\n# flags: @tmp/flagsfile\nx: int\nFLAG = False\nif not FLAG:\n    x = \"unreachable\"\n[file flagsfile]\n----always-true=FLAG\n\n[case testConfigFile]\n# flags: --config-file tmp/mypy.ini\nx: int\nFLAG = False\nif not FLAG:\n    x = \"unreachable\"\n[file mypy.ini]\n\\[mypy]\nalways_true = FLAG\n\n[case testAltConfigFile]\n# flags: --config-file tmp/config.ini\nx: int\nFLAG = False\nif not FLAG:\n    x = \"unreachable\"\n[file config.ini]\n\\[mypy]\nalways_true = FLAG\n\n[case testMultipleGlobConfigSection]\n# flags: --config-file tmp/mypy.ini\nimport x, y, z\n[file mypy.ini]\n\\[mypy]\n\\[mypy-x.*,z.*]\ndisallow_untyped_defs = True\n[file x.py]\ndef f(a): pass  # E: Function is missing a type annotation\n[file y.py]\ndef f(a): pass\n[file z.py]\ndef f(a): pass  # E: Function is missing a type annotation\n\n[case testConfigMypyPath]\n# flags: --config-file tmp/mypy.ini\nimport no_stubs  # E: Cannot find implementation or library stub for module named \"no_stubs\" \\\n                 # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nfrom foo import foo\nfrom bar import bar\nfrom baz import baz\nbaz(bar(foo(42)))\nbaz(bar(foo('oof')))  # E: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\n[file mypy.ini]\n\\[mypy]\nmypy_path =\n    $MYPY_CONFIG_FILE_DIR/foo_dir:$MYPY_CONFIG_FILE_DIR/bar_dir\n    , $MYPY_CONFIG_FILE_DIR/baz_dir\n[file foo_dir/foo.pyi]\ndef foo(x: int) -> str: ...\n[file bar_dir/bar.pyi]\ndef bar(x: str) -> list: ...\n[file baz_dir/baz.pyi]\ndef baz(x: list) -> dict: ...\n\n[case testDisallowAnyGenericsBuiltinCollections]\n# flags: --config-file tmp/mypy.ini\nimport m\n[file mypy.ini]\n\\[mypy]\n\\[mypy-m]\ndisallow_any_generics = True\n[file m.py]\ndef j(s: set) -> None: pass  # E: Missing type arguments for generic type \"set\"\n[builtins fixtures/set.pyi]\n\n[case testDisallowAnyGenericsTypingCollections]\n# flags: --config-file tmp/mypy.ini\nimport m\n[file mypy.ini]\n\\[mypy]\n\\[mypy-m]\ndisallow_any_generics = True\n[file m.py]\nfrom typing import Set\ndef j(s: Set) -> None: pass  # E: Missing type arguments for generic type \"Set\"\n[builtins fixtures/set.pyi]\n\n[case testSectionInheritance]\n# flags: --config-file tmp/mypy.ini\nimport a, a.foo, a.b.c, a.b.c.d.e\n[file a/__init__.py]\n0()\n[file a/foo.py]\n0()\n[file a/b/__init__.py]\n[file a/b/c/__init__.py]\n0()\n[file a/b/c/d/__init__.py]\n[file a/b/c/d/e/__init__.py]\nfrom typing import List\ndef g(x: List) -> None: pass  # E: Missing type arguments for generic type \"List\"\ng(None)  # E: Argument 1 to \"g\" has incompatible type \"None\"; expected \"list[Any]\"\n[file mypy.ini]\n\\[mypy]\nallow_any_generics = True\nstrict_optional = False\n\\[mypy-a.*]\nignore_errors = True\n\\[mypy-a.b.*]\ndisallow_any_generics = True\nignore_errors = True\n\\[mypy-a.b.c.*]\nignore_errors = True\n\\[mypy-a.b.c.d.*]\nignore_errors = True\n\\[mypy-a.b.c.d.e.*]\nignore_errors = True\nstrict_optional = True\n\\[mypy-a.b.c.d.e]\nignore_errors = False\n\n[case testFollowImportStubs1]\n# flags: --config-file tmp/mypy.ini\nimport math  # E: Import of \"math\" ignored \\\n             # N: (Using --follow-imports=error, module not passed on command line)\nmath.frobnicate()\n[file mypy.ini]\n\\[mypy]\n\\[mypy-math.*]\nfollow_imports = error\nfollow_imports_for_stubs = True\n\n[case testFollowImportStubs2]\n# flags: --config-file tmp/mypy.ini\nimport math\nmath.frobnicate()\n[file mypy.ini]\n\\[mypy]\n\\[mypy-math.*]\nfollow_imports = skip\nfollow_imports_for_stubs = True\n\n[case testConfigUnstructuredGlob]\n# flags: --config-file tmp/mypy.ini\nimport emarg.foo, emarg.villip, emarg.hatch.villip.nus, emarg.hatch.villip.mankangulisk, foo.lol\n[file mypy.ini]\n\\[mypy]\nignore_errors = true\n\\[mypy-*.lol]\nignore_errors = false\n\\[mypy-emarg.*]\nignore_errors = false\n\\[mypy-emarg.*.villip.*]\nignore_errors = true\n\\[mypy-emarg.hatch.villip.mankangulisk]\nignore_errors = false\n[file emarg/__init__.py]\n[file emarg/foo.py]\nfail  # E: Name \"fail\" is not defined\n[file emarg/villip.py]\nfail\n[file emarg/hatch/__init__.py]\n[file emarg/hatch/villip/__init__.py]\n[file emarg/hatch/villip/nus.py]\nfail\n[file emarg/hatch/villip/mankangulisk.py]\nfail  # E: Name \"fail\" is not defined\n[file foo/__init__.py]\n[file foo/lol.py]\nfail  # E: Name \"fail\" is not defined\n\n[case testIgnoreMissingImportsFalse]\nfrom mod import x\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"mod\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testIgnoreMissingImportsTrue]\n# flags: --ignore-missing-imports\nfrom mod import x\n[out]\n\n[case testNoConfigFile]\n# flags: --config-file=\n# type: ignore\n\n[file mypy.ini]\n\\[mypy]\nwarn_unused_ignores = True\n[out]\n\n[case testPerFileIncompleteDefsBasic]\n# flags: --config-file tmp/mypy.ini\nimport standard, incomplete\n\n[file standard.py]\ndef incomplete(x) -> int:\n    return 0\n[file incomplete.py]\ndef incomplete(x) -> int:  # E: Function is missing a type annotation for one or more parameters\n    return 0\n[file mypy.ini]\n\\[mypy]\ndisallow_incomplete_defs = False\n\\[mypy-incomplete]\ndisallow_incomplete_defs = True\n\n\n[case testPerFileIncompleteDefsBasicPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport standard, incomplete\n\n[file standard.py]\ndef incomplete(x) -> int:\n    return 0\n[file incomplete.py]\ndef incomplete(x) -> int:  # E: Function is missing a type annotation for one or more parameters\n    return 0\n[file pyproject.toml]\n\\[tool.mypy]\ndisallow_incomplete_defs = false\n\\[[tool.mypy.overrides]]\nmodule = 'incomplete'\ndisallow_incomplete_defs = true\n\n\n[case testPerFileStrictOptionalBasic]\n# flags: --config-file tmp/mypy.ini\nimport standard, optional\n\n[file standard.py]\nx = 0\nif int():\n    x = None\n[file optional.py]\nx = 0\nif int():\n    x = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\n[file mypy.ini]\n\\[mypy]\nstrict_optional = False\n\\[mypy-optional]\nstrict_optional = True\n\n\n[case testPerFileStrictOptionalBasicPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport standard, optional\n\n[file standard.py]\nx = 0\nif int():\n    x = None\n[file optional.py]\nx = 0\nif int():\n    x = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\n[file pyproject.toml]\n\\[tool.mypy]\nstrict_optional = false\n\\[[tool.mypy.overrides]]\nmodule = 'optional'\nstrict_optional = true\n\n\n[case testPerFileStrictOptionalBasicImportStandard]\n# flags: --config-file tmp/mypy.ini\nimport standard, optional\n\n[file standard.py]\nfrom typing import Optional\ndef f(x: int) -> None: pass\nan_int = 0  # type: int\noptional_int = None  # type: Optional[int]\nf(an_int)  # ints can be used as ints\nf(optional_int)  # optional ints can be used as ints in this file\n\n[file optional.py]\nimport standard\ndef f(x: int) -> None: pass\nstandard.an_int = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\nstandard.optional_int = None  # OK -- explicitly declared as optional\nf(standard.an_int)  # ints can be used as ints\nf(standard.optional_int)  # E: Argument 1 to \"f\" has incompatible type \"None\"; expected \"int\"\n\n[file mypy.ini]\n\\[mypy]\nstrict_optional = False\n\\[mypy-optional]\nstrict_optional = True\n\n\n[case testPerFileStrictOptionalBasicImportStandardPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport standard, optional\n\n[file standard.py]\nfrom typing import Optional\ndef f(x: int) -> None: pass\nan_int = 0  # type: int\noptional_int = None  # type: Optional[int]\nf(an_int)  # ints can be used as ints\nf(optional_int)  # optional ints can be used as ints in this file\n\n[file optional.py]\nimport standard\ndef f(x: int) -> None: pass\nstandard.an_int = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\nstandard.optional_int = None  # OK -- explicitly declared as optional\nf(standard.an_int)  # ints can be used as ints\nf(standard.optional_int)  # E: Argument 1 to \"f\" has incompatible type \"None\"; expected \"int\"\n\n[file pyproject.toml]\n\\[tool.mypy]\nstrict_optional = false\n\\[[tool.mypy.overrides]]\nmodule = 'optional'\nstrict_optional = true\n\n\n[case testPerFileStrictOptionalBasicImportOptional]\n# flags: --config-file tmp/mypy.ini\nimport standard, optional\n\n[file standard.py]\nimport optional\ndef f(x: int) -> None: pass\nf(optional.x)  # OK -- in non-strict Optional context\nf(optional.y)  # OK -- in non-strict Optional context\n\n[file optional.py]\nfrom typing import Optional\ndef f(x: int) -> None: pass\nx = 0  # type: Optional[int]\ny = None  # type: None\n\n[file mypy.ini]\n\\[mypy]\nstrict_optional = False\n\\[mypy-optional]\nstrict_optional = True\n\n\n[case testPerFileStrictOptionalBasicImportOptionalPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport standard, optional\n\n[file standard.py]\nimport optional\ndef f(x: int) -> None: pass\nf(optional.x)  # OK -- in non-strict Optional context\nf(optional.y)  # OK -- in non-strict Optional context\n\n[file optional.py]\nfrom typing import Optional\ndef f(x: int) -> None: pass\nx = 0  # type: Optional[int]\ny = None  # type: None\n\n[file pyproject.toml]\n\\[tool.mypy]\nstrict_optional = false\n\\[[tool.mypy.overrides]]\nmodule = 'optional'\nstrict_optional = true\n\n\n[case testPerFileStrictOptionalListItemImportOptional]\n# flags: --config-file tmp/mypy.ini\nimport standard, optional\n\n[file standard.py]\nimport optional\nfrom typing import List\ndef f(x: List[int]) -> None: pass\nf(optional.x)  # OK -- in non-strict Optional context\nf(optional.y)  # OK -- in non-strict Optional context\n\n[file optional.py]\nfrom typing import Optional, List\ndef f(x: List[int]) -> None: pass\nx = []  # type: List[Optional[int]]\ny = []  # type: List[int]\n\n[file mypy.ini]\n\\[mypy]\nstrict_optional = False\n\\[mypy-optional]\nstrict_optional = True\n[builtins fixtures/list.pyi]\n\n\n[case testPerFileStrictOptionalListItemImportOptionalPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport standard, optional\n\n[file standard.py]\nimport optional\nfrom typing import List\ndef f(x: List[int]) -> None: pass\nf(optional.x)  # OK -- in non-strict Optional context\nf(optional.y)  # OK -- in non-strict Optional context\n\n[file optional.py]\nfrom typing import Optional, List\ndef f(x: List[int]) -> None: pass\nx = []  # type: List[Optional[int]]\ny = []  # type: List[int]\n\n[file pyproject.toml]\n\\[tool.mypy]\nstrict_optional = false\n\\[[tool.mypy.overrides]]\nmodule = 'optional'\nstrict_optional = true\n\n[builtins fixtures/list.pyi]\n\n\n[case testPerFileStrictOptionalComplicatedList]\nfrom typing import Union, Optional, List\n\ndef f() -> None:\n    x = [] # type: Union[List[Optional[str]], str]\n[builtins fixtures/list.pyi]\n\n[case testPerFileStrictOptionalNoneArguments]\n# flags: --config-file tmp/mypy.ini\nimport standard, optional\n\n[file standard.py]\ndef f(x: int = None) -> None: pass\n\n[file optional.py]\nimport standard\ndef f(x: int = None) -> None: pass\nstandard.f(None)\n\n[file mypy.ini]\n\\[mypy]\nstrict_optional = False\nimplicit_optional = true\n\\[mypy-optional]\nstrict_optional = True\n\n\n[case testPerFileStrictOptionalNoneArgumentsPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport standard, optional\n\n[file standard.py]\ndef f(x: int = None) -> None: pass\n\n[file optional.py]\nimport standard\ndef f(x: int = None) -> None: pass\nstandard.f(None)\n\n[file pyproject.toml]\n\\[tool.mypy]\nstrict_optional = false\nimplicit_optional = true\n\\[[tool.mypy.overrides]]\nmodule = 'optional'\nstrict_optional = true\n\n[case testSilentMissingImportsOff]\n-- ignore_missing_imports is False by default.\nimport missing  # E: Cannot find implementation or library stub for module named \"missing\" \\\n                # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nreveal_type(missing.x)  # N: Revealed type is \"Any\"\n\n[case testSilentMissingImportsOn]\n# flags: --ignore-missing-imports\nimport missing\nreveal_type(missing.x)  # N: Revealed type is \"Any\"\n\n[case testDisallowImplicitTypesIgnoreMissingTypes]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom missing import MyType\n\ndef f(x: MyType) -> None:  # E: Argument 1 to \"f\" becomes \"Any\" due to an unfollowed import\n    pass\n\n[case testDisallowImplicitTypes]\n# flags: --disallow-any-unimported\nfrom missing import MyType\n\ndef f(x: MyType) -> None:\n    pass\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"missing\"\nmain:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:4: error: Argument 1 to \"f\" becomes \"Any\" due to an unfollowed import\n\n[case testDisallowImplicitAnyVariableDefinition]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom missing import Unchecked\n\nt: Unchecked = 12  # E: Type of variable becomes \"Any\" due to an unfollowed import\n\n[case testAllowImplicitAnyVariableDefinition]\n# flags: --ignore-missing-imports --allow-any-unimported\nfrom missing import Unchecked\n\nt: Unchecked = 12\n\n[case testDisallowImplicitAnyGeneric]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom missing import Unchecked\nfrom typing import List\n\ndef foo(l: List[Unchecked]) -> List[Unchecked]:\n    t = []  # type: List[Unchecked]\n    return l\n[builtins fixtures/list.pyi]\n[out]\nmain:5: error: Return type becomes \"list[Any]\" due to an unfollowed import\nmain:5: error: Argument 1 to \"foo\" becomes \"list[Any]\" due to an unfollowed import\nmain:6: error: Type of variable becomes \"list[Any]\" due to an unfollowed import\n\n[case testDisallowImplicitAnyInherit]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom missing import Unchecked\nfrom typing import List\n\nclass C(Unchecked): # E: Base type Unchecked becomes \"Any\" due to an unfollowed import\n    pass\n\nclass A(List[Unchecked]): # E: Base type becomes \"list[Any]\" due to an unfollowed import\n    pass\n[builtins fixtures/list.pyi]\n\n[case testDisallowImplicitAnyAlias]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom missing import Unchecked\nfrom typing import List\n\nX = List[Unchecked]  # E: Type alias target becomes \"list[Any]\" due to an unfollowed import\n\ndef f(x: X) -> None:\n    pass\n[builtins fixtures/list.pyi]\n\n[case testDisallowImplicitAnyCast]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom missing import Unchecked\nfrom typing import List, cast\n\n\nfoo = [1, 2, 3]\ncast(List[Unchecked], foo)  # E: Target type of cast becomes \"list[Any]\" due to an unfollowed import\ncast(Unchecked, foo)  # E: Target type of cast becomes \"Any\" due to an unfollowed import\n[builtins fixtures/list.pyi]\n\n[case testDisallowImplicitAnyNamedTuple]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom typing import List, NamedTuple\nfrom missing import Unchecked\n\nPoint = NamedTuple('Point', [('x', List[Unchecked]),\n                             ('y', Unchecked)])\n[builtins fixtures/list.pyi]\n[out]\nmain:5: error: NamedTuple type becomes \"tuple[list[Any], Any]\" due to an unfollowed import\n\n[case testDisallowImplicitAnyTypeVarConstraints]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom typing import List, NamedTuple, TypeVar, Any\nfrom missing import Unchecked\n\nT = TypeVar('T', Unchecked, List[Unchecked], str)\n[builtins fixtures/list.pyi]\n[out]\nmain:5: error: Constraint 1 becomes \"Any\" due to an unfollowed import\nmain:5: error: Constraint 2 becomes \"list[Any]\" due to an unfollowed import\n\n[case testDisallowImplicitAnyNewType]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom typing import NewType, List\nfrom missing import Unchecked\n\nBaz = NewType('Baz', Unchecked)  # E: Argument 2 to NewType(...) must be subclassable (got \"Any\")\nBar = NewType('Bar', List[Unchecked])  # E: Argument 2 to NewType(...) becomes \"list[Any]\" due to an unfollowed import\n\n[builtins fixtures/list.pyi]\n\n[case testDisallowImplicitAnyCallableAndTuple]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom typing import Callable, Tuple\nfrom missing import Unchecked\n\ndef foo(f: Callable[[], Unchecked]) -> Tuple[Unchecked]:\n    return f()\n[builtins fixtures/list.pyi]\n[out]\nmain:5: error: Return type becomes \"tuple[Any]\" due to an unfollowed import\nmain:5: error: Argument 1 to \"foo\" becomes \"Callable[[], Any]\" due to an unfollowed import\n\n[case testDisallowImplicitAnySubclassingExplicitAny]\n# flags: --ignore-missing-imports --disallow-any-unimported --disallow-subclassing-any\nfrom typing import Any\n\nclass C(Any): # E: Class cannot subclass \"Any\" (has type \"Any\")\n    pass\n\n[case testDisallowImplicitAnyVarDeclaration]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom missing import Unchecked\n\nfoo: Unchecked = \"\"\nfoo = \"\"\nx, y = 1, 2  # type: Unchecked, Unchecked\n[builtins fixtures/tuple.pyi]\n[out]\nmain:4: error: Type of variable becomes \"Any\" due to an unfollowed import\nmain:6: error: A type on this line becomes \"Any\" due to an unfollowed import\n\n[case testDisallowUnimportedAnyTypedDictSimple]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom typing import TypedDict\nfrom x import Unchecked\n\nM = TypedDict('M', {'x': str, 'y': Unchecked})  # E: Type of a TypedDict key becomes \"Any\" due to an unfollowed import\n\ndef f(m: M) -> M: pass  # no error\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDisallowUnimportedAnyTypedDictGeneric]\n# flags: --ignore-missing-imports --disallow-any-unimported\nfrom typing import List, TypedDict\nfrom x import Unchecked\n\nM = TypedDict('M', {'x': str, 'y': List[Unchecked]})  # E: Type of a TypedDict key becomes \"list[Any]\" due to an unfollowed import\n\ndef f(m: M) -> M: pass  # no error\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDisallowAnyDecoratedUnannotatedDecorator]\n# flags: --disallow-any-decorated\nfrom typing import Any\n\ndef d(f):\n    return f\n\n@d\ndef f(x: Any) -> Any:  # E: Function is untyped after decorator transformation\n    pass\n@d\ndef h(x):  # E: Function is untyped after decorator transformation\n    pass\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyDecoratedUnannotatedDecoratorDeferred1]\n# flags: --disallow-any-decorated\nfrom typing import Callable\n\ndef d(f: Callable[[int], None]) -> Callable[[int], None]:\n    return f\n\ndef wrapper() -> None:\n    if c:\n        @d\n        def h(x):\n            pass\n\nc = [1]\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyDecoratedUnannotatedDecoratorDeferred2]\n# flags: --disallow-any-decorated\nfrom typing import Callable\n\ndef d(f: Callable[[int], None]) -> Callable[[int], None]:\n    return f\n\nc = 1  # no deferral - check that the previous testcase is valid\n\ndef wrapper() -> None:\n    if c:\n        @d\n        def h(x):\n            pass\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyDecoratedErrorIsReportedOnlyOnce]\n# flags: --disallow-any-decorated\n\ndef d(f):\n    return f\n\ndef d2(f):\n    return f\n\n@d\n@d2\n@d\ndef f(x: int) -> None: pass  # E: Function is untyped after decorator transformation\n[case testDisallowAnyDecoratedReturnAny]\n# flags: --disallow-any-decorated\nfrom typing import Any\n\ndef d(f) -> Any:\n    return f\n\n@d\ndef f() -> None: pass  # E: Function is untyped after decorator transformation\n[builtins fixtures/list.pyi]\n[case testDisallowAnyDecoratedReturnCallable]\n# flags: --disallow-any-decorated\nfrom typing import Any, Callable\n\ndef d(f) -> Callable[..., None]:\n    return f\n\n@d\ndef g(i: int, s: str) -> None: pass  # E: Type of decorated function contains type \"Any\" (\"Callable[..., None]\")\n\n[builtins fixtures/list.pyi]\n[case testDisallowAnyDecoratedNonexistentDecorator]\n# flags: --disallow-any-decorated --ignore-missing-imports\nfrom nonexistent import d\n\n@d\ndef f() -> None: pass  # E: Function is untyped after decorator transformation\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyDecoratedPartlyTypedCallable]\n# flags: --disallow-any-decorated --ignore-missing-imports\nfrom typing import Callable, Any, List\n\ndef d(f) -> Callable[[int, Any], Any]: pass\ndef d2(f) -> Callable[[int], List[Any]]: pass\ndef d3(f) -> Callable[[Any], List[str]]: pass\n\n@d\ndef f(i: int, s: str) -> None:  # E: Type of decorated function contains type \"Any\" (\"Callable[[int, Any], Any]\")\n    pass\n@d2\ndef g(i: int) -> None:  # E: Type of decorated function contains type \"Any\" (\"Callable[[int], list[Any]]\")\n    pass\n@d3\ndef h(i: int) -> None:  # E: Type of decorated function contains type \"Any\" (\"Callable[[Any], list[str]]\")\n    pass\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyDecoratedReturnsCallableNoParams]\n# flags: --disallow-any-decorated\nfrom typing import Callable\n\ndef d(p) -> Callable[[], int]:\n    return p\n\n@d\ndef f(i):\n    return i\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyDecoratedDecoratorReturnsNonCallable]\n# flags: --disallow-any-decorated\ndef d(p) -> int:\n    return p(0)\n\n@d\ndef f(i):\n    return i\n\n[case testDisallowAnyDecoratedUntypedUndecoratedFunction]\n# flags: --disallow-any-decorated\nfrom typing import Callable\n\ndef f(i):  # no error\n    return i\n\n[case testDisallowAnyDecoratedTwoDecorators]\n# flags: --disallow-any-decorated\nfrom typing import Callable\n\ndef typed_dec(f) -> Callable[[], int]: pass\ndef untyped_dec(f): pass\n\n@typed_dec\n@untyped_dec\ndef f():  # no error\n    return i\n\n@untyped_dec\n@typed_dec\ndef g():  # E: Function is untyped after decorator transformation\n    return i\n\n[case testDisallowAnyExprSimple]\n# flags: --disallow-any-expr\nfrom typing import Any\ndef f(s):\n    yield s\n\ndef g(x) -> Any:\n    yield x  # E: Expression has type \"Any\"\n\nx = f(0)  # E: Expression has type \"Any\"\nfor x in f(0):  # E: Expression has type \"Any\"\n    g(x)  # E: Expression has type \"Any\"\n\nl = [1, 2, 3]\nl[f(0)]  # E: Expression has type \"Any\"\nf(l)\nf(f(0))  # E: Expression has type \"Any\"\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExprUnannotatedFunction]\n# flags: --disallow-any-expr\ndef g(s):\n    return s\n\ng(0)\nw: int = g(1)\n\n[case testDisallowAnyExprExplicitAnyParam]\n# flags: --disallow-any-expr\nfrom typing import Any, List\ndef f(s: Any) -> None:\n    pass\n\ndef g(s: List[Any]) -> None:\n    pass\n\nf(0)\n\n# type of list below is inferred with expected type of \"list[Any]\", so that becomes it's type\n# instead of list[str]\ng([''])  # E: Expression type contains \"Any\" (has type \"list[Any]\")\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExprAllowsAnyInCast]\n# flags: --disallow-any-expr\nfrom typing import Any, cast\nclass Foo:\n    g: Any = 2\n\nz = cast(int, Foo().g)\nm = cast(Any, Foo().g)  # E: Expression has type \"Any\"\nk = Foo.g  # E: Expression has type \"Any\"\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExprAllowsAnyInVariableAssignmentWithExplicitTypeAnnotation]\n# flags: --disallow-any-expr\nfrom typing import Any\nclass Foo:\n    g: Any = 2\n\nz: int = Foo().g\nx = Foo().g  # type: int\nm: Any = Foo().g  # E: Expression has type \"Any\"\nn = Foo().g  # type: Any  # E: Expression has type \"Any\"\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExprGeneric]\n# flags: --disallow-any-expr\nfrom typing import List\n\nl: List = []\nl.append(1)  # E: Expression type contains \"Any\" (has type \"list[Any]\")\nk = l[0]  # E: Expression type contains \"Any\" (has type \"list[Any]\")  # E: Expression has type \"Any\"\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExprTypeVar]\n# flags: --disallow-any-expr\nfrom typing import TypeVar\n\nT = TypeVar('T')  # no error\n\ndef f(t: T) -> T:\n    return t\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExprNamedTuple]\n# flags: --disallow-any-expr\nfrom typing import NamedTuple\n\nPoint = NamedTuple('Point', [('x', int), ('y', int)])  # no error\n\ndef origin() -> Point:\n    return Point(x=0, y=0)\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExprNewType]\n# flags: --disallow-any-expr\nfrom typing import NewType\n\nNT = NewType('NT', int)  # no error\n\ndef nt() -> NT:\n    return NT(1)\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExprEnum]\n# flags: --disallow-any-expr\nfrom enum import Enum\nE = Enum('E', '1, 2, 3')  # no error\n\ndef k(s: E) -> None: pass\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExprTypedDict]\n# flags: --disallow-any-expr\nfrom typing import TypedDict\n\nMovie = TypedDict('Movie', {'name': str, 'year': int})\n\ndef g(m: Movie) -> Movie:\n    return m\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDisallowIncompleteDefs]\n# flags: --disallow-incomplete-defs\n\ndef f(i: int):  # E: Function is missing a return type annotation\n    pass\ndef g(i) -> None:  # E: Function is missing a type annotation for one or more parameters\n    pass\ndef h(i: int) -> int:  # no error\n    return i\ndef i() -> None:  # no error\n    pass\n\n[case testDisallowIncompleteDefsNoReturn]\n# flags: --disallow-incomplete-defs --disallow-untyped-defs\n\ndef f(i: int):  # E: Function is missing a return type annotation\n    pass\n\n[case testDisallowIncompleteDefsSelf]\n# flags: --disallow-incomplete-defs\nclass C:\n    def foo(self) -> None:  # no error\n        pass\n\n[case testDisallowIncompleteDefsPartiallyAnnotatedParams]\n# flags: --disallow-incomplete-defs\n\ndef f(i: int, s):\n    pass\n\n[out]\nmain:3: error: Function is missing a return type annotation\nmain:3: error: Function is missing a type annotation for one or more parameters\n\n[case testDisallowIncompleteDefsAttrsNoAnnotations]\n# flags: --disallow-incomplete-defs\nimport attrs\n\n@attrs.define\nclass Unannotated:\n    foo = attrs.field()\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testDisallowIncompleteDefsAttrsWithAnnotations]\n# flags: --disallow-incomplete-defs\nimport attrs\n\n@attrs.define\nclass Annotated:\n    bar: int = attrs.field()\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testDisallowIncompleteDefsAttrsPartialAnnotations]\n# flags: --disallow-incomplete-defs\nimport attrs\n\n@attrs.define\nclass PartiallyAnnotated:  # E: Function is missing a type annotation for one or more parameters\n    bar: int = attrs.field()\n    baz = attrs.field()\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAlwaysTrueAlwaysFalseFlags]\n# flags: --always-true=YOLO --always-true=YOLO1 --always-false=BLAH1 --always-false BLAH --ignore-missing-imports\nfrom somewhere import YOLO, BLAH\nif not YOLO:\n    1+()\nif BLAH:\n    1+()\n[builtins fixtures/bool.pyi]\n\n[case testAlwaysTrueAlwaysFalseConfigFile]\n# flags: --config-file tmp/mypy.ini\nfrom somewhere import YOLO, BLAH\nif not YOLO:\n    1+()\nif BLAH:\n    1+()\n[file mypy.ini]\n\\[mypy]\nignore_missing_imports = True\nalways_true = YOLO1, YOLO\nalways_false = BLAH, BLAH1\n[builtins fixtures/bool.pyi]\n\n\n[case testAlwaysTrueAlwaysFalseConfigFilePyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nfrom somewhere import YOLO, BLAH\nif not YOLO:\n    1+()\nif BLAH:\n    1+()\n\n[file pyproject.toml]\n\\[tool.mypy]\nignore_missing_imports = true\nalways_true = ['YOLO1', 'YOLO']\nalways_false = ['BLAH', 'BLAH1']\n\n[builtins fixtures/bool.pyi]\n\n\n[case testDisableErrorCodeConfigFile]\n# flags: --config-file tmp/mypy.ini --disallow-untyped-defs\nimport foo\ndef bar():\n    pass\n[file mypy.ini]\n\\[mypy]\ndisable_error_code = import, no-untyped-def\n\n\n[case testDisableErrorCodeConfigFilePyProjectTOML]\n# flags: --config-file tmp/pyproject.toml --disallow-untyped-defs\nimport foo\ndef bar():\n    pass\n\n[file pyproject.toml]\n\\[tool.mypy]\ndisable_error_code = ['import', 'no-untyped-def']\n\n\n[case testCheckDisallowAnyGenericsNamedTuple]\n# flags: --disallow-any-generics\nfrom typing import NamedTuple\n\nN = NamedTuple('N', [('x', N)])  # type: ignore\nn: N\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCheckDisallowAnyGenericsTypedDict]\n# flags: --disallow-any-generics\nfrom typing import Dict, Any, Optional, TypedDict\n\nVarsDict = Dict[str, Any]\nHostsDict = Dict[str, Optional[VarsDict]]\n\nGroupDataDict = TypedDict(\n    \"GroupDataDict\", {\"children\": \"GroupsDict\",  # type: ignore\n                      \"vars\": VarsDict,\n                      \"hosts\": HostsDict}, total=False\n)\n\nGroupsDict = Dict[str, GroupDataDict]  # type: ignore\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n[case testCheckDisallowAnyGenericsStubOnly]\n# flags: --disallow-any-generics\nfrom asyncio import Future\nfrom queue import Queue\nx: Future[str]\ny: Queue[int]\n\np: Future  # E: Missing type arguments for generic type \"Future\"\nq: Queue  # E: Missing type arguments for generic type \"Queue\"\n[file asyncio/__init__.pyi]\nfrom asyncio.futures import Future as Future\n[file asyncio/futures.pyi]\nfrom typing import TypeVar, Generic\n_T = TypeVar('_T')\nclass Future(Generic[_T]): ...\n[file queue.pyi]\nfrom typing import TypeVar, Generic\n_T = TypeVar('_T')\nclass Queue(Generic[_T]): ...\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testDisallowAnyGenericsBuiltinTuple]\n# flags: --disallow-any-generics\ns = tuple([1, 2, 3])\ndef f(t: tuple) -> None: pass  # E: Missing type arguments for generic type \"tuple\"\n[builtins fixtures/tuple.pyi]\n\n[case testDisallowAnyGenericsBuiltinList]\n# flags: --disallow-any-generics\nl = list([1, 2, 3])\ndef f(t: list) -> None: pass  # E: Missing type arguments for generic type \"list\"\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyGenericsBuiltinSet]\n# flags: --disallow-any-generics\nl = set({1, 2, 3})\ndef f(s: set) -> None: pass  # E: Missing type arguments for generic type \"set\"\n[builtins fixtures/set.pyi]\n\n[case testDisallowAnyGenericsBuiltinDict]\n# flags: --disallow-any-generics\nl = dict([('a', 1)])\ndef f(d: dict) -> None: pass  # E: Missing type arguments for generic type \"dict\"\n[builtins fixtures/dict.pyi]\n\n[case testCheckDefaultAllowAnyGeneric]\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\nC = Callable[[], T]\n\ndef f(c: C):\n    pass\n[out]\n\n[case testCheckAllowAnyGenericAnyGeneric]\n# flags: --strict --allow-any-generics\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\nC = Callable[[], T]\n\ndef f(c: C) -> None:\n    pass\n[out]\n\n[case testCheckDisallowAnyGenericsAnyGeneric]\n# flags: --disallow-any-generics\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\nC = Callable[[], T]\n\ndef f(c: C):  # E: Missing type arguments for generic type \"C\"\n    pass\n\n[case testStrictAnyGeneric]\n# flags: --strict\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    pass\n\ndef f(c: A) -> None:  # E: Missing type arguments for generic type \"A\"\n    pass\n\n[case testStrictInConfigAnyGeneric]\n# flags: --config-file tmp/mypy.ini\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    pass\n\ndef f(c: A) -> None:  # E: Missing type arguments for generic type \"A\"\n    pass\n[file mypy.ini]\n\\[mypy]\nstrict = True\n\n\n[case testStrictInConfigAnyGenericPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    pass\n\ndef f(c: A) -> None:  # E: Missing type arguments for generic type \"A\"\n    pass\n\n[file pyproject.toml]\n\\[tool.mypy]\nstrict = true\n\n\n[case testStrictFalseInConfigAnyGeneric]\n# flags: --config-file tmp/mypy.ini\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    pass\n\ndef f(c: A) -> None:\n    pass\n[file mypy.ini]\n\\[mypy]\nstrict = False\n[out]\n\n\n[case testStrictFalseInConfigAnyGenericPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    pass\n\ndef f(c: A) -> None:\n    pass\n\n[file pyproject.toml]\n\\[tool.mypy]\nstrict = false\n\n[out]\n\n\n[case testStrictAndStrictEquality]\n# flags: --strict\nx = 0\ny = ''\nif x == y:  # E: Non-overlapping equality check (left operand type: \"int\", right operand type: \"str\")\n    int()\n[builtins fixtures/ops.pyi]\n\n[case testStrictEqualityPerFile]\n# flags: --config-file tmp/mypy.ini\nimport b\n42 == 'no'  # E: Non-overlapping equality check (left operand type: \"Literal[42]\", right operand type: \"Literal['no']\")\n[file b.py]\n42 == 'no'\n[file mypy.ini]\n\\[mypy]\nstrict_equality = True\n\\[mypy-b]\nstrict_equality = False\n[builtins fixtures/bool.pyi]\n\n\n[case testStrictEqualityPerFilePyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport b\n42 == 'no'  # E: Non-overlapping equality check (left operand type: \"Literal[42]\", right operand type: \"Literal['no']\")\n\n[file b.py]\n42 == 'no'\n\n[file pyproject.toml]\n\\[tool.mypy]\nstrict_equality = true\n\\[[tool.mypy.overrides]]\nmodule = 'b'\nstrict_equality = false\n\n[builtins fixtures/bool.pyi]\n\n\n[case testNoImplicitReexport]\n# flags: --no-implicit-reexport --show-error-codes\nfrom other_module_2 import a  # E: Module \"other_module_2\" does not explicitly export attribute \"a\"  [attr-defined]\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\n\nimport other_module_2\nreveal_type(other_module_2.a)  # E: Module \"other_module_2\" does not explicitly export attribute \"a\"  [attr-defined] \\\n                               # N: Revealed type is \"builtins.int\"\n\nfrom other_module_2 import b  # E: Module \"other_module_2\" does not explicitly export attribute \"b\"  [attr-defined]\nreveal_type(b)  # N: Revealed type is \"def (a: builtins.int) -> builtins.str\"\n\nimport other_module_2\nreveal_type(other_module_2.b)  # E: Module \"other_module_2\" does not explicitly export attribute \"b\"  [attr-defined] \\\n                               # N: Revealed type is \"def (a: builtins.int) -> builtins.str\"\n\n[file other_module_1.py]\na = 5\ndef b(a: int) -> str: ...\n[file other_module_2.py]\nfrom other_module_1 import a, b\n[builtins fixtures/module.pyi]\n\n[case testNoImplicitReexportRespectsAll]\n# flags: --no-implicit-reexport\nfrom other_module_2 import a\nfrom other_module_2 import b\n[file other_module_1.py]\na = 5\nb = 6\n[file other_module_2.py]\nfrom other_module_1 import a, b\n__all__ = ('b',)\n[builtins fixtures/tuple.pyi]\n[out]\nmain:2: error: Module \"other_module_2\" does not explicitly export attribute \"a\"\n\n[case testNoImplicitReexportStarConsideredExplicit]\n# flags: --no-implicit-reexport\nfrom other_module_2 import a\nfrom other_module_2 import b\n[file other_module_1.py]\na = 5\nb = 6\n[file other_module_2.py]\nfrom other_module_1 import *\n__all__ = ('b',)\n[builtins fixtures/tuple.pyi]\n\n[case testNoImplicitReexportGetAttr]\n# flags: --no-implicit-reexport\nfrom other_module_2 import a  # E: Module \"other_module_2\" does not explicitly export attribute \"a\"\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\nfrom other_module_2 import b  # E: Module \"other_module_2\" does not explicitly export attribute \"b\"\nreveal_type(b)  # N: Revealed type is \"builtins.str\"\n[file other_module_1.py]\nb: str = \"asdf\"\ndef __getattr__(name: str) -> int: ...\n[file other_module_2.py]\nfrom other_module_1 import a, b\ndef __getattr__(name: str) -> bytes: ...\n[builtins fixtures/tuple.pyi]\n\n[case textNoImplicitReexportSuggestions]\n# flags: --no-implicit-reexport\nfrom other_module_2 import attr_1\n\n[file other_module_1.py]\nattr_1 = 5\nattr_2 = 6\n[file other_module_2.py]\nfrom other_module_1 import attr_1, attr_2\n[out]\nmain:2: error: Module \"other_module_2\" does not explicitly export attribute \"attr_1\"\n\n[case testNoImplicitReexportMypyIni]\n# flags: --config-file tmp/mypy.ini\nfrom other_module_2 import a\n\n[file other_module_1.py]\na = 5\n\n[file other_module_2.py]\nfrom other_module_1 import a\n\n[file mypy.ini]\n\\[mypy]\nimplicit_reexport = True\n\\[mypy-other_module_2]\nimplicit_reexport = False\n[out]\nmain:2: error: Module \"other_module_2\" does not explicitly export attribute \"a\"\n\n\n[case testNoImplicitReexportPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nfrom other_module_2 import a\n\n[file other_module_1.py]\na = 5\n\n[file other_module_2.py]\nfrom other_module_1 import a\n\n[file pyproject.toml]\n\\[tool.mypy]\nimplicit_reexport = true\n\\[[tool.mypy.overrides]]\nmodule = 'other_module_2'\nimplicit_reexport = false\n\n[out]\nmain:2: error: Module \"other_module_2\" does not explicitly export attribute \"a\"\n\n\n[case testImplicitAnyOKForNoArgs]\n# flags: --disallow-any-generics --show-column-numbers\nfrom typing import List\n\nA = List  # OK\nB = List[A]  # E:10: Missing type arguments for generic type \"A\"\nx: A  # E:4: Missing type arguments for generic type \"A\"\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExplicitDefSignature]\n# flags: --disallow-any-explicit --show-error-codes\n\nfrom typing import Any, List\n\ndef f(x: Any) -> None:  # E: Explicit \"Any\" is not allowed  [explicit-any]\n    pass\n\ndef g() -> Any:  # E: Explicit \"Any\" is not allowed  [explicit-any]\n    pass\n\ndef h() -> List[Any]:  # E: Explicit \"Any\" is not allowed  [explicit-any]\n    pass\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExplicitVarDeclaration]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any\nv: Any = ''  # E: Explicit \"Any\" is not allowed  [explicit-any]\nw = ''  # type: Any  # E: Explicit \"Any\" is not allowed  [explicit-any]\nclass X:\n    y = ''  # type: Any  # E: Explicit \"Any\" is not allowed  [explicit-any]\n\n[case testDisallowAnyExplicitGenericVarDeclaration]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any, List\nv: List[Any] = []  # E: Explicit \"Any\" is not allowed  [explicit-any]\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExplicitInheritance]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any, List\n\nclass C(Any):  # E: Explicit \"Any\" is not allowed  [explicit-any]\n    pass\n\nclass D(List[Any]):  # E: Explicit \"Any\" is not allowed  [explicit-any]\n    pass\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExplicitAlias]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any, List\n\nX = Any  # E: Explicit \"Any\" is not allowed  [explicit-any]\nY = List[Any]  # E: Explicit \"Any\" is not allowed  [explicit-any]\n\ndef foo(x: X) -> Y:  # no error\n    x.nonexistent()  # no error\n    return x\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExplicitGenericAlias]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any, TypeVar, Tuple\n\nT = TypeVar('T')\n\nTupleAny = Tuple[Any, T]  # E: Explicit \"Any\" is not allowed  [explicit-any]\n\ndef foo(x: TupleAny[str]) -> None:  # no error\n    pass\n\ndef goo(x: TupleAny[Any]) -> None:  # E: Explicit \"Any\" is not allowed  [explicit-any]\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testDisallowAnyExplicitCast]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any, List, cast\n\nx = 1\ny = cast(Any, x)  # E: Explicit \"Any\" is not allowed  [explicit-any]\nz = cast(List[Any], x)  # E: Explicit \"Any\" is not allowed  [explicit-any]\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExplicitNamedTuple]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any, List, NamedTuple\n\nPoint = NamedTuple('Point', [('x', List[Any]), ('y', Any)])  # E: Explicit \"Any\" is not allowed  [explicit-any]\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExplicitTypeVarConstraint]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any, List, TypeVar\n\nT = TypeVar('T', Any, List[Any])  # E: Explicit \"Any\" is not allowed  [explicit-any]\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExplicitNewType]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any, List, NewType\n\n# this error does not come from `--disallow-any-explicit` flag\nBaz = NewType('Baz', Any)  # E: Argument 2 to NewType(...) must be subclassable (got \"Any\")  [valid-newtype]\nBar = NewType('Bar', List[Any])  # E: Explicit \"Any\" is not allowed  [explicit-any]\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyExplicitTypedDictSimple]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any, TypedDict\n\nM = TypedDict('M', {'x': str, 'y': Any})  # E: Explicit \"Any\" is not allowed  [explicit-any]\nM(x='x', y=2)  # no error\ndef f(m: M) -> None: pass  # no error\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDisallowAnyExplicitTypedDictGeneric]\n# flags: --disallow-any-explicit --show-error-codes\nfrom typing import Any, List, TypedDict\n\nM = TypedDict('M', {'x': str, 'y': List[Any]})  # E: Explicit \"Any\" is not allowed  [explicit-any]\nN = TypedDict('N', {'x': str, 'y': List})  # no error\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testDisallowAnyGenericsTupleNoTypeParams]\n# flags: --disallow-any-generics\nfrom typing import Tuple\n\ndef f(s: Tuple) -> None: pass  # E: Missing type arguments for generic type \"Tuple\"\ndef g(s) -> Tuple:  # E: Missing type arguments for generic type \"Tuple\"\n    return 'a', 'b'\ndef h(s) -> Tuple[str, str]:  # no error\n    return 'a', 'b'\nx: Tuple = ()  # E: Missing type arguments for generic type \"Tuple\"\n[builtins fixtures/tuple.pyi]\n\n[case testDisallowAnyGenericsTupleWithNoTypeParamsGeneric]\n# flags: --disallow-any-generics\nfrom typing import Tuple, List\n\ndef f(s: Tuple) -> None: pass  # E: Missing type arguments for generic type \"Tuple\"\ndef g(s: List[Tuple]) -> None: pass  # E: Missing type arguments for generic type \"Tuple\"\ndef h(s: List[Tuple[str, str]]) -> None: pass  # no error\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyGenericsTypeType]\n# flags: --disallow-any-generics\nfrom typing import Type, Any\n\ndef f(s: Type[Any]) -> None: pass  # no error\ndef g(s) -> Type:  # E: Missing type arguments for generic type \"Type\"\n    return s\ndef h(s) -> Type[str]:  # no error\n    return s\nx: Type = g(0)  # E: Missing type arguments for generic type \"Type\"\n\n[case testDisallowAnyGenericsAliasGenericType]\n# flags: --disallow-any-generics\nfrom typing import List\n\nL = List  # no error\n\ndef f(l: L) -> None: pass  # E: Missing type arguments for generic type \"L\"\ndef g(l: L[str]) -> None: pass  # no error\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyGenericsGenericAlias]\n# flags: --disallow-any-generics\nfrom typing import TypeVar, Tuple\n\nT = TypeVar('T')\nA = Tuple[T, str, T]\n\ndef f(s: A) -> None: pass  # E: Missing type arguments for generic type \"A\"\ndef g(s) -> A:  # E: Missing type arguments for generic type \"A\"\n    return 'a', 'b', 1\ndef h(s) -> A[str]:  # no error\n    return 'a', 'b', 'c'\nx: A = ('a', 'b', 1)  # E: Missing type arguments for generic type \"A\"\n[builtins fixtures/tuple.pyi]\n\n[case testDisallowAnyGenericsPlainList]\n# flags: --disallow-any-generics\nfrom typing import List\n\ndef f(l: List) -> None: pass  # E: Missing type arguments for generic type \"List\"\ndef g(l: List[str]) -> None: pass\ndef h(l: List[List]) -> None: pass   # E: Missing type arguments for generic type \"List\"\ndef i(l: List[List[List[List]]]) -> None: pass  # E: Missing type arguments for generic type \"List\"\ndef j() -> List: pass  # E: Missing type arguments for generic type \"List\"\n\nx = []  # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\ny: List = []  # E: Missing type arguments for generic type \"List\"\n[builtins fixtures/list.pyi]\n\n[case testDisallowAnyGenericsPlainDict]\n# flags: --disallow-any-generics\nfrom typing import List, Dict\n\ndef f(d: Dict) -> None: pass  # E: Missing type arguments for generic type \"Dict\"\ndef g(d: Dict[str, Dict]) -> None: pass  # E: Missing type arguments for generic type \"Dict\"\ndef h(d: List[Dict]) -> None: pass  # E: Missing type arguments for generic type \"Dict\"\n\nd: Dict = {}  # E: Missing type arguments for generic type \"Dict\"\n[builtins fixtures/dict.pyi]\n\n[case testDisallowAnyGenericsPlainSet]\n# flags: --disallow-any-generics\nfrom typing import Set\n\ndef f(s: Set) -> None: pass  # E: Missing type arguments for generic type \"Set\"\ndef g(s: Set[Set]) -> None: pass  # E: Missing type arguments for generic type \"Set\"\n\ns: Set = set()  # E: Missing type arguments for generic type \"Set\"\n[builtins fixtures/set.pyi]\n\n[case testDisallowAnyGenericsCustomGenericClass]\n# flags: --disallow-any-generics\nfrom typing import Generic, TypeVar, Any\n\nT = TypeVar('T')\nclass G(Generic[T]): pass\n\ndef f() -> G:  # E: Missing type arguments for generic type \"G\"\n    return G()\n\nx: G[Any] = G()  # no error\ny: G = x  # E: Missing type arguments for generic type \"G\"\n\n[case testDisallowAnyGenericsForAliasesInRuntimeContext]\n# flags: --disallow-any-generics\nfrom typing import Any, TypeVar, Generic, Tuple\n\nT = TypeVar(\"T\")\nclass G(Generic[T]):\n    @classmethod\n    def foo(cls) -> T: ...\n\nA = G[Tuple[T, T]]\nA()  # E: Missing type arguments for generic type \"A\"\nA.foo()  # E: Missing type arguments for generic type \"A\"\n\nB = G\nB()\nB.foo()\n\ndef foo(x: Any) -> None: ...\nfoo(A)\nfoo(A.foo)\n[builtins fixtures/classmethod.pyi]\n\n[case testDisallowSubclassingAny]\n# flags: --config-file tmp/mypy.ini\nimport m\nimport y\n\n[file m.py]\nfrom typing import Any\n\nx = None  # type: Any\n\nclass ShouldBeFine(x): ...\n\n[file y.py]\nfrom typing import Any\n\nx = None  # type: Any\n\nclass ShouldNotBeFine(x): ...  # E: Class cannot subclass \"x\" (has type \"Any\")\n\n[file mypy.ini]\n\\[mypy]\ndisallow_subclassing_any = True\n\\[mypy-m]\ndisallow_subclassing_any = False\n\n\n[case testDisallowSubclassingAnyPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport m\nimport y\n\n[file m.py]\nfrom typing import Any\n\nx = None  # type: Any\n\nclass ShouldBeFine(x): ...\n\n[file y.py]\nfrom typing import Any\n\nx = None  # type: Any\n\nclass ShouldNotBeFine(x): ...  # E: Class cannot subclass \"x\" (has type \"Any\")\n\n[file pyproject.toml]\n\\[tool.mypy]\ndisallow_subclassing_any = true\n\\[[tool.mypy.overrides]]\nmodule = 'm'\ndisallow_subclassing_any = false\n\n\n[case testNoImplicitOptionalPerModule]\n# flags: --config-file tmp/mypy.ini\nimport m\n\n[file m.py]\ndef f(a: str = None) -> int:\n    return 0\n\n[file mypy.ini]\n\\[mypy]\nno_implicit_optional = True\n\\[mypy-m]\nno_implicit_optional = False\n\n\n[case testNoImplicitOptionalPerModulePyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport m\n\n[file m.py]\ndef f(a: str = None) -> int:\n    return 0\n\n[file pyproject.toml]\n\\[tool.mypy]\nno_implicit_optional = true\n\\[[tool.mypy.overrides]]\nmodule = 'm'\nno_implicit_optional = false\n\n[case testDisableErrorCode]\n# flags: --disable-error-code attr-defined\nx = 'should be fine'\nx.trim()\n\n[case testDisableDifferentErrorCode]\n# flags: --disable-error-code name-defined --show-error-codes\nx = 'should not be fine'\nx.trim()  # E: \"str\" has no attribute \"trim\"  [attr-defined]\n\n[case testDisableMultipleErrorCode]\n# flags: --disable-error-code attr-defined --disable-error-code return-value --show-error-codes\nx = 'should be fine'\nx.trim()\n\ndef bad_return_type() -> str:\n    return None\n\nbad_return_type('no args taken!')  # E: Too many arguments for \"bad_return_type\"  [call-arg]\n\n[case testEnableErrorCode]\n# flags: --disable-error-code attr-defined --enable-error-code attr-defined --show-error-codes\nx = 'should be fine'\nx.trim()  # E: \"str\" has no attribute \"trim\"  [attr-defined]\n\n[case testEnableDifferentErrorCode]\n# flags: --disable-error-code attr-defined --enable-error-code name-defined --show-error-codes\nx = 'should not be fine'\nx.trim()\ny.trim()  # E: Name \"y\" is not defined  [name-defined]\n\n[case testEnableMultipleErrorCode]\n# flags: \\\n    --disable-error-code attr-defined \\\n    --disable-error-code return-value \\\n    --disable-error-code call-arg \\\n    --enable-error-code attr-defined \\\n    --enable-error-code return-value --show-error-codes\nx = 'should be fine'\nx.trim()  # E: \"str\" has no attribute \"trim\"  [attr-defined]\n\ndef bad_return_type() -> str:\n    return None  # E: Incompatible return value type (got \"None\", expected \"str\")  [return-value]\n\nbad_return_type('no args taken!')\n\n[case testDisallowUntypedCallsArgType]\n# flags: --disallow-untyped-calls\ndef f(x):\n    pass\n\ny = 1\nf(reveal_type(y)) # E: Call to untyped function \"f\" in typed context \\\n                  # N: Revealed type is \"builtins.int\"\n\n[case testDisallowUntypedCallsAllowListFlags]\n# flags: --disallow-untyped-calls  --untyped-calls-exclude=foo --untyped-calls-exclude=bar.A\nfrom foo import test_foo\nfrom bar import A, B\nfrom baz import test_baz\nfrom foobar import bad\n\ntest_foo(42)  # OK\ntest_baz(42)  # E: Call to untyped function \"test_baz\" in typed context\nbad(42)  # E: Call to untyped function \"bad\" in typed context\n\na: A\nb: B\na.meth()  # OK\nb.meth()  # E: Call to untyped function \"meth\" in typed context\n[file foo.py]\ndef test_foo(x): pass\n[file foobar.py]\ndef bad(x): pass\n[file bar.py]\nclass A:\n    def meth(self): pass\nclass B:\n    def meth(self): pass\n[file baz.py]\ndef test_baz(x): pass\n\n[case testDisallowUntypedCallsAllowListConfig]\n# flags: --config-file tmp/mypy.ini\nfrom foo import test_foo\nfrom bar import A, B\nfrom baz import test_baz\n\ntest_foo(42)  # OK\ntest_baz(42)  # E: Call to untyped function \"test_baz\" in typed context\n\na: A\nb: B\na.meth()  # OK\nb.meth()  # E: Call to untyped function \"meth\" in typed context\n[file foo.py]\ndef test_foo(x): pass\n[file bar.py]\nclass A:\n    def meth(self): pass\nclass B:\n    def meth(self): pass\n[file baz.py]\ndef test_baz(x): pass\n\n[file mypy.ini]\n\\[mypy]\ndisallow_untyped_calls = True\nuntyped_calls_exclude = foo, bar.A\n\n[case testPerModuleErrorCodes]\n# flags: --config-file tmp/mypy.ini\nimport tests.foo\nimport bar\n[file bar.py]\nx = []  # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n[file tests/__init__.py]\n[file tests/foo.py]\nx = []  # OK\n[file mypy.ini]\n\\[mypy]\nstrict = True\n\n\\[mypy-tests.*]\nallow_untyped_defs = True\nallow_untyped_calls = True\ndisable_error_code = var-annotated\n\n[case testPerFileIgnoreErrors]\n# flags: --config-file tmp/mypy.ini\nimport foo, bar\n[file foo.py]\nx: str = 5\n[file bar.py]\nx: str = 5  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[file mypy.ini]\n\\[mypy]\n\\[mypy-foo]\nignore_errors = True\n\n[case testPerFileUntypedDefs]\n# flags: --config-file tmp/mypy.ini\nimport x, y, z\n[file x.py]\ndef f(a): ...  # E: Function is missing a type annotation\ndef g(a: int) -> int: return f(a)\n[file y.py]\ndef f(a): pass\ndef g(a: int) -> int: return f(a)\n[file z.py]\ndef f(a): pass  # E: Function is missing a type annotation\ndef g(a: int) -> int: return f(a)  # E: Call to untyped function \"f\" in typed context\n[file mypy.ini]\n\\[mypy]\ndisallow_untyped_defs = True\n\\[mypy-y]\ndisallow_untyped_defs = False\n\\[mypy-z]\ndisallow_untyped_calls = True\n\n[case testPerModuleErrorCodesOverride]\n# flags: --config-file tmp/mypy.ini\nimport tests.foo\nimport bar\n[file bar.py]\ndef foo() -> int: ...\nif foo: ...  # E: Function \"foo\" could always be true in boolean context\n42 + \"no\"  # type: ignore  # E: \"type: ignore\" comment without error code (consider \"type: ignore[operator]\" instead)\n[file tests/__init__.py]\n[file tests/foo.py]\ndef foo() -> int: ...\nif foo: ...  # E: Function \"foo\" could always be true in boolean context\n42 + \"no\"  # type: ignore\n[file mypy.ini]\n\\[mypy]\nenable_error_code = ignore-without-code, truthy-bool, used-before-def\n\n\\[mypy-tests.*]\ndisable_error_code = ignore-without-code\n\n[case testShowErrorCodes]\n# flags: --show-error-codes\nx: int = \"\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")  [assignment]\n\n[case testHideErrorCodes]\n# flags: --hide-error-codes\nx: int = \"\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testDisableBytearrayPromotion]\n# flags: --disable-bytearray-promotion --strict-equality --warn-unreachable\ndef f(x: bytes) -> None: ...\nf(bytearray(b\"asdf\"))  # E: Argument 1 to \"f\" has incompatible type \"bytearray\"; expected \"bytes\"\nf(memoryview(b\"asdf\"))\nba = bytearray(b\"\")\nif ba == b\"\":\n    f(ba)  # E: Argument 1 to \"f\" has incompatible type \"bytearray\"; expected \"bytes\"\nif b\"\" == ba:\n    f(ba)  # E: Argument 1 to \"f\" has incompatible type \"bytearray\"; expected \"bytes\"\nif ba == bytes():\n    f(ba)  # E: Argument 1 to \"f\" has incompatible type \"bytearray\"; expected \"bytes\"\nif bytes() == ba:\n    f(ba)  # E: Argument 1 to \"f\" has incompatible type \"bytearray\"; expected \"bytes\"\n[builtins fixtures/primitives.pyi]\n\n[case testDisableMemoryviewPromotion]\n# flags: --disable-memoryview-promotion\ndef f(x: bytes) -> None: ...\nf(bytearray(b\"asdf\"))\nf(memoryview(b\"asdf\"))  # E: Argument 1 to \"f\" has incompatible type \"memoryview\"; expected \"bytes\"\n[builtins fixtures/primitives.pyi]\n\n[case testDisableBytearrayMemoryviewPromotionStrictEquality]\n# flags: --disable-bytearray-promotion --disable-memoryview-promotion --strict-equality\ndef f(x: bytes, y: bytearray, z: memoryview) -> None:\n    x == y\n    y == z\n    x == z\n    97 in x\n    97 in y\n    97 in z\n    x in y\n    x in z\n[builtins fixtures/primitives.pyi]\n\n[case testEnableBytearrayMemoryviewPromotionStrictEquality]\n# flags: --strict-equality\ndef f(x: bytes, y: bytearray, z: memoryview) -> None:\n    x == y\n    y == z\n    x == z\n    97 in x\n    97 in y\n    97 in z\n    x in y\n    x in z\n[builtins fixtures/primitives.pyi]\n\n[case testStrictBytes]\n# flags: --strict-bytes\ndef f(x: bytes) -> None: ...\nf(bytearray(b\"asdf\"))  # E: Argument 1 to \"f\" has incompatible type \"bytearray\"; expected \"bytes\"\nf(memoryview(b\"asdf\"))  # E: Argument 1 to \"f\" has incompatible type \"memoryview\"; expected \"bytes\"\n[builtins fixtures/primitives.pyi]\n\n[case testNoStrictBytes]\n# flags: --no-strict-bytes\ndef f(x: bytes) -> None: ...\nf(bytearray(b\"asdf\"))\nf(memoryview(b\"asdf\"))\n[builtins fixtures/primitives.pyi]\n\n[case testStrictBytesDisabledByDefault]\n# TODO: probably change this default in Mypy v2.0, with https://github.com/python/mypy/pull/18371\n# (this would also obsolete the testStrictBytesEnabledByStrict test, below)\ndef f(x: bytes) -> None: ...\nf(bytearray(b\"asdf\"))\nf(memoryview(b\"asdf\"))\n[builtins fixtures/primitives.pyi]\n\n[case testStrictBytesEnabledByStrict]\n# flags: --strict --disable-error-code type-arg\n# The type-arg thing is just work around the primitives.pyi isinstance Tuple not having type parameters,\n#   which isn't important for this.\ndef f(x: bytes) -> None: ...\nf(bytearray(b\"asdf\"))  # E: Argument 1 to \"f\" has incompatible type \"bytearray\"; expected \"bytes\"\nf(memoryview(b\"asdf\"))  # E: Argument 1 to \"f\" has incompatible type \"memoryview\"; expected \"bytes\"\n[builtins fixtures/primitives.pyi]\n\n[case testNoCrashFollowImportsForStubs]\n# flags: --config-file tmp/mypy.ini\n{**{\"x\": \"y\"}}\n\n[file mypy.ini]\n\\[mypy]\nfollow_imports = skip\nfollow_imports_for_stubs = true\n[builtins fixtures/dict.pyi]\n\n[case testReturnAnyLambda]\n# flags: --warn-return-any\nfrom typing import Any, Callable\n\ndef cb(f: Callable[[int], int]) -> None: ...\na: Any\ncb(lambda x: a)  # OK\n\nfn = lambda x: a\ncb(fn)\n\n[case testShowErrorCodeLinks]\n# flags: --show-error-codes --show-error-code-links\n\nx: int = \"\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")  [assignment]\nlist(1)  # E: No overload variant of \"list\" matches argument type \"int\"  [call-overload] \\\n         # N: Possible overload variants: \\\n         # N:     def [T] list() -> list[T] \\\n         # N:     def [T] list(x: Iterable[T]) -> list[T] \\\n         # N: See https://mypy.rtfd.io/en/stable/_refs.html#code-call-overload for more info\nlist(2)  # E: No overload variant of \"list\" matches argument type \"int\"  [call-overload] \\\n         # N: Possible overload variants: \\\n         # N:     def [T] list() -> list[T] \\\n         # N:     def [T] list(x: Iterable[T]) -> list[T]\n[builtins fixtures/list.pyi]\n\n[case testNestedGenericInAliasDisallow]\n# flags: --disallow-any-generics\nfrom typing import TypeVar, Generic, List, Union\n\nclass C(Generic[T]): ...\n\nA = Union[C, List]  # E: Missing type arguments for generic type \"C\" \\\n                    # E: Missing type arguments for generic type \"List\"\n\n[builtins fixtures/list.pyi]\n\n[case testNestedGenericInAliasAllow]\n# flags: --allow-any-generics\nfrom typing import TypeVar, Generic, List, Union\n\nclass C(Generic[T]): ...\n\nA = Union[C, List]  # OK\n[builtins fixtures/list.pyi]\n\n[case testNotesOnlyResultInExitSuccess]\n-- check_untyped_defs is False by default.\ndef f():\n    x: int = \"no\"  # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs\n\n[case testRedefineLocalWithDifferentTypeAlias]\n# flags: --allow-redefinition-old\ndef f() -> None:\n    x = 0\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x = ''\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n\n[case testRedefineLocalWithDifferentTypeInline]\n# mypy: allow-redefinition\ndef f() -> None:\n    x = 0\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x = ''\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n\n[case testRedefineLocalWithDifferentTypeInverse]\n# flags: --disallow-redefinition-old\ndef f() -> None:\n    x = 0\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testRedefineLocalWithDifferentTypeConfigAlias]\n# flags: --config-file tmp/mypy.ini\ndef f() -> None:\n    x = 0\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x = ''\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n[file mypy.ini]\n\\[mypy]\nallow_redefinition = true\n\n[case testRedefineLocalWithDifferentTypeConfigOld]\n# flags: --config-file tmp/mypy.ini\ndef f() -> None:\n    x = 0\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x = ''\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n[file mypy.ini]\n\\[mypy]\nallow_redefinition_old = true\n\n[case testRedefineLocalWithDifferentTypeConfigInverse]\n# flags: --config-file tmp/mypy.ini\ndef f() -> None:\n    x = 0\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[file mypy.ini]\n\\[mypy]\ndisallow_redefinition = true\n\n[case testRevealSimpleTypes_no_verbose_reveal]\nfrom typing import Generic, TypeVar, Callable\nfrom typing_extensions import TypeVarTuple, Unpack, TypedDict\n\nT = TypeVar(\"T\", bound=int)\nS = TypeVar(\"S\", default=list[T])\n\nclass A(Generic[T, S]): ...\nreveal_type(A)  # N: Revealed type is \"def [T <: int, S = list[T]] () -> __main__.A[T, S]\"\n\nTs = TypeVarTuple(\"Ts\")\ndef foo(x: int, *xs: Unpack[Ts]) -> tuple[int, Unpack[Ts]]: ...\nreveal_type(foo)  # N: Revealed type is \"def [Ts] (x: int, *xs: *Ts) -> tuple[int, *Ts]\"\n\nclass User(TypedDict):\n    age: int\n    name: str\n\ndef bar(x: int, **kwargs: Unpack[User]) -> None: ...\nreveal_type(bar)  # N: Revealed type is \"def (x: int, **kwargs: **TypedDict(__main__.User, {'age': int, 'name': str}))\"\n\nfn: Callable[[Unpack[Ts], Unpack[User]], tuple[Unpack[Ts]]]\nreveal_type(fn)  # N: Revealed type is \"def [Ts] (*args: *Ts, **kwargs: **TypedDict(__main__.User, {'age': int, 'name': str})) -> tuple[*Ts]\"\n\nfx: Callable[[int, Unpack[Ts], int], tuple[Unpack[Ts]]]\nreveal_type(fx)  # N: Revealed type is \"def [Ts] (int, *args: *tuple[*Ts, int]) -> tuple[*Ts]\"\n[builtins fixtures/tuple.pyi]\n\n[case testOnlyOneRedefinitionModeAllowed]\n# flags: --allow-redefinition --allow-redefinition-new --local-partial-types\nx = 1\n[out]\nmain:1: error: --allow-redefinition-old and --allow-redefinition-new should not be used together\n"
  },
  {
    "path": "test-data/unit/check-formatting.test",
    "content": "\n-- String interpolation\n-- --------------------\n\n[case testStringInterpolationType]\nfrom typing import Tuple\ni: int\nf: float\ns: str\nt: Tuple[int]\n'%d' % i\n'%f' % f\n'%s' % s\n'%d' % (f,)\n'%d' % (s,) # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float | SupportsInt\")\n'%d' % t\n'%d' % s  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float | SupportsInt\")\n'%f' % s  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float | SupportsFloat\")\n'%x' % f  # E: Incompatible types in string interpolation (expression has type \"float\", placeholder has type \"int\")\n'%i' % f\n'%o' % f  # E: Incompatible types in string interpolation (expression has type \"float\", placeholder has type \"int\")\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationSAcceptsAnyType]\nfrom typing import Any\ni: int\no: object\ns: str\n'%s %s %s' % (i, o, s)\n[builtins fixtures/primitives.pyi]\n\n[case testStringInterpolationSBytesVsStrErrorPy3]\nxb: bytes\nxs: str\n\n'%s' % xs   # OK\n'%s' % xb   # E: If x = b'abc' then \"%s\" % x produces \"b'abc'\", not \"abc\". If this is desired behavior use \"%r\" % x. Otherwise, decode the bytes\n'%(name)s' % {'name': b'value'}  # E: If x = b'abc' then \"%s\" % x produces \"b'abc'\", not \"abc\". If this is desired behavior use \"%r\" % x. Otherwise, decode the bytes\n[builtins fixtures/primitives.pyi]\n\n[case testStringInterpolationCount]\n'%d %d' % 1  # E: Not enough arguments for format string\n'%d %d' % (1, 2)\n'%d %d' % (1, 2, 3)  # E: Not all arguments converted during string formatting\nt = 1, 's'\n'%d %s' % t\n'%s %d' % t  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float | SupportsInt\")\n'%d' % t  # E: Not all arguments converted during string formatting\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationWithAnyType]\nfrom typing import Any\na = None # type: Any\n'%d %d' % a\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationInvalidPlaceholder]\n'%W' % 1  # E: Unsupported format character \"W\"\n'%b' % 1  # E: Format character \"b\" is only supported on bytes patterns\n'%(a)' % {'a': 1}  # E: Unsupported format character \"\"\n\n[case testStringInterpolationWidth]\n'%2f' % 3.14\n'%*f' % 3.14 # E: Not enough arguments for format string\n'%*f' % (4, 3.14)\n'%*f' % (1.1, 3.14) # E: * wants int\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationPrecision]\n'%.2f' % 3.14\n'%.*f' % 3.14 # E: Not enough arguments for format string\n'%.*f' % (4, 3.14)\n'%.*f' % (1.1, 3.14) # E: * wants int\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationWidthAndPrecision]\n'%4.2f' % 3.14\n'%4.*f' % 3.14 # E: Not enough arguments for format string\n'%*.2f' % 3.14 # E: Not enough arguments for format string\n'%*.*f' % 3.14 # E: Not enough arguments for format string\n'%*.*f' % (4, 2, 3.14)\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationFlagsAndLengthModifiers]\n'%04hd' % 1\n'%-.4ld' % 1\n'%+*Ld' % (1, 1)\n'% .*ld' % (1, 1)\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationDoublePercentage]\n'%% %d' % 1\n'%3% %d' % 1\n'%*%' % 1\n'%*% %d' % 1  # E: Not enough arguments for format string\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationC]\n'%c' % 1\n'%c' % 1.0   # E: \"%c\" requires int or char (expression has type \"float\")\n'%c' % 's'\n'%c' % ''    # E: \"%c\" requires int or char\n'%c' % 'ab'  # E: \"%c\" requires int or char\n'%c' % b'a'  # E: \"%c\" requires int or char (expression has type \"bytes\")\n'%c' % b''   # E: \"%c\" requires int or char (expression has type \"bytes\")\n'%c' % b'ab' # E: \"%c\" requires int or char (expression has type \"bytes\")\n[builtins fixtures/primitives.pyi]\n\n[case testStringInterpolationMappingTypes]\n'%(a)d %(b)s' % {'a': 1, 'b': 's'}\n'%(a)d %(b)s' % {'a': 's', 'b': 1}  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder with key 'a' has type \"int | float | SupportsInt\")\nb'%(x)s' % {b'x': b'data'}\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationMappingKeys]\n'%()d' % {'': 2}\n'%(a)d' % {'a': 1, 'b': 2, 'c': 3}\n'%(q)d' % {'a': 1, 'b': 2, 'c': 3}  # E: Key \"q\" not found in mapping\n'%(a)d %%' % {'a': 1}\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationMappingDictTypes]\nfrom typing import Any, Dict, Iterable\n\nclass StringThing:\n    def keys(self) -> Iterable[str]:\n        ...\n    def __getitem__(self, __key: str) -> str:\n        ...\n\nclass BytesThing:\n    def keys(self) -> Iterable[bytes]:\n        ...\n    def __getitem__(self, __key: bytes) -> str:\n        ...\n\na: Any\nds: Dict[str, int]\ndo: Dict[object, int]\ndi: Dict[int, int]\n'%(a)' % 1  # E: Format requires a mapping (expression has type \"int\", expected type for mapping is \"SupportsKeysAndGetItem[str, Any]\")\n'%()d' % a\n'%()d' % ds\n'%()d' % do  # E: Format requires a mapping (expression has type \"dict[object, int]\", expected type for mapping is \"SupportsKeysAndGetItem[str, Any]\")\nb'%()d' % ds  # E: Format requires a mapping (expression has type \"dict[str, int]\", expected type for mapping is \"SupportsKeysAndGetItem[bytes, Any]\")\n'%()s' % StringThing()\nb'%()s' % BytesThing()\n[builtins fixtures/primitives.pyi]\n\n[case testStringInterpolationMappingInvalidSpecifiers]\n'%(a)d %d' % 1  # E: String interpolation mixes specifier with and without mapping keys\n'%(b)*d' % 1  # E: String interpolation contains both stars and mapping keys\n'%(b).*d' % 1  # E: String interpolation contains both stars and mapping keys\n\n[case testStringInterpolationMappingFlagsAndLengthModifiers]\n'%(a)1d' % {'a': 1}\n'%(a).1d' % {'a': 1}\n'%(a)#1.1ld' % {'a': 1}\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationFloatPrecision]\n'%.f' % 1.2\n'%.3f' % 1.2\n'%.f' % 'x'\n'%.3f' % 'x'\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\nmain:3: error: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float | SupportsFloat\")\nmain:4: error: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float | SupportsFloat\")\n\n[case testStringInterpolationSpaceKey]\n'%( )s' % {' ': 'foo'}\n\n[case testStringInterpolationStarArgs]\nx = (1, 2)\n\"%d%d\" % (*x,)\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testStringInterpolationVariableLengthTuple]\nfrom typing import Tuple\ndef f(t: Tuple[int, ...]) -> None:\n    '%d %d' % t\n    '%d %d %d' % t\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testStringInterpolationUnionType]\nfrom typing import Tuple, Union\na: Union[Tuple[int, str], Tuple[str, int]] = ('A', 1)\n'%s %s' % a\n'%s' % a  # E: Not all arguments converted during string formatting\n\nb: Union[Tuple[int, str], Tuple[int, int], Tuple[str, int]] = ('A', 1)\n'%s %s' % b\n'%s %s %s' % b  # E: Not enough arguments for format string\n\nc: Union[Tuple[str, int], Tuple[str, int, str]] = ('A', 1)\n'%s %s' % c  # E: Not all arguments converted during string formatting\n[builtins fixtures/tuple.pyi]\n\n[case testStringInterpolationIterableType]\nfrom typing import Sequence, List, Tuple, Iterable\n\nt1: Sequence[str] = ('A', 'B')\nt2: List[str] = ['A', 'B']\nt3: Tuple[str, ...] = ('A', 'B')\nt4: Tuple[str, str] = ('A', 'B')\nt5: Iterable[str] = ('A', 'B')\n'%s %s' % t1\n'%s %s' % t2\n'%s %s' % t3\n'%s %s %s' % t3\n'%s %s' % t4\n'%s %s %s' % t4 # E: Not enough arguments for format string\n'%s %s' % t5\n[builtins fixtures/tuple.pyi]\n\n\n-- Bytes interpolation\n-- --------------------\n\n[case testBytesInterpolation]\nb'%b' % 1  # E: Incompatible types in string interpolation (expression has type \"int\", placeholder has type \"bytes\")\nb'%b' % b'1'\nb'%a' % 3\n\n[case testBytesInterpolationC]\nb'%c' % 1\nb'%c' % 1.0   # E: \"%c\" requires an integer in range(256) or a single byte (expression has type \"float\")\nb'%c' % 's'   # E: \"%c\" requires an integer in range(256) or a single byte (expression has type \"str\")\nb'%c' % ''    # E: \"%c\" requires an integer in range(256) or a single byte (expression has type \"str\")\nb'%c' % 'ab'  # E: \"%c\" requires an integer in range(256) or a single byte (expression has type \"str\")\nb'%c' % b'a'\nb'%c' % b''   # E: \"%c\" requires an integer in range(256) or a single byte\nb'%c' % b'aa' # E: \"%c\" requires an integer in range(256) or a single byte\n[builtins fixtures/primitives.pyi]\n\n[case testByteByteInterpolation]\ndef foo(a: bytes, b: bytes):\n    b'%s:%s' % (a, b)\nfoo(b'a', b'b') == b'a:b'\n[builtins fixtures/tuple.pyi]\n\n[case testBytePercentInterpolationSupported]\nb'%s' % (b'xyz',)\nb'%(name)s' % {'name': b'jane'}  # E: Dictionary keys in bytes formatting must be bytes, not strings\nb'%(name)s' % {b'name': 'jane'}  # E: On Python 3 b'%s' requires bytes, not string\nb'%c' % (123)\n[builtins fixtures/tuple.pyi]\n\n\n-- str.format() calls\n-- ------------------\n\n\n[case testFormatCallParseErrors]\n'}'.format()  # E: Invalid conversion specifier in format string: unexpected }\n'{'.format()  # E: Invalid conversion specifier in format string: unmatched {\n\n'}}'.format()  # OK\n'{{'.format()  # OK\n\n'{{}}}'.format()  # E: Invalid conversion specifier in format string: unexpected }\n'{{{}}'.format()  # E: Invalid conversion specifier in format string: unexpected }\n\n'{}}{{}'.format()  # E: Invalid conversion specifier in format string: unexpected }\n'{{{}:{}}}'.format(0)  # E: Cannot find replacement for positional format specifier 1\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallValidationErrors]\n'{!}}'.format(0)  # E: Invalid conversion specifier in format string: unexpected }\n'{!x}'.format(0)  # E: Invalid conversion type \"x\", must be one of \"r\", \"s\" or \"a\"\n'{!:}'.format(0)  # E: Invalid conversion specifier in format string\n\n'{{}:s}'.format(0)  # E: Invalid conversion specifier in format string: unexpected }\n'{{}.attr}'.format(0)  # E: Invalid conversion specifier in format string: unexpected }\n'{{}[key]}'.format(0)  # E: Invalid conversion specifier in format string: unexpected }\n\n'{ {}:s}'.format()  # E: Conversion value must not contain { or }\n'{ {}.attr}'.format()  # E: Conversion value must not contain { or }\n'{ {}[key]}'.format()  # E: Conversion value must not contain { or }\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallEscaping]\n'{}'.format()  # E: Cannot find replacement for positional format specifier 0\n'{}'.format(0)  # OK\n\n'{{}}'.format()  # OK\n'{{}}'.format(0)  # E: Not all arguments converted during string formatting\n\n'{{{}}}'.format()  # E: Cannot find replacement for positional format specifier 0\n'{{{}}}'.format(0)  # OK\n\n'{{}} {} {{}}'.format(0)  # OK\n'{{}} {:d} {{}} {:d}'.format('a', 'b')  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\")\n\n'foo({}, {}) == {{}} ({{}} expected)'.format(0)  # E: Cannot find replacement for positional format specifier 1\n'foo({}, {}) == {{}} ({{}} expected)'.format(0, 1)  # OK\n'foo({}, {}) == {{}} ({{}} expected)'.format(0, 1, 2)  # E: Not all arguments converted during string formatting\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallNestedFormats]\n'{:{}{}}'.format(42, '*')  # E: Cannot find replacement for positional format specifier 2\n'{:{}{}}'.format(42, '*', '^')  # OK\n'{:{}{}}'.format(42, '*', '^', 0)  # E: Not all arguments converted during string formatting\n\n# NOTE: we don't check format specifiers that contain { or } at all\n'{:{{}}}'.format()  # E: Cannot find replacement for positional format specifier 0\n\n'{:{:{}}}'.format()  # E: Formatting nesting must be at most two levels deep\n'{:{{}:{}}}'.format()  # E: Invalid conversion specifier in format string: unexpected }\n\n'{!s:{fill:d}{align}}'.format(42, fill='*', align='^')  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\")\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallAutoNumbering]\n'{}, {{}}, {0}'.format()  # E: Cannot combine automatic field numbering and manual field specification\n'{0}, {1}, {}'.format()  # E: Cannot combine automatic field numbering and manual field specification\n\n'{0}, {1}, {0}'.format(1, 2, 3)  # E: Not all arguments converted during string formatting\n'{}, {other:+d}, {}'.format(1, 2, other='no')  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\")\n'{0}, {other}, {}'.format()  # E: Cannot combine automatic field numbering and manual field specification\n\n'{:{}}, {:{:.5d}{}}'.format(1, 2, 3, 'a', 5)  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\")\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallMatchingPositional]\n'{}'.format(positional='no')  # E: Cannot find replacement for positional format specifier 0 \\\n                              # E: Not all arguments converted during string formatting\n'{.x}, {}, {}'.format(1, 'two', 'three')  # E: \"int\" has no attribute \"x\"\n'Reverse {2.x}, {1}, {0}'.format(1, 2, 'three')  # E: \"str\" has no attribute \"x\"\n''.format(1, 2)  # E: Not all arguments converted during string formatting\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallMatchingNamed]\n'{named}'.format(0)  # E: Cannot find replacement for named format specifier \"named\" \\\n                     # E: Not all arguments converted during string formatting\n'{one.x}, {two}'.format(one=1, two='two')  # E: \"int\" has no attribute \"x\"\n'{one}, {two}, {.x}'.format(1, one='two', two='three')  # E: \"int\" has no attribute \"x\"\n''.format(stuff='yes')  # E: Not all arguments converted during string formatting\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallMatchingVarArg]\nfrom typing import List\nargs: List[int] = []\n'{}, {}'.format(1, 2, *args)  # Don't flag this because args may be empty\n\nstrings: List[str]\n'{:d}, {[0].x}'.format(*strings)  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\") \\\n                                  # E: \"str\" has no attribute \"x\"\n# TODO: this is a runtime error, but error message is confusing\n'{[0][:]:d}'.format(*strings)  # E: Syntax error in format specifier \"0[0][\"\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallMatchingKwArg]\nfrom typing import Dict\nkwargs: Dict[str, str] = {}\n'{one}, {two}'.format(one=1, two=2, **kwargs)  # Don't flag this because args may be empty\n\n'{stuff:.3d}'.format(**kwargs)  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\")\n'{stuff[0]:f}, {other}'.format(**kwargs)  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float\")\n'{stuff[0]:c}'.format(**kwargs)\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallCustomFormatSpec]\nfrom typing import Union\nclass Bad:\n    ...\nclass Good:\n    def __format__(self, spec: str) -> str: ...\n\n'{:OMG}'.format(Good())\n'{:OMG}'.format(Bad())  # E: Unrecognized format specification \"OMG\"\n'{!s:OMG}'.format(Good())  # E: Unrecognized format specification \"OMG\"\n'{:{}OMG{}}'.format(Bad(), 'too', 'dynamic')\n\nx: Union[Good, Bad]\n'{:OMG}'.format(x)  # E: Unrecognized format specification \"OMG\"\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallFormatTypes]\n'{:x}'.format(42)\n'{:E}'.format(42)\n'{:g}'.format(42)\n'{:x}'.format('no')  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\")\n'{:E}'.format('no')  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float\")\n'{:g}'.format('no')  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float\")\n'{:n}'.format(3.14)\n'{:d}'.format(3.14)  # E: Incompatible types in string interpolation (expression has type \"float\", placeholder has type \"int\")\n\n'{:s}'.format(42)\n'{:s}'.format('yes')\n\n'{:z}'.format('what')  # E: Unsupported format character \"z\"\n'{:Z}'.format('what')  # E: Unsupported format character \"Z\"\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallFormatTypesChar]\n'{:c}'.format(42)\n'{:c}'.format('no')  # E: \":c\" requires int or char\n'{:c}'.format('c')\n\nclass C:\n    ...\n'{:c}'.format(C())  # E: Incompatible types in string interpolation (expression has type \"C\", placeholder has type \"int | str\")\nx: str\n'{:c}'.format(x)\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallFormatTypesCustomFormat]\nfrom typing import Union\nclass Bad:\n    ...\nclass Good:\n    def __format__(self, spec: str) -> str: ...\n\nx: Union[Good, Bad]\ny: Union[Good, int]\nz: Union[Bad, int]\nt: Union[Good, str]\n'{:d}'.format(x)  # E: Incompatible types in string interpolation (expression has type \"Bad\", placeholder has type \"int\")\n'{:d}'.format(y)\n'{:d}'.format(z)  # E: Incompatible types in string interpolation (expression has type \"Bad\", placeholder has type \"int\")\n'{:d}'.format(t)  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\")\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallFormatTypesBytes]\nfrom typing import Union, TypeVar, NewType, Generic\n\nA = TypeVar('A', str, bytes)\nB = TypeVar('B', bound=bytes)\n\nx: Union[str, bytes]\na: str\nb: bytes\n\nN = NewType('N', bytes)\nn: N\n\n'{}'.format(a)\n'{}'.format(b)  # E: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). Otherwise, decode the bytes\n'{}'.format(x)  # E: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). Otherwise, decode the bytes\n'{}'.format(n)  # E: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). Otherwise, decode the bytes\n\nf'{b}'  # E: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). Otherwise, decode the bytes\nf'{x}'  # E: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). Otherwise, decode the bytes\nf'{n}'  # E: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). Otherwise, decode the bytes\n\nclass C(Generic[B]):\n    x: B\n    def meth(self) -> None:\n        '{}'.format(self.x)  # E: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). Otherwise, decode the bytes\n\ndef func(x: A) -> A:\n    '{}'.format(x)  # E: If x = b'abc' then f\"{x}\" or \"{}\".format(x) produces \"b'abc'\", not \"abc\". If this is desired behavior, use f\"{x!r}\" or \"{!r}\".format(x). Otherwise, decode the bytes\n    return x\n\n'{!r}'.format(a)\n'{!r}'.format(b)\n'{!r}'.format(x)\n'{!r}'.format(n)\nf'{a}'\nf'{a!r}'\nf'{b!r}'\nf'{x!r}'\nf'{n!r}'\n\nclass D(bytes):\n    def __str__(self) -> str:\n        return \"overrides __str__ of bytes\"\n\n'{}'.format(D())\n[builtins fixtures/primitives.pyi]\n\n[case testNoSpuriousFormattingErrorsDuringFailedOverlodMatch]\nfrom typing import overload, Callable\n\n@overload\ndef sub(pattern: str, repl: Callable[[str], str]) -> str: ...\n@overload\ndef sub(pattern: bytes, repl: Callable[[bytes], bytes]) -> bytes: ...\ndef sub(pattern: object, repl: object) -> object:\n    pass\n\ndef better_snakecase(text: str) -> str:\n    # Mypy used to emit a spurious error here\n    # warning about interpolating bytes into an f-string:\n    text = sub(r\"([A-Z])([A-Z]+)([A-Z](?:[^A-Z]|$))\", lambda match: f\"{match}\")\n    return text\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallFinal]\nfrom typing import Final\n\nFMT: Final = '{.x}, {:{:d}}'\n\nFMT.format(1, 2, 'no')  # E: \"int\" has no attribute \"x\" \\\n                        # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\")\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallFinalChar]\nfrom typing import Final\n\nGOOD: Final = 'c'\nBAD: Final = 'no'\nOK: Final[str] = '...'\n\n'{:c}'.format(GOOD)\n'{:c}'.format(BAD)  # E: \":c\" requires int or char\n'{:c}'.format(OK)\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallForcedConversions]\n'{!r}'.format(42)\n'{!s}'.format(42)\n'{!s:d}'.format(42)  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int\")\n'{!s:s}'.format('OK')\n'{} and {!x}'.format(0, 1)  # E: Invalid conversion type \"x\", must be one of \"r\", \"s\" or \"a\"\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallAccessorsBasic]\nfrom typing import Any\nx: Any\n\n'{.x:{[0]}}'.format('yes', 42)  # E: \"str\" has no attribute \"x\" \\\n                                # E: Value of type \"int\" is not indexable\n\n'{.1+}'.format(x)  # E: Syntax error in format specifier \"0.1+\"\n'{name.x[x]()[x]:.2f}'.format(name=x)  # E: Only index and member expressions are allowed in format field accessors; got \"name.x[x]()[x]\"\n[builtins fixtures/primitives.pyi]\n\n[case testFormatCallAccessorsIndices]\nfrom typing import TypedDict\n\nclass User(TypedDict):\n    id: int\n    name: str\n\nu: User\n'{user[name]:.3f}'.format(user=u)  # E: Incompatible types in string interpolation (expression has type \"str\", placeholder has type \"int | float\")\n\ndef f() -> str: ...\n'{[f()]}'.format(u)  # E: Invalid index expression in format field accessor \"[f()]\"\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testFormatCallFlags]\nfrom typing import Union\n\nclass Good:\n    def __format__(self, spec: str) -> str: ...\n\n'{:#}'.format(42)\n\n'{:#}'.format('no')  # E: Numeric flags are only allowed for numeric types\n'{!s:#}'.format(42)  # E: Numeric flags are only allowed for numeric types\n\n'{:#s}'.format(42)  # E: Numeric flags are only allowed for numeric types\n'{:+s}'.format(42)  # E: Numeric flags are only allowed for numeric types\n\n'{:+d}'.format(42)\n'{:#d}'.format(42)\n\nx: Union[float, Good]\n'{:+f}'.format(x)\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testFormatCallSpecialCases]\n'{:08b}'.format(int('3'))\n\nclass S:\n    def __int__(self) -> int: ...\n\n'{:+d}'.format(S())  # E: Incompatible types in string interpolation (expression has type \"S\", placeholder has type \"int\")\n'%d' % S()  # This is OK however\n'{:%}'.format(0.001)\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testEnumWithStringToFormatValue]\nfrom enum import Enum\n\nclass Responses(str, Enum):\n    TEMPLATED = 'insert {} here'\n    TEMPLATED_WITH_KW = 'insert {value} here'\n    NORMAL = 'something'\n\nResponses.TEMPLATED.format(42)\nResponses.TEMPLATED_WITH_KW.format(value=42)\nResponses.TEMPLATED.format()  # E: Cannot find replacement for positional format specifier 0\nResponses.TEMPLATED_WITH_KW.format()  # E: Cannot find replacement for named format specifier \"value\"\nResponses.NORMAL.format(42)  # E: Not all arguments converted during string formatting\nResponses.NORMAL.format(value=42)  # E: Not all arguments converted during string formatting\n[builtins fixtures/primitives.pyi]\n\n[case testNonStringEnumToFormatValue]\nfrom enum import Enum\n\nclass Responses(Enum):\n    TEMPLATED = 'insert {value} here'\n\nResponses.TEMPLATED.format(value=42)  # E: \"Responses\" has no attribute \"format\"\n[builtins fixtures/primitives.pyi]\n\n[case testStrEnumWithStringToFormatValue]\n# flags: --python-version 3.11\nfrom enum import StrEnum\n\nclass Responses(StrEnum):\n    TEMPLATED = 'insert {} here'\n    TEMPLATED_WITH_KW = 'insert {value} here'\n    NORMAL = 'something'\n\nResponses.TEMPLATED.format(42)\nResponses.TEMPLATED_WITH_KW.format(value=42)\nResponses.TEMPLATED.format()  # E: Cannot find replacement for positional format specifier 0\nResponses.TEMPLATED_WITH_KW.format()  # E: Cannot find replacement for named format specifier \"value\"\nResponses.NORMAL.format(42)  # E: Not all arguments converted during string formatting\nResponses.NORMAL.format(value=42)  # E: Not all arguments converted during string formatting\n[builtins fixtures/primitives.pyi]\n"
  },
  {
    "path": "test-data/unit/check-functions.test",
    "content": "-- Test cases for the type checker related to functions, function types and\n-- calls.\n\n-- See also check-varargs.test.\n\n\n-- Callable type basics\n-- --------------------\n\n\n[case testCallingVariableWithFunctionType]\nfrom typing import Callable\nf: Callable[[A], B]\na: A\nb: B\nif int():\n    a = f(a)    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    b = f(b)    # E: Argument 1 has incompatible type \"B\"; expected \"A\"\nif int():\n    b = f()     # E: Too few arguments\nif int():\n    b = f(a, a) # E: Too many arguments\nif int():\n    b = f(a)\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testKeywordOnlyArgumentOrderInsensitivity]\nimport typing\n\nclass A(object):\n    def f(self, *, a: int, b: str) -> None: pass\n\nclass B(A):\n    def f(self, *, b: str, a: int) -> None: pass\n\nclass C(A):\n    def f(self, *, b: int, a: str) -> None: pass  # Fail\n[out]\nmain:10: error: Argument 1 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"str\"\nmain:10: note: This violates the Liskov substitution principle\nmain:10: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\nmain:10: error: Argument 2 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\"\n\n[case testPositionalOverridingArgumentNameInsensitivity]\nimport typing\n\nclass A(object):\n    def f(self, a: int, b: str) -> None: pass\n\nclass B(A):\n    def f(self, b: str, a: int) -> None: pass # E: Argument 1 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\" \\\n                                              # N: This violates the Liskov substitution principle \\\n                                              # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides \\\n                                              # E: Argument 2 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"str\"\n\nclass C(A):\n    def f(self, foo: int, bar: str) -> None: pass\n\n\n[case testPositionalOverridingArgumentNamesCheckedWhenMismatchingPos]\nimport typing\n\nclass A(object):\n    def f(self, a: int, b: str) -> None: pass\n\nclass B(A):\n    def f(self, b: int, a: str) -> None: pass  # Fail\n[out]\nmain:7: error: Signature of \"f\" incompatible with supertype \"A\"\nmain:7: note:      Superclass:\nmain:7: note:          def f(self, a: int, b: str) -> None\nmain:7: note:      Subclass:\nmain:7: note:          def f(self, b: int, a: str) -> None\n\n[case testSubtypingFunctionTypes]\nfrom typing import Callable\n\nclass A: pass\nclass B(A): pass\n\nf: Callable[[B], A]\ng: Callable[[A], A]  # subtype of f\nh: Callable[[B], B]  # subtype of f\nif int():\n    g = h  # E: Incompatible types in assignment (expression has type \"Callable[[B], B]\", variable has type \"Callable[[A], A]\")\nif int():\n    h = f  # E: Incompatible types in assignment (expression has type \"Callable[[B], A]\", variable has type \"Callable[[B], B]\")\nif int():\n    h = g  # E: Incompatible types in assignment (expression has type \"Callable[[A], A]\", variable has type \"Callable[[B], B]\")\nif int():\n    g = f  # E: Incompatible types in assignment (expression has type \"Callable[[B], A]\", variable has type \"Callable[[A], A]\")\nif int():\n    f = g\nif int():\n    f = h\nif int():\n    f = f\nif int():\n    g = g\nif int():\n    h = h\n\n[case testSubtypingFunctionsDoubleCorrespondence]\ndef l(x) -> None: ...\ndef r(__x, *, x) -> None: ...\nr = l  # E: Incompatible types in assignment (expression has type \"Callable[[Any], None]\", variable has type \"def r(Any, /, *, x: Any) -> None\")\n\n[case testSubtypingFunctionsDoubleCorrespondenceNamedOptional]\ndef l(x) -> None: ...\ndef r(__x, *, x = 1) -> None: ...\nr = l  # E: Incompatible types in assignment (expression has type \"Callable[[Any], None]\", variable has type \"def r(Any, /, *, x: Any = ...) -> None\")\n\n[case testSubtypingFunctionsDoubleCorrespondenceBothNamedOptional]\ndef l(x = 1) -> None: ...\ndef r(__x, *, x = 1) -> None: ...\nr = l  # E: Incompatible types in assignment (expression has type \"Callable[[Any], None]\", variable has type \"def r(Any, /, *, x: Any = ...) -> None\")\n\n[case testSubtypingFunctionsTrivialSuffixRequired]\ndef l(__x) -> None: ...\ndef r(x, *args, **kwargs) -> None: ...\n\nr = l  # E: Incompatible types in assignment (expression has type \"Callable[[Any], None]\", variable has type \"def r(x: Any, *args: Any, **kwargs: Any) -> None\")\n[builtins fixtures/dict.pyi]\n\n[case testSubtypingFunctionsTrivialSuffixOptional]\ndef l(__x = 1) -> None: ...\ndef r(x = 1, *args, **kwargs) -> None: ...\n\nr = l  # E: Incompatible types in assignment (expression has type \"def l(Any = ..., /) -> None\", variable has type \"def r(x: Any = ..., *args: Any, **kwargs: Any) -> None\")\n[builtins fixtures/dict.pyi]\n\n[case testSubtypingFunctionsRequiredLeftArgNotPresent]\ndef l(x, y) -> None: ...\ndef r(x) -> None: ...\nr = l  # E: Incompatible types in assignment (expression has type \"Callable[[Any, Any], None]\", variable has type \"Callable[[Any], None]\")\n\n[case testSubtypingFunctionsImplicitNames]\nfrom typing import Any\n\ndef f(a, b): pass\ndef g(c: Any, d: Any) -> Any: pass\n\nff = f\ngg = g\n\ngg = f\nff = g\n\n[case testSubtypingFunctionsDefaultsNames]\nfrom typing import Callable\n\ndef f(a: int, b: str) -> None: pass\nf_nonames: Callable[[int, str], None]\ndef g(a: int, b: str = \"\") -> None: pass\ndef h(aa: int, b: str = \"\") -> None: pass\n\nff_nonames = f_nonames\nff = f\ngg = g\nhh = h\n\nif int():\n    ff = gg\nif int():\n    ff_nonames = ff\nif int():\n    ff_nonames = f_nonames # reset\nif int():\n    ff = ff_nonames # E: Incompatible types in assignment (expression has type \"Callable[[int, str], None]\", variable has type \"def f(a: int, b: str) -> None\")\nif int():\n    ff = f # reset\nif int():\n    gg = ff # E: Incompatible types in assignment (expression has type \"def f(a: int, b: str) -> None\", variable has type \"def g(a: int, b: str = ...) -> None\")\nif int():\n    gg = hh # E: Incompatible types in assignment (expression has type \"def h(aa: int, b: str = ...) -> None\", variable has type \"def g(a: int, b: str = ...) -> None\")\n\n[case testSubtypingFunctionsArgsKwargs]\nfrom typing import Any, Callable\n\ndef everything(*args: Any, **kwargs: Any) -> None: pass\neverywhere: Callable[..., None]\n\ndef specific_1(a: int, b: str) -> None: pass\ndef specific_2(a: int, *, b: str) -> None: pass\n\nss_1 = specific_1\nss_2 = specific_2\nee_def = everything\nee_var = everywhere\n\nif int():\n    ss_1 = ee_def\nif int():\n    ss_1 = specific_1\nif int():\n    ss_2 = ee_def\nif int():\n    ss_2 = specific_2\nif int():\n    ee_def = everywhere\nif int():\n    ee_def = everything\nif int():\n    ee_var = everything\nif int():\n    ee_var = everywhere\n\nif int():\n    ee_var = specific_1\nif int():\n    ee_def = specific_1\n\n[builtins fixtures/dict.pyi]\n\n[case testSubtypingFunctionsDecorated]\nfrom typing import Any\n\n# untyped decorator\ndef deco(f): pass\n\nclass A:\n    @deco\n    def f(self) -> Any:\n        pass\n\nclass B(A):\n    @deco\n    def f(self) -> Any:\n        pass\n\n[builtins fixtures/list.pyi]\n\n\n[case testLackOfNames]\ndef f(__a: int, __b: str) -> None: pass\ndef g(a: int, b: str) -> None: pass\n\nff = f\ngg = g\n\nif int():\n    ff = g\nif int():\n    gg = f # E: Incompatible types in assignment (expression has type \"Callable[[int, str], None]\", variable has type \"def g(a: int, b: str) -> None\")\n\n[case testLackOfNamesFastparse]\ndef f(__a: int, __b: str) -> None: pass\ndef g(a: int, b: str) -> None: pass\n\nff = f\ngg = g\n\nif int():\n    ff = g\nif int():\n    gg = f # E: Incompatible types in assignment (expression has type \"Callable[[int, str], None]\", variable has type \"def g(a: int, b: str) -> None\")\n\n[case testFunctionTypeCompatibilityWithOtherTypes]\n# flags: --no-strict-optional\nfrom typing import Callable\nf = None # type: Callable[[], None]\na, o = None, None # type: (A, object)\nif int():\n    a = f   # E: Incompatible types in assignment (expression has type \"Callable[[], None]\", variable has type \"A\")\nif int():\n    f = a   # E: Incompatible types in assignment (expression has type \"A\", variable has type \"Callable[[], None]\")\nif int():\n    f = o   # E: Incompatible types in assignment (expression has type \"object\", variable has type \"Callable[[], None]\")\nif int():\n    f = f() # E: Function does not return a value (it only ever returns None)\n\nif int():\n    f = f\nif int():\n    f = None\nif int():\n    o = f\n\nclass A: pass\n[builtins fixtures/tuple.pyi]\n\n[case testReturnEmptyTuple]\nfrom typing import Tuple\ndef f(x): # type: (int) -> () # E: Syntax error in type annotation \\\n                              # N: Suggestion: Use Tuple[()] instead of () for an empty tuple, or None for a function without a return value\n   pass\n\ndef g(x: int) -> Tuple[()]:\n   pass\n[builtins fixtures/tuple.pyi]\n\n[case testFunctionSubtypingWithVoid]\nfrom typing import Callable\nf: Callable[[], None]\ng: Callable[[], object]\nif int():\n    f = g  # E: Incompatible types in assignment (expression has type \"Callable[[], object]\", variable has type \"Callable[[], None]\")\nif int():\n    g = f  # OK\n\nif int():\n    f = f\nif int():\n    g = g\n\n[case testFunctionSubtypingWithMultipleArgs]\nfrom typing import Callable\nf: Callable[[A, A], None]\ng: Callable[[A, B], None]\nh: Callable[[B, B], None]\nif int():\n    f = g  # E: Incompatible types in assignment (expression has type \"Callable[[A, B], None]\", variable has type \"Callable[[A, A], None]\")\nif int():\n    f = h  # E: Incompatible types in assignment (expression has type \"Callable[[B, B], None]\", variable has type \"Callable[[A, A], None]\")\nif int():\n    g = h  # E: Incompatible types in assignment (expression has type \"Callable[[B, B], None]\", variable has type \"Callable[[A, B], None]\")\nif int():\n    g = f\nif int():\n    h = f\nif int():\n    h = g\nif int():\n    f = f\nif int():\n    g = g\nif int():\n    h = h\n\nclass A: pass\nclass B(A): pass\n\n[case testFunctionTypesWithDifferentArgumentCounts]\nfrom typing import Callable\nf: Callable[[], None]\ng: Callable[[A], None]\nh: Callable[[A, A], None]\n\nif int():\n    f = g   # E: Incompatible types in assignment (expression has type \"Callable[[A], None]\", variable has type \"Callable[[], None]\")\nif int():\n    f = h   # E: Incompatible types in assignment (expression has type \"Callable[[A, A], None]\", variable has type \"Callable[[], None]\")\nif int():\n    h = f   # E: Incompatible types in assignment (expression has type \"Callable[[], None]\", variable has type \"Callable[[A, A], None]\")\nif int():\n    h = g   # E: Incompatible types in assignment (expression has type \"Callable[[A], None]\", variable has type \"Callable[[A, A], None]\")\n\nif int():\n    f = f\nif int():\n    g = g\nif int():\n    h = h\n\nclass A: pass\n[out]\n\n[case testCompatibilityOfSimpleTypeObjectWithStdType]\nclass A:\n    def __init__(self, a: 'A') -> None: pass\n\ndef f() -> None: pass\n\nt: type\na: A\n\nif int():\n    a = A # E: Incompatible types in assignment (expression has type \"type[A]\", variable has type \"A\")\nif int():\n    t = f # E: Incompatible types in assignment (expression has type \"Callable[[], None]\", variable has type \"type\")\nif int():\n    t = A\n\n[case testFunctionTypesWithOverloads]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Callable, overload\nf: Callable[[AA], A]\ng: Callable[[B], B]\nh: Callable[[A], AA]\n\nif int():\n    h = i  # E: Incompatible types in assignment (expression has type overloaded function, variable has type \"Callable[[A], AA]\")\nif int():\n    f = j\n\nif int():\n    f = i\nif int():\n    g = i\nif int():\n    g = j\n\nclass A: pass\nclass AA(A): pass\n\nclass B: pass\n\n@overload\ndef i(x: AA) -> A:\n    pass\n@overload\ndef i(x: B) -> B:\n    pass\n\n@overload\ndef j(x: B) -> B:\n    pass\n@overload\ndef j(x: A) -> AA:\n    pass\n\n[case testOverloadWithThreeItems]\nfrom foo import *\n[file foo.pyi]\nfrom typing import Callable, overload\ng1: Callable[[A], A]\ng2: Callable[[B], B]\ng3: Callable[[C], C]\ng4: Callable[[A], B]\na: A\nb: B\nc: C\n\nif int():\n    b = f(a)  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    a = f(b)  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    b = f(c)  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\nif int():\n    g4 = f    # E: Incompatible types in assignment (expression has type overloaded function, variable has type \"Callable[[A], B]\")\n\nif int():\n    g1 = f\nif int():\n    g2 = f\nif int():\n    g3 = f\nif int():\n    a = f(a)\nif int():\n    b = f(b)\nif int():\n    c = f(c)\n\nclass A: pass\nclass B: pass\nclass C: pass\n\n@overload\ndef f(x: A) -> A: pass\n@overload\ndef f(x: B) -> B: pass\n@overload\ndef f(x: C) -> C: pass\n[builtins fixtures/tuple.pyi]\n\n[case testInferConstraintsUnequalLengths]\nfrom typing import Any, Callable, List\ndef f(fields: List[Callable[[Any], Any]]): pass\nclass C: pass\nf([C])  # E: List item 0 has incompatible type \"type[C]\"; expected \"Callable[[Any], Any]\"\nclass D:\n    def __init__(self, a, b): pass\nf([D])  # E: List item 0 has incompatible type \"type[D]\"; expected \"Callable[[Any], Any]\"\n[builtins fixtures/list.pyi]\n\n[case testSubtypingTypeTypeAsCallable]\nfrom typing import Callable, Type\nclass A: pass\nx: Callable[..., A]\ny: Type[A]\nx = y\n\n[case testSubtypingCallableAsTypeType]\nfrom typing import Callable, Type\nclass A: pass\nx: Callable[..., A]\ny: Type[A]\nif int():\n    y = x  # E: Incompatible types in assignment (expression has type \"Callable[..., A]\", variable has type \"type[A]\")\n\n-- Default argument values\n-- -----------------------\n\n\n[case testCallingFunctionsWithDefaultArgumentValues]\n# flags: --implicit-optional --no-strict-optional\nclass A: pass\nclass AA(A): pass\nclass B: pass\n\ndef f(x: 'A'  =  None) -> 'B': pass\n\na, b = None, None # type: (A, B)\nif int():\n    a = f()     # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    b = f(b)    # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A | None\"\nif int():\n    b = f(a, a) # E: Too many arguments for \"f\"\n\nif int():\n    b = f()\nif int():\n    b = f(a)\nif int():\n    b = f(AA())\n\n[builtins fixtures/tuple.pyi]\n\n[case testDefaultParameterExpressions]\nimport typing\nclass B: pass\nclass A: pass\n\ndef f(x: 'A' = A()) -> None:\n    b = x # type: B # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    a = x # type: A\n[out]\n\n[case testDefaultParameterExpressions2]\nimport typing\nclass B: pass\nclass A: pass\n\ndef f(x: 'A' = B()) -> None: # E: Incompatible default for parameter \"x\" (default has type \"B\", parameter has type \"A\")\n    b = x # type: B      # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    a = x # type: A\n[case testDefaultParameterExpressionsGeneric]\nfrom typing import TypeVar\nT = TypeVar('T', bound='A')\n\nclass B: pass\nclass A: pass\n\ndef f(x: T = B()) -> None: # E: Incompatible default for parameter \"x\" (default has type \"B\", parameter has type \"T\")\n    b = x # type: B      # E: Incompatible types in assignment (expression has type \"T\", variable has type \"B\")\n    a = x # type: A\n[case testDefaultParametersWithSubtypes]\nimport typing\nclass A: pass\nclass B(A): pass\n\ndef f(x: 'B' = A()) -> None: # E: Incompatible default for parameter \"x\" (default has type \"A\", parameter has type \"B\")\n    pass\ndef g(x: 'A' = B()) -> None:\n    pass\n[out]\n\n[case testMultipleDefaultParameterExpressions]\nimport typing\nclass A: pass\nclass B: pass\n\ndef f(x: 'A' = B(), y: 'B' = B()) -> None: # E: Incompatible default for parameter \"x\" (default has type \"B\", parameter has type \"A\")\n    pass\ndef h(x: 'A' = A(), y: 'B' = B()) -> None:\n    pass\n[out]\n\n[case testMultipleDefaultParameterExpressions2]\nimport typing\nclass A: pass\nclass B: pass\n\ndef g(x: 'A' = A(), y: 'B' = A()) -> None: # E: Incompatible default for parameter \"y\" (default has type \"A\", parameter has type \"B\")\n    pass\n[out]\n\n[case testDefaultArgumentsAndSignatureAsComment]\nimport typing\ndef f(x = 1): # type: (int) -> str\n    pass\nf()\nf(1)\nf('') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\n[case testMethodDefaultArgumentsAndSignatureAsComment]\nimport typing\nclass A:\n    def f(self, x = 1): # type: (int) -> str\n        pass\nA().f()\nA().f(1)\nA().f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\n\n-- Access to method defined as a data attribute\n-- --------------------------------------------\n\n\n[case testMethodAsDataAttribute]\nfrom typing import Any, Callable, ClassVar\nclass B: pass\nx: Any\nclass A:\n    f = x # type: ClassVar[Callable[[A], None]]\n    g = x # type: ClassVar[Callable[[A, B], None]]\na: A\na.f()\na.g(B())\na.f(a) # E: Too many arguments\na.g()  # E: Too few arguments\n\n[case testMethodWithInvalidMethodAsDataAttribute]\nfrom typing import Any, Callable, ClassVar\nclass B: pass\nx: Any\nclass A:\n    f = x # type: ClassVar[Callable[[], None]]\n    g = x # type: ClassVar[Callable[[B], None]]\na: A\na.f() # E: Attribute function \"f\" with type \"Callable[[], None]\" does not accept self argument\na.g() # E: Invalid self argument \"A\" to attribute function \"g\" with type \"Callable[[B], None]\"\n\n[case testMethodWithDynamicallyTypedMethodAsDataAttribute]\nfrom typing import Any, Callable, ClassVar\nclass B: pass\nx: Any\nclass A:\n    f = x # type: ClassVar[Callable[[Any], Any]]\na: A\na.f()\na.f(a) # E: Too many arguments\n\n[case testMethodWithInferredMethodAsDataAttribute]\nfrom typing import Any\ndef m(self: \"A\") -> int: ...\n\nclass A:\n    n = m\n\na = A()\nreveal_type(a.n())  # N: Revealed type is \"builtins.int\"\nreveal_type(A.n(a))  # N: Revealed type is \"builtins.int\"\nA.n()  # E: Too few arguments\n\n[case testOverloadedMethodAsDataAttribute]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\nclass B: pass\nclass A:\n    @overload\n    def f(self) -> None: pass\n    @overload\n    def f(self, b: B) -> None: pass\n    g = f\na: A\na.g()\na.g(B())\na.g(a) # E: No overload variant matches argument type \"A\" \\\n       # N: Possible overload variants: \\\n       # N:     def f(self) -> None \\\n       # N:     def f(self, b: B) -> None\n\n[case testMethodAsDataAttributeInferredFromDynamicallyTypedMethod]\n\nclass A:\n    def f(self, x): pass\n    g = f\na: A\na.g(object())\na.g(a, a) # E: Too many arguments\na.g()     # E: Too few arguments\n\n[case testMethodAsDataAttributeInGenericClass]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass B: pass\nclass A(Generic[t]):\n    def f(self, x: t) -> None: pass\n    g = f\na: A[B]\na.g(B())\na.g(a)   # E: Argument 1 has incompatible type \"A[B]\"; expected \"B\"\n\n[case testInvalidMethodAsDataAttributeInGenericClass]\nfrom typing import Any, TypeVar, Generic, Callable, ClassVar\nt = TypeVar('t')\nclass B: pass\nclass C: pass\nx: Any\nclass A(Generic[t]):\n    f = x # type: ClassVar[Callable[[A[B]], None]]\nab: A[B]\nac: A[C]\nab.f()\nac.f()   # E: Invalid self argument \"A[C]\" to attribute function \"f\" with type \"Callable[[A[B]], None]\"\n\n[case testPartiallyTypedSelfInMethodDataAttribute]\nfrom typing import Any, TypeVar, Generic, Callable, ClassVar\nt = TypeVar('t')\nclass B: pass\nclass C: pass\nx: Any\nclass A(Generic[t]):\n    f = x # type: ClassVar[Callable[[A], None]]\nab: A[B]\nac: A[C]\nab.f()\nac.f()\n\n[case testCallableDataAttribute]\nfrom typing import Callable, ClassVar\nclass A:\n    g: ClassVar[Callable[[A], None]]\n    def __init__(self, f: Callable[[], None]) -> None:\n        self.f = f\na = A(lambda: None)\na.f()\na.g()\na.f(a) # E: Too many arguments\na.g(a) # E: Too many arguments\n\n\n-- Nested functions\n-- ----------------\n\n\n[case testSimpleNestedFunction]\nimport typing\ndef f(a: 'A') -> None:\n    def g(b: 'B') -> None:\n        if int():\n            b = a \\\n            # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n            aa = a # type: A # ok\n            b = B()\n    g(a) # E: Argument 1 to \"g\" has incompatible type \"A\"; expected \"B\"\n    g(B())\nclass A: pass\nclass B: pass\n\n[case testReturnAndNestedFunction]\nimport typing\ndef f() -> 'A':\n    def g() -> 'B':\n        return A() # fail\n        return B()\n    return B() # fail\n    return A()\nclass A: pass\nclass B: pass\n[out]\nmain:4: error: Incompatible return value type (got \"A\", expected \"B\")\nmain:6: error: Incompatible return value type (got \"B\", expected \"A\")\n\n[case testDynamicallyTypedNestedFunction]\nimport typing\ndef f(x: object) -> None:\n    def g(y):\n        pass\n    g() # E: Missing positional argument \"y\" in call to \"g\"\n    g(x)\n[out]\n\n[case testNestedFunctionInMethod]\nimport typing\nclass A:\n    def f(self) -> None:\n        def g(x: int) -> None:\n            y = x # type: int\n            a = x # type: A # fail\n        g(2)\n        g(A()) # fail\n[out]\nmain:6: error: Incompatible types in assignment (expression has type \"int\", variable has type \"A\")\nmain:8: error: Argument 1 to \"g\" has incompatible type \"A\"; expected \"int\"\n\n[case testNestedFunctionInMethodWithTooFewArgumentsInTypeComment_no_native_parse]\nclass A:\n    def f(self):\n        # type: () -> None\n        def g(x):  # E: Type signature has too few parameters\n            # type: () -> None\n            pass\n\n[case testNestedFunctionInMethodCannotAccessEnclosingClassAttributes]\nclass A:\n    var: int\n    import mod\n    class B: ...\n\n    def method(self) -> None:\n        def f1(arg: object) -> None:\n            arg.var  # E: \"object\" has no attribute \"var\"\n            arg.mod  # E: \"object\" has no attribute \"mod\"\n            arg.B  # E: \"object\" has no attribute \"B\"\n[file mod.py]\n\n[case testDeepNestedFunctionWithTooFewArgumentsInTypeComment_no_native_parse]\nclass A:\n    def f(self):\n        # type: () -> None\n        class B:\n            def g(self):\n                # type: () -> None\n                def h(x):  # E: Type signature has too few parameters\n                    # type: () -> None\n                    pass\n\n[case testDeepNestedMethodInTypeComment]\nclass A:\n    def f(self):\n        # type: () -> None\n        class B:\n            class C:\n                def g(self):\n                    # type: () -> None\n                    pass\n\n[case testMutuallyRecursiveNestedFunctions]\ndef f() -> None:\n    def g() -> None:\n        h(1)\n        h('') # E\n    def h(x: int) -> None:\n        g()\n        g(1) # E\n[out]\nmain:4: error: Argument 1 to \"h\" has incompatible type \"str\"; expected \"int\"\nmain:7: error: Too many arguments for \"g\"\n\n[case testMutuallyRecursiveDecoratedFunctions]\nfrom typing import Callable, Any\ndef dec(f) -> Callable[..., Any]: pass\ndef f() -> None:\n    @dec\n    def g() -> None:\n        h()\n        h.x # E\n    @dec\n    def h(x: int) -> None:\n        g(1)\n        g.x # E\n[out]\nmain:7: error: \"Callable[..., Any]\" has no attribute \"x\"\nmain:11: error: \"Callable[..., Any]\" has no attribute \"x\"\n\n[case testNestedGenericFunctions]\nfrom typing import TypeVar\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef outer(x: T) -> T:\n    def inner(y: U) -> T: ...\n    return inner(1)\n\n\n-- Casts\n-- -----\n\n\n[case testCastsToAndFromFunctionTypes]\nfrom typing import TypeVar, Callable, Any, cast\nt = TypeVar('t')\ndef f(x: t,\n      f1: Callable[[], None],\n      f2: Callable[[Any], None], o: object) -> None:\n    x = cast(t, f1)\n    f1 = cast(Callable[[], None], x)\n    f1 = cast(Callable[[], None], f2)\n    f1 = cast(Callable[[], None], o)\n\n\n-- Function decorators\n-- -------------------\n\n\n[case testTrivialStaticallyTypedFunctionDecorator]\nfrom typing import TypeVar\nt = TypeVar('t')\ndef dec(f: t) -> t:\n    return f\n@dec\ndef f(x: int) -> None: pass\nf(1)\nf('x') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\n[case testTrivialStaticallyTypedMethodDecorator]\nfrom typing import TypeVar\nt = TypeVar('t')\ndef dec(f: t) -> t:\n    return f\nclass A:\n    @dec\n    def f(self, x: int) -> None: pass\nA().f(1)\nA().f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\nclass B: pass\n\n[case testTrivialDecoratedNestedFunction]\nfrom typing import TypeVar\nt = TypeVar('t')\ndef dec(f: t) -> t:\n    return f\ndef g() -> None:\n    @dec\n    def f(x: int) -> None: pass\n    f(1)\n    f('') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n[out]\n\n[case testCheckingDecoratedFunction]\nimport typing\ndef dec(f): pass\n@dec\ndef f(x: 'A') -> None:\n    a = x # type: A\n    if int():\n        x = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nclass A: pass\n[out]\n\n[case testDecoratorThatSwitchesType]\nfrom typing import Callable\ndef dec(x) -> Callable[[], None]: pass\n@dec\ndef f(y): pass\nf()\nf(None) # E: Too many arguments for \"f\"\n\n[case testDecoratorThatSwitchesTypeWithMethod]\nfrom typing import Any, Callable\ndef dec(x) -> Callable[[Any], None]: pass\nclass A:\n    @dec\n    def f(self, a, b, c): pass\na: A\na.f()\na.f(None) # E: Too many arguments for \"f\" of \"A\"\n\n[case testNestedDecorators]\nfrom typing import Any, Callable\ndef dec1(f: Callable[[Any], None]) -> Callable[[], None]: pass\ndef dec2(f: Callable[[Any, Any], None]) -> Callable[[Any], None]: pass\n@dec1\n@dec2\ndef f(x, y): pass\nf()\nf(None) # E: Too many arguments for \"f\"\n\n[case testInvalidDecorator1]\nfrom typing import Any, Callable\ndef dec1(f: Callable[[Any], None]) -> Callable[[], None]: pass\ndef dec2(f: Callable[[Any, Any], None]) -> Callable[[Any], None]: pass\n@dec1\n@dec2  # E: Argument 1 to \"dec2\" has incompatible type \"Callable[[Any], Any]\"; expected \"Callable[[Any, Any], None]\"\ndef f(x): pass\n\ndef faulty(c: Callable[[int], None]) -> Callable[[tuple[int, int]], None]:\n    return lambda x: None\n\n@faulty  # E: Argument 1 to \"faulty\" has incompatible type \"Callable[[tuple[int, int]], None]\"; expected \"Callable[[int], None]\"\n@faulty  # E: Argument 1 to \"faulty\" has incompatible type \"Callable[[str], None]\"; expected \"Callable[[int], None]\"\ndef g(x: str) -> None:\n    return None\n[builtins fixtures/tuple.pyi]\n\n[case testInvalidDecorator2]\nfrom typing import Any, Callable\ndef dec1(f: Callable[[Any, Any], None]) -> Callable[[], None]: pass\ndef dec2(f: Callable[[Any, Any], None]) -> Callable[[Any], None]: pass\n@dec1 # E: Argument 1 to \"dec1\" has incompatible type \"Callable[[Any], None]\"; expected \"Callable[[Any, Any], None]\"\n@dec2\ndef f(x, y): pass\n\n[case testNoTypeCheckDecoratorOnMethod1]\nfrom typing import no_type_check\n\n@no_type_check\ndef foo(x: 'bar', y: {'x': 4}) -> 42:\n    1 + 'x'\n[typing fixtures/typing-medium.pyi]\n\n[case testNoTypeCheckDecoratorOnMethod2]\nimport typing\n\n@typing.no_type_check\ndef foo(x: 's', y: {'x': 4}) -> 42:\n    1 + 'x'\n\n@typing.no_type_check\ndef bar() -> None:\n    1 + 'x'\n[typing fixtures/typing-medium.pyi]\n\n[case testCallingNoTypeCheckFunction]\nimport typing\n\n@typing.no_type_check\ndef foo(x: {1:2}) -> [1]:\n    1 + 'x'\n\nfoo()\nfoo(1, 'b')\n[typing fixtures/typing-medium.pyi]\n\n[case testCallingNoTypeCheckFunction2]\nimport typing\n\ndef f() -> None:\n    foo()\n\n@typing.no_type_check\ndef foo(x: {1:2}) -> [1]:\n    1 + 'x'\n[typing fixtures/typing-medium.pyi]\n\n[case testNoTypeCheckDecoratorSemanticError]\nimport typing\n\n@typing.no_type_check\ndef foo(x: {1:2}) -> [1]:\n    x = y\n[typing fixtures/typing-medium.pyi]\n\n\n-- Forward references to decorated functions\n-- -----------------------------------------\n\n\n[case testForwardReferenceToDynamicallyTypedDecorator]\ndef f(self) -> None:\n    g()\n    g(1)\n\ndef dec(f):\n    return f\n\n@dec\ndef g():\n    pass\n\n[case testForwardReferenceToDecoratorWithAnyReturn]\nfrom typing import Any\n\ndef f(self) -> None:\n    g()\n    g(1)\n\ndef dec(f) -> Any:\n    return f\n\n@dec\ndef g():\n    pass\n\n[case testForwardReferenceToDecoratorWithIdentityMapping]\nfrom typing import TypeVar\n\ndef f(self) -> None:\n    g()\n    g(1) # E: Too many arguments for \"g\"\n    h(1).x # E: \"str\" has no attribute \"x\"\n    h('') # E: Argument 1 to \"h\" has incompatible type \"str\"; expected \"int\"\n\nT = TypeVar('T')\ndef dec(f: T) -> T:\n    return f\n\n@dec\ndef g(): pass\n@dec\ndef h(x: int) -> str: pass\n[out]\n\n[case testForwardReferenceToDynamicallyTypedDecoratedMethod]\ndef f(self) -> None:\n    A().f(1).y\n    A().f()\n\nclass A:\n    @dec\n    def f(self, x): pass\n\ndef dec(f): return f\n[builtins fixtures/staticmethod.pyi]\n\n[case testForwardReferenceToStaticallyTypedDecoratedMethod]\nfrom typing import TypeVar\n\ndef f(self) -> None:\n    A().f(1).y # E: \"str\" has no attribute \"y\"\n    A().f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\nclass A:\n    @dec\n    def f(self, a: int) -> str: return ''\n\nT = TypeVar('T')\ndef dec(f: T) -> T: return f\n[builtins fixtures/staticmethod.pyi]\n[out]\n\n[case testForwardReferenceToDynamicallyTypedProperty]\ndef f(self) -> None:\n    A().x.y\n\nclass A:\n    @property\n    def x(self): pass\n[builtins fixtures/property.pyi]\n\n[case testForwardReferenceToStaticallyTypedProperty]\ndef f(self) -> None:\n    A().x.y # E: \"int\" has no attribute \"y\"\n\nclass A:\n    @property\n    def x(self) -> int: return 1\n[builtins fixtures/property.pyi]\n[out]\n\n[case testForwardReferenceToDynamicallyTypedStaticMethod]\ndef f(self) -> None:\n    A.x(1).y\n    A.x() # E: Missing positional argument \"x\" in call to \"x\"\n\nclass A:\n    @staticmethod\n    def x(x): pass\n[builtins fixtures/staticmethod.pyi]\n[out]\n\n[case testForwardReferenceToStaticallyTypedStaticMethod]\ndef f(self) -> None:\n    A.x(1).y # E: \"str\" has no attribute \"y\"\n    A.x('') # E: Argument 1 to \"x\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\nclass A:\n    @staticmethod\n    def x(a: int) -> str: return ''\n[builtins fixtures/staticmethod.pyi]\n[out]\n\n[case testForwardReferenceToDynamicallyTypedClassMethod]\ndef f(self) -> None:\n    A.x(1).y\n    A.x() # E: Missing positional argument \"a\" in call to \"x\"\n\nclass A:\n    @classmethod\n    def x(cls, a): pass\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testForwardReferenceToStaticallyTypedClassMethod]\ndef f(self) -> None:\n    A.x(1).y # E: \"str\" has no attribute \"y\"\n    A.x('') # E: Argument 1 to \"x\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\nclass A:\n    @classmethod\n    def x(cls, x: int) -> str: return ''\n[builtins fixtures/classmethod.pyi]\n[out]\n\n[case testForwardReferenceToDecoratedFunctionUsingMemberExpr]\nimport m\n\ndef f(self) -> None:\n    g(1).x # E: \"str\" has no attribute \"x\"\n\n@m.dec\ndef g(x: int) -> str: pass\n[file m.py]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef dec(f: T) -> T:\n    return f\n[out]\n\n[case testForwardReferenceToFunctionWithMultipleDecorators]\n# flags: --disable-error-code=used-before-def\ndef f(self) -> None:\n    g()\n    g(1)\n\ndef dec(f):\n    return f\n\n@dec\n@dec2\ndef g():\n    pass\n\ndef dec2(f):\n    return f\n\n[case testForwardReferenceToDynamicallyTypedDecoratedStaticMethod]\ndef f(self) -> None:\n    A().f(1).y\n    A().f()\n    A().g(1).y\n    A().g()\n\nclass A:\n    @dec\n    @staticmethod\n    def f(self, x): pass\n    @staticmethod\n    @dec\n    def g(self, x): pass\n\ndef dec(f): return f\n[builtins fixtures/staticmethod.pyi]\n\n[case testForwardRefereceToDecoratedFunctionWithCallExpressionDecorator]\n# flags: --disable-error-code=used-before-def\ndef f(self) -> None:\n    g()\n    g(1)\n\n@dec(1)\ndef g(): pass\n\ndef dec(f): pass\n\n\n-- Decorator functions in import cycles\n-- ------------------------------------\n\n\n[case testDecoratorWithIdentityTypeInImportCycle]\nimport a\n\n[file a.py]\nimport b\nfrom d import dec\n@dec\ndef f(x: int) -> None: pass\nb.g(1)  # E: Argument 1 to \"g\" has incompatible type \"int\"; expected \"str\"\n\n[file b.py]\nimport a\nfrom d import dec\n@dec\ndef g(x: str) -> None: pass\na.f('')  # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\n[file d.py]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef dec(f: T) -> T: return f\n\n[case testDecoratorWithNoAnnotationInImportCycle]\nimport a\n\n[file a.py]\nimport b\nfrom d import dec\n@dec\ndef f(x: int) -> None: pass\nb.g(1, z=4)\n\n[file b.py]\nimport a\nfrom d import dec\n@dec\ndef g(x: str) -> None: pass\na.f('', y=2)\n\n[file d.py]\ndef dec(f): return f\n\n[case testDecoratorWithFixedReturnTypeInImportCycle]\nimport a\n\n[file a.py]\nimport b\nfrom d import dec\n@dec\ndef f(x: int) -> str: pass\nb.g(1)()  # E: \"str\" not callable\n\n[file b.py]\nimport a\nfrom d import dec\n@dec\ndef g(x: int) -> str: pass\na.f(1)()  # E: \"str\" not callable\n\n[file d.py]\nfrom typing import Callable\ndef dec(f: Callable[[int], str]) -> Callable[[int], str]: return f\n\n[case testDecoratorWithCallAndFixedReturnTypeInImportCycle]\nimport a\n\n[file a.py]\nimport b\nfrom d import dec\n@dec()\ndef f(x: int) -> str: pass\nb.g(1)()  # E: \"str\" not callable\n\n[file b.py]\nimport a\nfrom d import dec\n@dec()\ndef g(x: int) -> str: pass\na.f(1)()  # E: \"str\" not callable\n\n[file d.py]\nfrom typing import Callable\ndef dec() -> Callable[[Callable[[int], str]], Callable[[int], str]]: pass\n\n[case testDecoratorWithCallAndFixedReturnTypeInImportCycleAndDecoratorArgs]\nimport a\n\n[file a.py]\nimport b\nfrom d import dec\n@dec(1)  # E: Argument 1 to \"dec\" has incompatible type \"int\"; expected \"str\"\ndef f(x: int) -> str: pass\nb.g(1)()  # E: \"str\" not callable\n\n[file b.py]\nimport a\nfrom d import dec\n@dec(1)  # E: Argument 1 to \"dec\" has incompatible type \"int\"; expected \"str\"\ndef g(x: int) -> str: pass\na.f(1)()  # E: \"str\" not callable\n\n[file d.py]\nfrom typing import Callable\ndef dec(x: str) -> Callable[[Callable[[int], str]], Callable[[int], str]]: pass\n\n[case testUndefinedDecoratorInImportCycle]\n# cmd: mypy -m foo.base\n[file foo/__init__.py]\nimport foo.base\nclass Derived(foo.base.Base):\n    def method(self) -> None: pass\n[file foo/base.py]\nimport foo\nclass Base:\n    @decorator\n    def method(self) -> None: pass\n[out]\ntmp/foo/base.py:3: error: Name \"decorator\" is not defined\n\n\n-- Conditional function definition\n-- -------------------------------\n\n\n[case testTypeCheckBodyOfConditionalFunction]\nfrom typing import Any\nx = None # type: Any\nif x:\n    def f(x: int) -> None:\n        if int():\n            x = 1\n            x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[out]\n\n[case testCallConditionalFunction]\nfrom typing import Any\nx = None # type: Any\nif x:\n    def f(x: int) -> None:  pass\n    f(1)\n    f('x') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\nf(1)\nf('x') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\n[case testConditionalFunctionDefinitionWithIfElse]\nfrom typing import Any\nx = None # type: Any\nif x:\n    def f(x: int) -> None:\n        'x' + x   # fail\n        if int():\n            x = 1\nelse:\n    def f(x: int) -> None:\n        x + 'x'   # fail\n        if int():\n            x = 1\nf(1)\nf('x') # fail\n[builtins fixtures/primitives.pyi]\n[out]\nmain:5: error: Unsupported operand types for + (\"str\" and \"int\")\nmain:10: error: Unsupported operand types for + (\"int\" and \"str\")\nmain:14: error: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\n[case testNestedConditionalFunctionDefinitionWithIfElse]\nfrom typing import Any\nx = None # type: Any\ndef top() -> None:\n    if x:\n        def f(x: int) -> None:\n            if int():\n                x = 'x'  # E: Incompatible types in assignment \\\n                          (expression has type \"str\", variable has type \"int\")\n                x = 1\n    else:\n        def f(x: int) -> None:\n            x + 'x'   # E: Unsupported operand types for + (\"int\" and \"str\")\n            x = 1\n    f(1)\n    f('x') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\n[case testUnconditionalRedefinitionOfConditionalFunction]\nfrom typing import Any\nx = None # type: Any\nif x:\n    def f(): pass\ndef f(): pass # E: Name \"f\" already defined on line 4\n\n[case testIncompatibleConditionalFunctionDefinition]\nfrom typing import Any\nx = None # type: Any\nif x:\n    def f(x: int) -> None: pass\nelse:\n    def f(x): pass # E: All conditional function variants must have identical signatures \\\n                   # N: Original: \\\n                   # N:     def f(x: int) -> None \\\n                   # N: Redefinition: \\\n                   # N:     def f(x: Any) -> Any\n\n[case testIncompatibleConditionalFunctionDefinition2]\nfrom typing import Any\nx = None # type: Any\nif x:\n    def f(x: int) -> None: pass\nelse:\n    def f(y: int) -> None: pass # E: All conditional function variants must have identical signatures \\\n                                # N: Original: \\\n                                # N:     def f(x: int) -> None \\\n                                # N: Redefinition: \\\n                                # N:     def f(y: int) -> None\n\n[case testIncompatibleConditionalFunctionDefinition3]\nfrom typing import Any\nx = None # type: Any\nif x:\n    def f(x: int) -> None: pass\nelse:\n    def f(x: int = 0) -> None: pass # E: All conditional function variants must have identical signatures \\\n                                    # N: Original: \\\n                                    # N:     def f(x: int) -> None \\\n                                    # N: Redefinition: \\\n                                    # N:     def f(x: int = ...) -> None\n\n[case testIncompatibleConditionalFunctionDefinition4]\nfrom typing import Any, Union, TypeVar\nT1 = TypeVar('T1')\nT2 = TypeVar('T2', bound=Union[int, str])\nx = None # type: Any\nif x:\n    def f(x: T1) -> T1: pass\nelse:\n    def f(x: T2) -> T2: pass # E: All conditional function variants must have identical signatures \\\n                             # N: Original: \\\n                             # N:     def [T1] f(x: T1) -> T1 \\\n                             # N: Redefinition: \\\n                             # N:     def [T2: int | str] f(x: T2) -> T2\n\n[case testConditionalFunctionDefinitionUsingDecorator1]\nfrom typing import Callable\n\ndef dec(f) -> Callable[[int], None]: pass\n\nx = int()\nif x:\n    @dec\n    def f(): pass\nelse:\n    def f(x: int) -> None: pass\n\n[case testConditionalFunctionDefinitionUsingDecorator2]\nfrom typing import Callable\n\ndef dec(f) -> Callable[[int], None]: pass\n\nx = int()\nif x:\n    @dec\n    def f(): pass\nelse:\n    def f(x: str) -> None: pass # E: Incompatible redefinition (redefinition with type \"Callable[[str], None]\", original type \"Callable[[int], None]\")\n\n[case testConditionalFunctionDefinitionUsingDecorator3]\n\nfrom typing import Callable\n\ndef dec(f) -> Callable[[int], None]: pass\n\nx = int()\nif x:\n    def f(x: int, /) -> None: pass\nelse:\n    @dec\n    def f(): pass\n\n[case testConditionalFunctionDefinitionUsingDecorator4]\n\nfrom typing import Callable\n\ndef dec(f) -> Callable[[int], None]: pass\n\nx = int()\nif x:\n    def f(x: str) -> None: pass\nelse:\n    @dec\n    def f(): pass   # E: All conditional function variants must have identical signatures \\\n                    # N: Original: \\\n                    # N:     def f(x: str) -> None \\\n                    # N: Redefinition: \\\n                    # N:     def f(int, /) -> None\n\n[case testConditionalFunctionDefinitionUnreachable]\n# flags: --warn-unreachable\ndef bar() -> None:\n    if False:\n        foo = 1  # E: Statement is unreachable\n    else:\n        def foo(obj): ...\n\ndef baz() -> None:\n    if False:\n        foo: int = 1  # E: Statement is unreachable\n    else:\n        def foo(obj): ...  # E: Incompatible redefinition (redefinition with type \"Callable[[Any], Any]\", original type \"int\")\n[builtins fixtures/tuple.pyi]\n\n[case testConditionalRedefinitionOfAnUnconditionalFunctionDefinition1]\nfrom typing import Any\ndef f(x: str) -> None: pass\nx = None # type: Any\nif x:\n    def f(x: int) -> None: pass # E: All conditional function variants must have identical signatures \\\n                                # N: Original: \\\n                                # N:     def f(x: str) -> None \\\n                                # N: Redefinition: \\\n                                # N:     def f(x: int) -> None\n\n[case testConditionalRedefinitionOfAnUnconditionalFunctionDefinition2]\nfrom typing import Any\ndef f(x: int) -> None: pass\nx = None # type: Any\nif x:\n    def f(y: int) -> None: pass # E: All conditional function variants must have identical signatures \\\n                                # N: Original: \\\n                                # N:     def f(x: int) -> None \\\n                                # N: Redefinition: \\\n                                # N:     def f(y: int) -> None\nf(x=1) # The first definition takes precedence.\nf(y=1) # E: Unexpected keyword argument \"y\" for \"f\"\n\n[case testRedefineFunctionDefinedAsVariable]\ndef g(): pass\nf = g\nif g():\n    def f(): pass\nf()\nf(1) # E: Too many arguments\n\n[case testRedefineFunctionDefinedAsVariableInitializedToNone]\ndef g(): pass\nf = None\nif g():\n    def f(): pass\nf()\nf(1) # E: Too many arguments for \"f\"\n\n[case testRedefineNestedFunctionDefinedAsVariableInitializedToNone]\ndef g() -> None:\n    f = None\n    if object():\n        def f(x: int) -> None: pass\n    f() # E: Missing positional argument \"x\" in call to \"f\"\n    f(1)\n    f('') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n[out]\n\n[case testRedefineFunctionDefinedAsVariableWithInvalidSignature]\ndef g(): pass\nf = g\nif g():\n    def f(x): pass  # E: Incompatible redefinition (redefinition with type \"Callable[[Any], Any]\", original type \"Callable[[], Any]\")\n\n[case testRedefineFunctionDefinedAsVariableWithVariance1]\nclass B: pass\nclass C(B): pass\ndef g(x: C) -> B: pass\nf = g\nif g(C()):\n    def f(x: C) -> C: pass\n\n[case testRedefineFunctionDefinedAsVariableWithVariance2]\nclass B: pass\nclass C(B): pass\ndef g(x: C) -> B: pass\nf = g\nif g(C()):\n    def f(x: B) -> B: pass\n\n[case testRedefineFunctionDefinedAsVariableInitializedToEmptyList]\nf = [] # E: Need type annotation for \"f\" (hint: \"f: list[<type>] = ...\")\nif object():\n    def f(): pass # E: Incompatible redefinition\nf()  # E: \"list[Any]\" not callable\nf(1)  # E: \"list[Any]\" not callable\n[builtins fixtures/list.pyi]\n\n[case testDefineConditionallyAsImportedAndDecorated]\nfrom typing import Callable\n\ndef dec(f: Callable[[], None]) -> Callable[[], None]: ...\n\nif int():\n    from m import f\nelse:\n    @dec\n    def f():\n        yield\n[file m.py]\ndef f() -> None: pass\n\n[case testDefineConditionallyAsImportedAndDecoratedWithInference]\nif int():\n    from m import f\nelse:\n    from contextlib import contextmanager\n\n    @contextmanager\n    def f():\n        yield\n[file m.py]\nfrom contextlib import contextmanager\n\n@contextmanager\ndef f():\n    yield\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/tuple.pyi]\n\n\n-- Conditional method definition\n-- -----------------------------\n\n\n[case testTypeCheckBodyOfConditionalMethod]\nfrom typing import Any\nx = None # type: Any\nclass A:\n    if x:\n        def f(self, x: int) -> None:\n            if int():\n                x = 1\n                x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[out]\n\n[case testCallConditionalMethodInClassBody]\nfrom typing import Any\nx = None # type: Any\nclass A:\n    if x:\n        def f(self, x: int) -> None:  pass\n        f(x, 1)\n        f(x, 'x') # E: Argument 2 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n    f(x, 1)\n    f(x, 'x') # E: Argument 2 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n[out]\n\n[case testCallConditionalMethodViaInstance]\nfrom typing import Any\nx = None # type: Any\nclass A:\n    if x:\n         def f(self, x: int) -> None: pass\nA().f(1)\nA().f('x') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\n[case testConditionalMethodDefinitionWithIfElse]\nfrom typing import Any\nx = None # type: Any\nclass A:\n    if x:\n        def f(self, x: int) -> None:\n            'x' + x   # fail\n            if int():\n                x = 1\n    else:\n        def f(self, x: int) -> None:\n            x + 'x'   # fail\n            if int():\n                x = 1\nA().f(1)\nA().f('x') # fail\n[builtins fixtures/primitives.pyi]\n[out]\nmain:6: error: Unsupported operand types for + (\"str\" and \"int\")\nmain:11: error: Unsupported operand types for + (\"int\" and \"str\")\nmain:15: error: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\n[case testUnconditionalRedefinitionOfConditionalMethod]\nfrom typing import Any\nx = None # type: Any\nclass A:\n    if x:\n        def f(self): pass\n    def f(self): pass # E: Name \"f\" already defined on line 5\n\n[case testIncompatibleConditionalMethodDefinition]\nfrom typing import Any\nx = None # type: Any\nclass A:\n    if x:\n        def f(self, x: int) -> None: pass\n    else:\n        def f(self, x): pass # E: All conditional function variants must have identical signatures \\\n                             # N: Original: \\\n                             # N:     def f(self: A, x: int) -> None \\\n                             # N: Redefinition: \\\n                             # N:     def f(self: A, x: Any) -> Any\n[out]\n\n[case testConditionalFunctionDefinitionInTry]\nimport typing\ntry:\n    def f(x: int) -> None: pass\nexcept:\n    def g(x: str) -> None: pass\nf(1)\nf('x') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\ng('x')\ng(1) # E: Argument 1 to \"g\" has incompatible type \"int\"; expected \"str\"\n\n[case testConditionalMethodDefinitionUsingDecorator]\nfrom typing import Callable\n\ndef dec(f) -> Callable[['A', int], None]: pass\n\nclass A:\n    x = int()\n    if x:\n        @dec\n        def f(self): pass\n    else:\n        def f(self, x: int) -> None: pass\n\n\n-- Callable with specific arg list\n-- -------------------------------\n\n\n[case testCallableWithNamedArg]\nfrom typing import Callable\nfrom mypy_extensions import Arg\n\ndef a(f: Callable[[Arg(int, 'x')], int]):\n    f(x=4)\n    f(5)\n    f(y=3) # E: Unexpected keyword argument \"y\"\n\n[builtins fixtures/dict.pyi]\n\n[case testCallableWithOptionalArg]\nfrom typing import Callable\nfrom mypy_extensions import DefaultArg\n\ndef a(f: Callable[[DefaultArg(int, 'x')], int]):\n    f(x=4)\n    f(2)\n    f()\n    f(y=3) # E: Unexpected keyword argument \"y\"\n    f(\"foo\") # E: Argument 1 has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testCallableWithNamedArgFromExpr]\nfrom typing import Callable\nfrom mypy_extensions import Arg\n\nF = Callable[[Arg(int, 'x')], int]\n\ndef a(f: F):\n    f(x=4)\n    f(5)\n    f(y=3) # E: Unexpected keyword argument \"y\"\n\n[builtins fixtures/dict.pyi]\n\n[case testCallableWithOptionalArgFromExpr]\nfrom typing import Callable\nfrom mypy_extensions import DefaultArg\n\nF = Callable[[DefaultArg(int, 'x')], int]\ndef a(f: F):\n    f(x=4)\n    f(2)\n    f()\n    f(y=3) # E: Unexpected keyword argument \"y\"\n    f(\"foo\") # E: Argument 1 has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testCallableParsingInInheritance]\n\nfrom collections import namedtuple\nclass C(namedtuple('t', 'x')):\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testCallableParsingSameName]\nfrom typing import Callable\n\ndef Arg(x, y): pass\n\nF = Callable[[Arg(int, 'x')], int]  # E: Invalid argument constructor \"__main__.Arg\"\n\n[case testCallableParsingFromExpr]\nfrom typing import Callable, List\nfrom mypy_extensions import Arg, VarArg, KwArg\nimport mypy_extensions\nimport types  # Needed for type checking\n\ndef WrongArg(x, y): return y\n# Note that for this test, the 'Value of type \"int\" is not indexable' errors are silly,\n# and a consequence of Callable being set to an int in the test stub.  We can't set it to\n# something else sensible, because other tests require the stub not have anything\n# that looks like a function call.\nF = Callable[[WrongArg(int, 'x')], int] # E: Invalid argument constructor \"__main__.WrongArg\"\nG = Callable[[Arg(1, 'x')], int] # E: Invalid type: try using Literal[1] instead?\nH = Callable[[VarArg(int, 'x')], int] # E: VarArg arguments should not have names\nI = Callable[[VarArg(int)], int] # ok\nJ = Callable[[VarArg(), KwArg()], int] # ok\nK = Callable[[VarArg(), int], int] # E: Required positional args may not appear after default, named or var args\nL = Callable[[Arg(name='x', type=int)], int] # ok\n# I have commented out the following test because I don't know how to expect the \"defined here\" note part of the error.\n# M = Callable[[Arg(gnome='x', type=int)], int]   E: Invalid type alias: expression is not a valid type   E: Unexpected keyword argument \"gnome\" for \"Arg\"\nN = Callable[[Arg(name=None, type=int)], int] # ok\nO = Callable[[List[Arg(int)]], int]  # E: Invalid type alias: expression is not a valid type \\\n                                     # E: Value of type \"int\" is not indexable \\\n                                     # E: Type expected within [...]\nP = Callable[[mypy_extensions.VarArg(int)], int] # ok\nQ = Callable[[Arg(int, type=int)], int]  # E: Invalid type alias: expression is not a valid type \\\n                                         # E: Value of type \"int\" is not indexable \\\n                                         # E: \"Arg\" gets multiple values for keyword argument \"type\"\nR = Callable[[Arg(int, 'x', name='y')], int]  # E: Invalid type alias: expression is not a valid type \\\n                                              # E: Value of type \"int\" is not indexable \\\n                                              # E: \"Arg\" gets multiple values for keyword argument \"name\"\n[builtins fixtures/dict.pyi]\n\n[case testCallableParsing]\nfrom typing import Callable\nfrom mypy_extensions import Arg, VarArg, KwArg\n\ndef WrongArg(x, y): return y\n\ndef b(f: Callable[[Arg(1, 'x')], int]): pass # Invalid type. Try using Literal[1] instead?\ndef d(f: Callable[[VarArg(int)], int]): pass # ok\ndef e(f: Callable[[VarArg(), KwArg()], int]): pass # ok\ndef g(f: Callable[[Arg(name='x', type=int)], int]): pass # ok\ndef h(f: Callable[[Arg(gnome='x', type=int)], int]): pass  # E: Unexpected argument \"gnome\" for argument constructor\ndef i(f: Callable[[Arg(name=None, type=int)], int]): pass # ok\ndef j(f: Callable[[Arg(int, 'x', name='y')], int]): pass # E: \"Arg\" gets multiple values for keyword argument \"name\"\ndef k(f: Callable[[Arg(int, type=int)], int]): pass # E: \"Arg\" gets multiple values for keyword argument \"type\"\n\n[builtins fixtures/dict.pyi]\n\n[case testCallableTypeAnalysis]\nfrom typing import Callable\nfrom mypy_extensions import Arg, VarArg as VARG, KwArg\nimport mypy_extensions as ext\n\ndef WrongArg(x, y): return y\ndef a(f: Callable[[WrongArg(int, 'x')], int]): pass # E: Invalid argument constructor \"__main__.WrongArg\"\ndef b(f: Callable[[BadArg(int, 'x')], int]): pass # E: Name \"BadArg\" is not defined\ndef d(f: Callable[[ext.VarArg(int)], int]): pass # ok\ndef e(f: Callable[[VARG(), ext.KwArg()], int]): pass # ok\ndef g(f: Callable[[ext.Arg(name='x', type=int)], int]): pass # ok\ndef i(f: Callable[[Arg(name=None, type=int)], int]): pass # ok\n\ndef f1(*args) -> int: pass\ndef f2(*args, **kwargs) -> int: pass\n\nd(f1)\ne(f2)\nd(f2)\ne(f1)\n\n[builtins fixtures/dict.pyi]\n\n[case testCallableWrongTypeType]\nfrom typing import Callable\nfrom mypy_extensions import Arg\ndef b(f: Callable[[Arg(1, 'x')], int]): pass # E: Invalid type: try using Literal[1] instead?\n[builtins fixtures/dict.pyi]\n\n[case testCallableTooManyVarArg]\nfrom typing import Callable\nfrom mypy_extensions import VarArg\ndef c(f: Callable[[VarArg(int, 'x')], int]): pass # E: VarArg arguments should not have names\n[builtins fixtures/dict.pyi]\n\n[case testCallableFastParseGood]\nfrom typing import Callable\nfrom mypy_extensions import VarArg, Arg, KwArg\ndef d(f: Callable[[VarArg(int)], int]): pass # ok\ndef e(f: Callable[[VarArg(), KwArg()], int]): pass # ok\ndef g(f: Callable[[Arg(name='x', type=int)], int]): pass # ok\ndef i(f: Callable[[Arg(name=None, type=int)], int]): pass # ok\n[builtins fixtures/dict.pyi]\n\n[case testCallableFastParseBadArgArgName]\nfrom typing import Callable\nfrom mypy_extensions import Arg\ndef h(f: Callable[[Arg(gnome='x', type=int)], int]): pass # E: Unexpected argument \"gnome\" for argument constructor\n[builtins fixtures/dict.pyi]\n\n[case testCallableKindsOrdering]\nfrom typing import Callable, Any\nfrom mypy_extensions import Arg, VarArg, KwArg, DefaultArg, NamedArg\n\ndef f(f: Callable[[VarArg(), int], int]): pass # E: Required positional args may not appear after default, named or var args\ndef g(f: Callable[[VarArg(), VarArg()], int]): pass # E: Var args may not appear after named or var args\ndef h(f: Callable[[KwArg(), KwArg()], int]): pass # E: You may only have one **kwargs argument\ndef i(f: Callable[[DefaultArg(), int], int]): pass # E: Required positional args may not appear after default, named or var args\ndef j(f: Callable[[NamedArg(Any, 'x'), DefaultArg(int, 'y')], int]): pass # E: Positional default args may not appear after named or var args\ndef k(f: Callable[[KwArg(), NamedArg(Any, 'x')], int]): pass # E: A **kwargs argument must be the last argument\n[builtins fixtures/dict.pyi]\n\n[case testCallableDuplicateNames]\nfrom typing import Callable\nfrom mypy_extensions import Arg, VarArg, KwArg, DefaultArg\n\ndef f(f: Callable[[Arg(int, 'x'), int, Arg(int, 'x')], int]): pass # E: Duplicate parameter \"x\" in Callable\n\n[builtins fixtures/dict.pyi]\n\n\n[case testCallableWithKeywordOnlyArg]\nfrom typing import Callable\nfrom mypy_extensions import NamedArg\n\ndef a(f: Callable[[NamedArg(int, 'x')], int]):\n    f(x=4)\n    f(2) # E: Too many positional arguments\n    f() # E: Missing named argument \"x\"\n    f(y=3) # E: Unexpected keyword argument \"y\"\n    f(x=\"foo\") # E: Argument \"x\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testCallableWithKeywordOnlyOptionalArg]\nfrom typing import Callable\nfrom mypy_extensions import DefaultNamedArg\n\ndef a(f: Callable[[DefaultNamedArg(int, 'x')], int]):\n    f(x=4)\n    f(2) # E: Too many positional arguments\n    f()\n    f(y=3) # E: Unexpected keyword argument \"y\"\n    f(x=\"foo\") # E: Argument \"x\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testCallableWithKwargs]\nfrom typing import Callable\nfrom mypy_extensions import KwArg\n\ndef a(f: Callable[[KwArg(int)], int]):\n    f(x=4)\n    f(2) # E: Too many arguments\n    f()\n    f(y=3)\n    f(x=4, y=3, z=10)\n    f(x=\"foo\") # E: Argument \"x\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n\n[case testCallableWithVarArg]\nfrom typing import Callable\nfrom mypy_extensions import VarArg\n\ndef a(f: Callable[[VarArg(int)], int]):\n    f(x=4)  # E: Unexpected keyword argument \"x\"\n    f(2)\n    f()\n    f(3, 4, 5)\n    f(\"a\")  # E: Argument 1 has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testCallableArgKindSubtyping]\nfrom typing import Callable\nfrom mypy_extensions import Arg, DefaultArg\n\nint_str_fun: Callable[[int, str], str]\nint_opt_str_fun: Callable[[int, DefaultArg(str, None)], str]\nint_named_str_fun: Callable[[int, Arg(str, 's')], str]\n\ndef isf(ii: int, ss: str) -> str:\n    return ss\n\ndef iosf(i: int, s: str = \"bar\") -> str:\n    return s\n\ndef isf_unnamed(__i: int, __s: str) -> str:\n    return __s\n\nint_str_fun = isf\nint_str_fun = isf_unnamed\nint_named_str_fun = isf_unnamed # E: Incompatible types in assignment (expression has type \"Callable[[int, str], str]\", variable has type \"def (int, /, s: str) -> str\")\nint_opt_str_fun = iosf\nint_str_fun = iosf\nint_opt_str_fun = isf # E: Incompatible types in assignment (expression has type \"def isf(ii: int, ss: str) -> str\", variable has type \"def (int, str = ..., /) -> str\")\n\nint_named_str_fun = isf # E: Incompatible types in assignment (expression has type \"def isf(ii: int, ss: str) -> str\", variable has type \"def (int, /, s: str) -> str\")\nint_named_str_fun = iosf\n\n[builtins fixtures/dict.pyi]\n\n-- Callable[..., T]\n-- ----------------\n\n\n[case testCallableWithArbitraryArgs]\nfrom typing import Callable\ndef f(x: Callable[..., int]) -> None:\n    x()\n    x(1)\n    x(z=1)\n    x() + '' # E: Unsupported operand types for + (\"int\" and \"str\")\n[out]\n\n[case testCallableWithArbitraryArgs2]\nfrom typing import Callable\ndef f(x: Callable[..., int]) -> None:\n    x(*[1], **{'x': 2})\n[builtins fixtures/dict.pyi]\n\n[case testCastWithCallableAndArbitraryArgs]\nfrom typing import Callable, cast\nf = cast(Callable[..., int], None)\nf(x=4) + '' # E: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testCallableWithArbitraryArgsInErrorMessage]\nfrom typing import Callable\ndef f(x: Callable[..., int]) -> None:\n    if int():\n        x = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Callable[..., int]\")\n[out]\n\n[case testCallableWithArbitraryArgsInGenericFunction]\nfrom typing import Callable, TypeVar\nT = TypeVar('T')\ndef f(x: Callable[..., T]) -> T: pass\ndef g(*x: int) -> str: pass\nx = f(g)\nx + 1 # E: Unsupported left operand type for + (\"str\")\n[builtins fixtures/list.pyi]\n\n[case testCallableWithArbitraryArgsSubtyping]\nfrom typing import Callable\ndef f(x: Callable[..., int]) -> None: pass\ndef g1(): pass\ndef g2(x, y) -> int: pass\ndef g3(*, y: str) -> int: pass\ndef g4(*, y: int) -> str: pass\nf(g1)\nf(g2)\nf(g3)\nf(g4) # E: Argument 1 to \"f\" has incompatible type \"def g4(*, y: int) -> str\"; expected \"Callable[..., int]\"\n\n[case testCallableWithArbitraryArgsSubtypingWithGenericFunc]\nfrom typing import Callable, TypeVar\nT = TypeVar('T')\ndef f(x: Callable[..., int]) -> None: pass\ndef g1(x: T) -> int: pass\ndef g2(*x: T) -> int: pass\ndef g3(*x: T) -> T: pass\nf(g1)\nf(g2)\nf(g3)\n[builtins fixtures/tuple.pyi]\n\n-- (...) -> T\n-- ----------------\n\n[case testEllipsisWithArbitraryArgsOnBareFunction]\ndef f(x, y, z): # type: (...) -> None\n    pass\nf(1, \"hello\", [])\nf(x=1, y=\"hello\", z=[])\n[builtins fixtures/dict.pyi]\n\n[case testEllipsisWithArbitraryArgsOnBareFunctionWithDefaults]\ndef f(x, y=1, z=\"hey\"): # type: (...) -> None\n    pass\nf(1, \"hello\", [])\nf(x=1, y=\"hello\", z=[])\n[builtins fixtures/dict.pyi]\n\n[case testEllipsisWithArbitraryArgsOnBareFunctionWithKwargs]\nfrom typing import Dict\ndef f(x, **kwargs): # type: (...) -> None\n    success_dict_type = kwargs # type: Dict[str, str]\n    failure_dict_type = kwargs # type: Dict[int, str] # E: Incompatible types in assignment (expression has type \"dict[str, Any]\", variable has type \"dict[int, str]\")\nf(1, thing_in_kwargs=[\"hey\"])\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testEllipsisWithArbitraryArgsOnBareFunctionWithVarargs]\nfrom typing import Tuple, Any\ndef f(x, *args): # type: (...) -> None\n    success_tuple_type = args # type: Tuple[Any, ...]\n    fail_tuple_type = args # type: None # E: Incompatible types in assignment (expression has type \"tuple[Any, ...]\", variable has type \"None\")\nf(1, \"hello\")\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testEllipsisWithArbitraryArgsOnInstanceMethod]\nclass A:\n    def f(self, x, y, z): # type: (...) -> None\n        pass\n\n[case testEllipsisWithArbitraryArgsOnClassMethod]\nclass A:\n    @classmethod\n    def f(cls, x, y, z): # type: (...) -> None\n        pass\n[builtins fixtures/classmethod.pyi]\n\n[case testEllipsisWithArbitraryArgsOnStaticMethod]\nclass A:\n    @staticmethod\n    def f(x, y, z): # type: (...) -> None\n        pass\n[builtins fixtures/staticmethod.pyi]\n\n[case testEllipsisWithSomethingAfterItFails_no_native_parse]\ndef f(x, y, z): # type: (..., int) -> None\n    pass\n[out]\nmain:1: error: Ellipses cannot accompany other parameter types in function type signature\n\n[case testEllipsisWithSomethingBeforeItFails_no_native_parse]\ndef f(x, y, z): # type: (int, ...) -> None\n    pass\n[out]\nmain:1: error: Ellipses cannot accompany other parameter types in function type signature\n\n[case testRejectCovariantArgument]\nfrom typing import TypeVar, Generic\n\nt = TypeVar('t', covariant=True)\nclass A(Generic[t]):\n    def foo(self, x: t) -> None:\n        return None\n[builtins fixtures/bool.pyi]\n[out]\nmain:5: error: Cannot use a covariant type variable as a parameter\n\n[case testRejectCovariantArgumentSplitLine]\nfrom typing import TypeVar, Generic\n\nt = TypeVar('t', covariant=True)\nclass A(Generic[t]):\n    def foo(self,\n            x: t) -> None:\n        return None\n[builtins fixtures/bool.pyi]\n[out]\nmain:6: error: Cannot use a covariant type variable as a parameter\n\n[case testRejectCovariantArgumentInLambda]\nfrom typing import TypeVar, Generic, Callable\n\nt = TypeVar('t', covariant=True)\nclass Thing(Generic[t]):\n    def chain(self, func: Callable[[t], None]) -> None: pass\n    def end(self) -> None:\n        return self.chain(  # Note that lambda args have no line numbers\n            lambda _: None)\n[builtins fixtures/bool.pyi]\n[out]\nmain:8: error: Cannot use a covariant type variable as a parameter\n\n[case testRejectCovariantArgumentInLambdaSplitLine]\nfrom typing import TypeVar, Generic, Callable\n\n[case testRejectContravariantReturnType]\n# flags: --no-strict-optional\nfrom typing import TypeVar, Generic\n\nt = TypeVar('t', contravariant=True)\nclass A(Generic[t]):\n    def foo(self) -> t:\n        return None\n[builtins fixtures/bool.pyi]\n[out]\nmain:6: error: Cannot use a contravariant type variable as return type\n\n[case testAcceptCovariantReturnType]\n# flags: --no-strict-optional\nfrom typing import TypeVar, Generic\n\nt = TypeVar('t', covariant=True)\nclass A(Generic[t]):\n    def foo(self) -> t:\n        return None\n[builtins fixtures/bool.pyi]\n\n[case testAcceptContravariantArgument]\nfrom typing import TypeVar, Generic\n\nt = TypeVar('t', contravariant=True)\nclass A(Generic[t]):\n    def foo(self, x: t) -> None:\n        return None\n[builtins fixtures/bool.pyi]\n\n\n-- Redefining functions\n-- --------------------\n\n\n[case testRedefineFunction]\nfrom typing import Any\ndef f(x) -> Any: pass\ndef g(x, y): pass\ndef h(x): pass\ndef j(y) -> Any: pass\nf = h\nf = j # E: Incompatible types in assignment (expression has type \"def j(y: Any) -> Any\", variable has type \"def f(x: Any) -> Any\")\nf = g # E: Incompatible types in assignment (expression has type \"Callable[[Any, Any], Any]\", variable has type \"Callable[[Any], Any]\")\n\n[case testRedefineFunction2]\ndef f() -> None: pass\ndef f() -> None: pass # E: Name \"f\" already defined on line 1\n\n\n-- Special cases\n-- -------------\n\n\n[case testFunctionDefinitionWithForStatement]\nfor _ in [1]:\n    def f(): pass\nelse:\n    def g(): pass\nf()\ng()\n[builtins fixtures/list.pyi]\n\n[case testFunctionDefinitionWithWhileStatement]\nwhile bool():\n    def f(): pass\nelse:\n    def g(): pass\nf()\ng()\n[builtins fixtures/bool.pyi]\n\n[case testBareCallable]\nfrom typing import Callable, Any\n\ndef foo(f: Callable) -> bool:\n    return f()\n\ndef f1() -> bool:\n    return False\n\nfoo(f1)\n[builtins fixtures/bool.pyi]\n\n[case testFunctionNestedWithinWith]\nfrom typing import Any\na = 1  # type: Any\nwith a:\n    def f() -> None:\n        pass\n    f(1) # E: Too many arguments for \"f\"\n\n\n[case testNameForDecoratorMethod]\nfrom typing import Callable\n\nclass A:\n    def f(self) -> None:\n        # In particular, test that the error message contains \"g\" of \"A\".\n        self.g() # E: Too few arguments for \"g\" of \"A\"\n        self.g(1)\n    @dec\n    def g(self, x: str) -> None: pass\n\ndef dec(f: Callable[[A, str], None]) -> Callable[[A, int], None]: pass\n[out]\n\n[case testUnknownFunctionNotCallable]\nfrom typing import TypeVar\n\ndef f() -> None:\n    pass\ndef g(x: int) -> None:\n    pass\nh = f if bool() else g\nreveal_type(h) # N: Revealed type is \"(def ()) | (def (x: builtins.int))\"\nh(7) # E: Too many arguments for \"f\"\n\nT = TypeVar(\"T\")\ndef join(x: T, y: T) -> T: ...\n\nh2 = join(f, g)\nreveal_type(h2)  # N: Revealed type is \"builtins.function\"\nh2(7)  # E: Cannot call function of unknown type\n\nh3 = join(g, f)\nreveal_type(h3)  # N: Revealed type is \"builtins.function\"\nh3(7)  # E: Cannot call function of unknown type\n[builtins fixtures/bool.pyi]\n\n[case testFunctionWithNameUnderscore]\ndef _(x: int) -> None: pass\n\n_(1)\n_('x')  # E: Argument 1 to \"_\" has incompatible type \"str\"; expected \"int\"\n\n-- Positional-only arguments\n-- -------------------------\n\n[case testPositionalOnlyArg]\ndef f(__a: int) -> None: pass\ndef g(__a__: int) -> None: pass\n\nf(1)\nf(__a=1) # E: Unexpected keyword argument \"__a\" for \"f\"\n\ng(1)\n# Argument names that also end with __ are not positional-only.\ng(__a__=1)\n\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testMagicMethodPositionalOnlyArg]\nclass A(object):\n    def __eq__(self, other) -> bool: return True # We are all equal.\n\na = A()\na.__eq__(a)\na.__eq__(other=a) # E: Unexpected keyword argument \"other\" for \"__eq__\" of \"A\"\n\n[builtins fixtures/bool.pyi]\n\n[case testMagicMethodPositionalOnlyArgFastparse]\n\n\nclass A(object):\n    def __eq__(self, other) -> bool: return True # We are all equal.\n\na = A()\na.__eq__(a)\na.__eq__(other=a) # E: Unexpected keyword argument \"other\" for \"__eq__\" of \"A\"\n\n[builtins fixtures/bool.pyi]\n\n-- Type variable shenanigans\n-- -------------------------\n\n[case testGenericFunctionTypeDecl]\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T')\n\nf: Callable[[T], T]\nreveal_type(f)  # N: Revealed type is \"def [T] (T`-1) -> T`-1\"\ndef g(__x: T) -> T: pass\nf = g\nreveal_type(f)  # N: Revealed type is \"def [T] (T`-1) -> T`-1\"\ni = f(3)\nreveal_type(i)  # N: Revealed type is \"builtins.int\"\n\n[case testFunctionReturningGenericFunction]\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T')\ndef deco() -> Callable[[T], T]: pass\nreveal_type(deco)  # N: Revealed type is \"def () -> def [T] (T`-1) -> T`-1\"\nf = deco()\nreveal_type(f)  # N: Revealed type is \"def [T] (T`1) -> T`1\"\ni = f(3)\nreveal_type(i)  # N: Revealed type is \"builtins.int\"\n\n[case testFunctionReturningGenericFunctionPartialBinding]\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef deco(x: U) -> Callable[[T, U], T]: pass\nreveal_type(deco)  # N: Revealed type is \"def [U] (x: U`-1) -> def [T] (T`-2, U`-1) -> T`-2\"\nf = deco(\"foo\")\nreveal_type(f)  # N: Revealed type is \"def [T] (T`1, builtins.str) -> T`1\"\ni = f(3, \"eggs\")\nreveal_type(i)  # N: Revealed type is \"builtins.int\"\n\n[case testFunctionReturningGenericFunctionTwoLevelBinding]\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T')\nR = TypeVar('R')\ndef deco() -> Callable[[T], Callable[[T, R], R]]: pass\nf = deco()\nreveal_type(f)  # N: Revealed type is \"def [T] (T`2) -> def [R] (T`2, R`1) -> R`1\"\ng = f(3)\nreveal_type(g)  # N: Revealed type is \"def [R] (builtins.int, R`3) -> R`3\"\ns = g(4, \"foo\")\nreveal_type(s)  # N: Revealed type is \"builtins.str\"\n\n[case testGenericFunctionReturnAsDecorator]\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T')\ndef deco(__i: int) -> Callable[[T], T]: pass\n\n@deco(3)\ndef lol(x: int) -> str: ...\n\nreveal_type(lol)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\ns = lol(4)\nreveal_type(s)  # N: Revealed type is \"builtins.str\"\n\n[case testGenericFunctionOnReturnTypeOnly]\nfrom typing import TypeVar, List\n\nT = TypeVar('T')\n\ndef make_list() -> List[T]: pass\n\nl: List[int] = make_list()\n\nbad = make_list()  # E: Need type annotation for \"bad\" (hint: \"bad: list[<type>] = ...\")\n[builtins fixtures/list.pyi]\n\n[case testAnonymousArgumentError]\ndef foo(__b: int, x: int, y: int) -> int: pass\nfoo(x=2, y=2)  # E: Too few arguments for \"foo\"\nfoo(y=2)  # E: Too few arguments for \"foo\"\n\n[case testMissingArgumentError]\ndef f(a, b, c, d=None) -> None: pass\nf(1, 2, d=3) # E: Missing positional argument \"c\" in call to \"f\"\n\n[case testMissingArgumentErrorMoreThanOneOptional]\ndef f(a: int, b=None, c=None) -> None: pass\nf(b=4) # E: Missing positional argument \"a\" in call to \"f\"\n\n[case testMissingArgumentsError]\ndef f(a, b, c, d=None) -> None: pass\nf(1, d=3) # E: Missing positional arguments \"b\", \"c\" in call to \"f\"\n\n[case testReturnTypeLineNumberWithDecorator]\ndef dec(f): pass\n\n@dec\ndef test(a: str) -> (str,): # E: Syntax error in type annotation # N: Suggestion: Is there a spurious trailing comma?\n    return None\n\n[case testReturnTypeLineNumberNewLine]\ndef fn(a: str\n       ) -> badtype: # E: Name \"badtype\" is not defined\n    pass\n\n[case testArgumentTypeLineNumberWithDecorator]\ndef dec(f): pass\n\n@dec\ndef some_method(self: badtype): pass # E: Name \"badtype\" is not defined\n\n[case TestArgumentTypeLineNumberNewline]\ndef fn(\n        a: badtype) -> None: # E: Name \"badtype\" is not defined\n    pass\n\n[case testInferredTypeSubTypeOfReturnType]\nfrom typing import Union, Dict, List\ndef f() -> List[Union[str, int]]:\n    x = ['a']\n    return x # E: Incompatible return value type (got \"list[str]\", expected \"list[str | int]\") \\\n      # N: \"list\" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \\\n      # N: Consider using \"Sequence\" instead, which is covariant \\\n      # N: Perhaps you need a type annotation for \"x\"? Suggestion: \"list[str | int]\"\n\ndef g() -> Dict[str, Union[str, int]]:\n    x = {'a': 'a'}\n    return x # E: Incompatible return value type (got \"dict[str, str]\", expected \"dict[str, str | int]\") \\\n      # N: \"dict\" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \\\n      # N: Consider using \"Mapping\" instead, which is covariant in the value type \\\n      # N: Perhaps you need a type annotation for \"x\"? Suggestion: \"dict[str, str | int]\"\n\ndef h() -> Dict[Union[str, int], str]:\n    x = {'a': 'a'}\n    return x # E: Incompatible return value type (got \"dict[str, str]\", expected \"dict[str | int, str]\") \\\n# N: Perhaps you need a type annotation for \"x\"? Suggestion: \"dict[str | int, str]\"\n\ndef i() -> List[Union[int, float]]:\n    x: List[int] = [1]\n    return x # E: Incompatible return value type (got \"list[int]\", expected \"list[int | float]\") \\\n      # N: \"list\" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \\\n      # N: Consider using \"Sequence\" instead, which is covariant\n\n[builtins fixtures/dict.pyi]\n\n[case testInferredTypeNotSubTypeOfReturnType]\nfrom typing import Union, List\ndef f() -> List[Union[int, float]]:\n    x = ['a']\n    return x # E: Incompatible return value type (got \"list[str]\", expected \"list[int | float]\")\n\ndef g() -> List[Union[str, int]]:\n    x = ('a', 2)\n    return x # E: Incompatible return value type (got \"tuple[str, int]\", expected \"list[str | int]\")\n\n[builtins fixtures/list.pyi]\n\n[case testInferredTypeIsObjectMismatch]\nfrom typing import Union, Dict, List\ndef f() -> Dict[str, Union[str, int]]:\n    x = {'a': 'a', 'b': 2}\n    return x # E: Incompatible return value type (got \"dict[str, object]\", expected \"dict[str, str | int]\")\n\ndef g() -> Dict[str, Union[str, int]]:\n    x: Dict[str, Union[str, int]] = {'a': 'a', 'b': 2}\n    return x\n\ndef h() -> List[Union[str, int]]:\n    x = ['a', 2]\n    return x # E: Incompatible return value type (got \"list[object]\", expected \"list[str | int]\")\n\ndef i() -> List[Union[str, int]]:\n    x: List[Union[str, int]] = ['a', 2]\n    return x\n\n[builtins fixtures/dict.pyi]\n\n[case testLambdaSemanal]\nf = lambda: xyz\n[out]\nmain:1: error: Name \"xyz\" is not defined\n\n[case testLambdaTypeCheck]\nf = lambda: 1 + '1'\n[out]\nmain:1: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testLambdaTypeInference]\nf = lambda: 5\nreveal_type(f)\n[out]\nmain:2: note: Revealed type is \"def () -> builtins.int\"\n\n[case testRevealLocalsFunction]\na = 1.0\n\nclass A: pass\n\ndef f(a: int, b: int) -> int:\n    reveal_locals()\n    c = a + b\n    class C: pass\n    reveal_locals()\n    return c\n\nreveal_locals()\n[out]\nmain:6: note: Revealed local types are:\nmain:6: note:     a: builtins.int\nmain:6: note:     b: builtins.int\nmain:9: note: Revealed local types are:\nmain:9: note:     a: builtins.int\nmain:9: note:     b: builtins.int\nmain:9: note:     c: builtins.int\nmain:12: note: Revealed local types are:\nmain:12: note:     a: builtins.float\n\n[case testNoComplainOverloadNone]\n# flags: --no-strict-optional\nfrom typing import overload, Optional\n@overload\ndef bar(x: None) -> None:\n    ...\n@overload\ndef bar(x: int) -> str:\n    ...\ndef bar(x: Optional[int]) -> Optional[str]:\n    if x is None:\n        return None\n    return \"number\"\n\nreveal_type(bar(None))  # N: Revealed type is \"None\"\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testNoComplainOverloadNoneStrict]\nfrom typing import overload, Optional\n@overload\ndef bar(x: None) -> None:\n    ...\n@overload\ndef bar(x: int) -> str:\n    ...\ndef bar(x: Optional[int]) -> Optional[str]:\n    if x is None:\n        return None\n    return \"number\"\n\nreveal_type(bar(None))  # N: Revealed type is \"None\"\n[builtins fixtures/isinstance.pyi]\n[out]\n\n[case testNoComplainInferredNone]\n# flags: --no-strict-optional\nfrom typing import TypeVar, Optional\nT = TypeVar('T')\ndef X(val: T) -> T: ...\nx_in = None\ndef Y(x: Optional[str] = X(x_in)): ...\n\nxx: Optional[int] = X(x_in)\n\n[case testNoComplainInferredNoneStrict]\nfrom typing import TypeVar, Optional\nT = TypeVar('T')\ndef X(val: T) -> T: ...\nx_in = None\ndef Y(x: Optional[str] = X(x_in)): ...\n\nxx: Optional[int] = X(x_in)\n\n[case testNoComplainNoneReturnFromUntyped]\ndef foo() -> None:\n    pass\n\ndef lol():\n    x = foo()\n\n[case testConditionalImportFunction]\nimport p\n[file p/__init__.py]\n\nif int():\n    from p.a import f\nelif int():\n    from p.b import f\nelse:\n    from p.c import f\n\n[file p/a.py]\ndef f() -> int: ...\n\n[file p/b.py]\nfrom p.d import f\n\n[file p/c.py]\ndef f() -> int: ...\n\n[file p/d.py]\nimport p\ndef f() -> int: ...\n\n[case testLambdaDefaultTypeErrors]\nlambda a=(1 + 'asdf'): a  # E: Unsupported operand types for + (\"int\" and \"str\")\nlambda a=nonsense: a  # E: Name \"nonsense\" is not defined\ndef f(x: int = i):  # E: Name \"i\" is not defined\n    i = 42\n\n[case testRevealTypeOfCallExpressionReturningNoneWorks]\ndef foo() -> None:\n    pass\n\nreveal_type(foo()) # N: Revealed type is \"None\"\n\n[case testAnyArgument]\ndef a(b: any): pass # E: Function \"builtins.any\" is not valid as a type \\\n                    # N: Perhaps you meant \"typing.Any\" instead of \"any\"?\n[builtins fixtures/any.pyi]\n\n[case testCallableArgument]\ndef a(b: callable): pass # E: Function \"builtins.callable\" is not valid as a type \\\n                         # N: Perhaps you meant \"typing.Callable\" instead of \"callable\"?\n[builtins fixtures/callable.pyi]\n\n[case testDecoratedProperty]\nfrom typing import TypeVar, Callable, final\n\nT = TypeVar(\"T\")\n\ndef dec(f: Callable[[T], int]) -> Callable[[T], str]: ...\ndef dec2(f: T) -> T: ...\n\nclass A:\n    @property\n    @dec\n    def f(self) -> int: pass\n    @property\n    @dec2\n    def g(self) -> int: pass\nreveal_type(A().f)  # N: Revealed type is \"builtins.str\"\nreveal_type(A().g)  # N: Revealed type is \"builtins.int\"\n\nclass B:\n    @final\n    @property\n    @dec\n    def f(self) -> int: pass\nreveal_type(B().f)  # N: Revealed type is \"builtins.str\"\n\nclass C:\n    @property  # E: Only instance methods can be decorated with @property\n    @classmethod\n    def f(cls) -> int: pass\nreveal_type(C().f)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/property.pyi]\n[out]\n\n[case testDecoratedPropertySetter]\nfrom typing import TypeVar, Callable, final\n\nT = TypeVar(\"T\")\ndef dec(f: T) -> T: ...\n\nclass A:\n    @property\n    @dec\n    def f(self) -> int: pass\n    @f.setter\n    @dec\n    def f(self, v: int) -> None: pass\nreveal_type(A().f)  # N: Revealed type is \"builtins.int\"\n\nclass B:\n    @property\n    @dec\n    def f(self) -> int: pass\n    @dec # E: Only supported top decorators are \"@f.setter\" and \"@f.deleter\"\n    @f.setter\n    def f(self, v: int) -> None: pass\n\nclass C:\n    @dec  # E: Decorators on top of @property are not supported\n    @property\n    def f(self) -> int: pass\n    @f.setter\n    @dec\n    def f(self, v: int) -> None: pass\n[builtins fixtures/property.pyi]\n\n[case testInvalidArgCountForProperty]\nfrom typing import Callable, TypeVar\n\nT = TypeVar(\"T\")\ndef dec(f: Callable[[T], int]) -> Callable[[T, int], int]: ...\n\nclass A:\n    @property  # E: Too many arguments for property\n    def f(self, x) -> int: pass\n    @property  # E: Too many arguments for property\n    @dec\n    def e(self) -> int: pass\n    @property\n    def g() -> int: pass   # E: Method must have at least one argument. Did you forget the \"self\" argument?\n    @property\n    def h(self, *args, **kwargs) -> int: pass   # OK\n[builtins fixtures/property.pyi]\n\n[case testSubtypingUnionGenericBounds]\nfrom typing import Callable, TypeVar, Union, Sequence\n\nTI = TypeVar(\"TI\", bound=int)\nTS = TypeVar(\"TS\", bound=str)\n\nf: Callable[[Sequence[TI]], None]\ng: Callable[[Union[Sequence[TI], Sequence[TS]]], None]\nf = g\n\n[case testOverrideDecoratedProperty]\nclass Base:\n    @property\n    def foo(self) -> int: ...\n\nclass decorator:\n    def __init__(self, fn):\n        self.fn = fn\n    def __call__(self, decorated_self) -> int:\n        return self.fn(decorated_self)\n\nclass Child(Base):\n    @property\n    @decorator\n    def foo(self) -> int:\n        return 42\nreveal_type(Child().foo)  # N: Revealed type is \"builtins.int\"\nChild().foo = 1  # E: Property \"foo\" defined in \"Child\" is read-only\n\nreveal_type(Child().foo)  # N: Revealed type is \"builtins.int\"\n\nclass BadChild1(Base):\n    @decorator\n    def foo(self) -> int:  # E: Signature of \"foo\" incompatible with supertype \"Base\" \\\n                           # N:      Superclass: \\\n                           # N:          int \\\n                           # N:      Subclass: \\\n                           # N:          decorator\n        return 42\n\nclass not_a_decorator:\n    def __init__(self, fn): ...\n\nclass BadChild2(Base):\n    # Override error not shown as accessing 'foo' on BadChild2 returns Any.\n    @property\n    @not_a_decorator\n    def foo(self) -> int:\n        return 42\nreveal_type(BadChild2().foo)  # E: \"not_a_decorator\" not callable \\\n                              # N: Revealed type is \"Any\"\n[builtins fixtures/property.pyi]\n\n[case explicitOverride]\n# flags: --python-version 3.12\nfrom typing import override\n\nclass A:\n    def f(self, x: int) -> str: pass\n    @override\n    def g(self, x: int) -> str: pass  # E: Method \"g\" is marked as an override, but no base method was found with this name\n\nclass B(A):\n    @override\n    def f(self, x: int) -> str: pass\n    @override\n    def g(self, x: int) -> str: pass\n\nclass C(A):\n    @override\n    def f(self, x: str) -> str: pass  # E: Argument 1 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\" \\\n                                      # N: This violates the Liskov substitution principle \\\n                                      # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n    def g(self, x: int) -> str: pass\n\nclass D(A): pass\nclass E(D): pass\nclass F(E):\n    @override\n    def f(self, x: int) -> str: pass\n[typing fixtures/typing-override.pyi]\n\n[case explicitOverrideStaticmethod]\n# flags: --python-version 3.12\nfrom typing import override\n\nclass A:\n    @staticmethod\n    def f(x: int) -> str: pass\n\nclass B(A):\n    @staticmethod\n    @override\n    def f(x: int) -> str: pass\n    @override\n    @staticmethod\n    def g(x: int) -> str: pass  # E: Method \"g\" is marked as an override, but no base method was found with this name\n\nclass C(A):  # inverted order of decorators\n    @override\n    @staticmethod\n    def f(x: int) -> str: pass\n    @override\n    @staticmethod\n    def g(x: int) -> str: pass  # E: Method \"g\" is marked as an override, but no base method was found with this name\n\nclass D(A):\n    @staticmethod\n    @override\n    def f(x: str) -> str: pass  # E: Argument 1 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\" \\\n                                # N: This violates the Liskov substitution principle \\\n                                # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n[typing fixtures/typing-override.pyi]\n[builtins fixtures/staticmethod.pyi]\n\n[case explicitOverrideClassmethod]\n# flags: --python-version 3.12\nfrom typing import override\n\nclass A:\n    @classmethod\n    def f(cls, x: int) -> str: pass\n\nclass B(A):\n    @classmethod\n    @override\n    def f(cls, x: int) -> str: pass\n    @override\n    @classmethod\n    def g(cls, x: int) -> str: pass  # E: Method \"g\" is marked as an override, but no base method was found with this name\n\nclass C(A):  # inverted order of decorators\n    @override\n    @classmethod\n    def f(cls, x: int) -> str: pass\n    @override\n    @classmethod\n    def g(cls, x: int) -> str: pass  # E: Method \"g\" is marked as an override, but no base method was found with this name\n\nclass D(A):\n    @classmethod\n    @override\n    def f(cls, x: str) -> str: pass  # E: Argument 1 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"int\" \\\n                                     # N: This violates the Liskov substitution principle \\\n                                     # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n[typing fixtures/typing-override.pyi]\n[builtins fixtures/classmethod.pyi]\n\n[case explicitOverrideProperty]\n# flags: --python-version 3.12\nfrom typing import override\n\nclass A:\n    @property\n    def f(self) -> str: pass\n\nclass B(A):\n    @property\n    @override\n    def f(self) -> str: pass\n    @override\n    @property\n    def g(self) -> str: pass  # E: Method \"g\" is marked as an override, but no base method was found with this name\n\nclass C(A):  # inverted order of decorators\n    @override\n    @property\n    def f(self) -> str: pass\n    @override\n    @property\n    def g(self) -> str: pass  # E: Method \"g\" is marked as an override, but no base method was found with this name\n\nclass D(A):\n    @property\n    @override\n    def f(self) -> int: pass  # E: Signature of \"f\" incompatible with supertype \"A\" \\\n                              # N:      Superclass: \\\n                              # N:          str \\\n                              # N:      Subclass: \\\n                              # N:          int\n[typing fixtures/typing-override.pyi]\n[builtins fixtures/property.pyi]\n\n[case explicitOverrideSettableProperty]\n# flags: --python-version 3.12\nfrom typing import override\n\nclass A:\n    @property\n    def f(self) -> str: pass\n\n    @f.setter\n    def f(self, value: str) -> None: pass\n\nclass B(A):\n    @property  # E: Read-only property cannot override read-write property\n    @override\n    def f(self) -> str: pass\n\nclass C(A):\n    @override\n    @property\n    def f(self) -> str: pass\n\n    @f.setter\n    def f(self, value: str) -> None: pass\n\nclass D(A):\n    @override  # E: Signature of \"f\" incompatible with supertype \"A\" \\\n               # N:      Superclass: \\\n               # N:          str \\\n               # N:      Subclass: \\\n               # N:          int\n    @property\n    def f(self) -> int: pass\n\n    @f.setter\n    def f(self, value: int) -> None: pass\n[typing fixtures/typing-override.pyi]\n[builtins fixtures/property.pyi]\n\n[case invalidExplicitOverride]\n# flags: --python-version 3.12\nfrom typing import override\n\n@override  # E: \"override\" used with a non-method\ndef f(x: int) -> str: pass\n\n@override  # this should probably throw an error but the signature from typeshed should ensure this already\nclass A: pass\n\ndef g() -> None:\n    @override  # E: \"override\" used with a non-method\n    def h(b: bool) -> int: pass\n[typing fixtures/typing-override.pyi]\n\n[case explicitOverrideSpecialMethods]\n# flags: --python-version 3.12\nfrom typing import override\n\nclass A:\n    def __init__(self, a: int) -> None: pass\n\nclass B(A):\n    @override\n    def __init__(self, b: str) -> None: pass\n\nclass C:\n    @override\n    def __init__(self, a: int) -> None: pass\n[typing fixtures/typing-override.pyi]\n\n[case explicitOverrideFromExtensions]\nfrom typing_extensions import override\n\nclass A:\n    def f(self, x: int) -> str: pass\n\nclass B(A):\n    @override\n    def f2(self, x: int) -> str: pass  # E: Method \"f2\" is marked as an override, but no base method was found with this name\n[builtins fixtures/tuple.pyi]\n\n[case explicitOverrideOverloads]\n# flags: --python-version 3.12\nfrom typing import overload, override\n\nclass A:\n    def f(self, x: int) -> str: pass\n\nclass B(A):\n    @overload  # E: Method \"f2\" is marked as an override, but no base method was found with this name\n    def f2(self, x: int) -> str: pass\n    @overload\n    def f2(self, x: str) -> str: pass\n    @override\n    def f2(self, x: int | str) -> str: pass\n[typing fixtures/typing-override.pyi]\n\n[case explicitOverrideNotOnOverloadsImplementation]\n# flags: --python-version 3.12\nfrom typing import overload, override\n\nclass A:\n    def f(self, x: int) -> str: pass\n\nclass B(A):\n    @overload  # E: Method \"f2\" is marked as an override, but no base method was found with this name\n    def f2(self, x: int) -> str: pass\n    @override\n    @overload\n    def f2(self, x: str) -> str: pass\n    def f2(self, x: int | str) -> str: pass\n\nclass C(A):\n    @overload\n    def f(self, y: int) -> str: pass\n    @override\n    @overload\n    def f(self, y: str) -> str: pass\n    def f(self, y: int | str) -> str: pass\n[typing fixtures/typing-override.pyi]\n\n[case explicitOverrideOnMultipleOverloads]\n# flags: --python-version 3.12\nfrom typing import overload, override\n\nclass A:\n    def f(self, x: int) -> str: pass\n\nclass B(A):\n    @override  # E: Method \"f2\" is marked as an override, but no base method was found with this name\n    @overload\n    def f2(self, x: int) -> str: pass\n    @override\n    @overload\n    def f2(self, x: str) -> str: pass\n    def f2(self, x: int | str) -> str: pass\n\nclass C(A):\n    @overload\n    def f(self, y: int) -> str: pass\n    @override\n    @overload\n    def f(self, y: str) -> str: pass\n    @override\n    def f(self, y: int | str) -> str: pass\n[typing fixtures/typing-override.pyi]\n\n[case explicitOverrideCyclicDependency]\n# flags: --python-version 3.12\nimport b\n[file a.py]\nfrom typing import override\nimport b\nimport c\n\nclass A(b.B):\n    @override  # This is fine\n    @c.deco\n    def meth(self) -> int: ...\n[file b.py]\nimport a\nimport c\n\nclass B:\n    @c.deco\n    def meth(self) -> int: ...\n[file c.py]\nfrom typing import TypeVar, Tuple, Callable\nT = TypeVar('T')\ndef deco(f: Callable[..., T]) -> Callable[..., Tuple[T, int]]: ...\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-override.pyi]\n\n[case requireExplicitOverrideMethod]\n# flags: --enable-error-code explicit-override --python-version 3.12\nfrom typing import override\n\nclass A:\n    def f(self, x: int) -> str: pass\n\nclass B(A):\n    @override\n    def f(self, y: int) -> str: pass\n\nclass C(A):\n    def f(self, y: int) -> str: pass  # E: Method \"f\" is not using @override but is overriding a method in class \"__main__.A\"\n\nclass D(B):\n    def f(self, y: int) -> str: pass  # E: Method \"f\" is not using @override but is overriding a method in class \"__main__.B\"\n[typing fixtures/typing-override.pyi]\n\n[case requireExplicitOverrideSpecialMethod]\n# flags: --enable-error-code explicit-override --python-version 3.12\nfrom typing import Callable, Self, TypeVar, override, overload\n\nT = TypeVar('T')\ndef some_decorator(f: Callable[..., T]) -> Callable[..., T]: ...\n\n# Don't require override decorator for __init__ and __new__\n# See: https://github.com/python/typing/issues/1376\nclass A:\n    def __init__(self) -> None: pass\n    def __new__(cls) -> Self: pass\n\nclass B(A):\n    def __init__(self) -> None: pass\n    def __new__(cls) -> Self: pass\n\nclass C(A):\n    @some_decorator\n    def __init__(self) -> None: pass\n\n    @some_decorator\n    def __new__(cls) -> Self: pass\n\nclass D(A):\n    @overload\n    def __init__(self, x: int) -> None: ...\n    @overload\n    def __init__(self, x: str) -> None: ...\n    def __init__(self, x): pass\n\n    @overload\n    def __new__(cls, x: int) -> Self: pass\n    @overload\n    def __new__(cls, x: str) -> Self: pass\n    def __new__(cls, x): pass\n[typing fixtures/typing-override.pyi]\n\n[case requireExplicitOverrideProperty]\n# flags: --enable-error-code explicit-override --python-version 3.12\nfrom typing import override\n\nclass A:\n    @property\n    def prop(self) -> int: pass\n\nclass B(A):\n    @override\n    @property\n    def prop(self) -> int: pass\n\nclass C(A):\n    @property\n    def prop(self) -> int: pass  # E: Method \"prop\" is not using @override but is overriding a method in class \"__main__.A\"\n[typing fixtures/typing-override.pyi]\n[builtins fixtures/property.pyi]\n\n[case requireExplicitOverrideOverload]\n# flags: --enable-error-code explicit-override --python-version 3.12\nfrom typing import overload, override\n\nclass A:\n    @overload\n    def f(self, x: int) -> str: ...\n    @overload\n    def f(self, x: str) -> str: ...\n    def f(self, x): pass\n\nclass B(A):\n    @overload\n    def f(self, y: int) -> str: ...\n    @overload\n    def f(self, y: str) -> str: ...\n    @override\n    def f(self, y): pass\n\nclass C(A):\n    @overload\n    @override\n    def f(self, y: int) -> str: ...\n    @overload\n    def f(self, y: str) -> str: ...\n    def f(self, y): pass\n\nclass D(A):\n    @overload\n    def f(self, y: int) -> str: ...\n    @overload\n    def f(self, y: str) -> str: ...\n    def f(self, y): pass  # E: Method \"f\" is not using @override but is overriding a method in class \"__main__.A\"\n[typing fixtures/typing-override.pyi]\n\n[case requireExplicitOverrideMultipleInheritance]\n# flags: --enable-error-code explicit-override --python-version 3.12\nfrom typing import override\n\nclass A:\n    def f(self, x: int) -> str: pass\nclass B:\n    def f(self, y: int) -> str: pass\n\nclass C(A, B):\n    @override\n    def f(self, z: int) -> str: pass\n\nclass D(A, B):\n    def f(self, z: int) -> str: pass  # E: Method \"f\" is not using @override but is overriding a method in class \"__main__.A\"\n[typing fixtures/typing-override.pyi]\n\n[case testExplicitOverrideAllowedForPrivate]\n# flags: --enable-error-code explicit-override --python-version 3.12\n\nclass B:\n    def __f(self, y: int) -> str: pass\n\nclass C(B):\n    def __f(self, y: int) -> str: pass  # OK\n[typing fixtures/typing-override.pyi]\n\n[case testOverrideUntypedDef]\n# flags: --python-version 3.12\nfrom typing import override\n\nclass Parent: pass\n\nclass Child(Parent):\n    @override\n    def foo(self, y): pass  # E: Method \"foo\" is marked as an override, but no base method was found with this name\n\n[typing fixtures/typing-override.pyi]\n\n[case testOverrideOnUnknownBaseClass]\n# flags: --python-version 3.12\nfrom typing import overload, override\n\nfrom unknown import UnknownParent  # type: ignore[import-not-found]\n\nclass UnknownChild(UnknownParent):\n    @override\n    def foo(self, y): pass  # OK\n    @override\n    def bar(self, y: str) -> None: pass  # OK\n\n    @override\n    @overload\n    def baz(self, y: str) -> None: ...\n    @override\n    @overload\n    def baz(self, y: int) -> None: ...\n    def baz(self, y: str | int) -> None: ...\n[typing fixtures/typing-override.pyi]\n\n[case testCallableProperty]\nfrom typing import Callable\n\nclass something_callable:\n    def __call__(self, fn) -> str: ...\n\ndef decorator(fn: Callable[..., int]) -> something_callable: ...\n\nclass A:\n    @property\n    @decorator\n    def f(self) -> int: ...\n\nreveal_type(A.f)  # N: Revealed type is \"__main__.something_callable\"\nreveal_type(A().f)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/property.pyi]\n\n[case testFinalOverrideOnUntypedDef]\nfrom typing import final\n\nclass Base:\n    @final\n    def foo(self):\n        pass\n\nclass Derived(Base):\n    def foo(self):  # E: Cannot override final attribute \"foo\" (previously declared in base class \"Base\")\n        pass\n\n[case testTypeVarIdClashPolymorphic]\nfrom typing import Callable, Generic, TypeVar\n\nA = TypeVar(\"A\")\nB = TypeVar(\"B\")\n\nclass Gen(Generic[A]): ...\n\ndef id_(x: A) -> A: ...\ndef f(x: Gen[A], y: A) -> Gen[Gen[A]]: ...\ndef g(x: Gen[A], id_: Callable[[B], B], f: Callable[[A, B], Gen[A]]) -> A: ...\n\ndef test(x: Gen[Gen[A]]) -> Gen[A]:\n    return g(x, id_, f)  # Technically OK\n\nx: Gen[Gen[int]]\nreveal_type(g(x, id_, f))  # N: Revealed type is \"__main__.Gen[builtins.int]\"\n\ndef h(x: A, y: A) -> A: ...\ndef gn(id_: Callable[[B], B], step: Callable[[A, B], A]) -> A: ...\n\ndef fn(x: A) -> A:\n    return gn(id_, h)  # Technically OK\n\n[case testTypeVarIdsNested]\nfrom typing import Callable, TypeVar\n\nA = TypeVar(\"A\")\nB = TypeVar(\"B\")\n\ndef f(x: Callable[[A], A]) -> Callable[[B], B]:\n    def g(x: B) -> B: ...\n    return g\n\nreveal_type(f(f))  # N: Revealed type is \"def [B] (B`1) -> B`1\"\nreveal_type(f(f)(f))  # N: Revealed type is \"def [A] (x: def (A`-1) -> A`-1) -> def [B] (B`-2) -> B`-2\"\n\n[case testGenericUnionFunctionJoin]\nfrom typing import TypeVar, Union\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\ndef f(x: T, y: S) -> Union[T, S]: ...\ndef g(x: T, y: S) -> Union[T, S]: ...\n\nx = [f, g]\nreveal_type(x)  # N: Revealed type is \"builtins.list[def [T, S] (x: T`4, y: S`5) -> T`4 | S`5]\"\n[builtins fixtures/list.pyi]\n\n[case testTypeVariableClashErrorMessage]\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\n\nclass C:  # Note: Generic[T] missing\n    def bad_idea(self, x: T) -> None:\n        self.x = x\n\n    def nope(self, x: T) -> None:\n        self.x = x  # E: Incompatible types in assignment (expression has type \"T@nope\", variable has type \"T@bad_idea\")\n\n[case testNoCrashOnBadCallablePropertyOverride]\nfrom typing import Callable, Union\n\nclass C: ...\nclass D: ...\n\nA = Callable[[C], None]\nB = Callable[[D], None]\n\nclass Foo:\n    @property\n    def method(self) -> Callable[[int, Union[A, B]], None]:\n        ...\n\nclass Bar(Foo):\n    @property\n    def method(self) -> Callable[[int, A], None]:  # E: Argument 2 of \"method\" is incompatible with supertype \"Foo\"; supertype defines the argument type as \"Callable[[C], None] | Callable[[D], None]\" \\\n                                                   # N: This violates the Liskov substitution principle \\\n                                                   # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n        ...\n[builtins fixtures/property.pyi]\n\n[case testNoCrashOnUnpackOverride]\nfrom typing import TypedDict, Unpack\n\nclass Params(TypedDict):\n    x: int\n    y: str\n\nclass Other(TypedDict):\n    x: int\n    y: int\n\nclass B:\n    def meth(self, **kwargs: Unpack[Params]) -> None:\n        ...\nclass C(B):\n    def meth(self, **kwargs: Unpack[Other]) -> None:  # E: Signature of \"meth\" incompatible with supertype \"B\" \\\n                                                      # N:      Superclass: \\\n                                                      # N:          def meth(*, x: int, y: str) -> None \\\n                                                      # N:      Subclass: \\\n                                                      # N:          def meth(*, x: int, y: int) -> None\n        ...\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testOverrideErrorLocationNamed]\nclass B:\n    def meth(\n        self, *,\n        x: int,\n        y: str,\n    ) -> None:\n        ...\nclass C(B):\n    def meth(\n        self, *,\n        y: int,  # E: Argument 1 of \"meth\" is incompatible with supertype \"B\"; supertype defines the argument type as \"str\" \\\n                 # N: This violates the Liskov substitution principle \\\n                 # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n        x: int,\n    ) -> None:\n        ...\n[builtins fixtures/tuple.pyi]\n\n[case testLambdaAlwaysAllowed]\n# flags: --disallow-untyped-calls\nfrom typing import Callable, Optional\n\ndef func() -> Optional[str]: ...\nvar: Optional[str]\n\nfactory: Callable[[], Optional[str]]\nfor factory in (\n    lambda: var,\n    func,\n):\n    reveal_type(factory)  # N: Revealed type is \"def () -> builtins.str | None\"\n    var = factory()\n[builtins fixtures/tuple.pyi]\n\n[case testLambdaInDeferredDecoratorNoCrash]\ndef foo(x):\n    pass\n\nclass Bar:\n    def baz(self, x):\n        pass\n\nclass Qux(Bar):\n    @foo(lambda x: None)\n    def baz(self, x) -> None:\n        pass\n[builtins fixtures/tuple.pyi]\n\n[case testGeneratorInDeferredDecoratorNoCrash]\nfrom typing import Protocol, TypeVar\n\nT = TypeVar(\"T\", covariant=True)\n\nclass SupportsNext(Protocol[T]):\n    def __next__(self) -> T: ...\n\ndef next(i: SupportsNext[T]) -> T: ...\n\ndef foo(x):\n    pass\n\nclass Bar:\n    def baz(self, x):\n        pass\n\nclass Qux(Bar):\n    @next(f for f in [foo])\n    def baz(self, x) -> None:\n        pass\n[builtins fixtures/tuple.pyi]\n\n[case testCallableJoinWithDefaults]\nfrom typing import Callable, TypeVar\n\nT = TypeVar(\"T\")\n\ndef join(t1: T, t2: T) -> T: ...\n\ndef f1() -> None: ...\ndef f2(i: int = 0) -> None: ...\ndef f3(i: str = \"\") -> None: ...\n\nreveal_type(join(f1, f2))  # N: Revealed type is \"def ()\"\nreveal_type(join(f1, f3))  # N: Revealed type is \"def ()\"\nreveal_type(join(f2, f3))  # N: Revealed type is \"builtins.function\"  # TODO: this could be better\n[builtins fixtures/tuple.pyi]\n\n[case testCallableJoinWithDefaultsMultiple]\nfrom typing import TypeVar\nT = TypeVar(\"T\")\ndef join(t1: T, t2: T, t3: T) -> T: ...\n\ndef f_1(common, a=None): ...\ndef f_any(*_, **__): ...\ndef f_3(common, b=None, x=None): ...\n\nfdict = {\n    \"f_1\": f_1,\n    \"f_any\": f_any,\n    \"f_3\": f_3,\n}\nreveal_type(fdict)  # N: Revealed type is \"builtins.dict[builtins.str, def (common: Any, a: Any =) -> Any]\"\n\nreveal_type(join(f_1, f_any, f_3))  # N: Revealed type is \"def (common: Any, a: Any =) -> Any\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testCallableJoinWithType]\nfrom __future__ import annotations\nclass Exc: ...\nclass AttributeErr(Exc):\n    def __init__(self, *args: object) -> None: ...\nclass FnfErr(Exc): ...\n\nx = [\n    FnfErr,\n    AttributeErr,\n]\nreveal_type(x)  # N: Revealed type is \"builtins.list[builtins.type]\"\n[builtins fixtures/type.pyi]\n\n[case testDistinctFormatting]\nfrom typing import Awaitable, Callable, ParamSpec\n\nP = ParamSpec(\"P\")\n\nclass A: pass\nclass B(A): pass\n\ndef decorator(f: Callable[P, None]) -> Callable[[Callable[P, A]], None]:\n    return lambda _: None\n\ndef key(x: int) -> None: ...\ndef fn_b(b: int) -> B: ...\n\ndecorator(key)(fn_b)  # E: Argument 1 has incompatible type \"def fn_b(b: int) -> B\"; expected \"def (x: int) -> A\"\n\ndef decorator2(f: Callable[P, None]) -> Callable[\n    [Callable[P, Awaitable[None]]],\n    Callable[P, Awaitable[None]],\n]:\n    return lambda f: f\n\ndef key2(x: int) -> None:\n    ...\n\n@decorator2(key2)  # E: Argument 1 has incompatible type \"def foo2(y: int) -> Coroutine[Any, Any, None]\"; expected \"def (x: int) -> Awaitable[None]\"\nasync def foo2(y: int) -> None:\n    ...\n\nclass Parent:\n    def method_without(self) -> \"Parent\": ...\n    def method_with(self, param: str) -> \"Parent\": ...\n\nclass Child(Parent):\n    method_without: Callable[[], \"Child\"]\n    method_with: Callable[[str], \"Child\"]  # E: Incompatible types in assignment (expression has type \"Callable[[str], Child]\", base class \"Parent\" defined the type as \"def method_with(self, param: str) -> Parent\")\n[builtins fixtures/tuple.pyi]\n\n[case testDistinctFormattingUnion]\nfrom typing import Callable, Union\nfrom mypy_extensions import Arg\n\ndef f(x: Callable[[Arg(int, 'x')], None]) -> None: pass\n\ny: Callable[[Union[int, str]], None]\nf(y)  # E: Argument 1 to \"f\" has incompatible type \"Callable[[int | str], None]\"; expected \"def (x: int) -> None\"\n[builtins fixtures/tuple.pyi]\n\n[case testAbstractOverloadsWithoutImplementationAllowed]\nfrom abc import abstractmethod\nfrom typing import overload, Union\n\nclass Foo:\n    @overload\n    @abstractmethod\n    def foo(self, value: int) -> int:\n        ...\n    @overload\n    @abstractmethod\n    def foo(self, value: str) -> str:\n        ...\n\nclass Bar(Foo):\n    @overload\n    def foo(self, value: int) -> int:\n        ...\n    @overload\n    def foo(self, value: str) -> str:\n        ...\n\n    def foo(self, value: Union[int, str]) -> Union[int, str]:\n        return super().foo(value)  # E: Call to abstract method \"foo\" of \"Foo\" with trivial body via super() is unsafe\n\n[case fullNamesOfImportedBaseClassesDisplayed]\nfrom a import A\n\nclass B(A):\n    def f(self, x: str) -> None:  # E: Argument 1 of \"f\" is incompatible with supertype \"a.A\"; supertype defines the argument type as \"int\" \\\n                                  # N: This violates the Liskov substitution principle \\\n                                  # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n        ...\n    def g(self, x: str) -> None:  # E: Signature of \"g\" incompatible with supertype \"a.A\" \\\n                                  # N:      Superclass: \\\n                                  # N:          def g(self) -> None \\\n                                  # N:      Subclass: \\\n                                  # N:          def g(self, x: str) -> None\n        ...\n\n[file a.py]\nclass A:\n    def f(self, x: int) -> None:\n        ...\n    def g(self) -> None:\n        ...\n\n[case testBoundMethodsAssignedInClassBody]\nfrom typing import Callable\n\nclass A:\n    def f(self, x: int) -> str:\n        pass\n    @classmethod\n    def g(cls, x: int) -> str:\n        pass\n    @staticmethod\n    def h(x: int) -> str:\n        pass\n    attr: Callable[[int], str]\n\nclass C:\n    x1 = A.f\n    x2 = A.g\n    x3 = A().f\n    x4 = A().g\n    x5 = A.h\n    x6 = A().h\n    x7 = A().attr\n\nreveal_type(C.x1)  # N: Revealed type is \"def (self: __main__.A, x: builtins.int) -> builtins.str\"\nreveal_type(C.x2)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C.x3)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C.x4)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C.x5)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C.x6)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C.x7)  # N: Revealed type is \"def (builtins.int) -> builtins.str\"\n\nreveal_type(C().x1)  # E: Invalid self argument \"C\" to attribute function \"x1\" with type \"Callable[[A, int], str]\" \\\n                     # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C().x2)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C().x3)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C().x4)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C().x5)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C().x6)  # N: Revealed type is \"def (x: builtins.int) -> builtins.str\"\nreveal_type(C().x7)  # E: Invalid self argument \"C\" to attribute function \"x7\" with type \"Callable[[int], str]\" \\\n                     # N: Revealed type is \"def () -> builtins.str\"\n[builtins fixtures/classmethod.pyi]\n\n[case testFunctionRedefinitionDeferred]\nfrom typing import Callable, TypeVar\n\ndef outer() -> None:\n    if bool():\n        def inner() -> str: ...\n    else:\n        def inner() -> int: ...  # E: All conditional function variants must have identical signatures \\\n                                 # N: Original: \\\n                                 # N:     def inner() -> str \\\n                                 # N: Redefinition: \\\n                                 # N:     def inner() -> int\n    x = defer()\n\nT = TypeVar(\"T\")\ndef deco(fn: Callable[[], T]) -> Callable[[], list[T]]: ...\n\n@deco\ndef defer() -> int: ...\n[builtins fixtures/list.pyi]\n\n[case testCheckFunctionErrorContextDuplicateDeferred]\n# flags: --show-error-context\nfrom typing import Callable, TypeVar\n\ndef a() -> None:\n    def b() -> None:\n        1 + \"\"\n        x = defer()\n\nT = TypeVar(\"T\")\ndef deco(fn: Callable[[], T]) -> Callable[[], list[T]]: ...\n\n@deco\ndef defer() -> int: ...\n[out]\nmain: note: In function \"a\":\nmain:6: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testNoExtraNoteForUnpacking]\nfrom typing import Protocol\n\nclass P(Protocol):\n    arg: int\n    # Something that list and dict also have\n    def __contains__(self, item: object) -> bool: ...\n\ndef foo(x: P, y: P) -> None: ...\n\nargs: list[object]\nfoo(*args)  # E: Argument 1 to \"foo\" has incompatible type \"*list[object]\"; expected \"P\"\nkwargs: dict[str, object]\nfoo(**kwargs)  # E: Argument 1 to \"foo\" has incompatible type \"**dict[str, object]\"; expected \"P\"\n[builtins fixtures/dict.pyi]\n\n[case testNoImplicitReturnErrorOnDeferral_no_empty]\n# flags: --no-warn-no-return\ndef deferred() -> int:\n    c: C\n    x = 1\n    if int():\n        x = c.x\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    return x\n\nclass C:\n    def __init__(self) -> None:\n        self.x = defer()\n\ndef defer() -> int:\n    return 1\n"
  },
  {
    "path": "test-data/unit/check-functools.test",
    "content": "[case testTotalOrderingEqLt]\nfrom functools import total_ordering\n\n@total_ordering\nclass Ord:\n    def __eq__(self, other: object) -> bool:\n        return False\n\n    def __lt__(self, other: \"Ord\") -> bool:\n        return False\n\nreveal_type(Ord() < Ord())  # N: Revealed type is \"builtins.bool\"\nreveal_type(Ord() <= Ord())  # N: Revealed type is \"builtins.bool\"\nreveal_type(Ord() == Ord())  # N: Revealed type is \"builtins.bool\"\nreveal_type(Ord() > Ord())  # N: Revealed type is \"builtins.bool\"\nreveal_type(Ord() >= Ord())  # N: Revealed type is \"builtins.bool\"\n\nOrd() < 1  # E: Unsupported operand types for < (\"Ord\" and \"int\")\nOrd() <= 1  # E: Unsupported operand types for <= (\"Ord\" and \"int\")\nOrd() == 1\nOrd() > 1  # E: Unsupported operand types for > (\"Ord\" and \"int\")\nOrd() >= 1  # E: Unsupported operand types for >= (\"Ord\" and \"int\")\n[builtins fixtures/dict.pyi]\n\n[case testTotalOrderingLambda]\nfrom functools import total_ordering\nfrom typing import Any, Callable, ClassVar\n\n@total_ordering\nclass Ord:\n    __eq__: Callable[[Any, object], bool] = lambda self, other: False\n    __lt__: Callable[[Any, \"Ord\"], bool] = lambda self, other: False\n\nreveal_type(Ord() < Ord())  # N: Revealed type is \"builtins.bool\"\nreveal_type(Ord() <= Ord())  # N: Revealed type is \"builtins.bool\"\nreveal_type(Ord() == Ord())  # N: Revealed type is \"builtins.bool\"\nreveal_type(Ord() > Ord())  # N: Revealed type is \"builtins.bool\"\nreveal_type(Ord() >= Ord())  # N: Revealed type is \"builtins.bool\"\n\nOrd() < 1  # E: Argument 1 has incompatible type \"int\"; expected \"Ord\"\nOrd() <= 1  # E: Unsupported operand types for <= (\"Ord\" and \"int\")\nOrd() == 1\nOrd() > 1  # E: Unsupported operand types for > (\"Ord\" and \"int\")\nOrd() >= 1  # E: Unsupported operand types for >= (\"Ord\" and \"int\")\n[builtins fixtures/dict.pyi]\n\n[case testTotalOrderingNonCallable]\nfrom functools import total_ordering\n\n@total_ordering\nclass Ord(object):\n    def __eq__(self, other: object) -> bool:\n        return False\n\n    __lt__ = 5\n\nOrd() <= Ord()  # E: Unsupported left operand type for <= (\"Ord\")\nOrd() > Ord()  # E: \"int\" not callable\nOrd() >= Ord()  # E: Unsupported left operand type for >= (\"Ord\")\n[builtins fixtures/dict.pyi]\n\n[case testTotalOrderingReturnNotBool]\nfrom functools import total_ordering\n\n@total_ordering\nclass Ord:\n    def __eq__(self, other: object) -> bool:\n        return False\n\n    def __lt__(self, other: \"Ord\") -> str:\n        return \"blah\"\n\nreveal_type(Ord() < Ord())  # N: Revealed type is \"builtins.str\"\nreveal_type(Ord() <= Ord())  # N: Revealed type is \"Any\"\nreveal_type(Ord() == Ord())  # N: Revealed type is \"builtins.bool\"\nreveal_type(Ord() > Ord())  # N: Revealed type is \"Any\"\nreveal_type(Ord() >= Ord())  # N: Revealed type is \"Any\"\n[builtins fixtures/dict.pyi]\n\n[case testTotalOrderingAllowsAny]\nfrom functools import total_ordering\n\n@total_ordering\nclass Ord:\n    def __eq__(self, other):\n        return False\n\n    def __gt__(self, other):\n        return False\n\nreveal_type(Ord() < Ord())  # N: Revealed type is \"Any\"\nOrd() <= Ord()  # E: Unsupported left operand type for <= (\"Ord\")\nreveal_type(Ord() == Ord())  # N: Revealed type is \"Any\"\nreveal_type(Ord() > Ord())  # N: Revealed type is \"Any\"\nOrd() >= Ord()  # E: Unsupported left operand type for >= (\"Ord\")\n\nOrd() < 1  # E: Unsupported left operand type for < (\"Ord\")\nOrd() <= 1  # E: Unsupported left operand type for <= (\"Ord\")\nOrd() == 1\nOrd() > 1\nOrd() >= 1  # E: Unsupported left operand type for >= (\"Ord\")\n[builtins fixtures/dict.pyi]\n\n[case testCachedProperty]\nfrom functools import cached_property\nclass Parent:\n    @property\n    def f(self) -> str: pass\nclass Child(Parent):\n    @cached_property\n    def f(self) -> str: pass\n    @cached_property\n    def g(self) -> int: pass\n    @cached_property  # E: Too many arguments for property\n    def h(self, arg) -> int: pass\nreveal_type(Parent().f)  # N: Revealed type is \"builtins.str\"\nreveal_type(Child().f)  # N: Revealed type is \"builtins.str\"\nreveal_type(Child().g)  # N: Revealed type is \"builtins.int\"\nChild().f = \"Hello World\"\nChild().g = \"invalid\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[file functools.pyi]\nimport sys\nfrom typing import TypeVar, Generic\n_T = TypeVar('_T')\nclass cached_property(Generic[_T]): ...\n[builtins fixtures/property.pyi]\n\n[case testTotalOrderingWithForwardReference]\nfrom typing import Generic, Any, TypeVar\nimport functools\n\nT = TypeVar(\"T\", bound=\"C\")\n\n@functools.total_ordering\nclass D(Generic[T]):\n    def __lt__(self, other: Any) -> bool:\n        ...\n\nclass C:\n    pass\n\ndef f(d: D[C]) -> None:\n    reveal_type(d.__gt__)  # N: Revealed type is \"def (other: Any) -> builtins.bool\"\n\nd: D[int]  # E: Type argument \"int\" of \"D\" must be a subtype of \"C\"\n[builtins fixtures/dict.pyi]\n\n[case testFunctoolsPartialBasic]\nfrom typing import Callable\nimport functools\n\ndef foo(a: int, b: str, c: int = 5) -> int: ...\n\np1 = functools.partial(foo)\np1(1, \"a\", 3)  # OK\np1(1, \"a\", c=3)  # OK\np1(1, b=\"a\", c=3)  # OK\n\nreveal_type(p1)  # N: Revealed type is \"functools.partial[builtins.int]\"\n\ndef takes_callable_int(f: Callable[..., int]) -> None: ...\ndef takes_callable_str(f: Callable[..., str]) -> None: ...\ntakes_callable_int(p1)\ntakes_callable_str(p1)  # E: Argument 1 to \"takes_callable_str\" has incompatible type \"partial[int]\"; expected \"Callable[..., str]\" \\\n                        # N: \"partial[int].__call__\" has type \"def __call__(__self, *args: Any, **kwargs: Any) -> int\"\n\np2 = functools.partial(foo, 1)\np2(\"a\")  # OK\np2(\"a\", 3)  # OK\np2(\"a\", c=3)  # OK\np2(1, 3)  # E: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\np2(1, \"a\", 3)  # E: Too many arguments for \"foo\" \\\n               # E: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\" \\\n               # E: Argument 2 to \"foo\" has incompatible type \"str\"; expected \"int\"\np2(a=1, b=\"a\", c=3)  # E: Unexpected keyword argument \"a\" for \"foo\"\n\np3 = functools.partial(foo, b=\"a\")\np3(1)  # OK\np3(1, c=3)  # OK\np3(a=1)  # OK\np3(1, b=\"a\", c=3)  # OK, keywords can be clobbered\np3(1, 3)  # E: Too many positional arguments for \"foo\" \\\n          # E: Argument 2 to \"foo\" has incompatible type \"int\"; expected \"str\"\n\nfunctools.partial(foo, \"a\")  # E: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\nfunctools.partial(foo, b=1)  # E: Argument \"b\" to \"foo\" has incompatible type \"int\"; expected \"str\"\nfunctools.partial(foo, a=1, b=2, c=3)  # E: Argument \"b\" to \"foo\" has incompatible type \"int\"; expected \"str\"\nfunctools.partial(1)  # E: \"int\" not callable \\\n                      # E: Argument 1 to \"partial\" has incompatible type \"int\"; expected \"Callable[..., Never]\"\n[builtins fixtures/dict.pyi]\n\n[case testFunctoolsPartialStar]\nimport functools\nfrom typing import List\n\ndef foo(a: int, b: str, *args: int, d: str, **kwargs: int) -> int: ...\n\np1 = functools.partial(foo, 1, d=\"a\", x=9)\np1(\"a\", 2, 3, 4)  # OK\np1(\"a\", 2, 3, 4, d=\"a\")  # OK\np1(\"a\", 2, 3, 4, \"a\")  # E: Argument 5 to \"foo\" has incompatible type \"str\"; expected \"int\"\np1(\"a\", 2, 3, 4, x=\"a\")  # E: Argument \"x\" to \"foo\" has incompatible type \"str\"; expected \"int\"\n\np2 = functools.partial(foo, 1, \"a\")\np2(2, 3, 4, d=\"a\")  # OK\np2(\"a\")  # E: Missing named argument \"d\" for \"foo\" \\\n         # E: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\np2(2, 3, 4)  # E: Missing named argument \"d\" for \"foo\"\n\nfunctools.partial(foo, 1, \"a\", \"b\", \"c\", d=\"a\")  # E: Argument 3 to \"foo\" has incompatible type \"str\"; expected \"int\" \\\n                                                 # E: Argument 4 to \"foo\" has incompatible type \"str\"; expected \"int\"\n\ndef bar(*a: bytes, **k: int):\n    p1(\"a\", 2, 3, 4, d=\"a\", **k)\n    p1(\"a\", d=\"a\", **k)\n    p1(\"a\", **k)  # E: Argument 2 to \"foo\" has incompatible type \"**dict[str, int]\"; expected \"str\"\n    p1(**k)  # E: Argument 1 to \"foo\" has incompatible type \"**dict[str, int]\"; expected \"str\"\n    p1(*a)  # E: Expected iterable as variadic argument\n\n\ndef baz(a: int, b: int) -> int: ...\ndef test_baz(xs: List[int]):\n    p3 = functools.partial(baz, *xs)\n    p3()\n    p3(1)  # E: Too many arguments for \"baz\"\n\n\n[builtins fixtures/dict.pyi]\n\n[case testFunctoolsPartialGeneric]\nfrom typing import TypeVar\nimport functools\n\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\ndef foo(a: T, b: T) -> T: ...\n\np1 = functools.partial(foo, 1)\nreveal_type(p1(2))  # N: Revealed type is \"builtins.int\"\np1(\"a\")  # E: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\n\np2 = functools.partial(foo, \"a\")\np2(1)  # E: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\nreveal_type(p2(\"a\"))  # N: Revealed type is \"builtins.str\"\n\ndef bar(a: T, b: U) -> U: ...\n\np3 = functools.partial(bar, 1)\nreveal_type(p3(2))  # N: Revealed type is \"builtins.int\"\nreveal_type(p3(\"a\"))  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n\n[case testFunctoolsPartialCallable]\nfrom typing import Callable\nimport functools\n\ndef main1(f: Callable[[int, str], int]) -> None:\n    p = functools.partial(f, 1)\n    p(\"a\")  # OK\n    p(1)  # E: Argument 1 has incompatible type \"int\"; expected \"str\"\n\n    functools.partial(f, a=1)  # E: Unexpected keyword argument \"a\"\n\nclass CallbackProto:\n    def __call__(self, a: int, b: str) -> int: ...\n\ndef main2(f: CallbackProto) -> None:\n    p = functools.partial(f, b=\"a\")\n    p(1)  # OK\n    p(\"a\")  # E: Argument 1 to \"__call__\" of \"CallbackProto\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testFunctoolsPartialOverload]\nfrom typing import overload\nimport functools\n\n@overload\ndef foo(a: int, b: str) -> int: ...\n@overload\ndef foo(a: str, b: int) -> str: ...\ndef foo(*a, **k): ...\n\np1 = functools.partial(foo)\nreveal_type(p1(1, \"a\"))  # N: Revealed type is \"builtins.int\"\nreveal_type(p1(\"a\", 1))  # N: Revealed type is \"builtins.int\"\np1(1, 2)  # TODO: false negative\np1(\"a\", \"b\")  # TODO: false negative\n[builtins fixtures/dict.pyi]\n\n[case testFunctoolsPartialTypeGuard]\nimport functools\nfrom typing_extensions import TypeGuard\n\ndef is_str_list(val: list[object]) -> TypeGuard[list[str]]: ...\n\nreveal_type(functools.partial(is_str_list, [1, 2, 3]))  # N: Revealed type is \"functools.partial[builtins.bool]\"\nreveal_type(functools.partial(is_str_list, [1, 2, 3])())  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/dict.pyi]\n\n[case testFunctoolsPartialType]\nimport functools\nfrom typing import Type\n\nclass A:\n    def __init__(self, a: int, b: str) -> None: ...\n\np = functools.partial(A, 1)\nreveal_type(p)  # N: Revealed type is \"functools.partial[__main__.A]\"\n\np(\"a\")  # OK\np(1)  # E: Argument 1 to \"A\" has incompatible type \"int\"; expected \"str\"\np(z=1)  # E: Unexpected keyword argument \"z\" for \"A\"\n\ndef main(t: Type[A]) -> None:\n    p = functools.partial(t, 1)\n    reveal_type(p)  # N: Revealed type is \"functools.partial[__main__.A]\"\n\n    p(\"a\")  # OK\n    p(1)  # E: Argument 1 to \"A\" has incompatible type \"int\"; expected \"str\"\n    p(z=1)  # E: Unexpected keyword argument \"z\" for \"A\"\n\n[builtins fixtures/dict.pyi]\n\n[case testFunctoolsPartialTypeVarTuple]\nimport functools\nimport typing\nTs = typing.TypeVarTuple(\"Ts\")\ndef foo(fn: typing.Callable[[typing.Unpack[Ts]], None], /, *arg: typing.Unpack[Ts], kwarg: str) -> None: ...\np = functools.partial(foo, kwarg=\"asdf\")\n\ndef bar(a: int, b: str, c: float) -> None: ...\np(bar, 1, \"a\", 3.0)  # OK\np(bar, 1, \"a\", 3.0, kwarg=\"asdf\")  # OK\np(bar, 1, \"a\", \"b\")  # E: Argument 1 to \"foo\" has incompatible type \"Callable[[int, str, float], None]\"; expected \"Callable[[int, str, str], None]\"\n[builtins fixtures/dict.pyi]\n\n[case testFunctoolsPartialUnion]\nimport functools\nfrom typing import Any, Callable, Union\n\ncls1: Any\ncls2: Union[Any, Any]\nreveal_type(functools.partial(cls1, 2)())  # N: Revealed type is \"Any\"\nreveal_type(functools.partial(cls2, 2)())  # N: Revealed type is \"Any\"\n\nfn1: Union[Callable[[int], int], Callable[[int], int]]\nreveal_type(functools.partial(fn1, 2)())  # N: Revealed type is \"builtins.int\"\n\nfn2: Union[Callable[[int], int], Callable[[int], str]]\nreveal_type(functools.partial(fn2, 2)())  # N: Revealed type is \"builtins.int | builtins.str\"\n\nfn3: Union[Callable[[int], int], str]\nreveal_type(functools.partial(fn3, 2)())  # E: \"str\" not callable \\\n                                          # N: Revealed type is \"builtins.int\" \\\n                                          # E: Argument 1 to \"partial\" has incompatible type \"Callable[[int], int] | str\"; expected \"Callable[..., int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialUnionOfTypeAndCallable]\nimport functools\nfrom typing import Callable, Union, Type\nfrom typing_extensions import TypeAlias\n\nclass FooBar:\n    def __init__(self, arg1: str) -> None:\n        pass\n\ndef f1(t: Union[Type[FooBar], Callable[..., 'FooBar']]) -> None:\n    val = functools.partial(t)\n\nFooBarFunc: TypeAlias = Callable[..., 'FooBar']\n\ndef f2(t: Union[Type[FooBar], FooBarFunc]) -> None:\n    val = functools.partial(t)\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialExplicitType]\nfrom functools import partial\nfrom typing import Type, TypeVar, Callable\n\nT = TypeVar(\"T\")\ndef generic(string: str, integer: int, resulting_type: Type[T]) -> T: ...\n\np: partial[str] = partial(generic, resulting_type=str)\nq: partial[bool] = partial(generic, resulting_type=str)  # E: Argument \"resulting_type\" to \"generic\" has incompatible type \"type[str]\"; expected \"type[bool]\"\n\npc: Callable[..., str] = partial(generic, resulting_type=str)\nqc: Callable[..., bool] = partial(generic, resulting_type=str)  # E: Incompatible types in assignment (expression has type \"partial[str]\", variable has type \"Callable[..., bool]\") \\\n                                                                # N: \"partial[str].__call__\" has type \"def __call__(__self, *args: Any, **kwargs: Any) -> str\"\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialNestedPartial]\nfrom functools import partial\nfrom typing import Any\n\ndef foo(x: int) -> int: ...\np = partial(partial, foo)\nreveal_type(p()(1))  # N: Revealed type is \"builtins.int\"\np()(\"no\")  # E: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\n\nq = partial(partial, partial, foo)\nq()()(\"no\")  # E: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"int\"\n\nr = partial(partial, foo, 1)\nreveal_type(r()())  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialTypeObject]\nimport functools\nfrom typing import Type, Generic, TypeVar\n\nclass A:\n    def __init__(self, val: int) -> None: ...\n\ncls1: Type[A]\nreveal_type(functools.partial(cls1, 2)())  # N: Revealed type is \"__main__.A\"\nfunctools.partial(cls1, \"asdf\")  # E: Argument 1 to \"A\" has incompatible type \"str\"; expected \"int\"\n\nT = TypeVar(\"T\")\nclass B(Generic[T]):\n    def __init__(self, val: T) -> None: ...\n\ncls2: Type[B[int]]\nreveal_type(functools.partial(cls2, 2)())  # N: Revealed type is \"__main__.B[builtins.int]\"\nfunctools.partial(cls2, \"asdf\")  # E: Argument 1 to \"B\" has incompatible type \"str\"; expected \"int\"\n\ndef foo(cls3: Type[B[T]]):\n    reveal_type(functools.partial(cls3, \"asdf\"))  # N: Revealed type is \"functools.partial[__main__.B[T`-1]]\" \\\n                                                  # E: Argument 1 to \"B\" has incompatible type \"str\"; expected \"T\"\n    reveal_type(functools.partial(cls3, 2)())  # N: Revealed type is \"__main__.B[T`-1]\" \\\n                                               # E: Argument 1 to \"B\" has incompatible type \"int\"; expected \"T\"\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialTypedDictUnpack]\nfrom typing import TypedDict\nfrom typing_extensions import Unpack\nfrom functools import partial\n\nclass D1(TypedDict, total=False):\n    a1: int\n\ndef fn1(a1: int) -> None: ...\ndef main1(**d1: Unpack[D1]) -> None:\n    partial(fn1, **d1)()\n    partial(fn1, **d1)(**d1)\n    partial(fn1, **d1)(a1=1)\n    partial(fn1, **d1)(a1=\"asdf\")  # E: Argument \"a1\" to \"fn1\" has incompatible type \"str\"; expected \"int\"\n    partial(fn1, **d1)(oops=1)  # E: Unexpected keyword argument \"oops\" for \"fn1\"\n\ndef fn2(**kwargs: Unpack[D1]) -> None: ...\ndef main2(**d1: Unpack[D1]) -> None:\n    partial(fn2, **d1)()\n    partial(fn2, **d1)(**d1)\n    partial(fn2, **d1)(a1=1)\n    partial(fn2, **d1)(a1=\"asdf\")  # E: Argument \"a1\" to \"fn2\" has incompatible type \"str\"; expected \"int\"\n    partial(fn2, **d1)(oops=1)  # E: Unexpected keyword argument \"oops\" for \"fn2\"\n\nclass D2(TypedDict, total=False):\n    a1: int\n    a2: str\n\nclass A2Good(TypedDict, total=False):\n    a2: str\nclass A2Bad(TypedDict, total=False):\n    a2: int\n\ndef fn3(a1: int, a2: str) -> None: ...\ndef main3(a2good: A2Good, a2bad: A2Bad, **d2: Unpack[D2]) -> None:\n    partial(fn3, **d2)()\n    partial(fn3, **d2)(a1=1, a2=\"asdf\")\n\n    partial(fn3, **d2)(**d2)\n\n    partial(fn3, **d2)(a1=\"asdf\")  # E: Argument \"a1\" to \"fn3\" has incompatible type \"str\"; expected \"int\"\n    partial(fn3, **d2)(a1=1, a2=\"asdf\", oops=1)  # E: Unexpected keyword argument \"oops\" for \"fn3\"\n\n    partial(fn3, **d2)(**a2good)\n    partial(fn3, **d2)(**a2bad)  # E: Argument \"a2\" to \"fn3\" has incompatible type \"int\"; expected \"str\"\n\ndef fn4(**kwargs: Unpack[D2]) -> None: ...\ndef main4(a2good: A2Good, a2bad: A2Bad, **d2: Unpack[D2]) -> None:\n    partial(fn4, **d2)()\n    partial(fn4, **d2)(a1=1, a2=\"asdf\")\n\n    partial(fn4, **d2)(**d2)\n\n    partial(fn4, **d2)(a1=\"asdf\")  # E: Argument \"a1\" to \"fn4\" has incompatible type \"str\"; expected \"int\"\n    partial(fn4, **d2)(a1=1, a2=\"asdf\", oops=1)  # E: Unexpected keyword argument \"oops\" for \"fn4\"\n\n    partial(fn3, **d2)(**a2good)\n    partial(fn3, **d2)(**a2bad)  # E: Argument \"a2\" to \"fn3\" has incompatible type \"int\"; expected \"str\"\n\ndef main5(**d2: Unpack[D2]) -> None:\n    partial(fn1, **d2)()  # E: Extra argument \"a2\" from **args for \"fn1\"\n    partial(fn2, **d2)()  # E: Extra argument \"a2\" from **args for \"fn2\"\n\ndef main6(a2good: A2Good, a2bad: A2Bad, **d1: Unpack[D1]) -> None:\n    partial(fn3, **d1)()  # E: Missing positional argument \"a1\" in call to \"fn3\"\n    partial(fn3, **d1)(\"asdf\")  # E: Too many positional arguments for \"fn3\" \\\n                                # E: Too few arguments for \"fn3\" \\\n                                # E: Argument 1 to \"fn3\" has incompatible type \"str\"; expected \"int\"\n    partial(fn3, **d1)(a2=\"asdf\")\n    partial(fn3, **d1)(**a2good)\n    partial(fn3, **d1)(**a2bad)  # E: Argument \"a2\" to \"fn3\" has incompatible type \"int\"; expected \"str\"\n\n    partial(fn4, **d1)()\n    partial(fn4, **d1)(\"asdf\")  # E: Too many positional arguments for \"fn4\" \\\n                                # E: Argument 1 to \"fn4\" has incompatible type \"str\"; expected \"int\"\n    partial(fn4, **d1)(a2=\"asdf\")\n    partial(fn4, **d1)(**a2good)\n    partial(fn4, **d1)(**a2bad)  # E: Argument \"a2\" to \"fn4\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n\n[case testFunctoolsPartialNestedGeneric]\nfrom functools import partial\nfrom typing import Generic, TypeVar, List\n\nT = TypeVar(\"T\")\ndef get(n: int, args: List[T]) -> T: ...\nfirst = partial(get, 0)\n\nx: List[str]\nreveal_type(first(x))  # N: Revealed type is \"builtins.str\"\nreveal_type(first([1]))  # N: Revealed type is \"builtins.int\"\n\nfirst_kw = partial(get, n=0)\nreveal_type(first_kw(args=[1]))  # N: Revealed type is \"builtins.int\"\n\n# TODO: this is indeed invalid, but the error is incomprehensible.\nfirst_kw([1])  # E: Too many positional arguments for \"get\" \\\n               # E: Too few arguments for \"get\" \\\n               # E: Argument 1 to \"get\" has incompatible type \"list[int]\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testFunctoolsPartialHigherOrder]\nfrom functools import partial\nfrom typing import Callable\n\ndef fn(a: int, b: str, c: bytes) -> int: ...\n\ndef callback1(fn: Callable[[str, bytes], int]) -> None: ...\ndef callback2(fn: Callable[[str, int], int]) -> None: ...\n\ncallback1(partial(fn, 1))\n# TODO: false negative\n# https://github.com/python/mypy/issues/17461\ncallback2(partial(fn, 1))\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialClassObjectMatchingPartial]\nfrom functools import partial\n\nclass A:\n    def __init__(self, var: int, b: int, c: int) -> None: ...\n\np = partial(A, 1)\nreveal_type(p)  # N: Revealed type is \"functools.partial[__main__.A]\"\np(1, \"no\")  # E: Argument 2 to \"A\" has incompatible type \"str\"; expected \"int\"\n\nq: partial[A] = partial(A, 1)  # OK\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialTypeVarBound]\nfrom typing import Callable, TypeVar, Type\nimport functools\n\nT = TypeVar(\"T\", bound=Callable[[str, int], str])\nS = TypeVar(\"S\", bound=Type[int])\n\ndef foo(f: T) -> T:\n    g = functools.partial(f, \"foo\")\n    return f\n\ndef bar(f: S) -> S:\n    g = functools.partial(f, \"foo\")\n    return f\n[builtins fixtures/primitives.pyi]\n\n[case testFunctoolsPartialAbstractType]\nfrom abc import ABC, abstractmethod\nfrom functools import partial\n\nclass A(ABC):\n    def __init__(self) -> None: ...\n    @abstractmethod\n    def method(self) -> None: ...\n\ndef f1(cls: type[A]) -> None:\n    cls()\n    partial_cls = partial(cls)\n    partial_cls()\n\ndef f2() -> None:\n    A()  # E: Cannot instantiate abstract class \"A\" with abstract attribute \"method\"\n    partial_cls = partial(A)  # E: Cannot instantiate abstract class \"A\" with abstract attribute \"method\"\n    partial_cls()  # E: Cannot instantiate abstract class \"A\" with abstract attribute \"method\"\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialSelfType]\nfrom functools import partial\nfrom typing_extensions import Self\n\nclass A:\n    def __init__(self, ts: float, msg: str) -> None: ...\n\n    @classmethod\n    def from_msg(cls, msg: str) -> Self:\n        factory = partial(cls, ts=0)\n        return factory(msg=msg)\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialTypeVarValues]\nfrom functools import partial\nfrom typing import TypeVar\n\nT = TypeVar(\"T\", int, str)\n\ndef f(x: int, y: T) -> T:\n    return y\n\ndef g(x: T, y: int) -> T:\n    return x\n\ndef h(x: T, y: T) -> T:\n    return x\n\nfp = partial(f, 1)\nreveal_type(fp(1))  # N: Revealed type is \"builtins.int\"\nreveal_type(fp(\"a\"))  # N: Revealed type is \"builtins.str\"\nfp(object())  # E: Value of type variable \"T\" of \"f\" cannot be \"object\"\n\ngp = partial(g, 1)\nreveal_type(gp(1))  # N: Revealed type is \"builtins.int\"\ngp(\"a\")  # E: Argument 1 to \"g\" has incompatible type \"str\"; expected \"int\"\n\nhp = partial(h, 1)\nreveal_type(hp(1))  # N: Revealed type is \"builtins.int\"\nhp(\"a\")  # E: Argument 1 to \"h\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialOverloadedCallableProtocol]\nfrom functools import partial\nfrom typing import Callable, Protocol, overload\n\nclass P(Protocol):\n    @overload\n    def __call__(self, x: int) -> int: ...\n    @overload\n    def __call__(self, x: str) -> str: ...\n\ndef f(x: P):\n    reveal_type(partial(x, 1)())  # N: Revealed type is \"builtins.int\"\n\n    # TODO: but this is incorrect, predating the functools.partial plugin\n    reveal_type(partial(x, \"a\")())  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testFunctoolsPartialTypeVarErasure]\nfrom typing import Callable, TypeVar, Union\nfrom typing_extensions import ParamSpec, TypeVarTuple, Unpack\nfrom functools import partial\n\ndef use_int_callable(x: Callable[[int], int]) -> None:\n    pass\ndef use_func_callable(\n    x: Callable[\n        [Callable[[int], None]],\n        Callable[[int], None],\n    ],\n) -> None:\n    pass\n\nTc = TypeVar(\"Tc\", int, str)\nTb = TypeVar(\"Tb\", bound=Union[int, str])\nP = ParamSpec(\"P\")\nTs = TypeVarTuple(\"Ts\")\n\ndef func_b(a: Tb, b: str) -> Tb:\n    return a\ndef func_c(a: Tc, b: str) -> Tc:\n    return a\n\ndef func_fn(fn: Callable[P, Tc], b: str) -> Callable[P, Tc]:\n    return fn\ndef func_fn_unpack(fn: Callable[[Unpack[Ts]], Tc], b: str) -> Callable[[Unpack[Ts]], Tc]:\n    return fn\n\n# We should not leak stray typevars that aren't in scope:\nreveal_type(partial(func_b, b=\"\"))  # N: Revealed type is \"functools.partial[Any]\"\nreveal_type(partial(func_c, b=\"\"))  # N: Revealed type is \"functools.partial[Any]\"\nreveal_type(partial(func_fn, b=\"\"))  # N: Revealed type is \"functools.partial[def (*Any, **Any) -> Any]\"\nreveal_type(partial(func_fn_unpack, b=\"\"))  # N: Revealed type is \"functools.partial[def (*Any) -> Any]\"\n\nuse_int_callable(partial(func_b, b=\"\"))\nuse_func_callable(partial(func_b, b=\"\"))\nuse_int_callable(partial(func_c, b=\"\"))\nuse_func_callable(partial(func_c, b=\"\"))\nuse_int_callable(partial(func_fn, b=\"\"))  # E: Argument 1 to \"use_int_callable\" has incompatible type \"partial[def (*Any, **Any) -> Any]\"; expected \"Callable[[int], int]\" \\\n                                          # N: \"partial[def (*Any, **Any) -> Any].__call__\" has type \"def __call__(__self, *args: Any, **kwargs: Any) -> def (*Any, **Any) -> Any\"\nuse_func_callable(partial(func_fn, b=\"\"))\nuse_int_callable(partial(func_fn_unpack, b=\"\"))  # E: Argument 1 to \"use_int_callable\" has incompatible type \"partial[def (*Any) -> Any]\"; expected \"Callable[[int], int]\" \\\n                                                 # N: \"partial[def (*Any) -> Any].__call__\" has type \"def __call__(__self, *args: Any, **kwargs: Any) -> def (*Any) -> Any\"\nuse_func_callable(partial(func_fn_unpack, b=\"\"))\n\n# But we should not erase typevars that aren't bound by function\n# passed to `partial`:\n\ndef outer_b(arg: Tb) -> None:\n\n    def inner(a: Tb, b: str) -> Tb:\n        return a\n\n    reveal_type(partial(inner, b=\"\"))  # N: Revealed type is \"functools.partial[Tb`-1]\"\n    use_int_callable(partial(inner, b=\"\"))  # E: Argument 1 to \"use_int_callable\" has incompatible type \"partial[Tb]\"; expected \"Callable[[int], int]\" \\\n                                            # N: \"partial[Tb].__call__\" has type \"def __call__(__self, *args: Any, **kwargs: Any) -> Tb\"\n\ndef outer_c(arg: Tc) -> None:\n\n    def inner(a: Tc, b: str) -> Tc:\n        return a\n\n    reveal_type(partial(inner, b=\"\"))  # N: Revealed type is \"functools.partial[builtins.int]\" \\\n                                       # N: Revealed type is \"functools.partial[builtins.str]\"\n    use_int_callable(partial(inner, b=\"\"))  # E: Argument 1 to \"use_int_callable\" has incompatible type \"partial[str]\"; expected \"Callable[[int], int]\" \\\n                                            # N: \"partial[str].__call__\" has type \"def __call__(__self, *args: Any, **kwargs: Any) -> str\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-generic-alias.test",
    "content": "-- Test cases for generic aliases\n\n[case testGenericBuiltinFutureAnnotations]\nfrom __future__ import annotations\nt1: list\nt2: list[int]\nt3: list[str]\n\nt4: tuple\nt5: tuple[int]\nt6: tuple[int, str]\nt7: tuple[int, ...]\n\nt8: dict = {}\nt9: dict[int, str]\n\nt10: type\nt11: type[int]\n[builtins fixtures/dict.pyi]\n\n\n[case testGenericCollectionsFutureAnnotations]\nfrom __future__ import annotations\nimport collections\n\nt01: collections.deque\nt02: collections.deque[int]\nt03: collections.defaultdict\nt04: collections.defaultdict[int, str]\nt05: collections.OrderedDict\nt06: collections.OrderedDict[int, str]\nt07: collections.Counter\nt08: collections.Counter[int]\nt09: collections.ChainMap\nt10: collections.ChainMap[int, str]\n[builtins fixtures/tuple.pyi]\n\n\n[case testGenericAliasBuiltinsReveal]\nt1: list\nt2: list[int]\nt3: list[str]\n\nt4: tuple\nt5: tuple[int]\nt6: tuple[int, str]\nt7: tuple[int, ...]\n\nt8: dict = {}\nt9: dict[int, str]\n\nt10: type\nt11: type[int]\n\nreveal_type(t1)  # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(t2)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(t3)  # N: Revealed type is \"builtins.list[builtins.str]\"\nreveal_type(t4)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n# TODO: ideally these would reveal builtins.tuple\nreveal_type(t5)  # N: Revealed type is \"tuple[builtins.int]\"\nreveal_type(t6)  # N: Revealed type is \"tuple[builtins.int, builtins.str]\"\n# TODO: this is incorrect, see #9522\nreveal_type(t7)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(t8)  # N: Revealed type is \"builtins.dict[Any, Any]\"\nreveal_type(t9)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\nreveal_type(t10)  # N: Revealed type is \"builtins.type\"\nreveal_type(t11)  # N: Revealed type is \"type[builtins.int]\"\n[builtins fixtures/dict.pyi]\n\n\n[case testGenericAliasBuiltinsSetReveal]\nt1: set\nt2: set[int]\nt3: set[str]\n\nreveal_type(t1)  # N: Revealed type is \"builtins.set[Any]\"\nreveal_type(t2)  # N: Revealed type is \"builtins.set[builtins.int]\"\nreveal_type(t3)  # N: Revealed type is \"builtins.set[builtins.str]\"\n[builtins fixtures/set.pyi]\n\n\n[case testGenericAliasCollectionsReveal]\nimport collections\n\nt1: collections.deque[int]\nt2: collections.defaultdict[int, str]\nt3: collections.OrderedDict[int, str]\nt4: collections.Counter[int]\nt5: collections.ChainMap[int, str]\n\nreveal_type(t1)  # N: Revealed type is \"collections.deque[builtins.int]\"\nreveal_type(t2)  # N: Revealed type is \"collections.defaultdict[builtins.int, builtins.str]\"\nreveal_type(t3)  # N: Revealed type is \"collections.OrderedDict[builtins.int, builtins.str]\"\nreveal_type(t4)  # N: Revealed type is \"collections.Counter[builtins.int]\"\nreveal_type(t5)  # N: Revealed type is \"collections.ChainMap[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testGenericAliasCollectionsABCReveal]\nimport collections.abc\n\nt01: collections.abc.Awaitable[int]\nt02: collections.abc.Coroutine[str, int, float]\nt03: collections.abc.AsyncIterable[int]\nt04: collections.abc.AsyncIterator[int]\nt05: collections.abc.AsyncGenerator[int, float]\nt06: collections.abc.Iterable[int]\nt07: collections.abc.Iterator[int]\nt08: collections.abc.Generator[int, float, str]\nt09: collections.abc.Reversible[int]\nt10: collections.abc.Container[int]\nt11: collections.abc.Collection[int]\nt12: collections.abc.Callable[[int], float]\nt13: collections.abc.Set[int]\nt14: collections.abc.MutableSet[int]\nt15: collections.abc.Mapping[int, str]\nt16: collections.abc.MutableMapping[int, str]\nt17: collections.abc.Sequence[int]\nt18: collections.abc.MutableSequence[int]\nt19: collections.abc.ByteString\nt20: collections.abc.MappingView[int, int]\nt21: collections.abc.KeysView[int]\nt22: collections.abc.ItemsView[int, str]\nt23: collections.abc.ValuesView[str]\n\n# TODO: these currently reveal the classes from typing, see #7907\n# reveal_type(t01)  # Nx Revealed type is \"collections.abc.Awaitable[builtins.int]\"\n# reveal_type(t02)  # Nx Revealed type is \"collections.abc.Coroutine[builtins.str, builtins.int, builtins.float]\"\n# reveal_type(t03)  # Nx Revealed type is \"collections.abc.AsyncIterable[builtins.int]\"\n# reveal_type(t04)  # Nx Revealed type is \"collections.abc.AsyncIterator[builtins.int]\"\n# reveal_type(t05)  # Nx Revealed type is \"collections.abc.AsyncGenerator[builtins.int, builtins.float]\"\n# reveal_type(t06)  # Nx Revealed type is \"collections.abc.Iterable[builtins.int]\"\n# reveal_type(t07)  # Nx Revealed type is \"collections.abc.Iterator[builtins.int]\"\n# reveal_type(t08)  # Nx Revealed type is \"collections.abc.Generator[builtins.int, builtins.float, builtins.str]\"\n# reveal_type(t09)  # Nx Revealed type is \"collections.abc.Reversible[builtins.int]\"\n# reveal_type(t10)  # Nx Revealed type is \"collections.abc.Container[builtins.int]\"\n# reveal_type(t11)  # Nx Revealed type is \"collections.abc.Collection[builtins.int]\"\n# reveal_type(t12)  # Nx Revealed type is \"collections.abc.Callable[[builtins.int], builtins.float]\"\n# reveal_type(t13)  # Nx Revealed type is \"collections.abc.Set[builtins.int]\"\n# reveal_type(t14)  # Nx Revealed type is \"collections.abc.MutableSet[builtins.int]\"\n# reveal_type(t15)  # Nx Revealed type is \"collections.abc.Mapping[builtins.int, builtins.str]\"\n# reveal_type(t16)  # Nx Revealed type is \"collections.abc.MutableMapping[builtins.int, builtins.str]\"\n# reveal_type(t17)  # Nx Revealed type is \"collections.abc.Sequence[builtins.int]\"\n# reveal_type(t18)  # Nx Revealed type is \"collections.abc.MutableSequence[builtins.int]\"\n# reveal_type(t19)  # Nx Revealed type is \"collections.abc.ByteString\"\n# reveal_type(t20)  # Nx Revealed type is \"collections.abc.MappingView[builtins.int, builtins.int]\"\n# reveal_type(t21)  # Nx Revealed type is \"collections.abc.KeysView[builtins.int]\"\n# reveal_type(t22)  # Nx Revealed type is \"collections.abc.ItemsView[builtins.int, builtins.str]\"\n# reveal_type(t23)  # Nx Revealed type is \"collections.abc.ValuesView[builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testGenericAliasIsinstanceUnreachable]\n# flags: --warn-unreachable --python-version 3.10\nfrom collections.abc import Iterable\n\nclass A: ...\n\ndef test(dependencies: list[A] | None) -> None:\n    if dependencies is None:\n        dependencies = []\n    elif not isinstance(dependencies, Iterable):\n        dependencies = [dependencies]  # E: Statement is unreachable\n\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testGenericAliasRedundantExprCompoundIfExpr]\n# flags: --warn-unreachable --enable-error-code=redundant-expr --python-version 3.10\n\nfrom typing import Any, reveal_type\nfrom collections.abc import Iterable\n\ndef test_example(x: Iterable[Any]) -> None:\n    if isinstance(x, Iterable) and not isinstance(x, str):  # E: Left operand of \"and\" is always true\n        reveal_type(x)  # N: Revealed type is \"typing.Iterable[Any]\"\n\ndef test_counterexample(x: Any) -> None:\n    if isinstance(x, Iterable) and not isinstance(x, str):\n        reveal_type(x)  # N: Revealed type is \"typing.Iterable[Any]\"\n\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-full.pyi]\n\n\n[case testGenericBuiltinTupleTyping]\nfrom typing import Tuple\n\nt01: Tuple = ()\nt02: Tuple[int] = (1, )\nt03: Tuple[int, str] = (1, 'a')\nt04: Tuple[int, int] = (1, 2)\nt05: Tuple[int, int, int] = (1, 2, 3)\nt06: Tuple[int, ...]\nt07: Tuple[int, ...] = (1,)\nt08: Tuple[int, ...] = (1, 2)\nt09: Tuple[int, ...] = (1, 2, 3)\n[builtins fixtures/tuple.pyi]\n\n\n[case testGenericBuiltinTuple]\nt01: tuple = ()\nt02: tuple[int] = (1, )\nt03: tuple[int, str] = (1, 'a')\nt04: tuple[int, int] = (1, 2)\nt05: tuple[int, int, int] = (1, 2, 3)\nt06: tuple[int, ...]\nt07: tuple[int, ...] = (1,)\nt08: tuple[int, ...] = (1, 2)\nt09: tuple[int, ...] = (1, 2, 3)\n\nfrom typing import Tuple\nt10: Tuple[int, ...] = t09\n[builtins fixtures/tuple.pyi]\n\n[case testTypeAliasWithBuiltinTuple]\nA = tuple[int, ...]\na: A = ()\nb: A = (1, 2, 3)\nc: A = ('x', 'y')  # E: Incompatible types in assignment (expression has type \"tuple[str, str]\", variable has type \"tuple[int, ...]\")\n\nB = tuple[int, str]\nx: B = (1, 'x')\ny: B = ('x', 1)  # E: Incompatible types in assignment (expression has type \"tuple[str, int]\", variable has type \"tuple[int, str]\")\n\nreveal_type(tuple[int, ...]())  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeAliasWithBuiltinTupleInStub]\nimport m\nreveal_type(m.a)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nreveal_type(m.b)  # N: Revealed type is \"tuple[builtins.int, builtins.str]\"\n\n[file m.pyi]\nA = tuple[int, ...]\na: A\nB = tuple[int, str]\nb: B\n[builtins fixtures/tuple.pyi]\n\n[case testTypeAliasWithBuiltinListInStub]\nimport m\nreveal_type(m.a)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(m.b)  # N: Revealed type is \"builtins.list[builtins.list[builtins.int]]\"\nm.C  # has complex representation, ignored\nreveal_type(m.d)  # N: Revealed type is \"type[builtins.str]\"\n\n[file m.pyi]\nA = list[int]\na: A\nB = list[list[int]]\nb: B\nclass C(list[int]):\n    pass\nd: type[str]\n[builtins fixtures/list.pyi]\n\n\n[case testTypeAliasWithBuiltinListAliasInStub]\nimport m\nreveal_type(m.a()[0])  # N: Revealed type is \"builtins.int\"\n\n[file m.pyi]\nList = list\na = List[int]\n[builtins fixtures/list.pyi]\n"
  },
  {
    "path": "test-data/unit/check-generic-subtyping.test",
    "content": "-- Test cases for the type checker related to subtyping and inheritance with\n-- generics.\n\n\n-- Subtyping + inheritance\n-- -----------------------\n\n\n[case testSubtypingAndInheritingNonGenericTypeFromGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nac: A[C]\nad: A[D]\nb: B\n\nif int():\n    b = ad # E: Incompatible types in assignment (expression has type \"A[D]\", variable has type \"B\")\n    ad = b # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A[D]\")\nif int():\n    b = ac # E: Incompatible types in assignment (expression has type \"A[C]\", variable has type \"B\")\n\nif int():\n    b = b\n    ac = b\n\nclass C: pass\nclass A(Generic[T]): pass\nclass B(A[C]): pass\nclass D: pass\n\n[case testSubtypingAndInheritingGenericTypeFromNonGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\na: A\nbc: B[C]\nbd: B[D]\n\nif int():\n    bc = bd # E: Incompatible types in assignment (expression has type \"B[D]\", variable has type \"B[C]\")\n    bd = bc # E: Incompatible types in assignment (expression has type \"B[C]\", variable has type \"B[D]\")\nif int():\n    bc = a  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B[C]\")\n    bd = a  # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B[D]\")\n\nif int():\n    a = bc\nif int():\n    a = bd\n\nclass A: pass\nclass B(A, Generic[T]): pass\nclass C: pass\nclass D: pass\n\n[case testSubtypingAndInheritingGenericTypeFromGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nac: A[C]\nad: A[D]\nbcc: B[C, C]\nbdc: B[D, C]\n\nif int():\n    ad = bcc # E: Incompatible types in assignment (expression has type \"B[C, C]\", variable has type \"A[D]\")\nif int():\n    ad = bdc # E: Incompatible types in assignment (expression has type \"B[D, C]\", variable has type \"A[D]\")\n    bcc = ac # E: Incompatible types in assignment (expression has type \"A[C]\", variable has type \"B[C, C]\")\n    bdc = ac # E: Incompatible types in assignment (expression has type \"A[C]\", variable has type \"B[D, C]\")\n\nif int():\n    bcc = bcc\n    bdc = bdc\n    ac = bcc\nif int():\n    ac = bdc\n\nclass A(Generic[T]): pass\nclass B(A[S], Generic[T, S]): pass\nclass C: pass\nclass D: pass\n\n[case testSubtypingAndInheritingGenericTypeFromGenericTypeAcrossHierarchy]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nX = TypeVar('X')\nY = TypeVar('Y')\nae: A[A[E]]\naf: A[A[F]]\n\ncef: C[E, F]\ncff: C[F, F]\ncfe: C[F, E]\n\nif int():\n    ae = cef # E: Incompatible types in assignment (expression has type \"C[E, F]\", variable has type \"A[A[E]]\")\n    af = cfe # E: Incompatible types in assignment (expression has type \"C[F, E]\", variable has type \"A[A[F]]\")\n\nif int():\n    ae = cfe\n    af = cef\nif int():\n    af = cff\n\nclass A(Generic[T]): pass\nclass B(A[S], Generic[T, S]): pass\nclass C(B[A[X], A[Y]], Generic[X, Y]): pass\nclass E: pass\nclass F: pass\n\n[case testIncludingBaseClassTwice]\nfrom typing import TypeVar, Generic\nt = TypeVar('t')\nclass I(Generic[t]): pass\nclass A(I[C], I[object]): pass # E: Duplicate base class \"I\"\nclass C: pass\n\n\n-- Accessing inherited generic members\n-- -----------------------------------\n\n\n[case testAccessingMethodInheritedFromGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nb: B[C, D]\nc: C\nd: D\n\nb.f(c) # E: Argument 1 to \"f\" of \"A\" has incompatible type \"C\"; expected \"D\"\nb.f(d)\n\nclass A(Generic[T]):\n    def f(self, a: T) -> None:\n        pass\nclass B(A[S], Generic[T, S]): pass\nclass C: pass\nclass D: pass\n[builtins fixtures/tuple.pyi]\n\n[case testAccessingMethodInheritedFromGenericTypeInNonGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nb: B\nc: C\nd: D\n\nb.f(c) # E: Argument 1 to \"f\" of \"A\" has incompatible type \"C\"; expected \"D\"\nb.f(d)\n\nclass C: pass\nclass D: pass\nclass A(Generic[T]):\n    def f(self, a: T) -> None:\n        pass\nclass B(A[D]): pass\n[builtins fixtures/tuple.pyi]\n\n[case testAccessingMemberVarInheritedFromGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass A(Generic[T]):\n    def __init__(self, a: T) -> None:\n        self.a = a\n\nb: B[C, D]\nc: C\nd: D\n\nb.a = c # E: Incompatible types in assignment (expression has type \"C\", variable has type \"D\")\nb.a = d\n\nclass B(A[S], Generic[T, S]): pass\nclass C: pass\nclass D: pass\n[builtins fixtures/tuple.pyi]\n\n\n-- Overriding with generic types\n-- -----------------------------\n\n\n[case testOverridingMethodInSimpleTypeInheritingGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass B(Generic[T]):\n    def f(self, a: T) -> None: pass\n    def g(self, a: T) -> None: pass\nclass C: pass\nclass D: pass\nclass A(B[C]):\n    def f(self, a: D) -> None: pass \\\n        # E: Argument 1 of \"f\" is incompatible with supertype \"B\"; supertype defines the argument type as \"C\" \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n    def g(self, a: C) -> None: pass\n[out]\n\n[case testOverridingMethodInGenericTypeInheritingSimpleType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C: pass\nclass B:\n    def f(self, a: C) -> None: pass\n    def g(self, a: C) -> None: pass\nclass A(B, Generic[T]):\n    def f(self, a: T) -> None: pass \\\n        # E: Argument 1 of \"f\" is incompatible with supertype \"B\"; supertype defines the argument type as \"C\" \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n    def g(self, a: 'C') -> None: pass\n[out]\n\n[case testOverridingMethodInGenericTypeInheritingGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass B(Generic[T]):\n    def f(self, a: T) -> None: pass\n    def g(self, a: T) -> None: pass\nclass A(B[S], Generic[T, S]):\n    def f(self, a: T) -> None: pass \\\n        # E: Argument 1 of \"f\" is incompatible with supertype \"B\"; supertype defines the argument type as \"S\" \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n    def g(self, a: S) -> None: pass\n[out]\n\n[case testOverridingMethodInMultilevelHierarchyOfGenericTypes]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nU = TypeVar('U')\nV = TypeVar('V')\n\nclass D: pass\nclass C(Generic[T, U, V]):\n    def f(self, a: V) -> None: pass\n    def g(self, a: V) -> None: pass\nclass B(C[D, D, T], Generic[T]): pass\nclass A(B[S], Generic[T, S]):\n    def f(self, a: T) -> None: pass \\\n        # E: Argument 1 of \"f\" is incompatible with supertype \"C\"; supertype defines the argument type as \"S\" \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n    def g(self, a: S) -> None: pass\n[out]\n\n[case testOverrideGenericMethodInNonGenericClass]\nfrom typing import TypeVar\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass A:\n    def f(self, x: T, y: S) -> None: pass\nclass B(A):\n    def f(self, x: S, y: T) -> None: pass\nclass C(A):\n    # Okay, because T = object allows any type for the arguments.\n    def f(self, x: T, y: T) -> None: pass\n\n[case testOverrideGenericMethodInNonGenericClassLists]\nfrom typing import TypeVar, List\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass A:\n    def f(self, x: List[T], y: List[S]) -> None: pass\nclass B(A):\n    def f(self, x: List[S], y: List[T]) -> None: pass\nclass C(A):\n    def f(self, x: List[T], y: List[T]) -> None: pass  # Fail\n[builtins fixtures/list.pyi]\n[out]\nmain:11: error: Signature of \"f\" incompatible with supertype \"A\"\nmain:11: note:      Superclass:\nmain:11: note:          def [T, S] f(self, x: list[T], y: list[S]) -> None\nmain:11: note:      Subclass:\nmain:11: note:          def [T] f(self, x: list[T], y: list[T]) -> None\n\n[case testOverrideGenericMethodInNonGenericClassGeneralize]\nfrom typing import TypeVar\n\nT = TypeVar('T')\nT1 = TypeVar('T1', bound=str)\nS = TypeVar('S')\n\nclass A:\n    def f(self, x: int, y: S) -> None: pass\nclass B(A):\n    def f(self, x: T, y: S) -> None: pass\nclass C(A):\n    def f(self, x: T, y: str) -> None: pass\nclass D(A):\n    def f(self, x: T1, y: S) -> None: pass # TODO: This error could be more specific.\n[out]\nmain:12: error: Argument 2 of \"f\" is incompatible with supertype \"A\"; supertype defines the argument type as \"S\"\nmain:12: note: This violates the Liskov substitution principle\nmain:12: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\nmain:14: error: Signature of \"f\" incompatible with supertype \"A\"\nmain:14: note:      Superclass:\nmain:14: note:          def [S] f(self, x: int, y: S) -> None\nmain:14: note:      Subclass:\nmain:14: note:          def [T1: str, S] f(self, x: T1, y: S) -> None\n\n-- Inheritance from generic types with implicit dynamic supertype\n-- --------------------------------------------------------------\n\n\n[case testInheritanceFromGenericWithImplicitDynamicAndSubtyping]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\na: A\nbc: B[C]\nbd: B[D]\n\nif int():\n    a = bc # E: Incompatible types in assignment (expression has type \"B[C]\", variable has type \"A\")\n    bc = a\n    bd = a\n\nclass B(Generic[T]): pass\nclass A(B): pass\nclass C: pass\nclass D: pass\n[out]\n\n[case testInheritanceFromGenericWithImplicitDynamicAndExternalAccess]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\n\nclass B(Generic[T]):\n    def f(self, a: 'B[T]') -> None: pass\n    def __init__(self, x: 'B[T]') -> None:\n        self.x = x\nclass A(B): pass\nclass C: pass\n\na: A\nc: C\nbc: B[C]\n\na.x = c # E: Incompatible types in assignment (expression has type \"C\", variable has type \"B[Any]\")\na.f(c)  # E: Argument 1 to \"f\" of \"B\" has incompatible type \"C\"; expected \"B[Any]\"\na.x = bc\na.f(bc)\n[out]\n\n[case testInheritanceFromGenericWithImplicitDynamic]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\na: A\nc: C\nbc: B[C]\n\nclass B(Generic[T]):\n  def f(self, a: 'B[T]') -> None: pass\n  def __init__(self, x: 'B[T]') -> None:\n    self.x = x\n\nclass A(B):\n  def g(self) -> None:\n    self.x = c # E: Incompatible types in assignment (expression has type \"C\", variable has type \"B[Any]\")\n    self.f(c)  # E: Argument 1 to \"f\" of \"B\" has incompatible type \"C\"; expected \"B[Any]\"\n    self.x = bc\n    self.f(bc)\n\nclass C: pass\n[out]\n\n[case testInheritanceFromGenericWithImplicitDynamicAndOverriding]\nfrom typing import TypeVar, Generic, Tuple\nT = TypeVar('T')\nclass B(Generic[T]):\n    def f(self, a: T, b: 'Tuple[T, B[T]]') -> None:\n        pass\nclass A(B):\n    def f(self, a, b): pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n\n-- Inheritance from generic types and super expressions\n-- ----------------------------------------------------\n\n\n[case testSuperExpressionsWhenInheritingFromGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass B(Generic[T]):\n    def f(self, a: T) -> None: pass\nclass A(B[S], Generic[T, S]):\n    def g(self, t: T, s: S) -> None:\n        super().f(t)   # E: Argument 1 to \"f\" of \"B\" has incompatible type \"T\"; expected \"S\"\n        super().f(s)\n[out]\n\n[case testSuperExpressionsWhenInheritingFromGenericTypeAndDeepHierarchy]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nU = TypeVar('U')\nV = TypeVar('V')\nclass C(Generic[T, U, V]):\n    def f(self, a: V) -> None: pass\nclass D: pass\nclass B(C[D, D, T], Generic[T]): pass\nclass A(B[S], Generic[T, S]):\n    def g(self, t: T, s: S) -> None:\n        super().f(t)   # E: Argument 1 to \"f\" of \"C\" has incompatible type \"T\"; expected \"S\"\n        super().f(s)\n[out]\n\n\n-- Type of inherited constructor\n-- -----------------------------\n\n\n[case testInheritedConstructor]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    def __init__(self, x: T) -> None: pass\nclass B(A[T], Generic[T]): pass\nclass C(A[int]): pass\nclass D(A[A[T]], Generic[T]): pass\nB(1)\nC(1)\nC('a')  # E: Argument 1 to \"C\" has incompatible type \"str\"; expected \"int\"\nD(A(1))\nD(1)  # E: Argument 1 to \"D\" has incompatible type \"int\"; expected \"A[Never]\"\n\n\n[case testInheritedConstructor2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\nZ = TypeVar('Z')\nclass A(Generic[T, U]):\n    def __init__(self, x: T, y: U, z: Z) -> None: pass\nclass B(A[int, T], Generic[T]): pass\nclass C(B[A[T, str]], Generic[T, U]): pass\n# C[T, U] <: B[A[T, str]] <: A[int, A[T, str]]\nC(1, A(1, 'a', 0), 'z')\nC(1, A('1', 'a', 0), 'z')\nC('1', A(1, 'a', 0), 'z')  # E: Argument 1 to \"C\" has incompatible type \"str\"; expected \"int\"\nC(1, A(1, 1, 0), 'z')  # E: Argument 2 to \"A\" has incompatible type \"int\"; expected \"str\"\n\n\n-- Subtyping with a generic abstract base class\n-- --------------------------------------------\n\n\n[case testSubtypingWithGenericTypeSubclassingGenericAbstractClass]\nfrom typing import TypeVar, Generic\nfrom abc import abstractmethod\nT = TypeVar('T')\nS = TypeVar('S')\nacd: A[C, D]\nadc: A[D, C]\nic: I[C]\nid: I[D]\n\nif int():\n    ic = acd # E: Incompatible types in assignment (expression has type \"A[C, D]\", variable has type \"I[C]\")\n    id = adc # E: Incompatible types in assignment (expression has type \"A[D, C]\", variable has type \"I[D]\")\n    adc = ic # E: Incompatible types in assignment (expression has type \"I[C]\", variable has type \"A[D, C]\")\n\nif int():\n    ic = adc\n    id = acd\n\nclass I(Generic[T]):\n    @abstractmethod\n    def f(self): pass\nclass A(I[S], Generic[T, S]): pass\nclass C: pass\nclass D: pass\n\n[case testSubtypingWithTypeImplementingGenericABCViaInheritance]\nfrom typing import TypeVar, Generic\nS = TypeVar('S')\na: A\nb: B\nic: I[C]\nid: I[D]\nie: I[E]\n\nclass I(Generic[S]): pass\nclass B(I[C]): pass\nclass A(B): pass\n\nif int():\n    ie = a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"I[E]\")\n    a = ic # E: Incompatible types in assignment (expression has type \"I[C]\", variable has type \"A\")\nif int():\n    a = id # E: Incompatible types in assignment (expression has type \"I[D]\", variable has type \"A\")\nif int():\n    a = b  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    id = a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"I[D]\")\n\n    ic = a\n    b = a\n\nclass C: pass\nclass D: pass\nclass E: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testSubtypingWithTypeImplementingGenericABCViaInheritance2-skip]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass I(Generic[T]): pass\nclass A(I[C]): pass\nclass B(A, I[D]): pass # Fail\n\nclass C: pass\nclass D: pass\n[out]\nmain:5: error: Class \"B\" has base \"I\" duplicated inconsistently\n\n[case testSubtypingAndABCExtension]\nfrom typing import TypeVar, Generic\nfrom abc import abstractmethod, ABCMeta\nt = TypeVar('t')\na: A[object]\ni: I[object]\nj: J[object]\n(ii, jj) = (i, j)\nif int():\n    ii = a\n    jj = a\nif int():\n    jj = i\n    a = i # E: Incompatible types in assignment (expression has type \"I[object]\", variable has type \"A[object]\")\nif int():\n    a = j # E: Incompatible types in assignment (expression has type \"J[object]\", variable has type \"A[object]\")\n\nclass J(Generic[t]): pass\nclass X(metaclass=ABCMeta): pass\nclass I(X, J[t], Generic[t]): pass\nclass A(I[t], Generic[t]): pass\n[builtins fixtures/tuple.pyi]\n\n\n-- Subclassing a generic ABC\n-- -------------------------\n\n\n[case testSubclassingGenericABC1]\nfrom typing import TypeVar, Generic\nfrom abc import abstractmethod\nT = TypeVar('T')\nclass I(Generic[T]):\n    @abstractmethod\n    def f(self, a: T) -> None: pass\n    @abstractmethod\n    def g(self, a: T) -> None: pass\nclass A(I[C]):\n    def f(self, a: 'D') -> None: pass \\\n        # E: Argument 1 of \"f\" is incompatible with supertype \"I\"; supertype defines the argument type as \"C\" \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n    def g(self, a: 'C') -> None: pass\nclass C: pass\nclass D: pass\n[out]\n\n\n-- Extending a generic ABC with deep type hierarchy\n-- ------------------------------------------------\n\n\n[case testSubclassingGenericABCWithDeepHierarchy]\nfrom typing import Any, TypeVar, Generic\nfrom abc import abstractmethod\nT = TypeVar('T')\na: A\nic: I[C]\nid: I[D]\n\nif int():\n    id = a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"I[D]\")\n    ic = a\n\nclass I(Generic[T]):\n    @abstractmethod\n    def f(self, a: T, b: T) -> None: pass\n    @abstractmethod\n    def g(self, a: T, b: 'D') -> None: pass\nclass B(I[C]):\n    def f(self, a: 'C', b: 'C') -> None: pass\n    def g(self, a: 'C', b: Any) -> None: pass\nclass A(B):\n    def g(self, a: 'C', b: 'C') -> None: pass \\\n        # E: Argument 2 of \"g\" is incompatible with supertype \"I\"; supertype defines the argument type as \"D\" \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\n    def f(self, a: 'C', b: 'C') -> None: pass\nclass C: pass\nclass D: pass\n[builtins fixtures/tuple.pyi]\n\n[case testSubclassingGenericABCWithDeepHierarchy2]\nfrom typing import Any, TypeVar, Generic\nfrom abc import abstractmethod\nT = TypeVar('T')\nclass I(Generic[T]):\n    @abstractmethod\n    def f(self, a: T, b: T) -> None: pass\nclass B(I[C]):\n    def f(self, a: 'C', b: Any) -> None: pass\nclass A(B):\n    def f(self, a: 'C', b: 'D') -> None: pass \\\n        # E: Argument 2 of \"f\" is incompatible with supertype \"I\"; supertype defines the argument type as \"C\" \\\n        # N: This violates the Liskov substitution principle \\\n        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#incompatible-overrides\nclass C: pass\nclass D: pass\n[out]\n\n\n-- Implicit Any types and subclassing generic ABC\n-- ----------------------------------------------\n\n\n[case testSubclassingGenericABCWithImplicitAny]\nfrom typing import Any, TypeVar, Generic\nfrom abc import abstractmethod\nT = TypeVar('T')\na: Any\nic: I[C]\nid: I[D]\n\nic = a\nid = a\n\nclass I(Generic[T]):\n    @abstractmethod\n    def f(self, a: T) -> None: pass\nclass A(I):\n    def f(self, a): pass\n\nclass C: pass\nclass D: pass\n\n[case testSubclassingGenericABCWithImplicitAnyAndDeepHierarchy]\nfrom typing import Any, TypeVar, Generic\nfrom abc import abstractmethod\nT = TypeVar('T')\na: Any\nic: I[C]\nid: I[D]\n\nic = a\nid = a\n\nclass I(Generic[T]):\n    @abstractmethod\n    def f(self, a: T, b: T) -> None: pass\nclass B(I):\n    def f(self, a, b): pass\nclass A(B):\n    def f(self, a: 'C', b: 'D') -> None: pass\nclass C: pass\nclass D: pass\n\n[case testImplementingGenericABCWithImplicitAnyAndDeepHierarchy2]\nfrom typing import Any, TypeVar, Generic\nfrom abc import abstractmethod\nT = TypeVar('T')\na: Any\njc: J[C]\njd: J[D]\n\njc = a\njd = a\n\nclass J(Generic[T]):\n    @abstractmethod\n    def f(self, a: T, b: T) -> None: pass\nclass I(J):\n    @abstractmethod\n    def f(self, a, b): pass\nclass A(I):\n    def f(self, a: 'C', b: 'D') -> None: pass\n\nclass C: pass\nclass D: pass\n\n\n-- Accessing generic ABC members\n-- -----------------------------\n\n\n[case testAccessingGenericABCMembers]\nfrom typing import TypeVar, Generic\nfrom abc import abstractmethod\nT = TypeVar('T')\nclass I(Generic[T]):\n    @abstractmethod\n    def f(self, a: T) -> None: pass\nclass A: pass\nclass B: pass\n\na: A\nb: B\nia: I[A]\n\nia.f(b)  # E: Argument 1 to \"f\" of \"I\" has incompatible type \"B\"; expected \"A\"\nia.f(a)\n[builtins fixtures/tuple.pyi]\n\n[case testAccessingInheritedGenericABCMembers]\nfrom typing import TypeVar, Generic\nfrom abc import abstractmethod\nT = TypeVar('T')\nclass J(Generic[T]):\n    @abstractmethod\n    def f(self, a: T) -> None: pass\nclass I(J[T], Generic[T]): pass\nclass A: pass\nclass B: pass\na: A\nb: B\nia: I[A]\n\nia.f(b)  # E: Argument 1 to \"f\" of \"J\" has incompatible type \"B\"; expected \"A\"\nia.f(a)\n[builtins fixtures/tuple.pyi]\n\n\n-- Misc\n-- ----\n\n\n[case testMultipleAssignmentAndGenericSubtyping]\nfrom typing import Iterable\nn: int\ns: str\nclass Nums(Iterable[int]):\n    def __iter__(self): pass\n    def __next__(self): pass\nn, n = Nums()\ns, s = Nums() # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[builtins fixtures/for.pyi]\n[out]\n\n[case testUninhabitedCacheChecksAmbiguous]\n# https://github.com/python/mypy/issues/19641\nfrom typing import Mapping, Never, TypeVar\n\nM = TypeVar(\"M\", bound=Mapping[str,object])\n\ndef get(arg: M, /) -> M:\n    return arg\n\nget({})\n\ndef upcast(d: dict[Never, Never]) -> Mapping[str, object]:\n    return d  # E: Incompatible return value type (got \"dict[Never, Never]\", expected \"Mapping[str, object]\")\n[builtins fixtures/dict.pyi]\n\n-- Variance\n-- --------\n\n\n[case testCovariant]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', covariant=True)\n\nclass G(Generic[T]): pass\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\na: G[A]\nb: G[B]\nc: G[C]\n\nif int():\n    b = a  # E: Incompatible types in assignment (expression has type \"G[A]\", variable has type \"G[B]\")\n    b = c\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testContravariant]\nfrom typing import TypeVar, Generic\nT = TypeVar('T', contravariant=True)\n\nclass G(Generic[T]): pass\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\na: G[A]\nb: G[B]\nc: G[C]\n\nif int():\n    b = a\n    b = c  # E: Incompatible types in assignment (expression has type \"G[C]\", variable has type \"G[B]\")\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testInvariant]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')  # invariant (default)\n\nclass G(Generic[T]): pass\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\na: G[A]\nb: G[B]\nc: G[C]\n\nif int():\n    b = a  # E: Incompatible types in assignment (expression has type \"G[A]\", variable has type \"G[B]\")\n    b = c  # E: Incompatible types in assignment (expression has type \"G[C]\", variable has type \"G[B]\")\n[builtins fixtures/bool.pyi]\n[out]\n\n\n[case testTypeVarSubtypeUnion]\nfrom typing import Union, TypeVar, Generic\n\nclass U: pass\nclass W: pass\n\nT = TypeVar('T', bound=Union[U, W])\n\nclass Y(Generic[T]):\n    def __init__(self) -> None:\n        pass\n    def f(self) -> T:\n        return U()  # E: Incompatible return value type (got \"U\", expected \"T\")\n\n\n[case testTypeVarBoundToOldUnionAttributeAccess]\nfrom typing import Union, TypeVar\n\nclass U:\n    a: float\nclass V:\n    b: float\nclass W:\n    c: float\n\nT = TypeVar(\"T\", bound=Union[U, V, W])\n\ndef f(x: T) -> None:\n    x.a  # E\n    x.b = 1.0  # E\n    del x.c  # E\n\n[out]\nmain:13: error: Item \"V\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"a\"\nmain:13: error: Item \"W\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"a\"\nmain:14: error: Item \"U\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"b\"\nmain:14: error: Item \"W\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"b\"\nmain:15: error: Item \"U\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"c\"\nmain:15: error: Item \"V\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"c\"\n\n\n[case testTypeVarBoundToNewUnionAttributeAccess]\n# flags: --python-version 3.10\nfrom typing import TypeVar\n\nclass U:\n    a: int\nclass V:\n    b: int\nclass W:\n    c: int\n\nT = TypeVar(\"T\", bound=U | V | W)\n\ndef f(x: T) -> None:\n    x.a  # E\n    x.b = 1  # E\n    del x.c  # E\n\n[builtins fixtures/tuple.pyi]\n[out]\nmain:14: error: Item \"V\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"a\"\nmain:14: error: Item \"W\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"a\"\nmain:15: error: Item \"U\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"b\"\nmain:15: error: Item \"W\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"b\"\nmain:16: error: Item \"U\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"c\"\nmain:16: error: Item \"V\" of the upper bound \"U | V | W\" of type variable \"T\" has no attribute \"c\"\n\n\n[case testSubtypingIterableUnpacking1]\n# https://github.com/python/mypy/issues/11138\nfrom typing import Generic, Iterator, TypeVar\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\nclass X1(Iterator[U], Generic[T, U]):\n    pass\n\nx1: X1[str, int]\nreveal_type(list(x1))  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type([*x1])  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nclass X2(Iterator[T], Generic[T, U]):\n    pass\n\nx2: X2[str, int]\nreveal_type(list(x2))  # N: Revealed type is \"builtins.list[builtins.str]\"\nreveal_type([*x2])  # N: Revealed type is \"builtins.list[builtins.str]\"\n\nclass X3(Generic[T, U], Iterator[U]):\n    pass\n\nx3: X3[str, int]\nreveal_type(list(x3))  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type([*x3])  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nclass X4(Generic[T, U], Iterator[T]):\n    pass\n\nx4: X4[str, int]\nreveal_type(list(x4))  # N: Revealed type is \"builtins.list[builtins.str]\"\nreveal_type([*x4])  # N: Revealed type is \"builtins.list[builtins.str]\"\n\nclass X5(Iterator[T]):\n    pass\n\nx5: X5[str]\nreveal_type(list(x5))  # N: Revealed type is \"builtins.list[builtins.str]\"\nreveal_type([*x5])  # N: Revealed type is \"builtins.list[builtins.str]\"\n\nclass X6(Generic[T, U], Iterator[bool]):\n    pass\n\nx6: X6[str, int]\nreveal_type(list(x6))  # N: Revealed type is \"builtins.list[builtins.bool]\"\nreveal_type([*x6])  # N: Revealed type is \"builtins.list[builtins.bool]\"\n[builtins fixtures/list.pyi]\n\n[case testSubtypingIterableUnpacking2]\nfrom typing import Generic, Iterator, TypeVar, Mapping\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\nclass X1(Generic[T, U], Iterator[U], Mapping[U, T]):\n    pass\n\nx1: X1[str, int]\nreveal_type(list(x1))  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type([*x1])  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nclass X2(Generic[T, U], Iterator[U], Mapping[T, U]):\n    pass\n\nx2: X2[str, int]\nreveal_type(list(x2))  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type([*x2])  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testSubtypingMappingUnpacking1]\n# https://github.com/python/mypy/issues/11138\nfrom typing import Generic, TypeVar, Mapping\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\nclass X1(Generic[T, U],  Mapping[U, T]):\n    pass\n\nx1: X1[str, int]\nreveal_type(iter(x1))  # N: Revealed type is \"typing.Iterator[builtins.int]\"\nreveal_type({**x1})  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n\nclass X2(Generic[T, U],  Mapping[T, U]):\n    pass\n\nx2: X2[str, int]\nreveal_type(iter(x2))  # N: Revealed type is \"typing.Iterator[builtins.str]\"\nreveal_type({**x2})  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n\nclass X3(Generic[T, U],  Mapping[bool, float]):\n    pass\n\nx3: X3[str, int]\nreveal_type(iter(x3))  # N: Revealed type is \"typing.Iterator[builtins.bool]\"\nreveal_type({**x3})  # N: Revealed type is \"builtins.dict[builtins.bool, builtins.float]\"\n[builtins fixtures/dict.pyi]\n\n[case testSubtypingMappingUnpacking2]\nfrom typing import Generic, TypeVar, Mapping\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\nclass X1(Generic[T, U],  Mapping[U, T]):\n    pass\n\ndef func_with_kwargs(**kwargs: int):\n    pass\n\nx1: X1[str, int]\nreveal_type(iter(x1))\nreveal_type({**x1})\nfunc_with_kwargs(**x1)\n[out]\nmain:12: note: Revealed type is \"typing.Iterator[builtins.int]\"\nmain:13: note: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\nmain:14: error: Argument after ** must have string keys\nmain:14: error: Argument 1 to \"func_with_kwargs\" has incompatible type \"**X1[str, int]\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testSubtypingMappingUnpacking3]\nfrom typing import Generic, TypeVar, Mapping, Iterable\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\nclass X1(Generic[T, U],  Mapping[U, T], Iterable[U]):\n    pass\n\nx1: X1[str, int]\nreveal_type(iter(x1))  # N: Revealed type is \"typing.Iterator[builtins.int]\"\nreveal_type({**x1})  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n\n# Some people would expect this to raise an error, but this currently does not:\n# `Mapping` has `Iterable[U]` base class, `X2` has direct `Iterable[T]` base class.\n# It would be impossible to define correct `__iter__` method for incompatible `T` and `U`.\nclass X2(Generic[T, U],  Mapping[U, T], Iterable[T]):\n    pass\n\nx2: X2[str, int]\nreveal_type(iter(x2))  # N: Revealed type is \"typing.Iterator[builtins.int]\"\nreveal_type({**x2})  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n[builtins fixtures/dict.pyi]\n\n[case testNotDirectIterableAndMappingSubtyping]\nfrom typing import Generic, TypeVar, Dict, Iterable, Iterator, List\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\nclass X1(Generic[T, U], Dict[U, T], Iterable[U]):\n    def __iter__(self) -> Iterator[U]: pass\n\nx1: X1[str, int]\nreveal_type(iter(x1))  # N: Revealed type is \"typing.Iterator[builtins.int]\"\nreveal_type({**x1})  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n\nclass X2(Generic[T, U], List[U]):\n    def __iter__(self) -> Iterator[U]: pass\n\nx2: X2[str, int]\nreveal_type(iter(x2))  # N: Revealed type is \"typing.Iterator[builtins.int]\"\nreveal_type([*x2])  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/dict.pyi]\n\n[case testIncompatibleVariance]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nT_co = TypeVar('T_co', covariant=True)\nT_contra = TypeVar('T_contra', contravariant=True)\n\nclass A(Generic[T_co]): ...\nclass B(A[T_contra], Generic[T_contra]): ...  # E: Variance of TypeVar \"T_contra\" incompatible with variance in parent type\n\nclass C(Generic[T_contra]): ...\nclass D(C[T_co], Generic[T_co]): ...  # E: Variance of TypeVar \"T_co\" incompatible with variance in parent type\n\nclass E(Generic[T]): ...\nclass F(E[T_co], Generic[T_co]): ...  # E: Variance of TypeVar \"T_co\" incompatible with variance in parent type\n\nclass G(Generic[T]): ...\nclass H(G[T_contra], Generic[T_contra]): ...  # E: Variance of TypeVar \"T_contra\" incompatible with variance in parent type\n\n[case testParameterizedGenericOverrideWithProperty]\nfrom typing import TypeVar, Generic\n\nT = TypeVar(\"T\")\n\nclass A(Generic[T]):\n    def __init__(self, val: T):\n        self.member: T = val\n\nclass B(A[str]):\n    member: str\n\nclass GoodPropertyOverride(A[str]):\n    @property\n    def member(self) -> str: ...\n    @member.setter\n    def member(self, val: str): ...\n\nclass BadPropertyOverride(A[str]):\n    @property  # E: Signature of \"member\" incompatible with supertype \"A\" \\\n               # N:      Superclass: \\\n               # N:          str \\\n               # N:      Subclass: \\\n               # N:          int\n    def member(self) -> int: ...\n    @member.setter\n    def member(self, val: int): ...\n\nclass BadGenericPropertyOverride(A[str], Generic[T]):\n    @property  # E: Signature of \"member\" incompatible with supertype \"A\" \\\n               # N:      Superclass: \\\n               # N:          str \\\n               # N:      Subclass: \\\n               # N:          T\n    def member(self) -> T: ...\n    @member.setter\n    def member(self, val: T): ...\n[builtins fixtures/property.pyi]\n\n[case testParameterizedGenericPropertyOverrideWithProperty]\nfrom typing import TypeVar, Generic\n\nT = TypeVar(\"T\")\n\nclass A(Generic[T]):\n    @property\n    def member(self) -> T: ...\n    @member.setter\n    def member(self, val: T): ...\n\nclass B(A[str]):\n    member: str\n\nclass GoodPropertyOverride(A[str]):\n    @property\n    def member(self) -> str: ...\n    @member.setter\n    def member(self, val: str): ...\n\nclass BadPropertyOverride(A[str]):\n    @property  # E: Signature of \"member\" incompatible with supertype \"A\" \\\n               # N:      Superclass: \\\n               # N:          str \\\n               # N:      Subclass: \\\n               # N:          int\n    def member(self) -> int: ...\n    @member.setter\n    def member(self, val: int): ...\n\nclass BadGenericPropertyOverride(A[str], Generic[T]):\n    @property  # E: Signature of \"member\" incompatible with supertype \"A\" \\\n               # N:      Superclass: \\\n               # N:          str \\\n               # N:      Subclass: \\\n               # N:          T\n    def member(self) -> T: ...\n    @member.setter\n    def member(self, val: T): ...\n[builtins fixtures/property.pyi]\n\n[case testParameterizedGenericOverrideSelfWithProperty]\nfrom typing_extensions import Self\n\nclass A:\n    def __init__(self, val: Self):\n        self.member: Self = val\n\nclass GoodPropertyOverride(A):\n    @property\n    def member(self) -> \"GoodPropertyOverride\": ...\n    @member.setter\n    def member(self, val: \"GoodPropertyOverride\"): ...\n\nclass GoodPropertyOverrideSelf(A):\n    @property\n    def member(self) -> Self: ...\n    @member.setter\n    def member(self, val: Self): ...\n[builtins fixtures/property.pyi]\n\n[case testParameterizedGenericOverrideWithSelfProperty]\nfrom typing import TypeVar, Generic\nfrom typing_extensions import Self\n\nT = TypeVar(\"T\")\n\nclass A(Generic[T]):\n    def __init__(self, val: T):\n        self.member: T = val\n\nclass B(A[\"B\"]):\n    member: Self\n\nclass GoodPropertyOverride(A[\"GoodPropertyOverride\"]):\n    @property\n    def member(self) -> Self: ...\n    @member.setter\n    def member(self, val: Self): ...\n[builtins fixtures/property.pyi]\n\n[case testMultipleInheritanceCompatibleTypeVar]\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\nclass A(Generic[T]):\n    x: T\n    def fn(self, t: T) -> None: ...\n\nclass A2(A[T]):\n    y: str\n    z: str\n\nclass B(Generic[T]):\n    x: T\n    def fn(self, t: T) -> None: ...\n\nclass C1(A2[str], B[str]): pass\nclass C2(A2[str], B[int]): pass  # E: Definition of \"fn\" in base class \"A\" is incompatible with definition in base class \"B\" \\\n                                 # E: Definition of \"x\" in base class \"A\" is incompatible with definition in base class \"B\"\nclass C3(A2[T], B[T]): pass\nclass C4(A2[U], B[U]): pass\nclass C5(A2[U], B[T]): pass  # E: Definition of \"fn\" in base class \"A\" is incompatible with definition in base class \"B\" \\\n                             # E: Definition of \"x\" in base class \"A\" is incompatible with definition in base class \"B\"\n\nclass D1(A[str], B[str]): pass\nclass D2(A[str], B[int]): pass  # E: Definition of \"fn\" in base class \"A\" is incompatible with definition in base class \"B\" \\\n                                # E: Definition of \"x\" in base class \"A\" is incompatible with definition in base class \"B\"\nclass D3(A[T], B[T]): pass\nclass D4(A[U], B[U]): pass\nclass D5(A[U], B[T]): pass  # E: Definition of \"fn\" in base class \"A\" is incompatible with definition in base class \"B\" \\\n                            # E: Definition of \"x\" in base class \"A\" is incompatible with definition in base class \"B\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-generics.test",
    "content": "-- Simple generic types\n-- --------------------\n\n\n[case testGenericMethodReturnType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\na: A[B]\nb: B\nc: C\nif int():\n    c = a.f() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"C\")\n    b = a.f()\n\nclass A(Generic[T]):\n    def f(self) -> T: pass\n\nclass B: pass\nclass C: pass\n[builtins fixtures/tuple.pyi]\n\n[case testGenericMethodArgument]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    def f(self, a: T) -> None: pass\n\na: A[B]\nb: B\nc: C\n\na.f(c) # E: Argument 1 to \"f\" of \"A\" has incompatible type \"C\"; expected \"B\"\na.f(b)\n\nclass B: pass\nclass C: pass\n[case testGenericMemberVariable]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    def __init__(self, v: T) -> None:\n        self.v = v\n\na: A[B]\nb: B\nc: C\na.v = c # Fail\na.v = b\n\nclass B: pass\nclass C: pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:10: error: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\n\n[case testGenericMemberVariable2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\na: A[B]\nb: B\nc: C\na.v = c # Fail\na.v = b\n\nclass A(Generic[T]):\n    v: T\nclass B: pass\nclass C: pass\n[builtins fixtures/tuple.pyi]\n[out]\nmain:6: error: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\n\n[case testSimpleGenericSubtyping]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nb: A[B]\nbb: A[B]\nc: A[C]\nif int():\n    c = b # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[C]\")\n    b = c # E: Incompatible types in assignment (expression has type \"A[C]\", variable has type \"A[B]\")\n\nif int():\n    b = b\nif int():\n    b = bb\n\nclass A(Generic[T]): pass\nclass B: pass\nclass C(B): pass\n[builtins fixtures/tuple.pyi]\n\n[case testGenericTypeCompatibilityWithAny]\nfrom typing import Any, TypeVar, Generic\nT = TypeVar('T')\nb: A[B]\nc: A[C]\nd: A[Any]\n\nb = d\nc = d\nd = b\nd = c\n\nclass A(Generic[T]): pass\nclass B: pass\nclass C(B): pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testTypeVariableAsTypeArgument]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\na: A[B]\nb: A[B]\nc: A[C]\n\na.v = c # E: Incompatible types in assignment (expression has type \"A[C]\", variable has type \"A[B]\")\nif int():\n    c = a.v # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[C]\")\na.v = b\nif int():\n    b = a.v\n\nclass A(Generic[T]):\n    v: A[T]\n\nclass B: pass\nclass C: pass\n\n[case testMultipleGenericTypeParametersWithMemberVars]\nfrom typing import TypeVar, Generic\nS = TypeVar('S')\nT = TypeVar('T')\na: A[B, C]\ns: B\nt: C\n\nif int():\n    t = a.s # E: Incompatible types in assignment (expression has type \"B\", variable has type \"C\")\n    s = a.t # E: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\n\nif int():\n    s = a.s\n    t = a.t\n\nclass A(Generic[S, T]):\n    s: S\n    t: T\nclass B: pass\nclass C: pass\n\n[case testMultipleGenericTypeParametersWithMethods]\nfrom typing import TypeVar, Generic\nS = TypeVar('S')\nT = TypeVar('T')\na: A[B, C]\ns: B\nt: C\n\na.f(s, s) # Fail\na.f(t, t) # Fail\na.f(s, t)\n\nclass A(Generic[S, T]):\n    def f(self, s: S, t: T) -> None: pass\nclass B: pass\nclass C: pass\n[out]\nmain:8: error: Argument 2 to \"f\" of \"A\" has incompatible type \"B\"; expected \"C\"\nmain:9: error: Argument 1 to \"f\" of \"A\" has incompatible type \"C\"; expected \"B\"\n\n[case testMultipleGenericTypeParametersAndSubtyping]\nfrom typing import TypeVar, Generic\nS = TypeVar('S')\nT = TypeVar('T')\nbc: A[B, C]\nbb: A[B, B]\ncb: A[C, B]\n\nif int():\n    bb = bc # E: Incompatible types in assignment (expression has type \"A[B, C]\", variable has type \"A[B, B]\")\nif int():\n    bb = cb # E: Incompatible types in assignment (expression has type \"A[C, B]\", variable has type \"A[B, B]\")\n    bc = bb # E: Incompatible types in assignment (expression has type \"A[B, B]\", variable has type \"A[B, C]\")\n\nif int():\n    bb = bb\n    bc = bc\n\nclass A(Generic[S, T]):\n    s: S\n    t: T\n\nclass B: pass\nclass C(B):pass\n\n\n-- Simple generic type bodies\n-- --------------------------\n\n\n[case testGenericTypeBody1]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    a: T\n\n    def f(self, b: T) -> T:\n        self.f(x)     # Fail\n        d = self # type: A[B] # Fail\n        self.a = self.f(self.a)\n        return self.a\n        c = self # type: A[T]\nx: B\nclass B: pass\n[out]\nmain:7: error: Argument 1 to \"f\" of \"A\" has incompatible type \"B\"; expected \"T\"\nmain:8: error: Incompatible types in assignment (expression has type \"A[T]\", variable has type \"A[B]\")\n\n[case testGenericTypeBodyWithMultipleVariables]\nfrom typing import TypeVar, Generic\nS = TypeVar('S')\nT = TypeVar('T')\nclass A(Generic[S, T]):\n    def f(self) -> None:\n        s: S\n        t: T\n        if int():\n            s = t # E: Incompatible types in assignment (expression has type \"T\", variable has type \"S\")\n            t = s # E: Incompatible types in assignment (expression has type \"S\", variable has type \"T\")\n        a = self # type: A[S, B] # E: Incompatible types in assignment (expression has type \"A[S, T]\", variable has type \"A[S, B]\")\n        b = self # type: A[T, T] # E: Incompatible types in assignment (expression has type \"A[S, T]\", variable has type \"A[T, T]\")\n        c = self # type: A[S, T]\n        if int():\n            t = t\n\nclass B: pass\n[out]\n\n[case testCompatibilityOfNoneWithTypeVar]\n# flags: --no-strict-optional\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    def f(self) -> None:\n        a = None # type: T\n        a = None\n[out]\n\n[case testCompatibilityOfTypeVarWithObject]\n# flags: --no-strict-optional\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    def f(self) -> T:\n        a = object() # type: T  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"T\")\n        if int():\n            a = object()    # E: Incompatible types in assignment (expression has type \"object\", variable has type \"T\")\n        b = self.f() # type: object\n        if int():\n            b = self.f()\n        return None\n[out]\n\n\n-- Operations with generic types\n-- -----------------------------\n\n\n[case testGenericOperations]\nfrom typing import TypeVar, Generic\nS = TypeVar('S')\nT = TypeVar('T')\na: A[B, C]\nb: B\nc: C\n\nif int():\n    b = a + b # E: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\n    c = a + c # E: Unsupported operand types for + (\"A[B, C]\" and \"C\")\nif int():\n    c = a[c]  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"C\")\n    b = a[b]  # E: Invalid index type \"B\" for \"A[B, C]\"; expected type \"C\"\n\nif int():\n    c = a + b\n    b = a[c]\n\nclass A(Generic[S, T]):\n    def __add__(self, a: S) -> T: pass\n    def __getitem__(self, i: T) -> S: pass\n\nclass B: pass\nclass C: pass\n\n[case testOperatorAssignmentWithIndexLvalue1]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nb: B\nc: C\nac: A[C]\n\nac[b] += b # Fail\nac[c] += c # Fail\nac[b] += c\nac[b] = ac[b] + c\n\nclass A(Generic[T]):\n    def __getitem__(self, i: 'B') -> T: pass\n    def __setitem__(self, i: 'B', v: T) -> None: pass\n\nclass B: pass\nclass C:\n    def __add__(self, o: 'C') -> 'C': pass\n[out]\nmain:7: error: Unsupported operand types for + (\"C\" and \"B\")\nmain:8: error: Invalid index type \"C\" for \"A[C]\"; expected type \"B\"\n\n[case testOperatorAssignmentWithIndexLvalue2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nb: B\nc: C\nac: A[C]\n\nac[b] += c        # Fail\nac[c] += c        # Fail\nac[b] = ac[b] + c # Fail\n\nclass A(Generic[T]):\n    def __getitem__(self, i: 'B') -> T: pass\n    def __setitem__(self, i: 'C', v: T) -> None: pass\n\nclass B: pass\nclass C:\n    def __add__(self, o: 'C') -> 'C': pass\n[out]\nmain:7: error: Invalid index type \"B\" for \"A[C]\"; expected type \"C\"\nmain:8: error: Invalid index type \"C\" for \"A[C]\"; expected type \"B\"\nmain:9: error: Invalid index type \"B\" for \"A[C]\"; expected type \"C\"\n\n\n-- Nested generic types\n-- --------------------\n\n\n[case testNestedGenericTypes]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\naab: A[A[B]]\naac: A[A[C]]\nab: A[B]\nac: A[C]\n\nif int():\n    ac = aab.x # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[C]\")\nac.y = aab # E: Incompatible types in assignment (expression has type \"A[A[B]]\", variable has type \"A[A[C]]\")\n\nif int():\n    ab = aab.x\n    ac = aac.x\nab.y = aab\nac.y = aac\n\nclass A(Generic[T]):\n    x: T\n    y: A[A[T]]\n\nclass B:\n    pass\nclass C:\n    pass\n\n\n-- Generic functions\n-- -----------------\n\n\n[case testTypeCheckingGenericFunctionBody]\nfrom typing import TypeVar, Generic\nS = TypeVar('S')\nT = TypeVar('T')\nclass A: pass\nclass p(Generic[T, S]):\n    def __init__(self, t: T, a: S) -> None: pass\ndef f(s: S, t: T) -> p[T, A]:\n    a = t # type: S # E: Incompatible types in assignment (expression has type \"T\", variable has type \"S\")\n    if int():\n        s = t           # E: Incompatible types in assignment (expression has type \"T\", variable has type \"S\")\n    p_s_a: p[S, A]\n    if s:\n        return p_s_a # E: Incompatible return value type (got \"p[S, A]\", expected \"p[T, A]\")\n    b = t # type: T\n    c = s # type: S\n    p_t_a: p[T, A]\n    return p_t_a\n[out]\n\n[case testTypeCheckingGenericMethodBody]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass p(Generic[T, S]):\n    def __init__(self, t: T, a: S) -> None: pass\nclass A(Generic[T]):\n    def f(self, s: S, t: T) -> p[S, T]:\n        if int():\n            s = t # E: Incompatible types in assignment (expression has type \"T\", variable has type \"S\")\n        p_s_s: p[S, S]\n        if s:\n            return p_s_s # E: Incompatible return value type (got \"p[S, S]\", expected \"p[S, T]\")\n        p_t_t: p[T, T]\n        if t:\n            return p_t_t # E: Incompatible return value type (got \"p[T, T]\", expected \"p[S, T]\")\n        if 1:\n            t = t\n            s = s\n            p_s_t: p[S, T]\n            return p_s_t\n[out]\n\n[case testProhibitTypeApplicationToGenericFunctions]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef f(x: T) -> T: pass\n\ny = f[int]  # E: Type application is only supported for generic classes\n[out]\n\n\n-- Generic types in expressions\n-- ----------------------------\n\n\n[case testTypeApplicationArgs]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass Node(Generic[T]):\n    def __init__(self, x: T) -> None:\n        ...\nNode[int]()  # E: Missing positional argument \"x\" in call to \"Node\"\nNode[int](1, 1, 1)  # E: Too many arguments for \"Node\"\n[out]\n\n[case testTypeApplicationTvars]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass A(Generic[T, S]): pass\nA[int]()  # E: Type application has too few types (2 expected)\nA[int, str, int]() # E: Type application has too many types (2 expected)\n[out]\n\n[case testInvalidTypeApplicationType]\nimport types\na: A\nclass A: pass\na[A]()  # E: Value of type \"A\" is not indexable\nA[A]()  # E: The type \"type[A]\" is not generic and not indexable\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testTypeApplicationArgTypes]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass Node(Generic[T]):\n    def __init__(self, x: T) -> None:\n        ...\n\nNode[int](1)\nNode[int]('a')  # E: Argument 1 to \"Node\" has incompatible type \"str\"; expected \"int\"\n\nclass Dummy(Generic[T]):\n    def meth(self, x: T) -> None:\n        ...\n    def methout(self) -> T:\n        ...\n\nDummy[int]().meth(1)\nDummy[int]().meth('a')  # E: Argument 1 to \"meth\" of \"Dummy\" has incompatible type \"str\"; expected \"int\"\nreveal_type(Dummy[int]())  # N: Revealed type is \"__main__.Dummy[builtins.int]\"\nreveal_type(Dummy[int]().methout())  # N: Revealed type is \"builtins.int\"\n[out]\n\n[case testTypeApplicationArgTypesSubclasses]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass C(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None:\n        ...\n\nclass D(C[int, T]): ...\n\nD[str](1, 'a')\nD[str](1, 1)  # E: Argument 2 to \"D\" has incompatible type \"int\"; expected \"str\"\n\nclass E(D[str]): ...\nE(1, 'a')\nE(1, 1)  # E: Argument 2 to \"E\" has incompatible type \"int\"; expected \"str\"\n[out]\n\n[case testTypeApplicationAlias]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass Node(Generic[T]):\n    def __init__(self, x: T) -> None:\n        ...\n\nAlias = Node\nAlias[int](1)\nAlias[int](\"a\")  # E: Argument 1 to \"Node\" has incompatible type \"str\"; expected \"int\"\n[out]\n\n[case testTypeApplicationCrash]\nimport types\ntype[int]\n[builtins fixtures/tuple.pyi]\n\n\n-- Generic type aliases\n-- --------------------\n\n[case testGenericTypeAliasesBasic]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass Node(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None:\n        ...\n\nIntNode = Node[int, S]\nIntIntNode = Node[int, int]\nSameNode = Node[T, T]\n\nn = Node(1, 1) # type: IntIntNode\nn1 = Node(1, 'a') # type: IntIntNode # E: Argument 2 to \"Node\" has incompatible type \"str\"; expected \"int\"\n\nm = Node(1, 1) # type: IntNode\nm1 = Node('x', 1) # type: IntNode # E: Argument 1 to \"Node\" has incompatible type \"str\"; expected \"int\"\nm2 = Node(1, 1) # type: IntNode[str] # E: Argument 2 to \"Node\" has incompatible type \"int\"; expected \"str\"\n\ns = Node(1, 1) # type: SameNode[int]\nreveal_type(s) # N: Revealed type is \"__main__.Node[builtins.int, builtins.int]\"\ns1 = Node(1, 'x') # type: SameNode[int] # E: Argument 2 to \"Node\" has incompatible type \"str\"; expected \"int\"\n\n[out]\n\n[case testGenericTypeAliasesBasic2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass Node(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None:\n        ...\n\nIntNode = Node[int, S]\nIntIntNode = Node[int, int]\nSameNode = Node[T, T]\n\ndef output_bad() -> IntNode[str]:\n    return Node(1, 1) # Error - bad return type, see out\n\ndef input(x: IntNode[str]) -> None:\n    pass\ninput(Node(1, 's'))\ninput(Node(1, 1)) # E: Argument 2 to \"Node\" has incompatible type \"int\"; expected \"str\"\n\ndef output() -> IntNode[str]:\n    return Node(1, 'x')\nreveal_type(output()) # N: Revealed type is \"__main__.Node[builtins.int, builtins.str]\"\n\ndef func(x: IntNode[T]) -> IntNode[T]:\n    return x\nreveal_type(func) # N: Revealed type is \"def [T] (x: __main__.Node[builtins.int, T`-1]) -> __main__.Node[builtins.int, T`-1]\"\n\nfunc(1) # E: Argument 1 to \"func\" has incompatible type \"int\"; expected \"Node[int, Never]\"\nfunc(Node('x', 1)) # E: Argument 1 to \"Node\" has incompatible type \"str\"; expected \"int\"\nreveal_type(func(Node(1, 'x'))) # N: Revealed type is \"__main__.Node[builtins.int, builtins.str]\"\n\ndef func2(x: SameNode[T]) -> SameNode[T]:\n    return x\nreveal_type(func2) # N: Revealed type is \"def [T] (x: __main__.Node[T`-1, T`-1]) -> __main__.Node[T`-1, T`-1]\"\n\nfunc2(Node(1, 'x')) # E: Cannot infer value of type parameter \"T\" of \"func2\"\ny = func2(Node('x', 'x'))\nreveal_type(y) # N: Revealed type is \"__main__.Node[builtins.str, builtins.str]\"\n\ndef wrap(x: T) -> IntNode[T]:\n    return Node(1, x)\n\nz: str\nreveal_type(wrap(z)) # N: Revealed type is \"__main__.Node[builtins.int, builtins.str]\"\n\n[out]\nmain:13: error: Argument 2 to \"Node\" has incompatible type \"int\"; expected \"str\"\n\n-- Error formatting is a bit different (and probably better) with new analyzer\n[case testGenericTypeAliasesWrongAliases]\n# flags: --show-column-numbers --no-strict-optional\nfrom typing import TypeVar, Generic, List, Callable, Tuple, Union\nT = TypeVar('T')\nS = TypeVar('S')\nclass Node(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None:\n        ...\n\nA = Node[T] # Error\nB = Node[T, T]\nC = Node[T, T, T] # Error\nD = Node[T, S]\nE = Node[Node[T, T], List[T]]\n\nF = Node[List[T, T], S] # Error\nG = Callable[..., List[T, T]] # Error\nH = Union[int, Tuple[T, Node[T]]] # Error\nh: H # This was reported on previous line\nh1: H[int, str] # Error\n\nx = None # type: D[int, str]\nreveal_type(x)\ny = None # type: E[int]\nreveal_type(y)\n\nX = T # Error\n\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-full.pyi]\n[out]\nmain:9:5: error: \"Node\" expects 2 type arguments, but 1 given\nmain:11:5: error: \"Node\" expects 2 type arguments, but 3 given\nmain:15:10: error: \"list\" expects 1 type argument, but 2 given\nmain:16:19: error: \"list\" expects 1 type argument, but 2 given\nmain:17:25: error: \"Node\" expects 2 type arguments, but 1 given\nmain:19:5: error: Bad number of arguments for type alias, expected 1, given 2\nmain:22:13: note: Revealed type is \"__main__.Node[builtins.int, builtins.str]\"\nmain:24:13: note: Revealed type is \"__main__.Node[__main__.Node[builtins.int, builtins.int], builtins.list[builtins.int]]\"\nmain:26:5: error: Type variable \"__main__.T\" is invalid as target for type alias\n\n[case testGenericTypeAliasesForAliases]\nfrom typing import TypeVar, Generic, List, Union\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass Node(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None:\n        pass\n\nListedNode = Node[List[T], List[S]]\nSecond = ListedNode[int, T]\nThird = Union[int, Second[str]]\n\ndef f2(x: T) -> Second[T]:\n    return Node([1], [x])\nreveal_type(f2('a')) # N: Revealed type is \"__main__.Node[builtins.list[builtins.int], builtins.list[builtins.str]]\"\n\ndef f3() -> Third:\n    return Node([1], ['x'])\nreveal_type(f3()) # N: Revealed type is \"builtins.int | __main__.Node[builtins.list[builtins.int], builtins.list[builtins.str]]\"\n\n[builtins fixtures/list.pyi]\n\n[case testGenericTypeAliasesWithNestedArgs]\n# flags: --pretty --show-error-codes\nimport other\na: other.Array[float]\nreveal_type(a) # N: Revealed type is \"other.array[Any, other.dtype[builtins.float]]\"\n\n[out]\nmain:3: error: Type argument \"float\" of \"Array\" must be a subtype of \"generic\"  [type-var]\n    a: other.Array[float]\n                   ^\n[file other.py]\nfrom typing import Any, Generic, TypeVar\n\nDT = TypeVar(\"DT\", covariant=True, bound='dtype[Any]')\nDTS = TypeVar(\"DTS\", covariant=True, bound='generic')\nS = TypeVar(\"S\", bound=Any)\nST = TypeVar(\"ST\", bound='generic', covariant=True)\n\nclass common: pass\nclass generic(common): pass\nclass dtype(Generic[DTS]): pass\nclass array(common, Generic[S, DT]): pass\nArray = array[Any, dtype[ST]]\n\n[case testGenericTypeAliasesAny]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass Node(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None:\n        self.x = x\n        self.y = y\n\nIntNode = Node[int, S]\nAnyNode = Node[S, T]\n\ndef output() -> IntNode[str]:\n    return Node(1, 'x')\nx = output() # type: IntNode # This is OK (implicit Any)\n\ny: IntNode\ny.x = 1\ny.x = 'x' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ny.y = 1 # Both are OK (implicit Any)\ny.y = 'x'\n\nz = Node(1, 'x') # type: AnyNode\nreveal_type(z) # N: Revealed type is \"__main__.Node[Any, Any]\"\n\n[out]\n\n[case testGenericTypeAliasesAccessingMethods]\nfrom typing import TypeVar, Generic, List\nT = TypeVar('T')\nclass Node(Generic[T]):\n    def __init__(self, x: T) -> None:\n        self.x = x\n    def meth(self) -> T:\n        return self.x\n\nListedNode = Node[List[T]]\nl: ListedNode[int]\nl.x.append(1)\nl.meth().append(1)\nreveal_type(l.meth()) # N: Revealed type is \"builtins.list[builtins.int]\"\nl.meth().append('x') # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\n\nListedNode[str]([]).x = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"list[str]\")\n\n[builtins fixtures/list.pyi]\n\n[case testGenericTypeAliasesSubclassing]\nfrom typing import TypeVar, Generic, Tuple, List\nT = TypeVar('T')\nclass Node(Generic[T]):\n    def __init__(self, x: T) -> None:\n        ...\n\nTupledNode = Node[Tuple[T, T]]\n\nclass D(TupledNode[T]):\n    ...\nclass L(List[TupledNode[T]]):\n    ...\n\ndef f_bad(x: T) -> D[T]:\n    return D(1)  # Error, see out\n\nL[int]().append(Node((1, 1)))\nL[int]().append(5) # E: Argument 1 to \"append\" of \"list\" has incompatible type \"int\"; expected \"Node[tuple[int, int]]\"\n\nx = D((1, 1)) # type: D[int]\ny = D(5) # type: D[int] # E: Argument 1 to \"D\" has incompatible type \"int\"; expected \"tuple[int, int]\"\n\ndef f(x: T) -> D[T]:\n    return D((x, x))\nreveal_type(f('a'))  # N: Revealed type is \"__main__.D[builtins.str]\"\n\n[builtins fixtures/list.pyi]\n[out]\nmain:15: error: Argument 1 to \"D\" has incompatible type \"int\"; expected \"tuple[T, T]\"\n\n[case testGenericTypeAliasesSubclassingBad]\n\nfrom typing import TypeVar, Generic, Tuple, Union\nT = TypeVar('T')\nclass Node(Generic[T]):\n    def __init__(self, x: T) -> None:\n        ...\n\nTupledNode = Node[Tuple[T, T]]\nUNode = Union[int, Node[T]]\n\nclass C(TupledNode): ... # Same as TupledNode[Any]\nclass D(TupledNode[T]): ...\nclass E(Generic[T], UNode[T]): ... # E: Invalid base class \"UNode\"\n\nreveal_type(D((1, 1))) # N: Revealed type is \"__main__.D[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testGenericTypeAliasesUnion]\nfrom typing import TypeVar, Generic, Union, Any\nT = TypeVar('T')\nclass Node(Generic[T]):\n    def __init__(self, x: T) -> None:\n        self.x = x\n\nUNode = Union[int, Node[T]]\nx = 1 # type: UNode[int]\n\nx + 1 # E: Unsupported left operand type for + (\"Node[int]\") \\\n      # N: Left operand is of type \"int | Node[int]\"\nif not isinstance(x, Node):\n    x + 1\n\nif not isinstance(x, int):\n   x.x = 1\n   x.x = 'a' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\ndef f(x: T) -> UNode[T]:\n    if int():\n        return Node(x)\n    else:\n        return 1\n\nreveal_type(f(1)) # N: Revealed type is \"builtins.int | __main__.Node[builtins.int]\"\n\nTNode = Union[T, Node[int]]\ns = 1 # type: TNode[str] # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str | Node[int]\")\n\nif not isinstance(s, str):\n    s.x = 1\n\nz = None # type: TNode # Same as TNode[Any]\nz.x\nz.foo() # E: Item \"Node[int]\" of \"Any | Node[int]\" has no attribute \"foo\"\n\n[builtins fixtures/isinstance.pyi]\n\n[case testGenericTypeAliasesTuple]\nfrom typing import TypeVar, Tuple\nT = TypeVar('T')\n\nSameTP = Tuple[T, T]\nIntTP = Tuple[int, T]\n\ndef f1(x: T) -> SameTP[T]:\n    return x, x\n\na, b, c = f1(1) # E: Need more than 2 values to unpack (3 expected)\nx, y = f1(1)\nreveal_type(x) # N: Revealed type is \"builtins.int\"\n\ndef f2(x: IntTP[T]) -> IntTP[T]:\n    return x\n\nf2((1, 2, 3)) # E: Argument 1 to \"f2\" has incompatible type \"tuple[int, int, int]\"; expected \"tuple[int, Never]\"\nreveal_type(f2((1, 'x'))) # N: Revealed type is \"tuple[builtins.int, builtins.str]\"\n\n[builtins fixtures/for.pyi]\n\n[case testGenericTypeAliasesCallable]\nfrom typing import TypeVar, Generic, Callable\nT = TypeVar('T')\nclass Node(Generic[T]):\n    def __init__(self, x: T) -> None:\n        ...\n\nBadC = Callable[T] # E: Please use \"Callable[[<parameters>], <return type>]\" or \"Callable\"\n\nC = Callable[..., T]\nC2 = Callable[[T, T], Node[T]]\n\ndef make_cb(x: T) -> C[T]:\n    return lambda *args: x\n\nreveal_type(make_cb(1)) # N: Revealed type is \"def (*Any, **Any) -> builtins.int\"\n\ndef use_cb(arg: T, cb: C2[T]) -> Node[T]:\n    return cb(arg, arg)\n\nuse_cb(1, 1) # E: Argument 2 to \"use_cb\" has incompatible type \"int\"; expected \"Callable[[int, int], Node[int]]\"\nmy_cb: C2[int]\nuse_cb('x', my_cb) # E: Argument 2 to \"use_cb\" has incompatible type \"Callable[[int, int], Node[int]]\"; expected \"Callable[[str, str], Node[str]]\"\nreveal_type(use_cb(1, my_cb)) # N: Revealed type is \"__main__.Node[builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[out]\n\n[case testGenericTypeAliasesPEPBasedExample]\nfrom typing import TypeVar, List, Tuple\nT = TypeVar('T', int, bool)\n\nVec = List[Tuple[T, T]]\n\nvec = []  # type: Vec[bool]\nvec.append('x') # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"tuple[bool, bool]\"\nreveal_type(vec[0]) # N: Revealed type is \"tuple[builtins.bool, builtins.bool]\"\n\ndef fun1(v: Vec[T]) -> T:\n    return v[0][0]\ndef fun2(v: Vec[T], scale: T) -> Vec[T]:\n    return v\n\nreveal_type(fun1([(1, 1)])) # N: Revealed type is \"builtins.int\"\nfun1(1) # E: Argument 1 to \"fun1\" has incompatible type \"int\"; expected \"list[tuple[bool, bool]]\"\nfun1([(1, 'x')]) # E: Cannot infer value of type parameter \"T\" of \"fun1\"\n\nreveal_type(fun2([(1, 1)], 1)) # N: Revealed type is \"builtins.list[tuple[builtins.int, builtins.int]]\"\nfun2([('x', 'x')], 'x') # E: Value of type variable \"T\" of \"fun2\" cannot be \"str\"\n\n[builtins fixtures/list.pyi]\n\n[case testGenericTypeAliasesImporting]\nfrom typing import TypeVar\nfrom a import Node, TupledNode\nT = TypeVar('T')\n\nn: TupledNode[int]\nn.x = 1\nn.y = (1, 1)\nn.y = 'x' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"tuple[int, int]\")\n\ndef f(x: Node[T, T]) -> TupledNode[T]:\n    return Node(x.x, (x.x, x.x))\n\nf(1) # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"Node[Never, Never]\"\nf(Node(1, 'x')) # E: Cannot infer value of type parameter \"T\" of \"f\"\nreveal_type(Node('x', 'x')) # N: Revealed type is \"a.Node[builtins.str, builtins.str]\"\n\n[file a.py]\nfrom typing import TypeVar, Generic, Tuple\nT = TypeVar('T')\nS = TypeVar('S')\nclass Node(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None:\n        self.x = x\n        self.y = y\n\nTupledNode = Node[T, Tuple[T, T]]\n\n[builtins fixtures/list.pyi]\n\n[case testGenericTypeAliasesImportingWithoutTypeVar]\nfrom typing import Tuple\nfrom lib import Transform\n\ndef int_tf(m: int) -> Transform[int, str]:\n    def transform(i: int, pos: int) -> Tuple[int, str]:\n        pass\n    return transform\n\nvar: Transform[int, str]\nreveal_type(var)  # N: Revealed type is \"def (builtins.int, builtins.int) -> tuple[builtins.int, builtins.str]\"\n[file lib.py]\nfrom typing import Callable, TypeVar, Tuple\n\nT = TypeVar('T')\nR = TypeVar('R')\n\nTransform = Callable[[T, int], Tuple[T, R]]\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testGenericTypeAliasesImportingWithoutTypeVarError]\nfrom a import Alias\nx: Alias[int, str]  # E: Bad number of arguments for type alias, expected 1, given 2\nreveal_type(x)  # N: Revealed type is \"builtins.list[builtins.list[Any]]\"\n\n[file a.py]\nfrom typing import TypeVar, List\nT = TypeVar('T')\n\nAlias = List[List[T]]\n[builtins fixtures/list.pyi]\n\n[case testGenericAliasWithTypeVarsFromDifferentModules]\nfrom mod import Alias, TypeVar\n\nS = TypeVar('S')\nNewAlias = Alias[int, int, S, S]\nclass C: pass\n\nx: NewAlias[str]\nreveal_type(x)  # N: Revealed type is \"builtins.list[tuple[builtins.int, builtins.int, builtins.str, builtins.str]]\"\ny: Alias[int, str, C, C]\nreveal_type(y)  # N: Revealed type is \"builtins.list[tuple[builtins.int, builtins.str, __main__.C, __main__.C]]\"\n\n[file mod.py]\nfrom typing import TypeVar, List, Tuple\nimport a\nimport b\nT = TypeVar('T')\nAlias = List[Tuple[T, a.T, b.T, b.B.T]]  # alias_tvars here will be ['T', 'a.T', 'b.T', 'b.B.T']\n\n[file a.py]\nfrom typing import TypeVar\nT = TypeVar('T')\n\n[file b.py]\nfrom typing import TypeVar\n\nT = TypeVar('T')\nclass B:\n    T = TypeVar('T')\n[builtins fixtures/list.pyi]\n[out]\n\n[case testTypeAliasesResultingInPlainInstance]\nfrom typing import Optional, Union\n\nO = Optional[int]\nU = Union[int]\n\nx: O\ny: U\n\nreveal_type(x)  # N: Revealed type is \"builtins.int | None\"\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\n\nU[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nO[int]  # E: Bad number of arguments for type alias, expected 0, given 1 \\\n        # E: Type application is only supported for generic classes\n\n[case testAliasesInClassBodyNormalVsSubscripted]\n\nfrom typing import Union, Type, Iterable\n\nclass A: pass\nclass B(A): pass\nclass C:\n    a = A  # This is a variable\n    b = Union[int, str]  # This is an alias\n    c: Type[object] = Iterable[int]  # This is however also a variable\n    if int():\n        a = B\n    if int():\n        b = int  # E: Cannot assign multiple types to name \"b\" without an explicit \"type[...]\" annotation\n    if int():\n        c = int\n    def f(self, x: a) -> None: pass  # E: Variable \"__main__.C.a\" is not valid as a type \\\n                                     # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n    def g(self, x: b) -> None: pass\n    def h(self, x: c) -> None: pass  # E: Variable \"__main__.C.c\" is not valid as a type \\\n                                     # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n    x: b\n    reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n[out]\n\n[case testGenericTypeAliasesRuntimeExpressionsInstance]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass Node(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None:\n        ...\n\nIntNode = Node[int, T]\nIntNode[int](1, 1)\nIntNode[int](1, 'a')  # E: Argument 2 to \"Node\" has incompatible type \"str\"; expected \"int\"\n\nSameNode = Node[T, T]\nff = SameNode[T](1, 1)  # E: Type variable \"__main__.T\" is unbound \\\n        # N: (Hint: Use \"Generic[T]\" or \"Protocol[T]\" base class to bind \"T\" inside a class) \\\n        # N: (Hint: Use \"T\" in function signature to bind \"T\" inside a function)\na = SameNode(1, 'x')\nreveal_type(a) # N: Revealed type is \"__main__.Node[Any, Any]\"\nb = SameNode[int](1, 1)\nreveal_type(b) # N: Revealed type is \"__main__.Node[builtins.int, builtins.int]\"\nSameNode[int](1, 'x') # E: Argument 2 to \"Node\" has incompatible type \"str\"; expected \"int\"\n\n[out]\n\n[case testGenericTypeAliasesRuntimeExpressionsOther]\nfrom typing import TypeVar, Union, Tuple, Callable, Any\nT = TypeVar('T')\n\nCA = Callable[[T], int]\nTA = Tuple[T, int]\nUA = Union[T, int]\n\ncs = CA + 1 # E: Unsupported left operand type for + (\"<typing special form>\")\nreveal_type(cs) # N: Revealed type is \"Any\"\n\nts = TA() # E: \"<typing special form>\" not callable\nreveal_type(ts) # N: Revealed type is \"Any\"\n\nus = UA.x # E: \"<typing special form>\" has no attribute \"x\"\nreveal_type(us) # N: Revealed type is \"Any\"\n\nxx = CA[str] + 1  # E: Type application is only supported for generic classes\nyy = TA[str]()  # E: Type application is only supported for generic classes\nzz = UA[str].x  # E: Type application is only supported for generic classes\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\n\n[case testGenericTypeAliasesTypeVarBinding]\nfrom typing import TypeVar, Generic, List\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass A(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None: ...\n\nclass B(Generic[T, S]):\n    def __init__(self, x: List[T], y: List[S]) -> None: ...\n\nSameA = A[T, T]\nSameB = B[T, T]\n\nclass C(Generic[T]):\n    a: SameA[T]\n    b = SameB[T]([], [])\n\nreveal_type(C[int]().a) # N: Revealed type is \"__main__.A[builtins.int, builtins.int]\"\nreveal_type(C[str]().b) # N: Revealed type is \"__main__.B[builtins.str, builtins.str]\"\n\n[builtins fixtures/list.pyi]\n\n[case testGenericTypeAliasesTypeVarConstraints]\n# flags: --show-column-numbers --no-strict-optional\nfrom typing import TypeVar, Generic\nT = TypeVar('T', int, list)\nS = TypeVar('S', int, list)\n\nclass A(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None: ...\n\nBadA = A[str, T]  # One error here\nSameA = A[T, T]\n\nx = None # type: SameA[int]\ny = None # type: SameA[str] # Another error here\n\n[builtins fixtures/list.pyi]\n[out]\nmain:9:8: error: Value of type variable \"T\" of \"A\" cannot be \"str\"\nmain:13:1: error: Value of type variable \"T\" of \"SameA\" cannot be \"str\"\n\n[case testGenericTypeAliasesIgnoredPotentialAlias]\nclass A: ...\nBad = A[int] # type: ignore\n\nreveal_type(Bad) # N: Revealed type is \"def () -> __main__.A\"\n[out]\n\n[case testSubscriptionOfBuiltinAliases]\nfrom typing import List, TypeVar\n\nlist[int]()\n\nListAlias = List\ndef fun() -> ListAlias[int]:\n    pass\n\nreveal_type(fun())  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nBuiltinAlias = list\nBuiltinAlias[int]()\n\nT = TypeVar('T')\nBadGenList = list[T]\n\nreveal_type(BadGenList[int]()) # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(BadGenList()) # N: Revealed type is \"builtins.list[Any]\"\n\n[builtins fixtures/list.pyi]\n[out]\n\n[case testImportedTypeAliasInRuntimeContext]\nfrom m import Alias\n\nn = Alias[int]([1])\nreveal_type(n)  # N: Revealed type is \"m.Node[builtins.list[builtins.int]]\"\nbad = Alias[str]([1])  # E: List item 0 has incompatible type \"int\"; expected \"str\"\n\nn2 = Alias([1]) # Same as Node[List[Any]]\nreveal_type(n2)  # N: Revealed type is \"m.Node[builtins.list[Any]]\"\n[file m.py]\nfrom typing import TypeVar, Generic, List\nT = TypeVar('T')\n\nclass Node(Generic[T]):\n    def __init__(self, x: T) -> None:\n        self.x = x\n\nAlias = Node[List[T]]\n[builtins fixtures/list.pyi]\n[out]\n\n-- Simplified declaration of generics\n-- ----------------------------------\n\n[case testSimplifiedGenericSimple]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass B(Generic[T]):\n    def b(self) -> T: ...\n\nclass C(Generic[T]):\n    def c(self) -> T: ...\n\nclass D(B[T], C[S]): ...\n\nreveal_type(D[str, int]().b()) # N: Revealed type is \"builtins.str\"\nreveal_type(D[str, int]().c()) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testSimplifiedGenericCallable]\nfrom typing import TypeVar, Generic, Callable\nT = TypeVar('T')\nS = TypeVar('S')\nclass B(Generic[T]):\n    def b(self) -> T: ...\n\nclass D(B[Callable[[T], S]]): ...\n\nreveal_type(D[str, int]().b()) # N: Revealed type is \"def (builtins.str) -> builtins.int\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testSimplifiedGenericComplex]\nfrom typing import TypeVar, Generic, Tuple\nT = TypeVar('T')\nS = TypeVar('S')\nU = TypeVar('U')\n\nclass A(Generic[T, S]):\n    pass\n\nclass B(Generic[T, S]):\n    def m(self) -> Tuple[T, S]:\n        pass\n\nclass C(A[S, B[T, int]], B[U, A[int, T]]):\n    pass\n\nc = C[object, int, str]()\nreveal_type(c.m()) # N: Revealed type is \"tuple[builtins.str, __main__.A[builtins.int, builtins.int]]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n\n[case testSimplifiedGenericOrder]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass B(Generic[T]):\n    def b(self) -> T: ...\n\nclass C(Generic[T]):\n    def c(self) -> T: ...\n\nclass D(B[T], C[S], Generic[S, T]): ...\n\nreveal_type(D[str, int]().b()) # N: Revealed type is \"builtins.int\"\nreveal_type(D[str, int]().c()) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testSimplifiedGenericDuplicate]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\n\nclass A(Generic[T, T]): # E: Duplicate type variables in Generic[...] or Protocol[...]\n    pass\n\na = A[int]()\n[builtins fixtures/list.pyi]\n[out]\n\n[case testSimplifiedGenericNotAll]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass A(Generic[T]):\n    pass\nclass B(Generic[T]):\n    pass\n\nclass C(A[T], B[S], Generic[T]): # E: If Generic[...] or Protocol[...] is present it should list all type variables\n    pass\n\nc = C[int, str]()\n[builtins fixtures/list.pyi]\n[out]\n\n[case testSimplifiedGenericInvalid]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    pass\n\nclass B(A[S]): # E: Name \"S\" is not defined\n    pass\n[builtins fixtures/list.pyi]\n[out]\n\n\n-- Multiple assignment with lists\n-- ------------------------------\n\n\n[case testMultipleAssignmentWithLists]\nfrom typing import List\nclass A: pass\nclass B: pass\nclass B2(B): pass\na: A\nb: B\nb2: B2\n\nlist_a = [a]\nlist_b = [b]\nlist_b2 = [b2]\n\nif int():\n    a, b = list_a   # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    b, a = list_a   # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    b2, b2 = list_b # E: Incompatible types in assignment (expression has type \"B\", variable has type \"B2\")\n\na, a = list_a\nb, b2, b = list_b2\n[builtins fixtures/for.pyi]\n\n[case testMultipleAssignmentWithListsInInitialization]\nfrom typing import List\nclass A: pass\nlist_object = [object()]\nlist_a = [A()]\na, b = list_object # type: (A, object) # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nc, d = list_object # type: (object, A) # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\ne, f = list_a # type: (A, object)\n[builtins fixtures/for.pyi]\n\n[case testMultipleAssignmentWithListAndIndexing]\nfrom typing import List\na: List[A]\nb: List[int]\n\na[1], b[1] = a # E: Incompatible types in assignment (expression has type \"A\", target has type \"int\")\na[1], a[2] = a\n\nclass A: pass\n[file builtins.py]\nfrom typing import TypeVar, Generic, Iterable\nT = TypeVar('T')\nclass object: pass\nclass list(Iterable[T]):\n  def __setitem__(self, x: int, v: T) -> None: pass\nclass int: pass\nclass type: pass\nclass tuple: pass\nclass function: pass\nclass str: pass\nclass dict: pass\n\n[case testMultipleAssignmentWithIterable]\nfrom typing import Iterable, TypeVar\na: int\nb: str\nT = TypeVar('T')\n\ndef f(x: T) -> Iterable[T]: pass\n\na, b = f(a)   # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nb, b = f(a)   # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\na, a = f(a)\nb, b = f(b)\n[builtins fixtures/for.pyi]\n\n\n-- Error messages\n-- --------------\n\n\n[case testErrorWithLongGenericTypeName]\nfrom typing import TypeVar, Generic\nB = TypeVar('B')\nC = TypeVar('C')\nD = TypeVar('D')\nE = TypeVar('E')\nF = TypeVar('F')\nG = TypeVar('G')\nH = TypeVar('H')\nI = TypeVar('I')\nJ = TypeVar('J')\nK = TypeVar('K')\nL = TypeVar('L')\nM = TypeVar('M')\nN = TypeVar('N')\nO = TypeVar('O')\nP = TypeVar('P')\nQ = TypeVar('Q')\nR = TypeVar('R')\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\nV = TypeVar('V')\nW = TypeVar('W')\nX = TypeVar('X')\nY = TypeVar('Y')\nZ = TypeVar('Z')\nclass OO: pass\na: A[object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object]\n\ndef f(a: OO) -> None:\n    pass\n\nf(a) # E: Argument 1 to \"f\" has incompatible type \"A[object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object, object]\"; expected \"OO\"\n\nclass A(Generic[B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z]): pass\n\n[case testErrorWithShorterGenericTypeName]\nfrom typing import TypeVar, Generic\nS = TypeVar('S')\nT = TypeVar('T')\na: A[object, B]\ndef f(a: 'B') -> None: pass\n\nf(a) # E: Argument 1 to \"f\" has incompatible type \"A[object, B]\"; expected \"B\"\n\nclass A(Generic[S, T]): pass\nclass B: pass\n\n[case testErrorWithShorterGenericTypeName2]\nfrom typing import Callable, TypeVar, Generic\nS = TypeVar('S')\nT = TypeVar('T')\na: A[object, Callable[[], None]]\ndef f(a: 'B') -> None: pass\n\nf(a) # E: Argument 1 to \"f\" has incompatible type \"A[object, Callable[[], None]]\"; expected \"B\"\n\nclass A(Generic[S, T]): pass\nclass B: pass\n\n\n-- Overloads + generics\n-- --------------------\n\n\n[case testGenericArgumentInOverload]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, List\nclass A: pass\nclass B: pass\na: A\nb: B\n\n@overload\ndef f(a: List[A]) -> A: pass\n@overload\ndef f(a: B) -> B: pass\n\nb = f([a]) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\na = f([b]) # E: List item 0 has incompatible type \"B\"; expected \"A\"\na = f(b)   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\na = f([a])\nb = f(b)\n[builtins fixtures/list.pyi]\n\n[case testGenericFunctionAsOverloadItem]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, TypeVar, List\nT = TypeVar('T')\nclass A: pass\nclass B: pass\n\n@overload\ndef f(a: B) -> B: pass\n@overload\ndef f(a: List[T]) -> T: pass\n\na: A\nb: B\n\nif int():\n    b = f([a]) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    a = f([b]) # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    a = f(b)   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\nif int():\n    a = f([a])\n    b = f([b])\nif int():\n    b = f(b)\n[builtins fixtures/list.pyi]\n\n[case testGenericDictWithOverload]\nfrom typing import Dict, Generic, TypeVar, Any, overload\nT = TypeVar(\"T\")\n\nclass Key(Generic[T]): ...\nclass CustomDict(dict):\n    @overload  # type: ignore[override]\n    def __setitem__(self, key: Key[T], value: T) -> None: ...\n    @overload\n    def __setitem__(self, key: str, value: Any) -> None: ...\n    def __setitem__(self, key, value):\n        return super().__setitem__(key, value)\n\ndef a1(d: Dict[str, Any]) -> None:\n    if (var := d.get(\"arg\")) is None:\n        var = d[\"arg\"] = {}\n        reveal_type(var)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n\ndef a2(d: CustomDict) -> None:\n    if (var := d.get(\"arg\")) is None:\n        var = d[\"arg\"] = {}\n        reveal_type(var)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n\n-- Type variable scoping\n-- ---------------------\n\n\n[case testLocalTypeVariable]\nfrom typing import TypeVar\ndef f() -> None:\n    T = TypeVar('T')\n    def g(x: T) -> T: pass\n    a = g(1)\n    if int():\n        a = 1\n        a = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[out]\n\n[case testClassLevelTypeVariable]\nfrom typing import TypeVar\nclass A:\n    T = TypeVar('T')\n    def g(self, x: T) -> T: pass\na = A().g(1)\nif int():\n    a = 1\nif int():\n    a = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testGenericInnerClass]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A:\n    class B(Generic[T]):\n        def meth(self) -> T:  ...\n    B[int]()\n    reveal_type(B[int]().meth) # N: Revealed type is \"def () -> builtins.int\"\n\nA.B[int]()\nreveal_type(A.B[int]().meth) # N: Revealed type is \"def () -> builtins.int\"\n\n[case testGenericClassInnerFunctionTypeVariable]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    def __init__(self, a: T) -> None:\n        self.a = a\n    def f(self, n: int) -> None:\n        def g(a: T):\n            self.a = a\n        g(self.a)\n        g(n) # E: Argument 1 to \"g\" has incompatible type \"int\"; expected \"T\"\n\n-- This is non-trivial with new analyzer (and also in fine grained incremental):\n-- We need to store whole tvar_scope, not only active class.\n[case testFunctionInGenericInnerClassTypeVariable-skip]\n\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nclass Outer(Generic[T]):\n    class Inner:\n        x: T  # E: Invalid type \"__main__.T\"\n        def f(self, x: T) -> T: ...  # E: Type variable \"T\" is bound by an outer class\n        def g(self) -> None:\n            y: T  # E: Invalid type \"__main__.T\"\n\n[case testGenericClassInsideOtherGenericClass]\nfrom typing import TypeVar, Generic\nT = TypeVar(\"T\")\nK = TypeVar(\"K\")\n\nclass C(Generic[T]):\n    def __init__(self, t: T) -> None: ...\n    class F(Generic[K]):\n        def __init__(self, k: K) -> None: ...\n        def foo(self) -> K: ...\n\nreveal_type(C.F(17).foo())      # N: Revealed type is \"builtins.int\"\nreveal_type(C(\"\").F(17).foo())  # N: Revealed type is \"builtins.int\"\nreveal_type(C.F)                # N: Revealed type is \"def [K] (k: K`1) -> __main__.C.F[K`1]\"\nreveal_type(C(\"\").F)            # N: Revealed type is \"def [K] (k: K`6) -> __main__.C.F[K`6]\"\n\n\n-- Callable subtyping with generic functions\n-- -----------------------------------------\n\n\n[case testSubtypingWithGenericFunctions]\nfrom typing import TypeVar\nA = TypeVar('A')\nB = TypeVar('B')\n\ndef f1(x: A) -> A: ...\ndef f2(x: A) -> B: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\ndef f3(x: B) -> B: ...\ndef f4(x: int) -> A: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\n\ny1 = f1\nif int():\n    y1 = f1\nif int():\n    y1 = f2\nif int():\n    y1 = f3\nif int():\n    y1 = f4 # E: Incompatible types in assignment (expression has type \"Callable[[int], A@f4]\", variable has type \"Callable[[A@f1], A@f1]\")\n\ny2 = f2\nif int():\n    y2 = f2\nif int():\n    y2 = f1 # E: Incompatible types in assignment (expression has type \"Callable[[A@f1], A@f1]\", variable has type \"Callable[[A@f2], B]\")\nif int():\n    y2 = f3 # E: Incompatible types in assignment (expression has type \"Callable[[B@f3], B@f3]\", variable has type \"Callable[[A], B@f2]\")\nif int():\n    y2 = f4 # E: Incompatible types in assignment (expression has type \"Callable[[int], A@f4]\", variable has type \"Callable[[A@f2], B]\")\n\ny3 = f3\nif int():\n    y3 = f3\nif int():\n    y3 = f1\nif int():\n    y3 = f2\nif int():\n    y3 = f4 # E: Incompatible types in assignment (expression has type \"Callable[[int], A]\", variable has type \"Callable[[B], B]\")\n\ny4 = f4\nif int():\n    y4 = f4\nif int():\n    y4 = f1 # E: Incompatible types in assignment (expression has type \"Callable[[A@f1], A@f1]\", variable has type \"Callable[[int], A@f4]\")\nif int():\n    y4 = f2\nif int():\n    y4 = f3 # E: Incompatible types in assignment (expression has type \"Callable[[B], B]\", variable has type \"Callable[[int], A]\")\n\n[case testSubtypingWithGenericInnerFunctions]\nfrom typing import TypeVar\nA = TypeVar('A')\nB = TypeVar('B')\nT = TypeVar('T')\ndef outer(t: T) -> None:\n    def f1(x: A) -> A: ...\n    def f2(x: A) -> B: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\n    def f3(x: T) -> A: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\n    def f4(x: A) -> T: ...\n    def f5(x: T) -> T: ...\n\n    y1 = f1\n    if int():\n        y1 = f2\n        y1 = f3 # E: Incompatible types in assignment (expression has type \"Callable[[T], A@f3]\", variable has type \"Callable[[A@f1], A@f1]\")\n        y1 = f4 # E: Incompatible types in assignment (expression has type \"Callable[[A@f4], T]\", variable has type \"Callable[[A@f1], A@f1]\")\n        y1 = f5 # E: Incompatible types in assignment (expression has type \"Callable[[T], T]\", variable has type \"Callable[[A], A]\")\n\n    y2 = f2\n    if int():\n        y2 = f1 # E: Incompatible types in assignment (expression has type \"Callable[[A@f1], A@f1]\", variable has type \"Callable[[A@f2], B]\")\n\n    y3 = f3\n    if int():\n        y3 = f1 # E: Incompatible types in assignment (expression has type \"Callable[[A@f1], A@f1]\", variable has type \"Callable[[T], A@f3]\")\n        y3 = f2\n        y3 = f4 # E: Incompatible types in assignment (expression has type \"Callable[[A@f4], T]\", variable has type \"Callable[[T], A@f3]\")\n        y3 = f5 # E: Incompatible types in assignment (expression has type \"Callable[[T], T]\", variable has type \"Callable[[T], A]\")\n\n    y4 = f4\n    if int():\n        y4 = f1 # E: Incompatible types in assignment (expression has type \"Callable[[A@f1], A@f1]\", variable has type \"Callable[[A@f4], T]\")\n        y4 = f2\n        y4 = f3 # E: Incompatible types in assignment (expression has type \"Callable[[T], A@f3]\", variable has type \"Callable[[A@f4], T]\")\n        y4 = f5 # E: Incompatible types in assignment (expression has type \"Callable[[T], T]\", variable has type \"Callable[[A], T]\")\n\n    y5 = f5\n    if int():\n        y5 = f1\n        y5 = f2\n        y5 = f3\n        y5 = f4\n\n[case testSubtypingWithGenericFunctionUsingTypevarWithValues]\nfrom typing import TypeVar, Callable\nT = TypeVar('T', int, str)\ndef f(x: T) -> T: pass\ndef g1(f: Callable[[str], str]) -> None: pass\ng1(f)\ndef g2(f: Callable[[int], int]) -> None: pass\ng2(f)\ndef g3(f: Callable[[object], object]) -> None: pass\ng3(f) # E: Argument 1 to \"g3\" has incompatible type \"Callable[[T], T]\"; \\\n           expected \"Callable[[object], object]\"\n\n[case testSubtypingWithGenericFunctionUsingTypevarWithValues2]\nfrom typing import TypeVar, Callable\nT = TypeVar('T', int, str)\ndef f(x: T) -> T: pass\ng = f\ng = f\n\n\n--Operations on type variable types\n-- ---------------------------------\n\n\n[case testTypeVariableTypeEquality]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef f(a: T, b: T) -> T:\n    a.__ne__(b)\n    if a == b:\n        return a\n    else:\n        return b\n[builtins fixtures/ops.pyi]\n\n[case testTypeVariableTypeIs]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef f(a: T, b: T) -> T:\n    if a is b or a is 1:\n        return a\n    else:\n        return b\n[builtins fixtures/ops.pyi]\n\n[case testTypeVarLessThan]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef f(a: T, b: T) -> T:\n    if a < b:  # E: Unsupported left operand type for < (\"T\")\n        return a\n    else:\n        return b\n[builtins fixtures/ops.pyi]\n\n[case testTypeVarReversibleOperator]\nfrom typing import TypeVar\nclass A:\n    def __mul__(cls, other: int) -> str: return \"\"\nT = TypeVar(\"T\", bound=A)\ndef f(x: T) -> str:\n    return reveal_type(x * 0)  # N: Revealed type is \"builtins.str\"\n\n[case testTypeVarReversibleOperatorTuple]\nfrom typing import TypeVar, Tuple\nclass A(Tuple[int, int]):\n    def __mul__(cls, other: Tuple[int, int]) -> str: return \"\" # type: ignore # overriding default __mul__\nT = TypeVar(\"T\", bound=A)\ndef f(x: T) -> str:\n    return reveal_type(x * (1, 2) )  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/tuple.pyi]\n\n\n-- Subtyping generic callables\n-- ---------------------------\n\n[case testSubtypingGenericTypeObject]\nfrom typing import Callable, Generic, TypeVar\nT = TypeVar('T')\nclass C(Generic[T]):\n    def __init__(self) -> None: pass\nx = C # type: Callable[[], C[int]]\ny = C # type: Callable[[], int] # E: Incompatible types in assignment (expression has type \"type[C[T]]\", variable has type \"Callable[[], int]\")\n\n-- Special cases\n-- -------------\n\n\n[case testIdentityHigherOrderFunction]\nfrom typing import Callable, TypeVar\nA = TypeVar('A')\nB = TypeVar('B')\ndef square(n: int) -> int:\n    return n\ndef id(f: Callable[[A], B]) -> Callable[[A], B]:\n    return f\ng = id(square)\ng(1)\ng('x')  # E: Argument 1 has incompatible type \"str\"; expected \"int\"\n\n\n[case testIdentityHigherOrderFunction2]\nfrom typing import Callable, TypeVar\nA = TypeVar('A')\ndef voidify(n: int) -> None: pass\ndef identity(f: Callable[[A], None]) -> Callable[[A], None]:\n    return f\nidentity(voidify)(3)\n\n[case testIdentityHigherOrderFunction3]\nfrom typing import Callable, TypeVar\nA = TypeVar('A')\nB = TypeVar('B')\ndef fn(n: B) -> None: pass\ndef identity(f: A) -> A:\n    return f\nidentity(fn)\nidentity(fn)('x')\n\n[case testTypeVariableUnionAndCallableInTypeInference]\nfrom typing import Union, Callable, TypeVar\nT = TypeVar('T')\ndef f(x: T, y: Union[T, Callable[[T], None]]) -> None: pass\nf('', '')\n\n[case testGenericFunctionsWithUnalignedIds]\nfrom typing import TypeVar\nA = TypeVar('A')\nB = TypeVar('B')\ndef f1(x: int, y: A) -> A: ...\ndef f2(x: int, y: A) -> B: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\ndef f3(x: A, y: B) -> B: ...\ng = f1\ng = f2\ng = f3\n\n[case testTypeVariableWithContainerAndTuple]\nfrom typing import TypeVar, Container\nT = TypeVar('T')\ndef f(x: Container[T]) -> T: ...\nreveal_type(f((1, 2))) # N: Revealed type is \"builtins.int\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testClassMethodInGenericClassWithGenericConstructorArg]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    def __init__(self, a: T) -> None: pass\n    @classmethod\n    def f(cls) -> None: pass\n[builtins fixtures/classmethod.pyi]\n\n[case testClassMethodInClassWithGenericConstructor]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A:\n    def __init__(self, a: T) -> None: pass\n    @classmethod\n    def f(cls) -> None: pass\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericOperatorMethodOverlapping]\nfrom typing import TypeVar, Generic, Tuple\nT = TypeVar('T')\nT2 = TypeVar('T2')\nS = TypeVar('S', bound=str)\nS2 = TypeVar('S2', bound=str)\nclass G(Generic[T]):\n    pass\nclass A:\n    def __or__(self, x: G[T]) -> G[T]: pass\n    def __ior__(self, x: G[T2]) -> G[T2]: pass\nclass B:\n    def __or__(self, x: G[T]) -> G[T]: pass\n    def __ior__(self, x: G[S]) -> G[S]: pass \\\n        # E: Signatures of \"__ior__\" and \"__or__\" are incompatible\nclass C:\n    def __or__(self, x: G[S]) -> G[S]: pass\n    def __ior__(self, x: G[S2]) -> G[S2]: pass\n\n[case testGenericOperatorMethodOverlapping2]\nfrom typing import TypeVar, Generic, Tuple\nX = TypeVar('X')\nT = TypeVar('T', int, str)\nT2 = TypeVar('T2', int, str)\nS = TypeVar('S', float, str)\nS2 = TypeVar('S2', float, str)\nclass G(Generic[X]):\n    pass\nclass A:\n    def __or__(self, x: G[T]) -> G[T]: pass\n    def __ior__(self, x: G[T2]) -> G[T2]: pass\nclass B:\n    def __or__(self, x: G[T]) -> G[T]: pass\n    def __ior__(self, x: G[S]) -> G[S]: pass \\\n        # E: Signatures of \"__ior__\" and \"__or__\" are incompatible\nclass C:\n    def __or__(self, x: G[S]) -> G[S]: pass\n    def __ior__(self, x: G[S2]) -> G[S2]: pass\nclass D:\n    def __or__(self, x: G[X]) -> G[X]: pass\n    def __ior__(self, x: G[S2]) -> G[S2]: pass \\\n        # E: Signatures of \"__ior__\" and \"__or__\" are incompatible\n\n[case testConstraintInferenceForAnyAgainstTypeT]\nfrom typing import Type, Any, TypeVar\n\nT = TypeVar('T')\n\ndef f(c: Type[T]) -> T: ...\n\nx: Any\nreveal_type(f(x))  # N: Revealed type is \"Any\"\n\n[case testCallTypeTWithGenericBound]\nfrom typing import Generic, TypeVar, Type\nT = TypeVar('T')\nS = TypeVar('S', bound='A')\n\nclass A(Generic[T]): pass\n\ndef f(cls: Type[S]) -> None:\n    cls()\n\n[case testQualifiedTypeVariableName]\nimport b\ndef f(x: b.T) -> b.T: return x\nreveal_type(f)\nreveal_type(b.g)\n[file b.py]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef g(x: T) -> T: return x\n[out]\nmain:3: note: Revealed type is \"def [b.T] (x: b.T`-1) -> b.T`-1\"\nmain:4: note: Revealed type is \"def [T] (x: T`-1) -> T`-1\"\n\n[case testPartiallyQualifiedTypeVariableName]\nfrom p import b\ndef f(x: b.T) -> b.T: return x\nreveal_type(f)\nreveal_type(b.g)\n[file p/__init__.py]\n[file p/b.py]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef g(x: T) -> T: return x\n[out]\nmain:3: note: Revealed type is \"def [b.T] (x: b.T`-1) -> b.T`-1\"\nmain:4: note: Revealed type is \"def [T] (x: T`-1) -> T`-1\"\n\n[case testGenericClassMethodSimple]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    @classmethod\n    def get(cls) -> T: ...\n\nclass D(C[str]): ...\n\nreveal_type(D.get())  # N: Revealed type is \"builtins.str\"\nreveal_type(D().get())  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassMethodExpansion]\nfrom typing import Generic, TypeVar, Tuple\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    @classmethod\n    def get(cls) -> T: ...\nclass D(C[Tuple[T, T]]): ...\nclass E(D[str]): ...\n\nreveal_type(E.get())  # N: Revealed type is \"tuple[builtins.str, builtins.str]\"\nreveal_type(E().get())  # N: Revealed type is \"tuple[builtins.str, builtins.str]\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassMethodExpansionReplacingTypeVar]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass C(Generic[T]):\n    @classmethod\n    def get(cls) -> T: ...\n\nclass D(C[S]): ...\nclass E(D[int]): ...\n\nreveal_type(E.get())  # N: Revealed type is \"builtins.int\"\nreveal_type(E().get())  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassMethodUnboundOnClass]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    @classmethod\n    def get(cls) -> T: ...\n    @classmethod\n    def make_one(cls, x: T) -> C[T]: ...\n\nreveal_type(C.get)  # N: Revealed type is \"def [T] () -> T`1\"\nreveal_type(C[int].get)  # N: Revealed type is \"def () -> builtins.int\"\nreveal_type(C.make_one)  # N: Revealed type is \"def [T] (x: T`1) -> __main__.C[T`1]\"\nreveal_type(C[int].make_one)  # N: Revealed type is \"def (x: builtins.int) -> __main__.C[builtins.int]\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassMethodUnboundOnSubClass]\nfrom typing import Generic, TypeVar, Tuple\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass C(Generic[T]):\n    @classmethod\n    def get(cls) -> T: ...\n    @classmethod\n    def make_one(cls, x: T) -> C[T]: ...\nclass D(C[Tuple[T, S]]): ...\nclass E(D[S, str]): ...\n\nreveal_type(D.make_one)  # N: Revealed type is \"def [T, S] (x: tuple[T`1, S`2]) -> __main__.C[tuple[T`1, S`2]]\"\nreveal_type(D[int, str].make_one)  # N: Revealed type is \"def (x: tuple[builtins.int, builtins.str]) -> __main__.C[tuple[builtins.int, builtins.str]]\"\nreveal_type(E.make_one)  # N: Revealed type is \"def [S] (x: tuple[S`1, builtins.str]) -> __main__.C[tuple[S`1, builtins.str]]\"\nreveal_type(E[int].make_one)  # N: Revealed type is \"def (x: tuple[builtins.int, builtins.str]) -> __main__.C[tuple[builtins.int, builtins.str]]\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassClsNonGeneric]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    @classmethod\n    def f(cls, x: T) -> T:\n        return x\n\n    @classmethod\n    def other(cls) -> None:\n        reveal_type(C)  # N: Revealed type is \"def [T] () -> __main__.C[T`1]\"\n        reveal_type(C[T])  # N: Revealed type is \"def () -> __main__.C[T`1]\"\n        reveal_type(C.f)  # N: Revealed type is \"def [T] (x: T`1) -> T`1\"\n        reveal_type(C[T].f)  # N: Revealed type is \"def (x: T`1) -> T`1\"\n        reveal_type(cls.f)  # N: Revealed type is \"def (x: T`1) -> T`1\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassUnrelatedVars]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nT2 = TypeVar('T2')\n\nclass C(Generic[T]):\n    @classmethod\n    def f(cls, x: T) -> T:\n        return x\n\n    @classmethod\n    def g(cls, x: T2) -> T2:\n        cls.f(x)  # E: Argument 1 to \"f\" of \"C\" has incompatible type \"T2\"; expected \"T\"\n        return x\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassInGenericFunction]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    def __init__(self, item: T) -> None: ...\n    @classmethod\n    def f(cls, x: T) -> T:\n        return x\n\ndef foo(x: T, y: int) -> T:\n    C(y)  # OK\n    C[T](y)  # E: Argument 1 to \"C\" has incompatible type \"int\"; expected \"T\"\n    C[T].f(y)  # E: Argument 1 to \"f\" of \"C\" has incompatible type \"int\"; expected \"T\"\n    C[T].f(x)  # OK\n    return x\n[builtins fixtures/classmethod.pyi]\n\n# TODO: enable this when #7935 is fixed.\n[case testGenericClassInGenericFunctionOverloadedConstructor-skip]\nfrom typing import TypeVar, Generic, overload\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    @overload\n    def __new__(cls) -> C[None]: ...\n    @overload\n    def __new__(cls, item: T) -> C[T]: ...\n    def __new__(cls, item=None):\n        ...\n    @classmethod\n    def f(cls, x: T) -> T:\n        return x\n\ndef foo(x: T, y: int) -> T:\n    C.f(y)\n    C(y)  # OK\n    C[T](y)  # E: Argument 1 to \"C\" has incompatible type \"int\"; expected \"T\"\n    C[T].f(y)  # E: Argument 1 to \"f\" of \"C\" has incompatible type \"int\"; expected \"T\"\n    C[T].f(x)  # OK\n    return x\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassDirectCall]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    def __init__(self, item: T) -> None: ...\n    @classmethod\n    def f(cls) -> None:\n        cls(1)  # E: Argument 1 to \"C\" has incompatible type \"int\"; expected \"T\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassAlternativeConstructorPrecise]\nfrom typing import Generic, TypeVar, Type, Tuple\n\nT = TypeVar('T')\n\nclass Base(Generic[T]):\n    Q = TypeVar('Q', bound=Base[T])\n\n    def __init__(self, item: T) -> None: ...\n\n    @classmethod\n    def make_pair(cls: Type[Q], item: T) -> Tuple[Q, Q]:\n        if bool():\n            return cls(0), cls(0)  # E: Argument 1 to \"Base\" has incompatible type \"int\"; expected \"T\"\n        return cls(item), cls(item)\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassAlternativeConstructorPreciseOverloaded]\nfrom typing import Generic, TypeVar, Type, Tuple, overload, Union\n\nT = TypeVar('T')\n\nclass Base(Generic[T]):\n    Q = TypeVar('Q', bound=Base[T])\n\n    def __init__(self, item: T) -> None: ...\n\n    @overload\n    @classmethod\n    def make_some(cls: Type[Q], item: T) -> Q: ...\n\n    @overload\n    @classmethod\n    def make_some(cls: Type[Q], item: T, n: int) -> Tuple[Q, ...]: ...\n\n    @classmethod\n    def make_some(cls: Type[Q], item: T, n: int = 0) -> Union[Q, Tuple[Q, ...]]:\n        if n:\n            return (cls(item),)\n        return cls(item)\n\nreveal_type(Base.make_some)  # N: Revealed type is \"Overload(def [T] (item: T`1) -> __main__.Base[T`1], def [T] (item: T`1, n: builtins.int) -> builtins.tuple[__main__.Base[T`1], ...])\"\nreveal_type(Base.make_some(1))  # N: Revealed type is \"__main__.Base[builtins.int]\"\nreveal_type(Base.make_some(1, 1))  # N: Revealed type is \"builtins.tuple[__main__.Base[builtins.int], ...]\"\n\nclass Sub(Base[str]): ...\nSub.make_some(1)  # E: No overload variant of \"make_some\" of \"Base\" matches argument type \"int\" \\\n                  # N: Possible overload variants: \\\n                  # N:     def make_some(cls, item: str) -> Sub \\\n                  # N:     def make_some(cls, item: str, n: int) -> tuple[Sub, ...]\n[builtins fixtures/classmethod.pyi]\n\n[case testNoGenericAccessOnImplicitAttributes]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    def __init__(self, x: T) -> None:\n        self.x = x\n\n    @classmethod\n    def meth(cls) -> None:\n        cls.x  # E: Cannot access instance-only attribute \"x\" on class object \\\n               # E: Access to generic instance variables via class is ambiguous\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassMethodUnboundOnClassNonMatchingIdNonGeneric]\nfrom typing import Generic, TypeVar, Any, Tuple, Type\n\nT = TypeVar('T')\nS = TypeVar('S')\nQ = TypeVar('Q', bound='A[Any]')\n\nclass A(Generic[T]):\n    @classmethod\n    def foo(cls: Type[Q]) -> Tuple[T, Q]: ...\n\nclass B(A[T], Generic[T, S]):\n    def meth(self) -> None:\n        reveal_type(A[T].foo)  # N: Revealed type is \"def () -> tuple[T`1, __main__.A[T`1]]\"\n    @classmethod\n    def other(cls) -> None:\n        reveal_type(cls.foo)  # N: Revealed type is \"def () -> tuple[T`1, __main__.B[T`1, S`2]]\"\nreveal_type(B.foo)  # N: Revealed type is \"def [T, S] () -> tuple[T`1, __main__.B[T`1, S`2]]\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassAlternativeConstructorPrecise2]\nfrom typing import Generic, TypeVar, Type, Tuple, Any\n\nT = TypeVar('T')\nQ = TypeVar('Q')\n\nclass Base(Generic[T]):\n    def __init__(self, item: T) -> None: ...\n    @classmethod\n    def make_pair(cls: Type[Q], item: T) -> Tuple[Q, Q]: ...\nclass Sub(Base[T]):\n    ...\n\nreveal_type(Sub.make_pair('yes'))  # N: Revealed type is \"tuple[__main__.Sub[builtins.str], __main__.Sub[builtins.str]]\"\nSub[int].make_pair('no')  # E: Argument 1 to \"make_pair\" of \"Base\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassAttrUnboundOnClass]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    x: T\n    @classmethod\n    def get(cls) -> T:\n        return cls.x  # OK\n\nx = C.x  # E: Access to generic instance variables via class is ambiguous\nreveal_type(x)  # N: Revealed type is \"Any\"\nxi = C[int].x  # E: Access to generic instance variables via class is ambiguous\nreveal_type(xi)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassAttrUnboundOnSubClass]\nfrom typing import Generic, TypeVar, Tuple\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    x: T\nclass D(C[int]): ...\nclass E(C[int]):\n    x = 42\n\nx = D.x  # E: Access to generic instance variables via class is ambiguous\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\nE.x  # OK\n\n[case testGenericClassMethodOverloaded]\nfrom typing import Generic, TypeVar, overload, Tuple\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    @overload\n    @classmethod\n    def get(cls) -> T: ...\n    @overload\n    @classmethod\n    def get(cls, n: int) -> Tuple[T, ...]: ...\n    @classmethod\n    def get(cls, n: int = 0):\n        pass\n\nclass D(C[str]): ...\n\nreveal_type(D.get())  # N: Revealed type is \"builtins.str\"\nreveal_type(D.get(42))  # N: Revealed type is \"builtins.tuple[builtins.str, ...]\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassMethodAnnotation]\nfrom typing import Generic, TypeVar, Type\nT = TypeVar('T')\n\nclass Maker(Generic[T]):\n    x: T\n    @classmethod\n    def get(cls) -> T: ...\n\nclass B(Maker[B]): ...\n\ndef f(o: Maker[T]) -> T:\n    if bool():\n        return o.x\n    return o.get()\nb = f(B())\nreveal_type(b)  # N: Revealed type is \"__main__.B\"\n\ndef g(t: Type[Maker[T]]) -> T:\n    if bool():\n        return t.x\n    return t.get()\nbb = g(B)\nreveal_type(bb)  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassMethodAnnotationDecorator]\nfrom typing import Generic, Callable, TypeVar, Iterator\n\nT = TypeVar('T')\n\nclass Box(Generic[T]):\n    @classmethod\n    def wrap(cls, generator: Callable[[], T]) -> Box[T]: ...\n\nclass IteratorBox(Box[Iterator[T]]): ...\n\n@IteratorBox.wrap  # E: Argument 1 to \"wrap\" of \"Box\" has incompatible type \"Callable[[], int]\"; expected \"Callable[[], Iterator[Never]]\"\ndef g() -> int:\n    ...\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericClassMethodInGenericFunction]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass C(Generic[T]):\n    @classmethod\n    def get(cls) -> T: ...\n\ndef func(x: S) -> S:\n    return C[S].get()\n[builtins fixtures/classmethod.pyi]\n\n[case testGenericStaticMethodInGenericFunction]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass C(Generic[T]):\n    @staticmethod\n    def get() -> T: ...\n\ndef func(x: S) -> S:\n    return C[S].get()\n[builtins fixtures/staticmethod.pyi]\n\n[case testMultipleAssignmentFromAnyIterable]\nfrom typing import Any\nclass A:\n    def __iter__(self) -> Any: ...\n\nx, y = A()\nreveal_type(x)  # N: Revealed type is \"Any\"\nreveal_type(y)  # N: Revealed type is \"Any\"\n\n[case testSubclassingGenericSelfClassMethod]\nfrom typing import TypeVar, Type\n\nAT = TypeVar('AT', bound='A')\n\nclass A:\n    @classmethod\n    def from_config(cls: Type[AT]) -> AT:\n        ...\n\nclass B(A):\n    @classmethod\n    def from_config(cls: Type[B]) -> B:\n        return B()\n[builtins fixtures/classmethod.pyi]\n\n[case testSubclassingGenericSelfClassMethodOptional]\nfrom typing import TypeVar, Type, Optional\n\nAT = TypeVar('AT', bound='A')\n\nclass A:\n    @classmethod\n    def from_config(cls: Type[AT]) -> Optional[AT]:\n        return None\n\nclass B(A):\n    @classmethod\n    def from_config(cls: Type[B]) -> Optional[B]:\n        return B()\n[builtins fixtures/classmethod.pyi]\n\n[case testSubclassingGenericSelfClassMethodNonAnnotated]\nfrom typing import TypeVar, Type\n\nAT = TypeVar('AT', bound='A')\n\nclass A:\n    @classmethod\n    def from_config(cls: Type[AT]) -> AT:\n        ...\n\nclass B(A):\n    @classmethod\n    def from_config(cls) -> B:\n        return B()\n[builtins fixtures/classmethod.pyi]\n\n[case testAbstractGenericMethodInference]\nfrom abc import ABC, abstractmethod\nfrom typing import Callable, Generic, TypeVar\n\nA = TypeVar('A')\nB = TypeVar('B')\nC = TypeVar('C')\n\nclass TwoTypes(Generic[A, B]):\n\n  def __call__(self) -> B: pass\n\nclass MakeTwoAbstract(ABC, Generic[A]):\n\n  def __init__(self) -> None: pass\n\n  @abstractmethod\n  def __call__(self, b: B) -> TwoTypes[A, B]: pass\n\nclass MakeTwoConcrete(Generic[A]):\n\n  def __call__(self, b: B) -> TwoTypes[A, B]: pass\n\n\nclass MakeTwoGenericSubAbstract(Generic[C], MakeTwoAbstract[C]):\n\n  def __call__(self, b: B) -> TwoTypes[C, B]: pass\n\nclass MakeTwoAppliedSubAbstract(MakeTwoAbstract[str]):\n\n  def __call__(self, b: B) -> TwoTypes[str, B]: pass\n\nclass Test():\n\n  def make_two(self,\n                mts: MakeTwoAbstract[A],\n                mte: MakeTwoConcrete[A],\n                mtgsa: MakeTwoGenericSubAbstract[A],\n                mtasa: MakeTwoAppliedSubAbstract) -> None:\n    reveal_type(mts(2)) # N: Revealed type is \"__main__.TwoTypes[A`-1, builtins.int]\"\n    reveal_type(mte(2)) # N: Revealed type is \"__main__.TwoTypes[A`-1, builtins.int]\"\n    reveal_type(mtgsa(2)) # N: Revealed type is \"__main__.TwoTypes[A`-1, builtins.int]\"\n    reveal_type(mtasa(2)) # N: Revealed type is \"__main__.TwoTypes[builtins.str, builtins.int]\"\n    reveal_type(MakeTwoConcrete[int]()('foo')) # N: Revealed type is \"__main__.TwoTypes[builtins.int, builtins.str]\"\n    reveal_type(MakeTwoConcrete[str]()(2)) # N: Revealed type is \"__main__.TwoTypes[builtins.str, builtins.int]\"\n    reveal_type(MakeTwoAppliedSubAbstract()('foo')) # N: Revealed type is \"__main__.TwoTypes[builtins.str, builtins.str]\"\n    reveal_type(MakeTwoAppliedSubAbstract()(2)) # N: Revealed type is \"__main__.TwoTypes[builtins.str, builtins.int]\"\n    reveal_type(MakeTwoGenericSubAbstract[str]()('foo')) # N: Revealed type is \"__main__.TwoTypes[builtins.str, builtins.str]\"\n    reveal_type(MakeTwoGenericSubAbstract[str]()(2)) # N: Revealed type is \"__main__.TwoTypes[builtins.str, builtins.int]\"\n\n[case testGenericClassPropertyBound]\nfrom typing import Generic, TypeVar, Callable, Type, List, Dict\n\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef classproperty(f: Callable[..., U]) -> U: ...\n\nclass C(Generic[T]):\n    @classproperty\n    def test(self) -> T: ...\n\nclass D(C[str]): ...\nclass E1(C[T], Generic[T, U]): ...\nclass E2(C[U], Generic[T, U]): ...\nclass G(C[List[T]]): ...\n\nx: C[int]\ny: Type[C[int]]\nreveal_type(x.test)  # N: Revealed type is \"builtins.int\"\nreveal_type(y.test)  # N: Revealed type is \"builtins.int\"\n\nxd: D\nyd: Type[D]\nreveal_type(xd.test)  # N: Revealed type is \"builtins.str\"\nreveal_type(yd.test)  # N: Revealed type is \"builtins.str\"\n\nye1: Type[E1[int, str]]\nye2: Type[E2[int, str]]\nreveal_type(ye1.test)  # N: Revealed type is \"builtins.int\"\nreveal_type(ye2.test)  # N: Revealed type is \"builtins.str\"\n\nxg: G[int]\nyg: Type[G[int]]\nreveal_type(xg.test)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(yg.test)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nclass Sup:\n    attr: int\nS = TypeVar('S', bound=Sup)\n\ndef func(tp: Type[C[S]]) -> S:\n    reveal_type(tp.test.attr)  # N: Revealed type is \"builtins.int\"\n\n    reg: Dict[S, G[S]]\n    reveal_type(reg[tp.test])  # N: Revealed type is \"__main__.G[S`-1]\"\n    reveal_type(reg[tp.test].test)  # N: Revealed type is \"builtins.list[S`-1]\"\n\n    if bool():\n        return tp.test\n    else:\n        return reg[tp.test].test[0]\n[builtins fixtures/dict.pyi]\n\n[case testGenericFunctionAliasExpand]\nfrom typing import Optional, TypeVar\n\nT = TypeVar(\"T\")\ndef gen(x: T) -> T: ...\ngen_a = gen\n\nS = TypeVar(\"S\", int, str)\nclass C: ...\ndef test() -> Optional[S]:\n    reveal_type(gen_a(C()))  # N: Revealed type is \"__main__.C\"\n    return None\n\n[case testGenericFunctionMemberExpand]\nfrom typing import Optional, TypeVar, Callable\n\nT = TypeVar(\"T\")\n\nclass A:\n    def __init__(self) -> None:\n        self.gen: Callable[[T], T]\n\nS = TypeVar(\"S\", int, str)\nclass C: ...\ndef test() -> Optional[S]:\n    reveal_type(A().gen(C()))  # N: Revealed type is \"__main__.C\"\n    return None\n\n[case testGenericJoinCovariant]\nfrom typing import Generic, TypeVar, List\n\nT = TypeVar(\"T\", covariant=True)\n\nclass Container(Generic[T]): ...\nclass Base: ...\nclass A(Base): ...\nclass B(Base): ...\n\na: A\nb: B\n\na_c: Container[A]\nb_c: Container[B]\n\nreveal_type([a, b])  # N: Revealed type is \"builtins.list[__main__.Base]\"\nreveal_type([a_c, b_c])  # N: Revealed type is \"builtins.list[__main__.Container[__main__.Base]]\"\n[builtins fixtures/list.pyi]\n\n[case testGenericJoinContravariant]\nfrom typing import Generic, TypeVar, List\n\nT = TypeVar(\"T\", contravariant=True)\n\nclass Container(Generic[T]): ...\nclass A: ...\nclass B(A): ...\n\na_c: Container[A]\nb_c: Container[B]\n\n# TODO: this can be more precise than \"object\", see a comment in mypy/join.py\nreveal_type([a_c, b_c])  # N: Revealed type is \"builtins.list[builtins.object]\"\n[builtins fixtures/list.pyi]\n\n[case testGenericJoinRecursiveTypes]\nfrom typing import Sequence, TypeVar\n\nclass A(Sequence[A]): ...\nclass B(Sequence[B]): ...\n\na: A\nb: B\n\nreveal_type([a, b])  # N: Revealed type is \"builtins.list[typing.Sequence[builtins.object]]\"\n[builtins fixtures/list.pyi]\n\n[case testGenericJoinRecursiveInvariant]\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\nclass I(Generic[T]): ...\n\nclass A(I[A]): ...\nclass B(I[B]): ...\n\na: A\nb: B\nreveal_type([a, b])  # N: Revealed type is \"builtins.list[builtins.object]\"\n[builtins fixtures/list.pyi]\n\n[case testGenericJoinNestedInvariantAny]\nfrom typing import Any, Generic, TypeVar\n\nT = TypeVar(\"T\")\nclass I(Generic[T]): ...\n\na: I[I[int]]\nb: I[I[Any]]\nreveal_type([a, b])  # N: Revealed type is \"builtins.list[__main__.I[__main__.I[Any]]]\"\nreveal_type([b, a])  # N: Revealed type is \"builtins.list[__main__.I[__main__.I[Any]]]\"\n[builtins fixtures/list.pyi]\n\n[case testOverlappingTypeVarIds]\nfrom typing import TypeVar, Generic\n\nclass A: ...\nclass B: ...\n\nT = TypeVar(\"T\", bound=A)\nV = TypeVar(\"V\", bound=B)\nS = TypeVar(\"S\")\n\nclass Whatever(Generic[T]):\n    def something(self: S) -> S:\n        return self\n\n# the \"V\" here had the same id as \"T\" and so mypy used to think it could expand one into another.\n# this test is here to make sure that doesn't happen!\nclass WhateverPartTwo(Whatever[A], Generic[V]):\n    def something(self: S) -> S:\n        return self\n\n\n[case testConstrainedGenericSuper]\nfrom typing import Generic, TypeVar\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\nclass Foo(Generic[AnyStr]):\n    def method1(self, s: AnyStr, t: AnyStr) -> None: ...\n\nclass Bar(Foo[AnyStr]):\n    def method1(self, s: AnyStr, t: AnyStr) -> None:\n        super().method1('x', b'y')  # Should be an error\n[out]\nmain:10: error: Argument 1 to \"method1\" of \"Foo\" has incompatible type \"str\"; expected \"AnyStr\"\nmain:10: error: Argument 2 to \"method1\" of \"Foo\" has incompatible type \"bytes\"; expected \"AnyStr\"\n\n[case testTypeVariableClashVar]\nfrom typing import Generic, TypeVar, Callable\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\nclass C(Generic[R]):\n    x: Callable[[T], R]\n\ndef func(x: C[R]) -> R:\n    return x.x(42)  # OK\n\n[case testTypeVariableClashVarTuple]\nfrom typing import Generic, TypeVar, Callable, Tuple\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\nclass C(Generic[R]):\n    x: Callable[[T], Tuple[R, T]]\n\ndef func(x: C[R]) -> R:\n    if bool():\n        return x.x(42)[0]  # OK\n    else:\n        return x.x(42)[1]  # E: Incompatible return value type (got \"int\", expected \"R\")\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVariableClashMethod]\nfrom typing import Generic, TypeVar, Callable\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\nclass C(Generic[R]):\n    def x(self) -> Callable[[T], R]: ...\n\ndef func(x: C[R]) -> R:\n    return x.x()(42)  # OK\n\n[case testTypeVariableClashMethodTuple]\nfrom typing import Generic, TypeVar, Callable, Tuple\n\nT = TypeVar(\"T\")\nR = TypeVar(\"R\")\nclass C(Generic[R]):\n    def x(self) -> Callable[[T], Tuple[R, T]]: ...\n\ndef func(x: C[R]) -> R:\n    if bool():\n        return x.x()(42)[0]  # OK\n    else:\n        return x.x()(42)[1]  # E: Incompatible return value type (got \"int\", expected \"R\")\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVariableClashVarSelf]\nfrom typing import Self, TypeVar, Generic, Callable\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nclass C(Generic[T]):\n    x: Callable[[S], Self]\n    y: T\n\ndef foo(x: C[T]) -> T:\n    return x.x(42).y  # OK\n\n[case testNestedGenericFunctionTypeApplication]\nfrom typing import TypeVar, Generic, List\n\nA = TypeVar(\"A\")\nB = TypeVar(\"B\")\n\nclass C(Generic[A]):\n    x: A\n\ndef foo(x: A) -> A:\n    def bar() -> List[A]:\n        y = C[List[A]]()\n        z = C[List[B]]()  # E: Type variable \"__main__.B\" is unbound \\\n                # N: (Hint: Use \"Generic[B]\" or \"Protocol[B]\" base class to bind \"B\" inside a class) \\\n                # N: (Hint: Use \"B\" in function signature to bind \"B\" inside a function)\n        return y.x\n    return bar()[0]\n\n\n-- TypeVar imported from typing_extensions\n-- ---------------------------------------\n\n[case testTypeVarTypingExtensionsSimpleGeneric]\nfrom typing import Generic\nfrom typing_extensions import TypeVar\n\nT = TypeVar(\"T\")\n\nclass A(Generic[T]):\n    def __init__(self, value: T) -> None:\n        self.value = value\n\na: A = A(8)\nb: A[str] = A(\"\")\n\nreveal_type(A(1.23))  # N: Revealed type is \"__main__.A[builtins.float]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTypingExtensionsSimpleBound]\nfrom typing_extensions import TypeVar\n\nT= TypeVar(\"T\")\n\ndef func(var: T) -> T:\n    return var\n\nreveal_type(func(1))  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testGenericLambdaGenericMethodNoCrash]\nfrom typing import TypeVar, Union, Callable, Generic\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\ndef f(x: Callable[[G[T]], int]) -> T: ...\n\nclass G(Generic[T]):\n    def g(self, x: S) -> Union[S, T]: ...\n\nreveal_type(f(lambda x: x.g(0)))  # N: Revealed type is \"builtins.int\"\n\n[case testDictStarInference]\nclass B: ...\nclass C1(B): ...\nclass C2(B): ...\n\ndict1 = {\"a\": C1()}\ndict2 = {\"a\": C2(), **dict1}\nreveal_type(dict2)  # N: Revealed type is \"builtins.dict[builtins.str, __main__.B]\"\n[builtins fixtures/dict.pyi]\n\n[case testDictStarAnyKeyJoinValue]\nfrom typing import Any\n\nclass B: ...\nclass C1(B): ...\nclass C2(B): ...\n\ndict1: Any\ndict2 = {\"a\": C1(), **{x: C2() for x in dict1}}\nreveal_type(dict2)  # N: Revealed type is \"builtins.dict[Any, __main__.B]\"\n[builtins fixtures/dict.pyi]\n\n-- Type inference for generic decorators applied to generic callables\n-- ------------------------------------------------------------------\n\n[case testInferenceAgainstGenericCallable]\nfrom typing import TypeVar, Callable, List\n\nX = TypeVar('X')\nT = TypeVar('T')\n\ndef foo(x: Callable[[int], X]) -> List[X]:\n    ...\ndef bar(x: Callable[[X], int]) -> List[X]:\n    ...\n\ndef id(x: T) -> T:\n    ...\nreveal_type(foo(id))  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(bar(id))  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallableNoLeak]\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\n\ndef f(x: Callable[..., T]) -> T:\n    return x()\n\ndef tpl(x: T) -> T:\n    return x\n\n# This is valid because of \"...\"\nreveal_type(f(tpl))  # N: Revealed type is \"Any\"\n[out]\n\n[case testInferenceAgainstGenericCallableChain]\nfrom typing import TypeVar, Callable, List\n\nX = TypeVar('X')\nT = TypeVar('T')\n\ndef chain(f: Callable[[X], T], g: Callable[[T], int]) -> Callable[[X], int]: ...\ndef id(x: T) -> T:\n    ...\nreveal_type(chain(id, id))  # N: Revealed type is \"def (builtins.int) -> builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallableGeneric]\nfrom typing import TypeVar, Callable, List\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef dec(f: Callable[[S], T]) -> Callable[[S], List[T]]:\n    ...\ndef id(x: U) -> U:\n    ...\nreveal_type(dec(id))  # N: Revealed type is \"def [S] (S`1) -> builtins.list[S`1]\"\n\n@dec\ndef same(x: U) -> U:\n    ...\nreveal_type(same)  # N: Revealed type is \"def [S] (S`3) -> builtins.list[S`3]\"\nreveal_type(same(42))  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallableGenericReverse]\nfrom typing import TypeVar, Callable, List\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef dec(f: Callable[[S], List[T]]) -> Callable[[S], T]:\n    ...\ndef id(x: U) -> U:\n    ...\nreveal_type(dec(id))  # N: Revealed type is \"def [T] (builtins.list[T`2]) -> T`2\"\n\n@dec\ndef same(x: U) -> U:\n    ...\nreveal_type(same)  # N: Revealed type is \"def [T] (builtins.list[T`4]) -> T`4\"\nreveal_type(same([42]))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallableGenericArg]\nfrom typing import TypeVar, Callable, List\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef dec(f: Callable[[S], T]) -> Callable[[S], T]:\n    ...\ndef test(x: U) -> List[U]:\n    ...\nreveal_type(dec(test))  # N: Revealed type is \"def [S] (S`1) -> builtins.list[S`1]\"\n\n@dec\ndef single(x: U) -> List[U]:\n    ...\nreveal_type(single)  # N: Revealed type is \"def [S] (S`3) -> builtins.list[S`3]\"\nreveal_type(single(42))  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallableGenericChain]\nfrom typing import TypeVar, Callable, List\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef comb(f: Callable[[T], S], g: Callable[[S], U]) -> Callable[[T], U]: ...\ndef id(x: U) -> U:\n    ...\nreveal_type(comb(id, id))  # N: Revealed type is \"def [T] (T`1) -> T`1\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallableGenericNonLinear]\nfrom typing import TypeVar, Callable, List\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef mix(fs: List[Callable[[S], T]]) -> Callable[[S], List[T]]:\n    def inner(x: S) -> List[T]:\n        return [f(x) for f in fs]\n    return inner\n\n# Errors caused by arg *name* mismatch are truly cryptic, but this is a known issue :/\ndef id(__x: U) -> U:\n    ...\nfs = [id, id, id]\nreveal_type(mix(fs))  # N: Revealed type is \"def [S] (S`2) -> builtins.list[S`2]\"\nreveal_type(mix([id, id, id]))  # N: Revealed type is \"def [S] (S`4) -> builtins.list[S`4]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCurry]\nfrom typing import Callable, List, TypeVar\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\nV = TypeVar(\"V\")\n\ndef dec1(f: Callable[[T], S]) -> Callable[[], Callable[[T], S]]: ...\ndef dec2(f: Callable[[T, U], S]) -> Callable[[U], Callable[[T], S]]: ...\n\ndef test1(x: V) -> V: ...\ndef test2(x: V, y: V) -> V: ...\n\nreveal_type(dec1(test1))  # N: Revealed type is \"def () -> def [T] (T`1) -> T`1\"\nreveal_type(dec2(test2))  # N: Revealed type is \"def [T] (T`3) -> def (T`3) -> T`3\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallableNewVariable]\nfrom typing import TypeVar, Callable, List\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef dec(f: Callable[[S], T]) -> Callable[[S], T]:\n    ...\ndef test(x: List[U]) -> List[U]:\n    ...\nreveal_type(dec(test))  # N: Revealed type is \"def [U] (builtins.list[U`-1]) -> builtins.list[U`-1]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallableGenericAlias]\nfrom typing import TypeVar, Callable, List\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\n\nA = Callable[[S], T]\nB = Callable[[S], List[T]]\n\ndef dec(f: A[S, T]) -> B[S, T]:\n    ...\ndef id(x: U) -> U:\n    ...\nreveal_type(dec(id))  # N: Revealed type is \"def [S] (S`1) -> builtins.list[S`1]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallableGenericProtocol]\nfrom typing import TypeVar, Protocol, Generic, Optional\n\nT = TypeVar('T')\n\nclass F(Protocol[T]):\n    def __call__(self, __x: T) -> T: ...\n\ndef lift(f: F[T]) -> F[Optional[T]]: ...\ndef g(x: T) -> T:\n    return x\n\nreveal_type(lift(g))  # N: Revealed type is \"def [T] (T`1 | None) -> T`1 | None\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericSplitOrder]\nfrom typing import TypeVar, Callable, List\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef dec(f: Callable[[T], S], g: Callable[[T], int]) -> Callable[[T], List[S]]: ...\ndef id(x: U) -> U:\n    ...\n\nreveal_type(dec(id, id))  # N: Revealed type is \"def (builtins.int) -> builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericSplitOrderGeneric]\nfrom typing import TypeVar, Callable, Tuple\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\nV = TypeVar('V')\n\ndef dec(f: Callable[[T], S], g: Callable[[T], U]) -> Callable[[T], Tuple[S, U]]: ...\ndef id(x: V) -> V:\n    ...\n\nreveal_type(dec(id, id))  # N: Revealed type is \"def [T] (T`1) -> tuple[T`1, T`1]\"\n[builtins fixtures/tuple.pyi]\n\n[case testInferenceAgainstGenericSecondary]\nfrom typing import TypeVar, Callable, List\n\nS = TypeVar('S')\nT = TypeVar('T')\nU = TypeVar('U')\n\ndef dec(f: Callable[[List[T]], List[int]]) -> Callable[[T], T]: ...\n\n@dec\ndef id(x: U) -> U:\n    ...\nreveal_type(id)  # N: Revealed type is \"def (builtins.int) -> builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testInferenceAgainstGenericEllipsisSelfSpecialCase]\nfrom typing import Self, Callable, TypeVar\n\nT = TypeVar(\"T\")\ndef dec(f: Callable[..., T]) -> Callable[..., T]: ...\n\nclass C:\n    @dec\n    def test(self) -> Self: ...\n\nc: C\nreveal_type(c.test())  # N: Revealed type is \"__main__.C\"\n\n[case testInferenceAgainstGenericBoundsAndValues]\nfrom typing import TypeVar, Callable, List\n\nclass B: ...\nclass C(B): ...\n\nS = TypeVar('S')\nT = TypeVar('T')\nUB = TypeVar('UB', bound=B)\nUC = TypeVar('UC', bound=C)\nV = TypeVar('V', int, str)\n\ndef dec1(f: Callable[[S], T]) -> Callable[[S], List[T]]:\n    ...\ndef dec2(f: Callable[[UC], T]) -> Callable[[UC], List[T]]:\n    ...\ndef id1(x: UB) -> UB:\n    ...\ndef id2(x: V) -> V:\n    ...\n\nreveal_type(dec1(id1))  # N: Revealed type is \"def [S <: __main__.B] (S`1) -> builtins.list[S`1]\"\nreveal_type(dec1(id2))  # N: Revealed type is \"def [S in (builtins.int, builtins.str)] (S`3) -> builtins.list[S`3]\"\nreveal_type(dec2(id1))  # N: Revealed type is \"def [UC <: __main__.C] (UC`5) -> builtins.list[UC`5]\"\nreveal_type(dec2(id2))  # N: Revealed type is \"def (Never) -> builtins.list[Never]\" \\\n                        # E: Argument 1 to \"dec2\" has incompatible type \"Callable[[V], V]\"; expected \"Callable[[Never], Never]\"\n\n[case testInferenceAgainstGenericLambdas]\nfrom typing import TypeVar, Callable, List\n\nS = TypeVar('S')\nT = TypeVar('T')\n\ndef dec1(f: Callable[[T], T]) -> Callable[[T], List[T]]:\n    ...\ndef dec2(f: Callable[[S], T]) -> Callable[[S], List[T]]:\n    ...\ndef dec3(f: Callable[[List[S]], T]) -> Callable[[S], T]:\n    def g(x: S) -> T:\n        return f([x])\n    return g\ndef dec4(f: Callable[[S], List[T]]) -> Callable[[S], T]:\n    ...\ndef dec5(f: Callable[[int], T]) -> Callable[[int], List[T]]:\n    def g(x: int) -> List[T]:\n        return [f(x)] * x\n    return g\n\nI = TypeVar(\"I\", bound=int)\ndef dec4_bound(f: Callable[[I], List[T]]) -> Callable[[I], T]:\n    ...\n\nreveal_type(dec1(lambda x: x))  # N: Revealed type is \"def [T] (T`3) -> builtins.list[T`3]\"\nreveal_type(dec2(lambda x: x))  # N: Revealed type is \"def [S] (S`5) -> builtins.list[S`5]\"\nreveal_type(dec3(lambda x: x[0]))  # N: Revealed type is \"def [S] (S`8) -> S`8\"\nreveal_type(dec4(lambda x: [x]))  # N: Revealed type is \"def [S] (S`11) -> S`11\"\nreveal_type(dec1(lambda x: 1))  # N: Revealed type is \"def (builtins.int) -> builtins.list[builtins.int]\"\nreveal_type(dec5(lambda x: x))  # N: Revealed type is \"def (builtins.int) -> builtins.list[builtins.int]\"\nreveal_type(dec3(lambda x: x))  # N: Revealed type is \"def [S] (S`19) -> builtins.list[S`19]\"\nreveal_type(dec4(lambda x: x))  # N: Revealed type is \"def [T] (builtins.list[T`23]) -> T`23\"\ndec4_bound(lambda x: x)  # E: Value of type variable \"I\" of \"dec4_bound\" cannot be \"list[T]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericParamSpecBasicInList]\nfrom typing import TypeVar, Callable, List, Tuple\nfrom typing_extensions import ParamSpec\n\nT = TypeVar('T')\nP = ParamSpec('P')\nU = TypeVar('U')\nV = TypeVar('V')\n\ndef dec(f: Callable[P, T]) -> Callable[P, List[T]]: ...\ndef id(x: U) -> U: ...\ndef either(x: U, y: U) -> U: ...\ndef pair(x: U, y: V) -> Tuple[U, V]: ...\nreveal_type(dec(id))  # N: Revealed type is \"def [T] (x: T`3) -> builtins.list[T`3]\"\nreveal_type(dec(either))  # N: Revealed type is \"def [T] (x: T`5, y: T`5) -> builtins.list[T`5]\"\nreveal_type(dec(pair))  # N: Revealed type is \"def [U, V] (x: U`-1, y: V`-2) -> builtins.list[tuple[U`-1, V`-2]]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericParamSpecBasicDeList]\nfrom typing import TypeVar, Callable, List, Tuple\nfrom typing_extensions import ParamSpec\n\nT = TypeVar('T')\nP = ParamSpec('P')\nU = TypeVar('U')\nV = TypeVar('V')\n\ndef dec(f: Callable[P, List[T]]) -> Callable[P, T]: ...\ndef id(x: U) -> U: ...\ndef either(x: U, y: U) -> U: ...\nreveal_type(dec(id))  # N: Revealed type is \"def [T] (x: builtins.list[T`3]) -> T`3\"\nreveal_type(dec(either))  # N: Revealed type is \"def [T] (x: builtins.list[T`5], y: builtins.list[T`5]) -> T`5\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericParamSpecPopOff]\nfrom typing import TypeVar, Callable, List, Tuple\nfrom typing_extensions import ParamSpec, Concatenate\n\nT = TypeVar('T')\nS = TypeVar('S')\nP = ParamSpec('P')\nU = TypeVar('U')\nV = TypeVar('V')\n\ndef dec(f: Callable[Concatenate[T, P], S]) -> Callable[P, Callable[[T], S]]: ...\ndef id(x: U) -> U: ...\ndef either(x: U, y: U) -> U: ...\ndef pair(x: U, y: V) -> Tuple[U, V]: ...\nreveal_type(dec(id))  # N: Revealed type is \"def () -> def [T] (T`2) -> T`2\"\nreveal_type(dec(either))  # N: Revealed type is \"def [T] (y: T`5) -> def (T`5) -> T`5\"\nreveal_type(dec(pair))  # N: Revealed type is \"def [V] (y: V`-2) -> def [T] (T`8) -> tuple[T`8, V`-2]\"\nreveal_type(dec(dec))  # N: Revealed type is \"def () -> def [T, P, S] (def (T`-1, *P.args, **P.kwargs) -> S`-3) -> def (*P.args, **P.kwargs) -> def (T`-1) -> S`-3\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericParamSpecPopOn]\nfrom typing import TypeVar, Callable, List, Tuple\nfrom typing_extensions import ParamSpec, Concatenate\n\nT = TypeVar('T')\nS = TypeVar('S')\nP = ParamSpec('P')\nU = TypeVar('U')\nV = TypeVar('V')\n\ndef dec(f: Callable[P, Callable[[T], S]]) -> Callable[Concatenate[T, P], S]: ...\ndef id() -> Callable[[U], U]: ...\ndef either(x: U) -> Callable[[U], U]: ...\ndef pair(x: U) -> Callable[[V], Tuple[V, U]]: ...\nreveal_type(dec(id))  # N: Revealed type is \"def [T] (T`3) -> T`3\"\nreveal_type(dec(either))  # N: Revealed type is \"def [T] (T`6, x: T`6) -> T`6\"\nreveal_type(dec(pair))  # N: Revealed type is \"def [T, U] (T`9, x: U`-1) -> tuple[T`9, U`-1]\"\n# This is counter-intuitive but looks correct, dec matches itself only if P can be empty\nreveal_type(dec(dec))  # N: Revealed type is \"def [T, S] (T`13, f: def () -> def (T`13) -> S`14) -> S`14\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericParamSpecVsParamSpec]\nfrom typing import TypeVar, Callable, List, Tuple, Generic\nfrom typing_extensions import ParamSpec, Concatenate\n\nT = TypeVar('T')\nP = ParamSpec('P')\nQ = ParamSpec('Q')\n\nclass Foo(Generic[P]): ...\nclass Bar(Generic[P, T]): ...\n\ndef dec(f: Callable[P, T]) -> Callable[P, List[T]]: ...\ndef f(*args: Q.args, **kwargs: Q.kwargs) -> Foo[Q]: ...\nreveal_type(dec(f))  # N: Revealed type is \"def [P] (*P.args, **P.kwargs) -> builtins.list[__main__.Foo[P`2]]\"\ng: Callable[Concatenate[int, Q], Foo[Q]]\nreveal_type(dec(g))  # N: Revealed type is \"def [Q] (builtins.int, *Q.args, **Q.kwargs) -> builtins.list[__main__.Foo[Q`-1]]\"\nh: Callable[Concatenate[T, Q], Bar[Q, T]]\nreveal_type(dec(h))  # N: Revealed type is \"def [T, Q] (T`-1, *Q.args, **Q.kwargs) -> builtins.list[__main__.Bar[Q`-2, T`-1]]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericParamSpecVsParamSpecConcatenate]\nfrom typing import TypeVar, Callable, List, Tuple, Generic\nfrom typing_extensions import ParamSpec, Concatenate\n\nT = TypeVar('T')\nP = ParamSpec('P')\nQ = ParamSpec('Q')\n\nclass Foo(Generic[P]): ...\n\ndef dec(f: Callable[P, int]) -> Callable[P, Foo[P]]: ...\nh: Callable[Concatenate[T, Q], int]\ng: Callable[Concatenate[T, Q], int]\nh = g\nreveal_type(dec(h))  # N: Revealed type is \"def [T, Q] (T`-1, *Q.args, **Q.kwargs) -> __main__.Foo[[T`-1, **Q`-2]]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericParamSpecSecondary]\nfrom typing import TypeVar, Callable, List, Tuple, Generic\nfrom typing_extensions import ParamSpec, Concatenate\n\nT = TypeVar('T')\nP = ParamSpec('P')\nQ = ParamSpec('Q')\n\nclass Foo(Generic[P]): ...\n\ndef dec(f: Callable[P, Foo[P]]) -> Callable[P, Foo[P]]: ...\ng: Callable[[T], Foo[[int]]]\nreveal_type(dec(g))  # N: Revealed type is \"def (builtins.int) -> __main__.Foo[[builtins.int]]\"\nh: Callable[Q, Foo[[int]]]\nreveal_type(dec(g))  # N: Revealed type is \"def (builtins.int) -> __main__.Foo[[builtins.int]]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericParamSpecSecondOrder]\nfrom typing import TypeVar, Callable\nfrom typing_extensions import ParamSpec, Concatenate\n\nT = TypeVar('T')\nS = TypeVar('S')\nP = ParamSpec('P')\nQ = ParamSpec('Q')\nU = TypeVar('U')\nW = ParamSpec('W')\n\ndef transform(\n    dec: Callable[[Callable[P, T]], Callable[Q, S]]\n) -> Callable[[Callable[Concatenate[int, P], T]], Callable[Concatenate[int, Q], S]]: ...\n\ndef dec(f: Callable[W, U]) -> Callable[W, U]: ...\ndef dec2(f: Callable[Concatenate[str, W], U]) -> Callable[Concatenate[bytes, W], U]: ...\nreveal_type(transform(dec))  # N: Revealed type is \"def [P, T] (def (builtins.int, *P.args, **P.kwargs) -> T`3) -> def (builtins.int, *P.args, **P.kwargs) -> T`3\"\nreveal_type(transform(dec2))  # N: Revealed type is \"def [W, T] (def (builtins.int, builtins.str, *W.args, **W.kwargs) -> T`7) -> def (builtins.int, builtins.bytes, *W.args, **W.kwargs) -> T`7\"\n[builtins fixtures/tuple.pyi]\n\n[case testNoAccidentalVariableClashInNestedGeneric]\nfrom typing import TypeVar, Callable, Generic, Tuple\n\nT = TypeVar('T')\nS = TypeVar('S')\nU = TypeVar('U')\n\ndef pipe(x: T, f1: Callable[[T], S], f2: Callable[[S], U]) -> U: ...\ndef and_then(a: T) -> Callable[[S], Tuple[S, T]]: ...\n\ndef apply(a: S, b: T) -> None:\n    v1 = and_then(b)\n    v2: Callable[[Tuple[S, T]], None]\n    return pipe(a, v1, v2)\n[builtins fixtures/tuple.pyi]\n\n[case testInferenceAgainstGenericParamSpecSpuriousBoundsNotUsed]\nfrom typing import TypeVar, Callable, Generic\nfrom typing_extensions import ParamSpec, Concatenate\n\nQ = ParamSpec(\"Q\")\nclass Foo(Generic[Q]): ...\n\nT1 = TypeVar(\"T1\", bound=Foo[...])\nT2 = TypeVar(\"T2\", bound=Foo[...])\nP = ParamSpec(\"P\")\ndef pop_off(fn: Callable[Concatenate[T1, P], T2]) -> Callable[P, Callable[[T1], T2]]:\n    ...\n\n@pop_off\ndef test(command: Foo[Q]) -> Foo[Q]: ...\nreveal_type(test)  # N: Revealed type is \"def () -> def [Q] (__main__.Foo[Q`-1]) -> __main__.Foo[Q`-1]\"\n[builtins fixtures/tuple.pyi]\n\n[case testInferenceAgainstGenericVariadicBasicInList]\nfrom typing import Tuple, TypeVar, List, Callable\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\ndef dec(f: Callable[[Unpack[Ts]], T]) -> Callable[[Unpack[Ts]], List[T]]: ...\n\nU = TypeVar(\"U\")\nV = TypeVar(\"V\")\ndef id(x: U) -> U: ...\ndef either(x: U, y: U) -> U: ...\ndef pair(x: U, y: V) -> Tuple[U, V]: ...\n\nreveal_type(dec(id))  # N: Revealed type is \"def [T] (T`3) -> builtins.list[T`3]\"\nreveal_type(dec(either))  # N: Revealed type is \"def [T] (T`5, T`5) -> builtins.list[T`5]\"\nreveal_type(dec(pair))  # N: Revealed type is \"def [U, V] (U`-1, V`-2) -> builtins.list[tuple[U`-1, V`-2]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testInferenceAgainstGenericVariadicBasicDeList]\nfrom typing import Tuple, TypeVar, List, Callable\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\ndef dec(f: Callable[[Unpack[Ts]], List[T]]) -> Callable[[Unpack[Ts]], T]: ...\n\nU = TypeVar(\"U\")\nV = TypeVar(\"V\")\ndef id(x: U) -> U: ...\ndef either(x: U, y: U) -> U: ...\n\nreveal_type(dec(id))  # N: Revealed type is \"def [T] (builtins.list[T`3]) -> T`3\"\nreveal_type(dec(either))  # N: Revealed type is \"def [T] (builtins.list[T`5], builtins.list[T`5]) -> T`5\"\n[builtins fixtures/tuple.pyi]\n\n[case testInferenceAgainstGenericVariadicPopOff]\nfrom typing import TypeVar, Callable, List, Tuple\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\ndef dec(f: Callable[[T, Unpack[Ts]], S]) -> Callable[[Unpack[Ts]], Callable[[T], S]]: ...\n\nU = TypeVar(\"U\")\nV = TypeVar(\"V\")\ndef id(x: U) -> U: ...\ndef either(x: U, y: U) -> U: ...\ndef pair(x: U, y: V) -> Tuple[U, V]: ...\n\nreveal_type(dec(id))  # N: Revealed type is \"def () -> def [T] (T`2) -> T`2\"\nreveal_type(dec(either))  # N: Revealed type is \"def [T] (T`5) -> def (T`5) -> T`5\"\nreveal_type(dec(pair))  # N: Revealed type is \"def [V] (V`-2) -> def [T] (T`8) -> tuple[T`8, V`-2]\"\nreveal_type(dec(dec))  # N: Revealed type is \"def () -> def [T, Ts, S] (def (T`-1, *Unpack[Ts`-2]) -> S`-3) -> def (*Unpack[Ts`-2]) -> def (T`-1) -> S`-3\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericVariadicPopOn]\nfrom typing import TypeVar, Callable, List, Tuple\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\ndef dec(f: Callable[[Unpack[Ts]], Callable[[T], S]]) -> Callable[[T, Unpack[Ts]], S]: ...\n\nU = TypeVar(\"U\")\nV = TypeVar(\"V\")\ndef id() -> Callable[[U], U]: ...\ndef either(x: U) -> Callable[[U], U]: ...\ndef pair(x: U) -> Callable[[V], Tuple[V, U]]: ...\n\nreveal_type(dec(id))  # N: Revealed type is \"def [T] (T`3) -> T`3\"\nreveal_type(dec(either))  # N: Revealed type is \"def [T] (T`6, T`6) -> T`6\"\nreveal_type(dec(pair))  # N: Revealed type is \"def [T, U] (T`9, U`-1) -> tuple[T`9, U`-1]\"\n# This is counter-intuitive but looks correct, dec matches itself only if Ts is empty\nreveal_type(dec(dec))  # N: Revealed type is \"def [T, S] (T`13, def () -> def (T`13) -> S`14) -> S`14\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericVariadicVsVariadic]\nfrom typing import TypeVar, Callable, List, Generic\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nUs = TypeVarTuple(\"Us\")\n\nclass Foo(Generic[Unpack[Ts]]): ...\nclass Bar(Generic[Unpack[Ts], T]): ...\n\ndef dec(f: Callable[[Unpack[Ts]], T]) -> Callable[[Unpack[Ts]], List[T]]: ...\ndef f(*args: Unpack[Us]) -> Foo[Unpack[Us]]: ...\nreveal_type(dec(f))  # N: Revealed type is \"def [Ts] (*Unpack[Ts`2]) -> builtins.list[__main__.Foo[Unpack[Ts`2]]]\"\ng: Callable[[Unpack[Us]], Foo[Unpack[Us]]]\nreveal_type(dec(g))  # N: Revealed type is \"def [Ts] (*Unpack[Ts`4]) -> builtins.list[__main__.Foo[Unpack[Ts`4]]]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericVariadicVsVariadicConcatenate]\nfrom typing import TypeVar, Callable, Generic\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nTs = TypeVarTuple(\"Ts\")\nUs = TypeVarTuple(\"Us\")\n\nclass Foo(Generic[Unpack[Ts]]): ...\n\ndef dec(f: Callable[[Unpack[Ts]], int]) -> Callable[[Unpack[Ts]], Foo[Unpack[Ts]]]: ...\nh: Callable[[T, Unpack[Us]], int]\ng: Callable[[T, Unpack[Us]], int]\nh = g\nreveal_type(dec(h))  # N: Revealed type is \"def [T, Us] (T`-1, *Unpack[Us`-2]) -> __main__.Foo[T`-1, Unpack[Us`-2]]\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericVariadicSecondary]\nfrom typing import TypeVar, Callable, Generic\nfrom typing_extensions import Unpack, TypeVarTuple\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\nUs = TypeVarTuple(\"Us\")\n\nclass Foo(Generic[Unpack[Ts]]): ...\n\ndef dec(f: Callable[[Unpack[Ts]], Foo[Unpack[Ts]]]) -> Callable[[Unpack[Ts]], Foo[Unpack[Ts]]]: ...\ng: Callable[[T], Foo[int]]\nreveal_type(dec(g))  # N: Revealed type is \"def (builtins.int) -> __main__.Foo[builtins.int]\"\nh: Callable[[Unpack[Us]], Foo[int]]\nreveal_type(dec(h))  # N: Revealed type is \"def (builtins.int) -> __main__.Foo[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testTypeApplicationGenericConstructor]\nfrom typing import Generic, TypeVar, Callable\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nclass C(Generic[T]):\n    def __init__(self, f: Callable[[S], T], x: S) -> None:\n        self.x = f(x)\n\nreveal_type(C[int])  # N: Revealed type is \"def [S] (f: def (S`-1) -> builtins.int, x: S`-1) -> __main__.C[builtins.int]\"\nAlias = C[int]\nC[int, str]  # E: Type application has too many types (1 expected)\n\n[case testHigherOrderGenericPartial]\nfrom typing import TypeVar, Callable\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nU = TypeVar(\"U\")\ndef apply(f: Callable[[T], S], x: T) -> S: ...\ndef id(x: U) -> U: ...\n\nA1 = TypeVar(\"A1\")\nA2 = TypeVar(\"A2\")\nR = TypeVar(\"R\")\ndef fake_partial(fun: Callable[[A1, A2], R], arg: A1) -> Callable[[A2], R]: ...\n\nf_pid = fake_partial(apply, id)\nreveal_type(f_pid)  # N: Revealed type is \"def [A2] (A2`2) -> A2`2\"\nreveal_type(f_pid(1))  # N: Revealed type is \"builtins.int\"\n\n[case testInvalidTypeVarParametersConcrete]\nfrom typing import Callable, Generic, ParamSpec, Protocol, TypeVar, overload\n\nP = ParamSpec('P')\nP2 = ParamSpec('P2')\nR = TypeVar('R')\nR2 = TypeVar('R2')\n\nclass C(Generic[P, R, P2, R2]): ...\n\nclass Proto(Protocol[P, R]):\n    @overload\n    def __call__(self, f: Callable[P2, R2]) -> C[P2, R2, ..., R]: ...\n    @overload\n    def __call__(self, **kwargs) -> C[P, R, ..., [int, str]]: ...  # E: Cannot use \"[int, str]\" for regular type variable, only for ParamSpec\n[builtins fixtures/tuple.pyi]\n\n[case testInvalidTypeVarParametersArbitrary]\nfrom typing import Callable, Generic, ParamSpec, Protocol, TypeVar, overload\n\nP = ParamSpec('P')\nP2 = ParamSpec('P2')\nR = TypeVar('R')\nR2 = TypeVar('R2')\n\nclass C(Generic[P, R, P2, R2]): ...\n\nclass Proto(Protocol[P, R]):\n    @overload\n    def __call__(self, f: Callable[P2, R2]) -> C[P2, R2, ..., R]: ...\n    @overload\n    def __call__(self, **kwargs) -> C[P, R, ..., ...]: ...  # E: Cannot use \"[VarArg(Any), KwArg(Any)]\" for regular type variable, only for ParamSpec\n[builtins fixtures/tuple.pyi]\n\n[case testGenericOverloadOverlapUnion]\nfrom typing import TypeVar, overload, Union, Generic\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\nT = TypeVar(\"T\")\n\nclass C(Generic[K, V]):\n    @overload\n    def pop(self, key: K) -> V: ...\n    @overload\n    def pop(self, key: K, default: Union[V, T] = ...) -> Union[V, T]: ...\n    def pop(self, key: K, default: Union[V, T] = ...) -> Union[V, T]:\n        ...\n\n[case testOverloadedGenericInit]\nfrom typing import TypeVar, overload, Union, Generic\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nclass Int(Generic[T]): ...\nclass Str(Generic[T]): ...\n\nclass C(Generic[T]):\n    @overload\n    def __init__(self: C[Int[S]], x: int, y: S) -> None: ...\n    @overload\n    def __init__(self: C[Str[S]], x: str, y: S) -> None: ...\n    def __init__(self, x, y) -> None: ...\n\ndef foo(x: T):\n    reveal_type(C)  # N: Revealed type is \"Overload(def [T, S] (x: builtins.int, y: S`-1) -> __main__.C[__main__.Int[S`-1]], def [T, S] (x: builtins.str, y: S`-1) -> __main__.C[__main__.Str[S`-1]])\"\n    reveal_type(C(0, x))  # N: Revealed type is \"__main__.C[__main__.Int[T`-1]]\"\n    reveal_type(C(\"yes\", x))  # N: Revealed type is \"__main__.C[__main__.Str[T`-1]]\"\n\n[case testInstanceMethodBoundOnClass]\nfrom typing import TypeVar, Generic\n\nT = TypeVar(\"T\")\nclass B(Generic[T]):\n    def foo(self) -> T: ...\nclass C(B[T]): ...\nclass D(C[int]): ...\n\nreveal_type(B.foo)  # N: Revealed type is \"def [T] (self: __main__.B[T`1]) -> T`1\"\nreveal_type(B[int].foo)  # N: Revealed type is \"def (self: __main__.B[builtins.int]) -> builtins.int\"\nreveal_type(C.foo)  # N: Revealed type is \"def [T] (self: __main__.B[T`1]) -> T`1\"\nreveal_type(C[int].foo)  # N: Revealed type is \"def (self: __main__.B[builtins.int]) -> builtins.int\"\nreveal_type(D.foo)  # N: Revealed type is \"def (self: __main__.B[builtins.int]) -> builtins.int\"\n\n[case testDeterminismFromJoinOrderingInSolver]\n# Used to fail non-deterministically\n# https://github.com/python/mypy/issues/19121\nfrom __future__ import annotations\nfrom typing import Generic, Iterable, Iterator, Self, TypeVar\n\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n_T3 = TypeVar(\"_T3\")\n_T_co = TypeVar(\"_T_co\", covariant=True)\n\nclass Base(Iterable[_T1]):\n    def __iter__(self) -> Iterator[_T1]: ...\nclass A(Base[_T1]): ...\nclass B(Base[_T1]): ...\nclass C(Base[_T1]): ...\nclass D(Base[_T1]): ...\nclass E(Base[_T1]): ...\n\nclass zip2(Generic[_T_co]):\n    def __new__(\n        cls,\n        iter1: Iterable[_T1],\n        iter2: Iterable[_T2],\n        iter3: Iterable[_T3],\n    ) -> zip2[tuple[_T1, _T2, _T3]]: ...\n    def __iter__(self) -> Self: ...\n    def __next__(self) -> _T_co: ...\n\ndef draw(\n    colors1: A[str] | B[str] | C[int] | D[int | str],\n    colors2: A[str] | B[str] | C[int] | D[int | str],\n    colors3: A[str] | B[str] | C[int] | D[int | str],\n) -> None:\n    for c1, c2, c3 in zip2(colors1, colors2, colors3):\n        reveal_type(c1)  # N: Revealed type is \"builtins.int | builtins.str\"\n        reveal_type(c2)  # N: Revealed type is \"builtins.int | builtins.str\"\n        reveal_type(c3)  # N: Revealed type is \"builtins.int | builtins.str\"\n\ndef takes_int_str_none(x: int | str | None) -> None: ...\n\ndef draw_none(\n    colors1: A[str] | B[str] | C[int] | D[None],\n    colors2: A[str] | B[str] | C[int] | D[None],\n    colors3: A[str] | B[str] | C[int] | D[None],\n) -> None:\n    for c1, c2, c3 in zip2(colors1, colors2, colors3):\n        # TODO: can't do reveal type because the union order is not deterministic\n        takes_int_str_none(c1)\n        takes_int_str_none(c2)\n        takes_int_str_none(c3)\n[builtins fixtures/tuple.pyi]\n\n[case testPropertyWithGenericSetter]\nfrom typing import TypeVar\n\nclass B: ...\nclass C(B): ...\nT = TypeVar(\"T\", bound=B)\n\nclass Test:\n    @property\n    def foo(self) -> list[C]: ...\n    @foo.setter\n    def foo(self, val: list[T]) -> None: ...\n\nt1: Test\nt2: Test\n\nlb: list[B]\nlc: list[C]\nli: list[int]\n\nt1.foo = lb\nt1.foo = lc\nt1.foo = li  # E: Value of type variable \"T\" of \"foo\" of \"Test\" cannot be \"int\"\n\nt2.foo = [B()]\nt2.foo = [C()]\nt2.foo = [1]  # E: Value of type variable \"T\" of \"foo\" of \"Test\" cannot be \"int\"\n[builtins fixtures/property.pyi]\n\n[case testEmptyParamSpecConsistency]\nfrom typing import Generic, Callable\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nclass X1(Generic[P]):\n    def __call__(self, *a: P.args, **k: P.kwargs) -> None: ...\nX2 = Callable[P, None]\n\nx1: X1[()]\nx2: X2[()]\n\nreveal_type(x1)  # N: Revealed type is \"__main__.X1[[]]\"\nreveal_type(x2)  # N: Revealed type is \"def ()\"\n\nx1()\nx1(5)  # E: Too many arguments for \"__call__\" of \"X1\"\nx2()\nx2(5)  # E: Too many arguments\n[builtins fixtures/tuple.pyi]\n\n[case testMissingTypeArgsInApplication]\nfrom typing import Generic\nfrom typing_extensions import Unpack, TypeVarTuple, ParamSpec\n\nTs = TypeVarTuple(\"Ts\")\nP = ParamSpec(\"P\")\n\nclass CanHaveZero1(Generic[Unpack[Ts]]): ...\nclass CanHaveZero2(Generic[P]): ...\n\nok1: CanHaveZero1[()]\nok2: CanHaveZero2[()]\nok3: tuple[()]\n\nreveal_type(ok1)  # N: Revealed type is \"__main__.CanHaveZero1[()]\"\nreveal_type(ok2)  # N: Revealed type is \"__main__.CanHaveZero2[[]]\"\nreveal_type(ok3)  # N: Revealed type is \"tuple[()]\"\n\nbad1: list[()] = []  # E: \"list\" expects 1 type argument, but none given\n[builtins fixtures/tuple.pyi]\n\n[case testMissingTypeArgsInApplicationStrict]\n# flags: --strict\nfrom typing import Generic\nfrom typing_extensions import Unpack, TypeVarTuple, ParamSpec\n\nTs = TypeVarTuple(\"Ts\")\nP = ParamSpec(\"P\")\n\nclass CanHaveZero1(Generic[Unpack[Ts]]): ...\nclass CanHaveZero2(Generic[P]): ...\n\nok1: CanHaveZero1[()]\nok2: CanHaveZero2[()]\nok3: tuple[()]\n\nreveal_type(ok1)  # N: Revealed type is \"__main__.CanHaveZero1[()]\"\nreveal_type(ok2)  # N: Revealed type is \"__main__.CanHaveZero2[[]]\"\nreveal_type(ok3)  # N: Revealed type is \"tuple[()]\"\n\nbad1: list[()] = []  # E: \"list\" expects 1 type argument, but none given \\\n                     # E: Missing type arguments for generic type \"list\"\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-ignore.test",
    "content": "[case testIgnoreTypeError]\nx = 1\nx() # type: ignore\nx() # E: \"int\" not callable\n\n[case testIgnoreUndefinedName]\nx = 1\ny # type: ignore\nz # E: Name \"z\" is not defined\n\n[case testIgnoreImportError]\nimport xyz_m # type: ignore\nxyz_m.foo\n1() # E: \"int\" not callable\n\n[case testIgnoreImportFromError]\nfrom xyz_m import a, b # type: ignore\na.foo\nb()\n1() # E: \"int\" not callable\n\n[case testIgnoreImportFromErrorMultiline]\nfrom xyz_m import ( # type: ignore\n    a, b\n)\na.foo\nb()\n1() # E: \"int\" not callable\n\n[case testIgnoreImportAllError]\nfrom xyz_m import * # type: ignore\nx   # E: Name \"x\" is not defined\n1() # E: \"int\" not callable\n\n[case testIgnoreImportBadModule_no_native_parse]\nimport m # type: ignore\nfrom m import a # type: ignore\n[file m.py]\n+\n[out]\ntmp/m.py:1: error: Invalid syntax\n\n[case testIgnoreAppliesOnlyToMissing]\nimport a # type: ignore\nimport b # type: ignore\nreveal_type(a.foo) # N: Revealed type is \"Any\"\nreveal_type(b.foo) # N: Revealed type is \"builtins.int\"\na.bar()\nb.bar() # E: Module has no attribute \"bar\"\n\n[file b.py]\nfoo = 3\n\n[builtins fixtures/module_all.pyi]\n[out]\n\n[case testIgnoreImportStarFromBadModule_no_native_parse]\nfrom m import * # type: ignore\n[file m.py]\n+\n[out]\ntmp/m.py:1: error: Invalid syntax\n\n[case testIgnoreAssignmentTypeError]\nx = 1\nif int():\n    x = '' # type: ignore\nif int():\n    x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testIgnoreInvalidOverride]\nclass A:\n    def f(self) -> int: pass\nclass B(A):\n    def f(self) -> str: pass # type: ignore\n\n[case testIgnoreMissingModuleAttribute]\nimport m\nm.x = object # type: ignore\nm.f() # type: ignore\nm.y # E: Module has no attribute \"y\"\n[file m.py]\n[builtins fixtures/module.pyi]\n\n[case testIgnoreTypeInferenceError]\nx = [] # type: ignore\ny = x\nx.append(1)\n[builtins fixtures/list.pyi]\n\n[case testIgnoreTypeInferenceError2]\ndef f() -> None: pass\nx = f() # type: ignore\ny = x\nx = 1\n[builtins fixtures/list.pyi]\n\n[case testIgnoreTypeInferenceErrorAndMultipleAssignment]\nx, y = [], [] # type: ignore\nz = x\nz = y\n[builtins fixtures/list.pyi]\n\n[case testIgnoreSomeStarImportErrors]\nfrom m1 import *\nfrom m2 import * # type: ignore\n# We should still import things that don't conflict.\ny() # E: \"str\" not callable\nz() # E: \"int\" not callable\nx() # E: \"int\" not callable\n[file m1.py]\nx = 1\ny = ''\n[file m2.py]\nx = ''\nz = 1\n\n[case testIgnoredModuleDefinesBaseClass1]\nfrom m import B # type: ignore\n\nclass C(B):\n    def f(self) -> None:\n        self.f(1) # E: Too many arguments for \"f\" of \"C\"\n        self.g(1)\n[out]\n\n[case testIgnoredModuleDefinesBaseClass2]\nimport m # type: ignore\n\nclass C(m.B):\n    def f(self) -> None: ...\n\nc = C()\nc.f(1) # E: Too many arguments for \"f\" of \"C\"\nc.g(1)\nc.x = 1\n[out]\n\n[case testIgnoredModuleDefinesBaseClassAndClassAttribute]\nimport m # type: ignore\n\nclass C(m.B):\n    @staticmethod\n    def f() -> None: pass\n\nC.f(1) # E: Too many arguments for \"f\" of \"C\"\nC.g(1)\nC.x = 1\n[builtins fixtures/staticmethod.pyi]\n[out]\n\n[case testIgnoredModuleDefinesBaseClassWithInheritance1]\nfrom m import B # type: ignore\n\nclass C: pass\nclass D(C, B):\n    def f(self) -> None:\n        self.f(1) # E: Too many arguments for \"f\" of \"D\"\n        self.g(1)\n[out]\n\n[case testIgnoredModuleDefinesBaseClassWithInheritance2]\nfrom m import B # type: ignore\n\nclass C(B): pass\nclass D(C):\n    def f(self) -> None:\n        self.f(1) # E: Too many arguments for \"f\" of \"D\"\n        self.g(1)\n[out]\n\n[case testIgnoreWithFollowingIndentedComment]\nif 1:  # type: ignore\n    # blah\n    pass\n[out]\n\n[case testIgnoreTooManyTypeArguments]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nU = TypeVar('U')\n\nclass Base(Generic[T, U]):\n  pass\n\nclass PartialBase(Base[T, int], Generic[T]):\n  pass\n\nclass Child(PartialBase[str, int]):  # type: ignore\n  pass\n\n\ndef foo(x: Base[str, int]) -> None: pass\nfoo(Child())\n\ndef bar(x: Base[str, str]) -> None: pass\nbar(Child())\n[out]\nmain:19: error: Argument 1 to \"bar\" has incompatible type \"Child\"; expected \"Base[str, str]\"\n\n[case testTypeIgnoreLineNumberWithinFile]\nimport m\npass # type: ignore\nm.f(kw=1)\n[file m.py]\npass\ndef f() -> None: pass\n[out]\nmain:3: error: Unexpected keyword argument \"kw\" for \"f\"\nmain:3: note: \"f\" defined in \"m\"\n\n[case testIgnoreUnexpectedKeywordArgument]\nimport m\nm.f(kw=1)  # type: ignore\n[file m.py]\ndef f() -> None: pass\n[out]\n\n[case testCannotIgnoreBlockingError]\nyield  # type: ignore  # E: \"yield\" outside function\n\n[case testIgnoreWholeModule1]\n# type: ignore\nif True:\n    IGNORE\n\n[case testIgnoreWholeModule2]\n# type: ignore\n@d\nclass C: ...\nIGNORE\n\n[case testIgnoreWholeModule3]\n# type: ignore\n@d\n\ndef f(): ...\nIGNORE\n\n[case testIgnoreWholeModule4]\n# type: ignore\nimport MISSING\n\n[case testDontIgnoreWholeModule1]\nif True:\n    # type: ignore\n    ERROR # E: Name \"ERROR\" is not defined\nERROR # E: Name \"ERROR\" is not defined\n\n[case testDontIgnoreWholeModule2]\n@d  # type: ignore\nclass C: ...\nERROR # E: Name \"ERROR\" is not defined\n\n[case testDontIgnoreWholeModule3]\n@d  # type: ignore\n\ndef f(): ...\nERROR # E: Name \"ERROR\" is not defined\n\n[case testIgnoreInsideFunctionDoesntAffectWhole]\n# flags: --disallow-untyped-defs\n\ndef f():  # E: Function is missing a return type annotation\n    42 + 'no way'  # type: ignore\n    return 0\n\n[case testIgnoreInsideClassDoesntAffectWhole]\nimport six\nclass M(type): pass\n\n@six.add_metaclass(M)\nclass CD(six.with_metaclass(M)):  # E: Multiple metaclass definitions\n    42 + 'no way'  # type: ignore\n\n[builtins fixtures/tuple.pyi]\n\n[case testUnusedIgnoreCodeOrder]\n# flags: --warn-unused-ignores\n5 # type: ignore[import, steven] # E: Unused \"type: ignore[import, steven]\" comment\n-- User ordering of codes is preserved\n5 # type: ignore[steven, import] # E: Unused \"type: ignore[steven, import]\" comment\n-- Spacing is not preserved\n5 # type: ignore[  steven,      import ] # E: Unused \"type: ignore[steven, import]\" comment\n-- Make sure it works as intended in more complex situations\n1 + \"ok\" + \"ok\".foo # type: ignore[  operator,steven,attr-defined, import] # E: Unused \"type: ignore[steven, import]\" comment\n\n[case testUnusedIgnoreTryExcept]\n# flags: --warn-unused-ignores\ntry:\n    import foo  # type: ignore  # E: Unused \"type: ignore\" comment\n    import bar  # type: ignore[import]  # E: Unused \"type: ignore\" comment\n    import foobar  # type: ignore[unused-ignore]\n    import barfoo  # type: ignore[import,unused-ignore]\n    import missing  # type: ignore[import,unused-ignore]\nexcept Exception:\n    pass\n[file foo.py]\n[file bar.py]\n[file foobar.py]\n[file barfoo.py]\n[builtins fixtures/exception.pyi]\n"
  },
  {
    "path": "test-data/unit/check-incomplete-fixture.test",
    "content": "-- Test cases for reporting errors when a test case uses a fixture with\n-- missing definitions.  At least in the most common cases this should not\n-- result in an uncaught exception.  These tests make sure that this behavior\n-- does not regress.\n--\n-- NOTE: These tests do NOT test behavior of mypy outside tests.\n\n[case testVariableUndefinedUsingDefaultFixture]\nimport m\n# This used to cause a crash since types.ModuleType is not available\n# by default. We fall back to 'object' now.\nm.x # E: \"object\" has no attribute \"x\"\n[file m.py]\n\n[case testSetMissingFromStubs]\nfrom typing import Set\ndef f(x: Set[int]) -> None: pass\n[out]\nmain:1: error: Module \"typing\" has no attribute \"Set\"\nmain:1: note: Maybe your test fixture does not define \"builtins.set\"?\nmain:1: note: Consider adding [builtins fixtures/set.pyi] to your test description\n\n[case testBaseExceptionMissingFromStubs]\ne: BaseException\n[out]\nmain:1: error: Name \"BaseException\" is not defined\nmain:1: note: Maybe your test fixture does not define \"builtins.BaseException\"?\nmain:1: note: Consider adding [builtins fixtures/exception.pyi] to your test description\n\n[case testExceptionMissingFromStubs]\ne: Exception\n[out]\nmain:1: error: Name \"Exception\" is not defined\nmain:1: note: Maybe your test fixture does not define \"builtins.Exception\"?\nmain:1: note: Consider adding [builtins fixtures/exception.pyi] to your test description\n\n[case testIsinstanceMissingFromStubs]\nif isinstance(1, int):\n    pass\n[out]\nmain:1: error: Name \"isinstance\" is not defined\nmain:1: note: Maybe your test fixture does not define \"builtins.isinstance\"?\nmain:1: note: Consider adding [builtins fixtures/isinstancelist.pyi] to your test description\n\n[case testTupleMissingFromStubs1]\ntuple()\n[out]\nmain:1: error: Name \"tuple\" is not defined\nmain:1: note: Maybe your test fixture does not define \"builtins.tuple\"?\nmain:1: note: Consider adding [builtins fixtures/tuple.pyi] to your test description\nmain:1: note: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import Tuple\")\n\n[case testTupleMissingFromStubs2]\ntuple()\nfrom typing import Tuple\nx: Tuple[int, str]\n[out]\nmain:1: error: Name \"tuple\" is not defined\nmain:1: note: Maybe your test fixture does not define \"builtins.tuple\"?\nmain:1: note: Consider adding [builtins fixtures/tuple.pyi] to your test description\nmain:1: note: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import Tuple\")\nmain:3: error: Name \"tuple\" is not defined\n\n[case testClassmethodMissingFromStubs]\nclass A:\n    @classmethod\n    def f(cls): pass\n[out]\nmain:2: error: Name \"classmethod\" is not defined\nmain:2: note: Maybe your test fixture does not define \"builtins.classmethod\"?\nmain:2: note: Consider adding [builtins fixtures/classmethod.pyi] to your test description\n\n[case testPropertyMissingFromStubs]\nclass A:\n    @property\n    def f(self): pass\n[out]\nmain:2: error: Name \"property\" is not defined\nmain:2: note: Maybe your test fixture does not define \"builtins.property\"?\nmain:2: note: Consider adding [builtins fixtures/property.pyi] to your test description\n"
  },
  {
    "path": "test-data/unit/check-incremental.test",
    "content": "-- Checks for incremental mode (see testcheck.py).\n-- Each test is run at least twice, once with a cold cache, once with a warm cache.\n-- Before the tests are run again, in step N any *.py.N files are copied to\n-- *.py.  There are at least two runs; more as long as there are *.py.N files.\n--\n-- You can add an empty section like `[delete mod.py.2]` to delete `mod.py`\n-- before the second run.\n--\n-- Errors expected in the first run should be in the `[out1]` section, and\n-- errors expected in the second run should be in the `[out2]` section, and so on.\n-- If a section is omitted, it is expected there are no errors on that run.\n-- The number of runs is determined by the highest N in all [outN] sections, but\n-- there are always at least two runs. (Note that [out] is equivalent to [out1].)\n--\n-- The list of modules to be checked can be specified using\n-- # cmd: mypy -m mod1 mod2 mod3\n-- To check a different list on the second run, use\n-- # cmd2: mypy -m mod1 mod3\n-- (and cmd3 for the third run, and so on).\n--\n-- Extra command line flags may be specified using\n-- # flags: --some-flag\n-- If the second run requires different flags, those can be specified using\n-- # flags2: --another-flag\n-- (and flags3 for the third run, and so on).\n--\n-- Incremental tests involving plugins that get updated are also supported.\n-- All plugin files that are updated *must* end in '_plugin', so they will\n-- be unloaded from 'sys.modules' between incremental steps.\n--\n-- Any files that we expect to be rechecked should be annotated in the [rechecked]\n-- annotation, and any files expect to be stale (aka have a modified interface)\n-- should be annotated in the [stale] annotation. Note that a file that ends up\n-- producing an error has its caches deleted and is marked stale automatically.\n-- Such files do not need to be included in [stale ...] list.\n--\n-- The test suite will automatically assume that __main__ is stale and rechecked in\n-- all cases so we can avoid constantly having to annotate it. The list of\n-- rechecked/stale files can be in any arbitrary order, or can be left empty\n-- if no files should be rechecked/stale.\n--\n-- There are additional incremental mode test cases in check-serialize.test.\n\n[case testIncrementalEmpty]\n[rechecked]\n[stale]\n\n[case testIncrementalBasics]\nimport m\n[file m.py]\ndef foo():\n    pass\n[file m.py.2]\ndef foo() -> None:\n    pass\n[rechecked m]\n[stale m]\n\n[case testIncrementalError]\nimport m\n[file m.py]\ndef foo() -> None:\n    pass\n[file m.py.2]\ndef foo() -> None:\n    bar()\n[rechecked m]\n[stale]\n[out2]\ntmp/m.py:2: error: Name \"bar\" is not defined\n\n[case testIncrementalSimpleImportSequence]\nimport mod1\nmod1.func1()\n\n[file mod1.py]\nimport mod2\ndef func1() -> None: mod2.func2()\n\n[file mod2.py]\nimport mod3\ndef func2() -> None: mod3.func3()\n\n[file mod3.py]\ndef func3() -> None: pass\n\n[rechecked]\n[stale]\n\n\n[case testIncrementalInternalChangeOnly]\nimport mod1\nmod1.func1()\n\n[file mod1.py]\nimport mod2\ndef func1() -> None: mod2.func2()\n\n[file mod2.py]\nimport mod3\ndef func2() -> None: mod3.func3()\n\n[file mod3.py]\ndef func3() -> None: pass\n\n[file mod3.py.2]\ndef func3() -> None: 3 + 2\n\n[rechecked mod3]\n[stale]\n\n\n[case testIncrementalImportGone]\nimport mod1\n\n[file mod1.py]\nfrom mod2 import A\ndef func1() -> A: pass\n\n[file mod2.py]\nclass A: pass\n\n[file mod1.py.2]\ndef func1() -> A: pass\n\n[rechecked mod1]\n[stale mod1]\n[out2]\ntmp/mod1.py:1: error: Name \"A\" is not defined\n\n[case testIncrementalCallable]\nimport mod1\n\n[file mod1.py]\nfrom typing import Callable\nfrom mypy_extensions import Arg\ndef func1() -> Callable[[Arg(int, 'x')], int]: pass\n\n[file mod1.py.2]\nfrom typing import Callable\nfrom mypy_extensions import Arg\ndef func1() -> Callable[[Arg(int, 'x')], int]: ...\n\n\n[rechecked mod1]\n[stale]\n\n[builtins fixtures/dict.pyi]\n\n[case testIncrementalSameNameChange]\nimport mod1\n\n[file mod1.py]\nfrom mod2 import A\ndef func1() -> A: pass\n\n[file mod2.py]\nclass A: pass\n\n[file mod2.py.2]\nclass Parent: pass\nclass A(Parent): pass\n\n[rechecked mod1, mod2]\n[stale mod2]\n\n[case testIncrementalPartialInterfaceChange]\nimport mod1\nmod1.func1()\n\n[file mod1.py]\nimport mod2\ndef func1() -> None: mod2.func2()\n\n[file mod2.py]\nimport mod3\ndef func2() -> None: mod3.func3()\n\n[file mod3.py]\ndef func3() -> None: pass\n\n[file mod3.py.2]\ndef func3() -> int: return 2\n\n[rechecked mod2, mod3]\n[stale mod3]\n\n[case testIncrementalInternalFunctionDefinitionChange]\nimport mod1\n\n[file mod1.py]\nimport mod2\ndef accepts_int(a: int) -> int: return a\naccepts_int(mod2.foo())\n\n[file mod2.py]\ndef foo() -> int:\n    def inner() -> int:\n        return 42\n    return inner()\n\n[file mod2.py.2]\ndef foo() -> int:\n    def inner2() -> str:\n        return \"foo\"\n    return inner2()\n\n[rechecked mod2]\n[stale]\n[out2]\ntmp/mod2.py:4: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testIncrementalInternalScramble]\nimport mod1\n\n[file mod1.py]\nimport mod2\nmod2.foo()\n\n[file mod2.py]\ndef baz() -> int:\n    return 3\n\ndef bar() -> int:\n    return baz()\n\ndef foo() -> int:\n    return bar()\n\n[file mod2.py.2]\ndef foo() -> int:\n    return baz()\n\ndef bar() -> int:\n    return bar()\n\ndef baz() -> int:\n    return 42\n[rechecked mod2]\n[stale]\n\n[case testIncrementalMethodInterfaceChange]\nimport mod1\n\n[file mod1.py]\nimport mod2\n\n[file mod2.py]\nclass Foo:\n    def bar(self, a: str) -> str:\n        return \"a\"\n\n[file mod2.py.2]\nclass Foo:\n    def bar(self, a: float) -> str:\n        return \"a\"\n\n[rechecked mod1, mod2]\n[stale mod2]\n\n[case testIncrementalBaseClassChange]\nimport mod1\n\n[file mod1.py]\nfrom mod2 import Child\nChild().good_method()\n\n[file mod2.py]\nclass Good:\n    def good_method(self) -> int: return 1\nclass Bad: pass\nclass Child(Good): pass\n\n[file mod2.py.2]\nclass Good:\n    def good_method(self) -> int: return 1\nclass Bad: pass\nclass Child(Bad): pass\n\n[rechecked mod1, mod2]\n[stale mod2]\n[out2]\ntmp/mod1.py:2: error: \"Child\" has no attribute \"good_method\"\n\n[case testIncrementalCascadingChange]\nimport mod1\n\n[file mod1.py]\nfrom mod2 import A\ndef accepts_int(a: int) -> None: pass\naccepts_int(A)\n\n[file mod2.py]\nfrom mod3 import B\nA = B\n\n[file mod3.py]\nfrom mod4 import C\nB = C\n\n[file mod4.py]\nC = 3\n\n[file mod4.py.2]\nC = \"A\"\n\n[rechecked mod1, mod2, mod3, mod4]\n[stale mod2, mod3, mod4]\n[out2]\ntmp/mod1.py:3: error: Argument 1 to \"accepts_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalBrokenCascade]\nimport mod1\n\n[file mod1.py]\nimport mod2\ndef accept_int(a: int) -> int: return a\naccept_int(mod2.mod3.mod4.const)\n\n[file mod2.py]\nimport mod3\n\n[file mod3.py]\nimport mod4\n\n[file mod4.py]\nconst = 3\n\n[file mod3.py.2]\n# Import to mod4 is gone!\n\n[rechecked mod1, mod2, mod3]\n[stale mod3]\n[builtins fixtures/module.pyi]\n[out2]\ntmp/mod1.py:3: error: Module has no attribute \"mod4\"\n\n[case testIncrementalLongBrokenCascade]\nimport mod1\n\n[file mod1.py]\nimport mod2\ndef accept_int(a: int) -> int: return a\naccept_int(mod2.mod3.mod4.mod5.mod6.mod7.const)\n\n[file mod2.py]\nimport mod3\n\n[file mod3.py]\nimport mod4\n\n[file mod4.py]\nimport mod5\n\n[file mod5.py]\nimport mod6\n\n[file mod6.py]\nimport mod7\n\n[file mod7.py]\nconst = 3\n\n[file mod6.py.2]\n# Import to mod7 is gone!\n\n[rechecked mod1, mod5, mod6]\n[stale mod6]\n[builtins fixtures/module.pyi]\n[out2]\ntmp/mod1.py:3: error: Module has no attribute \"mod7\"\n\n[case testIncrementalNestedBrokenCascade]\nimport mod1\n\n[file mod1.py]\nimport mod2\ndef accept_int(a: int) -> int: return a\naccept_int(mod2.mod3.mod4.const)\n\n[file mod2/__init__.py]\nimport mod2.mod3 as mod3\n\n[file mod2/mod3/__init__.py]\nimport mod2.mod3.mod4 as mod4\n\n[file mod2/mod3/__init__.py.2]\n# Import is gone!\n\n[file mod2/mod3/mod4.py]\nconst = 3\n\n[rechecked mod1, mod2, mod2.mod3]\n[stale mod2.mod3]\n[builtins fixtures/module.pyi]\n[out2]\ntmp/mod1.py:3: error: Module has no attribute \"mod4\"\n\n[case testIncrementalNestedBrokenCascadeWithType1]\nimport mod1, mod2.mod3.mod5\n\n[file mod1.py]\nimport mod2\ndef accept_int(x: int) -> None: pass\ndef produce() -> mod2.CustomType:\n    return mod2.CustomType()\na = produce()\naccept_int(a.foo())\n\n[file mod2/__init__.py]\nfrom mod2.mod3 import CustomType\n\n[file mod2/mod3/__init__.py]\nfrom mod2.mod3.mod4 import CustomType\n\n[file mod2/mod3/__init__.py.2]\n# Import a different class that also happens to be called 'CustomType'\nfrom mod2.mod3.mod5 import CustomType\ndef produce() -> CustomType:\n    return CustomType()\n\n[file mod2/mod3/mod4.py]\nclass CustomType:\n    def foo(self) -> int: return 1\n\n[file mod2/mod3/mod5.py]\nclass CustomType:\n    def foo(self) -> str: return \"a\"\n\n[rechecked mod1, mod2, mod2.mod3]\n[stale mod1, mod2, mod2.mod3]\n[builtins fixtures/module.pyi]\n[out1]\n[out2]\ntmp/mod1.py:6: error: Argument 1 to \"accept_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalNestedBrokenCascadeWithType2]\nimport mod1, mod2.mod3.mod5\n\n[file mod1.py]\nfrom mod2 import produce\ndef accept_int(x: int) -> None: pass\na = produce()\naccept_int(a.foo())\n\n[file mod2/__init__.py]\nfrom mod2.mod3 import produce\n\n[file mod2/mod3/__init__.py]\nfrom mod2.mod3.mod4 import CustomType\ndef produce() -> CustomType:\n    return CustomType()\n\n[file mod2/mod3/__init__.py.2]\n# Import a different class that also happens to be called 'CustomType'\nfrom mod2.mod3.mod5 import CustomType\ndef produce() -> CustomType:\n    return CustomType()\n\n[file mod2/mod3/mod4.py]\nclass CustomType:\n    def foo(self) -> int: return 1\n\n[file mod2/mod3/mod5.py]\nclass CustomType:\n    def foo(self) -> str: return \"a\"\n\n[rechecked mod1, mod2, mod2.mod3]\n[stale mod1, mod2.mod3]\n[builtins fixtures/module.pyi]\n[out1]\n[out2]\ntmp/mod1.py:4: error: Argument 1 to \"accept_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalRemoteChange]\nimport mod1\n\n[file mod1.py]\nimport mod2\ndef accepts_int(a: int) -> None: pass\naccepts_int(mod2.mod3.mod4.const)\n\n[file mod2.py]\nimport mod3\n\n[file mod3.py]\nimport mod4\n\n[file mod4.py]\nconst = 3\n\n[file mod4.py.2]\nconst = \"foo\"\n\n[rechecked mod1, mod3, mod4]\n[stale mod4]\n[out2]\ntmp/mod1.py:3: error: Argument 1 to \"accepts_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalBadChange]\nimport mod1\n\n[file mod1.py]\nfrom mod2 import func2\n\ndef func1() -> int:\n    return func2()\n\n[file mod2.py]\ndef func2() -> int:\n    return 1\n\n[file mod2.py.2]\ndef func2() -> str:\n    return \"foo\"\n\n[rechecked mod1, mod2]\n[stale mod2]\n[out2]\ntmp/mod1.py:4: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testIncrementalBadChangeWithSave]\nimport mod0\n\n[file mod0.py]\nimport mod1\nA = mod1.func2()\n\n[file mod1.py]\nfrom mod2 import func2\n\ndef func1() -> int:\n    return func2()\n\n[file mod2.py]\ndef func2() -> int:\n    return 1\n\n[file mod2.py.2]\ndef func2() -> str:\n    return \"foo\"\n\n[rechecked mod0, mod1, mod2]\n[stale mod0, mod2]\n[out2]\ntmp/mod1.py:4: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testIncrementalOkChangeWithSave]\nimport mod0\n\n[file mod0.py]\nimport mod1\nA = mod1.func2()\n\n[file mod1.py]\nfrom mod2 import func2\n\ndef func1() -> int:\n    func2()\n    return 1\n\n[file mod2.py]\ndef func2() -> int:\n    return 1\n\n[file mod2.py.2]\ndef func2() -> str:\n    return \"foo\"\n\n[rechecked mod0, mod1, mod2]\n[stale mod0, mod2]\n[out2]\n\n[case testIncrementalWithComplexDictExpression]\nimport mod1\n\n[file mod1.py]\nimport mod1_private\n\n[file mod1_private.py]\nmy_dict = {\n    'a': [1, 2, 3],\n    'b': [4, 5, 6]\n}\n\n[file mod1_private.py.2]\nmy_dict = {\n    'a': [1, 2, 3],\n    'b': [4, 5, 'a']\n}\n\n[rechecked mod1, mod1_private]\n[stale mod1_private]\n[builtins fixtures/dict.pyi]\n\n[case testIncrementalWithComplexConstantExpressionNoAnnotation]\nimport mod1\n\n[file mod1.py]\nimport mod1_private\n\n[file mod1_private.py]\ndef foobar() -> int: return 1\ndef baz() -> int: return 2\nconst = 1 + foobar()\n\n[file mod1_private.py.2]\ndef foobar() -> int: return 1\ndef baz() -> int: return 2\nconst = 1 + baz()\n\n[rechecked mod1_private]\n[stale]\n\n[case testIncrementalWithComplexConstantExpressionWithAnnotation]\nimport mod1\n\n[file mod1.py]\nimport mod1_private\n\n[file mod1_private.py]\ndef foobar() -> int: return 1\ndef baz() -> int: return 2\nconst = 1 + foobar()  # type: int\n\n[file mod1_private.py.2]\ndef foobar() -> int: return 1\ndef baz() -> int: return 2\nconst = 1 + baz()  # type: int\n\n[rechecked mod1_private]\n[stale]\n\n[case testIncrementalSmall]\nimport mod1\n\n[file mod1.py]\nimport mod1_private\ndef accepts_int(a: int) -> None: pass\naccepts_int(mod1_private.some_func(12))\n\n[file mod1_private.py]\ndef some_func(a: int) -> int:\n    return 1\n\n[file mod1_private.py.2]\ndef some_func(a: int) -> str:\n    return \"a\"\n\n[rechecked mod1, mod1_private]\n[stale mod1_private]\n[builtins fixtures/ops.pyi]\n[out2]\ntmp/mod1.py:3: error: Argument 1 to \"accepts_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalWithDecorators]\nimport mod1\n\n[file mod1.py]\nimport mod1_private\ndef accepts_int(a: int) -> None: pass\naccepts_int(mod1_private.some_func(12))\n\n[file mod1_private.py]\nfrom typing import Callable\ndef multiply(f: Callable[[int], int]) -> Callable[[int], int]:\n    return lambda a: f(a) * 10\n\ndef stringify(f: Callable[[int], int]) -> Callable[[int], str]:\n    return lambda a: str(f(a))\n\n@multiply\ndef some_func(a: int) -> int:\n    return a + 2\n\n[file mod1_private.py.2]\nfrom typing import Callable\ndef multiply(f: Callable[[int], int]) -> Callable[[int], int]:\n    return lambda a: f(a) * 10\n\ndef stringify(f: Callable[[int], int]) -> Callable[[int], str]:\n    return lambda a: str(f(a))\n\n@stringify\ndef some_func(a: int) -> int:\n    return a + 2\n[rechecked mod1, mod1_private]\n[stale mod1_private]\n[builtins fixtures/ops.pyi]\n[out2]\ntmp/mod1.py:3: error: Argument 1 to \"accepts_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalChangingClassAttributes]\nimport mod1\n\n[file mod1.py]\nimport mod2\nmod2.Foo.A\n\n[file mod2.py]\nclass Foo:\n    A = 3\n\n[file mod2.py.2]\nclass Foo:\n    A = \"hello\"\n\n[rechecked mod1, mod2]\n[stale mod2]\n\n[case testIncrementalChangingFields]\nimport mod1\n\n[file mod1.py]\nimport mod2\nf = mod2.Foo()\nf.A\n\n[file mod2.py]\nclass Foo:\n    def __init__(self) -> None:\n        self.A = 3\n\n[file mod2.py.2]\nclass Foo:\n    def __init__(self) -> None:\n        self.A = \"hello\"\n\n[rechecked mod1, mod2]\n[stale mod2]\n[out2]\n\n[case testIncrementalChangingFieldsWithAssignment]\nimport mod1\n\n[file mod1.py]\nimport mod2\nf = mod2.Foo()\nB = f.A\n\n[file mod2.py]\nclass Foo:\n    def __init__(self) -> None:\n        self.A = 3\n\n[file mod2.py.2]\nclass Foo:\n    def __init__(self) -> None:\n        self.A = \"hello\"\n\n[rechecked mod1, mod2]\n[stale mod1, mod2]\n\n[case testIncrementalCheckingChangingFields]\nimport mod1\n\n[file mod1.py]\nimport mod2\ndef accept_int(a: int) -> int: return a\nf = mod2.Foo()\naccept_int(f.A)\n\n[file mod2.py]\nclass Foo:\n    def __init__(self) -> None:\n        self.A = 3\n\n[file mod2.py.2]\nclass Foo:\n    def __init__(self) -> None:\n        self.A = \"hello\"\n\n[rechecked mod1, mod2]\n[stale mod2]\n[out2]\ntmp/mod1.py:4: error: Argument 1 to \"accept_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalNestedClassDefinition]\nimport mod1\n\n[file mod1.py]\nimport mod2\nb = mod2.Foo.Bar()\nb.attr\n\n[file mod2.py]\nclass Foo:\n    class Bar:\n        attr = 3\n\n[file mod2.py.2]\nclass Foo:\n    class Bar:\n        attr = \"foo\"\n\n[rechecked mod1, mod2]\n[stale mod2]\n\n[case testIncrementalSimpleBranchingModules]\nimport mod1\nimport mod2\n\n[file mod1.py]\ndef func() -> None: pass\n\n[file mod2.py]\ndef func() -> None: pass\n\n[file mod1.py.2]\ndef func() -> int: return 1\n\n[rechecked mod1]\n[stale mod1]\n\n[case testIncrementalSubmoduleImport]\nfrom parent.childA import Foo\n\ndef func1() -> Foo:\n    return Foo()\n\n[file parent/__init__.py]\nfrom parent.childA import Foo\nfrom parent.childB import Bar\n\n__all__ = ['Foo', 'Bar']\n\n[file parent/childA.py]\nimport parent\n\nclass Foo:\n    def test(self) -> int:\n        return parent.Bar().test()\n\n[file parent/childB.py]\nclass Bar:\n    def test(self) -> int: return 3\n\n[builtins fixtures/module_all.pyi]\n[rechecked]\n[stale]\n\n[case testIncrementalSubmoduleWithAttr]\nimport mod.child\nx = mod.child.Foo()\nx.bar()\n\n[file mod/__init__.py]\n\n[file mod/child.py]\nclass Foo:\n    def bar(self) -> None: pass\n[builtins fixtures/module.pyi]\n[rechecked]\n[stale]\n\n[case testIncrementalNestedSubmoduleImportFromWithAttr]\nfrom mod1.mod2 import mod3\ndef accept_int(a: int) -> None: pass\n\naccept_int(mod3.val3)\n\n[file mod1/__init__.py]\nval1 = 1\n\n[file mod1/mod2/__init__.py]\nval2 = 1\n\n[file mod1/mod2/mod3.py]\nval3 = 1\n\n[builtins fixtures/module.pyi]\n[rechecked]\n[stale]\n\n[case testIncrementalNestedSubmoduleWithAttr]\nimport mod1.mod2.mod3\ndef accept_int(a: int) -> None: pass\n\naccept_int(mod1.mod2.mod3.val3)\naccept_int(mod1.mod2.val2)\naccept_int(mod1.val1)\n\n[file mod1/__init__.py]\nval1 = 1\n\n[file mod1/mod2/__init__.py]\nval2 = 1\n\n[file mod1/mod2/mod3.py]\nval3 = 1\n\n[builtins fixtures/module.pyi]\n[rechecked]\n[stale]\n\n[case testIncrementalSubmoduleParentWithImportFrom]\nimport parent\n\n[file parent/__init__.py]\nfrom parent import a\n\n[file parent/a.py]\nval = 3\n\n[builtins fixtures/args.pyi]\n[stale]\n\n[case testIncrementalSubmoduleParentBackreference]\nimport parent\n\n[file parent/__init__.py]\nfrom parent import a\n\n[file parent/a.py]\nimport parent.b\n\n[file parent/b.py]\n\n[builtins fixtures/args.pyi]\n[stale]\n\n[case testIncrementalSubmoduleParentBackreferenceComplex]\nimport parent\n\n[file parent/__init__.py]\nimport parent.a\n\n[file parent/a.py]\nimport parent.b\nimport parent.c\n\n[file parent/b.py]\nimport parent.a\n\n[file parent/c.py]\nimport parent.a\n\n[builtins fixtures/args.pyi]\n[stale]\n\n[case testIncrementalReferenceNewFileWithImportFrom]\nfrom parent import a\n\n[file parent/__init__.py]\n\n[file parent/a.py]\n\n[file parent/a.py.2]\nfrom parent import b\nreveal_type(b.x)\n\n[file parent/b.py.2]\nx = 10\n\n[stale parent.a, parent.b]\n[rechecked parent.a, parent.b]\n[out2]\ntmp/parent/a.py:2: note: Revealed type is \"builtins.int\"\n\n[case testIncrementalReferenceExistingFileWithImportFrom]\nfrom parent import a, b\n\n[file parent/__init__.py]\n\n[file parent/a.py]\n\n[file parent/b.py]\n\n[file parent/a.py.2]\nfrom parent import b\n\n[stale parent.a]\n\n[case testIncrementalWithTypeIgnoreOnDirectImport]\nimport a, b\n\n[file a.py]\nimport b  # type: ignore\n\n[file b.py]\nimport c\n\n[file c.py]\n\n[stale]\n\n[case testIncrementalWithTypeIgnoreOnImportFrom]\nimport a, b\n\n[file a.py]\nfrom b import something # type: ignore\n\n[file b.py]\nimport c\nsomething = 3\n\n[file c.py]\n\n[stale]\n\n[case testIncrementalWithPartialTypeIgnore]\nimport a  # type: ignore\nimport a.b\n\n[file a/__init__.py]\n\n[file a/b.py]\n\n[stale]\n\n[case testIncrementalAnyIsDifferentFromIgnore]\nimport b\n\n[file b.py]\nfrom typing import Any\nimport a.b\n\n[file b.py.2]\nfrom typing import Any\n\na = 3  # type: Any\nimport a.b\n\n[file a/__init__.py]\n\n[file a/b.py]\n\n[stale b]\n\n[case testIncrementalSilentImportsAndImportsInClass]\n# flags: --ignore-missing-imports\nclass MyObject(object):\n    from bar import FooBar\n[stale]\n\n[case testIncrementalSameFileSize]\nimport m\n\n[file m.py]\ndef foo(a: int) -> None: pass\ndef bar(a: str) -> None: pass\n\nfoo(3)\n\n[file m.py.2]\ndef foo(a: int) -> None: pass\ndef bar(a: str) -> None: pass\n\nbar(3)\n\n[rechecked m]\n[stale]\n[out2]\ntmp/m.py:4: error: Argument 1 to \"bar\" has incompatible type \"int\"; expected \"str\"\n\n[case testIncrementalUnsilencingModule]\n# cmd: mypy -m main package.subpackage.mod2\n# cmd2: mypy -m main package.subpackage.mod1\n# flags: --follow-imports=skip\n\n[file main.py]\nfrom package.subpackage.mod1 import Class\n\ndef handle(c: Class) -> None:\n    c.some_attribute\n\n[file package/__init__.py]\n# empty\n\n[file package/subpackage/__init__.py]\n# empty\n\n[file package/subpackage/mod1.py]\nimport collections # Any previously unloaded package works here\n\nclass Class: pass\n\n[file package/subpackage/mod2.py]\n# empty\n\n[builtins fixtures/args.pyi]\n[rechecked collections, main, package.subpackage.mod1]\n[stale collections, main, package.subpackage.mod1]\n[out2]\ntmp/main.py:4: error: \"Class\" has no attribute \"some_attribute\"\n\n[case testIncrementalWithIgnores]\nimport foo # type: ignore\n\n[builtins fixtures/module.pyi]\n[stale]\n\n-- Order of processing of files is not stable in this test, skip it in parallel mode.\n-- Note: do not use _no_parallel unless really needed!\n[case testIncrementalWithSilentImportsAndIgnore_no_parallel]\n# cmd: mypy -m main b\n# cmd2: mypy -m main c c.submodule\n# flags: --follow-imports=skip\n\n[file main.py]\nimport a  # type: ignore\nimport b\nimport c\n\na.A().foo()\nb.B().foo()\nc.C().foo()\n\n[file b.py]\nclass B:\n    def foo(self) -> None: pass\n\n[file b.py.2]\n\n[file c/__init__.py]\nclass C: pass\n\n[file c/submodule.py]\nval = 3  # type: int\nif int():\n    val = \"foo\"\n\n[builtins fixtures/module_all.pyi]\n[rechecked main, c, c.submodule]\n[stale main, c, c.submodule]\n[out2]\ntmp/c/submodule.py:3: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ntmp/main.py:7: error: \"C\" has no attribute \"foo\"\n\n[case testIncrementalRemoteError]\nimport m\nm.C().foo().bar()\n[file m.py]\nimport n\nclass C:\n  def foo(self) -> n.A: pass\n[file n.py]\nclass A:\n  def bar(self): pass\n[file n.py.2]\nclass A:\n  pass\n[rechecked m, n]\n[stale n]\n[out2]\nmain:2: error: \"A\" has no attribute \"bar\"\n\n[case testIncrementalRemoteErrorFixed]\nimport m\nm.C().foo().bar()\n[file m.py]\nimport n\nclass C:\n  def foo(self) -> n.A: pass\n[file n.py]\nclass A:\n  pass\n[file n.py.2]\nclass A:\n  def bar(self): pass\n[rechecked m, n]\n[stale n]\n[out1]\nmain:2: error: \"A\" has no attribute \"bar\"\n\n[case testIncrementalChangedError]\nimport m\n[file m.py]\nimport n\ndef accept_int(x: int) -> None: pass\naccept_int(n.foo)\n[file n.py]\nfoo = \"hello\"\nreveal_type(foo)\n[file n.py.2]\nfoo = 3.14\nreveal_type(foo)\n[rechecked m, n]\n[stale n]\n[out1]\ntmp/n.py:2: note: Revealed type is \"builtins.str\"\ntmp/m.py:3: error: Argument 1 to \"accept_int\" has incompatible type \"str\"; expected \"int\"\n[out2]\ntmp/n.py:2: note: Revealed type is \"builtins.float\"\ntmp/m.py:3: error: Argument 1 to \"accept_int\" has incompatible type \"float\"; expected \"int\"\n\n[case testIncrementalReplacingImports]\nimport good, bad, client\n\n[file good.py]\ndef foo(a: int) -> None: pass\n\n[file bad.py]\ndef foo(a: str) -> None: pass\n\n[file client.py]\nimport good\nimport bad\nfrom good import foo\nfoo(3)\n\n[file client.py.2]\nimport good\nimport bad\nfrom bad import foo\nfoo(3)\n\n[rechecked client]\n[stale client]\n[out2]\ntmp/client.py:4: error: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testIncrementalChangingAlias]\nimport m1, m2, m3, m4, m5\n\n[file m1.py]\nfrom m2 import A\ndef accepts_int(x: int) -> None: pass\naccepts_int(A())\n\n[file m2.py]\nfrom m3 import A\n\n[file m3.py]\nfrom m4 import B\nA = B\n\n[file m3.py.2]\nfrom m5 import C\nA = C\n\n[file m4.py]\ndef B() -> int:\n    return 42\n\n[file m5.py]\ndef C() -> str:\n    return \"hello\"\n\n[rechecked m1, m2, m3]\n[stale m3]\n[out2]\ntmp/m1.py:3: error: Argument 1 to \"accepts_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalStoresAliasTypeVars]\nimport a\n\n[file mod.py]\nfrom typing import TypeVar, Union\nT = TypeVar('T')\nAlias = Union[int, T]\nx: Alias[str]\n\n[file a.py]\nfrom mod import Alias, x\n\n[file a.py.2]\nfrom mod import Alias, x\n\nreveal_type(x)\ny: Alias[int]\nreveal_type(y)\n[out2]\ntmp/a.py:3: note: Revealed type is \"builtins.int | builtins.str\"\ntmp/a.py:5: note: Revealed type is \"builtins.int | builtins.int\"\n\n[case testIncrementalSilentImportsWithBlatantError]\n# cmd: mypy -m main\n# flags: --follow-imports=skip\n\n[file main.py]\nfrom evil import Hello\n\n[file main.py.2]\nfrom evil import Hello\nreveal_type(Hello())\n\n[file evil.py]\ndef accept_int(x: int) -> None: pass\naccept_int(\"not an int\")\n\n[rechecked main]\n[stale]\n[out2]\ntmp/main.py:2: note: Revealed type is \"Any\"\n\n[case testIncrementalImportIsNewlySilenced]\n# cmd: mypy -m main foo\n# cmd2: mypy -m main\n# flags: --follow-imports=skip\n\n[file main.py]\nfrom foo import bar\ndef accept_int(x: int) -> None: pass\naccept_int(bar)\n\n[file foo.py]\nbar = 3\n\n[file foo.py.2]\n# Empty!\n\n[rechecked main]\n[stale main]\n\n[case testIncrementalSilencedModuleNoLongerCausesError]\n# cmd: mypy -m main evil\n# cmd2: mypy -m main\n# flags: --follow-imports=skip\n\n[file main.py]\nfrom evil import bar\ndef accept_int(x: int) -> None: pass\naccept_int(bar)\nreveal_type(bar)\n\n[file evil.py]\nbar = \"str\"\n\n[rechecked main]\n[stale main]\n[out1]\ntmp/main.py:3: error: Argument 1 to \"accept_int\" has incompatible type \"str\"; expected \"int\"\ntmp/main.py:4: note: Revealed type is \"builtins.str\"\n[out2]\ntmp/main.py:4: note: Revealed type is \"Any\"\n\n[case testIncrementalFixedBugCausesPropagation]\nimport mod1\n\n[file mod1.py]\nfrom mod2 import A\nval = A().makeB().makeC().foo()\nreveal_type(val)\n\n[file mod2.py]\nfrom mod3 import B\nclass A:\n    def makeB(self) -> B: return B()\n\n[file mod3.py]\nfrom mod4 import C\nclass B:\n    def makeC(self) -> C:\n        val = 3  # type: int\n        if 1:\n            val = \"str\"   # deliberately triggering error\n            return C()\n\n[file mod3.py.2]\nfrom mod4 import C\nclass B:\n    def makeC(self) -> C: return C()\n\n[file mod4.py]\nclass C:\n    def foo(self) -> int: return 1\n\n[rechecked mod3]\n[stale]\n[out1]\ntmp/mod3.py:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ntmp/mod1.py:3: note: Revealed type is \"builtins.int\"\n\n[out2]\ntmp/mod1.py:3: note: Revealed type is \"builtins.int\"\n\n[case testIncrementalIncidentalChangeWithBugCausesPropagation]\nimport mod1\n\n[file mod1.py]\nfrom mod2 import A\nval = A().makeB().makeC().foo()\nreveal_type(val)\n\n[file mod2.py]\nfrom mod3 import B\nclass A:\n    def makeB(self) -> B: return B()\n\n[file mod3.py]\nfrom mod4 import C\nclass B:\n    def makeC(self) -> C:\n        val = 3  # type: int\n        if 1:\n            val = \"str\"   # deliberately triggering error\n            return C()\n\n[file mod4.py]\nclass C:\n    def foo(self) -> int: return 1\n\n[file mod4.py.2]\nclass C:\n    def foo(self) -> str: return 'a'\n\n[rechecked mod4, mod3, mod1]\n[stale mod1, mod4]\n[out1]\ntmp/mod3.py:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ntmp/mod1.py:3: note: Revealed type is \"builtins.int\"\n\n[out2]\ntmp/mod3.py:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ntmp/mod1.py:3: note: Revealed type is \"builtins.str\"\n\n[case testIncrementalIncidentalChangeWithBugFixCausesPropagation]\nimport mod1\n\n[file mod1.py]\nfrom mod2 import A\nval = A().makeB().makeC().foo()\nreveal_type(val)\n\n[file mod2.py]\nfrom mod3 import B\nclass A:\n    def makeB(self) -> B: return B()\n\n[file mod3.py]\nfrom mod4 import C\nclass B:\n    def makeC(self) -> C:\n        val = 3  # type: int\n        if 1:\n            val = \"str\"   # deliberately triggering error\n            return C()\n\n[file mod3.py.2]\nfrom mod4 import C\nclass B:\n    def makeC(self) -> C: return C()\n\n[file mod4.py]\nclass C:\n    def foo(self) -> int: return 1\n\n[file mod4.py.2]\nclass C:\n    def foo(self) -> str: return 'a'\n\n[rechecked mod4, mod3, mod1]\n[stale mod1, mod4]\n[out1]\ntmp/mod3.py:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ntmp/mod1.py:3: note: Revealed type is \"builtins.int\"\n\n[out2]\ntmp/mod1.py:3: note: Revealed type is \"builtins.str\"\n\n[case testIncrementalSilentImportsWithInnerImports]\n# cmd: mypy -m main foo\n# flags: --ignore-missing-imports\n\n[file main.py]\nfrom foo import MyClass\nm = MyClass()\n\n[file main.py.2]\nfrom foo import MyClass\nm = MyClass()\nreveal_type(m.val)\n\n[file foo.py]\nclass MyClass:\n    def __init__(self) -> None:\n        import unrelated\n        self.val = unrelated.test()\n\n[rechecked main]\n[stale]\n[out2]\ntmp/main.py:3: note: Revealed type is \"Any\"\n\n[case testIncrementalSilentImportsWithInnerImportsAndNewFile]\n# cmd: mypy -m main foo\n# cmd2: mypy -m main foo unrelated\n# flags: --follow-imports=skip\n\n[file main.py]\nfrom foo import MyClass\nm = MyClass()\n\n[file main.py.2]\nfrom foo import MyClass\nm = MyClass()\nreveal_type(m.val)\n\n[file foo.py]\nclass MyClass:\n    def __init__(self) -> None:\n        import unrelated\n        self.val = unrelated.test()\n\n[file unrelated.py]\ndef test() -> str: return \"foo\"\n\n[rechecked main, foo, unrelated]\n[stale foo, unrelated]\n[out2]\ntmp/main.py:3: note: Revealed type is \"builtins.str\"\n\n[case testIncrementalWorksWithNestedClasses]\nimport foo\n\n[file foo.py]\nclass MyClass:\n    class NestedClass:\n        pass\n\n    class_attr = NestedClass()\n\n[rechecked]\n[stale]\n\n[case testIncrementalWorksWithBasicProtocols]\nimport a\n[file a.py]\nfrom b import P\n\nx: int\ny: P[int]\nx = y.meth()\n\nclass C:\n    def meth(self) -> int:\n        pass\ny = C()\n\n[file a.py.2]\nfrom b import P\n\nx: str\ny: P[str]\nx = y.meth()\n\nclass C:\n    def meth(self) -> str:\n        pass\ny = C()\n[file b.py]\nfrom typing import Protocol, TypeVar\n\nT = TypeVar('T', covariant=True)\nclass P(Protocol[T]):\n    def meth(self) -> T:\n        pass\n\n[case testIncrementalSwitchFromNominalToStructural]\nimport a\n[file a.py]\nfrom b import B, fun\nclass C(B):\n    def x(self) -> int: pass\n    def y(self) -> int: pass\nfun(C())\n\n[file b.py]\nfrom typing import Protocol\nclass B:\n    def x(self) -> float: pass\ndef fun(arg: B) -> None:\n    arg.x()\n\n[file b.py.2]\nfrom typing import Protocol\nclass B(Protocol):\n    def x(self) -> float: pass\ndef fun(arg: B) -> None:\n    arg.x()\n\n[file a.py.3]\nfrom b import fun\nclass C:\n    def x(self) -> int: pass\n    def y(self) -> int: pass\nfun(C())\n[out1]\n[out2]\n[out3]\n\n[case testIncrementalSwitchFromStructuralToNominal]\nimport a\n[file a.py]\nfrom b import fun\nclass C:\n    def x(self) -> int: pass\n    def y(self) -> int: pass\nfun(C())\n\n[file b.py]\nfrom typing import Protocol\nclass B(Protocol):\n    def x(self) -> float: pass\ndef fun(arg: B) -> None:\n    arg.x()\n\n[file b.py.2]\nfrom typing import Protocol\nclass B:\n    def x(self) -> float: pass\ndef fun(arg: B) -> None:\n    arg.x()\n\n[out1]\n[out2]\ntmp/a.py:5: error: Argument 1 to \"fun\" has incompatible type \"C\"; expected \"B\"\n\n[case testIncrementalWorksWithNamedTuple]\nimport foo\n\n[file foo.py]\nfrom mid import MyTuple\ndef accept_int(x: int) -> None: pass\naccept_int(MyTuple(1, \"b\", \"c\").a)\n\n[file mid.py]\nfrom bar import MyTuple\n\n[file bar.py]\nfrom typing import NamedTuple\nMyTuple = NamedTuple('MyTuple', [\n    ('a', int),\n    ('b', str),\n    ('c', str)\n])\n\n[file bar.py.2]\nfrom typing import NamedTuple\nMyTuple = NamedTuple('MyTuple', [\n    ('b', int),  # a and b are swapped\n    ('a', str),\n    ('c', str)\n])\n\n[rechecked bar, mid, foo]\n[stale bar]\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/foo.py:3: error: Argument 1 to \"accept_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalWorksWithNestedNamedTuple]\nimport foo\n\n[file foo.py]\nfrom mid import Outer\ndef accept_int(x: int) -> None: pass\naccept_int(Outer.MyTuple(1, \"b\", \"c\").a)\n\n[file mid.py]\nfrom bar import Outer\n\n[file bar.py]\nfrom typing import NamedTuple\nclass Outer:\n    MyTuple = NamedTuple('MyTuple', [\n        ('a', int),\n        ('b', str),\n        ('c', str)\n    ])\n\n[file bar.py.2]\nfrom typing import NamedTuple\nclass Outer:\n    MyTuple = NamedTuple('MyTuple', [\n        ('b', int),  # a and b are swapped\n        ('a', str),\n        ('c', str)\n    ])\n\n[rechecked bar, mid, foo]\n[stale bar]\n[builtins fixtures/tuple.pyi]\n[out2]\ntmp/foo.py:3: error: Argument 1 to \"accept_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalPartialSubmoduleUpdate]\n# cmd: mypy -m a\n# cmd2: mypy -m a a.c\n# flags: --follow-imports=skip\n\n[file a/__init__.py]\nfrom .b import B\nfrom .c import C\n\n[file a/b.py]\nclass B: pass\n\n[file a/c.py]\nclass C: pass\n\n[file a/c.py.2]\nclass C: pass\npass\n\n[rechecked a, a.c]\n[stale a, a.c]\n[out]\n\n[case testIncrementalNestedClassRef]\nimport top\n\n[file top.py]\nfrom funcs import callee\nfrom classes import Outer\ndef caller(a: Outer.Inner) -> None:\n    callee(a)\n\n[file funcs.py]\nfrom classes import Outer\ndef callee(a: Outer.Inner) -> None:\n    pass\n\n[file classes.py]\nclass Outer:\n    class Inner:\n        pass\n\n[file top.py.2]\nfrom funcs import callee\nfrom classes import Outer\ndef caller(a: Outer.Inner) -> int:\n    callee(a)\n    return 0\n\n[case testIncrementalLoadsParentAfterChild]\n# cmd: mypy -m r.s\n\n[file r/__init__.py]\nfrom . import s\n\n[file r/m.py]\nclass R: pass\n\n[file r/s.py]\nfrom . import m\nR = m.R\na: R\n\n[file r/s.py.2]\nfrom . import m\nR = m.R\na: R\n\n[case testIncrementalBaseClassAttributeConflict]\nclass A: pass\nclass B: pass\n\nclass X:\n    attr: A\nclass Y:\n    attr: B\nclass Z(X, Y): pass\n[stale]\n[out]\nmain:8: error: Definition of \"attr\" in base class \"X\" is incompatible with definition in base class \"Y\"\n[out2]\nmain:8: error: Definition of \"attr\" in base class \"X\" is incompatible with definition in base class \"Y\"\n\n[case testIncrementalFollowImportsSilent]\n# flags: --follow-imports=silent\nimport a\n[file a.py]\nx = 0\n[file a.py.2]\nx = 0\nx + ''\n\n[case testIncrementalFollowImportsSkip]\n# flags: --follow-imports=skip\nimport a\nreveal_type(a.x)\n[file a.py]\n/\n[file a.py.2]\n//\n[out]\nmain:3: note: Revealed type is \"Any\"\n[out2]\nmain:3: note: Revealed type is \"Any\"\n\n[case testIncrementalFollowImportsError]\n# flags: --follow-imports=error\nimport a\n[file a.py]\n/\n[file a.py.2]\n//\n[out1]\nmain:2: error: Import of \"a\" ignored\nmain:2: note: (Using --follow-imports=error, module not passed on command line)\n[out2]\nmain:2: error: Import of \"a\" ignored\nmain:2: note: (Using --follow-imports=error, module not passed on command line)\n\n[case testIncrementalFollowImportsVariable]\n# flags: --config-file tmp/mypy.ini\nimport a\nreveal_type(a.x)\n[file a.py]\nx = 0\n[file mypy.ini]\n\\[mypy]\nfollow_imports = normal\n[file mypy.ini.2]\n\\[mypy]\nfollow_imports = skip\n[out1]\nmain:3: note: Revealed type is \"builtins.int\"\n[out2]\nmain:3: note: Revealed type is \"Any\"\n\n\n[case testIncrementalFollowImportsVariablePyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport a\nreveal_type(a.x)\n\n[file a.py]\nx = 0\n\n[file pyproject.toml]\n\\[tool.mypy]\nfollow_imports = 'normal'\n\n[file pyproject.toml.2]\n\\[tool.mypy]\nfollow_imports = 'skip'\n\n[out1]\nmain:3: note: Revealed type is \"builtins.int\"\n\n[out2]\nmain:3: note: Revealed type is \"Any\"\n\n\n[case testIncrementalIgnoreErrors]\n# flags: --config-file tmp/mypy.ini\nimport a\n[file a.py]\nimport module_that_will_be_deleted\n[file module_that_will_be_deleted.py]\n\n[file mypy.ini]\n\\[mypy]\n\\[mypy-a]\nignore_errors = True\n[delete module_that_will_be_deleted.py.2]\n[out1]\n[out2]\n\n[case testIncrementalNamedTupleInMethod]\nfrom ntcrash import nope\n[file ntcrash.py]\nfrom typing import NamedTuple\nclass C:\n    def f(self) -> None:\n        A = NamedTuple('A', [('x', int), ('y', int)])\n[builtins fixtures/tuple.pyi]\n[out1]\nmain:1: error: Module \"ntcrash\" has no attribute \"nope\"\n[out2]\nmain:1: error: Module \"ntcrash\" has no attribute \"nope\"\n\n[case testIncrementalNamedTupleInMethod2]\nfrom ntcrash import nope\n[file ntcrash.py]\nfrom typing import NamedTuple\nclass C:\n    class D:\n        def f(self) -> None:\n            A = NamedTuple('A', [('x', int), ('y', int)])\n[builtins fixtures/tuple.pyi]\n[out1]\nmain:1: error: Module \"ntcrash\" has no attribute \"nope\"\n[out2]\nmain:1: error: Module \"ntcrash\" has no attribute \"nope\"\n\n[case testIncrementalNamedTupleInMethod3]\nfrom ntcrash import nope\n[file ntcrash.py]\nfrom typing import NamedTuple\nclass C:\n    def a(self):\n        class D:\n            def f(self) -> None:\n                A = NamedTuple('A', [('x', int), ('y', int)])\n[builtins fixtures/tuple.pyi]\n[out1]\nmain:1: error: Module \"ntcrash\" has no attribute \"nope\"\n[out2]\nmain:1: error: Module \"ntcrash\" has no attribute \"nope\"\n\n[case testIncrementalTypedDictInMethod]\nfrom tdcrash import nope\n[file tdcrash.py]\nfrom typing import TypedDict\nclass C:\n    def f(self) -> None:\n        A = TypedDict('A', {'x': int, 'y': int})\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out1]\nmain:1: error: Module \"tdcrash\" has no attribute \"nope\"\n[out2]\nmain:1: error: Module \"tdcrash\" has no attribute \"nope\"\n\n[case testIncrementalTypedDictInMethod2]\nfrom tdcrash import nope\n[file tdcrash.py]\nfrom typing import TypedDict\nclass C:\n    class D:\n        def f(self) -> None:\n            A = TypedDict('A', {'x': int, 'y': int})\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out1]\nmain:1: error: Module \"tdcrash\" has no attribute \"nope\"\n[out2]\nmain:1: error: Module \"tdcrash\" has no attribute \"nope\"\n\n[case testIncrementalTypedDictInMethod3]\nfrom tdcrash import nope\n[file tdcrash.py]\nfrom typing import TypedDict\nclass C:\n    def a(self):\n        class D:\n            def f(self) -> None:\n                A = TypedDict('A', {'x': int, 'y': int})\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out1]\nmain:1: error: Module \"tdcrash\" has no attribute \"nope\"\n[out2]\nmain:1: error: Module \"tdcrash\" has no attribute \"nope\"\n\n[case testIncrementalNewTypeInMethod]\nfrom ntcrash import nope\n[file ntcrash.py]\nfrom typing import NewType, NamedTuple, TypedDict\nclass C:\n    def f(self) -> None:\n        X = NewType('X', int)\n        A = TypedDict('A', {'x': X, 'y': int})\n        B = NamedTuple('B', [('x', X)])\n\ndef f() -> None:\n    X = NewType('X', int)\n    A = TypedDict('A', {'x': X, 'y': int})\n    B = NamedTuple('B', [('x', X)])\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out1]\nmain:1: error: Module \"ntcrash\" has no attribute \"nope\"\n[out2]\nmain:1: error: Module \"ntcrash\" has no attribute \"nope\"\n\n[case testIncrementalInnerClassAttrInMethod]\nimport crash\nnonexisting\n[file crash.py]\nclass C:\n    def f(self) -> None:\n        class A:\n            pass\n        self.a = A()\n[out1]\nmain:2: error: Name \"nonexisting\" is not defined\n[out2]\nmain:2: error: Name \"nonexisting\" is not defined\n\n[case testIncrementalInnerClassAttrInMethodReveal]\nimport crash\nreveal_type(crash.C().a)\nreveal_type(crash.D().a)\n[file crash.py]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass C:\n    def f(self) -> None:\n        class A:\n            pass\n        self.a = A()\nreveal_type(C().a)\nclass D:\n    def f(self) -> None:\n        class A:\n            def g(self) -> None:\n                class B(Generic[T]):\n                    pass\n                self.b = B[int]()\n        self.a = A().b\nreveal_type(D().a)\n[out1]\ntmp/crash.py:8: note: Revealed type is \"crash.A@5\"\ntmp/crash.py:17: note: Revealed type is \"crash.B@13[builtins.int]\"\nmain:2: note: Revealed type is \"crash.A@5\"\nmain:3: note: Revealed type is \"crash.B@13[builtins.int]\"\n[out2]\ntmp/crash.py:8: note: Revealed type is \"crash.A@5\"\ntmp/crash.py:17: note: Revealed type is \"crash.B@13[builtins.int]\"\nmain:2: note: Revealed type is \"crash.A@5\"\nmain:3: note: Revealed type is \"crash.B@13[builtins.int]\"\n\n[case testGenericMethodRestoreMetaLevel]\nfrom typing import Dict\n\nd = {}  # type: Dict[str, int]\ng = d.get  # This should not crash: see https://github.com/python/mypy/issues/2804\n[builtins fixtures/dict.pyi]\n\n[case testGenericMethodRestoreMetaLevel2]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\nclass D:\n    def m(self, x: T) -> T:\n        return x\n\ng = D().m  # This should not crash: see https://github.com/python/mypy/issues/2804\n[builtins fixtures/dict.pyi]\n\n[case testGenericMethodRestoreMetaLevel3]\nfrom typing import TypeVar\nT = TypeVar('T')\n\nclass C:\n    def m(self, x: T) -> T:\n        return x\n\nclass D(C):\n    def __init__(self) -> None:\n        self.d = super().m # This should not crash: see https://github.com/python/mypy/issues/2804\n[builtins fixtures/dict.pyi]\n\n[case testIncrementalPerFileFlags]\n# flags: --config-file tmp/mypy.ini\nimport a\n[file a.py]\npass\n[file mypy.ini]\n\\[mypy]\nwarn_no_return = False\n\\[mypy-a]\nwarn_no_return = True\n[rechecked]\n\n[case testIncrementalClassVar]\nfrom typing import ClassVar\nclass A:\n    x: ClassVar\nA().x = 0\n[out1]\nmain:4: error: Cannot assign to class variable \"x\" via instance\n[out2]\nmain:4: error: Cannot assign to class variable \"x\" via instance\n\n[case testIncrementalClassVarGone]\nimport m\nm.A().x = 0\n[file m.py]\nfrom typing import ClassVar\nclass A:\n    x: ClassVar[int]\n[file m.py.2]\nclass A:\n    x: int\n[out1]\nmain:2: error: Cannot assign to class variable \"x\" via instance\n\n[case testCachingClassVar]\nimport b\n[file a.py]\nfrom typing import ClassVar\nclass A:\n    x: ClassVar[int]\n[file b.py]\nimport a\n[file b.py.2]\nimport a\na.A().x = 0\n[out2]\ntmp/b.py:2: error: Cannot assign to class variable \"x\" via instance\n\n[case testSerializeTypedDict]\nimport b\nreveal_type(b.x)\ny: b.A\nreveal_type(y)\n[file b.py]\nfrom typing import TypedDict\nA = TypedDict('A', {'x': int, 'y': str})\nx: A\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out1]\nmain:2: note: Revealed type is \"TypedDict('b.A', {'x': builtins.int, 'y': builtins.str})\"\nmain:4: note: Revealed type is \"TypedDict('b.A', {'x': builtins.int, 'y': builtins.str})\"\n[out2]\nmain:2: note: Revealed type is \"TypedDict('b.A', {'x': builtins.int, 'y': builtins.str})\"\nmain:4: note: Revealed type is \"TypedDict('b.A', {'x': builtins.int, 'y': builtins.str})\"\n\n[case testSerializeMetaclass]\nimport b\nreveal_type(b.A.f())\nm: b.M = b.A\nreveal_type(b.a.f())\n[file b.py]\nfrom typing import Type\n\nclass M(type):\n    def f(cls) -> int: return 0\nclass A(metaclass=M): pass\na: Type[A]\n[out]\nmain:2: note: Revealed type is \"builtins.int\"\nmain:4: note: Revealed type is \"builtins.int\"\n[out2]\nmain:2: note: Revealed type is \"builtins.int\"\nmain:4: note: Revealed type is \"builtins.int\"\n\n[case testSerializeMetaclassInImportCycle1]\nimport b\nimport c\nreveal_type(b.A.f())\nm: c.M = b.A\nreveal_type(b.a.f())\n[file b.py]\nfrom typing import Type\nfrom c import M\nclass A(metaclass=M): pass\na: Type[A]\n[file c.py]\nclass M(type):\n    def f(cls) -> int: return 0\n[out]\nmain:3: note: Revealed type is \"builtins.int\"\nmain:5: note: Revealed type is \"builtins.int\"\n[out2]\nmain:3: note: Revealed type is \"builtins.int\"\nmain:5: note: Revealed type is \"builtins.int\"\n\n[case testSerializeMetaclassInImportCycle2]\nimport b\nimport c\nreveal_type(c.A.f())\nm: b.M = c.A\nreveal_type(c.a.f())\n[file b.py]\nfrom c import a\nclass M(type):\n    def f(cls) -> int: return 0\n[file c.py]\nfrom typing import Type\nimport b\nclass A(metaclass=b.M): pass\na: Type[A]\n[out]\nmain:3: note: Revealed type is \"builtins.int\"\nmain:5: note: Revealed type is \"builtins.int\"\n[out2]\nmain:3: note: Revealed type is \"builtins.int\"\nmain:5: note: Revealed type is \"builtins.int\"\n\n[case testDeleteFile]\nimport n\n[file n.py]\nimport m\n[file m.py]\nx = 1\n[delete m.py.2]\n[rechecked n]\n[stale n]\n[out2]\ntmp/n.py:1: error: Cannot find implementation or library stub for module named \"m\"\ntmp/n.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testDeleteFileWithinCycle]\nimport a\n[file a.py]\nimport b\n[file b.py]\nimport c\n[file c.py]\nimport a\n[file a.py.2]\nimport c\n[delete b.py.2]\n[rechecked a, c]\n[stale a]\n[out2]\n\n[case testThreePassesBasic]\nimport m\n[file m.py]\ndef foo():\n    pass\n[file m.py.2]\ndef foo() -> None:\n    pass\n[file m.py.3]\ndef foo():\n    pass\n[rechecked m]\n[stale m]\n[rechecked2 m]\n[stale2 m]\n[out3]\n\n[case testThreePassesErrorInThirdPass]\nimport m\n[file m.py]\ndef foo():\n    pass\n[file m.py.2]\ndef foo() -> None:\n    pass\n[file m.py.3]\ndef foo() -> int:\n    return ''\n[rechecked m]\n[stale m]\n[rechecked2 m]\n[stale2 m]\n[out3]\ntmp/m.py:2: error: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testThreePassesThirdPassFixesError]\nimport n\n[file n.py]\nimport m\nx = m.foo(1)\n[file m.py]\ndef foo(x):\n    pass\n[file m.py.2]\ndef foo() -> str:\n    pass\n[file m.py.3]\ndef foo(x) -> int:\n    pass\n[rechecked m, n]\n[stale m, n]\n[rechecked2 m, n]\n[stale2 m, n]\n[out2]\ntmp/n.py:2: error: Too many arguments for \"foo\"\n[out3]\n\n[case testCacheDeletedAfterErrorsFound]\nimport a\n[file a.py]\nfrom b import x\n[file b.py]\nfrom c import x\n[file c.py]\nx = 1\n[file c.py.2]\n1 + 1\n[file a.py.3]\nfrom b import x\n1 + 1\n[out]\n[out2]\ntmp/b.py:1: error: Module \"c\" has no attribute \"x\"\n[out3]\ntmp/b.py:1: error: Module \"c\" has no attribute \"x\"\n\n[case testCacheDeletedAfterErrorsFound2]\n\nimport a\n[file a.py]\nfrom b import x\n[file b.py]\nfrom c import C\nx: C\n[file c.py]\nclass C: pass\n[file c.py.2]\ndef C(): pass\n[file a.py.3]\nfrom b import x\n1 + 1\n[out]\n[out2]\ntmp/b.py:2: error: Function \"c.C\" is not valid as a type\ntmp/b.py:2: note: Perhaps you need \"Callable[...]\" or a callback protocol?\n[out3]\ntmp/b.py:2: error: Function \"c.C\" is not valid as a type\ntmp/b.py:2: note: Perhaps you need \"Callable[...]\" or a callback protocol?\n\n[case testCacheDeletedAfterErrorsFound3]\nimport a\n[file a.py]\nimport b\nb.f()\n[file b.py]\ndef f() -> None: pass\n[file b.py.2]\ndef f(x) -> None: pass\n[out]\n[out2]\ntmp/a.py:2: error: Missing positional argument \"x\" in call to \"f\"\n[out3]\ntmp/a.py:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testCacheDeletedAfterErrorsFound4]\nimport a\n[file a.py]\nfrom b import x\n[file b.py]\nfrom c import x\n[file c.py]\nfrom d import x\n[file d.py]\nx = 1\n[file d.py.2]\n1 + 1\n[file a.py.3]\nfrom b import x\n1 + 1\n[out]\n[out2]\ntmp/c.py:1: error: Module \"d\" has no attribute \"x\"\n[out3]\ntmp/c.py:1: error: Module \"d\" has no attribute \"x\"\n\n[case testNoCrashOnDeletedWithCacheOnCmdline]\n# cmd: mypy -m nonexistent\n# cmd2: mypy -m nonexistent\n[file nonexistent.py]\n[delete nonexistent.py.2]\n[out]\n[out2]\nmypy: error: cannot read file 'tmp/nonexistent.py': No such file or directory\n\n[case testSerializeAbstractPropertyIncremental]\nfrom abc import abstractmethod\nimport typing\nclass A:\n    @property\n    def f(self) -> int:\n        return 1\n    @f.setter  # type: ignore\n    @abstractmethod\n    def f(self, x: int) -> None:\n        pass\na = A()\n[builtins fixtures/property.pyi]\n\n[case testSerializeAbstractPropertyDisallowUntypedIncremental]\n# flags: --disallow-untyped-defs\nfrom abc import abstractmethod\nimport typing\nclass A:\n    @property\n    def f(self) -> int:\n        return 1\n    @f.setter  # type: ignore\n    @abstractmethod\n    def f(self, x: int) -> None:\n        pass\na = A()\n[builtins fixtures/property.pyi]\n\n[case testClassNamesResolutionCrashAccess]\nimport mod\n\n[file mod.py]\nclass C:\n    def __init__(self) -> None:\n        self.int = ''\n\n    def f(self, f: int) -> None:\n        pass\n\n[file mod.py.2]\nclass C:\n    def __init__(self) -> None:\n        self.int = ''\n\n    def f(self, f: int) -> None:\n        f.x\n\n[out]\n[out2]\ntmp/mod.py:6: error: \"int\" has no attribute \"x\"\n\n[case testClassNamesResolutionCrashReadCache]\nimport mod\n\n[file mod.py]\nimport submod\n\n[file mod.py.2]\nfrom submod import C\n\nc = C()\nreveal_type(c.int)\nreveal_type(c.y)\n\n[file submod.py]\nfrom typing import List\n\nclass C:\n    def __init__(self) -> None:\n        self.int = []  # type: List[int]\n\n    def f(self, f: int) -> None:\n        self.y = f\n\n[builtins fixtures/list.pyi]\n[out]\n[out2]\ntmp/mod.py:4: note: Revealed type is \"builtins.list[builtins.int]\"\ntmp/mod.py:5: note: Revealed type is \"builtins.int\"\n\n[case testClassNamesResolutionCrashReveal]\nimport mod\n\n[file mod.py]\nclass Foo(object):\n\n    def __init__(self) -> None:\n        self.bytes = b\"foo\"\n\n    def bar(self, f: bytes):\n        pass\n\nfoo = Foo()\nfoo.bar(b\"test\")\n\n[file mod.py.2]\nclass Foo(object):\n\n    def __init__(self) -> None:\n        self.bytes = b\"foo\"\n\n    def bar(self, f: bytes):\n        reveal_type(f)\n\nfoo = Foo()\nfoo.bar(b\"test\")\n[out]\n[out2]\ntmp/mod.py:7: note: Revealed type is \"builtins.bytes\"\n\n[case testIncrementalWithSilentImports]\n# cmd: mypy -m a\n# cmd2: mypy -m b\n# flags: --follow-imports=silent\n[file a.py]\nimport b\n\nb.foo(1, 2)\n\n[file b.py]\ndef foo(a: int, b: int) -> str:\n    return a + b\n\n[out1]\n[out2]\ntmp/b.py:2: error: Incompatible return value type (got \"int\", expected \"str\")\n\n[case testIncrementalWithSilentImportsReverse]\n-- Same commands as previous test, just in reverse order.\n-- expected output is also in reverse order\n# cmd: mypy -m b\n# cmd2: mypy -m a\n# flags: --follow-imports=silent\n[file a.py]\nimport b\n\nb.foo(1, 2)\n\n[file b.py]\ndef foo(a: int, b: int) -> str:\n    return a + b\n\n[out]\ntmp/b.py:2: error: Incompatible return value type (got \"int\", expected \"str\")\n[out2]\n\n[case testForwardNamedTupleToUnionWithOtherNamedTUple]\nfrom typing import NamedTuple, Union\n\nclass Person(NamedTuple):\n    name: Union[str, \"Pair\"]\n\nclass Pair(NamedTuple):\n    first: str\n    last: str\n\nPerson(name=Pair(first=\"John\", last=\"Doe\"))\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNoCrashForwardRefToBrokenDoubleNewTypeIncremental]\nfrom typing import Any, List, NewType\n\nFoo = NewType('NotFoo', int) # type: ignore\nFoos = NewType('Foos', List[Foo]) # type: ignore\n\ndef frob(foos: List[Foos]) -> None:\n    pass\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNoCrashForwardRefOverloadIncremental]\nfrom typing import overload, List\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: F) -> F: ...\ndef f(x):\n    pass\n\nF = List[int]\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNoCrashForwardRefOverloadIncrementalClass]\nfrom typing import overload, Tuple, NamedTuple\n\nx: C\nclass C:\n    @overload\n    def f(self, x: str) -> N: pass\n    @overload\n    def f(self, x: int) -> int: pass\n    def f(self, x):\n        pass\n\nclass N(NamedTuple):\n    x: A\nA = Tuple[int]\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNewTypeFromForwardNamedTupleIncremental]\nfrom typing import NewType, NamedTuple, Tuple\n\nNT = NewType('NT', 'N')\nclass N(NamedTuple):\n    x: int\n\nx: NT = N(1) # type: ignore\nx = NT(N(1))\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNewTypeFromForwardTypedDictIncremental]\nfrom typing import NewType, Tuple, TypedDict, Dict\n\nNT = NewType('NT', N) # type: ignore\nclass N(TypedDict):\n    x: A\nA = Dict[str, int]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n-- Some crazy self-referential named tuples, types dicts, and aliases\n-- to be sure that everything can be _serialized_ (i.e. ForwardRefs are removed).\n-- For this reason errors are silenced (tests with # type: ignore have equivalents in other files)\n\n[case testForwardTypeAliasInBase1]\nfrom typing import List\nclass C(List['A']):\n    pass\n\nA = List[int]\nx: int = C()[0][0]\n[builtins fixtures/list.pyi]\n[out]\n\n[case testForwardTypeAliasInBase2]\n\nfrom typing import List, Generic, TypeVar, NamedTuple\nT = TypeVar('T')\n\nclass C(A, B): # type: ignore\n    pass\nclass G(Generic[T]): pass\nA = G[C] # type: ignore\nclass B(NamedTuple):\n    x: int\n\nC(1).x\nC(1)[0]\n[builtins fixtures/list.pyi]\n[out]\n\n[case testSerializeRecursiveAlias]\nfrom typing import Callable, Union\n\nNode = Union[str, int, Callable[[], \"Node\"]]\nn: Node\n[out]\n\n[case testSerializeRecursiveAliases1]\n\nfrom typing import Type, Callable, Union\n\nA = Union[A, int]  # type: ignore\nB = Callable[[B], int] # type: ignore\nC = Type[C] # type: ignore\n[out]\n\n[case testSerializeRecursiveAliases2]\n\nfrom typing import Type, Callable, Union\n\nA = Union[B, int]  # type: ignore\nB = Callable[[C], int] # type: ignore\nC = Type[A] # type: ignore\n[out]\n\n[case testSerializeRecursiveAliases3]\n\nfrom typing import Type, Callable, Union, NamedTuple\n\nA = Union[B, int]  # type: ignore\nB = Callable[[C], int] # type: ignore\nclass C(NamedTuple): # type: ignore\n    x: A\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testGenericTypeAliasesForwardAnyIncremental1]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nIntNode = Node[int, S]  # type: ignore[used-before-def]\nAnyNode = Node[S, T]  # type: ignore[used-before-def]\n\nclass Node(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None:\n        self.x = x\n        self.y = y\n\ndef output() -> IntNode[str]:\n    return Node(1, 'x')\nx = output() # type: IntNode\n\ny: IntNode\ny.x = 1\ny.y = 1\ny.y = 'x'\n\nz = Node(1, 'x') # type: AnyNode\n[out]\n\n[case testGenericTypeAliasesForwardAnyIncremental2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass Node(Generic[T, S]):\n    def __init__(self, x: T, y: S) -> None:\n        self.x = x\n        self.y = y\n\ndef output() -> IntNode[str]:\n    return Node(1, 'x')\nx = output() # type: IntNode\n\ny: IntNode\ny.x = 1\ny.y = 1\ny.y = 'x'\n\nz = Node(1, 'x') # type: AnyNode\nIntNode = Node[int, S]\nAnyNode = Node[S, T]\n[out]\n\n[case testNamedTupleForwardAsUpperBoundSerialization]\nfrom typing import NamedTuple, TypeVar, Generic\nT = TypeVar('T', bound='M')\nclass G(Generic[T]):\n    x: T\n\nyg: G[M]\nz: int = G[M]().x.x  # type: ignore[used-before-def]\nz = G[M]().x[0]  # type: ignore[used-before-def]\nM = NamedTuple('M', [('x', int)])\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testSelfRefNTIncremental1]\n\nfrom typing import Tuple, NamedTuple\n\nNode = NamedTuple('Node', [\n        ('name', str),\n        ('children', Tuple['Node', ...]), # type: ignore\n    ])\nn: Node\n[builtins fixtures/tuple.pyi]\n\n[case testSelfRefNTIncremental2]\n\nfrom typing import Tuple, NamedTuple\n\nA = NamedTuple('A', [\n        ('x', str),\n        ('y', Tuple['B', ...]), # type: ignore\n    ])\nclass B(NamedTuple):\n    x: A\n    y: int\n\nn: A\n[builtins fixtures/tuple.pyi]\n\n[case testSelfRefNTIncremental3]\n\nfrom typing import NamedTuple, Tuple\n\nclass B(NamedTuple):\n    x: Tuple[A, int] # type: ignore\n    y: int\nA = NamedTuple('A', [\n        ('x', str),\n        ('y', 'B'),\n    ])\nn: B\nm: A\nlst = [m, n]\n[builtins fixtures/tuple.pyi]\n\n[case testSelfRefNTIncremental4]\n\nfrom typing import NamedTuple\n\nclass B(NamedTuple):\n    x: A # type: ignore\n    y: int\nclass A(NamedTuple):\n    x: str\n    y: B\n\nn: A\n[builtins fixtures/tuple.pyi]\n\n[case testSelfRefNTIncremental5]\n\nfrom typing import NamedTuple\n\nB = NamedTuple('B', [\n        ('x', A), # type: ignore\n        ('y', int),\n    ])\nA = NamedTuple('A', [\n        ('x', str),\n        ('y', 'B'),\n    ])\nn: A\ndef f(m: B) -> None: pass\n[builtins fixtures/tuple.pyi]\n\n[case testCrashWithPartialGlobalAndCycle]\nimport bar\n\n[file foo.py]\nimport bar\nmy_global_dict = {}  # type: ignore\ndef external_func_0() -> None:\n    global my_global_dict\n    bar.external_list\n    my_global_dict[12] = 0\n\n[file bar.py]\nimport foo\n\nexternal_list = [0]\n\n[builtins fixtures/dict.pyi]\n\n[case testIncrementalCrashOnTypeWithFunction]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nfrom b import x\n\n[file b.py]\nfrom typing import TypeVar, Type\nT = TypeVar('T')\n\ndef tp(arg: T) -> Type[T]:\n    pass\ndef func(x: int) -> int:\n    pass\n\nx = tp(func)\n[out]\n[out2]\n\n[case testReprocessModuleEvenIfInterfaceHashDoesNotChange]\nimport a\nimport d\n\n[file a.py]\nimport b\nx: b.c.A\nx = b.c.A()\n\n[file b.py]\nimport c\n\n[file c.py]\nclass A:\n    x = 1\n\n[file d.py]\nimport a\ndef f() -> None: pass\n\n[file a.py.2]\nimport b\nx: b.c.A\n\n[file c.py.3]\nclass A:\n    x = 2\n\n[file d.py.4]\nimport a\ndef f() -> None:\n    from c import A\n    a.x = [A(), a.x][0]\n\n[builtins fixtures/list.pyi]\n[stale]\n[rechecked a]\n[stale2]\n[rechecked2 c]\n[stale3]\n[rechecked3 d]\n[out1]\n[out2]\n[out3]\n[out4]\n\n[case testTreeShadowingViaParentPackage]\nimport m.semanal\n\n[file m/__init__.py]\npass\n\n[file m/nodes.py]\nif False:\n    import m.types\n    import m.semanal\nclass Node:\n    line: int\nclass FuncBase(Node):\n    type: m.types.Type\nclass OverloadedFuncDef(FuncBase): pass\n\n[file m/types.py]\nfrom m.nodes import Node\nclass Type(Node): pass\nclass Overloaded(Type): pass\n\n[file m/semanal.py]\nfrom m.nodes import OverloadedFuncDef\nfrom m.types import Overloaded\n\nclass C:\n    def func(self, defn: OverloadedFuncDef):\n        defn.type = Overloaded()\n        defn.type.line = 0\n\n[file m/nodes.py.2]\nif False:\n    import m.types\n    import m.semanal\nclass Node:\n    line: int\nclass FuncBase(Node):\n    type: m.types.Type\nclass OverloadedFuncDef(FuncBase): pass\nextra = 1\n\n[file m/types.py.2]\nfrom m.nodes import Node\nclass Type(Node): pass\nclass Overloaded(Type): pass\nextra = 1\n[builtins fixtures/list.pyi]\n\n[file m/semanal.py.2]\nfrom m.nodes import OverloadedFuncDef\nfrom m.types import Overloaded\n\nclass C:\n    def func(self, defn: OverloadedFuncDef):\n        defn.type = Overloaded()\n        defn.type.line = 0\n\nextra = 1\n\n[out1]\n[out2]\n\n[case testErrorsAffectDependentsOnly]\n# cmd: mypy -m m.a m.b m.c\n[file m/__init__.py]\n[file m/a.py]\n1 + ''  # Deliberate error\n[file m/b.py]\nimport m.a  # Depends on module with error\n[file m/c.py]\nimport m  # No error here\n[rechecked]\n[out1]\ntmp/m/a.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n[out2]\ntmp/m/a.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testDisallowAnyExprIncremental]\n# cmd: mypy -m main\n# flags: --disallow-any-expr\n\n[file ns.py]\nclass Namespace:\n    def __init__(self):\n        self.user = 0\n\n[file main.py]\nimport ns\nuser = ns.Namespace().user\n\n[out1]\ntmp/main.py:2: error: Expression has type \"Any\"\n\n[out2]\ntmp/main.py:2: error: Expression has type \"Any\"\n\n[case testIncrementalStrictOptional]\nimport a\n1 + a.foo()\n[file a.py]\ndef foo() -> int: return 0\n[file a.py.2]\nfrom typing import Optional\ndef foo() -> Optional[int]: return 0\n[out1]\n[out2]\nmain:2: error: Unsupported operand types for + (\"int\" and \"None\")\nmain:2: note: Right operand is of type \"int | None\"\n\n[case testAttrsIncrementalSubclassingCached]\nfrom a import A\nimport attrs\n@attrs.define\nclass B(A):\n    e: str = 'e'\na = B(5, [5], 'foo')\na.a = 6\na._b = [2]\na.c = 'yo'\na._d = 22\na.e = 'hi'\n\n[file a.py]\nimport attrs\nfrom typing import List, ClassVar\n@attrs.define\nclass A:\n    a: int\n    _b: List[int]\n    c: str = '18'\n    _d: int = attrs.field(validator=None, default=18)\n    E = 7\n    F: ClassVar[int] = 22\n\n[builtins fixtures/list.pyi]\n[out1]\n[out2]\n\n[case testAttrsIncrementalSubclassingCachedConverter]\nfrom a import A\nimport attrs\n@attrs.define\nclass B(A):\n    pass\nreveal_type(B)\n\n[file a.py]\ndef converter(s:int) -> str:\n    return 'hello'\n\nimport attrs\n@attrs.define\nclass A:\n    x: str = attrs.field(converter=converter)\n\n[builtins fixtures/list.pyi]\n[out1]\nmain:6: note: Revealed type is \"def (x: builtins.int) -> __main__.B\"\n\n[out2]\nmain:6: note: Revealed type is \"def (x: builtins.int) -> __main__.B\"\n\n[case testAttrsIncrementalSubclassingCachedType]\nfrom a import A\nimport attrs\n@attrs.define\nclass B(A):\n    pass\nreveal_type(B)\n\n[file a.py]\nimport attrs\n@attrs.define\nclass A:\n    x: int\n\n[builtins fixtures/list.pyi]\n[out1]\nmain:6: note: Revealed type is \"def (x: builtins.int) -> __main__.B\"\n[out2]\nmain:6: note: Revealed type is \"def (x: builtins.int) -> __main__.B\"\n\n[case testAttrsIncrementalArguments]\nfrom a import Frozen, NoInit, NoCmp\nf = Frozen(5)\nf.x = 6\n\ng = NoInit()\n\nFrozen(1) < Frozen(2)\nFrozen(1) <= Frozen(2)\nFrozen(1) > Frozen(2)\nFrozen(1) >= Frozen(2)\n\nNoCmp(1) < NoCmp(2)\nNoCmp(1) <= NoCmp(2)\nNoCmp(1) > NoCmp(2)\nNoCmp(1) >= NoCmp(2)\n\n[file a.py]\nimport attrs\n@attrs.frozen\nclass Frozen:\n    x: int\n@attrs.define(init=False)\nclass NoInit:\n    x: int\n@attrs.define(eq=False)\nclass NoCmp:\n    x: int\n\n[builtins fixtures/plugin_attrs.pyi]\n[rechecked]\n[stale]\n[out1]\nmain:3: error: Property \"x\" defined in \"Frozen\" is read-only\nmain:12: error: Unsupported left operand type for < (\"NoCmp\")\nmain:13: error: Unsupported left operand type for <= (\"NoCmp\")\nmain:14: error: Unsupported left operand type for > (\"NoCmp\")\nmain:15: error: Unsupported left operand type for >= (\"NoCmp\")\n\n[out2]\nmain:3: error: Property \"x\" defined in \"Frozen\" is read-only\nmain:12: error: Unsupported left operand type for < (\"NoCmp\")\nmain:13: error: Unsupported left operand type for <= (\"NoCmp\")\nmain:14: error: Unsupported left operand type for > (\"NoCmp\")\nmain:15: error: Unsupported left operand type for >= (\"NoCmp\")\n\n[case testAttrsIncrementalDunder]\nfrom a import A\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int) -> a.A\"\nreveal_type(A.__lt__)  # N: Revealed type is \"def [_AT] (self: _AT`3, other: _AT`3) -> builtins.bool\"\nreveal_type(A.__le__)  # N: Revealed type is \"def [_AT] (self: _AT`4, other: _AT`4) -> builtins.bool\"\nreveal_type(A.__gt__)  # N: Revealed type is \"def [_AT] (self: _AT`5, other: _AT`5) -> builtins.bool\"\nreveal_type(A.__ge__)  # N: Revealed type is \"def [_AT] (self: _AT`6, other: _AT`6) -> builtins.bool\"\n\nA(1) < A(2)\nA(1) <= A(2)\nA(1) > A(2)\nA(1) >= A(2)\nA(1) == A(2)\nA(1) != A(2)\n\nA(1) < 1  # E: Unsupported operand types for < (\"A\" and \"int\")\nA(1) <= 1  # E: Unsupported operand types for <= (\"A\" and \"int\")\nA(1) > 1  # E: Unsupported operand types for > (\"A\" and \"int\")\nA(1) >= 1  # E: Unsupported operand types for >= (\"A\" and \"int\")\nA(1) == 1\nA(1) != 1\n\n1 < A(1)  # E: Unsupported operand types for > (\"A\" and \"int\")\n1 <= A(1)  # E: Unsupported operand types for >= (\"A\" and \"int\")\n1 > A(1)  # E: Unsupported operand types for < (\"A\" and \"int\")\n1 >= A(1)  # E: Unsupported operand types for <= (\"A\" and \"int\")\n1 == A(1)\n1 != A(1)\n\n[file a.py]\nfrom attr import attrib, attrs\n@attrs(auto_attribs=True)\nclass A:\n    a: int\n\n[builtins fixtures/plugin_attrs.pyi]\n[rechecked]\n[stale]\n[out2]\nmain:2: note: Revealed type is \"def (a: builtins.int) -> a.A\"\nmain:3: note: Revealed type is \"def [_AT] (self: _AT`3, other: _AT`3) -> builtins.bool\"\nmain:4: note: Revealed type is \"def [_AT] (self: _AT`4, other: _AT`4) -> builtins.bool\"\nmain:5: note: Revealed type is \"def [_AT] (self: _AT`5, other: _AT`5) -> builtins.bool\"\nmain:6: note: Revealed type is \"def [_AT] (self: _AT`6, other: _AT`6) -> builtins.bool\"\nmain:15: error: Unsupported operand types for < (\"A\" and \"int\")\nmain:16: error: Unsupported operand types for <= (\"A\" and \"int\")\nmain:17: error: Unsupported operand types for > (\"A\" and \"int\")\nmain:18: error: Unsupported operand types for >= (\"A\" and \"int\")\nmain:22: error: Unsupported operand types for > (\"A\" and \"int\")\nmain:23: error: Unsupported operand types for >= (\"A\" and \"int\")\nmain:24: error: Unsupported operand types for < (\"A\" and \"int\")\nmain:25: error: Unsupported operand types for <= (\"A\" and \"int\")\n\n[case testAttrsIncrementalSubclassModified]\nfrom b import B\nB(5, 'foo')\n\n[file a.py]\nimport attrs\n@attrs.define\nclass A:\n    x: int\n\n[file b.py]\nimport attrs\nfrom a import A\n@attrs.define\nclass B(A):\n    y: str\n\n[file b.py.2]\nimport attrs\nfrom a import A\n@attrs.define\nclass B(A):\n    y: int\n\n[builtins fixtures/list.pyi]\n[out1]\n[out2]\nmain:2: error: Argument 2 to \"B\" has incompatible type \"str\"; expected \"int\"\n[rechecked b]\n\n[case testAttrsIncrementalSubclassModifiedErrorFirst]\nfrom b import B\nB(5, 'foo')\n[file a.py]\nimport attrs\n@attrs.define\nclass A:\n    x: int\n\n[file b.py]\nimport attrs\nfrom a import A\n@attrs.define\nclass B(A):\n    y: int\n\n[file b.py.2]\nimport attrs\nfrom a import A\n@attrs.define\nclass B(A):\n    y: str\n\n[builtins fixtures/list.pyi]\n[out1]\nmain:2: error: Argument 2 to \"B\" has incompatible type \"str\"; expected \"int\"\n\n[out2]\n[rechecked b]\n\n[case testAttrsIncrementalThreeFiles]\nfrom c import C\nC(5, 'foo', True)\n\n[file a.py]\nimport attrs\n@attrs.define(slots=False)\nclass A:\n    a: int\n\n[file b.py]\nimport attrs\n@attrs.define(slots=False)\nclass B:\n    b: str\n\n[file c.py]\nfrom a import A\nfrom b import B\nimport attrs\n@attrs.define(slots=False)\nclass C(A, B):\n    c: bool\n\n[builtins fixtures/list.pyi]\n[out1]\n[out2]\n\n[case testAttrsIncrementalConverterInSubmodule]\nfrom a.a import A\nreveal_type(A)\n[file a/__init__.py]\n[file a/a.py]\nfrom typing import Optional\ndef converter(s:Optional[int]) -> int:\n    ...\n\nimport attrs\n@attrs.define\nclass A:\n    x: int = attrs.field(converter=converter)\n\n[builtins fixtures/list.pyi]\n[out1]\nmain:2: note: Revealed type is \"def (x: builtins.int | None) -> a.a.A\"\n[out2]\nmain:2: note: Revealed type is \"def (x: builtins.int | None) -> a.a.A\"\n\n[case testAttrsIncrementalConverterManyStyles]\nimport a\n[file a.py]\nfrom base import Base\nBase(1, 'str', True)\nBase(None, None, None)\n\nfrom subclass import A, B\nA(1, 'str', True)\nA(None, None, None)\nB(1, 'str', True, 1, 'str', True)\nB(None, None, None, None, None, None)\n\nfrom submodule.base import SubBase\nSubBase(1, 'str', True)\nSubBase(None, None, None)\n\nfrom submodule.subclass import AA, BB\nAA(1, 'str', True)\nAA(None, None, None)\nBB(1, 'str', True, 1, 'str', True)\nBB(None, None, None, None, None, None)\n\nfrom submodule.subsubclass import SubAA, SubBB\nSubAA(1, 'str', True)\nSubAA(None, None, None)\nSubBB(1, 'str', True, 1, 'str', True)\nSubBB(None, None, None, None, None, None)\n\n[file a.py.2]\n# Now with errors.\nfrom base import Base\nBase(1, 1, True)\n\nfrom subclass import A, B\nA(1, 1, True)\nB(1, 'str', True, 1, 1, True)\n\nfrom submodule.base import SubBase\nSubBase(1, 1, True)\n\nfrom submodule.subclass import AA, BB\nAA(1, 1, True)\nBB(1, 'str', True, 1, 1, True)\n\nfrom submodule.subsubclass import SubAA, SubBB\nSubAA(1, 1, True)\nSubBB(1, 'str', True, 1, 1, True)\n\n[file foo.py]\nfrom typing import Optional\ndef maybe_int(x: Optional[int]) -> int:\n   ...\n[file bar.py]\nfrom typing import Optional\ndef maybe_bool(x: Optional[bool]) -> bool:\n   ...\n[file base.py]\nfrom typing import Optional\nimport attrs\nimport bar\nfrom foo import maybe_int\ndef maybe_str(x: Optional[str]) -> str:\n   ...\n@attrs.define\nclass Base:\n    x: int = attrs.field(converter=maybe_int)\n    y: str = attrs.field(converter=maybe_str)\n    z: bool = attrs.field(converter=bar.maybe_bool)\n[file subclass.py]\nfrom typing import Optional\nimport attrs\nfrom base import Base\n@attrs.define\nclass A(Base): pass\n\nimport bar\nfrom foo import maybe_int\ndef maybe_str(x: Optional[str]) -> str:\n   ...\n@attrs.define\nclass B(Base):\n    xx: int = attrs.field(converter=maybe_int)\n    yy: str = attrs.field(converter=maybe_str)\n    zz: bool = attrs.field(converter=bar.maybe_bool)\n\n[file submodule/__init__.py]\n[file submodule/base.py]\nfrom typing import Optional\nimport attrs\nimport bar\nfrom foo import maybe_int\ndef maybe_str(x: Optional[str]) -> str:\n   ...\n@attrs.define\nclass SubBase:\n    x: int = attrs.field(converter=maybe_int)\n    y: str = attrs.field(converter=maybe_str)\n    z: bool = attrs.field(converter=bar.maybe_bool)\n\n[file submodule/subclass.py]\nfrom typing import Optional\nimport attrs\nfrom base import Base\n@attrs.define\nclass AA(Base): pass\n\nimport bar\nfrom foo import maybe_int\ndef maybe_str(x: Optional[str]) -> str:\n   ...\n@attrs.define\nclass BB(Base):\n    xx: int = attrs.field(converter=maybe_int)\n    yy: str = attrs.field(converter=maybe_str)\n    zz: bool = attrs.field(converter=bar.maybe_bool)\n\n[file submodule/subsubclass.py]\nfrom typing import Optional\nimport attrs\nfrom .base import SubBase\n@attrs.define\nclass SubAA(SubBase): pass\n\nimport bar\nfrom foo import maybe_int\ndef maybe_str(x: Optional[str]) -> str:\n   ...\n@attrs.define\nclass SubBB(SubBase):\n    xx: int = attrs.field(converter=maybe_int)\n    yy: str = attrs.field(converter=maybe_str)\n    zz: bool = attrs.field(converter=bar.maybe_bool)\n[builtins fixtures/list.pyi]\n[out1]\n[out2]\ntmp/a.py:3: error: Argument 2 to \"Base\" has incompatible type \"int\"; expected \"str | None\"\ntmp/a.py:6: error: Argument 2 to \"A\" has incompatible type \"int\"; expected \"str | None\"\ntmp/a.py:7: error: Argument 5 to \"B\" has incompatible type \"int\"; expected \"str | None\"\ntmp/a.py:10: error: Argument 2 to \"SubBase\" has incompatible type \"int\"; expected \"str | None\"\ntmp/a.py:13: error: Argument 2 to \"AA\" has incompatible type \"int\"; expected \"str | None\"\ntmp/a.py:14: error: Argument 5 to \"BB\" has incompatible type \"int\"; expected \"str | None\"\ntmp/a.py:17: error: Argument 2 to \"SubAA\" has incompatible type \"int\"; expected \"str | None\"\ntmp/a.py:18: error: Argument 5 to \"SubBB\" has incompatible type \"int\"; expected \"str | None\"\n\n[case testAttrsIncrementalConverterInFunction]\nimport attrs\ndef foo() -> None:\n    def foo(x: str) -> int:\n        ...\n    @attrs.define\n    class A:\n        x: int = attrs.field(converter=foo)\n    reveal_type(A)\n[builtins fixtures/list.pyi]\n[out1]\nmain:8: note: Revealed type is \"def (x: builtins.str) -> __main__.A@6\"\n[out2]\nmain:8: note: Revealed type is \"def (x: builtins.str) -> __main__.A@6\"\n\n-- FIXME: new analyzer busted\n[case testAttrsIncrementalConverterInSubmoduleForwardRef-skip]\n\nfrom a.a import A\nreveal_type(A)\n[file a/__init__.py]\n[file a/a.py]\nfrom typing import List\ndef converter(s:F) -> int:\n    ...\n\nimport attrs\n@attrs.define\nclass A:\n    x: int = attrs.field(converter=converter)\n\nF = List[int]\n\n[builtins fixtures/list.pyi]\n[out1]\nmain:3: note: Revealed type is \"def (x: builtins.list[builtins.int]) -> a.a.A\"\n[out2]\nmain:3: note: Revealed type is \"def (x: builtins.list[builtins.int]) -> a.a.A\"\n\n-- FIXME: new analyzer busted\n[case testAttrsIncrementalConverterType-skip]\n\nfrom a import C\nimport attrs\no = C(\"1\", \"2\", \"3\", \"4\")\no = C(1, 2, \"3\", 4)\nreveal_type(C)\n@attrs.define\nclass D(C):\n    x: str\nreveal_type(D)\n[file a.py]\nfrom typing import overload\nimport attrs\n@attrs.define\nclass A:\n    x: str\n@overload\ndef parse(x: int) -> int:\n   ...\n@overload\ndef parse(x: str, y: str = '') -> int:\n   ...\ndef parse(x, y): ...\n@attrs.define\nclass C:\n    a: complex = attrs.field(converter=complex)\n    b: int = attrs.field(converter=int)\n    c: A = attrs.field(converter=A)\n    d: int = attrs.field(converter=parse)\n[builtins fixtures/plugin_attrs.pyi]\n[out1]\nmain:6: note: Revealed type is \"def (a: Union[builtins.float, builtins.str], b: Union[builtins.str, builtins.bytes, builtins.int], c: builtins.str, d: Union[builtins.int, builtins.str]) -> a.C\"\nmain:10: note: Revealed type is \"def (a: Union[builtins.float, builtins.str], b: Union[builtins.str, builtins.bytes, builtins.int], c: builtins.str, d: Union[builtins.int, builtins.str], x: builtins.str) -> __main__.D\"\n[out2]\nmain:6: note: Revealed type is \"def (a: Union[builtins.float, builtins.str], b: Union[builtins.str, builtins.bytes, builtins.int], c: builtins.str, d: Union[builtins.int, builtins.str]) -> a.C\"\nmain:10: note: Revealed type is \"def (a: Union[builtins.float, builtins.str], b: Union[builtins.str, builtins.bytes, builtins.int], c: builtins.str, d: Union[builtins.int, builtins.str], x: builtins.str) -> __main__.D\"\n\n[case testAttrsIncrementalThreeRuns]\nfrom a import A\nA(5)\n\n[file a.py]\nimport attrs\n@attrs.define\nclass A:\n    a: int\n\n[file a.py.2]\nimport attrs\n@attrs.define\nclass A:\n    a: str\n\n[file a.py.3]\nimport attrs\n@attrs.define\nclass A:\n    a: int = 6\n\n[builtins fixtures/list.pyi]\n[out1]\n[out2]\nmain:2: error: Argument 1 to \"A\" has incompatible type \"int\"; expected \"str\"\n[out3]\n\n[case testDeletedDepLineNumber]\n# The import is not on line 1 and that data should be preserved\nimport a\n[file a.py]\n[delete a.py.2]\n[out1]\n\n[out2]\nmain:2: error: Cannot find implementation or library stub for module named \"a\"\nmain:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testIncrementalInheritanceAddAnnotation]\nimport a\n[file a.py]\nimport b\ndef foo() -> None:\n    1 + b.Bar().get()\n[file b.py]\nfrom c import Baz\nclass Bar(Baz): pass\n\n[file c.py]\nclass Baz:\n    def get(self):\n        return 1\n[file c.py.2]\nfrom typing import Optional\nclass Baz:\n    def get(self) -> Optional[int]:\n        return 1\n[out]\n[out2]\ntmp/a.py:3: error: Unsupported operand types for + (\"int\" and \"None\")\ntmp/a.py:3: note: Right operand is of type \"int | None\"\n\n[case testIncrementalMetaclassUpdate]\nimport a\n[file a.py]\nfrom b import B\nB.x\n\n[file b.py]\nimport c\nclass B(metaclass=c.M): pass\n\n[file c.py]\nclass M(type):\n    x: int\n\n[file c.py.2]\nclass M(type):\n    y: int\n[out]\n[out2]\ntmp/a.py:2: error: \"type[B]\" has no attribute \"x\"\n\n[case testIncrementalLotsOfInheritance]\nimport a\n[file a.py]\nfrom b import B\nfrom d import D\ndef take(d: D) -> None: pass\ndef foo() -> None:\n    take(B())\n[file b.py]\nfrom c import C\nclass B(C): pass\n\n[file c.py]\nfrom d import D\nclass C(D): pass\n\n[file c.py.2]\nfrom d import D\nclass C: pass\n\n[file d.py]\nclass D: pass\n[out]\n[out2]\ntmp/a.py:5: error: Argument 1 to \"take\" has incompatible type \"B\"; expected \"D\"\n\n[case testIncrementalInheritanceProperty]\nimport a\n[file a.py]\nimport b\ndef foo() -> None:\n    1 + b.Bar().x\n[file b.py]\nfrom c import Baz\nclass Bar(Baz): pass\n\n[file c.py]\nclass Baz:\n    def __init__(self) -> None:\n        self.x = 12  # type: int\n[file c.py.2]\nclass Baz:\n    def __init__(self) -> None:\n        self.x = 'lol'  # type: str\n[out]\n[out2]\ntmp/a.py:3: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testIncrementalWithIgnoresTwice]\nimport a\n[file a.py]\nimport b\nimport foo # type: ignore\n[file b.py]\nx = 1\n[file b.py.2]\nx = 'hi'\n[file b.py.3]\nx = 1\n[builtins fixtures/module.pyi]\n[out]\n[out2]\n[out3]\n\n[case testIgnoredImport2]\nimport x\n[file y.py]\nimport xyz  # type: ignore\nB = 0\nfrom x import A\n[file x.py]\nA = 0\nfrom y import B\n[file x.py.2]\nA = 1\nfrom y import B\n[file x.py.3]\nA = 2\nfrom y import B\n[out]\n[out2]\n[out3]\n\n[case testDeletionOfSubmoduleTriggersImportFrom2]\nfrom p.q import f\nf()\n[file p/__init__.py]\n[file p/q.py]\ndef f() -> None: pass\n[delete p/q.py.2]\n[file p/q.py.3]\ndef f(x: int) -> None: pass\n[out]\n[out2]\nmain:1: error: Cannot find implementation or library stub for module named \"p.q\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n[out3]\nmain:2: error: Missing positional argument \"x\" in call to \"f\"\n\n[case testDeleteIndirectDependency]\nimport b\nb.x.foo()\n[file b.py]\nimport c\nx = c.Foo()\n[file c.py]\nclass Foo:\n    def foo(self) -> None: pass\n[delete c.py.2]\n[file b.py.2]\nclass Foo:\n    def foo(self) -> None: pass\nx = Foo()\n[out]\n[out2]\n\n[case testImportReExportInCycle]\nfrom m import One\n[file m/__init__.py]\nfrom .one import One\nfrom .two import Two\n[file m/one.py]\nclass One:\n    pass\n[file m/two.py]\nimport m\nclass Two:\n    pass\n[file m/one.py.2]\nclass One:\n    name: str\n[file m/two.py.2]\nimport m\nreveal_type(m.One.name)\nclass Two:\n    pass\n[out2]\ntmp/m/two.py:2: note: Revealed type is \"builtins.str\"\n\n[case testImportUnusedIgnore1]\n# flags: --warn-unused-ignores\nimport a\n[file a.py]\nimport b\nimport foo  # type: ignore\n[file b.py]\nx = 1\n[file b.py.2]\nx = '2'\n\n[case testImportUnusedIgnore2]\n# flags: --warn-unused-ignores\nimport a\n[file a.py]\nimport b\nimport c  # type: ignore\n[file b.py]\nx = 1\n[file b.py.2]\nx = 'hi'\n[file c.py.3]\npass\n[out]\n[out2]\n[out3]\ntmp/a.py:2: error: Unused \"type: ignore\" comment\n\n-- Test that a non cache_fine_grained run can use a fine-grained cache\n[case testRegularUsesFgCache]\n# flags: --config-file tmp/mypy.ini\nimport a\n[file a.py]\nx = 0\n[file mypy.ini]\n\\[mypy]\ncache_fine_grained = True\nlocal_partial_types = True\n[file mypy.ini.2]\n\\[mypy]\ncache_fine_grained = False\nlocal_partial_types = True\n-- Nothing should get rechecked\n[rechecked]\n[stale]\n\n[case testFgCacheNeedsFgCache]\n# flags: --config-file tmp/mypy.ini\nimport a\n[file a.py]\nx = 0\n[file mypy.ini]\n\\[mypy]\ncache_fine_grained = False\n[file mypy.ini.2]\n\\[mypy]\ncache_fine_grained = True\n[rechecked _typeshed, a, builtins, typing]\n[stale _typeshed, a, builtins, typing]\n[builtins fixtures/tuple.pyi]\n\n[case testIncrementalPackageNameOverload]\n# cmd: mypy -m main a\n# flags: --follow-imports=skip\n[file main.py]\nfrom a import x\nx.foo()\n[file a/__init__.py]\npass\n[file a/__init__.py.2]\nx = 10\n[file a/x.py]\ndef foo() -> None:\n    pass\n[out]\n[out2]\ntmp/main.py:2: error: \"int\" has no attribute \"foo\"\n\n[case testIncrementalFineGrainedCacheError1]\n# flags: --cache-fine-grained --no-sqlite-cache\nimport a\n[file a.py]\n[file b.py]\nx = 0\n[file a.py.2]\nfrom b import x\n1 + 'lol'\n[out]\n[out2]\ntmp/a.py:2: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testIncrementalBustedFineGrainedCache1]\n# flags: --cache-fine-grained --no-sqlite-cache\nimport a\nimport b\n[file a.py]\n[file b.py]\n-- This is a heinous hack, but we simulate having a invalid cache by clobbering\n-- the proto deps file with something with mtime mismatches.\n[file ../.mypy_cache/3.9/@deps.meta.json.2]\n{\"snapshot\": {\"__main__\": \"a7c958b001a45bd6a2a320f4e53c4c16\", \"a\": \"d41d8cd98f00b204e9800998ecf8427e\", \"b\": \"d41d8cd98f00b204e9800998ecf8427e\", \"builtins\": \"c532c89da517a4b779bcf7a964478d67\"}, \"deps_meta\": {\"@root\": {\"path\": \"@root.deps.json\", \"mtime\": 0}, \"__main__\": {\"path\": \"__main__.deps.json\", \"mtime\": 0}, \"a\": {\"path\": \"a.deps.json\", \"mtime\": 0}, \"b\": {\"path\": \"b.deps.json\", \"mtime\": 0}, \"builtins\": {\"path\": \"builtins.deps.json\", \"mtime\": 0}}}\n[file ../.mypy_cache/.gitignore]\n# Another hack to not trigger a .gitignore creation failure \"false positive\"\n[file ../.mypy_cache/CACHEDIR.TAG]\nSignature: 8a477f597d28d172789f06886806bc55\n# Another another hack to not trigger a CACHEDIR.TAG creation failure \"false positive\"\n[file b.py.2]\n# uh\n-- Every file should get reloaded, since the cache was invalidated\n[stale _typeshed, a, b, builtins, typing]\n[rechecked _typeshed, a, b, builtins, typing]\n[builtins fixtures/tuple.pyi]\n\n[case testIncrementalBustedFineGrainedCache2]\n# flags2: --cache-fine-grained\nimport a\nimport b\n[file a.py]\n[file b.py]\n[file b.py.2]\n# uh\n-- Every file should get reloaded, since the settings changed\n[stale _typeshed, a, b, builtins, typing]\n[rechecked _typeshed, a, b, builtins, typing]\n[builtins fixtures/tuple.pyi]\n\n[case testIncrementalBustedFineGrainedCache3]\n# flags: --cache-fine-grained --no-sqlite-cache\nimport a\nimport b\n[file a.py]\n[file b.py]\n-- This is a heinous hack, but we simulate having a invalid cache by deleting\n-- the proto deps file.\n[delete ../.mypy_cache/3.9/@deps.meta.json.2]\n[file b.py.2]\n# uh\n-- Every file should get reloaded, since the cache was invalidated\n[stale _typeshed, a, b, builtins, typing]\n[rechecked _typeshed, a, b, builtins, typing]\n[builtins fixtures/tuple.pyi]\n\n[case testIncrementalWorkingFineGrainedCache]\n# flags: --cache-fine-grained\n# flags2: --cache-fine-grained\nimport a\nimport b\n[file a.py]\n[file b.py]\n[file b.py.2]\n# uh\n-- b gets rechecked because it changed, but nothing is stale\n-- since the interface did not change\n[stale]\n[rechecked b]\n\n[case testIncrementalDataclassesSubclassingCached]\nfrom a import A\nfrom dataclasses import dataclass\n\n@dataclass\nclass B(A):\n    e: str = 'e'\n\na = B(5, [5], 'foo')\na.a = 6\na._b = [2]\na.c = 'yo'\na._d = 22\na.e = 'hi'\n\n[file a.py]\nfrom dataclasses import dataclass, field\nfrom typing import ClassVar, List\n\n@dataclass\nclass A:\n    a: int\n    _b: List[int]\n    c: str = '18'\n    _d: int = field(default=False)\n    E = 7\n    F: ClassVar[int] = 22\n\n[builtins fixtures/dataclasses.pyi]\n[out1]\n[out2]\n\n[case testIncrementalDataclassesSubclassingCachedType]\nimport b\n\n[file b.py]\nfrom a import A\nfrom dataclasses import dataclass\n\n@dataclass\nclass B(A):\n    pass\n\n[file b.py.2]\nfrom a import A\nfrom dataclasses import dataclass\n\n@dataclass\nclass B(A):\n    pass\n\nreveal_type(B)\n\n[file a.py]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    x: int\n\n[builtins fixtures/dataclasses.pyi]\n[out1]\n[out2]\ntmp/b.py:8: note: Revealed type is \"def (x: builtins.int) -> b.B\"\n\n[case testIncrementalDataclassesArguments]\nimport b\n\n[file b.py]\nfrom a import Frozen, NoInit, NoCmp\n\n[file b.py.2]\nfrom a import Frozen, NoInit, NoCmp\n\nf = Frozen(5)\nf.x = 6\n\ng = NoInit()\n\nFrozen(1) < Frozen(2)\nFrozen(1) <= Frozen(2)\nFrozen(1) > Frozen(2)\nFrozen(1) >= Frozen(2)\n\nNoCmp(1) < NoCmp(2)\nNoCmp(1) <= NoCmp(2)\nNoCmp(1) > NoCmp(2)\nNoCmp(1) >= NoCmp(2)\n\n[file a.py]\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True, order=True)\nclass Frozen:\n    x: int\n\n@dataclass(init=False)\nclass NoInit:\n    x: int\n\n@dataclass(order=False)\nclass NoCmp:\n    x: int\n\n[builtins fixtures/dataclasses.pyi]\n[out1]\n[out2]\ntmp/b.py:4: error: Property \"x\" defined in \"Frozen\" is read-only\ntmp/b.py:13: error: Unsupported left operand type for < (\"NoCmp\")\ntmp/b.py:14: error: Unsupported left operand type for <= (\"NoCmp\")\ntmp/b.py:15: error: Unsupported left operand type for > (\"NoCmp\")\ntmp/b.py:16: error: Unsupported left operand type for >= (\"NoCmp\")\n\n[case testIncrementalDataclassesDunder]\nimport b\n\n[file b.py]\nfrom a import A\n\n[file b.py.2]\nfrom a import A\n\nreveal_type(A)\nreveal_type(A.__eq__)\nreveal_type(A.__ne__)\nreveal_type(A.__lt__)\nreveal_type(A.__le__)\nreveal_type(A.__gt__)\nreveal_type(A.__ge__)\n\nA(1) < A(2)\nA(1) <= A(2)\nA(1) > A(2)\nA(1) >= A(2)\nA(1) == A(2)\nA(1) != A(2)\n\nA(1) < 1\nA(1) <= 1\nA(1) > 1\nA(1) >= 1\nA(1) == 1\nA(1) != 1\n\n1 < A(1)\n1 <= A(1)\n1 > A(1)\n1 >= A(1)\n1 == A(1)\n1 != A(1)\n\n[file a.py]\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass A:\n    a: int\n\n[builtins fixtures/dataclasses.pyi]\n[out1]\n[out2]\ntmp/b.py:3: note: Revealed type is \"def (a: builtins.int) -> a.A\"\ntmp/b.py:4: note: Revealed type is \"def (builtins.object, builtins.object) -> builtins.bool\"\ntmp/b.py:5: note: Revealed type is \"def (builtins.object, builtins.object) -> builtins.bool\"\ntmp/b.py:6: note: Revealed type is \"def [_DT] (self: _DT`1, other: _DT`1) -> builtins.bool\"\ntmp/b.py:7: note: Revealed type is \"def [_DT] (self: _DT`2, other: _DT`2) -> builtins.bool\"\ntmp/b.py:8: note: Revealed type is \"def [_DT] (self: _DT`3, other: _DT`3) -> builtins.bool\"\ntmp/b.py:9: note: Revealed type is \"def [_DT] (self: _DT`4, other: _DT`4) -> builtins.bool\"\ntmp/b.py:18: error: Unsupported operand types for < (\"A\" and \"int\")\ntmp/b.py:19: error: Unsupported operand types for <= (\"A\" and \"int\")\ntmp/b.py:20: error: Unsupported operand types for > (\"A\" and \"int\")\ntmp/b.py:21: error: Unsupported operand types for >= (\"A\" and \"int\")\ntmp/b.py:25: error: Unsupported operand types for > (\"A\" and \"int\")\ntmp/b.py:26: error: Unsupported operand types for >= (\"A\" and \"int\")\ntmp/b.py:27: error: Unsupported operand types for < (\"A\" and \"int\")\ntmp/b.py:28: error: Unsupported operand types for <= (\"A\" and \"int\")\n\n[case testIncrementalDataclassesSubclassModified]\nfrom b import B\nB(5, 'foo')\n\n[file a.py]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    x: int\n\n[file b.py]\nfrom a import A\nfrom dataclasses import dataclass\n\n@dataclass\nclass B(A):\n    y: str\n\n[file b.py.2]\nfrom a import A\nfrom dataclasses import dataclass\n\n@dataclass\nclass B(A):\n    y: int\n\n[builtins fixtures/dataclasses.pyi]\n[out1]\n[out2]\nmain:2: error: Argument 2 to \"B\" has incompatible type \"str\"; expected \"int\"\n[rechecked b]\n\n[case testIncrementalDataclassesSubclassModifiedErrorFirst]\nfrom b import B\nB(5, 'foo')\n\n[file a.py]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    x: int\n\n[file b.py]\nfrom a import A\nfrom dataclasses import dataclass\n\n@dataclass\nclass B(A):\n    y: int\n\n[file b.py.2]\nfrom a import A\nfrom dataclasses import dataclass\n\n@dataclass\nclass B(A):\n    y: str\n\n[builtins fixtures/dataclasses.pyi]\n[out1]\nmain:2: error: Argument 2 to \"B\" has incompatible type \"str\"; expected \"int\"\n\n[out2]\n[rechecked b]\n\n[case testIncrementalDataclassesThreeFiles]\nfrom c import C\nC('foo', 5, True)\n\n[file a.py]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    a: int\n\n[file b.py]\nfrom dataclasses import dataclass\n\n@dataclass\nclass B:\n    b: str\n\n[file b.py.2]\nfrom dataclasses import dataclass\n\n@dataclass\nclass B:\n    b: str\n    c: str\n\n[file c.py]\nfrom a import A\nfrom b import B\nfrom dataclasses import dataclass\n\n@dataclass\nclass C(A, B):\n    c: bool\n\n[builtins fixtures/dataclasses.pyi]\n[out1]\n[out2]\ntmp/c.py:7: error: Incompatible types in assignment (expression has type \"bool\", base class \"B\" defined the type as \"str\")\nmain:2: error: Argument 2 to \"C\" has incompatible type \"int\"; expected \"bool\"\n\n[case testIncrementalDataclassesThreeRuns]\nfrom a import A\nA(5)\n\n[file a.py]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    a: int\n\n[file a.py.2]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    a: str\n\n[file a.py.3]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    a: int = 6\n\n[builtins fixtures/dataclasses.pyi]\n[out1]\n[out2]\nmain:2: error: Argument 1 to \"A\" has incompatible type \"int\"; expected \"str\"\n[out3]\n\n[case testParentPatchingMess]\n# flags: --ignore-missing-imports --follow-imports=skip\n# cmd: mypy -m d d.k d.k.a d.k.v t\n[file d/__init__.py]\n[file d/k/__init__.py]\nfrom d.k.a import x\n[file d/k/a.py]\nx = 10\n[file d/k/v.py]\nfrom d.k.e import x\n\n[file t.py]\nfrom d import k\n[file t.py.2]\nfrom d import k\n# dummy change\n\n[case testCachedBadProtocolNote]\nimport b\n[file a.py]\nfrom typing import TypedDict\nPoint = TypedDict('Point', {'x': int, 'y': int})\n[file b.py]\nfrom typing import Iterable\nfrom a import Point\np: Point\nit: Iterable[int] = p\n[file b.py.2]\nfrom typing import Iterable\nfrom a import Point\np: Point\nit: Iterable[int] = p  # change\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n[out]\ntmp/b.py:4: error: Incompatible types in assignment (expression has type \"Point\", variable has type \"Iterable[int]\")\ntmp/b.py:4: note: Following member(s) of \"Point\" have conflicts:\ntmp/b.py:4: note:     Expected:\ntmp/b.py:4: note:         def __iter__(self) -> Iterator[int]\ntmp/b.py:4: note:     Got:\ntmp/b.py:4: note:         def __iter__(self) -> Iterator[str]\n[out2]\ntmp/b.py:4: error: Incompatible types in assignment (expression has type \"Point\", variable has type \"Iterable[int]\")\ntmp/b.py:4: note: Following member(s) of \"Point\" have conflicts:\ntmp/b.py:4: note:     Expected:\ntmp/b.py:4: note:         def __iter__(self) -> Iterator[int]\ntmp/b.py:4: note:     Got:\ntmp/b.py:4: note:         def __iter__(self) -> Iterator[str]\n\n[case testIndirectDepsAlwaysPatched-writescache]\n# flags: --no-incremental\n# flags2: --incremental\nfrom b import C\ndef f() -> None:\n    x: int = C().x\n[file b.py]\nfrom c import C\n[file c.pyi]\nclass C:\n    x: int\n[file c.pyi.2]\nclass C:\n    x: str\n[out]\n[out2]\nmain:5: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testBazelFlagIgnoresFileChanges-skip]\n-- This test fails on windows, when the mypy source in on a different drive than\n--   the run-directory. In this case os.path.relpath(...) fails with an exception\n-- Since the initial run wrote a cache file, the second run ignores the source\n# flags: --bazel\nfrom a import f\nf()\n[file a.py]\ndef f(): pass\n[file a.py.2]\n[out]\n[out2]\n\n[case testModuleGetattrInitIncremental]\nimport c\n[file c.py]\nimport a.b\nx = a.b.f()\n[file c.py.2]\nimport a.b\nx = a.b.f()\n# touch\n[file a/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[builtins fixtures/module.pyi]\n[out]\n[out2]\n\n[case testModuleGetattrInitIncremental2]\nimport c\n[file c.py]\nimport a.b.c\n[file c.py.2]\nimport a.b.c\n# touch\n[file a/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[file a/b.pyi]\n# empty\n[builtins fixtures/module.pyi]\n[out]\ntmp/c.py:1: error: Cannot find implementation or library stub for module named \"a.b.c\"\ntmp/c.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n[out2]\ntmp/c.py:1: error: Cannot find implementation or library stub for module named \"a.b.c\"\ntmp/c.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testModuleGetattrIncrementalSerializeVarFlag]\nimport main\n\n[file main.py]\nfrom b import A, f\nf()\n\n[file main.py.3]\nfrom b import A, f  # foo\nf()\n\n[file b.py]\nfrom c import A\ndef f() -> A: ...\n\n[file b.py.2]\nfrom c import A  # foo\ndef f() -> A: ...\n\n[file c.py]\nfrom d import A\n\n[file d.pyi]\ndef __getattr__(n): ...\n[out1]\n[out2]\n[out3]\n\n[case testAddedMissingStubs]\n# flags: --ignore-missing-imports\nfrom missing import f\nf(int())\n[file missing.pyi.2]\ndef f(x: str) -> None: pass\n[out]\n[out2]\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddedMissingStubsPackage]\n# flags: --ignore-missing-imports\nimport package.missing\npackage.missing.f(int())\n[file package/__init__.pyi.2]\n[file package/missing.pyi.2]\ndef f(x: str) -> None: pass\n[out]\n[out2]\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddedMissingStubsPackageFrom]\n# flags: --ignore-missing-imports\nfrom package import missing\nmissing.f(int())\n[file package/__init__.pyi.2]\n[file package/missing.pyi.2]\ndef f(x: str) -> None: pass\n[out]\n[out2]\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddedMissingStubsPackagePartial]\n# flags: --ignore-missing-imports\nimport package.missing\npackage.missing.f(int())\n[file package/__init__.pyi]\n[file package/missing.pyi.2]\ndef f(x: str) -> None: pass\n[out]\n[out2]\nmain:3: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddedMissingStubsPackagePartialGetAttr]\nimport package.missing\npackage.missing.f(int())\n[file package/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[file package/missing.pyi.2]\ndef f(x: str) -> None: pass\n[out]\n[out2]\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddedMissingStubsIgnore]\nfrom missing import f  # type: ignore\nf(int())\n[file missing.pyi.2]\ndef f(x: str) -> None: pass\n[out]\n[out2]\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddedMissingStubsIgnorePackage]\nimport package.missing  # type: ignore\npackage.missing.f(int())\n[file package/__init__.pyi.2]\n[file package/missing.pyi.2]\ndef f(x: str) -> None: pass\n[out]\n[out2]\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddedMissingStubsIgnorePackageFrom]\nfrom package import missing  # type: ignore\nmissing.f(int())\n[file package/__init__.pyi.2]\n[file package/missing.pyi.2]\ndef f(x: str) -> None: pass\n[out]\n[out2]\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testAddedMissingStubsIgnorePackagePartial]\nimport package.missing  # type: ignore\npackage.missing.f(int())\n[file package/__init__.pyi]\n[file package/missing.pyi.2]\ndef f(x: str) -> None: pass\n[out]\n[out2]\nmain:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n-- Test cases for final qualifier\n\n[case testFinalAddFinalVarAssign]\nimport mod\nfrom a import D\nfrom mod import x\n\nmod.x = 2  # This an all below are errors.\nx = 2\nd: D\nd.y = 2\nd.z = 2\nD.y = 2\n[file a.py]\nimport mod\n\nclass D(mod.C):\n    pass\n[file mod.py]\nx = 1\nclass C:\n    y = 1\n    def __init__(self) -> None:\n        self.z = 1\n\n[file mod.py.2]\nfrom typing import Final\n\nx: Final = 1\nclass C:\n    y: Final = 1\n    def __init__(self) -> None:\n        self.z: Final = 1\n[out]\n[out2]\nmain:5: error: Cannot assign to final name \"x\"\nmain:6: error: Cannot assign to final name \"x\"\nmain:8: error: Cannot assign to final attribute \"y\"\nmain:9: error: Cannot assign to final attribute \"z\"\nmain:10: error: Cannot assign to final attribute \"y\"\n\n[case testFinalAddFinalVarOverride]\nfrom mod import C\n\nclass D(C):\n    x = 2\n    def __init__(self) -> None:\n        self.y = 2\nclass E(C):\n    y = 2\n    def __init__(self) -> None:\n        self.x = 2\n\n[file mod.py]\nclass C:\n    x = 1\n    def __init__(self) -> None:\n        self.y = 1\n\n[file mod.py.2]\nfrom typing import Final\n\nclass C:\n    x: Final = 1\n    def __init__(self) -> None:\n        self.y: Final = 1\n[out]\n[out2]\nmain:4: error: Cannot assign to final name \"x\"\nmain:6: error: Cannot assign to final attribute \"y\"\nmain:8: error: Cannot assign to final name \"y\"\nmain:10: error: Cannot assign to final attribute \"x\"\n\n[case testFinalAddFinalMethodOverride]\nfrom mod import C\n\nclass D(C):\n    def meth(self) -> int: ...\n\n[file mod.py]\nclass C:\n    def meth(self) -> int: ...\n\n[file mod.py.2]\nfrom typing import final\n\nclass C:\n    @final\n    def meth(self) -> int: ...\n[out]\n[out2]\nmain:4: error: Cannot override final attribute \"meth\" (previously declared in base class \"C\")\n\n-- These tests should just not crash\n[case testOverrideByBadVar]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nclass Slow:\n    pass\n\ns: Slow\nfrom cext import Slow  # type: ignore\n[out]\n[out2]\n\n[case testOverrideByBadVarAlias]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nclass Slow:\n    pass\n\nA = Slow\nfrom cext import Slow  # type: ignore\n[out]\n[out2]\n\n[case testOverrideByBadVarClass]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nclass C:\n    class Slow:\n        pass\n    s: Slow\n    from cext import Slow  # type: ignore\n[out]\n[out2]\n\n[case testOverrideByBadVarClassAlias]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nclass C:\n    class Slow:\n        pass\n    A = Slow\n    from cext import Slow  # type: ignore\n[out]\n[out2]\n\n[case testOverrideByBadVarExisting]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nclass Slow:\n    pass\n\ns: Slow\nfrom cext import Slow  # type: ignore\n[file cext.py]\nSlow = 1\n[out]\n[out2]\n\n[case testOverrideByBadVarAliasExisting]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nclass Slow:\n    pass\n\nA = Slow\nfrom cext import Slow  # type: ignore\n[file cext.py]\nSlow = 1\n[out]\n[out2]\n\n[case testOverrideByBadFunction]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nclass C:\n    class Slow:\n        pass\n\n    s: Slow\n    def Slow() -> None: ...  # type: ignore\n[out]\n[out2]\n\n[case testOverrideByBadVarLocal]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\ndef outer() -> None:\n    class Slow:\n        pass\n\n    s: Slow\n    from cext import Slow  # type: ignore\n[out]\n[out2]\n\n[case testRecursiveAliasImported]\nimport a\n\n[file a.py]\nimport lib\nx: int\n\n[file a.py.2]\nimport lib\nx: lib.A\nreveal_type(x)\n\n[file lib.pyi]\nfrom typing import List\nMYPY = False\nif MYPY:  # Force processing order\n    from other import B\nA = List[B]  # type: ignore\n\n[file other.pyi]\nfrom typing import List\nfrom lib import A\nB = List[A]\n\n[builtins fixtures/list.pyi]\n[out]\n[out2]\ntmp/a.py:3: note: Revealed type is \"builtins.list[builtins.list[...]]\"\n\n[case testRecursiveNamedTupleTypedDict]\nimport a\n[file a.py]\nimport lib\nx: int\n[file a.py.2]\nimport lib\nx: lib.A\nreveal_type(x.x['x'])\n[file lib.pyi]\nfrom typing import NamedTuple\nfrom other import B\nA = NamedTuple('A', [('x', B)])\n[file other.pyi]\nfrom typing import TypedDict\nfrom lib import A\nB = TypedDict('B', {'x': A})\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n[out2]\ntmp/a.py:3: note: Revealed type is \"tuple[TypedDict('other.B', {'x': tuple[..., fallback=lib.A]}), fallback=lib.A]\"\n\n[case testFollowImportSkipNotInvalidatedOnPresent]\n# flags: --follow-imports=skip\n# cmd: mypy -m main\n[file main.py]\nimport other\n[file other.py]\nx = 1\n[file other.py.2]\nx = 'hi'\n[stale]\n[rechecked]\n\n[case testFollowImportSkipNotInvalidatedOnPresentPackage]\n# flags: --follow-imports=skip\n# cmd: mypy -m main\n[file main.py]\nimport other\n[file other/__init__.py]\nx = 1\n[file other/__init__.py.2]\nx = 'hi'\n[stale]\n[rechecked]\n\n[case testFollowImportSkipNotInvalidatedOnAdded]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy -m main\n[file main.py]\nimport other\n[file other.py.2]\nx = 1\n[stale]\n[rechecked]\n\n[case testFollowImportSkipInvalidatedOnAddedStub]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy -m main\n[file main.py]\nimport other\n[file other.pyi.2]\nx = 1\n[stale main, other]\n[rechecked main, other]\n\n[case testFollowImportSkipNotInvalidatedOnAddedStubOnFollowForStubs]\n# flags: --follow-imports=skip --ignore-missing-imports --config-file=tmp/mypy.ini\n# cmd: mypy -m main\n[file main.py]\nimport other\n[file other.pyi.2]\nx = 1\n[file mypy.ini]\n\\[mypy]\nfollow_imports_for_stubs = True\n[stale]\n[rechecked]\n\n[case testAddedSkippedStubsPackageFrom]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy -m main\n# cmd2: mypy -m main package package.missing\n[file main.py]\nfrom package import missing\nmissing.f(int())\n[file package/__init__.py]\n[file package/missing.py]\ndef f(x: str) -> None: pass\n[out]\n[out2]\ntmp/main.py:2: error: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testOverrideByIdemAlias]\n# https://github.com/python/mypy/issues/6404\n\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nC = C  # type: ignore\nclass C:  # type: ignore\n    pass\n[out]\n[out2]\n\n[case testOverrideByIdemAliasReversed]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nclass C:\n    pass\nC = C  # type: ignore\nx: C\n[out]\n[out2]\n\n[case testOverrideByIdemAliasGeneric]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    pass\nC = C[int]  # type: ignore\nx: C\n[out]\n[out2]\n\n[case testOverrideByIdemAliasImported]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nfrom other import C\nC = C  # type: ignore\nx: C\n[file other.py]\nclass C:\n    pass\n[out]\n[out2]\n\n[case testOverrideByIdemAliasImportedReversed]\nimport a\n[file a.py]\nimport lib\nx = 1\n[file a.py.2]\nimport lib\nx = 2\n[file lib.py]\nC = C  # type: ignore\nfrom other import C\n[file other.py]\nclass C:\n    pass\n[out]\n[out2]\n\n[case testConditionalExceptionAliasOverride]\nimport a\n[file a.py]\nimport lib\ntry:\n    x = 1\nexcept lib.Exception as e:\n    pass\n[file a.py.2]\nimport lib\ntry:\n    x = 2\nexcept lib.Exception as e:\n    pass\n[file lib.py]\ntry:\n    Exception = Exception\nexcept BaseException:\n    class Exception(BaseException): pass  # type: ignore\n\ntry:\n    pass\nexcept Exception as e:\n    pass\n[builtins fixtures/exception.pyi]\n[out]\n[out2]\n\n[case testBadEnumLoading]\nimport a\n[file a.py]\nfrom b import E\nx: E\ny = 1\n\n[file a.py.2]\nfrom b import E\nx: E\ny = 2\n\n[file b.py]\nfrom typing import List\nfrom enum import Enum\n\ndef f() -> List[str]: ...\n\nE = Enum('E', f())  # type: ignore\n[builtins fixtures/list.pyi]\n[out]\n[out2]\n\n[case testChangedPluginsInvalidateCache]\n# flags: --config-file tmp/mypy.ini\nimport a\n[file a.py]\nfrom b import x\ny: int = x\n\n[file a.py.2]\nfrom b import x\ny: int = x\ntouch = 1\n\n[file b.py]\nclass C: ...\ndef f() -> C: ...\nx = f()\n\n[file basic_plugin.py]\nfrom mypy.plugin import Plugin\n\nclass MyPlugin(Plugin):\n    def get_function_hook(self, fullname):\n        if fullname.endswith('.f'):\n            return my_hook\n        assert fullname is not None\n        return None\n\ndef my_hook(ctx):\n    return ctx.api.named_generic_type('builtins.int', [])\n\ndef plugin(version):\n    return MyPlugin\n\n[file basic_plugin.py.2]\nfrom mypy.plugin import Plugin\n\nclass MyPlugin(Plugin):\n    def get_function_hook(self, fullname):\n        if fullname.endswith('.f'):\n            return my_hook\n        assert fullname is not None\n        return None\n\ndef my_hook(ctx):\n    return ctx.api.named_generic_type('builtins.str', [])\n\ndef plugin(version):\n    return MyPlugin\n[file mypy.ini]\n\\[mypy]\nplugins=basic_plugin.py\n[out]\n[out2]\ntmp/a.py:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testChangedPluginsInvalidateCache2]\n# flags: --config-file tmp/mypy.ini\nimport a\n[file a.py]\nfrom b import x\ny: int = x\n\n[file a.py.2]\nfrom b import x\ny: int = x\ntouch = 1\n\n[file b.py]\nclass C: ...\ndef f() -> C: ...\nx = f()\n\n[file basic_plugin.py]\nfrom mypy.plugin import Plugin\nfrom version_plugin import __version__, choice\n\nclass MyPlugin(Plugin):\n    def get_function_hook(self, fullname):\n        if fullname.endswith('.f'):\n            return my_hook\n        assert fullname is not None\n        return None\n\ndef my_hook(ctx):\n    if choice:\n        return ctx.api.named_generic_type('builtins.int', [])\n    else:\n        return ctx.api.named_generic_type('builtins.str', [])\n\ndef plugin(version):\n    return MyPlugin\n\n[file version_plugin.py]\n__version__ = 0.1\nchoice = True\n\n[file version_plugin.py.2]\n__version__ = 0.2\nchoice = False\n[file mypy.ini]\n\\[mypy]\nplugins=basic_plugin.py\n[out]\n[out2]\ntmp/a.py:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testAddedPluginsInvalidateCache]\n# flags: --config-file tmp/mypy.ini\nimport a\n[file a.py]\nfrom b import x\ny: int = x\n\n[file a.py.2]\nfrom b import x\ny: int = x\ntouch = 1\n\n[file b.py]\ndef f() -> int: ...\nx = f()\n\n[file basic_plugin.py]\nfrom mypy.plugin import Plugin\n\nclass MyPlugin(Plugin):\n    def get_function_hook(self, fullname):\n        if fullname.endswith('.f'):\n            return my_hook\n        assert fullname is not None\n        return None\n\ndef my_hook(ctx):\n    return ctx.api.named_generic_type('builtins.str', [])\n\ndef plugin(version):\n    return MyPlugin\n\n[file mypy.ini]\n\\[mypy]\npython_version=3.6\n[file mypy.ini.2]\n\\[mypy]\npython_version=3.6\nplugins=basic_plugin.py\n[out]\n[out2]\ntmp/a.py:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testRemovedPluginsInvalidateCache]\n# flags: --config-file tmp/mypy.ini\nimport a\n[file a.py]\nfrom b import x\ny: str = x\n\n[file a.py.2]\nfrom b import x\ny: str = x\ntouch = 1\n\n[file b.py]\ndef f() -> int: ...\nx = f()\n\n[file basic_plugin.py]\nfrom mypy.plugin import Plugin\n\nclass MyPlugin(Plugin):\n    def get_function_hook(self, fullname):\n        if fullname.endswith('.f'):\n            return my_hook\n        assert fullname is not None\n        return None\n\ndef my_hook(ctx):\n    return ctx.api.named_generic_type('builtins.str', [])\n\ndef plugin(version):\n    return MyPlugin\n\n[file mypy.ini]\n\\[mypy]\npython_version=3.6\nplugins=basic_plugin.py\n[file mypy.ini.2]\n\\[mypy]\npython_version=3.6\n[out]\n[out2]\ntmp/a.py:2: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testPluginConfigData]\n# flags: --config-file tmp/mypy.ini\nimport a\nimport b\n[file a.py]\n[file b.py]\n[file test.json]\n{\"a\": false, \"b\": false}\n[file test.json.2]\n{\"a\": true, \"b\": false}\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/config_data.py\n\n# The config change will force a to be rechecked but not b.\n[rechecked a]\n\n[case testLiteralIncrementalTurningIntoLiteral]\nimport mod\nreveal_type(mod.a)\n[file mod.py]\nfrom typing import Literal\na = 1\n[file mod.py.2]\nfrom typing import Literal\na: Literal[2] = 2\n[builtins fixtures/tuple.pyi]\n[out]\nmain:2: note: Revealed type is \"builtins.int\"\n[out2]\nmain:2: note: Revealed type is \"Literal[2]\"\n\n[case testAddedSubStarImport]\n# cmd: mypy -m a pack pack.mod b\n# cmd2: mypy -m other\n[file a.py]\nfrom pack import *\n[file pack/__init__.py]\n[file pack/mod.py]\n[file b.py]\nimport pack.mod\n[file other.py]\nimport a\n[out]\n[out2]\n\n[case testNewAnalyzerIncrementalBrokenNamedTuple]\n\nimport a\n[file a.py]\nfrom b import NT\nx: NT\n[file a.py.2]\nfrom b import NT\nx: NT\nreveal_type(x)\n[file b.py]\nfrom typing import NamedTuple\nNT = NamedTuple('BadName', [('x', int)])\n[builtins fixtures/tuple.pyi]\n[out]\ntmp/b.py:2: error: First argument to namedtuple() should be \"NT\", not \"BadName\"\n[out2]\ntmp/b.py:2: error: First argument to namedtuple() should be \"NT\", not \"BadName\"\ntmp/a.py:3: note: Revealed type is \"tuple[builtins.int, fallback=b.NT]\"\n\n[case testNewAnalyzerIncrementalBrokenNamedTupleNested]\n\nimport a\n[file a.py]\nfrom b import C\nx: C\n[file a.py.2]\nfrom b import C\nx: C\n# touch\n[file b.py]\nclass C: ...\nfrom collections import namedtuple\ndef test() -> None:\n    NT = namedtuple('BadName', ['x', 'y'])\n[builtins fixtures/list.pyi]\n[out]\ntmp/b.py:4: error: First argument to namedtuple() should be \"NT\", not \"BadName\"\n[out2]\ntmp/b.py:4: error: First argument to namedtuple() should be \"NT\", not \"BadName\"\n\n[case testNewAnalyzerIncrementalMethodNamedTuple]\nimport a\n[file a.py]\nfrom b import C\nx: C\n[file a.py.2]\nfrom b import C\nx: C\nreveal_type(x.h)\n[file b.py]\nfrom typing import NamedTuple\nclass C:\n    def __init__(self) -> None:\n        self.h: Hidden\n        Hidden = NamedTuple('Hidden', [('x', int)])\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\ntmp/a.py:3: note: Revealed type is \"tuple[builtins.int, fallback=b.C.Hidden@5]\"\n\n[case testIncrementalNodeCreatedFromGetattr]\nimport a\n[file a.py]\nfrom b import C\nc: C\n[file b.py]\nfrom c import C\n[file c.pyi]\ndef __getattr__(s): ...\n[file a.py.2]\nfrom b import C\nc: C\nreveal_type(c)\n[out]\n[out2]\ntmp/a.py:3: note: Revealed type is \"Any\"\n\n[case testNewAnalyzerIncrementalNestedEnum]\n\nimport a\n[file a.py]\nfrom b import C\nx: C\n[file a.py.2]\nfrom b import C\nx: C\n# touch\n[file b.py]\nclass C: ...\nfrom enum import Enum\n\ndef test() -> None:\n    Color = Enum('Color', 'RED BLACK')\n[builtins fixtures/list.pyi]\n[out]\n[out2]\n\n[case testCannotDetermineTypeFromOtherModule]\n\nimport aa\n\n[file aa.py]\nimport a\n\n[file aa.py.2]\nimport a  # dummy\n\n[file a.py]\nfrom b import Sub\n\nSub().foo\nSub().foo\n\n[file b.py]\nfrom typing import Any\n\nclass desc:\n    def __get__(self, _: Any, __: Any = None) -> int:\n        return 42\n\nclass Base:\n    @property\n    def foo(self) -> int: ...\n\nclass Sub(Base):\n    foo = desc(42)  # type: ignore\n\n[builtins fixtures/property.pyi]\n[out]\n[out2]\n\n[case testRedefinitionClass]\nimport b\n[file a.py]\nfrom whatever import Foo  # type: ignore\n\nclass Foo:  # type: ignore\n    def f(self) -> None:\n        pass\n[file b.py]\nimport a\n[file b.py.2]\nimport a # a change\n\n[case testIsInstanceAdHocIntersectionIncrementalNoChange]\nimport b\n[file a.py]\nclass A: pass\nclass B: pass\n\nclass Foo:\n    def __init__(self) -> None:\n        x: A\n        assert isinstance(x, B)\n        self.x = x\n[file b.py]\nfrom a import Foo\n[file b.py.2]\nfrom a import Foo\nreveal_type(Foo().x)\n[builtins fixtures/isinstance.pyi]\n[out]\n[out2]\ntmp/b.py:2: note: Revealed type is \"a.<subclass of \"a.A\" and \"a.B\">\"\n\n[case testIsInstanceAdHocIntersectionIncrementalNoChangeSameName]\nimport b\n[file c.py]\nclass B: pass\n[file a.py]\nimport c\nclass B: pass\n\nclass Foo:\n    def __init__(self) -> None:\n        x: c.B\n        assert isinstance(x, B)\n        self.x = x\n[file b.py]\nfrom a import Foo\n[file b.py.2]\nfrom a import Foo\nreveal_type(Foo().x)\n[builtins fixtures/isinstance.pyi]\n[out]\n[out2]\ntmp/b.py:2: note: Revealed type is \"a.<subclass of \"c.B\" and \"a.B\">\"\n\n\n[case testIsInstanceAdHocIntersectionIncrementalNoChangeTuple]\nimport b\n[file a.py]\nfrom typing import Tuple\nclass B: pass\n\nclass Foo:\n    def __init__(self) -> None:\n        x: Tuple[int, ...]\n        assert isinstance(x, B)\n        self.x = x\n[file b.py]\nfrom a import Foo\n[file b.py.2]\nfrom a import Foo\nreveal_type(Foo().x)\n[builtins fixtures/isinstance.pyi]\n[out]\n[out2]\ntmp/b.py:2: note: Revealed type is \"a.<subclass of \"tuple[builtins.int, ...]\" and \"a.B\">\"\n\n[case testIsInstanceAdHocIntersectionIncrementalIsInstanceChange]\nimport c\n[file a.py]\nclass A: pass\nclass B: pass\nclass C: pass\n\nclass Foo:\n    def __init__(self) -> None:\n        x: A\n        assert isinstance(x, B)\n        self.x = x\n[file a.py.2]\nclass A: pass\nclass B: pass\nclass C: pass\n\nclass Foo:\n    def __init__(self) -> None:\n        x: A\n        assert isinstance(x, C)\n        self.x = x\n\n[file b.py]\nfrom a import Foo\ny = Foo().x\n\n[file c.py]\nfrom b import y\nreveal_type(y)\n[builtins fixtures/isinstance.pyi]\n[out]\ntmp/c.py:2: note: Revealed type is \"a.<subclass of \"a.A\" and \"a.B\">\"\n[out2]\ntmp/c.py:2: note: Revealed type is \"a.<subclass of \"a.A\" and \"a.C\">\"\n\n[case testIsInstanceAdHocIntersectionIncrementalUnderlyingObjChang]\nimport c\n[file a.py]\nclass A: pass\nclass B: pass\nclass C: pass\nExtra = B\n[file a.py.2]\nclass A: pass\nclass B: pass\nclass C: pass\nExtra = C\n\n[file b.py]\nfrom a import A, Extra\nx: A\nif isinstance(x, Extra):\n    y = x\n\n[file c.py]\nfrom b import y\nreveal_type(y)\n[builtins fixtures/isinstance.pyi]\n[out]\ntmp/c.py:2: note: Revealed type is \"b.<subclass of \"a.A\" and \"a.B\">\"\n[out2]\ntmp/c.py:2: note: Revealed type is \"b.<subclass of \"a.A\" and \"a.C\">\"\n\n[case testIsInstanceAdHocIntersectionIncrementalIntersectionToUnreachable]\nimport c\n[file a.py]\nclass A:\n    x: int\nclass B:\n    x: int\nx: A\nassert isinstance(x, B)\ny = x\n\n[file a.py.2]\nclass A:\n    x: int\nclass B:\n    x: str\nx: A\nassert isinstance(x, B)\ny = x\n\n[file b.py]\nfrom a import y\nz = y\n\n[file c.py]\nfrom b import z\nreveal_type(z)\n[builtins fixtures/isinstance.pyi]\n[out]\ntmp/c.py:2: note: Revealed type is \"a.<subclass of \"a.A\" and \"a.B\">\"\n[out2]\ntmp/b.py:2: error: Cannot determine type of \"y\"\ntmp/c.py:2: note: Revealed type is \"Any\"\n\n[case testIsInstanceAdHocIntersectionIncrementalUnreachaableToIntersection]\nimport c\n[file a.py]\nclass A:\n    x: int\nclass B:\n    x: str\nx: A\nassert isinstance(x, B)\ny = x\n\n[file a.py.2]\nclass A:\n    x: int\nclass B:\n    x: int\nx: A\nassert isinstance(x, B)\ny = x\n\n[file b.py]\nfrom a import y\nz = y\n\n[file c.py]\nfrom b import z\nreveal_type(z)\n[builtins fixtures/isinstance.pyi]\n[out]\ntmp/b.py:2: error: Cannot determine type of \"y\"\ntmp/c.py:2: note: Revealed type is \"Any\"\n[out2]\ntmp/c.py:2: note: Revealed type is \"a.<subclass of \"a.A\" and \"a.B\">\"\n\n[case testIsInstanceAdHocIntersectionIncrementalNestedClass]\nimport b\n[file a.py]\nclass A:\n    class B: ...\n    class C: ...\n    class D:\n        def __init__(self) -> None:\n            x: A.B\n            assert isinstance(x, A.C)\n            self.x = x\n[file b.py]\nfrom a import A\n[file b.py.2]\nfrom a import A\nreveal_type(A.D().x)\n[builtins fixtures/isinstance.pyi]\n[out]\n[out2]\ntmp/b.py:2: note: Revealed type is \"a.<subclass of \"a.A.B\" and \"a.A.C\">\"\n\n[case testIsInstanceAdHocIntersectionIncrementalUnions]\nimport c\n[file a.py]\nimport b\nclass A:\n    p: b.D\nclass B:\n    p: b.D\nclass C:\n    p: b.D\n    c: str\nx: A\nassert isinstance(x, (B, C))\ny = x\n[file b.py]\nclass D:\n    p: int\n[file c.py]\nfrom a import y\n[file c.py.2]\nfrom a import y, C\nreveal_type(y)\nreveal_type(y.p.p)\nassert isinstance(y, C)\nreveal_type(y.c)\n[builtins fixtures/isinstance.pyi]\n[out]\n[out2]\ntmp/c.py:2: note: Revealed type is \"a.<subclass of \"a.A\" and \"a.B\"> | a.<subclass of \"a.A\" and \"a.C\">\"\ntmp/c.py:3: note: Revealed type is \"builtins.int\"\ntmp/c.py:5: note: Revealed type is \"builtins.str\"\n\n[case testStubFixupIssues]\nimport a\n[file a.py]\nimport p\n[file a.py.2]\nimport p\np.N\n\n[file p/__init__.pyi]\nfrom p.util import *\n\n[file p/util.pyi]\nfrom p.params import N\nclass Test: ...\nx: N\n\n[file p/params.pyi]\nimport p.util\nclass N(p.util.Test):\n    ...\n[out2]\ntmp/a.py:2: error: \"object\" has no attribute \"N\"\n\n[case testIncrementalIndirectSkipWarnUnused]\n# flags: --follow-imports=skip --warn-unused-ignores\n# cmd: mypy -m main a b c1\n# cmd2: mypy -m main a b c2\n\n[file main.py]\nimport a\na.foo.bar()\n\n[file a.py]\nimport b\nfoo = b.Foo()\n\n[file b.py]\nfrom c1 import C\nclass Foo:\n    def bar(self) -> C:\n        return C()\n\n[file c1.py]\nclass C: pass\n\n[file b.py.2]\nfrom c2 import C\nclass Foo:\n    def bar(self) -> C:\n        return C()\n\n[file c2.py]\n\n[delete c1.py.2]\n[file c2.py.2]\nclass C: pass\n\n[case testIncrementalNestedNamedTuple]\nimport a\n\n[file a.py]\nimport b\n\n[file a.py.2]\nimport b # foo\n\n[file b.py]\nfrom typing import NamedTuple\n\ndef f() -> None:\n    class NT(NamedTuple):\n        x: int\n\n    n: NT = NT(x=2)\n\ndef g() -> None:\n    NT = NamedTuple('NT', [('y', str)])\n\n    n: NT = NT(y='x')\n\n[builtins fixtures/tuple.pyi]\n\n[case testIncrementalNestedTypeAlias]\nimport a\n\n[file a.py]\nimport b\n\n[file a.py.2]\nimport b\nreveal_type(b.C().x)\nreveal_type(b.D().x)\n\n[file b.py]\nfrom typing import List\n\nclass C:\n    def __init__(self) -> None:\n        Alias = List[int]\n        self.x = []  # type: Alias\n\nclass D:\n    def __init__(self) -> None:\n        Alias = List[str]\n        self.x = []  # type: Alias\n\n[builtins fixtures/list.pyi]\n[out2]\ntmp/a.py:2: note: Revealed type is \"builtins.list[builtins.int]\"\ntmp/a.py:3: note: Revealed type is \"builtins.list[builtins.str]\"\n\n[case testIncrementalNamespacePackage1]\n# flags: --namespace-packages\nimport m\n[file m.py]\nfrom foo.bar import x\nx + 0\n[file foo/bar.py]\nx = 0\n[rechecked]\n[stale]\n\n[case testIncrementalNamespacePackage2]\n# flags: --namespace-packages\nimport m\n[file m.py]\nfrom foo import bar\nbar.x + 0\n[file foo/bar.py]\nx = 0\n[rechecked]\n[stale]\n\n[case testExplicitReexportImportCycleWildcard]\n# flags: --no-implicit-reexport\nimport pkg.a\n[file pkg/__init__.pyi]\n\n[file pkg/a.pyi]\nMYPY = False\nif MYPY:\n    from pkg.b import B\n\n[file pkg/b.pyi]\nimport pkg.a\nMYPY = False\nif MYPY:\n    from pkg.c import C\nclass B:\n    pass\n\n[file pkg/c.pyi]\nfrom pkg.a import *\nclass C:\n    pass\n[rechecked]\n[stale]\n\n\n[case testEnumAreStillFinalAfterCache]\nimport a\nclass Ok(a.RegularEnum):\n    x = 1\nclass NotOk(a.FinalEnum):\n    x = 1\n[file a.py]\nfrom enum import Enum\nclass RegularEnum(Enum):\n    x: int\nclass FinalEnum(Enum):\n    x = 1\n[builtins fixtures/isinstance.pyi]\n[out]\nmain:3: error: Cannot override writable attribute \"x\" with a final one\nmain:3: error: Incompatible types in assignment (expression has type \"Ok\", base class \"RegularEnum\" defined the type as \"int\")\nmain:4: error: Cannot extend enum with existing members: \"FinalEnum\"\nmain:5: error: Cannot override final attribute \"x\" (previously declared in base class \"FinalEnum\")\n[out2]\nmain:3: error: Cannot override writable attribute \"x\" with a final one\nmain:3: error: Incompatible types in assignment (expression has type \"Ok\", base class \"RegularEnum\" defined the type as \"int\")\nmain:4: error: Cannot extend enum with existing members: \"FinalEnum\"\nmain:5: error: Cannot override final attribute \"x\" (previously declared in base class \"FinalEnum\")\n\n[case testSlotsSerialization]\nimport a\n[file a.py]\nfrom b import C\n\nclass D(C):\n    pass\n[file b.py]\nclass C:\n    __slots__ = ('x',)\n[file a.py.2]\nfrom b import C\n\nclass D(C):\n    __slots__ = ('y',)\n\n    def __init__(self) -> None:\n        self.x = 1\n        self.y = 2\n        self.z = 3\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\ntmp/a.py:9: error: Trying to assign name \"z\" that is not in \"__slots__\" of type \"a.D\"\n\n[case testMethodAliasIncremental]\nimport b\n[file a.py]\nclass A:\n    def f(self) -> None: pass\n    g = f\n\n[file b.py]\nfrom a import A\nA().g()\n[file b.py.2]\n# trivial change\nfrom a import A\nA().g()\n[out]\n[out2]\n\n[case testIncrementalWithDifferentKindsOfNestedTypesWithinMethod]\n\nimport a\n\n[file a.py]\nimport b\n\n[file a.py.2]\nimport b\nb.xyz\n\n[file b.py]\nfrom typing import NamedTuple, NewType, TypedDict\nfrom typing_extensions import TypeAlias\nfrom enum import Enum\nfrom dataclasses import dataclass\n\nclass C:\n    def f(self) -> None:\n        class C:\n            c: int\n        class NT1(NamedTuple):\n            c: int\n        NT2 = NamedTuple(\"NT2\", [(\"c\", int)])\n        class NT3(NT1):\n            pass\n        class TD(TypedDict):\n            c: int\n        TD2 = TypedDict(\"TD2\", {\"c\": int})\n        class E(Enum):\n            X = 1\n        @dataclass\n        class DC:\n            c: int\n        Alias: TypeAlias = NT1\n        N = NewType(\"N\", NT1)\n\n        c: C = C()\n        nt1: NT1 = NT1(c=1)\n        nt2: NT2 = NT2(c=1)\n        nt3: NT3 = NT3(c=1)\n        td: TD = TD(c=1)\n        td2: TD2 = TD2(c=1)\n        e: E = E.X\n        dc: DC = DC(c=1)\n        al: Alias = Alias(c=1)\n        n: N = N(NT1(c=1))\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out2]\ntmp/a.py:2: error: \"object\" has no attribute \"xyz\"\n\n[case testIncrementalInvalidNamedTupleInUnannotatedFunction]\n# flags: --disable-error-code=annotation-unchecked\nimport a\n\n[file a.py]\nimport b\n\n[file a.py.2]\nimport b # f\n\n[file b.py]\nfrom typing import NamedTuple\n\ndef toplevel(fields):\n    TupleType = NamedTuple(\"TupleType\", fields)\n    class InheritFromTuple(TupleType):\n        pass\n    NT2 = NamedTuple(\"bad\", [('x', int)])\n    nt2: NT2 = NT2(x=1)\n\nclass C:\n    def method(self, fields):\n        TupleType = NamedTuple(\"TupleType\", fields)\n        class InheritFromTuple(TupleType):\n            pass\n        NT2 = NamedTuple(\"bad\", [('x', int)])\n        nt2: NT2 = NT2(x=1)\n\n[builtins fixtures/tuple.pyi]\n\n[case testNamedTupleUpdateNonRecursiveToRecursiveCoarse]\nimport c\n[file a.py]\nfrom b import M\nfrom typing import NamedTuple, Optional\nclass N(NamedTuple):\n    r: Optional[M]\n    x: int\nn: N\n[file b.py]\nfrom a import N\nfrom typing import NamedTuple\nclass M(NamedTuple):\n    r: None\n    x: int\n[file b.py.2]\nfrom a import N\nfrom typing import NamedTuple, Optional\nclass M(NamedTuple):\n    r: Optional[N]\n    x: int\n[file c.py]\nimport a\ndef f(x: a.N) -> None:\n    if x.r is not None:\n        s: int = x.r.x\n[file c.py.3]\nimport a\ndef f(x: a.N) -> None:\n    if x.r is not None and x.r.r is not None and x.r.r.r is not None:\n        reveal_type(x)\n        s: int = x.r.r.r.r\nf(a.n)\nreveal_type(a.n)\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\n[out3]\ntmp/c.py:4: note: Revealed type is \"tuple[tuple[... | None, builtins.int, fallback=b.M] | None, builtins.int, fallback=a.N]\"\ntmp/c.py:5: error: Incompatible types in assignment (expression has type \"N | None\", variable has type \"int\")\ntmp/c.py:7: note: Revealed type is \"tuple[tuple[... | None, builtins.int, fallback=b.M] | None, builtins.int, fallback=a.N]\"\n\n[case testTupleTypeUpdateNonRecursiveToRecursiveCoarse]\nimport c\n[file a.py]\nfrom b import M\nfrom typing import Tuple, Optional\nclass N(Tuple[Optional[M], int]): ...\n[file b.py]\nfrom a import N\nfrom typing import Tuple\nclass M(Tuple[None, int]): ...\n[file b.py.2]\nfrom a import N\nfrom typing import Tuple, Optional\nclass M(Tuple[Optional[N], int]): ...\n[file c.py]\nimport a\ndef f(x: a.N) -> None:\n    if x[0] is not None:\n        s: int = x[0][1]\n[file c.py.3]\nimport a\ndef f(x: a.N) -> None:\n    if x[0] is not None and x[0][0] is not None and x[0][0][0] is not None:\n        reveal_type(x)\n        s: int = x[0][0][0][0]\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\n[out3]\ntmp/c.py:4: note: Revealed type is \"tuple[tuple[... | None, builtins.int, fallback=b.M] | None, builtins.int, fallback=a.N]\"\ntmp/c.py:5: error: Incompatible types in assignment (expression has type \"N | None\", variable has type \"int\")\n\n[case testTypeAliasUpdateNonRecursiveToRecursiveCoarse]\nimport c\n[file a.py]\nfrom b import M\nfrom typing import Tuple, Optional\nN = Tuple[Optional[M], int]\n[file b.py]\nfrom a import N\nfrom typing import Tuple\nM = Tuple[None, int]\n[file b.py.2]\nfrom a import N\nfrom typing import Tuple, Optional\nM = Tuple[Optional[N], int]\n[file c.py]\nimport a\ndef f(x: a.N) -> None:\n    if x[0] is not None:\n        s: int = x[0][1]\n[file c.py.3]\nimport a\ndef f(x: a.N) -> None:\n    if x[0] is not None and x[0][0] is not None and x[0][0][0] is not None:\n        reveal_type(x)\n        s: int = x[0][0][0][0]\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\n[out3]\ntmp/c.py:4: note: Revealed type is \"tuple[tuple[... | None, builtins.int] | None, builtins.int]\"\ntmp/c.py:5: error: Incompatible types in assignment (expression has type \"N | None\", variable has type \"int\")\n\n[case testTypedDictUpdateNonRecursiveToRecursiveCoarse]\nimport c\n[file a.py]\nfrom b import M\nfrom typing import TypedDict, Optional\nclass N(TypedDict):\n    r: Optional[M]\n    x: int\nn: N\n[file b.py]\nfrom a import N\nfrom typing import TypedDict\nclass M(TypedDict):\n    r: None\n    x: int\n[file b.py.2]\nfrom a import N\nfrom typing import TypedDict, Optional\nclass M(TypedDict):\n    r: Optional[N]\n    x: int\n[file c.py]\nimport a\ndef f(x: a.N) -> None:\n    if x[\"r\"] is not None:\n        s: int = x[\"r\"][\"x\"]\n[file c.py.3]\nimport a\ndef f(x: a.N) -> None:\n    if x[\"r\"] is not None and x[\"r\"][\"r\"] is not None and x[\"r\"][\"r\"][\"r\"] is not None:\n        reveal_type(x)\n        s: int = x[\"r\"][\"r\"][\"r\"][\"r\"]\nf(a.n)\nreveal_type(a.n)\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n[out2]\n[out3]\ntmp/c.py:4: note: Revealed type is \"TypedDict('a.N', {'r': TypedDict('b.M', {'r': ... | None, 'x': builtins.int}) | None, 'x': builtins.int})\"\ntmp/c.py:5: error: Incompatible types in assignment (expression has type \"N | None\", variable has type \"int\")\ntmp/c.py:7: note: Revealed type is \"TypedDict('a.N', {'r': TypedDict('b.M', {'r': ... | None, 'x': builtins.int}) | None, 'x': builtins.int})\"\n\n[case testIncrementalAddClassMethodPlugin]\n# flags: --config-file tmp/mypy.ini\nimport b\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/add_classmethod.py\n\n[file a.py]\nclass BaseAddMethod: pass\n\nclass MyClass(BaseAddMethod):\n    pass\n\n[file b.py]\nimport a\n\n[file b.py.2]\nimport a\n\nmy_class = a.MyClass()\nreveal_type(a.MyClass.foo_classmethod)\nreveal_type(a.MyClass.foo_staticmethod)\nreveal_type(my_class.foo_classmethod)\nreveal_type(my_class.foo_staticmethod)\n\n[rechecked b]\n[out2]\ntmp/b.py:4: note: Revealed type is \"def ()\"\ntmp/b.py:5: note: Revealed type is \"def (builtins.int) -> builtins.str\"\ntmp/b.py:6: note: Revealed type is \"def ()\"\ntmp/b.py:7: note: Revealed type is \"def (builtins.int) -> builtins.str\"\n\n[case testIncrementalAddOverloadedMethodPlugin]\n# flags: --config-file tmp/mypy.ini\nimport b\n\n[file mypy.ini]\n\\[mypy]\nplugins=<ROOT>/test-data/unit/plugins/add_overloaded_method.py\n\n[file a.py]\nclass AddOverloadedMethod: pass\n\nclass MyClass(AddOverloadedMethod):\n    pass\n\n[file b.py]\nimport a\n\n[file b.py.2]\nimport a\n\nreveal_type(a.MyClass.method)\nreveal_type(a.MyClass.clsmethod)\nreveal_type(a.MyClass.stmethod)\n\nmy_class = a.MyClass()\nreveal_type(my_class.method)\nreveal_type(my_class.clsmethod)\nreveal_type(my_class.stmethod)\n[rechecked b]\n[out2]\ntmp/b.py:3: note: Revealed type is \"Overload(def (self: a.MyClass, arg: builtins.int) -> builtins.str, def (self: a.MyClass, arg: builtins.str) -> builtins.int)\"\ntmp/b.py:4: note: Revealed type is \"Overload(def (arg: builtins.int) -> builtins.str, def (arg: builtins.str) -> builtins.int)\"\ntmp/b.py:5: note: Revealed type is \"Overload(def (arg: builtins.int) -> builtins.str, def (arg: builtins.str) -> builtins.int)\"\ntmp/b.py:8: note: Revealed type is \"Overload(def (arg: builtins.int) -> builtins.str, def (arg: builtins.str) -> builtins.int)\"\ntmp/b.py:9: note: Revealed type is \"Overload(def (arg: builtins.int) -> builtins.str, def (arg: builtins.str) -> builtins.int)\"\ntmp/b.py:10: note: Revealed type is \"Overload(def (arg: builtins.int) -> builtins.str, def (arg: builtins.str) -> builtins.int)\"\n\n[case testGenericNamedTupleSerialization]\nimport b\n[file a.py]\nfrom typing import NamedTuple, Generic, TypeVar\n\nT = TypeVar(\"T\")\nclass NT(NamedTuple, Generic[T]):\n    key: int\n    value: T\n\n[file b.py]\nfrom a import NT\nnt = NT(key=0, value=\"yes\")\ns: str = nt.value\n[file b.py.2]\nfrom a import NT\nnt = NT(key=0, value=42)\ns: str = nt.value\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\ntmp/b.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testGenericTypedDictSerialization]\nimport b\n[file a.py]\nfrom typing import TypedDict, Generic, TypeVar\n\nT = TypeVar(\"T\")\nclass TD(TypedDict, Generic[T]):\n    key: int\n    value: T\n\n[file b.py]\nfrom a import TD\ntd = TD(key=0, value=\"yes\")\ns: str = td[\"value\"]\n[file b.py.2]\nfrom a import TD\ntd = TD(key=0, value=42)\ns: str = td[\"value\"]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n[out2]\ntmp/b.py:3: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testUnpackKwargsSerialize]\nimport m\n[file lib.py]\nfrom typing import TypedDict\nfrom typing_extensions import Unpack\n\nclass Person(TypedDict):\n    name: str\n    age: int\n\ndef foo(**kwargs: Unpack[Person]):\n    ...\n\n[file m.py]\nfrom lib import foo\nfoo(name='Jennifer', age=38)\n[file m.py.2]\nfrom lib import foo\nfoo(name='Jennifer', age=\"38\")\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n[out2]\ntmp/m.py:2: error: Argument \"age\" to \"foo\" has incompatible type \"str\"; expected \"int\"\n\n[case testDisableEnableErrorCodesIncremental]\n# flags: --disable-error-code truthy-bool\n# flags2: --enable-error-code truthy-bool\nclass Foo:\n    pass\n\nfoo = Foo()\nif foo:\n    ...\n[out]\n[out2]\nmain:7: error: \"__main__.foo\" has type \"Foo\" which does not implement __bool__ or __len__ so it could always be true in boolean context\n\n[case testModuleAsProtocolImplementationSerialize]\nimport m\n[file m.py]\nfrom typing import Protocol\nfrom lib import C\n\nclass Options(Protocol):\n    timeout: int\n    def update(self) -> bool: ...\n\ndef setup(options: Options) -> None: ...\nsetup(C().config)\n\n[file lib.py]\nimport default_config\n\nclass C:\n    config = default_config\n\n[file default_config.py]\ntimeout = 100\ndef update() -> bool: ...\n\n[file default_config.py.2]\ntimeout = 100\ndef update() -> str: ...\n[builtins fixtures/module.pyi]\n[out]\n[out2]\ntmp/m.py:9: error: Argument 1 to \"setup\" has incompatible type Module; expected \"Options\"\ntmp/m.py:9: note: Following member(s) of Module \"default_config\" have conflicts:\ntmp/m.py:9: note:     Expected:\ntmp/m.py:9: note:         def update() -> bool\ntmp/m.py:9: note:     Got:\ntmp/m.py:9: note:         def update() -> str\n\n[case testAbstractBodyTurnsEmptyCoarse]\nfrom b import Base\n\nclass Sub(Base):\n    def meth(self) -> int:\n        return super().meth()\n\n[file b.py]\nfrom abc import abstractmethod\nclass Base:\n    @abstractmethod\n    def meth(self) -> int: return 0\n\n[file b.py.2]\nfrom abc import abstractmethod\nclass Base:\n    @abstractmethod\n    def meth(self) -> int: ...\n[out]\n[out2]\nmain:5: error: Call to abstract method \"meth\" of \"Base\" with trivial body via super() is unsafe\n\n[case testLiteralCoarseGrainedChainedAliases]\nfrom mod1 import Alias1\nfrom typing import Literal\nx: Alias1\ndef expect_int(x: int) -> None: pass\nexpect_int(x)\n[file mod1.py]\nfrom mod2 import Alias2\nAlias1 = Alias2\n[file mod2.py]\nfrom mod3 import Alias3\nAlias2 = Alias3\n[file mod3.py]\nfrom typing import Literal\nAlias3 = int\n[file mod3.py.2]\nfrom typing import Literal\nAlias3 = str\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\nmain:5: error: Argument 1 to \"expect_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testLiteralCoarseGrainedChainedAliases2]\nfrom mod1 import Alias1\nfrom typing import Literal\nx: Alias1\ndef expect_3(x: Literal[3]) -> None: pass\nexpect_3(x)\n[file mod1.py]\nfrom mod2 import Alias2\nAlias1 = Alias2\n[file mod2.py]\nfrom mod3 import Alias3\nAlias2 = Alias3\n[file mod3.py]\nfrom typing import Literal\nAlias3 = Literal[3]\n[file mod3.py.2]\nfrom typing import Literal\nAlias3 = Literal[4]\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\nmain:5: error: Argument 1 to \"expect_3\" has incompatible type \"Literal[4]\"; expected \"Literal[3]\"\n\n[case testDoubleReexportFunctionUpdated]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\nreveal_type(f.foo)\n\n[file f.py]\nimport c\ndef foo(arg: c.C) -> None: pass\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb1, pb2\nC = pb2.C\n\n[file pb1.py]\nclass C: ...\n[file pb2.py]\nclass C: ...\n[out]\n[out2]\n[out3]\ntmp/m.py:2: note: Revealed type is \"def (arg: pb2.C)\"\n\n[case testDoubleReexportGenericUpdated]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\nx: f.F\nreveal_type(x[0])\n\n[file f.py]\nimport c\nclass FB(list[c.C]): ...\nclass F(FB): ...\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb1, pb2\nC = pb2.C\n\n[file pb1.py]\nclass C: ...\n[file pb2.py]\nclass C: ...\n[out]\n[out2]\n[out3]\ntmp/m.py:3: note: Revealed type is \"pb2.C\"\n\n[case testNoCrashDoubleReexportFunctionEmpty]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\n# modify\n\n[file f.py]\nimport c\ndef foo(arg: c.C) -> None: pass\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb1, pb2\nC = pb2.C\n\n[file pb1.py]\nclass C: ...\n[file pb2.py.2]\nclass C: ...\n[file pb1.py.2]\n[out]\n[out2]\n[out3]\n\n[case testNoCrashDoubleReexportAliasEmpty]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\n# modify\n\n[file f.py]\nimport c\nD = list[c.C]\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb2\nC = pb2.C\n\n[file pb1.py]\nclass C: ...\n[file pb2.py.2]\nclass C: ...\n[file pb1.py.2]\n[out]\n[out2]\n[out3]\n\n[case testNoCrashDoubleReexportBaseEmpty]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\n# modify\n\n[file f.py]\nimport c\nclass D(c.C): pass\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb1, pb2\nC = pb2.C\n\n[file pb1.py]\nclass C: ...\n[file pb2.py.2]\nclass C: ...\n[file pb1.py.2]\n[out]\n[out2]\n[out3]\n\n[case testNoCrashDoubleReexportBaseEmpty2]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\n# modify\n\n[file f.py]\nimport c\nclass D(c.C): pass\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb2\nC = pb2.C\n\n[file pb1.py]\nclass C: ...\n[file pb2.py.2]\nclass C: ...\n[file pb1.py.2]\n[out]\n[out2]\n[out3]\n\n[case testDoubleReexportMetaUpdated]\nimport m\nclass C(metaclass=m.M): ...\n\n[file m.py]\nfrom types import M\n\n[file types.py]\nclass M(type): ...\n[file types.py.2]\nclass M: ...\n[out]\n[out2]\nmain:2: error: Metaclasses not inheriting from \"type\" are not supported\n\n[case testIncrementalOkChangeWithSave2]\nimport mod1\nx: int = mod1.x\n\n[file mod1.py]\nfrom mod2 import x\n\n[file mod2.py]\nx = 1\n\n[file mod2.py.2]\nx = \"no way\"\n[out]\n[out2]\nmain:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testNoCrashDoubleReexportMetaEmpty]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\n# modify\n\n[file f.py]\nimport c\nclass D(metaclass=c.C): pass\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb1, pb2\nC = pb2.C\n\n[file pb1.py]\nclass C(type): ...\n[file pb2.py.2]\nclass C(type): ...\n[file pb1.py.2]\n[out]\n[out2]\n[out3]\n\n[case testNoCrashDoubleReexportMetaEmpty2]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\n# modify\n\n[file f.py]\nimport c\nclass D(metaclass=c.C): pass\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb2\nC = pb2.C\n\n[file pb1.py]\nclass C(type): ...\n[file pb2.py.2]\nclass C(type): ...\n[file pb1.py.2]\n[out]\n[out2]\n[out3]\n\n[case testNoCrashDoubleReexportTypedDictEmpty]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\n# modify\n\n[file f.py]\nfrom typing import TypedDict\nimport c\nclass D(TypedDict):\n    x: c.C\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb1, pb2\nC = pb2.C\n\n[file pb1.py]\nclass C: ...\n[file pb2.py.2]\nclass C: ...\n[file pb1.py.2]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n[out2]\n[out3]\n\n[case testNoCrashDoubleReexportTupleEmpty]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\n# modify\n\n[file f.py]\nfrom typing import Tuple\nimport c\nclass D(Tuple[c.C, int]): pass\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb1, pb2\nC = pb2.C\n\n[file pb1.py]\nclass C: ...\n[file pb2.py.2]\nclass C: ...\n[file pb1.py.2]\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\n[out3]\n\n[case testNoCrashDoubleReexportOverloadEmpty]\nimport m\n\n[file m.py]\nimport f\n[file m.py.3]\nimport f\n# modify\n\n[file f.py]\nfrom typing import Any, overload\nimport c\n\n@overload\ndef foo(arg: int) -> None: ...\n@overload\ndef foo(arg: c.C) -> None: ...\ndef foo(arg: Any) -> None:\n    pass\n\n[file c.py]\nfrom types import C\n\n[file types.py]\nimport pb1\nC = pb1.C\n[file types.py.2]\nimport pb1, pb2\nC = pb2.C\n\n[file pb1.py]\nclass C: ...\n[file pb2.py.2]\nclass C: ...\n[file pb1.py.2]\n[out]\n[out2]\n[out3]\n\n[case testNoCrashOnPartialLambdaInference]\n# flags: --no-local-partial-types\nimport m\n[file m.py]\nfrom typing import TypeVar, Callable\n\nV = TypeVar(\"V\")\ndef apply(val: V, func: Callable[[V], None]) -> None:\n    return func(val)\n\nxs = []\napply(0, lambda a: xs.append(a))\n[file m.py.2]\nfrom typing import TypeVar, Callable\n\nV = TypeVar(\"V\")\ndef apply(val: V, func: Callable[[V], None]) -> None:\n    return func(val)\n\nxs = []\napply(0, lambda a: xs.append(a))\nreveal_type(xs)\n[builtins fixtures/list.pyi]\n[out]\n[out2]\ntmp/m.py:9: note: Revealed type is \"builtins.list[builtins.int]\"\n\n[case testTypingSelfCoarse]\nimport m\n[file lib.py]\nfrom typing import Self\n\nclass C:\n    def meth(self, other: Self) -> Self: ...\n\n[file m.py]\nimport lib\nclass D: ...\n[file m.py.2]\nimport lib\nclass D(lib.C): ...\n\nreveal_type(D.meth)\nreveal_type(D().meth)\n[out]\n[out2]\ntmp/m.py:4: note: Revealed type is \"def [Self <: lib.C] (self: Self`1, other: Self`1) -> Self`1\"\ntmp/m.py:5: note: Revealed type is \"def (other: m.D) -> m.D\"\n\n[case testIncrementalNestedGenericCallableCrash]\nfrom typing import TypeVar, Callable\n\nT = TypeVar(\"T\")\n\nclass B:\n    def foo(self) -> Callable[[T], T]: ...\n\nclass C(B):\n    def __init__(self) -> None:\n        self.x = self.foo()\n[out]\n[out2]\n\n[case testNoCrashIncrementalMetaAny]\nimport a\n[file a.py]\nfrom m import Foo\n[file a.py.2]\nfrom m import Foo\n# touch\n[file m.py]\nfrom missing_module import Meta  # type: ignore[import]\nclass Foo(metaclass=Meta): ...\n\n[case testIncrementalNativeInt]\nimport a\n[file a.py]\nfrom mypy_extensions import i64\nx: i64 = 0\n[file a.py.2]\nfrom mypy_extensions import i64\nx: i64 = 0\ny: int = x\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\n\n[case testGenericTypedDictWithError]\nimport b\n[file a.py]\nfrom typing import Generic, TypeVar, TypedDict\n\nTValue = TypeVar(\"TValue\")\nclass Dict(TypedDict, Generic[TValue]):\n    value: TValue\n\n[file b.py]\nfrom a import Dict, TValue\n\ndef f(d: Dict[TValue]) -> TValue:\n    return d[\"value\"]\ndef g(d: Dict[TValue]) -> TValue:\n    return d[\"x\"]\n\n[file b.py.2]\nfrom a import Dict, TValue\n\ndef f(d: Dict[TValue]) -> TValue:\n    return d[\"value\"]\ndef g(d: Dict[TValue]) -> TValue:\n    return d[\"y\"]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\ntmp/b.py:6: error: TypedDict \"a.Dict[TValue]\" has no key \"x\"\n[out2]\ntmp/b.py:6: error: TypedDict \"a.Dict[TValue]\" has no key \"y\"\n\n[case testParamSpecNoCrash]\nimport m\n[file m.py]\nfrom typing import Callable, TypeVar\nfrom lib import C\n\nT = TypeVar(\"T\")\ndef test(x: Callable[..., T]) -> T: ...\ntest(C)  # type: ignore\n\n[file m.py.2]\nfrom typing import Callable, TypeVar\nfrom lib import C\n\nT = TypeVar(\"T\")\ndef test(x: Callable[..., T]) -> T: ...\ntest(C)  # type: ignore\n# touch\n[file lib.py]\nfrom typing import ParamSpec, Generic, Callable\n\nP = ParamSpec(\"P\")\nclass C(Generic[P]):\n    def __init__(self, fn: Callable[P, int]) -> None: ...\n[builtins fixtures/dict.pyi]\n\n[case testVariadicClassIncrementalUpdateRegularToVariadic]\nfrom typing import Any\nfrom lib import C\n\nx: C[int, str]\n\n[file lib.py]\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nclass C(Generic[T, S]): ...\n\n[file lib.py.2]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass C(Generic[Unpack[Ts]]): ...\n[builtins fixtures/tuple.pyi]\n\n[case testVariadicClassIncrementalUpdateVariadicToRegular]\nfrom typing import Any\nfrom lib import C\n\nx: C[int, str, int]\n\n[file lib.py]\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass C(Generic[Unpack[Ts]]): ...\n[file lib.py.2]\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\nclass C(Generic[T, S]): ...\n[builtins fixtures/tuple.pyi]\n[out2]\nmain:4: error: \"C\" expects 2 type arguments, but 3 given\n\n[case testVariadicTupleIncrementalUpdateNoCrash]\nimport m\n[file m.py]\nfrom typing import Any\nfrom lib import C\n\nx: C[Any]\n[file m.py.2]\nfrom lib import C\n\nx: C[int]\n[file lib.py]\nfrom typing import Generic, Tuple, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\nclass C(Tuple[Unpack[Ts]]): ...\n[builtins fixtures/tuple.pyi]\n\n[case testNoIncrementalCrashOnInvalidTypedDict]\nimport m\n[file m.py]\nimport counts\n[file m.py.2]\nimport counts\n# touch\n[file counts.py]\nfrom typing import TypedDict\nCounts = TypedDict(\"Counts\", {k: int for k in \"abc\"})  # type: ignore\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNoIncrementalCrashOnInvalidTypedDictFunc]\nimport m\n[file m.py]\nimport counts\n[file m.py.2]\nimport counts\n# touch\n[file counts.py]\nfrom typing import TypedDict\ndef test() -> None:\n    Counts = TypedDict(\"Counts\", {k: int for k in \"abc\"})  # type: ignore\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNoIncrementalCrashOnTypedDictMethod]\nimport a\n[file a.py]\nfrom b import C\nx: C\n[file a.py.2]\nfrom b import C\nx: C\nreveal_type(x.h)\n[file b.py]\nfrom typing import TypedDict\nclass C:\n    def __init__(self) -> None:\n        self.h: Hidden\n        class Hidden(TypedDict):\n            x: int\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n[out2]\ntmp/a.py:3: note: Revealed type is \"TypedDict('b.C.Hidden@5', {'x': builtins.int})\"\n\n[case testNoIncrementalCrashOnInvalidEnumMethod]\nimport a\n[file a.py]\nfrom lib import TheClass\n[file a.py.2]\nfrom lib import TheClass\nx: TheClass\nreveal_type(x.enum_type)\n[file lib.py]\nimport enum\n\nclass TheClass:\n    def __init__(self) -> None:\n        names = [\"foo\"]\n        pyenum = enum.Enum('Blah', {  # type: ignore[misc]\n            x.upper(): x\n            for x in names\n        })\n        self.enum_type = pyenum\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\ntmp/a.py:3: note: Revealed type is \"def (value: builtins.object) -> lib.TheClass.pyenum@6\"\n\n-- Note: do not use _no_parallel unless really needed!\n[case testIncrementalFunctoolsPartial_no_parallel]\nimport a\n\n[file a.py]\nfrom typing import Callable\nfrom partial import p1, p2\n\np1(1, \"a\", 3)  # OK\np1(1, \"a\", c=3)  # OK\np1(1, b=\"a\", c=3)  # OK\n\nreveal_type(p1)\n\ndef takes_callable_int(f: Callable[..., int]) -> None: ...\ndef takes_callable_str(f: Callable[..., str]) -> None: ...\ntakes_callable_int(p1)\ntakes_callable_str(p1)\n\np2(\"a\")  # OK\np2(\"a\", 3)  # OK\np2(\"a\", c=3)  # OK\np2(1, 3)\np2(1, \"a\", 3)\np2(a=1, b=\"a\", c=3)\n\n[file a.py.2]\nfrom typing import Callable\nfrom partial import p3\n\np3(1)  # OK\np3(1, c=3)  # OK\np3(a=1)  # OK\np3(1, b=\"a\", c=3)  # OK, keywords can be clobbered\np3(1, 3)\n\n[file partial.py]\nfrom typing import Callable\nimport functools\n\ndef foo(a: int, b: str, c: int = 5) -> int: ...\n\np1 = functools.partial(foo)\np2 = functools.partial(foo, 1)\np3 = functools.partial(foo, b=\"a\")\n[builtins fixtures/dict.pyi]\n[out]\ntmp/a.py:8: note: Revealed type is \"functools.partial[builtins.int]\"\ntmp/a.py:13: error: Argument 1 to \"takes_callable_str\" has incompatible type \"partial[int]\"; expected \"Callable[..., str]\"\ntmp/a.py:13: note: \"partial[int].__call__\" has type \"def __call__(__self, *args: Any, **kwargs: Any) -> int\"\ntmp/a.py:18: error: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\ntmp/a.py:19: error: Too many arguments for \"foo\"\ntmp/a.py:19: error: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\ntmp/a.py:19: error: Argument 2 to \"foo\" has incompatible type \"str\"; expected \"int\"\ntmp/a.py:20: error: Unexpected keyword argument \"a\" for \"foo\"\ntmp/a.py:20: note: \"foo\" defined in \"partial\"\n[out2]\ntmp/a.py:8: error: Too many positional arguments for \"foo\"\ntmp/a.py:8: error: Argument 2 to \"foo\" has incompatible type \"int\"; expected \"str\"\n\n[case testStartUsingTypeGuard]\nimport a\n[file a.py]\nfrom lib import guard\nfrom typing import Union\nfrom typing_extensions import assert_type\nx: Union[int, str]\n\n[file a.py.2]\nfrom lib import guard\nfrom typing import Union\nfrom typing_extensions import assert_type\nx: Union[int, str]\nif guard(x):\n    assert_type(x, int)\nelse:\n    assert_type(x, Union[int, str])\n[file lib.py]\nfrom typing_extensions import TypeGuard\ndef guard(x: object) -> TypeGuard[int]:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testStartUsingTypeIs]\nimport a\n[file a.py]\nfrom lib import guard\nfrom typing import Union\nfrom typing_extensions import assert_type\nx: Union[int, str]\n\n[file a.py.2]\nfrom lib import guard\nfrom typing import Union\nfrom typing_extensions import assert_type\nx: Union[int, str]\nif guard(x):\n    assert_type(x, int)\nelse:\n    assert_type(x, str)\n[file lib.py]\nfrom typing_extensions import TypeIs\ndef guard(x: object) -> TypeIs[int]:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testTypeGuardToTypeIs]\nimport a\n[file a.py]\nfrom lib import guard\nfrom typing import Union\nfrom typing_extensions import assert_type\nx: Union[int, str]\nif guard(x):\n    assert_type(x, int)\nelse:\n    assert_type(x, Union[int, str])\n[file a.py.2]\nfrom lib import guard\nfrom typing import Union\nfrom typing_extensions import assert_type\nx: Union[int, str]\nif guard(x):\n    assert_type(x, int)\nelse:\n    assert_type(x, str)\n[file lib.py]\nfrom typing_extensions import TypeGuard\ndef guard(x: object) -> TypeGuard[int]:\n    pass\n[file lib.py.2]\nfrom typing_extensions import TypeIs\ndef guard(x: object) -> TypeIs[int]:\n    pass\n[builtins fixtures/tuple.pyi]\n\n[case testStartUsingPEP604Union]\n# flags: --python-version 3.10\nimport a\n[file a.py]\nimport lib\n\n[file a.py.2]\nfrom lib import IntOrStr\nassert isinstance(1, IntOrStr)\n\n[file lib.py]\nfrom typing_extensions import TypeAlias\n\nIntOrStr: TypeAlias = int | str\nassert isinstance(1, IntOrStr)\n[builtins fixtures/type.pyi]\n\n[case testPropertySetterTypeIncremental]\nimport b\n[file a.py]\nclass A:\n    @property\n    def f(self) -> int:\n        return 1\n    @f.setter\n    def f(self, x: str) -> None:\n        pass\n[file b.py]\nfrom a import A\n[file b.py.2]\nfrom a import A\na = A()\na.f = ''  # OK\nreveal_type(a.f)\na.f = 1\nreveal_type(a.f)\n[builtins fixtures/property.pyi]\n[out]\n[out2]\ntmp/b.py:4: note: Revealed type is \"builtins.int\"\ntmp/b.py:5: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\ntmp/b.py:6: note: Revealed type is \"builtins.int\"\n\n[case testSerializeDeferredGenericNamedTuple]\nimport pkg\n[file pkg/__init__.py]\nfrom .lib import NT\n[file pkg/lib.py]\nfrom typing import Generic, NamedTuple, TypeVar\nfrom pkg import does_not_exist  # type: ignore\nfrom pkg.missing import also_missing  # type: ignore\n\nT = TypeVar(\"T\", bound=does_not_exist)\nclass NT(NamedTuple, Generic[T]):\n    values: also_missing[T]\n[file pkg/__init__.py.2]\n# touch\nfrom .lib import NT\n[builtins fixtures/tuple.pyi]\n[out]\n[out2]\n\n[case testNewRedefineAffectsCache]\n# flags: --local-partial-types --allow-redefinition-new\n# flags2: --local-partial-types\n# flags3: --local-partial-types --allow-redefinition-new\nx = 0\nif int():\n    x = \"\"\n[out]\n[out2]\nmain:6: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testUntypedCallsExcludeAffectsCache]\n# flags: --disallow-untyped-calls --untyped-calls-exclude=mod.Super\n# flags2: --disallow-untyped-calls --untyped-calls-exclude=mod\n# flags3: --disallow-untyped-calls --untyped-calls-exclude=mod.Super\nimport mod\n[file mod.py]\nclass Super:\n    def draw(self):\n        ...\nclass Class(Super):\n    ...\nClass().draw()\n[out]\ntmp/mod.py:6: error: Call to untyped function \"draw\" in typed context\n[out2]\n[out3]\ntmp/mod.py:6: error: Call to untyped function \"draw\" in typed context\n\n[case testMethodMakeBoundIncremental]\nfrom a import A\na = A()\na.f()\n[file a.py]\nclass B:\n    def f(self, s: A) -> int: ...\n\ndef f(s: A) -> int: ...\n\nclass A:\n    f = f\n[file a.py.2]\nclass B:\n    def f(self, s: A) -> int: ...\n\ndef f(s: A) -> int: ...\n\nclass A:\n    f = B().f\n[out]\n[out2]\nmain:3: error: Too few arguments\n\n[case testUnreachableAfterToplevelAssertImportThirdParty]\n# flags: --platform unknown\nimport sys\nassert sys.platform == 'linux'\nimport does_not_exist\n[builtins fixtures/ops.pyi]\n[out]\n[out2]\n\n[case testIncrementalNoCrashOnParamSpecPrefixUpdateMethod]\nimport impl\n[file impl.py]\nfrom typing_extensions import ParamSpec\nfrom lib import Sub\n\nP = ParamSpec(\"P\")\nclass Impl(Sub[P]):\n    def test(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        self.meth(1, *args, **kwargs)\n\n[file impl.py.2]\nfrom typing_extensions import ParamSpec\nfrom lib import Sub\n\nP = ParamSpec(\"P\")\nclass Impl(Sub[P]):\n    def test(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        self.meth(\"no\", *args, **kwargs)\n\n[file lib.py]\nfrom typing import Generic\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\nclass Base(Generic[P]):\n    def meth(self, *args: P.args, **kwargs: P.kwargs) -> None: ...\nclass Sub(Base[Concatenate[int, P]]): ...\n[builtins fixtures/paramspec.pyi]\n[out]\n[out2]\ntmp/impl.py:7: error: Argument 1 to \"meth\" of \"Base\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalNoCrashOnParamSpecPrefixUpdateMethodAlias]\nimport impl\n[file impl.py]\nfrom typing_extensions import ParamSpec\nfrom lib import Sub\n\nP = ParamSpec(\"P\")\nclass Impl(Sub[P]):\n    def test(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        self.alias(1, *args, **kwargs)\n\n[file impl.py.2]\nfrom typing_extensions import ParamSpec\nfrom lib import Sub\n\nP = ParamSpec(\"P\")\nclass Impl(Sub[P]):\n    def test(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        self.alias(\"no\", *args, **kwargs)\n\n[file lib.py]\nfrom typing import Generic\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\nclass Base(Generic[P]):\n    def meth(self, *args: P.args, **kwargs: P.kwargs) -> None: ...\n    alias = meth\nclass Sub(Base[Concatenate[int, P]]): ...\n[builtins fixtures/paramspec.pyi]\n[out]\n[out2]\ntmp/impl.py:7: error: Argument 1 has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalDifferentSourcesFreshnessCorrect]\n# cmd: mypy -m foo bar\n# cmd2: mypy -m foo\n# cmd3: mypy -m foo bar\n[file foo.py]\nfoo = 5\n[file foo.py.2]\nfoo = \"foo\"\n[file bar.py]\nfrom foo import foo\nbar: int = foo\n[out]\n[out2]\n[out3]\ntmp/bar.py:2: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testIncrementalBlockingErrorRepeatAndUndo_no_native_parse]\nimport m\n[file m.py]\nimport f\nreveal_type(f.x)\n[file m.py.3]\nimport f\nreveal_type(f.x)\n# touch\n[file f.py]\nx = 1\n[file f.py.2]\nno way\n[file f.py.4]\nx = 1\n[out]\ntmp/m.py:2: note: Revealed type is \"builtins.int\"\n[out2]\ntmp/f.py:1: error: Invalid syntax\n[out3]\ntmp/f.py:1: error: Invalid syntax\n[out4]\ntmp/m.py:2: note: Revealed type is \"builtins.int\"\n\n[case testIncrementalSameErrorOrder]\nimport m\n[file m.py]\nimport n\ndef accept_int(x: int) -> None: pass\naccept_int(n.foo)\n[file n.py]\nimport other\nfoo = \"hello\"\nreveal_type(foo)\n[file other.py]\n[file other.py.2]\n# touch\n[rechecked other]\n[stale]\n[out]\ntmp/n.py:3: note: Revealed type is \"builtins.str\"\ntmp/m.py:3: error: Argument 1 to \"accept_int\" has incompatible type \"str\"; expected \"int\"\n[out2]\ntmp/n.py:3: note: Revealed type is \"builtins.str\"\ntmp/m.py:3: error: Argument 1 to \"accept_int\" has incompatible type \"str\"; expected \"int\"\n\n[case testIncrementalNoIndirectDepFromLocal]\nimport foo\nimport bar\n\n[file foo.py]\n# Having a local named 'bar' shouldn't generate a dependency on module 'bar'\ndef f(bar: int) -> int:\n    return bar\n\n[file bar.py]\nimport foo\nx = 1\n\n[file bar.py.2]\nimport foo\nx = 2\n\n[out]\n[rechecked bar]\n[stale]\n\n\n[case testIncrementalTypedDictGetMethodTotalFalse]\nimport impl\n[file lib.py]\nfrom typing import TypedDict\nclass Unrelated: pass\nD = TypedDict('D', {'x': int, 'y': str}, total=False)\n[file impl.py]\npass\n[file impl.py.2]\nfrom typing import Literal\nfrom lib import D, Unrelated\nd: D\nu: Unrelated\nx: Literal['x']\ny: Literal['y']\nz: Literal['z']\nx_or_y: Literal['x', 'y']\nx_or_z: Literal['x', 'z']\nx_or_y_or_z: Literal['x', 'y', 'z']\n\n# test with literal expression\nreveal_type(d.get('x'))\nreveal_type(d.get('y'))\nreveal_type(d.get('z'))\nreveal_type(d.get('x', u))\nreveal_type(d.get('x', 1))\nreveal_type(d.get('y', None))\n\n# test with literal type / union of literal types with implicit default\nreveal_type(d.get(x))\nreveal_type(d.get(y))\nreveal_type(d.get(z))\nreveal_type(d.get(x_or_y))\nreveal_type(d.get(x_or_z))\nreveal_type(d.get(x_or_y_or_z))\n\n# test with literal type / union of literal types with explicit default\nreveal_type(d.get(x, u))\nreveal_type(d.get(y, u))\nreveal_type(d.get(z, u))\nreveal_type(d.get(x_or_y, u))\nreveal_type(d.get(x_or_z, u))\nreveal_type(d.get(x_or_y_or_z, u))\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n[out2]\ntmp/impl.py:13: note: Revealed type is \"builtins.int | None\"\ntmp/impl.py:14: note: Revealed type is \"builtins.str | None\"\ntmp/impl.py:15: note: Revealed type is \"builtins.object\"\ntmp/impl.py:16: note: Revealed type is \"builtins.int | lib.Unrelated\"\ntmp/impl.py:17: note: Revealed type is \"builtins.int\"\ntmp/impl.py:18: note: Revealed type is \"builtins.str | None\"\ntmp/impl.py:21: note: Revealed type is \"builtins.int | None\"\ntmp/impl.py:22: note: Revealed type is \"builtins.str | None\"\ntmp/impl.py:23: note: Revealed type is \"builtins.object\"\ntmp/impl.py:24: note: Revealed type is \"builtins.int | builtins.str | None\"\ntmp/impl.py:25: note: Revealed type is \"builtins.object\"\ntmp/impl.py:26: note: Revealed type is \"builtins.object\"\ntmp/impl.py:29: note: Revealed type is \"builtins.int | lib.Unrelated\"\ntmp/impl.py:30: note: Revealed type is \"builtins.str | lib.Unrelated\"\ntmp/impl.py:31: note: Revealed type is \"builtins.object\"\ntmp/impl.py:32: note: Revealed type is \"builtins.int | builtins.str | lib.Unrelated\"\ntmp/impl.py:33: note: Revealed type is \"builtins.object\"\ntmp/impl.py:34: note: Revealed type is \"builtins.object\"\n\n[case testIncrementalTypedDictGetMethodTotalTrue]\nimport impl\n[file lib.py]\nfrom typing import TypedDict\nclass Unrelated: pass\nD = TypedDict('D', {'x': int, 'y': str}, total=True)\n[file impl.py]\npass\n[file impl.py.2]\nfrom typing import Literal\nfrom lib import D, Unrelated\nd: D\nu: Unrelated\nx: Literal['x']\ny: Literal['y']\nz: Literal['z']\nx_or_y: Literal['x', 'y']\nx_or_z: Literal['x', 'z']\nx_or_y_or_z: Literal['x', 'y', 'z']\n\n# test with literal expression\nreveal_type(d.get('x'))\nreveal_type(d.get('y'))\nreveal_type(d.get('z'))\nreveal_type(d.get('x', u))\nreveal_type(d.get('x', 1))\nreveal_type(d.get('y', None))\n\n# test with literal type / union of literal types with implicit default\nreveal_type(d.get(x))\nreveal_type(d.get(y))\nreveal_type(d.get(z))\nreveal_type(d.get(x_or_y))\nreveal_type(d.get(x_or_z))\nreveal_type(d.get(x_or_y_or_z))\n\n# test with literal type / union of literal types with explicit default\nreveal_type(d.get(x, u))\nreveal_type(d.get(y, u))\nreveal_type(d.get(z, u))\nreveal_type(d.get(x_or_y, u))\nreveal_type(d.get(x_or_z, u))\nreveal_type(d.get(x_or_y_or_z, u))\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n[out2]\ntmp/impl.py:13: note: Revealed type is \"builtins.int\"\ntmp/impl.py:14: note: Revealed type is \"builtins.str\"\ntmp/impl.py:15: note: Revealed type is \"builtins.object\"\ntmp/impl.py:16: note: Revealed type is \"builtins.int\"\ntmp/impl.py:17: note: Revealed type is \"builtins.int\"\ntmp/impl.py:18: note: Revealed type is \"builtins.str\"\ntmp/impl.py:21: note: Revealed type is \"builtins.int\"\ntmp/impl.py:22: note: Revealed type is \"builtins.str\"\ntmp/impl.py:23: note: Revealed type is \"builtins.object\"\ntmp/impl.py:24: note: Revealed type is \"builtins.int | builtins.str\"\ntmp/impl.py:25: note: Revealed type is \"builtins.object\"\ntmp/impl.py:26: note: Revealed type is \"builtins.object\"\ntmp/impl.py:29: note: Revealed type is \"builtins.int\"\ntmp/impl.py:30: note: Revealed type is \"builtins.str\"\ntmp/impl.py:31: note: Revealed type is \"builtins.object\"\ntmp/impl.py:32: note: Revealed type is \"builtins.int | builtins.str\"\ntmp/impl.py:33: note: Revealed type is \"builtins.object\"\ntmp/impl.py:34: note: Revealed type is \"builtins.object\"\n\n\n[case testIncrementalTypedDictGetMethodTotalMixed]\nimport impl\n[file lib.py]\nfrom typing import TypedDict\nfrom typing_extensions import Required, NotRequired\nclass Unrelated: pass\nD = TypedDict('D', {'x': Required[int], 'y': NotRequired[str]})\n[file impl.py]\npass\n[file impl.py.2]\nfrom typing import Literal\nfrom lib import D, Unrelated\nd: D\nu: Unrelated\nx: Literal['x']\ny: Literal['y']\nz: Literal['z']\nx_or_y: Literal['x', 'y']\nx_or_z: Literal['x', 'z']\nx_or_y_or_z: Literal['x', 'y', 'z']\n\n# test with literal expression\nreveal_type(d.get('x'))\nreveal_type(d.get('y'))\nreveal_type(d.get('z'))\nreveal_type(d.get('x', u))\nreveal_type(d.get('x', 1))\nreveal_type(d.get('y', None))\n\n# test with literal type / union of literal types with implicit default\nreveal_type(d.get(x))\nreveal_type(d.get(y))\nreveal_type(d.get(z))\nreveal_type(d.get(x_or_y))\nreveal_type(d.get(x_or_z))\nreveal_type(d.get(x_or_y_or_z))\n\n# test with literal type / union of literal types with explicit default\nreveal_type(d.get(x, u))\nreveal_type(d.get(y, u))\nreveal_type(d.get(z, u))\nreveal_type(d.get(x_or_y, u))\nreveal_type(d.get(x_or_z, u))\nreveal_type(d.get(x_or_y_or_z, u))\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n[out2]\ntmp/impl.py:13: note: Revealed type is \"builtins.int\"\ntmp/impl.py:14: note: Revealed type is \"builtins.str | None\"\ntmp/impl.py:15: note: Revealed type is \"builtins.object\"\ntmp/impl.py:16: note: Revealed type is \"builtins.int\"\ntmp/impl.py:17: note: Revealed type is \"builtins.int\"\ntmp/impl.py:18: note: Revealed type is \"builtins.str | None\"\ntmp/impl.py:21: note: Revealed type is \"builtins.int\"\ntmp/impl.py:22: note: Revealed type is \"builtins.str | None\"\ntmp/impl.py:23: note: Revealed type is \"builtins.object\"\ntmp/impl.py:24: note: Revealed type is \"builtins.int | builtins.str | None\"\ntmp/impl.py:25: note: Revealed type is \"builtins.object\"\ntmp/impl.py:26: note: Revealed type is \"builtins.object\"\ntmp/impl.py:29: note: Revealed type is \"builtins.int\"\ntmp/impl.py:30: note: Revealed type is \"builtins.str | lib.Unrelated\"\ntmp/impl.py:31: note: Revealed type is \"builtins.object\"\ntmp/impl.py:32: note: Revealed type is \"builtins.int | builtins.str | lib.Unrelated\"\ntmp/impl.py:33: note: Revealed type is \"builtins.object\"\ntmp/impl.py:34: note: Revealed type is \"builtins.object\"\n\n[case testIncrementalAccessSubmoduleWithoutExplicitImport]\nimport b\nimport a\n\n[file a.py]\nimport pkg\n\npkg.submod.foo()\n\n[file a.py.2]\nimport pkg\n\npkg.submod.foo()\nx = 1\n\n[file b.py]\nimport c\n\n[file c.py]\nfrom pkg import submod\n\n[file pkg/__init__.pyi]\n[file pkg/submod.pyi]\ndef foo() -> None: pass\n[out]\ntmp/a.py:3: error: \"object\" has no attribute \"submod\"\n[out2]\ntmp/a.py:3: error: \"object\" has no attribute \"submod\"\n\n[case testIncrementalAccessSubmoduleWithoutExplicitImportNested]\nimport a\n\n[file a.py]\nimport pandas\npandas.core.dtypes\n\n[file a.py.2]\nimport pandas\npandas.core.dtypes\n# touch\n\n[file pandas/__init__.py]\nimport pandas.core.api\n\n[file pandas/core/__init__.py]\n[file pandas/core/api.py]\nimport pandas.core.dtypes.dtypes\n\n[file pandas/core/dtypes/__init__.py]\n[file pandas/core/dtypes/dtypes.py]\nX = 0\n[out]\n[out2]\n\n[case testIncrementalAccessSubmoduleWithoutExplicitImportNestedFrom]\nimport a\n\n[file a.py]\nimport pandas\n\n# Although this actually works at runtime, we do not support this, since\n# this would cause major slowdown for a rare edge case. This test verifies\n# that we fail consistently on cold and warm runs.\npandas.core.dtypes\n\n[file a.py.2]\nimport pandas\npandas.core.dtypes\n\n[file pandas/__init__.py]\nimport pandas.core.api\n\n[file pandas/core/__init__.py]\n[file pandas/core/api.py]\nfrom pandas.core.dtypes.dtypes import X\n\n[file pandas/core/dtypes/__init__.py]\n[file pandas/core/dtypes/dtypes.py]\nX = 0\n[out]\ntmp/a.py:6: error: \"object\" has no attribute \"dtypes\"\n[out2]\ntmp/a.py:2: error: \"object\" has no attribute \"dtypes\"\n\n[case testStarImportCycleRedefinition]\nimport m\n\n[file m.py]\nimport a\n\n[file m.py.2]\nimport a\nreveal_type(a.C)\n\n[file a/__init__.py]\nfrom a.b import *\nfrom a.c import *\nx = 1\n\n[file a/b.py]\nfrom other import C\nfrom a.c import y\nclass C: ...  # type: ignore\n\n[file a/c.py]\nfrom other import C\nfrom a import x\ny = 1\n\n[file other.py]\nclass C: ...\n[out2]\ntmp/m.py:2: note: Revealed type is \"def () -> other.C\"\n\n[case testOutputFormatterIncremental]\n# flags2: --output json\ndef wrong() -> int:\n    if wrong():\n        return 0\n[out]\nmain:2: error: Missing return statement\n[out2]\n{\"file\": \"main\", \"line\": 2, \"column\": 0, \"end_line\": 4, \"end_column\": 16, \"message\": \"Missing return statement\", \"hint\": null, \"code\": \"return\", \"severity\": \"error\"}\n\n[case testReExportAllInStubIncremental]\nfrom m1 import C\nfrom m1 import D\nC()\nC(1)\n[file m1.pyi]\nfrom m2 import *\n[file m2.pyi]\nfrom m3 import *\nfrom m3 import __all__ as __all__\nclass D: pass\n[file m2.pyi.2]\nfrom m3 import *\nfrom m3 import __all__ as __all__\nclass D:\n    x = 1\n[file m3.pyi]\nfrom m4 import C as C\n__all__ = ['C']\n[file m4.pyi]\nclass C: pass\n[builtins fixtures/list.pyi]\n[out]\nmain:2: error: Module \"m1\" has no attribute \"D\"\nmain:4: error: Too many arguments for \"C\"\n[out2]\nmain:2: error: Module \"m1\" has no attribute \"D\"\nmain:4: error: Too many arguments for \"C\"\n\n[case testCyclicUndefinedImportWithStarIncremental]\nimport m\n[file m.py]\nimport a\n[file m.py.2]\nimport a\nreveal_type(a.no_such_export)\n[file a.py]\nfrom b import no_such_export\n[file b.py]\nfrom a import *\n[out]\ntmp/b.py:1: error: Cannot resolve name \"no_such_export\" (possible cyclic definition)\n[out2]\ntmp/b.py:1: error: Cannot resolve name \"no_such_export\" (possible cyclic definition)\ntmp/m.py:2: note: Revealed type is \"Any\"\n\n[case testCachedUnexpectedKeywordArgument]\nimport m\n[file m.py]\nimport a\n[file a.py]\nimport b\nb.lol(uhhhh=12) # tweak\n[file a.py.2]\nimport b\nb.lol(uhhhh=12)\n[file b.py]\ndef lol() -> None: pass\n[file b.py.3]\n# space\ndef lol() -> None: pass\n[file m.py.4]\nimport a  # touch\n[out]\ntmp/a.py:2: error: Unexpected keyword argument \"uhhhh\" for \"lol\"\ntmp/a.py:2: note: \"lol\" defined in \"b\"\n[out2]\ntmp/a.py:2: error: Unexpected keyword argument \"uhhhh\" for \"lol\"\ntmp/a.py:2: note: \"lol\" defined in \"b\"\n[out3]\ntmp/a.py:2: error: Unexpected keyword argument \"uhhhh\" for \"lol\"\ntmp/a.py:2: note: \"lol\" defined in \"b\"\n[out4]\ntmp/a.py:2: error: Unexpected keyword argument \"uhhhh\" for \"lol\"\ntmp/a.py:2: note: \"lol\" defined in \"b\"\n\n[case testMissingImportUnIgnoredInConfig]\n# flags: --config-file tmp/mypy.ini\nfrom foo import bar\n[file mypy.ini]\n\\[mypy]\n\\[mypy-foo]\nignore_missing_imports = True\n[file mypy.ini.2]\n\\[mypy]\n\\[mypy-foo]\nignore_missing_imports = False\n[out]\n[out2]\nmain:2: error: Cannot find implementation or library stub for module named \"foo\"\nmain:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testMissingImportUnIgnoredInConfig2]\n# flags: --config-file tmp/mypy.ini\nfrom foo import bar\n[file mypy.ini]\n\\[mypy]\n\\[mypy-foo]\nignore_missing_imports = False\n[file mypy.ini.2]\n\\[mypy]\n\\[mypy-foo]\nignore_missing_imports = True\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"foo\"\nmain:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n[out2]\n\n[case testMissingImportUnIgnoredInConfig3]\n# flags: --config-file tmp/mypy.ini\nfrom foo import bar\n[file foo.py]\nbar = 1\n[file mypy.ini]\n\\[mypy]\n\\[mypy-foo]\nfollow_imports = skip\n[file mypy.ini.2]\n\\[mypy]\n\\[mypy-foo]\nfollow_imports = error\n[out]\n[out2]\nmain:2: error: Import of \"foo\" ignored\nmain:2: note: (Using --follow-imports=error, module not passed on command line)\n\n[case testMissingImportUnIgnoredInConfig4]\n# flags: --config-file tmp/mypy.ini\nfrom foo import bar\n[file foo.py]\nbar = 1\n[file mypy.ini]\n\\[mypy]\n\\[mypy-foo]\nfollow_imports = error\n[file mypy.ini.2]\n\\[mypy]\n\\[mypy-foo]\nfollow_imports = skip\n[out]\nmain:2: error: Import of \"foo\" ignored\nmain:2: note: (Using --follow-imports=error, module not passed on command line)\n[out2]\n\n[case testMissingImportUnIgnoredInConfig5]\n# flags: --config-file tmp/mypy.ini --warn-unused-ignores\nfrom foo import bar  # type: ignore[import-not-found]\n[file mypy.ini]\n\\[mypy]\n\\[mypy-foo]\nignore_missing_imports = True\n[file mypy.ini.2]\n\\[mypy]\n\\[mypy-foo]\nignore_missing_imports = False\n[out]\nmain:2: error: Unused \"type: ignore\" comment\n[out2]\n\n[case testMissingImportUnIgnoredInConfig6]\n# flags: --config-file tmp/mypy.ini  --warn-unused-ignores\nfrom foo import bar  # type: ignore[import-not-found]\n[file mypy.ini]\n\\[mypy]\n\\[mypy-foo]\nignore_missing_imports = False\n[file mypy.ini.2]\n\\[mypy]\n\\[mypy-foo]\nignore_missing_imports = True\n[out]\n[out2]\nmain:2: error: Unused \"type: ignore\" comment\n\n[case testIndirectDependencyReorderModulesNoCrash]\nimport a\n[file a.py]\nimport b\n[file a.py.2]\nimport pkg.mod\nimport b\n[file b.py]\nimport foo\nimport pkg\nx: pkg.mod.C\n[file pkg/__init__.py]\n[file pkg/mod.py]\nimport c\nclass C: ...\n# The chain of trivial stale modules is to force late load of pkg.mod,\n# otherwise the test can pass accidentally.\n[file c.py]\nimport d\n[file c.py.2]\nimport d  # touch\n[file d.py]\nimport e\n[file d.py.2]\nimport e  # touch\n[file e.py]\n[file foo.py]\nimport bar\n[file bar.py]\nimport pkg.mod\n[file bar.py.2]\n[out]\n[out2]\ntmp/b.py:3: error: Name \"pkg.mod.C\" is not defined\n\n[case testIndirectDependencyReorderModulesNoCrash2]\nimport m\n[file m.py]\nimport a\n[file m.py.2]\nimport a\nimport d\n[file a.py]\nimport b\nx: b.c.d.C\n[file b.py]\nimport c\n[file c.py]\nimport d\n[file c.py.2]\n[file d.py]\nimport n1\nclass C: ...\n# The chain of trivial stale modules is to force late load of d,\n# otherwise the test can pass accidentally.\n[file n1.py]\nimport n2\n[file n1.py.2]\nimport n2  # touch\n[file n2.py]\nimport n3\n[file n2.py.2]\nimport n3  # touch\n[file n3.py]\n[out]\n[out2]\ntmp/a.py:2: error: Name \"b.c.d.C\" is not defined\n\n[case testDeletedModuleFromImport]\n# flags: --ignore-missing-imports\nfrom a import b\n[file a/__init__.py]\n[file a/b.py]\n[delete a/b.py.2]\n[out]\n[out2]\nmain:2: error: Module \"a\" has no attribute \"b\"\n\n[case testDeletedModuleFromImport2]\n# flags: --ignore-missing-imports\nimport a\nimport a.b\nfrom a import b  # no error here\n[file a/__init__.py]\n[file a/b.py]\n[delete a/b.py.2]\n[out]\n[out2]\n\n[case testDeletedModuleFromImport3]\n# flags: --warn-unused-ignores\nfrom a import b  # type: ignore[attr-defined]\n[file a/__init__.py]\n[file a/b.py]\n[delete a/b.py.2]\n[out]\nmain:2: error: Unused \"type: ignore\" comment\n[out2]\n\n[case testConfigWarnUnusedSectionIncremental]\n# flags: --config-file=tmp/mypy.ini\nimport m\n[file m.py]\nimport a\n[file m.py.2]\nimport a  # touch\n[file a.py]\nimport foo  # type: ignore\n[file mypy.ini]\n\\[mypy]\nwarn_unused_configs = true\n\\[mypy-bar]\n\\[mypy-foo]\n[file mypy.ini.3]\n\\[mypy]\nwarn_unused_configs = true\n\\[mypy-foo]\n[out]\ntmp/mypy.ini: note: unused section(s): [mypy-bar]\n[out2]\ntmp/mypy.ini: note: unused section(s): [mypy-bar]\n[out3]\n\n[case testConfigWarnUnusedSectionIncrementalTOML]\n# flags: --config-file tmp/pyproject.toml\nimport m\n[file m.py]\nimport a\n[file m.py.2]\nimport a  # touch\n[file a.py]\nimport foo  # type: ignore\n[file pyproject.toml]\n\\[tool.mypy]\nwarn_unused_configs = true\n\\[[tool.mypy.overrides]]\nmodule = \"bar\"\n\\[[tool.mypy.overrides]]\nmodule = \"foo\"\nwarn_unreachable = true\n[file pyproject.toml.3]\n\\[tool.mypy]\nwarn_unused_configs = true\n\\[[tool.mypy.overrides]]\nmodule = \"foo\"\n[out]\ntmp/pyproject.toml: note: unused section(s): module = ['bar']\n[out2]\ntmp/pyproject.toml: note: unused section(s): module = ['bar']\n[out3]\n\n[case testAddedMissingModuleSkip]\n# flags: --follow-imports=skip\nimport mod\n[file mod.py.2]\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"mod\"\nmain:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n[out2]\n\n[case testDeletedModuleSkip]\n# flags: --follow-imports=skip\nimport mod\n[file mod.py]\n[delete mod.py.2]\n[out]\n[out2]\nmain:2: error: Cannot find implementation or library stub for module named \"mod\"\nmain:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n"
  },
  {
    "path": "test-data/unit/check-inference-context.test",
    "content": "\n\n-- Basic test cases\n-- ----------------\n\n\n[case testBasicContextInference]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\n\ndef f() -> 'A[T]': pass\n\nclass A(Generic[T]): pass\nclass B: pass\n\nab: A[B]\nao: A[object]\nb: B\n\nif int():\n    ao = f()\nif int():\n    ab = f()\nif int():\n    b = f() # E: Incompatible types in assignment (expression has type \"A[Never]\", variable has type \"B\")\n[case testBasicContextInferenceForConstructor]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]): pass\nclass B: pass\nab: A[B]\nao: A[object]\nb: B\n\nif int():\n    ao = A()\nif int():\n    ab = A()\nif int():\n    b = A() # E: Incompatible types in assignment (expression has type \"A[Never]\", variable has type \"B\")\n[case testIncompatibleContextInference]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef f(a: T) -> 'A[T]':\n    pass\n\nclass A(Generic[T]): pass\n\nclass B: pass\nclass C: pass\nb: B\nc: C\nab: A[B]\nao: A[object]\nac: A[C]\n\nif int():\n    ac = f(b) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"C\"\nif int():\n    ab = f(c) # E: Argument 1 to \"f\" has incompatible type \"C\"; expected \"B\"\n\nif int():\n    ao = f(b)\nif int():\n    ab = f(b)\nif int():\n    ao = f(c)\nif int():\n    ac = f(c)\n\n\n-- Local variables\n-- ---------------\n\n\n[case testInferGenericLocalVariableTypeWithEmptyContext]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef g() -> None:\n    ao: A[object]\n    ab: A[B]\n    o: object\n    b: B\n\n    x = f(o)\n    if int():\n        ab = x # E: Incompatible types in assignment (expression has type \"A[object]\", variable has type \"A[B]\")\n        ao = x\n    y = f(b)\n    if int():\n        ao = y # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\n        ab = y\n\ndef f(a: T) -> 'A[T]': pass\n\nclass A(Generic[T]): pass\nclass B: pass\n[out]\n\n[case testInferLocalVariableTypeWithUnderspecifiedGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef g() -> None:\n    x = f() # E: Need type annotation for \"x\"\n\ndef f() -> 'A[T]': pass\nclass A(Generic[T]): pass\n[out]\n\n[case testInferMultipleLocalVariableTypesWithTupleRvalue]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef g() -> None:\n    ao: A[object]\n    ab: A[B]\n    b: B\n    x, y = f(b), f(b)\n    if int():\n        ao = x # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\n        ao = y # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\n        ab = x\n        ab = y\n\ndef f(a: T) -> 'A[T]': pass\nclass A(Generic[T]): pass\nclass B: pass\n[out]\n\n[case testInferMultipleLocalVariableTypesWithArrayRvalueAndNesting]\nfrom typing import TypeVar, List, Generic\nT = TypeVar('T')\ndef h() -> None:\n    ao: A[object]\n    ab: A[B]\n    b: B\n    x, y = g(f(b))\n    if int():\n        ao = x # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\n        ao = y # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\n        ab = x\n        ab = y\n\ndef f(a: T) -> 'A[T]': pass\ndef g(a: T) -> List[T]: pass\n\nclass A(Generic[T]): pass\nclass B: pass\n[builtins fixtures/for.pyi]\n[out]\n\n\n-- Return types with multiple tvar instances\n-- -----------------------------------------\n\n\n[case testInferenceWithTypeVariableTwiceInReturnType]\nfrom typing import TypeVar, Tuple, Generic\nT = TypeVar('T')\n\ndef f(a: T) -> 'Tuple[A[T], A[T]]': pass\n\nclass A(Generic[T]): pass\nclass B: pass\n\nb: B\no: object\nab: A[B]\nao: A[object]\n\nif int():\n    ab, ao = f(b) # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\nif int():\n    ao, ab = f(b) # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\n\nif int():\n    ao, ao = f(b)\nif int():\n    ab, ab = f(b)\nif int():\n    ao, ao = f(o)\n[builtins fixtures/tuple.pyi]\n\n[case testInferenceWithTypeVariableTwiceInReturnTypeAndMultipleVariables]\nfrom typing import TypeVar, Tuple, Generic\nS = TypeVar('S')\nT = TypeVar('T')\n\ndef f(a: S, b: T) -> 'Tuple[A[S], A[T], A[T]]': pass\ndef g(a: S, b: T) -> 'Tuple[A[S], A[S], A[T]]': pass\ndef h(a: S, b: T) -> 'Tuple[A[S], A[S], A[T], A[T]]': pass\n\nclass A(Generic[T]): pass\nclass B: pass\n\nb: B\no: object\nab: A[B]\nao: A[object]\n\nif int():\n    ao, ao, ab = f(b, b)     # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\nif int():\n    ao, ab, ao = g(b, b)     # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\nif int():\n    ao, ab, ab, ab = h(b, b) # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\nif int():\n    ab, ab, ao, ab = h(b, b) # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[object]\")\n\nif int():\n    ao, ab, ab = f(b, b)\nif int():\n    ab, ab, ao = g(b, b)\nif int():\n    ab, ab, ab, ab = h(b, b)\n[builtins fixtures/tuple.pyi]\n\n\n-- Multiple tvar instances in arguments\n-- ------------------------------------\n\n\n[case testMultipleTvatInstancesInArgs]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\n\ndef f(a: T, b: T) -> 'A[T]': pass\n\nclass A(Generic[T]): pass\nclass B: pass\nclass C(B): pass\n\nac: A[C]\nab: A[B]\nao: A[object]\nb: B\nc: C\no: object\n\nif int():\n    ab = f(b, o) # E: Argument 2 to \"f\" has incompatible type \"object\"; expected \"B\"\nif int():\n    ab = f(o, b) # E: Argument 1 to \"f\" has incompatible type \"object\"; expected \"B\"\nif int():\n    ac = f(b, c) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"C\"\nif int():\n    ac = f(c, b) # E: Argument 2 to \"f\" has incompatible type \"B\"; expected \"C\"\n\nif int():\n    ao = f(b, c)\nif int():\n    ao = f(c, b)\nif int():\n    ab = f(c, b)\n\n\n-- Nested generic function calls\n-- -----------------------------\n\n\n[case testNestedGenericFunctionCall1]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\n\ndef f(a: T) -> 'A[T]': pass\n\nclass A(Generic[T]): pass\nclass B: pass\n\naab: A[A[B]]\naao: A[A[object]]\nao: A[object]\nb: B\no: object\n\nif int():\n    aab = f(f(o)) # E: Argument 1 to \"f\" has incompatible type \"object\"; expected \"B\"\n\nif int():\n    aab = f(f(b))\n    aao = f(f(b))\n    ao = f(f(b))\n\n[case testNestedGenericFunctionCall2]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\n\ndef f(a: T) -> T: pass\ndef g(a: T) -> 'A[T]': pass\n\nclass A(Generic[T]): pass\nclass B: pass\n\nab: A[B]\nao: A[object]\nb: B\no: object\n\nif int():\n    ab = f(g(o)) # E: Argument 1 to \"g\" has incompatible type \"object\"; expected \"B\"\n\nif int():\n    ab = f(g(b))\n    ao = f(g(b))\n\n[case testNestedGenericFunctionCall3]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef f(a: T, b: T) -> T:\n    pass\n\ndef g(a: T) -> 'A[T]': pass\n\nclass A(Generic[T]): pass\nclass B: pass\nab: A[B]\nao: A[object]\nb: B\no: object\n\nif int():\n    ab = f(g(o), g(b)) # E: Argument 1 to \"g\" has incompatible type \"object\"; expected \"B\"\nif int():\n    ab = f(g(b), g(o)) # E: Argument 1 to \"g\" has incompatible type \"object\"; expected \"B\"\n\nif int():\n    ab = f(g(b), g(b))\n    ao = f(g(b), g(o))\nif int():\n    ao = f(g(o), g(b))\n\n\n-- Method calls\n-- ------------\n\n\n[case testMethodCallWithContextInference]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\no: object\nb: B\nc: C\ndef f(a: T) -> 'A[T]': pass\n\nclass A(Generic[T]):\n    def g(self, a: 'A[T]') -> 'A[T]': pass\n\nclass B: pass\nclass C(B): pass\nao: A[object]\nab: A[B]\nac: A[C]\n\nab.g(f(o))        # E: Argument 1 to \"f\" has incompatible type \"object\"; expected \"B\"\nif int():\n    ac = f(b).g(f(c)) # E: Incompatible types in assignment (expression has type \"A[B]\", variable has type \"A[C]\")\nif int():\n    ac = f(c).g(f(b)) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"C\"\n\nif int():\n    ab = f(b).g(f(c))\nab.g(f(c))\n\n\n-- List expressions\n-- ----------------\n\n\n[case testEmptyListExpression]\nfrom typing import List\naa: List[A]\nao: List[object]\na: A\ndef f(): a, aa, ao # Prevent redefinition\n\na = [] # E: Incompatible types in assignment (expression has type \"list[Never]\", variable has type \"A\")\n\naa = []\nao = []\n\nclass A: pass\n[builtins fixtures/list.pyi]\n\n[case testSingleItemListExpressions]\nfrom typing import List, Optional\naa: List[Optional[A]]\nab: List[B]\nao: List[object]\na: A\nb: B\ndef f(): aa, ab, ao # Prevent redefinition\n\naa = [b] # E: List item 0 has incompatible type \"B\"; expected \"A | None\"\nab = [a] # E: List item 0 has incompatible type \"A\"; expected \"B\"\n\naa = [a]\nab = [b]\nao = [a]\naa = [None]\nao = [None]\n\nclass A: pass\nclass B: pass\n[builtins fixtures/list.pyi]\n\n[case testMultiItemListExpressions]\nfrom typing import List\naa: List[A]\nab: List[B]\nao: List[object]\na: A\nb: B\ndef f(): ab, aa, ao # Prevent redefinition\n\nab = [b, a] # E: List item 1 has incompatible type \"A\"; expected \"B\"\nab = [a, b] # E: List item 0 has incompatible type \"A\"; expected \"B\"\n\naa = [a, b, a]\nao = [a, b]\n\nclass A: pass\nclass B(A): pass\n[builtins fixtures/list.pyi]\n\n[case testLocalVariableInferenceFromEmptyList]\nimport typing\ndef f() -> None:\n    a = []     # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n    b = [None]\n    c = [B()]\n    if int():\n        c = [object()] # E: List item 0 has incompatible type \"object\"; expected \"B\"\n        c = [B()]\nclass B: pass\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNestedListExpressions]\n# flags: --no-strict-optional\nfrom typing import List\naao = None # type: list[list[object]]\naab = None # type: list[list[B]]\nab = None # type: list[B]\nb = None # type: B\no = None # type: object\ndef f(): aao, aab # Prevent redefinition\n\naao = [[o], ab] # E: List item 1 has incompatible type \"list[B]\"; expected \"list[object]\"\naab = [[], [o]] # E: List item 0 has incompatible type \"object\"; expected \"B\"\n\naao = [[None], [b], [], [o]]\naab = [[None], [b], []]\naab = [ab, []]\n\nclass B: pass\n[builtins fixtures/list.pyi]\n\n\n-- Complex context\n-- ---------------\n\n\n[case testParenthesesAndContext]\nfrom typing import List\nclass A: pass\nl = ([A()]) # type: List[object]\n[builtins fixtures/list.pyi]\n\n[case testComplexTypeInferenceWithTuple]\nfrom typing import TypeVar, Tuple, Generic\nk = TypeVar('k')\nt = TypeVar('t')\nv = TypeVar('v')\n\nclass A(Generic[t]): pass\nclass B: pass\nclass C: pass\nclass D(Generic[k, v]): pass\n\ndef f(x: Tuple[k]) -> 'A[k]': pass\n\nd = f((A(),)) # type: A[A[B]]\n[builtins fixtures/list.pyi]\n\n\n-- Dictionary literals\n-- -------------------\n\n\n[case testDictionaryLiteralInContext]\nfrom typing import Dict, TypeVar, Generic\nt = TypeVar('t')\nclass A(Generic[t]): pass\nclass B: pass\nclass C: pass\na_b = A() # type: A[B]\na_c = A() # type: A[C]\nd = {A() : a_c,\n     a_b : A()} # type: Dict[A[B], A[C]]\n[builtins fixtures/dict.pyi]\n\n\n-- Special cases (regression tests etc.)\n-- -------------------------------------\n\n\n[case testInitializationWithInferredGenericType]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\n\ndef f(x: T) -> T: pass\nclass C(Generic[T]): pass\nclass A: pass\n\nc = f(A()) # type: C[A] # E: Argument 1 to \"f\" has incompatible type \"A\"; expected \"C[A]\"\n[case testInferredGenericTypeAsReturnValue]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\ndef t() -> 'A[B]':\n    return f(D()) # E: Argument 1 to \"f\" has incompatible type \"D\"; expected \"B\"\n    return A()\n    return f(C())\n\ndef f(a: T) -> 'A[T]': pass\nclass A(Generic[T]): pass\nclass B: pass\nclass C(B): pass\nclass D: pass\n[out]\n\n[case testIntersectionWithInferredGenericArgument]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload, TypeVar, Generic\nT = TypeVar('T')\nf(A())\n\n@overload\ndef f(x: 'A[B]') -> None: pass\n@overload\ndef f(x: 'B') -> None: pass\nclass A(Generic[T]): pass\nclass B: pass\n\n[case testInferenceWithAbstractClassContext]\nfrom typing import TypeVar, Generic\nfrom abc import abstractmethod, ABCMeta\nt = TypeVar('t')\n\nclass I(Generic[t]):\n    @abstractmethod\n    def f(self): pass\nclass A(I[t], Generic[t]):\n    def f(self): pass\n\nx = A() # type: I[int]\na_object = A() # type: A[object]\ny = a_object # type: I[int] # E: Incompatible types in assignment (expression has type \"A[object]\", variable has type \"I[int]\")\n\n[case testInferenceWithAbstractClassContext2]\nfrom typing import TypeVar, Generic\nfrom abc import abstractmethod, ABCMeta\nt = TypeVar('t')\nclass I(Generic[t]): pass\nclass A(I[t], Generic[t]): pass\ndef f(i: I[t]) -> A[t]: pass\na = f(A()) # type: A[int]\na_int = A() # type: A[int]\naa = f(a_int)\n\n[case testInferenceWithAbstractClassContext3]\nfrom typing import TypeVar, Generic, Iterable\nt = TypeVar('t')\nclass set(Generic[t]):\n    def __init__(self, iterable: Iterable[t]) -> None: pass\nb = bool()\nl = set([b])\nif int():\n    l = set([object()]) # E: List item 0 has incompatible type \"object\"; expected \"bool\"\n[builtins fixtures/for.pyi]\n\n\n-- Infer generic type in 'Any' context\n-- -----------------------------------\n\n\n[case testInferGenericTypeInAnyContext]\nfrom typing import Any, TypeVar, Generic\ns = TypeVar('s')\nt = TypeVar('t')\nclass C(Generic[s, t]): pass\nx = [] # type: Any\ny = C() # type: Any\n[builtins fixtures/list.pyi]\n\n\n-- Lambdas\n-- -------\n\n\n[case testInferLambdaArgumentTypeUsingContext]\nfrom typing import Callable\nf: Callable[[B], A]\nif int():\n    f = lambda x: x.o\n    f = lambda x: x.x # E: \"B\" has no attribute \"x\"\nclass A: pass\nclass B:\n  o: A\n\n[case testInferLambdaReturnTypeUsingContext]\nfrom typing import List, Callable\nf: Callable[[], List[A]]\nif int():\n    f = lambda: []\n    f = lambda: [B()]  # E: List item 0 has incompatible type \"B\"; expected \"A\"\nclass A: pass\nclass B: pass\n[builtins fixtures/list.pyi]\n\n[case testInferLambdaTypeUsingContext]\nx : str = (lambda x: x + 1)(1)  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nreveal_type((lambda x, y: x + y)(1, 2))  # N: Revealed type is \"builtins.int\"\n(lambda x, y: x + y)(1, \"\")  # E: Unsupported operand types for + (\"int\" and \"str\")\n(lambda *, x, y: x + y)(x=1, y=\"\")  # E: Unsupported operand types for + (\"int\" and \"str\")\nreveal_type((lambda s, i: s)(i=0, s='x')) # N: Revealed type is \"Literal['x']?\"\nreveal_type((lambda s, i: i)(i=0, s='x')) # N: Revealed type is \"Literal[0]?\"\nreveal_type((lambda x, s, i: x)(1.0, i=0, s='x')) # N: Revealed type is \"builtins.float\"\nif object():\n    (lambda x, s, i: x)() # E: Too few arguments\nif object():\n    (lambda: 0)(1) # E: Too many arguments\n-- varargs are not handled, but it should not crash\nreveal_type((lambda *k, s, i: i)(type, i=0, s='x')) # N: Revealed type is \"Any\"\nreveal_type((lambda s, *k, i: i)(i=0, s='x')) # N: Revealed type is \"Any\"\nreveal_type((lambda s, i, **k: i)(i=0, s='x')) # N: Revealed type is \"Any\"\n[builtins fixtures/dict.pyi]\n\n[case testInferLambdaAsGenericFunctionArgument]\nfrom typing import TypeVar, List, Any, Callable\nt = TypeVar('t')\nclass A:\n  x: 'A'\ndef f(a: List[t], fn: Callable[[t], Any]) -> None: pass\nlist_a = [] # type: List[A]\nf(list_a, lambda a: a.x)\n[builtins fixtures/list.pyi]\n\n[case testLambdaWithoutContext]\nreveal_type(lambda x: x)  # N: Revealed type is \"def (x: Any) -> Any\"\nreveal_type(lambda x: 1)  # N: Revealed type is \"def (x: Any) -> Literal[1]?\"\n\n[case testLambdaContextVararg]\nfrom typing import Callable\ndef f(t: Callable[[str], str]) -> str: ''\nf(lambda *_: '')\n[builtins fixtures/tuple.pyi]\n\n[case testInvalidContextForLambda]\nfrom typing import Callable\nf = lambda x: A() # type: Callable[[], A]\nf2 = lambda: A() # type: Callable[[A], A]\nclass A: pass\n[out]\nmain:2: error: Cannot infer type of lambda\nmain:2: error: Incompatible types in assignment (expression has type \"Callable[[Any], A]\", variable has type \"Callable[[], A]\")\nmain:3: error: Cannot infer type of lambda\nmain:3: error: Incompatible types in assignment (expression has type \"Callable[[], A]\", variable has type \"Callable[[A], A]\")\n\n[case testEllipsisContextForLambda]\nfrom typing import Callable\nf1 = lambda x: 1 # type: Callable[..., int]\nf2 = lambda: 1 # type: Callable[..., int]\nf3 = lambda *args, **kwargs: 1 # type: Callable[..., int]\nf4 = lambda x: x # type: Callable[..., int]\ng = lambda x: 1 # type: Callable[..., str]\n[builtins fixtures/dict.pyi]\n[out]\nmain:6: error: Incompatible types in assignment (expression has type \"Callable[[Any], int]\", variable has type \"Callable[..., str]\")\nmain:6: error: Incompatible return value type (got \"int\", expected \"str\")\n\n[case testEllipsisContextForLambda2]\nfrom typing import TypeVar, Callable\nT = TypeVar('T')\ndef foo(arg: Callable[..., T]) -> None: pass\nfoo(lambda: 1)\n\n[case testLambdaNoneInContext]\n# flags: --no-strict-optional\nfrom typing import Callable\ndef f(x: Callable[[], None]) -> None: pass\ndef g(x: Callable[[], int]) -> None: pass\nf(lambda: None)\ng(lambda: None)\n\n[case testIsinstanceInInferredLambda]\nfrom typing import TypeVar, Callable, Optional\nT = TypeVar('T')\nS = TypeVar('S')\nclass A: pass\nclass B(A): pass\nclass C(A): pass\ndef f(func: Callable[[T], S], *z: T, r: Optional[S] = None) -> S: pass\nreveal_type(f(lambda x: 0 if isinstance(x, B) else 1))  # N: Revealed type is \"Literal[0]? | Literal[1]?\"\nf(lambda x: 0 if isinstance(x, B) else 1, A())() # E: \"int\" not callable\nf(lambda x: x if isinstance(x, B) else B(), A(), r=B())() # E: \"B\" not callable\nf(\n    lambda x:  # E: Argument 1 to \"f\" has incompatible type \"Callable[[A], A]\"; expected \"Callable[[A], B]\"\n        B() if isinstance(x, B) else x, # E: Incompatible return value type (got \"A\", expected \"B\")\n    A(), r=B())\n[builtins fixtures/isinstance.pyi]\n\n[case testLambdaWithFastContainerType]\nfrom collections.abc import Callable\nfrom typing import Never, TypeVar\n\nT = TypeVar(\"T\")\n\ndef f(a: Callable[[], T]) -> None: ...\n\ndef foo(x: str) -> Never: ...\n\nf(lambda: [foo(0)])  # E: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\nf(lambda: {\"x\": foo(0)})  # E: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/tuple.pyi]\n\n\n-- Overloads + generic functions\n-- -----------------------------\n\n\n[case testMapWithOverloadedFunc]\nfrom foo import *\n[file foo.pyi]\nfrom typing import TypeVar, Callable, List, overload, Any\nt = TypeVar('t')\ns = TypeVar('s')\ndef map(f: Callable[[t], s], seq: List[t]) -> List[s]: pass\n\n@overload\ndef g(o: object) -> 'B': pass\n@overload\ndef g(o: 'A', x: Any = None) -> 'B': pass\n\nclass A: pass\nclass B: pass\n\nm = map(g, [A()])\nb = m # type: List[B]\na = m # type: List[A] # E: Incompatible types in assignment (expression has type \"list[B]\", variable has type \"list[A]\")\n[builtins fixtures/list.pyi]\n\n\n-- Boolean operators\n-- -----------------\n\n\n[case testOrOperationInferredFromContext]\nfrom typing import List\nclass A: pass\nclass B: pass\nclass C(B): pass\na: List[A]\nb: List[B]\nc: List[C]\nif int():\n    a = a or []\nif int():\n    a = [] or a\nif int():\n    b = b or [C()]\nif int():\n    a = a or b # E: Incompatible types in assignment (expression has type \"list[A] | list[B]\", variable has type \"list[A]\")\nif int():\n    b = b or c # E: Incompatible types in assignment (expression has type \"list[B] | list[C]\", variable has type \"list[B]\")\n[builtins fixtures/list.pyi]\n\n\n-- Special cases\n-- -------------\n\n\n[case testSomeTypeVarsInferredFromContext]\nfrom typing import List, TypeVar\nt = TypeVar('t')\ns = TypeVar('s')\n# Some type variables can be inferred using context, but not all of them.\na: List[A]\ndef f(a: s, b: t) -> List[s]: pass\nclass A: pass\nclass B: pass\nif int():\n    a = f(A(), B())\nif int():\n    a = f(B(), B()) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\n[builtins fixtures/list.pyi]\n\n[case testSomeTypeVarsInferredFromContext2]\nfrom typing import List, TypeVar\ns = TypeVar('s')\nt = TypeVar('t')\ndef f(a: s, b: t) -> List[s]: pass\nclass A: pass\nclass B: pass\n# Like testSomeTypeVarsInferredFromContext, but tvars in different order.\na: List[A]\nif int():\n    a = f(A(), B())\nif int():\n    a = f(B(), B()) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\n[builtins fixtures/list.pyi]\n\n[case testLambdaInListAndHigherOrderFunction]\nfrom typing import TypeVar, Callable, List\nt = TypeVar('t')\ns = TypeVar('s')\ndef map(f: List[Callable[[t], s]], a: List[t]) -> List[s]: pass\nclass A: pass\nmap(\n  [lambda x: x], [])\n[builtins fixtures/list.pyi]\n[out]\n\n[case testChainedAssignmentInferenceContexts]\nfrom typing import List\ni: List[int]\ns: List[str]\nif int():\n    i = i = []\nif int():\n    i = s = [] # E: Incompatible types in assignment (expression has type \"list[str]\", variable has type \"list[int]\")\n[builtins fixtures/list.pyi]\n\n[case testContextForAttributeDeclaredInInit]\nfrom typing import List\nclass A:\n  def __init__(self):\n    self.x = [] # type: List[int]  # N: By default the bodies of untyped functions are not checked, consider using --check-untyped-defs\na = A()\na.x = []\na.x = [1]\na.x = [''] # E: List item 0 has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testListMultiplyInContext]\nfrom typing import List\na: List[int]\nif int():\n    a = [None] * 3  # E: List item 0 has incompatible type \"None\"; expected \"int\"\n    a = [''] * 3  # E: List item 0 has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testUnionTypeContext]\nfrom typing import Union, List, TypeVar\nT = TypeVar('T')\ndef f(x: Union[List[T], str]) -> None: pass\nf([1])\nf('')\nf(1) # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"list[Never] | str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIgnoringInferenceContext]\nfrom typing import TypeVar, List\nT = TypeVar('T')\ndef f(x: List[T]) -> T: pass\ndef g(y: object) -> None: pass\na = [1]\ng(f(a))\n[builtins fixtures/list.pyi]\n\n[case testStar2Context]\nfrom typing import Any, Dict, Tuple, Iterable\ndef f1(iterable: Iterable[Tuple[str, Any]] = ()) -> None:\n    f2(**dict(iterable))\ndef f2(iterable: Iterable[Tuple[str, Any]], **kw: Any) -> None:\n    pass\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testInferenceInGenericFunction]\nfrom typing import TypeVar, List\nT = TypeVar('T')\ndef f(a: T) -> None:\n    l = []  # type: List[T]\n    l.append(a)\n    l.append(1) # E: Argument 1 to \"append\" of \"list\" has incompatible type \"int\"; expected \"T\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testInferenceInGenericClass]\nfrom typing import TypeVar, Generic, List\nS = TypeVar('S')\nT = TypeVar('T')\nclass A(Generic[S]):\n    def f(self, a: T, b: S) -> None:\n        l = []  # type: List[T]\n        l.append(a)\n        l.append(b) # E: Argument 1 to \"append\" of \"list\" has incompatible type \"S\"; expected \"T\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testLambdaInGenericFunction]\nfrom typing import TypeVar, Callable\nT = TypeVar('T')\nS = TypeVar('S')\ndef f(a: T, b: S) -> None:\n    c = lambda x: x  # type: Callable[[T], S]\n[out]\nmain:5: error: Incompatible types in assignment (expression has type \"Callable[[T], T]\", variable has type \"Callable[[T], S]\")\nmain:5: error: Incompatible return value type (got \"T\", expected \"S\")\n\n[case testLambdaInGenericClass]\nfrom typing import TypeVar, Callable, Generic\nT = TypeVar('T')\nS = TypeVar('S')\nclass A(Generic[T]):\n    def f(self, b: S) -> None:\n        c = lambda x: x  # type: Callable[[T], S]\n[out]\nmain:6: error: Incompatible types in assignment (expression has type \"Callable[[T], T]\", variable has type \"Callable[[T], S]\")\nmain:6: error: Incompatible return value type (got \"T\", expected \"S\")\n\n[case testRevealTypeContext]\nfrom typing import TypeVar, Callable, Generic\nT = TypeVar('T')\nclass A(Generic[T]):\n    pass\nreveal_type(A()) # N: Revealed type is \"__main__.A[Never]\"\nb = reveal_type(A())  # type: A[int] # N: Revealed type is \"__main__.A[builtins.int]\"\n\n[case testUnionWithGenericTypeItemContext]\nfrom typing import TypeVar, Union, List\n\nT = TypeVar('T')\n\ndef f(x: Union[T, List[int]]) -> Union[T, List[int]]: pass\nreveal_type(f(1)) # N: Revealed type is \"builtins.int | builtins.list[builtins.int]\"\nreveal_type(f([])) # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(f(None)) # N: Revealed type is \"None | builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testUnionWithGenericTypeItemContextAndStrictOptional]\nfrom typing import TypeVar, Union, List\n\nT = TypeVar('T')\n\ndef f(x: Union[T, List[int]]) -> Union[T, List[int]]: pass\nreveal_type(f(1)) # N: Revealed type is \"builtins.int | builtins.list[builtins.int]\"\nreveal_type(f([])) # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(f(None)) # N: Revealed type is \"None | builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testUnionWithGenericTypeItemContextInMethod]\nfrom typing import TypeVar, Union, List, Generic\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass C(Generic[T]):\n    def f(self, x: Union[T, S]) -> Union[T, S]: pass\n\nc = C[List[int]]()\nreveal_type(c.f('')) # N: Revealed type is \"builtins.list[builtins.int] | builtins.str\"\nreveal_type(c.f([1])) # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(c.f([])) # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(c.f(None)) # N: Revealed type is \"builtins.list[builtins.int] | None\"\n[builtins fixtures/list.pyi]\n\n[case testUnionWithTupleNeverBranch]\n# https://github.com/python/mypy/issues/20608\nfrom __future__ import annotations\nfrom typing import Callable, Never, Generic, TypeVar\n\nT = TypeVar('T')\nclass ValueType(Generic[T]): pass\nclass Bundle(Generic[T]): pass\n\nF = TypeVar('F')\n\ndef fail_value_type_inference(self_bundle: ValueType[F]) -> tuple[Never, Bundle[ValueType[F]]] | tuple[int, Bundle[ValueType[int]]]:\n    raise\n\nx = fail_value_type_inference\nx = fail_value_type_inference\n[builtins fixtures/tuple.pyi]\n\n[case testGenericMethodCalledInGenericContext]\nfrom typing import TypeVar, Generic\n\n_KT = TypeVar('_KT')\n_VT = TypeVar('_VT')\n_T = TypeVar('_T')\n\nclass M(Generic[_KT, _VT]):\n    def get(self, k: _KT, default: _T) -> _T: ...\n\ndef f(d: M[_KT, _VT], k: _KT) -> _VT:\n    return d.get(k, None)  # E: Incompatible return value type (got \"None\", expected \"_VT\")\n\n[case testGenericMethodCalledInGenericContext2]\nfrom typing import TypeVar, Generic, Union\n\n_KT = TypeVar('_KT')\n_VT = TypeVar('_VT')\n_T = TypeVar('_T')\n\nclass M(Generic[_KT, _VT]):\n    def get(self, k: _KT, default: _T) -> Union[_VT, _T]: ...\n\ndef f(d: M[_KT, _VT], k: _KT) -> Union[_VT, None]:\n    return d.get(k, None)\n\n[case testLambdaDeferredCrash]\nfrom typing import Callable\n\nclass C:\n    def f(self) -> None:\n        g: Callable[[], int] = lambda: 1 or self.x\n        self.x = int()\n\n[case testInferTypeVariableFromTwoGenericTypes1]\nfrom typing import TypeVar, List, Sequence\n\nT = TypeVar('T')\n\nclass C: ...\nclass D(C): ...\n\ndef f(x: Sequence[T], y: Sequence[T]) -> List[T]: ...\n\nreveal_type(f([C()], [D()])) # N: Revealed type is \"builtins.list[__main__.C]\"\n[builtins fixtures/list.pyi]\n\n[case testInferTypeVariableFromTwoGenericTypes2]\nfrom typing import TypeVar, List\n\nT = TypeVar('T')\n\nclass C: ...\nclass D(C): ...\n\ndef f(x: List[T], y: List[T]) -> List[T]: ...\n\nf([C()], [D()]) # E: Cannot infer value of type parameter \"T\" of \"f\"\n[builtins fixtures/list.pyi]\n\n[case testInferTypeVariableFromTwoGenericTypes3]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\nT_contra = TypeVar('T_contra', contravariant=True)\n\nclass A(Generic[T_contra]): pass\nclass B(A[T]): pass\n\nclass C: ...\nclass D(C): ...\n\ndef f(x: A[T], y: A[T]) -> B[T]: ...\n\nc: B[C]\nd: B[D]\nreveal_type(f(c, d)) # N: Revealed type is \"__main__.B[__main__.D]\"\n\n[case testInferTypeVariableFromTwoGenericTypes4]\nfrom typing import Generic, TypeVar, Callable, List\n\nT = TypeVar('T')\nT_contra = TypeVar('T_contra', contravariant=True)\n\nclass A(Generic[T_contra]): pass\nclass B(A[T_contra]): pass\n\nclass C: ...\nclass D(C): ...\n\ndef f(x: Callable[[B[T]], None],\n      y: Callable[[B[T]], None]) -> List[T]: ...\n\ndef gc(x: A[C]) -> None: pass  # B[C]\ndef gd(x: A[D]) -> None: pass  # B[C]\n\nreveal_type(f(gc, gd)) # N: Revealed type is \"builtins.list[__main__.C]\"\n[builtins fixtures/list.pyi]\n\n[case testWideOuterContextSubClassBound]\nfrom typing import TypeVar\n\nclass A: ...\nclass B(A): ...\n\nT = TypeVar('T', bound=B)\ndef f(x: T) -> T: ...\ndef outer(x: A) -> None: ...\n\nouter(f(B()))\nx: A = f(B())\n\n[case testWideOuterContextSubClassBoundGenericReturn]\nfrom typing import TypeVar, Iterable, List\n\nclass A: ...\nclass B(A): ...\n\nT = TypeVar('T', bound=B)\ndef f(x: T) -> List[T]: ...\ndef outer(x: Iterable[A]) -> None: ...\n\nouter(f(B()))\nx: Iterable[A] = f(B())\n[builtins fixtures/list.pyi]\n\n[case testWideOuterContextSubClassValues]\nfrom typing import TypeVar\n\nclass A: ...\nclass B(A): ...\n\nT = TypeVar('T', B, int)\ndef f(x: T) -> T: ...\ndef outer(x: A) -> None: ...\n\nouter(f(B()))\nx: A = f(B())\n\n[case testWideOuterContextSubClassValuesGenericReturn]\nfrom typing import TypeVar, Iterable, List\n\nclass A: ...\nclass B(A): ...\n\nT = TypeVar('T', B, int)\ndef f(x: T) -> List[T]: ...\ndef outer(x: Iterable[A]) -> None: ...\n\nouter(f(B()))\nx: Iterable[A] = f(B())\n[builtins fixtures/list.pyi]\n\n[case testWideOuterContextSubclassBoundGeneric]\nfrom typing import TypeVar, Generic\n\nS = TypeVar('S')\nclass A(Generic[S]): ...\nclass B(A[S]): ...\n\nT = TypeVar('T', bound=B[int])\ndef f(x: T) -> T: ...\ndef outer(x: A[int]) -> None: ...\n\ny: B[int]\nouter(f(y))\nx: A[int] = f(y)\n\n[case testWideOuterContextSubclassBoundGenericCovariant]\nfrom typing import TypeVar, Generic\n\nS_co = TypeVar('S_co', covariant=True)\nclass A(Generic[S_co]): ...\nclass B(A[S_co]): ...\n\nT = TypeVar('T', bound=B[int])\ndef f(x: T) -> T: ...\ndef outer(x: A[int]) -> None: ...\n\ny: B[int]\nouter(f(y))\nx: A[int] = f(y)\n\n[case testWideOuterContextSubclassValuesGeneric]\nfrom typing import TypeVar, Generic\n\nS = TypeVar('S')\nclass A(Generic[S]): ...\nclass B(A[S]): ...\n\nT = TypeVar('T', B[int], int)\ndef f(x: T) -> T: ...\ndef outer(x: A[int]) -> None: ...\n\ny: B[int]\nouter(f(y))\nx: A[int] = f(y)\n\n[case testWideOuterContextSubclassValuesGenericCovariant]\nfrom typing import TypeVar, Generic\n\nS_co = TypeVar('S_co', covariant=True)\nclass A(Generic[S_co]): ...\nclass B(A[S_co]): ...\n\nT = TypeVar('T', B[int], int)\ndef f(x: T) -> T: ...\ndef outer(x: A[int]) -> None: ...\n\ny: B[int]\nouter(f(y))\nx: A[int] = f(y)\n\n[case testWideOuterContextUnionBound]\nfrom typing import TypeVar, Union\n\nclass A: ...\nclass B: ...\n\nT = TypeVar('T', bound=B)\ndef f(x: T) -> T: ...\ndef outer(x: Union[A, B]) -> None: ...\n\nouter(f(B()))\nx: Union[A, B] = f(B())\n\n[case testWideOuterContextUnionBoundGenericReturn]\nfrom typing import TypeVar, Union, Iterable, List\n\nclass A: ...\nclass B: ...\n\nT = TypeVar('T', bound=B)\ndef f(x: T) -> List[T]: ...\ndef outer(x: Iterable[Union[A, B]]) -> None: ...\n\nouter(f(B()))\nx: Iterable[Union[A, B]] = f(B())\n[builtins fixtures/list.pyi]\n\n[case testWideOuterContextUnionValues]\nfrom typing import TypeVar, Union\n\nclass A: ...\nclass B: ...\n\nT = TypeVar('T', B, int)\ndef f(x: T) -> T: ...\ndef outer(x: Union[A, B]) -> None: ...\n\nouter(f(B()))\nx: Union[A, B] = f(B())\n\n[case testWideOuterContextUnionValuesGenericReturn]\nfrom typing import TypeVar, Union, Iterable, List\n\nclass A: ...\nclass B: ...\n\nT = TypeVar('T', B, int)\ndef f(x: T) -> List[T]: ...\ndef outer(x: Iterable[Union[A, B]]) -> None: ...\n\nouter(f(B()))\nx: Iterable[Union[A, B]] = f(B())\n[builtins fixtures/list.pyi]\n\n[case testWideOuterContextOptional]\nfrom typing import Optional, Type, TypeVar\n\nclass Custom:\n    pass\n\nT = TypeVar('T', bound=Custom)\n\ndef a(x: T) -> Optional[T]: ...\n\ndef b(x: T) -> Optional[T]:\n    return a(x)\n\n[case testWideOuterContextOptionalGenericReturn]\nfrom typing import Optional, Type, TypeVar, Iterable\n\nclass Custom:\n    pass\n\nT = TypeVar('T', bound=Custom)\n\ndef a(x: T) -> Iterable[Optional[T]]: ...\n\ndef b(x: T) -> Iterable[Optional[T]]:\n    return a(x)\n\n[case testWideOuterContextOptionalMethod]\nfrom typing import Optional, Type, TypeVar\n\nclass A: pass\nclass B: pass\n\nT = TypeVar('T', A, B)\nclass C:\n    def meth_a(self) -> Optional[A]:\n        return self.meth(A)\n\n    def meth(self, cls: Type[T]) -> Optional[T]: ...\n\n[case testWideOuterContextValuesOverlapping]\nfrom typing import TypeVar, List\n\nclass A:\n    pass\nclass B(A):\n    pass\nclass C:\n    pass\n\nT = TypeVar('T', A, B, C)\ndef foo(xs: List[T]) -> T: ...\n\nS = TypeVar('S', B, C)\ndef bar(xs: List[S]) -> S:\n    foo(xs)\n    return xs[0]\n[builtins fixtures/list.pyi]\n\n[case testWideOuterContextOptionalTypeVarReturn]\nfrom typing import Callable, Iterable, List, Optional, TypeVar\n\nclass C:\n    x: str\n\nT = TypeVar('T')\ndef f(i: Iterable[T], c: Callable[[T], str]) -> Optional[T]: ...\n\ndef g(l: List[C], x: str) -> Optional[C]:\n    def pred(c: C) -> str:\n        return c.x\n    return f(l, pred)\n[builtins fixtures/list.pyi]\n\n[case testWideOuterContextOptionalTypeVarReturnLambda]\nfrom typing import Callable, Iterable, List, Optional, TypeVar\n\nclass C:\n    x: str\n\nT = TypeVar('T')\ndef f(i: Iterable[T], c: Callable[[T], str]) -> Optional[T]: ...\n\ndef g(l: List[C], x: str) -> Optional[C]:\n    return f(l, lambda c: reveal_type(c).x)  # N: Revealed type is \"__main__.C\"\n[builtins fixtures/list.pyi]\n\n[case testPartialTypeContextWithTwoLambdas]\nfrom typing import Any, Generic, TypeVar, Callable\n\ndef int_to_any(x: int) -> Any: ...\ndef any_to_int(x: Any) -> int: ...\ndef any_to_str(x: Any) -> str: ...\n\nT = TypeVar(\"T\")\nclass W(Generic[T]):\n    def __init__(\n        self, serialize: Callable[[T], Any], deserialize: Callable[[Any], T]\n    ) -> None:\n        ...\nreveal_type(W(lambda x: int_to_any(x), lambda x: any_to_int(x)))  # N: Revealed type is \"__main__.W[builtins.int]\"\nW(\n    lambda x: int_to_any(x),  # E: Argument 1 to \"int_to_any\" has incompatible type \"str\"; expected \"int\"\n    lambda x: any_to_str(x)\n)\n\n[case testWideOuterContextEmpty]\nfrom typing import List, TypeVar\n\nT = TypeVar('T', bound=int)\ndef f(x: List[T]) -> T: ...\n\n# mypy infers List[Never] here, and Never is a subtype of str\ny: str = f([])\n[builtins fixtures/list.pyi]\n\n[case testWideOuterContextEmptyError]\nfrom typing import List, TypeVar\n\nT = TypeVar('T', bound=int)\ndef f(x: List[T]) -> List[T]: ...\n\ny: List[str] = f([])\n[builtins fixtures/list.pyi]\n\n[case testWideOuterContextNoArgs]\nfrom typing import TypeVar, Optional\n\nT = TypeVar('T', bound=int)\ndef f(x: Optional[T] = None) -> T: ...\n\ny: str = f()\n\n[case testWideOuterContextNoArgsError]\nfrom typing import TypeVar, Optional, List\n\nT = TypeVar('T', bound=int)\ndef f(x: Optional[T] = None) -> List[T]: ...\n\ny: List[str] = f()\n[builtins fixtures/list.pyi]\n\n[case testUseCovariantGenericOuterContext]\nfrom typing import TypeVar, Callable, Tuple\n\nT = TypeVar('T')\n\ndef f(x: Callable[..., T]) -> T:\n    return x()\n\nx: Tuple[str, ...] = f(tuple)\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testUseCovariantGenericOuterContextUserDefined]\nfrom typing import TypeVar, Callable, Generic\n\nT_co = TypeVar('T_co', covariant=True)\nT = TypeVar('T')\n\nclass G(Generic[T_co]): ...\n\ndef f(x: Callable[..., T]) -> T:\n    return x()\n\nx: G[str] = f(G)\n[out]\n\n[case testConditionalExpressionWithEmptyListAndUnionWithAny]\nfrom typing import Union, List, Any\n\ndef f(x: Union[List[str], Any]) -> None:\n    a = x if x else []\n    reveal_type(a)  # N: Revealed type is \"builtins.list[builtins.str] | Any | builtins.list[builtins.str | Any]\"\n[builtins fixtures/list.pyi]\n\n[case testConditionalExpressionWithEmptyIteableAndUnionWithAny]\nfrom typing import Union, Iterable, Any\n\ndef f(x: Union[Iterable[str], Any]) -> None:\n    a = x if x else []\n    reveal_type(a)  # N: Revealed type is \"typing.Iterable[builtins.str] | Any | builtins.list[builtins.str | Any]\"\n[builtins fixtures/list.pyi]\n\n[case testInferMultipleAnyUnionCovariant]\nfrom typing import Any, Mapping, Sequence, Union\n\ndef foo(x: Union[Mapping[Any, Any], Mapping[Any, Sequence[Any]]]) -> None:\n    ...\nfoo({1: 2})\n[builtins fixtures/dict.pyi]\n\n[case testInferMultipleAnyUnionInvariant]\nfrom typing import Any, Dict, Sequence, Union\n\ndef foo(x: Union[Dict[Any, Any], Dict[Any, Sequence[Any]]]) -> None:\n    ...\nfoo({1: 2})\n[builtins fixtures/dict.pyi]\n\n[case testInferMultipleAnyUnionDifferentVariance]\nfrom typing import Any, Dict, Mapping, Sequence, Union\n\ndef foo(x: Union[Dict[Any, Any], Mapping[Any, Sequence[Any]]]) -> None:\n    ...\nfoo({1: 2})\n\ndef bar(x: Union[Mapping[Any, Any], Dict[Any, Sequence[Any]]]) -> None:\n    ...\nbar({1: 2})\n[builtins fixtures/dict.pyi]\n\n[case testOptionalTypeNarrowedByGenericCall]\nfrom typing import Dict, Optional\n\nd: Dict[str, str] = {}\n\ndef foo(arg: Optional[str] = None) -> None:\n    if arg is None:\n        arg = d.get(\"a\", \"b\")\n    reveal_type(arg)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n\n[case testOptionalTypeNarrowedByGenericCall2]\nfrom typing import Dict, Optional\n\nd: Dict[str, str] = {}\nx: Optional[str]\nif x:\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    x = d.get(x, x)\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n\n[case testOptionalTypeNarrowedByGenericCall3]\nfrom typing import Generic, TypeVar, Union\n\nT = TypeVar(\"T\")\ndef bar(arg: Union[str, T]) -> Union[str, T]: ...\n\ndef foo(arg: Union[str, int]) -> None:\n    if isinstance(arg, int):\n        arg = bar(\"default\")\n    reveal_type(arg)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/isinstance.pyi]\n\n[case testOptionalTypeNarrowedByGenericCall4]\nfrom typing import Optional, List, Generic, TypeVar\n\nT = TypeVar(\"T\", covariant=True)\nclass C(Generic[T]): ...\n\nx: Optional[C[int]] = None\ny = x = C()\nreveal_type(y)  # N: Revealed type is \"__main__.C[builtins.int]\"\n\n[case testOptionalTypeNarrowedByGenericCall5]\nfrom typing import Any, Tuple, Union\n\ni: Union[Tuple[Any, ...], int]\nb: Any\ni = i if isinstance(i, int) else b\nreveal_type(i)  # N: Revealed type is \"Any | builtins.int\"\n[builtins fixtures/isinstance.pyi]\n\n[case testLambdaInferenceUsesNarrowedTypes]\nfrom typing import Optional, Callable\n\ndef f1(key: Callable[[], str]) -> None: ...\ndef f2(key: object) -> None: ...\n\ndef g(b: Optional[str]) -> None:\n    if b:\n        f1(lambda: reveal_type(b))  # N: Revealed type is \"builtins.str\"\n        z: Callable[[], str] = lambda: reveal_type(b)  # N: Revealed type is \"builtins.str\"\n        f2(lambda: reveal_type(b))  # N: Revealed type is \"builtins.str\"\n        lambda: reveal_type(b)  # N: Revealed type is \"builtins.str\"\n\n[case testInferenceContextReturningTypeVarUnion]\nfrom collections.abc import Callable, Iterable\nfrom typing import TypeVar, Union\n\n_T1 = TypeVar(\"_T1\")\n_T2 = TypeVar(\"_T2\")\n\ndef mymin(\n    iterable: Iterable[_T1], /, *, key: Callable[[_T1], int], default: _T2\n) -> Union[_T1, _T2]: ...\n\ndef check(paths: Iterable[str], key: Callable[[str], int]) -> Union[str, None]:\n    return mymin(paths, key=key, default=None)\n[builtins fixtures/tuple.pyi]\n\n[case testBinaryOpInferenceContext]\nfrom typing import Literal, TypeVar\n\nT = TypeVar(\"T\")\n\ndef identity(x: T) -> T:\n    return x\n\ndef check1(use: bool, val: str) -> \"str | Literal[True]\":\n    return use or identity(val)\n\ndef check2(use: bool, val: str) -> \"str | bool\":\n    return use or identity(val)\n\ndef check3(use: bool, val: str) -> \"str | Literal[False]\":\n    return use and identity(val)\n\ndef check4(use: bool, val: str) -> \"str | bool\":\n    return use and identity(val)\n[builtins fixtures/tuple.pyi]\n\n[case testDictAnyOrLiteralInContext]\nfrom typing import Union, Optional, Any\n\ndef f(x: dict[str, Union[str, None, int]]) -> None:\n    pass\n\ndef g(x: Optional[dict[str, Any]], s: Optional[str]) -> None:\n    f(x or {'x': s})\n[builtins fixtures/dict.pyi]\n\n[case testReturnFallbackInferenceTuple]\nfrom typing import TypeVar, Union\n\nT = TypeVar(\"T\")\ndef foo(x: list[T]) -> tuple[T, ...]: ...\n\ndef bar(x: list[int]) -> tuple[Union[str, int], ...]:\n    return foo(x)\n\ndef bar2(x: list[int]) -> tuple[Union[str, int], ...]:\n    y = foo(x)\n    return y\n[builtins fixtures/tuple.pyi]\n\n[case testReturnFallbackInferenceUnion]\nfrom typing import Generic, TypeVar, Union\n\nT = TypeVar(\"T\")\n\nclass Cls(Generic[T]):\n    pass\n\ndef inner(c: Cls[T]) -> Union[T, int]:\n    return 1\n\ndef outer(c: Cls[T]) -> Union[T, int]:\n    return inner(c)\n\n[case testReturnFallbackInferenceAsync]\nfrom typing import Generic, TypeVar, Optional\n\nT = TypeVar(\"T\")\n\nclass Cls(Generic[T]):\n    pass\n\nasync def inner(c: Cls[T]) -> Optional[T]:\n    return None\n\nasync def outer(c: Cls[T]) -> Optional[T]:\n    return await inner(c)\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n"
  },
  {
    "path": "test-data/unit/check-inference.test",
    "content": "-- Inferring locals/globals with simple types\n-- ------------------------------------------\n\n\n[case testInferSimpleGvarType]\nclass A: pass\nclass B: pass\n\nx = A()\ny = B()\nif int():\n    x = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    x = A()\nif int():\n    x = y   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    x = x\n[case testInferSimpleLvarType]\nimport typing\ndef f() -> None:\n    x = A()\n    y = B()\n    if int():\n        x = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        x = A()\n        x = y   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        x = x\nclass A: pass\nclass B: pass\n[out]\n\n[case testLvarInitializedToVoid]\nimport typing\ndef f() -> None:\n    a = g()    # E: \"g\" does not return a value (it only ever returns None)\n    #b, c = g() # \"g\" does not return a value (it only ever returns None) TODO\n\ndef g() -> None: pass\n[out]\n\n[case testInferringLvarTypeFromArgument]\nimport typing\ndef f(a: 'A') -> None:\n    b = a\n    if int():\n        b = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        b = a\n        a = b\n\nclass A: pass\nclass B: pass\n[out]\n\n[case testInferringLvarTypeFromGvar]\n\ng: B\n\ndef f() -> None:\n    a = g\n    if int():\n        a = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n        a = B()\n\nclass A: pass\nclass B: pass\n[out]\n\n[case testInferringImplicitDynamicTypeForLvar]\nimport typing\ndef f() -> None:\n    a = g()\n    None(a) # E: \"None\" not callable\n    a.x()\n\ndef g(): pass\n[out]\n\n[case testInferringExplicitDynamicTypeForLvar]\nfrom typing import Any\ng: Any\n\ndef f(a: Any) -> None:\n    b = g\n    None(b) # E: \"None\" not callable\n    a.x()\n[out]\n\n\n-- Inferring types of local variables with complex types\n-- -----------------------------------------------------\n\n\n[case testInferringTupleTypeForLvar]\n\ndef f() -> None:\n    a = A(), B()\n    aa: A\n    bb: B\n    if int():\n        bb = a[0] # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n        aa = a[1] # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        aa = a[0]\n        bb = a[1]\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testInferringTupleTypeForLvarWithNones]\nimport typing\ndef f() -> None:\n    a = A(), None\n    b = None, A()\n\nclass A: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testInferringGenericTypeForLvar]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nclass A(Generic[T]): pass\na_i: A[int]\na_s: A[str]\n\ndef f() -> None:\n    a_int = A() # type: A[int]\n    a = a_int\n    if int():\n        a = a_s # E: Incompatible types in assignment (expression has type \"A[str]\", variable has type \"A[int]\")\n        a = a_i\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testInferringFunctionTypeForLvar]\nimport typing\ndef f() -> None:\n    a = g\n    a(B()) # E: Argument 1 has incompatible type \"B\"; expected \"A\"\n    a(A())\n\ndef g(a: 'A') -> None: pass\n\nclass A: pass\nclass B: pass\n[out]\n\n[case testInferringFunctionTypeForLvarFromTypeObject]\nimport typing\ndef f() -> None:\n    a = A\n    a(A()) # E: Too many arguments\n    a()\n    t = a # type: type\n\nclass A: pass\n[out]\n\n\n-- Inferring variable types in multiple definition\n-- -----------------------------------------------\n\n\n[case testInferringLvarTypesInMultiDef]\nimport typing\ndef f() -> None:\n    a, b = A(), B()\n    if int():\n        a = b   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n        a = A()\n        b = B()\n\nclass A: pass\nclass B: pass\n[out]\n\n[case testInferringLvarTypesInTupleAssignment]\nfrom typing import Tuple\ndef f() -> None:\n    t: Tuple[A, B]\n    a, b = t\n    if int():\n        a = b   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n        a = A()\n        b = B()\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testInferringLvarTypesInNestedTupleAssignment1]\nfrom typing import Tuple\ndef f() -> None:\n    t: Tuple[A, B]\n    a1, (a, b) = A(), t\n    if int():\n        a = b   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n        a = A()\n        b = B()\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testInferringLvarTypesInNestedTupleAssignment2]\nimport typing\ndef f() -> None:\n    a, (b, c) = A(), (B(), C())\n    if int():\n        a = b   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n        c = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"C\")\n\n        a = A()\n        b = B()\n        c = C()\n\nclass A: pass\nclass B: pass\nclass C: pass\n[out]\n\n[case testInferringLvarTypesInNestedListAssignment]\nimport typing\ndef f() -> None:\n    a, (b, c) = A(), [B(), C()]\n    if int():\n        a = b   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n        c = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"C\")\n\n        a = A()\n        b = B()\n        c = C()\n\nclass A: pass\nclass B: pass\nclass C: pass\n[out]\n\n[case testInferringLvarTypesInMultiDefWithNoneTypes]\nimport typing\ndef f() -> None:\n    a, b = A(), None\n    c, d = None, A()\n\nclass A: pass\n[out]\n\n[case testInferringLvarTypesInNestedTupleAssignmentWithNoneTypes]\nimport typing\ndef f() -> None:\n    a1, (a2, b) = A(), (A(), None)\n\nclass A: pass\n[out]\n\n[case testClassObjectsNotUnpackableWithoutIterableMetaclass]\nfrom typing import Type\n\nclass Foo: ...\nA: Type[Foo] = Foo\na, b = Foo  # E: \"type[Foo]\" object is not iterable\nc, d = A  # E: \"type[Foo]\" object is not iterable\n\nclass Meta(type): ...\nclass Bar(metaclass=Meta): ...\nB: Type[Bar] = Bar\ne, f = Bar  # E: \"type[Bar]\" object is not iterable\ng, h = B  # E: \"type[Bar]\" object is not iterable\n\nreveal_type(a)  # E: Cannot determine type of \"a\"  # N: Revealed type is \"Any\"\nreveal_type(b)  # E: Cannot determine type of \"b\"  # N: Revealed type is \"Any\"\nreveal_type(c)  # E: Cannot determine type of \"c\"  # N: Revealed type is \"Any\"\nreveal_type(d)  # E: Cannot determine type of \"d\"  # N: Revealed type is \"Any\"\nreveal_type(e)  # E: Cannot determine type of \"e\"  # N: Revealed type is \"Any\"\nreveal_type(f)  # E: Cannot determine type of \"f\"  # N: Revealed type is \"Any\"\nreveal_type(g)  # E: Cannot determine type of \"g\"  # N: Revealed type is \"Any\"\nreveal_type(h)  # E: Cannot determine type of \"h\"  # N: Revealed type is \"Any\"\n[out]\n\n[case testInferringLvarTypesUnpackedFromIterableClassObject]\nfrom typing import Iterator, Type, TypeVar, Union, overload\nclass Meta(type):\n    def __iter__(cls) -> Iterator[int]:\n        yield from [1, 2, 3]\n\nclass Meta2(type):\n    def __iter__(cls) -> Iterator[str]:\n        yield from [\"foo\", \"bar\", \"baz\"]\n\nclass Meta3(type): ...\n\nclass Foo(metaclass=Meta): ...\nclass Bar(metaclass=Meta2): ...\nclass Baz(metaclass=Meta3): ...\nclass Spam: ...\n\nclass Eggs(metaclass=Meta):\n    @overload\n    def __init__(self, x: int) -> None: ...\n    @overload\n    def __init__(self, x: int, y: int, z: int) -> None: ...\n    def __init__(self, x: int, y: int = ..., z: int = ...) -> None: ...\n\nA: Type[Foo] = Foo\nB: Type[Union[Foo, Bar]] = Foo\nC: Union[Type[Foo], Type[Bar]] = Foo\nD: Type[Union[Foo, Baz]] = Foo\nE: Type[Union[Foo, Spam]] = Foo\nF: Type[Eggs] = Eggs\nG: Type[Union[Foo, Eggs]] = Foo\n\na, b, c = Foo\nd, e, f = A\ng, h, i = B\nj, k, l = C\nm, n, o = D  # E: \"type[Baz]\" object is not iterable\np, q, r = E  # E: \"type[Spam]\" object is not iterable\ns, t, u = Eggs\nv, w, x = F\ny, z, aa = G\n\nfor var in [a, b, c, d, e, f, s, t, u, v, w, x, y, z, aa]:\n    reveal_type(var)  # N: Revealed type is \"builtins.int\"\n\nfor var2 in [g, h, i, j, k, l]:\n    reveal_type(var2)  # N: Revealed type is \"builtins.int | builtins.str\"\n\nfor var3 in [m, n, o, p, q, r]:\n    reveal_type(var3)  # N: Revealed type is \"builtins.int | Any\"\n\nT = TypeVar(\"T\", bound=Type[Foo])\n\ndef check(x: T) -> T:\n    a, b, c = x\n    for var in [a, b, c]:\n        reveal_type(var)  # N: Revealed type is \"builtins.int\"\n    return x\n\nT2 = TypeVar(\"T2\", bound=Type[Union[Foo, Bar]])\n\ndef check2(x: T2) -> T2:\n    a, b, c = x\n    for var in [a, b, c]:\n        reveal_type(var)  # N: Revealed type is \"builtins.int | builtins.str\"\n    return x\n\nT3 = TypeVar(\"T3\", bound=Union[Type[Foo], Type[Bar]])\n\ndef check3(x: T3) -> T3:\n    a, b, c = x\n    for var in [a, b, c]:\n        reveal_type(var)  # N: Revealed type is \"builtins.int | builtins.str\"\n    return x\n[out]\n\n[case testInferringLvarTypesUnpackedFromIterableClassObjectWithGenericIter]\nfrom typing import Iterator, Type, TypeVar\n\nT = TypeVar(\"T\")\nclass Meta(type):\n    def __iter__(self: Type[T]) -> Iterator[T]: ...\nclass Foo(metaclass=Meta): ...\n\nA, B, C = Foo\nreveal_type(A)  # N: Revealed type is \"__main__.Foo\"\nreveal_type(B)  # N: Revealed type is \"__main__.Foo\"\nreveal_type(C)  # N: Revealed type is \"__main__.Foo\"\n[out]\n\n[case testInferringLvarTypesInMultiDefWithInvalidTuple]\nfrom typing import Tuple\nt: Tuple[object, object, object]\n\ndef f() -> None:\n    a, b = t         # Fail\n    c, d, e, f = t   # Fail\n    g, h, i = t\n[builtins fixtures/tuple.pyi]\n[out]\nmain:5: error: Too many values to unpack (2 expected, 3 provided)\nmain:6: error: Need more than 3 values to unpack (4 expected)\n\n[case testInvalidRvalueTypeInInferredMultipleLvarDefinition]\nimport typing\ndef f() -> None:\n    a, b = f   # E: \"Callable[[], None]\" object is not iterable\n    c, d = A() # E: \"A\" object is not iterable\nclass A: pass\n[builtins fixtures/for.pyi]\n[out]\n\n[case testInvalidRvalueTypeInInferredNestedTupleAssignment]\nimport typing\ndef f() -> None:\n    a1, (a2, b) = A(), f   # E: \"Callable[[], None]\" object is not iterable\n    a3, (c, d) = A(), A() # E: \"A\" object is not iterable\nclass A: pass\n[builtins fixtures/for.pyi]\n[out]\n\n[case testInferringMultipleLvarDefinitionWithListRvalue]\nfrom typing import List\n\nclass C: pass\nclass D: pass\n\ndef f() -> None:\n    list_c = [C()]\n    list_d = [D()]\n    a, b = list_c\n    c, d, e = list_d\n    if int():\n        a = D() # E: Incompatible types in assignment (expression has type \"D\", variable has type \"C\")\n        b = D() # E: Incompatible types in assignment (expression has type \"D\", variable has type \"C\")\n        c = C() # E: Incompatible types in assignment (expression has type \"C\", variable has type \"D\")\n        b = c   # E: Incompatible types in assignment (expression has type \"D\", variable has type \"C\")\n\n        a = C()\n        b = C()\n        c = D()\n        d = D()\n        e = D()\n\n        a = b\n        c = d\n        d = e\n[builtins fixtures/for.pyi]\n[out]\n\n[case testInferringNestedTupleAssignmentWithListRvalue]\nfrom typing import List\n\nclass C: pass\nclass D: pass\n\ndef f() -> None:\n    list_c = [C()]\n    list_d = [D()]\n    c1, (a, b) = C(), list_c\n    c2, (c, d, e) = C(), list_d\n    if int():\n        a = D() # E: Incompatible types in assignment (expression has type \"D\", variable has type \"C\")\n        b = D() # E: Incompatible types in assignment (expression has type \"D\", variable has type \"C\")\n        c = C() # E: Incompatible types in assignment (expression has type \"C\", variable has type \"D\")\n        b = c   # E: Incompatible types in assignment (expression has type \"D\", variable has type \"C\")\n\n        a = C()\n        b = C()\n        c = D()\n        d = D()\n        e = D()\n\n        a = b\n        c = d\n        d = e\n[builtins fixtures/for.pyi]\n[out]\n\n[case testInferringMultipleLvarDefinitionWithImplicitDynamicRvalue]\nimport typing\ndef f() -> None:\n    a, b = g()\n    a.x\n    b.x\ndef g(): pass\n\n[case testInferringMultipleLvarDefinitionWithExplicitDynamicRvalue]\nfrom typing import Any\ndef f(d: Any) -> None:\n    a, b = d\n    a.x\n    b.x\n\n[case testInferringTypesFromIterable]\nfrom typing import Iterable\nclass Nums(Iterable[int]):\n    def __iter__(self): pass\n    def __next__(self): pass\na, b = Nums()\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\nreveal_type(b)  # N: Revealed type is \"builtins.int\"\nif int():\n    a = b = 1\nif int():\n    a = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    b = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/for.pyi]\n\n[case testInferringTypesFromIterableStructuralSubtyping1]\nfrom typing import Iterator\nclass Nums:\n    def __iter__(self) -> Iterator[int]: pass\na, b = Nums()\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\nreveal_type(b)  # N: Revealed type is \"builtins.int\"\nif int():\n    a = b = 1\nif int():\n    a = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    b = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/for.pyi]\n\n[case testInferringTypesFromIterableStructuralSubtyping2]\nfrom typing import Self\nclass Nums:\n    def __iter__(self) -> Self: pass\n    def __next__(self) -> int: pass\na, b = Nums()\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\nreveal_type(b)  # N: Revealed type is \"builtins.int\"\nif int():\n    a = b = 1\nif int():\n    a = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nif int():\n    b = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[builtins fixtures/tuple.pyi]\n\n\n-- Type variable inference for generic functions\n-- ---------------------------------------------\n\n\n[case testInferSimpleGenericFunction]\nfrom typing import Tuple, TypeVar\nT = TypeVar('T')\na: A\nb: B\nc: Tuple[A, object]\n\ndef id(a: T) -> T: pass\n\nif int():\n    b = id(a) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    a = id(b) # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nif int():\n    a = id(c) # E: Incompatible types in assignment (expression has type \"tuple[A, object]\", variable has type \"A\")\n\nif int():\n    a = id(a)\n    b = id(b)\n    c = id(c)\n\nclass A: pass\nclass B: pass\n[builtins fixtures/tuple.pyi]\n\n[case testInferringGenericFunctionTypeForLvar]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef f() -> None:\n    a = id\n    b: int\n    c: str\n    if int():\n        b = a(c) # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        b = a(b)\n        c = a(c)\ndef id(x: T) -> T:\n    return x\n[out]\n\n[case testUnderspecifiedInferenceResult]\n# flags: --no-strict-optional\nfrom typing import TypeVar\nT = TypeVar('T')\nclass A: pass\na: A\n\ndef ff() -> None:\n    x = f() # E: Need type annotation for \"x\"\n    reveal_type(x) # N: Revealed type is \"Any\"\n\ndef f() -> T: pass # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\ndef g(a: T) -> None: pass\n\ng(None) # Ok\nf()     # Ok because not used to infer local variable type\ng(a)\n[out]\n\n[case testInferenceWithMultipleConstraints]\nfrom typing import TypeVar\n\nclass A: pass\nclass B(A): pass\n\nT = TypeVar('T')\na: A\nb: B\n\ndef f(a: T, b: T) -> T: pass\n\nif int():\n    b = f(a, b) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    b = f(b, a) # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\nif int():\n    a = f(a, b)\nif int():\n    a = f(b, a)\n\n[case testInferenceWithMultipleVariables]\nfrom typing import Tuple, TypeVar\nT = TypeVar('T')\nS = TypeVar('S')\n\ndef f(a: T, b: S) -> Tuple[T, S]: pass\n\nclass A: pass\nclass B: pass\n\na: A\nb: B\ntaa: Tuple[A, A]\ntab: Tuple[A, B]\ntba: Tuple[B, A]\n\nif int():\n    taa = f(a, b) # E: Argument 2 to \"f\" has incompatible type \"B\"; expected \"A\"\nif int():\n    taa = f(b, a) # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\nif int():\n    tba = f(a, b) # E: Argument 1 to \"f\" has incompatible type \"A\"; expected \"B\" \\\n                  # E: Argument 2 to \"f\" has incompatible type \"B\"; expected \"A\"\n\nif int():\n    tab = f(a, b)\nif int():\n    tba = f(b, a)\n[builtins fixtures/tuple.pyi]\n\n[case testConstraintSolvingWithSimpleGenerics]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nao: A[object]\nab: A[B]\nac: A[C]\n\ndef f(a: 'A[T]') -> 'A[T]': pass\n\ndef g(a: T) -> T: pass\n\nclass A(Generic[T]): pass\nclass B: pass\nclass C: pass\n\nif int():\n    ab = f(ao) # E: Argument 1 to \"f\" has incompatible type \"A[object]\"; expected \"A[B]\"\n    ao = f(ab) # E: Argument 1 to \"f\" has incompatible type \"A[B]\"; expected \"A[object]\"\nif int():\n    ab = f(ac) # E: Argument 1 to \"f\" has incompatible type \"A[C]\"; expected \"A[B]\"\nif int():\n    ab = g(ao) # E: Argument 1 to \"g\" has incompatible type \"A[object]\"; expected \"A[B]\"\n    ao = g(ab) # E: Argument 1 to \"g\" has incompatible type \"A[B]\"; expected \"A[object]\"\n\nif int():\n    ab = f(ab)\n    ac = f(ac)\n    ao = f(ao)\n\nif int():\n    ab = g(ab)\n    ao = g(ao)\n[case testConstraintSolvingFailureWithSimpleGenerics]\nfrom typing import TypeVar, Generic\nT = TypeVar('T')\nao: A[object]\nab: A[B]\n\ndef f(a: 'A[T]', b: 'A[T]') -> None: pass\n\nclass A(Generic[T]): pass\nclass B: pass\n\n\nf(ao, ab) # E: Cannot infer value of type parameter \"T\" of \"f\"\nf(ab, ao) # E: Cannot infer value of type parameter \"T\" of \"f\"\nf(ao, ao)\nf(ab, ab)\n\n[case testTypeInferenceWithCalleeDefaultArgs]\n# flags: --no-strict-optional\nfrom typing import TypeVar\nT = TypeVar('T')\na = None # type: A\no = None # type: object\n\ndef f(a: T = None) -> T: pass\ndef g(a: T, b: T = None) -> T: pass\n\nclass A: pass\n\nif int():\n    a = f(o)    # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nif int():\n    a = g(a, o) # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n\nif int():\n    o = f()\nif int():\n    o = f(o)\nif int():\n    a = f(a)\nif int():\n    a = g(a)\n\n\n-- Generic function inference with multiple inheritance\n-- ----------------------------------------------------\n\n\n[case testGenericFunctionInferenceWithMultipleInheritance]\nfrom typing import TypeVar\n\nclass I: pass\nclass J: pass\n\nclass A(I, J): pass\nclass B(I, J): pass\nclass C(I): pass\nclass D(J): pass\n\nT = TypeVar('T')\ndef f(a: T, b: T) -> T: pass\ndef g(x: I) -> None: pass\n\na = f(A(), C())\ng(a)\nb = f(A(), B())\ng(b)\nc = f(A(), D())\ng(c) # E: Argument 1 to \"g\" has incompatible type \"J\"; expected \"I\"\nd = f(D(), A())\ng(d) # E: Argument 1 to \"g\" has incompatible type \"J\"; expected \"I\"\ne = f(D(), C())\ng(e) # E: Argument 1 to \"g\" has incompatible type \"object\"; expected \"I\"\n\n[case testGenericFunctionInferenceWithMultipleInheritance2]\nfrom typing import TypeVar\n\nclass I: pass\nclass J: pass\n\nclass A(I): pass\nclass B(A, J): pass\nclass C(I, J): pass\n\nT = TypeVar('T')\ndef f(a: T, b: T) -> T: pass\ndef g(x: I) -> None: pass\ndef h(x: J) -> None: pass\n\na = f(B(), C())\ng(a)\nh(a) # E: Argument 1 to \"h\" has incompatible type \"I\"; expected \"J\"\nb = f(C(), B())\ng(b)\nh(b) # E: Argument 1 to \"h\" has incompatible type \"I\"; expected \"J\"\nc = f(A(), B())\ng(a)\nh(b) # E: Argument 1 to \"h\" has incompatible type \"I\"; expected \"J\"\n\n[case testGenericFunctionInferenceWithMultipleInheritance3]\nfrom typing import TypeVar\n\nclass I: pass\nclass J: pass\nclass K(J): pass\n\nclass A(K): pass\nclass B(A, I): pass\nclass C(I, J): pass\n\nT = TypeVar('T')\ndef f(a: T, b: T) -> T: pass\ndef g(x: K) -> None: pass\n\na = f(B(), C())\ng(a) # E: Argument 1 to \"g\" has incompatible type \"J\"; expected \"K\"\nb = f(A(), C())\ng(b) # E: Argument 1 to \"g\" has incompatible type \"J\"; expected \"K\"\nc = f(A(), B())\ng(c)\n\n[case testPrecedenceOfFirstBaseAsInferenceResult]\nfrom typing import TypeVar\nfrom abc import abstractmethod, ABCMeta\nclass A: pass\nclass B(A, I, J): pass\nclass C(A, I, J): pass\n\ndef f(a: T, b: T) -> T: pass\n\nT = TypeVar('T')\na: A\ni: I\nj: J\n\na = f(B(), C())\n\nclass I(metaclass=ABCMeta): pass\nclass J(metaclass=ABCMeta): pass\n\n\n[builtins fixtures/tuple.pyi]\n\n\n-- Generic function inference with function arguments\n-- --------------------------------------------------\n\n\n[case testNonOverloadedMapInference]\nfrom typing import TypeVar, Callable, List\nt = TypeVar('t')\ns = TypeVar('s')\nclass A: pass\nb = bool()\ndef f(x: bool) -> A: pass\ndef mymap(f: Callable[[t], s], a: List[t]) -> List[s]: pass\n\nl = mymap(f, [b])\nif int():\n    l = [A()]\nlb = [b]\nif int():\n    l = lb # E: Incompatible types in assignment (expression has type \"list[bool]\", variable has type \"list[A]\")\n[builtins fixtures/for.pyi]\n\n[case testGenericFunctionWithTypeTypeAsCallable]\nfrom typing import Callable, Type, TypeVar\nT = TypeVar('T')\ndef f(x: Callable[..., T]) -> T: return x()\nclass A: pass\nx: Type[A]\ny = f(x)\nreveal_type(y)  # N: Revealed type is \"__main__.A\"\n\n-- Generic function inference with unions\n-- --------------------------------------\n\n\n[case testUnionInference]\nfrom typing import TypeVar, Union, List\nT = TypeVar('T')\nU = TypeVar('U')\ndef f(x: Union[T, int], y: T) -> T: pass\nf(1, 'a')() # E: \"str\" not callable\nf('a', 1)() # E: \"object\" not callable\nf('a', 'a')() # E: \"str\" not callable\nf(1, 1)() # E: \"int\" not callable\n\ndef g(x: Union[T, List[T]]) -> List[T]: pass\ndef h(x: List[str]) -> None: pass\ng('a')() # E: \"list[str]\" not callable\n\n# The next line is a case where there are multiple ways to satisfy a constraint\n# involving a Union. Either T = list[str] or T = str would turn out to be valid,\n# but mypy doesn't know how to branch on these two options (and potentially have\n# to backtrack later) and defaults to T = Never. The result is an\n# awkward error message. Either a better error message, or simply accepting the\n# call, would be preferable here.\ng(['a']) # E: Argument 1 to \"g\" has incompatible type \"list[str]\"; expected \"list[Never]\"\n\nh(g(['a']))\n\ndef i(x: Union[List[T], List[U]], y: List[T], z: List[U]) -> None: pass\na = [1]\nb = ['b']\ni(a, a, b)\ni(b, a, b)\ni(a, b, b) # E: Argument 1 to \"i\" has incompatible type \"list[int]\"; expected \"list[str]\"\n[builtins fixtures/list.pyi]\n\n[case testCallableListJoinInference]\nfrom typing import Any, Callable\n\ndef fun() -> None:\n    callbacks = [\n        callback1,\n        callback2,\n    ]\n\n    for c in callbacks:\n        call(c, 1234) # this must not fail\n\ndef callback1(i: int) -> int:\n    return i\ndef callback2(i: int) -> str:\n    return 'hello'\ndef call(c: Callable[[int], Any], i: int) -> None:\n    c(i)\n[builtins fixtures/list.pyi]\n[out]\n\n[case testCallableMeetAndJoin]\nfrom typing import Callable, Any, TypeVar\n\nclass A: ...\nclass B(A): ...\n\ndef f(c: Callable[[B], int]) -> None: ...\n\nc: Callable[[A], int]\nd: Callable[[B], int]\n\nlst = [c, d]\nreveal_type(lst) # N: Revealed type is \"builtins.list[def (__main__.B) -> builtins.int]\"\n\nT = TypeVar('T')\ndef meet_test(x: Callable[[T], int], y: Callable[[T], int]) -> T: ...\n\nCA = Callable[[A], A]\nCB = Callable[[B], B]\n\nca: Callable[[CA], int]\ncb: Callable[[CB], int]\nreveal_type(meet_test(ca, cb)) # N: Revealed type is \"def (__main__.A) -> __main__.B\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testUnionInferenceWithTypeVarValues]\nfrom typing import TypeVar, Union\nAnyStr = TypeVar('AnyStr', bytes, str)\ndef f(x: Union[AnyStr, int], *a: AnyStr) -> None: pass\nf('foo')\nf('foo', 'bar')\nf('foo', b'bar') # E: Value of type variable \"AnyStr\" of \"f\" cannot be \"Sequence[object]\"\nf(1)\nf(1, 'foo')\nf(1, 'foo', b'bar') # E: Value of type variable \"AnyStr\" of \"f\" cannot be \"Sequence[object]\"\n[builtins fixtures/primitives.pyi]\n\n\n[case testUnionTwoPassInference-skip]\nfrom typing import TypeVar, Union, List\nT = TypeVar('T')\nU = TypeVar('U')\ndef j(x: Union[List[T], List[U]], y: List[T]) -> List[U]: pass\n\na = [1]\nb = ['b']\n# We could infer: Since List[str] <: List[T], we must have T = str.\n# Then since List[int] <: Union[List[str], List[U]], and List[int] is\n# not a subtype of List[str], we must have U = int.\n# This is not currently implemented.\nj(a, b)\n[builtins fixtures/list.pyi]\n\n\n[case testUnionContext]\nfrom typing import TypeVar, Union, List\nT = TypeVar('T')\ndef f() -> List[T]: pass\nd1 = f() # type: Union[List[int], str]\nd2 = f() # type: Union[int, str] # E: Incompatible types in assignment (expression has type \"list[Never]\", variable has type \"int | str\")\ndef g(x: T) -> List[T]: pass\nd3 = g(1) # type: Union[List[int], List[str]]\n[builtins fixtures/list.pyi]\n\n\n[case testGenericFunctionSubtypingWithUnions]\nfrom typing import TypeVar, Union, List\nT = TypeVar('T')\nS = TypeVar('S')\ndef k1(x: int, y: List[T]) -> List[Union[T, int]]: pass\ndef k2(x: S, y: List[T]) -> List[Union[T, int]]: pass\na = k2\nif int():\n    a = k2\nif int():\n    a = k1 # E: Incompatible types in assignment (expression has type \"Callable[[int, list[T@k1]], list[T@k1 | int]]\", variable has type \"Callable[[S, list[T@k2]], list[T@k2 | int]]\")\nb = k1\nif int():\n    b = k1\nif int():\n    b = k2\n[builtins fixtures/list.pyi]\n\n[case testAmbiguousUnionContextAndMultipleInheritance]\nfrom typing import TypeVar, Union, Generic\n\n_T = TypeVar('_T')\n\nclass T(Generic[_T]): pass\nclass U(Generic[_T]): pass\nclass V(T[_T], U[_T]): pass\n\ndef wait_for(fut: Union[T[_T], U[_T]]) -> _T: ...\n\nreveal_type(wait_for(V[str]()))  # N: Revealed type is \"builtins.str\"\n\n[case testAmbiguousUnionContextAndMultipleInheritance2]\nfrom typing import TypeVar, Union, Generic\n\n_T = TypeVar('_T')\n_S = TypeVar('_S')\n\nclass T(Generic[_T, _S]): pass\nclass U(Generic[_T, _S]): pass\nclass V(T[_T, _S], U[_T, _S]): pass\n\ndef wait_for(fut: Union[T[_T, _S], U[_T, _S]]) -> T[_T, _S]: ...\n\nreveal_type(wait_for(V[int, str]()))  \\\n    # N: Revealed type is \"__main__.T[builtins.int, builtins.str]\"\n\n\n-- Literal expressions\n-- -------------------\n\n\n[case testDictLiteral]\nfrom typing import Dict\nclass A: pass\nclass B: pass\ndef d_ab() -> Dict[A, B]: return {}\ndef d_aa() -> Dict[A, A]: return {}\na: A\nb: B\nd = {a:b}\nif int():\n    d = d_ab()\nif int():\n    d = d_aa() # E: Incompatible types in assignment (expression has type \"dict[A, A]\", variable has type \"dict[A, B]\")\n[builtins fixtures/dict.pyi]\n\n[case testSetLiteral]\nfrom typing import Any, Set\na: int\nx: Any\ndef s_i() -> Set[int]: return set()\ndef s_s() -> Set[str]: return set()\ns = {a}\nif int():\n    s = {x}\nif int():\n    s = s_i()\nif int():\n    s = s_s() # E: Incompatible types in assignment (expression has type \"set[str]\", variable has type \"set[int]\")\n[builtins fixtures/set.pyi]\n\n[case testSetWithStarExpr]\ns = {1, 2, *(3, 4)}\nt = {1, 2, *s}\nreveal_type(s)  # N: Revealed type is \"builtins.set[builtins.int]\"\nreveal_type(t)  # N: Revealed type is \"builtins.set[builtins.int]\"\n[builtins fixtures/set.pyi]\n\n[case testListLiteralWithFunctionsErasesNames]\ndef f1(x: int) -> int: ...\ndef g1(y: int) -> int: ...\ndef h1(x: int) -> int: ...\n\nlist_1 = [f1, g1]\nlist_2 = [f1, h1]\nreveal_type(list_1)  # N: Revealed type is \"builtins.list[def (builtins.int) -> builtins.int]\"\nreveal_type(list_2)  # N: Revealed type is \"builtins.list[def (x: builtins.int) -> builtins.int]\"\n\ndef f2(x: int, z: str) -> int: ...\ndef g2(y: int, z: str) -> int: ...\ndef h2(x: int, z: str) -> int: ...\n\nlist_3 = [f2, g2]\nlist_4 = [f2, h2]\nreveal_type(list_3)  # N: Revealed type is \"builtins.list[def (builtins.int, z: builtins.str) -> builtins.int]\"\nreveal_type(list_4)  # N: Revealed type is \"builtins.list[def (x: builtins.int, z: builtins.str) -> builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testListLiteralWithSimilarFunctionsErasesName]\nfrom typing import Union\n\nclass A: ...\nclass B(A): ...\nclass C: ...\nclass D: ...\n\ndef f(x: Union[A, C], y: B) -> A: ...\ndef g(z: Union[B, D], y: A) -> B: ...\ndef h(x: Union[B, D], y: A) -> B: ...\n\nlist_1 = [f, g]\nlist_2 = [f, h]\nreveal_type(list_1)  # N: Revealed type is \"builtins.list[def (__main__.B, y: __main__.B) -> __main__.A]\"\nreveal_type(list_2)  # N: Revealed type is \"builtins.list[def (x: __main__.B, y: __main__.B) -> __main__.A]\"\n[builtins fixtures/list.pyi]\n\n[case testListLiteralWithNameOnlyArgsDoesNotEraseNames]\ndef f(*, x: int) -> int: ...\ndef g(*, y: int) -> int: ...\ndef h(*, x: int) -> int: ...\n\nlist_1 = [f, g]  # E: List item 0 has incompatible type \"def f(*, x: int) -> int\"; expected \"def g(*, y: int) -> int\"\nlist_2 = [f, h]\n[builtins fixtures/list.pyi]\n\n\n-- For statements\n-- --------------\n\n\n[case testInferenceOfFor1]\na: A\nb: B\n\nclass A: pass\nclass B: pass\n\nfor x in [A()]:\n    b = x # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    a = x\n\nfor y in []: # E: Need type annotation for \"y\"\n    a = y\n    reveal_type(y)  # N: Revealed type is \"Any\"\n[builtins fixtures/for.pyi]\n\n[case testInferenceOfFor2]\nclass A: pass\nclass B: pass\nclass C: pass\n\na: A\nb: B\nc: C\nfor x, (y, z) in [(A(), (B(), C()))]:\n    b = x # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    c = y # E: Incompatible types in assignment (expression has type \"B\", variable has type \"C\")\n    a = z # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A\")\n    a = x\n    b = y\n    c = z\nfor xx, yy, zz in [(A(), B())]: # E: Need more than 2 values to unpack (3 expected)\n    pass\nfor xx, (yy, zz) in [(A(), B())]: # E: \"B\" object is not iterable\n    pass\nfor xxx, yyy in [(1, 2)]:\n    pass\n[builtins fixtures/for.pyi]\n\n[case testInferenceOfFor3]\nclass A: pass\nclass B: pass\n\na: A\nb: B\n\nfor x, y in [[A()]]:\n    b = x # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    b = y # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n    a = x\n    a = y\n\nfor e, f in [[]]:  # E: Need type annotation for \"e\" \\\n                   # E: Need type annotation for \"f\"\n    reveal_type(e)  # N: Revealed type is \"Any\"\n    reveal_type(f)  # N: Revealed type is \"Any\"\n\n[builtins fixtures/for.pyi]\n\n[case testForStatementInferenceWithVoid]\ndef f() -> None: pass\n\nfor x in f(): # E: \"f\" does not return a value (it only ever returns None) \\\n              # E: \"None\" has no attribute \"__iter__\" (not iterable)\n    pass\n[builtins fixtures/for.pyi]\n\n[case testReusingInferredForIndex]\nimport typing\n\nclass A: pass\nclass B: pass\n\nfor a in [A()]: pass\na = A()\nif int():\n    a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    for a in []: pass\n    a = A()\n    a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[builtins fixtures/for.pyi]\n\n[case testReusingInferredForIndex2]\n# flags: --allow-redefinition\n\ndef f() -> None:\n    for a in [A()]: pass\n    a = A()\n    a\n    if int():\n        a = B() \\\n            # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    for a in []: pass # E: Need type annotation for \"a\"\n    a = A()\n    if int():\n        a = B() \\\n            # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nclass A: pass\nclass B: pass\n[builtins fixtures/for.pyi]\n[out]\n\n[case testReusingInferredForIndex3]\n# flags: --disallow-redefinition\ndef f() -> None:\n    for a in [A()]: pass\n    a = A()\n    a\n    if int():\n        a = B() \\\n            # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    for a in []: pass\n    a = A()\n    if int():\n        a = B() \\\n            # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nclass A: pass\nclass B: pass\n[builtins fixtures/for.pyi]\n[out]\n\n[case testForStatementIndexNarrowing]\nfrom typing import TypedDict\n\nclass X(TypedDict):\n    hourly: int\n    daily: int\n\nx: X\nfor a in (\"hourly\", \"daily\"):\n    reveal_type(a)  # N: Revealed type is \"Literal['hourly']? | Literal['daily']?\"\n    reveal_type(x[a])  # N: Revealed type is \"builtins.int\"\n    reveal_type(a.upper())  # N: Revealed type is \"builtins.str\"\n    c = a\n    reveal_type(c)  # N: Revealed type is \"builtins.str\"\n    a = \"monthly\"\n    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    a = \"yearly\"\n    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    a = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    d = a\n    reveal_type(d)  # N: Revealed type is \"builtins.str\"\n\nb: str\nfor b in (\"hourly\", \"daily\"):\n    reveal_type(b)  # N: Revealed type is \"builtins.str\"\n    reveal_type(b.upper())  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/for.pyi]\n[typing fixtures/typing-full.pyi]\n\n\n-- Regression tests\n-- ----------------\n\n\n[case testMultipleAssignmentWithPartialDefinition]\na: A\nif int():\n    x, a = a, a\n    if int():\n        x = a\n    a = x\n    if int():\n        x = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n    a = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nclass A: pass\n\n[case testMultipleAssignmentWithPartialDefinition2]\na: A\nif int():\n    a, x = [a, a]\n    if int():\n        x = a\n    a = x\n    if int():\n        x = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\n    a = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nclass A: pass\n[builtins fixtures/for.pyi]\n\n[case testMultipleAssignmentWithPartialDefinition3]\nfrom typing import Any, cast\na: A\nif int():\n    x, a = cast(Any, a)\n    if int():\n        x = a\n    a = x\n    if int():\n        x = object()\n    a = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nclass A: pass\n\n[case testInferGlobalDefinedInBlock]\nclass A: pass\nclass B: pass\n\nif int():\n    a = A()\n    if int():\n        a = A()\n    if int():\n        a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\n[case testAssigningAnyStrToNone]\nfrom typing import Tuple, TypeVar\nAnyStr = TypeVar('AnyStr', str, bytes)\n\ndef f(x: AnyStr) -> Tuple[AnyStr]: pass\nx = None\n(x,) = f('')\nreveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n\n-- Inferring attribute types\n-- -------------------------\n\n\n[case testInferAttributeType]\nimport typing\nclass A:\n    a = B()\nclass B: pass\n\nA().a = B()\nA().a = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n[case testInferAttributeTypeAndAssignInInit]\nimport typing\nclass A:\n    a = B()\n    def __init__(self) -> None:\n        self.a = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n        self.a = B()\nclass B: pass\n[out]\n\n[case testInferAttributeInInit]\nimport typing\nclass B: pass\nclass A:\n    def __init__(self) -> None:\n        self.a = A()\n        self.b = B()\na = A()\na.a = A()\na.b = B()\na.a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\na.b = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\n\n[case testInferAttributeInInitUsingChainedAssignment]\nimport typing\nclass B: pass\nclass A:\n    def __init__(self) -> None:\n        self.a = self.b = A()\na = A()\na.a = A()\na.b = A()\na.a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\na.b = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\n\n-- Lambdas\n-- -------\n\n\n[case testInferLambdaType]\nfrom typing import List, Callable\nli = [1]\nl = lambda: li\nf1 = l # type: Callable[[], List[int]]\nf2 = l # type: Callable[[], List[str]] # E: Incompatible types in assignment (expression has type \"Callable[[], list[int]]\", variable has type \"Callable[[], list[str]]\")\n[builtins fixtures/list.pyi]\n\n[case testInferLambdaType2]\nfrom typing import List, Callable\nl = lambda: [B()]\nf1 = l # type: Callable[[], List[B]]\nf2 = l # type: Callable[[], List[A]] # E: Incompatible types in assignment (expression has type \"Callable[[], list[B]]\", variable has type \"Callable[[], list[A]]\")\n\nclass A: pass\nclass B: pass\n[builtins fixtures/list.pyi]\n\n[case testUninferableLambda]\nfrom typing import TypeVar, Callable\nX = TypeVar('X')\ndef f(x: Callable[[X], X]) -> X: pass\ny = f(lambda x: x)  # E: Need type annotation for \"y\"\n\n[case testUninferableLambdaWithTypeError]\nfrom typing import TypeVar, Callable\nX = TypeVar('X')\ndef f(x: Callable[[X], X], y: str) -> X: pass\ny = f(lambda x: x, 1) # E: Need type annotation for \"y\" \\\n                      # E: Argument 2 to \"f\" has incompatible type \"int\"; expected \"str\"\n\n[case testInferLambdaNone]\n# flags: --no-strict-optional\nfrom typing import Callable\ndef f(x: Callable[[], None]) -> None: pass\ndef g(x: Callable[[], int]) -> None: pass\na = lambda: None\nf(a)\ng(a)\nb = lambda: None  # type: Callable[[], None]\nf(b)\ng(b)\n\n[case testLambdaDefaultContext]\nfrom typing import Callable\ndef f(a: Callable[..., None] = lambda *a, **k: None):\n    pass\n\ndef g(a: Callable[..., None] = lambda *a, **k: 1):  # E: Incompatible default for parameter \"a\" (default has type \"def (*a: Any, **k: Any) -> int\", parameter has type \"Callable[..., None]\")\n    pass\n[builtins fixtures/dict.pyi]\n\n[case testLambdaVarargContext]\n# Should not crash\nfrom typing import Callable\ndef f(a: Callable[[int, int, int], int] = lambda *a, **k: 1):\n    pass\n[builtins fixtures/dict.pyi]\n\n[case testLambdaDeferredSpecialCase]\nfrom typing import Callable\n\nclass A:\n    def f(self) -> None:\n        h(lambda: self.x)\n\n    def g(self) -> None:\n        self.x = 1\n\ndef h(x: Callable[[], int]) -> None:\n    pass\n\n[case testLambdaJoinWithDynamicConstructor]\nfrom typing import Any, Union\n\nclass Wrapper:\n    def __init__(self, x: Any) -> None: ...\n\ndef f(cond: bool) -> Any:\n    f = Wrapper if cond else lambda x: x\n    reveal_type(f)  # N: Revealed type is \"(def (x: Any) -> __main__.Wrapper) | (def (x: Any) -> Any)\"\n    return f(3)\n\ndef g(cond: bool) -> Any:\n    f = lambda x: x if cond else Wrapper\n    reveal_type(f)  # N: Revealed type is \"def (x: Any) -> Any | (def (x: Any) -> __main__.Wrapper)\"\n    return f(3)\n\ndef h(cond: bool) -> Any:\n    f = (lambda x: x) if cond else Wrapper\n    reveal_type(f)  # N: Revealed type is \"(def (x: Any) -> Any) | (def (x: Any) -> __main__.Wrapper)\"\n    return f(3)\n\n-- Boolean operators\n-- -----------------\n\n[case testOrOperationWithGenericOperands]\nfrom typing import List\na: List[A]\no: List[object]\na2 = a or []\nif int():\n    a = a2\n    a2 = o # E: Incompatible types in assignment (expression has type \"list[object]\", variable has type \"list[A]\")\nclass A: pass\n[builtins fixtures/list.pyi]\n\n\n-- Accessing variable before its type has been inferred\n-- ----------------------------------------------------\n\n\n[case testAccessGlobalVarBeforeItsTypeIsAvailable]\nimport typing\nx.y  # E: Cannot determine type of \"x\"  # E: Name \"x\" is used before definition\nx = object()\nx.y  # E: \"object\" has no attribute \"y\"\n\n[case testAccessDataAttributeBeforeItsTypeIsAvailable]\n\na: A\na.x.y  # E: Cannot determine type of \"x\"\nclass A:\n   def __init__(self) -> None:\n       self.x = object()\na.x.y  # E: \"object\" has no attribute \"y\"\n\n\n-- Ducktype declarations\n-- ---------------------\n\n\n[case testListWithDucktypeCompatibility]\nfrom typing import List, _promote\nclass A: pass\n@_promote(A)\nclass B: pass\na: List[A]\nx1 = [A(), B()]\nx2 = [B(), A()]\nx3 = [B(), B()]\nif int():\n    a = x1\nif int():\n    a = x2\nif int():\n    a = x3 \\\n     # E: Incompatible types in assignment (expression has type \"list[B]\", variable has type \"list[A]\") \\\n     # N: \"list\" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \\\n     # N: Consider using \"Sequence\" instead, which is covariant\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testListWithDucktypeCompatibilityAndTransitivity]\nfrom typing import List, _promote\nclass A: pass\n@_promote(A)\nclass B: pass\n@_promote(B)\nclass C: pass\na: List[A]\nx1 = [A(), C()]\nx2 = [C(), A()]\nx3 = [B(), C()]\nif int():\n    a = x1\nif int():\n    a = x2\nif int():\n    a = x3 \\\n     # E: Incompatible types in assignment (expression has type \"list[B]\", variable has type \"list[A]\") \\\n     # N: \"list\" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \\\n     # N: Consider using \"Sequence\" instead, which is covariant\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-medium.pyi]\n\n\n-- Inferring type of variable when initialized to an empty collection\n-- ------------------------------------------------------------------\n\n\n[case testInferListInitializedToEmpty]\na = []\na.append(1)\na.append('')  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyUsingUpdate]\na = []\na.extend([''])\na.append(0)  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyAndNotAnnotated]\na = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyAndReadBeforeAppend]\na = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\nif a: pass\na.xyz  # E: \"list[Any]\" has no attribute \"xyz\"\na.append('')\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyAndIncompleteTypeInAppend]\na = [] # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\na.append([])\na()  # E: \"list[Any]\" not callable\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyAndMultipleAssignment]\na, b = [], []\na.append(1)\nb.append('')\na() # E: \"list[int]\" not callable\nb() # E: \"list[str]\" not callable\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyInFunction]\ndef f() -> None:\n   a = []\n   a.append(1)\n   a.append('')  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyAndNotAnnotatedInFunction]\ndef f() -> None:\n    a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n\ndef g() -> None: pass\n\na = []\na.append(1)\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyAndReadBeforeAppendInFunction]\ndef f() -> None:\n    a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n    if a: pass\n    a.xyz  # E: \"list[Any]\" has no attribute \"xyz\"\n    a.append('')\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyInClassBody]\nclass A:\n   a = []\n   a.append(1)\n   a.append('')  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyAndNotAnnotatedInClassBody]\nclass A:\n    a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n\nclass B:\n    a = []\n    a.append(1)\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyInMethod]\nclass A:\n    def f(self) -> None:\n        a = []\n        a.append(1)\n        a.append('')  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyAndNotAnnotatedInMethod]\nclass A:\n    def f(self) -> None:\n        a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyInMethodViaAttribute]\nclass A:\n    def f(self) -> None:\n        # Attributes aren't supported right now.\n        self.a = []\n        self.a.append(1)\n        self.a.append('')  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyInClassBodyAndOverridden]\nfrom typing import List\n\nclass A:\n    def __init__(self) -> None:\n        self.x = [] # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n\nclass B(A):\n    @property\n    def x(self) -> List[int]:  # E: Cannot override writeable attribute with read-only property\n        return [123]\n[builtins fixtures/list.pyi]\n\n[case testInferSetInitializedToEmpty]\na = set()\na.add(1)\na.add('')  # E: Argument 1 to \"add\" of \"set\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/set.pyi]\n\n[case testInferSetInitializedToEmptyUsingDiscard]\na = set()\na.discard('')\na.add(0)  # E: Argument 1 to \"add\" of \"set\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/set.pyi]\n\n[case testInferSetInitializedToEmptyUsingUpdate]\na = set()\na.update({0})\na.add('')  # E: Argument 1 to \"add\" of \"set\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/set.pyi]\n\n[case testInferDictInitializedToEmpty]\na = {}\na[1] = ''\na() # E: \"dict[int, str]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testInferDictInitializedToEmptyUsingUpdate]\na = {}\na.update({'': 42})\na() # E: \"dict[str, int]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testInferDictInitializedToEmptyUsingUpdateError]\na = {}  # E: Need type annotation for \"a\" (hint: \"a: dict[<type>, <type>] = ...\")\na.update([1, 2])  # E: Argument 1 to \"update\" of \"dict\" has incompatible type \"list[int]\"; expected \"SupportsKeysAndGetItem[Any, Any]\" \\\n                  # N: \"list\" is missing following \"SupportsKeysAndGetItem\" protocol member: \\\n                  # N:     keys\na()  # E: \"dict[Any, Any]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testInferDictInitializedToEmptyAndIncompleteTypeInUpdate]\na = {} # E: Need type annotation for \"a\" (hint: \"a: dict[<type>, <type>] = ...\")\na[1] = {}\nb = {} # E: Need type annotation for \"b\" (hint: \"b: dict[<type>, <type>] = ...\")\nb[{}] = 1\n[builtins fixtures/dict.pyi]\n\n[case testInferDictInitializedToEmptyAndUpdatedFromMethod]\n# flags: --no-local-partial-types\nmap = {}\ndef add() -> None:\n    map[1] = 2\n[builtins fixtures/dict.pyi]\n\n[case testInferDictInitializedToEmptyAndUpdatedFromMethodUnannotated]\n# flags: --no-local-partial-types\nmap = {}\ndef add():\n    map[1] = 2\n[builtins fixtures/dict.pyi]\n\n[case testSpecialCaseEmptyListInitialization]\ndef f(blocks: Any): # E: Name \"Any\" is not defined \\\n                    # N: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import Any\")\n    to_process = []\n    to_process = list(blocks)\n[builtins fixtures/list.pyi]\n\n[case testSpecialCaseEmptyListInitialization2]\ndef f(blocks: object):\n    to_process = []\n    to_process = list(blocks) # E: No overload variant of \"list\" matches argument type \"object\" \\\n                              # N: Possible overload variants: \\\n                              # N:     def [T] list() -> list[T] \\\n                              # N:     def [T] list(x: Iterable[T]) -> list[T]\n[builtins fixtures/list.pyi]\n\n[case testInferListInitializedToEmptyAndAssigned]\na = []\nif bool():\n    a = [1]\nreveal_type(a) # N: Revealed type is \"builtins.list[builtins.int]\"\n\ndef f():\n    return [1]\nb = []\nif bool():\n    b = f()\nreveal_type(b) # N: Revealed type is \"builtins.list[Any]\"\n\nd = {}\nif bool():\n    d = {1: 'x'}\nreveal_type(d) # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n\ndd = {} # E: Need type annotation for \"dd\" (hint: \"dd: dict[<type>, <type>] = ...\")\nif bool():\n    dd = [1] # E: Incompatible types in assignment (expression has type \"list[int]\", variable has type \"dict[Any, Any]\")\nreveal_type(dd) # N: Revealed type is \"builtins.dict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testInferOrderedDictInitializedToEmpty]\nfrom collections import OrderedDict\n\no = OrderedDict()\no[1] = 'x'\nreveal_type(o) # N: Revealed type is \"collections.OrderedDict[builtins.int, builtins.str]\"\n\nd = {1: 'x'}\noo = OrderedDict()\noo.update(d)\nreveal_type(oo) # N: Revealed type is \"collections.OrderedDict[builtins.int, builtins.str]\"\n[builtins fixtures/dict.pyi]\n\n[case testEmptyCollectionAssignedToVariableTwiceIncremental]\nx = [] # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\ny = x\nx = []\nreveal_type(x) # N: Revealed type is \"builtins.list[Any]\"\nd = {} # E: Need type annotation for \"d\" (hint: \"d: dict[<type>, <type>] = ...\")\nz = d\nd = {}\nreveal_type(d) # N: Revealed type is \"builtins.dict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n[out2]\nmain:1: error: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\nmain:4: note: Revealed type is \"builtins.list[Any]\"\nmain:5: error: Need type annotation for \"d\" (hint: \"d: dict[<type>, <type>] = ...\")\nmain:8: note: Revealed type is \"builtins.dict[Any, Any]\"\n\n[case testEmptyCollectionAssignedToVariableTwiceNoReadIncremental]\nx = [] # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\nx = []\n[builtins fixtures/list.pyi]\n[out2]\nmain:1: error: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n\n[case testInferAttributeInitializedToEmptyAndAssigned]\nclass C:\n    def __init__(self) -> None:\n        self.a = []\n        if bool():\n            self.a = [1]\nreveal_type(C().a)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testInferAttributeInitializedToEmptyAndAppended]\nclass C:\n    def __init__(self) -> None:\n        self.a = []\n        if bool():\n            self.a.append(1)\nreveal_type(C().a)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testInferAttributeInitializedToEmptyAndAssignedItem]\nclass C:\n    def __init__(self) -> None:\n        self.a = {}\n        if bool():\n            self.a[0] = 'yes'\nreveal_type(C().a)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n[builtins fixtures/dict.pyi]\n\n[case testInferAttributeInitializedToNoneAndAssigned]\nclass C:\n    def __init__(self) -> None:\n        self.a = None\n        if bool():\n            self.a = 1\nreveal_type(C().a)  # N: Revealed type is \"builtins.int | None\"\n\n[case testInferAttributeInitializedToEmptyNonSelf]\nclass C:\n    def __init__(self) -> None:\n        self.a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n        if bool():\n            a = self\n            a.a = [1]\n            a.a.append(1)\nreveal_type(C().a)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testInferAttributeInitializedToEmptyAndAssignedOtherMethod]\nclass C:\n    def __init__(self) -> None:\n        self.a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n    def meth(self) -> None:\n        self.a = [1]\nreveal_type(C().a)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testInferAttributeInitializedToEmptyAndAppendedOtherMethod]\nclass C:\n    def __init__(self) -> None:\n        self.a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n    def meth(self) -> None:\n        self.a.append(1)\nreveal_type(C().a)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testInferAttributeInitializedToEmptyAndAssignedItemOtherMethod]\nclass C:\n    def __init__(self) -> None:\n        self.a = {}  # E: Need type annotation for \"a\" (hint: \"a: dict[<type>, <type>] = ...\")\n    def meth(self) -> None:\n        self.a[0] = 'yes'\nreveal_type(C().a)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testInferAttributeInitializedToNoneAndAssignedOtherMethod]\nclass C:\n    def __init__(self) -> None:\n        self.a = None\n    def meth(self) -> None:\n        self.a = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"None\")\nreveal_type(C().a)  # N: Revealed type is \"None\"\n\n[case testInferAttributeInitializedToEmptyAndAssignedClassBody]\nclass C:\n    a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n    def __init__(self) -> None:\n        self.a = [1]\nreveal_type(C().a)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testInferAttributeInitializedToEmptyAndAppendedClassBody]\nclass C:\n    a = []  # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n    def __init__(self) -> None:\n        self.a.append(1)\nreveal_type(C().a)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testInferAttributeInitializedToEmptyAndAssignedItemClassBody]\nclass C:\n    a = {}  # E: Need type annotation for \"a\" (hint: \"a: dict[<type>, <type>] = ...\")\n    def __init__(self) -> None:\n        self.a[0] = 'yes'\nreveal_type(C().a)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testInferAttributeInitializedToNoneAndAssignedClassBody]\n# flags: --no-local-partial-types\nclass C:\n    a = None\n    def __init__(self) -> None:\n        self.a = 1\nreveal_type(C().a)  # N: Revealed type is \"builtins.int | None\"\n\n[case testInferListTypeFromEmptyListAndAny]\ndef f():\n    return []\n\ndef g() -> None:\n    x = []\n    if bool():\n        x = f()\n    reveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\n\n    y = []\n    y.extend(f())\n    reveal_type(y)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testInferFromEmptyDictWhenUsingIn]\nd = {}\nif 'x' in d:\n    d['x'] = 1\nreveal_type(d)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n\ndd = {}\nif 'x' not in dd:\n    dd['x'] = 1\nreveal_type(dd)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n[builtins fixtures/dict.pyi]\n\n[case testInferFromEmptyDictWhenUsingInSpecialCase]\n# flags: --no-strict-optional\nd = None\nif 'x' in d:  # E: \"None\" has no attribute \"__iter__\" (not iterable)\n    pass\nreveal_type(d)  # N: Revealed type is \"None\"\n[builtins fixtures/dict.pyi]\n\n[case testNoWrongUnreachableWarningWithNoStrictOptionalAndFinalInstance]\n# flags: --no-strict-optional --warn-unreachable\nfrom typing import final, Optional\n\n@final\nclass C: ...\n\nx: Optional[C]\nif not x:\n    x = C()\n[builtins fixtures/dict.pyi]\n\n[case testNoWrongUnreachableWarningWithNoStrictOptionalAndEnumLiteral]\n# flags: --no-strict-optional --warn-unreachable\nfrom enum import Enum\nfrom typing import Literal, Optional\n\nclass E(Enum):\n    a = 1\n\nx: Optional[Literal[E.a]]\nif not x:\n    x = E.a\n[builtins fixtures/dict.pyi]\n\n[case testInferFromEmptyListWhenUsingInWithStrictEquality]\n# flags: --strict-equality\ndef f() -> None:\n    a = []\n    if 1 in a:  # TODO: This should be an error\n        a.append('x')\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testInferListTypeFromInplaceAdd]\na = []\na += [1]\nreveal_type(a)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testInferSetTypeFromInplaceOr]\n# flags: --no-strict-optional\na = set()\na |= {'x'}\nreveal_type(a)  # N: Revealed type is \"builtins.set[builtins.str]\"\n[builtins fixtures/set.pyi]\n\n\n-- Inferring types of variables first initialized to None (partial types)\n-- ----------------------------------------------------------------------\n\n\n[case testLocalVariablePartiallyInitializedToNone]\ndef f() -> None:\n    if object():\n        x = None\n    else:\n        x = 1\n    x() # E: \"int\" not callable \\\n        # E: \"None\" not callable\n[out]\n\n[case testLocalVariablePartiallyTwiceInitializedToNone]\ndef f() -> None:\n    if object():\n        x = None\n    elif object():\n        x = None\n    else:\n        x = 1\n    x() # E: \"int\" not callable \\\n        # E: \"None\" not callable\n[out]\n\n[case testLvarInitializedToNoneWithoutType]\nimport typing\ndef f() -> None:\n    a = None\n    a.x() # E: \"None\" has no attribute \"x\"\n[out]\n\n[case testGvarPartiallyInitializedToNone]\nx = None\nif object():\n    x = 1\nx() # E: \"int\" not callable \\\n    # E: \"None\" not callable\n\n[case testPartiallyInitializedToNoneAndThenToPartialList]\nx = None\nif object():\n    # Promote from partial None to partial list.\n    x = []\n    x.append(1)\nx.append('') # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testPartiallyInitializedToNoneAndThenReadPartialList]\nx = None\nif object():\n    # Promote from partial None to partial list.\n    x = []  # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n    x\n[builtins fixtures/list.pyi]\n\n[case testPartiallyInitializedToNoneAndPartialListAndLeftPartial]\ndef f() -> None:\n    x = None\n    if object():\n        # Promote from partial None to partial list.\n        x = []  # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n[builtins fixtures/list.pyi]\n[out]\n\n[case testPartiallyInitializedToNoneAndThenToIncompleteType-skip]\n# TODO(ddfisher): fix partial type bug and re-enable\nfrom typing import TypeVar,  Dict\nT = TypeVar('T')\ndef f(*x: T) -> Dict[int, T]: pass\nx = None  # E: Need type annotation for \"x\"\nif object():\n    x = f()\n[builtins fixtures/dict.pyi]\n\n[case testPartiallyInitializedVariableDoesNotEscapeScope1]\ndef f() -> None:\n    x = None\n    reveal_type(x)  # N: Revealed type is \"None\"\nx = 1\n[out]\n\n[case testPartiallyInitializedVariableDoesNotEscapeScope2]\n# flags: --no-local-partial-types\nx = None\ndef f() -> None:\n    x = None\n    x = 1\nx()  # E: \"None\" not callable\n\n[case testAttributePartiallyInitializedToNone]\nclass A:\n    def f(self) -> None:\n        self.x = None\n        self.x = 1\n        self.x() # E: \"int\" not callable\n[out]\n\n[case testAttributePartiallyInitializedToNoneWithMissingAnnotation]\nclass A:\n    def f(self) -> None:\n        self.x = None\n\n    def g(self) -> None:\n        self.x = 1\n        self.x()\n[out]\nmain:6: error: Incompatible types in assignment (expression has type \"int\", variable has type \"None\")\nmain:7: error: \"None\" not callable\n\n[case testGlobalInitializedToNoneSetFromFunction]\n# flags: --no-local-partial-types\na = None\ndef f() -> None:\n    global a\n    a = 42\n    reveal_type(a)  # N: Revealed type is \"builtins.int\"\nreveal_type(a)  # N: Revealed type is \"builtins.int | None\"\n\nb = None\ndef unchecked():\n    global b\n    b = 42\nreveal_type(b)  # N: Revealed type is \"Any | None\"\n\n[case testGlobalInitializedToNoneSetFromFunctionLocalPartialTypes]\n# flags: --local-partial-types\na = None\ndef f() -> None:\n    global a\n    a = 42\n    reveal_type(a)  # N: Revealed type is \"builtins.int\"\nreveal_type(a)  # N: Revealed type is \"builtins.int | None\"\n\nb = None\ndef unchecked():\n    global b\n    b = 42\nreveal_type(b)  # N: Revealed type is \"Any | None\"\n\n[case testGlobalInitializedToNoneSetFromMethod]\n# flags: --no-local-partial-types\na = None\nclass C:\n    def m(self) -> None:\n        global a\n        a = 42\nreveal_type(a)  # N: Revealed type is \"builtins.int | None\"\n\nb = None\nclass CC:\n    def unchecked(self):\n        global b\n        b = 42\nreveal_type(b)  # N: Revealed type is \"Any | None\"\n\n[case testGlobalInitializedToNoneSetFromMethodLocalPartialTypes]\n# flags: --local-partial-types\na = None\nclass C:\n    def m(self) -> None:\n        global a\n        a = 42\nreveal_type(a)  # N: Revealed type is \"builtins.int | None\"\n\nb = None\nclass CC:\n    def unchecked(self):\n        global b\n        b = 42\nreveal_type(b)  # N: Revealed type is \"Any | None\"\n\n[case testPartialTypeErrorSpecialCase1]\n# flags: --no-local-partial-types\n# This used to crash.\nclass A:\n    x = None\n    def f(self) -> None:\n        for a in self.x:  # E: \"None\" has no attribute \"__iter__\" (not iterable)\n            pass\n[builtins fixtures/for.pyi]\n\n[case testPartialTypeErrorSpecialCase2]\n# This used to crash.\nclass A:\n    x = []  # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n    def f(self) -> None:\n        for a in self.x:\n            pass\n[builtins fixtures/for.pyi]\n\n[case testPartialTypeErrorSpecialCase3]\n# flags: --no-local-partial-types\nclass A:\n    x = None\n    def f(self) -> None:\n        for a in A.x:  # E: \"None\" has no attribute \"__iter__\" (not iterable)\n            pass\n[builtins fixtures/for.pyi]\n\n[case testPartialTypeErrorSpecialCase4]\n# This used to crash.\narr = []\narr.append(arr.append(1))\n[builtins fixtures/list.pyi]\n[out]\nmain:3: error: \"append\" of \"list\" does not return a value (it only ever returns None)\nmain:3: error: Argument 1 to \"append\" of \"list\" has incompatible type \"None\"; expected \"int\"\n\n-- Multipass\n-- ---------\n\n\n[case testMultipassAndAccessVariableBeforeDefinition]\ndef f() -> None:\n    y = x\n    y() # E: \"int\" not callable\nx = 1\n[out]\n\n[case testMultipassAndAccessInstanceVariableBeforeDefinition]\nclass A:\n    def f(self) -> None:\n        y = self.x\n        y() # E: \"int\" not callable\n\n    def g(self) -> None:\n        self.x = 1\n[out]\n\n[case testMultipassAndTopLevelVariable]\ny = x # E: Cannot determine type of \"x\"  # E: Name \"x\" is used before definition\ny()\nx = 1+int()\n[out]\n\n[case testMultipassAndDecoratedMethod]\nfrom typing import Callable, TypeVar\n\nT = TypeVar('T')\n\nclass A:\n    def f(self) -> None:\n        self.g() # E: Too few arguments for \"g\" of \"A\"\n        self.g(1)\n    @dec\n    def g(self, x: str) -> None: pass\n\ndef dec(f: Callable[[A, str], T]) -> Callable[[A, int], T]: pass\n[out]\n\n[case testMultipassAndDefineAttributeBasedOnNotReadyAttribute]\nclass A:\n    def f(self) -> None:\n        self.y = self.x\n\n    def g(self) -> None:\n        self.x = 1\n\n    def h(self) -> None:\n        self.y() # E: \"int\" not callable\n[out]\n\n[case testMultipassAndDefineAttributeBasedOnNotReadyAttribute2]\nclass A:\n    def f(self) -> None:\n        self.y = self.x\n        self.z = self.y\n        self.z() # E\n        self.y() # E\n\n    def g(self) -> None:\n        self.x = 1\n\n    def h(self) -> None:\n        self.y() # E\n[out]\nmain:5: error: \"int\" not callable\nmain:6: error: \"int\" not callable\nmain:12: error: \"int\" not callable\n\n[case testMultipassAndPartialTypes]\ndef f() -> None:\n    x = []\n    y\n    x.append(1)\n    x.append('') # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\n    x.append(y) # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\ny = ''\n[builtins fixtures/list.pyi]\n[out]\n\n[case testMultipassAndPartialTypes2]\ns = ''\nn = 0\ndef f() -> None:\n    global s, n\n    x = []\n    x.append(y)\n    s = x[0]\n    n = x[0] # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    x.append(1) # E: Argument 1 to \"append\" of \"list\" has incompatible type \"int\"; expected \"str\"\ny = ''\n[builtins fixtures/list.pyi]\n[out]\n\n[case testMultipassAndPartialTypes3]\nfrom typing import Dict\ndef g(d: Dict[str, int]) -> None: pass\ndef f() -> None:\n    x = {}\n    x[1] = y\n    g(x) # E: Argument 1 to \"g\" has incompatible type \"dict[int, str]\"; expected \"dict[str, int]\"\n    x[1] = 1 # E: Incompatible types in assignment (expression has type \"int\", target has type \"str\")\n    x[1] = ''\ny = ''\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testMultipassAndPartialTypes4]\nfrom typing import Dict\ndef g(d: Dict[str, int]) -> None: pass\ndef f() -> None:\n    x = {}\n    y\n    x[1] = 1\n    g(x) # E: Argument 1 to \"g\" has incompatible type \"dict[int, int]\"; expected \"dict[str, int]\"\ny = ''\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testMultipassAndCircularDependency]\nclass A:\n    def f(self) -> None:\n        self.x = self.y # E: Cannot determine type of \"y\"\n\n    def g(self) -> None:\n        self.y = self.x\n[out]\n\n[case testMultipassAndPartialTypesSpecialCase1]\ndef f() -> None:\n    y = o\n    x = []\n    x.append(y)\n    x() # E: \"list[int]\" not callable\no = 1\n[builtins fixtures/list.pyi]\n[out]\n\n[case testMultipassAndPartialTypesSpecialCase2]\ndef f() -> None:\n    y = o\n    x = {}\n    x[''] = y\n    x() # E: \"dict[str, int]\" not callable\no = 1\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testMultipassAndPartialTypesSpecialCase3]\ndef f() -> None:\n    x = {} # E: Need type annotation for \"x\" (hint: \"x: dict[<type>, <type>] = ...\")\n    y = o\n    z = {} # E: Need type annotation for \"z\" (hint: \"z: dict[<type>, <type>] = ...\")\no = 1\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testMultipassAndPartialTypesSpecialCase4]\ndef f() -> None:\n    y = o\n    x = None\n    x = y\n    x() # E: \"int\" not callable\no = 1\n[out]\n\n[case testMultipassAndPartialTypesSpecialCase5]\ndef f() -> None:\n    x = None\n    y = o\n    x = y\n    x() # E: \"int\" not callable\no = 1\n[out]\n\n[case testMultipassAndClassAttribute]\nclass S:\n    def foo(self) -> int:\n        return R.X\n\nclass R:\n    X = 2\n\n[case testMultipassAndMultipleFiles]\nimport m\ndef f() -> None:\n    x()\nx = 0\n[file m.py]\ndef g() -> None:\n    y()\ny = 0\n[out]\ntmp/m.py:2: error: \"int\" not callable\nmain:3: error: \"int\" not callable\n\n[case testForwardReferenceToDecoratedClassMethod]\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\ndef dec() -> Callable[[T], T]: pass\n\nA.g  # E: Cannot determine type of \"g\"  # E: Name \"A\" is used before definition\n\nclass A:\n    @classmethod\n    def f(cls) -> None:\n        reveal_type(cls.g)  # N: Revealed type is \"def (x: builtins.str)\"\n\n    @classmethod\n    @dec()\n    def g(cls, x: str) -> None:\n        pass\n\n    @classmethod\n    def h(cls) -> None:\n        reveal_type(cls.g)  # N: Revealed type is \"def (x: builtins.str)\"\n\nreveal_type(A.g)  # N: Revealed type is \"def (x: builtins.str)\"\n[builtins fixtures/classmethod.pyi]\n\n\n-- Tests for special cases of unification\n-- --------------------------------------\n\n\n[case testUnificationRedundantUnion]\nfrom typing import Union\na: Union[int, str]\nb: Union[str, tuple]\ndef f(): pass\ndef g(x: Union[int, str]): pass\nc = a if f() else b\ng(c) # E: Argument 1 to \"g\" has incompatible type \"int | str | tuple[Any, ...]\"; expected \"int | str\"\n[builtins fixtures/tuple.pyi]\n\n[case testUnificationMultipleInheritance]\nclass A: pass\nclass B:\n    def foo(self): pass\nclass C(A, B): pass\ndef f(): pass\na1 = B() if f() else C()\na1.foo()\na2 = C() if f() else B()\na2.foo()\n\n[case testUnificationMultipleInheritanceAmbiguous]\n# Show that join_instances_via_supertype() breaks ties using the first base class.\nclass A1: pass\nclass B1:\n    def foo1(self): pass\nclass C1(A1, B1): pass\n\nclass A2: pass\nclass B2:\n    def foo2(self): pass\nclass C2(A2, B2): pass\n\nclass D1(C1, C2): pass\nclass D2(C2, C1): pass\n\ndef f(): pass\n\na1 = D1() if f() else D2()\na1.foo1()\na2 = D2() if f() else D1()\na2.foo2()\n\n[case testUnificationEmptyListLeft]\ndef f(): pass\na = [] if f() else [0]\na() # E: \"list[int]\" not callable\n[builtins fixtures/list.pyi]\n\n[case testUnificationEmptyListRight]\ndef f(): pass\na = [0] if f() else []\na() # E: \"list[int]\" not callable\n[builtins fixtures/list.pyi]\n\n[case testUnificationEmptyListLeftInContext]\nfrom typing import List\ndef f(): pass\na = [] if f() else [0] # type: list[int]\na() # E: \"list[int]\" not callable\n[builtins fixtures/list.pyi]\n\n[case testUnificationEmptyListRightInContext]\n# TODO Find an example that really needs the context\nfrom typing import List\ndef f(): pass\na = [0] if f() else [] # type: list[int]\na() # E: \"list[int]\" not callable\n[builtins fixtures/list.pyi]\n\n[case testUnificationEmptySetLeft]\ndef f(): pass\na = set() if f() else {0}\na() # E: \"set[int]\" not callable\n[builtins fixtures/set.pyi]\n\n[case testUnificationEmptyDictLeft]\ndef f(): pass\na = {} if f() else {0: 0}\na() # E: \"dict[int, int]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testUnificationEmptyDictRight]\ndef f(): pass\na = {0: 0} if f() else {}\na() # E: \"dict[int, int]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testUnificationDictWithEmptyListLeft]\ndef f(): pass\na = {0: []} if f() else {0: [0]}\na() # E: \"dict[int, list[int]]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testUnificationDictWithEmptyListRight]\ndef f(): pass\na = {0: [0]} if f() else {0: []}\na() # E: \"dict[int, list[int]]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testMisguidedSetItem]\nfrom typing import Generic, Sequence, TypeVar\nT = TypeVar('T')\nclass C(Sequence[T], Generic[T]): pass\nC[0] = 0\n[out]\nmain:4: error: Unsupported target for indexed assignment (\"type[C[T]]\")\nmain:4: error: Invalid type: try using Literal[0] instead?\n\n[case testNoCrashOnPartialMember]\n# flags: --no-local-partial-types\nclass C:\n    x = None\n    def __init__(self) -> None:\n        self.x = []  # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n[builtins fixtures/list.pyi]\n\n[case testNoCrashOnPartialVariable]\nfrom typing import Tuple, TypeVar\nT = TypeVar('T', bound=str)\n\ndef f(x: T) -> Tuple[T]:\n    ...\nx = None\n(x,) = f('')\nreveal_type(x) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testNoCrashOnPartialVariable2]\n# flags: --no-local-partial-types\nfrom typing import Tuple, TypeVar\nT = TypeVar('T', bound=str)\n\ndef f() -> Tuple[T]:\n    ...\nx = None  # E: Need type annotation for \"x\"\nif int():\n    (x,) = f()\n[builtins fixtures/tuple.pyi]\n\n[case testNoCrashOnPartialVariable3]\nfrom typing import Tuple, TypeVar\nT = TypeVar('T')\n\ndef f(x: T) -> Tuple[T, T]:\n    ...\nx = None\n(x, x) = f('')\nreveal_type(x) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testRejectsPartialWithUninhabited]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass Foo(Generic[T]): ...\n\ndef check() -> None:\n    x = None  # E: Need type annotation for \"x\"\n    if int():\n        x = Foo()\n        reveal_type(x)  # N: Revealed type is \"__main__.Foo[Any]\"\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo[Any] | None\"\n\n[case testRejectsPartialWithUninhabited2]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass Foo(Generic[T]): ...\n\nx = None  # E: Need type annotation for \"x\"\n\ndef check() -> None:\n    global x\n    x = Foo()\n    reveal_type(x)  # N: Revealed type is \"__main__.Foo[Any]\"\n\nreveal_type(x)  # N: Revealed type is \"__main__.Foo[Any] | None\"\n\n[case testRejectsPartialWithUninhabited3]\n# Without force-rejecting Partial<None>, this crashes:\n# https://github.com/python/mypy/issues/16573\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass Foo(Generic[T]): ...\n\ndef check() -> None:\n    client = None  # E: Need type annotation for \"client\"\n\n    if client := Foo():\n        reveal_type(client)  # N: Revealed type is \"__main__.Foo[Any]\"\n\n    reveal_type(client)  # N: Revealed type is \"__main__.Foo[Any] | None\"\n\n    client = 0  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Foo[Any] | None\")\n    reveal_type(client)  # N: Revealed type is \"__main__.Foo[Any] | None\"\n\n[case testRejectsPartialWithUninhabitedIndependently]\nfrom typing import Generic, TypeVar\nT = TypeVar('T')\n\nclass Foo(Generic[T]): ...\n\nclient = None  # E: Need type annotation for \"client\"\n\ndef bad() -> None:\n    global client\n    client = Foo()\n    reveal_type(client)  # N: Revealed type is \"__main__.Foo[Any]\"\n\ndef good() -> None:\n    global client\n    client = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Foo[Any] | None\")\n    reveal_type(client)  # N: Revealed type is \"__main__.Foo[Any] | None\"\n\ndef bad2() -> None:\n    global client\n    client = Foo()\n    reveal_type(client)  # N: Revealed type is \"__main__.Foo[Any]\"\n\n[case testInferenceNestedTuplesFromGenericIterable]\nfrom typing import Tuple, TypeVar\n\nT = TypeVar('T')\n\ndef make_tuple(elem: T) -> Tuple[T]:\n    return (elem,)\n\ndef main() -> None:\n    ((a, b),) = make_tuple((1, 2))\n    reveal_type(a) # N: Revealed type is \"builtins.int\"\n    reveal_type(b) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testDontMarkUnreachableAfterInferenceUninhabited]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef f() -> T: pass # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\n\nclass C:\n    x = f() # E: Need type annotation for \"x\"\n    def m(self) -> str:\n        return 42 # E: Incompatible return value type (got \"int\", expected \"str\")\n\nif bool():\n    f()\n    1() # E: \"int\" not callable\n[builtins fixtures/list.pyi]\n[out]\n\n[case testDontMarkUnreachableAfterInferenceUninhabited2]\nfrom typing import TypeVar, Optional\nT = TypeVar('T')\ndef f(x: Optional[T] = None) -> T: pass\n\nclass C:\n    x = f() # E: Need type annotation for \"x\"\n    def m(self) -> str:\n        return 42 # E: Incompatible return value type (got \"int\", expected \"str\")\n\nif bool():\n    f()\n    1() # E: \"int\" not callable\n[builtins fixtures/list.pyi]\n[out]\n\n[case testDontMarkUnreachableAfterInferenceUninhabited3]\nfrom typing import TypeVar, List\nT = TypeVar('T')\ndef f(x: List[T]) -> T: pass\n\nclass C:\n    x = f([]) # E: Need type annotation for \"x\"\n    def m(self) -> str:\n        return 42 # E: Incompatible return value type (got \"int\", expected \"str\")\n\nif bool():\n    f([])\n    1() # E: \"int\" not callable\n[builtins fixtures/list.pyi]\n[out]\n\n\n-- --local-partial-types\n-- ---------------------\n\n\n[case testLocalPartialTypesWithGlobalInitializedToNone]\n# flags: --local-partial-types\nx = None\n\ndef f() -> None:\n    global x\n    x = 1\n\nreveal_type(x) # N: Revealed type is \"builtins.int | None\"\n\n[case testLocalPartialTypesWithGlobalInitializedToNone2]\n# flags: --local-partial-types\nx = None\n\ndef f():\n    global x\n    x = 1\n\nreveal_type(x) # N: Revealed type is \"Any | None\"\n\n[case testLocalPartialTypesWithGlobalInitializedToNone3]\n# flags: --local-partial-types --no-strict-optional\nx = None\n\ndef f() -> None:\n    global x\n    x = 1\n\nx = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nreveal_type(x) # N: Revealed type is \"builtins.int\"\n\n[case testLocalPartialTypesWithGlobalInitializedToNoneStrictOptional]\n# flags: --local-partial-types\nx = None\n\ndef f() -> None:\n    global x\n    x = 1\n\nx = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int | None\")\ndef g() -> None:\n    reveal_type(x) # N: Revealed type is \"builtins.int | None\"\n\n[case testLocalPartialTypesWithGlobalInitializedToNone4]\n# flags: --local-partial-types --no-strict-optional\na = None\n\ndef f() -> None:\n    reveal_type(a)  # N: Revealed type is \"None\"\n\nreveal_type(a)  # N: Revealed type is \"None\"\na = ''\nreveal_type(a)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testLocalPartialTypesWithGlobalInitializedToNone5]\n# flags: --local-partial-types\na = None\n\ndef f() -> None:\n    reveal_type(a)  # N: Revealed type is \"None\"\n\nreveal_type(a)  # N: Revealed type is \"None\"\na = ''\nreveal_type(a)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testLocalPartialTypesWithClassAttributeInitializedToNone]\n# flags: --local-partial-types\nclass A:\n    x = None\n\n    def f(self) -> None:\n        self.x = 1\n\n[case testLocalPartialTypesWithClassAttributeInitializedToEmptyDict]\n# flags: --local-partial-types\nclass A:\n    x = {}  # E: Need type annotation for \"x\" (hint: \"x: dict[<type>, <type>] = ...\")\n\n    def f(self) -> None:\n        self.x[0] = ''\n\nreveal_type(A().x)  # N: Revealed type is \"builtins.dict[Any, Any]\"\nreveal_type(A.x)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testLocalPartialTypesWithGlobalInitializedToEmptyList]\n# flags: --local-partial-types\na = []\n\ndef f() -> None:\n    a[0]\n    reveal_type(a)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\na.append(1)\nreveal_type(a) # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testLocalPartialTypesWithGlobalInitializedToEmptyList2]\n# flags: --local-partial-types\na = [] # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n\ndef f() -> None:\n    a.append(1)\n    reveal_type(a)  # N: Revealed type is \"builtins.list[Any]\"\n\nreveal_type(a) # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testLocalPartialTypesWithGlobalInitializedToEmptyList3]\n# flags: --local-partial-types\na = [] # E: Need type annotation for \"a\" (hint: \"a: list[<type>] = ...\")\n\ndef f():\n    a.append(1)\n\nreveal_type(a) # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testLocalPartialTypesWithGlobalInitializedToEmptyDict]\n# flags: --local-partial-types\na = {}\n\ndef f() -> None:\n    a[0]\n    reveal_type(a)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n\na[0] = ''\nreveal_type(a) # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n[builtins fixtures/dict.pyi]\n\n[case testLocalPartialTypesWithGlobalInitializedToEmptyDict2]\n# flags: --local-partial-types\na = {} # E: Need type annotation for \"a\" (hint: \"a: dict[<type>, <type>] = ...\")\n\ndef f() -> None:\n    a[0] = ''\n    reveal_type(a)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n\nreveal_type(a) # N: Revealed type is \"builtins.dict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testLocalPartialTypesWithGlobalInitializedToEmptyDict3]\n# flags: --local-partial-types\na = {} # E: Need type annotation for \"a\" (hint: \"a: dict[<type>, <type>] = ...\")\n\ndef f():\n    a[0] = ''\n\nreveal_type(a) # N: Revealed type is \"builtins.dict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testLocalPartialTypesWithNestedFunction]\n# flags: --local-partial-types\ndef f() -> None:\n    a = {}\n    def g() -> None:\n        a[0] = ''\n    reveal_type(a) # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n[builtins fixtures/dict.pyi]\n\n[case testLocalPartialTypesWithNestedFunction2]\n# flags: --local-partial-types\ndef f() -> None:\n    a = []\n    def g() -> None:\n        a.append(1)\n    reveal_type(a) # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testLocalPartialTypesWithNestedFunction3]\n# flags: --local-partial-types --no-strict-optional\ndef f() -> None:\n    a = None\n    def g() -> None:\n        nonlocal a\n        a = ''\n    reveal_type(a) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n\n[case testLocalPartialTypesWithInheritance]\n# flags: --local-partial-types\nfrom typing import Optional\n\nclass A:\n    x: Optional[str]\n\nclass B(A):\n    x = None\n\nreveal_type(B.x) # N: Revealed type is \"None\"\n\n[case testLocalPartialTypesWithInheritance2]\n# flags: --local-partial-types\nclass A:\n    x: str\n\nclass B(A):\n    x = None  # E: Incompatible types in assignment (expression has type \"None\", base class \"A\" defined the type as \"str\")\n\n[case testLocalPartialTypesWithAnyBaseClass]\n# flags: --local-partial-types\nfrom typing import Any\n\nA: Any\n\nclass B(A):\n    x = None\n\nclass C(B):\n    y = None\n\n[case testLocalPartialTypesInMultipleMroItems]\n# flags: --local-partial-types\nfrom typing import Optional\n\nclass A:\n    x: Optional[str]\n\nclass B(A):\n    x = None\n\nclass C(B):\n    x = None\n\n# TODO: Inferring None below is unsafe (https://github.com/python/mypy/issues/3208)\nreveal_type(B.x)  # N: Revealed type is \"None\"\nreveal_type(C.x)  # N: Revealed type is \"None\"\n\n[case testLocalPartialTypesWithInheritance3]\n# flags: --local-partial-types\nfrom typing import Optional\n\nclass X: pass\nclass Y(X): pass\n\nclass A:\n    x: Optional[X]\n\nclass B(A):\n    x = None\n    x = Y()\n\nreveal_type(B.x) # N: Revealed type is \"__main__.Y | None\"\n\n[case testLocalPartialTypesBinderSpecialCase]\n# flags: --local-partial-types\nfrom typing import List\n\ndef f(x): pass\n\nclass A:\n    x = None\n\n    def f(self, p: List[str]) -> None:\n        self.x = f(p)\n        f(z for z in p)\n[builtins fixtures/list.pyi]\n\n[case testLocalPartialTypesAccessPartialNoneAttribute]\n# flags: --local-partial-types\nclass C:\n    a = None\n\n    def f(self, x) -> None:\n        C.a.y  # E: \"None\" has no attribute \"y\"\n\n[case testLocalPartialTypesAccessPartialNoneAttribute2]\n# flags: --local-partial-types\nclass C:\n    a = None\n\n    def f(self, x) -> None:\n        self.a.y  # E: \"None\" has no attribute \"y\"\n\n[case testUnusedTargetLocal]\ndef foo() -> None:\n    _ = 0\n    _ = ''\n\n[case testUnusedTargetNotGlobal]\n_ = 0\n_ = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testUnusedTargetNotClass]\n# flags: --allow-redefinition\nclass C:\n    _, _ = 0, 0\n    _ = ''\nreveal_type(C._) # N: Revealed type is \"builtins.str\"\n\n[case testUnusedTargetNotClass2]\n# flags: --disallow-redefinition\nclass C:\n    _, _ = 0, 0\n    _ = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nreveal_type(C._) # N: Revealed type is \"builtins.int\"\n\n[case testUnusedTargetTupleUnpacking]\ndef foo() -> None:\n    _, _ = (0, '')\n    _ = 0\n    _ = ''\ndef bar() -> None:\n    t = (0, '')\n    _, _ = t\n    _ = 0\n    _ = ''\n[builtins fixtures/tuple.pyi]\n\n[case testUnusedTargetMultipleTargets]\ndef foo() -> None:\n    _ = x = 0\n    _ = y = ''\n    _ = 0\n    _ = ''\ndef bar() -> None:\n    x = _ = 0\n    y = _ = ''\n    _ = 0\n    _ = ''\n    x + 0\n    y + ''\n    x + ''  # E: Unsupported operand types for + (\"int\" and \"str\")\n    y + 0  # E: Unsupported operand types for + (\"str\" and \"int\")\n[builtins fixtures/primitives.pyi]\n\n[case testUnusedTargetNotImport]\nimport d, c, b, a\n[file _.py]\ndef f(): pass\n[file m.py]\ndef f(): pass\n_ = f\n_ = 0  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Callable[[], Any]\")\n[file a.py]\ndef foo() -> None:\n    import _\n    _.f()\n    _ = 0  # E: Incompatible types in assignment (expression has type \"int\", variable has type Module)\n[file b.py]\ndef foo() -> None:\n    import m as _\n    _.f()\n    _ = 0  # E: Incompatible types in assignment (expression has type \"int\", variable has type Module)\n[file c.py]\ndef foo() -> None:\n    from m import _\n    _()\n    _ = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"Callable[[], Any]\")\n[file d.py]\ndef foo() -> None:\n    from m import f as _\n    _()\n    _ = 0  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Callable[[], Any]\")\n[builtins fixtures/module.pyi]\n\n[case testUnderscoreClass]\ndef foo() -> None:\n    class _:\n        pass\n    _().method()  # E: \"_\" has no attribute \"method\"\n\n[case testUnusedTargetForLoop]\ndef f() -> None:\n    a = [(0, '', 0)]\n    for _, _, x in a:\n        x = 0\n        x = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    _ = 0\n    _ = ''\n[builtins fixtures/list.pyi]\n\n[case testUnusedTargetWithClause]\nclass C:\n    def __enter__(self) -> int: pass\n    def __exit__(self, *args): pass\ndef f() -> None:\n    with C() as _: pass\n    _ = 0\n    _ = ''\n[builtins fixtures/tuple.pyi]\n\n[case testUnusedTargetNotExceptClause]\n# Things don't work for except clauses.\n# This is due to the implementation, but it's just as well.\ndef f() -> None:\n    try: pass\n    except BaseException as _:\n        _ = 0  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"BaseException\")\n        _ = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"BaseException\")\n[builtins fixtures/exception.pyi]\n\n-- Tests for permissive toplevel checking\n-- --------------\n\n[case testPermissiveAttributeOverride1]\n# flags: --allow-untyped-globals\n\nclass A:\n    x = None\n\nclass B(A):\n    x = 12\n\nclass C(A):\n    x = '12'\n\nreveal_type(A.x) # N: Revealed type is \"Any | None\"\nreveal_type(B.x) # N: Revealed type is \"builtins.int\"\nreveal_type(C.x) # N: Revealed type is \"builtins.str\"\n\n[case testPermissiveAttributeOverride2]\n# flags: --allow-untyped-globals\n\nclass A:\n    x = []\n\nclass B(A):\n    x = [12]\n\nclass C(A):\n    x = ['12']\n\nreveal_type(A.x) # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(B.x) # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(C.x) # N: Revealed type is \"builtins.list[builtins.str]\"\n\n[builtins fixtures/list.pyi]\n\n[case testPermissiveAttribute]\n# flags: --allow-untyped-globals\n\nclass A:\n    x = []\n    def f(self) -> None:\n        reveal_type(self.x)  # N: Revealed type is \"builtins.list[Any]\"\n\n[builtins fixtures/list.pyi]\n\n[case testPermissiveGlobalContainer1]\n# flags: --allow-untyped-globals --local-partial-types\n\nimport a\n\n[file b.py]\nx = []\ny = {}\n\ndef foo() -> None:\n    reveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\n    reveal_type(y)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n\n[file a.py]\nfrom b import x, y\nreveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(y)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n\n[builtins fixtures/dict.pyi]\n\n[case testPermissiveGlobalContainer2]\n# flags: --allow-untyped-globals\n\nimport a\n\n[file b.py]\nx = []\ny = {}\n\ndef foo() -> None:\n    reveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\n    reveal_type(y)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n\n[file a.py]\nfrom b import x, y\nreveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(y)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n\n[builtins fixtures/dict.pyi]\n\n[case testPermissiveGlobalContainer3]\n# flags: --allow-untyped-globals --local-partial-types\n\nimport a\n\n[file b.py]\nx = []\ny = {}\nz = y\n\n\n[file a.py]\nfrom b import x, y\nreveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(y)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n\n[builtins fixtures/dict.pyi]\n[case testPermissiveGlobalContainer4]\n# flags: --allow-untyped-globals\n\nimport a\n\n[file b.py]\nx = []\ny = {}\nz = y\n\n\n[file a.py]\nfrom b import x, y\nreveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\nreveal_type(y)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n\n[builtins fixtures/dict.pyi]\n\n[case testInheritedAttributeNoStrictOptional]\n# flags: --no-strict-optional\nclass A:\n    x: str\n\nclass B(A):\n    x = None\n    x = ''\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\n[case testIncompatibleInheritedAttributeNoStrictOptional]\n# flags: --no-strict-optional\nclass A:\n    x: str\n\nclass B(A):\n    x = None\n    x = 2  # E: Incompatible types in assignment (expression has type \"int\", base class \"A\" defined the type as \"str\")\n\n[case testInheritedAttributeStrictOptional]\nclass A:\n    x: str\n\nclass B(A):\n    x = None  # E: Incompatible types in assignment (expression has type \"None\", base class \"A\" defined the type as \"str\")\n    x = ''\n\n[case testNeedAnnotationForCallable]\nfrom typing import TypeVar, Optional, Callable\n\nT = TypeVar('T')\n\ndef f(x: Optional[T] = None) -> Callable[..., T]: ...\n\nx = f()  # E: Need type annotation for \"x\"\ny = x\n\n[case testDontNeedAnnotationForCallable]\nfrom typing import TypeVar, Optional, Callable, NoReturn\n\nT = TypeVar('T')\n\ndef f() -> Callable[..., NoReturn]: ...\n\nx = f()\nreveal_type(x)  # N: Revealed type is \"def (*Any, **Any) -> Never\"\n\n[case testDeferralInNestedScopes]\n\n\ndef g() -> None:\n    def f() -> None:\n        x + 'no way'  # E: Unsupported operand types for + (\"int\" and \"str\")\n    x = int()\n    f()\n\n[case testDeferralOfMemberNested]\nfrom typing import Tuple\n\ndef f() -> None:\n    c: C\n    t: Tuple[str, Tuple[str, str]]\n    x, (y, c.a) = t  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\nclass C:\n    def __init__(self, a: int) -> None:\n        self.a = a\n[builtins fixtures/tuple.pyi]\n\n[case testUnionGenericWithBoundedVariable]\nfrom typing import Generic, TypeVar, Union\n\nclass A: ...\nclass B(A): ...\n\nT = TypeVar('T', bound=A)\nclass Z(Generic[T]):\n    def __init__(self, y: T) -> None:\n        self.y = y\n\nF = TypeVar('F', bound=A)\n\ndef q1(x: Union[F, Z[F]]) -> F:\n    if isinstance(x, Z):\n        return x.y\n    else:\n        return x\n\ndef q2(x: Union[Z[F], F]) -> F:\n    if isinstance(x, Z):\n        return x.y\n    else:\n        return x\n\nb: B\nreveal_type(q1(b))  # N: Revealed type is \"__main__.B\"\nreveal_type(q2(b))  # N: Revealed type is \"__main__.B\"\n\nz: Z[B]\nreveal_type(q1(z))  # N: Revealed type is \"__main__.B\"\nreveal_type(q2(z))  # N: Revealed type is \"__main__.B\"\n\nreveal_type(q1(Z(b)))  # N: Revealed type is \"__main__.B\"\nreveal_type(q2(Z(b)))  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnionInvariantSubClassAndCovariantBase]\nfrom typing import Union, Generic, TypeVar\n\nT = TypeVar('T')\nT_co = TypeVar('T_co', covariant=True)\n\nclass Cov(Generic[T_co]): ...\nclass Inv(Cov[T]): ...\n\nX = Union[Cov[T], Inv[T]]\n\ndef f(x: X[T]) -> T: ...\nx: Inv[int]\nreveal_type(f(x))  # N: Revealed type is \"builtins.int\"\n\n[case testOptionalTypeVarAgainstOptional]\nfrom typing import Optional, TypeVar, Iterable, Iterator, List\n\n_T = TypeVar('_T')\n\ndef filter(__function: None, __iterable: Iterable[Optional[_T]]) -> List[_T]: ...\n\nx: Optional[str]\n\ny = filter(None, [x])\nreveal_type(y)  # N: Revealed type is \"builtins.list[builtins.str]\"\n[builtins fixtures/list.pyi]\n\n[case testPartialDefaultDict]\nfrom collections import defaultdict\nx = defaultdict(int)\nx[''] = 1\nreveal_type(x) # N: Revealed type is \"collections.defaultdict[builtins.str, builtins.int]\"\n\ny = defaultdict(int) # E: Need type annotation for \"y\"\n\nz = defaultdict(int)  # E: Need type annotation for \"z\"\nz[''] = ''\nreveal_type(z) # N: Revealed type is \"collections.defaultdict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testPartialDefaultDictInconsistentValueTypes]\nfrom collections import defaultdict\na = defaultdict(int)  # E: Need type annotation for \"a\"\na[''] = ''\na[''] = 1\nreveal_type(a) # N: Revealed type is \"collections.defaultdict[builtins.str, builtins.int]\"\n[builtins fixtures/dict.pyi]\n\n[case testPartialDefaultDictListValue]\n# flags: --no-strict-optional\nfrom collections import defaultdict\na = defaultdict(list)\na['x'].append(1)\nreveal_type(a) # N: Revealed type is \"collections.defaultdict[builtins.str, builtins.list[builtins.int]]\"\n\nb = defaultdict(lambda: [])\nb[1].append('x')\nreveal_type(b) # N: Revealed type is \"collections.defaultdict[builtins.int, builtins.list[builtins.str]]\"\n[builtins fixtures/dict.pyi]\n\n[case testPartialDefaultDictListValueStrictOptional]\nfrom collections import defaultdict\na = defaultdict(list)\na['x'].append(1)\nreveal_type(a) # N: Revealed type is \"collections.defaultdict[builtins.str, builtins.list[builtins.int]]\"\n\nb = defaultdict(lambda: [])\nb[1].append('x')\nreveal_type(b) # N: Revealed type is \"collections.defaultdict[builtins.int, builtins.list[builtins.str]]\"\n[builtins fixtures/dict.pyi]\n\n[case testPartialDefaultDictSpecialCases]\nfrom collections import defaultdict\nclass A:\n    def f(self) -> None:\n        self.x = defaultdict(list)\n        self.x['x'].append(1)\n        reveal_type(self.x) # N: Revealed type is \"collections.defaultdict[builtins.str, builtins.list[builtins.int]]\"\n        self.y = defaultdict(list)  # E: Need type annotation for \"y\"\n        s = self\n        s.y['x'].append(1)\n\nx = {} # E: Need type annotation for \"x\" (hint: \"x: dict[<type>, <type>] = ...\")\nx['x'].append(1)\n\ny = defaultdict(list)  # E: Need type annotation for \"y\"\ny[[]].append(1)\n[builtins fixtures/dict.pyi]\n\n[case testPartialDefaultDictSpecialCases2]\nfrom collections import defaultdict\n\nx = defaultdict(lambda: [1]) # E: Need type annotation for \"x\"\nx[1].append('') # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\nreveal_type(x) # N: Revealed type is \"collections.defaultdict[Any, builtins.list[builtins.int]]\"\n\nxx = defaultdict(lambda: {'x': 1}) # E: Need type annotation for \"xx\"\nxx[1]['z'] = 3\nreveal_type(xx) # N: Revealed type is \"collections.defaultdict[Any, builtins.dict[builtins.str, builtins.int]]\"\n\ny = defaultdict(dict)  # E: Need type annotation for \"y\"\ny['x'][1] = [3]\n\nz = defaultdict(int) # E: Need type annotation for \"z\"\nz[1].append('')\nreveal_type(z) # N: Revealed type is \"collections.defaultdict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testPartialDefaultDictSpecialCase3]\nfrom collections import defaultdict\n\nx = defaultdict(list)\nx['a'] = [1, 2, 3]\nreveal_type(x)  # N: Revealed type is \"collections.defaultdict[builtins.str, builtins.list[builtins.int]]\"\n\ny = defaultdict(list)  # E: Need type annotation for \"y\"\ny['a'] = []\nreveal_type(y)  # N: Revealed type is \"collections.defaultdict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testInferCallableReturningNone1]\n# flags: --no-strict-optional\nfrom typing import Callable, TypeVar\n\nT = TypeVar(\"T\")\n\ndef f(x: Callable[[], T]) -> T:\n    return x()\n\nreveal_type(f(lambda: None))  # N: Revealed type is \"None\"\nreveal_type(f(lambda: 1))  # N: Revealed type is \"builtins.int\"\n\ndef g() -> None: pass\n\nreveal_type(f(g))  # N: Revealed type is \"None\"\n\n[case testInferCallableReturningNone2]\nfrom typing import Callable, TypeVar\n\nT = TypeVar(\"T\")\n\ndef f(x: Callable[[], T]) -> T:\n    return x()\n\nreveal_type(f(lambda: None))  # N: Revealed type is \"None\"\nreveal_type(f(lambda: 1))  # N: Revealed type is \"builtins.int\"\n\ndef g() -> None: pass\n\nreveal_type(f(g))  # N: Revealed type is \"None\"\n\n[case testInferredTypeIsSimpleNestedList]\nfrom typing import Any, Union, List\n\ny: Union[List[Any], Any]\nx: Union[List[Any], Any]\nx = [y]\nreveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testInferredTypeIsSimpleNestedIterable]\nfrom typing import Any, Union, Iterable\n\ny: Union[Iterable[Any], Any]\nx: Union[Iterable[Any], Any]\nx = [y]\nreveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testInferredTypeIsSimpleNestedListLoop]\nfrom typing import Any, Union, List\n\ndef test(seq: List[Union[List, Any]]) -> None:\n    k: Union[List, Any]\n    for k in seq:\n        if bool():\n            k = [k]\n            reveal_type(k)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testInferredTypeIsSimpleNestedIterableLoop]\nfrom typing import Any, Union, List, Iterable\n\ndef test(seq: List[Union[Iterable, Any]]) -> None:\n    k: Union[Iterable, Any]\n    for k in seq:\n        if bool():\n            k = [k]\n            reveal_type(k)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testErasedTypeRuntimeCoverage]\n# https://github.com/python/mypy/issues/11913\nfrom typing import TypeVar, Type, Generic, Callable, Iterable\n\nclass DataType: ...\n\nT1 = TypeVar('T1')\nT2 = TypeVar(\"T2\", bound=DataType)\n\ndef map(__func: T1) -> None: ...\n\ndef collection_from_dict_value(model: Type[T2]) -> None:\n    map(lambda i: i if isinstance(i, model) else i)\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRegression11705_Strict]\n# See: https://github.com/python/mypy/issues/11705\nfrom typing import Dict, Optional, NamedTuple\nclass C(NamedTuple):\n    x: int\n\nt: Optional[C]\nd: Dict[C, bytes]\nx = t and d[t]\nreveal_type(x)  # N: Revealed type is \"None | builtins.bytes\"\nif x:\n    reveal_type(x)  # N: Revealed type is \"builtins.bytes\"\n[builtins fixtures/dict.pyi]\n\n[case testRegression11705_NoStrict]\n# flags: --no-strict-optional\n# See: https://github.com/python/mypy/issues/11705\nfrom typing import Dict, Optional, NamedTuple\nclass C(NamedTuple):\n    x: int\n\nt: Optional[C]\nd: Dict[C, bytes]\nx = t and d[t]\nreveal_type(x)  # N: Revealed type is \"builtins.bytes\"\nif x:\n    reveal_type(x)  # N: Revealed type is \"builtins.bytes\"\n[builtins fixtures/dict.pyi]\n\n[case testAllowPlainNoneForPartialAtModuleScope]\n# flags: --local-partial-types --python-version 3.10\nx = None\nreveal_type(x)  # N: Revealed type is \"None\"\n\n[case testTupleContextFromIterable]\nfrom typing import TypeVar, Iterable, List, Union\n\nT = TypeVar(\"T\")\n\ndef foo(x: List[T]) -> List[T]: ...\nx: Iterable[List[Union[int, str]]] = (foo([1]), foo([\"a\"]))\n[builtins fixtures/tuple.pyi]\n\n[case testTupleContextFromIterable2]\nfrom typing import Dict, Iterable, Tuple, Union\n\ndef foo(x: Union[Tuple[str, Dict[str, int], str], Iterable[object]]) -> None: ...\nfoo((\"a\", {\"a\": \"b\"}, \"b\"))\n[builtins fixtures/dict.pyi]\n\n[case testUseSupertypeAsInferenceContext]\nfrom typing import List, Optional\n\nclass B:\n    x: List[Optional[int]]\n\nclass C(B):\n    x = [1]\n\nreveal_type(C().x)  # N: Revealed type is \"builtins.list[builtins.int | None]\"\n[builtins fixtures/list.pyi]\n\n[case testUseSupertypeAsInferenceContextInvalidType]\nfrom typing import List\nclass P:\n    x: List[int]\nclass C(P):\n    x = ['a']  # E: List item 0 has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testUseSupertypeAsInferenceContextPartial]\nfrom typing import List\n\nclass A:\n    x: List[str]\n\nclass B(A):\n    x = []\n\nreveal_type(B().x)  # N: Revealed type is \"builtins.list[builtins.str]\"\n[builtins fixtures/list.pyi]\n\n[case testUseSupertypeAsInferenceContextPartialError]\nclass A:\n    x = ['a', 'b']\n\nclass B(A):\n    x = []\n    x.append(2)  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/list.pyi]\n\n[case testUseSupertypeAsInferenceContextPartialErrorProperty]\nfrom typing import List\n\nclass P:\n    @property\n    def x(self) -> List[int]: ...\nclass C(P):\n    x = []\n\nC.x.append(\"no\")  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/list.pyi]\n\n[case testUseSupertypeAsInferenceContextConflict]\nfrom typing import List\nclass P:\n    x: List[int]\nclass M:\n    x: List[str]\nclass C(P, M):\n    x = []  # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\nreveal_type(C.x)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testNoPartialInSupertypeAsContext]\nclass A:\n    args = {}  # E: Need type annotation for \"args\" (hint: \"args: dict[<type>, <type>] = ...\")\n    def f(self) -> None:\n        value = {1: \"Hello\"}\n        class B(A):\n            args = value\n[builtins fixtures/dict.pyi]\n\n[case testInferSimpleLiteralInClassBodyCycle]\nimport a\n[file a.py]\nimport b\nreveal_type(b.B.x)  # N: Revealed type is \"builtins.int\"\nclass A:\n    x = 42\n[file b.py]\nimport a\nreveal_type(a.A.x)  # N: Revealed type is \"builtins.int\"\nclass B:\n    x = 42\n\n[case testUnionTypeCallableInference]\nfrom typing import Callable, Type, TypeVar, Union\n\nclass A:\n    def __init__(self, x: str) -> None: ...\n\nT = TypeVar(\"T\")\ndef type_or_callable(value: T, tp: Union[Type[T], Callable[[int], T]]) -> T: ...\nreveal_type(type_or_callable(A(\"test\"), A))  # N: Revealed type is \"__main__.A\"\n\n[case testUpperBoundAsInferenceFallback]\nfrom typing import Callable, TypeVar, Any, Mapping, Optional\nT = TypeVar(\"T\", bound=Mapping[str, Any])\ndef raises(opts: Optional[T]) -> T: pass\ndef assertRaises(cb: Callable[..., object]) -> None: pass\nassertRaises(raises)  # OK\n[builtins fixtures/dict.pyi]\n\n[case testJoinWithAnyFallback]\nfrom unknown import X  # type: ignore[import]\n\nclass A: ...\nclass B(X, A): ...\nclass C(B): ...\nclass D(C): ...\nclass E(D): ...\n\nreveal_type([E(), D()])  # N: Revealed type is \"builtins.list[__main__.D]\"\nreveal_type([D(), E()])  # N: Revealed type is \"builtins.list[__main__.D]\"\n\n[case testCallableInferenceAgainstCallablePosVsStar]\nfrom typing import TypeVar, Callable, Tuple\n\nT = TypeVar('T')\nS = TypeVar('S')\n\ndef f(x: Callable[[T, S], None]) -> Tuple[T, S]: ...\ndef g(*x: int) -> None: ...\nreveal_type(f(g))  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testCallableInferenceAgainstCallableStarVsPos]\nfrom typing import TypeVar, Callable, Tuple, Protocol\n\nT = TypeVar('T', contravariant=True)\nS = TypeVar('S', contravariant=True)\n\nclass Call(Protocol[T, S]):\n    def __call__(self, __x: T, *args: S) -> None: ...\n\ndef f(x: Call[T, S]) -> Tuple[T, S]: ...\ndef g(*x: int) -> None: ...\nreveal_type(f(g))  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testCallableInferenceAgainstCallableNamedVsStar]\nfrom typing import TypeVar, Callable, Tuple, Protocol\n\nT = TypeVar('T', contravariant=True)\nS = TypeVar('S', contravariant=True)\n\nclass Call(Protocol[T, S]):\n    def __call__(self, *, x: T, y: S) -> None: ...\n\ndef f(x: Call[T, S]) -> Tuple[T, S]: ...\ndef g(**kwargs: int) -> None: ...\nreveal_type(f(g))  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testCallableInferenceAgainstCallableStarVsNamed]\nfrom typing import TypeVar, Callable, Tuple, Protocol\n\nT = TypeVar('T', contravariant=True)\nS = TypeVar('S', contravariant=True)\n\nclass Call(Protocol[T, S]):\n    def __call__(self, *, x: T, **kwargs: S) -> None: ...\n\ndef f(x: Call[T, S]) -> Tuple[T, S]: ...\ndef g(**kwargs: int) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testCallableInferenceAgainstCallableNamedVsNamed]\nfrom typing import TypeVar, Callable, Tuple, Protocol\n\nT = TypeVar('T', contravariant=True)\nS = TypeVar('S', contravariant=True)\n\nclass Call(Protocol[T, S]):\n    def __call__(self, *, x: T, y: S) -> None: ...\n\ndef f(x: Call[T, S]) -> Tuple[T, S]: ...\n\n# Note: order of names is different w.r.t. protocol\ndef g(*, y: int, x: str) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"tuple[builtins.str, builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testCallableInferenceAgainstCallablePosOnlyVsNamed]\nfrom typing import TypeVar, Callable, Tuple, Protocol\n\nT = TypeVar('T', contravariant=True)\nS = TypeVar('S', contravariant=True)\n\nclass Call(Protocol[T]):\n    def __call__(self, *, x: T) -> None: ...\n\ndef f(x: Call[T]) -> Tuple[T, T]: ...\n\ndef g(__x: str) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"tuple[Never, Never]\" \\\n                   # E: Argument 1 to \"f\" has incompatible type \"Callable[[str], None]\"; expected \"Call[Never]\" \\\n                   # N: \"Call[Never].__call__\" has type \"def __call__(self, *, x: Never) -> None\"\n[builtins fixtures/list.pyi]\n\n[case testCallableInferenceAgainstCallableNamedVsPosOnly]\nfrom typing import TypeVar, Callable, Tuple, Protocol\n\nT = TypeVar('T', contravariant=True)\nS = TypeVar('S', contravariant=True)\n\nclass Call(Protocol[T]):\n    def __call__(self, __x: T) -> None: ...\n\ndef f(x: Call[T]) -> Tuple[T, T]: ...\n\ndef g(*, x: str) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"tuple[Never, Never]\" \\\n                   # E: Argument 1 to \"f\" has incompatible type \"def g(*, x: str) -> None\"; expected \"Call[Never]\" \\\n                   # N: \"Call[Never].__call__\" has type \"Callable[[Never], None]\"\n[builtins fixtures/list.pyi]\n\n[case testCallableInferenceAgainstCallablePosOnlyVsKwargs]\nfrom typing import TypeVar, Callable, Tuple, Protocol\n\nT = TypeVar('T', contravariant=True)\nS = TypeVar('S', contravariant=True)\n\nclass Call(Protocol[T]):\n    def __call__(self, __x: T) -> None: ...\n\ndef f(x: Call[T]) -> Tuple[T, T]: ...\n\ndef g(**x: str) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"tuple[Never, Never]\" \\\n                   # E: Argument 1 to \"f\" has incompatible type \"def g(**x: str) -> None\"; expected \"Call[Never]\" \\\n                   # N: \"Call[Never].__call__\" has type \"Callable[[Never], None]\"\n[builtins fixtures/list.pyi]\n\n[case testCallableInferenceAgainstCallableNamedVsArgs]\nfrom typing import TypeVar, Callable, Tuple, Protocol\n\nT = TypeVar('T', contravariant=True)\nS = TypeVar('S', contravariant=True)\n\nclass Call(Protocol[T]):\n    def __call__(self, *, x: T) -> None: ...\n\ndef f(x: Call[T]) -> Tuple[T, T]: ...\n\ndef g(*args: str) -> None: pass\nreveal_type(f(g))  # N: Revealed type is \"tuple[Never, Never]\" \\\n                   # E: Argument 1 to \"f\" has incompatible type \"def g(*args: str) -> None\"; expected \"Call[Never]\" \\\n                   # N: \"Call[Never].__call__\" has type \"def __call__(self, *, x: Never) -> None\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstTypeVarActualBound]\nfrom typing import Callable, TypeVar\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\ndef test(f: Callable[[T], S]) -> Callable[[T], S]: ...\n\nF = TypeVar(\"F\", bound=Callable[..., object])\ndef dec(f: F) -> F:\n    reveal_type(test(f))  # N: Revealed type is \"def (Any) -> builtins.object\"\n    return f\n\n[case testInferenceAgainstTypeVarActualUnionBound]\nfrom typing import Protocol, TypeVar, Union\n\nT_co = TypeVar(\"T_co\", covariant=True)\nclass SupportsFoo(Protocol[T_co]):\n    def foo(self) -> T_co: ...\n\nclass A:\n    def foo(self) -> A: ...\nclass B:\n    def foo(self) -> B: ...\n\ndef foo(f: SupportsFoo[T_co]) -> T_co: ...\n\nABT = TypeVar(\"ABT\", bound=Union[A, B])\ndef simpler(k: ABT):\n    foo(k)\n\n[case testInferenceWorksWithEmptyCollectionsNested]\nfrom typing import List, TypeVar, NoReturn\nT = TypeVar('T')\ndef f(a: List[T], b: List[T]) -> T: pass\nx = [\"yes\"]\nreveal_type(f(x, []))  # N: Revealed type is \"builtins.str\"\nreveal_type(f([\"yes\"], []))  # N: Revealed type is \"builtins.str\"\n\nempty: List[NoReturn]\nf(x, empty)  # E: Cannot infer value of type parameter \"T\" of \"f\"\nf([\"no\"], empty)  # E: Cannot infer value of type parameter \"T\" of \"f\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceWorksWithEmptyCollectionsUnion]\nfrom typing import Any, Dict, NoReturn, NoReturn, Union\n\ndef foo() -> Union[Dict[str, Any], Dict[int, Any]]:\n    return {}\n[builtins fixtures/dict.pyi]\n\n[case testExistingEmptyCollectionDoesNotUpcast]\nfrom typing import Any, Dict, NoReturn, NoReturn, Union\n\nempty: Dict[NoReturn, NoReturn]\n\ndef foo() -> Dict[str, Any]:\n    return empty  # E: Incompatible return value type (got \"dict[Never, Never]\", expected \"dict[str, Any]\")\n\ndef bar() -> Union[Dict[str, Any], Dict[int, Any]]:\n    return empty  # E: Incompatible return value type (got \"dict[Never, Never]\", expected \"dict[str, Any] | dict[int, Any]\")\n[builtins fixtures/dict.pyi]\n\n[case testUpperBoundInferenceFallbackNotOverused]\nfrom typing import TypeVar, Protocol, List\n\nS = TypeVar(\"S\", covariant=True)\nclass Foo(Protocol[S]):\n    def foo(self) -> S: ...\ndef foo(x: Foo[S]) -> S: ...\n\nT = TypeVar(\"T\", bound=\"Base\")\nclass Base:\n    def foo(self: T) -> T: ...\nclass C(Base):\n    pass\n\ndef f(values: List[T]) -> T: ...\nx = foo(f([C()]))\nreveal_type(x)  # N: Revealed type is \"__main__.C\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallableUnion]\nfrom typing import Callable, TypeVar, List, Union\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\ndef dec(f: Callable[[S], T]) -> Callable[[S], List[T]]: ...\n@dec\ndef func(arg: T) -> Union[T, str]:\n    ...\nreveal_type(func)  # N: Revealed type is \"def [S] (S`1) -> builtins.list[S`1 | builtins.str]\"\nreveal_type(func(42))  # N: Revealed type is \"builtins.list[builtins.int | builtins.str]\"\n\ndef dec2(f: Callable[[S], List[T]]) -> Callable[[S], T]: ...\n@dec2\ndef func2(arg: T) -> List[Union[T, str]]:\n    ...\nreveal_type(func2)  # N: Revealed type is \"def [S] (S`4) -> S`4 | builtins.str\"\nreveal_type(func2(42))  # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceAgainstGenericCallbackProtoMultiple]\nfrom typing import Callable, Protocol, TypeVar\nfrom typing_extensions import Concatenate, ParamSpec\n\nV_co = TypeVar(\"V_co\", covariant=True)\nclass Metric(Protocol[V_co]):\n    def __call__(self) -> V_co: ...\n\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\ndef simple_metric(func: Callable[Concatenate[int, P], T]) -> Callable[P, T]: ...\n\n@simple_metric\ndef Negate(count: int, /, metric: Metric[float]) -> float: ...\n@simple_metric\ndef Combine(count: int, m1: Metric[T], m2: Metric[T], /, *more: Metric[T]) -> T: ...\n\nreveal_type(Negate)  # N: Revealed type is \"def (metric: __main__.Metric[builtins.float]) -> builtins.float\"\nreveal_type(Combine)  # N: Revealed type is \"def [T] (def () -> T`5, def () -> T`5, *more: def () -> T`5) -> T`5\"\n\ndef m1() -> float: ...\ndef m2() -> float: ...\nreveal_type(Combine(m1, m2))  # N: Revealed type is \"builtins.float\"\n[builtins fixtures/list.pyi]\n\n[case testInferenceWithUninhabitedType]\nfrom typing import Dict, Generic, List, Never, TypeVar\n\nT = TypeVar(\"T\")\n\nclass A(Generic[T]): ...\nclass B(Dict[T, T]): ...\n\ndef func1(a: A[T], b: T) -> T: ...\ndef func2(a: T, b: A[T]) -> T: ...\n\ndef a1(a: A[Dict[str, int]]) -> None:\n    reveal_type(func1(a, {}))  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n    reveal_type(func2({}, a))  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n\ndef a2(check: bool, a: B[str]) -> None:\n    reveal_type(a if check else {})  # N: Revealed type is \"builtins.dict[builtins.str, builtins.str]\"\n\ndef a3() -> None:\n    a = {}  # E: Need type annotation for \"a\" (hint: \"a: dict[<type>, <type>] = ...\")\n    b = {1: {}}  # E: Need type annotation for \"b\"\n    c = {1: {}, 2: {\"key\": {}}}  # E: Need type annotation for \"c\"\n    reveal_type(a)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n    reveal_type(b)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.dict[Any, Any]]\"\n    reveal_type(c)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.dict[builtins.str, builtins.dict[Any, Any]]]\"\n\ndef a4(x: List[str], y: List[Never]) -> None:\n    z1 = [x, y]\n    z2 = [y, x]\n    reveal_type(z1)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    reveal_type(z2)  # N: Revealed type is \"builtins.list[builtins.object]\"\n    z1[1].append(\"asdf\")  # E: \"object\" has no attribute \"append\"\n[builtins fixtures/dict.pyi]\n\n\n[case testDeterminismCommutativityWithJoinInvolvingProtocolBaseAndPromotableType]\n# flags: --python-version 3.11\n# Regression test for https://github.com/python/mypy/issues/16979#issuecomment-1982246306\nfrom __future__ import annotations\n\nfrom typing import Any, Generic, Protocol, TypeVar, overload, cast\nfrom typing_extensions import Never\n\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\nclass _SupportsCompare(Protocol):\n    def __lt__(self, other: Any, /) -> bool:\n        return True\n\nclass Comparable(_SupportsCompare):\n    pass\n\ncomparable: Comparable = Comparable()\n\nfrom typing import _promote\n\nclass floatlike:\n    def __lt__(self, other: floatlike, /) -> bool: ...\n\n@_promote(floatlike)\nclass intlike:\n    def __lt__(self, other: intlike, /) -> bool: ...\n\n\nclass A(Generic[T, U]):\n    @overload\n    def __init__(self: A[T, T], a: T, b: T, /) -> None: ...  # type: ignore[overload-overlap]\n    @overload\n    def __init__(self: A[T, U], a: T, b: U, /) -> Never: ...\n    def __init__(self, *a) -> None: ...\n\ndef join(a: T, b: T) -> T: ...\n\nreveal_type(join(intlike(), comparable))  # N: Revealed type is \"__main__._SupportsCompare\"\nreveal_type(join(comparable, intlike()))  # N: Revealed type is \"__main__._SupportsCompare\"\nreveal_type(A(intlike(), comparable))  # N: Revealed type is \"__main__.A[__main__._SupportsCompare, __main__._SupportsCompare]\"\nreveal_type(A(comparable, intlike()))  # N: Revealed type is \"__main__.A[__main__._SupportsCompare, __main__._SupportsCompare]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testTupleJoinFallbackInference]\nfoo = [\n    (1, (\"a\", \"b\")),\n    (2, []),\n]\nreveal_type(foo)  # N: Revealed type is \"builtins.list[tuple[builtins.int, typing.Sequence[builtins.str]]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testForLoopIndexVaribaleNarrowing1]\n# flags: --local-partial-types\nfrom typing import Union\nx: Union[int, str]\nx = \"abc\"\nfor x in list[int]():\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nreveal_type(x) # N: Revealed type is \"builtins.int | builtins.str\"\n\n[case testForLoopIndexVaribaleNarrowing2]\n# flags: --enable-error-code=redundant-expr\nfrom typing import Union\nx: Union[int, str]\nx = \"abc\"\nfor x in list[int]():\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nreveal_type(x) # N: Revealed type is \"builtins.int | builtins.str\"\n\n[case testNarrowInFunctionDefer]\nfrom typing import Optional, Callable, TypeVar\n\ndef top() -> None:\n    x: Optional[int]\n    assert x is not None\n\n    def foo() -> None:\n        defer()\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nT = TypeVar(\"T\")\ndef deco(fn: Callable[[], T]) -> Callable[[], T]: ...\n\n@deco\ndef defer() -> int: ...\n\n[case testDeferMethodOfNestedClass]\nfrom typing import Optional, Callable, TypeVar\n\nclass Out:\n    def meth(self) -> None:\n        class In:\n            def meth(self) -> None:\n                reveal_type(defer())  # N: Revealed type is \"builtins.int\"\n\nT = TypeVar(\"T\")\ndef deco(fn: Callable[[], T]) -> Callable[[], T]: ...\n\n@deco\ndef defer() -> int: ...\n\n[case testVariableDeferredWithNestedFunction]\nfrom typing import Callable, TypeVar\n\nT = TypeVar(\"T\")\ndef deco(fn: Callable[[], T]) -> Callable[[], T]: ...\n\n@deco\ndef f() -> None:\n    x = 1\n    f()  # defer current node\n    x = x\n\n    def nested() -> None:\n        ...\n\n    # The type below should not be Any.\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[case testInferenceMappingTypeVarGet]\nfrom typing import Generic, TypeVar, Union\n\n_T = TypeVar(\"_T\")\n_K = TypeVar(\"_K\")\n_V = TypeVar(\"_V\")\n\nclass Mapping(Generic[_K, _V]):\n    def get(self, key: _K, default: Union[_V, _T]) -> Union[_V, _T]: ...\n\ndef check(mapping: Mapping[str, _T]) -> None:\n    ok1 = mapping.get(\"\", \"\")\n    reveal_type(ok1)  # N: Revealed type is \"_T`-1 | builtins.str\"\n    ok2: Union[_T, str] = mapping.get(\"\", \"\")\n[builtins fixtures/tuple.pyi]\n\n[case testInferWalrusAssignmentAttrInCondition]\nclass Foo:\n    def __init__(self, value: bool) -> None:\n        self.value = value\n\ndef check_and(maybe: bool) -> None:\n    foo = None\n    if maybe and (foo := Foo(True)).value:\n        reveal_type(foo)  # N: Revealed type is \"__main__.Foo\"\n    else:\n        reveal_type(foo)  # N: Revealed type is \"__main__.Foo | None\"\n\ndef check_and_nested(maybe: bool) -> None:\n    foo = None\n    bar = None\n    baz = None\n    if maybe and (foo := (bar := (baz := Foo(True)))).value:\n        reveal_type(foo)  # N: Revealed type is \"__main__.Foo\"\n        reveal_type(bar)  # N: Revealed type is \"__main__.Foo\"\n        reveal_type(baz)  # N: Revealed type is \"__main__.Foo\"\n    else:\n        reveal_type(foo)  # N: Revealed type is \"__main__.Foo | None\"\n        reveal_type(bar)  # N: Revealed type is \"__main__.Foo | None\"\n        reveal_type(baz)  # N: Revealed type is \"__main__.Foo | None\"\n\ndef check_or(maybe: bool) -> None:\n    foo = None\n    if maybe or (foo := Foo(True)).value:\n        reveal_type(foo)  # N: Revealed type is \"__main__.Foo | None\"\n    else:\n        reveal_type(foo)  # N: Revealed type is \"__main__.Foo\"\n\ndef check_or_nested(maybe: bool) -> None:\n    foo = None\n    bar = None\n    baz = None\n    if maybe and (foo := (bar := (baz := Foo(True)))).value:\n        reveal_type(foo)  # N: Revealed type is \"__main__.Foo\"\n        reveal_type(bar)  # N: Revealed type is \"__main__.Foo\"\n        reveal_type(baz)  # N: Revealed type is \"__main__.Foo\"\n    else:\n        reveal_type(foo)  # N: Revealed type is \"__main__.Foo | None\"\n        reveal_type(bar)  # N: Revealed type is \"__main__.Foo | None\"\n        reveal_type(baz)  # N: Revealed type is \"__main__.Foo | None\"\n\n[case testInferWalrusAssignmentIndexInCondition]\ndef check_and(maybe: bool) -> None:\n    foo = None\n    bar = None\n    if maybe and (foo := [1])[(bar := 0)]:\n        reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.int]\"\n        reveal_type(bar)  # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.int] | None\"\n        reveal_type(bar)  # N: Revealed type is \"builtins.int | None\"\n\ndef check_and_nested(maybe: bool) -> None:\n    foo = None\n    bar = None\n    baz = None\n    if maybe and (foo := (bar := (baz := [1])))[0]:\n        reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.int]\"\n        reveal_type(bar)  # N: Revealed type is \"builtins.list[builtins.int]\"\n        reveal_type(baz)  # N: Revealed type is \"builtins.list[builtins.int]\"\n    else:\n        reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.int] | None\"\n        reveal_type(bar)  # N: Revealed type is \"builtins.list[builtins.int] | None\"\n        reveal_type(baz)  # N: Revealed type is \"builtins.list[builtins.int] | None\"\n\ndef check_or(maybe: bool) -> None:\n    foo = None\n    bar = None\n    if maybe or (foo := [1])[(bar := 0)]:\n        reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.int] | None\"\n        reveal_type(bar)  # N: Revealed type is \"builtins.int | None\"\n    else:\n        reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.int]\"\n        reveal_type(bar)  # N: Revealed type is \"builtins.int\"\n\ndef check_or_nested(maybe: bool) -> None:\n    foo = None\n    bar = None\n    baz = None\n    if maybe or (foo := (bar := (baz := [1])))[0]:\n        reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.int] | None\"\n        reveal_type(bar)  # N: Revealed type is \"builtins.list[builtins.int] | None\"\n        reveal_type(baz)  # N: Revealed type is \"builtins.list[builtins.int] | None\"\n    else:\n        reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.int]\"\n        reveal_type(bar)  # N: Revealed type is \"builtins.list[builtins.int]\"\n        reveal_type(baz)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\n[case testInferOptionalAgainstAny]\nfrom typing import Any, Optional, TypeVar\n\na: Any\noa: Optional[Any]\nT = TypeVar(\"T\")\ndef f(x: Optional[T]) -> T: ...\nreveal_type(f(a))  # N: Revealed type is \"Any\"\nreveal_type(f(oa))  # N: Revealed type is \"Any\"\n\n[case testNoCrashOnPartialTypeAsContext]\nfrom typing import overload, TypeVar, Optional, Protocol\n\nT = TypeVar(\"T\")\nclass DbManager(Protocol):\n    @overload\n    def get(self, key: str) -> Optional[T]:\n        pass\n\n    @overload\n    def get(self, key: str, default: T) -> T:\n        pass\n\nclass Foo:\n    def __init__(self, db: DbManager, bar: bool) -> None:\n        if bar:\n            self.qux = db.get(\"qux\")\n        else:\n            self.qux = {}  # E: Need type annotation for \"qux\" (hint: \"qux: dict[<type>, <type>] = ...\")\n[builtins fixtures/dict.pyi]\n\n[case testConstraintSolvingFailureShowsCorrectArgument]\nfrom typing import Callable, TypeVar\n\nT1 = TypeVar('T1')\nT2 = TypeVar('T2')\ndef foo(\n    a: T1,\n    b: T2,\n    c: Callable[[T2], T2],\n) -> tuple[T1, T2]: ...\n\ndef bar(y: float) -> float: ...\n\nfoo(1, None, bar)  # E: Cannot infer value of type parameter \"T2\" of \"foo\"\n[builtins fixtures/tuple.pyi]\n\n[case testGlobalVariableNoneInitMultipleFuncs]\nx = None\n\ndef f() -> None:\n    global x\n    reveal_type(x)  # N: Revealed type is \"None\"\n    x = 1\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\ndef g() -> None:\n    global x\n    reveal_type(x)  # N: Revealed type is \"builtins.int | None\"\n    x = \"\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int | None\")\n    reveal_type(x)  # N: Revealed type is \"builtins.int | None\"\n\n[case testGlobalVariableNoneInitMultipleFuncsRedefine]\n# flags: --allow-redefinition-new --local-partial-types\n\n# Widening this is intentionally prohibited (for now).\nx = None\n\ndef f() -> None:\n    global x\n    reveal_type(x)  # N: Revealed type is \"None\"\n    x = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"None\")\n    reveal_type(x)  # N: Revealed type is \"None\"\n\ndef g() -> None:\n    global x\n    reveal_type(x)  # N: Revealed type is \"None\"\n    x = \"\"  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"None\")\n    reveal_type(x)  # N: Revealed type is \"None\"\n"
  },
  {
    "path": "test-data/unit/check-inline-config.test",
    "content": "-- Checks for 'mypy: option' directives inside files\n\n[case testInlineSimple1]\n\n# mypy: disallow-any-generics, no-warn-no-return\n\nfrom typing import List, Optional\ndef foo() -> Optional[List]:  # E: Missing type arguments for generic type \"List\"\n    20\n\n[builtins fixtures/list.pyi]\n\n[case testInlineSimple2]\n\n# mypy: disallow-any-generics\n# mypy: no-warn-no-return\n\nfrom typing import List, Optional\ndef foo() -> Optional[List]:  # E: Missing type arguments for generic type \"List\"\n    20\n\n[builtins fixtures/list.pyi]\n\n[case testInlineSimple3]\n\n# mypy: disallow-any-generics=true, warn-no-return=0\n\nfrom typing import List, Optional\ndef foo() -> Optional[List]:  # E: Missing type arguments for generic type \"List\"\n    20\n\n[builtins fixtures/list.pyi]\n\n\n[case testInlineSimple4]\n\n# mypy: disallow-any-generics = true, warn-no-return = 0\n\nfrom typing import List, Optional\ndef foo() -> Optional[List]:  # E: Missing type arguments for generic type \"List\"\n    20\n\n[builtins fixtures/list.pyi]\n\n[case testInlineList]\n\n# mypy: disallow-any-generics,always-false=\"FOO,BAR\"\n\nfrom typing import List\n\ndef foo(FOO: bool, BAR: bool) -> List:  # E: Missing type arguments for generic type \"List\"\n    if FOO or BAR:\n        1+'lol'\n    return []\n\n[builtins fixtures/list.pyi]\n\n[case testInlineInvert1]\n# flags: --disallow-any-generics --allow-untyped-globals\nimport a\n[file a.py]\n# mypy: allow-any-generics, disallow-untyped-globals\n\nx = []  # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n\nfrom typing import List\ndef foo() -> List:\n    ...\n\n[builtins fixtures/list.pyi]\n\n[case testInlineInvert2]\n\nimport a\n[file a.py]\n# mypy: no-always-true\n\n[out]\ntmp/a.py:1: error: Can not invert non-boolean key always_true\n\n[case testInlineIncremental1]\n\nimport a\n[file a.py]\n# mypy: disallow-any-generics, no-warn-no-return\n\nfrom typing import List, Optional\ndef foo() -> Optional[List]:\n    20\n\n[file a.py.2]\n# mypy: no-warn-no-return\n\nfrom typing import List, Optional\ndef foo() -> Optional[List]:\n    20\n\n[file a.py.3]\nfrom typing import List, Optional\ndef foo() -> Optional[List]:\n    20\n[out]\ntmp/a.py:4: error: Missing type arguments for generic type \"List\"\n[out2]\n[out3]\ntmp/a.py:2: error: Missing return statement\n\n[builtins fixtures/list.pyi]\n\n[case testInlineIncremental2]\n\n# flags2: --disallow-any-generics\nimport a\n[file a.py]\n# mypy: no-warn-no-return\n\nfrom typing import Optional, List\ndef foo() -> Optional[List]:\n    20\n\n[file b.py.2]\n# no changes to a.py, but flag change should cause recheck\n\n[out]\n[out2]\ntmp/a.py:4: error: Missing type arguments for generic type \"List\"\n\n[builtins fixtures/list.pyi]\n\n[case testInlineIncremental3]\nimport a, b\n[file a.py]\n# mypy: no-warn-no-return\nfrom typing import Optional\n\ndef foo() -> Optional[int]:\n    20\n\n[file b.py]\n[file b.py.2]\n# no changes to a.py and we want to make sure it isn't rechecked\n[out]\n[out2]\n[rechecked b]\n\n[case testInlineError1]\n# mypy: invalid-whatever\n# mypy: no-warn-no-return; no-strict-optional\n# mypy: always-true=FOO,BAR\n# mypy: always-true=\"FOO,BAR\n[out]\nmain:1: error: Unrecognized option: invalid_whatever = True\nmain:2: error: Unrecognized option: no_warn_no_return; no_strict_optional = True\nmain:3: error: Unrecognized option: bar = True\nmain:4: error: Unterminated quote in configuration comment\n\n[case testInlineError2]\n# mypy: skip-file\n[out]\nmain:1: error: Unrecognized option: skip_file = True\n\n[case testInlineStrict]\n# mypy: strict\n[out]\nmain:1: error: Setting \"strict\" not supported in inline configuration: specify it in a configuration file instead, or set individual inline flags (see \"mypy -h\" for the list of flags enabled in strict mode)\n\n[case testInlineErrorCodes]\n# mypy: enable-error-code=\"ignore-without-code,truthy-bool\"\nclass Foo:\n    pass\n\nfoo = Foo()\nif foo: ...  # E: \"__main__.foo\" has type \"Foo\" which does not implement __bool__ or __len__ so it could always be true in boolean context\n42 + \"no\"  # type: ignore  # E: \"type: ignore\" comment without error code (consider \"type: ignore[operator]\" instead)\n\n[case testInlineErrorCodesOverrideConfig]\n# flags: --config-file tmp/mypy.ini\nimport foo\nimport tests.bar\nimport tests.baz\n[file foo.py]\n# mypy: disable-error-code=\"truthy-bool\"\nclass Foo:\n    pass\n\nfoo = Foo()\nif foo: ...\n42 + \"no\"  # type: ignore  # E: \"type: ignore\" comment without error code (consider \"type: ignore[operator]\" instead)\n\n[file tests/__init__.py]\n[file tests/bar.py]\n# mypy: enable-error-code=\"ignore-without-code\"\n\ndef foo() -> int: ...\nif foo: ...  # E: Function \"foo\" could always be true in boolean context\n42 + \"no\"  # type: ignore  # E: \"type: ignore\" comment without error code (consider \"type: ignore[operator]\" instead)\n\n[file tests/baz.py]\n# mypy: disable-error-code=\"truthy-bool\"\nclass Foo:\n    pass\n\nfoo = Foo()\nif foo: ...\n42 + \"no\"  # type: ignore\n\n[file mypy.ini]\n\\[mypy]\nenable_error_code = ignore-without-code, truthy-bool\n\n\\[mypy-tests.*]\ndisable_error_code = ignore-without-code\n\n[case testInlineErrorCodesOverrideConfigSmall]\n# flags: --config-file tmp/mypy.ini\nimport tests.baz\n[file tests/__init__.py]\n[file tests/baz.py]\n42 + \"no\"  # type: ignore\n\n[file mypy.ini]\n\\[mypy]\nenable_error_code = ignore-without-code, truthy-bool\n\n\\[mypy-tests.*]\ndisable_error_code = ignore-without-code\n\n[case testInlineErrorCodesOverrideConfigSmall2]\n# flags: --config-file tmp/mypy.ini\nimport tests.bar\nimport tests.baz\n[file tests/__init__.py]\n[file tests/baz.py]\n42 + \"no\"  # type: ignore\n[file tests/bar.py]\n# mypy: enable-error-code=\"ignore-without-code\"\n\ndef foo() -> int: ...\nif foo: ...  # E: Function \"foo\" could always be true in boolean context\n42 + \"no\"  # type: ignore  # E: \"type: ignore\" comment without error code (consider \"type: ignore[operator]\" instead)\n\n[file mypy.ini]\n\\[mypy]\nenable_error_code = ignore-without-code, truthy-bool\n\n\\[mypy-tests.*]\ndisable_error_code = ignore-without-code\n\n\n[case testInlineErrorCodesOverrideConfigSmallBackward]\n# flags: --config-file tmp/mypy.ini\nimport tests.bar\nimport tests.baz\n[file tests/__init__.py]\n[file tests/baz.py]\n42 + \"no\"  # type: ignore # E: \"type: ignore\" comment without error code (consider \"type: ignore[operator]\" instead)\n[file tests/bar.py]\n# mypy: disable-error-code=\"ignore-without-code\"\n42 + \"no\"  # type: ignore\n\n[file mypy.ini]\n\\[mypy]\nenable_error_code = ignore-without-code, truthy-bool\n\n\\[mypy-tests.*]\nenable_error_code = ignore-without-code\n\n[case testInlineOverrideConfig]\n# flags: --config-file tmp/mypy.ini\nimport foo\nimport tests.bar\nimport tests.baz\n[file foo.py]\n# mypy: disable-error-code=\"truthy-bool\"\nclass Foo:\n    pass\n\nfoo = Foo()\nif foo: ...\n42 # type: ignore  # E: Unused \"type: ignore\" comment\n\n[file tests/__init__.py]\n[file tests/bar.py]\n# mypy: warn_unused_ignores\n\ndef foo() -> int: ...\nif foo: ...  # E: Function \"foo\" could always be true in boolean context\n42 # type: ignore  # E: Unused \"type: ignore\" comment\n\n[file tests/baz.py]\n# mypy: disable-error-code=\"truthy-bool\"\nclass Foo:\n    pass\n\nfoo = Foo()\nif foo: ...\n42 # type: ignore\n\n[file mypy.ini]\n\\[mypy]\nwarn_unused_ignores = True\n\n\\[mypy-tests.*]\nwarn_unused_ignores = False\n\n\n[case testIgnoreErrorsSimple]\n# mypy: ignore-errors=True\n\ndef f() -> None:\n    while 1():\n        pass\n\n[case testIgnoreErrorsInImportedModule]\nfrom m import C\nc = C()\nreveal_type(c.x)  # N: Revealed type is \"builtins.int\"\n\n[file m.py]\n# mypy: ignore-errors=True\n\nclass C:\n    def f(self) -> None:\n        self.x = 1\n\n[case testIgnoreErrorsWithLambda]\n# mypy: ignore-errors=True\n\ndef f(self, x=lambda: 1) -> None:\n    pass\n\nclass C:\n    def f(self) -> None:\n        l = lambda: 1\n        self.x = 1\n\n[case testIgnoreErrorsWithUnsafeSuperCall_no_empty]\n\nfrom m import C\n\nclass D(C):\n    def m(self) -> None:\n        super().m1()\n        super().m2() \\\n            # E: Call to abstract method \"m2\" of \"C\" with trivial body via super() is unsafe\n        super().m3() \\\n            # E: Call to abstract method \"m3\" of \"C\" with trivial body via super() is unsafe\n        super().m4() \\\n            # E: Call to abstract method \"m4\" of \"C\" with trivial body via super() is unsafe\n        super().m5() \\\n            # E: Call to abstract method \"m5\" of \"C\" with trivial body via super() is unsafe\n        super().m6() \\\n            # E: Call to abstract method \"m6\" of \"C\" with trivial body via super() is unsafe\n        super().m7()\n\n    def m1(self) -> int:\n        return 0\n\n    def m2(self) -> int:\n        return 0\n\n    def m3(self) -> int:\n        return 0\n\n    def m4(self) -> int:\n        return 0\n\n    def m5(self) -> int:\n        return 0\n\n    def m6(self) -> int:\n        return 0\n\n[file m.py]\n# mypy: ignore-errors=True\nimport abc\n\nclass C:\n    @abc.abstractmethod\n    def m1(self) -> int:\n        \"\"\"x\"\"\"\n        return 0\n\n    @abc.abstractmethod\n    def m2(self) -> int:\n        \"\"\"doc\"\"\"\n\n    @abc.abstractmethod\n    def m3(self) -> int:\n        pass\n\n    @abc.abstractmethod\n    def m4(self) -> int: ...\n\n    @abc.abstractmethod\n    def m5(self) -> int:\n        \"\"\"doc\"\"\"\n        ...\n\n    @abc.abstractmethod\n    def m6(self) -> int:\n        raise NotImplementedError()\n\n    @abc.abstractmethod\n    def m7(self) -> int:\n        raise NotImplementedError()\n        pass\n\n[builtins fixtures/exception.pyi]\n\n[case testInlineErrorCodesMultipleCodes]\n# mypy: disable-error-code=\"truthy-bool, ignore-without-code\"\nclass Foo:\n    pass\n\nfoo = Foo()\nif foo: ...\n42 + \"no\"  # type: ignore\n\n[case testInlinePythonVersion]\n# mypy: python-version=3.10  # E: python_version not supported in inline configuration\n\n[case testInlineErrorCodesArentRuinedByOthersBaseCase]\n# mypy: disable-error-code=name-defined\na\n\n[case testInlineErrorCodesArentRuinedByOthersInvalid]\n# mypy: disable-error-code=name-defined\n# mypy: AMONGUS\na\n[out]\nmain:2: error: Unrecognized option: amongus = True\n\n[case testInlineErrorCodesArentRuinedByOthersInvalidBefore]\n# mypy: AMONGUS\n# mypy: disable-error-code=name-defined\na\n[out]\nmain:1: error: Unrecognized option: amongus = True\n\n[case testInlineErrorCodesArentRuinedByOthersSe]\n# mypy: disable-error-code=name-defined\n# mypy: strict-equality\ndef is_magic(x: bytes) -> bool:\n    y\n    return x == 'magic' # E: Unsupported left operand type for == (\"bytes\")\n\n[case testInlineConfigErrorCodesOffAndOn]\n# mypy: disable-error-code=name-defined\n# mypy: enable-error-code=name-defined\na # E: Name \"a\" is not defined\n\n[case testInlineConfigErrorCodesOnAndOff]\n# mypy: enable-error-code=name-defined\n# mypy: disable-error-code=name-defined\na # E: Name \"a\" is not defined\n\n[case testConfigFileErrorCodesOnAndOff]\n# flags: --config-file tmp/mypy.ini\nimport foo\n[file foo.py]\n42 + \"no\"  # type: ignore  # E: \"type: ignore\" comment without error code (consider \"type: ignore[operator]\" instead)\n[file mypy.ini]\n\\[mypy]\nenable_error_code = ignore-without-code\ndisable_error_code = ignore-without-code\n\n[case testInlineConfigBaseCaseWui]\n# mypy: warn_unused_ignores\nx = 1 # type: ignore # E: Unused \"type: ignore\" comment\n\n[case testInlineConfigIsntRuinedByOthersInvalidWui]\n# mypy: warn_unused_ignores\n# mypy: AMONGUS\nx = 1 # type: ignore # E: Unused \"type: ignore\" comment\n[out]\nmain:2: error: Unrecognized option: amongus = True\n"
  },
  {
    "path": "test-data/unit/check-isinstance.test",
    "content": "[case testForcedAssignment]\n# flags: --warn-unreachable\nx = 1 # type: object\ny = 1\ndef f(): x, y  # Prevent independent redefinition\ny = x # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\nx = 2\ny = x\n[builtins fixtures/tuple.pyi]\n\n[case testJoinAny]\n# flags: --warn-unreachable\nfrom typing import List, Any\n\nx: List[Any]\n\ndef foo() -> List[int]: pass\ndef bar() -> List[str]: pass\n\nif bool():\n    x = foo()\nelse:\n    x = bar()\n\nx * 2\n[builtins fixtures/list.pyi]\n\n[case testGeneratorExpressionTypes]\n# flags: --warn-unreachable\nclass A: y = 1\nx = [A()]\ny = [x]\n\nz = [1,2]\nz = [a.y for b in y for a in b]\n[builtins fixtures/list.pyi]\n\n[case testIsinstanceNestedTuple]\n# flags: --warn-unreachable\nfrom typing import Union, List, Tuple, Dict\n\ndef f(x: Union[int, str, List]) -> None:\n    if isinstance(x, (str, (int,))):\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n        x[1]  # E: Value of type \"int | str\" is not indexable\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\n        x[1]\n    reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | builtins.list[Any]\"\n    if isinstance(x, (str, (list,))):\n        reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.list[Any]\"\n        x[1]\n    reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | builtins.list[Any]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testClassAttributeInitialization]\n# flags: --warn-unreachable\nclass A:\n    x: int\n    def __init__(self) -> None:\n        self.y: int\n        z = self.x\n        w = self.y\n\n[case testAssignmentSubtypes]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo(x: Union[str, int]):\n    if isinstance(x, int):\n        x = 'a'\n    x + 'a'\n    z = x\n    y = [x]\n    y[0] + 'a'\n    # TODO: should we allow these two lines?\n    y + [1]  # E: List item 0 has incompatible type \"int\"; expected \"str\"\n    z = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\nx: int\ny = [x]\n[builtins fixtures/isinstancelist.pyi]\n\n[case testFunctionDefaultArgs]\n# flags: --warn-unreachable\nclass A: pass\nclass B(A): y = 1\n\nx =  A()\n\ndef foo(x: A = B()):\n    x.y   # E: \"A\" has no attribute \"y\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceFancyConditionals]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    y = 1\n\nx =  A()\nif isinstance(x, B):\n    x.y\nwhile isinstance(x, B):\n    x.y\nwhile isinstance(x, B):\n    x.y\n    x = B()\n[builtins fixtures/isinstance.pyi]\n\n[case testSubtypingWithAny]\n# flags: --warn-unreachable\nclass A:\n    y = 1\n\nclass B(A):\n    z = 1\n\ndef foo(): pass\n\nx = A()\nif int():\n    x = B()\n    x.z\n    x = foo()\n    reveal_type(x)  # N: Revealed type is \"Any\"\nreveal_type(x)  # N: Revealed type is \"__main__.A\"\n\n[case testSingleMultiAssignment]\n# flags: --warn-unreachable\nx = 'a'\n(x,) = ('a',)\n\n[case testUnionMultiAssignment]\n# flags: --warn-unreachable\nfrom typing import Union\nx: Union[int, str]\nif int():\n    x = 1\n    x = 'a'\n    x + 1    # E: Unsupported operand types for + (\"str\" and \"int\")\n    x = 1\n    (x, y) = ('a', 1)\n    x + 1    # E: Unsupported operand types for + (\"str\" and \"int\")\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnionIfZigzag]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef f(x: Union[int, str]) -> None:\n    if 1: # Without this, the assignment below could create a new variable \"x\" of type \"int\"\n        x = 1\n        if x:\n            x = 'a'\n            x = 1\n        x + 1\n    x + 1\n[builtins fixtures/isinstancelist.pyi]\n\n[case testTwoLoopsUnion]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\ndef bar() -> None:\n    x = foo()\n    if isinstance(x, int):\n        return\n    while bool():\n        x + 'a'\n        while bool():\n            x = foo()\n            if bool():\n                return\n            x = 'a'\n    x + 'a'\n[builtins fixtures/isinstancelist.pyi]\n\n[case testComplicatedBlocks]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\ndef bar() -> None:\n    x = foo()\n    if isinstance(x, int):\n        return\n    while bool():\n        x + 'a'\n        while bool():\n            x = foo()\n            if bool():\n                return\n            x = 'a'\n    x + 'a'\n\n    x = foo()\n    if isinstance(x, int):\n        return\n    while bool():\n        x + 'a'\n        while bool():\n            x + 'a'         # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                            # N: Left operand is of type \"int | str\"\n            x = foo()\n            if bool():\n                continue\n            x = 'a'\n        x = 'a'\n    x + 'a'\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnionTryExcept]\n# flags: --warn-unreachable\nclass A:\n    y = A()\n\nclass B(A):\n    z = 1\n\nx = A()\ndef f(): x # Prevent redefinition of x\nx = B()\nx.z\ntry:\n    x.z\n    x = A()\n    x = B()\n    x.z\nexcept:\n    pass\nx.z           # E: \"A\" has no attribute \"z\"\n\n[case testUnionTryExcept2]\n# flags: --warn-unreachable\nclass A:\n    y = A()\n\nclass B(A):\n    z = 1\n\nx = A()\ntry:\n    x.z # E: \"A\" has no attribute \"z\"\n    x = A()\n    x = B()\n    x.z\nexcept:\n    x.z # E: \"A\" has no attribute \"z\"\n    x = B()\n    x.z\nelse:\n    x = B()\nx.z\n\n[case testUnionTryExcept3]\n# flags: --warn-unreachable\nclass A:\n    y = A()\n\nclass B(A):\n    z = 1\n\nx = A()\ndef f(): x # Prevent redefinition of x\nx = B()\ntry:\n    raise BaseException()\n    x = A()  # E: Statement is unreachable\nexcept:\n    pass\nx.z\nx = B()\ntry:\n    x = A()\n    raise BaseException()\nexcept:\n    pass\nx.z           # E: \"A\" has no attribute \"z\"\nx = B()\ntry:\n    pass\nexcept:\n    x = A()\n    raise BaseException()\nx.z\ntry:\n    x = A()\nexcept:\n    pass\nx.z           # E: \"A\" has no attribute \"z\"\nx = B()\ntry:\n    pass\nexcept:\n    x = A()\nx.z           # E: \"A\" has no attribute \"z\"\n[builtins fixtures/exception.pyi]\n\n[case testUnionTryExcept4]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    z = 1\n\nx = A()\nwhile bool():\n    try:\n        x.z # E: \"A\" has no attribute \"z\"\n        x = A()\n    except:\n        x = B()\n    else:\n        x = B()\n    x.z\n[builtins fixtures/exception.pyi]\n\n[case testUnionTryFinally]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    b = 1\n\nx = A()\ndef f(): x  # Prevent redefinition\nx = B()\ntry:\n    x = A()\n    x.b # E: \"A\" has no attribute \"b\"\n    x = B()\nfinally:\n    x.b  # E: \"A\" has no attribute \"b\"\nx.b\n\n[case testUnionTryFinally2]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    b = 1\n\nx = A()\ndef f(): x  # Prevent redefinition\nx = B()\ntry:\n    x = A()\n    x = B()\nexcept:\n    pass\nfinally:\n    pass\nx.b      # E: \"A\" has no attribute \"b\"\n\n[case testUnionTryFinally3]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    b = 1\n\nx = A()\ndef f(): x  # Prevent redefinition\nx = B()\ntry:\n    x = A()\n    x = B()\nexcept:\n    pass\nfinally:\n    x = B()\nx.b\n\n[case testUnionTryFinally4]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    b = 1\n\nwhile 2:\n    x = A()\n    def f(): x  # Prevents redefinition\n    x = B()\n    try:\n        x = A()\n        x = B()\n    except:\n        pass\n    finally:\n        x.b     # E: \"A\" has no attribute \"b\"\n        if not isinstance(x, B):\n            break\n    x.b\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnionTryFinally5]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    b = 1\n\nwhile 2:\n    x = A()\n    try:\n        x = A()\n        x = B()\n    finally:\n        x.b    # E: \"A\" has no attribute \"b\"\n        break\n        x.b  # E: Statement is unreachable\n    x.b  # E: Statement is unreachable\n\n[case testUnionTryFinally6]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    b = 1\n\ndef f() -> int:\n    x = B()  # type: A\n    try:\n        x = B()\n    except:\n        x = A()\n        # An exception could occur here\n        x = B()\n    finally:\n        return x.b # E: \"A\" has no attribute \"b\"\n\n[case testUnionListIsinstance]\n# flags: --warn-unreachable\nfrom typing import Union, List\n\ndef f(x: Union[List[int], List[str], int]) -> None:\n    if isinstance(x, list):\n        a = x[0]\n        if isinstance(a, int):\n            a + 1\n            a + 'x' # E: Unsupported operand types for + (\"int\" and \"str\")\n\n        # type of a?\n        reveal_type(x) # N: Revealed type is \"builtins.list[builtins.int] | builtins.list[builtins.str]\"\n        x + 1 # E: Unsupported operand types for + (\"list[int]\" and \"int\") \\\n              # E: Unsupported operand types for + (\"list[str]\" and \"int\") \\\n              # N: Left operand is of type \"list[int] | list[str]\"\n    else:\n        x[0] # E: Value of type \"int\" is not indexable\n        x + 1\n    x[0] # E: Value of type \"list[int] | list[str] | int\" is not indexable\n    x + 1 # E: Unsupported operand types for + (\"list[int]\" and \"int\") \\\n          # E: Unsupported operand types for + (\"list[str]\" and \"int\") \\\n          # N: Left operand is of type \"list[int] | list[str] | int\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnionListIsinstance2]\n# flags: --warn-unreachable\nfrom typing import Union, List\n\nclass A:\n    a = 1\n\nclass B: pass\nclass C: pass\n\ndef g(x: Union[A, B]) -> A: pass\ndef h(x: C) -> A: pass\ndef f(x: Union[A, B, C]) -> None:\n    if isinstance(x, C):\n        x = h(x)\n    else:\n        x = g(x)\n    x.a\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnionStrictDefnBasic]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\nx = foo()\nif int():\n    x = 1\n    x = x + 1\n    x = foo()\n    x = x + 1                # E: Unsupported operand types for + (\"str\" and \"int\") \\\n                             # N: Left operand is of type \"int | str\"\nif isinstance(x, str):\n   x = x + 1             # E: Unsupported operand types for + (\"str\" and \"int\")\n   x = 1\n   x = x + 1\n[builtins fixtures/isinstancelist.pyi]\n\n[case testSubtypeRedefinitionBasic]\n# flags: --warn-unreachable\nfrom typing import Union\n\nclass A: pass\n\nclass B(A):\n    y = 1\n\nx = A()\nx.y        # E: \"A\" has no attribute \"y\"\nx = B()\nx.y        # OK: x is known to be a B\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceBasic]\n# flags: --warn-unreachable\nfrom typing import Union\nx: Union[int, str]\nif isinstance(x, str):\n    x = x + 1   # E: Unsupported operand types for + (\"str\" and \"int\")\n    x = x + 'a'\nelse:\n    x = x + 'a' # E: Unsupported operand types for + (\"int\" and \"str\")\n    x = x + 1\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceIndexing]\n# flags: --warn-unreachable\nfrom typing import Union\nx: Union[int, str]\nj = [x]\nif isinstance(j[0], str):\n    j[0] = j[0] + 'a'\n    j[0] = j[0] + 1   # E: Unsupported operand types for + (\"str\" and \"int\")\nelse:\n    j[0] = j[0] + 'a' # E: Unsupported operand types for + (\"int\" and \"str\")\n    j[0] = j[0] + 1\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceSubClassMember]\n# flags: --warn-unreachable\nfrom typing import Union\n\nclass Animal: pass\n\nclass Dog(Animal):\n    paws = 4  # type: Union[int, str]\n\n    def bark(self): pass\n\nclass House:\n    pet: Animal\n\nh = House()\nh.pet = Dog()\n\nwhile bool():\n    if isinstance(h.pet, Dog):\n        if isinstance(h.pet.paws, str):\n            x = h.pet.paws + 'a'\n        y = h.pet.paws + 1   # E: Unsupported operand types for + (\"str\" and \"int\") \\\n                             # N: Left operand is of type \"int | str\"\n        z = h.pet.paws + 'a' # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                             # N: Left operand is of type \"int | str\"\n        if isinstance(h.pet.paws, str):\n            x = h.pet.paws + 'a'\n            break\n        y = h.pet.paws + 1\n        z = h.pet.paws + 'a' # E: Unsupported operand types for + (\"int\" and \"str\")\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceSubClassReset]\n# flags: --warn-unreachable\nclass A:\n    pass\n\nclass B(A):\n    b = 1\n\nclass C:\n    a = A()\n\nx = C()\nx.a.b                   # E: \"A\" has no attribute \"b\"\nif isinstance(x.a, B):\n    x.a.b\n    x = C()\n    x.a.b               # E: \"A\" has no attribute \"b\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceTuple]\n# flags: --warn-unreachable\nfrom typing import Union\n\nclass A: pass\n\nclass B:\n    def method2(self, arg: int):\n        return 123\n\nclass C:\n    def method2(self, arg: int):\n        return 456\n\n    def method3(self, arg: str):\n        return 'abc'\n\nv = A() # type: Union[A, B, C]\n\nif isinstance(v, (B, C)):\n    v.method2(123)\n    v.method3('xyz') # E: Item \"B\" of \"B | C\" has no attribute \"method3\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceNeverWidens]\n# flags: --warn-unreachable\nfrom typing import Union\n\nclass A: pass\nclass B: pass\nclass C: pass\n\na = A()  # type: A\nassert isinstance(a, (A, B))\nreveal_type(a)  # N: Revealed type is \"__main__.A\"\n\nb = A()  # type: Union[A, B]\nassert isinstance(b, (A, B, C))\nreveal_type(b)  # N: Revealed type is \"__main__.A | __main__.B\"\n[builtins fixtures/isinstance.pyi]\n\n[case testMemberAssignmentChanges]\n# flags: --warn-unreachable\nfrom typing import Union\n\nclass Dog:\n    paws = 1  # type: Union[int, str]\n\npet = Dog()\n\npet.paws + 'a'  # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                # N: Left operand is of type \"int | str\"\npet.paws = 'a'\npet.paws + 'a'\npet.paws = 1\npet.paws + 1\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceSubClassMemberHard]\n# flags: --warn-unreachable\nfrom typing import Union\n\nclass Animal:\n    pass\n\nclass Dog(Animal):\n    paws = 4  # type: Union[int, str]\n\n    def bark(self): pass\n\nclass House:\n    pet: Animal\n\nh = House()\nh.pet = Dog()\n\nif isinstance(h.pet, Dog):\n    if isinstance(h.pet.paws, str):\n        for i in [1]:\n            # TODO: should we allow this if iterable is of length one or zero?\n            h.pet.paws + 'a'  # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                              # N: Left operand is of type \"int | str\"\n            if bool():\n                break\n            h.pet.paws = 1\n            h.pet.paws + 1\n\n    if isinstance(h.pet.paws, str):\n        h.pet.paws + 'a'\n    else:\n        h.pet.paws + 1\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceReturn]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> None:\n    x = 1 # type: Union[int, str]\n    if isinstance(x, int):\n        return\n    y = x + 'asdad'\n\ndef bar() -> None:\n    x = 1 # type: Union[int, str]\n    if isinstance(x, int):\n        return\n    else:\n        pass\n    y = x + 'asdad'\n\nfoo()\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceBadBreak]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> None:\n    x: Union[int, str]\n    if isinstance(x, int):\n        for z in [1,2]:\n            break\n    else:\n        pass\n    y = x + 'asdad'    # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                       # N: Left operand is of type \"int | str\"\n\nfoo()\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceThreeUnion]\n# flags: --warn-unreachable\nfrom typing import Union, List\n\nx: Union[int, str, List[int]]\n\nwhile bool():\n    if isinstance(x, int):\n        x + 1\n    elif isinstance(x, str):\n        x + 'a'\n    else:\n        x + [1]\n    x + 'a'           # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                      # E: Unsupported operand types for + (\"list[int]\" and \"str\") \\\n                      # N: Left operand is of type \"int | str | list[int]\"\n\nx + [1]               # E: Unsupported operand types for + (\"int\" and \"list[int]\") \\\n                      # E: Unsupported operand types for + (\"str\" and \"list[int]\") \\\n                      # N: Left operand is of type \"int | str | list[int]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceThreeUnion2]\n# flags: --warn-unreachable\nfrom typing import Union, List\nx: Union[int, str, List[int]]\nwhile bool():\n    if isinstance(x, int):\n        x + 1\n        break\n    elif isinstance(x, str):\n        x + 'a'\n        break\n    x + [1]\n    x + 'a'           # E: Unsupported operand types for + (\"list[int]\" and \"str\")\nx + [1]               # E: Unsupported operand types for + (\"int\" and \"list[int]\") \\\n                      # E: Unsupported operand types for + (\"str\" and \"list[int]\") \\\n                      # N: Left operand is of type \"int | str | list[int]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceThreeUnion3]\n# flags: --warn-unreachable\nfrom typing import Union, List\n\nwhile bool():\n    x: Union[int, str, List[int]]\n    def f(): x  # Prevent redefinition\n    x = 1\n    if isinstance(x, int):\n        x + 1\n        break\n    elif isinstance(x, str):  # E: Statement is unreachable\n        x + 'a'\n        break\n    x + [1]           # These lines aren't reached because x was an int  # E: Statement is unreachable\n    x + 'a'\nx + [1]               # E: Unsupported operand types for + (\"int\" and \"list[int]\") \\\n                      # E: Unsupported operand types for + (\"str\" and \"list[int]\") \\\n                      # N: Left operand is of type \"int | str | list[int]\"\n\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testRemovingTypeRepeatedly]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\nfor i in [1, 2]:\n    x = foo()\n    x + 'a'                 # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                            # N: Left operand is of type \"int | str\"\n    if isinstance(x, int):\n        break\n    x + 'a'\n\n    x = foo()\n    x + 'a'                 # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                            # N: Left operand is of type \"int | str\"\n    if isinstance(x, int):\n        break\n    x + 'a'\n\n    x = foo()\n    x + 'a'                 # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                            # N: Left operand is of type \"int | str\"\n    if isinstance(x, int):\n        break\n    x + 'a'\n\nx + 'a'                    # E: Unsupported operand types for + (\"int\" and \"str\") \\\n                           # N: Left operand is of type \"int | str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyRepeatedly]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\nx = foo()\ndef f(): x  # Prevent redefinition\nx + 1     # E: Unsupported operand types for + (\"str\" and \"int\") \\\n          # N: Left operand is of type \"int | str\"\nx + 'a'   # E: Unsupported operand types for + (\"int\" and \"str\") \\\n          # N: Left operand is of type \"int | str\"\n\nx = 1\nx + 1\nx + 'a'   # E: Unsupported operand types for + (\"int\" and \"str\")\n\nx = 'a'\nx + 1     # E: Unsupported operand types for + (\"str\" and \"int\")\nx + 'a'\n\nx = foo()\nx + 1     # E: Unsupported operand types for + (\"str\" and \"int\") \\\n          # N: Left operand is of type \"int | str\"\nx + 'a'   # E: Unsupported operand types for + (\"int\" and \"str\") \\\n          # N: Left operand is of type \"int | str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoop]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\nx = foo()\ndef f(): x  # Prevent redefinition\nx + 1      # E: Unsupported operand types for + (\"str\" and \"int\") \\\n           # N: Left operand is of type \"int | str\"\nx = 'a'\nx + 1      # E: Unsupported operand types for + (\"str\" and \"int\")\nx = 1\nx + 1\n\nwhile bool():\n      x + 1    # E: Unsupported operand types for + (\"str\" and \"int\") \\\n               # N: Left operand is of type \"int | str\"\n      x = 'a'\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoop2]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\nx = foo()\ndef f(): x  # Prevent redefinition\nx + 1      # E: Unsupported operand types for + (\"str\" and \"int\") \\\n           # N: Left operand is of type \"int | str\"\nx = 'a'\nx + 1      # E: Unsupported operand types for + (\"str\" and \"int\")\nx = 1\nx + 1\n\nfor i in [1]:\n      x = 'a'\n\nx + 1    # E: Unsupported operand types for + (\"str\" and \"int\") \\\n         # N: Left operand is of type \"int | str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoop3]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\nx = foo()\ndef f(): x  # Prevent redefinition\nx = 1\n\nwhile bool():\n    x + 1\n    x = 'a'\n    break\nelse:\n    x + 1\nx + 1      # E: Unsupported operand types for + (\"str\" and \"int\") \\\n           # N: Left operand is of type \"int | str\"\nx = 1\nfor y in [1]:\n    x + 1\n    x = 'a'\n    break\nelse:\n    x + 1\nx + 1      # E: Unsupported operand types for + (\"str\" and \"int\") \\\n           # N: Left operand is of type \"int | str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoopWhile4]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\nx = foo()\ndef f(): x  # Prevent redefinition\nx = 1\n\nwhile bool():\n    x + 1\n    if bool():\n        x = 'a'\n        break\nelse:\n    x + 1\n    x = 'a'\nx + 'a'\nx = 1\nwhile bool():\n    x + 1 # E: Unsupported operand types for + (\"str\" and \"int\") \\\n          # N: Left operand is of type \"int | str\"\n    if bool():\n        x = 'a'\n        continue\nelse:\n    x + 1 # E: Unsupported operand types for + (\"str\" and \"int\") \\\n          # N: Left operand is of type \"int | str\"\n    x = 'a'\nx + 'a'\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoopFor4]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\nx = foo()\ndef f(): x # Prevent redefinition\nx = 1\n\nfor y in [1]:\n    x + 1\n    if bool():\n        x = 'a'\n        break\nelse:\n    x + 1\n    x = 'a'\nx + 'a'\nx = 1\nfor y in [1]:\n    x + 1 # E: Unsupported operand types for + (\"str\" and \"int\") \\\n          # N: Left operand is of type \"int | str\"\n    if bool():\n        x = 'a'\n        continue\nelse:\n    x + 1 # E: Unsupported operand types for + (\"str\" and \"int\") \\\n          # N: Left operand is of type \"int | str\"\n    x = 'a'\nx + 'a'\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyNestedLoop]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\nx = foo()\ndef f(): x  # Prevent redefinition\nx = 1\n\nfor y in [1]:\n    for z in [1]:\n        break\n    else:\n        x = 'a'\n        break\nelse:\n    x + 1\nx + 1 # E: Unsupported operand types for + (\"str\" and \"int\") \\\n      # N: Left operand is of type \"int | str\"\nx = 1\nwhile bool():\n    while bool():\n        break\n    else:\n        x = 'a'\n        break\nelse:\n    x + 1\nx + 1 # E: Unsupported operand types for + (\"str\" and \"int\") \\\n      # N: Left operand is of type \"int | str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testModifyLoopLong]\n# flags: --warn-unreachable\nfrom typing import Union\n\nclass A: a = 1\n\ndef foo() -> Union[int, str, A]: pass\n\ndef bar() -> None:\n    x = foo()\n    x + 1  # E: Unsupported left operand type for + (\"A\") \\\n           # N: Left operand is of type \"int | str | A\" \\\n           # E: Unsupported operand types for + (\"str\" and \"int\")\n    if isinstance(x, A):\n       x.a\n    else:\n       if isinstance(x, int):\n          x + 1\n          x + 'a'  # E: Unsupported operand types for + (\"int\" and \"str\")\n       else:\n          x + 'a'\n          x.a      # E: \"str\" has no attribute \"a\"\n       x = A()\n\n    if isinstance(x, str):\n       x + 'a'\n    else:\n       while bool():\n          if isinstance(x, int):\n             x + 1\n          else:\n             x.a\n          break\n       while bool():\n          if isinstance(x, int):\n             x + 1\n          else:\n             x.a\n          continue\n\n       while bool():\n          if isinstance(x, int):\n             x + 1\n          else:\n             x.a     # E: Item \"str\" of \"str | A\" has no attribute \"a\"\n          x = 'a'\n[builtins fixtures/isinstancelist.pyi]\n\n[case testWhileExitCondition1]\n# flags: --warn-unreachable\nfrom typing import Union\nx = 1  # type: Union[int, str]\nwhile isinstance(x, int):\n    if bool():\n        continue\n    x = 'a'\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\nreveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/isinstance.pyi]\n\n[case testWhileExitCondition2]\n# flags: --warn-unreachable\nfrom typing import Union\nx = 1  # type: Union[int, str]\nwhile isinstance(x, int):\n    if bool():\n        break\n    x = 'a'\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\nreveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/isinstance.pyi]\n\n[case testWhileLinkedList]\n# flags: --warn-unreachable\nfrom typing import Union\nLinkedList = Union['Cons', 'Nil']\nclass Nil: pass\nclass Cons:\n    tail: LinkedList\ndef last(x: LinkedList) -> Nil:\n    while isinstance(x, Cons):\n        x = x.tail\n    return x\n[builtins fixtures/isinstance.pyi]\n\n[case testReturnAndFlow]\n# flags: --warn-unreachable\ndef foo() -> int:\n    return 1 and 2\n    return 'a'  # E: Statement is unreachable\n[case testCastIsinstance]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef foo() -> Union[int, str]: pass\n\nx = foo()\ny = 1 # type: int\n\nif isinstance(x, str):\n    x = y\nx + 1\nx + 'a'   # E: Unsupported operand types for + (\"int\" and \"str\")\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnreachableCode]\n# flags: --warn-unreachable\nx = 1 # type: int\n\nwhile bool():\n    x = 'a'           # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    break\n    x = 'a'           # Note: no error because unreachable code  # E: Statement is unreachable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnreachableCode2]\n# flags: --warn-unreachable\nx = 1\nwhile bool():\n    try:\n        pass\n    except:\n        continue\n    else:\n        continue\n    x + 'a'  # E: Statement is unreachable\n[builtins fixtures/isinstance.pyi]\n\n[case testUnreachableWhileTrue]\n# flags: --warn-unreachable\ndef f(x: int) -> None:\n    while True:\n        if x:\n            return\n    1()  # E: Statement is unreachable\n[builtins fixtures/bool.pyi]\n\n[case testUnreachableAssertFalse]\n# flags: --warn-unreachable\ndef f() -> None:\n    assert False\n    1()  # E: Statement is unreachable\n[builtins fixtures/bool.pyi]\n\n[case testUnreachableAssertFalse2]\n# flags: --warn-unreachable\ndef f() -> None:\n    # The old parser doesn't understand the syntax below\n    assert False, \"hi\"\n    1()  # E: Statement is unreachable\n[builtins fixtures/bool.pyi]\n\n[case testUnreachableReturnOrAssertFalse]\n# flags: --warn-unreachable\ndef f(x: int) -> int:\n    if x:\n        return x\n    else:\n        assert False\n    1()  # E: Statement is unreachable\n[builtins fixtures/bool.pyi]\n\n[case testUnreachableTryExcept]\n# flags: --warn-unreachable\ndef f() -> None:\n    try:\n        f()\n        return\n    except BaseException:\n        return\n    1()  # E: Statement is unreachable\n[builtins fixtures/exception.pyi]\n\n[case testUnreachableTryExceptElse]\n# flags: --warn-unreachable\ndef f() -> None:\n    try:\n        f()\n    except BaseException:\n        return\n    else:\n        return\n    1()  # E: Statement is unreachable\n[builtins fixtures/exception.pyi]\n\n[case testUnreachableTryReturnFinally1]\n# flags: --warn-unreachable\ndef f() -> None:\n    try:\n        return\n    finally:\n        pass\n    1()  # E: Statement is unreachable\n\n[case testUnreachableTryReturnFinally2]\n# flags: --warn-unreachable\ndef f() -> None:\n    try:\n        pass\n    finally:\n        return\n    1()  # E: Statement is unreachable\n\n[case testUnreachableTryReturnExceptRaise]\n# flags: --warn-unreachable\ndef f() -> None:\n    try:\n        return\n    except:\n        raise\n    1()  # E: Statement is unreachable\n\n[case testUnreachableReturnLambda]\n# flags: --warn-unreachable\nfrom typing import Callable\ndef g(t: Callable[[int], int]) -> int: pass\ndef f() -> int:\n    return g(lambda x: x)\n    1()  # E: Statement is unreachable\n\n[case testIsinstanceAnd]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    flag = 1\n\nx = B() # type: A\n\nif isinstance(x, B) and 1:\n   x.flag\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsinstanceShortcircuit]\n# flags: --warn-unreachable\nclass A:\n    pass\n\nclass B(A):\n    flag = 1\n\nx = B() # type: A\n\nif isinstance(x, B) and x.flag:\n    pass\nif isinstance(x, B) or x.flag: # E: \"A\" has no attribute \"flag\"\n    pass\nif not isinstance(x, B) or x.flag:\n    pass\nif not isinstance(x, B) and x.flag: # E: \"A\" has no attribute \"flag\"\n    pass\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsinstanceExpression]\n# flags: --warn-unreachable\nclass A:\n    pass\n\nclass B(A):\n    flag = 1\n\nx = B() # type: A\n\nx.flag if isinstance(x, B) else 0\n0 if not isinstance(x, B) else x.flag\n0 if isinstance(x, B) else x.flag # E: \"A\" has no attribute \"flag\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsinstanceMultiAnd]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    flag = 1\n\nclass C(A):\n    glaf = 1\n\nx = B() # type: A\ny = C() # type: A\n\nif isinstance(x, B) and isinstance(y, C):\n    x.flag += 1\n    y.glaf += 1\n    x() # E: \"B\" not callable\n    y() # E: \"C\" not callable\nelse:\n    x() # E: \"A\" not callable\n    y() # E: \"A\" not callable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsinstanceMultiAndSpecialCase]\n# flags: --warn-unreachable\nclass A:\n    # Ensure A.__add__ and int.__add__ are different to\n    # force 'isinstance(y, int)' checks below to never succeed.\n    def __add__(self, other: A) -> A: pass\n\nclass B(A):\n    flag = 1\n\nclass C(A):\n    glaf = 1\n\nx = B() # type: A\ny = C() # type: A\n\nif isinstance(x, B) and isinstance(y, int):  # E: Subclass of \"A\" and \"int\" cannot exist: would have incompatible method signatures\n    1() # E: Statement is unreachable\nif isinstance(y, int) and isinstance(x, B):  # E: Subclass of \"A\" and \"int\" cannot exist: would have incompatible method signatures \\\n                                             # E: Right operand of \"and\" is never evaluated\n    1() # E: Statement is unreachable\nif isinstance(y, int) and y > 42:  # E: Subclass of \"A\" and \"int\" cannot exist: would have incompatible method signatures \\\n                                   # E: Right operand of \"and\" is never evaluated\n    1() # E: Statement is unreachable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testReturnWithCallExprAndIsinstance]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef f(x: Union[int, str]) -> None:\n    if not isinstance(x, int):\n        return foo()\n    x()  # E: \"int\" not callable\n\ndef foo(): pass\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsinstanceOr1]\n# flags: --warn-unreachable\nfrom typing import Optional\n\ndef f(a: bool, x: object) -> Optional[int]:\n    if a or not isinstance(x, int):\n        return None\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    return x\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceOr2]\n# flags: --warn-unreachable\nfrom typing import Optional\n\ndef g(a: bool, x: object) -> Optional[int]:\n    if not isinstance(x, int) or a:\n        return None\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    return x\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceOr3]\n# flags: --warn-unreachable\nfrom typing import Optional\n\ndef h(a: bool, x: object) -> Optional[int]:\n    if a or isinstance(x, int):\n        return None\n    return x # E: Incompatible return value type (got \"object\", expected \"int | None\")\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceWithOverlappingUnionType]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef f(x: Union[float, int]) -> None:\n    if isinstance(x, float):\n        pass\n    if not isinstance(x, int):\n        f(x)\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceWithOverlappingUnionType2]\n# flags: --warn-unreachable\nfrom typing import Union\n\nclass A: pass\nclass B(A): pass\n\ndef f(x: Union[A, B]) -> None:\n    if isinstance(x, A):\n        pass\n    if not isinstance(x, B):\n        f(x)\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceWithOverlappingPromotionTypes]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef f1(x: Union[float, int]) -> None:\n    # We ignore promotions in isinstance checks\n    if isinstance(x, float):\n        reveal_type(x)  # N: Revealed type is \"builtins.float\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nclass FloatLike: pass\nclass IntLike(FloatLike): pass\n\ndef f2(x: Union[FloatLike, IntLike]) -> None:\n    if isinstance(x, FloatLike):\n        reveal_type(x)  # N: Revealed type is \"__main__.FloatLike\"\n    else:\n        reveal_type(x)  # E: Statement is unreachable\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceOfSuperclass]\n# flags: --warn-unreachable\nclass A: pass\nclass B(A): pass\n\nx = B()\nif isinstance(x, A):\n    reveal_type(x)  # N: Revealed type is \"__main__.B\"\nif not isinstance(x, A):\n    reveal_type(x)  # E: Statement is unreachable\n    x = A()\nreveal_type(x)  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceOfNonoverlapping]\n# flags: --warn-unreachable\nclass A: pass\nclass B: pass\n\nx = B()\nif isinstance(x, A):\n    reveal_type(x)  # N: Revealed type is \"__main__.<subclass of \"__main__.B\" and \"__main__.A\">\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.B\"\nreveal_type(x)  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/isinstance.pyi]\n\n[case testAssertIsinstance]\n# flags: --warn-unreachable\ndef f(x: object):\n    assert isinstance(x, int)\n    y = 0 # type: int\n    y = x\n[builtins fixtures/isinstance.pyi]\n\n[case testUnionAssertIsinstance]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef f(x: Union[str, int]):\n    assert isinstance(x, int)\n    y = 0 # type: int\n    y = x\n[builtins fixtures/isinstance.pyi]\n\n[case testAnyAssertIsinstance]\n# flags: --warn-unreachable\nfrom typing import Any\n\ndef f(x: Any):\n    assert isinstance(x, int)  # this should narrow x to type int\n    x + \"foo\"  # E: Unsupported operand types for + (\"int\" and \"str\")\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceOfGenericClassRetainsParameters]\n# flags: --warn-unreachable\nfrom typing import List, Union\n\ndef f(x: Union[List[int], str]) -> None:\n    if isinstance(x, list):\n        x[0]() # E: \"int\" not callable\n    else:\n        reveal_type(x) # N: Revealed type is \"builtins.str\"\n    reveal_type(x) # N: Revealed type is \"builtins.list[builtins.int] | builtins.str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsinstanceOrIsinstance]\n# flags: --warn-unreachable\nclass A: pass\n\nclass B(A):\n    flag = 1\n\nclass C(A):\n    flag = 2\n\nx1 = A()\nif isinstance(x1, B) or isinstance(x1, C):\n    reveal_type(x1) # N: Revealed type is \"__main__.B | __main__.C\"\n    f = x1.flag  # type: int\nelse:\n    reveal_type(x1) # N: Revealed type is \"__main__.A\"\n    f = 0\nreveal_type(x1) # N: Revealed type is \"__main__.A\"\nx2 = A()\nif isinstance(x2, A) or isinstance(x2, C):  # E: Right operand of \"or\" is never evaluated\n    reveal_type(x2) # N: Revealed type is \"__main__.A\"\n    f = x2.flag # E: \"A\" has no attribute \"flag\"\nelse:\n    1()  # E: Statement is unreachable\nreveal_type(x2) # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testComprehensionIsInstance]\n# flags: --warn-unreachable\nfrom typing import List, Union\na = [] # type: List[Union[int, str]]\nl = [x for x in a if isinstance(x, int)]\ng = (x for x in a if isinstance(x, int))\nd = {0: x for x in a if isinstance(x, int)}\nreveal_type(l) # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(g) # N: Revealed type is \"typing.Generator[builtins.int, None, None]\"\nreveal_type(d) # N: Revealed type is \"builtins.dict[builtins.int, builtins.int]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsinstanceInWrongOrderInBooleanOp]\n# flags: --warn-unreachable\nclass A:\n    m = 1\n\ndef f(x: object) -> None:\n    if x.m and isinstance(x, A) or False:  # E: \"object\" has no attribute \"m\"\n        pass\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceAndOr]\n# flags: --warn-unreachable\nclass A:\n    a: 'A'\n\ndef f(x: object) -> None:\n    b = isinstance(x, A) and x.a or A()\n    reveal_type(b)  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceWithUnknownType]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef f(x: Union[int, str], typ: type) -> None:\n    if isinstance(x, (typ, int)):\n        x + 1  # E: Unsupported operand types for + (\"str\" and \"int\") \\\n               # N: Left operand is of type \"int | str\"\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    reveal_type(x) # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithBoundedType]\n# flags: --warn-unreachable\nfrom typing import Union, Type\n\nclass A: pass\n\ndef f(x: Union[int, A], a: Type[A]) -> None:\n    if isinstance(x, (a, int)):\n        reveal_type(x)  # N: Revealed type is \"builtins.int | __main__.A\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.A\"\n    reveal_type(x) # N: Revealed type is \"builtins.int | __main__.A\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithEmtpy2ndArg]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef f(x: Union[int, str]) -> None:\n    if isinstance(x, ()):\n        reveal_type(x)  # E: Statement is unreachable\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithTypeObject]\n# flags: --warn-unreachable\nfrom typing import Union, Type\n\nclass A: pass\n\ndef f(x: Union[int, A], a: Type[A]) -> None:\n    if isinstance(x, a):\n        reveal_type(x)  # N: Revealed type is \"__main__.A\"\n    elif isinstance(x, int):\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.A\"\n    reveal_type(x)  # N: Revealed type is \"builtins.int | __main__.A\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclassUnreachable]\n# flags: --warn-unreachable\nfrom typing import Type, Sequence, Union\n\nx: Type[str]\nif issubclass(x, int):  # E: Subclass of \"str\" and \"int\" cannot exist: would have incompatible method signatures\n    reveal_type(x)  # E: Statement is unreachable\n\nclass X: pass\nclass Y(X): pass\nclass Z(X): pass\n\na: Union[Type[Y], Type[Z]]\nif issubclass(a, X):\n    reveal_type(a)  # N: Revealed type is \"type[__main__.Y] | type[__main__.Z]\"\nelse:\n    reveal_type(a)  # E: Statement is unreachable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclasDestructuringUnions1]\n# flags: --warn-unreachable\nfrom typing import Union, List, Tuple, Dict, Type\ndef f(x: Union[Type[int], Type[str], Type[List]]) -> None:\n    if issubclass(x, (str, (int,))):\n        reveal_type(x)  # N: Revealed type is \"type[builtins.int] | type[builtins.str]\"\n        reveal_type(x())  # N: Revealed type is \"builtins.int | builtins.str\"\n        x()[1]  # E: Value of type \"int | str\" is not indexable\n    else:\n        reveal_type(x)  # N: Revealed type is \"type[builtins.list[Any]]\"\n        reveal_type(x())  # N: Revealed type is \"builtins.list[Any]\"\n        x()[1]\n    reveal_type(x)  # N: Revealed type is \"type[builtins.int] | type[builtins.str] | type[builtins.list[Any]]\"\n    reveal_type(x())  # N: Revealed type is \"builtins.int | builtins.str | builtins.list[Any]\"\n    if issubclass(x, (str, (list,))):\n        reveal_type(x)  # N: Revealed type is \"type[builtins.str] | type[builtins.list[Any]]\"\n        reveal_type(x())  # N: Revealed type is \"builtins.str | builtins.list[Any]\"\n        x()[1]\n    reveal_type(x)  # N: Revealed type is \"type[builtins.int] | type[builtins.str] | type[builtins.list[Any]]\"\n    reveal_type(x())  # N: Revealed type is \"builtins.int | builtins.str | builtins.list[Any]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclasDestructuringUnions2]\n# flags: --warn-unreachable\nfrom typing import Union, List, Tuple, Dict, Type\n\ndef f(x: Type[Union[int, str, List]]) -> None:\n    if issubclass(x, (str, (int,))):\n        reveal_type(x)  # N: Revealed type is \"type[builtins.int] | type[builtins.str]\"\n        reveal_type(x())  # N: Revealed type is \"builtins.int | builtins.str\"\n        x()[1]  # E: Value of type \"int | str\" is not indexable\n    else:\n        reveal_type(x)  # N: Revealed type is \"type[builtins.list[Any]]\"\n        reveal_type(x())  # N: Revealed type is \"builtins.list[Any]\"\n        x()[1]\n    reveal_type(x)  # N: Revealed type is \"type[builtins.int] | type[builtins.str] | type[builtins.list[Any]]\"\n    reveal_type(x())  # N: Revealed type is \"builtins.int | builtins.str | builtins.list[Any]\"\n    if issubclass(x, (str, (list,))):\n        reveal_type(x)  # N: Revealed type is \"type[builtins.str] | type[builtins.list[Any]]\"\n        reveal_type(x())  # N: Revealed type is \"builtins.str | builtins.list[Any]\"\n        x()[1]\n    reveal_type(x)  # N: Revealed type is \"type[builtins.int] | type[builtins.str] | type[builtins.list[Any]]\"\n    reveal_type(x())  # N: Revealed type is \"builtins.int | builtins.str | builtins.list[Any]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclasDestructuringUnions3]\n# flags: --warn-unreachable\nfrom typing import Union, List, Tuple, Dict, Type\n\ndef f(x: Type[Union[int, str, List]]) -> None:\n    reveal_type(x)  # N: Revealed type is \"type[builtins.int] | type[builtins.str] | type[builtins.list[Any]]\"\n    reveal_type(x())  # N: Revealed type is \"builtins.int | builtins.str | builtins.list[Any]\"\n    if issubclass(x, (str, (int,))):\n        reveal_type(x)  # N: Revealed type is \"type[builtins.int] | type[builtins.str]\"\n        reveal_type(x())  # N: Revealed type is \"builtins.int | builtins.str\"\n        x()[1]  # E: Value of type \"int | str\" is not indexable\n    else:\n        reveal_type(x)  # N: Revealed type is \"type[builtins.list[Any]]\"\n        reveal_type(x())  # N: Revealed type is \"builtins.list[Any]\"\n        x()[1]\n    reveal_type(x)  # N: Revealed type is \"type[builtins.int] | type[builtins.str] | type[builtins.list[Any]]\"\n    reveal_type(x())  # N: Revealed type is \"builtins.int | builtins.str | builtins.list[Any]\"\n    if issubclass(x, (str, (list,))):\n        reveal_type(x)  # N: Revealed type is \"type[builtins.str] | type[builtins.list[Any]]\"\n        reveal_type(x())  # N: Revealed type is \"builtins.str | builtins.list[Any]\"\n        x()[1]\n    reveal_type(x)  # N: Revealed type is \"type[builtins.int] | type[builtins.str] | type[builtins.list[Any]]\"\n    reveal_type(x())  # N: Revealed type is \"builtins.int | builtins.str | builtins.list[Any]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclass]\n# flags: --warn-unreachable\nfrom typing import Type, ClassVar\n\nclass Goblin:\n    level: int\n\nclass GoblinAmbusher(Goblin):\n    job: ClassVar[str] = 'Ranger'\n\ndef test_issubclass(cls: Type[Goblin]) -> None:\n    if issubclass(cls, GoblinAmbusher):\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.GoblinAmbusher]\"\n        cls.level\n        cls.job\n        ga = cls()\n        ga.level = 15\n        ga.job\n        ga.job = \"Warrior\"  # E: Cannot assign to class variable \"job\" via instance\n    else:\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.Goblin]\"\n        cls.level\n        cls.job  # E: \"type[Goblin]\" has no attribute \"job\"\n        g = cls()\n        g.level = 15\n        g.job  # E: \"Goblin\" has no attribute \"job\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclassDeepHierarchy]\n# flags: --warn-unreachable\nfrom typing import Type, ClassVar\n\nclass Mob: pass\n\nclass Goblin(Mob):\n    level: int\n\nclass GoblinAmbusher(Goblin):\n    job: ClassVar[str] = 'Ranger'\n\ndef test_issubclass(cls: Type[Mob]) -> None:\n    if issubclass(cls, Goblin):\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.Goblin]\"\n        cls.level\n        cls.job  # E: \"type[Goblin]\" has no attribute \"job\"\n        g = cls()\n        g.level = 15\n        g.job  # E: \"Goblin\" has no attribute \"job\"\n        if issubclass(cls, GoblinAmbusher):\n            reveal_type(cls)  # N: Revealed type is \"type[__main__.GoblinAmbusher]\"\n            cls.level\n            cls.job\n            g = cls()\n            g.level = 15\n            g.job\n            g.job = 'Warrior' # E: Cannot assign to class variable \"job\" via instance\n    else:\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.Mob]\"\n        cls.job  # E: \"type[Mob]\" has no attribute \"job\"\n        cls.level  # E: \"type[Mob]\" has no attribute \"level\"\n        m = cls()\n        m.level = 15  # E: \"Mob\" has no attribute \"level\"\n        m.job  # E: \"Mob\" has no attribute \"job\"\n        if issubclass(cls, GoblinAmbusher):\n            reveal_type(cls)  # N: Revealed type is \"type[__main__.GoblinAmbusher]\"\n            cls.job\n            cls.level\n            ga = cls()\n            ga.level = 15\n            ga.job\n            ga.job = 'Warrior' # E: Cannot assign to class variable \"job\" via instance\n\n    if issubclass(cls, GoblinAmbusher):\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.GoblinAmbusher]\"\n        cls.level\n        cls.job\n        ga = cls()\n        ga.level = 15\n        ga.job\n        ga.job = \"Warrior\"  # E: Cannot assign to class variable \"job\" via instance\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclassTuple]\n# flags: --warn-unreachable\nfrom typing import Type, ClassVar\n\nclass Mob: pass\n\nclass Goblin(Mob):\n    level: int\n\nclass GoblinAmbusher(Goblin):\n    job: ClassVar[str] = 'Ranger'\n\nclass GoblinDigger(Goblin):\n    job: ClassVar[str] = 'Thief'\n\ndef test_issubclass(cls: Type[Mob]) -> None:\n    if issubclass(cls, (Goblin, GoblinAmbusher)):\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.Goblin]\"\n        cls.level\n        cls.job  # E: \"type[Goblin]\" has no attribute \"job\"\n        g = cls()\n        g.level = 15\n        g.job  # E: \"Goblin\" has no attribute \"job\"\n        if issubclass(cls, GoblinAmbusher):\n            cls.level\n            reveal_type(cls)  # N: Revealed type is \"type[__main__.GoblinAmbusher]\"\n            cls.job\n            ga = cls()\n            ga.level = 15\n            ga.job\n            ga.job = \"Warrior\"  # E: Cannot assign to class variable \"job\" via instance\n    else:\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.Mob]\"\n        cls.job  # E: \"type[Mob]\" has no attribute \"job\"\n        cls.level  # E: \"type[Mob]\" has no attribute \"level\"\n        m = cls()\n        m.level = 15  # E: \"Mob\" has no attribute \"level\"\n        m.job  # E: \"Mob\" has no attribute \"job\"\n        if issubclass(cls, GoblinAmbusher):\n            reveal_type(cls)  # N: Revealed type is \"type[__main__.GoblinAmbusher]\"\n            cls.job\n            cls.level\n            ga = cls()\n            ga.level = 15\n            ga.job\n            ga.job = \"Warrior\"  # E: Cannot assign to class variable \"job\" via instance\n\n    if issubclass(cls, (GoblinDigger, GoblinAmbusher)):\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.GoblinDigger] | type[__main__.GoblinAmbusher]\"\n        cls.level\n        cls.job\n        g = cls()\n        g.level = 15\n        g.job\n        g.job = \"Warrior\" # E: Cannot assign to class variable \"job\" via instance\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclassBuiltins]\n# flags: --warn-unreachable\nfrom typing import List, Type\n\nclass MyList(List): pass\nclass MyIntList(List[int]): pass\n\ndef f(cls: Type[object]) -> None:\n    if issubclass(cls, MyList):\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.MyList]\"\n        cls()[0]\n    else:\n        reveal_type(cls)  # N: Revealed type is \"type[builtins.object]\"\n        cls()[0]  # E: Value of type \"object\" is not indexable\n\n    if issubclass(cls, MyIntList):\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.MyIntList]\"\n        cls()[0] + 1\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIssubclassTypeVar]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import TypeVar\n\nClassT = TypeVar(\"ClassT\", bound=type)\n\ndef directed_meet(cls0: ClassT, cls1: ClassT) -> ClassT | None:\n    if issubclass(cls1, cls0):\n        return cls1\n    if issubclass(cls0, cls1):\n        return cls0\n    return None\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsinstanceTypeArgs]\n# flags: --warn-unreachable\nfrom typing import Iterable, TypeVar\nx = 1\nisinstance(x, Iterable)\nisinstance(x, Iterable[int])  # E: Parameterized generics cannot be used with class or instance checks\nisinstance(x, (int, Iterable[int]))  # E: Parameterized generics cannot be used with class or instance checks\nisinstance(x, (int, (str, Iterable[int])))  # E: Parameterized generics cannot be used with class or instance checks\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testIsinstanceAnyAlias]\n# flags: --warn-unreachable\nfrom typing import Any\nA = Any\nisinstance(object(), A)  # E: Cannot use isinstance() with Any type\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceTypeArgsAliases]\n# flags: --warn-unreachable\nfrom typing import Iterable, TypeVar\nx = 1\nT = TypeVar('T')\nIt = Iterable\nIt2 = Iterable[T]\n\nisinstance(x, It[int])  # E: Parameterized generics cannot be used with class or instance checks\nisinstance(x, It)\nisinstance(x, It2[int])  # E: Parameterized generics cannot be used with class or instance checks\nisinstance(x, It2)  # E: Parameterized generics cannot be used with class or instance checks\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testIssubclassTypeArgs]\n# flags: --warn-unreachable\nfrom typing import Iterable, TypeVar\nx = int\nissubclass(x, Iterable)\nissubclass(x, Iterable[int])  # E: Parameterized generics cannot be used with class or instance checks\nissubclass(x, (int, Iterable[int]))  # E: Parameterized generics cannot be used with class or instance checks\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testIssubclassWithMetaclasses]\n# flags: --no-strict-optional --warn-unreachable\nclass FooMetaclass(type): ...\nclass Foo(metaclass=FooMetaclass): ...\nclass Bar: ...\n\nfm: FooMetaclass\nreveal_type(fm)  # N: Revealed type is \"__main__.FooMetaclass\"\nif issubclass(fm, Foo):\n    reveal_type(fm)  # N: Revealed type is \"type[__main__.Foo]\"\nif issubclass(fm, Bar):\n    reveal_type(fm)  # N: Revealed type is \"None\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIssubclassWithMetaclassesStrictOptional]\n# flags: --warn-unreachable\nclass FooMetaclass(type): ...\nclass BarMetaclass(type): ...\nclass Foo(metaclass=FooMetaclass): ...\nclass Bar(metaclass=BarMetaclass): ...\nclass Baz: ...\n\nfm: FooMetaclass\nreveal_type(fm)  # N: Revealed type is \"__main__.FooMetaclass\"\nif issubclass(fm, Foo):\n    reveal_type(fm)  # N: Revealed type is \"type[__main__.Foo]\"\nif issubclass(fm, Bar):\n    reveal_type(fm)  # N: Revealed type is \"type[__main__.Bar]\"\nif issubclass(fm, Baz):\n    reveal_type(fm)  # N: Revealed type is \"type[__main__.Baz]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceAndNarrowTypeVariable]\n# flags: --warn-unreachable\nfrom typing import TypeVar\n\nclass A: pass\nclass B(A):\n    attr: int\n\nT = TypeVar('T', bound=A)\n\ndef f(x: T) -> None:\n    if isinstance(x, B):\n        reveal_type(x) # N: Revealed type is \"T`-1\"\n        reveal_type(x.attr)  # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(x) # N: Revealed type is \"T`-1\"\n        x.attr  # E: \"T\" has no attribute \"attr\"\n    reveal_type(x) # N: Revealed type is \"T`-1\"\n    x.attr  # E: \"T\" has no attribute \"attr\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceAndNegativeNarrowTypeVariableWithUnionBound1]\n# flags: --warn-unreachable\nfrom typing import Union, TypeVar\n\nclass A:\n    a: int\nclass B:\n    b: int\n\nT = TypeVar(\"T\", bound=Union[A, B])\n\ndef f(x: T) -> T:\n    if isinstance(x, A):\n        reveal_type(x)      # N: Revealed type is \"T`-1\"\n        x.a\n        x.b                 # E: \"T\" has no attribute \"b\"\n        if bool():\n            return x\n    else:\n        reveal_type(x)      # N: Revealed type is \"T`-1\"\n        x.a                 # E: \"T\" has no attribute \"a\"\n        x.b\n    x.a                     # E: Item \"B\" of the upper bound \"A | B\" of type variable \"T\" has no attribute \"a\"\n    x.b                     # E: Item \"A\" of the upper bound \"A | B\" of type variable \"T\" has no attribute \"b\"\n    return x\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceAndNegativeNarrowTypeVariableWithUnionBound2]\n# flags: --warn-unreachable\nfrom typing import Union, TypeVar\n\nclass A:\n    a: int\nclass B:\n    b: int\n\nT = TypeVar(\"T\", bound=Union[A, B])\n\ndef f(x: T) -> T:\n    if isinstance(x, A):\n        return x\n    x.a # E: \"T\" has no attribute \"a\"\n    x.b # OK\n    return x\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceAndTypeType]\n# flags: --warn-unreachable\nfrom typing import Type\ndef f(x: Type[int]) -> None:\n    if isinstance(x, type):\n        reveal_type(x) # N: Revealed type is \"type[builtins.int]\"\n    else:\n        reveal_type(x)  # E: Statement is unreachable\n    reveal_type(x) # N: Revealed type is \"type[builtins.int]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceVariableSubstitution]\n# flags: --warn-unreachable\nT = (int, str)\nU = (list, T)\nx: object = None\n\nif isinstance(x, T):\n    reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n\nif isinstance(x, U):\n    reveal_type(x)  # N: Revealed type is \"builtins.list[Any] | builtins.int | builtins.str\"\n\nif isinstance(x, (set, (list, T))):\n    reveal_type(x)  # N: Revealed type is \"builtins.set[Any] | builtins.list[Any] | builtins.int | builtins.str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceTooFewArgs]\n# flags: --warn-unreachable\nisinstance() # E: Missing positional arguments \"x\", \"t\" in call to \"isinstance\"\nx: object\nif isinstance(): # E: Missing positional arguments \"x\", \"t\" in call to \"isinstance\"\n    x = 1\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\nif isinstance(x): # E: Missing positional argument \"t\" in call to \"isinstance\"\n    x = 1\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsSubclassTooFewArgs]\n# flags: --warn-unreachable\nfrom typing import Type\n\nissubclass() # E: Missing positional arguments \"x\", \"t\" in call to \"issubclass\"\ny: Type[object]\nif issubclass(): # E: Missing positional arguments \"x\", \"t\" in call to \"issubclass\"\n    reveal_type(y) # N: Revealed type is \"type[builtins.object]\"\nif issubclass(y): # E: Missing positional argument \"t\" in call to \"issubclass\"\n    reveal_type(y) # N: Revealed type is \"type[builtins.object]\"\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceTooManyArgs]\n# flags: --warn-unreachable\nisinstance(1, 1, 1) # E: Too many arguments for \"isinstance\" \\\n         # E: Argument 2 to \"isinstance\" has incompatible type \"int\"; expected \"type | tuple[Any, ...]\"\nx: object\nif isinstance(x, str, 1): # E: Too many arguments for \"isinstance\"\n    reveal_type(x) # N: Revealed type is \"builtins.object\"\n    x = 1\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsinstanceNarrowAnyExplicit]\n# flags: --warn-unreachable\nfrom typing import Any\n\ndef narrow_any_to_str_then_reassign_to_int() -> None:\n    v: Any = 1\n\n    if isinstance(v, str):\n        reveal_type(v)  # N: Revealed type is \"builtins.str\"\n        v = 2\n        reveal_type(v)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceNarrowAnyImplicit]\n# flags: --warn-unreachable\ndef foo(): ...\n\ndef narrow_any_to_str_then_reassign_to_int() -> None:\n    v = foo()\n\n    if isinstance(v, str):\n        reveal_type(v)  # N: Revealed type is \"builtins.str\"\n        v = 2\n        reveal_type(v)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowTypeAfterInList]\n# flags: --warn-unreachable\nfrom typing import List, Optional\n\nx: List[int]\ny: Optional[int]\n\nif y in x:\n    reveal_type(y)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"builtins.int | None\"\nif y not in x:\n    reveal_type(y)  # N: Revealed type is \"builtins.int | None\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNarrowTypeAfterInListOfOptional]\n# flags: --warn-unreachable\nfrom typing import List, Optional\n\nx: List[Optional[int]]\ny: Optional[int]\n\nif y not in x:\n    reveal_type(y)  # N: Revealed type is \"builtins.int | None\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"builtins.int | None\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNarrowTypeAfterInListNonOverlapping]\n# flags: --warn-unreachable\nfrom typing import List, Optional\n\nx: List[str]\ny: Optional[int]\n\nif y in x:\n    reveal_type(y)  # E: Statement is unreachable\nelse:\n    reveal_type(y)  # N: Revealed type is \"builtins.int | None\"\n[builtins fixtures/list.pyi]\n\n[case testNarrowTypeAfterInListNested]\n# flags: --warn-unreachable\nfrom typing import List, Optional, Any\n\nx: Optional[int]\nlst: Optional[List[int]]\nnested_any: List[List[Any]]\n\nif lst in nested_any:\n    reveal_type(lst) # N: Revealed type is \"builtins.list[builtins.int]\"\nif x in nested_any:\n    reveal_type(x) # E: Statement is unreachable\n[builtins fixtures/list.pyi]\n\n[case testNarrowTypeAfterInTuple]\n# flags: --warn-unreachable\nfrom typing import Optional\nclass A: pass\nclass B(A): pass\nclass C(A): pass\n\ny: Optional[B]\nif y in (B(), C()):\n    reveal_type(y) # N: Revealed type is \"__main__.B\"\nelse:\n    reveal_type(y) # N: Revealed type is \"__main__.B | None\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNarrowTypeAfterInNamedTuple]\n# flags: --warn-unreachable\nfrom typing import NamedTuple, Optional\nclass NT(NamedTuple):\n    x: int\n    y: int\nnt: NT\n\ny: Optional[int]\nif y not in nt:\n    reveal_type(y) # N: Revealed type is \"builtins.int | None\"\nelse:\n    reveal_type(y) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testNarrowTypeAfterInDict]\n# flags: --warn-unreachable\nfrom typing import Dict, Optional\nx: Dict[str, int]\ny: Optional[str]\n\nif y in x:\n    reveal_type(y) # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(y) # N: Revealed type is \"builtins.str | None\"\nif y not in x:\n    reveal_type(y) # N: Revealed type is \"builtins.str | None\"\nelse:\n    reveal_type(y) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testNarrowTypeAfterInNoAnyOrObject]\n# flags: --warn-unreachable\nfrom typing import Any, List, Optional\nx: List[Any]\nz: List[object]\n\ny: Optional[int]\nif y in x:\n    reveal_type(y) # N: Revealed type is \"builtins.int | None\"\nelse:\n    reveal_type(y) # N: Revealed type is \"builtins.int | None\"\n\nif y not in z:\n    reveal_type(y) # N: Revealed type is \"builtins.int | None\"\nelse:\n    reveal_type(y) # N: Revealed type is \"builtins.int | None\"\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNarrowTypeAfterInUserDefined]\n# flags: --warn-unreachable\nfrom typing import Container, Optional\n\nclass C(Container[int]):\n    def __contains__(self, item: object) -> bool:\n        return item is 'surprise'\n\ny: Optional[int]\n# We never trust user defined types\nif y in C():\n    reveal_type(y) # N: Revealed type is \"builtins.int | None\"\nelse:\n    reveal_type(y) # N: Revealed type is \"builtins.int | None\"\nif y not in C():\n    reveal_type(y) # N: Revealed type is \"builtins.int | None\"\nelse:\n    reveal_type(y) # N: Revealed type is \"builtins.int | None\"\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNarrowTypeAfterInSet]\n# flags: --warn-unreachable\nfrom typing import Optional, Set\ns: Set[str]\n\ny: Optional[str]\nif y in {'a', 'b', 'c'}:\n    reveal_type(y) # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(y) # N: Revealed type is \"builtins.str | None\"\nif y not in s:\n    reveal_type(y) # N: Revealed type is \"builtins.str | None\"\nelse:\n    reveal_type(y) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/set.pyi]\n[out]\n\n[case testNarrowTypeAfterInTypedDict]\n# flags: --warn-unreachable\nfrom typing import Optional, TypedDict\nclass TD(TypedDict):\n    a: int\n    b: str\ntd: TD\n\ndef f() -> None:\n    x: Optional[str]\n    if x not in td:\n        return\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testIsinstanceWidensWithAnyArg]\n# flags: --warn-unreachable\nfrom typing import Any\nclass A: ...\nB: Any\nx: A\nx.foo()  # E: \"A\" has no attribute \"foo\"\nassert isinstance(x, B)\nx.foo()\nreveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceWidensUnionWithAnyArg]\n# flags: --warn-unreachable\nfrom typing import Any, Union\nclass A: ...\nB: Any\nx: Union[A, B]\nreveal_type(x)  # N: Revealed type is \"__main__.A | Any\"\nassert isinstance(x, B)\nreveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceIgnoredImport]\n# flags: --warn-unreachable\nfrom typing import Union\nfrom foo import A  # type: ignore\ndef f(x: Union[A, str]) -> None:\n    x.method_only_in_a()  # E: Item \"str\" of \"Any | str\" has no attribute \"method_only_in_a\"\n    if isinstance(x, A):\n        x.method_only_in_a()\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceIgnoredImportDualAny]\n# flags: --warn-unreachable\nfrom typing import Any\nfrom foo import Bad, OtherBad  # type: ignore\nx: Any\nif isinstance(x, Bad):\n    reveal_type(x)  # N: Revealed type is \"Any\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Any\"\n\nif isinstance(x, (Bad, OtherBad)):\n    reveal_type(x)  # N: Revealed type is \"Any\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Any\"\n\ny: object\nif isinstance(y, Bad):\n    reveal_type(y)  # N: Revealed type is \"Any\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"builtins.object\"\n\nclass Ok: pass\nz: Any\nif isinstance(z, Ok):\n    reveal_type(z)  # N: Revealed type is \"__main__.Ok\"\nelse:\n    reveal_type(z)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceInitialNoneCheckSkipsImpossibleCasesNoStrictOptional]\n# flags: --warn-unreachable\nfrom typing import Optional, Union\n\nclass A: pass\n\ndef foo1(x: Union[A, str, None]) -> None:\n    if x is None:\n        reveal_type(x)      # N: Revealed type is \"None\"\n    elif isinstance(x, A):\n        reveal_type(x)      # N: Revealed type is \"__main__.A\"\n    else:\n        reveal_type(x)      # N: Revealed type is \"builtins.str\"\n\ndef foo2(x: Optional[str]) -> None:\n    if x is None:\n        reveal_type(x)      # N: Revealed type is \"None\"\n    elif isinstance(x, A):\n        reveal_type(x)      # N: Revealed type is \"__main__.<subclass of \"builtins.str\" and \"__main__.A\">\"\n    else:\n        reveal_type(x)      # N: Revealed type is \"builtins.str\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceInitialNoneCheckSkipsImpossibleCasesInNoStrictOptional]\n# flags: --no-strict-optional --warn-unreachable\nfrom typing import Optional, Union\n\nclass A: pass\n\ndef foo1(x: Union[A, str, None]) -> None:\n    if x is None:\n        reveal_type(x)      # N: Revealed type is \"None\"\n    elif isinstance(x, A):\n        # Note that Union[None, A] == A in no-strict-optional\n        reveal_type(x)      # N: Revealed type is \"__main__.A\"\n    else:\n        reveal_type(x)      # N: Revealed type is \"builtins.str\"\n\ndef foo2(x: Optional[str]) -> None:\n    if x is None:\n        reveal_type(x)      # N: Revealed type is \"None\"\n    elif isinstance(x, A):\n        reveal_type(x)      # N: Revealed type is \"__main__.<subclass of \"builtins.str\" and \"__main__.A\">\"\n    else:\n        reveal_type(x)      # N: Revealed type is \"builtins.str\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNoneCheckDoesNotMakeTypeVarOptional]\n# flags: --warn-unreachable\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef foo_if(x: T) -> T:\n    out = None\n    out = x\n    if out is None:\n        pass\n    return out\n\ndef foo_while(x: T) -> T:\n    out = None\n    out = x\n    while out is None:\n        pass\n    return out\n[builtins fixtures/isinstance.pyi]\n\n[case testNoneCheckDoesNotNarrowWhenUsingTypeVarsNoStrictOptional]\n# flags: --no-strict-optional --warn-unreachable\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef foo(x: T) -> T:\n    out = None\n    out = x\n    if out is None:\n        pass\n    return out\n[builtins fixtures/isinstance.pyi]\n\n[case testNoneAndGenericTypesOverlapNoStrictOptional]\n# flags: --no-strict-optional --warn-unreachable\nfrom typing import Union, Optional, List\n\n# Note: this test is indirectly making sure meet.is_overlapping_types\n# correctly ignores 'None' in unions.\n\ndef foo(x: Optional[List[str]]) -> None:\n    reveal_type(x)                  # N: Revealed type is \"builtins.list[builtins.str] | None\"\n    assert isinstance(x, list)\n    reveal_type(x)                  # N: Revealed type is \"builtins.list[builtins.str]\"\n\ndef bar(x: Union[List[str], List[int], None]) -> None:\n    reveal_type(x)                  # N: Revealed type is \"builtins.list[builtins.str] | builtins.list[builtins.int] | None\"\n    assert isinstance(x, list)\n    reveal_type(x)                  # N: Revealed type is \"builtins.list[builtins.str] | builtins.list[builtins.int]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testNoneAndGenericTypesOverlapStrictOptional]\n# flags: --warn-unreachable\nfrom typing import Union, Optional, List\n\n# This test is the same as the one above, except for strict-optional.\n# It isn't testing anything explicitly and mostly exists for the sake\n# of completeness.\n\ndef foo(x: Optional[List[str]]) -> None:\n    reveal_type(x)                  # N: Revealed type is \"builtins.list[builtins.str] | None\"\n    assert isinstance(x, list)\n    reveal_type(x)                  # N: Revealed type is \"builtins.list[builtins.str]\"\n\ndef bar(x: Union[List[str], List[int], None]) -> None:\n    reveal_type(x)                  # N: Revealed type is \"builtins.list[builtins.str] | builtins.list[builtins.int] | None\"\n    assert isinstance(x, list)\n    reveal_type(x)                  # N: Revealed type is \"builtins.list[builtins.str] | builtins.list[builtins.int]\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithStarExpression]\n# flags: --warn-unreachable\nfrom typing import Union, List, Tuple\n\ndef f(var: Union[List[str], Tuple[str, str], str]) -> None:\n    reveal_type(var)  # N: Revealed type is \"builtins.list[builtins.str] | tuple[builtins.str, builtins.str] | builtins.str\"\n    if isinstance(var, (list, *(str, int))):\n        reveal_type(var)  # N: Revealed type is \"builtins.list[builtins.str] | builtins.str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithStarExpressionAndVariable]\n# flags: --warn-unreachable\nfrom typing import Union\n\ndef f(var: Union[int, str]) -> None:\n    reveal_type(var)  # N: Revealed type is \"builtins.int | builtins.str\"\n    some_types = (str, tuple)\n    another_type = list\n    if isinstance(var, (*some_types, another_type)):\n        reveal_type(var)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceWithWrongStarExpression]\n# flags: --warn-unreachable\nvar = 'some string'\nif isinstance(var, *(str, int)):  # E: Too many arguments for \"isinstance\"\n    pass\n[builtins fixtures/isinstancelist.pyi]\n\n[case testIsInstanceAdHocIntersectionBasic]\n# flags: --warn-unreachable\nclass A:\n    def f1(self) -> int: ...\nclass B:\n    def f2(self) -> int: ...\nclass C:\n    def f3(self) -> int: ...\n\nx: A\nif isinstance(x, B):\n    reveal_type(x)           # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\n    if isinstance(x, C):\n        reveal_type(x)       # N: Revealed type is \"__main__.<subclass of \"__main__.A\", \"__main__.B\", and \"__main__.C\">\"\n        reveal_type(x.f1())  # N: Revealed type is \"builtins.int\"\n        reveal_type(x.f2())  # N: Revealed type is \"builtins.int\"\n        reveal_type(x.f3())  # N: Revealed type is \"builtins.int\"\n        x.bad()              # E: \"<subclass of \"__main__.A\", \"__main__.B\", and \"__main__.C\">\" has no attribute \"bad\"\n    else:\n        reveal_type(x)       # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\nelse:\n    reveal_type(x)           # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionRepeatedChecks]\n# flags: --warn-unreachable\n\nclass A: pass\nclass B: pass\n\nx: A\nif isinstance(x, B):\n    reveal_type(x)      # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\n    if isinstance(x, A):\n        reveal_type(x)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\n    if isinstance(x, B):\n        reveal_type(x)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionIncompatibleClasses]\n# flags: --warn-unreachable\nclass A:\n    def f(self) -> int: ...\nclass B:\n    def f(self) -> str: ...\nclass C:\n    def f(self) -> str: ...\n\nclass Example(A, B): pass  # E: Definition of \"f\" in base class \"A\" is incompatible with definition in base class \"B\"\nx: A\nif isinstance(x, B):  # E: Subclass of \"A\" and \"B\" cannot exist: would have incompatible method signatures\n    reveal_type(x)    # E: Statement is unreachable\nelse:\n    reveal_type(x)    # N: Revealed type is \"__main__.A\"\n\ny: C\nif isinstance(y, B):\n    reveal_type(y)        # N: Revealed type is \"__main__.<subclass of \"__main__.C\" and \"__main__.B\">\"\n    if isinstance(y, A):  # E: Subclass of \"C\", \"B\", and \"A\" cannot exist: would have incompatible method signatures\n        reveal_type(y)    # E: Statement is unreachable\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionReversed]\n# flags: --warn-unreachable\n\nfrom abc import abstractmethod\nfrom typing import Literal\n\nclass A0:\n    def f(self) -> Literal[0]:\n        ...\n\nclass A1:\n    def f(self) -> Literal[1]:\n        ...\n\nclass A2:\n    def f(self) -> Literal[2]:\n        ...\n\nclass B:\n    @abstractmethod\n    def f(self) -> Literal[1, 2]:\n        ...\n\n    def t0(self) -> None:\n        if isinstance(self, A0):        # E: Subclass of \"B\" and \"A0\" cannot exist: would have incompatible method signatures\n            x0: Literal[0] = self.f()   # E: Statement is unreachable\n\n    def t1(self) -> None:\n        if isinstance(self, A1):\n            reveal_type(self)           # N: Revealed type is \"__main__.<subclass of \"__main__.A1\" and \"__main__.B\">\"\n            x0: Literal[0] = self.f()   # E: Incompatible types in assignment (expression has type \"Literal[1]\", variable has type \"Literal[0]\")\n            x1: Literal[1] = self.f()\n\n    def t2(self) -> None:\n        if isinstance(self, (A0, A1)):\n            reveal_type(self)           # N: Revealed type is \"__main__.<subclass of \"__main__.A1\" and \"__main__.B\">\"\n            x0: Literal[0] = self.f()   # E: Incompatible types in assignment (expression has type \"Literal[1]\", variable has type \"Literal[0]\")\n            x1: Literal[1] = self.f()\n\n    def t3(self) -> None:\n        if isinstance(self, (A1, A2)):\n            reveal_type(self)           # N: Revealed type is \"__main__.<subclass of \"__main__.A1\" and \"__main__.B\"> | __main__.<subclass of \"__main__.A2\" and \"__main__.B\">\"\n            x0: Literal[0] = self.f()   # E: Incompatible types in assignment (expression has type \"Literal[1, 2]\", variable has type \"Literal[0]\")\n            x1: Literal[1] = self.f()   # E: Incompatible types in assignment (expression has type \"Literal[1, 2]\", variable has type \"Literal[1]\")\n\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionGenerics]\n# flags: --warn-unreachable\nfrom typing import Generic, TypeVar\n\nclass Parent: pass\nclass Child(Parent): pass\n\nT = TypeVar('T')\nclass A(Generic[T]):\n    def f(self) -> T: ...\nclass B:\n    def f(self) -> Parent: ...\n\nx: A[int]\nif isinstance(x, B):    # E: Subclass of \"A[int]\" and \"B\" cannot exist: would have incompatible method signatures\n    reveal_type(x)      # E: Statement is unreachable\nelse:\n    reveal_type(x)      # N: Revealed type is \"__main__.A[builtins.int]\"\n\ny: A[Parent]\nif isinstance(y, B):\n    reveal_type(y)      # N: Revealed type is \"__main__.<subclass of \"__main__.A[__main__.Parent]\" and \"__main__.B\">\"\n    reveal_type(y.f())  # N: Revealed type is \"__main__.Parent\"\nelse:\n    reveal_type(y)      # N: Revealed type is \"__main__.A[__main__.Parent]\"\n\nz: A[Child]\nif isinstance(z, B):\n    reveal_type(z)      # N: Revealed type is \"__main__.<subclass of \"__main__.A[__main__.Child]\" and \"__main__.B\">\"\n    reveal_type(z.f())  # N: Revealed type is \"__main__.Child\"\nelse:\n    reveal_type(z)      # N: Revealed type is \"__main__.A[__main__.Child]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionGenericsWithValues]\n# flags: --warn-unreachable\nfrom typing import TypeVar\n\nclass A:\n    attr: int\nclass B:\n    attr: int\nclass C:\n    attr: str\n\nT1 = TypeVar('T1', A, B)\ndef f1(x: T1) -> T1:\n    if isinstance(x, A):\n        reveal_type(x)      # N: Revealed type is \"__main__.A\" \\\n                            # N: Revealed type is \"__main__.<subclass of \"__main__.B\" and \"__main__.A\">\"\n        if isinstance(x, B):\n            reveal_type(x)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\" \\\n                            # N: Revealed type is \"__main__.<subclass of \"__main__.B\" and \"__main__.A\">\"\n        else:\n            reveal_type(x)  # N: Revealed type is \"__main__.A\"\n    else:\n        reveal_type(x)      # N: Revealed type is \"__main__.B\"\n    return x\n\nT2 = TypeVar('T2', B, C)\ndef f2(x: T2) -> T2:\n    if isinstance(x, B):\n        reveal_type(x)      # N: Revealed type is \"__main__.B\"\n        # Note: even though --warn-unreachable is set, we don't report\n        # errors for the below: we don't yet have a way of filtering out\n        # reachability errors that occur for only one variation of the\n        # TypeVar yet.\n        if isinstance(x, C):\n            reveal_type(x)\n        else:\n            reveal_type(x)  # N: Revealed type is \"__main__.B\"\n    else:\n        reveal_type(x)      # N: Revealed type is \"__main__.C\"\n    return x\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionGenericsWithValuesDirectReturn]\n# flags: --warn-unreachable\nfrom typing import TypeVar\n\nclass A:\n    attr: int\nclass B:\n    attr: int\nclass C:\n    attr: str\n\nT1 = TypeVar('T1', A, B)\ndef f1(x: T1) -> T1:\n    if isinstance(x, A):\n        # The error message is confusing, but we indeed do run into problems if\n        # 'x' is a subclass of __main__.A and __main__.B\n        return A()   # E: Incompatible return value type (got \"A\", expected \"B\")\n    else:\n        return B()\n\nT2 = TypeVar('T2', B, C)\ndef f2(x: T2) -> T2:\n    if isinstance(x, B):\n        # In contrast, it's impossible for a subclass of \"B\" and \"C\" to\n        # exist, so this is fine\n        return B()\n    else:\n        return C()\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceDisjointBase]\n# flags: --warn-unreachable\nfrom typing_extensions import disjoint_base\n\n@disjoint_base\nclass Disjoint1: pass\n@disjoint_base\nclass Disjoint2: pass\n@disjoint_base\nclass Disjoint3(Disjoint1): pass\nclass Child(Disjoint1): pass\nclass Unrelated: pass\n\ndef f(d1: Disjoint1, u: Unrelated, c: Child) -> object:\n    if isinstance(d1, Disjoint2): # E: Subclass of \"Disjoint1\" and \"Disjoint2\" cannot exist: have distinct disjoint bases\n        return u  # E: Statement is unreachable\n    if isinstance(u, Disjoint1):  # OK\n        return d1\n    if isinstance(c, Disjoint3):  # OK\n        return c\n    if isinstance(c, Disjoint2):  # E: Subclass of \"Child\" and \"Disjoint2\" cannot exist: have distinct disjoint bases\n        return c  # E: Statement is unreachable\n    return d1\n\n[builtins fixtures/isinstance.pyi]\n\n\n[case testIsInstanceAdHocIntersectionUsage]\n# flags: --warn-unreachable\nclass A: pass\nclass B: pass\nclass Concrete(A, B): pass\n\ndef accept_a(a: A) -> None: pass\ndef accept_b(a: B) -> None: pass\ndef accept_concrete(c: Concrete) -> None: pass\n\nx: A\nif isinstance(x, B):\n    var = x\n    reveal_type(var)      # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\n    accept_a(var)\n    accept_b(var)\n    accept_concrete(var)  # E: Argument 1 to \"accept_concrete\" has incompatible type \"<subclass of \"__main__.A\" and \"__main__.B\">\"; expected \"Concrete\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionReinfer]\n# flags: --warn-unreachable\nclass A: pass\nclass B: pass\n\nx: A\nassert isinstance(x, B)\nreveal_type(x)      # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\n\ny: A\nassert isinstance(y, B)\nreveal_type(y)      # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\n\nx = y\nreveal_type(x)      # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionWithUnions]\n# flags: --warn-unreachable\nfrom typing import Type, Union\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\n\nv1: A\nif isinstance(v1, (B, C)):\n    reveal_type(v1)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\"> | __main__.<subclass of \"__main__.A\" and \"__main__.C\">\"\n\nv2: Union[A, B]\nif isinstance(v2, C):\n    reveal_type(v2)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.C\"> | __main__.<subclass of \"__main__.B\" and \"__main__.C\">\"\n\nv3: Union[A, B]\nif isinstance(v3, (C, D)):\n    reveal_type(v3)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.C\"> | __main__.<subclass of \"__main__.A\" and \"__main__.D\"> | __main__.<subclass of \"__main__.B\" and \"__main__.C\"> | __main__.<subclass of \"__main__.B\" and \"__main__.D\">\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionSameNames]\n# flags: --warn-unreachable\nfrom foo import A as A2\nclass A: pass\n\nx: A\nif isinstance(x, A2):\n    reveal_type(x)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"foo.A\">\"\n\n[file foo.py]\nclass A: pass\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionBadMro]\n# flags: --warn-unreachable\nclass X: pass\nclass Y: pass\nclass A(X, Y): pass\nclass B(Y, X): pass\n\nfoo: A\nif isinstance(foo, B):  # E: Subclass of \"A\" and \"B\" cannot exist: would have inconsistent method resolution order\n    reveal_type(foo)    # E: Statement is unreachable\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceAdHocIntersectionAmbiguousClass]\n# flags: --warn-unreachable\nfrom typing import Any\n\nclass Concrete:\n    x: int\nclass Ambiguous:\n    x: Any\n\n# We bias towards assuming these two classes could be overlapping\nfoo: Concrete\nif isinstance(foo, Ambiguous):\n    reveal_type(foo)    # N: Revealed type is \"__main__.<subclass of \"__main__.Concrete\" and \"__main__.Ambiguous\">\"\n    reveal_type(foo.x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsSubclassAdHocIntersection]\n# flags: --warn-unreachable\nfrom typing import Type\n\nclass A:\n    x: int\nclass B:\n    x: int\nclass C:\n    x: str\n\nx: Type[A]\nif issubclass(x, B):\n    reveal_type(x)        # N: Revealed type is \"type[__main__.<subclass of \"__main__.A\" and \"__main__.B\">]\"\n    if issubclass(x, C):  # E: Subclass of \"A\", \"B\", and \"C\" cannot exist: would have incompatible method signatures\n        reveal_type(x)    # E: Statement is unreachable\n    else:\n        reveal_type(x)    # N: Revealed type is \"type[__main__.<subclass of \"__main__.A\" and \"__main__.B\">]\"\nelse:\n    reveal_type(x)        # N: Revealed type is \"type[__main__.A]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrExistingAttribute]\n# flags: --warn-unreachable\nclass C:\n    x: int\nc: C\nif hasattr(c, \"x\"):\n    reveal_type(c.x)  # N: Revealed type is \"builtins.int\"\nelse:\n    # We don't mark this unreachable since people may check for deleted attributes\n    reveal_type(c.x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeInstance]\n# flags: --warn-unreachable\nclass B: ...\nb: B\nif hasattr(b, \"x\"):\n    reveal_type(b.x)  # N: Revealed type is \"Any\"\nelse:\n    b.x  # E: \"B\" has no attribute \"x\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeFunction]\n# flags: --warn-unreachable\ndef foo(x: int) -> None: ...\nif hasattr(foo, \"x\"):\n    reveal_type(foo.x)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeClassObject]\n# flags: --warn-unreachable\nclass C: ...\nif hasattr(C, \"x\"):\n    reveal_type(C.x)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeTypeType]\n# flags: --warn-unreachable\nfrom typing import Type\nclass C: ...\nc: Type[C]\nif hasattr(c, \"x\"):\n    reveal_type(c.x)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeTypeVar]\n# flags: --warn-unreachable\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\ndef foo(x: T) -> T:\n    if hasattr(x, \"x\"):\n        reveal_type(x.x)  # N: Revealed type is \"Any\"\n        return x\n    else:\n        return x\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeChained]\n# flags: --warn-unreachable\nclass B: ...\nb: B\nif hasattr(b, \"x\"):\n    reveal_type(b.x)  # N: Revealed type is \"Any\"\nelif hasattr(b, \"y\"):\n    reveal_type(b.y)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeNested]\n# flags: --warn-unreachable\nclass A: ...\nclass B: ...\n\nx: A\nif hasattr(x, \"x\"):\n    if isinstance(x, B):\n        reveal_type(x.x)  # N: Revealed type is \"Any\"\n\nif hasattr(x, \"x\") and hasattr(x, \"y\"):\n    reveal_type(x.x)  # N: Revealed type is \"Any\"\n    reveal_type(x.y)  # N: Revealed type is \"Any\"\n\nif hasattr(x, \"x\"):\n    if hasattr(x, \"y\"):\n        reveal_type(x.x)  # N: Revealed type is \"Any\"\n        reveal_type(x.y)  # N: Revealed type is \"Any\"\n\nif hasattr(x, \"x\") or hasattr(x, \"y\"):\n    x.x  # E: \"A\" has no attribute \"x\"\n    x.y  # E: \"A\" has no attribute \"y\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrPreciseType]\n# flags: --warn-unreachable\nclass A: ...\n\nx: A\nif hasattr(x, \"a\") and isinstance(x.a, int):\n    reveal_type(x.a)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeUnion]\n# flags: --warn-unreachable\nfrom typing import Union\n\nclass A: ...\nclass B:\n    x: int\n\nxu: Union[A, B]\nif hasattr(xu, \"x\"):\n    reveal_type(xu)  # N: Revealed type is \"__main__.A | __main__.B\"\n    reveal_type(xu.x)  # N: Revealed type is \"Any | builtins.int\"\nelse:\n    reveal_type(xu)  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeOuterUnion]\n# flags: --warn-unreachable\nfrom typing import Union\n\nclass A: ...\nclass B: ...\nxu: Union[A, B]\nif isinstance(xu, B):\n    if hasattr(xu, \"x\"):\n        reveal_type(xu.x)  # N: Revealed type is \"Any\"\n\nif isinstance(xu, B) and hasattr(xu, \"x\"):\n        reveal_type(xu.x)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrDoesntInterfereGetAttr]\n# flags: --warn-unreachable\nclass C:\n    def __getattr__(self, attr: str) -> str: ...\n\nc: C\nif hasattr(c, \"foo\"):\n    reveal_type(c.foo)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrMissingAttributeLiteral]\n# flags: --warn-unreachable\nfrom typing import Final\nclass B: ...\nb: B\nATTR: Final = \"x\"\nif hasattr(b, ATTR):\n    reveal_type(b.x)  # N: Revealed type is \"Any\"\nelse:\n    b.x  # E: \"B\" has no attribute \"x\"\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrDeferred]\n# flags: --warn-unreachable\ndef foo() -> str: ...\n\nclass Test:\n    def stream(self) -> None:\n        if hasattr(self, \"_body\"):\n            reveal_type(self._body)  # N: Revealed type is \"builtins.str\"\n\n    def body(self) -> str:\n        if not hasattr(self, \"_body\"):\n            self._body = foo()\n        return self._body\n[builtins fixtures/isinstance.pyi]\n\n[case testHasAttrModule]\n# flags: --warn-unreachable\nimport mod\n\nif hasattr(mod, \"y\"):\n    reveal_type(mod.y)  # N: Revealed type is \"Any\"\n    reveal_type(mod.x)  # N: Revealed type is \"builtins.int\"\nelse:\n    mod.y  # E: Module has no attribute \"y\"\n    reveal_type(mod.x)  # N: Revealed type is \"builtins.int\"\n\nif hasattr(mod, \"x\"):\n    mod.y  # E: Module has no attribute \"y\"\n    reveal_type(mod.x)  # N: Revealed type is \"builtins.int\"\nelse:\n    mod.y  # E: Module has no attribute \"y\"\n    reveal_type(mod.x)  # N: Revealed type is \"builtins.int\"\n\n[file mod.py]\nx: int\n[builtins fixtures/module.pyi]\n\n[case testHasAttrDoesntInterfereModuleGetAttr]\n# flags: --warn-unreachable\nimport mod\n\nif hasattr(mod, \"y\"):\n    reveal_type(mod.y)  # N: Revealed type is \"builtins.str\"\n\n[file mod.py]\ndef __getattr__(attr: str) -> str: ...\n[builtins fixtures/module.pyi]\n\n[case testMultipleHasAttr-xfail]\n# flags: --warn-unreachable\n# https://github.com/python/mypy/issues/20596\nfrom __future__ import annotations\nfrom typing import Any\n\ndef len(obj: object) -> Any: ...\n\ndef f(x: type | str):\n    if (\n        hasattr(x, \"__origin__\")\n        and x.__origin__ is list\n        and hasattr(x, \"__args__\")\n        and len(x.__args__) == 1\n    ):\n        reveal_type(x.__args__[0])  # N: Revealed type is \"Any\"\n[builtins fixtures/module.pyi]\n\n[case testTypeIsntLostAfterNarrowing]\n# flags: --warn-unreachable\nfrom typing import Any\n\nvar: Any\nreveal_type(var)  # N: Revealed type is \"Any\"\nassert isinstance(var, (bool, str))\nreveal_type(var)  # N: Revealed type is \"builtins.bool | builtins.str\"\n\nif isinstance(var, bool):\n    reveal_type(var)  # N: Revealed type is \"builtins.bool\"\n\n# Type of var shouldn't fall back to Any\nreveal_type(var)  # N: Revealed type is \"builtins.bool | builtins.str\"\n[builtins fixtures/isinstance.pyi]\n\n[case testReuseIntersectionForRepeatedIsinstanceCalls]\n# flags: --warn-unreachable\n\nclass A: ...\nclass B: ...\n\na: A\nif isinstance(a, B):\n    c = a\nif isinstance(a, B):\n    c = a\n\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceTypeAny]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\ndef foo(x: object, t: type[Any]):\n    if isinstance(x, t):\n        reveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceObject]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\ndef foo(x: object, t: object):\n    if isinstance(x, t):  # E: Argument 2 to \"isinstance\" has incompatible type \"object\"; expected \"type[object] | tuple[type[object], ...]\"\n        reveal_type(x)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIsInstanceOrExprInTuple]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\ndef f1(x: object):\n    if isinstance(x, str | (int, dict)):  # E: Argument 2 to \"isinstance\" has incompatible type \"object\"; expected \"type | tuple[Any, ...]\"\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    if type(x) == str | (int, dict):\n        reveal_type(x)  # N: Revealed type is \"builtins.object\"\n\ndef f2(x: Any):\n    if isinstance(x, str | (int, dict)):  # E: Argument 2 to \"isinstance\" has incompatible type \"object\"; expected \"type | tuple[Any, ...]\"\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    if type(x) == str | (int, dict):\n        reveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/primitives.pyi]\n\n[case testIsInstanceUnionOfTuples]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import TypeVar, Iterator, final\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\ndef extract(\n    values: object,\n    ts: (\n        tuple[type[T1]]\n        | tuple[type[T1], type[T2]]\n        | tuple[type[T1], type[T2], type[T3]]\n    )\n) -> Iterator[T1 | T2 | T3]:\n    if isinstance(values, ts):\n        reveal_type(values)  # N: Revealed type is \"T1`-1 | T2`-2 | T3`-3\"\n        yield values\n    raise\n\nclass A: ...\nclass B: ...\n\ndef f1(x: A | B, t: tuple[type[A]] | tuple[type[B]]):\n    if isinstance(x, t):\n        reveal_type(x)  # N: Revealed type is \"__main__.A | __main__.B\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.A | __main__.B\"\n\ndef f2(x: object, t: tuple[type[A]] | tuple[type[B]]):\n    if isinstance(x, t):\n        reveal_type(x)  # N: Revealed type is \"__main__.A | __main__.B\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.object\"\n\n@final\nclass FA: ...\n@final\nclass FB: ...\n\ndef g1(x: FA | FB, t: tuple[type[FA]] | tuple[type[FB]]):\n    if isinstance(x, t):\n        reveal_type(x)  # N: Revealed type is \"__main__.FA | __main__.FB\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.FA | __main__.FB\"\n\ndef g2(x: object, t: tuple[type[FA]] | tuple[type[FB]]):\n    if isinstance(x, t):\n        reveal_type(x)  # N: Revealed type is \"__main__.FA | __main__.FB\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/primitives.pyi]\n\n\n[case testIsInstanceTypeVarBoundToType]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import TypeVar, Protocol\n\nclass A(Protocol):\n    x: int\n\nT = TypeVar(\"T\", bound=type[A])\n\ndef foo(x: object, t: T):\n    if isinstance(x, t):\n        reveal_type(x)  # N: Revealed type is \"__main__.A\"\n        reveal_type(x.x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/primitives.pyi]\n\n\n[case testIsInstanceFinalTypeObject]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import final\n\n@final\nclass A: ...\n\ndef f1(x: A, t: type[A]):\n    if isinstance(x, A):\n        reveal_type(x)  # N: Revealed type is \"__main__.A\"\n    else:\n        reveal_type(x)  # E: Statement is unreachable\n\n    if isinstance(x, t):\n        reveal_type(x)  # N: Revealed type is \"__main__.A\"\n    else:\n        reveal_type(x)  # E: Statement is unreachable\n\ndef f2(x: A | None, t: type[A]):\n    if isinstance(x, A):\n        reveal_type(x)  # N: Revealed type is \"__main__.A\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"None\"\n\n    if isinstance(x, t):\n        reveal_type(x)  # N: Revealed type is \"__main__.A\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"None\"\n[builtins fixtures/isinstancelist.pyi]\n"
  },
  {
    "path": "test-data/unit/check-itertools.test",
    "content": "[case testItertoolsBatched312]\n# flags: --python-version 3.12\n\nfrom itertools import batched\n\nb = batched([0], 1)\nreveal_type(b)  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\nreveal_type(b.__next__())  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nreveal_type(batched([0, 0], 2))  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\nreveal_type(batched([0, 0, 0], 3))  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\nreveal_type(batched([0, 0, 0, 0], 4))  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\nreveal_type(batched([0, 0, 0, 0, 0], 5))  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\n\nreveal_type(batched([0], 2))  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\nreveal_type(batched([0], 2))  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\n\ndef f() -> int:\n    return 3\n\nreveal_type(batched([0, 0, 0], f()))  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testItertoolsBatched313]\n# flags: --python-version 3.13\n\nfrom itertools import batched\n\nb = batched([0], 1, strict=True)\nreveal_type(b)  # N: Revealed type is \"itertools.batched[tuple[builtins.int]]\"\nreveal_type(b.__next__())  # N: Revealed type is \"tuple[builtins.int]\"\n\nreveal_type(batched([0, 0], 2, strict=True))  # N: Revealed type is \"itertools.batched[tuple[builtins.int, builtins.int]]\"\nreveal_type(batched([0, 0, 0], 3, strict=True))  # N: Revealed type is \"itertools.batched[tuple[builtins.int, builtins.int, builtins.int]]\"\nreveal_type(batched([0, 0, 0, 0], 4, strict=True))  # N: Revealed type is \"itertools.batched[tuple[builtins.int, builtins.int, builtins.int, builtins.int]]\"\nreveal_type(batched([0, 0, 0, 0, 0], 5, strict=True))  # N: Revealed type is \"itertools.batched[tuple[builtins.int, builtins.int, builtins.int, builtins.int, builtins.int]]\"\n\nreveal_type(batched([0], 2),)  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\nreveal_type(batched([0], 2, strict=False))  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\n\ndef f() -> int:\n    return 3\n\nreveal_type(batched([0, 0, 0], f(), strict=True))  # N: Revealed type is \"itertools.batched[builtins.tuple[builtins.int, ...]]\"\n\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-kwargs.test",
    "content": "-- Test cases for keyword arguments.\n\n\n[case testTypeErrorInKeywordArgument]\nimport typing\ndef f(o: object) -> None: pass\nf(o=None()) # E: \"None\" not callable\n\n[case testSimpleKeywordArgument]\nimport typing\nclass A: pass\ndef f(a: 'A') -> None: pass\nf(a=A())\nf(a=object()) # E: Argument \"a\" to \"f\" has incompatible type \"object\"; expected \"A\"\n\n[case testTwoKeywordArgumentsNotInOrder]\nimport typing\nclass A: pass\nclass B: pass\ndef f(a: 'A', b: 'B') -> None: pass\nf(b=A(), a=A()) # E: Argument \"b\" to \"f\" has incompatible type \"A\"; expected \"B\"\nf(b=B(), a=B()) # E: Argument \"a\" to \"f\" has incompatible type \"B\"; expected \"A\"\nf(a=A(), b=B())\nf(b=B(), a=A())\n\n[case testOneOfSeveralOptionalKeywordArguments]\n# flags: --implicit-optional\nimport typing\nclass A: pass\nclass B: pass\nclass C: pass\ndef f(a: 'A' = None, b: 'B' = None, c: 'C' = None) -> None: pass\nf(a=A())\nf(b=B())\nf(c=C())\nf(b=B(), c=C())\nf(a=B()) # E: Argument \"a\" to \"f\" has incompatible type \"B\"; expected \"A | None\"\nf(b=A()) # E: Argument \"b\" to \"f\" has incompatible type \"A\"; expected \"B | None\"\nf(c=B()) # E: Argument \"c\" to \"f\" has incompatible type \"B\"; expected \"C | None\"\nf(b=B(), c=A()) # E: Argument \"c\" to \"f\" has incompatible type \"A\"; expected \"C | None\"\n[case testBothPositionalAndKeywordArguments]\nimport typing\nclass A: pass\nclass B: pass\ndef f(a: 'A', b: 'B') -> None: pass\nf(A(), b=A()) # E: Argument \"b\" to \"f\" has incompatible type \"A\"; expected \"B\"\nf(A(), b=B())\n\n[case testContextSensitiveTypeInferenceForKeywordArg]\nfrom typing import List\nclass A: pass\ndef f(a: 'A', b: 'List[A]') -> None: pass\nf(b=[], a=A())\n[builtins fixtures/list.pyi]\n\n[case testGivingArgumentAsPositionalAndKeywordArg]\n# flags: --no-strict-optional\nimport typing\nclass A: pass\nclass B: pass\ndef f(a: 'A', b: 'B' = None) -> None: pass\nf(A(), a=A()) # E: \"f\" gets multiple values for keyword argument \"a\"\n\n[case testGivingArgumentAsPositionalAndKeywordArg2]\n# flags: --no-strict-optional\nimport typing\nclass A: pass\nclass B: pass\ndef f(a: 'A' = None, b: 'B' = None) -> None: pass\nf(A(), a=A()) # E: \"f\" gets multiple values for keyword argument \"a\"\n\n[case testPositionalAndKeywordForSameArg]\n# This used to crash in check_argument_count(). See #1095.\ndef f(a: int): pass\ndef g(): f(0, a=1)\n[out]\n\n[case testInvalidKeywordArgument]\nimport typing\ndef f(a: 'A') -> None: pass\nf(b=object()) # E: Unexpected keyword argument \"b\" for \"f\"\nclass A: pass\n\n[case testKeywordMisspelling]\nclass A: pass\ndef f(other: 'A') -> None: pass\nf(otter=A()) # E: Unexpected keyword argument \"otter\" for \"f\"; did you mean \"other\"?\n\n[case testMultipleKeywordsForMisspelling]\nclass A: pass\nclass B: pass\ndef f(thing : 'A', other: 'A', atter: 'A', btter: 'B') -> None: pass\nf(otter=A()) # E: Unexpected keyword argument \"otter\" for \"f\"; did you mean \"atter\" or \"other\"?\n\n[case testKeywordMisspellingDifferentType]\nclass A: pass\nclass B: pass\ndef f(other: 'A') -> None: pass\nf(otter=B()) # E: Unexpected keyword argument \"otter\" for \"f\"; did you mean \"other\"?\n\n[case testKeywordMisspellingInheritance]\nclass A: pass\nclass B(A): pass\nclass C: pass\ndef f(atter: 'A', btter: 'B', ctter: 'C') -> None: pass\nf(otter=B()) # E: Unexpected keyword argument \"otter\" for \"f\"; did you mean \"atter\" or \"btter\"?\n\n[case testKeywordMisspellingFloatInt]\ndef f(atter: float, btter: int) -> None: pass\nx: int = 5\nf(otter=x) # E: Unexpected keyword argument \"otter\" for \"f\"; did you mean \"atter\" or \"btter\"?\n\n[case testKeywordMisspellingVarArgs]\nclass A: pass\ndef f(other: 'A', *atter: 'A') -> None: pass\nf(otter=A()) # E: Unexpected keyword argument \"otter\" for \"f\"; did you mean \"other\"?\n[builtins fixtures/tuple.pyi]\n\n[case testKeywordMisspellingOnlyVarArgs]\nclass A: pass\ndef f(*other: 'A') -> None: pass\nf(otter=A()) # E: Unexpected keyword argument \"otter\" for \"f\"\n[builtins fixtures/tuple.pyi]\n\n[case testKeywordMisspellingVarArgsDifferentTypes]\nclass A: pass\nclass B: pass\ndef f(other: 'B', *atter: 'A') -> None: pass\nf(otter=A()) # E: Unexpected keyword argument \"otter\" for \"f\"; did you mean \"other\"?\n[builtins fixtures/tuple.pyi]\n\n[case testKeywordMisspellingVarKwargs]\nclass A: pass\ndef f(other: 'A', **atter: 'A') -> None: pass\nf(otter=A()) # E: Missing positional argument \"other\" in call to \"f\"\n[builtins fixtures/dict.pyi]\n\n[case testKeywordArgumentsWithDynamicallyTypedCallable]\nfrom typing import Any\nf: Any\nf(x=f(), z=None()) # E: \"None\" not callable\nf(f, zz=None()) # E: \"None\" not callable\nf(x=None)\n\n[case testKeywordArgumentWithFunctionObject]\nfrom typing import Callable\nclass A: pass\nclass B: pass\nf: Callable[[A, B], None]\nf(a=A(), b=B())  # E: Unexpected keyword argument \"a\"  # E: Unexpected keyword argument \"b\"\nf(A(), b=B())  # E: Unexpected keyword argument \"b\"\n\n[case testKeywordOnlyArguments]\n# flags: --no-strict-optional\nimport typing\nclass A: pass\nclass B: pass\ndef f(a: 'A', *, b: 'B' = None) -> None: pass\ndef g(a: 'A', *, b: 'B') -> None: pass\ndef h(a: 'A', *, b: 'B', aa: 'A') -> None: pass\ndef i(a: 'A', *, b: 'B', aa: 'A' = None) -> None: pass\nf(A(), b=B())\nf(b=B(), a=A())\nf(A())\nf(A(), B()) # E: Too many positional arguments for \"f\"\ng(A(), b=B())\ng(b=B(), a=A())\ng(A()) # E: Missing named argument \"b\" for \"g\"\ng(A(), B()) # E: Too many positional arguments for \"g\"\nh(A()) # E: Missing named argument \"b\" for \"h\" # E: Missing named argument \"aa\" for \"h\"\nh(A(), b=B()) # E: Missing named argument \"aa\" for \"h\"\nh(A(), aa=A()) # E: Missing named argument \"b\" for \"h\"\nh(A(), b=B(), aa=A())\nh(A(), aa=A(), b=B())\ni(A()) # E: Missing named argument \"b\" for \"i\"\ni(A(), b=B())\ni(A(), aa=A()) # E: Missing named argument \"b\" for \"i\"\ni(A(), b=B(), aa=A())\ni(A(), aa=A(), b=B())\n\n[case testKeywordOnlyArgumentsFastparse]\n# flags: --no-strict-optional\nimport typing\n\nclass A: pass\nclass B: pass\n\ndef f(a: 'A', *, b: 'B' = None) -> None: pass\ndef g(a: 'A', *, b: 'B') -> None: pass\ndef h(a: 'A', *, b: 'B', aa: 'A') -> None: pass\ndef i(a: 'A', *, b: 'B', aa: 'A' = None) -> None: pass\nf(A(), b=B())\nf(b=B(), a=A())\nf(A())\nf(A(), B()) # E: Too many positional arguments for \"f\"\ng(A(), b=B())\ng(b=B(), a=A())\ng(A()) # E: Missing named argument \"b\" for \"g\"\ng(A(), B()) # E: Too many positional arguments for \"g\"\nh(A()) # E: Missing named argument \"b\" for \"h\" # E: Missing named argument \"aa\" for \"h\"\nh(A(), b=B()) # E: Missing named argument \"aa\" for \"h\"\nh(A(), aa=A()) # E: Missing named argument \"b\" for \"h\"\nh(A(), b=B(), aa=A())\nh(A(), aa=A(), b=B())\ni(A()) # E: Missing named argument \"b\" for \"i\"\ni(A(), b=B())\ni(A(), aa=A()) # E: Missing named argument \"b\" for \"i\"\ni(A(), b=B(), aa=A())\ni(A(), aa=A(), b=B())\n[case testKwargsAfterBareArgs]\nfrom typing import Tuple, Any\ndef f(a, *, b=None) -> None: pass\na = None  # type: Any\nb = None  # type: Any\nf(a, **b)\n\n[builtins fixtures/dict.pyi]\n\n[case testKeywordArgAfterVarArgs]\n# flags: --implicit-optional\nimport typing\nclass A: pass\nclass B: pass\ndef f(*a: 'A', b: 'B' = None) -> None: pass\nf()\nf(A())\nf(A(), A())\nf(b=B())\nf(A(), b=B())\nf(A(), A(), b=B())\nf(B())      # E: Argument 1 to \"f\" has incompatible type \"B\"; expected \"A\"\nf(A(), B()) # E: Argument 2 to \"f\" has incompatible type \"B\"; expected \"A\"\nf(b=A())    # E: Argument \"b\" to \"f\" has incompatible type \"A\"; expected \"B | None\"\n[builtins fixtures/list.pyi]\n\n[case testKeywordArgAfterVarArgsWithBothCallerAndCalleeVarArgs]\n# flags: --implicit-optional --no-strict-optional\nfrom typing import List\nclass A: pass\nclass B: pass\ndef f(*a: 'A', b: 'B' = None) -> None: pass\na = None # type: List[A]\nf(*a)\nf(A(), *a)\nf(b=B())\nf(*a, b=B())\nf(A(), *a, b=B())\nf(A(), B())   # E: Argument 2 to \"f\" has incompatible type \"B\"; expected \"A\"\nf(A(), b=A()) # E: Argument \"b\" to \"f\" has incompatible type \"A\"; expected \"B | None\"\nf(*a, b=A())  # E: Argument \"b\" to \"f\" has incompatible type \"A\"; expected \"B | None\"\n[builtins fixtures/list.pyi]\n\n[case testCallingDynamicallyTypedFunctionWithKeywordArgs]\nimport typing\nclass A: pass\ndef f(x, y=A()): pass\nf(x=A(), y=A())\nf(y=A(), x=A())\nf(y=A())      # E: Missing positional argument \"x\" in call to \"f\"\nf(A(), z=A()) # E: Unexpected keyword argument \"z\" for \"f\"\n\n[case testKwargsArgumentInFunctionBody]\nfrom typing import Dict, Any\ndef f( **kwargs: 'A') -> None:\n    d1 = kwargs # type: Dict[str, A]\n    d2 = kwargs # type: Dict[A, Any] # E: Incompatible types in assignment (expression has type \"dict[str, A]\", variable has type \"dict[A, Any]\")\n    d3 = kwargs # type: Dict[Any, str] # E: Incompatible types in assignment (expression has type \"dict[str, A]\", variable has type \"dict[Any, str]\")\nclass A: pass\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testKwargsArgumentInFunctionBodyWithImplicitAny]\nfrom typing import Dict, Any\ndef f(**kwargs) -> None:\n    d1 = kwargs # type: Dict[str, A]\n    d2 = kwargs # type: Dict[str, str]\n    d3 = kwargs # type: Dict[A, Any] # E: Incompatible types in assignment (expression has type \"dict[str, Any]\", variable has type \"dict[A, Any]\")\nclass A: pass\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testCallingFunctionThatAcceptsVarKwargs]\nimport typing\nclass A: pass\nclass B: pass\ndef f( **kwargs: 'A') -> None: pass\nf()\nf(x=A())\nf(y=A(), z=A())\nf(x=B()) # E: Argument \"x\" to \"f\" has incompatible type \"B\"; expected \"A\"\nf(A())   # E: Too many arguments for \"f\"\n# Perhaps a better message would be \"Too many *positional* arguments...\"\n[builtins fixtures/dict.pyi]\n\n[case testCallingFunctionWithKeywordVarArgs]\nfrom typing import Dict\nclass A: pass\nclass B: pass\ndef f( **kwargs: 'A') -> None: pass\nd: Dict[str, A]\nf(**d)\nf(x=A(), **d)\nd2: Dict[str, B]\nf(**d2)         # E: Argument 1 to \"f\" has incompatible type \"**dict[str, B]\"; expected \"A\"\nf(x=A(), **d2)  # E: Argument 2 to \"f\" has incompatible type \"**dict[str, B]\"; expected \"A\"\nf(**{'x': B()}) # E: Argument 1 to \"f\" has incompatible type \"**dict[str, B]\"; expected \"A\"\n[builtins fixtures/dict.pyi]\n\n[case testKwargsAllowedInDunderCall]\nclass Formatter:\n    def __call__(self, message: str, bold: bool = False) -> str:\n        pass\n\nformatter = Formatter()\nformatter(\"test\", bold=True)\nreveal_type(formatter.__call__)  # N: Revealed type is \"def (message: builtins.str, bold: builtins.bool =) -> builtins.str\"\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testKwargsAllowedInDunderCallKwOnly]\nclass Formatter:\n    def __call__(self, message: str, *, bold: bool = False) -> str:\n        pass\n\nformatter = Formatter()\nformatter(\"test\", bold=True)\nreveal_type(formatter.__call__)  # N: Revealed type is \"def (message: builtins.str, *, bold: builtins.bool =) -> builtins.str\"\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testPassingMappingForKeywordVarArg]\nfrom typing import Mapping\ndef f(**kwargs: 'A') -> None: pass\nb: Mapping\nd: Mapping[A, A]\nm: Mapping[str, A]\nf(**d)         # E: Argument after ** must have string keys\nf(**m)\nf(**b)\nclass A: pass\n[builtins fixtures/dict.pyi]\n\n[case testPassingMappingSubclassForKeywordVarArg]\nfrom typing import Mapping\nclass MappingSubclass(Mapping[str, str]): pass\ndef f(**kwargs: 'A') -> None: pass\nd: MappingSubclass\nf(**d)  # E: Argument 1 to \"f\" has incompatible type \"**MappingSubclass\"; expected \"A\"\nclass A: pass\n[builtins fixtures/dict.pyi]\n\n[case testInvalidTypeForKeywordVarArg]\nfrom typing import Dict, Any, Optional\nclass A: pass\ndef f(**kwargs: 'A') -> None: pass\nd = {} # type: Dict[A, A]\nf(**d)         # E: Argument after ** must have string keys\nf(**A())       # E: Argument after ** must be a mapping, not \"A\"\nkwargs: Optional[Any]\nf(**kwargs)    # E: Argument after ** must be a mapping, not \"Any | None\"\n\ndef g(a: int) -> None: pass\ng(a=1, **4)  # E: Argument after ** must be a mapping, not \"int\"\n\ndef main(f: Any) -> None:\n    f(**3)  # E: Argument after ** must be a mapping, not \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testPassingKeywordVarArgsToNonVarArgsFunction]\nfrom typing import Any, Dict\ndef f(a: 'A', b: 'B') -> None: pass\nd: Dict[str, Any]\nf(**d)\nd2: Dict[str, A]\nf(**d2) # E: Argument 1 to \"f\" has incompatible type \"**dict[str, A]\"; expected \"B\"\nclass A: pass\nclass B: pass\n[builtins fixtures/dict.pyi]\n\n[case testBothKindsOfVarArgs]\nfrom typing import Any, List, Dict\ndef f(a: 'A', b: 'A') -> None: pass\nl: List[Any]\nd: Dict[Any, Any]\nf(*l, **d)\nclass A: pass\n[builtins fixtures/dict.pyi]\n\n[case testPassingMultipleKeywordVarArgs]\nfrom typing import Any, Dict\ndef f1(a: 'A', b: 'A') -> None: pass\ndef f2(a: 'A') -> None: pass\ndef f3(a: 'A', **kwargs: 'A') -> None: pass\ndef f4(**kwargs: 'A') -> None: pass\nd: Dict[Any, Any]\nd2: Dict[Any, Any]\nf1(**d, **d2)\nf2(**d, **d2)\nf3(**d, **d2)\nf4(**d, **d2)\nclass A: pass\n[builtins fixtures/dict.pyi]\n\n[case testPassingKeywordVarArgsToVarArgsOnlyFunction]\nfrom typing import Any, Dict\ndef f(*args: 'A') -> None: pass\nd: Dict[Any, Any]\nf(**d)\nclass A: pass\n[builtins fixtures/dict.pyi]\n\n[case testKeywordArgumentAndCommentSignature]\nimport typing\ndef f(x): # type: (int) -> str\n    pass\nf(x='') # E: Argument \"x\" to \"f\" has incompatible type \"str\"; expected \"int\"\nf(x=0)\nf(y=0) # E: Unexpected keyword argument \"y\" for \"f\"\n\n[case testKeywordArgumentAndCommentSignature2]\nimport typing\nclass A:\n    def f(self, x): # type: (int) -> str\n        pass\nA().f(x='') # E: Argument \"x\" to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\nA().f(x=0)\nA().f(y=0) # E: Unexpected keyword argument \"y\" for \"f\" of \"A\"\n\n[case testKeywordVarArgsAndCommentSignature]\nimport typing\ndef f(**kwargs): # type: (**int) -> None\n    pass\nf(z=1)\nf(x=1, y=1)\nf(x='', y=1) # E: Argument \"x\" to \"f\" has incompatible type \"str\"; expected \"int\"\nf(x=1, y='') # E: Argument \"y\" to \"f\" has incompatible type \"str\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testCallsWithStars]\ndef f(a: int) -> None:\n    pass\n\ns = ('',)\nf(*s) # E: Argument 1 to \"f\" has incompatible type \"*tuple[str]\"; expected \"int\"\n\na = {'': 0}\nf(a) # E: Argument 1 to \"f\" has incompatible type \"dict[str, int]\"; expected \"int\"\nf(**a) # okay\n\nb = {'': ''}\nf(b) # E: Argument 1 to \"f\" has incompatible type \"dict[str, str]\"; expected \"int\"\nf(**b) # E: Argument 1 to \"f\" has incompatible type \"**dict[str, str]\"; expected \"int\"\n\nc = {0: 0}\nf(**c) # E: Argument after ** must have string keys\n[builtins fixtures/dict.pyi]\n\n[case testCallStar2WithStar]\ndef f(**k): pass\nf(*(1, 2))  # E: Too many arguments for \"f\"\n[builtins fixtures/dict.pyi]\n\n[case testUnexpectedMethodKwargInNestedClass]\nclass A:\n    class B:\n        def __init__(self) -> None:\n            pass\nA.B(x=1)  # E: Unexpected keyword argument \"x\" for \"B\"\n\n[case testUnexpectedMethodKwargFromOtherModule]\nimport m\nm.A(x=1)\n[file m.py]\n1+'asdf'\nclass A:\n    def __init__(self) -> None:\n        pass\n[out]\ntmp/m.py:1: error: Unsupported operand types for + (\"int\" and \"str\")\nmain:2: error: Unexpected keyword argument \"x\" for \"A\"\nmain:2: note: \"A\" defined in \"m\"\n\n[case testMissingNamedArgumentFromOtherModule]\nimport m\nm.f(1)\nm.f(a=1)\n[file m.py]\ndef f(a: int, *, b: str) -> None:\n    pass\n[out]\nmain:2: error: Missing named argument \"b\" for \"f\"\nmain:2: note: \"f\" defined in \"m\"\nmain:3: error: Missing named argument \"b\" for \"f\"\nmain:3: note: \"f\" defined in \"m\"\n\n[case testMissingNamedArgumentForSameModule]\ndef f(a: int, *, b: str) -> None:\n    pass\nf(1)  # E: Missing named argument \"b\" for \"f\"\n\n[case testStarArgsAndKwArgsSpecialCase]\nfrom typing import Dict, Mapping\n\ndef f(*vargs: int, **kwargs: object) -> None:\n\tpass\n\ndef g(arg: int = 0, **kwargs: object) -> None:\n\tpass\n\nd = {} # type: Dict[str, object]\nf(**d)\ng(**d)  # E: Argument 1 to \"g\" has incompatible type \"**dict[str, object]\"; expected \"int\"\n\nm = {} # type: Mapping[str, object]\nf(**m)\ng(**m)  # E: Argument 1 to \"g\" has incompatible type \"**Mapping[str, object]\"; expected \"int\"\n[builtins fixtures/dict.pyi]\n\n[case testPassingEmptyDictWithStars]\ndef f(): pass\ndef g(x=1): pass\n\nf(**{})\ng(**{})\n[builtins fixtures/dict.pyi]\n\n[case testKeywordUnpackWithDifferentTypes]\n# https://github.com/python/mypy/issues/11144\nfrom typing import Dict, Generic, TypeVar, Mapping, Iterable\n\nT = TypeVar(\"T\")\nT2 = TypeVar(\"T2\")\n\nclass A(Dict[T, T2]):\n    ...\n\nclass B(Mapping[T, T2]):\n    ...\n\nclass C(Generic[T, T2]):\n    ...\n\nclass D:\n    ...\n\nclass E:\n    def keys(self) -> Iterable[str]:\n        ...\n    def __getitem__(self, key: str) -> float:\n        ...\n\ndef foo(**i: float) -> float:\n    ...\n\na: A[str, str]\nb: B[str, str]\nc: C[str, float]\nd: D\ne: E\nf = {\"a\": \"b\"}\n\nfoo(k=1.5)\nfoo(**a)\nfoo(**b)\nfoo(**c)\nfoo(**d)\nfoo(**e)\nfoo(**f)\n\n# Correct:\n\nclass Good(Mapping[str, float]):\n    ...\n\ngood1: Good\ngood2: A[str, float]\ngood3: B[str, float]\nfoo(**good1)\nfoo(**good2)\nfoo(**good3)\n[out]\nmain:36: error: Argument 1 to \"foo\" has incompatible type \"**A[str, str]\"; expected \"float\"\nmain:37: error: Argument 1 to \"foo\" has incompatible type \"**B[str, str]\"; expected \"float\"\nmain:38: error: Argument after ** must be a mapping, not \"C[str, float]\"\nmain:39: error: Argument after ** must be a mapping, not \"D\"\nmain:41: error: Argument 1 to \"foo\" has incompatible type \"**dict[str, str]\"; expected \"float\"\n[builtins fixtures/dict.pyi]\n\n[case testLiteralKwargs]\nfrom typing import Any, Literal\nkw: dict[Literal[\"a\", \"b\"], Any]\ndef func(a, b): ...\nfunc(**kw)\n\nbadkw: dict[Literal[\"one\", 1], Any]\nfunc(**badkw)  # E: Argument after ** must have string keys\n[builtins fixtures/dict.pyi]\n"
  },
  {
    "path": "test-data/unit/check-lists.test",
    "content": "-- Nested list assignment\n-- -----------------------------\n\n[case testNestedListAssignment]\nfrom typing import List\na1: A\na2: A\nb1: B\nb2: B\nc1: C\nc2: C\n\nif int():\n    a1, [b1, c1] = a2, [b2, c2]\nif int():\n    a1, [a1, [b1, c1]] = a2, [a2, [b2, c2]]\nif int():\n    a1, [a1, [a1, b1]] = a1, [a1, [a1, c1]]  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"B\")\n\nclass A: pass\nclass B: pass\nclass C: pass\n[builtins fixtures/list.pyi]\n[out]\n\n[case testNestedListAssignmentToTuple]\nfrom typing import List\na: A\nb: B\nc: C\n\na, b = [a, b]\na, b = [a]  # E: Need more than 1 value to unpack (2 expected)\na, b = [a, b, c]  # E: Too many values to unpack (2 expected, 3 provided)\n\nclass A: pass\nclass B: pass\nclass C: pass\n[builtins fixtures/list.pyi]\n[out]\n\n[case testListAssignmentFromTuple]\nfrom typing import List\na: A\nb: B\nc: C\nt = a, b\n\nif int():\n    [a, b], c = t, c\nif int():\n    [a, c], c = t, c  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"C\")\nif int():\n    [a, a, a], c = t, c  # E: Need more than 2 values to unpack (3 expected)\nif int():\n    [a], c = t, c  # E: Too many values to unpack (1 expected, 2 provided)\n\nclass A: pass\nclass B: pass\nclass C: pass\n[builtins fixtures/list.pyi]\n[out]\n\n[case testListAssignmentUnequalAmountToUnpack]\nfrom typing import List\na: A\nb: B\nc: C\n\ndef f() -> None: # needed because test parser tries to parse [a, b] as section header\n    [a, b] = [a, b]\n    [a, b] = [a]  # E: Need more than 1 value to unpack (2 expected)\n    [a, b] = [a, b, c]  # E: Too many values to unpack (2 expected, 3 provided)\n\nclass A: pass\nclass B: pass\nclass C: pass\n[builtins fixtures/list.pyi]\n[out]\n\n[case testListWithStarExpr]\n(x, *a) = [1, 2, 3]\na = [1, *[2, 3]]\nreveal_type(a)  # N: Revealed type is \"builtins.list[builtins.int]\"\nb = [0, *a]\nreveal_type(b)  # N: Revealed type is \"builtins.list[builtins.int]\"\nc = [*a, 0]\nreveal_type(c)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testComprehensionShadowBinder]\ndef foo(x: object) -> None:\n    if isinstance(x, str):\n        [reveal_type(x) for x in [1, 2, 3]]  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testUnpackAssignmentWithStarExpr]\na: A\nb: list[B]\nif int():\n    (a,) = [*b]  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\nclass A: pass\nclass B: pass\n"
  },
  {
    "path": "test-data/unit/check-literal.test",
    "content": "--\n-- Check to see how we handle raw types, error handling, and other\n-- semantic analysis shenanigans\n--\n\n[case testLiteralInvalidString]\nfrom typing import Literal\ndef f1(x: 'A[') -> None: pass  # E: Invalid type comment or annotation\ndef g1(x: Literal['A[']) -> None: pass\nreveal_type(f1)  # N: Revealed type is \"def (x: Any)\"\nreveal_type(g1)  # N: Revealed type is \"def (x: Literal['A['])\"\n\ndef f2(x: 'A B') -> None: pass  # E: Invalid type comment or annotation\ndef g2(x: Literal['A B']) -> None: pass\ndef h2(x: 'A|int') -> None: pass  # E: Name \"A\" is not defined\ndef i2(x: Literal['A|B']) -> None: pass\nreveal_type(f2)  # N: Revealed type is \"def (x: Any)\"\nreveal_type(g2)  # N: Revealed type is \"def (x: Literal['A B'])\"\nreveal_type(h2)  # N: Revealed type is \"def (x: Any | builtins.int)\"\nreveal_type(i2)  # N: Revealed type is \"def (x: Literal['A|B'])\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralInvalidTypeComment]\nfrom typing import Literal\ndef f(x):  # E: Syntax error in type comment \"(A[) -> None\"\n    # type: (A[) -> None\n    pass\n\n[case testLiteralInvalidTypeComment2]\nfrom typing import Literal\ndef f(x):  # E: Invalid type comment or annotation\n    # type: (\"A[\") -> None\n    pass\n\ndef g(x):\n    # type: (Literal[\"A[\"]) -> None\n    pass\n\nreveal_type(f)  # N: Revealed type is \"def (x: Any)\"\nreveal_type(g)  # N: Revealed type is \"def (x: Literal['A['])\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralFromTypingWorks]\nfrom typing import Literal\n\nx: Literal[42]\nx = 43  # E: Incompatible types in assignment (expression has type \"Literal[43]\", variable has type \"Literal[42]\")\n\ny: Literal[43]\ny = 43\n[typing fixtures/typing-medium.pyi]\n\n[case testLiteralFromTypingExtensionsWorks]\nfrom typing_extensions import Literal\n\nx: Literal[42]\nx = 43  # E: Incompatible types in assignment (expression has type \"Literal[43]\", variable has type \"Literal[42]\")\n\ny: Literal[43]\ny = 43\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralInsideOtherTypes]\nfrom typing import Literal, Tuple\n\nx: Tuple[1]                         # E: Invalid type: try using Literal[1] instead?\ndef foo(x: Tuple[1]) -> None: ...   # E: Invalid type: try using Literal[1] instead?\n\ny: Tuple[Literal[2]]\ndef bar(x: Tuple[Literal[2]]) -> None: ...\nreveal_type(x)                      # N: Revealed type is \"tuple[Any]\"\nreveal_type(y)                      # N: Revealed type is \"tuple[Literal[2]]\"\nreveal_type(bar)                    # N: Revealed type is \"def (x: tuple[Literal[2]])\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralInsideOtherTypesTypeCommentsPython3]\nfrom typing import Literal, Tuple, Optional\n\nx = None  # type: Optional[Tuple[1]]  # E: Invalid type: try using Literal[1] instead?\ndef foo(x):                           # E: Invalid type: try using Literal[1] instead?\n    # type: (Tuple[1]) -> None\n    pass\n\ny = None  # type: Optional[Tuple[Literal[2]]]\ndef bar(x):\n    # type: (Tuple[Literal[2]]) -> None\n    pass\nreveal_type(x)                      # N: Revealed type is \"tuple[Any] | None\"\nreveal_type(y)                      # N: Revealed type is \"tuple[Literal[2]] | None\"\nreveal_type(bar)                    # N: Revealed type is \"def (x: tuple[Literal[2]])\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralValidExpressionsInStringsPython3]\nfrom wrapper import *\n\n[file wrapper.pyi]\nfrom typing import Literal\n\nalias_1 = Literal['a+b']\nalias_2 = Literal['1+2']\nalias_3 = Literal['3']\nalias_4 = Literal['True']\nalias_5 = Literal['None']\nalias_6 = Literal['\"foo\"']\nexpr_of_alias_1: alias_1\nexpr_of_alias_2: alias_2\nexpr_of_alias_3: alias_3\nexpr_of_alias_4: alias_4\nexpr_of_alias_5: alias_5\nexpr_of_alias_6: alias_6\nreveal_type(expr_of_alias_1)  # N: Revealed type is \"Literal['a+b']\"\nreveal_type(expr_of_alias_2)  # N: Revealed type is \"Literal['1+2']\"\nreveal_type(expr_of_alias_3)  # N: Revealed type is \"Literal['3']\"\nreveal_type(expr_of_alias_4)  # N: Revealed type is \"Literal['True']\"\nreveal_type(expr_of_alias_5)  # N: Revealed type is \"Literal['None']\"\nreveal_type(expr_of_alias_6)  # N: Revealed type is \"Literal['\"foo\"']\"\n\nexpr_ann_1: Literal['a+b']\nexpr_ann_2: Literal['1+2']\nexpr_ann_3: Literal['3']\nexpr_ann_4: Literal['True']\nexpr_ann_5: Literal['None']\nexpr_ann_6: Literal['\"foo\"']\nreveal_type(expr_ann_1)  # N: Revealed type is \"Literal['a+b']\"\nreveal_type(expr_ann_2)  # N: Revealed type is \"Literal['1+2']\"\nreveal_type(expr_ann_3)  # N: Revealed type is \"Literal['3']\"\nreveal_type(expr_ann_4)  # N: Revealed type is \"Literal['True']\"\nreveal_type(expr_ann_5)  # N: Revealed type is \"Literal['None']\"\nreveal_type(expr_ann_6)  # N: Revealed type is \"Literal['\"foo\"']\"\n\nexpr_str_1: \"Literal['a+b']\"\nexpr_str_2: \"Literal['1+2']\"\nexpr_str_3: \"Literal['3']\"\nexpr_str_4: \"Literal['True']\"\nexpr_str_5: \"Literal['None']\"\nexpr_str_6: \"Literal['\\\"foo\\\"']\"\nreveal_type(expr_str_1)  # N: Revealed type is \"Literal['a+b']\"\nreveal_type(expr_str_2)  # N: Revealed type is \"Literal['1+2']\"\nreveal_type(expr_str_3)  # N: Revealed type is \"Literal['3']\"\nreveal_type(expr_str_4)  # N: Revealed type is \"Literal['True']\"\nreveal_type(expr_str_5)  # N: Revealed type is \"Literal['None']\"\nreveal_type(expr_str_6)  # N: Revealed type is \"Literal['\"foo\"']\"\n\nexpr_com_1 = ...   # type: Literal['a+b']\nexpr_com_2 = ...   # type: Literal['1+2']\nexpr_com_3 = ...   # type: Literal['3']\nexpr_com_4 = ...   # type: Literal['True']\nexpr_com_5 = ...   # type: Literal['None']\nexpr_com_6 = ...   # type: Literal['\"foo\"']\nreveal_type(expr_com_1)  # N: Revealed type is \"Literal['a+b']\"\nreveal_type(expr_com_2)  # N: Revealed type is \"Literal['1+2']\"\nreveal_type(expr_com_3)  # N: Revealed type is \"Literal['3']\"\nreveal_type(expr_com_4)  # N: Revealed type is \"Literal['True']\"\nreveal_type(expr_com_5)  # N: Revealed type is \"Literal['None']\"\nreveal_type(expr_com_6)  # N: Revealed type is \"Literal['\"foo\"']\"\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testLiteralMixingUnicodeAndBytesPython3]\nfrom typing import Literal\n\na_ann: Literal[u\"foo\"]\nb_ann: Literal[\"foo\"]\nc_ann: Literal[b\"foo\"]\n\na_hint = u\"foo\"  # type: Literal[u\"foo\"]\nb_hint = \"foo\"   # type: Literal[\"foo\"]\nc_hint = b\"foo\"  # type: Literal[b\"foo\"]\n\nAAlias = Literal[u\"foo\"]\nBAlias = Literal[\"foo\"]\nCAlias = Literal[b\"foo\"]\na_alias: AAlias\nb_alias: BAlias\nc_alias: CAlias\n\ndef accepts_str_1(x: Literal[u\"foo\"]) -> None: pass\ndef accepts_str_2(x: Literal[\"foo\"]) -> None: pass\ndef accepts_bytes(x: Literal[b\"foo\"]) -> None: pass\n\nreveal_type(a_ann)      # N: Revealed type is \"Literal['foo']\"\nreveal_type(b_ann)      # N: Revealed type is \"Literal['foo']\"\nreveal_type(c_ann)      # N: Revealed type is \"Literal[b'foo']\"\nreveal_type(a_hint)     # N: Revealed type is \"Literal['foo']\"\nreveal_type(b_hint)     # N: Revealed type is \"Literal['foo']\"\nreveal_type(c_hint)     # N: Revealed type is \"Literal[b'foo']\"\nreveal_type(a_alias)    # N: Revealed type is \"Literal['foo']\"\nreveal_type(b_alias)    # N: Revealed type is \"Literal['foo']\"\nreveal_type(c_alias)    # N: Revealed type is \"Literal[b'foo']\"\n\naccepts_str_1(a_ann)\naccepts_str_1(b_ann)\naccepts_str_1(c_ann)    # E: Argument 1 to \"accepts_str_1\" has incompatible type \"Literal[b'foo']\"; expected \"Literal['foo']\"\naccepts_str_1(a_hint)\naccepts_str_1(b_hint)\naccepts_str_1(c_hint)   # E: Argument 1 to \"accepts_str_1\" has incompatible type \"Literal[b'foo']\"; expected \"Literal['foo']\"\naccepts_str_1(a_alias)\naccepts_str_1(b_alias)\naccepts_str_1(c_alias)  # E: Argument 1 to \"accepts_str_1\" has incompatible type \"Literal[b'foo']\"; expected \"Literal['foo']\"\n\naccepts_str_2(a_ann)\naccepts_str_2(b_ann)\naccepts_str_2(c_ann)    # E: Argument 1 to \"accepts_str_2\" has incompatible type \"Literal[b'foo']\"; expected \"Literal['foo']\"\naccepts_str_2(a_hint)\naccepts_str_2(b_hint)\naccepts_str_2(c_hint)   # E: Argument 1 to \"accepts_str_2\" has incompatible type \"Literal[b'foo']\"; expected \"Literal['foo']\"\naccepts_str_2(a_alias)\naccepts_str_2(b_alias)\naccepts_str_2(c_alias)  # E: Argument 1 to \"accepts_str_2\" has incompatible type \"Literal[b'foo']\"; expected \"Literal['foo']\"\n\naccepts_bytes(a_ann)    # E: Argument 1 to \"accepts_bytes\" has incompatible type \"Literal['foo']\"; expected \"Literal[b'foo']\"\naccepts_bytes(b_ann)    # E: Argument 1 to \"accepts_bytes\" has incompatible type \"Literal['foo']\"; expected \"Literal[b'foo']\"\naccepts_bytes(c_ann)\naccepts_bytes(a_hint)   # E: Argument 1 to \"accepts_bytes\" has incompatible type \"Literal['foo']\"; expected \"Literal[b'foo']\"\naccepts_bytes(b_hint)   # E: Argument 1 to \"accepts_bytes\" has incompatible type \"Literal['foo']\"; expected \"Literal[b'foo']\"\naccepts_bytes(c_hint)\naccepts_bytes(a_alias)  # E: Argument 1 to \"accepts_bytes\" has incompatible type \"Literal['foo']\"; expected \"Literal[b'foo']\"\naccepts_bytes(b_alias)  # E: Argument 1 to \"accepts_bytes\" has incompatible type \"Literal['foo']\"; expected \"Literal[b'foo']\"\naccepts_bytes(c_alias)\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralMixingUnicodeAndBytesPython3ForwardStrings_no_native_parse]\nfrom typing import Literal, TypeVar, Generic\n\na_unicode_wrapper: u\"Literal[u'foo']\"\nb_unicode_wrapper: u\"Literal['foo']\"\nc_unicode_wrapper: u\"Literal[b'foo']\"\n\na_str_wrapper: \"Literal[u'foo']\"\nb_str_wrapper: \"Literal['foo']\"\nc_str_wrapper: \"Literal[b'foo']\"\n\n# In Python 3, forward references MUST be str, not bytes\na_bytes_wrapper: b\"Literal[u'foo']\"  # E: Invalid type comment or annotation\nb_bytes_wrapper: b\"Literal['foo']\"   # E: Invalid type comment or annotation\nc_bytes_wrapper: b\"Literal[b'foo']\"  # E: Invalid type comment or annotation\n\nreveal_type(a_unicode_wrapper)  # N: Revealed type is \"Literal['foo']\"\nreveal_type(b_unicode_wrapper)  # N: Revealed type is \"Literal['foo']\"\nreveal_type(c_unicode_wrapper)  # N: Revealed type is \"Literal[b'foo']\"\n\nreveal_type(a_str_wrapper)      # N: Revealed type is \"Literal['foo']\"\nreveal_type(b_str_wrapper)      # N: Revealed type is \"Literal['foo']\"\nreveal_type(c_str_wrapper)      # N: Revealed type is \"Literal[b'foo']\"\n\nT = TypeVar('T')\nclass Wrap(Generic[T]): pass\n\nAUnicodeWrapperAlias = Wrap[u\"Literal[u'foo']\"]\nBUnicodeWrapperAlias = Wrap[u\"Literal['foo']\"]\nCUnicodeWrapperAlias = Wrap[u\"Literal[b'foo']\"]\na_unicode_wrapper_alias: AUnicodeWrapperAlias\nb_unicode_wrapper_alias: BUnicodeWrapperAlias\nc_unicode_wrapper_alias: CUnicodeWrapperAlias\n\nAStrWrapperAlias = Wrap[\"Literal[u'foo']\"]\nBStrWrapperAlias = Wrap[\"Literal['foo']\"]\nCStrWrapperAlias = Wrap[\"Literal[b'foo']\"]\na_str_wrapper_alias: AStrWrapperAlias\nb_str_wrapper_alias: BStrWrapperAlias\nc_str_wrapper_alias: CStrWrapperAlias\n\nABytesWrapperAlias = Wrap[b\"Literal[u'foo']\"]\nBBytesWrapperAlias = Wrap[b\"Literal['foo']\"]\nCBytesWrapperAlias = Wrap[b\"Literal[b'foo']\"]\na_bytes_wrapper_alias: ABytesWrapperAlias\nb_bytes_wrapper_alias: BBytesWrapperAlias\nc_bytes_wrapper_alias: CBytesWrapperAlias\n\n# In Python 3, we assume that Literal['foo'] and Literal[u'foo'] are always\n# equivalent, no matter what.\nreveal_type(a_unicode_wrapper_alias)  # N: Revealed type is \"__main__.Wrap[Literal['foo']]\"\nreveal_type(b_unicode_wrapper_alias)  # N: Revealed type is \"__main__.Wrap[Literal['foo']]\"\nreveal_type(c_unicode_wrapper_alias)  # N: Revealed type is \"__main__.Wrap[Literal[b'foo']]\"\n\nreveal_type(a_str_wrapper_alias)      # N: Revealed type is \"__main__.Wrap[Literal['foo']]\"\nreveal_type(b_str_wrapper_alias)      # N: Revealed type is \"__main__.Wrap[Literal['foo']]\"\nreveal_type(c_str_wrapper_alias)      # N: Revealed type is \"__main__.Wrap[Literal[b'foo']]\"\n\nreveal_type(a_bytes_wrapper_alias)    # N: Revealed type is \"__main__.Wrap[Literal['foo']]\"\nreveal_type(b_bytes_wrapper_alias)    # N: Revealed type is \"__main__.Wrap[Literal['foo']]\"\nreveal_type(c_bytes_wrapper_alias)    # N: Revealed type is \"__main__.Wrap[Literal[b'foo']]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralUnicodeWeirdCharacters-skip_path_normalization]\nfrom typing import Any, Literal\n\na1: Literal[\"\\x00\\xAC\\x62 \\u2227 \\u03bb(p)\"]\nb1: Literal[\"\\x00¬b ∧ λ(p)\"]\nc1: Literal[\"¬b ∧ λ(p)\"]\nd1: Literal[\"\\U0001F600\"]\ne1: Literal[\"😀\"]\n\nAlias1 = Literal[\"\\x00\\xAC\\x62 \\u2227 \\u03bb(p)\"]\nAlias2 = Literal[\"\\x00¬b ∧ λ(p)\"]\nAlias3 = Literal[\"¬b ∧ λ(p)\"]\nAlias4 = Literal[\"\\U0001F600\"]\nAlias5 = Literal[\"😀\"]\na2: Alias1\nb2: Alias2\nc2: Alias3\nd2: Alias4\ne2: Alias5\n\nblah: Any\na3 = blah  # type: Literal[\"\\x00\\xAC\\x62 \\u2227 \\u03bb(p)\"]\nb3 = blah  # type: Literal[\"\\x00¬b ∧ λ(p)\"]\nc3 = blah  # type: Literal[\"¬b ∧ λ(p)\"]\nd3 = blah  # type: Literal[\"\\U0001F600\"]\ne3 = blah  # type: Literal[\"😀\"]\n\nreveal_type(a1)  # N: Revealed type is \"Literal['\\x00¬b ∧ λ(p)']\"\nreveal_type(b1)  # N: Revealed type is \"Literal['\\x00¬b ∧ λ(p)']\"\nreveal_type(c1)  # N: Revealed type is \"Literal['¬b ∧ λ(p)']\"\nreveal_type(d1)  # N: Revealed type is \"Literal['😀']\"\nreveal_type(e1)  # N: Revealed type is \"Literal['😀']\"\n\nreveal_type(a2)  # N: Revealed type is \"Literal['\\x00¬b ∧ λ(p)']\"\nreveal_type(b2)  # N: Revealed type is \"Literal['\\x00¬b ∧ λ(p)']\"\nreveal_type(c2)  # N: Revealed type is \"Literal['¬b ∧ λ(p)']\"\nreveal_type(d2)  # N: Revealed type is \"Literal['😀']\"\nreveal_type(e2)  # N: Revealed type is \"Literal['😀']\"\n\nreveal_type(a3)  # N: Revealed type is \"Literal['\\x00¬b ∧ λ(p)']\"\nreveal_type(b3)  # N: Revealed type is \"Literal['\\x00¬b ∧ λ(p)']\"\nreveal_type(c3)  # N: Revealed type is \"Literal['¬b ∧ λ(p)']\"\nreveal_type(d3)  # N: Revealed type is \"Literal['😀']\"\nreveal_type(e3)  # N: Revealed type is \"Literal['😀']\"\n\na1 = b1\na1 = c1  # E: Incompatible types in assignment (expression has type \"Literal['¬b ∧ λ(p)']\", variable has type \"Literal['\\x00¬b ∧ λ(p)']\")\na1 = a2\na1 = b2\na1 = c2  # E: Incompatible types in assignment (expression has type \"Literal['¬b ∧ λ(p)']\", variable has type \"Literal['\\x00¬b ∧ λ(p)']\")\na1 = a3\na1 = b3\na1 = c3  # E: Incompatible types in assignment (expression has type \"Literal['¬b ∧ λ(p)']\", variable has type \"Literal['\\x00¬b ∧ λ(p)']\")\n[builtins fixtures/tuple.pyi]\n\n[out]\n\n[case testLiteralRenamingImportWorks]\nfrom typing import Literal as Foo\n\nx: Foo[3]\nreveal_type(x)   # N: Revealed type is \"Literal[3]\"\n\ny: Foo[\"hello\"]\nreveal_type(y)   # N: Revealed type is \"Literal['hello']\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralRenamingImportViaAnotherImportWorks]\nfrom other_module import Foo, Bar\n\nx: Foo[3]\ny: Bar\n\nreveal_type(x)  # N: Revealed type is \"Literal[3]\"\nreveal_type(y)  # N: Revealed type is \"Literal[4]\"\n\n[file other_module.py]\nfrom typing import Literal as Foo\nBar = Foo[4]\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralRenamingImportNameConfusion]\nfrom typing import Literal as Foo\n\nx: Foo[\"Foo\"]\nreveal_type(x)  # N: Revealed type is \"Literal['Foo']\"\n\ny: Foo[Foo]     # E: Literal[...] must have at least one parameter\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralBadRawExpressionWithBadType]\n\nNotAType = 3\ndef f() -> NotAType['also' + 'not' + 'a' + 'type']: ... # E: Variable \"__main__.NotAType\" is not valid as a type \\\n                                                        # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases \\\n                                                        # E: Invalid type comment or annotation\n\n# Note: this makes us re-inspect the type (e.g. via '_patch_indirect_dependencies'\n# in build.py) so we can confirm the RawExpressionType did not leak out.\nindirect = f()\n[out]\n\n--\n-- Check to make sure we can construct the correct range of literal\n-- types (and correctly reject invalid literal types)\n--\n-- Note: the assignment tests exercise the logic in 'fastparse.py';\n-- the type alias tests exercise the logic in 'exprtotype.py'.\n--\n\n[case testLiteralBasicIntUsage]\nfrom typing import Literal\n\na1: Literal[4]\nb1: Literal[0x2a]\nc1: Literal[-300]\nd1: Literal[+8]\n\nreveal_type(a1)  # N: Revealed type is \"Literal[4]\"\nreveal_type(b1)  # N: Revealed type is \"Literal[42]\"\nreveal_type(c1)  # N: Revealed type is \"Literal[-300]\"\nreveal_type(d1)  # N: Revealed type is \"Literal[8]\"\n\na2t = Literal[4]\nb2t = Literal[0x2a]\nc2t = Literal[-300]\nd2t = Literal[+8]\na2: a2t\nb2: b2t\nc2: c2t\nd2: d2t\n\nreveal_type(a2)  # N: Revealed type is \"Literal[4]\"\nreveal_type(b2)  # N: Revealed type is \"Literal[42]\"\nreveal_type(c2)  # N: Revealed type is \"Literal[-300]\"\nreveal_type(d2)  # N: Revealed type is \"Literal[8]\"\n\ndef f1(x: Literal[4]) -> Literal[4]: pass\ndef f2(x: Literal[0x2a]) -> Literal[0x2a]: pass\ndef f3(x: Literal[-300]) -> Literal[-300]: pass\ndef f4(x: Literal[+8]) -> Literal[+8]: pass\n\nreveal_type(f1)  # N: Revealed type is \"def (x: Literal[4]) -> Literal[4]\"\nreveal_type(f2)  # N: Revealed type is \"def (x: Literal[42]) -> Literal[42]\"\nreveal_type(f3)  # N: Revealed type is \"def (x: Literal[-300]) -> Literal[-300]\"\nreveal_type(f4)  # N: Revealed type is \"def (x: Literal[8]) -> Literal[8]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralBasicBoolUsage]\nfrom typing import Literal\n\na1: Literal[True]\nb1: Literal[False]\n\nreveal_type(a1)  # N: Revealed type is \"Literal[True]\"\nreveal_type(b1)  # N: Revealed type is \"Literal[False]\"\n\na2t = Literal[True]\nb2t = Literal[False]\na2: a2t\nb2: b2t\n\nreveal_type(a2)  # N: Revealed type is \"Literal[True]\"\nreveal_type(b2)  # N: Revealed type is \"Literal[False]\"\n\ndef f1(x: Literal[True]) -> Literal[True]: pass\ndef f2(x: Literal[False]) -> Literal[False]: pass\n\nreveal_type(f1)  # N: Revealed type is \"def (x: Literal[True]) -> Literal[True]\"\nreveal_type(f2)  # N: Revealed type is \"def (x: Literal[False]) -> Literal[False]\"\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testLiteralBasicStrUsage]\nfrom typing import Literal\n\na: Literal[\"\"]\nb: Literal[\"  foo bar  \"]\nc: Literal['  foo bar  ']\nd: Literal[\"foo\"]\ne: Literal['foo']\n\nreveal_type(a)  # N: Revealed type is \"Literal['']\"\nreveal_type(b)  # N: Revealed type is \"Literal['  foo bar  ']\"\nreveal_type(c)  # N: Revealed type is \"Literal['  foo bar  ']\"\nreveal_type(d)  # N: Revealed type is \"Literal['foo']\"\nreveal_type(e)  # N: Revealed type is \"Literal['foo']\"\n\ndef f1(x: Literal[\"\"]) -> Literal[\"\"]: pass\ndef f2(x: Literal[\"  foo bar  \"]) -> Literal[\"  foo bar  \"]: pass\ndef f3(x: Literal['  foo bar  ']) -> Literal['  foo bar  ']: pass\ndef f4(x: Literal[\"foo\"]) -> Literal[\"foo\"]: pass\ndef f5(x: Literal['foo']) -> Literal['foo']: pass\n\nreveal_type(f1)  # N: Revealed type is \"def (x: Literal['']) -> Literal['']\"\nreveal_type(f2)  # N: Revealed type is \"def (x: Literal['  foo bar  ']) -> Literal['  foo bar  ']\"\nreveal_type(f3)  # N: Revealed type is \"def (x: Literal['  foo bar  ']) -> Literal['  foo bar  ']\"\nreveal_type(f4)  # N: Revealed type is \"def (x: Literal['foo']) -> Literal['foo']\"\nreveal_type(f5)  # N: Revealed type is \"def (x: Literal['foo']) -> Literal['foo']\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralBasicStrUsageSlashes-skip_path_normalization]\nfrom typing import Literal\n\na: Literal[r\"foo\\nbar\"]\nb: Literal[\"foo\\nbar\"]\n\nreveal_type(a)\nreveal_type(b)\n[builtins fixtures/tuple.pyi]\n[out]\nmain:6: note: Revealed type is \"Literal['foo\\\\nbar']\"\nmain:7: note: Revealed type is \"Literal['foo\\nbar']\"\n\n[case testLiteralBasicNoneUsage]\n# Note: Literal[None] and None are equivalent\nfrom typing import Literal\na: Literal[None]\nreveal_type(a)   # N: Revealed type is \"None\"\n\ndef f1(x: Literal[None]) -> None: pass\ndef f2(x: None) -> Literal[None]: pass\ndef f3(x: Literal[None]) -> Literal[None]: pass\n\nreveal_type(f1)  # N: Revealed type is \"def (x: None)\"\nreveal_type(f2)  # N: Revealed type is \"def (x: None)\"\nreveal_type(f3)  # N: Revealed type is \"def (x: None)\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralCallingUnionFunction]\nfrom typing import Literal\n\ndef func(x: Literal['foo', 'bar', '  foo  ']) -> None: ...\n\nfunc('foo')\nfunc('bar')\nfunc('  foo  ')\nfunc('baz')       # E: Argument 1 to \"func\" has incompatible type \"Literal['baz']\"; expected \"Literal['foo', 'bar', '  foo  ']\"\n\na: Literal['foo']\nb: Literal['bar']\nc: Literal['  foo  ']\nd: Literal['foo', 'bar']\ne: Literal['foo', 'bar', '  foo  ']\nf: Literal['foo', 'bar', 'baz']\n\nfunc(a)\nfunc(b)\nfunc(c)\nfunc(d)\nfunc(e)\nfunc(f)  # E: Argument 1 to \"func\" has incompatible type \"Literal['foo', 'bar', 'baz']\"; expected \"Literal['foo', 'bar', '  foo  ']\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralDisallowAny]\nfrom typing import Any, Literal\nfrom missing_module import BadAlias     # E: Cannot find implementation or library stub for module named \"missing_module\" \\\n                                        # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\na: Literal[Any]                         # E: Parameter 1 of Literal[...] cannot be of type \"Any\"\nb: Literal[BadAlias]                    # E: Parameter 1 of Literal[...] cannot be of type \"Any\"\n\nreveal_type(a)                          # N: Revealed type is \"Any\"\nreveal_type(b)                          # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralDisallowActualTypes]\nfrom typing import Literal\n\na: Literal[int]     # E: Parameter 1 of Literal[...] is invalid\nb: Literal[float]   # E: Parameter 1 of Literal[...] is invalid\nc: Literal[bool]    # E: Parameter 1 of Literal[...] is invalid\nd: Literal[str]     # E: Parameter 1 of Literal[...] is invalid\n\nreveal_type(a)      # N: Revealed type is \"Any\"\nreveal_type(b)      # N: Revealed type is \"Any\"\nreveal_type(c)      # N: Revealed type is \"Any\"\nreveal_type(d)      # N: Revealed type is \"Any\"\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testLiteralDisallowFloatsAndComplex_no_native_parse]\n\nfrom typing import Literal\na1: Literal[3.14]    # E: Parameter 1 of Literal[...] cannot be of type \"float\"\nb1: 3.14             # E: Invalid type: float literals cannot be used as a type\nc1: Literal[3j]      # E: Parameter 1 of Literal[...] cannot be of type \"complex\"\nd1: 3j               # E: Invalid type: complex literals cannot be used as a type\n\na2t = Literal[3.14]  # E: Parameter 1 of Literal[...] cannot be of type \"float\"\nb2t = 3.14\nc2t = Literal[3j]    # E: Parameter 1 of Literal[...] cannot be of type \"complex\"\nd2t = 3j\n\na2: a2t\nreveal_type(a2)      # N: Revealed type is \"Any\"\nb2: b2t              # E: Variable \"__main__.b2t\" is not valid as a type \\\n                     # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\nc2: c2t\nreveal_type(c2)      # N: Revealed type is \"Any\"\nd2: d2t              # E: Variable \"__main__.d2t\" is not valid as a type \\\n                     # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n[builtins fixtures/complex_tuple.pyi]\n[out]\n\n[case testLiteralDisallowComplexExpressions_no_native_parse]\nfrom typing import Literal\ndef dummy() -> int: return 3\na: Literal[3 + 4]               # E: Invalid type: Literal[...] cannot contain arbitrary expressions\nb: Literal[\"  foo  \".trim()]    # E: Invalid type: Literal[...] cannot contain arbitrary expressions\nd: Literal[~12]                 # E: Invalid type: Literal[...] cannot contain arbitrary expressions\ne: Literal[dummy()]             # E: Invalid type: Literal[...] cannot contain arbitrary expressions\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralDisallowCollections]\nfrom typing import Literal\na: Literal[{\"a\": 1, \"b\": 2}]    # E: Parameter 1 of Literal[...] is invalid\nb: Literal[{1, 2, 3}]           # E: Invalid type: Literal[...] cannot contain arbitrary expressions\nc: {\"a\": 1, \"b\": 2}             # E: Inline TypedDict is experimental, must be enabled with --enable-incomplete-feature=InlineTypedDict \\\n                                # E: Invalid type: try using Literal[1] instead? \\\n                                # E: Invalid type: try using Literal[2] instead?\nd: {1, 2, 3}                    # E: Invalid type comment or annotation\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testLiteralDisallowCollections2]\nfrom typing import Literal\na: (1, 2, 3)                    # E: Syntax error in type annotation \\\n                                # N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)\nb: Literal[[1, 2, 3]]           # E: Parameter 1 of Literal[...] is invalid\nc: [1, 2, 3]                    # E: Bracketed expression \"[...]\" is not valid as a type\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralDisallowCollectionsTypeAlias]\nfrom typing import Literal\nat = Literal[{\"a\": 1, \"b\": 2}]  # E: Parameter 1 of Literal[...] is invalid\nbt = {\"a\": 1, \"b\": 2}\na: at\nreveal_type(a)                  # N: Revealed type is \"Any\"\nb: bt                           # E: Variable \"__main__.bt\" is not valid as a type \\\n                                # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testLiteralDisallowCollectionsTypeAlias2]\nfrom typing import Literal\nat = Literal[{1, 2, 3}]         # E: Invalid type alias: expression is not a valid type\nbt = {1, 2, 3}\na: at                           # E: Variable \"__main__.at\" is not valid as a type \\\n                                # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\nb: bt                           # E: Variable \"__main__.bt\" is not valid as a type \\\n                                # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n[builtins fixtures/set.pyi]\n[typing fixtures/typing-full.pyi]\n[out]\n\n[case testLiteralDisallowTypeVar]\nfrom typing import Literal, TypeVar, Tuple\n\nT = TypeVar('T')\n\nat = Literal[T]  # E: Parameter 1 of Literal[...] is invalid\na: at\n\ndef foo(b: Literal[T]) -> Tuple[T]: pass   # E: Parameter 1 of Literal[...] is invalid\n[builtins fixtures/tuple.pyi]\n[out]\n\n\n--\n-- Test mixing and matching literals with other types\n--\n\n[case testLiteralMultipleValues]\nfrom typing import Literal\na: Literal[1, 2, 3]\nb: Literal[\"a\", \"b\", \"c\"]\nc: Literal[1, \"b\", True, None]\nd: Literal[1, 1, 1]\ne: Literal[None, None, None]\nreveal_type(a)   # N: Revealed type is \"Literal[1] | Literal[2] | Literal[3]\"\nreveal_type(b)   # N: Revealed type is \"Literal['a'] | Literal['b'] | Literal['c']\"\nreveal_type(c)   # N: Revealed type is \"Literal[1] | Literal['b'] | Literal[True] | None\"\n\n# Note: I was thinking these should be simplified, but it seems like\n# mypy doesn't simplify unions with duplicate values with other types.\nreveal_type(d)   # N: Revealed type is \"Literal[1] | Literal[1] | Literal[1]\"\nreveal_type(e)   # N: Revealed type is \"None | None | None\"\n[builtins fixtures/bool.pyi]\n[out]\n\n[case testLiteralMultipleValuesExplicitTuple]\nfrom typing import Literal\n# Unfortunately, it seems like typed_ast is unable to distinguish this from\n# Literal[1, 2, 3]. So we treat the two as being equivalent for now.\na: Literal[1, 2, 3]\nb: Literal[(1, 2, 3)]\nreveal_type(a)  # N: Revealed type is \"Literal[1] | Literal[2] | Literal[3]\"\nreveal_type(b)  # N: Revealed type is \"Literal[1] | Literal[2] | Literal[3]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralNestedUsage]\n\nfrom typing import Literal\na: Literal[Literal[3], 4, Literal[\"foo\"]]\nreveal_type(a)  # N: Revealed type is \"Literal[3] | Literal[4] | Literal['foo']\"\n\nalias_for_literal = Literal[5]\nb: Literal[alias_for_literal]\nreveal_type(b)  # N: Revealed type is \"Literal[5]\"\n\nanother_alias = Literal[1, None]\nc: Literal[alias_for_literal, another_alias, \"r\"]\nreveal_type(c)  # N: Revealed type is \"Literal[5] | Literal[1] | None | Literal['r']\"\n\nbasic_mode = Literal[\"r\", \"w\", \"a\"]\nbasic_with_plus = Literal[\"r+\", \"w+\", \"a+\"]\ncombined: Literal[basic_mode, basic_with_plus]\nreveal_type(combined)  # N: Revealed type is \"Literal['r'] | Literal['w'] | Literal['a'] | Literal['r+'] | Literal['w+'] | Literal['a+']\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralBiasTowardsAssumingForwardReference]\nfrom typing import Literal\n\na: \"Foo\"\nreveal_type(a)      # N: Revealed type is \"__main__.Foo\"\n\nb: Literal[\"Foo\"]\nreveal_type(b)      # N: Revealed type is \"Literal['Foo']\"\n\nc: \"Literal[Foo]\"   # E: Parameter 1 of Literal[...] is invalid\n\nd: \"Literal['Foo']\"\nreveal_type(d)      # N: Revealed type is \"Literal['Foo']\"\n\nclass Foo: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralBiasTowardsAssumingForwardReferenceForTypeAliases]\nfrom typing import Literal\n\na: \"Foo\"\nreveal_type(a)      # N: Revealed type is \"Literal[5]\"\n\nb: Literal[\"Foo\"]\nreveal_type(b)      # N: Revealed type is \"Literal['Foo']\"\n\nc: \"Literal[Foo]\"\nreveal_type(c)      # N: Revealed type is \"Literal[5]\"\n\nd: \"Literal['Foo']\"\nreveal_type(d)      # N: Revealed type is \"Literal['Foo']\"\n\ne: Literal[Foo, 'Foo']\nreveal_type(e)      # N: Revealed type is \"Literal[5] | Literal['Foo']\"\n\nFoo = Literal[5]\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralBiasTowardsAssumingForwardReferencesForTypeComments]\nfrom typing import Literal\n\na: Foo\nreveal_type(a)      # N: Revealed type is \"__main__.Foo\"\n\nb: \"Foo\"\nreveal_type(b)      # N: Revealed type is \"__main__.Foo\"\n\nc: Literal[\"Foo\"]\nreveal_type(c)      # N: Revealed type is \"Literal['Foo']\"\n\nd: Literal[Foo]     # E: Parameter 1 of Literal[...] is invalid\n\nclass Foo: pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n\n--\n-- Check how we handle very basic subtyping and other useful things\n--\n\n[case testLiteralCallingFunction]\nfrom typing import Literal\ndef foo(x: Literal[3]) -> None: pass\n\na: Literal[1]\nb: Literal[2]\nc: int\n\nfoo(a)  # E: Argument 1 to \"foo\" has incompatible type \"Literal[1]\"; expected \"Literal[3]\"\nfoo(b)  # E: Argument 1 to \"foo\" has incompatible type \"Literal[2]\"; expected \"Literal[3]\"\nfoo(c)  # E: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"Literal[3]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralCallingFunctionWithUnionLiteral]\nfrom typing import Literal\ndef foo(x: Literal[1, 2, 3]) -> None: pass\n\na: Literal[1]\nb: Literal[2, 3]\nc: Literal[4, 5]\nd: int\n\nfoo(a)\nfoo(b)\nfoo(c)  # E: Argument 1 to \"foo\" has incompatible type \"Literal[4, 5]\"; expected \"Literal[1, 2, 3]\"\nfoo(d)  # E: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"Literal[1, 2, 3]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralCallingFunctionWithStandardBase]\nfrom typing import Literal\ndef foo(x: int) -> None: pass\n\na: Literal[1]\nb: Literal[1, -4]\nc: Literal[4, 'foo']\n\nfoo(a)\nfoo(b)\nfoo(c)  # E: Argument 1 to \"foo\" has incompatible type \"Literal[4, 'foo']\"; expected \"int\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralCheckSubtypingStrictOptional]\nfrom typing import Any, Literal, NoReturn\n\nlit: Literal[1]\ndef f_lit(x: Literal[1]) -> None: pass\n\ndef fa(x: Any) -> None: pass\ndef fb(x: NoReturn) -> None: pass\ndef fc(x: None) -> None: pass\n\na: Any\nb: NoReturn\nc: None\n\nfa(lit)\nfb(lit)  # E: Argument 1 to \"fb\" has incompatible type \"Literal[1]\"; expected \"Never\"\nfc(lit)  # E: Argument 1 to \"fc\" has incompatible type \"Literal[1]\"; expected \"None\"\n\nf_lit(a)\nf_lit(b)\nf_lit(c) # E: Argument 1 to \"f_lit\" has incompatible type \"None\"; expected \"Literal[1]\"\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralCheckSubtypingNoStrictOptional]\n# flags: --no-strict-optional\nfrom typing import Any, Literal, NoReturn\n\nlit: Literal[1]\ndef f_lit(x: Literal[1]) -> None: pass\n\ndef fa(x: Any) -> None: pass\ndef fb(x: NoReturn) -> None: pass\ndef fc(x: None) -> None: pass\n\na: Any\nb: NoReturn\nc: None\n\nfa(lit)\nfb(lit)  # E: Argument 1 to \"fb\" has incompatible type \"Literal[1]\"; expected \"Never\"\nfc(lit)  # E: Argument 1 to \"fc\" has incompatible type \"Literal[1]\"; expected \"None\"\n\nf_lit(a)\nf_lit(b)\nf_lit(c)\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralCallingOverloadedFunction]\nfrom typing import overload, Generic, Literal, TypeVar, Any\n\nT = TypeVar('T')\nclass IOLike(Generic[T]): pass\n\n@overload\ndef foo(x: Literal[1]) -> IOLike[int]: ...\n@overload\ndef foo(x: Literal[2]) -> IOLike[str]: ...\n@overload\ndef foo(x: int) -> IOLike[Any]: ...\ndef foo(x: int) -> IOLike[Any]:\n    if x == 1:\n        return IOLike[int]()\n    elif x == 2:\n        return IOLike[str]()\n    else:\n        return IOLike()\n\na: Literal[1]\nb: Literal[2]\nc: int\nd: Literal[3]\n\nreveal_type(foo(a))  # N: Revealed type is \"__main__.IOLike[builtins.int]\"\nreveal_type(foo(b))  # N: Revealed type is \"__main__.IOLike[builtins.str]\"\nreveal_type(foo(c))  # N: Revealed type is \"__main__.IOLike[Any]\"\nfoo(d)\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testLiteralVariance]\nfrom typing import Generic, Literal, TypeVar\n\nT = TypeVar('T')\nT_co = TypeVar('T_co', covariant=True)\nT_contra = TypeVar('T_contra', contravariant=True)\n\nclass Invariant(Generic[T]): pass\nclass Covariant(Generic[T_co]): pass\nclass Contravariant(Generic[T_contra]): pass\n\na1: Invariant[Literal[1]]\na2: Invariant[Literal[1, 2]]\na3: Invariant[Literal[1, 2, 3]]\na2 = a1  # E: Incompatible types in assignment (expression has type \"Invariant[Literal[1]]\", variable has type \"Invariant[Literal[1, 2]]\")\na2 = a3  # E: Incompatible types in assignment (expression has type \"Invariant[Literal[1, 2, 3]]\", variable has type \"Invariant[Literal[1, 2]]\")\n\nb1: Covariant[Literal[1]]\nb2: Covariant[Literal[1, 2]]\nb3: Covariant[Literal[1, 2, 3]]\nb2 = b1\nb2 = b3  # E: Incompatible types in assignment (expression has type \"Covariant[Literal[1, 2, 3]]\", variable has type \"Covariant[Literal[1, 2]]\")\n\nc1: Contravariant[Literal[1]]\nc2: Contravariant[Literal[1, 2]]\nc3: Contravariant[Literal[1, 2, 3]]\nc2 = c1  # E: Incompatible types in assignment (expression has type \"Contravariant[Literal[1]]\", variable has type \"Contravariant[Literal[1, 2]]\")\nc2 = c3\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralInListAndSequence]\nfrom typing import List, Literal, Sequence\n\ndef foo(x: List[Literal[1, 2]]) -> None: pass\ndef bar(x: Sequence[Literal[1, 2]]) -> None: pass\n\na: List[Literal[1]]\nb: List[Literal[1, 2, 3]]\n\nfoo(a)  # E: Argument 1 to \"foo\" has incompatible type \"list[Literal[1]]\"; expected \"list[Literal[1, 2]]\" \\\n        # N: \"list\" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance \\\n        # N: Consider using \"Sequence\" instead, which is covariant\nfoo(b)  # E: Argument 1 to \"foo\" has incompatible type \"list[Literal[1, 2, 3]]\"; expected \"list[Literal[1, 2]]\"\nbar(a)\nbar(b)  # E: Argument 1 to \"bar\" has incompatible type \"list[Literal[1, 2, 3]]\"; expected \"Sequence[Literal[1, 2]]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testLiteralRenamingDoesNotChangeTypeChecking]\nfrom typing import Literal as Foo\nfrom other_module import Bar1, Bar2, c\n\ndef func(x: Foo[15]) -> None: pass\n\na: Bar1\nb: Bar2\nfunc(a)\nfunc(b)  # E: Argument 1 to \"func\" has incompatible type \"Literal[14]\"; expected \"Literal[15]\"\nfunc(c)\n\n[file other_module.py]\nfrom typing import Literal\n\nBar1 = Literal[15]\nBar2 = Literal[14]\nc: Literal[15]\n[builtins fixtures/tuple.pyi]\n\n\n--\n-- Check to make sure we handle inference of literal values correctly,\n-- especially when doing assignments or calls\n--\n\n[case testLiteralInferredInAssignment]\nfrom typing import Literal\n\nint1: Literal[1] = 1\nint2 = 1\nint3: int = 1\n\nstr1: Literal[\"foo\"] = \"foo\"\nstr2 = \"foo\"\nstr3: str = \"foo\"\n\nbool1: Literal[True] = True\nbool2 = True\nbool3: bool = True\n\nnone1: Literal[None] = None\nnone2 = None\nnone3: None = None\n\nreveal_type(int1)   # N: Revealed type is \"Literal[1]\"\nreveal_type(int2)   # N: Revealed type is \"builtins.int\"\nreveal_type(int3)   # N: Revealed type is \"builtins.int\"\nreveal_type(str1)   # N: Revealed type is \"Literal['foo']\"\nreveal_type(str2)   # N: Revealed type is \"builtins.str\"\nreveal_type(str3)   # N: Revealed type is \"builtins.str\"\nreveal_type(bool1)  # N: Revealed type is \"Literal[True]\"\nreveal_type(bool2)  # N: Revealed type is \"builtins.bool\"\nreveal_type(bool3)  # N: Revealed type is \"builtins.bool\"\nreveal_type(none1)  # N: Revealed type is \"None\"\nreveal_type(none2)  # N: Revealed type is \"None\"\nreveal_type(none3)  # N: Revealed type is \"None\"\n[builtins fixtures/primitives.pyi]\n\n[case testLiteralInferredOnlyForActualLiterals]\nfrom typing import Literal\n\nw: Literal[1]\nx: Literal[\"foo\"]\ny: Literal[True]\nz: Literal[None]\ncombined: Literal[1, \"foo\", True, None]\n\na = 1\nb = \"foo\"\nc = True\nd = None\n\nw = a  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Literal[1]\")\nx = b  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"Literal['foo']\")\ny = c  # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"Literal[True]\")\nz = d  # This is ok: Literal[None] and None are equivalent.\n\ncombined = a  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Literal[1, 'foo', True] | None\")\ncombined = b  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"Literal[1, 'foo', True] | None\")\ncombined = c  # E: Incompatible types in assignment (expression has type \"bool\", variable has type \"Literal[1, 'foo', True] | None\")\ncombined = d  # Also ok, for similar reasons.\n\ne: Literal[1] = 1\nf: Literal[\"foo\"] = \"foo\"\ng: Literal[True] = True\nh: Literal[None] = None\n\nw = e\nx = f\ny = g\nz = h\ncombined = e\ncombined = f\ncombined = g\ncombined = h\n\n[builtins fixtures/primitives.pyi]\n\n[case testLiteralInferredTypeMustMatchExpected]\nfrom typing import Literal\n\na: Literal[1] = 2           # E: Incompatible types in assignment (expression has type \"Literal[2]\", variable has type \"Literal[1]\")\nb: Literal[\"foo\"] = \"bar\"   # E: Incompatible types in assignment (expression has type \"Literal['bar']\", variable has type \"Literal['foo']\")\nc: Literal[True] = False    # E: Incompatible types in assignment (expression has type \"Literal[False]\", variable has type \"Literal[True]\")\n\nd: Literal[1, 2] = 3                # E: Incompatible types in assignment (expression has type \"Literal[3]\", variable has type \"Literal[1, 2]\")\ne: Literal[\"foo\", \"bar\"] = \"baz\"    # E: Incompatible types in assignment (expression has type \"Literal['baz']\", variable has type \"Literal['foo', 'bar']\")\nf: Literal[True, 4] = False         # E: Incompatible types in assignment (expression has type \"Literal[False]\", variable has type \"Literal[True, 4]\")\n\n[builtins fixtures/primitives.pyi]\n\n[case testLiteralInferredInCall]\nfrom typing import Literal\n\ndef f_int_lit(x: Literal[1]) -> None: pass\ndef f_int(x: int) -> None: pass\n\ndef f_str_lit(x: Literal[\"foo\"]) -> None: pass\ndef f_str(x: str) -> None: pass\n\ndef f_bool_lit(x: Literal[True]) -> None: pass\ndef f_bool(x: bool) -> None: pass\n\ndef f_none_lit(x: Literal[None]) -> None: pass\ndef f_none(x: None) -> None: pass\n\ni1: Literal[1]\ni2: Literal[2]\nf_int_lit(1)\nf_int_lit(2)  # E: Argument 1 to \"f_int_lit\" has incompatible type \"Literal[2]\"; expected \"Literal[1]\"\nf_int(1)\nf_int_lit(i1)\nf_int_lit(i2) # E: Argument 1 to \"f_int_lit\" has incompatible type \"Literal[2]\"; expected \"Literal[1]\"\n\ns1: Literal[\"foo\"]\ns2: Literal[\"bar\"]\nf_str_lit(\"foo\")\nf_str_lit(\"bar\")  # E: Argument 1 to \"f_str_lit\" has incompatible type \"Literal['bar']\"; expected \"Literal['foo']\"\nf_str(\"baz\")\nf_str_lit(s1)\nf_str_lit(s2)     # E: Argument 1 to \"f_str_lit\" has incompatible type \"Literal['bar']\"; expected \"Literal['foo']\"\n\nb1: Literal[True]\nb2: Literal[False]\nf_bool_lit(True)\nf_bool_lit(False)  # E: Argument 1 to \"f_bool_lit\" has incompatible type \"Literal[False]\"; expected \"Literal[True]\"\nf_bool(True)\nf_bool_lit(b1)\nf_bool_lit(b2)     # E: Argument 1 to \"f_bool_lit\" has incompatible type \"Literal[False]\"; expected \"Literal[True]\"\n\nn1: Literal[None]\nf_none_lit(None)\nf_none(None)\nf_none_lit(n1)\n[builtins fixtures/primitives.pyi]\n\n[case testLiteralInferredInReturnContext]\nfrom typing import Literal\n\ndef f1() -> int:\n    return 1\n\ndef f2() -> Literal[1]:\n    return 1\n\ndef f3() -> Literal[1]:\n    return 2  # E: Incompatible return value type (got \"Literal[2]\", expected \"Literal[1]\")\n\ndef f4(x: Literal[1]) -> Literal[1]:\n    return x\n\ndef f5(x: Literal[2]) -> Literal[1]:\n    return x  # E: Incompatible return value type (got \"Literal[2]\", expected \"Literal[1]\")\n[builtins fixtures/tuple.pyi]\n\n[out]\n\n[case testLiteralInferredInListContext]\nfrom typing import List, Literal\n\na: List[Literal[1]] = [1, 1, 1]\nb = [1, 1, 1]\nc: List[Literal[1, 2, 3]] = [1, 2, 3]\nd = [1, 2, 3]\ne: List[Literal[1, \"x\"]] = [1, \"x\"]\nf = [1, \"x\"]\ng: List[List[List[Literal[1, 2, 3]]]] = [[[1, 2, 3], [3]]]\nh: List[Literal[1]] = []\n\nreveal_type(a)  # N: Revealed type is \"builtins.list[Literal[1]]\"\nreveal_type(b)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(c)  # N: Revealed type is \"builtins.list[Literal[1] | Literal[2] | Literal[3]]\"\nreveal_type(d)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(e)  # N: Revealed type is \"builtins.list[Literal[1] | Literal['x']]\"\nreveal_type(f)  # N: Revealed type is \"builtins.list[builtins.object]\"\nreveal_type(g)  # N: Revealed type is \"builtins.list[builtins.list[builtins.list[Literal[1] | Literal[2] | Literal[3]]]]\"\nreveal_type(h)  # N: Revealed type is \"builtins.list[Literal[1]]\"\n\nlit1: Literal[1]\nlit2: Literal[2]\nlit3: Literal[\"foo\"]\n\narr1 = [lit1, lit1, lit1]\narr2 = [lit1, lit2]\narr3 = [lit1, 4, 5]\narr4 = [lit1, lit2, lit3]\narr5 = [object(), lit1]\n\nreveal_type(arr1)  # N: Revealed type is \"builtins.list[Literal[1]]\"\nreveal_type(arr2)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(arr3)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(arr4)  # N: Revealed type is \"builtins.list[builtins.object]\"\nreveal_type(arr5)  # N: Revealed type is \"builtins.list[builtins.object]\"\n\nbad: List[Literal[1, 2]] = [1, 2, 3]  # E: List item 2 has incompatible type \"Literal[3]\"; expected \"Literal[1, 2]\"\n\n[builtins fixtures/list.pyi]\n[out]\n\n[case testLiteralInferredInTupleContext]\n# Note: most of the 'are we handling context correctly' tests should have been\n# handled up above, so we keep things comparatively simple for tuples and dicts.\nfrom typing import Literal, Tuple\n\na: Tuple[Literal[1], Literal[2]] = (1, 2)\nb: Tuple[int, Literal[1, 2], Literal[3], Tuple[Literal[\"foo\"]]] = (1, 2, 3, (\"foo\",))\nc: Tuple[Literal[1], Literal[2]] = (2, 1)  # E: Incompatible types in assignment (expression has type \"tuple[Literal[2], Literal[1]]\", variable has type \"tuple[Literal[1], Literal[2]]\")\nd = (1, 2)\n\nreveal_type(d)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralInferredInDictContext]\nfrom typing import Dict, Literal\n\na = {\"x\": 1, \"y\": 2}\nb: Dict[str, Literal[1, 2]] = {\"x\": 1, \"y\": 2}\nc: Dict[Literal[\"x\", \"y\"], int] = {\"x\": 1, \"y\": 2}\n\nreveal_type(a)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testLiteralInferredInOverloadContextBasic]\nfrom typing import Literal, overload\n\n@overload\ndef func(x: Literal[1]) -> str: ...\n@overload\ndef func(x: Literal[2]) -> int: ...\n@overload\ndef func(x: int) -> object: ...\ndef func(x: int) -> object: pass\n\na: Literal[1]\nb: Literal[2]\nc: Literal[1, 2]\n\nreveal_type(func(1))  # N: Revealed type is \"builtins.str\"\nreveal_type(func(2))  # N: Revealed type is \"builtins.int\"\nreveal_type(func(3))  # N: Revealed type is \"builtins.object\"\nreveal_type(func(a))  # N: Revealed type is \"builtins.str\"\nreveal_type(func(b))  # N: Revealed type is \"builtins.int\"\n\n# Note: the fact that we don't do union math here is consistent\n# with the output we would have gotten if we replaced int and the\n# Literal types here with regular classes/subclasses.\nreveal_type(func(c))  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralOverloadProhibitUnsafeOverlaps]\nfrom typing import Literal, overload\n\n@overload\ndef func1(x: Literal[1]) -> str: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef func1(x: int) -> int: ...\ndef func1(x): pass\n\n@overload\ndef func2(x: Literal['a']) -> int: ...  # E: Overloaded function signatures 1 and 2 overlap with incompatible return types\n@overload\ndef func2(x: str) -> Literal[2]: ...\ndef func2(x): pass\n\n# This one is typesafe\n@overload\ndef func3(x: Literal['a']) -> Literal[2]: ...\n@overload\ndef func3(x: str) -> int: ...\ndef func3(x): pass\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralInferredInOverloadContextUnionMath]\nfrom typing import overload, Literal, Union\n\nclass A: pass\nclass B: pass\nclass C: pass\n\n@overload\ndef func(x: Literal[-40]) -> A: ...\n@overload\ndef func(x: Literal[3, 4, 5, 6]) -> B: ...\n@overload\ndef func(x: Literal[\"foo\"]) -> C: ...\ndef func(x: Union[int, str]) -> Union[A, B, C]: pass\n\na: Literal[-40, \"foo\"]\nb: Literal[3]\nc: Literal[3, -40]\nd: Literal[6, 7]\ne: int\nf: Literal[7, \"bar\"]\n\nreveal_type(func(a))  # N: Revealed type is \"__main__.A | __main__.C\"\nreveal_type(func(b))  # N: Revealed type is \"__main__.B\"\nreveal_type(func(c))  # N: Revealed type is \"__main__.B | __main__.A\"\nreveal_type(func(d))  # N: Revealed type is \"__main__.B\" \\\n                      # E: Argument 1 to \"func\" has incompatible type \"Literal[6, 7]\"; expected \"Literal[3, 4, 5, 6]\"\n\nreveal_type(func(e))  # E: No overload variant of \"func\" matches argument type \"int\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def func(x: Literal[-40]) -> A \\\n                      # N:     def func(x: Literal[3, 4, 5, 6]) -> B \\\n                      # N:     def func(x: Literal['foo']) -> C \\\n                      # N: Revealed type is \"Any\"\n\nreveal_type(func(f))  # E: No overload variant of \"func\" matches argument type \"Literal[7, 'bar']\" \\\n                      # N: Possible overload variants: \\\n                      # N:     def func(x: Literal[-40]) -> A \\\n                      # N:     def func(x: Literal[3, 4, 5, 6]) -> B \\\n                      # N:     def func(x: Literal['foo']) -> C \\\n                      # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralInferredInOverloadContextUnionMathOverloadingReturnsBestType]\n# This test is a transliteration of check-overloading::testUnionMathOverloadingReturnsBestType\nfrom typing import Literal, overload\n\n@overload\ndef f(x: Literal[1, 2]) -> int: ...\n@overload\ndef f(x: int) -> object: ...\ndef f(x):\n    pass\n\nx: Literal[1, 2]\ny: Literal[1, 2, 3]\nz: Literal[1, 2, \"three\"]\nreveal_type(f(x))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(1))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(2))  # N: Revealed type is \"builtins.int\"\nreveal_type(f(y))  # N: Revealed type is \"builtins.object\"\nreveal_type(f(z))  # N: Revealed type is \"builtins.int\" \\\n                   # E: Argument 1 to \"f\" has incompatible type \"Literal[1, 2, 'three']\"; expected \"Literal[1, 2]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralInferredInOverloadContextWithTypevars]\nfrom typing import Literal, TypeVar, overload, Union\n\nT = TypeVar('T')\n\n@overload\ndef f1(x: T, y: int) -> T: ...\n@overload\ndef f1(x: T, y: str) -> Union[T, str]: ...\ndef f1(x, y): pass\n\na: Literal[1]\nreveal_type(f1(1, 1))  # N: Revealed type is \"builtins.int\"\nreveal_type(f1(a, 1))  # N: Revealed type is \"Literal[1]\"\n\n@overload\ndef f2(x: T, y: Literal[3]) -> T: ...\n@overload\ndef f2(x: T, y: str) -> Union[T]: ...\ndef f2(x, y): pass\n\nreveal_type(f2(1, 3))  # N: Revealed type is \"builtins.int\"\nreveal_type(f2(a, 3))  # N: Revealed type is \"Literal[1]\"\n\n@overload\ndef f3(x: Literal[3]) -> Literal[3]: ...\n@overload\ndef f3(x: T) -> T: ...\ndef f3(x): pass\n\nreveal_type(f3(1))  # N: Revealed type is \"builtins.int\"\nreveal_type(f3(a))  # N: Revealed type is \"Literal[1]\"\n\n@overload\ndef f4(x: str) -> str: ...\n@overload\ndef f4(x: T) -> T: ...\ndef f4(x): pass\n\nb: Literal['foo']\nreveal_type(f4(1))      # N: Revealed type is \"builtins.int\"\nreveal_type(f4(a))      # N: Revealed type is \"Literal[1]\"\nreveal_type(f4(\"foo\"))  # N: Revealed type is \"builtins.str\"\n\n# Note: first overload is selected and prevents the typevar from\n# ever inferring a Literal[\"something\"].\nreveal_type(f4(b))      # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralInferredInOverloadContextUnionMathTrickyOverload]\n# This test is a transliteration of check-overloading::testUnionMathTrickyOverload1\nfrom typing import Literal, overload\n\n@overload\ndef f(x: Literal['a'], y: Literal['a']) -> int: ...\n@overload\ndef f(x: str, y: Literal['b']) -> str: ...\ndef f(x):\n    pass\n\nx: Literal['a', 'b']\ny: Literal['a', 'b']\nf(x, y)  # E: Argument 1 to \"f\" has incompatible type \"Literal['a', 'b']\"; expected \"Literal['a']\" \\\n         # E: Argument 2 to \"f\" has incompatible type \"Literal['a', 'b']\"; expected \"Literal['a']\" \\\n[builtins fixtures/tuple.pyi]\n[out]\n\n\n---\n--- Tests that make sure we're correctly using the fallback\n---\n\n[case testLiteralFallbackOperatorsWorkCorrectly]\nfrom typing import Literal\n\na: Literal[3]\nb: int\nc: Literal[4]\nd: Literal['foo']\ne: str\n\nreveal_type(a + a)      # N: Revealed type is \"builtins.int\"\nreveal_type(a + b)      # N: Revealed type is \"builtins.int\"\nreveal_type(b + a)      # N: Revealed type is \"builtins.int\"\nreveal_type(a + 1)      # N: Revealed type is \"builtins.int\"\nreveal_type(1 + a)      # N: Revealed type is \"builtins.int\"\nreveal_type(a + c)      # N: Revealed type is \"builtins.int\"\nreveal_type(c + a)      # N: Revealed type is \"builtins.int\"\n\nreveal_type(d + d)      # N: Revealed type is \"builtins.str\"\nreveal_type(d + e)      # N: Revealed type is \"builtins.str\"\nreveal_type(e + d)      # N: Revealed type is \"builtins.str\"\nreveal_type(d + 'foo')  # N: Revealed type is \"builtins.str\"\nreveal_type('foo' + d)  # N: Revealed type is \"builtins.str\"\n\nreveal_type(a.__add__(b))  # N: Revealed type is \"builtins.int\"\nreveal_type(b.__add__(a))  # N: Revealed type is \"builtins.int\"\n\na *= b                  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Literal[3]\")\nb *= a\n\nreveal_type(b)          # N: Revealed type is \"builtins.int\"\n[builtins fixtures/primitives.pyi]\n\n[case testLiteralFallbackInheritedMethodsWorkCorrectly]\nfrom typing import Literal\na: Literal['foo']\nb: str\n\nreveal_type(a.startswith(a))    # N: Revealed type is \"builtins.bool\"\nreveal_type(b.startswith(a))    # N: Revealed type is \"builtins.bool\"\nreveal_type(a.startswith(b))    # N: Revealed type is \"builtins.bool\"\nreveal_type(a.strip())          # N: Revealed type is \"builtins.str\"\n[builtins fixtures/ops.pyi]\n[out]\n\n[case testLiteralFallbackMethodsDoNotCoerceToLiteral]\nfrom typing import Literal\n\na: Literal[3]\nb: int\nc: Literal[\"foo\"]\n\nif int():\n    a = a * a  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Literal[3]\")\n    a = a * b  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Literal[3]\")\n    a = b * a  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Literal[3]\")\n\n    b = a * a\n    b = a * b\n    b = b * a\n\n    c = c.strip()  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"Literal['foo']\")\n[builtins fixtures/ops.pyi]\n[out]\n\n\n--\n-- Tests that check we report errors when we try using Literal[...]\n-- in invalid places.\n--\n\n[case testLiteralErrorsWithIsInstanceAndIsSubclass]\nfrom typing_extensions import Literal\nfrom typing_extensions import Literal as Renamed\nimport typing_extensions as indirect\n\nAlias = Literal[3]\n\nisinstance(3, Literal[3])           # E: Cannot use isinstance() with Literal type\nisinstance(3, Alias)                # E: Cannot use isinstance() with Literal type \\\n                                    # E: Argument 2 to \"isinstance\" has incompatible type \"<typing special form>\"; expected \"type | tuple[Any, ...]\"\nisinstance(3, Renamed[3])           # E: Cannot use isinstance() with Literal type\nisinstance(3, indirect.Literal[3])  # E: Cannot use isinstance() with Literal type\n\nissubclass(int, Literal[3])           # E: Cannot use issubclass() with Literal type\nissubclass(int, Alias)                # E: Cannot use issubclass() with Literal type \\\n                                      # E: Argument 2 to \"issubclass\" has incompatible type \"<typing special form>\"; expected \"type | tuple[Any, ...]\"\nissubclass(int, Renamed[3])           # E: Cannot use issubclass() with Literal type\nissubclass(int, indirect.Literal[3])  # E: Cannot use issubclass() with Literal type\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\n\n[case testLiteralErrorsWhenSubclassed]\nfrom typing import Literal\nfrom typing import Literal as Renamed\nimport typing as indirect\n\nAlias = Literal[3]\n\nclass Bad1(Literal[3]): pass            # E: Invalid base class \"Literal\"\nclass Bad2(Renamed[3]): pass            # E: Invalid base class \"Renamed\"\nclass Bad3(indirect.Literal[3]): pass   # E: Invalid base class \"indirect.Literal\"\nclass Bad4(Alias): pass                 # E: Invalid base class \"Alias\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralErrorsWhenInvoked-skip]\n# TODO: We don't seem to correctly handle invoking types like\n# 'Final' and 'Protocol' as well. When fixing this, also fix\n# those types?\nfrom typing import Literal\nfrom typing import Literal as Renamed\nimport typing as indirect\n\nAlias = Literal[3]\n\nLiteral[3]()           # E: The type \"Type[Literal]\" is not generic and not indexable\nRenamed[3]()           # E: The type \"Type[Literal]\" is not generic and not indexable\nindirect.Literal[3]()  # E: The type \"Type[Literal]\" is not generic and not indexable\nAlias()                # E: \"object\" not callable\n\n# TODO: Add appropriate error messages to the following lines\nLiteral()\nRenamed()\nindirect.Literal()\n[builtins fixtures/isinstancelist.pyi]\n[out]\n\n\n--\n-- Test to make sure literals interact with generics as expected\n--\n\n[case testLiteralAndGenericsWithSimpleFunctions]\nfrom typing import Literal, TypeVar\n\nT = TypeVar('T')\ndef foo(x: T) -> T: pass\ndef expects_literal(x: Literal[3]) -> None: pass\ndef expects_int(x: int) -> None: pass\n\na: Literal[3]\nreveal_type(foo(3))  # N: Revealed type is \"builtins.int\"\nreveal_type(foo(a))  # N: Revealed type is \"Literal[3]\"\n\nexpects_literal(3)\nexpects_literal(foo(3))\nexpects_literal(foo(foo(3)))\n\nexpects_literal(a)\nexpects_literal(foo(a))\nexpects_literal(foo(foo(a)))\n\nexpects_literal(5)              # E: Argument 1 to \"expects_literal\" has incompatible type \"Literal[5]\"; expected \"Literal[3]\"\nexpects_literal(foo(5))         # E: Argument 1 to \"foo\" has incompatible type \"Literal[5]\"; expected \"Literal[3]\"\nexpects_literal(foo(foo(5)))    # E: Argument 1 to \"foo\" has incompatible type \"Literal[5]\"; expected \"Literal[3]\"\n\nexpects_int(a)\nexpects_int(foo(a))\nexpects_int(foo(foo(a)))\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralAndGenericWithUnion]\nfrom typing import Literal, TypeVar, Union\n\nT = TypeVar('T')\ndef identity(x: T) -> T: return x\n\na: Union[int, Literal['foo']] = identity('foo')\nb: Union[int, Literal['foo']] = identity('bar')  # E: Argument 1 to \"identity\" has incompatible type \"Literal['bar']\"; expected \"int | Literal['foo']\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralAndGenericsNoMatch]\nfrom typing import Literal, TypeVar, Union, List\n\ndef identity(x: T) -> T:\n    return x\n\nOk1 = Union[List[int], Literal['bad']]\nOk2 = Union[List[Literal[42]], Literal['bad']]\nBad = Union[List[Literal[43]], Literal['bad']]\n\nx: Ok1 = identity([42])\ny: Ok2 = identity([42])\nz: Bad = identity([42])  # E: List item 0 has incompatible type \"Literal[42]\"; expected \"Literal[43]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testLiteralAndGenericsWithSimpleClasses]\nfrom typing import Literal, TypeVar, Generic\n\nT = TypeVar('T')\nclass Wrapper(Generic[T]):\n    def __init__(self, val: T) -> None:\n        self.val = val\n    def inner(self) -> T:\n        return self.val\n\ndef expects_literal(a: Literal[3]) -> None: pass\ndef expects_literal_wrapper(x: Wrapper[Literal[3]]) -> None: pass\n\na: Literal[3]\nreveal_type(Wrapper(3))              # N: Revealed type is \"__main__.Wrapper[builtins.int]\"\nreveal_type(Wrapper[Literal[3]](3))  # N: Revealed type is \"__main__.Wrapper[Literal[3]]\"\nreveal_type(Wrapper(a))              # N: Revealed type is \"__main__.Wrapper[Literal[3]]\"\n\nexpects_literal(Wrapper(a).inner())\n\n# Note: the following probably ought to type-check: it's reasonable to infer\n# Wrapper[Literal[3]] here.\n# TODO: Consider finding a way to handle this edge case better\nexpects_literal(Wrapper(3).inner())  # E: Argument 1 to \"expects_literal\" has incompatible type \"int\"; expected \"Literal[3]\"\n\n# Note: if we handle the edge case above, we should make sure this error\n# message switches to warning about an incompatible type 'Literal[5]' rather\n# then an incompatible type 'int'\nexpects_literal(Wrapper(5).inner())  # E: Argument 1 to \"expects_literal\" has incompatible type \"int\"; expected \"Literal[3]\"\n\nexpects_literal_wrapper(Wrapper(a))\nexpects_literal_wrapper(Wrapper(3))\nexpects_literal_wrapper(Wrapper(5))  # E: Argument 1 to \"Wrapper\" has incompatible type \"Literal[5]\"; expected \"Literal[3]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralAndGenericsRespectsUpperBound]\nfrom typing import Literal, TypeVar\n\nTLiteral = TypeVar('TLiteral', bound=Literal[3])\nTInt = TypeVar('TInt', bound=int)\n\ndef func1(x: TLiteral) -> TLiteral: pass\ndef func2(x: TInt) -> TInt: pass\n\ndef func3(x: TLiteral) -> TLiteral:\n    y = func2(x)\n    return y\ndef func4(x: TInt) -> TInt:\n    y = func1(x)  # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"TInt\"\n    return y\n\na: Literal[3]\nb: Literal[4]\nc: int\n\nreveal_type(func1)      # N: Revealed type is \"def [TLiteral <: Literal[3]] (x: TLiteral`-1) -> TLiteral`-1\"\n\nreveal_type(func1(3))   # N: Revealed type is \"Literal[3]\"\nreveal_type(func1(a))   # N: Revealed type is \"Literal[3]\"\nreveal_type(func1(4))   # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"Literal[4]\" \\\n                        # N: Revealed type is \"Literal[4]\"\nreveal_type(func1(b))   # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"Literal[4]\" \\\n                        # N: Revealed type is \"Literal[4]\"\nreveal_type(func1(c))   # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"int\" \\\n                        # N: Revealed type is \"builtins.int\"\n\nreveal_type(func2(3))   # N: Revealed type is \"builtins.int\"\nreveal_type(func2(a))   # N: Revealed type is \"Literal[3]\"\nreveal_type(func2(4))   # N: Revealed type is \"builtins.int\"\nreveal_type(func2(b))   # N: Revealed type is \"Literal[4]\"\nreveal_type(func2(c))   # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralAndGenericsRespectsValueRestriction]\nfrom typing import Literal, TypeVar\n\nTLiteral = TypeVar('TLiteral', Literal[3], Literal['foo'])\nTNormal = TypeVar('TNormal', int, str)\n\ndef func1(x: TLiteral) -> TLiteral: pass\ndef func2(x: TNormal) -> TNormal: pass\n\ndef func3(x: TLiteral) -> TLiteral:\n    y = func2(x)\n    return y      # E: Incompatible return value type (got \"int\", expected \"Literal[3]\") \\\n                  # E: Incompatible return value type (got \"str\", expected \"Literal['foo']\")\ndef func4(x: TNormal) -> TNormal:\n    y = func1(x)  # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"int\" \\\n                  # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"str\"\n    return y\n\ni1: Literal[3]\ni2: Literal[4]\ni: int\n\ns1: Literal['foo']\ns2: Literal['bar']\ns: str\n\nreveal_type(func1)          # N: Revealed type is \"def [TLiteral in (Literal[3], Literal['foo'])] (x: TLiteral`-1) -> TLiteral`-1\"\n\nreveal_type(func1(3))       # N: Revealed type is \"Literal[3]\"\nreveal_type(func1(i1))      # N: Revealed type is \"Literal[3]\"\nreveal_type(func1(4))       # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"Literal[4]\" \\\n                            # N: Revealed type is \"Literal[4]\"\nreveal_type(func1(i2))      # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"Literal[4]\" \\\n                            # N: Revealed type is \"Literal[4]\"\nreveal_type(func1(i))       # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"int\" \\\n                            # N: Revealed type is \"builtins.int\"\nreveal_type(func1(\"foo\"))   # N: Revealed type is \"Literal['foo']\"\nreveal_type(func1(s1))      # N: Revealed type is \"Literal['foo']\"\nreveal_type(func1(\"bar\"))   # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"Literal['bar']\" \\\n                            # N: Revealed type is \"Literal['bar']\"\nreveal_type(func1(s2))      # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"Literal['bar']\" \\\n                            # N: Revealed type is \"Literal['bar']\"\nreveal_type(func1(s))       # E: Value of type variable \"TLiteral\" of \"func1\" cannot be \"str\" \\\n                            # N: Revealed type is \"builtins.str\"\n\nreveal_type(func2(3))       # N: Revealed type is \"builtins.int\"\nreveal_type(func2(i1))      # N: Revealed type is \"builtins.int\"\nreveal_type(func2(4))       # N: Revealed type is \"builtins.int\"\nreveal_type(func2(i2))      # N: Revealed type is \"builtins.int\"\nreveal_type(func2(\"foo\"))   # N: Revealed type is \"builtins.str\"\nreveal_type(func2(s1))      # N: Revealed type is \"builtins.str\"\nreveal_type(func2(\"bar\"))   # N: Revealed type is \"builtins.str\"\nreveal_type(func2(s2))      # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralAndGenericsWithOverloads]\nfrom typing import Literal, TypeVar, overload, Union\n\n@overload\ndef func1(x: Literal[4]) -> Literal[19]: ...\n@overload\ndef func1(x: int) -> int: ...\ndef func1(x: int) -> int: pass\n\nT = TypeVar('T')\ndef identity(x: T) -> T: pass\n\na: Literal[4]\nb: Literal[5]\n\nreveal_type(func1(identity(4)))  # N: Revealed type is \"Literal[19]\"\nreveal_type(func1(identity(5)))  # N: Revealed type is \"builtins.int\"\nreveal_type(func1(identity(a)))  # N: Revealed type is \"Literal[19]\"\nreveal_type(func1(identity(b)))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n--\n-- Interactions with meets\n--\n\n[case testLiteralMeets]\nfrom typing import TypeVar, List, Literal, Callable, Union, Optional\n\na: Callable[[Literal[1]], int]\nb: Callable[[Literal[2]], str]\nc: Callable[[int], str]\nd: Callable[[object], str]\ne: Callable[[Union[Literal[1], Literal[2]]], str]\n\narr1 = [a, a]\narr2 = [a, b]\narr3 = [a, c]\narr4 = [a, d]\narr5 = [a, e]\n\nreveal_type(arr1)  # N: Revealed type is \"builtins.list[def (Literal[1]) -> builtins.int]\"\nreveal_type(arr2)  # N: Revealed type is \"builtins.list[builtins.function]\"\nreveal_type(arr3)  # N: Revealed type is \"builtins.list[def (Literal[1]) -> builtins.object]\"\nreveal_type(arr4)  # N: Revealed type is \"builtins.list[def (Literal[1]) -> builtins.object]\"\nreveal_type(arr5)  # N: Revealed type is \"builtins.list[def (Literal[1]) -> builtins.object]\"\n\n# Inspect just only one interesting one\nlit: Literal[1]\nreveal_type(arr2[0](lit))  # E: Cannot call function of unknown type \\\n                           # N: Revealed type is \"Any\"\n\nT = TypeVar('T')\ndef unify(func: Callable[[T, T], None]) -> T: pass\n\ndef f1(x: Literal[1], y: Literal[1]) -> None: pass\ndef f2(x: Literal[1], y: Literal[2]) -> None: pass\ndef f3(x: Literal[1], y: int) -> None: pass\ndef f4(x: Literal[1], y: object) -> None: pass\ndef f5(x: Literal[1], y: Union[Literal[1], Literal[2]]) -> None: pass\ndef f6(x: Optional[Literal[1]], y: Optional[Literal[2]]) -> None: pass\n\nreveal_type(unify(f1))  # N: Revealed type is \"Literal[1]\"\nif object():\n    reveal_type(unify(f2))  # N: Revealed type is \"Never\"\nreveal_type(unify(f3))  # N: Revealed type is \"Literal[1]\"\nreveal_type(unify(f4))  # N: Revealed type is \"Literal[1]\"\nreveal_type(unify(f5))  # N: Revealed type is \"Literal[1]\"\nreveal_type(unify(f6))  # N: Revealed type is \"None\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testLiteralMeetsWithStrictOptional]\nfrom typing import TypeVar, Callable, Literal, Union\n\na: Callable[[Literal[1]], int]\nb: Callable[[Literal[2]], str]\nlit: Literal[1]\n\narr = [a, b]\nreveal_type(arr)  # N: Revealed type is \"builtins.list[builtins.function]\"\nreveal_type(arr[0](lit))  # E: Cannot call function of unknown type \\\n                          # N: Revealed type is \"Any\"\n\nT = TypeVar('T')\ndef unify(func: Callable[[T, T], None]) -> T: pass\ndef func(x: Literal[1], y: Literal[2]) -> None: pass\n\nreveal_type(unify(func))  # N: Revealed type is \"Never\"\n[builtins fixtures/list.pyi]\n[out]\n\n\n--\n-- Checks for intelligent indexing\n--\n\n[case testLiteralIntelligentIndexingTuples]\nfrom typing import Literal, Tuple, NamedTuple, Optional, Final\n\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\nclass E: pass\n\nidx0: Literal[0]\nidx1: Literal[1]\nidx2: Literal[2]\nidx3: Literal[3]\nidx4: Literal[4]\nidx5: Literal[5]\nidx_neg1: Literal[-1]\nidx_final: Final = 2\n\ntup1: Tuple[A, B, Optional[C], D, E]\nreveal_type(tup1[idx0])       # N: Revealed type is \"__main__.A\"\nreveal_type(tup1[idx1])       # N: Revealed type is \"__main__.B\"\nreveal_type(tup1[idx2])       # N: Revealed type is \"__main__.C | None\"\nreveal_type(tup1[idx_final])  # N: Revealed type is \"__main__.C | None\"\nreveal_type(tup1[idx3])       # N: Revealed type is \"__main__.D\"\nreveal_type(tup1[idx4])       # N: Revealed type is \"__main__.E\"\nreveal_type(tup1[idx_neg1])   # N: Revealed type is \"__main__.E\"\ntup1[idx5]                    # E: Tuple index out of range\nreveal_type(tup1[idx2:idx4])  # N: Revealed type is \"tuple[__main__.C | None, __main__.D]\"\nreveal_type(tup1[::idx2])     # N: Revealed type is \"tuple[__main__.A, __main__.C | None, __main__.E]\"\nif tup1[idx2] is not None:\n    reveal_type(tup1[idx2])   # N: Revealed type is \"__main__.C | None\"\nif tup1[idx_final] is not None:\n    reveal_type(tup1[idx_final]) # N: Revealed type is \"__main__.C\"\n\nTup2Class = NamedTuple('Tup2Class', [('a', A), ('b', B), ('c', C), ('d', D), ('e', E)])\ntup2: Tup2Class\nreveal_type(tup2[idx0])       # N: Revealed type is \"__main__.A\"\nreveal_type(tup2[idx1])       # N: Revealed type is \"__main__.B\"\nreveal_type(tup2[idx2])       # N: Revealed type is \"__main__.C\"\nreveal_type(tup2[idx3])       # N: Revealed type is \"__main__.D\"\nreveal_type(tup2[idx4])       # N: Revealed type is \"__main__.E\"\nreveal_type(tup2[idx_neg1])   # N: Revealed type is \"__main__.E\"\ntup2[idx5]                    # E: Tuple index out of range\nreveal_type(tup2[idx2:idx4])  # N: Revealed type is \"tuple[__main__.C, __main__.D]\"\nreveal_type(tup2[::idx2])     # N: Revealed type is \"tuple[__main__.A, __main__.C, __main__.E]\"\ntup3: Tup2Class = tup2[:]     # E: Incompatible types in assignment (expression has type \"tuple[A, B, C, D, E]\", variable has type \"Tup2Class\")\n[builtins fixtures/slice.pyi]\n\n[case testLiteralIntelligentIndexingTypedDict]\nfrom typing import Literal, TypedDict\n\nclass Unrelated: pass\nu: Unrelated\n\nclass Inner(TypedDict):\n    a: int\nclass Outer(Inner, total=False):\n    b: str\n\na_key: Literal[\"a\"]\nb_key: Literal[\"b\"]\nc_key: Literal[\"c\"]\n\nd: Outer\n\nreveal_type(d[a_key])         # N: Revealed type is \"builtins.int\"\nreveal_type(d[b_key])         # N: Revealed type is \"builtins.str\"\nd[c_key]                      # E: TypedDict \"Outer\" has no key \"c\"\n\nreveal_type(d.get(a_key, u))  # N: Revealed type is \"builtins.int\"\nreveal_type(d.get(b_key, u))  # N: Revealed type is \"builtins.str | __main__.Unrelated\"\nreveal_type(d.get(c_key, u))  # N: Revealed type is \"builtins.object\"\n\nreveal_type(d.pop(a_key))     # N: Revealed type is \"builtins.int\" \\\n                              # E: Key \"a\" of TypedDict \"Outer\" cannot be deleted\n\nreveal_type(d.pop(b_key))     # N: Revealed type is \"builtins.str\"\nd.pop(c_key)                  # E: TypedDict \"Outer\" has no key \"c\"\n\ndel d[a_key]                  # E: Key \"a\" of TypedDict \"Outer\" cannot be deleted\ndel d[b_key]\ndel d[c_key]                  # E: TypedDict \"Outer\" has no key \"c\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testLiteralIntelligentIndexingUsingFinal]\nfrom typing import Final, Literal, Tuple, NamedTuple, TypedDict\n\nint_key_good: Final = 0\nint_key_bad: Final = 3\nstr_key_good: Final = \"foo\"\nstr_key_bad: Final = \"missing\"\n\nclass Unrelated: pass\n\nMyTuple = NamedTuple('MyTuple', [\n    ('foo', int),\n    ('bar', str),\n])\n\nclass MyDict(TypedDict):\n    foo: int\n    bar: str\n\na: Tuple[int, str]\nb: MyTuple\nc: MyDict\nu: Unrelated\n\nreveal_type(a[int_key_good])         # N: Revealed type is \"builtins.int\"\nreveal_type(b[int_key_good])         # N: Revealed type is \"builtins.int\"\nreveal_type(c[str_key_good])         # N: Revealed type is \"builtins.int\"\nreveal_type(c.get(str_key_good, u))  # N: Revealed type is \"builtins.int\"\nreveal_type(c.get(str_key_bad, u))   # N: Revealed type is \"builtins.object\"\n\na[int_key_bad]                       # E: Tuple index out of range\nb[int_key_bad]                       # E: Tuple index out of range\nc[str_key_bad]                       # E: TypedDict \"MyDict\" has no key \"missing\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testLiteralIntelligentIndexingTupleUnions]\nfrom typing import Literal, Tuple, NamedTuple\n\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\nclass E: pass\n\nidx1: Literal[1, 2]\nidx2: Literal[3, 4]\nidx_bad: Literal[1, 20]\n\ntup1: Tuple[A, B, C, D, E]\nTup2Class = NamedTuple('Tup2Class', [('a', A), ('b', B), ('c', C), ('d', D), ('e', E)])\ntup2: Tup2Class\n\nreveal_type(tup1[idx1])         # N: Revealed type is \"__main__.B | __main__.C\"\nreveal_type(tup1[idx1:idx2])    # N: Revealed type is \"tuple[__main__.B, __main__.C] | tuple[__main__.B, __main__.C, __main__.D] | tuple[__main__.C] | tuple[__main__.C, __main__.D]\"\nreveal_type(tup1[0::idx1])      # N: Revealed type is \"tuple[__main__.A, __main__.B, __main__.C, __main__.D, __main__.E] | tuple[__main__.A, __main__.C, __main__.E]\"\ntup1[idx_bad]                   # E: Tuple index out of range\n\nreveal_type(tup2[idx1])         # N: Revealed type is \"__main__.B | __main__.C\"\nreveal_type(tup2[idx1:idx2])    # N: Revealed type is \"tuple[__main__.B, __main__.C] | tuple[__main__.B, __main__.C, __main__.D] | tuple[__main__.C] | tuple[__main__.C, __main__.D]\"\nreveal_type(tup2[0::idx1])      # N: Revealed type is \"tuple[__main__.A, __main__.B, __main__.C, __main__.D, __main__.E] | tuple[__main__.A, __main__.C, __main__.E]\"\ntup2[idx_bad]                   # E: Tuple index out of range\n[builtins fixtures/slice.pyi]\n[out]\n\n[case testLiteralIntelligentIndexingTypedDictUnions]\nfrom typing import Final, Literal, TypedDict\n\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\nclass E: pass\n\nclass Base(TypedDict):\n    a: A\n    b: B\n    c: C\n\nclass Test(Base, total=False):\n    d: D\n    e: E\n\nclass AAndB(A, B): pass\n\ntest: Test\ngood_keys: Literal[\"a\", \"b\"]\noptional_keys: Literal[\"d\", \"e\"]\nbad_keys: Literal[\"a\", \"bad\"]\n\nreveal_type(test[good_keys])                      # N: Revealed type is \"__main__.A | __main__.B\"\nreveal_type(test.get(good_keys))                  # N: Revealed type is \"__main__.A | __main__.B\"\nreveal_type(test.get(good_keys, 3))               # N: Revealed type is \"__main__.A | __main__.B\"\nreveal_type(test.pop(optional_keys))              # N: Revealed type is \"__main__.D | __main__.E\"\nreveal_type(test.pop(optional_keys, 3))           # N: Revealed type is \"__main__.D | __main__.E | Literal[3]?\"\nreveal_type(test.setdefault(good_keys, AAndB()))  # N: Revealed type is \"__main__.A | __main__.B\"\nreveal_type(test.get(bad_keys))                   # N: Revealed type is \"builtins.object\"\nreveal_type(test.get(bad_keys, 3))                # N: Revealed type is \"builtins.object\"\ndel test[optional_keys]\n\n\ntest[bad_keys]                  # E: TypedDict \"Test\" has no key \"bad\"\ntest.pop(good_keys)             # E: Key \"a\" of TypedDict \"Test\" cannot be deleted \\\n                                # E: Key \"b\" of TypedDict \"Test\" cannot be deleted\ntest.pop(bad_keys)              # E: Key \"a\" of TypedDict \"Test\" cannot be deleted \\\n                                # E: TypedDict \"Test\" has no key \"bad\"\ntest.setdefault(good_keys, 3)   # E: Argument 2 to \"setdefault\" of \"TypedDict\" has incompatible type \"int\"; expected \"A\"\ntest.setdefault(bad_keys, 3 )   # E: Argument 2 to \"setdefault\" of \"TypedDict\" has incompatible type \"int\"; expected \"A\"\ndel test[good_keys]             # E: Key \"a\" of TypedDict \"Test\" cannot be deleted \\\n                                # E: Key \"b\" of TypedDict \"Test\" cannot be deleted\ndel test[bad_keys]              # E: Key \"a\" of TypedDict \"Test\" cannot be deleted \\\n                                # E: TypedDict \"Test\" has no key \"bad\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n[out]\n\n[case testLiteralIntelligentIndexingMultiTypedDict]\nfrom typing import Literal, TypedDict, Union\n\nclass A: pass\nclass B: pass\nclass C: pass\nclass D: pass\n\nclass D1(TypedDict):\n    a: A\n    b: B\n    c: C\n\nclass D2(TypedDict):\n    b: B\n    c: C\n    d: D\n\nx: Union[D1, D2]\ngood_keys: Literal['b', 'c']\nmixed_keys: Literal['a', 'b', 'c', 'd']\nbad_keys: Literal['e', 'f']\n\nx[mixed_keys]         # E: TypedDict \"D1\" has no key \"d\" \\\n                    # E: TypedDict \"D2\" has no key \"a\"\n\nreveal_type(x[good_keys])           # N: Revealed type is \"__main__.B | __main__.C\"\nreveal_type(x.get(good_keys))       # N: Revealed type is \"__main__.B | __main__.C\"\nreveal_type(x.get(good_keys, 3))    # N: Revealed type is \"__main__.B | __main__.C\"\nreveal_type(x.get(mixed_keys))      # N: Revealed type is \"builtins.object\"\nreveal_type(x.get(mixed_keys, 3))   # N: Revealed type is \"builtins.object\"\nreveal_type(x.get(bad_keys))        # N: Revealed type is \"builtins.object\"\nreveal_type(x.get(bad_keys, 3))     # N: Revealed type is \"builtins.object\"\n\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n--\n-- Interactions with 'Final'\n--\n\n[case testLiteralFinalInferredAsLiteral]\nfrom typing import Final, Literal\n\nvar1: Final = 1\nvar2: Final = \"foo\"\nvar3: Final = True\nvar4: Final = None\n\nclass Foo:\n    classvar1: Final = 1\n    classvar2: Final = \"foo\"\n    classvar3: Final = True\n    classvar4: Final = None\n\n    def __init__(self) -> None:\n        self.instancevar1: Final = 1\n        self.instancevar2: Final = \"foo\"\n        self.instancevar3: Final = True\n        self.instancevar4: Final = None\n\ndef force1(x: Literal[1]) -> None: pass\ndef force2(x: Literal[\"foo\"]) -> None: pass\ndef force3(x: Literal[True]) -> None: pass\ndef force4(x: Literal[None]) -> None: pass\n\nreveal_type(var1)                    # N: Revealed type is \"Literal[1]?\"\nreveal_type(var2)                    # N: Revealed type is \"Literal['foo']?\"\nreveal_type(var3)                    # N: Revealed type is \"Literal[True]?\"\nreveal_type(var4)                    # N: Revealed type is \"None\"\nforce1(reveal_type(var1))            # N: Revealed type is \"Literal[1]\"\nforce2(reveal_type(var2))            # N: Revealed type is \"Literal['foo']\"\nforce3(reveal_type(var3))            # N: Revealed type is \"Literal[True]\"\nforce4(reveal_type(var4))            # N: Revealed type is \"None\"\n\nreveal_type(Foo.classvar1)           # N: Revealed type is \"Literal[1]?\"\nreveal_type(Foo.classvar2)           # N: Revealed type is \"Literal['foo']?\"\nreveal_type(Foo.classvar3)           # N: Revealed type is \"Literal[True]?\"\nreveal_type(Foo.classvar4)           # N: Revealed type is \"None\"\nforce1(reveal_type(Foo.classvar1))   # N: Revealed type is \"Literal[1]\"\nforce2(reveal_type(Foo.classvar2))   # N: Revealed type is \"Literal['foo']\"\nforce3(reveal_type(Foo.classvar3))   # N: Revealed type is \"Literal[True]\"\nforce4(reveal_type(Foo.classvar4))   # N: Revealed type is \"None\"\n\nf = Foo()\nreveal_type(f.instancevar1)          # N: Revealed type is \"Literal[1]?\"\nreveal_type(f.instancevar2)          # N: Revealed type is \"Literal['foo']?\"\nreveal_type(f.instancevar3)          # N: Revealed type is \"Literal[True]?\"\nreveal_type(f.instancevar4)          # N: Revealed type is \"None\"\nforce1(reveal_type(f.instancevar1))  # N: Revealed type is \"Literal[1]\"\nforce2(reveal_type(f.instancevar2))  # N: Revealed type is \"Literal['foo']\"\nforce3(reveal_type(f.instancevar3))  # N: Revealed type is \"Literal[True]\"\nforce4(reveal_type(f.instancevar4))  # N: Revealed type is \"None\"\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testLiteralFinalDirectInstanceTypesSupersedeInferredLiteral]\nfrom typing import Final, Literal\n\nvar1: Final[int] = 1\nvar2: Final[str] = \"foo\"\nvar3: Final[bool] = True\nvar4: Final[None] = None\n\nclass Foo:\n    classvar1: Final[int] = 1\n    classvar2: Final[str] = \"foo\"\n    classvar3: Final[bool] = True\n    classvar4: Final[None] = None\n\n    def __init__(self) -> None:\n        self.instancevar1: Final[int] = 1\n        self.instancevar2: Final[str] = \"foo\"\n        self.instancevar3: Final[bool] = True\n        self.instancevar4: Final[None] = None\n\ndef force1(x: Literal[1]) -> None: pass\ndef force2(x: Literal[\"foo\"]) -> None: pass\ndef force3(x: Literal[True]) -> None: pass\ndef force4(x: Literal[None]) -> None: pass\n\nreveal_type(var1)            # N: Revealed type is \"builtins.int\"\nreveal_type(var2)            # N: Revealed type is \"builtins.str\"\nreveal_type(var3)            # N: Revealed type is \"builtins.bool\"\nreveal_type(var4)            # N: Revealed type is \"None\"\nforce1(var1)                 # E: Argument 1 to \"force1\" has incompatible type \"int\"; expected \"Literal[1]\"\nforce2(var2)                 # E: Argument 1 to \"force2\" has incompatible type \"str\"; expected \"Literal['foo']\"\nforce3(var3)                 # E: Argument 1 to \"force3\" has incompatible type \"bool\"; expected \"Literal[True]\"\nforce4(var4)\n\nreveal_type(Foo.classvar1)   # N: Revealed type is \"builtins.int\"\nreveal_type(Foo.classvar2)   # N: Revealed type is \"builtins.str\"\nreveal_type(Foo.classvar3)   # N: Revealed type is \"builtins.bool\"\nreveal_type(Foo.classvar4)   # N: Revealed type is \"None\"\nforce1(Foo.classvar1)        # E: Argument 1 to \"force1\" has incompatible type \"int\"; expected \"Literal[1]\"\nforce2(Foo.classvar2)        # E: Argument 1 to \"force2\" has incompatible type \"str\"; expected \"Literal['foo']\"\nforce3(Foo.classvar3)        # E: Argument 1 to \"force3\" has incompatible type \"bool\"; expected \"Literal[True]\"\nforce4(Foo.classvar4)\n\nf = Foo()\nreveal_type(f.instancevar1)  # N: Revealed type is \"builtins.int\"\nreveal_type(f.instancevar2)  # N: Revealed type is \"builtins.str\"\nreveal_type(f.instancevar3)  # N: Revealed type is \"builtins.bool\"\nreveal_type(f.instancevar4)  # N: Revealed type is \"None\"\nforce1(f.instancevar1)       # E: Argument 1 to \"force1\" has incompatible type \"int\"; expected \"Literal[1]\"\nforce2(f.instancevar2)       # E: Argument 1 to \"force2\" has incompatible type \"str\"; expected \"Literal['foo']\"\nforce3(f.instancevar3)       # E: Argument 1 to \"force3\" has incompatible type \"bool\"; expected \"Literal[True]\"\nforce4(f.instancevar4)\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testLiteralFinalDirectLiteralTypesForceLiteral]\nfrom typing import Final, Literal\n\nvar1: Final[Literal[1]] = 1\nvar2: Final[Literal[\"foo\"]] = \"foo\"\nvar3: Final[Literal[True]] = True\nvar4: Final[Literal[None]] = None\n\nclass Foo:\n    classvar1: Final[Literal[1]] = 1\n    classvar2: Final[Literal[\"foo\"]] = \"foo\"\n    classvar3: Final[Literal[True]] = True\n    classvar4: Final[Literal[None]] = None\n\n    def __init__(self) -> None:\n        self.instancevar1: Final[Literal[1]] = 1\n        self.instancevar2: Final[Literal[\"foo\"]] = \"foo\"\n        self.instancevar3: Final[Literal[True]] = True\n        self.instancevar4: Final[Literal[None]] = None\n\ndef force1(x: Literal[1]) -> None: pass\ndef force2(x: Literal[\"foo\"]) -> None: pass\ndef force3(x: Literal[True]) -> None: pass\ndef force4(x: Literal[None]) -> None: pass\n\nreveal_type(var1)                    # N: Revealed type is \"Literal[1]\"\nreveal_type(var2)                    # N: Revealed type is \"Literal['foo']\"\nreveal_type(var3)                    # N: Revealed type is \"Literal[True]\"\nreveal_type(var4)                    # N: Revealed type is \"None\"\nforce1(reveal_type(var1))            # N: Revealed type is \"Literal[1]\"\nforce2(reveal_type(var2))            # N: Revealed type is \"Literal['foo']\"\nforce3(reveal_type(var3))            # N: Revealed type is \"Literal[True]\"\nforce4(reveal_type(var4))            # N: Revealed type is \"None\"\n\nreveal_type(Foo.classvar1)           # N: Revealed type is \"Literal[1]\"\nreveal_type(Foo.classvar2)           # N: Revealed type is \"Literal['foo']\"\nreveal_type(Foo.classvar3)           # N: Revealed type is \"Literal[True]\"\nreveal_type(Foo.classvar4)           # N: Revealed type is \"None\"\nforce1(reveal_type(Foo.classvar1))   # N: Revealed type is \"Literal[1]\"\nforce2(reveal_type(Foo.classvar2))   # N: Revealed type is \"Literal['foo']\"\nforce3(reveal_type(Foo.classvar3))   # N: Revealed type is \"Literal[True]\"\nforce4(reveal_type(Foo.classvar4))   # N: Revealed type is \"None\"\n\nf = Foo()\nreveal_type(f.instancevar1)          # N: Revealed type is \"Literal[1]\"\nreveal_type(f.instancevar2)          # N: Revealed type is \"Literal['foo']\"\nreveal_type(f.instancevar3)          # N: Revealed type is \"Literal[True]\"\nreveal_type(f.instancevar4)          # N: Revealed type is \"None\"\nforce1(reveal_type(f.instancevar1))  # N: Revealed type is \"Literal[1]\"\nforce2(reveal_type(f.instancevar2))  # N: Revealed type is \"Literal['foo']\"\nforce3(reveal_type(f.instancevar3))  # N: Revealed type is \"Literal[True]\"\nforce4(reveal_type(f.instancevar4))  # N: Revealed type is \"None\"\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testLiteralFinalErasureInMutableDatastructures1]\nfrom typing import Final\n\nvar1: Final = [0, None]\nvar2: Final = (0, None)\n\nreveal_type(var1)  # N: Revealed type is \"builtins.list[builtins.int | None]\"\nreveal_type(var2)  # N: Revealed type is \"tuple[Literal[0]?, None]\"\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralFinalErasureInMutableDatastructures2]\nfrom typing import Final, Literal\n\nvar1: Final = []\nvar1.append(0)\nreveal_type(var1)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nvar2 = []\nvar2.append(0)\nreveal_type(var2)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nx: Literal[0] = 0\nvar3 = []\nvar3.append(x)\nreveal_type(var3)  # N: Revealed type is \"builtins.list[Literal[0]]\"\n\n[builtins fixtures/list.pyi]\n\n[case testLiteralFinalMismatchCausesError]\nfrom typing import Final, Literal\n\nvar1: Final[Literal[4]]     = 1      # E: Incompatible types in assignment (expression has type \"Literal[1]\", variable has type \"Literal[4]\")\nvar2: Final[Literal['bad']] = \"foo\"  # E: Incompatible types in assignment (expression has type \"Literal['foo']\", variable has type \"Literal['bad']\")\nvar3: Final[Literal[False]] = True   # E: Incompatible types in assignment (expression has type \"Literal[True]\", variable has type \"Literal[False]\")\n\nclass Foo:\n    classvar1: Final[Literal[4]]     = 1      # E: Incompatible types in assignment (expression has type \"Literal[1]\", variable has type \"Literal[4]\")\n    classvar2: Final[Literal['bad']] = \"foo\"  # E: Incompatible types in assignment (expression has type \"Literal['foo']\", variable has type \"Literal['bad']\")\n    classvar3: Final[Literal[False]] = True   # E: Incompatible types in assignment (expression has type \"Literal[True]\", variable has type \"Literal[False]\")\n\n    def __init__(self) -> None:\n        self.instancevar1: Final[Literal[4]]     = 1      # E: Incompatible types in assignment (expression has type \"Literal[1]\", variable has type \"Literal[4]\")\n        self.instancevar2: Final[Literal['bad']] = \"foo\"  # E: Incompatible types in assignment (expression has type \"Literal['foo']\", variable has type \"Literal['bad']\")\n        self.instancevar3: Final[Literal[False]] = True    # E: Incompatible types in assignment (expression has type \"Literal[True]\", variable has type \"Literal[False]\")\n\n# TODO: Fix the order in which these error messages are shown to be more consistent.\nvar1 = 10                # E: Cannot assign to final name \"var1\" \\\n                         # E: Incompatible types in assignment (expression has type \"Literal[10]\", variable has type \"Literal[4]\")\n\n\nFoo.classvar1 = 10       # E: Cannot assign to final attribute \"classvar1\" \\\n                         # E: Incompatible types in assignment (expression has type \"Literal[10]\", variable has type \"Literal[4]\")\n\nFoo().instancevar1 = 10  # E: Cannot assign to final attribute \"instancevar1\" \\\n                         # E: Incompatible types in assignment (expression has type \"Literal[10]\", variable has type \"Literal[4]\")\n[builtins fixtures/primitives.pyi]\n[out]\n\n[case testLiteralFinalGoesOnlyOneLevelDown]\nfrom typing import Final, Literal, Tuple\n\na: Final = 1\nb: Final = (1, 2)\n\ndef force1(x: Literal[1]) -> None: pass\ndef force2(x: Tuple[Literal[1], Literal[2]]) -> None: pass\n\nreveal_type(a)          # N: Revealed type is \"Literal[1]?\"\nreveal_type(b)          # N: Revealed type is \"tuple[Literal[1]?, Literal[2]?]\"\n\nforce1(a)  # ok\nforce2(b)  # ok\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralFinalCollectionPropagation]\nfrom typing import Final, List, Literal\n\na: Final = 1\nimplicit = [a]\nexplicit: List[Literal[1]] = [a]\ndirect = [1]\n\ndef force1(x: List[Literal[1]]) -> None: pass\ndef force2(x: Literal[1]) -> None: pass\n\nreveal_type(implicit)            # N: Revealed type is \"builtins.list[builtins.int]\"\nforce1(reveal_type(implicit))    # E: Argument 1 to \"force1\" has incompatible type \"list[int]\"; expected \"list[Literal[1]]\" \\\n                                 # N: Revealed type is \"builtins.list[builtins.int]\"\nforce2(reveal_type(implicit[0])) # E: Argument 1 to \"force2\" has incompatible type \"int\"; expected \"Literal[1]\" \\\n                                 # N: Revealed type is \"builtins.int\"\n\nreveal_type(explicit)            # N: Revealed type is \"builtins.list[Literal[1]]\"\nforce1(reveal_type(explicit))    # N: Revealed type is \"builtins.list[Literal[1]]\"\nforce2(reveal_type(explicit[0])) # N: Revealed type is \"Literal[1]\"\n\nreveal_type(direct)              # N: Revealed type is \"builtins.list[builtins.int]\"\nforce1(reveal_type(direct))      # E: Argument 1 to \"force1\" has incompatible type \"list[int]\"; expected \"list[Literal[1]]\" \\\n                                 # N: Revealed type is \"builtins.list[builtins.int]\"\nforce2(reveal_type(direct[0]))   # E: Argument 1 to \"force2\" has incompatible type \"int\"; expected \"Literal[1]\" \\\n                                 # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testLiteralFinalStringTypesPython3]\nfrom typing import Final, Literal\n\na: Final = u\"foo\"\nb: Final = \"foo\"\nc: Final = b\"foo\"\n\ndef force_unicode(x: Literal[u\"foo\"]) -> None: pass\ndef force_bytes(x: Literal[b\"foo\"]) -> None: pass\n\nforce_unicode(reveal_type(a))  # N: Revealed type is \"Literal['foo']\"\nforce_unicode(reveal_type(b))  # N: Revealed type is \"Literal['foo']\"\nforce_unicode(reveal_type(c))  # E: Argument 1 to \"force_unicode\" has incompatible type \"Literal[b'foo']\"; expected \"Literal['foo']\" \\\n                               # N: Revealed type is \"Literal[b'foo']\"\n\nforce_bytes(reveal_type(a))    # E: Argument 1 to \"force_bytes\" has incompatible type \"Literal['foo']\"; expected \"Literal[b'foo']\" \\\n                               # N: Revealed type is \"Literal['foo']\"\nforce_bytes(reveal_type(b))    # E: Argument 1 to \"force_bytes\" has incompatible type \"Literal['foo']\"; expected \"Literal[b'foo']\" \\\n                               # N: Revealed type is \"Literal['foo']\"\nforce_bytes(reveal_type(c))    # N: Revealed type is \"Literal[b'foo']\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralFinalPropagatesThroughGenerics]\nfrom typing import TypeVar, Generic, Final, Literal\n\n\nT = TypeVar('T')\n\nclass WrapperClass(Generic[T]):\n    def __init__(self, data: T) -> None:\n        self.data = data\n\ndef wrapper_func(x: T) -> T:\n    return x\n\ndef force(x: Literal[99]) -> None: pass\ndef over_int(x: WrapperClass[int]) -> None: pass\ndef over_literal(x: WrapperClass[Literal[99]]) -> None: pass\n\nvar1: Final = 99\nw1 = WrapperClass(var1)\nforce(reveal_type(w1.data))                     # E: Argument 1 to \"force\" has incompatible type \"int\"; expected \"Literal[99]\" \\\n                                                # N: Revealed type is \"builtins.int\"\nforce(reveal_type(WrapperClass(var1).data))     # E: Argument 1 to \"force\" has incompatible type \"int\"; expected \"Literal[99]\" \\\n                                                # N: Revealed type is \"builtins.int\"\nforce(reveal_type(wrapper_func(var1)))          # N: Revealed type is \"Literal[99]\"\nover_int(reveal_type(w1))                       # N: Revealed type is \"__main__.WrapperClass[builtins.int]\"\nover_literal(reveal_type(w1))                   # E: Argument 1 to \"over_literal\" has incompatible type \"WrapperClass[int]\"; expected \"WrapperClass[Literal[99]]\" \\\n                                                # N: Revealed type is \"__main__.WrapperClass[builtins.int]\"\nover_int(reveal_type(WrapperClass(var1)))       # N: Revealed type is \"__main__.WrapperClass[builtins.int]\"\nover_literal(reveal_type(WrapperClass(var1)))   # N: Revealed type is \"__main__.WrapperClass[Literal[99]]\"\n\nw2 = WrapperClass(99)\nforce(reveal_type(w2.data))                     # E: Argument 1 to \"force\" has incompatible type \"int\"; expected \"Literal[99]\" \\\n                                                # N: Revealed type is \"builtins.int\"\nforce(reveal_type(WrapperClass(99).data))       # E: Argument 1 to \"force\" has incompatible type \"int\"; expected \"Literal[99]\" \\\n                                                # N: Revealed type is \"builtins.int\"\nforce(reveal_type(wrapper_func(99)))            # N: Revealed type is \"Literal[99]\"\nover_int(reveal_type(w2))                       # N: Revealed type is \"__main__.WrapperClass[builtins.int]\"\nover_literal(reveal_type(w2))                   # E: Argument 1 to \"over_literal\" has incompatible type \"WrapperClass[int]\"; expected \"WrapperClass[Literal[99]]\" \\\n                                                # N: Revealed type is \"__main__.WrapperClass[builtins.int]\"\nover_int(reveal_type(WrapperClass(99)))         # N: Revealed type is \"__main__.WrapperClass[builtins.int]\"\nover_literal(reveal_type(WrapperClass(99)))     # N: Revealed type is \"__main__.WrapperClass[Literal[99]]\"\n\nvar3: Literal[99] = 99\nw3 = WrapperClass(var3)\nforce(reveal_type(w3.data))                     # N: Revealed type is \"Literal[99]\"\nforce(reveal_type(WrapperClass(var3).data))     # N: Revealed type is \"Literal[99]\"\nforce(reveal_type(wrapper_func(var3)))          # N: Revealed type is \"Literal[99]\"\nover_int(reveal_type(w3))                       # E: Argument 1 to \"over_int\" has incompatible type \"WrapperClass[Literal[99]]\"; expected \"WrapperClass[int]\" \\\n                                                # N: Revealed type is \"__main__.WrapperClass[Literal[99]]\"\nover_literal(reveal_type(w3))                   # N: Revealed type is \"__main__.WrapperClass[Literal[99]]\"\nover_int(reveal_type(WrapperClass(var3)))       # N: Revealed type is \"__main__.WrapperClass[builtins.int]\"\nover_literal(reveal_type(WrapperClass(var3)))   # N: Revealed type is \"__main__.WrapperClass[Literal[99]]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralFinalUsedInLiteralType]\nfrom typing import Final, Literal\na: Final[int] = 3\nb: Final = 3\nc: Final[Literal[3]] = 3\nd: Literal[3]\n\na_wrap: Literal[4, a]  # E: Parameter 2 of Literal[...] is invalid\nb_wrap: Literal[4, b]  # E: Parameter 2 of Literal[...] is invalid\nc_wrap: Literal[4, c]  # E: Parameter 2 of Literal[...] is invalid\nd_wrap: Literal[4, d]  # E: Parameter 2 of Literal[...] is invalid\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralWithFinalPropagation]\nfrom typing import Final, Literal\n\na: Final = 3\nb: Final = a\nc = a\n\ndef expect_3(x: Literal[3]) -> None: pass\nexpect_3(a)\nexpect_3(b)\nexpect_3(c)  # E: Argument 1 to \"expect_3\" has incompatible type \"int\"; expected \"Literal[3]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralWithFinalPropagationIsNotLeaking]\nfrom typing import Final, Literal\n\nfinal_tuple_direct: Final = (2, 3)\nfinal_tuple_indirect: Final = final_tuple_direct\nmutable_tuple = final_tuple_direct\nfinal_list_1: Final = [2]\nfinal_list_2: Final = [2, 2]\nfinal_dict: Final = {\"foo\": 2}\nfinal_set_1: Final = {2}\nfinal_set_2: Final = {2, 2}\n\ndef expect_2(x: Literal[2]) -> None: pass\n\nexpect_2(final_tuple_direct[0])\nexpect_2(final_tuple_indirect[0])\n\nexpect_2(mutable_tuple[0])   # E: Argument 1 to \"expect_2\" has incompatible type \"int\"; expected \"Literal[2]\"\nexpect_2(final_list_1[0])    # E: Argument 1 to \"expect_2\" has incompatible type \"int\"; expected \"Literal[2]\"\nexpect_2(final_list_2[0])    # E: Argument 1 to \"expect_2\" has incompatible type \"int\"; expected \"Literal[2]\"\nexpect_2(final_dict[\"foo\"])  # E: Argument 1 to \"expect_2\" has incompatible type \"int\"; expected \"Literal[2]\"\nexpect_2(final_set_1.pop())  # E: Argument 1 to \"expect_2\" has incompatible type \"int\"; expected \"Literal[2]\"\nexpect_2(final_set_2.pop())  # E: Argument 1 to \"expect_2\" has incompatible type \"int\"; expected \"Literal[2]\"\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-medium.pyi]\n\n--\n-- Tests for Literals and enums\n--\n\n[case testLiteralWithEnumsBasic_no_native_parse]\nfrom typing import Literal\nfrom enum import Enum\n\nclass Color(Enum):\n    RED = 1\n    GREEN = 2\n    BLUE = 3\n    __ROUGE = RED\n    def func(self) -> int: pass\n\nr: Literal[Color.RED]\ng: Literal[Color.GREEN]\nb: Literal[Color.BLUE]\nbad1: Literal[Color]         # E: Parameter 1 of Literal[...] is invalid\nbad2: Literal[Color.func]    # E: Parameter 1 of Literal[...] is invalid\nbad3: Literal[Color.func()]  # E: Invalid type: Literal[...] cannot contain arbitrary expressions\n# TODO: change the next line to use Color._Color__ROUGE when mypy implements name mangling\nbad4: Literal[Color.__ROUGE]  # E: Parameter 1 of Literal[...] is invalid\n\ndef expects_color(x: Color) -> None: pass\ndef expects_red(x: Literal[Color.RED]) -> None: pass\ndef bad_func(x: Color.RED) -> None: pass             # E: Invalid type: try using Literal[Color.RED] instead?\n\nexpects_color(r)\nexpects_color(g)\nexpects_color(b)\nexpects_red(r)\nexpects_red(g)  # E: Argument 1 to \"expects_red\" has incompatible type \"Literal[Color.GREEN]\"; expected \"Literal[Color.RED]\"\nexpects_red(b)  # E: Argument 1 to \"expects_red\" has incompatible type \"Literal[Color.BLUE]\"; expected \"Literal[Color.RED]\"\n\nreveal_type(expects_red)  # N: Revealed type is \"def (x: Literal[__main__.Color.RED])\"\nreveal_type(r)            # N: Revealed type is \"Literal[__main__.Color.RED]\"\nreveal_type(r.func())     # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralWithEnumsDefinedInClass]\nfrom typing import Literal\nfrom enum import Enum\n\nclass Wrapper:\n    class Color(Enum):\n        RED = 1\n        GREEN = 2\n        BLUE = 3\n\ndef foo(x: Literal[Wrapper.Color.RED]) -> None: pass\n\nr: Literal[Wrapper.Color.RED]\ng: Literal[Wrapper.Color.GREEN]\n\nfoo(r)\nfoo(g)  # E: Argument 1 to \"foo\" has incompatible type \"Literal[Color.GREEN]\"; expected \"Literal[Color.RED]\"\n\nreveal_type(foo)  # N: Revealed type is \"def (x: Literal[__main__.Wrapper.Color.RED])\"\nreveal_type(r)    # N: Revealed type is \"Literal[__main__.Wrapper.Color.RED]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralWithEnumsSimilarDefinitions]\nfrom typing import Literal\nimport mod_a\nimport mod_b\n\ndef f(x: Literal[mod_a.Test.FOO]) -> None: pass\n\na: Literal[mod_a.Test.FOO]\nb: Literal[mod_a.Test2.FOO]\nc: Literal[mod_b.Test.FOO]\n\nf(a)\nf(b)  # E: Argument 1 to \"f\" has incompatible type \"Literal[Test2.FOO]\"; expected \"Literal[Test.FOO]\"\nf(c)  # E: Argument 1 to \"f\" has incompatible type \"Literal[mod_b.Test.FOO]\"; expected \"Literal[mod_a.Test.FOO]\"\n\n[file mod_a.py]\nfrom enum import Enum\n\nclass Test(Enum):\n    FOO = 1\n    BAR = 2\n\nclass Test2(Enum):\n    FOO = 1\n    BAR = 2\n\n[file mod_b.py]\nfrom enum import Enum\n\nclass Test(Enum):\n    FOO = 1\n    BAR = 2\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralWithEnumsDeclaredUsingCallSyntax]\nfrom typing import Literal\nfrom enum import Enum\n\nA = Enum('A', 'FOO BAR')\nB = Enum('B', ['FOO', 'BAR'])\nC = Enum('C', [('FOO', 1), ('BAR', 2)])\nD = Enum('D', {'FOO': 1, 'BAR': 2})\n\na: Literal[A.FOO]\nb: Literal[B.FOO]\nc: Literal[C.FOO]\nd: Literal[D.FOO]\n\nreveal_type(a)  # N: Revealed type is \"Literal[__main__.A.FOO]\"\nreveal_type(b)  # N: Revealed type is \"Literal[__main__.B.FOO]\"\nreveal_type(c)  # N: Revealed type is \"Literal[__main__.C.FOO]\"\nreveal_type(d)  # N: Revealed type is \"Literal[__main__.D.FOO]\"\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testLiteralWithEnumsDerivedEnums]\nfrom typing import Literal\nfrom enum import Enum, IntEnum, IntFlag, Flag\n\ndef expects_int(x: int) -> None: pass\n\nclass A(Enum):\n    FOO = 1\n\nclass B(IntEnum):\n    FOO = 1\n\nclass C(IntFlag):\n    FOO = 1\n\nclass D(Flag):\n    FOO = 1\n\na: Literal[A.FOO]\nb: Literal[B.FOO]\nc: Literal[C.FOO]\nd: Literal[D.FOO]\n\nexpects_int(a)  # E: Argument 1 to \"expects_int\" has incompatible type \"Literal[A.FOO]\"; expected \"int\"\nexpects_int(b)\nexpects_int(c)\nexpects_int(d)  # E: Argument 1 to \"expects_int\" has incompatible type \"Literal[D.FOO]\"; expected \"int\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralWithEnumsAliases]\nfrom typing import Literal\nfrom enum import Enum\n\nclass Test(Enum):\n    FOO = 1\n    BAR = 2\n\nAlias = Test\n\nx: Literal[Alias.FOO]\nreveal_type(x)  # N: Revealed type is \"Literal[__main__.Test.FOO]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralUsingEnumAttributesInLiteralContexts]\nfrom typing import Final, Literal\nfrom enum import Enum\n\nclass Test1(Enum):\n    FOO = 1\n    BAR = 2\nTest2 = Enum('Test2', [('FOO', 1), ('BAR', 2)])\n\ndef expects_test1_foo(x: Literal[Test1.FOO]) -> None: ...\ndef expects_test2_foo(x: Literal[Test2.FOO]) -> None: ...\n\nexpects_test1_foo(Test1.FOO)\nexpects_test1_foo(Test1.BAR)  # E: Argument 1 to \"expects_test1_foo\" has incompatible type \"Literal[Test1.BAR]\"; expected \"Literal[Test1.FOO]\"\nexpects_test2_foo(Test2.FOO)\nexpects_test2_foo(Test2.BAR)  # E: Argument 1 to \"expects_test2_foo\" has incompatible type \"Literal[Test2.BAR]\"; expected \"Literal[Test2.FOO]\"\n\n# Make sure the two 'FOO's are not interchangeable\nexpects_test1_foo(Test2.FOO)  # E: Argument 1 to \"expects_test1_foo\" has incompatible type \"Literal[Test2.FOO]\"; expected \"Literal[Test1.FOO]\"\nexpects_test2_foo(Test1.FOO)  # E: Argument 1 to \"expects_test2_foo\" has incompatible type \"Literal[Test1.FOO]\"; expected \"Literal[Test2.FOO]\"\n\n# Make sure enums follow the same semantics as 'x = 1' vs 'x: Final = 1'\nvar1 = Test1.FOO\nfinal1: Final = Test1.FOO\nexpects_test1_foo(var1)       # E: Argument 1 to \"expects_test1_foo\" has incompatible type \"Test1\"; expected \"Literal[Test1.FOO]\"\nexpects_test1_foo(final1)\n\nvar2 = Test2.FOO\nfinal2: Final = Test2.FOO\nexpects_test2_foo(var2)       # E: Argument 1 to \"expects_test2_foo\" has incompatible type \"Test2\"; expected \"Literal[Test2.FOO]\"\nexpects_test2_foo(final2)\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralUsingEnumAttributeNamesInLiteralContexts]\nfrom typing import Final, Literal\nfrom enum import Enum\n\nclass Test1(Enum):\n    FOO = 1\n    BAR = 2\nTest2 = Enum('Test2', [('FOO', 1), ('BAR', 2)])\nTest3 = Enum('Test3', 'FOO BAR')\nTest4 = Enum('Test4', ['FOO', 'BAR'])\nTest5 = Enum('Test5', {'FOO': 1, 'BAR': 2})\n\ndef expects_foo(x: Literal['FOO']) -> None: ...\n\nexpects_foo(Test1.FOO.name)\nexpects_foo(Test2.FOO.name)\nexpects_foo(Test3.FOO.name)\nexpects_foo(Test4.FOO.name)\nexpects_foo(Test5.FOO.name)\n\nexpects_foo(Test1.BAR.name)  # E: Argument 1 to \"expects_foo\" has incompatible type \"Literal['BAR']\"; expected \"Literal['FOO']\"\nexpects_foo(Test2.BAR.name)  # E: Argument 1 to \"expects_foo\" has incompatible type \"Literal['BAR']\"; expected \"Literal['FOO']\"\nexpects_foo(Test3.BAR.name)  # E: Argument 1 to \"expects_foo\" has incompatible type \"Literal['BAR']\"; expected \"Literal['FOO']\"\nexpects_foo(Test4.BAR.name)  # E: Argument 1 to \"expects_foo\" has incompatible type \"Literal['BAR']\"; expected \"Literal['FOO']\"\nexpects_foo(Test5.BAR.name)  # E: Argument 1 to \"expects_foo\" has incompatible type \"Literal['BAR']\"; expected \"Literal['FOO']\"\n\nreveal_type(Test1.FOO.name)  # N: Revealed type is \"Literal['FOO']?\"\nreveal_type(Test2.FOO.name)  # N: Revealed type is \"Literal['FOO']?\"\nreveal_type(Test3.FOO.name)  # N: Revealed type is \"Literal['FOO']?\"\nreveal_type(Test4.FOO.name)  # N: Revealed type is \"Literal['FOO']?\"\nreveal_type(Test5.FOO.name)  # N: Revealed type is \"Literal['FOO']?\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testLiteralBinderLastValueErased]\n# mypy: strict-equality\nfrom typing import Literal\n\ndef takes_three(x: Literal[3]) -> None: ...\nx: object\nx = 3\n\ntakes_three(x)  # E: Argument 1 to \"takes_three\" has incompatible type \"int\"; expected \"Literal[3]\"\nif x == 2:  # OK\n    ...\n[builtins fixtures/bool.pyi]\n\n[case testLiteralBinderLastValueErasedPartialTypes]\n# mypy: strict-equality\n\ndef test() -> None:\n    x = None\n    if bool():\n        x = 1\n\n    if x == 2:  # OK\n        ...\n[builtins fixtures/bool.pyi]\n\n[case testUnaryOpLiteral]\nfrom typing import Literal\n\na: Literal[-2] = -2\nb: Literal[-1] = -1\nc: Literal[0] = 0\nd: Literal[1] = 1\ne: Literal[2] = 2\nf: Literal[+1] = 1\ng: Literal[+2] = 2\nh: Literal[1] = +1\ni: Literal[+2] = 2\nj: Literal[+3] = +3\n\nx: Literal[+True] = True  # E: Invalid type: Literal[...] cannot contain arbitrary expressions\ny: Literal[-True] = -1  # E: Invalid type: Literal[...] cannot contain arbitrary expressions\nz: Literal[~0] = 0  # E: Invalid type: Literal[...] cannot contain arbitrary expressions\n[out]\n[builtins fixtures/ops.pyi]\n\n[case testNegativeIntLiteralWithFinal]\nfrom typing import Final, Literal\n\nONE: Final = 1\nx: Literal[-1] = -ONE\ny: Literal[+1] = +ONE\n\nTWO: Final = 2\nTHREE: Final = 3\n\nerr_code = -TWO\nif bool():\n    err_code = -THREE\n[builtins fixtures/ops.pyi]\n\n[case testAliasForEnumTypeAsLiteral]\nfrom typing import Literal\nfrom enum import Enum\n\nclass Foo(Enum):\n    A = 1\n\nF = Foo\n\nx: Literal[Foo.A]\ny: Literal[F.A]\nreveal_type(x)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nreveal_type(y)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralUnionEnumAliasAssignable]\nfrom enum import Enum\nfrom typing import Literal, Union\n\nclass E(Enum):\n    A = 'a'\n    B = 'b'\n    C = 'c'\n\nA = Literal[E.A]\nB = Literal[E.B, E.C]\n\ndef f(x: Union[A, B]) -> None: ...\ndef f2(x: Union[A, Literal[E.B, E.C]]) -> None: ...\ndef f3(x: Union[Literal[E.A], B]) -> None: ...\n\ndef main(x: E) -> None:\n    f(x)\n    f2(x)\n    f3(x)\n[builtins fixtures/tuple.pyi]\n\n[case testStrictEqualityLiteralTrueVsFalse]\n# mypy: strict-equality\n\nclass C:\n    a = True\n\n    def update(self) -> None:\n        self.a = False\n\nc = C()\nassert c.a is True\nc.update()\nassert c.a is False\n[builtins fixtures/bool.pyi]\n\n[case testConditionalBoolLiteralUnionNarrowing]\n# flags: --warn-unreachable\nfrom typing import Literal, Union\n\nclass Truth:\n    def __bool__(self) -> Literal[True]: ...\n\nclass AlsoTruth:\n    def __bool__(self) -> Literal[True]: ...\n\nclass Lie:\n    def __bool__(self) -> Literal[False]: ...\n\nclass AnyAnswer:\n    def __bool__(self) -> bool: ...\n\nclass NoAnswerSpecified:\n    pass\n\nx: Union[Truth, Lie]\n\nif x:\n    reveal_type(x)  # N: Revealed type is \"__main__.Truth\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Lie\"\n\nif not x:\n    reveal_type(x)  # N: Revealed type is \"__main__.Lie\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Truth\"\n\ny: Union[Truth, AlsoTruth, Lie]\n\nif y:\n    reveal_type(y)  # N: Revealed type is \"__main__.Truth | __main__.AlsoTruth\"\nelse:\n    reveal_type(y)  # N: Revealed type is \"__main__.Lie\"\n\nz: Union[Truth, AnyAnswer]\n\nif z:\n    reveal_type(z)  # N: Revealed type is \"__main__.Truth | __main__.AnyAnswer\"\nelse:\n    reveal_type(z)  # N: Revealed type is \"__main__.AnyAnswer\"\n\nq: Union[Truth, NoAnswerSpecified]\n\nif q:\n    reveal_type(q)  # N: Revealed type is \"__main__.Truth | __main__.NoAnswerSpecified\"\nelse:\n    reveal_type(q)  # N: Revealed type is \"__main__.NoAnswerSpecified\"\n\nw: Union[Truth, AlsoTruth]\n\nif w:\n    reveal_type(w)  # N: Revealed type is \"__main__.Truth | __main__.AlsoTruth\"\nelse:\n    reveal_type(w)  # E: Statement is unreachable\n\n[builtins fixtures/bool.pyi]\n\n[case testLiteralAndInstanceSubtyping]\n# https://github.com/python/mypy/issues/7399\n# https://github.com/python/mypy/issues/11232\nfrom typing import Final, Literal, Tuple, Union\n\nx: bool\n\ndef f() -> Union[Tuple[Literal[True], int], Tuple[Literal[False], str]]:\n    if x:\n        return (True, 5)\n    else:\n        return (False, 'oops')\n\nreveal_type(f())  # N: Revealed type is \"tuple[Literal[True], builtins.int] | tuple[Literal[False], builtins.str]\"\n\ndef does_work() -> Tuple[Literal[1]]:\n    x: Final = (1,)\n    return x\n\ndef also_works() -> Tuple[Literal[1]]:\n    x: Tuple[Literal[1]] = (1,)\n    return x\n\ndef invalid_literal_value() -> Tuple[Literal[1]]:\n    x: Final = (2,)\n    return x  # E: Incompatible return value type (got \"tuple[int]\", expected \"tuple[Literal[1]]\")\n\ndef invalid_literal_type() -> Tuple[Literal[1]]:\n    x: Final = (True,)\n    return x  # E: Incompatible return value type (got \"tuple[bool]\", expected \"tuple[Literal[1]]\")\n\ndef incorrect_return1() -> Union[Tuple[Literal[True], int], Tuple[Literal[False], str]]:\n    if x:\n        return (False, 5)  # E: Incompatible return value type (got \"tuple[bool, int]\", expected \"tuple[Literal[True], int] | tuple[Literal[False], str]\")\n    else:\n        return (True, 'oops')  # E: Incompatible return value type (got \"tuple[bool, str]\", expected \"tuple[Literal[True], int] | tuple[Literal[False], str]\")\n\ndef incorrect_return2() -> Union[Tuple[Literal[True], int], Tuple[Literal[False], str]]:\n    if x:\n        return (bool(), 5)  # E: Incompatible return value type (got \"tuple[bool, int]\", expected \"tuple[Literal[True], int] | tuple[Literal[False], str]\")\n    else:\n        return (bool(), 'oops')  # E: Incompatible return value type (got \"tuple[bool, str]\", expected \"tuple[Literal[True], int] | tuple[Literal[False], str]\")\n[builtins fixtures/bool.pyi]\n\n[case testLiteralSubtypeContext]\nfrom typing import Literal\n\nclass A:\n    foo: Literal['bar', 'spam']\nclass B(A):\n    foo = 'spam'\n\nreveal_type(B().foo)  # N: Revealed type is \"Literal['spam']\"\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralSubtypeContextNested]\nfrom typing import List, Literal\n\nclass A:\n    foo: List[Literal['bar', 'spam']]\nclass B(A):\n    foo = ['spam']\n\nreveal_type(B().foo)  # N: Revealed type is \"builtins.list[Literal['bar'] | Literal['spam']]\"\n[builtins fixtures/tuple.pyi]\n\n[case testLiteralSubtypeContextGeneric]\nfrom typing import Generic, List, Literal, TypeVar\n\nT = TypeVar(\"T\", bound=str)\n\nclass B(Generic[T]):\n    collection: List[T]\n    word: T\n\nclass C(B[Literal[\"word\"]]):\n   collection = [\"word\"]\n   word = \"word\"\n\nreveal_type(C().collection)  # N: Revealed type is \"builtins.list[Literal['word']]\"\nreveal_type(C().word)  # N: Revealed type is \"Literal['word']\"\n[builtins fixtures/tuple.pyi]\n\n[case testStringIntUnionTernary]\n# https://github.com/python/mypy/issues/19534\ndef test(b: bool) -> None:\n    l = 1 if b else \"a\"\n    reveal_type(l)  # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testListComprehensionTernary]\n# https://github.com/python/mypy/issues/19534\ndef test(b: bool) -> None:\n    l = [1] if b else [\"a\"]\n    reveal_type(l)  # N: Revealed type is \"builtins.list[builtins.int] | builtins.list[builtins.str]\"\n[builtins fixtures/list.pyi]\n\n[case testLambdaTernary]\nfrom typing import TypeVar, Union, Callable, reveal_type\n\nNOOP = lambda: None\nclass A: pass\nclass B:\n    attr: Union[A, None]\n\ndef test_static(x: Union[A, None]) -> None:\n    def foo(t: A) -> None: ...\n\n    l1: Callable[[], object] = (lambda: foo(x)) if x is not None else NOOP\n    r1: Callable[[], object] = NOOP if x is None else (lambda: foo(x))\n    l2 = (lambda: foo(x)) if x is not None else NOOP\n    r2 = NOOP if x is None else (lambda: foo(x))\n    reveal_type(l2)  # N: Revealed type is \"def ()\"\n    reveal_type(r2)  # N: Revealed type is \"def ()\"\n\ndef test_generic(x: Union[A, None]) -> None:\n    T = TypeVar(\"T\")\n    def bar(t: T) -> T: return t\n\n    l1: Callable[[], None] = (lambda: bar(x)) if x is None else NOOP\n    r1: Callable[[], None] = NOOP if x is not None else (lambda: bar(x))\n    l2 = (lambda: bar(x)) if x is None else NOOP\n    r2 = NOOP if x is not None else (lambda: bar(x))\n    reveal_type(l2)  # N: Revealed type is \"def ()\"\n    reveal_type(r2)  # N: Revealed type is \"def ()\"\n\n\n[case testLambdaTernaryIndirectAttribute]\n# fails due to binder issue inside `check_func_def`\n# https://github.com/python/mypy/issues/19561\nfrom typing import TypeVar, Union, Callable, reveal_type\n\nNOOP = lambda: None\nclass A: pass\nclass B:\n    attr: Union[A, None]\n\ndef test_static_with_attr(x: B) -> None:\n    def foo(t: A) -> None: ...\n\n    l1: Callable[[], None] = (lambda: foo(x.attr)) if x.attr is not None else NOOP  # E: Argument 1 to \"foo\" has incompatible type \"A | None\"; expected \"A\"\n    r1: Callable[[], None] = NOOP if x.attr is None else (lambda: foo(x.attr))  # E: Argument 1 to \"foo\" has incompatible type \"A | None\"; expected \"A\"\n    l2 = (lambda: foo(x.attr)) if x.attr is not None else NOOP  # E: Argument 1 to \"foo\" has incompatible type \"A | None\"; expected \"A\"\n    r2 = NOOP if x.attr is None else (lambda: foo(x.attr))  # E: Argument 1 to \"foo\" has incompatible type \"A | None\"; expected \"A\"\n    reveal_type(l2)  # N: Revealed type is \"def ()\"\n    reveal_type(r2)  # N: Revealed type is \"def ()\"\n\ndef test_generic_with_attr(x: B) -> None:\n    T = TypeVar(\"T\")\n    def bar(t: T) -> T: return t\n\n    l1: Callable[[], None] = (lambda: bar(x.attr)) if x.attr is None else NOOP  # E: Incompatible types in assignment (expression has type \"Callable[[], A | None]\", variable has type \"Callable[[], None]\")\n    r1: Callable[[], None] = NOOP if x.attr is not None else (lambda: bar(x.attr))  # E: Incompatible types in assignment (expression has type \"Callable[[], A | None]\", variable has type \"Callable[[], None]\")\n    l2 = (lambda: bar(x.attr)) if x.attr is None else NOOP\n    r2 = NOOP if x.attr is not None else (lambda: bar(x.attr))\n    reveal_type(l2)  # N: Revealed type is \"def () -> __main__.A | None\"\n    reveal_type(r2)  # N: Revealed type is \"def () -> __main__.A | None\"\n\n[case testLambdaTernaryDoubleIndirectAttribute]\n# fails due to binder issue inside `check_func_def`\n# https://github.com/python/mypy/issues/19561\nfrom typing import TypeVar, Union, Callable, reveal_type\n\nNOOP = lambda: None\nclass A: pass\nclass B:\n    attr: Union[A, None]\nclass C:\n    attr: B\n\ndef test_static_with_attr(x: C) -> None:\n    def foo(t: A) -> None: ...\n\n    l1: Callable[[], None] = (lambda: foo(x.attr.attr)) if x.attr.attr is not None else NOOP  # E: Argument 1 to \"foo\" has incompatible type \"A | None\"; expected \"A\"\n    r1: Callable[[], None] = NOOP if x.attr.attr is None else (lambda: foo(x.attr.attr))  # E: Argument 1 to \"foo\" has incompatible type \"A | None\"; expected \"A\"\n    l2 = (lambda: foo(x.attr.attr)) if x.attr.attr is not None else NOOP  # E: Argument 1 to \"foo\" has incompatible type \"A | None\"; expected \"A\"\n    r2 = NOOP if x.attr.attr is None else (lambda: foo(x.attr.attr))  # E: Argument 1 to \"foo\" has incompatible type \"A | None\"; expected \"A\"\n    reveal_type(l2)  # N: Revealed type is \"def ()\"\n    reveal_type(r2)  # N: Revealed type is \"def ()\"\n\ndef test_generic_with_attr(x: C) -> None:\n    T = TypeVar(\"T\")\n    def bar(t: T) -> T: return t\n\n    l1: Callable[[], None] = (lambda: bar(x.attr.attr)) if x.attr.attr is None else NOOP  # E: Incompatible types in assignment (expression has type \"Callable[[], A | None]\", variable has type \"Callable[[], None]\")\n    r1: Callable[[], None] = NOOP if x.attr.attr is not None else (lambda: bar(x.attr.attr))  # E: Incompatible types in assignment (expression has type \"Callable[[], A | None]\", variable has type \"Callable[[], None]\")\n    l2 = (lambda: bar(x.attr.attr)) if x.attr.attr is None else NOOP\n    r2 = NOOP if x.attr.attr is not None else (lambda: bar(x.attr.attr))\n    reveal_type(l2)  # N: Revealed type is \"def () -> __main__.A | None\"\n    reveal_type(r2)  # N: Revealed type is \"def () -> __main__.A | None\"\n\n\n[case testLiteralTernaryUnionNarrowing]\nfrom typing import Literal, Optional\n\nSEP = Literal[\"a\", \"b\"]\n\nclass Base:\n    def feed_data(\n        self,\n        sep: SEP,\n    ) -> int:\n        return 0\n\nclass C(Base):\n    def feed_data(\n        self,\n        sep: Optional[SEP] = None,\n    ) -> int:\n        if sep is None:\n            sep = \"a\" if int() else \"b\"\n            reveal_type(sep)  # N: Revealed type is \"Literal['a'] | Literal['b']\"\n        return super().feed_data(sep)\n[builtins fixtures/primitives.pyi]\n\n[case testLiteralInsideAType]\nfrom typing import Literal, Type, Union\n\nx: Type[Literal[1]]  # E: Type[...] can't contain \"Literal[...]\"\ny: Type[Union[Literal[1], Literal[2]]]  # E: Type[...] can't contain \"Union[Literal[...], Literal[...]]\"\nz: Type[Literal[1, 2]]  # E: Type[...] can't contain \"Union[Literal[...], Literal[...]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testJoinLiteralAndInstance]\nfrom typing import Generic, TypeVar, Literal\n\nT = TypeVar(\"T\")\n\nclass A(Generic[T]): ...\n\ndef f(a: A[T], t: T) -> T: ...\ndef g(a: T, t: A[T]) -> T: ...\n\ndef check(obj: A[Literal[1]]) -> None:\n    reveal_type(f(obj, 1))  # N: Revealed type is \"Literal[1]\"\n    reveal_type(f(obj, ''))  # E: Cannot infer value of type parameter \"T\" of \"f\" \\\n                             # N: Revealed type is \"Any\"\n    reveal_type(g(1, obj))  # N: Revealed type is \"Literal[1]\"\n    reveal_type(g('', obj))  # E: Cannot infer value of type parameter \"T\" of \"g\" \\\n                             # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testEnumLiteralIsNotIntLiteral]\n# See https://discuss.python.org/t/amend-pep-586-to-make-enum-values-subtypes-of-literal/59456/4\nfrom enum import IntEnum\nfrom typing import Literal\n\nclass X(IntEnum):\n    a = 1\n\n    def __add__(self, value: int, /) -> int:\n        return self.value + value + 42\n\n    def __eq__(self, other: object):\n        return False\n\n    def __bool__(self) -> bool:\n        return False\n\ndef f(x: Literal[1]):\n    # 44 at runtime if you were to allow passing X.a\n    reveal_type(x + 1)  # N: Revealed type is \"builtins.int\"\n\ndef g(x: Literal[1, 2]):\n    # false if you were to allow passing X.a\n    if x == 1:\n        reveal_type(x)  # N: Revealed type is \"Literal[1]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"Literal[2]\"\n\ndef h(x: Literal[0, 1]):\n    # false if you were to allow passing X.a\n    if x:\n        reveal_type(x)  # N: Revealed type is \"Literal[1]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"Literal[0]\"\n\nf(X.a)  # E: Argument 1 to \"f\" has incompatible type \"Literal[X.a]\"; expected \"Literal[1]\"\ng(X.a)  # E: Argument 1 to \"g\" has incompatible type \"Literal[X.a]\"; expected \"Literal[1, 2]\"\nh(X.a)  # E: Argument 1 to \"h\" has incompatible type \"Literal[X.a]\"; expected \"Literal[0, 1]\"\n\nf(X.a.value)\ng(X.a.value)\nh(X.a.value)\n[builtins fixtures/primitives.pyi]\n"
  },
  {
    "path": "test-data/unit/check-lowercase.test",
    "content": "[case testTupleLowercase]\nx = (3,)\nx = 3 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"tuple[int]\")\n[builtins fixtures/tuple.pyi]\n\n[case testListLowercase]\nx = [3]\nx = 3  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"list[int]\")\n\n[case testDictLowercase]\nx = {\"key\": \"value\"}\nx = 3  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"dict[str, str]\")\n\n[case testSetLowercase]\nx = {3}\nx = 3  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"set[int]\")\n[builtins fixtures/set.pyi]\n\n[case testTypeLowercase]\nx: type[type]\ny: int\n\ny = x  # E: Incompatible types in assignment (expression has type \"type[type]\", variable has type \"int\")\n\n[case testLowercaseTypeAnnotationHint]\nx = []  # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\ny = {}  # E: Need type annotation for \"y\" (hint: \"y: dict[<type>, <type>] = ...\")\nz = set()  # E: Need type annotation for \"z\" (hint: \"z: set[<type>] = ...\")\n[builtins fixtures/primitives.pyi]\n\n[case testLowercaseRevealTypeType]\ndef f(t: type[int]) -> None:\n    reveal_type(t)  # N: Revealed type is \"type[builtins.int]\"\nreveal_type(f)  # N: Revealed type is \"def (t: type[builtins.int])\"\n[builtins fixtures/primitives.pyi]\n"
  },
  {
    "path": "test-data/unit/check-modules-case.test",
    "content": "-- Type checker test cases dealing with modules and imports on case-insensitive filesystems.\n\n[case testCaseSensitivityDir]\n# flags: --no-namespace-packages\nfrom a import B  # E: Module \"a\" has no attribute \"B\"\n\n[file a/__init__.py]\n[file a/b/__init__.py]\n\n[case testCaseSensitivityDirNamespacePackages]\n# flags: --namespace-packages\nfrom a import B  # E: Module \"a\" has no attribute \"B\"\n\n[file a/__init__.py]\n[file a/b/__init__.py]\n\n[case testCaseInsensitivityDir]\n# flags: --config-file tmp/mypy.ini\n\nfrom a import B  # E: Module \"a\" has no attribute \"B\"\nfrom other import x\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[file a/__init__.py]\n[file a/b/__init__.py]\n[file FuNkY_CaSe/other.py]\nx = 1\n\n[file mypy.ini]\n\\[mypy]\nmypy_path = tmp/funky_case\n\n\n[case testCaseInsensitivityDirPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\n\nfrom a import B  # E: Module \"a\" has no attribute \"B\"\nfrom other import x\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[file a/__init__.py]\n\n[file a/b/__init__.py]\n\n[file FuNkY_CaSe/other.py]\nx = 1\n\n[file pyproject.toml]\n\\[tool.mypy]\nmypy_path = \"tmp/funky_case\"\n\n\n[case testPreferPackageOverFileCase]\n# flags: --config-file tmp/mypy.ini\nimport a\n[file funky/a.py]\n/  # Deliberate syntax error, this file should not be parsed.\n[file FuNkY/a/__init__.py]\npass\n\n[file mypy.ini]\n\\[mypy]\nmypy_path = tmp/funky\n\n\n[case testPreferPackageOverFileCasePyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport a\n\n[file funky/a.py]\n/  # Deliberate syntax error, this file should not be parsed.\n\n[file FuNkY/a/__init__.py]\npass\n\n[file pyproject.toml]\n\\[tool.mypy]\nmypy_path = \"tmp/funky\"\n\n\n[case testNotPreferPackageOverFileCase]\nimport a\n[file a.py]\n'no'()  # E: \"str\" not callable\n[file A/__init__.py]\n/  # Deliberate syntax error, this file should not be parsed.\n\n[case testNamespacePackagePickFirstOnMypyPathCase]\n# flags: --namespace-packages --config-file tmp/mypy.ini\nfrom foo.bar import x\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[file XX/foo/bar.py]\nx = 0\n[file yy/foo/bar.py]\nx = ''\n[file mypy.ini]\n\\[mypy]\nmypy_path = tmp/xx, tmp/yy\n\n\n[case testNamespacePackagePickFirstOnMypyPathCasePyProjectTOML]\n# flags: --namespace-packages --config-file tmp/pyproject.toml\nfrom foo.bar import x\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[file XX/foo/bar.py]\nx = 0\n\n[file yy/foo/bar.py]\nx = ''\n\n[file pyproject.toml]\n\\[tool.mypy]\nmypy_path = [\"tmp/xx\", \"tmp/yy\"]\n\n\n[case testClassicPackageInsideNamespacePackageCase]\n# flags: --namespace-packages --config-file tmp/mypy.ini\nfrom foo.bar.baz.boo import x\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[file xx/foo/bar/baz/boo.py]\nx = ''\n[file xx/foo/bar/baz/__init__.py]\n[file yy/foo/bar/baz/boo.py]\nx = 0\n[file yy/foo/bar/__init__.py]\n\n[file mypy.ini]\n\\[mypy]\nmypy_path = TmP/xX, TmP/yY\n\n\n[case testClassicPackageInsideNamespacePackageCasePyProjectTOML]\n# flags: --namespace-packages --config-file tmp/pyproject.toml\nfrom foo.bar.baz.boo import x\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[file xx/foo/bar/baz/boo.py]\nx = ''\n\n[file xx/foo/bar/baz/__init__.py]\n\n[file yy/foo/bar/baz/boo.py]\nx = 0\n\n[file yy/foo/bar/__init__.py]\n\n[file pyproject.toml]\n\\[tool.mypy]\nmypy_path = [\"TmP/xX\", \"TmP/yY\"]\n"
  },
  {
    "path": "test-data/unit/check-modules-fast.test",
    "content": "-- Type checker test cases dealing with module lookup edge cases\n-- to ensure that --fast-module-lookup matches regular lookup behavior\n\n[case testModuleLookup]\n# flags: --fast-module-lookup\nimport m\nreveal_type(m.a)  # N: Revealed type is \"m.A\"\n\n[file m.py]\nclass A: pass\na = A()\n\n[case testModuleLookupStub]\n# flags: --fast-module-lookup\nimport m\nreveal_type(m.a)  # N: Revealed type is \"m.A\"\n\n[file m.pyi]\nclass A: pass\na = A()\n\n[case testModuleLookupFromImport]\n# flags: --fast-module-lookup\nfrom m import a\nreveal_type(a)  # N: Revealed type is \"m.A\"\n\n[file m.py]\nclass A: pass\na = A()\n\n[case testModuleLookupStubFromImport]\n# flags: --fast-module-lookup\nfrom m import a\nreveal_type(a)  # N: Revealed type is \"m.A\"\n\n[file m.pyi]\nclass A: pass\na = A()\n\n\n[case testModuleLookupWeird]\n# flags: --fast-module-lookup\nfrom m import a\nreveal_type(a)  # N: Revealed type is \"builtins.object\"\nreveal_type(a.b)  # N: Revealed type is \"m.a.B\"\n\n[file m.py]\nclass A: pass\na = A()\n\n[file m/__init__.py]\n[file m/a.py]\nclass B: pass\nb = B()\n\n\n[case testModuleLookupWeird2]\n# flags: --fast-module-lookup\nfrom m.a import b\nreveal_type(b)  # N: Revealed type is \"m.a.B\"\n\n[file m.py]\nclass A: pass\na = A()\n\n[file m/__init__.py]\n[file m/a.py]\nclass B: pass\nb = B()\n\n\n[case testModuleLookupWeird3]\n# flags: --fast-module-lookup\nfrom m.a import b\nreveal_type(b)  # N: Revealed type is \"m.a.B\"\n\n[file m.py]\nclass A: pass\na = A()\n[file m/__init__.py]\nclass B: pass\na = B()\n[file m/a.py]\nclass B: pass\nb = B()\n\n\n[case testModuleLookupWeird4]\n# flags: --fast-module-lookup\nimport m.a\nm.a.b  # E: \"str\" has no attribute \"b\"\n\n[file m.py]\nclass A: pass\na = A()\n[file m/__init__.py]\nclass B: pass\na = 'foo'\nb = B()\n[file m/a.py]\nclass C: pass\nb = C()\n\n\n[case testModuleLookupWeird5]\n# flags: --fast-module-lookup\nimport m.a as ma\nreveal_type(ma.b)  # N: Revealed type is \"m.a.C\"\n\n[file m.py]\nclass A: pass\na = A()\n[file m/__init__.py]\nclass B: pass\na = 'foo'\nb = B()\n[file m/a.py]\nclass C: pass\nb = C()\n\n\n[case testModuleLookupWeird6]\n# flags: --fast-module-lookup\nfrom m.a import b\nreveal_type(b)  # N: Revealed type is \"m.a.C\"\n\n[file m.py]\nclass A: pass\na = A()\n[file m/__init__.py]\nclass B: pass\na = 'foo'\nb = B()\n[file m/a.py]\nclass C: pass\nb = C()\n"
  },
  {
    "path": "test-data/unit/check-modules.test",
    "content": "-- Type checker test cases dealing with modules and imports.\n-- Towards the end there are tests for PEP 420 (namespace packages, i.e. __init__.py-less packages).\n\n[case testAccessImportedDefinitions0]\nimport m\nimport typing\nm.f()           # E: Missing positional argument \"a\" in call to \"f\"\nm.f(object())   # E: Argument 1 to \"f\" has incompatible type \"object\"; expected \"A\"\nm.x = object()  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"A\")\nm.f(m.A())\nm.x = m.A()\n[file m.py]\nclass A: pass\ndef f(a: A) -> None: pass\nx = A()\n\n[case testAccessImportedDefinitions1]\nimport m\nimport typing\nm.f(object()) # E: Argument 1 to \"f\" has incompatible type \"object\"; expected \"A\"\nm.f(m.A())\n[file m.py]\nclass A: pass\ndef f(a: A) -> None: pass\n\n[case testAccessImportedDefinitions2]\nfrom m import f, A\nimport typing\nf(object()) # E: Argument 1 to \"f\" has incompatible type \"object\"; expected \"A\"\nf(A())\n[file m.py]\nclass A: pass\ndef f(a: A) -> None: pass\n\n[case testImportedExceptionType]\nimport m\nimport typing\ntry:\n    pass\nexcept m.Err:\n    pass\nexcept m.Bad: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n    pass\n[file m.py]\nclass Err(BaseException): pass\nclass Bad: pass\n[builtins fixtures/exception.pyi]\n\n[case testImportedExceptionType2]\nfrom m import Err, Bad\nimport typing\ntry:\n    pass\nexcept Err:\n    pass\nexcept Bad: # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n    pass\n[file m.py]\nclass Err(BaseException): pass\nclass Bad: pass\n[builtins fixtures/exception.pyi]\n\n[case testImportWithinBlock]\nimport typing\nif 1:\n    import m\n    m.a = m.b   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    m.a = m.a\n    m.f()\n    m.f(m.a)    # E: Too many arguments for \"f\"\n    m.a = m.A()\n    m.a = m.B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[file m.py]\nclass A: pass\nclass B: pass\na = A()\nb = B()\ndef f() -> None: pass\n\n[case testImportWithinFunction]\nimport typing\ndef f() -> None:\n    from m import a, b, f, A, B\n    if int():\n        a = b \\\n            # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n        a = a\n        f()\n        f(a)    # E: Too many arguments for \"f\"\n        a = A()\n        a = B() \\\n            # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[file m.py]\nclass A: pass\nclass B: pass\na = A()\nb = B()\ndef f() -> None: pass\n[out]\n\n[case testImportWithinMethod]\nimport typing\nclass C:\n    def f(self) -> None:\n        from m import *\n        if int():\n            a = b   # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n            a = a\n            f()\n            f(a)    # E: Too many arguments for \"f\"\n            a = A()\n            a = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[file m.py]\nclass A: pass\nclass B: pass\na = A()\nb = B()\ndef f() -> None: pass\n[out]\n\n[case testImportWithinClassBody]\nimport typing\nclass C:\n    import m\n    m.f()\n    m.f(C) # E: Too many arguments for \"f\"\n[file m.py]\ndef f() -> None: pass\n[out]\n\n[case testImportWithinClassBody2]\nimport typing\nclass C:\n    from m import f  # E: Unsupported class scoped import\n    f()\n    # ideally, the following should error:\n    f(C)\n[file m.py]\ndef f() -> None: pass\n[out]\n\n[case testImportWithStub]\nimport _m\n_m.f(\"hola\")\n[file _m.pyi]\ndef f(c:str) -> None: pass\n[out]\n\n[case testImportWithStubIncompatibleType]\nimport _m\n_m.f(\"hola\")\n_m.f(12)  # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n[file _m.py]\ndef f(c):\n  print(c)\n[file _m.pyi]\ndef f(c:str) -> None: pass\n\n[case testInvalidOperationsOnModules]\nimport m\nimport typing\n\nclass A: pass\nm()      # E: Module not callable\na = m # type: A  # E: Incompatible types in assignment (expression has type Module, variable has type \"A\")\nm + None # E: Unsupported left operand type for + (Module)\n[file m.py]\n[builtins fixtures/module.pyi]\n\n[case testNameDefinedInDifferentModule]\nimport m, n\nimport typing\nm.x # E: Module has no attribute \"x\"\n[file m.py]\ny = object()\n[file n.py]\nx = object()\n[builtins fixtures/module.pyi]\n\n[case testChainedAssignmentAndImports]\nimport m\n\ni: int\ns: str\nif int():\n    i = m.x\nif int():\n    i = m.y\nif int():\n    s = m.x # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nif int():\n    s = m.y # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[file m.py]\nx = y = 1\n[builtins fixtures/primitives.pyi]\n\n[case testConditionalFunctionDefinitionAndImports]\nimport m\nimport typing\nm.f(1)\nm.f('x') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n[file m.py]\nx = object()\nif x:\n    def f(x: int) -> None: pass\nelse:\n    def f(x: int) -> None: pass\n\n[case testTypeCheckWithUnknownModule]\nimport nonexistent\nNone + ''\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"nonexistent\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:2: error: Unsupported left operand type for + (\"None\")\n\n[case testTypeCheckWithUnknownModule2]\nimport m, nonexistent\nNone + ''\nm.x = 1\nm.x = ''\n[file m.py]\nx = 1\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"nonexistent\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:2: error: Unsupported left operand type for + (\"None\")\nmain:4: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testTypeCheckWithUnknownModule3]\nimport nonexistent, m\nNone + ''\nm.x = 1\nm.x = ''\n[file m.py]\nx = 1\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"nonexistent\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:2: error: Unsupported left operand type for + (\"None\")\nmain:4: error: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testTypeCheckWithUnknownModule4]\nimport nonexistent, another\nNone + ''\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"nonexistent\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:1: error: Cannot find implementation or library stub for module named \"another\"\nmain:2: error: Unsupported left operand type for + (\"None\")\n\n[case testTypeCheckWithUnknownModule5]\nimport nonexistent as x\nNone + ''\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"nonexistent\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:2: error: Unsupported left operand type for + (\"None\")\n\n[case testTypeCheckWithUnknownModuleUsingFromImport]\nfrom nonexistent import x\nNone + ''\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"nonexistent\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:2: error: Unsupported left operand type for + (\"None\")\n\n[case testTypeCheckWithUnknownModuleUsingImportStar]\nfrom nonexistent import *\nNone + ''\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"nonexistent\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:2: error: Unsupported left operand type for + (\"None\")\n\n[case testAccessingUnknownModule]\nimport xyz\nxyz.foo()\nxyz()\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"xyz\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testAccessingUnknownModule2]\nimport xyz, bar\nxyz.foo()\nbar()\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"xyz\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:1: error: Cannot find implementation or library stub for module named \"bar\"\n\n[case testAccessingUnknownModule3]\nimport xyz as z\nxyz.foo()\nz()\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"xyz\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:2: error: Name \"xyz\" is not defined\n\n[case testAccessingNameImportedFromUnknownModule]\nfrom xyz import y, z\ny.foo()\nz()\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"xyz\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testAccessingNameImportedFromUnknownModule2]\nfrom xyz import *\ny\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"xyz\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:2: error: Name \"y\" is not defined\n\n[case testAccessingNameImportedFromUnknownModule3]\nfrom xyz import y as z\ny\nz\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"xyz\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:2: error: Name \"y\" is not defined\n\n[case testUnknownModuleRedefinition]\n# Error messages differ with the new analyzer\n\nimport xab  # E: Cannot find implementation or library stub for module named \"xab\"  # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\ndef xab(): pass  # E: Name \"xab\" already defined (possibly by an import)\n\n[case testAccessingUnknownModuleFromOtherModule]\nimport x\nx.nonexistent.foo\nx.z\n[file x.py]\nimport nonexistent\n[builtins fixtures/module.pyi]\n[out]\ntmp/x.py:1: error: Cannot find implementation or library stub for module named \"nonexistent\"\ntmp/x.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:3: error: Module has no attribute \"z\"\n\n[case testUnknownModuleImportedWithinFunction]\ndef f():\n    import foobar\ndef foobar(): pass\nfoobar('')\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"foobar\"\nmain:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:4: error: Too many arguments for \"foobar\"\n\n[case testUnknownModuleImportedWithinFunction2]\ndef f():\n    from foobar import x\ndef x(): pass\nx('')\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"foobar\"\nmain:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:4: error: Too many arguments for \"x\"\n\n[case testRelativeImports]\nimport typing\nimport m.a\nm.a.x = m.a.y # Error\n[file m/__init__.py]\n[file m/a.py]\nimport typing\nfrom .b import A, B, x, y\nz = x\nif int():\n    z = y # Error\n[file m/b.py]\nimport typing\nclass A: pass\nclass B: pass\nx = A()\ny = B()\n[out]\ntmp/m/a.py:5: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nmain:3: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\n[case testRelativeImports2]\nimport typing\nimport m.a\nm.a.x = m.a.y # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n[file m/__init__.py]\n[file m/a.py]\nimport typing\nfrom .b import A, B, x, y\n[file m/b.py]\nimport typing\nclass A: pass\nclass B: pass\nx = A()\ny = B()\n\n[case testExportedValuesInImportAll]\nimport typing\nfrom m import *\n_ = a\n_ = b\n_ = c\n_ = d\n_ = e  # E: Name \"e\" is not defined\n_ = f\n_ = _g # E: Name \"_g\" is not defined\n[file m.py]\n__all__ = ['a']\n__all__ += ('b',)\n__all__.append('c')\n__all__.extend(('d', 'e', 'f'))\n__all__.remove('e')\n\na = b = c = d = e = f = _g = 1\n[builtins fixtures/module_all.pyi]\n\n[case testAllMustBeSequenceStr]\nimport typing\n__all__ = [1, 2, 3]\n[builtins fixtures/module_all.pyi]\n[out]\nmain:2: error: List item 0 has incompatible type \"int\"; expected \"str\"\nmain:2: error: List item 1 has incompatible type \"int\"; expected \"str\"\nmain:2: error: List item 2 has incompatible type \"int\"; expected \"str\"\n\n[case testAllMustBeSequenceStr2]\nimport typing\n__all__ = 1  # E: Type of __all__ must be \"Sequence[str]\", not \"int\"\nreveal_type(__all__)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/module_all.pyi]\n\n[case testAllMustBeSequenceStr3]\nimport typing\n__all__ = set()  # E: Need type annotation for \"__all__\" (hint: \"__all__: set[<type>] = ...\") \\\n                 # E: Type of __all__ must be \"Sequence[str]\", not \"set[Any]\"\nreveal_type(__all__)  # N: Revealed type is \"builtins.set[Any]\"\n[builtins fixtures/set.pyi]\n\n[case testModuleAllEmptyList]\n__all__ = []\nreveal_type(__all__)  # N: Revealed type is \"builtins.list[builtins.str]\"\n[builtins fixtures/module_all.pyi]\n\n[case testDunderAllNotGlobal]\nclass A:\n    __all__ = 1\n\ndef foo() -> None:\n    __all__ = 1\n[builtins fixtures/module_all.pyi]\n\n[case testUnderscoreExportedValuesInImportAll]\nimport typing\nfrom m import *\n_ = a\n_ = _b\n_ = __c__\n_ = ___d\n_ = e\n_ = f # E: Name \"f\" is not defined\n_ = _g # E: Name \"_g\" is not defined\n[file m.py]\n__all__ = ['a']\n__all__ += ('_b',)\n__all__.append('__c__')\n__all__.extend(('___d', 'e'))\n\na = _b = __c__ = ___d = e = f = _g = 1\n[builtins fixtures/module_all.pyi]\n\n[case testEllipsisInitializerInStubFileWithType]\nimport m\nm.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[file m.pyi]\nx = ... # type: int\n\n[case testEllipsisInitializerInStubFileWithoutType]\nimport m\nm.x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"ellipsis\")\n[file m.pyi]\n# Ellipsis is only special with a # type: comment (not sure though if this is great)\nx = ...\n\n[case testEllipsisInitializerInModule]\nx = ... # type: int # E: Incompatible types in assignment (expression has type \"ellipsis\", variable has type \"int\")\n\n[case testEllipsisDefaultArgValueInStub]\nimport m\nm.f(1)\nm.f('') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n[file m.pyi]\ndef f(x: int = ...) -> None: pass\n\n[case testEllipsisDefaultParamValueInStub2]\nimport m\ndef f1(x: int = ...) -> int: return 1\ndef f2(x: int = '') -> int: return 1\n[file m.pyi]\ndef g1(x: int = ...) -> int: pass\ndef g2(x: int = '') -> int: pass\n[out]\ntmp/m.pyi:2: error: Incompatible default for parameter \"x\" (default has type \"str\", parameter has type \"int\")\nmain:2: error: Incompatible default for parameter \"x\" (default has type \"ellipsis\", parameter has type \"int\")\nmain:3: error: Incompatible default for parameter \"x\" (default has type \"str\", parameter has type \"int\")\n\n[case testEllipsisDefaultParamValueInNonStub]\ndef ok_1(x: int = ...) -> None: pass\ndef ok_2(x: int = ...) -> None: ...\ndef ok_3(x: int = ...) -> None: raise NotImplementedError\ndef ok_4(x: int = ...) -> None: raise NotImplementedError()\ndef ok_5(x: int = ...) -> None:\n    \"\"\"Docstring here\"\"\"\n    pass\n\ndef bad_1(x: int = ...) -> None: 1   # E: Incompatible default for parameter \"x\" (default has type \"ellipsis\", parameter has type \"int\")\ndef bad_2(x: int = ...) -> None:     # E: Incompatible default for parameter \"x\" (default has type \"ellipsis\", parameter has type \"int\")\n    \"\"\"Docstring here\"\"\"\n    ok_1()\ndef bad_3(x: int = ...) -> None:     # E: Incompatible default for parameter \"x\" (default has type \"ellipsis\", parameter has type \"int\")\n    raise Exception(\"Some other exception\")\n[builtins fixtures/exception.pyi]\n[out]\n\n[case testEllipsisDefaultParamValueInNonStubsOverload]\nfrom typing import overload, Union\n\nBoth = Union[int, str]\n\n@overload\ndef foo(x: int, y: int = ...) -> int: ...\n@overload\ndef foo(x: str, y: str = ...) -> str: ...\ndef foo(x: Both, y: Both = ...) -> Both:  # E: Incompatible default for parameter \"y\" (default has type \"ellipsis\", parameter has type \"int | str\")\n    return x\n\n@overload\ndef bar(x: int, y: int = ...) -> int: ...\n@overload\ndef bar(x: str, y: str = ...) -> str: ...\ndef bar(x: Both, y: Both = ...) -> Both:\n    raise NotImplementedError\n[builtins fixtures/exception.pyi]\n[out]\n\n[case testEllipsisDefaultParamValueInNonStubsMethods]\nfrom typing import Generic, Protocol, TypeVar\nfrom abc import abstractmethod\n\nT = TypeVar('T')\nclass Wrap(Generic[T]): ...\n\nclass MyProtocol(Protocol):\n    def no_impl(self, x: Wrap[int] = ...) -> int: ...\n    def default_impl(self, x: Wrap[int] = ...) -> int: return 3  # E: Incompatible default for parameter \"x\" (default has type \"ellipsis\", parameter has type \"Wrap[int]\")\n\nclass MyAbstractClass:\n    @abstractmethod\n    def no_impl(self, x: Wrap[int] = ...) -> int: raise NotImplementedError\n\n    @abstractmethod\n    def default_impl(self, x: Wrap[int] = ...) -> int: return 3  # E: Incompatible default for parameter \"x\" (default has type \"ellipsis\", parameter has type \"Wrap[int]\")\n[builtins fixtures/exception.pyi]\n[out]\n\n[case testStarImportOverlapping]\nfrom m1 import *\nfrom m2 import *\nj = ''\n[file m1.py]\nx = 1\n[file m2.py]\nx = 1\n\n[case testStarImportOverlappingMismatch]\nfrom m1 import *\nfrom m2 import * # E: Incompatible import of \"x\" (imported name has type \"int\", local name has type \"str\")\nj = ''\n[file m1.py]\nx = ''\n[file m2.py]\nx = 1\n\n[case testStarImportOverridingLocalImports]\nfrom m1 import *\nfrom m2 import *\nx = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[file m1.py]\nx = 1\n[file m2.py]\nx = 1\n\n[case testStarImportDoesNotImportGeneratedIntersections]\nfrom m1 import *\nfrom m2 import *\n[file m1.py]\nfrom m3 import A, B\n\na: A\nif isinstance(a, B): ...\n[file m2.py]\nfrom m3 import A, B\n\na: A\nif isinstance(a, B): ...\n[file m3.py]\nclass A: ...\nclass B: ...\nclass AB(A, B): ...\n[builtins fixtures/isinstance.pyi]\n\n[case testAssignToFuncDefViaImport]\n\n# Errors differ with the new analyzer. (Old analyzer gave error on the\n# input, which is maybe better, but no error about f, which seems\n# wrong)\nfrom m import *\nf = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"Callable[[], Any]\")\nx = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n[file m.py]\ndef f(): pass\nx = 1+0\n[out]\n\n\n-- Conditional definitions and function redefinitions via module object\n-- --------------------------------------------------------------------\n\n\n[case testConditionalImportAndAssign]\n# flags: --no-strict-optional\ntry:\n    from m import x\nexcept:\n    x = None\ntry:\n    from m import x as y\nexcept:\n    y = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[file m.py]\nx = ''\n\n[case testAssignAndConditionalImport]\nx = ''\ntry:\n    from m import x\nexcept:\n    pass\ny = 1\ntry:\n    from m import x as y  # E: Incompatible import of \"y\" (imported name has type \"str\", local name has type \"int\")\nexcept:\n    pass\n[file m.py]\nx = ''\n\n[case testAssignAndConditionalStarImport]\nx = ''\ny = 1\ntry:\n    from m import * # E: Incompatible import of \"y\" (imported name has type \"str\", local name has type \"int\")\nexcept:\n    pass\n[file m.py]\nx = ''\ny = ''\n\n[case testRedefineImportedFunctionViaImport]\ntry:\n    from m import f, g\nexcept:\n    def f(x): pass\n    def g(x): pass # E: All conditional function variants must have identical signatures \\\n                   # N: Original: \\\n                   # N:     def g(x: Any, y: Any) -> Any \\\n                   # N: Redefinition: \\\n                   # N:     def g(x: Any) -> Any\n[file m.py]\ndef f(x): pass\ndef g(x, y): pass\n\n[case testImportedVariableViaImport]\ntry:\n    from m import x\nexcept:\n    from n import x # E: Incompatible import of \"x\" (imported name has type \"str\", local name has type \"int\")\n[file m.py]\nx = 1\n[file n.py]\nx = ''\n\n[case testRedefineFunctionViaImport]\ndef f(x): pass\ndef g(x): pass\ntry:\n    from m import f, g # E: Incompatible import of \"g\" (imported name has type \"Callable[[Any, Any], Any]\", local name has type \"Callable[[Any], Any]\")\nexcept:\n    pass\n\nimport m as f  # E: Incompatible import of \"f\" (imported name has type \"object\", local name has type \"Callable[[Any], Any]\")\n\n[file m.py]\ndef f(x): pass\ndef g(x, y): pass\n\n[case testRedefineTypeViaImport]\nfrom typing import Type\nimport mod\n\nX: Type[mod.A]\nY: Type[mod.B]\nfrom mod import B as X\nfrom mod import A as Y  # E: Incompatible import of \"Y\" (imported name has type \"type[A]\", local name has type \"type[B]\")\n\nimport mod as X  # E: Incompatible import of \"X\" (imported name has type \"object\", local name has type \"type[A]\")\n\n[file mod.py]\nclass A: ...\nclass B(A): ...\n\n\n[case testImportVariableAndAssignNone]\n# flags: --no-strict-optional\ntry:\n    from m import x\nexcept:\n    x = None\n[file m.py]\nx = 1\n\n[case testImportFunctionAndAssignNone]\n# flags: --no-strict-optional\ntry:\n    from m import f\nexcept:\n    f = None\n[file m.py]\ndef f(): pass\n\n[case testImportFunctionAndAssignFunction]\ndef g(x): pass\ntry:\n    from m import f\nexcept:\n    f = g\n[file m.py]\ndef f(x): pass\n\n[case testImportFunctionAndAssignIncompatible]\ntry:\n    from m import f\nexcept:\n    f = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Callable[[], Any]\")\n[file m.py]\ndef f(): pass\n\n[case testAssignToFuncDefViaGlobalDecl2]\n# flags: --no-strict-optional\nimport typing\nfrom m import f\ndef g() -> None:\n    global f\n    f = None\n    if int():\n        f = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Callable[[], Any]\")\n[file m.py]\ndef f(): pass\n[out]\n\n[case testAssignToFuncDefViaNestedModules]\n# flags: --no-strict-optional\nimport m.n\nm.n.f = None\nm.n.f = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Callable[[], Any]\")\n[file m/__init__.py]\n[file m/n.py]\ndef f(): pass\n[out]\n\n[case testAssignToFuncDefViaModule]\n# flags: --no-strict-optional\nimport m\nm.f = None\nm.f = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Callable[[], Any]\")\n[file m.py]\ndef f(): pass\n[out]\n\n[case testConditionalImportAndAssignNoneToModule]\n# flags: --no-strict-optional\nif object():\n    import m\nelse:\n    m = None\nm.f(1) # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n[file m.py]\ndef f(x: str) -> None: pass\n[builtins fixtures/module.pyi]\n[out]\n\n[case testConditionalImportAndAssignInvalidToModule]\nif object():\n    import m\nelse:\n    m = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type Module)\n[file m.py]\n[builtins fixtures/module.pyi]\n[out]\n\n[case testImportAndAssignToModule]\n# flags: --no-strict-optional\nimport m\nm = None\nm.f(1) # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\n[file m.py]\ndef f(x: str) -> None: pass\n[builtins fixtures/module.pyi]\n[out]\n\n\n-- Test cases that simulate 'mypy -m modname'\n--\n-- The module name to import is encoded in a comment.\n\n[case testTypeCheckNamedModule]\n# cmd: mypy -m m.a\n[file m/__init__.py]\nNone + 1\n[file m/a.py]\n[out]\ntmp/m/__init__.py:1: error: Unsupported left operand type for + (\"None\")\n\n[case testTypeCheckNamedModule2]\n# cmd: mypy -m m.a\n[file m/__init__.py]\n[file m/a.py]\nNone + 1\n[out]\ntmp/m/a.py:1: error: Unsupported left operand type for + (\"None\")\n\n[case testTypeCheckNamedModule3]\n# cmd: mypy -m m\n[file m/__init__.py]\nNone + 1\n[file m/a.py]\n[out]\ntmp/m/__init__.py:1: error: Unsupported left operand type for + (\"None\")\n\n[case testTypeCheckNamedModule4]\n# cmd: mypy -m m\n[file m/__init__.py]\n[file m/a.py]\nNone + 1  # Not analyzed.\n[out]\n\n[case testTypeCheckNamedModule5]\n# cmd: mypy -m m\nNone + ''  # Not analyzed.\n[file m.py]\nNone + 1\n[out]\ntmp/m.py:1: error: Unsupported left operand type for + (\"None\")\n\n[case testTypeCheckNamedModuleWithImportCycle]\n# cmd: mypy -m m.a\nNone + 1  # Does not generate error, as this file won't be analyzed.\n[file m/__init__.py]\nimport m.a\n[file m/a.py]\n[out]\n\n[case testCheckDecoratedFuncAsAnnotWithImportCycle]\n\nimport a\n[file a.py]\nfrom typing import TypeVar\nimport b\n\nT = TypeVar('T')\ndef idf(x: T) -> T: return x\n\n@idf\ndef Session() -> None: pass\n\n[file b.py]\nMYPY = False\nif MYPY:\n    from a import Session\n\ndef f(self, session: Session) -> None:  # E: Function \"a.Session\" is not valid as a type \\\n                                        # N: Perhaps you need \"Callable[...]\" or a callback protocol?\n    pass\n[builtins fixtures/bool.pyi]\n\n\n-- Checks dealing with submodules and different kinds of imports\n-- -------------------------------------------------------------\n\n[case testSubmoduleRegularImportAddsAllParents]\nimport a.b.c\nreveal_type(a.value)  # N: Revealed type is \"builtins.int\"\nreveal_type(a.b.value)  # N: Revealed type is \"builtins.str\"\nreveal_type(a.b.c.value)  # N: Revealed type is \"builtins.float\"\nb.value  # E: Name \"b\" is not defined\nc.value  # E: Name \"c\" is not defined\n\n[file a/__init__.py]\nvalue = 3\n[file a/b/__init__.py]\nvalue = \"a\"\n[file a/b/c.py]\nvalue = 3.2\n[out]\n\n[case testSubmoduleImportAsDoesNotAddParents]\nimport a.b.c as foo\nreveal_type(foo.value)  # N: Revealed type is \"builtins.float\"\na.value  # E: Name \"a\" is not defined\nb.value  # E: Name \"b\" is not defined\nc.value  # E: Name \"c\" is not defined\n\n[file a/__init__.py]\nvalue = 3\n[file a/b/__init__.py]\nvalue = \"a\"\n[file a/b/c.py]\nvalue = 3.2\n[out]\n\n[case testSubmoduleImportFromDoesNotAddParents]\nfrom a import b\nreveal_type(b.value)  # N: Revealed type is \"builtins.str\"\nb.c.value  # E: Module has no attribute \"c\"\na.value  # E: Name \"a\" is not defined\n\n[file a/__init__.py]\nvalue = 3\n[file a/b/__init__.py]\nvalue = \"a\"\n[file a/b/c.py]\nvalue = 3.2\n[builtins fixtures/module.pyi]\n[out]\n\n[case testSubmoduleImportFromDoesNotAddParents2]\nfrom a.b import c\nreveal_type(c.value)  # N: Revealed type is \"builtins.float\"\na.value  # E: Name \"a\" is not defined\nb.value  # E: Name \"b\" is not defined\n\n[file a/__init__.py]\nvalue = 3\n[file a/b/__init__.py]\nvalue = \"a\"\n[file a/b/c.py]\nvalue = 3.2\n[out]\n\n[case testSubmoduleRegularImportNotDirectlyAddedToParent]\nimport a.b.c\ndef accept_float(x: float) -> None: pass\naccept_float(a.b.c.value)\n\n[file a/__init__.py]\nvalue = 3\nb.value  # E: Name \"b\" is not defined\na.b.value  # E: Name \"a\" is not defined\n\n[file a/b/__init__.py]\nvalue = \"a\"\nc.value  # E: Name \"c\" is not defined\na.b.c.value  # E: Name \"a\" is not defined\n\n[file a/b/c.py]\nvalue = 3.2\n\n[case testSubmoduleMixingLocalAndQualifiedNames]\nfrom a.b import MyClass\nval1: a.b.MyClass  # E: Name \"a\" is not defined\nval2: MyClass\n\n[file a/__init__.py]\n[file a/b.py]\nclass MyClass: pass\n[out]\n\n[case testSubmoduleMixingImportFrom]\nimport parent.child\n\n[file parent/__init__.py]\n\n[file parent/common.py]\nclass SomeClass: pass\n\n[file parent/child.py]\nfrom parent.common import SomeClass\nfrom parent import common\nfoo = parent.common.SomeClass()\n\n[builtins fixtures/module.pyi]\n[out]\ntmp/parent/child.py:3: error: Name \"parent\" is not defined\n\n[case testSubmoduleMixingImportFromAndImport]\nimport parent.child\n\n[file parent/__init__.py]\n\n[file parent/common.py]\nclass SomeClass: pass\n\n[file parent/unrelated.py]\nclass ShouldNotLoad: pass\n\n[file parent/child.py]\nfrom parent.common import SomeClass\nimport parent\n\n# Note, since this might be unintuitive -- when `parent.common` is loaded in any way,\n# shape, or form, it's added to `parent`'s namespace, which is why the below line\n# succeeds.\nfoo = parent.common.SomeClass()\nreveal_type(foo)\nbar = parent.unrelated.ShouldNotLoad()\n\n[builtins fixtures/module.pyi]\n[out]\ntmp/parent/child.py:8: note: Revealed type is \"parent.common.SomeClass\"\ntmp/parent/child.py:9: error: Module has no attribute \"unrelated\"\n\n[case testSubmoduleMixingImportFromAndImport2]\nimport parent.child\n\n[file parent/__init__.py]\n\n[file parent/common.py]\nclass SomeClass: pass\n\n[file parent/child.py]\nfrom parent import common\nimport parent\nfoo = parent.common.SomeClass()\nreveal_type(foo)\n\n[builtins fixtures/module.pyi]\n[out]\ntmp/parent/child.py:4: note: Revealed type is \"parent.common.SomeClass\"\n\n-- Tests repeated imports\n\n[case testIdenticalImportFromTwice]\nfrom a import x, y, z\nfrom b import x, y, z\n[file a.py]\nfrom common import x, y, z\n[file b.py]\nfrom common import x, y, z\n[file common.py]\nx = 3\ndef y() -> int: return 3\nclass z: pass\n[out]\n\n[case testIdenticalImportStarTwice]\nfrom a import *\nfrom b import *\n[file a.py]\nfrom common import x, y, z\n[file b.py]\nfrom common import x, y, z\n[file common.py]\nx = 3\ndef y() -> int: return 3\nclass z: pass\n[out]\n\n[case testDifferentImportSameNameTwice]\nfrom a import x, y, z\nfrom b import x, y, z\n[file a.py]\nx = 3\ndef y() -> int: return 1\nclass z: pass\n[file b.py]\nx = \"foo\"\ndef y() -> str: return \"foo\"\nclass z: pass\n[out]\nmain:2: error: Incompatible import of \"x\" (imported name has type \"str\", local name has type \"int\")\nmain:2: error: Incompatible import of \"y\" (imported name has type \"Callable[[], str]\", local name has type \"Callable[[], int]\")\nmain:2: error: Incompatible import of \"z\" (imported name has type \"type[b.z]\", local name has type \"type[a.z]\")\n\n-- Misc\n\n[case testInheritFromBadImport]\n# cmd: mypy -m bar\n[file foo.py]\npass\n[file bar.py]\nfrom foo import B\nclass C(B):\n    pass\n[out]\ntmp/bar.py:1: error: Module \"foo\" has no attribute \"B\"\n\n[case testImportSuppressedWhileAlmostSilent]\n# cmd: mypy -m main\n# flags: --follow-imports=error\n[file main.py]\nimport mod\n[file mod.py]\n[builtins fixtures/module.pyi]\n[out]\ntmp/main.py:1: error: Import of \"mod\" ignored\ntmp/main.py:1: note: (Using --follow-imports=error, module not passed on command line)\n\n[case testAncestorSuppressedWhileAlmostSilent]\n# cmd: mypy -m foo.bar\n# flags: --follow-imports=error\n[file foo/bar.py]\n[file foo/__init__.py]\n[builtins fixtures/module.pyi]\n[out]\ntmp/foo/bar.py: error: Ancestor package \"foo\" ignored\ntmp/foo/bar.py: note: (Using --follow-imports=error, submodule passed on command line)\n\n[case testStubImportNonStubWhileSilent]\n# cmd: mypy -m main\n# flags: --follow-imports=skip\n[file main.py]\nfrom stub import x, z  # Followed\nfrom other import y  # Not followed\nx + ''  # No error here\ny + ''  # No error here\nz + ''  # Error here\n[file stub.pyi]\nfrom non_stub import x as x  # this import is not followed\n\nz = 42\n[file non_stub.py]\nx = 42\n\nx + ''  # no error because file is not analyzed\n[file other.py]\ny = 42\n[builtins fixtures/module.pyi]\n[out]\ntmp/main.py:5: error: Unsupported left operand type for + (\"int\")\n\n[case testSilentSubmoduleImport]\n# cmd: mypy -m foo\n# flags: --follow-imports=skip\n[file foo/__init__.py]\nfrom foo import bar\n[file foo/bar.py]\npass\n\n[case testImportReExportFromChildrenInCycle1]\n# cmd: mypy -m project.root project.study.a project.neighbor\n[file project/__init__.py]\nfrom project.study import CustomType\nx = 10\n[file project/root.py]\n[file project/study/__init__.py]\nfrom project.study.a import CustomType\n[file project/study/a.py]\nfrom project import root\n# TODO (#4498): This test is basically testing the `all_are_submodules` logic\n# in build, which skips generating a dependency to a module if\n# everything in it is a submodule. But that is still all just a\n# workaround for bugs in cycle handling. If we uncomment the next\n# line, we'll still break:\n# from project import x\nCustomType = str\n[file project/neighbor/__init__.py]\nfrom project.study import CustomType\ndef m(arg: CustomType) -> str:\n    return 'test'\n\n[case testImportReExportFromChildrenInCycle2]\n# cmd: mypy -m project project.b project.ba project.c\n# See comments in above test about this being a workaround.\n[file foo.py]\ndef get_foo() -> int: return 12\n\n[file project/ba.py]\nfrom . import b\nb.FOO\n\n[file project/b.py]\nimport foo\nfrom . import c\nFOO = foo.get_foo()\n\n[file project/c.py]\n\n[file project/__init__.py]\nfrom . import ba\n\n[case testSuperclassInImportCycle]\nimport a\nimport d\na.A().f(d.D())\n[file a.py]\nif 0:\n    import d\nclass B: pass\nclass C(B): pass\nclass A:\n    def f(self, x: B) -> None: pass\n[file d.py]\nimport a\nclass D(a.C): pass\n\n[case testSuperclassInImportCycleReversedImports]\nimport d\nimport a\na.A().f(d.D())\n[file a.py]\nif 0:\n    import d\nclass B: pass\nclass C(B): pass\nclass A:\n    def f(self, x: B) -> None: pass\n[file d.py]\nimport a\nclass D(a.C): pass\n\n[case testPreferPackageOverFile]\nimport a\n[file a.py]\n/  # intentional syntax error -- this file shouldn't be parsed\n[file a/__init__.py]\npass\n[out]\n\n[case testPreferPackageOverFile2]\nfrom a import x\n[file a.py]\n/  # intentional syntax error -- this file shouldn't be parsed\n[file a/__init__.py]\nx = 0\n[out]\n\n[case testImportInClass]\nclass C:\n    import foo\nreveal_type(C.foo.bar)  # N: Revealed type is \"builtins.int\"\n[file foo.py]\nbar = 0\n[builtins fixtures/module.pyi]\n[out]\n\n[case testIfFalseImport]\nif False:\n    import a\ndef f(x: 'a.A') -> int:\n    return x.f()\n[file a.py]\nclass A:\n    def f(self) -> int:\n        return 0\n[builtins fixtures/bool.pyi]\n\n\n-- Test stability under import cycles\n-- ----------------------------------\n\n-- The first two tests are identical except one main has 'import x'\n-- and the other 'import y'.  Previously (before build.order_ascc()\n-- was added) one of these would fail because the imports were\n-- processed in the (reverse) order in which the files were\n-- encountered.\n\n[case testImportCycleStability1]\nimport x\n[file x.py]\ndef f() -> str: return ''\nclass Base:\n    attr = f()\ndef foo():\n    import y\n[file y.py]\nimport x\nclass Sub(x.Base):\n    attr = x.Base.attr\n[out]\n\n[case testImportCycleStability2]\nimport y\n[file x.py]\ndef f() -> str: return ''\nclass Base:\n    attr = f()\ndef foo():\n    import y\n[file y.py]\nimport x\nclass Sub(x.Base):\n    attr = x.Base.attr\n[out]\n\n-- This case isn't fixed by order_ascc(), but is fixed by the\n-- lightweight type inference added to semanal.py\n-- (analyze_simple_literal_type()).\n\n[case testImportCycleStability3]\nimport y\n[file x.py]\nclass Base:\n    pass\ndef foo() -> int:\n    import y\n    reveal_type(y.Sub.attr)\n    return y.Sub.attr\n[file y.py]\nimport x\nclass Sub(x.Base):\n    attr = 0\n[out]\ntmp/x.py:5: note: Revealed type is \"builtins.int\"\n\n-- This case has a symmetrical cycle, so it doesn't matter in what\n-- order the files are processed.  It depends on the lightweight type\n-- interference.\n\n[case testImportCycleStability4]\nimport x\n[file x.py]\nimport y\nclass C:\n    attr = ''\ndef foo() -> int:\n    return y.D.attr\n[file y.py]\nimport x\nclass D:\n    attr = 0\ndef bar() -> str:\n    return x.C.attr\n\n-- These cases test all supported literal types.\n\n[case testImportCycleStability5]\nimport y\n[file x.py]\nclass Base:\n    pass\ndef foo() -> None:\n    import y\n    i = y.Sub.iattr  # type: int\n    f = y.Sub.fattr  # type: float\n    s = y.Sub.sattr  # type: str\n    b = y.Sub.battr  # type: bytes\n[file y.py]\nimport x\nclass Sub(x.Base):\n    iattr = 0\n    fattr = 0.0\n    sattr = ''\n    battr = b''\n[out]\n\n-- This case tests module-level variables.\n\n[case testImportCycleStability7]\nimport x\n[file x.py]\ndef foo() -> int:\n    import y\n    reveal_type(y.value)\n    return y.value\n[file y.py]\nimport x\nvalue = 12\n[out]\ntmp/x.py:3: note: Revealed type is \"builtins.int\"\n\n-- This is not really cycle-related but still about the lightweight\n-- type checker.\n\n[case testImportCycleStability8]\nx = 1  # type: str\nreveal_type(x)\n[out]\nmain:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\nmain:2: note: Revealed type is \"builtins.str\"\n\n-- Tests for cross-module second_pass checking.\n\n[case testSymmetricImportCycle1]\nimport a\n[file a.py]\nimport b\ndef f() -> int:\n    return b.x\ny = 0 + int()\n[file b.py]\nimport a\ndef g() -> int:\n    reveal_type(a.y)\n    return a.y\nx = 1 + int()\n[out]\ntmp/b.py:3: note: Revealed type is \"builtins.int\"\n\n[case testSymmetricImportCycle2]\nimport b\n[file a.py]\nimport b\ndef f() -> int:\n    reveal_type(b.x)\n    return b.x\ny = 0 + int()\n[file b.py]\nimport a\ndef g() -> int:\n    return a.y\nx = 1 + int()\n[out]\ntmp/a.py:3: note: Revealed type is \"builtins.int\"\n\n[case testThreePassesRequired]\nimport b\n[file a.py]\nimport b\nclass C:\n    def f1(self) -> None:\n        reveal_type(self.x2)\n    def f2(self) -> None:\n        self.x2 = b.b\n[file b.py]\nimport a\nb = 1 + int()\n[out]\ntmp/a.py:4: note: Revealed type is \"builtins.int\"\n\n[case testErrorInPassTwo1]\nimport b\n[file a.py]\nimport b\ndef f() -> None:\n    a = b.x + 1\n    a + ''\n[file b.py]\nimport a\nx = 1 + int()\n[out]\ntmp/a.py:4: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testErrorInPassTwo2]\nimport a\n[file a.py]\nimport b\ndef f() -> None:\n    a = b.x + 1\n    a + ''\n[file b.py]\nimport a\nx = 1 + int()\n[out]\ntmp/a.py:4: error: Unsupported operand types for + (\"int\" and \"str\")\n\n[case testDeferredDecorator]\nimport a\n[file a.py]\nimport b\ndef g() -> None:\n    f('')\n@b.deco\ndef f(a: str) -> int: pass\nreveal_type(f)\nx = 1 + int()\n[file b.py]\nfrom typing import Callable, TypeVar\nimport a\nT = TypeVar('T')\ndef deco(f: Callable[[T], int]) -> Callable[[T], int]:\n    a.x\n    return f\n[out]\ntmp/a.py:6: note: Revealed type is \"def (builtins.str) -> builtins.int\"\n\n[case testDeferredClassContext]\nclass A:\n    def f(self) -> str: return 'foo'\nclass B(A):\n    def f(self) -> str: return self.x\n    def initialize(self) -> None: self.x = 'bar'\n\n[case testDeferredClassContextUnannotated]\nclass A:\n    def f(self) -> str: return 'foo'\nclass B(A):\n    def f(self) -> str: return self.x\n    def initialize(self): self.x = 'bar'\n\n-- Scripts and __main__\n\n[case testScriptsAreModules]\n# flags: --scripts-are-modules\n[file a]\npass\n[file b]\npass\n\n-- Misc\n\n[case testScriptsAreNotModules]\n# cmd: mypy a b\n[file a]\npass\n[file b]\npass\n[out]\n\n[case testTypeCheckPrio]\n# cmd: mypy -m part1 part2 part3 part4\n\n[file part1.py]\nfrom part3 import Thing\nclass FirstThing: pass\n\n[file part2.py]\nfrom part4 import part4_thing as Thing\n\n[file part3.py]\nfrom part2 import Thing\nreveal_type(Thing)\n\n[file part4.py]\nfrom typing import TYPE_CHECKING\nif TYPE_CHECKING:\n    from part1 import FirstThing\ndef part4_thing(a: int) -> str: pass\n\n[builtins fixtures/bool.pyi]\n[typing fixtures/typing-medium.pyi]\n[out]\ntmp/part3.py:2: note: Revealed type is \"def (a: builtins.int) -> builtins.str\"\n\n[case testImportStarAliasAnyList]\nimport bar\n\n[file bar.py]\nfrom foo import *\ndef bar(y: AnyAlias) -> None:  pass\n\nl: ListAlias[int]\nreveal_type(l)\n\n[file foo.py]\nfrom typing import Any, List\nAnyAlias = Any\nListAlias = List\n[builtins fixtures/list.pyi]\n[out]\ntmp/bar.py:5: note: Revealed type is \"builtins.list[builtins.int]\"\n\n[case testImportStarAliasSimpleGeneric]\nfrom ex2a import *\n\ndef do_something(dic: Row) -> None:\n    pass\n\ndef do_another() -> Row:\n    return {}\n\ndo_something({'good': 'bad'}) # E: Dict entry 0 has incompatible type \"str\": \"str\"; expected \"str\": \"int\"\nreveal_type(do_another()) # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n\n[file ex2a.py]\nfrom typing import Dict\nRow = Dict[str, int]\n[builtins fixtures/dict.pyi]\n[out]\n\n[case testImportStarAliasGeneric]\nfrom y import *\nnotes: G[X]\nanother = G[X]()\nsecond = XT[str]()\nlast = XT[G]()\n\nreveal_type(notes) # N: Revealed type is \"y.G[y.G[builtins.int]]\"\nreveal_type(another) # N: Revealed type is \"y.G[y.G[builtins.int]]\"\nreveal_type(second) # N: Revealed type is \"y.G[builtins.str]\"\nreveal_type(last) # N: Revealed type is \"y.G[y.G[Any]]\"\n\n[file y.py]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass G(Generic[T]):\n    pass\n\nX = G[int]\nXT = G[T]\n[out]\n\n[case testImportStarAliasCallable]\nfrom foo import *\nfrom typing import Any\n\ndef bar(x: Any, y: AnyCallable) -> Any:\n    return 'foo'\n\ncb: AnyCallable\nreveal_type(cb) # N: Revealed type is \"def (*Any, **Any) -> Any\"\n\n[file foo.py]\nfrom typing import Callable, Any\nAnyCallable = Callable[..., Any]\n[out]\n\n[case testRevealType]\nimport types\ndef f() -> types.ModuleType:\n    return types\nreveal_type(f())  # N: Revealed type is \"types.ModuleType\"\nreveal_type(types)  # N: Revealed type is \"types.ModuleType\"\n[builtins fixtures/module.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testClassImportAccessedInMethod]\nclass C:\n    import m\n    def foo(self) -> None:\n        x = self.m.a\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n        # ensure we distinguish self from other variables\n        y = 'hello'\n        z = y.m.a  # E: \"str\" has no attribute \"m\"\n    @classmethod\n    def cmethod(cls) -> None:\n        y = cls.m.a\n        reveal_type(y)  # N: Revealed type is \"builtins.str\"\n    @staticmethod\n    def smethod(foo: int) -> None:\n        # we aren't confused by first arg of a staticmethod\n        y = foo.m.a  # E: \"int\" has no attribute \"m\"\n\n[file m.py]\na = 'foo'\n\n[builtins fixtures/module.pyi]\n\n[case testModuleAlias]\nimport m\nm2 = m\nreveal_type(m2.a)  # N: Revealed type is \"builtins.str\"\nm2.b  # E: Module has no attribute \"b\"\nm2.c = 'bar'  # E: Module has no attribute \"c\"\n\n[file m.py]\na = 'foo'\n\n[builtins fixtures/module.pyi]\n\n[case testClassModuleAlias]\nimport m\n\nclass C:\n    x = m\n    def foo(self) -> None:\n        reveal_type(self.x.a)  # N: Revealed type is \"builtins.str\"\n\n[file m.py]\na = 'foo'\n\n[builtins fixtures/module.pyi]\n\n[case testLocalModuleAlias]\nimport m\n\ndef foo() -> None:\n    x = m\n    reveal_type(x.a)  # N: Revealed type is \"builtins.str\"\n\nclass C:\n    def foo(self) -> None:\n        x = m\n        reveal_type(x.a)  # N: Revealed type is \"builtins.str\"\n\n[file m.py]\na = 'foo'\n\n[builtins fixtures/module.pyi]\n\n[case testChainedModuleAlias]\nimport m\nm3 = m2 = m\nm4 = m3\nm5 = m4\nreveal_type(m2.a)  # N: Revealed type is \"builtins.str\"\nreveal_type(m3.a)  # N: Revealed type is \"builtins.str\"\nreveal_type(m4.a)  # N: Revealed type is \"builtins.str\"\nreveal_type(m5.a)  # N: Revealed type is \"builtins.str\"\n\n[file m.py]\na = 'foo'\n\n[builtins fixtures/module.pyi]\n\n[case testMultiModuleAlias]\nimport m, n\nm2, n2, (m3, n3) = m, n, [m, n]\nreveal_type(m2.a)  # N: Revealed type is \"builtins.str\"\nreveal_type(n2.b)  # N: Revealed type is \"builtins.str\"\nreveal_type(m3.a)  # N: Revealed type is \"builtins.str\"\nreveal_type(n3.b)  # N: Revealed type is \"builtins.str\"\n\nx, y = m  # E: Module object is not iterable\nx, y, z = m, n  # E: Need more than 2 values to unpack (3 expected)\nx, y = m, m, m  # E: Too many values to unpack (2 expected, 3 provided)\nx, (y, z) = m, n  # E: Module object is not iterable\nx, (y, z) = m, (n, n, n)  # E: Too many values to unpack (2 expected, 3 provided)\n\n[file m.py]\na = 'foo'\n\n[file n.py]\nb = 'bar'\n\n[builtins fixtures/module.pyi]\n\n[case testModuleAliasWithExplicitAnnotation]\nfrom typing import Any\nimport types\nimport m\nmod_mod: types.ModuleType = m\nmod_mod2: types.ModuleType\nmod_mod2 = m\nmod_mod3 = m  # type: types.ModuleType\nmod_any: Any = m\nmod_int: int = m  # E: Incompatible types in assignment (expression has type Module, variable has type \"int\")\n\nreveal_type(mod_mod)  # N: Revealed type is \"types.ModuleType\"\nreveal_type(mod_mod.a)  # N: Revealed type is \"Any\"\nreveal_type(mod_mod2)  # N: Revealed type is \"types.ModuleType\"\nreveal_type(mod_mod2.a)  # N: Revealed type is \"Any\"\nreveal_type(mod_mod3)  # N: Revealed type is \"types.ModuleType\"\nreveal_type(mod_mod3.a)  # N: Revealed type is \"Any\"\nreveal_type(mod_any)  # N: Revealed type is \"Any\"\n\n[file m.py]\na = 'foo'\n\n[builtins fixtures/module.pyi]\n\n[case testModuleAliasPassedToFunction]\nimport types\nimport m\n\ndef takes_module(x: types.ModuleType):\n    reveal_type(x.__file__)  # N: Revealed type is \"builtins.str\"\n\nn = m\ntakes_module(m)\ntakes_module(n)\n\n[file m.py]\na = 'foo'\n\n[builtins fixtures/module.pyi]\n\n[case testModuleAliasRepeated]\nimport m, n\n\nif bool():\n    x = m\nelse:\n    x = 3  # E: Incompatible types in assignment (expression has type \"int\", variable has type Module)\n\nif bool():\n    y = 3\nelse:\n    y = m  # E: Incompatible types in assignment (expression has type Module, variable has type \"int\")\n\nif bool():\n    z = m\nelse:\n    z = n  # E: Cannot assign multiple modules to name \"z\" without explicit \"types.ModuleType\" annotation\n\n[file m.py]\na = 'foo'\n\n[file n.py]\na = 3\n\n[builtins fixtures/module.pyi]\n\n[case testModuleAliasRepeatedWithAnnotation]\nimport types\nimport m, n\n\nx: types.ModuleType\nif bool():\n    x = m\nelse:\n    x = n\n\nreveal_type(x.nope)  # N: Revealed type is \"Any\"\nreveal_type(x.__file__)  # N: Revealed type is \"builtins.str\"\n\n[file m.py]\na = 'foo'\n\n[file n.py]\na = 3\n\n[builtins fixtures/module.pyi]\n\n[case testModuleAliasRepeatedComplex]\nimport m, n, o\n\nx = m\nif int():\n    x = n  # E: Cannot assign multiple modules to name \"x\" without explicit \"types.ModuleType\" annotation\nif int():\n    x = o  # E: Cannot assign multiple modules to name \"x\" without explicit \"types.ModuleType\" annotation\n\ny = o\nif int():\n    y, z = m, n  # E: Cannot assign multiple modules to name \"y\" without explicit \"types.ModuleType\" annotation\n\nxx = m\nif int():\n    xx = m\nreveal_type(xx.a)  # N: Revealed type is \"builtins.str\"\n\n[file m.py]\na = 'foo'\n\n[file n.py]\na = 3\n\n[file o.py]\na = 'bar'\n\n[builtins fixtures/module.pyi]\n\n[case testModuleAliasToOtherModule]\nimport m, n\nm = n  # E: Cannot assign multiple modules to name \"m\" without explicit \"types.ModuleType\" annotation\n\n[file m.py]\n\n[file n.py]\n\n[builtins fixtures/module.pyi]\n\n[case testNoReExportFromStubs]\nfrom stub import Iterable  # E: Module \"stub\" does not explicitly export attribute \"Iterable\"\nfrom stub import D  # E: Module \"stub\" does not explicitly export attribute \"D\"\nfrom stub import C\nfrom stub import foo\nfrom stub import bar  # E: Module \"stub\" does not explicitly export attribute \"bar\"\n\nc = C()\nreveal_type(c.x)  # N: Revealed type is \"builtins.int\"\nit: Iterable[int]\nreveal_type(it)  # N: Revealed type is \"typing.Iterable[builtins.int]\"\n\n[file stub.pyi]\nfrom typing import Iterable\nfrom substub import C as C\nfrom substub import C as D\nfrom package import foo as foo\nimport package.bar as bar\n\ndef fun(x: Iterable[str]) -> Iterable[int]: pass\n\n[file substub.pyi]\nclass C:\n    x: int\n\n[file package/foo.pyi]\n\n[file package/bar.pyi]\n\n[builtins fixtures/module.pyi]\n\n[case testNoReExportFromStubsMemberType]\nimport stub\n\nc = stub.C()\nreveal_type(c.x)  # N: Revealed type is \"builtins.int\"\nit: stub.Iterable[int]  # E: Name \"stub.Iterable\" is not defined\nreveal_type(it)  # N: Revealed type is \"Any\"\n\n[file stub.pyi]\nfrom typing import Iterable\nfrom substub import C as C\n\ndef fun(x: Iterable[str]) -> Iterable[int]: pass\n\n[file substub.pyi]\nclass C:\n    x: int\n\n[builtins fixtures/module.pyi]\n\n[case testNoReExportFromStubsMemberVar]\nimport stub\n\nreveal_type(stub.y)  # N: Revealed type is \"builtins.int\"\nreveal_type(stub.z)  # E: Module \"stub\" does not explicitly export attribute \"z\" \\\n                     # N: Revealed type is \"builtins.int\"\n\n\n[file stub.pyi]\nfrom substub import y as y\nfrom substub import z\n\n[file substub.pyi]\ny = 42\nz: int\n\n[builtins fixtures/module.pyi]\n\n[case testReExportChildStubs]\nimport mod\nfrom mod import submod\n\nreveal_type(mod.x)  # N: Revealed type is \"mod.submod.C\"\ny = submod.C()\nreveal_type(y.a)  # N: Revealed type is \"builtins.str\"\n\n[file mod/__init__.pyi]\nfrom . import submod\nx: submod.C\n\n[file mod/submod.pyi]\nclass C:\n    a: str\n\n[builtins fixtures/module.pyi]\n\n[case testReExportChildStubs2]\nimport mod.submod\n\ny = mod.submod.C()\nreveal_type(y.a)  # N: Revealed type is \"builtins.str\"\n\n[file mod/__init__.pyi]\nfrom . import submod\nx: submod.C\n\n[file mod/submod.pyi]\nclass C:\n    a: str\n\n[builtins fixtures/module.pyi]\n\n[case testReExportChildStubs3]\nfrom util import mod\nreveal_type(mod)  # N: Revealed type is \"def () -> package.mod.mod\"\n\nfrom util import internal_detail  # E: Module \"util\" does not explicitly export attribute \"internal_detail\"\n\n[file package/__init__.pyi]\nfrom .mod import mod as mod\n\n[file package/mod.pyi]\nclass mod: ...\n\n[file util.pyi]\nfrom package import mod as mod\n# stubs require explicit re-export\nfrom package import mod as internal_detail\n[builtins fixtures/module.pyi]\n\n[case testNoReExportUnrelatedModule]\nfrom mod2 import unrelated  # E: Module \"mod2\" does not explicitly export attribute \"unrelated\"\n\n[file mod1/__init__.pyi]\n[file mod1/unrelated.pyi]\nx: int\n\n[file mod2.pyi]\nfrom mod1 import unrelated\n[builtins fixtures/module.pyi]\n\n[case testNoReExportUnrelatedSiblingPrefix]\nfrom pkg.unrel import unrelated  # E: Module \"pkg.unrel\" does not explicitly export attribute \"unrelated\"\n\n[file pkg/__init__.pyi]\n[file pkg/unrelated.pyi]\nx: int\n\n[file pkg/unrel.pyi]\nfrom pkg import unrelated\n[builtins fixtures/module.pyi]\n\n[case testNoReExportChildStubs]\nimport mod\nfrom mod import C, D  # E: Module \"mod\" does not explicitly export attribute \"C\"\n\nreveal_type(mod.x)  # N: Revealed type is \"mod.submod.C\"\nmod.C  # E: Module \"mod\" does not explicitly export attribute \"C\"\ny = mod.D()\nreveal_type(y.a)  # N: Revealed type is \"builtins.str\"\n\n[file mod/__init__.pyi]\nfrom .submod import C, D as D\nx: C\n\n[file mod/submod.pyi]\nclass C: pass\nclass D:\n    a: str\n[builtins fixtures/module.pyi]\n\n[case testNoReExportNestedStub]\nfrom stub import substub  # E: Module \"stub\" does not explicitly export attribute \"substub\"\n\n[file stub.pyi]\nimport substub\n\n[file substub.pyi]\nx = 42\n\n[file mod/submod.pyi]\n\n[case testModuleAliasToQualifiedImport]\nimport package.module\nalias = package.module\nreveal_type(alias.whatever('/'))  # N: Revealed type is \"builtins.str\"\n[file package/__init__.py]\n\n[file package/module.py]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef whatever(x: T) -> T: pass\n[builtins fixtures/module.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testModuleAliasToQualifiedImport2]\nimport mod\nimport othermod\nalias = mod.submod\nreveal_type(alias.whatever('/'))  # N: Revealed type is \"builtins.str\"\nif int():\n    alias = othermod  # E: Cannot assign multiple modules to name \"alias\" without explicit \"types.ModuleType\" annotation\n[file mod.py]\nimport submod\n[file submod.py]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef whatever(x: T) -> T: pass\n[file othermod.py]\n[builtins fixtures/module.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testModuleLevelGetattr]\nimport has_getattr\n\nreveal_type(has_getattr.any_attribute)  # N: Revealed type is \"Any\"\n\n[file has_getattr.pyi]\nfrom typing import Any\n\ndef __getattr__(name: str) -> Any: ...\n\n[builtins fixtures/module.pyi]\n\n[case testModuleLevelGetattrReturnType]\nimport has_getattr\n\nreveal_type(has_getattr.any_attribute)  # N: Revealed type is \"builtins.str\"\n\n[file has_getattr.pyi]\ndef __getattr__(name: str) -> str: ...\n\n[builtins fixtures/module.pyi]\n\n[case testModuleLevelGetattrInvalidSignature]\nimport has_getattr\n\nreveal_type(has_getattr.any_attribute)\n\n[file has_getattr.pyi]\ndef __getattr__(x: int, y: str) -> str: ...\n\n[out]\ntmp/has_getattr.pyi:1: error: Invalid signature \"Callable[[int, str], str]\" for \"__getattr__\"\nmain:3: note: Revealed type is \"builtins.str\"\n\n[builtins fixtures/module.pyi]\n\n[case testModuleLevelGetattrNotCallable]\nimport has_getattr\n\nreveal_type(has_getattr.any_attribute)\n\n[file has_getattr.pyi]\n__getattr__ = 3\n\n[out]\ntmp/has_getattr.pyi:1: error: Invalid signature \"int\" for \"__getattr__\"\nmain:3: note: Revealed type is \"Any\"\n\n[builtins fixtures/module.pyi]\n\n[case testModuleLevelGetattrUntyped]\nimport has_getattr\nreveal_type(has_getattr.any_attribute)  # N: Revealed type is \"Any\"\n\n[file has_getattr.pyi]\ndef __getattr__(name): ...\n\n[builtins fixtures/module.pyi]\n\n[case testModuleLevelGetattrNotStub]\nimport has_getattr\nreveal_type(has_getattr.any_attribute)  # N: Revealed type is \"builtins.str\"\n\n[file has_getattr.py]\ndef __getattr__(name) -> str: ...\n\n[builtins fixtures/module.pyi]\n\n[case testModuleLevelGetattribute]\n\ndef __getattribute__(): ...  # E: __getattribute__ is not valid at the module level\n\n[case testModuleLevelGetattrImportFrom]\nfrom has_attr import name\nreveal_type(name)  # N: Revealed type is \"Any\"\n\n[file has_attr.pyi]\nfrom typing import Any\ndef __getattr__(name: str) -> Any: ...\n\n[builtins fixtures/module.pyi]\n\n[case testModuleLevelGetattrImportFromRetType]\nfrom has_attr import int_attr\nreveal_type(int_attr)  # N: Revealed type is \"builtins.int\"\n\n[file has_attr.pyi]\ndef __getattr__(name: str) -> int: ...\n\n[builtins fixtures/module.pyi]\n\n[case testModuleLevelGetattrImportFromNotStub]\nfrom non_stub import name\nreveal_type(name)  # N: Revealed type is \"Any\"\n\n[file non_stub.py]\nfrom typing import Any\ndef __getattr__(name: str) -> Any: ...\n\n[builtins fixtures/module.pyi]\n\n[case testModuleLevelGetattrImportFromAs]\nfrom has_attr import name as n\nreveal_type(name)  # E: Name \"name\" is not defined  # N: Revealed type is \"Any\"\nreveal_type(n)  # N: Revealed type is \"Any\"\n\n[file has_attr.pyi]\nfrom typing import Any\ndef __getattr__(name: str) -> Any: ...\n\n[builtins fixtures/module.pyi]\n\n[case testModuleLevelGetattrImportFromAsTwice]\n\nfrom has_attr import name\nfrom has_attr import name\nfrom has_attr import x\nfrom has_attr import y as x  # E: Name \"x\" already defined (possibly by an import)\nreveal_type(name)  # N: Revealed type is \"builtins.int\"\n\n[file has_attr.pyi]\nfrom typing import Any\ndef __getattr__(name: str) -> int: ...\n\n\n[case testModuleLevelGetattrAssignedGood]\nimport non_stub\nreveal_type(non_stub.name)  # N: Revealed type is \"builtins.int\"\n\n[file non_stub.py]\nfrom typing import Callable\n\ndef make_getattr_good() -> Callable[[str], int]: ...\n__getattr__ = make_getattr_good()  # OK\n\n[case testModuleLevelGetattrAssignedBad]\nimport non_stub\nreveal_type(non_stub.name)\n\n[file non_stub.py]\nfrom typing import Callable\n\ndef make_getattr_bad() -> Callable[[], int]: ...\n__getattr__ = make_getattr_bad()\n\n[out]\ntmp/non_stub.py:4: error: Invalid signature \"Callable[[], int]\" for \"__getattr__\"\nmain:2: note: Revealed type is \"builtins.int\"\n\n[case testModuleLevelGetattrImportedGood]\nimport non_stub\nreveal_type(non_stub.name)  # N: Revealed type is \"builtins.int\"\n\n[file non_stub.py]\nfrom has_getattr import __getattr__\n\n[file has_getattr.py]\ndef __getattr__(name: str) -> int: ...\n\n[case testModuleLevelGetattrImportedBad]\nimport non_stub\nreveal_type(non_stub.name)\n\n[file non_stub.py]\nfrom has_getattr import __getattr__\n\n[file has_getattr.py]\ndef __getattr__() -> int: ...\n\n[out]\ntmp/has_getattr.py:1: error: Invalid signature \"Callable[[], int]\" for \"__getattr__\"\nmain:2: note: Revealed type is \"builtins.int\"\n\n[builtins fixtures/module.pyi]\n\n-- Parallel mode gives only_once notes once *per worker*\n[case testFailedImportFromTwoModules_no_parallel]\nimport c\nimport b\n[file b.py]\nimport c\n[out]\n-- TODO: it would be better for this to be in the other order\ntmp/b.py:1: error: Cannot find implementation or library stub for module named \"c\"\nmain:1: error: Cannot find implementation or library stub for module named \"c\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testIndirectFromImportWithinCycle1]\nimport a\n[file a.py]\nfrom b import f\nfrom c import x\n[file b.py]\nfrom c import y\nfrom a import x\ndef f() -> None: pass\nreveal_type(x) # N: Revealed type is \"builtins.str\"\n[file c.py]\nx = str()\ny = int()\n\n[case testIndirectFromImportWithinCycle2]\nimport a\n[file a.py]\nfrom c import y\nfrom b import x\ndef f() -> None: pass\nreveal_type(x) # N: Revealed type is \"builtins.str\"\n[file b.py]\nfrom a import f\nfrom c import x\n[file c.py]\nx = str()\ny = int()\n\n[case testIndirectFromImportWithinCycleInPackage]\nimport p.a\n[file p/__init__.py]\n[file p/a.py]\nfrom p.b import f\nfrom p.c import x\n[file p/b.py]\nfrom p.c import y\nfrom p.a import x\ndef f() -> None: pass\nreveal_type(x) # N: Revealed type is \"builtins.str\"\n[file p/c.py]\nx = str()\ny = int()\n\n[case testIndirectFromImportWithinCycleInPackageIgnoredInit]\n# cmd: mypy -m p.a p.b p.c\n# flags: --follow-imports=skip --ignore-missing-imports\n[file p/__init__.py]\n[file p/a.py]\nfrom p.b import f\nfrom p.c import x\n[file p/b.py]\nfrom p.c import y\nfrom p.a import x\ndef f() -> None: pass\nreveal_type(x) # N: Revealed type is \"builtins.str\"\n[file p/c.py]\nx = str()\ny = int()\n\n[case testForwardReferenceToListAlias]\nx: List[int]\nreveal_type(x) # N: Revealed type is \"builtins.list[builtins.int]\"\ndef f() -> 'List[int]': pass\nreveal_type(f) # N: Revealed type is \"def () -> builtins.list[builtins.int]\"\nclass A:\n    y: 'List[str]'\n    def g(self, x: 'List[int]') -> None: pass\nreveal_type(A().y) # N: Revealed type is \"builtins.list[builtins.str]\"\nreveal_type(A().g) # N: Revealed type is \"def (x: builtins.list[builtins.int])\"\nfrom typing import List\n[builtins fixtures/list.pyi]\n\n[case testIndirectStarImportWithinCycle1]\nimport a\n[file a.py]\nfrom b import f\nfrom c import x\n[file b.py]\nfrom c import y\nfrom a import *\ndef f() -> None: pass\nreveal_type(x) # N: Revealed type is \"builtins.str\"\n[file c.py]\nx = str()\ny = int()\n\n[case testIndirectStarImportWithinCycle2]\nimport a\n[file a.py]\nfrom c import y\nfrom b import *\ndef f() -> None: pass\nreveal_type(x) # N: Revealed type is \"builtins.str\"\n[file b.py]\nfrom a import f\nfrom c import x\n[file c.py]\nx = str()\ny = int()\n\n[case testModuleGetattrInit1]\nfrom a import b\n\nx = b.f()\n[file a/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[builtins fixtures/module.pyi]\n[out]\n\n[case testModuleGetattrInit2]\nimport a.b\n\nx = a.b.f()\n[file a/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[builtins fixtures/module.pyi]\n[out]\n\n[case testModuleGetattrInit3]\nimport a.b\n\nx = a.b.f()\n[file a/__init__.py]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[builtins fixtures/module.pyi]\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"a.b\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testModuleGetattrInit4]\nimport a.b.c\n\nx = a.b.c.f()\n[file a/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[builtins fixtures/module.pyi]\n[out]\n\n[case testModuleGetattrInit5]\nfrom a.b import f\n\nx = f()\n[file a/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[builtins fixtures/module.pyi]\n[out]\n\n[case testModuleGetattrInit5a]\nfrom a.b import f\n\nx = f()\n[file a/__init__.pyi]\nfrom types import ModuleType\ndef __getattr__(attr: str) -> ModuleType: ...\n[builtins fixtures/module.pyi]\n[out]\n\n\n[case testModuleGetattrInit8]\nimport a.b.c.d\n\nx = a.b.c.d.f()\n[file a/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[file a/b/__init__.pyi]\n# empty (i.e. complete subpackage)\n[builtins fixtures/module.pyi]\n[out]\nmain:1: error: Cannot find implementation or library stub for module named \"a.b.c.d\"\nmain:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nmain:1: error: Cannot find implementation or library stub for module named \"a.b.c\"\n\n[case testModuleGetattrInit8a]\nimport a.b.c  # E: Cannot find implementation or library stub for module named \"a.b.c\"  # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nimport a.d  # OK\n[file a/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[file a/b/__init__.pyi]\n# empty (i.e. complete subpackage)\n[builtins fixtures/module.pyi]\n\n[case testModuleGetattrInit10]\n# flags: --config-file tmp/mypy.ini\nimport a.b.c  # silenced\nimport a.b.d  # error\n\n[file a/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[file a/b/__init__.pyi]\n# empty (i.e. complete subpackage)\n\n[file mypy.ini]\n\\[mypy]\n\\[mypy-a.b.c]\nignore_missing_imports = True\n[builtins fixtures/module.pyi]\n[out]\nmain:3: error: Cannot find implementation or library stub for module named \"a.b.d\"\nmain:3: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n\n[case testModuleGetattrInit10PyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport a.b.c  # silenced\nimport a.b.d  # error\n\n[file a/__init__.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n\n[file a/b/__init__.pyi]\n# empty (i.e. complete subpackage)\n\n[file pyproject.toml]\n\\[tool.mypy]\n\\[[tool.mypy.overrides]]\nmodule = 'a.b.c'\nignore_missing_imports = true\n\n[builtins fixtures/module.pyi]\n\n[out]\nmain:3: error: Cannot find implementation or library stub for module named \"a.b.d\"\nmain:3: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n\n[case testMultipleModulesInOverridePyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport a\nimport b\n\n[file pyproject.toml]\n\\[tool.mypy]\n\\[[tool.mypy.overrides]]\nmodule = ['a', 'b']\nignore_missing_imports = true\n\n\n[case testIndirectFromImportWithinCycleUsedAsBaseClass]\nimport a\n[file a.py]\nfrom b import f\nfrom c import B\n[file b.py]\nfrom c import y\nclass A(B): pass\nreveal_type(A().x) # N: Revealed type is \"builtins.int\"\nfrom a import B\ndef f() -> None: pass\n[file c.py]\nclass B:\n    x: int\nx = str()\ny = int()\n\n[case testImportFromReExportInCycleUsingRelativeImport1]\nfrom m import One\nreveal_type(One)  # N: Revealed type is \"def () -> m.one.One\"\n[file m/__init__.py]\nfrom .one import One\nfrom .two import Two\nreveal_type(One)  # N: Revealed type is \"def () -> m.one.One\"\n[file m/one.py]\nclass One:\n    pass\n[file m/two.py]\nfrom m import One\nreveal_type(One)  # N: Revealed type is \"def () -> m.one.One\"\nx: One\nreveal_type(x)  # N: Revealed type is \"m.one.One\"\n\nclass Two(One):\n    pass\ny: Two\ny = x  # E: Incompatible types in assignment (expression has type \"One\", variable has type \"Two\")\nx = y\n\n[case testImportReExportInCycleUsingRelativeImport2]\nfrom m import One\nreveal_type(One)  # N: Revealed type is \"def () -> m.one.One\"\n[file m/__init__.py]\nfrom .one import One\nfrom .two import Two\nreveal_type(One)  # N: Revealed type is \"def () -> m.one.One\"\n[file m/one.py]\nclass One:\n    pass\n[file m/two.py]\nimport m\nreveal_type(m.One)  # N: Revealed type is \"def () -> m.one.One\"\nx: m.One\nreveal_type(x)  # N: Revealed type is \"m.one.One\"\nclass Two:\n    pass\n\n[case testImportReExportedNamedTupleInCycle1]\nfrom m import One\n[file m/__init__.py]\nfrom .one import One\nfrom .two import Two\n[file m/one.py]\nfrom typing import NamedTuple\nclass One(NamedTuple):\n    name: str\n[file m/two.py]\nimport m\nx = m.One(name=\"Foo\")\nreveal_type(x.name)\nclass Two:\n    pass\n[builtins fixtures/tuple.pyi]\n[out]\ntmp/m/two.py:3: note: Revealed type is \"builtins.str\"\n\n[case testImportReExportedNamedTupleInCycle2]\nfrom m import One\n[file m/__init__.py]\nfrom .one import One\nfrom .two import Two\n[file m/one.py]\nfrom typing import NamedTuple\nOne = NamedTuple('One', [('name', str)])\n[file m/two.py]\nimport m\nx = m.One(name=\"Foo\")\nreveal_type(x.name)\nclass Two:\n    pass\n[builtins fixtures/tuple.pyi]\n[out]\ntmp/m/two.py:3: note: Revealed type is \"builtins.str\"\n\n[case testImportReExportedTypeAliasInCycle]\nfrom m import One\n[file m/__init__.py]\nfrom .one import One\nfrom .two import Two\n[file m/one.py]\nfrom typing import Union\nOne = Union[int, str]\n[file m/two.py]\nimport m\nx: m.One\nreveal_type(x)\nclass Two:\n    pass\n[out]\ntmp/m/two.py:3: note: Revealed type is \"builtins.int | builtins.str\"\n\n[case testImportCycleSpecialCase]\nimport p\n[file p/__init__.py]\nfrom . import a\nfrom . import b\nreveal_type(a.foo())  # N: Revealed type is \"builtins.int\"\n[file p/a.py]\nimport p\ndef foo() -> int: pass\n[file p/b.py]\nimport p\n\ndef run() -> None:\n    reveal_type(p.a.foo())  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/module.pyi]\n\n[case testMissingSubmoduleImportedWithIgnoreMissingImports]\n# flags: --ignore-missing-imports\nimport whatever.works\nimport a.b\nx = whatever.works.f()\ny = a.b.f()\n[file a/__init__.py]\n# empty\n[out]\n\n[case testMissingSubmoduleImportedWithIgnoreMissingImportsStub]\n# flags: --ignore-missing-imports --follow-imports=skip\nimport whatever.works\nimport a.b\nx = whatever.works.f()\ny = a.b.f()\nxx: whatever.works.C\nyy: a.b.C\nxx2: whatever.works.C.D\nyy2: a.b.C.D\n[file a/__init__.pyi]\n# empty\n[out]\n\n[case testMissingSubmoduleImportedWithIgnoreMissingImportsNested]\n# flags: --ignore-missing-imports\nimport a.b.c.d\ny = a.b.c.d.f()\n[file a/__init__.py]\n# empty\n[file a/b/__init__.py]\n# empty\n[out]\n\n[case testModuleGetattrBusted]\nfrom a import A\nx: A\nreveal_type(x)  # N: Revealed type is \"Any\"\n[file a.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[builtins fixtures/module.pyi]\n[out]\n\n[case testModuleGetattrBusted2]\nfrom a import A\ndef f(x: A.B) -> None: ...\nreveal_type(f)  # N: Revealed type is \"def (x: Any)\"\n[file a.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\n[builtins fixtures/module.pyi]\n[out]\n\n[case testNoGetattrInterference]\nimport testmod as t\ndef f(x: t.Cls) -> None:\n    reveal_type(x)  # N: Revealed type is \"testmod.Cls\"\n[file testmod.pyi]\nfrom typing import Any\ndef __getattr__(attr: str) -> Any: ...\nclass Cls: ...\n[builtins fixtures/module.pyi]\n[out]\n\n[case testFunctionWithDunderName]\ndef __add__(self) -> int: ...\n\n[case testFunctionWithReversibleDunderName]\ndef __radd__(self) -> int: ...\n\n[case testFunctionWithInPlaceDunderName]\ndef __iadd__(self) -> int: ...\n\n-- Tests for PEP 420 namespace packages.\n\n[case testClassicPackage]\nfrom foo.bar import x\n[file foo/__init__.py]\n# empty\n[file foo/bar.py]\nx = 0\n\n[case testClassicNotPackage]\n# flags: --no-namespace-packages\nfrom foo.bar import x\n[file foo/bar.py]\nx = 0\n[out]\nmain:2: error: Cannot find implementation or library stub for module named \"foo.bar\"\nmain:2: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testNamespacePackage]\n# flags: --namespace-packages\nfrom foo.bar import x\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[file foo/bar.py]\nx = 0\n\n[case testNamespacePackageWithMypyPath]\n# flags: --namespace-packages --config-file tmp/mypy.ini\nfrom foo.bax import x\nfrom foo.bay import y\nfrom foo.baz import z\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\nreveal_type(z)  # N: Revealed type is \"builtins.int\"\n[file xx/foo/bax.py]\nx = 0\n[file yy/foo/bay.py]\ny = 0\n[file foo/baz.py]\nz = 0\n[file mypy.ini]\n\\[mypy]\nmypy_path = tmp/xx, tmp/yy\n\n\n[case testNamespacePackageWithMypyPathPyProjectTOML]\n# flags: --namespace-packages --config-file tmp/pyproject.toml\nfrom foo.bax import x\nfrom foo.bay import y\nfrom foo.baz import z\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\nreveal_type(z)  # N: Revealed type is \"builtins.int\"\n\n[file xx/foo/bax.py]\nx = 0\n\n[file yy/foo/bay.py]\ny = 0\n\n[file foo/baz.py]\nz = 0\n\n[file pyproject.toml]\n\\[tool.mypy]\nmypy_path = [\"tmp/xx\", \"tmp/yy\"]\n\n\n[case testClassicPackageIgnoresEarlierNamespacePackage]\n# flags: --namespace-packages --config-file tmp/mypy.ini\nfrom foo.bar import y\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\n[file xx/foo/bar.py]\nx = ''\n[file yy/foo/bar.py]\ny = 0\n[file yy/foo/__init__.py]\n[file mypy.ini]\n\\[mypy]\nmypy_path = tmp/xx, tmp/yy\n\n[case testNamespacePackagePickFirstOnMypyPath]\n# flags: --namespace-packages --config-file tmp/mypy.ini\nfrom foo.bar import x\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[file xx/foo/bar.py]\nx = 0\n[file yy/foo/bar.py]\nx = ''\n[file mypy.ini]\n\\[mypy]\nmypy_path = tmp/xx, tmp/yy\n\n[case testNamespacePackageInsideClassicPackage]\n# flags: --namespace-packages --config-file tmp/mypy.ini\nfrom foo.bar.baz import x\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[file xx/foo/bar/baz.py]\nx = ''\n[file yy/foo/bar/baz.py]\nx = 0\n[file yy/foo/__init__.py]\n[file mypy.ini]\n\\[mypy]\nmypy_path = tmp/xx, tmp/yy\n\n[case testClassicPackageInsideNamespacePackage]\n# flags: --namespace-packages --config-file tmp/mypy.ini\nfrom foo.bar.baz.boo import x\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n[file xx/foo/bar/baz/boo.py]\nx = ''\n[file xx/foo/bar/baz/__init__.py]\n[file yy/foo/bar/baz/boo.py]\nx = 0\n[file yy/foo/bar/__init__.py]\n[file mypy.ini]\n\\[mypy]\nmypy_path = tmp/xx, tmp/yy\n\n[case testNamespacePackagePlainImport]\n# flags: --namespace-packages\nimport foo.bar.baz\nreveal_type(foo.bar.baz.x)  # N: Revealed type is \"builtins.int\"\n[file foo/bar/baz.py]\nx = 0\n\n[case testModuleGetAttrAssignUnannotated]\nimport roles\n# this should not crash\nroles.role = 1\n\n[file roles.pyi]\ndef __getattr__(name): ...\n\n[case testModuleGetAttrAssignUnannotatedDouble]\nimport roles\n# this also should not crash\nroles.role.attr = 1\n\n[file roles.pyi]\ndef __getattr__(name): ...\n\n[case testModuleGetAttrAssignAny]\nimport roles\nroles.role = 1\n\n[file roles.pyi]\nfrom typing import Any\ndef __getattr__(name: str) -> Any: ...\n\n[case testModuleGetAttrAssignError]\nimport roles\n\nroles.role = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[file roles.pyi]\ndef __getattr__(name: str) -> str: ...\n\n[case testModuleGetAttrAssignSubmodule]\nimport roles\nroles.role = 1\nroles.missing.attr = 1\n\n[file roles/__init__.pyi]\nfrom typing import Any\ndef __getattr__(name: str) -> Any: ...\n\n[case testModuleGetAttrAssignSubmoduleStrict]\nimport roles\nroles.role = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type Module)\n\n[file roles/__init__.pyi]\nfrom types import ModuleType\ndef __getattr__(name: str) -> ModuleType: ...\n[builtins fixtures/module.pyi]\n\n[case testAlwaysReportMissingAttributesOnFoundModules]\n# flags: --ignore-missing-imports\nimport pack.mod as alias\n\nx: alias.NonExistent  # E: Name \"alias.NonExistent\" is not defined\n\n[file pack/__init__.py]\n[file pack/mod.py]\nclass Existent: pass\n\n[case testModuleAttributeTwoSuggestions]\nimport m\nm.aaaa # E: Module has no attribute \"aaaa\"; maybe \"aaaaa\" or \"aaa\"?\n\n[file m.py]\naaa: int\naaaaa: int\n[builtins fixtures/module.pyi]\n\n[case testModuleAttributeThreeSuggestions]\nimport m\nm.aaaaa # E: Module has no attribute \"aaaaa\"; maybe \"aaaab\", \"aaaba\", or \"aabaa\"?\n\n[file m.py]\naaaab: int\naaaba: int\naabaa: int\n[builtins fixtures/module.pyi]\n\n[case testDirectlyImportTypedDictObjectAtTopLevel]\nimport foo.bar.custom_dict\nfrom foo import bar\nfrom foo.bar import custom_dict\nfrom foo.bar.custom_dict import CustomDict\n\nfoo.bar.custom_dict.CustomDict(foo=\"abc\", bar=\"def\")\nbar.custom_dict.CustomDict(foo=\"abc\", bar=\"def\")\ncustom_dict.CustomDict(foo=\"abc\", bar=\"def\")\nCustomDict(foo=\"abc\", bar=\"def\")\n\n[file foo/__init__.py]\n[file foo/bar/__init__.py]\n[file foo/bar/custom_dict.py]\nfrom typing import TypedDict\n\nCustomDict = TypedDict(\n    \"CustomDict\",\n    {\n        \"foo\": str,\n        \"bar\": str,\n    },\n)\n[typing fixtures/typing-full.pyi]\n[builtins fixtures/tuple.pyi]\n\n[case testNoReExportFromMissingStubs]\nfrom stub import a  # E: Module \"stub\" does not explicitly export attribute \"a\"\nfrom stub import b\nfrom stub import c  # E: Module \"stub\" has no attribute \"c\"\nfrom stub import d  # E: Module \"stub\" does not explicitly export attribute \"d\"\n\n[file stub.pyi]\nfrom mystery import a, b as b, c as d\n\n[out]\ntmp/stub.pyi:1: error: Cannot find implementation or library stub for module named \"mystery\"\ntmp/stub.pyi:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\n[case testPackagePath]\nimport p\nreveal_type(p.__path__)  # N: Revealed type is \"builtins.list[builtins.str]\"\np.m.__path__  # E: \"object\" has no attribute \"__path__\"\n\n[file p/__init__.py]\nfrom . import m as m\n[file p/m.py]\n[builtins fixtures/list.pyi]\n\n[case testSpecialModulesNameImplicitAttr]\nimport typing\nimport builtins\nimport abc\n\nreveal_type(abc.__name__)       # N: Revealed type is \"builtins.str\"\nreveal_type(builtins.__name__)  # N: Revealed type is \"builtins.str\"\nreveal_type(typing.__name__)    # N: Revealed type is \"builtins.str\"\n\n[case testSpecialAttrsAreAvailableInClasses]\nclass Some:\n    name = __name__\nreveal_type(Some.name)  # N: Revealed type is \"builtins.str\"\n\n[case testReExportAllInStub]\nfrom m1 import C\nfrom m1 import D  # E: Module \"m1\" has no attribute \"D\"\nC()\nC(1)  # E: Too many arguments for \"C\"\n[file m1.pyi]\nfrom m2 import *\n[file m2.pyi]\nfrom m3 import *\nfrom m3 import __all__ as __all__\nclass D: pass\n[file m3.pyi]\nfrom m4 import C as C\n__all__ = ['C']\n[file m4.pyi]\nclass C: pass\n[builtins fixtures/list.pyi]\n\n[case testMypyPathAndPython2Dir]\n# flags: --config-file tmp/mypy.ini\nfrom m import f\nf(1)  # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\nf('x')\n\n[file xx/@python2/m.pyi]\ndef f(x: int) -> None: ...\n\n[file xx/m.pyi]\ndef f(x: str) -> None: ...\n\n[file mypy.ini]\n\\[mypy]\nmypy_path = tmp/xx\n\n[case testImportCycleSpecialCase2]\nimport m\n\n[file m.pyi]\nfrom f import F\nclass M: pass\n\n[file f.pyi]\nfrom m import M\n\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\nclass W(Generic[T]): ...\n\nclass F(M):\n    A = W[int]\n    x: C\n    class C(W[F.A]): ...\n\n[case testImportCycleSpecialCase3]\nimport f\n\n[file m.pyi]\nfrom f import F\nclass M: pass\n\n[file f.pyi]\nfrom m import M\n\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\nclass F(M):\n    x: C\n    class C: ...\n\n[case testLimitLegacyStubErrorVolume]\n# flags: --disallow-any-expr --soft-error-limit=5\nimport certifi # E: Cannot find implementation or library stub for module named \"certifi\" \\\n               # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # N: (Skipping most remaining errors due to unresolved imports or missing stubs; fix these first)\ncertifi.x\ncertifi.x\ncertifi.x\ncertifi.x\n\n[case testDoNotLimitErrorVolumeIfNotImportErrors]\n# flags: --disallow-any-expr --soft-error-limit=5\ndef f(): pass\ncertifi = f()  # E: Expression has type \"Any\"\n1()  # E: \"int\" not callable\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\n1()  # E: \"int\" not callable\n\n[case testDoNotLimitImportErrorVolume]\n# flags: --disallow-any-expr --soft-error-limit=3\nimport xyz1  # E: Cannot find implementation or library stub for module named \"xyz1\" \\\n             # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nimport xyz2  # E: Cannot find implementation or library stub for module named \"xyz2\"\nimport xyz3  # E: Cannot find implementation or library stub for module named \"xyz3\"\nimport xyz4  # E: Cannot find implementation or library stub for module named \"xyz4\"\n\n[case testUnlimitedStubErrorVolume]\n# flags: --disallow-any-expr --soft-error-limit=-1\nimport certifi # E: Cannot find implementation or library stub for module named \"certifi\" \\\n               # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\ncertifi.x  # E: Expression has type \"Any\"\n\n[case testIgnoreErrorFromMissingStubs1]\n# flags: --config-file tmp/pyproject.toml\nimport certifi\nfrom foobar1 import x\nimport foobar2\n[file pyproject.toml]\n\\[tool.mypy]\nignore_missing_imports = true\n\\[[tool.mypy.overrides]]\nmodule = \"certifi\"\nignore_missing_imports = true\n\\[[tool.mypy.overrides]]\nmodule = \"foobar1\"\nignore_missing_imports = true\n\n[case testIgnoreErrorFromMissingStubs2]\n# flags: --config-file tmp/pyproject.toml\nimport certifi\nfrom foobar1 import x\nimport foobar2  # E: Cannot find implementation or library stub for module named \"foobar2\" \\\n                # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n[file pyproject.toml]\n\\[tool.mypy]\nignore_missing_imports = false\n\\[[tool.mypy.overrides]]\nmodule = \"certifi\"\nignore_missing_imports = true\n\\[[tool.mypy.overrides]]\nmodule = \"foobar1\"\nignore_missing_imports = true\n\n[case testIgnoreErrorFromGoogleCloud]\n# flags: --ignore-missing-imports\nimport google.cloud\nfrom google.cloud import x\n\n[case testErrorFromGoogleCloud]\nimport google.cloud  # E: Cannot find implementation or library stub for module named \"google.cloud\" \\\n                     # E: Cannot find implementation or library stub for module named \"google\"\nfrom google.cloud import x\nimport google.non_existent  # E: Cannot find implementation or library stub for module named \"google.non_existent\"\nfrom google.non_existent import x\n\nimport google.cloud.ndb  # E: Library stubs not installed for \"google.cloud.ndb\" \\\n                         # N: Hint: \"python3 -m pip install types-google-cloud-ndb\" \\\n                         # N: (or run \"mypy --install-types\" to install all missing stub packages) \\\n                         # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nfrom google.cloud import ndb\n\n[case testMissingSubmoduleOfInstalledStubPackage]\nimport bleach.exists\nimport bleach.xyz  # E: Cannot find implementation or library stub for module named \"bleach.xyz\" \\\n                   # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\nfrom bleach.abc import fgh  # E: Cannot find implementation or library stub for module named \"bleach.abc\"\n[file bleach/__init__.pyi]\n[file bleach/exists.pyi]\n\n[case testMissingSubmoduleOfInstalledStubPackageIgnored]\n# flags: --ignore-missing-imports\nimport bleach.xyz\nfrom bleach.abc import fgh\n[file bleach/__init__.pyi]\n\n[case testCyclicUndefinedImportWithName]\nimport a\n[file a.py]\nfrom b import no_such_export\n[file b.py]\nfrom a import no_such_export  # E: Module \"a\" has no attribute \"no_such_export\"\n\n[case testCyclicUndefinedImportWithStar1]\nimport a\n[file a.py]\nfrom b import no_such_export\n[file b.py]\nfrom a import *\n[out]\ntmp/b.py:1: error: Cannot resolve name \"no_such_export\" (possible cyclic definition)\n\n[case testCyclicUndefinedImportWithStar2]\nimport a\n[file a.py]\nfrom b import no_such_export\n[file b.py]\nfrom c import *\n[file c.py]\nfrom a import *\n[out]\ntmp/c.py:1: error: Cannot resolve name \"no_such_export\" (possible cyclic definition)\n\n[case testCyclicUndefinedImportWithStar3]\nimport test1\n[file test1.py]\nfrom dir1 import *\n[file dir1/__init__.py]\nfrom .test2 import *\n[file dir1/test2.py]\nfrom test1 import aaaa  # E: Module \"test1\" has no attribute \"aaaa\"\n\n[case testIncompatibleOverrideFromCachedModuleIncremental]\nimport b\n[file a.py]\nclass Foo:\n    def frobnicate(self, x: str, *args, **kwargs): pass\n[file b.py]\nfrom a import Foo\nclass Bar(Foo):\n    def frobnicate(self) -> None: pass\n[file b.py.2]\nfrom a import Foo\nclass Bar(Foo):\n    def frobnicate(self, *args: int) -> None: pass\n[file b.py.3]\nfrom a import Foo\nclass Bar(Foo):\n    def frobnicate(self, *args: int) -> None: pass # type: ignore[override] # I know\n[builtins fixtures/dict.pyi]\n[out1]\ntmp/b.py:3: error: Signature of \"frobnicate\" incompatible with supertype \"a.Foo\"\ntmp/b.py:3: note:      Superclass:\ntmp/b.py:3: note:          def frobnicate(self, x: str, *args: Any, **kwargs: Any) -> Any\ntmp/b.py:3: note:      Subclass:\ntmp/b.py:3: note:          def frobnicate(self) -> None\n[out2]\ntmp/b.py:3: error: Signature of \"frobnicate\" incompatible with supertype \"a.Foo\"\ntmp/b.py:3: note:      Superclass:\ntmp/b.py:3: note:          def frobnicate(self, x: str, *args: Any, **kwargs: Any) -> Any\ntmp/b.py:3: note:      Subclass:\ntmp/b.py:3: note:          def frobnicate(self, *args: int) -> None\n\n[case testTypeIgnoredImportsWorkWithCacheIncremental]\nimport a\n[file a.py]\nimport b  # type: ignore[import]\n[file b.py]\n[delete b.py.2]\n[out]\n[out2]\n\n[case testTypeIgnoredImportsWorkWithCacheIncremental2]\n# flags: --warn-unused-ignores\nimport a\n[file a.py]\nimport b  # type: ignore[import-not-found]\n[file b.py.2]\n[out]\n[out2]\ntmp/a.py:1: error: Unused \"type: ignore\" comment\n\n[case testTypeIgnoredImportsWorkWithCacheIncremental3]\n# flags: --warn-unused-ignores\nimport a\n[file a.py]\nimport b  # type: ignore[import-not-found]\n[file b.py]\n[delete b.py.2]\n[out]\ntmp/a.py:1: error: Unused \"type: ignore\" comment\n[out2]\n\n[case testImportErrorStaleLoadedFromCacheIncremental]\nimport a\n[file a.py]\nimport b\nimport c\n[file c.py]\nx: int\n[file c.py.2]\nx: str\n[out]\ntmp/a.py:1: error: Cannot find implementation or library stub for module named \"b\"\ntmp/a.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n[out2]\ntmp/a.py:1: error: Cannot find implementation or library stub for module named \"b\"\ntmp/a.py:1: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n"
  },
  {
    "path": "test-data/unit/check-narrowing.test",
    "content": "[case testNarrowingParentWithStrsBasic]\n# flags: --strict-equality --warn-unreachable\nfrom dataclasses import dataclass\nfrom typing import Literal, NamedTuple, Tuple, TypedDict, Union\n\nclass Object1:\n    key: Literal[\"A\"]\n    foo: int\nclass Object2:\n    key: Literal[\"B\"]\n    bar: str\n\n@dataclass\nclass Dataclass1:\n    key: Literal[\"A\"]\n    foo: int\n@dataclass\nclass Dataclass2:\n    key: Literal[\"B\"]\n    foo: str\n\nclass NamedTuple1(NamedTuple):\n    key: Literal[\"A\"]\n    foo: int\nclass NamedTuple2(NamedTuple):\n    key: Literal[\"B\"]\n    foo: str\n\nTuple1 = Tuple[Literal[\"A\"], int]\nTuple2 = Tuple[Literal[\"B\"], str]\n\nclass TypedDict1(TypedDict):\n    key: Literal[\"A\"]\n    foo: int\nclass TypedDict2(TypedDict):\n    key: Literal[\"B\"]\n    foo: str\n\nx1: Union[Object1, Object2]\nif x1.key == \"A\":\n    reveal_type(x1)         # N: Revealed type is \"__main__.Object1\"\n    reveal_type(x1.key)     # N: Revealed type is \"Literal['A']\"\nelse:\n    reveal_type(x1)         # N: Revealed type is \"__main__.Object2\"\n    reveal_type(x1.key)     # N: Revealed type is \"Literal['B']\"\n\nx2: Union[Dataclass1, Dataclass2]\nif x2.key == \"A\":\n    reveal_type(x2)         # N: Revealed type is \"__main__.Dataclass1\"\n    reveal_type(x2.key)     # N: Revealed type is \"Literal['A']\"\nelse:\n    reveal_type(x2)         # N: Revealed type is \"__main__.Dataclass2\"\n    reveal_type(x2.key)     # N: Revealed type is \"Literal['B']\"\n\nx3: Union[NamedTuple1, NamedTuple2]\nif x3.key == \"A\":\n    reveal_type(x3)         # N: Revealed type is \"tuple[Literal['A'], builtins.int, fallback=__main__.NamedTuple1]\"\n    reveal_type(x3.key)     # N: Revealed type is \"Literal['A']\"\nelse:\n    reveal_type(x3)         # N: Revealed type is \"tuple[Literal['B'], builtins.str, fallback=__main__.NamedTuple2]\"\n    reveal_type(x3.key)     # N: Revealed type is \"Literal['B']\"\nif x3[0] == \"A\":\n    reveal_type(x3)         # N: Revealed type is \"tuple[Literal['A'], builtins.int, fallback=__main__.NamedTuple1]\"\n    reveal_type(x3[0])      # N: Revealed type is \"Literal['A']\"\nelse:\n    reveal_type(x3)         # N: Revealed type is \"tuple[Literal['B'], builtins.str, fallback=__main__.NamedTuple2]\"\n    reveal_type(x3[0])      # N: Revealed type is \"Literal['B']\"\n\nx4: Union[Tuple1, Tuple2]\nif x4[0] == \"A\":\n    reveal_type(x4)         # N: Revealed type is \"tuple[Literal['A'], builtins.int]\"\n    reveal_type(x4[0])      # N: Revealed type is \"Literal['A']\"\nelse:\n    reveal_type(x4)         # N: Revealed type is \"tuple[Literal['B'], builtins.str]\"\n    reveal_type(x4[0])      # N: Revealed type is \"Literal['B']\"\n\nx5: Union[TypedDict1, TypedDict2]\nif x5[\"key\"] == \"A\":\n    reveal_type(x5)         # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key': Literal['A'], 'foo': builtins.int})\"\nelse:\n    reveal_type(x5)         # N: Revealed type is \"TypedDict('__main__.TypedDict2', {'key': Literal['B'], 'foo': builtins.str})\"\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNarrowingParentWithEnumsBasic]\n# flags: --strict-equality --warn-unreachable\nfrom enum import Enum\nfrom dataclasses import dataclass\nfrom typing import Literal, NamedTuple, Tuple, TypedDict, Union\n\nclass Key(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nclass Object1:\n    key: Literal[Key.A]\n    foo: int\nclass Object2:\n    key: Literal[Key.B]\n    bar: str\n\n@dataclass\nclass Dataclass1:\n    key: Literal[Key.A]\n    foo: int\n@dataclass\nclass Dataclass2:\n    key: Literal[Key.B]\n    foo: str\n\nclass NamedTuple1(NamedTuple):\n    key: Literal[Key.A]\n    foo: int\nclass NamedTuple2(NamedTuple):\n    key: Literal[Key.B]\n    foo: str\n\nTuple1 = Tuple[Literal[Key.A], int]\nTuple2 = Tuple[Literal[Key.B], str]\n\nclass TypedDict1(TypedDict):\n    key: Literal[Key.A]\n    foo: int\nclass TypedDict2(TypedDict):\n    key: Literal[Key.B]\n    foo: str\n\nx1: Union[Object1, Object2]\nif x1.key is Key.A:\n    reveal_type(x1)         # N: Revealed type is \"__main__.Object1\"\n    reveal_type(x1.key)     # N: Revealed type is \"Literal[__main__.Key.A]\"\nelse:\n    reveal_type(x1)         # N: Revealed type is \"__main__.Object2\"\n    reveal_type(x1.key)     # N: Revealed type is \"Literal[__main__.Key.B]\"\n\nx2: Union[Dataclass1, Dataclass2]\nif x2.key is Key.A:\n    reveal_type(x2)         # N: Revealed type is \"__main__.Dataclass1\"\n    reveal_type(x2.key)     # N: Revealed type is \"Literal[__main__.Key.A]\"\nelse:\n    reveal_type(x2)         # N: Revealed type is \"__main__.Dataclass2\"\n    reveal_type(x2.key)     # N: Revealed type is \"Literal[__main__.Key.B]\"\n\nx3: Union[NamedTuple1, NamedTuple2]\nif x3.key is Key.A:\n    reveal_type(x3)         # N: Revealed type is \"tuple[Literal[__main__.Key.A], builtins.int, fallback=__main__.NamedTuple1]\"\n    reveal_type(x3.key)     # N: Revealed type is \"Literal[__main__.Key.A]\"\nelse:\n    reveal_type(x3)         # N: Revealed type is \"tuple[Literal[__main__.Key.B], builtins.str, fallback=__main__.NamedTuple2]\"\n    reveal_type(x3.key)     # N: Revealed type is \"Literal[__main__.Key.B]\"\nif x3[0] is Key.A:\n    reveal_type(x3)         # N: Revealed type is \"tuple[Literal[__main__.Key.A], builtins.int, fallback=__main__.NamedTuple1]\"\n    reveal_type(x3[0])      # N: Revealed type is \"Literal[__main__.Key.A]\"\nelse:\n    reveal_type(x3)         # N: Revealed type is \"tuple[Literal[__main__.Key.B], builtins.str, fallback=__main__.NamedTuple2]\"\n    reveal_type(x3[0])      # N: Revealed type is \"Literal[__main__.Key.B]\"\n\nx4: Union[Tuple1, Tuple2]\nif x4[0] is Key.A:\n    reveal_type(x4)         # N: Revealed type is \"tuple[Literal[__main__.Key.A], builtins.int]\"\n    reveal_type(x4[0])      # N: Revealed type is \"Literal[__main__.Key.A]\"\nelse:\n    reveal_type(x4)         # N: Revealed type is \"tuple[Literal[__main__.Key.B], builtins.str]\"\n    reveal_type(x4[0])      # N: Revealed type is \"Literal[__main__.Key.B]\"\n\nx5: Union[TypedDict1, TypedDict2]\nif x5[\"key\"] is Key.A:\n    reveal_type(x5)         # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key': Literal[__main__.Key.A], 'foo': builtins.int})\"\nelse:\n    reveal_type(x5)         # N: Revealed type is \"TypedDict('__main__.TypedDict2', {'key': Literal[__main__.Key.B], 'foo': builtins.str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNarrowingParentWithIsInstanceBasic]\n# flags: --strict-equality --warn-unreachable\nfrom dataclasses import dataclass\nfrom typing import NamedTuple, Tuple, TypedDict, Union\n\nclass Object1:\n    key: int\nclass Object2:\n    key: str\n\n@dataclass\nclass Dataclass1:\n    key: int\n@dataclass\nclass Dataclass2:\n    key: str\n\nclass NamedTuple1(NamedTuple):\n    key: int\nclass NamedTuple2(NamedTuple):\n    key: str\n\nTuple1 = Tuple[int]\nTuple2 = Tuple[str]\n\nclass TypedDict1(TypedDict):\n    key: int\nclass TypedDict2(TypedDict):\n    key: str\n\nx1: Union[Object1, Object2]\nif isinstance(x1.key, int):\n    reveal_type(x1)         # N: Revealed type is \"__main__.Object1\"\nelse:\n    reveal_type(x1)         # N: Revealed type is \"__main__.Object2\"\n\nx2: Union[Dataclass1, Dataclass2]\nif isinstance(x2.key, int):\n    reveal_type(x2)         # N: Revealed type is \"__main__.Dataclass1\"\nelse:\n    reveal_type(x2)         # N: Revealed type is \"__main__.Dataclass2\"\n\nx3: Union[NamedTuple1, NamedTuple2]\nif isinstance(x3.key, int):\n    reveal_type(x3)         # N: Revealed type is \"tuple[builtins.int, fallback=__main__.NamedTuple1]\"\nelse:\n    reveal_type(x3)         # N: Revealed type is \"tuple[builtins.str, fallback=__main__.NamedTuple2]\"\nif isinstance(x3[0], int):\n    reveal_type(x3)         # N: Revealed type is \"tuple[builtins.int, fallback=__main__.NamedTuple1]\"\nelse:\n    reveal_type(x3)         # N: Revealed type is \"tuple[builtins.str, fallback=__main__.NamedTuple2]\"\n\nx4: Union[Tuple1, Tuple2]\nif isinstance(x4[0], int):\n    reveal_type(x4)         # N: Revealed type is \"tuple[builtins.int]\"\nelse:\n    reveal_type(x4)         # N: Revealed type is \"tuple[builtins.str]\"\n\nx5: Union[TypedDict1, TypedDict2]\nif isinstance(x5[\"key\"], int):\n    reveal_type(x5)         # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key': builtins.int})\"\nelse:\n    reveal_type(x5)         # N: Revealed type is \"TypedDict('__main__.TypedDict2', {'key': builtins.str})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNarrowingParentMultipleKeys]\n# flags: --strict-equality --warn-unreachable\nfrom enum import Enum\nfrom typing import Literal, Union\n\nclass Key(Enum):\n    A = 1\n    B = 2\n    C = 3\n    D = 4\n\nclass Object1:\n    key: Literal[Key.A, Key.C]\nclass Object2:\n    key: Literal[Key.B, Key.C]\n\nx: Union[Object1, Object2]\nif x.key is Key.A:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object1\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object1 | __main__.Object2\"\n\nif x.key is Key.C:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object1 | __main__.Object2\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object1 | __main__.Object2\"\n\nif x.key is Key.D:  # E: Non-overlapping identity check (left operand type: \"Literal[Key.A, Key.C, Key.B]\", right operand type: \"Literal[Key.D]\")\n    reveal_type(x)  # E: Statement is unreachable\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object1 | __main__.Object2\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingTypedDictParentMultipleKeys]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, TypedDict, Union\n\nclass TypedDict1(TypedDict):\n    key: Literal['A', 'C']\nclass TypedDict2(TypedDict):\n    key: Literal['B', 'C']\n\nx: Union[TypedDict1, TypedDict2]\nif x['key'] == 'A':\n    reveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key': Literal['A'] | Literal['C']})\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key': Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key': Literal['B'] | Literal['C']})\"\n\nif x['key'] == 'C':\n    reveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key': Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key': Literal['B'] | Literal['C']})\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key': Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key': Literal['B'] | Literal['C']})\"\n\nif x['key'] == 'D':  # E: Non-overlapping equality check (left operand type: \"Literal['A', 'C', 'B']\", right operand type: \"Literal['D']\")\n    reveal_type(x)  # E: Statement is unreachable\nelse:\n    reveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key': Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key': Literal['B'] | Literal['C']})\"\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNarrowingPartialTypedDictParentMultipleKeys]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, TypedDict, Union\n\nclass TypedDict1(TypedDict, total=False):\n    key: Literal['A', 'C']\nclass TypedDict2(TypedDict, total=False):\n    key: Literal['B', 'C']\n\nx: Union[TypedDict1, TypedDict2]\nif x['key'] == 'A':\n    reveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key'?: Literal['A'] | Literal['C']})\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key'?: Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key'?: Literal['B'] | Literal['C']})\"\n\nif x['key'] == 'C':\n    reveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key'?: Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key'?: Literal['B'] | Literal['C']})\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key'?: Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key'?: Literal['B'] | Literal['C']})\"\n\nif x['key'] == 'D':  # E: Non-overlapping equality check (left operand type: \"Literal['A', 'C', 'B']\", right operand type: \"Literal['D']\")\n    reveal_type(x)  # E: Statement is unreachable\nelse:\n    reveal_type(x)  # N: Revealed type is \"TypedDict('__main__.TypedDict1', {'key'?: Literal['A'] | Literal['C']}) | TypedDict('__main__.TypedDict2', {'key'?: Literal['B'] | Literal['C']})\"\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNarrowingNestedTypedDicts]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, TypedDict, Union\n\nclass A(TypedDict):\n    key: Literal['A']\nclass B(TypedDict):\n    key: Literal['B']\nclass C(TypedDict):\n    key: Literal['C']\n\nclass X(TypedDict):\n    inner: Union[A, B]\nclass Y(TypedDict):\n    inner: Union[B, C]\n\nunknown: Union[X, Y]\nif unknown['inner']['key'] == 'A':\n    reveal_type(unknown)            # N: Revealed type is \"TypedDict('__main__.X', {'inner': TypedDict('__main__.A', {'key': Literal['A']}) | TypedDict('__main__.B', {'key': Literal['B']})})\"\n    reveal_type(unknown['inner'])   # N: Revealed type is \"TypedDict('__main__.A', {'key': Literal['A']})\"\nif unknown['inner']['key'] == 'B':\n    reveal_type(unknown)            # N: Revealed type is \"TypedDict('__main__.X', {'inner': TypedDict('__main__.A', {'key': Literal['A']}) | TypedDict('__main__.B', {'key': Literal['B']})}) | TypedDict('__main__.Y', {'inner': TypedDict('__main__.B', {'key': Literal['B']}) | TypedDict('__main__.C', {'key': Literal['C']})})\"\n    reveal_type(unknown['inner'])   # N: Revealed type is \"TypedDict('__main__.B', {'key': Literal['B']})\"\nif unknown['inner']['key'] == 'C':\n    reveal_type(unknown)            # N: Revealed type is \"TypedDict('__main__.Y', {'inner': TypedDict('__main__.B', {'key': Literal['B']}) | TypedDict('__main__.C', {'key': Literal['C']})})\"\n    reveal_type(unknown['inner'])   # N: Revealed type is \"TypedDict('__main__.C', {'key': Literal['C']})\"\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNarrowingParentWithMultipleParents]\n# flags: --strict-equality --warn-unreachable\nfrom enum import Enum\nfrom typing import Literal, Union\n\nclass Key(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nclass Object1:\n    key: Literal[Key.A]\nclass Object2:\n    key: Literal[Key.B]\nclass Object3:\n    key: Literal[Key.C]\nclass Object4:\n    key: str\n\nx: Union[Object1, Object2, Object3, Object4]\nif x.key is Key.A:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object1\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object2 | __main__.Object3 | __main__.Object4\"\n\nif isinstance(x.key, str):\n    reveal_type(x)  # N: Revealed type is \"__main__.Object4\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object1 | __main__.Object2 | __main__.Object3\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowingParentsWithGenerics]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union, TypeVar, Generic\n\nT = TypeVar('T')\nclass Wrapper(Generic[T]):\n    key: T\n\nx: Union[Wrapper[int], Wrapper[str]]\nif isinstance(x.key, int):\n    reveal_type(x)  # N: Revealed type is \"__main__.Wrapper[builtins.int]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Wrapper[builtins.str]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowingParentWithParentMixtures]\n# flags: --strict-equality --warn-unreachable\nfrom enum import Enum\nfrom typing import Literal, Union, NamedTuple, TypedDict\n\nclass Key(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nclass KeyedObject:\n    key: Literal[Key.A]\nclass KeyedTypedDict(TypedDict):\n    key: Literal[Key.B]\nclass KeyedNamedTuple(NamedTuple):\n    key: Literal[Key.C]\n\nok_mixture: Union[KeyedObject, KeyedNamedTuple]\nif ok_mixture.key is Key.A:\n    reveal_type(ok_mixture)             # N: Revealed type is \"__main__.KeyedObject\"\nelse:\n    reveal_type(ok_mixture)             # N: Revealed type is \"tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]\"\n\nimpossible_mixture: Union[KeyedObject, KeyedTypedDict]\nif impossible_mixture.key is Key.A:     # E: Item \"KeyedTypedDict\" of \"KeyedObject | KeyedTypedDict\" has no attribute \"key\"\n    reveal_type(impossible_mixture)     # N: Revealed type is \"__main__.KeyedObject | TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})\"\nelse:\n    reveal_type(impossible_mixture)     # N: Revealed type is \"__main__.KeyedObject | TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})\"\n\nif impossible_mixture[\"key\"] is Key.A:  # E: Value of type \"KeyedObject | KeyedTypedDict\" is not indexable\n    reveal_type(impossible_mixture)     # N: Revealed type is \"__main__.KeyedObject | TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})\"\nelse:\n    reveal_type(impossible_mixture)     # N: Revealed type is \"__main__.KeyedObject | TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]})\"\n\nweird_mixture: Union[KeyedTypedDict, KeyedNamedTuple]\nif weird_mixture[\"key\"] is Key.B:       # E: No overload variant of \"__getitem__\" of \"tuple\" matches argument type \"str\" \\\n                                        # N: Possible overload variants: \\\n                                        # N:     def __getitem__(self, int, /) -> Literal[Key.C] \\\n                                        # N:     def __getitem__(self, slice, /) -> tuple[Literal[Key.C], ...]\n    reveal_type(weird_mixture)          # N: Revealed type is \"TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]}) | tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]\"\nelse:\n    reveal_type(weird_mixture)          # N: Revealed type is \"TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]}) | tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]\"\n\nif weird_mixture[0] is Key.B:           # E: TypedDict key must be a string literal; expected one of (\"key\")\n    reveal_type(weird_mixture)          # N: Revealed type is \"TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]}) | tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]\"\nelse:\n    reveal_type(weird_mixture)          # N: Revealed type is \"TypedDict('__main__.KeyedTypedDict', {'key': Literal[__main__.Key.B]}) | tuple[Literal[__main__.Key.C], fallback=__main__.KeyedNamedTuple]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testNarrowingParentWithProperties]\n# flags: --strict-equality --warn-unreachable\nfrom enum import Enum\nfrom typing import Literal, Union\n\nclass Key(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nclass Object1:\n    key: Literal[Key.A]\n\nclass Object2:\n    @property\n    def key(self) -> Literal[Key.A]: ...\n\nclass Object3:\n    @property\n    def key(self) -> Literal[Key.B]: ...\n\nx: Union[Object1, Object2, Object3]\nif x.key is Key.A:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object1 | __main__.Object2\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Object3\"\n[builtins fixtures/property.pyi]\n\n[case testNarrowingParentWithAny]\n# flags: --strict-equality --warn-unreachable\nfrom enum import Enum\nfrom typing import Literal, Union, Any\n\nclass Key(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nclass Object1:\n    key: Literal[Key.A]\n\nclass Object2:\n    key: Literal[Key.B]\n\nx: Union[Object1, Object2, Any]\nif x.key is Key.A:\n    reveal_type(x.key)  # N: Revealed type is \"Literal[__main__.Key.A]\"\n    reveal_type(x)      # N: Revealed type is \"__main__.Object1 | Any\"\nelse:\n    # TODO: Is this a bug? Should we skip inferring Any for singleton types?\n    reveal_type(x.key)  # N: Revealed type is \"Any | Literal[__main__.Key.B]\"\n    reveal_type(x)      # N: Revealed type is \"__main__.Object1 | __main__.Object2 | Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingParentsHierarchy]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Union\nfrom enum import Enum\n\nclass Key(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nclass Parent1:\n    child: Union[Child1, Child2]\nclass Parent2:\n    child: Union[Child2, Child3]\nclass Parent3:\n    child: Union[Child3, Child1]\n\nclass Child1:\n    main: Literal[Key.A]\n    same_for_1_and_2: Literal[Key.A]\nclass Child2:\n    main: Literal[Key.B]\n    same_for_1_and_2: Literal[Key.A]\nclass Child3:\n    main: Literal[Key.C]\n    same_for_1_and_2: Literal[Key.B]\n\nx: Union[Parent1, Parent2, Parent3]\nif x.child.main is Key.A:\n    reveal_type(x)          # N: Revealed type is \"__main__.Parent1 | __main__.Parent3\"\n    reveal_type(x.child)    # N: Revealed type is \"__main__.Child1\"\nelse:\n    reveal_type(x)          # N: Revealed type is \"__main__.Parent1 | __main__.Parent2 | __main__.Parent3\"\n    reveal_type(x.child)    # N: Revealed type is \"__main__.Child2 | __main__.Child3\"\n\nif x.child.same_for_1_and_2 is Key.A:\n    reveal_type(x)          # N: Revealed type is \"__main__.Parent1 | __main__.Parent2 | __main__.Parent3\"\n    reveal_type(x.child)    # N: Revealed type is \"__main__.Child1 | __main__.Child2\"\nelse:\n    reveal_type(x)          # N: Revealed type is \"__main__.Parent2 | __main__.Parent3\"\n    reveal_type(x.child)    # N: Revealed type is \"__main__.Child3\"\n\ny: Union[Parent1, Parent2]\nif y.child.main is Key.A:\n    reveal_type(y)          # N: Revealed type is \"__main__.Parent1\"\n    reveal_type(y.child)    # N: Revealed type is \"__main__.Child1\"\nelse:\n    reveal_type(y)          # N: Revealed type is \"__main__.Parent1 | __main__.Parent2\"\n    reveal_type(y.child)    # N: Revealed type is \"__main__.Child2 | __main__.Child3\"\n\nif y.child.same_for_1_and_2 is Key.A:\n    reveal_type(y)          # N: Revealed type is \"__main__.Parent1 | __main__.Parent2\"\n    reveal_type(y.child)    # N: Revealed type is \"__main__.Child1 | __main__.Child2\"\nelse:\n    reveal_type(y)          # N: Revealed type is \"__main__.Parent2\"\n    reveal_type(y.child)    # N: Revealed type is \"__main__.Child3\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingParentsHierarchyGenerics]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Generic, TypeVar, Union\n\nT = TypeVar('T')\nclass Model(Generic[T]):\n    attr: T\nclass A:\n    model: Model[int]\nclass B:\n    model: Model[str]\n\nx: Union[A, B]\nif isinstance(x.model.attr, int):\n    reveal_type(x)          # N: Revealed type is \"__main__.A\"\n    reveal_type(x.model)    # N: Revealed type is \"__main__.Model[builtins.int]\"\nelse:\n    reveal_type(x)          # N: Revealed type is \"__main__.B\"\n    reveal_type(x.model)    # N: Revealed type is \"__main__.Model[builtins.str]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowingParentsHierarchyTypedDict]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, TypedDict, Union\nfrom enum import Enum\n\nclass Key(Enum):\n    A = 1\n    B = 2\n    C = 3\n\nclass Parent1(TypedDict):\n    model: Model1\n    foo: int\n\nclass Parent2(TypedDict):\n    model: Model2\n    bar: str\n\nclass Model1(TypedDict):\n    key: Literal[Key.A]\n\nclass Model2(TypedDict):\n    key: Literal[Key.B]\n\nx: Union[Parent1, Parent2]\nif x[\"model\"][\"key\"] is Key.A:\n    reveal_type(x)              # N: Revealed type is \"TypedDict('__main__.Parent1', {'model': TypedDict('__main__.Model1', {'key': Literal[__main__.Key.A]}), 'foo': builtins.int})\"\n    reveal_type(x[\"model\"])     # N: Revealed type is \"TypedDict('__main__.Model1', {'key': Literal[__main__.Key.A]})\"\nelse:\n    reveal_type(x)              # N: Revealed type is \"TypedDict('__main__.Parent2', {'model': TypedDict('__main__.Model2', {'key': Literal[__main__.Key.B]}), 'bar': builtins.str})\"\n    reveal_type(x[\"model\"])     # N: Revealed type is \"TypedDict('__main__.Model2', {'key': Literal[__main__.Key.B]})\"\n\ny: Union[Parent1, Parent2]\nif y[\"model\"][\"key\"] is Key.C:  # E: Non-overlapping identity check (left operand type: \"Literal[Key.A, Key.B]\", right operand type: \"Literal[Key.C]\")\n    reveal_type(y)              # E: Statement is unreachable\n    reveal_type(y[\"model\"])\nelse:\n    reveal_type(y)              # N: Revealed type is \"TypedDict('__main__.Parent1', {'model': TypedDict('__main__.Model1', {'key': Literal[__main__.Key.A]}), 'foo': builtins.int}) | TypedDict('__main__.Parent2', {'model': TypedDict('__main__.Model2', {'key': Literal[__main__.Key.B]}), 'bar': builtins.str})\"\n    reveal_type(y[\"model\"])     # N: Revealed type is \"TypedDict('__main__.Model1', {'key': Literal[__main__.Key.A]}) | TypedDict('__main__.Model2', {'key': Literal[__main__.Key.B]})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNarrowingParentsHierarchyTypedDictWithStr]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, TypedDict, Union\n\nclass Parent1(TypedDict):\n    model: Model1\n    foo: int\n\nclass Parent2(TypedDict):\n    model: Model2\n    bar: str\n\nclass Model1(TypedDict):\n    key: Literal['A']\n\nclass Model2(TypedDict):\n    key: Literal['B']\n\nx: Union[Parent1, Parent2]\nif x[\"model\"][\"key\"] == 'A':\n    reveal_type(x)              # N: Revealed type is \"TypedDict('__main__.Parent1', {'model': TypedDict('__main__.Model1', {'key': Literal['A']}), 'foo': builtins.int})\"\n    reveal_type(x[\"model\"])     # N: Revealed type is \"TypedDict('__main__.Model1', {'key': Literal['A']})\"\nelse:\n    reveal_type(x)              # N: Revealed type is \"TypedDict('__main__.Parent2', {'model': TypedDict('__main__.Model2', {'key': Literal['B']}), 'bar': builtins.str})\"\n    reveal_type(x[\"model\"])     # N: Revealed type is \"TypedDict('__main__.Model2', {'key': Literal['B']})\"\n\ny: Union[Parent1, Parent2]\nif y[\"model\"][\"key\"] == 'C':  # E: Non-overlapping equality check (left operand type: \"Literal['A', 'B']\", right operand type: \"Literal['C']\")\n    reveal_type(y)              # E: Statement is unreachable\n    reveal_type(y[\"model\"])\nelse:\n    reveal_type(y)              # N: Revealed type is \"TypedDict('__main__.Parent1', {'model': TypedDict('__main__.Model1', {'key': Literal['A']}), 'foo': builtins.int}) | TypedDict('__main__.Parent2', {'model': TypedDict('__main__.Model2', {'key': Literal['B']}), 'bar': builtins.str})\"\n    reveal_type(y[\"model\"])     # N: Revealed type is \"TypedDict('__main__.Model1', {'key': Literal['A']}) | TypedDict('__main__.Model2', {'key': Literal['B']})\"\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNarrowingExprPropagation]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Union\n\nclass A:\n    tag: Literal['A']\n\nclass B:\n    tag: Literal['B']\n\nabo: Union[A, B, None]\n\nif abo is not None and abo.tag == \"A\":\n    reveal_type(abo.tag) # N: Revealed type is \"Literal['A']\"\n    reveal_type(abo) # N: Revealed type is \"__main__.A\"\n\nif not (abo is None or abo.tag != \"B\"):\n    reveal_type(abo.tag) # N: Revealed type is \"Literal['B']\"\n    reveal_type(abo) # N: Revealed type is \"__main__.B\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingEqualityFlipFlop]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Final, Literal\nfrom enum import Enum\n\nclass State(Enum):\n    A = 1\n    B = 2\n\nclass FlipFlopEnum:\n    def __init__(self) -> None:\n        self.state = State.A\n\n    def mutate(self) -> None:\n        self.state = State.B if self.state == State.A else State.A\n\nclass FlipFlopStr:\n    def __init__(self) -> None:\n        self.state = \"state-1\"\n\n    def mutate(self) -> None:\n        self.state = \"state-2\" if self.state == \"state-1\" else \"state-1\"\n\n\ndef test1(switch: FlipFlopStr) -> None:\n    # Naively, we might assume the 'assert' here would narrow the type to\n    # Literal[\"state-1\"]. However, doing this ends up breaking a fair number of real-world\n    # code (usually test cases) that looks similar to this function: e.g. checks\n    # to make sure a field was mutated to some particular value.\n    #\n    # And since mypy can't really reason about state mutation, we take a conservative\n    # approach and avoid narrowing anything here.\n\n    assert switch.state == \"state-1\"\n    reveal_type(switch.state)          # N: Revealed type is \"builtins.str\"\n\n    switch.mutate()\n\n    assert switch.state == \"state-2\"\n    reveal_type(switch.state)          # N: Revealed type is \"builtins.str\"\n\ndef test2(switch: FlipFlopEnum) -> None:\n    # This is the same thing as 'test1', except we use enums, which we allow to be narrowed\n    # to literals.\n\n    assert switch.state == State.A\n    reveal_type(switch.state)          # N: Revealed type is \"Literal[__main__.State.A]\"\n\n    switch.mutate()\n\n    assert switch.state == State.B     # E: Non-overlapping equality check (left operand type: \"Literal[State.A]\", right operand type: \"Literal[State.B]\")\n    reveal_type(switch.state)          # E: Statement is unreachable\n\ndef test3(switch: FlipFlopEnum) -> None:\n    # Same thing, but using 'is' comparisons. Previously mypy's behaviour differed\n    # here, narrowing when using 'is', but not when using '=='.\n\n    assert switch.state is State.A\n    reveal_type(switch.state)          # N: Revealed type is \"Literal[__main__.State.A]\"\n\n    switch.mutate()\n\n    assert switch.state is State.B     # E: Non-overlapping identity check (left operand type: \"Literal[State.A]\", right operand type: \"Literal[State.B]\")\n    reveal_type(switch.state)          # E: Statement is unreachable\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingEqualityRequiresExplicitStrLiteral]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Final, Literal\n\nA_final: Final = \"A\"\nA_literal: Literal[\"A\"]\n\n# Neither the LHS nor the RHS are explicit literals, so regrettably nothing\n# is narrowed here -- see 'testNarrowingEqualityFlipFlop' for an example of\n# why more precise inference here is problematic.\nx_str: str\nif x_str == \"A\":\n    reveal_type(x_str)  # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(x_str)  # N: Revealed type is \"builtins.str\"\nreveal_type(x_str)      # N: Revealed type is \"builtins.str\"\n\nif x_str == A_final:\n    reveal_type(x_str)  # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(x_str)  # N: Revealed type is \"builtins.str\"\nreveal_type(x_str)      # N: Revealed type is \"builtins.str\"\n\n# But the RHS is a literal, so we can at least narrow the 'if' case now.\nif x_str == A_literal:\n    reveal_type(x_str)  # N: Revealed type is \"Literal['A']\"\nelse:\n    reveal_type(x_str)  # N: Revealed type is \"builtins.str\"\nreveal_type(x_str)      # N: Revealed type is \"builtins.str\"\n\n# But in these two cases, the LHS is a literal/literal-like type. So we\n# assume the user *does* want literal-based narrowing and narrow accordingly\n# regardless of whether the RHS is an explicit literal or not.\nx_union: Literal[\"A\", \"B\", None]\nif x_union == A_final:\n    reveal_type(x_union)  # N: Revealed type is \"Literal['A']\"\nelse:\n    reveal_type(x_union)  # N: Revealed type is \"Literal['B'] | None\"\nreveal_type(x_union)      # N: Revealed type is \"Literal['A'] | Literal['B'] | None\"\n\nif x_union == A_literal:\n    reveal_type(x_union)  # N: Revealed type is \"Literal['A']\"\nelse:\n    reveal_type(x_union)  # N: Revealed type is \"Literal['B'] | None\"\nreveal_type(x_union)      # N: Revealed type is \"Literal['A'] | Literal['B'] | None\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingEqualityRequiresExplicitEnumLiteral]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Final, Literal, Union\nfrom enum import Enum\n\nclass Foo(Enum):\n    A = 1\n    B = 2\n\nA_final: Final = Foo.A\nA_literal: Literal[Foo.A]\n\n# Note this is unlike testNarrowingEqualityRequiresExplicitStrLiteral\n# See also testNarrowingEqualityFlipFlop\nx1: Foo\nif x1 == Foo.A:\n    reveal_type(x1)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelse:\n    reveal_type(x1)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\n\nx2: Foo\nif x2 == A_final:\n    reveal_type(x2)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelse:\n    reveal_type(x2)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\n\n# But we let this narrow since there's an explicit literal in the RHS.\nx3: Foo\nif x3 == A_literal:\n    reveal_type(x3)  # N: Revealed type is \"Literal[__main__.Foo.A]\"\nelse:\n    reveal_type(x3)  # N: Revealed type is \"Literal[__main__.Foo.B]\"\n\n\nclass SingletonFoo(Enum):\n    A = \"A\"\n\ndef bar(x: Union[SingletonFoo, Foo], y: SingletonFoo) -> None:\n    if x == y:\n        reveal_type(x)  # N: Revealed type is \"Literal[__main__.SingletonFoo.A]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingEqualityCustomEqualityDisabled]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Union\n\nclass Custom:\n    def __eq__(self, other: object) -> bool: return True\n\ndef f1(x: Union[Custom, Literal[1], Literal[2]]):\n    if x == 1:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | Literal[1]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | Literal[2]\"\n\nclass Default: pass\n\ndef f2(x: Union[Default, Literal[1], Literal[2]]):\n    if x == 1:\n        reveal_type(x)  # N: Revealed type is \"Literal[1]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.Default | Literal[2]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingEqualityCustomEqualityEnum]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Union\nfrom enum import Enum\n\nclass CustomEnum(Enum):\n    A = 1\n    B = 2\n\n    def __eq__(self, other: object) -> bool: return True\n\nx3: CustomEnum\nkey: Literal[CustomEnum.A]\nif x3 == key:\n    reveal_type(x3)  # N: Revealed type is \"__main__.CustomEnum\"\nelse:\n    reveal_type(x3)  # N: Revealed type is \"Literal[__main__.CustomEnum.B]\"\n\n# For comparison, this narrows since we bypass __eq__\nif x3 is key:\n    reveal_type(x3)  # N: Revealed type is \"Literal[__main__.CustomEnum.A]\"\nelse:\n    reveal_type(x3)  # N: Revealed type is \"Literal[__main__.CustomEnum.B]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingEqualityCustomEqualityChainedComparison]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Union\n\nclass Custom:\n    def __eq__(self, other: object) -> bool: return True\n\ndef f1(x: Literal[1, 2, None], y: Custom):\n    if 1 == x == y:\n        reveal_type(x)   # N: Revealed type is \"Literal[1]\"\n        reveal_type(y)   # N: Revealed type is \"__main__.Custom\"\n    else:\n        reveal_type(x)   # N: Revealed type is \"Literal[1] | Literal[2] | None\"\n        reveal_type(y)   # N: Revealed type is \"__main__.Custom\"\n\nclass Default: pass\n\ndef f2(x: Literal[1, 2, None], z: Default):\n    if 1 == x == z:      # E: Non-overlapping equality check (left operand type: \"Literal[1, 2] | None\", right operand type: \"Default\")\n        reveal_type(x)   # E: Statement is unreachable\n        reveal_type(z)\n    else:\n        reveal_type(x)   # N: Revealed type is \"Literal[1] | Literal[2] | None\"\n        reveal_type(z)   # N: Revealed type is \"__main__.Default\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingCustomEqualityLiteralElseBranch]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Literal\n\nclass Custom:\n    def __eq__(self, other: object) -> bool:\n        raise\n\ndef f(v: Custom | Literal[\"text\"]) -> Custom | None:\n    if v == \"text\":\n        reveal_type(v)  # N: Revealed type is \"__main__.Custom | Literal['text']\"\n        return None\n    else:\n        reveal_type(v)  # N: Revealed type is \"__main__.Custom\"\n        return v\n\ndef g(v: Custom | Literal[\"text\"]) -> Custom | None:\n    if v != \"text\":\n        reveal_type(v)  # N: Revealed type is \"__main__.Custom\"\n        return None\n    else:\n        reveal_type(v)  # N: Revealed type is \"__main__.Custom | Literal['text']\"\n        return v  # E: Incompatible return value type (got \"Custom | Literal['text']\", expected \"Custom | None\")\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingCustomEqualityUnion]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Any\n\ndef realistic(x: dict[str, Any]):\n    val = x.get(\"hey\")\n    if val == 12:\n        reveal_type(val)  # N: Revealed type is \"Any | Literal[12]?\"\n\ndef f1(x: Any | None):\n    if x == 12:\n        reveal_type(x)  # N: Revealed type is \"Any | Literal[12]?\"\n\nclass Custom:\n    def __eq__(self, other: object) -> bool:\n        raise\n\ndef f2(x: Custom | None):\n    if x == 12:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | None\"\n[builtins fixtures/dict.pyi]\n\n[case testNarrowingCustomEqualityUnion2]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Any\n\nclass Custom:\n    def __eq__(self, other: object) -> bool:\n        raise\n\ndef f3(x: str | Custom, y: str | int):\n    if x == y:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | __main__.Custom\"\n        reveal_type(y)  # N: Revealed type is \"builtins.str | builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | __main__.Custom\"\n        reveal_type(y)  # N: Revealed type is \"builtins.str | builtins.int\"\n\ndef f4(x: str | Any, y: str | int):\n    if x == y:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | Any | builtins.int\"\n        reveal_type(y)  # N: Revealed type is \"builtins.str | builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | Any\"\n        reveal_type(y)  # N: Revealed type is \"builtins.str | builtins.int\"\n[builtins fixtures/dict.pyi]\n\n[case testNarrowingCustomEqualityUnion3]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Any\n\nclass Custom:\n    def __eq__(self, other: object) -> bool:\n        raise\n\ndef f(x: Custom | None, y: int | None):\n    if x == y:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | None\"\n        reveal_type(y)  # N: Revealed type is \"builtins.int | None\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | None\"\n        reveal_type(y)  # N: Revealed type is \"builtins.int | None\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingCustomEqualityUnion4]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\n\nclass Custom:\n    def __eq__(self, other: object) -> bool:\n        return True\n\ndef f(x: Custom | None, y: Custom):\n    if x == y:\n        # We unsoundly special case None and narrow x to Custom here\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | None\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingCustomEqualityUnion5]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Any\n\nclass Custom1:\n    def __eq__(self, other: object) -> bool:\n        raise\n\nclass Custom2:\n    def __eq__(self, other: object) -> bool:\n        raise\n\ndef f(x: Custom1 | int, y: Custom2 | int):\n    if x == y:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom1 | builtins.int\"\n        reveal_type(y)  # N: Revealed type is \"__main__.Custom2 | builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom1 | builtins.int\"\n        reveal_type(y)  # N: Revealed type is \"__main__.Custom2 | builtins.int\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingCustomEqualitySubclass]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Any\n\nclass Custom:\n    def __eq__(self, other: object) -> bool:\n        raise\n\nclass CustomSub(Custom):\n    def __eq__(self, other: object) -> bool:\n        raise\n\ndef f(x: Custom, y: CustomSub):\n    if x == y:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom\"\n        reveal_type(y)  # N: Revealed type is \"__main__.CustomSub\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom\"\n        reveal_type(y)  # N: Revealed type is \"__main__.CustomSub\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingCustomEqualityGeneric]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Union\n\nclass Custom:\n    def __eq__(self, other: object) -> bool:\n        raise\n\nclass Default: ...\n\ndef f1(x: list[Custom] | Default, y: list[int]):\n    if x == y:  # E: Non-overlapping equality check (left operand type: \"list[Custom] | Default\", right operand type: \"list[int]\")\n        reveal_type(x)  # N: Revealed type is \"builtins.list[__main__.Custom]\"\n        reveal_type(y)  # N: Revealed type is \"builtins.list[builtins.int]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.list[__main__.Custom] | __main__.Default\"\n        reveal_type(y)  # N: Revealed type is \"builtins.list[builtins.int]\"\n\nf1([], [])\n\ndef f2(x: list[Custom] | Default, y: list[int] | list[Default]):\n    if x == y:  # E: Non-overlapping equality check (left operand type: \"list[Custom] | Default\", right operand type: \"list[int] | list[Default]\")\n        reveal_type(x)  # N: Revealed type is \"builtins.list[__main__.Custom]\"\n        reveal_type(y)  # N: Revealed type is \"builtins.list[builtins.int] | builtins.list[__main__.Default]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.list[__main__.Custom] | __main__.Default\"\n        reveal_type(y)  # N: Revealed type is \"builtins.list[builtins.int] | builtins.list[__main__.Default]\"\n\nlistcustom_or_default = Union[list[Custom], Default]\nlistint_or_default = Union[list[int], list[Default]]\n\ndef f2_with_alias(x: listcustom_or_default, y: listint_or_default):\n    if x == y:  # E: Non-overlapping equality check (left operand type: \"list[Custom] | Default\", right operand type: \"list[int] | list[Default]\")\n        reveal_type(x)  # N: Revealed type is \"builtins.list[__main__.Custom]\"\n        reveal_type(y)  # N: Revealed type is \"builtins.list[builtins.int] | builtins.list[__main__.Default]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.list[__main__.Custom] | __main__.Default\"\n        reveal_type(y)  # N: Revealed type is \"builtins.list[builtins.int] | builtins.list[__main__.Default]\"\n\ndef f3(x: Custom | dict[str, str], y: dict[int, int]):\n    if x == y:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | builtins.dict[builtins.str, builtins.str]\"\n        reveal_type(y)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.int]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | builtins.dict[builtins.str, builtins.str]\"\n        reveal_type(y)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.int]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingRecursiveCallable]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Callable\n\nclass A: ...\nclass B: ...\n\nT = Callable[[A], \"S\"]\nS = Callable[[B], \"T\"]\n\ndef f(x: S, y: T):\n    if x == y:  # E: Unsupported left operand type for == (\"Callable[[B], T]\")\n        reveal_type(x)  # E: Statement is unreachable\n        reveal_type(y)\n    else:\n        reveal_type(x)  # N: Revealed type is \"def (__main__.B) -> def (__main__.A) -> ...\"\n        reveal_type(y)  # N: Revealed type is \"def (__main__.A) -> def (__main__.B) -> ...\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingRecursiveUnion]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Union\n\nclass A: ...\nclass B: ...\n\nT = Union[A, \"S\"]\nS = Union[B, \"T\"]  # E: Invalid recursive alias: a union item of itself\n\ndef f(x: S, y: T):\n    if x == y:\n        reveal_type(x)  # N: Revealed type is \"Any\"\n        reveal_type(y)  # N: Revealed type is \"__main__.A | Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingUnreachableCases]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Union\n\na: Literal[1]\nb: Literal[1, 2]\nc: Literal[2, 3]\n\nif a == b == c:\n    reveal_type(a)  # E: Statement is unreachable\n    reveal_type(b)\n    reveal_type(c)\nelse:\n    reveal_type(a)  # N: Revealed type is \"Literal[1]\"\n    reveal_type(b)  # N: Revealed type is \"Literal[1] | Literal[2]\"\n    reveal_type(c)  # N: Revealed type is \"Literal[2] | Literal[3]\"\n\nif a == a == a:\n    reveal_type(a)  # N: Revealed type is \"Literal[1]\"\nelse:\n    reveal_type(a)  # E: Statement is unreachable\n\nif a == a == b:\n    reveal_type(a)  # N: Revealed type is \"Literal[1]\"\n    reveal_type(b)  # N: Revealed type is \"Literal[1]\"\nelse:\n    reveal_type(a)  # N: Revealed type is \"Literal[1]\"\n    reveal_type(b)  # N: Revealed type is \"Literal[2]\"\n\n# In this case, it's ok for 'b' to narrow down to Literal[1] in the else case\n# since that's the only way 'b == 2' can be false\nif b == 2:\n    reveal_type(b)  # N: Revealed type is \"Literal[2]\"\nelse:\n    reveal_type(b)  # N: Revealed type is \"Literal[1]\"\n\n# But in this case, we can't conclude anything about the else case. This expression\n# could end up being either '2 == 2 == 3' or '1 == 2 == 2', which means we can't\n# conclude anything.\nif b == 2 == c:\n    reveal_type(b)  # N: Revealed type is \"Literal[2]\"\n    reveal_type(c)  # N: Revealed type is \"Literal[2]\"\nelse:\n    reveal_type(b)  # N: Revealed type is \"Literal[1] | Literal[2]\"\n    reveal_type(c)  # N: Revealed type is \"Literal[2] | Literal[3]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingUnreachableCases2]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Union\n\na: Literal[1, 2, 3, 4]\nb: Literal[1, 2, 3, 4]\n\nif a == b == 1:\n    reveal_type(a)  # N: Revealed type is \"Literal[1]\"\n    reveal_type(b)  # N: Revealed type is \"Literal[1]\"\nelif a == b == 2:\n    reveal_type(a)  # N: Revealed type is \"Literal[2]\"\n    reveal_type(b)  # N: Revealed type is \"Literal[2]\"\nelif a == b == 3:\n    reveal_type(a)  # N: Revealed type is \"Literal[3]\"\n    reveal_type(b)  # N: Revealed type is \"Literal[3]\"\nelif a == b == 4:\n    reveal_type(a)  # N: Revealed type is \"Literal[4]\"\n    reveal_type(b)  # N: Revealed type is \"Literal[4]\"\nelse:\n    # This branch is reachable if a == 1 and b == 2, for example.\n    reveal_type(a)  # N: Revealed type is \"Literal[1] | Literal[2] | Literal[3] | Literal[4]\"\n    reveal_type(b)  # N: Revealed type is \"Literal[1] | Literal[2] | Literal[3] | Literal[4]\"\n\nif a == a == 1:\n    reveal_type(a)  # N: Revealed type is \"Literal[1]\"\nelif a == a == 2:\n    reveal_type(a)  # N: Revealed type is \"Literal[2]\"\nelif a == a == 3:\n    reveal_type(a)  # N: Revealed type is \"Literal[3]\"\nelif a == a == 4:\n    reveal_type(a)  # N: Revealed type is \"Literal[4]\"\nelse:\n    # In contrast, this branch must be unreachable: we assume (maybe naively)\n    # that 'a' won't be mutated in the middle of the expression.\n    reveal_type(a)  # E: Statement is unreachable\n    reveal_type(b)\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingLiteralTruthiness]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Union\n\nstr_or_false: Union[Literal[False], str]\n\nif str_or_false:\n    reveal_type(str_or_false)   # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(str_or_false)   # N: Revealed type is \"Literal[False] | Literal['']\"\n\ntrue_or_false: Literal[True, False]\n\nif true_or_false:\n    reveal_type(true_or_false)  # N: Revealed type is \"Literal[True]\"\nelse:\n    reveal_type(true_or_false)  # N: Revealed type is \"Literal[False]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingFalseyToLiteral]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union\n\na: str\nb: bytes\nc: int\nd: Union[str, bytes, int]\n\nif not a:\n    reveal_type(a)  # N: Revealed type is \"Literal['']\"\nif not b:\n    reveal_type(b)  # N: Revealed type is \"Literal[b'']\"\nif not c:\n    reveal_type(c)  # N: Revealed type is \"Literal[0]\"\nif not d:\n    reveal_type(d)  # N: Revealed type is \"Literal[''] | Literal[b''] | Literal[0]\"\n\n[case testNarrowingIsInstanceFinalSubclass]\n# flags: --strict-equality --warn-unreachable\n\nfrom typing import final\n\nclass N: ...\n@final\nclass F1: ...\n@final\nclass F2: ...\n\nn: N\nf1: F1\n\nif isinstance(f1, F1):\n    reveal_type(f1)  # N: Revealed type is \"__main__.F1\"\nelse:\n    reveal_type(f1)  # E: Statement is unreachable\n\nif isinstance(n, F1):  # E: Subclass of \"N\" and \"F1\" cannot exist: \"F1\" is final\n    reveal_type(n)  # E: Statement is unreachable\nelse:\n    reveal_type(n)  # N: Revealed type is \"__main__.N\"\n\nif isinstance(f1, N):  # E: Subclass of \"F1\" and \"N\" cannot exist: \"F1\" is final\n    reveal_type(f1)  # E: Statement is unreachable\nelse:\n    reveal_type(f1)  # N: Revealed type is \"__main__.F1\"\n\nif isinstance(f1, F2):  # E: Subclass of \"F1\" and \"F2\" cannot exist: \"F1\" is final \\\n                        # E: Subclass of \"F1\" and \"F2\" cannot exist: \"F2\" is final\n    reveal_type(f1)  # E: Statement is unreachable\nelse:\n    reveal_type(f1)  # N: Revealed type is \"__main__.F1\"\n[builtins fixtures/isinstance.pyi]\n\n\n[case testNarrowingIsInstanceFinalSubclassWithUnions]\n# flags: --strict-equality --warn-unreachable\n\nfrom typing import final, Union\n\nclass N: ...\n@final\nclass F1: ...\n@final\nclass F2: ...\n\nn_f1: Union[N, F1]\nn_f2: Union[N, F2]\nf1_f2: Union[F1, F2]\n\nif isinstance(n_f1, F1):\n    reveal_type(n_f1)  # N: Revealed type is \"__main__.F1\"\nelse:\n    reveal_type(n_f1)  # N: Revealed type is \"__main__.N\"\n\nif isinstance(n_f2, F1):  # E: Subclass of \"N\" and \"F1\" cannot exist: \"F1\" is final \\\n                          # E: Subclass of \"F2\" and \"F1\" cannot exist: \"F2\" is final \\\n                          # E: Subclass of \"F2\" and \"F1\" cannot exist: \"F1\" is final\n    reveal_type(n_f2)  # E: Statement is unreachable\nelse:\n    reveal_type(n_f2)  # N: Revealed type is \"__main__.N | __main__.F2\"\n\nif isinstance(f1_f2, F1):\n    reveal_type(f1_f2)  # N: Revealed type is \"__main__.F1\"\nelse:\n    reveal_type(f1_f2)  # N: Revealed type is \"__main__.F2\"\n[builtins fixtures/isinstance.pyi]\n\n\n[case testNarrowingIsSubclassFinalSubclassWithTypeVar]\n# flags: --strict-equality --warn-unreachable\n\nfrom typing import final, Type, TypeVar\n\n@final\nclass A: ...\n@final\nclass B: ...\n\nT = TypeVar(\"T\", A, B)\n\ndef f(cls: Type[T]) -> T:\n    if issubclass(cls, A):\n        reveal_type(cls)  # N: Revealed type is \"type[__main__.A]\"\n        x: bool\n        if x:\n            return A()\n        else:\n            return B()  # E: Incompatible return value type (got \"B\", expected \"A\")\n    assert False\n\nreveal_type(f(A))  # N: Revealed type is \"__main__.A\"\nreveal_type(f(B))  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/isinstance.pyi]\n\n\n[case testNarrowingLiteralIdentityCheck]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Union\n\nstr_or_false: Union[Literal[False], str]\n\nif str_or_false is not False:\n    reveal_type(str_or_false)   # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(str_or_false)   # N: Revealed type is \"Literal[False]\"\n\nif str_or_false is False:\n    reveal_type(str_or_false)  # N: Revealed type is \"Literal[False]\"\nelse:\n    reveal_type(str_or_false)  # N: Revealed type is \"builtins.str\"\n\nstr_or_true: Union[Literal[True], str]\n\nif str_or_true is True:\n    reveal_type(str_or_true)  # N: Revealed type is \"Literal[True]\"\nelse:\n    reveal_type(str_or_true)  # N: Revealed type is \"builtins.str\"\n\nif str_or_true is not True:\n    reveal_type(str_or_true)  # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(str_or_true)  # N: Revealed type is \"Literal[True]\"\n\nstr_or_bool_literal: Union[Literal[False], Literal[True], str]\n\nif str_or_bool_literal is not True:\n    reveal_type(str_or_bool_literal)  # N: Revealed type is \"Literal[False] | builtins.str\"\nelse:\n    reveal_type(str_or_bool_literal)  # N: Revealed type is \"Literal[True]\"\n\nif str_or_bool_literal is not True and str_or_bool_literal is not False:\n    reveal_type(str_or_bool_literal)  # N: Revealed type is \"builtins.str\"\nelse:\n    reveal_type(str_or_bool_literal)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingBooleanIdentityCheck]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Optional\n\nbool_val: bool\n\nif bool_val is not False:\n    reveal_type(bool_val)   # N: Revealed type is \"Literal[True]\"\nelse:\n    reveal_type(bool_val)   # N: Revealed type is \"Literal[False]\"\n\nopt_bool_val: Optional[bool]\n\nif opt_bool_val is not None:\n    reveal_type(opt_bool_val)   # N: Revealed type is \"builtins.bool\"\n\nif opt_bool_val is not False:\n    reveal_type(opt_bool_val)   # N: Revealed type is \"Literal[True] | None\"\nelse:\n    reveal_type(opt_bool_val)   # N: Revealed type is \"Literal[False]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingBooleanTruthiness]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Optional\n\nbool_val: bool\n\nif bool_val:\n    reveal_type(bool_val)   # N: Revealed type is \"Literal[True]\"\nelse:\n    reveal_type(bool_val)   # N: Revealed type is \"Literal[False]\"\nreveal_type(bool_val)  # N: Revealed type is \"builtins.bool\"\n\nopt_bool_val: Optional[bool]\n\nif opt_bool_val:\n    reveal_type(opt_bool_val)   # N: Revealed type is \"Literal[True]\"\nelse:\n    reveal_type(opt_bool_val)   # N: Revealed type is \"Literal[False] | None\"\nreveal_type(opt_bool_val)   # N: Revealed type is \"builtins.bool | None\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingBooleanBoolOp]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Optional\n\nbool_a: bool\nbool_b: bool\n\nif bool_a and bool_b:\n   reveal_type(bool_a) # N: Revealed type is \"Literal[True]\"\n   reveal_type(bool_b) # N: Revealed type is \"Literal[True]\"\nelse:\n   reveal_type(bool_a) # N: Revealed type is \"builtins.bool\"\n   reveal_type(bool_b) # N: Revealed type is \"builtins.bool\"\n\nif not bool_a or bool_b:\n   reveal_type(bool_a) # N: Revealed type is \"builtins.bool\"\n   reveal_type(bool_b) # N: Revealed type is \"builtins.bool\"\nelse:\n   reveal_type(bool_a) # N: Revealed type is \"Literal[True]\"\n   reveal_type(bool_b) # N: Revealed type is \"Literal[False]\"\n\nif True and bool_b:\n   reveal_type(bool_b) # N: Revealed type is \"Literal[True]\"\n\nx = True and bool_b\nreveal_type(x) # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingTypedDictUsingEnumLiteral]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, TypedDict, Union\nfrom enum import Enum\n\nclass E(Enum):\n    FOO = \"a\"\n    BAR = \"b\"\n\nclass Foo(TypedDict):\n    tag: Literal[E.FOO]\n    x: int\n\nclass Bar(TypedDict):\n    tag: Literal[E.BAR]\n    y: int\n\ndef f(d: Union[Foo, Bar]) -> None:\n    assert d['tag'] == E.FOO\n    d['x']\n    reveal_type(d)  # N: Revealed type is \"TypedDict('__main__.Foo', {'tag': Literal[__main__.E.FOO], 'x': builtins.int})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNarrowingUsingMetaclass]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Type\n\nclass M(type):\n    pass\n\nclass C: pass\n\ndef f(t: Type[C]) -> None:\n    if type(t) is M:\n        reveal_type(t)  # N: Revealed type is \"type[__main__.C]\"\n    else:\n        reveal_type(t)  # N: Revealed type is \"type[__main__.C]\"\n    if type(t) is not M:\n        reveal_type(t)  # N: Revealed type is \"type[__main__.C]\"\n    else:\n        reveal_type(t)  # N: Revealed type is \"type[__main__.C]\"\n    reveal_type(t)  # N: Revealed type is \"type[__main__.C]\"\n\n[case testNarrowingUsingTypeVar]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Type, TypeVar\n\nclass A: pass\nclass B(A): pass\n\nT = TypeVar(\"T\", bound=A)\n\ndef f(t: Type[T], a: A, b: B) -> None:\n    if type(a) is t:\n        reveal_type(a)  # N: Revealed type is \"T`-1\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"__main__.A\"\n\n    if type(b) is t:\n        reveal_type(b)  # N: Revealed type is \"T`-1\"\n    else:\n        reveal_type(b)  # N: Revealed type is \"__main__.B\"\n\n[case testNarrowingNestedUnionOfTypedDicts]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, TypedDict, Union\n\nclass A(TypedDict):\n    tag: Literal[\"A\"]\n    a: int\n\nclass B(TypedDict):\n    tag: Literal[\"B\"]\n    b: int\n\nclass C(TypedDict):\n    tag: Literal[\"C\"]\n    c: int\n\nAB = Union[A, B]\nABC = Union[AB, C]\nabc: ABC\n\nif abc[\"tag\"] == \"A\":\n    reveal_type(abc) # N: Revealed type is \"TypedDict('__main__.A', {'tag': Literal['A'], 'a': builtins.int})\"\nelif abc[\"tag\"] == \"C\":\n    reveal_type(abc) # N: Revealed type is \"TypedDict('__main__.C', {'tag': Literal['C'], 'c': builtins.int})\"\nelse:\n    reveal_type(abc) # N: Revealed type is \"TypedDict('__main__.B', {'tag': Literal['B'], 'b': builtins.int})\"\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNarrowingRuntimeCover]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Dict, List, Union\n\ndef unreachable(x: Union[str, List[str]]) -> None:\n    if isinstance(x, str):\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    elif isinstance(x, list):\n        reveal_type(x)  # N: Revealed type is \"builtins.list[builtins.str]\"\n    else:\n        reveal_type(x)  # No output: this branch is unreachable  # E: Statement is unreachable\n\ndef all_parts_covered(x: Union[str, List[str], List[int], int]) -> None:\n    if isinstance(x, str):\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    elif isinstance(x, list):\n        reveal_type(x)  # N: Revealed type is \"builtins.list[builtins.str] | builtins.list[builtins.int]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\ndef two_type_vars(x: Union[str, Dict[str, int], Dict[bool, object], int]) -> None:\n    if isinstance(x, str):\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    elif isinstance(x, dict):\n        reveal_type(x)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int] | builtins.dict[builtins.bool, builtins.object]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n\n\n[case testNarrowingWithDef]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Callable, Optional\n\ndef g() -> None:\n    foo: Optional[Callable[[], None]] = None\n    if foo is None:\n        def foo(): ...\n    foo()\n[builtins fixtures/dict.pyi]\n\n\n[case testNarrowingOptionalEqualsNone]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Optional\n\nclass A: ...\n\nval: Optional[A]\n\nif val == None:\n    reveal_type(val)  # N: Revealed type is \"None\"\nelse:\n    reveal_type(val)  # N: Revealed type is \"__main__.A\"\nif val != None:\n    reveal_type(val)  # N: Revealed type is \"__main__.A\"\nelse:\n    reveal_type(val)  # N: Revealed type is \"None\"\n\nif val in (None,):\n    reveal_type(val)  # N: Revealed type is \"None\"\nelse:\n    reveal_type(val)  # N: Revealed type is \"__main__.A\"\nif val not in (None,):\n    reveal_type(val)  # N: Revealed type is \"__main__.A\"\nelse:\n    reveal_type(val)  # N: Revealed type is \"None\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingCustomEqualityOptionalEqualsNone]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nclass Custom:\n    def __eq__(self, other) -> bool: ...\n\ndef f(x: Custom | None):\n    if x == None:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | None\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom\"\n    if x != None:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | None\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingWithTupleOfTypes]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple, Type\n\nclass Base: ...\n\nclass Impl1(Base): ...\nclass Impl2(Base): ...\n\nimpls: Tuple[Type[Base], ...] = (Impl1, Impl2)\nsome: object\n\nif isinstance(some, impls):\n    reveal_type(some)  # N: Revealed type is \"__main__.Base\"\nelse:\n    reveal_type(some)  # N: Revealed type is \"builtins.object\"\n\nraw: Tuple[type, ...]\nif isinstance(some, raw):\n    reveal_type(some)  # N: Revealed type is \"builtins.object\"\nelse:\n    reveal_type(some)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/dict.pyi]\n\n\n[case testNarrowingWithTupleOfTypesPy310Plus]\n# flags: --python-version 3.10 --strict-equality --warn-unreachable\nclass Base: ...\n\nclass Impl1(Base): ...\nclass Impl2(Base): ...\n\nsome: int | Base\n\nimpls: tuple[type[Base], ...] = (Impl1, Impl2)\nif isinstance(some, impls):\n    reveal_type(some)  # N: Revealed type is \"__main__.Base\"\nelse:\n    reveal_type(some)  # N: Revealed type is \"builtins.int | __main__.Base\"\n\nraw: tuple[type, ...]\nif isinstance(some, raw):\n    reveal_type(some)  # N: Revealed type is \"builtins.int | __main__.Base\"\nelse:\n    reveal_type(some)  # N: Revealed type is \"builtins.int | __main__.Base\"\n[builtins fixtures/dict.pyi]\n\n[case testNarrowingWithAnyOps]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\nclass C: ...\nclass D(C): ...\ntp: Any\n\nc: C\nif isinstance(c, tp) or isinstance(c, D):\n    reveal_type(c)  # N: Revealed type is \"Any | __main__.D\"\nelse:\n    reveal_type(c)  # N: Revealed type is \"__main__.C\"\nreveal_type(c)  # N: Revealed type is \"__main__.C\"\n\nc1: C\nif isinstance(c1, tp) and isinstance(c1, D):\n    reveal_type(c1)  # N: Revealed type is \"Any\"\nelse:\n    reveal_type(c1)  # N: Revealed type is \"__main__.C\"\nreveal_type(c1)  # N: Revealed type is \"__main__.C\"\n\nc2: C\nif isinstance(c2, D) or isinstance(c2, tp):\n    reveal_type(c2)  # N: Revealed type is \"__main__.D | Any\"\nelse:\n    reveal_type(c2)  # N: Revealed type is \"__main__.C\"\nreveal_type(c2)  # N: Revealed type is \"__main__.C\"\n\nc3: C\nif isinstance(c3, D) and isinstance(c3, tp):\n    reveal_type(c3)  # N: Revealed type is \"Any\"\nelse:\n    reveal_type(c3)  # N: Revealed type is \"__main__.C\"\nreveal_type(c3)  # N: Revealed type is \"__main__.C\"\n\nt: Any\nif isinstance(t, (list, tuple)) and isinstance(t, tuple):\n    reveal_type(t)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\nelse:\n    reveal_type(t)  # N: Revealed type is \"Any\"\nreveal_type(t)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testNarrowingAnyUnion]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom unknown import A, AA  # E: Cannot find implementation or library stub for module named \"unknown\" \\\n                           # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\nclass B: ...\n\ndef f(x: A | B) -> None:\n    if isinstance(x, (AA, B)):\n        reveal_type(x)  # N: Revealed type is \"Any | __main__.B\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testNarrowingLenItemAndLenCompare]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\nx: Any\nif len(x) == x:\n    reveal_type(x) # N: Revealed type is \"Any\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenTuple]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple, Union\n\nVarTuple = Union[Tuple[int, int], Tuple[int, int, int]]\n\nx: VarTuple\na = b = c = 0\nif len(x) == 3:\n    a, b, c = x\nelse:\n    a, b = x\n\nif len(x) != 3:\n    a, b = x\nelse:\n    a, b, c = x\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenHomogeneousTuple]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\n\nx: Tuple[int, ...]\nif len(x) == 3:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int, builtins.int]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n\nif len(x) != 3:\n    reveal_type(x) # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int, builtins.int]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenTypeUnaffected]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union, List\n\nx: Union[str, List[int]]\nif len(x) == 3:\n    reveal_type(x) # N: Revealed type is \"builtins.str | builtins.list[builtins.int]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"builtins.str | builtins.list[builtins.int]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenAnyListElseNotAffected]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\ndef f(self, value: Any) -> Any:\n    if isinstance(value, list) and len(value) == 0:\n        reveal_type(value) # N: Revealed type is \"builtins.list[Any]\"\n        return value\n    reveal_type(value) # N: Revealed type is \"Any\"\n    return None\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenMultiple]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple, Union\n\nVarTuple = Union[Tuple[int, int], Tuple[int, int, int]]\n\nx: VarTuple\ny: VarTuple\nif len(x) == len(y) == 3:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int, builtins.int]\"\n    reveal_type(y) # N: Revealed type is \"tuple[builtins.int, builtins.int, builtins.int]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenFinal]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Final, Tuple, Union\n\nVarTuple = Union[Tuple[int, int], Tuple[int, int, int]]\n\nx: VarTuple\nfin: Final = 3\nif len(x) == fin:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int, builtins.int]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenGreaterThan]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple, Union\n\nVarTuple = Union[Tuple[int], Tuple[int, int], Tuple[int, int, int]]\n\nx: VarTuple\nif len(x) > 1:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int]\"\n\nif len(x) < 2:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\n\nif len(x) >= 2:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int]\"\n\nif len(x) <= 2:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int] | tuple[builtins.int, builtins.int]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int, builtins.int]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenBothSidesUnionTuples]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple, Union\n\nVarTuple = Union[\n    Tuple[int],\n    Tuple[int, int],\n    Tuple[int, int, int],\n    Tuple[int, int, int, int],\n]\n\nx: VarTuple\nif 2 <= len(x) <= 3:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int] | tuple[builtins.int, builtins.int, builtins.int, builtins.int]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenGreaterThanHomogeneousTupleShort]\n# flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable\nfrom typing import Tuple\n\nVarTuple = Tuple[int, ...]\n\nx: VarTuple\nif len(x) < 3:\n    reveal_type(x) # N: Revealed type is \"tuple[()] | tuple[builtins.int] | tuple[builtins.int, builtins.int]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int, builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]\"\nreveal_type(x)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenBiggerThanHomogeneousTupleLong]\n# flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable\nfrom typing import Tuple\n\nVarTuple = Tuple[int, ...]\n\nx: VarTuple\nif len(x) < 30:\n    reveal_type(x) # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenBothSidesHomogeneousTuple]\n# flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable\nfrom typing import Tuple\n\nx: Tuple[int, ...]\nif 1 < len(x) < 4:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"tuple[()] | tuple[builtins.int] | tuple[builtins.int, builtins.int, builtins.int, builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]\"\nreveal_type(x)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenUnionTupleUnreachable]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple, Union\n\nx: Union[Tuple[int, int], Tuple[int, int, int]]\nif len(x) >= 4:\n    reveal_type(x) # E: Statement is unreachable\nelse:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\n\nif len(x) < 2:\n    reveal_type(x) # E: Statement is unreachable\nelse:\n    reveal_type(x) # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenMixedTypes]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple, List, Union\n\nx: Union[Tuple[int, int], Tuple[int, int, int], List[int]]\na = b = c = 0\nif len(x) == 3:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int, builtins.int] | builtins.list[builtins.int]\"\n    a, b, c = x\nelse:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int] | builtins.list[builtins.int]\"\n    a, b = x\n\nif len(x) != 3:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int] | builtins.list[builtins.int]\"\n    a, b = x\nelse:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int, builtins.int] | builtins.list[builtins.int]\"\n    a, b, c = x\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenTypeVarTupleEquals]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\ndef foo(x: Tuple[int, Unpack[Ts], str]) -> None:\n    if len(x) == 5:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n\n    if len(x) != 5:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenTypeVarTupleGreaterThan]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\ndef foo(x: Tuple[int, Unpack[Ts], str]) -> None:\n    if len(x) > 5:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n        reveal_type(x[5])  # N: Revealed type is \"builtins.object\"\n        reveal_type(x[-6])  # N: Revealed type is \"builtins.object\"\n        reveal_type(x[-1])  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n\n    if len(x) < 5:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n        x[5]  # E: Tuple index out of range \\\n              # N: Variadic tuple can have length 5\n        x[-6]  # E: Tuple index out of range \\\n               # N: Variadic tuple can have length 5\n    x[2]  # E: Tuple index out of range \\\n          # N: Variadic tuple can have length 2\n    x[-3]  # E: Tuple index out of range \\\n           # N: Variadic tuple can have length 2\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenTypeVarTupleUnreachable]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\ndef foo(x: Tuple[int, Unpack[Ts], str]) -> None:\n    if len(x) == 1:\n        reveal_type(x)  # E: Statement is unreachable\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n\n    if len(x) != 1:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n    else:\n        reveal_type(x)  # E: Statement is unreachable\n\ndef bar(x: Tuple[int, Unpack[Ts], str]) -> None:\n    if len(x) >= 2:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n    else:\n        reveal_type(x)  # E: Statement is unreachable\n\n    if len(x) < 2:\n        reveal_type(x)  # E: Statement is unreachable\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`-1], builtins.str]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenVariadicTupleEquals]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\ndef foo(x: Tuple[int, Unpack[Tuple[float, ...]], str]) -> None:\n    if len(x) == 4:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.float, builtins.float, builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\n\n    if len(x) != 4:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.float, builtins.float, builtins.str]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenVariadicTupleGreaterThan]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\ndef foo(x: Tuple[int, Unpack[Tuple[float, ...]], str]) -> None:\n    if len(x) > 3:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.float, builtins.float, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.str] | tuple[builtins.int, builtins.float, builtins.str]\"\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\n\n    if len(x) < 3:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.str]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.float, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenVariadicTupleUnreachable]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\ndef foo(x: Tuple[int, Unpack[Tuple[float, ...]], str]) -> None:\n    if len(x) == 1:\n        reveal_type(x)  # E: Statement is unreachable\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\n\n    if len(x) != 1:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\n    else:\n        reveal_type(x)  # E: Statement is unreachable\n\ndef bar(x: Tuple[int, Unpack[Tuple[float, ...]], str]) -> None:\n    if len(x) >= 2:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\n    else:\n        reveal_type(x)  # E: Statement is unreachable\n\n    if len(x) < 2:\n        reveal_type(x)  # E: Statement is unreachable\n    else:\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.float, ...]], builtins.str]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenBareExpressionPrecise]\n# flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable\nfrom typing import Tuple\n\nx: Tuple[int, ...]\nassert x\nreveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenBareExpressionTypeVarTuple]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\ndef test(*xs: Unpack[Ts]) -> None:\n    assert xs\n    xs[0]  # OK\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenBareExpressionWithNonePrecise]\n# flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable\nfrom typing import Tuple, Optional\n\nx: Optional[Tuple[int, ...]]\nif x:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"tuple[()] | None\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenBareExpressionWithNoneImprecise]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple, Optional\n\nx: Optional[Tuple[int, ...]]\nif x:\n    reveal_type(x)  # N: Revealed type is \"builtins.tuple[builtins.int, ...]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.tuple[builtins.int, ...] | None\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenMixWithAnyPrecise]\n# flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable\nfrom typing import Any\n\nx: Any\nif isinstance(x, (list, tuple)) and len(x) == 0:\n    reveal_type(x)  # N: Revealed type is \"tuple[()] | builtins.list[Any]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Any\"\nreveal_type(x)  # N: Revealed type is \"Any\"\n\nx1: Any\nif isinstance(x1, (list, tuple)) and len(x1) > 1:\n    reveal_type(x1)  # N: Revealed type is \"tuple[Any, Any, Unpack[builtins.tuple[Any, ...]]] | builtins.list[Any]\"\nelse:\n    reveal_type(x1)  # N: Revealed type is \"Any\"\nreveal_type(x1)  # N: Revealed type is \"Any\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenMixWithAnyImprecise]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\nx: Any\nif isinstance(x, (list, tuple)) and len(x) == 0:\n    reveal_type(x)  # N: Revealed type is \"tuple[()] | builtins.list[Any]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Any\"\nreveal_type(x)  # N: Revealed type is \"Any\"\n\nx1: Any\nif isinstance(x1, (list, tuple)) and len(x1) > 1:\n    reveal_type(x1)  # N: Revealed type is \"builtins.tuple[Any, ...] | builtins.list[Any]\"\nelse:\n    reveal_type(x1)  # N: Revealed type is \"Any\"\nreveal_type(x1)  # N: Revealed type is \"Any\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenExplicitLiteralTypes]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal, Tuple, Union\n\nVarTuple = Union[\n    Tuple[int],\n    Tuple[int, int],\n    Tuple[int, int, int],\n]\nx: VarTuple\n\nsupported: Literal[2]\nif len(x) == supported:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\n\nnot_supported_yet: Literal[2, 3]\nif len(x) == not_supported_yet:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int] | tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int] | tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenUnionOfVariadicTuples]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple, Union\n\nx: Union[Tuple[int, ...], Tuple[str, ...]]\nif len(x) == 2:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.str, builtins.str]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.tuple[builtins.int, ...] | builtins.tuple[builtins.str, ...]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenUnionOfNamedTuples]\n# flags: --strict-equality --warn-unreachable\nfrom typing import NamedTuple, Union\n\nclass Point2D(NamedTuple):\n    x: int\n    y: int\nclass Point3D(NamedTuple):\n    x: int\n    y: int\n    z: int\n\nx: Union[Point2D, Point3D]\nif len(x) == 2:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int, fallback=__main__.Point2D]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int, builtins.int, fallback=__main__.Point3D]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenTupleSubclass]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\n\nclass Ints(Tuple[int, ...]):\n    size: int\n\nx: Ints\nif len(x) == 2:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int, fallback=__main__.Ints]\"\n    reveal_type(x.size)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Ints\"\n    reveal_type(x.size)  # N: Revealed type is \"builtins.int\"\n\nreveal_type(x)  # N: Revealed type is \"__main__.Ints\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenTupleSubclassCustomNotAllowed]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\n\nclass Ints(Tuple[int, ...]):\n    def __len__(self) -> int:\n        return 0\n\nx: Ints\nif len(x) > 2:\n    reveal_type(x)  # N: Revealed type is \"__main__.Ints\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Ints\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenTupleSubclassPreciseNotAllowed]\n# flags: --enable-incomplete-feature=PreciseTupleTypes --strict-equality --warn-unreachable\nfrom typing import Tuple\n\nclass Ints(Tuple[int, ...]):\n    size: int\n\nx: Ints\nif len(x) > 2:\n    reveal_type(x)  # N: Revealed type is \"__main__.Ints\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.Ints\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenUnknownLen]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any, Tuple, Union\n\nx: Union[Tuple[int, int], Tuple[int, int, int]]\n\nn: int\nif len(x) == n:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\n\na: Any\nif len(x) == a:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int] | tuple[builtins.int, builtins.int, builtins.int]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingLenUnionWithUnreachable]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union, Sequence\n\ndef f(x: Union[int, Sequence[int]]) -> None:\n    if (\n        isinstance(x, tuple)\n        and len(x) == 2\n        and isinstance(x[0], int)\n        and isinstance(x[1], int)\n    ):\n        reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n[builtins fixtures/len.pyi]\n\n[case testNarrowingIsSubclassNoneType1]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Type, Union\n\ndef f(cls: Type[Union[None, int]]) -> None:\n    if issubclass(cls, int):\n        reveal_type(cls)  # N: Revealed type is \"type[builtins.int]\"\n    else:\n        reveal_type(cls)  # N: Revealed type is \"type[None]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowingIsSubclassNoneType2]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Type, Union\n\ndef f(cls: Type[Union[None, int]]) -> None:\n    if issubclass(cls, type(None)):\n        reveal_type(cls)  # N: Revealed type is \"type[None]\"\n    else:\n        reveal_type(cls)  # N: Revealed type is \"type[builtins.int]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowingIsSubclassNoneType3]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Type, Union\n\nNoneType_ = type(None)\n\ndef f(cls: Type[Union[None, int]]) -> None:\n    if issubclass(cls, NoneType_):\n        reveal_type(cls)  # N: Revealed type is \"type[None]\"\n    else:\n        reveal_type(cls)  # N: Revealed type is \"type[builtins.int]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowingIsSubclassNoneType4]\n# flags: --python-version 3.10 --strict-equality --warn-unreachable\n\nfrom types import NoneType\nfrom typing import Type, Union\n\ndef f(cls: Type[Union[None, int]]) -> None:\n    if issubclass(cls, NoneType):\n        reveal_type(cls)  # N: Revealed type is \"type[None]\"\n    else:\n        reveal_type(cls)  # N: Revealed type is \"type[builtins.int]\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowingIsInstanceNoIntersectionWithFinalTypeAndNoneType]\n# flags: --warn-unreachable --python-version 3.10 --strict-equality\n\nfrom types import NoneType\nfrom typing import final\n\nclass X: ...\nclass Y: ...\n@final\nclass Z: ...\n\nx: X\n\nif isinstance(x, (Y, Z)):\n    reveal_type(x)  # N: Revealed type is \"__main__.<subclass of \"__main__.X\" and \"__main__.Y\">\"\nif isinstance(x, (Y, NoneType)):\n    reveal_type(x)  # N: Revealed type is \"__main__.<subclass of \"__main__.X\" and \"__main__.Y\">\"\nif isinstance(x, (Y, Z, NoneType)):\n    reveal_type(x)  # N: Revealed type is \"__main__.<subclass of \"__main__.X\" and \"__main__.Y\">\"\nif isinstance(x, (Z, NoneType)):  # E: Subclass of \"X\" and \"Z\" cannot exist: \"Z\" is final \\\n                                  # E: Subclass of \"X\" and \"NoneType\" cannot exist: \"NoneType\" is final\n    reveal_type(x)  # E: Statement is unreachable\n\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeNarrowingReachableNegative]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal\n\nx: Literal[-1]\n\nif x == -1:\n    assert True\n\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/ops.pyi]\n\n[case testTypeNarrowingReachableNegativeUnion]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal\n\nx: Literal[-1, 1]\n\nif x == -1:\n    reveal_type(x)  # N: Revealed type is \"Literal[-1]\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"Literal[1]\"\n\n[typing fixtures/typing-medium.pyi]\n[builtins fixtures/ops.pyi]\n\n[case testNarrowingWithIntEnum]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Any\nfrom enum import IntEnum\n\nclass IE(IntEnum):\n    X = 1\n    Y = 2\n\ndef f1(x: int) -> None:\n    if x == IE.X:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    if x != IE.X:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\ndef f2(x: IE) -> None:\n    if x == 1:\n        reveal_type(x)  # N: Revealed type is \"__main__.IE\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.IE\"\n\ndef f3(x: object) -> None:\n    if x == IE.X:\n        reveal_type(x)  # N: Revealed type is \"builtins.object\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.object\"\n\ndef f4(x: int | Any) -> None:\n    if x == IE.X:\n        reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.X] | Any\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | Any\"\n\ndef f5(x: int) -> None:\n    if x is IE.X:\n        reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.X]\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    if x is not IE.X:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.X]\"\n\ndef f6(x: IE) -> None:\n     if x == IE.X:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.X]\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.Y]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingWithIntEnum2]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Any\nfrom enum import IntEnum, Enum\n\nclass MyDecimal: ...\n\nclass IE(IntEnum):\n    X = 1\n    Y = 2\n\nclass IE2(IntEnum):\n    X = 1\n    Y = 2\n\nclass E(Enum):\n    X = 1\n    Y = 2\n\ndef f1(x: IE | MyDecimal) -> None:\n     if x == IE.X:\n         reveal_type(x)  # N: Revealed type is \"__main__.IE | __main__.MyDecimal\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"__main__.IE | __main__.MyDecimal\"\n\ndef f2(x: E | bytes) -> None:\n     if x == E.X:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.E.X]\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.E.Y] | builtins.bytes\"\n\ndef f3(x: IE | IE2) -> None:\n     if x == IE.X:\n         reveal_type(x)  # N: Revealed type is \"__main__.IE | __main__.IE2\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"__main__.IE | __main__.IE2\"\n\ndef f4(x: IE | E) -> None:\n     if x == IE.X:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.X]\"\n     elif x == E.X:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.E.X]\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.Y] | Literal[__main__.E.Y]\"\n\ndef f5(x: E | str | int) -> None:\n     if x == E.X:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.E.X]\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.E.Y] | builtins.str | builtins.int\"\n\ndef f6(x: IE | Any) -> None:\n     if x == IE.X:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.X] | Any\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.Y] | Any\"\n\ndef f7(x: IE | None) -> None:\n     if x == IE.X:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.X]\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.Y] | None\"\n\ndef f8(x: IE | None) -> None:\n     if x is None:\n         reveal_type(x)  # N: Revealed type is \"None\"\n     elif x == IE.X:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.X]\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.IE.Y]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingWithStrEnum]\n# flags: --strict-equality --warn-unreachable\n# mypy: strict-equality\nfrom enum import StrEnum\n\nclass SE(StrEnum):\n    A = 'a'\n    B = 'b'\n\ndef f1(x: str) -> None:\n    if x == SE.A:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\ndef f2(x: SE) -> None:\n    if x == 'a':\n        reveal_type(x)  # N: Revealed type is \"__main__.SE\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.SE\"\n\ndef f3(x: object) -> None:\n    if x == SE.A:\n        reveal_type(x)  # N: Revealed type is \"builtins.object\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.object\"\n\ndef f4(x: SE) -> None:\n     if x == SE.A:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.SE.A]\"\n     else:\n         reveal_type(x)  # N: Revealed type is \"Literal[__main__.SE.B]\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingWithEnumStrSubclass]\n# flags: --strict-equality --warn-unreachable\nfrom enum import Enum\n\nclass ParameterLocation(str, Enum):\n    QUERY = \"query\"\n    HEADER = \"header\"\n    PATH = \"path\"\n\ndef foo(location: ParameterLocation):\n    if location == \"path\":\n        reveal_type(location)  # N: Revealed type is \"__main__.ParameterLocation\"\n    else:\n        reveal_type(location)  # N: Revealed type is \"__main__.ParameterLocation\"\n\n    if location == ParameterLocation.PATH:\n        reveal_type(location)  # N: Revealed type is \"Literal[__main__.ParameterLocation.PATH]\"\n    else:\n        reveal_type(location)  # N: Revealed type is \"Literal[__main__.ParameterLocation.QUERY] | Literal[__main__.ParameterLocation.HEADER]\"\n[builtins fixtures/primitives.pyi]\n\n[case testConsistentNarrowingEqAndIn]\n# flags: --python-version 3.10 --strict-equality --warn-unreachable\n\n# https://github.com/python/mypy/issues/17864\ndef f(x: str | int) -> None:\n    if x == \"x\":\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n        y = x\n\n    if x in [\"x\"]:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n        y = x\n        z = x\n    z = y\n[builtins fixtures/primitives.pyi]\n\n[case testConsistentNarrowingEqAndInWithCustomEq]\n# flags: --python-version 3.10 --strict-equality --warn-unreachable\n\n# https://github.com/python/mypy/issues/17864\nclass C:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def __eq__(self, other: object) -> bool:\n        raise\n        # Example implementation:\n        # if isinstance(other, C) and other.x == self.x:\n        #     return True\n        # return NotImplemented\n\nclass D(C):\n    pass\n\ndef f1(x: C) -> None:\n    if x in [D(5)]:\n        reveal_type(x)  # D  # N: Revealed type is \"__main__.C\"\n\nf1(C(5))\n\ndef f2(x: C) -> None:\n    if x == D(5):\n        reveal_type(x)  # D  # N: Revealed type is \"__main__.C\"\n\nf2(C(5))\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingTypeVarNone]\n# flags: --strict-equality --warn-unreachable\n\n# https://github.com/python/mypy/issues/18126\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\n\ndef fn_if(arg: T) -> None:\n    if arg is None:\n        return None\n    return None\n\ndef fn_while(arg: T) -> None:\n    while arg is None:\n        return None\n    return None\n[builtins fixtures/primitives.pyi]\n\n[case testRefinePartialTypeWithinLoop]\n# flags: --no-local-partial-types --strict-equality --warn-unreachable\n\nx = None\nfor _ in range(2):\n    if x is not None:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    x = 1\nreveal_type(x)  # N: Revealed type is \"builtins.int | None\"\n\ndef f() -> bool: ...\n\ny = None\nwhile f():\n    reveal_type(y)  # N: Revealed type is \"None | builtins.int\"\n    y = 1\nreveal_type(y)  # N: Revealed type is \"builtins.int | None\"\n\nz = []  # E: Need type annotation for \"z\" (hint: \"z: list[<type>] = ...\")\ndef g() -> None:\n    for i in range(2):\n        while f():\n            if z:\n                z[0] + \"v\"  # E: Unsupported operand types for + (\"int\" and \"str\")\n            z.append(1)\n\nclass A:\n    def g(self) -> None:\n        z = []  # E: Need type annotation for \"z\" (hint: \"z: list[<type>] = ...\")\n        for i in range(2):\n            while f():\n                if z:\n                    z[0] + \"v\"  # E: Unsupported operand types for + (\"int\" and \"str\")\n                z.append(1)\n[builtins fixtures/primitives.pyi]\n\n[case testPersistentUnreachableLinesNestedInInpersistentUnreachableLines]\n# flags: --warn-unreachable --python-version 3.11 --strict-equality\n\nx = None\ny = None\nwhile True:\n    if x is not None:\n        if y is not None:\n            reveal_type(y)  # E: Statement is unreachable\n    x = 1\n[builtins fixtures/bool.pyi]\n\n[case testAvoidFalseRedundantCastInLoops]\n# flags: --warn-redundant-casts --strict-equality --warn-unreachable\n\nfrom typing import Callable, cast, Union\n\nProcessorReturnValue = Union[str, int]\nProcessor = Callable[[str], ProcessorReturnValue]\n\ndef main_cast(p: Processor) -> None:\n    ed: ProcessorReturnValue\n    ed = cast(str, ...)\n    while True:\n        ed = p(cast(str, ed))\n\ndef main_no_cast(p: Processor) -> None:\n    ed: ProcessorReturnValue\n    ed = cast(str, ...)\n    while True:\n        ed = p(ed)  # E: Argument 1 has incompatible type \"str | int\"; expected \"str\"\n[builtins fixtures/bool.pyi]\n\n[case testAvoidFalseUnreachableInLoop1]\n# flags: --warn-unreachable --python-version 3.11 --strict-equality\n\ndef f() -> int | None: ...\ndef b() -> bool: ...\n\nx: int | None\nx = 1\nwhile x is not None or b():\n    x = f()\n[builtins fixtures/bool.pyi]\n\n[case testAvoidFalseUnreachableInLoop2]\n# flags: --warn-unreachable --python-version 3.11 --strict-equality\n\ny = None\nwhile y is None:\n    if y is None:\n        y = []\n    y.append(1)\n[builtins fixtures/list.pyi]\n\n[case testAvoidFalseUnreachableInLoop3]\n# flags: --warn-unreachable --python-version 3.11 --strict-equality\n\nxs: list[int | None]\ny = None\nfor x in xs:\n    if x is not None:\n        if y is None:\n            y = {}  # E: Need type annotation for \"y\" (hint: \"y: dict[<type>, <type>] = ...\")\n[builtins fixtures/list.pyi]\n\n[case testAvoidFalseRedundantExprInLoop]\n# flags: --enable-error-code redundant-expr --python-version 3.11 --strict-equality --warn-unreachable\n\ndef f() -> int | None: ...\ndef b() -> bool: ...\n\nx: int | None\nx = 1\nwhile x is not None and b():\n    x = f()\n[builtins fixtures/primitives.pyi]\n\n[case testAvoidFalseNonOverlappingEqualityCheckInLoop1]\n# flags: --allow-redefinition-new --local-partial-types --strict-equality --warn-unreachable\n\nx = 1\nwhile True:\n    if x == str():\n        break\n    x = str()\n    if x == int():  # E: Non-overlapping equality check (left operand type: \"str\", right operand type: \"int\")\n        break  # E: Statement is unreachable\n[builtins fixtures/primitives.pyi]\n\n[case testAvoidFalseNonOverlappingEqualityCheckInLoop2]\n# flags: --allow-redefinition-new --local-partial-types --strict-equality --warn-unreachable\n\nclass A: ...\nclass B: ...\nclass C: ...\n\nx = A()\nwhile True:\n    if x == C():  # E: Non-overlapping equality check (left operand type: \"A | B\", right operand type: \"C\")\n        break  # E: Statement is unreachable\n    x = B()\n[builtins fixtures/primitives.pyi]\n\n[case testAvoidFalseNonOverlappingEqualityCheckInLoop3]\n# flags: --strict-equality --warn-unreachable\n\nfor y in [1.0]:\n    if y is not None or y != \"None\":  # E: Right operand of \"or\" is never evaluated\n        ...\n\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowPromotionsInsideUnions1]\n# flags: --strict-equality --warn-unreachable\n\nfrom typing import Union\n\nx: Union[str, float, None]\ny: Union[int, str]\nx = y\nreveal_type(x)  # N: Revealed type is \"builtins.str | builtins.int\"\nz: Union[complex, str]\nz = x\nreveal_type(z)  # N: Revealed type is \"builtins.int | builtins.str\"\n\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowPromotionsInsideUnions2]\n# flags: --strict-equality --warn-unreachable\n\nfrom typing import Optional\n\ndef b() -> bool: ...\ndef i() -> int: ...\nx: Optional[float]\n\nwhile b():\n    x = None\n    while b():\n        reveal_type(x)  # N: Revealed type is \"None | builtins.int\"\n        if x is None or b():\n            x = i()\n            reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/bool.pyi]\n\n[case testAvoidFalseUnreachableInFinally]\n# flags: --allow-redefinition-new --local-partial-types --strict-equality --warn-unreachable\ndef f() -> None:\n    try:\n        x = 1\n        if int():\n            x = \"\"\n            return\n        if int():\n            x = None\n            return\n    finally:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | None\"\n        if isinstance(x, str):\n            reveal_type(x)  # N: Revealed type is \"builtins.str\"\n        reveal_type(x) # N: Revealed type is \"builtins.int | builtins.str | None\"\n\n[builtins fixtures/isinstancelist.pyi]\n\n[case testNarrowingTypeVarMultiple]\n# flags: --strict-equality --warn-unreachable\nfrom typing import TypeVar\n\nclass A: ...\nclass B: ...\n\nT = TypeVar(\"T\")\ndef foo(x: T) -> T:\n    if isinstance(x, A):\n        pass\n    elif isinstance(x, B):\n        pass\n    else:\n        raise\n    reveal_type(x)  # N: Revealed type is \"T`-1\"\n    return x\n[builtins fixtures/isinstance.pyi]\n\n[case testDoNotNarrowToNever]\n# flags: --strict-equality --warn-unreachable\ndef any():\n    return 1\n\ndef f() -> None:\n    x = \"a\"\n    x = any()\n    assert isinstance(x, int)\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowTypeVarBoundType]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Type, TypeVar\n\nclass A: ...\nclass B(A):\n    other: int\n\nT = TypeVar(\"T\", bound=A)\ndef test(cls: Type[T]) -> T:\n    if issubclass(cls, B):\n        reveal_type(cls)  # N: Revealed type is \"type[T`-1]\"\n        reveal_type(cls().other)  # N: Revealed type is \"builtins.int\"\n        return cls()\n    return cls()\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowTypeVarBoundUnion]\n# flags: --strict-equality --warn-unreachable\nfrom typing import TypeVar\n\nclass A:\n    x: int\nclass B:\n    x: str\n\nT = TypeVar(\"T\")\ndef test(x: T) -> T:\n    if not isinstance(x, (A, B)):\n        return x\n    reveal_type(x)  # N: Revealed type is \"T`-1\"\n    reveal_type(x.x)  # N: Revealed type is \"builtins.int | builtins.str\"\n    if isinstance(x, A):\n        reveal_type(x)  # N: Revealed type is \"T`-1\"\n        reveal_type(x.x)  # N: Revealed type is \"builtins.int\"\n        return x\n    reveal_type(x)  # N: Revealed type is \"T`-1\"\n    reveal_type(x.x)  # N: Revealed type is \"builtins.str\"\n    return x\n[builtins fixtures/isinstance.pyi]\n\n[case testIsinstanceNarrowingWithSelfTypes]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Generic, TypeVar, overload\n\nT = TypeVar(\"T\")\n\nclass A(Generic[T]):\n    def __init__(self: A[int]) -> None:\n        pass\n\ndef check_a(obj: \"A[T] | str\") -> None:\n    reveal_type(obj)  # N: Revealed type is \"__main__.A[T`-1] | builtins.str\"\n    if isinstance(obj, A):\n        reveal_type(obj)  # N: Revealed type is \"__main__.A[T`-1]\"\n    else:\n        reveal_type(obj)  # N: Revealed type is \"builtins.str\"\n\n\nclass B(Generic[T]):\n    @overload\n    def __init__(self, x: T) -> None: ...\n    @overload\n    def __init__(self: B[int]) -> None: ...\n    def __init__(self, x: \"T | None\" = None) -> None:\n        pass\n\ndef check_b(obj: \"B[T] | str\") -> None:\n    reveal_type(obj)  # N: Revealed type is \"__main__.B[T`-1] | builtins.str\"\n    if isinstance(obj, B):\n        reveal_type(obj)  # N: Revealed type is \"__main__.B[T`-1]\"\n    else:\n        reveal_type(obj)  # N: Revealed type is \"builtins.str\"\n\n\nclass C(Generic[T]):\n    @overload\n    def __init__(self: C[int]) -> None: ...\n    @overload\n    def __init__(self, x: T) -> None: ...\n    def __init__(self, x: \"T | None\" = None) -> None:\n        pass\n\ndef check_c(obj: \"C[T] | str\") -> None:\n    reveal_type(obj)  # N: Revealed type is \"__main__.C[T`-1] | builtins.str\"\n    if isinstance(obj, C):\n        reveal_type(obj)  # N: Revealed type is \"__main__.C[T`-1]\"\n    else:\n        reveal_type(obj)  # N: Revealed type is \"builtins.str\"\n\n\nclass D(tuple[T], Generic[T]): ...\n\ndef check_d(arg: D[T]) -> None:\n    if not isinstance(arg, D):\n        return  # E: Statement is unreachable\n    reveal_type(arg)  # N: Revealed type is \"tuple[T`-1, fallback=__main__.D[Any]]\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testNarrowingUnionMixins]\n# flags: --strict-equality --warn-unreachable\nclass Base: ...\n\nclass FooMixin:\n    def foo(self) -> None: ...\n\nclass BarMixin:\n    def bar(self) -> None: ...\n\ndef baz(item: Base) -> None:\n    if not isinstance(item, (FooMixin, BarMixin)):\n        raise\n\n    reveal_type(item)  # N: Revealed type is \"__main__.<subclass of \"__main__.Base\" and \"__main__.FooMixin\"> | __main__.<subclass of \"__main__.Base\" and \"__main__.BarMixin\">\"\n    if isinstance(item, FooMixin):\n        reveal_type(item)  # N: Revealed type is \"__main__.<subclass of \"__main__.Base\" and \"__main__.FooMixin\">\"\n        item.foo()\n    else:\n        reveal_type(item)  # N: Revealed type is \"__main__.<subclass of \"__main__.Base\" and \"__main__.BarMixin\">\"\n        item.bar()\n[builtins fixtures/isinstance.pyi]\n\n[case testCustomSetterNarrowingReWidened]\n# flags: --strict-equality --warn-unreachable\nclass B: ...\nclass C(B): ...\nclass C1(B): ...\nclass D(C): ...\n\nclass Test:\n    @property\n    def foo(self) -> C: ...\n    @foo.setter\n    def foo(self, val: B) -> None: ...\n\nt: Test\nt.foo = D()\nreveal_type(t.foo)  # N: Revealed type is \"__main__.D\"\nt.foo = C1()\nreveal_type(t.foo)  # N: Revealed type is \"__main__.C\"\n[builtins fixtures/property.pyi]\n\n[case testNarrowingNotImplemented]\n# flags: --python-version 3.10 --warn-unreachable\nfrom __future__ import annotations\nimport types\n\ndef foo(x: types.NotImplementedType | str):\n    if x is not NotImplemented:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\nfrom typing_extensions import Self\n\nclass X:\n    def __divmod__(self, other: Self | int) -> tuple[Self, Self]: ...\n\n    def __floordiv__(self, other: Self | int) -> Self:\n        qr = self.__divmod__(other)\n        if qr is NotImplemented:\n            return NotImplemented\n        return qr[0]\n[builtins fixtures/notimplemented.pyi]\n\n\n[case testNarrowingBooleans]\n# flags: --warn-return-any --strict-equality --warn-unreachable\nfrom typing import Any\n\ndef foo(x: dict[str, Any]) -> bool:\n    if x.get(\"event\") is False:\n        return False\n    if x.get(\"event\") is True:\n        return True\n    raise\n[builtins fixtures/dict.pyi]\n\n\n[case testNarrowingTypeObjects]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Callable, Any, TypeVar, Generic, Protocol\n_T_co = TypeVar('_T_co', covariant=True)\n\nclass Boxxy(Protocol[_T_co]):\n    def get_box(self) -> _T_co: ...\n\nclass TupleLike(Generic[_T_co]):\n    def __init__(self, iterable: Boxxy[_T_co], /) -> None:\n        raise\n\nclass Box1(Generic[_T_co]):\n    def __init__(self, content: _T_co, /) -> None: ...\n    def get_box(self) -> _T_co: raise\n\nclass Box2(Generic[_T_co]):\n    def __init__(self, content: _T_co, /) -> None: ...\n    def get_box(self) -> _T_co: raise\n\ndef get_type(setting_name: str) -> Callable[[Box1], Any] | type[Any]:\n    raise\n\ndef main(key: str):\n    existing_value_type = get_type(key)\n    if existing_value_type is TupleLike:\n        reveal_type(TupleLike)  # N: Revealed type is \"def [_T_co] (__main__.Boxxy[_T_co`1]) -> __main__.TupleLike[_T_co`1]\"\n        reveal_type(TupleLike(Box2(\"str\")))  # N: Revealed type is \"__main__.TupleLike[builtins.str]\"\n\n        reveal_type(existing_value_type)  # N: Revealed type is \"(def [_T_co] (__main__.Boxxy[_T_co`1]) -> __main__.TupleLike[_T_co`1]) | type[Any]\"\n        reveal_type(existing_value_type(Box2(\"str\")))  # N: Revealed type is \"__main__.TupleLike[builtins.str] | Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingCollections]\n# flags: --strict-equality --warn-unreachable\nfrom typing import cast\n\nclass X:\n    def __init__(self) -> None:\n        self.x: dict[str, str] = {}\n        self.y: list[str] = []\n\n    def xxx(self) -> None:\n        if self.x == {}:\n            reveal_type(self.x)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.str]\"\n            self.x[\"asdf\"]\n\n        if self.x == dict():\n            reveal_type(self.x)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.str]\"\n            self.x[\"asdf\"]\n\n        if self.x == cast(dict[int, int], {}):  # E: Non-overlapping equality check (left operand type: \"dict[str, str]\", right operand type: \"dict[int, int]\")\n            reveal_type(self.x)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.str]\"\n            self.x[\"asdf\"]\n\n    def yyy(self) -> None:\n        if self.y == []:\n            reveal_type(self.y)  # N: Revealed type is \"builtins.list[builtins.str]\"\n            self.y[0].does_not_exist  # E: \"str\" has no attribute \"does_not_exist\"\n\n        if self.y == list():\n            reveal_type(self.y)  # N: Revealed type is \"builtins.list[builtins.str]\"\n            self.y[0].does_not_exist  # E: \"str\" has no attribute \"does_not_exist\"\n\n        if self.y == cast(list[int], []):  # E: Non-overlapping equality check (left operand type: \"list[str]\", right operand type: \"list[int]\")\n            reveal_type(self.y)  # N: Revealed type is \"builtins.list[builtins.str]\"\n            self.y[0].does_not_exist  # E: \"str\" has no attribute \"does_not_exist\"\n[builtins fixtures/dict.pyi]\n\n\n[case testTypeNarrowingStringInLiteralContainer]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal\n\ndef narrow_tuple(x: str, t: tuple[Literal['a', 'b']]):\n    if x in t:\n        reveal_type(x)  # N: Revealed type is \"Literal['a'] | Literal['b']\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\n    if x not in t:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"Literal['a'] | Literal['b']\"\n\ndef narrow_homo_tuple(x: str, t: tuple[Literal['a', 'b'], ...]):\n    if x in t:\n        reveal_type(x)  # N: Revealed type is \"Literal['a'] | Literal['b']\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\ndef narrow_list(x: str, t: list[Literal['a', 'b']]):\n    if x in t:\n        reveal_type(x)  # N: Revealed type is \"Literal['a'] | Literal['b']\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\ndef narrow_set(x: str, t: set[Literal['a', 'b']]):\n    if x in t:\n        reveal_type(x)  # N: Revealed type is \"Literal['a'] | Literal['b']\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/primitives.pyi]\n\n\n[case testNarrowingLiteralInLiteralContainer]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Literal\n\ndef narrow_tuple(x: Literal['c'], overlap: list[Literal['b', 'c']], no_overlap: list[Literal['a', 'b']]):\n    if x in overlap:\n        reveal_type(x)  # N: Revealed type is \"Literal['c']\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"Literal['c']\"\n\n    if x in no_overlap:\n        reveal_type(x)  # E: Statement is unreachable\n    else:\n        reveal_type(x)  # N: Revealed type is \"Literal['c']\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeNarrowingUnionInContainer]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union, Literal\n\ndef f1(x: Union[str, float], t1: list[Literal['a', 'b']], t2: list[str]):\n    if x in t1:\n        reveal_type(x)  # N: Revealed type is \"Literal['a'] | Literal['b']\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.float\"\n\n    if x in t2:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.float\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowAnyWithEqualityOrContainment]\n# flags: --strict-equality --warn-unreachable\n# https://github.com/python/mypy/issues/17841\nfrom typing import Any\n\ndef f1(x: Any) -> None:\n    if x is not None and x not in [\"x\"]:\n        return\n    reveal_type(x)  # N: Revealed type is \"Any\"\n\ndef f2(x: Any) -> None:\n    if x is not None and x != \"x\":\n        return\n    reveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowChainedContainment]\n# flags: --strict-equality --warn-unreachable\n\ndef bad_compare_has_key(has_key: bool, key: str, s: tuple[str, ...]) -> None:\n    if has_key == key in s:  # E: Non-overlapping equality check (left operand type: \"bool\", right operand type: \"str\")\n        reveal_type(has_key)  # E: Statement is unreachable\n        reveal_type(key)\n\ndef bad_but_should_pass(has_key: bool, key: bool, s: tuple[bool, ...]) -> None:\n    if has_key == key in s:\n        reveal_type(has_key)  # N: Revealed type is \"builtins.bool\"\n        reveal_type(key)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowTypeObject]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\n# https://github.com/python/mypy/issues/13704\n\ndef f1(cls: type):\n    if cls is str:\n        reveal_type(cls)  # N: Revealed type is \"def (o: builtins.object =) -> builtins.str\"\n        reveal_type(cls(5))  # N: Revealed type is \"builtins.str\"\n\n    if issubclass(cls, int):\n        reveal_type(cls)  # N: Revealed type is \"type[builtins.int]\"\n    elif cls is str:\n        reveal_type(cls)  # N: Revealed type is \"def (o: builtins.object =) -> builtins.str\"\n        reveal_type(cls(5))  # N: Revealed type is \"builtins.str\"\n\ndef f2(cls: type[object]):\n    if cls is str:\n        reveal_type(cls)  # N: Revealed type is \"def (o: builtins.object =) -> builtins.str\"\n        reveal_type(cls(5))  # N: Revealed type is \"builtins.str\"\n\n    if issubclass(cls, int):\n        reveal_type(cls)  # N: Revealed type is \"type[builtins.int]\"\n    elif cls is str:\n        reveal_type(cls)  # N: Revealed type is \"def (o: builtins.object =) -> builtins.str\"\n        reveal_type(cls(5))  # N: Revealed type is \"builtins.str\"\n\ndef f3(cls: type[Any]):\n    if cls is str:\n        reveal_type(cls)  # N: Revealed type is \"type[Any]\"\n        reveal_type(cls(5))  # N: Revealed type is \"Any\"\n\n    if issubclass(cls, int):\n        reveal_type(cls)  # N: Revealed type is \"type[builtins.int]\"\n    elif cls is str:\n        reveal_type(cls)  # N: Revealed type is \"type[Any]\"\n        reveal_type(cls(5))  # N: Revealed type is \"Any\"\n[builtins fixtures/isinstance.pyi]\n\n[case testNarrowTypeObjectUnion]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\n\ndef f4(cls: type[str | int]):\n    reveal_type(cls)  # N: Revealed type is \"type[builtins.str] | type[builtins.int]\"\n\n    if cls is int:\n        reveal_type(cls)  # N: Revealed type is \"type[builtins.int]\"\n    if cls == int:\n        reveal_type(cls)  # N: Revealed type is \"type[builtins.int]\"\n[builtins fixtures/primitives.pyi]\n\n\n[case testTypeEqualsCheck]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\ny: Any\nif type(y) == int:\n    reveal_type(y) # N: Revealed type is \"builtins.int\"\n\n[case testMultipleTypeEqualsCheck]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\nx: Any\ny: Any\nif type(x) == type(y) == int:\n    reveal_type(y) # N: Revealed type is \"builtins.int\"\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n\nz: Any\nif int == type(z) == int:\n    reveal_type(z) # N: Revealed type is \"builtins.int\"\n\n[case testTypeEqualsCheckWidening]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\ndef f(x: str, y: Any, z: object):\n    if type(x) is type(y):\n        reveal_type(x) # N: Revealed type is \"builtins.str\"\n        reveal_type(y) # N: Revealed type is \"builtins.str\"\n\n    if type(x) == type(y):\n        reveal_type(x) # N: Revealed type is \"builtins.str\"\n        reveal_type(y) # N: Revealed type is \"builtins.str\"\n\n    if type(x) is type(z):\n        reveal_type(x) # N: Revealed type is \"builtins.str\"\n        reveal_type(z) # N: Revealed type is \"builtins.str\"\n\n    if type(x) == type(z):\n        reveal_type(x) # N: Revealed type is \"builtins.str\"\n        reveal_type(z) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/primitives.pyi]\n\n[case testTypeEqualsCheckUsingIs]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\ny: Any\nif type(y) is int:\n    reveal_type(y) # N: Revealed type is \"builtins.int\"\n\n[case testTypeEqualsCheckUsingIsNonOverlapping]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union\n\ny: str\nif type(y) is int:  # E: Non-overlapping identity check (left operand type: \"type[str]\", right operand type: \"type[int]\") \\\n                    # E: Subclass of \"str\" and \"int\" cannot exist: would have incompatible method signatures\n    y  # E: Statement is unreachable\nelse:\n    reveal_type(y) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeEqualsCheckUsingIsNonOverlappingChild]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union\n\nclass A: ...\nclass B: ...\nclass C(A): ...\ndef main(x: Union[B, C]):\n    # C instance cannot be exactly its parent A, we need reversed subtyping relationship\n    # here (type(parent) is Child).\n    if type(x) is A:\n        reveal_type(x)  # E: Statement is unreachable\n    else:\n        reveal_type(x)  # N: Revealed type is \"__main__.B | __main__.C\"\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeEqualsCheckTypeVar]\n# flags: --strict-equality --warn-unreachable\nfrom typing import TypeVar\n\nclass A: ...\nclass B: ...\n\nT = TypeVar(\"T\")\n\ndef forgets_about_subclasses(self, obj: T) -> T:\n    if isinstance(obj, A):\n        return A()  # E: Incompatible return value type (got \"A\", expected \"T\")\n    elif isinstance(obj, B):\n        return B()  # E: Incompatible return value type (got \"B\", expected \"T\")\n    raise\n\ndef correct1(self, obj: T) -> T:\n    # TODO: mypy should not error in this case\n    if type(obj) == A:\n        return A()  # E: Incompatible return value type (got \"A\", expected \"T\")\n    elif type(obj) == B:\n        return B()  # E: Incompatible return value type (got \"B\", expected \"T\")\n    raise\n\nT_value = TypeVar(\"T_value\", A, B)\n\ndef forgets_about_multiple_inheritance(self, obj: T_value) -> T_value:\n    # Note that it is a little confusing that mypy only errors in the first branch here, but this\n    # is a branch that would be taken by a subclass of both A and B.\n    # See also https://github.com/python/mypy/issues/10302#issuecomment-3832182574\n    if isinstance(obj, A):\n        return A()  # E: Incompatible return value type (got \"A\", expected \"B\")\n    elif isinstance(obj, B):\n        return B()\n    raise\n\ndef correct2(self, obj: T_value) -> T_value:\n    if type(obj) == A:\n        return A()\n    elif type(obj) == B:\n        return B()\n    raise\n[builtins fixtures/primitives.pyi]\n\n[case testTypeEqualsCheckUsingDifferentSpecializedTypes]\n# flags: --strict-equality --warn-unreachable\nfrom collections import defaultdict\n\nx: defaultdict\ny: dict\nz: object\nif type(x) is type(y) is type(z):\n    reveal_type(x) # N: Revealed type is \"collections.defaultdict[Any, Any]\"\n    reveal_type(y) # N: Revealed type is \"collections.defaultdict[Any, Any]\"\n    reveal_type(z) # N: Revealed type is \"collections.defaultdict[Any, Any]\"\n\n[case testTypeEqualsTypeObjectUnion]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\ndef f(x: object, y: type[int] | type[str]):\n    if type(x) == y:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n        reveal_type(y)  # N: Revealed type is \"type[builtins.int] | type[builtins.str]\"\n[builtins fixtures/primitives.pyi]\n\n[case testUnionTypeEquality]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any, reveal_type\n\ndef f(x: Any):\n    if type(x) == (int, str):  # E: Non-overlapping equality check (left operand type: \"type[Any]\", right operand type: \"tuple[type[int], type[str]]\")\n        reveal_type(x) # E: Statement is unreachable\n[builtins fixtures/tuple.pyi]\n\n[case testTypeIntersectionWithConcreteTypes]\n# flags: --strict-equality --warn-unreachable\nclass X: x = 1\nclass Y: y = 1\nclass Z(X, Y): ...\n\nz = Z()\nx: X = z\ny: Y = z\nif type(x) is type(y):  # E: Non-overlapping identity check (left operand type: \"type[X]\", right operand type: \"type[Y]\")\n    reveal_type(x)  # N: Revealed type is \"__main__.<subclass of \"__main__.X\" and \"__main__.Y\">\"\n    reveal_type(y)  # N: Revealed type is \"__main__.<subclass of \"__main__.Y\" and \"__main__.X\">\"\n    x.y + y.x\n\nif isinstance(x, type(y)) and isinstance(y, type(x)):\n    reveal_type(x)  # N: Revealed type is \"__main__.<subclass of \"__main__.X\" and \"__main__.Y\">\"\n    reveal_type(y)  # N: Revealed type is \"__main__.<subclass of \"__main__.X\" and \"__main__.Y\">\"\n    x.y + y.x\n\n[builtins fixtures/isinstance.pyi]\n\n[case testTypeEqualsNarrowingUnionWithElse]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union\n\nx: Union[int, str]\nif type(x) is int:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n\n[case testTypeEqualsMultipleTypesShouldntNarrow]\n# flags: --strict-equality --warn-unreachable\n\nfrom typing import Union\n\nx: Union[int, str]\nif type(x) == int == str:  # E: Non-overlapping equality check (left operand type: \"type[int]\", right operand type: \"type[str]\")\n    reveal_type(x)  # E: Statement is unreachable\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n\n[builtins fixtures/primitives.pyi]\n\n[case testTypeNotEqualsCheck]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union\n\nx: Union[int, str]\nif type(x) != int:\n    reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n# mypy thinks int isn't defined unless we include this\n[builtins fixtures/primitives.pyi]\n\n[case testTypeNotEqualsCheckUsingIsNot]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Union\n\nx: Union[int, str]\nif type(x) is not int:\n    reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[case testTypeNarrowingAgainstType]\n# flags: --strict-equality --warn-unreachable\nclass A:\n    def foo(self, x: object) -> None:\n        reveal_type(self)  # N: Revealed type is \"__main__.A\"\n        reveal_type(x)  # N: Revealed type is \"builtins.object\"\n        if type(self) is type(x):\n            reveal_type(self)  # N: Revealed type is \"__main__.A\"\n            reveal_type(x)  # N: Revealed type is \"__main__.A\"\n        else:\n            reveal_type(self)  # N: Revealed type is \"__main__.A\"\n            reveal_type(x)  # N: Revealed type is \"builtins.object\"\n        if type(self) == type(x):\n            reveal_type(self)  # N: Revealed type is \"__main__.A\"\n            reveal_type(x)  # N: Revealed type is \"__main__.A\"\n        else:\n            reveal_type(self)  # N: Revealed type is \"__main__.A\"\n            reveal_type(x)  # N: Revealed type is \"builtins.object\"\n\nclass B:\n    y: int\n\n    def __eq__(self, other: object) -> bool:\n        return type(other) is type(self) and other.y == self.y\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowInElseCaseIfFinal]\n# flags: --strict-equality --warn-unreachable\nfrom typing import final, Union\n@final\nclass C:\n    pass\nclass D:\n    pass\n\nx: Union[C, D]\nif type(x) is C:\n    reveal_type(x)  # N: Revealed type is \"__main__.C\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.D\"\n\n[case testNarrowInIfCaseIfFinalUsingIsNot]\n# flags: --strict-equality --warn-unreachable\nfrom typing import final, Union\n@final\nclass C:\n    pass\nclass D:\n    pass\n\nx: Union[C, D]\nif type(x) is not C:\n    reveal_type(x)  # N: Revealed type is \"__main__.D\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"__main__.C\"\n\n[case testDunderClassNarrowing]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\ndef foo(y: object):\n    if y.__class__ == int:\n        reveal_type(y) # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(y) # N: Revealed type is \"builtins.object\"\n\n    if y.__class__ is int:\n        reveal_type(y) # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(y) # N: Revealed type is \"builtins.object\"\n\n\ndef bar(y: Any):\n    if y.__class__ == int:\n        reveal_type(y) # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(y) # N: Revealed type is \"Any\"\n\n    if y.__class__ is int:\n        reveal_type(y) # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(y) # N: Revealed type is \"Any\"\n[builtins fixtures/dict-full.pyi]\n\n\n[case testNarrowTypeVarType]\n# flags: --strict-equality --warn-unreachable\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\n\nclass A: ...\n\ndef foo(X: type[T]) -> T:\n    if X == A:\n        return X()\n    raise\n\n# It could be nice to make these two test cases consistent, but it would be tricky\n# The above case is much more common in real world code\ndef bar(X: type[T]) -> T:\n    if X == A:\n        return A()  # E: Incompatible return value type (got \"A\", expected \"T\")\n    raise\n[builtins fixtures/type.pyi]\n\n[case testNarrowingConstrainedTypeVarType]\n# flags: --strict-equality --warn-unreachable\nfrom typing import TypeVar, Any, Type\n\nTargetType = TypeVar(\"TargetType\", int, float, str)\n\n# TODO: this behaviour is incorrect, it will be fixed by improving reachability\ndef convert_type(target_type: Type[TargetType]) -> TargetType:\n    if target_type == str:\n        return str()\n    if target_type == int:\n        return int()\n    if target_type == float:\n        return float()  # E: Incompatible return value type (got \"float\", expected \"int\")\n    raise\n\n\n[builtins fixtures/primitives.pyi]\n\n\n[case testNarrowingEqualityWithPromotions]\n# flags: --strict-equality --warn-unreachable\nfrom __future__ import annotations\nfrom typing import Literal\n\ndef f1(number: float, i: int):\n    if number == i:\n        reveal_type(number)  # N: Revealed type is \"builtins.float\"\n        reveal_type(i)  # N: Revealed type is \"builtins.int\"\n\ndef f2(number: float, five: Literal[5]):\n    if number == five:\n        reveal_type(number)  # N: Revealed type is \"builtins.float\"\n        reveal_type(five)  # N: Revealed type is \"Literal[5]\"\n\ndef f3(number: float | int, five: Literal[5]):\n    if number == five:\n        reveal_type(number)  # N: Revealed type is \"builtins.float | Literal[5]\"\n        reveal_type(five)  # N: Revealed type is \"Literal[5]\"\n\ndef f8(number: float | Literal[5], five: Literal[5]):\n    if number == five:\n        reveal_type(number)  # N: Revealed type is \"builtins.float | Literal[5]\"\n        reveal_type(five)  # N: Revealed type is \"Literal[5]\"\n    else:\n        reveal_type(number)  # N: Revealed type is \"builtins.float\"\n        reveal_type(five)  # N: Revealed type is \"Literal[5]\"\n\ndef f4(number: float | None, i: int):\n    if number == i:\n        reveal_type(number)  # N: Revealed type is \"builtins.float\"\n        reveal_type(i)  # N: Revealed type is \"builtins.int\"\n\ndef f5(number: float | int, i: int):\n    if number == i:\n        reveal_type(number)  # N: Revealed type is \"builtins.float | builtins.int\"\n        reveal_type(i)  # N: Revealed type is \"builtins.int\"\n\ndef f6(number: float | complex, i: int):\n    if number == i:\n        reveal_type(number)  # N: Revealed type is \"builtins.float | builtins.complex\"\n        reveal_type(i)  # N: Revealed type is \"builtins.int\"\n\nclass Custom:\n    def __eq__(self, other: object) -> bool: return True\n\ndef f7(number: float, x: Custom | int):\n    if number == x:\n        reveal_type(number)  # N: Revealed type is \"builtins.float\"\n        reveal_type(x)  # N: Revealed type is \"__main__.Custom | builtins.int\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingAnyNegativeIntersection-xfail]\n# flags: --strict-equality --warn-unreachable\n# https://github.com/python/mypy/issues/20597\nfrom __future__ import annotations\nfrom typing import Any\n\nclass array: ...\n\ndef get_result() -> Any: ...\n\ndef foo(x: str | array) -> str:\n    result = get_result()\n    if isinstance(result, array):\n        return \"asdf\"\n    if result is x:\n        reveal_type(result)  # N: Revealed type is \"Any\"\n        return result\n    raise\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingOptionalBytes]\nfrom __future__ import annotations\ndef f(x: bytes | None):\n    if x == b\"asdf\":\n        reveal_type(x)  # N: Revealed type is \"builtins.bytes\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.bytes | None\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingBytesLikeWithPromotion]\n# flags: --strict-equality --warn-unreachable --strict-bytes\nfrom __future__ import annotations\n\ndef check_test(x: bytes) -> None: ...\ncheck_test(bytearray(b\"asdf\"))  # E: Argument 1 to \"check_test\" has incompatible type \"bytearray\"; expected \"bytes\"\n\ndef main(\n    v_bytes: bytes,\n    v_bytearray: bytearray,\n    v_memoryview: memoryview,\n    v_all: bytes | bytearray | memoryview,\n) -> None:\n    if v_bytes == v_bytearray:\n        reveal_type(v_bytes)  # N: Revealed type is \"builtins.bytes\"\n        reveal_type(v_bytearray)  # N: Revealed type is \"builtins.bytearray\"\n    if v_bytes == v_memoryview:\n        reveal_type(v_bytes)  # N: Revealed type is \"builtins.bytes\"\n        reveal_type(v_memoryview)  # N: Revealed type is \"builtins.memoryview\"\n    if v_bytearray == v_memoryview:\n        reveal_type(v_bytearray)  # N: Revealed type is \"builtins.bytearray\"\n        reveal_type(v_memoryview)  # N: Revealed type is \"builtins.memoryview\"\n\n    if v_all == v_bytes:\n        reveal_type(v_all)  # N: Revealed type is \"builtins.bytes\"\n        reveal_type(v_bytes)  # N: Revealed type is \"builtins.bytes\"\n    if v_all == v_bytearray:\n        reveal_type(v_all)  # N: Revealed type is \"builtins.bytes | builtins.bytearray | builtins.memoryview\"\n        reveal_type(v_bytearray)  # N: Revealed type is \"builtins.bytearray\"\n    if v_all == v_memoryview:\n        reveal_type(v_all)  # N: Revealed type is \"builtins.bytes | builtins.bytearray | builtins.memoryview\"\n        reveal_type(v_memoryview)  # N: Revealed type is \"builtins.memoryview\"\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowingBytesLikeNoPromotion]\n# flags: --strict-equality --warn-unreachable --no-strict-bytes\nfrom __future__ import annotations\n\ndef check_test(x: bytes) -> None: ...\ncheck_test(bytearray(b\"asdf\"))\n\ndef main(\n    v_bytes: bytes,\n    v_bytearray: bytearray,\n    v_memoryview: memoryview,\n    v_all: bytes | bytearray | memoryview,\n) -> None:\n    if v_bytes == v_bytearray:\n        reveal_type(v_bytes)  # N: Revealed type is \"builtins.bytes\"\n        reveal_type(v_bytearray)  # N: Revealed type is \"builtins.bytearray\"\n    if v_bytes == v_memoryview:\n        reveal_type(v_bytes)  # N: Revealed type is \"builtins.bytes\"\n        reveal_type(v_memoryview)  # N: Revealed type is \"builtins.memoryview\"\n    if v_bytearray == v_memoryview:\n        reveal_type(v_bytearray)  # N: Revealed type is \"builtins.bytearray\"\n        reveal_type(v_memoryview)  # N: Revealed type is \"builtins.memoryview\"\n\n    if v_all == v_bytes:\n        reveal_type(v_all)  # N: Revealed type is \"builtins.bytes | builtins.bytearray | builtins.memoryview\"\n        reveal_type(v_bytes)  # N: Revealed type is \"builtins.bytes\"\n    if v_all == v_bytearray:\n        reveal_type(v_all)  # N: Revealed type is \"builtins.bytes | builtins.bytearray | builtins.memoryview\"\n        reveal_type(v_bytearray)  # N: Revealed type is \"builtins.bytearray\"\n    if v_all == v_memoryview:\n        reveal_type(v_all)  # N: Revealed type is \"builtins.bytes | builtins.bytearray | builtins.memoryview\"\n        reveal_type(v_memoryview)  # N: Revealed type is \"builtins.memoryview\"\n[builtins fixtures/primitives.pyi]\n\n\n[case testNarrowNewTypeVsSubclass]\n# mypy: strict-equality, warn-unreachable\nfrom typing import NewType\n\nM1 = NewType(\"M1\", int)\nM2 = NewType(\"M2\", int)\n\ndef check_m(base: int, m1: M1, m2: M2):\n    if m1 == m2:  # E: Non-overlapping equality check (left operand type: \"M1\", right operand type: \"M2\")\n        reveal_type(m1)  # N: Revealed type is \"__main__.M1\"\n        reveal_type(m2)  # N: Revealed type is \"__main__.M2\"\n\n    if m1 == base:\n        # We do not narrow base\n        reveal_type(m1)  # N: Revealed type is \"__main__.M1\"\n        reveal_type(base)  # N: Revealed type is \"builtins.int\"\n        if m2 == base:\n            reveal_type(m2)  # N: Revealed type is \"__main__.M2\"\n            reveal_type(base)  # N: Revealed type is \"builtins.int\"\n\n# We do narrow for subclasses! (assuming no custom equality)\nclass A: ...\nclass A1(A): ...\nclass A2(A): ...\n\ndef check_a(base: A, a1: A1, a2: A2):\n    if a1 == a2:  # E: Non-overlapping equality check (left operand type: \"A1\", right operand type: \"A2\")\n        reveal_type(a1)  # E: Statement is unreachable\n        reveal_type(a2)\n\n    if a1 == base:\n        # We do narrow base\n        reveal_type(a1)  # N: Revealed type is \"__main__.A1\"\n        reveal_type(base)  # N: Revealed type is \"__main__.A1\"\n        if a2 == base:  # E: Non-overlapping equality check (left operand type: \"A2\", right operand type: \"A1\")\n            reveal_type(a2)  # E: Statement is unreachable\n            reveal_type(base)\n[builtins fixtures/primitives.pyi]\n\n\n[case testNarrowNewTypeFromObject]\n# mypy: strict-equality, warn-unreachable\nfrom __future__ import annotations\nfrom typing import NewType\n\nUserId = NewType(\"UserId\", int)\n\ndef f1(whatever: object, uid: UserId):\n    # The general principle is that we should not be able to produce a value of NewType\n    # without there being explicit wrapping somewhere\n    if whatever == uid:\n        reveal_type(whatever)  # N: Revealed type is \"builtins.int\"\n        reveal_type(uid)  # N: Revealed type is \"__main__.UserId\"\n\nclass Other: ...\n\ndef f2(whatever: object, uid: UserId | Other):\n    if whatever == uid:\n        reveal_type(whatever)  # N: Revealed type is \"builtins.int | __main__.Other\"\n        reveal_type(uid)  # N: Revealed type is \"__main__.UserId | __main__.Other\"\n[builtins fixtures/primitives.pyi]\n\n\n[case testNarrowNewTypeNested]\n# mypy: strict-equality, warn-unreachable\nfrom typing import NewType, Final\n\nPath = NewType(\"Path\", str)\nNormPath = NewType(\"NormPath\", Path)\n\ndef op(normpath: NormPath, path: Path):\n    if normpath == path:\n        # No narrowing\n        reveal_type(normpath)  # N: Revealed type is \"__main__.NormPath\"\n        reveal_type(path)  # N: Revealed type is \"__main__.Path\"\n[builtins fixtures/primitives.pyi]\n\n\n[case testNarrowNewTypeSharedValue]\n# mypy: strict-equality, warn-unreachable\nfrom typing import NewType, Final\n\nUserId = NewType(\"UserId\", int)\nTeamId = NewType(\"TeamId\", int)\nINVALID = 123\n\ndef get_owner(uid: UserId, tid: TeamId):\n    # No narrowing for INVALID\n    if uid == INVALID:\n        reveal_type(uid)  # N: Revealed type is \"__main__.UserId\"\n        reveal_type(tid)  # N: Revealed type is \"__main__.TeamId\"\n        reveal_type(INVALID)  # N: Revealed type is \"builtins.int\"\n        if tid == INVALID:\n            reveal_type(uid)  # N: Revealed type is \"__main__.UserId\"\n            reveal_type(tid)  # N: Revealed type is \"__main__.TeamId\"\n            reveal_type(INVALID)  # N: Revealed type is \"builtins.int\"\n            return None\n[builtins fixtures/primitives.pyi]\n\n[case testNarrowCallableTypeVarByEquality]\nfrom typing import Callable, TypeVar\n\nT = TypeVar(\"T\")\n\ndef remove(path: str) -> None: ...\ndef unlink(path: str) -> None: ...\n\ndef f1(func: Callable[..., T], arg: str) -> T:\n    if func == remove:\n        reveal_type(func)  # N: Revealed type is \"def (path: builtins.str) -> T`-1\"\n        reveal_type(func(arg))  # N: Revealed type is \"T`-1\"\n        return func(arg)\n    return func(arg)\n\ndef f2(func: Callable[..., T], arg: str) -> T:\n    if func in [unlink, remove]:\n        reveal_type(func)  # N: Revealed type is \"def (path: builtins.str) -> T`-1\"\n        reveal_type(func(arg))  # N: Revealed type is \"T`-1\"\n        return func(arg)\n    return func(arg)\n[builtins fixtures/primitives.pyi]\n"
  },
  {
    "path": "test-data/unit/check-native-int.test",
    "content": "[case testNativeIntBasics]\nfrom mypy_extensions import i32, i64\n\ndef f(x: int) -> i32:\n    return i32(x)\n\ndef g(x: i32) -> None:\n    pass\n\nreveal_type(i32(1) + i32(2))  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(i64(1) + i64(2))  # N: Revealed type is \"mypy_extensions.i64\"\ni32(1) + i64(2)  # E: Unsupported operand types for + (\"i32\" and \"i64\")\ni64(1) + i32(2)  # E: Unsupported operand types for + (\"i64\" and \"i32\")\ng(i32(2))\ng(i64(2))  # E: Argument 1 to \"g\" has incompatible type \"i64\"; expected \"i32\"\n[builtins fixtures/dict.pyi]\n\n[case testNativeIntCoercions]\nfrom mypy_extensions import i32, i64\n\ndef f1(x: int) -> None: pass\ndef f2(x: i32) -> None: pass\n\na: i32 = 1\nb: i64 = 2\nc: i64 = a  # E: Incompatible types in assignment (expression has type \"i32\", variable has type \"i64\")\nd: i64 = i64(a)\ne: i32 = b  # E: Incompatible types in assignment (expression has type \"i64\", variable has type \"i32\")\nf: i32 = i32(b)\ng: int = a\nh: int = b\n\nf1(1)\nf1(a)\nf1(b)\nf2(1)\nf2(g)\nf2(h)\nf2(a)\nf2(b)  # E: Argument 1 to \"f2\" has incompatible type \"i64\"; expected \"i32\"\n[builtins fixtures/dict.pyi]\n\n[case testNativeIntJoins]\nfrom typing import TypeVar, Any\nfrom mypy_extensions import i32, i64\n\nT = TypeVar('T')\n\ndef join(x: T, y: T) -> T: return x\n\nn32: i32 = 0\nn64: i64 = 1\nn = 2\n\nreveal_type(join(n32, n))  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(join(n, n32))  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(join(n64, n))  # N: Revealed type is \"mypy_extensions.i64\"\nreveal_type(join(n, n64))  # N: Revealed type is \"mypy_extensions.i64\"\n# i32 and i64 aren't treated as compatible\nreveal_type(join(n32, n64))  # N: Revealed type is \"builtins.object\"\nreveal_type(join(n64, n32))  # N: Revealed type is \"builtins.object\"\n\na: Any\nreveal_type(join(n, a))    # N: Revealed type is \"Any\"\nreveal_type(join(n32, a))  # N: Revealed type is \"Any\"\nreveal_type(join(a, n64))  # N: Revealed type is \"Any\"\nreveal_type(join(n64, a))  # N: Revealed type is \"Any\"\nreveal_type(join(a, n64))  # N: Revealed type is \"Any\"\n[builtins fixtures/dict.pyi]\n\n[case testNativeIntMeets]\nfrom typing import TypeVar, Callable, Any\nfrom mypy_extensions import i32, i64\n\nT = TypeVar('T')\n\ndef f32(x: i32) -> None: pass\ndef f64(x: i64) -> None: pass\ndef f(x: int) -> None: pass\ndef fa(x: Any) -> None: pass\n\ndef meet(c1: Callable[[T], None], c2: Callable[[T], None]) -> T:\n    pass\n\nreveal_type(meet(f32, f))  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(meet(f, f32))  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(meet(f64, f))  # N: Revealed type is \"mypy_extensions.i64\"\nreveal_type(meet(f, f64))  # N: Revealed type is \"mypy_extensions.i64\"\nif object():\n    reveal_type(meet(f32, f64))  # N: Revealed type is \"Never\"\nif object():\n    reveal_type(meet(f64, f32))  # N: Revealed type is \"Never\"\n\nreveal_type(meet(f, fa))    # N: Revealed type is \"builtins.int\"\nreveal_type(meet(f32, fa))  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(meet(fa, f32))  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(meet(f64, fa))  # N: Revealed type is \"mypy_extensions.i64\"\nreveal_type(meet(fa, f64))  # N: Revealed type is \"mypy_extensions.i64\"\n[builtins fixtures/dict.pyi]\n\n[case testNativeIntCoerceInArithmetic]\nfrom mypy_extensions import i32, i64\n\nreveal_type(i32(1) + 1)  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(1 + i32(1))  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(i64(1) + 1)  # N: Revealed type is \"mypy_extensions.i64\"\nreveal_type(1 + i64(1))  # N: Revealed type is \"mypy_extensions.i64\"\nn = int()\nreveal_type(i32(1) + n)  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(n + i32(1))  # N: Revealed type is \"mypy_extensions.i32\"\n[builtins fixtures/dict.pyi]\n\n[case testNativeIntNoNarrowing]\nfrom mypy_extensions import i32\n\nx: i32 = 1\nif int():\n    x = 2\n    reveal_type(x)  # N: Revealed type is \"mypy_extensions.i32\"\nreveal_type(x)  # N: Revealed type is \"mypy_extensions.i32\"\n\ny = 1\nif int():\n    # We don't narrow an int down to i32, since they have different\n    # representations.\n    y = i32(1)\n    reveal_type(y)  # N: Revealed type is \"builtins.int\"\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n\n[case testNativeIntFloatConversion]\nfrom typing import TypeVar, Callable\nfrom mypy_extensions import i32\n\nx: i32 = 1.1  # E: Incompatible types in assignment (expression has type \"float\", variable has type \"i32\")\ny: float = i32(1)  # E: Incompatible types in assignment (expression has type \"i32\", variable has type \"float\")\n\nT = TypeVar('T')\n\ndef join(x: T, y: T) -> T: return x\n\nreveal_type(join(x, y))  # N: Revealed type is \"builtins.object\"\nreveal_type(join(y, x))  # N: Revealed type is \"builtins.object\"\n\ndef meet(c1: Callable[[T], None], c2: Callable[[T], None]) -> T:\n    pass\n\ndef ff(x: float) -> None: pass\ndef fi32(x: i32) -> None: pass\n\nif object():\n    reveal_type(meet(ff, fi32))  # N: Revealed type is \"Never\"\nif object():\n    reveal_type(meet(fi32, ff))  # N: Revealed type is \"Never\"\n[builtins fixtures/dict.pyi]\n\n[case testNativeIntForLoopRange]\nfrom mypy_extensions import i64, i32\n\nfor a in range(i64(5)):\n    reveal_type(a)  # N: Revealed type is \"mypy_extensions.i64\"\n\nfor b in range(0, i32(5)):\n    reveal_type(b)  # N: Revealed type is \"mypy_extensions.i32\"\n\nfor c in range(i64(0), 5):\n    reveal_type(c)  # N: Revealed type is \"mypy_extensions.i64\"\n\nfor d in range(i64(0), i64(5)):\n    reveal_type(d)  # N: Revealed type is \"mypy_extensions.i64\"\n\nfor e in range(i64(0), i32(5)):\n    reveal_type(e)  # N: Revealed type is \"builtins.int\"\n\nfor f in range(0, i64(3), 2):\n    reveal_type(f)  # N: Revealed type is \"mypy_extensions.i64\"\n\nn = 5\nfor g in range(0, n, i64(2)):\n    reveal_type(g)  # N: Revealed type is \"mypy_extensions.i64\"\n[builtins fixtures/primitives.pyi]\n\n[case testNativeIntComprehensionRange]\nfrom mypy_extensions import i64, i32\n\nreveal_type([a for a in range(i64(5))])  # N: Revealed type is \"builtins.list[mypy_extensions.i64]\"\n[reveal_type(a) for a in range(0, i32(5))]  # N: Revealed type is \"mypy_extensions.i32\"\n[builtins fixtures/primitives.pyi]\n\n[case testNativeIntNarrowing]\nfrom typing import Union\nfrom mypy_extensions import i64, i32\n\ndef narrow_i64(x: Union[str, i64]) -> None:\n    if isinstance(x, i64):\n        reveal_type(x)  # N: Revealed type is \"mypy_extensions.i64\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    reveal_type(x)  # N: Revealed type is \"builtins.str | mypy_extensions.i64\"\n\n    if isinstance(x, str):\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"mypy_extensions.i64\"\n    reveal_type(x)  # N: Revealed type is \"builtins.str | mypy_extensions.i64\"\n\n    if isinstance(x, int):\n        reveal_type(x)  # N: Revealed type is \"mypy_extensions.i64\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    reveal_type(x)  # N: Revealed type is \"builtins.str | mypy_extensions.i64\"\n\ndef narrow_i32(x: Union[str, i32]) -> None:\n    if isinstance(x, i32):\n        reveal_type(x)  # N: Revealed type is \"mypy_extensions.i32\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    reveal_type(x)  # N: Revealed type is \"builtins.str | mypy_extensions.i32\"\n\n    if isinstance(x, str):\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"mypy_extensions.i32\"\n    reveal_type(x)  # N: Revealed type is \"builtins.str | mypy_extensions.i32\"\n\n    if isinstance(x, int):\n        reveal_type(x)  # N: Revealed type is \"mypy_extensions.i32\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    reveal_type(x)  # N: Revealed type is \"builtins.str | mypy_extensions.i32\"\n\n[builtins fixtures/primitives.pyi]\n"
  },
  {
    "path": "test-data/unit/check-newsemanal.test",
    "content": "-- Test cases for the new semantic analyzer\n\n[case testNewAnalyzerEmpty]\n\n[case testNewAnalyzerSimpleAssignment]\nx = 1\nx.y # E: \"int\" has no attribute \"y\"\ny # E: Name \"y\" is not defined\n\n[case testNewAnalyzerSimpleAnnotation]\nx: int = 0\ny: str = 0 \\\n    # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testNewAnalyzerSimpleClass]\nclass A:\n    x: int\na: A\na.x\na.y # E: \"A\" has no attribute \"y\"\n\n[case testNewAnalyzerErrorInClassBody]\nclass A:\n    x # E: Name \"x\" is not defined\n\n[case testNewAnalyzerTypeAnnotationForwardReference]\nclass A:\n    b: B\nclass B:\n    a: A\na: A\nb: B\na.b = a # E: Incompatible types in assignment (expression has type \"A\", variable has type \"B\")\na.b = b\nb.a = a\nb.a = b # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n\n[case testNewAnalyzerTypeAnnotationCycle1]\nimport b\n[file a.py]\nimport b\nclass A: pass\ny: b.B\ny() # E: \"B\" not callable\n[file b.py]\nimport a\nclass B: pass\nx: a.A\nreveal_type(x) # N: Revealed type is \"a.A\"\n\n[case testNewAnalyzerTypeAnnotationCycle2]\nimport a\n[file a.py]\nfrom b import B\nclass A: pass\ny: B\ny()  # E: \"B\" not callable\n[file b.py]\nfrom a import A\nclass B: pass\nx: A\nx()  # E: \"A\" not callable\n\n[case testNewAnalyzerTypeAnnotationCycle3]\nimport b\n[file a.py]\nfrom b import bad # E: Module \"b\" has no attribute \"bad\"; maybe \"bad2\"?\n[file b.py]\nfrom a import bad2 # E: Module \"a\" has no attribute \"bad2\"; maybe \"bad\"?\n\n[case testNewAnalyzerTypeAnnotationCycle4]\nimport b\n[file a.py]\nfrom b import bad # E: Module \"b\" has no attribute \"bad\"\n[file b.py]\n# TODO: Could we generate an error here as well?\nfrom a import bad\n[targets a, b, a, b, a, b, a, b, __main__]\n\n[case testNewAnalyzerExportedValuesInImportAll]\nfrom m import *\n_ = a\n_ = b\n_ = c\n_ = d\n_e = e\n_f = f # E: Name \"f\" is not defined\n_ = _g # E: Name \"_g\" is not defined\nreveal_type(_e)  # N: Revealed type is \"m.A\"\n[file m.py]\n__all__ = ['a']\n__all__ += ('b',)\n__all__.append('c')\n__all__.extend(('d', 'e'))\n\na = b = c = d = _g = 1\ne: 'A'\nf: 'A'\n\nclass A: ...\n[builtins fixtures/module_all.pyi]\n\n[case testNewAnalyzerSimpleFunction]\ndef f(x: int) -> str:\n    return 'x'\n\ndef g(x: int) -> int:\n    y = f(1)\n    return y # E: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testNewAnalyzerSimpleMethod]\nclass A:\n    def __init__(self, x: int) -> None:\n        self.x = x\n\n    def f(self) -> str:\n        return self.x # E: Incompatible return value type (got \"int\", expected \"str\")\n\n    def g(self) -> int:\n        return self.f() # E: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testNewAnalyzerFunctionForwardRef]\ndef f() -> None:\n    x = g(1) # E: Argument 1 to \"g\" has incompatible type \"int\"; expected \"str\"\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n\ndef g(x: str) -> str:\n    return x\n\n[case testNewAnalyzerExportedImportThreePasses]\nimport b\n\n[file a.py]\nfrom b import b1 as a2\nfrom b import b2 as a3\n\ndef a1() -> int: pass\n\nreveal_type(a3()) # N: Revealed type is \"builtins.int\"\n\n[file b.py]\nfrom a import a1 as b2\nfrom a import a2 as b3\n\ndef b1() -> str: pass\n\nreveal_type(b3()) # N: Revealed type is \"builtins.str\"\n\n[case testNewAnalyzerBool]\nreveal_type(True) # N: Revealed type is \"Literal[True]?\"\nreveal_type(False) # N: Revealed type is \"Literal[False]?\"\n\n[case testNewAnalyzerNewTypeMultiplePasses]\nimport b\n\n[file a.py]\nfrom typing import NewType\nimport b\nclass A: pass\nN2 = NewType('N2', b.N1)\ndef f1(x: A) -> None: pass\ndef f2(x: b.N1) -> None: pass\ndef f3(x: N2) -> None: pass\na = A()\nn1 = b.N1(a)\nn2 = N2(n1)\nf1(a)\nf1(n1)\nf1(n2)\nf2(a) # E: Argument 1 to \"f2\" has incompatible type \"A\"; expected \"N1\"\nf2(n1)\nf2(n2)\nf3(a) # E: Argument 1 to \"f3\" has incompatible type \"A\"; expected \"N2\"\nf3(n1) # E: Argument 1 to \"f3\" has incompatible type \"N1\"; expected \"N2\"\nf3(n2)\n\n# Test N2 etc.\n\n[file b.py]\nfrom typing import NewType\nimport a\nN1 = NewType('N1', a.A)\n\n[case testNewAnalyzerInheritanceForwardRef]\nclass C(B):\n    pass\nclass B(A):\n    pass\nclass A:\n    def __init__(self, x: str) -> None: pass\n    def f(self, x: int) -> None: pass\n\nC(1) # E: Argument 1 to \"C\" has incompatible type \"int\"; expected \"str\"\nB(1) # E: Argument 1 to \"B\" has incompatible type \"int\"; expected \"str\"\nC('').f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\nB('').f('') # E: Argument 1 to \"f\" of \"A\" has incompatible type \"str\"; expected \"int\"\n\n[case testNewAnalyzerInheritanceMROInCycle]\nimport a\n\n[file a.py]\nfrom b import A\nimport b\n\nclass B(A):\n    b: int\n\nclass D(b.C):\n    d: int\n\nd = D()\nreveal_type(d.a) # N: Revealed type is \"builtins.int\"\nreveal_type(d.b) # N: Revealed type is \"builtins.int\"\nreveal_type(d.c) # N: Revealed type is \"builtins.int\"\nreveal_type(d.d) # N: Revealed type is \"builtins.int\"\n\n[file b.py]\nfrom a import B\n\nclass A:\n    a: int\n\nclass C(B):\n    c: int\n\n[targets b, a, b, a, __main__]\n\n[case testNewAnalyzerTypedDictClass]\nfrom typing import TypedDict\nimport a\nclass T1(TypedDict):\n    x: A\nclass A: pass\nreveal_type(T1(x=A())) # E\n\n[file a.py]\nfrom typing import TypedDict\nfrom b import TD1 as TD2, TD3\nclass T2(TD3):\n    x: int\nreveal_type(T2(x=2)) # E\n\n[file b.py]\nfrom a import TypedDict as TD1\nfrom a import TD2 as TD3\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[out]\ntmp/a.py:5: note: Revealed type is \"TypedDict('a.T2', {'x': builtins.int})\"\nmain:6: note: Revealed type is \"TypedDict('__main__.T1', {'x': __main__.A})\"\n\n\n[case testNewAnalyzerTypedDictClassInheritance]\nfrom typing import TypedDict\n\nclass T2(T1):\n    y: int\n\nclass T1(TypedDict):\n    x: str\n\nclass T3(TypedDict):\n    x: str\n\nclass T4(T3):\n    y: A\n\nclass A: pass\n\nT2(x=0, y=0) # E: Incompatible types (expression has type \"int\", TypedDict item \"x\" has type \"str\")\nx: T2\nreveal_type(x) # N: Revealed type is \"TypedDict('__main__.T2', {'x': builtins.str, 'y': builtins.int})\"\ny: T4\nreveal_type(y) # N: Revealed type is \"TypedDict('__main__.T4', {'x': builtins.str, 'y': __main__.A})\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNewAnalyzerRedefinitionAndDeferral1a]\nimport a\n\n[file a.py]\nMYPY = False\nif MYPY:\n    from b import x as y\nx = 0\n\ndef y(): pass # E: Name \"y\" already defined on line 4\nreveal_type(y) # N: Revealed type is \"builtins.int\"\n\ny2 = y\nclass y2: pass # E: Name \"y2\" already defined on line 9\nreveal_type(y2) # N: Revealed type is \"builtins.int\"\n\ny3, y4 = y, y\nif MYPY:  # Tweak processing order\n    from b import f as y3 # E: Incompatible import of \"y3\" (imported name has type \"Callable[[], Any]\", local name has type \"int\")\nreveal_type(y3) # N: Revealed type is \"builtins.int\"\n\n[file b.py]\nfrom a import x\n\ndef f(): pass\n\n[targets a, b, a, a.y, b.f, __main__]\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerRedefinitionAndDeferral1b]\nimport a\n\n[file a.py]\nfrom b import x as y\nx = 0\n\ndef y(): pass # E: Name \"y\" already defined on line 2\nreveal_type(y) # N: Revealed type is \"builtins.int\"\n\ny2 = y\nclass y2: pass # E: Name \"y2\" already defined on line 7\nreveal_type(y2) # N: Revealed type is \"builtins.int\"\n\ny3, y4 = y, y\nfrom b import f as y3 # E: Incompatible import of \"y3\" (imported name has type \"Callable[[], Any]\", local name has type \"int\")\nreveal_type(y3) # N: Revealed type is \"builtins.int\"\n\n[file b.py]\nMYPY = False\nif MYPY:  # Tweak processing order\n    from a import x\n\ndef f(): pass\n\n[targets b, a, b, a, b.f, a.y, __main__]\n\n[case testNewAnalyzerRedefinitionAndDeferral2a]\nimport a\n\n[file a.py]\nMYPY = False\nif MYPY:  # Tweak processing order\n    from b import C as C2\nclass C: pass\nclass C2: pass # E: Name \"C2\" already defined on line 4\n\n[file b.py]\nfrom a import C\n\n[case testNewAnalyzerRedefinitionAndDeferral2b]\nimport a\n\n[file a.py]\nfrom b import C as C2\nclass C: pass\n\nclass C2: pass # E: Name \"C2\" already defined on line 2\n[file b.py]\nMYPY = False\nif MYPY:  # Tweak processing order\n    from a import C\n\n[case testNewAnalyzerRedefinitionAndDeferral3]\nimport a\n\n[file a.py]\nfrom b import f as g\ndef f(): pass\n\na, *b = g()\nclass b(): pass # E: Name \"b\" already defined on line 4\nreveal_type(b) # N: Revealed type is \"Any\"\n\n[file b.py]\nfrom a import f\n\n[case testNewAnalyzerImportStarForwardRef1]\nimport a\n\n[file a.py]\nx: A\nreveal_type(x) # N: Revealed type is \"b.A\"\n\nfrom b import *\n\nclass A: pass # E: Name \"A\" already defined (possibly by an import)\n\n[file b.py]\nclass A: pass\nMYPY = False\nif MYPY:  # Tweak processing order\n    from a import x\n\n[case testNewAnalyzerImportStarForwardRef2]\nimport a\n\n[file a.py]\nx: A\nreveal_type(x) # N: Revealed type is \"b.A\"\n\nMYPY = False\nif MYPY: # Tweak processing order\n    from b import *\n\nclass A: pass # E: Name \"A\" already defined (possibly by an import)\n\n[file b.py]\nclass A: pass\nfrom a import x\n\n[case testNewAnalyzerClassInFunction]\ndef main() -> None:\n    x: C\n    class C:\n        def __init__(self) -> None:\n            self.x: A\n            x()  # E: \"C\" not callable\n    reveal_type(x.x)  # N: Revealed type is \"__main__.A@8\"\n    class A: pass\n\n[case testNewAnalyzerMutuallyRecursiveFunctions]\ndef main() -> None:\n    def f() -> int:\n        reveal_type(g())  # N: Revealed type is \"builtins.str\"\n        return int()\n    def g() -> str:\n        reveal_type(f())  # N: Revealed type is \"builtins.int\"\n        return str()\n\n[case testNewAnalyzerMissingNamesInFunctions]\ndef main() -> None:\n    def f() -> None:\n        x  # E: Name \"x\" is not defined\n        class C:\n            x  # E: Name \"x\" is not defined\n\n[case testNewAnalyzerCyclicDefinitions]\n# flags: --disable-error-code used-before-def\ngx = gy  # E: Cannot resolve name \"gy\" (possible cyclic definition)\ngy = gx\ndef main() -> None:\n    class C:\n        def meth(self) -> None:\n            lx = ly  # E: Cannot resolve name \"ly\" (possible cyclic definition) \\\n                     # N: Recursive types are not allowed at function scope\n            ly = lx\n\n[case testNewAnalyzerCyclicDefinitionCrossModule]\nimport b\n[file a.py]\nimport b\nx = b.x  # E: Cannot resolve attribute \"x\" (possible cyclic definition) \\\n         # E: Module has no attribute \"x\"\n[file b.py]\nimport a\nx = a.x\n[builtins fixtures/module.pyi]\n\n[case testNewAnalyzerMutuallyRecursiveOverloadedFunctions]\nfrom typing import overload, Union\n\ndef main() -> None:\n    @overload\n    def f(x: int) -> int: ...\n    @overload\n    def f(x: str) -> str: ...\n    def f(x: Union[int, str]) -> Union[int, str]:\n        reveal_type(g(str()))  # N: Revealed type is \"builtins.str\"\n        return x\n    @overload\n    def g(x: int) -> int: ...\n    @overload\n    def g(x: str) -> str: ...\n    def g(x: Union[int, str]) -> Union[int, str]:\n        reveal_type(f(int()))  # N: Revealed type is \"builtins.int\"\n        return float()  # E: Incompatible return value type (got \"float\", expected \"int | str\")\n\n[case testNewAnalyzerNestedClassInMethod]\nclass C:\n    class D:\n        def meth(self) -> None:\n            x: Out.In\n            reveal_type(x.t)  # N: Revealed type is \"builtins.int\"\n            class Out:\n                class In:\n                    def meth(self) -> None:\n                        self.t: int\n\n[case testNewAnalyzerDeeplyNestedFunctions]\nclass Out:\n    class In:\n        def meth(self) -> None:\n            x: C.D\n            reveal_type(x.t)  # N: Revealed type is \"__main__.Test@10\"\n            class C:\n                class D:\n                    def meth(self) -> None:\n                        self.t: Test\n                        class Test:\n                            def test(self) -> None:\n                                def one() -> int:\n                                    reveal_type(other())  # N: Revealed type is \"builtins.str\"\n                                    return int()\n                                def other() -> str:\n                                    reveal_type(one())  # N: Revealed type is \"builtins.int\"\n                                    return str()\n\n[case testNewAnalyzerNestedClass1]\nclass A:\n    class B:\n        x: int\n\n        def __init__(self, x: int) -> None:\n            self.x = x\n\n        def f(self) -> str:\n            return self.x # E: Incompatible return value type (got \"int\", expected \"str\")\n\nb: A.B\nb = A.B('') # E: Argument 1 to \"B\" has incompatible type \"str\"; expected \"int\"\nreveal_type(b) # N: Revealed type is \"__main__.A.B\"\nreveal_type(b.x) # N: Revealed type is \"builtins.int\"\nreveal_type(b.f()) # N: Revealed type is \"builtins.str\"\n\n[case testNewAnalyzerNestedClass2]\nclass A:\n    class B:\n        x: int\n\n        def __init__(self, x: int) -> None:\n            self.x = x\n\n        def f(self) -> str:\n            return self.x # E: Incompatible return value type (got \"int\", expected \"str\")\n\nb: A.B\nb = A.B('') # E: Argument 1 to \"B\" has incompatible type \"str\"; expected \"int\"\nreveal_type(b) # N: Revealed type is \"__main__.A.B\"\nreveal_type(b.x) # N: Revealed type is \"builtins.int\"\nreveal_type(b.f()) # N: Revealed type is \"builtins.str\"\n[case testNewAnalyzerGenerics]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    def __init__(self, x: T) -> None:\n        self.x = x\n\n    def get(self) -> T:\n        return self.x\n\nc: C[int]\nc2: C[int, str] # E: \"C\" expects 1 type argument, but 2 given\nc3: C\nc = C('') # E: Argument 1 to \"C\" has incompatible type \"str\"; expected \"int\"\nreveal_type(c.get()) # N: Revealed type is \"builtins.int\"\nreveal_type(c2) # N: Revealed type is \"__main__.C[Any]\"\nreveal_type(c3) # N: Revealed type is \"__main__.C[Any]\"\n[case testNewAnalyzerGenericsTypeVarForwardRef]\nfrom typing import TypeVar, Generic\n\nclass C(Generic[T]):\n    def __init__(self, x: T) -> None:\n        self.x = x\n\n    def get(self) -> T:\n        return self.x\n\nT = TypeVar('T')\n\nc: C[int]\nreveal_type(c) # N: Revealed type is \"__main__.C[builtins.int]\"\nc = C('') # E: Argument 1 to \"C\" has incompatible type \"str\"; expected \"int\"\nreveal_type(c.get()) # N: Revealed type is \"builtins.int\"\n\n[case testNewAnalyzerTypeAlias]\nfrom typing import Union, TypeVar, Generic\n\nT = TypeVar('T')\nS = TypeVar('S')\nclass D(Generic[T, S]): pass\n\nclass C: pass\n\nC2 = C\nU = Union[C, int]\nG = D[T, C]\n\nc: C2\nreveal_type(c) # N: Revealed type is \"__main__.C\"\nu: U\nreveal_type(u) # N: Revealed type is \"__main__.C | builtins.int\"\ng: G[int]\nreveal_type(g) # N: Revealed type is \"__main__.D[builtins.int, __main__.C]\"\n[case testNewAnalyzerTypeAlias2]\nfrom typing import Union\n\nclass C(D): pass\n\nA = Union[C, int]\nx: A\nreveal_type(x) # N: Revealed type is \"__main__.C | builtins.int\"\n\nclass D: pass\n\n[case testNewAnalyzerBuiltinTypeAliases]\nfrom typing import List\n\nx: List[C]\nreveal_type(x) # N: Revealed type is \"builtins.list[__main__.C]\"\n\nclass C: pass\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerVersionCheck]\nimport sys\n\nif sys.version_info[0] < 2:\n    1()\n    import nonexistent\nelse:\n    def f(x: int) -> None: pass\n\nf('') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\ndef g() -> None:\n    if sys.version_info[0] < 3:\n        import nonexistent2\n    else:\n        1() # E: \"int\" not callable\n[builtins fixtures/ops.pyi]\n\n[case testNewAnalyzerVersionCheck2]\nimport sys\n\nassert sys.version_info[0] == 3\n1() # E: \"int\" not callable\nassert sys.version_info[0] < 3\n''()\n[builtins fixtures/ops.pyi]\n\n[case testNewAnalyzerOverload]\nfrom typing import overload, Union\n\n@overload\ndef f(x: int) -> int: ...\n@overload\ndef f(x: str) -> str: ...\ndef f(x: Union[int, str]) -> Union[int, str]:\n    return 1.0 # E: Incompatible return value type (got \"float\", expected \"int | str\")\n\nf(1)\nf('')\nf(1.0) # E: No overload variant of \"f\" matches argument type \"float\" \\\n       # N: Possible overload variants: \\\n       # N:     def f(x: int) -> int \\\n       # N:     def f(x: str) -> str\n\n[case testNewAnalyzerOverload2]\nfrom typing import overload, Union\n\nclass A:\n    @overload\n    def f(self, x: int) -> int: ...\n    @overload\n    def f(self, x: str) -> str: ...\n    def f(self, x: Union[int, str]) -> Union[int, str]:\n        return 1.0 # E: Incompatible return value type (got \"float\", expected \"int | str\")\n\na = A()\na.f(1)\na.f('')\na.f(1.0) # E: No overload variant of \"f\" of \"A\" matches argument type \"float\" \\\n         # N: Possible overload variants: \\\n         # N:     def f(self, x: int) -> int \\\n         # N:     def f(self, x: str) -> str\n\n[case testNewAnalyzerPromotion]\ndef f(x: float) -> None: pass\ny: int\nf(y)\nf(1)\n[builtins fixtures/primitives.pyi]\n\n[case testNewAnalyzerFunctionDecorator]\n# flags: --disable-error-code used-before-def\nfrom typing import Callable\n\n@dec\ndef f1(x: int) -> int:\n    return '' # E: Incompatible return value type (got \"str\", expected \"int\")\n\ndef dec(f: Callable[[int], int]) -> Callable[[str], str]: ...\n\n@dec\ndef f2(x: int) -> int:\n    return '' # E: Incompatible return value type (got \"str\", expected \"int\")\n\nf1(1) # E: Argument 1 to \"f1\" has incompatible type \"int\"; expected \"str\"\nreveal_type(f1('')) # N: Revealed type is \"builtins.str\"\nf2(1) # E: Argument 1 to \"f2\" has incompatible type \"int\"; expected \"str\"\n\n[case testNewAnalyzerTypeVarForwardReference]\n# flags: --disable-error-code used-before-def\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nXY = TypeVar('XY', X, Y)\n\nclass C(Generic[T]): pass\n\nclass D(C[XY], Generic[XY]): pass\n\nclass X: pass\nclass Y: pass\n\nx: D[int]  # E: Value of type variable \"XY\" of \"D\" cannot be \"int\"\ny: D[Y]\n\n[case testNewAnalyzerTypeVarForwardReference2]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nXY = TypeVar('XY', 'X', 'Y')\n\nclass C(Generic[T]): pass\n\nclass D(C[XY]): pass\n\nclass X: pass\nclass Y: pass\n\nx: D[int]  # E: Value of type variable \"XY\" of \"D\" cannot be \"int\"\ny: D[Y]\n\n[case testNewAnalyzerTypeVarForwardReferenceValuesDeferred]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nXY = TypeVar('XY', 'X', 'Y')\n\nclass C(Generic[T]): pass\n\nclass D(C[XY], Generic[XY]): pass\n\nclass X(Defer): pass\nclass Y(Defer): pass\nclass Defer: ...\n\nx: D[int]  # E: Value of type variable \"XY\" of \"D\" cannot be \"int\"\ny: D[Y]\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerTypeVarForwardReferenceBoundDeferred]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\nTY = TypeVar('TY', bound='Y')\n\nclass C(Generic[T]): pass\n\nclass D(C[TY], Generic[TY]): pass\n\nclass Y(Defer): pass\nclass Defer: ...\n\nx: D[int]  # E: Type argument \"int\" of \"D\" must be a subtype of \"Y\"\ny: D[Y]\n\n[case testNewAnalyzerTypeVarForwardReferenceErrors]\nfrom typing import TypeVar, Generic\n\nclass C(Generic[T]):\n    def __init__(self, x: T) -> None: ...\ndef func(x: U) -> U: ...\n\nU = TypeVar('U', asdf, asdf)  # E: Name \"asdf\" is not defined\nT = TypeVar('T', bound='asdf')  # E: Name \"asdf\" is not defined\n\nreveal_type(C)  # N: Revealed type is \"def [T <: Any] (x: T`1) -> __main__.C[T`1]\"\nreveal_type(func)  # N: Revealed type is \"def [U in (Any, Any)] (x: U`-1) -> U`-1\"\n\n[case testNewAnalyzerSubModuleInCycle]\nimport a\n[file a.py]\nMYPY = False\nif MYPY:\n    from b.c import x\n[file b/__init__.pyi]\nimport b.c\n[file b/c.pyi]\nx = 0\nimport a\n\n[case testNewAnalyzerBaseClassSelfReference]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T')\n\nclass A(Generic[T]): pass\n\nclass C(A[C]):\n    pass\n\nclass D(A['D']):\n    pass\n\na1: A[C] = C()\na2: A[D] = C() \\\n    # E: Incompatible types in assignment (expression has type \"C\", variable has type \"A[D]\")\n\n[case testNewAnalyzerTypeVarBoundForwardRef]\nfrom typing import TypeVar\n\nT = TypeVar('T', bound='C')\n\nclass C: pass\nclass D(C): pass\nclass E: pass\n\ndef f(x: T) -> T:\n    return x\n\nreveal_type(f(D())) # N: Revealed type is \"__main__.D\"\nf(E()) # E: Value of type variable \"T\" of \"f\" cannot be \"E\"\n\n[case testNewAnalyzerNameExprRefersToIncompleteType]\nimport a\n\n[file a.py]\nfrom b import f\n\nclass C(D): pass\nclass D: pass\n\n[file b.py]\nfrom a import C\nreveal_type(C()) # N: Revealed type is \"a.C\"\ndef f(): pass\n\n[case testNewAnalyzerMemberExprRefersToIncompleteType]\nimport a\n\n[file a.py]\nfrom b import f\n\nclass C(D): pass\nclass D: pass\n\n[file b.py]\nimport a\nreveal_type(a.C()) # N: Revealed type is \"a.C\"\ndef f(): pass\n\n[case testNewAnalyzerNamedTupleCall]\nfrom typing import NamedTuple\n\n\nclass Other: pass\nIn = NamedTuple('In', [('s', str), ('t', Other)])\nOut = NamedTuple('Out', [('x', In), ('y', Other)])\no: Out\ni: In\nreveal_type(o)  # N: Revealed type is \"tuple[tuple[builtins.str, __main__.Other, fallback=__main__.In], __main__.Other, fallback=__main__.Out]\"\nreveal_type(o.x)  # N: Revealed type is \"tuple[builtins.str, __main__.Other, fallback=__main__.In]\"\nreveal_type(o.y)  # N: Revealed type is \"__main__.Other\"\nreveal_type(o.x.t)  # N: Revealed type is \"__main__.Other\"\nreveal_type(i.t)  # N: Revealed type is \"__main__.Other\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerNamedTupleClass]\nfrom typing import NamedTuple\n\no: Out\ni: In\n\nclass Out(NamedTuple):\n    x: In\n    y: Other\n\nreveal_type(o)  # N: Revealed type is \"tuple[tuple[builtins.str, __main__.Other, fallback=__main__.In], __main__.Other, fallback=__main__.Out]\"\nreveal_type(o.x)  # N: Revealed type is \"tuple[builtins.str, __main__.Other, fallback=__main__.In]\"\nreveal_type(o.y)  # N: Revealed type is \"__main__.Other\"\nreveal_type(o.x.t)  # N: Revealed type is \"__main__.Other\"\nreveal_type(i.t)  # N: Revealed type is \"__main__.Other\"\n\nclass In(NamedTuple):\n    s: str\n    t: Other\nclass Other: pass\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerNamedTupleCallNested]\nfrom typing import NamedTuple\n\no: C.Out\ni: C.In\n\nreveal_type(o)  # N: Revealed type is \"tuple[tuple[builtins.str, __main__.C.Other, fallback=__main__.C.In], __main__.C.Other, fallback=__main__.C.Out]\"\nreveal_type(o.x)  # N: Revealed type is \"tuple[builtins.str, __main__.C.Other, fallback=__main__.C.In]\"\nreveal_type(o.y)  # N: Revealed type is \"__main__.C.Other\"\nreveal_type(o.x.t)  # N: Revealed type is \"__main__.C.Other\"\nreveal_type(i.t)  # N: Revealed type is \"__main__.C.Other\"\n\nclass C:\n    In = NamedTuple('In', [('s', str), ('t', Other)])\n    Out = NamedTuple('Out', [('x', In), ('y', Other)])\n    class Other: pass\n[builtins fixtures/tuple.pyi]\n\n\n[case testNewAnalyzerNamedTupleClassNested]\nfrom typing import NamedTuple\n\no: C.Out\ni: C.In\n\nreveal_type(o)  # N: Revealed type is \"tuple[tuple[builtins.str, __main__.C.Other, fallback=__main__.C.In], __main__.C.Other, fallback=__main__.C.Out]\"\nreveal_type(o.x)  # N: Revealed type is \"tuple[builtins.str, __main__.C.Other, fallback=__main__.C.In]\"\nreveal_type(o.y)  # N: Revealed type is \"__main__.C.Other\"\nreveal_type(o.x.t)  # N: Revealed type is \"__main__.C.Other\"\nreveal_type(i.t)  # N: Revealed type is \"__main__.C.Other\"\n\nclass C:\n    class Out(NamedTuple):\n        x: C.In\n        y: C.Other\n    class In(NamedTuple):\n        s: str\n        t: C.Other\n    class Other: pass\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerNamedTupleCallNestedMethod]\nfrom typing import NamedTuple\n\nclass C:\n    def get_tuple(self) -> None:\n        Out = NamedTuple('Out', [('x', 'In'), ('y', 'Other')])\n        In = NamedTuple('In', [('s', str), ('t', 'Other')])\n        class Other: pass\n        self.o: Out\n\nc = C()\nreveal_type(c.o)  # N: Revealed type is \"tuple[tuple[builtins.str, __main__.Other@7, fallback=__main__.C.In@6], __main__.Other@7, fallback=__main__.C.Out@5]\"\nreveal_type(c.o.x)  # N: Revealed type is \"tuple[builtins.str, __main__.Other@7, fallback=__main__.C.In@6]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerNamedTupleClassNestedMethod]\nfrom typing import NamedTuple\n\nclass C:\n    def get_tuple(self) -> None:\n        class Out(NamedTuple):\n            x: In\n            y: Other\n            def method(self) -> In: ...\n        class In(NamedTuple):\n            s: str\n            t: Other\n        class Other: pass\n        self.o: Out\n\nc = C()\nreveal_type(c.o)  # N: Revealed type is \"tuple[tuple[builtins.str, __main__.Other@12, fallback=__main__.C.In@9], __main__.Other@12, fallback=__main__.C.Out@5]\"\nreveal_type(c.o.x)  # N: Revealed type is \"tuple[builtins.str, __main__.Other@12, fallback=__main__.C.In@9]\"\nreveal_type(c.o.method())  # N: Revealed type is \"tuple[builtins.str, __main__.Other@12, fallback=__main__.C.In@9]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerNamedTupleClassForwardMethod]\nfrom typing import NamedTuple\n\nn: NT\nreveal_type(n.get_other())  # N: Revealed type is \"tuple[builtins.str, fallback=__main__.Other]\"\nreveal_type(n.get_other().s)  # N: Revealed type is \"builtins.str\"\n\nclass NT(NamedTuple):\n    x: int\n    y: int\n    def get_other(self) -> Other: pass\n\nclass Other(NamedTuple):\n    s: str\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerNamedTupleSpecialMethods]\nfrom typing import NamedTuple\n\nclass Other: pass\nIn = NamedTuple('In', [('s', str), ('t', Other)])\nOut = NamedTuple('Out', [('x', In), ('y', Other)])\nclass SubO(Out): pass\n\no: SubO\n\nreveal_type(SubO._make)  # N: Revealed type is \"def (iterable: typing.Iterable[Any]) -> tuple[tuple[builtins.str, __main__.Other, fallback=__main__.In], __main__.Other, fallback=__main__.SubO]\"\nreveal_type(o._replace(y=Other()))  # N: Revealed type is \"tuple[tuple[builtins.str, __main__.Other, fallback=__main__.In], __main__.Other, fallback=__main__.SubO]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerNamedTupleBaseClass]\nfrom typing import NamedTuple\nclass Other: pass\nclass In(NamedTuple):\n    s: str\n    t: Other\nclass Out(NamedTuple('Out', [('x', In), ('y', Other)])):\n    pass\n\no: Out\nreveal_type(o)  # N: Revealed type is \"tuple[tuple[builtins.str, __main__.Other, fallback=__main__.In], __main__.Other, fallback=__main__.Out]\"\nreveal_type(o.x)  # N: Revealed type is \"tuple[builtins.str, __main__.Other, fallback=__main__.In]\"\nreveal_type(o.x.t)  # N: Revealed type is \"__main__.Other\"\nreveal_type(Out._make)  # N: Revealed type is \"def (iterable: typing.Iterable[Any]) -> tuple[tuple[builtins.str, __main__.Other, fallback=__main__.In], __main__.Other, fallback=__main__.Out]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerIncompleteRefShadowsBuiltin1]\nimport a\n\n[file a.py]\nfrom typing import TypeVar, Generic\n\nfrom b import C as int\n\nx: int[str]\n\nreveal_type(x) # N: Revealed type is \"a.C[builtins.str]\"\n\nT = TypeVar('T')\nclass C(Generic[T]): pass\n\n[file b.py]\nfrom a import C\n\n[case testNewAnalyzerIncompleteRefShadowsBuiltin2]\nimport b\n\n[file a.py]\nimport b\n\nint = b.C\n\nclass C: pass\n\nx: int\nreveal_type(x) # N: Revealed type is \"b.C\"\n\n[file b.py]\nimport a\n\nint = a.C\n\nclass C: pass\n\nx: int\nreveal_type(x) # N: Revealed type is \"a.C\"\n\n[case testNewAnalyzerNamespaceCompleteness]\nimport a\n\n[file a.py]\nimport b\n\nx: b.C\n\n[file b.py]\nfrom c import *\nclass C: pass\n\n[file c.py]\nimport a\nfrom b import C\n\n[targets c, b, a, c, b, __main__]\n\n[case testNewAnalyzerImportOverExistingInCycle]\nimport a\n[file a.py]\nC = 1\nfrom b import C  # E: Incompatible import of \"C\" (imported name has type \"type[C]\", local name has type \"int\")\n\n[file b.py]\nimport a\n\nclass C(B): ...\nclass B: ...\n\n[case testNewAnalyzerImportOverExistingInCycleStar1]\nimport a\n[file a.py]\nC = 1\nMYPY = False\nif MYPY:  # Tweak processing order\n    from b import *  # E: Incompatible import of \"C\" (imported name has type \"type[C]\", local name has type \"int\")\n\n[file b.py]\nimport a\n\nclass C(B): ...\nclass B: ...\n\n[case testNewAnalyzerImportOverExistingInCycleStar2]\nimport a\n[file a.py]\nC = 1\nfrom b import *  # E: Incompatible import of \"C\" (imported name has type \"type[C]\", local name has type \"int\")\n\n[file b.py]\nMYPY = False\nif MYPY:  # Tweak processing order\n    import a\n\nclass C(B): ...\nclass B: ...\n\n[case testNewAnalyzerIncompleteFixture]\nfrom typing import Tuple\n\nx: Tuple[int]  # E: Name \"tuple\" is not defined\n[builtins fixtures/complex.pyi]\n\n[case testNewAnalyzerMetaclass1]\nclass A(metaclass=B):\n    pass\n\nclass B(type):\n    def f(cls) -> int:\n        return 0\n\nreveal_type(A.f()) # N: Revealed type is \"builtins.int\"\n\n[case testNewAnalyzerMetaclass2]\nclass B(type):\n    def f(cls) -> int:\n        return 0\n\nclass C: pass\n\nclass A(metaclass=B):\n    pass\n\nclass AA(metaclass=C): # E: Metaclasses not inheriting from \"type\" are not supported\n    pass\n\nreveal_type(A.f()) # N: Revealed type is \"builtins.int\"\n[case testNewAnalyzerMetaclassPlaceholder]\nclass B(C): pass\n\nclass A(metaclass=B):\n    pass\n\nclass C(type):\n    def f(cls) -> int:\n        return 0\n\nreveal_type(A.f()) # N: Revealed type is \"builtins.int\"\n\n[case testNewAnalyzerMetaclassSix1]\nimport six\n\nclass A(six.with_metaclass(B)):\n    pass\n\nclass B(type):\n    def f(cls) -> int:\n        return 0\n\nreveal_type(A.f()) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerMetaclassSix2]\nimport six\n\n@six.add_metaclass(B)\nclass A:\n    pass\n\nclass B(type):\n    def f(cls) -> int:\n        return 0\n\nreveal_type(A.f()) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerMetaclassSix3]\nimport six\n\nclass A(six.with_metaclass(B, Defer)):\n    pass\n\nclass B(type):\n    def f(cls) -> int:\n        return 0\n\nclass Defer:\n    x: str\n\nreveal_type(A.f()) # N: Revealed type is \"builtins.int\"\nreveal_type(A.x) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerMetaclassSix4]\nimport six\n\nclass B(type):\n    def f(cls) -> int:\n        return 0\n\nclass A(six.with_metaclass(B, Defer)):\n    pass\n\nclass Defer:\n    x: str\n\nreveal_type(A.f()) # N: Revealed type is \"builtins.int\"\nreveal_type(A.x) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerMetaclassFuture1]\nimport future.utils\n\nclass A(future.utils.with_metaclass(B)):\n    pass\n\nclass B(type):\n    def f(cls) -> int:\n        return 0\n\nreveal_type(A.f()) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerMetaclassFuture3]\nimport future.utils\n\nclass A(future.utils.with_metaclass(B, Defer)):\n    pass\n\nclass B(type):\n    def f(cls) -> int:\n        return 0\n\nclass Defer:\n    x: str\n\nreveal_type(A.f()) # N: Revealed type is \"builtins.int\"\nreveal_type(A.x) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerMetaclassFuture4]\n# flags: --disable-error-code used-before-def\nimport future.utils\n\nclass B(type):\n    def f(cls) -> int:\n        return 0\n\nreveal_type(A.f()) # N: Revealed type is \"builtins.int\"\nreveal_type(A.x) # N: Revealed type is \"builtins.str\"\n\nclass A(future.utils.with_metaclass(B, Defer)):\n    pass\n\nclass Defer:\n    x: str\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerFinalDefiningModuleVar]\nfrom typing import Final\n\nclass D(C): ...\nclass C: ...\n\nx: Final = C()\ny: Final[C] = D()\nbad: Final[D] = C()  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"D\")\n\nreveal_type(x)  # N: Revealed type is \"__main__.C\"\nreveal_type(y)  # N: Revealed type is \"__main__.C\"\n[case testNewAnalyzerFinalDefiningInstanceVar]\nfrom typing import Final\n\nclass D: ...\nclass E(C): ...\n\nclass C:\n    def __init__(self, x: D) -> None:\n        self.x: Final = x\n        self.y: Final[C] = E(D())\nreveal_type(C(D()).x)  # N: Revealed type is \"__main__.D\"\nreveal_type(C(D()).y)  # N: Revealed type is \"__main__.C\"\n[case testNewAnalyzerFinalReassignModuleVar]\nfrom typing import Final\n\nclass A: ...\n\nx: Final = A()\nx = A()  # E: Cannot assign to final name \"x\"\n\nx2: Final = A()\ndef f2() -> None:\n    global x2\n    def f() -> None:\n        g()\n    x2 = A()  # E: Cannot assign to final name \"x2\"\n    def g() -> None:\n        f()\n\n[case testNewAnalyzerFinalReassignModuleReexport]\nimport a\n[file a.py]\nfrom b import ID, A\n\nclass C(A): ...\nID = C()  # E: Cannot assign to final name \"ID\"\n[file b.py]\nfrom typing import Final\nfrom a import C\n\nclass A:\n    x: C\n\nID: Final = A()\n\n[case testNewAnalyzerFinalOverrideInSubclass]\nfrom typing import Final\n\nclass B:\n    def __init__(self, x: int) -> None:\n        self.x: Final = x\n\nclass C(B):\n    x = 1  # E: Cannot assign to final name \"x\"\n\n[case testNewAnalyzerAssignmentAfterStarImport]\nimport a\n[file a.py]\nfrom b import *\n\nx = 1\ndef f(): ...\n[file b.py]\nfrom a import f\nx: int\n\n[case testNewAnalyzerClassLevelImport]\n# flags: --ignore-missing-imports\nclass Test:\n    import a\n    def __init__(self) -> None:\n        some_module = self.a\n\n[case testNewAnalyzerAliasToNotReadyClass]\nimport a\n[file a.py]\nfrom b import B\n\nx: A\nA = B\n[file b.py]\nfrom typing import List\nfrom a import x\n\nclass B(List[B]): pass\n\nreveal_type(x[0][0])  # N: Revealed type is \"b.B\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyClass2]\nfrom typing import List\n\nx: A\n\nclass A(List[B]): pass\nB = A\n\nreveal_type(x[0][0])  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyClass3]\n# flags: --disable-error-code used-before-def\nfrom typing import List\n\nx: B\nB = A\nA = C\nclass C(List[B]): pass\n\nreveal_type(x[0][0])  # N: Revealed type is \"__main__.C\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyNestedClass]\nimport a\n[file a.py]\nfrom b import Out\n\nx: A\nA = Out.B\n[file b.py]\nfrom typing import List\nfrom a import x\n\nclass Out:\n    class B(List[B]): pass\n\nreveal_type(x[0][0])  # N: Revealed type is \"b.Out.B\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyNestedClass2]\nfrom typing import List\n\nx: Out.A\n\nclass Out:\n    class A(List[B]): pass\nB = Out.A\n\nreveal_type(x[0][0])  # N: Revealed type is \"__main__.Out.A\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyClassGeneric]\nimport a\n[file a.py]\nfrom typing import Tuple\nfrom b import B, T\n\nx: A[int]\nA = B[Tuple[T, T]]\n[file b.py]\nfrom typing import List, Generic, TypeVar\nfrom a import x\n\nclass B(List[B], Generic[T]): pass\nT = TypeVar('T')\nreveal_type(x)  # N: Revealed type is \"b.B[tuple[builtins.int, builtins.int]]\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyClassInGeneric]\nimport a\n[file a.py]\nfrom typing import Tuple\nfrom b import B\n\nx: A\nA = Tuple[B, B]\n[file b.py]\nfrom typing import List\nfrom a import x\n\nclass B(List[B]): pass\n\nreveal_type(x)  # N: Revealed type is \"tuple[b.B, b.B]\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyClassDoubleGeneric]\nfrom typing import List, TypeVar, Union\n\nT = TypeVar('T')\n\nx: B[int]\nA = Union[int, T]\nB = A[List[T]]\nclass C(List[B[int]]): pass\n\ny: C\nreveal_type(x)  # N: Revealed type is \"builtins.int | builtins.list[builtins.int]\"\nreveal_type(y[0])  # N: Revealed type is \"builtins.int | builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerForwardAliasFromUnion]\nfrom typing import Union, List\n\nA = Union['B', 'C']\n\nclass D:\n    x: List[A]\n\n    def test(self) -> None:\n        reveal_type(self.x[0].y)  # N: Revealed type is \"builtins.int\"\n\nclass B:\n    y: int\nclass C:\n    y: int\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyTwoDeferrals]\n# flags: --disable-error-code used-before-def\nfrom typing import List\n\nx: B\nB = List[C]\nA = C\nclass C(List[A]): pass\n\nreveal_type(x)  # N: Revealed type is \"builtins.list[__main__.C]\"\nreveal_type(x[0][0])  # N: Revealed type is \"__main__.C\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyDirectBase]\n# flags: --disable-error-code used-before-def\nfrom typing import List\n\ndef test() -> None:\n    x: B\n    B = List[C]\n    class C(B): pass\n\n    reveal_type(x)\n    reveal_type(x[0][0])\n[builtins fixtures/list.pyi]\n[out]\nmain:5: error: Cannot resolve name \"B\" (possible cyclic definition)\nmain:5: note: Recursive types are not allowed at function scope\nmain:6: error: Cannot resolve name \"B\" (possible cyclic definition)\nmain:6: note: Recursive types are not allowed at function scope\nmain:6: error: Cannot resolve name \"C\" (possible cyclic definition)\nmain:9: note: Revealed type is \"Any\"\nmain:10: note: Revealed type is \"Any\"\n\n[case testNewAnalyzerAliasToNotReadyTwoDeferralsFunction]\n# flags: --disable-error-code used-before-def\nimport a\n[file a.py]\nfrom typing import List\nfrom b import D\n\ndef f(x: B) -> List[B]: ...\nB = List[C]\nA = C\nclass C(List[A]): pass\n[file b.py]\nfrom a import f\nclass D: ...\nreveal_type(f)  # N: Revealed type is \"def (x: builtins.list[a.C]) -> builtins.list[builtins.list[a.C]]\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyDirectBaseFunction]\n# flags: --disable-error-code used-before-def\nimport a\n[file a.py]\nfrom typing import List\nfrom b import D\n\ndef f(x: B) -> List[B]: ...\nB = List[C]\nclass C(B): pass\n\n[file b.py]\nfrom a import f\nclass D: ...\nreveal_type(f)  # N: Revealed type is \"def (x: builtins.list[a.C]) -> builtins.list[builtins.list[a.C]]\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasToNotReadyMixed]\nfrom typing import List, Union\nx: A\n\nclass B(List[A]): pass\nclass C(List[A]): pass\n\nA = Union[B, C]\n\nreveal_type(x)  # N: Revealed type is \"__main__.B | __main__.C\"\nreveal_type(x[0])  # N: Revealed type is \"__main__.B | __main__.C\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerTrickyAliasInFuncDef]\nimport a\n[file a.py]\nfrom b import B\ndef func() -> B: ...\nreveal_type(func())  # N: Revealed type is \"builtins.list[tuple[b.C, b.C]]\"\n\n[file b.py]\nfrom typing import List, Tuple\nfrom a import func\n\nclass A: ...\nclass C(A): ...\nB = List[Tuple[C, C]]\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerListComprehension]\nfrom typing import List\nclass A: pass\nclass B: pass\na: List[A]\na = [x for x in a]\nb: List[B] = [x for x in a] # E: List comprehension has incompatible type List[A]; expected List[B]\n[builtins fixtures/for.pyi]\n\n[case testNewAnalyzerDictionaryComprehension]\nfrom typing import Dict, List, Tuple\nabd: Dict[A, B]\nabl: List[Tuple[A, B]]\nabd = {a: b for a, b in abl}\nx: Dict[B, A] = {a: b for a, b in abl} # E: Key expression in dictionary comprehension has incompatible type \"A\"; expected type \"B\" \\\n  # E: Value expression in dictionary comprehension has incompatible type \"B\"; expected type \"A\"\ny: A = {a: b for a, b in abl} # E: Incompatible types in assignment (expression has type \"dict[A, B]\", variable has type \"A\")\nclass A: pass\nclass B: pass\n[builtins fixtures/dict.pyi]\n\n[case testNewAnalyzerTypeArgBoundCheck]\nfrom typing import TypeVar, Generic\n\nclass F(E): pass\nclass E: pass\nT = TypeVar('T', bound=E)\nclass C(Generic[T]): pass\n\nclass D(B): pass\n\nx: C[D] # E: Type argument \"D\" of \"C\" must be a subtype of \"E\"\ny: C[F]\n\nclass B: pass\n\n[case testNewAnalyzerTypeArgValueRestriction]\nfrom typing import TypeVar, Generic\n\nclass F(E): pass\nclass E: pass\nT = TypeVar('T', E, str)\nclass C(Generic[T]): pass\n\nclass D(B): pass\n\nx: C[D] # E: Value of type variable \"T\" of \"C\" cannot be \"D\"\ny: C[E]\nz: C[str]\n\nclass B: pass\n\n[case testNewAnalyzerTypeArgBoundCheckWithContext]\n# flags: --show-error-context\nimport a\n[file a.py]\nfrom typing import TypeVar, Generic\n\nT = TypeVar('T', bound=int)\nclass C(Generic[T]): pass\n\ndef f(x: C[str]) -> None: # E\n    y: C[str] # E\nclass A(C[str]): # E\n    z: C[str] # E\n    def g(self, x: C[str]) -> None: # E\n        a: C[str] # E\n[out]\nmain:2: note: In module imported here:\ntmp/a.py: note: In function \"f\":\ntmp/a.py:6: error: Type argument \"str\" of \"C\" must be a subtype of \"int\"\ntmp/a.py:7: error: Type argument \"str\" of \"C\" must be a subtype of \"int\"\ntmp/a.py: note: In class \"A\":\ntmp/a.py:8: error: Type argument \"str\" of \"C\" must be a subtype of \"int\"\ntmp/a.py:9: error: Type argument \"str\" of \"C\" must be a subtype of \"int\"\ntmp/a.py: note: In member \"g\" of class \"A\":\ntmp/a.py:10: error: Type argument \"str\" of \"C\" must be a subtype of \"int\"\ntmp/a.py:11: error: Type argument \"str\" of \"C\" must be a subtype of \"int\"\n\n[case testNewAnalyzerTypeArgBoundCheckDifferentNodes_no_native_parse]\nfrom typing import TypeVar, TypedDict, Generic, NamedTuple, NewType, Union, Any, cast, overload\n\nT = TypeVar('T', bound=int)\nclass C(Generic[T]): pass\nclass C2(Generic[T]): pass\n\nA = C[str] # E: Value of type variable \"T\" of \"C\" cannot be \"str\" \\\n           # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nB = Union[C[str], int] # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nS = TypeVar('S', bound=C[str]) # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nU = TypeVar('U', C[str], str) # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nN = NamedTuple('N', [\n    ('x', C[str])]) # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nclass N2(NamedTuple):\n    x: C[str]  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nclass TD(TypedDict):\n    x: C[str]  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nclass TD2(TD):\n    y: C2[str]  # E: Type argument \"str\" of \"C2\" must be a subtype of \"int\"\nNT = NewType('NT',\n             C[str]) # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nclass D(\n        C[str]): # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\n    pass\n\nTD3 = TypedDict('TD3', {'x': C[str]}) # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\n\na: Any\nfor i in a: # type: C[str]  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\n    pass\n\nwith a as w: # type: C[str]  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\n    pass\n\ncast(C[str], a)  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nC[str]()  # E: Value of type variable \"T\" of \"C\" cannot be \"str\"\n\ndef f(s: S, y: U) -> None: pass  # No error here\n\n@overload\ndef g(x: C[str]) -> int: ...  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\n@overload\ndef g(x: int) -> int: ...\ndef g(x: Union[C[str], int]) -> int:  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\n    y: C[object]  # E: Type argument \"object\" of \"C\" must be a subtype of \"int\"\n    return 0\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNewAnalyzerTypeArgBoundCheckWithStrictOptional]\n# flags: --config-file tmp/mypy.ini\nimport a\n\n[file b.py]\nfrom typing import TypeVar, Generic\n\nx: C[None]\ny: C[str]  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nz: C[int]\n\nT = TypeVar('T', bound=int)\nclass C(Generic[T]):\n    pass\n\n[file a.py]\nfrom b import C\n\nx: C[None]  # E: Type argument \"None\" of \"C\" must be a subtype of \"int\"\ny: C[str]  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nz: C[int]\n\n[file mypy.ini]\n\\[mypy-a]\nstrict_optional = True\n\\[mypy-b]\nstrict_optional = False\n\n\n[case testNewAnalyzerTypeArgBoundCheckWithStrictOptionalPyProjectTOML]\n# flags: --config-file tmp/pyproject.toml\nimport a\n\n[file b.py]\nfrom typing import TypeVar, Generic\n\nx: C[None]\ny: C[str]  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nz: C[int]\n\nT = TypeVar('T', bound=int)\nclass C(Generic[T]):\n    pass\n\n[file a.py]\nfrom b import C\n\nx: C[None]  # E: Type argument \"None\" of \"C\" must be a subtype of \"int\"\ny: C[str]  # E: Type argument \"str\" of \"C\" must be a subtype of \"int\"\nz: C[int]\n\n[file pyproject.toml]\n\\[[tool.mypy.overrides]]\nmodule = 'a'\nstrict_optional = true\n\\[[tool.mypy.overrides]]\nmodule = 'b'\nstrict_optional = false\n\n\n[case testNewAnalyzerProperty]\nclass A:\n    @property\n    def x(self) -> B:\n        return 0  # E: Incompatible return value type (got \"int\", expected \"B\")\n\n    @property\n    def y(self) -> B:\n        pass\n\n    @y.setter\n    def y(self, x: B) -> None:\n        pass\n\nclass B: pass\n\na = A()\nreveal_type(a.x)  # N: Revealed type is \"__main__.B\"\na.y = 1  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"B\")\n[builtins fixtures/property.pyi]\n\n[case testNewAnalyzerAliasesFixedFew]\nfrom typing import List, Generic, TypeVar\nT = TypeVar('T')\nclass C(Generic[T]):\n    ...\nA = List[C]\nx: A\n\ndef func(x: List[C[T]]) -> T:\n    ...\n\nreveal_type(x)  # N: Revealed type is \"builtins.list[__main__.C[Any]]\"\nreveal_type(func(x))  # N: Revealed type is \"Any\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerAliasesFixedMany]\nfrom typing import List, Generic, TypeVar\n\nT = TypeVar('T')\nclass C(Generic[T]):\n    ...\n\ndef func(x: List[C[T]]) -> T:\n    ...\n\nx: A\nA = List[C[int, str]]  # E: \"C\" expects 1 type argument, but 2 given\n\nreveal_type(x)  # N: Revealed type is \"builtins.list[__main__.C[Any]]\"\nreveal_type(func(x))  # N: Revealed type is \"Any\"\n\n\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerBuiltinAliasesFixed]\nfrom typing import List, Optional\nx: Optional[List] = None\ny: List[str]\n\nreveal_type(x)  # N: Revealed type is \"builtins.list[Any] | None\"\nx = ['a', 'b']\nreveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\nx.extend(y)\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerImportPriosB]\nimport b\n[file a.py]\nfrom b import x\nreveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n[file b.py]\nimport a\nx = (1, 2)\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerImportPriosA]\nimport a\n[file a.py]\nfrom b import x\nreveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\"\n[file b.py]\nimport a\nx = (1, 2)\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerConditionalFunc]\nif int():\n    def f(x: int) -> None:\n        pass\n    def g(x: int) -> None:\n        pass\nelif bool():\n    def f(x: int) -> None:\n        1()  # E: \"int\" not callable\n    def g(x: str) -> None:  # E: All conditional function variants must have identical signatures \\\n                            # N: Original: \\\n                            # N:     def g(x: int) -> None \\\n                            # N: Redefinition: \\\n                            # N:     def g(x: str) -> None\n        pass\nelse:\n    def f(x: int) -> None:\n        ''()  # E: \"str\" not callable\n\nreveal_type(g) # N: Revealed type is \"def (x: builtins.int)\"\n\n[case testNewAnalyzerConditionalFuncDefer]\nif int():\n    def f(x: A) -> None:\n        pass\n    def g(x: A) -> None:\n        pass\nelse:\n    def f(x: A) -> None:\n        1()  # E: \"int\" not callable\n    def g(x: str) -> None:  # E: All conditional function variants must have identical signatures \\\n                            # N: Original: \\\n                            # N:     def g(x: A) -> None \\\n                            # N: Redefinition: \\\n                            # N:     def g(x: str) -> None\n\n        pass\n\nreveal_type(g) # N: Revealed type is \"def (x: __main__.A)\"\n\nclass A: pass\n\n[case testNewAnalyzerConditionalDecoratedFunc]\nfrom typing import Callable\n\ndef dec(f: Callable[[int], None]) -> Callable[[str], None]:\n    pass\n\nif int():\n    from m import f\nelse:\n    @dec\n    def f(x: int) -> None:\n        1()  # E: \"int\" not callable\nreveal_type(f) # N: Revealed type is \"def (builtins.str)\"\n[file m.py]\ndef f(x: str, /) -> None: pass\n\n[case testNewAnalyzerConditionallyDefineFuncOverVar]\nfrom typing import Callable\n\nif int():\n    f: Callable[[str], None]\nelse:\n    def f(x: str) -> None:\n        ...\nreveal_type(f) # N: Revealed type is \"def (builtins.str)\"\n\n[case testNewAnalyzerConditionallyDefineFuncOverClass]\nclass C:\n    1()  # E: \"int\" not callable\ndef C() -> None:  # E: Name \"C\" already defined on line 1\n    ''()  # E: \"str\" not callable\n\n[case testNewAnalyzerTupleIteration]\nfrom typing import Union, Tuple, NamedTuple\n\nclass T(Tuple[B, C]):\n    pass\n\nclass A: pass\nclass B(A): pass\nclass C(A): pass\n\nclass NTInt(NamedTuple):\n    x: int\n    y: int\n\nclass NTStr(NamedTuple):\n    x: str\n    y: str\n\nt1: T\nreveal_type(t1.__iter__) # N: Revealed type is \"def () -> typing.Iterator[__main__.B | __main__.C]\"\n\nt2: NTInt\nreveal_type(t2.__iter__) # N: Revealed type is \"def () -> typing.Iterator[builtins.int]\"\nnt: Union[NTInt, NTStr]\nreveal_type(nt.__iter__) # N: Revealed type is \"(def () -> typing.Iterator[builtins.int]) | (def () -> typing.Iterator[builtins.str])\"\nfor nx in nt:\n    reveal_type(nx) # N: Revealed type is \"builtins.int | builtins.str\"\n\nt: Union[Tuple[int, int], Tuple[str, str]]\nfor x in t:\n    reveal_type(x) # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/for.pyi]\n\n[case testNewAnalyzerFallbackUpperBoundCheckAndFallbacks]\nfrom typing import TypeVar, Generic, Tuple\n\nclass A: pass\nclass B: pass\nclass C(B): pass\n\nS = TypeVar('S', bound='Tuple[G[A], ...]')\n\nclass GG(Generic[S]): pass\n\ng: GG[Tuple[G[B], G[C]]] # E: Type argument \"tuple[G[B], G[C]]\" of \"GG\" must be a subtype of \"tuple[G[A], ...]\" \\\n                         # E: Type argument \"B\" of \"G\" must be a subtype of \"A\" \\\n                         # E: Type argument \"C\" of \"G\" must be a subtype of \"A\"\n\nT = TypeVar('T', bound=A, covariant=True)\n\nclass G(Generic[T]): pass\n\nt: Tuple[G[B], G[C]] # E: Type argument \"B\" of \"G\" must be a subtype of \"A\" \\\n                     # E: Type argument \"C\" of \"G\" must be a subtype of \"A\"\nreveal_type(t.__iter__) # N: Revealed type is \"def () -> typing.Iterator[__main__.G[__main__.B]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerClassKeywordsForward]\nclass C(B, other=A): ...\nclass B: ...\nclass A: ...\n\n[case testNewAnalyzerClassKeywordsCyclic]\nfrom typing import List\n\nclass C(List[C], other=C): ...\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerClassKeywordsError]\nclass C(other=asdf): ...  # E: Name \"asdf\" is not defined\n\n[case testNewAnalyzerMissingImport]\n# flags: --ignore-missing-imports\nimport non_existing\n\nx: C\nclass C: ...\n\n[case testNewAnalyzerMissingImportFrom]\n# flags: --ignore-missing-imports\nfrom non_existing import stuff\n\nx: C\nclass C: ...\n\n[case testNewAnalyzerFollowSkip]\n# flags: --follow-imports=skip\nfrom other import y\nx: C\nclass C: ...\n[file other.py]\ny = 1\n\n[case testNewAnalyzerMissingImportErrors]\n# flags: --ignore-missing-imports\nfrom non_existing import stuff, other_stuff\n\nstuff = 1  # OK\nother_stuff: int = 1  # E: Name \"other_stuff\" already defined (possibly by an import)\n\nx: C\nclass C: ...\n\n[case testNewAnalyzerMissingImportErrorsRedefinition]\n# flags: --ignore-missing-imports\n\nclass Other: ...\nfrom non_existing import Other  # E: Name \"Other\" already defined on line 3\nfrom non_existing import Cls\nclass Cls: ...  # E: Name \"Cls\" already defined (possibly by an import)\n\nx: C\nclass C: ...\n\n[case testNewAnalyzerTupleInit]\nfrom typing import Tuple\n\nc: C\nclass C(Tuple[int, str]):\n    def __init__(self) -> None: pass\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerNotAnAlias]\nclass Meta(type):\n    x = int()\n\nclass C(metaclass=Meta):\n    pass\n\ny = C.x\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\n\n[case testNewAnalyzerFunctionError]\ndef f(x: asdf) -> None:  # E: Name \"asdf\" is not defined\n    pass\n\n[case testNewAnalyzerEnumRedefinition]\nfrom enum import Enum\n\nA = Enum('A', ['x', 'y'])\nA = Enum('A', ['z', 't'])  # E: Name \"A\" already defined on line 3\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerNewTypeRedefinition]\nfrom typing import NewType\n\nA = NewType('A', int)\nA = NewType('A', str)  # E: Cannot redefine \"A\" as a NewType \\\n                       # E: Name \"A\" already defined on line 3\n\n[case testNewAnalyzerNewTypeForwardClass]\nfrom typing import NewType, List\n\nx: C\nreveal_type(x[0])  # N: Revealed type is \"__main__.C\"\n\nC = NewType('C', 'B')\n\nclass B(List[C]):\n    pass\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerNewTypeForwardClassAlias]\nfrom typing import NewType, List\n\nx: D\nreveal_type(x[0])  # N: Revealed type is \"__main__.C\"\n\nC = NewType('C', 'B')\nD = C\n\nclass B(List[D]):\n    pass\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerNewTypeForwardClassAliasReversed]\nfrom typing import NewType, List\n\nx: D\nreveal_type(x[0][0])  # N: Revealed type is \"__main__.C\"\n\nD = C  # E: Name \"C\" is used before definition\nC = NewType('C', 'List[B]')\n\nclass B(List[C]):\n    pass\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerNewTypeForwardClassAliasDirect]\n# flags: --disable-error-code used-before-def\nfrom typing import NewType, List\n\ndef test() -> None:\n    x: D\n    reveal_type(x[0][0])\n\n    D = List[C]\n    C = NewType('C', 'B')\n\n    class B(D):\n        pass\n[builtins fixtures/list.pyi]\n[out]\nmain:5: error: Cannot resolve name \"D\" (possible cyclic definition)\nmain:5: note: Recursive types are not allowed at function scope\nmain:6: note: Revealed type is \"Any\"\nmain:8: error: Cannot resolve name \"D\" (possible cyclic definition)\nmain:8: note: Recursive types are not allowed at function scope\nmain:8: error: Cannot resolve name \"C\" (possible cyclic definition)\nmain:9: error: Argument 2 to NewType(...) must be a valid type\nmain:9: error: Cannot resolve name \"B\" (possible cyclic definition)\nmain:9: note: Recursive types are not allowed at function scope\n\n-- Copied from check-classes.test (tricky corner cases).\n[case testNewAnalyzerNoCrashForwardRefToBrokenDoubleNewTypeClass]\nfrom typing import Any, Dict, List, NewType\n\nFoo = NewType('NotFoo', int)  # type: ignore\nFoos = NewType('Foos', List[Foo])\n\nx: C\nclass C:\n    def frob(self, foos: Dict[Any, Foos]) -> None:\n        foo = foos.get(1)\n        assert foo\n        dict(foo)\n[builtins fixtures/dict.pyi]\n\n[case testNewAnalyzerForwardTypeAliasInBase]\nfrom typing import List, Generic, TypeVar, NamedTuple\nT = TypeVar('T')\n\ndef test() -> None:\n    class C(A, B):  # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n                    # N: Recursive types are not allowed at function scope\n        pass\n    class G(Generic[T]): pass\n    A = G[C]  # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n              # N: Recursive types are not allowed at function scope\n    class B(NamedTuple):\n        x: int\n\n    y: C\n    reveal_type(y.x)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y[0])  # N: Revealed type is \"builtins.int\"\n    x: A\n    reveal_type(x)  # N: Revealed type is \"__main__.G@7[tuple[builtins.int, fallback=__main__.C@5]]\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerDuplicateTypeVar]\nfrom typing import TypeVar, Generic, Any\n\nT = TypeVar('T', bound='B[Any]')\n# The \"int\" error is because of typing fixture.\nT = TypeVar('T', bound='C')  # E: Cannot redefine \"T\" as a type variable \\\n                           # E: Invalid assignment target\n\nclass B(Generic[T]):\n    x: T\nclass C: ...\n\nx: B[int]  # E: Type argument \"int\" of \"B\" must be a subtype of \"B[Any]\"\ny: B[B[Any]]\nreveal_type(y.x)  # N: Revealed type is \"__main__.B[Any]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testNewAnalyzerDuplicateTypeVarImportCycle]\n# flags: --disable-error-code used-before-def\nimport a\n[file a.py]\nfrom typing import TypeVar, Any\nfrom b import B, C\n\nT = TypeVar('T', bound=B[Any])\nT = TypeVar('T', bound=C)  # E: Cannot redefine \"T\" as a type variable \\\n                           # E: Invalid assignment target\n\n[file b.py]\nfrom typing import Generic, Any\nfrom a import T\n\nclass B(Generic[T]):\n    x: T\nclass C: ...\n\nx: B[int]  # E: Type argument \"int\" of \"B\" must be a subtype of \"B[Any]\"\ny: B[B[Any]]\nreveal_type(y.x)  # N: Revealed type is \"b.B[Any]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testNewAnalyzerDuplicateTypeVarImportCycleWithAliases]\n# flags: --disable-error-code used-before-def\nimport a\n[file a.py]\nfrom typing import TypeVar, Any\nfrom b import BA, C\n\nT = TypeVar('T', bound=BAA[Any])\nT = TypeVar('T', bound=C)  # E: Cannot redefine \"T\" as a type variable \\\n                           # E: Invalid assignment target\nBAA = BA\n\n[file b.py]\nfrom typing import Generic, Any\nfrom a import T\n\nBA = B\nclass B(Generic[T]):\n    x: T\nclass C: ...\n\nx: B[int]  # E: Type argument \"int\" of \"B\" must be a subtype of \"B[Any]\"\ny: B[B[Any]]\nreveal_type(y.x)  # N: Revealed type is \"b.B[Any]\"\n\n[case testNewAnalyzerTypeVarBoundInCycle]\nimport factory, box\n\n[file factory.py]\nfrom typing import Generic, Type\n\nfrom box import BoxT\n\nclass Factory(Generic[BoxT]):\n    value: int\n\n    def create(self, boxClass: Type[BoxT]) -> BoxT:\n        reveal_type(boxClass.create(self))  # N: Revealed type is \"BoxT`1\"\n        return boxClass.create(self)\n\n[file box.py]\nfrom typing import TYPE_CHECKING, Type, TypeVar\n\nif TYPE_CHECKING:\n    from factory import Factory\n\nBoxT = TypeVar('BoxT', bound='Box')\n\nclass Box:\n    @classmethod\n    def create(cls: Type[BoxT], f: Factory) -> BoxT:\n        return cls(f.value)\n\n    def __init__(self, value: int) -> None: ...\n[builtins fixtures/classmethod.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testNewAnalyzerCastForward1]\nfrom typing import cast\n\nx = cast('C', None)\nclass A:\n    def foo(self) -> None:\n        self.x = cast('C', None)\n\nreveal_type(x)  # N: Revealed type is \"__main__.C\"\nreveal_type(A().x)  # N: Revealed type is \"__main__.C\"\n\nclass C(A): ...\n\n[case testNewAnalyzerCastForward2]\nfrom typing import cast\n\nx = cast('C', None)\n\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n\nC = int\n\n[case testNewAnalyzerCastForward3]\nfrom typing import cast, NamedTuple\n\nx = cast('C', None)\n\nreveal_type(x)  # N: Revealed type is \"tuple[builtins.int, fallback=__main__.C]\"\nreveal_type(x.x)  # N: Revealed type is \"builtins.int\"\n\nC = NamedTuple('C', [('x', int)])\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerApplicationForward1]\n# flags: --disable-error-code used-before-def\nfrom typing import Generic, TypeVar\n\nx = C[int]()\nreveal_type(x)  # N: Revealed type is \"__main__.C[builtins.int]\"\n\nT = TypeVar('T')\nclass C(Generic[T]): ...\n\n[case testNewAnalyzerApplicationForward2]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\nclass C(Generic[T]): ...\n\nx = C['A']()\nreveal_type(x)  # N: Revealed type is \"__main__.C[__main__.A]\"\n\nclass A: ...\n\n[case testNewAnalyzerApplicationForward3]\nfrom typing import Generic, TypeVar\n\nclass A: ...\nT = TypeVar('T')\nclass C(Generic[T]): ...\nx = C[A]()\nreveal_type(x)  # N: Revealed type is \"__main__.C[__main__.A]\"\n\n[case testNewAnalyzerApplicationForward4]\n# flags: --disable-error-code used-before-def\nfrom typing import Generic, TypeVar\n\nx = C[A]()  # E: Value of type variable \"T\" of \"C\" cannot be \"A\"\nreveal_type(x)  # N: Revealed type is \"__main__.C[__main__.A]\"\n\nT = TypeVar('T', bound='D')\nclass C(Generic[T]): ...\n\nclass A: ...\nclass D: ...\n\n[case testNewAnalyzerModuleGetattrSerialize_incremental]\nimport a\n[file a.py]\nimport p\n[file a.py.2]\nimport p\nreveal_type(p.y)\n[file p.pyi]\nfrom pp import x\ny = x\n[file pp.pyi]\ndef __getattr__(attr): ...\n[out2]\ntmp/a.py:2: note: Revealed type is \"Any\"\n\n[case testNewAnanlyzerTrickyImportPackage]\nfrom lib import config\nimport lib\n\nreveal_type(lib.config.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(config.x)  # N: Revealed type is \"builtins.int\"\n\n[file lib/__init__.py]\nfrom lib.config import config\n\n[file lib/config.py]\nclass Config:\n    x: int\n\nconfig = Config()\n[builtins fixtures/module.pyi]\n\n[case testNewAnanlyzerTrickyImportPackageAlt]\nimport lib.config\nimport lib.config as tmp\n\nreveal_type(lib.config.x)  # N: Revealed type is \"builtins.int\"\n# TODO: this actually doesn't match runtime behavior, variable wins.\ntmp.x  # E: Module has no attribute \"x\"\n\n[file lib/__init__.py]\nfrom lib.config import config\n\n[file lib/config.py]\nclass Config:\n    x: int\n\nconfig = Config()\n[builtins fixtures/module.pyi]\n\n[case testNewAnanlyzerTrickyImportPackage_incremental]\nimport a\n\n[file a.py]\nfrom lib import config\nimport lib\n\n[file a.py.2]\nfrom lib import config\nimport lib\n\nreveal_type(lib.config.x)\nreveal_type(config.x)\n\n[file lib/__init__.py]\nfrom lib.config import config\n\n[file lib/config.py]\nclass Config:\n    x: int\n\nconfig = Config()\n[builtins fixtures/module.pyi]\n[out2]\ntmp/a.py:4: note: Revealed type is \"builtins.int\"\ntmp/a.py:5: note: Revealed type is \"builtins.int\"\n\n[case testNewAnalyzerRedefineAsClass]\nfrom typing import Any\nfrom other import C  # type: ignore\n\ny = 'bad'\n\nclass C:  # E: Name \"C\" already defined (possibly by an import)\n    def meth(self, other: int) -> None:\n        y()  # E: \"str\" not callable\n\n[case testNewAnalyzerRedefineAsOverload]\nfrom typing import overload\n\ny = 'bad'\n\nif int():\n    def f(x: int) -> None:\n        pass\nelse:\n    @overload  # E: Name \"f\" already defined on line 6\n    def f(x: int) -> None: ...\n    @overload\n    def f(x: str) -> None: ...\n    def f(x) -> None:\n        y()  # E: \"str\" not callable\n\n[case testNewAnalyzerFirstAliasTargetWins]\nclass DesiredTarget:\n    attr: int\n\nif int():\n    Alias = DesiredTarget\nelse:\n    class DummyTarget:\n        pass\n    Alias = DummyTarget  # type: ignore\n\nx: Alias\nreveal_type(x.attr)  # N: Revealed type is \"builtins.int\"\n[case testNewAnalyzerFirstVarDefinitionWins]\nx = y  # E: Name \"y\" is used before definition\nx = 1\n\n# We want to check that the first definition creates the variable.\ndef x() -> None: ...  # E: Name \"x\" already defined on line 1\ny = 2\n\n[case testNewAnalyzerImportStarSpecialCase]\nimport unittest\n[file unittest/__init__.pyi]\nfrom unittest.suite import *\n\ndef load_tests() -> TestSuite: ...\n[file unittest/suite.pyi]\nfrom typing import Union # Iterable not imported\nimport unittest.case\n\n_TestType = Union[unittest.case.TestCase]\n\nclass BaseTestSuite(Iterable[_TestType]):\n    ...\n\nclass TestSuite(BaseTestSuite):\n    ...\n\n[file unittest/case.pyi]\nclass TestCase: ...\n\n[out]\ntmp/unittest/suite.pyi:6: error: Name \"Iterable\" is not defined\ntmp/unittest/suite.pyi:6: note: Did you forget to import it from \"typing\"? (Suggestion: \"from typing import Iterable\")\n\n[case testNewAnalyzerNewTypeSpecialCase]\nfrom typing import Final, Literal, NewType\n\nX = NewType('X', int)\n\nvar1: Final = 1\n\ndef force1(x: Literal[1]) -> None: pass\n\nforce1(reveal_type(var1))            # N: Revealed type is \"Literal[1]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerReportLoopInMRO]\nclass A(A): ... # E: Cannot resolve name \"A\" (possible cyclic definition)\n[out]\n\n[case testNewSemanticAnalyzerUnimportedSpecialCase]\n# flags: --ignore-missing-imports\nimport other\nimport p.u\n\n[file p/__init__.py]\n\n[file p/u.pyi]\nfrom . import c\nx: c.C\n\n[file other.py]\nfrom p.c import B\n\n[out]\n\n[case testNewSemanticAnalyzerQualifiedFunctionAsType]\nimport m\n\nx: m.C.a.b # E: Name \"m.C.a.b\" is not defined\n\n[file m.py]\ndef C(): pass\n\n[case testNewSemanticAnalyzerModulePrivateRefInMiddleOfQualified]\nimport m\n\nx: m.n.C # E: Name \"m.n.C\" is not defined\nreveal_type(x) # N: Revealed type is \"Any\"\n\n[file m.pyi]\nimport n\n\n[file n.pyi]\nclass C: pass\n\n[case testNewAnalyzerModuleGetAttr]\nimport m\nimport n\n\nx: m.n.C\ny: n.D\n[file m.py]\nimport n\n[file n.py]\ndef __getattr__(x): pass\n\n[case testNewAnalyzerReportLoopInMRO2]\ndef f() -> None:\n    class A(A): ...  # E: Cannot resolve name \"A\" (possible cyclic definition) \\\n                     # N: Recursive types are not allowed at function scope\n\n[case testNewAnalyzerUnsupportedBaseClassInsideFunction]\nclass C:\n    class E: pass\n\n    def f(self) -> None:\n        # TODO: Error message could be better\n        class D(self.E): # E: Name \"self.E\" is not defined\n            pass\n\n[case testNewAnalyzerShadowOuterDefinitionBasedOnOrderSinglePass]\n# Only one semantic analysis pass\nclass X: pass\nclass C:\n    X = X\n    reveal_type(X)  # N: Revealed type is \"def () -> __main__.X\"\nreveal_type(C.X)  # N: Revealed type is \"def () -> __main__.X\"\n\n[case testNewAnalyzerShadowOuterDefinitionBasedOnOrderTwoPasses]\nc: C  # Force second semantic analysis pass\nclass X: pass\nclass C:\n    X = X\n    reveal_type(X)  # N: Revealed type is \"def () -> __main__.X\"\n\nreveal_type(C.X)  # N: Revealed type is \"def () -> __main__.X\"\n\n[case testNewAnalyzerAnnotationConflictsWithAttributeSinglePass]\nclass C:\n    def x(self) -> int:\n        return 0\n\n    def __init__(self) -> None:\n        self.int = ''\n\n    def y(self) -> int:\n        return 0\n\n    z: str\n\n    def str(self) -> str:\n        return 0 # E: Incompatible return value type (got \"int\", expected \"str\")\n\n    zz: str # E: Function \"__main__.C.str\" is not valid as a type \\\n            # N: Perhaps you need \"Callable[...]\" or a callback protocol?\n\nreveal_type(C().x()) # N: Revealed type is \"builtins.int\"\nreveal_type(C().y()) # N: Revealed type is \"builtins.int\"\nreveal_type(C().z) # N: Revealed type is \"builtins.str\"\nreveal_type(C().str()) # N: Revealed type is \"builtins.str\"\n\n[case testNewAnalyzerAnnotationConflictsWithAttributeTwoPasses]\nc: C  # Force second semantic analysis pass\n\nclass C:\n    def x(self) -> int:\n        return 0\n\n    def __init__(self) -> None:\n        self.int = ''\n\n    def y(self) -> int:\n        return 0\n\n    z: str\n\n    def str(self) -> str:\n        return 0 # E: Incompatible return value type (got \"int\", expected \"str\")\n\n    zz: str # E: Function \"__main__.C.str\" is not valid as a type \\\n            # N: Perhaps you need \"Callable[...]\" or a callback protocol?\n\nreveal_type(C().x()) # N: Revealed type is \"builtins.int\"\nreveal_type(C().y()) # N: Revealed type is \"builtins.int\"\nreveal_type(C().z) # N: Revealed type is \"builtins.str\"\nreveal_type(C().str()) # N: Revealed type is \"builtins.str\"\n\n[case testNewAnalyzerNameConflictsAndMultiLineDefinition]\nc: C  # Force second semantic analysis pass\n\nclass X: pass\n\nclass C:\n    X = (\n        X)\n\n    def str(self\n            ) -> str:\n        return 0 # E: Incompatible return value type (got \"int\", expected \"str\")\n\nreveal_type(C.X) # E:  # N: Revealed type is \"def () -> __main__.X\"\nreveal_type(C().str()) # N: Revealed type is \"builtins.str\"\n\n[case testNewAnalyzerNameNotDefinedYetInClassBody]\nclass C:\n    X = Y  # E: Name \"Y\" is not defined\n    Y = 1\n\n    f = g  # E: Name \"g\" is not defined\n\n    def g(self) -> None: pass\n\nreveal_type(C.X)  # N: Revealed type is \"Any\"\n\n[case testNewAnalyzerImportedNameUsedInClassBody]\nimport m\n\n[file m.py]\nclass C:\n    from mm import f  # E: Unsupported class scoped import\n    @dec(f)\n    def m(self): pass\n\ndef dec(f): pass\n[file mm.py]\n# 1 padding to increase line number of 'f'\n# 2 padding\n# 3 padding\n# 4 padding\n# 5 padding\n# 6 padding\ndef f(): pass\n\n\n[case testNewAnalyzerImportedNameUsedInClassBody2]\nimport m\n\n[file m/__init__.py]\nclass C:\n    from m.m import f  # E: Unsupported class scoped import\n    @dec(f)\n    def m(self): pass\n\ndef dec(f): pass\n[file m/m.py]\n# 1 padding to increase line number of 'f'\n# 2 padding\n# 3 padding\n# 4 padding\n# 5 padding\n# 6 padding\ndef f(): pass\n\n[case testNewAnalyzerOverrideClassWithTypeAlias]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass C(Generic[T]):\n    pass\n\nC = C[int]  # E: Cannot assign to a type \\\n            # E: Incompatible types in assignment (expression has type \"type[C[int]]\", variable has type \"type[C[T]]\")\nx: C\nreveal_type(x) # N: Revealed type is \"__main__.C[Any]\"\n\n[case testNewAnalyzerClassVariableOrdering]\ndef foo(x: str) -> None: pass\n\nclass Something:\n    def run(self) -> None:\n        foo(self.IDS[0])  # E: Argument 1 to \"foo\" has incompatible type \"int\"; expected \"str\"\n\n    IDS = [87]\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerPlaceholderFromOuterScope]\nimport b\n[file a.py]\nimport b\nclass A(B): ...\nclass B: ...\n\n[file b.py]\nfrom a import A\n\nclass C:\n    A = A  # Initially rvalue will be a placeholder\n\nreveal_type(C.A)  # N: Revealed type is \"def () -> a.A\"\n\n[case testNewAnalyzerFinalLiteralInferredAsLiteralWithDeferral]\nfrom typing import Final, Literal\n\ndefer: Yes\n\nvar: Final = 42\ndef force(x: Literal[42]) -> None: pass\nforce(reveal_type(var))  # N: Revealed type is \"Literal[42]\"\n\nclass Yes: ...\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerImportCycleWithIgnoreMissingImports]\n# flags: --ignore-missing-imports\nimport p\nreveal_type(p.get)  # N: Revealed type is \"def () -> builtins.int\"\n\n[file p/__init__.pyi]\nfrom . import api\nget = api.get\n\n[file p/api.pyi]\nimport p\n\ndef get() -> int: ...\n\n[case testUseObsoleteNameForTypeVar3]\nimport typing\nt = typing.typevar('t') # E: Module has no attribute \"typevar\"\n[builtins fixtures/module.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testNewAnalyzerImportFromTopLevelFunction]\nimport a.b  # This works at runtime\nreveal_type(a.b)  # N\n[file a/__init__.py]\nfrom .b import B\nfrom . import b as c\ndef b() -> None: pass\nreveal_type(b)  # N\nreveal_type(c.B())  # N\nx: Forward\nclass Forward:\n    ...\n\n[file a/b.py]\nclass B: ...\n[builtins fixtures/module.pyi]\n\n[out]\ntmp/a/__init__.py:4: note: Revealed type is \"def ()\"\ntmp/a/__init__.py:5: note: Revealed type is \"a.b.B\"\nmain:2: note: Revealed type is \"def ()\"\n\n[case testNewAnalyzerImportFromTopLevelAlias]\nimport a.b  # This works at runtime\nreveal_type(a.b)  # N\n[file a/__init__.py]\nfrom .b import B\nfrom . import b as c\nb = int\ny: b\nreveal_type(y)  # N\nreveal_type(c.B)  # N\nx: Forward\nclass Forward:\n    ...\n\n[file a/b.py]\nclass B: ...\n[builtins fixtures/module.pyi]\n\n[out]\ntmp/a/__init__.py:5: note: Revealed type is \"builtins.int\"\ntmp/a/__init__.py:6: note: Revealed type is \"def () -> a.b.B\"\nmain:2: note: Revealed type is \"def () -> builtins.int\"\n\n[case testNewAnalyzerImportAmbiguousWithTopLevelFunction]\nimport a.b  # This works at runtime\nx: a.b.B  # E\nreveal_type(a.b)  # N\n[file a/__init__.py]\nimport a.b\nimport a.b as c\ndef b() -> None: pass\nreveal_type(b)  # N\nreveal_type(c.B())  # N\nx: Forward\nclass Forward:\n    ...\n\n[file a/b.py]\nclass B: ...\n[builtins fixtures/module.pyi]\n\n[out]\ntmp/a/__init__.py:4: note: Revealed type is \"def ()\"\ntmp/a/__init__.py:5: note: Revealed type is \"a.b.B\"\nmain:2: error: Name \"a.b.B\" is not defined\nmain:3: note: Revealed type is \"def ()\"\n\n[case testNewAnalyzerConfusingImportConflictingNames]\n# flags: --follow-imports=skip --ignore-missing-imports\n# cmd: mypy -m other a.b a\n[file a/__init__.py]\n[file a/b/__init__.py]\nimport other\nimport a.b.a\nimport a.b.c\n\n[file other.py]\nfrom a.b.a import foo\n[builtins fixtures/module.pyi]\n[out]\n\n[case testNewAnalyzerNamedTupleMethod]\nfrom typing import NamedTuple\n\ng: N\n\nclass N(NamedTuple):\n    def f(self) -> None:\n        b = (\n            a\n            for a in [1]\n        )\n        b\n[builtins fixtures/tuple.pyi]\n\n[case testWithMultipleTargetsDeferred]\na: A\n\nclass A:\n    def __enter__(self) -> int: pass\n    def __exit__(self, x, y, z): pass\n\nwith A() as x, A() as y:  # type: int, int\n    pass\n\n[case testNewAnalyzerLessErrorsNeedAnnotation]\nfrom typing import TypeVar, Optional\n\nT = TypeVar('T')\n\ndef f(x: Optional[T] = None) -> T: ...\n\nx = f()  # E: Need type annotation for \"x\"\ny = x\n\ndef g() -> None:\n    x = f()  # E: Need type annotation for \"x\"\n    y = x\n\n[case testNewAnalyzerLessErrorsNeedAnnotationList]\nx = []  # type: ignore\nreveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\n\ndef g() -> None:\n    x = []  # type: ignore\n    reveal_type(x)  # N: Revealed type is \"builtins.list[Any]\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerLessErrorsNeedAnnotationNested]\nfrom typing import TypeVar, Optional, Generic\n\nT = TypeVar('T')\nclass G(Generic[T]): ...\n\ndef f(x: Optional[T] = None) -> G[T]: ...\n\nx = f()  # E: Need type annotation for \"x\"\ny = x\nreveal_type(y)  # N: Revealed type is \"__main__.G[Any]\"\n\ndef g() -> None:\n    x = f()  # E: Need type annotation for \"x\"\n    y = x\n    reveal_type(y)  # N: Revealed type is \"__main__.G[Any]\"\n\n[case testNewAnalyzerRedefinedNonlocal]\n# flags: --disable-error-code=annotation-unchecked\nimport typing\n\ndef f():\n    bar = []  # type: typing.List[int]\n\n    def foo():\n        nonlocal bar\n        bar = []  # type: typing.List[int]\n\ndef g() -> None:\n    bar = []  # type: typing.List[int]\n\n    def foo() -> None:\n        nonlocal bar\n        bar = []  # type: typing.List[int] # E: Name \"bar\" already defined on line 12\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerMoreInvalidTypeVarArgumentsDeferred]\nfrom typing import TypeVar, Generic\n\ndefer: Yes\n\nS = TypeVar('S', covariant=True, contravariant=True)  # E: TypeVar cannot be both covariant and contravariant \\\n                                                      # E: \"int\" not callable\n\nclass Yes: ...\n[builtins fixtures/bool.pyi]\n\n[case testNewAnalyzerDisallowAnyGenericsMessages]\n# mypy: disallow-any-generics\nfrom a import B\nx: B\n\n[file a.py]\nfrom typing import TypeVar, List\n\nT = TypeVar('T')\n\nA = List[T]\nB = A\n\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerVarTypeVarNoCrash]\nfrom typing import Callable, TypeVar\n\nFooT = TypeVar('FooT', bound='Foo')\nclass Foo: ...\n\nf = lambda x: True  # type: Callable[[FooT], bool]\nreveal_type(f)  # N: Revealed type is \"def [FooT <: __main__.Foo] (FooT`-1) -> builtins.bool\"\n[builtins fixtures/bool.pyi]\n\n[case testNewAnalyzerVarTypeVarNoCrashImportCycle]\nimport a\n\n[file a.py]\nfrom b import B\nfrom typing import TypeVar\n\nFooT = TypeVar('FooT', bound='Foo')\nclass Foo: ...\n\n[file b.py]\nfrom a import FooT\nfrom typing import Callable\n\nf = lambda x: True  # type: Callable[[FooT], bool]\nreveal_type(f)  # N: Revealed type is \"def [FooT <: a.Foo] (FooT`-1) -> builtins.bool\"\n\nclass B: ...\n[builtins fixtures/bool.pyi]\n\n[case testNewAnalyzerFuncTypeVarNoCrashImportCycle]\nimport a\n\n[file a.py]\nfrom b import B\nfrom typing import TypeVar\n\nFooT = TypeVar('FooT', bound='Foo')\nclass Foo: ...\n\n[file b.py]\nfrom a import FooT\nfrom typing import Callable\n\ndef f(x: FooT) -> bool: ...\nreveal_type(f)  # N: Revealed type is \"def [FooT <: a.Foo] (x: FooT`-1) -> builtins.bool\"\n\nclass B: ...\n[builtins fixtures/bool.pyi]\n\n[case testNewAnalyzerNoCrashOnStarInference]\nfrom typing import Tuple\n\ndef f() -> None:\n    t: Tuple[str, Tuple[str, str, str]]\n    x, (y, *z) = t\n    reveal_type(z)  # N: Revealed type is \"builtins.list[builtins.str]\"\n[builtins fixtures/list.pyi]\n\n[case testNewAnalyzerIdentityAssignment1]\nfrom foo import *\n\ntry:\n    X = X\nexcept:\n    class X: # E: Name \"X\" already defined (possibly by an import)\n        pass\n\nreveal_type(X()) # N: Revealed type is \"foo.X\"\n\n[file foo.py]\nclass X: pass\n\n[case testNewAnalyzerIdentityAssignment2]\ntry:\n    int = int\n    reveal_type(int()) # N: Revealed type is \"builtins.int\"\nexcept:\n    class int: # E: Name \"int\" already defined (possibly by an import)\n        pass\n\nreveal_type(int()) # N: Revealed type is \"builtins.int\"\n\n[case testNewAnalyzerIdentityAssignment3]\nforwardref: C\n\ntry:\n    int = int\n    reveal_type(int()) # N: Revealed type is \"builtins.int\"\nexcept:\n    class int: # E: Name \"int\" already defined (possibly by an import)\n        pass\n\nreveal_type(int()) # N: Revealed type is \"builtins.int\"\n\nclass C: pass\n\n[case testNewAnalyzerIdentityAssignment4]\ntry:\n    C = C\n    C\nexcept:\n    class C:\n        pass\n\nreveal_type(C()) # N: Revealed type is \"__main__.C\"\n\n[case testNewAnalyzerIdentityAssignment5]\nforwardref: D\n\ntry:\n    C = C\n    C\nexcept:\n    class C:\n        pass\n\nclass D: pass\n\nreveal_type(C()) # N: Revealed type is \"__main__.C\"\n\n[case testNewAnalyzerIdentityAssignment6]\nx: C\nclass C:\n    pass\nC = C\n\nreveal_type(C()) # N: Revealed type is \"__main__.C\"\nreveal_type(x) # N: Revealed type is \"__main__.C\"\n\n[case testNewAnalyzerIdentityAssignment7]\nC = C # E: Name \"C\" is not defined\n\nreveal_type(C) # E: Name \"C\" is not defined \\\n               # N: Revealed type is \"Any\"\n\n[case testNewAnalyzerIdentityAssignment8]\nfrom typing import Final\nx: Final = 0\nx = x # E: Cannot assign to final name \"x\"\n\n[case testNewAnalyzerIdentityAssignmentClassImplicit]\nclass C: ...\nclass A:\n    C = C[str]  # E: \"C\" expects no type arguments, but 1 given\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerIdentityAssignmentClassExplicit]\nfrom typing_extensions import TypeAlias\n\nclass A:\n    C: TypeAlias = C\nclass C: ...\nc: A.C\nreveal_type(c)  # N: Revealed type is \"__main__.C\"\n[builtins fixtures/tuple.pyi]\n\n[case testNewAnalyzerClassPropertiesInAllScopes]\nfrom abc import abstractmethod, ABCMeta\n\nclass TopLevel(metaclass=ABCMeta):\n    @abstractmethod\n    def f(self) -> None: pass\n\nTopLevel()  # E: Cannot instantiate abstract class \"TopLevel\" with abstract attribute \"f\"\n\ndef func() -> None:\n    class Function(metaclass=ABCMeta):\n        @abstractmethod\n        def f(self) -> None: pass\n\n    Function()  # E: Cannot instantiate abstract class \"Function\" with abstract attribute \"f\"\n\nclass C:\n    def meth(self) -> None:\n        class Method(metaclass=ABCMeta):\n            @abstractmethod\n            def f(self) -> None: pass\n\n        Method()  # E: Cannot instantiate abstract class \"Method\" with abstract attribute \"f\"\n\n[case testModulesAndFuncsTargetsInCycle]\nimport a\n[file a.py]\nimport b\ndefer: Yes\ndef func() -> int: ...\nclass Yes: ...\n[file b.py]\nimport a\n\ndef func() -> int: ...\n[targets b, a, a, b.func, a.func, __main__]\n\n[case testNewAnalyzerForwardReferenceInFunction]\ndef f(x: 'A') -> 'A':\n    return A()\n\nclass A:\n    pass\n[targets __main__, __main__.f]\n\n[case testNewAnalyzerSimpleImportStarNoDeferral]\nfrom m import *\n\nx: A\nf()\n\n[file m.py]\nclass A: pass\ndef f() -> None: pass\n\n[targets m, m.f, __main__]\n\n[case testNewAnalyzerNoCrashOnCustomProperty]\n# flags: --ignore-missing-imports\nfrom unimported import custom\n\nclass User:\n    first_name: str\n\n    @custom\n    def name(self) -> str:\n        return self.first_name\n\n    @name.setter  # type: ignore\n    def name(self, value: str) -> None:\n        self.first_name = value\n\n    def __init__(self, name: str) -> None:\n        self.name = name  # E: Cannot assign to a method\n\n[case testNewAnalyzerMemberNameMatchesTypedDict]\nfrom typing import TypedDict, Union, Any\n\nclass T(TypedDict):\n    b: b.T\n\nclass b:\n    T: Union[Any]\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-typeddict.pyi]\n\n[case testNewAnalyzerMemberNameMatchesNamedTuple]\nfrom typing import Union, Any, NamedTuple\n\nclass T(NamedTuple):\n    b: b.T\n\nclass b:\n    T = Union[Any]\n\n[builtins fixtures/tuple.pyi]\n\n[case testSelfReferentialSubscriptExpression]\nx = x[1]  # E: Cannot resolve name \"x\" (possible cyclic definition)\ny = 1[y]  # E: Value of type \"int\" is not indexable \\\n          # E: Cannot determine type of \"y\"\n\n[case testForwardBaseDeferAttr]\nfrom typing import Optional, Callable, TypeVar\n\nclass C(B):\n    def a(self) -> None:\n        reveal_type(self._foo)  # N: Revealed type is \"builtins.int | None\"\n        self._foo = defer()\n\nclass B:\n    def __init__(self) -> None:\n        self._foo: Optional[int] = None\n\nT = TypeVar(\"T\")\ndef deco(fn: Callable[[], T]) -> Callable[[], T]: ...\n\n@deco\ndef defer() -> int: ...\n"
  },
  {
    "path": "test-data/unit/check-optional.test",
    "content": "-- Tests for strict Optional behavior\n\n[case testImplicitNoneType]\nx = None\nx()  # E: \"None\" not callable\n\n[case testImplicitNoneTypeInNestedFunction]\ndef f() -> None:\n    def g() -> None:\n        x = None\n        x()  # E: \"None\" not callable\n\n[case testExplicitNoneType]\nx = None  # type: None\nx()  # E: \"None\" not callable\n\n[case testNoneMemberOfOptional]\nfrom typing import Optional\nx = None  # type: Optional[int]\n\n[case testTypeMemberOfOptional]\nfrom typing import Optional\nx = 0  # type: Optional[int]\n\n[case testNoneNotMemberOfType]\nx = None  # type: int\n[out]\nmain:1: error: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\n[case testTypeNotMemberOfNone]\nx = 0  # type: None\n[out]\nmain:1: error: Incompatible types in assignment (expression has type \"int\", variable has type \"None\")\n\n[case testOptionalNotMemberOfType]\nfrom typing import Optional\ndef f(a: int) -> None: pass\nx = None  # type:  Optional[int]\nf(x)  # E: Argument 1 to \"f\" has incompatible type \"int | None\"; expected \"int\"\n\n[case testIsinstanceCases]\nfrom typing import Optional\nx = None  # type:  Optional[int]\nif isinstance(x, int):\n  reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n  reveal_type(x)  # N: Revealed type is \"None\"\n[builtins fixtures/isinstance.pyi]\n\n[case testIfCases]\nfrom typing import Optional\nx = None  # type:  Optional[int]\nif x:\n  reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n  reveal_type(x)  # N: Revealed type is \"Literal[0] | None\"\n[builtins fixtures/bool.pyi]\n\n[case testIfNotCases]\nfrom typing import Optional\nx = None  # type:  Optional[int]\nif not x:\n  reveal_type(x)  # N: Revealed type is \"Literal[0] | None\"\nelse:\n  reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/bool.pyi]\n\n[case testIsNotNoneCases]\nfrom typing import Optional\nx = None  # type:  Optional[int]\nif x is not None:\n  reveal_type(x)  # N: Revealed type is \"builtins.int\"\nelse:\n  reveal_type(x)  # N: Revealed type is \"None\"\n[builtins fixtures/bool.pyi]\n\n[case testIsNoneCases]\nfrom typing import Optional\nx = None  # type:  Optional[int]\nif x is None:\n  reveal_type(x)  # N: Revealed type is \"None\"\nelse:\n  reveal_type(x)  # N: Revealed type is \"builtins.int\"\nreveal_type(x)  # N: Revealed type is \"builtins.int | None\"\n[builtins fixtures/bool.pyi]\n\n[case testAnyCanBeNone]\nfrom typing import Optional, Any\nx = None  # type:  Any\nif x is None:\n  reveal_type(x)  # N: Revealed type is \"None\"\nelse:\n  reveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/bool.pyi]\n\n[case testOrCases]\nfrom typing import Optional\nx = None  # type: Optional[str]\ny1 = x or 'a'\nreveal_type(y1)  # N: Revealed type is \"builtins.str\"\ny2 = x or 1\nreveal_type(y2)  # N: Revealed type is \"builtins.str | builtins.int\"\nz1 = 'a' or x\nreveal_type(z1)  # N: Revealed type is \"builtins.str | None\"\nz2 = int() or x\nreveal_type(z2)  # N: Revealed type is \"builtins.int | builtins.str | None\"\n\n[case testAndCases]\nfrom typing import Optional\nx = None  # type: Optional[str]\ny1 = x and 'b'\nreveal_type(y1)  # N: Revealed type is \"Literal[''] | None | builtins.str\"\ny2 = x and 1  # x could be '', so...\nreveal_type(y2)  # N: Revealed type is \"Literal[''] | None | builtins.int\"\nz1 = 'b' and x\nreveal_type(z1)  # N: Revealed type is \"builtins.str | None\"\nz2 = int() and x\nreveal_type(z2)  # N: Revealed type is \"Literal[0] | builtins.str | None\"\n\n[case testLambdaReturningNone]\nf = lambda: None\nx = f()\nreveal_type(x)  # N: Revealed type is \"None\"\n\n[case testNoneArgumentType]\ndef f(x: None) -> None: pass\nf(None)\n\n[case testInferOptionalFromDefaultNone]\n# flags: --implicit-optional\ndef f(x: int = None) -> None:\n  x + 1  # E: Unsupported left operand type for + (\"None\") \\\n         # N: Left operand is of type \"int | None\"\nf(None)\n[out]\n\n[case testNoInferOptionalFromDefaultNone]\n# flags: --no-implicit-optional\ndef f(x: int = None) -> None:  # E: Incompatible default for parameter \"x\" (default has type \"None\", parameter has type \"int\") \\\n                               # N: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True \\\n                               # N: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase\n  pass\n[out]\n\n[case testInferOptionalFromDefaultNoneComment]\n# flags: --implicit-optional\ndef f(x=None):\n  # type: (int) -> None\n  x + 1  # E: Unsupported left operand type for + (\"None\") \\\n         # N: Left operand is of type \"int | None\"\nf(None)\n[out]\n\n[case testNoInferOptionalFromDefaultNoneComment]\n# flags: --no-implicit-optional\ndef f(x=None):  # E: Incompatible default for parameter \"x\" (default has type \"None\", parameter has type \"int\") \\\n                # N: PEP 484 prohibits implicit Optional. Accordingly, mypy has changed its default to no_implicit_optional=True \\\n                # N: Use https://github.com/hauntsaninja/no_implicit_optional to automatically upgrade your codebase\n  # type: (int) -> None\n  pass\n[out]\n\n[case testInferOptionalType]\nx = None\nif bool():\n  # scope limit assignment\n  x = 1\n  # in scope of the assignment, x is an int\n  reveal_type(x)  # N: Revealed type is \"builtins.int\"\n# out of scope of the assignment, it's an Optional[int]\nreveal_type(x)  # N: Revealed type is \"builtins.int | None\"\n[builtins fixtures/bool.pyi]\n\n[case testInferOptionalTypeLocallyBound]\nx = None\nx = 1\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\n\n[case testInferOptionalAnyType]\nfrom typing import Any\nx = None\na = None  # type: Any\nif bool():\n  x = a\n  reveal_type(x)  # N: Revealed type is \"Any\"\nreveal_type(x)  # N: Revealed type is \"Any | None\"\n[builtins fixtures/bool.pyi]\n\n[case testInferOptionalTypeFromOptional]\nfrom typing import Optional\ny = None  # type: Optional[int]\nx = None\nx = y\nreveal_type(x)  # N: Revealed type is \"builtins.int | None\"\n\n[case testInferOptionalListType]\nx = [None]\nx.append(1)  # E: Argument 1 to \"append\" of \"list\" has incompatible type \"int\"; expected \"None\"\n[builtins fixtures/list.pyi]\n\n[case testInferNonOptionalListType]\nx = []\nx.append(1)\nx()  # E: \"list[int]\" not callable\n[builtins fixtures/list.pyi]\n\n[case testInferOptionalDictKeyValueTypes]\nx = {None: None}\nx[\"bar\"] = 1\n[builtins fixtures/dict.pyi]\n[out]\nmain:2: error: Invalid index type \"str\" for \"dict[None, None]\"; expected type \"None\"\nmain:2: error: Incompatible types in assignment (expression has type \"int\", target has type \"None\")\n\n[case testInferNonOptionalDictType]\nx = {}\nx[\"bar\"] = 1\nx()  # E: \"dict[str, int]\" not callable\n[builtins fixtures/dict.pyi]\n\n[case testNoneClassVariable]\nfrom typing import Optional\nclass C:\n    x: int\n    def __init__(self) -> None:\n        self.x = 0\n\n[case testNoneClassVariableInInit]\nfrom typing import Optional\nclass C:\n    x: int\n    def __init__(self) -> None:\n        self.x = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n[out]\n\n[case testMultipleAssignmentNoneClassVariableInInit]\nfrom typing import Optional\nclass C:\n    x, y = None, None  # type: int, str\n    def __init__(self) -> None:\n        self.x = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n        self.y = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"str\")\n\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadWithNone]\nfrom foo import *\n[file foo.pyi]\nfrom typing import overload\n@overload\ndef f(x: None) -> str: pass\n@overload\ndef f(x: int) -> int: pass\nreveal_type(f(None))  # N: Revealed type is \"builtins.str\"\nreveal_type(f(0))  # N: Revealed type is \"builtins.int\"\n\n[case testOptionalTypeOrTypePlain]\nfrom typing import Optional\ndef f(a: Optional[int]) -> int:\n    return a or 0\n[out]\n\n[case testOptionalTypeOrTypeTypeVar]\nfrom typing import Optional, TypeVar\nT = TypeVar('T')\ndef f(a: Optional[T], b: T) -> T:\n    return a or b\n[out]\n\n[case testOptionalTypeOrTypeBothOptional]\nfrom typing import Optional\ndef f(a: Optional[int], b: Optional[int]) -> None:\n    reveal_type(a or b)\ndef g(a: int, b: Optional[int]) -> None:\n    reveal_type(a or b)\n[out]\nmain:3: note: Revealed type is \"builtins.int | None\"\nmain:5: note: Revealed type is \"builtins.int | None\"\n\n[case testOptionalTypeOrTypeComplexUnion]\nfrom typing import Union\ndef f(a: Union[int, str, None]) -> None:\n    reveal_type(a or 'default')\n[out]\nmain:3: note: Revealed type is \"builtins.int | builtins.str\"\n\n[case testOptionalTypeOrTypeNoTriggerPlain]\nfrom typing import Optional\ndef f(a: Optional[int], b: int) -> int:\n    return b or a\n[out]\nmain:3: error: Incompatible return value type (got \"int | None\", expected \"int\")\n\n[case testOptionalTypeOrTypeNoTriggerTypeVar]\nfrom typing import Optional, TypeVar\nT = TypeVar('T')\ndef f(a: Optional[T], b: T) -> T:\n    return b or a\n[out]\nmain:4: error: Incompatible return value type (got \"T | None\", expected \"T\")\n\n[case testNoneOrStringIsString]\ndef f() -> str:\n    a = None\n    b = ''\n    return a or b\n[out]\n\n[case testNoneOrTypeVarIsTypeVar]\nfrom typing import TypeVar\nT = TypeVar('T')\ndef f(b: T) -> T:\n    a = None\n    return a or b\n[out]\n\n[case testYieldNothingInFunctionReturningGenerator]\nfrom typing import Generator\ndef f() -> Generator[None, None, None]:\n    yield\n[out]\n\n[case testNoneAndStringIsNone]\na: None = None\nb = \"foo\"\nreveal_type(a and b)  # N: Revealed type is \"None\"\n\nc = None\nreveal_type(c and b)  # N: Revealed type is \"None\"\n\n[case testNoneMatchesObjectInOverload]\nimport a\na.f(None)\n\n[file a.pyi]\nfrom typing import overload\n@overload\ndef f() -> None: ...\n@overload\ndef f(o: object) -> None: ...\n\n[case testGenericSubclassReturningNone]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass Base(Generic[T]):\n  def f(self) -> T:\n    pass\n\nclass SubNone(Base[None]):\n  def f(self) -> None:\n    pass\n\nclass SubInt(Base[int]):\n  def f(self) -> int:\n    return 1\n\n[case testUseOfNoneReturningFunction]\nfrom typing import Optional\ndef f() -> None:\n    pass\n\ndef g(x: Optional[int]) -> int:\n  pass\n\nx = f()  # E: \"f\" does not return a value (it only ever returns None)\nf() + 1  # E: \"f\" does not return a value (it only ever returns None) \\\n         # E: Unsupported left operand type for + (\"None\")\ng(f())  # E: \"f\" does not return a value (it only ever returns None)\n\n[case testEmptyReturn]\ndef f() -> None:\n    return\n\n[case testReturnNone]\ndef f() -> None:\n    return None\n\n[case testNoneCallable]\nfrom typing import Callable\ndef f() -> None: pass\nx = f  # type: Callable[[], None]\n\n[case testOptionalCallable]\nfrom typing import Callable, Optional\nT = Optional[Callable[..., None]]\n\n[case testAnyTypeInPartialTypeList]\n# flags: --check-untyped-defs\ndef f(): ...\n\ndef lookup_field(name, obj):\n    try:\n        pass\n    except:\n        attr = f()\n    else:\n        attr = None\n\n[case testTernaryWithNone]\nreveal_type(None if bool() else 0)  # N: Revealed type is \"None | Literal[0]?\"\n[builtins fixtures/bool.pyi]\n\n[case testListWithNone]\nreveal_type([0, None, 0])    # N: Revealed type is \"builtins.list[builtins.int | None]\"\n[builtins fixtures/list.pyi]\n\n[case testNoneContextInference]\nfrom typing import Dict, List\ndef f() -> List[None]:\n    return []\ndef g() -> Dict[None, None]:\n    return {}\n[builtins fixtures/dict.pyi]\n\n[case testRaiseFromNone]\nraise BaseException from None\n[builtins fixtures/exception.pyi]\n\n[case testOptionalNonPartialTypeWithNone]\nfrom typing import Generator\ndef f() -> Generator[str, None, None]: pass\nx = f()\nreveal_type(x)  # N: Revealed type is \"typing.Generator[builtins.str, None, None]\"\nl = [f()]\nreveal_type(l)  # N: Revealed type is \"builtins.list[typing.Generator[builtins.str, None, None]]\"\n[builtins fixtures/list.pyi]\n\n[case testNoneListTernary]\n# https://github.com/python/mypy/issues/19534\nx = [None] if \"\" else [1]\nreveal_type(x)  # N: Revealed type is \"builtins.list[None] | builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testListIncompatibleErrorMessage]\nfrom typing import List, Callable\n\ndef foo(l: List[Callable[[], str]]) -> None: pass\ndef f() -> int:\n    return 42\n\nfoo([f])  # E: List item 0 has incompatible type \"Callable[[], int]\"; expected \"Callable[[], str]\"\n[builtins fixtures/list.pyi]\n\n[case testInferEqualsNotOptional]\nfrom typing import Optional\n\ndef main(x: Optional[str]):\n    if x == '<string>':\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | None\"\n    if x is '<string>':\n        reveal_type(x)  # N: Revealed type is \"Literal['<string>']\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | None\"\n[builtins fixtures/ops.pyi]\n\n[case testInferEqualsNotOptionalWithUnion]\nfrom typing import Union\ndef main(x: Union[str, int, None]):\n    if x == '<string>':\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.int | None\"\n    if x is '<string>':\n        reveal_type(x)  # N: Revealed type is \"Literal['<string>']\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.int | None\"\n[builtins fixtures/ops.pyi]\n\n[case testInferEqualsNotOptionalWithOverlap]\nfrom typing import Union\n\ndef make_random_object() -> object:\n    return None\n\ndef main(x: Union[str, int, None]):\n    if x == make_random_object():\n        reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.int | None\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.int | None\"\n    if x is make_random_object():\n        reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.int | None\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.int | None\"\n[builtins fixtures/ops.pyi]\n\n[case testInferEqualsStillOptionalWithNoOverlap]\n# flags: --warn-unreachable\nfrom typing import Optional\n\ndef main(x: Optional[str]):\n    if x == 0:\n        reveal_type(x)  # E: Statement is unreachable\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | None\"\n    if x is 0:\n        reveal_type(x)  # E: Statement is unreachable\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.str | None\"\n[builtins fixtures/ops.pyi]\n\n[case testInferEqualsStillOptionalWithBothOptional]\nfrom typing import Union\nx = ''  # type: Union[str, int, None]\ny = ''  # type: Union[str, None]\nif x == y:\n    reveal_type(x)  # N: Revealed type is \"builtins.str | None\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.int | None\"\nif x is y:\n    reveal_type(x)  # N: Revealed type is \"builtins.str | None\"\nelse:\n    reveal_type(x)  # N: Revealed type is \"builtins.str | builtins.int | None\"\n[builtins fixtures/ops.pyi]\n\n[case testInferEqualsNotOptionalWithMultipleArgs]\nfrom typing import Optional\n\ndef main(x: Optional[int], y: Optional[int]):\n    if x == y == 1:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n        reveal_type(y)  # N: Revealed type is \"builtins.int\"\n    else:\n        reveal_type(x)  # N: Revealed type is \"builtins.int | None\"\n        reveal_type(y)  # N: Revealed type is \"builtins.int | None\"\n\nclass A: pass\n\ndef returns_random_object() -> object:\n    return None\n\ndef main2(a: Optional[A], b: Optional[A]):\n    if a == b == returns_random_object():\n        reveal_type(a)  # N: Revealed type is \"__main__.A | None\"\n        reveal_type(b)  # N: Revealed type is \"__main__.A | None\"\n    else:\n        reveal_type(a)  # N: Revealed type is \"__main__.A | None\"\n        reveal_type(b)  # N: Revealed type is \"__main__.A | None\"\n[builtins fixtures/ops.pyi]\n\n[case testInferInWithErasedTypes]\nfrom typing import TypeVar, Callable\n\nT = TypeVar('T')\ndef foo(f: Callable[[T], bool], it: T) -> None: ...\n\nfoo(lambda x: x in [1, 2] and bool(), 3)\n[builtins fixtures/list.pyi]\n\n[case testWarnNoReturnWorksWithStrictOptional]\n# flags: --warn-no-return\ndef f() -> None:\n  1 + 1  # no error\n\ndef g() -> int:\n  1 + 1  #\n[out]\nmain:5: error: Missing return statement\n\n[case testGenericTypeAliasesOptional]\nfrom typing import TypeVar, Generic, Optional\nT = TypeVar('T')\nclass Node(Generic[T]):\n    def __init__(self, x: T) -> None:\n        self.x = x\n\nONode = Optional[Node[T]]\ndef f(x: T) -> ONode[T]:\n    if 1 > 0:\n        return Node(x)\n    else:\n        return None\n\nx = None # type: ONode[int]\nif int():\n    x = f(1)\nif int():\n    x = f('x') # E: Argument 1 to \"f\" has incompatible type \"str\"; expected \"int\"\n\nx.x = 1 # E: Item \"None\" of \"Node[int] | None\" has no attribute \"x\"\nif x is not None:\n    x.x = 1 # OK here\n\n[builtins fixtures/ops.pyi]\n\n[case testOptionalTypeNarrowedInBooleanStatement]\nfrom typing import Optional\n\nx: Optional[int] = None\nx is not None and x + 42\nx is not None and x + '42'  # E: Unsupported operand types for + (\"int\" and \"str\")\n[builtins fixtures/isinstance.pyi]\n\n[case testInvalidBooleanBranchIgnored]\nfrom typing import Optional\n\nx: None = None\nx is not None and x + 42\n[builtins fixtures/isinstance.pyi]\n\n[case testOptionalLambdaInference]\nfrom typing import Optional, Callable\nf = None # type: Optional[Callable[[int], None]]\nf = lambda x: None\nf(0)\n[builtins fixtures/function.pyi]\n\n[case testDontSimplifyNoneUnionsWithStrictOptional]\nfrom typing import Any, TypeVar, Union\nA = None  # type: Any\nclass C(A): pass\nT = TypeVar('T')\nS = TypeVar('S')\ndef u(x: T, y: S) -> Union[S, T]: pass\na = None # type: Any\n\n# Test both orders\nreveal_type(u(C(), None))  # N: Revealed type is \"None | __main__.C\"\nreveal_type(u(None, C()))  # N: Revealed type is \"__main__.C | None\"\n\nreveal_type(u(a, None))  # N: Revealed type is \"None | Any\"\nreveal_type(u(None, a))  # N: Revealed type is \"Any | None\"\n\nreveal_type(u(1, None))  # N: Revealed type is \"None | builtins.int\"\nreveal_type(u(None, 1))  # N: Revealed type is \"builtins.int | None\"\n\n[case testOptionalAndAnyBaseClass]\nfrom typing import Any, Optional\nA = None  # type: Any\nclass C(A):\n    pass\nx = None  # type: Optional[C]\nx.foo()  # E: Item \"None\" of \"C | None\" has no attribute \"foo\"\n\n[case testIsinstanceAndOptionalAndAnyBase]\nfrom typing import Any, Optional\n\nB = None  # type: Any\nclass A(B): pass\n\ndef f(a: Optional[A]):\n    reveal_type(a) # N: Revealed type is \"__main__.A | None\"\n    if a is not None:\n        reveal_type(a) # N: Revealed type is \"__main__.A\"\n    else:\n        reveal_type(a) # N: Revealed type is \"None\"\n    reveal_type(a) # N: Revealed type is \"__main__.A | None\"\n[builtins fixtures/isinstance.pyi]\n\n[case testFlattenOptionalUnion]\nfrom typing import Optional, Union\n\nx: Optional[Union[int, str]]\nreveal_type(x) # N: Revealed type is \"builtins.int | builtins.str | None\"\ny: Optional[Union[int, None]]\nreveal_type(y) # N: Revealed type is \"builtins.int | None\"\n\n[case testOverloadWithNoneAndOptional]\nfrom typing import overload, Optional\n\n@overload\ndef f(x: int) -> str: ...\n@overload\ndef f(x: Optional[int]) -> Optional[str]: ...\ndef f(x): return x\n\nreveal_type(f(1)) # N: Revealed type is \"builtins.str\"\nreveal_type(f(None)) # N: Revealed type is \"builtins.str | None\"\nx: Optional[int]\nreveal_type(f(x)) # N: Revealed type is \"builtins.str | None\"\n\n[case testUnionTruthinessTracking]\nfrom typing import Optional, Any\ndef test_or_shortcut(value: Optional[Any]) -> None:\n    if not value:\n        pass\n    if not value or value.get('foo') == 'hello':\n        pass\n[builtins fixtures/bool.pyi]\n\n[case testNarrowingFromObjectToOptional]\nfrom typing import Optional\nx: object\ny: Optional[int]\nx = y\nreveal_type(x) # N: Revealed type is \"builtins.int | None\"\n[out]\n\n[case testNarrowOptionalOutsideLambda]\nfrom typing import Optional\n\nclass A:\n    a: int\n\ndef f(x: Optional[A]) -> None:\n    assert x\n    lambda: x.a\n[builtins fixtures/isinstancelist.pyi]\n\n[case testNarrowOptionalOutsideLambdaWithDeferred]\nfrom typing import Optional\n\nclass A:\n    a: int\n\n    def f(self, x: Optional['A']) -> None:\n        assert x\n        lambda: (self.y, x.a) # E: Cannot determine type of \"y\"\n        self.y = int()\n[builtins fixtures/isinstancelist.pyi]\n\n[case testDeferredAndOptionalInferenceSpecialCase]\ndef f() -> str:\n    y\n    x = None\n    if int():\n        x = ''\n    if x is None:\n        x = ''\n        g(x)\n    return x\n\ndef g(x: str) -> None: pass\n\ny = int()\n[builtins fixtures/bool.pyi]\n\n[case testOptionalAssignAny1]\nfrom typing import Optional\ndef f():\n    return 0\n\ndef g(x: Optional[int]) -> int:\n    if x is None:\n        reveal_type(x)  # N: Revealed type is \"None\"\n        # As a special case for Unions containing None, during\n        x = f()\n        reveal_type(x)  # N: Revealed type is \"builtins.int | Any\"\n    reveal_type(x)  # N: Revealed type is \"builtins.int | Any\"\n    return x\n[builtins fixtures/bool.pyi]\n\n[case testOptionalAssignAny2]\nfrom typing import Optional\ndef f():\n    return 0\n\ndef g(x: Optional[int]) -> int:\n    if x is None:\n        reveal_type(x)  # N: Revealed type is \"None\"\n        x = 1\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n        # Same as above, even after we've assigned to x\n        x = f()\n        reveal_type(x)  # N: Revealed type is \"builtins.int | Any\"\n    reveal_type(x)  # N: Revealed type is \"builtins.int | Any\"\n    return x\n[builtins fixtures/bool.pyi]\n\n[case testOptionalAssignAny3]\nfrom typing import Optional\ndef f():\n    return 0\n\ndef g(x: Optional[int]) -> int:\n    if x is not None:\n        return x\n    reveal_type(x)  # N: Revealed type is \"None\"\n    x = f()\n    reveal_type(x)  # N: Revealed type is \"builtins.int | Any\"\n    return x\n[builtins fixtures/bool.pyi]\n\n[case testStrictOptionalCovarianceCrossModule]\n# flags: --config-file tmp/mypy.ini\nfrom a import asdf\nx = [\"lol\"]\nasdf(x)\n\n[file a.py]\nfrom typing import List, Optional\n\ndef asdf(x: List[Optional[str]]) -> None:\n    pass\n\nx = [\"lol\"]\nasdf(x)\n\n[file mypy.ini]\n\\[mypy]\n\\[mypy-a]\nstrict_optional = False\n[out]\nmain:4: error: Argument 1 to \"asdf\" has incompatible type \"list[str]\"; expected \"list[str | None]\"\nmain:4: note: \"list\" is invariant -- see https://mypy.readthedocs.io/en/stable/common_issues.html#variance\nmain:4: note: Consider using \"Sequence\" instead, which is covariant\n[builtins fixtures/list.pyi]\n\n[case testOptionalBackwards1]\nfrom typing import Any, Optional\n\ndef f1(b: bool) -> Optional[int]:\n    if b:\n        z = 10\n        reveal_type(z)  # N: Revealed type is \"builtins.int\"\n    else:\n        z = None\n        reveal_type(z)  # N: Revealed type is \"None\"\n    reveal_type(z)  # N: Revealed type is \"builtins.int | None\"\n    return z\n\ndef f2(b: bool) -> int:\n    if b:\n        z = 10\n    else:\n        z = None\n    return z  # E: Incompatible return value type (got \"int | None\", expected \"int\")\n\ndef f3(b: bool) -> int:\n    # XXX: This one is a little questionable! Maybe we *do* want to allow this?\n    z = 10\n    if b:\n        z = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n    return z\n\ndef f4() -> Optional[int]:\n    z = 10\n    z = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\n    return z\n\ndef f5() -> None:\n    z = 10\n\n    def f() -> None:\n        nonlocal z\n        z = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\ndef f6(b: bool) -> None:\n    if b:\n        z = 10\n    else:\n        z = 11\n\n    def f() -> None:\n        nonlocal z\n        z = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\ndef f7(b: bool) -> None:\n    if b:\n        z = 10\n    else:\n        z = 11\n\n    z = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\ndef f8(b: bool, c: bool) -> Optional[int]:\n    if b:\n        if c:\n            z = 10\n        else:\n            z = 11\n    else:\n        z = None\n    return z\n\ndef f9(b: bool) -> None:\n    if b:\n        z: int = 10\n    else:\n        z = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\ndef f10(b: bool) -> None:\n    z: int\n    if b:\n        z = 10\n    else:\n        z = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\ndef f11(b: bool, c: bool) -> None:\n    if b:\n        z = 10\n    elif c:\n        z = 30\n    else:\n        z = None\n\ndef f12(b: bool, a: Any) -> None:\n    if b:\n        z = a\n    else:\n        z = None\n    reveal_type(z)  # N: Revealed type is \"Any\"\n\ndef f13(b: bool, a: Any) -> None:\n    if b:\n        try:\n            z = f2(True)\n        except Exception:\n            raise RuntimeError\n    else:\n        z = None\n\ndef f14(b: bool, a: Any) -> None:\n    if b:\n        with a:\n            z = 10\n    else:\n        z = None\n\ndef f15() -> None:\n    try:\n        z = f2(True)\n    except Exception:\n        z = None\n    reveal_type(z)  # N: Revealed type is \"builtins.int | None\"\n\ndef f16(z: Any) -> None:\n    for x in z:\n        if x == 0:\n            y = 50\n            break\n    else:\n        y = None\n    reveal_type(y)  # N: Revealed type is \"builtins.int | None\"\n\ndef f17(b: bool, c: bool, d: bool) -> None:\n    if b:\n        z = 2\n    elif c:\n        z = None\n    elif d:\n        z = 3\n    reveal_type(z)  # N: Revealed type is \"builtins.int | None\"\n\ndef f18(b: bool, c: bool, d: bool) -> None:\n    if b:\n        z = 4\n    else:\n        if c:\n            z = 5\n        else:\n            z = None\n    reveal_type(z)  # N: Revealed type is \"builtins.int | None\"\n\ndef f19(b: bool, c: bool, d: bool) -> None:\n    if b:\n        z = 5\n    else:\n        z = None\n        if c:\n            z = 6\n    reveal_type(z)  # N: Revealed type is \"builtins.int | None\"\n\ndef f20(b: bool) -> None:\n    if b:\n        x: Any = 5\n    else:\n        x = None\n    reveal_type(x)  # N: Revealed type is \"Any\"\n\ndef f_unannot(): pass\n\ndef f21(b: bool) -> None:\n    if b:\n        x = f_unannot()\n    else:\n        x = None\n    reveal_type(x)  # N: Revealed type is \"Any\"\n\ndef f22(b: bool) -> None:\n    if b:\n        z = 10\n    if not b:\n        z = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\ndef f23(b: bool) -> None:\n    if b:\n        z = 10\n    if b:\n        z = 11\n    else:\n        z = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\n[builtins fixtures/exception.pyi]\n\n[case testOptionalBackwards2]\n\ndef f1(b: bool) -> None:\n    if b:\n        x = []  # E: Need type annotation for \"x\" (hint: \"x: list[<type>] = ...\")\n    else:\n        x = None\n\ndef f2(b: bool) -> None:\n    if b:\n        x = []\n        x.append(1)\n    else:\n        x = None\n    reveal_type(x)  # N: Revealed type is \"builtins.list[builtins.int] | None\"\n\n\n[builtins fixtures/list.pyi]\n\n[case testOptionalBackwards3]\n\n# We don't allow this sort of updating for globals or attributes currently.\ngb: bool\nif gb:\n    Z = 10\nelse:\n    Z = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\nclass Foo:\n    def __init__(self, b: bool) -> None:\n        if b:\n            self.x = 5\n        else:\n            self.x = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"int\")\n\n    def foo(self) -> None:\n        reveal_type(self.x)  # N: Revealed type is \"builtins.int\"\n\n[case testOptionalBackwards4]\nfrom typing import Any, Optional\n\ndef f1(b: bool) -> Optional[int]:\n    if b:\n        z = 10\n        reveal_type(z)  # N: Revealed type is \"builtins.int\"\n    else:\n        # Force the node to get deferred between the two assignments\n        Defer().defer\n        z = None\n        reveal_type(z)  # N: Revealed type is \"None\"\n    reveal_type(z)  # N: Revealed type is \"builtins.int | None\"\n    return z\n\nclass Defer:\n    def __init__(self) -> None:\n        self.defer = 10\n\n[case testOptionalIterator]\n# mypy: no-strict-optional\nfrom typing import Optional, List\n\nx: Optional[List[int]]\nif 3 in x:\n    pass\n\n[case testNarrowedVariableInNestedFunctionBasic]\nfrom typing import Optional\n\ndef can_narrow(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    nested()\n\ndef foo(a): pass\n\nclass C:\n    def can_narrow_in_method(self, x: Optional[str]) -> None:\n        if x is None:\n            x = \"a\"\n        def nested() -> str:\n            return reveal_type(x)  # N: Revealed type is \"builtins.str\"\n        # Reading the variable is fine\n        y = x\n        with foo(x):\n            foo(x)\n        for a in foo(x):\n            foo(x)\n        nested()\n\ndef can_narrow_lambda(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    nested = lambda: x\n    reveal_type(nested())  # N: Revealed type is \"builtins.str\"\n\ndef cannot_narrow_if_reassigned(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    if int():\n        x = None\n    nested()\n\nx: Optional[str] = \"x\"\n\ndef narrow_global_in_func() -> None:\n    global x\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        # This should perhaps not be narrowed, since the nested function could outlive\n        # the outer function, and since other functions could also assign to x, but\n        # this seems like a minor issue.\n        return x\n    nested()\n\nx = \"y\"\n\ndef narrowing_global_at_top_level_not_propagated() -> str:\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n\n[case testNarrowedVariableInNestedFunctionMore1]\nfrom typing import Optional, overload\n\nclass C:\n    a: Optional[str]\n\ndef attribute_narrowing(c: C) -> None:\n    # This case is not supported, since we can't keep track of assignments to attributes.\n    c.a = \"x\"\n    def nested() -> str:\n        return c.a  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    nested()\n\ndef assignment_in_for(x: Optional[str]) -> None:\n    if x is None:\n        x = \"e\"\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    for x in [\"x\"]:\n        pass\n\ndef foo(): pass\n\ndef assignment_in_with(x: Optional[str]) -> None:\n    if x is None:\n        x = \"e\"\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    with foo() as x:\n        pass\n\ng: Optional[str]\n\ndef assign_to_global() -> None:\n    global g\n    g = \"x\"\n    # This is unsafe, but we don't generate an error, for convenience. Besides,\n    # this is probably a very rare case.\n    def nested() -> str:\n        return g\n\ndef assign_to_nonlocal(x: Optional[str]) -> None:\n    def nested() -> str:\n        nonlocal x\n\n        if x is None:\n            x = \"a\"\n\n        def nested2() -> str:\n            return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n\n        return nested2()\n    nested()\n    x = None\n\ndef dec(f):\n    return f\n\n@dec\ndef decorated_outer(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x\n    nested()\n\n@dec\ndef decorated_outer_bad(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    x = None\n    nested()\n\ndef decorated_inner(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    @dec\n    def nested() -> str:\n        return x\n    nested()\n\ndef decorated_inner_bad(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    @dec\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    x = None\n    nested()\n\n@overload\ndef overloaded_outer(x: None) -> None: ...\n@overload\ndef overloaded_outer(x: str) -> None: ...\ndef overloaded_outer(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x\n    nested()\n\n@overload\ndef overloaded_outer_bad(x: None) -> None: ...\n@overload\ndef overloaded_outer_bad(x: str) -> None: ...\ndef overloaded_outer_bad(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    x = None\n    nested()\n\n[case testNarrowedVariableInNestedFunctionMore2]\nfrom typing import Optional\n\ndef narrow_multiple(x: Optional[str], y: Optional[int]) -> None:\n    z: Optional[str] = x\n    if x is None:\n        x = \"\"\n    if y is None:\n        y = 1\n    if int():\n        if z is None:\n            z = \"\"\n        def nested() -> None:\n            a: str = x\n            b: int = y\n            c: str = z\n        nested()\n\ndef narrow_multiple_partial(x: Optional[str], y: Optional[int]) -> None:\n    z: Optional[str] = x\n    if x is None:\n        x = \"\"\n    if isinstance(y, int):\n        if z is None:\n            z = \"\"\n        def nested() -> None:\n            a: str = x\n            b: int = y\n            c: str = z  # E: Incompatible types in assignment (expression has type \"str | None\", variable has type \"str\")\n        z = None\n        nested()\n\ndef multiple_nested_functions(x: Optional[str], y: Optional[str]) -> None:\n    if x is None:\n        x = \"\"\n    def nested1() -> str:\n        return x\n    if y is None:\n        y = \"\"\n    def nested2() -> str:\n        a: str = y\n        return x\n\nclass C:\n    a: str\n    def __setitem__(self, key, value): pass\n\ndef narrowed_variable_used_in_lvalue_but_not_assigned(c: Optional[C]) -> None:\n    if c is None:\n        c = C()\n    def nested() -> C:\n        return c\n    c.a = \"x\"\n    c[1] = 2\n    cc = C()\n    cc[c] = 3\n    nested()\n\ndef narrow_with_multi_lvalues_1(x: Optional[str]) -> None:\n    if x is None:\n        x = \"\"\n\n    def nested() -> str:\n        return x\n\n    y = z = None\n\ndef narrow_with_multi_lvalue_2(x: Optional[str]) -> None:\n    if x is None:\n        x = \"\"\n\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n\n    x = y = None\n\ndef narrow_with_multi_lvalue_3(x: Optional[str]) -> None:\n    if x is None:\n        x = \"\"\n\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n\n    y = x = None\n\ndef narrow_with_multi_assign_1(x: Optional[str]) -> None:\n    if x is None:\n        x = \"\"\n\n    def nested() -> str:\n        return x\n\n    y, z = None, None\n\ndef narrow_with_multi_assign_2(x: Optional[str]) -> None:\n    if x is None:\n        x = \"\"\n\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n\n    x, y = None, None\n\ndef narrow_with_multi_assign_3(x: Optional[str]) -> None:\n    if x is None:\n        x = \"\"\n\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n\n    y, x = None, None\n\n[builtins fixtures/isinstance.pyi]\n\n[case testNestedFunctionSpecialCase]\nclass C:\n    def __enter__(self, *args): ...\n    def __exit__(self, *args) -> bool: ...\n\ndef f(x: object) -> None:\n    if x is not None:\n        pass\n\n    def nested() -> None:\n        with C():\n            pass\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-parameter-specification.test",
    "content": "[case testBasicParamSpec]\nfrom typing_extensions import ParamSpec\nP = ParamSpec('P')\n[builtins fixtures/tuple.pyi]\n\n[case testInvalidParamSpecDefinitions]\nfrom typing import ParamSpec\n\nP1 = ParamSpec(\"P1\", covariant=True)  # E: The variance and bound arguments to ParamSpec do not have defined semantics yet\nP2 = ParamSpec(\"P2\", contravariant=True)  # E: The variance and bound arguments to ParamSpec do not have defined semantics yet\nP3 = ParamSpec(\"P3\", bound=int)  # E: The variance and bound arguments to ParamSpec do not have defined semantics yet\nP4 = ParamSpec(\"P4\", int, str)  # E: Too many positional arguments for \"ParamSpec\"\nP5 = ParamSpec(\"P5\", covariant=True, bound=int)  # E: The variance and bound arguments to ParamSpec do not have defined semantics yet\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecLocations]\nfrom typing import Any, Callable, List, Type\nfrom typing_extensions import ParamSpec, Concatenate\nP = ParamSpec('P')\n\nx: P  # E: ParamSpec \"P\" is unbound\n\ndef foo1(x: Callable[P, int]) -> Callable[P, str]:  ...\n\ndef foo2(x: P) -> P: ...  # E: Invalid location for ParamSpec \"P\" \\\n                          # N: You can use ParamSpec as the first argument to Callable, e.g., \"Callable[P, int]\"\n\ndef foo3(x: Concatenate[int, P]) -> int: ...  # E: Invalid location for Concatenate \\\n                                              # N: You can use Concatenate as the first argument to Callable\n\ndef foo4(x: List[P]) -> None: ...  # E: Invalid location for ParamSpec \"P\" \\\n                                   # N: You can use ParamSpec as the first argument to Callable, e.g., \"Callable[P, int]\"\n\ndef foo5(x: Callable[[int, str], P]) -> None: ...  # E: Invalid location for ParamSpec \"P\" \\\n                                                   # N: You can use ParamSpec as the first argument to Callable, e.g., \"Callable[P, int]\"\n\ndef foo6(x: Callable[[P], int]) -> None: ...  # E: Invalid location for ParamSpec \"P\" \\\n                                              # N: You can use ParamSpec as the first argument to Callable, e.g., \"Callable[P, int]\"\n\ndef foo7(\n    *args: P.args, **kwargs: P.kwargs  # E: ParamSpec \"P\" is unbound\n) -> Callable[[Callable[P, T]], Type[T]]:\n    ...\n\ndef wrapper(f: Callable[P, int]) -> None:\n    def inner(*args: P.args, **kwargs: P.kwargs) -> None: ...  # OK\n\n    def extra_args_left(x: int, *args: P.args, **kwargs: P.kwargs) -> None: ...  # OK\n    def extra_args_between(*args: P.args, x: int, **kwargs: P.kwargs) -> None: ...  # E: Arguments not allowed after ParamSpec.args\n\n    def swapped(*args: P.kwargs, **kwargs: P.args) -> None: ... # E: Use \"P.args\" for variadic \"*\" parameter \\\n                                                                # E: Use \"P.kwargs\" for variadic \"**\" parameter\n    def bad_kwargs(*args: P.args, **kwargs: P.args) -> None: ...  # E: Use \"P.kwargs\" for variadic \"**\" parameter\n    def bad_args(*args: P.kwargs, **kwargs: P.kwargs) -> None: ...  # E: Use \"P.args\" for variadic \"*\" parameter\n\n    def misplaced(x: P.args) -> None:  ...  # E: ParamSpec components are not allowed here\n    def bad_kwargs_any(*args: P.args, **kwargs: Any) -> None: ... # E: ParamSpec must have \"*args\" typed as \"P.args\" and \"**kwargs\" typed as \"P.kwargs\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecImports]\nimport lib\nfrom lib import Base\n\nclass C(Base[[int]]):\n    def test(self, x: int): ...\n\nclass D(lib.Base[[int]]):\n    def test(self, x: int): ...\n\nclass E(lib.Base[...]): ...\nreveal_type(E().test)  # N: Revealed type is \"def (*Any, **Any)\"\n\n[file lib.py]\nfrom typing import Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nclass Base(Generic[P]):\n    def test(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        ...\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecEllipsisInAliases]\nfrom typing import Any, Callable, Generic, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nR = TypeVar('R')\nAlias = Callable[P, R]\n\nclass B(Generic[P]): ...\nOther = B[P]\n\nT = TypeVar('T', bound=Alias[..., Any])\nAlias[..., Any]  # E: Type application is only supported for generic classes\nB[...]\nOther[...]\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecEllipsisInConcatenate]\nfrom typing import Any, Callable, Generic, TypeVar\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec('P')\nR = TypeVar('R')\nAlias = Callable[P, R]\n\nIntFun = Callable[Concatenate[int, ...], None]\nf: IntFun\nreveal_type(f)  # N: Revealed type is \"def (builtins.int, *Any, **Any)\"\n\ng: Callable[Concatenate[int, ...], None]\nreveal_type(g)  # N: Revealed type is \"def (builtins.int, *Any, **Any)\"\n\nclass B(Generic[P]):\n    def test(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        ...\n\nx: B[Concatenate[int, ...]]\nreveal_type(x.test)  # N: Revealed type is \"def (builtins.int, *Any, **Any)\"\n\nBad = Callable[Concatenate[int, [int, str]], None]  # E: The last parameter to Concatenate needs to be a ParamSpec \\\n                                                    # E: Bracketed expression \"[...]\" is not valid as a type\ndef bad(fn: Callable[Concatenate[P, int], None]):  # E: The last parameter to Concatenate needs to be a ParamSpec\n    ...\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecContextManagerLike]\nfrom typing import Callable, List, Iterator, TypeVar\nfrom typing_extensions import ParamSpec\nP = ParamSpec('P')\nT = TypeVar('T')\n\ndef tmpcontextmanagerlike(x: Callable[P, Iterator[T]]) -> Callable[P, List[T]]: ...\n\n@tmpcontextmanagerlike\ndef whatever(x: int) -> Iterator[int]:\n    yield x\n\nreveal_type(whatever)  # N: Revealed type is \"def (x: builtins.int) -> builtins.list[builtins.int]\"\nreveal_type(whatever(217))  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testInvalidParamSpecType]\n# flags: --python-version 3.10\nfrom typing import ParamSpec\n\nP = ParamSpec(\"P\")\n\nclass MyFunction(P):  # E: Invalid base class \"P\"\n    ...\n\n[case testParamSpecRevealType]\nfrom typing import Callable\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\n\ndef f(x: Callable[P, int]) -> None: ...\nreveal_type(f)  # N: Revealed type is \"def [P] (x: def (*P.args, **P.kwargs) -> builtins.int)\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecSimpleFunction]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\n\ndef changes_return_type_to_str(x: Callable[P, int]) -> Callable[P, str]: ...\n\ndef returns_int(a: str, b: bool) -> int: ...\n\nreveal_type(changes_return_type_to_str(returns_int))  # N: Revealed type is \"def (a: builtins.str, b: builtins.bool) -> builtins.str\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecSimpleClass]\nfrom typing import Callable, TypeVar, Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\n\nclass C(Generic[P]):\n    def __init__(self, x: Callable[P, None]) -> None: ...\n\n    def m(self, *args: P.args, **kwargs: P.kwargs) -> int:\n        return 1\n\ndef f(x: int, y: str) -> None: ...\n\nreveal_type(C(f))  # N: Revealed type is \"__main__.C[[x: builtins.int, y: builtins.str]]\"\nreveal_type(C(f).m)  # N: Revealed type is \"def (x: builtins.int, y: builtins.str) -> builtins.int\"\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecClassWithPrefixArgument]\nfrom typing import Callable, TypeVar, Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\n\nclass C(Generic[P]):\n    def __init__(self, x: Callable[P, None]) -> None: ...\n\n    def m(self, a: str, *args: P.args, **kwargs: P.kwargs) -> int:\n        return 1\n\ndef f(x: int, y: str) -> None: ...\n\nreveal_type(C(f).m)  # N: Revealed type is \"def (a: builtins.str, x: builtins.int, y: builtins.str) -> builtins.int\"\nreveal_type(C(f).m('', 1, ''))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecDecorator]\nfrom typing import Callable, TypeVar, Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nR = TypeVar('R')\n\nclass W(Generic[P, R]):\n    f: Callable[P, R]\n    x: int\n    def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n        reveal_type(self.f(*args, **kwargs))  # N: Revealed type is \"R`2\"\n        return self.f(*args, **kwargs)\n\ndef dec() -> Callable[[Callable[P, R]], W[P, R]]:\n    pass\n\n@dec()\ndef f(a: int, b: str) -> None: ...\n\nreveal_type(f)  # N: Revealed type is \"__main__.W[[a: builtins.int, b: builtins.str], None]\"\nreveal_type(f(1, ''))  # N: Revealed type is \"None\"\nreveal_type(f.x)  # N: Revealed type is \"builtins.int\"\n\n## TODO: How should this work?\n#\n# class C:\n#     @dec()\n#     def m(self, x: int) -> str: ...\n#\n# reveal_type(C().m(x=1))\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecFunction]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nR = TypeVar('R')\n\ndef f(x: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R:\n    return x(*args, **kwargs)\n\ndef g(x: int, y: str) -> None: ...\n\nreveal_type(f(g, 1, y='x'))  # N: Revealed type is \"None\"\nf(g, 'x', y='x')  # E: Argument 2 to \"f\" has incompatible type \"str\"; expected \"int\"\nf(g, 1, y=1)  # E: Argument \"y\" to \"f\" has incompatible type \"int\"; expected \"str\"\nf(g)  # E: Missing positional arguments \"x\", \"y\" in call to \"f\"\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecSpecialCase]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nT = TypeVar('T')\n\ndef register(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> Callable[P, T]: ...\n\ndef f(x: int, y: str, z: int, a: str) -> None: ...\n\nx = register(f, 1, '', 1, '')\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecInferredFromAny]\nfrom typing import Callable, Any\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\n\ndef f(x: Callable[P, int]) -> Callable[P, str]: ...\n\ng: Any\nreveal_type(f(g))  # N: Revealed type is \"def (*Any, **Any) -> builtins.str\"\n\nf(g)(1, 3, x=1, y=2)\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecDecoratorImplementation]\nfrom typing import Callable, Any, TypeVar, List\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nT = TypeVar('T')\n\ndef dec(f: Callable[P, T]) -> Callable[P, List[T]]:\n    def wrapper(*args: P.args, **kwargs: P.kwargs) -> List[T]:\n        return [f(*args, **kwargs)]\n    return wrapper\n\n@dec\ndef g(x: int, y: str = '') -> int: ...\n\nreveal_type(g)  # N: Revealed type is \"def (x: builtins.int, y: builtins.str =) -> builtins.list[builtins.int]\"\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecArgsAndKwargsTypes]\nfrom typing import Callable, TypeVar, Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\n\nclass C(Generic[P]):\n    def __init__(self, x: Callable[P, None]) -> None: ...\n\n    def m(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        reveal_type(args)  # N: Revealed type is \"P.args`1\"\n        reveal_type(kwargs)  # N: Revealed type is \"P.kwargs`1\"\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecSubtypeChecking1]\nfrom typing import Callable, TypeVar, Generic, Any\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\n\nclass C(Generic[P]):\n    def __init__(self, x: Callable[P, None]) -> None: ...\n\n    def m(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        args = args\n        kwargs = kwargs\n        o: object\n        o = args\n        o = kwargs\n        o2: object\n        args = o2  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"P.args\")\n        kwargs = o2  # E: Incompatible types in assignment (expression has type \"object\", variable has type \"P.kwargs\")\n        a: Any\n        a = args\n        a = kwargs\n        args = kwargs  # E: Incompatible types in assignment (expression has type \"P.kwargs\", variable has type \"P.args\")\n        kwargs = args  # E: Incompatible types in assignment (expression has type \"P.args\", variable has type \"P.kwargs\")\n        a1: Any\n        args = a1\n        kwargs = a1\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecSubtypeChecking2]\nfrom typing import Callable, Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nP2 = ParamSpec('P2')\n\nclass C(Generic[P]):\n    pass\n\ndef f(c1: C[P], c2: C[P2]) -> None:\n    c1 = c1\n    c2 = c2\n    c1 = c2  # E: Incompatible types in assignment (expression has type \"C[P2]\", variable has type \"C[P]\")\n    c2 = c1  # E: Incompatible types in assignment (expression has type \"C[P]\", variable has type \"C[P2]\")\n\ndef g(f: Callable[P, None], g: Callable[P2, None]) -> None:\n    f = f\n    g = g\n    f = g  # E: Incompatible types in assignment (expression has type \"Callable[P2, None]\", variable has type \"Callable[P, None]\")\n    g = f  # E: Incompatible types in assignment (expression has type \"Callable[P, None]\", variable has type \"Callable[P2, None]\")\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecJoin]\nfrom typing import Callable, Generic, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nP2 = ParamSpec('P2')\nP3 = ParamSpec('P3')\nT = TypeVar('T')\n\ndef join(x: T, y: T) -> T: ...\n\nclass C(Generic[P, P2]):\n    def m(self, f: Callable[P, None], g: Callable[P2, None]) -> None:\n        reveal_type(join(f, f))  # N: Revealed type is \"def (*P.args, **P.kwargs)\"\n        reveal_type(join(f, g))  # N: Revealed type is \"builtins.function\"\n\n    def m2(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        reveal_type(join(args, args))  # N: Revealed type is \"P.args`1\"\n        reveal_type(join(kwargs, kwargs))  # N: Revealed type is \"P.kwargs`1\"\n        reveal_type(join(args, kwargs))  # N: Revealed type is \"builtins.object\"\n        def f(*args2: P2.args, **kwargs2: P2.kwargs) -> None:\n            reveal_type(join(args, args2))  # N: Revealed type is \"builtins.object\"\n            reveal_type(join(kwargs, kwargs2))  # N: Revealed type is \"builtins.object\"\n\n    def m3(self, c: C[P, P3]) -> None:\n        reveal_type(join(c, c))  # N: Revealed type is \"__main__.C[P`1, P3`-1]\"\n        reveal_type(join(self, c))  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecClassWithAny]\nfrom typing import Callable, Generic, Any\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\n\nclass C(Generic[P]):\n    def __init__(self, x: Callable[P, None]) -> None: ...\n\n    def m(self, *args: P.args, **kwargs: P.kwargs) -> int:\n        return 1\n\nc: C[Any]\nreveal_type(c)  # N: Revealed type is \"__main__.C[Any]\"\nreveal_type(c.m)  # N: Revealed type is \"def (*args: Any, **kwargs: Any) -> builtins.int\"\nc.m(4, 6, y='x')\nc = c\n\ndef f() -> None: pass\n\nc2 = C(f)\nc2 = c\nc3 = C(f)\nc = c3\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecInferredFromLambda]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nT = TypeVar('T')\n\n# Similar to atexit.register\ndef register(f: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> Callable[P, T]: ...\n\ndef f(x: int) -> None: pass\ndef g(x: int, y: str) -> None: pass\n\nreveal_type(register(lambda: f(1)))  # N: Revealed type is \"def ()\"\nreveal_type(register(lambda x: f(x), x=1))  # N: Revealed type is \"def (x: Literal[1]?)\"\nregister(lambda x: f(x))  # E: Cannot infer type of lambda \\\n                          # E: Argument 1 to \"register\" has incompatible type \"Callable[[Any], None]\"; expected \"Callable[[], None]\"\nregister(lambda x: f(x), y=1)  # E: Argument 1 to \"register\" has incompatible type \"def (x: int) -> None\"; expected \"def (y: int) -> None\"\nreveal_type(register(lambda x: f(x), 1))  # N: Revealed type is \"def (Literal[1]?)\"\nreveal_type(register(lambda x, y: g(x, y), 1, \"a\"))  # N: Revealed type is \"def (Literal[1]?, Literal['a']?)\"\nreveal_type(register(lambda x, y: g(x, y), 1, y=\"a\"))  # N: Revealed type is \"def (Literal[1]?, y: Literal['a']?)\"\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecInvalidCalls]\nfrom typing import Callable, Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nP2 = ParamSpec('P2')\n\nclass C(Generic[P, P2]):\n    def m1(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        self.m1(*args, **kwargs)\n        self.m2(*args, **kwargs)  # E: Argument 1 to \"m2\" of \"C\" has incompatible type \"*P.args\"; expected \"P2.args\" \\\n            # E: Argument 2 to \"m2\" of \"C\" has incompatible type \"**P.kwargs\"; expected \"P2.kwargs\"\n        self.m1(*kwargs, **args)  # E: Argument 1 to \"m1\" of \"C\" has incompatible type \"*P.kwargs\"; expected \"P.args\" \\\n            # E: Argument 2 to \"m1\" of \"C\" has incompatible type \"**P.args\"; expected \"P.kwargs\"\n        self.m3(*args, **kwargs)  # E: Argument 1 to \"m3\" of \"C\" has incompatible type \"*P.args\"; expected \"int\" \\\n            # E: Argument 2 to \"m3\" of \"C\" has incompatible type \"**P.kwargs\"; expected \"int\"\n        self.m4(*args, **kwargs)  # E: Argument 1 to \"m4\" of \"C\" has incompatible type \"*P.args\"; expected \"int\" \\\n            # E: Argument 2 to \"m4\" of \"C\" has incompatible type \"**P.kwargs\"; expected \"int\"\n\n        self.m1(*args, **args)  # E: Argument 2 to \"m1\" of \"C\" has incompatible type \"**P.args\"; expected \"P.kwargs\"\n        self.m1(*kwargs, **kwargs)  # E: Argument 1 to \"m1\" of \"C\" has incompatible type \"*P.kwargs\"; expected \"P.args\"\n\n    def m2(self, *args: P2.args, **kwargs: P2.kwargs) -> None:\n        pass\n\n    def m3(self, *args: int, **kwargs: int) -> None:\n        pass\n\n    def m4(self, x: int) -> None:\n        pass\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecOverUnannotatedDecorator]\nfrom typing import Callable, Iterator, TypeVar, ContextManager, Any\nfrom typing_extensions import ParamSpec\n\nfrom nonexistent import deco2  # type: ignore\n\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nT_co = TypeVar(\"T_co\", covariant=True)\n\nclass CM(ContextManager[T_co]):\n    def __call__(self, func: T) -> T: ...\n\ndef deco1(\n    func: Callable[P, Iterator[T]]) -> Callable[P, CM[T]]: ...\n\n@deco1\n@deco2\ndef f():\n    pass\n\nreveal_type(f)  # N: Revealed type is \"def (*Any, **Any) -> __main__.CM[Any]\"\n\nwith f() as x:\n    pass\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testParamSpecLiterals]\nfrom typing_extensions import ParamSpec, TypeAlias\nfrom typing import Generic, TypeVar\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\nclass Z(Generic[P]): ...\n\n# literals can be applied\nn: Z[[int]]\n\nnt1 = Z[[int]]\nnt2: TypeAlias = Z[[int]]\n\nunt1: nt1\nunt2: nt2\n\n# literals actually keep types\nreveal_type(n)  # N: Revealed type is \"__main__.Z[[builtins.int]]\"\nreveal_type(unt1)  # N: Revealed type is \"__main__.Z[[builtins.int]]\"\nreveal_type(unt2)  # N: Revealed type is \"__main__.Z[[builtins.int]]\"\n\n# passing into a function keeps the type\ndef fT(a: T) -> T: ...\ndef fP(a: Z[P]) -> Z[P]: ...\n\nreveal_type(fT(n))  # N: Revealed type is \"__main__.Z[[builtins.int]]\"\nreveal_type(fP(n))  # N: Revealed type is \"__main__.Z[[builtins.int]]\"\n\n# literals can be in function args and return type\ndef k(a: Z[[int]]) -> Z[[str]]: ...\n\n# functions work\nreveal_type(k(n))  # N: Revealed type is \"__main__.Z[[builtins.str]]\"\n\n# literals can be matched in arguments\ndef kb(a: Z[[bytes]]) -> Z[[str]]: ...\n\nreveal_type(kb(n))  # N: Revealed type is \"__main__.Z[[builtins.str]]\" \\\n                    # E: Argument 1 to \"kb\" has incompatible type \"Z[[int]]\"; expected \"Z[[bytes]]\"\n\n\nn2: Z[bytes]\n\nreveal_type(kb(n2))  # N: Revealed type is \"__main__.Z[[builtins.str]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testParamSpecConcatenateFromPep]\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable, TypeVar, Generic\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\n# CASE 1\nclass Request:\n    ...\n\ndef with_request(f: Callable[Concatenate[Request, P], R]) -> Callable[P, R]:\n    def inner(*args: P.args, **kwargs: P.kwargs) -> R:\n        return f(Request(), *args, **kwargs)\n    return inner\n\n@with_request\ndef takes_int_str(request: Request, x: int, y: str) -> int:\n    # use request\n    return x + 7\n\nreveal_type(takes_int_str)  # N: Revealed type is \"def (x: builtins.int, y: builtins.str) -> builtins.int\"\n\ntakes_int_str(1, \"A\") # Accepted\ntakes_int_str(\"B\", 2) # E: Argument 1 to \"takes_int_str\" has incompatible type \"str\"; expected \"int\" \\\n                      # E: Argument 2 to \"takes_int_str\" has incompatible type \"int\"; expected \"str\"\n\n# CASE 2\nT = TypeVar(\"T\")\nP_2 = ParamSpec(\"P_2\")\n\nclass X(Generic[T, P]):\n  f: Callable[P, int]\n  x: T\n\ndef f1(x: X[int, P_2]) -> str: ...                    # Accepted\ndef f2(x: X[int, Concatenate[int, P_2]]) -> str: ...  # Accepted\ndef f3(x: X[int, [int, bool]]) -> str: ...            # Accepted\n# ellipsis only show up here, but I can assume it works like Callable[..., R]\ndef f4(x: X[int, ...]) -> str: ...                    # Accepted\ndef f5(x: X[int, int]) -> str: ...  # E: Can only replace ParamSpec with a parameter types list or another ParamSpec, got \"int\"\n\n# CASE 3\ndef bar(x: int, *args: bool) -> int: ...\ndef add(x: Callable[P, int]) -> Callable[Concatenate[str, P], bool]: ...\n\nreveal_type(add(bar))       # N: Revealed type is \"def (builtins.str, x: builtins.int, *args: builtins.bool) -> builtins.bool\"\n\ndef remove(x: Callable[Concatenate[int, P], int]) -> Callable[P, bool]: ...\n\nreveal_type(remove(bar))    # N: Revealed type is \"def (*args: builtins.bool) -> builtins.bool\"\n\ndef transform(\n  x: Callable[Concatenate[int, P], int]\n) -> Callable[Concatenate[str, P], bool]: ...\n\n# In the PEP, \"__a\" appears. What is that? Autogenerated names? To what spec?\nreveal_type(transform(bar)) # N: Revealed type is \"def (builtins.str, *args: builtins.bool) -> builtins.bool\"\n\n# CASE 4\ndef expects_int_first(x: Callable[Concatenate[int, P], int]) -> None: ...\n\n@expects_int_first  # E: Argument 1 to \"expects_int_first\" has incompatible type \"Callable[[str], int]\"; expected \"Callable[[int], int]\" \\\n                    # N: This is likely because \"one\" has named arguments: \"x\". Consider marking them positional-only\ndef one(x: str) -> int: ...\n\n@expects_int_first  # E: Argument 1 to \"expects_int_first\" has incompatible type \"def two(*, x: int) -> int\"; expected \"def (int, /, *, x: int) -> int\"\ndef two(*, x: int) -> int: ...\n\n@expects_int_first  # E: Argument 1 to \"expects_int_first\" has incompatible type \"def three(**kwargs: int) -> int\"; expected \"def (int, /, **kwargs: int) -> int\"\ndef three(**kwargs: int) -> int: ...\n\n@expects_int_first # Accepted\ndef four(*args: int) -> int: ...\n[builtins fixtures/dict.pyi]\n\n[case testParamSpecTwiceSolving]\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable, TypeVar\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\ndef f(one: Callable[Concatenate[int, P], R], two: Callable[Concatenate[str, P], R]) -> Callable[P, R]: ...\n\na: Callable[[int, bytes], str]\nb: Callable[[str, bytes], str]\n\nreveal_type(f(a, b))  # N: Revealed type is \"def (builtins.bytes) -> builtins.str\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecConcatenateInReturn]\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable, Protocol\n\nP = ParamSpec(\"P\")\n\ndef f(i: Callable[Concatenate[int, P], str]) -> Callable[Concatenate[int, P], str]: ...\n\nn: Callable[[int, bytes], str]\n\nreveal_type(f(n))  # N: Revealed type is \"def (builtins.int, builtins.bytes) -> builtins.str\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecConcatenateNamedArgs]\n# flags: --extra-checks\n# this is one noticeable deviation from PEP but I believe it is for the better\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable, TypeVar\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\ndef f1(c: Callable[P, R]) -> Callable[Concatenate[int, P], R]:\n    def result(x: int, /, *args: P.args, **kwargs: P.kwargs) -> R: ...\n\n    return result  # Accepted\n\ndef f2(c: Callable[P, R]) -> Callable[Concatenate[int, P], R]:\n    def result(x: int, *args: P.args, **kwargs: P.kwargs) -> R: ...\n\n    return result  # Rejected\n\n# reason for rejection:\nf2(lambda x: 42)(42, x=42)\n[builtins fixtures/paramspec.pyi]\n[out]\nmain:17: error: Incompatible return value type (got \"Callable[[Arg(int, 'x'), **P], R]\", expected \"Callable[[int, **P], R]\")\nmain:17: note: This is likely because \"result\" has named arguments: \"x\". Consider marking them positional-only\n\n[case testNonStrictParamSpecConcatenateNamedArgs]\n# this is one noticeable deviation from PEP but I believe it is for the better\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable, TypeVar\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\ndef f1(c: Callable[P, R]) -> Callable[Concatenate[int, P], R]:\n    def result(x: int, /, *args: P.args, **kwargs: P.kwargs) -> R: ...\n\n    return result  # Accepted\n\ndef f2(c: Callable[P, R]) -> Callable[Concatenate[int, P], R]:\n    def result(x: int, *args: P.args, **kwargs: P.kwargs) -> R: ...\n\n    return result  # Rejected -> Accepted\n\n# reason for rejection:\nf2(lambda x: 42)(42, x=42)\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecConcatenateWithTypeVar]\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable, TypeVar\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\nS = TypeVar(\"S\")\n\ndef f(c: Callable[Concatenate[S, P], R]) -> Callable[Concatenate[S, P], R]: ...\n\ndef a(n: int) -> None: ...\n\nn = f(a)\n\nreveal_type(n)  # N: Revealed type is \"def (builtins.int)\"\nreveal_type(n(42))  # N: Revealed type is \"None\"\n[builtins fixtures/paramspec.pyi]\n\n[case testCallablesAsParameters]\n# credits to https://github.com/microsoft/pyright/issues/2705\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Generic, Callable, Any\n\nP = ParamSpec(\"P\")\n\nclass Foo(Generic[P]):\n    def __init__(self, func: Callable[P, Any]) -> None: ...\ndef bar(baz: Foo[Concatenate[int, P]]) -> Foo[P]: ...\n\ndef test(a: int, /, b: str) -> str: ...\n\nabc = Foo(test)\nreveal_type(abc)\nbar(abc)\n[builtins fixtures/paramspec.pyi]\n[out]\nmain:14: note: Revealed type is \"__main__.Foo[[builtins.int, b: builtins.str]]\"\n\n[case testSolveParamSpecWithSelfType]\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable, Generic\n\nP = ParamSpec(\"P\")\n\nclass Foo(Generic[P]):\n    def foo(self: 'Foo[P]', other: Callable[P, None]) -> None: ...\n\nn: Foo[[int]]\ndef f(x: int) -> None: ...\n\nn.foo(f)\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecLiteralsTypeApplication]\nfrom typing_extensions import ParamSpec\nfrom typing import Generic, Callable\n\nP = ParamSpec(\"P\")\n\nclass Z(Generic[P]):\n    def __init__(self, c: Callable[P, None]) -> None:\n        ...\n\n# it allows valid functions\nreveal_type(Z[[int]](lambda x: None))  # N: Revealed type is \"__main__.Z[[builtins.int]]\"\nreveal_type(Z[[]](lambda: None))  # N: Revealed type is \"__main__.Z[[]]\"\nreveal_type(Z[bytes, str](lambda b, s: None))  # N: Revealed type is \"__main__.Z[[builtins.bytes, builtins.str]]\"\n\n# it disallows invalid functions\ndef f1(n: str) -> None: ...\ndef f2(b: bytes, i: int) -> None: ...\n\nZ[[int]](lambda one, two: None)  # E: Cannot infer type of lambda \\\n                                 # E: Argument 1 to \"Z\" has incompatible type \"Callable[[Any, Any], None]\"; expected \"Callable[[int], None]\"\nZ[[int]](f1)  # E: Argument 1 to \"Z\" has incompatible type \"Callable[[str], None]\"; expected \"Callable[[int], None]\"\n\nZ[[]](lambda one: None)  # E: Cannot infer type of lambda \\\n                         # E: Argument 1 to \"Z\" has incompatible type \"Callable[[Any], None]\"; expected \"Callable[[], None]\"\n\nZ[bytes, str](lambda one: None)  # E: Cannot infer type of lambda \\\n                                 # E: Argument 1 to \"Z\" has incompatible type \"Callable[[Any], None]\"; expected \"Callable[[bytes, str], None]\"\nZ[bytes, str](f2)  # E: Argument 1 to \"Z\" has incompatible type \"Callable[[bytes, int], None]\"; expected \"Callable[[bytes, str], None]\"\n\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecLiteralEllipsis]\nfrom typing_extensions import ParamSpec\nfrom typing import Generic, Callable\n\nP = ParamSpec(\"P\")\n\nclass Z(Generic[P]):\n    def __init__(self: 'Z[P]', c: Callable[P, None]) -> None:\n        ...\n\ndef f1() -> None: ...\ndef f2(*args: int) -> None: ...\ndef f3(a: int, *, b: bytes) -> None: ...\n\ndef f4(b: bytes) -> None: ...\n\nargh: Callable[..., None] = f4\n\n# check it works\nZ[...](f1)\nZ[...](f2)\nZ[...](f3)\n\n# check subtyping works\nn: Z[...]\nn = Z(f1)\nn = Z(f2)\nn = Z(f3)\n\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecApplyConcatenateTwice]\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Generic, Callable, Optional\n\nP = ParamSpec(\"P\")\n\nclass C(Generic[P]):\n    # think PhantomData<T> from rust\n    phantom: Optional[Callable[P, None]]\n\n    def add_str(self) -> C[Concatenate[str, P]]:\n        return C[Concatenate[str, P]]()\n\n    def add_int(self) -> C[Concatenate[int, P]]:\n        return C[Concatenate[int, P]]()\n\ndef f(c: C[P]) -> None:\n    reveal_type(c)  # N: Revealed type is \"__main__.C[P`-1]\"\n\n    n1 = c.add_str()\n    reveal_type(n1)  # N: Revealed type is \"__main__.C[[builtins.str, **P`-1]]\"\n    n2 = n1.add_int()\n    reveal_type(n2)  # N: Revealed type is \"__main__.C[[builtins.int, builtins.str, **P`-1]]\"\n\n    p1 = c.add_int()\n    reveal_type(p1)  # N: Revealed type is \"__main__.C[[builtins.int, **P`-1]]\"\n    p2 = p1.add_str()\n    reveal_type(p2)  # N: Revealed type is \"__main__.C[[builtins.str, builtins.int, **P`-1]]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecLiteralJoin]\nfrom typing import Generic, Callable, Union\nfrom typing_extensions import ParamSpec\n\n\n_P = ParamSpec(\"_P\")\n\nclass Job(Generic[_P]):\n    def __init__(self, target: Callable[_P, None]) -> None:\n        self.target = target\n\ndef func(\n    action: Union[Job[int], Callable[[int], None]],\n) -> None:\n    job = action if isinstance(action, Job) else Job(action)\n    reveal_type(job)  # N: Revealed type is \"__main__.Job[[builtins.int]]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testApplyParamSpecToParamSpecLiterals]\nfrom typing import TypeVar, Generic, Callable\nfrom typing_extensions import ParamSpec\n\n_P = ParamSpec(\"_P\")\n_R_co = TypeVar(\"_R_co\", covariant=True)\n\nclass Job(Generic[_P, _R_co]):\n    def __init__(self, target: Callable[_P, _R_co]) -> None:\n        self.target = target\n\ndef run_job(job: Job[_P, None], *args: _P.args, **kwargs: _P.kwargs) -> None:\n    ...\n\n\ndef func(job: Job[[int, str], None]) -> None:\n    run_job(job, 42, \"Hello\")\n    run_job(job, \"Hello\", 42) # E: Argument 2 to \"run_job\" has incompatible type \"str\"; expected \"int\" \\\n                              # E: Argument 3 to \"run_job\" has incompatible type \"int\"; expected \"str\"\n    run_job(job, 42, msg=\"Hello\")  # E: Unexpected keyword argument \"msg\" for \"run_job\"\n    run_job(job, \"Hello\") # E: Too few arguments for \"run_job\" \\\n                          # E: Argument 2 to \"run_job\" has incompatible type \"str\"; expected \"int\"\n\ndef func2(job: Job[..., None]) -> None:\n    run_job(job, 42, \"Hello\")\n    run_job(job, \"Hello\", 42)\n    run_job(job, 42, msg=\"Hello\")\n    run_job(job, x=42, msg=\"Hello\")\n[builtins fixtures/paramspec.pyi]\n\n[case testExpandNonBareParamSpecAgainstCallable]\nfrom typing import Callable, TypeVar, Any\nfrom typing_extensions import ParamSpec\n\nCallableT = TypeVar(\"CallableT\", bound=Callable[..., Any])\n_P = ParamSpec(\"_P\")\n_R = TypeVar(\"_R\")\n\ndef simple_decorator(callable: CallableT) -> CallableT:\n    # set some attribute on 'callable'\n    return callable\n\n\nclass A:\n    @simple_decorator\n    def func(self, action: Callable[_P, _R], *args: _P.args, **kwargs: _P.kwargs) -> _R:\n        ...\n\nreveal_type(A.func)  # N: Revealed type is \"def [_P, _R] (self: __main__.A, action: def (*_P.args, **_P.kwargs) -> _R`4, *_P.args, **_P.kwargs) -> _R`4\"\nreveal_type(A().func)  # N: Revealed type is \"def [_P, _R] (action: def (*_P.args, **_P.kwargs) -> _R`8, *_P.args, **_P.kwargs) -> _R`8\"\n\ndef f(x: int) -> int:\n    ...\n\nreveal_type(A().func(f, 42))  # N: Revealed type is \"builtins.int\"\n\nreveal_type(A().func(lambda x: x + x, 42))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecConstraintOnOtherParamSpec]\nfrom typing import Callable, TypeVar, Any, Generic\nfrom typing_extensions import ParamSpec\n\nCallableT = TypeVar(\"CallableT\", bound=Callable[..., Any])\n_P = ParamSpec(\"_P\")\n_R_co = TypeVar(\"_R_co\", covariant=True)\n\ndef simple_decorator(callable: CallableT) -> CallableT:\n    ...\n\nclass Job(Generic[_P, _R_co]):\n    def __init__(self, target: Callable[_P, _R_co]) -> None:\n        ...\n\n\nclass A:\n    @simple_decorator\n    def func(self, action: Job[_P, None]) -> Job[_P, None]:\n        ...\n\nreveal_type(A.func)  # N: Revealed type is \"def [_P] (self: __main__.A, action: __main__.Job[_P`3, None]) -> __main__.Job[_P`3, None]\"\nreveal_type(A().func)  # N: Revealed type is \"def [_P] (action: __main__.Job[_P`5, None]) -> __main__.Job[_P`5, None]\"\nreveal_type(A().func(Job(lambda x: x)))  # N: Revealed type is \"__main__.Job[[x: Any], None]\"\n\ndef f(x: int, y: int) -> None: ...\nreveal_type(A().func(Job(f)))  # N: Revealed type is \"__main__.Job[[x: builtins.int, y: builtins.int], None]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testConstraintBetweenParamSpecFunctions1]\nfrom typing import Callable, TypeVar, Any, Generic\nfrom typing_extensions import ParamSpec\n\n_P = ParamSpec(\"_P\")\n_R_co = TypeVar(\"_R_co\", covariant=True)\n\ndef simple_decorator(callable: Callable[_P, _R_co]) -> Callable[_P, _R_co]: ...\nclass Job(Generic[_P]): ...\n\n\n@simple_decorator\ndef func(__action: Job[_P]) -> Callable[_P, None]:\n    ...\n\nreveal_type(func)  # N: Revealed type is \"def [_P] (__main__.Job[_P`-1]) -> def (*_P.args, **_P.kwargs)\"\n[builtins fixtures/paramspec.pyi]\n\n[case testConstraintBetweenParamSpecFunctions2]\nfrom typing import Callable, TypeVar, Any, Generic\nfrom typing_extensions import ParamSpec\n\nCallableT = TypeVar(\"CallableT\", bound=Callable[..., Any])\n_P = ParamSpec(\"_P\")\n\ndef simple_decorator(callable: CallableT) -> CallableT: ...\nclass Job(Generic[_P]): ...\n\n\n@simple_decorator\ndef func(__action: Job[_P]) -> Callable[_P, None]:\n    ...\n\nreveal_type(func)  # N: Revealed type is \"def [_P] (__main__.Job[_P`-1]) -> def (*_P.args, **_P.kwargs)\"\n[builtins fixtures/paramspec.pyi]\n\n[case testConstraintsBetweenConcatenatePrefixes]\nfrom typing import Any, Callable, Generic, TypeVar\nfrom typing_extensions import Concatenate, ParamSpec\n\n_P = ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\n\nclass Awaitable(Generic[_T]): ...\n\ndef adds_await() -> Callable[\n    [Callable[Concatenate[_T, _P], None]],\n    Callable[Concatenate[_T, _P], Awaitable[None]],\n]:\n    def decorator(\n        func: Callable[Concatenate[_T, _P], None],\n    ) -> Callable[Concatenate[_T, _P], Awaitable[None]]:\n        ...\n\n    return decorator  # we want `_T` and `_P` to refer to the same things.\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecVariance]\nfrom typing import Callable, Generic\nfrom typing_extensions import ParamSpec\n\n_P = ParamSpec(\"_P\")\n\nclass Job(Generic[_P]):\n    def __init__(self, target: Callable[_P, None]) -> None: ...\n    def into_callable(self) -> Callable[_P, None]: ...\n\nclass A:\n    def func(self, var: int) -> None: ...\n    def other_func(self, job: Job[[int]]) -> None: ...\n\n\njob = Job(A().func)\nreveal_type(job)  # N: Revealed type is \"__main__.Job[[var: builtins.int]]\"\nA().other_func(job)  # This should NOT error (despite the keyword)\n\n# and yet the keyword should remain\njob.into_callable()(var=42)\njob.into_callable()(x=42)  # E: Unexpected keyword argument \"x\"\n\n# similar for other functions\ndef f1(n: object) -> None: ...\ndef f2(n: int) -> None: ...\ndef f3(n: bool) -> None: ...\n\n# just like how this is legal...\na1: Callable[[bool], None]\na1 = f3\na1 = f2\na1 = f1\n\n# ... this is also legal\na2: Job[[bool]]\na2 = Job(f3)\na2 = Job(f2)\na2 = Job(f1)\n\n# and this is not legal\ndef f4(n: bytes) -> None: ...\na1 = f4  # E: Incompatible types in assignment (expression has type \"Callable[[bytes], None]\", variable has type \"Callable[[bool], None]\")\na2 = Job(f4)  # E: Argument 1 to \"Job\" has incompatible type \"Callable[[bytes], None]\"; expected \"Callable[[bool], None]\"\n\n# nor is this:\na4: Job[[int]]\na4 = Job(f3)  # E: Argument 1 to \"Job\" has incompatible type \"Callable[[bool], None]\"; expected \"Callable[[int], None]\"\na4 = Job(f2)\na4 = Job(f1)\n\n# just like this:\na3: Callable[[int], None]\na3 = f3  # E: Incompatible types in assignment (expression has type \"Callable[[bool], None]\", variable has type \"Callable[[int], None]\")\na3 = f2\na3 = f1\n[builtins fixtures/paramspec.pyi]\n\n[case testDecoratingClassesThatUseParamSpec]\nfrom typing import Generic, TypeVar, Callable, Any\nfrom typing_extensions import ParamSpec\n\n_P = ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\n_F = TypeVar(\"_F\", bound=Callable[..., Any])\n\ndef f(x: _F) -> _F: ...\n\n@f  # Should be ok\nclass OnlyParamSpec(Generic[_P]):\n    pass\n\n@f  # Should be ok\nclass MixedWithTypeVar1(Generic[_P, _T]):\n    pass\n\n@f  # Should be ok\nclass MixedWithTypeVar2(Generic[_T, _P]):\n    pass\n[builtins fixtures/dict.pyi]\n\n[case testGenericsInInferredParamspec]\nfrom typing import Callable, TypeVar, Generic\nfrom typing_extensions import ParamSpec\n\n_P = ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\n\nclass Job(Generic[_P]):\n    def __init__(self, target: Callable[_P, None]) -> None: ...\n    def into_callable(self) -> Callable[_P, None]: ...\n\ndef generic_f(x: _T) -> None: ...\n\nj = Job(generic_f)\nreveal_type(j)  # N: Revealed type is \"__main__.Job[[x: _T`-1]]\"\n\njf = j.into_callable()\nreveal_type(jf)  # N: Revealed type is \"def [_T] (x: _T`4)\"\nreveal_type(jf(1))  # N: Revealed type is \"None\"\n[builtins fixtures/paramspec.pyi]\n\n[case testGenericsInInferredParamspecReturn]\nfrom typing import Callable, TypeVar, Generic\nfrom typing_extensions import ParamSpec\n\n_P = ParamSpec(\"_P\")\n_T = TypeVar(\"_T\")\n\nclass Job(Generic[_P, _T]):\n    def __init__(self, target: Callable[_P, _T]) -> None: ...\n    def into_callable(self) -> Callable[_P, _T]: ...\n\ndef generic_f(x: _T) -> _T: ...\n\nj = Job(generic_f)\nreveal_type(j)  # N: Revealed type is \"__main__.Job[[x: _T`3], _T`3]\"\n\njf = j.into_callable()\nreveal_type(jf)  # N: Revealed type is \"def [_T] (x: _T`4) -> _T`4\"\nreveal_type(jf(1))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/paramspec.pyi]\n\n[case testStackedConcatenateIsIllegal]\nfrom typing_extensions import Concatenate, ParamSpec\nfrom typing import Callable\n\nP = ParamSpec(\"P\")\n\ndef x(f: Callable[Concatenate[int, Concatenate[int, P]], None]) -> None: ...  # E: Nested Concatenates are invalid\n[builtins fixtures/paramspec.pyi]\n\n[case testPropagatedAnyConstraintsAreOK]\nfrom typing import Any, Callable, Generic, TypeVar\nfrom typing_extensions import ParamSpec\n\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\n\ndef callback(func: Callable[[Any], Any]) -> None: ...\nclass Job(Generic[P]): ...\n\n@callback\ndef run_job(job: Job[...]) -> T: ... # E: A function returning TypeVar should receive at least one argument containing the same TypeVar\n[builtins fixtures/tuple.pyi]\n\n[case testTupleAndDictOperationsOnParamSpecArgsAndKwargs]\nfrom typing import Callable, Iterator, Iterable, TypeVar, Tuple\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\nT = TypeVar('T')\ndef enumerate(x: Iterable[T]) -> Iterator[Tuple[int, T]]: ...\n\ndef func(callback: Callable[P, str]) -> Callable[P, str]:\n    def inner(*args: P.args, **kwargs: P.kwargs) -> str:\n        reveal_type(args[5])  # N: Revealed type is \"builtins.object\"\n        for a in args:\n            reveal_type(a)  # N: Revealed type is \"builtins.object\"\n        for idx, a in enumerate(args):\n            reveal_type(idx)  # N: Revealed type is \"builtins.int\"\n            reveal_type(a)  # N: Revealed type is \"builtins.object\"\n        b = 'foo' in args\n        reveal_type(b)  # N: Revealed type is \"builtins.bool\"\n        reveal_type(args.count(42))  # N: Revealed type is \"builtins.int\"\n        reveal_type(len(args))  # N: Revealed type is \"builtins.int\"\n        for c, d in kwargs.items():\n            reveal_type(c)  # N: Revealed type is \"builtins.str\"\n            reveal_type(d)  # N: Revealed type is \"builtins.object\"\n        kwargs.pop('bar')\n        return 'baz'\n    return inner\n[builtins fixtures/paramspec.pyi]\n\n[case testUnpackingParamsSpecArgsAndKwargs]\nfrom typing import Callable\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\n\ndef func(callback: Callable[P, str]) -> Callable[P, str]:\n    def inner(*args: P.args, **kwargs: P.kwargs) -> str:\n        a, *b = args\n        reveal_type(a)  # N: Revealed type is \"builtins.object\"\n        reveal_type(b)  # N: Revealed type is \"builtins.list[builtins.object]\"\n        c, *d = kwargs\n        reveal_type(c)  # N: Revealed type is \"builtins.str\"\n        reveal_type(d)  # N: Revealed type is \"builtins.list[builtins.str]\"\n        e = {**kwargs}\n        reveal_type(e)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\n        return \"foo\"\n    return inner\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecArgsAndKwargsMismatch]\nfrom typing import Callable\nfrom typing_extensions import ParamSpec\n\nP1 = ParamSpec(\"P1\")\n\ndef func(callback: Callable[P1, str]) -> Callable[P1, str]:\n    def inner(\n        *args: P1.kwargs,   # E: Use \"P1.args\" for variadic \"*\" parameter\n        **kwargs: P1.args,  # E: Use \"P1.kwargs\" for variadic \"**\" parameter\n    ) -> str:\n        return \"foo\"\n    return inner\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecTestPropAccess]\nfrom typing import Callable\nfrom typing_extensions import ParamSpec\n\nP1 = ParamSpec(\"P1\")\n\ndef func1(callback: Callable[P1, str]) -> Callable[P1, str]:\n    def inner(\n        *args: P1.typo,  # E: Use \"P1.args\" for variadic \"*\" parameter \\\n                         # E: Name \"P1.typo\" is not defined\n        **kwargs: P1.kwargs,\n    ) -> str:\n        return \"foo\"\n    return inner\n\ndef func2(callback: Callable[P1, str]) -> Callable[P1, str]:\n    def inner(\n        *args: P1.args,\n        **kwargs: P1.__bound__,  # E: Use \"P1.kwargs\" for variadic \"**\" parameter \\\n                                 # E: Name \"P1.__bound__\" is not defined\n    ) -> str:\n        return \"foo\"\n    return inner\n\ndef func3(callback: Callable[P1, str]) -> Callable[P1, str]:\n    def inner(\n        *args: P1.__bound__,   # E: Use \"P1.args\" for variadic \"*\" parameter \\\n                               # E: Name \"P1.__bound__\" is not defined\n        **kwargs: P1.invalid,  # E: Use \"P1.kwargs\" for variadic \"**\" parameter \\\n                               # E: Name \"P1.invalid\" is not defined\n    ) -> str:\n        return \"foo\"\n    return inner\n[builtins fixtures/paramspec.pyi]\n\n\n[case testInvalidParamSpecDefinitionsWithArgsKwargs]\nfrom typing import Callable, ParamSpec\n\nP = ParamSpec('P')\n\ndef c1(f: Callable[P, int], *args: P.args, **kwargs: P.kwargs) -> int: ...\ndef c2(f: Callable[P, int]) -> int: ...\ndef c3(f: Callable[P, int], *args, **kwargs) -> int: ...\n\n# It is ok to define,\ndef c4(f: Callable[P, int], *args: int, **kwargs: str) -> int:\n    # but not ok to call:\n    f(*args, **kwargs)  # E: Argument 1 has incompatible type \"*tuple[int, ...]\"; expected \"P.args\" \\\n                        # E: Argument 2 has incompatible type \"**dict[str, str]\"; expected \"P.kwargs\"\n    return 1\n\ndef f1(f: Callable[P, int], *args, **kwargs: P.kwargs) -> int: ...  # E: ParamSpec must have \"*args\" typed as \"P.args\" and \"**kwargs\" typed as \"P.kwargs\"\ndef f2(f: Callable[P, int], *args: P.args, **kwargs) -> int: ...  # E: ParamSpec must have \"*args\" typed as \"P.args\" and \"**kwargs\" typed as \"P.kwargs\"\ndef f3(f: Callable[P, int], *args: P.args) -> int: ...  # E: ParamSpec must have \"*args\" typed as \"P.args\" and \"**kwargs\" typed as \"P.kwargs\"\ndef f4(f: Callable[P, int], **kwargs: P.kwargs) -> int: ...  # E: ParamSpec must have \"*args\" typed as \"P.args\" and \"**kwargs\" typed as \"P.kwargs\"\ndef f5(f: Callable[P, int], *args: P.args, extra_keyword_arg: int, **kwargs: P.kwargs) -> int: ...  # E: Arguments not allowed after ParamSpec.args\n\n# Error message test:\nP1 = ParamSpec('P1')\n\ndef m1(f: Callable[P1, int], *a, **k: P1.kwargs) -> int: ...  # E: ParamSpec must have \"*args\" typed as \"P1.args\" and \"**kwargs\" typed as \"P1.kwargs\"\n[builtins fixtures/paramspec.pyi]\n\n\n[case testInvalidParamSpecAndConcatenateDefinitionsWithArgsKwargs]\nfrom typing import Callable, ParamSpec\nfrom typing_extensions import Concatenate\n\nP = ParamSpec('P')\n\ndef c1(f: Callable[Concatenate[int, P], int], *args: P.args, **kwargs: P.kwargs) -> int: ...\ndef c2(f: Callable[Concatenate[int, P], int]) -> int: ...\ndef c3(f: Callable[Concatenate[int, P], int], *args, **kwargs) -> int: ...\n\n# It is ok to define,\ndef c4(f: Callable[Concatenate[int, P], int], *args: int, **kwargs: str) -> int:\n    # but not ok to call:\n    f(1, *args, **kwargs)  # E: Argument 2 has incompatible type \"*tuple[int, ...]\"; expected \"P.args\" \\\n                           # E: Argument 3 has incompatible type \"**dict[str, str]\"; expected \"P.kwargs\"\n    return 1\n\ndef f1(f: Callable[Concatenate[int, P], int], *args, **kwargs: P.kwargs) -> int: ...  # E: ParamSpec must have \"*args\" typed as \"P.args\" and \"**kwargs\" typed as \"P.kwargs\"\ndef f2(f: Callable[Concatenate[int, P], int], *args: P.args, **kwargs) -> int: ...  # E: ParamSpec must have \"*args\" typed as \"P.args\" and \"**kwargs\" typed as \"P.kwargs\"\ndef f3(f: Callable[Concatenate[int, P], int], *args: P.args) -> int: ...  # E: ParamSpec must have \"*args\" typed as \"P.args\" and \"**kwargs\" typed as \"P.kwargs\"\ndef f4(f: Callable[Concatenate[int, P], int], **kwargs: P.kwargs) -> int: ...  # E: ParamSpec must have \"*args\" typed as \"P.args\" and \"**kwargs\" typed as \"P.kwargs\"\ndef f5(f: Callable[Concatenate[int, P], int], *args: P.args, extra_keyword_arg: int, **kwargs: P.kwargs) -> int: ...  # E: Arguments not allowed after ParamSpec.args\n[builtins fixtures/paramspec.pyi]\n\n\n[case testValidParamSpecInsideGenericWithoutArgsAndKwargs]\nfrom typing import Callable, ParamSpec, Generic\nfrom typing_extensions import Concatenate\n\nP = ParamSpec('P')\n\nclass Some(Generic[P]): ...\n\ndef create(s: Some[P], *args: int): ...\ndef update(s: Some[P], **kwargs: int): ...\ndef delete(s: Some[P]): ...\n\ndef from_callable1(c: Callable[P, int], *args: int, **kwargs: int) -> Some[P]: ...\ndef from_callable2(c: Callable[P, int], **kwargs: int) -> Some[P]: ...\ndef from_callable3(c: Callable[P, int], *args: int) -> Some[P]: ...\n\ndef from_extra1(c: Callable[Concatenate[int, P], int], *args: int, **kwargs: int) -> Some[P]: ...\ndef from_extra2(c: Callable[Concatenate[int, P], int], **kwargs: int) -> Some[P]: ...\ndef from_extra3(c: Callable[Concatenate[int, P], int], *args: int) -> Some[P]: ...\n[builtins fixtures/paramspec.pyi]\n\n\n[case testUnboundParamSpec]\nfrom typing import Callable, ParamSpec\n\nP1 = ParamSpec('P1')\nP2 = ParamSpec('P2')\n\ndef f0(f: Callable[P1, int], *args: P1.args, **kwargs: P2.kwargs): ...  # E: ParamSpec must have \"*args\" typed as \"P1.args\" and \"**kwargs\" typed as \"P1.kwargs\" \\\n                                                                        # E: ParamSpec \"P2\" is unbound\n\ndef f1(*args: P1.args): ...  # E: ParamSpec \"P1\" is unbound\ndef f2(**kwargs: P1.kwargs): ...  # E: ParamSpec \"P1\" is unbound\ndef f3(*args: P1.args, **kwargs: int): ...  # E: ParamSpec \"P1\" is unbound\ndef f4(*args: int, **kwargs: P1.kwargs): ...  # E: ParamSpec \"P1\" is unbound\n\n# Error message is based on the `args` definition:\ndef f5(*args: P2.args, **kwargs: P1.kwargs): ...  # E: ParamSpec \"P2\" is unbound \\\n                                                  # E: ParamSpec \"P1\" is unbound\ndef f6(*args: P1.args, **kwargs: P2.kwargs): ...  # E: ParamSpec \"P1\" is unbound \\\n                                                  # E: ParamSpec \"P2\" is unbound\n\n# Multiple `ParamSpec` variables can be found, they should not affect error message:\nP3 = ParamSpec('P3')\n\ndef f7(first: Callable[P3, int], *args: P1.args, **kwargs: P2.kwargs): ...  # E: ParamSpec \"P1\" is unbound \\\n                                                                            # E: ParamSpec \"P2\" is unbound\ndef f8(first: Callable[P3, int], *args: P2.args, **kwargs: P1.kwargs): ...  # E: ParamSpec \"P2\" is unbound \\\n                                                                            # E: ParamSpec \"P1\" is unbound\n\n[builtins fixtures/paramspec.pyi]\n\n\n[case testArgsKwargsWithoutParamSpecVar]\nfrom typing import Generic, Callable, ParamSpec\n\nP = ParamSpec('P')\n\n# This must be allowed:\nclass Some(Generic[P]):\n    def call(self, *args: P.args, **kwargs: P.kwargs): ...\n\ndef call(*args: P.args, **kwargs: P.kwargs): ...  # E: ParamSpec \"P\" is unbound\n\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecInferenceCrash]\nfrom typing import Callable, Generic, ParamSpec, TypeVar\n\ndef foo(x: int) -> int: ...\nT = TypeVar(\"T\")\ndef bar(x: T) -> T: ...\n\nP = ParamSpec(\"P\")\n\nclass C(Generic[P]):\n    def __init__(self, fn: Callable[P, int], *args: P.args, **kwargs: P.kwargs): ...\n\nreveal_type(bar(C(fn=foo, x=1)))  # N: Revealed type is \"__main__.C[[x: builtins.int]]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecClassConstructor]\nfrom typing import ParamSpec, Callable, TypeVar\n\nP = ParamSpec(\"P\")\n\nclass SomeClass:\n    def __init__(self, a: str) -> None:\n        pass\n\ndef func(t: Callable[P, SomeClass], val: Callable[P, SomeClass]) -> Callable[P, SomeClass]:\n    pass\n\ndef func_regular(t: Callable[[T], SomeClass], val: Callable[[T], SomeClass]) -> Callable[[T], SomeClass]:\n    pass\n\ndef constructor(a: str) -> SomeClass:\n    return SomeClass(a)\n\ndef wrong_constructor(a: bool) -> SomeClass:\n    return SomeClass(\"a\")\n\ndef wrong_name_constructor(b: bool) -> SomeClass:\n    return SomeClass(\"a\")\n\nfunc(SomeClass, constructor)\nreveal_type(func(SomeClass, wrong_constructor))  # N: Revealed type is \"def (a: Never) -> __main__.SomeClass\"\nreveal_type(func_regular(SomeClass, wrong_constructor))  # N: Revealed type is \"def (Never) -> __main__.SomeClass\"\nreveal_type(func(SomeClass, wrong_name_constructor))  # N: Revealed type is \"def (Never) -> __main__.SomeClass\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecInTypeAliasBasic]\nfrom typing import ParamSpec, Callable\n\nP = ParamSpec(\"P\")\nC = Callable[P, int]\ndef f(n: C[P]) -> C[P]: ...\n\n@f\ndef bar(x: int) -> int: ...\n@f    # E: Argument 1 to \"f\" has incompatible type \"Callable[[int], str]\"; expected \"Callable[[int], int]\"\ndef foo(x: int) -> str: ...\n\nx: C[[int, str]]\nreveal_type(x)  # N: Revealed type is \"def (builtins.int, builtins.str) -> builtins.int\"\ny: C[int, str]\nreveal_type(y)  # N: Revealed type is \"def (builtins.int, builtins.str) -> builtins.int\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecInTypeAliasConcatenate]\nfrom typing import ParamSpec, Callable\nfrom typing_extensions import Concatenate\n\nP = ParamSpec(\"P\")\nC = Callable[Concatenate[int, P], int]\ndef f(n: C[P]) -> C[P]: ...\n\n@f  # E: Argument 1 to \"f\" has incompatible type \"Callable[[], int]\"; expected \"Callable[[int], int]\"\ndef bad() -> int: ...\n\n@f\ndef bar(x: int) -> int: ...\n\n@f\ndef bar2(x: int, y: str) -> int: ...\nreveal_type(bar2)  # N: Revealed type is \"def (builtins.int, y: builtins.str) -> builtins.int\"\n\n@f  # E: Argument 1 to \"f\" has incompatible type \"Callable[[int], str]\"; expected \"Callable[[int], int]\" \\\n    # N: This is likely because \"foo\" has named arguments: \"x\". Consider marking them positional-only\ndef foo(x: int) -> str: ...\n\n@f  # E: Argument 1 to \"f\" has incompatible type \"Callable[[str, int], int]\"; expected \"Callable[[int, int], int]\" \\\n    # N: This is likely because \"foo2\" has named arguments: \"x\". Consider marking them positional-only\ndef foo2(x: str, y: int) -> int: ...\n\nx: C[[int, str]]\nreveal_type(x)  # N: Revealed type is \"def (builtins.int, builtins.int, builtins.str) -> builtins.int\"\ny: C[int, str]\nreveal_type(y)  # N: Revealed type is \"def (builtins.int, builtins.int, builtins.str) -> builtins.int\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecInTypeAliasIllegalBare]\nfrom typing import ParamSpec\nfrom typing_extensions import Concatenate, TypeAlias\n\nP = ParamSpec(\"P\")\nBad1: TypeAlias = P                     # E: Invalid location for ParamSpec \"P\" \\\n                                        # N: You can use ParamSpec as the first argument to Callable, e.g., \"Callable[P, int]\"\nBad2: TypeAlias = Concatenate[int, P]   # E: Invalid location for Concatenate \\\n                                        # N: You can use Concatenate as the first argument to Callable\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecInTypeAliasRecursive]\nfrom typing import ParamSpec, Callable, Union\n\nP = ParamSpec(\"P\")\nC = Callable[P, Union[int, C[P]]]\ndef f(n: C[P]) -> C[P]: ...\n\n@f\ndef bar(x: int) -> int: ...\n\n@f\ndef bar2(__x: int) -> Callable[[int], int]: ...\n\n@f  # E: Argument 1 to \"f\" has incompatible type \"Callable[[int], str]\"; expected \"C[[int]]\"\ndef foo(x: int) -> str: ...\n\n@f  # E: Argument 1 to \"f\" has incompatible type \"Callable[[int], Callable[[int], str]]\"; expected \"C[[int]]\"\ndef foo2(__x: int) -> Callable[[int], str]: ...\n\nx: C[[int, str]]\nreveal_type(x)  # N: Revealed type is \"def (builtins.int, builtins.str) -> builtins.int | (...)\"\ny: C[int, str]\nreveal_type(y)  # N: Revealed type is \"def (builtins.int, builtins.str) -> builtins.int | (...)\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecAliasInRuntimeContext]\nfrom typing import ParamSpec, Generic\n\nP = ParamSpec(\"P\")\nclass C(Generic[P]): ...\n\nc = C[int, str]()\nreveal_type(c)  # N: Revealed type is \"__main__.C[[builtins.int, builtins.str]]\"\n\nA = C[P]\na = A[int, str]()\nreveal_type(a)  # N: Revealed type is \"__main__.C[[builtins.int, builtins.str]]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecAliasInvalidLocations]\nfrom typing import ParamSpec, Generic, List, TypeVar, Callable\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nA = List[T]\ndef f(x: A[[int, str]]) -> None: ...  # E: Bracketed expression \"[...]\" is not valid as a type\ndef g(x: A[P]) -> None: ...  # E: Invalid location for ParamSpec \"P\" \\\n                             # N: You can use ParamSpec as the first argument to Callable, e.g., \"Callable[P, int]\"\n\nC = Callable[P, T]\nx: C[int]  # E: Bad number of arguments for type alias, expected 2, given 1\ny: C[int, str]  # E: Can only replace ParamSpec with a parameter types list or another ParamSpec, got \"int\"\nz: C[int, str, bytes]  # E: Bad number of arguments for type alias, expected 2, given 3\n\n[builtins fixtures/paramspec.pyi]\n\n[case testTrivialParametersHandledCorrectly]\nfrom typing import ParamSpec, Generic, TypeVar, Callable, Any\nfrom typing_extensions import Concatenate\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\nclass C(Generic[S, P, T]): ...\n\ndef foo(f: Callable[P, int]) -> None:\n    x: C[Any, ..., Any]\n    x1: C[int, Concatenate[int, str, P], str]\n    x = x1  # OK\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecAliasNested]\nfrom typing import ParamSpec, Callable, List, TypeVar, Generic\nfrom typing_extensions import Concatenate\n\nP = ParamSpec(\"P\")\nA = List[Callable[P, None]]\nB = List[Callable[Concatenate[int, P], None]]\n\nfs: A[int, str]\nreveal_type(fs)  # N: Revealed type is \"builtins.list[def (builtins.int, builtins.str)]\"\ngs: B[int, str]\nreveal_type(gs)  # N: Revealed type is \"builtins.list[def (builtins.int, builtins.int, builtins.str)]\"\n\nT = TypeVar(\"T\")\nclass C(Generic[T]): ...\nC[Callable[P, int]]()\n[builtins fixtures/paramspec.pyi]\n\n[case testConcatDeferralNoCrash]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import Concatenate, ParamSpec\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\", bound=\"Defer\")\n\nAlias = Callable[P, bool]\nConcat = Alias[Concatenate[T, P]]\n\ndef test(f: Concat[T, ...]) -> None: ...\n\nclass Defer: ...\n[builtins fixtures/paramspec.pyi]\n\n[case testNoParamSpecDoubling]\n# https://github.com/python/mypy/issues/12734\nfrom typing import Callable, ParamSpec\nfrom typing_extensions import Concatenate\n\nP = ParamSpec(\"P\")\nQ = ParamSpec(\"Q\")\n\ndef foo(f: Callable[P, int]) -> Callable[P, int]:\n    return f\n\ndef bar(f: Callable[Concatenate[str, Q], int]) -> Callable[Concatenate[str, Q], int]:\n    return foo(f)\n[builtins fixtures/paramspec.pyi]\n\n[case testAlreadyExpandedCallableWithParamSpecReplacement]\nfrom typing import Callable, Any, overload\nfrom typing_extensions import Concatenate, ParamSpec\n\nP = ParamSpec(\"P\")\n\n@overload\ndef command() -> Callable[[Callable[Concatenate[object, object, P], object]], None]:\n    ...\n\n@overload\ndef command(\n    cls: int = ...,\n) -> Callable[[Callable[Concatenate[object, P], object]], None]:\n    ...\n\ndef command(\n    cls: int = 42,\n) -> Any:\n    ...\n[builtins fixtures/paramspec.pyi]\n\n[case testCopiedParamSpecComparison]\n# minimized from https://github.com/python/mypy/issues/12909\nfrom typing import Callable\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\n\ndef identity(func: Callable[P, None]) -> Callable[P, None]: ...\n\n@identity\ndef f(f: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecDecoratorAppliedToGeneric]\nfrom typing import Callable, List, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\n\ndef dec(f: Callable[P, T]) -> Callable[P, List[T]]: ...\ndef test(x: U) -> U: ...\nreveal_type(dec)  # N: Revealed type is \"def [P, T] (f: def (*P.args, **P.kwargs) -> T`-2) -> def (*P.args, **P.kwargs) -> builtins.list[T`-2]\"\nreveal_type(dec(test))  # N: Revealed type is \"def [T] (x: T`3) -> builtins.list[T`3]\"\n\nclass A: ...\nTA = TypeVar(\"TA\", bound=A)\n\ndef test_with_bound(x: TA) -> TA: ...\nreveal_type(dec(test_with_bound))  # N: Revealed type is \"def [T <: __main__.A] (x: T`5) -> builtins.list[T`5]\"\ndec(test_with_bound)(0)  # E: Value of type variable \"T\" of function cannot be \"int\"\ndec(test_with_bound)(A())  # OK\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecArgumentParamInferenceRegular]\nfrom typing import TypeVar, Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nclass Foo(Generic[P]):\n    def call(self, *args: P.args, **kwargs: P.kwargs) -> None: ...\ndef test(*args: P.args, **kwargs: P.kwargs) -> Foo[P]: ...\n\nreveal_type(test(1, 2))  # N: Revealed type is \"__main__.Foo[[Literal[1]?, Literal[2]?]]\"\nreveal_type(test(x=1, y=2))  # N: Revealed type is \"__main__.Foo[[x: Literal[1]?, y: Literal[2]?]]\"\nints = [1, 2, 3]\nreveal_type(test(*ints))  # N: Revealed type is \"__main__.Foo[[*builtins.int]]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecArgumentParamInferenceGeneric]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\ndef call(f: Callable[P, R], *args: P.args, **kwargs: P.kwargs) -> R:\n    return f(*args, **kwargs)\n\nT = TypeVar(\"T\")\ndef identity(x: T) -> T:\n    return x\n\nreveal_type(call(identity, 2))  # N: Revealed type is \"builtins.int\"\ny: int = call(identity, 2)\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecNestedApplyNoCrash]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\ndef apply(fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T: ...\ndef test() -> int: ...\nreveal_type(apply(apply, test))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecNestedApplyPosVsNamed]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\ndef apply(fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> None: ...\n\ndef test(x: int) -> int: ...\napply(apply, test, x=42)  # OK\napply(apply, test, 42)  # Also OK (but requires some special casing)\napply(apply, test, \"bad\")  # E: Argument 1 to \"apply\" has incompatible type \"Callable[[Callable[P, T], **P], None]\"; expected \"Callable[[Callable[[int], int], str], None]\"\n\ndef test2(x: int, y: str) -> None: ...\napply(apply, test2, 42, \"yes\")\napply(apply, test2, \"no\", 42)  # E: Argument 1 to \"apply\" has incompatible type \"Callable[[Callable[P, T], **P], None]\"; expected \"Callable[[Callable[[int, str], None], str, int], None]\"\napply(apply, test2, x=42, y=\"yes\")\napply(apply, test2, y=\"yes\", x=42)\napply(apply, test2, y=42, x=\"no\")  # E: Argument 1 to \"apply\" has incompatible type \"Callable[[Callable[P, T], **P], None]\"; expected \"Callable[[Callable[[int, str], None], int, str], None]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecApplyPosVsNamedOptional]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\ndef apply(fn: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> None: ...\ndef test(x: str = ..., y: int = ...) -> int: ...\napply(test, y=42)  # OK\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecPrefixSubtypingGenericInvalid]\nfrom typing import Generic\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\n\nclass A(Generic[P]):\n    def foo(self, *args: P.args, **kwargs: P.kwargs):\n        ...\n\ndef bar(b: A[P]) -> A[Concatenate[int, P]]:\n    return b  # E: Incompatible return value type (got \"A[P]\", expected \"A[[int, **P]]\")\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecPrefixSubtypingProtocolInvalid]\nfrom typing import Protocol\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\n\nclass A(Protocol[P]):\n    def foo(self, *args: P.args, **kwargs: P.kwargs):\n        ...\n\ndef bar(b: A[P]) -> A[Concatenate[int, P]]:\n    return b  # E: Incompatible return value type (got \"A[P]\", expected \"A[[int, **P]]\") \\\n              # N: Following member(s) of \"A[P]\" have conflicts: \\\n              # N:     Expected: \\\n              # N:         def foo(self, int, /, *args: P.args, **kwargs: P.kwargs) -> Any \\\n              # N:     Got: \\\n              # N:         def foo(self, *args: P.args, **kwargs: P.kwargs) -> Any\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecPrefixSubtypingValidNonStrict]\nfrom typing import Protocol\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\n\nclass A(Protocol[P]):\n    def foo(self, a: int, *args: P.args, **kwargs: P.kwargs):\n        ...\n\nclass B(Protocol[P]):\n    def foo(self, a: int, b: int, *args: P.args, **kwargs: P.kwargs):\n        ...\n\ndef bar(b: B[P]) -> A[Concatenate[int, P]]:\n    return b\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecPrefixSubtypingInvalidStrict]\n# flags: --extra-checks\nfrom typing import Protocol\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\n\nclass A(Protocol[P]):\n    def foo(self, a: int, *args: P.args, **kwargs: P.kwargs):\n        ...\n\nclass B(Protocol[P]):\n    def foo(self, a: int, b: int, *args: P.args, **kwargs: P.kwargs):\n        ...\n\ndef bar(b: B[P]) -> A[Concatenate[int, P]]:\n    return b  # E: Incompatible return value type (got \"B[P]\", expected \"A[[int, **P]]\") \\\n              # N: Following member(s) of \"B[P]\" have conflicts: \\\n              # N:     Expected: \\\n              # N:         def foo(self, a: int, int, /, *args: P.args, **kwargs: P.kwargs) -> Any \\\n              # N:     Got: \\\n              # N:         def foo(self, a: int, b: int, *args: P.args, **kwargs: P.kwargs) -> Any\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecDecoratorOverload]\nfrom typing import Callable, overload, TypeVar, List\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\ndef transform(func: Callable[P, List[T]]) -> Callable[P, T]: ...\n\n@overload\ndef foo(x: int) -> List[float]: ...\n@overload\ndef foo(x: str) -> List[str]: ...\ndef foo(x): ...\n\nreveal_type(transform(foo))  # N: Revealed type is \"Overload(def (x: builtins.int) -> builtins.float, def (x: builtins.str) -> builtins.str)\"\n\n@transform\n@overload\ndef bar(x: int) -> List[float]: ...\n@transform\n@overload\ndef bar(x: str) -> List[str]: ...\n@transform\ndef bar(x): ...\n\nreveal_type(bar)  # N: Revealed type is \"Overload(def (x: builtins.int) -> builtins.float, def (x: builtins.str) -> builtins.str)\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecDecoratorOverloadNoCrashOnInvalidTypeVar]\nfrom typing import Any, Callable, List\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nT = 1\n\nAlias = Callable[P, List[T]]  # type: ignore\ndef dec(fn: Callable[P, T]) -> Alias[P, T]: ...  # type: ignore\nf: Any\ndec(f)  # No crash\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecErrorNestedParams]\nfrom typing import Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nclass C(Generic[P]): ...\nc: C[int, [int, str], str]  # E: Nested parameter specifications are not allowed\nreveal_type(c)  # N: Revealed type is \"__main__.C[Any]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecInheritNoCrashOnNested]\nfrom typing import Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nclass C(Generic[P]): ...\nclass D(C[int, [int, str], str]): ... # E: Nested parameter specifications are not allowed\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecConcatenateSelfType]\nfrom typing import Callable\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\nclass A:\n    def __init__(self, a_param_1: str) -> None: ...\n\n    @classmethod\n    def add_params(cls: Callable[P, A]) -> Callable[Concatenate[float, P], A]:\n        def new_constructor(i: float, *args: P.args, **kwargs: P.kwargs) -> A:\n            return cls(*args, **kwargs)\n        return new_constructor\n\n    @classmethod\n    def remove_params(cls: Callable[Concatenate[str, P], A]) -> Callable[P, A]:\n        def new_constructor(*args: P.args, **kwargs: P.kwargs) -> A:\n            return cls(\"my_special_str\", *args, **kwargs)\n        return new_constructor\n\nreveal_type(A.add_params())  # N: Revealed type is \"def (builtins.float, a_param_1: builtins.str) -> __main__.A\"\nreveal_type(A.remove_params())  # N: Revealed type is \"def () -> __main__.A\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecConcatenateCallbackProtocol]\nfrom typing import Protocol, TypeVar\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\", covariant=True)\n\nclass Path: ...\n\nclass Function(Protocol[P, R]):\n    def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R: ...\n\ndef file_cache(fn: Function[Concatenate[Path, P], R]) -> Function[P, R]:\n    def wrapper(*args: P.args, **kw: P.kwargs) -> R:\n        return fn(Path(), *args, **kw)\n    return wrapper\n\n@file_cache\ndef get_thing(path: Path, *, some_arg: int) -> int: ...\nreveal_type(get_thing)  # N: Revealed type is \"__main__.Function[[*, some_arg: builtins.int], builtins.int]\"\nget_thing(some_arg=1)  # OK\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecConcatenateKeywordOnly]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nclass Path: ...\n\ndef file_cache(fn: Callable[Concatenate[Path, P], R]) -> Callable[P, R]:\n    def wrapper(*args: P.args, **kw: P.kwargs) -> R:\n        return fn(Path(), *args, **kw)\n    return wrapper\n\n@file_cache\ndef get_thing(path: Path, *, some_arg: int) -> int: ...\nreveal_type(get_thing)  # N: Revealed type is \"def (*, some_arg: builtins.int) -> builtins.int\"\nget_thing(some_arg=1)  # OK\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecConcatenateCallbackApply]\nfrom typing import Callable, Protocol\nfrom typing_extensions import ParamSpec, Concatenate\n\nP = ParamSpec(\"P\")\n\nclass FuncType(Protocol[P]):\n    def __call__(self, x: int, s: str, *args: P.args, **kw_args: P.kwargs) -> str: ...\n\ndef forwarder1(fp: FuncType[P], *args: P.args, **kw_args: P.kwargs) -> str:\n    return fp(0, '', *args, **kw_args)\n\ndef forwarder2(fp: Callable[Concatenate[int, str, P], str], *args: P.args, **kw_args: P.kwargs) -> str:\n    return fp(0, '', *args, **kw_args)\n\ndef my_f(x: int, s: str, d: bool) -> str: ...\nforwarder1(my_f, True)  # OK\nforwarder2(my_f, True)  # OK\nforwarder1(my_f, 1.0)  # E: Argument 2 to \"forwarder1\" has incompatible type \"float\"; expected \"bool\"\nforwarder2(my_f, 1.0)  # E: Argument 2 to \"forwarder2\" has incompatible type \"float\"; expected \"bool\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecCallbackProtocolSelf]\nfrom typing import Callable, Protocol, TypeVar\nfrom typing_extensions import ParamSpec, Concatenate\n\nParams = ParamSpec(\"Params\")\nResult = TypeVar(\"Result\", covariant=True)\n\nclass FancyMethod(Protocol):\n    def __call__(self, arg1: int, arg2: str) -> bool: ...\n    def return_me(self: Callable[Params, Result]) -> Callable[Params, Result]: ...\n    def return_part(self: Callable[Concatenate[int, Params], Result]) -> Callable[Params, Result]: ...\n\nm: FancyMethod\nreveal_type(m.return_me())  # N: Revealed type is \"def (arg1: builtins.int, arg2: builtins.str) -> builtins.bool\"\nreveal_type(m.return_part())  # N: Revealed type is \"def (arg2: builtins.str) -> builtins.bool\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecInferenceCallableAgainstAny]\nfrom typing import Callable, TypeVar, Any\nfrom typing_extensions import ParamSpec, Concatenate\n\n_P = ParamSpec(\"_P\")\n_R = TypeVar(\"_R\")\n\nclass A: ...\na = A()\n\ndef a_func(\n    func: Callable[Concatenate[A, _P], _R],\n) -> Callable[Concatenate[Any, _P], _R]:\n    def wrapper(__a: Any, *args: _P.args, **kwargs: _P.kwargs) -> _R:\n        return func(a, *args, **kwargs)\n    return wrapper\n\ndef test(a, *args): ...\nx: Any\ny: object\n\na_func(test)\nx = a_func(test)\ny = a_func(test)\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecInferenceWithCallbackProtocol]\nfrom typing import Protocol, Callable, ParamSpec\n\nclass CB(Protocol):\n    def __call__(self, x: str, y: int) -> None: ...\n\nP = ParamSpec('P')\ndef g(fn: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n\ncb: CB\ng(cb, y=0, x='a')  # OK\ng(cb, y='a', x=0)  # E: Argument \"y\" to \"g\" has incompatible type \"str\"; expected \"int\" \\\n                   # E: Argument \"x\" to \"g\" has incompatible type \"int\"; expected \"str\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecBadRuntimeTypeApplication]\nfrom typing import ParamSpec, TypeVar, Generic, Callable\n\nR = TypeVar(\"R\")\nP = ParamSpec(\"P\")\nclass C(Generic[P, R]):\n    x: Callable[P, R]\n\nbad = C[int, str]()  # E: Can only replace ParamSpec with a parameter types list or another ParamSpec, got \"int\"\nreveal_type(bad)  # N: Revealed type is \"__main__.C[Any, Any]\"\nreveal_type(bad.x)  # N: Revealed type is \"def (*Any, **Any) -> Any\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecNoCrashOnUnificationAlias]\nimport mod\n[file mod.pyi]\nfrom typing import Callable, Protocol, TypeVar, overload\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nR_co = TypeVar(\"R_co\", covariant=True)\nHandler = Callable[P, R_co]\n\nclass HandlerDecorator(Protocol):\n    def __call__(self, handler: Handler[P, R_co]) -> Handler[P, R_co]: ...\n\n@overload\ndef event(event_handler: Handler[P, R_co]) -> Handler[P, R_co]: ...\n@overload\ndef event(namespace: str, *args, **kwargs) -> HandlerDecorator: ...\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecNoCrashOnUnificationCallable]\nimport mod\n[file mod.pyi]\nfrom typing import Callable, Protocol, TypeVar, overload\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\nR_co = TypeVar(\"R_co\", covariant=True)\n\nclass HandlerDecorator(Protocol):\n    def __call__(self, handler: Callable[P, R_co]) -> Callable[P, R_co]: ...\n\n@overload\ndef event(event_handler: Callable[P, R_co]) -> Callable[P, R_co]: ...\n@overload\ndef event(namespace: str, *args, **kwargs) -> HandlerDecorator: ...\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecNoCrashOnUnificationPrefix]\nfrom typing import Any, Callable, TypeVar, overload\nfrom typing_extensions import ParamSpec, Concatenate\n\nT = TypeVar(\"T\")\nU = TypeVar(\"U\")\nV = TypeVar(\"V\")\nW = TypeVar(\"W\")\nP = ParamSpec(\"P\")\n\n@overload\ndef call(\n    func: Callable[Concatenate[T, P], U],\n    x: T,\n    *args: Any,\n    **kwargs: Any,\n) -> U: ...\n@overload\ndef call(\n    func: Callable[Concatenate[T, U, P], V],\n    x: T,\n    y: U,\n    *args: Any,\n    **kwargs: Any,\n) -> V: ...\ndef call(*args: Any, **kwargs: Any) -> Any: ...\n\ndef test1(x: int) -> str: ...\ndef test2(x: int, y: int) -> str: ...\nreveal_type(call(test1, 1))  # N: Revealed type is \"builtins.str\"\nreveal_type(call(test2, 1, 2))  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecCorrectParameterNameInference]\nfrom typing import Callable, Protocol\nfrom typing_extensions import ParamSpec, Concatenate\n\ndef a(i: int) -> None: ...\ndef b(__i: int) -> None: ...\n\nclass WithName(Protocol):\n    def __call__(self, i: int) -> None: ...\nNoName = Callable[[int], None]\n\ndef f1(__fn: WithName, i: int) -> None: ...\ndef f2(__fn: NoName, i: int) -> None: ...\n\nP = ParamSpec(\"P\")\ndef d(f: Callable[P, None], fn: Callable[Concatenate[Callable[P, None], P], None]) -> Callable[P, None]:\n    def inner(*args: P.args, **kwargs: P.kwargs) -> None:\n        fn(f, *args, **kwargs)\n    return inner\n\nreveal_type(d(a, f1))  # N: Revealed type is \"def (i: builtins.int)\"\nreveal_type(d(a, f2))  # N: Revealed type is \"def (i: builtins.int)\"\nreveal_type(d(b, f1))  # E: Cannot infer value of type parameter \"P\" of \"d\" \\\n                       # N: Revealed type is \"def (*Any, **Any)\"\nreveal_type(d(b, f2))  # N: Revealed type is \"def (builtins.int)\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecGenericWithNamedArg1]\nfrom typing import Callable, TypeVar\nfrom typing_extensions import ParamSpec\n\nR = TypeVar(\"R\")\nP = ParamSpec(\"P\")\n\ndef run(func: Callable[[], R], *args: object, backend: str = \"asyncio\") -> R: ...\nclass Result: ...\ndef run_portal() -> Result: ...\ndef submit(func: Callable[P, R], /, *args: P.args, **kwargs: P.kwargs) -> R: ...\n\nreveal_type(submit(  # N: Revealed type is \"__main__.Result\"\n    run,\n    run_portal,\n    backend=\"asyncio\",\n))\nsubmit(\n    run,  # E: Argument 1 to \"submit\" has incompatible type \"def [R] run(func: Callable[[], R], *args: object, backend: str = ...) -> R\"; expected \"Callable[[Callable[[], Result], int], Result]\"\n    run_portal,\n    backend=int(),\n)\n[builtins fixtures/paramspec.pyi]\n\n[case testInferenceAgainstGenericCallableUnionParamSpec]\nfrom typing import Callable, TypeVar, List, Union\nfrom typing_extensions import ParamSpec\n\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\n\ndef dec(f: Callable[P, T]) -> Callable[P, List[T]]: ...\n@dec\ndef func(arg: T) -> Union[T, str]:\n    ...\nreveal_type(func)  # N: Revealed type is \"def [T] (arg: T`-1) -> builtins.list[T`-1 | builtins.str]\"\nreveal_type(func(42))  # N: Revealed type is \"builtins.list[builtins.int | builtins.str]\"\n\ndef dec2(f: Callable[P, List[T]]) -> Callable[P, T]: ...\n@dec2\ndef func2(arg: T) -> List[Union[T, str]]:\n    ...\nreveal_type(func2)  # N: Revealed type is \"def [T] (arg: T`-1) -> T`-1 | builtins.str\"\nreveal_type(func2(42))  # N: Revealed type is \"builtins.int | builtins.str\"\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecPreciseKindsUsedIfPossible]\nfrom typing import Callable, Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec('P')\n\nclass Case(Generic[P]):\n    def __init__(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        pass\n\ndef _test(a: int, b: int = 0) -> None: ...\n\ndef parametrize(\n    func: Callable[P, None], *cases: Case[P], **named_cases: Case[P]\n) -> Callable[[], None]:\n    ...\n\nparametrize(_test, Case(1, 2), Case(3, 4))\nparametrize(_test, Case(1, b=2), Case(3, b=4))\nparametrize(_test, Case(1, 2), Case(3))\nparametrize(_test, Case(1, 2), Case(3, b=4))\n[builtins fixtures/paramspec.pyi]\n\n[case testRunParamSpecInsufficientArgs]\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable\n\n_P = ParamSpec(\"_P\")\n\ndef run(predicate: Callable[_P, None], *args: _P.args, **kwargs: _P.kwargs) -> None:\n    predicate()  # E: Too few arguments\n    predicate(*args)  # E: Too few arguments\n    predicate(**kwargs)  # E: Too few arguments\n    predicate(*args, **kwargs)\n\ndef fn() -> None: ...\ndef fn_args(x: int) -> None: ...\ndef fn_posonly(x: int, /) -> None: ...\n\nrun(fn)\nrun(fn_args, 1)\nrun(fn_args, x=1)\nrun(fn_posonly, 1)\nrun(fn_posonly, x=1)  # E: Unexpected keyword argument \"x\" for \"run\"\n\n[builtins fixtures/paramspec.pyi]\n\n[case testRunParamSpecConcatenateInsufficientArgs]\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable\n\n_P = ParamSpec(\"_P\")\n\ndef run(predicate: Callable[Concatenate[int, _P], None], *args: _P.args, **kwargs: _P.kwargs) -> None:\n    predicate()  # E: Too few arguments\n    predicate(1)  # E: Too few arguments\n    predicate(1, *args)  # E: Too few arguments\n    predicate(1, *args)  # E: Too few arguments\n    predicate(1, **kwargs)  # E: Too few arguments\n    predicate(*args, **kwargs)  # E: Argument 1 has incompatible type \"*_P.args\"; expected \"int\"\n    predicate(1, *args, **kwargs)\n\ndef fn() -> None: ...\ndef fn_args(x: int, y: str) -> None: ...\ndef fn_posonly(x: int, /) -> None: ...\ndef fn_posonly_args(x: int, /, y: str) -> None: ...\n\nrun(fn)  # E: Argument 1 to \"run\" has incompatible type \"Callable[[], None]\"; expected \"Callable[[int], None]\"\nrun(fn_args, 1, 'a')  # E: Too many arguments for \"run\" \\\n                      # E: Argument 2 to \"run\" has incompatible type \"int\"; expected \"str\"\nrun(fn_args, y='a')\nrun(fn_args, 'a')\nrun(fn_posonly)\nrun(fn_posonly, x=1)  # E: Unexpected keyword argument \"x\" for \"run\"\nrun(fn_posonly_args)  # E: Missing positional argument \"y\" in call to \"run\"\nrun(fn_posonly_args, 'a')\nrun(fn_posonly_args, y='a')\n\n[builtins fixtures/paramspec.pyi]\n\n[case testRunParamSpecConcatenateInsufficientArgsInDecorator]\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable\n\nP = ParamSpec(\"P\")\n\ndef decorator(fn: Callable[Concatenate[str, P], None]) -> Callable[P, None]:\n    def inner(*args: P.args, **kwargs: P.kwargs) -> None:\n        fn(\"value\")  # E: Too few arguments\n        fn(\"value\", *args)  # E: Too few arguments\n        fn(\"value\", **kwargs)  # E: Too few arguments\n        fn(*args, **kwargs)  # E: Argument 1 has incompatible type \"*P.args\"; expected \"str\"\n        fn(\"value\", *args, **kwargs)\n    return inner\n\n@decorator\ndef foo(s: str, s2: str) -> None: ...\n\n[builtins fixtures/paramspec.pyi]\n\n[case testRunParamSpecOverload]\nfrom typing_extensions import ParamSpec\nfrom typing import Callable, NoReturn, TypeVar, Union, overload\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\n@overload\ndef capture(\n    sync_fn: Callable[P, NoReturn],\n    *args: P.args,\n    **kwargs: P.kwargs,\n) -> int: ...\n@overload\ndef capture(\n    sync_fn: Callable[P, T],\n    *args: P.args,\n    **kwargs: P.kwargs,\n) -> Union[T, int]: ...\ndef capture(\n    sync_fn: Callable[P, T],\n    *args: P.args,\n    **kwargs: P.kwargs,\n) -> Union[T, int]:\n    return sync_fn(*args, **kwargs)\n\ndef fn() -> str: return ''\ndef err() -> NoReturn: ...\n\nreveal_type(capture(fn))  # N: Revealed type is \"builtins.str | builtins.int\"\nreveal_type(capture(err))  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/paramspec.pyi]\n\n[case testRunParamSpecOverlappingOverloadsOrder]\nfrom typing import Any, Callable, overload\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\n\nclass Base:\n    pass\nclass Child(Base):\n    def __call__(self) -> str: ...\nclass NotChild:\n    def __call__(self) -> str: ...\n\n@overload\ndef handle(func: Base) -> int: ...\n@overload\ndef handle(func: Callable[P, str], *args: P.args, **kwargs: P.kwargs) -> str: ...\ndef handle(func: Any, *args: Any, **kwargs: Any) -> Any:\n    return func(*args, **kwargs)\n\n@overload\ndef handle_reversed(func: Callable[P, str], *args: P.args, **kwargs: P.kwargs) -> str: ...\n@overload\ndef handle_reversed(func: Base) -> int: ...\ndef handle_reversed(func: Any, *args: Any, **kwargs: Any) -> Any:\n    return func(*args, **kwargs)\n\nreveal_type(handle(Child()))  # N: Revealed type is \"builtins.int\"\nreveal_type(handle(NotChild()))  # N: Revealed type is \"builtins.str\"\n\nreveal_type(handle_reversed(Child()))  # N: Revealed type is \"builtins.str\"\nreveal_type(handle_reversed(NotChild()))  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/paramspec.pyi]\n\n[case testBindPartial]\nfrom functools import partial\nfrom typing_extensions import ParamSpec\nfrom typing import Callable, TypeVar\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\ndef run(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, **kwargs)\n    return func2(*args)\n\ndef run2(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, *args)\n    return func2(**kwargs)\n\ndef run3(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, *args, **kwargs)\n    return func2()\n\ndef run4(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, *args, **kwargs)\n    return func2(**kwargs)\n\ndef run_bad(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, *args, **kwargs)\n    return func2(*args)  # E: Too many arguments\n\ndef run_bad2(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, **kwargs)\n    return func2(**kwargs)  # E: Too few arguments\n\ndef run_bad3(func: Callable[P, T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, *args)\n    return func2()  # E: Too few arguments\n\n[builtins fixtures/paramspec.pyi]\n\n[case testBindPartialConcatenate]\nfrom functools import partial\nfrom typing_extensions import Concatenate, ParamSpec\nfrom typing import Callable, TypeVar\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\ndef run(func: Callable[Concatenate[int, P], T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, 1, **kwargs)\n    return func2(*args)\n\ndef run2(func: Callable[Concatenate[int, P], T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, **kwargs)\n    p = [\"\"]\n    func2(1, *p)  # E: Too few arguments \\\n                  # E: Argument 2 has incompatible type \"*list[str]\"; expected \"P.args\"\n    func2(1, 2, *p)  # E: Too few arguments \\\n                     # E: Argument 2 has incompatible type \"int\"; expected \"P.args\" \\\n                     # E: Argument 3 has incompatible type \"*list[str]\"; expected \"P.args\"\n    func2(1, *args, *p)  # E: Argument 3 has incompatible type \"*list[str]\"; expected \"P.args\"\n    func2(1, *p, *args)  # E: Argument 2 has incompatible type \"*list[str]\"; expected \"P.args\"\n    return func2(1, *args)\n\ndef run3(func: Callable[Concatenate[int, P], T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, 1, *args)\n    d = {\"\":\"\"}\n    func2(**d)  # E: Too few arguments \\\n                # E: Argument 1 has incompatible type \"**dict[str, str]\"; expected \"P.kwargs\"\n    return func2(**kwargs)\n\ndef run4(func: Callable[Concatenate[int, P], T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, 1)\n    return func2(*args, **kwargs)\n\ndef run5(func: Callable[Concatenate[int, P], T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, 1, *args, **kwargs)\n    func2()\n    return func2(**kwargs)\n\ndef run_bad(func: Callable[Concatenate[int, P], T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, *args)  # E: Argument 1 has incompatible type \"*P.args\"; expected \"int\"\n    return func2(1, **kwargs)  # E: Argument 1 has incompatible type \"int\"; expected \"P.args\"\n\ndef run_bad2(func: Callable[Concatenate[int, P], T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, 1, *args)\n    func2()  # E: Too few arguments\n    func2(*args, **kwargs)  # E: Too many arguments\n    return func2(1, **kwargs)  # E: Argument 1 has incompatible type \"int\"; expected \"P.args\"\n\ndef run_bad3(func: Callable[Concatenate[int, P], T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, 1, **kwargs)\n    func2()  # E: Too few arguments\n    return func2(1, *args)  # E: Argument 1 has incompatible type \"int\"; expected \"P.args\"\n\ndef run_bad4(func: Callable[Concatenate[int, P], T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, 1)\n    func2()  # E: Too few arguments\n    func2(*args)  # E: Too few arguments\n    func2(1, *args)  # E: Too few arguments \\\n                     # E: Argument 1 has incompatible type \"int\"; expected \"P.args\"\n    func2(1, **kwargs)  # E: Too few arguments \\\n                        # E: Argument 1 has incompatible type \"int\"; expected \"P.args\"\n    return func2(**kwargs)  # E: Too few arguments\n\n[builtins fixtures/paramspec.pyi]\n\n[case testOtherVarArgs]\nfrom functools import partial\nfrom typing_extensions import Concatenate, ParamSpec\nfrom typing import Callable, TypeVar, Tuple\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\n\ndef run(func: Callable[Concatenate[int, str, P], T], *args: P.args, **kwargs: P.kwargs) -> T:\n    func2 = partial(func, **kwargs)\n    args_prefix: Tuple[int, str] = (1, 'a')\n    func2(*args_prefix)  # E: Too few arguments\n    func2(*args, *args_prefix)  # E: Argument 1 has incompatible type \"*P.args\"; expected \"int\" \\\n                                # E: Argument 1 has incompatible type \"*P.args\"; expected \"str\" \\\n                                # E: Argument 2 has incompatible type \"*tuple[int, str]\"; expected \"P.args\"\n    return func2(*args_prefix, *args)\n\n[builtins fixtures/paramspec.pyi]\n\n[case testParamSpecScoping]\nfrom typing import Any, Callable, Generic\nfrom typing_extensions import Concatenate, ParamSpec\n\nP = ParamSpec(\"P\")\nP2 = ParamSpec(\"P2\")\n\ndef contains(c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\ndef contains_other(f: Callable[P2, None], c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n\ndef contains_only_other(c: Callable[P2, None], *args: P.args, **kwargs: P.kwargs) -> None: ...  # E: ParamSpec \"P\" is unbound\n\ndef puts_p_into_scope(f: Callable[P, int]) -> None:\n    def contains(c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n    def inherits(*args: P.args, **kwargs: P.kwargs) -> None: ...\n\ndef puts_p_into_scope_concatenate(f: Callable[Concatenate[int, P], int]) -> None:\n    def contains(c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n    def inherits(*args: P.args, **kwargs: P.kwargs) -> None: ...\n\ndef wrapper() -> None:\n    def puts_p_into_scope1(f: Callable[P, int]) -> None:\n        def contains(c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n        def inherits(*args: P.args, **kwargs: P.kwargs) -> None: ...\n\nclass Wrapper:\n    def puts_p_into_scope1(self, f: Callable[P, int]) -> None:\n        def contains(c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n        def inherits(*args: P.args, **kwargs: P.kwargs) -> None: ...\n\n    def contains(self, c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n    def uses(self, *args: P.args, **kwargs: P.kwargs) -> None: ...  # E: ParamSpec \"P\" is unbound\n\n    def method(self) -> None:\n        def contains(c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n        def inherits(*args: P.args, **kwargs: P.kwargs) -> None: ...  # E: ParamSpec \"P\" is unbound\n\nclass GenericWrapper(Generic[P]):\n    x: P.args  # E: ParamSpec components are not allowed here\n    y: P.kwargs  # E: ParamSpec components are not allowed here\n\n    def contains(self, c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n    def puts_p_into_scope1(self, f: Callable[P, int]) -> None:\n        def contains(c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n        def inherits(*args: P.args, **kwargs: P.kwargs) -> None: ...\n\n    def uses(self, *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n    def method(self) -> None:\n        def contains(c: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None: ...\n        def inherits(*args: P.args, **kwargs: P.kwargs) -> None: ...\n[builtins fixtures/paramspec.pyi]\n\n[case testCallbackProtocolClassObjectParamSpec]\nfrom typing import Any, Callable, Protocol, Optional, Generic\nfrom typing_extensions import ParamSpec\n\nP = ParamSpec(\"P\")\n\nclass App: ...\n\nclass MiddlewareFactory(Protocol[P]):\n    def __call__(self, app: App, /, *args: P.args, **kwargs: P.kwargs) -> App:\n        ...\n\nclass Capture(Generic[P]): ...\n\nclass ServerErrorMiddleware(App):\n    def __init__(\n        self,\n        app: App,\n        handler: Optional[str] = None,\n        debug: bool = False,\n    ) -> None: ...\n\ndef fn(f: MiddlewareFactory[P]) -> Capture[P]: ...\n\nreveal_type(fn(ServerErrorMiddleware))  # N: Revealed type is \"__main__.Capture[[handler: builtins.str | None =, debug: builtins.bool =]]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testRunParamSpecDuplicateArgsKwargs]\nfrom typing_extensions import ParamSpec, Concatenate\nfrom typing import Callable, Union\n\n_P = ParamSpec(\"_P\")\n\ndef run(predicate: Callable[_P, None], *args: _P.args, **kwargs: _P.kwargs) -> None:\n    predicate(*args, *args, **kwargs)  # E: ParamSpec.args should only be passed once\n    predicate(*args, **kwargs, **kwargs)  # E: ParamSpec.kwargs should only be passed once\n    predicate(*args, *args, **kwargs, **kwargs)  # E: ParamSpec.args should only be passed once \\\n                                                 # E: ParamSpec.kwargs should only be passed once\n    copy_args = args\n    copy_kwargs = kwargs\n    predicate(*args, *copy_args, **kwargs)  # E: ParamSpec.args should only be passed once\n    predicate(*copy_args, *args, **kwargs)  # E: ParamSpec.args should only be passed once\n    predicate(*args, **copy_kwargs, **kwargs)  # E: ParamSpec.kwargs should only be passed once\n    predicate(*args, **kwargs, **copy_kwargs)  # E: ParamSpec.kwargs should only be passed once\n\ndef run2(predicate: Callable[Concatenate[int, _P], None], *args: _P.args, **kwargs: _P.kwargs) -> None:\n    predicate(*args, *args, **kwargs)  # E: ParamSpec.args should only be passed once \\\n                                       # E: Argument 1 has incompatible type \"*_P.args\"; expected \"int\"\n    predicate(*args, **kwargs, **kwargs)  # E: ParamSpec.kwargs should only be passed once \\\n                                          # E: Argument 1 has incompatible type \"*_P.args\"; expected \"int\"\n    predicate(1, *args, *args, **kwargs)  # E: ParamSpec.args should only be passed once\n    predicate(1, *args, **kwargs, **kwargs)  # E: ParamSpec.kwargs should only be passed once\n    predicate(1, *args, *args, **kwargs, **kwargs)  # E: ParamSpec.args should only be passed once \\\n                                                    # E: ParamSpec.kwargs should only be passed once\n    copy_args = args\n    copy_kwargs = kwargs\n    predicate(1, *args, *copy_args, **kwargs)  # E: ParamSpec.args should only be passed once\n    predicate(1, *copy_args, *args, **kwargs)  # E: ParamSpec.args should only be passed once\n    predicate(1, *args, **copy_kwargs, **kwargs)  # E: ParamSpec.kwargs should only be passed once\n    predicate(1, *args, **kwargs, **copy_kwargs)  # E: ParamSpec.kwargs should only be passed once\n\ndef run3(predicate: Callable[Concatenate[int, str, _P], None], *args: _P.args, **kwargs: _P.kwargs) -> None:\n    base_ok: tuple[int, str]\n    predicate(*base_ok, *args, **kwargs)\n    base_bad: tuple[Union[int, str], ...]\n    predicate(*base_bad, *args, **kwargs)  # E: Argument 1 has incompatible type \"*tuple[int | str, ...]\"; expected \"int\" \\\n                                           # E: Argument 1 has incompatible type \"*tuple[int | str, ...]\"; expected \"str\" \\\n                                           # E: Argument 1 has incompatible type \"*tuple[int | str, ...]\"; expected \"_P.args\"\n[builtins fixtures/paramspec.pyi]\n\n[case testRevealBoundParamSpecArgs]\nfrom typing import Callable, Generic, ParamSpec\nfrom typing_extensions import Concatenate, TypeVarTuple, Unpack\n\nP = ParamSpec(\"P\")\nTs = TypeVarTuple(\"Ts\")\n\nclass Sneaky(Generic[P]):\n    def __init__(self, fn: Callable[P, object], *args: P.args, **kwargs: P.kwargs) -> None:\n        self.fn = fn\n        self.args = args\n        self.kwargs = kwargs\n\nclass SneakyPrefix(Generic[P]):\n    def __init__(self, fn: Callable[Concatenate[int, P], object], _: int, *args: P.args, **kwargs: P.kwargs) -> None:\n        self.fn = fn\n        self.args = args\n        self.kwargs = kwargs\n\ndef f1() -> int:\n    return 0\ndef f2(x: int) -> int:\n    return 0\ndef f3(x: int, /) -> int:\n    return 0\ndef f4(*, x: int) -> int:\n    return 0\ndef f5(x: int, y: int = 0) -> int:\n    return 0\ndef f6(x: int, *args: int) -> int:\n    return 0\ndef f7(x: int, *args: Unpack[Ts]) -> int:\n    return 0\ndef f8(x: int, *args: Unpack[tuple[str, ...]]) -> int:\n    return 0\ndef f9(x: int, *args: Unpack[tuple[str, int]]) -> int:\n    return 0\ndef f10(x: int=0, *args: Unpack[tuple[str, ...]]) -> int:\n    return 0\ndef f11(x: int = 0, /) -> int:\n    return 0\n\nreveal_type(Sneaky(f1).args)  # N: Revealed type is \"tuple[()]\"\nreveal_type(SneakyPrefix(f1).args)  # E: Missing positional argument \"_\" in call to \"SneakyPrefix\" \\\n                                    # N: Revealed type is \"tuple[()]\" \\\n                                    # E: Argument 1 to \"SneakyPrefix\" has incompatible type \"Callable[[], int]\"; expected \"Callable[[int], object]\"\n\nreveal_type(Sneaky(f2, 1).args)  # N: Revealed type is \"tuple[()] | tuple[builtins.int]\"\nreveal_type(SneakyPrefix(f2, 1).args)  # N: Revealed type is \"tuple[()]\"\n\nreveal_type(Sneaky(f3, 1).args)  # N: Revealed type is \"tuple[builtins.int]\"\nreveal_type(SneakyPrefix(f3, 1).args)  # N: Revealed type is \"tuple[()]\"\n\nreveal_type(Sneaky(f4, x=1).args)  # N: Revealed type is \"tuple[()]\"\n\nreveal_type(Sneaky(f5, 1).args)  # N: Revealed type is \"tuple[()] | tuple[builtins.int] | tuple[builtins.int, builtins.int]\"\nreveal_type(SneakyPrefix(f5, 1).args)  # N: Revealed type is \"tuple[()] | tuple[builtins.int]\"\nreveal_type(Sneaky(f5, 1, 2).args)  # N: Revealed type is \"tuple[()] | tuple[builtins.int] | tuple[builtins.int, builtins.int]\"\nreveal_type(SneakyPrefix(f5, 1, 2).args)  # N: Revealed type is \"tuple[()] | tuple[builtins.int]\"\n\nreveal_type(Sneaky(f6, 1).args)  # N: Revealed type is \"tuple[()] | tuple[builtins.int] | tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]\"\nreveal_type(SneakyPrefix(f6, 1).args)  # N: Revealed type is \"tuple[()] | tuple[Unpack[builtins.tuple[builtins.int, ...]]]\"\nreveal_type(Sneaky(f6, 1, 2).args)  # N: Revealed type is \"tuple[()] | tuple[builtins.int] | tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]\"\nreveal_type(SneakyPrefix(f6, 1, 2).args)  # N: Revealed type is \"tuple[()] | tuple[Unpack[builtins.tuple[builtins.int, ...]]]\"\n\nreveal_type(Sneaky(f7, 1, 2).args)  # N: Revealed type is \"tuple[Literal[1]?, Literal[2]?]\"\nreveal_type(SneakyPrefix(f7, 1, 2).args)  # N: Revealed type is \"tuple[Literal[2]?]\"\n\nreveal_type(Sneaky(f8, 1, '').args)  # N: Revealed type is \"tuple[()] | tuple[builtins.int] | tuple[builtins.int, Unpack[builtins.tuple[builtins.str, ...]]]\"\nreveal_type(SneakyPrefix(f8, 1, '').args)  # N: Revealed type is \"tuple[()] | tuple[Unpack[builtins.tuple[builtins.str, ...]]]\"\n\nreveal_type(Sneaky(f9, 1, '', 0).args)  # N: Revealed type is \"tuple[builtins.int, builtins.str, builtins.int]\"\nreveal_type(SneakyPrefix(f9, 1, '', 0).args)  # N: Revealed type is \"tuple[builtins.str, builtins.int]\"\n\nreveal_type(Sneaky(f10, 1, '', '').args)  # N: Revealed type is \"tuple[()] | tuple[builtins.int] | tuple[builtins.int, Unpack[builtins.tuple[builtins.str, ...]]]\"\nreveal_type(SneakyPrefix(f10, 1, '', '').args)  # N: Revealed type is \"tuple[()] | tuple[Unpack[builtins.tuple[builtins.str, ...]]]\"\n\nreveal_type(Sneaky(f11).args)  # N: Revealed type is \"tuple[()] | tuple[builtins.int]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testRevealBoundParamSpecGeneric]\nfrom typing import Callable, Generic, ParamSpec, TypeVar\nfrom typing_extensions import TypeVarTuple, Unpack\n\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nTs = TypeVarTuple(\"Ts\")\n\nclass SplitSneaky(Generic[P]):\n    def __init__(self, target: Callable[P, None]) -> None:\n        ...\n\n    def run(self, *args: P.args, **kwargs: P.kwargs) -> None:\n        self.args = args\n        self.kwargs = kwargs\n\ndef f1(x: T) -> None: ...\ndef f2(*xs: Unpack[Ts]) -> None: ...\ndef f3(fn: Callable[P, None]) -> None: ...\n\nreveal_type(SplitSneaky(f1).args)  # N: Revealed type is \"builtins.tuple[builtins.object, ...]\"\nreveal_type(SplitSneaky(f1).kwargs)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nreveal_type(SplitSneaky(f2).args)  # N: Revealed type is \"builtins.tuple[builtins.object, ...]\"\nreveal_type(SplitSneaky(f2).kwargs)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\nreveal_type(SplitSneaky(f3).args)  # N: Revealed type is \"builtins.tuple[builtins.object, ...]\"\nreveal_type(SplitSneaky(f3).kwargs)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.object]\"\n[builtins fixtures/paramspec.pyi]\n\n[case testRevealBoundParamSpecKwargs]\nfrom typing import Callable, Generic, ParamSpec\nfrom typing_extensions import Unpack, NotRequired, TypedDict\n\nP = ParamSpec(\"P\")\n\nclass Sneaky(Generic[P]):\n    def __init__(self, fn: Callable[P, object], *args: P.args, **kwargs: P.kwargs) -> None:\n        self.fn = fn\n        self.args = args\n        self.kwargs = kwargs\n\nclass Opt(TypedDict):\n    y: int\n    z: NotRequired[str]\n\ndef f1() -> int:\n    return 0\ndef f2(x: int) -> int:\n    return 0\ndef f3(x: int, /) -> int:\n    return 0\ndef f4(*, x: int) -> int:\n    return 0\ndef f5(x: int, y: int = 0) -> int:\n    return 0\ndef f6(**kwargs: int) -> int:\n    return 0\ndef f7(x: int, **kwargs: str) -> int:\n    return 0\ndef f8(x: int, /, **kwargs: str) -> int:\n    return 0\ndef f9(x: int, **kwargs: Unpack[Opt]) -> int:\n    return 0\n\nreveal_type(Sneaky(f1).kwargs)  # N: Revealed type is \"builtins.dict[builtins.str, Never]\"\nreveal_type(Sneaky(f2, 1).kwargs)  # N: Revealed type is \"TypedDict('builtins.dict', {'x'?: builtins.int})\"\nreveal_type(Sneaky(f3, 1).kwargs)  # N: Revealed type is \"builtins.dict[builtins.str, Never]\"\nreveal_type(Sneaky(f4, x=1).kwargs)  # N: Revealed type is \"TypedDict('builtins.dict', {'x': builtins.int})\"\nreveal_type(Sneaky(f5, 1).kwargs)  # N: Revealed type is \"TypedDict('builtins.dict', {'x'?: builtins.int, 'y'?: builtins.int})\"\nreveal_type(Sneaky(f5, 1, 2).kwargs)  # N: Revealed type is \"TypedDict('builtins.dict', {'x'?: builtins.int, 'y'?: builtins.int})\"\nreveal_type(Sneaky(f6, x=1).kwargs)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\nreveal_type(Sneaky(f6, x=1, y=2).kwargs)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\nreveal_type(Sneaky(f7, 1, y='').kwargs)  # N: Revealed type is \"TypedDict('builtins.dict', {'x'?: builtins.int})\"\nreveal_type(Sneaky(f8, 1, y='').kwargs)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.str]\"\nreveal_type(Sneaky(f9, 1, y=0).kwargs)  # N: Revealed type is \"TypedDict('builtins.dict', {'x'?: builtins.int, 'y': builtins.int, 'z'?: builtins.str})\"\nreveal_type(Sneaky(f9, 1, y=0, z='').kwargs)  # N: Revealed type is \"TypedDict('builtins.dict', {'x'?: builtins.int, 'y': builtins.int, 'z'?: builtins.str})\"\n[builtins fixtures/paramspec.pyi]\n"
  },
  {
    "path": "test-data/unit/check-plugin-attrs.test",
    "content": "[case testAttrsSimple_no_empty]\nimport attr\n@attr.s\nclass A:\n    a = attr.ib()\n    _b = attr.ib()\n    c = attr.ib(18)\n    _d = attr.ib(validator=None, default=18)\n    E = 18\n\n    def foo(self):\n        return self.a\nreveal_type(A)  # N: Revealed type is \"def (a: Any, b: Any, c: Any =, d: Any =) -> __main__.A\"\nA(1, [2])\nA(1, [2], '3', 4)\nA(1, 2, 3, 4)\nA(1, [2], '3', 4, 5)  # E: Too many arguments for \"A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsAnnotated]\nimport attr\nfrom typing import List, ClassVar\n@attr.s\nclass A:\n    a: int = attr.ib()\n    _b: List[int] = attr.ib()\n    c: str = attr.ib('18')\n    _d: int = attr.ib(validator=None, default=18)\n    E = 7\n    F: ClassVar[int] = 22\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int, b: builtins.list[builtins.int], c: builtins.str =, d: builtins.int =) -> __main__.A\"\nA(1, [2])\nA(1, [2], '3', 4)\nA(1, 2, 3, 4)  # E: Argument 2 to \"A\" has incompatible type \"int\"; expected \"list[int]\" # E: Argument 3 to \"A\" has incompatible type \"int\"; expected \"str\"\nA(1, [2], '3', 4, 5)  # E: Too many arguments for \"A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsTypeComments]\nimport attr\nfrom typing import List, ClassVar\n@attr.s\nclass A:\n    a = attr.ib()   # type: int\n    _b = attr.ib()  # type: List[int]\n    c = attr.ib('18') # type: str\n    _d = attr.ib(validator=None, default=18) # type: int\n    E = 7\n    F: ClassVar[int] = 22\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int, b: builtins.list[builtins.int], c: builtins.str =, d: builtins.int =) -> __main__.A\"\nA(1, [2])\nA(1, [2], '3', 4)\nA(1, 2, 3, 4)  # E: Argument 2 to \"A\" has incompatible type \"int\"; expected \"list[int]\" # E: Argument 3 to \"A\" has incompatible type \"int\"; expected \"str\"\nA(1, [2], '3', 4, 5)  # E: Too many arguments for \"A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsAutoAttribs]\nimport attr\nfrom typing import List, ClassVar\n@attr.s(auto_attribs=True)\nclass A:\n    a: int\n    _b: List[int]\n    c: str = '18'\n    _d: int = attr.ib(validator=None, default=18)\n    E = 7\n    F: ClassVar[int] = 22\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int, b: builtins.list[builtins.int], c: builtins.str =, d: builtins.int =) -> __main__.A\"\nA(1, [2])\nA(1, [2], '3', 4)\nA(1, 2, 3, 4)  # E: Argument 2 to \"A\" has incompatible type \"int\"; expected \"list[int]\" # E: Argument 3 to \"A\" has incompatible type \"int\"; expected \"str\"\nA(1, [2], '3', 4, 5)  # E: Too many arguments for \"A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsUntypedNoUntypedDefs]\n# flags: --disallow-untyped-defs\nimport attr\n@attr.s\nclass A:\n    a = attr.ib()  # E: Need type annotation for \"a\"\n    _b = attr.ib()  # E: Need type annotation for \"_b\"\n    c = attr.ib(18)  # E: Need type annotation for \"c\"\n    _d = attr.ib(validator=None, default=18)   # E: Need type annotation for \"_d\"\n    E = 18\n[builtins fixtures/bool.pyi]\n\n[case testAttrsWrongReturnValue]\nimport attr\n@attr.s\nclass A:\n    x: int = attr.ib(8)\n    def foo(self) -> str:\n        return self.x  # E: Incompatible return value type (got \"int\", expected \"str\")\n@attr.s\nclass B:\n    x = attr.ib(8)  # type: int\n    def foo(self) -> str:\n        return self.x  # E: Incompatible return value type (got \"int\", expected \"str\")\n@attr.dataclass\nclass C:\n    x: int = 8\n    def foo(self) -> str:\n        return self.x  # E: Incompatible return value type (got \"int\", expected \"str\")\n@attr.s\nclass D:\n    x = attr.ib(8, type=int)\n    def foo(self) -> str:\n        return self.x  # E: Incompatible return value type (got \"int\", expected \"str\")\n[builtins fixtures/bool.pyi]\n\n[case testAttrsSeriousNames]\nfrom attr import attrib, attrs\nfrom typing import List\n@attrs(init=True)\nclass A:\n    a = attrib()\n    _b: List[int] = attrib()\n    c = attrib(18)\n    _d = attrib(validator=None, default=18)\n    CLASS_VAR = 18\nreveal_type(A)  # N: Revealed type is \"def (a: Any, b: builtins.list[builtins.int], c: Any =, d: Any =) -> __main__.A\"\nA(1, [2])\nA(1, [2], '3', 4)\nA(1, 2, 3, 4)  # E: Argument 2 to \"A\" has incompatible type \"int\"; expected \"list[int]\"\nA(1, [2], '3', 4, 5)  # E: Too many arguments for \"A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsDefaultErrors]\nimport attr\n@attr.s\nclass A:\n    x = attr.ib(default=17)\n    y = attr.ib()  # E: Non-default attributes not allowed after default attributes.\n@attr.s(auto_attribs=True)\nclass B:\n    x: int = 17\n    y: int # E: Non-default attributes not allowed after default attributes.\n@attr.s(auto_attribs=True)\nclass C:\n    x: int = attr.ib(default=17)\n    y: int # E: Non-default attributes not allowed after default attributes.\n@attr.s\nclass D:\n    x = attr.ib()\n    y = attr.ib() # E: Non-default attributes not allowed after default attributes.\n\n    @x.default\n    def foo(self):\n        return 17\n[builtins fixtures/bool.pyi]\n\n[case testAttrsNotBooleans]\nimport attr\nx = True\n@attr.s(cmp=x)  # E: \"cmp\" argument must be a True, False, or None literal\nclass A:\n    a = attr.ib(init=x)  # E: \"init\" argument must be a True or False literal\n[builtins fixtures/bool.pyi]\n\n[case testAttrsInitFalse]\nfrom attr import attrib, attrs\n@attrs(auto_attribs=True, init=False)\nclass A:\n    a: int\n    _b: int\n    c: int = 18\n    _d: int = attrib(validator=None, default=18)\nreveal_type(A)  # N: Revealed type is \"def () -> __main__.A\"\nA()\nA(1, [2])  # E: Too many arguments for \"A\"\nA(1, [2], '3', 4)  # E: Too many arguments for \"A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsInitAttribFalse]\nfrom attr import attrib, attrs\n@attrs\nclass A:\n    a = attrib(init=False)\n    b = attrib()\nreveal_type(A)  # N: Revealed type is \"def (b: Any) -> __main__.A\"\n[builtins fixtures/bool.pyi]\n\n[case testAttrsCmpTrue]\nfrom attr import attrib, attrs\n@attrs(auto_attribs=True)\nclass A:\n    a: int\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int) -> __main__.A\"\nreveal_type(A.__lt__)  # N: Revealed type is \"def [_AT] (self: _AT`3, other: _AT`3) -> builtins.bool\"\nreveal_type(A.__le__)  # N: Revealed type is \"def [_AT] (self: _AT`4, other: _AT`4) -> builtins.bool\"\nreveal_type(A.__gt__)  # N: Revealed type is \"def [_AT] (self: _AT`5, other: _AT`5) -> builtins.bool\"\nreveal_type(A.__ge__)  # N: Revealed type is \"def [_AT] (self: _AT`6, other: _AT`6) -> builtins.bool\"\n\nA(1) < A(2)\nA(1) <= A(2)\nA(1) > A(2)\nA(1) >= A(2)\nA(1) == A(2)\nA(1) != A(2)\n\nA(1) < 1  # E: Unsupported operand types for < (\"A\" and \"int\")\nA(1) <= 1  # E: Unsupported operand types for <= (\"A\" and \"int\")\nA(1) > 1  # E: Unsupported operand types for > (\"A\" and \"int\")\nA(1) >= 1  # E: Unsupported operand types for >= (\"A\" and \"int\")\nA(1) == 1\nA(1) != 1\n\n1 < A(1)  # E: Unsupported operand types for > (\"A\" and \"int\")\n1 <= A(1)  # E: Unsupported operand types for >= (\"A\" and \"int\")\n1 > A(1)  # E: Unsupported operand types for < (\"A\" and \"int\")\n1 >= A(1)  # E: Unsupported operand types for <= (\"A\" and \"int\")\n1 == A(1)\n1 != A(1)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsEqFalse]\nfrom attr import attrib, attrs\n@attrs(auto_attribs=True, eq=False)\nclass A:\n    a: int\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int) -> __main__.A\"\nreveal_type(A.__eq__)  # N: Revealed type is \"def (builtins.object, builtins.object) -> builtins.bool\"\nreveal_type(A.__ne__)  # N: Revealed type is \"def (builtins.object, builtins.object) -> builtins.bool\"\n\nA(1) < A(2)  # E: Unsupported left operand type for < (\"A\")\nA(1) <= A(2)  # E: Unsupported left operand type for <= (\"A\")\nA(1) > A(2)  # E: Unsupported left operand type for > (\"A\")\nA(1) >= A(2)  # E: Unsupported left operand type for >= (\"A\")\nA(1) == A(2)\nA(1) != A(2)\n\nA(1) < 1  # E: Unsupported left operand type for < (\"A\")\nA(1) <= 1  # E: Unsupported left operand type for <= (\"A\")\nA(1) > 1  # E: Unsupported left operand type for > (\"A\")\nA(1) >= 1  # E: Unsupported left operand type for >= (\"A\")\nA(1) == 1\nA(1) != 1\n\n1 < A(1)  # E: Unsupported left operand type for < (\"int\")\n1 <= A(1)  # E: Unsupported left operand type for <= (\"int\")\n1 > A(1)  # E: Unsupported left operand type for > (\"int\")\n1 >= A(1)  # E: Unsupported left operand type for >= (\"int\")\n1 == A(1)\n1 != A(1)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsOrderFalse]\nfrom attr import attrib, attrs\n@attrs(auto_attribs=True, order=False)\nclass A:\n    a: int\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int) -> __main__.A\"\n\nA(1) < A(2)  # E: Unsupported left operand type for < (\"A\")\nA(1) <= A(2)  # E: Unsupported left operand type for <= (\"A\")\nA(1) > A(2)  # E: Unsupported left operand type for > (\"A\")\nA(1) >= A(2)  # E: Unsupported left operand type for >= (\"A\")\nA(1) == A(2)\nA(1) != A(2)\n\nA(1) < 1  # E: Unsupported left operand type for < (\"A\")\nA(1) <= 1  # E: Unsupported left operand type for <= (\"A\")\nA(1) > 1  # E: Unsupported left operand type for > (\"A\")\nA(1) >= 1  # E: Unsupported left operand type for >= (\"A\")\nA(1) == 1\nA(1) != 1\n\n1 < A(1)  # E: Unsupported left operand type for < (\"int\")\n1 <= A(1)  # E: Unsupported left operand type for <= (\"int\")\n1 > A(1)  # E: Unsupported left operand type for > (\"int\")\n1 >= A(1)  # E: Unsupported left operand type for >= (\"int\")\n1 == A(1)\n1 != A(1)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsCmpEqOrderValues]\nfrom attr import attrib, attrs\n@attrs(cmp=True)\nclass DeprecatedTrue:\n   ...\n\n@attrs(cmp=False)\nclass DeprecatedFalse:\n   ...\n\n@attrs(cmp=False, eq=True)  # E: Don't mix \"cmp\" with \"eq\" and \"order\"\nclass Mixed:\n   ...\n\n@attrs(order=True, eq=False)  # E: eq must be True if order is True\nclass Confused:\n   ...\n[builtins fixtures/plugin_attrs.pyi]\n\n\n[case testAttrsInheritance]\nimport attr\n@attr.s\nclass A:\n    a: int = attr.ib()\n@attr.s\nclass B:\n    b: str = attr.ib()\n@attr.s\nclass C(A, B):\n    c: bool = attr.ib()\nreveal_type(C)  # N: Revealed type is \"def (a: builtins.int, b: builtins.str, c: builtins.bool) -> __main__.C\"\n[builtins fixtures/bool.pyi]\n\n[case testAttrsNestedInClasses]\nimport attr\n@attr.s\nclass C:\n    y = attr.ib()\n    @attr.s\n    class D:\n        x: int = attr.ib()\nreveal_type(C)  # N: Revealed type is \"def (y: Any) -> __main__.C\"\nreveal_type(C.D)  # N: Revealed type is \"def (x: builtins.int) -> __main__.C.D\"\n[builtins fixtures/bool.pyi]\n\n[case testAttrsInheritanceOverride]\nimport attr\n\n@attr.s\nclass A:\n    a: int = attr.ib()\n    x: int = attr.ib()\n\n@attr.s\nclass B(A):\n    b: str = attr.ib()\n    x: int = attr.ib(default=22)\n\n@attr.s\nclass C(B):\n    c: bool = attr.ib()  # No error here because the x below overwrites the x above.\n    x: int = attr.ib()\n\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int, x: builtins.int) -> __main__.A\"\nreveal_type(B)  # N: Revealed type is \"def (a: builtins.int, b: builtins.str, x: builtins.int =) -> __main__.B\"\nreveal_type(C)  # N: Revealed type is \"def (a: builtins.int, b: builtins.str, c: builtins.bool, x: builtins.int) -> __main__.C\"\n[builtins fixtures/bool.pyi]\n\n[case testAttrsTypeEquals]\nimport attr\n\n@attr.s\nclass A:\n    a = attr.ib(type=int)\n    b = attr.ib(18, type=int)\nreveal_type(A) # N: Revealed type is \"def (a: builtins.int, b: builtins.int =) -> __main__.A\"\n[builtins fixtures/bool.pyi]\n\n[case testAttrsFrozen]\nimport attr\n\n@attr.s(frozen=True)\nclass A:\n    a = attr.ib()\n\na = A(5)\na.a = 16  # E: Property \"a\" defined in \"A\" is read-only\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsNextGenFrozen]\nfrom attr import frozen, field\n\n@frozen\nclass A:\n    a = field()\n\na = A(5)\na.a = 16  # E: Property \"a\" defined in \"A\" is read-only\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsNextGenDetect]\nfrom attr import define, field\n\n@define\nclass A:\n    a = field()\n\n@define\nclass B:\n    a: int\n\n@define\nclass C:\n    a: int = field()\n    b = field()\n\n@define\nclass D:\n    a: int\n    b = field()\n\nreveal_type(A)  # N: Revealed type is \"def (a: Any) -> __main__.A\"\nreveal_type(B)  # N: Revealed type is \"def (a: builtins.int) -> __main__.B\"\nreveal_type(C)  # N: Revealed type is \"def (a: builtins.int, b: Any) -> __main__.C\"\nreveal_type(D)  # N: Revealed type is \"def (b: Any) -> __main__.D\"\n\n[builtins fixtures/bool.pyi]\n\n[case testAttrsOldPackage]\nimport attr\n@attr.s(auto_attribs=True)\nclass A:\n    a: int = attr.ib()\n    b: bool\n\n@attr.s(auto_attribs=True, frozen=True)\nclass B:\n    a: bool\n    b: int\n\n@attr.s\nclass C:\n    a = attr.ib(type=int)\n\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int, b: builtins.bool) -> __main__.A\"\nreveal_type(B)  # N: Revealed type is \"def (a: builtins.bool, b: builtins.int) -> __main__.B\"\nreveal_type(C)  # N: Revealed type is \"def (a: builtins.int) -> __main__.C\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsDataClass]\nimport attr\nfrom typing import List, ClassVar\n@attr.dataclass\nclass A:\n    a: int\n    _b: List[str]\n    c: str = '18'\n    _d: int = attr.ib(validator=None, default=18)\n    E = 7\n    F: ClassVar[int] = 22\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int, b: builtins.list[builtins.str], c: builtins.str =, d: builtins.int =) -> __main__.A\"\nA(1, ['2'])\n[builtins fixtures/list.pyi]\n\n[case testAttrsTypeAlias]\nfrom typing import List\nimport attr\nAlias = List[int]\n@attr.s(auto_attribs=True)\nclass A:\n    Alias2 = List[str]\n    x: Alias\n    y: Alias2 = attr.ib()\nreveal_type(A) # N: Revealed type is \"def (x: builtins.list[builtins.int], y: builtins.list[builtins.str]) -> __main__.A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsGeneric]\nfrom typing import TypeVar, Generic, List\nimport attr\nT = TypeVar('T')\n@attr.s(auto_attribs=True)\nclass A(Generic[T]):\n    x: List[T]\n    y: T = attr.ib()\n    def foo(self) -> List[T]:\n        return [self.y]\n    def bar(self) -> T:\n        return self.x[0]\n    def problem(self) -> T:\n        return self.x  # E: Incompatible return value type (got \"list[T]\", expected \"T\")\nreveal_type(A) # N: Revealed type is \"def [T] (x: builtins.list[T`1], y: T`1) -> __main__.A[T`1]\"\na = A([1], 2)\nreveal_type(a)  # N: Revealed type is \"__main__.A[builtins.int]\"\nreveal_type(a.x)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(a.y)  # N: Revealed type is \"builtins.int\"\n\nA(['str'], 7)  # E: Cannot infer value of type parameter \"T\" of \"A\"\nA([1], '2')  # E: Cannot infer value of type parameter \"T\" of \"A\"\n\n[builtins fixtures/list.pyi]\n\n[case testAttrsGenericWithConverter]\nfrom typing import TypeVar, Generic, List, Iterable, Iterator, Callable\nimport attr\nT = TypeVar('T')\n\ndef int_gen() -> Iterator[int]:\n    yield 1\n\ndef list_converter(x: Iterable[T]) -> List[T]:\n    return list(x)\n\n@attr.s(auto_attribs=True)\nclass A(Generic[T]):\n    x: List[T] = attr.ib(converter=list_converter)\n    y: T = attr.ib()\n    def foo(self) -> List[T]:\n        return [self.y]\n    def bar(self) -> T:\n        return self.x[0]\n    def problem(self) -> T:\n        return self.x  # E: Incompatible return value type (got \"list[T]\", expected \"T\")\nreveal_type(A) # N: Revealed type is \"def [T] (x: typing.Iterable[T`1], y: T`1) -> __main__.A[T`1]\"\na1 = A([1], 2)\nreveal_type(a1)  # N: Revealed type is \"__main__.A[builtins.int]\"\nreveal_type(a1.x)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(a1.y)  # N: Revealed type is \"builtins.int\"\n\na2 = A(int_gen(), 2)\nreveal_type(a2)  # N: Revealed type is \"__main__.A[builtins.int]\"\nreveal_type(a2.x)  # N: Revealed type is \"builtins.list[builtins.int]\"\nreveal_type(a2.y)  # N: Revealed type is \"builtins.int\"\n\n\ndef get_int() -> int:\n    return 1\n\nclass Other(Generic[T]):\n    def __init__(self, x: T) -> None:\n        pass\n\n@attr.s(auto_attribs=True)\nclass B(Generic[T]):\n    x: Other[Callable[..., T]] = attr.ib(converter=Other[Callable[..., T]])\n\nb1 = B(get_int)\nreveal_type(b1)  # N: Revealed type is \"__main__.B[builtins.int]\"\nreveal_type(b1.x)  # N: Revealed type is \"__main__.Other[def (*Any, **Any) -> builtins.int]\"\n\n[builtins fixtures/list.pyi]\n\n\n[case testAttrsUntypedGenericInheritance]\nfrom typing import Generic, TypeVar\nimport attr\n\nT = TypeVar(\"T\")\n\n@attr.s(auto_attribs=True)\nclass Base(Generic[T]):\n    attr: T\n\n@attr.s(auto_attribs=True)\nclass Sub(Base):\n    pass\n\nsub = Sub(attr=1)\nreveal_type(sub)  # N: Revealed type is \"__main__.Sub\"\nreveal_type(sub.attr)  # N: Revealed type is \"Any\"\n\n[builtins fixtures/bool.pyi]\n\n\n[case testAttrsGenericInheritance]\nfrom typing import Generic, TypeVar\nimport attr\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\n@attr.s(auto_attribs=True)\nclass Base(Generic[T]):\n    attr: T\n\n@attr.s(auto_attribs=True)\nclass Sub(Base[S]):\n    pass\n\nsub_int = Sub[int](attr=1)\nreveal_type(sub_int)  # N: Revealed type is \"__main__.Sub[builtins.int]\"\nreveal_type(sub_int.attr)  # N: Revealed type is \"builtins.int\"\n\nsub_str = Sub[str](attr='ok')\nreveal_type(sub_str)  # N: Revealed type is \"__main__.Sub[builtins.str]\"\nreveal_type(sub_str.attr)  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/bool.pyi]\n\n\n[case testAttrsGenericInheritance2]\nfrom typing import Generic, TypeVar\nimport attr\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\n@attr.s(auto_attribs=True)\nclass Base(Generic[T1, T2, T3]):\n    one: T1\n    two: T2\n    three: T3\n\n@attr.s(auto_attribs=True)\nclass Sub(Base[int, str, float]):\n    pass\n\nsub = Sub(one=1, two='ok', three=3.14)\nreveal_type(sub)  # N: Revealed type is \"__main__.Sub\"\nreveal_type(sub.one)  # N: Revealed type is \"builtins.int\"\nreveal_type(sub.two)  # N: Revealed type is \"builtins.str\"\nreveal_type(sub.three)  # N: Revealed type is \"builtins.float\"\n\n[builtins fixtures/bool.pyi]\n\n\n[case testAttrsGenericInheritance3]\nimport attr\nfrom typing import Any, Callable, Generic, TypeVar, List\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\n@attr.s(auto_attribs=True)\nclass Parent(Generic[T]):\n    f: Callable[[T], Any]\n\n@attr.s(auto_attribs=True)\nclass Child(Parent[T]): ...\n\nclass A: ...\ndef func(obj: A) -> bool: ...\n\nreveal_type(Child[A](func).f)  # N: Revealed type is \"def (__main__.A) -> Any\"\n\n@attr.s(auto_attribs=True)\nclass Parent2(Generic[T]):\n    a: List[T]\n\n@attr.s(auto_attribs=True)\nclass Child2(Generic[T, S], Parent2[S]):\n    b: List[T]\n\nreveal_type(Child2([A()], [1]).a)  # N: Revealed type is \"builtins.list[__main__.A]\"\nreveal_type(Child2[int, A]([A()], [1]).b)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsMultiGenericInheritance]\nfrom typing import Generic, TypeVar\nimport attr\n\nT = TypeVar(\"T\")\n\n@attr.s(auto_attribs=True, eq=False)\nclass Base(Generic[T]):\n    base_attr: T\n\nS = TypeVar(\"S\")\n\n@attr.s(auto_attribs=True, eq=False)\nclass Middle(Base[int], Generic[S]):\n    middle_attr: S\n\n@attr.s(auto_attribs=True, eq=False)\nclass Sub(Middle[str]):\n    pass\n\nsub = Sub(base_attr=1, middle_attr='ok')\nreveal_type(sub)  # N: Revealed type is \"__main__.Sub\"\nreveal_type(sub.base_attr)  # N: Revealed type is \"builtins.int\"\nreveal_type(sub.middle_attr)  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/bool.pyi]\n\n\n[case testAttrsGenericClassmethod]\nfrom typing import TypeVar, Generic, Optional\nimport attr\nT = TypeVar('T')\n@attr.s(auto_attribs=True)\nclass A(Generic[T]):\n    x: Optional[T]\n    @classmethod\n    def clsmeth(cls) -> None:\n       reveal_type(cls)  # N: Revealed type is \"type[__main__.A[T`1]]\"\n\n[builtins fixtures/classmethod.pyi]\n\n[case testAttrsForwardReference]\n# flags: --no-strict-optional\nimport attr\n@attr.s(auto_attribs=True)\nclass A:\n    parent: 'B'\n\n@attr.s(auto_attribs=True)\nclass B:\n    parent: A\n\nreveal_type(A) # N: Revealed type is \"def (parent: __main__.B) -> __main__.A\"\nreveal_type(B) # N: Revealed type is \"def (parent: __main__.A) -> __main__.B\"\nA(B(None))\n[builtins fixtures/list.pyi]\n\n[case testAttrsForwardReferenceInClass]\n# flags: --no-strict-optional\nimport attr\n@attr.s(auto_attribs=True)\nclass A:\n    parent: A.B\n\n    @attr.s(auto_attribs=True)\n    class B:\n        parent: A\n\nreveal_type(A) # N: Revealed type is \"def (parent: __main__.A.B) -> __main__.A\"\nreveal_type(A.B) # N: Revealed type is \"def (parent: __main__.A) -> __main__.A.B\"\nA(A.B(None))\n[builtins fixtures/list.pyi]\n\n[case testAttrsImporting]\nfrom helper import A\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int, b: builtins.str) -> helper.A\"\n[file helper.py]\nimport attr\n@attr.s(auto_attribs=True)\nclass A:\n   a: int\n   b: str = attr.ib()\n[builtins fixtures/list.pyi]\n\n[case testAttrsOtherMethods]\nimport attr\n@attr.s(auto_attribs=True)\nclass A:\n    a: int\n    b: str = attr.ib()\n    @classmethod\n    def new(cls) -> A:\n       reveal_type(cls)  # N: Revealed type is \"type[__main__.A]\"\n       return cls(6, 'hello')\n    @classmethod\n    def bad(cls) -> A:\n        return cls(17)  # E: Missing positional argument \"b\" in call to \"A\"\n    def foo(self) -> int:\n       return self.a\nreveal_type(A)  # N: Revealed type is \"def (a: builtins.int, b: builtins.str) -> __main__.A\"\na = A.new()\nreveal_type(a.foo) # N: Revealed type is \"def () -> builtins.int\"\n[builtins fixtures/classmethod.pyi]\n\n[case testAttrsOtherOverloads]\nimport attr\nfrom typing import overload, Union\n\n@attr.s\nclass A:\n    a = attr.ib()\n    b = attr.ib(default=3)\n\n    @classmethod\n    def other(cls) -> str:\n        return \"...\"\n\n    @overload\n    @classmethod\n    def foo(cls, x: int) -> int: ...\n\n    @overload\n    @classmethod\n    def foo(cls, x: str) -> str: ...\n\n    @classmethod\n    def foo(cls, x: Union[int, str]) -> Union[int, str]:\n        reveal_type(cls)            # N: Revealed type is \"type[__main__.A]\"\n        reveal_type(cls.other())    # N: Revealed type is \"builtins.str\"\n        return x\n\nreveal_type(A.foo(3))      # N: Revealed type is \"builtins.int\"\nreveal_type(A.foo(\"foo\"))  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/classmethod.pyi]\n\n[case testAttrsDefaultDecorator]\nimport attr\n@attr.s\nclass C(object):\n    x: int = attr.ib(default=1)\n    y: int = attr.ib()\n    @y.default\n    def name_does_not_matter(self):\n        return self.x + 1\nC()\n[builtins fixtures/list.pyi]\n\n[case testAttrsValidatorDecorator]\nimport attr\n@attr.s\nclass C(object):\n    x = attr.ib()\n    @x.validator\n    def check(self, attribute, value):\n        if value > 42:\n            raise ValueError(\"x must be smaller or equal to 42\")\nC(42)\nC(43)\n[builtins fixtures/exception.pyi]\n\n[case testAttrsLocalVariablesInClassMethod]\nimport attr\n@attr.s(auto_attribs=True)\nclass A:\n    a: int\n    b: int = attr.ib()\n    @classmethod\n    def new(cls, foo: int) -> A:\n       a = foo\n       b = a\n       return cls(a, b)\n[builtins fixtures/classmethod.pyi]\n\n[case testAttrsUnionForward]\nimport attr\nfrom typing import Union, List\n\n@attr.s(auto_attribs=True)\nclass A:\n    frob: List['AOrB']\n\nclass B:\n   pass\n\nAOrB = Union[A, B]\n\nreveal_type(A)  # N: Revealed type is \"def (frob: builtins.list[__main__.A | __main__.B]) -> __main__.A\"\nreveal_type(B)  # N: Revealed type is \"def () -> __main__.B\"\n\nA([B()])\n[builtins fixtures/list.pyi]\n\n[case testAttrsUsingConvert]\nimport attr\n\ndef convert(s:int) -> str:\n    return 'hello'\n\n@attr.s\nclass C:\n    x: str = attr.ib(convert=convert)  # E: convert is deprecated, use converter\n\n# Because of the convert the __init__ takes an int, but the variable is a str.\nreveal_type(C)  # N: Revealed type is \"def (x: builtins.int) -> __main__.C\"\nreveal_type(C(15).x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsUsingConverter]\nimport attr\nimport helper\n\ndef converter2(s:int) -> str:\n    return 'hello'\n\n@attr.s\nclass C:\n    x: str = attr.ib(converter=helper.converter)\n    y: str = attr.ib(converter=converter2)\n\n# Because of the converter the __init__ takes an int, but the variable is a str.\nreveal_type(C)  # N: Revealed type is \"def (x: builtins.int, y: builtins.int) -> __main__.C\"\nreveal_type(C(15, 16).x)  # N: Revealed type is \"builtins.str\"\n[file helper.py]\ndef converter(s:int) -> str:\n    return 'hello'\n[builtins fixtures/list.pyi]\n\n[case testAttrsUsingConvertAndConverter]\nimport attr\n\ndef converter(s:int) -> str:\n    return 'hello'\n\n@attr.s\nclass C:\n    x: str = attr.ib(converter=converter, convert=converter)  # E: Can't pass both \"convert\" and \"converter\".\n\n[builtins fixtures/list.pyi]\n\n[case testAttrsUsingBadConverter]\n# flags: --no-strict-optional\nimport attr\nfrom typing import overload\n@overload\ndef bad_overloaded_converter(x: int, y: int) -> int:\n    ...\n@overload\ndef bad_overloaded_converter(x: str, y: str) -> str:\n    ...\ndef bad_overloaded_converter(x, y=7):\n    return x\ndef bad_converter() -> str:\n    return ''\n@attr.dataclass\nclass A:\n    bad: str = attr.ib(converter=bad_converter)\n    bad_overloaded: int = attr.ib(converter=bad_overloaded_converter)\nreveal_type(A)\n[out]\nmain:16: error: Cannot determine __init__ type from converter\nmain:16: error: Argument \"converter\" has incompatible type \"Callable[[], str]\"; expected \"Callable[[Any], str]\"\nmain:17: error: Cannot determine __init__ type from converter\nmain:17: error: Argument \"converter\" has incompatible type overloaded function; expected \"Callable[[Any], int]\"\nmain:18: note: Revealed type is \"def (bad: Any, bad_overloaded: Any) -> __main__.A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsUsingBadConverterReprocess]\n# flags: --no-strict-optional\nimport attr\nfrom typing import overload\nforward: 'A'\n@overload\ndef bad_overloaded_converter(x: int, y: int) -> int:\n    ...\n@overload\ndef bad_overloaded_converter(x: str, y: str) -> str:\n    ...\ndef bad_overloaded_converter(x, y=7):\n    return x\ndef bad_converter() -> str:\n    return ''\n@attr.dataclass\nclass A:\n    bad: str = attr.ib(converter=bad_converter)\n    bad_overloaded: int = attr.ib(converter=bad_overloaded_converter)\nreveal_type(A)\n[out]\nmain:17: error: Cannot determine __init__ type from converter\nmain:17: error: Argument \"converter\" has incompatible type \"Callable[[], str]\"; expected \"Callable[[Any], str]\"\nmain:18: error: Cannot determine __init__ type from converter\nmain:18: error: Argument \"converter\" has incompatible type overloaded function; expected \"Callable[[Any], int]\"\nmain:19: note: Revealed type is \"def (bad: Any, bad_overloaded: Any) -> __main__.A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsUsingUnsupportedConverter]\nimport attr\nclass Thing:\n    def do_it(self, int) -> str:\n        ...\nthing = Thing()\ndef factory(default: int):\n   ...\n@attr.s\nclass C:\n    x: str = attr.ib(converter=thing.do_it)  # E: Unsupported converter, only named functions, types and lambdas are currently supported\n    y: str = attr.ib(converter=lambda x: x)\n    z: str = attr.ib(converter=factory(8))   # E: Unsupported converter, only named functions, types and lambdas are currently supported\nreveal_type(C)  # N: Revealed type is \"def (x: Any, y: Any, z: Any) -> __main__.C\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsUsingConverterAndSubclass]\nimport attr\n\ndef converter(s:int) -> str:\n    return 'hello'\n\n@attr.s\nclass C:\n    x: str = attr.ib(converter=converter)\n\n@attr.s\nclass A(C):\n    pass\n\n# Because of the convert the __init__ takes an int, but the variable is a str.\nreveal_type(A)  # N: Revealed type is \"def (x: builtins.int) -> __main__.A\"\nreveal_type(A(15).x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsUsingConverterWithTypes]\nfrom typing import overload\nimport attr\n\n@attr.dataclass\nclass A:\n    x: str\n\n@attr.s\nclass C:\n    x: complex = attr.ib(converter=complex)\n    y: int = attr.ib(converter=int)\n    z: A = attr.ib(converter=A)\n\no = C(\"1\", \"2\", \"3\")\no = C(1, 2, \"3\")\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsCmpWithSubclasses]\nimport attr\n@attr.s\nclass A: pass\n@attr.s\nclass B: pass\n@attr.s\nclass C(A, B): pass\n@attr.s\nclass D(A): pass\n\nreveal_type(A.__lt__)  # N: Revealed type is \"def [_AT] (self: _AT`29, other: _AT`29) -> builtins.bool\"\nreveal_type(B.__lt__)  # N: Revealed type is \"def [_AT] (self: _AT`30, other: _AT`30) -> builtins.bool\"\nreveal_type(C.__lt__)  # N: Revealed type is \"def [_AT] (self: _AT`31, other: _AT`31) -> builtins.bool\"\nreveal_type(D.__lt__)  # N: Revealed type is \"def [_AT] (self: _AT`32, other: _AT`32) -> builtins.bool\"\n\nA() < A()\nB() < B()\nA() < B() # E: Unsupported operand types for < (\"A\" and \"B\")\n\nC() > A()\nC() > B()\nC() > C()\nC() > D() # E: Unsupported operand types for > (\"C\" and \"D\")\n\nD() >= A()\nD() >= B()  # E: Unsupported operand types for >= (\"D\" and \"B\")\nD() >= C()  # E: Unsupported operand types for >= (\"D\" and \"C\")\nD() >= D()\n\nA() <= 1  # E: Unsupported operand types for <= (\"A\" and \"int\")\nB() <= 1  # E: Unsupported operand types for <= (\"B\" and \"int\")\nC() <= 1  # E: Unsupported operand types for <= (\"C\" and \"int\")\nD() <= 1  # E: Unsupported operand types for <= (\"D\" and \"int\")\n\n[builtins fixtures/list.pyi]\n\n[case testAttrsComplexSuperclass]\nimport attr\n@attr.s\nclass C:\n    x: int = attr.ib(default=1)\n    y: int = attr.ib()\n    @y.default\n    def name_does_not_matter(self):\n        return self.x + 1\n@attr.s\nclass A(C):\n    z: int = attr.ib(default=18)\nreveal_type(C)  # N: Revealed type is \"def (x: builtins.int =, y: builtins.int =) -> __main__.C\"\nreveal_type(A)  # N: Revealed type is \"def (x: builtins.int =, y: builtins.int =, z: builtins.int =) -> __main__.A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsMultiAssign]\nimport attr\n@attr.s\nclass A:\n   x, y, z = attr.ib(), attr.ib(type=int), attr.ib(default=17)\nreveal_type(A) # N: Revealed type is \"def (x: Any, y: builtins.int, z: Any =) -> __main__.A\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsMultiAssign2]\nimport attr\n@attr.s\nclass A:\n   x = y = z = attr.ib()  # E: Too many names for one attribute\n[builtins fixtures/list.pyi]\n\n[case testAttrsPrivateInit]\nimport attr\n@attr.s\nclass C(object):\n    _x = attr.ib(init=False, default=42)\nC()\nC(_x=42)  # E: Unexpected keyword argument \"_x\" for \"C\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsAliasForInit]\nfrom attrs import define, field\n\n@define\nclass C1:\n    _x: int = field(alias=\"x1\")\n\nc1 = C1(x1=42)\nreveal_type(c1._x)  # N: Revealed type is \"builtins.int\"\nc1.x1  # E: \"C1\" has no attribute \"x1\"\nC1(_x=42)  # E: Unexpected keyword argument \"_x\" for \"C1\"\n\nalias = \"x2\"\n@define\nclass C2:\n    _x: int = field(alias=alias)  # E: \"alias\" argument to attrs field must be a string literal\n\n@define\nclass C3:\n    _x: int = field(alias=\"_x\")\n\nc3 = C3(_x=1)\nreveal_type(c3._x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsAutoMustBeAll]\nimport attr\n@attr.s(auto_attribs=True)\nclass A:\n   a: int\n   b = 17\n   # The following forms are not allowed with auto_attribs=True\n   c = attr.ib()  # E: Need type annotation for \"c\"\n   d, e = attr.ib(), attr.ib() # E: Need type annotation for \"d\" # E: Need type annotation for \"e\"\n   f = g = attr.ib()  # E: Need type annotation for \"f\" # E: Need type annotation for \"g\"\n[builtins fixtures/bool.pyi]\n\n[case testAttrsRepeatedName]\nimport attr\n@attr.s\nclass A:\n   a = attr.ib(default=8)\n   b = attr.ib()\n   a = attr.ib()\nreveal_type(A)  # N: Revealed type is \"def (b: Any, a: Any) -> __main__.A\"\n@attr.s\nclass B:\n   a: int = attr.ib(default=8)\n   b: int = attr.ib()\n   a: int = attr.ib()  # E: Name \"a\" already defined on line 10\nreveal_type(B)  # N: Revealed type is \"def (b: builtins.int, a: builtins.int) -> __main__.B\"\n@attr.s(auto_attribs=True)\nclass C:\n   a: int = 8\n   b: int\n   a: int = attr.ib()  # E: Name \"a\" already defined on line 16\nreveal_type(C)  # N: Revealed type is \"def (a: builtins.int, b: builtins.int) -> __main__.C\"\n[builtins fixtures/bool.pyi]\n\n[case testAttrsFrozenSubclass]\nimport attr\n\n@attr.dataclass\nclass NonFrozenBase:\n    a: int\n\n@attr.dataclass(frozen=True)\nclass FrozenBase:\n    a: int\n\n@attr.dataclass(frozen=True)\nclass FrozenNonFrozen(NonFrozenBase):\n    b: int\n\n@attr.dataclass(frozen=True)\nclass FrozenFrozen(FrozenBase):\n    b: int\n\n@attr.dataclass\nclass NonFrozenFrozen(FrozenBase):\n    b: int\n\n# Make sure these are untouched\nnon_frozen_base = NonFrozenBase(1)\nnon_frozen_base.a = 17\nfrozen_base = FrozenBase(1)\nfrozen_base.a = 17  # E: Property \"a\" defined in \"FrozenBase\" is read-only\n\na = FrozenNonFrozen(1, 2)\na.a = 17  # E: Property \"a\" defined in \"FrozenNonFrozen\" is read-only\na.b = 17  # E: Property \"b\" defined in \"FrozenNonFrozen\" is read-only\n\nb = FrozenFrozen(1, 2)\nb.a = 17  # E: Property \"a\" defined in \"FrozenFrozen\" is read-only\nb.b = 17  # E: Property \"b\" defined in \"FrozenFrozen\" is read-only\n\nc = NonFrozenFrozen(1, 2)\nc.a = 17  # E: Property \"a\" defined in \"NonFrozenFrozen\" is read-only\nc.b = 17  # E: Property \"b\" defined in \"NonFrozenFrozen\" is read-only\n\n[builtins fixtures/plugin_attrs.pyi]\n[case testAttrsCallableAttributes]\nfrom typing import Callable\nimport attr\ndef blah(a: int, b: int) -> bool:\n    return True\n\n@attr.s(auto_attribs=True)\nclass F:\n    _cb: Callable[[int, int], bool] = blah\n    def foo(self) -> bool:\n        return self._cb(5, 6)\n\n@attr.s\nclass G:\n    _cb: Callable[[int, int], bool] = attr.ib(blah)\n    def foo(self) -> bool:\n        return self._cb(5, 6)\n\n@attr.s(auto_attribs=True, frozen=True)\nclass FFrozen(F):\n    def bar(self) -> bool:\n        return self._cb(5, 6)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsWithFactory]\nfrom typing import List\nimport attr\ndef my_factory() -> int:\n    return 7\n@attr.s\nclass A:\n    x: List[int] = attr.ib(factory=list)\n    y: int = attr.ib(factory=my_factory)\nA()\n[builtins fixtures/list.pyi]\n\n[case testAttrsFactoryAndDefault]\nimport attr\n@attr.s\nclass A:\n    x: int = attr.ib(factory=int, default=7)  # E: Can't pass both \"default\" and \"factory\".\n[builtins fixtures/bool.pyi]\n\n[case testAttrsFactoryBadReturn]\nimport attr\ndef my_factory() -> int:\n    return 7\n@attr.s\nclass A:\n    x: int = attr.ib(factory=list)  # E: Incompatible types in assignment (expression has type \"list[Never]\", variable has type \"int\")\n    y: str = attr.ib(factory=my_factory) # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n[builtins fixtures/list.pyi]\n\n[case testAttrsDefaultAndInit]\nimport attr\n\n@attr.s\nclass C:\n   a = attr.ib(init=False, default=42)\n   b = attr.ib()  # Ok because previous attribute is init=False\n   c = attr.ib(default=44)\n   d = attr.ib(init=False)  # Ok because this attribute is init=False\n   e = attr.ib()  # E: Non-default attributes not allowed after default attributes.\n\n[builtins fixtures/bool.pyi]\n\n[case testAttrsOptionalConverter]\nimport attr\nfrom attr.converters import optional\nfrom typing import Optional\n\ndef converter(s:int) -> str:\n    return 'hello'\n\n\n@attr.s\nclass A:\n    y: Optional[int] = attr.ib(converter=optional(int))\n    z: Optional[str] = attr.ib(converter=optional(converter))\n\n\nA(None, None)\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsOptionalConverterNewPackage]\nimport attrs\nfrom attrs.converters import optional\nfrom typing import Optional\n\ndef converter(s:int) -> str:\n    return 'hello'\n\n\n@attrs.define\nclass A:\n    y: Optional[int] = attrs.field(converter=optional(int))\n    z: Optional[str] = attrs.field(converter=optional(converter))\n\n\nA(None, None)\n\n[builtins fixtures/plugin_attrs.pyi]\n\n\n[case testAttrsTypeVarNoCollision]\nfrom typing import TypeVar, Generic\nimport attr\n\nT = TypeVar(\"T\", bytes, str)\n\n# Make sure the generated __le__ (and friends) don't use T for their arguments.\n@attr.s(auto_attribs=True)\nclass A(Generic[T]):\n    v: T\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsKwOnlyAttrib]\nimport attr\n@attr.s\nclass A:\n    a = attr.ib(kw_only=True)\nA()  # E: Missing named argument \"a\" for \"A\"\nA(15) # E: Too many positional arguments for \"A\"\nA(a=15)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsKwOnlyClass]\nimport attr\n@attr.s(kw_only=True, auto_attribs=True)\nclass A:\n    a: int\n    b: bool\nA()  # E: Missing named argument \"a\" for \"A\" # E: Missing named argument \"b\" for \"A\"\nA(b=True, a=15)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsKwOnlyClassNoInit]\nimport attr\n@attr.s(kw_only=True)\nclass B:\n    a = attr.ib(init=False)\n    b = attr.ib()\nB(b=True)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsKwOnlyWithDefault]\nimport attr\n@attr.s\nclass C:\n    a = attr.ib(0)\n    b = attr.ib(kw_only=True)\n    c = attr.ib(16, kw_only=True)\nC(b=17)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsKwOnlyClassWithMixedDefaults]\nimport attr\n@attr.s(kw_only=True)\nclass D:\n    a = attr.ib(10)\n    b = attr.ib()\n    c = attr.ib(15)\nD(b=17)\n[builtins fixtures/plugin_attrs.pyi]\n\n\n[case testAttrsKwOnlyClassAttributeFalse]\nfrom attrs import define, field\n@define(kw_only=True)\nclass A:\n    a: int = field(kw_only=False)\n    b: int = 1\nA(0)\nA(1, b=3)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsKwOnlyClassAttributeFalseSubclass]\nfrom attrs import define, field\n@define(kw_only=True)\nclass A:\n    a: int = field(kw_only=False)\n    b: int = 1\n@define(kw_only=True)\nclass B(A):\n    c: int = field(kw_only=False)\n    d: int = 3\n\nB(0, 1)\nB(0, 1, b=3, d=4)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsKwOnlyClassAttributeFalseSubclassOnly]\nfrom attrs import define, field\n@define\nclass A:\n    a: int\n    b: int = field(kw_only=True, default=1)\n@define(kw_only=True)\nclass B(A):\n    c: int = field(kw_only=False)\n    d: int = 3\n\nB(0, 1)\nB(0, 1, b=3, d=4)\n[builtins fixtures/plugin_attrs.pyi]\n\n\n[case testAttrsKwOnlySubclass]\nimport attr\n@attr.s\nclass A2:\n     a = attr.ib(default=0)\n@attr.s\nclass B2(A2):\n    b = attr.ib(kw_only=True)\nB2(b=1)\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsNonKwOnlyAfterKwOnly]\nimport attr\n@attr.s(kw_only=True)\nclass A:\n     a = attr.ib(default=0)\n@attr.s\nclass B(A):\n    b = attr.ib()\n@attr.s\nclass C:\n    a = attr.ib(kw_only=True)\n    b = attr.ib(15)\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsDisallowUntypedWorksForward]\n# flags: --disallow-untyped-defs\nimport attr\nfrom typing import List\n\n@attr.s\nclass B:\n    x: C = attr.ib()\n\nclass C(List[C]):\n    pass\n\nreveal_type(B)  # N: Revealed type is \"def (x: __main__.C) -> __main__.B\"\n[builtins fixtures/list.pyi]\n\n[case testDisallowUntypedWorksForwardBad]\n# flags: --disallow-untyped-defs\nimport attr\n\n@attr.s\nclass B:\n    x = attr.ib()  # E: Need type annotation for \"x\"\n\nreveal_type(B)  # N: Revealed type is \"def (x: Any) -> __main__.B\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsDefaultDecoratorDeferred]\ndefer: Yes\n\nimport attr\n@attr.s\nclass C(object):\n    x: int = attr.ib(default=1)\n    y: int = attr.ib()\n    @y.default\n    def inc(self):\n        return self.x + 1\n\nclass Yes: ...\n[builtins fixtures/list.pyi]\n\n[case testAttrsValidatorDecoratorDeferred]\ndefer: Yes\n\nimport attr\n@attr.s\nclass C(object):\n    x = attr.ib()\n    @x.validator\n    def check(self, attribute, value):\n        if value > 42:\n            raise ValueError(\"x must be smaller or equal to 42\")\nC(42)\nC(43)\n\nclass Yes: ...\n[builtins fixtures/exception.pyi]\n\n[case testTypeInAttrUndefined]\nimport attr\n\n@attr.s\nclass C:\n    total = attr.ib(type=Bad)  # E: Name \"Bad\" is not defined\n[builtins fixtures/bool.pyi]\n\n[case testTypeInAttrForwardInRuntime]\nimport attr\n\n@attr.s\nclass C:\n    total = attr.ib(type=Forward)\n\nreveal_type(C.total)  # N: Revealed type is \"__main__.Forward\"\nC('no')  # E: Argument 1 to \"C\" has incompatible type \"str\"; expected \"Forward\"\nclass Forward: ...\n[builtins fixtures/bool.pyi]\n\n[case testDefaultInAttrForward]\nimport attr\n\n@attr.s\nclass C:\n    total = attr.ib(default=func())\n\ndef func() -> int: ...\n\nC()\nC(1)\nC(1, 2)  # E: Too many arguments for \"C\"\n[builtins fixtures/bool.pyi]\n\n[case testTypeInAttrUndefinedFrozen]\nimport attr\n\n@attr.s(frozen=True)\nclass C:\n    total = attr.ib(type=Bad)  # E: Name \"Bad\" is not defined\n\nC(0).total = 1  # E: Property \"total\" defined in \"C\" is read-only\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testTypeInAttrDeferredStar]\nimport lib\n[file lib.py]\nimport attr\nMYPY = False\nif MYPY:  # Force deferral\n    from other import *\n\n@attr.s\nclass C:\n    total = attr.ib(type=int)\n\nC()  # E: Missing positional argument \"total\" in call to \"C\"\nC('no')  # E: Argument 1 to \"C\" has incompatible type \"str\"; expected \"int\"\n[file other.py]\nimport lib\n[builtins fixtures/bool.pyi]\n\n[case testAttrsDefaultsMroOtherFile]\nimport a\n\n[file a.py]\nimport attr\nfrom b import A1, A2\n\n@attr.s\nclass Asdf(A1, A2):  # E: Non-default attributes not allowed after default attributes.\n    pass\n\n[file b.py]\nimport attr\n\n@attr.s\nclass A1:\n    a: str = attr.ib('test')\n\n@attr.s\nclass A2:\n    b: int = attr.ib()\n\n[builtins fixtures/list.pyi]\n\n[case testAttrsInheritanceNoAnnotation]\nimport attr\n\n@attr.s\nclass A:\n    foo = attr.ib()  # type: int\n\nx = 0\n@attr.s\nclass B(A):\n    foo = x\n\nreveal_type(B)  # N: Revealed type is \"def (foo: builtins.int) -> __main__.B\"\n[builtins fixtures/bool.pyi]\n\n[case testAttrsClassHasMagicAttribute]\nimport attr\n\n@attr.s\nclass A:\n    b: int = attr.ib()\n    c: str = attr.ib()\n\nreveal_type(A.__attrs_attrs__)  # N: Revealed type is \"tuple[attr.Attribute[builtins.int], attr.Attribute[builtins.str], fallback=__main__.A.____main___A_AttrsAttributes__]\"\nreveal_type(A.__attrs_attrs__[0])  # N: Revealed type is \"attr.Attribute[builtins.int]\"\nreveal_type(A.__attrs_attrs__.b)  # N: Revealed type is \"attr.Attribute[builtins.int]\"\nA.__attrs_attrs__.x  # E: \"____main___A_AttrsAttributes__\" has no attribute \"x\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsBareClassHasMagicAttribute]\nimport attr\n\n@attr.s\nclass A:\n    b = attr.ib()\n    c = attr.ib()\n\nreveal_type(A.__attrs_attrs__)  # N: Revealed type is \"tuple[attr.Attribute[Any], attr.Attribute[Any], fallback=__main__.A.____main___A_AttrsAttributes__]\"\nreveal_type(A.__attrs_attrs__[0])  # N: Revealed type is \"attr.Attribute[Any]\"\nreveal_type(A.__attrs_attrs__.b)  # N: Revealed type is \"attr.Attribute[Any]\"\nA.__attrs_attrs__.x  # E: \"____main___A_AttrsAttributes__\" has no attribute \"x\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsNGClassHasMagicAttribute]\nimport attr\n\n@attr.define\nclass A:\n    b: int\n    c: str\n\nreveal_type(A.__attrs_attrs__)  # N: Revealed type is \"tuple[attr.Attribute[builtins.int], attr.Attribute[builtins.str], fallback=__main__.A.____main___A_AttrsAttributes__]\"\nreveal_type(A.__attrs_attrs__[0])  # N: Revealed type is \"attr.Attribute[builtins.int]\"\nreveal_type(A.__attrs_attrs__.b)  # N: Revealed type is \"attr.Attribute[builtins.int]\"\nA.__attrs_attrs__.x  # E: \"____main___A_AttrsAttributes__\" has no attribute \"x\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsMagicAttributeProtocol]\nimport attr\nfrom typing import Any, Protocol, Type, ClassVar\n\nclass AttrsInstance(Protocol):\n    __attrs_attrs__: ClassVar[Any]\n\n@attr.define\nclass A:\n    b: int\n    c: str\n\ndef takes_attrs_cls(cls: Type[AttrsInstance]) -> None:\n    pass\n\ndef takes_attrs_instance(inst: AttrsInstance) -> None:\n    pass\n\ntakes_attrs_cls(A)\ntakes_attrs_instance(A(1, \"\"))\n\ntakes_attrs_cls(A(1, \"\"))  # E: Argument 1 to \"takes_attrs_cls\" has incompatible type \"A\"; expected \"type[AttrsInstance]\"\ntakes_attrs_instance(A)  # E: Argument 1 to \"takes_attrs_instance\" has incompatible type \"type[A]\"; expected \"AttrsInstance\" # N: ClassVar protocol member AttrsInstance.__attrs_attrs__ can never be matched by a class object\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsFields]\nimport attr\nfrom attrs import fields as f  # Common usage.\n\n@attr.define\nclass A:\n    b: int\n    c: str\n\nreveal_type(f(A))  # N: Revealed type is \"tuple[attr.Attribute[builtins.int], attr.Attribute[builtins.str], fallback=__main__.A.____main___A_AttrsAttributes__]\"\nreveal_type(f(A)[0])  # N: Revealed type is \"attr.Attribute[builtins.int]\"\nreveal_type(f(A).b)  # N: Revealed type is \"attr.Attribute[builtins.int]\"\nf(A).x  # E: \"____main___A_AttrsAttributes__\" has no attribute \"x\"\n\nfor ff in f(A):\n    reveal_type(ff)  # N: Revealed type is \"attr.Attribute[Any]\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsGenericFields]\nfrom typing import TypeVar\n\nimport attr\nfrom attrs import fields\n\n@attr.define\nclass A:\n    b: int\n    c: str\n\nTA = TypeVar('TA', bound=A)\n\ndef f(t: TA) -> None:\n    reveal_type(fields(t))  # N: Revealed type is \"tuple[attr.Attribute[builtins.int], attr.Attribute[builtins.str], fallback=__main__.A.____main___A_AttrsAttributes__]\"\n    reveal_type(fields(t)[0])  # N: Revealed type is \"attr.Attribute[builtins.int]\"\n    reveal_type(fields(t).b)  # N: Revealed type is \"attr.Attribute[builtins.int]\"\n    fields(t).x  # E: \"____main___A_AttrsAttributes__\" has no attribute \"x\"\n\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testNonattrsFields]\nfrom typing import Any, cast, Type\nfrom attrs import fields, has\n\nclass A:\n    b: int\n    c: str\n\nif has(A):\n    fields(A)\nelse:\n    fields(A)  # E: Argument 1 to \"fields\" has incompatible type \"type[A]\"; expected \"type[AttrsInstance]\"\nfields(None)  # E: Argument 1 to \"fields\" has incompatible type \"None\"; expected \"type[AttrsInstance]\"\nfields(cast(Any, 42))\nfields(cast(Type[Any], 43))\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsInitMethodAlwaysGenerates]\nfrom typing import Tuple\nimport attr\n\n@attr.define(init=False)\nclass A:\n    b: int\n    c: str\n    def __init__(self, bc: Tuple[int, str]) -> None:\n        b, c = bc\n        self.__attrs_init__(b, c)\n\nreveal_type(A)  # N: Revealed type is \"def (bc: tuple[builtins.int, builtins.str]) -> __main__.A\"\nreveal_type(A.__init__)  # N: Revealed type is \"def (self: __main__.A, bc: tuple[builtins.int, builtins.str])\"\nreveal_type(A.__attrs_init__)  # N: Revealed type is \"def (self: __main__.A, b: builtins.int, c: builtins.str)\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsClassWithSlots]\nimport attr\n\n@attr.define\nclass Define:\n    b: int = attr.ib()\n\n    def __attrs_post_init__(self) -> None:\n        self.b = 1\n        self.c = 2  # E: Trying to assign name \"c\" that is not in \"__slots__\" of type \"__main__.Define\"\n\n\n@attr.define(slots=False)\nclass DefineSlotsFalse:\n    b: int = attr.ib()\n\n    def __attrs_post_init__(self) -> None:\n        self.b = 1\n        self.c = 2\n\n\n@attr.s(slots=True)\nclass A:\n    b: int = attr.ib()\n\n    def __attrs_post_init__(self) -> None:\n        self.b = 1\n        self.c = 2  # E: Trying to assign name \"c\" that is not in \"__slots__\" of type \"__main__.A\"\n\n@attr.dataclass(slots=True)\nclass B:\n    __slots__ = ()  # would be replaced\n    b: int\n\n    def __attrs_post_init__(self) -> None:\n        self.b = 1\n        self.c = 2  # E: Trying to assign name \"c\" that is not in \"__slots__\" of type \"__main__.B\"\n\n@attr.dataclass(slots=False)\nclass C:\n    __slots__ = ()  # would not be replaced\n    b: int\n\n    def __attrs_post_init__(self) -> None:\n        self.b = 1  # E: Trying to assign name \"b\" that is not in \"__slots__\" of type \"__main__.C\"\n        self.c = 2  # E: Trying to assign name \"c\" that is not in \"__slots__\" of type \"__main__.C\"\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsClassWithSlotsDerivedFromNonSlots]\nimport attrs\n\nclass A:\n    pass\n\n@attrs.define(slots=True)\nclass B(A):\n    x: int\n\n    def __attrs_post_init__(self) -> None:\n        self.y = 42\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testRuntimeSlotsAttr]\nfrom attr import dataclass\n\n@dataclass(slots=True)\nclass Some:\n    x: int\n    y: str\n    z: bool\n\nreveal_type(Some.__slots__)  # N: Revealed type is \"tuple[builtins.str, builtins.str, builtins.str]\"\n\n@dataclass(slots=True)\nclass Other:\n    x: int\n    y: str\n\nreveal_type(Other.__slots__)  # N: Revealed type is \"tuple[builtins.str, builtins.str]\"\n\n\n@dataclass\nclass NoSlots:\n    x: int\n    y: str\n\nNoSlots.__slots__  # E: \"type[NoSlots]\" has no attribute \"__slots__\"\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsWithMatchArgs]\n# flags: --python-version 3.10\nimport attr\n\n@attr.s(match_args=True, auto_attribs=True)\nclass ToMatch:\n    x: int\n    y: int\n    # Not included:\n    z: int = attr.field(kw_only=True)\n    i: int = attr.field(init=False)\n\nreveal_type(ToMatch(x=1, y=2, z=3).__match_args__)  # N: Revealed type is \"tuple[Literal['x']?, Literal['y']?]\"\nreveal_type(ToMatch(1, 2, z=3).__match_args__)      # N: Revealed type is \"tuple[Literal['x']?, Literal['y']?]\"\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsWithMatchArgsDefaultCase]\n# flags: --python-version 3.10\nimport attr\n\n@attr.s(auto_attribs=True)\nclass ToMatch1:\n    x: int\n    y: int\n\nt1: ToMatch1\nreveal_type(t1.__match_args__)  # N: Revealed type is \"tuple[Literal['x']?, Literal['y']?]\"\n\n@attr.define\nclass ToMatch2:\n    x: int\n    y: int\n\nt2: ToMatch2\nreveal_type(t2.__match_args__)  # N: Revealed type is \"tuple[Literal['x']?, Literal['y']?]\"\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsWithMatchArgsOverrideExisting]\n# flags: --python-version 3.10\nimport attr\nfrom typing import Final\n\n@attr.s(match_args=True, auto_attribs=True)\nclass ToMatch:\n    __match_args__: Final = ('a', 'b')\n    x: int\n    y: int\n\n# It works the same way runtime does:\nreveal_type(ToMatch(x=1, y=2).__match_args__)  # N: Revealed type is \"tuple[Literal['a']?, Literal['b']?]\"\n\n@attr.s(auto_attribs=True)\nclass WithoutMatch:\n    __match_args__: Final = ('a', 'b')\n    x: int\n    y: int\n\nreveal_type(WithoutMatch(x=1, y=2).__match_args__)  # N: Revealed type is \"tuple[Literal['a']?, Literal['b']?]\"\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsWithMatchArgsOldVersion]\n# flags: --python-version 3.9\nimport attr\n\n@attr.s(match_args=True)\nclass NoMatchArgs:\n    ...\n\nn: NoMatchArgs\n\nreveal_type(n.__match_args__)  # E: \"NoMatchArgs\" has no attribute \"__match_args__\" \\\n                               # N: Revealed type is \"Any\"\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsMultipleInheritance]\n# flags: --python-version 3.10\nimport attr\n\n@attr.s\nclass A:\n    x = attr.ib(type=int)\n\n@attr.s\nclass B:\n    y = attr.ib(type=int)\n\nclass AB(A, B):\n    pass\n[builtins fixtures/plugin_attrs.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testAttrsForwardReferenceInTypeVarBound]\nfrom typing import TypeVar, Generic\nimport attr\n\nT = TypeVar(\"T\", bound=\"C\")\n\n@attr.define\nclass D(Generic[T]):\n    x: int\n\nclass C:\n    pass\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testComplexTypeInAttrIb]\nimport a\n\n[file a.py]\nimport attr\nimport b\nfrom typing import Callable\n\n@attr.s\nclass C:\n    a = attr.ib(type=Lst[int])  # E: Name \"Lst\" is not defined\n    # Note that for this test, the 'Value of type \"int\" is not indexable' errors are silly,\n    # and a consequence of Callable etc. being set to an int in the test stub.\n    b = attr.ib(type=Callable[[], C])  # E: Value of type \"int\" is not indexable\n[file b.py]\nimport attr\nimport a\nfrom typing import List as Lst, Optional\n\n@attr.s\nclass D:\n    a = attr.ib(type=Lst[int])\n    b = attr.ib(type=Optional[int])  # E: Value of type \"int\" is not indexable\n[builtins fixtures/list.pyi]\n\n[case testAttrsGenericInheritanceSpecialCase1]\nimport attr\nfrom typing import Generic, TypeVar, List\n\nT = TypeVar(\"T\")\n\n@attr.define\nclass Parent(Generic[T]):\n    x: List[T]\n\n@attr.define\nclass Child1(Parent[\"Child2\"]): ...\n\n@attr.define\nclass Child2(Parent[\"Child1\"]): ...\n\ndef f(c: Child2) -> None:\n    reveal_type(Child1([c]).x)  # N: Revealed type is \"builtins.list[__main__.Child2]\"\n\ndef g(c: Child1) -> None:\n    reveal_type(Child2([c]).x)  # N: Revealed type is \"builtins.list[__main__.Child1]\"\n[builtins fixtures/list.pyi]\n\n[case testAttrsGenericInheritanceSpecialCase2]\nimport attr\nfrom typing import Generic, TypeVar\n\nT = TypeVar(\"T\")\n\n# A subclass might be analyzed before base in import cycles.  They are\n# defined here in reversed order to simulate this.\n\n@attr.define\nclass Child1(Parent[\"Child2\"]):\n    x: int\n\n@attr.define\nclass Child2(Parent[\"Child1\"]):\n    y: int\n\n@attr.define\nclass Parent(Generic[T]):\n    key: str\n\nChild1(x=1, key='')\nChild2(y=1, key='')\n[builtins fixtures/list.pyi]\n\n[case testAttrsUnsupportedConverterWithDisallowUntypedDefs]\n# flags: --disallow-untyped-defs\nimport attr\nfrom typing import Mapping, Any, Union\n\ndef default_if_none(factory: Any) -> Any: pass\n\n@attr.s(slots=True, frozen=True)\nclass C:\n    name: Union[str, None] = attr.ib(default=None)\n    options: Mapping[str, Mapping[str, Any]] = attr.ib(\n        default=None, converter=default_if_none(factory=dict) \\\n        # E: Unsupported converter, only named functions, types and lambdas are currently supported\n    )\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsUnannotatedConverter]\nimport attr\n\ndef foo(value):\n    return value.split()\n\n@attr.s\nclass Bar:\n    field = attr.ib(default=None, converter=foo)\n\nreveal_type(Bar)  # N: Revealed type is \"def (field: Any =) -> __main__.Bar\"\nbar = Bar(\"Hello\")\nreveal_type(bar.field)  # N: Revealed type is \"Any\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testAttrsLambdaConverter]\nimport attr\n\n@attr.s\nclass Bar:\n    name: str = attr.ib(converter=lambda s: s.lower())\n\nreveal_type(Bar)  # N: Revealed type is \"def (name: Any) -> __main__.Bar\"\nbar = Bar(\"Hello\")\nreveal_type(bar.name)  # N: Revealed type is \"builtins.str\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testAttrsNestedClass]\nfrom typing import List\nimport attr\n\n@attr.s\nclass C:\n    @attr.s\n    class D:\n        pass\n    x = attr.ib(type=List[D])\n\nc = C(x=[C.D()])\nreveal_type(c.x)  # N: Revealed type is \"builtins.list[__main__.C.D]\"\n[builtins fixtures/list.pyi]\n\n[case testRedefinitionInFrozenClassNoCrash]\nimport attr\n\n@attr.s\nclass MyData:\n    is_foo: bool = attr.ib()\n\n    @staticmethod  # E: Name \"is_foo\" already defined on line 5\n    def is_foo(string: str) -> bool: ...\n[builtins fixtures/classmethod.pyi]\n\n[case testOverrideWithPropertyInFrozenClassNoCrash]\nfrom attrs import frozen\n\n@frozen(kw_only=True)\nclass Base:\n    name: str\n\n@frozen(kw_only=True)\nclass Sub(Base):\n    first_name: str\n    last_name: str\n\n    @property\n    def name(self) -> str: ...\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testOverrideWithPropertyInFrozenClassChecked]\nfrom attrs import frozen\n\n@frozen(kw_only=True)\nclass Base:\n    name: str\n\n@frozen(kw_only=True)\nclass Sub(Base):\n    first_name: str\n    last_name: str\n\n    @property\n    def name(self) -> int: ...  # E: Signature of \"name\" incompatible with supertype \"Base\" \\\n                                # N:      Superclass: \\\n                                # N:          str \\\n                                # N:      Subclass: \\\n                                # N:          int\n\n# This matches runtime semantics\nreveal_type(Sub)  # N: Revealed type is \"def (*, name: builtins.str, first_name: builtins.str, last_name: builtins.str) -> __main__.Sub\"\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testFinalInstanceAttribute]\nfrom attrs import define\nfrom typing import Final\n\n@define\nclass C:\n    a: Final[int]\n\nreveal_type(C) # N: Revealed type is \"def (a: builtins.int) -> __main__.C\"\n\nC(1).a = 2 # E: Cannot assign to final attribute \"a\"\n\n[builtins fixtures/property.pyi]\n\n[case testFinalInstanceAttributeInheritance]\nfrom attrs import define\nfrom typing import Final\n\n@define\nclass C:\n    a: Final[int]\n\n@define\nclass D(C):\n    b: Final[str]\n\nreveal_type(D) # N: Revealed type is \"def (a: builtins.int, b: builtins.str) -> __main__.D\"\n\nD(1, \"\").a = 2 # E: Cannot assign to final attribute \"a\"\nD(1, \"\").b = \"2\" # E: Cannot assign to final attribute \"b\"\n\n[builtins fixtures/property.pyi]\n\n[case testEvolve]\nimport attr\n\nclass Base:\n    pass\n\nclass Derived(Base):\n    pass\n\nclass Other:\n    pass\n\n@attr.s(auto_attribs=True)\nclass C:\n    name: str\n    b: Base\n\nc = C(name='foo', b=Derived())\nc = attr.evolve(c)\nc = attr.evolve(c, name='foo')\nc = attr.evolve(c, 'foo')  # E: Too many positional arguments for \"evolve\" of \"C\"\nc = attr.evolve(c, b=Derived())\nc = attr.evolve(c, b=Base())\nc = attr.evolve(c, b=Other())  # E: Argument \"b\" to \"evolve\" of \"C\" has incompatible type \"Other\"; expected \"Base\"\nc = attr.evolve(c, name=42)  # E: Argument \"name\" to \"evolve\" of \"C\" has incompatible type \"int\"; expected \"str\"\nc = attr.evolve(c, foobar=42)  # E: Unexpected keyword argument \"foobar\" for \"evolve\" of \"C\"\n\n# test passing instance as 'inst' kw\nc = attr.evolve(inst=c, name='foo')\nc = attr.evolve(not_inst=c, name='foo')  # E: Missing positional argument \"inst\" in call to \"evolve\"\n\n# test determining type of first argument's expression from something that's not NameExpr\ndef f() -> C:\n    return c\n\nc = attr.evolve(f(), name='foo')\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testEvolveFromNonAttrs]\nimport attr\n\nattr.evolve(42, name='foo')  # E: Argument 1 to \"evolve\" has incompatible type \"int\"; expected an attrs class\nattr.evolve(None, name='foo')  # E: Argument 1 to \"evolve\" has incompatible type \"None\"; expected an attrs class\n[case testEvolveFromAny]\nfrom typing import Any\nimport attr\n\nany: Any = 42\nret = attr.evolve(any, name='foo')\nreveal_type(ret)  # N: Revealed type is \"Any\"\n\n[typing fixtures/typing-medium.pyi]\n\n[case testEvolveGeneric]\nimport attrs\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\n@attrs.define\nclass A(Generic[T]):\n    x: T\n\n\na = A(x=42)\nreveal_type(a)  # N: Revealed type is \"__main__.A[builtins.int]\"\na2 = attrs.evolve(a, x=42)\nreveal_type(a2)  # N: Revealed type is \"__main__.A[builtins.int]\"\na2 = attrs.evolve(a, x='42')  # E: Argument \"x\" to \"evolve\" of \"A[int]\" has incompatible type \"str\"; expected \"int\"\nreveal_type(a2)  # N: Revealed type is \"__main__.A[builtins.int]\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testEvolveUnion]\n# flags: --python-version 3.10\nfrom typing import Generic, TypeVar\nimport attrs\n\nT = TypeVar('T')\n\n\n@attrs.define\nclass A(Generic[T]):\n    x: T  # exercises meet(T=int, int) = int\n    y: bool  # exercises meet(bool, int) = bool\n    z: str  # exercises meet(str, bytes) = Never\n    w: dict  # exercises meet(dict, Never) = Never\n\n\n@attrs.define\nclass B:\n    x: int\n    y: bool\n    z: bytes\n\n\na_or_b: A[int] | B\na2 = attrs.evolve(a_or_b, x=42, y=True)\na2 = attrs.evolve(a_or_b, x=42, y=True, z='42')  # E: Argument \"z\" to \"evolve\" of \"A[int] | B\" has incompatible type \"str\"; expected \"Never\"\na2 = attrs.evolve(a_or_b, x=42, y=True, w={})  # E: Argument \"w\" to \"evolve\" of \"A[int] | B\" has incompatible type \"dict[Never, Never]\"; expected \"Never\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testEvolveUnionOfTypeVar]\n# flags: --python-version 3.10\nimport attrs\nfrom typing import TypeVar\n\n@attrs.define\nclass A:\n    x: int\n    y: int\n    z: str\n    w: dict\n\n\nclass B:\n    pass\n\nTA = TypeVar('TA', bound=A)\nTB = TypeVar('TB', bound=B)\n\ndef f(b_or_t: TA | TB | int) -> None:\n    a2 = attrs.evolve(b_or_t)  # E: Argument 1 to \"evolve\" has type \"TA | TB | int\" whose item \"TB\" is not bound to an attrs class \\\n                               # E: Argument 1 to \"evolve\" has incompatible type \"TA | TB | int\" whose item \"int\" is not an attrs class\n\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testEvolveTypeVarBound]\nimport attrs\nfrom typing import TypeVar\n\n@attrs.define\nclass A:\n    x: int\n\n@attrs.define\nclass B(A):\n    pass\n\nTA = TypeVar('TA', bound=A)\n\ndef f(t: TA) -> TA:\n    t2 = attrs.evolve(t, x=42)\n    reveal_type(t2)  # N: Revealed type is \"TA`-1\"\n    t3 = attrs.evolve(t, x='42')  # E: Argument \"x\" to \"evolve\" of \"TA\" has incompatible type \"str\"; expected \"int\"\n    return t2\n\nf(A(x=42))\nf(B(x=42))\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testEvolveTypeVarBoundNonAttrs]\nimport attrs\nfrom typing import Union, TypeVar\n\nTInt = TypeVar('TInt', bound=int)\nTAny = TypeVar('TAny')\nTNone = TypeVar('TNone', bound=None)\nTUnion = TypeVar('TUnion', bound=Union[str, int])\n\ndef f(t: TInt) -> None:\n    _ = attrs.evolve(t, x=42)  # E: Argument 1 to \"evolve\" has a variable type \"TInt\" not bound to an attrs class\n\ndef g(t: TAny) -> None:\n    _ = attrs.evolve(t, x=42)  # E: Argument 1 to \"evolve\" has a variable type \"TAny\" not bound to an attrs class\n\ndef h(t: TNone) -> None:\n    _ = attrs.evolve(t, x=42)  # E: Argument 1 to \"evolve\" has a variable type \"TNone\" not bound to an attrs class\n\ndef x(t: TUnion) -> None:\n    _ = attrs.evolve(t, x=42)  # E: Argument 1 to \"evolve\" has incompatible type \"TUnion\" whose item \"str\" is not an attrs class \\\n                               # E: Argument 1 to \"evolve\" has incompatible type \"TUnion\" whose item \"int\" is not an attrs class\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testEvolveTypeVarConstrained]\nimport attrs\nfrom typing import TypeVar\n\n@attrs.define\nclass A:\n    x: int\n\n@attrs.define\nclass B:\n    x: str  # conflicting with A.x\n\nT = TypeVar('T', A, B)\n\ndef f(t: T) -> T:\n    t2 = attrs.evolve(t, x=42)  # E: Argument \"x\" to \"evolve\" of \"B\" has incompatible type \"int\"; expected \"str\"\n    reveal_type(t2)  # N: Revealed type is \"__main__.A\"  # N: Revealed type is \"__main__.B\"\n    t2 = attrs.evolve(t, x='42')  # E: Argument \"x\" to \"evolve\" of \"A\" has incompatible type \"str\"; expected \"int\"\n    return t2\n\nf(A(x=42))\nf(B(x='42'))\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testEvolveVariants]\nfrom typing import Any\nimport attr\nimport attrs\n\n\n@attr.s(auto_attribs=True)\nclass C:\n    name: str\n\nc = C(name='foo')\n\nc = attr.assoc(c, name='test')\nc = attr.assoc(c, name=42)  # E: Argument \"name\" to \"assoc\" of \"C\" has incompatible type \"int\"; expected \"str\"\n\nc = attrs.evolve(c, name='test')\nc = attrs.evolve(c, name=42)  # E: Argument \"name\" to \"evolve\" of \"C\" has incompatible type \"int\"; expected \"str\"\n\nc = attrs.assoc(c, name='test')\nc = attrs.assoc(c, name=42)  # E: Argument \"name\" to \"assoc\" of \"C\" has incompatible type \"int\"; expected \"str\"\n\n[builtins fixtures/plugin_attrs.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testFrozenInheritFromGeneric]\nfrom typing import Generic, TypeVar\nfrom attrs import field, frozen\n\nT = TypeVar('T')\n\ndef f(s: str) -> int:\n    ...\n\n@frozen\nclass A(Generic[T]):\n    x: T\n    y: int = field(converter=f)\n\n@frozen\nclass B(A[int]):\n    pass\n\nb = B(42, 'spam')\nreveal_type(b.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(b.y)  # N: Revealed type is \"builtins.int\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testDefaultHashability]\nfrom attrs import define\n\n@define\nclass A:\n    a: int\n\nreveal_type(A.__hash__)  # N: Revealed type is \"None\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testFrozenHashability]\nfrom attrs import frozen\n\n@frozen\nclass A:\n    a: int\n\nreveal_type(A.__hash__)  # N: Revealed type is \"def (self: builtins.object) -> builtins.int\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testManualHashHashability]\nfrom attrs import define\n\n@define(hash=True)\nclass A:\n    a: int\n\nreveal_type(A.__hash__)  # N: Revealed type is \"def (self: builtins.object) -> builtins.int\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testManualUnsafeHashHashability]\nfrom attrs import define\n\n@define(unsafe_hash=True)\nclass A:\n    a: int\n\nreveal_type(A.__hash__)  # N: Revealed type is \"def (self: builtins.object) -> builtins.int\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testSubclassingHashability]\nfrom attrs import define\n\n@define(unsafe_hash=True)\nclass A:\n    a: int\n\n@define\nclass B(A):\n    pass\n\nreveal_type(B.__hash__)  # N: Revealed type is \"None\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testManualOwnHashability]\nfrom attrs import define, frozen\n\n@define\nclass A:\n    a: int\n    def __hash__(self) -> int:\n        ...\n\nreveal_type(A.__hash__)  # N: Revealed type is \"def (self: __main__.A) -> builtins.int\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testSubclassDefaultLosesHashability]\nfrom attrs import define, frozen\n\n@define\nclass A:\n    a: int\n    def __hash__(self) -> int:\n        ...\n\n@define\nclass B(A):\n    pass\n\nreveal_type(B.__hash__)  # N: Revealed type is \"None\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testSubclassEqFalseKeepsHashability]\nfrom attrs import define, frozen\n\n@define\nclass A:\n    a: int\n    def __hash__(self) -> int:\n        ...\n\n@define(eq=False)\nclass B(A):\n    pass\n\nreveal_type(B.__hash__)  # N: Revealed type is \"def (self: __main__.A) -> builtins.int\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testSubclassingFrozenHashability]\nfrom attrs import define, frozen\n\n@define\nclass A:\n    a: int\n\n@frozen\nclass B(A):\n    pass\n\nreveal_type(B.__hash__)  # N: Revealed type is \"def (self: builtins.object) -> builtins.int\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testSubclassingFrozenHashOffHashability]\nfrom attrs import define, frozen\n\n@define\nclass A:\n    a: int\n    def __hash__(self) -> int:\n        ...\n\n@frozen(unsafe_hash=False)\nclass B(A):\n    pass\n\nreveal_type(B.__hash__)  # N: Revealed type is \"None\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testUnsafeHashPrecedence]\nfrom attrs import define, frozen\n\n@define(unsafe_hash=True, hash=False)\nclass A:\n    pass\nreveal_type(A.__hash__)  # N: Revealed type is \"def (self: builtins.object) -> builtins.int\"\n\n@define(unsafe_hash=False, hash=True)\nclass B:\n    pass\nreveal_type(B.__hash__)  # N: Revealed type is \"None\"\n\n[builtins fixtures/plugin_attrs.pyi]\n\n[case testAttrsStrictOptionalSetProperly]\nfrom typing import Generic, Optional, TypeVar\n\nimport attr\n\nT = TypeVar(\"T\")\n\n@attr.mutable()\nclass Parent(Generic[T]):\n    run_type: Optional[int] = None\n\n@attr.mutable()\nclass Child(Parent[float]):\n    pass\n\nParent(run_type = None)\nc = Child(run_type = None)\nreveal_type(c.run_type)  # N: Revealed type is \"builtins.int | None\"\n[builtins fixtures/plugin_attrs.pyi]\n"
  },
  {
    "path": "test-data/unit/check-protocols.test",
    "content": "-- Simple protocol types\n-- ---------------------\n\n[case testCannotInstantiateProtocol]\nfrom typing import Protocol\n\nclass P(Protocol):\n    def meth(self) -> None:\n        pass\n\nP() # E: Cannot instantiate protocol class \"P\"\n\n[case testSimpleProtocolOneMethod]\nfrom typing import Protocol\n\nclass P(Protocol):\n    def meth(self) -> None:\n        pass\n\nclass B: pass\nclass C:\n    def meth(self) -> None:\n        pass\n\nx: P\ndef fun(x: P) -> None:\n    x.meth()\n    x.meth(x) # E: Too many arguments for \"meth\" of \"P\"\n    x.bad # E: \"P\" has no attribute \"bad\"\n\nx = C()\nx = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"P\")\n\nfun(C())\nfun(B()) # E: Argument 1 to \"fun\" has incompatible type \"B\"; expected \"P\"\n\ndef fun2() -> P:\n    return C()\ndef fun3() -> P:\n    return B() # E: Incompatible return value type (got \"B\", expected \"P\")\n\n[case testProtocolAttrAccessDecoratedGetAttrDunder]\nfrom typing import Any, Protocol, Callable\n\ndef typed_decorator(fun: Callable) -> Callable[[Any, str], str]:\n    pass\n\ndef untyped_decorator(fun):\n    pass\n\nclass P(Protocol):\n    @property\n    def x(self) -> int:\n        pass\n\nclass A:\n    @untyped_decorator\n    def __getattr__(self, key: str) -> int:\n        pass\n\nclass B:\n    @typed_decorator\n    def __getattr__(self, key: str) -> int:\n        pass\n\nclass C:\n    def __getattr__(self, key: str) -> int:\n        pass\n\ndef fun(x: P) -> None:\n    pass\n\na: A\nreveal_type(a.x)\nfun(a)\n\nb: B\nreveal_type(b.x)\nfun(b)\n\nc: C\nreveal_type(c.x)\nfun(c)\n[out]\nmain:32: note: Revealed type is \"Any\"\nmain:36: note: Revealed type is \"builtins.str\"\nmain:37: error: Argument 1 to \"fun\" has incompatible type \"B\"; expected \"P\"\nmain:37: note: Following member(s) of \"B\" have conflicts:\nmain:37: note:     x: expected \"int\", got \"str\"\nmain:40: note: Revealed type is \"builtins.int\"\n[builtins fixtures/bool.pyi]\n\n[case testSimpleProtocolOneAbstractMethod]\nfrom typing import Protocol\nfrom abc import abstractmethod\n\nclass P(Protocol):\n    @abstractmethod\n    def meth(self) -> None:\n        pass\n\nclass B: pass\nclass C:\n    def meth(self) -> None:\n        pass\nclass D(B):\n    def meth(self) -> None:\n        pass\n\nx: P\ndef fun(x: P) -> None:\n    x.meth()\n    x.meth(x) # E: Too many arguments for \"meth\" of \"P\"\n    x.bad # E: \"P\" has no attribute \"bad\"\n\nx = C()\nx = D()\nx = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"P\")\nfun(C())\nfun(D())\nfun(B()) # E: Argument 1 to \"fun\" has incompatible type \"B\"; expected \"P\"\nfun(x)\n\n[case testProtocolMethodBodies]\nfrom typing import Protocol, List\n\nclass P(Protocol):\n    def meth(self) -> int:\n        return 'no way' # E: Incompatible return value type (got \"str\", expected \"int\")\n\n# explicit ellipsis is OK in protocol methods\nclass P2(Protocol):\n    def meth2(self) -> List[int]:\n        ...\n[builtins fixtures/list.pyi]\n\n[case testSimpleProtocolOneMethodOverride]\nfrom typing import Protocol, Union\n\nclass P(Protocol):\n    def meth(self) -> Union[int, str]:\n        pass\nclass SubP(P, Protocol):\n    def meth(self) -> int:\n        pass\n\nclass B: pass\nclass C:\n    def meth(self) -> int:\n        pass\nz: P\nx: SubP\ndef fun(x: SubP) -> str:\n    x.bad # E: \"SubP\" has no attribute \"bad\"\n    return x.meth() # E: Incompatible return value type (got \"int\", expected \"str\")\n\nz = x\nx = C()\nx = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"SubP\")\n\nreveal_type(fun(C())) # N: Revealed type is \"builtins.str\"\nfun(B()) # E: Argument 1 to \"fun\" has incompatible type \"B\"; expected \"SubP\"\n\n[case testSimpleProtocolTwoMethodsMerge]\nfrom typing import Protocol\n\nclass P1(Protocol):\n    def meth1(self) -> int:\n        pass\nclass P2(Protocol):\n    def meth2(self) -> str:\n        pass\nclass P(P1, P2, Protocol): pass\n\nclass B: pass\nclass C1:\n    def meth1(self) -> int:\n        pass\nclass C2(C1):\n    def meth2(self) -> str:\n        pass\nclass C:\n    def meth1(self) -> int:\n        pass\n    def meth2(self) -> str:\n        pass\n\nclass AnotherP(Protocol):\n    def meth1(self) -> int:\n        pass\n    def meth2(self) -> str:\n        pass\n\nx: P\nreveal_type(x.meth1())  # N: Revealed type is \"builtins.int\"\nreveal_type(x.meth2())  # N: Revealed type is \"builtins.str\"\n\nc: C\nc1: C1\nc2: C2\ny: AnotherP\n\nif int():\n    x = c\nif int():\n    x = B()  # E: Incompatible types in assignment (expression has type \"B\", variable has type \"P\")\nif int():\n    x = c1 # E: Incompatible types in assignment (expression has type \"C1\", variable has type \"P\") \\\n        # N: \"C1\" is missing following \"P\" protocol member: \\\n        # N:     meth2\nif int():\n    x = c2\nif int():\n    x = y\nif int():\n    y = x\n\n[case testSimpleProtocolTwoMethodsExtend]\nfrom typing import Protocol\n\nclass P1(Protocol):\n    def meth1(self) -> int:\n        pass\nclass P2(P1, Protocol):\n    def meth2(self) -> str:\n        pass\n\nclass Cbad:\n    def meth1(self) -> int:\n        pass\n\nclass C:\n    def meth1(self) -> int:\n        pass\n    def meth2(self) -> str:\n        pass\n\nx: P2\nreveal_type(x.meth1()) # N: Revealed type is \"builtins.int\"\nreveal_type(x.meth2()) # N: Revealed type is \"builtins.str\"\n\nif int():\n    x = C() # OK\nif int():\n    x = Cbad() # E: Incompatible types in assignment (expression has type \"Cbad\", variable has type \"P2\") \\\n        # N: \"Cbad\" is missing following \"P2\" protocol member: \\\n        # N:     meth2\n\n[case testProtocolMethodVsAttributeErrors]\nfrom typing import Protocol\n\nclass P(Protocol):\n    def meth(self) -> int:\n        pass\nclass C:\n    meth: int\nx: P = C() # E: Incompatible types in assignment (expression has type \"C\", variable has type \"P\") \\\n           # N: Following member(s) of \"C\" have conflicts: \\\n           # N:     meth: expected \"Callable[[], int]\", got \"int\"\n\n[case testProtocolMethodVsAttributeErrors2]\nfrom typing import Protocol\n\nclass P(Protocol):\n    @property\n    def meth(self) -> int:\n        pass\nclass C:\n    def meth(self) -> int:\n        pass\nx: P = C() # E: Incompatible types in assignment (expression has type \"C\", variable has type \"P\") \\\n           # N: Following member(s) of \"C\" have conflicts: \\\n           # N:     meth: expected \"int\", got \"Callable[[], int]\"\n[builtins fixtures/property.pyi]\n\n[case testCannotAssignNormalToProtocol]\nfrom typing import Protocol\n\nclass P(Protocol):\n    def meth(self) -> int:\n        pass\nclass C:\n    def meth(self) -> int:\n        pass\n\nx: C\ny: P\nx = y # E: Incompatible types in assignment (expression has type \"P\", variable has type \"C\")\n\n[case testIndependentProtocolSubtyping]\nfrom typing import Protocol\n\nclass P1(Protocol):\n    def meth(self) -> int:\n        pass\nclass P2(Protocol):\n    def meth(self) -> int:\n        pass\n\nx1: P1\nx2: P2\n\nx1 = x2\nx2 = x1\n\ndef f1(x: P1) -> None: pass\ndef f2(x: P2) -> None: pass\n\nf1(x2)\nf2(x1)\n\n[case testNoneDisablesProtocolImplementation]\nfrom typing import Protocol\n\nclass MyHashable(Protocol):\n    def __my_hash__(self) -> int:\n        return 0\n\nclass C:\n    __my_hash__ = None\n\nvar: MyHashable = C()  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"MyHashable\") \\\n                       # N: Following member(s) of \"C\" have conflicts: \\\n                       # N:     __my_hash__: expected \"Callable[[], int]\", got \"None\"\n\n[case testNoneDisablesProtocolSubclassingWithStrictOptional]\nfrom typing import Protocol\n\nclass MyHashable(Protocol):\n    def __my_hash__(self) -> int:\n        return 0\n\nclass C(MyHashable):\n    __my_hash__ = None  # E: Incompatible types in assignment \\\n(expression has type \"None\", base class \"MyHashable\" defined the type as \"Callable[[], int]\")\n\n[case testProtocolsWithNoneAndStrictOptional]\nfrom typing import Protocol\nclass P(Protocol):\n    x = 0  # type: int\n\nclass C:\n    x = None\n\nx: P = C() # Error!\ndef f(x: P) -> None: pass\nf(C()) # Error!\n[out]\nmain:8: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\nmain:8: note: Following member(s) of \"C\" have conflicts:\nmain:8: note:     x: expected \"int\", got \"None\"\nmain:10: error: Argument 1 to \"f\" has incompatible type \"C\"; expected \"P\"\nmain:10: note: Following member(s) of \"C\" have conflicts:\nmain:10: note:     x: expected \"int\", got \"None\"\n\n-- Semanal errors in protocol types\n-- --------------------------------\n\n[case testBasicSemanalErrorsInProtocols]\n\nfrom typing import Protocol, Generic, TypeVar, Iterable\n\nT = TypeVar('T', covariant=True)\nS = TypeVar('S', covariant=True)\n\nclass P1(Protocol[T, T]): # E: Duplicate type variables in Generic[...] or Protocol[...]\n    def meth(self) -> T:\n        pass\n\nclass P2(Protocol[T], Protocol[S]): # E: Only single Generic[...] or Protocol[...] can be in bases\n    def meth(self) -> T:\n        pass\n\nclass P3(Protocol[T], Generic[S]): # E: Only single Generic[...] or Protocol[...] can be in bases\n    def meth(self) -> T:\n        pass\n\nclass P4(Protocol[T]):\n    attr: Iterable[S] # E: Type variable \"__main__.S\" is unbound \\\n                      # N: (Hint: Use \"Generic[S]\" or \"Protocol[S]\" base class to bind \"S\" inside a class) \\\n                      # N: (Hint: Use \"S\" in function signature to bind \"S\" inside a function)\n\nclass P5(Iterable[S], Protocol[T]): # E: If Generic[...] or Protocol[...] is present it should list all type variables\n    def meth(self) -> T:\n        pass\n\n[case testProhibitSelfDefinitionInProtocols]\nfrom typing import Protocol\n\nclass P(Protocol):\n    def __init__(self, a: int) -> None:\n        self.a = a # E: Protocol members cannot be defined via assignment to self \\\n                   # E: \"P\" has no attribute \"a\"\n\nclass B: pass\nclass C:\n    def __init__(self, a: int) -> None:\n        pass\n\nx: P\nx = B()\n# The above has an incompatible __init__, but mypy ignores this for nominal subtypes?\nx = C(1)\n\nclass P2(Protocol):\n    a: int\n    def __init__(self) -> None:\n        self.a = 1\n\nclass B2(P2):\n    a: int\n\nx2: P2 = B2()  # OK\n\n[case testProtocolAndRuntimeAreDefinedAlsoInTypingExtensions]\nfrom typing_extensions import Protocol, runtime_checkable\n\n@runtime_checkable\nclass P(Protocol):\n    def meth(self) -> int:\n        pass\n\nx: object\nif isinstance(x, P):\n    reveal_type(x)  # N: Revealed type is \"__main__.P\"\n    reveal_type(x.meth())  # N: Revealed type is \"builtins.int\"\n\nclass C:\n    def meth(self) -> int:\n        pass\n\nz: P = C()\n[builtins fixtures/dict.pyi]\n\n[case testProtocolsCannotInheritFromNormal]\nfrom typing import Protocol\n\nclass C: pass\nclass D: pass\n\nclass P(C, Protocol): # E: All bases of a protocol must be protocols\n    attr: int\n\nclass P2(P, D, Protocol): # E: All bases of a protocol must be protocols\n    pass\n\nP2() # E: Cannot instantiate protocol class \"P2\"\np: P2\nreveal_type(p.attr) # N: Revealed type is \"builtins.int\"\n\n-- Generic protocol types\n-- ----------------------\n\n[case testGenericMethodWithProtocol]\nfrom typing import Protocol, TypeVar\nT = TypeVar('T')\n\nclass P(Protocol):\n    def meth(self, x: int) -> int:\n        return x\nclass C:\n    def meth(self, x: T) -> T:\n        return x\n\nx: P = C()\n\n[case testGenericMethodWithProtocol2]\nfrom typing import Protocol, TypeVar\nT = TypeVar('T')\n\nclass P(Protocol):\n    def meth(self, x: T) -> T:\n        return x\nclass C:\n    def meth(self, x: int) -> int:\n        return x\n\nx: P = C()\n[out]\nmain:11: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\nmain:11: note: Following member(s) of \"C\" have conflicts:\nmain:11: note:     Expected:\nmain:11: note:         def [T] meth(self, x: T) -> T\nmain:11: note:     Got:\nmain:11: note:         def meth(self, x: int) -> int\n\n[case testAutomaticProtocolVariance]\nfrom typing import TypeVar, Protocol\n\nT = TypeVar('T')\n\n# In case of these errors we proceed with declared variance.\nclass Pco(Protocol[T]): # E: Invariant type variable \"T\" used in protocol where covariant one is expected\n    def meth(self) -> T:\n        pass\nclass Pcontra(Protocol[T]): # E: Invariant type variable \"T\" used in protocol where contravariant one is expected\n    def meth(self, x: T) -> None:\n        pass\nclass Pinv(Protocol[T]):\n    attr: T\n\nclass A: pass\nclass B(A): pass\n\nx1: Pco[B]\ny1: Pco[A]\nif int():\n    x1 = y1 # E: Incompatible types in assignment (expression has type \"Pco[A]\", variable has type \"Pco[B]\")\nif int():\n    y1 = x1 # E: Incompatible types in assignment (expression has type \"Pco[B]\", variable has type \"Pco[A]\")\n\nx2: Pcontra[B]\ny2: Pcontra[A]\nif int():\n    y2 = x2 # E: Incompatible types in assignment (expression has type \"Pcontra[B]\", variable has type \"Pcontra[A]\")\nif int():\n    x2 = y2 # E: Incompatible types in assignment (expression has type \"Pcontra[A]\", variable has type \"Pcontra[B]\")\n\nx3: Pinv[B]\ny3: Pinv[A]\nif int():\n    y3 = x3 # E: Incompatible types in assignment (expression has type \"Pinv[B]\", variable has type \"Pinv[A]\")\nif int():\n    x3 = y3 # E: Incompatible types in assignment (expression has type \"Pinv[A]\", variable has type \"Pinv[B]\")\n\n[case testProtocolVarianceWithCallableAndList]\nfrom typing import Protocol, TypeVar, Callable, List\nT = TypeVar('T')\nS = TypeVar('S')\nT_co = TypeVar('T_co', covariant=True)\n\nclass P(Protocol[T, S]): # E: Invariant type variable \"T\" used in protocol where covariant one is expected \\\n                         # E: Invariant type variable \"S\" used in protocol where contravariant one is expected\n    def fun(self, callback: Callable[[T], S]) -> None: pass\n\nclass P2(Protocol[T_co]): # E: Covariant type variable \"T_co\" used in protocol where invariant one is expected\n    lst: List[T_co]\n[builtins fixtures/list.pyi]\n\n\n[case testProtocolConstraintsUnsolvableWithSelfAnnotation1]\n# https://github.com/python/mypy/issues/11020\nfrom typing import overload, Protocol, TypeVar\n\nI = TypeVar('I', covariant=True)\nV_contra = TypeVar('V_contra', contravariant=True)\n\nclass C(Protocol[I]):\n    def __abs__(self: 'C[V_contra]') -> 'C[V_contra]':\n        ...\n\n    @overload\n    def f(self: 'C', q: int) -> int:\n        ...\n    @overload\n    def f(self: 'C[float]', q: float) -> 'C[float]':\n        ...\n[builtins fixtures/bool.pyi]\n\n\n[case testProtocolConstraintsUnsolvableWithSelfAnnotation2]\n# https://github.com/python/mypy/issues/11020\nfrom typing import Protocol, TypeVar\n\nI = TypeVar('I', covariant=True)\nV = TypeVar('V')\n\nclass C(Protocol[I]):\n    def g(self: 'C[V]') -> 'C[V]':\n        ...\n\nclass D:\n    pass\n\nx: C = D()  # E: Incompatible types in assignment (expression has type \"D\", variable has type \"C[Any]\")\n[builtins fixtures/bool.pyi]\n\n\n[case testProtocolConstraintsUnsolvableWithSelfAnnotation3]\n# https://github.com/python/mypy/issues/11020\nfrom typing import Protocol, TypeVar\n\nI = TypeVar('I', covariant=True)\nV = TypeVar('V')\n\nclass C(Protocol[I]):\n    def g(self: 'C[V]') -> 'C[V]':\n        ...\n\nclass D:\n    def g(self) -> D:\n        ...\n\nx: C = D()\n[builtins fixtures/bool.pyi]\n\n\n[case testProtocolVarianceWithUnusedVariable]\nfrom typing import Protocol, TypeVar\nT = TypeVar('T')\n\nclass P(Protocol[T]): # E: Invariant type variable \"T\" used in protocol where covariant one is expected\n    attr: int\n\n[case testGenericProtocolsInference1]\nfrom typing import Protocol, Sequence, TypeVar\n\nT = TypeVar('T', covariant=True)\n\nclass Closeable(Protocol[T]):\n    def close(self) -> T:\n        pass\n\nclass F:\n    def close(self) -> int:\n        return 0\n\ndef close(arg: Closeable[T]) -> T:\n    return arg.close()\n\ndef close_all(args: Sequence[Closeable[T]]) -> T:\n    for arg in args:\n        arg.close()\n    return args[0].close()\n\narg: Closeable[int]\n\nreveal_type(close(F())) # N: Revealed type is \"builtins.int\"\nreveal_type(close(arg)) # N: Revealed type is \"builtins.int\"\nreveal_type(close_all([F()])) # N: Revealed type is \"builtins.int\"\nreveal_type(close_all([arg])) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testProtocolGenericInference2]\nfrom typing import Generic, TypeVar, Protocol\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass P(Protocol[T, S]):\n    x: T\n    y: S\n\nclass C:\n    x: int\n    y: int\n\ndef fun3(x: P[T, T]) -> T:\n    pass\nreveal_type(fun3(C())) # N: Revealed type is \"builtins.int\"\n\n[case testProtocolGenericInferenceCovariant]\nfrom typing import Generic, TypeVar, Protocol\nT = TypeVar('T', covariant=True)\nS = TypeVar('S', covariant=True)\nU = TypeVar('U')\n\nclass P(Protocol[T, S]):\n    def x(self) -> T: pass\n    def y(self) -> S: pass\n\nclass C:\n    def x(self) -> int: pass\n    def y(self) -> int: pass\n\ndef fun4(x: U, y: P[U, U]) -> U:\n    pass\nreveal_type(fun4('a', C())) # N: Revealed type is \"builtins.object\"\n\n[case testUnrealtedGenericProtocolsEquivalent]\nfrom typing import TypeVar, Protocol\nT = TypeVar('T')\n\nclass PA(Protocol[T]):\n    attr: int\n    def meth(self) -> T: pass\n    def other(self, arg: T) -> None: pass\nclass PB(Protocol[T]): # exactly the same as above\n    attr: int\n    def meth(self) -> T: pass\n    def other(self, arg: T) -> None: pass\n\ndef fun(x: PA[T]) -> PA[T]:\n    y: PB[T] = x\n    z: PB[T]\n    return z\n\nx: PA\ny: PB\nx = y\ny = x\n\nxi: PA[int]\nyi: PB[int]\nxi = yi\nyi = xi\n\n[case testGenericSubProtocols]\nfrom typing import TypeVar, Protocol, Tuple, Generic\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass P1(Protocol[T]):\n    attr1: T\nclass P2(P1[T], Protocol[T, S]):\n    attr2: Tuple[T, S]\n\nclass C:\n    def __init__(self, a1: int, a2: Tuple[int, int]) -> None:\n        self.attr1 = a1\n        self.attr2 = a2\n\nc: C\nvar: P2[int, int] = c\nvar2: P2[int, str] = c # E: Incompatible types in assignment (expression has type \"C\", variable has type \"P2[int, str]\") \\\n                       # N: Following member(s) of \"C\" have conflicts: \\\n                       # N:     attr2: expected \"tuple[int, str]\", got \"tuple[int, int]\"\n\nclass D(Generic[T]):\n    attr1: T\nclass E(D[T]):\n    attr2: Tuple[T, T]\n\ndef f(x: T) -> T:\n    z: P2[T, T] = E[T]()\n    y: P2[T, T] = D[T]() # E: Incompatible types in assignment (expression has type \"D[T]\", variable has type \"P2[T, T]\") \\\n                         # N: \"D\" is missing following \"P2\" protocol member: \\\n                         # N:     attr2\n    return x\n[builtins fixtures/isinstancelist.pyi]\n\n[case testGenericSubProtocolsExtensionInvariant]\nfrom typing import TypeVar, Protocol, Union\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass P1(Protocol[T]):\n    attr1: T\nclass P2(Protocol[T]):\n    attr2: T\nclass P(P1[T], P2[S], Protocol):\n    pass\n\nclass C:\n    attr1: int\n    attr2: str\n\nclass A:\n    attr1: A\nclass B:\n    attr2: B\nclass D(A, B): pass\n\nx: P = D()  # Same as P[Any, Any]\n\nvar: P[Union[int, P], Union[P, str]] = C() # E: Incompatible types in assignment (expression has type \"C\", variable has type \"P[int | P[Any, Any], P[Any, Any] | str]\") \\\n                                           # N: Following member(s) of \"C\" have conflicts: \\\n                                           # N:     attr1: expected \"int | P[Any, Any]\", got \"int\" \\\n                                           # N:     attr2: expected \"P[Any, Any] | str\", got \"str\"\n\n[case testGenericSubProtocolsExtensionCovariant]\nfrom typing import TypeVar, Protocol, Union\n\nT = TypeVar('T', covariant=True)\nS = TypeVar('S', covariant=True)\n\nclass P1(Protocol[T]):\n    def attr1(self) -> T: pass\nclass P2(Protocol[T]):\n    def attr2(self) -> T: pass\nclass P(P1[T], P2[S], Protocol):\n    pass\n\nclass C:\n    def attr1(self) -> int: pass\n    def attr2(self) -> str: pass\n\nvar: P[Union[int, P], Union[P, str]] = C() # OK for covariant\nvar2: P[Union[str, P], Union[P, int]] = C()\n[out]\nmain:18: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P[str | P[Any, Any], P[Any, Any] | int]\")\nmain:18: note: Following member(s) of \"C\" have conflicts:\nmain:18: note:     Expected:\nmain:18: note:         def attr1(self) -> str | P[Any, Any]\nmain:18: note:     Got:\nmain:18: note:         def attr1(self) -> int\nmain:18: note:     Expected:\nmain:18: note:         def attr2(self) -> P[Any, Any] | int\nmain:18: note:     Got:\nmain:18: note:         def attr2(self) -> str\n\n[case testSelfTypesWithProtocolsBehaveAsWithNominal]\nfrom typing import Protocol, TypeVar\n\nT = TypeVar('T', bound='Shape')\nclass Shape(Protocol):\n    def combine(self: T, other: T) -> T:\n        pass\n\nclass NonProtoShape:\n    def combine(self: T, other: T) -> T:\n        pass\nclass Circle:\n    def combine(self: T, other: Shape) -> T:\n        pass\nclass Triangle:\n    def combine(self, other: Shape) -> Shape:\n        pass\nclass Bad:\n    def combine(self, other: int) -> str:\n        pass\n\ndef f(s: Shape) -> None: pass\nf(NonProtoShape())\nf(Circle())\ns: Shape\nif int():\n    s = Triangle()\n    s = Bad()\n\nn2: NonProtoShape = s\n[out]\nmain:26: error: Incompatible types in assignment (expression has type \"Triangle\", variable has type \"Shape\")\nmain:26: note: Following member(s) of \"Triangle\" have conflicts:\nmain:26: note:     Expected:\nmain:26: note:         def combine(self, other: Triangle) -> Triangle\nmain:26: note:     Got:\nmain:26: note:         def combine(self, other: Shape) -> Shape\nmain:27: error: Incompatible types in assignment (expression has type \"Bad\", variable has type \"Shape\")\nmain:27: note: Following member(s) of \"Bad\" have conflicts:\nmain:27: note:     Expected:\nmain:27: note:         def combine(self, other: Bad) -> Bad\nmain:27: note:     Got:\nmain:27: note:         def combine(self, other: int) -> str\nmain:29: error: Incompatible types in assignment (expression has type \"Shape\", variable has type \"NonProtoShape\")\n\n[case testBadVarianceInProtocols]\nfrom typing import Protocol, TypeVar\n\nT_co = TypeVar('T_co', covariant=True)\nT_contra = TypeVar('T_contra', contravariant=True)\n\nclass Proto(Protocol[T_co, T_contra]):  # type: ignore\n    def one(self, x: T_co) -> None:  # E: Cannot use a covariant type variable as a parameter\n        pass\n    def other(self) -> T_contra:  # E: Cannot use a contravariant type variable as return type\n        pass\n\n# Check that we respect user overrides of variance after the errors are reported\nx: Proto[int, float]\ny: Proto[float, int]\ny = x # OK\n[builtins fixtures/list.pyi]\n\n[case testSubtleBadVarianceInProtocols]\nfrom typing import Protocol, TypeVar, Iterable, Sequence\n\nT_co = TypeVar('T_co', covariant=True)\nT_contra = TypeVar('T_contra', contravariant=True)\n\nclass Proto(Protocol[T_co, T_contra]): # E: Covariant type variable \"T_co\" used in protocol where contravariant one is expected \\\n                                       # E: Contravariant type variable \"T_contra\" used in protocol where covariant one is expected\n    def one(self, x: Iterable[T_co]) -> None:\n        pass\n    def other(self) -> Sequence[T_contra]:\n        pass\n\n# Check that we respect user overrides of variance after the errors are reported\nx: Proto[int, float]\ny: Proto[float, int]\ny = x # OK\n[builtins fixtures/list.pyi]\n\n-- Recursive protocol types\n-- ------------------------\n\n[case testRecursiveProtocols1]\nfrom typing import Protocol, Sequence, List, Generic, TypeVar\n\nT = TypeVar('T')\n\nclass Traversable(Protocol):\n    @property\n    def leaves(self) -> Sequence[Traversable]: pass\n\nclass C: pass\n\nclass D(Generic[T]):\n    leaves: List[D[T]]\n\nt: Traversable\nt = D[int]() # OK\nif int():\n    t = C() # E: Incompatible types in assignment (expression has type \"C\", variable has type \"Traversable\")\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testRecursiveProtocols2]\nfrom typing import Protocol, TypeVar\n\nT = TypeVar('T')\nclass Linked(Protocol[T]):\n    val: T\n    def next(self) -> Linked[T]: pass\n\nclass L:\n    val: int\n    def next(self) -> L: pass\n\ndef last(seq: Linked[T]) -> T:\n    pass\n\nreveal_type(last(L())) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testRecursiveProtocolSubtleMismatch]\nfrom typing import Protocol, TypeVar\n\nT = TypeVar('T')\nclass Linked(Protocol[T]):\n    val: T\n    def next(self) -> Linked[T]: pass\nclass L:\n    val: int\n    def next(self) -> int: pass\n\ndef last(seq: Linked[T]) -> T:\n    pass\nlast(L()) # E: Argument 1 to \"last\" has incompatible type \"L\"; expected \"Linked[Never]\"\n\n[case testMutuallyRecursiveProtocols]\nfrom typing import Protocol, Sequence, List\n\nclass P1(Protocol):\n    @property\n    def attr1(self) -> Sequence[P2]: pass\nclass P2(Protocol):\n    @property\n    def attr2(self) -> Sequence[P1]: pass\n\nclass C: pass\nclass A:\n    attr1: List[B]\nclass B:\n    attr2: List[A]\n\nt: P1\nt = A() # OK\nif int():\n    t = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"P1\")\n    t = C() # E: Incompatible types in assignment (expression has type \"C\", variable has type \"P1\")\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testMutuallyRecursiveProtocolsTypesWithSubteMismatch]\nfrom typing import Protocol, Sequence, List\n\nclass P1(Protocol):\n    @property\n    def attr1(self) -> Sequence[P2]: pass\nclass P2(Protocol):\n    @property\n    def attr2(self) -> Sequence[P1]: pass\n\nclass C: pass\nclass A:\n    attr1: List[B]\nclass B:\n    attr2: List[C]\n\nt: P1\nt = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"P1\") \\\n        # N: Following member(s) of \"A\" have conflicts: \\\n        # N:     attr1: expected \"Sequence[P2]\", got \"list[B]\"\n[builtins fixtures/list.pyi]\n\n[case testMutuallyRecursiveProtocolsTypesWithSubteMismatchWriteable]\nfrom typing import Protocol\n\nclass P1(Protocol):\n    @property\n    def attr1(self) -> P2: pass\nclass P2(Protocol):\n    attr2: P1\n\nclass A:\n    attr1: B\nclass B:\n    attr2: A\n\nx: P1 = A() # E: Incompatible types in assignment (expression has type \"A\", variable has type \"P1\") \\\n            # N: Following member(s) of \"A\" have conflicts: \\\n            # N:     attr1: expected \"P2\", got \"B\"\n[builtins fixtures/property.pyi]\n\n[case testTwoUncomfortablyIncompatibleProtocolsWithoutRunningInIssue9771]\nfrom typing import cast, Protocol, TypeVar, Union\n\nT1 = TypeVar(\"T1\", covariant=True)\nT2 = TypeVar(\"T2\")\n\nclass P1(Protocol[T1]):\n    def b(self) -> int: ...\n    def a(self, other: \"P1[T2]\") -> T1: ...\n\nclass P2(Protocol[T1]):\n    def a(self, other: Union[P1[T2], \"P2[T2]\"]) -> T1: ...\n\np11: P1 = cast(P1, 1)\np12: P1 = cast(P2, 1)   # E\np21: P2 = cast(P1, 1)\np22: P2 = cast(P2, 1)   # E\n[out]\nmain:14: error: Incompatible types in assignment (expression has type \"P2[Any]\", variable has type \"P1[Any]\")\nmain:14: note: \"P2\" is missing following \"P1\" protocol member:\nmain:14: note:     b\nmain:15: error: Incompatible types in assignment (expression has type \"P1[Any]\", variable has type \"P2[Any]\")\nmain:15: note: Following member(s) of \"P1[Any]\" have conflicts:\nmain:15: note:     Expected:\nmain:15: note:         def [T2] a(self, other: P1[T2] | P2[T2]) -> Any\nmain:15: note:     Got:\nmain:15: note:         def [T2] a(self, other: P1[T2]) -> Any\n\n[case testHashable]\n\nfrom typing import Hashable, Iterable\n\ndef f(x: Hashable) -> None:\n    pass\n\ndef g(x: Iterable[str]) -> None:\n    f(x)   # E: Argument 1 to \"f\" has incompatible type \"Iterable[str]\"; expected \"Hashable\"\n\n[builtins fixtures/object_hashable.pyi]\n[typing fixtures/typing-full.pyi]\n\n-- FIXME: things like this should work\n[case testWeirdRecursiveInferenceForProtocols-skip]\nfrom typing import Protocol, TypeVar, Generic\nT_co = TypeVar('T_co', covariant=True)\nT = TypeVar('T')\n\nclass P(Protocol[T_co]):\n    def meth(self) -> P[T_co]: pass\n\nclass C(Generic[T]):\n    def meth(self) -> C[T]: pass\n\nx: C[int]\ndef f(arg: P[T]) -> T: pass\nreveal_type(f(x)) #E: Revealed type is \"builtins.int\"\n\n-- @property, @classmethod and @staticmethod in protocol types\n-- -----------------------------------------------------------\n\n[case testCannotInstantiateAbstractMethodExplicitProtocolSubtypes]\nfrom typing import Protocol\nfrom abc import abstractmethod\n\nclass P(Protocol):\n    @abstractmethod\n    def meth(self) -> int:\n        pass\n\nclass A(P):\n    pass\n\nA() # E: Cannot instantiate abstract class \"A\" with abstract attribute \"meth\"\n\nclass C(A):\n    def meth(self) -> int:\n        pass\nclass C2(P):\n    def meth(self) -> int:\n        pass\n\nC()\nC2()\n\n[case testCannotInstantiateAbstractVariableExplicitProtocolSubtypes]\nfrom typing import Protocol\n\nclass P(Protocol):\n    attr: int\n\nclass A(P):\n    pass\n\nA() # E: Cannot instantiate abstract class \"A\" with abstract attribute \"attr\"\n\nclass C(A):\n    attr: int\nclass C2(P):\n    def __init__(self) -> None:\n        self.attr = 1\n\nC()\nC2()\n\nclass P2(Protocol):\n    attr: int = 1\n\nclass B(P2): pass\nB() # OK, attr is not abstract\n\n[case testClassVarsInProtocols]\nfrom typing import Protocol, ClassVar\n\nclass PInst(Protocol):\n   v: int\n\nclass PClass(Protocol):\n   v: ClassVar[int]\n\nclass CInst:\n   v: int\n\nclass CClass:\n   v: ClassVar[int]\n\nx: PInst\ny: PClass\n\nx = CInst()\nif int():\n    x = CClass() # E: Incompatible types in assignment (expression has type \"CClass\", variable has type \"PInst\") \\\n             # N: Protocol member PInst.v expected instance variable, got class variable\ny = CClass()\nif int():\n    y = CInst()  # E: Incompatible types in assignment (expression has type \"CInst\", variable has type \"PClass\") \\\n             # N: Protocol member PClass.v expected class variable, got instance variable\n\n[case testPropertyInProtocols]\nfrom typing import Protocol\n\nclass PP(Protocol):\n    @property\n    def attr(self) -> int:\n        pass\n\nclass P(Protocol):\n    attr: int\n\nx: P\ny: PP\ny = x\n\nx2: P\ny2: PP\nx2 = y2 # E: Incompatible types in assignment (expression has type \"PP\", variable has type \"P\") \\\n        # N: Protocol member P.attr expected settable variable, got read-only attribute\n[builtins fixtures/property.pyi]\n\n[case testClassVarProtocolImmutable]\nfrom typing import Protocol, ClassVar\n\nclass P(Protocol):\n    @property\n    def x(self) -> int: ...\n\nclass C:\n    x: ClassVar[int]\n\nclass Bad:\n    x: ClassVar[str]\n\nx: P = C()\ny: P = Bad()  # E: Incompatible types in assignment (expression has type \"Bad\", variable has type \"P\") \\\n              # N: Following member(s) of \"Bad\" have conflicts: \\\n              # N:     x: expected \"int\", got \"str\"\n[builtins fixtures/property.pyi]\n\n[case testSettablePropertyInProtocols]\nfrom typing import Protocol\n\nclass PPS(Protocol):\n    @property\n    def attr(self) -> int:\n        pass\n    @attr.setter\n    def attr(self, x: int) -> None:\n        pass\n\nclass PP(Protocol):\n    @property\n    def attr(self) -> int:\n        pass\n\nclass P(Protocol):\n    attr: int\n\nx: P\nz: PPS\nz = x\n\nx2: P\nz2: PPS\nx2 = z2\n\ny3: PP\nz3: PPS\ny3 = z3\n\ny4: PP\nz4: PPS\nz4 = y4 # E: Incompatible types in assignment (expression has type \"PP\", variable has type \"PPS\") \\\n        # N: Protocol member PPS.attr expected settable variable, got read-only attribute\n[builtins fixtures/property.pyi]\n\n[case testFinalAttributeProtocol]\nfrom typing import Protocol, Final\n\nclass P(Protocol):\n    x: int\n\nclass C:\n    def __init__(self, x: int) -> None:\n        self.x = x\nclass CF:\n    def __init__(self, x: int) -> None:\n        self.x: Final = x\n\nx: P\ny: P\nx = C(42)\ny = CF(42)  # E: Incompatible types in assignment (expression has type \"CF\", variable has type \"P\") \\\n            # N: Protocol member P.x expected settable variable, got read-only attribute\n\n[case testStaticAndClassMethodsInProtocols]\nfrom typing import Protocol, Type, TypeVar\n\nclass P(Protocol):\n    def meth(self, x: int) -> str:\n        pass\n\nclass PC(Protocol):\n    @classmethod\n    def meth(cls, x: int) -> str:\n        pass\n\nclass B:\n    @staticmethod\n    def meth(x: int) -> str:\n        pass\n\nclass C:\n    def meth(self, x: int) -> str:\n        pass\n\nx: P\nx = C()\nif int():\n    x = B()\n\ny: PC\ny = B()\nif int():\n    y = C() \\\n      # E: Incompatible types in assignment (expression has type \"C\", variable has type \"PC\") \\\n      # N: Protocol member PC.meth expected class or static method\n[builtins fixtures/classmethod.pyi]\n\n[case testOverloadedMethodsInProtocols]\nfrom typing import overload, Protocol, Union, Optional\n\nclass P(Protocol):\n    @overload\n    def f(self, x: int) -> Optional[int]: pass\n    @overload\n    def f(self, x: str) -> Optional[str]: pass\n\nclass C:\n    def f(self, x: Union[int, str]) -> None:\n        pass\nclass D:\n    def f(self, x: int) -> None:\n        pass\n\nx: P = C()\nif int():\n    x = D()\n[out]\nmain:18: error: Incompatible types in assignment (expression has type \"D\", variable has type \"P\")\nmain:18: note: Following member(s) of \"D\" have conflicts:\nmain:18: note:     Expected:\nmain:18: note:         @overload\nmain:18: note:         def f(self, x: int) -> int | None\nmain:18: note:         @overload\nmain:18: note:         def f(self, x: str) -> str | None\nmain:18: note:     Got:\nmain:18: note:         def f(self, x: int) -> None\n\n[case testCannotInstantiateProtocolWithOverloadedUnimplementedMethod]\nfrom typing import overload, Protocol\n\nclass P(Protocol):\n    @overload\n    def meth(self, x: int) -> int: pass\n    @overload\n    def meth(self, x: str) -> bytes: pass\nclass C(P):\n    pass\nC() # E: Cannot instantiate abstract class \"C\" with abstract attribute \"meth\"\n\n[case testCanUseOverloadedImplementationsInProtocols]\nfrom typing import overload, Protocol, Union\nclass P(Protocol):\n    @overload\n    def meth(self, x: int) -> int: pass\n    @overload\n    def meth(self, x: str) -> bool: pass\n    def meth(self, x: Union[int, str]):\n        if isinstance(x, int):\n            return x\n        return True\n\nclass C(P):\n    pass\nx = C()\nreveal_type(x.meth('hi')) # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/isinstance.pyi]\n\n[case testProtocolsWithIdenticalOverloads]\nfrom typing import overload, Protocol\n\nclass PA(Protocol):\n    @overload\n    def meth(self, x: int) -> int: pass\n    @overload\n    def meth(self, x: str) -> bytes: pass\nclass PB(Protocol): # identical to above\n    @overload\n    def meth(self, x: int) -> int: pass\n    @overload\n    def meth(self, x: str) -> bytes: pass\n\nx: PA\ny: PB\nx = y\ndef fun(arg: PB) -> None: pass\nfun(x)\n\n[case testProtocolsWithIncompatibleOverloads]\nfrom typing import overload, Protocol\n\nclass PA(Protocol):\n    @overload\n    def meth(self, x: int) -> int: pass\n    @overload\n    def meth(self, x: str) -> bytes: pass\nclass PB(Protocol):\n    @overload\n    def meth(self, x: int) -> int: pass\n    @overload\n    def meth(self, x: bytes) -> str: pass\n\nx: PA\ny: PB\nx = y\n[out]\nmain:16: error: Incompatible types in assignment (expression has type \"PB\", variable has type \"PA\")\nmain:16: note: Following member(s) of \"PB\" have conflicts:\nmain:16: note:     Expected:\nmain:16: note:         @overload\nmain:16: note:         def meth(self, x: int) -> int\nmain:16: note:         @overload\nmain:16: note:         def meth(self, x: str) -> bytes\nmain:16: note:     Got:\nmain:16: note:         @overload\nmain:16: note:         def meth(self, x: int) -> int\nmain:16: note:         @overload\nmain:16: note:         def meth(self, x: bytes) -> str\n\n[case testProtocolWithMultiContravariantTypeVarOverloads]\nfrom typing import overload, Protocol, TypeVar\n\nT1 = TypeVar(\"T1\", contravariant=True)\nT2 = TypeVar(\"T2\", contravariant=True)\n\nclass A(Protocol[T1, T2]):\n    @overload\n    def method(self, a: T1) -> None: ...\n    @overload\n    def method(self, a: T2) -> None: ...\n\n\n-- Join and meet with protocol types\n-- ---------------------------------\n\n[case testJoinProtocolWithProtocol]\nfrom typing import Protocol\n\nclass P(Protocol):\n    attr: int\nclass P2(Protocol):\n    attr: int\n    attr2: str\n\nx: P\ny: P2\n\nl0 = [x, x]\nl1 = [y, y]\nl = [x, y]\nreveal_type(l0) # N: Revealed type is \"builtins.list[__main__.P]\"\nreveal_type(l1) # N: Revealed type is \"builtins.list[__main__.P2]\"\nreveal_type(l) # N: Revealed type is \"builtins.list[__main__.P]\"\n[builtins fixtures/list.pyi]\n\n[case testJoinOfIncompatibleProtocols]\nfrom typing import Protocol\n\nclass P(Protocol):\n    attr: int\nclass P2(Protocol):\n    attr2: str\n\nx: P\ny: P2\nreveal_type([x, y]) # N: Revealed type is \"builtins.list[builtins.object]\"\n[builtins fixtures/list.pyi]\n\n[case testJoinProtocolWithNormal]\nfrom typing import Protocol\n\nclass P(Protocol):\n    attr: int\n\nclass C:\n    attr: int\n\nx: P\ny: C\n\nl = [x, y]\n\nreveal_type(l) # N: Revealed type is \"builtins.list[__main__.P]\"\n[builtins fixtures/list.pyi]\n\n[case testMeetProtocolWithProtocol]\nfrom typing import Protocol, Callable, TypeVar\n\nclass P(Protocol):\n    attr: int\nclass P2(Protocol):\n    attr: int\n    attr2: str\n\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: P, y: P2) -> None: pass\nreveal_type(f(g)) # N: Revealed type is \"__main__.P2\"\n\n[case testMeetOfIncompatibleProtocols]\n# flags: --no-strict-optional\nfrom typing import Protocol, Callable, TypeVar\n\nclass P(Protocol):\n    attr: int\nclass P2(Protocol):\n    attr2: str\n\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: P, y: P2) -> None: pass\nx = f(g)\nreveal_type(x)  # N: Revealed type is \"None\"\n\n[case testMeetProtocolWithNormal]\nfrom typing import Protocol, Callable, TypeVar\n\nclass P(Protocol):\n    attr: int\nclass C:\n    attr: int\n\nT = TypeVar('T')\ndef f(x: Callable[[T, T], None]) -> T: pass\ndef g(x: P, y: C) -> None: pass\nreveal_type(f(g)) # N: Revealed type is \"__main__.C\"\n\n[case testInferProtocolFromProtocol]\nfrom typing import Protocol, Sequence, TypeVar, Generic\n\nT = TypeVar('T')\nclass Box(Protocol[T]):\n    content: T\nclass Linked(Protocol[T]):\n    val: T\n    def next(self) -> Linked[T]: pass\n\nclass L(Generic[T]):\n    val: Box[T]\n    def next(self) -> L[T]: pass\n\ndef last(seq: Linked[T]) -> T:\n    pass\n\nreveal_type(last(L[int]())) # N: Revealed type is \"__main__.Box[builtins.int]\"\nreveal_type(last(L[str]()).content) # N: Revealed type is \"builtins.str\"\n\n[case testOverloadOnProtocol]\nfrom typing import overload, Protocol, runtime_checkable\n\n@runtime_checkable\nclass P1(Protocol):\n    attr1: int\nclass P2(Protocol):\n    attr2: str\n\nclass C1:\n    attr1: int\nclass C2:\n    attr2: str\nclass C: pass\n\n@overload\ndef f(x: P1) -> int: ...\n@overload\ndef f(x: P2) -> str: ...\ndef f(x: object) -> object:\n    if isinstance(x, P1):\n        return P1.attr1\n    if isinstance(x, P2): # E: Only @runtime_checkable protocols can be used with instance and class checks\n        return P2.attr2\n    return None\n\nreveal_type(f(C1())) # N: Revealed type is \"builtins.int\"\nreveal_type(f(C2())) # N: Revealed type is \"builtins.str\"\nclass D(C1, C2): pass # Compatible with both P1 and P2\n# TODO: Should this return a union instead?\nreveal_type(f(D())) # N: Revealed type is \"builtins.int\"\nf(C()) # E: No overload variant of \"f\" matches argument type \"C\" \\\n       # N: Possible overload variants: \\\n       # N:     def f(x: P1) -> int \\\n       # N:     def f(x: P2) -> str\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-full.pyi]\n\n-- Unions of protocol types\n-- ------------------------\n\n[case testBasicUnionsOfProtocols]\nfrom typing import Union, Protocol\n\nclass P1(Protocol):\n    attr1: int\nclass P2(Protocol):\n    attr2: int\n\nclass C1:\n    attr1: int\nclass C2:\n    attr2: int\nclass C(C1, C2):\n    pass\n\nclass B: ...\n\nx: Union[P1, P2]\n\nx = C1()\nif int():\n    x = C2()\n    x = C()\n    x = B() # E: Incompatible types in assignment (expression has type \"B\", variable has type \"P1 | P2\")\n\n[case testUnionsOfNormalClassesWithProtocols]\nfrom typing import Protocol, Union\n\nclass P1(Protocol):\n    attr1: int\nclass P2(Protocol):\n    attr2: int\n\nclass C1:\n    attr1: int\nclass C2:\n    attr2: int\nclass C(C1, C2):\n    pass\n\nclass D1:\n    attr1: int\n\ndef f1(x: P1) -> None:\n    pass\ndef f2(x: P2) -> None:\n    pass\n\nx: Union[C1, C2]\ny: Union[C1, D1]\nz: Union[C, D1]\n\nf1(x) # E: Argument 1 to \"f1\" has incompatible type \"C1 | C2\"; expected \"P1\"\nf1(y)\nf1(z)\nf2(x) # E: Argument 1 to \"f2\" has incompatible type \"C1 | C2\"; expected \"P2\"\nf2(z) # E: Argument 1 to \"f2\" has incompatible type \"C | D1\"; expected \"P2\"\n\n-- Type[] with protocol types\n-- --------------------------\n\n[case testInstantiationProtocolInTypeForFunctions]\nfrom typing import Type, Protocol\n\nclass P(Protocol):\n    def m(self) -> None: return None\nclass P1(Protocol):\n    def m(self) -> None: pass\nclass Pbad(Protocol):\n    def mbad(self) -> int: pass\nclass B(P): pass\nclass C:\n    def m(self) -> None:\n        pass\n\ndef f(cls: Type[P]) -> P:\n    return cls()  # OK\ndef g() -> P:\n    return P()  # E: Cannot instantiate protocol class \"P\"\n\nf(P)  # E: Only concrete class can be given where \"type[P]\" is expected\nf(B)  # OK\nf(C)  # OK\nx: Type[P1]\nxbad: Type[Pbad]\nf(x)  # OK\nf(xbad)  # E: Argument 1 to \"f\" has incompatible type \"type[Pbad]\"; expected \"type[P]\"\n\n[case testInstantiationProtocolInTypeForAliases]\nfrom typing import Type, Protocol\n\nclass P(Protocol):\n    def m(self) -> None: pass\nclass C:\n    def m(self) -> None:\n        pass\n\ndef f(cls: Type[P]) -> P:\n    return cls()  # OK\n\nAlias = P\nGoodAlias = C\nAlias()  # E: Cannot instantiate protocol class \"P\"\nGoodAlias()\nf(Alias)  # E: Only concrete class can be given where \"type[P]\" is expected\nf(GoodAlias)\n\n[case testInstantiationProtocolInTypeForVariables]\n# flags: --no-strict-optional\nfrom typing import Type, Protocol\n\nclass P(Protocol):\n    def m(self) -> None: return None\nclass B(P): pass\nclass C:\n    def m(self) -> None:\n        pass\n\nvar: Type[P]\nvar()\nif int():\n    var = P # E: Can only assign concrete classes to a variable of type \"type[P]\"\n    var = B # OK\n    var = C # OK\n\nvar_old = None # type: Type[P] # Old syntax for variable annotations\nvar_old()\nif int():\n    var_old = P # E: Can only assign concrete classes to a variable of type \"type[P]\"\n    var_old = B # OK\n    var_old = C # OK\n\n[case testInstantiationProtocolInTypeForClassMethods]\nfrom typing import Type, Protocol\n\nclass Logger:\n    @staticmethod\n    def log(a: Type[C]):\n        pass\nclass C(Protocol):\n    @classmethod\n    def action(cls) -> None:\n        cls() #OK for classmethods\n        Logger.log(cls)  #OK for classmethods\n[builtins fixtures/classmethod.pyi]\n\n-- isinstance() with @runtime_checkable protocols\n-- ----------------------------------------------\n\n[case testSimpleRuntimeProtocolCheck]\nfrom typing import Protocol, runtime_checkable\n\n@runtime_checkable\nclass C:  # E: @runtime_checkable can only be used with protocol classes\n    pass\n\nclass P(Protocol):\n    def meth(self) -> None:\n        pass\n\n@runtime_checkable\nclass R(Protocol):\n    def meth(self) -> int:\n        pass\n\nx: object\n\nif isinstance(x, P):  # E: Only @runtime_checkable protocols can be used with instance and class checks\n    reveal_type(x)  # N: Revealed type is \"__main__.P\"\n\nif isinstance(x, R):\n    reveal_type(x)  # N: Revealed type is \"__main__.R\"\n    reveal_type(x.meth())  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testRuntimeIterableProtocolCheck]\nfrom typing import Iterable, List, Union\n\nx: Union[int, List[str]]\n\nif isinstance(x, Iterable):\n    reveal_type(x) # N: Revealed type is \"builtins.list[builtins.str]\"\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testConcreteClassesInProtocolsIsInstance]\n# flags: --warn-unreachable\nfrom typing import Protocol, runtime_checkable, TypeVar, Generic\n\nT = TypeVar('T')\n\n@runtime_checkable\nclass P1(Protocol):\n    def meth1(self) -> int:\n        pass\n@runtime_checkable\nclass P2(Protocol):\n    def meth2(self) -> int:\n        pass\n@runtime_checkable\nclass P(P1, P2, Protocol):\n    pass\n\nclass C1(Generic[T]):\n    def meth1(self) -> T:\n        pass\nclass C2:\n    def meth2(self) -> int:\n        pass\nclass C(C1[int], C2): pass\n\nc = C()\nif isinstance(c, P1):\n    reveal_type(c) # N: Revealed type is \"__main__.C\"\nelse:\n    reveal_type(c)  # E: Statement is unreachable\nif isinstance(c, P):\n    reveal_type(c) # N: Revealed type is \"__main__.C\"\nelse:\n    reveal_type(c)  # E: Statement is unreachable\n\nc1i: C1[int]\nif isinstance(c1i, P1):\n    reveal_type(c1i) # N: Revealed type is \"__main__.C1[builtins.int]\"\nelse:\n    reveal_type(c1i)  # E: Statement is unreachable\nif isinstance(c1i, P):\n    reveal_type(c1i) # N: Revealed type is \"__main__.<subclass of \"__main__.C1[builtins.int]\" and \"__main__.P\">\"\nelse:\n    reveal_type(c1i) # N: Revealed type is \"__main__.C1[builtins.int]\"\n\nc1s: C1[str]\nif isinstance(c1s, P1):  # E: Subclass of \"C1[str]\" and \"P1\" cannot exist: would have incompatible method signatures\n    reveal_type(c1s)  # E: Statement is unreachable\nelse:\n    reveal_type(c1s) # N: Revealed type is \"__main__.C1[builtins.str]\"\n\nc2: C2\nif isinstance(c2, P):\n    reveal_type(c2) # N: Revealed type is \"__main__.<subclass of \"__main__.C2\" and \"__main__.P\">\"\nelse:\n    reveal_type(c2) # N: Revealed type is \"__main__.C2\"\n\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testConcreteClassesUnionInProtocolsIsInstance]\nfrom typing import Protocol, runtime_checkable, TypeVar, Generic, Union\n\nT = TypeVar('T')\n\n@runtime_checkable\nclass P1(Protocol):\n    def meth1(self) -> int:\n        pass\n@runtime_checkable\nclass P2(Protocol):\n    def meth2(self) -> int:\n        pass\n\nclass C1(Generic[T]):\n    def meth1(self) -> T:\n        pass\nclass C2:\n    def meth2(self) -> int:\n        pass\n\nx: Union[C1[int], C2]\nif isinstance(x, P1):\n    reveal_type(x) # N: Revealed type is \"__main__.C1[builtins.int]\"\nelse:\n    reveal_type(x) # N: Revealed type is \"__main__.C2\"\n\nif isinstance(x, P2):\n    reveal_type(x) # N: Revealed type is \"__main__.C2\"\nelse:\n    reveal_type(x) # N: Revealed type is \"__main__.C1[builtins.int]\"\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-full.pyi]\n\n-- Non-Instances and protocol types (Callable vs __call__ etc.)\n-- ------------------------------------------------------------\n\n[case testBasicTupleStructuralSubtyping]\nfrom typing import Tuple, TypeVar, Protocol\n\nT = TypeVar('T', covariant=True)\n\nclass MyProto(Protocol[T]):\n    def __len__(self) -> T:\n        pass\n\nt: Tuple[int, str]\ndef f(x: MyProto[int]) -> None:\n    pass\nf(t)  # OK\n\ny: MyProto[str]\ny = t # E: Incompatible types in assignment (expression has type \"tuple[int, str]\", variable has type \"MyProto[str]\")\n[builtins fixtures/isinstancelist.pyi]\n\n[case testBasicNamedTupleStructuralSubtyping]\nfrom typing import NamedTuple, TypeVar, Protocol\n\nT = TypeVar('T', covariant=True)\nS = TypeVar('S', covariant=True)\n\nclass P(Protocol[T, S]):\n    @property\n    def x(self) -> T: pass\n    @property\n    def y(self) -> S: pass\n\nclass N(NamedTuple):\n    x: int\n    y: str\nclass N2(NamedTuple):\n    x: int\nclass N3(NamedTuple):\n    x: int\n    y: int\n\nz: N\nz3: N3\n\ndef fun(x: P[int, str]) -> None:\n    pass\ndef fun2(x: P[int, int]) -> None:\n    pass\ndef fun3(x: P[T, T]) -> T:\n    return x.x\n\nfun(z)\nfun2(z) # E: Argument 1 to \"fun2\" has incompatible type \"N\"; expected \"P[int, int]\" \\\n        # N: Following member(s) of \"N\" have conflicts: \\\n        # N:     y: expected \"int\", got \"str\"\n\nfun(N2(1)) # E: Argument 1 to \"fun\" has incompatible type \"N2\"; expected \"P[int, str]\" \\\n           # N: \"N2\" is missing following \"P\" protocol member: \\\n           # N:     y\n\nreveal_type(fun3(z)) # N: Revealed type is \"builtins.object\"\n\nreveal_type(fun3(z3)) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testBasicCallableStructuralSubtyping]\nfrom typing import Callable, Generic, TypeVar\n\ndef apply(f: Callable[[int], int], x: int) -> int:\n    return f(x)\n\nclass Add5:\n    def __call__(self, x: int) -> int:\n        return x + 5\n\napply(Add5(), 5)\n\nT = TypeVar('T')\ndef apply_gen(f: Callable[[T], T]) -> T:\n    pass\n\nreveal_type(apply_gen(Add5())) # N: Revealed type is \"builtins.int\"\ndef apply_str(f: Callable[[str], int], x: str) -> int:\n    return f(x)\napply_str(Add5(), 'a') # E: Argument 1 to \"apply_str\" has incompatible type \"Add5\"; expected \"Callable[[str], int]\" \\\n                       # N: \"Add5.__call__\" has type \"def __call__(self, x: int) -> int\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testMoreComplexCallableStructuralSubtyping]\nfrom mypy_extensions import Arg, VarArg\nfrom typing import Protocol, Callable\n\ndef call_soon(cb: Callable[[Arg(int, 'x'), VarArg(str)], int]): pass\n\nclass Good:\n    def __call__(self, x: int, *rest: str) -> int: pass\nclass Bad1:\n    def __call__(self, x: int, *rest: int) -> int: pass\nclass Bad2:\n    def __call__(self, y: int, *rest: str) -> int: pass\ncall_soon(Good())\ncall_soon(Bad1()) # E: Argument 1 to \"call_soon\" has incompatible type \"Bad1\"; expected \"def (x: int, *str) -> int\" \\\n                  # N: \"Bad1.__call__\" has type \"def __call__(self, x: int, *rest: int) -> int\"\ncall_soon(Bad2()) # E: Argument 1 to \"call_soon\" has incompatible type \"Bad2\"; expected \"def (x: int, *str) -> int\" \\\n                  # N: \"Bad2.__call__\" has type \"def __call__(self, y: int, *rest: str) -> int\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testStructuralSupportForPartial]\nfrom typing import Callable, TypeVar, Generic, Any\n\nT = TypeVar('T')\n\nclass partial(Generic[T]):\n    def __init__(self, func: Callable[..., T], *args: Any) -> None: ...\n    def __call__(self, *args: Any) -> T: ...\n\ndef inc(a: int, temp: str) -> int:\n    pass\n\ndef foo(f: Callable[[int], T]) -> T:\n    return f(1)\n\nreveal_type(foo(partial(inc, 'temp'))) # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testStructuralInferenceForCallable]\nfrom typing import Callable, TypeVar, Tuple\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass Actual:\n    def __call__(self, arg: int) -> str: pass\n\ndef fun(cb: Callable[[T], S]) -> Tuple[T, S]: pass\nreveal_type(fun(Actual())) # N: Revealed type is \"tuple[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n-- Standard protocol types (SupportsInt, Sized, etc.)\n-- --------------------------------------------------\n\n-- More tests could be added for types from typing converted to protocols\n\n[case testBasicSizedProtocol]\nfrom typing import Sized\n\nclass Foo:\n    def __len__(self) -> int:\n        return 42\n\ndef bar(a: Sized) -> int:\n    return a.__len__()\n\nbar(Foo())\nbar((1, 2))\nbar(1) # E: Argument 1 to \"bar\" has incompatible type \"int\"; expected \"Sized\"\n\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-medium.pyi]\n\n[case testBasicSupportsIntProtocol]\nfrom typing import SupportsInt\n\nclass Bar:\n    def __int__(self):\n        return 1\n\ndef foo(a: SupportsInt):\n    pass\n\nfoo(Bar())\nfoo('no way') # E: Argument 1 to \"foo\" has incompatible type \"str\"; expected \"SupportsInt\"\n\n[builtins fixtures/isinstancelist.pyi]\n[typing fixtures/typing-medium.pyi]\n\n-- Additional tests and corner cases for protocols\n-- ----------------------------------------------\n\n[case testAnyWithProtocols]\nfrom typing import Protocol, Any, TypeVar\n\nT = TypeVar('T')\n\nclass P1(Protocol):\n    attr1: int\nclass P2(Protocol[T]):\n    attr2: T\nclass P3(Protocol):\n    attr: P3\n\ndef f1(x: P1) -> None: pass\ndef f2(x: P2[str]) -> None: pass\ndef f3(x: P3) -> None: pass\n\nclass C1:\n    attr1: Any\nclass C2:\n    attr2: Any\nclass C3:\n    attr: Any\n\nf1(C1())\nf2(C2())\nf3(C3())\n\nf2(C3())  # E: Argument 1 to \"f2\" has incompatible type \"C3\"; expected \"P2[str]\"\na: Any\nf1(a)\nf2(a)\nf3(a)\n\n[case testErrorsForProtocolsInDifferentPlaces]\nfrom typing import Protocol\n\nclass P(Protocol):\n    attr1: int\n    attr2: str\n    attr3: int\n\nclass C:\n    attr1: str\n    @property\n    def attr2(self) -> int: pass\n\nx: P = C() # E: Incompatible types in assignment (expression has type \"C\", variable has type \"P\") \\\n           # N: \"C\" is missing following \"P\" protocol member: \\\n           # N:     attr3 \\\n           # N: Following member(s) of \"C\" have conflicts: \\\n           # N:     attr1: expected \"int\", got \"str\" \\\n           # N:     attr2: expected \"str\", got \"int\" \\\n           # N: Protocol member P.attr2 expected settable variable, got read-only attribute\n\ndef f(x: P) -> P:\n    return C() # E: Incompatible return value type (got \"C\", expected \"P\") \\\n               # N: \"C\" is missing following \"P\" protocol member: \\\n               # N:     attr3 \\\n               # N: Following member(s) of \"C\" have conflicts: \\\n               # N:     attr1: expected \"int\", got \"str\" \\\n               # N:     attr2: expected \"str\", got \"int\" \\\n               # N: Protocol member P.attr2 expected settable variable, got read-only attribute\n\nf(C()) # E: Argument 1 to \"f\" has incompatible type \"C\"; expected \"P\" \\\n       # N: \"C\" is missing following \"P\" protocol member: \\\n       # N:     attr3 \\\n       # N: Following member(s) of \"C\" have conflicts: \\\n       # N:     attr1: expected \"int\", got \"str\" \\\n       # N:     attr2: expected \"str\", got \"int\" \\\n       # N: Protocol member P.attr2 expected settable variable, got read-only attribute\n[builtins fixtures/list.pyi]\n\n[case testIterableProtocolOnClass]\nfrom typing import TypeVar, Iterator\nT = TypeVar('T', bound='A')\n\nclass A:\n    def __iter__(self: T) -> Iterator[T]: pass\n\nclass B(A): pass\n\nreveal_type(list(b for b in B()))  # N: Revealed type is \"builtins.list[__main__.B]\"\nreveal_type(list(B()))  # N: Revealed type is \"builtins.list[__main__.B]\"\n[builtins fixtures/list.pyi]\n\n[case testIterableProtocolOnMetaclass]\nfrom typing import TypeVar, Iterator, Type\nT = TypeVar('T')\n\nclass EMeta(type):\n    def __iter__(self: Type[T]) -> Iterator[T]: pass\n\nclass E(metaclass=EMeta):\n    pass\n\nclass C(E):\n    pass\n\nreveal_type(list(c for c in C))  # N: Revealed type is \"builtins.list[__main__.C]\"\nreveal_type(list(C))  # N: Revealed type is \"builtins.list[__main__.C]\"\n[builtins fixtures/list.pyi]\n\n[case testClassesGetattrWithProtocols]\nfrom typing import Protocol\n\nclass P(Protocol):\n    attr: int\n\nclass PP(Protocol):\n    @property\n    def attr(self) -> int:\n        pass\n\nclass C:\n    def __getattr__(self, attr: str) -> int:\n        pass\nclass C2(C):\n    def __setattr__(self, attr: str, val: int) -> None:\n        pass\n\nclass D:\n    def __getattr__(self, attr: str) -> str:\n        pass\n\ndef fun(x: P) -> None:\n    reveal_type(P.attr) # N: Revealed type is \"builtins.int\"\ndef fun_p(x: PP) -> None:\n    reveal_type(P.attr) # N: Revealed type is \"builtins.int\"\n\nfun(C())  # E: Argument 1 to \"fun\" has incompatible type \"C\"; expected \"P\" \\\n          # N: Protocol member P.attr expected settable variable, got read-only attribute\nfun(C2())\nfun_p(D())  # E: Argument 1 to \"fun_p\" has incompatible type \"D\"; expected \"PP\" \\\n            # N: Following member(s) of \"D\" have conflicts: \\\n            # N:     attr: expected \"int\", got \"str\"\nfun_p(C())  # OK\n[builtins fixtures/list.pyi]\n\n[case testImplicitTypesInProtocols]\nfrom typing import Protocol\n\nclass P(Protocol):\n    x = 1  # E: All protocol members must have explicitly declared types\n\nclass C:\n    x: int\n\nclass D:\n    x: str\n\nx: P\nx = D() # E: Incompatible types in assignment (expression has type \"D\", variable has type \"P\") \\\n        # N: Following member(s) of \"D\" have conflicts: \\\n        # N:     x: expected \"int\", got \"str\"\nx = C() # OK\n[builtins fixtures/list.pyi]\n\n[case testProtocolIncompatibilityWithGenericMethod]\nfrom typing import Protocol, TypeVar\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass A(Protocol):\n    def f(self, x: T) -> None: pass\nclass B:\n    def f(self, x: S, y: T) -> None: pass\n\nx: A = B()\n[out]\nmain:11: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nmain:11: note: Following member(s) of \"B\" have conflicts:\nmain:11: note:     Expected:\nmain:11: note:         def [T] f(self, x: T) -> None\nmain:11: note:     Got:\nmain:11: note:         def [S, T] f(self, x: S, y: T) -> None\n\n[case testProtocolIncompatibilityWithGenericMethodBounded]\nfrom typing import Protocol, TypeVar\n\nT = TypeVar('T')\nS = TypeVar('S', bound=int)\n\nclass A(Protocol):\n    def f(self, x: T) -> None: pass\nclass B:\n    def f(self, x: S, y: T) -> None: pass\n\nx: A = B()\n[out]\nmain:11: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nmain:11: note: Following member(s) of \"B\" have conflicts:\nmain:11: note:     Expected:\nmain:11: note:         def [T] f(self, x: T) -> None\nmain:11: note:     Got:\nmain:11: note:         def [S: int, T] f(self, x: S, y: T) -> None\n\n[case testProtocolIncompatibilityWithGenericRestricted]\nfrom typing import Protocol, TypeVar\n\nT = TypeVar('T')\nS = TypeVar('S', int, str)\n\nclass A(Protocol):\n    def f(self, x: T) -> None: pass\nclass B:\n    def f(self, x: S, y: T) -> None: pass\n\nx: A = B()\n[out]\nmain:11: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nmain:11: note: Following member(s) of \"B\" have conflicts:\nmain:11: note:     Expected:\nmain:11: note:         def [T] f(self, x: T) -> None\nmain:11: note:     Got:\nmain:11: note:         def [S: (int, str), T] f(self, x: S, y: T) -> None\n\n[case testProtocolIncompatibilityWithManyOverloads]\nfrom typing import Protocol, overload\n\nclass C1: pass\nclass C2: pass\nclass A(Protocol):\n    @overload\n    def f(self, x: int) -> int: pass\n    @overload\n    def f(self, x: str) -> str: pass\n    @overload\n    def f(self, x: C1) -> C2: pass\n    @overload\n    def f(self, x: C2) -> C1: pass\n\nclass B:\n    def f(self) -> None: pass\n\nx: A = B()\n[out]\nmain:18: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nmain:18: note: Following member(s) of \"B\" have conflicts:\nmain:18: note:     Expected:\nmain:18: note:         @overload\nmain:18: note:         def f(self, x: int) -> int\nmain:18: note:         @overload\nmain:18: note:         def f(self, x: str) -> str\nmain:18: note:         @overload\nmain:18: note:         def f(self, x: C1) -> C2\nmain:18: note:         @overload\nmain:18: note:         def f(self, x: C2) -> C1\nmain:18: note:     Got:\nmain:18: note:         def f(self) -> None\n\n[case testProtocolIncompatibilityWithManyConflicts]\nfrom typing import Protocol\n\nclass A(Protocol):\n    def f(self, x: int) -> None: pass\n    def g(self, x: int) -> None: pass\n    def h(self, x: int) -> None: pass\n    def i(self, x: int) -> None: pass\nclass B:\n    def f(self, x: str) -> None: pass\n    def g(self, x: str) -> None: pass\n    def h(self, x: str) -> None: pass\n    def i(self, x: str) -> None: pass\n\nx: A = B()\n[out]\nmain:14: error: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\nmain:14: note: Following member(s) of \"B\" have conflicts:\nmain:14: note:     Expected:\nmain:14: note:         def f(self, x: int) -> None\nmain:14: note:     Got:\nmain:14: note:         def f(self, x: str) -> None\nmain:14: note:     Expected:\nmain:14: note:         def g(self, x: int) -> None\nmain:14: note:     Got:\nmain:14: note:         def g(self, x: str) -> None\nmain:14: note:     <2 more conflict(s) not shown>\n\n[case testProtocolIncompatibilityWithUnionType]\nfrom typing import Any, Optional, Protocol\n\nclass A(Protocol):\n    def execute(self, statement: Any, *args: Any, **kwargs: Any) -> None: ...\n\nclass B(Protocol):\n    def execute(self, stmt: Any, *args: Any, **kwargs: Any) -> None: ...\n    def cool(self) -> None: ...\n\ndef func1(arg: A) -> None: ...\ndef func2(arg: Optional[A]) -> None: ...\n\nx: B\nfunc1(x)\nfunc2(x)\n[builtins fixtures/dict.pyi]\n[out]\nmain:14: error: Argument 1 to \"func1\" has incompatible type \"B\"; expected \"A\"\nmain:14: note: Following member(s) of \"B\" have conflicts:\nmain:14: note:     Expected:\nmain:14: note:         def execute(self, statement: Any, *args: Any, **kwargs: Any) -> None\nmain:14: note:     Got:\nmain:14: note:         def execute(self, stmt: Any, *args: Any, **kwargs: Any) -> None\nmain:15: error: Argument 1 to \"func2\" has incompatible type \"B\"; expected \"A | None\"\nmain:15: note: Following member(s) of \"B\" have conflicts:\nmain:15: note:     Expected:\nmain:15: note:         def execute(self, statement: Any, *args: Any, **kwargs: Any) -> None\nmain:15: note:     Got:\nmain:15: note:         def execute(self, stmt: Any, *args: Any, **kwargs: Any) -> None\n\n[case testDontShowNotesForTupleAndIterableProtocol]\nfrom typing import Iterable, Sequence, Protocol, NamedTuple\n\nclass N(NamedTuple):\n    x: int\n\ndef f1(x: Iterable[str]) -> None: pass\ndef f2(x: Sequence[str]) -> None: pass\n\n# The errors below should be short\nf1(N(1))  # E: Argument 1 to \"f1\" has incompatible type \"N\"; expected \"Iterable[str]\"\nf2(N(2))  # E: Argument 1 to \"f2\" has incompatible type \"N\"; expected \"Sequence[str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNotManyFlagConflitsShownInProtocols]\nfrom typing import Protocol\n\nclass AllSettable(Protocol):\n    a: int\n    b: int\n    c: int\n    d: int\n\nclass AllReadOnly:\n    @property\n    def a(self) -> int: pass\n    @property\n    def b(self) -> int: pass\n    @property\n    def c(self) -> int: pass\n    @property\n    def d(self) -> int: pass\n\nx: AllSettable = AllReadOnly()\n[builtins fixtures/property.pyi]\n[out]\nmain:19: error: Incompatible types in assignment (expression has type \"AllReadOnly\", variable has type \"AllSettable\")\nmain:19: note: Protocol member AllSettable.a expected settable variable, got read-only attribute\nmain:19: note: Protocol member AllSettable.b expected settable variable, got read-only attribute\nmain:19: note:     <2 more conflict(s) not shown>\n\n[case testProtocolsMoreConflictsNotShown]\nfrom typing import Generic, Protocol, TypeVar\n\nT = TypeVar('T')\n\nclass MockMapping(Protocol[T]):\n    def a(self, x: T) -> int: pass\n    def b(self, x: T) -> int: pass\n    def c(self, x: T) -> int: pass\n    d: T\n    e: T\n    f: T\n\nclass MockDict(MockMapping[T]):\n    more: int\n\ndef f(x: MockMapping[int]) -> None: pass\nx: MockDict[str]\nf(x)  # E: Argument 1 to \"f\" has incompatible type \"MockDict[str]\"; expected \"MockMapping[int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testProtocolNotesForComplexSignatures]\nfrom typing import Protocol, Optional\n\nclass P(Protocol):\n    def meth(self, x: int, *args: str) -> None: pass\n    def other(self, *args, hint: Optional[str] = None, **kwargs: str) -> None: pass\nclass C:\n    def meth(self) -> int: pass\n    def other(self) -> int: pass\n\nx: P = C()\n[builtins fixtures/dict.pyi]\n[out]\nmain:10: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\nmain:10: note: Following member(s) of \"C\" have conflicts:\nmain:10: note:     Expected:\nmain:10: note:         def meth(self, x: int, *args: str) -> None\nmain:10: note:     Got:\nmain:10: note:         def meth(self) -> int\nmain:10: note:     Expected:\nmain:10: note:         def other(self, *args: Any, hint: str | None = ..., **kwargs: str) -> None\nmain:10: note:     Got:\nmain:10: note:         def other(self) -> int\n\n[case testObjectAllowedInProtocolBases]\nfrom typing import Protocol\nclass P(Protocol, object):\n    pass\n[out]\n\n[case testNoneSubtypeOfEmptyProtocol]\nfrom typing import Protocol\nclass P(Protocol):\n    pass\n\nx: P = None\n[out]\n\n[case testNoneSubtypeOfAllProtocolsWithoutStrictOptional]\n# flags: --no-strict-optional\nfrom typing import Protocol\nclass P(Protocol):\n    attr: int\n    def meth(self, arg: str) -> str:\n        pass\n\nx: P = None\n[out]\n\n[case testNoneSubtypeOfEmptyProtocolStrict]\nfrom typing import Protocol\nclass P(Protocol):\n    pass\nx: P = None\n\nclass PBad(Protocol):\n    x: int\ny: PBad = None  # E: Incompatible types in assignment (expression has type \"None\", variable has type \"PBad\")\n[out]\n\n[case testOnlyMethodProtocolUsableWithIsSubclass]\nfrom typing import Protocol, runtime_checkable, Union, Type, Sequence, overload\n@runtime_checkable\nclass P(Protocol):\n    def meth(self) -> int:\n        pass\n@runtime_checkable\nclass PBad(Protocol):\n    x: str\n\nclass C:\n    x: str\n    def meth(self) -> int:\n        pass\nclass E: pass\n\ncls: Type[Union[C, E]]\nissubclass(cls, PBad)  # E: Only protocols that don't have non-method members can be used with issubclass() \\\n                       # N: Protocol \"PBad\" has non-method member(s): x\nif issubclass(cls, P):\n    reveal_type(cls)  # N: Revealed type is \"type[__main__.C]\"\nelse:\n    reveal_type(cls)  # N: Revealed type is \"type[__main__.E]\"\n\n@runtime_checkable\nclass POverload(Protocol):\n    @overload\n    def meth(self, a: int) -> float: ...\n    @overload\n    def meth(self, a: str) -> Sequence[float]: ...\n    def meth(self, a):\n        pass\n\nreveal_type(issubclass(int, POverload))  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-full.pyi]\n[out]\n\n[case testCallableImplementsProtocol]\nfrom typing import Protocol\n\nclass Caller(Protocol):\n    def __call__(self, x: str, *args: int) -> None: ...\n\ndef call(x: str, *args: int) -> None:\n    pass\ndef bad(x: int, *args: str) -> None:\n    pass\n\ndef func(caller: Caller) -> None:\n    pass\n\nfunc(call)\nfunc(bad)  # E: Argument 1 to \"func\" has incompatible type \"def bad(x: int, *args: str) -> None\"; expected \"Caller\" \\\n           # N: \"Caller.__call__\" has type \"def __call__(self, x: str, *args: int) -> None\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCallableImplementsProtocolGeneric]\nfrom typing import Protocol, TypeVar, Tuple\n\nT = TypeVar('T')\nS = TypeVar('S')\n\nclass Caller(Protocol[T, S]):\n    def __call__(self, x: T, y: S) -> Tuple[T, S]: ...\n\ndef call(x: int, y: str) -> Tuple[int, str]: ...\n\ndef func(caller: Caller[T, S]) -> Tuple[T, S]:\n    pass\n\nreveal_type(func(call))  # N: Revealed type is \"tuple[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCallableImplementsProtocolGenericTight]\nfrom typing import Protocol, TypeVar\n\nT = TypeVar('T')\n\nclass Caller(Protocol):\n    def __call__(self, x: T) -> T: ...\n\ndef call(x: T) -> T: ...\ndef bad(x: int) -> int: ...\n\ndef func(caller: Caller) -> None:\n    pass\n\nfunc(call)\nfunc(bad)  # E: Argument 1 to \"func\" has incompatible type \"Callable[[int], int]\"; expected \"Caller\" \\\n           # N: \"Caller.__call__\" has type \"def [T] __call__(self, x: T) -> T\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCallableImplementsProtocolGenericNotGeneric]\nfrom typing import Protocol, TypeVar, Tuple\n\nT = TypeVar('T')\n\nclass Caller(Protocol):\n    def __call__(self, x: int) -> int: ...\n\ndef call(x: T) -> T: ...\n\ndef bad(x: T) -> Tuple[T, T]: ...\n\ndef func(caller: Caller) -> None:\n    pass\n\nfunc(call)\nfunc(bad)  # E: Argument 1 to \"func\" has incompatible type \"Callable[[T], tuple[T, T]]\"; expected \"Caller\" \\\n           # N: \"Caller.__call__\" has type \"def __call__(self, x: int) -> int\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCallableImplementsProtocolOverload]\nfrom typing import Protocol, overload, Union\n\nclass Caller(Protocol):\n    @overload\n    def __call__(self, x: int) -> int: ...\n    @overload\n    def __call__(self, x: str) -> str: ...\n\n@overload\ndef call(x: int) -> int: ...\n@overload\ndef call(x: str) -> str: ...\ndef call(x: Union[int, str]) -> Union[int, str]:\n    pass\n\ndef bad(x: Union[int, str]) -> Union[int, str]:\n    pass\n\ndef func(caller: Caller) -> None:\n    pass\n\nfunc(call)\nfunc(bad)  # E: Argument 1 to \"func\" has incompatible type \"Callable[[int | str], int | str]\"; expected \"Caller\" \\\n           # N: \"Caller.__call__\" has type overloaded function\n[out]\n\n[case testCallableImplementsProtocolExtraNote]\nfrom typing import Protocol\n\nclass Caller(Protocol):\n    def __call__(self, x: str, *args: int) -> None: ...\n\ndef bad(x: int, *args: str) -> None:\n    pass\n\ncb: Caller = bad  # E: Incompatible types in assignment (expression has type \"def bad(x: int, *args: str) -> None\", variable has type \"Caller\") \\\n                  # N: \"Caller.__call__\" has type \"def __call__(self, x: str, *args: int) -> None\"\n[builtins fixtures/tuple.pyi]\n[out]\n\n[case testCallableImplementsProtocolArgName]\nfrom typing import Protocol\n\nclass Caller(Protocol):\n    def __call__(self, x: str) -> None: ...\n\nclass CallerAnon(Protocol):\n    def __call__(self, __x: str) -> None: ...\n\ndef call(x: str) -> None:\n    pass\ndef bad(y: str) -> None:\n    pass\n\ndef func(caller: Caller) -> None:\n    pass\n\ndef anon(caller: CallerAnon) -> None:\n    pass\n\n\nfunc(call)\nfunc(bad)  # E: Argument 1 to \"func\" has incompatible type \"Callable[[str], None]\"; expected \"Caller\" \\\n           # N: \"Caller.__call__\" has type \"def __call__(self, x: str) -> None\"\nanon(bad)\n[out]\n\n[case testCallableProtocolVsProtocol]\nfrom typing import Protocol\n\nclass One(Protocol):\n    def __call__(self, x: str) -> None: ...\n\nclass Other(Protocol):\n    def __call__(self, x: str) -> None: ...\n\nclass Bad(Protocol):\n    def __call__(self, zzz: str) -> None: ...\n\ndef func(caller: One) -> None:\n    pass\n\na: Other\nb: Bad\n\nfunc(a)\nfunc(b)  # E: Argument 1 to \"func\" has incompatible type \"Bad\"; expected \"One\" \\\n         # N: \"One.__call__\" has type \"def __call__(self, x: str) -> None\"\n[out]\n\n[case testJoinProtocolCallback]\nfrom typing import Protocol, Callable\n\nclass A: ...\nclass B(A): ...\nclass C(B): ...\nclass D(B): ...\n\nclass Call(Protocol):\n    def __call__(self, x: B) -> C: ...\nNormal = Callable[[A], D]\n\na: Call\nb: Normal\n\nreveal_type([a, b])  # N: Revealed type is \"builtins.list[def (__main__.B) -> __main__.B]\"\nreveal_type([b, a])  # N: Revealed type is \"builtins.list[def (__main__.B) -> __main__.B]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testMeetProtocolCallback]\nfrom typing import Protocol, Callable\n\nclass A: ...\nclass B(A): ...\nclass C(B): ...\nclass D(B): ...\n\nclass Call(Protocol):\n    def __call__(self, __x: C) -> B: ...\nNormal = Callable[[D], A]\n\ndef a(x: Call) -> None: ...\ndef b(x: Normal) -> None: ...\n\nreveal_type([a, b])  # N: Revealed type is \"builtins.list[def (x: def (__main__.B) -> __main__.B)]\"\nreveal_type([b, a])  # N: Revealed type is \"builtins.list[def (x: def (__main__.B) -> __main__.B)]\"\n[builtins fixtures/list.pyi]\n[out]\n\n[case testCallbackProtocolFunctionAttributesSubtyping]\nfrom typing import Protocol\n\nclass A(Protocol):\n    __name__: str\n    def __call__(self) -> str: ...\n\nclass B1(Protocol):\n    __name__: int\n    def __call__(self) -> str: ...\n\nclass B2(Protocol):\n    __name__: str\n    def __call__(self) -> int: ...\n\nclass B3(Protocol):\n    __name__: str\n    extra_stuff: int\n    def __call__(self) -> str: ...\n\ndef f() -> str: ...\n\nreveal_type(f.__name__)  # N: Revealed type is \"builtins.str\"\na: A = f  # OK\nb1: B1 = f  # E: Incompatible types in assignment (expression has type \"Callable[[], str]\", variable has type \"B1\") \\\n            # N: Following member(s) of \"function\" have conflicts: \\\n            # N:     __name__: expected \"int\", got \"str\"\nb2: B2 = f  # E: Incompatible types in assignment (expression has type \"Callable[[], str]\", variable has type \"B2\") \\\n            # N: \"B2.__call__\" has type \"Callable[[], int]\"\nb3: B3 = f  # E: Incompatible types in assignment (expression has type \"Callable[[], str]\", variable has type \"B3\") \\\n            # N: \"function\" is missing following \"B3\" protocol member: \\\n            # N:     extra_stuff\n\n[case testCallbackProtocolFunctionAttributesInference]\nfrom typing import Protocol, TypeVar, Generic, Tuple\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\", covariant=True)\nclass A(Protocol[T, S]):\n    __name__: T\n    def __call__(self) -> S: ...\n\ndef f() -> int: ...\ndef test(func: A[T, S]) -> Tuple[T, S]: ...\nreveal_type(test(f))  # N: Revealed type is \"tuple[builtins.str, builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testProtocolsAlwaysABCs]\nfrom typing import Protocol\n\nclass P(Protocol): ...\nclass C(P): ...\n\nreveal_type(C.register(int))  # N: Revealed type is \"def () -> builtins.int\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n[out]\n\n[case testProtocolVarianceAfterDecorators]\n# The test case is simplified, in reality this caused problems with @abstractmethod\n# in stubs and test fixtures.\nfrom typing import Protocol, TypeVar\n\nT = TypeVar('T')\ndef dec(x: T) -> T: ...\nalias = dec\n\nclass P(Protocol[T]):\n    @alias\n    def meth(self, arg: T) -> T: ...\n[out]\n\n[case testNamedTupleWithNoArgsCallableField]\nfrom typing import Callable, NamedTuple, Protocol\n\nclass N(NamedTuple):\n    func: Callable[[], str]\n\nclass P(Protocol):\n    @property\n    def func(self) -> Callable[[], str]: ...\n\np: P = N(lambda: 'foo')\n[builtins fixtures/property.pyi]\n\n[case testNamedTupleWithManyArgsCallableField]\nfrom typing import Callable, NamedTuple, Protocol\n\nclass N(NamedTuple):\n    func: Callable[[str, str, str], str]\n\nclass P(Protocol):\n    @property\n    def func(self) -> Callable[[str, str, str], str]: ...\n\np: P = N(lambda a, b, c: 'foo')\n[builtins fixtures/property.pyi]\n\n[case testLiteralsAgainstProtocols]\nfrom typing import Final, Literal, SupportsInt, SupportsAbs, TypeVar\n\nT = TypeVar('T')\ndef abs(x: SupportsAbs[T]) -> T: ...\ndef foo(x: SupportsInt) -> None: ...\n\nONE: Final = 1\nTWO: Literal[2]\nALL: Literal[1, 2, 3]\n\nfoo(ONE)\nfoo(TWO)\nfoo(3)\n\nreveal_type(abs(ONE))  # N: Revealed type is \"builtins.int\"\nreveal_type(abs(TWO))  # N: Revealed type is \"builtins.int\"\nreveal_type(abs(3))  # N: Revealed type is \"builtins.int\"\nreveal_type(abs(ALL))  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/float.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testProtocolWithSlots]\nfrom typing import Protocol\n\nclass A(Protocol):\n    __slots__ = ()\n\n[builtins fixtures/tuple.pyi]\n\n[case testProtocolSlotsIsNotProtocolMember]\n# https://github.com/python/mypy/issues/11884\nfrom typing import Protocol\n\nclass Foo(Protocol):\n    __slots__ = ()\nclass NoSlots:\n    pass\nclass EmptySlots:\n    __slots__ = ()\nclass TupleSlots:\n    __slots__ = ('x', 'y')\nclass StringSlots:\n    __slots__ = 'x y'\nclass InitSlots:\n    __slots__ = ('x',)\n    def __init__(self) -> None:\n        self.x = None\ndef foo(f: Foo):\n    pass\n\n# All should pass:\nfoo(NoSlots())\nfoo(EmptySlots())\nfoo(TupleSlots())\nfoo(StringSlots())\nfoo(InitSlots())\n[builtins fixtures/tuple.pyi]\n\n[case testProtocolSlotsAndRuntimeCheckable]\nfrom typing import Protocol, runtime_checkable\n\n@runtime_checkable\nclass Foo(Protocol):\n    __slots__ = ()\nclass Bar:\n    pass\nissubclass(Bar, Foo)  # Used to be an error, when `__slots__` counted as a protocol member\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-full.pyi]\n\n\n[case testProtocolWithClassGetItem]\n# https://github.com/python/mypy/issues/11886\nfrom typing import Any, Iterable, Protocol, Union\n\nclass B:\n    ...\n\nclass C:\n    def __class_getitem__(cls, __item: Any) -> Any:\n        ...\n\nclass SupportsClassGetItem(Protocol):\n    __slots__: Union[str, Iterable[str]] = ()\n    def __class_getitem__(cls, __item: Any) -> Any:\n        ...\n\nb1: SupportsClassGetItem = B()\nc1: SupportsClassGetItem = C()\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n\n[case testNoneVsProtocol]\n# mypy: strict-optional\nfrom typing import Protocol\n\nclass MyHashable(Protocol):\n    def __hash__(self) -> int: ...\n\ndef f(h: MyHashable) -> None: pass\nf(None)\n\nclass Proto(Protocol):\n    def __hash__(self) -> int: ...\n    def method(self) -> None: ...\n\ndef g(h: Proto) -> None: pass\ng(None)  # E: Argument 1 to \"g\" has incompatible type \"None\"; expected \"Proto\"\n\nclass Proto2(Protocol):\n    def hash(self) -> None: ...\n\ndef h(h: Proto2) -> None: pass\nh(None)  # E: Argument 1 to \"h\" has incompatible type \"None\"; expected \"Proto2\"\n\nclass EmptyProto(Protocol): ...\n\ndef hh(h: EmptyProto) -> None: pass\nhh(None)\n\n# See https://github.com/python/mypy/issues/13081\nclass SupportsStr(Protocol):\n    def __str__(self) -> str: ...\n\ndef ss(s: SupportsStr) -> None: pass\nss(None)\n\nclass HashableStr(Protocol):\n    def __str__(self) -> str: ...\n    def __hash__(self) -> int: ...\n\ndef hs(n: HashableStr) -> None: pass\nhs(None)\n[builtins fixtures/tuple.pyi]\n\n\n[case testPartialTypeProtocol]\n# flags: --no-local-partial-types\nfrom typing import Protocol\n\nclass Flapper(Protocol):\n    def flap(self) -> int: ...\n\nclass Blooper:\n    flap = None\n\n    def bloop(self, x: Flapper) -> None:\n        reveal_type([self, x])  # N: Revealed type is \"builtins.list[builtins.object]\"\n\nclass Gleemer:\n    flap = []  # E: Need type annotation for \"flap\" (hint: \"flap: list[<type>] = ...\")\n\n    def gleem(self, x: Flapper) -> None:\n        reveal_type([self, x])  # N: Revealed type is \"builtins.list[builtins.object]\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testPartialTypeProtocolHashable]\n# flags: --no-strict-optional --no-local-partial-types\nfrom typing import Protocol\n\nclass Hashable(Protocol):\n    def __hash__(self) -> int: ...\n\nclass ObjectHashable:\n    def __hash__(self) -> int: ...\n\nclass DataArray(ObjectHashable):\n    __hash__ = None\n\n    def f(self, x: Hashable) -> None:\n        reveal_type([self, x])  # N: Revealed type is \"builtins.list[builtins.object]\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testPartialTypeProtocolHashableLocalPartialTypes]\n# flags: --no-strict-optional --local-partial-types\nfrom typing import Protocol\n\nclass Hashable(Protocol):\n    def __hash__(self) -> int: ...\n\nclass ObjectHashable:\n    def __hash__(self) -> int: ...\n\nclass DataArray(ObjectHashable):\n    __hash__ = None\n\n    def f(self, x: Hashable) -> None:\n        reveal_type([self, x])  # N: Revealed type is \"builtins.list[builtins.object]\"\n[builtins fixtures/tuple.pyi]\n\n\n[case testPartialAttributeNoneType]\n# flags: --no-strict-optional --no-local-partial-types\nfrom typing import Optional, Protocol, runtime_checkable\n\n@runtime_checkable\nclass MyProtocol(Protocol):\n    def is_valid(self) -> bool: ...\n    text: Optional[str]\n\nclass MyClass:\n    text = None\n    def is_valid(self) -> bool:\n        reveal_type(self.text)  # N: Revealed type is \"None\"\n        assert isinstance(self, MyProtocol)\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-full.pyi]\n\n\n[case testPartialAttributeNoneTypeStrictOptional]\n# flags: --no-local-partial-types\nfrom typing import Optional, Protocol, runtime_checkable\n\n@runtime_checkable\nclass MyProtocol(Protocol):\n    def is_valid(self) -> bool: ...\n    text: Optional[str]\n\nclass MyClass:\n    text = None\n    def is_valid(self) -> bool:\n        reveal_type(self.text)  # N: Revealed type is \"None\"\n        assert isinstance(self, MyProtocol)\n[builtins fixtures/isinstance.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testProtocolAndTypeVariableSpecialCase]\nfrom typing import TypeVar, Iterable, Optional, Callable, Protocol\n\nT_co = TypeVar('T_co', covariant=True)\n\nclass SupportsNext(Protocol[T_co]):\n    def __next__(self) -> T_co: ...\n\nN = TypeVar(\"N\", bound=SupportsNext, covariant=True)\n\nclass SupportsIter(Protocol[T_co]):\n    def __iter__(self) -> T_co: ...\n\ndef f(i: SupportsIter[N]) -> N: ...\n\nI = TypeVar('I', bound=Iterable)\n\ndef g(x: I, y: Iterable) -> None:\n    f(x)\n    f(y)\n\n[case testMatchProtocolAgainstOverloadWithAmbiguity]\nfrom typing import TypeVar, Protocol, Union, Generic, overload\n\nT = TypeVar(\"T\", covariant=True)\n\nclass slice: pass\n\nclass GetItem(Protocol[T]):\n    def __getitem__(self, k: int) -> T: ...\n\nclass Str:  # Resembles 'str'\n    def __getitem__(self, k: Union[int, slice]) -> Str: ...\n\nclass Lst(Generic[T]):  # Resembles 'list'\n    def __init__(self, x: T): ...\n    @overload\n    def __getitem__(self, k: int) -> T: ...\n    @overload\n    def __getitem__(self, k: slice) -> Lst[T]: ...\n    def __getitem__(self, k): pass\n\ndef f(x: GetItem[GetItem[Str]]) -> None: ...\n\na: Lst[Str]\nf(Lst(a))\n\nclass Lst2(Generic[T]):\n    def __init__(self, x: T): ...\n    # The overload items are tweaked but still compatible\n    @overload\n    def __getitem__(self, k: Str) -> None: ...\n    @overload\n    def __getitem__(self, k: slice) -> Lst2[T]: ...\n    @overload\n    def __getitem__(self, k: Union[int, str]) -> T: ...\n    def __getitem__(self, k): pass\n\nb: Lst2[Str]\nf(Lst2(b))\n\nclass Lst3(Generic[T]):  # Resembles 'list'\n    def __init__(self, x: T): ...\n    # The overload items are no longer compatible (too narrow argument type)\n    @overload\n    def __getitem__(self, k: slice) -> Lst3[T]: ...\n    @overload\n    def __getitem__(self, k: bool) -> T: ...\n    def __getitem__(self, k): pass\n\nc: Lst3[Str]\nf(Lst3(c))  # E: Argument 1 to \"f\" has incompatible type \"Lst3[Lst3[Str]]\"; expected \"GetItem[GetItem[Str]]\" \\\n# N: Following member(s) of \"Lst3[Lst3[Str]]\" have conflicts: \\\n# N:     Expected:                  \\\n# N:         def __getitem__(self, int, /) -> GetItem[Str] \\\n# N:     Got:                       \\\n# N:         @overload              \\\n# N:         def __getitem__(self, slice, /) -> Lst3[Lst3[Str]] \\\n# N:         @overload              \\\n# N:         def __getitem__(self, bool, /) -> Lst3[Str]\n\n[builtins fixtures/list.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testMatchProtocolAgainstOverloadWithMultipleMatchingItems]\nfrom typing import Protocol, overload, TypeVar, Any\n\n_T_co = TypeVar(\"_T_co\", covariant=True)\n_T = TypeVar(\"_T\")\n\nclass SupportsRound(Protocol[_T_co]):\n    @overload\n    def __round__(self) -> int: ...\n    @overload\n    def __round__(self, __ndigits: int) -> _T_co: ...\n\nclass C:\n    # This matches both overload items of SupportsRound\n    def __round__(self, __ndigits: int = ...) -> int: ...\n\ndef round(number: SupportsRound[_T], ndigits: int) -> _T: ...\n\nround(C(), 1)\n\n[case testEmptyBodyImplicitlyAbstractProtocol]\nfrom typing import Protocol, overload, Union\n\nclass P1(Protocol):\n    def meth(self) -> int: ...\nclass B1(P1): ...\nclass C1(P1):\n    def meth(self) -> int:\n        return 0\nB1()  # E: Cannot instantiate abstract class \"B1\" with abstract attribute \"meth\"\nC1()\n\nclass P2(Protocol):\n    @classmethod\n    def meth(cls) -> int: ...\nclass B2(P2): ...\nclass C2(P2):\n    @classmethod\n    def meth(cls) -> int:\n        return 0\nB2()  # E: Cannot instantiate abstract class \"B2\" with abstract attribute \"meth\"\nC2()\n\nclass P3(Protocol):\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n    @overload\n    def not_abstract(self, x: int) -> int: ...\n    @overload\n    def not_abstract(self, x: str) -> str: ...\n    def not_abstract(self, x: Union[int, str]) -> Union[int, str]:\n        return 0\nclass B3(P3): ...\nclass C3(P3):\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n    def meth(self, x: Union[int, str]) -> Union[int, str]:\n        return 0\nB3()  # E: Cannot instantiate abstract class \"B3\" with abstract attribute \"meth\"\nC3()\n[builtins fixtures/classmethod.pyi]\n\n[case testEmptyBodyImplicitlyAbstractProtocolProperty]\nfrom typing import Protocol\n\nclass P1(Protocol):\n    @property\n    def attr(self) -> int: ...\nclass B1(P1): ...\nclass C1(P1):\n    @property\n    def attr(self) -> int:\n        return 0\nB1()  # E: Cannot instantiate abstract class \"B1\" with abstract attribute \"attr\"\nC1()\n\nclass P2(Protocol):\n    @property\n    def attr(self) -> int: ...\n    @attr.setter\n    def attr(self, value: int) -> None: ...\nclass B2(P2): ...\nclass C2(P2):\n    @property\n    def attr(self) -> int: return 0\n    @attr.setter\n    def attr(self, value: int) -> None: pass\nB2()  # E: Cannot instantiate abstract class \"B2\" with abstract attribute \"attr\"\nC2()\n[builtins fixtures/property.pyi]\n\n[case testEmptyBodyImplicitlyAbstractProtocolStub]\nfrom stub import P1, P2, P3, P4\n\nclass B1(P1): ...\nclass B2(P2): ...\nclass B3(P3): ...\nclass B4(P4): ...\n\nB1()\nB2()\nB3()\nB4()  # E: Cannot instantiate abstract class \"B4\" with abstract attribute \"meth\"\n\n[file stub.pyi]\nfrom typing import Protocol, overload, Union\nfrom abc import abstractmethod\n\nclass P1(Protocol):\n    def meth(self) -> int: ...\n\nclass P2(Protocol):\n    @classmethod\n    def meth(cls) -> int: ...\n\nclass P3(Protocol):\n    @overload\n    def meth(self, x: int) -> int: ...\n    @overload\n    def meth(self, x: str) -> str: ...\n\nclass P4(Protocol):\n    @abstractmethod\n    def meth(self) -> int: ...\n[builtins fixtures/classmethod.pyi]\n\n[case testEmptyBodyVariationsImplicitlyAbstractProtocol]\nfrom typing import Protocol\n\nclass WithPass(Protocol):\n    def meth(self) -> int:\n        pass\nclass A(WithPass): ...\nA() # E: Cannot instantiate abstract class \"A\" with abstract attribute \"meth\"\n\nclass WithEllipses(Protocol):\n    def meth(self) -> int: ...\nclass B(WithEllipses): ...\nB() # E: Cannot instantiate abstract class \"B\" with abstract attribute \"meth\"\n\nclass WithDocstring(Protocol):\n    def meth(self) -> int:\n        \"\"\"Docstring for meth.\n\n\tThis is meth.\"\"\"\nclass C(WithDocstring): ...\nC() # E: Cannot instantiate abstract class \"C\" with abstract attribute \"meth\"\n\nclass WithRaise(Protocol):\n    def meth(self) -> int:\n        \"\"\"Docstring for meth.\"\"\"\n        raise NotImplementedError\nclass D(WithRaise): ...\nD() # E: Cannot instantiate abstract class \"D\" with abstract attribute \"meth\"\n[builtins fixtures/exception.pyi]\n\n[case testEmptyBodyNoneCompatibleProtocol]\nfrom abc import abstractmethod\nfrom typing import Any, Optional, Protocol, Union, overload\nfrom typing_extensions import TypeAlias\n\nNoneAlias: TypeAlias = None\n\nclass NoneCompatible(Protocol):\n    def f(self) -> None: ...\n    def g(self) -> Any: ...\n    def h(self) -> Optional[int]: ...\n    def i(self) -> NoneAlias: ...\n    @classmethod\n    def j(cls) -> None: ...\n\nclass A(NoneCompatible): ...\nA() # E: Cannot instantiate abstract class \"A\" with abstract attributes \"f\", \"g\", \"h\", \"i\" and \"j\" \\\n    # N: The following methods were marked implicitly abstract because they have empty function bodies: \"f\", \"g\", \"h\", \"i\" and \"j\". If they are not meant to be abstract, explicitly `return` or `return None`.\n\nclass NoneCompatible2(Protocol):\n    def f(self, x: int): ...\n\nclass B(NoneCompatible2): ...\nB() # E: Cannot instantiate abstract class \"B\" with abstract attribute \"f\" \\\n    # N: \"f\" is implicitly abstract because it has an empty function body. If it is not meant to be abstract, explicitly `return` or `return None`.\n\nclass NoneCompatible3(Protocol):\n    @abstractmethod\n    def f(self) -> None: ...\n    @overload\n    def g(self, x: int) -> int: ...\n    @overload\n    def g(self, x: str) -> None: ...\n    def h(self, x): ...\n\nclass C(NoneCompatible3): ...\nC() # E: Cannot instantiate abstract class \"C\" with abstract attributes \"f\", \"g\" and \"h\"\n[builtins fixtures/classmethod.pyi]\n\n[case testEmptyBodyWithFinal]\nfrom typing import Protocol, final\n\nclass P(Protocol):\n    @final          # E: Protocol member cannot be final\n    def f(self, x: int) -> str: ...\n\nclass A(P): ...\nA() # E: Cannot instantiate abstract class \"A\" with abstract attribute \"f\"\n\n[case testProtocolWithNestedClass]\nfrom typing import TypeVar, Protocol\n\nclass Template(Protocol):\n    var: int\n    class Meta: ...\n\nclass B:\n    var: int\n    class Meta: ...\nclass C:\n    var: int\n    class Meta(Template.Meta): ...\n\ndef foo(t: Template) -> None: ...\nfoo(B())  # E: Argument 1 to \"foo\" has incompatible type \"B\"; expected \"Template\" \\\n          # N: Following member(s) of \"B\" have conflicts: \\\n          # N:     Meta: expected \"type[__main__.Template.Meta]\", got \"type[__main__.B.Meta]\"\nfoo(C())  # OK\n\n[case testProtocolClassObjectAttribute]\nfrom typing import ClassVar, Protocol\n\nclass P(Protocol):\n    foo: int\n\nclass A:\n    foo = 42\nclass B:\n    foo: ClassVar[int]\nclass C:\n    foo: ClassVar[str]\nclass D:\n    foo: int\n\ndef test(arg: P) -> None: ...\ntest(A)  # OK\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     foo: expected \"int\", got \"str\"\ntest(D)  # E: Argument 1 to \"test\" has incompatible type \"type[D]\"; expected \"P\" \\\n         # N: Only class variables allowed for class object access on protocols, foo is an instance variable of \"D\"\n\n[case testProtocolClassObjectClassVarRejected]\nfrom typing import ClassVar, Protocol\n\nclass P(Protocol):\n    foo: ClassVar[int]\n\nclass B:\n    foo: ClassVar[int]\n\ndef test(arg: P) -> None: ...\ntest(B)  # E: Argument 1 to \"test\" has incompatible type \"type[B]\"; expected \"P\" \\\n         # N: ClassVar protocol member P.foo can never be matched by a class object\n\n[case testProtocolClassObjectPropertyRejected]\nfrom typing import ClassVar, Protocol\n\nclass P(Protocol):\n    @property\n    def foo(self) -> int: ...\n\nclass B:\n    @property\n    def foo(self) -> int: ...\nclass C:\n    foo: int\nclass D:\n    foo: ClassVar[int]\n\ndef test(arg: P) -> None: ...\n# TODO: skip type mismatch diagnostics in this case.\ntest(B)  # E: Argument 1 to \"test\" has incompatible type \"type[B]\"; expected \"P\" \\\n         # N: Following member(s) of \"B\" have conflicts: \\\n         # N:     foo: expected \"int\", got \"Callable[[B], int]\" \\\n         # N: Only class variables allowed for class object access on protocols, foo is an instance variable of \"B\"\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Only class variables allowed for class object access on protocols, foo is an instance variable of \"C\"\ntest(D)  # OK\n[builtins fixtures/property.pyi]\n\n[case testProtocolClassObjectInstanceMethod]\nfrom typing import Any, Protocol\n\nclass P(Protocol):\n    def foo(self, obj: Any) -> int: ...\n\nclass B:\n    def foo(self) -> int: ...\nclass C:\n    def foo(self) -> str: ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def foo(obj: Any) -> int \\\n         # N:     Got: \\\n         # N:         def foo(self: C) -> str\n\n[case testProtocolClassObjectInstanceMethodArg]\nfrom typing import Any, Protocol\n\nclass P(Protocol):\n    def foo(self, obj: B) -> int: ...\n\nclass B:\n    def foo(self) -> int: ...\nclass C:\n    def foo(self) -> int: ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def foo(obj: B) -> int \\\n         # N:     Got: \\\n         # N:         def foo(self: C) -> int\n\n[case testProtocolClassObjectInstanceMethodOverloaded]\nfrom typing import Any, Protocol, overload\n\nclass P(Protocol):\n    @overload\n    def foo(self, obj: Any, arg: int) -> int: ...\n    @overload\n    def foo(self, obj: Any, arg: str) -> str: ...\n\nclass B:\n    @overload\n    def foo(self, arg: int) -> int: ...\n    @overload\n    def foo(self, arg: str) -> str: ...\n    def foo(self, arg: Any) -> Any:\n        ...\n\nclass C:\n    @overload\n    def foo(self, arg: int) -> int: ...\n    @overload\n    def foo(self, arg: str) -> int: ...\n    def foo(self, arg: Any) -> Any:\n        ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         @overload \\\n         # N:         def foo(obj: Any, arg: int) -> int \\\n         # N:         @overload \\\n         # N:         def foo(obj: Any, arg: str) -> str \\\n         # N:     Got: \\\n         # N:         @overload \\\n         # N:         def foo(self: C, arg: int) -> int \\\n         # N:         @overload \\\n         # N:         def foo(self: C, arg: str) -> int\n\n[case testProtocolClassObjectClassMethod]\nfrom typing import Protocol\n\nclass P(Protocol):\n    def foo(self) -> int: ...\n\nclass B:\n    @classmethod\n    def foo(cls) -> int: ...\nclass C:\n    @classmethod\n    def foo(cls) -> str: ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def foo() -> int \\\n         # N:     Got: \\\n         # N:         def foo() -> str\n[builtins fixtures/classmethod.pyi]\n\n[case testProtocolClassObjectStaticMethod]\nfrom typing import Protocol\n\nclass P(Protocol):\n    def foo(self) -> int: ...\n\nclass B:\n    @staticmethod\n    def foo() -> int: ...\nclass C:\n    @staticmethod\n    def foo() -> str: ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def foo() -> int \\\n         # N:     Got: \\\n         # N:         def foo() -> str\n[builtins fixtures/staticmethod.pyi]\n\n[case testProtocolClassObjectGenericInstanceMethod]\nfrom typing import Any, Protocol, Generic, List, TypeVar\n\nclass P(Protocol):\n    def foo(self, obj: Any) -> List[int]: ...\n\nT = TypeVar(\"T\")\nclass A(Generic[T]):\n    def foo(self) -> T: ...\nclass AA(A[List[T]]): ...\n\nclass B(AA[int]): ...\nclass C(AA[str]): ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def foo(obj: Any) -> list[int] \\\n         # N:     Got: \\\n         # N:         def foo(self: A[list[str]]) -> list[str]\n[builtins fixtures/list.pyi]\n\n[case testProtocolClassObjectGenericClassMethod]\nfrom typing import Any, Protocol, Generic, List, TypeVar\n\nclass P(Protocol):\n    def foo(self) -> List[int]: ...\n\nT = TypeVar(\"T\")\nclass A(Generic[T]):\n    @classmethod\n    def foo(self) -> T: ...\nclass AA(A[List[T]]): ...\n\nclass B(AA[int]): ...\nclass C(AA[str]): ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def foo() -> list[int] \\\n         # N:     Got: \\\n         # N:         def foo() -> list[str]\n[builtins fixtures/isinstancelist.pyi]\n\n[case testProtocolClassObjectSelfTypeInstanceMethod]\nfrom typing import Protocol, TypeVar, Union\n\nT = TypeVar(\"T\")\nclass P(Protocol):\n    def foo(self, arg: T) -> T: ...\n\nclass B:\n    def foo(self: T) -> T: ...\nclass C:\n    def foo(self: T) -> Union[T, int]: ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def [T] foo(arg: T) -> T \\\n         # N:     Got: \\\n         # N:         def [T] foo(self: T) -> T | int\n\n[case testProtocolClassObjectSelfTypeClassMethod]\nfrom typing import Protocol, Type, TypeVar\n\nT = TypeVar(\"T\")\nclass P(Protocol):\n    def foo(self) -> B: ...\n\nclass B:\n    @classmethod\n    def foo(cls: Type[T]) -> T: ...\nclass C:\n    @classmethod\n    def foo(cls: Type[T]) -> T: ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def foo() -> B \\\n         # N:     Got: \\\n         # N:         def foo() -> C\n[builtins fixtures/classmethod.pyi]\n\n[case testProtocolClassObjectAttributeAndCall]\nfrom typing import Any, ClassVar, Protocol\n\nclass P(Protocol):\n    foo: int\n    def __call__(self, x: int, y: int) -> Any: ...\n\nclass B:\n    foo: ClassVar[int]\n    def __init__(self, x: int, y: int) -> None: ...\nclass C:\n    foo: ClassVar[int]\n    def __init__(self, x: int, y: str) -> None: ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: \"C\" has constructor incompatible with \"__call__\" of \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def __call__(x: int, y: int) -> Any \\\n         # N:     Got: \\\n         # N:         def C(x: int, y: str) -> C \\\n         # N: \"P.__call__\" has type \"def __call__(self, x: int, y: int) -> Any\"\n\n[case testProtocolClassObjectPureCallback]\nfrom typing import Any, ClassVar, Protocol\n\nclass P(Protocol):\n    def __call__(self, x: int, y: int) -> Any: ...\n\nclass B:\n    def __init__(self, x: int, y: int) -> None: ...\nclass C:\n    def __init__(self, x: int, y: str) -> None: ...\n\ndef test(arg: P) -> None: ...\ntest(B)  # OK\ntest(C)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: \"C\" has constructor incompatible with \"__call__\" of \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def __call__(x: int, y: int) -> Any \\\n         # N:     Got: \\\n         # N:         def C(x: int, y: str) -> C \\\n         # N: \"P.__call__\" has type \"def __call__(self, x: int, y: int) -> Any\"\n[builtins fixtures/type.pyi]\n\n[case testProtocolClassObjectCallableError]\nfrom typing import Protocol, Any, Callable\n\nclass P(Protocol):\n    def __call__(self, app: int) -> Callable[[str], None]:\n        ...\n\nclass C:\n    def __init__(self, app: str) -> None:\n        pass\n\n    def __call__(self, el: str) -> None:\n        return None\n\np: P = C  # E: Incompatible types in assignment (expression has type \"type[C]\", variable has type \"P\") \\\n          # N: Following member(s) of \"C\" have conflicts: \\\n          # N:     Expected: \\\n          # N:         def __call__(app: int) -> Callable[[str], None] \\\n          # N:     Got: \\\n          # N:         def C(app: str) -> C \\\n          # N: \"P.__call__\" has type \"def __call__(self, app: int) -> Callable[[str], None]\"\n\n[builtins fixtures/type.pyi]\n\n[case testProtocolTypeTypeAttribute]\nfrom typing import ClassVar, Protocol, Type\n\nclass P(Protocol):\n    foo: int\n\nclass A:\n    foo = 42\nclass B:\n    foo: ClassVar[int]\nclass C:\n    foo: ClassVar[str]\nclass D:\n    foo: int\n\ndef test(arg: P) -> None: ...\na: Type[A]\nb: Type[B]\nc: Type[C]\nd: Type[D]\ntest(a)  # OK\ntest(b)  # OK\ntest(c)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     foo: expected \"int\", got \"str\"\ntest(d)  # E: Argument 1 to \"test\" has incompatible type \"type[D]\"; expected \"P\" \\\n         # N: Only class variables allowed for class object access on protocols, foo is an instance variable of \"D\"\n\n[case testProtocolTypeTypeInstanceMethod]\nfrom typing import Any, Protocol, Type\n\nclass P(Protocol):\n    def foo(self, cls: Any) -> int: ...\n\nclass B:\n    def foo(self) -> int: ...\nclass C:\n    def foo(self) -> str: ...\n\ndef test(arg: P) -> None: ...\nb: Type[B]\nc: Type[C]\ntest(b)  # OK\ntest(c)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def foo(cls: Any) -> int \\\n         # N:     Got: \\\n         # N:         def foo(self: C) -> str\n\n[case testProtocolTypeTypeClassMethod]\nfrom typing import Protocol, Type\n\nclass P(Protocol):\n    def foo(self) -> int: ...\n\nclass B:\n    @classmethod\n    def foo(cls) -> int: ...\nclass C:\n    @classmethod\n    def foo(cls) -> str: ...\n\ndef test(arg: P) -> None: ...\nb: Type[B]\nc: Type[C]\ntest(b)  # OK\ntest(c)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def foo() -> int \\\n         # N:     Got: \\\n         # N:         def foo() -> str\n[builtins fixtures/classmethod.pyi]\n\n[case testProtocolTypeTypeSelfTypeInstanceMethod]\nfrom typing import Protocol, Type, TypeVar, Union\n\nT = TypeVar(\"T\")\nclass P(Protocol):\n    def foo(self, arg: T) -> T: ...\n\nclass B:\n    def foo(self: T) -> T: ...\nclass C:\n    def foo(self: T) -> Union[T, int]: ...\n\ndef test(arg: P) -> None: ...\nb: Type[B]\nc: Type[C]\ntest(b)  # OK\ntest(c)  # E: Argument 1 to \"test\" has incompatible type \"type[C]\"; expected \"P\" \\\n         # N: Following member(s) of \"C\" have conflicts: \\\n         # N:     Expected: \\\n         # N:         def [T] foo(arg: T) -> T \\\n         # N:     Got: \\\n         # N:         def [T] foo(self: T) -> T | int\n\n[case testProtocolClassObjectInference]\nfrom typing import Any, Protocol, TypeVar\n\nT = TypeVar(\"T\", contravariant=True)\nclass P(Protocol[T]):\n    def foo(self, obj: T) -> int: ...\n\nclass B:\n    def foo(self) -> int: ...\n\nS = TypeVar(\"S\")\ndef test(arg: P[S]) -> S: ...\nreveal_type(test(B))  # N: Revealed type is \"__main__.B\"\n\n[case testProtocolTypeTypeInference]\nfrom typing import Any, Protocol, TypeVar, Type\n\nT = TypeVar(\"T\", contravariant=True)\nclass P(Protocol[T]):\n    def foo(self, obj: T) -> int: ...\n\nclass B:\n    def foo(self) -> int: ...\n\nS = TypeVar(\"S\")\ndef test(arg: P[S]) -> S: ...\nb: Type[B]\nreveal_type(test(b))  # N: Revealed type is \"__main__.B\"\n\n[case testTypeAliasInProtocolBody]\nfrom typing import Protocol, List\n\nclass P(Protocol):\n    x = List[str]  # E: Type aliases are prohibited in protocol bodies \\\n                   # N: Use variable annotation syntax to define protocol members\n\nclass C:\n    x: int\ndef foo(x: P) -> None: ...\nfoo(C())  # No extra error here\n[builtins fixtures/list.pyi]\n\n[case testTypeVarInProtocolBody]\nfrom typing import Protocol, TypeVar\n\nclass C(Protocol):\n    T = TypeVar('T')\n    def __call__(self, t: T) -> T: ...\n\ndef f_bad(t: int) -> int:\n    return t\n\nS = TypeVar(\"S\")\ndef f_good(t: S) -> S:\n    return t\n\ng: C = f_bad  # E: Incompatible types in assignment (expression has type \"Callable[[int], int]\", variable has type \"C\") \\\n              # N: \"C.__call__\" has type \"def [T] __call__(self, t: T) -> T\"\ng = f_good  # OK\n\n[case testModuleAsProtocolImplementation]\nimport default_config\nimport bad_config_1\nimport bad_config_2\nimport bad_config_3\nfrom typing import Protocol\n\nclass Options(Protocol):\n    timeout: int\n    one_flag: bool\n    other_flag: bool\n    def update(self) -> bool: ...\n\ndef setup(options: Options) -> None: ...\nsetup(default_config)  # OK\nsetup(bad_config_1)  # E: Argument 1 to \"setup\" has incompatible type Module; expected \"Options\" \\\n                     # N: \"ModuleType\" is missing following \"Options\" protocol member: \\\n                     # N:     timeout\nsetup(bad_config_2)  # E: Argument 1 to \"setup\" has incompatible type Module; expected \"Options\" \\\n                     # N: Following member(s) of Module \"bad_config_2\" have conflicts: \\\n                     # N:     one_flag: expected \"bool\", got \"int\"\nsetup(bad_config_3)  # E: Argument 1 to \"setup\" has incompatible type Module; expected \"Options\" \\\n                     # N: Following member(s) of Module \"bad_config_3\" have conflicts: \\\n                     # N:     Expected: \\\n                     # N:         def update() -> bool \\\n                     # N:     Got: \\\n                     # N:         def update(obj: Any) -> bool\n\n[file default_config.py]\ntimeout = 100\none_flag = True\nother_flag = False\ndef update() -> bool: ...\n\n[file bad_config_1.py]\none_flag = True\nother_flag = False\ndef update() -> bool: ...\n\n[file bad_config_2.py]\ntimeout = 100\none_flag = 42\nother_flag = False\ndef update() -> bool: ...\n\n[file bad_config_3.py]\ntimeout = 100\none_flag = True\nother_flag = False\ndef update(obj) -> bool: ...\n[builtins fixtures/module.pyi]\n\n[case testModuleAsProtocolImplementationInference]\nimport default_config\nfrom typing import Protocol, TypeVar\n\nT = TypeVar(\"T\", covariant=True)\nclass Options(Protocol[T]):\n    timeout: int\n    one_flag: bool\n    other_flag: bool\n    def update(self) -> T: ...\n\ndef setup(options: Options[T]) -> T: ...\nreveal_type(setup(default_config))  # N: Revealed type is \"builtins.str\"\n\n[file default_config.py]\ntimeout = 100\none_flag = True\nother_flag = False\ndef update() -> str: ...\n[builtins fixtures/module.pyi]\n\n[case testModuleAsProtocolImplementationClassObject]\nimport runner\nimport bad_runner\nfrom typing import Callable, Protocol\n\nclass Runner(Protocol):\n    @property\n    def Run(self) -> Callable[[int], Result]: ...\n\nclass Result(Protocol):\n    value: int\n\ndef run(x: Runner) -> None: ...\nrun(runner)  # OK\nrun(bad_runner)  # E: Argument 1 to \"run\" has incompatible type Module; expected \"Runner\" \\\n                 # N: Following member(s) of Module \"bad_runner\" have conflicts: \\\n                 # N:     Expected: \\\n                 # N:         def (int, /) -> Result \\\n                 # N:     Got: \\\n                 # N:         def Run(arg: str) -> Run\n\n[file runner.py]\nclass Run:\n    value: int\n    def __init__(self, arg: int) -> None: ...\n\n[file bad_runner.py]\nclass Run:\n    value: int\n    def __init__(self, arg: str) -> None: ...\n[builtins fixtures/module.pyi]\n\n[case testModuleAsProtocolImplementationTypeAlias]\nimport runner\nimport bad_runner\nfrom typing import Callable, Protocol\n\nclass Runner(Protocol):\n    @property\n    def run(self) -> Callable[[int], Result]: ...\n\nclass Result(Protocol):\n    value: int\n\ndef run(x: Runner) -> None: ...\nrun(runner)  # OK\nrun(bad_runner)  # E: Argument 1 to \"run\" has incompatible type Module; expected \"Runner\" \\\n                 # N: Following member(s) of Module \"bad_runner\" have conflicts: \\\n                 # N:     Expected: \\\n                 # N:         def (int, /) -> Result \\\n                 # N:     Got: \\\n                 # N:         def Run(arg: str) -> Run\n\n[file runner.py]\nclass Run:\n    value: int\n    def __init__(self, arg: int) -> None: ...\nrun = Run\n\n[file bad_runner.py]\nclass Run:\n    value: int\n    def __init__(self, arg: str) -> None: ...\nrun = Run\n[builtins fixtures/module.pyi]\n\n[case testModuleAsProtocolImplementationClassVar]\nfrom typing import ClassVar, Protocol\nimport mod\n\nclass My(Protocol):\n    x: ClassVar[int]\n\ndef test(mod: My) -> None: ...\ntest(mod=mod)  # E: Argument \"mod\" to \"test\" has incompatible type Module; expected \"My\" \\\n               # N: Protocol member My.x expected class variable, got instance variable\n[file mod.py]\nx: int\n[builtins fixtures/module.pyi]\n\n[case testModuleAsProtocolImplementationFinal]\nfrom typing import Protocol\nimport some_module\n\nclass My(Protocol):\n   a: int\n\ndef func(arg: My) -> None: ...\nfunc(some_module)  # E: Argument 1 to \"func\" has incompatible type Module; expected \"My\" \\\n                   # N: Protocol member My.a expected settable variable, got read-only attribute\n\n[file some_module.py]\nfrom typing import Final\n\na: Final = 1\n[builtins fixtures/module.pyi]\n\n\n[case testModuleAsProtocolRedefinitionTopLevel]\nfrom typing import Protocol\n\nclass P(Protocol):\n    def f(self) -> str: ...\n\ncond: bool\nt: P\nif cond:\n    import mod1 as t\nelse:\n    import mod2 as t\n\nimport badmod as t  # E: Incompatible import of \"t\" (imported name has type Module, local name has type \"P\")\n\n[file mod1.py]\ndef f() -> str: ...\n\n[file mod2.py]\ndef f() -> str: ...\n\n[file badmod.py]\ndef nothing() -> int: ...\n[builtins fixtures/module.pyi]\n\n[case testModuleAsProtocolRedefinitionImportFrom]\nfrom typing import Protocol\n\nclass P(Protocol):\n    def f(self) -> str: ...\n\ncond: bool\nt: P\nif cond:\n    from package import mod1 as t\nelse:\n    from package import mod2 as t\n\nfrom package import badmod as t  # E: Incompatible import of \"t\" (imported name has type Module, local name has type \"P\")\n\npackage: int = 10\n\nimport package.mod1 as t\nimport package.mod1  # E: Incompatible import of \"package\" (imported name has type Module, local name has type \"int\")\n\n[file package/mod1.py]\ndef f() -> str: ...\n\n[file package/mod2.py]\ndef f() -> str: ...\n\n[file package/badmod.py]\ndef nothing() -> int: ...\n[builtins fixtures/module.pyi]\n\n[case testProtocolSelfTypeNewSyntax]\nfrom typing import Protocol, Self\n\nclass P(Protocol):\n    @property\n    def next(self) -> Self: ...\n\nclass C:\n    next: C\nclass S:\n    next: Self\n\nx: P = C()\ny: P = S()\n\nz: P\nreveal_type(S().next)  # N: Revealed type is \"__main__.S\"\nreveal_type(z.next)  # N: Revealed type is \"__main__.P\"\n[builtins fixtures/property.pyi]\n\n[case testProtocolSelfTypeNewSyntaxSubProtocol]\nfrom typing import Protocol, Self\n\nclass P(Protocol):\n    @property\n    def next(self) -> Self: ...\nclass PS(P, Protocol):\n    @property\n    def other(self) -> Self: ...\n\nclass C:\n    next: C\n    other: C\nclass S:\n    next: Self\n    other: Self\n\nx: PS = C()\ny: PS = S()\n[builtins fixtures/property.pyi]\n\n[case testProtocolClassVarSelfType]\nfrom typing import ClassVar, Self, Protocol\n\nclass P(Protocol):\n    DEFAULT: ClassVar[Self]\nclass C:\n    DEFAULT: ClassVar[C]\n\nx: P = C()\n\n[case testInferenceViaTypeTypeMetaclass]\nfrom typing import Iterator, Iterable, TypeVar, Type\n\nM = TypeVar(\"M\")\n\nclass Meta(type):\n    def __iter__(self: Type[M]) -> Iterator[M]: ...\nclass Foo(metaclass=Meta): ...\n\nT = TypeVar(\"T\")\ndef test(x: Iterable[T]) -> T: ...\n\nreveal_type(test(Foo))  # N: Revealed type is \"__main__.Foo\"\nt_foo: Type[Foo]\nreveal_type(test(t_foo))  # N: Revealed type is \"__main__.Foo\"\n\nTF = TypeVar(\"TF\", bound=Foo)\ndef outer(cls: Type[TF]) -> TF:\n    reveal_type(test(cls))  # N: Revealed type is \"TF`-1\"\n    return cls()\n\n[case testProtocolImportNotMember]\nimport m\nimport lib\n\nclass Bad:\n    x: int\nclass Good:\n    x: lib.C\n\nx: m.P = Bad()  # E: Incompatible types in assignment (expression has type \"Bad\", variable has type \"P\") \\\n                # N: Following member(s) of \"Bad\" have conflicts: \\\n                # N:     x: expected \"C\", got \"int\"\nx = Good()\n\n[file m.py]\nfrom typing import Protocol\n\nclass P(Protocol):\n    import lib\n    x: lib.C\n\n[file lib.py]\nclass C: ...\n\n[case testAllowDefaultConstructorInProtocols]\nfrom typing import Protocol\n\nclass P(Protocol):\n    x: int\n    def __init__(self, x: int) -> None:\n        self.x = x\n\nclass C(P): ...\nC(0)  # OK\n\n[case testTypeVarValueConstraintAgainstGenericProtocol]\nfrom typing import TypeVar, Generic, Protocol, overload\n\nT_contra = TypeVar(\"T_contra\", contravariant=True)\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\nclass SupportsWrite(Protocol[T_contra]):\n    def write(self, s: T_contra, /) -> None: ...\n\nclass Buffer: ...\n\nclass IO(Generic[AnyStr]):\n    @overload\n    def write(self: IO[bytes], s: Buffer, /) -> None: ...\n    @overload\n    def write(self, s: AnyStr, /) -> None: ...\n    def write(self, s): ...\n\ndef foo(fdst: SupportsWrite[AnyStr]) -> None: ...\n\nx: IO[str]\nfoo(x)\n\n[case testTypeVarValueConstraintAgainstGenericProtocol2]\nfrom typing import Generic, Protocol, TypeVar, overload\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\nclass SupportsRead(Generic[T_co]):\n    def read(self) -> T_co: ...\n\nclass SupportsWrite(Protocol[T_contra]):\n    def write(self, s: T_contra) -> object: ...\n\ndef copyfileobj(fsrc: SupportsRead[AnyStr], fdst: SupportsWrite[AnyStr]) -> None: ...\n\nclass WriteToMe(Generic[AnyStr]):\n    @overload\n    def write(self: WriteToMe[str], s: str) -> int: ...\n    @overload\n    def write(self: WriteToMe[bytes], s: bytes) -> int: ...\n    def write(self, s): ...\n\nclass WriteToMeOrReadFromMe(WriteToMe[AnyStr], SupportsRead[AnyStr]): ...\n\ncopyfileobj(WriteToMeOrReadFromMe[bytes](), WriteToMe[bytes]())\n\n[case testOverloadedMethodWithExplicitSelfTypes]\nfrom typing import Generic, overload, Protocol, TypeVar, Union\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\nclass SupportsRead(Protocol[T_co]):\n    def read(self) -> T_co: ...\n\nclass SupportsWrite(Protocol[T_contra]):\n    def write(self, s: T_contra) -> int: ...\n\nclass Input(Generic[AnyStr]):\n    def read(self) -> AnyStr: ...\n\nclass Output(Generic[AnyStr]):\n    @overload\n    def write(self: Output[str], s: str) -> int: ...\n    @overload\n    def write(self: Output[bytes], s: bytes) -> int: ...\n    def write(self, s: Union[str, bytes]) -> int: ...\n\ndef f(src: SupportsRead[AnyStr], dst: SupportsWrite[AnyStr]) -> None: ...\n\ndef g1(a: Input[bytes], b: Output[bytes]) -> None:\n    f(a, b)\n\ndef g2(a: Input[bytes], b: Output[bytes]) -> None:\n    f(a, b)\n\ndef g3(a: Input[str], b: Output[bytes]) -> None:\n    f(a, b)  # E: Cannot infer value of type parameter \"AnyStr\" of \"f\"\n\ndef g4(a: Input[bytes], b: Output[str]) -> None:\n    f(a, b)  # E: Cannot infer value of type parameter \"AnyStr\" of \"f\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testOverloadProtocolSubtyping]\nfrom typing import Protocol, Self, overload\n\nclass NumpyFloat:\n    __add__: \"FloatOP\"\n\nclass FloatOP(Protocol):\n    @overload\n    def __call__(self, other: float) -> NumpyFloat: ...\n    @overload\n    def __call__(self, other: NumpyFloat) -> NumpyFloat: ...\n\nclass SupportsAdd(Protocol):\n    @overload\n    def __add__(self, other: float) -> Self: ...\n    @overload\n    def __add__(self, other: NumpyFloat) -> Self: ...\n\nx: SupportsAdd = NumpyFloat()\n[builtins fixtures/tuple.pyi]\n\n[case testSetterPropertyProtocolSubtypingBoth]\nfrom typing import Protocol\n\nclass B1: ...\nclass C1(B1): ...\nclass B2: ...\nclass C2(B2): ...\n\nclass P1(Protocol):\n    @property\n    def foo(self) -> B1: ...\n    @foo.setter\n    def foo(self, x: C2) -> None: ...\n\nclass P2(Protocol):\n    @property\n    def foo(self) -> B1: ...\n    @foo.setter\n    def foo(self, x: B2) -> None: ...\n\nclass A1:\n    @property\n    def foo(self) -> B1: ...\n    @foo.setter\n    def foo(self, x: C2) -> None: ...\n\nclass A2:\n    @property\n    def foo(self) -> C1: ...\n    @foo.setter\n    def foo(self, x: C2) -> None: ...\n\nclass A3:\n    @property\n    def foo(self) -> C1: ...\n    @foo.setter\n    def foo(self, x: str) -> None: ...\n\nclass A4:\n    @property\n    def foo(self) -> str: ...\n    @foo.setter\n    def foo(self, x: str) -> None: ...\n\ndef f1(x: P1) -> None: ...\ndef f2(x: P2) -> None: ...\n\na1: A1\na2: A2\na3: A3\na4: A4\n\nf1(a1)\nf1(a2)\nf1(a3)  # E: Argument 1 to \"f1\" has incompatible type \"A3\"; expected \"P1\" \\\n        # N: Following member(s) of \"A3\" have conflicts: \\\n        # N:     foo: expected setter type \"C2\", got \"str\"\nf1(a4)  # E: Argument 1 to \"f1\" has incompatible type \"A4\"; expected \"P1\" \\\n        # N: Following member(s) of \"A4\" have conflicts: \\\n        # N:     foo: expected \"B1\", got \"str\" \\\n        # N:     foo: expected setter type \"C2\", got \"str\"\n\nf2(a1)  # E: Argument 1 to \"f2\" has incompatible type \"A1\"; expected \"P2\" \\\n        # N: Following member(s) of \"A1\" have conflicts: \\\n        # N:     foo: expected setter type \"B2\", got \"C2\" \\\n        # N:     Setter types should behave contravariantly\nf2(a2)  # E: Argument 1 to \"f2\" has incompatible type \"A2\"; expected \"P2\" \\\n        # N: Following member(s) of \"A2\" have conflicts: \\\n        # N:     foo: expected setter type \"B2\", got \"C2\" \\\n        # N:     Setter types should behave contravariantly\nf2(a3)  # E: Argument 1 to \"f2\" has incompatible type \"A3\"; expected \"P2\" \\\n        # N: Following member(s) of \"A3\" have conflicts: \\\n        # N:     foo: expected setter type \"B2\", got \"str\"\nf2(a4)  # E: Argument 1 to \"f2\" has incompatible type \"A4\"; expected \"P2\" \\\n        # N: Following member(s) of \"A4\" have conflicts: \\\n        # N:     foo: expected \"B1\", got \"str\" \\\n        # N:     foo: expected setter type \"B2\", got \"str\"\n[builtins fixtures/property.pyi]\n\n[case testSetterPropertyProtocolSubtypingVarSuper]\nfrom typing import Protocol\n\nclass B1: ...\nclass C1(B1): ...\n\nclass P1(Protocol):\n    foo: B1\n\nclass P2(Protocol):\n    foo: C1\n\nclass A1:\n    @property\n    def foo(self) -> B1: ...\n    @foo.setter\n    def foo(self, x: C1) -> None: ...\n\nclass A2:\n    @property\n    def foo(self) -> C1: ...\n    @foo.setter\n    def foo(self, x: B1) -> None: ...\n\nclass A3:\n    @property\n    def foo(self) -> C1: ...\n    @foo.setter\n    def foo(self, x: str) -> None: ...\n\nclass A4:\n    @property\n    def foo(self) -> str: ...\n    @foo.setter\n    def foo(self, x: str) -> None: ...\n\ndef f1(x: P1) -> None: ...\ndef f2(x: P2) -> None: ...\n\na1: A1\na2: A2\na3: A3\na4: A4\n\nf1(a1)  # E: Argument 1 to \"f1\" has incompatible type \"A1\"; expected \"P1\" \\\n        # N: Following member(s) of \"A1\" have conflicts: \\\n        # N:     foo: expected setter type \"B1\", got \"C1\" \\\n        # N:     Setter types should behave contravariantly\nf1(a2)\nf1(a3)  # E: Argument 1 to \"f1\" has incompatible type \"A3\"; expected \"P1\" \\\n        # N: Following member(s) of \"A3\" have conflicts: \\\n        # N:     foo: expected setter type \"B1\", got \"str\"\nf1(a4)  # E: Argument 1 to \"f1\" has incompatible type \"A4\"; expected \"P1\" \\\n        # N: Following member(s) of \"A4\" have conflicts: \\\n        # N:     foo: expected \"B1\", got \"str\"\n\nf2(a1)  # E: Argument 1 to \"f2\" has incompatible type \"A1\"; expected \"P2\" \\\n        # N: Following member(s) of \"A1\" have conflicts: \\\n        # N:     foo: expected \"C1\", got \"B1\"\nf2(a2)\nf2(a3)  # E: Argument 1 to \"f2\" has incompatible type \"A3\"; expected \"P2\" \\\n        # N: Following member(s) of \"A3\" have conflicts: \\\n        # N:     foo: expected setter type \"C1\", got \"str\"\nf2(a4)  # E: Argument 1 to \"f2\" has incompatible type \"A4\"; expected \"P2\" \\\n        # N: Following member(s) of \"A4\" have conflicts: \\\n        # N:     foo: expected \"C1\", got \"str\"\n[builtins fixtures/property.pyi]\n\n[case testSetterPropertyProtocolSubtypingVarSub]\nfrom typing import Protocol\n\nclass B1: ...\nclass C1(B1): ...\nclass B2: ...\nclass C2(B2): ...\n\nclass P1(Protocol):\n    @property\n    def foo(self) -> B1: ...\n    @foo.setter\n    def foo(self, x: C2) -> None: ...\n\nclass P2(Protocol):\n    @property\n    def foo(self) -> B1: ...\n    @foo.setter\n    def foo(self, x: C1) -> None: ...\n\nclass A1:\n    foo: B1\n\nclass A2:\n    foo: B2\n\nclass A3:\n    foo: C2\n\nclass A4:\n    foo: str\n\ndef f1(x: P1) -> None: ...\ndef f2(x: P2) -> None: ...\n\na1: A1\na2: A2\na3: A3\na4: A4\n\nf1(a1)  # E: Argument 1 to \"f1\" has incompatible type \"A1\"; expected \"P1\" \\\n        # N: Following member(s) of \"A1\" have conflicts: \\\n        # N:     foo: expected setter type \"C2\", got \"B1\"\nf1(a2)  # E: Argument 1 to \"f1\" has incompatible type \"A2\"; expected \"P1\" \\\n        # N: Following member(s) of \"A2\" have conflicts: \\\n        # N:     foo: expected \"B1\", got \"B2\"\nf1(a3)  # E: Argument 1 to \"f1\" has incompatible type \"A3\"; expected \"P1\" \\\n        # N: Following member(s) of \"A3\" have conflicts: \\\n        # N:     foo: expected \"B1\", got \"C2\"\nf1(a4)  # E: Argument 1 to \"f1\" has incompatible type \"A4\"; expected \"P1\" \\\n        # N: Following member(s) of \"A4\" have conflicts: \\\n        # N:     foo: expected \"B1\", got \"str\" \\\n        # N:     foo: expected setter type \"C2\", got \"str\"\n\nf2(a1)\nf2(a2)  # E: Argument 1 to \"f2\" has incompatible type \"A2\"; expected \"P2\" \\\n        # N: Following member(s) of \"A2\" have conflicts: \\\n        # N:     foo: expected \"B1\", got \"B2\" \\\n        # N:     foo: expected setter type \"C1\", got \"B2\"\nf2(a3)  # E: Argument 1 to \"f2\" has incompatible type \"A3\"; expected \"P2\" \\\n        # N: Following member(s) of \"A3\" have conflicts: \\\n        # N:     foo: expected \"B1\", got \"C2\" \\\n        # N:     foo: expected setter type \"C1\", got \"C2\"\nf2(a4)  # E: Argument 1 to \"f2\" has incompatible type \"A4\"; expected \"P2\" \\\n        # N: Following member(s) of \"A4\" have conflicts: \\\n        # N:     foo: expected \"B1\", got \"str\" \\\n        # N:     foo: expected setter type \"C1\", got \"str\"\n[builtins fixtures/property.pyi]\n\n\n[case testExplicitProtocolJoinPreference]\nfrom typing import Protocol, TypeVar\n\nT = TypeVar(\"T\")\n\nclass Proto1(Protocol):\n    def foo(self) -> int: ...\nclass Proto2(Proto1):\n    def bar(self) -> str: ...\nclass Proto3(Proto2):\n    def baz(self) -> str: ...\n\nclass Base: ...\n\nclass A(Base, Proto3): ...\nclass B(Base, Proto3): ...\n\ndef join(a: T, b: T) -> T: ...\n\ndef main(a: A, b: B) -> None:\n    reveal_type(join(a, b))  # N: Revealed type is \"__main__.Proto3\"\n    reveal_type(join(b, a))  # N: Revealed type is \"__main__.Proto3\"\n\n[case testProtocolImplementationWithDescriptors]\nfrom typing import Any, Protocol\n\nclass Descr:\n    def __get__(self, inst: Any, owner: Any) -> int: ...\n\nclass DescrBad:\n    def __get__(self, inst: Any, owner: Any) -> str: ...\n\nclass Proto(Protocol):\n    x: int\n\nclass C:\n    x = Descr()\n\nclass CBad:\n    x = DescrBad()\n\na: Proto = C()\nb: Proto = CBad()  # E: Incompatible types in assignment (expression has type \"CBad\", variable has type \"Proto\") \\\n                   # N: Following member(s) of \"CBad\" have conflicts: \\\n                   # N:     x: expected \"int\", got \"str\"\n\n[case testProtocolCheckDefersNode]\nfrom typing import Any, Callable, Protocol\n\nclass Proto(Protocol):\n    def f(self) -> int:\n        ...\n\ndef defer(f: Callable[[Any], int]) -> Callable[[Any], str]:\n    ...\n\ndef bad() -> Proto:\n    return Impl()  # E: Incompatible return value type (got \"Impl\", expected \"Proto\") \\\n                   # N: Following member(s) of \"Impl\" have conflicts: \\\n                   # N:     Expected: \\\n                   # N:         def f(self) -> int \\\n                   # N:     Got: \\\n                   # N:         def f() -> str \\\n\nclass Impl:\n    @defer\n    def f(self) -> int: ...\n\n[case testInferCallableProtoWithAnySubclass]\nfrom typing import Any, Generic, Protocol, TypeVar\n\nT = TypeVar(\"T\", covariant=True)\n\nUnknown: Any\nclass Mock(Unknown):\n    def __init__(self, **kwargs: Any) -> None: ...\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n\nclass Factory(Protocol[T]):\n    def __call__(self, **kwargs: Any) -> T: ...\n\n\nclass Test(Generic[T]):\n    def __init__(self, f: Factory[T]) -> None:\n        ...\n\nt = Test(Mock())\nreveal_type(t)  # N: Revealed type is \"__main__.Test[Any]\"\n[builtins fixtures/dict.pyi]\n\n[case testProtocolClassObjectDescriptor]\nfrom typing import Any, Protocol, overload\n\nclass Desc:\n    @overload\n    def __get__(self, instance: None, owner: Any) -> Desc: ...\n    @overload\n    def __get__(self, instance: object, owner: Any) -> int: ...\n    def __get__(self, instance, owner):\n        pass\n\nclass HasDesc(Protocol):\n    attr: Desc\n\nclass HasInt(Protocol):\n    attr: int\n\nclass C:\n    attr = Desc()\n\nx: HasInt = C()\ny: HasDesc = C\nz: HasInt = C  # E: Incompatible types in assignment (expression has type \"type[C]\", variable has type \"HasInt\") \\\n               # N: Following member(s) of \"C\" have conflicts: \\\n               # N:     attr: expected \"int\", got \"Desc\"\n\n[case testProtocolErrorReportingNoDuplicates]\nfrom typing import Callable, Protocol, TypeVar\n\nclass P(Protocol):\n    def meth(self) -> int: ...\n\nclass C:\n    def meth(self) -> str: ...\n\ndef foo() -> None:\n    c: P = C()  # E: Incompatible types in assignment (expression has type \"C\", variable has type \"P\") \\\n                # N: Following member(s) of \"C\" have conflicts: \\\n                # N:     Expected: \\\n                # N:         def meth(self) -> int \\\n                # N:     Got: \\\n                # N:         def meth(self) -> str\n    x = defer()\n\nT = TypeVar(\"T\")\ndef deco(fn: Callable[[], T]) -> Callable[[], list[T]]: ...\n\n@deco\ndef defer() -> int: ...\n[builtins fixtures/list.pyi]\n\n[case testProtocolClassValDescriptor]\nfrom typing import Any, Protocol, overload, ClassVar, Type\n\nclass Desc:\n    @overload\n    def __get__(self, instance: None, owner: object) -> Desc: ...\n    @overload\n    def __get__(self, instance: object, owner: object) -> int: ...\n    def __get__(self, instance, owner):\n        pass\n\nclass P(Protocol):\n    x: ClassVar[Desc]\n\nclass C:\n    x = Desc()\n\nt: P = C()\nreveal_type(t.x)  # N: Revealed type is \"builtins.int\"\ntt: Type[P] = C\nreveal_type(tt.x)  # N: Revealed type is \"__main__.Desc\"\n\nbad: P = C  # E: Incompatible types in assignment (expression has type \"type[C]\", variable has type \"P\") \\\n            # N: Following member(s) of \"C\" have conflicts: \\\n            # N:     x: expected \"int\", got \"Desc\"\n\n[case testProtocolClassValCallable]\nfrom typing import Any, Protocol, overload, ClassVar, Type, Callable\n\nclass P(Protocol):\n    foo: Callable[[object], int]\n    bar: ClassVar[Callable[[object], int]]\n\nclass C:\n    foo: Callable[[object], int]\n    bar: ClassVar[Callable[[object], int]]\n\nt: P = C()\nreveal_type(t.foo)  # N: Revealed type is \"def (builtins.object) -> builtins.int\"\nreveal_type(t.bar)  # N: Revealed type is \"def () -> builtins.int\"\ntt: Type[P] = C\nreveal_type(tt.foo)  # N: Revealed type is \"def (builtins.object) -> builtins.int\"\nreveal_type(tt.bar)  # N: Revealed type is \"def (builtins.object) -> builtins.int\"\n\n[case testProtocolDecoratedSelfBound]\nfrom abc import abstractmethod\nfrom typing import Protocol, Self\n\nclass Proto(Protocol):\n    @abstractmethod\n    def foo(self, x: Self) -> None: ...\n\nclass Impl:\n    def foo(self, x: Self) -> None:\n        pass\n\nx: Proto = Impl()\n\n[case testIndirectDependencyOnProtocolIncremental]\nimport a\n[file a.py]\nfrom b import P\n\nclass CNested:\n    def f(self) -> int: ...\nclass C:\n    def f(self) -> CNested: ...\n\nx: P = C()\n\n[file b.py]\nfrom typing import Protocol\nfrom c import PNested\n\nclass P(Protocol):\n    def f(self) -> PNested: ...\n\n[file c.py]\nfrom typing import Protocol\n\nclass PNested(Protocol):\n    def f(self) -> str: ...\n\n[file c.py.2]\nfrom typing import Protocol\n\nclass PNested(Protocol):\n    def f(self) -> int: ...\n\n[file c.py.3]\nfrom typing import Protocol\n\nclass PNested(Protocol):\n    def f(self) -> str: ...\n[out]\ntmp/a.py:8: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\ntmp/a.py:8: note: Following member(s) of \"C\" have conflicts:\ntmp/a.py:8: note:     Expected:\ntmp/a.py:8: note:         def f(self) -> PNested\ntmp/a.py:8: note:     Got:\ntmp/a.py:8: note:         def f(self) -> CNested\n[out2]\n[out3]\ntmp/a.py:8: error: Incompatible types in assignment (expression has type \"C\", variable has type \"P\")\ntmp/a.py:8: note: Following member(s) of \"C\" have conflicts:\ntmp/a.py:8: note:     Expected:\ntmp/a.py:8: note:         def f(self) -> PNested\ntmp/a.py:8: note:     Got:\ntmp/a.py:8: note:         def f(self) -> CNested\n\n[case testProtocolCannotBeDisjointBase]\nfrom typing import Protocol\nfrom typing_extensions import disjoint_base\n\n@disjoint_base  # E: @disjoint_base cannot be used with protocol class\nclass A(Protocol):\n    pass\n\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-python310.test",
    "content": "-- Capture Pattern --\n\n[case testMatchCapturePatternType]\nclass A: ...\nm: A\n\nmatch m:\n    case a:\n        reveal_type(a)  # N: Revealed type is \"__main__.A\"\n\n-- Literal Pattern --\n\n[case testMatchLiteralPatternNarrows]\n# flags: --warn-unreachable\nm: object\n\nmatch m:\n    case 1:\n        reveal_type(m)  # N: Revealed type is \"Literal[1]\"\n    case 2:\n        reveal_type(m)  # N: Revealed type is \"Literal[2]\"\n    case other:\n        reveal_type(other)  # N: Revealed type is \"builtins.object\"\n\n[case testMatchLiteralPatternNarrows2]\n# flags: --warn-unreachable\nfrom typing import Any\n\nm: Any\n\nmatch m:\n    case 1:\n        reveal_type(m)  # N: Revealed type is \"Any\"\n    case 2:\n        reveal_type(m)  # N: Revealed type is \"Any\"\n    case other:\n        reveal_type(other)  # N: Revealed type is \"Any\"\n\n[case testMatchLiteralPatternBoolIntAlreadyNarrower]\n# flags: --strict-equality --warn-unreachable\n\ndef foo(m: bool, x: int):\n    match m:\n        case 1:\n            reveal_type(m)  # N: Revealed type is \"Literal[1]\"\n\n    match m:\n        case x:\n            reveal_type(m)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/primitives.pyi]\n\n[case testMatchLiteralPatternUnreachable]\n# flags: --strict-equality --warn-unreachable\nm: int\n\nmatch m:\n    case \"str\":\n        reveal_type(m)  # E: Statement is unreachable\n[builtins fixtures/primitives.pyi]\n\n-- Value Pattern --\n\n[case testMatchValuePatternNarrows]\n# flags: --strict-equality --warn-unreachable\nimport b\nm: object\n\nmatch m:\n    case b.b:\n        reveal_type(m)  # N: Revealed type is \"builtins.int\"\n[file b.py]\nb: int\n\n[case testMatchValuePatternAlreadyNarrower]\n# flags: --strict-equality --warn-unreachable\nimport b\nm: bool\n\nmatch m:\n    case b.b:\n        reveal_type(m)  # N: Revealed type is \"builtins.bool\"\n[file b.py]\nb: int\n\n[case testMatchValuePatternIntersect]\n# flags: --strict-equality --warn-unreachable\nimport b\n\nclass A: ...\nm: A\n\nmatch m:\n    case b.b:\n        reveal_type(m)  # E: Statement is unreachable\n[file b.py]\nclass B: ...\nb: B\n\n[case testMatchValuePatternUnreachable]\n# flags: --strict-equality --warn-unreachable\nimport b\n\nm: int\n\nmatch m:\n    case b.b:\n        reveal_type(m)  # E: Statement is unreachable\n[file b.py]\nb: str\n[builtins fixtures/primitives.pyi]\n\n-- Sequence Pattern --\n\n[case testMatchSequencePatternCaptures]\nfrom typing import List\nm: List[int]\n\nmatch m:\n    case [a]:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testMatchSequencePatternCapturesStarred]\nfrom typing import Sequence\nm: Sequence[int]\n\nmatch m:\n    case [a, *b]:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n        reveal_type(b)  # N: Revealed type is \"builtins.list[builtins.int]\"\n[builtins fixtures/list.pyi]\n\n[case testMatchSequencePatternNarrowsInner]\nfrom typing import Sequence\nm: Sequence[object]\n\nmatch m:\n    case [1, True]:\n        reveal_type(m)  # N: Revealed type is \"typing.Sequence[builtins.int]\"\n\n[case testMatchSequencePatternNarrowsOuter]\nfrom typing import Sequence\nm: object\n\nmatch m:\n    case [1, True]:\n        reveal_type(m)  # N: Revealed type is \"typing.Sequence[builtins.int]\"\n\n[case testMatchSequencePatternAlreadyNarrowerInner]\nfrom typing import Sequence\nm: Sequence[bool]\n\nmatch m:\n    case [1, True]:\n        reveal_type(m)  # N: Revealed type is \"typing.Sequence[builtins.bool]\"\n\n[case testMatchSequencePatternAlreadyNarrowerOuter]\nfrom typing import Sequence\nm: Sequence[object]\n\nmatch m:\n    case [1, True]:\n        reveal_type(m)  # N: Revealed type is \"typing.Sequence[builtins.int]\"\n\n[case testMatchSequencePatternAlreadyNarrowerBoth]\nfrom typing import Sequence\nm: Sequence[bool]\n\nmatch m:\n    case [1, True]:\n        reveal_type(m)  # N: Revealed type is \"typing.Sequence[builtins.bool]\"\n\n[case testMatchNestedSequencePatternNarrowsInner]\nfrom typing import Sequence\nm: Sequence[Sequence[object]]\n\nmatch m:\n    case [[1], [True]]:\n        reveal_type(m)  # N: Revealed type is \"typing.Sequence[typing.Sequence[builtins.int]]\"\n\n[case testMatchNestedSequencePatternNarrowsOuter]\nfrom typing import Sequence\nm: object\n\nmatch m:\n    case [[1], [True]]:\n        reveal_type(m)  # N: Revealed type is \"typing.Sequence[typing.Sequence[builtins.int]]\"\n\n[case testMatchSequencePatternDoesntNarrowInvariant]\nfrom typing import List\nm: List[object]\n\nmatch m:\n    case [1]:\n        reveal_type(m)  # N: Revealed type is \"builtins.list[builtins.object]\"\n[builtins fixtures/list.pyi]\n\n[case testMatchSequencePatternMatches]\nimport array, collections\nfrom typing import Sequence, Iterable\n\nm1: object\nm2: Sequence[int]\nm3: array.array[int]\nm4: collections.deque[int]\nm5: list[int]\nm6: memoryview\nm7: range\nm8: tuple[int]\n\nm9: str\nm10: bytes\nm11: bytearray\n\nmatch m1:\n    case [a]:\n        reveal_type(a)  # N: Revealed type is \"builtins.object\"\n\nmatch m2:\n    case [b]:\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n\nmatch m3:\n    case [c]:\n        reveal_type(c)  # N: Revealed type is \"builtins.int\"\n\nmatch m4:\n    case [d]:\n        reveal_type(d)  # N: Revealed type is \"builtins.int\"\n\nmatch m5:\n    case [e]:\n        reveal_type(e)  # N: Revealed type is \"builtins.int\"\n\nmatch m6:\n    case [f]:\n        reveal_type(f)  # N: Revealed type is \"builtins.int\"\n\nmatch m7:\n    case [g]:\n        reveal_type(g)  # N: Revealed type is \"builtins.int\"\n\nmatch m8:\n    case [h]:\n        reveal_type(h)  # N: Revealed type is \"builtins.int\"\n\nmatch m9:\n    case [i]:\n        reveal_type(i)\n\nmatch m10:\n    case [j]:\n        reveal_type(j)\n\nmatch m11:\n    case [k]:\n        reveal_type(k)\n[builtins fixtures/primitives.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testMatchSequencePatternCapturesTuple]\nfrom typing import Tuple\nm: Tuple[int, str, bool]\n\nmatch m:\n    case [a, b, c]:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n        reveal_type(b)  # N: Revealed type is \"builtins.str\"\n        reveal_type(c)  # N: Revealed type is \"builtins.bool\"\n        reveal_type(m)  # N: Revealed type is \"tuple[builtins.int, builtins.str, builtins.bool]\"\n[builtins fixtures/list.pyi]\n\n[case testMatchSequencePatternTupleTooLong]\nfrom typing import Tuple\nm: Tuple[int, str]\n\nmatch m:\n    case [a, b, c]:\n        reveal_type(a)\n        reveal_type(b)\n        reveal_type(c)\n[builtins fixtures/list.pyi]\n\n[case testMatchSequencePatternTupleTooShort]\nfrom typing import Tuple\nm: Tuple[int, str, bool]\n\nmatch m:\n    case [a, b]:\n        reveal_type(a)\n        reveal_type(b)\n[builtins fixtures/list.pyi]\n\n[case testMatchSequencePatternTupleNarrows]\nfrom typing import Tuple\nm: Tuple[object, object]\n\nmatch m:\n    case [1, \"str\"]:\n        reveal_type(m)  # N: Revealed type is \"tuple[Literal[1], Literal['str']]\"\n[builtins fixtures/list.pyi]\n\n[case testMatchSequencePatternTupleStarred]\nfrom typing import Tuple\nm: Tuple[int, str, bool]\n\nmatch m:\n    case [a, *b, c]:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n        reveal_type(b)  # N: Revealed type is \"builtins.list[builtins.str]\"\n        reveal_type(c)  # N: Revealed type is \"builtins.bool\"\n        reveal_type(m)  # N: Revealed type is \"tuple[builtins.int, builtins.str, builtins.bool]\"\n[builtins fixtures/list.pyi]\n\n[case testMatchSequencePatternTupleStarredUnion]\nfrom typing import Tuple\nm: Tuple[int, str, float, bool]\n\nmatch m:\n    case [a, *b, c]:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n        reveal_type(b)  # N: Revealed type is \"builtins.list[builtins.str | builtins.float]\"\n        reveal_type(c)  # N: Revealed type is \"builtins.bool\"\n        reveal_type(m)  # N: Revealed type is \"tuple[builtins.int, builtins.str, builtins.float, builtins.bool]\"\n[builtins fixtures/list.pyi]\n\n[case testMatchSequencePatternTupleStarredTooShort]\nfrom typing import Tuple\nm: Tuple[int]\nreveal_type(m)  # N: Revealed type is \"tuple[builtins.int]\"\n\nmatch m:\n    case [a, *b, c]:\n        reveal_type(a)\n        reveal_type(b)\n        reveal_type(c)\n[builtins fixtures/list.pyi]\n\n[case testMatchNonMatchingSequencePattern]\nfrom typing import List\n\nx: List[int]\nmatch x:\n    case [str()]:\n        pass\n\n[case testMatchSequencePatternWithTypeObject]\n# flags: --strict-equality --warn-unreachable\nclass Example:\n    __match_args__ = (\"value\",)\n    def __init__(self, value: str) -> None:\n        self.value = value\n\nSubClass: type[Example]\n\nmatch [SubClass(\"a\"), SubClass(\"b\")]:\n    case [SubClass(value), *rest]:\n        reveal_type(value)  # N: Revealed type is \"builtins.str\"\n        reveal_type(rest)  # N: Revealed type is \"builtins.list[__main__.Example]\"\n\n[builtins fixtures/tuple.pyi]\n\n# Narrowing union-based values via a literal pattern on an indexed/attribute subject\n# -------------------------------------------------------------------------------\n# Literal patterns against a union of types can be used to narrow the subject\n# itself, not just the expression being matched. Previously, the patterns below\n# failed to narrow the `d` variable, leading to errors for missing members; we\n# now propagate the type information up to the parent.\n\n[case testMatchNarrowingUnionTypedDictViaIndex]\nfrom typing import Literal, TypedDict\n\nclass A(TypedDict):\n    tag: Literal[\"a\"]\n    name: str\n\nclass B(TypedDict):\n    tag: Literal[\"b\"]\n    num: int\n\nd: A | B\nmatch d[\"tag\"]:\n    case \"a\":\n        reveal_type(d)  # N: Revealed type is \"TypedDict('__main__.A', {'tag': Literal['a'], 'name': builtins.str})\"\n        reveal_type(d[\"name\"])  # N: Revealed type is \"builtins.str\"\n    case \"b\":\n        reveal_type(d)  # N: Revealed type is \"TypedDict('__main__.B', {'tag': Literal['b'], 'num': builtins.int})\"\n        reveal_type(d[\"num\"])  # N: Revealed type is \"builtins.int\"\n[typing fixtures/typing-typeddict.pyi]\n\n[case testMatchNarrowingUnionClassViaAttribute]\nfrom typing import Literal\n\nclass A:\n    tag: Literal[\"a\"]\n    name: str\n\nclass B:\n    tag: Literal[\"b\"]\n    num: int\n\nd: A | B\nmatch d.tag:\n    case \"a\":\n        reveal_type(d)  # N: Revealed type is \"__main__.A\"\n        reveal_type(d.name)  # N: Revealed type is \"builtins.str\"\n    case \"b\":\n        reveal_type(d)  # N: Revealed type is \"__main__.B\"\n        reveal_type(d.num)  # N: Revealed type is \"builtins.int\"\n\n[case testMatchSequenceUnion]\nfrom typing import List, Union\nm: Union[List[List[str]], str]\n\nmatch m:\n    case [list(['str'])]:\n        reveal_type(m)  # N: Revealed type is \"builtins.list[builtins.list[builtins.str]]\"\n[builtins fixtures/list.pyi]\n\n[case testMatchSequencePatternNarrowSubjectItems]\nm: int\nn: str\no: bool\n\nmatch m, n, o:\n    case [3, \"foo\", True]:\n        reveal_type(m)  # N: Revealed type is \"Literal[3]\"\n        reveal_type(n)  # N: Revealed type is \"Literal['foo']\"\n        reveal_type(o)  # N: Revealed type is \"Literal[True]\"\n    case [a, b, c]:\n        reveal_type(m)  # N: Revealed type is \"builtins.int\"\n        reveal_type(n)  # N: Revealed type is \"builtins.str\"\n        reveal_type(o)  # N: Revealed type is \"builtins.bool\"\n\nreveal_type(m)  # N: Revealed type is \"builtins.int\"\nreveal_type(n)  # N: Revealed type is \"builtins.str\"\nreveal_type(o)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequencePatternNarrowSubjectItemsRecursive]\nm: int\nn: int\no: int\np: int\nq: int\nr: int\n\nmatch m, (n, o), (p, (q, r)):\n    case [0, [1, 2], [3, [4, 5]]]:\n        reveal_type(m)  # N: Revealed type is \"Literal[0]\"\n        reveal_type(n)  # N: Revealed type is \"Literal[1]\"\n        reveal_type(o)  # N: Revealed type is \"Literal[2]\"\n        reveal_type(p)  # N: Revealed type is \"Literal[3]\"\n        reveal_type(q)  # N: Revealed type is \"Literal[4]\"\n        reveal_type(r)  # N: Revealed type is \"Literal[5]\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequencePatternSequencesLengthMismatchNoNarrowing]\nm: int\nn: str\no: bool\n\nmatch m, n, o:\n    case [3, \"foo\"]:\n        pass\n    case [3, \"foo\", True, True]:\n        pass\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequencePatternSequencesLengthMismatchNoNarrowingRecursive]\nm: int\nn: int\no: int\n\nmatch m, (n, o):\n    case [0]:\n        pass\n    case [0, 1, [2]]:\n        pass\n    case [0, [1]]:\n        pass\n    case [0, [1, 2, 3]]:\n        pass\n[builtins fixtures/tuple.pyi]\n\n-- Mapping Pattern --\n\n[case testMatchMappingPatternCaptures]\nfrom typing import Dict\nimport b\nm: Dict[str, int]\n\nmatch m:\n    case {\"key\": v}:\n        reveal_type(v)  # N: Revealed type is \"builtins.int\"\n    case {b.b: v2}:\n        reveal_type(v2)  # N: Revealed type is \"builtins.int\"\n[file b.py]\nb: str\n[builtins fixtures/dict.pyi]\n\n[case testMatchMappingPatternCapturesWrongKeyType]\n# flags: --strict-equality --warn-unreachable\n# This is not actually unreachable, as a subclass of dict could accept keys with different types\nfrom typing import Dict\nimport b\nm: Dict[str, int]\n\nmatch m:\n    case {1: v}:\n        reveal_type(v)  # N: Revealed type is \"builtins.int\"\n    case {b.b: v2}:\n        reveal_type(v2)  # N: Revealed type is \"builtins.int\"\n[file b.py]\nb: int\n[builtins fixtures/dict.pyi]\n\n[case testMatchMappingPatternCapturesTypedDict]\nfrom typing import TypedDict\n\nclass A(TypedDict):\n    a: str\n    b: int\n\nm: A\n\nmatch m:\n    case {\"a\": v}:\n        reveal_type(v)  # N: Revealed type is \"builtins.str\"\n    case {\"b\": v2}:\n        reveal_type(v2)  # N: Revealed type is \"builtins.int\"\n    case {\"a\": v3, \"b\": v4}:\n        reveal_type(v3)  # N: Revealed type is \"builtins.str\"\n        reveal_type(v4)  # N: Revealed type is \"builtins.int\"\n    case {\"o\": v5}:\n        reveal_type(v5)  # N: Revealed type is \"builtins.object\"\n[typing fixtures/typing-typeddict.pyi]\n\n[case testMatchMappingPatternCapturesTypedDictWithLiteral]\nfrom typing import TypedDict\nimport b\n\nclass A(TypedDict):\n    a: str\n    b: int\n\nm: A\n\nmatch m:\n    case {b.a: v}:\n        reveal_type(v)  # N: Revealed type is \"builtins.str\"\n    case {b.b: v2}:\n        reveal_type(v2)  # N: Revealed type is \"builtins.int\"\n    case {b.a: v3, b.b: v4}:\n        reveal_type(v3)  # N: Revealed type is \"builtins.str\"\n        reveal_type(v4)  # N: Revealed type is \"builtins.int\"\n    case {b.o: v5}:\n        reveal_type(v5)  # N: Revealed type is \"builtins.object\"\n[file b.py]\nfrom typing import Final, Literal\na: Final = \"a\"\nb: Literal[\"b\"] = \"b\"\no: Final[str] = \"o\"\n[typing fixtures/typing-typeddict.pyi]\n\n[case testMatchMappingPatternCapturesTypedDictWithNonLiteral]\nfrom typing import TypedDict\nimport b\n\nclass A(TypedDict):\n    a: str\n    b: int\n\nm: A\n\nmatch m:\n    case {b.a: v}:\n        reveal_type(v)  # N: Revealed type is \"builtins.object\"\n[file b.py]\nfrom typing import Final, Literal\na: str\n[typing fixtures/typing-typeddict.pyi]\n\n[case testMatchMappingPatternCapturesTypedDictUnreachable]\n# flags: --strict-equality --warn-unreachable\n# TypedDict keys are always str, so this is actually unreachable\nfrom typing import TypedDict\nimport b\n\nclass A(TypedDict):\n    a: str\n    b: int\n\nm: A\n\nmatch m:\n    case {1: v}:\n        reveal_type(v)  # E: Statement is unreachable\n    case {b.b: v2}:\n        reveal_type(v2)  # E: Statement is unreachable\n[file b.py]\nb: int\n[typing fixtures/typing-typeddict.pyi]\n\n[case testMatchMappingPatternCaptureRest]\nm: object\n\nmatch m:\n    case {'k': 1, **r}:\n        reveal_type(r)  # N: Revealed type is \"builtins.dict[builtins.object, builtins.object]\"\n[builtins fixtures/dict.pyi]\n\n[case testMatchMappingPatternCaptureRestFromMapping]\nfrom typing import Mapping\n\nm: Mapping[str, int]\n\nmatch m:\n    case {'k': 1, **r}:\n        reveal_type(r)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.int]\"\n[builtins fixtures/dict.pyi]\n\n[case testMatchMappingPatternNarrowing]\nfrom typing import Mapping, Sequence\n\ndef f1(x: dict[str, str] | list[str] | str) -> None:\n    match x:\n        case {}:\n            reveal_type(x)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.str]\"\n        case [*_]:\n            reveal_type(x)  # N: Revealed type is \"builtins.list[builtins.str]\"\n        case _:\n            reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\ndef f1_rest(x: dict[str, str] | list[str] | str) -> None:\n    match x:\n        case {**rest}:\n            reveal_type(x)  # N: Revealed type is \"builtins.dict[builtins.str, builtins.str]\"\n        case [*_]:\n            reveal_type(x)  # N: Revealed type is \"builtins.list[builtins.str]\"\n        case _:\n            reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\ndef f2(x: Mapping[str, str] | Sequence[str] | str) -> None:\n    match x:\n        case {}:\n            reveal_type(x)  # N: Revealed type is \"typing.Mapping[builtins.str, builtins.str]\"\n        case [*_]:\n            reveal_type(x)  # N: Revealed type is \"typing.Sequence[builtins.str]\"\n        case _:\n            reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\ndef f2_rest(x: Mapping[str, str] | Sequence[str] | str) -> None:\n    match x:\n        case {**rest}:\n            reveal_type(x)  # N: Revealed type is \"typing.Mapping[builtins.str, builtins.str]\"\n        case [*_]:\n            reveal_type(x)  # N: Revealed type is \"typing.Sequence[builtins.str]\"\n        case _:\n            reveal_type(x)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n\n[case testMatchMappingPatternNarrowingAny]\nfrom typing import Any\n\ndef f1(x: Any) -> None:\n    match x:\n        case {}:\n            reveal_type(x)  # N: Revealed type is \"Any\"\n\ndef f2(x: Any) -> None:\n    match x:\n        case {\"x\": \"y\"}:\n            reveal_type(x)  # N: Revealed type is \"Any\"\n[builtins fixtures/dict.pyi]\n\n-- Class Pattern --\n\n[case testMatchClassPatternCapturePositional]\nfrom typing import Final\n\nclass A:\n    __match_args__: Final = (\"a\", \"b\")\n    a: str\n    b: int\n\nm: A\n\nmatch m:\n    case A(i, j):\n        reveal_type(i)  # N: Revealed type is \"builtins.str\"\n        reveal_type(j)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternMemberClassCapturePositional]\nimport b\n\nm: b.A\n\nmatch m:\n    case b.A(i, j):\n        reveal_type(i)  # N: Revealed type is \"builtins.str\"\n        reveal_type(j)  # N: Revealed type is \"builtins.int\"\n[file b.py]\nfrom typing import Final\n\nclass A:\n    __match_args__: Final = (\"a\", \"b\")\n    a: str\n    b: int\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternCaptureKeyword]\nclass A:\n    a: str\n    b: int\n\nm: A\n\nmatch m:\n    case A(a=i, b=j):\n        reveal_type(i)  # N: Revealed type is \"builtins.str\"\n        reveal_type(j)  # N: Revealed type is \"builtins.int\"\n\n[case testMatchClassPatternCaptureSelf]\nm: object\n\nmatch m:\n    case bool(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.bool\"\n    case bytearray(b):\n        reveal_type(b)  # N: Revealed type is \"builtins.bytearray\"\n    case bytes(c):\n        reveal_type(c)  # N: Revealed type is \"builtins.bytes\"\n    case dict(d):\n        reveal_type(d)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n    case float(e):\n        reveal_type(e)  # N: Revealed type is \"builtins.float\"\n    case frozenset(f):\n        reveal_type(f)  # N: Revealed type is \"builtins.frozenset[Any]\"\n    case int(g):\n        reveal_type(g)  # N: Revealed type is \"builtins.int\"\n    case list(h):\n        reveal_type(h)  # N: Revealed type is \"builtins.list[Any]\"\n    case set(i):\n        reveal_type(i)  # N: Revealed type is \"builtins.set[Any]\"\n    case str(j):\n        reveal_type(j)  # N: Revealed type is \"builtins.str\"\n    case tuple(k):\n        reveal_type(k)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n[builtins fixtures/primitives.pyi]\n\n[case testMatchClassPatternNarrowSelfCapture]\nm: object\n\nmatch m:\n    case bool():\n        reveal_type(m)  # N: Revealed type is \"builtins.bool\"\n    case bytearray():\n        reveal_type(m)  # N: Revealed type is \"builtins.bytearray\"\n    case bytes():\n        reveal_type(m)  # N: Revealed type is \"builtins.bytes\"\n    case dict():\n        reveal_type(m)  # N: Revealed type is \"builtins.dict[Any, Any]\"\n    case float():\n        reveal_type(m)  # N: Revealed type is \"builtins.float\"\n    case frozenset():\n        reveal_type(m)  # N: Revealed type is \"builtins.frozenset[Any]\"\n    case int():\n        reveal_type(m)  # N: Revealed type is \"builtins.int\"\n    case list():\n        reveal_type(m)  # N: Revealed type is \"builtins.list[Any]\"\n    case set():\n        reveal_type(m)  # N: Revealed type is \"builtins.set[Any]\"\n    case str():\n        reveal_type(m)  # N: Revealed type is \"builtins.str\"\n    case tuple():\n        reveal_type(m)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n[builtins fixtures/primitives.pyi]\n\n[case testMatchClassPatternCaptureSelfSubtype]\nclass A(str):\n    pass\n\nclass B(str):\n    __match_args__ = (\"b\",)\n    b: int\n\ndef f1(x: A):\n    match x:\n        case A(a):\n            reveal_type(a)  # N: Revealed type is \"__main__.A\"\n\ndef f2(x: B):\n    match x:\n        case B(b):\n            reveal_type(b)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchInvalidClassPattern]\nm: object\n\nmatch m:\n    case xyz(y):  # E: Name \"xyz\" is not defined\n        reveal_type(m)  # N: Revealed type is \"Any\"\n        reveal_type(y)  # N: Revealed type is \"Any\"\n\nmatch m:\n    case xyz(z=x):  # E: Name \"xyz\" is not defined\n        reveal_type(x)  # N: Revealed type is \"Any\"\n    case (xyz1() as n) | (xyz2(attr=n)):  # E: Name \"xyz1\" is not defined \\\n                                          # E: Name \"xyz2\" is not defined\n        reveal_type(n)  # N: Revealed type is \"Any\"\n\n[case testMatchClassPatternCaptureDataclass]\nfrom dataclasses import dataclass\n\n@dataclass\nclass A:\n    a: str\n    b: int\n\nm: A\n\nmatch m:\n    case A(i, j):\n        reveal_type(i)  # N: Revealed type is \"builtins.str\"\n        reveal_type(j)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testMatchClassPatternCaptureDataclassNoMatchArgs]\nfrom dataclasses import dataclass\n\n@dataclass(match_args=False)\nclass A:\n    a: str\n    b: int\n\nm: A\n\nmatch m:\n    case A(i, j):  # E: Class \"__main__.A\" doesn't define \"__match_args__\"\n        pass\n[builtins fixtures/dataclasses.pyi]\n\n[case testMatchClassPatternCaptureDataclassPartialMatchArgs]\nfrom dataclasses import dataclass, field\n\n@dataclass\nclass A:\n    a: str\n    b: int = field(init=False)\n\nm: A\n\nmatch m:\n    case A(i, j):  # E: Too many positional patterns for class pattern\n        pass\n    case A(k):\n        reveal_type(k)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testMatchClassPatternCaptureNamedTupleInline]\nfrom collections import namedtuple\n\nA = namedtuple(\"A\", [\"a\", \"b\"])\n\nm: A\n\nmatch m:\n    case A(i, j):\n        reveal_type(i)  # N: Revealed type is \"Any\"\n        reveal_type(j)  # N: Revealed type is \"Any\"\n[builtins fixtures/list.pyi]\n\n[case testMatchClassPatternCaptureNamedTupleInlineTyped]\nfrom typing import NamedTuple\n\nA = NamedTuple(\"A\", [(\"a\", str), (\"b\", int)])\n\nm: A\n\nmatch m:\n    case A(i, j):\n        reveal_type(i)  # N: Revealed type is \"builtins.str\"\n        reveal_type(j)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testMatchClassPatternCaptureNamedTupleClass]\nfrom typing import NamedTuple\n\nclass A(NamedTuple):\n    a: str\n    b: int\n\nm: A\n\nmatch m:\n    case A(i, j):\n        reveal_type(i)  # N: Revealed type is \"builtins.str\"\n        reveal_type(j)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequencePatternCaptureNamedTuple]\nfrom typing import NamedTuple\n\nclass N(NamedTuple):\n    x: int\n    y: str\n\na = N(1, \"a\")\n\nmatch a:\n    case [x, y]:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n        reveal_type(y)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternCaptureGeneric]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    a: T\n\nm: object\n\nmatch m:\n    case A(a=i):\n        reveal_type(m)  # N: Revealed type is \"__main__.A[Any]\"\n        reveal_type(i)  # N: Revealed type is \"Any\"\n\n[case testMatchClassPatternCaptureVariadicGeneric]\nfrom typing import Generic, Tuple\nfrom typing_extensions import TypeVarTuple, Unpack\n\nTs = TypeVarTuple('Ts')\nclass A(Generic[Unpack[Ts]]):\n    a: Tuple[Unpack[Ts]]\n\nm: object\nmatch m:\n    case A(a=i):\n        reveal_type(m)  # N: Revealed type is \"__main__.A[Unpack[builtins.tuple[Any, ...]]]\"\n        reveal_type(i)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternCaptureGenericAlreadyKnown]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    a: T\n\nm: A[int]\n\nmatch m:\n    case A(a=i):\n        reveal_type(m)  # N: Revealed type is \"__main__.A[builtins.int]\"\n        reveal_type(i)  # N: Revealed type is \"builtins.int\"\n\n[case testMatchClassPatternCaptureFilledGenericTypeAlias]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    a: T\n\nB = A[int]\n\nm: object\n\nmatch m:\n    case B(a=i):  # E: Class pattern class must not be a type alias with type parameters\n        reveal_type(i)\n\n[case testMatchClassPatternCaptureGenericTypeAlias]\nfrom typing import Generic, TypeVar\n\nT = TypeVar('T')\n\nclass A(Generic[T]):\n    a: T\n\nB = A\n\nm: object\n\nmatch m:\n    case B(a=i):\n        pass\n\n[case testMatchClassPatternNarrows]\nfrom typing import Final\n\nclass A:\n    __match_args__: Final = (\"a\", \"b\")\n    a: str\n    b: int\n\nm: object\n\nmatch m:\n    case A():\n        reveal_type(m)  # N: Revealed type is \"__main__.A\"\n    case A(i, j):\n        reveal_type(m)  # N: Revealed type is \"__main__.A\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternNarrowsUnion]\nfrom typing import Final, Union\n\nclass A:\n    __match_args__: Final = (\"a\", \"b\")\n    a: str\n    b: int\n\nclass B:\n    __match_args__: Final = (\"a\", \"b\")\n    a: int\n    b: str\n\nm: Union[A, B]\n\nmatch m:\n    case A():\n        reveal_type(m)  # N: Revealed type is \"__main__.A\"\n\nmatch m:\n    case A(i, j):\n        reveal_type(m)  # N: Revealed type is \"__main__.A\"\n        reveal_type(i)  # N: Revealed type is \"builtins.str\"\n        reveal_type(j)  # N: Revealed type is \"builtins.int\"\n\nmatch m:\n    case B():\n        reveal_type(m)  # N: Revealed type is \"__main__.B\"\n\nmatch m:\n    case B(k, l):\n        reveal_type(m)  # N: Revealed type is \"__main__.B\"\n        reveal_type(k)  # N: Revealed type is \"builtins.int\"\n        reveal_type(l)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternAlreadyNarrower]\nfrom typing import Final\n\nclass A:\n    __match_args__: Final = (\"a\", \"b\")\n    a: str\n    b: int\nclass B(A): ...\n\nm: B\n\nmatch m:\n    case A():\n        reveal_type(m)  # N: Revealed type is \"__main__.B\"\n\nmatch m:\n    case A(i, j):\n        reveal_type(m)  # N: Revealed type is \"__main__.B\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternIntersection]\nfrom typing import Final\n\nclass A:\n    __match_args__: Final = (\"a\", \"b\")\n    a: str\n    b: int\nclass B: ...\n\nm: B\n\nmatch m:\n    case A():\n        reveal_type(m)  # N: Revealed type is \"__main__.<subclass of \"__main__.B\" and \"__main__.A\">\"\n    case A(i, j):\n        reveal_type(m)  # N: Revealed type is \"__main__.<subclass of \"__main__.B\" and \"__main__.A\">\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternNonexistentKeyword]\nfrom typing import Any\nclass A: ...\n\nm: object\nn: Any\n\nmatch m:\n    case A(a=j):  # E: Class \"__main__.A\" has no attribute \"a\"\n        reveal_type(m)  # N: Revealed type is \"__main__.A\"\n        reveal_type(j)  # N: Revealed type is \"Any\"\n\nmatch n:\n    # Matching against object should not emit an error for non-existing keys\n    case object(a=k):\n        reveal_type(n)  # N: Revealed type is \"builtins.object\"\n        reveal_type(n.a)  # N: Revealed type is \"Any\"\n        reveal_type(k)  # N: Revealed type is \"Any\"\n\n[case testMatchClassPatternDuplicateKeyword]\nclass A:\n    a: str\n\nm: object\n\nmatch m:\n    case A(a=i, a=j):  # E: Duplicate keyword pattern \"a\"\n        pass\n\n[case testMatchClassPatternDuplicateImplicitKeyword]\nfrom typing import Final\n\nclass A:\n    __match_args__: Final = (\"a\",)\n    a: str\n\nm: object\n\nmatch m:\n    case A(i, a=j):  # E: Keyword \"a\" already matches a positional pattern\n        pass\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternTooManyPositionals]\nfrom typing import Final\n\nclass A:\n    __match_args__: Final = (\"a\", \"b\")\n    a: str\n    b: int\n\nm: object\n\nmatch m:\n    case A(i, j, k):  # E: Too many positional patterns for class pattern\n        pass\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternIsNotType]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Any\n\ndef match_int(m: object, a: int):\n    match m:\n        case a(i, j):  # E: Expected type in class pattern; found \"builtins.int\"\n            reveal_type(i)  # E: Statement is unreachable\n            reveal_type(j)\n\ndef match_int_str(m: object, a: int | str):\n    match m:\n        case a(i, j):  # E: Expected type in class pattern; found \"builtins.int\" \\\n                       # E: Expected type in class pattern; found \"builtins.str\"\n            reveal_type(i)  # E: Statement is unreachable\n            reveal_type(j)\n\ndef match_int_any(m: object, a: int | Any):\n    match m:\n        case a(i, j):  # E: Expected type in class pattern; found \"builtins.int\"\n            reveal_type(i)  # N: Revealed type is \"Any\"\n            reveal_type(j)  # N: Revealed type is \"Any\"\n\n[case testMatchClassPatternAny]\nfrom typing import Any\n\nFoo: Any\nm: object\n\nmatch m:\n    case Foo():\n        pass\n\n[case testMatchClassPatternCallable]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Callable, Any\n\nclass FnImpl:\n    def __call__(self, x: object, /) -> int: ...\n\ndef test_any(x: Any) -> None:\n    match x:\n        case Callable() as fn:\n            reveal_type(fn)  # N: Revealed type is \"def (*Any, **Any) -> Any\"\n        case other:\n            reveal_type(other)  # N: Revealed type is \"Any\"\n\ndef test_object(x: object) -> None:\n    match x:\n        case Callable() as fn:\n            reveal_type(fn)  # N: Revealed type is \"def (*Any, **Any) -> Any\"\n        case other:\n            reveal_type(other)  # N: Revealed type is \"builtins.object\"\n\ndef test_impl(x: FnImpl) -> None:\n    match x:\n        case Callable() as fn:\n            reveal_type(fn)  # N: Revealed type is \"__main__.FnImpl\"\n        case other:\n            reveal_type(other)  # E: Statement is unreachable\n\ndef test_callable(x: Callable[[object], int]) -> None:\n    match x:\n        case Callable() as fn:\n            reveal_type(fn)  # N: Revealed type is \"def (builtins.object) -> builtins.int\"\n        case other:\n            reveal_type(other)  # E: Statement is unreachable\n\n[case testMatchClassPatternCallbackProtocol]\n# flags: --warn-unreachable\nfrom typing import Any, Callable\nfrom typing_extensions import Protocol, runtime_checkable\n\n@runtime_checkable\nclass FnProto(Protocol):\n    def __call__(self, x: int, /) -> object: ...\n\nclass FnImpl:\n    def __call__(self, x: object, /) -> int: ...\n\ndef test_any(x: Any) -> None:\n    match x:\n        case FnProto() as fn:\n            reveal_type(fn)  # N: Revealed type is \"__main__.FnProto\"\n        case other:\n            reveal_type(other)  # N: Revealed type is \"Any\"\n\ndef test_object(x: object) -> None:\n    match x:\n        case FnProto() as fn:\n            reveal_type(fn)  # N: Revealed type is \"__main__.FnProto\"\n        case other:\n            reveal_type(other)  # N: Revealed type is \"builtins.object\"\n\ndef test_impl(x: FnImpl) -> None:\n    match x:\n        case FnProto() as fn:\n            reveal_type(fn)  # N: Revealed type is \"__main__.FnImpl\"\n        case other:\n            reveal_type(other)  # E: Statement is unreachable\n\ndef test_callable(x: Callable[[object], int]) -> None:\n    match x:\n        case FnProto() as fn:\n            reveal_type(fn)  # N: Revealed type is \"def (builtins.object) -> builtins.int\"\n        case other:\n            reveal_type(other)  # E: Statement is unreachable\n\n[builtins fixtures/dict.pyi]\n\n[case testMatchClassPatternAnyCallableProtocol]\n# flags: --warn-unreachable\nfrom typing import Any, Callable\nfrom typing_extensions import Protocol, runtime_checkable\n\n@runtime_checkable\nclass AnyCallable(Protocol):\n    def __call__(self, *args: Any, **kwargs: Any) -> Any: ...\n\nclass FnImpl:\n    def __call__(self, x: object, /) -> int: ...\n\ndef test_object(x: object) -> None:\n    match x:\n        case AnyCallable() as fn:\n            reveal_type(fn)  # N: Revealed type is \"__main__.AnyCallable\"\n        case other:\n            reveal_type(other)  # N: Revealed type is \"builtins.object\"\n\ndef test_impl(x: FnImpl) -> None:\n    match x:\n        case AnyCallable() as fn:\n            reveal_type(fn)  # N: Revealed type is \"__main__.FnImpl\"\n        case other:\n            reveal_type(other)  # E: Statement is unreachable\n\ndef test_callable(x: Callable[[object], int]) -> None:\n    match x:\n        case AnyCallable() as fn:\n            reveal_type(fn)  # N: Revealed type is \"def (builtins.object) -> builtins.int\"\n        case other:\n            reveal_type(other)  # E: Statement is unreachable\n\n[builtins fixtures/dict.pyi]\n\n\n[case testMatchClassPatternProtocol]\nfrom typing import Any\nfrom typing_extensions import Protocol, runtime_checkable\n\n@runtime_checkable\nclass Proto(Protocol):\n    def foo(self, x: int, /) -> object: ...\n\nclass Impl:\n    def foo(self, x: object, /) -> int: ...\n\ndef test_object(x: object) -> None:\n    match x:\n        case Proto() as y:\n            reveal_type(y)  # N: Revealed type is \"__main__.Proto\"\n\ndef test_impl(x: Impl) -> None:\n    match x:\n        case Proto() as y:\n            reveal_type(y)  # N: Revealed type is \"__main__.Impl\"\n\n[builtins fixtures/dict.pyi]\n\n\n[case testMatchClassPatternNestedGenerics]\n# From cpython test_patma.py\nx = [[{0: 0}]]\nmatch x:\n    case list([({-0-0j: int(real=0+0j, imag=0-0j) | (1) as z},)]):\n        y = 0\n\nreveal_type(x)  # N: Revealed type is \"builtins.list[builtins.list[builtins.dict[builtins.int, builtins.int]]]\"\nreveal_type(y)  # N: Revealed type is \"builtins.int\"\nreveal_type(z)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/dict-full.pyi]\n\n[case testMatchClassPatternTypeObject]\n# flags: --strict-equality --warn-unreachable\nclass Example:\n    __match_args__ = (\"value\",)\n    def __init__(self, value: str) -> None:\n        self.value = value\n\ndef f1(subclass: type[Example]) -> None:\n    match subclass(\"a\"):\n        case Example(value):\n            reveal_type(value)  # N: Revealed type is \"builtins.str\"\n        case anything:\n            reveal_type(anything)  # E: Statement is unreachable\n\ndef f2(subclass: type[Example]) -> None:\n    match Example(\"a\"):\n        case subclass(value):\n            reveal_type(value)  # N: Revealed type is \"builtins.str\"\n        case anything:\n            reveal_type(anything)  # N: Revealed type is \"__main__.Example\"\n\ndef f3(subclass: type[Example]) -> None:\n    match subclass(\"a\"):\n        case subclass(value):\n            reveal_type(value)  # N: Revealed type is \"builtins.str\"\n        case anything:\n            reveal_type(anything)  # N: Revealed type is \"__main__.Example\"\n\nclass Example2:\n    __match_args__ = (\"value\",)\n    def __init__(self, value: str) -> None:\n        self.value = value\n\ndef f4(T: type[Example | Example2]) -> None:\n    match T(\"a\"):\n        case Example(value):\n            reveal_type(value)  # N: Revealed type is \"builtins.str\"\n        case anything:\n            reveal_type(anything)  # N: Revealed type is \"__main__.Example2\"\n\ndef f5(T: type[Example | Example2]) -> None:\n    match Example(\"a\"):\n        case T(value):\n            reveal_type(value)  # N: Revealed type is \"builtins.str\"\n        case anything:\n            reveal_type(anything)  # N: Revealed type is \"__main__.Example\"\n\ndef f6(T: type[Example | Example2]) -> None:\n    match T(\"a\"):\n        case T(value):\n            reveal_type(value)  # N: Revealed type is \"builtins.str\"\n        case anything:\n            reveal_type(anything)  # N: Revealed type is \"__main__.Example | __main__.Example2\"\n\ndef f7(m: object, t: type[object]) -> None:\n    match m:\n        case t():\n            reveal_type(m)  # N: Revealed type is \"builtins.object\"\n        case _:\n            reveal_type(m)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchClassPatternTypeObjectGeneric]\n# flags: --strict-equality --warn-unreachable\nfrom typing import TypeVar\nT = TypeVar(\"T\")\n\ndef print_test(m: object, typ: type[T]) -> T:\n    match m:\n        case typ():\n            reveal_type(m)  # N: Revealed type is \"T`-1\"\n            return m\n        case str():\n            reveal_type(m)  # N: Revealed type is \"builtins.str\"\n        case _:\n            reveal_type(m)  # N: Revealed type is \"builtins.object\"\n    raise\n\n[case testMatchClassPatternTupleAlias]\n# flags: --strict-equality --warn-unreachable\nfrom typing import Tuple\n\ntuple_alias = tuple\nTuple_alias = Tuple\n\ndef main(m: object):\n    match m:\n        case tuple():\n            reveal_type(m)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n        case _:\n            reveal_type(m)  # N: Revealed type is \"builtins.object\"\n\n    match m:\n        case tuple_alias():\n            reveal_type(m)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n        case _:\n            reveal_type(m)  # N: Revealed type is \"builtins.object\"\n\n    match m:\n        # With real typeshed you'll get an error like this instead:\n        # Expected type in class pattern; found \"typing._SpecialForm\"\n        case Tuple():  # E: Expected type in class pattern; found \"builtins.int\"\n            reveal_type(m)  # E: Statement is unreachable\n        case _:\n            reveal_type(m)  # N: Revealed type is \"builtins.object\"\n\n    match m:\n        # This is a false negative, it will raise at runtime\n        case Tuple_alias():\n            reveal_type(m)  # N: Revealed type is \"builtins.tuple[Any, ...]\"\n        case _:\n            reveal_type(m)  # N: Revealed type is \"builtins.object\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchNonFinalMatchArgs]\nclass A:\n    __match_args__ = (\"a\", \"b\")\n    a: str\n    b: int\n\nm: object\n\nmatch m:\n    case A(i, j):\n        reveal_type(i)  # N: Revealed type is \"builtins.str\"\n        reveal_type(j)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchAnyTupleMatchArgs]\nfrom typing import Tuple, Any\n\nclass A:\n    __match_args__: Tuple[Any, ...]\n    a: str\n    b: int\n\nm: object\n\nmatch m:\n    case A(i, j, k):\n        reveal_type(i)  # N: Revealed type is \"Any\"\n        reveal_type(j)  # N: Revealed type is \"Any\"\n        reveal_type(k)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchNonLiteralMatchArgs]\nfrom typing import Final\n\nb: str = \"b\"\nclass A:\n    __match_args__: Final = (\"a\", b)  # N: __match_args__ must be a tuple containing string literals for checking of match statements to work\n    a: str\n    b: int\n\nm: object\n\nmatch m:\n    case A(i, j, k):  # E: Too many positional patterns for class pattern\n        pass\n    case A(i, j):\n        reveal_type(i)  # N: Revealed type is \"builtins.str\"\n        reveal_type(j)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchExternalMatchArgs]\nfrom typing import Final, Literal\n\nargs: Final = (\"a\", \"b\")\nclass A:\n    __match_args__: Final = args\n    a: str\n    b: int\n\narg: Final = \"a\"\narg2: Literal[\"b\"] = \"b\"\nclass B:\n    __match_args__: Final = (arg, arg2)\n    a: str\n    b: int\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-medium.pyi]\n\n-- As Pattern --\n\n[case testMatchAsPattern]\nm: int\n\nmatch m:\n    case x as l:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n        reveal_type(l)  # N: Revealed type is \"builtins.int\"\n\n[case testMatchAsPatternNarrows]\nm: object\n\nmatch m:\n    case int() as l:\n        reveal_type(l)  # N: Revealed type is \"builtins.int\"\n\n[case testMatchAsPatternCapturesOr]\nm: object\n\nmatch m:\n    case 1 | 2 as n:\n        reveal_type(n)  # N: Revealed type is \"Literal[1] | Literal[2]\"\n\n[case testMatchAsPatternAlreadyNarrower]\nm: bool\n\nmatch m:\n    case int() as l:\n        reveal_type(l)  # N: Revealed type is \"builtins.bool\"\n\n-- Or Pattern --\n\n[case testMatchOrPatternNarrows]\nm: object\n\nmatch m:\n    case 1 | 2:\n        reveal_type(m)  # N: Revealed type is \"Literal[1] | Literal[2]\"\n\n[case testMatchOrPatternNarrowsStr]\nm: object\n\nmatch m:\n    case \"foo\" | \"bar\":\n        reveal_type(m)  # N: Revealed type is \"Literal['foo'] | Literal['bar']\"\n\n[case testMatchOrPatternNarrowsUnion]\nm: object\n\nmatch m:\n    case 1 | \"foo\":\n        reveal_type(m)  # N: Revealed type is \"Literal[1] | Literal['foo']\"\n\n[case testMatchOrPatternCapturesMissing]\nfrom typing import List\nm: List[int]\n\nmatch m:\n    case [x, y] | list(x):  # E: Alternative patterns bind different names\n        reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.list[builtins.int]\"\n        reveal_type(y)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testMatchOrPatternCapturesJoin]\nm: object\n\nmatch m:\n    case list(x) | dict(x):\n        reveal_type(x)  # N: Revealed type is \"builtins.list[Any] | builtins.dict[Any, Any]\"\n[builtins fixtures/dict.pyi]\n\n-- Interactions --\n\n[case testMatchCapturePatternMultipleCases]\nm: object\n\nmatch m:\n    case int(x):\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n    case str(x):\n        reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\nreveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n\n[case testMatchCapturePatternMultipleCaptures]\nfrom typing import Iterable\n\nm: Iterable[int]\n\nmatch m:\n    case [x, x]:  # E: Multiple assignments to name \"x\" in pattern\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n[case testMatchCapturePatternPreexistingSame]\na: int\nm: int\n\nmatch m:\n    case a:\n        reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n[case testMatchCapturePatternPreexistingNarrows]\na: int\nm: bool\n\nmatch m:\n    case a:\n        reveal_type(a)  # N: Revealed type is \"builtins.bool\"\n\nreveal_type(a)  # N: Revealed type is \"builtins.bool\"\na = 3\nreveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n[case testMatchCapturePatternPreexistingIncompatible]\na: str\nm: int\n\nmatch m:\n    case a:  # E: Incompatible types in capture pattern (pattern captures type \"int\", variable has type \"str\")\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n\nreveal_type(a)  # N: Revealed type is \"builtins.str\"\n\n[case testMatchCapturePatternPreexistingIncompatibleLater]\na: str\nm: object\n\nmatch m:\n    case str(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    case int(a):  # E: Incompatible types in capture pattern (pattern captures type \"int\", variable has type \"str\")\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n\nreveal_type(a)  # N: Revealed type is \"builtins.str\"\n\n[case testMatchCapturePatternFromFunctionReturningUnion]\ndef func1(arg: bool) -> str | int: ...\ndef func2(arg: bool) -> bytes | int: ...\n\ndef main() -> None:\n    match func1(True):\n        case str(a):\n            match func2(True):\n                case c:\n                    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n                    reveal_type(c)  # N: Revealed type is \"builtins.bytes | builtins.int\"\n            reveal_type(a)  # N: Revealed type is \"builtins.str\"\n        case a:\n            reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n[case testMatchCapturePatternFromAsyncFunctionReturningUnion]\nasync def func1(arg: bool) -> str | int: ...\nasync def func2(arg: bool) -> bytes | int: ...\n\nasync def main() -> None:\n    match await func1(True):\n        case str(a):\n            match await func2(True):\n                case c:\n                    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n                    reveal_type(c)  # N: Revealed type is \"builtins.bytes | builtins.int\"\n            reveal_type(a)  # N: Revealed type is \"builtins.str\"\n        case a:\n            reveal_type(a)  # N: Revealed type is \"builtins.int\"\n\n-- Guards --\n\n[case testMatchSimplePatternGuard]\nm: str\n\ndef guard() -> bool: ...\n\nmatch m:\n    case a if guard():\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n\n[case testMatchAlwaysTruePatternGuard]\nm: str\n\nmatch m:\n    case a if True:\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n\n[case testMatchAlwaysFalsePatternGuard]\nm: str\n\nmatch m:\n    case a if False:\n        reveal_type(a)\n\n[case testMatchRedefiningPatternGuard]\nm: str\n\nmatch m:\n    case a if a := 1:  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        reveal_type(a)  # N: Revealed type is \"Literal[1]?\"\n\n[case testMatchAssigningPatternGuard]\nm: str\n\nmatch m:\n    case a if a := \"test\":\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n\n[case testMatchNarrowingPatternGuard]\nm: object\n\nmatch m:\n    case a if isinstance(a, str):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testMatchIncompatiblePatternGuard]\nclass A: ...\nclass B: ...\n\nm: A\n\nmatch m:\n    case a if isinstance(a, B):\n        reveal_type(a)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\n[builtins fixtures/isinstancelist.pyi]\n\n[case testMatchUnreachablePatternGuard]\n# flags: --strict-equality --warn-unreachable\nm: str\n\nmatch m:\n    case a if isinstance(a, int):  # E: Subclass of \"str\" and \"int\" cannot exist: would have incompatible method signatures\n        reveal_type(a)  # E: Statement is unreachable\n[builtins fixtures/isinstancelist.pyi]\n\n[case testMatchSubjectAssignExprWithGuard]\nfrom typing import Optional\ndef func() -> Optional[str]: ...\n\nmatch m := func():\n    case _ if not m:\n        reveal_type(m)  # N: Revealed type is \"Literal[''] | None\"\n    case _:\n        reveal_type(m)  # N: Revealed type is \"builtins.str\"\n\n-- Exhaustiveness --\n\n[case testMatchUnionNegativeNarrowing]\nfrom typing import Union\n\nm: Union[str, int]\n\nmatch m:\n    case str(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n        reveal_type(m)  # N: Revealed type is \"builtins.str\"\n    case b:\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n        reveal_type(m)  # N: Revealed type is \"builtins.int\"\n\n[case testMatchOrPatternNegativeNarrowing]\nfrom typing import Union\n\nm: Union[str, bytes, int]\n\nmatch m:\n    case str(a) | bytes(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str | builtins.bytes\"\n        reveal_type(m)  # N: Revealed type is \"builtins.str | builtins.bytes\"\n    case b:\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n\n[case testMatchExhaustiveReturn]\ndef foo(value) -> int:\n  match value:\n    case \"bar\":\n      return 1\n    case _:\n      return 2\n\n[case testMatchNonExhaustiveReturn]\ndef foo(value) -> int:  # E: Missing return statement\n  match value:\n    case \"bar\":\n      return 1\n    case 2:\n      return 2\n\n[case testMatchMoreExhaustiveReturnCases]\ndef g(value: int | None) -> int:\n    match value:\n        case int():\n            return 0\n        case None:\n            return 1\n\ndef b(value: bool) -> int:\n    match value:\n        case True:\n            return 2\n        case False:\n            return 3\n\n[case testMatchMiscNonExhaustiveReturn]\nclass C:\n    a: int | str\n\ndef f1(value: int | str | None) -> int:  # E: Missing return statement\n    match value:\n        case int():\n            return 0\n        case None:\n            return 1\n\ndef f2(c: C) -> int:  # E: Missing return statement\n    match c:\n        case C(a=int()):\n            return 0\n        case C(a=str()):\n            return 1\n\ndef f3(x: list[str]) -> int:  # E: Missing return statement\n    match x:\n        case [a]:\n            return 0\n        case [a, b]:\n            return 1\n\ndef f4(x: dict[str, int]) -> int:  # E: Missing return statement\n    match x:\n        case {'x': a}:\n            return 0\n\ndef f5(x: bool) -> int:  # E: Missing return statement\n    match x:\n        case True:\n            return 0\n[builtins fixtures/dict.pyi]\n\n[case testMatchNonExhaustiveError]\nfrom typing import NoReturn\ndef assert_never(x: NoReturn) -> None: ...\n\ndef f(value: int) -> int:  # E: Missing return statement\n    match value:\n        case 1:\n            return 0\n        case 2:\n            return 1\n        case o:\n            assert_never(o)  # E: Argument 1 to \"assert_never\" has incompatible type \"int\"; expected \"Never\"\n\n[case testMatchExhaustiveNoError]\nfrom typing import NoReturn, Union, Literal\ndef assert_never(x: NoReturn) -> None: ...\n\ndef f(value: Literal[1] | Literal[2]) -> int:\n    match value:\n        case 1:\n            return 0\n        case 2:\n            return 1\n        case o:\n            assert_never(o)\n[typing fixtures/typing-medium.pyi]\n\n[case testMatchSequencePatternNegativeNarrowing]\nfrom typing import Literal, Union, Sequence, Tuple\n\nm1: Sequence[int | str]\n\nmatch m1:\n    case [int()]:\n        reveal_type(m1)  # N: Revealed type is \"typing.Sequence[builtins.int]\"\n    case r:\n        reveal_type(m1)  # N: Revealed type is \"typing.Sequence[builtins.int | builtins.str]\"\n\nm2: Tuple[int | str]\n\nmatch m2:\n    case (int(),):\n        reveal_type(m2)  # N: Revealed type is \"tuple[builtins.int]\"\n    case r2:\n        reveal_type(m2)  # N: Revealed type is \"tuple[builtins.str]\"\n\nm3: Tuple[Union[int, str]]\n\nmatch m3:\n    case (1,):\n        reveal_type(m3)  # N: Revealed type is \"tuple[Literal[1]]\"\n    case r2:\n        reveal_type(m3)  # N: Revealed type is \"tuple[builtins.int | builtins.str]\"\n\nm4: Tuple[Literal[1], int]\n\nmatch m4:\n    case (1, 5):\n        reveal_type(m4)  # N: Revealed type is \"tuple[Literal[1], Literal[5]]\"\n    case (1, 6):\n        reveal_type(m4)  # N: Revealed type is \"tuple[Literal[1], Literal[6]]\"\n    case _:\n        reveal_type(m4)  # N: Revealed type is \"tuple[Literal[1], builtins.int]\"\n\nm5: Tuple[Literal[1, 2], Literal[\"a\", \"b\"]]\n\nmatch m5:\n    case (1, str()):\n        reveal_type(m5)  # N: Revealed type is \"tuple[Literal[1], Literal['a'] | Literal['b']]\"\n    case _:\n        reveal_type(m5)  # N: Revealed type is \"tuple[Literal[2], Literal['a'] | Literal['b']]\"\n\nm6: Tuple[Literal[1, 2], Literal[\"a\", \"b\"]]\n\nmatch m6:\n    case (1, \"a\"):\n        reveal_type(m6)  # N: Revealed type is \"tuple[Literal[1], Literal['a']]\"\n    case _:\n        reveal_type(m6)  # N: Revealed type is \"tuple[Literal[1] | Literal[2], Literal['a'] | Literal['b']]\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequenceWildcardRefutability]\n# flags: --strict-equality --warn-unreachable\ndef f1(x: int | list[int]):\n    match x:\n        case [*foo]:\n            reveal_type(x)  # N: Revealed type is \"builtins.list[builtins.int]\"\n            reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.int]\"\n        case _:\n            reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\ndef f2(x: object):\n    match x:\n        case [*foo]:\n            reveal_type(x)  # N: Revealed type is \"typing.Sequence[builtins.object]\"\n            reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.object]\"\n        case _:\n            reveal_type(x)  # N: Revealed type is \"builtins.object\"\n\ndef f3(x: int | list[int]):\n    match x:\n        case [1, *foo]:\n            reveal_type(x)  # N: Revealed type is \"builtins.list[builtins.int]\"\n            reveal_type(foo)  # N: Revealed type is \"builtins.list[builtins.int]\"\n        case _:\n            reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.list[builtins.int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequenceTupleAsPattern]\n# flags: --strict-equality --warn-unreachable\n\ndef f1(x: tuple[list[int], list[int]]):\n    match x:\n        case _, []:\n            reveal_type(x)  # N: Revealed type is \"tuple[builtins.list[builtins.int], builtins.list[builtins.int]]\"\n        case [], _:\n            reveal_type(x)  # N: Revealed type is \"tuple[builtins.list[builtins.int], builtins.list[builtins.int]]\"\n        case _:\n            reveal_type(x)  # N: Revealed type is \"tuple[builtins.list[builtins.int], builtins.list[builtins.int]]\"\n\ndef f2(x: tuple[list[int], list[int]]):\n    match x:\n        case a, b:\n            reveal_type(x)  # N: Revealed type is \"tuple[builtins.list[builtins.int], builtins.list[builtins.int]]\"\n        case [], _:\n            reveal_type(x)  # E: Statement is unreachable\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequenceTupleRegression]\n# flags: --strict-equality --warn-unreachable\n\ndef f1(a: str | None, b: str | None):\n    # https://github.com/python/mypy/issues/14731\n    match (a, b):\n        case (None, _) | (_, None):\n            reveal_type(a)  # N: Revealed type is \"builtins.str | None\"\n            reveal_type(b)  # N: Revealed type is \"builtins.str | None\"\n        case (a, b):\n            reveal_type(a)  # N: Revealed type is \"builtins.str\"\n            reveal_type(b)  # N: Revealed type is \"builtins.str\"\n\ndef f2(x: tuple[int | str]):\n    # https://github.com/python/mypy/issues/14833#issuecomment-1454768900\n    match x:\n        case (int(),):\n            reveal_type(x)  # N: Revealed type is \"tuple[builtins.int]\"\n        case (str(),):\n            reveal_type(x)  # N: Revealed type is \"tuple[builtins.str]\"\n        case _:\n            reveal_type(x)  # E: Statement is unreachable\n\ndef f4(x: tuple[int | str, str]):\n    # https://github.com/python/mypy/issues/18792\n    match x:\n        case (int(), y):\n            reveal_type(x)  # N: Revealed type is \"tuple[builtins.int, builtins.str]\"\n        case (str(), y):\n            reveal_type(x)  # N: Revealed type is \"tuple[builtins.str, builtins.str]\"\n        case _:\n            reveal_type(x)  # E: Statement is unreachable\n\nclass Add(tuple[int, int]): ...\nclass Const(int): ...\n\ndef f5(e: Add | Const) -> int:\n    # https://github.com/python/mypy/issues/17139\n    reveal_type(e)  # N: Revealed type is \"tuple[builtins.int, builtins.int, fallback=__main__.Add] | __main__.Const\"\n    match e:\n        case Add((a, b)):\n            reveal_type(e)  # N: Revealed type is \"tuple[builtins.int, builtins.int, fallback=__main__.Add]\"\n            return a + b\n        case Const(x):\n            reveal_type(e)  # N: Revealed type is \"__main__.Const\"\n            return x\n    reveal_type(e)  # E: Statement is unreachable\n\ndef f6(d1: list[str], d2: list[str]):\n    # https://github.com/python/mypy/issues/19995\n    match (d1, d2):\n        case ([sym], _) | (_, [sym]):\n            reveal_type(sym)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dict.pyi]\n\n\n[case testMatchTupleUnions]\nfrom typing_extensions import Unpack\n\nm1: tuple[int, str] | None\nmatch m1:\n    case (a1, b1):\n        reveal_type(a1)  # N: Revealed type is \"builtins.int\"\n        reveal_type(b1)  # N: Revealed type is \"builtins.str\"\n\nm2: tuple[int, str] | tuple[float, str]\nmatch m2:\n    case (a2, b2):\n        reveal_type(a2)  # N: Revealed type is \"builtins.int | builtins.float\"\n        reveal_type(b2)  # N: Revealed type is \"builtins.str\"\n\nm3: tuple[int] | tuple[float, str]\nmatch m3:\n    case (a3, b3):\n        reveal_type(a3)  # N: Revealed type is \"builtins.float\"\n        reveal_type(b3)  # N: Revealed type is \"builtins.str\"\n\nm4: tuple[int] | list[str]\nmatch m4:\n    case (a4, b4):\n        reveal_type(a4)  # N: Revealed type is \"builtins.str\"\n        reveal_type(b4)  # N: Revealed type is \"builtins.str\"\n\nm5: tuple[int, Unpack[tuple[float, ...]]] | None\nmatch m5:\n    case (a5, b5):\n        reveal_type(a5)  # N: Revealed type is \"builtins.int\"\n        reveal_type(b5)  # N: Revealed type is \"builtins.float\"\n\nm6: tuple[int, Unpack[tuple[float, ...]]] | list[str]\nmatch m6:\n    case (a6, b6):\n        reveal_type(a6)  # N: Revealed type is \"builtins.int | builtins.str\"\n        reveal_type(b6)  # N: Revealed type is \"builtins.float | builtins.str\"\n\nm7: tuple[int, Unpack[tuple[float, ...]]] | tuple[str, str]\nmatch m7:\n    case (a7, b7, *rest7):\n        reveal_type(a7)  # N: Revealed type is \"builtins.int | builtins.str\"\n        reveal_type(b7)  # N: Revealed type is \"builtins.float | builtins.str\"\n        reveal_type(rest7)  # N: Revealed type is \"builtins.list[builtins.float]\"\n\n# verify that if we are unpacking, it will get the type of the sequence if the tuple is too short\nm8: tuple[int, str] | list[float]\nmatch m8:\n    case (a8, b8, *rest8):\n        reveal_type(a8)  # N: Revealed type is \"builtins.int | builtins.float\"\n        reveal_type(b8)  # N: Revealed type is \"builtins.str | builtins.float\"\n        reveal_type(rest8)  # N: Revealed type is \"builtins.list[builtins.float]\"\n\nm9: tuple[str, str, int] | tuple[str, str]\nmatch m9:\n    case (a9, *rest9):\n        reveal_type(a9)  # N: Revealed type is \"builtins.str\"\n        reveal_type(rest9)  # N: Revealed type is \"builtins.list[builtins.str | builtins.int] | builtins.list[builtins.str]\"\n\n[builtins fixtures/tuple.pyi]\n\n\n[case testMatchEnumSingleChoice]\nfrom enum import Enum\nfrom typing import NoReturn\n\ndef assert_never(x: NoReturn) -> None: ...\n\nclass Medal(Enum):\n    GOLD = 1\n\ndef f(m: Medal) -> None:\n    always_assigned: int | None = None\n    match m:\n        case Medal.GOLD:\n            always_assigned = 1\n            # Ideally, this should narrow to literal\n            # However `expr_type = try_expanding_sum_type_to_union(coerce_to_literal(expr_type), None)`\n            # in checker.py means we expand the type to a LiteralType and then because there is no\n            # net change we don't end up inserting the LiteralType into the type map\n            reveal_type(m)  # N: Revealed type is \"__main__.Medal\"\n        case _:\n            assert_never(m)\n\n    reveal_type(always_assigned)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/bool.pyi]\n\n[case testMatchLiteralPatternEnumNegativeNarrowing]\nfrom enum import Enum\nclass Medal(Enum):\n    gold = 1\n    silver = 2\n    bronze = 3\n\ndef f(m: Medal) -> int:\n    match m:\n        case Medal.gold:\n            reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.gold]\"\n            return 0\n        case _:\n            reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.silver] | Literal[__main__.Medal.bronze]\"\n            return 1\n\ndef g(m: Medal) -> int:\n    match m:\n        case Medal.gold:\n            reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.gold]\"\n            return 0\n        case Medal.silver:\n            reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.silver]\"\n            return 1\n        case Medal.bronze:\n            reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.bronze]\"\n            return 2\n[builtins fixtures/enum.pyi]\n\n[case testMatchLiteralOrValuePattern]\n# flags: --warn-unreachable\nfrom typing import Literal\n\ndef test1(x: Literal[1,2,3]) -> None:\n    match x:\n        case 1:\n            reveal_type(x)  # N: Revealed type is \"Literal[1]\"\n        case other:\n            reveal_type(x)  # N: Revealed type is \"Literal[2] | Literal[3]\"\n\ndef test2(x: Literal[1,2,3]) -> None:\n    match x:\n        case 1:\n            reveal_type(x)  # N: Revealed type is \"Literal[1]\"\n        case 2:\n            reveal_type(x)  # N: Revealed type is \"Literal[2]\"\n        case 3:\n            reveal_type(x)  # N: Revealed type is \"Literal[3]\"\n        case other:\n            1  # E: Statement is unreachable\n\ndef test3(x: Literal[1,2,3]) -> None:\n    match x:\n        case 1 | 3:\n            reveal_type(x)  # N: Revealed type is \"Literal[1] | Literal[3]\"\n        case other:\n            reveal_type(x)  # N: Revealed type is \"Literal[2]\"\n\n[case testMatchLiteralPatternEnumWithTypedAttribute]\nfrom enum import Enum\nfrom typing import NoReturn\ndef assert_never(x: NoReturn) -> None: ...\n\nclass int:\n    def __new__(cls, value: int): pass\n\nclass Medal(int, Enum):\n    prize: str\n\n    def __new__(cls, value: int, prize: str) -> Medal:\n        enum = int.__new__(cls, value)\n        enum._value_ = value\n        enum.prize = prize\n        return enum\n\n    gold = (1, 'cash prize')\n    silver = (2, 'sponsorship')\n    bronze = (3, 'nothing')\n\nm: Medal\n\nmatch m:\n    case Medal.gold:\n        reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.gold]\"\n    case Medal.silver:\n        reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.silver]\"\n    case Medal.bronze:\n        reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.bronze]\"\n    case _ as unreachable:\n        assert_never(unreachable)\n\n[builtins fixtures/tuple.pyi]\n\n[case testMatchLiteralPatternFunctionalEnum]\nfrom enum import Enum\nfrom typing import NoReturn\ndef assert_never(x: NoReturn) -> None: ...\n\nMedal = Enum('Medal', 'gold silver bronze')\nm: Medal\n\nmatch m:\n    case Medal.gold:\n        reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.gold]\"\n    case Medal.silver:\n        reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.silver]\"\n    case Medal.bronze:\n        reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.bronze]\"\n    case _ as unreachable:\n        assert_never(unreachable)\n[builtins fixtures/enum.pyi]\n\n[case testMatchLiteralPatternEnumCustomEquals]\n# flags: --strict-equality --warn-unreachable\nfrom enum import Enum\nclass Medal(Enum):\n    gold = 1\n    silver = 2\n    bronze = 3\n\n    def __eq__(self, other) -> bool: ...\n\nm: Medal\n\nmatch m:\n    case Medal.gold:\n        reveal_type(m)  # N: Revealed type is \"__main__.Medal\"\n    case _:\n        reveal_type(m)  # N: Revealed type is \"Literal[__main__.Medal.silver] | Literal[__main__.Medal.bronze]\"\n[builtins fixtures/enum.pyi]\n\n[case testMatchNarrowUsingPatternGuardSpecialCase]\ndef f(x: int | str) -> int:\n    match x:\n        case x if isinstance(x, str):\n            return 0\n        case int():\n            return 1\n[builtins fixtures/isinstance.pyi]\n\n[case testMatchNarrowDownUnionPartially]\n\ndef f(x: int | str) -> None:\n    match x:\n        case int():\n            return\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\ndef g(x: int | str | None) -> None:\n    match x:\n        case int() | None:\n            return\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\ndef h(x: int | str | None) -> None:\n    match x:\n        case int() | str():\n            return\n    reveal_type(x)  # N: Revealed type is \"None\"\n\n[case testMatchNarrowDownUsingLiteralMatch]\nfrom enum import Enum\nclass Medal(Enum):\n    gold = 1\n    silver = 2\n\ndef b1(x: bool) -> None:\n    match x:\n        case True:\n            return\n    reveal_type(x)  # N: Revealed type is \"Literal[False]\"\n\ndef b2(x: bool) -> None:\n    match x:\n        case False:\n            return\n    reveal_type(x)  # N: Revealed type is \"Literal[True]\"\n\ndef e1(x: Medal) -> None:\n    match x:\n        case Medal.gold:\n            return\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Medal.silver]\"\n\ndef e2(x: Medal) -> None:\n    match x:\n        case Medal.silver:\n            return\n    reveal_type(x)  # N: Revealed type is \"Literal[__main__.Medal.gold]\"\n\ndef i(x: int) -> None:\n    match x:\n        case 1:\n            return\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n\ndef s(x: str) -> None:\n    match x:\n        case 'x':\n            return\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n\ndef union(x: str | bool) -> None:\n    match x:\n        case True:\n            return\n    reveal_type(x)  # N: Revealed type is \"builtins.str | Literal[False]\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchNarrowDownUnionUsingClassPattern]\n\nclass Foo: ...\nclass Bar(Foo): ...\n\ndef test_1(bar: Bar) -> None:\n    match bar:\n        case Foo() as foo:\n            reveal_type(foo)  # N: Revealed type is \"__main__.Bar\"\n\ndef test_2(bar: Bar | str) -> None:\n    match bar:\n        case Foo() as foo:\n            reveal_type(foo)  # N: Revealed type is \"__main__.Bar\"\n\n\n[case testMatchAssertFalseToSilenceFalsePositives]\nclass C:\n    a: int | str\n\ndef f(c: C) -> int:\n    match c:\n        case C(a=int()):\n            return 0\n        case C(a=str()):\n            return 1\n        case _:\n            assert False\n\ndef g(c: C) -> int:\n    match c:\n        case C(a=int()):\n            return 0\n        case C(a=str()):\n            return 1\n    assert False\n\n[case testMatchAsPatternExhaustiveness]\ndef f(x: int | str) -> int:\n    match x:\n        case int() as n:\n            return n\n        case str() as s:\n            return 1\n\n[case testMatchOrPatternExhaustiveness]\nfrom typing import NoReturn, Literal\ndef assert_never(x: NoReturn) -> None: ...\n\nColor = Literal[\"blue\", \"green\", \"red\"]\nc: Color\n\nmatch c:\n    case \"blue\":\n        reveal_type(c) # N: Revealed type is \"Literal['blue']\"\n    case \"green\" | \"notColor\":\n        reveal_type(c) # N: Revealed type is \"Literal['green']\"\n    case _:\n        assert_never(c) # E: Argument 1 to \"assert_never\" has incompatible type \"Literal['red']\"; expected \"Never\"\n[typing fixtures/typing-typeddict.pyi]\n\n[case testMatchAsPatternIntersection]\n# flags: --strict-equality --warn-unreachable\nclass A: pass\nclass B: pass\nclass C: pass\n\ndef f(x: A) -> None:\n    match x:\n        case B() as y:\n            reveal_type(y)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\">\"\n        case C() as y:\n            reveal_type(y)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.C\">\"\n    reveal_type(y)  # N: Revealed type is \"__main__.<subclass of \"__main__.A\" and \"__main__.B\"> | __main__.<subclass of \"__main__.A\" and \"__main__.C\">\"\n\n[case testMatchWithBreakAndContinue]\ndef f(x: int | str | None) -> None:\n    i = int()\n    while i:\n        match x:\n            case int():\n                continue\n            case str():\n                break\n        reveal_type(x)  # N: Revealed type is \"None\"\n    reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str | None\"\n\n[case testMatchNarrowDownWithStarred-skip]\nfrom typing import List\ndef f(x: List[int] | int) -> None:\n    match x:\n        case [*y]:\n            reveal_type(y)  # N: Revealed type is \"builtins.list[builtins.int]\"\n            return\n    reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/list.pyi]\n\n-- Misc\n\n[case testMatchAndWithStatementScope]\nfrom m import A, B\n\nwith A() as x:\n    pass\nwith B() as x: \\\n    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    pass\n\nwith A() as y:\n    pass\nwith B() as y: \\\n    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    pass\n\nwith A() as z:\n    pass\nwith B() as z: \\\n    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    pass\n\nwith A() as zz:\n    pass\nwith B() as zz: \\\n    # E: Incompatible types in assignment (expression has type \"B\", variable has type \"A\")\n    pass\n\nmatch x:\n    case str(y) as z:\n        zz = y\n\n[file m.pyi]\nfrom typing import Any\n\nclass A:\n    def __enter__(self) -> A: ...\n    def __exit__(self, x, y, z) -> None: ...\nclass B:\n    def __enter__(self) -> B: ...\n    def __exit__(self, x, y, z) -> None: ...\n\n[case testOverrideMatchArgs]\nclass AST:\n   __match_args__ = ()\n\nclass stmt(AST): ...\n\nclass AnnAssign(stmt):\n   __match_args__ = ('target', 'annotation', 'value', 'simple')\n   target: str\n   annotation: int\n   value: str\n   simple: int\n\nreveal_type(AST.__match_args__)  # N: Revealed type is \"tuple[()]\"\nreveal_type(stmt.__match_args__)  # N: Revealed type is \"tuple[()]\"\nreveal_type(AnnAssign.__match_args__)  # N: Revealed type is \"tuple[Literal['target']?, Literal['annotation']?, Literal['value']?, Literal['simple']?]\"\n\nAnnAssign.__match_args__ = ('a', 'b', 'c', 'd')  # E: Cannot assign to \"__match_args__\"\n__match_args__ = 0\n\ndef f(x: AST) -> None:\n    match x:\n        case AST():\n            reveal_type(x)  # N: Revealed type is \"__main__.AST\"\n    match x:\n        case stmt():\n            reveal_type(x)  # N: Revealed type is \"__main__.stmt\"\n    match x:\n        case AnnAssign(a, b, c, d):\n            reveal_type(a)  # N: Revealed type is \"builtins.str\"\n            reveal_type(b)  # N: Revealed type is \"builtins.int\"\n            reveal_type(c)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchReachableDottedNames]\n# flags: --warn-unreachable\nclass Consts:\n    BLANK = \"\"\n    SPECIAL = \"asdf\"\n\ndef test_func(test_str: str) -> str:\n    match test_str:\n        case Consts.BLANK:\n            return \"blank\"\n        case Consts.SPECIAL:\n            return \"special\"\n        case _:\n            return \"other\"\n\n\n[case testNoneTypeWarning]\nfrom types import NoneType\n\ndef foo(x: NoneType): # E: NoneType should not be used as a type, please use None instead\n    reveal_type(x) # N: Revealed type is \"None\"\n\n[builtins fixtures/tuple.pyi]\n\n[case testMatchTupleInstanceUnionNoCrash]\nfrom typing import Union\n\ndef func(e: Union[str, tuple[str]]) -> None:\n    match e:\n        case (a,) if isinstance(a, str):\n            reveal_type(a)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchTupleOptionalNoCrash]\nfoo: tuple[int] | None\nmatch foo:\n    case x,:\n        reveal_type(x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchUnionTwoTuples]\n# flags: --strict-equality --warn-unreachable\n\ndef main(var: tuple[int, int] | tuple[str, str]):\n    match var:\n        case (42, a):\n            reveal_type(a)  # N: Revealed type is \"builtins.int\"\n        case (\"yes\", b):\n            reveal_type(b)  # N: Revealed type is \"builtins.str\"\n\n\ndef main2(var: tuple[int, int] | tuple[str, str] | tuple[str, int]):\n    match var:\n        case (42, a):\n            reveal_type(a)  # N: Revealed type is \"builtins.int\"\n        case (\"yes\", b):\n            reveal_type(b)  # N: Revealed type is \"builtins.str | builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchNamedAndKeywordsAreTheSame]\nfrom typing import Generic, Final, TypeVar, Union\nfrom dataclasses import dataclass\n\nT = TypeVar(\"T\")\n\nclass Regular:\n    x: str\n    y: int\n    __match_args__ = (\"x\",)\nclass ReversedOrder:\n    x: int\n    y: str\n    __match_args__ = (\"y\",)\nclass GenericRegular(Generic[T]):\n    x: T\n    __match_args__ = (\"x\",)\nclass GenericWithFinal(Generic[T]):\n    x: T\n    __match_args__: Final = (\"x\",)\nclass RegularSubtype(GenericRegular[str]): ...\n\n@dataclass\nclass GenericDataclass(Generic[T]):\n    x: T\n\ninput_arg: Union[\n    Regular,\n    ReversedOrder,\n    GenericRegular[str],\n    GenericWithFinal[str],\n    RegularSubtype,\n    GenericDataclass[str],\n]\n\n# Positional:\nmatch input_arg:\n    case Regular(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    case ReversedOrder(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    case GenericWithFinal(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    case RegularSubtype(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    case GenericRegular(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    case GenericDataclass(a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n\n# Keywords:\nmatch input_arg:\n    case Regular(x=a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    case ReversedOrder(x=b):  # Order is different\n        reveal_type(b)  # N: Revealed type is \"builtins.int\"\n    case GenericWithFinal(x=a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    case RegularSubtype(x=a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    case GenericRegular(x=a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    case GenericDataclass(x=a):\n        reveal_type(a)  # N: Revealed type is \"builtins.str\"\n[builtins fixtures/dataclasses.pyi]\n\n[case testMatchValueConstrainedTypeVar]\nfrom typing import TypeVar, Iterable\n\nS = TypeVar(\"S\", int, str)\n\ndef my_func(pairs: Iterable[tuple[S, S]]) -> None:\n    for pair in pairs:\n        reveal_type(pair)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\" \\\n                           # N: Revealed type is \"tuple[builtins.str, builtins.str]\"\n        match pair:\n            case _:\n                reveal_type(pair)  # N: Revealed type is \"tuple[builtins.int, builtins.int]\" \\\n                                   # N: Revealed type is \"tuple[builtins.str, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testPossiblyUndefinedMatch]\n# flags: --enable-error-code possibly-undefined\ndef f0(x: int | str) -> int:\n    match x:\n        case int():\n            y = 1\n    return y  # E: Name \"y\" may be undefined\n\ndef f1(a: object) -> None:\n    match a:\n        case [y]: pass\n        case _:\n            y = 1\n            x = 2\n    z = y\n    z = x  # E: Name \"x\" may be undefined\n\ndef f2(a: object) -> None:\n    match a:\n        case [[y] as x]: pass\n        case {\"k1\": 1, \"k2\": x, \"k3\": y}: pass\n        case [0, *x]:\n            y = 2\n        case _:\n            y = 1\n            x = [2]\n    z = x\n    z = y\n\ndef f3(a: object) -> None:\n    y = 1\n    match a:\n        case [x]:\n            y = 2\n        # Note the missing `case _:`\n    z = x  # E: Name \"x\" may be undefined\n    z = y\n\ndef f4(a: object) -> None:\n    y = 1\n    match a:\n        case [x]:\n            y = 2\n        case _:\n            assert False, \"unsupported\"\n    z = x\n    z = y\n\ndef f5(a: object) -> None:\n    match a:\n        case tuple(x): pass\n        case _:\n            return\n    y = x\n\ndef f6(a: object) -> None:\n    if int():\n        y = 1\n    match a:\n        case _ if y is not None:  # E: Name \"y\" may be undefined\n            pass\n[builtins fixtures/tuple.pyi]\n\n[case testPossiblyUndefinedMatchUnreachable]\n# flags: --enable-error-code possibly-undefined\nimport typing\n\ndef f0(x: int) -> int:\n    match x:\n        case 1 if not typing.TYPE_CHECKING:\n            pass\n        case 2:\n            y = 2\n        case _:\n            y = 3\n    return y # No error.\n\ndef f1(x: int) -> int:\n    match x:\n        case 1 if not typing.TYPE_CHECKING:\n            pass\n        case 2:\n            y = 2\n    return y  # E: Name \"y\" may be undefined\n\n[typing fixtures/typing-medium.pyi]\n\n[case testUsedBeforeDefMatchWalrus]\n# flags: --enable-error-code used-before-def\nimport typing\n\ndef f0(x: int) -> None:\n    a = y  # E: Cannot determine type of \"y\"  # E: Name \"y\" is used before definition\n    match y := x:\n        case 1:\n            b = y\n        case 2:\n            c = y\n    d = y\n\n[case testTypeAliasWithNewUnionSyntaxAndNoneLeftOperand]\nfrom typing import overload\nclass C:\n    @overload\n    def __init__(self) -> None: pass\n    @overload\n    def __init__(self, x: int) -> None: pass\n    def __init__(self, x=0):\n        pass\n\nclass D: pass\n\nX = None | C\nY = None | D\n[builtins fixtures/type.pyi]\n\n[case testMatchStatementWalrus]\nclass A:\n    a = 1\n\ndef returns_a_or_none() -> A | None:\n    return A()\n\ndef returns_a() -> A:\n    return A()\n\ndef f() -> None:\n    match x := returns_a_or_none():\n        case A():\n            reveal_type(x.a)  # N: Revealed type is \"builtins.int\"\n    reveal_type(x)  # N: Revealed type is \"__main__.A | None\"\n    match x := returns_a():\n        case A():\n            reveal_type(x.a)  # N: Revealed type is \"builtins.int\"\n    reveal_type(x)  # N: Revealed type is \"__main__.A\"\n    y = returns_a_or_none()\n    match y:\n        case A():\n            reveal_type(y.a)  # N: Revealed type is \"builtins.int\"\n\n[case testNarrowedVariableInNestedModifiedInMatch]\nfrom typing import Optional\n\ndef match_stmt_error1(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    match object():\n        case str(x):\n            pass\n    nested()\n\ndef foo(x): pass\n\ndef match_stmt_ok1(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x\n    match foo(x):\n        case str(y):\n            z = x\n    nested()\n\ndef match_stmt_error2(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    match [None]:\n        case [x]:\n            pass\n    nested()\n\ndef match_stmt_error3(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    match {'a': None}:\n        case {'a': x}:\n            pass\n    nested()\n\ndef match_stmt_error4(x: Optional[list[str]]) -> None:\n    if x is None:\n        x = [\"a\"]\n    def nested() -> list[str]:\n        return x  # E: Incompatible return value type (got \"list[str] | None\", expected \"list[str]\")\n    match [\"a\"]:\n        case [*x]:\n            pass\n    nested()\n\nclass C:\n    a: str\n\ndef match_stmt_error5(x: Optional[str]) -> None:\n    if x is None:\n        x = \"a\"\n    def nested() -> str:\n        return x  # E: Incompatible return value type (got \"str | None\", expected \"str\")\n    match C():\n        case C(a=x):\n            pass\n    nested()\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSubjectRedefinition]\n# flags: --allow-redefinition\ndef transform1(a: str) -> int:\n    ...\n\ndef transform2(a: int) -> str:\n    ...\n\ndef redefinition_good(a: str):\n    a = transform1(a)\n\n    match (a + 1):\n        case _:\n            ...\n\n\ndef redefinition_bad(a: int):\n    a = transform2(a)\n\n    match (a + 1):  # E: Unsupported operand types for + (\"str\" and \"int\")\n        case _:\n            ...\n\n[builtins fixtures/primitives.pyi]\n\n[case testPatternMatchingClassPatternLocation]\n# See https://github.com/python/mypy/issues/15496\nfrom some_missing_lib import DataFrame, Series  # type: ignore[import]\nfrom typing import TypeVar\n\nT = TypeVar(\"T\", Series, DataFrame)\n\ndef f(x: T) -> None:\n    match x:\n        case Series() | DataFrame():  # type: ignore[misc]\n            pass\n\ndef f2(x: T) -> None:\n    match x:\n        case Series():  # type: ignore[misc]\n            pass\n        case DataFrame():  # type: ignore[misc]\n            pass\n[builtins fixtures/primitives.pyi]\n\n[case testMatchGuardReachability]\n# flags: --warn-unreachable\ndef f1(e: int) -> int:\n    match e:\n        case x if True:\n            return x\n        case _:\n            return 0  # E: Statement is unreachable\n    e = 0  # E: Statement is unreachable\n\n\ndef f2(e: int) -> int:\n    match e:\n        case x if bool():\n            return x\n        case _:\n            return 0\n    e = 0  # E: Statement is unreachable\n\ndef f3(e: int | str | bytes) -> int:\n    match e:\n        case x if isinstance(x, int):\n            return x\n        case [x]:\n            return 0  # E: Statement is unreachable\n        case str(x):\n            return 0\n    reveal_type(e)  # N: Revealed type is \"builtins.bytes\"\n    return 0\n\ndef f4(e: int | str | bytes) -> int:\n    match e:\n        case int(x):\n            pass\n        case [x]:\n            return 0  # E: Statement is unreachable\n        case x if isinstance(x, str):\n            return 0\n    reveal_type(e)  # N: Revealed type is \"builtins.int | builtins.bytes\"\n    return 0\n[builtins fixtures/primitives.pyi]\n\n[case testMatchGuardAlwaysTrueAlwaysFalse]\n# flags: --warn-unreachable --always-true TRUEFLAG --always-false FALSEFLAG\nTRUEFLAG = False\nFALSEFLAG = True\n\ndef true_flag(e: int) -> None:\n    match e:\n        case _ if TRUEFLAG:\n            pass\n        case 0:\n            # No error\n            1 + \"asdf\"\n\ndef false_flag(e: int) -> None:\n    match e:\n        case _ if FALSEFLAG:\n            # No error\n            1 + \"asdf\"\n\n[case testMatchSequencePatternVariadicTupleNotTooShort]\nfrom typing import Tuple\nfrom typing_extensions import Unpack\n\nfm1: Tuple[int, int, Unpack[Tuple[str, ...]], int]\nmatch fm1:\n    case [fa1, fb1, fc1]:\n        reveal_type(fa1)  # N: Revealed type is \"builtins.int\"\n        reveal_type(fb1)  # N: Revealed type is \"builtins.int\"\n        reveal_type(fc1)  # N: Revealed type is \"builtins.int\"\n\nfm2: Tuple[int, int, Unpack[Tuple[str, ...]], int]\nmatch fm2:\n    case [fa2, fb2]:\n        reveal_type(fa2)\n        reveal_type(fb2)\n\nfm3: Tuple[int, int, Unpack[Tuple[str, ...]], int]\nmatch fm3:\n    case [fa3, fb3, fc3, fd3, fe3]:\n        reveal_type(fa3)  # N: Revealed type is \"builtins.int\"\n        reveal_type(fb3)  # N: Revealed type is \"builtins.int\"\n        reveal_type(fc3)  # N: Revealed type is \"builtins.str\"\n        reveal_type(fd3)  # N: Revealed type is \"builtins.str\"\n        reveal_type(fe3)  # N: Revealed type is \"builtins.int\"\n\nm1: Tuple[int, Unpack[Tuple[str, ...]], int]\nmatch m1:\n    case [a1, *b1, c1]:\n        reveal_type(a1)  # N: Revealed type is \"builtins.int\"\n        reveal_type(b1)  # N: Revealed type is \"builtins.list[builtins.str]\"\n        reveal_type(c1)  # N: Revealed type is \"builtins.int\"\n\nm2: Tuple[int, Unpack[Tuple[str, ...]], int]\nmatch m2:\n    case [a2, b2, *c2, d2, e2]:\n        reveal_type(a2)  # N: Revealed type is \"builtins.int\"\n        reveal_type(b2)  # N: Revealed type is \"builtins.str\"\n        reveal_type(c2)  # N: Revealed type is \"builtins.list[builtins.str]\"\n        reveal_type(d2)  # N: Revealed type is \"builtins.str\"\n        reveal_type(e2)  # N: Revealed type is \"builtins.int\"\n\nm3: Tuple[int, int, Unpack[Tuple[str, ...]], int, int]\nmatch m3:\n    case [a3, *b3, c3]:\n        reveal_type(a3)  # N: Revealed type is \"builtins.int\"\n        reveal_type(b3)  # N: Revealed type is \"builtins.list[builtins.int | builtins.str]\"\n        reveal_type(c3)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequencePatternTypeVarTupleNotTooShort]\nfrom typing import Tuple\nfrom typing_extensions import Unpack, TypeVarTuple\n\nTs = TypeVarTuple(\"Ts\")\ndef test(xs: Tuple[Unpack[Ts]]) -> None:\n    fm1: Tuple[int, int, Unpack[Ts], int]\n    match fm1:\n        case [fa1, fb1, fc1]:\n            reveal_type(fa1)  # N: Revealed type is \"builtins.int\"\n            reveal_type(fb1)  # N: Revealed type is \"builtins.int\"\n            reveal_type(fc1)  # N: Revealed type is \"builtins.int\"\n\n    fm2: Tuple[int, int, Unpack[Ts], int]\n    match fm2:\n        case [fa2, fb2]:\n            reveal_type(fa2)\n            reveal_type(fb2)\n\n    fm3: Tuple[int, int, Unpack[Ts], int]\n    match fm3:\n        case [fa3, fb3, fc3, fd3, fe3]:\n            reveal_type(fa3)  # N: Revealed type is \"builtins.int\"\n            reveal_type(fb3)  # N: Revealed type is \"builtins.int\"\n            reveal_type(fc3)  # N: Revealed type is \"builtins.object\"\n            reveal_type(fd3)  # N: Revealed type is \"builtins.object\"\n            reveal_type(fe3)  # N: Revealed type is \"builtins.int\"\n\n    m1: Tuple[int, Unpack[Ts], int]\n    match m1:\n        case [a1, *b1, c1]:\n            reveal_type(a1)  # N: Revealed type is \"builtins.int\"\n            reveal_type(b1)  # N: Revealed type is \"builtins.list[builtins.object]\"\n            reveal_type(c1)  # N: Revealed type is \"builtins.int\"\n\n    m2: Tuple[int, Unpack[Ts], int]\n    match m2:\n        case [a2, b2, *c2, d2, e2]:\n            reveal_type(a2)  # N: Revealed type is \"builtins.int\"\n            reveal_type(b2)  # N: Revealed type is \"builtins.object\"\n            reveal_type(c2)  # N: Revealed type is \"builtins.list[builtins.object]\"\n            reveal_type(d2)  # N: Revealed type is \"builtins.object\"\n            reveal_type(e2)  # N: Revealed type is \"builtins.int\"\n\n    m3: Tuple[int, int, Unpack[Ts], int, int]\n    match m3:\n        case [a3, *b3, c3]:\n            reveal_type(a3)  # N: Revealed type is \"builtins.int\"\n            reveal_type(b3)  # N: Revealed type is \"builtins.list[builtins.object]\"\n            reveal_type(c3)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequencePatternTypeVarBoundNoCrash]\n# This was crashing: https://github.com/python/mypy/issues/18089\nfrom typing import TypeVar, Sequence, Any\n\nT = TypeVar(\"T\", bound=Sequence[Any])\n\ndef f(x: T) -> None:\n    match x:\n        case [_]:\n            pass\n[builtins fixtures/tuple.pyi]\n\n[case testMatchSequencePatternTypeVarBoundNarrows]\nfrom typing import TypeVar, Sequence\n\nT = TypeVar(\"T\", bound=Sequence[int | str])\n\ndef accept_seq_int(x: Sequence[int]): ...\n\ndef f(x: T) -> None:\n    match x:\n        case [1, 2]:\n            accept_seq_int(x)\n        case _:\n            accept_seq_int(x)  # E: Argument 1 to \"accept_seq_int\" has incompatible type \"T\"; expected \"Sequence[int]\"\n[builtins fixtures/tuple.pyi]\n\n[case testNarrowingTypeVarMatch]\n# flags: --warn-unreachable\n\n# https://github.com/python/mypy/issues/18126\nfrom typing import TypeVar\n\nT = TypeVar(\"T\")\n\ndef fn_case(arg: T) -> None:\n    match arg:\n        case None:\n            return None\n    return None\n[builtins fixtures/primitives.pyi]\n\n[case testNoneCheckDoesNotMakeTypeVarOptionalMatch]\nfrom typing import TypeVar\n\nT = TypeVar('T')\n\ndef foo(x: T) -> T:\n    out = None\n    out = x\n    match out:\n        case None:\n            pass\n    return out\n\n[builtins fixtures/isinstance.pyi]\n\n[case testMatchSequenceReachableFromAny]\n# flags: --warn-unreachable\nfrom typing import Any\n\ndef maybe_list(d: Any) -> int:\n    match d:\n        case []:\n            return 0\n        case [[_]]:\n            return 1\n        case [_]:\n            return 1\n        case _:\n            return 2\n\ndef with_guard(d: Any) -> None:\n    match d:\n        case [s] if isinstance(s, str):\n            reveal_type(s)  # N: Revealed type is \"builtins.str\"\n    match d:\n        case (s,) if isinstance(s, str):\n            reveal_type(s)  # N: Revealed type is \"builtins.str\"\n\ndef nested_in_dict(d: dict[str, Any]) -> int:\n    match d:\n        case {\"src\": [\"src\"]}:\n            return 1\n        case _:\n            return 0\n\n[builtins fixtures/dict.pyi]\n\n[case testMatchRebindsOuterFunctionName]\n# flags: --warn-unreachable\nfrom typing import Literal\n\ndef x() -> tuple[Literal[\"test\"]]: ...\n\nmatch x():\n    case (x,) if x == \"test\":  # E: Incompatible types in capture pattern (pattern captures type \"Literal['test']\", variable has type \"Callable[[], tuple[Literal['test']]]\")\n        reveal_type(x)  # E: Statement is unreachable\n    case foo:\n        foo\n\n[builtins fixtures/dict.pyi]\n\n[case testMatchRebindsInnerFunctionName]\n# flags: --warn-unreachable\nclass Some:\n    value: int | str\n    __match_args__ = (\"value\",)\n\ndef fn1(x: Some | int | str) -> None:\n    match x:\n        case int():\n            def value():\n                return 1\n            reveal_type(value)  # N: Revealed type is \"def () -> Any\"\n        case str():\n            def value():\n                return 1\n            reveal_type(value)  # N: Revealed type is \"def () -> Any\"\n        case Some(value):  # E: Incompatible types in capture pattern (pattern captures type \"int | str\", variable has type \"Callable[[], Any]\")\n            pass\n\ndef fn2(x: Some | int | str) -> None:\n    match x:\n        case int():\n            def value() -> str:\n                return \"\"\n            reveal_type(value)  # N: Revealed type is \"def () -> builtins.str\"\n        case str():\n            def value() -> int:  # E: All conditional function variants must have identical signatures \\\n                                 # N: Original: \\\n                                 # N:     def value() -> str \\\n                                 # N: Redefinition: \\\n                                 # N:     def value() -> int\n                return 1\n            reveal_type(value)  # N: Revealed type is \"def () -> builtins.str\"\n        case Some(value):  # E: Incompatible types in capture pattern (pattern captures type \"int | str\", variable has type \"Callable[[], str]\")\n            pass\n[builtins fixtures/dict.pyi]\n\n[case testMatchFunctionCall]\n# flags: --warn-unreachable\n\ndef fn() -> int | str: ...\n\nmatch fn():\n    case str(s):\n        reveal_type(s)  # N: Revealed type is \"builtins.str\"\n    case int(i):\n        reveal_type(i)  # N: Revealed type is \"builtins.int\"\n    case other:\n        other  # E: Statement is unreachable\n\n[case testMatchAttribute]\n# flags: --warn-unreachable\n\nclass A:\n    foo: int | str\n\nmatch A().foo:\n    case str(s):\n        reveal_type(s)  # N: Revealed type is \"builtins.str\"\n    case int(i):\n        reveal_type(i)  # N: Revealed type is \"builtins.int\"\n    case other:\n        other  # E: Statement is unreachable\n\n[case testMatchLiteral]\n# flags: --warn-unreachable\n\ndef int_literal() -> None:\n    match 12:\n        case 1 as s:\n            reveal_type(s)  # E: Statement is unreachable\n        case int(i):\n            reveal_type(i)  # N: Revealed type is \"Literal[12]?\"\n        case other:\n            other  # E: Statement is unreachable\n\ndef str_literal() -> None:\n    match 'foo':\n        case 'a' as s:\n            reveal_type(s)  # E: Statement is unreachable\n        case str(i):\n            reveal_type(i)  # N: Revealed type is \"Literal['foo']?\"\n        case other:\n            other  # E: Statement is unreachable\n\n[case testMatchOperations]\n# flags: --warn-unreachable\n\nx: int\nmatch -x:\n    case -1 as s:\n        reveal_type(s)  # N: Revealed type is \"Literal[-1]\"\n    case int(s):\n        reveal_type(s)  # N: Revealed type is \"builtins.int\"\n    case other:\n        other  # E: Statement is unreachable\n\nmatch 1 + 2:\n    case 3 as s:\n        reveal_type(s)  # N: Revealed type is \"Literal[3]\"\n    case int(s):\n        reveal_type(s)  # N: Revealed type is \"builtins.int\"\n    case other:\n        other  # E: Statement is unreachable\n\nmatch 1 > 2:\n    case True as s:\n        reveal_type(s)  # N: Revealed type is \"Literal[True]\"\n    case False as s:\n        reveal_type(s)  # N: Revealed type is \"Literal[False]\"\n    case other:\n        other  # E: Statement is unreachable\n[builtins fixtures/ops.pyi]\n\n[case testMatchDictItem]\n# flags: --warn-unreachable\n\nm: dict[str, int | str]\nk: str\n\nmatch m[k]:\n    case str(s):\n        reveal_type(s)  # N: Revealed type is \"builtins.str\"\n    case int(i):\n        reveal_type(i)  # N: Revealed type is \"builtins.int\"\n    case other:\n        other  # E: Statement is unreachable\n\n[builtins fixtures/dict.pyi]\n\n[case testMatchLiteralValuePathological]\n# flags: --warn-unreachable\n\nmatch 0:\n    case 0 as i:\n        reveal_type(i)  # N: Revealed type is \"Literal[0]?\"\n    case int(i):\n        i  # E: Statement is unreachable\n    case other:\n        other  # E: Statement is unreachable\n\n[case testMatchNamedTupleSequence]\nfrom typing import Any, NamedTuple\n\nclass T(NamedTuple):\n    t: list[Any]\n\nclass K(NamedTuple):\n    k: int\n\ndef f(t: T) -> None:\n    match t:\n        case T([K() as k]):\n            reveal_type(k)  # N: Revealed type is \"tuple[builtins.int, fallback=__main__.K]\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchTypeObjectTypeVar]\n# flags: --warn-unreachable\nfrom typing import TypeVar\nimport b\n\nT_Choice = TypeVar(\"T_Choice\", bound=b.One | b.Two)\n\ndef switch(choice: type[T_Choice]) -> None:\n    match choice:\n        case b.One:\n            reveal_type(choice)  # N: Revealed type is \"def () -> b.One\"\n            reveal_type(choice())  # N: Revealed type is \"b.One\"\n        case b.Two:\n            reveal_type(choice)  # N: Revealed type is \"def () -> b.Two\"\n            reveal_type(choice())  # N: Revealed type is \"b.Two\"\n        case _:\n            reveal_type(choice)  # N: Revealed type is \"type[T_Choice`-1]\"\n            reveal_type(choice())  # N: Revealed type is \"b.One | b.Two\"\n\n[file b.py]\nclass One: ...\nclass Two: ...\n\n[builtins fixtures/tuple.pyi]\n\n[case testNewRedefineMatchBasics]\n# flags: --allow-redefinition-new --local-partial-types\n\ndef f1(x: int | str | list[bytes]) -> None:\n    match x:\n        case int():\n            reveal_type(x) # N: Revealed type is \"builtins.int\"\n        case str(y):\n            reveal_type(y) # N: Revealed type is \"builtins.str\"\n        case [y]:\n            reveal_type(y) # N: Revealed type is \"builtins.bytes\"\n    reveal_type(y) # N: Revealed type is \"builtins.str | builtins.bytes\"\n\n[case testNewRedefineLoopWithMatch]\n# flags: --allow-redefinition-new --local-partial-types\n\ndef f1() -> None:\n    while True:\n        x = object()\n        match x:\n            case str(y):\n                pass\n            case int():\n                pass\n        if int():\n            continue\n\ndef f2() -> None:\n    for x in [\"\"]:\n        match str():\n            case \"a\":\n                y = \"\"\n            case \"b\":\n                y = 1\n                return\n    reveal_type(y) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/list.pyi]\n\n[case testExhaustiveMatchNoFlag]\n\na: int = 5\nmatch a:\n    case 1:\n        pass\n    case _:\n        pass\n\nb: str = \"hello\"\nmatch b:\n    case \"bye\":\n        pass\n    case _:\n        pass\n\n[case testNonExhaustiveMatchNoFlag]\n\na: int = 5\nmatch a:\n    case 1:\n        pass\n\nb: str = \"hello\"\nmatch b:\n    case \"bye\":\n        pass\n\n\n[case testExhaustiveMatchWithFlag]\n# flags: --enable-error-code exhaustive-match\n\na: int = 5\nmatch a:\n    case 1:\n        pass\n    case _:\n        pass\n\nb: str = \"hello\"\nmatch b:\n    case \"bye\":\n        pass\n    case _:\n        pass\n\n[case testNonExhaustiveMatchWithFlag]\n# flags: --enable-error-code exhaustive-match\n\na: int = 5\nmatch a: # E: Match statement has unhandled case for values of type \"int\" \\\n         # N: If match statement is intended to be non-exhaustive, add `case _: pass`\n    case 1:\n        pass\n\nb: str = \"hello\"\nmatch b: # E: Match statement has unhandled case for values of type \"str\" \\\n         # N: If match statement is intended to be non-exhaustive, add `case _: pass`\n    case \"bye\":\n        pass\n[case testNonExhaustiveMatchEnumWithFlag]\n# flags: --enable-error-code exhaustive-match\n\nimport enum\n\nclass Color(enum.Enum):\n    RED = 1\n    BLUE = 2\n    GREEN = 3\n\nval: Color = Color.RED\n\nmatch val: # E: Match statement has unhandled case for values of type \"Literal[Color.GREEN]\" \\\n           # N: If match statement is intended to be non-exhaustive, add `case _: pass`\n    case Color.RED:\n        a = \"red\"\n    case Color.BLUE:\n        a= \"blue\"\n[builtins fixtures/enum.pyi]\n\n[case testExhaustiveMatchEnumWithFlag]\n# flags: --enable-error-code exhaustive-match\n\nimport enum\n\nclass Color(enum.Enum):\n    RED = 1\n    BLUE = 2\n\nval: Color = Color.RED\n\nmatch val:\n    case Color.RED:\n        a = \"red\"\n    case Color.BLUE:\n        a= \"blue\"\n[builtins fixtures/enum.pyi]\n\n[case testNonExhaustiveMatchEnumMultipleMissingMatchesWithFlag]\n# flags: --enable-error-code exhaustive-match\n\nimport enum\n\nclass Color(enum.Enum):\n    RED = 1\n    BLUE = 2\n    GREEN = 3\n\nval: Color = Color.RED\n\nmatch val: # E: Match statement has unhandled case for values of type \"Literal[Color.BLUE, Color.GREEN]\" \\\n           # N: If match statement is intended to be non-exhaustive, add `case _: pass`\n    case Color.RED:\n        a = \"red\"\n[builtins fixtures/enum.pyi]\n\n[case testExhaustiveMatchEnumFallbackWithFlag]\n# flags: --enable-error-code exhaustive-match\n\nimport enum\n\nclass Color(enum.Enum):\n    RED = 1\n    BLUE = 2\n    GREEN = 3\n\nval: Color = Color.RED\n\nmatch val:\n    case Color.RED:\n        a = \"red\"\n    case _:\n        a = \"other\"\n[builtins fixtures/enum.pyi]\n\n# Fork of testMatchNarrowingUnionTypedDictViaIndex to check behaviour with exhaustive match flag\n[case testExhaustiveMatchNarrowingUnionTypedDictViaIndex]\n# flags: --enable-error-code exhaustive-match\n\nfrom typing import Literal, TypedDict\n\nclass A(TypedDict):\n    tag: Literal[\"a\"]\n    name: str\n\nclass B(TypedDict):\n    tag: Literal[\"b\"]\n    num: int\n\nd: A | B\nmatch d[\"tag\"]: # E: Match statement has unhandled case for values of type \"Literal['b']\" \\\n                # N: If match statement is intended to be non-exhaustive, add `case _: pass` \\\n                # E: Match statement has unhandled case for values of type \"B\"\n    case \"a\":\n        reveal_type(d)  # N: Revealed type is \"TypedDict('__main__.A', {'tag': Literal['a'], 'name': builtins.str})\"\n        reveal_type(d[\"name\"])  # N: Revealed type is \"builtins.str\"\n[typing fixtures/typing-typeddict.pyi]\n\n[case testEnumTypeObjectMember]\nimport enum\nfrom typing import NoReturn\n\ndef assert_never(x: NoReturn) -> None: ...\n\nclass ValueType(enum.Enum):\n    INT = int\n    STR = str\n\nvalue_type: ValueType = ValueType.INT\n\nmatch value_type:\n    case ValueType.INT:\n        pass\n    case ValueType.STR:\n        pass\n    case _:\n        assert_never(value_type)\n[builtins fixtures/tuple.pyi]\n\n[case testAssignmentToFinalInMatchCaseNotAllowed]\nfrom typing import Final\n\nFOO: Final[int] = 10\n\nval: int = 8\nmatch val:\n    case FOO:  # E: Cannot assign to final name \"FOO\"\n        pass\n\n[case testMatchExhaustivenessWithDeferral]\n# flags: --enable-error-code exhaustive-match\nfrom typing import Literal\nimport unknown_module  # E: Cannot find implementation or library stub for module named \"unknown_module\" \\\n                       # N: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports\n\ndef foo(e: Literal[0, 1]) -> None:\n    match e:\n        case 0:\n            defer\n        case 1:\n            ...\n\ndefer = unknown_module.foo\n\n[case testMatchErrorsIncorrectName]\nclass A:\n    pass\n\nmatch 5:\n    case A.blah():  # E: \"type[A]\" has no attribute \"blah\"\n        pass\n\n[case testMatchAllowsAnyClassArgsForAny]\nmatch 5:\n    case BlahBlah(a, b):  # E: Name \"BlahBlah\" is not defined\n        reveal_type(a)  # N: Revealed type is \"Any\"\n        reveal_type(b)  # N: Revealed type is \"Any\"\n    case BlahBlah(c=c):  # E: Name \"BlahBlah\" is not defined\n        reveal_type(c)  # N: Revealed type is \"Any\"\n\n[case testMatchAllowsNoneTypeAsClass]\nimport types\n\nclass V:\n    X = types.NoneType\n\ndef fun(val: str | None):\n    match val:\n        case V.X():\n            reveal_type(val)  # N: Revealed type is \"None\"\n\n    match val:\n        case types.NoneType():\n            reveal_type(val)  # N: Revealed type is \"None\"\n[builtins fixtures/tuple.pyi]\n\n[case testMatchMappingRestErrorLocation]\nrest: list[int]\ndata: list[int]\nmatch data:\n    case [1, *rest]:\n        ...\nconfig: dict[str, object]\nmatch config:\n    case {\"a\": 1, **rest}:  # E: Incompatible types in capture pattern (pattern captures type \"dict[str, object]\", variable has type \"list[int]\")\n        ...\n[builtins fixtures/dict.pyi]\n\n[case testMatchTypeNarrowing]\n# flags: --warn-unreachable\nimport builtins\nimport typing\nimport types\n\ndef type_bare(field_type: type) -> str:\n    match field_type:\n        case builtins.int:\n            reveal_type(field_type)  # N: Revealed type is \"def () -> builtins.int\"\n            ret = \"foo\"\n        case builtins.str:\n            reveal_type(field_type)  # N: Revealed type is \"def () -> builtins.str\"\n            ret = \"foo\"\n        case builtins.bytes:\n            reveal_type(field_type)  # N: Revealed type is \"def () -> builtins.bytes\"\n            ret = \"foo\"\n        case builtins.bool:\n            reveal_type(field_type)  # N: Revealed type is \"def () -> builtins.bool\"\n            ret = \"foo\"\n        case types.NoneType:\n            reveal_type(field_type)  # N: Revealed type is \"type[None]\"\n            ret = \"foo\"\n        case _:\n            reveal_type(field_type)  # N: Revealed type is \"builtins.type\"\n            return \"bar\"\n    return ret\n\ndef type_any(field_type: type[typing.Any]) -> str:\n    match field_type:\n        case builtins.int:\n            reveal_type(field_type)  # N: Revealed type is \"type[Any]\"\n            ret = \"foo\"\n        case builtins.str:\n            reveal_type(field_type)  # N: Revealed type is \"type[Any]\"\n            ret = \"foo\"\n        case builtins.bytes:\n            reveal_type(field_type)  # N: Revealed type is \"type[Any]\"\n            ret = \"foo\"\n        case builtins.bool:\n            reveal_type(field_type)  # N: Revealed type is \"type[Any]\"\n            ret = \"foo\"\n        case types.NoneType:\n            reveal_type(field_type)  # N: Revealed type is \"type[None]\"\n            ret = \"foo\"\n        case _:\n            reveal_type(field_type)  # N: Revealed type is \"type[Any]\"\n            return \"bar\"\n    return ret\n\ndef type_object(field_type: type[object]) -> str:\n    match field_type:\n        case builtins.int:\n            reveal_type(field_type)  # N: Revealed type is \"def () -> builtins.int\"\n            ret = \"foo\"\n        case builtins.str:\n            reveal_type(field_type)  # N: Revealed type is \"def () -> builtins.str\"\n            ret = \"foo\"\n        case builtins.bytes:\n            reveal_type(field_type)  # N: Revealed type is \"def () -> builtins.bytes\"\n            ret = \"foo\"\n        case builtins.bool:\n            reveal_type(field_type)  # N: Revealed type is \"def () -> builtins.bool\"\n            ret = \"foo\"\n        case types.NoneType:\n            reveal_type(field_type)  # N: Revealed type is \"type[None]\"\n            ret = \"foo\"\n        case _:\n            reveal_type(field_type)  # N: Revealed type is \"type[builtins.object]\"\n            return \"bar\"\n    return ret\n[builtins fixtures/dict.pyi]\n\n\n[case testMatchFinalClass]\nfrom typing import final, NoReturn\n\ndef assert_never(x: NoReturn) -> NoReturn: ...\n\nclass Types:\n\n    @final\n    class A:\n        pass\n\n    @final\n    class B:\n        pass\n\ndef foo(cls: type[Types.A | Types.B]) -> None:\n    match cls:\n        case Types.A:\n            reveal_type(cls)  # N: Revealed type is \"type[__main__.Types.A]\"\n        case Types.B:\n            reveal_type(cls)  # N: Revealed type is \"type[__main__.Types.B]\"\n        case _:\n            assert_never(cls)\n\n\nclass TypeTypes:\n    A: type[Types.A] = Types.A\n    B: type[Types.B] = Types.B\n\n\ndef bar(cls: type[Types.A | Types.B]) -> None:\n    match cls:\n        case TypeTypes.A:\n            reveal_type(cls)  # N: Revealed type is \"type[__main__.Types.A]\"\n        case TypeTypes.B:\n            reveal_type(cls)  # N: Revealed type is \"type[__main__.Types.B]\"\n        case _:\n            assert_never(cls)\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-python311.test",
    "content": "[case testTryStarSimple]\ntry:\n    pass\nexcept* Exception as e:\n    reveal_type(e)  # N: Revealed type is \"builtins.ExceptionGroup[builtins.Exception]\"\n[builtins fixtures/exception.pyi]\n\n[case testTryStarMultiple]\ntry:\n    pass\nexcept* Exception as e:\n    reveal_type(e)  # N: Revealed type is \"builtins.ExceptionGroup[builtins.Exception]\"\nexcept* RuntimeError as e:\n    reveal_type(e)  # N: Revealed type is \"builtins.ExceptionGroup[builtins.RuntimeError]\"\n[builtins fixtures/exception.pyi]\n\n[case testTryStarBase]\ntry:\n    pass\nexcept* BaseException as e:\n    reveal_type(e)  # N: Revealed type is \"builtins.BaseExceptionGroup[builtins.BaseException]\"\n[builtins fixtures/exception.pyi]\n\n[case testTryStarTuple]\nclass Custom(Exception): ...\n\ntry:\n    pass\nexcept* (RuntimeError, Custom) as e:\n    reveal_type(e)  # N: Revealed type is \"builtins.ExceptionGroup[builtins.RuntimeError | __main__.Custom]\"\n[builtins fixtures/exception.pyi]\n\n[case testTryStarInvalidType]\nclass Bad: ...\ntry:\n    pass\nexcept* (RuntimeError, Bad) as e:  # E: Exception type must be derived from BaseException (or be a tuple of exception classes)\n    reveal_type(e)  # N: Revealed type is \"builtins.ExceptionGroup[Any]\"\n[builtins fixtures/exception.pyi]\n\n[case testTryStarGroupInvalid]\ntry:\n    pass\nexcept* ExceptionGroup as e:  # E: Exception type in except* cannot derive from BaseExceptionGroup\n    reveal_type(e)  # N: Revealed type is \"builtins.ExceptionGroup[Any]\"\n[builtins fixtures/exception.pyi]\n\n[case testTryStarGroupInvalidTuple]\ntry:\n    pass\nexcept* (RuntimeError, ExceptionGroup) as e:  # E: Exception type in except* cannot derive from BaseExceptionGroup\n    reveal_type(e)  # N: Revealed type is \"builtins.ExceptionGroup[builtins.RuntimeError | Any]\"\n[builtins fixtures/exception.pyi]\n\n[case testBasicTypeVarTupleGeneric]\nfrom typing import Generic, TypeVarTuple, Unpack\n\nTs = TypeVarTuple(\"Ts\")\n\nclass Variadic(Generic[Unpack[Ts]]):\n    ...\n\nvariadic: Variadic[int, str]\nreveal_type(variadic)  # N: Revealed type is \"__main__.Variadic[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testAsyncGeneratorWithinComprehension]\n# flags: --python-version 3.11\nfrom typing import Any, Generator, List\n\nasync def asynciter(iterable):\n    for x in iterable:\n        yield x\n\nasync def coro() -> Generator[List[Any], None, None]:\n    return ([i async for i in asynciter([0,j])] for j in [3, 5])\nreveal_type(coro)  # N: Revealed type is \"def () -> typing.Coroutine[Any, Any, typing.Generator[builtins.list[Any], None, None]]\"\n[builtins fixtures/async_await.pyi]\n[typing fixtures/typing-async.pyi]\n\n[case testTypeVarTupleNewSyntaxAnnotations]\nInts = tuple[int, int, int]\nx: tuple[str, *Ints]\nreveal_type(x)  # N: Revealed type is \"tuple[builtins.str, builtins.int, builtins.int, builtins.int]\"\ny: tuple[int, *tuple[int, ...]]\nreveal_type(y)  # N: Revealed type is \"tuple[builtins.int, Unpack[builtins.tuple[builtins.int, ...]]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleNewSyntaxGenerics]\nfrom typing import Generic, TypeVar, TypeVarTuple\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\nclass C(Generic[T, *Ts]):\n    attr: tuple[int, *Ts, str]\n\n    def test(self) -> None:\n        reveal_type(self.attr)  # N: Revealed type is \"tuple[builtins.int, Unpack[Ts`2], builtins.str]\"\n        self.attr = ci  # E: Incompatible types in assignment (expression has type \"C[*tuple[int, ...]]\", variable has type \"tuple[int, *Ts, str]\")\n    def meth(self, *args: *Ts) -> T: ...\n\nci: C[*tuple[int, ...]]\nreveal_type(ci)  # N: Revealed type is \"__main__.C[Unpack[builtins.tuple[builtins.int, ...]]]\"\nreveal_type(ci.meth)  # N: Revealed type is \"def (*args: builtins.int) -> builtins.int\"\nc3: C[str, str, str]\nreveal_type(c3)  # N: Revealed type is \"__main__.C[builtins.str, builtins.str, builtins.str]\"\n\nA = C[int, *Ts]\nB = tuple[str, *tuple[str, str], str]\nz: A[*B]\nreveal_type(z)  # N: Revealed type is \"__main__.C[builtins.int, builtins.str, builtins.str, builtins.str, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarTupleNewSyntaxCallables]\nfrom typing import Generic, overload, TypeVar\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nclass MyClass(Generic[T1, T2]):\n    @overload\n    def __init__(self: MyClass[None, None]) -> None: ...\n\n    @overload\n    def __init__(self: MyClass[T1, None], *types: *tuple[type[T1]]) -> None: ...\n\n    @overload\n    def __init__(self: MyClass[T1, T2], *types: *tuple[type[T1], type[T2]]) -> None: ...\n\n    def __init__(self: MyClass[T1, T2], *types: *tuple[type, ...]) -> None:\n        pass\n\nmyclass = MyClass()\nreveal_type(myclass)  # N: Revealed type is \"__main__.MyClass[None, None]\"\nmyclass1 = MyClass(float)\nreveal_type(myclass1)  # N: Revealed type is \"__main__.MyClass[builtins.float, None]\"\nmyclass2 = MyClass(float, float)\nreveal_type(myclass2)  # N: Revealed type is \"__main__.MyClass[builtins.float, builtins.float]\"\nmyclass3 = MyClass(float, float, float)  # E: No overload variant of \"MyClass\" matches argument types \"type[float]\", \"type[float]\", \"type[float]\" \\\n                                         # N: Possible overload variants: \\\n                                         # N:     def [T1, T2] MyClass() -> MyClass[None, None] \\\n                                         # N:     def [T1, T2] MyClass(type[T1], /) -> MyClass[T1, None] \\\n                                         # N:     def [T1, T2] MyClass(type[T1], type[T2], /) -> MyClass[T1, T2]\nreveal_type(myclass3)  # N: Revealed type is \"Any\"\n[builtins fixtures/tuple.pyi]\n\n[case testUnpackNewSyntaxInvalidCallableAlias]\nfrom typing import Any, Callable, List, Tuple, TypeVar, Unpack\n\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")  # E: Name \"TypeVarTuple\" is not defined\n\ndef good(*x: int) -> int: ...\ndef bad(*x: int, y: int) -> int: ...\n\nAlias1 = Callable[[*Ts], int]  # E: Variable \"__main__.Ts\" is not valid as a type \\\n                               # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\nx1: Alias1[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nreveal_type(x1)  # N: Revealed type is \"def (*Any) -> builtins.int\"\nx1 = good\nx1 = bad  # E: Incompatible types in assignment (expression has type \"def bad(*x: int, y: int) -> int\", variable has type \"def (*Any) -> int\")\n\nAlias2 = Callable[[*T], int]  # E: \"T\" cannot be unpacked (must be tuple or TypeVarTuple)\nx2: Alias2[int]\nreveal_type(x2)  # N: Revealed type is \"def (*Any) -> builtins.int\"\n\nUnknown = Any\nAlias3 = Callable[[*Unknown], int]\nx3: Alias3[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nreveal_type(x3)  # N: Revealed type is \"def (*Any) -> builtins.int\"\n\nIntList = List[int]\nAlias4 = Callable[[*IntList], int]  # E: \"list[int]\" cannot be unpacked (must be tuple or TypeVarTuple)\nx4: Alias4[int]  # E: Bad number of arguments for type alias, expected 0, given 1\nreveal_type(x4)  # N: Revealed type is \"def (*Any) -> builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testReturnInExceptStarBlock1]\n# flags: --python-version 3.11\ndef foo() -> None:\n    try:\n        pass\n    except* Exception:\n        return   # E: \"return\" not allowed in except* block\n    finally:\n        return\n[builtins fixtures/exception.pyi]\n\n[case testReturnInExceptStarBlock2]\n# flags: --python-version 3.11\ndef foo():\n    while True:\n        try:\n            pass\n        except* Exception:\n            while True:\n                return  # E: \"return\" not allowed in except* block\n[builtins fixtures/exception.pyi]\n\n[case testContinueInExceptBlockNestedInExceptStarBlock]\n# flags: --python-version 3.11\nwhile True:\n    try:\n        ...\n    except* Exception:\n        try:\n            ...\n        except Exception:\n            continue  # E: \"continue\" not allowed in except* block\n        continue  # E: \"continue\" not allowed in except* block\n[builtins fixtures/exception.pyi]\n\n[case testReturnInExceptBlockNestedInExceptStarBlock]\n# flags: --python-version 3.11\ndef foo():\n    try:\n        ...\n    except* Exception:\n        try:\n            ...\n        except Exception:\n            return  # E: \"return\" not allowed in except* block\n        return  # E: \"return\" not allowed in except* block\n[builtins fixtures/exception.pyi]\n\n[case testBreakContinueReturnInExceptStarBlock1]\n# flags: --python-version 3.11\nfrom typing import Iterable\ndef foo(x: Iterable[int]) -> None:\n    for _ in x:\n        try:\n            pass\n        except* Exception:\n            continue   # E: \"continue\" not allowed in except* block\n        except* Exception:\n            for _ in x:\n                continue\n            break  # E: \"break\" not allowed in except* block\n        except* Exception:\n            return  # E: \"return\" not allowed in except* block\n[builtins fixtures/exception.pyi]\n\n[case testBreakContinueReturnInExceptStarBlock2]\n# flags: --python-version 3.11\ndef foo():\n    while True:\n        try:\n            pass\n        except* Exception:\n            def inner():\n                while True:\n                    if 1 < 1:\n                        continue\n                    else:\n                        break\n                return\n            if 1 < 2:\n                break  # E: \"break\" not allowed in except* block\n            if 1 < 2:\n                continue  # E: \"continue\" not allowed in except* block\n            return  # E: \"return\" not allowed in except* block\n[builtins fixtures/exception.pyi]\n\n[case testLambdaInExceptStarBlock]\n# flags: --python-version 3.11\ndef foo():\n    try:\n        pass\n    except* Exception:\n        x = lambda: 0\n        return lambda: 0  # E: \"return\" not allowed in except* block\n\ndef loop():\n    while True:\n        try:\n            pass\n        except* Exception:\n            x = lambda: 0\n            return lambda: 0  # E: \"return\" not allowed in except* block\n[builtins fixtures/exception.pyi]\n\n[case testRedefineLocalWithinExceptStarTryClauses]\n# flags: --allow-redefinition\ndef fn_str(_: str) -> int: ...\ndef fn_int(_: int) -> None: ...\ndef fn_exc(_: Exception) -> str: ...\n\ndef in_block() -> None:\n    try:\n        a = \"\"\n        a = fn_str(a)  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        fn_int(a)  # E: Argument 1 to \"fn_int\" has incompatible type \"str\"; expected \"int\"\n    except* Exception:\n        b = \"\"\n        b = fn_str(b)\n        fn_int(b)\n    else:\n        c = \"\"\n        c = fn_str(c)\n        fn_int(c)\n    finally:\n        d = \"\"\n        d = fn_str(d)\n        fn_int(d)\n    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    reveal_type(b)  # N: Revealed type is \"builtins.int\"\n    reveal_type(c)  # N: Revealed type is \"builtins.int\"\n    reveal_type(d)  # N: Revealed type is \"builtins.int\"\n\ndef across_blocks() -> None:\n    try:\n        a = \"\"\n    except* Exception:\n        a = fn_str(a)  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    else:\n        a = fn_str(a)  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n\ndef exc_name() -> None:\n    try:\n        pass\n    except* RuntimeError as e:\n        e = fn_exc(e)\n[builtins fixtures/exception.pyi]\n\n[case testGenericTypeAliasArgOfTypeAliasIsUnpackedTuple]\nfrom typing_extensions import TypeAlias\nfrom typing import TypeVarTuple, Unpack\n\nTs = TypeVarTuple('Ts')\nTA: TypeAlias = tuple[Unpack[Ts]]\n\nv1: TA[*list[int]]  # E: \"list[int]\" cannot be unpacked (must be tuple or TypeVarTuple)\n\nv2: TA[Unpack[list[int]]]  # E: \"list[int]\" cannot be unpacked (must be tuple or TypeVarTuple)\n[builtins fixtures/tuple.pyi]\n"
  },
  {
    "path": "test-data/unit/check-python313.test",
    "content": "[case testPEP695TypeParameterDefaultSupported]\nclass C[T = None]: ...\ndef f[T = list[int]]() -> None: ...\ndef g[**P = [int, str]]() -> None: ...\ntype A[T, S = int, U = str] = list[T]\n\n[case testPEP695TypeParameterDefaultBasic]\nfrom typing import Callable\n\ndef f1[T1 = int](a: T1) -> list[T1]: ...\nreveal_type(f1)  # N: Revealed type is \"def [T1 = builtins.int] (a: T1`-1 = builtins.int) -> builtins.list[T1`-1 = builtins.int]\"\n\ndef f2[**P1 = [int, str]](a: Callable[P1, None]) -> Callable[P1, None]: ...\nreveal_type(f2)  # N: Revealed type is \"def [P1 = [builtins.int, builtins.str]] (a: def (*P1.args, **P1.kwargs)) -> def (*P1.args, **P1.kwargs)\"\n\ndef f3[*Ts1 = *tuple[int, str]](a: tuple[*Ts1]) -> tuple[*Ts1]: ...\nreveal_type(f3)  # N: Revealed type is \"def [Ts1 = Unpack[tuple[builtins.int, builtins.str]]] (a: tuple[Unpack[Ts1`-1 = Unpack[tuple[builtins.int, builtins.str]]]]) -> tuple[Unpack[Ts1`-1 = Unpack[tuple[builtins.int, builtins.str]]]]\"\n\n\nclass ClassA1[T1 = int]: ...\nclass ClassA2[**P1 = [int, str]]: ...\nclass ClassA3[*Ts1 = *tuple[int, str]]: ...\n\nreveal_type(ClassA1)  # N: Revealed type is \"def [T1 = builtins.int] () -> __main__.ClassA1[T1`1 = builtins.int]\"\nreveal_type(ClassA2)  # N: Revealed type is \"def [P1 = [builtins.int, builtins.str]] () -> __main__.ClassA2[P1`1 = [builtins.int, builtins.str]]\"\nreveal_type(ClassA3)  # N: Revealed type is \"def [Ts1 = Unpack[tuple[builtins.int, builtins.str]]] () -> __main__.ClassA3[Unpack[Ts1`1 = Unpack[tuple[builtins.int, builtins.str]]]]\"\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeParameterDefaultValid]\nfrom typing import Any\n\nclass ClassT1[T = int]: ...\nclass ClassT2[T: float = int]: ...\nclass ClassT3[T: list[Any] = list[int]]: ...\nclass ClassT4[T: (int, str) = int]: ...\n\nclass ClassP1[**P = []]: ...\nclass ClassP2[**P = ...]: ...\nclass ClassP3[**P = [int, str]]: ...\n\nclass ClassTs1[*Ts = *tuple[int]]: ...\nclass ClassTs2[*Ts = *tuple[int, ...]]: ...\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeParameterDefaultInvalid]\nclass ClassT1[T = 2]: ...  # E: TypeVar \"default\" must be a type\nclass ClassT2[T = [int]]: ...  # E: Bracketed expression \"[...]\" is not valid as a type \\\n                               # N: Did you mean \"List[...]\"? \\\n                               # E: TypeVar \"default\" must be a type\nclass ClassT3[T: str = int]: ...               # E: TypeVar default must be a subtype of the bound type\nclass ClassT4[T: list[str] = list[int]]: ...   # E: TypeVar default must be a subtype of the bound type\nclass ClassT5[T: (int, str) = bytes]: ...      # E: TypeVar default must be one of the constraint types\nclass ClassT6[T: (int, str) = int | str]: ...  # E: TypeVar default must be one of the constraint types\nclass ClassT7[T: (float, str) = int]: ...      # E: TypeVar default must be one of the constraint types\n\nclass ClassP1[**P = int]: ...       # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\nclass ClassP2[**P = 2]: ...         # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\nclass ClassP3[**P = (2, int)]: ...  # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\nclass ClassP4[**P = [2, int]]: ...  # E: Argument 0 of ParamSpec default must be a type\n\nclass ClassTs1[*Ts = 2]: ...           # E: The default argument to TypeVarTuple must be an Unpacked tuple\nclass ClassTs2[*Ts = int]: ...         # E: The default argument to TypeVarTuple must be an Unpacked tuple\nclass ClassTs3[*Ts = tuple[int]]: ...  # E: The default argument to TypeVarTuple must be an Unpacked tuple\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeParameterDefaultInvalid2]\nfrom typing import overload\ndef f1[T = 2]() -> None: ...  # E: TypeVar \"default\" must be a type\ndef f2[T = [int]]() -> None: ...  # E: Bracketed expression \"[...]\" is not valid as a type \\\n                                  # N: Did you mean \"List[...]\"? \\\n                                  # E: TypeVar \"default\" must be a type\ndef f3[T: str = int](x: T) -> T: ...               # E: TypeVar default must be a subtype of the bound type\ndef f4[T: list[str] = list[int]](x: T) -> T: ...   # E: TypeVar default must be a subtype of the bound type\ndef f5[T: (int, str) = bytes](x: T) -> T: ...      # E: TypeVar default must be one of the constraint types\ndef f6[T: (int, str) = int | str](x: T) -> T: ...  # E: TypeVar default must be one of the constraint types\ndef f7[T: (float, str) = int](x: T) -> T: ...      # E: TypeVar default must be one of the constraint types\ndef f8[T: str = int]() -> None: ...                # TODO check unused TypeVars\n@overload\ndef f9[T: str = int](x: T) -> T: ...               # E: TypeVar default must be a subtype of the bound type\n@overload\ndef f9[T: (int, str) = bytes](x: T) -> T: ...      # E: TypeVar default must be one of the constraint types\ndef f9() -> None: ...  # type: ignore[misc]\n\ndef g1[**P = int]() -> None: ...       # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\ndef g2[**P = 2]() -> None: ...         # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\ndef g3[**P = (2, int)]() -> None: ...  # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\ndef g4[**P = [2, int]]() -> None: ...  # E: Argument 0 of ParamSpec default must be a type\n\ndef h1[*Ts = 2]() -> None: ...           # E: The default argument to TypeVarTuple must be an Unpacked tuple\ndef h2[*Ts = int]() -> None: ...         # E: The default argument to TypeVarTuple must be an Unpacked tuple\ndef h3[*Ts = tuple[int]]() -> None: ...  # E: The default argument to TypeVarTuple must be an Unpacked tuple\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeParameterDefaultInvalid3]\nfrom typing import Callable\n\ntype TA1[T: str = 1] = list[T]  # E: TypeVar \"default\" must be a type\ntype TA2[T: str = [int]] = list[T]  # E: Bracketed expression \"[...]\" is not valid as a type \\\n                                    # N: Did you mean \"List[...]\"? \\\n                                    # E: TypeVar \"default\" must be a type\ntype TA3[T: str = int] = list[T]               # E: TypeVar default must be a subtype of the bound type\ntype TA4[T: list[str] = list[int]] = list[T]   # E: TypeVar default must be a subtype of the bound type\ntype TA5[T: (int, str) = bytes] = list[T]      # E: TypeVar default must be one of the constraint types\ntype TA6[T: (int, str) = int | str] = list[T]  # E: TypeVar default must be one of the constraint types\ntype TA7[T: (float, str) = int] = list[T]      # E: TypeVar default must be one of the constraint types\n\ntype TB1[**P = int] = Callable[P, None]       # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\ntype TB2[**P = 2] = Callable[P, None]         # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\ntype TB3[**P = (2, int)] = Callable[P, None]  # E: The default argument to ParamSpec must be a list expression, ellipsis, or a ParamSpec\ntype TB4[**P = [2, int]] = Callable[P, None]  # E: Argument 0 of ParamSpec default must be a type\n\ntype TC1[*Ts = 2] = tuple[*Ts]           # E: The default argument to TypeVarTuple must be an Unpacked tuple\ntype TC2[*Ts = int] = tuple[*Ts]         # E: The default argument to TypeVarTuple must be an Unpacked tuple\ntype TC3[*Ts = tuple[int]] = tuple[*Ts]  # E: The default argument to TypeVarTuple must be an Unpacked tuple\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695TypeParameterDefaultFunctions]\nfrom typing import Callable\n\ndef callback1(x: str) -> None: ...\n\ndef func_a1[T = str](x: int | T) -> T: ...\nreveal_type(func_a1(2))  # N: Revealed type is \"builtins.str\"\nreveal_type(func_a1(2.1))  # N: Revealed type is \"builtins.float\"\n\ndef func_a2[T = str](x: int | T) -> list[T]: ...\nreveal_type(func_a2(2))  # N: Revealed type is \"builtins.list[builtins.str]\"\nreveal_type(func_a2(2.1))  # N: Revealed type is \"builtins.list[builtins.float]\"\n\n\ndef func_a3[T: str = str](x: int | T) -> T: ...\nreveal_type(func_a3(2))  # N: Revealed type is \"builtins.str\"\n\ndef func_a4[T: (bytes, str) = str](x: int | T) -> T: ...\nreveal_type(func_a4(2))  # N: Revealed type is \"builtins.str\"\n\ndef func_b1[**P = [int, str]](x: int | Callable[P, None]) -> Callable[P, None]: ...\nreveal_type(func_b1(callback1))  # N: Revealed type is \"def (x: builtins.str)\"\nreveal_type(func_b1(2))  # N: Revealed type is \"def (builtins.int, builtins.str)\"\n\ndef func_c1[*Ts = *tuple[int, str]](x: int | Callable[[*Ts], None]) -> tuple[*Ts]: ...\n# reveal_type(func_c1(callback1))  # Revealed type is \"Tuple[str]\"  # TODO\nreveal_type(func_c1(2))  # N: Revealed type is \"tuple[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeParameterDefaultClass1]\n# flags: --disallow-any-generics\n\nclass ClassA1[T2 = int, T3 = str]: ...\n\ndef func_a1(\n    a: ClassA1,\n    b: ClassA1[float],\n    c: ClassA1[float, float],\n    d: ClassA1[float, float, float],  # E: \"ClassA1\" expects between 0 and 2 type arguments, but 3 given\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassA1[builtins.int, builtins.str]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassA1[builtins.float, builtins.str]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassA1[builtins.float, builtins.float]\"\n    reveal_type(d)  # N: Revealed type is \"__main__.ClassA1[builtins.int, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeParameterDefaultClass2]\n# flags: --disallow-any-generics\n\nclass ClassB1[**P2 = [int, str], **P3 = ...]: ...\n\ndef func_b1(\n    a: ClassB1,\n    b: ClassB1[[float]],\n    c: ClassB1[[float], [float]],\n    d: ClassB1[[float], [float], [float]],  # E: \"ClassB1\" expects between 0 and 2 type arguments, but 3 given\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassB1[[builtins.int, builtins.str], ...]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassB1[[builtins.float], ...]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassB1[[builtins.float], [builtins.float]]\"\n    reveal_type(d)  # N: Revealed type is \"__main__.ClassB1[[builtins.int, builtins.str], ...]\"\n\n    k = ClassB1()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassB1[[builtins.int, builtins.str], [*Any, **Any]]\"\n    l = ClassB1[[float]]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassB1[[builtins.float], [*Any, **Any]]\"\n    m = ClassB1[[float], [float]]()\n    reveal_type(m)  # N: Revealed type is \"__main__.ClassB1[[builtins.float], [builtins.float]]\"\n    n = ClassB1[[float], [float], [float]]()  # E: Type application has too many types (expected between 0 and 2)\n    reveal_type(n)  # N: Revealed type is \"Any\"\n\n[case testPEP695TypeParameterDefaultClass3]\n# flags: --disallow-any-generics\n\nclass ClassC1[*Ts = *tuple[int, str]]: ...\n\ndef func_c1(\n    a: ClassC1,\n    b: ClassC1[float],\n) -> None:\n    # reveal_type(a)  # Revealed type is \"__main__.ClassC1[builtins.int, builtins.str]\"  # TODO\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassC1[builtins.float]\"\n\n    k = ClassC1()\n    reveal_type(k)  # N: Revealed type is \"__main__.ClassC1[builtins.int, builtins.str]\"\n    l = ClassC1[float]()\n    reveal_type(l)  # N: Revealed type is \"__main__.ClassC1[builtins.float]\"\n[builtins fixtures/tuple.pyi]\n\n[case testPEP695TypeParameterDefaultTypeAlias1]\n# flags: --disallow-any-generics\n\ntype TA1[T2 = int, T3 = str] = dict[T2, T3]\n\ndef func_a1(\n    a: TA1,\n    b: TA1[float],\n    c: TA1[float, float],\n    d: TA1[float, float, float],  # E: Bad number of arguments for type alias, expected between 0 and 2, given 3\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n    reveal_type(b)  # N: Revealed type is \"builtins.dict[builtins.float, builtins.str]\"\n    reveal_type(c)  # N: Revealed type is \"builtins.dict[builtins.float, builtins.float]\"\n    reveal_type(d)  # N: Revealed type is \"builtins.dict[builtins.int, builtins.str]\"\n[builtins fixtures/dict.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695TypeParameterDefaultTypeAlias2]\n# flags: --disallow-any-generics\n\nclass ClassB1[**P2, **P3]: ...\ntype TB1[**P2 = [int, str], **P3 = ...] = ClassB1[P2, P3]\n\ndef func_b1(\n    a: TB1,\n    b: TB1[[float]],\n    c: TB1[[float], [float]],\n    d: TB1[[float], [float], [float]],  # E: Bad number of arguments for type alias, expected between 0 and 2, given 3\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.ClassB1[[builtins.int, builtins.str], [*Any, **Any]]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.ClassB1[[builtins.float], [*Any, **Any]]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.ClassB1[[builtins.float], [builtins.float]]\"\n    reveal_type(d)  # N: Revealed type is \"__main__.ClassB1[[builtins.int, builtins.str], [*Any, **Any]]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695TypeParameterDefaultTypeAlias3]\n# flags: --disallow-any-generics\n\ntype TC1[*Ts = *tuple[int, str]] = tuple[*Ts]\n\ndef func_c1(\n    a: TC1,\n    b: TC1[float],\n) -> None:\n    # reveal_type(a)  # Revealed type is \"Tuple[builtins.int, builtins.str]\"  # TODO\n    reveal_type(b)  # N: Revealed type is \"tuple[builtins.float]\"\n\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testPEP695TypeParameterDefaultTypeAlias4]\n# flags: --disallow-any-generics\nclass A[L = int, M = str]: ...\nTD1 = A[float]\ntype TD2 = A[float]\n\ndef func_d1(\n    a: TD1,\n    b: TD1[float],  # E: Bad number of arguments for type alias, expected 0, given 1\n    c: TD2,\n    d: TD2[float],  # E: Bad number of arguments for type alias, expected 0, given 1\n) -> None:\n    reveal_type(a)  # N: Revealed type is \"__main__.A[builtins.float, builtins.str]\"\n    reveal_type(b)  # N: Revealed type is \"__main__.A[builtins.float, builtins.str]\"\n    reveal_type(c)  # N: Revealed type is \"__main__.A[builtins.float, builtins.str]\"\n    reveal_type(d)  # N: Revealed type is \"__main__.A[builtins.float, builtins.str]\"\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testTypeVarConstraintsDefaultAliasesInline]\ntype K = int\ntype V = int\n\nclass A1[T: (str, int) = K]:\n    x: T\nclass A2[T: (str, K) = K]:\n    x: T\nclass A3[T: (str, K) = V]:\n    x: T\n\nreveal_type(A1().x)  # N: Revealed type is \"builtins.int\"\nreveal_type(A2().x)  # N: Revealed type is \"builtins.int\"\nreveal_type(A3().x)  # N: Revealed type is \"builtins.int\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarDefaultToAnotherTypeVar]\nclass A[X, Y = X, Z = Y]:\n    x: X\n    y: Y\n    z: Z\n\na1: A[int]\nreveal_type(a1.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(a1.y)  # N: Revealed type is \"builtins.int\"\n# TODO: this must reveal `int` as well:\nreveal_type(a1.z)  # N: Revealed type is \"X`1\"\n\na2: A[int, str]\nreveal_type(a2.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(a2.y)  # N: Revealed type is \"builtins.str\"\nreveal_type(a2.z)  # N: Revealed type is \"builtins.str\"\n\na3: A[int, str, bool]\nreveal_type(a3.x)  # N: Revealed type is \"builtins.int\"\nreveal_type(a3.y)  # N: Revealed type is \"builtins.str\"\nreveal_type(a3.z)  # N: Revealed type is \"builtins.bool\"\n[builtins fixtures/tuple.pyi]\n\n[case testTypeVarDefaultToAnotherTypeVarWrong]\nclass A[Y = X, X = int]: ...  # E: Name \"X\" is not defined\n\nclass B[Y = X]: ...  # E: Name \"X\" is not defined\n[builtins fixtures/tuple.pyi]\n\n\n[case testTernaryOperatorWithTypeVarDefault]\n# https://github.com/python/mypy/issues/18817\n\nclass Ok[T, E = None]:\n    def __init__(self, value: T) -> None:\n        self._value = value\n\nclass Err[E, T = None]:\n    def __init__(self, value: E) -> None:\n        self._value = value\n\ntype Result[T, E] = Ok[T, E] | Err[E, T]\n\nclass Bar[U]:\n    def foo(data: U, cond: bool) -> Result[U, str]:\n        return Ok(data) if cond else Err(\"Error\")\n"
  },
  {
    "path": "test-data/unit/check-redefine.test",
    "content": "-- Test cases for the redefinition of variable with a different type.\n\n\n-- Redefine local variable\n-- -----------------------\n\n\n[case testRedefineLocalWithDifferentType]\n# flags: --allow-redefinition\ndef f() -> None:\n    x = 0\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x = ''\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n\n[case testCannotConditionallyRedefineLocalWithDifferentType]\n# flags: --allow-redefinition\ndef f() -> None:\n    y = 0\n    reveal_type(y) # N: Revealed type is \"builtins.int\"\n    if int():\n        y = ''  \\\n        # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        reveal_type(y)  # N: Revealed type is \"builtins.int\"\n    reveal_type(y) # N: Revealed type is \"builtins.int\"\n\n[case testRedefineFunctionArg]\n# flags: --allow-redefinition\ndef f(x: int) -> None:\n    g(x)\n    x = ''\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\ndef g(x: int) -> None:\n    if int():\n        x = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        reveal_type(x) # N: Revealed type is \"builtins.int\"\n\n[case testRedefineAnnotationOnly]\n# flags: --allow-redefinition\ndef f() -> None:\n    x: int\n    x = '' \\\n        # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\ndef g() -> None:\n    x: int\n    x = 1\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x = ''\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n\n[case testRedefineLocalUsingOldValue]\n# flags: --allow-redefinition\nfrom typing import TypeVar, Union\n\nT = TypeVar('T')\n\ndef f(x: int) -> None:\n    x = g(x)\n    reveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n    y = 1\n    y = g(y)\n    reveal_type(y)  # N: Revealed type is \"builtins.int | builtins.str\"\n\ndef g(x: T) -> Union[T, str]: pass\n\n[case testRedefineLocalForLoopIndexVariable]\n# flags: --allow-redefinition\nfrom typing import Iterable\ndef f(a: Iterable[int], b: Iterable[str]) -> None:\n    for x in a:\n        x = '' \\\n        # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    for x in b:\n        x = 1 \\\n        # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n\ndef g(a: Iterable[int]) -> None:\n    for x in a: pass\n    x = ''\n\ndef h(a: Iterable[int]) -> None:\n    x = ''\n    reveal_type(x)  # N: Revealed type is \"builtins.str\"\n    for x in a: pass\n\n[case testCannotRedefineLocalWithinTry]\n# flags: --allow-redefinition\ndef g(): pass\ndef f() -> None:\n    try:\n        x = 0\n        x\n        g()  # Might raise an exception\n        x = '' \\\n        # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    except:\n        pass\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    y = 0\n    y\n    y = ''\n\n[case testRedefineLocalWithinTryClauses]\n# flags: --allow-redefinition\ndef fn_str(_: str) -> int: ...\ndef fn_int(_: int) -> None: ...\n\ndef in_block() -> None:\n    try:\n        a = \"\"\n        a = fn_str(a)  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        fn_int(a)  # E: Argument 1 to \"fn_int\" has incompatible type \"str\"; expected \"int\"\n    except:\n        b = \"\"\n        b = fn_str(b)\n        fn_int(b)\n    else:\n        c = \"\"\n        c = fn_str(c)\n        fn_int(c)\n    finally:\n        d = \"\"\n        d = fn_str(d)\n        fn_int(d)\n    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n    reveal_type(b)  # N: Revealed type is \"builtins.int\"\n    reveal_type(c)  # N: Revealed type is \"builtins.int\"\n    reveal_type(d)  # N: Revealed type is \"builtins.int\"\n\ndef across_blocks() -> None:\n    try:\n        a = \"\"\n    except:\n        pass\n    else:\n        a = fn_str(a)  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n    reveal_type(a)  # N: Revealed type is \"builtins.str\"\n\n[case testRedefineLocalExceptVar]\n# flags: --allow-redefinition\ndef fn_exc(_: Exception) -> str: ...\n\ndef exc_name() -> None:\n    try:\n        pass\n    except RuntimeError as e:\n        e = fn_exc(e)\n[builtins fixtures/exception.pyi]\n\n[case testRedefineNestedInTry]\n# flags: --allow-redefinition\n\ndef fn_int(_: int) -> None: ...\n\ntry:\n    try:\n        ...\n    finally:\n        a = \"\"\n        a = 5  # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n        fn_int(a)  # E: Argument 1 to \"fn_int\" has incompatible type \"str\"; expected \"int\"\nexcept:\n    pass\n\n[case testRedefineLocalWithinWith]\n# flags: --allow-redefinition\ndef f() -> None:\n    with g():\n        x = 0\n        x\n        g()  # Might raise an exception, but we ignore this\n        x = ''\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n    y = 0\n    y\n    y = ''\n\ndef g(): pass\n\n[case testCannotRedefineAcrossNestedFunction]\n# flags: --allow-redefinition\ndef f() -> None:\n    x = 0\n    x\n    def g() -> None:\n        x\n    g()\n    x = '' \\\n    # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    g()\n    y = 0\n    y\n    y = ''\n\n[case testCannotRedefineAcrossNestedDecoratedFunction]\n# flags: --allow-redefinition\ndef dec(f): return f\n\ndef f() -> None:\n    x = 0\n    x\n    @dec\n    def g() -> None:\n        x\n    g()\n    x = '' \\\n    # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    g()\n    y = 0\n    y\n    y = ''\n\n[case testCannotRedefineAcrossNestedOverloadedFunction]\n# flags: --allow-redefinition\nfrom typing import overload\n\ndef f() -> None:\n    x = 0\n    x\n    @overload\n    def g() -> None: pass\n    @overload\n    def g(x: int) -> None: pass\n    def g(x=0):\n        pass\n    g()\n    x = '' \\\n    # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    g()\n    y = 0\n    y\n    y = ''\n\n[case testRedefineLocalInMultipleAssignment]\n# flags: --allow-redefinition\ndef f() -> None:\n    x, x = 1, ''\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n    x = object()\n    reveal_type(x) # N: Revealed type is \"builtins.object\"\n\ndef g() -> None:\n    x = 1\n    if 1:\n        x, x = '', 1 \\\n        # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testRedefineUnderscore]\n# flags: --allow-redefinition\ndef f() -> None:\n    _, _ = 1, ''\n    if 1:\n        _, _ = '', 1\n        # This is unintentional but probably fine. No one is going to read _ value.\n        reveal_type(_) # N: Revealed type is \"builtins.int\"\n\n[case testRedefineWithBreakAndContinue]\n# flags: --allow-redefinition\ndef f() -> None:\n    y = 0\n    y\n    while int():\n        z = 0\n        z\n        z = ''\n        x = 0\n        if int():\n            break\n        x = '' \\\n        # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    y = ''\n\ndef g() -> None:\n    y = 0\n    y\n    for a in h():\n        z = 0\n        z\n        z = ''\n        x = 0\n        if int():\n            continue\n        x = '' \\\n        # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    y = ''\n\ndef h(): pass\n\n[case testRedefineLocalAndNestedLoops]\n# flags: --allow-redefinition\ndef f() -> None:\n    z = 0\n    z\n    while int():\n        x = 0\n        x\n        while int():\n            if 1:\n                y = 1\n                y\n                if int():\n                    break\n                y = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n        x = ''\n    z = ''\n\n[case testCannotRedefineVarAsFunction]\n# flags: --allow-redefinition\ndef f() -> None:\n    def x(): pass\n    x = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"Callable[[], Any]\")\n    reveal_type(x) # N: Revealed type is \"def () -> Any\"\n    y = 1\n    def y(): pass # E: Name \"y\" already defined on line 6\n\n[case testCannotRedefineVarAsClass]\n# flags: --allow-redefinition\ndef f() -> None:\n    class x: pass\n    x = 1 # E: Cannot assign to a type \\\n          # E: Incompatible types in assignment (expression has type \"int\", variable has type \"type[x]\")\n    y = 1\n    class y: pass # E: Name \"y\" already defined on line 5\n\n[case testRedefineVarAsTypeVar]\n# flags: --allow-redefinition\nfrom typing import TypeVar\ndef f() -> None:\n    x = TypeVar('x')\n    x = 1  # E: Invalid assignment target \\\n           # E: Incompatible types in assignment (expression has type \"int\", variable has type \"TypeVar\")\n    reveal_type(x) # N: Revealed type is \"typing.TypeVar\"\n    y = 1\n    y = TypeVar('y')  # E: Cannot redefine \"y\" as a type variable \\\n                      # E: Incompatible types in assignment (expression has type \"TypeVar\", variable has type \"int\")\n    def h(a: y) -> y: return a # E: Variable \"y\" is not valid as a type \\\n                               # N: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases\n[builtins fixtures/tuple.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testCannotRedefineVarAsModule]\n# flags: --allow-redefinition\ndef f() -> None:\n    import typing as m\n    m = 1 # E: Incompatible types in assignment (expression has type \"int\", variable has type Module)\n    n = 1\n    import typing as n  # E: Incompatible import of \"n\" (imported name has type Module, local name has type \"int\")\n[builtins fixtures/module.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testRedefineLocalWithTypeAnnotation]\n# flags: --allow-redefinition\ndef f() -> None:\n    x = 1\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x = ''  # type: object\n    reveal_type(x) # N: Revealed type is \"builtins.object\"\ndef g() -> None:\n    x = 1\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x: object = ''\n    reveal_type(x) # N: Revealed type is \"builtins.object\"\ndef h() -> None:\n    x: int\n    x = 1\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\n    x: object\n    x: object = '' # E: Name \"x\" already defined on line 16\ndef farg(x: int) -> None:\n    x: str = '' # E: Name \"x\" already defined on line 18\ndef farg2(x: int) -> None:\n    x: str = x # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n[case testRedefineLocalWithTypeAnnotationSpecialCases]\n# flags: --allow-redefinition\ndef f() -> None:\n    x: object\n    x = 1\n    if int():\n        x = ''\n    reveal_type(x) # N: Revealed type is \"builtins.str | builtins.int\"\n    x = ''\n    reveal_type(x) # N: Revealed type is \"builtins.str\"\n    if int():\n        x = 2 \\\n        # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n\n[case testCannotRedefineSelf]\n# flags: --allow-redefinition\nclass A:\n    x = 0\n\n    def f(self) -> None:\n        reveal_type(self.x) # N: Revealed type is \"builtins.int\"\n        self = f()\n        self.y: str = ''\n        reveal_type(self.y) # N: Revealed type is \"builtins.str\"\n\ndef f() -> A: return A()\n\n\n-- Redefine global variable\n-- ------------------------\n\n\n[case testRedefineGlobalWithDifferentType]\n# flags: --allow-redefinition\nimport m\nreveal_type(m.x)\n[file m.py]\nx = 0\nreveal_type(x)\nx = object()\nreveal_type(x)\nx = ''\nreveal_type(x)\n[out]\ntmp/m.py:2: note: Revealed type is \"builtins.int\"\ntmp/m.py:4: note: Revealed type is \"builtins.object\"\ntmp/m.py:6: note: Revealed type is \"builtins.str\"\nmain:3: note: Revealed type is \"builtins.str\"\n\n[case testRedefineGlobalForIndex]\n# flags: --allow-redefinition\nimport m\nreveal_type(m.x)\n[file m.py]\nfrom typing import Iterable\ndef f(): pass\nit1: Iterable[int] = f()\nit2: Iterable[str] = f()\nfor x in it1:\n    reveal_type(x)\nfor x in it2:\n    reveal_type(x)\nreveal_type(x)\n[out]\ntmp/m.py:6: note: Revealed type is \"builtins.int\"\ntmp/m.py:8: note: Revealed type is \"builtins.str\"\ntmp/m.py:9: note: Revealed type is \"builtins.str\"\nmain:3: note: Revealed type is \"builtins.str\"\n\n[case testRedefineGlobalBasedOnPreviousValues]\n# flags: --allow-redefinition\nfrom typing import TypeVar, Iterable\nT = TypeVar('T')\ndef f(x: T) -> Iterable[T]: pass\na = 0\na = f(a)\nreveal_type(a) # N: Revealed type is \"typing.Iterable[builtins.int]\"\n\n[case testRedefineGlobalWithSeparateDeclaration]\n# flags: --allow-redefinition\nx = ''\nreveal_type(x) # N: Revealed type is \"builtins.str\"\nx: int\nx = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nreveal_type(x) # N: Revealed type is \"builtins.int\"\nx: object\nx = 1\nreveal_type(x) # N: Revealed type is \"builtins.int\"\nif int():\n    x = object()\n\n[case testRedefineGlobalUsingForLoop]\n# flags: --allow-redefinition\nfrom typing import Iterable, TypeVar, Union\nT = TypeVar('T')\ndef f(x: T) -> Iterable[Union[T, str]]: pass\nx = 0\nreveal_type(x)  # N: Revealed type is \"builtins.int\"\nfor x in f(x):\n    pass\nreveal_type(x)  # N: Revealed type is \"builtins.int | builtins.str\"\n\n[case testNoRedefinitionIfOnlyInitialized]\n# flags: --allow-redefinition --no-strict-optional\nx = None  # type: int\nx = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nx = object() # E: Incompatible types in assignment (expression has type \"object\", variable has type \"int\")\nx  # Reference to variable\nx = ''\n\ny = 0\ny = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\n\n[case testNoRedefinitionIfNoValueAssigned]\n# flags: --allow-redefinition\nx: int\nx = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nreveal_type(x) # N: Revealed type is \"builtins.int\"\nx: object\n\n[case testNoRedefinitionIfExplicitlyDisallowed]\n# flags: --disallow-redefinition\nx = 0\nx = 2\nx = ''  # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ndef f() -> None:\n    y = 0\n    y = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\nclass C:\n    y = 0\n    y = '' # E: Incompatible types in assignment (expression has type \"str\", variable has type \"int\")\ndef g() -> None:\n    # _ is a special case\n    _ = 0\n    _ = ''\n    x, _ = 0, C()\n[builtins fixtures/tuple.pyi]\n\n[case testRedefineAsException]\n# flags: --allow-redefinition\ne = 1\nreveal_type(e) # N: Revealed type is \"builtins.int\"\ntry:\n    pass\nexcept Exception as e:\n    reveal_type(e) # N: Revealed type is \"builtins.Exception\"\ne = ''\nreveal_type(e) # N: Revealed type is \"builtins.str\"\n[builtins fixtures/exception.pyi]\n\n[case testRedefineUsingWithStatement]\n# flags: --allow-redefinition\nclass A:\n    def __enter__(self) -> int: ...\n    def __exit__(self, x, y, z) -> None: ...\nclass B:\n    def __enter__(self) -> str: ...\n    def __exit__(self, x, y, z) -> None: ...\nwith A() as x:\n    reveal_type(x) # N: Revealed type is \"builtins.int\"\nwith B() as x:\n    x = 0 # E: Incompatible types in assignment (expression has type \"int\", variable has type \"str\")\n\n\n[case testRedefineModuleAsException]\nimport typing\ntry:\n    pass\nexcept Exception as typing:\n    pass\n[builtins fixtures/exception.pyi]\n[typing fixtures/typing-full.pyi]\n\n[case testRedefiningUnderscoreFunctionIsntAnError]\ndef _(arg):\n    pass\n\ndef _(arg):\n    pass\n\n[case testTypeErrorsInUnderscoreFunctionsReported]\ndef _(arg: str):\n    x = arg + 1 # E: Unsupported left operand type for + (\"str\")\n\ndef _(arg: int) -> int:\n    return 'a' # E: Incompatible return value type (got \"str\", expected \"int\")\n\n[case testFunctionStillTypeCheckedWhenAliasedAsUnderscoreDuringImport]\nfrom a import f as _\n\n_(1) # E: Argument 1 to \"f\" has incompatible type \"int\"; expected \"str\"\nreveal_type(_('a')) # N: Revealed type is \"builtins.str\"\n\n[file a.py]\ndef f(arg: str) -> str:\n    return arg\n\n[case testCallToFunctionStillTypeCheckedWhenAssignedToUnderscoreVariable]\nfrom a import g\n_ = g\n\n_('a') # E: Argument 1 has incompatible type \"str\"; expected \"int\"\nreveal_type(_(1)) # N: Revealed type is \"builtins.int\"\n\n[file a.py]\ndef g(arg: int) -> int:\n    return arg\n\n[case testRedefiningUnderscoreFunctionWithDecoratorWithUnderscoreFunctionsNextToEachOther]\ndef dec(f):\n    return f\n\n@dec\ndef _(arg):\n    pass\n\n@dec\ndef _(arg):\n    pass\n\n[case testRedefiningUnderscoreFunctionWithDecoratorInDifferentPlaces]\ndef dec(f):\n    return f\n\ndef dec2(f):\n    return f\n\n@dec\ndef _(arg):\n    pass\n\ndef f(arg):\n    pass\n\n@dec2\ndef _(arg):\n    pass\n\n[case testOverwritingImportedFunctionThatWasAliasedAsUnderscore]\nfrom a import f as _\n\ndef _(arg: str) -> str: # E: Name \"_\" already defined (possibly by an import)\n    return arg\n\n[file a.py]\ndef f(s: str) -> str:\n    return s\n"
  },
  {
    "path": "test-data/unit/lib-stub/string/__init__.pyi",
    "content": ""
  }
]